diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000000..96dc1b77a55d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +end_of_line = lf +indent_size = 2 + +[*.md] +max_line_length = 79 +trim_trailing_whitespace = false + +[*.{py,pyi,toml,json}] +max_line_length = 130 +indent_size = 4 diff --git a/.flake8 b/.flake8 index 4d5b841beba6..e45a7f11787b 100644 --- a/.flake8 +++ b/.flake8 @@ -1,26 +1,16 @@ -# Some PEP8 deviations are considered irrelevant to stub files: -# E301 expected 1 blank line -# E302 expected 2 blank lines -# E305 expected 2 blank lines -# E701 multiple statements on one line (colon) -# E741 ambiguous variable name -# F401 imported but unused -# F403 import *' used; unable to detect undefined names -# F405 defined from star imports -# F822 undefined name in __all__ - -# Nice-to-haves ignored for now -# E501 line too long - [flake8] +# Y: Flake8 is only used to run flake8-pyi, everything else is in Ruff +select = Y +# Ignore rules normally excluded by default +# Also ignore Y041 (redundant (complex |) float | int), see +# https://github.com/python/typeshed/issues/16059 +extend-ignore = Y041,Y090,Y091 per-file-ignores = - *.py: E203, W503 - *.pyi: E301, E302, E305, E501, E701, E741, F401, F403, F405, F822 - # Since typing.pyi defines "overload" this is not recognized by flake8 as typing.overload. - # Unfortunately, flake8 does not allow to "noqa" just a specific error inside the file itself. - typing.pyi: E301, E302, E305, E501, E701, E741, F401, F403, F405, F811, F822 + # Generated protobuf files: + # Y021: Include docstrings + # Y023: Alias typing as typing_extensions + # Y026: Have implicit type aliases + # Y053: have literals >50 characters long + stubs/*_pb2.pyi: Y021, Y023, Y026, Y053 -# We are checking with Python 3 but many of the stubs are Python 2 stubs. -builtins = StandardError,apply,basestring,buffer,cmp,coerce,execfile,file,intern,long,raw_input,reduce,reload,unichr,unicode,xrange -exclude = .venv*,.git,*_pb2.pyi -max-line-length = 130 +exclude = .venv*,.git diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000000..19c9bb2b07f7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Normalize EOF +* autocrlf=false +* eol=lf +# Set linguist-language to support comments syntax highlight +**/stubtest_allowlist*.txt linguist-language=ini +**/stubtest_allowlists/*.txt linguist-language=ini +pyrightconfig*.json linguist-language=jsonc +.vscode/*.json linguist-language=jsonc diff --git a/.github/renovate.json5 b/.github/renovate.json5 new file mode 100644 index 000000000000..1cded73b61c7 --- /dev/null +++ b/.github/renovate.json5 @@ -0,0 +1,79 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "dependencyDashboard": true, + "suppressNotifications": ["prEditedNotification"], + "extends": [ + "config:recommended", + "helpers:pinGitHubActionDigestsToSemver", + "replacements:all", + "abandonments:recommended" + ], + "configMigration": true, + "labels": ["bot: dependencies"], + "rebaseLabel": "bot: rebase", + "semanticCommits": "disabled", + "separateMajorMinor": false, + "prHourlyLimit": 10, + // This package rule disables updates for `actions/setup-python` Python versions: + // it's better to do these manually as there's often a reason why we can't use + // the latest Python version in CI for a specific job + ignoreDeps: ["python"], + "pre-commit": { + "enabled": true + }, + "minimumReleaseAge": "7 days", + "packageRules": [ + { + // Pin versions already in use without waiting for the upgrade cooldown. + "matchUpdateTypes": ["pinDigest"], + "minimumReleaseAge": null + }, + { + groupName: "GitHub Actions", + matchManagers: ["github-actions"], + description: "Quarterly update of GitHub Action dependencies", + schedule: ["every 3 months on the first day of the month"] + }, + { + groupName: "most test/lint dependencies", + matchManagers: ["pip_requirements", "pre-commit"], + description: "Quarterly update of most test dependencies", + schedule: ["every 3 months on the first day of the month"] + }, + { + groupName: "ruff", + matchManagers: ["pip_requirements", "pre-commit"], + matchPackageNames: ["ruff", "astral-sh/ruff-pre-commit"], + description: "Quarterly update of Ruff", + schedule: ["every 3 months on the first day of the month"] + }, + { + groupName: "ty", + matchManagers: ["pip_requirements"], + matchPackageNames: ["ty"], + description: "Daily update of ty", + schedule: ["before 4am"] + }, + { + groupName: "pyrefly", + matchManagers: ["pip_requirements"], + matchPackageNames: ["pyrefly"], + description: "Daily update of pyrefly", + schedule: ["before 4am"] + }, + { + groupName: "mypy", + matchManagers: ["pip_requirements"], + matchPackageNames: ["mypy"], + description: "Daily update of mypy", + schedule: ["before 4am"] + }, + { + "groupName": "pyright", + "matchManagers": ["pip_requirements"], + "matchPackageNames": ["pyright"], + "description": "Daily update of pyright", + "schedule": ["before 4am"] + } + ] +} diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml new file mode 100644 index 000000000000..712bc610cce5 --- /dev/null +++ b/.github/workflows/actionlint.yml @@ -0,0 +1,36 @@ +name: Lint GitHub Actions workflows + +on: + workflow_dispatch: + push: + branches: + - main + paths: + - ".github/workflows/**" + pull_request: + paths: + - ".github/workflows/**" + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + actionlint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Run actionlint + # This is the recommended way to run actionlint in CI: + # https://github.com/rhysd/actionlint/blob/main/docs/usage.md#use-actionlint-on-github-actions. + # The actionlint pre-commit hook would be an alternative, + # but it causes our pre-commit CI jobs to time out. + # The Docker image includes ShellCheck and Pyflakes. + uses: docker://rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 + with: + args: -color -verbose diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml new file mode 100644 index 000000000000..70e6e2e6a24a --- /dev/null +++ b/.github/workflows/daily.yml @@ -0,0 +1,165 @@ +name: Daily tests + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "requirements-tests.txt" + - ".github/workflows/daily.yml" + +# Please keep the permissions minimal, as stubtest runs arbitrary code from pypi. +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +env: + # A few env vars to speedup brew install + HOMEBREW_NO_ANALYTICS: 1 + HOMEBREW_NO_AUTOUPDATE: 1 + HOMEBREW_NO_INSTALL_CLEANUP: 1 # Environments are isolated, no need to cleanup old versions + NONINTERACTIVE: 1 # Required for brew install on CI + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817 + +jobs: + stubtest-stdlib: + name: "stubtest: stdlib" + if: ${{ github.repository == 'python/typeshed' || github.event_name != 'schedule' }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + exclude: + # https://github.com/python/typeshed/issues/15694 + - os: "windows-latest" + python-version: "3.10" + fail-fast: false + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: requirements-tests.txt + allow-prereleases: true + check-latest: true + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Run stubtest + run: python tests/stubtest_stdlib.py + + stubtest-third-party: + name: "stubtest: third party" + if: ${{ github.repository == 'python/typeshed' || github.event_name != 'schedule' }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + shard-index: [0, 1, 2, 3] + fail-fast: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.13" + cache: pip + cache-dependency-path: | + requirements-tests.txt + stubs/**/METADATA.toml + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Install required system packages + shell: bash + run: | + PACKAGES=$(python tests/get_stubtest_system_requirements.py) + + # System package names contain no whitespace or glob characters, so word splitting is intentional. + # shellcheck disable=SC2086 + if [ "${{ runner.os }}" = "Linux" ]; then + if [ -n "$PACKAGES" ]; then + printf 'Installing APT packages:\n' + printf ' %s\n' $PACKAGES + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + else + if [ "${{ runner.os }}" = "macOS" ] && [ -n "$PACKAGES" ]; then + printf 'Installing Homebrew packages:\n' + printf ' %s\n' $PACKAGES + brew install -q $PACKAGES + fi + + if [ "${{ runner.os }}" = "Windows" ] && [ -n "$PACKAGES" ]; then + printf 'Installing Chocolatey packages:\n' + printf ' %s\n' $PACKAGES + choco install -y $PACKAGES + fi + fi + - name: Run stubtest + shell: bash + run: | + if [ "${{ runner.os }}" = "Linux" ]; then + PYTHON_EXECUTABLE="xvfb-run python" + else + PYTHON_EXECUTABLE="python" + fi + + $PYTHON_EXECUTABLE tests/stubtest_third_party.py --ci-platforms-only --num-shards 4 --shard-index ${{ matrix.shard-index }} + + stub-uploader: + name: stub_uploader tests + if: ${{ github.repository == 'python/typeshed' || github.event_name != 'schedule' }} + runs-on: ubuntu-latest + steps: + - name: Checkout typeshed + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: typeshed + persist-credentials: false + - name: Checkout stub_uploader + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: typeshed-internal/stub_uploader + path: stub_uploader + persist-credentials: false + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "typeshed/requirements-tests.txt" + - name: Run tests + run: | + cd stub_uploader + # Keep Python version in sync with stub_uploader's check_scripts.yml workflow. + uv run --python=3.13 --locked --group dev -m pytest tests + + # https://github.community/t/run-github-actions-job-only-if-previous-job-has-failed/174786/2 + create-issue-on-failure: + name: Create issue on failure + runs-on: ubuntu-latest + needs: [stubtest-stdlib, stubtest-third-party, stub-uploader] + if: ${{ github.repository == 'python/typeshed' && always() && github.event_name == 'schedule' && (needs.stubtest-stdlib.result == 'failure' || needs.stubtest-third-party.result == 'failure' || needs.stub-uploader.result == 'failure') }} + permissions: + issues: write + steps: + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.create({ + owner: "python", + repo: "typeshed", + title: `Daily tests failed on ${new Date().toDateString()}`, + body: "Run listed here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}", + labels: ["help wanted"], + }) diff --git a/.github/workflows/meta_tests.yml b/.github/workflows/meta_tests.yml new file mode 100644 index 000000000000..ef509e62aa25 --- /dev/null +++ b/.github/workflows/meta_tests.yml @@ -0,0 +1,100 @@ +# This workflow is for testing typeshed's scripts and tests themselves +name: Infrastructure tests + +on: + workflow_dispatch: + push: + branches: + - main + pull_request: + paths: + - "scripts/**" + - "tests/**" + - "lib/**" + - ".github/workflows/meta_tests.yml" + - "requirements-tests.txt" + - "pyproject.toml" + +permissions: + contents: read + +env: + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + mypy: + name: "mypy: type check" + runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32"] + fail-fast: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Run check_typeshed_structure.py + run: | + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + ./tests/typecheck_typeshed.py \ + --platform=${{ matrix.platform }} + + pyright: + name: "pyright: type check" + runs-on: ubuntu-latest + strategy: + matrix: + python-platform: ["Linux", "Windows"] + fail-fast: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.13" + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - run: uv pip install -r requirements-tests.txt --system + - name: Run pyright on typeshed + uses: jakebailey/pyright-action@8ec14b5cfe41f26e5f41686a31eb6012758217ef # v3.0.2 + with: + version: PATH + python-platform: ${{ matrix.python-platform }} + python-version: "3.10" # Oldest version supported for running scripts and tests + project: ./pyrightconfig.scripts_and_tests.json + + stubsabot-dry-run: + name: "stubsabot: dry run" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Git config + run: | + git config --global user.name stubsabot + git config --global user.email '<>' + - name: Run stubsabot + run: | + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + scripts/stubsabot.py \ + --action-level=local diff --git a/.github/workflows/mypy_primer.yml b/.github/workflows/mypy_primer.yml index b793b3c2c828..6828ba72b4c3 100644 --- a/.github/workflows/mypy_primer.yml +++ b/.github/workflows/mypy_primer.yml @@ -1,32 +1,38 @@ -name: Run mypy_primer +name: mypy_primer on: - # Only run on PR, since we diff against master + # Only run on PR, since we diff against main pull_request: - # Since modular typeshed, mypy primer doesn't check third party stubs. Till that is changed, - # only run it on stdlib changes to avoid false confidence and wasted CI minutes. paths: - - 'stdlib/**' + - "stdlib/**" + - "stubs/**/*.pyi" + - ".github/workflows/mypy_primer.yml" + - ".github/workflows/mypy_primer_comment.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +permissions: + contents: read jobs: mypy_primer: name: Run - if: github.actor != 'pre-commit-ci[bot]' runs-on: ubuntu-latest - permissions: - contents: read strategy: matrix: - shard-index: [0, 1, 2, 3] + shard-index: [0, 1, 2, 3, 4, 5] fail-fast: false steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: typeshed_to_test fetch-depth: 0 - - uses: actions/setup-python@v2 + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: - python-version: "3.10" + python-version: "3.13" - name: Install dependencies run: pip install git+https://github.com/hauntsaninja/mypy_primer.git - name: Run mypy_primer @@ -35,35 +41,52 @@ jobs: cd typeshed_to_test MYPY_VERSION=$(grep mypy== requirements-tests.txt | cut -d = -f 3) echo "new commit" - git rev-list --format=%s --max-count=1 $GITHUB_SHA - git checkout -b upstream_master origin/master + git rev-list --format=%s --max-count=1 "$GITHUB_SHA" + git checkout -b upstream_main origin/main echo "base commit" - git rev-list --format=%s --max-count=1 upstream_master + git rev-list --format=%s --max-count=1 upstream_main echo '' cd .. # fail action if exit code isn't zero or one ( mypy_primer \ - --new v${MYPY_VERSION} --old v${MYPY_VERSION} \ + --new "v${MYPY_VERSION}" --old "v${MYPY_VERSION}" \ --custom-typeshed-repo typeshed_to_test \ - --new-typeshed $GITHUB_SHA --old-typeshed upstream_master \ - --num-shards 4 --shard-index ${{ matrix.shard-index }} \ + --new-typeshed "$GITHUB_SHA" --old-typeshed upstream_main \ + --num-shards 6 --shard-index ${{ matrix.shard-index }} \ --debug \ --output concise \ | tee diff_${{ matrix.shard-index }}.txt ) || [ $? -eq 1 ] - - name: Upload mypy_primer diff - uses: actions/upload-artifact@v2 - with: - name: mypy_primer_diffs - path: diff_${{ matrix.shard-index }}.txt - - if: ${{ matrix.shard-index }} == 0 + - if: ${{ matrix.shard-index == 0 }} name: Save PR number run: | echo ${{ github.event.pull_request.number }} | tee pr_number.txt - - if: ${{ matrix.shard-index }} == 0 - name: Upload PR number - uses: actions/upload-artifact@v2 + - name: Upload mypy_primer diff + PR number + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: ${{ matrix.shard-index == 0 }} + with: + name: mypy_primer_diffs-${{ matrix.shard-index }} + path: | + diff_${{ matrix.shard-index }}.txt + pr_number.txt + - name: Upload mypy_primer diff + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: ${{ matrix.shard-index != 0 }} + with: + name: mypy_primer_diffs-${{ matrix.shard-index }} + path: diff_${{ matrix.shard-index }}.txt + + join_artifacts: + name: Join artifacts + runs-on: ubuntu-latest + needs: [mypy_primer] + permissions: + contents: read + steps: + - name: Merge artifacts + uses: actions/upload-artifact/merge@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: mypy_primer_diffs - path: pr_number.txt + pattern: mypy_primer_diffs-* + delete-merged: true diff --git a/.github/workflows/mypy_primer_comment.yml b/.github/workflows/mypy_primer_comment.yml index ae9c7dcd4400..a0b964c748f2 100644 --- a/.github/workflows/mypy_primer_comment.yml +++ b/.github/workflows/mypy_primer_comment.yml @@ -1,9 +1,11 @@ -name: Post mypy_primer comment +name: mypy_primer (comment) -on: +# workflow_run is needed to comment on PRs from forks. This workflow only reads +# artifacts as data; it never checks out or executes PR code. +on: # zizmor: ignore[dangerous-triggers] workflow_run: workflows: - - Run mypy_primer + - mypy_primer types: - completed @@ -15,13 +17,14 @@ jobs: comment: name: Comment PR from mypy_primer runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} steps: - name: Download diffs - uses: actions/github-script@v3 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: script: | const fs = require('fs'); - const artifacts = await github.actions.listWorkflowRunArtifacts({ + const artifacts = await github.rest.actions.listWorkflowRunArtifacts({ owner: context.repo.owner, repo: context.repo.repo, run_id: ${{ github.event.workflow_run.id }}, @@ -29,7 +32,7 @@ jobs: const [matchArtifact] = artifacts.data.artifacts.filter((artifact) => artifact.name == "mypy_primer_diffs"); - const download = await github.actions.downloadArtifact({ + const download = await github.rest.actions.downloadArtifact({ owner: context.repo.owner, repo: context.repo.repo, artifact_id: matchArtifact.id, @@ -38,18 +41,28 @@ jobs: fs.writeFileSync("diff.zip", Buffer.from(download.data)); - run: unzip diff.zip - # 30000 bytes is about 300 lines, posting comment fails if too long - run: | - cat diff_*.txt | head -c 30000 | tee fulldiff.txt + cat diff_*.txt | tee fulldiff.txt - name: Post comment id: post-comment - uses: actions/github-script@v3 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: - github-token: ${{secrets.GITHUB_TOKEN}} + github-token: ${{ secrets.GITHUB_TOKEN }} script: | const fs = require('fs') - const data = fs.readFileSync('fulldiff.txt', { encoding: 'utf8' }) + let data = fs.readFileSync('fulldiff.txt', { encoding: 'utf8' }) + + // Maximum comment length is 65536 characters. We need much less than 236 for extra text. + const MAX_LENGTH = 65300 + if (data.length > MAX_LENGTH) { + let truncated_data = data.substring(0, MAX_LENGTH) + let lines_truncated = data.split('\n').length - truncated_data.split('\n').length + data = truncated_data + `\n\n... (truncated ${lines_truncated} lines) ...\n` + } + + console.log("Diff from mypy_primer:") + console.log(data) let body if (data.trim()) { @@ -59,7 +72,7 @@ jobs: } const prNumber = parseInt(fs.readFileSync("pr_number.txt", { encoding: "utf8" })) - await github.issues.createComment({ + await github.rest.issues.createComment({ issue_number: prNumber, owner: context.repo.owner, repo: context.repo.repo, @@ -68,8 +81,7 @@ jobs: return prNumber - name: Hide old comments - # v0.3.0 - uses: kanga333/comment-hider@bbdf5b562fbec24e6f60572d8f712017428b92e0 + uses: kanga333/comment-hider@c12bb20b48aeb8fc098e35967de8d4f8018fffdf # v0.4.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} leave_visible: 1 diff --git a/.github/workflows/stubsabot.yml b/.github/workflows/stubsabot.yml new file mode 100644 index 000000000000..be067faa5697 --- /dev/null +++ b/.github/workflows/stubsabot.yml @@ -0,0 +1,67 @@ +name: Stubsabot + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * *" + +permissions: {} + +env: + FORCE_COLOR: 1 + +jobs: + stubsabot: + name: Upgrade stubs with stubsabot + if: github.repository == 'python/typeshed' + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write # Create, update, and label PRs. + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # use an ssh key so that checks automatically run on stubsabot PRs + ssh-key: ${{ secrets.STUBSABOT_SSH_PRIVATE_KEY }} + fetch-depth: 0 + persist-credentials: true # stubsabot needs the SSH key to push branches. + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + # A compromised dependency in a test job on main could poison the shared + # uv cache. Restoring it here could execute attacker-controlled code + # with access to stubsabot's SSH key and GitHub token. + enable-cache: false + - name: Git config + run: | + git config --global user.name stubsabot + git config --global user.email '<>' + - name: Run stubsabot + run: | + GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} \ + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + scripts/stubsabot.py \ + --action-level=everything + + # https://github.community/t/run-github-actions-job-only-if-previous-job-has-failed/174786/2 + create-issue-on-failure: + name: Create issue on failure + runs-on: ubuntu-latest + needs: [stubsabot] + if: ${{ github.repository == 'python/typeshed' && always() && (needs.stubsabot.result == 'failure') }} + permissions: + issues: write + steps: + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.create({ + owner: "python", + repo: "typeshed", + title: `Stubsabot failed on ${new Date().toDateString()}`, + body: "Stubsabot run is listed here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}", + }) diff --git a/.github/workflows/stubtest.yml b/.github/workflows/stubtest.yml deleted file mode 100644 index 40e130734495..000000000000 --- a/.github/workflows/stubtest.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Run stubtest on all stubs - -on: - workflow_dispatch: - schedule: - - cron: "0 0 * * *" - -permissions: - contents: read - -env: - PIP_DISABLE_PIP_VERSION_CHECK: 1 - -jobs: - stubtest-stdlib: - name: Check stdlib with stubtest - if: github.repository == 'python/typeshed' - runs-on: ${{ matrix.os }} - strategy: - matrix: - # Temporarily disable "macos-latest", since Python 3.10.1 is not available. - # os: ["ubuntu-latest", "windows-latest", "macos-latest"] - os: ["ubuntu-latest", "windows-latest"] - # Temporarily hard-coded 3.10.1 due to stubtest incompatibilities. - python-version: ["3.6", "3.7", "3.8", "3.9", "3.10.1"] - fail-fast: false - - steps: - - uses: actions/checkout@v2 - - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.python-version }} - - name: Update pip - run: python -m pip install -U pip - - name: Install dependencies - run: pip install $(grep tomli== requirements-tests.txt) $(grep mypy== requirements-tests.txt) - - name: Run stubtest - run: python tests/stubtest_stdlib.py - - stubtest-third-party: - name: Check third party stubs with stubtest - if: github.repository == 'python/typeshed' - runs-on: ubuntu-latest - strategy: - matrix: - shard-index: [0, 1, 2, 3] - fail-fast: false - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - with: - python-version: 3.9 - - name: Install dependencies - run: pip install $(grep tomli== requirements-tests.txt) - - name: Run stubtest - run: python tests/stubtest_third_party.py --num-shards 4 --shard-index ${{ matrix.shard-index }} diff --git a/.github/workflows/stubtest_stdlib.yml b/.github/workflows/stubtest_stdlib.yml new file mode 100644 index 000000000000..8653d846f73c --- /dev/null +++ b/.github/workflows/stubtest_stdlib.yml @@ -0,0 +1,56 @@ +name: "Stubtest: stdlib" + +on: + workflow_dispatch: + push: + branches: + - main + pull_request: + paths: + - "stdlib/**" + - ".github/workflows/stubtest_stdlib.yml" + - "tests/**" + # When requirements.txt changes, we run `daily.yml`, which includes stdlib stubtest + +permissions: + contents: read + +env: + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + stubtest-stdlib: + name: "stubtest: stdlib" + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + exclude: + # https://github.com/python/typeshed/issues/15694 + - os: "windows-latest" + python-version: "3.10" + fail-fast: false + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: requirements-tests.txt + allow-prereleases: true + check-latest: true + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Run stubtest + run: python tests/stubtest_stdlib.py diff --git a/.github/workflows/stubtest_third_party.yml b/.github/workflows/stubtest_third_party.yml new file mode 100644 index 000000000000..3d90a7a77c33 --- /dev/null +++ b/.github/workflows/stubtest_third_party.yml @@ -0,0 +1,109 @@ +name: "Stubtest: third-party" + +on: + pull_request: + paths: + - "stubs/**" + - ".github/workflows/stubtest_third_party.yml" + - "tests/**" + # When requirements.txt changes, we run `daily.yml`, which includes third-party stubtest + +permissions: + contents: read + +env: + # A few env vars to speedup brew install + HOMEBREW_NO_ANALYTICS: 1 + HOMEBREW_NO_AUTOUPDATE: 1 + HOMEBREW_NO_INSTALL_CLEANUP: 1 # Environments are isolated, no need to cleanup old versions + NONINTERACTIVE: 1 # Required for brew install on CI + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + stubtest-third-party: + name: "stubtest: third party" + + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + fail-fast: false + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.13" + cache: pip + cache-dependency-path: | + requirements-tests.txt + stubs/**/METADATA.toml + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Determine changed stubs + shell: bash + run: | + # This only runs stubtest on changed stubs, because it is much faster. + # Use the daily.yml workflow to run stubtest on all third party stubs. + function find_stubs { + git diff --name-only "origin/${GITHUB_BASE_REF}" HEAD | \ + grep -E ^stubs/ | cut -d "/" -f 2 | sort -u | \ + (while IFS= read -r stub; do [ -d "stubs/$stub" ] && echo -n "$stub " || true; done) + } + STUBS=$(find_stubs || echo '') + echo "Changed stubs: $STUBS" + echo "STUBS=$STUBS" >> "$GITHUB_ENV" + - name: Install required system packages + shell: bash + run: | + # System package and stub directory names contain no whitespace or glob characters; split both lists into arguments. + # shellcheck disable=SC2086 + if [ -n "$STUBS" ]; then + PACKAGES=$(python tests/get_stubtest_system_requirements.py $STUBS) + if [ "${{ runner.os }}" = "Linux" ]; then + if [ -n "$PACKAGES" ]; then + printf 'Installing APT packages:\n' + printf ' %s\n' $PACKAGES + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + else + if [ "${{ runner.os }}" = "macOS" ] && [ -n "$PACKAGES" ]; then + printf 'Installing Homebrew packages:\n' + printf ' %s\n' $PACKAGES + brew install -q $PACKAGES + fi + + if [ "${{ runner.os }}" = "Windows" ] && [ -n "$PACKAGES" ]; then + printf 'Installing Chocolatey packages:\n' + printf ' %s\n' $PACKAGES + choco install -y $PACKAGES + fi + fi + fi + - name: Run stubtest + shell: bash + run: | + if [ -n "$STUBS" ]; then + echo "Testing $STUBS..." + + if [ "${{ runner.os }}" = "Linux" ]; then + PYTHON_EXECUTABLE="xvfb-run python" + else + PYTHON_EXECUTABLE="python" + fi + + # Stub directory names contain no whitespace or glob characters, so word splitting is intentional. + # shellcheck disable=SC2086 + $PYTHON_EXECUTABLE tests/stubtest_third_party.py --ci-platforms-only $STUBS + else + echo "Nothing to test" + fi diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index d935ad4632ce..1651e6261b4b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,138 +1,270 @@ -name: Check stubs +name: Type check, regression tests on: workflow_dispatch: push: + branches: + - main pull_request: + paths-ignore: + - "**/*.md" + - "scripts/**" permissions: contents: read env: PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true jobs: - file-consistency: - name: Check file consistency + typeshed-structure: + name: Check typeshed structure runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - - run: pip install $(grep tomli== requirements-tests.txt) - - run: ./tests/check_consistent.py + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Run check_typeshed_structure.py + run: | + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + ./tests/check_typeshed_structure.py - new-syntax: - name: Ensure new syntax usage + mypy: + name: "mypy: type check" runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32", "darwin"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + fail-fast: false steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - - run: ./tests/check_new_syntax.py + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - run: uv pip install -r requirements-tests.txt --system + - name: Install required APT packages + run: | + PACKAGES=$(python tests/get_stubtest_system_requirements.py) + # System package names contain no whitespace or glob characters, so word splitting is intentional. + # shellcheck disable=SC2086 + if [ -n "$PACKAGES" ]; then + printf 'Installing APT packages:\n' + printf ' %s\n' $PACKAGES + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + - name: Run mypy_test.py + run: python ./tests/mypy_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} - flake8: - name: Lint with flake8 + regression-tests: + name: "mypy: regression tests" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - - run: pip install $(grep flake8 requirements-tests.txt) - - run: flake8 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Run regr_test.py + run: | + uv run \ + --python=3.14 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + ./tests/regr_test.py \ + --all \ + --verbosity=QUIET - pytype: - name: Run pytype against the stubs + ty: + name: "ty: type check" runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32", "darwin"] + # TODO: Add 3.15 once third-party runtime dependencies provide compatible wheels. + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] + fail-fast: false steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - python-version: 3.9 - - run: pip install -r requirements-tests.txt - - run: ./tests/pytype_test.py + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Install typeshed test-suite requirements + run: uv pip install -r requirements-tests.txt --system + - name: Create an isolated venv for testing + run: uv venv .venv + - name: Install third-party stub dependencies + run: | + PACKAGES=$(python tests/get_external_stub_requirements.py) + if [ -n "$PACKAGES" ]; then + PACKAGE_ARGS=() + while IFS= read -r package; do + PACKAGE_ARGS+=("$package") + done <<< "$PACKAGES" + uv pip install --python-version ${{ matrix.python-version }} "${PACKAGE_ARGS[@]}" + fi + # Published stub packages can shadow the checked-in stubs when ty + # resolves their relative imports. + uv pip uninstall types-PyYAML types-pytz + - name: Run ty on all stubs + run: python tests/ty_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} --python=.venv - mypy: - name: Run mypy against the stubs + pyrefly: + name: "pyrefly: type check" runs-on: ubuntu-latest strategy: matrix: platform: ["linux", "win32", "darwin"] - python-version: ["2.7", "3.6", "3.7", "3.8", "3.9", "3.10"] + # TODO: Add 3.15 once third-party runtime dependencies provide compatible wheels. + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] fail-fast: false steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - - run: pip install $(grep tomli== requirements-tests.txt) $(grep mypy== requirements-tests.txt) - - run: ./tests/mypy_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Install typeshed test-suite requirements + run: uv pip install -r requirements-tests.txt --system + - name: Create an isolated venv for testing + run: uv venv .venv + - name: Install third-party stub dependencies + run: | + PACKAGES=$(python tests/get_external_stub_requirements.py) + if [ -n "$PACKAGES" ]; then + PACKAGE_ARGS=() + while IFS= read -r package; do + PACKAGE_ARGS+=("$package") + done <<< "$PACKAGES" + uv pip install --python-version ${{ matrix.python-version }} "${PACKAGE_ARGS[@]}" + fi + # Published stub packages can shadow the checked-in stubs when pyrefly + # resolves their relative imports. + uv pip uninstall types-PyYAML types-pytz + - name: Run pyrefly on all stubs + run: python tests/pyrefly_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} --python=.venv/bin/python pyright: - name: Run pyright against the stubs + name: "pyright: regression tests" runs-on: ubuntu-latest strategy: matrix: + # TODO: Add 3.15 once pyright CI can avoid installing third-party + # runtime dependency stacks that do not support Python 3.15 yet. python-platform: ["Linux", "Windows", "Darwin"] - python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] + python-version: ["3.11", "3.12", "3.13", "3.14"] fail-fast: false - env: - PYRIGHT_VERSION: 1.1.192 # Must match pyright_test.py. steps: - - uses: actions/checkout@v2 - - uses: jakebailey/pyright-action@v1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - version: ${{ env.PYRIGHT_VERSION }} + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.13" + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + with: + version-file: "requirements-tests.txt" + - name: Install typeshed test-suite requirements + # Install these so we can run `get_*_requirements.py` + run: uv pip install -r requirements-tests.txt --system + - name: Install required APT packages + run: | + PACKAGES=$(python tests/get_stubtest_system_requirements.py) + # System package names contain no whitespace or glob characters, so word splitting is intentional. + # shellcheck disable=SC2086 + if [ -n "$PACKAGES" ]; then + printf 'Installing APT packages:\n' + printf ' %s\n' $PACKAGES + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + - name: Create an isolated venv for testing + run: uv venv .venv + - name: Install 3rd-party stub dependencies + run: | + PACKAGES=$(python tests/get_external_stub_requirements.py) + if [ -n "$PACKAGES" ]; then + PACKAGE_ARGS=() + while IFS= read -r package; do + PACKAGE_ARGS+=("$package") + done <<< "$PACKAGES" + printf 'Installing python packages:\n' + printf ' %s\n' "${PACKAGE_ARGS[@]}" + uv pip install --python-version ${{ matrix.python-version }} "${PACKAGE_ARGS[@]}" + fi + - name: Activate the isolated venv for the rest of the job + run: echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: List 3rd-party stub dependencies installed + run: uv pip freeze + - name: Run pyright with basic settings on all the stubs + uses: jakebailey/pyright-action@8ec14b5cfe41f26e5f41686a31eb6012758217ef # v3.0.2 + with: + version: PATH python-platform: ${{ matrix.python-platform }} python-version: ${{ matrix.python-version }} - no-comments: ${{ matrix.python-version != '3.9' || matrix.python-platform != 'Linux' }} # Having each job create the same comment is too noisy. - project: ./pyrightconfig.stricter.json - - uses: jakebailey/pyright-action@v1 + annotate: ${{ matrix.python-version == '3.13' && matrix.python-platform == 'Linux' }} # Having each job create the same comment is too noisy. + - name: Run pyright with stricter settings on some of the stubs + uses: jakebailey/pyright-action@8ec14b5cfe41f26e5f41686a31eb6012758217ef # v3.0.2 with: - version: ${{ env.PYRIGHT_VERSION }} + version: PATH python-platform: ${{ matrix.python-platform }} python-version: ${{ matrix.python-version }} - no-comments: ${{ matrix.python-version != '3.9' || matrix.python-platform != 'Linux' }} # Having each job create the same comment is too noisy. - - stubtest-stdlib: - name: Check stdlib with stubtest - runs-on: ${{ matrix.os }} - strategy: - matrix: - # Temporarily disable "macos-latest", since Python 3.10.1 is not available. - # os: ["ubuntu-latest", "windows-latest", "macos-latest"] - os: ["ubuntu-latest", "windows-latest"] - # Temporarily hard-coded 3.10.1 due to stubtest incompatibilities. - python-version: ["3.6", "3.7", "3.8", "3.9", "3.10.1"] - fail-fast: false - - steps: - - uses: actions/checkout@v2 - - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} - uses: actions/setup-python@v2 + annotate: ${{ matrix.python-version == '3.13' && matrix.python-platform == 'Linux' }} # Having each job create the same comment is too noisy. + project: ./pyrightconfig.stricter.json + - name: Run pyright on the test cases + uses: jakebailey/pyright-action@8ec14b5cfe41f26e5f41686a31eb6012758217ef # v3.0.2 with: + version: PATH + python-platform: ${{ matrix.python-platform }} python-version: ${{ matrix.python-version }} - - name: Update pip - run: python -m pip install -U pip - - name: Install dependencies - run: pip install $(grep tomli== requirements-tests.txt) $(grep mypy== requirements-tests.txt) - - name: Run stubtest - run: python tests/stubtest_stdlib.py + annotate: ${{ matrix.python-version == '3.13' && matrix.python-platform == 'Linux' }} # Having each job create the same comment is too noisy. + project: ./pyrightconfig.testcases.json - stubtest-third-party: - name: Check third party stubs with stubtest + stub-uploader: + name: "stub uploader: tests" runs-on: ubuntu-latest - if: github.event_name == 'pull_request' steps: - - uses: actions/checkout@v2 + - name: Checkout typeshed + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: typeshed + persist-credentials: false + - name: Checkout stub_uploader + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 - - uses: actions/setup-python@v2 + repository: typeshed-internal/stub_uploader + path: stub_uploader + persist-credentials: false + - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 with: - python-version: 3.9 - - name: Install dependencies - run: pip install $(grep tomli== requirements-tests.txt) - - name: Run stubtest + version-file: "typeshed/requirements-tests.txt" + - name: Run tests run: | - STUBS=$(git diff --name-only origin/${{ github.base_ref }} HEAD | egrep ^stubs/ | cut -d "/" -f 2 | sort -u | (while read stub; do [ -d stubs/$stub ] && echo $stub || true; done)) - if test -n "$STUBS"; then - echo "Testing $STUBS..." - python tests/stubtest_third_party.py $STUBS - else - echo "Nothing to test" - fi + cd stub_uploader + uv run --python=3.13 --locked --group dev -m pytest tests diff --git a/.gitignore b/.gitignore index cca2cf7b80d3..edd0a9568bc0 100644 --- a/.gitignore +++ b/.gitignore @@ -8,12 +8,11 @@ __pycache__/ # Distribution / packaging .Python /env/ -/build/ +/lib/build/ /develop-eggs/ /dist/ /downloads/ /eggs/ -/lib/ /lib64/ /parts/ /sdist/ @@ -60,9 +59,19 @@ analyze.py # Editor backup files *~ .*.sw? -.vscode/ +.vscode/* +!.vscode/settings.default.json +!.vscode/extensions.json .idea/ .venv*/ # Mypy cache .mypy_cache/ + +# pyenv and uv local python version +.python-version +# we don't use uv's lock as we're not actually a project +uv.lock + +# deliberately local test configuration files +stdlib/@tests/stubtest_allowlists/*.local diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6f957cada1c5..8c6cc60df962 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,19 +1,64 @@ repos: - - repo: https://github.com/psf/black - rev: 21.12b0 # must match requirements-tests.txt + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-toml + - id: check-merge-conflict + - id: mixed-line-ending + args: [--fix=lf] + - id: check-case-conflict + - repo: https://github.com/python-jsonschema/check-jsonschema + rev: 4f85d46a92dc17713078e5de73f8a13190edf6fc # frozen: 0.38.2 + hooks: + - id: check-github-workflows + - id: check-renovate + additional_dependencies: ["json5==0.15.0"] + - repo: https://github.com/astral-sh/ruff-pre-commit + # The Ruff version must match requirements-tests.txt. + rev: f12be1ebaa5351c1fc76472de98db2c3446c8253 # frozen: v0.16.10 + hooks: + - id: ruff + name: Run ruff on stubs, tests and scripts + args: ["--exit-non-zero-on-fix"] + - id: ruff + # Very few rules are useful to run on our test cases; + # we explicitly enumerate them here: + name: Run ruff on the test cases + args: + - "--exit-non-zero-on-fix" + - "--select=FA,I,ICN001,RUF100" + - "--no-force-exclude" + - "--unsafe-fixes" + files: '.*test_cases/.+\.py$' + - repo: https://github.com/psf/black-pre-commit-mirror + rev: 96ae3e5802f3fe2d551e703e18f0a367d1a81ac2 # frozen: 26.10.0 hooks: - id: black - language_version: python3.9 - - repo: https://github.com/pycqa/isort - rev: 5.10.1 # must match requirements-tests.txt + - repo: https://github.com/pycqa/flake8 + rev: cfbbfdeb2391c14a37e101e92a77f54f329e1726 # frozen: 7.4.1 + hooks: + - id: flake8 + language: python + additional_dependencies: + - "flake8-pyi==26.5.0" + types: [file] + types_or: [python, pyi] + - repo: meta + hooks: + - id: check-hooks-apply + # zizmor detects security vulnerabilities in GitHub Actions workflows. + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: fa412071e4f5d44d44f9e365f4676f9df92456a2 # frozen: v1.30.1 hooks: - - id: isort - name: isort (python) + - id: zizmor + args: [--no-progress, --fix] ci: - autofix_commit_msg: '[pre-commit.ci] auto fixes from pre-commit.com hooks' - autofix_prs: true - autoupdate_commit_msg: '[pre-commit.ci] pre-commit autoupdate' - autoupdate_schedule: weekly - skip: [] - submodules: false + autofix_commit_msg: "[pre-commit.ci] auto fixes from pre-commit.com hooks" + autofix_prs: true + autoupdate_commit_msg: "[pre-commit.ci] pre-commit autoupdate" + autoupdate_schedule: quarterly + submodules: false diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000000..01b9ad4369db --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,41 @@ +// ⚠ Disclaimer: The typeshed team doesn't commit to maintaining this file. It exists purely for your ease of use. +// Keep in alphabetical order +{ + "recommendations": [ + "bierner.github-markdown-preview", + "charliermarsh.ruff", + "editorconfig.editorconfig", + "ms-python.black-formatter", + "ms-python.flake8", + "ms-python.mypy-type-checker", + "ms-python.python", + "ms-python.vscode-pylance", + "tamasfe.even-better-toml", + "redhat.vscode-yaml", + ], + "unwantedRecommendations": [ + /* + * Don't recommend by default for this workspace + */ + "christian-kohler.npm-intellisense", + /* + * Must disable in this workspace + * https://github.com/microsoft/vscode/issues/40239 + */ + // even-better-toml has format on save + "bungcip.better-toml", + // Don't use two mypy extensions simultaneously + "matangover.mypy", + // Use Ruff instead + "ms-python.isort", + // We use Black + "ms-python.autopep8", + // Not using pylint + "ms-python.pylint", + // VSCode has implemented an optimized version + "coenraads.bracket-pair-colorizer", + "coenraads.bracket-pair-colorizer-2", + // Obsoleted by Pylance + "ms-pyright.pyright", + ], +} diff --git a/.vscode/settings.default.json b/.vscode/settings.default.json new file mode 100644 index 000000000000..b7005630a4e3 --- /dev/null +++ b/.vscode/settings.default.json @@ -0,0 +1,125 @@ +/* + * Copy this file as `.vscode/settings.json` to configure VSCode for this workspace. + * Unfortunately, VSCode doesn't (yet) offer any way to have "workspace defaults" or "user-worspace settings", + * so offering defaults to copy is the best we can do at the moment. + * + * ⚠ Disclaimer: The typeshed team doesn't commit to maintaining this file. It exists purely for your ease of use. +*/ +{ + // Don't format on save for formatters we don't explicitely control + "editor.formatOnSave": false, + "editor.codeActionsOnSave": { + "source.fixAll": "never" + }, + // Set file associations to support comments syntax highlight + "files.associations": { + "settings.default.json": "jsonc", + "pyrightconfig*.json": "jsonc", + ".flake8": "properties", + "stubtest_allowlist*.txt": "properties", + "**/stubtest_allowlists/*.txt": "properties", + "pytype_exclude_list.txt": "properties" + }, + "files.exclude": { + "**/.*_cache": true, // mypy and Ruff cache + "**/__pycache__": true + }, + "files.eol": "\n", + "files.insertFinalNewline": true, + "files.trimFinalNewlines": true, + "files.trimTrailingWhitespace": true, + "editor.comments.insertSpace": true, + "editor.insertSpaces": true, + "editor.detectIndentation": false, + "editor.tabSize": 2, + "[json][jsonc][python][toml]": { + "editor.tabSize": 4 + }, + "editor.rulers": [ + 90, + 130 + ], + "[git-commit]": { + "editor.rulers": [ + 72 + ] + }, + // Format on save for formatters we explicitely control + "[json][jsonc][yaml][python][toml]": { + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll": "explicit" + } + }, + "[json][jsonc]": { + "editor.defaultFormatter": "vscode.json-language-features" + }, + "[yaml]": { + "editor.defaultFormatter": "redhat.vscode-yaml" + }, + "[toml]": { + "editor.rulers": [ + 90 + ], + "editor.defaultFormatter": "tamasfe.even-better-toml" + }, + "[python]": { + "editor.rulers": [ + 130 + ], + "editor.defaultFormatter": "ms-python.black-formatter", + "editor.codeActionsOnSave": { + // Let Ruff lint fixes handle imports + "source.organizeImports": "never", + "source.unusedImports": "never" + } + }, + // python.analysis is Pylance (pyright) configurations + "python.analysis.fixAll": [ + // Explicitly omiting "source.convertImportFormat", some stubs use relative imports + // Explicitly omiting "source.unusedImports", Let Ruff lint fixes handle imports + ], + "python.analysis.typeshedPaths": [ + "${workspaceFolder}" + ], + "python.analysis.extraPaths": [ + "tests" + ], + "mypy-type-checker.importStrategy": "fromEnvironment", + "mypy-type-checker.args": [ + "--custom-typeshed-dir=${workspaceFolder}", + // We only guarantee all of our tests can be run if you're on Python 3.9 or higher + "--python-version=3.9", + "--strict", + // Needed because a library stubbed in typeshed won't necessarily be installed in the dev's environment + "--ignore-missing-imports" + ], + // Ensure typeshed's configs are used, and not user's VSCode settings + "flake8.args": [ + "--config=.flake8" + ], + "flake8.importStrategy": "fromEnvironment", + "black-formatter.importStrategy": "fromEnvironment", + // Using Ruff instead of isort + "isort.check": false, + "ruff.importStrategy": "fromEnvironment", + "ruff.fixAll": true, + "ruff.organizeImports": true, + "evenBetterToml.formatter.alignComments": false, + "evenBetterToml.formatter.alignEntries": false, + "evenBetterToml.formatter.allowedBlankLines": 1, + "evenBetterToml.formatter.arrayAutoCollapse": true, + "evenBetterToml.formatter.arrayAutoExpand": true, + "evenBetterToml.formatter.arrayTrailingComma": true, + "evenBetterToml.formatter.columnWidth": 90, + "evenBetterToml.formatter.compactArrays": true, + "evenBetterToml.formatter.compactEntries": false, + "evenBetterToml.formatter.compactInlineTables": false, + "evenBetterToml.formatter.indentEntries": false, + "evenBetterToml.formatter.indentTables": false, + "evenBetterToml.formatter.inlineTableExpand": false, + "evenBetterToml.formatter.reorderArrays": true, + "evenBetterToml.formatter.trailingNewline": true, + // We like keeping TOML keys in a certain non-alphabetical order that feels more natural + "evenBetterToml.formatter.reorderKeys": false +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000000..c98f405a3e7d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,55 @@ +# typeshed - Python type stub repository + +typeshed contains [type stubs](https://typing.python.org/en/latest/spec/distributing.html) +for Python's standard library as well as for some packages available on +[PyPI](https://pypi.org/) (usually called "third-party stubs" in typeshed) +that don't provide their own type annotations. + +The standard library stubs get vendored by type checkers. Each third-party +stub package is distributed as a separate package (usually called +`types-`) on PyPI. + +## Directory Structure + +- `stdlib/` - Python standard library stubs +- `stubs/` - PyPI package stubs, one directory per package +- `scripts`/ - utility scripts +- `tests/` - scripts for various tests, see `tests/README.md` +- `lib/` - utility modules used by multiple scripts + +## Running tests + +To run all tests: + +- Create a new virtual environment (venv), update pip +- Install the dependencies from `requirements-tests.txt` into it +- Run `tests/runtests.py ` from the activated venv + +`` is either: + +- `stdlib/.pyi` +- `stubs/` + +See `tests/README.md` for more information about running tests. + +## Issues + +When also opening a pull request, only open issues for complex cases where +more discussion is expected. In simple or uncontroversial cases, opening only +a pull request is preferred. + +## Pull Requests + +When opening pull requests, do the following: + +- Follow the guidance from `CONTRIBUTING.md`. +- Run the tests as described above before submitting. +- Don't include tests for .pyi files, unless the situation is complex. See + `tests/REGRESSION.md`. +- Use a concise PR description: + - Either link to an issue or describe the problem briefly, never both. + - Limit the summary of changes to one sentence, unless the PR is complex. + - Include links to the "upstream" implementation code and/or API + documentation if possible. + - Don't include a testing plan. +- Add the name of the agent used to the PR description. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000000..43c994c2d361 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bd254a9a6cc8..2e1d4a56f1c0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,23 +1,23 @@ # Contributing to typeshed -Welcome! typeshed is a community project that aims to work for a wide -range of Python users and Python codebases. If you're trying a type +Welcome! typeshed is a community project that aims to work for a wide +range of Python users and Python codebases. If you're trying a type checker on your Python code, your experience and what you can contribute are important to the project's success. - ## The contribution process at a glance 1. [Prepare your environment](#preparing-the-environment). 2. Find out [where to make your changes](#where-to-make-changes). -3. [Prepare your changes](#preparing-changes): +3. [Making your changes](#making-changes): * Small fixes and additions can be submitted directly as pull requests, but [contact us](README.md#discussion) before starting significant work. * Create your stubs, considering [what to include](#what-to-include) and - conforming to the [coding style](#stub-file-coding-style). -4. [Format and check your stubs](#formatting-stubs). -5. Optionally [run the tests](#running-the-tests). + conforming to the [coding style](https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#style-guide). +4. Optionally [format and check your stubs](#stub-content-and-style). +5. Optionally [run the tests](tests/README.md). 6. [Submit your changes](#submitting-changes) by opening a pull request. +7. Make sure that all tests in CI are passing. You can expect a reply within a few days, but please be patient when it takes a bit longer. For more details, read below. @@ -26,88 +26,95 @@ it takes a bit longer. For more details, read below. ### Code away! -Typeshed runs continuous integration (CI) on all pull requests. This will -automatically fix formatting (using `black`, `isort`) and run tests. -It means you can ignore all local setup on your side, focus on the +Typeshed runs continuous integration (CI) on all pull requests. This means that +if you file a pull request (PR), our full test suite +-- including our linter, [`flake8-pyi`](https://github.com/pycqa/flake8-pyi) -- +is run on your PR. It also means that bots will automatically apply +changes to your PR (using [Black](https://github.com/psf/black) and +[Ruff](https://github.com/astral-sh/ruff)) to fix any formatting issues. +This frees you up to ignore all local setup on your side, focus on the code and rely on the CI to fix everything, or point you to the places that need fixing. ### ... Or create a local development environment -If you prefer to run the tests & formatting locally, it's +If you prefer to run the tests and formatting locally, it's possible too. Follow platform-specific instructions below. +For more information about our available tests, see +[tests/README.md](tests/README.md). Whichever platform you're using, you will need a virtual environment. If you're not familiar with what it is and how it works, please refer to this [documentation](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). -### Linux/Mac OS - -On Linux and Mac OS, you will be able to run the full test suite on Python 3.8 -or 3.9. Running the tests on <=3.7 is not supported, and the pytype tests -[cannot currently be run on Python 3.10](https://github.com/google/pytype/issues/1022). - -To install the necessary requirements, run the following commands from a -terminal window: - -``` -$ python3 -m venv .venv3 -$ source .venv3/bin/activate -(.venv3)$ pip install -U pip -(.venv3)$ pip install -r requirements-tests.txt -``` - -### Windows - -If you are using a Windows operating system, you will not be able to run the -full test suite. One option is to install -[Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/faq), -which will allow you to run the full suite of tests. If you choose to install -WSL, follow the Linux/Mac OS instructions above. - -If you do not wish to install WSL, you will not be able to run the pytype -tests, as pytype -[does not currently support running on Windows](https://github.com/google/pytype#requirements). -However, the upside of this is that you will be able to run all -Windows-compatible tests on Python 3.9, 3.8 or 3.10, as it is only the pytype -tests that cannot currently be run on 3.10. - -To install all non-pytype requirements on Windows without WSL, run the -following commands from a Windows terminal: - -``` -> python3 -m venv .venv3 -> ".venv3/Scripts/activate" -(.venv3) > python -m pip install -U pip -(.venv3) > python -m pip install -r requirements-tests.txt -``` - -## Code formatting - -The code is formatted by `black` and `isort`. - -The repository is equipped with a [`pre-commit.ci`](https://pre-commit.ci/) -configuration file. This means that you don't *need* to do anything yourself to -run the code formatters. When you push a commit, a bot will run those for you -right away and add a commit to your PR. Neat, no? - -That being said, if you *want* to run the checks locally when you commit, you -can install the hooks: please refer to the [pre-commit](https://pre-commit.com/) -documentation. +Note that some tests require extra setup steps to install the required dependencies. + + + + + + + + + + + + + + + + +
Linux / macOS / WSL + + To install the necessary requirements, run the following commands from a + terminal window: + + ```bash + $ python3 -m venv .venv + $ source .venv/bin/activate + (.venv)$ pip install -U pip + (.venv)$ pip install -r requirements-tests.txt + ``` + +
Windows + + Run the following commands from a Windows terminal to install all requirements: + + ```powershell + > py -m venv .venv + > .venv\Scripts\activate + (.venv) > python -m pip install -U pip + (.venv) > pip install -r requirements-tests.txt + ``` + +
Using uv + + If you already have [uv](https://docs.astral.sh/uv/getting-started/installation/) installed, you can simply replace the commands above with: + + ```shell + uv venv + uv pip install -r requirements-tests.txt + ``` + +
## Where to make changes ### Standard library stubs The `stdlib` directory contains stubs for modules in the -Python 3 standard library — which +Python standard library — which includes pure Python modules, dynamically loaded extension modules, hard-linked extension modules, and the builtins. The `VERSIONS` file lists the versions of Python where the module is available. -Stubs for Python 2 are available in the `stdlib/@python2` subdirectory. -Modules that are only available for Python 2 are not listed in `VERSIONS`. +We accept changes for future versions of Python after the first beta for that +version was released. We drop support for a Python version three months +after it reaches [end-of-life](https://devguide.python.org/versions/). This +means that we will no longer actively test the stubs against that version. +After six months, we will remove the stubs for that version and start +to use syntax and typing features not supported by that version. ### Third-party library stubs @@ -116,24 +123,16 @@ We accept stubs for third-party packages into typeshed as long as: * the package supports any Python version supported by typeshed; and * the package does not ship with its own stubs or type annotations. -Stubs for third-party packages -go into `stubs`. Each subdirectory there represents a PyPI distribution, and -contains the following: +The fastest way to generate new stubs is to use `scripts/create_baseline_stubs.py` (see below). + +Stubs for third-party packages go into the `stubs` directory. Each subdirectory +there represents a PyPI distribution, and contains the following: * `METADATA.toml`, describing the package. See below for details. * Stubs (i.e. `*.pyi` files) for packages and modules that are shipped in the source distribution. -* If the stubs are either Python 2-only, or if the Python 2 and Python 3 stubs - are separate, the Python 2 stubs are put in a `@python2` subdirectory. - Stubs outside `@python2` are always used with Python 3, - and also with Python 2 if `python2 = true` is set in `METADATA.toml` (see below). * (Rarely) some docs specific to a given type stub package in `README` file. -The fastest way to generate new stubs is to use [stubgen](https://mypy.readthedocs.io/en/stable/stubgen.html), -a tool shipped with mypy. Please make sure to use the latest version. -The generated stubs usually need some trimming of imports. You also need -to run `black` and `isort` manually on the generated stubs (see below). - -When a third party stub is added or +When a third-party stub is added or modified, an updated version of the corresponding distribution will be automatically uploaded to PyPI within a few hours. Each time this happens the least significant @@ -164,25 +163,129 @@ supported: When the stubs are updated to a newer version of the library, the version of the stub should be bumped (note that previous versions are still available on PyPI). -* `python2` (default: `false`): If set to `true`, the top-level stubs - support both Python 2 and Python 3. -* `requires` (optional): A list of other stub packages or packages with type +* `dependencies` (optional): A list of other stub packages or packages with type information that are imported by the stubs in this package. Only packages generated by typeshed or required by the upstream package are allowed to - be listed here, for security reasons. -* `extra_description` (optional): Can be used to add a custom description to + be listed here, for security reasons. See + [this issue](https://github.com/typeshed-internal/stub_uploader/issues/90) + for more information about what external dependencies are allowed. +* `optional-dependencies` (optional): A list of other stub packages or packages + with type information that are imported by some stubs in this package. This + is often used for packages that provide optional features that require extra + dependencies. The same limitations apply to this field as to `dependencies`. +* `extra-description` (optional): Can be used to add a custom description to the package's long description. It should be a multi-line string in Markdown format. -* `obsolete_since` (optional): This field is part of our process for +* `stub-distribution` (optional): Distribution name to be uploaded to PyPI. + This defaults to `types-` and should only be set in special + cases. +* `upstream-repository` (recommended): The URL of the upstream repository. +* `obsolete-since` (optional): This table is part of our process for [removing obsolete third-party libraries](#third-party-library-removal-policy). It contains the first version of the corresponding library that ships - its own `py.typed` file. + its own `py.typed` file, and the date when that version was released. +* `no-longer-updated` (optional): This field is set to `true` before removing + stubs for other reasons than the upstream library shipping with type + information. +* `upload` (optional): This field is set to `false` to prevent automatic + uploads to PyPI. This should only be used in special cases, e.g. when the stubs + break the upload. +* `partial-stub` (optional): This field marks the type stub package as + [partial](https://typing.python.org/en/latest/spec/distributing.html#partial-stub-packages). + This is for 3rd-party stubs that don't cover the entirety of the package's public API. +* `requires-python` (optional): The minimum version of Python required to install + the type stub package. It must be in the form `>=3.*`. If omitted, the oldest + Python version supported by typeshed is used. + +In addition, we specify configuration for stubtest in the `tool.stubtest` table. +This has the following keys: +* `skip` (default: `false`): Whether stubtest should be run against this + package. Please avoid setting this to `true`, and add a comment if you have + to. +* `ignore-missing-stub` (default: `false`): When set to `true`, this will add + the `--ignore-missing-stub` option to the stubtest call. See + [tests/README.md](./tests/README.md) for more information. In most cases, + this field should be identical to `partial-stub`. +* `stubtest-dependencies` (default: `[]`): A list of Python packages that need + to be installed for stubtest to run successfully. These packages are installed + in addition to the dependencies in the `dependencies` and + `optional-dependencies` fields. +* `apt-dependencies` (default: `[]`): A list of Ubuntu APT packages + that need to be installed for stubtest to run successfully. +* `brew-dependencies` (default: `[]`): A list of MacOS Homebrew packages + that need to be installed for stubtest to run successfully +* `choco-dependencies` (default: `[]`): A list of Windows Chocolatey packages + that need to be installed for stubtest to run successfully +* `extras` (default: `[]`): A list of optional dependency groups + ([extras](https://packaging.python.org/en/latest/specifications/core-metadata/#provides-extra-multiple-use)) + that need to be installed for stubtest to run successfully. + For example, `extras = ["foo"]` installs the package as `[foo]`. +* `supported-platforms` (default: all platforms): A list of OSes on which + stubtest can be run. When a package is not platform-specific, this should + not be set. If the package is platform-specific, this should usually be set + to the supported platforms, unless stubtest is known to fail on a + specific platform. +* `ci-platforms` (default: `["linux"]`): A list of OSes on which to run + stubtest as part of our continuous integration (CI) tests. Can contain + `win32`, `linux`, and `darwin` values. If not specified, stubtest is run + only on `linux`. Only add extra OSes to the test if there are + platform-specific branches in a stubs package. +* `mypy-plugins` (default: `[]`): A list of Python modules to use as mypy plugins +when running stubtest. For example: `mypy-plugins = ["mypy_django_plugin.main"]` +* `mypy-plugins-config` (default: `{}`): A dictionary mapping plugin names to their +configuration dictionaries for use by mypy plugins. For example: +`mypy-plugins-config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}}` +* `install-environment` (default: `{}`): A dictionary of environment variables + to set while `pip install`ing the package and its dependencies for stubtest. + Useful for packages that read build-time options from the environment, for + example to disable CPU-specific compiler flags that do not survive CI's + shared wheel cache. For example: + `install-environment = { HNSWLIB_NO_NATIVE = "1" }` + +`*-dependencies` are usually packages needed to `pip install` the implementation +distribution. The format of all `METADATA.toml` files can be checked by running -`python3 ./tests/check_consistent.py`. +`python3 ./tests/check_typeshed_structure.py`. + +### Dependencies + +When a third-party stub package depends on another package, there are several +strategies available, depending on whether the other package is typed. + +1. If the other package is typed and includes a `py.typed` marker, add that + package to the `dependencies` key in `METADATA.toml`. This might fail the + stub uploader checks, in which case you can ask the maintainers for help. +2. Otherwise, if a type package is available, add that package to the + `dependencies` key. If the type package originates from typeshed, the + stub uploader checks should succeed. +3. In case the dependency in untyped and no stubs are available, you may stub + the dependency in your type stubs. For example: + + ```python + from typing import Any + # from fruzzle import Frobnicator # won't work + _Frobnicator: TypeAlias = Any # actually fruzzle.Frobnicator + ``` -## Preparing Changes + In more complex or advanced cases you may instead opt to add a stubs + is a separate helper package: + + ```python + # stubs/my-stubs/my_stubs/_fruzzle.pyi + + # Utility stubs for the untyped "fruzzle" package. + + from typing import Any, Protocol + + Frobnicator: TypeAlias = Any + + class Flubberer(Protocol): + def flubb_it(self, x: int, /) -> str: ... + ``` + +## Making Changes ### Before you begin @@ -191,66 +294,32 @@ recommend starting by opening an issue laying out what you want to do. That lets a conversation happen early in case other contributors disagree with what you'd like to do or have ideas that will help you do it. -### Format - -Each Python module is represented by a `.pyi` "stub file". This is a -syntactically valid Python file, although it usually cannot be run by -Python 3 (since forward references don't require string quotes). All -the methods are empty. - -Python function annotations ([PEP 3107](https://www.python.org/dev/peps/pep-3107/)) -are used to describe the signature of each function or method. - -See [PEP 484](http://www.python.org/dev/peps/pep-0484/) for the exact -syntax of the stub files and [below](#stub-file-coding-style) for the -coding style used in typeshed. - -### Supported type system features - -Since PEP 484 was accepted, there have been many other PEPs that added -new features to the Python type system. In general, new features can -be used in typeshed as soon as the PEP has been accepted and implemented -and most type checkers support the new feature. - -Accepted features that *cannot* yet be used in typeshed include: -- [PEP 570](https://www.python.org/dev/peps/pep-0570/) (positional-only - arguments): see [#4972](https://github.com/python/typeshed/issues/4972), - use argument names prefixed with `__` instead -- [PEP 613](https://www.python.org/dev/peps/pep-0613/) (TypeAlias): - see [#4913](https://github.com/python/typeshed/issues/4913) - -The following features are partially supported: -- [PEP 585](https://www.python.org/dev/peps/pep-0585/) (builtin - generics): see [#4820](https://github.com/python/typeshed/issues/4820), - mostly supported but bugs remain for a few specific cases -- [PEP 612](https://www.python.org/dev/peps/pep-0612/) (ParamSpec): - see [#4827](https://github.com/python/typeshed/issues/4827), - supported in some contexts but requires `# type: ignore` comments - -Supported features include: -- [PEP 544](https://www.python.org/dev/peps/pep-0544/) (Protocol) -- [PEP 586](https://www.python.org/dev/peps/pep-0586/) (Literal) -- [PEP 591](https://www.python.org/dev/peps/pep-0591/) (Final/@final) -- [PEP 589](https://www.python.org/dev/peps/pep-0589/) (TypedDict) -- [PEP 604](https://www.python.org/dev/peps/pep-0604/) (`Foo | Bar` union syntax) -- [PEP 647](https://www.python.org/dev/peps/pep-0647/) (TypeGuard): - see [#5406](https://github.com/python/typeshed/issues/5406) +### Stub Content and Style -Features from the `typing` module that are not present in all -supported Python 3 versions must be imported from `typing_extensions` -instead in typeshed stubs. This currently affects: +Each Python module is represented by a .pyi "stub file". This is a syntactically valid Python file, where all methods are empty and [type annotations](https://typing.readthedocs.io/en/latest/spec/annotations.html) are used to describe function signatures and variable types. -- `Final` and `@final` (new in Python 3.8) -- `Literal` (new in Python 3.8) -- `SupportsIndex` (new in Python 3.8) -- `TypedDict` (new in Python 3.8) -- `Concatenate` (new in Python 3.10) -- `ParamSpec` (new in Python 3.10) -- `TypeGuard` (new in Python 3.10) +Typeshed follows the standard type system guidelines for [stub content](https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#stub-content) and [coding style](https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#style-guide). -Two exceptions are `Protocol` and `runtime_checkable`: although -these were added in Python 3.8, they can be used in stubs regardless -of Python version. +The code is formatted using [`Black`](https://github.com/psf/black). +Various other autofixes and lint rules are +also performed by [`Ruff`](https://github.com/astral-sh/ruff) and +[`Flake8`](https://github.com/pycqa/flake8), +with plugin [`flake8-pyi`](https://github.com/pycqa/flake8-pyi). + +The repository is equipped with a [pre-commit.ci](https://pre-commit.ci/) +configuration file. This means that you don't *need* to do anything yourself to +run the code formatters or linters. When you push a commit, a bot will run +those for you right away and add any autofixes to your PR. Anything +that can't be autofixed will show up as a CI failure, hopefully with an error +message that will make it clear what's gone wrong. + +That being said, if you *want* to run the formatters and linters locally +when you commit, you're free to do so. To use the same configuration as we use +in CI, we recommend doing this via pre-commit: + +```bash +(.venv)$ pre-commit run --all-files +``` ### What to include @@ -267,237 +336,115 @@ or if they are not prefixed with an underscore. This means that typeshed will generally accept contributions that add missing objects, even if they are undocumented. Undocumented objects should be marked with a comment of the form ``# undocumented``. -Example: + +### Incomplete Annotations + +When submitting new stubs, it is not necessary to annotate all arguments, +return types, and fields. Such items should either be left unannotated or +use `_typeshed.Incomplete` if this is not possible: ```python -def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented +from _typeshed import Incomplete + +field: Incomplete # unannotated + +def foo(x): ... # unannotated argument and return type ``` -We accept such undocumented objects because omitting objects can confuse -users. Users who see an error like "module X has no attribute Y" will -not know whether the error appeared because their code had a bug or -because the stub is wrong. Although it may also be helpful for a type -checker to point out usage of private objects, we usually prefer false -negatives (no errors for wrong code) over false positives (type errors -for correct code). In addition, even for private objects a type checker -can be helpful in pointing out that an incorrect type was used. +`Incomplete` can also be used for partially known types: + +```python +def foo(x: Incomplete | None) -> list[Incomplete]: ... +``` ### What to do when a project's documentation and implementation disagree Type stubs are meant to be external type annotations for a given -library. While they are useful documentation in its own merit, they +library. While they are useful documentation in their own right, they augment the project's concrete implementation, not the project's documentation. Whenever you find them disagreeing, model the type information after the actual implementation and file an issue on the project's tracker to fix their documentation. -### Stub versioning - -You can use checks -like `if sys.version_info >= (3, 8):` to denote new functionality introduced -in a given Python version or solve type differences. When doing so, only use -one-tuples or two-tuples. Because of this, if a given functionality was -introduced in, say, Python 3.7.4, your check: +### Byte Types -* should be expressed as `if sys.version_info >= (3, 7):` -* should NOT be expressed as `if sys.version_info >= (3, 7, 4):` -* should NOT be expressed as `if sys.version_info >= (3, 8):` +[PEP 688](https://www.python.org/dev/peps/pep-0688/) removes +the implicit promotion from `bytearray` and `memoryview` to `bytes`. +Typeshed stubs should be written assuming that these promotions +do not happen, so a parameter that accepts either `bytes` or +`bytearray` should be typed as `bytes | bytearray`. +Often one of the aliases from `_typeshed`, such as +`_typeshed.ReadableBuffer`, can be used instead. -When your stub contains if statements for different Python versions, -always put the code for the most recent Python version first. +### Deprecations (using the `@deprecated` decorator) -### Incomplete stubs +Generally deprecactions using the `@deprecated` decorator are added more +liberally in typeshed than runtime deprecation warnings. Here are some +guidelines that can be deviated from in special cases. -We accept partial stubs, especially for larger packages. These need to -follow the following guidelines: +Use `@deprecated` if and only if -* Included functions and methods must list all arguments, but the arguments - can be left unannotated. Do not use `Any` to mark unannotated arguments - or return values. -* Partial classes must include a `__getattr__()` method marked with an - `# incomplete` comment (see example below). -* Partial modules (i.e. modules that are missing some or all classes, - functions, or attributes) must include a top-level `__getattr__()` - function marked with an `# incomplete` comment (see example below). -* Partial packages (i.e. packages that are missing one or more sub-modules) - must have a `__init__.pyi` stub that is marked as incomplete (see above). - A better alternative is to create empty stubs for all sub-modules and - mark them as incomplete individually. +- a feature is deprecated at runtime (either using `@deprecated` or with a + runtime warning); or +- a feature is documented to be deprecated (e.g. in API documentation, + docstrings, or comments). -Example of a partial module with a partial class `Foo` and a partially -annotated function `bar()`: +For standard library features that are not deprecated in all Python versions +currently supported by typeshed use `@deprecated` for -```python -def __getattr__(name: str) -> Any: ... # incomplete - -class Foo: - def __getattr__(self, name: str) -> Any: ... # incomplete - x: int - y: str - -def bar(x: str, y, *, z=...): ... -``` +- all versions starting with the "Deprecated since" version, plus +- all versions for which an alternative is available. -### Using stubgen +### Docstrings -Mypy includes a tool called [stubgen](https://mypy.readthedocs.io/en/latest/stubgen.html) -that auto-generates stubs for Python and C modules using static analysis, -Sphinx docs, and runtime introspection. It can be used to get a starting -point for your stubs. Note that this generator is currently unable to -determine most argument and return types and omits them or uses ``Any`` in -their place. Fill out manually the types that you know. +Typeshed stubs should not include duplicated docstrings from the source code. -## Stub file coding style +### Auto-generating stub files -### Syntax example +Typeshed includes `scripts/create_baseline_stubs.py`. +It generates stubs automatically using a tool called +[stubgen](https://mypy.readthedocs.io/en/latest/stubgen.html) that comes with mypy. -The below is an excerpt from the types for the `datetime` module. +To get started, fork typeshed, clone your fork, and then +[create a virtualenv](#-or-create-a-local-development-environment). +You can then install the library with `pip` into the virtualenv and run the script below, +replacing `$INSERT_LIBRARY_NAME_HERE` with the name of the library: -```python -MAXYEAR: int -MINYEAR: int - -class date: - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... - @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... - @classmethod - def today(cls: Type[_S]) -> _S: ... - @classmethod - def fromordinal(cls: Type[_S], __n: int) -> _S: ... - @property - def year(self) -> int: ... - def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... - def ctime(self) -> str: ... - def weekday(self) -> int: ... +```bash +(.venv)$ pip install $INSERT_LIBRARY_NAME_HERE +(.venv)$ python3 scripts/create_baseline_stubs.py $INSERT_LIBRARY_NAME_HERE ``` -### Conventions - -Stub files are *like* Python files and you should generally expect them -to look the same. Your tools should be able to successfully treat them -as regular Python files. However, there are a few important differences -you should know about. - -Style conventions for stub files are different from PEP 8. The general -rule is that they should be as concise as possible. Specifically: -* all function bodies should be empty; -* prefer ``...`` over ``pass``; -* prefer ``...`` on the same line as the class/function signature; -* avoid vertical whitespace between consecutive module-level functions, - names, or methods and fields within a single class; -* use a single blank line between top-level class definitions, or none - if the classes are very small; -* do not use docstrings; -* use variable annotations instead of type comments, even for stubs - that target older versions of Python. - -Stub files should only contain information necessary for the type -checker, and leave out unnecessary detail: -* for arguments with a default, use `...` instead of the actual - default; -* for arguments that default to `None`, use `Foo | None` explicitly - (see below for details); -* use `float` instead of `int | float`. - -Some further tips for good type hints: -* use built-in generics (`list`, `dict`, `tuple`, `set`), instead - of importing them from `typing`, **except** in type aliases, in base classes, and for - arbitrary length tuples (`Tuple[int, ...]`); -* use `X | Y` instead of `Union[X, Y]` and `X | None`, instead of - `Optional[X]`, **except** when it is not possible due to mypy bugs (type aliases and base classes); -* in Python 3 stubs, import collections (`Mapping`, `Iterable`, etc.) - from `collections.abc` instead of `typing`; -* avoid invariant collection types (`list`, `dict`) in argument - positions, in favor of covariant types like `Mapping` or `Sequence`; -* avoid union return types: https://github.com/python/mypy/issues/1693; -* in Python 2, whenever possible, use `unicode` if that's the only - possible type, and `Text` if it can be either `unicode` or `bytes`; -* use platform checks like `if sys.platform == 'win32'` to denote - platform-dependent APIs; -* use mypy error codes for mypy-specific `# type: ignore` annotations, - e.g. `# type: ignore[override]` for Liskov Substitution Principle violations. - -Imports in stubs are considered private (not part of the exported API) -unless: -* they use the form ``from library import name as name`` (sic, using - explicit ``as`` even if the name stays the same); or -* they use the form ``from library import *`` which means all names - from that library are exported. - -When adding type hints, avoid using the `Any` type when possible. Reserve -the use of `Any` for when: -* the correct type cannot be expressed in the current type system; and -* to avoid union returns (see above). - -Note that `Any` is not the correct type to use if you want to indicate -that some function can accept literally anything: in those cases use -`object` instead. - -Stub files support forward references natively. In other words, the -order of class declarations and type aliases does not matter in -a stub file. You can also use the name of the class within its own -body. Focus on making your stubs clear to the reader. Avoid using -string literals in type annotations. - -Type variables and aliases you introduce purely for legibility reasons -should be prefixed with an underscore to make it obvious to the reader -they are not part of the stubbed API. - -When adding type annotations for context manager classes, annotate -the return type of `__exit__` as bool only if the context manager -sometimes suppresses exceptions -- if it sometimes returns `True` -at runtime. If the context manager never suppresses exceptions, -have the return type be either `None` or `bool | None`. If you -are not sure whether exceptions are suppressed or not or if the -context manager is meant to be subclassed, pick `bool | None`. -See https://github.com/python/mypy/issues/7214 for more details. - -`__enter__` methods and other methods that return instances of the -current class should be annotated with the `_typeshed.Self` type -variable ([example](https://github.com/python/typeshed/pull/5698)). - -A few guidelines for protocol names below. In cases that don't fall -into any of those categories, use your best judgement. - -* Use plain names for protocols that represent a clear concept - (e.g. `Iterator`, `Container`). -* Use `SupportsX` for protocols that provide callable methods (e.g. - `SupportsInt`, `SupportsRead`, `SupportsReadSeek`). -* Use `HasX` for protocols that have readable and/or writable attributes - or getter/setter methods (e.g. `HasItems`, `HasFileno`). - -## Formatting stubs - -Stubs should be reformatted with the formatters -[black](https://github.com/psf/black) and -[isort](https://github.com/PyCQA/isort) before submission. They -should also be checked for common problems by using -[flake8](https://flake8.pycqa.org/en/latest/) and the flake8 plugins -[flake8-pyi](https://github.com/ambv/flake8-pyi) and -[flake8-bugbear](https://github.com/PyCQA/flake8-bugbear). -All of these packages have been installed if you followed the -[setup instructions above](#preparing-the-environment). - -To format and check your stubs, run the following commands: +When the script has finished running, it will print instructions telling you what to do next. -``` -(.venv3)$ black stdlib stubs -(.venv3)$ isort stdlib stubs -(.venv3)$ flake8 -``` +If it has been a while since you set up the virtualenv, make sure you have +the latest mypy (`pip install -r requirements-tests.txt`) before running the script. +### Unsupported Type System Features -## Running the tests +Unless listed here, all type system features that have been added to the +[Python typing specification](https://typing.python.org/en/latest/spec/) +can be used. The following features are *not* supported: -The tests are automatically run on every PR and push to the repo. -Therefore you don't need to run them locally, unless you want to run -them before making a pull request or you want to debug some problem without -creating several small commits. +- [PEP 695](https://peps.python.org/pep-0695/) type parameter syntax. + (See [issue #10869](https://github.com/python/typeshed/issues/10869).) Use + explicit `TypeVar` definitions. +- [PEP 695](https://peps.python.org/pep-0695/) type statement for aliases. + (See [issue #10870](https://github.com/python/typeshed/issues/10870).) Use + `TypeAlias` annotations. -For more information about our available tests, see -[tests/README.md](tests/README.md). +Features from the `typing` module that are not present in all +supported Python versions must be imported from `typing_extensions` +instead in typeshed stubs. This currently affects: +- `Self` (new in Python 3.11) +- `Never` (new in Python 3.11) +- `LiteralString` (new in Python 3.11) +- `TypeVarTuple` and `Unpack` (new in Python 3.11) +- `Required` and `NotRequired` (new in Python 3.11) +- `Buffer` (new in Python 3.12; in the `collections.abc` module) +- `@deprecated` (new in Python 3.13; in the `warnings` module) +- `TypeForm` (new in Python 3.15) ## Submitting Changes @@ -522,6 +469,13 @@ processed incorrectly by a type checker. It is also helpful to add links to online documentation or to the implementation of the code you are changing. +As the author of the pull request, it is your responsibility to make +sure all CI tests pass and that any feedback is addressed. The typeshed +maintainers will probably provide some help and may even push changes +to your PR to fix any minor issues, but this is not always possible. +If a PR lingers with unresolved problems for too long, we may close it +([see below](#closing-stale-prs)). + Also, do not squash your commits or use `git commit --amend` after you have submitted a pull request, as this erases context during review. We will squash commits when the pull request is merged. This way, your pull request will appear as a single commit in our git history, even @@ -529,44 +483,49 @@ if it consisted of several smaller commits. ## Third-party library removal policy -Third-party packages are generally removed from typeshed when one of the +Third-party stubs are generally removed from typeshed when one of the following criteria is met: -* The upstream package ships a `py.typed` file for at least 6-12 months, or -* the package does not support any of the Python versions supported by - typeshed. +* The upstream package ships a `py.typed` file for at least six months, + and the upstream type annotations are of a comparable standard to those in + typeshed, or +* the upstream package was declared or appears to be unmaintained, and + retaining the stubs causes maintenance issues in typeshed. -If a package ships its own `py.typed` file, please follow these steps: +Case 1: If a package ships its own `py.typed` file, please follow these steps: -1. Open an issue with the earliest month of removal in the subject. +1. Make sure **stubsabot** open a PR that sets the `obsolete-since` field in the + `METADATA.toml` file to the first version of the package that shipped `py.typed`. +2. After at least six months, make sure **stubsabot** open a PR to remove the stubs. + +Case 2: If third-party stubs should be removed for other reasons, please follow +these steps: + +1. Open an issue explaining why the stubs should be removed. 2. A maintainer will add the - ["removal" label](https://github.com/python/typeshed/labels/removal). -3. Open a PR that sets the `obsolete_since` field in the `METADATA.toml` - file to the first version of the package that shipped `py.typed`. - -## Maintainer guidelines - -The process for preparing and submitting changes also applies to -maintainers. This ensures high quality contributions and keeps -everybody on the same page. Avoid direct pushes to the repository. - -When reviewing pull requests, follow these guidelines: - -* Typing is hard. Try to be helpful and explain issues with the PR, - especially to new contributors. -* When reviewing auto-generated stubs, just scan for red flags and obvious - errors. Leave possible manual improvements for separate PRs. -* When reviewing large, hand-crafted PRs, you only need to look for red flags - and general issues, and do a few spot checks. -* Review smaller, hand-crafted PRs thoroughly. - -When merging pull requests, follow these guidelines: - -* Always wait for tests to pass before merging PRs. -* Use "[Squash and merge](https://github.com/blog/2141-squash-your-commits)" to merge PRs. -* Make sure the commit message is meaningful. For example, remove irrelevant - intermediate commit messages. -* The commit message for third-party stubs is used to generate the changelog. - It should be valid Markdown, be comprehensive, read like a changelog entry, - and assume that the reader has no access to the diff. -* Delete branches for merged PRs (by maintainers pushing to the main repo). + ["stubs: removal" label](https://github.com/python/typeshed/labels/stubs%3A%20removal). +3. Open a PR that sets the `no-longer-updated` field in the `METADATA.toml` + file to `true`. +4. When a new version of the package was automatically uploaded to PyPI (which + can take up to a day), make sure **stubsabot** open a PR to remove the stubs. + +If feeling kindly, please update [mypy](https://github.com/python/mypy/blob/master/mypy/stubinfo.py) +for any stub obsoletions or removals. + +### Marking PRs as "deferred" + +We sometimes use the ["status: deferred" label](https://github.com/python/typeshed/labels/status%3A%20deferred) +to mark PRs and issues that we'd like to accept, but that are blocked by some +external factor. Blockers can include: + +- An unambiguous bug in a type checker (i.e., a case where the + type checker is not implementing [the typing spec](https://typing.readthedocs.io/en/latest/spec/index.html)). +- A dependency on a typing PEP that is still under consideration. +- A pending change in a related project, such as stub-uploader. + +### Closing stale PRs + +To keep the number of open PRs manageable, we may close PRs when they have been +open for too long. Specifically, we close open PRs that either have failures in CI, +serious merge conflicts or unaddressed feedback, and that have not seen any +activity in three months. diff --git a/LICENSE b/LICENSE index e5833ae4231d..13264487581f 100644 --- a/LICENSE +++ b/LICENSE @@ -235,4 +235,3 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. = = = = = - diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 15ff6c9b5788..2048da2064d9 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -5,13 +5,101 @@ At present the active maintainers are (alphabetically): * Ivan Levkivskyi (@ilevkivskyi) * Sebastian Rittau (@srittau) * Guido van Rossum (@gvanrossum) +* Brian Schubert (@brianschubert) * Shantanu (@hauntsaninja) -* Rune Tynan (@CraftSpider) +* Nikita Sobolev (@sobolevn) +* Samuel Therrien (@Avasam) * Aku Viljanen (@Akuli) +* Alex Waygood (@AlexWaygood) * Jelle Zijlstra (@JelleZijlstra) -Former and inactive maintainers include: +Former maintainers include: + * David Fisher (@ddfisher) -* Łukasz Langa (@ambv) * Matthias Kramm (@matthiaskramm) +* Łukasz Langa (@ambv) * Greg Price (@gnprice) +* Rune Tynan (@CraftSpider) + +For security reasons, maintainers who haven't been active for twelve months +(no PR reviews or merges, no opened PRs, no significant participation in +issues or typing-related discussion) will have their access rights removed. +They will also be moved to the "former maintainers" section here. + +Former maintainers who want their access rights restored should open +an issue or mail one of the active maintainers. + +## Maintainer guidelines + +The process for preparing and submitting changes as outlined +in the [CONTRIBUTING document](./CONTRIBUTING.md) also applies to +maintainers. This ensures high quality contributions and keeps +everybody on the same page. Do not make direct pushes to the repository. + +### Reviewing and merging pull requests + +When reviewing pull requests, follow these guidelines: + +* Typing is hard. Try to be helpful and explain issues with the PR, + especially to new contributors. +* When reviewing auto-generated stubs, just scan for red flags and obvious + errors. Leave possible manual improvements for separate PRs. +* When reviewing large, hand-crafted PRs, you only need to look for red flags + and general issues, and do a few spot checks. +* Review smaller, hand-crafted PRs thoroughly. + +When merging pull requests, follow these guidelines: + +* Always wait for tests to pass before merging PRs. +* Use "[Squash and merge](https://github.com/blog/2141-squash-your-commits)" to merge PRs. +* Make sure the commit message is meaningful. For example, remove irrelevant + intermediate commit messages. +* The commit message for third-party stubs is used to generate the changelog. + It should be valid Markdown, be comprehensive, read like a changelog entry, + and assume that the reader has no access to the diff. +* Delete branches for merged PRs (by maintainers pushing to the main repo). + +### Marking PRs as "deferred" + +*See also the [guidelines in the CONTRIBUTING file](./CONTRIBUTING.md#marking-prs-as-deferred).* + +PRs should only be marked as "deferred" if there is a clear path towards getting +the blocking issue resolved within a reasonable time frame. If a PR depends on +a more amorphous change, such as a type system change that has not yet reached +the PEP stage, it should instead be closed. + +Maintainers who add the "deferred" label should state clearly what exactly the +blocker is, usually with a link to an open issue in another project. + +### Closing stale PRs + +*See also the [guidelines in the CONTRIBUTING file](./CONTRIBUTING.md#closing-stale-prs).* + +We want to maintain a welcoming atmosphere for contributors, so use a friendly +message when closing the PR. Example message: + + Thanks for contributing! I'm closing this PR for now, because it still after three months of inactivity. If you are still interested, please feel free to open a new PR (or ping us to reopen this one). + +### Closing PRs for future standard library changes + +*See also the [guidelines in the CONTRIBUTING file](./CONTRIBUTING.md#standard-library-stubs).* + +When rejecting a PR for a change for a future Python version, use a message +like: + + Thanks for contributing! Unfortunately, [as outlined in our CONTRIBUTING document](https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#standard-library-stubs) we only accept pull requests to the standard library for future Python versions after the first beta version has been released. This is in part to prevent churn in the stubs, and in part because the testing infrastructure for the future version is not yet in place. Please feel free to open a new PR when the first beta version has been released. Alternatively, if this PR is still relevant, you can leave a comment here to reopen it. + +### Closing requests for third-party stubs + +We don't keep requests for third-party library stubs open. Close those +requests as "not planned" with an explanation like this: + + We gladly accept type stub contributions for third-party libraries that are published on PyPI in typeshed. To contribute a new library, please follow the steps outlined in [CONTRIBUTING.md](/python/typeshed/blob/main/CONTRIBUTING.md). The `create_baseline_stubs.py` script can be useful to create an initial version, suitable for inclusion in typeshed. + + That said, we don't keep requests for third-party library stubs open, unless there are issues that need to be addressed before a PR can be opened. Therefore, I'm closing this issue. + +### Asking to remove tests + + Please remove the tests. In typeshed, we only add regression tests for functions and classes which are known to have caused complex problems in the past, or where stubs are difficult to get right. 100% test coverage for typeshed is neither necessary nor desirable, as it would lead to code duplication. + + See [`tests/REGRESSION.md`](https://github.com/python/typeshed/blob/main/tests/REGRESSION.md) for more information. diff --git a/README.md b/README.md index afd140b10831..dae1780a4127 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,107 @@ # typeshed -[![Build status](https://github.com/python/typeshed/workflows/Check%20stubs/badge.svg)](https://github.com/python/typeshed/actions?query=workflow%3A%22Check+stubs%22) +[![Tests](https://github.com/python/typeshed/actions/workflows/tests.yml/badge.svg)](https://github.com/python/typeshed/actions/workflows/tests.yml) [![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Pull Requests Welcome](https://img.shields.io/badge/pull%20requests-welcome-brightgreen.svg)](https://github.com/python/typeshed/blob/master/CONTRIBUTING.md) +[![Pull Requests Welcome](https://img.shields.io/badge/pull%20requests-welcome-brightgreen.svg)](https://github.com/python/typeshed/blob/main/CONTRIBUTING.md) ## About Typeshed contains external type annotations for the Python standard library -and Python builtins, as well as third party packages as contributed by +and Python builtins, as well as third-party packages that are contributed by people external to those projects. -This data can e.g. be used for static analysis, type checking or type inference. +This data can, e.g., be used for static analysis, type checking, type inference, +and autocompletion. -For information on how to use `typeshed`, read below. Information for +For information on how to use typeshed, read below. Information for contributors can be found in [CONTRIBUTING.md](CONTRIBUTING.md). **Please read it before submitting pull requests; do not report issues with annotations to the project the stubs are for, but instead report them here to typeshed.** -Typeshed supports Python versions 2.7 and 3.6 and up. +Further documentation on stub files, typeshed, and Python's typing system in +general, can also be found at https://typing.readthedocs.io/en/latest/. + +Typeshed supports Python versions 3.10 to 3.14. ## Using -If you're just using mypy (or pytype or PyCharm), as opposed to +If you're just using a type checker (e.g. [mypy](https://github.com/python/mypy/), +[pyright](https://github.com/microsoft/pyright), or PyCharm's built-in type +checker), as opposed to developing it, you don't need to interact with the typeshed repo at -all: a copy of standard library part of typeshed is bundled with mypy. -And type stubs for third party packages and modules you are using can -be installed from PyPI. For example, if you are using `six` and `requests`, +all: a copy of the standard library part of typeshed is bundled with type checkers. +And type stubs for third-party packages and modules you are using can +be installed from PyPI. For example, if you are using `html5lib` and `requests`, you can install the type stubs using - $ pip install types-six types-requests +```bash +$ pip install types-html5lib types-requests +``` -These PyPI packages follow [PEP 561](http://www.python.org/dev/peps/pep-0561/) -and are automatically released (multiple times a day, when needed) by +These PyPI packages follow [the typing spec standards](https://typing.python.org/en/latest/spec/distributing.html) +and are automatically released (up to once a day) by [typeshed internal machinery](https://github.com/typeshed-internal/stub_uploader). Type checkers should be able to use these stub packages when installed. For more details, see the documentation for your type checker. +### Package versioning for third-party stubs + +Version numbers of third-party stub packages consist of at least four parts. +All parts of the stub version, except for the last part, correspond to the +version of the runtime package being stubbed. For example, if the `types-foo` +package has version `1.2.0.20240309`, this guarantees that the `types-foo` package +contains stubs targeted against `foo==1.2.*` and tested against the latest +version of `foo` matching that specifier. In this example, the final element +of the version number (20240309) indicates that the stub package was pushed on +March 9, 2024. + +At typeshed, we try to keep breaking changes to a minimum. However, due to the +nature of stubs, any version bump can introduce changes that might make your +code fail to type check. + +There are several strategies available for specifying the version of a stubs +package you're using, each with its own tradeoffs: + +1. Use the same bounds that you use for the package being stubbed. For example, + if you use `requests>=2.30.0,<2.32`, you can use + `types-requests>=2.30.0,<2.32`. This ensures that the stubs are compatible + with the package you are using, but it carries a small risk of breaking + type checking due to changes in the stubs. + + Another risk of this strategy is that stubs often lag behind + the package that is being stubbed. You might want to force the package being stubbed + to a certain minimum version because it fixes a critical bug, but if + correspondingly updated stubs have not been released, your type + checking results may not be fully accurate. +2. Pin the stubs to a known good version and update the pin from time to time + (either manually, or using a tool such as dependabot or renovate). + + For example, if you use `types-requests==2.31.0.1`, you can have confidence + that upgrading dependencies will not break type checking. However, you will + miss out on improvements in the stubs that could potentially improve type + checking until you update the pin. This strategy also has the risk that the + stubs you are using might become incompatible with the package being stubbed. +3. Don't pin the stubs. This is the option that demands the least work from + you when it comes to updating version pins, and has the advantage that you + will automatically benefit from improved stubs whenever a new version of the + stubs package is released. However, it carries the risk that the stubs + become incompatible with the package being stubbed. + + For example, if a new major version of the package is released, there's a + chance the stubs might be updated to reflect the new version of the runtime + package before you update the package being stubbed. + +You can also switch between the different strategies as needed. For example, +you could default to strategy (1), but fall back to strategy (2) when +a problem arises that can't easily be fixed. + ### The `_typeshed` package typeshed includes a package `_typeshed` as part of the standard library. -This package and its submodules contains utility types, but is not +This package and its submodules contain utility types, but are not available at runtime. For more information about how to use this package, -[see the `stdlib/_typeshed` directory](https://github.com/python/typeshed/tree/master/stdlib/_typeshed). +[see the `stdlib/_typeshed` directory](https://github.com/python/typeshed/tree/main/stdlib/_typeshed). ## Discussion @@ -60,6 +119,6 @@ a review of your type annotations or stubs outside of typeshed, head over to [our discussion forum](https://github.com/python/typing/discussions). For less formal discussion, try the typing chat room on [gitter.im](https://gitter.im/python/typing). Some typeshed maintainers -are almost always present; feel free to find us there and we're happy +are almost always present; feel free to find us there, and we're happy to chat. Substantive technical discussion will be directed to the issue tracker. diff --git a/lib/pyproject.toml b/lib/pyproject.toml new file mode 100644 index 000000000000..34720aa9acba --- /dev/null +++ b/lib/pyproject.toml @@ -0,0 +1,9 @@ +# Utilities for typeshed infrastructure scripts. + +[project] +name = "ts_utils" +version = "0.0.0" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" diff --git a/lib/ts_utils/__init__.py b/lib/ts_utils/__init__.py new file mode 100644 index 000000000000..44e839ba3a27 --- /dev/null +++ b/lib/ts_utils/__init__.py @@ -0,0 +1 @@ +"""Utilities for typeshed infrastructure scripts.""" diff --git a/lib/ts_utils/formatter.py b/lib/ts_utils/formatter.py new file mode 100644 index 000000000000..649403f81fbe --- /dev/null +++ b/lib/ts_utils/formatter.py @@ -0,0 +1,190 @@ +import subprocess +import time +from typing_extensions import Self + +from ts_utils.utils import TextColor, colored, format_time + + +class StatusLineFormatter: + """Context manager for printing a single line status. + + This prints a leading text (for example the name of an item) when the + context manager is entered, and the colored success status when the + context manager is exited: + + >>> with StatusLineFormatter("requests") as formatter: + ... # ... + ... formatter.success("ok") + requests... ok + + The possible status methods are "success", "warning", and "error". If + multiple functions are called, only the last one is considered: + + >>> with StatusLineFormatter("requests") as formatter: + ... # ... + ... formatter.success("ok") + ... formatter.error("error") + requests... error + + If no status method is called before the context manager exists, an error + is printed and an exception is raised: + + >>> with StatusLineFormatter("requests") as formatter: + ... pass + Traceback (most recent call last): + ... + RuntimeError: Progress formatter status not set + >>> try: + ... with StatusLineFormatter("requests") as formatter: + ... pass + ... except RuntimeError: + ... pass + requests... unknown result + + If the context manager is exited with an exception, an error is printed, + regardless of any status set. The exception is not handled: + + >>> with StatusLineFormatter("requests") as formatter: + ... raise ValueError("test error") + Traceback (most recent call last): + ... + ValueError: test error + >>> try: + ... with StatusLineFormatter("requests") as formatter: + ... raise ValueError("test error") + ... except ValueError: + ... pass + requests... error (test error) + + It's possible to attach additional output to the formatter. This is + printed after the status line, using a dimmed color by default: + + >>> with StatusLineFormatter("requests") as formatter: + ... formatter.error("fail") + ... formatter.append_output("This is an additional line.") + requests... fail + + This is an additional line. + + """ + + def __init__(self, initial_text: str, *, timed: bool = False) -> None: + self.initial_text = initial_text + self.timed = timed + self.status_message: str | None = None + self.status_color: TextColor = "red" + self.additional_output: list[tuple[str, TextColor]] = [] + self.start_time = 0.0 + + def __enter__(self) -> Self: + print(f"{self.initial_text}... ", end="", flush=True) + self.start_time = time.time() + return self + + def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> None: + t = time.time() - self.start_time + + if exc_value is not None: + print(colored(f"error ({exc_value})", "red")) + return + + if self.status_message is None: + print(colored("unknown result", "red")) + raise RuntimeError("Progress formatter status not set") + + print(colored(self.status_message, self.status_color), end="") + if self.timed: + print(" ", end="") + print(colored(format_time(t)), end="") + print() + + if self.additional_output: + print() + for text, color in self.additional_output: + print(colored(text.strip(), color)) + print() + + def success(self, message: str) -> None: + """Print a successful status.""" + self.status_message = message + self.status_color = "green" + + def warning(self, message: str) -> None: + """Print a warning status.""" + self.status_message = message + self.status_color = "yellow" + + def error(self, message: str) -> None: + """Print an error status.""" + self.status_message = message + self.status_color = "red" + + def append_output(self, message: str) -> None: + """Print an additional message after the status line.""" + self.additional_output.append((message, "dark_grey")) + + def append_warning(self, message: str) -> None: + """Print an additional warning after the status line.""" + self.additional_output.append((message, "yellow")) + + def append_hint(self, message: str) -> None: + """Print a hint for the user.""" + self.additional_output.append((message, "magenta")) + + def append_divider(self) -> None: + """Append a divider to the additional output. + + This can be used to separate sections in the output: + + >>> with StatusLineFormatter("requests") as formatter: + ... formatter.success("ok") + ... formatter.append_output("Line 1") + ... formatter.append_divider() + ... formatter.append_output("Line 2") + requests... ok + + Line 1 + + ********************************************************************** + + Line 2 + + """ + self.additional_output.extend([("", "dark_grey"), ("*" * 70, "dark_grey"), ("", "dark_grey")]) + + def command_output(self, e: subprocess.CompletedProcess[bytes] | subprocess.CalledProcessError) -> None: + """Print command output (stdout and stderr) as additional messages. + + >>> with StatusLineFormatter("requests") as formatter: + ... e = subprocess.run(["ls", "/dev/null"], capture_output=True) + ... formatter.command_output(e) + ... formatter.success("ok") + requests... ok + + /dev/null + + """ + stdout = e.stdout.decode() + stderr = e.stderr.decode() + if stdout: + self.additional_output.append((stdout, "dark_grey")) + if stderr: + self.additional_output.append((stderr, "dark_grey")) + + def command_error(self, message: str, e: subprocess.CalledProcessError) -> None: + """Print an error status for a failed command. + + The command output (stdout and stderr) will also be printed. + + >>> with StatusLineFormatter("requests") as formatter: + ... try: + ... subprocess.run(["ls", "/will/not/exist"], check=True, capture_output=True) + ... except subprocess.CalledProcessError as e: + ... formatter.command_error("fail (could not list directory)", e) + requests... fail (could not list directory) + + ls: cannot access '/will/not/exist': No such file or directory + + """ + self.error(message) + self.command_output(e) diff --git a/lib/ts_utils/metadata.py b/lib/ts_utils/metadata.py new file mode 100644 index 000000000000..5aa7109e346c --- /dev/null +++ b/lib/ts_utils/metadata.py @@ -0,0 +1,468 @@ +# This module is made specifically to abstract away those type errors +# pyright: reportUnknownVariableType=false, reportUnknownArgumentType=false + +"""Tools to help parse and validate information stored in METADATA.toml files.""" + +from __future__ import annotations + +import datetime +import functools +import re +import sys +import urllib.parse +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Annotated, Any, Final, NamedTuple, TypeGuard, cast, final + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +import tomlkit +from packaging.requirements import Requirement +from packaging.specifiers import Specifier + +from .paths import PYPROJECT_PATH, STUBS_PATH, distribution_path + +__all__ = [ + "NoSuchStubError", + "PackageDependencies", + "StubMetadata", + "StubtestSettings", + "get_oldest_supported_python", + "get_recursive_requirements", + "read_dependencies", + "read_metadata", + "read_stubtest_settings", +] + +DEFAULT_STUBTEST_PLATFORMS = ["linux"] + +_STUBTEST_PLATFORM_MAPPING: Final = {"linux": "apt_dependencies", "darwin": "brew_dependencies", "win32": "choco_dependencies"} +# Some older websites have a bad pattern of using query params for navigation. +_QUERY_URL_ALLOWLIST = {"sourceware.org"} + + +def _is_list_of_strings(obj: object) -> TypeGuard[list[str]]: + return isinstance(obj, list) and all(isinstance(item, str) for item in obj) + + +def _is_nested_dict(obj: object) -> TypeGuard[dict[str, dict[str, Any]]]: + return isinstance(obj, dict) and all(isinstance(k, str) and isinstance(v, dict) for k, v in obj.items()) + + +def _is_dict_of_strings(obj: object) -> TypeGuard[dict[str, str]]: + return isinstance(obj, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in obj.items()) + + +@functools.cache +def get_oldest_supported_python() -> str: + with PYPROJECT_PATH.open("rb") as config: + val = tomllib.load(config)["tool"]["typeshed"]["oldest-supported-python"] + assert type(val) is str + return val + + +def metadata_path(distribution: str) -> Path: + """Return the path to the METADATA.toml file of a third-party distribution.""" + return distribution_path(distribution) / "METADATA.toml" + + +@final +@dataclass(frozen=True) +class StubtestSettings: + """The stubtest settings for a single stubs distribution. + + Don't construct instances directly; use the `read_stubtest_settings` function. + """ + + skip: bool + apt_dependencies: list[str] + brew_dependencies: list[str] + choco_dependencies: list[str] + extras: list[str] + ignore_missing_stub: bool + supported_platforms: list[str] | None # None means all platforms + ci_platforms: list[str] + stubtest_dependencies: list[str] + mypy_plugins: list[str] + mypy_plugins_config: dict[str, dict[str, Any]] + install_environment: dict[str, str] + + def system_requirements_for_platform(self, platform: str) -> list[str]: + assert platform in _STUBTEST_PLATFORM_MAPPING, f"Unrecognised platform {platform!r}" + ret = getattr(self, _STUBTEST_PLATFORM_MAPPING[platform]) + assert _is_list_of_strings(ret) + return ret + + +@functools.cache +def read_stubtest_settings(distribution: str) -> StubtestSettings: + """Return an object describing the stubtest settings for a single stubs distribution.""" + with metadata_path(distribution).open("rb") as f: + data: dict[str, object] = tomllib.load(f).get("tool", {}).get("stubtest", {}) + + skip: object = data.get("skip", False) + apt_dependencies: object = data.get("apt-dependencies", []) + brew_dependencies: object = data.get("brew-dependencies", []) + choco_dependencies: object = data.get("choco-dependencies", []) + extras: object = data.get("extras", []) + ignore_missing_stub: object = data.get("ignore-missing-stub", False) + supported_platforms: object = data.get("supported-platforms") + ci_platforms: object = data.get("ci-platforms", DEFAULT_STUBTEST_PLATFORMS) + stubtest_dependencies: object = data.get("stubtest-dependencies", []) + mypy_plugins: object = data.get("mypy-plugins", []) + mypy_plugins_config: object = data.get("mypy-plugins-config", {}) + install_environment: object = data.get("install-environment", {}) + + assert type(skip) is bool + assert type(ignore_missing_stub) is bool + + # It doesn't work for type-narrowing if we use a for loop here... + assert supported_platforms is None or _is_list_of_strings(supported_platforms) + assert _is_list_of_strings(ci_platforms) + assert _is_list_of_strings(apt_dependencies) + assert _is_list_of_strings(brew_dependencies) + assert _is_list_of_strings(choco_dependencies) + assert _is_list_of_strings(extras) + assert _is_list_of_strings(stubtest_dependencies) + assert _is_list_of_strings(mypy_plugins) + assert _is_nested_dict(mypy_plugins_config) + assert _is_dict_of_strings(install_environment) + + unrecognised_platforms = set(ci_platforms) - _STUBTEST_PLATFORM_MAPPING.keys() + assert not unrecognised_platforms, f"Unrecognised ci-platforms specified for {distribution!r}: {unrecognised_platforms}" + + if supported_platforms is not None: + assert set(ci_platforms).issubset( + supported_platforms + ), f"ci-platforms must be a subset of supported-platforms for {distribution!r}" + + for platform, dep_key in _STUBTEST_PLATFORM_MAPPING.items(): + if platform not in ci_platforms: + assert dep_key not in data, ( + f"Stubtest is not run on {platform} in CI for {distribution!r}, " + f"but {dep_key!r} are specified in METADATA.toml" + ) + + return StubtestSettings( + skip=skip, + apt_dependencies=apt_dependencies, + brew_dependencies=brew_dependencies, + choco_dependencies=choco_dependencies, + extras=extras, + ignore_missing_stub=ignore_missing_stub, + supported_platforms=supported_platforms, + ci_platforms=ci_platforms, + stubtest_dependencies=stubtest_dependencies, + mypy_plugins=mypy_plugins, + mypy_plugins_config=mypy_plugins_config, + install_environment=install_environment, + ) + + +@final +@dataclass(frozen=True) +class ObsoleteMetadata: + since_version: Annotated[str, "A string representing a specific version"] + since_date: Annotated[datetime.date, "A date when the package became obsolete"] + + +@final +@dataclass(frozen=True) +class StubMetadata: + """The metadata for a single stubs distribution. + + Don't construct instances directly; use the `read_metadata` function. + """ + + distribution: Annotated[str, "The name of the distribution on PyPI"] + version_spec: Annotated[Specifier, "Upstream versions that the stubs are compatible with"] + dependencies: Annotated[list[Requirement], "The parsed dependencies as listed in METADATA.toml"] + optional_dependencies: Annotated[list[Requirement], "The parsed optional dependencies as listed in METADATA.toml"] + extra_description: str | None + stub_distribution: Annotated[str, "The name under which the distribution is uploaded to PyPI"] + upstream_repository: Annotated[str, "The URL of the upstream repository"] | None + obsolete: Annotated[ObsoleteMetadata, "Metadata indicating when the stubs package became obsolete"] | None + no_longer_updated: bool + uploaded_to_pypi: Annotated[bool, "Whether or not a distribution is uploaded to PyPI"] + partial_stub: Annotated[bool, "Whether this is a partial type stub package as per PEP 561."] + stubtest_settings: StubtestSettings + requires_python: Annotated[Specifier, "Versions of Python supported by the stub package"] + + @property + def is_obsolete(self) -> bool: + return self.obsolete is not None + + @property + def all_dependencies(self) -> list[Requirement]: + """The dependencies and optional dependencies of this stubs package. + + Does not include the stubtest dependencies. + """ + return self.dependencies + self.optional_dependencies + + +_KNOWN_METADATA_FIELDS: Final = frozenset( + { + "version", + "dependencies", + "optional-dependencies", + "extra-description", + "stub-distribution", + "upstream-repository", + "obsolete-since", + "no-longer-updated", + "upload", + "tool", + "partial-stub", + "requires-python", + "mypy-tests", + } +) +_KNOWN_METADATA_TOOL_FIELDS: Final = { + "stubtest": { + "skip", + "apt-dependencies", + "brew-dependencies", + "choco-dependencies", + "extras", + "ignore-missing-stub", + "supported-platforms", + "ci-platforms", + "stubtest-dependencies", + "mypy-plugins", + "mypy-plugins-config", + "install-environment", + } +} +_DIST_NAME_RE: Final = re.compile(r"^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$", re.IGNORECASE) + + +class NoSuchStubError(ValueError): + """Raise NoSuchStubError to indicate that a stubs/{distribution} directory doesn't exist.""" + + +@functools.cache +def read_metadata(distribution: str) -> StubMetadata: + """Return an object describing the metadata of a stub as given in the METADATA.toml file. + + This function does some basic validation, + but does no parsing, transforming or normalization of the metadata. + Use `read_dependencies` if you need to parse the dependencies + given in the `dependencies` field, for example. + """ + try: + with metadata_path(distribution).open("rb") as f: + # This cast is necessary for pyright to understand that the + # variable is a dict with object values. Just using + # `data: dict[str, object] = tomlkit.load(f)` doesn't work because + # pyright still infers TOMLDocument which derives from + # dict[Unknown, Unknown]. + data = cast(dict[str, object], tomlkit.load(f)) + except FileNotFoundError: + raise NoSuchStubError(f"Typeshed has no stubs for {distribution!r}!") from None + + unknown_metadata_fields = data.keys() - _KNOWN_METADATA_FIELDS + assert not unknown_metadata_fields, f"Unexpected keys in METADATA.toml for {distribution!r}: {unknown_metadata_fields}" + + assert "version" in data, f"Missing 'version' field in METADATA.toml for {distribution!r}" + version = data.get("version") + assert isinstance(version, str) and len(version) > 0, f"Invalid 'version' field in METADATA.toml for {distribution!r}" + # Check that the version spec parses + if version[0].isdigit(): + version = f"=={version}" + version_spec = Specifier(version) + assert version_spec.operator in {"==", "~="}, f"Invalid 'version' field in METADATA.toml for {distribution!r}" + + dependencies_s = data.get("dependencies", []) + assert isinstance(dependencies_s, list) + dependencies = [parse_dependencies(distribution, dep) for dep in dependencies_s] + + optional_dependencies_s = data.get("optional-dependencies", []) + assert isinstance(optional_dependencies_s, list) + optional_dependencies = [parse_dependencies(distribution, dep) for dep in optional_dependencies_s] + + extra_description = data.get("extra-description") + assert isinstance(extra_description, (str, type(None))) + + if "stub-distribution" in data: + stub_distribution = data["stub-distribution"] + assert isinstance(stub_distribution, str) + assert _DIST_NAME_RE.fullmatch(stub_distribution), f"Invalid 'stub-distribution' value for {distribution!r}" + else: + stub_distribution = f"types-{distribution}" + + upstream_repository = data.get("upstream-repository") + assert isinstance(upstream_repository, (str, type(None))) + if isinstance(upstream_repository, str): + parsed_url = urllib.parse.urlsplit(upstream_repository) + assert parsed_url.scheme == "https", f"{distribution}: URLs in the upstream-repository field should use https" + no_www_please = ( + f"{distribution}: `World Wide Web` subdomain (`www.`) should be removed from URLs in the upstream-repository field" + ) + assert not parsed_url.netloc.startswith("www."), no_www_please + no_query_params_please = ( + f"{distribution}: Query params (`?`) should be removed from URLs in the upstream-repository field" + ) + assert parsed_url.hostname in _QUERY_URL_ALLOWLIST or (not parsed_url.query), no_query_params_please + no_fragments_please = f"{distribution}: Fragments (`#`) should be removed from URLs in the upstream-repository field" + assert not parsed_url.fragment, no_fragments_please + if parsed_url.netloc == "github.com": + cleaned_url_path = parsed_url.path.strip("/") + num_url_path_parts = len(Path(cleaned_url_path).parts) + bad_github_url_msg = ( + f"Invalid upstream-repository for {distribution!r}: " + "URLs for GitHub repositories always have two parts in their paths" + ) + assert num_url_path_parts == 2, bad_github_url_msg + + obsolete_since = data.get("obsolete-since") + assert isinstance(obsolete_since, (dict, type(None))) + if obsolete_since is not None: + obsolete_table: dict[str, object] = obsolete_since + obsolete_since_version = obsolete_table.get("version") + obsolete_since_date = obsolete_table.get("date") + assert isinstance(obsolete_since_version, str) + assert isinstance(obsolete_since_date, str) + since_date = datetime.date.fromisoformat(obsolete_since_date) + obsolete = ObsoleteMetadata(since_version=obsolete_since_version, since_date=since_date) + else: + obsolete = None + no_longer_updated = data.get("no-longer-updated", False) + assert type(no_longer_updated) is bool + uploaded_to_pypi = data.get("upload", True) + assert type(uploaded_to_pypi) is bool + partial_stub = data.get("partial-stub", True) + assert type(partial_stub) is bool + requires_python_str = data.get("requires-python") + oldest_supported_python = get_oldest_supported_python() + oldest_supported_python_specifier = Specifier(f">={oldest_supported_python}") + if requires_python_str is None: + requires_python = oldest_supported_python_specifier + else: + assert isinstance(requires_python_str, str) + requires_python = Specifier(requires_python_str) + assert requires_python != oldest_supported_python_specifier, f'requires-python="{requires_python}" is redundant' + # Check minimum Python version is not less than the oldest version of Python supported by typeshed + assert oldest_supported_python_specifier.contains( + requires_python.version + ), f"'requires-python' contains versions lower than typeshed's oldest supported Python ({oldest_supported_python})" + assert requires_python.operator == ">=", "'requires-python' should be a minimum version specifier, use '>=3.x'" + + empty_tools: dict[object, object] = {} + tools_settings = data.get("tool", empty_tools) + assert isinstance(tools_settings, dict) + assert tools_settings.keys() <= _KNOWN_METADATA_TOOL_FIELDS.keys(), f"Unrecognised tool for {distribution!r}" + for tool, tk in _KNOWN_METADATA_TOOL_FIELDS.items(): + settings_for_tool = cast(dict[str, object], tools_settings).get(tool, {}) + assert isinstance(settings_for_tool, dict) + for key in settings_for_tool: + assert key in tk, f"Unrecognised {tool} key {key!r} for {distribution!r}" + + return StubMetadata( + distribution=distribution, + version_spec=version_spec, + dependencies=dependencies, + optional_dependencies=optional_dependencies, + extra_description=extra_description, + stub_distribution=stub_distribution, + upstream_repository=upstream_repository, + obsolete=obsolete, + no_longer_updated=no_longer_updated, + uploaded_to_pypi=uploaded_to_pypi, + partial_stub=partial_stub, + stubtest_settings=read_stubtest_settings(distribution), + requires_python=requires_python, + ) + + +def update_metadata(distribution: str, **new_values: object) -> dict[str, object]: + """Update a distribution's METADATA.toml. + + Return the updated TOML dictionary for use without having to open the file separately. + """ + path = metadata_path(distribution) + try: + with path.open("rb") as f: + # This cast is necessary for pyright to understand that the + # variable is a dict with object values. Just using + # `data: dict[str, object] = tomlkit.load(f)` doesn't work because + # pyright still infers TOMLDocument which derives from + # dict[Unknown, Unknown]. + data = cast(dict[str, object], tomlkit.load(f)) + except FileNotFoundError: + raise NoSuchStubError(f"Typeshed has no stubs for {distribution!r}!") from None + data.update(new_values) + for key in list(data.keys()): + new_key = key.replace("_", "-") + data[new_key] = data.pop(key) + with path.open("w", encoding="UTF-8") as f: + tomlkit.dump(data, f) + return data + + +def parse_dependencies(distribution: str, req: object) -> Requirement: + assert isinstance(req, str), f"Invalid requirement {req!r} for {distribution!r}" + return Requirement(req) + + +class PackageDependencies(NamedTuple): + typeshed_pkgs: tuple[Requirement, ...] + external_pkgs: tuple[Requirement, ...] + + +@functools.cache +def get_pypi_name_to_typeshed_name_mapping() -> Mapping[str, str]: + return {read_metadata(stub_dir.name).stub_distribution: stub_dir.name for stub_dir in STUBS_PATH.iterdir()} + + +@functools.cache +def read_dependencies(distribution: str) -> PackageDependencies: + """Read the dependencies listed in a METADATA.toml file for a stubs package. + + Once the dependencies have been read, + determine which dependencies are typeshed-internal dependencies, + and which dependencies are external (non-types) dependencies. + For typeshed dependencies, translate the "dependency name" into the "package name"; + for external dependencies, leave them as they are in the METADATA.toml file. + + Note that this function may consider things to be typeshed stubs + even if they haven't yet been uploaded to PyPI. + If a typeshed stub is removed, this function will consider it to be an external dependency. + """ + pypi_name_to_typeshed_name_mapping = get_pypi_name_to_typeshed_name_mapping() + typeshed: list[Requirement] = [] + external: list[Requirement] = [] + for dependency in read_metadata(distribution).all_dependencies: + if dependency.name in pypi_name_to_typeshed_name_mapping: + req = Requirement(str(dependency)) # copy the requirement + req.name = pypi_name_to_typeshed_name_mapping[dependency.name] + typeshed.append(req) + else: + external.append(dependency) + return PackageDependencies(tuple(typeshed), tuple(external)) + + +@functools.cache +def get_recursive_requirements(package_name: str) -> PackageDependencies: + """Recursively gather dependencies for a single stubs package. + + For example, if the stubs for `caldav` + declare a dependency on typeshed's stubs for `requests`, + and the stubs for requests declare a dependency on typeshed's stubs for `urllib3`, + `get_recursive_requirements("caldav")` will determine that the stubs for `caldav` + have both `requests` and `urllib3` as typeshed-internal dependencies. + """ + typeshed: set[Requirement] = set() + external: set[Requirement] = set() + non_recursive_requirements = read_dependencies(package_name) + typeshed.update(non_recursive_requirements.typeshed_pkgs) + external.update(non_recursive_requirements.external_pkgs) + for pkg in non_recursive_requirements.typeshed_pkgs: + reqs = get_recursive_requirements(pkg.name) + typeshed.update(reqs.typeshed_pkgs) + external.update(reqs.external_pkgs) + return PackageDependencies(tuple(typeshed), tuple(external)) diff --git a/lib/ts_utils/mypy.py b/lib/ts_utils/mypy.py new file mode 100644 index 000000000000..17cba6978061 --- /dev/null +++ b/lib/ts_utils/mypy.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import sys +from collections.abc import Generator, Iterable +from contextlib import contextmanager +from typing import Any, NamedTuple + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +from ts_utils.metadata import StubtestSettings, metadata_path +from ts_utils.utils import NamedTemporaryFile, TemporaryFileWrapper + + +class MypyDistConf(NamedTuple): + module_name: str + values: dict[str, dict[str, Any]] + + +# The configuration section in the metadata file looks like the following, with multiple module sections possible +# [mypy-tests] +# [mypy-tests.yaml] +# module-name = "yaml" +# [mypy-tests.yaml.values] +# disallow_incomplete_defs = true +# disallow_untyped_defs = true + + +def mypy_configuration_from_distribution(distribution: str) -> list[MypyDistConf]: + with metadata_path(distribution).open("rb") as f: + data = tomllib.load(f) + + # TODO: This could be added to ts_utils.metadata + mypy_tests_conf: dict[str, dict[str, Any]] = data.get("mypy-tests", {}) + if not mypy_tests_conf: + return [] + + def validate_configuration(section_name: str, mypy_section: dict[str, Any]) -> MypyDistConf: + assert isinstance(mypy_section, dict), f"{section_name} should be a section" + module_name = mypy_section.get("module-name") + + assert module_name is not None, f"{section_name} should have a module-name key" + assert isinstance(module_name, str), f"{section_name} should be a key-value pair" + + assert "values" in mypy_section, f"{section_name} should have a values section" + values: dict[str, dict[str, Any]] = mypy_section["values"] + assert isinstance(values, dict), "values should be a section" + return MypyDistConf(module_name, values.copy()) + + assert isinstance(mypy_tests_conf, dict), "mypy-tests should be a section" + return [validate_configuration(section_name, mypy_section) for section_name, mypy_section in mypy_tests_conf.items()] + + +@contextmanager +def temporary_mypy_config_file( + configurations: Iterable[MypyDistConf], stubtest_settings: StubtestSettings | None = None +) -> Generator[TemporaryFileWrapper[str]]: + temp = NamedTemporaryFile("w+") + try: + for dist_conf in configurations: + temp.write(f"[mypy-{dist_conf.module_name}]\n") + for k, v in dist_conf.values.items(): + temp.write(f"{k} = {v}\n") + temp.write("[mypy]\n") + + if stubtest_settings: + if stubtest_settings.mypy_plugins: + temp.write(f"plugins = {'.'.join(stubtest_settings.mypy_plugins)}\n") + + if stubtest_settings.mypy_plugins_config: + for plugin_name, plugin_dict in stubtest_settings.mypy_plugins_config.items(): + temp.write(f"[mypy.plugins.{plugin_name}]\n") + for k, v in plugin_dict.items(): + temp.write(f"{k} = {v}\n") + + temp.flush() + yield temp + finally: + temp.close() diff --git a/lib/ts_utils/paths.py b/lib/ts_utils/paths.py new file mode 100644 index 000000000000..3a9a65e32181 --- /dev/null +++ b/lib/ts_utils/paths.py @@ -0,0 +1,41 @@ +from pathlib import Path +from typing import Final + +# TODO: Use base path relative to this file. Currently, ts_utils gets +# installed into the user's virtual env, so we can't determine the path +# to typeshed. Installing ts_utils editable would solve that, see +# https://github.com/python/typeshed/pull/12806. +TS_BASE_PATH: Final = Path() +STDLIB_PATH: Final = TS_BASE_PATH / "stdlib" +STUBS_PATH: Final = TS_BASE_PATH / "stubs" + +PYPROJECT_PATH: Final = TS_BASE_PATH / "pyproject.toml" +REQUIREMENTS_PATH: Final = TS_BASE_PATH / "requirements-tests.txt" +GITIGNORE_PATH: Final = TS_BASE_PATH / ".gitignore" +PYRIGHT_CONFIG: Final = TS_BASE_PATH / "pyrightconfig.stricter.json" + +TESTS_DIR: Final = "@tests" +TEST_CASES_DIR: Final = "test_cases" + + +def distribution_path(distribution_name: str) -> Path: + """Return the path to the directory of a third-party distribution.""" + return STUBS_PATH / distribution_name + + +def tests_path(distribution_name: str) -> Path: + if distribution_name == "stdlib": + return STDLIB_PATH / TESTS_DIR + else: + return STUBS_PATH / distribution_name / TESTS_DIR + + +def test_cases_path(distribution_name: str) -> Path: + return tests_path(distribution_name) / TEST_CASES_DIR + + +def allowlists_path(distribution_name: str) -> Path: + if distribution_name == "stdlib": + return tests_path("stdlib") / "stubtest_allowlists" + else: + return tests_path(distribution_name) diff --git a/stdlib/@python2/antigravity.pyi b/lib/ts_utils/py.typed similarity index 100% rename from stdlib/@python2/antigravity.pyi rename to lib/ts_utils/py.typed diff --git a/lib/ts_utils/py315.py b/lib/ts_utils/py315.py new file mode 100644 index 000000000000..91eacc100c11 --- /dev/null +++ b/lib/ts_utils/py315.py @@ -0,0 +1,18 @@ +"""Helpers for Python 3.15 test infrastructure.""" + +# These stubs require runtime dependencies that do not install cleanly on Python 3.15 yet. +PY315_INCOMPATIBLE_RUNTIME_DEPENDENCIES = { + # Depend on numpy, which does not provide Python 3.15 wheels yet. + "JACK-Client", + "geopandas", + "hnswlib", + "networkx", + "pycocotools", + "pyogrio", + "resampy", + "shapely", + "tensorflow", + # Depends on matplotlib, which depends on contourpy. contourpy does not + # provide Python 3.15 wheels yet. + "seaborn", +} diff --git a/lib/ts_utils/requirements.py b/lib/ts_utils/requirements.py new file mode 100644 index 000000000000..e592bd73ad54 --- /dev/null +++ b/lib/ts_utils/requirements.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import itertools +import os +import sys +from collections.abc import Iterable + +from packaging.requirements import Requirement + +from ts_utils.metadata import read_dependencies, read_stubtest_settings +from ts_utils.paths import STUBS_PATH + + +def get_external_stub_requirements(distributions: Iterable[str] = ()) -> set[Requirement]: + if not distributions: + distributions = os.listdir(STUBS_PATH) + + return set(itertools.chain.from_iterable([read_dependencies(distribution).external_pkgs for distribution in distributions])) + + +def get_stubtest_system_requirements(distributions: Iterable[str] = (), platform: str = sys.platform) -> set[str]: + if not distributions: + distributions = os.listdir(STUBS_PATH) + + return set( + itertools.chain.from_iterable( + [read_stubtest_settings(distribution).system_requirements_for_platform(platform) for distribution in distributions] + ) + ) diff --git a/lib/ts_utils/stubs.py b/lib/ts_utils/stubs.py new file mode 100644 index 000000000000..ae09ae27c554 --- /dev/null +++ b/lib/ts_utils/stubs.py @@ -0,0 +1,80 @@ +"""Stub file discovery.""" + +from functools import cached_property +from pathlib import Path + +from ts_utils.paths import STDLIB_PATH, STUBS_PATH, TESTS_DIR, distribution_path +from ts_utils.utils import parse_stdlib_versions_file + + +class StubFile: + """Base class for stub files.""" + + def __init__(self, path: Path) -> None: + self.path = path + + def __fspath__(self) -> str: + return self.path.__fspath__() + + def __str__(self) -> str: + return str(self.path) + + @cached_property + def module_name(self) -> str: + return ".".join(self.module_parts) + + @cached_property + def module_parts(self) -> tuple[str, ...]: + raise NotImplementedError + + +class StdlibStubFile(StubFile): + """A stdlib stub file.""" + + @cached_property + def module_parts(self) -> tuple[str, ...]: + relative = self.path.relative_to(STDLIB_PATH) + parts = list(relative.parts[:-1]) + if relative.name != "__init__.pyi": + parts.append(relative.stem) + return tuple(parts) + + +class ThirdPartyStubFile(StubFile): + """A third-party stub file.""" + + @cached_property + def upstream_distribution(self) -> str: + return self.path.relative_to(STUBS_PATH).parts[0] + + @cached_property + def module_parts(self) -> tuple[str, ...]: + relative = self.path.relative_to(STUBS_PATH) + parts = list(relative.parts[1:-1]) + if relative.name != "__init__.pyi": + parts.append(relative.stem) + return tuple(parts) + + +def stdlib_stubs(version: str) -> list[StdlibStubFile]: + """Return the stdlib stubs available for the requested Python version.""" + module_versions = parse_stdlib_versions_file() + stubs = (StdlibStubFile(path) for path in path_stubs(STDLIB_PATH)) + return [stub for stub in stubs if module_versions.is_supported(stub.module_name, version)] + + +def third_party_stubs(distribution: str | None = None) -> list[ThirdPartyStubFile]: + """Return third-party stubs. + + If distribution is None, return all third-party stubs. Otherwise, + return only stubs for the given distribution. + """ + stub_path = distribution_path(distribution) if distribution else STUBS_PATH + return [ThirdPartyStubFile(path) for path in path_stubs(stub_path)] + + +def path_stubs(path: Path) -> list[Path]: + """Return paths to all stub files in a certain path.""" + if path.is_file(): + return [path] if path.suffix == ".pyi" and TESTS_DIR not in path.parts else [] + return sorted(p for p in path.rglob("*.pyi") if TESTS_DIR not in p.parts) diff --git a/lib/ts_utils/utils.py b/lib/ts_utils/utils.py new file mode 100644 index 000000000000..a91694909e9f --- /dev/null +++ b/lib/ts_utils/utils.py @@ -0,0 +1,306 @@ +"""Utilities that are imported by multiple scripts in the tests directory.""" + +from __future__ import annotations + +import functools +import re +import sys +import tempfile +from collections.abc import Iterable, Mapping +from pathlib import Path +from types import MethodType +from typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, TypeAlias + +import pathspec +from packaging.requirements import Requirement + +from .paths import GITIGNORE_PATH, REQUIREMENTS_PATH, STDLIB_PATH, STUBS_PATH, TEST_CASES_DIR, allowlists_path, test_cases_path + +if TYPE_CHECKING: + from _typeshed import OpenTextMode + +try: + from termcolor import colored as colored # pyright: ignore[reportAssignmentType] +except ImportError: + + def colored(text: str, color: str | None = None, **kwargs: Any) -> str: # type: ignore[misc] # ruff: ignore[unused-function-argument] + return text + + +TextColor: TypeAlias = Literal[ + "black", + "red", + "green", + "yellow", + "blue", + "magenta", + "cyan", + "white", + "light_grey", + "dark_grey", + "light_red", + "light_green", + "light_yellow", + "light_blue", + "light_magenta", + "light_cyan", +] + + +_REMOVE_COMMENT_RE = re.compile( + r""" + (\"(?:\\.|[^\\\"])*?\") # matches literal strings + | + (\/\*.*?\*\/ | \/\/[^\r\n]*?(?:[\r\n])) # matches single- and multi-line comments + """, + re.DOTALL | re.VERBOSE, +) +_REMOVE_TRAILING_COMMA_RE = re.compile( + r""" + (\"(?:\\.|[^\\\"])*?\") # matches literal strings + | + ,\s*([\]}]) # matches commas before '}' or ']' + """, + re.DOTALL | re.VERBOSE, +) + + +PYTHON_VERSION: Final = f"{sys.version_info.major}.{sys.version_info.minor}" + + +def strip_comments(text: str) -> str: + return text.split("#", maxsplit=1)[0].strip() + + +def jsonc_to_json(text: str) -> str: + """Conversion from JSONC format input to valid JSON.""" + # Remove comments + if not text.endswith("\n"): + text += "\n" + text = _REMOVE_COMMENT_RE.sub(lambda m: m.group(1) or "", text) + + # Remove trailing commas before } or ] + text = _REMOVE_TRAILING_COMMA_RE.sub(lambda m: m.group(1) or m.group(2), text) + return text + + +# ==================================================================== +# Printing utilities +# ==================================================================== + + +def print_command(cmd: str | Iterable[str]) -> None: + if not isinstance(cmd, str): + cmd = " ".join(cmd) + print(colored(f"Running: {cmd}", "blue")) + + +def print_skipped(message: str) -> None: + print(colored(message, "yellow")) + + +def print_error(error: str, end: str = "\n", fix_path: tuple[str, str] = ("", "")) -> None: + error_split = error.split("\n") + old, new = fix_path + for line in error_split[:-1]: + print(colored(line.replace(old, new), "red")) + print(colored(error_split[-1], "red"), end=end) + + +def print_success_msg() -> None: + print(colored("success", "green")) + + +def format_time(t: float) -> str: + return f"({t:.2f} s)" + + +# ==================================================================== +# Dynamic venv creation +# ==================================================================== + + +@functools.cache +def venv_python(venv_dir: Path) -> Path: + if sys.platform == "win32": + return venv_dir / "Scripts" / "python.exe" + return venv_dir / "bin" / "python" + + +# ==================================================================== +# Parsing the requirements file +# ==================================================================== + + +@functools.cache +def parse_requirements() -> Mapping[str, Requirement]: + """Return a dictionary of requirements from the requirements file.""" + with REQUIREMENTS_PATH.open(encoding="UTF-8") as requirements_file: + stripped_lines = map(strip_comments, requirements_file) + stripped_more = [li for li in stripped_lines if not li.startswith("-")] + requirements = map(Requirement, filter(None, stripped_more)) + return {requirement.name: requirement for requirement in requirements} + + +def get_mypy_req() -> str: + return str(parse_requirements()["mypy"]) + + +# ==================================================================== +# Parsing the stdlib/VERSIONS file +# ==================================================================== + +VersionTuple: TypeAlias = tuple[int, int] + +VERSIONS_PATH = STDLIB_PATH / "VERSIONS" +VERSION_LINE_RE = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_.]*): ([23]\.\d{1,2})-([23]\.\d{1,2})?$") +VERSION_RE = re.compile(r"^([23])\.(\d+)$") + + +class SupportedVersions: + def __init__(self, module_versions: dict[str, tuple[VersionTuple, VersionTuple]]) -> None: + self.module_versions = module_versions + + def supported_versions_for_module(self, module_name: str) -> tuple[VersionTuple, VersionTuple]: + while "." in module_name: + if module_name in self.module_versions: + return self.module_versions[module_name] + module_name = ".".join(module_name.split(".")[:-1]) + return self.module_versions[module_name] + + def is_supported(self, module_name: str, version: str) -> bool: + version_tuple = tuple(map(int, version.split("."))) + minimum, maximum = self.supported_versions_for_module(module_name) + return minimum <= version_tuple <= maximum + + +def parse_stdlib_versions_file() -> SupportedVersions: + result: dict[str, tuple[VersionTuple, VersionTuple]] = {} + with VERSIONS_PATH.open(encoding="UTF-8") as f: + for line in f: + stripped_line = strip_comments(line) + if not stripped_line: + continue + m = VERSION_LINE_RE.match(stripped_line) + assert m, f"invalid VERSIONS line: {stripped_line}" + mod: str = m.group(1) + assert mod not in result, f"Duplicate module {mod} in VERSIONS" + min_version = _parse_version(m.group(2)) + max_version = _parse_version(m.group(3)) if m.group(3) else (99, 99) + result[mod] = min_version, max_version + return SupportedVersions(result) + + +def _parse_version(v_str: str) -> tuple[int, int]: + m = VERSION_RE.match(v_str) + assert m, f"invalid version: {v_str}" + return int(m.group(1)), int(m.group(2)) + + +# ==================================================================== +# Test Directories +# ==================================================================== + + +class DistributionTests(NamedTuple): + name: str + test_cases_path: Path + + @property + def is_stdlib(self) -> bool: + return self.name == "stdlib" + + +def distribution_info(distribution_name: str) -> DistributionTests: + if distribution_name == "stdlib": + return DistributionTests("stdlib", test_cases_path("stdlib")) + test_path = test_cases_path(distribution_name) + if test_path.is_dir(): + if not list(test_path.iterdir()): + raise RuntimeError(f"{distribution_name!r} has a '{TEST_CASES_DIR}' directory but it is empty!") + return DistributionTests(distribution_name, test_path) + raise RuntimeError(f"No test cases found for {distribution_name!r}!") + + +def get_all_testcase_directories() -> list[DistributionTests]: + testcase_directories: list[DistributionTests] = [] + for distribution_path in STUBS_PATH.iterdir(): + try: + pkg_info = distribution_info(distribution_path.name) + except RuntimeError: + continue + testcase_directories.append(pkg_info) + return [distribution_info("stdlib"), *sorted(testcase_directories)] + + +def allowlists(distribution_name: str) -> list[str]: + prefix = "" if distribution_name == "stdlib" else "stubtest_allowlist_" + version_id = f"py{sys.version_info.major}{sys.version_info.minor}" + + platform_allowlist = f"{prefix}{sys.platform}.txt" + version_allowlist = f"{prefix}{version_id}.txt" + combined_allowlist = f"{prefix}{sys.platform}-{version_id}.txt" + local_version_allowlist = version_allowlist + ".local" + + if distribution_name == "stdlib": + return ["common.txt", platform_allowlist, version_allowlist, combined_allowlist, local_version_allowlist] + else: + return ["stubtest_allowlist.txt", platform_allowlist] + + +# Re-exposing as a public name to avoid many pyright reportPrivateUsage +TemporaryFileWrapper = tempfile._TemporaryFileWrapper # pyright: ignore[reportPrivateUsage] + +# We need to work around a limitation of tempfile.NamedTemporaryFile on Windows +# For details, see https://github.com/python/typeshed/pull/13620#discussion_r1990185997 +# Python 3.12 added a cross-platform solution with `tempfile.NamedTemporaryFile("w+", delete_on_close=False)` +if sys.platform != "win32": + # We ignore the Ruff error here because this defines the helper that callers should use + # instead of `tempfile.NamedTemporaryFile`, which is banned by `banned-api`. + # + NamedTemporaryFile = tempfile.NamedTemporaryFile # ruff: ignore[banned-api] +else: + + def NamedTemporaryFile(mode: OpenTextMode) -> TemporaryFileWrapper[str]: # ruff: ignore[invalid-function-name] + def close(self: TemporaryFileWrapper[str]) -> None: + TemporaryFileWrapper.close(self) # pyright: ignore[reportUnknownMemberType] + Path(self.name).unlink() + + # We ignore the `banned-api` Ruff error here because this call is part of the helper that callers should use + # instead of `tempfile.NamedTemporaryFile`. + # + temp = tempfile.NamedTemporaryFile(mode, delete=False) # ruff: ignore[open-file-with-context-handler, banned-api] + temp.close = MethodType(close, temp) # type: ignore[method-assign] + return temp + + +# ==================================================================== +# Parsing .gitignore +# ==================================================================== + + +@functools.cache +def get_gitignore_spec() -> pathspec.GitIgnoreSpec: + with GITIGNORE_PATH.open(encoding="UTF-8") as f: + return pathspec.GitIgnoreSpec.from_lines(f) + + +def spec_matches_path(spec: pathspec.PathSpec[Any], path: Path) -> bool: + normalized_path = path.as_posix() + if path.is_dir(): + normalized_path += "/" + return spec.match_file(normalized_path) + + +# ==================================================================== +# stubtest call +# ==================================================================== + + +def allowlist_stubtest_arguments(distribution_name: str) -> list[str]: + stubtest_arguments: list[str] = [] + for allowlist in allowlists(distribution_name): + path = allowlists_path(distribution_name) / allowlist + if path.exists(): + stubtest_arguments.extend(["--allowlist", str(path)]) + return stubtest_arguments diff --git a/pyproject.toml b/pyproject.toml index a8e04873aa3d..e832d3f1f711 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,48 +1,288 @@ +[project] +# This section is needed to avoid writing --no-project everytime when using "uv run" +# https://github.com/astral-sh/uv/issues/8666 +name = "typeshed" +version = "0" +requires-python = ">=3.10" # Minimum version to run tests, used by uv run + [tool.black] -line_length = 130 -target_version = ["py37"] -force-exclude = ".*_pb2.pyi" -skip_magic_trailing_comma = true - -[tool.isort] -profile = "black" -combine_as_imports = true -line_length = 130 -skip_glob = "*_pb2.pyi" -extra_standard_library = [ - "typing_extensions", +line-length = 130 +target-version = ["py310"] +skip-magic-trailing-comma = true +preview = true + +# Override `exclude` so that the `stdlib/venv` directory is not excluded +# if you invoke Black "manually" (not using pre-commit). `venv` is one of +# the directories that Black excludes by default if `tool.black.exclude` +# is not set. See https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#exclude +exclude = ''' +/( + \.env| + \.venv| + env| + \.git| + \.mypy_cache +)/ +''' + +[tool.ruff] +line-length = 130 +fix = true + +# Override `exclude` so that the `stdlib/venv` directory is not excluded +# if you invoke Ruff "manually" (not using pre-commit). `venv` is one of +# the directories that Ruff excludes by default if `tool.ruff.exclude` +# is not set. See https://docs.astral.sh/ruff/configuration/ +exclude = [ + # virtual environment + ".env", + ".venv", + "env", + # cache directories, etc.: + ".git", + ".mypy_cache", +] + +[tool.ruff.lint] +future-annotations = true +preview = true +# Disable all rules on test cases by default: +# test cases often deliberately contain code +# that might not be considered idiomatic or modern. +# +# Note: some rules that are specifically useful to the test cases +# are invoked via separate runs of ruff in pre-commit: +# see our .pre-commit-config.yaml file for details +exclude = ["**/test_cases/**/*.py"] +# We still use flake8-pyi to check these (see .flake8 config file); +# tell ruff not to flag these as e.g. "unused noqa comments" +external = ["F821", "Y"] +select = [ + "A", # flake8-builtins + "ARG", # flake8-unused-arguments + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "D", # pydocstyle + "DTZ", # flake8-datetimez + "EXE", # flake8-executable + "FA", # flake8-future-annotations + "FBT", # flake8-boolean-trap + "FLY", # flynt + "I", # isort + "N", # pep8-naming + "PGH", # pygrep-hooks + "PIE", # flake8-pie + "PL", # Pylint + "PTH", # flake8-use-pathlib + "RSE", # flake8-raise + "RUF", # Ruff-specific and unused-noqa + "SLOT", # flake8-slots + "T10", # flake8-debugger + "TD", # flake8-todos + "TRY", # tryceratops + "UP", # pyupgrade + "YTT", # flake8-2020 + # Flake8 base rules + "E", # pycodestyle Error + "F", # Pyflakes + "W", # pycodestyle Warning + # Only include flake8-annotations rules that are autofixable. Otherwise leave this to mypy+pyright + "ANN2", + # Most refurb rules are in preview and can be opinionated, + # consider them individually as they come out of preview (last check: 0.13.1) + "print-empty-string", # Unnecessary empty string passed to `print` + "f-string-number-format", # Replace `{function_name}` call with `{display}` + "for-loop-writes", # Use of `{}.write` in a for loop + "readlines-in-for", # Instead of calling `readlines()`, iterate over file object directly + "check-and-remove-from-set", # Use `{suggestion}` instead of `check` and `remove` + "if-expr-min-max", # Replace `if` expression with `{min_max}` call + "verbose-decimal-constructor", # Verbose expression in `Decimal` constructor + "fromisoformat-replace-z", # Unnecessary timezone replacement with zero offset + "int-on-sliced-str", # Use of `int` with explicit `base={base}` after removing prefix + "regex-flag-alias", # Use of regular expression alias `re.{}` + "isinstance-type-none", # Prefer `is` operator over `isinstance` to check if an object is `None` + "type-none-comparison", # Compare the identities of `{object}` and None instead of their respective types + "implicit-cwd", # Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups + "list-reverse-copy", # Use of assignment of `reversed` on list `{name}` + "slice-to-remove-prefix-or-suffix", # Prefer `str.removeprefix()` over conditionally replacing with slice. + # Used for lint.flake8-import-conventions.aliases + "unconventional-import-alias", # `{name}` should be imported as `{asname}` + # PYI: only enable rules that have autofixes and that we always want to fix (even manually), + # avoids duplicate # noqa with flake8-pyi + "pass-statement-stub-body", # Empty body should contain `...`, not pass + "non-empty-stub-body", # Function body must contain only `...` + "pass-in-class-body", # Class bodies must not contain `pass` + "ellipsis-in-non-empty-class-body", # Non-empty class bodies must not contain `...` + "argument-default-in-stub", # Only simple default values allowed for arguments + "assignment-default-in-stub", # Only simple default values allowed for assignments + "duplicate-union-member", + "unused-private-type-var", # Private `{type_var_like_kind}` `{type_var_like_name}` is never used + "custom-type-var-for-self", # Methods like `{method_name}` should return `Self` instead of a custom `TypeVar` + "quoted-annotation-in-stub", # Quoted annotations should not be included in stubs + "unaliased-collections-abc-set-import", # Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin + # "PYI026", Waiting for this mypy bug to be fixed: https://github.com/python/mypy/issues/16581 + "unnecessary-literal-union", # Multiple literal members in a union. Use a single literal, e.g. `Literal[{}]` + "any-eq-ne-annotation", # Prefer `object` to `Any` for the second parameter to `{method_name}` + "bad-exit-annotation", # Star-args in `{method_name}` should be annotated with `object` + "future-annotations-in-stub", # `from __future__ import annotations` has no effect in stub files, since type checkers automatically treat stubs as having those semantics + "unnecessary-type-union", # Multiple `type[T]` usages in a union. Combine them into one, e.g., `type[{union_str}]`. + "generator-return-from-iter-method", # Use `{return_type}` as the return value for simple `{method}` methods + "generic-not-last-base-class", # Checks for classes inheriting from typing.Generic[] where Generic[] is not the last base class in the bases tuple + "redundant-none-literal", # Use `None` rather than `Literal[None]` + "duplicate-literal-member", # Duplicate literal member `{}` + "redundant-final-literal", # `Final[Literal[{literal}]]` can be replaced with a bare Final + # flake8-simplify, excluding rules that can reduce performance or readability due to long line formatting + "duplicate-isinstance-call", # Multiple `isinstance` calls for `{name}`, merge into a single call + "needless-bool", # Return the condition `{condition}` directly + "return-in-try-except-finally", # Don't use return in `try-except` and `finally` + "compare-with-tuple", # Use `{replacement}` instead of multiple equality comparisons + "uncapitalized-environment-variables", # Use capitalized environment variable `{expected}` instead of `{actual}` + "enumerate-for-loop", # Use `enumerate()` for index variable `{index}` in `for` loop + "if-with-same-arms", # Combine `if` branches using logical `or` operator + "open-file-with-context-handler", # Use a context manager for opening files + "in-dict-keys", # Use key `{operator}` dict instead of key `{operator} dict.keys()` + "negate-equal-op", # Use `{left} != {right}` instead of not `{left} == {right}` + "negate-not-equal-op", # Use `{left} == {right}` instead of not `{left} != {right}` + "double-negation", # Use `{expr}` instead of `not (not {expr})` + "if-expr-with-true-false", # Remove unnecessary `True if ... else False` + "if-expr-with-false-true", # Use `not ...` instead of `False if ... else True` + "if-expr-with-twisted-arms", # Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not {expr_else} else {expr_else}` + "expr-and-not-expr", # Use `False` instead of `{name} and not {name}` + "expr-or-not-expr", # Use `True` instead of `{name} or not {name}` + "expr-or-true", + "expr-and-false", + "yoda-conditions", + "if-else-block-instead-of-dict-get", + "split-static-string", # Consider using a list literal instead of `str.{}` + "dict-get-with-none-default", + "zip-dict-keys-and-values", + # Don't include TC rules that create a TYPE_CHECKING block or stringifies annotations + "runtime-import-in-type-checking-block", # Move import `{qualified_name}` out of type-checking block. Import is used for more than type hinting. + "empty-type-checking-block", + "quoted-type-alias", + "runtime-string-union", # Invalid string member in `X | Y`-style union type + # Used for lint.flake8-import-conventions.aliases + "banned-api", +] +extend-safe-fixes = [ + "outdated-version-block", # Remove unnecessary `sys.version_info` blocks +] +ignore = [ + ### + # Rules that can conflict with the formatter (Black) + # https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules + ### + "indentation-with-invalid-multiple", + "indentation-with-invalid-multiple-comment", + "over-indented", + "tab-indentation", + ### + # Rules we don't want or don't agree with + ### + # We're not a library, no need to document everything + "D1", # Missing docstring in ... + # Sometimes, an extra blank line is more readable + "blank-line-after-function", # No blank lines allowed after function docstring + # Doesn't support split "summary line" + "missing-blank-line-after-summary", # 1 blank line required between summary line and description + # Used for direct, non-subclass type comparison, for example: `type(val) is str` + # see https://github.com/astral-sh/ruff/issues/6465 + "type-comparison", # Do not compare types, use `isinstance()` + # Highly opinionated, and it's often necessary to violate it + "import-outside-top-level", # `import` should be at the top-level of a file + # Leave the size and complexity of tests to human interpretation + "PLR09", # Too many ... + # Too many magic number "2" that are preferable inline. https://github.com/astral-sh/ruff/issues/10009 + "magic-value-comparison", # Magic value used in comparison, consider replacing `{value}` with a constant variable + # Keep codeflow path separation explicit + "collapsible-else-if", # Use `elif` instead of `else` then `if`, to reduce indentation + # Often just leads to redundant more verbose code when needing an actual str + "os-listdir", # Use `pathlib.Path.iterdir()` instead. + # Allow FIXME + "invalid-todo-tag", # Invalid TODO tag: `{tag}` + # Git blame is sufficient + "missing-todo-author", # Missing author in TODO; + "missing-todo-link", # Missing issue link for this TODO + # Mostly from scripts and tests, it's ok to have messages passed directly to exceptions + "raise-vanilla-args", # Avoid specifying long messages outside the exception class + # Stubs need private imports to describe runtime APIs; our scripts also import local private modules such as `_utils`. + "import-private-name", + ### + # False-positives, but already checked by type-checkers + ### + # Ruff doesn't support multi-file analysis yet: https://github.com/astral-sh/ruff/issues/5295 + "implicit-optional", # PEP 484 prohibits implicit `Optional` +] + +[tool.ruff.lint.per-file-ignores] +"*.pyi" = [ + # A lot of stubs are incomplete on purpose, and that's configured through pyright + # Some ANN204 (special method) are autofixable in stubs, but not all. + "ANN2", # Missing return type annotation for ... + # Ruff 0.8.0 added sorting of __all__ and __slots_. + # There is no consensus on whether we want to apply this to stubs, so keeping the status quo. + # See https://github.com/python/typeshed/pull/13108 + "unsorted-dunder-all", + "unsorted-dunder-slots", + ### + # Rules that are out of the control of stub authors: + ### + # Names in stubs should match the implementation, even if it's ambiguous. + # https://github.com/astral-sh/ruff/issues/15293 + "A", # flake8-builtins + # Stubs can sometimes re-export entire modules. + # Issues with using a star-imported name will be caught by type-checkers. + "undefined-local-with-import-star", # `from . import *` used; unable to detect undefined names + "undefined-local-with-import-star-usage", # may be undefined, or defined from star imports + # Most pep8-naming rules don't apply for third-party stubs like typeshed. + # N811 to N814 could apply, but we often use them to disambiguate a name whilst making it look like a more common one + "N8", # pep8-naming + # Sometimes __slots__ really is a string at runtime + "single-string-slots", # Class `__slots__` should be a non-string iterable + # Names in stubs should match implementation + "bad-staticmethod-argument", # First argument of a static method should not be named `{argument_name}` + # Runtime classes may redefine inherited slots, which their stubs need to preserve. + "redefined-slots-in-subclass", + # String literals in stubs must sometimes match runtime values containing confusable Unicode. + "ambiguous-unicode-character-string", +] +"lib/ts_utils/**" = [ + # Doesn't affect stubs. The only re-exports we have should be in our local lib ts_utils + "useless-import-alias", # Import alias does not rename original package +] +"*_pb2.pyi" = [ + # Special autogenerated typing --> typing_extensions aliases + "unconventional-import-alias", # `{name}` should be imported as `{asname}` + # Leave the docstrings as-is, matching source + "D", # pydocstyle + # See comment on black's force-exclude config above + "line-too-long", + "outdated-version-block", # Remove unnecessary `sys.version_info` blocks +] + +[tool.ruff.lint.pydocstyle] +convention = "pep257" # https://docs.astral.sh/ruff/settings/#lint_pydocstyle_convention + +[tool.ruff.lint.flake8-import-conventions.aliases] +# Prevent aliasing these, as it causes false-negatives for certain rules +typing_extensions = "typing_extensions" +typing = "typing" + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"tempfile.NamedTemporaryFile".msg = "Use `ts_util.util.NamedTemporaryFile` instead." + +[tool.ruff.lint.isort] +split-on-trailing-comma = false +combine-as-imports = true +extra-standard-library = [ + # Group these with stdlib "_typeshed", - # Extra modules not recognized by isort - "_ast", - "_collections_abc", - "_compression", - "_csv", - "_curses", - "_markupbase", - "_random", - "_tkinter", - "_tracemalloc", - "_warnings", - "_weakrefset", - "genericpath", - "opcode", - "pyexpat", - # Python 2 modules - "__builtin__", - "cookielib", - "cStringIO", - "httplib", - "mimetools", - "rfc822", - "thread", - "urllib2", - "urlparse", - "BaseHTTPServer", - "Queue", - "SimpleHTTPServer", - "SocketServer", - "StringIO", - "UserDict", - "UserList", - "UserString", + "typing_extensions", + # Extra modules not recognized by Ruff + # Added in Python 3.14 + "compression", ] +known-first-party = ["_utils", "ts_utils"] + +[tool.typeshed] +oldest-supported-python = "3.10" diff --git a/pyrefly.toml b/pyrefly.toml new file mode 100644 index 000000000000..1da5e49c879e --- /dev/null +++ b/pyrefly.toml @@ -0,0 +1,26 @@ +# typeshed uses `# type: ignore` comments to silence mypy and pyright; pyrefly +# should not treat them as suppressing its own errors. Keep in sync with the +# `respect-type-ignore-comments` setting in ty.toml. +enabled-ignores = ["pyrefly"] + +# pyrefly excludes "**/venv/**/*" by default, which matches "stdlib/venv", +# a proper stdlib module. +project-excludes = ["**/__pycache__", "**/.[!/.]*/**"] +disable-project-excludes-heuristics = true + +# These imports are intentionally optional and are also ignored by mypy and pyright. +ignore-missing-imports = [ + "branca", + "folium", + "pydot", + "pygraphviz.*", + "scipy.*", + "twisted.*", + "xyzservices", +] + +[errors] +# Incompatible overrides and deprecations are inherited from the implementation +# and are not actionable in typeshed. Keep in sync with pyrightconfig.json. +deprecated = false +bad-override = false diff --git a/pyrightconfig.json b/pyrightconfig.json index 25900f563525..74ddb65b85f6 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -1,54 +1,48 @@ { + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", "typeshedPath": ".", "include": [ "stdlib", - "stubs" + "stubs", ], "exclude": [ - "**/@python2" + // Stubs that don't work in all Python versions + "stubs/seaborn", + "stubs/shapely", + "stubs/geopandas", + // test cases use a custom config file + "**/@tests/test_cases", ], - "typeCheckingMode": "basic", - "strictListInference": true, - "strictDictionaryInference": true, - "strictParameterNoneValue": true, - "reportFunctionMemberAccess": "error", - "reportMissingModuleSource": "none", - "reportMissingTypeStubs": "error", - "reportUnusedImport": "error", - "reportUnusedClass": "error", - "reportUnusedFunction": "error", - "reportUnusedVariable": "error", - "reportDuplicateImport": "error", - "reportOptionalSubscript": "error", - "reportOptionalMemberAccess": "error", - "reportOptionalCall": "error", - "reportOptionalIterable": "error", - "reportOptionalContextManager": "error", - "reportOptionalOperand": "error", - "reportUntypedFunctionDecorator": "error", - "reportUntypedClassDecorator": "error", - "reportUntypedBaseClass": "error", - "reportUntypedNamedTuple": "error", + "typeCheckingMode": "strict", + // Allowed in base settings for incomplete stubs, checked in stricter settings + "reportIncompleteStub": "none", + "reportMissingParameterType": "none", + "reportUnknownMemberType": "none", + "reportUnknownParameterType": "none", + "reportUnknownVariableType": "none", + // Extra strict settings + "reportCallInDefaultInitializer": "error", + "reportUnnecessaryTypeIgnoreComment": "error", + // Leave "type: ignore" comments to mypy + "enableTypeIgnoreComments": false, + // No effect in stubs + "reportMissingSuperCall": "none", + "reportUninitializedInstanceVariable": "none", + // Stubs are allowed to use private variables "reportPrivateUsage": "none", - "reportConstantRedefinition": "error", - "reportIncompatibleMethodOverride": "error", - "reportIncompatibleVariableOverride": "error", - "reportInvalidStringEscapeSequence": "error", - "reportUnknownArgumentType": "error", - "reportUnknownLambdaType": "error", - "reportMissingTypeArgument": "error", - "reportUndefinedVariable": "error", - "reportUnboundVariable": "error", - "reportInvalidStubStatement": "error", - "reportInvalidTypeVarUse": "error", - "reportPropertyTypeMismatch": "error", - "reportSelfClsParameterName": "error", - // Overlapping overloads cannot be enabled at this time because - // of the "factions.Fraction.__pow__" method and "tasks.gather" function. - // Mypy's overlapping overload logic misses these issues (see mypy - // issue #10143 and #10157). + // Stubs don't need the actual modules to be installed + "reportMissingModuleSource": "none", + // Incompatible overrides and property type mismatches are out of typeshed's control + // as they are inherited from the implementation. + "reportIncompatibleMethodOverride": "none", + "reportIncompatibleVariableOverride": "none", + "reportPropertyTypeMismatch": "none", + // Overlapping overloads are often necessary in a stub, meaning pyright's check + // (which is stricter than mypy's; see mypy issue #10143 and #10157) + // would cause many false positives and catch few bugs. "reportOverlappingOverload": "none", - // Several stubs refer to symbols in __all__ that are conditionally - // declared based on platform or version checks. - "reportUnsupportedDunderAll": "none", + // The name of the self/cls parameter is out of typeshed's control. + "reportSelfClsParameterName": "none", + // Not actionable in typeshed + "reportDeprecated": "none", } diff --git a/pyrightconfig.scripts_and_tests.json b/pyrightconfig.scripts_and_tests.json new file mode 100644 index 000000000000..f9b093547281 --- /dev/null +++ b/pyrightconfig.scripts_and_tests.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", + "typeshedPath": ".", + "include": [ + "lib", + "scripts", + "tests", + ], + "extraPaths": [ + "lib", + ], + "typeCheckingMode": "strict", + // More of a lint. Unwanted for typeshed's own code. + "reportImplicitStringConcatenation": "none", + // Extra strict settings + "reportMissingModuleSource": "error", + "reportCallInDefaultInitializer": "error", + "reportPropertyTypeMismatch": "error", + "reportUninitializedInstanceVariable": "error", + "reportUnnecessaryTypeIgnoreComment": "error", + // Leave "type: ignore" comments to mypy + "enableTypeIgnoreComments": false, + // Too strict + "reportMissingSuperCall": "none", +} diff --git a/pyrightconfig.stricter.json b/pyrightconfig.stricter.json index 2441f5863a95..d3d66b8fd7fc 100644 --- a/pyrightconfig.stricter.json +++ b/pyrightconfig.stricter.json @@ -3,113 +3,133 @@ "typeshedPath": ".", "include": [ "stdlib", - "stubs" + "stubs", ], "exclude": [ - "**/@python2", + // test cases use a custom pyrightconfig file + "**/@tests/test_cases", + "stdlib/__main__.pyi", + "stdlib/_operator.pyi", + "stdlib/_tkinter.pyi", + "stdlib/distutils/cmd.pyi", "stdlib/distutils/command", - "stdlib/lib2to3/refactor.pyi", - "stdlib/sqlite3/dbapi2.pyi", - "stdlib/tkinter", - "stdlib/unittest/mock.pyi", - "stdlib/xml/dom/NodeFilter.pyi", - "stdlib/xml/dom/expatbuilder.pyi", - "stdlib/xml/dom/minidom.pyi", - "stdlib/xml/dom/pulldom.pyi", - "stdlib/xml/sax", + "stdlib/distutils/dist.pyi", + "stdlib/email/*.pyi", + "stdlib/encodings/__init__.pyi", + "stdlib/lib2to3/fixes/*.pyi", + "stdlib/numbers.pyi", + "stdlib/operator.pyi", + "stdlib/tkinter/__init__.pyi", + "stdlib/tkinter/dialog.pyi", + "stdlib/tkinter/filedialog.pyi", + "stdlib/tkinter/scrolledtext.pyi", + "stdlib/tkinter/tix.pyi", + "stdlib/tkinter/ttk.pyi", + "stubs/antlr4-python3-runtime", + "stubs/auth0-python", + "stubs/Authlib", "stubs/aws-xray-sdk", - "stubs/babel", - "stubs/backports.ssl_match_hostname", - "stubs/backports_abc", - "stubs/bleach", - "stubs/boto", - "stubs/beautifulsoup4", + "stubs/behave", + "stubs/boltons", "stubs/braintree", - "stubs/caldav", - "stubs/commonmark", - "stubs/cryptography", + "stubs/cffi", + "stubs/colorful", "stubs/dateparser", + "stubs/defusedxml", + "stubs/docker", "stubs/docutils", - "stubs/fpdf2", + "stubs/Flask-SocketIO", + "stubs/gdb", + "stubs/geojson", + "stubs/geopandas", + "stubs/google-cloud-ndb", + "stubs/grpcio-channelz/grpc_channelz/v1", + "stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi", + "stubs/grpcio-reflection/grpc_reflection/v1alpha", + "stubs/grpcio-status/grpc_status", + "stubs/grpcio/grpc/__init__.pyi", + "stubs/gunicorn/gunicorn/dirty", + "stubs/hdbcli/hdbcli/dbapi.pyi", "stubs/html5lib", "stubs/httplib2", - "stubs/humanfriendly", - "stubs/jmespath", + "stubs/hvac", "stubs/jsonschema", + "stubs/jwcrypto", + "stubs/kafka-python", "stubs/ldap3", + "stubs/m3u8/m3u8/model.pyi", "stubs/Markdown", - "stubs/mock", + "stubs/mock/mock/mock.pyi", "stubs/mysqlclient", + "stubs/netaddr/netaddr/core.pyi", + "stubs/netaddr/netaddr/ip/__init__.pyi", + "stubs/netaddr/netaddr/ip/iana.pyi", + "stubs/networkx", "stubs/oauthlib", - "stubs/Pillow", - "stubs/paramiko", - "stubs/prettytable", + "stubs/openpyxl", + "stubs/opentracing/opentracing/span.pyi", + "stubs/paramiko/paramiko/_winapi.pyi", + "stubs/parsimonious/parsimonious/nodes.pyi", + "stubs/peewee", + "stubs/pexpect", + "stubs/pika/pika/adapters/twisted_connection.pyi", + "stubs/pika/pika/adapters/utils/connection_workflow.pyi", + "stubs/pika/pika/callback.pyi", + "stubs/pika/pika/channel.pyi", + "stubs/pony", "stubs/protobuf", - "stubs/google-cloud-ndb", - "stubs/psutil", + "stubs/psutil/psutil/__init__.pyi", "stubs/psycopg2", + "stubs/punq", + "stubs/pyasn1", + "stubs/pycups", "stubs/Pygments", "stubs/PyMySQL", - "stubs/python-dateutil", - "stubs/pyvmomi", + "stubs/pyogrio", + "stubs/python-jose", + "stubs/pywin32", "stubs/PyYAML", - "stubs/redis", + "stubs/reportlab", "stubs/requests", - "stubs/selenium", - "stubs/Send2Trash", - "stubs/setuptools", - "stubs/simplejson", - "stubs/slumber", - "stubs/SQLAlchemy", - "stubs/stripe", - "stubs/ttkthemes", - "stubs/vobject" + "stubs/requests-oauthlib", + "stubs/seaborn", + "stubs/setuptools/setuptools", + "stubs/shapely", + "stubs/simple-websocket", + "stubs/tensorflow", + "stubs/tqdm", + "stubs/vobject", + "stubs/workalendar", + "stubs/xmldiff", ], - "typeCheckingMode": "basic", - "strictListInference": true, - "strictDictionaryInference": true, - "strictParameterNoneValue": true, - "reportFunctionMemberAccess": "error", - "reportMissingModuleSource": "none", - "reportMissingTypeStubs": "error", - "reportUnusedImport": "error", - "reportUnusedClass": "error", - "reportUnusedFunction": "error", - "reportUnusedVariable": "error", - "reportDuplicateImport": "error", - "reportOptionalSubscript": "error", - "reportOptionalMemberAccess": "error", - "reportOptionalCall": "error", - "reportOptionalIterable": "error", - "reportOptionalContextManager": "error", - "reportOptionalOperand": "error", - "reportUntypedFunctionDecorator": "error", - "reportUntypedClassDecorator": "error", - "reportUntypedBaseClass": "error", - "reportUntypedNamedTuple": "error", + "typeCheckingMode": "strict", + // TODO: Complete incomplete stubs + "reportIncompleteStub": "none", + // Extra strict settings + "reportCallInDefaultInitializer": "error", + // implicit string concatenation is useful for long deprecation messages + "reportImplicitStringConcatenation": "none", + "reportUnnecessaryTypeIgnoreComment": "error", + // Leave "type: ignore" comments to mypy + "enableTypeIgnoreComments": false, + // No effect in stubs + "reportMissingSuperCall": "none", + "reportUninitializedInstanceVariable": "none", + // Stubs are allowed to use private variables "reportPrivateUsage": "none", - "reportConstantRedefinition": "error", - "reportIncompatibleMethodOverride": "error", - "reportIncompatibleVariableOverride": "error", - "reportInvalidStringEscapeSequence": "error", - "reportUnknownParameterType": "error", - "reportUnknownArgumentType": "error", - "reportUnknownLambdaType": "error", - "reportUnknownVariableType": "error", - "reportUnknownMemberType": "error", - "reportMissingTypeArgument": "error", - "reportUndefinedVariable": "error", - "reportUnboundVariable": "error", - "reportInvalidStubStatement": "error", - "reportInvalidTypeVarUse": "error", - "reportPropertyTypeMismatch": "error", - "reportSelfClsParameterName": "error", - // Overlapping overloads cannot be enabled at this time because - // of the "factions.Fraction.__pow__" method and "tasks.gather" function. - // Mypy's overlapping overload logic misses these issues (see mypy - // issue #10143 and #10157). + // Stubs don't need the actual modules to be installed + "reportMissingModuleSource": "none", + // Incompatible overrides and property type mismatches are out of typeshed's control + // as they are inherited from the implementation. + "reportIncompatibleMethodOverride": "none", + "reportIncompatibleVariableOverride": "none", + "reportPropertyTypeMismatch": "none", + // Overlapping overloads are often necessary in a stub, meaning pyright's check + // (which is stricter than mypy's; see mypy issue #10143 and #10157) + // would cause many false positives and catch few bugs. "reportOverlappingOverload": "none", - // Several stubs refer to symbols in __all__ that are conditionally - // declared based on platform or version checks. - "reportUnsupportedDunderAll": "none", + // The name of the self/cls parameter is out of typeshed's control. + "reportSelfClsParameterName": "none", + // Not actionable in typeshed + "reportDeprecated": "none", } diff --git a/pyrightconfig.testcases.json b/pyrightconfig.testcases.json new file mode 100644 index 000000000000..ab1cb86b9900 --- /dev/null +++ b/pyrightconfig.testcases.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", + "typeshedPath": ".", + "include": [ + "**/@tests/test_cases", + ], + "typeCheckingMode": "strict", + // Extra strict settings + "reportImplicitStringConcatenation": "error", + "reportUninitializedInstanceVariable": "error", + "reportUnnecessaryTypeIgnoreComment": "error", + // Using unspecific `type: ignore` comments in test_cases. + // See https://github.com/python/typeshed/pull/8083 + "enableTypeIgnoreComments": true, + // If a test case uses this anti-pattern, there's likely a reason and annoying to `type: ignore`. + // Let Ruff flag it (B006) + "reportCallInDefaultInitializer": "none", + // Too strict and not needed for type testing + "reportMissingSuperCall": "none", + // Stubs are allowed to use private variables. We may want to test those. + "reportPrivateUsage": "none", + // Stubs don't need the actual modules to be installed + "reportMissingModuleSource": "none", + // Incompatible property type mismatches may be out of typeshed's control + // when they are inherited from the implementation. + "reportPropertyTypeMismatch": "none", + // isinstance checks are still needed when validating inputs outside of typeshed's control + "reportUnnecessaryIsInstance": "none", + // The name of the self/cls parameter is out of typeshed's control. + "reportSelfClsParameterName": "none", +} diff --git a/requirements-tests.txt b/requirements-tests.txt index 3f50e343a37d..3c1e54b81e41 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,10 +1,26 @@ -mypy==0.930 -pytype==2021.11.29; platform_system != "Windows" -# must match .pre-commit-config.yaml -black==21.12b0 -flake8==4.0.1 -flake8-bugbear==21.11.29 -flake8-pyi==20.10.0 -# must match .pre-commit-config.yaml -isort==5.10.1 -tomli==1.2.2 +# Type checkers that we test our stubs against. These should always +# be pinned to a specific version to make failure reproducible. +mypy==2.4.0 +pyrefly==1.3.2 +pyright==1.1.414 +ty==0.0.85 + +# Libraries used by our various scripts. +aiohttp==3.14.3 +grpcio-tools>=1.76.0; python_version < "3.15" # For grpc_tools.protoc +mypy-protobuf==5.1.0; python_version < "3.15" +packaging==26.3 +pathspec>=1.1.1 +pre-commit +ruff==0.16.10 +# Required by create_baseline_stubs.py. +# stubdefaulter depends on libcst, which does not yet install cleanly on Python 3.15. +stubdefaulter==0.1.0; python_version < "3.15" +termcolor>=2.3 +tomli==2.4.1; python_version < "3.11" +tomlkit==0.15.1 +typing_extensions>=4.16.0rc2 +uv==0.12.18 + +# Utilities for typeshed infrastructure scripts. +ts_utils @ file:lib diff --git a/scripts/create_baseline_stubs.py b/scripts/create_baseline_stubs.py index 742eb5beee31..4d1548e3583e 100755 --- a/scripts/create_baseline_stubs.py +++ b/scripts/create_baseline_stubs.py @@ -8,18 +8,25 @@ Run with -h for more help. """ +from __future__ import annotations + import argparse -import os +import asyncio import re -import shutil import subprocess import sys -from typing import Optional, Tuple +import urllib.parse +from http import HTTPStatus +from importlib.metadata import distribution +from pathlib import Path + +import aiohttp +import termcolor -PYRIGHT_CONFIG = "pyrightconfig.stricter.json" +from ts_utils.paths import PYRIGHT_CONFIG, STDLIB_PATH, STUBS_PATH -def search_pip_freeze_output(project: str, output: str) -> Optional[Tuple[str, str]]: +def search_pip_freeze_output(project: str, output: str) -> tuple[str, str] | None: # Look for lines such as "typed-ast==1.4.2". '-' matches '_' and # '_' matches '-' in project name, so that "typed_ast" matches # "typed-ast", and vice versa. @@ -30,7 +37,7 @@ def search_pip_freeze_output(project: str, output: str) -> Optional[Tuple[str, s return m.group(1), m.group(2) -def get_installed_package_info(project: str) -> Optional[Tuple[str, str]]: +def get_installed_package_info(project: str) -> tuple[str, str] | None: """Find package information from pip freeze output. Match project name somewhat fuzzily (case sensitive; '-' matches '_', and @@ -38,56 +45,107 @@ def get_installed_package_info(project: str) -> Optional[Tuple[str, str]]: Return (normalized project name, installed version) if successful. """ + # Not using "uv pip freeze" because if this is run from a global Python, + # it'll mistakenly list the .venv's packages. r = subprocess.run(["pip", "freeze"], capture_output=True, text=True, check=True) return search_pip_freeze_output(project, r.stdout) -def run_stubgen(package: str) -> None: - print(f"Running stubgen: stubgen -p {package}") - subprocess.run(["python", "-m", "mypy.stubgen", "-p", package], check=True) - - -def copy_stubs(src_base_dir: str, package: str, stub_dir: str) -> None: - """Copy generated stubs to the target directory under stub_dir/.""" - print(f"Copying stubs to {stub_dir}") - if not os.path.isdir(stub_dir): - os.mkdir(stub_dir) - src_dir = os.path.join(src_base_dir, package) - if os.path.isdir(src_dir): - shutil.copytree(src_dir, os.path.join(stub_dir, package)) - else: - src_file = os.path.join("out", package + ".pyi") - if not os.path.isfile(src_file): - sys.exit("Error: Cannot find generated stubs") - shutil.copy(src_file, stub_dir) - - -def run_black(stub_dir: str) -> None: - print(f"Running black: black {stub_dir}") - subprocess.run(["black", stub_dir]) - - -def run_isort(stub_dir: str) -> None: - print(f"Running isort: isort {stub_dir}") - subprocess.run(["python3", "-m", "isort", stub_dir]) - - -def create_metadata(stub_dir: str, version: str) -> None: +def run_stubgen(package: str, output: Path) -> None: + print(f"Running stubgen: stubgen -o {output} -p {package}") + subprocess.run(["stubgen", "-o", output, "-p", package, "--export-less"], check=True) + + +def run_stubdefaulter(stub_dir: Path) -> None: + print(f"Running stubdefaulter: stubdefaulter --packages {stub_dir}") + subprocess.run(["stubdefaulter", "--packages", stub_dir], check=False) + + +def run_black(stub_dir: Path) -> None: + print(f"Running Black: black {stub_dir}") + subprocess.run(["pre-commit", "run", "black", "--files", *stub_dir.rglob("*.pyi")], check=False) + + +def run_ruff(stub_dir: Path) -> None: + print(f"Running Ruff: ruff check {stub_dir} --fix-only") + subprocess.run([sys.executable, "-m", "ruff", "check", stub_dir, "--fix-only"], check=False) + + +async def get_project_urls_from_pypi(project: str, session: aiohttp.ClientSession) -> dict[str, str]: + pypi_root = f"https://pypi.org/pypi/{urllib.parse.quote(project)}" + async with session.get(f"{pypi_root}/json") as response: + if response.status != HTTPStatus.OK: + return {} + j: dict[str, dict[str, dict[str, str]]] + j = await response.json() + return j["info"].get("project_urls") or {} + + +async def get_upstream_repo_url(project: str) -> str | None: + # aiohttp is overkill here, but it would also just be silly + # to have both requests and aiohttp in our requirements-tests.txt file. + async with aiohttp.ClientSession() as session: + project_urls = await get_project_urls_from_pypi(project, session) + + if not project_urls: + return None + + # Order the project URLs so that we put the ones + # that are most likely to point to the source code first + urls_to_check: list[str] = [] + url_names_probably_pointing_to_source = ("Source", "Repository", "Homepage") + for url_name in url_names_probably_pointing_to_source: + if url := project_urls.get(url_name): + urls_to_check.append(url) + urls_to_check.extend( + url for url_name, url in project_urls.items() if url_name not in url_names_probably_pointing_to_source + ) + + for url_to_check in urls_to_check: + # Remove `www.`; replace `http://` with `https://` + url = re.sub(r"^(https?://)?(www\.)?", "https://", url_to_check) + netloc = urllib.parse.urlparse(url).netloc + if netloc not in {"gitlab.com", "github.com", "bitbucket.org", "foss.heptapod.net"}: + continue + # truncate to https://site.com/user/repo + upstream_repo_url = "/".join(url.split("/")[:5]) + async with session.get(upstream_repo_url, allow_redirects=True) as response: + if response.status != HTTPStatus.OK: + continue + # final url after redirects + final_url = str(response.url) + # normalize again (in case redirect added extra path) + final_repo_url = "/".join(final_url.split("/")[:5]) + return final_repo_url + return None + + +def create_metadata(project: str, stub_dir: Path, version: str) -> None: """Create a METADATA.toml file.""" - m = re.match(r"[0-9]+.[0-9]+", version) - if m is None: + match = re.match(r"[0-9]+.[0-9]+", version) + if match is None: sys.exit(f"Error: Cannot parse version number: {version}") - fnam = os.path.join(stub_dir, "METADATA.toml") - version = m.group(0) - assert not os.path.exists(fnam) - print(f"Writing {fnam}") - with open(fnam, "w") as f: - f.write(f'version = "{version}.*"\n') + filename = stub_dir / "METADATA.toml" + version = match.group(0) + if filename.exists(): + return + metadata = f'version = "{version}.*"\n' + upstream_repo_url = asyncio.run(get_upstream_repo_url(project)) + if upstream_repo_url is None: + warning = ( + f"\nCould not find a URL pointing to the source code for {project!r}.\n" + f"Please add it as `upstream-repository` to `stubs/{project}/METADATA.toml`, if possible!\n" + ) + print(termcolor.colored(warning, "red")) + else: + metadata += f'upstream-repository = "{upstream_repo_url}"\n' + print(f"Writing {filename}") + filename.write_text(metadata, encoding="UTF-8") -def add_pyright_exclusion(stub_dir: str) -> None: +def add_pyright_exclusion(stub_dir: Path) -> None: """Exclude stub_dir from strict pyright checks.""" - with open(PYRIGHT_CONFIG) as f: + with PYRIGHT_CONFIG.open(encoding="UTF-8") as f: lines = f.readlines() i = 0 while i < len(lines) and not lines[i].strip().startswith('"exclude": ['): @@ -95,67 +153,93 @@ def add_pyright_exclusion(stub_dir: str) -> None: assert i < len(lines), f"Error parsing {PYRIGHT_CONFIG}" while not lines[i].strip().startswith("]"): i += 1 - line_to_add = f' "{stub_dir}",' - initial = i - 1 - while lines[i].lower() > line_to_add.lower(): + end = i + + # We assume that all third-party excludes must be at the end of the list. + # This helps with skipping special entries, such as "stubs/**/@tests/test_cases". + while lines[i - 1].strip().startswith('"stubs/'): i -= 1 - if lines[i + 1].strip().rstrip(",") == line_to_add.strip().rstrip(","): + start = i + + before_third_party_excludes = lines[:start] + third_party_excludes = lines[start:end] + after_third_party_excludes = lines[end:] + + last_line = third_party_excludes[-1].rstrip() + if not last_line.endswith(","): + last_line += "," + third_party_excludes[-1] = last_line + "\n" + + # Must use forward slash in the .json file + line_to_add = f' "{stub_dir.as_posix()}",\n' + + if line_to_add in third_party_excludes: print(f"{PYRIGHT_CONFIG} already up-to-date") return - if i == initial: - # Special case: when adding to the end of the list, commas need tweaking - line_to_add = line_to_add.rstrip(",") - lines[i] = lines[i].rstrip() + ",\n" - lines.insert(i + 1, line_to_add + "\n") + + third_party_excludes.append(line_to_add) + third_party_excludes.sort(key=str.lower) + print(f"Updating {PYRIGHT_CONFIG}") - with open(PYRIGHT_CONFIG, "w") as f: - f.writelines(lines) + with PYRIGHT_CONFIG.open("w", encoding="UTF-8") as f: + f.writelines(before_third_party_excludes) + f.writelines(third_party_excludes) + f.writelines(after_third_party_excludes) def main() -> None: - parser = argparse.ArgumentParser( - description="""Generate baseline stubs automatically for an installed pip package - using stubgen. Also run black and isort. If the name of - the project is different from the runtime Python package name, you must - also use --package (example: --package yaml PyYAML).""" - ) + parser = argparse.ArgumentParser(description="""Generate baseline stubs automatically for an installed pip package + using stubgen. Also run Black and Ruff. If the name of + the project is different from the runtime Python package name, you may + need to use --package (example: --package yaml PyYAML).""") parser.add_argument("project", help="name of PyPI project for which to generate stubs under stubs/") - parser.add_argument("--package", help="generate stubs for this Python package (defaults to project)") + parser.add_argument("--package", help="generate stubs for this Python package (default is autodetected)") args = parser.parse_args() project = args.project - package = args.package + package: str = args.package if not re.match(r"[a-zA-Z0-9-_.]+$", project): sys.exit(f"Invalid character in project name: {project!r}") if not package: - package = project # TODO: infer from installed files - - if not os.path.isdir("stubs") or not os.path.isdir("stdlib"): + package = project # default + # Try to find which packages are provided by the project + # Use default if that fails or if several packages are found + # + # The importlib.metadata module is used for projects whose name is different + # from the runtime Python package name (example: PyYAML/yaml) + dist = distribution(project).read_text("top_level.txt") + if dist is not None: + packages = [name for name in dist.split() if not name.startswith("_")] + if len(packages) == 1: + package = packages[0] + print(f'Using detected package "{package}" for project "{project}"', file=sys.stderr) + print("Suggestion: Try again with --package argument if that's not what you wanted", file=sys.stderr) + + if not STUBS_PATH.is_dir() or not STDLIB_PATH.is_dir(): sys.exit("Error: Current working directory must be the root of typeshed repository") # Get normalized project name and version of installed package. info = get_installed_package_info(project) if info is None: print(f'Error: "{project}" is not installed', file=sys.stderr) - print("", file=sys.stderr) - print(f'Suggestion: Run "python3 -m pip install {project}" and try again', file=sys.stderr) + print(file=sys.stderr) + print(f"Suggestion: Run `{sys.executable} -m pip install {project}` and try again", file=sys.stderr) sys.exit(1) project, version = info - stub_dir = os.path.join("stubs", project) - if os.path.exists(stub_dir): - sys.exit(f"Error: {stub_dir} already exists (delete it first)") - - run_stubgen(package) + stub_dir = STUBS_PATH / project + package_dir = stub_dir / package + if package_dir.exists(): + sys.exit(f"Error: {package_dir} already exists (delete it first)") - # Stubs were generated under out/. Copy them to stubs/. - copy_stubs("out", package, stub_dir) + run_stubgen(package, stub_dir) + run_stubdefaulter(stub_dir) - run_isort(stub_dir) + run_ruff(stub_dir) run_black(stub_dir) - create_metadata(stub_dir, version) + create_metadata(project, stub_dir, version) # Since the generated stubs won't have many type annotations, we # have to exclude them from strict pyright checks. @@ -163,11 +247,8 @@ def main() -> None: print("\nDone!\n\nSuggested next steps:") print(f" 1. Manually review the generated stubs in {stub_dir}") - print(f' 2. Run "MYPYPATH={stub_dir} python3 -m mypy.stubtest {package}" to check the stubs against runtime') - print(f' 3. Run "mypy {stub_dir}" to check for errors') - print(f' 4. Run "black {stub_dir}" and "isort {stub_dir}" (if you\'ve made code changes)') - print(f' 5. Run "flake8 {stub_dir}" to check for e.g. unused imports') - print(" 6. Commit the changes on a new branch and create a typeshed PR") + print(" 2. Optionally run tests and autofixes (see tests/README.md for details)") + print(" 3. Commit the changes on a new branch and create a typeshed PR (don't force-push!)") if __name__ == "__main__": diff --git a/scripts/generate_proto_stubs.sh b/scripts/generate_proto_stubs.sh deleted file mode 100755 index 7d7a606da686..000000000000 --- a/scripts/generate_proto_stubs.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/bin/bash -# Some of the proto .pyi stubs in stubs/protobuf/ -# are autogenerated using the mypy-protobuf project on the -# latest `.proto` files shipped with protoc. -# -# When run, this script will autogenerate the _pb2.pyi stubs to -# stubs/protobuf. It should be run any time there's -# a meaningful update to either PROTOBUF_VERSION or MYPY_PROTOBUF_VERSION, -# followed by committing the changes to typeshed -# -# Update these two variables when rerunning script -PROTOBUF_VERSION=3.18.1 -MYPY_PROTOBUF_VERSION=v3.0.0 - -set -ex - -if uname -a | grep Darwin; then - # brew install coreutils wget - PLAT=osx -else - PLAT=linux -fi -REPO_ROOT=$(realpath $(dirname "${BASH_SOURCE[0]}")/..) -TMP_DIR=$(mktemp -d) -PYTHON_PROTOBUF_FILENAME=protobuf-python-${PROTOBUF_VERSION}.zip -PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-${PLAT}-x86_64.zip -PROTOC_URL=https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME} -PYTHON_PROTOBUF_URL=https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOBUF_VERSION}/${PYTHON_PROTOBUF_FILENAME} - -cd $TMP_DIR -echo "Working in $TMP_DIR" - -# Install protoc -wget $PROTOC_URL -mkdir protoc_install -unzip $PROTOC_FILENAME -d protoc_install - -# Fetch protoc-python (which contains all the .proto files) -wget $PYTHON_PROTOBUF_URL -unzip $PYTHON_PROTOBUF_FILENAME -PYTHON_PROTOBUF_DIR=protobuf-$PROTOBUF_VERSION - -# Prepare virtualenv -VENV=venv -python3 -m venv $VENV -source $VENV/bin/activate -pip install -r $REPO_ROOT/requirements-tests.txt # for black and isort - -# Install mypy-protobuf -pip install git+https://github.com/dropbox/mypy-protobuf@${MYPY_PROTOBUF_VERSION} - -# Remove existing pyi -find $REPO_ROOT/stubs/protobuf/ -name "*_pb2.pyi" -delete - -# Roughly reproduce the subset of .proto files on the public interface as described -# by find_package_modules in the protobuf setup.py. -# The logic (as of 3.14.0) can roughly be described as a allowlist of .proto files -# further limited to exclude *test* and internal/ -# https://github.com/protocolbuffers/protobuf/blob/master/python/setup.py -PROTO_FILES=$(grep "generate_proto.*google" $PYTHON_PROTOBUF_DIR/python/setup.py | \ - cut -d\" -f2 | \ - grep -v "test" | \ - grep -v google/protobuf/internal/ | \ - grep -v google/protobuf/pyext/python.proto | \ - grep -v src/google/protobuf/util/json_format.proto | \ - grep -v src/google/protobuf/util/json_format_proto3.proto | \ - sed "s:^:$PYTHON_PROTOBUF_DIR/python/:" | \ - xargs -L1 realpath --relative-to=. \ -) - -# And regenerate! -protoc_install/bin/protoc --proto_path=$PYTHON_PROTOBUF_DIR/src --mypy_out=$REPO_ROOT/stubs/protobuf $PROTO_FILES - -isort $REPO_ROOT/stubs/protobuf -black $REPO_ROOT/stubs/protobuf - -sed -i="" "s/mypy-protobuf [^\"]*/mypy-protobuf ${MYPY_PROTOBUF_VERSION}/" $REPO_ROOT/stubs/protobuf/METADATA.toml diff --git a/scripts/install_all_third_party_dependencies.py b/scripts/install_all_third_party_dependencies.py new file mode 100644 index 000000000000..ca1b7075589f --- /dev/null +++ b/scripts/install_all_third_party_dependencies.py @@ -0,0 +1,15 @@ +import subprocess +import sys + +from ts_utils.requirements import get_external_stub_requirements + + +def main() -> None: + requirements = get_external_stub_requirements() + # By forwarding arguments, we naturally allow non-venv (system installs) + # by letting the script's user follow uv's own helpful hint of passing the `--system` flag. + subprocess.check_call(["uv", "pip", "install", *sys.argv[1:], *[str(requirement) for requirement in requirements]]) + + +if __name__ == "__main__": + main() diff --git a/scripts/stubsabot.py b/scripts/stubsabot.py new file mode 100755 index 000000000000..7ced8f5a81e0 --- /dev/null +++ b/scripts/stubsabot.py @@ -0,0 +1,1047 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import asyncio +import calendar +import contextlib +import datetime +import enum +import functools +import io +import os +import re +import shutil +import subprocess +import sys +import tarfile +import textwrap +import urllib.parse +import zipfile +from collections.abc import Callable, Iterator, Mapping, Sequence +from dataclasses import dataclass, field +from http import HTTPStatus +from pathlib import Path +from typing import Annotated, Any, ClassVar, Literal, NamedTuple, TypeAlias, TypedDict, TypeVar, cast +from typing_extensions import Self + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +import aiohttp +import packaging.version +import tomlkit +from packaging.specifiers import Specifier +from termcolor import colored + +from ts_utils.metadata import ( + ObsoleteMetadata, + StubMetadata, + StubtestSettings, + read_metadata, + read_stubtest_settings, + update_metadata, +) +from ts_utils.paths import PYRIGHT_CONFIG, STUBS_PATH, distribution_path +from ts_utils.stubs import third_party_stubs + +TYPESHED_OWNER = "python" +TYPESHED_API_URL = f"https://api.github.com/repos/{TYPESHED_OWNER}/typeshed" + +STUBSABOT_LABEL = "bot: stubsabot" + +POLICY_MONTHS_DELTA = 6 + + +class ActionLevel(enum.IntEnum): + def __new__(cls, value: int, doc: str) -> Self: + member = int.__new__(cls, value) + member._value_ = value + member.__doc__ = doc + return member + + @classmethod + def from_cmd_arg(cls, cmd_arg: str) -> ActionLevel: + try: + return cls[cmd_arg] + except KeyError: + raise argparse.ArgumentTypeError(f'Argument must be one of "{list(cls.__members__)}"') from None + + nothing = 0, "make no changes" + local = 1, "make changes that affect local repo" + fork = 2, "make changes that affect remote repo, but won't open PRs against upstream" + everything = 3, "do everything, e.g. open PRs" + + +@dataclass +class PypiReleaseDownload: + distribution: str + url: str + packagetype: Annotated[str, "Should hopefully be either 'bdist_wheel' or 'sdist'"] + filename: str + version: packaging.version.Version + upload_date: datetime.datetime + + +VersionString: TypeAlias = str +ReleaseDownload: TypeAlias = dict[str, Any] + + +def _best_effort_version(version: VersionString) -> packaging.version.Version: + try: + return packaging.version.Version(version) + except packaging.version.InvalidVersion: + # packaging.version.Version no longer parses legacy versions + try: + return packaging.version.Version(version.replace("-", "+")) + except packaging.version.InvalidVersion: + return packaging.version.Version("0") + + +@dataclass +class PypiInfo: + distribution: str + pypi_root: str + releases: dict[VersionString, list[ReleaseDownload]] = field(repr=False) + info: dict[str, Any] = field(repr=False) + + def get_release(self, *, version: VersionString) -> PypiReleaseDownload: + # prefer wheels, since it's what most users will get / it's pretty easy to mess up MANIFEST + release_info = sorted(self.releases[version], key=lambda x: bool(x["packagetype"] == "bdist_wheel"))[-1] + return PypiReleaseDownload( + distribution=self.distribution, + url=release_info["url"], + packagetype=release_info["packagetype"], + filename=release_info["filename"], + version=packaging.version.Version(version), + upload_date=datetime.datetime.fromisoformat(release_info["upload_time"]), + ) + + def get_latest_release(self) -> PypiReleaseDownload: + return self.get_release(version=self.info["version"]) + + def releases_in_descending_order(self) -> Iterator[PypiReleaseDownload]: + for version in sorted(self.releases, key=_best_effort_version, reverse=True): + yield self.get_release(version=version) + + +async def fetch_pypi_info(distribution: str, session: aiohttp.ClientSession) -> PypiInfo: + # Cf. # https://warehouse.pypa.io/api-reference/json.html#get--pypi--project_name--json + pypi_root = f"https://pypi.org/pypi/{urllib.parse.quote(distribution)}" + async with session.get(f"{pypi_root}/json") as response: + response.raise_for_status() + j = await response.json() + return PypiInfo(distribution=distribution, pypi_root=pypi_root, releases=j["releases"], info=j["info"]) + + +@dataclass +class Update: + distribution: str + old_version_spec: Specifier + new_version_spec: Specifier + links: dict[str, str] + diff_analysis: DiffAnalysis | None + + def __str__(self) -> str: + return f"{colored('updating', 'yellow')} from '{self.old_version_spec}' to '{self.new_version_spec}'" + + @property + def new_version(self) -> str: + if self.new_version_spec.operator == "==": + return str(self.new_version_spec)[2:] + else: + return str(self.new_version_spec) + + +@dataclass +class Obsolete: + distribution: str + obsolete_since_version: str + obsolete_since_date: datetime.datetime + links: dict[str, str] + + def __str__(self) -> str: + return f"{colored('marking as obsolete', 'yellow')} since {self.obsolete_since_version!r}" + + +@dataclass +class Remove: + distribution: str + reason: Literal["ships py.typed file", "unmaintained"] + links: dict[str, str] + + def __str__(self) -> str: + return f"{colored('removing', 'yellow')} ({self.reason})" + + +@dataclass +class NoUpdate: + distribution: str + reason: Literal["obsolete", "no longer updated", "up to date", "pr open"] + pr_number: int = 0 + + def __str__(self) -> str: + if self.reason == "pr open": + return f"{colored('skipping', 'green')} ({self.reason} {self.pr_number})" + else: + return f"{colored('skipping', 'green')} ({self.reason})" + + +@dataclass +class Error: + distribution: str + message: str + + def __str__(self) -> str: + return f"{colored('error', 'red')} ({self.message})" + + +_T = TypeVar("_T") + + +async def with_extracted_archive( + release_to_download: PypiReleaseDownload, + *, + session: aiohttp.ClientSession, + handler: Callable[[zipfile.ZipFile | tarfile.TarFile], _T], +) -> _T: + async with session.get(release_to_download.url) as response: + body = io.BytesIO(await response.read()) + + packagetype = release_to_download.packagetype + if packagetype == "bdist_wheel": + assert release_to_download.filename.endswith(".whl") + with zipfile.ZipFile(body) as zf: + return handler(zf) + elif packagetype == "sdist": + # sdist defaults to `.tar.gz` on Linux and to `.zip` on Windows: + # https://docs.python.org/3.11/distutils/sourcedist.html + if release_to_download.filename.endswith(".tar.gz"): + with tarfile.open(fileobj=body, mode="r:gz") as zf: + return handler(zf) + elif release_to_download.filename.endswith(".zip"): + with zipfile.ZipFile(body) as zf: + return handler(zf) + else: + raise AssertionError(f"Package file {release_to_download.filename!r} does not end with '.tar.gz' or '.zip'") + else: + raise AssertionError(f"Unknown package type for {release_to_download.distribution}: {packagetype!r}") + + +def all_py_files_in_source_are_in_py_typed_dirs(source: zipfile.ZipFile | tarfile.TarFile) -> bool: + py_typed_dirs: list[Path] = [] + all_python_files: list[Path] = [] + py_file_suffixes = {".py", ".pyi"} + + # Obtain an iterator over all files in the zipfile/tarfile. + # Filter out empty __init__.py files: this reduces false negatives + # in cases like this: + # + # repo_root/ + # ├─ src/ + # | ├─ pkg/ + # | | ├─ __init__.py <-- This file is empty + # | | ├─ subpkg/ + # | | | ├─ __init__.py + # | | | ├─ libraryfile.py + # | | | ├─ libraryfile2.py + # | | | ├─ py.typed + if isinstance(source, zipfile.ZipFile): + path_iter = ( + Path(zip_info.filename) + for zip_info in source.infolist() + if ((not zip_info.is_dir()) and not (Path(zip_info.filename).name == "__init__.py" and zip_info.file_size == 0)) + ) + else: + path_iter = ( + Path(tar_info.path) + for tar_info in source + if (tar_info.isfile() and not (Path(tar_info.name).name == "__init__.py" and tar_info.size == 0)) + ) + + for path in path_iter: + if path.suffix in py_file_suffixes: + all_python_files.append(path) + elif path.name == "py.typed": + py_typed_dirs.append(path.parent) + + if not py_typed_dirs: + return False + if not all_python_files: + return False + + for path in all_python_files: + if not any(py_typed_dir in path.parents for py_typed_dir in py_typed_dirs): + return False + return True + + +async def release_contains_py_typed(release_to_download: PypiReleaseDownload, *, session: aiohttp.ClientSession) -> bool: + return await with_extracted_archive(release_to_download, session=session, handler=all_py_files_in_source_are_in_py_typed_dirs) + + +async def find_first_release_with_py_typed(pypi_info: PypiInfo, *, session: aiohttp.ClientSession) -> PypiReleaseDownload | None: + """If the latest release is py.typed, return the first release that included a py.typed file. + + If the latest release is not py.typed, return None. + """ + release_iter = (release for release in pypi_info.releases_in_descending_order() if not release.version.is_prerelease) + latest_release = next(release_iter) + # If the latest release is not py.typed, assume none are. + if not (await release_contains_py_typed(latest_release, session=session)): + return None + + first_release_with_py_typed = latest_release + while await release_contains_py_typed(release := next(release_iter), session=session): + first_release_with_py_typed = release + return first_release_with_py_typed + + +def get_updated_version_spec(spec: Specifier, version: packaging.version.Version) -> Specifier: + """ + Given the old specifier and an updated version, returns an updated specifier that has the + specificity of the old specifier, but matches the updated version. + + For example: + spec="1", version="1.2.3" -> "1.2.3" + spec="1.0.1", version="1.2.3" -> "1.2.3" + spec="1.*", version="1.2.3" -> "1.*" + spec="1.*", version="2.3.4" -> "2.*" + spec="1.1.*", version="1.2.3" -> "1.2.*" + spec="1.1.1.*", version="1.2.3" -> "1.2.3.*" + spec="~=1.0.1", version="1.0.3" -> "~=1.0.3" + spec="~=1.0.1", version="1.1.0" -> "~=1.1.0" + """ + if spec.operator == "==" and spec.version.endswith(".*"): + specificity = spec.version.count(".") if spec.version.removesuffix(".*") else 0 + rounded_version = version.base_version.split(".")[:specificity] + rounded_version.extend(["0"] * (specificity - len(rounded_version))) + updated_spec = Specifier("==" + ".".join(rounded_version) + ".*") + elif spec.operator == "==": + updated_spec = Specifier(f"=={version}") + elif spec.operator == "~=": + updated_spec = Specifier(f"~={version}") + else: + raise ValueError(f"Unsupported version operator: {spec.operator}") + assert version in updated_spec, f"{version} not in {updated_spec}" + return updated_spec + + +@functools.cache +def get_github_api_headers() -> Mapping[str, str]: + headers = {"Accept": "application/vnd.github.v3+json"} + secret = os.environ.get("GITHUB_TOKEN") + if secret is not None: + headers["Authorization"] = f"token {secret}" if secret.startswith("ghp") else f"Bearer {secret}" + return headers + + +GitHost: TypeAlias = Literal["github", "gitlab"] + + +@dataclass +class GitHostInfo: + host: GitHost + repo_path: str + tags: list[str] = field(repr=False) + + +async def get_host_repo_info(session: aiohttp.ClientSession, stub_info: StubMetadata) -> GitHostInfo | None: + """ + If the project represented by `stub_info` is publicly hosted (e.g. on GitHub) + return information regarding the project as it exists on the public host. + + Else, return None. + """ + if not stub_info.upstream_repository: + return None + # We have various sanity checks for the upstream_repository field in ts_utils.metadata, + # so no need to repeat all of them here + split_url = urllib.parse.urlsplit(stub_info.upstream_repository) + host = split_url.netloc.removesuffix(".com") + if host not in {"github", "gitlab"}: + return None + url_path = split_url.path.strip("/") + assert len(Path(url_path).parts) == 2 + if host == "github": + # https://docs.github.com/en/rest/git/tags + info_url = f"https://api.github.com/repos/{url_path}/tags" + headers = get_github_api_headers() + else: + assert host == "gitlab" + # https://docs.gitlab.com/api/tags/ + project_id = urllib.parse.quote(url_path, safe="") + info_url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/tags" + headers = None + async with session.get(info_url, headers=headers) as response: + if response.status == HTTPStatus.OK: + # Conveniently both GitHub and GitLab use the same key name. + tags = [tag["name"] for tag in await response.json()] + return GitHostInfo(host=host, repo_path=url_path, tags=tags) # type: ignore[arg-type] + return None + + +class GitHostDiffInfo(NamedTuple): + host: GitHost + repo_path: str + old_tag: str + new_tag: str + + @property + def diff_url(self) -> str: + if self.host == "github": + return f"https://github.com/{self.repo_path}/compare/{self.old_tag}...{self.new_tag}" + else: + assert self.host == "gitlab" + return f"https://gitlab.com/{self.repo_path}/-/compare/{self.old_tag}...{self.new_tag}" + + +async def get_diff_info( + session: aiohttp.ClientSession, stub_info: StubMetadata, pypi_version: packaging.version.Version +) -> GitHostDiffInfo | None: + """Return a tuple giving info about the diff between two releases, if possible. + + Return `None` if the project isn't hosted on GitHub, + or if a link pointing to the diff couldn't be found for any other reason. + """ + host_info = await get_host_repo_info(session, stub_info) + if host_info is None: + return None + + versions_to_tags: dict[packaging.version.Version, str] = {} + for tag_name in host_info.tags: + # Some packages in typeshed have tag names + # that are invalid to be passed to the Version() constructor, + # e.g. v.1.4.2 + with contextlib.suppress(packaging.version.InvalidVersion): + versions_to_tags[packaging.version.Version(tag_name)] = tag_name + + try: + new_tag = versions_to_tags[pypi_version] + except KeyError: + return None + + try: + old_version = max(version for version in versions_to_tags if version in stub_info.version_spec and version < pypi_version) + except ValueError: + return None + else: + old_tag = versions_to_tags[old_version] + + return GitHostDiffInfo(host=host_info.host, repo_path=host_info.repo_path, old_tag=old_tag, new_tag=new_tag) + + +FileStatus: TypeAlias = Literal["added", "modified", "removed", "renamed"] + + +class FileInfo(TypedDict): + filename: str + status: FileStatus + additions: int + deletions: int + + +def _plural_s(num: int, /) -> str: + return "s" if num != 1 else "" + + +@dataclass(repr=False) +class DiffAnalysis: + MAXIMUM_NUMBER_OF_FILES_TO_LIST: ClassVar[int] = 7 + py_files: list[FileInfo] + py_files_stubbed_in_typeshed: list[FileInfo] + + @property + def runtime_definitely_has_consistent_directory_structure_with_typeshed(self) -> bool: + """ + If 0 .py files in the GitHub diff exist in typeshed's stubs, + there's a possibility that the .py files might be found + in a different directory at runtime. + + For example: pyopenssl has its .py files in the `src/OpenSSL/` directory at runtime, + but in typeshed the stubs are in the `OpenSSL/` directory. + """ + return bool(self.py_files_stubbed_in_typeshed) + + @functools.cached_property + def public_files_added(self) -> Sequence[str]: + def is_public(path: Path) -> bool: + return not re.match(r"_[^_]", path.name) and not path.name.startswith("test_") + + return [file["filename"] for file in self.py_files if is_public(Path(file["filename"])) and file["status"] == "added"] + + @functools.cached_property + def typeshed_files_deleted(self) -> Sequence[str]: + return [file["filename"] for file in self.py_files_stubbed_in_typeshed if file["status"] == "removed"] + + @functools.cached_property + def typeshed_files_modified(self) -> Sequence[str]: + return [file["filename"] for file in self.py_files_stubbed_in_typeshed if file["status"] in {"modified", "renamed"}] + + @property + def total_lines_added(self) -> int: + return sum(file["additions"] for file in self.py_files) + + @property + def total_lines_deleted(self) -> int: + return sum(file["deletions"] for file in self.py_files) + + def _describe_files(self, *, verb: str, filenames: Sequence[str]) -> str: + num_files = len(filenames) + if num_files > 1: + description = f"have been {verb}" + # Don't list the filenames if there are *loads* of files + if num_files <= self.MAXIMUM_NUMBER_OF_FILES_TO_LIST: + description += ": " + description += ", ".join(f"`{filename}`" for filename in filenames) + description += "." + return description + if num_files == 1: + return f"has been {verb}: `{filenames[0]}`." + return f"have been {verb}." + + def describe_public_files_added(self) -> str: + num_files_added = len(self.public_files_added) + analysis = f"{num_files_added} public Python file{_plural_s(num_files_added)} " + analysis += self._describe_files(verb="added", filenames=self.public_files_added) + return analysis + + def describe_typeshed_files_deleted(self) -> str: + num_files_deleted = len(self.typeshed_files_deleted) + analysis = f"{num_files_deleted} file{_plural_s(num_files_deleted)} included in typeshed's stubs " + analysis += self._describe_files(verb="deleted", filenames=self.typeshed_files_deleted) + return analysis + + def describe_typeshed_files_modified(self) -> str: + num_files_modified = len(self.typeshed_files_modified) + analysis = f"{num_files_modified} file{_plural_s(num_files_modified)} included in typeshed's stubs " + analysis += self._describe_files(verb="modified or renamed", filenames=self.typeshed_files_modified) + return analysis + + def __str__(self) -> str: + data_points: list[str] = [] + if self.runtime_definitely_has_consistent_directory_structure_with_typeshed: + data_points += [ + self.describe_public_files_added(), + self.describe_typeshed_files_deleted(), + self.describe_typeshed_files_modified(), + ] + data_points += [ + f"Total lines of Python code added: {self.total_lines_added}.", + f"Total lines of Python code deleted: {self.total_lines_deleted}.", + ] + return "Stubsabot analysis of the diff between the two releases:\n - " + "\n - ".join(data_points) + + +async def analyze_github_diff( + repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession +) -> DiffAnalysis | None: + url = f"https://api.github.com/repos/{repo_path}/compare/{old_tag}...{new_tag}" + async with session.get(url, headers=get_github_api_headers()) as response: + response.raise_for_status() + json_resp: dict[str, list[FileInfo]] = await response.json() + assert isinstance(json_resp, dict) + # https://docs.github.com/en/rest/commits/commits#compare-two-commits + py_files: list[FileInfo] = [file for file in json_resp["files"] if Path(file["filename"]).suffix == ".py"] + stub_path = distribution_path(distribution) + files_in_typeshed = {stub.path for stub in third_party_stubs(distribution)} + py_files_stubbed_in_typeshed = [file for file in py_files if (stub_path / f"{file['filename']}i") in files_in_typeshed] + return DiffAnalysis(py_files=py_files, py_files_stubbed_in_typeshed=py_files_stubbed_in_typeshed) + + +async def analyze_gitlab_diff( + repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession +) -> DiffAnalysis | None: + # https://docs.gitlab.com/api/repositories/#compare-branches-tags-or-commits + project_id = urllib.parse.quote(repo_path, safe="") + url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/compare?from={old_tag}&to={new_tag}" + async with session.get(url) as response: + response.raise_for_status() + json_resp: dict[str, Any] = await response.json() + assert isinstance(json_resp, dict) + + py_files: list[FileInfo] = [] + for file_diff in json_resp["diffs"]: + filename = file_diff["new_path"] + if Path(filename).suffix != ".py": + continue + status: FileStatus + if file_diff["new_file"]: + status = "added" + elif file_diff["renamed_file"]: + status = "renamed" + elif file_diff["deleted_file"]: + status = "removed" + else: + status = "modified" + diff_lines = file_diff["diff"].splitlines() + additions = sum(1 for ln in diff_lines if ln.startswith("+")) + deletions = sum(1 for ln in diff_lines if ln.startswith("-")) + py_files.append(FileInfo(filename=filename, status=status, additions=additions, deletions=deletions)) + + stub_path = distribution_path(distribution) + files_in_typeshed = {stub.path for stub in third_party_stubs(distribution)} + py_files_stubbed_in_typeshed = [file for file in py_files if (stub_path / f"{file['filename']}i") in files_in_typeshed] + return DiffAnalysis(py_files=py_files, py_files_stubbed_in_typeshed=py_files_stubbed_in_typeshed) + + +def _add_months(date: datetime.date, months: int) -> datetime.date: + month = date.month - 1 + months + year = date.year + month // 12 + month = month % 12 + 1 + day = min(date.day, calendar.monthrange(year, month)[1]) + return datetime.date(year, month, day) + + +def obsolete_more_than_n_months(since_date: datetime.date) -> bool: + remove_date = _add_months(since_date, POLICY_MONTHS_DELTA) + today = datetime.datetime.now(tz=datetime.timezone.utc).date() + return remove_date <= today + + +def parse_no_longer_updated_from_archive(source: zipfile.ZipFile | tarfile.TarFile) -> bool: + if isinstance(source, zipfile.ZipFile): + try: + file = source.open("METADATA.toml", "r") + except KeyError: + return False + else: + try: + tarinfo = source.getmember("METADATA.toml") + file = source.extractfile(tarinfo) # type: ignore[assignment] + if file is None: + return False + except KeyError: + return False + + with file as f: + toml_data: dict[str, object] = tomllib.load(f) + + no_longer_updated = toml_data.get("no-longer-updated", False) + assert type(no_longer_updated) is bool + return bool(no_longer_updated) + + +async def has_no_longer_updated_release(release_to_download: PypiReleaseDownload, *, session: aiohttp.ClientSession) -> bool: + """ + Return `True` if the `no_longer_updated` field exists and the value is + `True` in the `METADATA.toml` file of latest `types-{distribution}` pypi release. + """ + return await with_extracted_archive(release_to_download, session=session, handler=parse_no_longer_updated_from_archive) + + +async def determine_action(distribution: str, session: aiohttp.ClientSession) -> Update | NoUpdate | Obsolete | Remove | Error: + try: + return await determine_action_no_error_handling(distribution, session) + except Exception as exc: + return Error(distribution, str(exc)) + + +async def determine_action_no_error_handling( + distribution: str, session: aiohttp.ClientSession +) -> Update | NoUpdate | Obsolete | Remove: + stub_info = read_metadata(distribution) + if stub_info.is_obsolete: + assert type(stub_info.obsolete) is ObsoleteMetadata + since_date = stub_info.obsolete.since_date + + if obsolete_more_than_n_months(since_date): + pypi_info = await fetch_pypi_info(f"types-{stub_info.distribution}", session) + latest_release = pypi_info.get_latest_release() + links = { + "Typeshed release": f"{pypi_info.pypi_root}", + "Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}", + } + return Remove(stub_info.distribution, reason="ships py.typed file", links=links) + else: + return NoUpdate(stub_info.distribution, "obsolete") + if stub_info.no_longer_updated: + pypi_info = await fetch_pypi_info(f"types-{stub_info.distribution}", session) + latest_release = pypi_info.get_latest_release() + + if await has_no_longer_updated_release(latest_release, session=session): + links = { + "Typeshed release": f"{pypi_info.pypi_root}", + "Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}", + } + return Remove(stub_info.distribution, reason="unmaintained", links=links) + else: + return NoUpdate(stub_info.distribution, "no longer updated") + + pypi_info = await fetch_pypi_info(stub_info.distribution, session) + latest_release = pypi_info.get_latest_release() + latest_version = latest_release.version + obsolete_since = await find_first_release_with_py_typed(pypi_info, session=session) + if obsolete_since is None and latest_version in stub_info.version_spec: + return NoUpdate(stub_info.distribution, "up to date") + + relevant_version = obsolete_since.version if obsolete_since else latest_version + + project_urls: dict[str, str] = pypi_info.info["project_urls"] or {} + maybe_links: dict[str, str | None] = { + "Release": f"{pypi_info.pypi_root}/{relevant_version}", + "Homepage": project_urls.get("Homepage"), + "Repository": stub_info.upstream_repository, + "Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}", + "Changelog": project_urls.get("Changelog") or project_urls.get("Changes") or project_urls.get("Change Log"), + } + links = {k: v for k, v in maybe_links.items() if v is not None} + + diff_info = await get_diff_info(session, stub_info, relevant_version) + if diff_info is not None: + links["Diff"] = diff_info.diff_url + + if obsolete_since: + return Obsolete( + stub_info.distribution, + obsolete_since_version=str(obsolete_since.version), + obsolete_since_date=obsolete_since.upload_date, + links=links, + ) + + if diff_info is None: + diff_analysis: DiffAnalysis | None = None + else: + analyze_diff = {"github": analyze_github_diff, "gitlab": analyze_gitlab_diff}[diff_info.host] + diff_analysis = await analyze_diff( + repo_path=diff_info.repo_path, + distribution=distribution, + old_tag=diff_info.old_tag, + new_tag=diff_info.new_tag, + session=session, + ) + + return Update( + distribution=stub_info.distribution, + old_version_spec=stub_info.version_spec, + new_version_spec=get_updated_version_spec(stub_info.version_spec, latest_version), + links=links, + diff_analysis=diff_analysis, + ) + + +@functools.lru_cache +def get_origin_owner() -> str: + output = subprocess.check_output(["git", "remote", "get-url", "origin"], text=True).strip() + match = re.match(r"(git@github.com:|https://github.com/)(?P[^/]+)/(?P[^/\s]+)", output) + assert match is not None, f"Couldn't identify origin's owner: {output!r}" + assert match.group("repo").removesuffix(".git") == "typeshed", f"Unexpected repo: {match.group('repo')!r}" + return match.group("owner") + + +async def create_or_update_pull_request(*, title: str, body: str, branch_name: str, session: aiohttp.ClientSession) -> None: + fork_owner = get_origin_owner() + + async with session.post( + f"{TYPESHED_API_URL}/pulls", + json={"title": title, "body": body, "head": f"{fork_owner}:{branch_name}", "base": "main"}, + headers=get_github_api_headers(), + ) as response: + resp_json = await response.json() + if response.status == HTTPStatus.CREATED: + pr_number = resp_json["number"] + assert isinstance(pr_number, int) + elif response.status == HTTPStatus.UNPROCESSABLE_ENTITY and any( + "A pull request already exists" in e.get("message", "") for e in resp_json.get("errors", []) + ): + pr_number = await update_existing_pull_request(title=title, body=body, branch_name=branch_name, session=session) + else: + response.raise_for_status() + raise AssertionError(f"Unexpected response: {response.status}") + await update_pull_request_label(pr_number=pr_number, session=session) + + +async def find_existing_pr(*, branch_name: str, session: aiohttp.ClientSession) -> int: + fork_owner = get_origin_owner() + + async with session.get( + f"{TYPESHED_API_URL}/pulls", + params={"state": "open", "head": f"{fork_owner}:{branch_name}", "base": "main"}, + headers=get_github_api_headers(), + ) as response: + response.raise_for_status() + resp_json = await response.json() + assert len(resp_json) >= 1 + pr_number = resp_json[0]["number"] + assert isinstance(pr_number, int) + + return pr_number + + +async def update_existing_pull_request(*, title: str, body: str, branch_name: str, session: aiohttp.ClientSession) -> int: + # Find the existing PR + pr_number = await find_existing_pr(branch_name=branch_name, session=session) + # Update the PR's title and body + async with session.patch( + f"{TYPESHED_API_URL}/pulls/{pr_number}", json={"title": title, "body": body}, headers=get_github_api_headers() + ) as response: + response.raise_for_status() + return pr_number + + +async def update_pull_request_label(*, pr_number: int, session: aiohttp.ClientSession) -> None: + # There is no pulls/.../labels endpoint, which is why we need to use the issues endpoint. + async with session.post( + f"{TYPESHED_API_URL}/issues/{pr_number}/labels", json={"labels": [STUBSABOT_LABEL]}, headers=get_github_api_headers() + ) as response: + response.raise_for_status() + + +def remote_branch_exists(branch: str) -> bool: + return ( + subprocess.run(["git", "show-ref", "--verify", "--quiet", f"refs/remotes/origin/{branch}"], check=False).returncode == 0 + ) + + +def has_non_stubsabot_commits(branch: str) -> bool: + assert not branch.startswith("origin/") + + if not remote_branch_exists(branch): + return False + + # commits on origin/branch that are not on branch or are + # patch equivalent to a commit on branch + output = subprocess.check_output( + ["git", "log", "--right-only", "--pretty=%an", "--cherry-pick", f"{branch}...origin/{branch}"], stderr=subprocess.DEVNULL + ) + return bool(set(output.splitlines()) - {b"stubsabot"}) + + +def latest_commit_is_different_to_last_commit_on_origin(branch: str) -> bool: + assert not branch.startswith("origin/") + + if not remote_branch_exists(branch): + return True + + # https://www.git-scm.com/docs/git-range-diff + # If the number of lines is >1, + # it indicates that something about our commit is different to the last commit + # (Could be the commit "content", or the commit message). + commit_comparison = subprocess.run( + ["git", "range-diff", f"origin/{branch}~1..origin/{branch}", "HEAD~1..HEAD"], check=True, capture_output=True + ) + return len(commit_comparison.stdout.splitlines()) > 1 + + +class RemoteConflictError(Exception): + pass + + +def somewhat_safe_force_push(branch: str) -> None: + if has_non_stubsabot_commits(branch): + raise RemoteConflictError(f"origin/{branch} has non-stubsabot changes that are not on {branch}!") + result = subprocess.run(["git", "push", "--quiet", "origin", branch, "--force"], text=True, capture_output=True, check=False) + if result.returncode: + # Capture both streams to suppress stderr on success without losing it on failure + sys.stdout.write(result.stdout) + sys.stderr.write(result.stderr) + result.check_returncode() + + +def normalize(name: str) -> str: + # PEP 503 normalization + return re.sub(r"[-_.]+", "-", name).lower() + + +# lock should be unnecessary, but can't hurt to enforce mutual exclusion +_repo_lock = asyncio.Lock() + +BRANCH_PREFIX = "stubsabot" + + +def get_update_pr_body(update: Update, settings: StubtestSettings) -> str: + body = "\n".join(f"{k}: {v}" for k, v in update.links.items()) + + if update.diff_analysis is not None: + body += f"\n\n{update.diff_analysis}" + + if not settings.skip: + body += textwrap.dedent(""" + + If stubtest fails for this PR: + - Leave this PR open (as a reminder, and to prevent stubsabot from opening another PR) + - Fix stubtest failures in another PR, then close this PR + """) + else: + body += textwrap.dedent(f""" + + :warning: Review this PR manually, as stubtest is skipped in CI for {update.distribution}! + Also check whether stubtest can be reenabled. :warning: + """) + return body + + +def remove_stubs(distribution: str) -> None: + stub_path = distribution_path(distribution) + target_path_prefix = f'"stubs/{distribution}' + + if stub_path.exists() and stub_path.is_dir(): + shutil.rmtree(stub_path) + + with PYRIGHT_CONFIG.open("r", encoding="UTF-8") as f: + lines = f.readlines() + + lines = [line for line in lines if not line.lstrip().startswith(target_path_prefix)] + + with PYRIGHT_CONFIG.open("w", encoding="UTF-8") as f: + f.writelines(lines) + + +def get_commit_message(action: Update | Obsolete | Remove) -> tuple[str, str]: + """Return git commit message title and body.""" + match action: + case Update(): + stubtest_settings = read_stubtest_settings(action.distribution) + return ( + f"[stubsabot] Bump {action.distribution} to {action.new_version}", + get_update_pr_body(action, stubtest_settings), + ) + case Obsolete(): + return ( + f"[stubsabot] Mark {action.distribution} as obsolete since {action.obsolete_since_version}", + "\n".join(f"{k}: {v}" for k, v in action.links.items()), + ) + case Remove(): + return ( + f"[stubsabot] Remove {action.distribution} as {action.reason}", + "\n".join(f"{k}: {v}" for k, v in action.links.items()), + ) + + +def run_action(action: Update | Obsolete | Remove) -> None: + match action: + case Update(): + update_metadata(action.distribution, version=action.new_version) + case Obsolete(): + obsolete_t = cast(dict[str, object], tomlkit.inline_table()) + obsolete_t.update({"version": action.obsolete_since_version, "date": action.obsolete_since_date.date().isoformat()}) + update_metadata(action.distribution, obsolete_since=obsolete_t) + case Remove(): + remove_stubs(action.distribution) + + +_A = TypeVar("_A", bound=Update | Obsolete | Remove) + + +async def process_typeshed_change(action: _A, session: aiohttp.ClientSession, action_level: ActionLevel) -> _A | NoUpdate: + if action_level <= ActionLevel.nothing: + return action + + async with _repo_lock: + branch_name = f"{BRANCH_PREFIX}/{normalize(action.distribution)}" + subprocess.check_call(["git", "checkout", "--quiet", "-B", branch_name, "origin/main"]) + run_action(action) + title, body = get_commit_message(action) + subprocess.check_call(["git", "commit", "--quiet", "--all", "-m", f"{title}\n\n{body}"]) + if action_level <= ActionLevel.local: + return action + if not latest_commit_is_different_to_last_commit_on_origin(branch_name): + pr_number = await find_existing_pr(branch_name=branch_name, session=session) + return NoUpdate(action.distribution, "pr open", pr_number) + somewhat_safe_force_push(branch_name) + if action_level <= ActionLevel.fork: + return action + + await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session) + return action + + +async def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "--action-level", + type=ActionLevel.from_cmd_arg, + default=ActionLevel.everything, + help="Limit actions performed to achieve dry runs for different levels of dryness", + ) + parser.add_argument( + "--action-count-limit", + type=int, + default=None, + help="Limit number of actions performed and the remainder are logged. Useful for testing", + ) + parser.add_argument("distributions", nargs="*", help="Distributions to update, default = all") + args = parser.parse_args() + + if args.distributions: + dists_to_update = args.distributions + else: + dists_to_update = sorted(path.name for path in STUBS_PATH.iterdir()) + + if args.action_level > ActionLevel.nothing: + subprocess.run(["git", "update-index", "--refresh"], capture_output=True, check=False) + diff_result = subprocess.run(["git", "diff-index", "HEAD", "--name-only"], text=True, capture_output=True, check=False) + if diff_result.returncode: + print("Unexpected exception!") + print(diff_result.stdout) + print(diff_result.stderr) + return diff_result.returncode + if diff_result.stdout: + changed_files = ", ".join(repr(line) for line in diff_result.stdout.split("\n") if line) + print(f"Cannot run stubsabot, as uncommitted changes are present in {changed_files}!") + return 1 + + if args.action_level > ActionLevel.fork: + if os.environ.get("GITHUB_TOKEN") is None: + raise ValueError("GITHUB_TOKEN environment variable must be set") + + denylist = {"gdb"} # gdb is not a pypi distribution + + original_branch = subprocess.run( + ["git", "branch", "--show-current"], text=True, capture_output=True, check=True + ).stdout.strip() + + if args.action_level >= ActionLevel.local: + subprocess.check_call(["git", "fetch", "--prune", "--all"]) + + error = False + + try: + conn = aiohttp.TCPConnector(limit_per_host=10) + async with aiohttp.ClientSession(connector=conn) as session: + tasks = [ + asyncio.create_task(determine_action(distribution, session)) + for distribution in dists_to_update + if distribution not in denylist + ] + + action_count = 0 + for task in asyncio.as_completed(tasks): + action = await task + print(f"{action.distribution}... ", end="") + + if isinstance(action, NoUpdate): + print(action) + continue + if isinstance(action, Error): + print(action) + error = True + continue + + if args.action_count_limit is not None and action_count >= args.action_count_limit: + print(action) + print(colored("... but we've reached action count limit", "red")) + continue + action_count += 1 + + try: + action_result = await process_typeshed_change(action, session, action_level=args.action_level) + print(action_result) + continue + except RemoteConflictError as e: + print(colored(f"... but ran into {type(e).__qualname__}: {e}", "red")) + continue + raise AssertionError + finally: + # if you need to cleanup, try: + # git branch -D $(git branch --list 'stubsabot/*') + if args.action_level >= ActionLevel.local and original_branch: + subprocess.check_call(["git", "checkout", "--quiet", original_branch]) + + return 1 if error else 0 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/scripts/sync_protobuf/_utils.py b/scripts/sync_protobuf/_utils.py new file mode 100644 index 000000000000..2af94d3d1c79 --- /dev/null +++ b/scripts/sync_protobuf/_utils.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import subprocess +import sys +from collections.abc import Iterable +from http.client import HTTPResponse +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.request import urlopen +from zipfile import ZipFile + +try: + _mypy_protobuf_version = version("mypy-protobuf") +except PackageNotFoundError: + _mypy_protobuf_version = "unavailable" + +if TYPE_CHECKING: + from _typeshed import StrOrBytesPath, StrPath + +MYPY_PROTOBUF_VERSION = _mypy_protobuf_version + + +def download_file(url: str, destination: Path) -> None: + print(f"Downloading '{url}' to '{destination}'") + resp: HTTPResponse + with urlopen(url) as resp: + destination.write_bytes(resp.read()) + + +def extract_archive(archive_path: StrPath, destination: StrPath) -> None: + print(f"Extracting '{archive_path}' to '{destination}'") + with ZipFile(archive_path) as file_in: + file_in.extractall(destination) + + +def run_protoc( + proto_paths: Iterable[StrPath], mypy_out: StrPath, proto_globs: Iterable[str], cwd: StrOrBytesPath | None = None +) -> str: + """TODO: Describe parameters and return.""" + protoc_version = ( + subprocess.run([sys.executable, "-m", "grpc_tools.protoc", "--version"], capture_output=True, check=False) + .stdout.decode() + .strip() + ) + print() + print(protoc_version) + protoc_args = [ + *[f"--proto_path={proto_path}" for proto_path in proto_paths], + "--mypy_out", + f"relax_strict_optional_primitives:{mypy_out}", + *proto_globs, + ] + print("Running: protoc\n " + "\n ".join(protoc_args) + "\n") + subprocess.run((sys.executable, "-m", "grpc_tools.protoc", *protoc_args), cwd=cwd, check=True) + return protoc_version diff --git a/scripts/sync_protobuf/google_protobuf.py b/scripts/sync_protobuf/google_protobuf.py new file mode 100755 index 000000000000..f285a45d129e --- /dev/null +++ b/scripts/sync_protobuf/google_protobuf.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +""" +Generates the protobuf stubs for the given protobuf version using mypy-protobuf. +Generally, new minor versions are a good time to update the stubs. +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +from _utils import MYPY_PROTOBUF_VERSION, download_file, extract_archive, run_protoc +from ts_utils.metadata import read_metadata, update_metadata +from ts_utils.paths import distribution_path + +# PyPi version has an extra "major" number that the Git version doesn't have +PACKAGE_VERSION = read_metadata("protobuf").version_spec.version[2:] + +STUBS_FOLDER = distribution_path("protobuf").absolute() +ARCHIVE_FILENAME = f"protobuf-{PACKAGE_VERSION}.zip" +ARCHIVE_URL = f"https://github.com/protocolbuffers/protobuf/releases/download/v{PACKAGE_VERSION}/{ARCHIVE_FILENAME}" +EXTRACTED_PACKAGE_DIR = f"protobuf-{PACKAGE_VERSION}" + +VERSION_PATTERN = re.compile(r'def game_version\(\):\n return "(.+?)"') +PROTO_FILE_PATTERN = re.compile(r'"//:(.*)_proto"') + + +def extract_python_version(file_path: Path) -> str: + """Extract the Python version from https://github.com/protocolbuffers/protobuf/blob/main/version.json .""" + with file_path.open(encoding="utf-8") as file: + data: dict[str, Any] = json.load(file) + # The root key will be the protobuf source code version + version = next(iter(data.values()))["languages"]["python"] + assert isinstance(version, str) + return version + + +def extract_proto_file_paths(temp_dir: Path) -> list[str]: + """ + Roughly reproduce the subset of .proto files on the public interface + as described in py_proto_library calls in + https://github.com/protocolbuffers/protobuf/blob/main/python/dist/BUILD.bazel . + """ + with (temp_dir / EXTRACTED_PACKAGE_DIR / "python" / "dist" / "BUILD.bazel").open() as file: + matched_lines = filter(None, (re.search(PROTO_FILE_PATTERN, line) for line in file)) + proto_files = [ + EXTRACTED_PACKAGE_DIR + "/src/google/protobuf/" + match.group(1).replace("compiler_", "compiler/") + ".proto" + for match in matched_lines + ] + return proto_files + + +def main() -> None: + temp_dir = Path(tempfile.mkdtemp()) + # Fetch s2clientprotocol (which contains all the .proto files) + archive_path = temp_dir / ARCHIVE_FILENAME + download_file(ARCHIVE_URL, archive_path) + extract_archive(archive_path, temp_dir) + + # Remove existing pyi + for old_stub in STUBS_FOLDER.rglob("*_pb2.pyi"): + old_stub.unlink() + + protoc_version = run_protoc( + proto_paths=(f"{EXTRACTED_PACKAGE_DIR}/src",), + mypy_out=STUBS_FOLDER, + proto_globs=extract_proto_file_paths(temp_dir), + cwd=temp_dir, + ) + + python_protobuf_version = extract_python_version(temp_dir / EXTRACTED_PACKAGE_DIR / "version.json") + + # Cleanup after ourselves, this is a temp dir, but it can still grow fast if run multiple times + shutil.rmtree(temp_dir) + + update_metadata( + "protobuf", + extra_description=f"""Partially generated using \ +[mypy-protobuf=={MYPY_PROTOBUF_VERSION}](https://github.com/nipunn1313/mypy-protobuf/tree/v{MYPY_PROTOBUF_VERSION}) \ +and {protoc_version} on \ +[protobuf v{PACKAGE_VERSION}](https://github.com/protocolbuffers/protobuf/releases/tag/v{PACKAGE_VERSION}) \ +(python `protobuf=={python_protobuf_version}`).""", + ) + print("Updated protobuf/METADATA.toml") + + # Run pre-commit to cleanup the stubs + subprocess.run((sys.executable, "-m", "pre_commit", "run", "--files", *STUBS_FOLDER.rglob("*_pb2.pyi")), check=False) + + +if __name__ == "__main__": + main() diff --git a/scripts/sync_protobuf/s2clientprotocol.py b/scripts/sync_protobuf/s2clientprotocol.py new file mode 100755 index 000000000000..95fcc2086b8c --- /dev/null +++ b/scripts/sync_protobuf/s2clientprotocol.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +""" +Generates the protobuf stubs for the given s2clientprotocol version using mypy-protobuf. +Generally, new minor versions are a good time to update the stubs. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from _utils import MYPY_PROTOBUF_VERSION, download_file, extract_archive, run_protoc +from ts_utils.metadata import update_metadata +from ts_utils.paths import distribution_path + +# Whenever you update PACKAGE_VERSION here, version should be updated +# in stubs/s2clientprotocol/METADATA.toml and vice-versa. +PACKAGE_VERSION = "c04df4adbe274858a4eb8417175ee32ad02fd609" + +STUBS_FOLDER = distribution_path("s2clientprotocol").absolute() +ARCHIVE_FILENAME = f"{PACKAGE_VERSION}.zip" +ARCHIVE_URL = f"https://github.com/Blizzard/s2client-proto/archive/{ARCHIVE_FILENAME}" +EXTRACTED_PACKAGE_DIR = f"s2client-proto-{PACKAGE_VERSION}" + +VERSION_PATTERN = re.compile(r'def game_version\(\):\n return "(.+?)"') + + +def extract_python_version(file_path: Path) -> str: + """Extract Python version from s2clientprotocol's build file.""" + match = re.search(VERSION_PATTERN, file_path.read_text(encoding="utf-8")) + assert match + return match.group(1) + + +def main() -> None: + temp_dir = Path(tempfile.mkdtemp()) + # Fetch s2clientprotocol (which contains all the .proto files) + archive_path = temp_dir / ARCHIVE_FILENAME + download_file(ARCHIVE_URL, archive_path) + extract_archive(archive_path, temp_dir) + + # Remove existing pyi + for old_stub in STUBS_FOLDER.rglob("*_pb2.pyi"): + old_stub.unlink() + + protoc_version = run_protoc( + proto_paths=(EXTRACTED_PACKAGE_DIR,), + mypy_out=STUBS_FOLDER, + proto_globs=(f"{EXTRACTED_PACKAGE_DIR}/s2clientprotocol/*.proto",), + cwd=temp_dir, + ) + + python_s2_client_proto_version = extract_python_version(temp_dir / EXTRACTED_PACKAGE_DIR / "s2clientprotocol" / "build.py") + + # Cleanup after ourselves, this is a temp dir, but it can still grow fast if run multiple times + shutil.rmtree(temp_dir) + + update_metadata( + "s2clientprotocol", + extra_description=f"""Partially generated using \ +[mypy-protobuf=={MYPY_PROTOBUF_VERSION}](https://github.com/nipunn1313/mypy-protobuf/tree/v{MYPY_PROTOBUF_VERSION}) \ +and {protoc_version} on \ +[s2client-proto {python_s2_client_proto_version}](https://github.com/Blizzard/s2client-proto/tree/{PACKAGE_VERSION}).""", + ) + print("Updated s2clientprotocol/METADATA.toml") + + # Run pre-commit to cleanup the stubs + subprocess.run((sys.executable, "-m", "pre_commit", "run", "--files", *STUBS_FOLDER.rglob("*_pb2.pyi")), check=False) + + +if __name__ == "__main__": + main() diff --git a/scripts/sync_protobuf/tensorflow.py b/scripts/sync_protobuf/tensorflow.py new file mode 100755 index 000000000000..fcb53226636e --- /dev/null +++ b/scripts/sync_protobuf/tensorflow.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +""" +Generates the protobuf stubs for the given tensorflow version using mypy-protobuf. +Generally, new minor versions are a good time to update the stubs. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from _utils import MYPY_PROTOBUF_VERSION, download_file, extract_archive, run_protoc +from ts_utils.metadata import read_metadata, update_metadata +from ts_utils.paths import distribution_path + +PACKAGE_VERSION = read_metadata("tensorflow").version_spec.version + +STUBS_FOLDER = distribution_path("tensorflow").absolute() +ARCHIVE_FILENAME = f"v{PACKAGE_VERSION}.zip" +ARCHIVE_URL = f"https://github.com/tensorflow/tensorflow/archive/refs/tags/{ARCHIVE_FILENAME}" +EXTRACTED_PACKAGE_DIR = f"tensorflow-{PACKAGE_VERSION}" + +PROTOS_TO_REMOVE = ( + "compiler/xla/autotune_results_pb2.pyi", + "compiler/xla/autotuning_pb2.pyi", + "compiler/xla/service/buffer_assignment_pb2.pyi", + "compiler/xla/service/hlo_execution_profile_data_pb2.pyi", + "core/protobuf/autotuning_pb2.pyi", + "core/protobuf/conv_autotuning_pb2.pyi", + "core/protobuf/critical_section_pb2.pyi", + "core/protobuf/eager_service_pb2.pyi", + "core/protobuf/master_pb2.pyi", + "core/protobuf/master_service_pb2.pyi", + "core/protobuf/replay_log_pb2.pyi", + "core/protobuf/tpu/compile_metadata_pb2.pyi", + "core/protobuf/worker_pb2.pyi", + "core/protobuf/worker_service_pb2.pyi", + "core/util/example_proto_fast_parsing_test_pb2.pyi", +) +""" +These protos exist in a folder with protos used in python, +but are not included in the python wheel. +They are likely only used for other language builds. +stubtest was used to identify them by looking for ModuleNotFoundError. +(comment out ".*_pb2.*" from the allowlist) +""" + +TSL_IMPORT_PATTERN = re.compile(r"(\[|\s)tsl\.") +XLA_IMPORT_PATTERN = re.compile(r"(\[|\s)xla\.") + + +def move_tree(source: Path, destination: Path) -> None: + """Move directory and merge if destination already exists. + + Can't use shutil.move because it can't merge existing directories. + """ + print(f"Moving '{source}' to '{destination}'") + shutil.copytree(source, destination, dirs_exist_ok=True) + shutil.rmtree(source) + + +def post_creation() -> None: + """Move third-party and fix imports.""" + print() + move_tree(STUBS_FOLDER / "tsl", STUBS_FOLDER / "tensorflow" / "tsl") + move_tree(STUBS_FOLDER / "xla", STUBS_FOLDER / "tensorflow" / "compiler" / "xla") + + for path in STUBS_FOLDER.rglob("*_pb2.pyi"): + print(f"Fixing imports in '{path}'") + filedata = path.read_text(encoding="utf-8") + + # Replace the target string + filedata = re.sub(TSL_IMPORT_PATTERN, "\\1tensorflow.tsl.", filedata) + filedata = re.sub(XLA_IMPORT_PATTERN, "\\1tensorflow.compiler.xla.", filedata) + + # Write the file out again + path.write_text(filedata, encoding="utf-8") + + print() + for to_remove in PROTOS_TO_REMOVE: + file_path = STUBS_FOLDER / "tensorflow" / to_remove + file_path.unlink() + print(f"Removed '{file_path}'") + + +def main() -> None: + temp_dir = Path(tempfile.mkdtemp()) + # Fetch tensorflow (which contains all the .proto files) + archive_path = temp_dir / ARCHIVE_FILENAME + download_file(ARCHIVE_URL, archive_path) + extract_archive(archive_path, temp_dir) + + # Remove existing pyi + for old_stub in STUBS_FOLDER.rglob("*_pb2.pyi"): + old_stub.unlink() + + protoc_version = run_protoc( + proto_paths=( + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/third_party/tsl", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla", + f"{EXTRACTED_PACKAGE_DIR}", + ), + mypy_out=STUBS_FOLDER, + proto_globs=( + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/xla/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/xla/service/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/xla/tsl/protobuf/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/example/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/framework/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/protobuf/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/protobuf/tpu/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/util/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/python/keras/protobuf/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/third_party/tsl/tsl/protobuf/*.proto", + ), + cwd=temp_dir, + ) + + # Cleanup after ourselves, this is a temp dir, but it can still grow fast if run multiple times + shutil.rmtree(temp_dir) + + post_creation() + + update_metadata( + "tensorflow", + extra_description=f"""Partially generated using \ +[mypy-protobuf=={MYPY_PROTOBUF_VERSION}](https://github.com/nipunn1313/mypy-protobuf/tree/v{MYPY_PROTOBUF_VERSION}) \ +and {protoc_version} on `tensorflow=={PACKAGE_VERSION}`.""", + ) + print("Updated tensorflow/METADATA.toml") + + # Run pre-commit to cleanup the stubs + subprocess.run((sys.executable, "-m", "pre_commit", "run", "--files", *STUBS_FOLDER.rglob("*_pb2.pyi")), check=False) + + +if __name__ == "__main__": + main() diff --git a/scripts/update-stubtest-allowlist.py b/scripts/update-stubtest-allowlist.py deleted file mode 100755 index 0d9c44e6c375..000000000000 --- a/scripts/update-stubtest-allowlist.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python3 - -# This script removes lines from stubtest allowlists, according to -# an input file. The input file has one entry to remove per line. -# Each line consists of a allowlist filename and an entry, separated -# by a colon. - -# This script is used by the workflow to remove unused allowlist entries. - -import sys -from collections import defaultdict -from typing import Dict, List, Set, Tuple - - -def main() -> None: - if len(sys.argv) != 2: - print(f"Usage: {sys.argv[0]} FILENAME", file=sys.stderr) - sys.exit(1) - - to_remove = parse_input_file(sys.argv[1]) - for filename, entries in to_remove.items(): - remove_entries_from_allowlist(filename, entries) - - -def parse_input_file(input_file: str) -> Dict[str, Set[str]]: - to_remove = defaultdict(set) - with open(input_file) as f: - for filename, wl_entry in [parse_input_line(li) for li in f if li.strip()]: - to_remove[filename].add(wl_entry) - return to_remove - - -# Returns a (filename, entry) tuple. -def parse_input_line(line: str) -> Tuple[str, str]: - line = line.strip() - filename, entry = line.split(":", maxsplit=1) - return filename, entry - - -def remove_entries_from_allowlist(filename: str, entries: Set[str]) -> None: - new_lines: List[str] = [] - with open(filename) as f: - for line in f: - entry = line.split("#")[0].strip() - if entry in entries: - entries.remove(entry) - else: - new_lines.append(line) - if entries: - print(f"WARNING: The following entries were not found in '{filename}':", file=sys.stderr) - for entry in entries: - print(f" * {entry}") - with open(filename, "w") as f: - for line in new_lines: - f.write(line) - - -if __name__ == "__main__": - main() diff --git a/stdlib/@python2/BaseHTTPServer.pyi b/stdlib/@python2/BaseHTTPServer.pyi deleted file mode 100644 index 46946aa37c46..000000000000 --- a/stdlib/@python2/BaseHTTPServer.pyi +++ /dev/null @@ -1,41 +0,0 @@ -import mimetools -import SocketServer -from typing import Any, BinaryIO, Callable, Mapping, Tuple - -class HTTPServer(SocketServer.TCPServer): - server_name: str - server_port: int - def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... - -class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): - client_address: Tuple[str, int] - server: SocketServer.BaseServer - close_connection: bool - command: str - path: str - request_version: str - headers: mimetools.Message - rfile: BinaryIO - wfile: BinaryIO - server_version: str - sys_version: str - error_message_format: str - error_content_type: str - protocol_version: str - MessageClass: type - responses: Mapping[int, Tuple[str, str]] - def __init__(self, request: bytes, client_address: Tuple[str, int], server: SocketServer.BaseServer) -> None: ... - def handle(self) -> None: ... - def handle_one_request(self) -> None: ... - def send_error(self, code: int, message: str | None = ...) -> None: ... - def send_response(self, code: int, message: str | None = ...) -> None: ... - def send_header(self, keyword: str, value: str) -> None: ... - def end_headers(self) -> None: ... - def flush_headers(self) -> None: ... - def log_request(self, code: int | str = ..., size: int | str = ...) -> None: ... - def log_error(self, format: str, *args: Any) -> None: ... - def log_message(self, format: str, *args: Any) -> None: ... - def version_string(self) -> str: ... - def date_time_string(self, timestamp: int | None = ...) -> str: ... - def log_date_time_string(self) -> str: ... - def address_string(self) -> str: ... diff --git a/stdlib/@python2/CGIHTTPServer.pyi b/stdlib/@python2/CGIHTTPServer.pyi deleted file mode 100644 index 393dcb83217f..000000000000 --- a/stdlib/@python2/CGIHTTPServer.pyi +++ /dev/null @@ -1,6 +0,0 @@ -import SimpleHTTPServer -from typing import List - -class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - cgi_directories: List[str] - def do_POST(self) -> None: ... diff --git a/stdlib/@python2/ConfigParser.pyi b/stdlib/@python2/ConfigParser.pyi deleted file mode 100644 index 89167b3e7ec8..000000000000 --- a/stdlib/@python2/ConfigParser.pyi +++ /dev/null @@ -1,97 +0,0 @@ -from _typeshed import SupportsNoArgReadline -from typing import IO, Any, Dict, List, Sequence, Tuple - -DEFAULTSECT: str -MAX_INTERPOLATION_DEPTH: int - -class Error(Exception): - message: Any - def __init__(self, msg: str = ...) -> None: ... - def _get_message(self) -> None: ... - def _set_message(self, value: str) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - -class NoSectionError(Error): - section: str - def __init__(self, section: str) -> None: ... - -class DuplicateSectionError(Error): - section: str - def __init__(self, section: str) -> None: ... - -class NoOptionError(Error): - section: str - option: str - def __init__(self, option: str, section: str) -> None: ... - -class InterpolationError(Error): - section: str - option: str - msg: str - def __init__(self, option: str, section: str, msg: str) -> None: ... - -class InterpolationMissingOptionError(InterpolationError): - reference: str - def __init__(self, option: str, section: str, rawval: str, reference: str) -> None: ... - -class InterpolationSyntaxError(InterpolationError): ... - -class InterpolationDepthError(InterpolationError): - def __init__(self, option: str, section: str, rawval: str) -> None: ... - -class ParsingError(Error): - filename: str - errors: List[Tuple[Any, Any]] - def __init__(self, filename: str) -> None: ... - def append(self, lineno: Any, line: Any) -> None: ... - -class MissingSectionHeaderError(ParsingError): - lineno: Any - line: Any - def __init__(self, filename: str, lineno: Any, line: Any) -> None: ... - -class RawConfigParser: - _dict: Any - _sections: Dict[Any, Any] - _defaults: Dict[Any, Any] - _optcre: Any - SECTCRE: Any - OPTCRE: Any - OPTCRE_NV: Any - def __init__(self, defaults: Dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... - def defaults(self) -> Dict[Any, Any]: ... - def sections(self) -> List[str]: ... - def add_section(self, section: str) -> None: ... - def has_section(self, section: str) -> bool: ... - def options(self, section: str) -> List[str]: ... - def read(self, filenames: str | Sequence[str]) -> List[str]: ... - def readfp(self, fp: SupportsNoArgReadline[str], filename: str = ...) -> None: ... - def get(self, section: str, option: str) -> str: ... - def items(self, section: str) -> List[Tuple[Any, Any]]: ... - def _get(self, section: str, conv: type, option: str) -> Any: ... - def getint(self, section: str, option: str) -> int: ... - def getfloat(self, section: str, option: str) -> float: ... - _boolean_states: Dict[str, bool] - def getboolean(self, section: str, option: str) -> bool: ... - def optionxform(self, optionstr: str) -> str: ... - def has_option(self, section: str, option: str) -> bool: ... - def set(self, section: str, option: str, value: Any = ...) -> None: ... - def write(self, fp: IO[str]) -> None: ... - def remove_option(self, section: str, option: Any) -> bool: ... - def remove_section(self, section: str) -> bool: ... - def _read(self, fp: IO[str], fpname: str) -> None: ... - -class ConfigParser(RawConfigParser): - _KEYCRE: Any - def get(self, section: str, option: str, raw: bool = ..., vars: Dict[Any, Any] | None = ...) -> Any: ... - def items(self, section: str, raw: bool = ..., vars: Dict[Any, Any] | None = ...) -> List[Tuple[str, Any]]: ... - def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... - def _interpolation_replace(self, match: Any) -> str: ... - -class SafeConfigParser(ConfigParser): - _interpvar_re: Any - def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... - def _interpolate_some( - self, option: str, accum: List[Any], rest: str, section: str, map: Dict[Any, Any], depth: int - ) -> None: ... diff --git a/stdlib/@python2/Cookie.pyi b/stdlib/@python2/Cookie.pyi deleted file mode 100644 index 3d01c3c66152..000000000000 --- a/stdlib/@python2/Cookie.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Any, Dict - -class CookieError(Exception): ... - -class Morsel(Dict[Any, Any]): - key: Any - def __init__(self): ... - def __setitem__(self, K, V): ... - def isReservedKey(self, K): ... - value: Any - coded_value: Any - def set(self, key, val, coded_val, LegalChars=..., idmap=..., translate=...): ... - def output(self, attrs: Any | None = ..., header=...): ... - def js_output(self, attrs: Any | None = ...): ... - def OutputString(self, attrs: Any | None = ...): ... - -class BaseCookie(Dict[Any, Any]): - def value_decode(self, val): ... - def value_encode(self, val): ... - def __init__(self, input: Any | None = ...): ... - def __setitem__(self, key, value): ... - def output(self, attrs: Any | None = ..., header=..., sep=...): ... - def js_output(self, attrs: Any | None = ...): ... - def load(self, rawdata): ... - -class SimpleCookie(BaseCookie): - def value_decode(self, val): ... - def value_encode(self, val): ... - -class SerialCookie(BaseCookie): - def __init__(self, input: Any | None = ...): ... - def value_decode(self, val): ... - def value_encode(self, val): ... - -class SmartCookie(BaseCookie): - def __init__(self, input: Any | None = ...): ... - def value_decode(self, val): ... - def value_encode(self, val): ... - -Cookie: Any diff --git a/stdlib/@python2/HTMLParser.pyi b/stdlib/@python2/HTMLParser.pyi deleted file mode 100644 index ebc2735e9c48..000000000000 --- a/stdlib/@python2/HTMLParser.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import AnyStr, List, Tuple - -from markupbase import ParserBase - -class HTMLParser(ParserBase): - def __init__(self) -> None: ... - def feed(self, feed: AnyStr) -> None: ... - def close(self) -> None: ... - def reset(self) -> None: ... - def get_starttag_text(self) -> AnyStr: ... - def set_cdata_mode(self, AnyStr) -> None: ... - def clear_cdata_mode(self) -> None: ... - def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... - def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... - def handle_endtag(self, tag: AnyStr): ... - def handle_charref(self, name: AnyStr): ... - def handle_entityref(self, name: AnyStr): ... - def handle_data(self, data: AnyStr): ... - def handle_comment(self, data: AnyStr): ... - def handle_decl(self, decl: AnyStr): ... - def handle_pi(self, data: AnyStr): ... - def unknown_decl(self, data: AnyStr): ... - def unescape(self, s: AnyStr) -> AnyStr: ... - -class HTMLParseError(Exception): - msg: str - lineno: int - offset: int diff --git a/stdlib/@python2/Queue.pyi b/stdlib/@python2/Queue.pyi deleted file mode 100644 index 24743a80280d..000000000000 --- a/stdlib/@python2/Queue.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any, Deque, Generic, TypeVar - -_T = TypeVar("_T") - -class Empty(Exception): ... -class Full(Exception): ... - -class Queue(Generic[_T]): - maxsize: Any - mutex: Any - not_empty: Any - not_full: Any - all_tasks_done: Any - unfinished_tasks: Any - queue: Deque[Any] # undocumented - def __init__(self, maxsize: int = ...) -> None: ... - def task_done(self) -> None: ... - def join(self) -> None: ... - def qsize(self) -> int: ... - def empty(self) -> bool: ... - def full(self) -> bool: ... - def put(self, item: _T, block: bool = ..., timeout: float | None = ...) -> None: ... - def put_nowait(self, item: _T) -> None: ... - def get(self, block: bool = ..., timeout: float | None = ...) -> _T: ... - def get_nowait(self) -> _T: ... - -class PriorityQueue(Queue[_T]): ... -class LifoQueue(Queue[_T]): ... diff --git a/stdlib/@python2/SimpleHTTPServer.pyi b/stdlib/@python2/SimpleHTTPServer.pyi deleted file mode 100644 index 758d5bd6d515..000000000000 --- a/stdlib/@python2/SimpleHTTPServer.pyi +++ /dev/null @@ -1,14 +0,0 @@ -import BaseHTTPServer -from StringIO import StringIO -from typing import IO, Any, AnyStr, Mapping - -class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): - server_version: str - def do_GET(self) -> None: ... - def do_HEAD(self) -> None: ... - def send_head(self) -> IO[str] | None: ... - def list_directory(self, path: str | unicode) -> StringIO[Any] | None: ... - def translate_path(self, path: AnyStr) -> AnyStr: ... - def copyfile(self, source: IO[AnyStr], outputfile: IO[AnyStr]): ... - def guess_type(self, path: str | unicode) -> str: ... - extensions_map: Mapping[str, str] diff --git a/stdlib/@python2/SocketServer.pyi b/stdlib/@python2/SocketServer.pyi deleted file mode 100644 index e5a19ffd5e68..000000000000 --- a/stdlib/@python2/SocketServer.pyi +++ /dev/null @@ -1,114 +0,0 @@ -import sys -from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, List, Text, Tuple, Union - -class BaseServer: - address_family: int - RequestHandlerClass: Callable[..., BaseRequestHandler] - server_address: Tuple[str, int] - socket: SocketType - allow_reuse_address: bool - request_queue_size: int - socket_type: int - timeout: float | None - def __init__(self, server_address: Any, RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... - def fileno(self) -> int: ... - def handle_request(self) -> None: ... - def serve_forever(self, poll_interval: float = ...) -> None: ... - def shutdown(self) -> None: ... - def server_close(self) -> None: ... - def finish_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - def get_request(self) -> Tuple[SocketType, Tuple[str, int]]: ... - def handle_error(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - def handle_timeout(self) -> None: ... - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - def server_activate(self) -> None: ... - def server_bind(self) -> None: ... - def verify_request(self, request: bytes, client_address: Tuple[str, int]) -> bool: ... - -class TCPServer(BaseServer): - def __init__( - self, - server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., - ) -> None: ... - -class UDPServer(BaseServer): - def __init__( - self, - server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., - ) -> None: ... - -if sys.platform != "win32": - class UnixStreamServer(BaseServer): - def __init__( - self, - server_address: Text | bytes, - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., - ) -> None: ... - class UnixDatagramServer(BaseServer): - def __init__( - self, - server_address: Text | bytes, - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., - ) -> None: ... - -if sys.platform != "win32": - class ForkingMixIn: - timeout: float | None # undocumented - active_children: List[int] | None # undocumented - max_children: int # undocumented - def collect_children(self) -> None: ... # undocumented - def handle_timeout(self) -> None: ... # undocumented - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - -class ThreadingMixIn: - daemon_threads: bool - def process_request_thread(self, request: bytes, client_address: Tuple[str, int]) -> None: ... # undocumented - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - -if sys.platform != "win32": - class ForkingTCPServer(ForkingMixIn, TCPServer): ... - class ForkingUDPServer(ForkingMixIn, UDPServer): ... - -class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... -class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... - -if sys.platform != "win32": - class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... - class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... - -class BaseRequestHandler: - # Those are technically of types, respectively: - # * Union[SocketType, Tuple[bytes, SocketType]] - # * Union[Tuple[str, int], str] - # But there are some concerns that having unions here would cause - # too much inconvenience to people using it (see - # https://github.com/python/typeshed/pull/384#issuecomment-234649696) - request: Any - client_address: Any - server: BaseServer - def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... - def setup(self) -> None: ... - def handle(self) -> None: ... - def finish(self) -> None: ... - -class StreamRequestHandler(BaseRequestHandler): - rbufsize: ClassVar[int] # undocumented - wbufsize: ClassVar[int] # undocumented - timeout: ClassVar[float | None] # undocumented - disable_nagle_algorithm: ClassVar[bool] # undocumented - connection: SocketType # undocumented - rfile: BinaryIO - wfile: BinaryIO - -class DatagramRequestHandler(BaseRequestHandler): - packet: SocketType # undocumented - socket: SocketType # undocumented - rfile: BinaryIO - wfile: BinaryIO diff --git a/stdlib/@python2/StringIO.pyi b/stdlib/@python2/StringIO.pyi deleted file mode 100644 index efa90f8e0330..000000000000 --- a/stdlib/@python2/StringIO.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List - -class StringIO(IO[AnyStr], Generic[AnyStr]): - closed: bool - softspace: int - len: int - name: str - def __init__(self, buf: AnyStr = ...) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... - def next(self) -> AnyStr: ... - def close(self) -> None: ... - def isatty(self) -> bool: ... - def seek(self, pos: int, mode: int = ...) -> int: ... - def tell(self) -> int: ... - def read(self, n: int = ...) -> AnyStr: ... - def readline(self, length: int = ...) -> AnyStr: ... - def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... - def truncate(self, size: int | None = ...) -> int: ... - def write(self, s: AnyStr) -> int: ... - def writelines(self, iterable: Iterable[AnyStr]) -> None: ... - def flush(self) -> None: ... - def getvalue(self) -> AnyStr: ... - def __enter__(self) -> Any: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> Any: ... - def fileno(self) -> int: ... - def readable(self) -> bool: ... - def seekable(self) -> bool: ... - def writable(self) -> bool: ... diff --git a/stdlib/@python2/UserDict.pyi b/stdlib/@python2/UserDict.pyi deleted file mode 100644 index dce7bebafd66..000000000000 --- a/stdlib/@python2/UserDict.pyi +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any, Container, Dict, Generic, Iterable, Iterator, List, Mapping, Sized, Tuple, TypeVar, overload - -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") -_T = TypeVar("_T") - -class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): - data: Dict[_KT, _VT] - def __init__(self, initialdata: Mapping[_KT, _VT] = ...) -> None: ... - # TODO: __iter__ is not available for UserDict - -class IterableUserDict(UserDict[_KT, _VT], Generic[_KT, _VT]): ... - -class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): - def has_key(self, key: _KT) -> bool: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_KT]: ... - # From typing.Mapping[_KT, _VT] - # (can't inherit because of keys()) - @overload - def get(self, k: _KT) -> _VT | None: ... - @overload - def get(self, k: _KT, default: _VT | _T) -> _VT | _T: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def __contains__(self, o: Any) -> bool: ... - # From typing.MutableMapping[_KT, _VT] - def clear(self) -> None: ... - def pop(self, k: _KT, default: _VT = ...) -> _VT: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... - @overload - def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... diff --git a/stdlib/@python2/UserList.pyi b/stdlib/@python2/UserList.pyi deleted file mode 100644 index be4ebce5a815..000000000000 --- a/stdlib/@python2/UserList.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Iterable, List, MutableSequence, TypeVar, overload - -_T = TypeVar("_T") -_S = TypeVar("_S") - -class UserList(MutableSequence[_T]): - data: List[_T] - def insert(self, index: int, object: _T) -> None: ... - @overload - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __len__(self) -> int: ... - @overload - def __getitem__(self, i: int) -> _T: ... - @overload - def __getitem__(self: _S, s: slice) -> _S: ... - def sort(self) -> None: ... diff --git a/stdlib/@python2/UserString.pyi b/stdlib/@python2/UserString.pyi deleted file mode 100644 index f60dbe18f9b1..000000000000 --- a/stdlib/@python2/UserString.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from typing import Any, Iterable, List, MutableSequence, Sequence, Text, Tuple, TypeVar, overload - -_UST = TypeVar("_UST", bound=UserString) -_MST = TypeVar("_MST", bound=MutableString) - -class UserString(Sequence[UserString]): - data: unicode - def __init__(self, seq: object) -> None: ... - def __int__(self) -> int: ... - def __long__(self) -> long: ... - def __float__(self) -> float: ... - def __complex__(self) -> complex: ... - def __hash__(self) -> int: ... - def __len__(self) -> int: ... - @overload - def __getitem__(self: _UST, i: int) -> _UST: ... - @overload - def __getitem__(self: _UST, s: slice) -> _UST: ... - def __add__(self: _UST, other: Any) -> _UST: ... - def __radd__(self: _UST, other: Any) -> _UST: ... - def __mul__(self: _UST, other: int) -> _UST: ... - def __rmul__(self: _UST, other: int) -> _UST: ... - def __mod__(self: _UST, args: Any) -> _UST: ... - def capitalize(self: _UST) -> _UST: ... - def center(self: _UST, width: int, *args: Any) -> _UST: ... - def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... - def decode(self: _UST, encoding: str | None = ..., errors: str | None = ...) -> _UST: ... - def encode(self: _UST, encoding: str | None = ..., errors: str | None = ...) -> _UST: ... - def endswith(self, suffix: Text | Tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... - def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def isalpha(self) -> bool: ... - def isalnum(self) -> bool: ... - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isnumeric(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, seq: Iterable[Text]) -> Text: ... - def ljust(self: _UST, width: int, *args: Any) -> _UST: ... - def lower(self: _UST) -> _UST: ... - def lstrip(self: _UST, chars: Text | None = ...) -> _UST: ... - def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... - def rfind(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UST, width: int, *args: Any) -> _UST: ... - def rpartition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def rstrip(self: _UST, chars: Text | None = ...) -> _UST: ... - def split(self, sep: Text | None = ..., maxsplit: int = ...) -> List[Text]: ... - def rsplit(self, sep: Text | None = ..., maxsplit: int = ...) -> List[Text]: ... - def splitlines(self, keepends: int = ...) -> List[Text]: ... - def startswith(self, prefix: Text | Tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UST, chars: Text | None = ...) -> _UST: ... - def swapcase(self: _UST) -> _UST: ... - def title(self: _UST) -> _UST: ... - def translate(self: _UST, *args: Any) -> _UST: ... - def upper(self: _UST) -> _UST: ... - def zfill(self: _UST, width: int) -> _UST: ... - -class MutableString(UserString, MutableSequence[MutableString]): - @overload - def __getitem__(self: _MST, i: int) -> _MST: ... - @overload - def __getitem__(self: _MST, s: slice) -> _MST: ... - def __setitem__(self, index: int | slice, sub: Any) -> None: ... - def __delitem__(self, index: int | slice) -> None: ... - def immutable(self) -> UserString: ... - def __iadd__(self: _MST, other: Any) -> _MST: ... - def __imul__(self, n: int) -> _MST: ... - def insert(self, index: int, value: Any) -> None: ... diff --git a/stdlib/@python2/__builtin__.pyi b/stdlib/@python2/__builtin__.pyi deleted file mode 100644 index fad8b2b4e7d8..000000000000 --- a/stdlib/@python2/__builtin__.pyi +++ /dev/null @@ -1,1187 +0,0 @@ -# True and False are deliberately omitted because they are keywords in -# Python 3, and stub files conform to Python 3 syntax. - -from _typeshed import ReadableBuffer, SupportsKeysAndGetItem, SupportsWrite -from abc import ABCMeta -from ast import mod -from types import CodeType -from typing import ( - AbstractSet, - Any, - AnyStr, - BinaryIO, - ByteString, - Callable, - Container, - Dict, - FrozenSet, - Generic, - ItemsView, - Iterable, - Iterator, - KeysView, - List, - Mapping, - MutableMapping, - MutableSequence, - MutableSet, - NoReturn, - Protocol, - Reversible, - Sequence, - Set, - Sized, - SupportsAbs, - SupportsComplex, - SupportsFloat, - SupportsInt, - Text, - Tuple, - Type, - TypeVar, - ValuesView, - overload, -) -from typing_extensions import Literal, final - -class _SupportsIndex(Protocol): - def __index__(self) -> int: ... - -class _SupportsTrunc(Protocol): - def __trunc__(self) -> int: ... - -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") -_S = TypeVar("_S") -_T1 = TypeVar("_T1") -_T2 = TypeVar("_T2") -_T3 = TypeVar("_T3") -_T4 = TypeVar("_T4") -_T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") - -class object: - __doc__: str | None - __dict__: Dict[str, Any] - __slots__: Text | Iterable[Text] - __module__: str - @property - def __class__(self: _T) -> Type[_T]: ... - @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 - def __init__(self) -> None: ... - def __new__(cls) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __eq__(self, o: object) -> bool: ... - def __ne__(self, o: object) -> bool: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __hash__(self) -> int: ... - def __format__(self, format_spec: str) -> str: ... - def __getattribute__(self, name: str) -> Any: ... - def __delattr__(self, name: str) -> None: ... - def __sizeof__(self) -> int: ... - def __reduce__(self) -> str | Tuple[Any, ...]: ... - def __reduce_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... - -class staticmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] - def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... - -class classmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] - def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... - -class type(object): - __base__: type - __bases__: Tuple[type, ...] - __basicsize__: int - __dict__: Dict[str, Any] - __dictoffset__: int - __flags__: int - __itemsize__: int - __module__: str - __mro__: Tuple[type, ...] - __name__: str - __weakrefoffset__: int - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... - @overload - def __new__(cls, o: object) -> type: ... - @overload - def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... - def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> List[_TT]: ... - # Note: the documentation doesn't specify what the return type is, the standard - # implementation seems to be returning a list. - def mro(self) -> List[type]: ... - def __instancecheck__(self, instance: Any) -> bool: ... - def __subclasscheck__(self, subclass: type) -> bool: ... - -class super(object): - @overload - def __init__(self, t: Any, obj: Any) -> None: ... - @overload - def __init__(self, t: Any) -> None: ... - -class int: - @overload - def __new__(cls: Type[_T], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> _T: ... - @overload - def __new__(cls: Type[_T], x: Text | bytes | bytearray, base: int) -> _T: ... - @property - def real(self) -> int: ... - @property - def imag(self) -> int: ... - @property - def numerator(self) -> int: ... - @property - def denominator(self) -> int: ... - def conjugate(self) -> int: ... - def bit_length(self) -> int: ... - def __add__(self, x: int) -> int: ... - def __sub__(self, x: int) -> int: ... - def __mul__(self, x: int) -> int: ... - def __floordiv__(self, x: int) -> int: ... - def __div__(self, x: int) -> int: ... - def __truediv__(self, x: int) -> float: ... - def __mod__(self, x: int) -> int: ... - def __divmod__(self, x: int) -> Tuple[int, int]: ... - def __radd__(self, x: int) -> int: ... - def __rsub__(self, x: int) -> int: ... - def __rmul__(self, x: int) -> int: ... - def __rfloordiv__(self, x: int) -> int: ... - def __rdiv__(self, x: int) -> int: ... - def __rtruediv__(self, x: int) -> float: ... - def __rmod__(self, x: int) -> int: ... - def __rdivmod__(self, x: int) -> Tuple[int, int]: ... - @overload - def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... - @overload - def __pow__(self, __x: int, __modulo: int | None = ...) -> Any: ... # Return type can be int or float, depending on x. - def __rpow__(self, x: int, mod: int | None = ...) -> Any: ... - def __and__(self, n: int) -> int: ... - def __or__(self, n: int) -> int: ... - def __xor__(self, n: int) -> int: ... - def __lshift__(self, n: int) -> int: ... - def __rshift__(self, n: int) -> int: ... - def __rand__(self, n: int) -> int: ... - def __ror__(self, n: int) -> int: ... - def __rxor__(self, n: int) -> int: ... - def __rlshift__(self, n: int) -> int: ... - def __rrshift__(self, n: int) -> int: ... - def __neg__(self) -> int: ... - def __pos__(self) -> int: ... - def __invert__(self) -> int: ... - def __trunc__(self) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: int) -> bool: ... - def __le__(self, x: int) -> bool: ... - def __gt__(self, x: int) -> bool: ... - def __ge__(self, x: int) -> bool: ... - def __str__(self) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - def __abs__(self) -> int: ... - def __hash__(self) -> int: ... - def __nonzero__(self) -> bool: ... - def __index__(self) -> int: ... - -class float: - def __new__(cls: Type[_T], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> _T: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... - def hex(self) -> str: ... - def is_integer(self) -> bool: ... - @classmethod - def fromhex(cls, __s: str) -> float: ... - @property - def real(self) -> float: ... - @property - def imag(self) -> float: ... - def conjugate(self) -> float: ... - def __add__(self, x: float) -> float: ... - def __sub__(self, x: float) -> float: ... - def __mul__(self, x: float) -> float: ... - def __floordiv__(self, x: float) -> float: ... - def __div__(self, x: float) -> float: ... - def __truediv__(self, x: float) -> float: ... - def __mod__(self, x: float) -> float: ... - def __divmod__(self, x: float) -> Tuple[float, float]: ... - def __pow__( - self, x: float, mod: None = ... - ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole - def __radd__(self, x: float) -> float: ... - def __rsub__(self, x: float) -> float: ... - def __rmul__(self, x: float) -> float: ... - def __rfloordiv__(self, x: float) -> float: ... - def __rdiv__(self, x: float) -> float: ... - def __rtruediv__(self, x: float) -> float: ... - def __rmod__(self, x: float) -> float: ... - def __rdivmod__(self, x: float) -> Tuple[float, float]: ... - def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... - def __trunc__(self) -> int: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: float) -> bool: ... - def __le__(self, x: float) -> bool: ... - def __gt__(self, x: float) -> bool: ... - def __ge__(self, x: float) -> bool: ... - def __neg__(self) -> float: ... - def __pos__(self) -> float: ... - def __str__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __abs__(self) -> float: ... - def __hash__(self) -> int: ... - def __nonzero__(self) -> bool: ... - -class complex: - @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... - @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | _SupportsIndex) -> _T: ... - @property - def real(self) -> float: ... - @property - def imag(self) -> float: ... - def conjugate(self) -> complex: ... - def __add__(self, x: complex) -> complex: ... - def __sub__(self, x: complex) -> complex: ... - def __mul__(self, x: complex) -> complex: ... - def __pow__(self, x: complex, mod: None = ...) -> complex: ... - def __div__(self, x: complex) -> complex: ... - def __truediv__(self, x: complex) -> complex: ... - def __radd__(self, x: complex) -> complex: ... - def __rsub__(self, x: complex) -> complex: ... - def __rmul__(self, x: complex) -> complex: ... - def __rpow__(self, x: complex, mod: None = ...) -> complex: ... - def __rdiv__(self, x: complex) -> complex: ... - def __rtruediv__(self, x: complex) -> complex: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __neg__(self) -> complex: ... - def __pos__(self) -> complex: ... - def __str__(self) -> str: ... - def __complex__(self) -> complex: ... - def __abs__(self) -> float: ... - def __hash__(self) -> int: ... - def __nonzero__(self) -> bool: ... - -class basestring(metaclass=ABCMeta): ... - -class unicode(basestring, Sequence[unicode]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... - def capitalize(self) -> unicode: ... - def center(self, width: int, fillchar: unicode = ...) -> unicode: ... - def count(self, x: unicode) -> int: ... - def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... - def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... - def endswith(self, __suffix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> unicode: ... - def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> unicode: ... - def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - def isidentifier(self) -> bool: ... - def islower(self) -> bool: ... - def isnumeric(self) -> bool: ... - def isprintable(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, iterable: Iterable[unicode]) -> unicode: ... - def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def lower(self) -> unicode: ... - def lstrip(self, chars: unicode = ...) -> unicode: ... - def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... - def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, __prefix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def strip(self, chars: unicode = ...) -> unicode: ... - def swapcase(self) -> unicode: ... - def title(self) -> unicode: ... - def translate(self, table: Dict[int, Any] | unicode) -> unicode: ... - def upper(self) -> unicode: ... - def zfill(self, width: int) -> unicode: ... - @overload - def __getitem__(self, i: int) -> unicode: ... - @overload - def __getitem__(self, s: slice) -> unicode: ... - def __getslice__(self, start: int, stop: int) -> unicode: ... - def __add__(self, s: unicode) -> unicode: ... - def __mul__(self, n: int) -> unicode: ... - def __rmul__(self, n: int) -> unicode: ... - def __mod__(self, x: Any) -> unicode: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: unicode) -> bool: ... - def __le__(self, x: unicode) -> bool: ... - def __gt__(self, x: unicode) -> bool: ... - def __ge__(self, x: unicode) -> bool: ... - def __len__(self) -> int: ... - # The argument type is incompatible with Sequence - def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore - def __iter__(self) -> Iterator[unicode]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __hash__(self) -> int: ... - def __getnewargs__(self) -> Tuple[unicode]: ... - -class _FormatMapMapping(Protocol): - def __getitem__(self, __key: str) -> Any: ... - -class str(Sequence[str], basestring): - def __init__(self, o: object = ...) -> None: ... - def capitalize(self) -> str: ... - def center(self, __width: int, __fillchar: str = ...) -> str: ... - def count(self, x: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... - def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, __suffix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> str: ... - def find(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> str: ... - def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... - def ljust(self, __width: int, __fillchar: str = ...) -> str: ... - def lower(self) -> str: ... - @overload - def lstrip(self, __chars: str = ...) -> str: ... - @overload - def lstrip(self, __chars: unicode) -> unicode: ... - @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... - def rfind(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def rindex(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def rjust(self, __width: int, __fillchar: str = ...) -> str: ... - @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - @overload - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - @overload - def rstrip(self, __chars: str = ...) -> str: ... - @overload - def rstrip(self, __chars: unicode) -> unicode: ... - @overload - def split(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, __prefix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - @overload - def strip(self, __chars: str = ...) -> str: ... - @overload - def strip(self, chars: unicode) -> unicode: ... - def swapcase(self) -> str: ... - def title(self) -> str: ... - def translate(self, __table: AnyStr | None, deletechars: AnyStr = ...) -> AnyStr: ... - def upper(self) -> str: ... - def zfill(self, __width: int) -> str: ... - def __add__(self, s: AnyStr) -> AnyStr: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: str | Text) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ge__(self, x: Text) -> bool: ... - def __getitem__(self, i: int | slice) -> str: ... - def __gt__(self, x: Text) -> bool: ... - def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... - def __le__(self, x: Text) -> bool: ... - def __len__(self) -> int: ... - def __lt__(self, x: Text) -> bool: ... - def __mod__(self, x: Any) -> str: ... - def __mul__(self, n: int) -> str: ... - def __ne__(self, x: object) -> bool: ... - def __repr__(self) -> str: ... - def __rmul__(self, n: int) -> str: ... - def __str__(self) -> str: ... - def __getnewargs__(self) -> Tuple[str]: ... - def __getslice__(self, start: int, stop: int) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - -bytes = str - -class bytearray(MutableSequence[int], ByteString): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: str) -> None: ... - @overload - def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - def capitalize(self) -> bytearray: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def count(self, __sub: str) -> int: ... - def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... - def endswith(self, __suffix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytearray: ... - def extend(self, iterable: str | Iterable[int]) -> None: ... - def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def insert(self, __index: int, __item: int) -> None: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[str]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... - def lower(self) -> bytearray: ... - def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... - def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith(self, __prefix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def strip(self, __bytes: bytes | None = ...) -> bytearray: ... - def swapcase(self) -> bytearray: ... - def title(self) -> bytearray: ... - def translate(self, __table: str) -> bytearray: ... - def upper(self) -> bytearray: ... - def zfill(self, __width: int) -> bytearray: ... - @classmethod - def fromhex(cls, __string: str) -> bytearray: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - __hash__: None # type: ignore - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> bytearray: ... - @overload - def __setitem__(self, i: int, x: int) -> None: ... - @overload - def __setitem__(self, s: slice, x: Iterable[int] | bytes) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> bytearray: ... - def __setslice__(self, start: int, stop: int, x: Sequence[int] | str) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, s: bytes) -> bytearray: ... - def __mul__(self, n: int) -> bytearray: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: int | bytes) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... - -class memoryview(Sized, Container[str]): - format: str - itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None - readonly: bool - ndim: int - def __init__(self, obj: ReadableBuffer) -> None: ... - @overload - def __getitem__(self, i: int) -> str: ... - @overload - def __getitem__(self, s: slice) -> memoryview: ... - def __contains__(self, x: object) -> bool: ... - def __iter__(self) -> Iterator[str]: ... - def __len__(self) -> int: ... - @overload - def __setitem__(self, s: slice, o: bytes) -> None: ... - @overload - def __setitem__(self, i: int, o: int) -> None: ... - def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... - -@final -class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... - @overload - def __and__(self, x: bool) -> bool: ... - @overload - def __and__(self, x: int) -> int: ... - @overload - def __or__(self, x: bool) -> bool: ... - @overload - def __or__(self, x: int) -> int: ... - @overload - def __xor__(self, x: bool) -> bool: ... - @overload - def __xor__(self, x: int) -> int: ... - @overload - def __rand__(self, x: bool) -> bool: ... - @overload - def __rand__(self, x: int) -> int: ... - @overload - def __ror__(self, x: bool) -> bool: ... - @overload - def __ror__(self, x: int) -> int: ... - @overload - def __rxor__(self, x: bool) -> bool: ... - @overload - def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... - -class slice(object): - start: Any - step: Any - stop: Any - @overload - def __init__(self, stop: Any) -> None: ... - @overload - def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... - __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... - -class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... - def __len__(self) -> int: ... - def __contains__(self, x: object) -> bool: ... - @overload - def __getitem__(self, x: int) -> _T_co: ... - @overload - def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... - @overload - def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... - @overload - def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... - def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... - def count(self, __value: Any) -> int: ... - def index(self, __value: Any) -> int: ... - -class function: - # TODO not defined in builtins! - __name__: str - __module__: str - __code__: CodeType - -class list(MutableSequence[_T], Generic[_T]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, iterable: Iterable[_T]) -> None: ... - def append(self, __object: _T) -> None: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: int = ...) -> _T: ... - def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... - def count(self, __value: _T) -> int: ... - def insert(self, __index: int, __object: _T) -> None: ... - def remove(self, __value: _T) -> None: ... - def reverse(self) -> None: ... - def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore - @overload - def __getitem__(self, i: int) -> _T: ... - @overload - def __getitem__(self, s: slice) -> List[_T]: ... - @overload - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_T]: ... - def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, x: List[_T]) -> List[_T]: ... - def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: int) -> List[_T]: ... - def __rmul__(self, n: int) -> List[_T]: ... - def __contains__(self, o: object) -> bool: ... - def __reversed__(self) -> Iterator[_T]: ... - def __gt__(self, x: List[_T]) -> bool: ... - def __ge__(self, x: List[_T]) -> bool: ... - def __lt__(self, x: List[_T]) -> bool: ... - def __le__(self, x: List[_T]) -> bool: ... - -class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): - # NOTE: Keyword arguments are special. If they are used, _KT must include - # str, but we have no way of enforcing it here. - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... - def has_key(self, k: _KT) -> bool: ... - def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... - @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - @overload - def update(self, **kwargs: _VT) -> None: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def viewkeys(self) -> KeysView[_KT]: ... - def viewvalues(self) -> ValuesView[_VT]: ... - def viewitems(self) -> ItemsView[_KT, _VT]: ... - @classmethod - @overload - def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... - @classmethod - @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... - def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore - -class set(MutableSet[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T] = ...) -> None: ... - def add(self, element: _T) -> None: ... - def clear(self) -> None: ... - def copy(self) -> Set[_T]: ... - def difference(self, *s: Iterable[Any]) -> Set[_T]: ... - def difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... - def intersection_update(self, *s: Iterable[Any]) -> None: ... - def isdisjoint(self, s: Iterable[Any]) -> bool: ... - def issubset(self, s: Iterable[Any]) -> bool: ... - def issuperset(self, s: Iterable[Any]) -> bool: ... - def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... - def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... - def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... - def union(self, *s: Iterable[_T]) -> Set[_T]: ... - def update(self, *s: Iterable[_T]) -> None: ... - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __or__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ior__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - @overload - def __sub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... - @overload - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - @overload # type: ignore - def __isub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... - @overload - def __isub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - def __xor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ixor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - __hash__: None # type: ignore - -class frozenset(AbstractSet[_T_co], Generic[_T_co]): - def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... - def copy(self) -> FrozenSet[_T_co]: ... - def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... - def issubset(self, s: Iterable[object]) -> bool: ... - def issuperset(self, s: Iterable[object]) -> bool: ... - def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __or__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... - def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): - def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... - def __iter__(self) -> Iterator[Tuple[int, _T]]: ... - def next(self) -> Tuple[int, _T]: ... - -class xrange(Sized, Iterable[int], Reversible[int]): - @overload - def __init__(self, stop: int) -> None: ... - @overload - def __init__(self, start: int, stop: int, step: int = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __getitem__(self, i: _SupportsIndex) -> int: ... - def __reversed__(self) -> Iterator[int]: ... - -class property(object): - def __init__( - self, - fget: Callable[[Any], Any] | None = ..., - fset: Callable[[Any, Any], None] | None = ..., - fdel: Callable[[Any], None] | None = ..., - doc: str | None = ..., - ) -> None: ... - def getter(self, fget: Callable[[Any], Any]) -> property: ... - def setter(self, fset: Callable[[Any, Any], None]) -> property: ... - def deleter(self, fdel: Callable[[Any], None]) -> property: ... - def __get__(self, obj: Any, type: type | None = ...) -> Any: ... - def __set__(self, obj: Any, value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... - def fget(self) -> Any: ... - def fset(self, value: Any) -> None: ... - def fdel(self) -> None: ... - -long = int - -class _NotImplementedType(Any): # type: ignore - # A little weird, but typing the __call__ as NotImplemented makes the error message - # for NotImplemented() much better - __call__: NotImplemented # type: ignore - -NotImplemented: _NotImplementedType - -def abs(__x: SupportsAbs[_T]) -> _T: ... -def all(__iterable: Iterable[object]) -> bool: ... -def any(__iterable: Iterable[object]) -> bool: ... -def apply(__func: Callable[..., _T], __args: Sequence[Any] | None = ..., __kwds: Mapping[str, Any] | None = ...) -> _T: ... -def bin(__number: int | _SupportsIndex) -> str: ... -def callable(__obj: object) -> bool: ... -def chr(__i: int) -> str: ... -def cmp(__x: Any, __y: Any) -> int: ... - -_N1 = TypeVar("_N1", bool, int, float, complex) - -def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... -def compile(source: Text | mod, filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... -def delattr(__obj: Any, __name: Text) -> None: ... -def dir(__o: object = ...) -> List[str]: ... - -_N2 = TypeVar("_N2", int, float) - -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... -def eval( - __source: Text | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... -) -> Any: ... -def execfile(__filename: str, __globals: Dict[str, Any] | None = ..., __locals: Dict[str, Any] | None = ...) -> None: ... -def exit(code: object = ...) -> NoReturn: ... -@overload -def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore -@overload -def filter(__function: None, __iterable: Tuple[_T | None, ...]) -> Tuple[_T, ...]: ... # type: ignore -@overload -def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore -@overload -def filter(__function: None, __iterable: Iterable[_T | None]) -> List[_T]: ... -@overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... -def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode -@overload -def getattr(__o: Any, name: Text) -> Any: ... - -# While technically covered by the last overload, spelling out the types for None, bool -# and basic containers help mypy out in some tricky situations involving type context -# (aka bidirectional inference) -@overload -def getattr(__o: Any, name: Text, __default: None) -> Any | None: ... -@overload -def getattr(__o: Any, name: Text, __default: bool) -> Any | bool: ... -@overload -def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ... -@overload -def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... -@overload -def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... -def globals() -> Dict[str, Any]: ... -def hasattr(__obj: Any, __name: Text) -> bool: ... -def hash(__obj: object) -> int: ... -def hex(__number: int | _SupportsIndex) -> str: ... -def id(__obj: object) -> int: ... -def input(__prompt: Any = ...) -> Any: ... -def intern(__string: str) -> str: ... -@overload -def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... -@overload -def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... -@overload -def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def len(__obj: Sized) -> int: ... -def locals() -> Dict[str, Any]: ... -@overload -def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... -@overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... -@overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... -@overload -def map( - __func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def map( - __func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def map( - __func: None, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... -@overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... -@overload -def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] -) -> List[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], -) -> List[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], -) -> List[_S]: ... -@overload -def map( - __func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> List[_S]: ... -@overload -def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def next(__i: Iterator[_T]) -> _T: ... -@overload -def next(__i: Iterator[_T], __default: _VT) -> _T | _VT: ... -def oct(__number: int | _SupportsIndex) -> str: ... -def open(name: unicode | int, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... -def ord(__c: Text | bytes) -> int: ... - -# This is only available after from __future__ import print_function. -def print(*values: object, sep: Text | None = ..., end: Text | None = ..., file: SupportsWrite[Any] | None = ...) -> None: ... - -_E = TypeVar("_E", contravariant=True) -_M = TypeVar("_M", contravariant=True) - -class _SupportsPow2(Protocol[_E, _T_co]): - def __pow__(self, __other: _E) -> _T_co: ... - -class _SupportsPow3(Protocol[_E, _M, _T_co]): - def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... - -@overload -def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative -@overload -def pow(__base: int, __exp: int, __mod: int) -> int: ... -@overload -def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... -@overload -def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... -@overload -def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... -def quit(code: object = ...) -> NoReturn: ... -def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 -def raw_input(__prompt: Any = ...) -> str: ... -@overload -def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... -@overload -def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... -def reload(__module: Any) -> Any: ... -@overload -def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... -@overload -def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... -def repr(__obj: object) -> str: ... -@overload -def round(number: float) -> float: ... -@overload -def round(number: float, ndigits: int) -> float: ... -@overload -def round(number: SupportsFloat) -> float: ... -@overload -def round(number: SupportsFloat, ndigits: int) -> float: ... -def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... -def sorted( - __iterable: Iterable[_T], *, cmp: Callable[[_T, _T], int] = ..., key: Callable[[_T], Any] | None = ..., reverse: bool = ... -) -> List[_T]: ... -@overload -def sum(__iterable: Iterable[_T]) -> _T | int: ... -@overload -def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... -def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... -@overload -def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... -@overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... -@overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... -@overload -def zip( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def zip( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def zip( - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... -def __import__( - name: Text, - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., - fromlist: Sequence[str] = ..., - level: int = ..., -) -> Any: ... - -# Actually the type of Ellipsis is , but since it's -# not exposed anywhere under that name, we make it private here. -class ellipsis: ... - -Ellipsis: ellipsis - -# TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. -_AnyBuffer = TypeVar("_AnyBuffer", str, unicode, bytearray, buffer) - -class buffer(Sized): - def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... - def __add__(self, other: _AnyBuffer) -> str: ... - def __cmp__(self, other: _AnyBuffer) -> bool: ... - def __getitem__(self, key: int | slice) -> str: ... - def __getslice__(self, i: int, j: int) -> str: ... - def __len__(self) -> int: ... - def __mul__(self, x: int) -> str: ... - -class BaseException(object): - args: Tuple[Any, ...] - message: Any - def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __getitem__(self, i: int) -> Any: ... - def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... - -class GeneratorExit(BaseException): ... -class KeyboardInterrupt(BaseException): ... - -class SystemExit(BaseException): - code: int - -class Exception(BaseException): ... -class StopIteration(Exception): ... -class StandardError(Exception): ... - -_StandardError = StandardError - -class EnvironmentError(StandardError): - errno: int - strerror: str - # TODO can this be unicode? - filename: str - -class OSError(EnvironmentError): ... -class IOError(EnvironmentError): ... -class ArithmeticError(_StandardError): ... -class AssertionError(_StandardError): ... -class AttributeError(_StandardError): ... -class BufferError(_StandardError): ... -class EOFError(_StandardError): ... -class ImportError(_StandardError): ... -class LookupError(_StandardError): ... -class MemoryError(_StandardError): ... -class NameError(_StandardError): ... -class ReferenceError(_StandardError): ... -class RuntimeError(_StandardError): ... - -class SyntaxError(_StandardError): - msg: str - lineno: int | None - offset: int | None - text: str | None - filename: str | None - -class SystemError(_StandardError): ... -class TypeError(_StandardError): ... -class ValueError(_StandardError): ... -class FloatingPointError(ArithmeticError): ... -class OverflowError(ArithmeticError): ... -class ZeroDivisionError(ArithmeticError): ... -class IndexError(LookupError): ... -class KeyError(LookupError): ... -class UnboundLocalError(NameError): ... - -class WindowsError(OSError): - winerror: int - -class NotImplementedError(RuntimeError): ... -class IndentationError(SyntaxError): ... -class TabError(IndentationError): ... -class UnicodeError(ValueError): ... - -class UnicodeDecodeError(UnicodeError): - encoding: str - object: bytes - start: int - end: int - reason: str - def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... - -class UnicodeEncodeError(UnicodeError): - encoding: str - object: Text - start: int - end: int - reason: str - def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, __reason: str) -> None: ... - -class UnicodeTranslateError(UnicodeError): ... -class Warning(Exception): ... -class UserWarning(Warning): ... -class DeprecationWarning(Warning): ... -class SyntaxWarning(Warning): ... -class RuntimeWarning(Warning): ... -class FutureWarning(Warning): ... -class PendingDeprecationWarning(Warning): ... -class ImportWarning(Warning): ... -class UnicodeWarning(Warning): ... -class BytesWarning(Warning): ... - -class file(BinaryIO): - @overload - def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... - def __enter__(self) -> BinaryIO: ... - def __exit__(self, t: type | None = ..., exc: BaseException | None = ..., tb: Any | None = ...) -> bool | None: ... - def flush(self) -> None: ... - def fileno(self) -> int: ... - def isatty(self) -> bool: ... - def close(self) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def seekable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def write(self, data: str) -> int: ... - def writelines(self, data: Iterable[str]) -> None: ... - def truncate(self, pos: int | None = ...) -> int: ... diff --git a/stdlib/@python2/__future__.pyi b/stdlib/@python2/__future__.pyi deleted file mode 100644 index 8f5ff06ac080..000000000000 --- a/stdlib/@python2/__future__.pyi +++ /dev/null @@ -1,17 +0,0 @@ -import sys -from typing import List - -class _Feature: - def __init__(self, optionalRelease: sys._version_info, mandatoryRelease: sys._version_info, compiler_flag: int) -> None: ... - def getOptionalRelease(self) -> sys._version_info: ... - def getMandatoryRelease(self) -> sys._version_info: ... - compiler_flag: int - -absolute_import: _Feature -division: _Feature -generators: _Feature -nested_scopes: _Feature -print_function: _Feature -unicode_literals: _Feature -with_statement: _Feature -all_feature_names: List[str] # undocumented diff --git a/stdlib/@python2/__main__.pyi b/stdlib/@python2/__main__.pyi deleted file mode 100644 index e27843e53382..000000000000 --- a/stdlib/@python2/__main__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... diff --git a/stdlib/@python2/_ast.pyi b/stdlib/@python2/_ast.pyi deleted file mode 100644 index 05cbc70c41d2..000000000000 --- a/stdlib/@python2/_ast.pyi +++ /dev/null @@ -1,302 +0,0 @@ -import typing - -__version__: str -PyCF_ONLY_AST: int -_identifier = str - -class AST: - _attributes: typing.Tuple[str, ...] - _fields: typing.Tuple[str, ...] - def __init__(self, *args, **kwargs) -> None: ... - -class mod(AST): ... - -class Module(mod): - body: typing.List[stmt] - -class Interactive(mod): - body: typing.List[stmt] - -class Expression(mod): - body: expr - -class Suite(mod): - body: typing.List[stmt] - -class stmt(AST): - lineno: int - col_offset: int - -class FunctionDef(stmt): - name: _identifier - args: arguments - body: typing.List[stmt] - decorator_list: typing.List[expr] - -class ClassDef(stmt): - name: _identifier - bases: typing.List[expr] - body: typing.List[stmt] - decorator_list: typing.List[expr] - -class Return(stmt): - value: expr | None - -class Delete(stmt): - targets: typing.List[expr] - -class Assign(stmt): - targets: typing.List[expr] - value: expr - -class AugAssign(stmt): - target: expr - op: operator - value: expr - -class Print(stmt): - dest: expr | None - values: typing.List[expr] - nl: bool - -class For(stmt): - target: expr - iter: expr - body: typing.List[stmt] - orelse: typing.List[stmt] - -class While(stmt): - test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] - -class If(stmt): - test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] - -class With(stmt): - context_expr: expr - optional_vars: expr | None - body: typing.List[stmt] - -class Raise(stmt): - type: expr | None - inst: expr | None - tback: expr | None - -class TryExcept(stmt): - body: typing.List[stmt] - handlers: typing.List[ExceptHandler] - orelse: typing.List[stmt] - -class TryFinally(stmt): - body: typing.List[stmt] - finalbody: typing.List[stmt] - -class Assert(stmt): - test: expr - msg: expr | None - -class Import(stmt): - names: typing.List[alias] - -class ImportFrom(stmt): - module: _identifier | None - names: typing.List[alias] - level: int | None - -class Exec(stmt): - body: expr - globals: expr | None - locals: expr | None - -class Global(stmt): - names: typing.List[_identifier] - -class Expr(stmt): - value: expr - -class Pass(stmt): ... -class Break(stmt): ... -class Continue(stmt): ... -class slice(AST): ... - -_slice = slice # this lets us type the variable named 'slice' below - -class Slice(slice): - lower: expr | None - upper: expr | None - step: expr | None - -class ExtSlice(slice): - dims: typing.List[slice] - -class Index(slice): - value: expr - -class Ellipsis(slice): ... - -class expr(AST): - lineno: int - col_offset: int - -class BoolOp(expr): - op: boolop - values: typing.List[expr] - -class BinOp(expr): - left: expr - op: operator - right: expr - -class UnaryOp(expr): - op: unaryop - operand: expr - -class Lambda(expr): - args: arguments - body: expr - -class IfExp(expr): - test: expr - body: expr - orelse: expr - -class Dict(expr): - keys: typing.List[expr] - values: typing.List[expr] - -class Set(expr): - elts: typing.List[expr] - -class ListComp(expr): - elt: expr - generators: typing.List[comprehension] - -class SetComp(expr): - elt: expr - generators: typing.List[comprehension] - -class DictComp(expr): - key: expr - value: expr - generators: typing.List[comprehension] - -class GeneratorExp(expr): - elt: expr - generators: typing.List[comprehension] - -class Yield(expr): - value: expr | None - -class Compare(expr): - left: expr - ops: typing.List[cmpop] - comparators: typing.List[expr] - -class Call(expr): - func: expr - args: typing.List[expr] - keywords: typing.List[keyword] - starargs: expr | None - kwargs: expr | None - -class Repr(expr): - value: expr - -class Num(expr): - n: float - -class Str(expr): - s: str - -class Attribute(expr): - value: expr - attr: _identifier - ctx: expr_context - -class Subscript(expr): - value: expr - slice: _slice - ctx: expr_context - -class Name(expr): - id: _identifier - ctx: expr_context - -class List(expr): - elts: typing.List[expr] - ctx: expr_context - -class Tuple(expr): - elts: typing.List[expr] - ctx: expr_context - -class expr_context(AST): ... -class AugLoad(expr_context): ... -class AugStore(expr_context): ... -class Del(expr_context): ... -class Load(expr_context): ... -class Param(expr_context): ... -class Store(expr_context): ... -class boolop(AST): ... -class And(boolop): ... -class Or(boolop): ... -class operator(AST): ... -class Add(operator): ... -class BitAnd(operator): ... -class BitOr(operator): ... -class BitXor(operator): ... -class Div(operator): ... -class FloorDiv(operator): ... -class LShift(operator): ... -class Mod(operator): ... -class Mult(operator): ... -class Pow(operator): ... -class RShift(operator): ... -class Sub(operator): ... -class unaryop(AST): ... -class Invert(unaryop): ... -class Not(unaryop): ... -class UAdd(unaryop): ... -class USub(unaryop): ... -class cmpop(AST): ... -class Eq(cmpop): ... -class Gt(cmpop): ... -class GtE(cmpop): ... -class In(cmpop): ... -class Is(cmpop): ... -class IsNot(cmpop): ... -class Lt(cmpop): ... -class LtE(cmpop): ... -class NotEq(cmpop): ... -class NotIn(cmpop): ... - -class comprehension(AST): - target: expr - iter: expr - ifs: typing.List[expr] - -class excepthandler(AST): ... - -class ExceptHandler(excepthandler): - type: expr | None - name: expr | None - body: typing.List[stmt] - lineno: int - col_offset: int - -class arguments(AST): - args: typing.List[expr] - vararg: _identifier | None - kwarg: _identifier | None - defaults: typing.List[expr] - -class keyword(AST): - arg: _identifier - value: expr - -class alias(AST): - name: _identifier - asname: _identifier | None diff --git a/stdlib/@python2/_bisect.pyi b/stdlib/@python2/_bisect.pyi deleted file mode 100644 index e3327a0af4e6..000000000000 --- a/stdlib/@python2/_bisect.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import MutableSequence, Sequence, TypeVar - -_T = TypeVar("_T") - -def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> int: ... -def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> int: ... -def insort_left(a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> None: ... -def insort_right(a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> None: ... diff --git a/stdlib/@python2/_codecs.pyi b/stdlib/@python2/_codecs.pyi deleted file mode 100644 index 83601f6621bb..000000000000 --- a/stdlib/@python2/_codecs.pyi +++ /dev/null @@ -1,66 +0,0 @@ -import codecs -import sys -from typing import Any, Callable, Dict, Text, Tuple, Union - -# For convenience: -_Handler = Callable[[Exception], Tuple[Text, int]] -_String = Union[bytes, str] -_Errors = Union[str, Text, None] -_Decodable = Union[bytes, Text] -_Encodable = Union[bytes, Text] - -# This type is not exposed; it is defined in unicodeobject.c -class _EncodingMap(object): - def size(self) -> int: ... - -_MapT = Union[Dict[int, int], _EncodingMap] - -def register(__search_function: Callable[[str], Any]) -> None: ... -def register_error(__errors: str | Text, __handler: _Handler) -> None: ... -def lookup(__encoding: str | Text) -> codecs.CodecInfo: ... -def lookup_error(__name: str | Text) -> _Handler: ... -def decode(obj: Any, encoding: str | Text = ..., errors: _Errors = ...) -> Any: ... -def encode(obj: Any, encoding: str | Text = ..., errors: _Errors = ...) -> Any: ... -def charmap_build(__map: Text) -> _MapT: ... -def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> Tuple[Text, int]: ... -def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> Tuple[bytes, int]: ... -def escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[str, int]: ... -def escape_encode(__data: bytes, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... -def utf_16_ex_decode( - __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_16_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... -def utf_32_ex_decode( - __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_32_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_7_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_7_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_8_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_8_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... - -if sys.platform == "win32": - def mbcs_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... - def mbcs_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... diff --git a/stdlib/@python2/_collections.pyi b/stdlib/@python2/_collections.pyi deleted file mode 100644 index 22ada07d0f24..000000000000 --- a/stdlib/@python2/_collections.pyi +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Any, Callable, Dict, Generic, Iterator, TypeVar - -_K = TypeVar("_K") -_V = TypeVar("_V") -_T = TypeVar("_T") -_T2 = TypeVar("_T2") - -class defaultdict(Dict[_K, _V]): - default_factory: None - def __init__(self, __default_factory: Callable[[], _V] = ..., init: Any = ...) -> None: ... - def __missing__(self, key: _K) -> _V: ... - def __copy__(self: _T) -> _T: ... - def copy(self: _T) -> _T: ... - -class deque(Generic[_T]): - maxlen: int | None - def __init__(self, iterable: Iterator[_T] = ..., maxlen: int = ...) -> None: ... - def append(self, x: _T) -> None: ... - def appendleft(self, x: _T) -> None: ... - def clear(self) -> None: ... - def count(self, x: Any) -> int: ... - def extend(self, iterable: Iterator[_T]) -> None: ... - def extendleft(self, iterable: Iterator[_T]) -> None: ... - def pop(self) -> _T: ... - def popleft(self) -> _T: ... - def remove(self, value: _T) -> None: ... - def reverse(self) -> None: ... - def rotate(self, n: int = ...) -> None: ... - def __contains__(self, o: Any) -> bool: ... - def __copy__(self) -> deque[_T]: ... - def __getitem__(self, i: int) -> _T: ... - def __iadd__(self, other: deque[_T2]) -> deque[_T | _T2]: ... - def __iter__(self) -> Iterator[_T]: ... - def __len__(self) -> int: ... - def __reversed__(self) -> Iterator[_T]: ... - def __setitem__(self, i: int, x: _T) -> None: ... diff --git a/stdlib/@python2/_csv.pyi b/stdlib/@python2/_csv.pyi deleted file mode 100644 index ebe44bab67d9..000000000000 --- a/stdlib/@python2/_csv.pyi +++ /dev/null @@ -1,42 +0,0 @@ -from typing import Any, Iterable, Iterator, List, Protocol, Sequence, Text, Type, Union - -QUOTE_ALL: int -QUOTE_MINIMAL: int -QUOTE_NONE: int -QUOTE_NONNUMERIC: int - -class Error(Exception): ... - -class Dialect: - delimiter: str - quotechar: str | None - escapechar: str | None - doublequote: bool - skipinitialspace: bool - lineterminator: str - quoting: int - strict: int - def __init__(self) -> None: ... - -_DialectLike = Union[str, Dialect, Type[Dialect]] - -class _reader(Iterator[List[str]]): - dialect: Dialect - line_num: int - def next(self) -> List[str]: ... - -class _writer: - dialect: Dialect - def writerow(self, row: Sequence[Any]) -> Any: ... - def writerows(self, rows: Iterable[Sequence[Any]]) -> None: ... - -class _Writer(Protocol): - def write(self, s: str) -> Any: ... - -def writer(csvfile: _Writer, dialect: _DialectLike = ..., **fmtparams: Any) -> _writer: ... -def reader(csvfile: Iterable[Text], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... -def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... -def unregister_dialect(name: str) -> None: ... -def get_dialect(name: str) -> Dialect: ... -def list_dialects() -> List[str]: ... -def field_size_limit(new_limit: int = ...) -> int: ... diff --git a/stdlib/@python2/_curses.pyi b/stdlib/@python2/_curses.pyi deleted file mode 100644 index 32c1f761ac9e..000000000000 --- a/stdlib/@python2/_curses.pyi +++ /dev/null @@ -1,511 +0,0 @@ -from typing import IO, Any, BinaryIO, Tuple, Union, overload - -_chtype = Union[str, bytes, int] - -# ACS codes are only initialized after initscr is called -ACS_BBSS: int -ACS_BLOCK: int -ACS_BOARD: int -ACS_BSBS: int -ACS_BSSB: int -ACS_BSSS: int -ACS_BTEE: int -ACS_BULLET: int -ACS_CKBOARD: int -ACS_DARROW: int -ACS_DEGREE: int -ACS_DIAMOND: int -ACS_GEQUAL: int -ACS_HLINE: int -ACS_LANTERN: int -ACS_LARROW: int -ACS_LEQUAL: int -ACS_LLCORNER: int -ACS_LRCORNER: int -ACS_LTEE: int -ACS_NEQUAL: int -ACS_PI: int -ACS_PLMINUS: int -ACS_PLUS: int -ACS_RARROW: int -ACS_RTEE: int -ACS_S1: int -ACS_S3: int -ACS_S7: int -ACS_S9: int -ACS_SBBS: int -ACS_SBSB: int -ACS_SBSS: int -ACS_SSBB: int -ACS_SSBS: int -ACS_SSSB: int -ACS_SSSS: int -ACS_STERLING: int -ACS_TTEE: int -ACS_UARROW: int -ACS_ULCORNER: int -ACS_URCORNER: int -ACS_VLINE: int -ALL_MOUSE_EVENTS: int -A_ALTCHARSET: int -A_ATTRIBUTES: int -A_BLINK: int -A_BOLD: int -A_CHARTEXT: int -A_COLOR: int -A_DIM: int -A_HORIZONTAL: int -A_INVIS: int -A_LEFT: int -A_LOW: int -A_NORMAL: int -A_PROTECT: int -A_REVERSE: int -A_RIGHT: int -A_STANDOUT: int -A_TOP: int -A_UNDERLINE: int -A_VERTICAL: int -BUTTON1_CLICKED: int -BUTTON1_DOUBLE_CLICKED: int -BUTTON1_PRESSED: int -BUTTON1_RELEASED: int -BUTTON1_TRIPLE_CLICKED: int -BUTTON2_CLICKED: int -BUTTON2_DOUBLE_CLICKED: int -BUTTON2_PRESSED: int -BUTTON2_RELEASED: int -BUTTON2_TRIPLE_CLICKED: int -BUTTON3_CLICKED: int -BUTTON3_DOUBLE_CLICKED: int -BUTTON3_PRESSED: int -BUTTON3_RELEASED: int -BUTTON3_TRIPLE_CLICKED: int -BUTTON4_CLICKED: int -BUTTON4_DOUBLE_CLICKED: int -BUTTON4_PRESSED: int -BUTTON4_RELEASED: int -BUTTON4_TRIPLE_CLICKED: int -BUTTON_ALT: int -BUTTON_CTRL: int -BUTTON_SHIFT: int -COLOR_BLACK: int -COLOR_BLUE: int -COLOR_CYAN: int -COLOR_GREEN: int -COLOR_MAGENTA: int -COLOR_RED: int -COLOR_WHITE: int -COLOR_YELLOW: int -ERR: int -KEY_A1: int -KEY_A3: int -KEY_B2: int -KEY_BACKSPACE: int -KEY_BEG: int -KEY_BREAK: int -KEY_BTAB: int -KEY_C1: int -KEY_C3: int -KEY_CANCEL: int -KEY_CATAB: int -KEY_CLEAR: int -KEY_CLOSE: int -KEY_COMMAND: int -KEY_COPY: int -KEY_CREATE: int -KEY_CTAB: int -KEY_DC: int -KEY_DL: int -KEY_DOWN: int -KEY_EIC: int -KEY_END: int -KEY_ENTER: int -KEY_EOL: int -KEY_EOS: int -KEY_EXIT: int -KEY_F0: int -KEY_F1: int -KEY_F10: int -KEY_F11: int -KEY_F12: int -KEY_F13: int -KEY_F14: int -KEY_F15: int -KEY_F16: int -KEY_F17: int -KEY_F18: int -KEY_F19: int -KEY_F2: int -KEY_F20: int -KEY_F21: int -KEY_F22: int -KEY_F23: int -KEY_F24: int -KEY_F25: int -KEY_F26: int -KEY_F27: int -KEY_F28: int -KEY_F29: int -KEY_F3: int -KEY_F30: int -KEY_F31: int -KEY_F32: int -KEY_F33: int -KEY_F34: int -KEY_F35: int -KEY_F36: int -KEY_F37: int -KEY_F38: int -KEY_F39: int -KEY_F4: int -KEY_F40: int -KEY_F41: int -KEY_F42: int -KEY_F43: int -KEY_F44: int -KEY_F45: int -KEY_F46: int -KEY_F47: int -KEY_F48: int -KEY_F49: int -KEY_F5: int -KEY_F50: int -KEY_F51: int -KEY_F52: int -KEY_F53: int -KEY_F54: int -KEY_F55: int -KEY_F56: int -KEY_F57: int -KEY_F58: int -KEY_F59: int -KEY_F6: int -KEY_F60: int -KEY_F61: int -KEY_F62: int -KEY_F63: int -KEY_F7: int -KEY_F8: int -KEY_F9: int -KEY_FIND: int -KEY_HELP: int -KEY_HOME: int -KEY_IC: int -KEY_IL: int -KEY_LEFT: int -KEY_LL: int -KEY_MARK: int -KEY_MAX: int -KEY_MESSAGE: int -KEY_MIN: int -KEY_MOUSE: int -KEY_MOVE: int -KEY_NEXT: int -KEY_NPAGE: int -KEY_OPEN: int -KEY_OPTIONS: int -KEY_PPAGE: int -KEY_PREVIOUS: int -KEY_PRINT: int -KEY_REDO: int -KEY_REFERENCE: int -KEY_REFRESH: int -KEY_REPLACE: int -KEY_RESET: int -KEY_RESIZE: int -KEY_RESTART: int -KEY_RESUME: int -KEY_RIGHT: int -KEY_SAVE: int -KEY_SBEG: int -KEY_SCANCEL: int -KEY_SCOMMAND: int -KEY_SCOPY: int -KEY_SCREATE: int -KEY_SDC: int -KEY_SDL: int -KEY_SELECT: int -KEY_SEND: int -KEY_SEOL: int -KEY_SEXIT: int -KEY_SF: int -KEY_SFIND: int -KEY_SHELP: int -KEY_SHOME: int -KEY_SIC: int -KEY_SLEFT: int -KEY_SMESSAGE: int -KEY_SMOVE: int -KEY_SNEXT: int -KEY_SOPTIONS: int -KEY_SPREVIOUS: int -KEY_SPRINT: int -KEY_SR: int -KEY_SREDO: int -KEY_SREPLACE: int -KEY_SRESET: int -KEY_SRIGHT: int -KEY_SRSUME: int -KEY_SSAVE: int -KEY_SSUSPEND: int -KEY_STAB: int -KEY_SUNDO: int -KEY_SUSPEND: int -KEY_UNDO: int -KEY_UP: int -OK: int -REPORT_MOUSE_POSITION: int -_C_API: Any -version: bytes - -def baudrate() -> int: ... -def beep() -> None: ... -def can_change_color() -> bool: ... -def cbreak(__flag: bool = ...) -> None: ... -def color_content(__color_number: int) -> Tuple[int, int, int]: ... - -# Changed in Python 3.8.8 and 3.9.2 -def color_pair(__color_number: int) -> int: ... -def curs_set(__visibility: int) -> int: ... -def def_prog_mode() -> None: ... -def def_shell_mode() -> None: ... -def delay_output(__ms: int) -> None: ... -def doupdate() -> None: ... -def echo(__flag: bool = ...) -> None: ... -def endwin() -> None: ... -def erasechar() -> bytes: ... -def filter() -> None: ... -def flash() -> None: ... -def flushinp() -> None: ... -def getmouse() -> Tuple[int, int, int, int, int]: ... -def getsyx() -> Tuple[int, int]: ... -def getwin(__file: BinaryIO) -> _CursesWindow: ... -def halfdelay(__tenths: int) -> None: ... -def has_colors() -> bool: ... -def has_ic() -> bool: ... -def has_il() -> bool: ... -def has_key(__key: int) -> bool: ... -def init_color(__color_number: int, __r: int, __g: int, __b: int) -> None: ... -def init_pair(__pair_number: int, __fg: int, __bg: int) -> None: ... -def initscr() -> _CursesWindow: ... -def intrflush(__flag: bool) -> None: ... -def is_term_resized(__nlines: int, __ncols: int) -> bool: ... -def isendwin() -> bool: ... -def keyname(__key: int) -> bytes: ... -def killchar() -> bytes: ... -def longname() -> bytes: ... -def meta(__yes: bool) -> None: ... -def mouseinterval(__interval: int) -> None: ... -def mousemask(__newmask: int) -> Tuple[int, int]: ... -def napms(__ms: int) -> int: ... -def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... -def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... -def nl(__flag: bool = ...) -> None: ... -def nocbreak() -> None: ... -def noecho() -> None: ... -def nonl() -> None: ... -def noqiflush() -> None: ... -def noraw() -> None: ... -def pair_content(__pair_number: int) -> Tuple[int, int]: ... -def pair_number(__attr: int) -> int: ... -def putp(__string: bytes) -> None: ... -def qiflush(__flag: bool = ...) -> None: ... -def raw(__flag: bool = ...) -> None: ... -def reset_prog_mode() -> None: ... -def reset_shell_mode() -> None: ... -def resetty() -> None: ... -def resize_term(__nlines: int, __ncols: int) -> None: ... -def resizeterm(__nlines: int, __ncols: int) -> None: ... -def savetty() -> None: ... -def setsyx(__y: int, __x: int) -> None: ... -def setupterm(term: str | None = ..., fd: int = ...) -> None: ... -def start_color() -> None: ... -def termattrs() -> int: ... -def termname() -> bytes: ... -def tigetflag(__capname: str) -> int: ... -def tigetnum(__capname: str) -> int: ... -def tigetstr(__capname: str) -> bytes: ... -def tparm( - __str: bytes, - __i1: int = ..., - __i2: int = ..., - __i3: int = ..., - __i4: int = ..., - __i5: int = ..., - __i6: int = ..., - __i7: int = ..., - __i8: int = ..., - __i9: int = ..., -) -> bytes: ... -def typeahead(__fd: int) -> None: ... -def unctrl(__ch: _chtype) -> bytes: ... -def ungetch(__ch: _chtype) -> None: ... -def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... -def use_default_colors() -> None: ... -def use_env(__flag: bool) -> None: ... - -class error(Exception): ... - -class _CursesWindow: - @overload - def addch(self, ch: _chtype, attr: int = ...) -> None: ... - @overload - def addch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... - @overload - def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... - @overload - def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... - @overload - def addstr(self, str: str, attr: int = ...) -> None: ... - @overload - def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... - def attroff(self, __attr: int) -> None: ... - def attron(self, __attr: int) -> None: ... - def attrset(self, __attr: int) -> None: ... - def bkgd(self, __ch: _chtype, __attr: int = ...) -> None: ... - def bkgdset(self, __ch: _chtype, __attr: int = ...) -> None: ... - def border( - self, - ls: _chtype = ..., - rs: _chtype = ..., - ts: _chtype = ..., - bs: _chtype = ..., - tl: _chtype = ..., - tr: _chtype = ..., - bl: _chtype = ..., - br: _chtype = ..., - ) -> None: ... - @overload - def box(self) -> None: ... - @overload - def box(self, vertch: _chtype = ..., horch: _chtype = ...) -> None: ... - @overload - def chgat(self, attr: int) -> None: ... - @overload - def chgat(self, num: int, attr: int) -> None: ... - @overload - def chgat(self, y: int, x: int, attr: int) -> None: ... - @overload - def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... - def clear(self) -> None: ... - def clearok(self, yes: int) -> None: ... - def clrtobot(self) -> None: ... - def clrtoeol(self) -> None: ... - def cursyncup(self) -> None: ... - @overload - def delch(self) -> None: ... - @overload - def delch(self, y: int, x: int) -> None: ... - def deleteln(self) -> None: ... - @overload - def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - def echochar(self, __ch: _chtype, __attr: int = ...) -> None: ... - def enclose(self, __y: int, __x: int) -> bool: ... - def erase(self) -> None: ... - def getbegyx(self) -> Tuple[int, int]: ... - def getbkgd(self) -> Tuple[int, int]: ... - @overload - def getch(self) -> int: ... - @overload - def getch(self, y: int, x: int) -> int: ... - @overload - def getkey(self) -> str: ... - @overload - def getkey(self, y: int, x: int) -> str: ... - def getmaxyx(self) -> Tuple[int, int]: ... - def getparyx(self) -> Tuple[int, int]: ... - @overload - def getstr(self) -> _chtype: ... - @overload - def getstr(self, n: int) -> _chtype: ... - @overload - def getstr(self, y: int, x: int) -> _chtype: ... - @overload - def getstr(self, y: int, x: int, n: int) -> _chtype: ... - def getyx(self) -> Tuple[int, int]: ... - @overload - def hline(self, ch: _chtype, n: int) -> None: ... - @overload - def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... - def idcok(self, flag: bool) -> None: ... - def idlok(self, yes: bool) -> None: ... - def immedok(self, flag: bool) -> None: ... - @overload - def inch(self) -> _chtype: ... - @overload - def inch(self, y: int, x: int) -> _chtype: ... - @overload - def insch(self, ch: _chtype, attr: int = ...) -> None: ... - @overload - def insch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... - def insdelln(self, nlines: int) -> None: ... - def insertln(self) -> None: ... - @overload - def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... - @overload - def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... - @overload - def insstr(self, str: str, attr: int = ...) -> None: ... - @overload - def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... - @overload - def instr(self, n: int = ...) -> _chtype: ... - @overload - def instr(self, y: int, x: int, n: int = ...) -> _chtype: ... - def is_linetouched(self, __line: int) -> bool: ... - def is_wintouched(self) -> bool: ... - def keypad(self, yes: bool) -> None: ... - def leaveok(self, yes: bool) -> None: ... - def move(self, new_y: int, new_x: int) -> None: ... - def mvderwin(self, y: int, x: int) -> None: ... - def mvwin(self, new_y: int, new_x: int) -> None: ... - def nodelay(self, yes: bool) -> None: ... - def notimeout(self, yes: bool) -> None: ... - def noutrefresh(self) -> None: ... - @overload - def overlay(self, destwin: _CursesWindow) -> None: ... - @overload - def overlay( - self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int - ) -> None: ... - @overload - def overwrite(self, destwin: _CursesWindow) -> None: ... - @overload - def overwrite( - self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int - ) -> None: ... - def putwin(self, __file: IO[Any]) -> None: ... - def redrawln(self, __beg: int, __num: int) -> None: ... - def redrawwin(self) -> None: ... - @overload - def refresh(self) -> None: ... - @overload - def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... - def resize(self, nlines: int, ncols: int) -> None: ... - def scroll(self, lines: int = ...) -> None: ... - def scrollok(self, flag: bool) -> None: ... - def setscrreg(self, __top: int, __bottom: int) -> None: ... - def standend(self) -> None: ... - def standout(self) -> None: ... - @overload - def subpad(self, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def subwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - def syncdown(self) -> None: ... - def syncok(self, flag: bool) -> None: ... - def syncup(self) -> None: ... - def timeout(self, delay: int) -> None: ... - def touchline(self, start: int, count: int, changed: bool = ...) -> None: ... - def touchwin(self) -> None: ... - def untouchwin(self) -> None: ... - @overload - def vline(self, ch: _chtype, n: int) -> None: ... - @overload - def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... diff --git a/stdlib/@python2/_dummy_threading.pyi b/stdlib/@python2/_dummy_threading.pyi deleted file mode 100644 index e45a1b5c4a89..000000000000 --- a/stdlib/@python2/_dummy_threading.pyi +++ /dev/null @@ -1,109 +0,0 @@ -from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar - -# TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] - -_PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") - -__all__: List[str] - -def active_count() -> int: ... -def activeCount() -> int: ... -def current_thread() -> Thread: ... -def currentThread() -> Thread: ... -def enumerate() -> List[Thread]: ... -def settrace(func: _TF) -> None: ... -def setprofile(func: _PF | None) -> None: ... -def stack_size(size: int = ...) -> int: ... - -class ThreadError(Exception): ... - -class local(object): - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... - -class Thread: - name: str - ident: int | None - daemon: bool - def __init__( - self, - group: None = ..., - target: Callable[..., Any] | None = ..., - name: Text | None = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[Text, Any] | None = ..., - ) -> None: ... - def start(self) -> None: ... - def run(self) -> None: ... - def join(self, timeout: float | None = ...) -> None: ... - def getName(self) -> str: ... - def setName(self, name: Text) -> None: ... - def is_alive(self) -> bool: ... - def isAlive(self) -> bool: ... - def isDaemon(self) -> bool: ... - def setDaemon(self, daemonic: bool) -> None: ... - -class _DummyThread(Thread): ... - -class Lock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - def locked(self) -> bool: ... - -class _RLock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - -RLock = _RLock - -class Condition: - def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - def notify(self, n: int = ...) -> None: ... - def notify_all(self) -> None: ... - def notifyAll(self) -> None: ... - -class Semaphore: - def __init__(self, value: int = ...) -> None: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def __enter__(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - -class BoundedSemaphore(Semaphore): ... - -class Event: - def __init__(self) -> None: ... - def is_set(self) -> bool: ... - def isSet(self) -> bool: ... - def set(self) -> None: ... - def clear(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - -class Timer(Thread): - def __init__( - self, interval: float, function: Callable[..., Any], args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ... - ) -> None: ... - def cancel(self) -> None: ... diff --git a/stdlib/@python2/_functools.pyi b/stdlib/@python2/_functools.pyi deleted file mode 100644 index e68398238f9b..000000000000 --- a/stdlib/@python2/_functools.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any, Callable, Dict, Iterable, Tuple, TypeVar, overload - -_T = TypeVar("_T") -_S = TypeVar("_S") - -@overload -def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... -@overload -def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... - -class partial(object): - func: Callable[..., Any] - args: Tuple[Any, ...] - keywords: Dict[str, Any] - def __init__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/stdlib/@python2/_heapq.pyi b/stdlib/@python2/_heapq.pyi deleted file mode 100644 index 08a8add08e9a..000000000000 --- a/stdlib/@python2/_heapq.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any, Callable, Iterable, List, TypeVar - -_T = TypeVar("_T") - -def heapify(__heap: List[Any]) -> None: ... -def heappop(__heap: List[_T]) -> _T: ... -def heappush(__heap: List[_T], __item: _T) -> None: ... -def heappushpop(__heap: List[_T], __item: _T) -> _T: ... -def heapreplace(__heap: List[_T], __item: _T) -> _T: ... -def nlargest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> List[_T]: ... -def nsmallest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> List[_T]: ... diff --git a/stdlib/@python2/_hotshot.pyi b/stdlib/@python2/_hotshot.pyi deleted file mode 100644 index b048f6fb83d5..000000000000 --- a/stdlib/@python2/_hotshot.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any, Tuple - -def coverage(a: str) -> Any: ... -def logreader(a: str) -> LogReaderType: ... -def profiler(a: str, *args, **kwargs) -> Any: ... -def resolution() -> Tuple[Any, ...]: ... - -class LogReaderType(object): - def close(self) -> None: ... - def fileno(self) -> int: ... - -class ProfilerType(object): - def addinfo(self, a: str, b: str) -> None: ... - def close(self) -> None: ... - def fileno(self) -> int: ... - def runcall(self, *args, **kwargs) -> Any: ... - def runcode(self, a, b, *args, **kwargs) -> Any: ... - def start(self) -> None: ... - def stop(self) -> None: ... diff --git a/stdlib/@python2/_io.pyi b/stdlib/@python2/_io.pyi deleted file mode 100644 index fedbbe137940..000000000000 --- a/stdlib/@python2/_io.pyi +++ /dev/null @@ -1,180 +0,0 @@ -from _typeshed import Self -from mmap import mmap -from typing import IO, Any, BinaryIO, Iterable, List, Text, TextIO, Tuple, Type, TypeVar, Union - -_bytearray_like = Union[bytearray, mmap] - -DEFAULT_BUFFER_SIZE: int - -class BlockingIOError(IOError): - characters_written: int - -class UnsupportedOperation(ValueError, IOError): ... - -_T = TypeVar("_T") - -class _IOBase(BinaryIO): - @property - def closed(self) -> bool: ... - def _checkClosed(self, msg: str | None = ...) -> None: ... # undocumented - def _checkReadable(self) -> None: ... - def _checkSeekable(self) -> None: ... - def _checkWritable(self) -> None: ... - # All these methods are concrete here (you can instantiate this) - def close(self) -> None: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def readable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... - def writable(self) -> bool: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... - def __iter__(self: _T) -> _T: ... - # The parameter type of writelines[s]() is determined by that of write(): - def writelines(self, lines: Iterable[bytes]) -> None: ... - # The return type of readline[s]() and next() is determined by that of read(): - def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... - def next(self) -> bytes: ... - # These don't actually exist but we need to pretend that it does - # so that this class is concrete. - def write(self, s: bytes) -> int: ... - def read(self, n: int = ...) -> bytes: ... - -class _BufferedIOBase(_IOBase): - def read1(self, n: int) -> bytes: ... - def read(self, size: int = ...) -> bytes: ... - def readinto(self, buffer: _bytearray_like) -> int: ... - def write(self, s: bytes) -> int: ... - def detach(self) -> _IOBase: ... - -class BufferedRWPair(_BufferedIOBase): - def __init__(self, reader: _RawIOBase, writer: _RawIOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - def __enter__(self: Self) -> Self: ... - -class BufferedRandom(_BufferedIOBase): - mode: str - name: str - raw: _IOBase - def __init__(self, raw: _IOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - -class BufferedReader(_BufferedIOBase): - mode: str - name: str - raw: _IOBase - def __init__(self, raw: _IOBase, buffer_size: int = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - -class BufferedWriter(_BufferedIOBase): - name: str - raw: _IOBase - mode: str - def __init__(self, raw: _IOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... - -class BytesIO(_BufferedIOBase): - def __init__(self, initial_bytes: bytes = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... - # BytesIO does not contain a "name" field. This workaround is necessary - # to allow BytesIO sub-classes to add this field, as it is defined - # as a read-only property on IO[]. - name: Any - def getvalue(self) -> bytes: ... - def write(self, s: bytes) -> int: ... - def writelines(self, lines: Iterable[bytes]) -> None: ... - def read1(self, size: int) -> bytes: ... - def next(self) -> bytes: ... - -class _RawIOBase(_IOBase): - def readall(self) -> str: ... - def read(self, n: int = ...) -> str: ... - -class FileIO(_RawIOBase, BytesIO): - mode: str - closefd: bool - def __init__(self, file: str | int, mode: str = ..., closefd: bool = ...) -> None: ... - def readinto(self, buffer: _bytearray_like) -> int: ... - def write(self, pbuf: str) -> int: ... - -class IncrementalNewlineDecoder(object): - newlines: str | unicode - def __init__(self, decoder, translate, z=...) -> None: ... - def decode(self, input, final) -> Any: ... - def getstate(self) -> Tuple[Any, int]: ... - def setstate(self, state: Tuple[Any, int]) -> None: ... - def reset(self) -> None: ... - -# Note: In the actual _io.py, _TextIOBase inherits from _IOBase. -class _TextIOBase(TextIO): - errors: str | None - # TODO: On _TextIOBase, this is always None. But it's unicode/bytes in subclasses. - newlines: None | unicode | bytes - encoding: str - @property - def closed(self) -> bool: ... - def _checkClosed(self) -> None: ... - def _checkReadable(self) -> None: ... - def _checkSeekable(self) -> None: ... - def _checkWritable(self) -> None: ... - def close(self) -> None: ... - def detach(self) -> IO[Any]: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def next(self) -> unicode: ... - def read(self, size: int = ...) -> unicode: ... - def readable(self) -> bool: ... - def readline(self, limit: int = ...) -> unicode: ... - def readlines(self, hint: int = ...) -> list[unicode]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... - def writable(self) -> bool: ... - def write(self, pbuf: unicode) -> int: ... - def writelines(self, lines: Iterable[unicode]) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... - def __iter__(self: _T) -> _T: ... - -class StringIO(_TextIOBase): - line_buffering: bool - def __init__(self, initial_value: unicode | None = ..., newline: unicode | None = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... - # StringIO does not contain a "name" field. This workaround is necessary - # to allow StringIO sub-classes to add this field, as it is defined - # as a read-only property on IO[]. - name: Any - def getvalue(self) -> unicode: ... - -class TextIOWrapper(_TextIOBase): - name: str - line_buffering: bool - buffer: BinaryIO - _CHUNK_SIZE: int - def __init__( - self, - buffer: IO[Any], - encoding: Text | None = ..., - errors: Text | None = ..., - newline: Text | None = ..., - line_buffering: bool = ..., - write_through: bool = ..., - ) -> None: ... - -def open( - file: str | unicode | int, - mode: Text = ..., - buffering: int = ..., - encoding: Text | None = ..., - errors: Text | None = ..., - newline: Text | None = ..., - closefd: bool = ..., -) -> IO[Any]: ... diff --git a/stdlib/@python2/_json.pyi b/stdlib/@python2/_json.pyi deleted file mode 100644 index a9868b3e60fd..000000000000 --- a/stdlib/@python2/_json.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any, Tuple - -def encode_basestring_ascii(*args, **kwargs) -> str: ... -def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... - -class Encoder(object): ... -class Scanner(object): ... diff --git a/stdlib/@python2/_markupbase.pyi b/stdlib/@python2/_markupbase.pyi deleted file mode 100644 index d8bc79f34e8c..000000000000 --- a/stdlib/@python2/_markupbase.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Tuple - -class ParserBase: - def __init__(self) -> None: ... - def error(self, message: str) -> None: ... - def reset(self) -> None: ... - def getpos(self) -> Tuple[int, int]: ... - def unknown_decl(self, data: str) -> None: ... diff --git a/stdlib/@python2/_md5.pyi b/stdlib/@python2/_md5.pyi deleted file mode 100644 index 96111b70af9b..000000000000 --- a/stdlib/@python2/_md5.pyi +++ /dev/null @@ -1,13 +0,0 @@ -blocksize: int -digest_size: int - -class MD5Type(object): - name: str - block_size: int - digest_size: int - def copy(self) -> MD5Type: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -def new(arg: str = ...) -> MD5Type: ... diff --git a/stdlib/@python2/_msi.pyi b/stdlib/@python2/_msi.pyi deleted file mode 100644 index a1030a66160f..000000000000 --- a/stdlib/@python2/_msi.pyi +++ /dev/null @@ -1,49 +0,0 @@ -import sys -from typing import List - -if sys.platform == "win32": - - # Actual typename View, not exposed by the implementation - class _View: - def Execute(self, params: _Record | None = ...) -> None: ... - def GetColumnInfo(self, kind: int) -> _Record: ... - def Fetch(self) -> _Record: ... - def Modify(self, mode: int, record: _Record) -> None: ... - def Close(self) -> None: ... - # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore - # Actual typename Summary, not exposed by the implementation - class _Summary: - def GetProperty(self, propid: int) -> str | bytes | None: ... - def GetPropertyCount(self) -> int: ... - def SetProperty(self, propid: int, value: str | bytes) -> None: ... - def Persist(self) -> None: ... - # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore - # Actual typename Database, not exposed by the implementation - class _Database: - def OpenView(self, sql: str) -> _View: ... - def Commit(self) -> None: ... - def GetSummaryInformation(self, updateCount: int) -> _Summary: ... - def Close(self) -> None: ... - # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore - # Actual typename Record, not exposed by the implementation - class _Record: - def GetFieldCount(self) -> int: ... - def GetInteger(self, field: int) -> int: ... - def GetString(self, field: int) -> str: ... - def SetString(self, field: int, str: str) -> None: ... - def SetStream(self, field: int, stream: str) -> None: ... - def SetInteger(self, field: int, int: int) -> None: ... - def ClearData(self) -> None: ... - # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore - def UuidCreate() -> str: ... - def FCICreate(cabname: str, files: List[str]) -> None: ... - def OpenDatabase(name: str, flags: int) -> _Database: ... - def CreateRecord(count: int) -> _Record: ... diff --git a/stdlib/@python2/_osx_support.pyi b/stdlib/@python2/_osx_support.pyi deleted file mode 100644 index 1b890d8d8a0a..000000000000 --- a/stdlib/@python2/_osx_support.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Dict, Iterable, List, Sequence, Tuple, TypeVar - -_T = TypeVar("_T") -_K = TypeVar("_K") -_V = TypeVar("_V") - -__all__: List[str] - -_UNIVERSAL_CONFIG_VARS: Tuple[str, ...] # undocumented -_COMPILER_CONFIG_VARS: Tuple[str, ...] # undocumented -_INITPRE: str # undocumented - -def _find_executable(executable: str, path: str | None = ...) -> str | None: ... # undocumented -def _read_output(commandstring: str) -> str | None: ... # undocumented -def _find_build_tool(toolname: str) -> str: ... # undocumented - -_SYSTEM_VERSION: str | None # undocumented - -def _get_system_version() -> str: ... # undocumented -def _remove_original_values(_config_vars: Dict[str, str]) -> None: ... # undocumented -def _save_modified_value(_config_vars: Dict[str, str], cv: str, newvalue: str) -> None: ... # undocumented -def _supports_universal_builds() -> bool: ... # undocumented -def _find_appropriate_compiler(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _remove_universal_flags(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _remove_unsupported_archs(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _override_all_archs(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _check_for_unavailable_sdk(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> List[str]: ... -def customize_config_vars(_config_vars: Dict[str, str]) -> Dict[str, str]: ... -def customize_compiler(_config_vars: Dict[str, str]) -> Dict[str, str]: ... -def get_platform_osx( - _config_vars: Dict[str, str], osname: _T, release: _K, machine: _V -) -> Tuple[str | _T, str | _K, str | _V]: ... diff --git a/stdlib/@python2/_random.pyi b/stdlib/@python2/_random.pyi deleted file mode 100644 index 7c2dd61af49f..000000000000 --- a/stdlib/@python2/_random.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Tuple - -# Actually Tuple[(int,) * 625] -_State = Tuple[int, ...] - -class Random(object): - def __init__(self, seed: object = ...) -> None: ... - def seed(self, __n: object = ...) -> None: ... - def getstate(self) -> _State: ... - def setstate(self, __state: _State) -> None: ... - def random(self) -> float: ... - def getrandbits(self, __k: int) -> int: ... - def jumpahead(self, i: int) -> None: ... diff --git a/stdlib/@python2/_sha.pyi b/stdlib/@python2/_sha.pyi deleted file mode 100644 index 7c472562fc17..000000000000 --- a/stdlib/@python2/_sha.pyi +++ /dev/null @@ -1,15 +0,0 @@ -blocksize: int -block_size: int -digest_size: int - -class sha(object): # not actually exposed - name: str - block_size: int - digest_size: int - digestsize: int - def copy(self) -> sha: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -def new(arg: str = ...) -> sha: ... diff --git a/stdlib/@python2/_sha256.pyi b/stdlib/@python2/_sha256.pyi deleted file mode 100644 index 746432094bf2..000000000000 --- a/stdlib/@python2/_sha256.pyi +++ /dev/null @@ -1,21 +0,0 @@ -class sha224(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: str | None) -> None: ... - def copy(self) -> sha224: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -class sha256(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: str | None) -> None: ... - def copy(self) -> sha256: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... diff --git a/stdlib/@python2/_sha512.pyi b/stdlib/@python2/_sha512.pyi deleted file mode 100644 index 90e2aee1542f..000000000000 --- a/stdlib/@python2/_sha512.pyi +++ /dev/null @@ -1,21 +0,0 @@ -class sha384(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: str | None) -> None: ... - def copy(self) -> sha384: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -class sha512(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: str | None) -> None: ... - def copy(self) -> sha512: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... diff --git a/stdlib/@python2/_socket.pyi b/stdlib/@python2/_socket.pyi deleted file mode 100644 index c505384c5226..000000000000 --- a/stdlib/@python2/_socket.pyi +++ /dev/null @@ -1,281 +0,0 @@ -from typing import IO, Any, Tuple, overload - -AF_APPLETALK: int -AF_ASH: int -AF_ATMPVC: int -AF_ATMSVC: int -AF_AX25: int -AF_BLUETOOTH: int -AF_BRIDGE: int -AF_DECnet: int -AF_ECONET: int -AF_INET: int -AF_INET6: int -AF_IPX: int -AF_IRDA: int -AF_KEY: int -AF_LLC: int -AF_NETBEUI: int -AF_NETLINK: int -AF_NETROM: int -AF_PACKET: int -AF_PPPOX: int -AF_ROSE: int -AF_ROUTE: int -AF_SECURITY: int -AF_SNA: int -AF_TIPC: int -AF_UNIX: int -AF_UNSPEC: int -AF_WANPIPE: int -AF_X25: int -AI_ADDRCONFIG: int -AI_ALL: int -AI_CANONNAME: int -AI_NUMERICHOST: int -AI_NUMERICSERV: int -AI_PASSIVE: int -AI_V4MAPPED: int -BDADDR_ANY: str -BDADDR_LOCAL: str -BTPROTO_HCI: int -BTPROTO_L2CAP: int -BTPROTO_RFCOMM: int -BTPROTO_SCO: int -EAI_ADDRFAMILY: int -EAI_AGAIN: int -EAI_BADFLAGS: int -EAI_FAIL: int -EAI_FAMILY: int -EAI_MEMORY: int -EAI_NODATA: int -EAI_NONAME: int -EAI_OVERFLOW: int -EAI_SERVICE: int -EAI_SOCKTYPE: int -EAI_SYSTEM: int -EBADF: int -EINTR: int -HCI_DATA_DIR: int -HCI_FILTER: int -HCI_TIME_STAMP: int -INADDR_ALLHOSTS_GROUP: int -INADDR_ANY: int -INADDR_BROADCAST: int -INADDR_LOOPBACK: int -INADDR_MAX_LOCAL_GROUP: int -INADDR_NONE: int -INADDR_UNSPEC_GROUP: int -IPPORT_RESERVED: int -IPPORT_USERRESERVED: int -IPPROTO_AH: int -IPPROTO_DSTOPTS: int -IPPROTO_EGP: int -IPPROTO_ESP: int -IPPROTO_FRAGMENT: int -IPPROTO_GRE: int -IPPROTO_HOPOPTS: int -IPPROTO_ICMP: int -IPPROTO_ICMPV6: int -IPPROTO_IDP: int -IPPROTO_IGMP: int -IPPROTO_IP: int -IPPROTO_IPIP: int -IPPROTO_IPV6: int -IPPROTO_NONE: int -IPPROTO_PIM: int -IPPROTO_PUP: int -IPPROTO_RAW: int -IPPROTO_ROUTING: int -IPPROTO_RSVP: int -IPPROTO_TCP: int -IPPROTO_TP: int -IPPROTO_UDP: int -IPV6_CHECKSUM: int -IPV6_DSTOPTS: int -IPV6_HOPLIMIT: int -IPV6_HOPOPTS: int -IPV6_JOIN_GROUP: int -IPV6_LEAVE_GROUP: int -IPV6_MULTICAST_HOPS: int -IPV6_MULTICAST_IF: int -IPV6_MULTICAST_LOOP: int -IPV6_NEXTHOP: int -IPV6_PKTINFO: int -IPV6_RECVDSTOPTS: int -IPV6_RECVHOPLIMIT: int -IPV6_RECVHOPOPTS: int -IPV6_RECVPKTINFO: int -IPV6_RECVRTHDR: int -IPV6_RECVTCLASS: int -IPV6_RTHDR: int -IPV6_RTHDRDSTOPTS: int -IPV6_RTHDR_TYPE_0: int -IPV6_TCLASS: int -IPV6_UNICAST_HOPS: int -IPV6_V6ONLY: int -IP_ADD_MEMBERSHIP: int -IP_DEFAULT_MULTICAST_LOOP: int -IP_DEFAULT_MULTICAST_TTL: int -IP_DROP_MEMBERSHIP: int -IP_HDRINCL: int -IP_MAX_MEMBERSHIPS: int -IP_MULTICAST_IF: int -IP_MULTICAST_LOOP: int -IP_MULTICAST_TTL: int -IP_OPTIONS: int -IP_RECVOPTS: int -IP_RECVRETOPTS: int -IP_RETOPTS: int -IP_TOS: int -IP_TTL: int -MSG_CTRUNC: int -MSG_DONTROUTE: int -MSG_DONTWAIT: int -MSG_EOR: int -MSG_OOB: int -MSG_PEEK: int -MSG_TRUNC: int -MSG_WAITALL: int -MethodType: type -NETLINK_DNRTMSG: int -NETLINK_FIREWALL: int -NETLINK_IP6_FW: int -NETLINK_NFLOG: int -NETLINK_ROUTE: int -NETLINK_USERSOCK: int -NETLINK_XFRM: int -NI_DGRAM: int -NI_MAXHOST: int -NI_MAXSERV: int -NI_NAMEREQD: int -NI_NOFQDN: int -NI_NUMERICHOST: int -NI_NUMERICSERV: int -PACKET_BROADCAST: int -PACKET_FASTROUTE: int -PACKET_HOST: int -PACKET_LOOPBACK: int -PACKET_MULTICAST: int -PACKET_OTHERHOST: int -PACKET_OUTGOING: int -PF_PACKET: int -SHUT_RD: int -SHUT_RDWR: int -SHUT_WR: int -SOCK_DGRAM: int -SOCK_RAW: int -SOCK_RDM: int -SOCK_SEQPACKET: int -SOCK_STREAM: int -SOL_HCI: int -SOL_IP: int -SOL_SOCKET: int -SOL_TCP: int -SOL_TIPC: int -SOL_UDP: int -SOMAXCONN: int -SO_ACCEPTCONN: int -SO_BROADCAST: int -SO_DEBUG: int -SO_DONTROUTE: int -SO_ERROR: int -SO_KEEPALIVE: int -SO_LINGER: int -SO_OOBINLINE: int -SO_RCVBUF: int -SO_RCVLOWAT: int -SO_RCVTIMEO: int -SO_REUSEADDR: int -SO_REUSEPORT: int -SO_SNDBUF: int -SO_SNDLOWAT: int -SO_SNDTIMEO: int -SO_TYPE: int -SSL_ERROR_EOF: int -SSL_ERROR_INVALID_ERROR_CODE: int -SSL_ERROR_SSL: int -SSL_ERROR_SYSCALL: int -SSL_ERROR_WANT_CONNECT: int -SSL_ERROR_WANT_READ: int -SSL_ERROR_WANT_WRITE: int -SSL_ERROR_WANT_X509_LOOKUP: int -SSL_ERROR_ZERO_RETURN: int -TCP_CORK: int -TCP_DEFER_ACCEPT: int -TCP_INFO: int -TCP_KEEPCNT: int -TCP_KEEPIDLE: int -TCP_KEEPINTVL: int -TCP_LINGER2: int -TCP_MAXSEG: int -TCP_NODELAY: int -TCP_QUICKACK: int -TCP_SYNCNT: int -TCP_WINDOW_CLAMP: int -TIPC_ADDR_ID: int -TIPC_ADDR_NAME: int -TIPC_ADDR_NAMESEQ: int -TIPC_CFG_SRV: int -TIPC_CLUSTER_SCOPE: int -TIPC_CONN_TIMEOUT: int -TIPC_CRITICAL_IMPORTANCE: int -TIPC_DEST_DROPPABLE: int -TIPC_HIGH_IMPORTANCE: int -TIPC_IMPORTANCE: int -TIPC_LOW_IMPORTANCE: int -TIPC_MEDIUM_IMPORTANCE: int -TIPC_NODE_SCOPE: int -TIPC_PUBLISHED: int -TIPC_SRC_DROPPABLE: int -TIPC_SUBSCR_TIMEOUT: int -TIPC_SUB_CANCEL: int -TIPC_SUB_PORTS: int -TIPC_SUB_SERVICE: int -TIPC_TOP_SRV: int -TIPC_WAIT_FOREVER: int -TIPC_WITHDRAWN: int -TIPC_ZONE_SCOPE: int - -# PyCapsule -CAPI: Any - -has_ipv6: bool - -class error(IOError): ... -class gaierror(error): ... -class timeout(error): ... - -class SocketType(object): - family: int - type: int - proto: int - timeout: float - def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... - def accept(self) -> Tuple[SocketType, Tuple[Any, ...]]: ... - def bind(self, address: Tuple[Any, ...]) -> None: ... - def close(self) -> None: ... - def connect(self, address: Tuple[Any, ...]) -> None: ... - def connect_ex(self, address: Tuple[Any, ...]) -> int: ... - def dup(self) -> SocketType: ... - def fileno(self) -> int: ... - def getpeername(self) -> Tuple[Any, ...]: ... - def getsockname(self) -> Tuple[Any, ...]: ... - def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ... - def gettimeout(self) -> float: ... - def listen(self, backlog: int) -> None: ... - def makefile(self, mode: str = ..., buffersize: int = ...) -> IO[Any]: ... - def recv(self, buffersize: int, flags: int = ...) -> str: ... - def recv_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... - def recvfrom(self, buffersize: int, flags: int = ...) -> Tuple[Any, ...]: ... - def recvfrom_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... - def send(self, data: str, flags: int = ...) -> int: ... - def sendall(self, data: str, flags: int = ...) -> None: ... - @overload - def sendto(self, data: str, address: Tuple[Any, ...]) -> int: ... - @overload - def sendto(self, data: str, flags: int, address: Tuple[Any, ...]) -> int: ... - def setblocking(self, flag: bool) -> None: ... - def setsockopt(self, level: int, option: int, value: int | str) -> None: ... - def settimeout(self, value: float | None) -> None: ... - def shutdown(self, flag: int) -> None: ... diff --git a/stdlib/@python2/_sre.pyi b/stdlib/@python2/_sre.pyi deleted file mode 100644 index 3bacc097451e..000000000000 --- a/stdlib/@python2/_sre.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple, overload - -CODESIZE: int -MAGIC: int -MAXREPEAT: long -copyright: str - -class SRE_Match(object): - def start(self, group: int = ...) -> int: ... - def end(self, group: int = ...) -> int: ... - def expand(self, s: str) -> Any: ... - @overload - def group(self) -> str: ... - @overload - def group(self, group: int = ...) -> str | None: ... - def groupdict(self) -> Dict[int, str | None]: ... - def groups(self) -> Tuple[str | None, ...]: ... - def span(self) -> Tuple[int, int]: ... - @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented - -class SRE_Scanner(object): - pattern: str - def match(self) -> SRE_Match: ... - def search(self) -> SRE_Match: ... - -class SRE_Pattern(object): - pattern: str - flags: int - groups: int - groupindex: Mapping[str, int] - indexgroup: Sequence[int] - def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Tuple[Any, ...] | str]: ... - def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Tuple[Any, ...] | str]: ... - def match(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... - def scanner(self, s: str, start: int = ..., end: int = ...) -> SRE_Scanner: ... - def search(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... - def split(self, source: str, maxsplit: int = ...) -> List[str | None]: ... - def sub(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... - def subn(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... - -def compile( - pattern: str, - flags: int, - code: List[int], - groups: int = ..., - groupindex: Mapping[str, int] = ..., - indexgroup: Sequence[int] = ..., -) -> SRE_Pattern: ... -def getcodesize() -> int: ... -def getlower(a: int, b: int) -> int: ... diff --git a/stdlib/@python2/_struct.pyi b/stdlib/@python2/_struct.pyi deleted file mode 100644 index 316307eaabca..000000000000 --- a/stdlib/@python2/_struct.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any, AnyStr, Tuple - -class error(Exception): ... - -class Struct(object): - size: int - format: str - def __init__(self, fmt: str) -> None: ... - def pack_into(self, buffer: bytearray, offset: int, obj: Any) -> None: ... - def pack(self, *args) -> str: ... - def unpack(self, s: str) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... - -def _clearcache() -> None: ... -def calcsize(fmt: str) -> int: ... -def pack(fmt: AnyStr, obj: Any) -> str: ... -def pack_into(fmt: AnyStr, buffer: bytearray, offset: int, obj: Any) -> None: ... -def unpack(fmt: AnyStr, data: str) -> Tuple[Any, ...]: ... -def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/stdlib/@python2/_symtable.pyi b/stdlib/@python2/_symtable.pyi deleted file mode 100644 index 5b2370449c31..000000000000 --- a/stdlib/@python2/_symtable.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Dict, List - -CELL: int -DEF_BOUND: int -DEF_FREE: int -DEF_FREE_CLASS: int -DEF_GLOBAL: int -DEF_IMPORT: int -DEF_LOCAL: int -DEF_PARAM: int -FREE: int -GLOBAL_EXPLICIT: int -GLOBAL_IMPLICIT: int -LOCAL: int -OPT_BARE_EXEC: int -OPT_EXEC: int -OPT_IMPORT_STAR: int -SCOPE_MASK: int -SCOPE_OFF: int -TYPE_CLASS: int -TYPE_FUNCTION: int -TYPE_MODULE: int -USE: int - -class _symtable_entry(object): ... - -class symtable(object): - children: List[_symtable_entry] - id: int - lineno: int - name: str - nested: int - optimized: int - symbols: Dict[str, int] - type: int - varnames: List[str] - def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/stdlib/@python2/_thread.pyi b/stdlib/@python2/_thread.pyi deleted file mode 100644 index 562ece61e042..000000000000 --- a/stdlib/@python2/_thread.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from types import TracebackType -from typing import Any, Callable, Dict, NoReturn, Tuple, Type - -error = RuntimeError - -def _count() -> int: ... - -_dangling: Any - -class LockType: - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - def release(self) -> None: ... - def locked(self) -> bool: ... - def __enter__(self) -> bool: ... - def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> None: ... - -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> int: ... -def interrupt_main() -> None: ... -def exit() -> NoReturn: ... -def allocate_lock() -> LockType: ... -def get_ident() -> int: ... -def stack_size(size: int = ...) -> int: ... - -TIMEOUT_MAX: float diff --git a/stdlib/@python2/_threading_local.pyi b/stdlib/@python2/_threading_local.pyi deleted file mode 100644 index 481d304578dd..000000000000 --- a/stdlib/@python2/_threading_local.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class _localbase(object): ... - -class local(_localbase): - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... - def __del__(self) -> None: ... - -def _patch(self: local) -> None: ... diff --git a/stdlib/@python2/_tkinter.pyi b/stdlib/@python2/_tkinter.pyi deleted file mode 100644 index 378b04202c4f..000000000000 --- a/stdlib/@python2/_tkinter.pyi +++ /dev/null @@ -1,95 +0,0 @@ -from typing import Any -from typing_extensions import Literal - -# _tkinter is meant to be only used internally by tkinter, but some tkinter -# functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl -# object that hasn't been converted to a string. -# -# There are not many ways to get Tcl_Objs from tkinter, and I'm not sure if the -# only existing ways are supposed to return Tcl_Objs as opposed to returning -# strings. Here's one of these things that return Tcl_Objs: -# -# >>> import tkinter -# >>> text = tkinter.Text() -# >>> text.tag_add('foo', '1.0', 'end') -# >>> text.tag_ranges('foo') -# (, ) -class Tcl_Obj: - string: str # str(tclobj) returns this - typename: str - -class TclError(Exception): ... - -# This class allows running Tcl code. Tkinter uses it internally a lot, and -# it's often handy to drop a piece of Tcl code into a tkinter program. Example: -# -# >>> import tkinter, _tkinter -# >>> tkapp = tkinter.Tk().tk -# >>> isinstance(tkapp, _tkinter.TkappType) -# True -# >>> tkapp.call('set', 'foo', (1,2,3)) -# (1, 2, 3) -# >>> tkapp.eval('return $foo') -# '1 2 3' -# >>> -# -# call args can be pretty much anything. Also, call(some_tuple) is same as call(*some_tuple). -# -# eval always returns str because _tkinter_tkapp_eval_impl in _tkinter.c calls -# Tkapp_UnicodeResult, and it returns a string when it succeeds. -class TkappType: - # Please keep in sync with tkinter.Tk - def call(self, __command: Any, *args: Any) -> Any: ... - def eval(self, __script: str) -> str: ... - adderrorinfo: Any - createcommand: Any - createfilehandler: Any - createtimerhandler: Any - deletecommand: Any - deletefilehandler: Any - dooneevent: Any - evalfile: Any - exprboolean: Any - exprdouble: Any - exprlong: Any - exprstring: Any - getboolean: Any - getdouble: Any - getint: Any - getvar: Any - globalgetvar: Any - globalsetvar: Any - globalunsetvar: Any - interpaddr: Any - loadtk: Any - mainloop: Any - quit: Any - record: Any - setvar: Any - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any - -# These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS -ALL_EVENTS: Literal[-3] -FILE_EVENTS: Literal[8] -IDLE_EVENTS: Literal[32] -TIMER_EVENTS: Literal[16] -WINDOW_EVENTS: Literal[4] - -DONT_WAIT: Literal[2] -EXCEPTION: Literal[8] -READABLE: Literal[2] -WRITABLE: Literal[4] - -TCL_VERSION: str -TK_VERSION: str - -# TODO: figure out what these are (with e.g. help()) and get rid of Any -TkttType: Any -_flatten: Any -create: Any -getbusywaitinterval: Any -setbusywaitinterval: Any diff --git a/stdlib/@python2/_typeshed/__init__.pyi b/stdlib/@python2/_typeshed/__init__.pyi deleted file mode 100644 index ca698e29ae8a..000000000000 --- a/stdlib/@python2/_typeshed/__init__.pyi +++ /dev/null @@ -1,162 +0,0 @@ -# Utility types for typeshed - -# This module contains various common types to be used by typeshed. The -# module and its types do not exist at runtime. You can use this module -# outside of typeshed, but no API stability guarantees are made. To use -# it in implementation (.py) files, the following construct must be used: -# -# from typing import TYPE_CHECKING -# if TYPE_CHECKING: -# from _typeshed import ... -# -# If on Python versions < 3.10 and "from __future__ import annotations" -# is not used, types from this module must be quoted. - -import array -import mmap -from typing import Any, Container, Iterable, Protocol, Text, Tuple, TypeVar, Union -from typing_extensions import Literal, final - -_KT = TypeVar("_KT") -_KT_co = TypeVar("_KT_co", covariant=True) -_KT_contra = TypeVar("_KT_contra", contravariant=True) -_VT = TypeVar("_VT") -_VT_co = TypeVar("_VT_co", covariant=True) -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) -_T_contra = TypeVar("_T_contra", contravariant=True) - -# Use for "self" annotations: -# def __enter__(self: Self) -> Self: ... -Self = TypeVar("Self") # noqa Y001 - -class IdentityFunction(Protocol): - def __call__(self, __x: _T) -> _T: ... - -class SupportsLessThan(Protocol): - def __lt__(self, __other: Any) -> bool: ... - -SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001 - -class SupportsDivMod(Protocol[_T_contra, _T_co]): - def __divmod__(self, __other: _T_contra) -> _T_co: ... - -class SupportsRDivMod(Protocol[_T_contra, _T_co]): - def __rdivmod__(self, __other: _T_contra) -> _T_co: ... - -# Mapping-like protocols - -class SupportsItems(Protocol[_KT_co, _VT_co]): - # We want dictionaries to support this on Python 2. - def items(self) -> Iterable[Tuple[_KT_co, _VT_co]]: ... - -class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): - def keys(self) -> Iterable[_KT]: ... - def __getitem__(self, __k: _KT) -> _VT_co: ... - -class SupportsGetItem(Container[_KT_contra], Protocol[_KT_contra, _VT_co]): - def __getitem__(self, __k: _KT_contra) -> _VT_co: ... - -class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, _VT]): - def __setitem__(self, __k: _KT_contra, __v: _VT) -> None: ... - def __delitem__(self, __v: _KT_contra) -> None: ... - -# These aliases can be used in places where a PathLike object can be used -# instead of a string in Python 3. -StrPath = Text -BytesPath = str -StrOrBytesPath = Text -AnyPath = StrOrBytesPath # obsolete, will be removed soon - -OpenTextModeUpdating = Literal[ - "r+", - "+r", - "rt+", - "r+t", - "+rt", - "tr+", - "t+r", - "+tr", - "w+", - "+w", - "wt+", - "w+t", - "+wt", - "tw+", - "t+w", - "+tw", - "a+", - "+a", - "at+", - "a+t", - "+at", - "ta+", - "t+a", - "+ta", - "x+", - "+x", - "xt+", - "x+t", - "+xt", - "tx+", - "t+x", - "+tx", -] -OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] -OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] -OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] -OpenBinaryModeUpdating = Literal[ - "rb+", - "r+b", - "+rb", - "br+", - "b+r", - "+br", - "wb+", - "w+b", - "+wb", - "bw+", - "b+w", - "+bw", - "ab+", - "a+b", - "+ab", - "ba+", - "b+a", - "+ba", - "xb+", - "x+b", - "+xb", - "bx+", - "b+x", - "+bx", -] -OpenBinaryModeWriting = Literal["wb", "bw", "ab", "ba", "xb", "bx"] -OpenBinaryModeReading = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] -OpenBinaryMode = Union[OpenBinaryModeUpdating, OpenBinaryModeReading, OpenBinaryModeWriting] - -class HasFileno(Protocol): - def fileno(self) -> int: ... - -FileDescriptor = int -FileDescriptorLike = Union[int, HasFileno] - -class SupportsRead(Protocol[_T_co]): - def read(self, __length: int = ...) -> _T_co: ... - -class SupportsReadline(Protocol[_T_co]): - def readline(self, __length: int = ...) -> _T_co: ... - -class SupportsNoArgReadline(Protocol[_T_co]): - def readline(self) -> _T_co: ... - -class SupportsWrite(Protocol[_T_contra]): - def write(self, __s: _T_contra) -> Any: ... - -ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap, buffer] -WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, buffer] - -# Used by type checkers for checks involving None (does not exist at runtime) -@final -class NoneType: - def __bool__(self) -> Literal[False]: ... diff --git a/stdlib/@python2/_typeshed/wsgi.pyi b/stdlib/@python2/_typeshed/wsgi.pyi deleted file mode 100644 index a1f10443a6f0..000000000000 --- a/stdlib/@python2/_typeshed/wsgi.pyi +++ /dev/null @@ -1,35 +0,0 @@ -# Types to support PEP 3333 (WSGI) -# -# This module doesn't exist at runtime and neither do the types defined in this -# file. They are provided for type checking purposes. - -from sys import _OptExcInfo -from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Text, Tuple - -class StartResponse(Protocol): - def __call__( - self, status: str, headers: List[Tuple[str, str]], exc_info: _OptExcInfo | None = ... - ) -> Callable[[bytes], Any]: ... - -WSGIEnvironment = Dict[Text, Any] -WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] - -# WSGI input streams per PEP 3333 -class InputStream(Protocol): - def read(self, size: int = ...) -> bytes: ... - def readline(self, size: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... - def __iter__(self) -> Iterable[bytes]: ... - -# WSGI error streams per PEP 3333 -class ErrorStream(Protocol): - def flush(self) -> None: ... - def write(self, s: str) -> None: ... - def writelines(self, seq: List[str]) -> None: ... - -class _Readable(Protocol): - def read(self, size: int = ...) -> bytes: ... - -# Optional file wrapper in wsgi.file_wrapper -class FileWrapper(Protocol): - def __call__(self, file: _Readable, block_size: int = ...) -> Iterable[bytes]: ... diff --git a/stdlib/@python2/_typeshed/xml.pyi b/stdlib/@python2/_typeshed/xml.pyi deleted file mode 100644 index eaff9a641db4..000000000000 --- a/stdlib/@python2/_typeshed/xml.pyi +++ /dev/null @@ -1,9 +0,0 @@ -# Stub-only types. This module does not exist at runtime. - -from typing import Any, Protocol - -# As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects -class DOMImplementation(Protocol): - def hasFeature(self, feature: str, version: str | None) -> bool: ... - def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Any | None) -> Any: ... - def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str) -> Any: ... diff --git a/stdlib/@python2/_warnings.pyi b/stdlib/@python2/_warnings.pyi deleted file mode 100644 index ccc51fecb8da..000000000000 --- a/stdlib/@python2/_warnings.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any, Dict, List, Tuple, Type, overload - -default_action: str -once_registry: Dict[Any, Any] - -filters: List[Tuple[Any, ...]] - -@overload -def warn(message: str, category: Type[Warning] | None = ..., stacklevel: int = ...) -> None: ... -@overload -def warn(message: Warning, category: Any = ..., stacklevel: int = ...) -> None: ... -@overload -def warn_explicit( - message: str, - category: Type[Warning], - filename: str, - lineno: int, - module: str | None = ..., - registry: Dict[str | Tuple[str, Type[Warning], int], int] | None = ..., - module_globals: Dict[str, Any] | None = ..., -) -> None: ... -@overload -def warn_explicit( - message: Warning, - category: Any, - filename: str, - lineno: int, - module: str | None = ..., - registry: Dict[str | Tuple[str, Type[Warning], int], int] | None = ..., - module_globals: Dict[str, Any] | None = ..., -) -> None: ... diff --git a/stdlib/@python2/_weakref.pyi b/stdlib/@python2/_weakref.pyi deleted file mode 100644 index a283d4cb60d3..000000000000 --- a/stdlib/@python2/_weakref.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any, Callable, Generic, List, TypeVar, overload - -_C = TypeVar("_C", bound=Callable[..., Any]) -_T = TypeVar("_T") - -class CallableProxyType(Generic[_C]): # "weakcallableproxy" - def __getattr__(self, attr: str) -> Any: ... - -class ProxyType(Generic[_T]): # "weakproxy" - def __getattr__(self, attr: str) -> Any: ... - -class ReferenceType(Generic[_T]): - def __init__(self, o: _T, callback: Callable[[ReferenceType[_T]], Any] | None = ...) -> None: ... - def __call__(self) -> _T | None: ... - def __hash__(self) -> int: ... - -ref = ReferenceType - -def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(object: Any) -> List[Any]: ... -@overload -def proxy(object: _C, callback: Callable[[_C], Any] | None = ...) -> CallableProxyType[_C]: ... - -# Return CallableProxyType if object is callable, ProxyType otherwise -@overload -def proxy(object: _T, callback: Callable[[_T], Any] | None = ...) -> Any: ... diff --git a/stdlib/@python2/_weakrefset.pyi b/stdlib/@python2/_weakrefset.pyi deleted file mode 100644 index f2cde7d67e52..000000000000 --- a/stdlib/@python2/_weakrefset.pyi +++ /dev/null @@ -1,41 +0,0 @@ -from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar - -_S = TypeVar("_S") -_T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) - -class WeakSet(MutableSet[_T], Generic[_T]): - def __init__(self, data: Iterable[_T] | None = ...) -> None: ... - def add(self, item: _T) -> None: ... - def clear(self) -> None: ... - def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... - def pop(self) -> _T: ... - def remove(self, item: _T) -> None: ... - def update(self, other: Iterable[_T]) -> None: ... - def __contains__(self, item: object) -> bool: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __ior__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def issubset(self, other: Iterable[_T]) -> bool: ... - def __le__(self, other: Iterable[_T]) -> bool: ... - def __lt__(self, other: Iterable[_T]) -> bool: ... - def issuperset(self, other: Iterable[_T]) -> bool: ... - def __ge__(self, other: Iterable[_T]) -> bool: ... - def __gt__(self, other: Iterable[_T]) -> bool: ... - def __eq__(self, other: object) -> bool: ... - def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def __xor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... - def __ixor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def isdisjoint(self, other: Iterable[_T]) -> bool: ... diff --git a/stdlib/@python2/_winreg.pyi b/stdlib/@python2/_winreg.pyi deleted file mode 100644 index 7297626ac8b3..000000000000 --- a/stdlib/@python2/_winreg.pyi +++ /dev/null @@ -1,96 +0,0 @@ -from types import TracebackType -from typing import Any, Tuple, Type, Union - -_KeyType = Union[HKEYType, int] - -def CloseKey(__hkey: _KeyType) -> None: ... -def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... -def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... -def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = ..., access: int = ...) -> HKEYType: ... -def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... -def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... -def DeleteValue(__key: _KeyType, __value: str) -> None: ... -def EnumKey(__key: _KeyType, __index: int) -> str: ... -def EnumValue(__key: _KeyType, __index: int) -> Tuple[str, Any, int]: ... -def ExpandEnvironmentStrings(__str: str) -> str: ... -def FlushKey(__key: _KeyType) -> None: ... -def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... -def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def QueryInfoKey(__key: _KeyType) -> Tuple[int, int, int]: ... -def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... -def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... -def SaveKey(__key: _KeyType, __file_name: str) -> None: ... -def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... -def SetValueEx( - __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int -) -> None: ... # reserved is ignored -def DisableReflectionKey(__key: _KeyType) -> None: ... -def EnableReflectionKey(__key: _KeyType) -> None: ... -def QueryReflectionKey(__key: _KeyType) -> bool: ... - -HKEY_CLASSES_ROOT: int -HKEY_CURRENT_USER: int -HKEY_LOCAL_MACHINE: int -HKEY_USERS: int -HKEY_PERFORMANCE_DATA: int -HKEY_CURRENT_CONFIG: int -HKEY_DYN_DATA: int - -KEY_ALL_ACCESS: int -KEY_WRITE: int -KEY_READ: int -KEY_EXECUTE: int -KEY_QUERY_VALUE: int -KEY_SET_VALUE: int -KEY_CREATE_SUB_KEY: int -KEY_ENUMERATE_SUB_KEYS: int -KEY_NOTIFY: int -KEY_CREATE_LINK: int - -KEY_WOW64_64KEY: int -KEY_WOW64_32KEY: int - -REG_BINARY: int -REG_DWORD: int -REG_DWORD_LITTLE_ENDIAN: int -REG_DWORD_BIG_ENDIAN: int -REG_EXPAND_SZ: int -REG_LINK: int -REG_MULTI_SZ: int -REG_NONE: int -REG_RESOURCE_LIST: int -REG_FULL_RESOURCE_DESCRIPTOR: int -REG_RESOURCE_REQUIREMENTS_LIST: int -REG_SZ: int - -REG_CREATED_NEW_KEY: int # undocumented -REG_LEGAL_CHANGE_FILTER: int # undocumented -REG_LEGAL_OPTION: int # undocumented -REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented -REG_NOTIFY_CHANGE_LAST_SET: int # undocumented -REG_NOTIFY_CHANGE_NAME: int # undocumented -REG_NOTIFY_CHANGE_SECURITY: int # undocumented -REG_NO_LAZY_FLUSH: int # undocumented -REG_OPENED_EXISTING_KEY: int # undocumented -REG_OPTION_BACKUP_RESTORE: int # undocumented -REG_OPTION_CREATE_LINK: int # undocumented -REG_OPTION_NON_VOLATILE: int # undocumented -REG_OPTION_OPEN_LINK: int # undocumented -REG_OPTION_RESERVED: int # undocumented -REG_OPTION_VOLATILE: int # undocumented -REG_REFRESH_HIVE: int # undocumented -REG_WHOLE_HIVE_VOLATILE: int # undocumented - -error = OSError - -# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason -class HKEYType: - def __bool__(self) -> bool: ... - def __int__(self) -> int: ... - def __enter__(self) -> HKEYType: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def Close(self) -> None: ... - def Detach(self) -> int: ... diff --git a/stdlib/@python2/abc.pyi b/stdlib/@python2/abc.pyi deleted file mode 100644 index ac14246d44a5..000000000000 --- a/stdlib/@python2/abc.pyi +++ /dev/null @@ -1,31 +0,0 @@ -import _weakrefset -from _typeshed import SupportsWrite -from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar - -_FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) - -# NOTE: mypy has special processing for ABCMeta and abstractmethod. - -def abstractmethod(funcobj: _FuncT) -> _FuncT: ... - -class ABCMeta(type): - __abstractmethods__: frozenset[str] - _abc_cache: _weakrefset.WeakSet[Any] - _abc_invalidation_counter: int - _abc_negative_cache: _weakrefset.WeakSet[Any] - _abc_negative_cache_version: int - _abc_registry: _weakrefset.WeakSet[Any] - def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> None: ... - def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... - def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... - def _dump_registry(cls: ABCMeta, file: SupportsWrite[Any] | None = ...) -> None: ... - def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... - -# TODO: The real abc.abstractproperty inherits from "property". -class abstractproperty(object): - def __new__(cls, func: Any) -> Any: ... - __isabstractmethod__: bool - doc: Any - fdel: Any - fget: Any - fset: Any diff --git a/stdlib/@python2/aifc.pyi b/stdlib/@python2/aifc.pyi deleted file mode 100644 index 42f20b7466a1..000000000000 --- a/stdlib/@python2/aifc.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from typing import IO, Any, List, NamedTuple, Text, Tuple, Union, overload -from typing_extensions import Literal - -class Error(Exception): ... - -class _aifc_params(NamedTuple): - nchannels: int - sampwidth: int - framerate: int - nframes: int - comptype: bytes - compname: bytes - -_File = Union[Text, IO[bytes]] -_Marker = Tuple[int, int, bytes] - -class Aifc_read: - def __init__(self, f: _File) -> None: ... - def initfp(self, file: IO[bytes]) -> None: ... - def getfp(self) -> IO[bytes]: ... - def rewind(self) -> None: ... - def close(self) -> None: ... - def tell(self) -> int: ... - def getnchannels(self) -> int: ... - def getnframes(self) -> int: ... - def getsampwidth(self) -> int: ... - def getframerate(self) -> int: ... - def getcomptype(self) -> bytes: ... - def getcompname(self) -> bytes: ... - def getparams(self) -> _aifc_params: ... - def getmarkers(self) -> List[_Marker] | None: ... - def getmark(self, id: int) -> _Marker: ... - def setpos(self, pos: int) -> None: ... - def readframes(self, nframes: int) -> bytes: ... - -class Aifc_write: - def __init__(self, f: _File) -> None: ... - def __del__(self) -> None: ... - def initfp(self, file: IO[bytes]) -> None: ... - def aiff(self) -> None: ... - def aifc(self) -> None: ... - def setnchannels(self, nchannels: int) -> None: ... - def getnchannels(self) -> int: ... - def setsampwidth(self, sampwidth: int) -> None: ... - def getsampwidth(self) -> int: ... - def setframerate(self, framerate: int) -> None: ... - def getframerate(self) -> int: ... - def setnframes(self, nframes: int) -> None: ... - def getnframes(self) -> int: ... - def setcomptype(self, comptype: bytes, compname: bytes) -> None: ... - def getcomptype(self) -> bytes: ... - def getcompname(self) -> bytes: ... - def setparams(self, params: Tuple[int, int, int, int, bytes, bytes]) -> None: ... - def getparams(self) -> _aifc_params: ... - def setmark(self, id: int, pos: int, name: bytes) -> None: ... - def getmark(self, id: int) -> _Marker: ... - def getmarkers(self) -> List[_Marker] | None: ... - def tell(self) -> int: ... - def writeframesraw(self, data: Any) -> None: ... # Actual type for data is Buffer Protocol - def writeframes(self, data: Any) -> None: ... - def close(self) -> None: ... - -@overload -def open(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... -@overload -def open(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... -@overload -def open(f: _File, mode: str | None = ...) -> Any: ... -@overload -def openfp(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... -@overload -def openfp(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... -@overload -def openfp(f: _File, mode: str | None = ...) -> Any: ... diff --git a/stdlib/@python2/argparse.pyi b/stdlib/@python2/argparse.pyi deleted file mode 100644 index 4d77f6582c5f..000000000000 --- a/stdlib/@python2/argparse.pyi +++ /dev/null @@ -1,371 +0,0 @@ -from typing import ( - IO, - Any, - Callable, - Dict, - Generator, - Iterable, - List, - NoReturn, - Pattern, - Protocol, - Sequence, - Text, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -_T = TypeVar("_T") -_ActionT = TypeVar("_ActionT", bound=Action) -_N = TypeVar("_N") - -_Text = Union[str, unicode] - -ONE_OR_MORE: str -OPTIONAL: str -PARSER: str -REMAINDER: str -SUPPRESS: str -ZERO_OR_MORE: str -_UNRECOGNIZED_ARGS_ATTR: str # undocumented - -class ArgumentError(Exception): - argument_name: str | None - message: str - def __init__(self, argument: Action | None, message: str) -> None: ... - -# undocumented -class _AttributeHolder: - def _get_kwargs(self) -> List[Tuple[str, Any]]: ... - def _get_args(self) -> List[Any]: ... - -# undocumented -class _ActionsContainer: - description: _Text | None - prefix_chars: _Text - argument_default: Any - conflict_handler: _Text - - _registries: Dict[_Text, Dict[Any, Any]] - _actions: List[Action] - _option_string_actions: Dict[_Text, Action] - _action_groups: List[_ArgumentGroup] - _mutually_exclusive_groups: List[_MutuallyExclusiveGroup] - _defaults: Dict[str, Any] - _negative_number_matcher: Pattern[str] - _has_negative_number_optionals: List[bool] - def __init__(self, description: Text | None, prefix_chars: Text, argument_default: Any, conflict_handler: Text) -> None: ... - def register(self, registry_name: Text, value: Any, object: Any) -> None: ... - def _registry_get(self, registry_name: Text, value: Any, default: Any = ...) -> Any: ... - def set_defaults(self, **kwargs: Any) -> None: ... - def get_default(self, dest: Text) -> Any: ... - def add_argument( - self, - *name_or_flags: Text, - action: Text | Type[Action] = ..., - nargs: int | Text = ..., - const: Any = ..., - default: Any = ..., - type: Callable[[Text], _T] | Callable[[str], _T] | FileType = ..., - choices: Iterable[_T] = ..., - required: bool = ..., - help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., - dest: Text | None = ..., - version: Text = ..., - **kwargs: Any, - ) -> Action: ... - def add_argument_group(self, *args: Any, **kwargs: Any) -> _ArgumentGroup: ... - def add_mutually_exclusive_group(self, **kwargs: Any) -> _MutuallyExclusiveGroup: ... - def _add_action(self, action: _ActionT) -> _ActionT: ... - def _remove_action(self, action: Action) -> None: ... - def _add_container_actions(self, container: _ActionsContainer) -> None: ... - def _get_positional_kwargs(self, dest: Text, **kwargs: Any) -> Dict[str, Any]: ... - def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ... - def _pop_action_class(self, kwargs: Any, default: Type[Action] | None = ...) -> Type[Action]: ... - def _get_handler(self) -> Callable[[Action, Iterable[Tuple[Text, Action]]], Any]: ... - def _check_conflict(self, action: Action) -> None: ... - def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> NoReturn: ... - def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> None: ... - -class _FormatterClass(Protocol): - def __call__(self, prog: str) -> HelpFormatter: ... - -class ArgumentParser(_AttributeHolder, _ActionsContainer): - prog: _Text - usage: _Text | None - epilog: _Text | None - formatter_class: _FormatterClass - fromfile_prefix_chars: _Text | None - add_help: bool - - # undocumented - _positionals: _ArgumentGroup - _optionals: _ArgumentGroup - _subparsers: _ArgumentGroup | None - def __init__( - self, - prog: Text | None = ..., - usage: Text | None = ..., - description: Text | None = ..., - epilog: Text | None = ..., - parents: Sequence[ArgumentParser] = ..., - formatter_class: _FormatterClass = ..., - prefix_chars: Text = ..., - fromfile_prefix_chars: Text | None = ..., - argument_default: Any = ..., - conflict_handler: Text = ..., - add_help: bool = ..., - ) -> None: ... - # The type-ignores in these overloads should be temporary. See: - # https://github.com/python/typeshed/pull/2643#issuecomment-442280277 - @overload - def parse_args(self, args: Sequence[Text] | None = ...) -> Namespace: ... - @overload - def parse_args(self, args: Sequence[Text] | None, namespace: None) -> Namespace: ... # type: ignore - @overload - def parse_args(self, args: Sequence[Text] | None, namespace: _N) -> _N: ... - @overload - def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore - @overload - def parse_args(self, *, namespace: _N) -> _N: ... - def add_subparsers( - self, - *, - title: Text = ..., - description: Text | None = ..., - prog: Text = ..., - parser_class: Type[ArgumentParser] = ..., - action: Type[Action] = ..., - option_string: Text = ..., - dest: Text | None = ..., - help: Text | None = ..., - metavar: Text | None = ..., - ) -> _SubParsersAction: ... - def print_usage(self, file: IO[str] | None = ...) -> None: ... - def print_help(self, file: IO[str] | None = ...) -> None: ... - def format_usage(self) -> str: ... - def format_help(self) -> str: ... - def parse_known_args( - self, args: Sequence[Text] | None = ..., namespace: Namespace | None = ... - ) -> Tuple[Namespace, List[str]]: ... - def convert_arg_line_to_args(self, arg_line: Text) -> List[str]: ... - def exit(self, status: int = ..., message: Text | None = ...) -> NoReturn: ... - def error(self, message: Text) -> NoReturn: ... - # undocumented - def _get_optional_actions(self) -> List[Action]: ... - def _get_positional_actions(self) -> List[Action]: ... - def _parse_known_args(self, arg_strings: List[Text], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... - def _read_args_from_files(self, arg_strings: List[Text]) -> List[Text]: ... - def _match_argument(self, action: Action, arg_strings_pattern: Text) -> int: ... - def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: Text) -> List[int]: ... - def _parse_optional(self, arg_string: Text) -> Tuple[Action | None, Text, Text | None] | None: ... - def _get_option_tuples(self, option_string: Text) -> List[Tuple[Action, Text, Text | None]]: ... - def _get_nargs_pattern(self, action: Action) -> _Text: ... - def _get_values(self, action: Action, arg_strings: List[Text]) -> Any: ... - def _get_value(self, action: Action, arg_string: Text) -> Any: ... - def _check_value(self, action: Action, value: Any) -> None: ... - def _get_formatter(self) -> HelpFormatter: ... - def _print_message(self, message: str, file: IO[str] | None = ...) -> None: ... - -class HelpFormatter: - # undocumented - _prog: _Text - _indent_increment: int - _max_help_position: int - _width: int - _current_indent: int - _level: int - _action_max_length: int - _root_section: Any - _current_section: Any - _whitespace_matcher: Pattern[str] - _long_break_matcher: Pattern[str] - _Section: Type[Any] # Nested class - def __init__( - self, prog: Text, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ... - ) -> None: ... - def _indent(self) -> None: ... - def _dedent(self) -> None: ... - def _add_item(self, func: Callable[..., _Text], args: Iterable[Any]) -> None: ... - def start_section(self, heading: Text | None) -> None: ... - def end_section(self) -> None: ... - def add_text(self, text: Text | None) -> None: ... - def add_usage( - self, usage: Text | None, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Text | None = ... - ) -> None: ... - def add_argument(self, action: Action) -> None: ... - def add_arguments(self, actions: Iterable[Action]) -> None: ... - def format_help(self) -> _Text: ... - def _join_parts(self, part_strings: Iterable[Text]) -> _Text: ... - def _format_usage( - self, usage: Text, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Text | None - ) -> _Text: ... - def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> _Text: ... - def _format_text(self, text: Text) -> _Text: ... - def _format_action(self, action: Action) -> _Text: ... - def _format_action_invocation(self, action: Action) -> _Text: ... - def _metavar_formatter(self, action: Action, default_metavar: Text) -> Callable[[int], Tuple[_Text, ...]]: ... - def _format_args(self, action: Action, default_metavar: Text) -> _Text: ... - def _expand_help(self, action: Action) -> _Text: ... - def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... - def _split_lines(self, text: Text, width: int) -> List[_Text]: ... - def _fill_text(self, text: Text, width: int, indent: Text) -> _Text: ... - def _get_help_string(self, action: Action) -> _Text | None: ... - def _get_default_metavar_for_optional(self, action: Action) -> _Text: ... - def _get_default_metavar_for_positional(self, action: Action) -> _Text: ... - -class RawDescriptionHelpFormatter(HelpFormatter): ... -class RawTextHelpFormatter(RawDescriptionHelpFormatter): ... -class ArgumentDefaultsHelpFormatter(HelpFormatter): ... - -class Action(_AttributeHolder): - option_strings: Sequence[_Text] - dest: _Text - nargs: int | _Text | None - const: Any - default: Any - type: Callable[[str], Any] | FileType | None - choices: Iterable[Any] | None - required: bool - help: _Text | None - metavar: _Text | Tuple[_Text, ...] | None - def __init__( - self, - option_strings: Sequence[Text], - dest: Text, - nargs: int | Text | None = ..., - const: _T | None = ..., - default: _T | str | None = ..., - type: Callable[[Text], _T] | Callable[[str], _T] | FileType | None = ..., - choices: Iterable[_T] | None = ..., - required: bool = ..., - help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., - ) -> None: ... - def __call__( - self, parser: ArgumentParser, namespace: Namespace, values: Text | Sequence[Any] | None, option_string: Text | None = ... - ) -> None: ... - -class Namespace(_AttributeHolder): - def __init__(self, **kwargs: Any) -> None: ... - def __getattr__(self, name: Text) -> Any: ... - def __setattr__(self, name: Text, value: Any) -> None: ... - def __contains__(self, key: str) -> bool: ... - -class FileType: - # undocumented - _mode: _Text - _bufsize: int - def __init__(self, mode: Text = ..., bufsize: int | None = ...) -> None: ... - def __call__(self, string: Text) -> IO[Any]: ... - -# undocumented -class _ArgumentGroup(_ActionsContainer): - title: _Text | None - _group_actions: List[Action] - def __init__( - self, container: _ActionsContainer, title: Text | None = ..., description: Text | None = ..., **kwargs: Any - ) -> None: ... - -# undocumented -class _MutuallyExclusiveGroup(_ArgumentGroup): - required: bool - _container: _ActionsContainer - def __init__(self, container: _ActionsContainer, required: bool = ...) -> None: ... - -# undocumented -class _StoreAction(Action): ... - -# undocumented -class _StoreConstAction(Action): - def __init__( - self, - option_strings: Sequence[Text], - dest: Text, - const: Any, - default: Any = ..., - required: bool = ..., - help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., - ) -> None: ... - -# undocumented -class _StoreTrueAction(_StoreConstAction): - def __init__( - self, option_strings: Sequence[Text], dest: Text, default: bool = ..., required: bool = ..., help: Text | None = ... - ) -> None: ... - -# undocumented -class _StoreFalseAction(_StoreConstAction): - def __init__( - self, option_strings: Sequence[Text], dest: Text, default: bool = ..., required: bool = ..., help: Text | None = ... - ) -> None: ... - -# undocumented -class _AppendAction(Action): ... - -# undocumented -class _AppendConstAction(Action): - def __init__( - self, - option_strings: Sequence[Text], - dest: Text, - const: Any, - default: Any = ..., - required: bool = ..., - help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., - ) -> None: ... - -# undocumented -class _CountAction(Action): - def __init__( - self, option_strings: Sequence[Text], dest: Text, default: Any = ..., required: bool = ..., help: Text | None = ... - ) -> None: ... - -# undocumented -class _HelpAction(Action): - def __init__( - self, option_strings: Sequence[Text], dest: Text = ..., default: Text = ..., help: Text | None = ... - ) -> None: ... - -# undocumented -class _VersionAction(Action): - version: _Text | None - def __init__( - self, option_strings: Sequence[Text], version: Text | None = ..., dest: Text = ..., default: Text = ..., help: Text = ... - ) -> None: ... - -# undocumented -class _SubParsersAction(Action): - _ChoicesPseudoAction: Type[Any] # nested class - _prog_prefix: _Text - _parser_class: Type[ArgumentParser] - _name_parser_map: Dict[_Text, ArgumentParser] - choices: Dict[_Text, ArgumentParser] - _choices_actions: List[Action] - def __init__( - self, - option_strings: Sequence[Text], - prog: Text, - parser_class: Type[ArgumentParser], - dest: Text = ..., - help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., - ) -> None: ... - # TODO: Type keyword args properly. - def add_parser(self, name: Text, **kwargs: Any) -> ArgumentParser: ... - def _get_subactions(self) -> List[Action]: ... - -# undocumented -class ArgumentTypeError(Exception): ... - -# undocumented -def _ensure_value(namespace: Namespace, name: Text, value: Any) -> Any: ... - -# undocumented -def _get_action_name(argument: Action | None) -> str | None: ... diff --git a/stdlib/@python2/array.pyi b/stdlib/@python2/array.pyi deleted file mode 100644 index 39670fe734fc..000000000000 --- a/stdlib/@python2/array.pyi +++ /dev/null @@ -1,65 +0,0 @@ -from typing import Any, BinaryIO, Generic, Iterable, List, MutableSequence, Text, Tuple, TypeVar, Union, overload -from typing_extensions import Literal - -_IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] -_FloatTypeCode = Literal["f", "d"] -_UnicodeTypeCode = Literal["u"] -_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] - -_T = TypeVar("_T", int, float, Text) - -class array(MutableSequence[_T], Generic[_T]): - typecode: _TypeCode - itemsize: int - @overload - def __init__(self: array[int], typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... - @overload - def __init__(self: array[float], typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... - @overload - def __init__(self: array[Text], typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... - @overload - def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ... - def append(self, __v: _T) -> None: ... - def buffer_info(self) -> Tuple[int, int]: ... - def byteswap(self) -> None: ... - def count(self, __v: Any) -> int: ... - def extend(self, __bb: Iterable[_T]) -> None: ... - def fromfile(self, __f: BinaryIO, __n: int) -> None: ... - def fromlist(self, __list: List[_T]) -> None: ... - def fromunicode(self, __ustr: str) -> None: ... - def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence - def insert(self, __i: int, __v: _T) -> None: ... - def pop(self, __i: int = ...) -> _T: ... - def read(self, f: BinaryIO, n: int) -> None: ... - def remove(self, __v: Any) -> None: ... - def reverse(self) -> None: ... - def tofile(self, __f: BinaryIO) -> None: ... - def tolist(self) -> List[_T]: ... - def tounicode(self) -> str: ... - def write(self, f: BinaryIO) -> None: ... - def fromstring(self, __buffer: bytes) -> None: ... - def tostring(self) -> bytes: ... - def __len__(self) -> int: ... - @overload - def __getitem__(self, i: int) -> _T: ... - @overload - def __getitem__(self, s: slice) -> array[_T]: ... - @overload # type: ignore # Overrides MutableSequence - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - def __setitem__(self, s: slice, o: array[_T]) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __add__(self, x: array[_T]) -> array[_T]: ... - def __ge__(self, other: array[_T]) -> bool: ... - def __gt__(self, other: array[_T]) -> bool: ... - def __iadd__(self, x: array[_T]) -> array[_T]: ... # type: ignore # Overrides MutableSequence - def __imul__(self, n: int) -> array[_T]: ... - def __le__(self, other: array[_T]) -> bool: ... - def __lt__(self, other: array[_T]) -> bool: ... - def __mul__(self, n: int) -> array[_T]: ... - def __rmul__(self, n: int) -> array[_T]: ... - def __delslice__(self, i: int, j: int) -> None: ... - def __getslice__(self, i: int, j: int) -> array[_T]: ... - def __setslice__(self, i: int, j: int, y: array[_T]) -> None: ... - -ArrayType = array diff --git a/stdlib/@python2/ast.pyi b/stdlib/@python2/ast.pyi deleted file mode 100644 index b86e38dce4c5..000000000000 --- a/stdlib/@python2/ast.pyi +++ /dev/null @@ -1,27 +0,0 @@ -# Python 2.7 ast - -# Rename typing to _typing, as not to conflict with typing imported -# from _ast below when loaded in an unorthodox way by the Dropbox -# internal Bazel integration. -import typing as _typing -from _ast import * -from _ast import AST, Module -from typing import Any, Iterator - -def parse(source: str | unicode, filename: str | unicode = ..., mode: str | unicode = ...) -> Module: ... -def copy_location(new_node: AST, old_node: AST) -> AST: ... -def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... -def fix_missing_locations(node: AST) -> AST: ... -def get_docstring(node: AST, clean: bool = ...) -> str: ... -def increment_lineno(node: AST, n: int = ...) -> AST: ... -def iter_child_nodes(node: AST) -> Iterator[AST]: ... -def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... -def literal_eval(node_or_string: str | unicode | AST) -> Any: ... -def walk(node: AST) -> Iterator[AST]: ... - -class NodeVisitor: - def visit(self, node: AST) -> Any: ... - def generic_visit(self, node: AST) -> Any: ... - -class NodeTransformer(NodeVisitor): - def generic_visit(self, node: AST) -> AST | None: ... diff --git a/stdlib/@python2/asynchat.pyi b/stdlib/@python2/asynchat.pyi deleted file mode 100644 index 0f5526d71b1d..000000000000 --- a/stdlib/@python2/asynchat.pyi +++ /dev/null @@ -1,37 +0,0 @@ -import asyncore -import socket -from abc import abstractmethod -from typing import Sequence, Tuple - -class simple_producer: - def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... - def more(self) -> bytes: ... - -class async_chat(asyncore.dispatcher): - ac_in_buffer_size: int - ac_out_buffer_size: int - def __init__(self, sock: socket.socket | None = ..., map: asyncore._maptype | None = ...) -> None: ... - @abstractmethod - def collect_incoming_data(self, data: bytes) -> None: ... - @abstractmethod - def found_terminator(self) -> None: ... - def set_terminator(self, term: bytes | int | None) -> None: ... - def get_terminator(self) -> bytes | int | None: ... - def handle_read(self) -> None: ... - def handle_write(self) -> None: ... - def handle_close(self) -> None: ... - def push(self, data: bytes) -> None: ... - def push_with_producer(self, producer: simple_producer) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def close_when_done(self) -> None: ... - def initiate_send(self) -> None: ... - def discard_buffers(self) -> None: ... - -class fifo: - def __init__(self, list: Sequence[bytes | simple_producer] = ...) -> None: ... - def __len__(self) -> int: ... - def is_empty(self) -> bool: ... - def first(self) -> bytes: ... - def push(self, data: bytes | simple_producer) -> None: ... - def pop(self) -> Tuple[int, bytes]: ... diff --git a/stdlib/@python2/asyncore.pyi b/stdlib/@python2/asyncore.pyi deleted file mode 100644 index 95acf9b706d3..000000000000 --- a/stdlib/@python2/asyncore.pyi +++ /dev/null @@ -1,118 +0,0 @@ -import sys -from _typeshed import FileDescriptorLike -from socket import SocketType -from typing import Any, Dict, Optional, Tuple, overload - -# cyclic dependence with asynchat -_maptype = Dict[int, Any] - -socket_map: _maptype = ... # undocumented - -class ExitNow(Exception): ... - -def read(obj: Any) -> None: ... -def write(obj: Any) -> None: ... -def readwrite(obj: Any, flags: int) -> None: ... -def poll(timeout: float = ..., map: _maptype | None = ...) -> None: ... -def poll2(timeout: float = ..., map: _maptype | None = ...) -> None: ... - -poll3 = poll2 - -def loop(timeout: float = ..., use_poll: bool = ..., map: _maptype | None = ..., count: int | None = ...) -> None: ... - -# Not really subclass of socket.socket; it's only delegation. -# It is not covariant to it. -class dispatcher: - - debug: bool - connected: bool - accepting: bool - connecting: bool - closing: bool - ignore_log_types: frozenset[str] - socket: SocketType | None - def __init__(self, sock: SocketType | None = ..., map: _maptype | None = ...) -> None: ... - def add_channel(self, map: _maptype | None = ...) -> None: ... - def del_channel(self, map: _maptype | None = ...) -> None: ... - def create_socket(self, family: int = ..., type: int = ...) -> None: ... - def set_socket(self, sock: SocketType, map: _maptype | None = ...) -> None: ... - def set_reuse_addr(self) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def listen(self, num: int) -> None: ... - def bind(self, addr: Tuple[Any, ...] | str) -> None: ... - def connect(self, address: Tuple[Any, ...] | str) -> None: ... - def accept(self) -> Tuple[SocketType, Any] | None: ... - def send(self, data: bytes) -> int: ... - def recv(self, buffer_size: int) -> bytes: ... - def close(self) -> None: ... - def log(self, message: Any) -> None: ... - def log_info(self, message: Any, type: str = ...) -> None: ... - def handle_read_event(self) -> None: ... - def handle_connect_event(self) -> None: ... - def handle_write_event(self) -> None: ... - def handle_expt_event(self) -> None: ... - def handle_error(self) -> None: ... - def handle_expt(self) -> None: ... - def handle_read(self) -> None: ... - def handle_write(self) -> None: ... - def handle_connect(self) -> None: ... - def handle_accept(self) -> None: ... - def handle_close(self) -> None: ... - # Historically, some methods were "imported" from `self.socket` by - # means of `__getattr__`. This was long deprecated, and as of Python - # 3.5 has been removed; simply call the relevant methods directly on - # self.socket if necessary. - def detach(self) -> int: ... - def fileno(self) -> int: ... - # return value is an address - def getpeername(self) -> Any: ... - def getsockname(self) -> Any: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: None = ...) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - def gettimeout(self) -> float: ... - def ioctl(self, control: object, option: Tuple[int, int, int]) -> None: ... - # TODO the return value may be BinaryIO or TextIO, depending on mode - def makefile( - self, mode: str = ..., buffering: int = ..., encoding: str = ..., errors: str = ..., newline: str = ... - ) -> Any: ... - # return type is an address - def recvfrom(self, bufsize: int, flags: int = ...) -> Any: ... - def recvfrom_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... - def recv_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... - def sendall(self, data: bytes, flags: int = ...) -> None: ... - def sendto(self, data: bytes, address: Tuple[str, int] | str, flags: int = ...) -> int: ... - def setblocking(self, flag: bool) -> None: ... - def settimeout(self, value: float | None) -> None: ... - def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... - def shutdown(self, how: int) -> None: ... - -class dispatcher_with_send(dispatcher): - def __init__(self, sock: SocketType = ..., map: _maptype | None = ...) -> None: ... - def initiate_send(self) -> None: ... - def handle_write(self) -> None: ... - # incompatible signature: - # def send(self, data: bytes) -> Optional[int]: ... - -def compact_traceback() -> Tuple[Tuple[str, str, str], type, type, str]: ... -def close_all(map: _maptype | None = ..., ignore_all: bool = ...) -> None: ... - -if sys.platform != "win32": - class file_wrapper: - fd: int - def __init__(self, fd: int) -> None: ... - def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def send(self, data: bytes, flags: int = ...) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: None = ...) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - def read(self, bufsize: int, flags: int = ...) -> bytes: ... - def write(self, data: bytes, flags: int = ...) -> int: ... - def close(self) -> None: ... - def fileno(self) -> int: ... - class file_dispatcher(dispatcher): - def __init__(self, fd: FileDescriptorLike, map: _maptype | None = ...) -> None: ... - def set_file(self, fd: int) -> None: ... diff --git a/stdlib/@python2/atexit.pyi b/stdlib/@python2/atexit.pyi deleted file mode 100644 index 2336bf91149e..000000000000 --- a/stdlib/@python2/atexit.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any, TypeVar - -_FT = TypeVar("_FT") - -def register(func: _FT, *args: Any, **kargs: Any) -> _FT: ... diff --git a/stdlib/@python2/audioop.pyi b/stdlib/@python2/audioop.pyi deleted file mode 100644 index 71671afe487e..000000000000 --- a/stdlib/@python2/audioop.pyi +++ /dev/null @@ -1,42 +0,0 @@ -from typing import Tuple - -AdpcmState = Tuple[int, int] -RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] - -class error(Exception): ... - -def add(__fragment1: bytes, __fragment2: bytes, __width: int) -> bytes: ... -def adpcm2lin(__fragment: bytes, __width: int, __state: AdpcmState | None) -> Tuple[bytes, AdpcmState]: ... -def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... -def avg(__fragment: bytes, __width: int) -> int: ... -def avgpp(__fragment: bytes, __width: int) -> int: ... -def bias(__fragment: bytes, __width: int, __bias: int) -> bytes: ... -def byteswap(__fragment: bytes, __width: int) -> bytes: ... -def cross(__fragment: bytes, __width: int) -> int: ... -def findfactor(__fragment: bytes, __reference: bytes) -> float: ... -def findfit(__fragment: bytes, __reference: bytes) -> Tuple[int, float]: ... -def findmax(__fragment: bytes, __length: int) -> int: ... -def getsample(__fragment: bytes, __width: int, __index: int) -> int: ... -def lin2adpcm(__fragment: bytes, __width: int, __state: AdpcmState | None) -> Tuple[bytes, AdpcmState]: ... -def lin2alaw(__fragment: bytes, __width: int) -> bytes: ... -def lin2lin(__fragment: bytes, __width: int, __newwidth: int) -> bytes: ... -def lin2ulaw(__fragment: bytes, __width: int) -> bytes: ... -def max(__fragment: bytes, __width: int) -> int: ... -def maxpp(__fragment: bytes, __width: int) -> int: ... -def minmax(__fragment: bytes, __width: int) -> Tuple[int, int]: ... -def mul(__fragment: bytes, __width: int, __factor: float) -> bytes: ... -def ratecv( - __fragment: bytes, - __width: int, - __nchannels: int, - __inrate: int, - __outrate: int, - __state: RatecvState | None, - __weightA: int = ..., - __weightB: int = ..., -) -> Tuple[bytes, RatecvState]: ... -def reverse(__fragment: bytes, __width: int) -> bytes: ... -def rms(__fragment: bytes, __width: int) -> int: ... -def tomono(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... -def tostereo(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... -def ulaw2lin(__fragment: bytes, __width: int) -> bytes: ... diff --git a/stdlib/@python2/base64.pyi b/stdlib/@python2/base64.pyi deleted file mode 100644 index 00856aafddbe..000000000000 --- a/stdlib/@python2/base64.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import IO, Union - -_encodable = Union[bytes, unicode] -_decodable = Union[bytes, unicode] - -def b64encode(s: _encodable, altchars: bytes | None = ...) -> bytes: ... -def b64decode(s: _decodable, altchars: bytes | None = ..., validate: bool = ...) -> bytes: ... -def standard_b64encode(s: _encodable) -> bytes: ... -def standard_b64decode(s: _decodable) -> bytes: ... -def urlsafe_b64encode(s: _encodable) -> bytes: ... -def urlsafe_b64decode(s: _decodable) -> bytes: ... -def b32encode(s: _encodable) -> bytes: ... -def b32decode(s: _decodable, casefold: bool = ..., map01: bytes | None = ...) -> bytes: ... -def b16encode(s: _encodable) -> bytes: ... -def b16decode(s: _decodable, casefold: bool = ...) -> bytes: ... -def decode(input: IO[bytes], output: IO[bytes]) -> None: ... -def encode(input: IO[bytes], output: IO[bytes]) -> None: ... -def encodestring(s: bytes) -> bytes: ... -def decodestring(s: bytes) -> bytes: ... diff --git a/stdlib/@python2/bdb.pyi b/stdlib/@python2/bdb.pyi deleted file mode 100644 index 5bee9dadb928..000000000000 --- a/stdlib/@python2/bdb.pyi +++ /dev/null @@ -1,94 +0,0 @@ -from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Dict, Iterable, List, Mapping, Set, SupportsInt, Tuple, Type, TypeVar - -_T = TypeVar("_T") -_TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] - -GENERATOR_AND_COROUTINE_FLAGS: int = ... - -class BdbQuit(Exception): ... - -class Bdb: - - skip: Set[str] | None - breaks: Dict[str, List[int]] - fncache: Dict[str, str] - frame_returning: FrameType | None - botframe: FrameType | None - quitting: bool - stopframe: FrameType | None - returnframe: FrameType | None - stoplineno: int - def __init__(self, skip: Iterable[str] | None = ...) -> None: ... - def canonic(self, filename: str) -> str: ... - def reset(self) -> None: ... - def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> _TraceDispatch: ... - def dispatch_line(self, frame: FrameType) -> _TraceDispatch: ... - def dispatch_call(self, frame: FrameType, arg: None) -> _TraceDispatch: ... - def dispatch_return(self, frame: FrameType, arg: Any) -> _TraceDispatch: ... - def dispatch_exception(self, frame: FrameType, arg: _ExcInfo) -> _TraceDispatch: ... - def is_skipped_module(self, module_name: str) -> bool: ... - def stop_here(self, frame: FrameType) -> bool: ... - def break_here(self, frame: FrameType) -> bool: ... - def do_clear(self, arg: Any) -> bool | None: ... - def break_anywhere(self, frame: FrameType) -> bool: ... - def user_call(self, frame: FrameType, argument_list: None) -> None: ... - def user_line(self, frame: FrameType) -> None: ... - def user_return(self, frame: FrameType, return_value: Any) -> None: ... - def user_exception(self, frame: FrameType, exc_info: _ExcInfo) -> None: ... - def set_until(self, frame: FrameType, lineno: int | None = ...) -> None: ... - def set_step(self) -> None: ... - def set_next(self, frame: FrameType) -> None: ... - def set_return(self, frame: FrameType) -> None: ... - def set_trace(self, frame: FrameType | None = ...) -> None: ... - def set_continue(self) -> None: ... - def set_quit(self) -> None: ... - def set_break( - self, filename: str, lineno: int, temporary: bool = ..., cond: str | None = ..., funcname: str | None = ... - ) -> None: ... - def clear_break(self, filename: str, lineno: int) -> None: ... - def clear_bpbynumber(self, arg: SupportsInt) -> None: ... - def clear_all_file_breaks(self, filename: str) -> None: ... - def clear_all_breaks(self) -> None: ... - def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... - def get_break(self, filename: str, lineno: int) -> bool: ... - def get_breaks(self, filename: str, lineno: int) -> List[Breakpoint]: ... - def get_file_breaks(self, filename: str) -> List[Breakpoint]: ... - def get_all_breaks(self) -> List[Breakpoint]: ... - def get_stack(self, f: FrameType | None, t: TracebackType | None) -> Tuple[List[Tuple[FrameType, int]], int]: ... - def format_stack_entry(self, frame_lineno: int, lprefix: str = ...) -> str: ... - def run(self, cmd: str | CodeType, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runeval(self, expr: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runctx(self, cmd: str | CodeType, globals: Dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... - -class Breakpoint: - - next: int = ... - bplist: Dict[Tuple[str, int], List[Breakpoint]] = ... - bpbynumber: List[Breakpoint | None] = ... - - funcname: str | None - func_first_executable_line: int | None - file: str - line: int - temporary: bool - cond: str | None - enabled: bool - ignore: int - hits: int - number: int - def __init__( - self, file: str, line: int, temporary: bool = ..., cond: str | None = ..., funcname: str | None = ... - ) -> None: ... - def deleteMe(self) -> None: ... - def enable(self) -> None: ... - def disable(self) -> None: ... - def bpprint(self, out: IO[str] | None = ...) -> None: ... - def bpformat(self) -> str: ... - def __str__(self) -> str: ... - -def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... -def effective(file: str, line: int, frame: FrameType) -> Tuple[Breakpoint, bool] | Tuple[None, None]: ... -def set_trace() -> None: ... diff --git a/stdlib/@python2/binascii.pyi b/stdlib/@python2/binascii.pyi deleted file mode 100644 index b8da269c95a8..000000000000 --- a/stdlib/@python2/binascii.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Text - -# Python 2 accepts unicode ascii pretty much everywhere. -_Bytes = Text -_Ascii = Text - -def a2b_uu(__data: _Ascii) -> bytes: ... -def b2a_uu(__data: _Bytes) -> bytes: ... -def a2b_base64(__data: _Ascii) -> bytes: ... -def b2a_base64(__data: _Bytes) -> bytes: ... -def a2b_qp(data: _Ascii, header: bool = ...) -> bytes: ... -def b2a_qp(data: _Bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... -def a2b_hqx(__data: _Ascii) -> bytes: ... -def rledecode_hqx(__data: _Bytes) -> bytes: ... -def rlecode_hqx(__data: _Bytes) -> bytes: ... -def b2a_hqx(__data: _Bytes) -> bytes: ... -def crc_hqx(__data: _Bytes, __crc: int) -> int: ... -def crc32(__data: _Bytes, __crc: int = ...) -> int: ... -def b2a_hex(__data: _Bytes) -> bytes: ... -def hexlify(__data: _Bytes) -> bytes: ... -def a2b_hex(__hexstr: _Ascii) -> bytes: ... -def unhexlify(__hexstr: _Ascii) -> bytes: ... - -class Error(ValueError): ... -class Incomplete(Exception): ... diff --git a/stdlib/@python2/binhex.pyi b/stdlib/@python2/binhex.pyi deleted file mode 100644 index 02d094faf923..000000000000 --- a/stdlib/@python2/binhex.pyi +++ /dev/null @@ -1,42 +0,0 @@ -from typing import IO, Any, Tuple, Union - -class Error(Exception): ... - -REASONABLY_LARGE: int -LINELEN: int -RUNCHAR: bytes - -class FInfo: - def __init__(self) -> None: ... - Type: str - Creator: str - Flags: int - -_FileInfoTuple = Tuple[str, FInfo, int, int] -_FileHandleUnion = Union[str, IO[bytes]] - -def getfileinfo(name: str) -> _FileInfoTuple: ... - -class openrsrc: - def __init__(self, *args: Any) -> None: ... - def read(self, *args: Any) -> bytes: ... - def write(self, *args: Any) -> None: ... - def close(self) -> None: ... - -class BinHex: - def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ... - def write(self, data: bytes) -> None: ... - def close_data(self) -> None: ... - def write_rsrc(self, data: bytes) -> None: ... - def close(self) -> None: ... - -def binhex(inp: str, out: str) -> None: ... - -class HexBin: - def __init__(self, ifp: _FileHandleUnion) -> None: ... - def read(self, *n: int) -> bytes: ... - def close_data(self) -> None: ... - def read_rsrc(self, *n: int) -> bytes: ... - def close(self) -> None: ... - -def hexbin(inp: str, out: str) -> None: ... diff --git a/stdlib/@python2/bisect.pyi b/stdlib/@python2/bisect.pyi deleted file mode 100644 index 60dfc48d69bd..000000000000 --- a/stdlib/@python2/bisect.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from _bisect import * - -bisect = bisect_right -insort = insort_right diff --git a/stdlib/@python2/builtins.pyi b/stdlib/@python2/builtins.pyi deleted file mode 100644 index fad8b2b4e7d8..000000000000 --- a/stdlib/@python2/builtins.pyi +++ /dev/null @@ -1,1187 +0,0 @@ -# True and False are deliberately omitted because they are keywords in -# Python 3, and stub files conform to Python 3 syntax. - -from _typeshed import ReadableBuffer, SupportsKeysAndGetItem, SupportsWrite -from abc import ABCMeta -from ast import mod -from types import CodeType -from typing import ( - AbstractSet, - Any, - AnyStr, - BinaryIO, - ByteString, - Callable, - Container, - Dict, - FrozenSet, - Generic, - ItemsView, - Iterable, - Iterator, - KeysView, - List, - Mapping, - MutableMapping, - MutableSequence, - MutableSet, - NoReturn, - Protocol, - Reversible, - Sequence, - Set, - Sized, - SupportsAbs, - SupportsComplex, - SupportsFloat, - SupportsInt, - Text, - Tuple, - Type, - TypeVar, - ValuesView, - overload, -) -from typing_extensions import Literal, final - -class _SupportsIndex(Protocol): - def __index__(self) -> int: ... - -class _SupportsTrunc(Protocol): - def __trunc__(self) -> int: ... - -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") -_S = TypeVar("_S") -_T1 = TypeVar("_T1") -_T2 = TypeVar("_T2") -_T3 = TypeVar("_T3") -_T4 = TypeVar("_T4") -_T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") - -class object: - __doc__: str | None - __dict__: Dict[str, Any] - __slots__: Text | Iterable[Text] - __module__: str - @property - def __class__(self: _T) -> Type[_T]: ... - @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 - def __init__(self) -> None: ... - def __new__(cls) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __eq__(self, o: object) -> bool: ... - def __ne__(self, o: object) -> bool: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __hash__(self) -> int: ... - def __format__(self, format_spec: str) -> str: ... - def __getattribute__(self, name: str) -> Any: ... - def __delattr__(self, name: str) -> None: ... - def __sizeof__(self) -> int: ... - def __reduce__(self) -> str | Tuple[Any, ...]: ... - def __reduce_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... - -class staticmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] - def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... - -class classmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] - def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... - -class type(object): - __base__: type - __bases__: Tuple[type, ...] - __basicsize__: int - __dict__: Dict[str, Any] - __dictoffset__: int - __flags__: int - __itemsize__: int - __module__: str - __mro__: Tuple[type, ...] - __name__: str - __weakrefoffset__: int - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... - @overload - def __new__(cls, o: object) -> type: ... - @overload - def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... - def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> List[_TT]: ... - # Note: the documentation doesn't specify what the return type is, the standard - # implementation seems to be returning a list. - def mro(self) -> List[type]: ... - def __instancecheck__(self, instance: Any) -> bool: ... - def __subclasscheck__(self, subclass: type) -> bool: ... - -class super(object): - @overload - def __init__(self, t: Any, obj: Any) -> None: ... - @overload - def __init__(self, t: Any) -> None: ... - -class int: - @overload - def __new__(cls: Type[_T], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> _T: ... - @overload - def __new__(cls: Type[_T], x: Text | bytes | bytearray, base: int) -> _T: ... - @property - def real(self) -> int: ... - @property - def imag(self) -> int: ... - @property - def numerator(self) -> int: ... - @property - def denominator(self) -> int: ... - def conjugate(self) -> int: ... - def bit_length(self) -> int: ... - def __add__(self, x: int) -> int: ... - def __sub__(self, x: int) -> int: ... - def __mul__(self, x: int) -> int: ... - def __floordiv__(self, x: int) -> int: ... - def __div__(self, x: int) -> int: ... - def __truediv__(self, x: int) -> float: ... - def __mod__(self, x: int) -> int: ... - def __divmod__(self, x: int) -> Tuple[int, int]: ... - def __radd__(self, x: int) -> int: ... - def __rsub__(self, x: int) -> int: ... - def __rmul__(self, x: int) -> int: ... - def __rfloordiv__(self, x: int) -> int: ... - def __rdiv__(self, x: int) -> int: ... - def __rtruediv__(self, x: int) -> float: ... - def __rmod__(self, x: int) -> int: ... - def __rdivmod__(self, x: int) -> Tuple[int, int]: ... - @overload - def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... - @overload - def __pow__(self, __x: int, __modulo: int | None = ...) -> Any: ... # Return type can be int or float, depending on x. - def __rpow__(self, x: int, mod: int | None = ...) -> Any: ... - def __and__(self, n: int) -> int: ... - def __or__(self, n: int) -> int: ... - def __xor__(self, n: int) -> int: ... - def __lshift__(self, n: int) -> int: ... - def __rshift__(self, n: int) -> int: ... - def __rand__(self, n: int) -> int: ... - def __ror__(self, n: int) -> int: ... - def __rxor__(self, n: int) -> int: ... - def __rlshift__(self, n: int) -> int: ... - def __rrshift__(self, n: int) -> int: ... - def __neg__(self) -> int: ... - def __pos__(self) -> int: ... - def __invert__(self) -> int: ... - def __trunc__(self) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: int) -> bool: ... - def __le__(self, x: int) -> bool: ... - def __gt__(self, x: int) -> bool: ... - def __ge__(self, x: int) -> bool: ... - def __str__(self) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - def __abs__(self) -> int: ... - def __hash__(self) -> int: ... - def __nonzero__(self) -> bool: ... - def __index__(self) -> int: ... - -class float: - def __new__(cls: Type[_T], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> _T: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... - def hex(self) -> str: ... - def is_integer(self) -> bool: ... - @classmethod - def fromhex(cls, __s: str) -> float: ... - @property - def real(self) -> float: ... - @property - def imag(self) -> float: ... - def conjugate(self) -> float: ... - def __add__(self, x: float) -> float: ... - def __sub__(self, x: float) -> float: ... - def __mul__(self, x: float) -> float: ... - def __floordiv__(self, x: float) -> float: ... - def __div__(self, x: float) -> float: ... - def __truediv__(self, x: float) -> float: ... - def __mod__(self, x: float) -> float: ... - def __divmod__(self, x: float) -> Tuple[float, float]: ... - def __pow__( - self, x: float, mod: None = ... - ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole - def __radd__(self, x: float) -> float: ... - def __rsub__(self, x: float) -> float: ... - def __rmul__(self, x: float) -> float: ... - def __rfloordiv__(self, x: float) -> float: ... - def __rdiv__(self, x: float) -> float: ... - def __rtruediv__(self, x: float) -> float: ... - def __rmod__(self, x: float) -> float: ... - def __rdivmod__(self, x: float) -> Tuple[float, float]: ... - def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... - def __trunc__(self) -> int: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: float) -> bool: ... - def __le__(self, x: float) -> bool: ... - def __gt__(self, x: float) -> bool: ... - def __ge__(self, x: float) -> bool: ... - def __neg__(self) -> float: ... - def __pos__(self) -> float: ... - def __str__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __abs__(self) -> float: ... - def __hash__(self) -> int: ... - def __nonzero__(self) -> bool: ... - -class complex: - @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... - @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | _SupportsIndex) -> _T: ... - @property - def real(self) -> float: ... - @property - def imag(self) -> float: ... - def conjugate(self) -> complex: ... - def __add__(self, x: complex) -> complex: ... - def __sub__(self, x: complex) -> complex: ... - def __mul__(self, x: complex) -> complex: ... - def __pow__(self, x: complex, mod: None = ...) -> complex: ... - def __div__(self, x: complex) -> complex: ... - def __truediv__(self, x: complex) -> complex: ... - def __radd__(self, x: complex) -> complex: ... - def __rsub__(self, x: complex) -> complex: ... - def __rmul__(self, x: complex) -> complex: ... - def __rpow__(self, x: complex, mod: None = ...) -> complex: ... - def __rdiv__(self, x: complex) -> complex: ... - def __rtruediv__(self, x: complex) -> complex: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __neg__(self) -> complex: ... - def __pos__(self) -> complex: ... - def __str__(self) -> str: ... - def __complex__(self) -> complex: ... - def __abs__(self) -> float: ... - def __hash__(self) -> int: ... - def __nonzero__(self) -> bool: ... - -class basestring(metaclass=ABCMeta): ... - -class unicode(basestring, Sequence[unicode]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... - def capitalize(self) -> unicode: ... - def center(self, width: int, fillchar: unicode = ...) -> unicode: ... - def count(self, x: unicode) -> int: ... - def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... - def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... - def endswith(self, __suffix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> unicode: ... - def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> unicode: ... - def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - def isidentifier(self) -> bool: ... - def islower(self) -> bool: ... - def isnumeric(self) -> bool: ... - def isprintable(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, iterable: Iterable[unicode]) -> unicode: ... - def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def lower(self) -> unicode: ... - def lstrip(self, chars: unicode = ...) -> unicode: ... - def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... - def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, __prefix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def strip(self, chars: unicode = ...) -> unicode: ... - def swapcase(self) -> unicode: ... - def title(self) -> unicode: ... - def translate(self, table: Dict[int, Any] | unicode) -> unicode: ... - def upper(self) -> unicode: ... - def zfill(self, width: int) -> unicode: ... - @overload - def __getitem__(self, i: int) -> unicode: ... - @overload - def __getitem__(self, s: slice) -> unicode: ... - def __getslice__(self, start: int, stop: int) -> unicode: ... - def __add__(self, s: unicode) -> unicode: ... - def __mul__(self, n: int) -> unicode: ... - def __rmul__(self, n: int) -> unicode: ... - def __mod__(self, x: Any) -> unicode: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: unicode) -> bool: ... - def __le__(self, x: unicode) -> bool: ... - def __gt__(self, x: unicode) -> bool: ... - def __ge__(self, x: unicode) -> bool: ... - def __len__(self) -> int: ... - # The argument type is incompatible with Sequence - def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore - def __iter__(self) -> Iterator[unicode]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __hash__(self) -> int: ... - def __getnewargs__(self) -> Tuple[unicode]: ... - -class _FormatMapMapping(Protocol): - def __getitem__(self, __key: str) -> Any: ... - -class str(Sequence[str], basestring): - def __init__(self, o: object = ...) -> None: ... - def capitalize(self) -> str: ... - def center(self, __width: int, __fillchar: str = ...) -> str: ... - def count(self, x: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... - def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, __suffix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> str: ... - def find(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> str: ... - def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... - def ljust(self, __width: int, __fillchar: str = ...) -> str: ... - def lower(self) -> str: ... - @overload - def lstrip(self, __chars: str = ...) -> str: ... - @overload - def lstrip(self, __chars: unicode) -> unicode: ... - @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... - def rfind(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def rindex(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... - def rjust(self, __width: int, __fillchar: str = ...) -> str: ... - @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - @overload - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - @overload - def rstrip(self, __chars: str = ...) -> str: ... - @overload - def rstrip(self, __chars: unicode) -> unicode: ... - @overload - def split(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, __prefix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - @overload - def strip(self, __chars: str = ...) -> str: ... - @overload - def strip(self, chars: unicode) -> unicode: ... - def swapcase(self) -> str: ... - def title(self) -> str: ... - def translate(self, __table: AnyStr | None, deletechars: AnyStr = ...) -> AnyStr: ... - def upper(self) -> str: ... - def zfill(self, __width: int) -> str: ... - def __add__(self, s: AnyStr) -> AnyStr: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: str | Text) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ge__(self, x: Text) -> bool: ... - def __getitem__(self, i: int | slice) -> str: ... - def __gt__(self, x: Text) -> bool: ... - def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... - def __le__(self, x: Text) -> bool: ... - def __len__(self) -> int: ... - def __lt__(self, x: Text) -> bool: ... - def __mod__(self, x: Any) -> str: ... - def __mul__(self, n: int) -> str: ... - def __ne__(self, x: object) -> bool: ... - def __repr__(self) -> str: ... - def __rmul__(self, n: int) -> str: ... - def __str__(self) -> str: ... - def __getnewargs__(self) -> Tuple[str]: ... - def __getslice__(self, start: int, stop: int) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - -bytes = str - -class bytearray(MutableSequence[int], ByteString): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: str) -> None: ... - @overload - def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - def capitalize(self) -> bytearray: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def count(self, __sub: str) -> int: ... - def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... - def endswith(self, __suffix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytearray: ... - def extend(self, iterable: str | Iterable[int]) -> None: ... - def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def insert(self, __index: int, __item: int) -> None: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[str]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... - def lower(self) -> bytearray: ... - def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... - def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith(self, __prefix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... - def strip(self, __bytes: bytes | None = ...) -> bytearray: ... - def swapcase(self) -> bytearray: ... - def title(self) -> bytearray: ... - def translate(self, __table: str) -> bytearray: ... - def upper(self) -> bytearray: ... - def zfill(self, __width: int) -> bytearray: ... - @classmethod - def fromhex(cls, __string: str) -> bytearray: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - __hash__: None # type: ignore - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> bytearray: ... - @overload - def __setitem__(self, i: int, x: int) -> None: ... - @overload - def __setitem__(self, s: slice, x: Iterable[int] | bytes) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> bytearray: ... - def __setslice__(self, start: int, stop: int, x: Sequence[int] | str) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, s: bytes) -> bytearray: ... - def __mul__(self, n: int) -> bytearray: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: int | bytes) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... - -class memoryview(Sized, Container[str]): - format: str - itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None - readonly: bool - ndim: int - def __init__(self, obj: ReadableBuffer) -> None: ... - @overload - def __getitem__(self, i: int) -> str: ... - @overload - def __getitem__(self, s: slice) -> memoryview: ... - def __contains__(self, x: object) -> bool: ... - def __iter__(self) -> Iterator[str]: ... - def __len__(self) -> int: ... - @overload - def __setitem__(self, s: slice, o: bytes) -> None: ... - @overload - def __setitem__(self, i: int, o: int) -> None: ... - def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... - -@final -class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... - @overload - def __and__(self, x: bool) -> bool: ... - @overload - def __and__(self, x: int) -> int: ... - @overload - def __or__(self, x: bool) -> bool: ... - @overload - def __or__(self, x: int) -> int: ... - @overload - def __xor__(self, x: bool) -> bool: ... - @overload - def __xor__(self, x: int) -> int: ... - @overload - def __rand__(self, x: bool) -> bool: ... - @overload - def __rand__(self, x: int) -> int: ... - @overload - def __ror__(self, x: bool) -> bool: ... - @overload - def __ror__(self, x: int) -> int: ... - @overload - def __rxor__(self, x: bool) -> bool: ... - @overload - def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... - -class slice(object): - start: Any - step: Any - stop: Any - @overload - def __init__(self, stop: Any) -> None: ... - @overload - def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... - __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... - -class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... - def __len__(self) -> int: ... - def __contains__(self, x: object) -> bool: ... - @overload - def __getitem__(self, x: int) -> _T_co: ... - @overload - def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... - @overload - def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... - @overload - def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... - def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... - def count(self, __value: Any) -> int: ... - def index(self, __value: Any) -> int: ... - -class function: - # TODO not defined in builtins! - __name__: str - __module__: str - __code__: CodeType - -class list(MutableSequence[_T], Generic[_T]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, iterable: Iterable[_T]) -> None: ... - def append(self, __object: _T) -> None: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: int = ...) -> _T: ... - def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... - def count(self, __value: _T) -> int: ... - def insert(self, __index: int, __object: _T) -> None: ... - def remove(self, __value: _T) -> None: ... - def reverse(self) -> None: ... - def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore - @overload - def __getitem__(self, i: int) -> _T: ... - @overload - def __getitem__(self, s: slice) -> List[_T]: ... - @overload - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_T]: ... - def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, x: List[_T]) -> List[_T]: ... - def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: int) -> List[_T]: ... - def __rmul__(self, n: int) -> List[_T]: ... - def __contains__(self, o: object) -> bool: ... - def __reversed__(self) -> Iterator[_T]: ... - def __gt__(self, x: List[_T]) -> bool: ... - def __ge__(self, x: List[_T]) -> bool: ... - def __lt__(self, x: List[_T]) -> bool: ... - def __le__(self, x: List[_T]) -> bool: ... - -class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): - # NOTE: Keyword arguments are special. If they are used, _KT must include - # str, but we have no way of enforcing it here. - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... - def has_key(self, k: _KT) -> bool: ... - def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... - @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - @overload - def update(self, **kwargs: _VT) -> None: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def viewkeys(self) -> KeysView[_KT]: ... - def viewvalues(self) -> ValuesView[_VT]: ... - def viewitems(self) -> ItemsView[_KT, _VT]: ... - @classmethod - @overload - def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... - @classmethod - @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... - def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore - -class set(MutableSet[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T] = ...) -> None: ... - def add(self, element: _T) -> None: ... - def clear(self) -> None: ... - def copy(self) -> Set[_T]: ... - def difference(self, *s: Iterable[Any]) -> Set[_T]: ... - def difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... - def intersection_update(self, *s: Iterable[Any]) -> None: ... - def isdisjoint(self, s: Iterable[Any]) -> bool: ... - def issubset(self, s: Iterable[Any]) -> bool: ... - def issuperset(self, s: Iterable[Any]) -> bool: ... - def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... - def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... - def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... - def union(self, *s: Iterable[_T]) -> Set[_T]: ... - def update(self, *s: Iterable[_T]) -> None: ... - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __or__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ior__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - @overload - def __sub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... - @overload - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - @overload # type: ignore - def __isub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... - @overload - def __isub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - def __xor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ixor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - __hash__: None # type: ignore - -class frozenset(AbstractSet[_T_co], Generic[_T_co]): - def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... - def copy(self) -> FrozenSet[_T_co]: ... - def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... - def issubset(self, s: Iterable[object]) -> bool: ... - def issuperset(self, s: Iterable[object]) -> bool: ... - def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __or__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... - def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): - def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... - def __iter__(self) -> Iterator[Tuple[int, _T]]: ... - def next(self) -> Tuple[int, _T]: ... - -class xrange(Sized, Iterable[int], Reversible[int]): - @overload - def __init__(self, stop: int) -> None: ... - @overload - def __init__(self, start: int, stop: int, step: int = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __getitem__(self, i: _SupportsIndex) -> int: ... - def __reversed__(self) -> Iterator[int]: ... - -class property(object): - def __init__( - self, - fget: Callable[[Any], Any] | None = ..., - fset: Callable[[Any, Any], None] | None = ..., - fdel: Callable[[Any], None] | None = ..., - doc: str | None = ..., - ) -> None: ... - def getter(self, fget: Callable[[Any], Any]) -> property: ... - def setter(self, fset: Callable[[Any, Any], None]) -> property: ... - def deleter(self, fdel: Callable[[Any], None]) -> property: ... - def __get__(self, obj: Any, type: type | None = ...) -> Any: ... - def __set__(self, obj: Any, value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... - def fget(self) -> Any: ... - def fset(self, value: Any) -> None: ... - def fdel(self) -> None: ... - -long = int - -class _NotImplementedType(Any): # type: ignore - # A little weird, but typing the __call__ as NotImplemented makes the error message - # for NotImplemented() much better - __call__: NotImplemented # type: ignore - -NotImplemented: _NotImplementedType - -def abs(__x: SupportsAbs[_T]) -> _T: ... -def all(__iterable: Iterable[object]) -> bool: ... -def any(__iterable: Iterable[object]) -> bool: ... -def apply(__func: Callable[..., _T], __args: Sequence[Any] | None = ..., __kwds: Mapping[str, Any] | None = ...) -> _T: ... -def bin(__number: int | _SupportsIndex) -> str: ... -def callable(__obj: object) -> bool: ... -def chr(__i: int) -> str: ... -def cmp(__x: Any, __y: Any) -> int: ... - -_N1 = TypeVar("_N1", bool, int, float, complex) - -def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... -def compile(source: Text | mod, filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... -def delattr(__obj: Any, __name: Text) -> None: ... -def dir(__o: object = ...) -> List[str]: ... - -_N2 = TypeVar("_N2", int, float) - -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... -def eval( - __source: Text | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... -) -> Any: ... -def execfile(__filename: str, __globals: Dict[str, Any] | None = ..., __locals: Dict[str, Any] | None = ...) -> None: ... -def exit(code: object = ...) -> NoReturn: ... -@overload -def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore -@overload -def filter(__function: None, __iterable: Tuple[_T | None, ...]) -> Tuple[_T, ...]: ... # type: ignore -@overload -def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore -@overload -def filter(__function: None, __iterable: Iterable[_T | None]) -> List[_T]: ... -@overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... -def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode -@overload -def getattr(__o: Any, name: Text) -> Any: ... - -# While technically covered by the last overload, spelling out the types for None, bool -# and basic containers help mypy out in some tricky situations involving type context -# (aka bidirectional inference) -@overload -def getattr(__o: Any, name: Text, __default: None) -> Any | None: ... -@overload -def getattr(__o: Any, name: Text, __default: bool) -> Any | bool: ... -@overload -def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ... -@overload -def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... -@overload -def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... -def globals() -> Dict[str, Any]: ... -def hasattr(__obj: Any, __name: Text) -> bool: ... -def hash(__obj: object) -> int: ... -def hex(__number: int | _SupportsIndex) -> str: ... -def id(__obj: object) -> int: ... -def input(__prompt: Any = ...) -> Any: ... -def intern(__string: str) -> str: ... -@overload -def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... -@overload -def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... -@overload -def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def len(__obj: Sized) -> int: ... -def locals() -> Dict[str, Any]: ... -@overload -def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... -@overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... -@overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... -@overload -def map( - __func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def map( - __func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def map( - __func: None, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... -@overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... -@overload -def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] -) -> List[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], -) -> List[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], -) -> List[_S]: ... -@overload -def map( - __func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> List[_S]: ... -@overload -def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def next(__i: Iterator[_T]) -> _T: ... -@overload -def next(__i: Iterator[_T], __default: _VT) -> _T | _VT: ... -def oct(__number: int | _SupportsIndex) -> str: ... -def open(name: unicode | int, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... -def ord(__c: Text | bytes) -> int: ... - -# This is only available after from __future__ import print_function. -def print(*values: object, sep: Text | None = ..., end: Text | None = ..., file: SupportsWrite[Any] | None = ...) -> None: ... - -_E = TypeVar("_E", contravariant=True) -_M = TypeVar("_M", contravariant=True) - -class _SupportsPow2(Protocol[_E, _T_co]): - def __pow__(self, __other: _E) -> _T_co: ... - -class _SupportsPow3(Protocol[_E, _M, _T_co]): - def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... - -@overload -def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative -@overload -def pow(__base: int, __exp: int, __mod: int) -> int: ... -@overload -def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... -@overload -def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... -@overload -def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... -def quit(code: object = ...) -> NoReturn: ... -def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 -def raw_input(__prompt: Any = ...) -> str: ... -@overload -def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... -@overload -def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... -def reload(__module: Any) -> Any: ... -@overload -def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... -@overload -def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... -def repr(__obj: object) -> str: ... -@overload -def round(number: float) -> float: ... -@overload -def round(number: float, ndigits: int) -> float: ... -@overload -def round(number: SupportsFloat) -> float: ... -@overload -def round(number: SupportsFloat, ndigits: int) -> float: ... -def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... -def sorted( - __iterable: Iterable[_T], *, cmp: Callable[[_T, _T], int] = ..., key: Callable[[_T], Any] | None = ..., reverse: bool = ... -) -> List[_T]: ... -@overload -def sum(__iterable: Iterable[_T]) -> _T | int: ... -@overload -def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... -def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... -@overload -def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... -@overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... -@overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... -@overload -def zip( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def zip( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def zip( - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... -def __import__( - name: Text, - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., - fromlist: Sequence[str] = ..., - level: int = ..., -) -> Any: ... - -# Actually the type of Ellipsis is , but since it's -# not exposed anywhere under that name, we make it private here. -class ellipsis: ... - -Ellipsis: ellipsis - -# TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. -_AnyBuffer = TypeVar("_AnyBuffer", str, unicode, bytearray, buffer) - -class buffer(Sized): - def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... - def __add__(self, other: _AnyBuffer) -> str: ... - def __cmp__(self, other: _AnyBuffer) -> bool: ... - def __getitem__(self, key: int | slice) -> str: ... - def __getslice__(self, i: int, j: int) -> str: ... - def __len__(self) -> int: ... - def __mul__(self, x: int) -> str: ... - -class BaseException(object): - args: Tuple[Any, ...] - message: Any - def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __getitem__(self, i: int) -> Any: ... - def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... - -class GeneratorExit(BaseException): ... -class KeyboardInterrupt(BaseException): ... - -class SystemExit(BaseException): - code: int - -class Exception(BaseException): ... -class StopIteration(Exception): ... -class StandardError(Exception): ... - -_StandardError = StandardError - -class EnvironmentError(StandardError): - errno: int - strerror: str - # TODO can this be unicode? - filename: str - -class OSError(EnvironmentError): ... -class IOError(EnvironmentError): ... -class ArithmeticError(_StandardError): ... -class AssertionError(_StandardError): ... -class AttributeError(_StandardError): ... -class BufferError(_StandardError): ... -class EOFError(_StandardError): ... -class ImportError(_StandardError): ... -class LookupError(_StandardError): ... -class MemoryError(_StandardError): ... -class NameError(_StandardError): ... -class ReferenceError(_StandardError): ... -class RuntimeError(_StandardError): ... - -class SyntaxError(_StandardError): - msg: str - lineno: int | None - offset: int | None - text: str | None - filename: str | None - -class SystemError(_StandardError): ... -class TypeError(_StandardError): ... -class ValueError(_StandardError): ... -class FloatingPointError(ArithmeticError): ... -class OverflowError(ArithmeticError): ... -class ZeroDivisionError(ArithmeticError): ... -class IndexError(LookupError): ... -class KeyError(LookupError): ... -class UnboundLocalError(NameError): ... - -class WindowsError(OSError): - winerror: int - -class NotImplementedError(RuntimeError): ... -class IndentationError(SyntaxError): ... -class TabError(IndentationError): ... -class UnicodeError(ValueError): ... - -class UnicodeDecodeError(UnicodeError): - encoding: str - object: bytes - start: int - end: int - reason: str - def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... - -class UnicodeEncodeError(UnicodeError): - encoding: str - object: Text - start: int - end: int - reason: str - def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, __reason: str) -> None: ... - -class UnicodeTranslateError(UnicodeError): ... -class Warning(Exception): ... -class UserWarning(Warning): ... -class DeprecationWarning(Warning): ... -class SyntaxWarning(Warning): ... -class RuntimeWarning(Warning): ... -class FutureWarning(Warning): ... -class PendingDeprecationWarning(Warning): ... -class ImportWarning(Warning): ... -class UnicodeWarning(Warning): ... -class BytesWarning(Warning): ... - -class file(BinaryIO): - @overload - def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... - def __enter__(self) -> BinaryIO: ... - def __exit__(self, t: type | None = ..., exc: BaseException | None = ..., tb: Any | None = ...) -> bool | None: ... - def flush(self) -> None: ... - def fileno(self) -> int: ... - def isatty(self) -> bool: ... - def close(self) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def seekable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def write(self, data: str) -> int: ... - def writelines(self, data: Iterable[str]) -> None: ... - def truncate(self, pos: int | None = ...) -> int: ... diff --git a/stdlib/@python2/bz2.pyi b/stdlib/@python2/bz2.pyi deleted file mode 100644 index 81ee6f6ce26a..000000000000 --- a/stdlib/@python2/bz2.pyi +++ /dev/null @@ -1,32 +0,0 @@ -import io -from _typeshed import ReadableBuffer, WriteableBuffer -from typing import IO, Any, Iterable, List, Text, TypeVar, Union -from typing_extensions import SupportsIndex - -_PathOrFile = Union[Text, IO[bytes]] -_T = TypeVar("_T") - -def compress(data: bytes, compresslevel: int = ...) -> bytes: ... -def decompress(data: bytes) -> bytes: ... - -class BZ2File(io.BufferedIOBase, IO[bytes]): - def __enter__(self: _T) -> _T: ... - def __init__(self, filename: _PathOrFile, mode: str = ..., buffering: Any | None = ..., compresslevel: int = ...) -> None: ... - def read(self, size: int | None = ...) -> bytes: ... - def read1(self, size: int = ...) -> bytes: ... - def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore - def readinto(self, b: WriteableBuffer) -> int: ... - def readlines(self, size: SupportsIndex = ...) -> List[bytes]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def write(self, data: ReadableBuffer) -> int: ... - def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... - -class BZ2Compressor(object): - def __init__(self, compresslevel: int = ...) -> None: ... - def compress(self, __data: bytes) -> bytes: ... - def flush(self) -> bytes: ... - -class BZ2Decompressor(object): - def decompress(self, data: bytes) -> bytes: ... - @property - def unused_data(self) -> bytes: ... diff --git a/stdlib/@python2/cPickle.pyi b/stdlib/@python2/cPickle.pyi deleted file mode 100644 index d8db140cdda1..000000000000 --- a/stdlib/@python2/cPickle.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import IO, Any, List - -HIGHEST_PROTOCOL: int -compatible_formats: List[str] -format_version: str - -class Pickler: - def __init__(self, file: IO[str], protocol: int = ...) -> None: ... - def dump(self, obj: Any) -> None: ... - def clear_memo(self) -> None: ... - -class Unpickler: - def __init__(self, file: IO[str]) -> None: ... - def load(self) -> Any: ... - def noload(self) -> Any: ... - -def dump(obj: Any, file: IO[str], protocol: int = ...) -> None: ... -def dumps(obj: Any, protocol: int = ...) -> str: ... -def load(file: IO[str]) -> Any: ... -def loads(str: str) -> Any: ... - -class PickleError(Exception): ... -class UnpicklingError(PickleError): ... -class BadPickleGet(UnpicklingError): ... -class PicklingError(PickleError): ... -class UnpickleableError(PicklingError): ... diff --git a/stdlib/@python2/cProfile.pyi b/stdlib/@python2/cProfile.pyi deleted file mode 100644 index 1257b0cc92eb..000000000000 --- a/stdlib/@python2/cProfile.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from types import CodeType -from typing import Any, Callable, Dict, Text, Tuple, TypeVar - -def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... -def runctx( - statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: str | None = ..., sort: str | int = ... -) -> None: ... - -_SelfT = TypeVar("_SelfT", bound=Profile) -_T = TypeVar("_T") -_Label = Tuple[str, int, str] - -class Profile: - stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented - def __init__( - self, timer: Callable[[], float] = ..., timeunit: float = ..., subcalls: bool = ..., builtins: bool = ... - ) -> None: ... - def enable(self) -> None: ... - def disable(self) -> None: ... - def print_stats(self, sort: str | int = ...) -> None: ... - def dump_stats(self, file: Text) -> None: ... - def create_stats(self) -> None: ... - def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... - -def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/stdlib/@python2/cStringIO.pyi b/stdlib/@python2/cStringIO.pyi deleted file mode 100644 index 7703e030c332..000000000000 --- a/stdlib/@python2/cStringIO.pyi +++ /dev/null @@ -1,47 +0,0 @@ -from abc import ABCMeta -from typing import IO, Iterable, Iterator, List, overload - -# This class isn't actually abstract, but you can't instantiate it -# directly, so we might as well treat it as abstract in the stub. -class InputType(IO[str], Iterator[str], metaclass=ABCMeta): - def getvalue(self) -> str: ... - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def read(self, size: int = ...) -> str: ... - def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... - def __iter__(self) -> InputType: ... - def next(self) -> str: ... - def reset(self) -> None: ... - -class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): - @property - def softspace(self) -> int: ... - def getvalue(self) -> str: ... - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def read(self, size: int = ...) -> str: ... - def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... - def __iter__(self) -> OutputType: ... - def next(self) -> str: ... - def reset(self) -> None: ... - def write(self, b: str | unicode) -> int: ... - def writelines(self, lines: Iterable[str | unicode]) -> None: ... - -@overload -def StringIO() -> OutputType: ... -@overload -def StringIO(s: str) -> InputType: ... diff --git a/stdlib/@python2/calendar.pyi b/stdlib/@python2/calendar.pyi deleted file mode 100644 index ce765210dc1e..000000000000 --- a/stdlib/@python2/calendar.pyi +++ /dev/null @@ -1,105 +0,0 @@ -import datetime -from time import struct_time -from typing import Any, Iterable, List, Optional, Sequence, Tuple - -_LocaleType = Tuple[Optional[str], Optional[str]] - -class IllegalMonthError(ValueError): - def __init__(self, month: int) -> None: ... - def __str__(self) -> str: ... - -class IllegalWeekdayError(ValueError): - def __init__(self, weekday: int) -> None: ... - def __str__(self) -> str: ... - -def isleap(year: int) -> bool: ... -def leapdays(y1: int, y2: int) -> int: ... -def weekday(year: int, month: int, day: int) -> int: ... -def monthrange(year: int, month: int) -> Tuple[int, int]: ... - -class Calendar: - firstweekday: int - def __init__(self, firstweekday: int = ...) -> None: ... - def getfirstweekday(self) -> int: ... - def setfirstweekday(self, firstweekday: int) -> None: ... - def iterweekdays(self) -> Iterable[int]: ... - def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ... - def itermonthdays2(self, year: int, month: int) -> Iterable[Tuple[int, int]]: ... - def itermonthdays(self, year: int, month: int) -> Iterable[int]: ... - def monthdatescalendar(self, year: int, month: int) -> List[List[datetime.date]]: ... - def monthdays2calendar(self, year: int, month: int) -> List[List[Tuple[int, int]]]: ... - def monthdayscalendar(self, year: int, month: int) -> List[List[int]]: ... - def yeardatescalendar(self, year: int, width: int = ...) -> List[List[int]]: ... - def yeardays2calendar(self, year: int, width: int = ...) -> List[List[Tuple[int, int]]]: ... - def yeardayscalendar(self, year: int, width: int = ...) -> List[List[int]]: ... - -class TextCalendar(Calendar): - def prweek(self, theweek: int, width: int) -> None: ... - def formatday(self, day: int, weekday: int, width: int) -> str: ... - def formatweek(self, theweek: int, width: int) -> str: ... - def formatweekday(self, day: int, width: int) -> str: ... - def formatweekheader(self, width: int) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... - def prmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... - def formatmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... - def formatyear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... - def pryear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... - -def firstweekday() -> int: ... -def monthcalendar(year: int, month: int) -> List[List[int]]: ... -def prweek(theweek: int, width: int) -> None: ... -def week(theweek: int, width: int) -> str: ... -def weekheader(width: int) -> str: ... -def prmonth(theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... -def month(theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... -def calendar(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... -def prcal(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... - -class HTMLCalendar(Calendar): - def formatday(self, day: int, weekday: int) -> str: ... - def formatweek(self, theweek: int) -> str: ... - def formatweekday(self, day: int) -> str: ... - def formatweekheader(self) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... - def formatmonth(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... - def formatyear(self, theyear: int, width: int = ...) -> str: ... - def formatyearpage(self, theyear: int, width: int = ..., css: str | None = ..., encoding: str | None = ...) -> str: ... - -class TimeEncoding: - def __init__(self, locale: _LocaleType) -> None: ... - def __enter__(self) -> _LocaleType: ... - def __exit__(self, *args: Any) -> None: ... - -class LocaleTextCalendar(TextCalendar): - def __init__(self, firstweekday: int = ..., locale: _LocaleType | None = ...) -> None: ... - def formatweekday(self, day: int, width: int) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... - -class LocaleHTMLCalendar(HTMLCalendar): - def __init__(self, firstweekday: int = ..., locale: _LocaleType | None = ...) -> None: ... - def formatweekday(self, day: int) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... - -c: TextCalendar - -def setfirstweekday(firstweekday: int) -> None: ... -def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... -def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... -def timegm(tuple: Tuple[int, ...] | struct_time) -> int: ... - -# Data attributes -day_name: Sequence[str] -day_abbr: Sequence[str] -month_name: Sequence[str] -month_abbr: Sequence[str] - -# Below constants are not in docs or __all__, but enough people have used them -# they are now effectively public. - -MONDAY: int -TUESDAY: int -WEDNESDAY: int -THURSDAY: int -FRIDAY: int -SATURDAY: int -SUNDAY: int diff --git a/stdlib/@python2/cgi.pyi b/stdlib/@python2/cgi.pyi deleted file mode 100644 index 674748242ebb..000000000000 --- a/stdlib/@python2/cgi.pyi +++ /dev/null @@ -1,109 +0,0 @@ -from _typeshed import SupportsGetItem, SupportsItemAccess -from builtins import type as _type -from typing import IO, Any, AnyStr, Iterable, Iterator, List, Mapping, Protocol, TypeVar -from UserDict import UserDict - -_T = TypeVar("_T", bound=FieldStorage) - -def parse( - fp: IO[Any] | None = ..., - environ: SupportsItemAccess[str, str] = ..., - keep_blank_values: bool = ..., - strict_parsing: bool = ..., -) -> dict[str, List[str]]: ... -def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> dict[str, List[str]]: ... -def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> List[tuple[str, str]]: ... -def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, List[bytes]]: ... - -class _Environ(Protocol): - def __getitem__(self, __k: str) -> str: ... - def keys(self) -> Iterable[str]: ... - -def parse_header(line: str) -> tuple[str, dict[str, str]]: ... -def test(environ: _Environ = ...) -> None: ... -def print_environ(environ: _Environ = ...) -> None: ... -def print_form(form: dict[str, Any]) -> None: ... -def print_directory() -> None: ... -def print_environ_usage() -> None: ... -def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... - -class MiniFieldStorage: - # The first five "Any" attributes here are always None, but mypy doesn't support that - filename: Any - list: Any - type: Any - file: IO[bytes] | None - type_options: dict[Any, Any] - disposition: Any - disposition_options: dict[Any, Any] - headers: dict[Any, Any] - name: Any - value: Any - def __init__(self, name: Any, value: Any) -> None: ... - def __repr__(self) -> str: ... - -class FieldStorage(object): - FieldStorageClass: _type | None - keep_blank_values: int - strict_parsing: int - qs_on_post: str | None - headers: Mapping[str, str] - fp: IO[bytes] - encoding: str - errors: str - outerboundary: bytes - bytes_read: int - limit: int | None - disposition: str - disposition_options: dict[str, str] - filename: str | None - file: IO[bytes] | None - type: str - type_options: dict[str, str] - innerboundary: bytes - length: int - done: int - list: List[Any] | None - value: None | bytes | List[Any] - def __init__( - self, - fp: IO[Any] = ..., - headers: Mapping[str, str] = ..., - outerboundary: bytes = ..., - environ: SupportsGetItem[str, str] = ..., - keep_blank_values: int = ..., - strict_parsing: int = ..., - ) -> None: ... - def __repr__(self) -> str: ... - def __iter__(self) -> Iterator[str]: ... - def __getitem__(self, key: str) -> Any: ... - def getvalue(self, key: str, default: Any = ...) -> Any: ... - def getfirst(self, key: str, default: Any = ...) -> Any: ... - def getlist(self, key: str) -> List[Any]: ... - def keys(self) -> List[str]: ... - def has_key(self, key: str) -> bool: ... - def __contains__(self, key: str) -> bool: ... - def __len__(self) -> int: ... - def __nonzero__(self) -> bool: ... - # In Python 2 it always returns bytes and ignores the "binary" flag - def make_file(self, binary: Any = ...) -> IO[bytes]: ... - -class FormContentDict(UserDict[str, List[str]]): - query_string: str - def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... - -class SvFormContentDict(FormContentDict): - def getlist(self, key: Any) -> Any: ... - -class InterpFormContentDict(SvFormContentDict): ... - -class FormContent(FormContentDict): - # TODO this should have - # def values(self, key: Any) -> Any: ... - # but this is incompatible with the supertype, and adding '# type: ignore' triggers - # a parse error in pytype (https://github.com/google/pytype/issues/53) - def indexed_value(self, key: Any, location: int) -> Any: ... - def value(self, key: Any) -> Any: ... - def length(self, key: Any) -> int: ... - def stripped(self, key: Any) -> Any: ... - def pars(self) -> dict[Any, Any]: ... diff --git a/stdlib/@python2/cgitb.pyi b/stdlib/@python2/cgitb.pyi deleted file mode 100644 index daa0233ee69a..000000000000 --- a/stdlib/@python2/cgitb.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from types import FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, Optional, Text, Tuple, Type - -_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] - -def reset() -> str: ... # undocumented -def small(text: str) -> str: ... # undocumented -def strong(text: str) -> str: ... # undocumented -def grey(text: str) -> str: ... # undocumented -def lookup(name: str, frame: FrameType, locals: Dict[str, Any]) -> Tuple[str | None, Any]: ... # undocumented -def scanvars( - reader: Callable[[], bytes], frame: FrameType, locals: Dict[str, Any] -) -> List[Tuple[str, str | None, Any]]: ... # undocumented -def html(einfo: _ExcInfo, context: int = ...) -> str: ... -def text(einfo: _ExcInfo, context: int = ...) -> str: ... - -class Hook: # undocumented - def __init__( - self, display: int = ..., logdir: Text | None = ..., context: int = ..., file: IO[str] | None = ..., format: str = ... - ) -> None: ... - def __call__(self, etype: Type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... - def handle(self, info: _ExcInfo | None = ...) -> None: ... - -def handler(info: _ExcInfo | None = ...) -> None: ... -def enable(display: int = ..., logdir: Text | None = ..., context: int = ..., format: str = ...) -> None: ... diff --git a/stdlib/@python2/chunk.pyi b/stdlib/@python2/chunk.pyi deleted file mode 100644 index 50ff267c5436..000000000000 --- a/stdlib/@python2/chunk.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import IO - -class Chunk: - closed: bool - align: bool - file: IO[bytes] - chunkname: bytes - chunksize: int - size_read: int - offset: int - seekable: bool - def __init__(self, file: IO[bytes], align: bool = ..., bigendian: bool = ..., inclheader: bool = ...) -> None: ... - def getname(self) -> bytes: ... - def getsize(self) -> int: ... - def close(self) -> None: ... - def isatty(self) -> bool: ... - def seek(self, pos: int, whence: int = ...) -> None: ... - def tell(self) -> int: ... - def read(self, size: int = ...) -> bytes: ... - def skip(self) -> None: ... diff --git a/stdlib/@python2/cmath.pyi b/stdlib/@python2/cmath.pyi deleted file mode 100644 index 1e19687b4885..000000000000 --- a/stdlib/@python2/cmath.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import SupportsComplex, SupportsFloat, Tuple, Union - -e: float -pi: float -_C = Union[SupportsFloat, SupportsComplex, complex] - -def acos(__z: _C) -> complex: ... -def acosh(__z: _C) -> complex: ... -def asin(__z: _C) -> complex: ... -def asinh(__z: _C) -> complex: ... -def atan(__z: _C) -> complex: ... -def atanh(__z: _C) -> complex: ... -def cos(__z: _C) -> complex: ... -def cosh(__z: _C) -> complex: ... -def exp(__z: _C) -> complex: ... -def isinf(__z: _C) -> bool: ... -def isnan(__z: _C) -> bool: ... -def log(__x: _C, __y_obj: _C = ...) -> complex: ... -def log10(__z: _C) -> complex: ... -def phase(__z: _C) -> float: ... -def polar(__z: _C) -> Tuple[float, float]: ... -def rect(__r: float, __phi: float) -> complex: ... -def sin(__z: _C) -> complex: ... -def sinh(__z: _C) -> complex: ... -def sqrt(__z: _C) -> complex: ... -def tan(__z: _C) -> complex: ... -def tanh(__z: _C) -> complex: ... diff --git a/stdlib/@python2/cmd.pyi b/stdlib/@python2/cmd.pyi deleted file mode 100644 index ffccba84ec16..000000000000 --- a/stdlib/@python2/cmd.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from typing import IO, Any, Callable, List, Tuple - -class Cmd: - prompt: str - identchars: str - ruler: str - lastcmd: str - intro: Any | None - doc_leader: str - doc_header: str - misc_header: str - undoc_header: str - nohelp: str - use_rawinput: bool - stdin: IO[str] - stdout: IO[str] - cmdqueue: List[str] - completekey: str - def __init__(self, completekey: str = ..., stdin: IO[str] | None = ..., stdout: IO[str] | None = ...) -> None: ... - old_completer: Callable[[str, int], str | None] | None - def cmdloop(self, intro: Any | None = ...) -> None: ... - def precmd(self, line: str) -> str: ... - def postcmd(self, stop: bool, line: str) -> bool: ... - def preloop(self) -> None: ... - def postloop(self) -> None: ... - def parseline(self, line: str) -> Tuple[str | None, str | None, str]: ... - def onecmd(self, line: str) -> bool: ... - def emptyline(self) -> bool: ... - def default(self, line: str) -> bool: ... - def completedefault(self, *ignored: Any) -> List[str]: ... - def completenames(self, text: str, *ignored: Any) -> List[str]: ... - completion_matches: List[str] | None - def complete(self, text: str, state: int) -> List[str] | None: ... - def get_names(self) -> List[str]: ... - # Only the first element of args matters. - def complete_help(self, *args: Any) -> List[str]: ... - def do_help(self, arg: str) -> bool | None: ... - def print_topics(self, header: str, cmds: List[str] | None, cmdlen: Any, maxcol: int) -> None: ... - def columnize(self, list: List[str] | None, displaywidth: int = ...) -> None: ... diff --git a/stdlib/@python2/code.pyi b/stdlib/@python2/code.pyi deleted file mode 100644 index ae8dfc91a32b..000000000000 --- a/stdlib/@python2/code.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from types import CodeType -from typing import Any, Callable, Mapping - -class InteractiveInterpreter: - def __init__(self, locals: Mapping[str, Any] | None = ...) -> None: ... - def runsource(self, source: str, filename: str = ..., symbol: str = ...) -> bool: ... - def runcode(self, code: CodeType) -> None: ... - def showsyntaxerror(self, filename: str | None = ...) -> None: ... - def showtraceback(self) -> None: ... - def write(self, data: str) -> None: ... - -class InteractiveConsole(InteractiveInterpreter): - def __init__(self, locals: Mapping[str, Any] | None = ..., filename: str = ...) -> None: ... - def interact(self, banner: str | None = ...) -> None: ... - def push(self, line: str) -> bool: ... - def resetbuffer(self) -> None: ... - def raw_input(self, prompt: str = ...) -> str: ... - -def interact( - banner: str | None = ..., readfunc: Callable[[str], str] | None = ..., local: Mapping[str, Any] | None = ... -) -> None: ... -def compile_command(source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... diff --git a/stdlib/@python2/codecs.pyi b/stdlib/@python2/codecs.pyi deleted file mode 100644 index a7835106336d..000000000000 --- a/stdlib/@python2/codecs.pyi +++ /dev/null @@ -1,286 +0,0 @@ -import types -from abc import abstractmethod -from typing import ( - IO, - Any, - BinaryIO, - Callable, - Generator, - Iterable, - Iterator, - List, - Protocol, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal - -# TODO: this only satisfies the most common interface, where -# bytes (py2 str) is the raw form and str (py2 unicode) is the cooked form. -# In the long run, both should become template parameters maybe? -# There *are* bytes->bytes and str->str encodings in the standard library. -# They are much more common in Python 2 than in Python 3. - -_Decoded = Text -_Encoded = bytes - -class _Encoder(Protocol): - def __call__(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... # signature of Codec().encode - -class _Decoder(Protocol): - def __call__(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... # signature of Codec().decode - -class _StreamReader(Protocol): - def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamReader: ... - -class _StreamWriter(Protocol): - def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamWriter: ... - -class _IncrementalEncoder(Protocol): - def __call__(self, errors: str = ...) -> IncrementalEncoder: ... - -class _IncrementalDecoder(Protocol): - def __call__(self, errors: str = ...) -> IncrementalDecoder: ... - -# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 -# mypy and pytype disagree about where the type ignore can and cannot go, so alias the long type -_BytesToBytesEncodingT = Literal[ - "base64", - "base_64", - "base64_codec", - "bz2", - "bz2_codec", - "hex", - "hex_codec", - "quopri", - "quotedprintable", - "quoted_printable", - "quopri_codec", - "uu", - "uu_codec", - "zip", - "zlib", - "zlib_codec", -] - -@overload -def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... -@overload -def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore -@overload -def encode(obj: _Decoded, encoding: str = ..., errors: str = ...) -> _Encoded: ... -@overload -def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore -@overload -def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> Text: ... -@overload -def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: ... -def lookup(__encoding: str) -> CodecInfo: ... -def utf_16_be_decode( - __data: _Encoded, __errors: str | None = ..., __final: bool = ... -) -> Tuple[_Decoded, int]: ... # undocumented -def utf_16_be_encode(__str: _Decoded, __errors: str | None = ...) -> Tuple[_Encoded, int]: ... # undocumented - -class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): - @property - def encode(self) -> _Encoder: ... - @property - def decode(self) -> _Decoder: ... - @property - def streamreader(self) -> _StreamReader: ... - @property - def streamwriter(self) -> _StreamWriter: ... - @property - def incrementalencoder(self) -> _IncrementalEncoder: ... - @property - def incrementaldecoder(self) -> _IncrementalDecoder: ... - name: str - def __new__( - cls, - encode: _Encoder, - decode: _Decoder, - streamreader: _StreamReader | None = ..., - streamwriter: _StreamWriter | None = ..., - incrementalencoder: _IncrementalEncoder | None = ..., - incrementaldecoder: _IncrementalDecoder | None = ..., - name: str | None = ..., - *, - _is_text_encoding: bool | None = ..., - ) -> CodecInfo: ... - -def getencoder(encoding: str) -> _Encoder: ... -def getdecoder(encoding: str) -> _Decoder: ... -def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... -def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... -def getreader(encoding: str) -> _StreamReader: ... -def getwriter(encoding: str) -> _StreamWriter: ... -def register(__search_function: Callable[[str], CodecInfo | None]) -> None: ... -def open( - filename: str, mode: str = ..., encoding: str | None = ..., errors: str = ..., buffering: int = ... -) -> StreamReaderWriter: ... -def EncodedFile(file: IO[_Encoded], data_encoding: str, file_encoding: str | None = ..., errors: str = ...) -> StreamRecoder: ... -def iterencode(iterator: Iterable[_Decoded], encoding: str, errors: str = ...) -> Generator[_Encoded, None, None]: ... -def iterdecode(iterator: Iterable[_Encoded], encoding: str, errors: str = ...) -> Generator[_Decoded, None, None]: ... - -BOM: bytes -BOM_BE: bytes -BOM_LE: bytes -BOM_UTF8: bytes -BOM_UTF16: bytes -BOM_UTF16_BE: bytes -BOM_UTF16_LE: bytes -BOM_UTF32: bytes -BOM_UTF32_BE: bytes -BOM_UTF32_LE: bytes - -# It is expected that different actions be taken depending on which of the -# three subclasses of `UnicodeError` is actually ...ed. However, the Union -# is still needed for at least one of the cases. -def register_error(__errors: str, __handler: Callable[[UnicodeError], Tuple[str | bytes, int]]) -> None: ... -def lookup_error(__name: str) -> Callable[[UnicodeError], Tuple[str | bytes, int]]: ... -def strict_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def replace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def ignore_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def xmlcharrefreplace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def backslashreplace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... - -class Codec: - # These are sort of @abstractmethod but sort of not. - # The StreamReader and StreamWriter subclasses only implement one. - def encode(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... - def decode(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... - -class IncrementalEncoder: - errors: str - def __init__(self, errors: str = ...) -> None: ... - @abstractmethod - def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... - def reset(self) -> None: ... - # documentation says int but str is needed for the subclass. - def getstate(self) -> int | _Decoded: ... - def setstate(self, state: int | _Decoded) -> None: ... - -class IncrementalDecoder: - errors: str - def __init__(self, errors: str = ...) -> None: ... - @abstractmethod - def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... - def reset(self) -> None: ... - def getstate(self) -> Tuple[_Encoded, int]: ... - def setstate(self, state: Tuple[_Encoded, int]) -> None: ... - -# These are not documented but used in encodings/*.py implementations. -class BufferedIncrementalEncoder(IncrementalEncoder): - buffer: str - def __init__(self, errors: str = ...) -> None: ... - @abstractmethod - def _buffer_encode(self, input: _Decoded, errors: str, final: bool) -> _Encoded: ... - def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... - -class BufferedIncrementalDecoder(IncrementalDecoder): - buffer: bytes - def __init__(self, errors: str = ...) -> None: ... - @abstractmethod - def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> Tuple[_Decoded, int]: ... - def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... - -_SW = TypeVar("_SW", bound=StreamWriter) - -# TODO: it is not possible to specify the requirement that all other -# attributes and methods are passed-through from the stream. -class StreamWriter(Codec): - errors: str - def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... - def write(self, object: _Decoded) -> None: ... - def writelines(self, list: Iterable[_Decoded]) -> None: ... - def reset(self) -> None: ... - def __enter__(self: _SW) -> _SW: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... - -_SR = TypeVar("_SR", bound=StreamReader) - -class StreamReader(Codec): - errors: str - def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... - def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _Decoded: ... - def readline(self, size: int | None = ..., keepends: bool = ...) -> _Decoded: ... - def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> List[_Decoded]: ... - def reset(self) -> None: ... - def __enter__(self: _SR) -> _SR: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - def __iter__(self) -> Iterator[_Decoded]: ... - def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... - -_T = TypeVar("_T", bound=StreamReaderWriter) - -# Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing -# and delegates attributes to the underlying binary stream with __getattr__. -class StreamReaderWriter(TextIO): - def __init__(self, stream: IO[_Encoded], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... - def read(self, size: int = ...) -> _Decoded: ... - def readline(self, size: int | None = ...) -> _Decoded: ... - def readlines(self, sizehint: int | None = ...) -> List[_Decoded]: ... - def next(self) -> Text: ... - def __iter__(self: _T) -> _T: ... - # This actually returns None, but that's incompatible with the supertype - def write(self, data: _Decoded) -> int: ... - def writelines(self, list: Iterable[_Decoded]) -> None: ... - def reset(self) -> None: ... - # Same as write() - def seek(self, offset: int, whence: int = ...) -> int: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - def __getattr__(self, name: str) -> Any: ... - # These methods don't actually exist directly, but they are needed to satisfy the TextIO - # interface. At runtime, they are delegated through __getattr__. - def close(self) -> None: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def readable(self) -> bool: ... - def truncate(self, size: int | None = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def writable(self) -> bool: ... - -_SRT = TypeVar("_SRT", bound=StreamRecoder) - -class StreamRecoder(BinaryIO): - def __init__( - self, - stream: IO[_Encoded], - encode: _Encoder, - decode: _Decoder, - Reader: _StreamReader, - Writer: _StreamWriter, - errors: str = ..., - ) -> None: ... - def read(self, size: int = ...) -> bytes: ... - def readline(self, size: int | None = ...) -> bytes: ... - def readlines(self, sizehint: int | None = ...) -> List[bytes]: ... - def next(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... - def write(self, data: bytes) -> int: ... - def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None - def reset(self) -> None: ... - def __getattr__(self, name: str) -> Any: ... - def __enter__(self: _SRT) -> _SRT: ... - def __exit__(self, type: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... - # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO - # interface. At runtime, they are delegated through __getattr__. - def seek(self, offset: int, whence: int = ...) -> int: ... - def close(self) -> None: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def readable(self) -> bool: ... - def truncate(self, size: int | None = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def writable(self) -> bool: ... diff --git a/stdlib/@python2/codeop.pyi b/stdlib/@python2/codeop.pyi deleted file mode 100644 index 8ed5710c9891..000000000000 --- a/stdlib/@python2/codeop.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from types import CodeType - -def compile_command(source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... - -class Compile: - flags: int - def __init__(self) -> None: ... - def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... - -class CommandCompiler: - compiler: Compile - def __init__(self) -> None: ... - def __call__(self, source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... diff --git a/stdlib/@python2/collections.pyi b/stdlib/@python2/collections.pyi deleted file mode 100644 index 5a2f73aed7ce..000000000000 --- a/stdlib/@python2/collections.pyi +++ /dev/null @@ -1,122 +0,0 @@ -from typing import ( - AbstractSet, - Any, - Callable as Callable, - Container as Container, - Dict, - Generic, - Hashable as Hashable, - ItemsView as ItemsView, - Iterable as Iterable, - Iterator as Iterator, - KeysView as KeysView, - List, - Mapping as Mapping, - MappingView as MappingView, - MutableMapping as MutableMapping, - MutableSequence as MutableSequence, - MutableSet as MutableSet, - Reversible, - Sequence as Sequence, - Sized as Sized, - Tuple, - Type, - TypeVar, - ValuesView as ValuesView, - overload, -) - -Set = AbstractSet - -_S = TypeVar("_S") -_T = TypeVar("_T") -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - -# namedtuple is special-cased in the type checker; the initializer is ignored. -def namedtuple( - typename: str | unicode, field_names: str | unicode | Iterable[str | unicode], verbose: bool = ..., rename: bool = ... -) -> Type[Tuple[Any, ...]]: ... - -class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T] = ..., maxlen: int = ...) -> None: ... - @property - def maxlen(self) -> int | None: ... - def append(self, x: _T) -> None: ... - def appendleft(self, x: _T) -> None: ... - def clear(self) -> None: ... - def count(self, x: _T) -> int: ... - def extend(self, iterable: Iterable[_T]) -> None: ... - def extendleft(self, iterable: Iterable[_T]) -> None: ... - def pop(self) -> _T: ... - def popleft(self) -> _T: ... - def remove(self, value: _T) -> None: ... - def reverse(self) -> None: ... - def rotate(self, n: int = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - def __hash__(self) -> int: ... - def __getitem__(self, i: int) -> _T: ... - def __setitem__(self, i: int, x: _T) -> None: ... - def __contains__(self, o: _T) -> bool: ... - def __reversed__(self) -> Iterator[_T]: ... - def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... - -class Counter(Dict[_T, int], Generic[_T]): - @overload - def __init__(self, **kwargs: int) -> None: ... - @overload - def __init__(self, mapping: Mapping[_T, int]) -> None: ... - @overload - def __init__(self, iterable: Iterable[_T]) -> None: ... - def copy(self: _S) -> _S: ... - def elements(self) -> Iterator[_T]: ... - def most_common(self, n: int | None = ...) -> List[Tuple[_T, int]]: ... - @overload - def subtract(self, __mapping: Mapping[_T, int]) -> None: ... - @overload - def subtract(self, iterable: Iterable[_T]) -> None: ... - # The Iterable[Tuple[...]] argument type is not actually desirable - # (the tuples will be added as keys, breaking type safety) but - # it's included so that the signature is compatible with - # Dict.update. Not sure if we should use '# type: ignore' instead - # and omit the type from the union. - @overload - def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... - @overload - def update(self, __m: Iterable[_T] | Iterable[Tuple[_T, int]], **kwargs: int) -> None: ... - @overload - def update(self, **kwargs: int) -> None: ... - def __add__(self, other: Counter[_T]) -> Counter[_T]: ... - def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... - def __and__(self, other: Counter[_T]) -> Counter[_T]: ... - def __or__(self, other: Counter[_T]) -> Counter[_T]: ... - def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... - def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... - def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... - def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... - -class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): - def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... - def copy(self: _S) -> _S: ... - def __reversed__(self) -> Iterator[_KT]: ... - -class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): - default_factory: Callable[[], _VT] - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, default_factory: Callable[[], _VT] | None) -> None: ... - @overload - def __init__(self, default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... - @overload - def __init__(self, default_factory: Callable[[], _VT] | None, map: Mapping[_KT, _VT]) -> None: ... - @overload - def __init__(self, default_factory: Callable[[], _VT] | None, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... - @overload - def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __missing__(self, key: _KT) -> _VT: ... - def copy(self: _S) -> _S: ... diff --git a/stdlib/@python2/colorsys.pyi b/stdlib/@python2/colorsys.pyi deleted file mode 100644 index 8db2e2c9ab3a..000000000000 --- a/stdlib/@python2/colorsys.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Tuple - -def rgb_to_yiq(r: float, g: float, b: float) -> Tuple[float, float, float]: ... -def yiq_to_rgb(y: float, i: float, q: float) -> Tuple[float, float, float]: ... -def rgb_to_hls(r: float, g: float, b: float) -> Tuple[float, float, float]: ... -def hls_to_rgb(h: float, l: float, s: float) -> Tuple[float, float, float]: ... -def rgb_to_hsv(r: float, g: float, b: float) -> Tuple[float, float, float]: ... -def hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: ... - -# TODO undocumented -ONE_SIXTH: float -ONE_THIRD: float -TWO_THIRD: float diff --git a/stdlib/@python2/commands.pyi b/stdlib/@python2/commands.pyi deleted file mode 100644 index 970d6ccf2032..000000000000 --- a/stdlib/@python2/commands.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import AnyStr, Text, Tuple, overload - -def getstatus(file: Text) -> str: ... -def getoutput(cmd: Text) -> str: ... -def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... -@overload -def mk2arg(head: bytes, x: bytes) -> bytes: ... -@overload -def mk2arg(head: Text, x: Text) -> Text: ... -def mkarg(x: AnyStr) -> AnyStr: ... diff --git a/stdlib/@python2/compileall.pyi b/stdlib/@python2/compileall.pyi deleted file mode 100644 index ef22929c4c19..000000000000 --- a/stdlib/@python2/compileall.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any, Pattern, Text - -# rx can be any object with a 'search' method; once we have Protocols we can change the type -def compile_dir( - dir: Text, maxlevels: int = ..., ddir: Text | None = ..., force: bool = ..., rx: Pattern[Any] | None = ..., quiet: int = ... -) -> int: ... -def compile_file( - fullname: Text, ddir: Text | None = ..., force: bool = ..., rx: Pattern[Any] | None = ..., quiet: int = ... -) -> int: ... -def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ... diff --git a/stdlib/@python2/contextlib.pyi b/stdlib/@python2/contextlib.pyi deleted file mode 100644 index 6782fbf1874c..000000000000 --- a/stdlib/@python2/contextlib.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Protocol, Type, TypeVar - -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) -_T_io = TypeVar("_T_io", bound=Optional[IO[str]]) -_F = TypeVar("_F", bound=Callable[..., Any]) - -_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] -_CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) - -class GeneratorContextManager(ContextManager[_T_co]): - def __call__(self, func: _F) -> _F: ... - -def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... -def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ... - -class _SupportsClose(Protocol): - def close(self) -> None: ... - -_SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) - -class closing(ContextManager[_SupportsCloseT]): - def __init__(self, thing: _SupportsCloseT) -> None: ... diff --git a/stdlib/@python2/cookielib.pyi b/stdlib/@python2/cookielib.pyi deleted file mode 100644 index 0f813c128cc4..000000000000 --- a/stdlib/@python2/cookielib.pyi +++ /dev/null @@ -1,142 +0,0 @@ -from typing import Any - -class Cookie: - version: Any - name: Any - value: Any - port: Any - port_specified: Any - domain: Any - domain_specified: Any - domain_initial_dot: Any - path: Any - path_specified: Any - secure: Any - expires: Any - discard: Any - comment: Any - comment_url: Any - rfc2109: Any - def __init__( - self, - version, - name, - value, - port, - port_specified, - domain, - domain_specified, - domain_initial_dot, - path, - path_specified, - secure, - expires, - discard, - comment, - comment_url, - rest, - rfc2109: bool = ..., - ): ... - def has_nonstandard_attr(self, name): ... - def get_nonstandard_attr(self, name, default: Any | None = ...): ... - def set_nonstandard_attr(self, name, value): ... - def is_expired(self, now: Any | None = ...): ... - -class CookiePolicy: - def set_ok(self, cookie, request): ... - def return_ok(self, cookie, request): ... - def domain_return_ok(self, domain, request): ... - def path_return_ok(self, path, request): ... - -class DefaultCookiePolicy(CookiePolicy): - DomainStrictNoDots: Any - DomainStrictNonDomain: Any - DomainRFC2965Match: Any - DomainLiberal: Any - DomainStrict: Any - netscape: Any - rfc2965: Any - rfc2109_as_netscape: Any - hide_cookie2: Any - strict_domain: Any - strict_rfc2965_unverifiable: Any - strict_ns_unverifiable: Any - strict_ns_domain: Any - strict_ns_set_initial_dollar: Any - strict_ns_set_path: Any - def __init__( - self, - blocked_domains: Any | None = ..., - allowed_domains: Any | None = ..., - netscape: bool = ..., - rfc2965: bool = ..., - rfc2109_as_netscape: Any | None = ..., - hide_cookie2: bool = ..., - strict_domain: bool = ..., - strict_rfc2965_unverifiable: bool = ..., - strict_ns_unverifiable: bool = ..., - strict_ns_domain=..., - strict_ns_set_initial_dollar: bool = ..., - strict_ns_set_path: bool = ..., - ): ... - def blocked_domains(self): ... - def set_blocked_domains(self, blocked_domains): ... - def is_blocked(self, domain): ... - def allowed_domains(self): ... - def set_allowed_domains(self, allowed_domains): ... - def is_not_allowed(self, domain): ... - def set_ok(self, cookie, request): ... - def set_ok_version(self, cookie, request): ... - def set_ok_verifiability(self, cookie, request): ... - def set_ok_name(self, cookie, request): ... - def set_ok_path(self, cookie, request): ... - def set_ok_domain(self, cookie, request): ... - def set_ok_port(self, cookie, request): ... - def return_ok(self, cookie, request): ... - def return_ok_version(self, cookie, request): ... - def return_ok_verifiability(self, cookie, request): ... - def return_ok_secure(self, cookie, request): ... - def return_ok_expires(self, cookie, request): ... - def return_ok_port(self, cookie, request): ... - def return_ok_domain(self, cookie, request): ... - def domain_return_ok(self, domain, request): ... - def path_return_ok(self, path, request): ... - -class Absent: ... - -class CookieJar: - non_word_re: Any - quote_re: Any - strict_domain_re: Any - domain_re: Any - dots_re: Any - magic_re: Any - def __init__(self, policy: Any | None = ...): ... - def set_policy(self, policy): ... - def add_cookie_header(self, request): ... - def make_cookies(self, response, request): ... - def set_cookie_if_ok(self, cookie, request): ... - def set_cookie(self, cookie): ... - def extract_cookies(self, response, request): ... - def clear(self, domain: Any | None = ..., path: Any | None = ..., name: Any | None = ...): ... - def clear_session_cookies(self): ... - def clear_expired_cookies(self): ... - def __iter__(self): ... - def __len__(self): ... - -class LoadError(IOError): ... - -class FileCookieJar(CookieJar): - filename: Any - delayload: Any - def __init__(self, filename: Any | None = ..., delayload: bool = ..., policy: Any | None = ...): ... - def save(self, filename: Any | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... - def load(self, filename: Any | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... - def revert(self, filename: Any | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... - -class LWPCookieJar(FileCookieJar): - def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented - -MozillaCookieJar = FileCookieJar - -def lwp_cookie_str(cookie: Cookie) -> str: ... diff --git a/stdlib/@python2/copy.pyi b/stdlib/@python2/copy.pyi deleted file mode 100644 index c88f92846ddf..000000000000 --- a/stdlib/@python2/copy.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Any, Dict, TypeVar - -_T = TypeVar("_T") - -# None in CPython but non-None in Jython -PyStringMap: Any - -# Note: memo and _nil are internal kwargs. -def deepcopy(x: _T, memo: Dict[int, Any] | None = ..., _nil: Any = ...) -> _T: ... -def copy(x: _T) -> _T: ... - -class Error(Exception): ... - -error = Error diff --git a/stdlib/@python2/copy_reg.pyi b/stdlib/@python2/copy_reg.pyi deleted file mode 100644 index 91b099888bab..000000000000 --- a/stdlib/@python2/copy_reg.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union - -_TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] - -__all__: List[str] - -def pickle( - ob_type: _TypeT, - pickle_function: Callable[[_TypeT], str | _Reduce[_TypeT]], - constructor_ob: Callable[[_Reduce[_TypeT]], _TypeT] | None = ..., -) -> None: ... -def constructor(object: Callable[[_Reduce[_TypeT]], _TypeT]) -> None: ... -def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: ... -def remove_extension(module: Hashable, name: Hashable, code: int) -> None: ... -def clear_extension_cache() -> None: ... diff --git a/stdlib/@python2/copyreg.pyi b/stdlib/@python2/copyreg.pyi deleted file mode 100644 index 91b099888bab..000000000000 --- a/stdlib/@python2/copyreg.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union - -_TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] - -__all__: List[str] - -def pickle( - ob_type: _TypeT, - pickle_function: Callable[[_TypeT], str | _Reduce[_TypeT]], - constructor_ob: Callable[[_Reduce[_TypeT]], _TypeT] | None = ..., -) -> None: ... -def constructor(object: Callable[[_Reduce[_TypeT]], _TypeT]) -> None: ... -def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: ... -def remove_extension(module: Hashable, name: Hashable, code: int) -> None: ... -def clear_extension_cache() -> None: ... diff --git a/stdlib/@python2/crypt.pyi b/stdlib/@python2/crypt.pyi deleted file mode 100644 index c4036dbe7a5a..000000000000 --- a/stdlib/@python2/crypt.pyi +++ /dev/null @@ -1 +0,0 @@ -def crypt(word: str, salt: str) -> str: ... diff --git a/stdlib/@python2/csv.pyi b/stdlib/@python2/csv.pyi deleted file mode 100644 index 886de6210ca9..000000000000 --- a/stdlib/@python2/csv.pyi +++ /dev/null @@ -1,102 +0,0 @@ -from _csv import ( - QUOTE_ALL as QUOTE_ALL, - QUOTE_MINIMAL as QUOTE_MINIMAL, - QUOTE_NONE as QUOTE_NONE, - QUOTE_NONNUMERIC as QUOTE_NONNUMERIC, - Dialect as Dialect, - Error as Error, - _DialectLike, - _reader, - _writer, - field_size_limit as field_size_limit, - get_dialect as get_dialect, - list_dialects as list_dialects, - reader as reader, - register_dialect as register_dialect, - unregister_dialect as unregister_dialect, - writer as writer, -) -from typing import ( - Any, - Dict as _DictReadMapping, - Generic, - Iterable, - Iterator, - List, - Mapping, - Sequence, - Text, - Type, - TypeVar, - overload, -) - -_T = TypeVar("_T") - -class excel(Dialect): - delimiter: str - quotechar: str - doublequote: bool - skipinitialspace: bool - lineterminator: str - quoting: int - -class excel_tab(excel): - delimiter: str - -class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): - fieldnames: Sequence[_T] | None - restkey: str | None - restval: str | None - reader: _reader - dialect: _DialectLike - line_num: int - @overload - def __init__( - self, - f: Iterable[Text], - fieldnames: Sequence[_T], - restkey: str | None = ..., - restval: str | None = ..., - dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, - ) -> None: ... - @overload - def __init__( - self: DictReader[str], - f: Iterable[Text], - fieldnames: Sequence[str] | None = ..., - restkey: str | None = ..., - restval: str | None = ..., - dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, - ) -> None: ... - def __iter__(self) -> DictReader[_T]: ... - def next(self) -> _DictReadMapping[_T, str]: ... - -class DictWriter(Generic[_T]): - fieldnames: Sequence[_T] - restval: Any | None - extrasaction: str - writer: _writer - def __init__( - self, - f: Any, - fieldnames: Sequence[_T], - restval: Any | None = ..., - extrasaction: str = ..., - dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, - ) -> None: ... - def writeheader(self) -> None: ... - def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... - def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... - -class Sniffer(object): - preferred: List[str] - def __init__(self) -> None: ... - def sniff(self, sample: str, delimiters: str | None = ...) -> Type[Dialect]: ... - def has_header(self, sample: str) -> bool: ... diff --git a/stdlib/@python2/ctypes/__init__.pyi b/stdlib/@python2/ctypes/__init__.pyi deleted file mode 100644 index 8a10ff954e27..000000000000 --- a/stdlib/@python2/ctypes/__init__.pyi +++ /dev/null @@ -1,293 +0,0 @@ -import sys -from array import array -from typing import ( - Any, - Callable, - ClassVar, - Generic, - Iterable, - Iterator, - List, - Mapping, - Optional, - Sequence, - Text, - Tuple, - Type, - TypeVar, - Union as _UnionT, - overload, -) - -_T = TypeVar("_T") -_DLLT = TypeVar("_DLLT", bound=CDLL) -_CT = TypeVar("_CT", bound=_CData) - -RTLD_GLOBAL: int = ... -RTLD_LOCAL: int = ... -DEFAULT_MODE: int = ... - -class CDLL(object): - _func_flags_: ClassVar[int] = ... - _func_restype_: ClassVar[_CData] = ... - _name: str = ... - _handle: int = ... - _FuncPtr: Type[_FuncPointer] = ... - def __init__( - self, name: str | None, mode: int = ..., handle: int | None = ..., use_errno: bool = ..., use_last_error: bool = ... - ) -> None: ... - def __getattr__(self, name: str) -> _NamedFuncPointer: ... - def __getitem__(self, name: str) -> _NamedFuncPointer: ... - -if sys.platform == "win32": - class OleDLL(CDLL): ... - class WinDLL(CDLL): ... - -class PyDLL(CDLL): ... - -class LibraryLoader(Generic[_DLLT]): - def __init__(self, dlltype: Type[_DLLT]) -> None: ... - def __getattr__(self, name: str) -> _DLLT: ... - def __getitem__(self, name: str) -> _DLLT: ... - def LoadLibrary(self, name: str) -> _DLLT: ... - -cdll: LibraryLoader[CDLL] = ... -if sys.platform == "win32": - windll: LibraryLoader[WinDLL] = ... - oledll: LibraryLoader[OleDLL] = ... -pydll: LibraryLoader[PyDLL] = ... -pythonapi: PyDLL = ... - -# Anything that implements the read-write buffer interface. -# The buffer interface is defined purely on the C level, so we cannot define a normal Protocol -# for it. Instead we have to list the most common stdlib buffer classes in a Union. -_WritableBuffer = _UnionT[bytearray, memoryview, array[Any], _CData] -# Same as _WritableBuffer, but also includes read-only buffer types (like bytes). -_ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes] - -class _CDataMeta(type): - # By default mypy complains about the following two methods, because strictly speaking cls - # might not be a Type[_CT]. However this can never actually happen, because the only class that - # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here. - def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore - def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore - -class _CData(metaclass=_CDataMeta): - _b_base: int = ... - _b_needsfree_: bool = ... - _objects: Mapping[Any, int] | None = ... - @classmethod - def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ... - @classmethod - def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ... - @classmethod - def from_address(cls: Type[_CT], address: int) -> _CT: ... - @classmethod - def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... - @classmethod - def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... - -class _CanCastTo(_CData): ... -class _PointerLike(_CanCastTo): ... - -_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData] -_PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] - -class _FuncPointer(_PointerLike, _CData): - restype: _UnionT[Type[_CData], Callable[[int], Any], None] = ... - argtypes: Sequence[Type[_CData]] = ... - errcheck: _ECT = ... - @overload - def __init__(self, address: int) -> None: ... - @overload - def __init__(self, callable: Callable[..., Any]) -> None: ... - @overload - def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ... - @overload - def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - -class _NamedFuncPointer(_FuncPointer): - __name__: str - -class ArgumentError(Exception): ... - -def CFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... -) -> Type[_FuncPointer]: ... - -if sys.platform == "win32": - def WINFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... - ) -> Type[_FuncPointer]: ... - -def PYFUNCTYPE(restype: Type[_CData] | None, *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... - -class _CArgObject: ... - -# Any type that can be implicitly converted to c_void_p when passed as a C function argument. -# (bytes is not included here, see below.) -_CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] -# Same as above, but including types known to be read-only (i. e. bytes). -# This distinction is not strictly necessary (ctypes doesn't differentiate between const -# and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) -# when memmove(buf, b'foo', 4) was intended. -_CVoidConstPLike = _UnionT[_CVoidPLike, bytes] - -def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... -def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... - -_CastT = TypeVar("_CastT", bound=_CanCastTo) - -def cast(obj: _UnionT[_CData, _CArgObject, int], typ: Type[_CastT]) -> _CastT: ... -def create_string_buffer(init: _UnionT[int, bytes], size: int | None = ...) -> Array[c_char]: ... - -c_buffer = create_string_buffer - -def create_unicode_buffer(init: _UnionT[int, Text], size: int | None = ...) -> Array[c_wchar]: ... - -if sys.platform == "win32": - def DllCanUnloadNow() -> int: ... - def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented - def FormatError(code: int = ...) -> str: ... - def GetLastError() -> int: ... - -def get_errno() -> int: ... - -if sys.platform == "win32": - def get_last_error() -> int: ... - -def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ... -def memset(dst: _CVoidPLike, c: int, count: int) -> None: ... -def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... - -# The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like -# ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, -# it can be instantiated directly (to mimic the behavior of the real pointer function). -class pointer(Generic[_CT], _PointerLike, _CData): - _type_: Type[_CT] = ... - contents: _CT = ... - def __init__(self, arg: _CT = ...) -> None: ... - @overload - def __getitem__(self, i: int) -> _CT: ... - @overload - def __getitem__(self, s: slice) -> List[_CT]: ... - @overload - def __setitem__(self, i: int, o: _CT) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... - -def resize(obj: _CData, size: int) -> None: ... -def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ... -def set_errno(value: int) -> int: ... - -if sys.platform == "win32": - def set_last_error(value: int) -> int: ... - -def sizeof(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... -def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... - -if sys.platform == "win32": - def WinError(code: int | None = ..., descr: str | None = ...) -> OSError: ... - -def wstring_at(address: _CVoidConstPLike, size: int = ...) -> str: ... - -class _SimpleCData(Generic[_T], _CData): - value: _T = ... - def __init__(self, value: _T = ...) -> None: ... - -class c_byte(_SimpleCData[int]): ... - -class c_char(_SimpleCData[bytes]): - def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ... - -class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): - def __init__(self, value: _UnionT[int, bytes] | None = ...) -> None: ... - -class c_double(_SimpleCData[float]): ... -class c_longdouble(_SimpleCData[float]): ... -class c_float(_SimpleCData[float]): ... -class c_int(_SimpleCData[int]): ... -class c_int8(_SimpleCData[int]): ... -class c_int16(_SimpleCData[int]): ... -class c_int32(_SimpleCData[int]): ... -class c_int64(_SimpleCData[int]): ... -class c_long(_SimpleCData[int]): ... -class c_longlong(_SimpleCData[int]): ... -class c_short(_SimpleCData[int]): ... -class c_size_t(_SimpleCData[int]): ... -class c_ssize_t(_SimpleCData[int]): ... -class c_ubyte(_SimpleCData[int]): ... -class c_uint(_SimpleCData[int]): ... -class c_uint8(_SimpleCData[int]): ... -class c_uint16(_SimpleCData[int]): ... -class c_uint32(_SimpleCData[int]): ... -class c_uint64(_SimpleCData[int]): ... -class c_ulong(_SimpleCData[int]): ... -class c_ulonglong(_SimpleCData[int]): ... -class c_ushort(_SimpleCData[int]): ... -class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ... -class c_wchar(_SimpleCData[Text]): ... - -class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]): - def __init__(self, value: _UnionT[int, Text] | None = ...) -> None: ... - -class c_bool(_SimpleCData[bool]): - def __init__(self, value: bool = ...) -> None: ... - -if sys.platform == "win32": - class HRESULT(_SimpleCData[int]): ... # TODO undocumented - -class py_object(_CanCastTo, _SimpleCData[_T]): ... - -class _CField: - offset: int = ... - size: int = ... - -class _StructUnionMeta(_CDataMeta): - _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ... - _pack_: int = ... - _anonymous_: Sequence[str] = ... - def __getattr__(self, name: str) -> _CField: ... - -class _StructUnionBase(_CData, metaclass=_StructUnionMeta): - def __init__(self, *args: Any, **kw: Any) -> None: ... - def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - -class Union(_StructUnionBase): ... -class Structure(_StructUnionBase): ... -class BigEndianStructure(Structure): ... -class LittleEndianStructure(Structure): ... - -class Array(Generic[_CT], _CData): - _length_: int = ... - _type_: Type[_CT] = ... - raw: bytes = ... # Note: only available if _CT == c_char - value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise - # TODO These methods cannot be annotated correctly at the moment. - # All of these "Any"s stand for the array's element type, but it's not possible to use _CT - # here, because of a special feature of ctypes. - # By default, when accessing an element of an Array[_CT], the returned object has type _CT. - # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object - # and converts it to the corresponding Python primitive. For example, when accessing an element - # of an Array[c_int], a Python int object is returned, not a c_int. - # This behavior does *not* apply to subclasses of "simple types". - # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns - # a MyInt, not an int. - # This special behavior is not easy to model in a stub, so for now all places where - # the array element type would belong are annotated with Any instead. - def __init__(self, *args: Any) -> None: ... - @overload - def __getitem__(self, i: int) -> Any: ... - @overload - def __getitem__(self, s: slice) -> List[Any]: ... - @overload - def __setitem__(self, i: int, o: Any) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ... - def __iter__(self) -> Iterator[Any]: ... - # Can't inherit from Sized because the metaclass conflict between - # Sized and _CData prevents using _CDataMeta. - def __len__(self) -> int: ... diff --git a/stdlib/@python2/ctypes/util.pyi b/stdlib/@python2/ctypes/util.pyi deleted file mode 100644 index c0274f5e539b..000000000000 --- a/stdlib/@python2/ctypes/util.pyi +++ /dev/null @@ -1,6 +0,0 @@ -import sys - -def find_library(name: str) -> str | None: ... - -if sys.platform == "win32": - def find_msvcrt() -> str | None: ... diff --git a/stdlib/@python2/ctypes/wintypes.pyi b/stdlib/@python2/ctypes/wintypes.pyi deleted file mode 100644 index c178a9bdf936..000000000000 --- a/stdlib/@python2/ctypes/wintypes.pyi +++ /dev/null @@ -1,234 +0,0 @@ -from ctypes import ( - Array, - Structure, - _SimpleCData, - c_byte, - c_char, - c_char_p, - c_double, - c_float, - c_int, - c_long, - c_longlong, - c_short, - c_uint, - c_ulong, - c_ulonglong, - c_ushort, - c_void_p, - c_wchar, - c_wchar_p, - pointer, -) - -BYTE = c_byte -WORD = c_ushort -DWORD = c_ulong -CHAR = c_char -WCHAR = c_wchar -UINT = c_uint -INT = c_int -DOUBLE = c_double -FLOAT = c_float -BOOLEAN = BYTE -BOOL = c_long - -class VARIANT_BOOL(_SimpleCData[bool]): ... - -ULONG = c_ulong -LONG = c_long -USHORT = c_ushort -SHORT = c_short -LARGE_INTEGER = c_longlong -_LARGE_INTEGER = c_longlong -ULARGE_INTEGER = c_ulonglong -_ULARGE_INTEGER = c_ulonglong - -OLESTR = c_wchar_p -LPOLESTR = c_wchar_p -LPCOLESTR = c_wchar_p -LPWSTR = c_wchar_p -LPCWSTR = c_wchar_p -LPSTR = c_char_p -LPCSTR = c_char_p -LPVOID = c_void_p -LPCVOID = c_void_p - -# These two types are pointer-sized unsigned and signed ints, respectively. -# At runtime, they are either c_[u]long or c_[u]longlong, depending on the host's pointer size -# (they are not really separate classes). -class WPARAM(_SimpleCData[int]): ... -class LPARAM(_SimpleCData[int]): ... - -ATOM = WORD -LANGID = WORD -COLORREF = DWORD -LGRPID = DWORD -LCTYPE = DWORD -LCID = DWORD - -HANDLE = c_void_p -HACCEL = HANDLE -HBITMAP = HANDLE -HBRUSH = HANDLE -HCOLORSPACE = HANDLE -HDC = HANDLE -HDESK = HANDLE -HDWP = HANDLE -HENHMETAFILE = HANDLE -HFONT = HANDLE -HGDIOBJ = HANDLE -HGLOBAL = HANDLE -HHOOK = HANDLE -HICON = HANDLE -HINSTANCE = HANDLE -HKEY = HANDLE -HKL = HANDLE -HLOCAL = HANDLE -HMENU = HANDLE -HMETAFILE = HANDLE -HMODULE = HANDLE -HMONITOR = HANDLE -HPALETTE = HANDLE -HPEN = HANDLE -HRGN = HANDLE -HRSRC = HANDLE -HSTR = HANDLE -HTASK = HANDLE -HWINSTA = HANDLE -HWND = HANDLE -SC_HANDLE = HANDLE -SERVICE_STATUS_HANDLE = HANDLE - -class RECT(Structure): - left: LONG - top: LONG - right: LONG - bottom: LONG - -RECTL = RECT -_RECTL = RECT -tagRECT = RECT - -class _SMALL_RECT(Structure): - Left: SHORT - Top: SHORT - Right: SHORT - Bottom: SHORT - -SMALL_RECT = _SMALL_RECT - -class _COORD(Structure): - X: SHORT - Y: SHORT - -class POINT(Structure): - x: LONG - y: LONG - -POINTL = POINT -_POINTL = POINT -tagPOINT = POINT - -class SIZE(Structure): - cx: LONG - cy: LONG - -SIZEL = SIZE -tagSIZE = SIZE - -def RGB(red: int, green: int, blue: int) -> int: ... - -class FILETIME(Structure): - dwLowDateTime: DWORD - dwHighDateTime: DWORD - -_FILETIME = FILETIME - -class MSG(Structure): - hWnd: HWND - message: UINT - wParam: WPARAM - lParam: LPARAM - time: DWORD - pt: POINT - -tagMSG = MSG -MAX_PATH: int - -class WIN32_FIND_DATAA(Structure): - dwFileAttributes: DWORD - ftCreationTime: FILETIME - ftLastAccessTime: FILETIME - ftLastWriteTime: FILETIME - nFileSizeHigh: DWORD - nFileSizeLow: DWORD - dwReserved0: DWORD - dwReserved1: DWORD - cFileName: Array[CHAR] - cAlternateFileName: Array[CHAR] - -class WIN32_FIND_DATAW(Structure): - dwFileAttributes: DWORD - ftCreationTime: FILETIME - ftLastAccessTime: FILETIME - ftLastWriteTime: FILETIME - nFileSizeHigh: DWORD - nFileSizeLow: DWORD - dwReserved0: DWORD - dwReserved1: DWORD - cFileName: Array[WCHAR] - cAlternateFileName: Array[WCHAR] - -# These pointer type definitions use pointer[...] instead of POINTER(...), to allow them -# to be used in type annotations. -PBOOL = pointer[BOOL] -LPBOOL = pointer[BOOL] -PBOOLEAN = pointer[BOOLEAN] -PBYTE = pointer[BYTE] -LPBYTE = pointer[BYTE] -PCHAR = pointer[CHAR] -LPCOLORREF = pointer[COLORREF] -PDWORD = pointer[DWORD] -LPDWORD = pointer[DWORD] -PFILETIME = pointer[FILETIME] -LPFILETIME = pointer[FILETIME] -PFLOAT = pointer[FLOAT] -PHANDLE = pointer[HANDLE] -LPHANDLE = pointer[HANDLE] -PHKEY = pointer[HKEY] -LPHKL = pointer[HKL] -PINT = pointer[INT] -LPINT = pointer[INT] -PLARGE_INTEGER = pointer[LARGE_INTEGER] -PLCID = pointer[LCID] -PLONG = pointer[LONG] -LPLONG = pointer[LONG] -PMSG = pointer[MSG] -LPMSG = pointer[MSG] -PPOINT = pointer[POINT] -LPPOINT = pointer[POINT] -PPOINTL = pointer[POINTL] -PRECT = pointer[RECT] -LPRECT = pointer[RECT] -PRECTL = pointer[RECTL] -LPRECTL = pointer[RECTL] -LPSC_HANDLE = pointer[SC_HANDLE] -PSHORT = pointer[SHORT] -PSIZE = pointer[SIZE] -LPSIZE = pointer[SIZE] -PSIZEL = pointer[SIZEL] -LPSIZEL = pointer[SIZEL] -PSMALL_RECT = pointer[SMALL_RECT] -PUINT = pointer[UINT] -LPUINT = pointer[UINT] -PULARGE_INTEGER = pointer[ULARGE_INTEGER] -PULONG = pointer[ULONG] -PUSHORT = pointer[USHORT] -PWCHAR = pointer[WCHAR] -PWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] -LPWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] -PWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] -LPWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] -PWORD = pointer[WORD] -LPWORD = pointer[WORD] diff --git a/stdlib/@python2/curses/__init__.pyi b/stdlib/@python2/curses/__init__.pyi deleted file mode 100644 index 73e84fba3763..000000000000 --- a/stdlib/@python2/curses/__init__.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from _curses import * # noqa: F403 -from _curses import _CursesWindow as _CursesWindow -from typing import Any, Callable, TypeVar - -_T = TypeVar("_T") - -# available after calling `curses.initscr()` -LINES: int -COLS: int - -# available after calling `curses.start_color()` -COLORS: int -COLOR_PAIRS: int - -def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... diff --git a/stdlib/@python2/curses/ascii.pyi b/stdlib/@python2/curses/ascii.pyi deleted file mode 100644 index 05efb326687a..000000000000 --- a/stdlib/@python2/curses/ascii.pyi +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List, TypeVar - -_CharT = TypeVar("_CharT", str, int) - -NUL: int -SOH: int -STX: int -ETX: int -EOT: int -ENQ: int -ACK: int -BEL: int -BS: int -TAB: int -HT: int -LF: int -NL: int -VT: int -FF: int -CR: int -SO: int -SI: int -DLE: int -DC1: int -DC2: int -DC3: int -DC4: int -NAK: int -SYN: int -ETB: int -CAN: int -EM: int -SUB: int -ESC: int -FS: int -GS: int -RS: int -US: int -SP: int -DEL: int - -controlnames: List[int] - -def isalnum(c: str | int) -> bool: ... -def isalpha(c: str | int) -> bool: ... -def isascii(c: str | int) -> bool: ... -def isblank(c: str | int) -> bool: ... -def iscntrl(c: str | int) -> bool: ... -def isdigit(c: str | int) -> bool: ... -def isgraph(c: str | int) -> bool: ... -def islower(c: str | int) -> bool: ... -def isprint(c: str | int) -> bool: ... -def ispunct(c: str | int) -> bool: ... -def isspace(c: str | int) -> bool: ... -def isupper(c: str | int) -> bool: ... -def isxdigit(c: str | int) -> bool: ... -def isctrl(c: str | int) -> bool: ... -def ismeta(c: str | int) -> bool: ... -def ascii(c: _CharT) -> _CharT: ... -def ctrl(c: _CharT) -> _CharT: ... -def alt(c: _CharT) -> _CharT: ... -def unctrl(c: str | int) -> str: ... diff --git a/stdlib/@python2/curses/panel.pyi b/stdlib/@python2/curses/panel.pyi deleted file mode 100644 index 138e4a9f727e..000000000000 --- a/stdlib/@python2/curses/panel.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from _curses import _CursesWindow - -class _Curses_Panel: # type is (note the space in the class name) - def above(self) -> _Curses_Panel: ... - def below(self) -> _Curses_Panel: ... - def bottom(self) -> None: ... - def hidden(self) -> bool: ... - def hide(self) -> None: ... - def move(self, y: int, x: int) -> None: ... - def replace(self, win: _CursesWindow) -> None: ... - def set_userptr(self, obj: object) -> None: ... - def show(self) -> None: ... - def top(self) -> None: ... - def userptr(self) -> object: ... - def window(self) -> _CursesWindow: ... - -def bottom_panel() -> _Curses_Panel: ... -def new_panel(__win: _CursesWindow) -> _Curses_Panel: ... -def top_panel() -> _Curses_Panel: ... -def update_panels() -> _Curses_Panel: ... diff --git a/stdlib/@python2/curses/textpad.pyi b/stdlib/@python2/curses/textpad.pyi deleted file mode 100644 index 578a579fda38..000000000000 --- a/stdlib/@python2/curses/textpad.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from _curses import _CursesWindow -from typing import Callable - -def rectangle(win: _CursesWindow, uly: int, ulx: int, lry: int, lrx: int) -> None: ... - -class Textbox: - stripspaces: bool - def __init__(self, win: _CursesWindow, insert_mode: bool = ...) -> None: ... - def edit(self, validate: Callable[[int], int] | None = ...) -> str: ... - def do_command(self, ch: str | int) -> None: ... - def gather(self) -> str: ... diff --git a/stdlib/@python2/datetime.pyi b/stdlib/@python2/datetime.pyi deleted file mode 100644 index 8b19a3d316f2..000000000000 --- a/stdlib/@python2/datetime.pyi +++ /dev/null @@ -1,226 +0,0 @@ -from time import struct_time -from typing import AnyStr, ClassVar, SupportsAbs, Tuple, Type, TypeVar, Union, overload - -_S = TypeVar("_S") - -_Text = Union[str, unicode] - -MINYEAR: int -MAXYEAR: int - -class tzinfo: - def tzname(self, dt: datetime | None) -> str | None: ... - def utcoffset(self, dt: datetime | None) -> timedelta | None: ... - def dst(self, dt: datetime | None) -> timedelta | None: ... - def fromutc(self, dt: datetime) -> datetime: ... - -_tzinfo = tzinfo - -class date: - min: ClassVar[date] - max: ClassVar[date] - resolution: ClassVar[timedelta] - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... - @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... - @classmethod - def today(cls: Type[_S]) -> _S: ... - @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... - @property - def year(self) -> int: ... - @property - def month(self) -> int: ... - @property - def day(self) -> int: ... - def ctime(self) -> str: ... - def strftime(self, fmt: _Text) -> str: ... - def __format__(self, fmt: AnyStr) -> AnyStr: ... - def isoformat(self) -> str: ... - def timetuple(self) -> struct_time: ... - def toordinal(self) -> int: ... - def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... - def __le__(self, other: date) -> bool: ... - def __lt__(self, other: date) -> bool: ... - def __ge__(self, other: date) -> bool: ... - def __gt__(self, other: date) -> bool: ... - def __add__(self, other: timedelta) -> date: ... - def __radd__(self, other: timedelta) -> date: ... - @overload - def __sub__(self, other: timedelta) -> date: ... - @overload - def __sub__(self, other: date) -> timedelta: ... - def __hash__(self) -> int: ... - def weekday(self) -> int: ... - def isoweekday(self) -> int: ... - def isocalendar(self) -> Tuple[int, int, int]: ... - -class time: - min: ClassVar[time] - max: ClassVar[time] - resolution: ClassVar[timedelta] - def __new__( - cls: Type[_S], hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ... - ) -> _S: ... - @property - def hour(self) -> int: ... - @property - def minute(self) -> int: ... - @property - def second(self) -> int: ... - @property - def microsecond(self) -> int: ... - @property - def tzinfo(self) -> _tzinfo | None: ... - def __le__(self, other: time) -> bool: ... - def __lt__(self, other: time) -> bool: ... - def __ge__(self, other: time) -> bool: ... - def __gt__(self, other: time) -> bool: ... - def __hash__(self) -> int: ... - def isoformat(self) -> str: ... - def strftime(self, fmt: _Text) -> str: ... - def __format__(self, fmt: AnyStr) -> AnyStr: ... - def utcoffset(self) -> timedelta | None: ... - def tzname(self) -> str | None: ... - def dst(self) -> timedelta | None: ... - def replace( - self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ... - ) -> time: ... - -_date = date -_time = time - -class timedelta(SupportsAbs[timedelta]): - min: ClassVar[timedelta] - max: ClassVar[timedelta] - resolution: ClassVar[timedelta] - def __new__( - cls: Type[_S], - days: float = ..., - seconds: float = ..., - microseconds: float = ..., - milliseconds: float = ..., - minutes: float = ..., - hours: float = ..., - weeks: float = ..., - ) -> _S: ... - @property - def days(self) -> int: ... - @property - def seconds(self) -> int: ... - @property - def microseconds(self) -> int: ... - def total_seconds(self) -> float: ... - def __add__(self, other: timedelta) -> timedelta: ... - def __radd__(self, other: timedelta) -> timedelta: ... - def __sub__(self, other: timedelta) -> timedelta: ... - def __rsub__(self, other: timedelta) -> timedelta: ... - def __neg__(self) -> timedelta: ... - def __pos__(self) -> timedelta: ... - def __abs__(self) -> timedelta: ... - def __mul__(self, other: float) -> timedelta: ... - def __rmul__(self, other: float) -> timedelta: ... - @overload - def __floordiv__(self, other: timedelta) -> int: ... - @overload - def __floordiv__(self, other: int) -> timedelta: ... - @overload - def __div__(self, other: timedelta) -> float: ... - @overload - def __div__(self, other: float) -> timedelta: ... - def __le__(self, other: timedelta) -> bool: ... - def __lt__(self, other: timedelta) -> bool: ... - def __ge__(self, other: timedelta) -> bool: ... - def __gt__(self, other: timedelta) -> bool: ... - def __hash__(self) -> int: ... - -class datetime(date): - min: ClassVar[datetime] - max: ClassVar[datetime] - resolution: ClassVar[timedelta] - def __new__( - cls: Type[_S], - year: int, - month: int, - day: int, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., - ) -> _S: ... - @property - def year(self) -> int: ... - @property - def month(self) -> int: ... - @property - def day(self) -> int: ... - @property - def hour(self) -> int: ... - @property - def minute(self) -> int: ... - @property - def second(self) -> int: ... - @property - def microsecond(self) -> int: ... - @property - def tzinfo(self) -> _tzinfo | None: ... - @classmethod - def fromtimestamp(cls: Type[_S], t: float, tz: _tzinfo | None = ...) -> _S: ... - @classmethod - def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... - @classmethod - def today(cls: Type[_S]) -> _S: ... - @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... - @overload - @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... - @overload - @classmethod - def now(cls, tz: _tzinfo) -> datetime: ... - @classmethod - def utcnow(cls: Type[_S]) -> _S: ... - @classmethod - def combine(cls, date: _date, time: _time) -> datetime: ... - def strftime(self, fmt: _Text) -> str: ... - def __format__(self, fmt: AnyStr) -> AnyStr: ... - def toordinal(self) -> int: ... - def timetuple(self) -> struct_time: ... - def utctimetuple(self) -> struct_time: ... - def date(self) -> _date: ... - def time(self) -> _time: ... - def timetz(self) -> _time: ... - def replace( - self, - year: int = ..., - month: int = ..., - day: int = ..., - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., - ) -> datetime: ... - def astimezone(self, tz: _tzinfo) -> datetime: ... - def ctime(self) -> str: ... - def isoformat(self, sep: str = ...) -> str: ... - @classmethod - def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... - def utcoffset(self) -> timedelta | None: ... - def tzname(self) -> str | None: ... - def dst(self) -> timedelta | None: ... - def __le__(self, other: datetime) -> bool: ... # type: ignore - def __lt__(self, other: datetime) -> bool: ... # type: ignore - def __ge__(self, other: datetime) -> bool: ... # type: ignore - def __gt__(self, other: datetime) -> bool: ... # type: ignore - def __add__(self, other: timedelta) -> datetime: ... - def __radd__(self, other: timedelta) -> datetime: ... - @overload # type: ignore - def __sub__(self, other: datetime) -> timedelta: ... - @overload - def __sub__(self, other: timedelta) -> datetime: ... - def __hash__(self) -> int: ... - def weekday(self) -> int: ... - def isoweekday(self) -> int: ... - def isocalendar(self) -> Tuple[int, int, int]: ... diff --git a/stdlib/@python2/dbm/__init__.pyi b/stdlib/@python2/dbm/__init__.pyi deleted file mode 100644 index 95f6d9cf0363..000000000000 --- a/stdlib/@python2/dbm/__init__.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from types import TracebackType -from typing import Iterator, MutableMapping, Tuple, Type, Union -from typing_extensions import Literal - -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] - -class _Database(MutableMapping[_KeyType, bytes]): - def close(self) -> None: ... - def __getitem__(self, key: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... - def __delitem__(self, key: _KeyType) -> None: ... - def __iter__(self) -> Iterator[bytes]: ... - def __len__(self) -> int: ... - def __del__(self) -> None: ... - def __enter__(self) -> _Database: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - -class _error(Exception): ... - -error = Tuple[Type[_error], Type[OSError]] - -def whichdb(filename: str) -> str: ... -def open(file: str, flag: Literal["r", "w", "c", "n"] = ..., mode: int = ...) -> _Database: ... diff --git a/stdlib/@python2/dbm/dumb.pyi b/stdlib/@python2/dbm/dumb.pyi deleted file mode 100644 index fb5e2da5fa2c..000000000000 --- a/stdlib/@python2/dbm/dumb.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union - -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] - -error = OSError - -class _Database(MutableMapping[_KeyType, bytes]): - def __init__(self, filebasename: str, mode: str, flag: str = ...) -> None: ... - def sync(self) -> None: ... - def iterkeys(self) -> Iterator[bytes]: ... # undocumented - def close(self) -> None: ... - def __getitem__(self, key: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... - def __delitem__(self, key: _KeyType) -> None: ... - def __iter__(self) -> Iterator[bytes]: ... - def __len__(self) -> int: ... - def __del__(self) -> None: ... - def __enter__(self) -> _Database: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - -def open(file: str, flag: str = ..., mode: int = ...) -> _Database: ... diff --git a/stdlib/@python2/dbm/gnu.pyi b/stdlib/@python2/dbm/gnu.pyi deleted file mode 100644 index 0e9339bf81f9..000000000000 --- a/stdlib/@python2/dbm/gnu.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from types import TracebackType -from typing import List, Type, TypeVar, Union, overload - -_T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] - -class error(OSError): ... - -# Actual typename gdbm, not exposed by the implementation -class _gdbm: - def firstkey(self) -> bytes | None: ... - def nextkey(self, key: _KeyType) -> bytes | None: ... - def reorganize(self) -> None: ... - def sync(self) -> None: ... - def close(self) -> None: ... - def __getitem__(self, item: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... - def __delitem__(self, key: _KeyType) -> None: ... - def __len__(self) -> int: ... - def __enter__(self) -> _gdbm: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - @overload - def get(self, k: _KeyType) -> bytes | None: ... - @overload - def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> List[bytes]: ... - def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... - # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore - -def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... diff --git a/stdlib/@python2/dbm/ndbm.pyi b/stdlib/@python2/dbm/ndbm.pyi deleted file mode 100644 index 28f4dd8e4e59..000000000000 --- a/stdlib/@python2/dbm/ndbm.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from types import TracebackType -from typing import List, Type, TypeVar, Union, overload - -_T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] - -class error(OSError): ... - -library: str = ... - -# Actual typename dbm, not exposed by the implementation -class _dbm: - def close(self) -> None: ... - def __getitem__(self, item: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... - def __delitem__(self, key: _KeyType) -> None: ... - def __len__(self) -> int: ... - def __del__(self) -> None: ... - def __enter__(self) -> _dbm: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - @overload - def get(self, k: _KeyType) -> bytes | None: ... - @overload - def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> List[bytes]: ... - def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... - # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore - -def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... diff --git a/stdlib/@python2/decimal.pyi b/stdlib/@python2/decimal.pyi deleted file mode 100644 index 915bddadb584..000000000000 --- a/stdlib/@python2/decimal.pyi +++ /dev/null @@ -1,246 +0,0 @@ -from types import TracebackType -from typing import Any, Container, Dict, List, NamedTuple, Sequence, Text, Tuple, Type, TypeVar, Union - -_Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) - -class DecimalTuple(NamedTuple): - sign: int - digits: Tuple[int, ...] - exponent: int - -ROUND_DOWN: str -ROUND_HALF_UP: str -ROUND_HALF_EVEN: str -ROUND_CEILING: str -ROUND_FLOOR: str -ROUND_UP: str -ROUND_HALF_DOWN: str -ROUND_05UP: str - -class DecimalException(ArithmeticError): - def handle(self, context: Context, *args: Any) -> Decimal | None: ... - -class Clamped(DecimalException): ... -class InvalidOperation(DecimalException): ... -class ConversionSyntax(InvalidOperation): ... -class DivisionByZero(DecimalException, ZeroDivisionError): ... -class DivisionImpossible(InvalidOperation): ... -class DivisionUndefined(InvalidOperation, ZeroDivisionError): ... -class Inexact(DecimalException): ... -class InvalidContext(InvalidOperation): ... -class Rounded(DecimalException): ... -class Subnormal(DecimalException): ... -class Overflow(Inexact, Rounded): ... -class Underflow(Inexact, Rounded, Subnormal): ... - -def setcontext(__context: Context) -> None: ... -def getcontext() -> Context: ... -def localcontext(ctx: Context | None = ...) -> _ContextManager: ... - -class Decimal(object): - def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... - @classmethod - def from_float(cls, __f: float) -> Decimal: ... - def __nonzero__(self) -> bool: ... - def __div__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rdiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __ne__(self, other: object, context: Context | None = ...) -> bool: ... - def compare(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __hash__(self) -> int: ... - def as_tuple(self) -> DecimalTuple: ... - def to_eng_string(self, context: Context | None = ...) -> str: ... - def __abs__(self, round: bool = ..., context: Context | None = ...) -> Decimal: ... - def __add__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __divmod__(self, other: _Decimal, context: Context | None = ...) -> Tuple[Decimal, Decimal]: ... - def __eq__(self, other: object, context: Context | None = ...) -> bool: ... - def __floordiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __ge__(self, other: _ComparableNum, context: Context | None = ...) -> bool: ... - def __gt__(self, other: _ComparableNum, context: Context | None = ...) -> bool: ... - def __le__(self, other: _ComparableNum, context: Context | None = ...) -> bool: ... - def __lt__(self, other: _ComparableNum, context: Context | None = ...) -> bool: ... - def __mod__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __mul__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __neg__(self, context: Context | None = ...) -> Decimal: ... - def __pos__(self, context: Context | None = ...) -> Decimal: ... - def __pow__(self, other: _Decimal, modulo: _Decimal | None = ..., context: Context | None = ...) -> Decimal: ... - def __radd__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rdivmod__(self, other: _Decimal, context: Context | None = ...) -> Tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rmod__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rmul__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rsub__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rtruediv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __str__(self, eng: bool = ..., context: Context | None = ...) -> str: ... - def __sub__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __truediv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - def __trunc__(self) -> int: ... - @property - def real(self) -> Decimal: ... - @property - def imag(self) -> Decimal: ... - def conjugate(self) -> Decimal: ... - def __complex__(self) -> complex: ... - def __long__(self) -> long: ... - def fma(self, other: _Decimal, third: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rpow__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def normalize(self, context: Context | None = ...) -> Decimal: ... - def quantize( - self, exp: _Decimal, rounding: str | None = ..., context: Context | None = ..., watchexp: bool = ... - ) -> Decimal: ... - def same_quantum(self, other: _Decimal) -> bool: ... - def to_integral_exact(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def to_integral_value(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def to_integral(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def sqrt(self, context: Context | None = ...) -> Decimal: ... - def max(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def min(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def adjusted(self) -> int: ... - def canonical(self, context: Context | None = ...) -> Decimal: ... - def compare_signal(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def compare_total(self, other: _Decimal) -> Decimal: ... - def compare_total_mag(self, other: _Decimal) -> Decimal: ... - def copy_abs(self) -> Decimal: ... - def copy_negate(self) -> Decimal: ... - def copy_sign(self, other: _Decimal) -> Decimal: ... - def exp(self, context: Context | None = ...) -> Decimal: ... - def is_canonical(self) -> bool: ... - def is_finite(self) -> bool: ... - def is_infinite(self) -> bool: ... - def is_nan(self) -> bool: ... - def is_normal(self, context: Context | None = ...) -> bool: ... - def is_qnan(self) -> bool: ... - def is_signed(self) -> bool: ... - def is_snan(self) -> bool: ... - def is_subnormal(self, context: Context | None = ...) -> bool: ... - def is_zero(self) -> bool: ... - def ln(self, context: Context | None = ...) -> Decimal: ... - def log10(self, context: Context | None = ...) -> Decimal: ... - def logb(self, context: Context | None = ...) -> Decimal: ... - def logical_and(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def logical_invert(self, context: Context | None = ...) -> Decimal: ... - def logical_or(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def logical_xor(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def max_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def min_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def next_minus(self, context: Context | None = ...) -> Decimal: ... - def next_plus(self, context: Context | None = ...) -> Decimal: ... - def next_toward(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def number_class(self, context: Context | None = ...) -> str: ... - def radix(self) -> Decimal: ... - def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self) -> Tuple[Type[Decimal], Tuple[str]]: ... - def __copy__(self) -> Decimal: ... - def __deepcopy__(self, memo: Any) -> Decimal: ... - def __format__(self, specifier: str, context: Context | None = ...) -> str: ... - -class _ContextManager(object): - new_context: Context - saved_context: Context - def __init__(self, new_context: Context) -> None: ... - def __enter__(self) -> Context: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... - -_TrapType = Type[DecimalException] - -class Context(object): - prec: int - rounding: str - Emin: int - Emax: int - capitals: int - _clamp: int - traps: Dict[_TrapType, bool] - flags: Dict[_TrapType, bool] - def __init__( - self, - prec: int | None = ..., - rounding: str | None = ..., - traps: None | Dict[_TrapType, bool] | Container[_TrapType] = ..., - flags: None | Dict[_TrapType, bool] | Container[_TrapType] = ..., - Emin: int | None = ..., - Emax: int | None = ..., - capitals: int | None = ..., - _clamp: int | None = ..., - _ignored_flags: List[_TrapType] | None = ..., - ) -> None: ... - def clear_flags(self) -> None: ... - def copy(self) -> Context: ... - def __copy__(self) -> Context: ... - __hash__: Any = ... - def Etiny(self) -> int: ... - def Etop(self) -> int: ... - def create_decimal(self, __num: _DecimalNew = ...) -> Decimal: ... - def create_decimal_from_float(self, __f: float) -> Decimal: ... - def abs(self, __x: _Decimal) -> Decimal: ... - def add(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def canonical(self, __x: Decimal) -> Decimal: ... - def compare(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_signal(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def copy_abs(self, __x: _Decimal) -> Decimal: ... - def copy_decimal(self, __x: _Decimal) -> Decimal: ... - def copy_negate(self, __x: _Decimal) -> Decimal: ... - def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divmod(self, __x: _Decimal, __y: _Decimal) -> Tuple[Decimal, Decimal]: ... - def exp(self, __x: _Decimal) -> Decimal: ... - def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... - def is_canonical(self, __x: _Decimal) -> bool: ... - def is_finite(self, __x: _Decimal) -> bool: ... - def is_infinite(self, __x: _Decimal) -> bool: ... - def is_nan(self, __x: _Decimal) -> bool: ... - def is_normal(self, __x: _Decimal) -> bool: ... - def is_qnan(self, __x: _Decimal) -> bool: ... - def is_signed(self, __x: _Decimal) -> bool: ... - def is_snan(self, __x: _Decimal) -> bool: ... - def is_subnormal(self, __x: _Decimal) -> bool: ... - def is_zero(self, __x: _Decimal) -> bool: ... - def ln(self, __x: _Decimal) -> Decimal: ... - def log10(self, __x: _Decimal) -> Decimal: ... - def logb(self, __x: _Decimal) -> Decimal: ... - def logical_and(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_invert(self, __x: _Decimal) -> Decimal: ... - def logical_or(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_xor(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def minus(self, __x: _Decimal) -> Decimal: ... - def multiply(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def next_minus(self, __x: _Decimal) -> Decimal: ... - def next_plus(self, __x: _Decimal) -> Decimal: ... - def next_toward(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def normalize(self, __x: _Decimal) -> Decimal: ... - def number_class(self, __x: _Decimal) -> str: ... - def plus(self, __x: _Decimal) -> Decimal: ... - def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = ...) -> Decimal: ... - def quantize(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def radix(self) -> Decimal: ... - def remainder(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def remainder_near(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def rotate(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def same_quantum(self, __x: _Decimal, __y: _Decimal) -> bool: ... - def scaleb(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def shift(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def sqrt(self, __x: _Decimal) -> Decimal: ... - def subtract(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def to_eng_string(self, __x: _Decimal) -> str: ... - def to_sci_string(self, __x: _Decimal) -> str: ... - def to_integral_exact(self, __x: _Decimal) -> Decimal: ... - def to_integral_value(self, __x: _Decimal) -> Decimal: ... - def to_integral(self, __x: _Decimal) -> Decimal: ... - -DefaultContext: Context -BasicContext: Context -ExtendedContext: Context diff --git a/stdlib/@python2/difflib.pyi b/stdlib/@python2/difflib.pyi deleted file mode 100644 index 41ffc6a286d1..000000000000 --- a/stdlib/@python2/difflib.pyi +++ /dev/null @@ -1,112 +0,0 @@ -from typing import ( - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - List, - NamedTuple, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) - -_T = TypeVar("_T") - -# Aliases can't point to type vars, so we need to redeclare AnyStr -_StrType = TypeVar("_StrType", Text, bytes) - -_JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] - -class Match(NamedTuple): - a: int - b: int - size: int - -class SequenceMatcher(Generic[_T]): - def __init__( - self, isjunk: Callable[[_T], bool] | None = ..., a: Sequence[_T] = ..., b: Sequence[_T] = ..., autojunk: bool = ... - ) -> None: ... - def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... - def set_seq1(self, a: Sequence[_T]) -> None: ... - def set_seq2(self, b: Sequence[_T]) -> None: ... - def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... - def get_matching_blocks(self) -> List[Match]: ... - def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ... - def get_grouped_opcodes(self, n: int = ...) -> Iterable[List[Tuple[str, int, int, int, int]]]: ... - def ratio(self) -> float: ... - def quick_ratio(self) -> float: ... - def real_quick_ratio(self) -> float: ... - -# mypy thinks the signatures of the overloads overlap, but the types still work fine -@overload -def get_close_matches( # type: ignore - word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ... -) -> List[AnyStr]: ... -@overload -def get_close_matches( - word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... -) -> List[Sequence[_T]]: ... - -class Differ: - def __init__(self, linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ...) -> None: ... - def compare(self, a: Sequence[_StrType], b: Sequence[_StrType]) -> Iterator[_StrType]: ... - -def IS_LINE_JUNK(line: _StrType, pat: Any = ...) -> bool: ... # pat is undocumented -def IS_CHARACTER_JUNK(ch: _StrType, ws: _StrType = ...) -> bool: ... # ws is undocumented -def unified_diff( - a: Sequence[_StrType], - b: Sequence[_StrType], - fromfile: _StrType = ..., - tofile: _StrType = ..., - fromfiledate: _StrType = ..., - tofiledate: _StrType = ..., - n: int = ..., - lineterm: _StrType = ..., -) -> Iterator[_StrType]: ... -def context_diff( - a: Sequence[_StrType], - b: Sequence[_StrType], - fromfile: _StrType = ..., - tofile: _StrType = ..., - fromfiledate: _StrType = ..., - tofiledate: _StrType = ..., - n: int = ..., - lineterm: _StrType = ..., -) -> Iterator[_StrType]: ... -def ndiff( - a: Sequence[_StrType], b: Sequence[_StrType], linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ... -) -> Iterator[_StrType]: ... - -class HtmlDiff(object): - def __init__( - self, - tabsize: int = ..., - wrapcolumn: int | None = ..., - linejunk: _JunkCallback | None = ..., - charjunk: _JunkCallback | None = ..., - ) -> None: ... - def make_file( - self, - fromlines: Sequence[_StrType], - tolines: Sequence[_StrType], - fromdesc: _StrType = ..., - todesc: _StrType = ..., - context: bool = ..., - numlines: int = ..., - ) -> _StrType: ... - def make_table( - self, - fromlines: Sequence[_StrType], - tolines: Sequence[_StrType], - fromdesc: _StrType = ..., - todesc: _StrType = ..., - context: bool = ..., - numlines: int = ..., - ) -> _StrType: ... - -def restore(delta: Iterable[_StrType], which: int) -> Iterator[_StrType]: ... diff --git a/stdlib/@python2/dircache.pyi b/stdlib/@python2/dircache.pyi deleted file mode 100644 index 366909d87133..000000000000 --- a/stdlib/@python2/dircache.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import List, MutableSequence, Text - -def reset() -> None: ... -def listdir(path: Text) -> List[str]: ... - -opendir = listdir - -def annotate(head: Text, list: MutableSequence[str] | MutableSequence[Text] | MutableSequence[str | Text]) -> None: ... diff --git a/stdlib/@python2/dis.pyi b/stdlib/@python2/dis.pyi deleted file mode 100644 index 1d6537667a60..000000000000 --- a/stdlib/@python2/dis.pyi +++ /dev/null @@ -1,30 +0,0 @@ -import types -from opcode import ( - EXTENDED_ARG as EXTENDED_ARG, - HAVE_ARGUMENT as HAVE_ARGUMENT, - cmp_op as cmp_op, - hascompare as hascompare, - hasconst as hasconst, - hasfree as hasfree, - hasjabs as hasjabs, - hasjrel as hasjrel, - haslocal as haslocal, - hasname as hasname, - opmap as opmap, - opname as opname, -) -from typing import Any, Callable, Dict, Iterator, List, Tuple, Union - -# Strictly this should not have to include Callable, but mypy doesn't use FunctionType -# for functions (python/mypy#3171) -_have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] -_have_code_or_string = Union[_have_code, str, bytes] - -COMPILER_FLAG_NAMES: Dict[int, str] - -def findlabels(code: _have_code) -> List[int]: ... -def findlinestarts(code: _have_code) -> Iterator[Tuple[int, int]]: ... -def dis(x: _have_code_or_string = ...) -> None: ... -def distb(tb: types.TracebackType = ...) -> None: ... -def disassemble(co: _have_code, lasti: int = ...) -> None: ... -def disco(co: _have_code, lasti: int = ...) -> None: ... diff --git a/stdlib/@python2/distutils/archive_util.pyi b/stdlib/@python2/distutils/archive_util.pyi deleted file mode 100644 index dd2cbda73fc6..000000000000 --- a/stdlib/@python2/distutils/archive_util.pyi +++ /dev/null @@ -1,5 +0,0 @@ -def make_archive( - base_name: str, format: str, root_dir: str | None = ..., base_dir: str | None = ..., verbose: int = ..., dry_run: int = ... -) -> str: ... -def make_tarball(base_name: str, base_dir: str, compress: str | None = ..., verbose: int = ..., dry_run: int = ...) -> str: ... -def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., dry_run: int = ...) -> str: ... diff --git a/stdlib/@python2/distutils/bcppcompiler.pyi b/stdlib/@python2/distutils/bcppcompiler.pyi deleted file mode 100644 index 3e432f94b525..000000000000 --- a/stdlib/@python2/distutils/bcppcompiler.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from distutils.ccompiler import CCompiler - -class BCPPCompiler(CCompiler): ... diff --git a/stdlib/@python2/distutils/ccompiler.pyi b/stdlib/@python2/distutils/ccompiler.pyi deleted file mode 100644 index b0539bf9e5dc..000000000000 --- a/stdlib/@python2/distutils/ccompiler.pyi +++ /dev/null @@ -1,150 +0,0 @@ -from typing import Any, Callable, List, Optional, Tuple, Union - -_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] - -def gen_lib_options( - compiler: CCompiler, library_dirs: List[str], runtime_library_dirs: List[str], libraries: List[str] -) -> List[str]: ... -def gen_preprocess_options(macros: List[_Macro], include_dirs: List[str]) -> List[str]: ... -def get_default_compiler(osname: str | None = ..., platform: str | None = ...) -> str: ... -def new_compiler( - plat: str | None = ..., compiler: str | None = ..., verbose: int = ..., dry_run: int = ..., force: int = ... -) -> CCompiler: ... -def show_compilers() -> None: ... - -class CCompiler: - dry_run: bool - force: bool - verbose: bool - output_dir: str | None - macros: List[_Macro] - include_dirs: List[str] - libraries: List[str] - library_dirs: List[str] - runtime_library_dirs: List[str] - objects: List[str] - def __init__(self, verbose: int = ..., dry_run: int = ..., force: int = ...) -> None: ... - def add_include_dir(self, dir: str) -> None: ... - def set_include_dirs(self, dirs: List[str]) -> None: ... - def add_library(self, libname: str) -> None: ... - def set_libraries(self, libnames: List[str]) -> None: ... - def add_library_dir(self, dir: str) -> None: ... - def set_library_dirs(self, dirs: List[str]) -> None: ... - def add_runtime_library_dir(self, dir: str) -> None: ... - def set_runtime_library_dirs(self, dirs: List[str]) -> None: ... - def define_macro(self, name: str, value: str | None = ...) -> None: ... - def undefine_macro(self, name: str) -> None: ... - def add_link_object(self, object: str) -> None: ... - def set_link_objects(self, objects: List[str]) -> None: ... - def detect_language(self, sources: str | List[str]) -> str | None: ... - def find_library_file(self, dirs: List[str], lib: str, debug: bool = ...) -> str | None: ... - def has_function( - self, - funcname: str, - includes: List[str] | None = ..., - include_dirs: List[str] | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - ) -> bool: ... - def library_dir_option(self, dir: str) -> str: ... - def library_option(self, lib: str) -> str: ... - def runtime_library_dir_option(self, dir: str) -> str: ... - def set_executables(self, **args: str) -> None: ... - def compile( - self, - sources: List[str], - output_dir: str | None = ..., - macros: _Macro | None = ..., - include_dirs: List[str] | None = ..., - debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - depends: List[str] | None = ..., - ) -> List[str]: ... - def create_static_lib( - self, - objects: List[str], - output_libname: str, - output_dir: str | None = ..., - debug: bool = ..., - target_lang: str | None = ..., - ) -> None: ... - def link( - self, - target_desc: str, - objects: List[str], - output_filename: str, - output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., - debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - build_temp: str | None = ..., - target_lang: str | None = ..., - ) -> None: ... - def link_executable( - self, - objects: List[str], - output_progname: str, - output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - target_lang: str | None = ..., - ) -> None: ... - def link_shared_lib( - self, - objects: List[str], - output_libname: str, - output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., - debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - build_temp: str | None = ..., - target_lang: str | None = ..., - ) -> None: ... - def link_shared_object( - self, - objects: List[str], - output_filename: str, - output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., - debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - build_temp: str | None = ..., - target_lang: str | None = ..., - ) -> None: ... - def preprocess( - self, - source: str, - output_file: str | None = ..., - macros: List[_Macro] | None = ..., - include_dirs: List[str] | None = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - ) -> None: ... - def executable_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... - def library_filename(self, libname: str, lib_type: str = ..., strip_dir: int = ..., output_dir: str = ...) -> str: ... - def object_filenames(self, source_filenames: List[str], strip_dir: int = ..., output_dir: str = ...) -> List[str]: ... - def shared_object_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... - def execute(self, func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., level: int = ...) -> None: ... - def spawn(self, cmd: List[str]) -> None: ... - def mkpath(self, name: str, mode: int = ...) -> None: ... - def move_file(self, src: str, dst: str) -> str: ... - def announce(self, msg: str, level: int = ...) -> None: ... - def warn(self, msg: str) -> None: ... - def debug_print(self, msg: str) -> None: ... diff --git a/stdlib/@python2/distutils/cmd.pyi b/stdlib/@python2/distutils/cmd.pyi deleted file mode 100644 index d4e90bf69970..000000000000 --- a/stdlib/@python2/distutils/cmd.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from abc import abstractmethod -from distutils.dist import Distribution -from typing import Any, Callable, Iterable, List, Text, Tuple - -class Command: - sub_commands: List[Tuple[str, Callable[[Command], bool] | None]] - def __init__(self, dist: Distribution) -> None: ... - @abstractmethod - def initialize_options(self) -> None: ... - @abstractmethod - def finalize_options(self) -> None: ... - @abstractmethod - def run(self) -> None: ... - def announce(self, msg: Text, level: int = ...) -> None: ... - def debug_print(self, msg: Text) -> None: ... - def ensure_string(self, option: str, default: str | None = ...) -> None: ... - def ensure_string_list(self, option: str | List[str]) -> None: ... - def ensure_filename(self, option: str) -> None: ... - def ensure_dirname(self, option: str) -> None: ... - def get_command_name(self) -> str: ... - def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ... - def get_finalized_command(self, command: Text, create: int = ...) -> Command: ... - def reinitialize_command(self, command: Command | Text, reinit_subcommands: int = ...) -> Command: ... - def run_command(self, command: Text) -> None: ... - def get_sub_commands(self) -> List[str]: ... - def warn(self, msg: Text) -> None: ... - def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Text | None = ..., level: int = ...) -> None: ... - def mkpath(self, name: str, mode: int = ...) -> None: ... - def copy_file( - self, - infile: str, - outfile: str, - preserve_mode: int = ..., - preserve_times: int = ..., - link: str | None = ..., - level: Any = ..., - ) -> Tuple[str, bool]: ... # level is not used - def copy_tree( - self, - infile: str, - outfile: str, - preserve_mode: int = ..., - preserve_times: int = ..., - preserve_symlinks: int = ..., - level: Any = ..., - ) -> List[str]: ... # level is not used - def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used - def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used - def make_archive( - self, - base_name: str, - format: str, - root_dir: str | None = ..., - base_dir: str | None = ..., - owner: str | None = ..., - group: str | None = ..., - ) -> str: ... - def make_file( - self, - infiles: str | List[str] | Tuple[str], - outfile: str, - func: Callable[..., Any], - args: List[Any], - exec_msg: str | None = ..., - skip_msg: str | None = ..., - level: Any = ..., - ) -> None: ... # level is not used diff --git a/stdlib/@python2/distutils/command/bdist_msi.pyi b/stdlib/@python2/distutils/command/bdist_msi.pyi deleted file mode 100644 index a761792018a9..000000000000 --- a/stdlib/@python2/distutils/command/bdist_msi.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from distutils.cmd import Command - -class bdist_msi(Command): - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... diff --git a/stdlib/@python2/distutils/command/build_py.pyi b/stdlib/@python2/distutils/command/build_py.pyi deleted file mode 100644 index a29a1f3a12a7..000000000000 --- a/stdlib/@python2/distutils/command/build_py.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from distutils.cmd import Command - -class build_py(Command): - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... diff --git a/stdlib/@python2/distutils/command/config.pyi b/stdlib/@python2/distutils/command/config.pyi deleted file mode 100644 index d0fd762e83b2..000000000000 --- a/stdlib/@python2/distutils/command/config.pyi +++ /dev/null @@ -1,83 +0,0 @@ -from distutils import log as log -from distutils.ccompiler import CCompiler -from distutils.core import Command as Command -from distutils.errors import DistutilsExecError as DistutilsExecError -from distutils.sysconfig import customize_compiler as customize_compiler -from typing import Dict, List, Pattern, Sequence, Tuple - -LANG_EXT: Dict[str, str] - -class config(Command): - description: str = ... - # Tuple is full name, short name, description - user_options: Sequence[Tuple[str, str | None, str]] = ... - compiler: str | CCompiler | None = ... - cc: str | None = ... - include_dirs: Sequence[str] | None = ... - libraries: Sequence[str] | None = ... - library_dirs: Sequence[str] | None = ... - noisy: int = ... - dump_source: int = ... - temp_files: Sequence[str] = ... - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... - def try_cpp( - self, - body: str | None = ..., - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - lang: str = ..., - ) -> bool: ... - def search_cpp( - self, - pattern: Pattern[str] | str, - body: str | None = ..., - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - lang: str = ..., - ) -> bool: ... - def try_compile( - self, body: str, headers: Sequence[str] | None = ..., include_dirs: Sequence[str] | None = ..., lang: str = ... - ) -> bool: ... - def try_link( - self, - body: str, - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - libraries: Sequence[str] | None = ..., - library_dirs: Sequence[str] | None = ..., - lang: str = ..., - ) -> bool: ... - def try_run( - self, - body: str, - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - libraries: Sequence[str] | None = ..., - library_dirs: Sequence[str] | None = ..., - lang: str = ..., - ) -> bool: ... - def check_func( - self, - func: str, - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - libraries: Sequence[str] | None = ..., - library_dirs: Sequence[str] | None = ..., - decl: int = ..., - call: int = ..., - ) -> bool: ... - def check_lib( - self, - library: str, - library_dirs: Sequence[str] | None = ..., - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - other_libraries: List[str] = ..., - ) -> bool: ... - def check_header( - self, header: str, include_dirs: Sequence[str] | None = ..., library_dirs: Sequence[str] | None = ..., lang: str = ... - ) -> bool: ... - -def dump_file(filename: str, head: str | None = ...) -> None: ... diff --git a/stdlib/@python2/distutils/command/install.pyi b/stdlib/@python2/distutils/command/install.pyi deleted file mode 100644 index 2824236735f0..000000000000 --- a/stdlib/@python2/distutils/command/install.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from distutils.cmd import Command -from typing import Text - -class install(Command): - user: bool - prefix: Text | None - home: Text | None - root: Text | None - install_lib: Text | None - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... diff --git a/stdlib/@python2/distutils/command/install_egg_info.pyi b/stdlib/@python2/distutils/command/install_egg_info.pyi deleted file mode 100644 index bf3d0737f244..000000000000 --- a/stdlib/@python2/distutils/command/install_egg_info.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from distutils.cmd import Command -from typing import ClassVar, List, Tuple - -class install_egg_info(Command): - description: ClassVar[str] - user_options: ClassVar[List[Tuple[str, str | None, str]]] - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... - def get_outputs(self) -> List[str]: ... diff --git a/stdlib/@python2/distutils/command/upload.pyi b/stdlib/@python2/distutils/command/upload.pyi deleted file mode 100644 index 3835d9fd6ec6..000000000000 --- a/stdlib/@python2/distutils/command/upload.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from distutils.config import PyPIRCCommand -from typing import ClassVar, List, Tuple - -class upload(PyPIRCCommand): - description: ClassVar[str] - boolean_options: ClassVar[List[str]] - def run(self) -> None: ... - def upload_file(self, command, pyversion, filename) -> None: ... diff --git a/stdlib/@python2/distutils/config.pyi b/stdlib/@python2/distutils/config.pyi deleted file mode 100644 index bcd626c81d48..000000000000 --- a/stdlib/@python2/distutils/config.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from abc import abstractmethod -from distutils.cmd import Command -from typing import ClassVar, List, Tuple - -DEFAULT_PYPIRC: str - -class PyPIRCCommand(Command): - DEFAULT_REPOSITORY: ClassVar[str] - DEFAULT_REALM: ClassVar[str] - repository: None - realm: None - user_options: ClassVar[List[Tuple[str, str | None, str]]] - boolean_options: ClassVar[List[str]] - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - @abstractmethod - def run(self) -> None: ... diff --git a/stdlib/@python2/distutils/core.pyi b/stdlib/@python2/distutils/core.pyi deleted file mode 100644 index 48bd7b5018bc..000000000000 --- a/stdlib/@python2/distutils/core.pyi +++ /dev/null @@ -1,48 +0,0 @@ -from distutils.cmd import Command as Command -from distutils.dist import Distribution as Distribution -from distutils.extension import Extension as Extension -from typing import Any, List, Mapping, Tuple, Type - -def setup( - *, - name: str = ..., - version: str = ..., - description: str = ..., - long_description: str = ..., - author: str = ..., - author_email: str = ..., - maintainer: str = ..., - maintainer_email: str = ..., - url: str = ..., - download_url: str = ..., - packages: List[str] = ..., - py_modules: List[str] = ..., - scripts: List[str] = ..., - ext_modules: List[Extension] = ..., - classifiers: List[str] = ..., - distclass: Type[Distribution] = ..., - script_name: str = ..., - script_args: List[str] = ..., - options: Mapping[str, Any] = ..., - license: str = ..., - keywords: List[str] | str = ..., - platforms: List[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., - data_files: List[Tuple[str, List[str]]] = ..., - package_dir: Mapping[str, str] = ..., - obsoletes: List[str] = ..., - provides: List[str] = ..., - requires: List[str] = ..., - command_packages: List[str] = ..., - command_options: Mapping[str, Mapping[str, Tuple[Any, Any]]] = ..., - package_data: Mapping[str, List[str]] = ..., - include_package_data: bool = ..., - libraries: List[str] = ..., - headers: List[str] = ..., - ext_package: str = ..., - include_dirs: List[str] = ..., - password: str = ..., - fullname: str = ..., - **attrs: Any, -) -> None: ... -def run_setup(script_name: str, script_args: List[str] | None = ..., stop_after: str = ...) -> Distribution: ... diff --git a/stdlib/@python2/distutils/cygwinccompiler.pyi b/stdlib/@python2/distutils/cygwinccompiler.pyi deleted file mode 100644 index 1f85b254860b..000000000000 --- a/stdlib/@python2/distutils/cygwinccompiler.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from distutils.unixccompiler import UnixCCompiler - -class CygwinCCompiler(UnixCCompiler): ... -class Mingw32CCompiler(CygwinCCompiler): ... diff --git a/stdlib/@python2/distutils/debug.pyi b/stdlib/@python2/distutils/debug.pyi deleted file mode 100644 index 098dc3dee246..000000000000 --- a/stdlib/@python2/distutils/debug.pyi +++ /dev/null @@ -1 +0,0 @@ -DEBUG: bool diff --git a/stdlib/@python2/distutils/dep_util.pyi b/stdlib/@python2/distutils/dep_util.pyi deleted file mode 100644 index 6f779d540e5e..000000000000 --- a/stdlib/@python2/distutils/dep_util.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import List, Tuple - -def newer(source: str, target: str) -> bool: ... -def newer_pairwise(sources: List[str], targets: List[str]) -> List[Tuple[str, str]]: ... -def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ... diff --git a/stdlib/@python2/distutils/dir_util.pyi b/stdlib/@python2/distutils/dir_util.pyi deleted file mode 100644 index 4c4a22102558..000000000000 --- a/stdlib/@python2/distutils/dir_util.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import List - -def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> List[str]: ... -def create_tree(base_dir: str, files: List[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... -def copy_tree( - src: str, - dst: str, - preserve_mode: int = ..., - preserve_times: int = ..., - preserve_symlinks: int = ..., - update: int = ..., - verbose: int = ..., - dry_run: int = ..., -) -> List[str]: ... -def remove_tree(directory: str, verbose: int = ..., dry_run: int = ...) -> None: ... diff --git a/stdlib/@python2/distutils/dist.pyi b/stdlib/@python2/distutils/dist.pyi deleted file mode 100644 index adba8f093569..000000000000 --- a/stdlib/@python2/distutils/dist.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from distutils.cmd import Command -from typing import Any, Dict, Iterable, Mapping, Text, Tuple, Type - -class Distribution: - cmdclass: Dict[str, Type[Command]] - def __init__(self, attrs: Mapping[str, Any] | None = ...) -> None: ... - def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... - def parse_config_files(self, filenames: Iterable[Text] | None = ...) -> None: ... - def get_command_obj(self, command: str, create: bool = ...) -> Command | None: ... diff --git a/stdlib/@python2/distutils/emxccompiler.pyi b/stdlib/@python2/distutils/emxccompiler.pyi deleted file mode 100644 index 19e4023fef04..000000000000 --- a/stdlib/@python2/distutils/emxccompiler.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from distutils.unixccompiler import UnixCCompiler - -class EMXCCompiler(UnixCCompiler): ... diff --git a/stdlib/@python2/distutils/errors.pyi b/stdlib/@python2/distutils/errors.pyi deleted file mode 100644 index e483362bfbf1..000000000000 --- a/stdlib/@python2/distutils/errors.pyi +++ /dev/null @@ -1,19 +0,0 @@ -class DistutilsError(Exception): ... -class DistutilsModuleError(DistutilsError): ... -class DistutilsClassError(DistutilsError): ... -class DistutilsGetoptError(DistutilsError): ... -class DistutilsArgError(DistutilsError): ... -class DistutilsFileError(DistutilsError): ... -class DistutilsOptionError(DistutilsError): ... -class DistutilsSetupError(DistutilsError): ... -class DistutilsPlatformError(DistutilsError): ... -class DistutilsExecError(DistutilsError): ... -class DistutilsInternalError(DistutilsError): ... -class DistutilsTemplateError(DistutilsError): ... -class DistutilsByteCompileError(DistutilsError): ... -class CCompilerError(Exception): ... -class PreprocessError(CCompilerError): ... -class CompileError(CCompilerError): ... -class LibError(CCompilerError): ... -class LinkError(CCompilerError): ... -class UnknownFileError(CCompilerError): ... diff --git a/stdlib/@python2/distutils/extension.pyi b/stdlib/@python2/distutils/extension.pyi deleted file mode 100644 index 9335fad86418..000000000000 --- a/stdlib/@python2/distutils/extension.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import List, Tuple - -class Extension: - def __init__( - self, - name: str, - sources: List[str], - include_dirs: List[str] = ..., - define_macros: List[Tuple[str, str | None]] = ..., - undef_macros: List[str] = ..., - library_dirs: List[str] = ..., - libraries: List[str] = ..., - runtime_library_dirs: List[str] = ..., - extra_objects: List[str] = ..., - extra_compile_args: List[str] = ..., - extra_link_args: List[str] = ..., - export_symbols: List[str] = ..., - swig_opts: str | None = ..., # undocumented - depends: List[str] = ..., - language: str = ..., - ) -> None: ... diff --git a/stdlib/@python2/distutils/fancy_getopt.pyi b/stdlib/@python2/distutils/fancy_getopt.pyi deleted file mode 100644 index d0e3309c2d77..000000000000 --- a/stdlib/@python2/distutils/fancy_getopt.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any, List, Mapping, Optional, Tuple, overload - -_Option = Tuple[str, Optional[str], str] -_GR = Tuple[List[str], OptionDummy] - -def fancy_getopt( - options: List[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: List[str] | None -) -> List[str] | _GR: ... -def wrap_text(text: str, width: int) -> List[str]: ... - -class FancyGetopt: - def __init__(self, option_table: List[_Option] | None = ...) -> None: ... - # TODO kinda wrong, `getopt(object=object())` is invalid - @overload - def getopt(self, args: List[str] | None = ...) -> _GR: ... - @overload - def getopt(self, args: List[str] | None, object: Any) -> List[str]: ... - def get_option_order(self) -> List[Tuple[str, str]]: ... - def generate_help(self, header: str | None = ...) -> List[str]: ... - -class OptionDummy: ... diff --git a/stdlib/@python2/distutils/file_util.pyi b/stdlib/@python2/distutils/file_util.pyi deleted file mode 100644 index cfe840e71040..000000000000 --- a/stdlib/@python2/distutils/file_util.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Sequence, Tuple - -def copy_file( - src: str, - dst: str, - preserve_mode: bool = ..., - preserve_times: bool = ..., - update: bool = ..., - link: str | None = ..., - verbose: bool = ..., - dry_run: bool = ..., -) -> Tuple[str, str]: ... -def move_file(src: str, dst: str, verbose: bool = ..., dry_run: bool = ...) -> str: ... -def write_file(filename: str, contents: Sequence[str]) -> None: ... diff --git a/stdlib/@python2/distutils/filelist.pyi b/stdlib/@python2/distutils/filelist.pyi deleted file mode 100644 index 8fa55d09d265..000000000000 --- a/stdlib/@python2/distutils/filelist.pyi +++ /dev/null @@ -1 +0,0 @@ -class FileList: ... diff --git a/stdlib/@python2/distutils/log.pyi b/stdlib/@python2/distutils/log.pyi deleted file mode 100644 index 668adaab99d1..000000000000 --- a/stdlib/@python2/distutils/log.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any, Text - -DEBUG: int -INFO: int -WARN: int -ERROR: int -FATAL: int - -class Log: - def __init__(self, threshold: int = ...) -> None: ... - def log(self, level: int, msg: Text, *args: Any) -> None: ... - def debug(self, msg: Text, *args: Any) -> None: ... - def info(self, msg: Text, *args: Any) -> None: ... - def warn(self, msg: Text, *args: Any) -> None: ... - def error(self, msg: Text, *args: Any) -> None: ... - def fatal(self, msg: Text, *args: Any) -> None: ... - -def log(level: int, msg: Text, *args: Any) -> None: ... -def debug(msg: Text, *args: Any) -> None: ... -def info(msg: Text, *args: Any) -> None: ... -def warn(msg: Text, *args: Any) -> None: ... -def error(msg: Text, *args: Any) -> None: ... -def fatal(msg: Text, *args: Any) -> None: ... -def set_threshold(level: int) -> int: ... -def set_verbosity(v: int) -> None: ... diff --git a/stdlib/@python2/distutils/msvccompiler.pyi b/stdlib/@python2/distutils/msvccompiler.pyi deleted file mode 100644 index 80872a6b739f..000000000000 --- a/stdlib/@python2/distutils/msvccompiler.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from distutils.ccompiler import CCompiler - -class MSVCCompiler(CCompiler): ... diff --git a/stdlib/@python2/distutils/spawn.pyi b/stdlib/@python2/distutils/spawn.pyi deleted file mode 100644 index 0fffc5402c62..000000000000 --- a/stdlib/@python2/distutils/spawn.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import List - -def spawn(cmd: List[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... -def find_executable(executable: str, path: str | None = ...) -> str | None: ... diff --git a/stdlib/@python2/distutils/sysconfig.pyi b/stdlib/@python2/distutils/sysconfig.pyi deleted file mode 100644 index 7d9fe7d34de3..000000000000 --- a/stdlib/@python2/distutils/sysconfig.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from distutils.ccompiler import CCompiler -from typing import Mapping - -PREFIX: str -EXEC_PREFIX: str - -def get_config_var(name: str) -> int | str | None: ... -def get_config_vars(*args: str) -> Mapping[str, int | str]: ... -def get_config_h_filename() -> str: ... -def get_makefile_filename() -> str: ... -def get_python_inc(plat_specific: bool = ..., prefix: str | None = ...) -> str: ... -def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., prefix: str | None = ...) -> str: ... -def customize_compiler(compiler: CCompiler) -> None: ... -def set_python_build() -> None: ... diff --git a/stdlib/@python2/distutils/text_file.pyi b/stdlib/@python2/distutils/text_file.pyi deleted file mode 100644 index 26ba5a6fabb6..000000000000 --- a/stdlib/@python2/distutils/text_file.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import IO, List, Tuple - -class TextFile: - def __init__( - self, - filename: str | None = ..., - file: IO[str] | None = ..., - *, - strip_comments: bool = ..., - lstrip_ws: bool = ..., - rstrip_ws: bool = ..., - skip_blanks: bool = ..., - join_lines: bool = ..., - collapse_join: bool = ..., - ) -> None: ... - def open(self, filename: str) -> None: ... - def close(self) -> None: ... - def warn(self, msg: str, line: List[int] | Tuple[int, int] | int = ...) -> None: ... - def readline(self) -> str | None: ... - def readlines(self) -> List[str]: ... - def unreadline(self, line: str) -> str: ... diff --git a/stdlib/@python2/distutils/unixccompiler.pyi b/stdlib/@python2/distutils/unixccompiler.pyi deleted file mode 100644 index e1d443471af3..000000000000 --- a/stdlib/@python2/distutils/unixccompiler.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from distutils.ccompiler import CCompiler - -class UnixCCompiler(CCompiler): ... diff --git a/stdlib/@python2/distutils/util.pyi b/stdlib/@python2/distutils/util.pyi deleted file mode 100644 index c0882d1dd1cb..000000000000 --- a/stdlib/@python2/distutils/util.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Any, Callable, List, Mapping, Tuple - -def get_platform() -> str: ... -def convert_path(pathname: str) -> str: ... -def change_root(new_root: str, pathname: str) -> str: ... -def check_environ() -> None: ... -def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... -def split_quoted(s: str) -> List[str]: ... -def execute( - func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... -) -> None: ... -def strtobool(val: str) -> bool: ... -def byte_compile( - py_files: List[str], - optimize: int = ..., - force: bool = ..., - prefix: str | None = ..., - base_dir: str | None = ..., - verbose: bool = ..., - dry_run: bool = ..., - direct: bool | None = ..., -) -> None: ... -def rfc822_escape(header: str) -> str: ... diff --git a/stdlib/@python2/distutils/version.pyi b/stdlib/@python2/distutils/version.pyi deleted file mode 100644 index dd0969b8635f..000000000000 --- a/stdlib/@python2/distutils/version.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from abc import abstractmethod -from typing import Pattern, Text, Tuple, TypeVar - -_T = TypeVar("_T", bound=Version) - -class Version: - def __repr__(self) -> str: ... - @abstractmethod - def __init__(self, vstring: Text | None = ...) -> None: ... - @abstractmethod - def parse(self: _T, vstring: Text) -> _T: ... - @abstractmethod - def __str__(self) -> str: ... - @abstractmethod - def __cmp__(self: _T, other: _T | str) -> bool: ... - -class StrictVersion(Version): - version_re: Pattern[str] - version: Tuple[int, int, int] - prerelease: Tuple[Text, int] | None - def __init__(self, vstring: Text | None = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... - def __str__(self) -> str: ... - def __cmp__(self: _T, other: _T | str) -> bool: ... - -class LooseVersion(Version): - component_re: Pattern[str] - vstring: Text - version: Tuple[Text | int, ...] - def __init__(self, vstring: Text | None = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... - def __str__(self) -> str: ... - def __cmp__(self: _T, other: _T | str) -> bool: ... diff --git a/stdlib/@python2/doctest.pyi b/stdlib/@python2/doctest.pyi deleted file mode 100644 index 6c3b922244f4..000000000000 --- a/stdlib/@python2/doctest.pyi +++ /dev/null @@ -1,209 +0,0 @@ -import types -import unittest -from typing import Any, Callable, Dict, List, NamedTuple, Tuple, Type - -class TestResults(NamedTuple): - failed: int - attempted: int - -OPTIONFLAGS_BY_NAME: Dict[str, int] - -def register_optionflag(name: str) -> int: ... - -DONT_ACCEPT_TRUE_FOR_1: int -DONT_ACCEPT_BLANKLINE: int -NORMALIZE_WHITESPACE: int -ELLIPSIS: int -SKIP: int -IGNORE_EXCEPTION_DETAIL: int - -COMPARISON_FLAGS: int - -REPORT_UDIFF: int -REPORT_CDIFF: int -REPORT_NDIFF: int -REPORT_ONLY_FIRST_FAILURE: int -REPORTING_FLAGS: int - -BLANKLINE_MARKER: str -ELLIPSIS_MARKER: str - -class Example: - source: str - want: str - exc_msg: str | None - lineno: int - indent: int - options: Dict[int, bool] - def __init__( - self, - source: str, - want: str, - exc_msg: str | None = ..., - lineno: int = ..., - indent: int = ..., - options: Dict[int, bool] | None = ..., - ) -> None: ... - def __hash__(self) -> int: ... - -class DocTest: - examples: List[Example] - globs: Dict[str, Any] - name: str - filename: str | None - lineno: int | None - docstring: str | None - def __init__( - self, - examples: List[Example], - globs: Dict[str, Any], - name: str, - filename: str | None, - lineno: int | None, - docstring: str | None, - ) -> None: ... - def __hash__(self) -> int: ... - def __lt__(self, other: DocTest) -> bool: ... - -class DocTestParser: - def parse(self, string: str, name: str = ...) -> List[str | Example]: ... - def get_doctest(self, string: str, globs: Dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... - def get_examples(self, string: str, name: str = ...) -> List[Example]: ... - -class DocTestFinder: - def __init__( - self, verbose: bool = ..., parser: DocTestParser = ..., recurse: bool = ..., exclude_empty: bool = ... - ) -> None: ... - def find( - self, - obj: object, - name: str | None = ..., - module: None | bool | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - extraglobs: Dict[str, Any] | None = ..., - ) -> List[DocTest]: ... - -_Out = Callable[[str], Any] -_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] - -class DocTestRunner: - DIVIDER: str - optionflags: int - original_optionflags: int - tries: int - failures: int - test: DocTest - def __init__(self, checker: OutputChecker | None = ..., verbose: bool | None = ..., optionflags: int = ...) -> None: ... - def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ... - def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... - def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... - def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... - def run( - self, test: DocTest, compileflags: int | None = ..., out: _Out | None = ..., clear_globs: bool = ... - ) -> TestResults: ... - def summarize(self, verbose: bool | None = ...) -> TestResults: ... - def merge(self, other: DocTestRunner) -> None: ... - -class OutputChecker: - def check_output(self, want: str, got: str, optionflags: int) -> bool: ... - def output_difference(self, example: Example, got: str, optionflags: int) -> str: ... - -class DocTestFailure(Exception): - test: DocTest - example: Example - got: str - def __init__(self, test: DocTest, example: Example, got: str) -> None: ... - -class UnexpectedException(Exception): - test: DocTest - example: Example - exc_info: _ExcInfo - def __init__(self, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... - -class DebugRunner(DocTestRunner): ... - -master: DocTestRunner | None - -def testmod( - m: types.ModuleType | None = ..., - name: str | None = ..., - globs: Dict[str, Any] | None = ..., - verbose: bool | None = ..., - report: bool = ..., - optionflags: int = ..., - extraglobs: Dict[str, Any] | None = ..., - raise_on_error: bool = ..., - exclude_empty: bool = ..., -) -> TestResults: ... -def testfile( - filename: str, - module_relative: bool = ..., - name: str | None = ..., - package: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - verbose: bool | None = ..., - report: bool = ..., - optionflags: int = ..., - extraglobs: Dict[str, Any] | None = ..., - raise_on_error: bool = ..., - parser: DocTestParser = ..., - encoding: str | None = ..., -) -> TestResults: ... -def run_docstring_examples( - f: object, globs: Dict[str, Any], verbose: bool = ..., name: str = ..., compileflags: int | None = ..., optionflags: int = ... -) -> None: ... -def set_unittest_reportflags(flags: int) -> int: ... - -class DocTestCase(unittest.TestCase): - def __init__( - self, - test: DocTest, - optionflags: int = ..., - setUp: Callable[[DocTest], Any] | None = ..., - tearDown: Callable[[DocTest], Any] | None = ..., - checker: OutputChecker | None = ..., - ) -> None: ... - def setUp(self) -> None: ... - def tearDown(self) -> None: ... - def runTest(self) -> None: ... - def format_failure(self, err: str) -> str: ... - def debug(self) -> None: ... - def id(self) -> str: ... - def __hash__(self) -> int: ... - def shortDescription(self) -> str: ... - -class SkipDocTestCase(DocTestCase): - def __init__(self, module: types.ModuleType) -> None: ... - def setUp(self) -> None: ... - def test_skip(self) -> None: ... - def shortDescription(self) -> str: ... - -_DocTestSuite = unittest.TestSuite - -def DocTestSuite( - module: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - extraglobs: Dict[str, Any] | None = ..., - test_finder: DocTestFinder | None = ..., - **options: Any, -) -> _DocTestSuite: ... - -class DocFileCase(DocTestCase): - def id(self) -> str: ... - def format_failure(self, err: str) -> str: ... - -def DocFileTest( - path: str, - module_relative: bool = ..., - package: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - parser: DocTestParser = ..., - encoding: str | None = ..., - **options: Any, -) -> DocFileCase: ... -def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... -def script_from_examples(s: str) -> str: ... -def testsource(module: None | str | types.ModuleType, name: str) -> str: ... -def debug_src(src: str, pm: bool = ..., globs: Dict[str, Any] | None = ...) -> None: ... -def debug_script(src: str, pm: bool = ..., globs: Dict[str, Any] | None = ...) -> None: ... -def debug(module: None | str | types.ModuleType, name: str, pm: bool = ...) -> None: ... diff --git a/stdlib/@python2/dummy_thread.pyi b/stdlib/@python2/dummy_thread.pyi deleted file mode 100644 index 0a28b3aaeeb9..000000000000 --- a/stdlib/@python2/dummy_thread.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any, Callable, Dict, NoReturn, Tuple - -class error(Exception): - def __init__(self, *args: Any) -> None: ... - -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... -def exit() -> NoReturn: ... -def get_ident() -> int: ... -def allocate_lock() -> LockType: ... -def stack_size(size: int | None = ...) -> int: ... - -class LockType(object): - locked_status: bool - def __init__(self) -> None: ... - def acquire(self, waitflag: bool | None = ...) -> bool: ... - def __enter__(self, waitflag: bool | None = ...) -> bool: ... - def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... - def release(self) -> bool: ... - def locked(self) -> bool: ... - -def interrupt_main() -> None: ... diff --git a/stdlib/@python2/dummy_threading.pyi b/stdlib/@python2/dummy_threading.pyi deleted file mode 100644 index 757cb8d4bd4c..000000000000 --- a/stdlib/@python2/dummy_threading.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from _dummy_threading import * -from _dummy_threading import __all__ as __all__ diff --git a/stdlib/@python2/email/MIMEText.pyi b/stdlib/@python2/email/MIMEText.pyi deleted file mode 100644 index 3b059778aa66..000000000000 --- a/stdlib/@python2/email/MIMEText.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEText(MIMENonMultipart): - def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/stdlib/@python2/email/__init__.pyi b/stdlib/@python2/email/__init__.pyi deleted file mode 100644 index 83d9895cab4d..000000000000 --- a/stdlib/@python2/email/__init__.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import IO, AnyStr - -def message_from_string(s: AnyStr, *args, **kwargs): ... -def message_from_bytes(s: str, *args, **kwargs): ... -def message_from_file(fp: IO[AnyStr], *args, **kwargs): ... -def message_from_binary_file(fp: IO[str], *args, **kwargs): ... diff --git a/stdlib/@python2/email/_parseaddr.pyi b/stdlib/@python2/email/_parseaddr.pyi deleted file mode 100644 index 74ea3a6e4a69..000000000000 --- a/stdlib/@python2/email/_parseaddr.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Any - -def parsedate_tz(data): ... -def parsedate(data): ... -def mktime_tz(data): ... -def quote(str): ... - -class AddrlistClass: - specials: Any - pos: Any - LWS: Any - CR: Any - FWS: Any - atomends: Any - phraseends: Any - field: Any - commentlist: Any - def __init__(self, field): ... - def gotonext(self): ... - def getaddrlist(self): ... - def getaddress(self): ... - def getrouteaddr(self): ... - def getaddrspec(self): ... - def getdomain(self): ... - def getdelimited(self, beginchar, endchars, allowcomments: bool = ...): ... - def getquote(self): ... - def getcomment(self): ... - def getdomainliteral(self): ... - def getatom(self, atomends: Any | None = ...): ... - def getphraselist(self): ... - -class AddressList(AddrlistClass): - addresslist: Any - def __init__(self, field): ... - def __len__(self): ... - def __add__(self, other): ... - def __iadd__(self, other): ... - def __sub__(self, other): ... - def __isub__(self, other): ... - def __getitem__(self, index): ... diff --git a/stdlib/@python2/email/base64mime.pyi b/stdlib/@python2/email/base64mime.pyi deleted file mode 100644 index fc6552974e60..000000000000 --- a/stdlib/@python2/email/base64mime.pyi +++ /dev/null @@ -1,11 +0,0 @@ -def base64_len(s: bytes) -> int: ... -def header_encode(header, charset=..., keep_eols=..., maxlinelen=..., eol=...): ... -def encode(s, binary=..., maxlinelen=..., eol=...): ... - -body_encode = encode -encodestring = encode - -def decode(s, convert_eols=...): ... - -body_decode = decode -decodestring = decode diff --git a/stdlib/@python2/email/charset.pyi b/stdlib/@python2/email/charset.pyi deleted file mode 100644 index 88b5f88d1843..000000000000 --- a/stdlib/@python2/email/charset.pyi +++ /dev/null @@ -1,26 +0,0 @@ -def add_charset(charset, header_enc=..., body_enc=..., output_charset=...) -> None: ... -def add_alias(alias, canonical) -> None: ... -def add_codec(charset, codecname) -> None: ... - -QP: int # undocumented -BASE64: int # undocumented -SHORTEST: int # undocumented - -class Charset: - input_charset = ... - header_encoding = ... - body_encoding = ... - output_charset = ... - input_codec = ... - output_codec = ... - def __init__(self, input_charset=...) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def get_body_encoding(self): ... - def convert(self, s): ... - def to_splittable(self, s): ... - def from_splittable(self, ustr, to_output: bool = ...): ... - def get_output_charset(self): ... - def encoded_header_len(self, s): ... - def header_encode(self, s, convert: bool = ...): ... - def body_encode(self, s, convert: bool = ...): ... diff --git a/stdlib/@python2/email/encoders.pyi b/stdlib/@python2/email/encoders.pyi deleted file mode 100644 index 5670cbaf08ed..000000000000 --- a/stdlib/@python2/email/encoders.pyi +++ /dev/null @@ -1,4 +0,0 @@ -def encode_base64(msg) -> None: ... -def encode_quopri(msg) -> None: ... -def encode_7or8bit(msg) -> None: ... -def encode_noop(msg) -> None: ... diff --git a/stdlib/@python2/email/feedparser.pyi b/stdlib/@python2/email/feedparser.pyi deleted file mode 100644 index fb2aa9f5ff1b..000000000000 --- a/stdlib/@python2/email/feedparser.pyi +++ /dev/null @@ -1,17 +0,0 @@ -class BufferedSubFile: - def __init__(self) -> None: ... - def push_eof_matcher(self, pred) -> None: ... - def pop_eof_matcher(self): ... - def close(self) -> None: ... - def readline(self): ... - def unreadline(self, line) -> None: ... - def push(self, data): ... - def pushlines(self, lines) -> None: ... - def is_closed(self): ... - def __iter__(self): ... - def next(self): ... - -class FeedParser: - def __init__(self, _factory=...) -> None: ... - def feed(self, data) -> None: ... - def close(self): ... diff --git a/stdlib/@python2/email/generator.pyi b/stdlib/@python2/email/generator.pyi deleted file mode 100644 index a5f5983b48e6..000000000000 --- a/stdlib/@python2/email/generator.pyi +++ /dev/null @@ -1,8 +0,0 @@ -class Generator: - def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ...) -> None: ... - def write(self, s) -> None: ... - def flatten(self, msg, unixfrom: bool = ...) -> None: ... - def clone(self, fp): ... - -class DecodedGenerator(Generator): - def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ..., fmt=...) -> None: ... diff --git a/stdlib/@python2/email/header.pyi b/stdlib/@python2/email/header.pyi deleted file mode 100644 index 429ee16d8917..000000000000 --- a/stdlib/@python2/email/header.pyi +++ /dev/null @@ -1,10 +0,0 @@ -def decode_header(header): ... -def make_header(decoded_seq, maxlinelen=..., header_name=..., continuation_ws=...): ... - -class Header: - def __init__(self, s=..., charset=..., maxlinelen=..., header_name=..., continuation_ws=..., errors=...) -> None: ... - def __unicode__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def append(self, s, charset=..., errors=...) -> None: ... - def encode(self, splitchars=...): ... diff --git a/stdlib/@python2/email/iterators.pyi b/stdlib/@python2/email/iterators.pyi deleted file mode 100644 index 5002644117a4..000000000000 --- a/stdlib/@python2/email/iterators.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any, Generator - -def walk(self) -> Generator[Any, Any, Any]: ... -def body_line_iterator(msg, decode: bool = ...) -> Generator[Any, Any, Any]: ... -def typed_subpart_iterator(msg, maintype=..., subtype=...) -> Generator[Any, Any, Any]: ... diff --git a/stdlib/@python2/email/message.pyi b/stdlib/@python2/email/message.pyi deleted file mode 100644 index 642bba7c0102..000000000000 --- a/stdlib/@python2/email/message.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Any, Generator - -class Message: - preamble = ... - epilogue = ... - defects = ... - def __init__(self): ... - def as_string(self, unixfrom=...): ... - def is_multipart(self) -> bool: ... - def set_unixfrom(self, unixfrom) -> None: ... - def get_unixfrom(self): ... - def attach(self, payload) -> None: ... - def get_payload(self, i=..., decode: bool = ...): ... - def set_payload(self, payload, charset=...) -> None: ... - def set_charset(self, charset): ... - def get_charset(self): ... - def __len__(self): ... - def __getitem__(self, name): ... - def __setitem__(self, name, val) -> None: ... - def __delitem__(self, name) -> None: ... - def __contains__(self, name): ... - def has_key(self, name) -> bool: ... - def keys(self): ... - def values(self): ... - def items(self): ... - def get(self, name, failobj=...): ... - def get_all(self, name, failobj=...): ... - def add_header(self, _name, _value, **_params) -> None: ... - def replace_header(self, _name, _value) -> None: ... - def get_content_type(self): ... - def get_content_maintype(self): ... - def get_content_subtype(self): ... - def get_default_type(self): ... - def set_default_type(self, ctype) -> None: ... - def get_params(self, failobj=..., header=..., unquote: bool = ...): ... - def get_param(self, param, failobj=..., header=..., unquote: bool = ...): ... - def set_param(self, param, value, header=..., requote: bool = ..., charset=..., language=...) -> None: ... - def del_param(self, param, header=..., requote: bool = ...): ... - def set_type(self, type, header=..., requote: bool = ...): ... - def get_filename(self, failobj=...): ... - def get_boundary(self, failobj=...): ... - def set_boundary(self, boundary) -> None: ... - def get_content_charset(self, failobj=...): ... - def get_charsets(self, failobj=...): ... - def walk(self) -> Generator[Any, Any, Any]: ... diff --git a/stdlib/@python2/email/mime/application.pyi b/stdlib/@python2/email/mime/application.pyi deleted file mode 100644 index 4245e3e0f980..000000000000 --- a/stdlib/@python2/email/mime/application.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart -from typing import Callable, Optional, Tuple, Union - -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] - -class MIMEApplication(MIMENonMultipart): - def __init__( - self, _data: bytes, _subtype: str = ..., _encoder: Callable[[MIMEApplication], None] = ..., **_params: _ParamsType - ) -> None: ... diff --git a/stdlib/@python2/email/mime/audio.pyi b/stdlib/@python2/email/mime/audio.pyi deleted file mode 100644 index 5f11f8d79008..000000000000 --- a/stdlib/@python2/email/mime/audio.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEAudio(MIMENonMultipart): - def __init__(self, _audiodata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/stdlib/@python2/email/mime/base.pyi b/stdlib/@python2/email/mime/base.pyi deleted file mode 100644 index 4bde4f073395..000000000000 --- a/stdlib/@python2/email/mime/base.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email import message - -class MIMEBase(message.Message): - def __init__(self, _maintype, _subtype, **_params) -> None: ... diff --git a/stdlib/@python2/email/mime/image.pyi b/stdlib/@python2/email/mime/image.pyi deleted file mode 100644 index 3fe8249d6ac8..000000000000 --- a/stdlib/@python2/email/mime/image.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEImage(MIMENonMultipart): - def __init__(self, _imagedata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/stdlib/@python2/email/mime/message.pyi b/stdlib/@python2/email/mime/message.pyi deleted file mode 100644 index 9d6fafa2a19b..000000000000 --- a/stdlib/@python2/email/mime/message.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEMessage(MIMENonMultipart): - def __init__(self, _msg, _subtype=...) -> None: ... diff --git a/stdlib/@python2/email/mime/multipart.pyi b/stdlib/@python2/email/mime/multipart.pyi deleted file mode 100644 index 0a7d3fa8acb0..000000000000 --- a/stdlib/@python2/email/mime/multipart.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.base import MIMEBase - -class MIMEMultipart(MIMEBase): - def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ... diff --git a/stdlib/@python2/email/mime/nonmultipart.pyi b/stdlib/@python2/email/mime/nonmultipart.pyi deleted file mode 100644 index 04d130e3da88..000000000000 --- a/stdlib/@python2/email/mime/nonmultipart.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.base import MIMEBase - -class MIMENonMultipart(MIMEBase): - def attach(self, payload): ... diff --git a/stdlib/@python2/email/mime/text.pyi b/stdlib/@python2/email/mime/text.pyi deleted file mode 100644 index 3b059778aa66..000000000000 --- a/stdlib/@python2/email/mime/text.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEText(MIMENonMultipart): - def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/stdlib/@python2/email/parser.pyi b/stdlib/@python2/email/parser.pyi deleted file mode 100644 index 4f2282834ca5..000000000000 --- a/stdlib/@python2/email/parser.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from .feedparser import FeedParser as FeedParser # not in __all__ but listed in documentation - -class Parser: - def __init__(self, *args, **kws) -> None: ... - def parse(self, fp, headersonly: bool = ...): ... - def parsestr(self, text, headersonly: bool = ...): ... - -class HeaderParser(Parser): - def parse(self, fp, headersonly: bool = ...): ... - def parsestr(self, text, headersonly: bool = ...): ... diff --git a/stdlib/@python2/email/quoprimime.pyi b/stdlib/@python2/email/quoprimime.pyi deleted file mode 100644 index 3f2963c06e6d..000000000000 --- a/stdlib/@python2/email/quoprimime.pyi +++ /dev/null @@ -1,18 +0,0 @@ -def header_quopri_check(c): ... -def body_quopri_check(c): ... -def header_quopri_len(s): ... -def body_quopri_len(str): ... -def unquote(s): ... -def quote(c): ... -def header_encode(header, charset: str = ..., keep_eols: bool = ..., maxlinelen: int = ..., eol=...): ... -def encode(body, binary: bool = ..., maxlinelen: int = ..., eol=...): ... - -body_encode = encode -encodestring = encode - -def decode(encoded, eol=...): ... - -body_decode = decode -decodestring = decode - -def header_decode(s): ... diff --git a/stdlib/@python2/email/utils.pyi b/stdlib/@python2/email/utils.pyi deleted file mode 100644 index 0d185134c9d7..000000000000 --- a/stdlib/@python2/email/utils.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from email._parseaddr import ( - AddressList as _AddressList, - mktime_tz as mktime_tz, - parsedate as _parsedate, - parsedate_tz as _parsedate_tz, -) -from quopri import decodestring as _qdecode -from typing import Any - -def formataddr(pair): ... -def getaddresses(fieldvalues): ... -def formatdate(timeval: Any | None = ..., localtime: bool = ..., usegmt: bool = ...): ... -def make_msgid(idstring: Any | None = ...): ... -def parsedate(data): ... -def parsedate_tz(data): ... -def parseaddr(addr): ... -def unquote(str): ... -def decode_rfc2231(s): ... -def encode_rfc2231(s, charset: Any | None = ..., language: Any | None = ...): ... -def decode_params(params): ... -def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ... diff --git a/stdlib/@python2/encodings/__init__.pyi b/stdlib/@python2/encodings/__init__.pyi deleted file mode 100644 index d6f4389bc820..000000000000 --- a/stdlib/@python2/encodings/__init__.pyi +++ /dev/null @@ -1,7 +0,0 @@ -import codecs -from typing import Any - -def search_function(encoding: str) -> codecs.CodecInfo: ... - -# Explicitly mark this package as incomplete. -def __getattr__(name: str) -> Any: ... diff --git a/stdlib/@python2/encodings/utf_8.pyi b/stdlib/@python2/encodings/utf_8.pyi deleted file mode 100644 index d38bd58d0e43..000000000000 --- a/stdlib/@python2/encodings/utf_8.pyi +++ /dev/null @@ -1,15 +0,0 @@ -import codecs -from typing import Text, Tuple - -class IncrementalEncoder(codecs.IncrementalEncoder): - def encode(self, input: Text, final: bool = ...) -> bytes: ... - -class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... - -class StreamWriter(codecs.StreamWriter): ... -class StreamReader(codecs.StreamReader): ... - -def getregentry() -> codecs.CodecInfo: ... -def encode(input: Text, errors: Text = ...) -> bytes: ... -def decode(input: bytes, errors: Text = ...) -> Text: ... diff --git a/stdlib/@python2/ensurepip/__init__.pyi b/stdlib/@python2/ensurepip/__init__.pyi deleted file mode 100644 index 60946e7cf35a..000000000000 --- a/stdlib/@python2/ensurepip/__init__.pyi +++ /dev/null @@ -1,9 +0,0 @@ -def version() -> str: ... -def bootstrap( - root: str | None = ..., - upgrade: bool = ..., - user: bool = ..., - altinstall: bool = ..., - default_pip: bool = ..., - verbosity: int = ..., -) -> None: ... diff --git a/stdlib/@python2/errno.pyi b/stdlib/@python2/errno.pyi deleted file mode 100644 index b053604fc33a..000000000000 --- a/stdlib/@python2/errno.pyi +++ /dev/null @@ -1,137 +0,0 @@ -from typing import Mapping - -errorcode: Mapping[int, str] - -EPERM: int -ENOENT: int -ESRCH: int -EINTR: int -EIO: int -ENXIO: int -E2BIG: int -ENOEXEC: int -EBADF: int -ECHILD: int -EAGAIN: int -ENOMEM: int -EACCES: int -EFAULT: int -ENOTBLK: int -EBUSY: int -EEXIST: int -EXDEV: int -ENODEV: int -ENOTDIR: int -EISDIR: int -EINVAL: int -ENFILE: int -EMFILE: int -ENOTTY: int -ETXTBSY: int -EFBIG: int -ENOSPC: int -ESPIPE: int -EROFS: int -EMLINK: int -EPIPE: int -EDOM: int -ERANGE: int -EDEADLCK: int -ENAMETOOLONG: int -ENOLCK: int -ENOSYS: int -ENOTEMPTY: int -ELOOP: int -EWOULDBLOCK: int -ENOMSG: int -EIDRM: int -ECHRNG: int -EL2NSYNC: int -EL3HLT: int -EL3RST: int -ELNRNG: int -EUNATCH: int -ENOCSI: int -EL2HLT: int -EBADE: int -EBADR: int -EXFULL: int -ENOANO: int -EBADRQC: int -EBADSLT: int -EDEADLOCK: int -EBFONT: int -ENOSTR: int -ENODATA: int -ETIME: int -ENOSR: int -ENONET: int -ENOPKG: int -EREMOTE: int -ENOLINK: int -EADV: int -ESRMNT: int -ECOMM: int -EPROTO: int -EMULTIHOP: int -EDOTDOT: int -EBADMSG: int -EOVERFLOW: int -ENOTUNIQ: int -EBADFD: int -EREMCHG: int -ELIBACC: int -ELIBBAD: int -ELIBSCN: int -ELIBMAX: int -ELIBEXEC: int -EILSEQ: int -ERESTART: int -ESTRPIPE: int -EUSERS: int -ENOTSOCK: int -EDESTADDRREQ: int -EMSGSIZE: int -EPROTOTYPE: int -ENOPROTOOPT: int -EPROTONOSUPPORT: int -ESOCKTNOSUPPORT: int -ENOTSUP: int -EOPNOTSUPP: int -EPFNOSUPPORT: int -EAFNOSUPPORT: int -EADDRINUSE: int -EADDRNOTAVAIL: int -ENETDOWN: int -ENETUNREACH: int -ENETRESET: int -ECONNABORTED: int -ECONNRESET: int -ENOBUFS: int -EISCONN: int -ENOTCONN: int -ESHUTDOWN: int -ETOOMANYREFS: int -ETIMEDOUT: int -ECONNREFUSED: int -EHOSTDOWN: int -EHOSTUNREACH: int -EALREADY: int -EINPROGRESS: int -ESTALE: int -EUCLEAN: int -ENOTNAM: int -ENAVAIL: int -EISNAM: int -EREMOTEIO: int -EDQUOT: int -ECANCELED: int # undocumented -EKEYEXPIRED: int # undocumented -EKEYREJECTED: int # undocumented -EKEYREVOKED: int # undocumented -EMEDIUMTYPE: int # undocumented -ENOKEY: int # undocumented -ENOMEDIUM: int # undocumented -ENOTRECOVERABLE: int # undocumented -EOWNERDEAD: int # undocumented -ERFKILL: int # undocumented diff --git a/stdlib/@python2/exceptions.pyi b/stdlib/@python2/exceptions.pyi deleted file mode 100644 index fbad89750731..000000000000 --- a/stdlib/@python2/exceptions.pyi +++ /dev/null @@ -1,50 +0,0 @@ -from __builtin__ import ( - ArithmeticError as ArithmeticError, - AssertionError as AssertionError, - AttributeError as AttributeError, - BaseException as BaseException, - BufferError as BufferError, - BytesWarning as BytesWarning, - DeprecationWarning as DeprecationWarning, - EnvironmentError as EnvironmentError, - EOFError as EOFError, - Exception as Exception, - FloatingPointError as FloatingPointError, - FutureWarning as FutureWarning, - GeneratorExit as GeneratorExit, - ImportError as ImportError, - ImportWarning as ImportWarning, - IndentationError as IndentationError, - IndexError as IndexError, - IOError as IOError, - KeyboardInterrupt as KeyboardInterrupt, - KeyError as KeyError, - LookupError as LookupError, - MemoryError as MemoryError, - NameError as NameError, - NotImplementedError as NotImplementedError, - OSError as OSError, - OverflowError as OverflowError, - PendingDeprecationWarning as PendingDeprecationWarning, - ReferenceError as ReferenceError, - RuntimeError as RuntimeError, - RuntimeWarning as RuntimeWarning, - StandardError as StandardError, - StopIteration as StopIteration, - SyntaxError as SyntaxError, - SyntaxWarning as SyntaxWarning, - SystemError as SystemError, - SystemExit as SystemExit, - TabError as TabError, - TypeError as TypeError, - UnboundLocalError as UnboundLocalError, - UnicodeDecodeError as UnicodeDecodeError, - UnicodeEncodeError as UnicodeEncodeError, - UnicodeError as UnicodeError, - UnicodeTranslateError as UnicodeTranslateError, - UnicodeWarning as UnicodeWarning, - UserWarning as UserWarning, - ValueError as ValueError, - Warning as Warning, - ZeroDivisionError as ZeroDivisionError, -) diff --git a/stdlib/@python2/fcntl.pyi b/stdlib/@python2/fcntl.pyi deleted file mode 100644 index b3730270f1cc..000000000000 --- a/stdlib/@python2/fcntl.pyi +++ /dev/null @@ -1,82 +0,0 @@ -from _typeshed import FileDescriptorLike -from typing import Any - -FASYNC: int -FD_CLOEXEC: int - -DN_ACCESS: int -DN_ATTRIB: int -DN_CREATE: int -DN_DELETE: int -DN_MODIFY: int -DN_MULTISHOT: int -DN_RENAME: int -F_DUPFD: int -F_EXLCK: int -F_GETFD: int -F_GETFL: int -F_GETLEASE: int -F_GETLK: int -F_GETLK64: int -F_GETOWN: int -F_GETSIG: int -F_NOTIFY: int -F_RDLCK: int -F_SETFD: int -F_SETFL: int -F_SETLEASE: int -F_SETLK: int -F_SETLK64: int -F_SETLKW: int -F_SETLKW64: int -F_SETOWN: int -F_SETSIG: int -F_SHLCK: int -F_UNLCK: int -F_WRLCK: int -I_ATMARK: int -I_CANPUT: int -I_CKBAND: int -I_FDINSERT: int -I_FIND: int -I_FLUSH: int -I_FLUSHBAND: int -I_GETBAND: int -I_GETCLTIME: int -I_GETSIG: int -I_GRDOPT: int -I_GWROPT: int -I_LINK: int -I_LIST: int -I_LOOK: int -I_NREAD: int -I_PEEK: int -I_PLINK: int -I_POP: int -I_PUNLINK: int -I_PUSH: int -I_RECVFD: int -I_SENDFD: int -I_SETCLTIME: int -I_SETSIG: int -I_SRDOPT: int -I_STR: int -I_SWROPT: int -I_UNLINK: int -LOCK_EX: int -LOCK_MAND: int -LOCK_NB: int -LOCK_READ: int -LOCK_RW: int -LOCK_SH: int -LOCK_UN: int -LOCK_WRITE: int - -# TODO All these return either int or bytes depending on the value of -# cmd (not on the type of arg). -def fcntl(fd: FileDescriptorLike, op: int, arg: int | bytes = ...) -> Any: ... - -# TODO: arg: int or read-only buffer interface or read-write buffer interface -def ioctl(fd: FileDescriptorLike, op: int, arg: int | bytes = ..., mutate_flag: bool = ...) -> Any: ... -def flock(fd: FileDescriptorLike, op: int) -> None: ... -def lockf(fd: FileDescriptorLike, op: int, length: int = ..., start: int = ..., whence: int = ...) -> Any: ... diff --git a/stdlib/@python2/filecmp.pyi b/stdlib/@python2/filecmp.pyi deleted file mode 100644 index 0be5596c2bdb..000000000000 --- a/stdlib/@python2/filecmp.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Sequence, Text, Tuple - -DEFAULT_IGNORES: List[str] - -def cmp(f1: bytes | Text, f2: bytes | Text, shallow: int | bool = ...) -> bool: ... -def cmpfiles( - a: AnyStr, b: AnyStr, common: Iterable[AnyStr], shallow: int | bool = ... -) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... - -class dircmp(Generic[AnyStr]): - def __init__( - self, a: AnyStr, b: AnyStr, ignore: Sequence[AnyStr] | None = ..., hide: Sequence[AnyStr] | None = ... - ) -> None: ... - left: AnyStr - right: AnyStr - hide: Sequence[AnyStr] - ignore: Sequence[AnyStr] - # These properties are created at runtime by __getattr__ - subdirs: Dict[AnyStr, dircmp[AnyStr]] - same_files: List[AnyStr] - diff_files: List[AnyStr] - funny_files: List[AnyStr] - common_dirs: List[AnyStr] - common_files: List[AnyStr] - common_funny: List[AnyStr] - common: List[AnyStr] - left_only: List[AnyStr] - right_only: List[AnyStr] - left_list: List[AnyStr] - right_list: List[AnyStr] - def report(self) -> None: ... - def report_partial_closure(self) -> None: ... - def report_full_closure(self) -> None: ... - methodmap: Dict[str, Callable[[], None]] - def phase0(self) -> None: ... - def phase1(self) -> None: ... - def phase2(self) -> None: ... - def phase3(self) -> None: ... - def phase4(self) -> None: ... - def phase4_closure(self) -> None: ... diff --git a/stdlib/@python2/fileinput.pyi b/stdlib/@python2/fileinput.pyi deleted file mode 100644 index 316643fcf15f..000000000000 --- a/stdlib/@python2/fileinput.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Text - -def input( - files: Text | Iterable[Text] | None = ..., - inplace: bool = ..., - backup: str = ..., - bufsize: int = ..., - mode: str = ..., - openhook: Callable[[Text, str], IO[AnyStr]] = ..., -) -> FileInput[AnyStr]: ... -def close() -> None: ... -def nextfile() -> None: ... -def filename() -> str: ... -def lineno() -> int: ... -def filelineno() -> int: ... -def fileno() -> int: ... -def isfirstline() -> bool: ... -def isstdin() -> bool: ... - -class FileInput(Iterable[AnyStr], Generic[AnyStr]): - def __init__( - self, - files: None | Text | Iterable[Text] = ..., - inplace: bool = ..., - backup: str = ..., - bufsize: int = ..., - mode: str = ..., - openhook: Callable[[Text, str], IO[AnyStr]] = ..., - ) -> None: ... - def __del__(self) -> None: ... - def close(self) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... - def __next__(self) -> AnyStr: ... - def __getitem__(self, i: int) -> AnyStr: ... - def nextfile(self) -> None: ... - def readline(self) -> AnyStr: ... - def filename(self) -> str: ... - def lineno(self) -> int: ... - def filelineno(self) -> int: ... - def fileno(self) -> int: ... - def isfirstline(self) -> bool: ... - def isstdin(self) -> bool: ... - -def hook_compressed(filename: Text, mode: str) -> IO[Any]: ... -def hook_encoded(encoding: str) -> Callable[[Text, str], IO[Any]]: ... diff --git a/stdlib/@python2/fnmatch.pyi b/stdlib/@python2/fnmatch.pyi deleted file mode 100644 index e933b7b2cb62..000000000000 --- a/stdlib/@python2/fnmatch.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import AnyStr, Iterable, List, Union - -_EitherStr = Union[str, unicode] - -def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... -def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... -def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> List[AnyStr]: ... -def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/stdlib/@python2/formatter.pyi b/stdlib/@python2/formatter.pyi deleted file mode 100644 index da165f2d55e3..000000000000 --- a/stdlib/@python2/formatter.pyi +++ /dev/null @@ -1,103 +0,0 @@ -from typing import IO, Any, Iterable, List, Tuple - -AS_IS: None -_FontType = Tuple[str, bool, bool, bool] -_StylesType = Tuple[Any, ...] - -class NullFormatter: - writer: NullWriter | None - def __init__(self, writer: NullWriter | None = ...) -> None: ... - def end_paragraph(self, blankline: int) -> None: ... - def add_line_break(self) -> None: ... - def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def add_label_data(self, format: str, counter: int, blankline: int | None = ...) -> None: ... - def add_flowing_data(self, data: str) -> None: ... - def add_literal_data(self, data: str) -> None: ... - def flush_softspace(self) -> None: ... - def push_alignment(self, align: str | None) -> None: ... - def pop_alignment(self) -> None: ... - def push_font(self, x: _FontType) -> None: ... - def pop_font(self) -> None: ... - def push_margin(self, margin: int) -> None: ... - def pop_margin(self) -> None: ... - def set_spacing(self, spacing: str | None) -> None: ... - def push_style(self, *styles: _StylesType) -> None: ... - def pop_style(self, n: int = ...) -> None: ... - def assert_line_data(self, flag: int = ...) -> None: ... - -class AbstractFormatter: - writer: NullWriter - align: str | None - align_stack: List[str | None] - font_stack: List[_FontType] - margin_stack: List[int] - spacing: str | None - style_stack: Any - nospace: int - softspace: int - para_end: int - parskip: int - hard_break: int - have_label: int - def __init__(self, writer: NullWriter) -> None: ... - def end_paragraph(self, blankline: int) -> None: ... - def add_line_break(self) -> None: ... - def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def add_label_data(self, format: str, counter: int, blankline: int | None = ...) -> None: ... - def format_counter(self, format: Iterable[str], counter: int) -> str: ... - def format_letter(self, case: str, counter: int) -> str: ... - def format_roman(self, case: str, counter: int) -> str: ... - def add_flowing_data(self, data: str) -> None: ... - def add_literal_data(self, data: str) -> None: ... - def flush_softspace(self) -> None: ... - def push_alignment(self, align: str | None) -> None: ... - def pop_alignment(self) -> None: ... - def push_font(self, font: _FontType) -> None: ... - def pop_font(self) -> None: ... - def push_margin(self, margin: int) -> None: ... - def pop_margin(self) -> None: ... - def set_spacing(self, spacing: str | None) -> None: ... - def push_style(self, *styles: _StylesType) -> None: ... - def pop_style(self, n: int = ...) -> None: ... - def assert_line_data(self, flag: int = ...) -> None: ... - -class NullWriter: - def __init__(self) -> None: ... - def flush(self) -> None: ... - def new_alignment(self, align: str | None) -> None: ... - def new_font(self, font: _FontType) -> None: ... - def new_margin(self, margin: int, level: int) -> None: ... - def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_label_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - def send_literal_data(self, data: str) -> None: ... - -class AbstractWriter(NullWriter): - def new_alignment(self, align: str | None) -> None: ... - def new_font(self, font: _FontType) -> None: ... - def new_margin(self, margin: int, level: int) -> None: ... - def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_label_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - def send_literal_data(self, data: str) -> None: ... - -class DumbWriter(NullWriter): - file: IO[str] - maxcol: int - def __init__(self, file: IO[str] | None = ..., maxcol: int = ...) -> None: ... - def reset(self) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_literal_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - -def test(file: str | None = ...) -> None: ... diff --git a/stdlib/@python2/fractions.pyi b/stdlib/@python2/fractions.pyi deleted file mode 100644 index 872e20ede688..000000000000 --- a/stdlib/@python2/fractions.pyi +++ /dev/null @@ -1,145 +0,0 @@ -from decimal import Decimal -from numbers import Integral, Rational, Real -from typing import Tuple, Type, TypeVar, Union, overload -from typing_extensions import Literal - -_ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") - -@overload -def gcd(a: int, b: int) -> int: ... -@overload -def gcd(a: Integral, b: int) -> Integral: ... -@overload -def gcd(a: int, b: Integral) -> Integral: ... -@overload -def gcd(a: Integral, b: Integral) -> Integral: ... - -class Fraction(Rational): - @overload - def __new__( - cls: Type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... - @overload - def __new__(cls: Type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... - @classmethod - def from_float(cls, f: float) -> Fraction: ... - @classmethod - def from_decimal(cls, dec: Decimal) -> Fraction: ... - def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... - @property - def numerator(self) -> int: ... - @property - def denominator(self) -> int: ... - @overload - def __add__(self, other: int | Fraction) -> Fraction: ... - @overload - def __add__(self, other: float) -> float: ... - @overload - def __add__(self, other: complex) -> complex: ... - @overload - def __radd__(self, other: int | Fraction) -> Fraction: ... - @overload - def __radd__(self, other: float) -> float: ... - @overload - def __radd__(self, other: complex) -> complex: ... - @overload - def __sub__(self, other: int | Fraction) -> Fraction: ... - @overload - def __sub__(self, other: float) -> float: ... - @overload - def __sub__(self, other: complex) -> complex: ... - @overload - def __rsub__(self, other: int | Fraction) -> Fraction: ... - @overload - def __rsub__(self, other: float) -> float: ... - @overload - def __rsub__(self, other: complex) -> complex: ... - @overload - def __mul__(self, other: int | Fraction) -> Fraction: ... - @overload - def __mul__(self, other: float) -> float: ... - @overload - def __mul__(self, other: complex) -> complex: ... - @overload - def __rmul__(self, other: int | Fraction) -> Fraction: ... - @overload - def __rmul__(self, other: float) -> float: ... - @overload - def __rmul__(self, other: complex) -> complex: ... - @overload - def __truediv__(self, other: int | Fraction) -> Fraction: ... - @overload - def __truediv__(self, other: float) -> float: ... - @overload - def __truediv__(self, other: complex) -> complex: ... - @overload - def __rtruediv__(self, other: int | Fraction) -> Fraction: ... - @overload - def __rtruediv__(self, other: float) -> float: ... - @overload - def __rtruediv__(self, other: complex) -> complex: ... - @overload - def __div__(self, other: int | Fraction) -> Fraction: ... - @overload - def __div__(self, other: float) -> float: ... - @overload - def __div__(self, other: complex) -> complex: ... - @overload - def __rdiv__(self, other: int | Fraction) -> Fraction: ... - @overload - def __rdiv__(self, other: float) -> float: ... - @overload - def __rdiv__(self, other: complex) -> complex: ... - @overload - def __floordiv__(self, other: int | Fraction) -> int: ... - @overload - def __floordiv__(self, other: float) -> float: ... - @overload - def __rfloordiv__(self, other: int | Fraction) -> int: ... - @overload - def __rfloordiv__(self, other: float) -> float: ... - @overload - def __mod__(self, other: int | Fraction) -> Fraction: ... - @overload - def __mod__(self, other: float) -> float: ... - @overload - def __rmod__(self, other: int | Fraction) -> Fraction: ... - @overload - def __rmod__(self, other: float) -> float: ... - @overload - def __divmod__(self, other: int | Fraction) -> Tuple[int, Fraction]: ... - @overload - def __divmod__(self, other: float) -> Tuple[float, Fraction]: ... - @overload - def __rdivmod__(self, other: int | Fraction) -> Tuple[int, Fraction]: ... - @overload - def __rdivmod__(self, other: float) -> Tuple[float, Fraction]: ... - @overload - def __pow__(self, other: int) -> Fraction: ... - @overload - def __pow__(self, other: float | Fraction) -> float: ... - @overload - def __pow__(self, other: complex) -> complex: ... - @overload - def __rpow__(self, other: int | float | Fraction) -> float: ... - @overload - def __rpow__(self, other: complex) -> complex: ... - def __pos__(self) -> Fraction: ... - def __neg__(self) -> Fraction: ... - def __abs__(self) -> Fraction: ... - def __trunc__(self) -> int: ... - def __hash__(self) -> int: ... - def __eq__(self, other: object) -> bool: ... - def __lt__(self, other: _ComparableNum) -> bool: ... - def __gt__(self, other: _ComparableNum) -> bool: ... - def __le__(self, other: _ComparableNum) -> bool: ... - def __ge__(self, other: _ComparableNum) -> bool: ... - def __nonzero__(self) -> bool: ... - # Not actually defined within fractions.py, but provides more useful - # overrides - @property - def real(self) -> Fraction: ... - @property - def imag(self) -> Literal[0]: ... - def conjugate(self) -> Fraction: ... diff --git a/stdlib/@python2/ftplib.pyi b/stdlib/@python2/ftplib.pyi deleted file mode 100644 index 0931a9d171cd..000000000000 --- a/stdlib/@python2/ftplib.pyi +++ /dev/null @@ -1,128 +0,0 @@ -from _typeshed import SupportsRead, SupportsReadline -from socket import socket -from ssl import SSLContext -from typing import Any, BinaryIO, Callable, List, Text, Tuple, Type, TypeVar, Union -from typing_extensions import Literal - -_T = TypeVar("_T") -_IntOrStr = Union[int, Text] - -MSG_OOB: int -FTP_PORT: int -MAXLINE: int -CRLF: str - -class Error(Exception): ... -class error_reply(Error): ... -class error_temp(Error): ... -class error_perm(Error): ... -class error_proto(Error): ... - -all_errors: Tuple[Type[Exception], ...] - -class FTP: - debugging: int - - # Note: This is technically the type that's passed in as the host argument. But to make it easier in Python 2 we - # accept Text but return str. - host: str - - port: int - maxline: int - sock: socket | None - welcome: str | None - passiveserver: int - timeout: int - af: int - lastresp: str - - file: BinaryIO | None - def __init__( - self, host: Text = ..., user: Text = ..., passwd: Text = ..., acct: Text = ..., timeout: float = ... - ) -> None: ... - def connect(self, host: Text = ..., port: int = ..., timeout: float = ...) -> str: ... - def getwelcome(self) -> str: ... - def set_debuglevel(self, level: int) -> None: ... - def debug(self, level: int) -> None: ... - def set_pasv(self, val: bool | int) -> None: ... - def sanitize(self, s: Text) -> str: ... - def putline(self, line: Text) -> None: ... - def putcmd(self, line: Text) -> None: ... - def getline(self) -> str: ... - def getmultiline(self) -> str: ... - def getresp(self) -> str: ... - def voidresp(self) -> str: ... - def abort(self) -> str: ... - def sendcmd(self, cmd: Text) -> str: ... - def voidcmd(self, cmd: Text) -> str: ... - def sendport(self, host: Text, port: int) -> str: ... - def sendeprt(self, host: Text, port: int) -> str: ... - def makeport(self) -> socket: ... - def makepasv(self) -> Tuple[str, int]: ... - def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ...) -> str: ... - # In practice, `rest` rest can actually be anything whose str() is an integer sequence, so to make it simple we allow integers. - def ntransfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> Tuple[socket, int]: ... - def transfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> socket: ... - def retrbinary( - self, cmd: Text, callback: Callable[[bytes], Any], blocksize: int = ..., rest: _IntOrStr | None = ... - ) -> str: ... - def storbinary( - self, - cmd: Text, - fp: SupportsRead[bytes], - blocksize: int = ..., - callback: Callable[[bytes], Any] | None = ..., - rest: _IntOrStr | None = ..., - ) -> str: ... - def retrlines(self, cmd: Text, callback: Callable[[str], Any] | None = ...) -> str: ... - def storlines(self, cmd: Text, fp: SupportsReadline[bytes], callback: Callable[[bytes], Any] | None = ...) -> str: ... - def acct(self, password: Text) -> str: ... - def nlst(self, *args: Text) -> List[str]: ... - # Technically only the last arg can be a Callable but ... - def dir(self, *args: str | Callable[[str], None]) -> None: ... - def rename(self, fromname: Text, toname: Text) -> str: ... - def delete(self, filename: Text) -> str: ... - def cwd(self, dirname: Text) -> str: ... - def size(self, filename: Text) -> int | None: ... - def mkd(self, dirname: Text) -> str: ... - def rmd(self, dirname: Text) -> str: ... - def pwd(self) -> str: ... - def quit(self) -> str: ... - def close(self) -> None: ... - -class FTP_TLS(FTP): - def __init__( - self, - host: Text = ..., - user: Text = ..., - passwd: Text = ..., - acct: Text = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - context: SSLContext | None = ..., - timeout: float = ..., - source_address: Tuple[str, int] | None = ..., - ) -> None: ... - ssl_version: int - keyfile: str | None - certfile: str | None - context: SSLContext - def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ..., secure: bool = ...) -> str: ... - def auth(self) -> str: ... - def prot_p(self) -> str: ... - def prot_c(self) -> str: ... - -class Netrc: - def __init__(self, filename: Text | None = ...) -> None: ... - def get_hosts(self) -> List[str]: ... - def get_account(self, host: Text) -> Tuple[str | None, str | None, str | None]: ... - def get_macros(self) -> List[str]: ... - def get_macro(self, macro: Text) -> Tuple[str, ...]: ... - -def parse150(resp: str) -> int | None: ... # undocumented -def parse227(resp: str) -> Tuple[str, int]: ... # undocumented -def parse229(resp: str, peer: Any) -> Tuple[str, int]: ... # undocumented -def parse257(resp: str) -> str: ... # undocumented -def ftpcp( - source: FTP, sourcename: str, target: FTP, targetname: str = ..., type: Literal["A", "I"] = ... -) -> None: ... # undocumented diff --git a/stdlib/@python2/functools.pyi b/stdlib/@python2/functools.pyi deleted file mode 100644 index dd873708fea4..000000000000 --- a/stdlib/@python2/functools.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Any, Callable, Dict, Generic, Iterable, Sequence, Tuple, Type, TypeVar, overload - -_AnyCallable = Callable[..., Any] - -_T = TypeVar("_T") -_S = TypeVar("_S") - -@overload -def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... -@overload -def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... - -WRAPPER_ASSIGNMENTS: Sequence[str] -WRAPPER_UPDATES: Sequence[str] - -def update_wrapper( - wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ... -) -> _AnyCallable: ... -def wraps( - wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ... -) -> Callable[[_AnyCallable], _AnyCallable]: ... -def total_ordering(cls: Type[_T]) -> Type[_T]: ... -def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... - -class partial(Generic[_T]): - func = ... # Callable[..., _T] - args: Tuple[Any, ...] - keywords: Dict[str, Any] - def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... diff --git a/stdlib/@python2/future_builtins.pyi b/stdlib/@python2/future_builtins.pyi deleted file mode 100644 index 2a06c73cf409..000000000000 --- a/stdlib/@python2/future_builtins.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from itertools import ifilter, imap, izip -from typing import Any - -filter = ifilter -map = imap -zip = izip - -def ascii(obj: Any) -> str: ... -def hex(x: int) -> str: ... -def oct(x: int) -> str: ... diff --git a/stdlib/@python2/gc.pyi b/stdlib/@python2/gc.pyi deleted file mode 100644 index b1fb1acc07d2..000000000000 --- a/stdlib/@python2/gc.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any, List, Tuple - -def enable() -> None: ... -def disable() -> None: ... -def isenabled() -> bool: ... -def collect(generation: int = ...) -> int: ... -def set_debug(flags: int) -> None: ... -def get_debug() -> int: ... -def get_objects() -> List[Any]: ... -def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ...) -> None: ... -def get_count() -> Tuple[int, int, int]: ... -def get_threshold() -> Tuple[int, int, int]: ... -def get_referrers(*objs: Any) -> List[Any]: ... -def get_referents(*objs: Any) -> List[Any]: ... -def is_tracked(obj: Any) -> bool: ... - -garbage: List[Any] - -DEBUG_STATS: int -DEBUG_COLLECTABLE: int -DEBUG_UNCOLLECTABLE: int -DEBUG_INSTANCES: int -DEBUG_OBJECTS: int -DEBUG_SAVEALL: int -DEBUG_LEAK: int diff --git a/stdlib/@python2/genericpath.pyi b/stdlib/@python2/genericpath.pyi deleted file mode 100644 index ba29db4692bb..000000000000 --- a/stdlib/@python2/genericpath.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from _typeshed import SupportsLessThanT -from typing import List, Sequence, Text, Tuple, Union, overload -from typing_extensions import Literal - -# All overloads can return empty string. Ideally, Literal[""] would be a valid -# Iterable[T], so that Union[List[T], Literal[""]] could be used as a return -# type. But because this only works when T is str, we need Sequence[T] instead. -@overload -def commonprefix(m: Sequence[str]) -> str | Literal[""]: ... # type: ignore -@overload -def commonprefix(m: Sequence[Text]) -> Text: ... # type: ignore -@overload -def commonprefix(m: Sequence[List[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... -@overload -def commonprefix(m: Sequence[Tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... -def exists(path: Text) -> bool: ... -def getsize(filename: Text) -> int: ... -def isfile(path: Text) -> bool: ... -def isdir(s: Text) -> bool: ... - -# These return float if os.stat_float_times() == True, -# but int is a subclass of float. -def getatime(filename: Text) -> float: ... -def getmtime(filename: Text) -> float: ... -def getctime(filename: Text) -> float: ... diff --git a/stdlib/@python2/getopt.pyi b/stdlib/@python2/getopt.pyi deleted file mode 100644 index 370d4d5c1cba..000000000000 --- a/stdlib/@python2/getopt.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import List, Tuple - -class GetoptError(Exception): - opt: str - msg: str - def __init__(self, msg: str, opt: str = ...) -> None: ... - def __str__(self) -> str: ... - -error = GetoptError - -def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... -def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... diff --git a/stdlib/@python2/getpass.pyi b/stdlib/@python2/getpass.pyi deleted file mode 100644 index 784eb1a1d760..000000000000 --- a/stdlib/@python2/getpass.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import IO, Any - -class GetPassWarning(UserWarning): ... - -def getpass(prompt: str = ..., stream: IO[Any] = ...) -> str: ... -def getuser() -> str: ... diff --git a/stdlib/@python2/gettext.pyi b/stdlib/@python2/gettext.pyi deleted file mode 100644 index a91234f6b2d3..000000000000 --- a/stdlib/@python2/gettext.pyi +++ /dev/null @@ -1,48 +0,0 @@ -from typing import IO, Any, Container, Dict, List, Sequence, Type - -def bindtextdomain(domain: str, localedir: str = ...) -> str: ... -def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... -def textdomain(domain: str = ...) -> str: ... -def gettext(message: str) -> str: ... -def lgettext(message: str) -> str: ... -def dgettext(domain: str, message: str) -> str: ... -def ldgettext(domain: str, message: str) -> str: ... -def ngettext(singular: str, plural: str, n: int) -> str: ... -def lngettext(singular: str, plural: str, n: int) -> str: ... -def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ... -def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ... - -class NullTranslations(object): - def __init__(self, fp: IO[str] = ...) -> None: ... - def _parse(self, fp: IO[str]) -> None: ... - def add_fallback(self, fallback: NullTranslations) -> None: ... - def gettext(self, message: str) -> str: ... - def lgettext(self, message: str) -> str: ... - def ugettext(self, message: str | unicode) -> unicode: ... - def ngettext(self, singular: str, plural: str, n: int) -> str: ... - def lngettext(self, singular: str, plural: str, n: int) -> str: ... - def ungettext(self, singular: str | unicode, plural: str | unicode, n: int) -> unicode: ... - def info(self) -> Dict[str, str]: ... - def charset(self) -> str | None: ... - def output_charset(self) -> str | None: ... - def set_output_charset(self, charset: str | None) -> None: ... - def install(self, unicode: bool = ..., names: Container[str] = ...) -> None: ... - -class GNUTranslations(NullTranslations): - LE_MAGIC: int - BE_MAGIC: int - -def find( - domain: str, localedir: str | None = ..., languages: Sequence[str] | None = ..., all: Any = ... -) -> str | List[str] | None: ... -def translation( - domain: str, - localedir: str | None = ..., - languages: Sequence[str] | None = ..., - class_: Type[NullTranslations] | None = ..., - fallback: bool = ..., - codeset: str | None = ..., -) -> NullTranslations: ... -def install( - domain: str, localedir: str | None = ..., unicode: bool = ..., codeset: str | None = ..., names: Container[str] = ... -) -> None: ... diff --git a/stdlib/@python2/glob.pyi b/stdlib/@python2/glob.pyi deleted file mode 100644 index f5a389a0ddfa..000000000000 --- a/stdlib/@python2/glob.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import AnyStr, Iterator, List - -def glob(pathname: AnyStr) -> List[AnyStr]: ... -def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... -def glob1(dirname: str | unicode, pattern: AnyStr) -> List[AnyStr]: ... -def glob0(dirname: str | unicode, basename: AnyStr) -> List[AnyStr]: ... -def has_magic(s: str | unicode) -> bool: ... # undocumented diff --git a/stdlib/@python2/grp.pyi b/stdlib/@python2/grp.pyi deleted file mode 100644 index 63898b26bf17..000000000000 --- a/stdlib/@python2/grp.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import List, NamedTuple - -class struct_group(NamedTuple): - gr_name: str - gr_passwd: str | None - gr_gid: int - gr_mem: List[str] - -def getgrall() -> List[struct_group]: ... -def getgrgid(id: int) -> struct_group: ... -def getgrnam(name: str) -> struct_group: ... diff --git a/stdlib/@python2/gzip.pyi b/stdlib/@python2/gzip.pyi deleted file mode 100644 index f5c5af9c4c40..000000000000 --- a/stdlib/@python2/gzip.pyi +++ /dev/null @@ -1,38 +0,0 @@ -import io -from typing import IO, Any, Text - -class GzipFile(io.BufferedIOBase): - myfileobj: Any - max_read_chunk: Any - mode: Any - extrabuf: Any - extrasize: Any - extrastart: Any - name: Any - min_readsize: Any - compress: Any - fileobj: Any - offset: Any - mtime: Any - def __init__( - self, filename: str = ..., mode: Text = ..., compresslevel: int = ..., fileobj: IO[str] = ..., mtime: float = ... - ) -> None: ... - @property - def filename(self): ... - size: Any - crc: Any - def write(self, data): ... - def read(self, size=...): ... - @property - def closed(self): ... - def close(self): ... - def flush(self, zlib_mode=...): ... - def fileno(self): ... - def rewind(self): ... - def readable(self): ... - def writable(self): ... - def seekable(self): ... - def seek(self, offset, whence=...): ... - def readline(self, size=...): ... - -def open(filename: str, mode: Text = ..., compresslevel: int = ...) -> GzipFile: ... diff --git a/stdlib/@python2/hashlib.pyi b/stdlib/@python2/hashlib.pyi deleted file mode 100644 index 9c53d2b6b30d..000000000000 --- a/stdlib/@python2/hashlib.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Tuple, Union - -_DataType = Union[str, unicode, bytearray, buffer, memoryview] - -class _hash(object): # This is not actually in the module namespace. - @property - def name(self) -> str: ... - @property - def block_size(self) -> int: ... - @property - def digest_size(self) -> int: ... - @property - def digestsize(self) -> int: ... - def __init__(self, arg: _DataType = ...) -> None: ... - def update(self, arg: _DataType) -> None: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def copy(self) -> _hash: ... - -def new(name: str, data: str = ...) -> _hash: ... -def md5(s: _DataType = ...) -> _hash: ... -def sha1(s: _DataType = ...) -> _hash: ... -def sha224(s: _DataType = ...) -> _hash: ... -def sha256(s: _DataType = ...) -> _hash: ... -def sha384(s: _DataType = ...) -> _hash: ... -def sha512(s: _DataType = ...) -> _hash: ... - -algorithms: Tuple[str, ...] -algorithms_guaranteed: Tuple[str, ...] -algorithms_available: Tuple[str, ...] - -def pbkdf2_hmac(name: str, password: str, salt: str, rounds: int, dklen: int = ...) -> str: ... diff --git a/stdlib/@python2/heapq.pyi b/stdlib/@python2/heapq.pyi deleted file mode 100644 index 78ce6fd03928..000000000000 --- a/stdlib/@python2/heapq.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from _typeshed import SupportsLessThan -from typing import Callable, Iterable, List, TypeVar - -_T = TypeVar("_T") - -def cmp_lt(x, y) -> bool: ... -def heappush(heap: List[_T], item: _T) -> None: ... -def heappop(heap: List[_T]) -> _T: ... -def heappushpop(heap: List[_T], item: _T) -> _T: ... -def heapify(x: List[_T]) -> None: ... -def heapreplace(heap: List[_T], item: _T) -> _T: ... -def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... -def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> List[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> List[_T]: ... -def _heapify_max(__x: List[_T]) -> None: ... # undocumented diff --git a/stdlib/@python2/hmac.pyi b/stdlib/@python2/hmac.pyi deleted file mode 100644 index cc39d8c65c8f..000000000000 --- a/stdlib/@python2/hmac.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from _typeshed import ReadableBuffer -from types import ModuleType -from typing import Any, AnyStr, Callable, Union, overload - -# TODO more precise type for object of hashlib -_Hash = Any -_DigestMod = Union[str, Callable[[], _Hash], ModuleType] - -digest_size: None - -def new(key: bytes, msg: ReadableBuffer | None = ..., digestmod: _DigestMod | None = ...) -> HMAC: ... - -class HMAC: - def __init__(self, key: bytes, msg: ReadableBuffer | None = ..., digestmod: _DigestMod = ...) -> None: ... - def update(self, msg: ReadableBuffer) -> None: ... - def digest(self) -> bytes: ... - def hexdigest(self) -> str: ... - def copy(self) -> HMAC: ... - -@overload -def compare_digest(__a: ReadableBuffer, __b: ReadableBuffer) -> bool: ... -@overload -def compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... diff --git a/stdlib/@python2/htmlentitydefs.pyi b/stdlib/@python2/htmlentitydefs.pyi deleted file mode 100644 index 749b3039dfc3..000000000000 --- a/stdlib/@python2/htmlentitydefs.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Dict - -name2codepoint: Dict[str, int] -codepoint2name: Dict[int, str] -entitydefs: Dict[str, str] diff --git a/stdlib/@python2/httplib.pyi b/stdlib/@python2/httplib.pyi deleted file mode 100644 index f2163818fae4..000000000000 --- a/stdlib/@python2/httplib.pyi +++ /dev/null @@ -1,217 +0,0 @@ -import mimetools -from typing import Any, Dict, Protocol - -class HTTPMessage(mimetools.Message): - def addcontinue(self, key: str, more: str) -> None: ... - dict: Dict[str, str] - def addheader(self, key: str, value: str) -> None: ... - unixfrom: str - headers: Any - status: str - seekable: bool - def readheaders(self) -> None: ... - -class HTTPResponse: - fp: Any - debuglevel: Any - strict: Any - msg: Any - version: Any - status: Any - reason: Any - chunked: Any - chunk_left: Any - length: Any - will_close: Any - def __init__( - self, sock, debuglevel: int = ..., strict: int = ..., method: Any | None = ..., buffering: bool = ... - ) -> None: ... - def begin(self): ... - def close(self): ... - def isclosed(self): ... - def read(self, amt: Any | None = ...): ... - def fileno(self): ... - def getheader(self, name, default: Any | None = ...): ... - def getheaders(self): ... - -# This is an API stub only for HTTPConnection and HTTPSConnection, as used in -# urllib2.AbstractHTTPHandler.do_open, which takes either the class -# HTTPConnection or the class HTTPSConnection, *not* an instance of either -# class. do_open does not use all of the parameters of HTTPConnection.__init__ -# or HTTPSConnection.__init__, so HTTPConnectionProtocol only implements the -# parameters that do_open does use. -class HTTPConnectionProtocol(Protocol): - def __call__(self, host: str, timeout: int = ..., **http_con_args: Any) -> HTTPConnection: ... - -class HTTPConnection: - response_class: Any - default_port: Any - auto_open: Any - debuglevel: Any - strict: Any - timeout: Any - source_address: Any - sock: Any - host: str = ... - port: int = ... - def __init__( - self, host, port: Any | None = ..., strict: Any | None = ..., timeout=..., source_address: Any | None = ... - ) -> None: ... - def set_tunnel(self, host, port: Any | None = ..., headers: Any | None = ...): ... - def set_debuglevel(self, level): ... - def connect(self): ... - def close(self): ... - def send(self, data): ... - def putrequest(self, method, url, skip_host: int = ..., skip_accept_encoding: int = ...): ... - def putheader(self, header, *values): ... - def endheaders(self, message_body: Any | None = ...): ... - def request(self, method, url, body: Any | None = ..., headers=...): ... - def getresponse(self, buffering: bool = ...): ... - -class HTTP: - debuglevel: Any - def __init__(self, host: str = ..., port: Any | None = ..., strict: Any | None = ...) -> None: ... - def connect(self, host: Any | None = ..., port: Any | None = ...): ... - def getfile(self): ... - file: Any - headers: Any - def getreply(self, buffering: bool = ...): ... - def close(self): ... - -class HTTPSConnection(HTTPConnection): - default_port: Any - key_file: Any - cert_file: Any - def __init__( - self, - host, - port: Any | None = ..., - key_file: Any | None = ..., - cert_file: Any | None = ..., - strict: Any | None = ..., - timeout=..., - source_address: Any | None = ..., - context: Any | None = ..., - ) -> None: ... - sock: Any - def connect(self): ... - -class HTTPS(HTTP): - key_file: Any - cert_file: Any - def __init__( - self, - host: str = ..., - port: Any | None = ..., - key_file: Any | None = ..., - cert_file: Any | None = ..., - strict: Any | None = ..., - context: Any | None = ..., - ) -> None: ... - -class HTTPException(Exception): ... -class NotConnected(HTTPException): ... -class InvalidURL(HTTPException): ... - -class UnknownProtocol(HTTPException): - args: Any - version: Any - def __init__(self, version) -> None: ... - -class UnknownTransferEncoding(HTTPException): ... -class UnimplementedFileMode(HTTPException): ... - -class IncompleteRead(HTTPException): - args: Any - partial: Any - expected: Any - def __init__(self, partial, expected: Any | None = ...) -> None: ... - -class ImproperConnectionState(HTTPException): ... -class CannotSendRequest(ImproperConnectionState): ... -class CannotSendHeader(ImproperConnectionState): ... -class ResponseNotReady(ImproperConnectionState): ... - -class BadStatusLine(HTTPException): - args: Any - line: Any - def __init__(self, line) -> None: ... - -class LineTooLong(HTTPException): - def __init__(self, line_type) -> None: ... - -error: Any - -class LineAndFileWrapper: - def __init__(self, line, file) -> None: ... - def __getattr__(self, attr): ... - def read(self, amt: Any | None = ...): ... - def readline(self): ... - def readlines(self, size: Any | None = ...): ... - -# Constants - -responses: Dict[int, str] - -HTTP_PORT: int -HTTPS_PORT: int - -# status codes -# informational -CONTINUE: int -SWITCHING_PROTOCOLS: int -PROCESSING: int - -# successful -OK: int -CREATED: int -ACCEPTED: int -NON_AUTHORITATIVE_INFORMATION: int -NO_CONTENT: int -RESET_CONTENT: int -PARTIAL_CONTENT: int -MULTI_STATUS: int -IM_USED: int - -# redirection -MULTIPLE_CHOICES: int -MOVED_PERMANENTLY: int -FOUND: int -SEE_OTHER: int -NOT_MODIFIED: int -USE_PROXY: int -TEMPORARY_REDIRECT: int - -# client error -BAD_REQUEST: int -UNAUTHORIZED: int -PAYMENT_REQUIRED: int -FORBIDDEN: int -NOT_FOUND: int -METHOD_NOT_ALLOWED: int -NOT_ACCEPTABLE: int -PROXY_AUTHENTICATION_REQUIRED: int -REQUEST_TIMEOUT: int -CONFLICT: int -GONE: int -LENGTH_REQUIRED: int -PRECONDITION_FAILED: int -REQUEST_ENTITY_TOO_LARGE: int -REQUEST_URI_TOO_LONG: int -UNSUPPORTED_MEDIA_TYPE: int -REQUESTED_RANGE_NOT_SATISFIABLE: int -EXPECTATION_FAILED: int -UNPROCESSABLE_ENTITY: int -LOCKED: int -FAILED_DEPENDENCY: int -UPGRADE_REQUIRED: int - -# server error -INTERNAL_SERVER_ERROR: int -NOT_IMPLEMENTED: int -BAD_GATEWAY: int -SERVICE_UNAVAILABLE: int -GATEWAY_TIMEOUT: int -HTTP_VERSION_NOT_SUPPORTED: int -INSUFFICIENT_STORAGE: int -NOT_EXTENDED: int diff --git a/stdlib/@python2/imaplib.pyi b/stdlib/@python2/imaplib.pyi deleted file mode 100644 index c4346851bdac..000000000000 --- a/stdlib/@python2/imaplib.pyi +++ /dev/null @@ -1,130 +0,0 @@ -import subprocess -import time -from socket import socket as _socket -from ssl import SSLSocket -from typing import IO, Any, Callable, Dict, List, Pattern, Text, Tuple, Type, Union -from typing_extensions import Literal - -# TODO: Commands should use their actual return types, not this type alias. -# E.g. Tuple[Literal["OK"], List[bytes]] -_CommandResults = Tuple[str, List[Any]] - -_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] - -class IMAP4: - error: Type[Exception] = ... - abort: Type[Exception] = ... - readonly: Type[Exception] = ... - mustquote: Pattern[Text] = ... - debug: int = ... - state: str = ... - literal: Text | None = ... - tagged_commands: Dict[bytes, List[bytes] | None] - untagged_responses: Dict[str, List[bytes | Tuple[bytes, bytes]]] - continuation_response: str = ... - is_readonly: bool = ... - tagnum: int = ... - tagpre: str = ... - tagre: Pattern[Text] = ... - welcome: bytes = ... - capabilities: Tuple[str] = ... - PROTOCOL_VERSION: str = ... - def __init__(self, host: str = ..., port: int = ...) -> None: ... - def open(self, host: str = ..., port: int = ...) -> None: ... - def __getattr__(self, attr: str) -> Any: ... - host: str = ... - port: int = ... - sock: _socket = ... - file: IO[Text] | IO[bytes] = ... - def read(self, size: int) -> bytes: ... - def readline(self) -> bytes: ... - def send(self, data: bytes) -> None: ... - def shutdown(self) -> None: ... - def socket(self) -> _socket: ... - def recent(self) -> _CommandResults: ... - def response(self, code: str) -> _CommandResults: ... - def append(self, mailbox: str, flags: str, date_time: str, message: str) -> str: ... - def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> Tuple[str, str]: ... - def capability(self) -> _CommandResults: ... - def check(self) -> _CommandResults: ... - def close(self) -> _CommandResults: ... - def copy(self, message_set: str, new_mailbox: str) -> _CommandResults: ... - def create(self, mailbox: str) -> _CommandResults: ... - def delete(self, mailbox: str) -> _CommandResults: ... - def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... - def expunge(self) -> _CommandResults: ... - def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... - def getacl(self, mailbox: str) -> _CommandResults: ... - def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ... - def getquota(self, root: str) -> _CommandResults: ... - def getquotaroot(self, mailbox: str) -> _CommandResults: ... - def list(self, directory: str = ..., pattern: str = ...) -> Tuple[str, _AnyResponseData]: ... - def login(self, user: str, password: str) -> Tuple[Literal["OK"], List[bytes]]: ... - def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... - def logout(self) -> Tuple[str, _AnyResponseData]: ... - def lsub(self, directory: str = ..., pattern: str = ...) -> _CommandResults: ... - def myrights(self, mailbox: str) -> _CommandResults: ... - def namespace(self) -> _CommandResults: ... - def noop(self) -> Tuple[str, List[bytes]]: ... - def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: ... - def proxyauth(self, user: str) -> _CommandResults: ... - def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ... - def search(self, charset: str | None, *criteria: str) -> _CommandResults: ... - def select(self, mailbox: str = ..., readonly: bool = ...) -> Tuple[str, List[bytes | None]]: ... - def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... - def setannotation(self, *args: str) -> _CommandResults: ... - def setquota(self, root: str, limits: str) -> _CommandResults: ... - def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... - def status(self, mailbox: str, names: str) -> _CommandResults: ... - def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ... - def subscribe(self, mailbox: str) -> _CommandResults: ... - def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ... - def uid(self, command: str, *args: str) -> _CommandResults: ... - def unsubscribe(self, mailbox: str) -> _CommandResults: ... - def xatom(self, name: str, *args: str) -> _CommandResults: ... - def print_log(self) -> None: ... - -class IMAP4_SSL(IMAP4): - keyfile: str = ... - certfile: str = ... - def __init__(self, host: str = ..., port: int = ..., keyfile: str | None = ..., certfile: str | None = ...) -> None: ... - host: str = ... - port: int = ... - sock: _socket = ... - sslobj: SSLSocket = ... - file: IO[Any] = ... - def open(self, host: str = ..., port: int | None = ...) -> None: ... - def read(self, size: int) -> bytes: ... - def readline(self) -> bytes: ... - def send(self, data: bytes) -> None: ... - def shutdown(self) -> None: ... - def socket(self) -> _socket: ... - def ssl(self) -> SSLSocket: ... - -class IMAP4_stream(IMAP4): - command: str = ... - def __init__(self, command: str) -> None: ... - host: str = ... - port: int = ... - sock: _socket = ... - file: IO[Any] = ... - process: subprocess.Popen[bytes] = ... - writefile: IO[Any] = ... - readfile: IO[Any] = ... - def open(self, host: str | None = ..., port: int | None = ...) -> None: ... - def read(self, size: int) -> bytes: ... - def readline(self) -> bytes: ... - def send(self, data: bytes) -> None: ... - def shutdown(self) -> None: ... - -class _Authenticator: - mech: Callable[[bytes], bytes] = ... - def __init__(self, mechinst: Callable[[bytes], bytes]) -> None: ... - def process(self, data: str) -> str: ... - def encode(self, inp: bytes) -> str: ... - def decode(self, inp: str) -> bytes: ... - -def Internaldate2tuple(resp: str) -> time.struct_time: ... -def Int2AP(num: int) -> str: ... -def ParseFlags(resp: str) -> Tuple[str]: ... -def Time2Internaldate(date_time: float | time.struct_time | str) -> str: ... diff --git a/stdlib/@python2/imghdr.pyi b/stdlib/@python2/imghdr.pyi deleted file mode 100644 index d60cafa4c78f..000000000000 --- a/stdlib/@python2/imghdr.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any, BinaryIO, Callable, List, Protocol, Text, Union, overload - -class _ReadableBinary(Protocol): - def tell(self) -> int: ... - def read(self, size: int) -> bytes: ... - def seek(self, offset: int) -> Any: ... - -_File = Union[Text, _ReadableBinary] - -@overload -def what(file: _File, h: None = ...) -> str | None: ... -@overload -def what(file: Any, h: bytes) -> str | None: ... - -tests: List[Callable[[bytes, BinaryIO | None], str | None]] diff --git a/stdlib/@python2/imp.pyi b/stdlib/@python2/imp.pyi deleted file mode 100644 index 128bd900e996..000000000000 --- a/stdlib/@python2/imp.pyi +++ /dev/null @@ -1,33 +0,0 @@ -import types -from typing import IO, Any, Iterable, List, Tuple - -C_BUILTIN: int -C_EXTENSION: int -IMP_HOOK: int -PKG_DIRECTORY: int -PY_CODERESOURCE: int -PY_COMPILED: int -PY_FROZEN: int -PY_RESOURCE: int -PY_SOURCE: int -SEARCH_ERROR: int - -def acquire_lock() -> None: ... -def find_module(name: str, path: Iterable[str] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]] | None: ... -def get_magic() -> str: ... -def get_suffixes() -> List[Tuple[str, str, int]]: ... -def init_builtin(name: str) -> types.ModuleType: ... -def init_frozen(name: str) -> types.ModuleType: ... -def is_builtin(name: str) -> int: ... -def is_frozen(name: str) -> bool: ... -def load_compiled(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def load_dynamic(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def load_module(name: str, file: str, pathname: str, description: Tuple[str, str, int]) -> types.ModuleType: ... -def load_source(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def lock_held() -> bool: ... -def new_module(name: str) -> types.ModuleType: ... -def release_lock() -> None: ... - -class NullImporter: - def __init__(self, path_string: str) -> None: ... - def find_module(self, fullname: str, path: str = ...) -> None: ... diff --git a/stdlib/@python2/importlib.pyi b/stdlib/@python2/importlib.pyi deleted file mode 100644 index 530cb1a3c79c..000000000000 --- a/stdlib/@python2/importlib.pyi +++ /dev/null @@ -1,4 +0,0 @@ -import types -from typing import Text - -def import_module(name: Text, package: Text | None = ...) -> types.ModuleType: ... diff --git a/stdlib/@python2/inspect.pyi b/stdlib/@python2/inspect.pyi deleted file mode 100644 index c6118ea8aebb..000000000000 --- a/stdlib/@python2/inspect.pyi +++ /dev/null @@ -1,129 +0,0 @@ -from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import Any, AnyStr, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple, Type, Union - -# Types and members -class EndOfBlock(Exception): ... - -class BlockFinder: - indent: int - islambda: bool - started: bool - passline: bool - last: int - def tokeneater( - self, type: int, token: AnyStr, srow_scol: Tuple[int, int], erow_ecol: Tuple[int, int], line: AnyStr - ) -> None: ... - -CO_GENERATOR: int -CO_NESTED: int -CO_NEWLOCALS: int -CO_NOFREE: int -CO_OPTIMIZED: int -CO_VARARGS: int -CO_VARKEYWORDS: int -TPFLAGS_IS_ABSTRACT: int - -class ModuleInfo(NamedTuple): - name: str - suffix: str - mode: str - module_type: int - -def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> List[Tuple[str, Any]]: ... -def getmoduleinfo(path: str | unicode) -> ModuleInfo | None: ... -def getmodulename(path: AnyStr) -> AnyStr | None: ... -def ismodule(object: object) -> bool: ... -def isclass(object: object) -> bool: ... -def ismethod(object: object) -> bool: ... -def isfunction(object: object) -> bool: ... -def isgeneratorfunction(object: object) -> bool: ... -def isgenerator(object: object) -> bool: ... -def istraceback(object: object) -> bool: ... -def isframe(object: object) -> bool: ... -def iscode(object: object) -> bool: ... -def isbuiltin(object: object) -> bool: ... -def isroutine(object: object) -> bool: ... -def isabstract(object: object) -> bool: ... -def ismethoddescriptor(object: object) -> bool: ... -def isdatadescriptor(object: object) -> bool: ... -def isgetsetdescriptor(object: object) -> bool: ... -def ismemberdescriptor(object: object) -> bool: ... - -# Retrieving source code -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] - -def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... -def getabsfile(object: _SourceObjectType) -> str: ... -def getblock(lines: Sequence[AnyStr]) -> Sequence[AnyStr]: ... -def getdoc(object: object) -> str | None: ... -def getcomments(object: object) -> str | None: ... -def getfile(object: _SourceObjectType) -> str: ... -def getmodule(object: object) -> ModuleType | None: ... -def getsourcefile(object: _SourceObjectType) -> str | None: ... -def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... -def getsource(object: _SourceObjectType) -> str: ... -def cleandoc(doc: AnyStr) -> AnyStr: ... -def indentsize(line: str | unicode) -> int: ... - -# Classes and functions -def getclasstree(classes: List[type], unique: bool = ...) -> List[Tuple[type, Tuple[type, ...]] | List[Any]]: ... - -class ArgSpec(NamedTuple): - args: List[str] - varargs: str | None - keywords: str | None - defaults: Tuple[Any, ...] - -class ArgInfo(NamedTuple): - args: List[str] - varargs: str | None - keywords: str | None - locals: Dict[str, Any] - -class Arguments(NamedTuple): - args: List[str | List[Any]] - varargs: str | None - keywords: str | None - -def getargs(co: CodeType) -> Arguments: ... -def getargspec(func: object) -> ArgSpec: ... -def getargvalues(frame: FrameType) -> ArgInfo: ... -def formatargspec( - args, varargs=..., varkw=..., defaults=..., formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., join=... -) -> str: ... -def formatargvalues( - args, varargs=..., varkw=..., defaults=..., formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., join=... -) -> str: ... -def getmro(cls: type) -> Tuple[type, ...]: ... -def getcallargs(func, *args, **kwds) -> Dict[str, Any]: ... - -# The interpreter stack - -class Traceback(NamedTuple): - filename: str - lineno: int - function: str - code_context: List[str] | None - index: int | None # type: ignore - -_FrameInfo = Tuple[FrameType, str, int, str, Optional[List[str]], Optional[int]] - -def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... -def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... -def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... -def getlineno(frame: FrameType) -> int: ... -def currentframe(depth: int = ...) -> FrameType: ... -def stack(context: int = ...) -> List[_FrameInfo]: ... -def trace(context: int = ...) -> List[_FrameInfo]: ... - -# Create private type alias to avoid conflict with symbol of same -# name created in Attribute class. -_Object = object - -class Attribute(NamedTuple): - name: str - kind: str - defining_class: type - object: _Object - -def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/stdlib/@python2/io.pyi b/stdlib/@python2/io.pyi deleted file mode 100644 index f36138edd598..000000000000 --- a/stdlib/@python2/io.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import IO, Any - -import _io -from _io import ( - DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE, - BlockingIOError as BlockingIOError, - BufferedRandom as BufferedRandom, - BufferedReader as BufferedReader, - BufferedRWPair as BufferedRWPair, - BufferedWriter as BufferedWriter, - BytesIO as BytesIO, - FileIO as FileIO, - IncrementalNewlineDecoder as IncrementalNewlineDecoder, - StringIO as StringIO, - TextIOWrapper as TextIOWrapper, - UnsupportedOperation as UnsupportedOperation, - open as open, -) - -def _OpenWrapper( - file: str | unicode | int, - mode: unicode = ..., - buffering: int = ..., - encoding: unicode = ..., - errors: unicode = ..., - newline: unicode = ..., - closefd: bool = ..., -) -> IO[Any]: ... - -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int - -class IOBase(_io._IOBase): ... -class RawIOBase(_io._RawIOBase, IOBase): ... -class BufferedIOBase(_io._BufferedIOBase, IOBase): ... - -# Note: In the actual io.py, TextIOBase subclasses IOBase. -# (Which we don't do here because we don't want to subclass both TextIO and BinaryIO.) -class TextIOBase(_io._TextIOBase): ... diff --git a/stdlib/@python2/itertools.pyi b/stdlib/@python2/itertools.pyi deleted file mode 100644 index 12996d44628b..000000000000 --- a/stdlib/@python2/itertools.pyi +++ /dev/null @@ -1,165 +0,0 @@ -from typing import Any, Callable, Generic, Iterable, Iterator, Sequence, Tuple, TypeVar, overload - -_T = TypeVar("_T") -_S = TypeVar("_S") - -def count(start: int = ..., step: int = ...) -> Iterator[int]: ... # more general types? - -class cycle(Iterator[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T]) -> None: ... - def next(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... - -def repeat(object: _T, times: int = ...) -> Iterator[_T]: ... - -class chain(Iterator[_T], Generic[_T]): - def __init__(self, *iterables: Iterable[_T]) -> None: ... - def next(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... - @staticmethod - def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... - -def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... -def dropwhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterator[_T]: ... -def ifilter(predicate: Callable[[_T], Any] | None, iterable: Iterable[_T]) -> Iterator[_T]: ... -def ifilterfalse(predicate: Callable[[_T], Any] | None, iterable: Iterable[_T]) -> Iterator[_T]: ... -@overload -def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... -@overload -def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... -@overload -def islice(iterable: Iterable[_T], stop: int | None) -> Iterator[_T]: ... -@overload -def islice(iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = ...) -> Iterator[_T]: ... - -_T1 = TypeVar("_T1") -_T2 = TypeVar("_T2") -_T3 = TypeVar("_T3") -_T4 = TypeVar("_T4") -_T5 = TypeVar("_T5") -_T6 = TypeVar("_T6") - -@overload -def imap(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... -@overload -def imap(func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[_S]: ... -@overload -def imap( - func: Callable[[_T1, _T2, _T3], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3] -) -> Iterator[_S]: ... -@overload -def imap( - func: Callable[[_T1, _T2, _T3, _T4], _S], - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], -) -> Iterator[_S]: ... -@overload -def imap( - func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], -) -> Iterator[_S]: ... -@overload -def imap( - func: Callable[[_T1, _T2, _T3, _T4, _T5, _T6], _S], - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], - iter6: Iterable[_T6], -) -> Iterator[_S]: ... -@overload -def imap( - func: Callable[..., _S], - iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - iter7: Iterable[Any], - *iterables: Iterable[Any], -) -> Iterator[_S]: ... -def starmap(func: Any, iterable: Iterable[Any]) -> Iterator[Any]: ... -def takewhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterator[_T]: ... -def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... -@overload -def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... -@overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... -@overload -def izip( - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def izip( - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def izip( - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], - iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... -@overload -def izip( - iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - iter7: Iterable[Any], - *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... -def izip_longest(*p: Iterable[Any], fillvalue: Any = ...) -> Iterator[Any]: ... -@overload -def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -def product(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... -@overload -def product(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... -@overload -def product( - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def product( - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def product( - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], - iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... -@overload -def product( - iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - iter7: Iterable[Any], - *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... -@overload -def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... -def permutations(iterable: Iterable[_T], r: int = ...) -> Iterator[Sequence[_T]]: ... -def combinations(iterable: Iterable[_T], r: int) -> Iterator[Sequence[_T]]: ... -def combinations_with_replacement(iterable: Iterable[_T], r: int) -> Iterator[Sequence[_T]]: ... diff --git a/stdlib/@python2/json.pyi b/stdlib/@python2/json.pyi deleted file mode 100644 index bfbddb2a6835..000000000000 --- a/stdlib/@python2/json.pyi +++ /dev/null @@ -1,93 +0,0 @@ -from _typeshed import SupportsRead -from typing import IO, Any, Callable, Dict, List, Text, Tuple, Type - -def dumps( - obj: Any, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., - indent: int | None = ..., - separators: Tuple[str, str] | None = ..., - encoding: str = ..., - default: Callable[[Any], Any] | None = ..., - sort_keys: bool = ..., - **kwds: Any, -) -> str: ... -def dump( - obj: Any, - fp: IO[str] | IO[Text], - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., - indent: int | None = ..., - separators: Tuple[str, str] | None = ..., - encoding: str = ..., - default: Callable[[Any], Any] | None = ..., - sort_keys: bool = ..., - **kwds: Any, -) -> None: ... -def loads( - s: Text | bytes, - encoding: Any = ..., - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[Dict[Any, Any]], Any] | None = ..., - parse_float: Callable[[str], Any] | None = ..., - parse_int: Callable[[str], Any] | None = ..., - parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[List[Tuple[Any, Any]]], Any] | None = ..., - **kwds: Any, -) -> Any: ... -def load( - fp: SupportsRead[Text | bytes], - encoding: str | None = ..., - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[Dict[Any, Any]], Any] | None = ..., - parse_float: Callable[[str], Any] | None = ..., - parse_int: Callable[[str], Any] | None = ..., - parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[List[Tuple[Any, Any]]], Any] | None = ..., - **kwds: Any, -) -> Any: ... - -class JSONDecoder(object): - def __init__( - self, - encoding: Text | bytes = ..., - object_hook: Callable[..., Any] = ..., - parse_float: Callable[[str], float] = ..., - parse_int: Callable[[str], int] = ..., - parse_constant: Callable[[str], Any] = ..., - strict: bool = ..., - object_pairs_hook: Callable[..., Any] = ..., - ) -> None: ... - def decode(self, s: Text | bytes, _w: Any = ...) -> Any: ... - def raw_decode(self, s: Text | bytes, idx: int = ...) -> Tuple[Any, Any]: ... - -class JSONEncoder(object): - item_separator: str - key_separator: str - skipkeys: bool - ensure_ascii: bool - check_circular: bool - allow_nan: bool - sort_keys: bool - indent: int | None - def __init__( - self, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - sort_keys: bool = ..., - indent: int | None = ..., - separators: Tuple[Text | bytes, Text | bytes] = ..., - encoding: Text | bytes = ..., - default: Callable[..., Any] = ..., - ) -> None: ... - def default(self, o: Any) -> Any: ... - def encode(self, o: Any) -> str: ... - def iterencode(self, o: Any, _one_shot: bool = ...) -> str: ... diff --git a/stdlib/@python2/keyword.pyi b/stdlib/@python2/keyword.pyi deleted file mode 100644 index e84ea1c919ec..000000000000 --- a/stdlib/@python2/keyword.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Sequence, Text - -def iskeyword(s: Text) -> bool: ... - -kwlist: Sequence[str] diff --git a/stdlib/@python2/lib2to3/pgen2/driver.pyi b/stdlib/@python2/lib2to3/pgen2/driver.pyi deleted file mode 100644 index f36e3dd0a10c..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/driver.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from _typeshed import StrPath -from lib2to3.pgen2.grammar import Grammar -from lib2to3.pytree import _NL, _Convert -from logging import Logger -from typing import IO, Any, Iterable, Text - -class Driver: - grammar: Grammar - logger: Logger - convert: _Convert - def __init__(self, grammar: Grammar, convert: _Convert | None = ..., logger: Logger | None = ...) -> None: ... - def parse_tokens(self, tokens: Iterable[Any], debug: bool = ...) -> _NL: ... - def parse_stream_raw(self, stream: IO[Text], debug: bool = ...) -> _NL: ... - def parse_stream(self, stream: IO[Text], debug: bool = ...) -> _NL: ... - def parse_file(self, filename: StrPath, encoding: Text | None = ..., debug: bool = ...) -> _NL: ... - def parse_string(self, text: Text, debug: bool = ...) -> _NL: ... - -def load_grammar( - gt: Text = ..., gp: Text | None = ..., save: bool = ..., force: bool = ..., logger: Logger | None = ... -) -> Grammar: ... diff --git a/stdlib/@python2/lib2to3/pgen2/grammar.pyi b/stdlib/@python2/lib2to3/pgen2/grammar.pyi deleted file mode 100644 index 6ec97ce849d2..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/grammar.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from _typeshed import StrPath -from typing import Dict, List, Optional, Text, Tuple, TypeVar - -_P = TypeVar("_P") -_Label = Tuple[int, Optional[Text]] -_DFA = List[List[Tuple[int, int]]] -_DFAS = Tuple[_DFA, Dict[int, int]] - -class Grammar: - symbol2number: Dict[Text, int] - number2symbol: Dict[int, Text] - states: List[_DFA] - dfas: Dict[int, _DFAS] - labels: List[_Label] - keywords: Dict[Text, int] - tokens: Dict[int, int] - symbol2label: Dict[Text, int] - start: int - def __init__(self) -> None: ... - def dump(self, filename: StrPath) -> None: ... - def load(self, filename: StrPath) -> None: ... - def copy(self: _P) -> _P: ... - def report(self) -> None: ... - -opmap_raw: Text -opmap: Dict[Text, Text] diff --git a/stdlib/@python2/lib2to3/pgen2/literals.pyi b/stdlib/@python2/lib2to3/pgen2/literals.pyi deleted file mode 100644 index 160d6fd76f76..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/literals.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Dict, Match, Text - -simple_escapes: Dict[Text, Text] - -def escape(m: Match[str]) -> Text: ... -def evalString(s: Text) -> Text: ... -def test() -> None: ... diff --git a/stdlib/@python2/lib2to3/pgen2/parse.pyi b/stdlib/@python2/lib2to3/pgen2/parse.pyi deleted file mode 100644 index eed165db551c..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/parse.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from lib2to3.pgen2.grammar import _DFAS, Grammar -from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, List, Sequence, Set, Text, Tuple - -_Context = Sequence[Any] - -class ParseError(Exception): - msg: Text - type: int - value: Text | None - context: _Context - def __init__(self, msg: Text, type: int, value: Text | None, context: _Context) -> None: ... - -class Parser: - grammar: Grammar - convert: _Convert - stack: List[Tuple[_DFAS, int, _RawNode]] - rootnode: _NL | None - used_names: Set[Text] - def __init__(self, grammar: Grammar, convert: _Convert | None = ...) -> None: ... - def setup(self, start: int | None = ...) -> None: ... - def addtoken(self, type: int, value: Text | None, context: _Context) -> bool: ... - def classify(self, type: int, value: Text | None, context: _Context) -> int: ... - def shift(self, type: int, value: Text | None, newstate: int, context: _Context) -> None: ... - def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: ... - def pop(self) -> None: ... diff --git a/stdlib/@python2/lib2to3/pgen2/pgen.pyi b/stdlib/@python2/lib2to3/pgen2/pgen.pyi deleted file mode 100644 index 67dbbccdd4a6..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/pgen.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from _typeshed import StrPath -from lib2to3.pgen2 import grammar -from lib2to3.pgen2.tokenize import _TokenInfo -from typing import IO, Any, Dict, Iterable, Iterator, List, NoReturn, Text, Tuple - -class PgenGrammar(grammar.Grammar): ... - -class ParserGenerator: - filename: StrPath - stream: IO[Text] - generator: Iterator[_TokenInfo] - first: Dict[Text, Dict[Text, int]] - def __init__(self, filename: StrPath, stream: IO[Text] | None = ...) -> None: ... - def make_grammar(self) -> PgenGrammar: ... - def make_first(self, c: PgenGrammar, name: Text) -> Dict[int, int]: ... - def make_label(self, c: PgenGrammar, label: Text) -> int: ... - def addfirstsets(self) -> None: ... - def calcfirst(self, name: Text) -> None: ... - def parse(self) -> Tuple[Dict[Text, List[DFAState]], Text]: ... - def make_dfa(self, start: NFAState, finish: NFAState) -> List[DFAState]: ... - def dump_nfa(self, name: Text, start: NFAState, finish: NFAState) -> List[DFAState]: ... - def dump_dfa(self, name: Text, dfa: Iterable[DFAState]) -> None: ... - def simplify_dfa(self, dfa: List[DFAState]) -> None: ... - def parse_rhs(self) -> Tuple[NFAState, NFAState]: ... - def parse_alt(self) -> Tuple[NFAState, NFAState]: ... - def parse_item(self) -> Tuple[NFAState, NFAState]: ... - def parse_atom(self) -> Tuple[NFAState, NFAState]: ... - def expect(self, type: int, value: Any | None = ...) -> Text: ... - def gettoken(self) -> None: ... - def raise_error(self, msg: str, *args: Any) -> NoReturn: ... - -class NFAState: - arcs: List[Tuple[Text | None, NFAState]] - def __init__(self) -> None: ... - def addarc(self, next: NFAState, label: Text | None = ...) -> None: ... - -class DFAState: - nfaset: Dict[NFAState, Any] - isfinal: bool - arcs: Dict[Text, DFAState] - def __init__(self, nfaset: Dict[NFAState, Any], final: NFAState) -> None: ... - def addarc(self, next: DFAState, label: Text) -> None: ... - def unifystate(self, old: DFAState, new: DFAState) -> None: ... - def __eq__(self, other: Any) -> bool: ... - -def generate_grammar(filename: StrPath = ...) -> PgenGrammar: ... diff --git a/stdlib/@python2/lib2to3/pgen2/token.pyi b/stdlib/@python2/lib2to3/pgen2/token.pyi deleted file mode 100644 index 3f4e41d49bd5..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/token.pyi +++ /dev/null @@ -1,63 +0,0 @@ -from typing import Dict, Text - -ENDMARKER: int -NAME: int -NUMBER: int -STRING: int -NEWLINE: int -INDENT: int -DEDENT: int -LPAR: int -RPAR: int -LSQB: int -RSQB: int -COLON: int -COMMA: int -SEMI: int -PLUS: int -MINUS: int -STAR: int -SLASH: int -VBAR: int -AMPER: int -LESS: int -GREATER: int -EQUAL: int -DOT: int -PERCENT: int -BACKQUOTE: int -LBRACE: int -RBRACE: int -EQEQUAL: int -NOTEQUAL: int -LESSEQUAL: int -GREATEREQUAL: int -TILDE: int -CIRCUMFLEX: int -LEFTSHIFT: int -RIGHTSHIFT: int -DOUBLESTAR: int -PLUSEQUAL: int -MINEQUAL: int -STAREQUAL: int -SLASHEQUAL: int -PERCENTEQUAL: int -AMPEREQUAL: int -VBAREQUAL: int -CIRCUMFLEXEQUAL: int -LEFTSHIFTEQUAL: int -RIGHTSHIFTEQUAL: int -DOUBLESTAREQUAL: int -DOUBLESLASH: int -DOUBLESLASHEQUAL: int -OP: int -COMMENT: int -NL: int -ERRORTOKEN: int -N_TOKENS: int -NT_OFFSET: int -tok_name: Dict[int, Text] - -def ISTERMINAL(x: int) -> bool: ... -def ISNONTERMINAL(x: int) -> bool: ... -def ISEOF(x: int) -> bool: ... diff --git a/stdlib/@python2/lib2to3/pgen2/tokenize.pyi b/stdlib/@python2/lib2to3/pgen2/tokenize.pyi deleted file mode 100644 index 477341c1a54e..000000000000 --- a/stdlib/@python2/lib2to3/pgen2/tokenize.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from lib2to3.pgen2.token import * # noqa -from typing import Callable, Iterable, Iterator, List, Text, Tuple - -_Coord = Tuple[int, int] -_TokenEater = Callable[[int, Text, _Coord, _Coord, Text], None] -_TokenInfo = Tuple[int, Text, _Coord, _Coord, Text] - -class TokenError(Exception): ... -class StopTokenizing(Exception): ... - -def tokenize(readline: Callable[[], Text], tokeneater: _TokenEater = ...) -> None: ... - -class Untokenizer: - tokens: List[Text] - prev_row: int - prev_col: int - def __init__(self) -> None: ... - def add_whitespace(self, start: _Coord) -> None: ... - def untokenize(self, iterable: Iterable[_TokenInfo]) -> Text: ... - def compat(self, token: Tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... - -def untokenize(iterable: Iterable[_TokenInfo]) -> Text: ... -def generate_tokens(readline: Callable[[], Text]) -> Iterator[_TokenInfo]: ... diff --git a/stdlib/@python2/lib2to3/pygram.pyi b/stdlib/@python2/lib2to3/pygram.pyi deleted file mode 100644 index bf96a55c41b3..000000000000 --- a/stdlib/@python2/lib2to3/pygram.pyi +++ /dev/null @@ -1,113 +0,0 @@ -from lib2to3.pgen2.grammar import Grammar - -class Symbols: - def __init__(self, grammar: Grammar) -> None: ... - -class python_symbols(Symbols): - and_expr: int - and_test: int - annassign: int - arglist: int - argument: int - arith_expr: int - assert_stmt: int - async_funcdef: int - async_stmt: int - atom: int - augassign: int - break_stmt: int - classdef: int - comp_for: int - comp_if: int - comp_iter: int - comp_op: int - comparison: int - compound_stmt: int - continue_stmt: int - decorated: int - decorator: int - decorators: int - del_stmt: int - dictsetmaker: int - dotted_as_name: int - dotted_as_names: int - dotted_name: int - encoding_decl: int - eval_input: int - except_clause: int - exec_stmt: int - expr: int - expr_stmt: int - exprlist: int - factor: int - file_input: int - flow_stmt: int - for_stmt: int - funcdef: int - global_stmt: int - if_stmt: int - import_as_name: int - import_as_names: int - import_from: int - import_name: int - import_stmt: int - lambdef: int - listmaker: int - not_test: int - old_lambdef: int - old_test: int - or_test: int - parameters: int - pass_stmt: int - power: int - print_stmt: int - raise_stmt: int - return_stmt: int - shift_expr: int - simple_stmt: int - single_input: int - sliceop: int - small_stmt: int - star_expr: int - stmt: int - subscript: int - subscriptlist: int - suite: int - term: int - test: int - testlist: int - testlist1: int - testlist_gexp: int - testlist_safe: int - testlist_star_expr: int - tfpdef: int - tfplist: int - tname: int - trailer: int - try_stmt: int - typedargslist: int - varargslist: int - vfpdef: int - vfplist: int - vname: int - while_stmt: int - with_item: int - with_stmt: int - with_var: int - xor_expr: int - yield_arg: int - yield_expr: int - yield_stmt: int - -class pattern_symbols(Symbols): - Alternative: int - Alternatives: int - Details: int - Matcher: int - NegatedUnit: int - Repeater: int - Unit: int - -python_grammar: Grammar -python_grammar_no_print_statement: Grammar -pattern_grammar: Grammar diff --git a/stdlib/@python2/lib2to3/pytree.pyi b/stdlib/@python2/lib2to3/pytree.pyi deleted file mode 100644 index 27c64853329e..000000000000 --- a/stdlib/@python2/lib2to3/pytree.pyi +++ /dev/null @@ -1,90 +0,0 @@ -from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union - -_P = TypeVar("_P") -_NL = Union[Node, Leaf] -_Context = Tuple[Text, int, int] -_Results = Dict[Text, _NL] -_RawNode = Tuple[int, Text, _Context, Optional[List[_NL]]] -_Convert = Callable[[Grammar, _RawNode], Any] - -HUGE: int - -def type_repr(type_num: int) -> Text: ... - -class Base: - type: int - parent: Node | None - prefix: Text - children: List[_NL] - was_changed: bool - was_checked: bool - def __eq__(self, other: Any) -> bool: ... - def _eq(self: _P, other: _P) -> bool: ... - def clone(self: _P) -> _P: ... - def post_order(self) -> Iterator[_NL]: ... - def pre_order(self) -> Iterator[_NL]: ... - def replace(self, new: _NL | List[_NL]) -> None: ... - def get_lineno(self) -> int: ... - def changed(self) -> None: ... - def remove(self) -> int | None: ... - @property - def next_sibling(self) -> _NL | None: ... - @property - def prev_sibling(self) -> _NL | None: ... - def leaves(self) -> Iterator[Leaf]: ... - def depth(self) -> int: ... - def get_suffix(self) -> Text: ... - def get_prefix(self) -> Text: ... - def set_prefix(self, prefix: Text) -> None: ... - -class Node(Base): - fixers_applied: List[Any] - def __init__( - self, - type: int, - children: List[_NL], - context: Any | None = ..., - prefix: Text | None = ..., - fixers_applied: List[Any] | None = ..., - ) -> None: ... - def set_child(self, i: int, child: _NL) -> None: ... - def insert_child(self, i: int, child: _NL) -> None: ... - def append_child(self, child: _NL) -> None: ... - -class Leaf(Base): - lineno: int - column: int - value: Text - fixers_applied: List[Any] - def __init__( - self, type: int, value: Text, context: _Context | None = ..., prefix: Text | None = ..., fixers_applied: List[Any] = ... - ) -> None: ... - -def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... - -class BasePattern: - type: int - content: Text | None - name: Text | None - def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns - def match(self, node: _NL, results: _Results | None = ...) -> bool: ... - def match_seq(self, nodes: List[_NL], results: _Results | None = ...) -> bool: ... - def generate_matches(self, nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... - -class LeafPattern(BasePattern): - def __init__(self, type: int | None = ..., content: Text | None = ..., name: Text | None = ...) -> None: ... - -class NodePattern(BasePattern): - wildcards: bool - def __init__(self, type: int | None = ..., content: Text | None = ..., name: Text | None = ...) -> None: ... - -class WildcardPattern(BasePattern): - min: int - max: int - def __init__(self, content: Text | None = ..., min: int = ..., max: int = ..., name: Text | None = ...) -> None: ... - -class NegatedPattern(BasePattern): - def __init__(self, content: Text | None = ...) -> None: ... - -def generate_matches(patterns: List[BasePattern], nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... diff --git a/stdlib/@python2/linecache.pyi b/stdlib/@python2/linecache.pyi deleted file mode 100644 index 8628a0c58adc..000000000000 --- a/stdlib/@python2/linecache.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any, Dict, List, Text - -_ModuleGlobals = Dict[str, Any] - -def getline(filename: Text, lineno: int, module_globals: _ModuleGlobals | None = ...) -> str: ... -def clearcache() -> None: ... -def getlines(filename: Text, module_globals: _ModuleGlobals | None = ...) -> List[str]: ... -def checkcache(filename: Text | None = ...) -> None: ... -def updatecache(filename: Text, module_globals: _ModuleGlobals | None = ...) -> List[str]: ... diff --git a/stdlib/@python2/locale.pyi b/stdlib/@python2/locale.pyi deleted file mode 100644 index 21a7da166e29..000000000000 --- a/stdlib/@python2/locale.pyi +++ /dev/null @@ -1,96 +0,0 @@ -# workaround for mypy#2010 -from __builtin__ import str as _str -from decimal import Decimal -from typing import Any, Callable, Dict, Iterable, List, Mapping, Sequence, Tuple - -CODESET: int -D_T_FMT: int -D_FMT: int -T_FMT: int -T_FMT_AMPM: int - -DAY_1: int -DAY_2: int -DAY_3: int -DAY_4: int -DAY_5: int -DAY_6: int -DAY_7: int -ABDAY_1: int -ABDAY_2: int -ABDAY_3: int -ABDAY_4: int -ABDAY_5: int -ABDAY_6: int -ABDAY_7: int - -MON_1: int -MON_2: int -MON_3: int -MON_4: int -MON_5: int -MON_6: int -MON_7: int -MON_8: int -MON_9: int -MON_10: int -MON_11: int -MON_12: int -ABMON_1: int -ABMON_2: int -ABMON_3: int -ABMON_4: int -ABMON_5: int -ABMON_6: int -ABMON_7: int -ABMON_8: int -ABMON_9: int -ABMON_10: int -ABMON_11: int -ABMON_12: int - -RADIXCHAR: int -THOUSEP: int -YESEXPR: int -NOEXPR: int -CRNCYSTR: int - -ERA: int -ERA_D_T_FMT: int -ERA_D_FMT: int -ERA_T_FMT: int - -ALT_DIGITS: int - -LC_CTYPE: int -LC_COLLATE: int -LC_TIME: int -LC_MONETARY: int -LC_MESSAGES: int -LC_NUMERIC: int -LC_ALL: int - -CHAR_MAX: int - -class Error(Exception): ... - -def setlocale(category: int, locale: _str | Iterable[_str] | None = ...) -> _str: ... -def localeconv() -> Mapping[_str, int | _str | List[int]]: ... -def nl_langinfo(__key: int) -> _str: ... -def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> Tuple[_str | None, _str | None]: ... -def getlocale(category: int = ...) -> Sequence[_str]: ... -def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... -def normalize(localename: _str) -> _str: ... -def resetlocale(category: int = ...) -> None: ... -def strcoll(string1: _str, string2: _str) -> int: ... -def strxfrm(string: _str) -> _str: ... -def format(percent: _str, value: float | Decimal, grouping: bool = ..., monetary: bool = ..., *additional: Any) -> _str: ... -def format_string(f: _str, val: Any, grouping: bool = ...) -> _str: ... -def currency(val: int | float | Decimal, symbol: bool = ..., grouping: bool = ..., international: bool = ...) -> _str: ... -def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... -def atoi(string: _str) -> int: ... -def str(val: float) -> _str: ... - -locale_alias: Dict[_str, _str] # undocumented -locale_encoding_alias: Dict[_str, _str] # undocumented -windows_locale: Dict[int, _str] # undocumented diff --git a/stdlib/@python2/logging/__init__.pyi b/stdlib/@python2/logging/__init__.pyi deleted file mode 100644 index f981e2400624..000000000000 --- a/stdlib/@python2/logging/__init__.pyi +++ /dev/null @@ -1,278 +0,0 @@ -import threading -from _typeshed import StrPath, SupportsWrite -from time import struct_time -from types import FrameType, TracebackType -from typing import ( - IO, - Any, - Callable, - Dict, - Generic, - List, - Mapping, - MutableMapping, - Optional, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) - -_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] -_ExcInfoType = Union[None, bool, _SysExcInfoType] -_ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] -_FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, Text] - -raiseExceptions: bool -logThreads: bool -logMultiprocessing: bool -logProcesses: bool -_srcfile: str | None - -def currentframe() -> FrameType: ... - -_levelNames: Dict[int | str, str | int] # Union[int:str, str:int] - -class Filterer(object): - filters: List[Filter] - def __init__(self) -> None: ... - def addFilter(self, filter: _FilterType) -> None: ... - def removeFilter(self, filter: _FilterType) -> None: ... - def filter(self, record: LogRecord) -> bool: ... - -class Logger(Filterer): - name: str - level: int - parent: Logger | PlaceHolder - propagate: bool - handlers: List[Handler] - disabled: int - def __init__(self, name: str, level: _Level = ...) -> None: ... - def setLevel(self, level: _Level) -> None: ... - def isEnabledFor(self, level: int) -> bool: ... - def getEffectiveLevel(self) -> int: ... - def getChild(self, suffix: str) -> Logger: ... - def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - warn = warning - def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - fatal = critical - def log( - self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def _log( - self, level: int, msg: Any, args: _ArgsType, exc_info: _ExcInfoType | None = ..., extra: Dict[str, Any] | None = ... - ) -> None: ... # undocumented - def filter(self, record: LogRecord) -> bool: ... - def addHandler(self, hdlr: Handler) -> None: ... - def removeHandler(self, hdlr: Handler) -> None: ... - def findCaller(self) -> Tuple[str, int, str]: ... - def handle(self, record: LogRecord) -> None: ... - def makeRecord( - self, - name: str, - level: int, - fn: str, - lno: int, - msg: Any, - args: _ArgsType, - exc_info: _SysExcInfoType | None, - func: str | None = ..., - extra: Mapping[str, Any] | None = ..., - ) -> LogRecord: ... - -CRITICAL: int -FATAL: int -ERROR: int -WARNING: int -WARN: int -INFO: int -DEBUG: int -NOTSET: int - -class Handler(Filterer): - level: int # undocumented - formatter: Formatter | None # undocumented - lock: threading.Lock | None # undocumented - name: str | None # undocumented - def __init__(self, level: _Level = ...) -> None: ... - def createLock(self) -> None: ... - def acquire(self) -> None: ... - def release(self) -> None: ... - def setLevel(self, level: _Level) -> None: ... - def setFormatter(self, fmt: Formatter) -> None: ... - def filter(self, record: LogRecord) -> bool: ... - def flush(self) -> None: ... - def close(self) -> None: ... - def handle(self, record: LogRecord) -> None: ... - def handleError(self, record: LogRecord) -> None: ... - def format(self, record: LogRecord) -> str: ... - def emit(self, record: LogRecord) -> None: ... - -class Formatter: - converter: Callable[[float | None], struct_time] - _fmt: str | None - datefmt: str | None - def __init__(self, fmt: str | None = ..., datefmt: str | None = ...) -> None: ... - def format(self, record: LogRecord) -> str: ... - def formatTime(self, record: LogRecord, datefmt: str | None = ...) -> str: ... - def formatException(self, ei: _SysExcInfoType) -> str: ... - -class Filter: - def __init__(self, name: str = ...) -> None: ... - def filter(self, record: LogRecord) -> bool: ... - -class LogRecord: - args: _ArgsType - asctime: str - created: int - exc_info: _SysExcInfoType | None - exc_text: str | None - filename: str - funcName: str - levelname: str - levelno: int - lineno: int - module: str - msecs: int - message: str - msg: str - name: str - pathname: str - process: int - processName: str - relativeCreated: int - thread: int - threadName: str - def __init__( - self, - name: str, - level: int, - pathname: str, - lineno: int, - msg: Any, - args: _ArgsType, - exc_info: _SysExcInfoType | None, - func: str | None = ..., - ) -> None: ... - def getMessage(self) -> str: ... - -_L = TypeVar("_L", Logger, LoggerAdapter[Logger], LoggerAdapter[Any]) - -class LoggerAdapter(Generic[_L]): - logger: _L - extra: Mapping[str, Any] - def __init__(self, logger: _L, extra: Mapping[str, Any]) -> None: ... - def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... - def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def log( - self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any - ) -> None: ... - def isEnabledFor(self, level: int) -> bool: ... - -@overload -def getLogger() -> Logger: ... -@overload -def getLogger(name: Text | str) -> Logger: ... -def getLoggerClass() -> type: ... -def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... - -warn = warning - -def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def log( - level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any -) -> None: ... - -fatal = critical - -def disable(level: int) -> None: ... -def addLevelName(level: int, levelName: str) -> None: ... -def getLevelName(level: int | str) -> Any: ... -def makeLogRecord(dict: Mapping[str, Any]) -> LogRecord: ... -@overload -def basicConfig() -> None: ... -@overload -def basicConfig( - *, - filename: str | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - level: _Level | None = ..., - stream: IO[str] = ..., -) -> None: ... -def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented -def setLoggerClass(klass: type) -> None: ... -def captureWarnings(capture: bool) -> None: ... - -_StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) - -class StreamHandler(Handler, Generic[_StreamT]): - stream: _StreamT # undocumented - @overload - def __init__(self: StreamHandler[IO[str]], stream: None = ...) -> None: ... - @overload - def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... - -class FileHandler(StreamHandler): - baseFilename: str # undocumented - mode: str # undocumented - encoding: str | None # undocumented - delay: bool # undocumented - def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... - def _open(self) -> IO[Any]: ... - -class NullHandler(Handler): ... - -class PlaceHolder: - def __init__(self, alogger: Logger) -> None: ... - def append(self, alogger: Logger) -> None: ... - -# Below aren't in module docs but still visible - -class RootLogger(Logger): - def __init__(self, level: int) -> None: ... - -root: RootLogger - -BASIC_FORMAT: str diff --git a/stdlib/@python2/logging/config.pyi b/stdlib/@python2/logging/config.pyi deleted file mode 100644 index 03707bb98f55..000000000000 --- a/stdlib/@python2/logging/config.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from _typeshed import StrPath -from threading import Thread -from typing import IO, Any, Dict - -_Path = StrPath - -def dictConfig(config: Dict[str, Any]) -> None: ... -def fileConfig(fname: str | IO[str], defaults: Dict[str, str] | None = ..., disable_existing_loggers: bool = ...) -> None: ... -def listen(port: int = ...) -> Thread: ... -def stopListening() -> None: ... diff --git a/stdlib/@python2/logging/handlers.pyi b/stdlib/@python2/logging/handlers.pyi deleted file mode 100644 index d18d57e77af4..000000000000 --- a/stdlib/@python2/logging/handlers.pyi +++ /dev/null @@ -1,129 +0,0 @@ -from _typeshed import StrPath -from logging import FileHandler, Handler, LogRecord -from socket import SocketKind, SocketType -from typing import Any, ClassVar, Dict, List, Tuple - -DEFAULT_TCP_LOGGING_PORT: int -DEFAULT_UDP_LOGGING_PORT: int -DEFAULT_HTTP_LOGGING_PORT: int -DEFAULT_SOAP_LOGGING_PORT: int -SYSLOG_UDP_PORT: int -SYSLOG_TCP_PORT: int - -class WatchedFileHandler(FileHandler): - dev: int - ino: int - def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... - def _statstream(self) -> None: ... - -class RotatingFileHandler(Handler): - def __init__( - self, - filename: str, - mode: str = ..., - maxBytes: int = ..., - backupCount: int = ..., - encoding: str | None = ..., - delay: bool = ..., - ) -> None: ... - def doRollover(self) -> None: ... - -class TimedRotatingFileHandler(Handler): - def __init__( - self, - filename: str, - when: str = ..., - interval: int = ..., - backupCount: int = ..., - encoding: str | None = ..., - delay: bool = ..., - utc: bool = ..., - ) -> None: ... - def doRollover(self) -> None: ... - -class SocketHandler(Handler): - retryStart: float - retryFactor: float - retryMax: float - def __init__(self, host: str, port: int) -> None: ... - def makeSocket(self, timeout: float = ...) -> SocketType: ... # timeout is undocumented - def makePickle(self, record: LogRecord) -> bytes: ... - def send(self, s: bytes) -> None: ... - def createSocket(self) -> None: ... - -class DatagramHandler(SocketHandler): - def makeSocket(self) -> SocketType: ... # type: ignore - -class SysLogHandler(Handler): - LOG_EMERG: int - LOG_ALERT: int - LOG_CRIT: int - LOG_ERR: int - LOG_WARNING: int - LOG_NOTICE: int - LOG_INFO: int - LOG_DEBUG: int - - LOG_KERN: int - LOG_USER: int - LOG_MAIL: int - LOG_DAEMON: int - LOG_AUTH: int - LOG_SYSLOG: int - LOG_LPR: int - LOG_NEWS: int - LOG_UUCP: int - LOG_CRON: int - LOG_AUTHPRIV: int - LOG_FTP: int - LOG_LOCAL0: int - LOG_LOCAL1: int - LOG_LOCAL2: int - LOG_LOCAL3: int - LOG_LOCAL4: int - LOG_LOCAL5: int - LOG_LOCAL6: int - LOG_LOCAL7: int - address: Tuple[str, int] | str # undocumented - unixsocket: bool # undocumented - socktype: SocketKind # undocumented - facility: int # undocumented - priority_names: ClassVar[Dict[str, int]] # undocumented - facility_names: ClassVar[Dict[str, int]] # undocumented - priority_map: ClassVar[Dict[str, str]] # undocumented - def __init__(self, address: Tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... - def encodePriority(self, facility: int | str, priority: int | str) -> int: ... - def mapPriority(self, levelName: str) -> str: ... - -class NTEventLogHandler(Handler): - def __init__(self, appname: str, dllname: str | None = ..., logtype: str = ...) -> None: ... - def getEventCategory(self, record: LogRecord) -> int: ... - # TODO correct return value? - def getEventType(self, record: LogRecord) -> int: ... - def getMessageID(self, record: LogRecord) -> int: ... - -class SMTPHandler(Handler): - # TODO `secure` can also be an empty tuple - def __init__( - self, - mailhost: str | Tuple[str, int], - fromaddr: str, - toaddrs: List[str], - subject: str, - credentials: Tuple[str, str] | None = ..., - secure: Tuple[str] | Tuple[str, str] | None = ..., - ) -> None: ... - def getSubject(self, record: LogRecord) -> str: ... - -class BufferingHandler(Handler): - buffer: List[LogRecord] - def __init__(self, capacity: int) -> None: ... - def shouldFlush(self, record: LogRecord) -> bool: ... - -class MemoryHandler(BufferingHandler): - def __init__(self, capacity: int, flushLevel: int = ..., target: Handler | None = ...) -> None: ... - def setTarget(self, target: Handler) -> None: ... - -class HTTPHandler(Handler): - def __init__(self, host: str, url: str, method: str = ...) -> None: ... - def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... diff --git a/stdlib/@python2/macpath.pyi b/stdlib/@python2/macpath.pyi deleted file mode 100644 index bcb882e23eef..000000000000 --- a/stdlib/@python2/macpath.pyi +++ /dev/null @@ -1,55 +0,0 @@ -from genericpath import ( - commonprefix as commonprefix, - exists as exists, - getatime as getatime, - getctime as getctime, - getmtime as getmtime, - getsize as getsize, - isdir as isdir, - isfile as isfile, -) - -# Re-export common definitions from posixpath to reduce duplication -from posixpath import ( - abspath as abspath, - curdir as curdir, - defpath as defpath, - devnull as devnull, - expanduser as expanduser, - expandvars as expandvars, - extsep as extsep, - isabs as isabs, - lexists as lexists, - pardir as pardir, - pathsep as pathsep, - sep as sep, - splitdrive as splitdrive, - splitext as splitext, - supports_unicode_filenames as supports_unicode_filenames, -) -from typing import AnyStr, Text, Tuple, overload - -altsep: str | None - -def basename(s: AnyStr) -> AnyStr: ... -def dirname(s: AnyStr) -> AnyStr: ... -def normcase(path: AnyStr) -> AnyStr: ... -def normpath(s: AnyStr) -> AnyStr: ... -def realpath(path: AnyStr) -> AnyStr: ... -def islink(s: Text) -> bool: ... - -# Make sure signatures are disjunct, and allow combinations of bytes and unicode. -# (Since Python 2 allows that, too) -# Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in -# a type error. -@overload -def join(__p1: bytes, *p: bytes) -> bytes: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... -@overload -def join(__p1: Text, *p: Text) -> Text: ... -def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/stdlib/@python2/macurl2path.pyi b/stdlib/@python2/macurl2path.pyi deleted file mode 100644 index 6aac6dfeace5..000000000000 --- a/stdlib/@python2/macurl2path.pyi +++ /dev/null @@ -1,3 +0,0 @@ -def url2pathname(pathname: str) -> str: ... -def pathname2url(pathname: str) -> str: ... -def _pncomp2url(component: str | bytes) -> str: ... diff --git a/stdlib/@python2/mailbox.pyi b/stdlib/@python2/mailbox.pyi deleted file mode 100644 index 18a66fa964c4..000000000000 --- a/stdlib/@python2/mailbox.pyi +++ /dev/null @@ -1,187 +0,0 @@ -import email.message -from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Dict, - Generic, - Iterable, - Iterator, - List, - Mapping, - Protocol, - Sequence, - Text, - Tuple, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal - -_T = TypeVar("_T") -_MessageT = TypeVar("_MessageT", bound=Message) -_MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] - -class _HasIteritems(Protocol): - def iteritems(self) -> Iterator[Tuple[str, _MessageData]]: ... - -class _HasItems(Protocol): - def items(self) -> Iterator[Tuple[str, _MessageData]]: ... - -linesep: bytes - -class Mailbox(Generic[_MessageT]): - - _path: bytes | str # undocumented - _factory: Callable[[IO[Any]], _MessageT] | None # undocumented - def __init__(self, path: Text, factory: Callable[[IO[Any]], _MessageT] | None = ..., create: bool = ...) -> None: ... - def add(self, message: _MessageData) -> str: ... - def remove(self, key: str) -> None: ... - def __delitem__(self, key: str) -> None: ... - def discard(self, key: str) -> None: ... - def __setitem__(self, key: str, message: _MessageData) -> None: ... - @overload - def get(self, key: str, default: None = ...) -> _MessageT | None: ... - @overload - def get(self, key: str, default: _T) -> _MessageT | _T: ... - def __getitem__(self, key: str) -> _MessageT: ... - def get_message(self, key: str) -> _MessageT: ... - def get_string(self, key: str) -> str: ... - def get_bytes(self, key: str) -> bytes: ... - # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here - def get_file(self, key: str) -> Any: ... - def iterkeys(self) -> Iterator[str]: ... - def keys(self) -> List[str]: ... - def itervalues(self) -> Iterator[_MessageT]: ... - def __iter__(self) -> Iterator[_MessageT]: ... - def values(self) -> List[_MessageT]: ... - def iteritems(self) -> Iterator[Tuple[str, _MessageT]]: ... - def items(self) -> List[Tuple[str, _MessageT]]: ... - def __contains__(self, key: str) -> bool: ... - def __len__(self) -> int: ... - def clear(self) -> None: ... - @overload - def pop(self, key: str, default: None = ...) -> _MessageT | None: ... - @overload - def pop(self, key: str, default: _T = ...) -> _MessageT | _T: ... - def popitem(self) -> Tuple[str, _MessageT]: ... - def update(self, arg: _HasIteritems | _HasItems | Iterable[Tuple[str, _MessageData]] | None = ...) -> None: ... - def flush(self) -> None: ... - def lock(self) -> None: ... - def unlock(self) -> None: ... - def close(self) -> None: ... - -class Maildir(Mailbox[MaildirMessage]): - - colon: str - def __init__(self, dirname: Text, factory: Callable[[IO[Any]], MaildirMessage] | None = ..., create: bool = ...) -> None: ... - def get_file(self, key: str) -> _ProxyFile[bytes]: ... - def list_folders(self) -> List[str]: ... - def get_folder(self, folder: Text) -> Maildir: ... - def add_folder(self, folder: Text) -> Maildir: ... - def remove_folder(self, folder: Text) -> None: ... - def clean(self) -> None: ... - def next(self) -> str | None: ... - -class _singlefileMailbox(Mailbox[_MessageT]): ... - -class _mboxMMDF(_singlefileMailbox[_MessageT]): - def get_file(self, key: str, from_: bool = ...) -> _PartialFile[bytes]: ... - def get_bytes(self, key: str, from_: bool = ...) -> bytes: ... - def get_string(self, key: str, from_: bool = ...) -> str: ... - -class mbox(_mboxMMDF[mboxMessage]): - def __init__(self, path: Text, factory: Callable[[IO[Any]], mboxMessage] | None = ..., create: bool = ...) -> None: ... - -class MMDF(_mboxMMDF[MMDFMessage]): - def __init__(self, path: Text, factory: Callable[[IO[Any]], MMDFMessage] | None = ..., create: bool = ...) -> None: ... - -class MH(Mailbox[MHMessage]): - def __init__(self, path: Text, factory: Callable[[IO[Any]], MHMessage] | None = ..., create: bool = ...) -> None: ... - def get_file(self, key: str) -> _ProxyFile[bytes]: ... - def list_folders(self) -> List[str]: ... - def get_folder(self, folder: Text) -> MH: ... - def add_folder(self, folder: Text) -> MH: ... - def remove_folder(self, folder: Text) -> None: ... - def get_sequences(self) -> Dict[str, List[int]]: ... - def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... - def pack(self) -> None: ... - -class Babyl(_singlefileMailbox[BabylMessage]): - def __init__(self, path: Text, factory: Callable[[IO[Any]], BabylMessage] | None = ..., create: bool = ...) -> None: ... - def get_file(self, key: str) -> IO[bytes]: ... - def get_labels(self) -> List[str]: ... - -class Message(email.message.Message): - def __init__(self, message: _MessageData | None = ...) -> None: ... - -class MaildirMessage(Message): - def get_subdir(self) -> str: ... - def set_subdir(self, subdir: Literal["new", "cur"]) -> None: ... - def get_flags(self) -> str: ... - def set_flags(self, flags: Iterable[str]) -> None: ... - def add_flag(self, flag: str) -> None: ... - def remove_flag(self, flag: str) -> None: ... - def get_date(self) -> int: ... - def set_date(self, date: float) -> None: ... - def get_info(self) -> str: ... - def set_info(self, info: str) -> None: ... - -class _mboxMMDFMessage(Message): - def get_from(self) -> str: ... - def set_from(self, from_: str, time_: bool | Tuple[int, int, int, int, int, int, int, int, int] | None = ...) -> None: ... - def get_flags(self) -> str: ... - def set_flags(self, flags: Iterable[str]) -> None: ... - def add_flag(self, flag: str) -> None: ... - def remove_flag(self, flag: str) -> None: ... - -class mboxMessage(_mboxMMDFMessage): ... - -class MHMessage(Message): - def get_sequences(self) -> List[str]: ... - def set_sequences(self, sequences: Iterable[str]) -> None: ... - def add_sequence(self, sequence: str) -> None: ... - def remove_sequence(self, sequence: str) -> None: ... - -class BabylMessage(Message): - def get_labels(self) -> List[str]: ... - def set_labels(self, labels: Iterable[str]) -> None: ... - def add_label(self, label: str) -> None: ... - def remove_label(self, label: str) -> None: ... - def get_visible(self) -> Message: ... - def set_visible(self, visible: _MessageData) -> None: ... - def update_visible(self) -> None: ... - -class MMDFMessage(_mboxMMDFMessage): ... - -class _ProxyFile(Generic[AnyStr]): - def __init__(self, f: IO[AnyStr], pos: int | None = ...) -> None: ... - def read(self, size: int | None = ...) -> AnyStr: ... - def read1(self, size: int | None = ...) -> AnyStr: ... - def readline(self, size: int | None = ...) -> AnyStr: ... - def readlines(self, sizehint: int | None = ...) -> List[AnyStr]: ... - def __iter__(self) -> Iterator[AnyStr]: ... - def tell(self) -> int: ... - def seek(self, offset: int, whence: int = ...) -> None: ... - def close(self) -> None: ... - def __enter__(self) -> _ProxyFile[AnyStr]: ... - def __exit__(self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def seekable(self) -> bool: ... - def flush(self) -> None: ... - @property - def closed(self) -> bool: ... - -class _PartialFile(_ProxyFile[AnyStr]): - def __init__(self, f: IO[AnyStr], start: int | None = ..., stop: int | None = ...) -> None: ... - -class Error(Exception): ... -class NoSuchMailboxError(Error): ... -class NotEmptyError(Error): ... -class ExternalClashError(Error): ... -class FormatError(Error): ... diff --git a/stdlib/@python2/mailcap.pyi b/stdlib/@python2/mailcap.pyi deleted file mode 100644 index b29854f3c744..000000000000 --- a/stdlib/@python2/mailcap.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Dict, List, Mapping, Sequence, Tuple, Union - -_Cap = Dict[str, Union[str, int]] - -def findmatch( - caps: Mapping[str, List[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... -) -> Tuple[str | None, _Cap | None]: ... -def getcaps() -> Dict[str, List[_Cap]]: ... diff --git a/stdlib/@python2/markupbase.pyi b/stdlib/@python2/markupbase.pyi deleted file mode 100644 index 727daaacf25e..000000000000 --- a/stdlib/@python2/markupbase.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Tuple - -class ParserBase(object): - def __init__(self) -> None: ... - def error(self, message: str) -> None: ... - def reset(self) -> None: ... - def getpos(self) -> Tuple[int, int]: ... - def unknown_decl(self, data: str) -> None: ... diff --git a/stdlib/@python2/marshal.pyi b/stdlib/@python2/marshal.pyi deleted file mode 100644 index b2fde674a647..000000000000 --- a/stdlib/@python2/marshal.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import IO, Any - -version: int - -def dump(__value: Any, __file: IO[Any], __version: int = ...) -> None: ... -def load(__file: IO[Any]) -> Any: ... -def dumps(__value: Any, __version: int = ...) -> bytes: ... -def loads(__bytes: bytes) -> Any: ... diff --git a/stdlib/@python2/math.pyi b/stdlib/@python2/math.pyi deleted file mode 100644 index caddcedd864b..000000000000 --- a/stdlib/@python2/math.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Iterable, SupportsFloat, SupportsInt, Tuple - -e: float -pi: float - -def acos(__x: SupportsFloat) -> float: ... -def acosh(__x: SupportsFloat) -> float: ... -def asin(__x: SupportsFloat) -> float: ... -def asinh(__x: SupportsFloat) -> float: ... -def atan(__x: SupportsFloat) -> float: ... -def atan2(__y: SupportsFloat, __x: SupportsFloat) -> float: ... -def atanh(__x: SupportsFloat) -> float: ... -def ceil(__x: SupportsFloat) -> float: ... -def copysign(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -def cos(__x: SupportsFloat) -> float: ... -def cosh(__x: SupportsFloat) -> float: ... -def degrees(__x: SupportsFloat) -> float: ... -def erf(__x: SupportsFloat) -> float: ... -def erfc(__x: SupportsFloat) -> float: ... -def exp(__x: SupportsFloat) -> float: ... -def expm1(__x: SupportsFloat) -> float: ... -def fabs(__x: SupportsFloat) -> float: ... -def factorial(__x: SupportsInt) -> int: ... -def floor(__x: SupportsFloat) -> float: ... -def fmod(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -def frexp(__x: SupportsFloat) -> Tuple[float, int]: ... -def fsum(__seq: Iterable[float]) -> float: ... -def gamma(__x: SupportsFloat) -> float: ... -def hypot(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -def isinf(__x: SupportsFloat) -> bool: ... -def isnan(__x: SupportsFloat) -> bool: ... -def ldexp(__x: SupportsFloat, __i: int) -> float: ... -def lgamma(__x: SupportsFloat) -> float: ... -def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... -def log10(__x: SupportsFloat) -> float: ... -def log1p(__x: SupportsFloat) -> float: ... -def modf(__x: SupportsFloat) -> Tuple[float, float]: ... -def pow(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -def radians(__x: SupportsFloat) -> float: ... -def sin(__x: SupportsFloat) -> float: ... -def sinh(__x: SupportsFloat) -> float: ... -def sqrt(__x: SupportsFloat) -> float: ... -def tan(__x: SupportsFloat) -> float: ... -def tanh(__x: SupportsFloat) -> float: ... -def trunc(__x: SupportsFloat) -> int: ... diff --git a/stdlib/@python2/md5.pyi b/stdlib/@python2/md5.pyi deleted file mode 100644 index 371f61135b7e..000000000000 --- a/stdlib/@python2/md5.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from hashlib import md5 as md5 - -new = md5 -blocksize: int -digest_size: int diff --git a/stdlib/@python2/mimetools.pyi b/stdlib/@python2/mimetools.pyi deleted file mode 100644 index 3c6cbfcbacae..000000000000 --- a/stdlib/@python2/mimetools.pyi +++ /dev/null @@ -1,27 +0,0 @@ -import rfc822 -from typing import Any - -class Message(rfc822.Message): - encodingheader: Any - typeheader: Any - def __init__(self, fp, seekable: int = ...): ... - plisttext: Any - type: Any - maintype: Any - subtype: Any - def parsetype(self): ... - plist: Any - def parseplist(self): ... - def getplist(self): ... - def getparam(self, name): ... - def getparamnames(self): ... - def getencoding(self): ... - def gettype(self): ... - def getmaintype(self): ... - def getsubtype(self): ... - -def choose_boundary(): ... -def decode(input, output, encoding): ... -def encode(input, output, encoding): ... -def copyliteral(input, output): ... -def copybinary(input, output): ... diff --git a/stdlib/@python2/mimetypes.pyi b/stdlib/@python2/mimetypes.pyi deleted file mode 100644 index a9661dab56ad..000000000000 --- a/stdlib/@python2/mimetypes.pyi +++ /dev/null @@ -1,30 +0,0 @@ -import sys -from typing import IO, Dict, List, Sequence, Text, Tuple - -def guess_type(url: Text, strict: bool = ...) -> Tuple[str | None, str | None]: ... -def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ... -def guess_extension(type: str, strict: bool = ...) -> str | None: ... -def init(files: Sequence[str] | None = ...) -> None: ... -def read_mime_types(file: str) -> Dict[str, str] | None: ... -def add_type(type: str, ext: str, strict: bool = ...) -> None: ... - -inited: bool -knownfiles: List[str] -suffix_map: Dict[str, str] -encodings_map: Dict[str, str] -types_map: Dict[str, str] -common_types: Dict[str, str] - -class MimeTypes: - suffix_map: Dict[str, str] - encodings_map: Dict[str, str] - types_map: Tuple[Dict[str, str], Dict[str, str]] - types_map_inv: Tuple[Dict[str, str], Dict[str, str]] - def __init__(self, filenames: Tuple[str, ...] = ..., strict: bool = ...) -> None: ... - def guess_extension(self, type: str, strict: bool = ...) -> str | None: ... - def guess_type(self, url: str, strict: bool = ...) -> Tuple[str | None, str | None]: ... - def guess_all_extensions(self, type: str, strict: bool = ...) -> List[str]: ... - def read(self, filename: str, strict: bool = ...) -> None: ... - def readfp(self, fp: IO[str], strict: bool = ...) -> None: ... - if sys.platform == "win32": - def read_windows_registry(self, strict: bool = ...) -> None: ... diff --git a/stdlib/@python2/mmap.pyi b/stdlib/@python2/mmap.pyi deleted file mode 100644 index 44369e6c051d..000000000000 --- a/stdlib/@python2/mmap.pyi +++ /dev/null @@ -1,51 +0,0 @@ -import sys -from typing import NoReturn, Sequence - -ACCESS_DEFAULT: int -ACCESS_READ: int -ACCESS_WRITE: int -ACCESS_COPY: int - -ALLOCATIONGRANULARITY: int - -if sys.platform == "linux": - MAP_DENYWRITE: int - MAP_EXECUTABLE: int - -if sys.platform != "win32": - MAP_ANON: int - MAP_ANONYMOUS: int - MAP_PRIVATE: int - MAP_SHARED: int - PROT_EXEC: int - PROT_READ: int - PROT_WRITE: int - - PAGESIZE: int - -class mmap(Sequence[bytes]): - if sys.platform == "win32": - def __init__(self, fileno: int, length: int, tagname: str | None = ..., access: int = ..., offset: int = ...) -> None: ... - else: - def __init__( - self, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = ..., offset: int = ... - ) -> None: ... - def close(self) -> None: ... - def flush(self, offset: int = ..., size: int = ...) -> int: ... - def move(self, dest: int, src: int, count: int) -> None: ... - def read_byte(self) -> bytes: ... - def readline(self) -> bytes: ... - def resize(self, newsize: int) -> None: ... - def seek(self, pos: int, whence: int = ...) -> None: ... - def size(self) -> int: ... - def tell(self) -> int: ... - def write_byte(self, byte: bytes) -> None: ... - def __len__(self) -> int: ... - def find(self, string: bytes, start: int = ..., end: int = ...) -> int: ... - def rfind(self, string: bytes, start: int = ..., stop: int = ...) -> int: ... - def read(self, num: int) -> bytes: ... - def write(self, string: bytes) -> None: ... - def __getitem__(self, index: int | slice) -> bytes: ... - def __getslice__(self, i: int | None, j: int | None) -> bytes: ... - def __delitem__(self, index: int | slice) -> NoReturn: ... - def __setitem__(self, index: int | slice, object: bytes) -> None: ... diff --git a/stdlib/@python2/modulefinder.pyi b/stdlib/@python2/modulefinder.pyi deleted file mode 100644 index 76fd014daf6e..000000000000 --- a/stdlib/@python2/modulefinder.pyi +++ /dev/null @@ -1,63 +0,0 @@ -from types import CodeType -from typing import IO, Any, Container, Dict, Iterable, List, Sequence, Tuple - -LOAD_CONST: int # undocumented -IMPORT_NAME: int # undocumented -STORE_NAME: int # undocumented -STORE_GLOBAL: int # undocumented -STORE_OPS: Tuple[int, int] # undocumented -EXTENDED_ARG: int # undocumented - -packagePathMap: Dict[str, List[str]] # undocumented - -def AddPackagePath(packagename: str, path: str) -> None: ... - -replacePackageMap: Dict[str, str] # undocumented - -def ReplacePackage(oldname: str, newname: str) -> None: ... - -class Module: # undocumented - def __init__(self, name: str, file: str | None = ..., path: str | None = ...) -> None: ... - def __repr__(self) -> str: ... - -class ModuleFinder: - - modules: Dict[str, Module] - path: List[str] # undocumented - badmodules: Dict[str, Dict[str, int]] # undocumented - debug: int # undocumented - indent: int # undocumented - excludes: Container[str] # undocumented - replace_paths: Sequence[Tuple[str, str]] # undocumented - def __init__( - self, - path: List[str] | None = ..., - debug: int = ..., - excludes: Container[str] = ..., - replace_paths: Sequence[Tuple[str, str]] = ..., - ) -> None: ... - def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented - def msgin(self, *args: Any) -> None: ... # undocumented - def msgout(self, *args: Any) -> None: ... # undocumented - def run_script(self, pathname: str) -> None: ... - def load_file(self, pathname: str) -> None: ... # undocumented - def import_hook( - self, name: str, caller: Module | None = ..., fromlist: List[str] | None = ..., level: int = ... - ) -> Module | None: ... # undocumented - def determine_parent(self, caller: Module | None, level: int = ...) -> Module | None: ... # undocumented - def find_head_package(self, parent: Module, name: str) -> Tuple[Module, str]: ... # undocumented - def load_tail(self, q: Module, tail: str) -> Module: ... # undocumented - def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = ...) -> None: ... # undocumented - def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented - def import_module(self, partname: str, fqname: str, parent: Module) -> Module | None: ... # undocumented - def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: Tuple[str, str, str]) -> Module: ... # undocumented - def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented - def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented - def add_module(self, fqname: str) -> Module: ... # undocumented - def find_module( - self, name: str, path: str | None, parent: Module | None = ... - ) -> Tuple[IO[Any] | None, str | None, Tuple[str, str, int]]: ... # undocumented - def report(self) -> None: ... - def any_missing(self) -> List[str]: ... # undocumented - def any_missing_maybe(self) -> Tuple[List[str], List[str]]: ... # undocumented - def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented diff --git a/stdlib/@python2/msilib/__init__.pyi b/stdlib/@python2/msilib/__init__.pyi deleted file mode 100644 index fa6757696845..000000000000 --- a/stdlib/@python2/msilib/__init__.pyi +++ /dev/null @@ -1,175 +0,0 @@ -import sys -from types import ModuleType -from typing import Any, Container, Dict, Iterable, List, Sequence, Set, Tuple, Type -from typing_extensions import Literal - -if sys.platform == "win32": - from _msi import _Database - - AMD64: bool - Itanium: bool - Win64: bool - - datasizemask: Literal[0x00FF] - type_valid: Literal[0x0100] - type_localizable: Literal[0x0200] - typemask: Literal[0x0C00] - type_long: Literal[0x0000] - type_short: Literal[0x0400] - type_string: Literal[0x0C00] - type_binary: Literal[0x0800] - type_nullable: Literal[0x1000] - type_key: Literal[0x2000] - knownbits: Literal[0x3FFF] - class Table: - - name: str - fields: List[Tuple[int, str, int]] - def __init__(self, name: str) -> None: ... - def add_field(self, index: int, name: str, type: int) -> None: ... - def sql(self) -> str: ... - def create(self, db: _Database) -> None: ... - class _Unspecified: ... - def change_sequence( - seq: Sequence[Tuple[str, str | None, int]], - action: str, - seqno: int | Type[_Unspecified] = ..., - cond: str | Type[_Unspecified] = ..., - ) -> None: ... - def add_data(db: _Database, table: str, values: Iterable[Tuple[Any, ...]]) -> None: ... - def add_stream(db: _Database, name: str, path: str) -> None: ... - def init_database( - name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str - ) -> _Database: ... - def add_tables(db: _Database, module: ModuleType) -> None: ... - def make_id(str: str) -> str: ... - def gen_uuid() -> str: ... - class CAB: - - name: str - files: List[Tuple[str, str]] - filenames: Set[str] - index: int - def __init__(self, name: str) -> None: ... - def gen_id(self, file: str) -> str: ... - def append(self, full: str, file: str, logical: str) -> Tuple[int, str]: ... - def commit(self, db: _Database) -> None: ... - _directories: Set[str] - class Directory: - - db: _Database - cab: CAB - basedir: str - physical: str - logical: str - component: str | None - short_names: Set[str] - ids: Set[str] - keyfiles: Dict[str, str] - componentflags: int | None - absolute: str - def __init__( - self, - db: _Database, - cab: CAB, - basedir: str, - physical: str, - _logical: str, - default: str, - componentflags: int | None = ..., - ) -> None: ... - def start_component( - self, - component: str | None = ..., - feature: Feature | None = ..., - flags: int | None = ..., - keyfile: str | None = ..., - uuid: str | None = ..., - ) -> None: ... - def make_short(self, file: str) -> str: ... - def add_file(self, file: str, src: str | None = ..., version: str | None = ..., language: str | None = ...) -> str: ... - def glob(self, pattern: str, exclude: Container[str] | None = ...) -> List[str]: ... - def remove_pyc(self) -> None: ... - class Binary: - - name: str - def __init__(self, fname: str) -> None: ... - def __repr__(self) -> str: ... - class Feature: - - id: str - def __init__( - self, - db: _Database, - id: str, - title: str, - desc: str, - display: int, - level: int = ..., - parent: Feature | None = ..., - directory: str | None = ..., - attributes: int = ..., - ) -> None: ... - def set_current(self) -> None: ... - class Control: - - dlg: Dialog - name: str - def __init__(self, dlg: Dialog, name: str) -> None: ... - def event(self, event: str, argument: str, condition: str = ..., ordering: int | None = ...) -> None: ... - def mapping(self, event: str, attribute: str) -> None: ... - def condition(self, action: str, condition: str) -> None: ... - class RadioButtonGroup(Control): - - property: str - index: int - def __init__(self, dlg: Dialog, name: str, property: str) -> None: ... - def add(self, name: str, x: int, y: int, w: int, h: int, text: str, value: str | None = ...) -> None: ... - class Dialog: - - db: _Database - name: str - x: int - y: int - w: int - h: int - def __init__( - self, - db: _Database, - name: str, - x: int, - y: int, - w: int, - h: int, - attr: int, - title: str, - first: str, - default: str, - cancel: str, - ) -> None: ... - def control( - self, - name: str, - type: str, - x: int, - y: int, - w: int, - h: int, - attr: int, - prop: str | None, - text: str | None, - next: str | None, - help: str | None, - ) -> Control: ... - def text(self, name: str, x: int, y: int, w: int, h: int, attr: int, text: str | None) -> Control: ... - def bitmap(self, name: str, x: int, y: int, w: int, h: int, text: str | None) -> Control: ... - def line(self, name: str, x: int, y: int, w: int, h: int) -> Control: ... - def pushbutton( - self, name: str, x: int, y: int, w: int, h: int, attr: int, text: str | None, next: str | None - ) -> Control: ... - def radiogroup( - self, name: str, x: int, y: int, w: int, h: int, attr: int, prop: str | None, text: str | None, next: str | None - ) -> RadioButtonGroup: ... - def checkbox( - self, name: str, x: int, y: int, w: int, h: int, attr: int, prop: str | None, text: str | None, next: str | None - ) -> Control: ... diff --git a/stdlib/@python2/msilib/schema.pyi b/stdlib/@python2/msilib/schema.pyi deleted file mode 100644 index d59e9767c3de..000000000000 --- a/stdlib/@python2/msilib/schema.pyi +++ /dev/null @@ -1,95 +0,0 @@ -import sys -from typing import List, Tuple - -if sys.platform == "win32": - from . import Table - - _Validation: Table - ActionText: Table - AdminExecuteSequence: Table - Condition: Table - AdminUISequence: Table - AdvtExecuteSequence: Table - AdvtUISequence: Table - AppId: Table - AppSearch: Table - Property: Table - BBControl: Table - Billboard: Table - Feature: Table - Binary: Table - BindImage: Table - File: Table - CCPSearch: Table - CheckBox: Table - Class: Table - Component: Table - Icon: Table - ProgId: Table - ComboBox: Table - CompLocator: Table - Complus: Table - Directory: Table - Control: Table - Dialog: Table - ControlCondition: Table - ControlEvent: Table - CreateFolder: Table - CustomAction: Table - DrLocator: Table - DuplicateFile: Table - Environment: Table - Error: Table - EventMapping: Table - Extension: Table - MIME: Table - FeatureComponents: Table - FileSFPCatalog: Table - SFPCatalog: Table - Font: Table - IniFile: Table - IniLocator: Table - InstallExecuteSequence: Table - InstallUISequence: Table - IsolatedComponent: Table - LaunchCondition: Table - ListBox: Table - ListView: Table - LockPermissions: Table - Media: Table - MoveFile: Table - MsiAssembly: Table - MsiAssemblyName: Table - MsiDigitalCertificate: Table - MsiDigitalSignature: Table - MsiFileHash: Table - MsiPatchHeaders: Table - ODBCAttribute: Table - ODBCDriver: Table - ODBCDataSource: Table - ODBCSourceAttribute: Table - ODBCTranslator: Table - Patch: Table - PatchPackage: Table - PublishComponent: Table - RadioButton: Table - Registry: Table - RegLocator: Table - RemoveFile: Table - RemoveIniFile: Table - RemoveRegistry: Table - ReserveCost: Table - SelfReg: Table - ServiceControl: Table - ServiceInstall: Table - Shortcut: Table - Signature: Table - TextStyle: Table - TypeLib: Table - UIText: Table - Upgrade: Table - Verb: Table - - tables: List[Table] - - _Validation_records: List[Tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] diff --git a/stdlib/@python2/msilib/sequence.pyi b/stdlib/@python2/msilib/sequence.pyi deleted file mode 100644 index e4f400d33233..000000000000 --- a/stdlib/@python2/msilib/sequence.pyi +++ /dev/null @@ -1,14 +0,0 @@ -import sys -from typing import List, Optional, Tuple - -if sys.platform == "win32": - - _SequenceType = List[Tuple[str, Optional[str], int]] - - AdminExecuteSequence: _SequenceType - AdminUISequence: _SequenceType - AdvtExecuteSequence: _SequenceType - InstallExecuteSequence: _SequenceType - InstallUISequence: _SequenceType - - tables: List[str] diff --git a/stdlib/@python2/msilib/text.pyi b/stdlib/@python2/msilib/text.pyi deleted file mode 100644 index 4ae8ee68184b..000000000000 --- a/stdlib/@python2/msilib/text.pyi +++ /dev/null @@ -1,9 +0,0 @@ -import sys -from typing import List, Tuple - -if sys.platform == "win32": - - ActionText: List[Tuple[str, str, str | None]] - UIText: List[Tuple[str, str | None]] - - tables: List[str] diff --git a/stdlib/@python2/msvcrt.pyi b/stdlib/@python2/msvcrt.pyi deleted file mode 100644 index ede80c9fbb66..000000000000 --- a/stdlib/@python2/msvcrt.pyi +++ /dev/null @@ -1,24 +0,0 @@ -import sys -from typing import Text - -# This module is only available on Windows -if sys.platform == "win32": - LK_LOCK: int - LK_NBLCK: int - LK_NBRLCK: int - LK_RLCK: int - LK_UNLCK: int - def locking(__fd: int, __mode: int, __nbytes: int) -> None: ... - def setmode(__fd: int, __mode: int) -> int: ... - def open_osfhandle(__handle: int, __flags: int) -> int: ... - def get_osfhandle(__fd: int) -> int: ... - def kbhit() -> bool: ... - def getch() -> bytes: ... - def getwch() -> Text: ... - def getche() -> bytes: ... - def getwche() -> Text: ... - def putch(__char: bytes) -> None: ... - def putwch(__unicode_char: Text) -> None: ... - def ungetch(__char: bytes) -> None: ... - def ungetwch(__unicode_char: Text) -> None: ... - def heapmin() -> None: ... diff --git a/stdlib/@python2/multiprocessing/__init__.pyi b/stdlib/@python2/multiprocessing/__init__.pyi deleted file mode 100644 index e22e09000de1..000000000000 --- a/stdlib/@python2/multiprocessing/__init__.pyi +++ /dev/null @@ -1,50 +0,0 @@ -from multiprocessing import pool -from multiprocessing.process import Process as Process, active_children as active_children, current_process as current_process -from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING -from Queue import Queue as _BaseQueue -from typing import Any, Callable, Iterable, TypeVar - -class ProcessError(Exception): ... -class BufferTooShort(ProcessError): ... -class TimeoutError(ProcessError): ... -class AuthenticationError(ProcessError): ... - -_T = TypeVar("_T") - -class Queue(_BaseQueue[_T]): - def __init__(self, maxsize: int = ...) -> None: ... - def get(self, block: bool = ..., timeout: float | None = ...) -> _T: ... - def put(self, item: _T, block: bool = ..., timeout: float | None = ...) -> None: ... - def qsize(self) -> int: ... - def empty(self) -> bool: ... - def full(self) -> bool: ... - def put_nowait(self, item: _T) -> None: ... - def get_nowait(self) -> _T: ... - def close(self) -> None: ... - def join_thread(self) -> None: ... - def cancel_join_thread(self) -> None: ... - -def Manager(): ... -def Pipe(duplex: bool = ...): ... -def cpu_count() -> int: ... -def freeze_support(): ... -def get_logger(): ... -def log_to_stderr(level: Any | None = ...): ... -def allow_connection_pickling(): ... -def Lock(): ... -def RLock(): ... -def Condition(lock: Any | None = ...): ... -def Semaphore(value: int = ...): ... -def BoundedSemaphore(value: int = ...): ... -def Event(): ... -def JoinableQueue(maxsize: int = ...): ... -def RawValue(typecode_or_type, *args): ... -def RawArray(typecode_or_type, size_or_initializer): ... -def Value(typecode_or_type, *args, **kwds): ... -def Array(typecode_or_type, size_or_initializer, **kwds): ... -def Pool( - processes: int | None = ..., - initializer: Callable[..., Any] | None = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: int | None = ..., -) -> pool.Pool: ... diff --git a/stdlib/@python2/multiprocessing/dummy/__init__.pyi b/stdlib/@python2/multiprocessing/dummy/__init__.pyi deleted file mode 100644 index 80a1456d1be8..000000000000 --- a/stdlib/@python2/multiprocessing/dummy/__init__.pyi +++ /dev/null @@ -1,41 +0,0 @@ -import array -import threading -import weakref -from Queue import Queue -from typing import Any, List - -class DummyProcess(threading.Thread): - _children: weakref.WeakKeyDictionary[Any, Any] - _parent: threading.Thread - _pid: None - _start_called: bool - def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... - @property - def exitcode(self) -> int | None: ... - -Process = DummyProcess - -# This should be threading._Condition but threading.pyi exports it as Condition -class Condition(threading.Condition): - notify_all: Any - -class Namespace(object): - def __init__(self, **kwds) -> None: ... - -class Value(object): - _typecode: Any - _value: Any - value: Any - def __init__(self, typecode, value, lock=...) -> None: ... - def _get(self) -> Any: ... - def _set(self, value) -> None: ... - -JoinableQueue = Queue - -def Array(typecode, sequence, lock=...) -> array.array[Any]: ... -def Manager() -> Any: ... -def Pool(processes=..., initializer=..., initargs=...) -> Any: ... -def active_children() -> List[Any]: ... -def current_process() -> threading.Thread: ... -def freeze_support() -> None: ... -def shutdown() -> None: ... diff --git a/stdlib/@python2/multiprocessing/dummy/connection.pyi b/stdlib/@python2/multiprocessing/dummy/connection.pyi deleted file mode 100644 index ae5e05e9ccdd..000000000000 --- a/stdlib/@python2/multiprocessing/dummy/connection.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from Queue import Queue -from typing import Any, List, Tuple - -families: List[None] - -class Connection(object): - _in: Any - _out: Any - recv: Any - recv_bytes: Any - send: Any - send_bytes: Any - def __init__(self, _in, _out) -> None: ... - def close(self) -> None: ... - def poll(self, timeout=...) -> Any: ... - -class Listener(object): - _backlog_queue: Queue[Any] | None - address: Any - def __init__(self, address=..., family=..., backlog=...) -> None: ... - def accept(self) -> Connection: ... - def close(self) -> None: ... - -def Client(address) -> Connection: ... -def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... diff --git a/stdlib/@python2/multiprocessing/pool.pyi b/stdlib/@python2/multiprocessing/pool.pyi deleted file mode 100644 index be9747e89c2f..000000000000 --- a/stdlib/@python2/multiprocessing/pool.pyi +++ /dev/null @@ -1,52 +0,0 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, TypeVar - -_T = TypeVar("_T", bound=Pool) - -class AsyncResult: - def get(self, timeout: float | None = ...) -> Any: ... - def wait(self, timeout: float | None = ...) -> None: ... - def ready(self) -> bool: ... - def successful(self) -> bool: ... - -class IMapIterator(Iterator[Any]): - def __iter__(self) -> Iterator[Any]: ... - def next(self, timeout: float | None = ...) -> Any: ... - -class IMapUnorderedIterator(IMapIterator): ... - -class Pool(object): - def __init__( - self, - processes: int | None = ..., - initializer: Callable[..., None] | None = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: int | None = ..., - ) -> None: ... - def apply(self, func: Callable[..., Any], args: Iterable[Any] = ..., kwds: Dict[str, Any] = ...) -> Any: ... - def apply_async( - self, - func: Callable[..., Any], - args: Iterable[Any] = ..., - kwds: Dict[str, Any] = ..., - callback: Callable[..., None] | None = ..., - ) -> AsyncResult: ... - def map(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ...) -> List[Any]: ... - def map_async( - self, - func: Callable[..., Any], - iterable: Iterable[Any] = ..., - chunksize: int | None = ..., - callback: Callable[..., None] | None = ..., - ) -> AsyncResult: ... - def imap(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ...) -> IMapIterator: ... - def imap_unordered( - self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ... - ) -> IMapIterator: ... - def close(self) -> None: ... - def terminate(self) -> None: ... - def join(self) -> None: ... - -class ThreadPool(Pool): - def __init__( - self, processes: int | None = ..., initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ... - ) -> None: ... diff --git a/stdlib/@python2/multiprocessing/process.pyi b/stdlib/@python2/multiprocessing/process.pyi deleted file mode 100644 index 2cb691342580..000000000000 --- a/stdlib/@python2/multiprocessing/process.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any - -def current_process(): ... -def active_children(): ... - -class Process: - def __init__(self, group: Any | None = ..., target: Any | None = ..., name: Any | None = ..., args=..., kwargs=...): ... - def run(self): ... - def start(self): ... - def terminate(self): ... - def join(self, timeout: Any | None = ...): ... - def is_alive(self): ... - @property - def name(self): ... - @name.setter - def name(self, name): ... - @property - def daemon(self): ... - @daemon.setter - def daemon(self, daemonic): ... - @property - def authkey(self): ... - @authkey.setter - def authkey(self, authkey): ... - @property - def exitcode(self): ... - @property - def ident(self): ... - pid: Any - -class AuthenticationString(bytes): - def __reduce__(self): ... - -class _MainProcess(Process): - def __init__(self): ... diff --git a/stdlib/@python2/multiprocessing/util.pyi b/stdlib/@python2/multiprocessing/util.pyi deleted file mode 100644 index 6976bc3e6cf4..000000000000 --- a/stdlib/@python2/multiprocessing/util.pyi +++ /dev/null @@ -1,29 +0,0 @@ -import threading -from typing import Any - -SUBDEBUG: Any -SUBWARNING: Any - -def sub_debug(msg, *args): ... -def debug(msg, *args): ... -def info(msg, *args): ... -def sub_warning(msg, *args): ... -def get_logger(): ... -def log_to_stderr(level: Any | None = ...): ... -def get_temp_dir(): ... -def register_after_fork(obj, func): ... - -class Finalize: - def __init__(self, obj, callback, args=..., kwargs: Any | None = ..., exitpriority: Any | None = ...): ... - def __call__(self, wr: Any | None = ...): ... - def cancel(self): ... - def still_active(self): ... - -def is_exiting(): ... - -class ForkAwareThreadLock: - def __init__(self): ... - -class ForkAwareLocal(threading.local): - def __init__(self): ... - def __reduce__(self): ... diff --git a/stdlib/@python2/mutex.pyi b/stdlib/@python2/mutex.pyi deleted file mode 100644 index e0931dc1188a..000000000000 --- a/stdlib/@python2/mutex.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any, Callable, Deque, TypeVar - -_T = TypeVar("_T") - -class mutex: - locked: bool - queue: Deque[Any] - def __init__(self) -> None: ... - def test(self) -> bool: ... - def testandset(self) -> bool: ... - def lock(self, function: Callable[[_T], Any], argument: _T) -> None: ... - def unlock(self) -> None: ... diff --git a/stdlib/@python2/netrc.pyi b/stdlib/@python2/netrc.pyi deleted file mode 100644 index 3033c2f78955..000000000000 --- a/stdlib/@python2/netrc.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Dict, List, Optional, Text, Tuple - -class NetrcParseError(Exception): - filename: str | None - lineno: int | None - msg: str - def __init__(self, msg: str, filename: Text | None = ..., lineno: int | None = ...) -> None: ... - -# (login, account, password) tuple -_NetrcTuple = Tuple[str, Optional[str], Optional[str]] - -class netrc: - hosts: Dict[str, _NetrcTuple] - macros: Dict[str, List[str]] - def __init__(self, file: Text | None = ...) -> None: ... - def authenticators(self, host: str) -> _NetrcTuple | None: ... diff --git a/stdlib/@python2/nis.pyi b/stdlib/@python2/nis.pyi deleted file mode 100644 index bc6c2bc07256..000000000000 --- a/stdlib/@python2/nis.pyi +++ /dev/null @@ -1,9 +0,0 @@ -import sys -from typing import Dict, List - -if sys.platform != "win32": - def cat(map: str, domain: str = ...) -> Dict[str, str]: ... - def get_default_domain() -> str: ... - def maps(domain: str = ...) -> List[str]: ... - def match(key: str, map: str, domain: str = ...) -> str: ... - class error(Exception): ... diff --git a/stdlib/@python2/nntplib.pyi b/stdlib/@python2/nntplib.pyi deleted file mode 100644 index 56545d3b88b4..000000000000 --- a/stdlib/@python2/nntplib.pyi +++ /dev/null @@ -1,109 +0,0 @@ -import datetime -import socket -import ssl -from typing import IO, Any, Dict, Iterable, List, NamedTuple, Tuple, TypeVar, Union - -_SelfT = TypeVar("_SelfT", bound=_NNTPBase) -_File = Union[IO[bytes], bytes, str, None] - -class NNTPError(Exception): - response: str - -class NNTPReplyError(NNTPError): ... -class NNTPTemporaryError(NNTPError): ... -class NNTPPermanentError(NNTPError): ... -class NNTPProtocolError(NNTPError): ... -class NNTPDataError(NNTPError): ... - -NNTP_PORT: int -NNTP_SSL_PORT: int - -class GroupInfo(NamedTuple): - group: str - last: str - first: str - flag: str - -class ArticleInfo(NamedTuple): - number: int - message_id: str - lines: List[bytes] - -def decode_header(header_str: str) -> str: ... - -class _NNTPBase: - encoding: str - errors: str - - host: str - file: IO[bytes] - debugging: int - welcome: str - readermode_afterauth: bool - tls_on: bool - authenticated: bool - nntp_implementation: str - nntp_version: int - def __init__(self, file: IO[bytes], host: str, readermode: bool | None = ..., timeout: float = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... - def __exit__(self, *args: Any) -> None: ... - def getwelcome(self) -> str: ... - def getcapabilities(self) -> Dict[str, List[str]]: ... - def set_debuglevel(self, level: int) -> None: ... - def debug(self, level: int) -> None: ... - def capabilities(self) -> Tuple[str, Dict[str, List[str]]]: ... - def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def list(self, group_pattern: str | None = ..., *, file: _File = ...) -> Tuple[str, List[str]]: ... - def description(self, group: str) -> str: ... - def descriptions(self, group_pattern: str) -> Tuple[str, Dict[str, str]]: ... - def group(self, name: str) -> Tuple[str, int, int, int, str]: ... - def help(self, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def stat(self, message_spec: Any = ...) -> Tuple[str, int, str]: ... - def next(self) -> Tuple[str, int, str]: ... - def last(self) -> Tuple[str, int, str]: ... - def head(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... - def body(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... - def article(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... - def slave(self) -> str: ... - def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def xover(self, start: int, end: int, *, file: _File = ...) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... - def over( - self, message_spec: None | str | List[Any] | Tuple[Any, ...], *, file: _File = ... - ) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... - def xgtitle(self, group: str, *, file: _File = ...) -> Tuple[str, List[Tuple[str, str]]]: ... - def xpath(self, id: Any) -> Tuple[str, str]: ... - def date(self) -> Tuple[str, datetime.datetime]: ... - def post(self, data: bytes | Iterable[bytes]) -> str: ... - def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... - def quit(self) -> str: ... - def login(self, user: str | None = ..., password: str | None = ..., usenetrc: bool = ...) -> None: ... - def starttls(self, context: ssl.SSLContext | None = ...) -> None: ... - -class NNTP(_NNTPBase): - port: int - sock: socket.socket - def __init__( - self, - host: str, - port: int = ..., - user: str | None = ..., - password: str | None = ..., - readermode: bool | None = ..., - usenetrc: bool = ..., - timeout: float = ..., - ) -> None: ... - -class NNTP_SSL(_NNTPBase): - sock: socket.socket - def __init__( - self, - host: str, - port: int = ..., - user: str | None = ..., - password: str | None = ..., - ssl_context: ssl.SSLContext | None = ..., - readermode: bool | None = ..., - usenetrc: bool = ..., - timeout: float = ..., - ) -> None: ... diff --git a/stdlib/@python2/ntpath.pyi b/stdlib/@python2/ntpath.pyi deleted file mode 100644 index 514db760886f..000000000000 --- a/stdlib/@python2/ntpath.pyi +++ /dev/null @@ -1,84 +0,0 @@ -import os -import sys -from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload - -_T = TypeVar("_T") - -# ----- os.path variables ----- -supports_unicode_filenames: bool -# aliases (also in os) -curdir: str -pardir: str -sep: str -if sys.platform == "win32": - altsep: str -else: - altsep: str | None -extsep: str -pathsep: str -defpath: str -devnull: str - -# ----- os.path function stubs ----- -def abspath(path: AnyStr) -> AnyStr: ... -def basename(p: AnyStr) -> AnyStr: ... -def dirname(p: AnyStr) -> AnyStr: ... -def expanduser(path: AnyStr) -> AnyStr: ... -def expandvars(path: AnyStr) -> AnyStr: ... -def normcase(s: AnyStr) -> AnyStr: ... -def normpath(path: AnyStr) -> AnyStr: ... - -if sys.platform == "win32": - def realpath(path: AnyStr) -> AnyStr: ... - -else: - def realpath(filename: AnyStr) -> AnyStr: ... - -# NOTE: Empty lists results in '' (str) regardless of contained type. -# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes -# So, fall back to Any -def commonprefix(m: Sequence[Text]) -> Any: ... -def lexists(path: Text) -> bool: ... - -# These return float if os.stat_float_times() == True, -# but int is a subclass of float. -def getatime(filename: Text) -> float: ... -def getmtime(filename: Text) -> float: ... -def getctime(filename: Text) -> float: ... -def getsize(filename: Text) -> int: ... -def isabs(s: Text) -> bool: ... -def isfile(path: Text) -> bool: ... -def isdir(s: Text) -> bool: ... -def islink(path: Text) -> bool: ... -def ismount(path: Text) -> bool: ... - -# Make sure signatures are disjunct, and allow combinations of bytes and unicode. -# (Since Python 2 allows that, too) -# Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in -# a type error. -@overload -def join(__p1: bytes, *p: bytes) -> bytes: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... -@overload -def join(__p1: Text, *p: Text) -> Text: ... -@overload -def relpath(path: str, start: str | None = ...) -> str: ... -@overload -def relpath(path: Text, start: Text | None = ...) -> Text: ... -def samefile(f1: Text, f2: Text) -> bool: ... -def sameopenfile(fp1: int, fp2: int) -> bool: ... -def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/stdlib/@python2/nturl2path.pyi b/stdlib/@python2/nturl2path.pyi deleted file mode 100644 index b87b008e4cec..000000000000 --- a/stdlib/@python2/nturl2path.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import AnyStr - -def url2pathname(url: AnyStr) -> AnyStr: ... -def pathname2url(p: AnyStr) -> AnyStr: ... diff --git a/stdlib/@python2/numbers.pyi b/stdlib/@python2/numbers.pyi deleted file mode 100644 index fb88e076d446..000000000000 --- a/stdlib/@python2/numbers.pyi +++ /dev/null @@ -1,119 +0,0 @@ -# Note: these stubs are incomplete. The more complex type -# signatures are currently omitted. - -from abc import ABCMeta, abstractmethod -from typing import Any, SupportsFloat - -class Number(metaclass=ABCMeta): - @abstractmethod - def __hash__(self) -> int: ... - -class Complex(Number): - @abstractmethod - def __complex__(self) -> complex: ... - def __nonzero__(self) -> bool: ... - @property - @abstractmethod - def real(self) -> Any: ... - @property - @abstractmethod - def imag(self) -> Any: ... - @abstractmethod - def __add__(self, other: Any) -> Any: ... - @abstractmethod - def __radd__(self, other: Any) -> Any: ... - @abstractmethod - def __neg__(self) -> Any: ... - @abstractmethod - def __pos__(self) -> Any: ... - def __sub__(self, other: Any) -> Any: ... - def __rsub__(self, other: Any) -> Any: ... - @abstractmethod - def __mul__(self, other: Any) -> Any: ... - @abstractmethod - def __rmul__(self, other: Any) -> Any: ... - @abstractmethod - def __div__(self, other): ... - @abstractmethod - def __rdiv__(self, other): ... - @abstractmethod - def __truediv__(self, other: Any) -> Any: ... - @abstractmethod - def __rtruediv__(self, other: Any) -> Any: ... - @abstractmethod - def __pow__(self, exponent: Any) -> Any: ... - @abstractmethod - def __rpow__(self, base: Any) -> Any: ... - def __abs__(self) -> Real: ... - def conjugate(self) -> Any: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - -class Real(Complex, SupportsFloat): - @abstractmethod - def __float__(self) -> float: ... - @abstractmethod - def __trunc__(self) -> int: ... - def __divmod__(self, other: Any) -> Any: ... - def __rdivmod__(self, other: Any) -> Any: ... - @abstractmethod - def __floordiv__(self, other: Any) -> int: ... - @abstractmethod - def __rfloordiv__(self, other: Any) -> int: ... - @abstractmethod - def __mod__(self, other: Any) -> Any: ... - @abstractmethod - def __rmod__(self, other: Any) -> Any: ... - @abstractmethod - def __lt__(self, other: Any) -> bool: ... - @abstractmethod - def __le__(self, other: Any) -> bool: ... - def __complex__(self) -> complex: ... - @property - def real(self) -> Any: ... - @property - def imag(self) -> Any: ... - def conjugate(self) -> Any: ... - -class Rational(Real): - @property - @abstractmethod - def numerator(self) -> int: ... - @property - @abstractmethod - def denominator(self) -> int: ... - def __float__(self) -> float: ... - -class Integral(Rational): - @abstractmethod - def __long__(self) -> long: ... - def __index__(self) -> int: ... - @abstractmethod - def __pow__(self, exponent: Any, modulus: Any | None = ...) -> Any: ... - @abstractmethod - def __lshift__(self, other: Any) -> Any: ... - @abstractmethod - def __rlshift__(self, other: Any) -> Any: ... - @abstractmethod - def __rshift__(self, other: Any) -> Any: ... - @abstractmethod - def __rrshift__(self, other: Any) -> Any: ... - @abstractmethod - def __and__(self, other: Any) -> Any: ... - @abstractmethod - def __rand__(self, other: Any) -> Any: ... - @abstractmethod - def __xor__(self, other: Any) -> Any: ... - @abstractmethod - def __rxor__(self, other: Any) -> Any: ... - @abstractmethod - def __or__(self, other: Any) -> Any: ... - @abstractmethod - def __ror__(self, other: Any) -> Any: ... - @abstractmethod - def __invert__(self) -> Any: ... - def __float__(self) -> float: ... - @property - def numerator(self) -> int: ... - @property - def denominator(self) -> int: ... diff --git a/stdlib/@python2/opcode.pyi b/stdlib/@python2/opcode.pyi deleted file mode 100644 index 893dd7c7df9c..000000000000 --- a/stdlib/@python2/opcode.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Dict, List, Sequence - -cmp_op: Sequence[str] -hasconst: List[int] -hasname: List[int] -hasjrel: List[int] -hasjabs: List[int] -haslocal: List[int] -hascompare: List[int] -hasfree: List[int] -opname: List[str] - -opmap: Dict[str, int] -HAVE_ARGUMENT: int -EXTENDED_ARG: int diff --git a/stdlib/@python2/operator.pyi b/stdlib/@python2/operator.pyi deleted file mode 100644 index 76a8a9b6bee4..000000000000 --- a/stdlib/@python2/operator.pyi +++ /dev/null @@ -1,190 +0,0 @@ -from typing import ( - Any, - Container, - Generic, - Mapping, - MutableMapping, - MutableSequence, - Sequence, - SupportsAbs, - Tuple, - TypeVar, - overload, -) - -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) -_K = TypeVar("_K") -_V = TypeVar("_V") - -def lt(__a: Any, __b: Any) -> Any: ... -def le(__a: Any, __b: Any) -> Any: ... -def eq(__a: Any, __b: Any) -> Any: ... -def ne(__a: Any, __b: Any) -> Any: ... -def ge(__a: Any, __b: Any) -> Any: ... -def gt(__a: Any, __b: Any) -> Any: ... -def __lt__(a: Any, b: Any) -> Any: ... -def __le__(a: Any, b: Any) -> Any: ... -def __eq__(a: Any, b: Any) -> Any: ... -def __ne__(a: Any, b: Any) -> Any: ... -def __ge__(a: Any, b: Any) -> Any: ... -def __gt__(a: Any, b: Any) -> Any: ... -def not_(__a: Any) -> bool: ... -def __not__(a: Any) -> bool: ... -def truth(__a: Any) -> bool: ... -def is_(__a: Any, __b: Any) -> bool: ... -def is_not(__a: Any, __b: Any) -> bool: ... -def abs(__a: SupportsAbs[_T]) -> _T: ... -def __abs__(a: SupportsAbs[_T]) -> _T: ... -def add(__a: Any, __b: Any) -> Any: ... -def __add__(a: Any, b: Any) -> Any: ... -def and_(__a: Any, __b: Any) -> Any: ... -def __and__(a: Any, b: Any) -> Any: ... -def div(a: Any, b: Any) -> Any: ... -def __div__(a: Any, b: Any) -> Any: ... -def floordiv(__a: Any, __b: Any) -> Any: ... -def __floordiv__(a: Any, b: Any) -> Any: ... -def index(__a: Any) -> int: ... -def __index__(a: Any) -> int: ... -def inv(__a: Any) -> Any: ... -def invert(__a: Any) -> Any: ... -def __inv__(a: Any) -> Any: ... -def __invert__(a: Any) -> Any: ... -def lshift(__a: Any, __b: Any) -> Any: ... -def __lshift__(a: Any, b: Any) -> Any: ... -def mod(__a: Any, __b: Any) -> Any: ... -def __mod__(a: Any, b: Any) -> Any: ... -def mul(__a: Any, __b: Any) -> Any: ... -def __mul__(a: Any, b: Any) -> Any: ... -def neg(__a: Any) -> Any: ... -def __neg__(a: Any) -> Any: ... -def or_(__a: Any, __b: Any) -> Any: ... -def __or__(a: Any, b: Any) -> Any: ... -def pos(__a: Any) -> Any: ... -def __pos__(a: Any) -> Any: ... -def pow(__a: Any, __b: Any) -> Any: ... -def __pow__(a: Any, b: Any) -> Any: ... -def rshift(__a: Any, __b: Any) -> Any: ... -def __rshift__(a: Any, b: Any) -> Any: ... -def sub(__a: Any, __b: Any) -> Any: ... -def __sub__(a: Any, b: Any) -> Any: ... -def truediv(__a: Any, __b: Any) -> Any: ... -def __truediv__(a: Any, b: Any) -> Any: ... -def xor(__a: Any, __b: Any) -> Any: ... -def __xor__(a: Any, b: Any) -> Any: ... -def concat(__a: Sequence[_T], __b: Sequence[_T]) -> Sequence[_T]: ... -def __concat__(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ... -def contains(__a: Container[Any], __b: Any) -> bool: ... -def __contains__(a: Container[Any], b: Any) -> bool: ... -def countOf(__a: Container[Any], __b: Any) -> int: ... -@overload -def delitem(__a: MutableSequence[Any], __b: int) -> None: ... -@overload -def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... -@overload -def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... -@overload -def __delitem__(a: MutableSequence[Any], b: int) -> None: ... -@overload -def __delitem__(a: MutableSequence[Any], b: slice) -> None: ... -@overload -def __delitem__(a: MutableMapping[_K, Any], b: _K) -> None: ... -def delslice(a: MutableSequence[Any], b: int, c: int) -> None: ... -def __delslice__(a: MutableSequence[Any], b: int, c: int) -> None: ... -@overload -def getitem(__a: Sequence[_T], __b: int) -> _T: ... -@overload -def getitem(__a: Sequence[_T], __b: slice) -> Sequence[_T]: ... -@overload -def getitem(__a: Mapping[_K, _V], __b: _K) -> _V: ... -@overload -def __getitem__(a: Sequence[_T], b: int) -> _T: ... -@overload -def __getitem__(a: Sequence[_T], b: slice) -> Sequence[_T]: ... -@overload -def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ... -def getslice(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... -def __getslice__(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... -def indexOf(__a: Sequence[_T], __b: _T) -> int: ... -def repeat(a: Any, b: int) -> Any: ... -def __repeat__(a: Any, b: int) -> Any: ... -def sequenceIncludes(a: Container[Any], b: Any) -> bool: ... -@overload -def setitem(__a: MutableSequence[_T], __b: int, __c: _T) -> None: ... -@overload -def setitem(__a: MutableSequence[_T], __b: slice, __c: Sequence[_T]) -> None: ... -@overload -def setitem(__a: MutableMapping[_K, _V], __b: _K, __c: _V) -> None: ... -@overload -def __setitem__(a: MutableSequence[_T], b: int, c: _T) -> None: ... -@overload -def __setitem__(a: MutableSequence[_T], b: slice, c: Sequence[_T]) -> None: ... -@overload -def __setitem__(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ... -def setslice(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... -def __setslice__(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... - -class attrgetter(Generic[_T_co]): - @overload - def __new__(cls, attr: str) -> attrgetter[Any]: ... - @overload - def __new__(cls, attr: str, __attr2: str) -> attrgetter[Tuple[Any, Any]]: ... - @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[Tuple[Any, Any, Any]]: ... - @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[Tuple[Any, Any, Any, Any]]: ... - @overload - def __new__(cls, attr: str, *attrs: str) -> attrgetter[Tuple[Any, ...]]: ... - def __call__(self, obj: Any) -> _T_co: ... - -class itemgetter(Generic[_T_co]): - @overload - def __new__(cls, item: Any) -> itemgetter[Any]: ... - @overload - def __new__(cls, item: Any, __item2: Any) -> itemgetter[Tuple[Any, Any]]: ... - @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[Tuple[Any, Any, Any]]: ... - @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[Tuple[Any, Any, Any, Any]]: ... - @overload - def __new__(cls, item: Any, *items: Any) -> itemgetter[Tuple[Any, ...]]: ... - def __call__(self, obj: Any) -> _T_co: ... - -class methodcaller: - def __init__(self, __name: str, *args: Any, **kwargs: Any) -> None: ... - def __call__(self, obj: Any) -> Any: ... - -def iadd(__a: Any, __b: Any) -> Any: ... -def __iadd__(a: Any, b: Any) -> Any: ... -def iand(__a: Any, __b: Any) -> Any: ... -def __iand__(a: Any, b: Any) -> Any: ... -def iconcat(__a: Any, __b: Any) -> Any: ... -def __iconcat__(a: Any, b: Any) -> Any: ... -def idiv(a: Any, b: Any) -> Any: ... -def __idiv__(a: Any, b: Any) -> Any: ... -def ifloordiv(__a: Any, __b: Any) -> Any: ... -def __ifloordiv__(a: Any, b: Any) -> Any: ... -def ilshift(__a: Any, __b: Any) -> Any: ... -def __ilshift__(a: Any, b: Any) -> Any: ... -def imod(__a: Any, __b: Any) -> Any: ... -def __imod__(a: Any, b: Any) -> Any: ... -def imul(__a: Any, __b: Any) -> Any: ... -def __imul__(a: Any, b: Any) -> Any: ... -def ior(__a: Any, __b: Any) -> Any: ... -def __ior__(a: Any, b: Any) -> Any: ... -def ipow(__a: Any, __b: Any) -> Any: ... -def __ipow__(a: Any, b: Any) -> Any: ... -def irepeat(a: Any, b: int) -> Any: ... -def __irepeat__(a: Any, b: int) -> Any: ... -def irshift(__a: Any, __b: Any) -> Any: ... -def __irshift__(a: Any, b: Any) -> Any: ... -def isub(__a: Any, __b: Any) -> Any: ... -def __isub__(a: Any, b: Any) -> Any: ... -def itruediv(__a: Any, __b: Any) -> Any: ... -def __itruediv__(a: Any, b: Any) -> Any: ... -def ixor(__a: Any, __b: Any) -> Any: ... -def __ixor__(a: Any, b: Any) -> Any: ... -def isCallable(x: Any) -> bool: ... -def isMappingType(x: Any) -> bool: ... -def isNumberType(x: Any) -> bool: ... -def isSequenceType(x: Any) -> bool: ... diff --git a/stdlib/@python2/optparse.pyi b/stdlib/@python2/optparse.pyi deleted file mode 100644 index 08a926e301b3..000000000000 --- a/stdlib/@python2/optparse.pyi +++ /dev/null @@ -1,229 +0,0 @@ -from typing import IO, Any, AnyStr, Callable, Dict, Iterable, List, Mapping, Sequence, Tuple, Type, Union, overload - -# See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g -_Text = Union[str, unicode] - -NO_DEFAULT: Tuple[_Text, ...] -SUPPRESS_HELP: _Text -SUPPRESS_USAGE: _Text - -def check_builtin(option: Option, opt: Any, value: _Text) -> Any: ... -def check_choice(option: Option, opt: Any, value: _Text) -> Any: ... -def isbasestring(x: Any) -> bool: ... - -class OptParseError(Exception): - msg: _Text - def __init__(self, msg: _Text) -> None: ... - -class BadOptionError(OptParseError): - opt_str: _Text - def __init__(self, opt_str: _Text) -> None: ... - -class AmbiguousOptionError(BadOptionError): - possibilities: Iterable[_Text] - def __init__(self, opt_str: _Text, possibilities: Sequence[_Text]) -> None: ... - -class OptionError(OptParseError): - msg: _Text - option_id: _Text - def __init__(self, msg: _Text, option: Option) -> None: ... - -class OptionConflictError(OptionError): ... -class OptionValueError(OptParseError): ... - -class HelpFormatter: - NO_DEFAULT_VALUE: _Text - _long_opt_fmt: _Text - _short_opt_fmt: _Text - current_indent: int - default_tag: _Text - help_position: Any - help_width: Any - indent_increment: int - level: int - max_help_position: int - option_strings: Dict[Option, _Text] - parser: OptionParser - short_first: Any - width: int - def __init__(self, indent_increment: int, max_help_position: int, width: int | None, short_first: int) -> None: ... - def dedent(self) -> None: ... - def expand_default(self, option: Option) -> _Text: ... - def format_description(self, description: _Text) -> _Text: ... - def format_epilog(self, epilog: _Text) -> _Text: ... - def format_heading(self, heading: Any) -> _Text: ... - def format_option(self, option: Option) -> _Text: ... - def format_option_strings(self, option: Option) -> _Text: ... - def format_usage(self, usage: Any) -> _Text: ... - def indent(self) -> None: ... - def set_long_opt_delimiter(self, delim: _Text) -> None: ... - def set_parser(self, parser: OptionParser) -> None: ... - def set_short_opt_delimiter(self, delim: _Text) -> None: ... - def store_option_strings(self, parser: OptionParser) -> None: ... - -class IndentedHelpFormatter(HelpFormatter): - def __init__( - self, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ..., short_first: int = ... - ) -> None: ... - def format_heading(self, heading: _Text) -> _Text: ... - def format_usage(self, usage: _Text) -> _Text: ... - -class TitledHelpFormatter(HelpFormatter): - def __init__( - self, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ..., short_first: int = ... - ) -> None: ... - def format_heading(self, heading: _Text) -> _Text: ... - def format_usage(self, usage: _Text) -> _Text: ... - -class Option: - ACTIONS: Tuple[_Text, ...] - ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] - ATTRS: List[_Text] - CHECK_METHODS: List[Callable[..., Any]] | None - CONST_ACTIONS: Tuple[_Text, ...] - STORE_ACTIONS: Tuple[_Text, ...] - TYPED_ACTIONS: Tuple[_Text, ...] - TYPES: Tuple[_Text, ...] - TYPE_CHECKER: Dict[_Text, Callable[..., Any]] - _long_opts: List[_Text] - _short_opts: List[_Text] - action: _Text - dest: _Text | None - default: Any - nargs: int - type: Any - callback: Callable[..., Any] | None - callback_args: Tuple[Any, ...] | None - callback_kwargs: Dict[_Text, Any] | None - help: _Text | None - metavar: _Text | None - def __init__(self, *opts: _Text | None, **attrs: Any) -> None: ... - def _check_action(self) -> None: ... - def _check_callback(self) -> None: ... - def _check_choice(self) -> None: ... - def _check_const(self) -> None: ... - def _check_dest(self) -> None: ... - def _check_nargs(self) -> None: ... - def _check_opt_strings(self, opts: Iterable[_Text | None]) -> List[_Text]: ... - def _check_type(self) -> None: ... - def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... - def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... - def check_value(self, opt: _Text, value: Any) -> Any: ... - def convert_value(self, opt: _Text, value: Any) -> Any: ... - def get_opt_string(self) -> _Text: ... - def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... - def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... - def takes_value(self) -> bool: ... - -make_option = Option - -class OptionContainer: - _long_opt: Dict[_Text, Option] - _short_opt: Dict[_Text, Option] - conflict_handler: _Text - defaults: Dict[_Text, Any] - description: Any - option_class: Type[Option] - def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... - def _check_conflict(self, option: Any) -> None: ... - def _create_option_mappings(self) -> None: ... - def _share_option_mappings(self, parser: OptionParser) -> None: ... - @overload - def add_option(self, opt: Option) -> Option: ... - @overload - def add_option(self, *args: _Text | None, **kwargs: Any) -> Any: ... - def add_options(self, option_list: Iterable[Option]) -> None: ... - def destroy(self) -> None: ... - def format_description(self, formatter: HelpFormatter | None) -> Any: ... - def format_help(self, formatter: HelpFormatter | None) -> _Text: ... - def format_option_help(self, formatter: HelpFormatter | None) -> _Text: ... - def get_description(self) -> Any: ... - def get_option(self, opt_str: _Text) -> Option | None: ... - def has_option(self, opt_str: _Text) -> bool: ... - def remove_option(self, opt_str: _Text) -> None: ... - def set_conflict_handler(self, handler: Any) -> None: ... - def set_description(self, description: Any) -> None: ... - -class OptionGroup(OptionContainer): - option_list: List[Option] - parser: OptionParser - title: _Text - def __init__(self, parser: OptionParser, title: _Text, description: _Text | None = ...) -> None: ... - def _create_option_list(self) -> None: ... - def set_title(self, title: _Text) -> None: ... - -class Values: - def __init__(self, defaults: Mapping[str, Any] | None = ...) -> None: ... - def _update(self, dict: Mapping[_Text, Any], mode: Any) -> None: ... - def _update_careful(self, dict: Mapping[_Text, Any]) -> None: ... - def _update_loose(self, dict: Mapping[_Text, Any]) -> None: ... - def ensure_value(self, attr: _Text, value: Any) -> Any: ... - def read_file(self, filename: _Text, mode: _Text = ...) -> None: ... - def read_module(self, modname: _Text, mode: _Text = ...) -> None: ... - def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - -class OptionParser(OptionContainer): - allow_interspersed_args: bool - epilog: _Text | None - formatter: HelpFormatter - largs: List[_Text] | None - option_groups: List[OptionGroup] - option_list: List[Option] - process_default_values: Any - prog: _Text | None - rargs: List[Any] | None - standard_option_list: List[Option] - usage: _Text | None - values: Values | None - version: _Text - def __init__( - self, - usage: _Text | None = ..., - option_list: Iterable[Option] | None = ..., - option_class: Type[Option] = ..., - version: _Text | None = ..., - conflict_handler: _Text = ..., - description: _Text | None = ..., - formatter: HelpFormatter | None = ..., - add_help_option: bool = ..., - prog: _Text | None = ..., - epilog: _Text | None = ..., - ) -> None: ... - def _add_help_option(self) -> None: ... - def _add_version_option(self) -> None: ... - def _create_option_list(self) -> None: ... - def _get_all_options(self) -> List[Option]: ... - def _get_args(self, args: Iterable[Any]) -> List[Any]: ... - def _init_parsing_state(self) -> None: ... - def _match_long_opt(self, opt: _Text) -> _Text: ... - def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ... - def _process_args(self, largs: List[Any], rargs: List[Any], values: Values) -> None: ... - def _process_long_opt(self, rargs: List[Any], values: Any) -> None: ... - def _process_short_opts(self, rargs: List[Any], values: Any) -> None: ... - @overload - def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... - @overload - def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... - def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ... - def disable_interspersed_args(self) -> None: ... - def enable_interspersed_args(self) -> None: ... - def error(self, msg: _Text) -> None: ... - def exit(self, status: int = ..., msg: str | None = ...) -> None: ... - def expand_prog_name(self, s: _Text | None) -> Any: ... - def format_epilog(self, formatter: HelpFormatter) -> Any: ... - def format_help(self, formatter: HelpFormatter | None = ...) -> _Text: ... - def format_option_help(self, formatter: HelpFormatter | None = ...) -> _Text: ... - def get_default_values(self) -> Values: ... - def get_option_group(self, opt_str: _Text) -> Any: ... - def get_prog_name(self) -> _Text: ... - def get_usage(self) -> _Text: ... - def get_version(self) -> _Text: ... - def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> Tuple[Values, List[AnyStr]]: ... - def print_usage(self, file: IO[str] | None = ...) -> None: ... - def print_help(self, file: IO[str] | None = ...) -> None: ... - def print_version(self, file: IO[str] | None = ...) -> None: ... - def set_default(self, dest: Any, value: Any) -> None: ... - def set_defaults(self, **kwargs: Any) -> None: ... - def set_process_default_values(self, process: Any) -> None: ... - def set_usage(self, usage: _Text) -> None: ... diff --git a/stdlib/@python2/os/__init__.pyi b/stdlib/@python2/os/__init__.pyi deleted file mode 100644 index 1955c07020de..000000000000 --- a/stdlib/@python2/os/__init__.pyi +++ /dev/null @@ -1,334 +0,0 @@ -import sys -from _typeshed import FileDescriptorLike -from builtins import OSError -from posix import listdir as listdir, stat_result as stat_result # TODO: use this, see https://github.com/python/mypy/issues/3078 -from typing import ( - IO, - Any, - AnyStr, - Callable, - Dict, - Generic, - Iterator, - List, - Mapping, - MutableMapping, - NamedTuple, - NoReturn, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) - -from . import path as path - -# We need to use something from path, or flake8 and pytype get unhappy -_supports_unicode_filenames = path.supports_unicode_filenames - -_T = TypeVar("_T") - -# ----- os variables ----- - -error = OSError - -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int - -O_RDONLY: int -O_WRONLY: int -O_RDWR: int -O_APPEND: int -O_CREAT: int -O_EXCL: int -O_TRUNC: int -# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, -# including tests for mypy, use a more finer way than sys.platform before using these APIs -# See https://github.com/python/typeshed/pull/2286 for discussions -O_DSYNC: int # Unix only -O_RSYNC: int # Unix only -O_SYNC: int # Unix only -O_NDELAY: int # Unix only -O_NONBLOCK: int # Unix only -O_NOCTTY: int # Unix only -O_SHLOCK: int # Unix only -O_EXLOCK: int # Unix only -O_BINARY: int # Windows only -O_NOINHERIT: int # Windows only -O_SHORT_LIVED: int # Windows only -O_TEMPORARY: int # Windows only -O_RANDOM: int # Windows only -O_SEQUENTIAL: int # Windows only -O_TEXT: int # Windows only -O_ASYNC: int # Gnu extension if in C library -O_DIRECT: int # Gnu extension if in C library -O_DIRECTORY: int # Gnu extension if in C library -O_NOFOLLOW: int # Gnu extension if in C library -O_NOATIME: int # Gnu extension if in C library -O_LARGEFILE: int # Gnu extension if in C library - -curdir: str -pardir: str -sep: str -if sys.platform == "win32": - altsep: str -else: - altsep: str | None -extsep: str -pathsep: str -defpath: str -linesep: str -devnull: str -name: str - -F_OK: int -R_OK: int -W_OK: int -X_OK: int - -class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): - def copy(self) -> Dict[AnyStr, AnyStr]: ... - def __delitem__(self, key: AnyStr) -> None: ... - def __getitem__(self, key: AnyStr) -> AnyStr: ... - def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... - def __len__(self) -> int: ... - -environ: _Environ[str] -if sys.platform != "win32": - # Unix only - confstr_names: Dict[str, int] - pathconf_names: Dict[str, int] - sysconf_names: Dict[str, int] - - EX_OK: int - EX_USAGE: int - EX_DATAERR: int - EX_NOINPUT: int - EX_NOUSER: int - EX_NOHOST: int - EX_UNAVAILABLE: int - EX_SOFTWARE: int - EX_OSERR: int - EX_OSFILE: int - EX_CANTCREAT: int - EX_IOERR: int - EX_TEMPFAIL: int - EX_PROTOCOL: int - EX_NOPERM: int - EX_CONFIG: int - EX_NOTFOUND: int - -P_NOWAIT: int -P_NOWAITO: int -P_WAIT: int -if sys.platform == "win32": - P_DETACH: int - P_OVERLAY: int - -# wait()/waitpid() options -if sys.platform != "win32": - WNOHANG: int # Unix only - WCONTINUED: int # some Unix systems - WUNTRACED: int # Unix only - -TMP_MAX: int # Undocumented, but used by tempfile - -# ----- os classes (structures) ----- -class _StatVFS(NamedTuple): - f_bsize: int - f_frsize: int - f_blocks: int - f_bfree: int - f_bavail: int - f_files: int - f_ffree: int - f_favail: int - f_flag: int - f_namemax: int - -def getlogin() -> str: ... -def getpid() -> int: ... -def getppid() -> int: ... -def strerror(code: int) -> str: ... -def umask(mask: int) -> int: ... - -if sys.platform != "win32": - def ctermid() -> str: ... - def getegid() -> int: ... - def geteuid() -> int: ... - def getgid() -> int: ... - def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac - def initgroups(username: str, gid: int) -> None: ... - def getpgid(pid: int) -> int: ... - def getpgrp() -> int: ... - def getresuid() -> Tuple[int, int, int]: ... - def getresgid() -> Tuple[int, int, int]: ... - def getuid() -> int: ... - def setegid(egid: int) -> None: ... - def seteuid(euid: int) -> None: ... - def setgid(gid: int) -> None: ... - def setgroups(groups: Sequence[int]) -> None: ... - def setpgrp() -> None: ... - def setpgid(pid: int, pgrp: int) -> None: ... - def setregid(rgid: int, egid: int) -> None: ... - def setresgid(rgid: int, egid: int, sgid: int) -> None: ... - def setresuid(ruid: int, euid: int, suid: int) -> None: ... - def setreuid(ruid: int, euid: int) -> None: ... - def getsid(pid: int) -> int: ... - def setsid() -> None: ... - def setuid(uid: int) -> None: ... - def uname() -> Tuple[str, str, str, str, str]: ... - -@overload -def getenv(key: Text) -> str | None: ... -@overload -def getenv(key: Text, default: _T) -> str | _T: ... -def putenv(key: bytes | Text, value: bytes | Text) -> None: ... -def unsetenv(key: bytes | Text) -> None: ... -def fdopen(fd: int, *args, **kwargs) -> IO[Any]: ... -def close(fd: int) -> None: ... -def closerange(fd_low: int, fd_high: int) -> None: ... -def dup(fd: int) -> int: ... -def dup2(fd: int, fd2: int) -> None: ... -def fstat(fd: int) -> Any: ... -def fsync(fd: FileDescriptorLike) -> None: ... -def lseek(fd: int, pos: int, how: int) -> int: ... -def open(file: Text, flags: int, mode: int = ...) -> int: ... -def pipe() -> Tuple[int, int]: ... -def read(fd: int, n: int) -> bytes: ... -def write(fd: int, string: bytes | buffer) -> int: ... -def access(path: Text, mode: int) -> bool: ... -def chdir(path: Text) -> None: ... -def fchdir(fd: FileDescriptorLike) -> None: ... -def getcwd() -> str: ... -def getcwdu() -> unicode: ... -def chmod(path: Text, mode: int) -> None: ... -def link(src: Text, link_name: Text) -> None: ... -def lstat(path: Text) -> Any: ... -def mknod(filename: Text, mode: int = ..., device: int = ...) -> None: ... -def major(device: int) -> int: ... -def minor(device: int) -> int: ... -def makedev(major: int, minor: int) -> int: ... -def mkdir(path: Text, mode: int = ...) -> None: ... -def makedirs(path: Text, mode: int = ...) -> None: ... -def readlink(path: AnyStr) -> AnyStr: ... -def remove(path: Text) -> None: ... -def removedirs(path: Text) -> None: ... -def rename(src: Text, dst: Text) -> None: ... -def renames(old: Text, new: Text) -> None: ... -def rmdir(path: Text) -> None: ... -def stat(path: Text) -> Any: ... -@overload -def stat_float_times() -> bool: ... -@overload -def stat_float_times(newvalue: bool) -> None: ... -def symlink(source: Text, link_name: Text) -> None: ... -def unlink(path: Text) -> None: ... - -# TODO: add ns, dir_fd, follow_symlinks argument -def utime(path: Text, times: Tuple[float, float] | None) -> None: ... - -if sys.platform != "win32": - # Unix only - def fchmod(fd: int, mode: int) -> None: ... - def fchown(fd: int, uid: int, gid: int) -> None: ... - if sys.platform != "darwin": - def fdatasync(fd: FileDescriptorLike) -> None: ... # Unix only, not Mac - def fpathconf(fd: int, name: str | int) -> int: ... - def fstatvfs(fd: int) -> _StatVFS: ... - def ftruncate(fd: int, length: int) -> None: ... - def isatty(fd: int) -> bool: ... - def openpty() -> Tuple[int, int]: ... # some flavors of Unix - def tcgetpgrp(fd: int) -> int: ... - def tcsetpgrp(fd: int, pg: int) -> None: ... - def ttyname(fd: int) -> str: ... - def chflags(path: Text, flags: int) -> None: ... - def chroot(path: Text) -> None: ... - def chown(path: Text, uid: int, gid: int) -> None: ... - def lchflags(path: Text, flags: int) -> None: ... - def lchmod(path: Text, mode: int) -> None: ... - def lchown(path: Text, uid: int, gid: int) -> None: ... - def mkfifo(path: Text, mode: int = ...) -> None: ... - def pathconf(path: Text, name: str | int) -> int: ... - def statvfs(path: Text) -> _StatVFS: ... - -def walk( - top: AnyStr, topdown: bool = ..., onerror: Callable[[OSError], Any] | None = ..., followlinks: bool = ... -) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... -def abort() -> NoReturn: ... - -# These are defined as execl(file, *args) but the first *arg is mandatory. -def execl(file: Text, __arg0: bytes | Text, *args: bytes | Text) -> NoReturn: ... -def execlp(file: Text, __arg0: bytes | Text, *args: bytes | Text) -> NoReturn: ... - -# These are: execle(file, *args, env) but env is pulled from the last element of the args. -def execle(file: Text, __arg0: bytes | Text, *args: Any) -> NoReturn: ... -def execlpe(file: Text, __arg0: bytes | Text, *args: Any) -> NoReturn: ... - -# The docs say `args: tuple or list of strings` -# The implementation enforces tuple or list so we can't use Sequence. -_ExecVArgs = Union[Tuple[Union[bytes, Text], ...], List[bytes], List[Text], List[Union[bytes, Text]]] - -def execv(path: Text, args: _ExecVArgs) -> NoReturn: ... -def execve(path: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... -def execvp(file: Text, args: _ExecVArgs) -> NoReturn: ... -def execvpe(file: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... -def _exit(n: int) -> NoReturn: ... -def kill(pid: int, sig: int) -> None: ... - -if sys.platform != "win32": - # Unix only - def fork() -> int: ... - def forkpty() -> Tuple[int, int]: ... # some flavors of Unix - def killpg(__pgid: int, __signal: int) -> None: ... - def nice(increment: int) -> int: ... - def plock(op: int) -> None: ... # ???op is int? - -def popen(command: str, *args, **kwargs) -> IO[Any]: ... -def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... -def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ... -def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... -def spawnl(mode: int, path: Text, arg0: bytes | Text, *args: bytes | Text) -> int: ... -def spawnle(mode: int, path: Text, arg0: bytes | Text, *args: Any) -> int: ... # Imprecise sig -def spawnv(mode: int, path: Text, args: List[bytes | Text]) -> int: ... -def spawnve(mode: int, path: Text, args: List[bytes | Text], env: Mapping[str, str]) -> int: ... -def system(command: Text) -> int: ... -def times() -> Tuple[float, float, float, float, float]: ... -def waitpid(pid: int, options: int) -> Tuple[int, int]: ... -def urandom(n: int) -> bytes: ... - -if sys.platform == "win32": - def startfile(path: Text, operation: str | None = ...) -> None: ... - -else: - # Unix only - def spawnlp(mode: int, file: Text, arg0: bytes | Text, *args: bytes | Text) -> int: ... - def spawnlpe(mode: int, file: Text, arg0: bytes | Text, *args: Any) -> int: ... # Imprecise signature - def spawnvp(mode: int, file: Text, args: List[bytes | Text]) -> int: ... - def spawnvpe(mode: int, file: Text, args: List[bytes | Text], env: Mapping[str, str]) -> int: ... - def wait() -> Tuple[int, int]: ... - def wait3(options: int) -> Tuple[int, int, Any]: ... - def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... - def WCOREDUMP(status: int) -> bool: ... - def WIFCONTINUED(status: int) -> bool: ... - def WIFSTOPPED(status: int) -> bool: ... - def WIFSIGNALED(status: int) -> bool: ... - def WIFEXITED(status: int) -> bool: ... - def WEXITSTATUS(status: int) -> int: ... - def WSTOPSIG(status: int) -> int: ... - def WTERMSIG(status: int) -> int: ... - def confstr(name: str | int) -> str | None: ... - def getloadavg() -> Tuple[float, float, float]: ... - def sysconf(name: str | int) -> int: ... - -def tmpfile() -> IO[Any]: ... -def tmpnam() -> str: ... -def tempnam(dir: str = ..., prefix: str = ...) -> str: ... - -P_ALL: int -WEXITED: int -WNOWAIT: int diff --git a/stdlib/@python2/os/path.pyi b/stdlib/@python2/os/path.pyi deleted file mode 100644 index 2ce2f592f0e2..000000000000 --- a/stdlib/@python2/os/path.pyi +++ /dev/null @@ -1,84 +0,0 @@ -import os -import sys -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload - -_T = TypeVar("_T") - -# ----- os.path variables ----- -supports_unicode_filenames: bool -# aliases (also in os) -curdir: str -pardir: str -sep: str -if sys.platform == "win32": - altsep: str -else: - altsep: str | None -extsep: str -pathsep: str -defpath: str -devnull: str - -# ----- os.path function stubs ----- -def abspath(path: AnyStr) -> AnyStr: ... -def basename(p: AnyStr) -> AnyStr: ... -def dirname(p: AnyStr) -> AnyStr: ... -def expanduser(path: AnyStr) -> AnyStr: ... -def expandvars(path: AnyStr) -> AnyStr: ... -def normcase(s: AnyStr) -> AnyStr: ... -def normpath(path: AnyStr) -> AnyStr: ... - -if sys.platform == "win32": - def realpath(path: AnyStr) -> AnyStr: ... - -else: - def realpath(filename: AnyStr) -> AnyStr: ... - -# NOTE: Empty lists results in '' (str) regardless of contained type. -# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes -# So, fall back to Any -def commonprefix(m: Sequence[Text]) -> Any: ... -def exists(path: Text) -> bool: ... -def lexists(path: Text) -> bool: ... - -# These return float if os.stat_float_times() == True, -# but int is a subclass of float. -def getatime(filename: Text) -> float: ... -def getmtime(filename: Text) -> float: ... -def getctime(filename: Text) -> float: ... -def getsize(filename: Text) -> int: ... -def isabs(s: Text) -> bool: ... -def isfile(path: Text) -> bool: ... -def isdir(s: Text) -> bool: ... -def islink(path: Text) -> bool: ... -def ismount(path: Text) -> bool: ... - -# Make sure signatures are disjunct, and allow combinations of bytes and unicode. -# (Since Python 2 allows that, too) -# Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in -# a type error. -@overload -def join(__p1: bytes, *p: bytes) -> bytes: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... -@overload -def join(__p1: Text, *p: Text) -> Text: ... -@overload -def relpath(path: str, start: str | None = ...) -> str: ... -@overload -def relpath(path: Text, start: Text | None = ...) -> Text: ... -def samefile(f1: Text, f2: Text) -> bool: ... -def sameopenfile(fp1: int, fp2: int) -> bool: ... -def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/stdlib/@python2/os2emxpath.pyi b/stdlib/@python2/os2emxpath.pyi deleted file mode 100644 index 514db760886f..000000000000 --- a/stdlib/@python2/os2emxpath.pyi +++ /dev/null @@ -1,84 +0,0 @@ -import os -import sys -from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload - -_T = TypeVar("_T") - -# ----- os.path variables ----- -supports_unicode_filenames: bool -# aliases (also in os) -curdir: str -pardir: str -sep: str -if sys.platform == "win32": - altsep: str -else: - altsep: str | None -extsep: str -pathsep: str -defpath: str -devnull: str - -# ----- os.path function stubs ----- -def abspath(path: AnyStr) -> AnyStr: ... -def basename(p: AnyStr) -> AnyStr: ... -def dirname(p: AnyStr) -> AnyStr: ... -def expanduser(path: AnyStr) -> AnyStr: ... -def expandvars(path: AnyStr) -> AnyStr: ... -def normcase(s: AnyStr) -> AnyStr: ... -def normpath(path: AnyStr) -> AnyStr: ... - -if sys.platform == "win32": - def realpath(path: AnyStr) -> AnyStr: ... - -else: - def realpath(filename: AnyStr) -> AnyStr: ... - -# NOTE: Empty lists results in '' (str) regardless of contained type. -# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes -# So, fall back to Any -def commonprefix(m: Sequence[Text]) -> Any: ... -def lexists(path: Text) -> bool: ... - -# These return float if os.stat_float_times() == True, -# but int is a subclass of float. -def getatime(filename: Text) -> float: ... -def getmtime(filename: Text) -> float: ... -def getctime(filename: Text) -> float: ... -def getsize(filename: Text) -> int: ... -def isabs(s: Text) -> bool: ... -def isfile(path: Text) -> bool: ... -def isdir(s: Text) -> bool: ... -def islink(path: Text) -> bool: ... -def ismount(path: Text) -> bool: ... - -# Make sure signatures are disjunct, and allow combinations of bytes and unicode. -# (Since Python 2 allows that, too) -# Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in -# a type error. -@overload -def join(__p1: bytes, *p: bytes) -> bytes: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... -@overload -def join(__p1: Text, *p: Text) -> Text: ... -@overload -def relpath(path: str, start: str | None = ...) -> str: ... -@overload -def relpath(path: Text, start: Text | None = ...) -> Text: ... -def samefile(f1: Text, f2: Text) -> bool: ... -def sameopenfile(fp1: int, fp2: int) -> bool: ... -def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/stdlib/@python2/ossaudiodev.pyi b/stdlib/@python2/ossaudiodev.pyi deleted file mode 100644 index af3e2c210930..000000000000 --- a/stdlib/@python2/ossaudiodev.pyi +++ /dev/null @@ -1,131 +0,0 @@ -from typing import Any, List, overload -from typing_extensions import Literal - -AFMT_AC3: int -AFMT_A_LAW: int -AFMT_IMA_ADPCM: int -AFMT_MPEG: int -AFMT_MU_LAW: int -AFMT_QUERY: int -AFMT_S16_BE: int -AFMT_S16_LE: int -AFMT_S16_NE: int -AFMT_S8: int -AFMT_U16_BE: int -AFMT_U16_LE: int -AFMT_U8: int -SNDCTL_COPR_HALT: int -SNDCTL_COPR_LOAD: int -SNDCTL_COPR_RCODE: int -SNDCTL_COPR_RCVMSG: int -SNDCTL_COPR_RDATA: int -SNDCTL_COPR_RESET: int -SNDCTL_COPR_RUN: int -SNDCTL_COPR_SENDMSG: int -SNDCTL_COPR_WCODE: int -SNDCTL_COPR_WDATA: int -SNDCTL_DSP_BIND_CHANNEL: int -SNDCTL_DSP_CHANNELS: int -SNDCTL_DSP_GETBLKSIZE: int -SNDCTL_DSP_GETCAPS: int -SNDCTL_DSP_GETCHANNELMASK: int -SNDCTL_DSP_GETFMTS: int -SNDCTL_DSP_GETIPTR: int -SNDCTL_DSP_GETISPACE: int -SNDCTL_DSP_GETODELAY: int -SNDCTL_DSP_GETOPTR: int -SNDCTL_DSP_GETOSPACE: int -SNDCTL_DSP_GETSPDIF: int -SNDCTL_DSP_GETTRIGGER: int -SNDCTL_DSP_MAPINBUF: int -SNDCTL_DSP_MAPOUTBUF: int -SNDCTL_DSP_NONBLOCK: int -SNDCTL_DSP_POST: int -SNDCTL_DSP_PROFILE: int -SNDCTL_DSP_RESET: int -SNDCTL_DSP_SAMPLESIZE: int -SNDCTL_DSP_SETDUPLEX: int -SNDCTL_DSP_SETFMT: int -SNDCTL_DSP_SETFRAGMENT: int -SNDCTL_DSP_SETSPDIF: int -SNDCTL_DSP_SETSYNCRO: int -SNDCTL_DSP_SETTRIGGER: int -SNDCTL_DSP_SPEED: int -SNDCTL_DSP_STEREO: int -SNDCTL_DSP_SUBDIVIDE: int -SNDCTL_DSP_SYNC: int -SNDCTL_FM_4OP_ENABLE: int -SNDCTL_FM_LOAD_INSTR: int -SNDCTL_MIDI_INFO: int -SNDCTL_MIDI_MPUCMD: int -SNDCTL_MIDI_MPUMODE: int -SNDCTL_MIDI_PRETIME: int -SNDCTL_SEQ_CTRLRATE: int -SNDCTL_SEQ_GETINCOUNT: int -SNDCTL_SEQ_GETOUTCOUNT: int -SNDCTL_SEQ_GETTIME: int -SNDCTL_SEQ_NRMIDIS: int -SNDCTL_SEQ_NRSYNTHS: int -SNDCTL_SEQ_OUTOFBAND: int -SNDCTL_SEQ_PANIC: int -SNDCTL_SEQ_PERCMODE: int -SNDCTL_SEQ_RESET: int -SNDCTL_SEQ_RESETSAMPLES: int -SNDCTL_SEQ_SYNC: int -SNDCTL_SEQ_TESTMIDI: int -SNDCTL_SEQ_THRESHOLD: int -SNDCTL_SYNTH_CONTROL: int -SNDCTL_SYNTH_ID: int -SNDCTL_SYNTH_INFO: int -SNDCTL_SYNTH_MEMAVL: int -SNDCTL_SYNTH_REMOVESAMPLE: int -SNDCTL_TMR_CONTINUE: int -SNDCTL_TMR_METRONOME: int -SNDCTL_TMR_SELECT: int -SNDCTL_TMR_SOURCE: int -SNDCTL_TMR_START: int -SNDCTL_TMR_STOP: int -SNDCTL_TMR_TEMPO: int -SNDCTL_TMR_TIMEBASE: int -SOUND_MIXER_ALTPCM: int -SOUND_MIXER_BASS: int -SOUND_MIXER_CD: int -SOUND_MIXER_DIGITAL1: int -SOUND_MIXER_DIGITAL2: int -SOUND_MIXER_DIGITAL3: int -SOUND_MIXER_IGAIN: int -SOUND_MIXER_IMIX: int -SOUND_MIXER_LINE: int -SOUND_MIXER_LINE1: int -SOUND_MIXER_LINE2: int -SOUND_MIXER_LINE3: int -SOUND_MIXER_MIC: int -SOUND_MIXER_MONITOR: int -SOUND_MIXER_NRDEVICES: int -SOUND_MIXER_OGAIN: int -SOUND_MIXER_PCM: int -SOUND_MIXER_PHONEIN: int -SOUND_MIXER_PHONEOUT: int -SOUND_MIXER_RADIO: int -SOUND_MIXER_RECLEV: int -SOUND_MIXER_SPEAKER: int -SOUND_MIXER_SYNTH: int -SOUND_MIXER_TREBLE: int -SOUND_MIXER_VIDEO: int -SOUND_MIXER_VOLUME: int - -control_labels: List[str] -control_names: List[str] - -# TODO: oss_audio_device return type -@overload -def open(mode: Literal["r", "w", "rw"]) -> Any: ... -@overload -def open(device: str, mode: Literal["r", "w", "rw"]) -> Any: ... - -# TODO: oss_mixer_device return type -def openmixer(device: str = ...) -> Any: ... - -class OSSAudioError(Exception): ... - -error = OSSAudioError diff --git a/stdlib/@python2/parser.pyi b/stdlib/@python2/parser.pyi deleted file mode 100644 index ff8bf039ee80..000000000000 --- a/stdlib/@python2/parser.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from types import CodeType -from typing import Any, List, Sequence, Text, Tuple - -def expr(source: Text) -> STType: ... -def suite(source: Text) -> STType: ... -def sequence2st(sequence: Sequence[Any]) -> STType: ... -def tuple2st(sequence: Sequence[Any]) -> STType: ... -def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... -def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... -def compilest(st: STType, filename: Text = ...) -> CodeType: ... -def isexpr(st: STType) -> bool: ... -def issuite(st: STType) -> bool: ... - -class ParserError(Exception): ... - -class STType: - def compile(self, filename: Text = ...) -> CodeType: ... - def isexpr(self) -> bool: ... - def issuite(self) -> bool: ... - def tolist(self, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... - def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... diff --git a/stdlib/@python2/pdb.pyi b/stdlib/@python2/pdb.pyi deleted file mode 100644 index 6d3a6d5c5903..000000000000 --- a/stdlib/@python2/pdb.pyi +++ /dev/null @@ -1,165 +0,0 @@ -from bdb import Bdb -from cmd import Cmd -from types import FrameType, TracebackType -from typing import IO, Any, Callable, ClassVar, Dict, Iterable, List, Mapping, Tuple, TypeVar - -_T = TypeVar("_T") - -line_prefix: str # undocumented - -class Restart(Exception): ... - -def run(statement: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... -def runeval(expression: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... -def runctx(statement: str, globals: Dict[str, Any], locals: Mapping[str, Any]) -> None: ... -def runcall(func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... -def set_trace() -> None: ... -def post_mortem(t: TracebackType | None = ...) -> None: ... -def pm() -> None: ... - -class Pdb(Bdb, Cmd): - # Everything here is undocumented, except for __init__ - - commands_resuming: ClassVar[List[str]] - - aliases: Dict[str, str] - mainpyfile: str - _wait_for_mainpyfile: bool - rcLines: List[str] - commands: Dict[int, List[str]] - commands_doprompt: Dict[int, bool] - commands_silent: Dict[int, bool] - commands_defining: bool - commands_bnum: int | None - lineno: int | None - stack: List[Tuple[FrameType, int]] - curindex: int - curframe: FrameType | None - curframe_locals: Mapping[str, Any] - def __init__( - self, completekey: str = ..., stdin: IO[str] | None = ..., stdout: IO[str] | None = ..., skip: Iterable[str] | None = ... - ) -> None: ... - def forget(self) -> None: ... - def setup(self, f: FrameType | None, tb: TracebackType | None) -> None: ... - def execRcLines(self) -> None: ... - def bp_commands(self, frame: FrameType) -> bool: ... - def interaction(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ... - def displayhook(self, obj: object) -> None: ... - def handle_command_def(self, line: str) -> bool: ... - def defaultFile(self) -> str: ... - def lineinfo(self, identifier: str) -> Tuple[None, None, None] | Tuple[str, str, int]: ... - def checkline(self, filename: str, lineno: int) -> int: ... - def _getval(self, arg: str) -> object: ... - def print_stack_trace(self) -> None: ... - def print_stack_entry(self, frame_lineno: Tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... - def lookupmodule(self, filename: str) -> str | None: ... - def _runscript(self, filename: str) -> None: ... - def do_commands(self, arg: str) -> bool | None: ... - def do_break(self, arg: str, temporary: bool = ...) -> bool | None: ... - def do_tbreak(self, arg: str) -> bool | None: ... - def do_enable(self, arg: str) -> bool | None: ... - def do_disable(self, arg: str) -> bool | None: ... - def do_condition(self, arg: str) -> bool | None: ... - def do_ignore(self, arg: str) -> bool | None: ... - def do_clear(self, arg: str) -> bool | None: ... - def do_where(self, arg: str) -> bool | None: ... - def do_up(self, arg: str) -> bool | None: ... - def do_down(self, arg: str) -> bool | None: ... - def do_until(self, arg: str) -> bool | None: ... - def do_step(self, arg: str) -> bool | None: ... - def do_next(self, arg: str) -> bool | None: ... - def do_run(self, arg: str) -> bool | None: ... - def do_return(self, arg: str) -> bool | None: ... - def do_continue(self, arg: str) -> bool | None: ... - def do_jump(self, arg: str) -> bool | None: ... - def do_debug(self, arg: str) -> bool | None: ... - def do_quit(self, arg: str) -> bool | None: ... - def do_EOF(self, arg: str) -> bool | None: ... - def do_args(self, arg: str) -> bool | None: ... - def do_retval(self, arg: str) -> bool | None: ... - def do_p(self, arg: str) -> bool | None: ... - def do_pp(self, arg: str) -> bool | None: ... - def do_list(self, arg: str) -> bool | None: ... - def do_whatis(self, arg: str) -> bool | None: ... - def do_alias(self, arg: str) -> bool | None: ... - def do_unalias(self, arg: str) -> bool | None: ... - def do_help(self, arg: str) -> bool | None: ... - do_b = do_break - do_cl = do_clear - do_w = do_where - do_bt = do_where - do_u = do_up - do_d = do_down - do_unt = do_until - do_s = do_step - do_n = do_next - do_restart = do_run - do_r = do_return - do_c = do_continue - do_cont = do_continue - do_j = do_jump - do_q = do_quit - do_exit = do_quit - do_a = do_args - do_rv = do_retval - do_l = do_list - do_h = do_help - def help_exec(self) -> None: ... - def help_pdb(self) -> None: ... - def help_help(self) -> None: ... - def help_h(self) -> None: ... - def help_where(self) -> None: ... - def help_w(self) -> None: ... - def help_down(self) -> None: ... - def help_d(self) -> None: ... - def help_up(self) -> None: ... - def help_u(self) -> None: ... - def help_break(self) -> None: ... - def help_b(self) -> None: ... - def help_clear(self) -> None: ... - def help_cl(self) -> None: ... - def help_tbreak(self) -> None: ... - def help_enable(self) -> None: ... - def help_disable(self) -> None: ... - def help_ignore(self) -> None: ... - def help_condition(self) -> None: ... - def help_step(self) -> None: ... - def help_s(self) -> None: ... - def help_until(self) -> None: ... - def help_unt(self) -> None: ... - def help_next(self) -> None: ... - def help_n(self) -> None: ... - def help_return(self) -> None: ... - def help_r(self) -> None: ... - def help_continue(self) -> None: ... - def help_cont(self) -> None: ... - def help_c(self) -> None: ... - def help_jump(self) -> None: ... - def help_j(self) -> None: ... - def help_debug(self) -> None: ... - def help_list(self) -> None: ... - def help_l(self) -> None: ... - def help_args(self) -> None: ... - def help_a(self) -> None: ... - def help_p(self) -> None: ... - def help_pp(self) -> None: ... - def help_run(self) -> None: ... - def help_quit(self) -> None: ... - def help_q(self) -> None: ... - def help_whatis(self) -> None: ... - def help_EOF(self) -> None: ... - def help_alias(self) -> None: ... - def help_unalias(self) -> None: ... - def help_commands(self) -> None: ... - help_bt = help_w - help_restart = help_run - help_exit = help_q - -# undocumented - -def find_function(funcname: str, filename: str) -> Tuple[str, str, int] | None: ... -def main() -> None: ... -def help() -> None: ... - -class _rstr(str): - def __repr__(self) -> _rstr: ... diff --git a/stdlib/@python2/pickle.pyi b/stdlib/@python2/pickle.pyi deleted file mode 100644 index 07e32e64b449..000000000000 --- a/stdlib/@python2/pickle.pyi +++ /dev/null @@ -1,95 +0,0 @@ -from typing import IO, Any, Callable, Iterator, Optional, Tuple, Type, Union - -HIGHEST_PROTOCOL: int -bytes_types: Tuple[Type[Any], ...] # undocumented - -def dump(obj: Any, file: IO[bytes], protocol: int | None = ...) -> None: ... -def dumps(obj: Any, protocol: int | None = ...) -> bytes: ... -def load(file: IO[bytes]) -> Any: ... -def loads(string: bytes) -> Any: ... - -class PickleError(Exception): ... -class PicklingError(PickleError): ... -class UnpicklingError(PickleError): ... - -_reducedtype = Union[ - str, - Tuple[Callable[..., Any], Tuple[Any, ...]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], -] - -class Pickler: - fast: bool - def __init__(self, file: IO[bytes], protocol: int | None = ...) -> None: ... - def dump(self, __obj: Any) -> None: ... - def clear_memo(self) -> None: ... - def persistent_id(self, obj: Any) -> Any: ... - -class Unpickler: - def __init__(self, file: IO[bytes]) -> None: ... - def load(self) -> Any: ... - def find_class(self, __module_name: str, __global_name: str) -> Any: ... - -MARK: bytes -STOP: bytes -POP: bytes -POP_MARK: bytes -DUP: bytes -FLOAT: bytes -INT: bytes -BININT: bytes -BININT1: bytes -LONG: bytes -BININT2: bytes -NONE: bytes -PERSID: bytes -BINPERSID: bytes -REDUCE: bytes -STRING: bytes -BINSTRING: bytes -SHORT_BINSTRING: bytes -UNICODE: bytes -BINUNICODE: bytes -APPEND: bytes -BUILD: bytes -GLOBAL: bytes -DICT: bytes -EMPTY_DICT: bytes -APPENDS: bytes -GET: bytes -BINGET: bytes -INST: bytes -LONG_BINGET: bytes -LIST: bytes -EMPTY_LIST: bytes -OBJ: bytes -PUT: bytes -BINPUT: bytes -LONG_BINPUT: bytes -SETITEM: bytes -TUPLE: bytes -EMPTY_TUPLE: bytes -SETITEMS: bytes -BINFLOAT: bytes - -TRUE: bytes -FALSE: bytes - -# protocol 2 -PROTO: bytes -NEWOBJ: bytes -EXT1: bytes -EXT2: bytes -EXT4: bytes -TUPLE1: bytes -TUPLE2: bytes -TUPLE3: bytes -NEWTRUE: bytes -NEWFALSE: bytes -LONG1: bytes -LONG4: bytes - -def encode_long(x: int) -> bytes: ... # undocumented -def decode_long(data: bytes) -> int: ... # undocumented diff --git a/stdlib/@python2/pickletools.pyi b/stdlib/@python2/pickletools.pyi deleted file mode 100644 index 14ec0fdff03a..000000000000 --- a/stdlib/@python2/pickletools.pyi +++ /dev/null @@ -1,124 +0,0 @@ -from typing import IO, Any, Callable, Iterator, List, MutableMapping, Text, Tuple, Type - -_Reader = Callable[[IO[bytes]], Any] - -UP_TO_NEWLINE: int -TAKEN_FROM_ARGUMENT1: int -TAKEN_FROM_ARGUMENT4: int - -class ArgumentDescriptor(object): - name: str - n: int - reader: _Reader - doc: str - def __init__(self, name: str, n: int, reader: _Reader, doc: str) -> None: ... - -def read_uint1(f: IO[bytes]) -> int: ... - -uint1: ArgumentDescriptor - -def read_uint2(f: IO[bytes]) -> int: ... - -uint2: ArgumentDescriptor - -def read_int4(f: IO[bytes]) -> int: ... - -int4: ArgumentDescriptor - -def read_stringnl(f: IO[bytes], decode: bool = ..., stripquotes: bool = ...) -> bytes | Text: ... - -stringnl: ArgumentDescriptor - -def read_stringnl_noescape(f: IO[bytes]) -> str: ... - -stringnl_noescape: ArgumentDescriptor - -def read_stringnl_noescape_pair(f: IO[bytes]) -> Text: ... - -stringnl_noescape_pair: ArgumentDescriptor - -def read_string1(f: IO[bytes]) -> str: ... - -string1: ArgumentDescriptor - -def read_string4(f: IO[bytes]) -> str: ... - -string4: ArgumentDescriptor - -def read_unicodestringnl(f: IO[bytes]) -> Text: ... - -unicodestringnl: ArgumentDescriptor - -def read_unicodestring4(f: IO[bytes]) -> Text: ... - -unicodestring4: ArgumentDescriptor - -def read_decimalnl_short(f: IO[bytes]) -> int: ... -def read_decimalnl_long(f: IO[bytes]) -> int: ... - -decimalnl_short: ArgumentDescriptor -decimalnl_long: ArgumentDescriptor - -def read_floatnl(f: IO[bytes]) -> float: ... - -floatnl: ArgumentDescriptor - -def read_float8(f: IO[bytes]) -> float: ... - -float8: ArgumentDescriptor - -def read_long1(f: IO[bytes]) -> int: ... - -long1: ArgumentDescriptor - -def read_long4(f: IO[bytes]) -> int: ... - -long4: ArgumentDescriptor - -class StackObject(object): - name: str - obtype: Type[Any] | Tuple[Type[Any], ...] - doc: str - def __init__(self, name: str, obtype: Type[Any] | Tuple[Type[Any], ...], doc: str) -> None: ... - -pyint: StackObject -pylong: StackObject -pyinteger_or_bool: StackObject -pybool: StackObject -pyfloat: StackObject -pystring: StackObject -pyunicode: StackObject -pynone: StackObject -pytuple: StackObject -pylist: StackObject -pydict: StackObject -anyobject: StackObject -markobject: StackObject -stackslice: StackObject - -class OpcodeInfo(object): - name: str - code: str - arg: ArgumentDescriptor | None - stack_before: List[StackObject] - stack_after: List[StackObject] - proto: int - doc: str - def __init__( - self, - name: str, - code: str, - arg: ArgumentDescriptor | None, - stack_before: List[StackObject], - stack_after: List[StackObject], - proto: int, - doc: str, - ) -> None: ... - -opcodes: List[OpcodeInfo] - -def genops(pickle: bytes | IO[bytes]) -> Iterator[Tuple[OpcodeInfo, Any | None, int | None]]: ... -def optimize(p: bytes | IO[bytes]) -> bytes: ... -def dis( - pickle: bytes | IO[bytes], out: IO[str] | None = ..., memo: MutableMapping[int, Any] | None = ..., indentlevel: int = ... -) -> None: ... diff --git a/stdlib/@python2/pipes.pyi b/stdlib/@python2/pipes.pyi deleted file mode 100644 index 5249543425c6..000000000000 --- a/stdlib/@python2/pipes.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import IO, Any, AnyStr - -class Template: - def __init__(self) -> None: ... - def reset(self) -> None: ... - def clone(self) -> Template: ... - def debug(self, flag: bool) -> None: ... - def append(self, cmd: str, kind: str) -> None: ... - def prepend(self, cmd: str, kind: str) -> None: ... - def open(self, file: str, mode: str) -> IO[Any]: ... - def copy(self, infile: str, outfile: str) -> None: ... - -def quote(s: AnyStr) -> AnyStr: ... diff --git a/stdlib/@python2/pkgutil.pyi b/stdlib/@python2/pkgutil.pyi deleted file mode 100644 index fd42af916cfe..000000000000 --- a/stdlib/@python2/pkgutil.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from _typeshed import SupportsRead -from typing import IO, Any, Callable, Iterable, Iterator, List, Tuple, Union - -Loader = Any -MetaPathFinder = Any -PathEntryFinder = Any - -_ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] - -def extend_path(path: List[str], name: str) -> List[str]: ... - -class ImpImporter: - def __init__(self, path: str | None = ...) -> None: ... - -class ImpLoader: - def __init__(self, fullname: str, file: IO[str], filename: str, etc: Tuple[str, str, int]) -> None: ... - -def find_loader(fullname: str) -> Loader | None: ... -def get_importer(path_item: str) -> PathEntryFinder | None: ... -def get_loader(module_or_name: str) -> Loader: ... -def iter_importers(fullname: str = ...) -> Iterator[MetaPathFinder | PathEntryFinder]: ... -def iter_modules(path: Iterable[str] | None = ..., prefix: str = ...) -> Iterator[_ModuleInfoLike]: ... -def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented -def walk_packages( - path: Iterable[str] | None = ..., prefix: str = ..., onerror: Callable[[str], None] | None = ... -) -> Iterator[_ModuleInfoLike]: ... -def get_data(package: str, resource: str) -> bytes | None: ... diff --git a/stdlib/@python2/platform.pyi b/stdlib/@python2/platform.pyi deleted file mode 100644 index b984a2b2d3d5..000000000000 --- a/stdlib/@python2/platform.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Any, Tuple - -__copyright__: Any -DEV_NULL: Any - -def libc_ver(executable=..., lib=..., version=..., chunksize: int = ...): ... -def linux_distribution(distname=..., version=..., id=..., supported_dists=..., full_distribution_name: int = ...): ... -def dist(distname=..., version=..., id=..., supported_dists=...): ... - -class _popen: - tmpfile: Any - pipe: Any - bufsize: Any - mode: Any - def __init__(self, cmd, mode=..., bufsize: Any | None = ...): ... - def read(self): ... - def readlines(self): ... - def close(self, remove=..., error=...): ... - __del__: Any - -def popen(cmd, mode=..., bufsize: Any | None = ...): ... -def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> Tuple[str, str, str, str]: ... -def mac_ver( - release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ... -) -> Tuple[str, Tuple[str, str, str], str]: ... -def java_ver( - release: str = ..., vendor: str = ..., vminfo: Tuple[str, str, str] = ..., osinfo: Tuple[str, str, str] = ... -) -> Tuple[str, str, Tuple[str, str, str], Tuple[str, str, str]]: ... -def system_alias(system, release, version): ... -def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... -def uname() -> Tuple[str, str, str, str, str, str]: ... -def system() -> str: ... -def node() -> str: ... -def release() -> str: ... -def version() -> str: ... -def machine() -> str: ... -def processor() -> str: ... -def python_implementation() -> str: ... -def python_version() -> str: ... -def python_version_tuple() -> Tuple[str, str, str]: ... -def python_branch() -> str: ... -def python_revision() -> str: ... -def python_build() -> Tuple[str, str]: ... -def python_compiler() -> str: ... -def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/stdlib/@python2/plistlib.pyi b/stdlib/@python2/plistlib.pyi deleted file mode 100644 index d815e3c35404..000000000000 --- a/stdlib/@python2/plistlib.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from typing import IO, Any, Dict as DictT, Mapping, Text, Union - -_Path = Union[str, Text] - -def readPlist(pathOrFile: _Path | IO[bytes]) -> Any: ... -def writePlist(value: Mapping[str, Any], pathOrFile: _Path | IO[bytes]) -> None: ... -def readPlistFromBytes(data: bytes) -> Any: ... -def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... -def readPlistFromResource(path: _Path, restype: str = ..., resid: int = ...) -> Any: ... -def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, restype: str = ..., resid: int = ...) -> None: ... -def readPlistFromString(data: str) -> Any: ... -def writePlistToString(rootObject: Mapping[str, Any]) -> str: ... - -class Dict(DictT[str, Any]): - def __getattr__(self, attr: str) -> Any: ... - def __setattr__(self, attr: str, value: Any) -> None: ... - def __delattr__(self, attr: str) -> None: ... - -class Data: - data: bytes - def __init__(self, data: bytes) -> None: ... - -class InvalidFileException(ValueError): - def __init__(self, message: str = ...) -> None: ... diff --git a/stdlib/@python2/popen2.pyi b/stdlib/@python2/popen2.pyi deleted file mode 100644 index 0efee4e6d271..000000000000 --- a/stdlib/@python2/popen2.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any, Iterable, TextIO, Tuple, TypeVar - -_T = TypeVar("_T") - -class Popen3: - sts: int - cmd: Iterable[Any] - pid: int - tochild: TextIO - fromchild: TextIO - childerr: TextIO | None - def __init__(self, cmd: Iterable[Any] = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ... - def __del__(self) -> None: ... - def poll(self, _deadstate: _T = ...) -> int | _T: ... - def wait(self) -> int: ... - -class Popen4(Popen3): - childerr: None - cmd: Iterable[Any] - pid: int - tochild: TextIO - fromchild: TextIO - def __init__(self, cmd: Iterable[Any] = ..., bufsize: int = ...) -> None: ... - -def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... -def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... -def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... diff --git a/stdlib/@python2/poplib.pyi b/stdlib/@python2/poplib.pyi deleted file mode 100644 index 7a71f9850dfe..000000000000 --- a/stdlib/@python2/poplib.pyi +++ /dev/null @@ -1,45 +0,0 @@ -import socket -from typing import Any, BinaryIO, List, Pattern, Text, Tuple, overload - -_LongResp = Tuple[bytes, List[bytes], int] - -class error_proto(Exception): ... - -POP3_PORT: int -POP3_SSL_PORT: int -CR: bytes -LF: bytes -CRLF: bytes - -class POP3: - host: Text - port: int - sock: socket.socket - file: BinaryIO - welcome: bytes - def __init__(self, host: Text, port: int = ..., timeout: float = ...) -> None: ... - def getwelcome(self) -> bytes: ... - def set_debuglevel(self, level: int) -> None: ... - def user(self, user: Text) -> bytes: ... - def pass_(self, pswd: Text) -> bytes: ... - def stat(self) -> Tuple[int, int]: ... - def list(self, which: Any | None = ...) -> _LongResp: ... - def retr(self, which: Any) -> _LongResp: ... - def dele(self, which: Any) -> bytes: ... - def noop(self) -> bytes: ... - def rset(self) -> bytes: ... - def quit(self) -> bytes: ... - def close(self) -> None: ... - def rpop(self, user: Text) -> bytes: ... - timestamp: Pattern[Text] - def apop(self, user: Text, secret: Text) -> bytes: ... - def top(self, which: Any, howmuch: int) -> _LongResp: ... - @overload - def uidl(self) -> _LongResp: ... - @overload - def uidl(self, which: Any) -> bytes: ... - -class POP3_SSL(POP3): - def __init__( - self, host: Text, port: int = ..., keyfile: Text | None = ..., certfile: Text | None = ..., timeout: float = ... - ) -> None: ... diff --git a/stdlib/@python2/posix.pyi b/stdlib/@python2/posix.pyi deleted file mode 100644 index c39ce325289b..000000000000 --- a/stdlib/@python2/posix.pyi +++ /dev/null @@ -1,201 +0,0 @@ -from _typeshed import FileDescriptorLike -from typing import IO, AnyStr, Dict, List, Mapping, NamedTuple, Sequence, Tuple, TypeVar - -error = OSError - -confstr_names: Dict[str, int] -environ: Dict[str, str] -pathconf_names: Dict[str, int] -sysconf_names: Dict[str, int] - -_T = TypeVar("_T") - -EX_CANTCREAT: int -EX_CONFIG: int -EX_DATAERR: int -EX_IOERR: int -EX_NOHOST: int -EX_NOINPUT: int -EX_NOPERM: int -EX_NOUSER: int -EX_OK: int -EX_OSERR: int -EX_OSFILE: int -EX_PROTOCOL: int -EX_SOFTWARE: int -EX_TEMPFAIL: int -EX_UNAVAILABLE: int -EX_USAGE: int -F_OK: int -NGROUPS_MAX: int -O_APPEND: int -O_ASYNC: int -O_CREAT: int -O_DIRECT: int -O_DIRECTORY: int -O_DSYNC: int -O_EXCL: int -O_LARGEFILE: int -O_NDELAY: int -O_NOATIME: int -O_NOCTTY: int -O_NOFOLLOW: int -O_NONBLOCK: int -O_RDONLY: int -O_RDWR: int -O_RSYNC: int -O_SYNC: int -O_TRUNC: int -O_WRONLY: int -R_OK: int -TMP_MAX: int -WCONTINUED: int -WNOHANG: int -WUNTRACED: int -W_OK: int -X_OK: int - -def WCOREDUMP(status: int) -> bool: ... -def WEXITSTATUS(status: int) -> bool: ... -def WIFCONTINUED(status: int) -> bool: ... -def WIFEXITED(status: int) -> bool: ... -def WIFSIGNALED(status: int) -> bool: ... -def WIFSTOPPED(status: int) -> bool: ... -def WSTOPSIG(status: int) -> bool: ... -def WTERMSIG(status: int) -> bool: ... - -class stat_result(object): - n_fields: int - n_sequence_fields: int - n_unnamed_fields: int - st_mode: int - st_ino: int - st_dev: int - st_nlink: int - st_uid: int - st_gid: int - st_size: int - st_atime: int - st_mtime: int - st_ctime: int - -class statvfs_result(NamedTuple): - f_bsize: int - f_frsize: int - f_blocks: int - f_bfree: int - f_bavail: int - f_files: int - f_ffree: int - f_favail: int - f_flag: int - f_namemax: int - -def _exit(status: int) -> None: ... -def abort() -> None: ... -def access(path: unicode, mode: int) -> bool: ... -def chdir(path: unicode) -> None: ... -def chmod(path: unicode, mode: int) -> None: ... -def chown(path: unicode, uid: int, gid: int) -> None: ... -def chroot(path: unicode) -> None: ... -def close(fd: int) -> None: ... -def closerange(fd_low: int, fd_high: int) -> None: ... -def confstr(name: str | int) -> str: ... -def ctermid() -> str: ... -def dup(fd: int) -> int: ... -def dup2(fd: int, fd2: int) -> None: ... -def execv(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... -def execve(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... -def fchdir(fd: FileDescriptorLike) -> None: ... -def fchmod(fd: int, mode: int) -> None: ... -def fchown(fd: int, uid: int, gid: int) -> None: ... -def fdatasync(fd: FileDescriptorLike) -> None: ... -def fdopen(fd: int, mode: str = ..., bufsize: int = ...) -> IO[str]: ... -def fork() -> int: ... -def forkpty() -> Tuple[int, int]: ... -def fpathconf(fd: int, name: str) -> None: ... -def fstat(fd: int) -> stat_result: ... -def fstatvfs(fd: int) -> statvfs_result: ... -def fsync(fd: FileDescriptorLike) -> None: ... -def ftruncate(fd: int, length: int) -> None: ... -def getcwd() -> str: ... -def getcwdu() -> unicode: ... -def getegid() -> int: ... -def geteuid() -> int: ... -def getgid() -> int: ... -def getgroups() -> List[int]: ... -def getloadavg() -> Tuple[float, float, float]: ... -def getlogin() -> str: ... -def getpgid(pid: int) -> int: ... -def getpgrp() -> int: ... -def getpid() -> int: ... -def getppid() -> int: ... -def getresgid() -> Tuple[int, int, int]: ... -def getresuid() -> Tuple[int, int, int]: ... -def getsid(pid: int) -> int: ... -def getuid() -> int: ... -def initgroups(username: str, gid: int) -> None: ... -def isatty(fd: int) -> bool: ... -def kill(pid: int, sig: int) -> None: ... -def killpg(pgid: int, sig: int) -> None: ... -def lchown(path: unicode, uid: int, gid: int) -> None: ... -def link(source: unicode, link_name: str) -> None: ... -def listdir(path: AnyStr) -> List[AnyStr]: ... -def lseek(fd: int, pos: int, how: int) -> None: ... -def lstat(path: unicode) -> stat_result: ... -def major(device: int) -> int: ... -def makedev(major: int, minor: int) -> int: ... -def minor(device: int) -> int: ... -def mkdir(path: unicode, mode: int = ...) -> None: ... -def mkfifo(path: unicode, mode: int = ...) -> None: ... -def mknod(filename: unicode, mode: int = ..., device: int = ...) -> None: ... -def nice(increment: int) -> int: ... -def open(file: unicode, flags: int, mode: int = ...) -> int: ... -def openpty() -> Tuple[int, int]: ... -def pathconf(path: unicode, name: str) -> str: ... -def pipe() -> Tuple[int, int]: ... -def popen(command: str, mode: str = ..., bufsize: int = ...) -> IO[str]: ... -def putenv(varname: str, value: str) -> None: ... -def read(fd: int, n: int) -> str: ... -def readlink(path: _T) -> _T: ... -def remove(path: unicode) -> None: ... -def rename(src: unicode, dst: unicode) -> None: ... -def rmdir(path: unicode) -> None: ... -def setegid(egid: int) -> None: ... -def seteuid(euid: int) -> None: ... -def setgid(gid: int) -> None: ... -def setgroups(groups: Sequence[int]) -> None: ... -def setpgid(pid: int, pgrp: int) -> None: ... -def setpgrp() -> None: ... -def setregid(rgid: int, egid: int) -> None: ... -def setresgid(rgid: int, egid: int, sgid: int) -> None: ... -def setresuid(ruid: int, euid: int, suid: int) -> None: ... -def setreuid(ruid: int, euid: int) -> None: ... -def setsid() -> None: ... -def setuid(pid: int) -> None: ... -def stat(path: unicode) -> stat_result: ... -def statvfs(path: unicode) -> statvfs_result: ... -def stat_float_times(fd: int) -> None: ... -def strerror(code: int) -> str: ... -def symlink(source: unicode, link_name: unicode) -> None: ... -def sysconf(name: str | int) -> int: ... -def system(command: unicode) -> int: ... -def tcgetpgrp(fd: int) -> int: ... -def tcsetpgrp(fd: int, pg: int) -> None: ... -def times() -> Tuple[float, float, float, float, float]: ... -def tmpfile() -> IO[str]: ... -def ttyname(fd: int) -> str: ... -def umask(mask: int) -> int: ... -def uname() -> Tuple[str, str, str, str, str]: ... -def unlink(path: unicode) -> None: ... -def unsetenv(varname: str) -> None: ... -def urandom(n: int) -> str: ... -def utime(path: unicode, times: Tuple[int, int] | None) -> None: ... -def wait() -> int: ... - -_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] - -def wait3(options: int) -> Tuple[int, int, _r]: ... -def wait4(pid: int, options: int) -> Tuple[int, int, _r]: ... -def waitpid(pid: int, options: int) -> int: ... -def write(fd: int, str: str) -> int: ... diff --git a/stdlib/@python2/posixpath.pyi b/stdlib/@python2/posixpath.pyi deleted file mode 100644 index 514db760886f..000000000000 --- a/stdlib/@python2/posixpath.pyi +++ /dev/null @@ -1,84 +0,0 @@ -import os -import sys -from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload - -_T = TypeVar("_T") - -# ----- os.path variables ----- -supports_unicode_filenames: bool -# aliases (also in os) -curdir: str -pardir: str -sep: str -if sys.platform == "win32": - altsep: str -else: - altsep: str | None -extsep: str -pathsep: str -defpath: str -devnull: str - -# ----- os.path function stubs ----- -def abspath(path: AnyStr) -> AnyStr: ... -def basename(p: AnyStr) -> AnyStr: ... -def dirname(p: AnyStr) -> AnyStr: ... -def expanduser(path: AnyStr) -> AnyStr: ... -def expandvars(path: AnyStr) -> AnyStr: ... -def normcase(s: AnyStr) -> AnyStr: ... -def normpath(path: AnyStr) -> AnyStr: ... - -if sys.platform == "win32": - def realpath(path: AnyStr) -> AnyStr: ... - -else: - def realpath(filename: AnyStr) -> AnyStr: ... - -# NOTE: Empty lists results in '' (str) regardless of contained type. -# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes -# So, fall back to Any -def commonprefix(m: Sequence[Text]) -> Any: ... -def lexists(path: Text) -> bool: ... - -# These return float if os.stat_float_times() == True, -# but int is a subclass of float. -def getatime(filename: Text) -> float: ... -def getmtime(filename: Text) -> float: ... -def getctime(filename: Text) -> float: ... -def getsize(filename: Text) -> int: ... -def isabs(s: Text) -> bool: ... -def isfile(path: Text) -> bool: ... -def isdir(s: Text) -> bool: ... -def islink(path: Text) -> bool: ... -def ismount(path: Text) -> bool: ... - -# Make sure signatures are disjunct, and allow combinations of bytes and unicode. -# (Since Python 2 allows that, too) -# Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in -# a type error. -@overload -def join(__p1: bytes, *p: bytes) -> bytes: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... -@overload -def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... -@overload -def join(__p1: Text, *p: Text) -> Text: ... -@overload -def relpath(path: str, start: str | None = ...) -> str: ... -@overload -def relpath(path: Text, start: Text | None = ...) -> Text: ... -def samefile(f1: Text, f2: Text) -> bool: ... -def sameopenfile(fp1: int, fp2: int) -> bool: ... -def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/stdlib/@python2/pprint.pyi b/stdlib/@python2/pprint.pyi deleted file mode 100644 index 407a9afb8e47..000000000000 --- a/stdlib/@python2/pprint.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import IO, Any, Dict, Tuple - -def pformat(object: object, indent: int = ..., width: int = ..., depth: int | None = ...) -> str: ... -def pprint( - object: object, stream: IO[str] | None = ..., indent: int = ..., width: int = ..., depth: int | None = ... -) -> None: ... -def isreadable(object: object) -> bool: ... -def isrecursive(object: object) -> bool: ... -def saferepr(object: object) -> str: ... - -class PrettyPrinter: - def __init__(self, indent: int = ..., width: int = ..., depth: int | None = ..., stream: IO[str] | None = ...) -> None: ... - def pformat(self, object: object) -> str: ... - def pprint(self, object: object) -> None: ... - def isreadable(self, object: object) -> bool: ... - def isrecursive(self, object: object) -> bool: ... - def format(self, object: object, context: Dict[int, Any], maxlevels: int, level: int) -> Tuple[str, bool, bool]: ... diff --git a/stdlib/@python2/profile.pyi b/stdlib/@python2/profile.pyi deleted file mode 100644 index 08e9b906dd0d..000000000000 --- a/stdlib/@python2/profile.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any, Callable, Dict, Text, Tuple, TypeVar - -def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... -def runctx( - statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: str | None = ..., sort: str | int = ... -) -> None: ... - -_SelfT = TypeVar("_SelfT", bound=Profile) -_T = TypeVar("_T") -_Label = Tuple[str, int, str] - -class Profile: - bias: int - stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented - def __init__(self, timer: Callable[[], float] | None = ..., bias: int | None = ...) -> None: ... - def set_cmd(self, cmd: str) -> None: ... - def simulate_call(self, name: str) -> None: ... - def simulate_cmd_complete(self) -> None: ... - def print_stats(self, sort: str | int = ...) -> None: ... - def dump_stats(self, file: Text) -> None: ... - def create_stats(self) -> None: ... - def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... - def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/stdlib/@python2/pstats.pyi b/stdlib/@python2/pstats.pyi deleted file mode 100644 index cecd1e84e305..000000000000 --- a/stdlib/@python2/pstats.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from cProfile import Profile as _cProfile -from profile import Profile -from typing import IO, Any, Dict, Iterable, List, Text, Tuple, TypeVar, Union, overload - -_Selector = Union[str, float, int] -_T = TypeVar("_T", bound=Stats) - -class Stats: - sort_arg_dict_default: Dict[str, Tuple[Any, str]] - def __init__( - self: _T, - __arg: None | str | Text | Profile | _cProfile = ..., - *args: None | str | Text | Profile | _cProfile | _T, - stream: IO[Any] | None = ..., - ) -> None: ... - def init(self, arg: None | str | Text | Profile | _cProfile) -> None: ... - def load_stats(self, arg: None | str | Text | Profile | _cProfile) -> None: ... - def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Text | Profile | _cProfile | _T) -> _T: ... - def dump_stats(self, filename: Text) -> None: ... - def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ... - @overload - def sort_stats(self: _T, field: int) -> _T: ... - @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... - def calc_callees(self) -> None: ... - def eval_print_amount(self, sel: _Selector, list: List[str], msg: str) -> Tuple[List[str], str]: ... - def get_print_list(self, sel_list: Iterable[_Selector]) -> Tuple[int, List[str]]: ... - def print_stats(self: _T, *amount: _Selector) -> _T: ... - def print_callees(self: _T, *amount: _Selector) -> _T: ... - def print_callers(self: _T, *amount: _Selector) -> _T: ... - def print_call_heading(self, name_size: int, column_title: str) -> None: ... - def print_call_line(self, name_size: int, source: str, call_dict: Dict[str, Any], arrow: str = ...) -> None: ... - def print_title(self) -> None: ... - def print_line(self, func: str) -> None: ... diff --git a/stdlib/@python2/pty.pyi b/stdlib/@python2/pty.pyi deleted file mode 100644 index e8afa2df5166..000000000000 --- a/stdlib/@python2/pty.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Callable, Iterable, Tuple - -_Reader = Callable[[int], bytes] - -STDIN_FILENO: int -STDOUT_FILENO: int -STDERR_FILENO: int - -CHILD: int - -def openpty() -> Tuple[int, int]: ... -def master_open() -> Tuple[int, str]: ... -def slave_open(tty_name: str) -> int: ... -def fork() -> Tuple[int, int]: ... -def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... diff --git a/stdlib/@python2/pwd.pyi b/stdlib/@python2/pwd.pyi deleted file mode 100644 index 83020c1576dd..000000000000 --- a/stdlib/@python2/pwd.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import List, Tuple - -class struct_passwd(Tuple[str, str, int, int, str, str, str]): - pw_name: str - pw_passwd: str - pw_uid: int - pw_gid: int - pw_gecos: str - pw_dir: str - pw_shell: str - -def getpwall() -> List[struct_passwd]: ... -def getpwuid(__uid: int) -> struct_passwd: ... -def getpwnam(__name: str) -> struct_passwd: ... diff --git a/stdlib/@python2/py_compile.pyi b/stdlib/@python2/py_compile.pyi deleted file mode 100644 index 44905b43da33..000000000000 --- a/stdlib/@python2/py_compile.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import List, Text, Type, Union - -_EitherStr = Union[bytes, Text] - -class PyCompileError(Exception): - exc_type_name: str - exc_value: BaseException - file: str - msg: str - def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... - -def compile(file: _EitherStr, cfile: _EitherStr | None = ..., dfile: _EitherStr | None = ..., doraise: bool = ...) -> None: ... -def main(args: List[Text] | None = ...) -> int: ... diff --git a/stdlib/@python2/pyclbr.pyi b/stdlib/@python2/pyclbr.pyi deleted file mode 100644 index 893079901665..000000000000 --- a/stdlib/@python2/pyclbr.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Dict, List, Sequence - -class Class: - module: str - name: str - super: List[Class | str] | None - methods: Dict[str, int] - file: int - lineno: int - def __init__(self, module: str, name: str, super: List[Class | str] | None, file: str, lineno: int) -> None: ... - -class Function: - module: str - name: str - file: int - lineno: int - def __init__(self, module: str, name: str, file: str, lineno: int) -> None: ... - -def readmodule(module: str, path: Sequence[str] | None = ...) -> Dict[str, Class]: ... -def readmodule_ex(module: str, path: Sequence[str] | None = ...) -> Dict[str, Class | Function | List[str]]: ... diff --git a/stdlib/@python2/pydoc.pyi b/stdlib/@python2/pydoc.pyi deleted file mode 100644 index dee0c4710b39..000000000000 --- a/stdlib/@python2/pydoc.pyi +++ /dev/null @@ -1,258 +0,0 @@ -from _typeshed import SupportsWrite -from types import MethodType, ModuleType, TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Container, - Dict, - List, - Mapping, - MutableMapping, - NoReturn, - Optional, - Text, - Tuple, - Type, -) - -from repr import Repr - -# the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] - -__author__: str -__date__: str -__version__: str -__credits__: str - -def pathdirs() -> List[str]: ... -def getdoc(object: object) -> Text: ... -def splitdoc(doc: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def classname(object: object, modname: str) -> str: ... -def isdata(object: object) -> bool: ... -def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ... -def cram(text: str, maxlen: int) -> str: ... -def stripid(text: str) -> str: ... -def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... -def visiblename(name: str, all: Container[str] | None = ..., obj: object | None = ...) -> bool: ... -def classify_class_attrs(object: object) -> List[Tuple[str, str, type, str]]: ... -def ispackage(path: str) -> bool: ... -def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... -def synopsis(filename: str, cache: MutableMapping[str, Tuple[int, str]] = ...) -> str | None: ... - -class ErrorDuringImport(Exception): - filename: str - exc: Type[BaseException] | None - value: BaseException | None - tb: TracebackType | None - def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... - -def importfile(path: str) -> ModuleType: ... -def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = ...) -> ModuleType: ... - -class Doc: - PYTHONDOCS: str - def document(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def fail(self, object: object, name: str | None = ..., *args: Any) -> NoReturn: ... - def docmodule(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docclass(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docroutine(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docother(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docproperty(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docdata(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... - -class HTMLRepr(Repr): - maxlist: int - maxtuple: int - maxdict: int - maxstring: int - maxother: int - def __init__(self) -> None: ... - def escape(self, text: str) -> str: ... - def repr(self, object: object) -> str: ... - def repr1(self, x: object, level: complex) -> str: ... - def repr_string(self, x: Text, level: complex) -> str: ... - def repr_str(self, x: Text, level: complex) -> str: ... - def repr_instance(self, x: object, level: complex) -> str: ... - def repr_unicode(self, x: AnyStr, level: complex) -> str: ... - -class HTMLDoc(Doc): - repr: Callable[[object], str] - escape: Callable[[str], str] - def page(self, title: str, contents: str) -> str: ... - def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... - def section( - self, - title: str, - fgcol: str, - bgcol: str, - contents: str, - width: int = ..., - prelude: str = ..., - marginalia: str | None = ..., - gap: str = ..., - ) -> str: ... - def bigsection(self, title: str, *args: Any) -> str: ... - def preformat(self, text: str) -> str: ... - def multicolumn(self, list: List[Any], format: Callable[[Any], str], cols: int = ...) -> str: ... - def grey(self, text: str) -> str: ... - def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... - def classlink(self, object: object, modname: str) -> str: ... - def modulelink(self, object: object) -> str: ... - def modpkglink(self, modpkginfo: Tuple[str, str, bool, bool]) -> str: ... - def markup( - self, - text: str, - escape: Callable[[str], str] | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - methods: Mapping[str, str] = ..., - ) -> str: ... - def formattree( - self, tree: List[Tuple[type, Tuple[type, ...]] | List[Any]], modname: str, parent: type | None = ... - ) -> str: ... - def docmodule(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... - def docclass( - self, - object: object, - name: str | None = ..., - mod: str | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - *ignored: Any, - ) -> str: ... - def formatvalue(self, object: object) -> str: ... - def docroutine( - self, - object: object, - name: str | None = ..., - mod: str | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - methods: Mapping[str, str] = ..., - cl: type | None = ..., - *ignored: Any, - ) -> str: ... - def docproperty( - self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docother(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... - def docdata( - self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = ...) -> str: ... - def filelink(self, url: str, path: str) -> str: ... - -class TextRepr(Repr): - maxlist: int - maxtuple: int - maxdict: int - maxstring: int - maxother: int - def __init__(self) -> None: ... - def repr1(self, x: object, level: complex) -> str: ... - def repr_string(self, x: str, level: complex) -> str: ... - def repr_str(self, x: str, level: complex) -> str: ... - def repr_instance(self, x: object, level: complex) -> str: ... - -class TextDoc(Doc): - repr: Callable[[object], str] - def bold(self, text: str) -> str: ... - def indent(self, text: str, prefix: str = ...) -> str: ... - def section(self, title: str, contents: str) -> str: ... - def formattree( - self, tree: List[Tuple[type, Tuple[type, ...]] | List[Any]], modname: str, parent: type | None = ..., prefix: str = ... - ) -> str: ... - def docmodule(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... - def docclass(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... - def formatvalue(self, object: object) -> str: ... - def docroutine( - self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docproperty( - self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docdata( - self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docother( - self, - object: object, - name: str | None = ..., - mod: str | None = ..., - parent: str | None = ..., - maxlen: int | None = ..., - doc: Any | None = ..., - *ignored: Any, - ) -> str: ... - -def pager(text: str) -> None: ... -def getpager() -> Callable[[str], None]: ... -def plain(text: str) -> str: ... -def pipepager(text: str, cmd: str) -> None: ... -def tempfilepager(text: str, cmd: str) -> None: ... -def ttypager(text: str) -> None: ... -def plainpager(text: str) -> None: ... -def describe(thing: Any) -> str: ... -def locate(path: str, forceload: bool = ...) -> object: ... - -text: TextDoc -html: HTMLDoc - -class _OldStyleClass: ... - -def resolve(thing: str | object, forceload: bool = ...) -> Tuple[object, str] | None: ... -def render_doc(thing: str | object, title: str = ..., forceload: bool = ..., renderer: Doc | None = ...) -> str: ... -def doc(thing: str | object, title: str = ..., forceload: bool = ..., output: SupportsWrite[str] | None = ...) -> None: ... -def writedoc(thing: str | object, forceload: bool = ...) -> None: ... -def writedocs(dir: str, pkgpath: str = ..., done: Any | None = ...) -> None: ... - -class Helper: - keywords: Dict[str, str | Tuple[str, str]] - symbols: Dict[str, str] - topics: Dict[str, str | Tuple[str, ...]] - def __init__(self, input: IO[str] | None = ..., output: IO[str] | None = ...) -> None: ... - input: IO[str] - output: IO[str] - def __call__(self, request: str | Helper | object = ...) -> None: ... - def interact(self) -> None: ... - def getline(self, prompt: str) -> str: ... - def help(self, request: Any) -> None: ... - def intro(self) -> None: ... - def list(self, items: List[str], columns: int = ..., width: int = ...) -> None: ... - def listkeywords(self) -> None: ... - def listsymbols(self) -> None: ... - def listtopics(self) -> None: ... - def showtopic(self, topic: str, more_xrefs: str = ...) -> None: ... - def showsymbol(self, symbol: str) -> None: ... - def listmodules(self, key: str = ...) -> None: ... - -help: Helper - -# See Python issue #11182: "remove the unused and undocumented pydoc.Scanner class" -# class Scanner: -# roots = ... # type: Any -# state = ... # type: Any -# children = ... # type: Any -# descendp = ... # type: Any -# def __init__(self, roots, children, descendp) -> None: ... -# def next(self): ... - -class ModuleScanner: - quit: bool - def run( - self, - callback: Callable[[str | None, str, str], None], - key: Any | None = ..., - completer: Callable[[], None] | None = ..., - onerror: Callable[[str], None] | None = ..., - ) -> None: ... - -def apropos(key: str) -> None: ... -def ispath(x: Any) -> bool: ... -def cli() -> None: ... -def serve(port: int, callback: Callable[[Any], None] | None = ..., completer: Callable[[], None] | None = ...) -> None: ... -def gui() -> None: ... diff --git a/stdlib/@python2/pydoc_data/topics.pyi b/stdlib/@python2/pydoc_data/topics.pyi deleted file mode 100644 index 1c48f4022fd6..000000000000 --- a/stdlib/@python2/pydoc_data/topics.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Dict - -topics: Dict[str, str] diff --git a/stdlib/@python2/pyexpat/__init__.pyi b/stdlib/@python2/pyexpat/__init__.pyi deleted file mode 100644 index bd73f850b559..000000000000 --- a/stdlib/@python2/pyexpat/__init__.pyi +++ /dev/null @@ -1,75 +0,0 @@ -import pyexpat.errors as errors -import pyexpat.model as model -from _typeshed import SupportsRead -from typing import Any, Callable, Dict, List, Optional, Text, Tuple - -EXPAT_VERSION: str # undocumented -version_info: Tuple[int, int, int] # undocumented -native_encoding: str # undocumented -features: List[Tuple[str, int]] # undocumented - -class ExpatError(Exception): - code: int - lineno: int - offset: int - -error = ExpatError - -XML_PARAM_ENTITY_PARSING_NEVER: int -XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int -XML_PARAM_ENTITY_PARSING_ALWAYS: int - -_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] - -class XMLParserType(object): - def Parse(self, __data: Text | bytes, __isfinal: bool = ...) -> int: ... - def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... - def SetBase(self, __base: Text) -> None: ... - def GetBase(self) -> str | None: ... - def GetInputContext(self) -> bytes | None: ... - def ExternalEntityParserCreate(self, __context: Text | None, __encoding: Text = ...) -> XMLParserType: ... - def SetParamEntityParsing(self, __flag: int) -> int: ... - def UseForeignDTD(self, __flag: bool = ...) -> None: ... - buffer_size: int - buffer_text: bool - buffer_used: int - namespace_prefixes: bool # undocumented - ordered_attributes: bool - specified_attributes: bool - ErrorByteIndex: int - ErrorCode: int - ErrorColumnNumber: int - ErrorLineNumber: int - CurrentByteIndex: int - CurrentColumnNumber: int - CurrentLineNumber: int - XmlDeclHandler: Callable[[str, str | None, int], Any] | None - StartDoctypeDeclHandler: Callable[[str, str | None, str | None, bool], Any] | None - EndDoctypeDeclHandler: Callable[[], Any] | None - ElementDeclHandler: Callable[[str, _Model], Any] | None - AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None - StartElementHandler: Callable[[str, Dict[str, str]], Any] | Callable[[str, List[str]], Any] | Callable[ - [str, Dict[str, str], List[str]], Any - ] | None - EndElementHandler: Callable[[str], Any] | None - ProcessingInstructionHandler: Callable[[str, str], Any] | None - CharacterDataHandler: Callable[[str], Any] | None - UnparsedEntityDeclHandler: Callable[[str, str | None, str, str | None, str], Any] | None - EntityDeclHandler: Callable[[str, bool, str | None, str | None, str, str | None, str | None], Any] | None - NotationDeclHandler: Callable[[str, str | None, str, str | None], Any] | None - StartNamespaceDeclHandler: Callable[[str, str], Any] | None - EndNamespaceDeclHandler: Callable[[str], Any] | None - CommentHandler: Callable[[str], Any] | None - StartCdataSectionHandler: Callable[[], Any] | None - EndCdataSectionHandler: Callable[[], Any] | None - DefaultHandler: Callable[[str], Any] | None - DefaultHandlerExpand: Callable[[str], Any] | None - NotStandaloneHandler: Callable[[], int] | None - ExternalEntityRefHandler: Callable[[str, str | None, str | None, str | None], int] | None - -def ErrorString(__code: int) -> str: ... - -# intern is undocumented -def ParserCreate( - encoding: Text | None = ..., namespace_separator: Text | None = ..., intern: Dict[str, Any] | None = ... -) -> XMLParserType: ... diff --git a/stdlib/@python2/pyexpat/errors.pyi b/stdlib/@python2/pyexpat/errors.pyi deleted file mode 100644 index 498030fd695f..000000000000 --- a/stdlib/@python2/pyexpat/errors.pyi +++ /dev/null @@ -1,37 +0,0 @@ -XML_ERROR_ABORTED: str -XML_ERROR_ASYNC_ENTITY: str -XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: str -XML_ERROR_BAD_CHAR_REF: str -XML_ERROR_BINARY_ENTITY_REF: str -XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: str -XML_ERROR_DUPLICATE_ATTRIBUTE: str -XML_ERROR_ENTITY_DECLARED_IN_PE: str -XML_ERROR_EXTERNAL_ENTITY_HANDLING: str -XML_ERROR_FEATURE_REQUIRES_XML_DTD: str -XML_ERROR_FINISHED: str -XML_ERROR_INCOMPLETE_PE: str -XML_ERROR_INCORRECT_ENCODING: str -XML_ERROR_INVALID_TOKEN: str -XML_ERROR_JUNK_AFTER_DOC_ELEMENT: str -XML_ERROR_MISPLACED_XML_PI: str -XML_ERROR_NOT_STANDALONE: str -XML_ERROR_NOT_SUSPENDED: str -XML_ERROR_NO_ELEMENTS: str -XML_ERROR_NO_MEMORY: str -XML_ERROR_PARAM_ENTITY_REF: str -XML_ERROR_PARTIAL_CHAR: str -XML_ERROR_PUBLICID: str -XML_ERROR_RECURSIVE_ENTITY_REF: str -XML_ERROR_SUSPENDED: str -XML_ERROR_SUSPEND_PE: str -XML_ERROR_SYNTAX: str -XML_ERROR_TAG_MISMATCH: str -XML_ERROR_TEXT_DECL: str -XML_ERROR_UNBOUND_PREFIX: str -XML_ERROR_UNCLOSED_CDATA_SECTION: str -XML_ERROR_UNCLOSED_TOKEN: str -XML_ERROR_UNDECLARING_PREFIX: str -XML_ERROR_UNDEFINED_ENTITY: str -XML_ERROR_UNEXPECTED_STATE: str -XML_ERROR_UNKNOWN_ENCODING: str -XML_ERROR_XML_DECL: str diff --git a/stdlib/@python2/pyexpat/model.pyi b/stdlib/@python2/pyexpat/model.pyi deleted file mode 100644 index f357cf6511a2..000000000000 --- a/stdlib/@python2/pyexpat/model.pyi +++ /dev/null @@ -1,11 +0,0 @@ -XML_CTYPE_ANY: int -XML_CTYPE_CHOICE: int -XML_CTYPE_EMPTY: int -XML_CTYPE_MIXED: int -XML_CTYPE_NAME: int -XML_CTYPE_SEQ: int - -XML_CQUANT_NONE: int -XML_CQUANT_OPT: int -XML_CQUANT_PLUS: int -XML_CQUANT_REP: int diff --git a/stdlib/@python2/quopri.pyi b/stdlib/@python2/quopri.pyi deleted file mode 100644 index c2ffabe7d531..000000000000 --- a/stdlib/@python2/quopri.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import BinaryIO - -def encode(input: BinaryIO, output: BinaryIO, quotetabs: int, header: int = ...) -> None: ... -def encodestring(s: bytes, quotetabs: int = ..., header: int = ...) -> bytes: ... -def decode(input: BinaryIO, output: BinaryIO, header: int = ...) -> None: ... -def decodestring(s: bytes, header: int = ...) -> bytes: ... diff --git a/stdlib/@python2/random.pyi b/stdlib/@python2/random.pyi deleted file mode 100644 index 6fb5d602067c..000000000000 --- a/stdlib/@python2/random.pyi +++ /dev/null @@ -1,67 +0,0 @@ -import _random -from typing import Any, Callable, Iterator, List, MutableSequence, Protocol, Sequence, TypeVar, overload - -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) - -class _Sampleable(Protocol[_T_co]): - def __iter__(self) -> Iterator[_T_co]: ... - def __len__(self) -> int: ... - -class Random(_random.Random): - def __init__(self, x: object = ...) -> None: ... - def seed(self, x: object = ...) -> None: ... - def getstate(self) -> _random._State: ... - def setstate(self, state: _random._State) -> None: ... - def jumpahead(self, n: int) -> None: ... - def getrandbits(self, k: int) -> int: ... - @overload - def randrange(self, stop: int) -> int: ... - @overload - def randrange(self, start: int, stop: int, step: int = ...) -> int: ... - def randint(self, a: int, b: int) -> int: ... - def choice(self, seq: Sequence[_T]) -> _T: ... - def shuffle(self, x: MutableSequence[Any], random: Callable[[], None] = ...) -> None: ... - def sample(self, population: _Sampleable[_T], k: int) -> List[_T]: ... - def random(self) -> float: ... - def uniform(self, a: float, b: float) -> float: ... - def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... - def betavariate(self, alpha: float, beta: float) -> float: ... - def expovariate(self, lambd: float) -> float: ... - def gammavariate(self, alpha: float, beta: float) -> float: ... - def gauss(self, mu: float, sigma: float) -> float: ... - def lognormvariate(self, mu: float, sigma: float) -> float: ... - def normalvariate(self, mu: float, sigma: float) -> float: ... - def vonmisesvariate(self, mu: float, kappa: float) -> float: ... - def paretovariate(self, alpha: float) -> float: ... - def weibullvariate(self, alpha: float, beta: float) -> float: ... - -# SystemRandom is not implemented for all OS's; good on Windows & Linux -class SystemRandom(Random): ... - -# ----- random function stubs ----- -def seed(x: object = ...) -> None: ... -def getstate() -> object: ... -def setstate(state: object) -> None: ... -def jumpahead(n: int) -> None: ... -def getrandbits(k: int) -> int: ... -@overload -def randrange(stop: int) -> int: ... -@overload -def randrange(start: int, stop: int, step: int = ...) -> int: ... -def randint(a: int, b: int) -> int: ... -def choice(seq: Sequence[_T]) -> _T: ... -def shuffle(x: MutableSequence[Any], random: Callable[[], float] = ...) -> None: ... -def sample(population: _Sampleable[_T], k: int) -> List[_T]: ... -def random() -> float: ... -def uniform(a: float, b: float) -> float: ... -def triangular(low: float = ..., high: float = ..., mode: float = ...) -> float: ... -def betavariate(alpha: float, beta: float) -> float: ... -def expovariate(lambd: float) -> float: ... -def gammavariate(alpha: float, beta: float) -> float: ... -def gauss(mu: float, sigma: float) -> float: ... -def lognormvariate(mu: float, sigma: float) -> float: ... -def normalvariate(mu: float, sigma: float) -> float: ... -def vonmisesvariate(mu: float, kappa: float) -> float: ... -def paretovariate(alpha: float) -> float: ... -def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/stdlib/@python2/re.pyi b/stdlib/@python2/re.pyi deleted file mode 100644 index fbe021ce67be..000000000000 --- a/stdlib/@python2/re.pyi +++ /dev/null @@ -1,87 +0,0 @@ -from typing import Any, AnyStr, Callable, Iterator, List, Match, Pattern, Tuple, overload - -# ----- re variables and constants ----- -DEBUG: int -I: int -IGNORECASE: int -L: int -LOCALE: int -M: int -MULTILINE: int -S: int -DOTALL: int -X: int -VERBOSE: int -U: int -UNICODE: int -T: int -TEMPLATE: int - -class error(Exception): ... - -@overload -def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ... -@overload -def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... -@overload -def search(pattern: str | unicode, string: AnyStr, flags: int = ...) -> Match[AnyStr] | None: ... -@overload -def search(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> Match[AnyStr] | None: ... -@overload -def match(pattern: str | unicode, string: AnyStr, flags: int = ...) -> Match[AnyStr] | None: ... -@overload -def match(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> Match[AnyStr] | None: ... -@overload -def split(pattern: str | unicode, string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... -@overload -def split(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... -@overload -def findall(pattern: str | unicode, string: AnyStr, flags: int = ...) -> List[Any]: ... -@overload -def findall(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... - -# Return an iterator yielding match objects over all non-overlapping matches -# for the RE pattern in string. The string is scanned left-to-right, and -# matches are returned in the order found. Empty matches are included in the -# result unless they touch the beginning of another match. -@overload -def finditer(pattern: str | unicode, string: AnyStr, flags: int = ...) -> Iterator[Match[AnyStr]]: ... -@overload -def finditer(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> Iterator[Match[AnyStr]]: ... -@overload -def sub(pattern: str | unicode, repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... -@overload -def sub( - pattern: str | unicode, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: int = ... -) -> AnyStr: ... -@overload -def sub(pattern: Pattern[str] | Pattern[unicode], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... -@overload -def sub( - pattern: Pattern[str] | Pattern[unicode], - repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, - count: int = ..., - flags: int = ..., -) -> AnyStr: ... -@overload -def subn(pattern: str | unicode, repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> Tuple[AnyStr, int]: ... -@overload -def subn( - pattern: str | unicode, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: int = ... -) -> Tuple[AnyStr, int]: ... -@overload -def subn( - pattern: Pattern[str] | Pattern[unicode], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ... -) -> Tuple[AnyStr, int]: ... -@overload -def subn( - pattern: Pattern[str] | Pattern[unicode], - repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, - count: int = ..., - flags: int = ..., -) -> Tuple[AnyStr, int]: ... -def escape(string: AnyStr) -> AnyStr: ... -def purge() -> None: ... -def template(pattern: AnyStr | Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/stdlib/@python2/readline.pyi b/stdlib/@python2/readline.pyi deleted file mode 100644 index fb9b12d9a8e9..000000000000 --- a/stdlib/@python2/readline.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Callable, Optional, Sequence, Text - -_CompleterT = Optional[Callable[[str, int], Optional[str]]] -_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] - -def parse_and_bind(__string: str) -> None: ... -def read_init_file(__filename: Text | None = ...) -> None: ... -def get_line_buffer() -> str: ... -def insert_text(__string: str) -> None: ... -def redisplay() -> None: ... -def read_history_file(__filename: Text | None = ...) -> None: ... -def write_history_file(__filename: Text | None = ...) -> None: ... -def get_history_length() -> int: ... -def set_history_length(__length: int) -> None: ... -def clear_history() -> None: ... -def get_current_history_length() -> int: ... -def get_history_item(__index: int) -> str: ... -def remove_history_item(__pos: int) -> None: ... -def replace_history_item(__pos: int, __line: str) -> None: ... -def add_history(__string: str) -> None: ... -def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_completer(__function: _CompleterT = ...) -> None: ... -def get_completer() -> _CompleterT: ... -def get_completion_type() -> int: ... -def get_begidx() -> int: ... -def get_endidx() -> int: ... -def set_completer_delims(__string: str) -> None: ... -def get_completer_delims() -> str: ... -def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... diff --git a/stdlib/@python2/repr.pyi b/stdlib/@python2/repr.pyi deleted file mode 100644 index bdb8822ac77d..000000000000 --- a/stdlib/@python2/repr.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Any, List - -class Repr: - maxarray: int - maxdeque: int - maxdict: int - maxfrozenset: int - maxlevel: int - maxlist: int - maxlong: int - maxother: int - maxset: int - maxstring: int - maxtuple: int - def __init__(self) -> None: ... - def _repr_iterable(self, x, level: complex, left, right, maxiter, trail=...) -> str: ... - def repr(self, x) -> str: ... - def repr1(self, x, level: complex) -> str: ... - def repr_array(self, x, level: complex) -> str: ... - def repr_deque(self, x, level: complex) -> str: ... - def repr_dict(self, x, level: complex) -> str: ... - def repr_frozenset(self, x, level: complex) -> str: ... - def repr_instance(self, x, level: complex) -> str: ... - def repr_list(self, x, level: complex) -> str: ... - def repr_long(self, x, level: complex) -> str: ... - def repr_set(self, x, level: complex) -> str: ... - def repr_str(self, x, level: complex) -> str: ... - def repr_tuple(self, x, level: complex) -> str: ... - -def _possibly_sorted(x) -> List[Any]: ... - -aRepr: Repr - -def repr(x) -> str: ... diff --git a/stdlib/@python2/resource.pyi b/stdlib/@python2/resource.pyi deleted file mode 100644 index ad9502db1940..000000000000 --- a/stdlib/@python2/resource.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import NamedTuple, Tuple - -class error(Exception): ... - -RLIM_INFINITY: int - -def getrlimit(resource: int) -> Tuple[int, int]: ... -def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... - -RLIMIT_CORE: int -RLIMIT_CPU: int -RLIMIT_FSIZE: int -RLIMIT_DATA: int -RLIMIT_STACK: int -RLIMIT_RSS: int -RLIMIT_NPROC: int -RLIMIT_NOFILE: int -RLIMIT_OFILE: int -RLIMIT_MEMLOCK: int -RLIMIT_VMEM: int -RLIMIT_AS: int - -class _RUsage(NamedTuple): - ru_utime: float - ru_stime: float - ru_maxrss: int - ru_ixrss: int - ru_idrss: int - ru_isrss: int - ru_minflt: int - ru_majflt: int - ru_nswap: int - ru_inblock: int - ru_oublock: int - ru_msgsnd: int - ru_msgrcv: int - ru_nsignals: int - ru_nvcsw: int - ru_nivcsw: int - -def getrusage(who: int) -> _RUsage: ... -def getpagesize() -> int: ... - -RUSAGE_SELF: int -RUSAGE_CHILDREN: int -RUSAGE_BOTH: int diff --git a/stdlib/@python2/rfc822.pyi b/stdlib/@python2/rfc822.pyi deleted file mode 100644 index d6ae0031ffdf..000000000000 --- a/stdlib/@python2/rfc822.pyi +++ /dev/null @@ -1,75 +0,0 @@ -from typing import Any - -class Message: - fp: Any - seekable: Any - startofheaders: Any - startofbody: Any - def __init__(self, fp, seekable: int = ...): ... - def rewindbody(self): ... - dict: Any - unixfrom: Any - headers: Any - status: Any - def readheaders(self): ... - def isheader(self, line): ... - def islast(self, line): ... - def iscomment(self, line): ... - def getallmatchingheaders(self, name): ... - def getfirstmatchingheader(self, name): ... - def getrawheader(self, name): ... - def getheader(self, name, default: Any | None = ...): ... - get: Any - def getheaders(self, name): ... - def getaddr(self, name): ... - def getaddrlist(self, name): ... - def getdate(self, name): ... - def getdate_tz(self, name): ... - def __len__(self): ... - def __getitem__(self, name): ... - def __setitem__(self, name, value): ... - def __delitem__(self, name): ... - def setdefault(self, name, default=...): ... - def has_key(self, name): ... - def __contains__(self, name): ... - def __iter__(self): ... - def keys(self): ... - def values(self): ... - def items(self): ... - -class AddrlistClass: - specials: Any - pos: Any - LWS: Any - CR: Any - atomends: Any - phraseends: Any - field: Any - commentlist: Any - def __init__(self, field): ... - def gotonext(self): ... - def getaddrlist(self): ... - def getaddress(self): ... - def getrouteaddr(self): ... - def getaddrspec(self): ... - def getdomain(self): ... - def getdelimited(self, beginchar, endchars, allowcomments: int = ...): ... - def getquote(self): ... - def getcomment(self): ... - def getdomainliteral(self): ... - def getatom(self, atomends: Any | None = ...): ... - def getphraselist(self): ... - -class AddressList(AddrlistClass): - addresslist: Any - def __init__(self, field): ... - def __len__(self): ... - def __add__(self, other): ... - def __iadd__(self, other): ... - def __sub__(self, other): ... - def __isub__(self, other): ... - def __getitem__(self, index): ... - -def parsedate_tz(data): ... -def parsedate(data): ... -def mktime_tz(data): ... diff --git a/stdlib/@python2/rlcompleter.pyi b/stdlib/@python2/rlcompleter.pyi deleted file mode 100644 index a61c61eb24f2..000000000000 --- a/stdlib/@python2/rlcompleter.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any, Dict, Union - -_Text = Union[str, unicode] - -class Completer: - def __init__(self, namespace: Dict[str, Any] | None = ...) -> None: ... - def complete(self, text: _Text, state: int) -> str | None: ... diff --git a/stdlib/@python2/robotparser.pyi b/stdlib/@python2/robotparser.pyi deleted file mode 100644 index 403039ae91c9..000000000000 --- a/stdlib/@python2/robotparser.pyi +++ /dev/null @@ -1,7 +0,0 @@ -class RobotFileParser: - def set_url(self, url: str): ... - def read(self): ... - def parse(self, lines: str): ... - def can_fetch(self, user_agent: str, url: str): ... - def mtime(self): ... - def modified(self): ... diff --git a/stdlib/@python2/runpy.pyi b/stdlib/@python2/runpy.pyi deleted file mode 100644 index 3d5f0500f2e0..000000000000 --- a/stdlib/@python2/runpy.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -class _TempModule: - mod_name: Any - module: Any - def __init__(self, mod_name): ... - def __enter__(self): ... - def __exit__(self, *args): ... - -class _ModifiedArgv0: - value: Any - def __init__(self, value): ... - def __enter__(self): ... - def __exit__(self, *args): ... - -def run_module(mod_name, init_globals: Any | None = ..., run_name: Any | None = ..., alter_sys: bool = ...): ... -def run_path(path_name, init_globals: Any | None = ..., run_name: Any | None = ...): ... diff --git a/stdlib/@python2/sched.pyi b/stdlib/@python2/sched.pyi deleted file mode 100644 index f718dd7a57bd..000000000000 --- a/stdlib/@python2/sched.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any, Callable, Dict, List, NamedTuple, Text, Tuple - -class Event(NamedTuple): - time: float - priority: Any - action: Callable[..., Any] - argument: Tuple[Any, ...] - kwargs: Dict[Text, Any] - -class scheduler: - def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ... - def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... - def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... - def run(self) -> None: ... - def cancel(self, event: Event) -> None: ... - def empty(self) -> bool: ... - @property - def queue(self) -> List[Event]: ... diff --git a/stdlib/@python2/select.pyi b/stdlib/@python2/select.pyi deleted file mode 100644 index b960fd4e24b5..000000000000 --- a/stdlib/@python2/select.pyi +++ /dev/null @@ -1,124 +0,0 @@ -import sys -from _typeshed import FileDescriptorLike -from typing import Any, Iterable, List, Tuple - -if sys.platform != "win32": - PIPE_BUF: int - POLLERR: int - POLLHUP: int - POLLIN: int - POLLMSG: int - POLLNVAL: int - POLLOUT: int - POLLPRI: int - POLLRDBAND: int - POLLRDNORM: int - POLLWRBAND: int - POLLWRNORM: int - -class poll: - def __init__(self) -> None: ... - def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... - def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... - def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ...) -> List[Tuple[int, int]]: ... - -def select( - __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: float | None = ... -) -> Tuple[List[Any], List[Any], List[Any]]: ... - -class error(Exception): ... - -if sys.platform != "linux" and sys.platform != "win32": - # BSD only - class kevent(object): - data: Any - fflags: int - filter: int - flags: int - ident: int - udata: Any - def __init__( - self, - ident: FileDescriptorLike, - filter: int = ..., - flags: int = ..., - fflags: int = ..., - data: Any = ..., - udata: Any = ..., - ) -> None: ... - # BSD only - class kqueue(object): - closed: bool - def __init__(self) -> None: ... - def close(self) -> None: ... - def control( - self, __changelist: Iterable[kevent] | None, __maxevents: int, __timeout: float | None = ... - ) -> List[kevent]: ... - def fileno(self) -> int: ... - @classmethod - def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... - KQ_EV_ADD: int - KQ_EV_CLEAR: int - KQ_EV_DELETE: int - KQ_EV_DISABLE: int - KQ_EV_ENABLE: int - KQ_EV_EOF: int - KQ_EV_ERROR: int - KQ_EV_FLAG1: int - KQ_EV_ONESHOT: int - KQ_EV_SYSFLAGS: int - KQ_FILTER_AIO: int - KQ_FILTER_NETDEV: int - KQ_FILTER_PROC: int - KQ_FILTER_READ: int - KQ_FILTER_SIGNAL: int - KQ_FILTER_TIMER: int - KQ_FILTER_VNODE: int - KQ_FILTER_WRITE: int - KQ_NOTE_ATTRIB: int - KQ_NOTE_CHILD: int - KQ_NOTE_DELETE: int - KQ_NOTE_EXEC: int - KQ_NOTE_EXIT: int - KQ_NOTE_EXTEND: int - KQ_NOTE_FORK: int - KQ_NOTE_LINK: int - if sys.platform != "darwin": - KQ_NOTE_LINKDOWN: int - KQ_NOTE_LINKINV: int - KQ_NOTE_LINKUP: int - KQ_NOTE_LOWAT: int - KQ_NOTE_PCTRLMASK: int - KQ_NOTE_PDATAMASK: int - KQ_NOTE_RENAME: int - KQ_NOTE_REVOKE: int - KQ_NOTE_TRACK: int - KQ_NOTE_TRACKERR: int - KQ_NOTE_WRITE: int - -if sys.platform == "linux": - class epoll(object): - def __init__(self, sizehint: int = ...) -> None: ... - def close(self) -> None: ... - closed: bool - def fileno(self) -> int: ... - def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... - def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... - def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ..., maxevents: int = ...) -> List[Tuple[int, int]]: ... - @classmethod - def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... - EPOLLERR: int - EPOLLET: int - EPOLLHUP: int - EPOLLIN: int - EPOLLMSG: int - EPOLLONESHOT: int - EPOLLOUT: int - EPOLLPRI: int - EPOLLRDBAND: int - EPOLLRDNORM: int - EPOLLWRBAND: int - EPOLLWRNORM: int - EPOLL_RDHUP: int diff --git a/stdlib/@python2/sets.pyi b/stdlib/@python2/sets.pyi deleted file mode 100644 index d2b94ea44bbc..000000000000 --- a/stdlib/@python2/sets.pyi +++ /dev/null @@ -1,60 +0,0 @@ -from typing import Any, Hashable, Iterable, Iterator, MutableMapping, TypeVar, Union - -_T = TypeVar("_T") -_Setlike = Union[BaseSet[_T], Iterable[_T]] -_SelfT = TypeVar("_SelfT") - -class BaseSet(Iterable[_T]): - def __init__(self) -> None: ... - def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - def __iter__(self) -> Iterator[_T]: ... - def __cmp__(self, other: Any) -> int: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - def copy(self: _SelfT) -> _SelfT: ... - def __copy__(self: _SelfT) -> _SelfT: ... - def __deepcopy__(self: _SelfT, memo: MutableMapping[int, BaseSet[_T]]) -> _SelfT: ... - def __or__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def union(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... - def __xor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def symmetric_difference(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def difference(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... - def __contains__(self, element: Any) -> bool: ... - def issubset(self, other: BaseSet[_T]) -> bool: ... - def issuperset(self, other: BaseSet[_T]) -> bool: ... - def __le__(self, other: BaseSet[_T]) -> bool: ... - def __ge__(self, other: BaseSet[_T]) -> bool: ... - def __lt__(self, other: BaseSet[_T]) -> bool: ... - def __gt__(self, other: BaseSet[_T]) -> bool: ... - -class ImmutableSet(BaseSet[_T], Hashable): - def __init__(self, iterable: _Setlike[_T] | None = ...) -> None: ... - def __hash__(self) -> int: ... - -class Set(BaseSet[_T]): - def __init__(self, iterable: _Setlike[_T] | None = ...) -> None: ... - def __ior__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def union_update(self, other: _Setlike[_T]) -> None: ... - def __iand__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def intersection_update(self, other: _Setlike[Any]) -> None: ... - def __ixor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def symmetric_difference_update(self, other: _Setlike[_T]) -> None: ... - def __isub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def difference_update(self, other: _Setlike[Any]) -> None: ... - def update(self, iterable: _Setlike[_T]) -> None: ... - def clear(self) -> None: ... - def add(self, element: _T) -> None: ... - def remove(self, element: _T) -> None: ... - def discard(self, element: _T) -> None: ... - def pop(self) -> _T: ... - def __as_immutable__(self) -> ImmutableSet[_T]: ... - def __as_temporarily_immutable__(self) -> _TemporarilyImmutableSet[_T]: ... - -class _TemporarilyImmutableSet(BaseSet[_T]): - def __init__(self, set: BaseSet[_T]) -> None: ... - def __hash__(self) -> int: ... diff --git a/stdlib/@python2/sha.pyi b/stdlib/@python2/sha.pyi deleted file mode 100644 index aac8c8bc57bb..000000000000 --- a/stdlib/@python2/sha.pyi +++ /dev/null @@ -1,10 +0,0 @@ -class sha(object): - def update(self, arg: str) -> None: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def copy(self) -> sha: ... - -def new(string: str = ...) -> sha: ... - -blocksize: int -digest_size: int diff --git a/stdlib/@python2/shelve.pyi b/stdlib/@python2/shelve.pyi deleted file mode 100644 index d9b1a00e58df..000000000000 --- a/stdlib/@python2/shelve.pyi +++ /dev/null @@ -1,36 +0,0 @@ -import collections -from typing import Any, Dict, Iterator, List, Tuple - -class Shelf(collections.MutableMapping[Any, Any]): - def __init__( - self, dict: Dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... - ) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def keys(self) -> List[Any]: ... - def __len__(self) -> int: ... - def has_key(self, key: Any) -> bool: ... - def __contains__(self, key: Any) -> bool: ... - def get(self, key: Any, default: Any = ...) -> Any: ... - def __getitem__(self, key: Any) -> Any: ... - def __setitem__(self, key: Any, value: Any) -> None: ... - def __delitem__(self, key: Any) -> None: ... - def __enter__(self) -> Shelf: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... - def close(self) -> None: ... - def __del__(self) -> None: ... - def sync(self) -> None: ... - -class BsdDbShelf(Shelf): - def __init__( - self, dict: Dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... - ) -> None: ... - def set_location(self, key: Any) -> Tuple[str, Any]: ... - def next(self) -> Tuple[str, Any]: ... - def previous(self) -> Tuple[str, Any]: ... - def first(self) -> Tuple[str, Any]: ... - def last(self) -> Tuple[str, Any]: ... - -class DbfilenameShelf(Shelf): - def __init__(self, filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> None: ... - -def open(filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/stdlib/@python2/shlex.pyi b/stdlib/@python2/shlex.pyi deleted file mode 100644 index 89c28fc9be7f..000000000000 --- a/stdlib/@python2/shlex.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from typing import IO, Any, List, Text, TypeVar - -def split(s: str | None, comments: bool = ..., posix: bool = ...) -> List[str]: ... - -_SLT = TypeVar("_SLT", bound=shlex) - -class shlex: - def __init__(self, instream: IO[Any] | Text = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... - def next(self) -> str: ... - def get_token(self) -> str | None: ... - def push_token(self, _str: str) -> None: ... - def read_token(self) -> str: ... - def sourcehook(self, filename: str) -> None: ... - def push_source(self, stream: IO[Any], filename: str = ...) -> None: ... - def pop_source(self) -> IO[Any]: ... - def error_leader(self, file: str = ..., line: int = ...) -> str: ... - commenters: str - wordchars: str - whitespace: str - escape: str - quotes: str - escapedquotes: str - whitespace_split: bool - infile: IO[Any] - source: str | None - debug: int - lineno: int - token: Any - eof: str | None diff --git a/stdlib/@python2/shutil.pyi b/stdlib/@python2/shutil.pyi deleted file mode 100644 index 4805c8e4cdb7..000000000000 --- a/stdlib/@python2/shutil.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from _typeshed import SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, List, Sequence, Set, Text, Tuple, Type, TypeVar, Union - -_AnyStr = TypeVar("_AnyStr", str, unicode) -_AnyPath = TypeVar("_AnyPath", str, unicode) -_PathReturn = Type[None] - -class Error(EnvironmentError): ... -class SpecialFileError(EnvironmentError): ... -class ExecError(EnvironmentError): ... - -def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... -def copyfile(src: Text, dst: Text) -> None: ... -def copymode(src: Text, dst: Text) -> None: ... -def copystat(src: Text, dst: Text) -> None: ... -def copy(src: Text, dst: Text) -> _PathReturn: ... -def copy2(src: Text, dst: Text) -> _PathReturn: ... -def ignore_patterns(*patterns: Text) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... -def copytree( - src: AnyStr, dst: AnyStr, symlinks: bool = ..., ignore: None | Callable[[AnyStr, List[AnyStr]], Iterable[AnyStr]] = ... -) -> _PathReturn: ... -def rmtree(path: _AnyPath, ignore_errors: bool = ..., onerror: Callable[[Any, _AnyPath, Any], Any] | None = ...) -> None: ... - -_CopyFn = Union[Callable[[str, str], None], Callable[[Text, Text], None]] - -def move(src: Text, dst: Text) -> _PathReturn: ... -def make_archive( - base_name: _AnyStr, - format: str, - root_dir: Text | None = ..., - base_dir: Text | None = ..., - verbose: bool = ..., - dry_run: bool = ..., - owner: str | None = ..., - group: str | None = ..., - logger: Any | None = ..., -) -> _AnyStr: ... -def get_archive_formats() -> List[Tuple[str, str]]: ... -def register_archive_format( - name: str, - function: Callable[..., Any], - extra_args: Sequence[Tuple[str, Any] | List[Any]] | None = ..., - description: str = ..., -) -> None: ... -def unregister_archive_format(name: str) -> None: ... diff --git a/stdlib/@python2/signal.pyi b/stdlib/@python2/signal.pyi deleted file mode 100644 index 16a8f2d1cb8b..000000000000 --- a/stdlib/@python2/signal.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from types import FrameType -from typing import Callable, Tuple, Union - -SIG_DFL: int = ... -SIG_IGN: int = ... - -ITIMER_REAL: int = ... -ITIMER_VIRTUAL: int = ... -ITIMER_PROF: int = ... - -NSIG: int = ... - -SIGABRT: int = ... -SIGALRM: int = ... -SIGBREAK: int = ... # Windows -SIGBUS: int = ... -SIGCHLD: int = ... -SIGCLD: int = ... -SIGCONT: int = ... -SIGEMT: int = ... -SIGFPE: int = ... -SIGHUP: int = ... -SIGILL: int = ... -SIGINFO: int = ... -SIGINT: int = ... -SIGIO: int = ... -SIGIOT: int = ... -SIGKILL: int = ... -SIGPIPE: int = ... -SIGPOLL: int = ... -SIGPROF: int = ... -SIGPWR: int = ... -SIGQUIT: int = ... -SIGRTMAX: int = ... -SIGRTMIN: int = ... -SIGSEGV: int = ... -SIGSTOP: int = ... -SIGSYS: int = ... -SIGTERM: int = ... -SIGTRAP: int = ... -SIGTSTP: int = ... -SIGTTIN: int = ... -SIGTTOU: int = ... -SIGURG: int = ... -SIGUSR1: int = ... -SIGUSR2: int = ... -SIGVTALRM: int = ... -SIGWINCH: int = ... -SIGXCPU: int = ... -SIGXFSZ: int = ... - -# Windows -CTRL_C_EVENT: int = ... -CTRL_BREAK_EVENT: int = ... - -class ItimerError(IOError): ... - -_HANDLER = Union[Callable[[int, FrameType], None], int, None] - -def alarm(time: int) -> int: ... -def getsignal(signalnum: int) -> _HANDLER: ... -def pause() -> None: ... -def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... -def getitimer(which: int) -> Tuple[float, float]: ... -def set_wakeup_fd(fd: int) -> int: ... -def siginterrupt(signalnum: int, flag: bool) -> None: ... -def signal(signalnum: int, handler: _HANDLER) -> _HANDLER: ... -def default_int_handler(signum: int, frame: FrameType) -> None: ... diff --git a/stdlib/@python2/site.pyi b/stdlib/@python2/site.pyi deleted file mode 100644 index c77c9397f612..000000000000 --- a/stdlib/@python2/site.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Iterable, List - -PREFIXES: List[str] -ENABLE_USER_SITE: bool | None -USER_SITE: str | None -USER_BASE: str | None - -def main() -> None: ... -def addsitedir(sitedir: str, known_paths: Iterable[str] | None = ...) -> None: ... -def getsitepackages(prefixes: Iterable[str] | None = ...) -> List[str]: ... -def getuserbase() -> str: ... -def getusersitepackages() -> str: ... diff --git a/stdlib/@python2/smtpd.pyi b/stdlib/@python2/smtpd.pyi deleted file mode 100644 index 1c17b82d8ab5..000000000000 --- a/stdlib/@python2/smtpd.pyi +++ /dev/null @@ -1,45 +0,0 @@ -import asynchat -import asyncore -import socket -from typing import Any, List, Text, Tuple, Type - -_Address = Tuple[str, int] # (host, port) - -class SMTPChannel(asynchat.async_chat): - COMMAND: int - DATA: int - def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ...) -> None: ... - # base asynchat.async_chat.push() accepts bytes - def push(self, msg: Text) -> None: ... # type: ignore - def collect_incoming_data(self, data: bytes) -> None: ... - def found_terminator(self) -> None: ... - def smtp_HELO(self, arg: str) -> None: ... - def smtp_NOOP(self, arg: str) -> None: ... - def smtp_QUIT(self, arg: str) -> None: ... - def smtp_MAIL(self, arg: str) -> None: ... - def smtp_RCPT(self, arg: str) -> None: ... - def smtp_RSET(self, arg: str) -> None: ... - def smtp_DATA(self, arg: str) -> None: ... - -class SMTPServer(asyncore.dispatcher): - channel_class: Type[SMTPChannel] - - data_size_limit: int - enable_SMTPUTF8: bool - def __init__(self, localaddr: _Address, remoteaddr: _Address, data_size_limit: int = ...) -> None: ... - def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... - def process_message( - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str, **kwargs: Any - ) -> str | None: ... - -class DebuggingServer(SMTPServer): ... - -class PureProxy(SMTPServer): - def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str - ) -> str | None: ... - -class MailmanProxy(PureProxy): - def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str - ) -> str | None: ... diff --git a/stdlib/@python2/smtplib.pyi b/stdlib/@python2/smtplib.pyi deleted file mode 100644 index 438221a439b7..000000000000 --- a/stdlib/@python2/smtplib.pyi +++ /dev/null @@ -1,86 +0,0 @@ -from typing import Any - -class SMTPException(Exception): ... -class SMTPServerDisconnected(SMTPException): ... - -class SMTPResponseException(SMTPException): - smtp_code: Any - smtp_error: Any - args: Any - def __init__(self, code, msg) -> None: ... - -class SMTPSenderRefused(SMTPResponseException): - smtp_code: Any - smtp_error: Any - sender: Any - args: Any - def __init__(self, code, msg, sender) -> None: ... - -class SMTPRecipientsRefused(SMTPException): - recipients: Any - args: Any - def __init__(self, recipients) -> None: ... - -class SMTPDataError(SMTPResponseException): ... -class SMTPConnectError(SMTPResponseException): ... -class SMTPHeloError(SMTPResponseException): ... -class SMTPAuthenticationError(SMTPResponseException): ... - -def quoteaddr(addr): ... -def quotedata(data): ... - -class SSLFakeFile: - sslobj: Any - def __init__(self, sslobj) -> None: ... - def readline(self, size=...): ... - def close(self): ... - -class SMTP: - debuglevel: Any - file: Any - helo_resp: Any - ehlo_msg: Any - ehlo_resp: Any - does_esmtp: Any - default_port: Any - timeout: Any - esmtp_features: Any - local_hostname: Any - def __init__(self, host: str = ..., port: int = ..., local_hostname=..., timeout=...) -> None: ... - def set_debuglevel(self, debuglevel): ... - sock: Any - def connect(self, host=..., port=...): ... - def send(self, str): ... - def putcmd(self, cmd, args=...): ... - def getreply(self): ... - def docmd(self, cmd, args=...): ... - def helo(self, name=...): ... - def ehlo(self, name=...): ... - def has_extn(self, opt): ... - def help(self, args=...): ... - def rset(self): ... - def noop(self): ... - def mail(self, sender, options=...): ... - def rcpt(self, recip, options=...): ... - def data(self, msg): ... - def verify(self, address): ... - vrfy: Any - def expn(self, address): ... - def ehlo_or_helo_if_needed(self): ... - def login(self, user, password): ... - def starttls(self, keyfile=..., certfile=...): ... - def sendmail(self, from_addr, to_addrs, msg, mail_options=..., rcpt_options=...): ... - def close(self): ... - def quit(self): ... - -class SMTP_SSL(SMTP): - default_port: Any - keyfile: Any - certfile: Any - def __init__(self, host=..., port=..., local_hostname=..., keyfile=..., certfile=..., timeout=...) -> None: ... - -class LMTP(SMTP): - ehlo_msg: Any - def __init__(self, host=..., port=..., local_hostname=...) -> None: ... - sock: Any - def connect(self, host=..., port=...): ... diff --git a/stdlib/@python2/sndhdr.pyi b/stdlib/@python2/sndhdr.pyi deleted file mode 100644 index 189529fd21d6..000000000000 --- a/stdlib/@python2/sndhdr.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Text, Tuple, Union - -_SndHeaders = Tuple[str, int, int, int, Union[int, str]] - -def what(filename: Text) -> _SndHeaders | None: ... -def whathdr(filename: Text) -> _SndHeaders | None: ... diff --git a/stdlib/@python2/socket.pyi b/stdlib/@python2/socket.pyi deleted file mode 100644 index 2bf719dd9faa..000000000000 --- a/stdlib/@python2/socket.pyi +++ /dev/null @@ -1,471 +0,0 @@ -import sys -from typing import Any, BinaryIO, Iterable, List, Text, Tuple, TypeVar, Union, overload - -# ----- Constants ----- -# Some socket families are listed in the "Socket families" section of the docs, -# but not the "Constants" section. These are listed at the end of the list of -# constants. -# -# Besides those and the first few constants listed, the constants are listed in -# documentation order. - -# Constants defined by Python (i.e. not OS constants re-exported from C) -has_ipv6: bool -SocketType: Any -# Re-exported errno -EAGAIN: int -EBADF: int -EINTR: int -EWOULDBLOCK: int - -# Constants re-exported from C - -# Per socketmodule.c, only these three families are portable -AF_UNIX: AddressFamily -AF_INET: AddressFamily -AF_INET6: AddressFamily - -SOCK_STREAM: SocketKind -SOCK_DGRAM: SocketKind -SOCK_RAW: SocketKind -SOCK_RDM: SocketKind -SOCK_SEQPACKET: SocketKind - -# Address families not mentioned in the docs -AF_AAL5: AddressFamily -AF_APPLETALK: AddressFamily -AF_ASH: AddressFamily -AF_ATMPVC: AddressFamily -AF_ATMSVC: AddressFamily -AF_AX25: AddressFamily -AF_BRIDGE: AddressFamily -AF_DECnet: AddressFamily -AF_ECONET: AddressFamily -AF_IPX: AddressFamily -AF_IRDA: AddressFamily -AF_KEY: AddressFamily -AF_LLC: AddressFamily -AF_NETBEUI: AddressFamily -AF_NETROM: AddressFamily -AF_PPPOX: AddressFamily -AF_ROSE: AddressFamily -AF_ROUTE: AddressFamily -AF_SECURITY: AddressFamily -AF_SNA: AddressFamily -AF_SYSTEM: AddressFamily -AF_UNSPEC: AddressFamily -AF_WANPIPE: AddressFamily -AF_X25: AddressFamily - -# The "many constants" referenced by the docs -SOMAXCONN: int -AI_ADDRCONFIG: AddressInfo -AI_ALL: AddressInfo -AI_CANONNAME: AddressInfo -AI_DEFAULT: AddressInfo -AI_MASK: AddressInfo -AI_NUMERICHOST: AddressInfo -AI_NUMERICSERV: AddressInfo -AI_PASSIVE: AddressInfo -AI_V4MAPPED: AddressInfo -AI_V4MAPPED_CFG: AddressInfo -EAI_ADDRFAMILY: int -EAI_AGAIN: int -EAI_BADFLAGS: int -EAI_BADHINTS: int -EAI_FAIL: int -EAI_FAMILY: int -EAI_MAX: int -EAI_MEMORY: int -EAI_NODATA: int -EAI_NONAME: int -EAI_OVERFLOW: int -EAI_PROTOCOL: int -EAI_SERVICE: int -EAI_SOCKTYPE: int -EAI_SYSTEM: int -INADDR_ALLHOSTS_GROUP: int -INADDR_ANY: int -INADDR_BROADCAST: int -INADDR_LOOPBACK: int -INADDR_MAX_LOCAL_GROUP: int -INADDR_NONE: int -INADDR_UNSPEC_GROUP: int -IPPORT_RESERVED: int -IPPORT_USERRESERVED: int -IPPROTO_AH: int -IPPROTO_BIP: int -IPPROTO_DSTOPTS: int -IPPROTO_EGP: int -IPPROTO_EON: int -IPPROTO_ESP: int -IPPROTO_FRAGMENT: int -IPPROTO_GGP: int -IPPROTO_GRE: int -IPPROTO_HELLO: int -IPPROTO_HOPOPTS: int -IPPROTO_ICMP: int -IPPROTO_ICMPV6: int -IPPROTO_IDP: int -IPPROTO_IGMP: int -IPPROTO_IP: int -IPPROTO_IPCOMP: int -IPPROTO_IPIP: int -IPPROTO_IPV4: int -IPPROTO_IPV6: int -IPPROTO_MAX: int -IPPROTO_MOBILE: int -IPPROTO_ND: int -IPPROTO_NONE: int -IPPROTO_PIM: int -IPPROTO_PUP: int -IPPROTO_RAW: int -IPPROTO_ROUTING: int -IPPROTO_RSVP: int -IPPROTO_SCTP: int -IPPROTO_TCP: int -IPPROTO_TP: int -IPPROTO_UDP: int -IPPROTO_VRRP: int -IPPROTO_XTP: int -IPV6_CHECKSUM: int -IPV6_DONTFRAG: int -IPV6_DSTOPTS: int -IPV6_HOPLIMIT: int -IPV6_HOPOPTS: int -IPV6_JOIN_GROUP: int -IPV6_LEAVE_GROUP: int -IPV6_MULTICAST_HOPS: int -IPV6_MULTICAST_IF: int -IPV6_MULTICAST_LOOP: int -IPV6_NEXTHOP: int -IPV6_PATHMTU: int -IPV6_PKTINFO: int -IPV6_RECVDSTOPTS: int -IPV6_RECVHOPLIMIT: int -IPV6_RECVHOPOPTS: int -IPV6_RECVPATHMTU: int -IPV6_RECVPKTINFO: int -IPV6_RECVRTHDR: int -IPV6_RECVTCLASS: int -IPV6_RTHDR: int -IPV6_RTHDRDSTOPTS: int -IPV6_RTHDR_TYPE_0: int -IPV6_TCLASS: int -IPV6_UNICAST_HOPS: int -IPV6_USE_MIN_MTU: int -IPV6_V6ONLY: int -IPX_TYPE: int -IP_ADD_MEMBERSHIP: int -IP_DEFAULT_MULTICAST_LOOP: int -IP_DEFAULT_MULTICAST_TTL: int -IP_DROP_MEMBERSHIP: int -IP_HDRINCL: int -IP_MAX_MEMBERSHIPS: int -IP_MULTICAST_IF: int -IP_MULTICAST_LOOP: int -IP_MULTICAST_TTL: int -IP_OPTIONS: int -IP_RECVDSTADDR: int -IP_RECVOPTS: int -IP_RECVRETOPTS: int -IP_RETOPTS: int -IP_TOS: int -IP_TRANSPARENT: int -IP_TTL: int -LOCAL_PEERCRED: int -MSG_BCAST: MsgFlag -MSG_BTAG: MsgFlag -MSG_CMSG_CLOEXEC: MsgFlag -MSG_CONFIRM: MsgFlag -MSG_CTRUNC: MsgFlag -MSG_DONTROUTE: MsgFlag -MSG_DONTWAIT: MsgFlag -MSG_EOF: MsgFlag -MSG_EOR: MsgFlag -MSG_ERRQUEUE: MsgFlag -MSG_ETAG: MsgFlag -MSG_FASTOPEN: MsgFlag -MSG_MCAST: MsgFlag -MSG_MORE: MsgFlag -MSG_NOSIGNAL: MsgFlag -MSG_NOTIFICATION: MsgFlag -MSG_OOB: MsgFlag -MSG_PEEK: MsgFlag -MSG_TRUNC: MsgFlag -MSG_WAITALL: MsgFlag -NI_DGRAM: int -NI_MAXHOST: int -NI_MAXSERV: int -NI_NAMEREQD: int -NI_NOFQDN: int -NI_NUMERICHOST: int -NI_NUMERICSERV: int -SCM_CREDENTIALS: int -SCM_CREDS: int -SCM_RIGHTS: int -SHUT_RD: int -SHUT_RDWR: int -SHUT_WR: int -SOL_ATALK: int -SOL_AX25: int -SOL_HCI: int -SOL_IP: int -SOL_IPX: int -SOL_NETROM: int -SOL_ROSE: int -SOL_SOCKET: int -SOL_TCP: int -SOL_UDP: int -SO_ACCEPTCONN: int -SO_BINDTODEVICE: int -SO_BROADCAST: int -SO_DEBUG: int -SO_DONTROUTE: int -SO_ERROR: int -SO_EXCLUSIVEADDRUSE: int -SO_KEEPALIVE: int -SO_LINGER: int -SO_MARK: int -SO_OOBINLINE: int -SO_PASSCRED: int -SO_PEERCRED: int -SO_PRIORITY: int -SO_RCVBUF: int -SO_RCVLOWAT: int -SO_RCVTIMEO: int -SO_REUSEADDR: int -SO_REUSEPORT: int -SO_SETFIB: int -SO_SNDBUF: int -SO_SNDLOWAT: int -SO_SNDTIMEO: int -SO_TYPE: int -SO_USELOOPBACK: int -TCP_CORK: int -TCP_DEFER_ACCEPT: int -TCP_FASTOPEN: int -TCP_INFO: int -TCP_KEEPCNT: int -TCP_KEEPIDLE: int -TCP_KEEPINTVL: int -TCP_LINGER2: int -TCP_MAXSEG: int -TCP_NODELAY: int -TCP_QUICKACK: int -TCP_SYNCNT: int -TCP_WINDOW_CLAMP: int -# Specifically-documented constants - -if sys.platform == "linux": - AF_PACKET: AddressFamily - PF_PACKET: int - PACKET_BROADCAST: int - PACKET_FASTROUTE: int - PACKET_HOST: int - PACKET_LOOPBACK: int - PACKET_MULTICAST: int - PACKET_OTHERHOST: int - PACKET_OUTGOING: int - -if sys.platform == "win32": - SIO_RCVALL: int - SIO_KEEPALIVE_VALS: int - RCVALL_IPLEVEL: int - RCVALL_MAX: int - RCVALL_OFF: int - RCVALL_ON: int - RCVALL_SOCKETLEVELONLY: int - -if sys.platform == "linux": - AF_TIPC: AddressFamily - SOL_TIPC: int - TIPC_ADDR_ID: int - TIPC_ADDR_NAME: int - TIPC_ADDR_NAMESEQ: int - TIPC_CFG_SRV: int - TIPC_CLUSTER_SCOPE: int - TIPC_CONN_TIMEOUT: int - TIPC_CRITICAL_IMPORTANCE: int - TIPC_DEST_DROPPABLE: int - TIPC_HIGH_IMPORTANCE: int - TIPC_IMPORTANCE: int - TIPC_LOW_IMPORTANCE: int - TIPC_MEDIUM_IMPORTANCE: int - TIPC_NODE_SCOPE: int - TIPC_PUBLISHED: int - TIPC_SRC_DROPPABLE: int - TIPC_SUBSCR_TIMEOUT: int - TIPC_SUB_CANCEL: int - TIPC_SUB_PORTS: int - TIPC_SUB_SERVICE: int - TIPC_TOP_SRV: int - TIPC_WAIT_FOREVER: int - TIPC_WITHDRAWN: int - TIPC_ZONE_SCOPE: int - -AF_LINK: AddressFamily # Availability: BSD, macOS - -# Semi-documented constants -# (Listed under "Socket families" in the docs, but not "Constants") - -if sys.platform == "linux": - # Netlink is defined by Linux - AF_NETLINK: AddressFamily - NETLINK_ARPD: int - NETLINK_CRYPTO: int - NETLINK_DNRTMSG: int - NETLINK_FIREWALL: int - NETLINK_IP6_FW: int - NETLINK_NFLOG: int - NETLINK_ROUTE6: int - NETLINK_ROUTE: int - NETLINK_SKIP: int - NETLINK_TAPBASE: int - NETLINK_TCPDIAG: int - NETLINK_USERSOCK: int - NETLINK_W1: int - NETLINK_XFRM: int - -if sys.platform != "win32" and sys.platform != "darwin": - # Linux and some BSD support is explicit in the docs - # Windows and macOS do not support in practice - AF_BLUETOOTH: AddressFamily - BTPROTO_HCI: int - BTPROTO_L2CAP: int - BTPROTO_RFCOMM: int - BTPROTO_SCO: int # not in FreeBSD - - BDADDR_ANY: str - BDADDR_LOCAL: str - - HCI_FILTER: int # not in NetBSD or DragonFlyBSD - # not in FreeBSD, NetBSD, or DragonFlyBSD - HCI_TIME_STAMP: int - HCI_DATA_DIR: int - -if sys.platform == "darwin": - # PF_SYSTEM is defined by macOS - PF_SYSTEM: int - SYSPROTO_CONTROL: int - -# enum versions of above flags -AddressFamily = int -SocketKind = int - -AddressInfo = int -MsgFlag = int - -# ----- Exceptions ----- - -class error(IOError): ... - -class herror(error): - def __init__(self, herror: int = ..., string: str = ...) -> None: ... - -class gaierror(error): - def __init__(self, error: int = ..., string: str = ...) -> None: ... - -class timeout(error): - def __init__(self, error: int = ..., string: str = ...) -> None: ... - -# ----- Classes ----- - -# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, -# AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] -_RetAddress = Any -# TODO Most methods allow bytes as address objects - -_WriteBuffer = Union[bytearray, memoryview] - -_CMSG = Tuple[int, int, bytes] -_SelfT = TypeVar("_SelfT", bound=socket) - -class socket: - family: int - type: int - proto: int - def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... - # --- methods --- - def accept(self) -> Tuple[socket, _RetAddress]: ... - def bind(self, address: _Address | bytes) -> None: ... - def close(self) -> None: ... - def connect(self, address: _Address | bytes) -> None: ... - def connect_ex(self, address: _Address | bytes) -> int: ... - def detach(self) -> int: ... - def dup(self) -> socket: ... - def fileno(self) -> int: ... - def getpeername(self) -> _RetAddress: ... - def getsockname(self) -> _RetAddress: ... - @overload - def getsockopt(self, level: int, optname: int) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - def gettimeout(self) -> float | None: ... - if sys.platform == "win32": - def ioctl(self, control: int, option: int | Tuple[int, int, int]) -> None: ... - def listen(self, __backlog: int) -> None: ... - # Note that the makefile's documented windows-specific behavior is not represented - def makefile(self, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... - def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... - def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... - def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... - def send(self, data: bytes, flags: int = ...) -> int: ... - def sendall(self, data: bytes, flags: int = ...) -> None: ... # return type: None on success - @overload - def sendto(self, data: bytes, address: _Address) -> int: ... - @overload - def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... - def setblocking(self, flag: bool) -> None: ... - def settimeout(self, value: float | None) -> None: ... - def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... - if sys.platform == "win32": - def share(self, process_id: int) -> bytes: ... - def shutdown(self, how: int) -> None: ... - -# ----- Functions ----- - -def create_connection( - address: Tuple[str | None, int], - timeout: float | None = ..., - source_address: Tuple[bytearray | bytes | Text, int] | None = ..., -) -> socket: ... -def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... - -# the 5th tuple item is an address -def getaddrinfo( - host: bytearray | bytes | Text | None, - port: str | int | None, - family: int = ..., - socktype: int = ..., - proto: int = ..., - flags: int = ..., -) -> List[Tuple[AddressFamily, SocketKind, int, str, Tuple[Any, ...]]]: ... -def getfqdn(name: str = ...) -> str: ... -def gethostbyname(hostname: str) -> str: ... -def gethostbyname_ex(hostname: str) -> Tuple[str, List[str], List[str]]: ... -def gethostname() -> str: ... -def gethostbyaddr(ip_address: str) -> Tuple[str, List[str], List[str]]: ... -def getnameinfo(sockaddr: Tuple[str, int] | Tuple[str, int, int, int], flags: int) -> Tuple[str, str]: ... -def getprotobyname(protocolname: str) -> int: ... -def getservbyname(servicename: str, protocolname: str = ...) -> int: ... -def getservbyport(port: int, protocolname: str = ...) -> str: ... - -if sys.platform == "win32": - def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... - -else: - def socketpair(family: int | None = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... - -def ntohl(x: int) -> int: ... # param & ret val are 32-bit ints -def ntohs(x: int) -> int: ... # param & ret val are 16-bit ints -def htonl(x: int) -> int: ... # param & ret val are 32-bit ints -def htons(x: int) -> int: ... # param & ret val are 16-bit ints -def inet_aton(ip_string: str) -> bytes: ... # ret val 4 bytes in length -def inet_ntoa(packed_ip: bytes) -> str: ... -def inet_pton(address_family: int, ip_string: str) -> bytes: ... -def inet_ntop(address_family: int, packed_ip: bytes) -> str: ... -def getdefaulttimeout() -> float | None: ... -def setdefaulttimeout(timeout: float | None) -> None: ... diff --git a/stdlib/@python2/spwd.pyi b/stdlib/@python2/spwd.pyi deleted file mode 100644 index 756c142a61da..000000000000 --- a/stdlib/@python2/spwd.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import List, NamedTuple - -class struct_spwd(NamedTuple): - sp_nam: str - sp_pwd: str - sp_lstchg: int - sp_min: int - sp_max: int - sp_warn: int - sp_inact: int - sp_expire: int - sp_flag: int - -def getspall() -> List[struct_spwd]: ... -def getspnam(name: str) -> struct_spwd: ... diff --git a/stdlib/@python2/sqlite3/__init__.pyi b/stdlib/@python2/sqlite3/__init__.pyi deleted file mode 100644 index d5d20d67b58e..000000000000 --- a/stdlib/@python2/sqlite3/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from sqlite3.dbapi2 import * # noqa: F403 diff --git a/stdlib/@python2/sqlite3/dbapi2.pyi b/stdlib/@python2/sqlite3/dbapi2.pyi deleted file mode 100644 index 023a0506f4aa..000000000000 --- a/stdlib/@python2/sqlite3/dbapi2.pyi +++ /dev/null @@ -1,251 +0,0 @@ -from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, List, Protocol, Text, Tuple, Type, TypeVar - -_T = TypeVar("_T") - -paramstyle: str -threadsafety: int -apilevel: str -Date = date -Time = time -Timestamp = datetime - -def DateFromTicks(ticks: float) -> Date: ... -def TimeFromTicks(ticks: float) -> Time: ... -def TimestampFromTicks(ticks: float) -> Timestamp: ... - -version_info: Tuple[int, int, int] -sqlite_version_info: Tuple[int, int, int] -Binary = buffer - -# The remaining definitions are imported from _sqlite3. - -PARSE_COLNAMES: int -PARSE_DECLTYPES: int -SQLITE_ALTER_TABLE: int -SQLITE_ANALYZE: int -SQLITE_ATTACH: int -SQLITE_CREATE_INDEX: int -SQLITE_CREATE_TABLE: int -SQLITE_CREATE_TEMP_INDEX: int -SQLITE_CREATE_TEMP_TABLE: int -SQLITE_CREATE_TEMP_TRIGGER: int -SQLITE_CREATE_TEMP_VIEW: int -SQLITE_CREATE_TRIGGER: int -SQLITE_CREATE_VIEW: int -SQLITE_DELETE: int -SQLITE_DENY: int -SQLITE_DETACH: int -SQLITE_DROP_INDEX: int -SQLITE_DROP_TABLE: int -SQLITE_DROP_TEMP_INDEX: int -SQLITE_DROP_TEMP_TABLE: int -SQLITE_DROP_TEMP_TRIGGER: int -SQLITE_DROP_TEMP_VIEW: int -SQLITE_DROP_TRIGGER: int -SQLITE_DROP_VIEW: int -SQLITE_IGNORE: int -SQLITE_INSERT: int -SQLITE_OK: int -SQLITE_PRAGMA: int -SQLITE_READ: int -SQLITE_REINDEX: int -SQLITE_SELECT: int -SQLITE_TRANSACTION: int -SQLITE_UPDATE: int -adapters: Any -converters: Any -sqlite_version: str -version: str - -# TODO: adapt needs to get probed -def adapt(obj, protocol, alternate): ... -def complete_statement(sql: str) -> bool: ... -def connect( - database: bytes | Text, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., - cached_statements: int = ..., -) -> Connection: ... -def enable_callback_tracebacks(__enable: bool) -> None: ... -def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: Type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... -def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... - -class Cache(object): - def __init__(self, *args, **kwargs) -> None: ... - def display(self, *args, **kwargs) -> None: ... - def get(self, *args, **kwargs) -> None: ... - -class _AggregateProtocol(Protocol): - def step(self, value: int) -> None: ... - def finalize(self) -> int: ... - -class Connection(object): - DataError: Any - DatabaseError: Any - Error: Any - IntegrityError: Any - InterfaceError: Any - InternalError: Any - NotSupportedError: Any - OperationalError: Any - ProgrammingError: Any - Warning: Any - in_transaction: Any - isolation_level: Any - row_factory: Any - text_factory: Any - total_changes: Any - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def close(self) -> None: ... - def commit(self) -> None: ... - def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... - def create_collation(self, __name: str, __callback: Any) -> None: ... - def create_function(self, name: str, num_params: int, func: Any) -> None: ... - def cursor(self, cursorClass: type | None = ...) -> Cursor: ... - def execute(self, sql: str, parameters: Iterable[Any] = ...) -> Cursor: ... - # TODO: please check in executemany() if seq_of_parameters type is possible like this - def executemany(self, __sql: str, __parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: bytes | Text) -> Cursor: ... - def interrupt(self, *args: Any, **kwargs: Any) -> None: ... - def iterdump(self, *args: Any, **kwargs: Any) -> Generator[str, None, None]: ... - def rollback(self, *args: Any, **kwargs: Any) -> None: ... - # TODO: set_authorizer(authorzer_callback) - # see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_authorizer - # returns [SQLITE_OK, SQLITE_DENY, SQLITE_IGNORE] so perhaps int - def set_authorizer(self, *args: Any, **kwargs: Any) -> None: ... - # set_progress_handler(handler, n) -> see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_progress_handler - def set_progress_handler(self, *args: Any, **kwargs: Any) -> None: ... - def set_trace_callback(self, *args: Any, **kwargs: Any) -> None: ... - # enable_load_extension and load_extension is not available on python distributions compiled - # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 - def enable_load_extension(self, enabled: bool) -> None: ... - def load_extension(self, path: str) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __enter__(self) -> Connection: ... - def __exit__(self, t: type | None, exc: BaseException | None, tb: Any | None) -> None: ... - -class Cursor(Iterator[Any]): - arraysize: Any - connection: Any - description: Any - lastrowid: Any - row_factory: Any - rowcount: int - # TODO: Cursor class accepts exactly 1 argument - # required type is sqlite3.Connection (which is imported as _Connection) - # however, the name of the __init__ variable is unknown - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def close(self, *args: Any, **kwargs: Any) -> None: ... - def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... - def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: bytes | Text) -> Cursor: ... - def fetchall(self) -> List[Any]: ... - def fetchmany(self, size: int | None = ...) -> List[Any]: ... - def fetchone(self) -> Any: ... - def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... - def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... - def __iter__(self) -> Cursor: ... - def next(self) -> Any: ... - -class DataError(DatabaseError): ... -class DatabaseError(Error): ... -class Error(Exception): ... -class IntegrityError(DatabaseError): ... -class InterfaceError(Error): ... -class InternalError(DatabaseError): ... -class NotSupportedError(DatabaseError): ... -class OperationalError(DatabaseError): ... - -class OptimizedUnicode(object): - maketrans: Any - def __init__(self, *args, **kwargs): ... - def capitalize(self, *args, **kwargs): ... - def casefold(self, *args, **kwargs): ... - def center(self, *args, **kwargs): ... - def count(self, *args, **kwargs): ... - def encode(self, *args, **kwargs): ... - def endswith(self, *args, **kwargs): ... - def expandtabs(self, *args, **kwargs): ... - def find(self, *args, **kwargs): ... - def format(self, *args, **kwargs): ... - def format_map(self, *args, **kwargs): ... - def index(self, *args, **kwargs): ... - def isalnum(self, *args, **kwargs): ... - def isalpha(self, *args, **kwargs): ... - def isdecimal(self, *args, **kwargs): ... - def isdigit(self, *args, **kwargs): ... - def isidentifier(self, *args, **kwargs): ... - def islower(self, *args, **kwargs): ... - def isnumeric(self, *args, **kwargs): ... - def isprintable(self, *args, **kwargs): ... - def isspace(self, *args, **kwargs): ... - def istitle(self, *args, **kwargs): ... - def isupper(self, *args, **kwargs): ... - def join(self, *args, **kwargs): ... - def ljust(self, *args, **kwargs): ... - def lower(self, *args, **kwargs): ... - def lstrip(self, *args, **kwargs): ... - def partition(self, *args, **kwargs): ... - def replace(self, *args, **kwargs): ... - def rfind(self, *args, **kwargs): ... - def rindex(self, *args, **kwargs): ... - def rjust(self, *args, **kwargs): ... - def rpartition(self, *args, **kwargs): ... - def rsplit(self, *args, **kwargs): ... - def rstrip(self, *args, **kwargs): ... - def split(self, *args, **kwargs): ... - def splitlines(self, *args, **kwargs): ... - def startswith(self, *args, **kwargs): ... - def strip(self, *args, **kwargs): ... - def swapcase(self, *args, **kwargs): ... - def title(self, *args, **kwargs): ... - def translate(self, *args, **kwargs): ... - def upper(self, *args, **kwargs): ... - def zfill(self, *args, **kwargs): ... - def __add__(self, other): ... - def __contains__(self, *args, **kwargs): ... - def __eq__(self, other): ... - def __format__(self, *args, **kwargs): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... - def __getnewargs__(self, *args, **kwargs): ... - def __gt__(self, other): ... - def __hash__(self): ... - def __iter__(self): ... - def __le__(self, other): ... - def __len__(self, *args, **kwargs): ... - def __lt__(self, other): ... - def __mod__(self, other): ... - def __mul__(self, other): ... - def __ne__(self, other): ... - def __rmod__(self, other): ... - def __rmul__(self, other): ... - -class PrepareProtocol(object): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - -class ProgrammingError(DatabaseError): ... - -class Row(object): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def keys(self, *args: Any, **kwargs: Any): ... - def __eq__(self, other): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... - def __gt__(self, other): ... - def __hash__(self): ... - def __iter__(self): ... - def __le__(self, other): ... - def __len__(self): ... - def __lt__(self, other): ... - def __ne__(self, other): ... - -class Statement(object): - def __init__(self, *args, **kwargs): ... - -class Warning(Exception): ... diff --git a/stdlib/@python2/sre_compile.pyi b/stdlib/@python2/sre_compile.pyi deleted file mode 100644 index efc3e568a07c..000000000000 --- a/stdlib/@python2/sre_compile.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from sre_constants import ( - SRE_FLAG_DEBUG as SRE_FLAG_DEBUG, - SRE_FLAG_DOTALL as SRE_FLAG_DOTALL, - SRE_FLAG_IGNORECASE as SRE_FLAG_IGNORECASE, - SRE_FLAG_LOCALE as SRE_FLAG_LOCALE, - SRE_FLAG_MULTILINE as SRE_FLAG_MULTILINE, - SRE_FLAG_TEMPLATE as SRE_FLAG_TEMPLATE, - SRE_FLAG_UNICODE as SRE_FLAG_UNICODE, - SRE_FLAG_VERBOSE as SRE_FLAG_VERBOSE, - SRE_INFO_CHARSET as SRE_INFO_CHARSET, - SRE_INFO_LITERAL as SRE_INFO_LITERAL, - SRE_INFO_PREFIX as SRE_INFO_PREFIX, -) -from sre_parse import SubPattern -from typing import Any, List, Pattern, Tuple, Type - -MAXCODE: int -STRING_TYPES: Tuple[Type[str], Type[unicode]] -_IsStringType = int - -def isstring(obj: Any) -> _IsStringType: ... -def compile(p: str | bytes | SubPattern, flags: int = ...) -> Pattern[Any]: ... diff --git a/stdlib/@python2/sre_constants.pyi b/stdlib/@python2/sre_constants.pyi deleted file mode 100644 index bc15754d6fa1..000000000000 --- a/stdlib/@python2/sre_constants.pyi +++ /dev/null @@ -1,93 +0,0 @@ -from typing import Dict, List, TypeVar - -MAGIC: int -MAXREPEAT: int - -class error(Exception): ... - -FAILURE: str -SUCCESS: str -ANY: str -ANY_ALL: str -ASSERT: str -ASSERT_NOT: str -AT: str -BIGCHARSET: str -BRANCH: str -CALL: str -CATEGORY: str -CHARSET: str -GROUPREF: str -GROUPREF_IGNORE: str -GROUPREF_EXISTS: str -IN: str -IN_IGNORE: str -INFO: str -JUMP: str -LITERAL: str -LITERAL_IGNORE: str -MARK: str -MAX_REPEAT: str -MAX_UNTIL: str -MIN_REPEAT: str -MIN_UNTIL: str -NEGATE: str -NOT_LITERAL: str -NOT_LITERAL_IGNORE: str -RANGE: str -REPEAT: str -REPEAT_ONE: str -SUBPATTERN: str -MIN_REPEAT_ONE: str -AT_BEGINNING: str -AT_BEGINNING_LINE: str -AT_BEGINNING_STRING: str -AT_BOUNDARY: str -AT_NON_BOUNDARY: str -AT_END: str -AT_END_LINE: str -AT_END_STRING: str -AT_LOC_BOUNDARY: str -AT_LOC_NON_BOUNDARY: str -AT_UNI_BOUNDARY: str -AT_UNI_NON_BOUNDARY: str -CATEGORY_DIGIT: str -CATEGORY_NOT_DIGIT: str -CATEGORY_SPACE: str -CATEGORY_NOT_SPACE: str -CATEGORY_WORD: str -CATEGORY_NOT_WORD: str -CATEGORY_LINEBREAK: str -CATEGORY_NOT_LINEBREAK: str -CATEGORY_LOC_WORD: str -CATEGORY_LOC_NOT_WORD: str -CATEGORY_UNI_DIGIT: str -CATEGORY_UNI_NOT_DIGIT: str -CATEGORY_UNI_SPACE: str -CATEGORY_UNI_NOT_SPACE: str -CATEGORY_UNI_WORD: str -CATEGORY_UNI_NOT_WORD: str -CATEGORY_UNI_LINEBREAK: str -CATEGORY_UNI_NOT_LINEBREAK: str - -_T = TypeVar("_T") - -def makedict(list: List[_T]) -> Dict[_T, int]: ... - -OP_IGNORE: Dict[str, str] -AT_MULTILINE: Dict[str, str] -AT_LOCALE: Dict[str, str] -AT_UNICODE: Dict[str, str] -CH_LOCALE: Dict[str, str] -CH_UNICODE: Dict[str, str] -SRE_FLAG_TEMPLATE: int -SRE_FLAG_IGNORECASE: int -SRE_FLAG_LOCALE: int -SRE_FLAG_MULTILINE: int -SRE_FLAG_DOTALL: int -SRE_FLAG_UNICODE: int -SRE_FLAG_VERBOSE: int -SRE_FLAG_DEBUG: int -SRE_INFO_PREFIX: int -SRE_INFO_LITERAL: int -SRE_INFO_CHARSET: int diff --git a/stdlib/@python2/sre_parse.pyi b/stdlib/@python2/sre_parse.pyi deleted file mode 100644 index 35f6d4d32ae2..000000000000 --- a/stdlib/@python2/sre_parse.pyi +++ /dev/null @@ -1,62 +0,0 @@ -from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union - -SPECIAL_CHARS: str -REPEAT_CHARS: str -DIGITS: Set[Any] -OCTDIGITS: Set[Any] -HEXDIGITS: Set[Any] -WHITESPACE: Set[Any] -ESCAPES: Dict[str, Tuple[str, int]] -CATEGORIES: Dict[str, Tuple[str, str] | Tuple[str, List[Tuple[str, str]]]] -FLAGS: Dict[str, int] - -class Pattern: - flags: int - open: List[int] - groups: int - groupdict: Dict[str, int] - lookbehind: int - def __init__(self) -> None: ... - def opengroup(self, name: str = ...) -> int: ... - def closegroup(self, gid: int) -> None: ... - def checkgroup(self, gid: int) -> bool: ... - -_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] -_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] -_OpInType = List[Tuple[str, int]] -_OpBranchType = Tuple[None, List[SubPattern]] -_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] -_CodeType = Union[str, _AvType] - -class SubPattern: - pattern: str - data: List[_CodeType] - width: int | None - def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... - def dump(self, level: int = ...) -> None: ... - def __len__(self) -> int: ... - def __delitem__(self, index: int | slice) -> None: ... - def __getitem__(self, index: int | slice) -> SubPattern | _CodeType: ... - def __setitem__(self, index: int | slice, code: _CodeType): ... - def insert(self, index, code: _CodeType) -> None: ... - def append(self, code: _CodeType) -> None: ... - def getwidth(self) -> int: ... - -class Tokenizer: - string: str - index: int - def __init__(self, string: str) -> None: ... - def match(self, char: str, skip: int = ...) -> int: ... - def get(self) -> str | None: ... - def tell(self) -> Tuple[int, str | None]: ... - def seek(self, index: int) -> None: ... - -def isident(char: str) -> bool: ... -def isdigit(char: str) -> bool: ... -def isname(name: str) -> bool: ... -def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... - -_Template = Tuple[List[Tuple[int, int]], List[Optional[int]]] - -def parse_template(source: str, pattern: _Pattern[Any]) -> _Template: ... -def expand_template(template: _Template, match: Match[Any]) -> str: ... diff --git a/stdlib/@python2/ssl.pyi b/stdlib/@python2/ssl.pyi deleted file mode 100644 index aabecaaba87a..000000000000 --- a/stdlib/@python2/ssl.pyi +++ /dev/null @@ -1,265 +0,0 @@ -import socket -import sys -from _typeshed import StrPath -from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Tuple, Union, overload -from typing_extensions import Literal - -_PCTRTT = Tuple[Tuple[str, str], ...] -_PCTRTTT = Tuple[_PCTRTT, ...] -_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] -_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] -_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] -_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] - -_SC1ArgT = SSLSocket -_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] - -class SSLError(OSError): - library: str - reason: str - -class SSLZeroReturnError(SSLError): ... -class SSLWantReadError(SSLError): ... -class SSLWantWriteError(SSLError): ... -class SSLSyscallError(SSLError): ... -class SSLEOFError(SSLError): ... -class CertificateError(ValueError): ... - -def wrap_socket( - sock: socket.socket, - keyfile: str | None = ..., - certfile: str | None = ..., - server_side: bool = ..., - cert_reqs: int = ..., - ssl_version: int = ..., - ca_certs: str | None = ..., - do_handshake_on_connect: bool = ..., - suppress_ragged_eofs: bool = ..., - ciphers: str | None = ..., -) -> SSLSocket: ... -def create_default_context( - purpose: Any = ..., *, cafile: str | None = ..., capath: str | None = ..., cadata: Text | bytes | None = ... -) -> SSLContext: ... -def _create_unverified_context( - protocol: int = ..., - *, - cert_reqs: int | None = ..., - check_hostname: bool = ..., - purpose: Any = ..., - certfile: str | None = ..., - keyfile: str | None = ..., - cafile: str | None = ..., - capath: str | None = ..., - cadata: Text | bytes | None = ..., -) -> SSLContext: ... - -_create_default_https_context: Callable[..., SSLContext] - -def RAND_status() -> bool: ... -def RAND_egd(path: str) -> None: ... -def RAND_add(__s: bytes, __entropy: float) -> None: ... -def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ... -def cert_time_to_seconds(cert_time: str) -> int: ... -def get_server_certificate(addr: Tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... -def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... -def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... - -class DefaultVerifyPaths(NamedTuple): - cafile: str - capath: str - openssl_cafile_env: str - openssl_cafile: str - openssl_capath_env: str - openssl_capath: str - -def get_default_verify_paths() -> DefaultVerifyPaths: ... - -if sys.platform == "win32": - def enum_certificates(store_name: str) -> _EnumRetType: ... - def enum_crls(store_name: str) -> _EnumRetType: ... - -CERT_NONE: int -CERT_OPTIONAL: int -CERT_REQUIRED: int - -VERIFY_DEFAULT: int -VERIFY_CRL_CHECK_LEAF: int -VERIFY_CRL_CHECK_CHAIN: int -VERIFY_X509_STRICT: int -VERIFY_X509_TRUSTED_FIRST: int - -PROTOCOL_SSLv23: int -PROTOCOL_SSLv2: int -PROTOCOL_SSLv3: int -PROTOCOL_TLSv1: int -PROTOCOL_TLSv1_1: int -PROTOCOL_TLSv1_2: int -PROTOCOL_TLS: int -OP_ALL: int -OP_NO_SSLv2: int -OP_NO_SSLv3: int -OP_NO_TLSv1: int -OP_NO_TLSv1_1: int -OP_NO_TLSv1_2: int -OP_CIPHER_SERVER_PREFERENCE: int -OP_SINGLE_DH_USE: int -OP_SINGLE_ECDH_USE: int -OP_NO_COMPRESSION: int - -HAS_ALPN: bool -HAS_ECDH: bool -HAS_SNI: bool -HAS_NPN: bool -CHANNEL_BINDING_TYPES: List[str] - -OPENSSL_VERSION: str -OPENSSL_VERSION_INFO: Tuple[int, int, int, int, int] -OPENSSL_VERSION_NUMBER: int - -ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int -ALERT_DESCRIPTION_INTERNAL_ERROR: int -ALERT_DESCRIPTION_ACCESS_DENIED: int -ALERT_DESCRIPTION_BAD_CERTIFICATE: int -ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int -ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int -ALERT_DESCRIPTION_BAD_RECORD_MAC: int -ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int -ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int -ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int -ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int -ALERT_DESCRIPTION_CLOSE_NOTIFY: int -ALERT_DESCRIPTION_DECODE_ERROR: int -ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int -ALERT_DESCRIPTION_DECRYPT_ERROR: int -ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int -ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int -ALERT_DESCRIPTION_NO_RENEGOTIATION: int -ALERT_DESCRIPTION_PROTOCOL_VERSION: int -ALERT_DESCRIPTION_RECORD_OVERFLOW: int -ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int -ALERT_DESCRIPTION_UNKNOWN_CA: int -ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int -ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int -ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int -ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int -ALERT_DESCRIPTION_USER_CANCELLED: int - -class _ASN1Object(NamedTuple): - nid: int - shortname: str - longname: str - oid: str - -class Purpose(_ASN1Object): - SERVER_AUTH: ClassVar[Purpose] - CLIENT_AUTH: ClassVar[Purpose] - -class SSLSocket(socket.socket): - context: SSLContext - server_side: bool - server_hostname: str | None - def __init__( - self, - sock: socket.socket | None = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - server_side: bool = ..., - cert_reqs: int = ..., - ssl_version: int = ..., - ca_certs: str | None = ..., - do_handshake_on_connect: bool = ..., - family: int = ..., - type: int = ..., - proto: int = ..., - fileno: int | None = ..., - suppress_ragged_eofs: bool = ..., - npn_protocols: Iterable[str] | None = ..., - ciphers: str | None = ..., - server_hostname: str | None = ..., - _context: SSLContext | None = ..., - _session: Any | None = ..., - ) -> None: ... - def connect(self, addr: socket._Address | bytes) -> None: ... - def connect_ex(self, addr: socket._Address | bytes) -> int: ... - def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... - def recv_into(self, buffer: socket._WriteBuffer, nbytes: int | None = ..., flags: int = ...) -> int: ... - def recvfrom(self, buflen: int = ..., flags: int = ...) -> tuple[bytes, socket._RetAddress]: ... - def recvfrom_into( - self, buffer: socket._WriteBuffer, nbytes: int | None = ..., flags: int = ... - ) -> tuple[int, socket._RetAddress]: ... - @overload - def sendto(self, data: bytes, flags_or_addr: socket._Address) -> int: ... - @overload - def sendto(self, data: bytes, flags_or_addr: int | socket._Address, addr: socket._Address | None = ...) -> int: ... - def read(self, len: int = ..., buffer: bytearray | None = ...) -> bytes: ... - def write(self, data: bytes) -> int: ... - def do_handshake(self, block: bool = ...) -> None: ... # block is undocumented - @overload - def getpeercert(self, binary_form: Literal[False] = ...) -> _PeerCertRetDictType | None: ... - @overload - def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... - @overload - def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... - def cipher(self) -> Tuple[str, str, int] | None: ... - def compression(self) -> str | None: ... - def get_channel_binding(self, cb_type: str = ...) -> bytes | None: ... - def selected_alpn_protocol(self) -> str | None: ... - def selected_npn_protocol(self) -> str | None: ... - def accept(self) -> Tuple[SSLSocket, socket._RetAddress]: ... - def unwrap(self) -> socket.socket: ... - def version(self) -> str | None: ... - def pending(self) -> int: ... - -class SSLContext: - check_hostname: bool - options: int - def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> SSLContext: ... - @property - def protocol(self) -> int: ... - verify_flags: int - verify_mode: int - def __init__(self, protocol: int) -> None: ... - def cert_store_stats(self) -> Dict[str, int]: ... - def load_cert_chain(self, certfile: StrPath, keyfile: StrPath | None = ..., password: _PasswordType | None = ...) -> None: ... - def load_default_certs(self, purpose: Purpose = ...) -> None: ... - def load_verify_locations( - self, cafile: StrPath | None = ..., capath: StrPath | None = ..., cadata: Text | bytes | None = ... - ) -> None: ... - def get_ca_certs(self, binary_form: bool = ...) -> List[_PeerCertRetDictType] | List[bytes]: ... - def set_default_verify_paths(self) -> None: ... - def set_ciphers(self, __cipherlist: str) -> None: ... - def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... - def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... - def set_servername_callback(self, __method: _SrvnmeCbType | None) -> None: ... - def load_dh_params(self, __path: str) -> None: ... - def set_ecdh_curve(self, __name: str) -> None: ... - def wrap_socket( - self, - sock: socket.socket, - server_side: bool = ..., - do_handshake_on_connect: bool = ..., - suppress_ragged_eofs: bool = ..., - server_hostname: str | None = ..., - ) -> SSLSocket: ... - def session_stats(self) -> Dict[str, int]: ... - -# TODO below documented in cpython but not in docs.python.org -# taken from python 3.4 -SSL_ERROR_EOF: int -SSL_ERROR_INVALID_ERROR_CODE: int -SSL_ERROR_SSL: int -SSL_ERROR_SYSCALL: int -SSL_ERROR_WANT_CONNECT: int -SSL_ERROR_WANT_READ: int -SSL_ERROR_WANT_WRITE: int -SSL_ERROR_WANT_X509_LOOKUP: int -SSL_ERROR_ZERO_RETURN: int - -def get_protocol_name(protocol_code: int) -> str: ... - -AF_INET: int -PEM_FOOTER: str -PEM_HEADER: str -SOCK_STREAM: int -SOL_SOCKET: int -SO_TYPE: int diff --git a/stdlib/@python2/stat.pyi b/stdlib/@python2/stat.pyi deleted file mode 100644 index b75c955d7ed9..000000000000 --- a/stdlib/@python2/stat.pyi +++ /dev/null @@ -1,58 +0,0 @@ -def S_ISDIR(mode: int) -> bool: ... -def S_ISCHR(mode: int) -> bool: ... -def S_ISBLK(mode: int) -> bool: ... -def S_ISREG(mode: int) -> bool: ... -def S_ISFIFO(mode: int) -> bool: ... -def S_ISLNK(mode: int) -> bool: ... -def S_ISSOCK(mode: int) -> bool: ... -def S_IMODE(mode: int) -> int: ... -def S_IFMT(mode: int) -> int: ... - -ST_MODE: int -ST_INO: int -ST_DEV: int -ST_NLINK: int -ST_UID: int -ST_GID: int -ST_SIZE: int -ST_ATIME: int -ST_MTIME: int -ST_CTIME: int -S_IFSOCK: int -S_IFLNK: int -S_IFREG: int -S_IFBLK: int -S_IFDIR: int -S_IFCHR: int -S_IFIFO: int -S_ISUID: int -S_ISGID: int -S_ISVTX: int -S_IRWXU: int -S_IRUSR: int -S_IWUSR: int -S_IXUSR: int -S_IRWXG: int -S_IRGRP: int -S_IWGRP: int -S_IXGRP: int -S_IRWXO: int -S_IROTH: int -S_IWOTH: int -S_IXOTH: int -S_ENFMT: int -S_IREAD: int -S_IWRITE: int -S_IEXEC: int -UF_NODUMP: int -UF_IMMUTABLE: int -UF_APPEND: int -UF_OPAQUE: int -UF_NOUNLINK: int -UF_COMPRESSED: int -UF_HIDDEN: int -SF_ARCHIVED: int -SF_IMMUTABLE: int -SF_APPEND: int -SF_NOUNLINK: int -SF_SNAPSHOT: int diff --git a/stdlib/@python2/string.pyi b/stdlib/@python2/string.pyi deleted file mode 100644 index fe028dab39bd..000000000000 --- a/stdlib/@python2/string.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Any, AnyStr, Iterable, List, Mapping, Sequence, Text, Tuple, overload - -ascii_letters: str -ascii_lowercase: str -ascii_uppercase: str -digits: str -hexdigits: str -letters: str -lowercase: str -octdigits: str -punctuation: str -printable: str -uppercase: str -whitespace: str - -def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... - -# TODO: originally named 'from' -def maketrans(_from: str, to: str) -> str: ... -def atof(s: unicode) -> float: ... -def atoi(s: unicode, base: int = ...) -> int: ... -def atol(s: unicode, base: int = ...) -> int: ... -def capitalize(word: AnyStr) -> AnyStr: ... -def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def lower(s: AnyStr) -> AnyStr: ... -def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def joinfields(word: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def lstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... -def rstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... -def strip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... -def swapcase(s: AnyStr) -> AnyStr: ... -def translate(s: str, table: str, deletechars: str = ...) -> str: ... -def upper(s: AnyStr) -> AnyStr: ... -def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def zfill(s: AnyStr, width: int) -> AnyStr: ... -def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... - -class Template: - template: Text - def __init__(self, template: Text) -> None: ... - @overload - def substitute(self, mapping: Mapping[str, str] | Mapping[unicode, str] = ..., **kwds: str) -> str: ... - @overload - def substitute(self, mapping: Mapping[str, Text] | Mapping[unicode, Text] = ..., **kwds: Text) -> Text: ... - @overload - def safe_substitute(self, mapping: Mapping[str, str] | Mapping[unicode, str] = ..., **kwds: str) -> str: ... - @overload - def safe_substitute(self, mapping: Mapping[str, Text] | Mapping[unicode, Text], **kwds: Text) -> Text: ... - -# TODO(MichalPokorny): This is probably badly and/or loosely typed. -class Formatter(object): - def format(self, format_string: str, *args, **kwargs) -> str: ... - def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... - def parse(self, format_string: str) -> Iterable[Tuple[str, str, str, str]]: ... - def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... - def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... - def check_unused_args(self, used_args: Sequence[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... - def format_field(self, value: Any, format_spec: str) -> Any: ... - def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/stdlib/@python2/stringold.pyi b/stdlib/@python2/stringold.pyi deleted file mode 100644 index d221547f1c07..000000000000 --- a/stdlib/@python2/stringold.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from typing import AnyStr, Iterable, List - -whitespace: str -lowercase: str -uppercase: str -letters: str -digits: str -hexdigits: str -octdigits: str -_idmap: str -_idmapL: List[str] | None -index_error = ValueError -atoi_error = ValueError -atof_error = ValueError -atol_error = ValueError - -def lower(s: AnyStr) -> AnyStr: ... -def upper(s: AnyStr) -> AnyStr: ... -def swapcase(s: AnyStr) -> AnyStr: ... -def strip(s: AnyStr) -> AnyStr: ... -def lstrip(s: AnyStr) -> AnyStr: ... -def rstrip(s: AnyStr) -> AnyStr: ... -def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def atof(s: unicode) -> float: ... -def atoi(s: unicode, base: int = ...) -> int: ... -def atol(s: unicode, base: int = ...) -> long: ... -def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def zfill(s: AnyStr, width: int) -> AnyStr: ... -def expandtabs(s: AnyStr, tabsize: int = ...) -> AnyStr: ... -def translate(s: str, table: str, deletions: str = ...) -> str: ... -def capitalize(s: AnyStr) -> AnyStr: ... -def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... -def maketrans(fromstr: str, tostr: str) -> str: ... -def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... diff --git a/stdlib/@python2/stringprep.pyi b/stdlib/@python2/stringprep.pyi deleted file mode 100644 index 604fd2f2cae7..000000000000 --- a/stdlib/@python2/stringprep.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Text - -def in_table_a1(code: Text) -> bool: ... -def in_table_b1(code: Text) -> bool: ... -def map_table_b3(code: Text) -> Text: ... -def map_table_b2(a: Text) -> Text: ... -def in_table_c11(code: Text) -> bool: ... -def in_table_c12(code: Text) -> bool: ... -def in_table_c11_c12(code: Text) -> bool: ... -def in_table_c21(code: Text) -> bool: ... -def in_table_c22(code: Text) -> bool: ... -def in_table_c21_c22(code: Text) -> bool: ... -def in_table_c3(code: Text) -> bool: ... -def in_table_c4(code: Text) -> bool: ... -def in_table_c5(code: Text) -> bool: ... -def in_table_c6(code: Text) -> bool: ... -def in_table_c7(code: Text) -> bool: ... -def in_table_c8(code: Text) -> bool: ... -def in_table_c9(code: Text) -> bool: ... -def in_table_d1(code: Text) -> bool: ... -def in_table_d2(code: Text) -> bool: ... diff --git a/stdlib/@python2/strop.pyi b/stdlib/@python2/strop.pyi deleted file mode 100644 index 81035eaabe79..000000000000 --- a/stdlib/@python2/strop.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import List, Sequence - -lowercase: str -uppercase: str -whitespace: str - -def atof(a: str) -> float: ... -def atoi(a: str, base: int = ...) -> int: ... -def atol(a: str, base: int = ...) -> long: ... -def capitalize(s: str) -> str: ... -def count(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... -def expandtabs(string: str, tabsize: int = ...) -> str: ... -def find(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... -def join(list: Sequence[str], sep: str = ...) -> str: ... -def joinfields(list: Sequence[str], sep: str = ...) -> str: ... -def lower(s: str) -> str: ... -def lstrip(s: str) -> str: ... -def maketrans(frm: str, to: str) -> str: ... -def replace(s: str, old: str, new: str, maxsplit: int = ...) -> str: ... -def rfind(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... -def rstrip(s: str) -> str: ... -def split(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... -def splitfields(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... -def strip(s: str) -> str: ... -def swapcase(s: str) -> str: ... -def translate(s: str, table: str, deletechars: str = ...) -> str: ... -def upper(s: str) -> str: ... diff --git a/stdlib/@python2/struct.pyi b/stdlib/@python2/struct.pyi deleted file mode 100644 index bf27d12783da..000000000000 --- a/stdlib/@python2/struct.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from array import array -from mmap import mmap -from typing import Any, Text, Tuple, Union - -class error(Exception): ... - -_FmtType = Union[bytes, Text] -_BufferType = Union[array[int], bytes, bytearray, buffer, memoryview, mmap] -_WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] - -def pack(fmt: _FmtType, *v: Any) -> bytes: ... -def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... -def unpack(__format: _FmtType, __buffer: _BufferType) -> Tuple[Any, ...]: ... -def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... -def calcsize(__format: _FmtType) -> int: ... - -class Struct: - format: bytes - size: int - def __init__(self, format: _FmtType) -> None: ... - def pack(self, *v: Any) -> bytes: ... - def pack_into(self, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... - def unpack(self, __buffer: _BufferType) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/stdlib/@python2/subprocess.pyi b/stdlib/@python2/subprocess.pyi deleted file mode 100644 index 8c101272322a..000000000000 --- a/stdlib/@python2/subprocess.pyi +++ /dev/null @@ -1,115 +0,0 @@ -from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union - -_FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, Text] -_CMD = Union[_TXT, Sequence[_TXT]] -_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] - -# Same args as Popen.__init__ -def call( - args: _CMD, - bufsize: int = ..., - executable: _TXT = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: _TXT | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., -) -> int: ... -def check_call( - args: _CMD, - bufsize: int = ..., - executable: _TXT = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: _TXT | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., -) -> int: ... - -# Same args as Popen.__init__ except for stdout -def check_output( - args: _CMD, - bufsize: int = ..., - executable: _TXT = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: _TXT | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., -) -> bytes: ... - -PIPE: int -STDOUT: int - -class CalledProcessError(Exception): - returncode: int - # morally: _CMD - cmd: Any - # morally: Optional[bytes] - output: bytes - def __init__(self, returncode: int, cmd: _CMD, output: bytes | None = ...) -> None: ... - -# We use a dummy type variable used to make Popen generic like it is in python 3 -_T = TypeVar("_T", bound=bytes) - -class Popen(Generic[_T]): - stdin: IO[bytes] | None - stdout: IO[bytes] | None - stderr: IO[bytes] | None - pid: int - returncode: int - def __new__( - cls, - args: _CMD, - bufsize: int = ..., - executable: _TXT | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: _TXT | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - ) -> Popen[bytes]: ... - def poll(self) -> int | None: ... - def wait(self) -> int: ... - # morally: -> Tuple[Optional[bytes], Optional[bytes]] - def communicate(self, input: _TXT | None = ...) -> Tuple[bytes, bytes]: ... - def send_signal(self, signal: int) -> None: ... - def terminate(self) -> None: ... - def kill(self) -> None: ... - -def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented - -# Windows-only: STARTUPINFO etc. - -STD_INPUT_HANDLE: Any -STD_OUTPUT_HANDLE: Any -STD_ERROR_HANDLE: Any -SW_HIDE: Any -STARTF_USESTDHANDLES: Any -STARTF_USESHOWWINDOW: Any -CREATE_NEW_CONSOLE: Any -CREATE_NEW_PROCESS_GROUP: Any diff --git a/stdlib/@python2/sunau.pyi b/stdlib/@python2/sunau.pyi deleted file mode 100644 index 3ee4b9651346..000000000000 --- a/stdlib/@python2/sunau.pyi +++ /dev/null @@ -1,66 +0,0 @@ -from typing import IO, Any, NoReturn, Text, Tuple, Union - -_File = Union[Text, IO[bytes]] - -class Error(Exception): ... - -AUDIO_FILE_MAGIC: int -AUDIO_FILE_ENCODING_MULAW_8: int -AUDIO_FILE_ENCODING_LINEAR_8: int -AUDIO_FILE_ENCODING_LINEAR_16: int -AUDIO_FILE_ENCODING_LINEAR_24: int -AUDIO_FILE_ENCODING_LINEAR_32: int -AUDIO_FILE_ENCODING_FLOAT: int -AUDIO_FILE_ENCODING_DOUBLE: int -AUDIO_FILE_ENCODING_ADPCM_G721: int -AUDIO_FILE_ENCODING_ADPCM_G722: int -AUDIO_FILE_ENCODING_ADPCM_G723_3: int -AUDIO_FILE_ENCODING_ADPCM_G723_5: int -AUDIO_FILE_ENCODING_ALAW_8: int -AUDIO_UNKNOWN_SIZE: int - -_sunau_params = Tuple[int, int, int, int, str, str] - -class Au_read: - def __init__(self, f: _File) -> None: ... - def getfp(self) -> IO[bytes] | None: ... - def rewind(self) -> None: ... - def close(self) -> None: ... - def tell(self) -> int: ... - def getnchannels(self) -> int: ... - def getnframes(self) -> int: ... - def getsampwidth(self) -> int: ... - def getframerate(self) -> int: ... - def getcomptype(self) -> str: ... - def getcompname(self) -> str: ... - def getparams(self) -> _sunau_params: ... - def getmarkers(self) -> None: ... - def getmark(self, id: Any) -> NoReturn: ... - def setpos(self, pos: int) -> None: ... - def readframes(self, nframes: int) -> bytes | None: ... - -class Au_write: - def __init__(self, f: _File) -> None: ... - def setnchannels(self, nchannels: int) -> None: ... - def getnchannels(self) -> int: ... - def setsampwidth(self, sampwidth: int) -> None: ... - def getsampwidth(self) -> int: ... - def setframerate(self, framerate: float) -> None: ... - def getframerate(self) -> int: ... - def setnframes(self, nframes: int) -> None: ... - def getnframes(self) -> int: ... - def setcomptype(self, type: str, name: str) -> None: ... - def getcomptype(self) -> str: ... - def getcompname(self) -> str: ... - def setparams(self, params: _sunau_params) -> None: ... - def getparams(self) -> _sunau_params: ... - def tell(self) -> int: ... - # should be any bytes-like object after 3.4, but we don't have a type for that - def writeframesraw(self, data: bytes) -> None: ... - def writeframes(self, data: bytes) -> None: ... - def close(self) -> None: ... - -# Returns a Au_read if mode is rb and Au_write if mode is wb -def open(f: _File, mode: str | None = ...) -> Any: ... - -openfp = open diff --git a/stdlib/@python2/symbol.pyi b/stdlib/@python2/symbol.pyi deleted file mode 100644 index a3561fe6b26f..000000000000 --- a/stdlib/@python2/symbol.pyi +++ /dev/null @@ -1,89 +0,0 @@ -from typing import Dict - -single_input: int -file_input: int -eval_input: int -decorator: int -decorators: int -decorated: int -funcdef: int -parameters: int -varargslist: int -fpdef: int -fplist: int -stmt: int -simple_stmt: int -small_stmt: int -expr_stmt: int -augassign: int -print_stmt: int -del_stmt: int -pass_stmt: int -flow_stmt: int -break_stmt: int -continue_stmt: int -return_stmt: int -yield_stmt: int -raise_stmt: int -import_stmt: int -import_name: int -import_from: int -import_as_name: int -dotted_as_name: int -import_as_names: int -dotted_as_names: int -dotted_name: int -global_stmt: int -exec_stmt: int -assert_stmt: int -compound_stmt: int -if_stmt: int -while_stmt: int -for_stmt: int -try_stmt: int -with_stmt: int -with_item: int -except_clause: int -suite: int -testlist_safe: int -old_test: int -old_lambdef: int -test: int -or_test: int -and_test: int -not_test: int -comparison: int -comp_op: int -expr: int -xor_expr: int -and_expr: int -shift_expr: int -arith_expr: int -term: int -factor: int -power: int -atom: int -listmaker: int -testlist_comp: int -lambdef: int -trailer: int -subscriptlist: int -subscript: int -sliceop: int -exprlist: int -testlist: int -dictorsetmaker: int -classdef: int -arglist: int -argument: int -list_iter: int -list_for: int -list_if: int -comp_iter: int -comp_for: int -comp_if: int -testlist1: int -encoding_decl: int -yield_expr: int - -sym_name: Dict[int, str] diff --git a/stdlib/@python2/symtable.pyi b/stdlib/@python2/symtable.pyi deleted file mode 100644 index bd3f25c7cb63..000000000000 --- a/stdlib/@python2/symtable.pyi +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Any, List, Sequence, Text, Tuple - -def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... - -class SymbolTable(object): - def __init__(self, raw_table: Any, filename: str) -> None: ... - def get_type(self) -> str: ... - def get_id(self) -> int: ... - def get_name(self) -> str: ... - def get_lineno(self) -> int: ... - def is_optimized(self) -> bool: ... - def is_nested(self) -> bool: ... - def has_children(self) -> bool: ... - def has_exec(self) -> bool: ... - def has_import_star(self) -> bool: ... - def get_identifiers(self) -> Sequence[str]: ... - def lookup(self, name: str) -> Symbol: ... - def get_symbols(self) -> List[Symbol]: ... - def get_children(self) -> List[SymbolTable]: ... - -class Function(SymbolTable): - def get_parameters(self) -> Tuple[str, ...]: ... - def get_locals(self) -> Tuple[str, ...]: ... - def get_globals(self) -> Tuple[str, ...]: ... - def get_frees(self) -> Tuple[str, ...]: ... - -class Class(SymbolTable): - def get_methods(self) -> Tuple[str, ...]: ... - -class Symbol(object): - def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ...) -> None: ... - def get_name(self) -> str: ... - def is_referenced(self) -> bool: ... - def is_parameter(self) -> bool: ... - def is_global(self) -> bool: ... - def is_declared_global(self) -> bool: ... - def is_local(self) -> bool: ... - def is_free(self) -> bool: ... - def is_imported(self) -> bool: ... - def is_assigned(self) -> bool: ... - def is_namespace(self) -> bool: ... - def get_namespaces(self) -> Sequence[SymbolTable]: ... - def get_namespace(self) -> SymbolTable: ... diff --git a/stdlib/@python2/sys.pyi b/stdlib/@python2/sys.pyi deleted file mode 100644 index d4858ec251fa..000000000000 --- a/stdlib/@python2/sys.pyi +++ /dev/null @@ -1,130 +0,0 @@ -from types import ClassType, FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, NoReturn, Text, Tuple, Type, Union - -# The following type alias are stub-only and do not exist during runtime -_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] - -class _flags: - bytes_warning: int - debug: int - division_new: int - division_warning: int - dont_write_bytecode: int - hash_randomization: int - ignore_environment: int - inspect: int - interactive: int - no_site: int - no_user_site: int - optimize: int - py3k_warning: int - tabcheck: int - unicode: int - verbose: int - -class _float_info: - max: float - max_exp: int - max_10_exp: int - min: float - min_exp: int - min_10_exp: int - dig: int - mant_dig: int - epsilon: float - radix: int - rounds: int - -class _version_info(Tuple[int, int, int, str, int]): - major: int - minor: int - micro: int - releaselevel: str - serial: int - -_mercurial: Tuple[str, str, str] -api_version: int -argv: List[str] -builtin_module_names: Tuple[str, ...] -byteorder: str -copyright: str -dont_write_bytecode: bool -exec_prefix: str -executable: str -flags: _flags -float_repr_style: str -hexversion: int -long_info: object -maxint: int -maxsize: int -maxunicode: int -modules: Dict[str, Any] -path: List[str] -platform: str -prefix: str -py3kwarning: bool -__stderr__: IO[str] -__stdin__: IO[str] -__stdout__: IO[str] -stderr: IO[str] -stdin: IO[str] -stdout: IO[str] -subversion: Tuple[str, str, str] -version: str -warnoptions: object -float_info: _float_info -version_info: _version_info -ps1: str -ps2: str -last_type: type -last_value: BaseException -last_traceback: TracebackType -# TODO precise types -meta_path: List[Any] -path_hooks: List[Any] -path_importer_cache: Dict[str, Any] -displayhook: Callable[[object], Any] -excepthook: Callable[[Type[BaseException], BaseException, TracebackType], Any] -exc_type: type | None -exc_value: BaseException | ClassType -exc_traceback: TracebackType - -class _WindowsVersionType: - major: Any - minor: Any - build: Any - platform: Any - service_pack: Any - service_pack_major: Any - service_pack_minor: Any - suite_mask: Any - product_type: Any - -def getwindowsversion() -> _WindowsVersionType: ... -def _clear_type_cache() -> None: ... -def _current_frames() -> Dict[int, FrameType]: ... -def _getframe(depth: int = ...) -> FrameType: ... -def call_tracing(fn: Any, args: Any) -> Any: ... -def __displayhook__(value: object) -> None: ... -def __excepthook__(type_: type, value: BaseException, traceback: TracebackType) -> None: ... -def exc_clear() -> None: ... -def exc_info() -> _OptExcInfo: ... - -# sys.exit() accepts an optional argument of anything printable -def exit(arg: Any = ...) -> NoReturn: ... -def getcheckinterval() -> int: ... # deprecated -def getdefaultencoding() -> str: ... -def getdlopenflags() -> int: ... -def getfilesystemencoding() -> str: ... # In practice, never returns None -def getrefcount(arg: Any) -> int: ... -def getrecursionlimit() -> int: ... -def getsizeof(obj: object, default: int = ...) -> int: ... -def getprofile() -> Any | None: ... -def gettrace() -> Any | None: ... -def setcheckinterval(interval: int) -> None: ... # deprecated -def setdlopenflags(n: int) -> None: ... -def setdefaultencoding(encoding: Text) -> None: ... # only exists after reload(sys) -def setprofile(profilefunc: Any) -> None: ... # TODO type -def setrecursionlimit(limit: int) -> None: ... -def settrace(tracefunc: Any) -> None: ... # TODO type diff --git a/stdlib/@python2/sysconfig.pyi b/stdlib/@python2/sysconfig.pyi deleted file mode 100644 index 2bef9e467bc9..000000000000 --- a/stdlib/@python2/sysconfig.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import IO, Any, Dict, List, Tuple, overload - -def get_config_var(name: str) -> str | None: ... -@overload -def get_config_vars() -> Dict[str, Any]: ... -@overload -def get_config_vars(arg: str, *args: str) -> List[Any]: ... -def get_scheme_names() -> Tuple[str, ...]: ... -def get_path_names() -> Tuple[str, ...]: ... -def get_path(name: str, scheme: str = ..., vars: Dict[str, Any] | None = ..., expand: bool = ...) -> str: ... -def get_paths(scheme: str = ..., vars: Dict[str, Any] | None = ..., expand: bool = ...) -> Dict[str, str]: ... -def get_python_version() -> str: ... -def get_platform() -> str: ... -def is_python_build(check_home: bool = ...) -> bool: ... -def parse_config_h(fp: IO[Any], vars: Dict[str, Any] | None = ...) -> Dict[str, Any]: ... -def get_config_h_filename() -> str: ... -def get_makefile_filename() -> str: ... diff --git a/stdlib/@python2/syslog.pyi b/stdlib/@python2/syslog.pyi deleted file mode 100644 index 49169f40db5c..000000000000 --- a/stdlib/@python2/syslog.pyi +++ /dev/null @@ -1,43 +0,0 @@ -from typing import overload - -LOG_ALERT: int -LOG_AUTH: int -LOG_CONS: int -LOG_CRIT: int -LOG_CRON: int -LOG_DAEMON: int -LOG_DEBUG: int -LOG_EMERG: int -LOG_ERR: int -LOG_INFO: int -LOG_KERN: int -LOG_LOCAL0: int -LOG_LOCAL1: int -LOG_LOCAL2: int -LOG_LOCAL3: int -LOG_LOCAL4: int -LOG_LOCAL5: int -LOG_LOCAL6: int -LOG_LOCAL7: int -LOG_LPR: int -LOG_MAIL: int -LOG_NDELAY: int -LOG_NEWS: int -LOG_NOTICE: int -LOG_NOWAIT: int -LOG_PERROR: int -LOG_PID: int -LOG_SYSLOG: int -LOG_USER: int -LOG_UUCP: int -LOG_WARNING: int - -def LOG_MASK(a: int) -> int: ... -def LOG_UPTO(a: int) -> int: ... -def closelog() -> None: ... -def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... -def setlogmask(x: int) -> int: ... -@overload -def syslog(priority: int, message: str) -> None: ... -@overload -def syslog(message: str) -> None: ... diff --git a/stdlib/@python2/tabnanny.pyi b/stdlib/@python2/tabnanny.pyi deleted file mode 100644 index 95873761ee75..000000000000 --- a/stdlib/@python2/tabnanny.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Iterable, Text, Tuple - -verbose: int -filename_only: int - -class NannyNag(Exception): - def __init__(self, lineno: int, msg: str, line: str) -> None: ... - def get_lineno(self) -> int: ... - def get_msg(self) -> str: ... - def get_line(self) -> str: ... - -def check(file: Text) -> None: ... -def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... diff --git a/stdlib/@python2/tarfile.pyi b/stdlib/@python2/tarfile.pyi deleted file mode 100644 index c08c96b6f0d5..000000000000 --- a/stdlib/@python2/tarfile.pyi +++ /dev/null @@ -1,288 +0,0 @@ -import io -from types import TracebackType -from typing import IO, Callable, Dict, Iterable, Iterator, List, Mapping, Text, Tuple, Type - -# tar constants -NUL: bytes -BLOCKSIZE: int -RECORDSIZE: int -GNU_MAGIC: bytes -POSIX_MAGIC: bytes - -LENGTH_NAME: int -LENGTH_LINK: int -LENGTH_PREFIX: int - -REGTYPE: bytes -AREGTYPE: bytes -LNKTYPE: bytes -SYMTYPE: bytes -CONTTYPE: bytes -BLKTYPE: bytes -DIRTYPE: bytes -FIFOTYPE: bytes -CHRTYPE: bytes - -GNUTYPE_LONGNAME: bytes -GNUTYPE_LONGLINK: bytes -GNUTYPE_SPARSE: bytes - -XHDTYPE: bytes -XGLTYPE: bytes -SOLARIS_XHDTYPE: bytes - -USTAR_FORMAT: int -GNU_FORMAT: int -PAX_FORMAT: int -DEFAULT_FORMAT: int - -# tarfile constants - -SUPPORTED_TYPES: Tuple[bytes, ...] -REGULAR_TYPES: Tuple[bytes, ...] -GNU_TYPES: Tuple[bytes, ...] -PAX_FIELDS: Tuple[str, ...] -PAX_NUMBER_FIELDS: Dict[str, type] - -ENCODING: str - -TAR_PLAIN: int -TAR_GZIPPED: int - -def open( - name: Text | None = ..., - mode: str = ..., - fileobj: IO[bytes] | None = ..., - bufsize: int = ..., - *, - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - errors: str = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - compresslevel: int | None = ..., -) -> TarFile: ... - -class ExFileObject(io.BufferedReader): - def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... - -class TarFile(Iterable[TarInfo]): - OPEN_METH: Mapping[str, str] - name: Text | None - mode: str - fileobj: IO[bytes] | None - format: int | None - tarinfo: Type[TarInfo] - dereference: bool | None - ignore_zeros: bool | None - encoding: str | None - errors: str - fileobject: Type[ExFileObject] - pax_headers: Mapping[str, str] | None - debug: int | None - errorlevel: int | None - offset: int # undocumented - posix: bool - def __init__( - self, - name: Text | None = ..., - mode: str = ..., - fileobj: IO[bytes] | None = ..., - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - errors: str = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - copybufsize: int | None = ..., # undocumented - ) -> None: ... - def __enter__(self) -> TarFile: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - def __iter__(self) -> Iterator[TarInfo]: ... - @classmethod - def open( - cls, - name: Text | None = ..., - mode: str = ..., - fileobj: IO[bytes] | None = ..., - bufsize: int = ..., - *, - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - errors: str = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> TarFile: ... - @classmethod - def taropen( - cls, - name: Text | None, - mode: str = ..., - fileobj: IO[bytes] | None = ..., - *, - compresslevel: int = ..., - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> TarFile: ... - @classmethod - def gzopen( - cls, - name: Text | None, - mode: str = ..., - fileobj: IO[bytes] | None = ..., - compresslevel: int = ..., - *, - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> TarFile: ... - @classmethod - def bz2open( - cls, - name: Text | None, - mode: str = ..., - fileobj: IO[bytes] | None = ..., - compresslevel: int = ..., - *, - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> TarFile: ... - @classmethod - def xzopen( - cls, - name: Text | None, - mode: str = ..., - fileobj: IO[bytes] | None = ..., - preset: int | None = ..., - *, - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> TarFile: ... - def getmember(self, name: str) -> TarInfo: ... - def getmembers(self) -> List[TarInfo]: ... - def getnames(self) -> List[str]: ... - def list(self, verbose: bool = ...) -> None: ... - def next(self) -> TarInfo | None: ... - def extractall(self, path: Text = ..., members: Iterable[TarInfo] | None = ...) -> None: ... - def extract(self, member: str | TarInfo, path: Text = ...) -> None: ... - def extractfile(self, member: str | TarInfo) -> IO[bytes] | None: ... - def makedir(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def makefile(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def makeunknown(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def makefifo(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def makedev(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def makelink(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def chown(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def chmod(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def utime(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented - def add( - self, - name: str, - arcname: str | None = ..., - recursive: bool = ..., - exclude: Callable[[str], bool] | None = ..., - filter: Callable[[TarInfo], TarInfo | None] | None = ..., - ) -> None: ... - def addfile(self, tarinfo: TarInfo, fileobj: IO[bytes] | None = ...) -> None: ... - def gettarinfo(self, name: str | None = ..., arcname: str | None = ..., fileobj: IO[bytes] | None = ...) -> TarInfo: ... - def close(self) -> None: ... - -def is_tarfile(name: Text) -> bool: ... -def filemode(mode: int) -> str: ... # undocumented - -class TarFileCompat: - def __init__(self, filename: str, mode: str = ..., compression: int = ...) -> None: ... - -class TarError(Exception): ... -class ReadError(TarError): ... -class CompressionError(TarError): ... -class StreamError(TarError): ... -class ExtractError(TarError): ... -class HeaderError(TarError): ... - -class TarInfo: - name: str - path: str - size: int - mtime: int - chksum: int - devmajor: int - devminor: int - offset: int - offset_data: int - sparse: bytes | None - tarfile: TarFile | None - mode: int - type: bytes - linkname: str - uid: int - gid: int - uname: str - gname: str - pax_headers: Mapping[str, str] - def __init__(self, name: str = ...) -> None: ... - @classmethod - def frombuf(cls, buf: bytes) -> TarInfo: ... - @classmethod - def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... - @property - def linkpath(self) -> str: ... - @linkpath.setter - def linkpath(self, linkname: str) -> None: ... - def get_info(self) -> Mapping[str, str | int | bytes | Mapping[str, str]]: ... - def tobuf(self, format: int | None = ..., encoding: str | None = ..., errors: str = ...) -> bytes: ... - def create_ustar_header( - self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str - ) -> bytes: ... - def create_gnu_header( - self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str - ) -> bytes: ... - def create_pax_header(self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str) -> bytes: ... - @classmethod - def create_pax_global_header(cls, pax_headers: Mapping[str, str]) -> bytes: ... - def isfile(self) -> bool: ... - def isreg(self) -> bool: ... - def issparse(self) -> bool: ... - def isdir(self) -> bool: ... - def issym(self) -> bool: ... - def islnk(self) -> bool: ... - def ischr(self) -> bool: ... - def isblk(self) -> bool: ... - def isfifo(self) -> bool: ... - def isdev(self) -> bool: ... diff --git a/stdlib/@python2/telnetlib.pyi b/stdlib/@python2/telnetlib.pyi deleted file mode 100644 index dfb01f26398e..000000000000 --- a/stdlib/@python2/telnetlib.pyi +++ /dev/null @@ -1,111 +0,0 @@ -import socket -from typing import Any, Callable, Match, Pattern, Sequence, Tuple - -DEBUGLEVEL: int -TELNET_PORT: int - -IAC: bytes -DONT: bytes -DO: bytes -WONT: bytes -WILL: bytes -theNULL: bytes - -SE: bytes -NOP: bytes -DM: bytes -BRK: bytes -IP: bytes -AO: bytes -AYT: bytes -EC: bytes -EL: bytes -GA: bytes -SB: bytes - -BINARY: bytes -ECHO: bytes -RCP: bytes -SGA: bytes -NAMS: bytes -STATUS: bytes -TM: bytes -RCTE: bytes -NAOL: bytes -NAOP: bytes -NAOCRD: bytes -NAOHTS: bytes -NAOHTD: bytes -NAOFFD: bytes -NAOVTS: bytes -NAOVTD: bytes -NAOLFD: bytes -XASCII: bytes -LOGOUT: bytes -BM: bytes -DET: bytes -SUPDUP: bytes -SUPDUPOUTPUT: bytes -SNDLOC: bytes -TTYPE: bytes -EOR: bytes -TUID: bytes -OUTMRK: bytes -TTYLOC: bytes -VT3270REGIME: bytes -X3PAD: bytes -NAWS: bytes -TSPEED: bytes -LFLOW: bytes -LINEMODE: bytes -XDISPLOC: bytes -OLD_ENVIRON: bytes -AUTHENTICATION: bytes -ENCRYPT: bytes -NEW_ENVIRON: bytes - -TN3270E: bytes -XAUTH: bytes -CHARSET: bytes -RSP: bytes -COM_PORT_OPTION: bytes -SUPPRESS_LOCAL_ECHO: bytes -TLS: bytes -KERMIT: bytes -SEND_URL: bytes -FORWARD_X: bytes -PRAGMA_LOGON: bytes -SSPI_LOGON: bytes -PRAGMA_HEARTBEAT: bytes -EXOPL: bytes -NOOPT: bytes - -class Telnet: - host: str | None # undocumented - def __init__(self, host: str | None = ..., port: int = ..., timeout: float = ...) -> None: ... - def open(self, host: str, port: int = ..., timeout: float = ...) -> None: ... - def msg(self, msg: str, *args: Any) -> None: ... - def set_debuglevel(self, debuglevel: int) -> None: ... - def close(self) -> None: ... - def get_socket(self) -> socket.socket: ... - def fileno(self) -> int: ... - def write(self, buffer: bytes) -> None: ... - def read_until(self, match: bytes, timeout: float | None = ...) -> bytes: ... - def read_all(self) -> bytes: ... - def read_some(self) -> bytes: ... - def read_very_eager(self) -> bytes: ... - def read_eager(self) -> bytes: ... - def read_lazy(self) -> bytes: ... - def read_very_lazy(self) -> bytes: ... - def read_sb_data(self) -> bytes: ... - def set_option_negotiation_callback(self, callback: Callable[[socket.socket, bytes, bytes], Any] | None) -> None: ... - def process_rawq(self) -> None: ... - def rawq_getchar(self) -> bytes: ... - def fill_rawq(self) -> None: ... - def sock_avail(self) -> bool: ... - def interact(self) -> None: ... - def mt_interact(self) -> None: ... - def listener(self) -> None: ... - def expect( - self, list: Sequence[Pattern[bytes] | bytes], timeout: float | None = ... - ) -> Tuple[int, Match[bytes] | None, bytes]: ... diff --git a/stdlib/@python2/tempfile.pyi b/stdlib/@python2/tempfile.pyi deleted file mode 100644 index c5f67d243ac8..000000000000 --- a/stdlib/@python2/tempfile.pyi +++ /dev/null @@ -1,100 +0,0 @@ -from random import Random -from thread import LockType -from typing import IO, Any, AnyStr, Iterable, Iterator, List, Text, Tuple, overload - -TMP_MAX: int -tempdir: str -template: str -_name_sequence: _RandomNameSequence | None - -class _RandomNameSequence: - characters: str = ... - mutex: LockType - @property - def rng(self) -> Random: ... - def __iter__(self) -> _RandomNameSequence: ... - def next(self) -> str: ... - # from os.path: - def normcase(self, path: AnyStr) -> AnyStr: ... - -class _TemporaryFileWrapper(IO[str]): - delete: bool - file: IO[str] - name: Any - def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... - def __del__(self) -> None: ... - def __enter__(self) -> _TemporaryFileWrapper: ... - def __exit__(self, exc, value, tb) -> bool | None: ... - def __getattr__(self, name: unicode) -> Any: ... - def close(self) -> None: ... - def unlink(self, path: unicode) -> None: ... - # These methods don't exist directly on this object, but - # are delegated to the underlying IO object through __getattr__. - # We need to add them here so that this class is concrete. - def __iter__(self) -> Iterator[str]: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... - def readable(self) -> bool: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... - def writable(self) -> bool: ... - def write(self, s: Text) -> int: ... - def writelines(self, lines: Iterable[str]) -> None: ... - -# TODO text files - -def TemporaryFile( - mode: bytes | unicode = ..., - bufsize: int = ..., - suffix: bytes | unicode = ..., - prefix: bytes | unicode = ..., - dir: bytes | unicode | None = ..., -) -> _TemporaryFileWrapper: ... -def NamedTemporaryFile( - mode: bytes | unicode = ..., - bufsize: int = ..., - suffix: bytes | unicode = ..., - prefix: bytes | unicode = ..., - dir: bytes | unicode | None = ..., - delete: bool = ..., -) -> _TemporaryFileWrapper: ... -def SpooledTemporaryFile( - max_size: int = ..., - mode: bytes | unicode = ..., - buffering: int = ..., - suffix: bytes | unicode = ..., - prefix: bytes | unicode = ..., - dir: bytes | unicode | None = ..., -) -> _TemporaryFileWrapper: ... - -class TemporaryDirectory: - name: Any - def __init__(self, suffix: bytes | unicode = ..., prefix: bytes | unicode = ..., dir: bytes | unicode = ...) -> None: ... - def cleanup(self) -> None: ... - def __enter__(self) -> Any: ... # Can be str or unicode - def __exit__(self, type, value, traceback) -> None: ... - -@overload -def mkstemp() -> Tuple[int, str]: ... -@overload -def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ..., text: bool = ...) -> Tuple[int, AnyStr]: ... -@overload -def mkdtemp() -> str: ... -@overload -def mkdtemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ...) -> AnyStr: ... -@overload -def mktemp() -> str: ... -@overload -def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ...) -> AnyStr: ... -def gettempdir() -> str: ... -def gettempprefix() -> str: ... -def _candidate_tempdir_list() -> List[str]: ... -def _get_candidate_names() -> _RandomNameSequence | None: ... -def _get_default_tempdir() -> str: ... diff --git a/stdlib/@python2/termios.pyi b/stdlib/@python2/termios.pyi deleted file mode 100644 index 0c627f4b72bd..000000000000 --- a/stdlib/@python2/termios.pyi +++ /dev/null @@ -1,246 +0,0 @@ -from _typeshed import FileDescriptorLike -from typing import Any, List, Union - -_Attr = List[Union[int, List[Union[bytes, int]]]] - -# TODO constants not really documented -B0: int -B1000000: int -B110: int -B115200: int -B1152000: int -B1200: int -B134: int -B150: int -B1500000: int -B1800: int -B19200: int -B200: int -B2000000: int -B230400: int -B2400: int -B2500000: int -B300: int -B3000000: int -B3500000: int -B38400: int -B4000000: int -B460800: int -B4800: int -B50: int -B500000: int -B57600: int -B576000: int -B600: int -B75: int -B921600: int -B9600: int -BRKINT: int -BS0: int -BS1: int -BSDLY: int -CBAUD: int -CBAUDEX: int -CDSUSP: int -CEOF: int -CEOL: int -CEOT: int -CERASE: int -CFLUSH: int -CIBAUD: int -CINTR: int -CKILL: int -CLNEXT: int -CLOCAL: int -CQUIT: int -CR0: int -CR1: int -CR2: int -CR3: int -CRDLY: int -CREAD: int -CRPRNT: int -CRTSCTS: int -CS5: int -CS6: int -CS7: int -CS8: int -CSIZE: int -CSTART: int -CSTOP: int -CSTOPB: int -CSUSP: int -CWERASE: int -ECHO: int -ECHOCTL: int -ECHOE: int -ECHOK: int -ECHOKE: int -ECHONL: int -ECHOPRT: int -EXTA: int -EXTB: int -FF0: int -FF1: int -FFDLY: int -FIOASYNC: int -FIOCLEX: int -FIONBIO: int -FIONCLEX: int -FIONREAD: int -FLUSHO: int -HUPCL: int -ICANON: int -ICRNL: int -IEXTEN: int -IGNBRK: int -IGNCR: int -IGNPAR: int -IMAXBEL: int -INLCR: int -INPCK: int -IOCSIZE_MASK: int -IOCSIZE_SHIFT: int -ISIG: int -ISTRIP: int -IUCLC: int -IXANY: int -IXOFF: int -IXON: int -NCC: int -NCCS: int -NL0: int -NL1: int -NLDLY: int -NOFLSH: int -N_MOUSE: int -N_PPP: int -N_SLIP: int -N_STRIP: int -N_TTY: int -OCRNL: int -OFDEL: int -OFILL: int -OLCUC: int -ONLCR: int -ONLRET: int -ONOCR: int -OPOST: int -PARENB: int -PARMRK: int -PARODD: int -PENDIN: int -TAB0: int -TAB1: int -TAB2: int -TAB3: int -TABDLY: int -TCFLSH: int -TCGETA: int -TCGETS: int -TCIFLUSH: int -TCIOFF: int -TCIOFLUSH: int -TCION: int -TCOFLUSH: int -TCOOFF: int -TCOON: int -TCSADRAIN: int -TCSAFLUSH: int -TCSANOW: int -TCSBRK: int -TCSBRKP: int -TCSETA: int -TCSETAF: int -TCSETAW: int -TCSETS: int -TCSETSF: int -TCSETSW: int -TCXONC: int -TIOCCONS: int -TIOCEXCL: int -TIOCGETD: int -TIOCGICOUNT: int -TIOCGLCKTRMIOS: int -TIOCGPGRP: int -TIOCGSERIAL: int -TIOCGSOFTCAR: int -TIOCGWINSZ: int -TIOCINQ: int -TIOCLINUX: int -TIOCMBIC: int -TIOCMBIS: int -TIOCMGET: int -TIOCMIWAIT: int -TIOCMSET: int -TIOCM_CAR: int -TIOCM_CD: int -TIOCM_CTS: int -TIOCM_DSR: int -TIOCM_DTR: int -TIOCM_LE: int -TIOCM_RI: int -TIOCM_RNG: int -TIOCM_RTS: int -TIOCM_SR: int -TIOCM_ST: int -TIOCNOTTY: int -TIOCNXCL: int -TIOCOUTQ: int -TIOCPKT: int -TIOCPKT_DATA: int -TIOCPKT_DOSTOP: int -TIOCPKT_FLUSHREAD: int -TIOCPKT_FLUSHWRITE: int -TIOCPKT_NOSTOP: int -TIOCPKT_START: int -TIOCPKT_STOP: int -TIOCSCTTY: int -TIOCSERCONFIG: int -TIOCSERGETLSR: int -TIOCSERGETMULTI: int -TIOCSERGSTRUCT: int -TIOCSERGWILD: int -TIOCSERSETMULTI: int -TIOCSERSWILD: int -TIOCSER_TEMT: int -TIOCSETD: int -TIOCSLCKTRMIOS: int -TIOCSPGRP: int -TIOCSSERIAL: int -TIOCSSOFTCAR: int -TIOCSTI: int -TIOCSWINSZ: int -TOSTOP: int -VDISCARD: int -VEOF: int -VEOL: int -VEOL2: int -VERASE: int -VINTR: int -VKILL: int -VLNEXT: int -VMIN: int -VQUIT: int -VREPRINT: int -VSTART: int -VSTOP: int -VSUSP: int -VSWTC: int -VSWTCH: int -VT0: int -VT1: int -VTDLY: int -VTIME: int -VWERASE: int -XCASE: int -XTABS: int - -def tcgetattr(__fd: FileDescriptorLike) -> List[Any]: ... -def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... -def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... -def tcdrain(__fd: FileDescriptorLike) -> None: ... -def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... -def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... - -class error(Exception): ... diff --git a/stdlib/@python2/textwrap.pyi b/stdlib/@python2/textwrap.pyi deleted file mode 100644 index c4147b4bd538..000000000000 --- a/stdlib/@python2/textwrap.pyi +++ /dev/null @@ -1,61 +0,0 @@ -from typing import AnyStr, Dict, List, Pattern - -class TextWrapper(object): - width: int = ... - initial_indent: str = ... - subsequent_indent: str = ... - expand_tabs: bool = ... - replace_whitespace: bool = ... - fix_sentence_endings: bool = ... - drop_whitespace: bool = ... - break_long_words: bool = ... - break_on_hyphens: bool = ... - - # Attributes not present in documentation - sentence_end_re: Pattern[str] = ... - wordsep_re: Pattern[str] = ... - wordsep_simple_re: Pattern[str] = ... - whitespace_trans: str = ... - unicode_whitespace_trans: Dict[int, int] = ... - uspace: int = ... - x: int = ... - def __init__( - self, - width: int = ..., - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ..., - ) -> None: ... - def wrap(self, text: AnyStr) -> List[AnyStr]: ... - def fill(self, text: AnyStr) -> AnyStr: ... - -def wrap( - text: AnyStr, - width: int = ..., - initial_indent: AnyStr = ..., - subsequent_indent: AnyStr = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ..., -) -> List[AnyStr]: ... -def fill( - text: AnyStr, - width: int = ..., - initial_indent: AnyStr = ..., - subsequent_indent: AnyStr = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ..., -) -> AnyStr: ... -def dedent(text: AnyStr) -> AnyStr: ... diff --git a/stdlib/@python2/this.pyi b/stdlib/@python2/this.pyi deleted file mode 100644 index 0687a6675cca..000000000000 --- a/stdlib/@python2/this.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Dict - -s: str -d: Dict[str, str] diff --git a/stdlib/@python2/thread.pyi b/stdlib/@python2/thread.pyi deleted file mode 100644 index b3ba062a498e..000000000000 --- a/stdlib/@python2/thread.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any, Callable - -def _count() -> int: ... - -class error(Exception): ... - -class LockType: - def acquire(self, waitflag: int = ...) -> bool: ... - def acquire_lock(self, waitflag: int = ...) -> bool: ... - def release(self) -> None: ... - def release_lock(self) -> None: ... - def locked(self) -> bool: ... - def locked_lock(self) -> bool: ... - def __enter__(self) -> LockType: ... - def __exit__(self, typ: Any, value: Any, traceback: Any) -> None: ... - -class _local(object): ... -class _localdummy(object): ... - -def start_new(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... -def start_new_thread(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... -def interrupt_main() -> None: ... -def exit() -> None: ... -def exit_thread() -> Any: ... -def allocate_lock() -> LockType: ... -def get_ident() -> int: ... -def stack_size(size: int = ...) -> int: ... diff --git a/stdlib/@python2/threading.pyi b/stdlib/@python2/threading.pyi deleted file mode 100644 index e45a1b5c4a89..000000000000 --- a/stdlib/@python2/threading.pyi +++ /dev/null @@ -1,109 +0,0 @@ -from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar - -# TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] - -_PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") - -__all__: List[str] - -def active_count() -> int: ... -def activeCount() -> int: ... -def current_thread() -> Thread: ... -def currentThread() -> Thread: ... -def enumerate() -> List[Thread]: ... -def settrace(func: _TF) -> None: ... -def setprofile(func: _PF | None) -> None: ... -def stack_size(size: int = ...) -> int: ... - -class ThreadError(Exception): ... - -class local(object): - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... - -class Thread: - name: str - ident: int | None - daemon: bool - def __init__( - self, - group: None = ..., - target: Callable[..., Any] | None = ..., - name: Text | None = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[Text, Any] | None = ..., - ) -> None: ... - def start(self) -> None: ... - def run(self) -> None: ... - def join(self, timeout: float | None = ...) -> None: ... - def getName(self) -> str: ... - def setName(self, name: Text) -> None: ... - def is_alive(self) -> bool: ... - def isAlive(self) -> bool: ... - def isDaemon(self) -> bool: ... - def setDaemon(self, daemonic: bool) -> None: ... - -class _DummyThread(Thread): ... - -class Lock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - def locked(self) -> bool: ... - -class _RLock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - -RLock = _RLock - -class Condition: - def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - def notify(self, n: int = ...) -> None: ... - def notify_all(self) -> None: ... - def notifyAll(self) -> None: ... - -class Semaphore: - def __init__(self, value: int = ...) -> None: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ...) -> bool: ... - def __enter__(self, blocking: bool = ...) -> bool: ... - def release(self) -> None: ... - -class BoundedSemaphore(Semaphore): ... - -class Event: - def __init__(self) -> None: ... - def is_set(self) -> bool: ... - def isSet(self) -> bool: ... - def set(self) -> None: ... - def clear(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - -class Timer(Thread): - def __init__( - self, interval: float, function: Callable[..., Any], args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ... - ) -> None: ... - def cancel(self) -> None: ... diff --git a/stdlib/@python2/time.pyi b/stdlib/@python2/time.pyi deleted file mode 100644 index 48ae9da9c65e..000000000000 --- a/stdlib/@python2/time.pyi +++ /dev/null @@ -1,45 +0,0 @@ -import sys -from typing import Any, NamedTuple, Tuple - -_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] - -accept2dyear: bool -altzone: int -daylight: int -timezone: int -tzname: Tuple[str, str] - -class _struct_time(NamedTuple): - tm_year: int - tm_mon: int - tm_mday: int - tm_hour: int - tm_min: int - tm_sec: int - tm_wday: int - tm_yday: int - tm_isdst: int - @property - def n_fields(self) -> int: ... - @property - def n_sequence_fields(self) -> int: ... - @property - def n_unnamed_fields(self) -> int: ... - -class struct_time(_struct_time): - def __init__(self, o: _TimeTuple, _arg: Any = ...) -> None: ... - def __new__(cls, o: _TimeTuple, _arg: Any = ...) -> struct_time: ... - -def asctime(t: _TimeTuple | struct_time = ...) -> str: ... -def clock() -> float: ... -def ctime(secs: float | None = ...) -> str: ... -def gmtime(secs: float | None = ...) -> struct_time: ... -def localtime(secs: float | None = ...) -> struct_time: ... -def mktime(t: _TimeTuple | struct_time) -> float: ... -def sleep(secs: float) -> None: ... -def strftime(format: str, t: _TimeTuple | struct_time = ...) -> str: ... -def strptime(string: str, format: str = ...) -> struct_time: ... -def time() -> float: ... - -if sys.platform != "win32": - def tzset() -> None: ... # Unix only diff --git a/stdlib/@python2/timeit.pyi b/stdlib/@python2/timeit.pyi deleted file mode 100644 index ecb528725a9c..000000000000 --- a/stdlib/@python2/timeit.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import IO, Any, Callable, List, Sequence, Text, Union - -_str = Union[str, Text] -_Timer = Callable[[], float] -_stmt = Union[_str, Callable[[], Any]] - -default_timer: _Timer - -class Timer: - def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... - def print_exc(self, file: IO[str] | None = ...) -> None: ... - def timeit(self, number: int = ...) -> float: ... - def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... - -def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ...) -> float: ... -def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ...) -> List[float]: ... - -_timerFunc = Callable[[], float] - -def main(args: Sequence[str] | None = ..., *, _wrap_timer: Callable[[_timerFunc], _timerFunc] | None = ...) -> None: ... diff --git a/stdlib/@python2/toaiff.pyi b/stdlib/@python2/toaiff.pyi deleted file mode 100644 index b70e026d6d8e..000000000000 --- a/stdlib/@python2/toaiff.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from pipes import Template -from typing import Dict, List - -table: Dict[str, Template] -t: Template -uncompress: Template - -class error(Exception): ... - -def toaiff(filename: str) -> str: ... -def _toaiff(filename: str, temps: List[str]) -> str: ... diff --git a/stdlib/@python2/token.pyi b/stdlib/@python2/token.pyi deleted file mode 100644 index 4ba710470624..000000000000 --- a/stdlib/@python2/token.pyi +++ /dev/null @@ -1,62 +0,0 @@ -from typing import Dict - -ENDMARKER: int -NAME: int -NUMBER: int -STRING: int -NEWLINE: int -INDENT: int -DEDENT: int -LPAR: int -RPAR: int -LSQB: int -RSQB: int -COLON: int -COMMA: int -SEMI: int -PLUS: int -MINUS: int -STAR: int -SLASH: int -VBAR: int -AMPER: int -LESS: int -GREATER: int -EQUAL: int -DOT: int -PERCENT: int -BACKQUOTE: int -LBRACE: int -RBRACE: int -EQEQUAL: int -NOTEQUAL: int -LESSEQUAL: int -GREATEREQUAL: int -TILDE: int -CIRCUMFLEX: int -LEFTSHIFT: int -RIGHTSHIFT: int -DOUBLESTAR: int -PLUSEQUAL: int -MINEQUAL: int -STAREQUAL: int -SLASHEQUAL: int -PERCENTEQUAL: int -AMPEREQUAL: int -VBAREQUAL: int -CIRCUMFLEXEQUAL: int -LEFTSHIFTEQUAL: int -RIGHTSHIFTEQUAL: int -DOUBLESTAREQUAL: int -DOUBLESLASH: int -DOUBLESLASHEQUAL: int -AT: int -OP: int -ERRORTOKEN: int -N_TOKENS: int -NT_OFFSET: int -tok_name: Dict[int, str] - -def ISTERMINAL(x: int) -> bool: ... -def ISNONTERMINAL(x: int) -> bool: ... -def ISEOF(x: int) -> bool: ... diff --git a/stdlib/@python2/tokenize.pyi b/stdlib/@python2/tokenize.pyi deleted file mode 100644 index 98ec01a6cb75..000000000000 --- a/stdlib/@python2/tokenize.pyi +++ /dev/null @@ -1,133 +0,0 @@ -from typing import Any, Callable, Dict, Generator, Iterable, Iterator, List, Tuple - -__author__: str -__credits__: str - -AMPER: int -AMPEREQUAL: int -AT: int -BACKQUOTE: int -Binnumber: str -Bracket: str -CIRCUMFLEX: int -CIRCUMFLEXEQUAL: int -COLON: int -COMMA: int -COMMENT: int -Comment: str -ContStr: str -DEDENT: int -DOT: int -DOUBLESLASH: int -DOUBLESLASHEQUAL: int -DOUBLESTAR: int -DOUBLESTAREQUAL: int -Decnumber: str -Double: str -Double3: str -ENDMARKER: int -EQEQUAL: int -EQUAL: int -ERRORTOKEN: int -Expfloat: str -Exponent: str -Floatnumber: str -Funny: str -GREATER: int -GREATEREQUAL: int -Hexnumber: str -INDENT: int - -def ISEOF(x: int) -> bool: ... -def ISNONTERMINAL(x: int) -> bool: ... -def ISTERMINAL(x: int) -> bool: ... - -Ignore: str -Imagnumber: str -Intnumber: str -LBRACE: int -LEFTSHIFT: int -LEFTSHIFTEQUAL: int -LESS: int -LESSEQUAL: int -LPAR: int -LSQB: int -MINEQUAL: int -MINUS: int -NAME: int -NEWLINE: int -NL: int -NOTEQUAL: int -NT_OFFSET: int -NUMBER: int -N_TOKENS: int -Name: str -Number: str -OP: int -Octnumber: str -Operator: str -PERCENT: int -PERCENTEQUAL: int -PLUS: int -PLUSEQUAL: int -PlainToken: str -Pointfloat: str -PseudoExtras: str -PseudoToken: str -RBRACE: int -RIGHTSHIFT: int -RIGHTSHIFTEQUAL: int -RPAR: int -RSQB: int -SEMI: int -SLASH: int -SLASHEQUAL: int -STAR: int -STAREQUAL: int -STRING: int -Single: str -Single3: str -Special: str -String: str -TILDE: int -Token: str -Triple: str -VBAR: int -VBAREQUAL: int -Whitespace: str -chain: type -double3prog: type -endprogs: Dict[str, Any] -pseudoprog: type -single3prog: type -single_quoted: Dict[str, str] -t: str -tabsize: int -tok_name: Dict[int, str] -tokenprog: type -triple_quoted: Dict[str, str] -x: str - -_Pos = Tuple[int, int] -_TokenType = Tuple[int, str, _Pos, _Pos, str] - -def any(*args, **kwargs) -> str: ... -def generate_tokens(readline: Callable[[], str]) -> Generator[_TokenType, None, None]: ... -def group(*args: str) -> str: ... -def maybe(*args: str) -> str: ... -def printtoken(type: int, token: str, srow_scol: _Pos, erow_ecol: _Pos, line: str) -> None: ... -def tokenize(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... -def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... -def untokenize(iterable: Iterable[_TokenType]) -> str: ... - -class StopTokenizing(Exception): ... -class TokenError(Exception): ... - -class Untokenizer: - prev_col: int - prev_row: int - tokens: List[str] - def __init__(self) -> None: ... - def add_whitespace(self, _Pos) -> None: ... - def compat(self, token: Tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... - def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/stdlib/@python2/trace.pyi b/stdlib/@python2/trace.pyi deleted file mode 100644 index 62f228673a55..000000000000 --- a/stdlib/@python2/trace.pyi +++ /dev/null @@ -1,49 +0,0 @@ -import types -from _typeshed import StrPath -from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, TypeVar - -_T = TypeVar("_T") -_localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = Tuple[str, Optional[str], str] - -class CoverageResults: - def __init__( - self, - counts: Dict[Tuple[str, int], int] | None = ..., - calledfuncs: Dict[_fileModuleFunction, int] | None = ..., - infile: StrPath | None = ..., - callers: Dict[Tuple[_fileModuleFunction, _fileModuleFunction], int] | None = ..., - outfile: StrPath | None = ..., - ) -> None: ... # undocumented - def update(self, other: CoverageResults) -> None: ... - def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: StrPath | None = ...) -> None: ... - def write_results_file( - self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = ... - ) -> Tuple[int, int]: ... - -class Trace: - def __init__( - self, - count: int = ..., - trace: int = ..., - countfuncs: int = ..., - countcallers: int = ..., - ignoremods: Sequence[str] = ..., - ignoredirs: Sequence[str] = ..., - infile: StrPath | None = ..., - outfile: StrPath | None = ..., - timing: bool = ..., - ) -> None: ... - def run(self, cmd: str | types.CodeType) -> None: ... - def runctx( - self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ... - ) -> None: ... - def runfunc(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... - def file_module_function_of(self, frame: types.FrameType) -> _fileModuleFunction: ... - def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... - def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... - def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ... - def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... - def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... - def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... - def results(self) -> CoverageResults: ... diff --git a/stdlib/@python2/traceback.pyi b/stdlib/@python2/traceback.pyi deleted file mode 100644 index 2152ab255942..000000000000 --- a/stdlib/@python2/traceback.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from types import FrameType, TracebackType -from typing import IO, List, Optional, Tuple, Type - -_PT = Tuple[str, int, str, Optional[str]] - -def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def print_exception( - etype: Type[BaseException] | None, - value: BaseException | None, - tb: TracebackType | None, - limit: int | None = ..., - file: IO[str] | None = ..., -) -> None: ... -def print_exc(limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def print_last(limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def print_stack(f: FrameType | None = ..., limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> List[_PT]: ... -def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> List[_PT]: ... -def format_list(extracted_list: List[_PT]) -> List[str]: ... -def format_exception_only(etype: Type[BaseException] | None, value: BaseException | None) -> List[str]: ... -def format_exception( - etype: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ... -) -> List[str]: ... -def format_exc(limit: int | None = ...) -> str: ... -def format_tb(tb: TracebackType | None, limit: int | None = ...) -> List[str]: ... -def format_stack(f: FrameType | None = ..., limit: int | None = ...) -> List[str]: ... -def tb_lineno(tb: TracebackType) -> int: ... diff --git a/stdlib/@python2/tty.pyi b/stdlib/@python2/tty.pyi deleted file mode 100644 index c0dc418e9933..000000000000 --- a/stdlib/@python2/tty.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import IO, Union - -_FD = Union[int, IO[str]] - -# XXX: Undocumented integer constants -IFLAG: int -OFLAG: int -CFLAG: int -LFLAG: int -ISPEED: int -OSPEED: int -CC: int - -def setraw(fd: _FD, when: int = ...) -> None: ... -def setcbreak(fd: _FD, when: int = ...) -> None: ... diff --git a/stdlib/@python2/turtle.pyi b/stdlib/@python2/turtle.pyi deleted file mode 100644 index 659dfd31b161..000000000000 --- a/stdlib/@python2/turtle.pyi +++ /dev/null @@ -1,504 +0,0 @@ -from typing import Any, Callable, Dict, List, Sequence, Text, Tuple, TypeVar, Union, overload - -# TODO: Replace these aliases once we have Python 2 stubs for the Tkinter module. -Canvas = Any -PhotoImage = Any - -# Note: '_Color' is the alias we use for arguments and _AnyColor is the -# alias we use for return types. Really, these two aliases should be the -# same, but as per the "no union returns" typeshed policy, we'll return -# Any instead. -_Color = Union[Text, Tuple[float, float, float]] -_AnyColor = Any - -# TODO: Replace this with a TypedDict once it becomes standardized. -_PenState = Dict[str, Any] - -_Speed = Union[str, float] -_PolygonCoords = Sequence[Tuple[float, float]] - -# TODO: Type this more accurately -# Vec2D is actually a custom subclass of 'tuple'. -Vec2D = Tuple[float, float] - -class TurtleScreenBase(object): - cv: Canvas = ... - canvwidth: int = ... - canvheight: int = ... - xscale: float = ... - yscale: float = ... - def __init__(self, cv: Canvas) -> None: ... - -class Terminator(Exception): ... -class TurtleGraphicsError(Exception): ... - -class Shape(object): - def __init__(self, type_: str, data: _PolygonCoords | PhotoImage | None = ...) -> None: ... - def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = ...) -> None: ... - -class TurtleScreen(TurtleScreenBase): - def __init__(self, cv: Canvas, mode: str = ..., colormode: float = ..., delay: int = ...) -> None: ... - def clear(self) -> None: ... - @overload - def mode(self, mode: None = ...) -> str: ... - @overload - def mode(self, mode: str) -> None: ... - def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ... - def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = ...) -> None: ... - @overload - def colormode(self, cmode: None = ...) -> float: ... - @overload - def colormode(self, cmode: float) -> None: ... - def reset(self) -> None: ... - def turtles(self) -> List[Turtle]: ... - @overload - def bgcolor(self) -> _AnyColor: ... - @overload - def bgcolor(self, color: _Color) -> None: ... - @overload - def bgcolor(self, r: float, g: float, b: float) -> None: ... - @overload - def tracer(self, n: None = ...) -> int: ... - @overload - def tracer(self, n: int, delay: int | None = ...) -> None: ... - @overload - def delay(self, delay: None = ...) -> int: ... - @overload - def delay(self, delay: int) -> None: ... - def update(self) -> None: ... - def window_width(self) -> int: ... - def window_height(self) -> int: ... - def getcanvas(self) -> Canvas: ... - def getshapes(self) -> List[str]: ... - def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... - def onkey(self, fun: Callable[[], Any], key: str) -> None: ... - def listen(self, xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... - def ontimer(self, fun: Callable[[], Any], t: int = ...) -> None: ... - @overload - def bgpic(self, picname: None = ...) -> str: ... - @overload - def bgpic(self, picname: str) -> None: ... - @overload - def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... - # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well - @overload - def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... - onscreenclick = onclick - resetscreen = reset - clearscreen = clear - addshape = register_shape - -class TNavigator(object): - START_ORIENTATION: Dict[str, Vec2D] = ... - DEFAULT_MODE: str = ... - DEFAULT_ANGLEOFFSET: int = ... - DEFAULT_ANGLEORIENT: int = ... - def __init__(self, mode: str = ...) -> None: ... - def reset(self) -> None: ... - def degrees(self, fullcircle: float = ...) -> None: ... - def radians(self) -> None: ... - def forward(self, distance: float) -> None: ... - def back(self, distance: float) -> None: ... - def right(self, angle: float) -> None: ... - def left(self, angle: float) -> None: ... - def pos(self) -> Vec2D: ... - def xcor(self) -> float: ... - def ycor(self) -> float: ... - @overload - def goto(self, x: Tuple[float, float], y: None = ...) -> None: ... - @overload - def goto(self, x: float, y: float) -> None: ... - def home(self) -> None: ... - def setx(self, x: float) -> None: ... - def sety(self, y: float) -> None: ... - @overload - def distance(self, x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... - @overload - def distance(self, x: float, y: float) -> float: ... - @overload - def towards(self, x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... - @overload - def towards(self, x: float, y: float) -> float: ... - def heading(self) -> float: ... - def setheading(self, to_angle: float) -> None: ... - def circle(self, radius: float, extent: float | None = ..., steps: int | None = ...) -> None: ... - fd = forward - bk = back - backward = back - rt = right - lt = left - position = pos - setpos = goto - setposition = goto - seth = setheading - -class TPen(object): - def __init__(self, resizemode: str = ...) -> None: ... - @overload - def resizemode(self, rmode: None = ...) -> str: ... - @overload - def resizemode(self, rmode: str) -> None: ... - @overload - def pensize(self, width: None = ...) -> int: ... - @overload - def pensize(self, width: int) -> None: ... - def penup(self) -> None: ... - def pendown(self) -> None: ... - def isdown(self) -> bool: ... - @overload - def speed(self, speed: None = ...) -> int: ... - @overload - def speed(self, speed: _Speed) -> None: ... - @overload - def pencolor(self) -> _AnyColor: ... - @overload - def pencolor(self, color: _Color) -> None: ... - @overload - def pencolor(self, r: float, g: float, b: float) -> None: ... - @overload - def fillcolor(self) -> _AnyColor: ... - @overload - def fillcolor(self, color: _Color) -> None: ... - @overload - def fillcolor(self, r: float, g: float, b: float) -> None: ... - @overload - def color(self) -> Tuple[_AnyColor, _AnyColor]: ... - @overload - def color(self, color: _Color) -> None: ... - @overload - def color(self, r: float, g: float, b: float) -> None: ... - @overload - def color(self, color1: _Color, color2: _Color) -> None: ... - def showturtle(self) -> None: ... - def hideturtle(self) -> None: ... - def isvisible(self) -> bool: ... - # Note: signatures 1 and 2 overlap unsafely when no arguments are provided - @overload - def pen(self) -> _PenState: ... # type: ignore - @overload - def pen( - self, - pen: _PenState | None = ..., - *, - shown: bool = ..., - pendown: bool = ..., - pencolor: _Color = ..., - fillcolor: _Color = ..., - pensize: int = ..., - speed: int = ..., - resizemode: str = ..., - stretchfactor: Tuple[float, float] = ..., - outline: int = ..., - tilt: float = ..., - ) -> None: ... - width = pensize - up = penup - pu = penup - pd = pendown - down = pendown - st = showturtle - ht = hideturtle - -_T = TypeVar("_T") - -class RawTurtle(TPen, TNavigator): - def __init__( - self, canvas: Canvas | TurtleScreen | None = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ... - ) -> None: ... - def reset(self) -> None: ... - def setundobuffer(self, size: int | None) -> None: ... - def undobufferentries(self) -> int: ... - def clear(self) -> None: ... - def clone(self: _T) -> _T: ... - @overload - def shape(self, name: None = ...) -> str: ... - @overload - def shape(self, name: str) -> None: ... - # Unsafely overlaps when no arguments are provided - @overload - def shapesize(self) -> Tuple[float, float, float]: ... # type: ignore - @overload - def shapesize( - self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ... - ) -> None: ... - def settiltangle(self, angle: float) -> None: ... - @overload - def tiltangle(self, angle: None = ...) -> float: ... - @overload - def tiltangle(self, angle: float) -> None: ... - def tilt(self, angle: float) -> None: ... - # Can return either 'int' or Tuple[int, ...] based on if the stamp is - # a compound stamp or not. So, as per the "no Union return" policy, - # we return Any. - def stamp(self) -> Any: ... - def clearstamp(self, stampid: int | Tuple[int, ...]) -> None: ... - def clearstamps(self, n: int | None = ...) -> None: ... - def filling(self) -> bool: ... - def begin_fill(self) -> None: ... - def end_fill(self) -> None: ... - def dot(self, size: int | None = ..., *color: _Color) -> None: ... - def write(self, arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> None: ... - def begin_poly(self) -> None: ... - def end_poly(self) -> None: ... - def get_poly(self) -> _PolygonCoords | None: ... - def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... - getpen = getturtle - def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... - def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... - def ondrag(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... - def undo(self) -> None: ... - turtlesize = shapesize - -class _Screen(TurtleScreen): - def __init__(self) -> None: ... - # Note int and float are interpreted differently, hence the Union instead of just float - def setup( - self, width: int | float = ..., height: int | float = ..., startx: int | None = ..., starty: int | None = ... - ) -> None: ... - def title(self, titlestring: str) -> None: ... - def bye(self) -> None: ... - def exitonclick(self) -> None: ... - -class Turtle(RawTurtle): - def __init__(self, shape: str = ..., undobuffersize: int = ..., visible: bool = ...) -> None: ... - -RawPen = RawTurtle -Pen = Turtle - -def write_docstringdict(filename: str = ...) -> None: ... - -# Note: it's somewhat unfortunate that we have to copy the function signatures. -# It would be nice if we could partially reduce the redundancy by doing something -# like the following: -# -# _screen: Screen -# clear = _screen.clear -# -# However, it seems pytype does not support this type of syntax in pyi files. - -# Functions copied from TurtleScreenBase: - -# Note: mainloop() was always present in the global scope, but was added to -# TurtleScreenBase in Python 3.0 -def mainloop() -> None: ... - -# Functions copied from TurtleScreen: - -def clear() -> None: ... -@overload -def mode(mode: None = ...) -> str: ... -@overload -def mode(mode: str) -> None: ... -def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ... -def register_shape(name: str, shape: _PolygonCoords | Shape | None = ...) -> None: ... -@overload -def colormode(cmode: None = ...) -> float: ... -@overload -def colormode(cmode: float) -> None: ... -def reset() -> None: ... -def turtles() -> List[Turtle]: ... -@overload -def bgcolor() -> _AnyColor: ... -@overload -def bgcolor(color: _Color) -> None: ... -@overload -def bgcolor(r: float, g: float, b: float) -> None: ... -@overload -def tracer(n: None = ...) -> int: ... -@overload -def tracer(n: int, delay: int | None = ...) -> None: ... -@overload -def delay(delay: None = ...) -> int: ... -@overload -def delay(delay: int) -> None: ... -def update() -> None: ... -def window_width() -> int: ... -def window_height() -> int: ... -def getcanvas() -> Canvas: ... -def getshapes() -> List[str]: ... -def onclick(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... -def onkey(fun: Callable[[], Any], key: str) -> None: ... -def listen(xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... -def ontimer(fun: Callable[[], Any], t: int = ...) -> None: ... -@overload -def bgpic(picname: None = ...) -> str: ... -@overload -def bgpic(picname: str) -> None: ... -@overload -def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... -@overload -def screensize(canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... - -onscreenclick = onclick -resetscreen = reset -clearscreen = clear -addshape = register_shape -# Functions copied from _Screen: - -def setup(width: float = ..., height: float = ..., startx: int | None = ..., starty: int | None = ...) -> None: ... -def title(titlestring: str) -> None: ... -def bye() -> None: ... -def exitonclick() -> None: ... -def Screen() -> _Screen: ... - -# Functions copied from TNavigator: - -def degrees(fullcircle: float = ...) -> None: ... -def radians() -> None: ... -def forward(distance: float) -> None: ... -def back(distance: float) -> None: ... -def right(angle: float) -> None: ... -def left(angle: float) -> None: ... -def pos() -> Vec2D: ... -def xcor() -> float: ... -def ycor() -> float: ... -@overload -def goto(x: Tuple[float, float], y: None = ...) -> None: ... -@overload -def goto(x: float, y: float) -> None: ... -def home() -> None: ... -def setx(x: float) -> None: ... -def sety(y: float) -> None: ... -@overload -def distance(x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... -@overload -def distance(x: float, y: float) -> float: ... -@overload -def towards(x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... -@overload -def towards(x: float, y: float) -> float: ... -def heading() -> float: ... -def setheading(to_angle: float) -> None: ... -def circle(radius: float, extent: float | None = ..., steps: int | None = ...) -> None: ... - -fd = forward -bk = back -backward = back -rt = right -lt = left -position = pos -setpos = goto -setposition = goto -seth = setheading - -# Functions copied from TPen: -@overload -def resizemode(rmode: None = ...) -> str: ... -@overload -def resizemode(rmode: str) -> None: ... -@overload -def pensize(width: None = ...) -> int: ... -@overload -def pensize(width: int) -> None: ... -def penup() -> None: ... -def pendown() -> None: ... -def isdown() -> bool: ... -@overload -def speed(speed: None = ...) -> int: ... -@overload -def speed(speed: _Speed) -> None: ... -@overload -def pencolor() -> _AnyColor: ... -@overload -def pencolor(color: _Color) -> None: ... -@overload -def pencolor(r: float, g: float, b: float) -> None: ... -@overload -def fillcolor() -> _AnyColor: ... -@overload -def fillcolor(color: _Color) -> None: ... -@overload -def fillcolor(r: float, g: float, b: float) -> None: ... -@overload -def color() -> Tuple[_AnyColor, _AnyColor]: ... -@overload -def color(color: _Color) -> None: ... -@overload -def color(r: float, g: float, b: float) -> None: ... -@overload -def color(color1: _Color, color2: _Color) -> None: ... -def showturtle() -> None: ... -def hideturtle() -> None: ... -def isvisible() -> bool: ... - -# Note: signatures 1 and 2 overlap unsafely when no arguments are provided -@overload -def pen() -> _PenState: ... # type: ignore -@overload -def pen( - pen: _PenState | None = ..., - *, - shown: bool = ..., - pendown: bool = ..., - pencolor: _Color = ..., - fillcolor: _Color = ..., - pensize: int = ..., - speed: int = ..., - resizemode: str = ..., - stretchfactor: Tuple[float, float] = ..., - outline: int = ..., - tilt: float = ..., -) -> None: ... - -width = pensize -up = penup -pu = penup -pd = pendown -down = pendown -st = showturtle -ht = hideturtle - -# Functions copied from RawTurtle: - -def setundobuffer(size: int | None) -> None: ... -def undobufferentries() -> int: ... -@overload -def shape(name: None = ...) -> str: ... -@overload -def shape(name: str) -> None: ... - -# Unsafely overlaps when no arguments are provided -@overload -def shapesize() -> Tuple[float, float, float]: ... # type: ignore -@overload -def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ... -def settiltangle(angle: float) -> None: ... -@overload -def tiltangle(angle: None = ...) -> float: ... -@overload -def tiltangle(angle: float) -> None: ... -def tilt(angle: float) -> None: ... - -# Can return either 'int' or Tuple[int, ...] based on if the stamp is -# a compound stamp or not. So, as per the "no Union return" policy, -# we return Any. -def stamp() -> Any: ... -def clearstamp(stampid: int | Tuple[int, ...]) -> None: ... -def clearstamps(n: int | None = ...) -> None: ... -def filling() -> bool: ... -def begin_fill() -> None: ... -def end_fill() -> None: ... -def dot(size: int | None = ..., *color: _Color) -> None: ... -def write(arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> None: ... -def begin_poly() -> None: ... -def end_poly() -> None: ... -def get_poly() -> _PolygonCoords | None: ... -def getscreen() -> TurtleScreen: ... -def getturtle() -> Turtle: ... - -getpen = getturtle - -def onrelease(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... -def ondrag(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... -def undo() -> None: ... - -turtlesize = shapesize - -# Functions copied from RawTurtle with a few tweaks: - -def clone() -> Turtle: ... - -# Extra functions present only in the global scope: - -done = mainloop diff --git a/stdlib/@python2/types.pyi b/stdlib/@python2/types.pyi deleted file mode 100644 index 72b9321a860f..000000000000 --- a/stdlib/@python2/types.pyi +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, Tuple, Type, TypeVar, overload - -_T = TypeVar("_T") - -# Note, all classes "defined" here require special handling. - -class NoneType: ... - -TypeType = type -ObjectType = object - -IntType = int -LongType = int # Really long, but can't reference that due to a mypy import cycle -FloatType = float -BooleanType = bool -ComplexType = complex -StringType = str -UnicodeType = unicode -StringTypes: Tuple[Type[StringType], Type[UnicodeType]] -BufferType = buffer -TupleType = tuple -ListType = list -DictType = dict -DictionaryType = dict - -class _Cell: - cell_contents: Any - -class FunctionType: - func_closure: Tuple[_Cell, ...] | None = ... - func_code: CodeType = ... - func_defaults: Tuple[Any, ...] | None = ... - func_dict: Dict[str, Any] = ... - func_doc: str | None = ... - func_globals: Dict[str, Any] = ... - func_name: str = ... - __closure__ = func_closure - __code__ = func_code - __defaults__ = func_defaults - __dict__ = func_dict - __globals__ = func_globals - __name__ = func_name - def __init__( - self, - code: CodeType, - globals: Dict[str, Any], - name: str | None = ..., - argdefs: Tuple[object, ...] | None = ..., - closure: Tuple[_Cell, ...] | None = ..., - ) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: object | None, type: type | None) -> UnboundMethodType: ... - -LambdaType = FunctionType - -class CodeType: - co_argcount: int - co_cellvars: Tuple[str, ...] - co_code: str - co_consts: Tuple[Any, ...] - co_filename: str - co_firstlineno: int - co_flags: int - co_freevars: Tuple[str, ...] - co_lnotab: str - co_name: str - co_names: Tuple[str, ...] - co_nlocals: int - co_stacksize: int - co_varnames: Tuple[str, ...] - def __init__( - self, - argcount: int, - nlocals: int, - stacksize: int, - flags: int, - codestring: str, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], - filename: str, - name: str, - firstlineno: int, - lnotab: str, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., - ) -> None: ... - -class GeneratorType: - gi_code: CodeType - gi_frame: FrameType - gi_running: int - def __iter__(self) -> GeneratorType: ... - def close(self) -> None: ... - def next(self) -> Any: ... - def send(self, __arg: Any) -> Any: ... - @overload - def throw(self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ...) -> Any: ... - @overload - def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Any: ... - -class ClassType: ... - -class UnboundMethodType: - im_class: type = ... - im_func: FunctionType = ... - im_self: object = ... - __name__: str - __func__ = im_func - __self__ = im_self - def __init__(self, func: Callable[..., Any], obj: object) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - -class InstanceType(object): ... - -MethodType = UnboundMethodType - -class BuiltinFunctionType: - __self__: object | None - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - -BuiltinMethodType = BuiltinFunctionType - -class ModuleType: - __doc__: str | None - __file__: str | None - __name__: str - __package__: str | None - __path__: Iterable[str] | None - __dict__: Dict[str, Any] - def __init__(self, name: str, doc: str | None = ...) -> None: ... - -FileType = file -XRangeType = xrange - -class TracebackType: - tb_frame: FrameType - tb_lasti: int - tb_lineno: int - tb_next: TracebackType - -class FrameType: - f_back: FrameType - f_builtins: Dict[str, Any] - f_code: CodeType - f_exc_type: None - f_exc_value: None - f_exc_traceback: None - f_globals: Dict[str, Any] - f_lasti: int - f_lineno: int - f_locals: Dict[str, Any] - f_restricted: bool - f_trace: Callable[[], None] - def clear(self) -> None: ... - -SliceType = slice - -class EllipsisType: ... - -class DictProxyType: - # TODO is it possible to have non-string keys? - # no __init__ - def copy(self) -> Dict[Any, Any]: ... - def get(self, key: str, default: _T = ...) -> Any | _T: ... - def has_key(self, key: str) -> bool: ... - def items(self) -> List[Tuple[str, Any]]: ... - def iteritems(self) -> Iterator[Tuple[str, Any]]: ... - def iterkeys(self) -> Iterator[str]: ... - def itervalues(self) -> Iterator[Any]: ... - def keys(self) -> List[str]: ... - def values(self) -> List[Any]: ... - def __contains__(self, key: str) -> bool: ... - def __getitem__(self, key: str) -> Any: ... - def __iter__(self) -> Iterator[str]: ... - def __len__(self) -> int: ... - -class NotImplementedType: ... - -class GetSetDescriptorType: - __name__: str - __objclass__: type - def __get__(self, obj: Any, type: type = ...) -> Any: ... - def __set__(self, obj: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... - -# Same type on Jython, different on CPython and PyPy, unknown on IronPython. -class MemberDescriptorType: - __name__: str - __objclass__: type - def __get__(self, obj: Any, type: type = ...) -> Any: ... - def __set__(self, obj: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... diff --git a/stdlib/@python2/typing.pyi b/stdlib/@python2/typing.pyi deleted file mode 100644 index a1b02e81990c..000000000000 --- a/stdlib/@python2/typing.pyi +++ /dev/null @@ -1,485 +0,0 @@ -import collections # Needed by aliases like DefaultDict, see mypy issue 2986 -from abc import ABCMeta, abstractmethod -from types import CodeType, FrameType, TracebackType - -# Definitions of special type checking related constructs. Their definitions -# are not used, so their value does not matter. - -Any = object() - -class TypeVar: - __name__: str - __bound__: Type[Any] | None - __constraints__: Tuple[Type[Any], ...] - __covariant__: bool - __contravariant__: bool - def __init__( - self, name: str, *constraints: Type[Any], bound: Type[Any] | None = ..., covariant: bool = ..., contravariant: bool = ... - ) -> None: ... - -_promote = object() - -class _SpecialForm(object): - def __getitem__(self, typeargs: Any) -> object: ... - -Union: _SpecialForm = ... -Optional: _SpecialForm = ... -Tuple: _SpecialForm = ... -Generic: _SpecialForm = ... -Protocol: _SpecialForm = ... -Callable: _SpecialForm = ... -Type: _SpecialForm = ... -ClassVar: _SpecialForm = ... -Final: _SpecialForm = ... -_F = TypeVar("_F", bound=Callable[..., Any]) - -def final(f: _F) -> _F: ... -def overload(f: _F) -> _F: ... - -Literal: _SpecialForm = ... -# TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... - -class GenericMeta(type): ... - -# Return type that indicates a function does not return. -# This type is equivalent to the None type, but the no-op Union is necessary to -# distinguish the None type from the None value. -NoReturn = Union[None] - -# These type variables are used by the container types. -_T = TypeVar("_T") -_S = TypeVar("_S") -_KT = TypeVar("_KT") # Key type. -_VT = TypeVar("_VT") # Value type. -_T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. -_V_co = TypeVar("_V_co", covariant=True) # Any type covariant containers. -_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. -_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. -_T_contra = TypeVar("_T_contra", contravariant=True) # Ditto contravariant. -_TC = TypeVar("_TC", bound=Type[object]) - -def no_type_check(f: _F) -> _F: ... -def no_type_check_decorator(decorator: _F) -> _F: ... - -# Type aliases and type constructors - -class _Alias: - # Class for defining generic aliases for library types. - def __getitem__(self, typeargs: Any) -> Any: ... - -List = _Alias() -Dict = _Alias() -DefaultDict = _Alias() -Set = _Alias() -FrozenSet = _Alias() -Counter = _Alias() -Deque = _Alias() - -# Predefined type variables. -AnyStr = TypeVar("AnyStr", str, unicode) - -# Abstract base classes. - -def runtime_checkable(cls: _TC) -> _TC: ... -@runtime_checkable -class SupportsInt(Protocol, metaclass=ABCMeta): - @abstractmethod - def __int__(self) -> int: ... - -@runtime_checkable -class SupportsFloat(Protocol, metaclass=ABCMeta): - @abstractmethod - def __float__(self) -> float: ... - -@runtime_checkable -class SupportsComplex(Protocol, metaclass=ABCMeta): - @abstractmethod - def __complex__(self) -> complex: ... - -@runtime_checkable -class SupportsAbs(Protocol[_T_co]): - @abstractmethod - def __abs__(self) -> _T_co: ... - -@runtime_checkable -class Reversible(Protocol[_T_co]): - @abstractmethod - def __reversed__(self) -> Iterator[_T_co]: ... - -@runtime_checkable -class Sized(Protocol, metaclass=ABCMeta): - @abstractmethod - def __len__(self) -> int: ... - -@runtime_checkable -class Hashable(Protocol, metaclass=ABCMeta): - # TODO: This is special, in that a subclass of a hashable class may not be hashable - # (for example, list vs. object). It's not obvious how to represent this. This class - # is currently mostly useless for static checking. - @abstractmethod - def __hash__(self) -> int: ... - -@runtime_checkable -class Iterable(Protocol[_T_co]): - @abstractmethod - def __iter__(self) -> Iterator[_T_co]: ... - -@runtime_checkable -class Iterator(Iterable[_T_co], Protocol[_T_co]): - @abstractmethod - def next(self) -> _T_co: ... - def __iter__(self) -> Iterator[_T_co]: ... - -class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): - @abstractmethod - def next(self) -> _T_co: ... - @abstractmethod - def send(self, __value: _T_contra) -> _T_co: ... - @overload - @abstractmethod - def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> _T_co: ... - @overload - @abstractmethod - def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... - @abstractmethod - def close(self) -> None: ... - @property - def gi_code(self) -> CodeType: ... - @property - def gi_frame(self) -> FrameType: ... - @property - def gi_running(self) -> bool: ... - -@runtime_checkable -class Container(Protocol[_T_co]): - @abstractmethod - def __contains__(self, x: object) -> bool: ... - -class Sequence(Iterable[_T_co], Container[_T_co], Reversible[_T_co], Generic[_T_co]): - @overload - @abstractmethod - def __getitem__(self, i: int) -> _T_co: ... - @overload - @abstractmethod - def __getitem__(self, s: slice) -> Sequence[_T_co]: ... - # Mixin methods - def index(self, x: Any) -> int: ... - def count(self, x: Any) -> int: ... - def __contains__(self, x: object) -> bool: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __reversed__(self) -> Iterator[_T_co]: ... - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - -class MutableSequence(Sequence[_T], Generic[_T]): - @abstractmethod - def insert(self, index: int, object: _T) -> None: ... - @overload - @abstractmethod - def __getitem__(self, i: int) -> _T: ... - @overload - @abstractmethod - def __getitem__(self, s: slice) -> MutableSequence[_T]: ... - @overload - @abstractmethod - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - @abstractmethod - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - @overload - @abstractmethod - def __delitem__(self, i: int) -> None: ... - @overload - @abstractmethod - def __delitem__(self, i: slice) -> None: ... - # Mixin methods - def append(self, object: _T) -> None: ... - def extend(self, iterable: Iterable[_T]) -> None: ... - def reverse(self) -> None: ... - def pop(self, index: int = ...) -> _T: ... - def remove(self, object: _T) -> None: ... - def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... - -class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): - @abstractmethod - def __contains__(self, x: object) -> bool: ... - # Mixin methods - def __le__(self, s: AbstractSet[Any]) -> bool: ... - def __lt__(self, s: AbstractSet[Any]) -> bool: ... - def __gt__(self, s: AbstractSet[Any]) -> bool: ... - def __ge__(self, s: AbstractSet[Any]) -> bool: ... - def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __or__(self, s: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... - def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... - # TODO: argument can be any container? - def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - -class MutableSet(AbstractSet[_T], Generic[_T]): - @abstractmethod - def add(self, x: _T) -> None: ... - @abstractmethod - def discard(self, x: _T) -> None: ... - # Mixin methods - def clear(self) -> None: ... - def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... - def __ior__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - -class MappingView(object): - def __len__(self) -> int: ... - -class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... - -class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_KT_co]: ... - -class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_VT_co]: ... - -@runtime_checkable -class ContextManager(Protocol[_T_co]): - def __enter__(self) -> _T_co: ... - def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> bool | None: ... - -class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): - # TODO: We wish the key type could also be covariant, but that doesn't work, - # see discussion in https: //github.com/python/typing/pull/273. - @abstractmethod - def __getitem__(self, k: _KT) -> _VT_co: ... - # Mixin methods - @overload - def get(self, k: _KT) -> _VT_co | None: ... - @overload - def get(self, k: _KT, default: _VT_co | _T) -> _VT_co | _T: ... - def keys(self) -> list[_KT]: ... - def values(self) -> list[_VT_co]: ... - def items(self) -> list[Tuple[_KT, _VT_co]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT_co]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT_co]]: ... - def __contains__(self, o: object) -> bool: ... - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - -class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): - @abstractmethod - def __setitem__(self, k: _KT, v: _VT) -> None: ... - @abstractmethod - def __delitem__(self, v: _KT) -> None: ... - def clear(self) -> None: ... - @overload - def pop(self, k: _KT) -> _VT: ... - @overload - def pop(self, k: _KT, default: _VT | _T = ...) -> _VT | _T: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... - @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - @overload - def update(self, **kwargs: _VT) -> None: ... - -Text = unicode - -TYPE_CHECKING = True - -class IO(Iterator[AnyStr], Generic[AnyStr]): - # TODO detach - # TODO use abstract properties - @property - def mode(self) -> str: ... - @property - def name(self) -> str: ... - @abstractmethod - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - @abstractmethod - def fileno(self) -> int: ... - @abstractmethod - def flush(self) -> None: ... - @abstractmethod - def isatty(self) -> bool: ... - # TODO what if n is None? - @abstractmethod - def read(self, n: int = ...) -> AnyStr: ... - @abstractmethod - def readable(self) -> bool: ... - @abstractmethod - def readline(self, limit: int = ...) -> AnyStr: ... - @abstractmethod - def readlines(self, hint: int = ...) -> list[AnyStr]: ... - @abstractmethod - def seek(self, offset: int, whence: int = ...) -> int: ... - @abstractmethod - def seekable(self) -> bool: ... - @abstractmethod - def tell(self) -> int: ... - @abstractmethod - def truncate(self, size: int | None = ...) -> int: ... - @abstractmethod - def writable(self) -> bool: ... - # TODO buffer objects - @abstractmethod - def write(self, s: AnyStr) -> int: ... - @abstractmethod - def writelines(self, lines: Iterable[AnyStr]) -> None: ... - @abstractmethod - def next(self) -> AnyStr: ... - @abstractmethod - def __iter__(self) -> Iterator[AnyStr]: ... - @abstractmethod - def __enter__(self) -> IO[AnyStr]: ... - @abstractmethod - def __exit__( - self, t: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... - -class BinaryIO(IO[str]): - # TODO readinto - # TODO read1? - # TODO peek? - @abstractmethod - def __enter__(self) -> BinaryIO: ... - -class TextIO(IO[unicode]): - # TODO use abstractproperty - @property - def buffer(self) -> BinaryIO: ... - @property - def encoding(self) -> str: ... - @property - def errors(self) -> str | None: ... - @property - def line_buffering(self) -> bool: ... - @property - def newlines(self) -> Any: ... # None, str or tuple - @abstractmethod - def __enter__(self) -> TextIO: ... - -class ByteString(Sequence[int], metaclass=ABCMeta): ... - -class Match(Generic[AnyStr]): - pos: int - endpos: int - lastindex: int | None - string: AnyStr - - # The regular expression object whose match() or search() method produced - # this match instance. This should not be Pattern[AnyStr] because the type - # of the pattern is independent of the type of the matched string in - # Python 2. Strictly speaking Match should be generic over AnyStr twice: - # once for the type of the pattern and once for the type of the matched - # string. - re: Pattern[Any] - # Can be None if there are no groups or if the last group was unnamed; - # otherwise matches the type of the pattern. - lastgroup: Any | None - def expand(self, template: str | Text) -> Any: ... - @overload - def group(self, group1: int = ...) -> AnyStr: ... - @overload - def group(self, group1: str) -> AnyStr: ... - @overload - def group(self, group1: int, group2: int, *groups: int) -> Tuple[AnyStr, ...]: ... - @overload - def group(self, group1: str, group2: str, *groups: str) -> Tuple[AnyStr, ...]: ... - def groups(self, default: AnyStr = ...) -> Tuple[AnyStr, ...]: ... - def groupdict(self, default: AnyStr = ...) -> Dict[str, AnyStr]: ... - def start(self, __group: int | str = ...) -> int: ... - def end(self, __group: int | str = ...) -> int: ... - def span(self, __group: int | str = ...) -> Tuple[int, int]: ... - @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented - -# We need a second TypeVar with the same definition as AnyStr, because -# Pattern is generic over AnyStr (determining the type of its .pattern -# attribute), but at the same time its methods take either bytes or -# Text and return the same type, regardless of the type of the pattern. -_AnyStr2 = TypeVar("_AnyStr2", bytes, Text) - -class Pattern(Generic[AnyStr]): - flags: int - groupindex: Dict[AnyStr, int] - groups: int - pattern: AnyStr - def search(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Match[_AnyStr2] | None: ... - def match(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Match[_AnyStr2] | None: ... - def split(self, string: _AnyStr2, maxsplit: int = ...) -> List[_AnyStr2]: ... - # Returns either a list of _AnyStr2 or a list of tuples, depending on - # whether there are groups in the pattern. - def findall(self, string: bytes | Text, pos: int = ..., endpos: int = ...) -> List[Any]: ... - def finditer(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Iterator[Match[_AnyStr2]]: ... - @overload - def sub(self, repl: _AnyStr2, string: _AnyStr2, count: int = ...) -> _AnyStr2: ... - @overload - def sub(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> _AnyStr2: ... - @overload - def subn(self, repl: _AnyStr2, string: _AnyStr2, count: int = ...) -> Tuple[_AnyStr2, int]: ... - @overload - def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> Tuple[_AnyStr2, int]: ... - -# Functions - -def get_type_hints( - obj: Callable[..., Any], globalns: Dict[Text, Any] | None = ..., localns: Dict[Text, Any] | None = ... -) -> None: ... -@overload -def cast(tp: Type[_T], obj: Any) -> _T: ... -@overload -def cast(tp: str, obj: Any) -> Any: ... -@overload -def cast(tp: object, obj: Any) -> Any: ... - -# Type constructors - -# NamedTuple is special-cased in the type checker -class NamedTuple(Tuple[Any, ...]): - _fields: Tuple[str, ...] - def __init__(self, typename: Text, fields: Iterable[Tuple[Text, Any]] = ..., **kwargs: Any) -> None: ... - @classmethod - def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... - def _asdict(self) -> Dict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... - -# Internal mypy fallback type for all typed dicts (does not exist at runtime) -class _TypedDict(Mapping[str, object], metaclass=ABCMeta): - def copy(self: _T) -> _T: ... - # Using NoReturn so that only calls using mypy plugin hook that specialize the signature - # can go through. - def setdefault(self, k: NoReturn, default: object) -> object: ... - # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. - def pop(self, k: NoReturn, default: _T = ...) -> object: ... - def update(self: _T, __m: _T) -> None: ... - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... - def __delitem__(self, k: NoReturn) -> None: ... - -def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... - -# This itself is only available during type checking -def type_check_only(func_or_cls: _F) -> _F: ... diff --git a/stdlib/@python2/typing_extensions.pyi b/stdlib/@python2/typing_extensions.pyi deleted file mode 100644 index d946cc278d32..000000000000 --- a/stdlib/@python2/typing_extensions.pyi +++ /dev/null @@ -1,105 +0,0 @@ -import abc -from typing import ( - TYPE_CHECKING as TYPE_CHECKING, - Any, - Callable, - ClassVar as ClassVar, - ContextManager as ContextManager, - Counter as Counter, - DefaultDict as DefaultDict, - Deque as Deque, - Dict, - ItemsView, - KeysView, - Mapping, - NewType as NewType, - NoReturn as NoReturn, - Text as Text, - Tuple, - Type as Type, - TypeVar, - ValuesView, - _Alias, - overload as overload, -) - -_T = TypeVar("_T") -_F = TypeVar("_F", bound=Callable[..., Any]) -_TC = TypeVar("_TC", bound=Type[object]) - -class _SpecialForm: - def __getitem__(self, typeargs: Any) -> Any: ... - -def runtime_checkable(cls: _TC) -> _TC: ... - -# This alias for above is kept here for backwards compatibility. -runtime = runtime_checkable -Protocol: _SpecialForm = ... -Final: _SpecialForm = ... - -def final(f: _F) -> _F: ... - -Literal: _SpecialForm = ... - -def IntVar(name: str) -> Any: ... # returns a new TypeVar - -# Internal mypy fallback type for all typed dicts (does not exist at runtime) -class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): - def copy(self: _T) -> _T: ... - # Using NoReturn so that only calls using mypy plugin hook that specialize the signature - # can go through. - def setdefault(self, k: NoReturn, default: object) -> object: ... - # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. - def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... - def __delitem__(self, k: NoReturn) -> None: ... - -# TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... - -OrderedDict = _Alias() - -def get_type_hints( - obj: Callable[..., Any], - globalns: Dict[str, Any] | None = ..., - localns: Dict[str, Any] | None = ..., - include_extras: bool = ..., -) -> Dict[str, Any]: ... - -Annotated: _SpecialForm = ... -_AnnotatedAlias: Any = ... # undocumented - -@runtime_checkable -class SupportsIndex(Protocol, metaclass=abc.ABCMeta): - @abc.abstractmethod - def __index__(self) -> int: ... - -# PEP 612 support for Python < 3.9 -class ParamSpecArgs: - __origin__: ParamSpec - def __init__(self, origin: ParamSpec) -> None: ... - -class ParamSpecKwargs: - __origin__: ParamSpec - def __init__(self, origin: ParamSpec) -> None: ... - -class ParamSpec: - __name__: str - __bound__: Type[Any] | None - __covariant__: bool - __contravariant__: bool - def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... - ) -> None: ... - @property - def args(self) -> ParamSpecArgs: ... - @property - def kwargs(self) -> ParamSpecKwargs: ... - -Concatenate: _SpecialForm = ... -TypeAlias: _SpecialForm = ... -TypeGuard: _SpecialForm = ... diff --git a/stdlib/@python2/unicodedata.pyi b/stdlib/@python2/unicodedata.pyi deleted file mode 100644 index f4ca655e5c7e..000000000000 --- a/stdlib/@python2/unicodedata.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Any, Text, TypeVar - -ucd_3_2_0: UCD -ucnhash_CAPI: Any -unidata_version: str - -_T = TypeVar("_T") - -def bidirectional(__chr: Text) -> Text: ... -def category(__chr: Text) -> Text: ... -def combining(__chr: Text) -> int: ... -def decimal(__chr: Text, __default: _T = ...) -> int | _T: ... -def decomposition(__chr: Text) -> Text: ... -def digit(__chr: Text, __default: _T = ...) -> int | _T: ... -def east_asian_width(__chr: Text) -> Text: ... -def lookup(__name: Text | bytes) -> Text: ... -def mirrored(__chr: Text) -> int: ... -def name(__chr: Text, __default: _T = ...) -> Text | _T: ... -def normalize(__form: Text, __unistr: Text) -> Text: ... -def numeric(__chr: Text, __default: _T = ...) -> float | _T: ... - -class UCD(object): - # The methods below are constructed from the same array in C - # (unicodedata_functions) and hence identical to the methods above. - unidata_version: str - def bidirectional(self, __chr: Text) -> str: ... - def category(self, __chr: Text) -> str: ... - def combining(self, __chr: Text) -> int: ... - def decimal(self, __chr: Text, __default: _T = ...) -> int | _T: ... - def decomposition(self, __chr: Text) -> str: ... - def digit(self, __chr: Text, __default: _T = ...) -> int | _T: ... - def east_asian_width(self, __chr: Text) -> str: ... - def lookup(self, __name: Text | bytes) -> Text: ... - def mirrored(self, __chr: Text) -> int: ... - def name(self, __chr: Text, __default: _T = ...) -> Text | _T: ... - def normalize(self, __form: Text, __unistr: Text) -> Text: ... - def numeric(self, __chr: Text, __default: _T = ...) -> float | _T: ... diff --git a/stdlib/@python2/unittest.pyi b/stdlib/@python2/unittest.pyi deleted file mode 100644 index 65a5a7878de6..000000000000 --- a/stdlib/@python2/unittest.pyi +++ /dev/null @@ -1,277 +0,0 @@ -import datetime -import types -from abc import ABCMeta, abstractmethod -from typing import ( - Any, - Callable, - Dict, - FrozenSet, - Iterable, - Iterator, - List, - Mapping, - NoReturn, - Pattern, - Sequence, - Set, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -_T = TypeVar("_T") -_FT = TypeVar("_FT") - -_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] -_Regexp = Union[Text, Pattern[Text]] - -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[None, None, None]] - -class Testable(metaclass=ABCMeta): - @abstractmethod - def run(self, result: TestResult) -> None: ... - @abstractmethod - def debug(self) -> None: ... - @abstractmethod - def countTestCases(self) -> int: ... - -# TODO ABC for test runners? - -class TestResult: - errors: List[Tuple[TestCase, str]] - failures: List[Tuple[TestCase, str]] - skipped: List[Tuple[TestCase, str]] - expectedFailures: List[Tuple[TestCase, str]] - unexpectedSuccesses: List[TestCase] - shouldStop: bool - testsRun: int - buffer: bool - failfast: bool - def wasSuccessful(self) -> bool: ... - def stop(self) -> None: ... - def startTest(self, test: TestCase) -> None: ... - def stopTest(self, test: TestCase) -> None: ... - def startTestRun(self) -> None: ... - def stopTestRun(self) -> None: ... - def addError(self, test: TestCase, err: _SysExcInfoType) -> None: ... - def addFailure(self, test: TestCase, err: _SysExcInfoType) -> None: ... - def addSuccess(self, test: TestCase) -> None: ... - def addSkip(self, test: TestCase, reason: str) -> None: ... - def addExpectedFailure(self, test: TestCase, err: str) -> None: ... - def addUnexpectedSuccess(self, test: TestCase) -> None: ... - -class _AssertRaisesBaseContext: - expected: Any - failureException: Type[BaseException] - obj_name: str - expected_regex: Pattern[str] - -class _AssertRaisesContext(_AssertRaisesBaseContext): - exception: Any - def __enter__(self) -> _AssertRaisesContext: ... - def __exit__(self, exc_type, exc_value, tb) -> bool: ... - -class TestCase(Testable): - failureException: Type[BaseException] - longMessage: bool - maxDiff: int | None - # undocumented - _testMethodName: str - def __init__(self, methodName: str = ...) -> None: ... - def setUp(self) -> None: ... - def tearDown(self) -> None: ... - @classmethod - def setUpClass(cls) -> None: ... - @classmethod - def tearDownClass(cls) -> None: ... - def run(self, result: TestResult = ...) -> None: ... - def debug(self) -> None: ... - def assert_(self, expr: Any, msg: object = ...) -> None: ... - def failUnless(self, expr: Any, msg: object = ...) -> None: ... - def assertTrue(self, expr: Any, msg: object = ...) -> None: ... - def assertEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... - def assertEquals(self, first: Any, second: Any, msg: object = ...) -> None: ... - def failUnlessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... - def assertNotEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... - def assertNotEquals(self, first: Any, second: Any, msg: object = ...) -> None: ... - def failIfEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... - @overload - def assertAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertAlmostEqual( - self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... - ) -> None: ... - @overload - def assertAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertAlmostEquals(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertAlmostEquals( - self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... - ) -> None: ... - def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: object = ...) -> None: ... - @overload - def assertNotAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertNotAlmostEqual( - self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... - ) -> None: ... - @overload - def assertNotAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertNotAlmostEquals(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertNotAlmostEquals( - self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... - ) -> None: ... - def failIfAlmostEqual( - self, first: float, second: float, places: int = ..., msg: object = ..., delta: float = ... - ) -> None: ... - def assertGreater(self, first: Any, second: Any, msg: object = ...) -> None: ... - def assertGreaterEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... - def assertMultiLineEqual(self, first: str, second: str, msg: object = ...) -> None: ... - def assertSequenceEqual( - self, first: Sequence[Any], second: Sequence[Any], msg: object = ..., seq_type: type = ... - ) -> None: ... - def assertListEqual(self, first: List[Any], second: List[Any], msg: object = ...) -> None: ... - def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], msg: object = ...) -> None: ... - def assertSetEqual(self, first: Set[Any] | FrozenSet[Any], second: Set[Any] | FrozenSet[Any], msg: object = ...) -> None: ... - def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], msg: object = ...) -> None: ... - def assertLess(self, first: Any, second: Any, msg: object = ...) -> None: ... - def assertLessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... - @overload - def assertRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - @overload - def assertRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... - @overload - def assertRaisesRegexp( - self, exception: _ExceptionType, regexp: _Regexp, callable: Callable[..., Any], *args: Any, **kwargs: Any - ) -> None: ... - @overload - def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp) -> _AssertRaisesContext: ... - def assertRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... - def assertNotRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... - def assertItemsEqual(self, first: Iterable[Any], second: Iterable[Any], msg: object = ...) -> None: ... - def assertDictContainsSubset(self, expected: Mapping[Any, Any], actual: Mapping[Any, Any], msg: object = ...) -> None: ... - def addTypeEqualityFunc(self, typeobj: type, function: Callable[..., None]) -> None: ... - @overload - def failUnlessRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - @overload - def failUnlessRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... - def failIf(self, expr: Any, msg: object = ...) -> None: ... - def assertFalse(self, expr: Any, msg: object = ...) -> None: ... - def assertIs(self, first: object, second: object, msg: object = ...) -> None: ... - def assertIsNot(self, first: object, second: object, msg: object = ...) -> None: ... - def assertIsNone(self, expr: Any, msg: object = ...) -> None: ... - def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... - def assertIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... - def assertNotIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... - def assertIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: object = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: object = ...) -> None: ... - def fail(self, msg: object = ...) -> NoReturn: ... - def countTestCases(self) -> int: ... - def defaultTestResult(self) -> TestResult: ... - def id(self) -> str: ... - def shortDescription(self) -> str: ... # May return None - def addCleanup(self, function: Any, *args: Any, **kwargs: Any) -> None: ... - def doCleanups(self) -> bool: ... - def skipTest(self, reason: Any) -> None: ... - def _formatMessage(self, msg: Text | None, standardMsg: Text) -> str: ... # undocumented - def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented - -class FunctionTestCase(TestCase): - def __init__( - self, - testFunc: Callable[[], None], - setUp: Callable[[], None] | None = ..., - tearDown: Callable[[], None] | None = ..., - description: str | None = ..., - ) -> None: ... - def debug(self) -> None: ... - def countTestCases(self) -> int: ... - -class TestSuite(Testable): - def __init__(self, tests: Iterable[Testable] = ...) -> None: ... - def addTest(self, test: Testable) -> None: ... - def addTests(self, tests: Iterable[Testable]) -> None: ... - def run(self, result: TestResult) -> None: ... - def debug(self) -> None: ... - def countTestCases(self) -> int: ... - def __iter__(self) -> Iterator[Testable]: ... - -class TestLoader: - testMethodPrefix: str - sortTestMethodsUsing: Callable[[str, str], int] | None - suiteClass: Callable[[List[TestCase]], TestSuite] - def loadTestsFromTestCase(self, testCaseClass: Type[TestCase]) -> TestSuite: ... - def loadTestsFromModule(self, module: types.ModuleType = ..., use_load_tests: bool = ...) -> TestSuite: ... - def loadTestsFromName(self, name: str = ..., module: types.ModuleType | None = ...) -> TestSuite: ... - def loadTestsFromNames(self, names: List[str] = ..., module: types.ModuleType | None = ...) -> TestSuite: ... - def discover(self, start_dir: str, pattern: str = ..., top_level_dir: str | None = ...) -> TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... - -defaultTestLoader: TestLoader - -class TextTestResult(TestResult): - def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... - def getDescription(self, test: TestCase) -> str: ... # undocumented - def printErrors(self) -> None: ... # undocumented - def printErrorList(self, flavour: str, errors: List[Tuple[TestCase, str]]) -> None: ... # undocumented - -class TextTestRunner: - def __init__( - self, - stream: TextIO | None = ..., - descriptions: bool = ..., - verbosity: int = ..., - failfast: bool = ..., - buffer: bool = ..., - resultclass: Type[TestResult] | None = ..., - ) -> None: ... - def _makeResult(self) -> TestResult: ... - def run(self, test: Testable) -> TestResult: ... # undocumented - -class SkipTest(Exception): ... - -# TODO precise types -def skipUnless(condition: Any, reason: str | unicode) -> Any: ... -def skipIf(condition: Any, reason: str | unicode) -> Any: ... -def expectedFailure(func: _FT) -> _FT: ... -def skip(reason: str | unicode) -> Any: ... - -# not really documented -class TestProgram: - result: TestResult - def runTests(self) -> None: ... # undocumented - -def main( - module: None | Text | types.ModuleType = ..., - defaultTest: str | None = ..., - argv: Sequence[str] | None = ..., - testRunner: Type[TextTestRunner] | TextTestRunner | None = ..., - testLoader: TestLoader = ..., - exit: bool = ..., - verbosity: int = ..., - failfast: bool | None = ..., - catchbreak: bool | None = ..., - buffer: bool | None = ..., -) -> TestProgram: ... -def load_tests(loader: TestLoader, tests: TestSuite, pattern: Text | None) -> TestSuite: ... -def installHandler() -> None: ... -def registerResult(result: TestResult) -> None: ... -def removeResult(result: TestResult) -> bool: ... -@overload -def removeHandler() -> None: ... -@overload -def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... - -# private but occasionally used -util: types.ModuleType diff --git a/stdlib/@python2/urllib.pyi b/stdlib/@python2/urllib.pyi deleted file mode 100644 index f6bb555b9581..000000000000 --- a/stdlib/@python2/urllib.pyi +++ /dev/null @@ -1,133 +0,0 @@ -from typing import IO, Any, AnyStr, List, Mapping, Sequence, Text, Tuple, TypeVar - -def url2pathname(pathname: AnyStr) -> AnyStr: ... -def pathname2url(pathname: AnyStr) -> AnyStr: ... -def urlopen(url: str, data=..., proxies: Mapping[str, str] = ..., context=...) -> IO[Any]: ... -def urlretrieve(url, filename=..., reporthook=..., data=..., context=...): ... -def urlcleanup() -> None: ... - -class ContentTooShortError(IOError): - content: Any - def __init__(self, message, content) -> None: ... - -class URLopener: - version: Any - proxies: Any - key_file: Any - cert_file: Any - context: Any - addheaders: Any - tempcache: Any - ftpcache: Any - def __init__(self, proxies: Mapping[str, str] = ..., context=..., **x509) -> None: ... - def __del__(self): ... - def close(self): ... - def cleanup(self): ... - def addheader(self, *args): ... - type: Any - def open(self, fullurl: str, data=...): ... - def open_unknown(self, fullurl, data=...): ... - def open_unknown_proxy(self, proxy, fullurl, data=...): ... - def retrieve(self, url, filename=..., reporthook=..., data=...): ... - def open_http(self, url, data=...): ... - def http_error(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_default(self, url, fp, errcode, errmsg, headers): ... - def open_https(self, url, data=...): ... - def open_file(self, url): ... - def open_local_file(self, url): ... - def open_ftp(self, url): ... - def open_data(self, url, data=...): ... - -class FancyURLopener(URLopener): - auth_cache: Any - tries: Any - maxtries: Any - def __init__(self, *args, **kwargs) -> None: ... - def http_error_default(self, url, fp, errcode, errmsg, headers): ... - def http_error_302(self, url, fp, errcode, errmsg, headers, data=...): ... - def redirect_internal(self, url, fp, errcode, errmsg, headers, data): ... - def http_error_301(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_303(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_307(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_401(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_407(self, url, fp, errcode, errmsg, headers, data=...): ... - def retry_proxy_http_basic_auth(self, url, realm, data=...): ... - def retry_proxy_https_basic_auth(self, url, realm, data=...): ... - def retry_http_basic_auth(self, url, realm, data=...): ... - def retry_https_basic_auth(self, url, realm, data=...): ... - def get_user_passwd(self, host, realm, clear_cache=...): ... - def prompt_user_passwd(self, host, realm): ... - -class ftpwrapper: - user: Any - passwd: Any - host: Any - port: Any - dirs: Any - timeout: Any - refcount: Any - keepalive: Any - def __init__(self, user, passwd, host, port, dirs, timeout=..., persistent=...) -> None: ... - busy: Any - ftp: Any - def init(self): ... - def retrfile(self, file, type): ... - def endtransfer(self): ... - def close(self): ... - def file_close(self): ... - def real_close(self): ... - -_AIUT = TypeVar("_AIUT", bound=addbase) - -class addbase: - fp: Any - def read(self, n: int = ...) -> bytes: ... - def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... - def fileno(self) -> int: ... # Optional[int], but that is rare - def __iter__(self: _AIUT) -> _AIUT: ... - def next(self) -> bytes: ... - def __init__(self, fp) -> None: ... - def close(self) -> None: ... - -class addclosehook(addbase): - closehook: Any - hookargs: Any - def __init__(self, fp, closehook, *hookargs) -> None: ... - def close(self): ... - -class addinfo(addbase): - headers: Any - def __init__(self, fp, headers) -> None: ... - def info(self): ... - -class addinfourl(addbase): - headers: Any - url: Any - code: Any - def __init__(self, fp, headers, url, code=...) -> None: ... - def info(self): ... - def getcode(self): ... - def geturl(self): ... - -def unwrap(url): ... -def splittype(url): ... -def splithost(url): ... -def splituser(host): ... -def splitpasswd(user): ... -def splitport(host): ... -def splitnport(host, defport=...): ... -def splitquery(url): ... -def splittag(url): ... -def splitattr(url): ... -def splitvalue(attr): ... -def unquote(s: AnyStr) -> AnyStr: ... -def unquote_plus(s: AnyStr) -> AnyStr: ... -def quote(s: AnyStr, safe: Text = ...) -> AnyStr: ... -def quote_plus(s: AnyStr, safe: Text = ...) -> AnyStr: ... -def urlencode(query: Sequence[Tuple[Any, Any]] | Mapping[Any, Any], doseq=...) -> str: ... -def getproxies() -> Mapping[str, str]: ... -def proxy_bypass(host: str) -> Any: ... # undocumented - -# Names in __all__ with no definition: -# basejoin diff --git a/stdlib/@python2/urllib2.pyi b/stdlib/@python2/urllib2.pyi deleted file mode 100644 index bf6157b8428b..000000000000 --- a/stdlib/@python2/urllib2.pyi +++ /dev/null @@ -1,185 +0,0 @@ -import ssl -from httplib import HTTPConnectionProtocol, HTTPResponse -from typing import Any, AnyStr, Callable, Dict, List, Mapping, Sequence, Text, Tuple, Type, Union -from urllib import addinfourl - -_string = Union[str, unicode] - -class URLError(IOError): - reason: str | BaseException - -class HTTPError(URLError, addinfourl): - code: int - headers: Mapping[str, str] - def __init__(self, url, code: int, msg: str, hdrs: Mapping[str, str], fp: addinfourl) -> None: ... - -class Request(object): - host: str - port: str - data: str - headers: Dict[str, str] - unverifiable: bool - type: str | None - origin_req_host = ... - unredirected_hdrs: Dict[str, str] - timeout: float | None # Undocumented, only set after __init__() by OpenerDirector.open() - def __init__( - self, - url: str, - data: str | None = ..., - headers: Dict[str, str] = ..., - origin_req_host: str | None = ..., - unverifiable: bool = ..., - ) -> None: ... - def __getattr__(self, attr): ... - def get_method(self) -> str: ... - def add_data(self, data) -> None: ... - def has_data(self) -> bool: ... - def get_data(self) -> str: ... - def get_full_url(self) -> str: ... - def get_type(self): ... - def get_host(self) -> str: ... - def get_selector(self): ... - def set_proxy(self, host, type) -> None: ... - def has_proxy(self) -> bool: ... - def get_origin_req_host(self) -> str: ... - def is_unverifiable(self) -> bool: ... - def add_header(self, key: str, val: str) -> None: ... - def add_unredirected_header(self, key: str, val: str) -> None: ... - def has_header(self, header_name: str) -> bool: ... - def get_header(self, header_name: str, default: str | None = ...) -> str: ... - def header_items(self): ... - -class OpenerDirector(object): - addheaders: List[Tuple[str, str]] - def add_handler(self, handler: BaseHandler) -> None: ... - def open(self, fullurl: Request | _string, data: _string | None = ..., timeout: float | None = ...) -> addinfourl | None: ... - def error(self, proto: _string, *args: Any): ... - -# Note that this type is somewhat a lie. The return *can* be None if -# a custom opener has been installed that fails to handle the request. -def urlopen( - url: Request | _string, - data: _string | None = ..., - timeout: float | None = ..., - cafile: _string | None = ..., - capath: _string | None = ..., - cadefault: bool = ..., - context: ssl.SSLContext | None = ..., -) -> addinfourl: ... -def install_opener(opener: OpenerDirector) -> None: ... -def build_opener(*handlers: BaseHandler | Type[BaseHandler]) -> OpenerDirector: ... - -class BaseHandler: - handler_order: int - parent: OpenerDirector - def add_parent(self, parent: OpenerDirector) -> None: ... - def close(self) -> None: ... - def __lt__(self, other: Any) -> bool: ... - -class HTTPErrorProcessor(BaseHandler): - def http_response(self, request, response): ... - -class HTTPDefaultErrorHandler(BaseHandler): - def http_error_default(self, req: Request, fp: addinfourl, code: int, msg: str, hdrs: Mapping[str, str]): ... - -class HTTPRedirectHandler(BaseHandler): - max_repeats: int - max_redirections: int - def redirect_request(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str], newurl): ... - def http_error_301(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - def http_error_302(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - def http_error_303(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - def http_error_307(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - inf_msg: str - -class ProxyHandler(BaseHandler): - proxies: Mapping[str, str] - def __init__(self, proxies: Mapping[str, str] | None = ...): ... - def proxy_open(self, req: Request, proxy, type): ... - -class HTTPPasswordMgr: - def __init__(self) -> None: ... - def add_password(self, realm: Text | None, uri: Text | Sequence[Text], user: Text, passwd: Text) -> None: ... - def find_user_password(self, realm: Text | None, authuri: Text) -> Tuple[Any, Any]: ... - def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... - def is_suburi(self, base: _string, test: _string) -> bool: ... - -class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): ... - -class AbstractBasicAuthHandler: - def __init__(self, password_mgr: HTTPPasswordMgr | None = ...) -> None: ... - def add_password(self, realm: Text | None, uri: Text | Sequence[Text], user: Text, passwd: Text) -> None: ... - def http_error_auth_reqed(self, authreq, host, req: Request, headers: Mapping[str, str]): ... - def retry_http_basic_auth(self, host, req: Request, realm): ... - -class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): - auth_header: str - def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): - auth_header: str - def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class AbstractDigestAuthHandler: - def __init__(self, passwd: HTTPPasswordMgr | None = ...) -> None: ... - def add_password(self, realm: Text | None, uri: Text | Sequence[Text], user: Text, passwd: Text) -> None: ... - def reset_retry_count(self) -> None: ... - def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, headers: Mapping[str, str]) -> None: ... - def retry_http_digest_auth(self, req: Request, auth: str) -> HTTPResponse | None: ... - def get_cnonce(self, nonce: str) -> str: ... - def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... - def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... - def get_entity_digest(self, data: bytes | None, chal: Mapping[str, str]) -> str | None: ... - -class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - auth_header: str - handler_order: int - def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - auth_header: str - handler_order: int - def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class AbstractHTTPHandler(BaseHandler): # undocumented - def __init__(self, debuglevel: int = ...) -> None: ... - def set_http_debuglevel(self, level: int) -> None: ... - def do_request_(self, request: Request) -> Request: ... - def do_open(self, http_class: HTTPConnectionProtocol, req: Request, **http_conn_args: Any | None) -> addinfourl: ... - -class HTTPHandler(AbstractHTTPHandler): - def http_open(self, req: Request) -> addinfourl: ... - def http_request(self, request: Request) -> Request: ... # undocumented - -class HTTPSHandler(AbstractHTTPHandler): - def __init__(self, debuglevel: int = ..., context: ssl.SSLContext | None = ...) -> None: ... - def https_open(self, req: Request) -> addinfourl: ... - def https_request(self, request: Request) -> Request: ... # undocumented - -class HTTPCookieProcessor(BaseHandler): - def __init__(self, cookiejar: Any | None = ...): ... - def http_request(self, request: Request): ... - def http_response(self, request: Request, response): ... - -class UnknownHandler(BaseHandler): - def unknown_open(self, req: Request): ... - -class FileHandler(BaseHandler): - def file_open(self, req: Request): ... - def get_names(self): ... - def open_local_file(self, req: Request): ... - -class FTPHandler(BaseHandler): - def ftp_open(self, req: Request): ... - def connect_ftp(self, user, passwd, host, port, dirs, timeout): ... - -class CacheFTPHandler(FTPHandler): - def __init__(self) -> None: ... - def setTimeout(self, t: float | None): ... - def setMaxConns(self, m: int): ... - def check_cache(self): ... - def clear_cache(self): ... - -def parse_http_list(s: AnyStr) -> List[AnyStr]: ... -def parse_keqv_list(l: List[AnyStr]) -> Dict[AnyStr, AnyStr]: ... diff --git a/stdlib/@python2/urlparse.pyi b/stdlib/@python2/urlparse.pyi deleted file mode 100644 index 6668c743373a..000000000000 --- a/stdlib/@python2/urlparse.pyi +++ /dev/null @@ -1,61 +0,0 @@ -from typing import AnyStr, Dict, List, NamedTuple, Sequence, Tuple, Union, overload - -_String = Union[str, unicode] - -uses_relative: List[str] -uses_netloc: List[str] -uses_params: List[str] -non_hierarchical: List[str] -uses_query: List[str] -uses_fragment: List[str] -scheme_chars: str -MAX_CACHE_SIZE: int - -def clear_cache() -> None: ... - -class ResultMixin(object): - @property - def username(self) -> str | None: ... - @property - def password(self) -> str | None: ... - @property - def hostname(self) -> str | None: ... - @property - def port(self) -> int | None: ... - -class _SplitResult(NamedTuple): - scheme: str - netloc: str - path: str - query: str - fragment: str - -class SplitResult(_SplitResult, ResultMixin): - def geturl(self) -> str: ... - -class _ParseResult(NamedTuple): - scheme: str - netloc: str - path: str - params: str - query: str - fragment: str - -class ParseResult(_ParseResult, ResultMixin): - def geturl(self) -> _String: ... - -def urlparse(url: _String, scheme: _String = ..., allow_fragments: bool = ...) -> ParseResult: ... -def urlsplit(url: _String, scheme: _String = ..., allow_fragments: bool = ...) -> SplitResult: ... -@overload -def urlunparse(data: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... -@overload -def urlunparse(data: Sequence[AnyStr]) -> AnyStr: ... -@overload -def urlunsplit(data: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... -@overload -def urlunsplit(data: Sequence[AnyStr]) -> AnyStr: ... -def urljoin(base: AnyStr, url: AnyStr, allow_fragments: bool = ...) -> AnyStr: ... -def urldefrag(url: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def unquote(s: AnyStr) -> AnyStr: ... -def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ... -def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ... diff --git a/stdlib/@python2/user.pyi b/stdlib/@python2/user.pyi deleted file mode 100644 index 9c33922b383d..000000000000 --- a/stdlib/@python2/user.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -def __getattr__(name) -> Any: ... - -home: str -pythonrc: str diff --git a/stdlib/@python2/uu.pyi b/stdlib/@python2/uu.pyi deleted file mode 100644 index e8717aecbe36..000000000000 --- a/stdlib/@python2/uu.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import BinaryIO, Text, Union - -_File = Union[Text, BinaryIO] - -class Error(Exception): ... - -def encode(in_file: _File, out_file: _File, name: str | None = ..., mode: int | None = ...) -> None: ... -def decode(in_file: _File, out_file: _File | None = ..., mode: int | None = ..., quiet: int = ...) -> None: ... diff --git a/stdlib/@python2/uuid.pyi b/stdlib/@python2/uuid.pyi deleted file mode 100644 index 2c8a9fb1c097..000000000000 --- a/stdlib/@python2/uuid.pyi +++ /dev/null @@ -1,81 +0,0 @@ -from typing import Any, Text, Tuple - -# Because UUID has properties called int and bytes we need to rename these temporarily. -_Int = int -_Bytes = bytes -_FieldsType = Tuple[int, int, int, int, int, int] - -class UUID: - def __init__( - self, - hex: Text | None = ..., - bytes: _Bytes | None = ..., - bytes_le: _Bytes | None = ..., - fields: _FieldsType | None = ..., - int: _Int | None = ..., - version: _Int | None = ..., - ) -> None: ... - @property - def bytes(self) -> _Bytes: ... - @property - def bytes_le(self) -> _Bytes: ... - @property - def clock_seq(self) -> _Int: ... - @property - def clock_seq_hi_variant(self) -> _Int: ... - @property - def clock_seq_low(self) -> _Int: ... - @property - def fields(self) -> _FieldsType: ... - @property - def hex(self) -> str: ... - @property - def int(self) -> _Int: ... - @property - def node(self) -> _Int: ... - @property - def time(self) -> _Int: ... - @property - def time_hi_version(self) -> _Int: ... - @property - def time_low(self) -> _Int: ... - @property - def time_mid(self) -> _Int: ... - @property - def urn(self) -> str: ... - @property - def variant(self) -> str: ... - @property - def version(self) -> _Int | None: ... - def __int__(self) -> _Int: ... - def get_bytes(self) -> _Bytes: ... - def get_bytes_le(self) -> _Bytes: ... - def get_clock_seq(self) -> _Int: ... - def get_clock_seq_hi_variant(self) -> _Int: ... - def get_clock_seq_low(self) -> _Int: ... - def get_fields(self) -> _FieldsType: ... - def get_hex(self) -> str: ... - def get_node(self) -> _Int: ... - def get_time(self) -> _Int: ... - def get_time_hi_version(self) -> _Int: ... - def get_time_low(self) -> _Int: ... - def get_time_mid(self) -> _Int: ... - def get_urn(self) -> str: ... - def get_variant(self) -> str: ... - def get_version(self) -> _Int | None: ... - def __cmp__(self, other: Any) -> _Int: ... - -def getnode() -> int: ... -def uuid1(node: _Int | None = ..., clock_seq: _Int | None = ...) -> UUID: ... -def uuid3(namespace: UUID, name: str) -> UUID: ... -def uuid4() -> UUID: ... -def uuid5(namespace: UUID, name: str) -> UUID: ... - -NAMESPACE_DNS: UUID -NAMESPACE_URL: UUID -NAMESPACE_OID: UUID -NAMESPACE_X500: UUID -RESERVED_NCS: str -RFC_4122: str -RESERVED_MICROSOFT: str -RESERVED_FUTURE: str diff --git a/stdlib/@python2/warnings.pyi b/stdlib/@python2/warnings.pyi deleted file mode 100644 index 0d187bf70c33..000000000000 --- a/stdlib/@python2/warnings.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from _warnings import warn as warn, warn_explicit as warn_explicit -from types import ModuleType, TracebackType -from typing import List, TextIO, Type, overload -from typing_extensions import Literal - -def showwarning( - message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... -) -> None: ... -def formatwarning(message: Warning | str, category: Type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... -def filterwarnings( - action: str, message: str = ..., category: Type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ... -) -> None: ... -def simplefilter(action: str, category: Type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... -def resetwarnings() -> None: ... - -class _OptionError(Exception): ... - -class WarningMessage: - message: Warning | str - category: Type[Warning] - filename: str - lineno: int - file: TextIO | None - line: str | None - def __init__( - self, - message: Warning | str, - category: Type[Warning], - filename: str, - lineno: int, - file: TextIO | None = ..., - line: str | None = ..., - ) -> None: ... - -class catch_warnings: - @overload - def __new__(cls, *, record: Literal[False] = ..., module: ModuleType | None = ...) -> _catch_warnings_without_records: ... - @overload - def __new__(cls, *, record: Literal[True], module: ModuleType | None = ...) -> _catch_warnings_with_records: ... - @overload - def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... - def __enter__(self) -> List[WarningMessage] | None: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - -class _catch_warnings_without_records(catch_warnings): - def __enter__(self) -> None: ... - -class _catch_warnings_with_records(catch_warnings): - def __enter__(self) -> List[WarningMessage]: ... diff --git a/stdlib/@python2/wave.pyi b/stdlib/@python2/wave.pyi deleted file mode 100644 index 0e9fe612cd24..000000000000 --- a/stdlib/@python2/wave.pyi +++ /dev/null @@ -1,56 +0,0 @@ -from typing import IO, Any, BinaryIO, NoReturn, Text, Tuple, Union - -_File = Union[Text, IO[bytes]] - -class Error(Exception): ... - -WAVE_FORMAT_PCM: int - -_wave_params = Tuple[int, int, int, int, str, str] - -class Wave_read: - def __init__(self, f: _File) -> None: ... - def getfp(self) -> BinaryIO | None: ... - def rewind(self) -> None: ... - def close(self) -> None: ... - def tell(self) -> int: ... - def getnchannels(self) -> int: ... - def getnframes(self) -> int: ... - def getsampwidth(self) -> int: ... - def getframerate(self) -> int: ... - def getcomptype(self) -> str: ... - def getcompname(self) -> str: ... - def getparams(self) -> _wave_params: ... - def getmarkers(self) -> None: ... - def getmark(self, id: Any) -> NoReturn: ... - def setpos(self, pos: int) -> None: ... - def readframes(self, nframes: int) -> bytes: ... - -class Wave_write: - def __init__(self, f: _File) -> None: ... - def setnchannels(self, nchannels: int) -> None: ... - def getnchannels(self) -> int: ... - def setsampwidth(self, sampwidth: int) -> None: ... - def getsampwidth(self) -> int: ... - def setframerate(self, framerate: float) -> None: ... - def getframerate(self) -> int: ... - def setnframes(self, nframes: int) -> None: ... - def getnframes(self) -> int: ... - def setcomptype(self, comptype: str, compname: str) -> None: ... - def getcomptype(self) -> str: ... - def getcompname(self) -> str: ... - def setparams(self, params: _wave_params) -> None: ... - def getparams(self) -> _wave_params: ... - def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... - def getmark(self, id: Any) -> NoReturn: ... - def getmarkers(self) -> None: ... - def tell(self) -> int: ... - # should be any bytes-like object after 3.4, but we don't have a type for that - def writeframesraw(self, data: bytes) -> None: ... - def writeframes(self, data: bytes) -> None: ... - def close(self) -> None: ... - -# Returns a Wave_read if mode is rb and Wave_write if mode is wb -def open(f: _File, mode: str | None = ...) -> Any: ... - -openfp = open diff --git a/stdlib/@python2/weakref.pyi b/stdlib/@python2/weakref.pyi deleted file mode 100644 index 6467f3a7517f..000000000000 --- a/stdlib/@python2/weakref.pyi +++ /dev/null @@ -1,72 +0,0 @@ -from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, List, Mapping, MutableMapping, Tuple, Type, TypeVar, overload - -from _weakref import ( - CallableProxyType as CallableProxyType, - ProxyType as ProxyType, - ReferenceType as ReferenceType, - getweakrefcount as getweakrefcount, - getweakrefs as getweakrefs, - proxy as proxy, - ref as ref, -) -from exceptions import ReferenceError as ReferenceError - -_S = TypeVar("_S") -_T = TypeVar("_T") -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - -ProxyTypes: Tuple[Type[Any], ...] - -class WeakValueDictionary(MutableMapping[_KT, _VT]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, __other: Mapping[_KT, _VT] | Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def has_key(self, key: object) -> bool: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... - def copy(self) -> WeakValueDictionary[_KT, _VT]: ... - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... - def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... - -class KeyedRef(ref[_T], Generic[_KT, _T]): - key: _KT - # This __new__ method uses a non-standard name for the "cls" parameter - def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... # type: ignore - def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... - -class WeakKeyDictionary(MutableMapping[_KT, _VT]): - @overload - def __init__(self, dict: None = ...) -> None: ... - @overload - def __init__(self, dict: Mapping[_KT, _VT] | Iterable[Tuple[_KT, _VT]]) -> None: ... - def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def has_key(self, key: object) -> bool: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... - def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... - def keyrefs(self) -> List[ref[_KT]]: ... diff --git a/stdlib/@python2/webbrowser.pyi b/stdlib/@python2/webbrowser.pyi deleted file mode 100644 index f634bc11ca7d..000000000000 --- a/stdlib/@python2/webbrowser.pyi +++ /dev/null @@ -1,96 +0,0 @@ -import sys -from typing import Callable, List, Sequence, Text - -class Error(Exception): ... - -def register( - name: Text, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = ..., update_tryorder: int = ... -) -> None: ... -def get(using: Text | None = ...) -> BaseBrowser: ... -def open(url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... -def open_new(url: Text) -> bool: ... -def open_new_tab(url: Text) -> bool: ... - -class BaseBrowser: - args: List[str] - name: str - basename: str - def __init__(self, name: Text = ...) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - def open_new(self, url: Text) -> bool: ... - def open_new_tab(self, url: Text) -> bool: ... - -class GenericBrowser(BaseBrowser): - args: List[str] - name: str - basename: str - def __init__(self, name: Text | Sequence[Text]) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - -class BackgroundBrowser(GenericBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - -class UnixBrowser(BaseBrowser): - raise_opts: List[str] | None - background: bool - redirect_stdout: bool - remote_args: List[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - -class Mozilla(UnixBrowser): - remote_args: List[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - -class Galeon(UnixBrowser): - raise_opts: List[str] - remote_args: List[str] - remote_action: str - remote_action_newwin: str - background: bool - -class Chrome(UnixBrowser): - remote_args: List[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - -class Opera(UnixBrowser): - remote_args: List[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - -class Elinks(UnixBrowser): - remote_args: List[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - redirect_stdout: bool - -class Konqueror(BaseBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - -class Grail(BaseBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - -if sys.platform == "win32": - class WindowsDefault(BaseBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - -if sys.platform == "darwin": - class MacOSX(BaseBrowser): - name: str - def __init__(self, name: Text) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - class MacOSXOSAScript(BaseBrowser): - def __init__(self, name: Text) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/stdlib/@python2/whichdb.pyi b/stdlib/@python2/whichdb.pyi deleted file mode 100644 index 1c678e9392e8..000000000000 --- a/stdlib/@python2/whichdb.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Text - -def whichdb(filename: Text) -> str | None: ... diff --git a/stdlib/@python2/winsound.pyi b/stdlib/@python2/winsound.pyi deleted file mode 100644 index 3d79f3b043f2..000000000000 --- a/stdlib/@python2/winsound.pyi +++ /dev/null @@ -1,27 +0,0 @@ -import sys -from typing import overload -from typing_extensions import Literal - -if sys.platform == "win32": - SND_FILENAME: int - SND_ALIAS: int - SND_LOOP: int - SND_MEMORY: int - SND_PURGE: int - SND_ASYNC: int - SND_NODEFAULT: int - SND_NOSTOP: int - SND_NOWAIT: int - - MB_ICONASTERISK: int - MB_ICONEXCLAMATION: int - MB_ICONHAND: int - MB_ICONQUESTION: int - MB_OK: int - def Beep(frequency: int, duration: int) -> None: ... - # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible - @overload - def PlaySound(sound: bytes | None, flags: Literal[4]) -> None: ... - @overload - def PlaySound(sound: str | bytes | None, flags: int) -> None: ... - def MessageBeep(type: int = ...) -> None: ... diff --git a/stdlib/@python2/wsgiref/handlers.pyi b/stdlib/@python2/wsgiref/handlers.pyi deleted file mode 100644 index d7e35ba8aff6..000000000000 --- a/stdlib/@python2/wsgiref/handlers.pyi +++ /dev/null @@ -1,89 +0,0 @@ -from abc import abstractmethod -from types import TracebackType -from typing import IO, Callable, List, MutableMapping, Optional, Text, Tuple, Type - -from .headers import Headers -from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment -from .util import FileWrapper - -_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] - -def format_date_time(timestamp: float | None) -> str: ... # undocumented - -class BaseHandler: - wsgi_version: Tuple[int, int] # undocumented - wsgi_multithread: bool - wsgi_multiprocess: bool - wsgi_run_once: bool - - origin_server: bool - http_version: str - server_software: str | None - - os_environ: MutableMapping[str, str] - - wsgi_file_wrapper: Type[FileWrapper] | None - headers_class: Type[Headers] # undocumented - - traceback_limit: int | None - error_status: str - error_headers: List[Tuple[Text, Text]] - error_body: bytes - def run(self, application: WSGIApplication) -> None: ... - def setup_environ(self) -> None: ... - def finish_response(self) -> None: ... - def get_scheme(self) -> str: ... - def set_content_length(self) -> None: ... - def cleanup_headers(self) -> None: ... - def start_response( - self, status: Text, headers: List[Tuple[Text, Text]], exc_info: _exc_info | None = ... - ) -> Callable[[bytes], None]: ... - def send_preamble(self) -> None: ... - def write(self, data: bytes) -> None: ... - def sendfile(self) -> bool: ... - def finish_content(self) -> None: ... - def close(self) -> None: ... - def send_headers(self) -> None: ... - def result_is_file(self) -> bool: ... - def client_is_modern(self) -> bool: ... - def log_exception(self, exc_info: _exc_info) -> None: ... - def handle_error(self) -> None: ... - def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... - @abstractmethod - def _write(self, data: bytes) -> None: ... - @abstractmethod - def _flush(self) -> None: ... - @abstractmethod - def get_stdin(self) -> InputStream: ... - @abstractmethod - def get_stderr(self) -> ErrorStream: ... - @abstractmethod - def add_cgi_vars(self) -> None: ... - -class SimpleHandler(BaseHandler): - stdin: InputStream - stdout: IO[bytes] - stderr: ErrorStream - base_env: MutableMapping[str, str] - def __init__( - self, - stdin: InputStream, - stdout: IO[bytes], - stderr: ErrorStream, - environ: MutableMapping[str, str], - multithread: bool = ..., - multiprocess: bool = ..., - ) -> None: ... - def get_stdin(self) -> InputStream: ... - def get_stderr(self) -> ErrorStream: ... - def add_cgi_vars(self) -> None: ... - def _write(self, data: bytes) -> None: ... - def _flush(self) -> None: ... - -class BaseCGIHandler(SimpleHandler): ... - -class CGIHandler(BaseCGIHandler): - def __init__(self) -> None: ... - -class IISCGIHandler(BaseCGIHandler): - def __init__(self) -> None: ... diff --git a/stdlib/@python2/wsgiref/headers.pyi b/stdlib/@python2/wsgiref/headers.pyi deleted file mode 100644 index 08061fee7664..000000000000 --- a/stdlib/@python2/wsgiref/headers.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from typing import List, Pattern, Tuple, overload - -_HeaderList = List[Tuple[str, str]] - -tspecials: Pattern[str] # undocumented - -class Headers: - def __init__(self, headers: _HeaderList) -> None: ... - def __len__(self) -> int: ... - def __setitem__(self, name: str, val: str) -> None: ... - def __delitem__(self, name: str) -> None: ... - def __getitem__(self, name: str) -> str | None: ... - def has_key(self, name: str) -> bool: ... - def __contains__(self, name: str) -> bool: ... - def get_all(self, name: str) -> List[str]: ... - @overload - def get(self, name: str, default: str) -> str: ... - @overload - def get(self, name: str, default: str | None = ...) -> str | None: ... - def keys(self) -> List[str]: ... - def values(self) -> List[str]: ... - def items(self) -> _HeaderList: ... - def setdefault(self, name: str, value: str) -> str: ... - def add_header(self, _name: str, _value: str | None, **_params: str | None) -> None: ... diff --git a/stdlib/@python2/wsgiref/simple_server.pyi b/stdlib/@python2/wsgiref/simple_server.pyi deleted file mode 100644 index a74a26fed935..000000000000 --- a/stdlib/@python2/wsgiref/simple_server.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer -from typing import List, Type, TypeVar, overload - -from .handlers import SimpleHandler -from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment - -server_version: str # undocumented -sys_version: str # undocumented -software_version: str # undocumented - -class ServerHandler(SimpleHandler): # undocumented - server_software: str - def close(self) -> None: ... - -class WSGIServer(HTTPServer): - application: WSGIApplication | None - base_environ: WSGIEnvironment # only available after call to setup_environ() - def setup_environ(self) -> None: ... - def get_app(self) -> WSGIApplication | None: ... - def set_app(self, application: WSGIApplication | None) -> None: ... - -class WSGIRequestHandler(BaseHTTPRequestHandler): - server_version: str - def get_environ(self) -> WSGIEnvironment: ... - def get_stderr(self) -> ErrorStream: ... - def handle(self) -> None: ... - -def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... - -_S = TypeVar("_S", bound=WSGIServer) - -@overload -def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... -@overload -def make_server( - host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ... -) -> _S: ... diff --git a/stdlib/@python2/wsgiref/types.pyi b/stdlib/@python2/wsgiref/types.pyi deleted file mode 100644 index c272ae67c391..000000000000 --- a/stdlib/@python2/wsgiref/types.pyi +++ /dev/null @@ -1,3 +0,0 @@ -# Obsolete, use _typeshed.wsgi directly. - -from _typeshed.wsgi import * diff --git a/stdlib/@python2/wsgiref/util.pyi b/stdlib/@python2/wsgiref/util.pyi deleted file mode 100644 index c8e045a8cb8e..000000000000 --- a/stdlib/@python2/wsgiref/util.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import IO, Any, Callable - -from .types import WSGIEnvironment - -class FileWrapper: - filelike: IO[bytes] - blksize: int - close: Callable[[], None] # only exists if filelike.close exists - def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... - def __getitem__(self, key: Any) -> bytes: ... - def __iter__(self) -> FileWrapper: ... - def next(self) -> bytes: ... - -def guess_scheme(environ: WSGIEnvironment) -> str: ... -def application_uri(environ: WSGIEnvironment) -> str: ... -def request_uri(environ: WSGIEnvironment, include_query: bool = ...) -> str: ... -def shift_path_info(environ: WSGIEnvironment) -> str | None: ... -def setup_testing_defaults(environ: WSGIEnvironment) -> None: ... -def is_hop_by_hop(header_name: str) -> bool: ... diff --git a/stdlib/@python2/wsgiref/validate.pyi b/stdlib/@python2/wsgiref/validate.pyi deleted file mode 100644 index b3e629b02d71..000000000000 --- a/stdlib/@python2/wsgiref/validate.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication -from typing import Any, Callable, Iterable, Iterator, NoReturn - -class WSGIWarning(Warning): ... - -def validator(application: WSGIApplication) -> WSGIApplication: ... - -class InputWrapper: - input: InputStream - def __init__(self, wsgi_input: InputStream) -> None: ... - def read(self, size: int = ...) -> bytes: ... - def readline(self) -> bytes: ... - def readlines(self, hint: int = ...) -> bytes: ... - def __iter__(self) -> Iterable[bytes]: ... - def close(self) -> NoReturn: ... - -class ErrorWrapper: - errors: ErrorStream - def __init__(self, wsgi_errors: ErrorStream) -> None: ... - def write(self, s: str) -> None: ... - def flush(self) -> None: ... - def writelines(self, seq: Iterable[str]) -> None: ... - def close(self) -> NoReturn: ... - -class WriteWrapper: - writer: Callable[[bytes], Any] - def __init__(self, wsgi_writer: Callable[[bytes], Any]) -> None: ... - def __call__(self, s: bytes) -> None: ... - -class PartialIteratorWrapper: - iterator: Iterator[bytes] - def __init__(self, wsgi_iterator: Iterator[bytes]) -> None: ... - def __iter__(self) -> IteratorWrapper: ... - -class IteratorWrapper: - original_iterator: Iterator[bytes] - iterator: Iterator[bytes] - closed: bool - check_start_response: bool | None - def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: bool | None) -> None: ... - def __iter__(self) -> IteratorWrapper: ... - def next(self) -> bytes: ... - def close(self) -> None: ... - def __del__(self) -> None: ... diff --git a/stdlib/@python2/xdrlib.pyi b/stdlib/@python2/xdrlib.pyi deleted file mode 100644 index 378504c37227..000000000000 --- a/stdlib/@python2/xdrlib.pyi +++ /dev/null @@ -1,55 +0,0 @@ -from typing import Callable, List, Sequence, TypeVar - -_T = TypeVar("_T") - -class Error(Exception): - msg: str - def __init__(self, msg: str) -> None: ... - -class ConversionError(Error): ... - -class Packer: - def __init__(self) -> None: ... - def reset(self) -> None: ... - def get_buffer(self) -> bytes: ... - def get_buf(self) -> bytes: ... - def pack_uint(self, x: int) -> None: ... - def pack_int(self, x: int) -> None: ... - def pack_enum(self, x: int) -> None: ... - def pack_bool(self, x: bool) -> None: ... - def pack_uhyper(self, x: int) -> None: ... - def pack_hyper(self, x: int) -> None: ... - def pack_float(self, x: float) -> None: ... - def pack_double(self, x: float) -> None: ... - def pack_fstring(self, n: int, s: bytes) -> None: ... - def pack_fopaque(self, n: int, s: bytes) -> None: ... - def pack_string(self, s: bytes) -> None: ... - def pack_opaque(self, s: bytes) -> None: ... - def pack_bytes(self, s: bytes) -> None: ... - def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... - def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... - def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... - -class Unpacker: - def __init__(self, data: bytes) -> None: ... - def reset(self, data: bytes) -> None: ... - def get_position(self) -> int: ... - def set_position(self, position: int) -> None: ... - def get_buffer(self) -> bytes: ... - def done(self) -> None: ... - def unpack_uint(self) -> int: ... - def unpack_int(self) -> int: ... - def unpack_enum(self) -> int: ... - def unpack_bool(self) -> bool: ... - def unpack_uhyper(self) -> int: ... - def unpack_hyper(self) -> int: ... - def unpack_float(self) -> float: ... - def unpack_double(self) -> float: ... - def unpack_fstring(self, n: int) -> bytes: ... - def unpack_fopaque(self, n: int) -> bytes: ... - def unpack_string(self) -> bytes: ... - def unpack_opaque(self) -> bytes: ... - def unpack_bytes(self) -> bytes: ... - def unpack_list(self, unpack_item: Callable[[], _T]) -> List[_T]: ... - def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> List[_T]: ... - def unpack_array(self, unpack_item: Callable[[], _T]) -> List[_T]: ... diff --git a/stdlib/@python2/xml/__init__.pyi b/stdlib/@python2/xml/__init__.pyi deleted file mode 100644 index c524ac2b1cfc..000000000000 --- a/stdlib/@python2/xml/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -import xml.parsers as parsers diff --git a/stdlib/@python2/xml/dom/NodeFilter.pyi b/stdlib/@python2/xml/dom/NodeFilter.pyi deleted file mode 100644 index 80fb73d23433..000000000000 --- a/stdlib/@python2/xml/dom/NodeFilter.pyi +++ /dev/null @@ -1,19 +0,0 @@ -class NodeFilter: - FILTER_ACCEPT: int - FILTER_REJECT: int - FILTER_SKIP: int - - SHOW_ALL: int - SHOW_ELEMENT: int - SHOW_ATTRIBUTE: int - SHOW_TEXT: int - SHOW_CDATA_SECTION: int - SHOW_ENTITY_REFERENCE: int - SHOW_ENTITY: int - SHOW_PROCESSING_INSTRUCTION: int - SHOW_COMMENT: int - SHOW_DOCUMENT: int - SHOW_DOCUMENT_TYPE: int - SHOW_DOCUMENT_FRAGMENT: int - SHOW_NOTATION: int - def acceptNode(self, node) -> int: ... diff --git a/stdlib/@python2/xml/dom/__init__.pyi b/stdlib/@python2/xml/dom/__init__.pyi deleted file mode 100644 index c5766c326c3e..000000000000 --- a/stdlib/@python2/xml/dom/__init__.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Any - -from .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation - -class Node: - ELEMENT_NODE: int - ATTRIBUTE_NODE: int - TEXT_NODE: int - CDATA_SECTION_NODE: int - ENTITY_REFERENCE_NODE: int - ENTITY_NODE: int - PROCESSING_INSTRUCTION_NODE: int - COMMENT_NODE: int - DOCUMENT_NODE: int - DOCUMENT_TYPE_NODE: int - DOCUMENT_FRAGMENT_NODE: int - NOTATION_NODE: int - -# ExceptionCode -INDEX_SIZE_ERR: int -DOMSTRING_SIZE_ERR: int -HIERARCHY_REQUEST_ERR: int -WRONG_DOCUMENT_ERR: int -INVALID_CHARACTER_ERR: int -NO_DATA_ALLOWED_ERR: int -NO_MODIFICATION_ALLOWED_ERR: int -NOT_FOUND_ERR: int -NOT_SUPPORTED_ERR: int -INUSE_ATTRIBUTE_ERR: int -INVALID_STATE_ERR: int -SYNTAX_ERR: int -INVALID_MODIFICATION_ERR: int -NAMESPACE_ERR: int -INVALID_ACCESS_ERR: int -VALIDATION_ERR: int - -class DOMException(Exception): - code: int - def __init__(self, *args: Any, **kw: Any) -> None: ... - def _get_code(self) -> int: ... - -class IndexSizeErr(DOMException): ... -class DomstringSizeErr(DOMException): ... -class HierarchyRequestErr(DOMException): ... -class WrongDocumentErr(DOMException): ... -class NoDataAllowedErr(DOMException): ... -class NoModificationAllowedErr(DOMException): ... -class NotFoundErr(DOMException): ... -class NotSupportedErr(DOMException): ... -class InuseAttributeErr(DOMException): ... -class InvalidStateErr(DOMException): ... -class SyntaxErr(DOMException): ... -class InvalidModificationErr(DOMException): ... -class NamespaceErr(DOMException): ... -class InvalidAccessErr(DOMException): ... -class ValidationErr(DOMException): ... - -class UserDataHandler: - NODE_CLONED: int - NODE_IMPORTED: int - NODE_DELETED: int - NODE_RENAMED: int - -XML_NAMESPACE: str -XMLNS_NAMESPACE: str -XHTML_NAMESPACE: str -EMPTY_NAMESPACE: None -EMPTY_PREFIX: None diff --git a/stdlib/@python2/xml/dom/domreg.pyi b/stdlib/@python2/xml/dom/domreg.pyi deleted file mode 100644 index 2496b3884ea1..000000000000 --- a/stdlib/@python2/xml/dom/domreg.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from _typeshed.xml import DOMImplementation -from typing import Callable, Dict, Iterable, Tuple - -well_known_implementations: Dict[str, str] -registered: Dict[str, Callable[[], DOMImplementation]] - -def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ... -def getDOMImplementation(name: str | None = ..., features: str | Iterable[Tuple[str, str | None]] = ...) -> DOMImplementation: ... diff --git a/stdlib/@python2/xml/dom/expatbuilder.pyi b/stdlib/@python2/xml/dom/expatbuilder.pyi deleted file mode 100644 index 964e6fa3f426..000000000000 --- a/stdlib/@python2/xml/dom/expatbuilder.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete diff --git a/stdlib/@python2/xml/dom/minicompat.pyi b/stdlib/@python2/xml/dom/minicompat.pyi deleted file mode 100644 index e9b0395ab50d..000000000000 --- a/stdlib/@python2/xml/dom/minicompat.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any, Iterable, List, Tuple, Type, TypeVar - -_T = TypeVar("_T") - -StringTypes: Tuple[Type[str]] - -class NodeList(List[_T]): - length: int - def item(self, index: int) -> _T | None: ... - -class EmptyNodeList(Tuple[Any, ...]): - length: int - def item(self, index: int) -> None: ... - def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore - def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... - -def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... diff --git a/stdlib/@python2/xml/dom/minidom.pyi b/stdlib/@python2/xml/dom/minidom.pyi deleted file mode 100644 index ed46ac4561ec..000000000000 --- a/stdlib/@python2/xml/dom/minidom.pyi +++ /dev/null @@ -1,292 +0,0 @@ -import xml.dom -from typing import IO, Any, Text as _Text, TypeVar -from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS -from xml.sax.xmlreader import XMLReader - -_T = TypeVar("_T") - -def parse(file: str | IO[Any], parser: XMLReader | None = ..., bufsize: int | None = ...): ... -def parseString(string: bytes | _Text, parser: XMLReader | None = ...): ... -def getDOMImplementation(features=...): ... - -class Node(xml.dom.Node): - namespaceURI: str | None - parentNode: Any - ownerDocument: Any - nextSibling: Any - previousSibling: Any - prefix: Any - def toxml(self, encoding: Any | None = ...): ... - def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Any | None = ...): ... - def hasChildNodes(self) -> bool: ... - def insertBefore(self, newChild, refChild): ... - def appendChild(self, node): ... - def replaceChild(self, newChild, oldChild): ... - def removeChild(self, oldChild): ... - def normalize(self) -> None: ... - def cloneNode(self, deep): ... - def isSupported(self, feature, version): ... - def isSameNode(self, other): ... - def getInterface(self, feature): ... - def getUserData(self, key): ... - def setUserData(self, key, data, handler): ... - childNodes: Any - def unlink(self) -> None: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, et, ev, tb) -> None: ... - -class DocumentFragment(Node): - nodeType: Any - nodeName: str - nodeValue: Any - attributes: Any - parentNode: Any - childNodes: Any - def __init__(self) -> None: ... - -class Attr(Node): - name: str - nodeType: Any - attributes: Any - specified: bool - ownerElement: Any - namespaceURI: str | None - childNodes: Any - nodeName: Any - nodeValue: str - value: str - prefix: Any - def __init__( - self, qName: str, namespaceURI: str | None = ..., localName: Any | None = ..., prefix: Any | None = ... - ) -> None: ... - def unlink(self) -> None: ... - -class NamedNodeMap: - def __init__(self, attrs, attrsNS, ownerElement) -> None: ... - def item(self, index): ... - def items(self): ... - def itemsNS(self): ... - def __contains__(self, key): ... - def keys(self): ... - def keysNS(self): ... - def values(self): ... - def get(self, name, value: Any | None = ...): ... - def __len__(self) -> int: ... - def __eq__(self, other: Any) -> bool: ... - def __ge__(self, other: Any) -> bool: ... - def __gt__(self, other: Any) -> bool: ... - def __le__(self, other: Any) -> bool: ... - def __lt__(self, other: Any) -> bool: ... - def __getitem__(self, attname_or_tuple): ... - def __setitem__(self, attname, value) -> None: ... - def getNamedItem(self, name): ... - def getNamedItemNS(self, namespaceURI: str, localName): ... - def removeNamedItem(self, name): ... - def removeNamedItemNS(self, namespaceURI: str, localName): ... - def setNamedItem(self, node): ... - def setNamedItemNS(self, node): ... - def __delitem__(self, attname_or_tuple) -> None: ... - -AttributeList = NamedNodeMap - -class TypeInfo: - namespace: Any - name: Any - def __init__(self, namespace, name) -> None: ... - -class Element(Node): - nodeType: Any - nodeValue: Any - schemaType: Any - parentNode: Any - tagName: str - prefix: Any - namespaceURI: str | None - childNodes: Any - nextSibling: Any - def __init__( - self, tagName, namespaceURI: str | None = ..., prefix: Any | None = ..., localName: Any | None = ... - ) -> None: ... - def unlink(self) -> None: ... - def getAttribute(self, attname): ... - def getAttributeNS(self, namespaceURI: str, localName): ... - def setAttribute(self, attname, value) -> None: ... - def setAttributeNS(self, namespaceURI: str, qualifiedName: str, value) -> None: ... - def getAttributeNode(self, attrname): ... - def getAttributeNodeNS(self, namespaceURI: str, localName): ... - def setAttributeNode(self, attr): ... - setAttributeNodeNS: Any - def removeAttribute(self, name) -> None: ... - def removeAttributeNS(self, namespaceURI: str, localName) -> None: ... - def removeAttributeNode(self, node): ... - removeAttributeNodeNS: Any - def hasAttribute(self, name: str) -> bool: ... - def hasAttributeNS(self, namespaceURI: str, localName) -> bool: ... - def getElementsByTagName(self, name): ... - def getElementsByTagNameNS(self, namespaceURI: str, localName): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - def hasAttributes(self) -> bool: ... - def setIdAttribute(self, name) -> None: ... - def setIdAttributeNS(self, namespaceURI: str, localName) -> None: ... - def setIdAttributeNode(self, idAttr) -> None: ... - -class Childless: - attributes: Any - childNodes: Any - firstChild: Any - lastChild: Any - def appendChild(self, node) -> None: ... - def hasChildNodes(self) -> bool: ... - def insertBefore(self, newChild, refChild) -> None: ... - def removeChild(self, oldChild) -> None: ... - def normalize(self) -> None: ... - def replaceChild(self, newChild, oldChild) -> None: ... - -class ProcessingInstruction(Childless, Node): - nodeType: Any - target: Any - data: Any - def __init__(self, target, data) -> None: ... - nodeValue: Any - nodeName: Any - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - -class CharacterData(Childless, Node): - ownerDocument: Any - previousSibling: Any - def __init__(self) -> None: ... - def __len__(self) -> int: ... - data: str - nodeValue: Any - def substringData(self, offset: int, count: int) -> str: ... - def appendData(self, arg: str) -> None: ... - def insertData(self, offset: int, arg: str) -> None: ... - def deleteData(self, offset: int, count: int) -> None: ... - def replaceData(self, offset: int, count: int, arg: str) -> None: ... - -class Text(CharacterData): - nodeType: Any - nodeName: str - attributes: Any - data: Any - def splitText(self, offset): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - def replaceWholeText(self, content): ... - -class Comment(CharacterData): - nodeType: Any - nodeName: str - def __init__(self, data) -> None: ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - -class CDATASection(Text): - nodeType: Any - nodeName: str - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - -class ReadOnlySequentialNamedNodeMap: - def __init__(self, seq=...) -> None: ... - def __len__(self): ... - def getNamedItem(self, name): ... - def getNamedItemNS(self, namespaceURI: str, localName): ... - def __getitem__(self, name_or_tuple): ... - def item(self, index): ... - def removeNamedItem(self, name) -> None: ... - def removeNamedItemNS(self, namespaceURI: str, localName) -> None: ... - def setNamedItem(self, node) -> None: ... - def setNamedItemNS(self, node) -> None: ... - -class Identified: ... - -class DocumentType(Identified, Childless, Node): - nodeType: Any - nodeValue: Any - name: Any - publicId: Any - systemId: Any - internalSubset: Any - entities: Any - notations: Any - nodeName: Any - def __init__(self, qualifiedName: str) -> None: ... - def cloneNode(self, deep): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - -class Entity(Identified, Node): - attributes: Any - nodeType: Any - nodeValue: Any - actualEncoding: Any - encoding: Any - version: Any - nodeName: Any - notationName: Any - childNodes: Any - def __init__(self, name, publicId, systemId, notation) -> None: ... - def appendChild(self, newChild) -> None: ... - def insertBefore(self, newChild, refChild) -> None: ... - def removeChild(self, oldChild) -> None: ... - def replaceChild(self, newChild, oldChild) -> None: ... - -class Notation(Identified, Childless, Node): - nodeType: Any - nodeValue: Any - nodeName: Any - def __init__(self, name, publicId, systemId) -> None: ... - -class DOMImplementation(DOMImplementationLS): - def hasFeature(self, feature, version) -> bool: ... - def createDocument(self, namespaceURI: str, qualifiedName: str, doctype): ... - def createDocumentType(self, qualifiedName: str, publicId, systemId): ... - def getInterface(self, feature): ... - -class ElementInfo: - tagName: Any - def __init__(self, name) -> None: ... - def getAttributeType(self, aname): ... - def getAttributeTypeNS(self, namespaceURI: str, localName): ... - def isElementContent(self): ... - def isEmpty(self): ... - def isId(self, aname): ... - def isIdNS(self, namespaceURI: str, localName): ... - -class Document(Node, DocumentLS): - implementation: Any - nodeType: Any - nodeName: str - nodeValue: Any - attributes: Any - parentNode: Any - previousSibling: Any - nextSibling: Any - actualEncoding: Any - encoding: Any - standalone: Any - version: Any - strictErrorChecking: bool - errorHandler: Any - documentURI: Any - doctype: Any - childNodes: Any - def __init__(self) -> None: ... - def appendChild(self, node): ... - documentElement: Any - def removeChild(self, oldChild): ... - def unlink(self) -> None: ... - def cloneNode(self, deep): ... - def createDocumentFragment(self): ... - def createElement(self, tagName: str): ... - def createTextNode(self, data): ... - def createCDATASection(self, data): ... - def createComment(self, data): ... - def createProcessingInstruction(self, target, data): ... - def createAttribute(self, qName) -> Attr: ... - def createElementNS(self, namespaceURI: str, qualifiedName: str): ... - def createAttributeNS(self, namespaceURI: str, qualifiedName: str) -> Attr: ... - def getElementById(self, id): ... - def getElementsByTagName(self, name: str): ... - def getElementsByTagNameNS(self, namespaceURI: str, localName): ... - def isSupported(self, feature, version): ... - def importNode(self, node, deep): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ..., encoding: Any | None = ...) -> None: ... - def renameNode(self, n, namespaceURI: str, name): ... diff --git a/stdlib/@python2/xml/dom/pulldom.pyi b/stdlib/@python2/xml/dom/pulldom.pyi deleted file mode 100644 index 964e6fa3f426..000000000000 --- a/stdlib/@python2/xml/dom/pulldom.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete diff --git a/stdlib/@python2/xml/dom/xmlbuilder.pyi b/stdlib/@python2/xml/dom/xmlbuilder.pyi deleted file mode 100644 index d8936bdc2ab4..000000000000 --- a/stdlib/@python2/xml/dom/xmlbuilder.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete - -class DocumentLS(Any): ... # type: ignore -class DOMImplementationLS(Any): ... # type: ignore diff --git a/stdlib/@python2/xml/etree/ElementInclude.pyi b/stdlib/@python2/xml/etree/ElementInclude.pyi deleted file mode 100644 index b74285d3e9b7..000000000000 --- a/stdlib/@python2/xml/etree/ElementInclude.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Callable -from xml.etree.ElementTree import Element - -XINCLUDE: str -XINCLUDE_INCLUDE: str -XINCLUDE_FALLBACK: str - -class FatalIncludeError(SyntaxError): ... - -def default_loader(href: str | bytes | int, parse: str, encoding: str | None = ...) -> str | Element: ... - -# TODO: loader is of type default_loader ie it takes a callable that has the -# same signature as default_loader. But default_loader has a keyword argument -# Which can't be represented using Callable... -def include(elem: Element, loader: Callable[..., str | Element] | None = ...) -> None: ... diff --git a/stdlib/@python2/xml/etree/ElementPath.pyi b/stdlib/@python2/xml/etree/ElementPath.pyi deleted file mode 100644 index 02fe84567543..000000000000 --- a/stdlib/@python2/xml/etree/ElementPath.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Callable, Dict, Generator, List, Pattern, Tuple, TypeVar -from xml.etree.ElementTree import Element - -xpath_tokenizer_re: Pattern[str] - -_token = Tuple[str, str] -_next = Callable[[], _token] -_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] - -def xpath_tokenizer(pattern: str, namespaces: Dict[str, str] | None = ...) -> Generator[_token, None, None]: ... -def get_parent_map(context: _SelectorContext) -> Dict[Element, Element]: ... -def prepare_child(next: _next, token: _token) -> _callback: ... -def prepare_star(next: _next, token: _token) -> _callback: ... -def prepare_self(next: _next, token: _token) -> _callback: ... -def prepare_descendant(next: _next, token: _token) -> _callback: ... -def prepare_parent(next: _next, token: _token) -> _callback: ... -def prepare_predicate(next: _next, token: _token) -> _callback: ... - -ops: Dict[str, Callable[[_next, _token], _callback]] - -class _SelectorContext: - parent_map: Dict[Element, Element] | None - root: Element - def __init__(self, root: Element) -> None: ... - -_T = TypeVar("_T") - -def iterfind(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> Generator[Element, None, None]: ... -def find(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> Element | None: ... -def findall(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> List[Element]: ... -def findtext(elem: Element, path: str, default: _T | None = ..., namespaces: Dict[str, str] | None = ...) -> _T | str: ... diff --git a/stdlib/@python2/xml/etree/ElementTree.pyi b/stdlib/@python2/xml/etree/ElementTree.pyi deleted file mode 100644 index a7a0a1c65f46..000000000000 --- a/stdlib/@python2/xml/etree/ElementTree.pyi +++ /dev/null @@ -1,201 +0,0 @@ -from _typeshed import FileDescriptor -from typing import ( - IO, - Any, - Callable, - Dict, - Generator, - ItemsView, - Iterable, - Iterator, - KeysView, - List, - MutableSequence, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) - -VERSION: str - -class ParseError(SyntaxError): - code: int - position: Tuple[int, int] - -def iselement(element: object) -> bool: ... - -_T = TypeVar("_T") - -# Type for parser inputs. Parser will accept any unicode/str/bytes and coerce, -# and this is true in py2 and py3 (even fromstringlist() in python3 can be -# called with a heterogeneous list) -_parser_input_type = Union[bytes, Text] - -# Type for individual tag/attr/ns/text values in args to most functions. -# In py2, the library accepts str or unicode everywhere and coerces -# aggressively. -# In py3, bytes is not coerced to str and so use of bytes is probably an error, -# so we exclude it. (why? the parser never produces bytes when it parses XML, -# so e.g., element.get(b'name') will always return None for parsed XML, even if -# there is a 'name' attribute.) -_str_argument_type = Union[str, Text] - -# Type for return values from individual tag/attr/text values -# in python2, if the tag/attribute/text wasn't decode-able as ascii, it -# comes out as a unicode string; otherwise it comes out as str. (see -# _fixtext function in the source). Client code knows best: -_str_result_type = Any - -_file_or_filename = Union[Text, FileDescriptor, IO[Any]] - -class Element(MutableSequence[Element]): - tag: _str_result_type - attrib: Dict[_str_result_type, _str_result_type] - text: _str_result_type | None - tail: _str_result_type | None - def __init__( - self, - tag: _str_argument_type | Callable[..., Element], - attrib: Dict[_str_argument_type, _str_argument_type] = ..., - **extra: _str_argument_type, - ) -> None: ... - def append(self, __subelement: Element) -> None: ... - def clear(self) -> None: ... - def extend(self, __elements: Iterable[Element]) -> None: ... - def find( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> Element | None: ... - def findall( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> List[Element]: ... - @overload - def findtext( - self, path: _str_argument_type, default: None = ..., namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> _str_result_type | None: ... - @overload - def findtext( - self, path: _str_argument_type, default: _T, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> _T | _str_result_type: ... - @overload - def get(self, key: _str_argument_type, default: None = ...) -> _str_result_type | None: ... - @overload - def get(self, key: _str_argument_type, default: _T) -> _str_result_type | _T: ... - def insert(self, __index: int, __element: Element) -> None: ... - def items(self) -> ItemsView[_str_result_type, _str_result_type]: ... - def iter(self, tag: _str_argument_type | None = ...) -> Generator[Element, None, None]: ... - def iterfind( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> Generator[Element, None, None]: ... - def itertext(self) -> Generator[_str_result_type, None, None]: ... - def keys(self) -> KeysView[_str_result_type]: ... - def makeelement(self, __tag: _str_argument_type, __attrib: Dict[_str_argument_type, _str_argument_type]) -> Element: ... - def remove(self, __subelement: Element) -> None: ... - def set(self, __key: _str_argument_type, __value: _str_argument_type) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - @overload - def __getitem__(self, i: int) -> Element: ... - @overload - def __getitem__(self, s: slice) -> MutableSequence[Element]: ... - def __len__(self) -> int: ... - @overload - def __setitem__(self, i: int, o: Element) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... - def getchildren(self) -> List[Element]: ... - def getiterator(self, tag: _str_argument_type | None = ...) -> List[Element]: ... - -def SubElement( - parent: Element, - tag: _str_argument_type, - attrib: Dict[_str_argument_type, _str_argument_type] = ..., - **extra: _str_argument_type, -) -> Element: ... -def Comment(text: _str_argument_type | None = ...) -> Element: ... -def ProcessingInstruction(target: _str_argument_type, text: _str_argument_type | None = ...) -> Element: ... - -PI: Callable[..., Element] - -class QName: - text: str - def __init__(self, text_or_uri: _str_argument_type, tag: _str_argument_type | None = ...) -> None: ... - -class ElementTree: - def __init__(self, element: Element | None = ..., file: _file_or_filename | None = ...) -> None: ... - def getroot(self) -> Element: ... - def parse(self, source: _file_or_filename, parser: XMLParser | None = ...) -> Element: ... - def iter(self, tag: _str_argument_type | None = ...) -> Generator[Element, None, None]: ... - def getiterator(self, tag: _str_argument_type | None = ...) -> List[Element]: ... - def find( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> Element | None: ... - @overload - def findtext( - self, path: _str_argument_type, default: None = ..., namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> _str_result_type | None: ... - @overload - def findtext( - self, path: _str_argument_type, default: _T, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> _T | _str_result_type: ... - def findall( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> List[Element]: ... - def iterfind( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> Generator[Element, None, None]: ... - def write( - self, - file_or_filename: _file_or_filename, - encoding: str | None = ..., - xml_declaration: bool | None = ..., - default_namespace: _str_argument_type | None = ..., - method: str | None = ..., - ) -> None: ... - def write_c14n(self, file: _file_or_filename) -> None: ... - -def register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... -def tostring(element: Element, encoding: str | None = ..., method: str | None = ...) -> bytes: ... -def tostringlist(element: Element, encoding: str | None = ..., method: str | None = ...) -> List[bytes]: ... -def dump(elem: Element) -> None: ... -def parse(source: _file_or_filename, parser: XMLParser | None = ...) -> ElementTree: ... -def iterparse( - source: _file_or_filename, events: Sequence[str] | None = ..., parser: XMLParser | None = ... -) -> Iterator[Tuple[str, Any]]: ... -def XML(text: _parser_input_type, parser: XMLParser | None = ...) -> Element: ... -def XMLID(text: _parser_input_type, parser: XMLParser | None = ...) -> Tuple[Element, Dict[_str_result_type, Element]]: ... - -# This is aliased to XML in the source. -fromstring = XML - -def fromstringlist(sequence: Sequence[_parser_input_type], parser: XMLParser | None = ...) -> Element: ... - -# This type is both not precise enough and too precise. The TreeBuilder -# requires the elementfactory to accept tag and attrs in its args and produce -# some kind of object that has .text and .tail properties. -# I've chosen to constrain the ElementFactory to always produce an Element -# because that is how almost everyone will use it. -# Unfortunately, the type of the factory arguments is dependent on how -# TreeBuilder is called by client code (they could pass strs, bytes or whatever); -# but we don't want to use a too-broad type, or it would be too hard to write -# elementfactories. -_ElementFactory = Callable[[Any, Dict[Any, Any]], Element] - -class TreeBuilder: - def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... - def close(self) -> Element: ... - def data(self, __data: _parser_input_type) -> None: ... - def start(self, __tag: _parser_input_type, __attrs: Dict[_parser_input_type, _parser_input_type]) -> Element: ... - def end(self, __tag: _parser_input_type) -> Element: ... - -class XMLParser: - parser: Any - target: Any - # TODO-what is entity used for??? - entity: Any - version: str - def __init__(self, html: int = ..., target: Any = ..., encoding: str | None = ...) -> None: ... - def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... - def close(self) -> Any: ... - def feed(self, __data: _parser_input_type) -> None: ... diff --git a/stdlib/@python2/xml/etree/cElementTree.pyi b/stdlib/@python2/xml/etree/cElementTree.pyi deleted file mode 100644 index c41e2bee0eb1..000000000000 --- a/stdlib/@python2/xml/etree/cElementTree.pyi +++ /dev/null @@ -1 +0,0 @@ -from xml.etree.ElementTree import * # noqa: F403 diff --git a/stdlib/@python2/xml/parsers/__init__.pyi b/stdlib/@python2/xml/parsers/__init__.pyi deleted file mode 100644 index cac086235cba..000000000000 --- a/stdlib/@python2/xml/parsers/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -import xml.parsers.expat as expat diff --git a/stdlib/@python2/xml/parsers/expat/__init__.pyi b/stdlib/@python2/xml/parsers/expat/__init__.pyi deleted file mode 100644 index 73f3758c61ec..000000000000 --- a/stdlib/@python2/xml/parsers/expat/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from pyexpat import * diff --git a/stdlib/@python2/xml/parsers/expat/errors.pyi b/stdlib/@python2/xml/parsers/expat/errors.pyi deleted file mode 100644 index e22d769ec340..000000000000 --- a/stdlib/@python2/xml/parsers/expat/errors.pyi +++ /dev/null @@ -1 +0,0 @@ -from pyexpat.errors import * diff --git a/stdlib/@python2/xml/parsers/expat/model.pyi b/stdlib/@python2/xml/parsers/expat/model.pyi deleted file mode 100644 index d8f44b47c51b..000000000000 --- a/stdlib/@python2/xml/parsers/expat/model.pyi +++ /dev/null @@ -1 +0,0 @@ -from pyexpat.model import * diff --git a/stdlib/@python2/xml/sax/__init__.pyi b/stdlib/@python2/xml/sax/__init__.pyi deleted file mode 100644 index 0c6da9a87d13..000000000000 --- a/stdlib/@python2/xml/sax/__init__.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import IO, Any, List, NoReturn, Text -from xml.sax.handler import ContentHandler, ErrorHandler -from xml.sax.xmlreader import Locator, XMLReader - -class SAXException(Exception): - def __init__(self, msg: str, exception: Exception | None = ...) -> None: ... - def getMessage(self) -> str: ... - def getException(self) -> Exception: ... - def __getitem__(self, ix: Any) -> NoReturn: ... - -class SAXParseException(SAXException): - def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... - def getColumnNumber(self) -> int: ... - def getLineNumber(self) -> int: ... - def getPublicId(self): ... - def getSystemId(self): ... - -class SAXNotRecognizedException(SAXException): ... -class SAXNotSupportedException(SAXException): ... -class SAXReaderNotAvailable(SAXNotSupportedException): ... - -default_parser_list: List[str] - -def make_parser(parser_list: List[str] = ...) -> XMLReader: ... -def parse(source: str | IO[str] | IO[bytes], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... -def parseString(string: bytes | Text, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... -def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/stdlib/@python2/xml/sax/handler.pyi b/stdlib/@python2/xml/sax/handler.pyi deleted file mode 100644 index 3a5193300981..000000000000 --- a/stdlib/@python2/xml/sax/handler.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Any - -version: Any - -class ErrorHandler: - def error(self, exception): ... - def fatalError(self, exception): ... - def warning(self, exception): ... - -class ContentHandler: - def __init__(self) -> None: ... - def setDocumentLocator(self, locator): ... - def startDocument(self): ... - def endDocument(self): ... - def startPrefixMapping(self, prefix, uri): ... - def endPrefixMapping(self, prefix): ... - def startElement(self, name, attrs): ... - def endElement(self, name): ... - def startElementNS(self, name, qname, attrs): ... - def endElementNS(self, name, qname): ... - def characters(self, content): ... - def ignorableWhitespace(self, whitespace): ... - def processingInstruction(self, target, data): ... - def skippedEntity(self, name): ... - -class DTDHandler: - def notationDecl(self, name, publicId, systemId): ... - def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... - -class EntityResolver: - def resolveEntity(self, publicId, systemId): ... - -feature_namespaces: Any -feature_namespace_prefixes: Any -feature_string_interning: Any -feature_validation: Any -feature_external_ges: Any -feature_external_pes: Any -all_features: Any -property_lexical_handler: Any -property_declaration_handler: Any -property_dom_node: Any -property_xml_string: Any -property_encoding: Any -property_interning_dict: Any -all_properties: Any diff --git a/stdlib/@python2/xml/sax/saxutils.pyi b/stdlib/@python2/xml/sax/saxutils.pyi deleted file mode 100644 index 1fc896490f54..000000000000 --- a/stdlib/@python2/xml/sax/saxutils.pyi +++ /dev/null @@ -1,59 +0,0 @@ -from _typeshed import SupportsWrite -from codecs import StreamReaderWriter, StreamWriter -from io import RawIOBase, TextIOBase -from typing import Mapping, Text -from xml.sax import handler, xmlreader - -def escape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... -def unescape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... -def quoteattr(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... - -class XMLGenerator(handler.ContentHandler): - def __init__( - self, - out: TextIOBase | RawIOBase | StreamWriter | StreamReaderWriter | SupportsWrite[str] | None = ..., - encoding: Text = ..., - ) -> None: ... - def startDocument(self): ... - def endDocument(self): ... - def startPrefixMapping(self, prefix, uri): ... - def endPrefixMapping(self, prefix): ... - def startElement(self, name, attrs): ... - def endElement(self, name): ... - def startElementNS(self, name, qname, attrs): ... - def endElementNS(self, name, qname): ... - def characters(self, content): ... - def ignorableWhitespace(self, content): ... - def processingInstruction(self, target, data): ... - -class XMLFilterBase(xmlreader.XMLReader): - def __init__(self, parent: xmlreader.XMLReader | None = ...) -> None: ... - def error(self, exception): ... - def fatalError(self, exception): ... - def warning(self, exception): ... - def setDocumentLocator(self, locator): ... - def startDocument(self): ... - def endDocument(self): ... - def startPrefixMapping(self, prefix, uri): ... - def endPrefixMapping(self, prefix): ... - def startElement(self, name, attrs): ... - def endElement(self, name): ... - def startElementNS(self, name, qname, attrs): ... - def endElementNS(self, name, qname): ... - def characters(self, content): ... - def ignorableWhitespace(self, chars): ... - def processingInstruction(self, target, data): ... - def skippedEntity(self, name): ... - def notationDecl(self, name, publicId, systemId): ... - def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... - def resolveEntity(self, publicId, systemId): ... - def parse(self, source): ... - def setLocale(self, locale): ... - def getFeature(self, name): ... - def setFeature(self, name, state): ... - def getProperty(self, name): ... - def setProperty(self, name, value): ... - def getParent(self): ... - def setParent(self, parent): ... - -def prepare_input_source(source, base=...): ... diff --git a/stdlib/@python2/xml/sax/xmlreader.pyi b/stdlib/@python2/xml/sax/xmlreader.pyi deleted file mode 100644 index 8afc566b16a1..000000000000 --- a/stdlib/@python2/xml/sax/xmlreader.pyi +++ /dev/null @@ -1,72 +0,0 @@ -from typing import Mapping, Tuple - -class XMLReader: - def __init__(self) -> None: ... - def parse(self, source): ... - def getContentHandler(self): ... - def setContentHandler(self, handler): ... - def getDTDHandler(self): ... - def setDTDHandler(self, handler): ... - def getEntityResolver(self): ... - def setEntityResolver(self, resolver): ... - def getErrorHandler(self): ... - def setErrorHandler(self, handler): ... - def setLocale(self, locale): ... - def getFeature(self, name): ... - def setFeature(self, name, state): ... - def getProperty(self, name): ... - def setProperty(self, name, value): ... - -class IncrementalParser(XMLReader): - def __init__(self, bufsize: int = ...) -> None: ... - def parse(self, source): ... - def feed(self, data): ... - def prepareParser(self, source): ... - def close(self): ... - def reset(self): ... - -class Locator: - def getColumnNumber(self): ... - def getLineNumber(self): ... - def getPublicId(self): ... - def getSystemId(self): ... - -class InputSource: - def __init__(self, system_id: str | None = ...) -> None: ... - def setPublicId(self, public_id): ... - def getPublicId(self): ... - def setSystemId(self, system_id): ... - def getSystemId(self): ... - def setEncoding(self, encoding): ... - def getEncoding(self): ... - def setByteStream(self, bytefile): ... - def getByteStream(self): ... - def setCharacterStream(self, charfile): ... - def getCharacterStream(self): ... - -class AttributesImpl: - def __init__(self, attrs: Mapping[str, str]) -> None: ... - def getLength(self): ... - def getType(self, name): ... - def getValue(self, name): ... - def getValueByQName(self, name): ... - def getNameByQName(self, name): ... - def getQNameByName(self, name): ... - def getNames(self): ... - def getQNames(self): ... - def __len__(self): ... - def __getitem__(self, name): ... - def keys(self): ... - def __contains__(self, name): ... - def get(self, name, alternative=...): ... - def copy(self): ... - def items(self): ... - def values(self): ... - -class AttributesNSImpl(AttributesImpl): - def __init__(self, attrs: Mapping[Tuple[str, str], str], qnames: Mapping[Tuple[str, str], str]) -> None: ... - def getValueByQName(self, name): ... - def getNameByQName(self, name): ... - def getQNameByName(self, name): ... - def getQNames(self): ... - def copy(self): ... diff --git a/stdlib/@python2/xmlrpclib.pyi b/stdlib/@python2/xmlrpclib.pyi deleted file mode 100644 index 5a7d0fc34f0e..000000000000 --- a/stdlib/@python2/xmlrpclib.pyi +++ /dev/null @@ -1,244 +0,0 @@ -from datetime import datetime -from gzip import GzipFile -from httplib import HTTPConnection, HTTPResponse, HTTPSConnection -from ssl import SSLContext -from StringIO import StringIO -from time import struct_time -from types import InstanceType -from typing import IO, Any, AnyStr, Callable, Iterable, List, Mapping, MutableMapping, Tuple, Type, Union - -_Unmarshaller = Any -_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] -# Represents types that can be compared against a DateTime object -_dateTimeComp = Union[unicode, DateTime, datetime] -# A "host description" used by Transport factories -_hostDesc = Union[str, Tuple[str, Mapping[Any, Any]]] - -def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... - -MAXINT: int -MININT: int -PARSE_ERROR: int -SERVER_ERROR: int -APPLICATION_ERROR: int -SYSTEM_ERROR: int -TRANSPORT_ERROR: int -NOT_WELLFORMED_ERROR: int -UNSUPPORTED_ENCODING: int -INVALID_ENCODING_CHAR: int -INVALID_XMLRPC: int -METHOD_NOT_FOUND: int -INVALID_METHOD_PARAMS: int -INTERNAL_ERROR: int - -class Error(Exception): ... - -class ProtocolError(Error): - url: str - errcode: int - errmsg: str - headers: Any - def __init__(self, url: str, errcode: int, errmsg: str, headers: Any) -> None: ... - -class ResponseError(Error): ... - -class Fault(Error): - faultCode: Any - faultString: str - def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... - -boolean: Type[bool] -Boolean: Type[bool] - -class DateTime: - value: str - def __init__(self, value: str | unicode | datetime | float | int | _timeTuple | struct_time = ...) -> None: ... - def make_comparable(self, other: _dateTimeComp) -> Tuple[unicode, unicode]: ... - def __lt__(self, other: _dateTimeComp) -> bool: ... - def __le__(self, other: _dateTimeComp) -> bool: ... - def __gt__(self, other: _dateTimeComp) -> bool: ... - def __ge__(self, other: _dateTimeComp) -> bool: ... - def __eq__(self, other: _dateTimeComp) -> bool: ... # type: ignore - def __ne__(self, other: _dateTimeComp) -> bool: ... # type: ignore - def timetuple(self) -> struct_time: ... - def __cmp__(self, other: _dateTimeComp) -> int: ... - def decode(self, data: Any) -> None: ... - def encode(self, out: IO[str]) -> None: ... - -class Binary: - data: str - def __init__(self, data: str | None = ...) -> None: ... - def __cmp__(self, other: Any) -> int: ... - def decode(self, data: str) -> None: ... - def encode(self, out: IO[str]) -> None: ... - -WRAPPERS: Tuple[Type[Any], ...] - -# Still part of the public API, but see http://bugs.python.org/issue1773632 -FastParser: None -FastUnmarshaller: None -FastMarshaller: None - -# xmlrpclib.py will leave ExpatParser undefined if it can't import expat from -# xml.parsers. Because this is Python 2.7, the import will succeed. -class ExpatParser: - def __init__(self, target: _Unmarshaller) -> None: ... - def feed(self, data: str): ... - def close(self): ... - -# TODO: Add xmllib.XMLParser as base class -class SlowParser: - handle_xml: Callable[[str, bool], None] - unknown_starttag: Callable[[str, Any], None] - handle_data: Callable[[str], None] - handle_cdata: Callable[[str], None] - unknown_endtag: Callable[[str, Callable[[Iterable[str], str], str]], None] - def __init__(self, target: _Unmarshaller) -> None: ... - -class Marshaller: - memo: MutableMapping[int, Any] - data: str | None - encoding: str | None - allow_none: bool - def __init__(self, encoding: str | None = ..., allow_none: bool = ...) -> None: ... - dispatch: Mapping[type, Callable[[Marshaller, str, Callable[[str], None]], None]] - def dumps( - self, - values: Iterable[ - None - | int - | bool - | long - | float - | str - | unicode - | List[Any] - | Tuple[Any, ...] - | Mapping[Any, Any] - | datetime - | InstanceType - ] - | Fault, - ) -> str: ... - def dump_nil(self, value: None, write: Callable[[str], None]) -> None: ... - def dump_int(self, value: int, write: Callable[[str], None]) -> None: ... - def dump_bool(self, value: bool, write: Callable[[str], None]) -> None: ... - def dump_long(self, value: long, write: Callable[[str], None]) -> None: ... - def dump_double(self, value: float, write: Callable[[str], None]) -> None: ... - def dump_string( - self, - value: str, - write: Callable[[str], None], - escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., - ) -> None: ... - def dump_unicode( - self, - value: unicode, - write: Callable[[str], None], - escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., - ) -> None: ... - def dump_array(self, value: Iterable[Any], write: Callable[[str], None]) -> None: ... - def dump_struct( - self, - value: Mapping[unicode, Any], - write: Callable[[str], None], - escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., - ) -> None: ... - def dump_datetime(self, value: datetime, write: Callable[[str], None]) -> None: ... - def dump_instance(self, value: InstanceType, write: Callable[[str], None]) -> None: ... - -class Unmarshaller: - def append(self, object: Any) -> None: ... - def __init__(self, use_datetime: bool = ...) -> None: ... - def close(self) -> Tuple[Any, ...]: ... - def getmethodname(self) -> str | None: ... - def xml(self, encoding: str, standalone: bool) -> None: ... - def start(self, tag: str, attrs: Any) -> None: ... - def data(self, text: str) -> None: ... - def end(self, tag: str, join: Callable[[Iterable[str], str], str] = ...) -> None: ... - def end_dispatch(self, tag: str, data: str) -> None: ... - dispatch: Mapping[str, Callable[[Unmarshaller, str], None]] - def end_nil(self, data: str): ... - def end_boolean(self, data: str) -> None: ... - def end_int(self, data: str) -> None: ... - def end_double(self, data: str) -> None: ... - def end_string(self, data: str) -> None: ... - def end_array(self, data: str) -> None: ... - def end_struct(self, data: str) -> None: ... - def end_base64(self, data: str) -> None: ... - def end_dateTime(self, data: str) -> None: ... - def end_value(self, data: str) -> None: ... - def end_params(self, data: str) -> None: ... - def end_fault(self, data: str) -> None: ... - def end_methodName(self, data: str) -> None: ... - -class _MultiCallMethod: - def __init__(self, call_list: List[Tuple[str, Tuple[Any, ...]]], name: str) -> None: ... - -class MultiCallIterator: - def __init__(self, results: List[Any]) -> None: ... - -class MultiCall: - def __init__(self, server: ServerProxy) -> None: ... - def __getattr__(self, name: str) -> _MultiCallMethod: ... - def __call__(self) -> MultiCallIterator: ... - -def getparser(use_datetime: bool = ...) -> Tuple[ExpatParser | SlowParser, Unmarshaller]: ... -def dumps( - params: Tuple[Any, ...] | Fault, - methodname: str | None = ..., - methodresponse: bool | None = ..., - encoding: str | None = ..., - allow_none: bool = ..., -) -> str: ... -def loads(data: str, use_datetime: bool = ...) -> Tuple[Tuple[Any, ...], str | None]: ... -def gzip_encode(data: str) -> str: ... -def gzip_decode(data: str, max_decode: int = ...) -> str: ... - -class GzipDecodedResponse(GzipFile): - stringio: StringIO[Any] - def __init__(self, response: HTTPResponse) -> None: ... - def close(self): ... - -class _Method: - def __init__(self, send: Callable[[str, Tuple[Any, ...]], Any], name: str) -> None: ... - def __getattr__(self, name: str) -> _Method: ... - def __call__(self, *args: Any) -> Any: ... - -class Transport: - user_agent: str - accept_gzip_encoding: bool - encode_threshold: int | None - def __init__(self, use_datetime: bool = ...) -> None: ... - def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... - verbose: bool - def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... - def getparser(self) -> Tuple[ExpatParser | SlowParser, Unmarshaller]: ... - def get_host_info(self, host: _hostDesc) -> Tuple[str, List[Tuple[str, str]] | None, Mapping[Any, Any] | None]: ... - def make_connection(self, host: _hostDesc) -> HTTPConnection: ... - def close(self) -> None: ... - def send_request(self, connection: HTTPConnection, handler: str, request_body: str) -> None: ... - def send_host(self, connection: HTTPConnection, host: str) -> None: ... - def send_user_agent(self, connection: HTTPConnection) -> None: ... - def send_content(self, connection: HTTPConnection, request_body: str) -> None: ... - def parse_response(self, response: HTTPResponse) -> Tuple[Any, ...]: ... - -class SafeTransport(Transport): - def __init__(self, use_datetime: bool = ..., context: SSLContext | None = ...) -> None: ... - def make_connection(self, host: _hostDesc) -> HTTPSConnection: ... - -class ServerProxy: - def __init__( - self, - uri: str, - transport: Transport | None = ..., - encoding: str | None = ..., - verbose: bool = ..., - allow_none: bool = ..., - use_datetime: bool = ..., - context: SSLContext | None = ..., - ) -> None: ... - def __getattr__(self, name: str) -> _Method: ... - def __call__(self, attr: str) -> Transport | None: ... - -Server = ServerProxy diff --git a/stdlib/@python2/zipfile.pyi b/stdlib/@python2/zipfile.pyi deleted file mode 100644 index 5a0879492a88..000000000000 --- a/stdlib/@python2/zipfile.pyi +++ /dev/null @@ -1,101 +0,0 @@ -import io -from _typeshed import StrPath -from types import TracebackType -from typing import IO, Any, Callable, Dict, Iterable, List, Pattern, Protocol, Sequence, Text, Tuple, Type, Union - -_SZI = Union[Text, ZipInfo] -_DT = Tuple[int, int, int, int, int, int] - -class BadZipfile(Exception): ... - -error = BadZipfile - -class LargeZipFile(Exception): ... - -class ZipExtFile(io.BufferedIOBase): - MAX_N: int = ... - MIN_READ_SIZE: int = ... - - PATTERN: Pattern[str] = ... - - newlines: List[bytes] | None - mode: str - name: str - def __init__( - self, - fileobj: IO[bytes], - mode: str, - zipinfo: ZipInfo, - decrypter: Callable[[Sequence[int]], bytes] | None = ..., - close_fileobj: bool = ..., - ) -> None: ... - def read(self, n: int | None = ...) -> bytes: ... - def readline(self, limit: int = ...) -> bytes: ... # type: ignore - def __repr__(self) -> str: ... - def peek(self, n: int = ...) -> bytes: ... - def read1(self, n: int | None) -> bytes: ... # type: ignore - -class _Writer(Protocol): - def write(self, __s: str) -> Any: ... - -class ZipFile: - filename: Text | None - debug: int - comment: bytes - filelist: List[ZipInfo] - fp: IO[bytes] | None - NameToInfo: Dict[Text, ZipInfo] - start_dir: int # undocumented - def __init__(self, file: StrPath | IO[bytes], mode: Text = ..., compression: int = ..., allowZip64: bool = ...) -> None: ... - def __enter__(self) -> ZipFile: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - def close(self) -> None: ... - def getinfo(self, name: Text) -> ZipInfo: ... - def infolist(self) -> List[ZipInfo]: ... - def namelist(self) -> List[Text]: ... - def open(self, name: _SZI, mode: Text = ..., pwd: bytes | None = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... - def extract(self, member: _SZI, path: StrPath | None = ..., pwd: bytes | None = ...) -> str: ... - def extractall(self, path: StrPath | None = ..., members: Iterable[Text] | None = ..., pwd: bytes | None = ...) -> None: ... - def printdir(self) -> None: ... - def setpassword(self, pwd: bytes) -> None: ... - def read(self, name: _SZI, pwd: bytes | None = ...) -> bytes: ... - def testzip(self) -> str | None: ... - def write(self, filename: StrPath, arcname: StrPath | None = ..., compress_type: int | None = ...) -> None: ... - def writestr(self, zinfo_or_arcname: _SZI, bytes: bytes, compress_type: int | None = ...) -> None: ... - -class PyZipFile(ZipFile): - def writepy(self, pathname: Text, basename: Text = ...) -> None: ... - -class ZipInfo: - filename: Text - date_time: _DT - compress_type: int - comment: bytes - extra: bytes - create_system: int - create_version: int - extract_version: int - reserved: int - flag_bits: int - volume: int - internal_attr: int - external_attr: int - header_offset: int - CRC: int - compress_size: int - file_size: int - def __init__(self, filename: Text | None = ..., date_time: _DT | None = ...) -> None: ... - def FileHeader(self, zip64: bool | None = ...) -> bytes: ... - -class _PathOpenProtocol(Protocol): - def __call__(self, mode: str = ..., pwd: bytes | None = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... - -def is_zipfile(filename: StrPath | IO[bytes]) -> bool: ... - -ZIP_STORED: int -ZIP_DEFLATED: int -ZIP64_LIMIT: int -ZIP_FILECOUNT_LIMIT: int -ZIP_MAX_COMMENT: int diff --git a/stdlib/@python2/zipimport.pyi b/stdlib/@python2/zipimport.pyi deleted file mode 100644 index bcefd6859059..000000000000 --- a/stdlib/@python2/zipimport.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from types import CodeType, ModuleType - -class ZipImportError(ImportError): ... - -class zipimporter(object): - archive: str - prefix: str - def __init__(self, path: str | bytes) -> None: ... - def find_module(self, fullname: str, path: str | None = ...) -> zipimporter | None: ... - def get_code(self, fullname: str) -> CodeType: ... - def get_data(self, pathname: str) -> str: ... - def get_filename(self, fullname: str) -> str: ... - def get_source(self, fullname: str) -> str | None: ... - def is_package(self, fullname: str) -> bool: ... - def load_module(self, fullname: str) -> ModuleType: ... diff --git a/stdlib/@python2/zlib.pyi b/stdlib/@python2/zlib.pyi deleted file mode 100644 index 2cee20fc0928..000000000000 --- a/stdlib/@python2/zlib.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from array import array -from typing import Any - -DEFLATED: int -DEF_MEM_LEVEL: int -MAX_WBITS: int -ZLIB_VERSION: str -Z_BEST_COMPRESSION: int -Z_BEST_SPEED: int -Z_DEFAULT_COMPRESSION: int -Z_DEFAULT_STRATEGY: int -Z_FILTERED: int -Z_FINISH: int -Z_FIXED: int -Z_FULL_FLUSH: int -Z_HUFFMAN_ONLY: int -Z_NO_FLUSH: int -Z_RLE: int -Z_SYNC_FLUSH: int - -class error(Exception): ... - -class _Compress: - def compress(self, data: bytes) -> bytes: ... - def flush(self, mode: int = ...) -> bytes: ... - def copy(self) -> _Compress: ... - -class _Decompress: - unused_data: bytes - unconsumed_tail: bytes - def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... - def flush(self, length: int = ...) -> bytes: ... - def copy(self) -> _Decompress: ... - -def adler32(__data: bytes, __value: int = ...) -> int: ... -def compress(__data: bytes, level: int = ...) -> bytes: ... -def compressobj(level: int = ..., method: int = ..., wbits: int = ..., memlevel: int = ..., strategy: int = ...) -> _Compress: ... -def crc32(__data: array[Any] | bytes, __value: int = ...) -> int: ... -def decompress(__data: bytes, wbits: int = ..., bufsize: int = ...) -> bytes: ... -def decompressobj(wbits: int = ...) -> _Decompress: ... diff --git a/stdlib/@tests/stubtest_allowlists/common.txt b/stdlib/@tests/stubtest_allowlists/common.txt new file mode 100644 index 000000000000..a02939590f22 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/common.txt @@ -0,0 +1,491 @@ +# ============================================ +# TODO: Allowlist entries that should be fixed +# ============================================ + +# Please keep sorted alphabetically + +importlib.abc.MetaPathFinder.find_spec # Not defined on the actual class, but expected to exist. +importlib.abc.PathEntryFinder.find_spec # Not defined on the actual class, but expected to exist. +tarfile.TarInfo.__slots__ # it's a big dictionary at runtime and the dictionary values are a bit long + + +# =============================================================== +# TODO: Modules that exist at runtime, but are missing from stubs +# =============================================================== + +turtledemo +turtledemo\..+ + + +# ====================================================================== +# Modules that exist at runtime, but are deliberately missing from stubs +# ====================================================================== + +idlelib + + +# ============================================================================= +# Module members that exist at runtime, but are deliberately missing from stubs +# ============================================================================= + +# Undocumented implementation details of a deprecated class +_frozen_importlib_external.WindowsRegistryFinder.DEBUG_BUILD +_frozen_importlib_external.WindowsRegistryFinder.REGISTRY_KEY +_frozen_importlib_external.WindowsRegistryFinder.REGISTRY_KEY_DEBUG + +builtins.OSError.characters_written # GetSetDescriptor that always raises AttributeError +builtins.float.__getformat__ # Internal method for CPython test suite + +# These super() dunders don't seem to be particularly useful, +# and having them pop up on autocomplete suggestions would be annoying +builtins.super.__self__ +builtins.super.__self_class__ +builtins.super.__thisclass__ + +# The following reverse operators are present in the C implementation +# (probably incidental), but missing from the Python implementation. +datetime.date.__rsub__ +datetime.datetime.__rsub__ +datetime.timedelta.__rdivmod__ +datetime.timedelta.__rfloordiv__ +datetime.timedelta.__rmod__ +datetime.timedelta.__rtruediv__ + +# Undocumented implementation details +email.contentmanager.get_and_fixup_unknown_message_content +email.contentmanager.get_message_content +email.contentmanager.get_non_text_content +email.contentmanager.get_text_content +email.contentmanager.set_bytes_content +email.contentmanager.set_message_content +email.contentmanager.set_text_content + +ftplib.FTP.trust_server_pasv_ipv4_address # Dangerous to use, intentionally undocumented #6154 +hmac.HMAC.blocksize # use block_size instead + +# Undocumented implementation details +profile.Profile.dispatch +profile.Profile.fake_code +profile.Profile.fake_frame +profile.Profile.trace_dispatch +profile.Profile.trace_dispatch_c_call +profile.Profile.trace_dispatch_call +profile.Profile.trace_dispatch_exception +profile.Profile.trace_dispatch_i +profile.Profile.trace_dispatch_l +profile.Profile.trace_dispatch_mac +profile.Profile.trace_dispatch_return + +re.Pattern.scanner # Undocumented and not useful. #6405 + +# Missing aliases to existing methods that not many people seem to use. +# Complicated multiple inheritance, confuses type checkers. +tkinter.Grid.bbox +tkinter.Grid.columnconfigure +tkinter.Grid.config +tkinter.Grid.configure +tkinter.Grid.forget +tkinter.Grid.grid_bbox +tkinter.Grid.grid_columnconfigure +tkinter.Grid.grid_location +tkinter.Grid.grid_propagate +tkinter.Grid.grid_rowconfigure +tkinter.Grid.grid_size +tkinter.Grid.grid_slaves +tkinter.Grid.info +tkinter.Grid.propagate +tkinter.Grid.rowconfigure +tkinter.Grid.slaves +tkinter.Pack.config +tkinter.Pack.configure +tkinter.Pack.info +tkinter.Pack.pack_propagate +tkinter.Pack.pack_slaves +tkinter.Pack.slaves +tkinter.Place.config +tkinter.Place.configure +tkinter.Place.forget +tkinter.Place.place_slaves +tkinter.Place.slaves + +turtle.ScrolledCanvas.adjustScrolls # Undocumented implementation detail +turtle.ScrolledCanvas.onResize # Undocumented implementation detail +uuid.bytes_ # Attributes that are intended to be private +uuid.int_ # Attributes that are intended to be private +wave.Wave_read.initfp # Undocumented implementation detail +wave.Wave_write.initfp # Undocumented implementation detail +_?weakref\.ProxyType\.__bytes__ # Doesn't actually exist + +# Undocumented and have a comment in the source code saying "State variables (don't mess with these)" +wsgiref.handlers.BaseHandler.bytes_sent +wsgiref.handlers.BaseHandler.headers +wsgiref.handlers.BaseHandler.headers_sent +wsgiref.handlers.BaseHandler.result +wsgiref.handlers.BaseHandler.status + + +# ===================================== +# Platform and installation differences +# ===================================== + +# LC_MESSAGES is sometimes present in __all__, sometimes not, +# so stubtest will sometimes complain about exported names being different at runtime to the exported names in the stub +(locale.__all__)? + +# Loadable SQLite extensions are disabled on GitHub runners +(sqlite3(.dbapi2)?.Connection.enable_load_extension)? +(sqlite3(.dbapi2)?.Connection.load_extension)? + +# sys attributes that are not always defined +sys.gettotalrefcount # Available on python debug builds +sys.last_traceback # Available after an unhandled error has occured +sys.last_type # Available after an unhandled error has occured +sys.last_value # Available after an unhandled error has occured +sys.ps1 # Available in interactive mode +sys.ps2 # Available in interactive mode +sys.tracebacklimit # Must be set first + +# This is only present if Python was built with zlib-ng. +(zlib\.ZLIBNG_VERSION)? +(compression\.zlib\.ZLIBNG_VERSION)? + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +# Pretend typing.ByteString is a Union, to better match its documented semantics. +# As a side effect, this changes the definition of collections.abc.ByteString, which is okay, +# because it's not an ABC that makes any sense and was deprecated in 3.12 +typing\.ByteString + +_ctypes.CFuncPtr # stubtest erroneously thinks it can't be subclassed + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.ExtensionFileLoader.get_filename +_frozen_importlib_external.FileLoader.get_filename +_frozen_importlib_external.FileLoader.get_resource_reader + +# Mismatch of default values of `report` parameter: +_markupbase.ParserBase.parse_comment +_markupbase.ParserBase.parse_marked_section + +_typeshed.* # Utility types for typeshed, doesn't exist at runtime +argparse.Namespace.__getattr__ # The whole point of this class is its attributes are dynamic + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.AST.__init__ +_?ast.excepthandler.__init__ +_?ast.expr.__init__ +_?ast.pattern.__init__ +_?ast.stmt.__init__ + +argparse.Namespace.__setattr__ # should allow setting any attribute + +ast.ImportFrom.level # None on the class, but never None on instances +ast.NodeVisitor.visit_\w+ # Methods are discovered dynamically, see #3796 + +# Condition functions are exported in __init__ +asyncio.locks.Condition.acquire +asyncio.locks.Condition.locked +asyncio.locks.Condition.release + +builtins.memoryview.__contains__ # C type that implements __getitem__ +builtins.property.__set_name__ # Doesn't actually exist +builtins.reveal_locals # Builtins that type checkers pretends exist +builtins.reveal_type # Builtins that type checkers pretends exist + +# The following CodecInfo properties are added in __new__ +codecs.CodecInfo.decode +codecs.CodecInfo.encode +codecs.CodecInfo.incrementaldecoder +codecs.CodecInfo.incrementalencoder +codecs.CodecInfo.streamreader +codecs.CodecInfo.streamwriter + +# See comments in file. List out methods that are delegated by __getattr__ at runtime. +# Used to make the relevant class satisfy BinaryIO interface. +codecs.StreamReaderWriter.\w+ +codecs.StreamRecoder.\w+ + +collections.UserList.index # ignoring pos-or-keyword parameter +collections.UserList.sort # Runtime has *args but will error if any are supplied +configparser.SectionProxy.__getattr__ # SectionProxy can have arbitrary attributes when custom converters are used +configparser.SectionProxy.getboolean # SectionProxy get functions are set in __init__ +configparser.SectionProxy.getfloat # SectionProxy get functions are set in __init__ +configparser.SectionProxy.getint # SectionProxy get functions are set in __init__ + +# Treated an alias of a typing class in the stubs, +# they are generic to type checkers anyway. +contextlib.AbstractAsyncContextManager.__class_getitem__ +contextlib.AbstractContextManager.__class_getitem__ + +copy.PyStringMap # defined only in Jython + +# The Dialect properties are initialized as None in Dialect but their values are enforced in _Dialect +csv.Dialect.delimiter +csv.Dialect.doublequote +csv.Dialect.lineterminator +csv.Dialect.quoting +csv.Dialect.skipinitialspace + +csv.DictReader.__init__ # runtime sig has *args but will error if more than 5 positional args are supplied +csv.DictWriter.__init__ # runtime sig has *args but will error if more than 5 positional args are supplied +_?ctypes.Array._type_ # _type_ is abstract, https://github.com/python/typeshed/pull/6361 +_?ctypes.Array._length_ # _length_ is abstract, https://github.com/python/typeshed/pull/6361 +_?ctypes.Array.raw # exists but stubtest can't see it; only available if _CT == c_char +ctypes.CDLL._FuncPtr # None at class level but initialized in __init__ to this value +_?ctypes.Structure.__getattr__ # doesn't exist, but makes things easy if we pretend it does +_?ctypes.Structure.__setattr__ # doesn't exist, but makes things easy if we pretend it does +_?ctypes.Union.__getattr__ # doesn't exist, but makes things easy if we pretend it does +_?ctypes.Union.__setattr__ # doesn't exist, but makes things easy if we pretend it does + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers. +# See https://github.com/python/mypy/issues/2220 and https://github.com/python/typeshed/issues/7813 +_?ctypes.Array.__iter__ +calendar._localized_day.__iter__ +calendar._localized_month.__iter__ + +dataclasses.KW_ONLY # white lies around defaults + +# __all__-related weirdness (see #6523) +email.__all__ +email.base64mime +email.charset +email.encoders +email.errors +email.feedparser +email.generator +email.header +email.iterators +email.message +email.mime +email.parser +email.quoprimime +email.utils + +enum.auto.__or__ # enum.auto is magic, see comments +enum.auto.__and__ # enum.auto is magic, see comments +enum.auto.__xor__ # enum.auto is magic, see comments + +functools._lru_cache_wrapper.cache_parameters # Cannot be detected statically +functools.cached_property.__set__ # doesn't exist, but cached_property is settable by another mechanism + +hmac.new # Raises TypeError if optional argument digestmod is not provided +html.parser.HTMLParser.parse_bogus_comment # default values mismatch +http.HTTPStatus.description # set in __new__; work-around for enum wierdness +http.HTTPStatus.phrase # set in __new__; work-around for enum wierdness +imaplib.IMAP4_SSL.ssl # Depends on the existence and flags of SSL + +importlib._abc.Loader.exec_module # See Lib/importlib/_abc.py. Might be defined for backwards compatibility + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +importlib.abc.FileLoader.get_filename + +importlib.metadata._meta.SimplePath.joinpath # Runtime definition of protocol is incorrect + +# We can't distinguish not having a default value from having a default value of inspect.Parameter.empty +inspect.Parameter.__init__ +inspect.Signature.__init__ + +logging.LogRecord.__setattr__ # doesn't exist, but makes things easy if we pretend it does + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers; see https://github.com/python/mypy/issues/2220 +mmap.mmap.__iter__ +mmap.mmap.__contains__ + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.BaseListProxy.__len__ +multiprocessing.managers.BaseListProxy.__reversed__ +multiprocessing.managers.BaseListProxy.reverse +multiprocessing.managers.BaseListProxy.sort + +# runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs +multiprocessing.managers.SyncManager.Event +multiprocessing.managers.SyncManager.Lock +multiprocessing.managers.SyncManager.Namespace +multiprocessing.managers.SyncManager.RLock + +multiprocessing.(dummy|managers).Namespace.__[gs]etattr__ # Any field can be set on Namespace +multiprocessing.pool.Pool.__del__ # Non-private parameter on __del__ + +# These are because the ctx argument has a default value in the stubs but not +# at runtime. This is a compromise between the runtime signatures of (for example) +# multiprocessing.Queue and multiprocessing.queues.Queue, which typeshed +# treats as the same object. +multiprocessing.queues.JoinableQueue.__init__ +multiprocessing.queues.Queue.__init__ +multiprocessing.queues.SimpleQueue.__init__ + +# These methods are dynamically created after object initialization, +# copied from a wrapped lock object. Stubtest doesn't think they exist +# because of that. +multiprocessing.synchronize.Condition.acquire +multiprocessing.synchronize.Condition.release +multiprocessing.synchronize.SemLock.acquire +multiprocessing.synchronize.SemLock.release + +numbers.Number.__hash__ # typeshed marks this as abstract but code just sets this as None + +optparse.Values.__getattr__ # Some attributes are set in __init__ using setattr +optparse.Values.__setattr__ # doesn't exist, but makes things easy if we pretend it does + +os._wrap_close.read # Methods that come from __getattr__() at runtime +os._wrap_close.readable # Methods that come from __getattr__() at runtime +os._wrap_close.readline # Methods that come from __getattr__() at runtime +os._wrap_close.readlines # Methods that come from __getattr__() at runtime +os._wrap_close.writable # Methods that come from __getattr__() at runtime +os._wrap_close.write # Methods that come from __getattr__() at runtime +os._wrap_close.writelines # Methods that come from __getattr__() at runtime +os.PathLike.__class_getitem__ # PathLike is a protocol; we don't expect all PathLike classes to implement class_getitem + +_pickle.Pickler.reducer_override # Can be added by subclasses +pickle._Pickler\..* # Best effort typing for undocumented internals +pickle._Unpickler\..* # Best effort typing for undocumented internals + +socketserver.BaseServer.get_request # Not implemented, but expected to exist on subclasses. +ssl.PROTOCOL_SSLv2 # Depends on the existence and flags of SSL +ssl.PROTOCOL_SSLv3 # Depends on the existence and flags of SSL +tarfile.TarFile.errors # errors is initialized for some reason as None even though it really only accepts str +tempfile._TemporaryFileWrapper.[\w_]+ # Dynamically specified by __getattr__, and thus don't exist on the class +threading.Condition.acquire # Condition functions are exported in __init__ +threading.Condition.release # Condition functions are exported in __init__ + +# A factory function that returns 'most efficient lock'. +# Marking it as a function will make it impossible for users to use the Lock type as an annotation. +threading.RLock + +tkinter.Misc.after # we intentionally don't allow everything that "works" at runtime + +# Methods that come from __getattr__() at runtime +tkinter.Tk.adderrorinfo +tkinter.Tk.call +tkinter.Tk.createcommand +tkinter.Tk.createtimerhandler +tkinter.Tk.dooneevent +tkinter.Tk.eval +tkinter.Tk.evalfile +tkinter.Tk.exprboolean +tkinter.Tk.exprdouble +tkinter.Tk.exprlong +tkinter.Tk.exprstring +tkinter.Tk.globalgetvar +tkinter.Tk.globalsetvar +tkinter.Tk.globalunsetvar +tkinter.Tk.interpaddr +tkinter.Tk.record +tkinter.Tk.splitlist +tkinter.Tk.unsetvar +tkinter.Tk.wantobjects +tkinter.Tk.willdispatch + +tkinter.Misc.grid_propagate # The noarg placeholder is a set value list +tkinter.Misc.pack_propagate # The noarg placeholder is a set value list +tkinter.Tk.report_callback_exception # A bit of a lie, since it's actually a method, but typing it as an attribute allows it to be assigned to +tkinter.Wm.wm_iconphoto # Default value of argument can't be used without runtime error +tkinter.font.Font.__getitem__ # Argument name differs (doesn't matter for __dunder__ methods) +traceback.TracebackException.from_exception # explicitly expanding arguments going into TracebackException __init__ +turtle.ScrolledCanvas.find_all # Dynamically created, has unnecessary *args +turtle.ScrolledCanvas.select_clear # Dynamically created, has unnecessary *args +turtle.ScrolledCanvas.select_item # Dynamically created, has unnecessary *args +# this is implemented with *args having a minimum size so arguments before it must be positional (but stubtest doesn't see that) +tkinter.ttk.Style.element_create + +types.GenericAlias.__call__ # Would be complicated to fix properly, Any could silence problems. #6392 +types.GenericAlias.__getattr__ + +typing.type_check_only # typing decorator that is not available at runtime + +# Details of runtime definition don't need to be in stubs +typing._Final +typing._Final.__init_subclass__ +typing(_extensions)?\._TypedDict +typing(_extensions)?\.Any.* +typing(_extensions)?\.TypedDict + +# Special primitives +typing(_extensions)?\.AbstractSet +typing(_extensions)?\.AsyncGenerator +typing(_extensions)?\.AsyncIterable +typing(_extensions)?\.AsyncIterator +typing(_extensions)?\.Awaitable +typing(_extensions)?\.Collection +typing(_extensions)?\.Container +typing(_extensions)?\.Coroutine +typing(_extensions)?\.Generator +typing(_extensions)?\.Hashable +typing(_extensions)?\.ItemsView +typing(_extensions)?\.Iterable +typing(_extensions)?\.Iterator +typing(_extensions)?\.KeysView +typing(_extensions)?\.Mapping +typing(_extensions)?\.MappingView +typing(_extensions)?\.MutableMapping +typing(_extensions)?\.MutableSequence +typing(_extensions)?\.MutableSet +typing(_extensions)?\.NamedTuple +typing(_extensions)?\.Reversible +typing(_extensions)?\.Sequence +typing(_extensions)?\.Sized +typing(_extensions)?\.ValuesView + +# Typing-related weirdness +typing._SpecialForm.__call__ +typing._SpecialForm.__init__ + +# These are abstract properties at runtime, +# but marking them as such in the stub breaks half the the typed-Python ecosystem (see #8726) +typing(_extensions)?\.IO\.closed +typing(_extensions)?\.IO\.mode +typing(_extensions)?\.IO\.name +typing(_extensions)?\.TextIO\.buffer +typing(_extensions)?\.TextIO\.encoding +typing(_extensions)?\.TextIO\.errors +typing(_extensions)?\.TextIO\.line_buffering +typing(_extensions)?\.TextIO\.newlines + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers; see https://github.com/python/mypy/issues/2220 +# See https://github.com/python/typeshed/commit/97bc450acd60c1bcdafef3ce8fbe3b95a9c0cac3 +typing(_extensions)?\.IO\.__iter__ +typing(_extensions)?\.IO\.__next__ + +types.MethodType.__closure__ # read-only but not actually a property; stubtest thinks it doesn't exist. +types.MethodType.__code__ # read-only but not actually a property; stubtest thinks it doesn't exist. +types.MethodType.__defaults__ # read-only but not actually a property; stubtest thinks it doesn't exist. +types.ModuleType.__dict__ # read-only but not actually a property; stubtest thinks it's a mutable attribute. +types.ModuleType.__getattr__ # this doesn't exist at runtime +unittest.runner._WritelnDecorator.flush # Methods that come from __getattr__() at runtime +unittest.runner._WritelnDecorator.write # Methods that come from __getattr__() at runtime +urllib.response.addbase.write # Methods that come from __getattr__() at runtime +urllib.response.addbase.writelines # Methods that come from __getattr__() at runtime + +(hashlib.__all__)? # scrypt depends on how OpenSSL was built. +(pydoc.Doc.getdocloc)? # Runtime default is an installation-specific stdlib path. + +_?weakref\.CallableProxyType\.__getattr__ # Should have all attributes of proxy +_?weakref\.(ref|ReferenceType)\.__init__ # C implementation has incorrect signature +_?weakref\.(ref|ReferenceType)\.__call__ # C function default annotation is wrong +_?weakref\.ProxyType\.__getattr__ # Should have all attributes of proxy +_?weakref\.ProxyType\.__reversed__ # Doesn't really exist +weakref.WeakValueDictionary.setdefault # has a default value for the "default" argument, but always errors out if no value is supplied for the parameter by the user + +webbrowser.UnixBrowser.remote_action # Always overridden in inheriting class +webbrowser.UnixBrowser.remote_action_newtab # Always overridden in inheriting class +webbrowser.UnixBrowser.remote_action_newwin # Always overridden in inheriting class +xml.__all__ # __all__-related weirdness (see #6523) +xml.dom # __all__-related weirdness (see #6523) +xml.etree # __all__-related weirdness (see #6523) +xml.parsers # __all__-related weirdness (see #6523) +xml.sax # __all__-related weirdness (see #6523) +xml.dom.minidom.StringTypes # Unnecessary re-export +xml.etree.ElementTree.XMLParser.__init__ # Defined in C so has general signature + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers; see https://github.com/python/mypy/issues/2220 +xml.etree.ElementTree.Element.__iter__ diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py310.txt b/stdlib/@tests/stubtest_allowlists/darwin-py310.txt new file mode 100644 index 000000000000..4d3b8964872e --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py310.txt @@ -0,0 +1,82 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.10.12 +# (Remove once 3.10.12 becomes available for GitHub Actions) +shutil.unpack_archive +tarfile.AbsoluteLinkError +tarfile.AbsolutePathError +tarfile.FilterError +tarfile.LinkOutsideDestinationError +tarfile.OutsideDestinationError +tarfile.SpecialFileError +tarfile.TarFile.extract +tarfile.TarFile.extractall +tarfile.TarInfo.replace +tarfile.data_filter +tarfile.fully_trusted_filter +tarfile.tar_filter + +# Incompatible changes introduced in Python 3.10.14 +# (Remove once 3.10.14 becomes available for GitHub Actions) +pyexpat.XMLParserType.GetReparseDeferralEnabled +pyexpat.XMLParserType.SetReparseDeferralEnabled +xml.etree.ElementTree.XMLParser.flush +xml.etree.ElementTree.XMLPullParser.flush +xml.sax.expatreader.ExpatParser.flush +zipfile.ZipInfo.__slots__ + +# Incompatible changes introduced in Python 3.10.15 +# (Remove once 3.10.15 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.10.17 +# (Remove once 3.10.17 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.10.18 +# (Remove once 3.10.18 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.10.19 +# (Remove once 3.10.19 becomes available for GitHub Actions) +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionActivationThreshold +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionMaximumAmplification + +# Incompatible changes introduced in Python 3.10.20 +# (Remove once 3.10.20 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Doesn't exist on macos: +_msi +msilib(.[a-z]+)? +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py311.txt b/stdlib/@tests/stubtest_allowlists/darwin-py311.txt new file mode 100644 index 000000000000..58ed2b6b27c7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py311.txt @@ -0,0 +1,75 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.11.10 +# (Remove once 3.11.10 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.11.12 +# (Remove once 3.11.12 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.11.13 +# (Remove once 3.11.13 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.11.14 +# (Remove once 3.11.14 becomes available for GitHub Actions) +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionActivationThreshold +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionMaximumAmplification + +# Incompatible changes introduced in Python 3.11.15 +# (Remove once 3.11.15 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============ +# 3.11 to 3.12 +# ============ + +# Not present on all MacOS versions +fcntl.F_OFD_GETLK +fcntl.F_OFD_SETLK +fcntl.F_OFD_SETLKW + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Doesn't exist on macos: +_msi +msilib(.[a-z]+)? +ossaudiodev +spwd + + +# ================ +# Unclear problems +# ================ + +# Added in 3.11.1, flagged by stubtest on Python < 3.14 for unknown reasons +errno.ENOTCAPABLE diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py312.txt b/stdlib/@tests/stubtest_allowlists/darwin-py312.txt new file mode 100644 index 000000000000..38f151441b3b --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py312.txt @@ -0,0 +1,62 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.12.11 +# (Remove once 3.12.11 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.12.12 +# (Remove once 3.12.12 becomes available for GitHub Actions) +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionActivationThreshold +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionMaximumAmplification + +# Incompatible changes introduced in Python 3.12.13 +# (Remove once 3.12.13 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============ +# 3.11 to 3.12 +# ============ + +# Not present on all MacOS versions +fcntl.F_OFD_GETLK +fcntl.F_OFD_SETLK +fcntl.F_OFD_SETLKW + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Doesn't exist on macos: +_msi +msilib(.[a-z]+)? +ossaudiodev +spwd + + +# ================ +# Unclear problems +# ================ + +# Added in 3.11.1, flagged by stubtest on Python < 3.14 for unknown reasons +errno.ENOTCAPABLE diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py313.txt b/stdlib/@tests/stubtest_allowlists/darwin-py313.txt new file mode 100644 index 000000000000..681f65781662 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py313.txt @@ -0,0 +1,15 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.13.13, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp + +# ======= +# >= 3.13 +# ======= + +(mmap.MAP_32BIT)? # Exists locally on MacOS but not on GitHub diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py314.txt b/stdlib/@tests/stubtest_allowlists/darwin-py314.txt new file mode 100644 index 000000000000..b651b2826e49 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py314.txt @@ -0,0 +1,23 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.14.4, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp + +# ========= +# 3.14 only +# ========= + +# Starting with Python 3.14.1, these methods accept None for some of their +# parameters, but would raise a TypeError with Python 3.14.0. +mmap.mmap.madvise + +# ======= +# >= 3.13 +# ======= + +(mmap.MAP_32BIT)? # Exists locally on MacOS but not on GitHub diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py315.txt b/stdlib/@tests/stubtest_allowlists/darwin-py315.txt new file mode 100644 index 000000000000..66aaf8d21845 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py315.txt @@ -0,0 +1,25 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# Depends on the ncurses version used to build Python. +(_curses.BUTTON5_CLICKED)? +(_curses.BUTTON5_DOUBLE_CLICKED)? +(_curses.BUTTON5_PRESSED)? +(_curses.BUTTON5_RELEASED)? +(_curses.BUTTON5_TRIPLE_CLICKED)? + +# Platform/build availability differs across Darwin builds. +(_socket.SO_BINDTODEVICE)? +(errno.ENOTCAPABLE)? + +# Depends on how readline was built. +readline.get_pre_input_hook + +# Internal implementation details of the sampling profiler. +profiling.sampling.live_collector +profiling.sampling.live_collector.collector +profiling.sampling.live_collector.constants +profiling.sampling.live_collector.display +profiling.sampling.live_collector.trend_tracker +profiling.sampling.live_collector.widgets diff --git a/stdlib/@tests/stubtest_allowlists/darwin.txt b/stdlib/@tests/stubtest_allowlists/darwin.txt new file mode 100644 index 000000000000..f1eb01ce62a5 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin.txt @@ -0,0 +1,53 @@ +# ============================================ +# TODO: Allowlist entries that should be fixed +# ============================================ + +(os|posix).sched_param # system dependent. Unclear if macos has it. + +# Sometimes these seem to exist on darwin, sometimes not +(_?curses.A_ITALIC)? # ncurses extension +(fcntl.F_GETLEASE)? # GNU extension +(fcntl.F_SETLEASE)? # GNU extension + + +# ========================================== +# Modules that do not exist on MacOS systems +# ========================================== + +_winapi +asyncio.windows_events +asyncio.windows_utils +encodings.oem +encodings.mbcs +msvcrt +nt +winreg +winsound + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +_gdbm # Only available if compiled with libgdbm + +_?curses.ACS_.* # ACS codes are initialized only after initscr call +curses.COLORS # Initialized after start_color +curses.COLOR_PAIRS # Initialized after start_color +curses.COLS # Initialized only after initscr call +curses.LINES # Initialized only after initscr call +multiprocessing.popen_spawn_win32 # exists on Darwin but fails to import +readline.append_history_file # Only available if compiled with GNU readline, not editline +select.poll # Actually a function; we have a class so it can be used as a type + +tkinter.Tk.createfilehandler # Methods that come from __getattr__() at runtime +tkinter.Tk.deletefilehandler # Methods that come from __getattr__() at runtime + +# These entries looks like a `setup-python` bug: +(dbm.gnu)? +(_?locale.bind_textdomain_codeset)? +(_?locale.bindtextdomain)? +(_?locale.dcgettext)? +(_?locale.dgettext)? +(_?locale.gettext)? +(_?locale.textdomain)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py310.txt b/stdlib/@tests/stubtest_allowlists/linux-py310.txt new file mode 100644 index 000000000000..a4083aa22ed7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py310.txt @@ -0,0 +1,10 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# doesn't exist on linux +_msi +msilib(.[a-z]+)? + +# doesn't exist in all installations +(nis)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py311.txt b/stdlib/@tests/stubtest_allowlists/linux-py311.txt new file mode 100644 index 000000000000..a4083aa22ed7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py311.txt @@ -0,0 +1,10 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# doesn't exist on linux +_msi +msilib(.[a-z]+)? + +# doesn't exist in all installations +(nis)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py312.txt b/stdlib/@tests/stubtest_allowlists/linux-py312.txt new file mode 100644 index 000000000000..a4083aa22ed7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py312.txt @@ -0,0 +1,10 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# doesn't exist on linux +_msi +msilib(.[a-z]+)? + +# doesn't exist in all installations +(nis)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py313.txt b/stdlib/@tests/stubtest_allowlists/linux-py313.txt new file mode 100644 index 000000000000..4fccdd15a0b5 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py313.txt @@ -0,0 +1,9 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.13.13, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp diff --git a/stdlib/@tests/stubtest_allowlists/linux-py314.txt b/stdlib/@tests/stubtest_allowlists/linux-py314.txt new file mode 100644 index 000000000000..cf414e9a9b3b --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py314.txt @@ -0,0 +1,17 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.14.4, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp + +# ========= +# 3.14 only +# ========= + +# Starting with Python 3.14.1, these methods accept None for some of their +# parameters, but would raise a TypeError with Python 3.14.0. +mmap.mmap.madvise diff --git a/stdlib/@tests/stubtest_allowlists/linux-py315.txt b/stdlib/@tests/stubtest_allowlists/linux-py315.txt new file mode 100644 index 000000000000..c2c4eb6ab13d --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py315.txt @@ -0,0 +1,19 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# GitHub Actions' Python 3.15 Linux build currently lacks _decimal, so +# decimal falls back to _pydecimal with different runtime signatures. +_decimal +decimal\..* + +# Depends on how readline was built. +readline.get_pre_input_hook + +# Internal implementation details of the sampling profiler. +profiling.sampling.live_collector +profiling.sampling.live_collector.collector +profiling.sampling.live_collector.constants +profiling.sampling.live_collector.display +profiling.sampling.live_collector.trend_tracker +profiling.sampling.live_collector.widgets diff --git a/stdlib/@tests/stubtest_allowlists/linux.txt b/stdlib/@tests/stubtest_allowlists/linux.txt new file mode 100644 index 000000000000..e2b09917706f --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux.txt @@ -0,0 +1,148 @@ +# ========================================== +# Modules that do not exist on Linux systems +# ========================================== + +_winapi +asyncio.windows_events +asyncio.windows_utils +encodings.oem +encodings.mbcs +msvcrt +nt +winreg +winsound + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +_?curses.ACS_.* # ACS codes are initialized only after initscr call +curses.COLORS # Initialized after start_color +curses.COLOR_PAIRS # Initialized after start_color +curses.COLS # Initialized only after initscr call +curses.LINES # Initialized only after initscr call +fcntl.I_[A-Z0-9_]+ # Platform differences that cannot be captured by the type system +(fcntl.F_DUPFD_QUERY)? # Depends on the glibc version Python was built against +multiprocessing.popen_spawn_win32 # exists on Linux but fails to import +select.poll # Actually a function; we have a class so it can be used as a type + +# Bluetooth constants which aren't on the GitHub Actions runners, see #15207 +(_?socket\.AF_BLUETOOTH)? +(_?socket\.BDADDR_ANY)? +(_?socket\.BDADDR_BREDR)? +(_?socket\.BDADDR_LE_PUBLIC)? +(_?socket\.BDADDR_LE_RANDOM)? +(_?socket\.BDADDR_LOCAL)? +(_?socket\.BT_CHANNEL_POLICY)? +(_?socket\.BT_CHANNEL_POLICY_BREDR_ONLY)? +(_?socket\.BT_CHANNEL_POLICY_BREDR_PREFERRED)? +(_?socket\.BT_CODEC)? +(_?socket\.BT_DEFER_SETUP)? +(_?socket\.BT_FLUSHABLE)? +(_?socket\.BT_FLUSHABLE_OFF)? +(_?socket\.BT_FLUSHABLE_ON)? +(_?socket\.BT_ISO_QOS)? +(_?socket\.BT_MODE)? +(_?socket\.BT_MODE_BASIC)? +(_?socket\.BT_MODE_ERTM)? +(_?socket\.BT_MODE_EXT_FLOWCTL)? +(_?socket\.BT_MODE_LE_FLOWCTL)? +(_?socket\.BT_MODE_STREAMING)? +(_?socket\.BT_PHY)? +(_?socket\.BT_PHY_BR_1M_1SLOT)? +(_?socket\.BT_PHY_BR_1M_3SLOT)? +(_?socket\.BT_PHY_BR_1M_5SLOT)? +(_?socket\.BT_PHY_EDR_2M_1SLOT)? +(_?socket\.BT_PHY_EDR_2M_3SLOT)? +(_?socket\.BT_PHY_EDR_2M_5SLOT)? +(_?socket\.BT_PHY_EDR_3M_1SLOT)? +(_?socket\.BT_PHY_EDR_3M_3SLOT)? +(_?socket\.BT_PHY_EDR_3M_5SLOT)? +(_?socket\.BT_PHY_LE_1M_RX)? +(_?socket\.BT_PHY_LE_1M_TX)? +(_?socket\.BT_PHY_LE_2M_RX)? +(_?socket\.BT_PHY_LE_2M_TX)? +(_?socket\.BT_PHY_LE_CODED_RX)? +(_?socket\.BT_PHY_LE_CODED_TX)? +(_?socket\.BT_PKT_STATUS)? +(_?socket\.BT_POWER)? +(_?socket\.BT_POWER_FORCE_ACTIVE_OFF)? +(_?socket\.BT_POWER_FORCE_ACTIVE_ON)? +(_?socket\.BT_RCVMTU)? +(_?socket\.BT_SECURITY)? +(_?socket\.BT_SECURITY_FIPS)? +(_?socket\.BT_SECURITY_HIGH)? +(_?socket\.BT_SECURITY_LOW)? +(_?socket\.BT_SECURITY_MEDIUM)? +(_?socket\.BT_SECURITY_SDP)? +(_?socket\.BT_SNDMTU)? +(_?socket\.BT_VOICE)? +(_?socket\.BT_VOICE_CVSD_16BIT)? +(_?socket\.BT_VOICE_TRANSPARENT)? +(_?socket\.BT_VOICE_TRANSPARENT_16BIT)? +(_?socket\.BTPROTO_HCI)? +(_?socket\.BTPROTO_L2CAP)? +(_?socket\.BTPROTO_RFCOMM)? +(_?socket\.BTPROTO_SCO)? +(_?socket\.HCI_CHANNEL_CONTROL)? +(_?socket\.HCI_CHANNEL_LOGGING)? +(_?socket\.HCI_CHANNEL_MONITOR)? +(_?socket\.HCI_CHANNEL_RAW)? +(_?socket\.HCI_CHANNEL_USER)? +(_?socket\.HCI_DEV_NONE)? +(_?socket\.HCI_DATA_DIR)? +(_?socket\.HCI_FILTER)? +(_?socket\.HCI_TIME_STAMP)? +(_?socket\.L2CAP_LM)? +(_?socket\.L2CAP_LM_AUTH)? +(_?socket\.L2CAP_LM_ENCRYPT)? +(_?socket\.L2CAP_LM_MASTER)? +(_?socket\.L2CAP_LM_RELIABLE)? +(_?socket\.L2CAP_LM_SECURE)? +(_?socket\.L2CAP_LM_TRUSTED)? +(_?socket\.SOL_BLUETOOTH)? +(_?socket\.SOL_L2CAP)? +(_?socket\.SOL_RFCOMM)? +(_?socket\.SOL_SCO)? + +# These seem like they should be available on Linux, but they're not +# on GitHub Actions runners for some reason. +_?socket.IPX_TYPE +_?socket.RDS_CANCEL_SENT_TO +_?socket.RDS_CMSG_RDMA_ARGS +_?socket.RDS_CMSG_RDMA_DEST +_?socket.RDS_CMSG_RDMA_MAP +_?socket.RDS_CMSG_RDMA_STATUS +_?socket.RDS_CONG_MONITOR +_?socket.RDS_FREE_MR +_?socket.RDS_GET_MR +_?socket.RDS_GET_MR_FOR_DEST +_?socket.RDS_RDMA_DONTWAIT +_?socket.RDS_RDMA_FENCE +_?socket.RDS_RDMA_INVALIDATE +_?socket.RDS_RDMA_NOTIFY_ME +_?socket.RDS_RDMA_READWRITE +_?socket.RDS_RDMA_SILENT +_?socket.RDS_RDMA_USE_ONCE +_?socket.RDS_RECVERR +_?socket.SOL_ATALK +_?socket.SOL_AX25 +_?socket.SOL_HCI +_?socket.SOL_IPX +_?socket.SOL_NETROM +_?socket.SOL_ROSE + +# This is available on Linux, but it's documented as for kernel debugging and +# not present on GitHub Actions runners. +termios.TIOCTTYGSTRUCT + +# Only defined when Python was built against glibc 2.42 or newer +(termios.B7200)? +(termios.B14400)? +(termios.B28800)? +(termios.B76800)? +(termios.IBSHIFT)? + +tkinter.Tk.createfilehandler # Methods that come from __getattr__() at runtime +tkinter.Tk.deletefilehandler # Methods that come from __getattr__() at runtime diff --git a/stdlib/@tests/stubtest_allowlists/py310.txt b/stdlib/@tests/stubtest_allowlists/py310.txt new file mode 100644 index 000000000000..2ff1c4c38385 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py310.txt @@ -0,0 +1,291 @@ +# ========================= +# New errors in Python 3.10 +# ========================= + +# ========= +# 3.10 only +# ========= + +# The "loop" argument exists at runtime, but raises TypeError if you try to provide any value for it +asyncio.locks.BoundedSemaphore.__init__ +asyncio.locks.Condition.__init__ +asyncio.locks.Event.__init__ +asyncio.locks.Lock.__init__ +asyncio.locks.Semaphore.__init__ +asyncio.queues.Queue.__init__ + +_random.Random.__init__ # Issues with __new__/__init__ correspondence + +bdb.Breakpoint.clearBreakpoints # Exists at runtime, but missing from stubs + +# Only exists for an error message. +typing_extensions.NewType.__mro_entries__ + + +# ============ +# 3.10 to 3.11 +# ============ + +importlib.metadata._meta.SimplePath.__truediv__ # Runtime definition of protocol is incorrect + + +# ======= +# <= 3.10 +# ======= + +builtins.float.__setformat__ # Internal method for CPython test suite +email.contentmanager.typ +gettext.install # codeset default value is ['unspecified'] so can't be specified +gettext.translation # codeset default value is ['unspecified'] so can't be specified +inspect.Signature.from_builtin # Removed in 3.11, can add if someone needs this +inspect.Signature.from_function # Removed in 3.11, can add if someone needs this + +# SpooledTemporaryFile implements IO except these methods before Python 3.11 +# See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918 +tempfile.SpooledTemporaryFile.__next__ +tempfile.SpooledTemporaryFile.readable +tempfile.SpooledTemporaryFile.seekable +tempfile.SpooledTemporaryFile.writable + +tkinter.Tk.split # Exists at runtime, but missing from stubs +typing._SpecialForm.__mro_entries__ # Exists at runtime, but missing from stubs + +typing_extensions.LiteralString + +# Will always raise. Not included to avoid type checkers inferring that +# Sentinel instances are callable. +typing_extensions.sentinel.__call__ + + +# ======= +# <= 3.11 +# ======= + +enum.Enum._generate_next_value_ +importlib.abc.Finder.find_module +urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified +xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub + + +# ======= +# <= 3.12 +# ======= + +# Exists at runtime, but missing from stubs +lib2to3.btm_utils +lib2to3.fixer_util +lib2to3.patcomp +lib2to3.pgen2.grammar.Grammar.loads +lib2to3.pygram.pattern_symbols +lib2to3.pygram.python_symbols +lib2to3.pytree.Base.__new__ +lib2to3.pytree.Base.children +lib2to3.pytree.Base.type +lib2to3.pytree.BasePattern.__new__ +lib2to3.pytree.BasePattern.type +lib2to3.pytree.NegatedPattern.match +lib2to3.pytree.NegatedPattern.match_seq +tkinter.tix.[A-Z_]+ +tkinter.tix.CObjView +tkinter.tix.DialogShell +tkinter.tix.ExFileSelectDialog +tkinter.tix.FileSelectDialog +tkinter.tix.FileTypeList +tkinter.tix.Grid +tkinter.tix.NoteBookFrame +tkinter.tix.OptionName +tkinter.tix.ResizeHandle +tkinter.tix.ScrolledGrid +tkinter.tix.ScrolledHList +tkinter.tix.ScrolledListBox +tkinter.tix.ScrolledTList +tkinter.tix.ScrolledText +tkinter.tix.ScrolledWindow +tkinter.tix.Shell +tkinter.tix.TclVersion +tkinter.tix.TkVersion + +# Details of runtime definition don't need to be in stubs +typing_extensions\.ParamSpec.* +typing_extensions\.TypeVar.* + +# These are typing._SpecialGenericAlias at runtime, which is not a real type, but it +# behaves like one in most cases +typing(_extensions)?\.(Async)?ContextManager + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +importlib.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.FileLoader.load_module +importlib.abc.FileLoader.load_module + + +# =============================================================== +# Allowlist entries that cannot or should not be fixed; 3.10 only +# =============================================================== + +importlib.abc.Traversable.joinpath # Problematic protocol signatures at runtime, see source code comments. + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.10 to 3.11 +# ================================================================== + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedList.reverse +importlib.metadata.DeprecatedList.sort + +# We pretend it's a read-only property for forward compatibility with 3.12 +typing.ParamSpec(Args|Kwargs).__origin__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.10 +# ============================================================= + +# Side effects from module initialization +_compat_pickle.excname +email.contentmanager.maintype +email.contentmanager.subtype +inspect.k +inspect.mod_dict +inspect.v +json.encoder.i +lib2to3.pgen2.grammar.line +lib2to3.pgen2.grammar.name +lib2to3.pgen2.grammar.op + +pstats.SortKey.__new__ # Derives from (str, Enum) +pydoc.Helper.symbol # Loop variable in class https://github.com/python/typeshed/issues/6401#issuecomment-981178522 +pydoc.Helper.symbols_ # Loop variable in class https://github.com/python/typeshed/issues/6401#issuecomment-981178522 +pydoc.Helper.topic # Loop variable in class https://github.com/python/typeshed/issues/6401#issuecomment-981178522 +sqlite3.test # Modules that exist at runtime, but shouldn't be added to typeshed +sqlite3\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +tkinter.EventType.__new__ # Derives from (str, Enum) +types.CodeType.replace # stubtest thinks default values are None but None doesn't work at runtime + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.11 +# ============================================================= + +.*.__buffer__ # We lie about the existence of these methods +.*.__release_buffer__ # We lie about the existence of these methods +asynchat.async_chat.encoding # Removed in 3.12 +asynchat.async_chat.use_encoding # Removed in 3.12 +asynchat.find_prefix_at_end # Removed in 3.12 +asyncore.dispatcher.addr # Removed in 3.12 +asyncore.dispatcher.handle_accepted # Removed in 3.12 +ctypes.test # Modules that exist at runtime, but shouldn't be added to typeshed +ctypes\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +distutils\..* # Removed in 3.12 +lib2to3.tests # Modules that exist at runtime, but shouldn't be added to typeshed +lib2to3\.tests\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +pkgutil.ImpImporter\..* # Removed in 3.12 +pkgutil.ImpLoader\..* # Removed in 3.12 +platform.platform # runtime default is 0, we pretend it's a bool +poplib.POP3_SSL.stls # bad declaration of inherited function. See poplib.pyi +tkinter.test # Modules that exist at runtime, but shouldn't be added to typeshed +tkinter\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + +# We call them read-only properties, runtime implementation is slightly different +typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__ + +unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed +unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Undocumented implementation details +cgi.FieldStorage.bufsize +cgi.FieldStorage.read_binary +cgi.FieldStorage.read_lines +cgi.FieldStorage.read_lines_to_eof +cgi.FieldStorage.read_lines_to_outerboundary +cgi.FieldStorage.read_multi +cgi.FieldStorage.read_single +cgi.FieldStorage.read_urlencoded +cgi.FieldStorage.skip_lines + +ctypes._endian.DEFAULT_MODE # Incorrectly star import. +ctypes._endian.RTLD_GLOBAL # Incorrectly star import. +ctypes._endian.RTLD_LOCAL # Incorrectly star import. + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.DictProxy.__iter__ +multiprocessing.managers.DictProxy.__len__ +multiprocessing.managers.DictProxy.copy +multiprocessing.managers.DictProxy.items +multiprocessing.managers.DictProxy.keys +multiprocessing.managers.DictProxy.values + +# Runtime signature is incorrect (https://github.com/python/cpython/issues/93021) +multiprocessing.managers.DictProxy.clear +multiprocessing.managers.DictProxy.popitem + +# Undocumented implementation details +pipes.Template.makepipeline +pipes.Template.open_r +pipes.Template.open_w +sunau.Au_read.initfp +sunau.Au_write.initfp + +threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints +types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature +typing_extensions\.Annotated # Undocumented implementation details +typing\.Annotated # Super-special typing primitive + +# These methods have no default implementation for Python < 3.13. +_pickle.Pickler.persistent_id +_pickle.Unpickler.persistent_load diff --git a/stdlib/@tests/stubtest_allowlists/py311.txt b/stdlib/@tests/stubtest_allowlists/py311.txt new file mode 100644 index 000000000000..f11779d324f1 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py311.txt @@ -0,0 +1,272 @@ +# ========================= +# New errors in Python 3.11 +# ========================= + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ========= +# 3.11 only +# ========= + +# Not strictly speaking a staticmethod on 3.11, but it acts like one: +enum.StrEnum._generate_next_value_ + + +# ==================================== +# Pre-existing errors from Python 3.10 +# ==================================== + + +# ============ +# 3.10 to 3.11 +# ============ + +importlib.metadata._meta.SimplePath.__truediv__ # Runtime definition of protocol is incorrect + + +# ======= +# <= 3.11 +# ======= + +enum.Enum._generate_next_value_ +importlib.abc.Finder.find_module +urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified +xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub + + +# ======= +# <= 3.12 +# ======= + +# Exists at runtime, but missing from stubs +lib2to3.btm_utils +lib2to3.fixer_util +lib2to3.patcomp +lib2to3.pgen2.grammar.Grammar.loads +lib2to3.pygram.pattern_symbols +lib2to3.pygram.python_symbols +lib2to3.pytree.Base.__new__ +lib2to3.pytree.Base.children +lib2to3.pytree.Base.type +lib2to3.pytree.BasePattern.__new__ +lib2to3.pytree.BasePattern.type +lib2to3.pytree.NegatedPattern.match +lib2to3.pytree.NegatedPattern.match_seq +tkinter.tix.[A-Z_]+ +tkinter.tix.CObjView +tkinter.tix.DialogShell +tkinter.tix.ExFileSelectDialog +tkinter.tix.FileSelectDialog +tkinter.tix.FileTypeList +tkinter.tix.Grid +tkinter.tix.NoteBookFrame +tkinter.tix.OptionName +tkinter.tix.ResizeHandle +tkinter.tix.ScrolledGrid +tkinter.tix.ScrolledHList +tkinter.tix.ScrolledListBox +tkinter.tix.ScrolledTList +tkinter.tix.ScrolledText +tkinter.tix.ScrolledWindow +tkinter.tix.Shell +tkinter.tix.TclVersion +tkinter.tix.TkVersion + +# Details of runtime definition don't need to be in stubs +typing_extensions\.ParamSpec.* +typing_extensions\.TypeVar.* + +# These are typing._SpecialGenericAlias at runtime, which is not a real type, but it +# behaves like one in most cases +typing(_extensions)?\.(Async)?ContextManager + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ============ +# 3.11 to 3.13 +# ============ + +enum.Enum.__init__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.FileLoader.load_module +importlib.abc.FileLoader.load_module + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive + + +# =============================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 only +# =============================================================== + +# We pretend it's a read-only property for forward compatibility with 3.12 +typing\.TypeVar\.__.*__ +typing\.ParamSpec\.__.*__ + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.12 +# ================================================================== + +configparser.LegacyInterpolation.__init__ # runtime is *args, **kwargs, but it's just a passthrough + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.10 to 3.11 +# ================================================================== + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedList.reverse +importlib.metadata.DeprecatedList.sort + +# We pretend it's a read-only property for forward compatibility with 3.12 +typing.ParamSpec(Args|Kwargs).__origin__ + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13 +# ================================================================== + +argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.11 +# ============================================================= + +.*.__buffer__ # We lie about the existence of these methods +.*.__release_buffer__ # We lie about the existence of these methods +asynchat.async_chat.encoding # Removed in 3.12 +asynchat.async_chat.use_encoding # Removed in 3.12 +asynchat.find_prefix_at_end # Removed in 3.12 +asyncore.dispatcher.addr # Removed in 3.12 +asyncore.dispatcher.handle_accepted # Removed in 3.12 +ctypes.test # Modules that exist at runtime, but shouldn't be added to typeshed +ctypes\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +distutils\..* # Removed in 3.12 +lib2to3.tests # Modules that exist at runtime, but shouldn't be added to typeshed +lib2to3\.tests\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +pkgutil.ImpImporter\..* # Removed in 3.12 +pkgutil.ImpLoader\..* # Removed in 3.12 +platform.platform # runtime default is 0, we pretend it's a bool +poplib.POP3_SSL.stls # bad declaration of inherited function. See poplib.pyi +tkinter.test # Modules that exist at runtime, but shouldn't be added to typeshed +tkinter\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + +# We call them read-only properties, runtime implementation is slightly different +typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__ + +unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed +unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Undocumented implementation details +cgi.FieldStorage.bufsize +cgi.FieldStorage.read_binary +cgi.FieldStorage.read_lines +cgi.FieldStorage.read_lines_to_eof +cgi.FieldStorage.read_lines_to_outerboundary +cgi.FieldStorage.read_multi +cgi.FieldStorage.read_single +cgi.FieldStorage.read_urlencoded +cgi.FieldStorage.skip_lines + +ctypes._endian.DEFAULT_MODE # Incorrectly star import. +ctypes._endian.RTLD_GLOBAL # Incorrectly star import. +ctypes._endian.RTLD_LOCAL # Incorrectly star import. + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.DictProxy.__iter__ +multiprocessing.managers.DictProxy.__len__ +multiprocessing.managers.DictProxy.copy +multiprocessing.managers.DictProxy.items +multiprocessing.managers.DictProxy.keys +multiprocessing.managers.DictProxy.values + +# Runtime signature is incorrect (https://github.com/python/cpython/issues/93021) +multiprocessing.managers.DictProxy.clear +multiprocessing.managers.DictProxy.popitem + +# Undocumented implementation details +pipes.Template.makepipeline +pipes.Template.open_r +pipes.Template.open_w +sunau.Au_read.initfp +sunau.Au_write.initfp + +threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints +types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature +typing_extensions\.Annotated # Undocumented implementation details +typing\.Annotated # Super-special typing primitive + +# These methods have no default implementation for Python < 3.13. +_pickle.Pickler.persistent_id +_pickle.Unpickler.persistent_load diff --git a/stdlib/@tests/stubtest_allowlists/py312.txt b/stdlib/@tests/stubtest_allowlists/py312.txt new file mode 100644 index 000000000000..92c3ed2db44b --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py312.txt @@ -0,0 +1,252 @@ +# ========================= +# New errors in Python 3.12 +# ========================= + +# ======= +# >= 3.12 +# ======= + +# Types that require `__setattr__` and `__delattr__` for typing purposes: +types.SimpleNamespace.__setattr__ +types.SimpleNamespace.__delattr__ + + +# ============ +# 3.12 to 3.13 +# ============ + +# Initialized at runtime +typing_extensions.TypeAliasType.__parameters__ +typing_extensions.TypeAliasType.__value__ + + +# ==================================== +# Pre-existing errors from Python 3.11 +# ==================================== + + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ============ +# 3.11 to 3.13 +# ============ + +enum.Enum.__init__ + + +# ======= +# <= 3.12 +# ======= + +# Exists at runtime, but missing from stubs +lib2to3.btm_utils +lib2to3.fixer_util +lib2to3.patcomp +lib2to3.pgen2.grammar.Grammar.loads +lib2to3.pygram.pattern_symbols +lib2to3.pygram.python_symbols +lib2to3.pytree.Base.__new__ +lib2to3.pytree.Base.children +lib2to3.pytree.Base.type +lib2to3.pytree.BasePattern.__new__ +lib2to3.pytree.BasePattern.type +lib2to3.pytree.NegatedPattern.match +lib2to3.pytree.NegatedPattern.match_seq +tkinter.tix.[A-Z_]+ +tkinter.tix.CObjView +tkinter.tix.DialogShell +tkinter.tix.ExFileSelectDialog +tkinter.tix.FileSelectDialog +tkinter.tix.FileTypeList +tkinter.tix.Grid +tkinter.tix.NoteBookFrame +tkinter.tix.OptionName +tkinter.tix.ResizeHandle +tkinter.tix.ScrolledGrid +tkinter.tix.ScrolledHList +tkinter.tix.ScrolledListBox +tkinter.tix.ScrolledTList +tkinter.tix.ScrolledText +tkinter.tix.ScrolledWindow +tkinter.tix.Shell +tkinter.tix.TclVersion +tkinter.tix.TkVersion + +# Details of runtime definition don't need to be in stubs +typing_extensions\.ParamSpec.* +typing_extensions\.TypeVar.* + +# These are typing._SpecialGenericAlias at runtime, which is not a real type, but it +# behaves like one in most cases +typing(_extensions)?\.(Async)?ContextManager + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.FileLoader.load_module +importlib.abc.FileLoader.load_module + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.type_param.__init__ + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedNonAbstract.__new__ + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.last_exc # not always defined + +# These only exist to give a better error message if you try to subclass an instance +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP-695 syntax in CPython +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13 +# ================================================================== + +argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super + + +# =============================================================== +# Allowlist entries that cannot or should not be fixed; 3.12 only +# =============================================================== + +concurrent.futures.__all__ # Incompatible changes introduced in Python 3.12.5 +ctypes._endian.SIZEOF_TIME_T # Incorrectly star import. + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.12 +# ================================================================== + +configparser.LegacyInterpolation.__init__ # runtime is *args, **kwargs, but it's just a passthrough + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Undocumented implementation details +cgi.FieldStorage.bufsize +cgi.FieldStorage.read_binary +cgi.FieldStorage.read_lines +cgi.FieldStorage.read_lines_to_eof +cgi.FieldStorage.read_lines_to_outerboundary +cgi.FieldStorage.read_multi +cgi.FieldStorage.read_single +cgi.FieldStorage.read_urlencoded +cgi.FieldStorage.skip_lines + +ctypes._endian.DEFAULT_MODE # Incorrectly star import. +ctypes._endian.RTLD_GLOBAL # Incorrectly star import. +ctypes._endian.RTLD_LOCAL # Incorrectly star import. + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.DictProxy.__iter__ +multiprocessing.managers.DictProxy.__len__ +multiprocessing.managers.DictProxy.copy +multiprocessing.managers.DictProxy.items +multiprocessing.managers.DictProxy.keys +multiprocessing.managers.DictProxy.values + +# Runtime signature is incorrect (https://github.com/python/cpython/issues/93021) +multiprocessing.managers.DictProxy.clear +multiprocessing.managers.DictProxy.popitem + +# Undocumented implementation details +pipes.Template.makepipeline +pipes.Template.open_r +pipes.Template.open_w +sunau.Au_read.initfp +sunau.Au_write.initfp + +threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints +types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature +typing_extensions\.Annotated # Undocumented implementation details +typing\.Annotated # Super-special typing primitive + +# These methods have no default implementation for Python < 3.13. +_pickle.Pickler.persistent_id +_pickle.Unpickler.persistent_load diff --git a/stdlib/@tests/stubtest_allowlists/py313.txt b/stdlib/@tests/stubtest_allowlists/py313.txt new file mode 100644 index 000000000000..f36328af3ef1 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py313.txt @@ -0,0 +1,180 @@ +# ========================= +# New errors in Python 3.13 +# ========================= +# No way to express keyword-only ParamSpec +copy.replace +# ==================================== +# Pre-existing errors from Python 3.12 +# ==================================== + + +# ======= +# >= 3.12 +# ======= + +# Types that require `__setattr__` and `__delattr__` for typing purposes: +types.SimpleNamespace.__setattr__ +types.SimpleNamespace.__delattr__ + + +# ============ +# 3.12 to 3.13 +# ============ + +# Initialized at runtime +typing_extensions.TypeAliasType.__parameters__ +typing_extensions.TypeAliasType.__value__ + + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ============ +# 3.11 to 3.13 +# ============ + +enum.Enum.__init__ + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + +# TypeVarTuple is a wrapper class that returns typing.TypeVarTuple instances. +# Keep __new__ checked because it is the wrapper's public constructor. +typing_extensions\.TypeVarTuple +typing_extensions\.TypeVarTuple\.(?!__new__).* + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.FileLoader.load_module +importlib.abc.FileLoader.load_module + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.13 +# ============================================================= + +# `cleanup_socket` was added in 3.13 to the concrete `_UnixSelectorEventLoop.create_unix_server`, +# not to the abstract `AbstractEventLoop.create_unix_server`. The stub adds it on the abstract +# method so code typing the loop as `AbstractEventLoop` can still pass `cleanup_socket=...`. See #15742. +asyncio.events.AbstractEventLoop.create_unix_server + +_pyrepl\..+ # The internal implementation of the REPL on py313+; not for public consumption +codecs.backslashreplace_errors # Runtime incorrectly has `self` +codecs.ignore_errors # Runtime incorrectly has `self` +codecs.namereplace_errors # Runtime incorrectly has `self` +codecs.replace_errors # Runtime incorrectly has `self` +codecs.strict_errors # Runtime incorrectly has `self` +codecs.xmlcharrefreplace_errors # Runtime incorrectly has `self` + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers._BaseDictProxy.__iter__ +multiprocessing.managers._BaseDictProxy.__len__ +multiprocessing.managers._BaseDictProxy.clear +multiprocessing.managers._BaseDictProxy.copy +multiprocessing.managers._BaseDictProxy.items +multiprocessing.managers._BaseDictProxy.keys +multiprocessing.managers._BaseDictProxy.popitem +multiprocessing.managers._BaseDictProxy.values + +# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior +types.MappingProxyType.get + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.type_param.__init__ + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedNonAbstract.__new__ + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.last_exc # not always defined + +# These only exist to give a better error message if you try to subclass an instance +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP-695 syntax in CPython +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive + +# Don't always exist at runtime +(pdb.Pdb.curframe_locals)? + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13 +# ================================================================== + +argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super diff --git a/stdlib/@tests/stubtest_allowlists/py314.txt b/stdlib/@tests/stubtest_allowlists/py314.txt new file mode 100644 index 000000000000..8f6c3a4a52a3 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py314.txt @@ -0,0 +1,202 @@ +# ========================= +# New errors in Python 3.14 +# ========================= + +# Union and UnionType are aliases in 3.14 but type checkers need some changes +typing.Union +types.UnionType.__class_getitem__ +types.UnionType.__mro_entries__ +types.UnionType.__name__ +types.UnionType.__qualname__ + +# Assigning `__new__` causes `func` not to get recognized. +functools.partialmethod.__new__ + +# Decorator approximated by classmethod +concurrent.interpreters._crossinterp.classonly.* +# Method using this decorator +concurrent.interpreters._crossinterp.UnboundItem.singleton + +# object() sentinels at runtime represented by NewTypes in the stubs +concurrent.interpreters._crossinterp.UNBOUND_ERROR +concurrent.interpreters._crossinterp.UNBOUND_REMOVE + +# Condition functions are exported in __init__ +threading.Condition.locked + +# ==================================== +# Pre-existing errors from Python 3.13 +# ==================================== + +# No way to express keyword-only ParamSpec +copy.replace + +# ======= +# >= 3.12 +# ======= + +# Types that require `__setattr__` and `__delattr__` for typing purposes: +types.SimpleNamespace.__setattr__ +types.SimpleNamespace.__delattr__ + + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + +# TypeVarTuple is a wrapper class that returns typing.TypeVarTuple instances. +# Keep __new__ checked because it is the wrapper's public constructor. +typing_extensions\.TypeVarTuple +typing_extensions\.TypeVarTuple\.(?!__new__).* + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.FileLoader.load_module +importlib.abc.FileLoader.load_module + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.14 +# ============================================================= + +# Undocumented private attributes +.*\.ForwardRef\.__arg__ +.*\.ForwardRef\.__ast_node__ +.*\.ForwardRef\.__cell__ +.*\.ForwardRef\.__code__ +.*\.ForwardRef\.__extra_names__ +.*\.ForwardRef\.__globals__ +.*\.ForwardRef\.__init_subclass__ +.*\.ForwardRef\.__owner__ +.*\.ForwardRef\.__stringifier_dict__ + +# These protocols use ABC hackery at runtime. +(io|typing_extensions)\.Reader\.__class_getitem__ +(io|typing_extensions)\.Reader\.read +(io|typing_extensions)\.Writer\.__class_getitem__ +(io|typing_extensions)\.Writer\.write + + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers._BaseSetProxy.__iter__ +multiprocessing.managers._BaseSetProxy.__len__ +multiprocessing.managers._BaseSetProxy.clear +multiprocessing.managers._BaseSetProxy.copy +multiprocessing.managers._BaseSetProxy.pop +multiprocessing.managers.BaseListProxy.clear +multiprocessing.managers.BaseListProxy.copy +multiprocessing.managers._BaseDictProxy.__reversed__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.13 +# ============================================================= + +# `cleanup_socket` was added in 3.13 to the concrete `_UnixSelectorEventLoop.create_unix_server`, +# not to the abstract `AbstractEventLoop.create_unix_server`. The stub adds it on the abstract +# method so code typing the loop as `AbstractEventLoop` can still pass `cleanup_socket=...`. See #15742. +asyncio.events.AbstractEventLoop.create_unix_server + +_pyrepl\..+ # The internal implementation of the REPL on py313+; not for public consumption +codecs.backslashreplace_errors # Runtime incorrectly has `self` +codecs.ignore_errors # Runtime incorrectly has `self` +codecs.namereplace_errors # Runtime incorrectly has `self` +codecs.replace_errors # Runtime incorrectly has `self` +codecs.strict_errors # Runtime incorrectly has `self` +codecs.xmlcharrefreplace_errors # Runtime incorrectly has `self` + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers._BaseDictProxy.__iter__ +multiprocessing.managers._BaseDictProxy.__len__ +multiprocessing.managers._BaseDictProxy.clear +multiprocessing.managers._BaseDictProxy.copy +multiprocessing.managers._BaseDictProxy.items +multiprocessing.managers._BaseDictProxy.keys +multiprocessing.managers._BaseDictProxy.popitem +multiprocessing.managers._BaseDictProxy.values + +# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior +types.MappingProxyType.get + + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.type_param.__init__ + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedNonAbstract.__new__ + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.__jit # Similar to sys._monitoring +sys.last_exc # not always defined + +# These only exist to give a better error message if you try to subclass an instance +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP-695 syntax in CPython +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive diff --git a/stdlib/@tests/stubtest_allowlists/py315.txt b/stdlib/@tests/stubtest_allowlists/py315.txt new file mode 100644 index 000000000000..f684f7e9d2c6 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py315.txt @@ -0,0 +1,168 @@ +# ============================================ +# TODO: Allowlist entries that should be fixed +# ============================================ + +dataclasses.MISSING +dataclasses._MISSING_TYPE + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# runtime default is a list object used as a sentinel +base64.b64decode + +# Internal implementation details of the sampling profiler. +profiling.sampling.binary_collector +profiling.sampling.binary_reader +profiling.sampling.cli +profiling.sampling.constants +profiling.sampling.dump +profiling.sampling.errors +profiling.sampling.heatmap_collector.FileStats +profiling.sampling.heatmap_collector.TreeNode +profiling.sampling.module_utils +profiling.sampling.opcode_utils +profiling.sampling.sample + +# These aliases are just like the aliases named "slaves" instead of "content". +# See common.txt. +tkinter.Grid.content +tkinter.Grid.grid_content +tkinter.Pack.content +tkinter.Pack.pack_content +tkinter.Place.content +tkinter.Place.place_content + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.14 +# ============================================================= + +# Undocumented private attributes +.*\.ForwardRef\.__arg__ +.*\.ForwardRef\.__ast_node__ +.*\.ForwardRef\.__cell__ +.*\.ForwardRef\.__code__ +.*\.ForwardRef\.__extra_names__ +.*\.ForwardRef\.__globals__ +.*\.ForwardRef\.__init_subclass__ +.*\.ForwardRef\.__owner__ +.*\.ForwardRef\.__stringifier_dict__ + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858). +_?ast.type_param.__init__ + +# Decorator approximated by classmethod +concurrent.interpreters._crossinterp.classonly.* +# Method using this decorator +concurrent.interpreters._crossinterp.UnboundItem.singleton + +# object() sentinels at runtime represented by NewTypes in the stubs +concurrent.interpreters._crossinterp.UNBOUND_ERROR +concurrent.interpreters._crossinterp.UNBOUND_REMOVE + +# Condition functions are exported in __init__ +threading.Condition.locked + +# Assigning `__new__` causes `func` not to get recognized. +functools.partialmethod.__new__ + +# These protocols use ABC hackery at runtime. +(io|typing_extensions)\.Reader\.__class_getitem__ +(io|typing_extensions)\.Reader\.read +(io|typing_extensions)\.Writer\.__class_getitem__ +(io|typing_extensions)\.Writer\.write + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# but have more precise (accurate) signatures in the stub. +multiprocessing.managers.BaseListProxy.clear +multiprocessing.managers.BaseListProxy.copy +multiprocessing.managers._BaseDictProxy.__reversed__ +multiprocessing.managers._BaseSetProxy.__iter__ +multiprocessing.managers._BaseSetProxy.__len__ +multiprocessing.managers._BaseSetProxy.clear +multiprocessing.managers._BaseSetProxy.copy +multiprocessing.managers._BaseSetProxy.pop + +# Union and UnionType are aliases in 3.14 but type checkers need some changes. +typing.Union +types.UnionType.__class_getitem__ +types.UnionType.__mro_entries__ +types.UnionType.__name__ +types.UnionType.__qualname__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.13 +# ============================================================= + +# `cleanup_socket` was added in 3.13 to the concrete `_UnixSelectorEventLoop.create_unix_server`, +# not to the abstract `AbstractEventLoop.create_unix_server`. The stub adds it on the abstract +# method so code typing the loop as `AbstractEventLoop` can still pass `cleanup_socket=...`. See #15742. +asyncio.events.AbstractEventLoop.create_unix_server + +_pyrepl\..+ # The internal implementation of the REPL on py313+; not for public consumption +codecs.backslashreplace_errors # Runtime incorrectly has `self` +codecs.ignore_errors # Runtime incorrectly has `self` +codecs.namereplace_errors # Runtime incorrectly has `self` +codecs.replace_errors # Runtime incorrectly has `self` +codecs.strict_errors # Runtime incorrectly has `self` +codecs.xmlcharrefreplace_errors # Runtime incorrectly has `self` + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# but have more precise (accurate) signatures in the stub. +multiprocessing.managers._BaseDictProxy.__iter__ +multiprocessing.managers._BaseDictProxy.__len__ +multiprocessing.managers._BaseDictProxy.clear +multiprocessing.managers._BaseDictProxy.copy +multiprocessing.managers._BaseDictProxy.items +multiprocessing.managers._BaseDictProxy.keys +multiprocessing.managers._BaseDictProxy.popitem +multiprocessing.managers._BaseDictProxy.values + +# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior. +types.MappingProxyType.get + + +copy.replace # Cannot have keyword-only ParamSpec + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.__jit # Similar to sys._monitoring +sys.last_exc # Not always defined. + +# Types that require `__setattr__` and `__delattr__` for typing purposes. +types.SimpleNamespace.__delattr__ +types.SimpleNamespace.__setattr__ + +# These only exist to give a better error message if you try to subclass an instance. +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP 695 syntax in CPython. +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # Mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing.LiteralString # Super-special typing primitive +typing.NewType.__mro_entries__ # Only exists for an error message. +typing._SpecialForm.__mro_entries__ # Super-special typing primitive diff --git a/stdlib/@tests/stubtest_allowlists/win32-py310.txt b/stdlib/@tests/stubtest_allowlists/win32-py310.txt new file mode 100644 index 000000000000..5ef3b597fc63 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py310.txt @@ -0,0 +1,82 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.10.12 +# (Remove once 3.10.12 becomes available for GitHub Actions) +shutil.unpack_archive +tarfile.AbsoluteLinkError +tarfile.AbsolutePathError +tarfile.FilterError +tarfile.LinkOutsideDestinationError +tarfile.OutsideDestinationError +tarfile.SpecialFileError +tarfile.TarFile.extract +tarfile.TarFile.extractall +tarfile.TarInfo.replace +tarfile.data_filter +tarfile.fully_trusted_filter +tarfile.tar_filter + +# Incompatible changes introduced in Python 3.10.14 +# (Remove once 3.10.14 becomes available for GitHub Actions) +pyexpat.XMLParserType.GetReparseDeferralEnabled +pyexpat.XMLParserType.SetReparseDeferralEnabled +xml.etree.ElementTree.XMLParser.flush +xml.etree.ElementTree.XMLPullParser.flush +xml.sax.expatreader.ExpatParser.flush +zipfile.ZipInfo.__slots__ + +# Incompatible changes introduced in Python 3.10.15 +# (Remove once 3.10.15 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.10.17 +# (Remove once 3.10.17 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.10.18 +# (Remove once 3.10.18 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.10.19 +# (Remove once 3.10.19 becomes available for GitHub Actions) +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionActivationThreshold +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionMaximumAmplification + +# Incompatible changes introduced in Python 3.10.20 +# (Remove once 3.10.20 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Modules that don't exist on Windows +crypt +nis +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/win32-py311.txt b/stdlib/@tests/stubtest_allowlists/win32-py311.txt new file mode 100644 index 000000000000..38c8daf436c6 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py311.txt @@ -0,0 +1,57 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.11.10 +# (Remove once 3.11.10 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.11.12 +# (Remove once 3.11.12 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.11.13 +# (Remove once 3.11.13 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.11.14 +# (Remove once 3.11.14 becomes available for GitHub Actions) +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionActivationThreshold +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionMaximumAmplification + +# Incompatible changes introduced in Python 3.11.15 +# (Remove once 3.11.15 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Modules that don't exist on Windows +crypt +nis +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/win32-py312.txt b/stdlib/@tests/stubtest_allowlists/win32-py312.txt new file mode 100644 index 000000000000..c22d4e4cf3cf --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py312.txt @@ -0,0 +1,61 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.12.11 +# (Remove once 3.12.11 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.12.12 +# (Remove once 3.12.12 becomes available for GitHub Actions) +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionActivationThreshold +pyexpat.XMLParserType.SetBillionLaughsAttackProtectionMaximumAmplification + +# Incompatible changes introduced in Python 3.12.13 +# (Remove once 3.12.13 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ======= +# >= 3.12 +# ======= + +# Undocumented internal method, not really for public consumption. +# (Hard to add types for unless we add stubs for the undocumented _overlapped module...) +asyncio.windows_events.IocpProactor.finish_socket_func + + +# ========= +# 3.12 only +# ========= + +_winapi.GetLongPathName +_winapi.GetShortPathName + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Modules that don't exist on Windows +crypt +nis +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/win32-py313.txt b/stdlib/@tests/stubtest_allowlists/win32-py313.txt new file mode 100644 index 000000000000..7fba48d7067a --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py313.txt @@ -0,0 +1,7 @@ +# ======= +# >= 3.12 +# ======= + +# Undocumented internal method, not really for public consumption. +# (Hard to add types for unless we add stubs for the undocumented _overlapped module...) +asyncio.windows_events.IocpProactor.finish_socket_func diff --git a/stdlib/@tests/stubtest_allowlists/win32-py314.txt b/stdlib/@tests/stubtest_allowlists/win32-py314.txt new file mode 100644 index 000000000000..7fba48d7067a --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py314.txt @@ -0,0 +1,7 @@ +# ======= +# >= 3.12 +# ======= + +# Undocumented internal method, not really for public consumption. +# (Hard to add types for unless we add stubs for the undocumented _overlapped module...) +asyncio.windows_events.IocpProactor.finish_socket_func diff --git a/stdlib/@tests/stubtest_allowlists/win32-py315.txt b/stdlib/@tests/stubtest_allowlists/win32-py315.txt new file mode 100644 index 000000000000..a3e4da3f7873 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py315.txt @@ -0,0 +1,11 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# Depends on whether the C _decimal extension or pure-Python fallback is used. +(_decimal.SPEC_VERSION)? +(decimal.SPEC_VERSION)? + +# Undocumented internal method, not really for public consumption. +# Hard to add types for unless we add stubs for the undocumented _overlapped module. +asyncio.windows_events.IocpProactor.finish_socket_func diff --git a/stdlib/@tests/stubtest_allowlists/win32.txt b/stdlib/@tests/stubtest_allowlists/win32.txt new file mode 100644 index 000000000000..b56fe5a2042e --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32.txt @@ -0,0 +1,41 @@ +# ============================================ +# Modules that do not exist on Windows systems +# ============================================ + +_curses +_dbm +_gdbm +_posixsubprocess +asyncio.unix_events +dbm.gnu +dbm.ndbm +fcntl +grp +posix +pwd +readline +resource +syslog +termios +xxlimited + +# Modules that rely on _curses +_curses_panel +curses +curses.ascii +curses.has_key +curses.panel +curses.textpad + +# Modules that rely on termios +pty +tty + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +multiprocessing.popen_fork # exists on Windows but fails to import +multiprocessing.popen_forkserver # exists on Windows but fails to import +multiprocessing.popen_spawn_posix # exists on Windows but fails to import diff --git a/stdlib/@tests/test_cases/asyncio/check_coroutines.py b/stdlib/@tests/test_cases/asyncio/check_coroutines.py new file mode 100644 index 000000000000..6062ca55146a --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_coroutines.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import sys +from asyncio import iscoroutinefunction +from collections.abc import Awaitable, Callable, Coroutine +from typing import Any +from typing_extensions import assert_type + + +def test_iscoroutinefunction_asyncio( + x: Callable[[str, int], Coroutine[str, int, bytes]], + y: Callable[[str, int], Awaitable[bytes]], + z: Callable[[str, int], str | Awaitable[bytes]], + xx: object, +) -> None: + # asyncio.iscoroutinefunction is deprecated >= 3.11, expecting a warning. + if sys.version_info >= (3, 11): + if iscoroutinefunction(x): # pyright: ignore + assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) + + if iscoroutinefunction(y): # pyright: ignore + assert_type(y, Callable[[str, int], Coroutine[Any, Any, bytes]]) + + if iscoroutinefunction(z): # pyright: ignore + assert_type(z, Callable[[str, int], Coroutine[Any, Any, Any]]) + + if iscoroutinefunction(xx): # pyright: ignore + assert_type(xx, Callable[..., Coroutine[Any, Any, Any]]) + else: + if iscoroutinefunction(x): + assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) + + if iscoroutinefunction(y): + assert_type(y, Callable[[str, int], Coroutine[Any, Any, bytes]]) + + if iscoroutinefunction(z): + assert_type(z, Callable[[str, int], Coroutine[Any, Any, Any]]) + + if iscoroutinefunction(xx): + assert_type(xx, Callable[..., Coroutine[Any, Any, Any]]) diff --git a/stdlib/@tests/test_cases/asyncio/check_create_server.py b/stdlib/@tests/test_cases/asyncio/check_create_server.py new file mode 100644 index 000000000000..1275ffe4823a --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_create_server.py @@ -0,0 +1,26 @@ +import asyncio +import socket + + +async def check_abstract_event_loop(loop: asyncio.AbstractEventLoop, sock: socket.socket) -> None: + await loop.create_server(asyncio.Protocol, None, 8000) + await loop.create_server(asyncio.Protocol, "localhost") + await loop.create_server(asyncio.Protocol, "localhost", None) + await loop.create_server(asyncio.Protocol, "localhost", 8000) + await loop.create_server(asyncio.Protocol, port=8000) + await loop.create_server(asyncio.Protocol, sock=sock) + + await loop.create_server(asyncio.Protocol) # type: ignore + await loop.create_server(asyncio.Protocol, "localhost", sock=sock) # type: ignore + + +async def check_base_event_loop(loop: asyncio.BaseEventLoop, sock: socket.socket) -> None: + await loop.create_server(asyncio.Protocol, None, 8000) + await loop.create_server(asyncio.Protocol, "localhost") + await loop.create_server(asyncio.Protocol, "localhost", None) + await loop.create_server(asyncio.Protocol, "localhost", 8000) + await loop.create_server(asyncio.Protocol, port=8000) + await loop.create_server(asyncio.Protocol, sock=sock) + + await loop.create_server(asyncio.Protocol) # type: ignore + await loop.create_server(asyncio.Protocol, "localhost", sock=sock) # type: ignore diff --git a/stdlib/@tests/test_cases/asyncio/check_gather.py b/stdlib/@tests/test_cases/asyncio/check_gather.py new file mode 100644 index 000000000000..9649b63ef235 --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_gather.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable +from typing_extensions import assert_type + + +async def coro1() -> int: + return 42 + + +async def coro2() -> str: + return "spam" + + +async def test_gather(awaitable1: Awaitable[int], awaitable2: Awaitable[str]) -> None: + a = await asyncio.gather(awaitable1) + assert_type(a, tuple[int]) + + b = await asyncio.gather(awaitable1, awaitable2, return_exceptions=True) + assert_type(b, tuple[int | BaseException, str | BaseException]) + + c = await asyncio.gather(awaitable1, awaitable2, awaitable1, awaitable1, awaitable1, awaitable1) + assert_type(c, tuple[int, str, int, int, int, int]) + + d = await asyncio.gather(awaitable1, awaitable1, awaitable1, awaitable1, awaitable1, awaitable1, awaitable1) + assert_type(d, list[int]) + + awaitables_list: list[Awaitable[int]] = [awaitable1] + e = await asyncio.gather(*awaitables_list) + assert_type(e, list[int]) + + # this case isn't reliable between typecheckers, no one would ever call it with no args anyway + # f = await asyncio.gather() + # assert_type(f, list[Any]) + + +asyncio.run(test_gather(coro1(), coro2())) diff --git a/stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py b/stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py new file mode 100644 index 000000000000..7ab8e9d814b1 --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import asyncio +from socket import AddressFamily +from typing_extensions import assert_type + + +async def check_getaddrinfo(loop: asyncio.AbstractEventLoop, base_loop: asyncio.BaseEventLoop) -> None: + # The address family (item 0) is a tag that discriminates the sockaddr (item 4). + for info in await loop.getaddrinfo("localhost", 80): + if info[0] == AddressFamily.AF_INET: + assert_type(info[4], "tuple[str, int]") + elif info[0] == AddressFamily.AF_INET6: + assert_type(info[4], "tuple[str, int, int, int] | tuple[int, bytes]") + + for info in await base_loop.getaddrinfo("localhost", 80): + if info[0] == AddressFamily.AF_INET: + assert_type(info[4], "tuple[str, int]") + elif info[0] == AddressFamily.AF_INET6: + assert_type(info[4], "tuple[str, int, int, int] | tuple[int, bytes]") diff --git a/stdlib/@tests/test_cases/asyncio/check_task.py b/stdlib/@tests/test_cases/asyncio/check_task.py new file mode 100644 index 000000000000..69bcf8f782aa --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_task.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import asyncio + + +class Waiter: + def __init__(self) -> None: + self.tasks: list[asyncio.Task[object]] = [] + + def add(self, t: asyncio.Task[object]) -> None: + self.tasks.append(t) + + async def join(self) -> None: + await asyncio.wait(self.tasks) + + +async def foo() -> int: + return 42 + + +async def main() -> None: + # asyncio.Task is covariant in its type argument, which is unusual since its parent class + # asyncio.Future is invariant in its type argument. This is only sound because asyncio.Task + # is not actually Liskov substitutable for asyncio.Future: it does not implement set_result. + w = Waiter() + t: asyncio.Task[int] = asyncio.create_task(foo()) + w.add(t) + await w.join() diff --git a/stdlib/@tests/test_cases/asyncio/check_task_factory.py b/stdlib/@tests/test_cases/asyncio/check_task_factory.py new file mode 100644 index 000000000000..30b587d9ccba --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_task_factory.py @@ -0,0 +1,13 @@ +import asyncio +import sys + + +def get_set(loop: asyncio.BaseEventLoop) -> None: + loop.set_task_factory(loop.get_task_factory()) + + +if sys.version_info >= (3, 12): + + def eager(loop: asyncio.BaseEventLoop) -> None: + loop.set_task_factory(asyncio.eager_task_factory) + loop.set_task_factory(asyncio.create_eager_task_factory(asyncio.Task)) diff --git a/stdlib/@tests/test_cases/builtins/check_dict.py b/stdlib/@tests/test_cases/builtins/check_dict.py new file mode 100644 index 000000000000..2b2fc5082933 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_dict.py @@ -0,0 +1,214 @@ +from __future__ import annotations + +import os +from collections.abc import Iterable, Mapping +from typing import Any, Generic, TypeVar +from typing_extensions import Self, assert_type + +################################################################### +# Note: tests for `dict.update()` are in `check_MutableMapping.py`. +################################################################### + +# These do follow `__init__` overloads order: +# mypy and pyright have different opinions about this one: +# mypy raises: 'Need type annotation for "bad"' +# pyright is fine with it. +# https://github.com/python/mypy/issues/12358 +# bad = dict() +good: dict[str, str] = dict() +assert_type(good, dict[str, str]) + +assert_type(dict(arg=1), dict[str, int]) + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +class KeysAndGetItem(Generic[_KT, _VT]): + data: dict[_KT, _VT] + + def __init__(self, data: dict[_KT, _VT]) -> None: + self.data = data + + def keys(self) -> Iterable[_KT]: + return self.data.keys() + + def __getitem__(self, __k: _KT) -> _VT: + return self.data[__k] + + +kt1: KeysAndGetItem[int, str] = KeysAndGetItem({0: ""}) +assert_type(dict(kt1), dict[int, str]) +dict(kt1, arg="a") # type: ignore + +kt2: KeysAndGetItem[str, int] = KeysAndGetItem({"": 0}) +assert_type(dict(kt2, arg=1), dict[str, int]) + + +def test_iterable_tuple_overload(x: Iterable[tuple[int, str]]) -> dict[int, str]: + return dict(x) + + +i1: Iterable[tuple[int, str]] = [(1, "a"), (2, "b")] +test_iterable_tuple_overload(i1) +dict(i1, arg="a") # type: ignore + +i2: Iterable[tuple[str, int]] = [("a", 1), ("b", 2)] +assert_type(dict(i2, arg=1), dict[str, int]) + +i3: Iterable[str] = ["a.b"] +i4: Iterable[bytes] = [b"a.b"] +assert_type(dict(string.split(".") for string in i3), dict[str, str]) +assert_type(dict(string.split(b".") for string in i4), dict[bytes, bytes]) + +dict(["foo", "bar", "baz"]) # type: ignore +dict([b"foo", b"bar", b"baz"]) # type: ignore + +# Exploring corner cases of dict.get() +d_any: dict[str, Any] = {} +d_str: dict[str, str] = {} +any_value: Any = None +str_value = "value" +int_value = 1 + +assert_type(d_any["key"], Any) +assert_type(d_any.get("key"), Any | None) +assert_type(d_any.get("key", None), Any | None) +assert_type(d_any.get("key", any_value), Any) +assert_type(d_any.get("key", str_value), Any) +assert_type(d_any.get("key", int_value), Any) + +assert_type(d_str["key"], str) +assert_type(d_str.get("key"), str | None) +assert_type(d_str.get("key", None), str | None) +# Pyright has str instead of Any here +assert_type(d_str.get("key", any_value), Any) # pyright: ignore[reportAssertTypeFailure] +assert_type(d_str.get("key", str_value), str) +assert_type(d_str.get("key", int_value), str | int) + +# Now with context! +result: str +result = d_any["key"] +result = d_any.get("key") # type: ignore[assignment] +result = d_any.get("key", None) # type: ignore[assignment] +result = d_any.get("key", any_value) +result = d_any.get("key", str_value) +result = d_any.get("key", int_value) + +result = d_str["key"] +result = d_str.get("key") # type: ignore[assignment] +result = d_str.get("key", None) # type: ignore[assignment] +# Pyright has str | None here, see https://github.com/microsoft/pyright/discussions/9570 +result = d_str.get("key", any_value) # pyright: ignore[reportAssignmentType] +result = d_str.get("key", str_value) +result = d_str.get("key", int_value) # type: ignore[arg-type] + + +# Return values also make things weird + +# Pyright doesn't have a version of no-any-return, +# and mypy doesn't have a type: ignore that pyright will ignore. +# def test1() -> str: +# return d_any["key"] # mypy: ignore[no-any-return] + + +def test2() -> str: + return d_any.get("key") # type: ignore[return-value] + + +# def test3() -> str: +# return d_any.get("key", None) # mypy: ignore[no-any-return] +# +# +# def test4() -> str: +# return d_any.get("key", any_value) # mypy: ignore[no-any-return] +# +# +# def test5() -> str: +# return d_any.get("key", str_value) # mypy: ignore[no-any-return] +# +# +# def test6() -> str: +# return d_any.get("key", int_value) # mypy: ignore[no-any-return] + + +def test7() -> str: + return d_str["key"] + + +def test8() -> str: + return d_str.get("key") # type: ignore[return-value] + + +def test9() -> str: + return d_str.get("key", None) # type: ignore[return-value] + + +def test10() -> str: + return d_str.get("key", any_value) # type: ignore[no-any-return] + + +def test11() -> str: + return d_str.get("key", str_value) + + +def test12() -> str: + return d_str.get("key", int_value) # type: ignore[arg-type] + + +# Tests for `dict.__(r)or__`. + + +class CustomDictSubclass(dict[_KT, _VT]): + pass + + +class CustomMappingWithDunderOr(Mapping[_KT, _VT]): + def __or__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ror__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ior__(self, other: Mapping[_KT, _VT]) -> Self: + return self + + +def test_dict_dot_or( + a: dict[int, int], + b: CustomDictSubclass[int, int], + c: dict[str, str], + d: Mapping[int, int], + e: CustomMappingWithDunderOr[str, str], +) -> None: + # dict.__(r)or__ always returns a dict, even if called on a subclass of dict: + assert_type(a | b, dict[int, int]) + assert_type(b | a, dict[int, int]) + + assert_type(a | c, dict[int | str, int | str]) + + # arbitrary mappings are not accepted by `dict.__or__`; + # it has to be a subclass of `dict` + a | d # type: ignore + + # but Mappings such as `os._Environ` or `CustomMappingWithDunderOr`, + # which define `__ror__` methods that accept `dict`, are fine: + assert_type(a | os.environ, dict[int | str, int | str]) + assert_type(os.environ | a, dict[int | str, int | str]) + + assert_type(c | os.environ, dict[str, str]) + assert_type(c | e, dict[str, str]) + + assert_type(os.environ | c, dict[str, str]) + assert_type(e | c, dict[str, str]) + + # store "untainted" `CustomMappingWithDunderOr[str, str]` to test `__ior__` against ` dict[str, str]` later + # Invalid `e |= a` causes pyright to join `Unknown` to `e`'s type + f = e + + e |= c + e |= a # type: ignore + + c |= f + + c |= a # type: ignore diff --git a/stdlib/@tests/test_cases/builtins/check_exception_group-py311.py b/stdlib/@tests/test_cases/builtins/check_exception_group-py311.py new file mode 100644 index 000000000000..b1bf701c4b8c --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_exception_group-py311.py @@ -0,0 +1,354 @@ +from __future__ import annotations + +import sys +from typing import TypeVar +from typing_extensions import assert_type + +if sys.version_info >= (3, 11): + # This can be removed later, but right now Flake8 does not know + # about these two classes: + from builtins import BaseExceptionGroup, ExceptionGroup + + # BaseExceptionGroup + # ================== + # `BaseExceptionGroup` can work with `BaseException`: + beg = BaseExceptionGroup("x", [SystemExit(), SystemExit()]) + assert_type(beg, BaseExceptionGroup[SystemExit]) + assert_type(beg.exceptions, tuple[SystemExit | BaseExceptionGroup[SystemExit], ...]) + + # Covariance works: + _beg1: BaseExceptionGroup[BaseException] = beg + + # `BaseExceptionGroup` can work with `Exception`: + beg2 = BaseExceptionGroup("x", [ValueError()]) + # FIXME: this is not right, runtime returns `ExceptionGroup` instance instead, + # but I am unable to represent this with types right now. + assert_type(beg2, BaseExceptionGroup[ValueError]) + + # .subgroup() + # ----------- + + assert_type(beg.subgroup(KeyboardInterrupt), BaseExceptionGroup[KeyboardInterrupt] | None) + assert_type(beg.subgroup((KeyboardInterrupt,)), BaseExceptionGroup[KeyboardInterrupt] | None) + + def is_base_exc(exc: BaseException) -> bool: + return isinstance(exc, BaseException) + + def is_specific(exc: SystemExit | BaseExceptionGroup[SystemExit]) -> bool: + return isinstance(exc, SystemExit) + + # This one does not have `BaseExceptionGroup` part, + # this is why we treat as an error. + def is_system_exit(exc: SystemExit) -> bool: + return isinstance(exc, SystemExit) + + def unrelated_subgroup(exc: KeyboardInterrupt) -> bool: + return False + + assert_type(beg.subgroup(is_base_exc), BaseExceptionGroup[SystemExit] | None) + assert_type(beg.subgroup(is_specific), BaseExceptionGroup[SystemExit] | None) + beg.subgroup(is_system_exit) # type: ignore + beg.subgroup(unrelated_subgroup) # type: ignore + + # `Exception`` subgroup returns `ExceptionGroup`: + assert_type(beg.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(beg.subgroup((ValueError,)), ExceptionGroup[ValueError] | None) + + # Callable are harder, we don't support cast to `ExceptionGroup` here. + # Because callables might return `True` the first time. And `BaseExceptionGroup` + # will stick, no matter what arguments are. + + def is_exception(exc: Exception) -> bool: + return isinstance(exc, Exception) + + def is_exception_or_beg(exc: Exception | BaseExceptionGroup[SystemExit]) -> bool: + return isinstance(exc, Exception) + + # This is an error because of the `Exception` argument type, + # while `SystemExit` is needed instead. + beg.subgroup(is_exception_or_beg) # type: ignore + + # This is an error, because `BaseExceptionGroup` is not an `Exception` + # subclass. It is required. + beg.subgroup(is_exception) # type: ignore + + # .split() + # -------- + + assert_type( + beg.split(KeyboardInterrupt), tuple[BaseExceptionGroup[KeyboardInterrupt] | None, BaseExceptionGroup[SystemExit] | None] + ) + assert_type( + beg.split((KeyboardInterrupt,)), + tuple[BaseExceptionGroup[KeyboardInterrupt] | None, BaseExceptionGroup[SystemExit] | None], + ) + assert_type( + beg.split(ValueError), # there are no `ValueError` items in there, but anyway + tuple[ExceptionGroup[ValueError] | None, BaseExceptionGroup[SystemExit] | None], + ) + + excs_to_split: list[ValueError | KeyError | SystemExit] = [ValueError(), KeyError(), SystemExit()] + to_split = BaseExceptionGroup("x", excs_to_split) + assert_type(to_split, BaseExceptionGroup[ValueError | KeyError | SystemExit]) + + # Ideally the first part should be `ExceptionGroup[ValueError]` (done) + # and the second part should be `BaseExceptionGroup[KeyError | SystemExit]`, + # but we cannot subtract type from a union. + # We also cannot change `BaseExceptionGroup` to `ExceptionGroup` even if needed + # in the second part here because of that. + assert_type( + to_split.split(ValueError), + tuple[ExceptionGroup[ValueError] | None, BaseExceptionGroup[ValueError | KeyError | SystemExit] | None], + ) + + def split_callable1(exc: ValueError | KeyError | SystemExit | BaseExceptionGroup[ValueError | KeyError | SystemExit]) -> bool: + return True + + assert_type( + to_split.split(split_callable1), # Concrete type is ok + tuple[ + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + ], + ) + assert_type( + to_split.split(is_base_exc), # Base class is ok + tuple[ + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + ], + ) + # `Exception` cannot be used: `BaseExceptionGroup` is not a subtype of it. + to_split.split(is_exception) # type: ignore + + # .derive() + # --------- + + assert_type(beg.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(beg.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # ExceptionGroup + # ============== + + # `ExceptionGroup` can work with `Exception`: + excs: list[ValueError | KeyError] = [ValueError(), KeyError()] + eg = ExceptionGroup("x", excs) + assert_type(eg, ExceptionGroup[ValueError | KeyError]) + assert_type(eg.exceptions, tuple[ValueError | KeyError | ExceptionGroup[ValueError | KeyError], ...]) + + # Covariance works: + _eg1: ExceptionGroup[Exception] = eg + + # `ExceptionGroup` cannot work with `BaseException`: + ExceptionGroup("x", [SystemExit()]) # type: ignore + + # .subgroup() + # ----------- + + # Our decision is to ban cases like:: + # + # >>> eg = ExceptionGroup('x', [ValueError()]) + # >>> eg.subgroup(BaseException) + # ExceptionGroup('e', [ValueError()]) + # + # are possible in runtime. + # We do it because, it does not make sense for all other base exception types. + # Supporting just `BaseException` looks like an overkill. + eg.subgroup(BaseException) # type: ignore + eg.subgroup((KeyboardInterrupt, SystemExit)) # type: ignore + + assert_type(eg.subgroup(Exception), ExceptionGroup[Exception] | None) + assert_type(eg.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(eg.subgroup((ValueError,)), ExceptionGroup[ValueError] | None) + + def subgroup_eg1(exc: ValueError | KeyError | ExceptionGroup[ValueError | KeyError]) -> bool: + return True + + def subgroup_eg2(exc: ValueError | KeyError) -> bool: + return True + + assert_type(eg.subgroup(subgroup_eg1), ExceptionGroup[ValueError | KeyError] | None) + assert_type(eg.subgroup(is_exception), ExceptionGroup[ValueError | KeyError] | None) + assert_type(eg.subgroup(is_base_exc), ExceptionGroup[ValueError | KeyError] | None) + assert_type(eg.subgroup(is_base_exc), ExceptionGroup[ValueError | KeyError] | None) + + # Does not have `ExceptionGroup` part: + eg.subgroup(subgroup_eg2) # type: ignore + + # .split() + # -------- + + assert_type(eg.split(TypeError), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError | KeyError] | None]) + assert_type(eg.split((TypeError,)), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError | KeyError] | None]) + assert_type( + eg.split(is_exception), tuple[ExceptionGroup[ValueError | KeyError] | None, ExceptionGroup[ValueError | KeyError] | None] + ) + assert_type( + eg.split(is_base_exc), + # is not converted, because `ExceptionGroup` cannot have + # direct `BaseException` subclasses inside. + tuple[ExceptionGroup[ValueError | KeyError] | None, ExceptionGroup[ValueError | KeyError] | None], + ) + + # It does not include `ExceptionGroup` itself, so it will fail: + def value_or_key_error(exc: ValueError | KeyError) -> bool: + return isinstance(exc, (ValueError, KeyError)) + + eg.split(value_or_key_error) # type: ignore + + # `ExceptionGroup` cannot have direct `BaseException` subclasses inside. + eg.split(BaseException) # type: ignore + eg.split((SystemExit, GeneratorExit)) # type: ignore + + # .derive() + # --------- + + assert_type(eg.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(eg.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # BaseExceptionGroup Custom Subclass + # ================================== + # In some cases `Self` type can be preserved in runtime, + # but it is impossible to express. That's why we always fallback to + # `BaseExceptionGroup` and `ExceptionGroup`. + + _BE = TypeVar("_BE", bound=BaseException) + + class CustomBaseGroup(BaseExceptionGroup[_BE]): ... + + cb1 = CustomBaseGroup("x", [SystemExit()]) + assert_type(cb1, CustomBaseGroup[SystemExit]) + cb2 = CustomBaseGroup("x", [ValueError()]) + assert_type(cb2, CustomBaseGroup[ValueError]) + + # .subgroup() + # ----------- + + assert_type(cb1.subgroup(KeyboardInterrupt), BaseExceptionGroup[KeyboardInterrupt] | None) + assert_type(cb2.subgroup((KeyboardInterrupt,)), BaseExceptionGroup[KeyboardInterrupt] | None) + + assert_type(cb1.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(cb2.subgroup((KeyError,)), ExceptionGroup[KeyError] | None) + + def cb_subgroup1(exc: SystemExit | CustomBaseGroup[SystemExit]) -> bool: + return True + + def cb_subgroup2(exc: ValueError | CustomBaseGroup[ValueError]) -> bool: + return True + + assert_type(cb1.subgroup(cb_subgroup1), BaseExceptionGroup[SystemExit] | None) + assert_type(cb2.subgroup(cb_subgroup2), BaseExceptionGroup[ValueError] | None) + cb1.subgroup(cb_subgroup2) # type: ignore + cb2.subgroup(cb_subgroup1) # type: ignore + + # .split() + # -------- + + assert_type( + cb1.split(KeyboardInterrupt), tuple[BaseExceptionGroup[KeyboardInterrupt] | None, BaseExceptionGroup[SystemExit] | None] + ) + assert_type(cb1.split(TypeError), tuple[ExceptionGroup[TypeError] | None, BaseExceptionGroup[SystemExit] | None]) + assert_type(cb2.split((TypeError,)), tuple[ExceptionGroup[TypeError] | None, BaseExceptionGroup[ValueError] | None]) + + def cb_split1(exc: SystemExit | CustomBaseGroup[SystemExit]) -> bool: + return True + + def cb_split2(exc: ValueError | CustomBaseGroup[ValueError]) -> bool: + return True + + assert_type(cb1.split(cb_split1), tuple[BaseExceptionGroup[SystemExit] | None, BaseExceptionGroup[SystemExit] | None]) + assert_type(cb2.split(cb_split2), tuple[BaseExceptionGroup[ValueError] | None, BaseExceptionGroup[ValueError] | None]) + cb1.split(cb_split2) # type: ignore + cb2.split(cb_split1) # type: ignore + + # .derive() + # --------- + + # Note, that `Self` type is not preserved in runtime. + assert_type(cb1.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(cb1.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + assert_type(cb2.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(cb2.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # ExceptionGroup Custom Subclass + # ============================== + + _E = TypeVar("_E", bound=Exception) + + class CustomGroup(ExceptionGroup[_E]): ... + + CustomGroup("x", [SystemExit()]) # type: ignore + cg1 = CustomGroup("x", [ValueError()]) + assert_type(cg1, CustomGroup[ValueError]) + + # .subgroup() + # ----------- + + cg1.subgroup(BaseException) # type: ignore + cg1.subgroup((KeyboardInterrupt, SystemExit)) # type: ignore + + assert_type(cg1.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(cg1.subgroup((KeyError,)), ExceptionGroup[KeyError] | None) + + def cg_subgroup1(exc: ValueError | CustomGroup[ValueError]) -> bool: + return True + + def cg_subgroup2(exc: ValueError) -> bool: + return True + + assert_type(cg1.subgroup(cg_subgroup1), ExceptionGroup[ValueError] | None) + cg1.subgroup(cb_subgroup2) # type: ignore + + # .split() + # -------- + + assert_type(cg1.split(TypeError), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError] | None]) + assert_type(cg1.split((TypeError,)), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError] | None]) + cg1.split(BaseException) # type: ignore + + def cg_split1(exc: ValueError | CustomGroup[ValueError]) -> bool: + return True + + def cg_split2(exc: ValueError) -> bool: + return True + + assert_type(cg1.split(cg_split1), tuple[ExceptionGroup[ValueError] | None, ExceptionGroup[ValueError] | None]) + cg1.split(cg_split2) # type: ignore + + # .derive() + # --------- + + # Note, that `Self` type is not preserved in runtime. + assert_type(cg1.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(cg1.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # Additional tests + # ============================== + + def test_exception_group_default_type() -> None: + try: + ex: ExceptionGroup = ExceptionGroup("", [ValueError("a"), ValueError("b")]) + raise ex + except ExceptionGroup as e: + assert all(isinstance(exc, ValueError) for exc in e.exceptions) + + def test_exception_group_with_specific_type() -> None: + try: + ex: ExceptionGroup[ValueError] = ExceptionGroup("", [ValueError("a"), ValueError("b")]) + raise ex + except ExceptionGroup as e: + assert all(isinstance(exc, ValueError) for exc in e.exceptions) + + def test_base_exception_group_default_type() -> None: + try: + ex: BaseExceptionGroup = BaseExceptionGroup("", [SystemExit("a"), SystemExit("b")]) + raise ex + except BaseExceptionGroup as e: + assert all(isinstance(exc, SystemExit) for exc in e.exceptions) + + def test_base_exception_group_with_specific_type() -> None: + try: + ex: BaseExceptionGroup[SystemExit] = BaseExceptionGroup("", [SystemExit("a"), SystemExit("b")]) + raise ex + except BaseExceptionGroup as e: + assert all(isinstance(exc, SystemExit) for exc in e.exceptions) diff --git a/stdlib/@tests/test_cases/builtins/check_frozendict-py315.py b/stdlib/@tests/test_cases/builtins/check_frozendict-py315.py new file mode 100644 index 000000000000..dd222a4c796f --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_frozendict-py315.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import sys +from typing import Any +from typing_extensions import assert_type + +if sys.version_info >= (3, 15): + # Regression test for gh-15985: ``frozendict`` can be constructed from + # keyword arguments, a mapping, or an iterable of pairs (not just with no + # arguments). + assert_type(frozendict(), frozendict[Any, Any]) + assert_type(frozendict(a=1), frozendict[str, int]) + assert_type(frozendict({"x": 1}), frozendict[str, int]) + assert_type(frozendict([("k", 2)]), frozendict[str, int]) + assert_type(frozendict({"x": 1}, y=2), frozendict[str, int]) diff --git a/stdlib/@tests/test_cases/builtins/check_iteration.py b/stdlib/@tests/test_cases/builtins/check_iteration.py new file mode 100644 index 000000000000..3d609635377e --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_iteration.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing import Iterator +from typing_extensions import assert_type + + +class OldStyleIter: + def __getitem__(self, index: int) -> str: + return str(index) + + +for x in iter(OldStyleIter()): + assert_type(x, str) + +assert_type(iter(OldStyleIter()), Iterator[str]) +assert_type(next(iter(OldStyleIter())), str) diff --git a/stdlib/@tests/test_cases/builtins/check_list.py b/stdlib/@tests/test_cases/builtins/check_list.py new file mode 100644 index 000000000000..f284f2c55b23 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_list.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from typing_extensions import assert_type + + +# list.__add__ example from #8292 +class Foo: + def asd(self) -> int: + return 1 + + +class Bar: + def asd(self) -> int: + return 2 + + +combined = [Foo()] + [Bar()] +assert_type(combined, list[Foo | Bar]) +for item in combined: + assert_type(item.asd(), int) diff --git a/stdlib/@tests/test_cases/builtins/check_memoryview.py b/stdlib/@tests/test_cases/builtins/check_memoryview.py new file mode 100644 index 000000000000..1ece6e6b850b --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_memoryview.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import array +import sys +from typing_extensions import assert_type + +# Casting to bytes. +buf = b"abcdefg" +view = memoryview(buf).cast("c") +elm = view[0] +assert_type(elm, bytes) +assert_type(view[0:2], memoryview[bytes]) + +# Casting to a bool. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +bool_mv = mv.cast("?") +assert_type(bool_mv[0], bool) +assert_type(bool_mv[0:2], memoryview[bool]) + + +# Casting to a signed char. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("b") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a signed short. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("h") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a signed int. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("i") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a signed long. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("l") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a float. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +float_mv = mv.cast("f") +assert_type(float_mv[0], float) +assert_type(float_mv[0:2], memoryview[float]) + +# An invalid literal should raise an error. +mv = memoryview(b"abc") +mv.cast("abc") # type: ignore + +if sys.version_info >= (3, 14): + mv.index(42) + mv.count(42) +else: + mv.index(42) # type: ignore + mv.count(42) # type: ignore diff --git a/stdlib/@tests/test_cases/builtins/check_min.py b/stdlib/@tests/test_cases/builtins/check_min.py new file mode 100644 index 000000000000..a300ad45c482 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_min.py @@ -0,0 +1,94 @@ +from typing_extensions import assert_type + + +def test_min_builtin() -> None: + # legal comparisons that succeed at runtime + b1, b2 = bool(True), bool(False) + i1, i2 = int(1), int(2) + s1, s2 = str("a"), str("b") + f1, f2 = float(0.5), float(2.3) + l1, l2 = list[int]([1, 2]), list[int]([3, 4]) + t1, t2 = tuple[str, str](("A", "B")), tuple[str, str](("C", "D")) + tN = tuple[str, ...](["A", "B", "C"]) + + assert_type(min(b1, b2), bool) + assert_type(min(i1, i2), int) + assert_type(min(s1, s2), str) + assert_type(min(f1, f2), float) + + # mixed numerical types (note: float = int or float) + assert_type(min(b1, i1), int) + assert_type(min(i1, b1), int) + + assert_type(min(b1, f1), float) + assert_type(min(f1, b1), float) + + assert_type(min(i1, f1), float) + assert_type(min(f1, i1), float) + + # comparisons with lists and tuples + assert_type(min(l1, l2), list[int]) + assert_type(min(t1, t2), tuple[str, str]) + assert_type(min(tN, t2), tuple[str, ...]) + + +def test_min_bad_builtin() -> None: + # illegal comparisons that fail at runtime + i1 = int(1) + s1 = str("a") + f1 = float(1.0) + c1, c2 = complex(1.0, 2.0), complex(3.0, 4.0) + list_str = list[str](["A", "B"]) + list_int = list[int]([2, 3]) + tup_str = tuple[str, str](("A", "B")) + tup_int = tuple[int, int]((2, 3)) + + # True negatives. + min(c1, c2) # type: ignore + + # FIXME: False negatives. + min(i1, s1) + min(s1, f1) + min(f1, list_str) + min(list_str, list_int) + min(tup_str, tup_int) + + +def test_min_custom_comparison() -> None: + class BoolScalar: + def __bool__(self) -> bool: ... + + class FloatScalar: + def __float__(self) -> float: ... + def __ge__(self, other: "FloatScalar") -> BoolScalar: ... + def __gt__(self, other: "FloatScalar") -> BoolScalar: ... + def __lt__(self, other: "FloatScalar") -> BoolScalar: ... + def __le__(self, other: "FloatScalar") -> BoolScalar: ... + + f1 = FloatScalar() + f2 = FloatScalar() + + assert_type(min(f1, f2), FloatScalar) + + +def test_min_bad_custom_type() -> None: + class FloatScalar: + def __float__(self) -> float: ... + def __ge__(self, other: "FloatScalar") -> object: + return object() + + def __gt__(self, other: "FloatScalar") -> object: + return object() + + def __lt__(self, other: "FloatScalar") -> object: + return object() + + def __le__(self, other: "FloatScalar") -> object: + return object() + + f1 = FloatScalar() + f2 = FloatScalar() + + # Note: min(f1, f2) works at runtime, but always returns the second argument. + # therefore, we require returning a boolean-like type for comparisons. + min(f1, f2) # type: ignore diff --git a/stdlib/@tests/test_cases/builtins/check_object.py b/stdlib/@tests/test_cases/builtins/check_object.py new file mode 100644 index 000000000000..60df1143f727 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_object.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from typing import Any + + +# The following should pass without error (see #6661): +class Diagnostic: + def __reduce__(self) -> str | tuple[Any, ...]: + res = super().__reduce__() + if isinstance(res, tuple) and len(res) >= 3: + res[2]["_info"] = 42 + + return res diff --git a/stdlib/@tests/test_cases/builtins/check_pow.py b/stdlib/@tests/test_cases/builtins/check_pow.py new file mode 100644 index 000000000000..01de2eb5fc8b --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_pow.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import sys +from decimal import Decimal +from fractions import Fraction +from typing import Any, Literal +from typing_extensions import assert_type + +# See #7163 +assert_type(pow(1, 0), Literal[1]) +assert_type(1**0, Literal[1]) +assert_type(pow(1, 0, None), Literal[1]) + +# TODO: We don't have a good way of expressing the fact +# that passing 0 for the third argument will lead to an exception being raised +# (see discussion in #8566) +# +# assert_type(pow(2, 4, 0), Never) + +assert_type(pow(2, 4), int) +# pyright infers a literal type here, but mypy does not. +# Unfortunately, there is no way to ignore an error only for mypy, +# whilst getting both pyright and mypy to respect `type: ignore`. +# So we can't check pyright's handling (https://github.com/python/mypy/issues/12358). +assert_type(2**4, int) # pyright: ignore[reportAssertTypeFailure] +# pyright version: assert_type(2**4, Literal[16]) +assert_type(pow(4, 6, None), int) + +assert_type(pow(5, -7), float) +assert_type(5**-7, float) + +assert_type(pow(2, 4, 5), int) # pow(, , ) +assert_type(pow(2, 35, 3), int) # pow(, , ) + +assert_type(pow(2, 8.5), float) +assert_type(2**8.6, float) +assert_type(pow(2, 8.6, None), float) + +assert_type((-2) ** 0.5, complex) + +assert_type(pow((-5), 8.42, None), complex) + +assert_type(pow(4.6, 8), float) +assert_type(4.6**8, float) +assert_type(pow(5.1, 4, None), float) + +assert_type(pow(complex(6), 6.2), complex) +assert_type(complex(6) ** 6.2, complex) +assert_type(pow(complex(9), 7.3, None), complex) + +assert_type(Fraction() ** 4, Fraction) + +assert_type(pow(Fraction(3, 7), complex(1, 8)), complex) +assert_type(Fraction(3, 7) ** complex(1, 8), complex) + +assert_type(pow(complex(4, -8), Fraction(2, 3)), complex) +assert_type(complex(4, -8) ** Fraction(2, 3), complex) + +assert_type(pow(Decimal("1.0"), Decimal("1.6")), Decimal) +assert_type(Decimal("1.0") ** Decimal("1.6"), Decimal) + +assert_type(pow(Decimal("1.0"), Decimal("1.0"), Decimal("1.0")), Decimal) +assert_type(pow(Decimal("4.6"), 7, None), Decimal) +assert_type(Decimal("4.6") ** 7, Decimal) + +# These would ideally be more precise, but `Any` is acceptable +# They have to be `Any` due to the fact that type-checkers can't distinguish +# between positive and negative numbers for the second argument to `pow()` +# +# int for positive 2nd-arg, float otherwise +assert_type(pow(4, 65), Any) +assert_type(pow(2, -45), Any) +assert_type(pow(3, 57, None), Any) +assert_type(pow(67, 0.98, None), Any) +assert_type(87**7.32, Any) +# pow(, ) -> float +# pow(, ) -> complex +assert_type(pow(4.7, 7.4), Any) +assert_type(pow(-9.8, 8.3), Any) +assert_type(pow(-9.3, -88.2), Any) +assert_type(pow(8.2, -9.8), Any) +assert_type(pow(4.7, 9.2, None), Any) +# See #7046 -- float for a positive 1st arg, complex otherwise +assert_type((-95) ** 8.42, Any) + +# Fraction.__pow__/__rpow__ with modulo parameter +# With the None parameter, we get the correct type, but with a non-None parameter, we receive TypeError +if sys.version_info >= (3, 14): + assert_type(pow(Fraction(3, 4), 2, None), Fraction) + # Non-none modulo should fail + pow(Fraction(3, 4), 2, 1) # type: ignore[misc] +else: + pow(Fraction(), 5, 8) # type: ignore + +# All of the following cases should fail a type-checker. +pow(1.9, 4, 6) # type: ignore +pow(4, 7, 4.32) # type: ignore +pow(6.2, 5.9, 73) # type: ignore +pow(complex(6), 6.2, 7) # type: ignore +Decimal("8.7") ** 3.14 # type: ignore + +# TODO: This fails at runtime, but currently passes mypy and pyright: +pow(Decimal("8.5"), 3.21) diff --git a/stdlib/@tests/test_cases/builtins/check_reversed.py b/stdlib/@tests/test_cases/builtins/check_reversed.py new file mode 100644 index 000000000000..d89ebf3a0ca7 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_reversed.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from collections.abc import Iterator +from typing import Generic, TypeVar +from typing_extensions import assert_type + +x: list[int] = [] +assert_type(list(reversed(x)), "list[int]") + + +class MyReversible: + def __iter__(self) -> Iterator[str]: + yield "blah" + + def __reversed__(self) -> Iterator[str]: + yield "blah" + + +assert_type(list(reversed(MyReversible())), "list[str]") + + +_T = TypeVar("_T") + + +class MyLenAndGetItem(Generic[_T]): + def __len__(self) -> int: + return 0 + + def __getitem__(self, item: int) -> _T: + raise KeyError + + +len_and_get_item: MyLenAndGetItem[int] = MyLenAndGetItem() +assert_type(reversed(len_and_get_item), "reversed[int]") + + +class UnTrue: + def __reversed__(self) -> UnFalse: + return UnFalse() + + +class UnFalse: + def __reversed__(self) -> UnTrue: + return UnTrue() + + +assert_type(reversed(UnTrue()), "UnFalse") +assert_type(reversed(reversed(UnTrue())), "UnTrue") diff --git a/stdlib/@tests/test_cases/builtins/check_round.py b/stdlib/@tests/test_cases/builtins/check_round.py new file mode 100644 index 000000000000..84081f3665b9 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_round.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import overload +from typing_extensions import assert_type + + +class CustomIndex: + def __index__(self) -> int: + return 1 + + +# float: + +assert_type(round(5.5), int) +assert_type(round(5.5, None), int) +assert_type(round(5.5, 0), float) +assert_type(round(5.5, 1), float) +assert_type(round(5.5, 5), float) +assert_type(round(5.5, CustomIndex()), float) + +# int: + +assert_type(round(1), int) +assert_type(round(1, 1), int) +assert_type(round(1, None), int) +assert_type(round(1, CustomIndex()), int) + +# Protocols: + + +class WithCustomRound1: + def __round__(self) -> str: + return "a" + + +assert_type(round(WithCustomRound1()), str) +assert_type(round(WithCustomRound1(), None), str) +# Errors: +round(WithCustomRound1(), 1) # type: ignore +round(WithCustomRound1(), CustomIndex()) # type: ignore + + +class WithCustomRound2: + def __round__(self, digits: int) -> str: + return "a" + + +assert_type(round(WithCustomRound2(), 1), str) +assert_type(round(WithCustomRound2(), CustomIndex()), str) +# Errors: +round(WithCustomRound2(), None) # type: ignore +round(WithCustomRound2()) # type: ignore + + +class WithOverloadedRound: + @overload + def __round__(self, ndigits: None = ...) -> str: ... + + @overload + def __round__(self, ndigits: int) -> bytes: ... + + def __round__(self, ndigits: int | None = None) -> str | bytes: + return b"" if ndigits is None else "" + + +assert_type(round(WithOverloadedRound()), str) +assert_type(round(WithOverloadedRound(), None), str) +assert_type(round(WithOverloadedRound(), 1), bytes) diff --git a/stdlib/@tests/test_cases/builtins/check_set.py b/stdlib/@tests/test_cases/builtins/check_set.py new file mode 100644 index 000000000000..89cb8683bfe1 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_set.py @@ -0,0 +1,57 @@ +from typing_extensions import Literal, assert_type + + +# Note: type checkers / linters are free to point out that the set difference +# below is redundant. But typeshed should allow it, as its job is to describe +# what is legal in Python, not what is sensible. +# For instance, set[Literal] - set[str] should be legal. +def test_set_difference(x: set[Literal["foo", "bar"]], y: set[str], z: set[int]) -> None: + assert_type(x - y, set[Literal["foo", "bar"]]) + assert_type(y - x, set[str]) + assert_type(x - z, set[Literal["foo", "bar"]]) + assert_type(z - x, set[int]) + assert_type(y - z, set[str]) + assert_type(z - y, set[int]) + + +def test_set_interface_overlapping_type(s: set[Literal["foo", "bar"]], y: set[str], key: str) -> None: + s.add(key) # type: ignore + s.discard(key) + s.remove(key) # type: ignore + s.difference_update(y) + s.intersection_update(y) + s.symmetric_difference_update(y) # type: ignore + s.update(y) # type: ignore + + assert_type(s.difference(y), set[Literal["foo", "bar"]]) + assert_type(s.intersection(y), set[Literal["foo", "bar"]]) + assert_type(s.isdisjoint(y), bool) + assert_type(s.issubset(y), bool) + assert_type(s.issuperset(y), bool) + assert_type(s.symmetric_difference(y), set[str]) + assert_type(s.union(y), set[str]) + + assert_type(s - y, set[Literal["foo", "bar"]]) + assert_type(s & y, set[Literal["foo", "bar"]]) + assert_type(s | y, set[str]) + assert_type(s ^ y, set[str]) + + s -= y + s &= y + s |= y # type: ignore + s ^= y # type: ignore + + +def test_frozenset_interface(s: frozenset[Literal["foo", "bar"]], y: frozenset[str]) -> None: + assert_type(s.difference(y), frozenset[Literal["foo", "bar"]]) + assert_type(s.intersection(y), frozenset[Literal["foo", "bar"]]) + assert_type(s.isdisjoint(y), bool) + assert_type(s.issubset(y), bool) + assert_type(s.issuperset(y), bool) + assert_type(s.symmetric_difference(y), frozenset[str]) + assert_type(s.union(y), frozenset[str]) + + assert_type(s - y, frozenset[Literal["foo", "bar"]]) + assert_type(s & y, frozenset[Literal["foo", "bar"]]) + assert_type(s | y, frozenset[str]) + assert_type(s ^ y, frozenset[str]) diff --git a/stdlib/@tests/test_cases/builtins/check_slice.py b/stdlib/@tests/test_cases/builtins/check_slice.py new file mode 100644 index 000000000000..596d8c63c1c5 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_slice.py @@ -0,0 +1,251 @@ +""" +Assuming X, Y and Z are types other than None, the following rules apply to the slice type: + +- The type hint `slice` should be compatible with all slices, including: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)`. (⟿ `slice[?, ?, ?]`) +- The type hint `slice[T]` should be compatible with: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)` (⟿ `slice[?, ?, ?]`) + - `slice(t)`, `slice(None, t)` and `slice(None, t, None)`. (⟿ `slice[?, T, ?]`) + - `slice(t, None)` and `slice(t, None, None)`. (⟿ `slice[T, ?, ?]`) + - `slice(t, t)` and `slice(t, t, None)`. (⟿ `slice[T, T, ?]`) +- The type hint `slice[X, Y]` should be compatible with: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)` (⟿ `slice[?, ?, ?]`) + - `slice(y)`, `slice(None, y)` and `slice(None, y, None)`. (⟿ `slice[?, Y, ?]`) + - `slice(x, None)` and `slice(x, None, None)` (⟿ `slice[X, ?, ?]`) + - `slice(x, y)` and `slice(x, y, None)`. (⟿ `slice[X, Y, ?]`) +- The type hint `slice[X, Y, Z]` should be compatible with: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)`. (⟿ `slice[?, ?, ?]`) + - `slice(y)`, `slice(None, y)` and `slice(None, y, None)`. (⟿ `slice[?, Y, ?]`) + - `slice(x, None)` and `slice(x, None, None)` (⟿ `slice[X, ?, ?]`) + - `slice(x, y)` and `slice(x, y, None)`. (⟿ `slice[X, Y, ?]`) + - `slice(None, None, z)` (⟿ `slice[?, ?, Z]`) + - `slice(None, y, z)` (⟿ `slice[?, Y, Z]`) + - `slice(x, None, z)` (⟿ `slice[X, ?, Z]`) + - `slice(x, y, z)` (⟿ `slice[X, Y, Z]`) + +Consistency criterion: Assuming now X, Y, Z can potentially be None, the following rules apply: + +- `slice(x)` must be compatible with `slice[None, X, None]`, even if X is None. +- `slice(x, y)` must be compatible with `slice[X,Y,None]`, even if X is None or Y is None. +- `slice(x, y, z)` must be compatible with `slice[X, Y, Z]`, even if X, Y, or Z are `None`. +""" + +from __future__ import annotations + +from datetime import date, datetime as DT, timedelta as TD +from typing import Any, SupportsIndex, cast +from typing_extensions import assert_type + +# region Tests for slice constructor overloads ----------------------------------------- +assert_type(slice(None), "slice[Any, Any, Any]") +assert_type(slice(1234), "slice[Any, int, Any]") + +assert_type(slice(None, None), "slice[Any, Any, Any]") +assert_type(slice(None, 5678), "slice[Any, int, Any]") +assert_type(slice(1234, None), "slice[int, Any, Any]") +assert_type(slice(1234, 5678), "slice[int, int, Any]") + +assert_type(slice(None, None, None), "slice[Any, Any, Any]") +assert_type(slice(None, 5678, None), "slice[Any, int, Any]") +assert_type(slice(1234, None, None), "slice[int, Any, Any]") +assert_type(slice(1234, 5678, None), "slice[int, int, Any]") +assert_type(slice(1234, 5678, 9012), "slice[int, int, int]") +# endregion Tests for slice constructor overloads -------------------------------------- + +# region Test parameter defaults for slice constructor --------------------------------- +# Note: need to cast, because pyright specializes regardless of type annotations +slc1 = cast("slice[SupportsIndex | None]", slice(1)) +slc2 = cast("slice[int | None, int | None]", slice(1, 2)) +fake_key_val = cast("slice[str, int]", slice("1", 2)) +assert_type(slc1, "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]") +assert_type(slc2, "slice[int | None, int | None, int | None]") +assert_type(fake_key_val, "slice[str, int, str | int]") +# endregion Test parameter defaults for slice constructor ------------------------------ + +# region Tests for slice properties ---------------------------------------------------- +# Note: if an argument is not None, we should get precisely the same type back +assert_type(slice(1234).stop, int) + +assert_type(slice(1234, None).start, int) +assert_type(slice(None, 5678).stop, int) + +assert_type(slice(1234, None, None).start, int) +assert_type(slice(None, 5678, None).stop, int) +assert_type(slice(None, None, 9012).step, int) +# endregion Tests for slice properties ------------------------------------------------- + + +# region Test for slice assignments ---------------------------------------------------- +# exhaustively test all possible assignments: miss (X), None (N), int (I), and str (S) +rXNX: slice = slice(None) +rXIX: slice = slice(1234) +rXSX: slice = slice("70") + +rNNX: slice = slice(None, None) +rINX: slice = slice(1234, None) +rSNX: slice = slice("70", None) + +rNIX: slice = slice(None, 5678) +rIIX: slice = slice(1234, 5678) +rSIX: slice = slice("70", 9012) + +rNSX: slice = slice(None, "71") +rISX: slice = slice(1234, "71") +rSSX: slice = slice("70", "71") + +rNNN: slice = slice(None, None, None) +rINN: slice = slice(1234, None, None) +rSNN: slice = slice("70", None, None) +rNIN: slice = slice(None, 5678, None) +rIIN: slice = slice(1234, 5678, None) +rSIN: slice = slice("70", 5678, None) +rNSN: slice = slice(None, "71", None) +rISN: slice = slice(1234, "71", None) +rSSN: slice = slice("70", "71", None) + +rNNI: slice = slice(None, None, 9012) +rINI: slice = slice(1234, None, 9012) +rSNI: slice = slice("70", None, 9012) +rNII: slice = slice(None, 5678, 9012) +rIII: slice = slice(1234, 5678, 9012) +rSII: slice = slice("70", 5678, 9012) +rNSI: slice = slice(None, "71", 9012) +rISI: slice = slice(1234, "71", 9012) +rSSI: slice = slice("70", "71", 9012) + +rNNS: slice = slice(None, None, "1d") +rINS: slice = slice(1234, None, "1d") +rSNS: slice = slice("70", None, "1d") +rNIS: slice = slice(None, 5678, "1d") +rIIS: slice = slice(1234, 5678, "1d") +rSIS: slice = slice("70", 5678, "1d") +rNSS: slice = slice(None, "71", "1d") +rISS: slice = slice(1234, "71", "1d") +rSSS: slice = slice("70", "71", "1d") +# endregion Test for slice assignments ------------------------------------------------- + + +# region Tests for slice[T] assignments ------------------------------------------------ +sXNX: "slice[int]" = slice(None) +sXIX: "slice[int]" = slice(1234) + +sNNX: "slice[int]" = slice(None, None) +sNIX: "slice[int]" = slice(None, 5678) +sINX: "slice[int]" = slice(1234, None) +sIIX: "slice[int]" = slice(1234, 5678) + +sNNN: "slice[int]" = slice(None, None, None) +sNIN: "slice[int]" = slice(None, 5678, None) +sNNS: "slice[int]" = slice(None, None, 9012) +sINN: "slice[int]" = slice(1234, None, None) +sINS: "slice[int]" = slice(1234, None, 9012) +sIIN: "slice[int]" = slice(1234, 5678, None) +sIIS: "slice[int]" = slice(1234, 5678, 9012) +# endregion Tests for slice[T] assignments --------------------------------------------- + + +# region Tests for slice[X, Y] assignments --------------------------------------------- +# Note: start=int is illegal and hence we add an explicit "type: ignore" comment. +tXNX: "slice[None, int]" = slice(None) # since slice(None) is slice[Any, Any, Any] +tXIX: "slice[None, int]" = slice(1234) + +tNNX: "slice[None, int]" = slice(None, None) +tNIX: "slice[None, int]" = slice(None, 5678) +tINX: "slice[None, int]" = slice(1234, None) # type: ignore +tIIX: "slice[None, int]" = slice(1234, 5678) # type: ignore + +tNNN: "slice[None, int]" = slice(None, None, None) +tNIN: "slice[None, int]" = slice(None, 5678, None) +tINN: "slice[None, int]" = slice(1234, None, None) # type: ignore +tIIN: "slice[None, int]" = slice(1234, 5678, None) # type: ignore +tNNS: "slice[None, int]" = slice(None, None, 9012) +tINS: "slice[None, int]" = slice(None, 5678, 9012) +tNIS: "slice[None, int]" = slice(1234, None, 9012) # type: ignore +tIIS: "slice[None, int]" = slice(1234, 5678, 9012) # type: ignore +# endregion Tests for slice[X, Y] assignments ------------------------------------------ + + +# region Tests for slice[X, Y, Z] assignments ------------------------------------------ +uXNX: "slice[int, int, int]" = slice(None) +uXIX: "slice[int, int, int]" = slice(1234) + +uNNX: "slice[int, int, int]" = slice(None, None) +uNIX: "slice[int, int, int]" = slice(None, 5678) +uINX: "slice[int, int, int]" = slice(1234, None) +uIIX: "slice[int, int, int]" = slice(1234, 5678) + +uNNN: "slice[int, int, int]" = slice(None, None, None) +uNNI: "slice[int, int, int]" = slice(None, None, 9012) +uNIN: "slice[int, int, int]" = slice(None, 5678, None) +uNII: "slice[int, int, int]" = slice(None, 5678, 9012) +uINN: "slice[int, int, int]" = slice(1234, None, None) +uINI: "slice[int, int, int]" = slice(1234, None, 9012) +uIIN: "slice[int, int, int]" = slice(1234, 5678, None) +uIII: "slice[int, int, int]" = slice(1234, 5678, 9012) +# endregion Tests for slice[X, Y, Z] assignments --------------------------------------- + + +# region Test for slice consistency criterion ------------------------------------------ +year = date(2021, 1, 1) +vXNX: "slice[None, None, None]" = slice(None) +vXIX: "slice[None, date, None]" = slice(year) + +vNNX: "slice[None, None, None]" = slice(None, None) +vNIX: "slice[None, date, None]" = slice(None, year) +vINX: "slice[date, None, None]" = slice(year, None) +vIIX: "slice[date, date, None]" = slice(year, year) + +vNNN: "slice[None, None, None]" = slice(None, None, None) +vNIN: "slice[None, date, None]" = slice(None, year, None) +vINN: "slice[date, None, None]" = slice(year, None, None) +vIIN: "slice[date, date, None]" = slice(year, year, None) +vNNI: "slice[None, None, str]" = slice(None, None, "1d") +vNII: "slice[None, date, str]" = slice(None, year, "1d") +vINI: "slice[date, None, str]" = slice(year, None, "1d") +vIII: "slice[date, date, str]" = slice(year, year, "1d") +# endregion Test for slice consistency criterion --------------------------------------- + + +# region Integration tests for slices with datetimes ----------------------------------- +class TimeSeries: # similar to pandas.Series with datetime index + def __getitem__(self, key: "slice[DT | str | None, DT | str | None]") -> Any: + """Subsample the time series at the given dates.""" + ... + + +class TimeSeriesInterpolator: # similar to pandas.Series with datetime index + def __getitem__(self, key: "slice[DT, DT, TD | None]") -> Any: + """Subsample the time series at the given dates.""" + ... + + +# tests slices as an argument +start = DT(1970, 1, 1) +stop = DT(1971, 1, 10) +step = TD(days=1) +# see: https://pandas.pydata.org/docs/user_guide/timeseries.html#partial-string-indexing +# FIXME: https://github.com/python/mypy/issues/2410 (use literal slices) +series = TimeSeries() +_ = series[slice(None, "1970-01-10")] +_ = series[slice("1970-01-01", None)] +_ = series[slice("1970-01-01", "1971-01-10")] +_ = series[slice(None, stop)] +_ = series[slice(start, None)] +_ = series[slice(start, stop)] +_ = series[slice(None)] + +model = TimeSeriesInterpolator() +_ = model[slice(start, stop)] +_ = model[slice(start, stop, step)] +_ = model[slice(start, stop, None)] + + +# test slices as a return type +def foo(flag: bool, value: DT) -> "slice[DT, None] | slice[None, DT]": + if flag: + return slice(value, None) # slice[DT, DT|Any, Any] incompatible + else: + return slice(None, value) # slice[DT|Any, DT, Any] incompatible + + +# endregion Integration tests for slices with datetimes -------------------------------- diff --git a/stdlib/@tests/test_cases/builtins/check_sum.py b/stdlib/@tests/test_cases/builtins/check_sum.py new file mode 100644 index 000000000000..2a839abbd8f5 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_sum.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import Any, Literal +from typing_extensions import assert_type + + +class Foo: + def __add__(self, other: Any) -> Foo: + return Foo() + + +class Bar: + def __radd__(self, other: Any) -> Bar: + return Bar() + + +class Baz: + def __add__(self, other: Any) -> Baz: + return Baz() + + def __radd__(self, other: Any) -> Baz: + return Baz() + + +literal_list: list[Literal[0, 1]] = [0, 1, 1] + +assert_type(sum([2, 4]), int) +assert_type(sum([3, 5], 4), int) + +assert_type(sum([True, False]), int) +assert_type(sum([True, False], True), int) +assert_type(sum(literal_list), int) + +assert_type(sum([["foo"], ["bar"]], ["baz"]), list[str]) + +assert_type(sum([Foo(), Foo()], Foo()), Foo) +assert_type(sum([Baz(), Baz()]), Baz | Literal[0]) + +# mypy and pyright infer the types differently for these, so we can't use assert_type +# Just test that no error is emitted for any of these +sum([("foo",), ("bar", "baz")], ()) # mypy: `tuple[str, ...]`; pyright: `tuple[str] | tuple[str, str] | tuple[()]` +sum([5.6, 3.2]) # mypy: `float`; pyright: `float | Literal[0]` +sum([2.5, 5.8], 5) # mypy: `float`; pyright: `float | int` + +# These all fail at runtime +sum("abcde") # type: ignore +sum([["foo"], ["bar"]]) # type: ignore +sum([("foo",), ("bar", "baz")]) # type: ignore +sum([Foo(), Foo()]) # type: ignore +sum([Bar(), Bar()], Bar()) # type: ignore +sum([Bar(), Bar()]) # type: ignore + +# TODO: these pass pyright with the current stubs, but mypy erroneously emits an error: +# sum([3, Fraction(7, 22), complex(8, 0), 9.83]) +# sum([3, Decimal("0.98")]) diff --git a/stdlib/@tests/test_cases/builtins/check_tuple.py b/stdlib/@tests/test_cases/builtins/check_tuple.py new file mode 100644 index 000000000000..ac9633135997 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_tuple.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import sys +from typing import Any +from typing_extensions import assert_type + + +# Empty tuples, see #8275 +class TupleSub(tuple[int, ...]): + pass + + +assert_type(TupleSub(), TupleSub) +assert_type(TupleSub([1, 2, 3]), TupleSub) + +# Hashability shenanigans, see #15852 +t: tuple[int, int] = (1, 3) +hash(t) +u: tuple[int, ...] = tuple(b"spam") +hash(u) +v: tuple[str] = ("",) +hash(v) +w: tuple[()] = () +hash(w) +hash(tuple(sys.platform)) +x: tuple[Any, Any] = ((), ()) +hash(x) diff --git a/stdlib/@tests/test_cases/builtins/check_type.py b/stdlib/@tests/test_cases/builtins/check_type.py new file mode 100644 index 000000000000..e29550169d99 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_type.py @@ -0,0 +1,12 @@ +from typing_extensions import assert_type + + +class Meta(type): ... + + +call = Meta.__dict__["__call__"] + +# Regression tests for https://github.com/python/typeshed/pull/16299 +assert_type(int.__subclasses__(), list[type[int]]) +assert_type(str.__subclasses__(), list[type[str]]) +assert_type(BaseException.__subclasses__(), list[type[BaseException]]) diff --git a/stdlib/@tests/test_cases/builtins/check_zip.py b/stdlib/@tests/test_cases/builtins/check_zip.py new file mode 100644 index 000000000000..c3b5997a3fd4 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_zip.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing_extensions import assert_type + +ints: Sequence[int] = [1, 2, 3] +strs: Sequence[str] = ["one", "two", "three"] +floats: Sequence[float] = [1.0, 2.0, 3.0] +str_tuples: Sequence[tuple[str]] = list((x,) for x in strs) + +assert_type(zip(ints), zip[tuple[int]]) +assert_type(zip(ints, strs), zip[tuple[int, str]]) +assert_type(zip(ints, strs, floats), zip[tuple[int, str, float]]) +assert_type(zip(strs, ints, floats, ints), zip[tuple[str, int, float, int]]) +assert_type(zip(strs, ints, floats, ints, str_tuples), zip[tuple[str, int, float, int, tuple[str]]]) diff --git a/stdlib/@tests/test_cases/check_SupportsGetItem.py b/stdlib/@tests/test_cases/check_SupportsGetItem.py new file mode 100644 index 000000000000..feb140438b2c --- /dev/null +++ b/stdlib/@tests/test_cases/check_SupportsGetItem.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from _typeshed import SupportsDunderGT, SupportsDunderLT, SupportsGetItem +from collections.abc import Callable +from operator import itemgetter +from typing import Any, TypeVar +from typing_extensions import assert_type + +_T = TypeVar("_T") + + +# This should be equivalent to itemgetter().__call__ +def standalone_call(obj: SupportsGetItem[Any, _T]) -> _T: ... + + +# Expected type of itemgetter(1).__call__ +expected_type_itemgetter_call: Callable[[SupportsGetItem[int, _T]], _T] # pyright: ignore[reportGeneralTypeIssues] + +# Expecting itemgetter(1) to be assignable to this +# based on the example below: min({"first": 1, "second": 2}.items(), key=itemgetter(1)) +# That example and assigning to this variable are what failed in https://github.com/python/mypy/issues/14032 +expected_assignable_to: Callable[[tuple[str, int]], SupportsDunderLT[Any] | SupportsDunderGT[Any]] + + +# Regression tests for https://github.com/python/mypy/issues/14032 +# assert_type(itemgetter("first")({"first": 1, "second": 2}), int) # See comment on itemgetter.__call__ +assert_type(min({"first": 1, "second": 2}, key=itemgetter(1)), str) +assert_type(min({"first": 1, "second": 2}.items(), key=itemgetter(1)), tuple[str, int]) +assert_type(standalone_call({"first": 1, "second": 2}), int) +assert_type(min({"first": 1, "second": 2}, key=standalone_call), str) +assert_type(min({"first": 1, "second": 2}.items(), key=standalone_call), tuple[str, int]) + +expected_itemgetter_call_type = itemgetter(1).__call__ +expected_itemgetter_call_type = itemgetter(1) +expected_assignable_to = itemgetter(1) + +expected_itemgetter_call_type = standalone_call +expected_assignable_to = standalone_call diff --git a/stdlib/@tests/test_cases/check_ast.py b/stdlib/@tests/test_cases/check_ast.py new file mode 100644 index 000000000000..4e99d00d6ccb --- /dev/null +++ b/stdlib/@tests/test_cases/check_ast.py @@ -0,0 +1,44 @@ +import ast +from typing_extensions import assert_type + +# Test with source code strings +assert_type(ast.parse("x = 1"), ast.Module) +assert_type(ast.parse("x = 1", mode="exec"), ast.Module) +assert_type(ast.parse("1 + 1", mode="eval"), ast.Expression) +assert_type(ast.parse("x = 1", mode="single"), ast.Interactive) +assert_type(ast.parse("(int, str) -> None", mode="func_type"), ast.FunctionType) + +# Test with mod objects - Module +mod1: ast.Module = ast.Module([], []) +assert_type(ast.parse(mod1), ast.Module) +assert_type(ast.parse(mod1, mode="exec"), ast.Module) +mod2: ast.Module = ast.Module(body=[ast.Expr(value=ast.Constant(value=42))], type_ignores=[]) +assert_type(ast.parse(mod2), ast.Module) + +# Test with mod objects - Expression +expr1: ast.Expression = ast.Expression(body=ast.Constant(value=42)) +assert_type(ast.parse(expr1, mode="eval"), ast.Expression) + +# Test with mod objects - Interactive +inter1: ast.Interactive = ast.Interactive(body=[]) +assert_type(ast.parse(inter1, mode="single"), ast.Interactive) + +# Test with mod objects - FunctionType +func1: ast.FunctionType = ast.FunctionType(argtypes=[], returns=ast.Constant(value=None)) +assert_type(ast.parse(func1, mode="func_type"), ast.FunctionType) + +# Test that any AST node can be passed and returns the same type +binop: ast.BinOp = ast.BinOp(left=ast.Constant(1), op=ast.Add(), right=ast.Constant(2)) +assert_type(ast.parse(binop), ast.BinOp) + +constant: ast.Constant = ast.Constant(value=42) +assert_type(ast.parse(constant), ast.Constant) + +expr_stmt: ast.Expr = ast.Expr(value=ast.Constant(value=42)) +assert_type(ast.parse(expr_stmt), ast.Expr) + +# Test with additional parameters +assert_type(ast.parse(mod1, filename="test.py"), ast.Module) +assert_type(ast.parse(mod1, type_comments=True), ast.Module) +assert_type(ast.parse(mod1, feature_version=(3, 10)), ast.Module) +assert_type(ast.parse(binop, filename="test.py"), ast.BinOp) diff --git a/stdlib/@tests/test_cases/check_codecs.py b/stdlib/@tests/test_cases/check_codecs.py new file mode 100644 index 000000000000..19e663ceeaaf --- /dev/null +++ b/stdlib/@tests/test_cases/check_codecs.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import codecs +from typing_extensions import assert_type + +assert_type(codecs.decode("x", "unicode-escape"), str) +assert_type(codecs.decode(b"x", "unicode-escape"), str) + +assert_type(codecs.decode(b"x", "utf-8"), str) +codecs.decode("x", "utf-8") # type: ignore + +assert_type(codecs.decode("ab", "hex"), bytes) +assert_type(codecs.decode(b"ab", "hex"), bytes) diff --git a/stdlib/@tests/test_cases/check_compression.py b/stdlib/@tests/test_cases/check_compression.py new file mode 100644 index 000000000000..7fc106f125c7 --- /dev/null +++ b/stdlib/@tests/test_cases/check_compression.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import io +import sys +from _typeshed import ReadableBuffer +from bz2 import BZ2Decompressor +from lzma import LZMADecompressor +from typing import cast +from typing_extensions import assert_type +from zlib import decompressobj + +if sys.version_info >= (3, 14): + from compression._common._streams import DecompressReader, _Decompressor, _Reader + from compression.zstd import ZstdDecompressor +else: + from _compression import DecompressReader, _Decompressor, _Reader + +### +# Tests for DecompressReader/_Decompressor +### + + +class CustomDecompressor: + def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: + return b"" + + @property + def unused_data(self) -> bytes: + return b"" + + @property + def eof(self) -> bool: + return False + + @property + def needs_input(self) -> bool: + return False + + +def accept_decompressor(d: _Decompressor) -> None: + d.decompress(b"random bytes", 0) + assert_type(d.eof, bool) + assert_type(d.unused_data, bytes) + + +fp = cast(_Reader, io.BytesIO(b"hello world")) +DecompressReader(fp, decompressobj) +DecompressReader(fp, BZ2Decompressor) +DecompressReader(fp, LZMADecompressor) +DecompressReader(fp, CustomDecompressor) +accept_decompressor(decompressobj()) +accept_decompressor(BZ2Decompressor()) +accept_decompressor(LZMADecompressor()) +accept_decompressor(CustomDecompressor()) + +if sys.version_info >= (3, 14): + DecompressReader(fp, ZstdDecompressor) + accept_decompressor(ZstdDecompressor()) diff --git a/stdlib/@tests/test_cases/check_concurrent_futures.py b/stdlib/@tests/test_cases/check_concurrent_futures.py new file mode 100644 index 000000000000..51a94b09d386 --- /dev/null +++ b/stdlib/@tests/test_cases/check_concurrent_futures.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable, Iterator +from concurrent.futures import Future, ThreadPoolExecutor, as_completed +from typing import Literal +from typing_extensions import assert_type + + +class Parent: ... + + +class Child(Parent): ... + + +def check_as_completed_covariance() -> None: + with ThreadPoolExecutor() as executor: + f1 = executor.submit(lambda: Parent()) + f2 = executor.submit(lambda: Child()) + fs: list[Future[Parent] | Future[Child]] = [f1, f2] + assert_type(as_completed(fs), Iterator[Future[Parent]]) + for future in as_completed(fs): + assert_type(future.result(), Parent) + + +def check_future_invariance() -> None: + def execute_callback(callback: Callable[[], Parent], future: Future[Parent]) -> None: + future.set_result(callback()) + + fut: Future[Child] = Future() + execute_callback(lambda: Parent(), fut) # type: ignore + assert isinstance(fut.result(), Child) + + +if sys.version_info >= (3, 14): + + def _initializer(x: int) -> None: + pass + + def check_interpreter_pool_executor() -> None: + import concurrent.futures.interpreter + from concurrent.futures import InterpreterPoolExecutor + + with InterpreterPoolExecutor(initializer=_initializer, initargs=(1,)): + ... + + with InterpreterPoolExecutor(initializer=_initializer, initargs=("x",)): # type: ignore + ... + + context = InterpreterPoolExecutor.prepare_context(initializer=_initializer, initargs=(1,)) + worker_context = context[0]() + assert_type(worker_context, concurrent.futures.interpreter.WorkerContext) + resolve_task = context[1] + # Function should enforce that the arguments are correct. + res = resolve_task(_initializer, 1) + assert_type(res, tuple[bytes, Literal["function"]]) + # When the function is a script, the arguments should be a string. + str_res = resolve_task("print('Hello, world!')") + assert_type(str_res, tuple[bytes, Literal["script"]]) + # When a script is passed, no arguments should be provided. + resolve_task("print('Hello, world!')", 1) # type: ignore + + # `WorkerContext.__init__` should accept the result of a resolved task. + concurrent.futures.interpreter.WorkerContext(initdata=res) + + # Run should also accept the result of a resolved task. + worker_context.run(res) + + def check_thread_worker_context() -> None: + import concurrent.futures.thread + + context = concurrent.futures.thread.WorkerContext.prepare(initializer=_initializer, initargs=(1,)) + worker_context = context[0]() + assert_type(worker_context, concurrent.futures.thread.WorkerContext) + resolve_task = context[1] + res = resolve_task(_initializer, (1,), {"test": 1}) + assert_type(res[1], tuple[int]) + assert_type(res[2], dict[str, int]) diff --git a/stdlib/@tests/test_cases/check_configparser.py b/stdlib/@tests/test_cases/check_configparser.py new file mode 100644 index 000000000000..28c355f385ff --- /dev/null +++ b/stdlib/@tests/test_cases/check_configparser.py @@ -0,0 +1,5 @@ +from configparser import RawConfigParser, SectionProxy +from typing_extensions import assert_type + +sp = SectionProxy(RawConfigParser(), "") +assert_type(sp.get("foo", fallback="hi"), str) diff --git a/stdlib/@tests/test_cases/check_contextlib.py b/stdlib/@tests/test_cases/check_contextlib.py new file mode 100644 index 000000000000..648661bca856 --- /dev/null +++ b/stdlib/@tests/test_cases/check_contextlib.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from contextlib import ExitStack +from typing_extensions import assert_type + + +# See issue #7961 +class Thing(ExitStack): + pass + + +stack = ExitStack() +thing = Thing() +assert_type(stack.enter_context(Thing()), Thing) +assert_type(thing.enter_context(ExitStack()), ExitStack) + +with stack as cm: + assert_type(cm, ExitStack) +with thing as cm2: + assert_type(cm2, Thing) diff --git a/stdlib/@tests/test_cases/check_copy.py b/stdlib/@tests/test_cases/check_copy.py new file mode 100644 index 000000000000..59896851d737 --- /dev/null +++ b/stdlib/@tests/test_cases/check_copy.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import copy +import sys +from typing import Generic, TypeVar +from typing_extensions import Self, assert_type + + +class ReplaceableClass: + def __init__(self, val: int) -> None: + self.val = val + + def __replace__(self, /, *, val: int) -> Self: + cpy = copy.copy(self) + cpy.val = val + return cpy + + +if sys.version_info >= (3, 13): + obj = ReplaceableClass(42) + cpy = copy.replace(obj, val=23) + assert_type(cpy, ReplaceableClass) + + +_T_co = TypeVar("_T_co", covariant=True) + + +class Box(Generic[_T_co]): + def __init__(self, value: _T_co, /) -> None: + self.value = value + + def __replace__(self, /, *, value: str) -> Box[str]: + return Box(value) + + +if sys.version_info >= (3, 13): + box1: Box[int] = Box(42) + box2 = copy.replace(box1, value="spam") + assert_type(box2, Box[str]) diff --git a/stdlib/@tests/test_cases/check_dataclasses.py b/stdlib/@tests/test_cases/check_dataclasses.py new file mode 100644 index 000000000000..cb2a112dbb42 --- /dev/null +++ b/stdlib/@tests/test_cases/check_dataclasses.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import dataclasses as dc +import sys +from typing import TYPE_CHECKING, Any +from typing_extensions import Annotated, assert_type + +if TYPE_CHECKING: + from _typeshed import DataclassInstance + + +@dc.dataclass +class Foo: + attr: str + + +assert_type(dc.fields(Foo), tuple[dc.Field[Any], ...]) + +dc.asdict(Foo) # type: ignore +dc.astuple(Foo) # type: ignore +dc.replace(Foo) # type: ignore + +# See #9723 for why we can't make this assertion +# if dc.is_dataclass(Foo): +# assert_type(Foo, type[Foo]) + +f = Foo(attr="attr") + +assert_type(dc.fields(f), tuple[dc.Field[Any], ...]) +assert_type(dc.asdict(f), dict[str, Any]) +assert_type(dc.astuple(f), tuple[Any, ...]) +assert_type(dc.replace(f, attr="new"), Foo) + +if dc.is_dataclass(f): + # The inferred type doesn't change + # if it's already known to be a subtype of _DataclassInstance + assert_type(f, Foo) + + +def is_dataclass_any(arg: Any) -> None: + if dc.is_dataclass(arg): + assert_type(arg, DataclassInstance | type[DataclassInstance]) + + +def is_dataclass_object(arg: object) -> None: + if dc.is_dataclass(arg): + assert_type(arg, DataclassInstance | type[DataclassInstance]) + + +def is_dataclass_type(arg: type) -> None: + if dc.is_dataclass(arg): + assert_type(arg, type[DataclassInstance]) + + +def check_other_isdataclass_overloads(x: type, y: object) -> None: + # TODO: neither pyright nor mypy emit error on this -- why? + # dc.fields(x) + + dc.fields(y) # type: ignore + + dc.asdict(x) # type: ignore + dc.asdict(y) # type: ignore + + dc.astuple(x) # type: ignore + dc.astuple(y) # type: ignore + + dc.replace(x) # type: ignore + dc.replace(y) # type: ignore + + if dc.is_dataclass(x): + assert_type(x, type[DataclassInstance]) + assert_type(dc.fields(x), tuple[dc.Field[Any], ...]) + + dc.asdict(x) # type: ignore + dc.astuple(x) # type: ignore + dc.replace(x) # type: ignore + + if dc.is_dataclass(y): + assert_type(y, DataclassInstance | type[DataclassInstance]) + assert_type(dc.fields(y), tuple[dc.Field[Any], ...]) + + dc.asdict(y) # type: ignore + dc.astuple(y) # type: ignore + dc.replace(y) # type: ignore + + if dc.is_dataclass(y) and not isinstance(y, type): + assert_type(y, DataclassInstance) + assert_type(dc.fields(y), tuple[dc.Field[Any], ...]) + assert_type(dc.asdict(y), dict[str, Any]) + assert_type(dc.astuple(y), tuple[Any, ...]) + dc.replace(y) + + +class _D: ... + + +custom_dc = dc.dataclass(_D, init=True) +assert_type(custom_dc, type[_D]) + +custom_dc_2 = dc.dataclass(None, init=True)(_D) +assert_type(custom_dc_2, type[_D]) + + +# Regression test for #11653 +D = dc.make_dataclass( + "D", [("a", int | None), "y", ("z", Annotated[frozenset[bytes], "metadata"], dc.field(default=frozenset({b"foo"})))] +) +# Check that it's inferred by the type checker as a class object of some kind +# (but don't assert the exact type that `D` is inferred as, +# in case a type checker decides to add some special-casing for +# `make_dataclass` in the future) +assert_type(D.__mro__, tuple[type, ...]) + + +if sys.version_info >= (3, 14): + from typing import TypeVar + + _T = TypeVar("_T") + + def custom_dataclass( + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type[_T]: + custom_dc_maker = dc.dataclass( + init=init, + repr=repr, + eq=eq, + order=order, + unsafe_hash=unsafe_hash, + frozen=frozen, + match_args=match_args, + kw_only=kw_only, + slots=slots, + weakref_slot=weakref_slot, + ) + return custom_dc_maker(cls) + + dc.make_dataclass( + "D", + [("a", int | None), "y", ("z", Annotated[frozenset[bytes], "metadata"], dc.field(default=frozenset({b"foo"})))], + decorator=custom_dataclass, + ) diff --git a/stdlib/@tests/test_cases/check_enum.py b/stdlib/@tests/test_cases/check_enum.py new file mode 100644 index 000000000000..6de68a560263 --- /dev/null +++ b/stdlib/@tests/test_cases/check_enum.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import enum +import sys +from typing import Literal, Type +from typing_extensions import assert_type + +A = enum.Enum("A", "spam eggs bacon") +B = enum.Enum("B", ["spam", "eggs", "bacon"]) +C = enum.Enum("C", [("spam", 1), ("eggs", 2), ("bacon", 3)]) +D = enum.Enum("D", {"spam": 1, "eggs": 2}) + +assert_type(A, Type[A]) +assert_type(B, Type[B]) +assert_type(C, Type[C]) +assert_type(D, Type[D]) + + +class EnumOfTuples(enum.Enum): + X = 1, 2, 3 + Y = 4, 5, 6 + + +assert_type(EnumOfTuples((1, 2, 3)), EnumOfTuples) + +# TODO: ideally this test would pass: +# +# if sys.version_info >= (3, 12): +# assert_type(EnumOfTuples(1, 2, 3), EnumOfTuples) + + +if sys.version_info >= (3, 11): + + class Foo(enum.StrEnum): + X = enum.auto() + + assert_type(Foo.X, Literal[Foo.X]) + assert_type(Foo.X.value, str) diff --git a/stdlib/@tests/test_cases/check_functools.py b/stdlib/@tests/test_cases/check_functools.py new file mode 100644 index 000000000000..93b8fe1cf3bc --- /dev/null +++ b/stdlib/@tests/test_cases/check_functools.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +from functools import cache, cached_property, lru_cache, wraps +from typing import Callable, ParamSpec, TypeVar +from typing_extensions import assert_type + +P = ParamSpec("P") +T_co = TypeVar("T_co", covariant=True) + +# +# Tests for @wraps +# + + +def my_decorator(func: Callable[P, T_co]) -> Callable[P, T_co]: + @wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T_co: + print(args) + return func(*args, **kwargs) + + # verify that the wrapped function has all these attributes + wrapper.__annotations__ = func.__annotations__ + wrapper.__doc__ = func.__doc__ + wrapper.__module__ = func.__module__ + wrapper.__name__ = func.__name__ + wrapper.__qualname__ = func.__qualname__ + return wrapper + + +def check_wraps_function() -> None: + def wrapped(x: int) -> None: ... + @wraps(wrapped) + def identical_wrapper(x: int) -> None: ... + @wraps(wrapped) + def other_signature_wrapper(x: str, y: float) -> None: ... + + identical_wrapper(3) + other_signature_wrapper("parrot", 42.0) + + +def check_wraps_method() -> None: + class Wrapped: + def wrapped(self, x: int) -> None: ... + @wraps(wrapped) + def wrapper(self, x: int) -> None: ... + + class Wrapper: # pyright: ignore[reportUnusedClass] + @wraps(Wrapped.wrapped) + def method(self, x: int) -> None: ... + + @wraps(Wrapped.wrapped) + def func_wrapper(x: int) -> None: ... + + # TODO: The following should work, but currently don't. + # https://github.com/python/typeshed/issues/10653 + # Wrapped().wrapper(3) + # Wrapper().method(3) + func_wrapper(3) + + +# +# Tests for @cache +# + + +@cache +def check_cache(x: int) -> int: + return x * 2 + + +assert_type(check_cache(3), int) +# Type checkers should check the argument type, but this is currently not +# possible. See https://github.com/python/typeshed/issues/6347 and +# https://github.com/python/typeshed/issues/11280. +# check_cached("invalid") # xtype: ignore + +assert_type(check_cache.cache_info().misses, int) + + +# +# Tests for @lru_cache +# + + +@lru_cache +def check_lru_cache(x: int) -> int: + return x * 2 + + +@lru_cache(maxsize=32) +def check_lru_cache_with_maxsize(x: int) -> int: + return x * 2 + + +assert_type(check_lru_cache(3), int) +assert_type(check_lru_cache_with_maxsize(3), int) +# Type checkers should check the argument type, but this is currently not +# possible. See https://github.com/python/typeshed/issues/6347 and +# https://github.com/python/typeshed/issues/11280. +# check_lru_cache("invalid") # xtype: ignore +# check_lru_cache_with_maxsize("invalid") # xtype: ignore + +assert_type(check_lru_cache.cache_info().misses, int) +assert_type(check_lru_cache_with_maxsize.cache_info().misses, int) + + +# +# Tests for @cached_property +# + + +class A: + def __init__(self, x: int): + self.x = x + + @cached_property + def x(self) -> int: + return 0 + + +assert_type(A(x=1).x, int) + + +class B: + @cached_property + def x(self) -> int: + return 0 + + +def check_cached_property_settable(x: int) -> None: + b = B() + assert_type(b.x, int) + b.x = x + assert_type(b.x, int) + + +# https://github.com/python/typeshed/issues/10048 +class Parent: ... + + +class Child(Parent): ... + + +class X: + @cached_property + def some(self) -> Parent: + return Parent() + + +class Y(X): + @cached_property + def some(self) -> Child: # safe override + return Child() + + +class CachedParent: + @cache + def method(self) -> Parent: + return Parent() + + +class CachedChild(CachedParent): + @cache + def method(self) -> Child: + return Child() diff --git a/stdlib/@tests/test_cases/check_hashlib.py b/stdlib/@tests/test_cases/check_hashlib.py new file mode 100644 index 000000000000..32e8451b615e --- /dev/null +++ b/stdlib/@tests/test_cases/check_hashlib.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +import _hashlib +import hashlib +import sys +from _hashlib import HASH, HASHXOF +from io import BytesIO +from typing_extensions import assert_type + + +def check_new(name: str) -> None: + for shake in ( + hashlib.new("shake_128"), + hashlib.new("shake_256"), + hashlib.new("SHAKE-128", b"data", usedforsecurity=False), + hashlib.new("SHAKE-256"), + ): + assert_type(shake, HASHXOF) + assert_type(shake.copy(), HASHXOF) + assert_type(shake.digest(16), bytes) + assert_type(shake.hexdigest(length=16), str) + shake.digest() # type: ignore + shake.hexdigest() # type: ignore + + fixed = hashlib.new("sha256") + assert_type(fixed, HASH) + assert_type(fixed.digest(), bytes) + fixed.digest(16) # type: ignore + + dynamic = hashlib.new(name) + assert_type(dynamic.digest(), bytes) + assert_type(dynamic.digest(16), bytes) + assert_type(dynamic.copy().hexdigest(length=16), str) + dynamic.digest("16") # type: ignore + + assert_type(_hashlib.new("shake_128", string=b"data").digest(16), bytes) + assert_type(_hashlib.new("SHAKE-256").hexdigest(16), str) + assert_type(_hashlib.new("MD5"), HASH) + assert_type(_hashlib.new(name).hexdigest(16), str) + if sys.version_info >= (3, 13): + assert_type(_hashlib.new("shake_256", data=b"data").copy(), HASHXOF) + + if sys.version_info >= (3, 11): + hashlib.file_digest(BytesIO(b"data"), lambda: hashlib.new("sha256")) diff --git a/stdlib/@tests/test_cases/check_importlib.py b/stdlib/@tests/test_cases/check_importlib.py new file mode 100644 index 000000000000..3f226b5dbe8f --- /dev/null +++ b/stdlib/@tests/test_cases/check_importlib.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import importlib.util +import pathlib +import sys +import zipfile +from collections.abc import Sequence +from importlib.machinery import ModuleSpec +from types import ModuleType +from typing_extensions import Self + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: + from importlib.abc import Traversable + + +# Assert that some Path classes are Traversable. +def traverse(t: Traversable) -> None: + pass + + +traverse(pathlib.Path()) +traverse(zipfile.Path("")) + + +class MetaFinder: + @classmethod + def find_spec(cls, fullname: str, path: Sequence[str] | None, target: ModuleType | None = None) -> ModuleSpec | None: + return None # simplified mock for demonstration purposes only + + +class PathFinder: + @classmethod + def path_hook(cls, path_entry: str) -> type[Self]: + return cls # simplified mock for demonstration purposes only + + @classmethod + def find_spec(cls, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: + return None # simplified mock for demonstration purposes only + + +class Loader: + @classmethod + def load_module(cls, fullname: str) -> ModuleType: + return ModuleType(fullname) + + +sys.meta_path.append(MetaFinder) +sys.path_hooks.append(PathFinder.path_hook) +importlib.util.spec_from_loader("xxxx42xxxx", Loader) diff --git a/stdlib/@tests/test_cases/check_importlib_metadata.py b/stdlib/@tests/test_cases/check_importlib_metadata.py new file mode 100644 index 000000000000..8f50496cbd69 --- /dev/null +++ b/stdlib/@tests/test_cases/check_importlib_metadata.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from _typeshed import StrPath +from importlib.metadata._meta import SimplePath +from os import PathLike +from pathlib import Path +from zipfile import Path as ZipPath + + +# Simplified version of zipfile.Path +class MyPath: + @property + def parent(self) -> PathLike[str]: ... # undocumented + + def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, *other: StrPath) -> MyPath: ... + def __truediv__(self, add: StrPath) -> MyPath: ... + def exists(self) -> bool: ... + + +def takes_simple_path(p: SimplePath) -> None: ... + + +takes_simple_path(Path()) +takes_simple_path(ZipPath("")) +takes_simple_path(MyPath()) +takes_simple_path("some string") # type: ignore diff --git a/stdlib/@tests/test_cases/check_importlib_resources.py b/stdlib/@tests/test_cases/check_importlib_resources.py new file mode 100644 index 000000000000..862456a017e9 --- /dev/null +++ b/stdlib/@tests/test_cases/check_importlib_resources.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import sys + + +class _CustomPathLike: + def __fspath__(self) -> str: + return "" + + +if sys.version_info >= (3, 13): + import importlib.resources + import pathlib + + def f(pth: pathlib.Path | str | _CustomPathLike) -> None: + importlib.resources.open_binary("pkg", pth) + # Encoding defaults to "utf-8" for one arg. + importlib.resources.open_text("pkg", pth) + # Otherwise, it must be specified. + importlib.resources.open_text("pkg", pth, pth) # type: ignore + importlib.resources.open_text("pkg", pth, pth, encoding="utf-8") + + # Encoding defaults to "utf-8" for one arg. + importlib.resources.read_text("pkg", pth) + # Otherwise, it must be specified. + importlib.resources.read_text("pkg", pth, pth) # type: ignore + importlib.resources.read_text("pkg", pth, pth, encoding="utf-8") + + importlib.resources.read_binary("pkg", pth) + importlib.resources.path("pkg", pth) + importlib.resources.is_resource("pkg", pth) + importlib.resources.contents("pkg", pth) # pyright: ignore[reportDeprecated] diff --git a/stdlib/@tests/test_cases/check_inspect.py b/stdlib/@tests/test_cases/check_inspect.py new file mode 100644 index 000000000000..3723739ac537 --- /dev/null +++ b/stdlib/@tests/test_cases/check_inspect.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import inspect +from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine, Generator +from typing import Any +from typing_extensions import assert_type + + +def test_iscoroutinefunction_inspect( + x: Callable[[str, int], Coroutine[str, int, bytes]], + y: Callable[[str, int], Awaitable[bytes]], + z: Callable[[str, int], str | Awaitable[bytes]], + xx: object, +) -> None: + if inspect.iscoroutinefunction(x): + assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) + + if inspect.iscoroutinefunction(y): + assert_type(y, Callable[[str, int], Coroutine[Any, Any, bytes]]) + + if inspect.iscoroutinefunction(z): + assert_type(z, Callable[[str, int], Coroutine[Any, Any, Any]]) + + if inspect.iscoroutinefunction(xx): + assert_type(xx, Callable[..., Coroutine[Any, Any, Any]]) + + +def test_isgeneratorfunction_inspect(x: Callable[[str], object], y: object) -> None: + if inspect.isgeneratorfunction(x): + assert_type(x, Callable[[str], Generator[Any, Any, Any]]) + if inspect.isgeneratorfunction(y): + assert_type(y, Callable[..., Generator[Any, Any, Any]]) + + +def test_isasyncgenfunction_inspect(x: Callable[[str], object], y: object) -> None: + if inspect.isasyncgenfunction(x): + assert_type(x, Callable[[str], AsyncGenerator[Any, Any]]) + if inspect.isasyncgenfunction(y): + assert_type(y, Callable[..., AsyncGenerator[Any, Any]]) diff --git a/stdlib/@tests/test_cases/check_io.py b/stdlib/@tests/test_cases/check_io.py new file mode 100644 index 000000000000..c3ee5aa4c6c0 --- /dev/null +++ b/stdlib/@tests/test_cases/check_io.py @@ -0,0 +1,18 @@ +from _io import BufferedReader, BufferedRWPair, BufferedWriter +from gzip import GzipFile +from io import FileIO, RawIOBase, TextIOWrapper +from socket import SocketIO +from typing import Any +from typing_extensions import assert_type + +socket: Any = None + +BufferedReader(RawIOBase()) +BufferedWriter(RawIOBase()) +BufferedWriter(SocketIO(socket, "r")) + +BufferedRWPair(open("", "rb"), open("", "wb")) + +assert_type(TextIOWrapper(FileIO("")).buffer, FileIO) +assert_type(TextIOWrapper(FileIO(13)).detach(), FileIO) +assert_type(TextIOWrapper(GzipFile("")).buffer, GzipFile) diff --git a/stdlib/@tests/test_cases/check_logging.py b/stdlib/@tests/test_cases/check_logging.py new file mode 100644 index 000000000000..a7d57cbda132 --- /dev/null +++ b/stdlib/@tests/test_cases/check_logging.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import logging +import logging.handlers +import multiprocessing +import queue +from typing import Any + +# This pattern comes from the logging docs, and should therefore pass a type checker +# See https://docs.python.org/3/library/logging.html#logrecord-objects + +old_factory = logging.getLogRecordFactory() + + +def record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord: + record = old_factory(*args, **kwargs) + record.custom_attribute = 0xDECAFBAD + return record + + +logging.setLogRecordFactory(record_factory) + +# The logging docs say that QueueHandler and QueueListener can take "any queue-like object" +# We test that here (regression test for #10168) +logging.handlers.QueueHandler(queue.Queue()) +logging.handlers.QueueHandler(queue.SimpleQueue()) +logging.handlers.QueueHandler(multiprocessing.Queue()) +logging.handlers.QueueListener(queue.Queue()) +logging.handlers.QueueListener(queue.SimpleQueue()) +logging.handlers.QueueListener(multiprocessing.Queue()) + +# These all raise at runtime. +logging.basicConfig(filename="foo.log", handlers=[]) # type: ignore +logging.basicConfig(filemode="w", handlers=[]) # type: ignore +logging.basicConfig(stream=None, handlers=[]) # type: ignore +logging.basicConfig(filename="foo.log", stream=None) # type: ignore +logging.basicConfig(filename=None, stream=None) # type: ignore +# These are ok. +logging.basicConfig() +logging.basicConfig(handlers=[]) +logging.basicConfig(filename="foo.log", filemode="w") +logging.basicConfig(filename="foo.log", filemode="w", handlers=None) +logging.basicConfig(stream=None) +logging.basicConfig(stream=None, handlers=None) +# dubious but accepted, has same meaning as 'stream=None'. +logging.basicConfig(filename=None) +# These are technically accepted at runtime, but are forbidden in the stubs to help +# prevent user mistakes. Passing 'filemode' / 'encoding' / 'errors' does nothing +# if 'filename' is not specified. +logging.basicConfig(stream=None, filemode="w") # type: ignore +logging.basicConfig(stream=None, encoding="utf-8") # type: ignore +logging.basicConfig(stream=None, errors="strict") # type: ignore +logging.basicConfig(handlers=[], encoding="utf-8") # type: ignore +logging.basicConfig(handlers=[], errors="strict") # type: ignore diff --git a/stdlib/@tests/test_cases/check_mailbox.py b/stdlib/@tests/test_cases/check_mailbox.py new file mode 100644 index 000000000000..03efe9520dd3 --- /dev/null +++ b/stdlib/@tests/test_cases/check_mailbox.py @@ -0,0 +1,13 @@ +import mailbox + + +def mbox1() -> mailbox.Mailbox: + return mailbox.mbox("") + + +def mbox2() -> mailbox.Mailbox[mailbox.mboxMessage]: + return mailbox.mbox("") + + +def mbox3() -> mailbox.Mailbox[mailbox.Message]: + return mailbox.mbox("") diff --git a/stdlib/@tests/test_cases/check_math.py b/stdlib/@tests/test_cases/check_math.py new file mode 100644 index 000000000000..5cba72589f42 --- /dev/null +++ b/stdlib/@tests/test_cases/check_math.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from decimal import Decimal +from fractions import Fraction +from math import prod +from typing import Any, Literal +from typing_extensions import assert_type + + +class SupportsMul: + def __mul__(self, other: Any) -> SupportsMul: + return SupportsMul() + + +class SupportsRMul: + def __rmul__(self, other: Any) -> SupportsRMul: + return SupportsRMul() + + +class SupportsMulAndRMul: + def __mul__(self, other: Any) -> SupportsMulAndRMul: + return SupportsMulAndRMul() + + def __rmul__(self, other: Any) -> SupportsMulAndRMul: + return SupportsMulAndRMul() + + +literal_list: list[Literal[0, 1]] = [0, 1, 1] + +assert_type(prod([2, 4]), int) +assert_type(prod([3, 5], start=4), int) + +assert_type(prod([True, False]), int) +assert_type(prod([True, False], start=True), int) +assert_type(prod(literal_list), int) + +assert_type(prod([SupportsMul(), SupportsMul()], start=SupportsMul()), SupportsMul) +assert_type(prod([SupportsMulAndRMul(), SupportsMulAndRMul()]), SupportsMulAndRMul | Literal[1]) + +assert_type(prod([5.6, 3.2]), float | Literal[1]) +assert_type(prod([5.6, 3.2], start=3), float | int) + +assert_type(prod([Fraction(7, 2), Fraction(3, 5)]), Fraction | Literal[1]) +assert_type(prod([Fraction(7, 2), Fraction(3, 5)], start=Fraction(1)), Fraction) +assert_type(prod([Decimal("3.14"), Decimal("2.71")]), Decimal | Literal[1]) +assert_type(prod([Decimal("3.14"), Decimal("2.71")], start=Decimal("1.00")), Decimal) +assert_type(prod([complex(7, 2), complex(3, 5)]), complex | Literal[1]) +assert_type(prod([complex(7, 2), complex(3, 5)], start=complex(1, 0)), complex) + + +# mypy and pyright infer the types differently for these, so we can't use assert_type +# Just test that no error is emitted for any of these +prod([5.6, 3.2]) # mypy: `float`; pyright: `float | Literal[0]` +prod([2.5, 5.8], start=5) # mypy: `float`; pyright: `float | int` + +# These all fail at runtime +prod([SupportsMul(), SupportsMul()]) # type: ignore +prod([SupportsRMul(), SupportsRMul()], start=SupportsRMul()) # type: ignore +prod([SupportsRMul(), SupportsRMul()]) # type: ignore + +# TODO: these pass pyright with the current stubs, but mypy erroneously emits an error: +# prod([3, Fraction(7, 22), complex(8, 0), 9.83]) +# prod([3, Decimal("0.98")]) diff --git a/stdlib/@tests/test_cases/check_os_path.py b/stdlib/@tests/test_cases/check_os_path.py new file mode 100644 index 000000000000..dcaabca0b712 --- /dev/null +++ b/stdlib/@tests/test_cases/check_os_path.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from _typeshed import StrOrBytesPath +from os import PathLike +from os.path import abspath, expanduser, expandvars +from typing import AnyStr +from typing_extensions import assert_type + + +def test_str_path(str_path: StrOrBytesPath) -> None: + # These methods are currently overloaded to work around python/mypy#17952 & python/mypy#11880 + # Let's ensure that they'll still work with a StrOrBytesPath if the workaround is removed + + assert_type(abspath(str_path), str | bytes) + assert_type(expanduser(str_path), str | bytes) + assert_type(expandvars(str_path), str | bytes) + + +# See python/mypy#17952 +class MyPathMissingGeneric(PathLike): # type: ignore # Explicitly testing w/ missing type argument + def __init__(self, path: str | bytes) -> None: + super().__init__() + self.path = path + + def __fspath__(self) -> str | bytes: + return self.path + + +# MyPathMissingGeneric could also be fixed by users by adding the missing generic annotation +class MyPathGeneric(PathLike[AnyStr]): + def __init__(self, path: AnyStr) -> None: + super().__init__() + self.path: AnyStr = path + + def __fspath__(self) -> AnyStr: + return self.path + + +class MyPathStr(PathLike[str]): + def __init__(self, path: str) -> None: + super().__init__() + self.path = path + + def __fspath__(self) -> str: + return self.path + + +abspath(MyPathMissingGeneric(".")) +expanduser(MyPathMissingGeneric(".")) +expandvars(MyPathMissingGeneric(".")) + +abspath(MyPathGeneric(".")) +expanduser(MyPathGeneric(".")) +expandvars(MyPathGeneric(".")) + +abspath(MyPathStr(".")) +expanduser(MyPathStr(".")) +expandvars(MyPathStr(".")) diff --git a/stdlib/@tests/test_cases/check_pathlib.py b/stdlib/@tests/test_cases/check_pathlib.py new file mode 100644 index 000000000000..d3e85188b97b --- /dev/null +++ b/stdlib/@tests/test_cases/check_pathlib.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import sys +from pathlib import Path, PureWindowsPath +from typing_extensions import assert_type + + +class MyCustomPath(Path): ... + + +if Path("asdf") == Path("asdf"): + ... + +# https://github.com/python/typeshed/issues/10661 +# Provide a true positive error when comparing Path to str +# mypy should report a comparison-overlap error with --strict-equality, +# and pyright should report a reportUnnecessaryComparison error +if Path("asdf") == "asdf": # type: ignore + ... + +# Errors on comparison here are technically false positives. However, this comparison is a little +# interesting: it can never hold true on Posix, but could hold true on Windows. We should experiment +# with more accurate __new__, such that we only get an error for such comparisons on platforms +# where they can never hold true. +if PureWindowsPath("asdf") == Path("asdf"): # type: ignore + ... + + +if sys.version_info >= (3, 13): + pth = MyCustomPath.from_uri("file:///tmp/abc.txt") + assert_type(pth, MyCustomPath) + + +if sys.version_info >= (3, 14): + pth = MyCustomPath("asdf") + # With text path, type should be preserved. + assert_type(pth.move_into("asdf"), MyCustomPath) + assert_type(pth.move("asdf"), MyCustomPath) + assert_type(pth.copy("asdf"), MyCustomPath) + assert_type(pth.copy_into("asdf"), MyCustomPath) + + # With an actual path type, that type should be preserved. + assert_type(pth.move_into(Path("asdf")), Path) + assert_type(pth.move(Path("asdf")), Path) + assert_type(pth.copy(Path("asdf")), Path) + assert_type(pth.copy_into(Path("asdf")), Path) diff --git a/stdlib/@tests/test_cases/check_platform.py b/stdlib/@tests/test_cases/check_platform.py new file mode 100644 index 000000000000..9d2c83ce2815 --- /dev/null +++ b/stdlib/@tests/test_cases/check_platform.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import platform +from typing_extensions import assert_type + +# platform.uname_result emulates a 6 field named tuple, but on 3.9+ the processor +# field is lazily evaluated, which results in it being a little funky. +uname = platform.uname() +myuname = platform.uname_result("Darwin", "local", "22.5.0", "Darwin Kernel Version 22.5.0", "arm64") + +assert_type(uname, platform.uname_result) +assert_type(myuname, platform.uname_result) + +assert_type(uname[5], str) +assert_type(myuname[5], str) diff --git a/stdlib/@tests/test_cases/check_re.py b/stdlib/@tests/test_cases/check_re.py new file mode 100644 index 000000000000..dee87b474fe2 --- /dev/null +++ b/stdlib/@tests/test_cases/check_re.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import mmap +import re +from typing import AnyStr, Match, Optional +from typing_extensions import assert_type + + +def check_search(str_pat: re.Pattern[str], bytes_pat: re.Pattern[bytes]) -> None: + assert_type(str_pat.search("x"), Optional[Match[str]]) + assert_type(bytes_pat.search(b"x"), Optional[Match[bytes]]) + assert_type(bytes_pat.search(bytearray(b"x")), Optional[Match[bytes]]) + assert_type(bytes_pat.search(mmap.mmap(0, 10)), Optional[Match[bytes]]) + + +def check_search_with_AnyStr(pattern: re.Pattern[AnyStr], string: AnyStr) -> re.Match[AnyStr]: + """See issue #9591""" + match = pattern.search(string) + if match is None: + raise ValueError(f"'{string!r}' does not match {pattern!r}") + return match + + +def check_no_ReadableBuffer_false_negatives() -> None: + re.compile("foo").search(bytearray(b"foo")) # type: ignore + re.compile("foo").search(mmap.mmap(0, 10)) # type: ignore diff --git a/stdlib/@tests/test_cases/check_socket.py b/stdlib/@tests/test_cases/check_socket.py new file mode 100644 index 000000000000..096bc23c1431 --- /dev/null +++ b/stdlib/@tests/test_cases/check_socket.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import socket +from typing_extensions import assert_type + + +def check_getaddrinfo() -> None: + # The address family (item 0) is a tag that discriminates the sockaddr (item 4). + for info in socket.getaddrinfo("localhost", 80): + if info[0] == socket.AddressFamily.AF_INET: + assert_type(info[4], "tuple[str, int]") + elif info[0] == socket.AddressFamily.AF_INET6: + assert_type(info[4], "tuple[str, int, int, int] | tuple[int, bytes]") diff --git a/stdlib/@tests/test_cases/check_sqlite3.py b/stdlib/@tests/test_cases/check_sqlite3.py new file mode 100644 index 000000000000..3ec47ceccb90 --- /dev/null +++ b/stdlib/@tests/test_cases/check_sqlite3.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import sqlite3 +from typing_extensions import assert_type + + +class MyConnection(sqlite3.Connection): + pass + + +# Default return-type is Connection. +assert_type(sqlite3.connect(":memory:"), sqlite3.Connection) + +# Providing an alternate factory changes the return-type. +assert_type(sqlite3.connect(":memory:", factory=MyConnection), MyConnection) + +# Provides a true positive error. When checking the connect() function, +# mypy should report an arg-type error for the factory argument. +with sqlite3.connect(":memory:", factory=None) as con: # type: ignore + pass + +# The Connection class also accepts a `factory` arg but it does not affect +# the return-type. This use case is not idiomatic--connections should be +# established using the `connect()` function, not directly (as shown here). +assert_type(sqlite3.Connection(":memory:", factory=None), sqlite3.Connection) +assert_type(sqlite3.Connection(":memory:", factory=MyConnection), sqlite3.Connection) diff --git a/stdlib/@tests/test_cases/check_tarfile.py b/stdlib/@tests/test_cases/check_tarfile.py new file mode 100644 index 000000000000..05d9207aaec9 --- /dev/null +++ b/stdlib/@tests/test_cases/check_tarfile.py @@ -0,0 +1,17 @@ +import lzma +import tarfile + +with tarfile.open("test.tar.xz", "w:xz") as tar: + pass + +# Test with valid preset values +tarfile.open("test.tar.xz", "w:xz", preset=0) +tarfile.open("test.tar.xz", "w:xz", preset=5) +tarfile.open("test.tar.xz", "w:xz", preset=9) + +# The preset may be combined with PRESET_EXTREME, as in lzma and TarFile.xzopen +tarfile.open("test.tar.xz", "w:xz", preset=9 | lzma.PRESET_EXTREME) + +# Test pipe modes +tarfile.open("test.tar.xz", "r|*") +tarfile.open("test.tar.xz", mode="r|*") diff --git a/stdlib/@tests/test_cases/check_tempfile.py b/stdlib/@tests/test_cases/check_tempfile.py new file mode 100644 index 000000000000..c259c192a140 --- /dev/null +++ b/stdlib/@tests/test_cases/check_tempfile.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import io +import sys +from tempfile import TemporaryFile, _TemporaryFileWrapper +from typing_extensions import assert_type + +if sys.platform == "win32": + assert_type(TemporaryFile(), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("w+"), _TemporaryFileWrapper[str]) + assert_type(TemporaryFile("w+b"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("wb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("rb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("wb", 0), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(mode="w+"), _TemporaryFileWrapper[str]) + assert_type(TemporaryFile(mode="w+b"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(mode="wb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(mode="rb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(buffering=0), _TemporaryFileWrapper[bytes]) +else: + assert_type(TemporaryFile(), io.BufferedRandom) + assert_type(TemporaryFile("w+"), io.TextIOWrapper) + assert_type(TemporaryFile("w+b"), io.BufferedRandom) + assert_type(TemporaryFile("wb"), io.BufferedWriter) + assert_type(TemporaryFile("rb"), io.BufferedReader) + assert_type(TemporaryFile("wb", 0), io.FileIO) + assert_type(TemporaryFile(mode="w+"), io.TextIOWrapper) + assert_type(TemporaryFile(mode="w+b"), io.BufferedRandom) + assert_type(TemporaryFile(mode="wb"), io.BufferedWriter) + assert_type(TemporaryFile(mode="rb"), io.BufferedReader) + assert_type(TemporaryFile(buffering=0), io.FileIO) diff --git a/stdlib/@tests/test_cases/check_threading.py b/stdlib/@tests/test_cases/check_threading.py new file mode 100644 index 000000000000..eddfc2549a64 --- /dev/null +++ b/stdlib/@tests/test_cases/check_threading.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +import _threading_local +import threading + +loc = threading.local() +loc.foo = 42 +del loc.foo +loc.baz = ["spam", "eggs"] +del loc.baz + +l2 = _threading_local.local() +l2.asdfasdf = 56 +del l2.asdfasdf diff --git a/stdlib/@tests/test_cases/check_tkinter.py b/stdlib/@tests/test_cases/check_tkinter.py new file mode 100644 index 000000000000..62ba0d11f045 --- /dev/null +++ b/stdlib/@tests/test_cases/check_tkinter.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import sys +import tkinter +import traceback +import types +from typing_extensions import assert_type + + +def custom_handler(exc: type[BaseException], val: BaseException, tb: types.TracebackType | None) -> None: + print("oh no") + + +root = tkinter.Tk() +root.report_callback_exception = traceback.print_exception +root.report_callback_exception = custom_handler + + +def foo(x: int, y: str) -> None: + pass + + +root.after(1000, foo, 10, "lol") +root.after(1000, foo, 10, 10) # type: ignore + +# Font size must be integer +label = tkinter.Label() +label.config(font=("", 12)) +label.config(font=("", 12.34)) # type: ignore +label.config(font=("", 12, "bold")) +label.config(font=("", 12.34, "bold")) # type: ignore + + +# Test the `.count()` method. Comments show values that are returned at runtime. +t = tkinter.Text() +t.insert("end", "asd asd asd\nasd asd") + +assert_type(t.count("1.0", "2.3"), tuple[int] | None) # (15,) +assert_type(t.count("2.3", "2.3"), tuple[int] | None) # None +assert_type(t.count("1.0", "2.3", "indices"), tuple[int] | None) # (15,) +assert_type(t.count("2.3", "2.3", "indices"), tuple[int] | None) # None +assert_type(t.count("1.0", "2.3", "indices", "update"), int | None) # 15 +assert_type(t.count("2.3", "2.3", "indices", "update"), int | None) # None +assert_type(t.count("1.0", "2.3", "indices", "lines"), tuple[int, int]) # (15, 1) +assert_type(t.count("2.3", "2.3", "indices", "lines"), tuple[int, int]) # (0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "update"), tuple[int, ...]) # (15, 1) +assert_type(t.count("2.3", "2.3", "indices", "lines", "update"), tuple[int, ...]) # (0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "chars"), tuple[int, ...]) # (15, 1, 15) +assert_type(t.count("2.3", "2.3", "indices", "lines", "chars"), tuple[int, ...]) # (0, 0, 0)—— +assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", "update"), tuple[int, ...]) # (15, 1, 15) +assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "update"), tuple[int, ...]) # (0, 0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", "ypixels"), tuple[int, ...]) # (15, 1, 15, 19) +assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "ypixels"), tuple[int, ...]) # (0, 0, 0, 0) + +if sys.version_info >= (3, 13): + assert_type(t.count("1.0", "2.3", return_ints=True), int) # 15 + assert_type(t.count("2.3", "2.3", return_ints=True), int) # 0 + assert_type(t.count("1.0", "2.3", "indices", return_ints=True), int) # 15 + assert_type(t.count("2.3", "2.3", "indices", return_ints=True), int) # 0 + assert_type(t.count("1.0", "2.3", "indices", "update", return_ints=True), int) # 15 + assert_type(t.count("2.3", "2.3", "indices", "update", return_ints=True), int) # 0 + assert_type(t.count("1.0", "2.3", "indices", "lines", return_ints=True), tuple[int, int]) # (15, 1) + assert_type(t.count("2.3", "2.3", "indices", "lines", return_ints=True), tuple[int, int]) # (0, 0) + assert_type(t.count("1.0", "2.3", "indices", "lines", "update", return_ints=True), tuple[int, ...]) # (15, 1) + assert_type(t.count("2.3", "2.3", "indices", "lines", "update", return_ints=True), tuple[int, ...]) # (0, 0) + assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", return_ints=True), tuple[int, ...]) # (15, 1, 15) + assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", return_ints=True), tuple[int, ...]) # (0, 0, 0) + assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", "update", return_ints=True), tuple[int, ...]) # (15, 1, 15) + assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "update", return_ints=True), tuple[int, ...]) # (0, 0, 0) + assert_type( + t.count("1.0", "2.3", "indices", "lines", "chars", "ypixels", return_ints=True), tuple[int, ...] + ) # (15, 1, 15, 19) + assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "ypixels", return_ints=True), tuple[int, ...]) # (0, 0, 0, 0) diff --git a/stdlib/@tests/test_cases/check_turtle.py b/stdlib/@tests/test_cases/check_turtle.py new file mode 100644 index 000000000000..6be64ea5da30 --- /dev/null +++ b/stdlib/@tests/test_cases/check_turtle.py @@ -0,0 +1,35 @@ +from turtle import Turtle, dot + +Turtle().dot() +Turtle().dot(10) +Turtle().dot(size=10) +Turtle().dot((0, 0, 0)) +Turtle().dot(size=(0, 0, 0)) +Turtle().dot("blue") +Turtle().dot("") +Turtle().dot(size="blue") +Turtle().dot(20, "blue") +Turtle().dot(20, "blue") +Turtle().dot(20, (0, 0, 0)) +Turtle().dot(20, 0, 0, 0) + +Turtle().dot(size=10, color="blue") # type: ignore +Turtle().dot(10, color="blue") # type: ignore +Turtle().dot(color="blue") # type: ignore + +dot() +dot(10) +dot(size=10) +dot((0, 0, 0)) +dot(size=(0, 0, 0)) +dot("blue") +dot("") +dot(size="blue") +dot(20, "blue") +dot(20, "blue") +dot(20, (0, 0, 0)) +dot(20, 0, 0, 0) + +dot(size=10, color="blue") # type: ignore +dot(10, color="blue") # type: ignore +dot(color="blue") # type: ignore diff --git a/stdlib/@tests/test_cases/check_types.py b/stdlib/@tests/test_cases/check_types.py new file mode 100644 index 000000000000..a9c2eeddbfdf --- /dev/null +++ b/stdlib/@tests/test_cases/check_types.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import sys +import types +from collections import UserDict +from typing import Any, Literal, TypeVar +from typing_extensions import assert_type + +_T = TypeVar("_T") + +# test `types.SimpleNamespace` + +# Valid: +types.SimpleNamespace() +types.SimpleNamespace(x=1, y=2) + +if sys.version_info >= (3, 13): + types.SimpleNamespace(()) + types.SimpleNamespace([]) + types.SimpleNamespace([("x", "y"), ("z", 1)]) + types.SimpleNamespace({}) + types.SimpleNamespace(UserDict({"x": 1, "y": 2})) + + +# Invalid: +types.SimpleNamespace(1) # type: ignore +types.SimpleNamespace([1]) # type: ignore +types.SimpleNamespace([["x"]]) # type: ignore +types.SimpleNamespace(**{1: 2}) # type: ignore +types.SimpleNamespace({1: 2}) # type: ignore +types.SimpleNamespace([[1, 2]]) # type: ignore +types.SimpleNamespace(UserDict({1: 2})) # type: ignore +types.SimpleNamespace([[[], 2]]) # type: ignore + +# test: `types.MappingProxyType` +mp = types.MappingProxyType({1: 2, 3: 4}) +mp.get("x") # type: ignore +item = mp.get(1) +assert_type(item, int | None) +item_2 = mp.get(2, 0) +assert_type(item_2, int) +item_3 = mp.get(3, "default") +assert_type(item_3, int | str) +# Default isn't accepted as a keyword argument. +mp.get(4, default="default") # type: ignore + + +# test: `types.DynamicClassAttribute` +class DCAtest: + _value: int | None = None + + @types.DynamicClassAttribute + def foo(self) -> int | None: + return self._value + + @foo.setter + def foo(self, value: int) -> None: + self._value = value + + @foo.deleter + def foo(self) -> None: + self._value = None + + +# check that NotImplemented is treated as an "Any" +x: int = NotImplemented + +# test NotImplementedType usage +assert_type(NotImplemented, types.NotImplementedType) +assert_type(types.NotImplementedType(), types.NotImplementedType) +# test EllipsisType usage +assert_type(Ellipsis, types.EllipsisType) +assert_type(types.EllipsisType(), types.EllipsisType) +# test NoneType usage (disabled, passes with pyright, but mypy errors +# assert_type(None, types.NoneType) +# assert_type(types.NoneType(), types.NoneType) + +if sys.version_info >= (3, 11): + union_type = int | list[_T] + + # pyright and mypy infer different types here + # ideally this would be `_SpecialForm` (Union) + assert_type(union_type | Literal[1], types.UnionType | Any) # pyright: ignore[reportAssertTypeFailure] + # assert_type(union_type | Literal[1], types.UnionType | type[Literal[1]]) # this is what pyright infers + # Both mypy and pyright special-case this operation, + # but in different ways, so we just check that no error is emitted: + _ = union_type[int] diff --git a/stdlib/@tests/test_cases/check_unittest.py b/stdlib/@tests/test_cases/check_unittest.py new file mode 100644 index 000000000000..75bf0a0e3353 --- /dev/null +++ b/stdlib/@tests/test_cases/check_unittest.py @@ -0,0 +1,255 @@ +from __future__ import annotations + +import unittest +from collections.abc import Iterator, Mapping +from datetime import datetime, timedelta +from decimal import Decimal +from fractions import Fraction +from typing import TypedDict +from typing_extensions import assert_type +from unittest.mock import _ANY, ANY, AsyncMock, MagicMock, Mock, patch + +case = unittest.TestCase() + +### +# Tests for assertAlmostEqual +### + +case.assertAlmostEqual(1, 2.4) +case.assertAlmostEqual(2.4, 2.41) +case.assertAlmostEqual(Fraction(49, 50), Fraction(48, 50)) +case.assertAlmostEqual(3.14, complex(5, 6)) +case.assertAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), delta=timedelta(hours=1)) +case.assertAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), None, "foo", timedelta(hours=1)) +case.assertAlmostEqual(Decimal("1.1"), Decimal("1.11")) +case.assertAlmostEqual(2.4, 2.41, places=8) +case.assertAlmostEqual(2.4, 2.41, delta=0.02) +case.assertAlmostEqual(2.4, 2.41, None, "foo", 0.02) + +case.assertAlmostEqual(2.4, 2.41, places=9, delta=0.02) # type: ignore +case.assertAlmostEqual("foo", "bar") # type: ignore +case.assertAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1)) # type: ignore +case.assertAlmostEqual(Decimal("0.4"), Fraction(1, 2)) # type: ignore +case.assertAlmostEqual(complex(2, 3), Decimal("0.9")) # type: ignore + +### +# Tests for assertNotAlmostEqual +### + +case.assertAlmostEqual(1, 2.4) +case.assertNotAlmostEqual(Fraction(49, 50), Fraction(48, 50)) +case.assertAlmostEqual(3.14, complex(5, 6)) +case.assertNotAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), delta=timedelta(hours=1)) +case.assertNotAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), None, "foo", timedelta(hours=1)) + +case.assertNotAlmostEqual(2.4, 2.41, places=9, delta=0.02) # type: ignore +case.assertNotAlmostEqual("foo", "bar") # type: ignore +case.assertNotAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1)) # type: ignore +case.assertNotAlmostEqual(Decimal("0.4"), Fraction(1, 2)) # type: ignore +case.assertNotAlmostEqual(complex(2, 3), Decimal("0.9")) # type: ignore + +### +# Tests for assertGreater +### + + +class Spam: + def __lt__(self, other: object) -> bool: + return True + + +class Eggs: + def __gt__(self, other: object) -> bool: + return True + + +class Ham: + def __lt__(self, other: Ham) -> bool: + if not isinstance(other, Ham): + return NotImplemented + return True + + +class Bacon: + def __gt__(self, other: Bacon) -> bool: + if not isinstance(other, Bacon): + return NotImplemented + return True + + +case.assertGreater(5.8, 3) +case.assertGreater(Decimal("4.5"), Fraction(3, 2)) +case.assertGreater(Fraction(3, 2), 0.9) +case.assertGreater(Eggs(), object()) +case.assertGreater(object(), Spam()) +case.assertGreater(Ham(), Ham()) +case.assertGreater(Bacon(), Bacon()) + +case.assertGreater(object(), object()) # type: ignore +case.assertGreater(datetime(1999, 1, 2), 1) # type: ignore +case.assertGreater(Spam(), Eggs()) # type: ignore +case.assertGreater(Ham(), Bacon()) # type: ignore +case.assertGreater(Bacon(), Ham()) # type: ignore + + +### +# Tests for assertDictEqual +### + + +class TD1(TypedDict): + x: int + y: str + + +class TD2(TypedDict): + a: bool + b: bool + + +class MyMapping(Mapping[str, int]): + def __getitem__(self, __key: str) -> int: + return 42 + + def __iter__(self) -> Iterator[str]: + return iter([]) + + def __len__(self) -> int: + return 0 + + +td1: TD1 = {"x": 1, "y": "foo"} +td2: TD2 = {"a": True, "b": False} +m = MyMapping() + +case.assertDictEqual({}, {}) +case.assertDictEqual({"x": 1, "y": 2}, {"x": 1, "y": 2}) +case.assertDictEqual({"x": 1, "y": "foo"}, {"y": "foo", "x": 1}) +case.assertDictEqual({"x": 1}, {}) +case.assertDictEqual({}, {"x": 1}) +case.assertDictEqual({1: "x"}, {"y": 222}) +case.assertDictEqual({1: "x"}, td1) +case.assertDictEqual(td1, {1: "x"}) +case.assertDictEqual(td1, td2) + +case.assertDictEqual(1, {}) # type: ignore +case.assertDictEqual({}, 1) # type: ignore + +# These should fail, but don't due to TypedDict limitations: +# case.assertDictEqual(m, {"": 0}) # xtype: ignore +# case.assertDictEqual({"": 0}, m) # xtype: ignore + +### +# Tests for mock.patch +### + + +@patch("sys.exit") +def f_default_new(i: int, mock: MagicMock) -> str: + return "asdf" + + +@patch("sys.exit", new=42) +def f_explicit_new(i: int) -> str: + return "asdf" + + +@patch("sys.exit", new_callable=lambda: 42) +def f_explicit_new_callable(i: int, new_callable_ret: int) -> str: + return "asdf" + + +assert_type(f_default_new(1), str) +f_default_new("a") # Not an error due to ParamSpec limitations +assert_type(f_explicit_new(1), str) +f_explicit_new("a") # type: ignore[arg-type] +assert_type(f_explicit_new_callable(1), str) +f_explicit_new_callable("a") # Same as default new + + +@patch("sys.exit", new=Mock()) +class TestXYZ(unittest.TestCase): + attr: int = 5 + + @staticmethod + def method() -> int: + return 123 + + +assert_type(TestXYZ.attr, int) +assert_type(TestXYZ.method(), int) + + +with patch("sys.exit") as default_new_enter: + assert_type(default_new_enter, MagicMock | AsyncMock) + +with patch("sys.exit", new=42) as explicit_new_enter: + assert_type(explicit_new_enter, int) + +with patch("sys.exit", new_callable=lambda: 42) as explicit_new_callable_enter: + assert_type(explicit_new_callable_enter, int) + + +### +# Tests for mock.patch.object +### + + +@patch.object(Decimal, "exp") +def obj_f_default_new(i: int, mock: MagicMock) -> str: + return "asdf" + + +@patch.object(Decimal, "exp", new=42) +def obj_f_explicit_new(i: int) -> str: + return "asdf" + + +@patch.object(Decimal, "exp", new_callable=lambda: 42) +def obj_f_explicit_new_callable(i: int, new_callable_ret: int) -> str: + return "asdf" + + +assert_type(obj_f_default_new(1), str) +obj_f_default_new("a") # Not an error due to ParamSpec limitations +assert_type(obj_f_explicit_new(1), str) +obj_f_explicit_new("a") # type: ignore[arg-type] +assert_type(obj_f_explicit_new_callable(1), str) +obj_f_explicit_new_callable("a") # Same as default new + + +with patch.object(Decimal, "exp") as obj_default_new_enter: + assert_type(obj_default_new_enter, MagicMock | AsyncMock) + +with patch.object(Decimal, "exp", new=42) as obj_explicit_new_enter: + assert_type(obj_explicit_new_enter, int) + +with patch.object(Decimal, "exp", new_callable=lambda: 42) as obj_explicit_new_callable_enter: + assert_type(obj_explicit_new_callable_enter, int) + + +### +# Tests for mock.ANY +### + + +assert_type(ANY, _ANY) # Make sure ANY has runtime type + + +# Regression tests. See https://github.com/python/typeshed/issues/14701 +class TD(TypedDict): + x: str + y: float + + +td: TD = {"x": "1", "y": ANY} + + +def test_as_param(x: str) -> None: ... + + +test_as_param(ANY) + + +def test_as_return_value(x: int) -> TD: + return {"x": str(x), "y": ANY} diff --git a/stdlib/@tests/test_cases/check_xml.py b/stdlib/@tests/test_cases/check_xml.py new file mode 100644 index 000000000000..31a4fa243eaa --- /dev/null +++ b/stdlib/@tests/test_cases/check_xml.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing_extensions import assert_type +from xml.dom.minidom import Document + +document = Document() + +assert_type(document.toxml(), str) +assert_type(document.toxml(encoding=None), str) +assert_type(document.toxml(encoding="UTF8"), bytes) +assert_type(document.toxml("UTF8"), bytes) +assert_type(document.toxml(standalone=True), str) +assert_type(document.toxml("UTF8", True), bytes) +assert_type(document.toxml(encoding="UTF8", standalone=True), bytes) + + +# Because toprettyxml can mix positional and keyword variants of the "encoding" argument, which +# determines the return type, the proper stub typing isn't immediately obvious. This is a basic +# brute-force sanity check. +# Test cases like toxml +assert_type(document.toprettyxml(), str) +assert_type(document.toprettyxml(encoding=None), str) +assert_type(document.toprettyxml(encoding="UTF8"), bytes) +assert_type(document.toprettyxml(standalone=True), str) +assert_type(document.toprettyxml(encoding="UTF8", standalone=True), bytes) +# Test cases unique to toprettyxml +assert_type(document.toprettyxml(" "), str) +assert_type(document.toprettyxml(" ", "\r\n"), str) +assert_type(document.toprettyxml(" ", "\r\n", "UTF8"), bytes) +assert_type(document.toprettyxml(" ", "\r\n", "UTF8", True), bytes) +assert_type(document.toprettyxml(" ", "\r\n", standalone=True), str) diff --git a/stdlib/@tests/test_cases/check_zipfile.py b/stdlib/@tests/test_cases/check_zipfile.py new file mode 100644 index 000000000000..3012271ccd8b --- /dev/null +++ b/stdlib/@tests/test_cases/check_zipfile.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import io +import pathlib +import zipfile +from typing import Literal + +### +# Tests for `zipfile.ZipFile` +### + +p = pathlib.Path("test.zip") + + +class CustomPathObj: + def __init__(self, path: str) -> None: + self.path = path + + def __fspath__(self) -> str: + return self.path + + +class NonPathObj: + def __init__(self, path: str) -> None: + self.path = path + + +class ReadableObj: + def seek(self, offset: int, whence: int = 0) -> int: + return 0 + + def read(self, n: int | None = -1) -> bytes: + return b"test" + + +class TellableObj: + def tell(self) -> int: + return 0 + + +class WriteableObj: + def close(self) -> None: + pass + + def write(self, b: bytes) -> int: + return len(b) + + def flush(self) -> None: + pass + + +class ReadTellableObj(ReadableObj): + def tell(self) -> int: + return 0 + + +class SeekTellObj: + def seek(self, offset: int, whence: int = 0) -> int: + return 0 + + def tell(self) -> int: + return 0 + + +def write_zip(mode: Literal["r", "w", "x", "a"]) -> None: + # Test any mode with `pathlib.Path` + with zipfile.ZipFile(p, mode) as z: + z.writestr("test.txt", "test") + + # Test any mode with `str` path + with zipfile.ZipFile("test.zip", mode) as z: + z.writestr("test.txt", "test") + + # Test any mode with `os.PathLike` object + with zipfile.ZipFile(CustomPathObj("test.zip"), mode) as z: + z.writestr("test.txt", "test") + + # Non-PathLike object should raise an error + with zipfile.ZipFile(NonPathObj("test.zip"), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # IO[bytes] like-obj should work for any mode. + io_obj = io.BytesIO(b"This is a test") + with zipfile.ZipFile(io_obj, mode) as z: + z.writestr("test.txt", "test") + + # Readable object should not work for any mode. + with zipfile.ZipFile(ReadableObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Readable object should work for "r" mode. + with zipfile.ZipFile(ReadableObj(), "r") as z: + z.writestr("test.txt", "test") + + # Readable/tellable object should work for "a" mode. + with zipfile.ZipFile(ReadTellableObj(), "a") as z: + z.writestr("test.txt", "test") + + # If it doesn't have 'tell' method, it should raise an error. + with zipfile.ZipFile(ReadableObj(), "a") as z: # type: ignore + z.writestr("test.txt", "test") + + # Readable object should not work for "w" mode. + with zipfile.ZipFile(ReadableObj(), "w") as z: # type: ignore + z.writestr("test.txt", "test") + + # Tellable object should not work for any mode. + with zipfile.ZipFile(TellableObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Tellable object shouldn't work for "w" mode. + # As `__del__` will call close. + with zipfile.ZipFile(TellableObj(), "w") as z: # type: ignore + z.writestr("test.txt", "test") + + # Writeable object should not work for any mode. + with zipfile.ZipFile(WriteableObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Writeable object should work for "w" mode. + with zipfile.ZipFile(WriteableObj(), "w") as z: + z.writestr("test.txt", "test") + + # Seekable and Tellable object should not work for any mode. + with zipfile.ZipFile(SeekTellObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Seekable and Tellable object shouldn't work for "w" mode. + # Cause `__del__` will call close. + with zipfile.ZipFile(SeekTellObj(), "w") as z: # type: ignore + z.writestr("test.txt", "test") diff --git a/stdlib/@tests/test_cases/collections/check_defaultdict.py b/stdlib/@tests/test_cases/collections/check_defaultdict.py new file mode 100644 index 000000000000..f29aa8778a3d --- /dev/null +++ b/stdlib/@tests/test_cases/collections/check_defaultdict.py @@ -0,0 +1,71 @@ +""" +Tests for `defaultdict.__or__` and `defaultdict.__ror__`. +""" + +from __future__ import annotations + +import os +from collections import defaultdict +from collections.abc import Mapping +from typing import TypeVar +from typing_extensions import Self, assert_type + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +class CustomDefaultDictSubclass(defaultdict[_KT, _VT]): + pass + + +class CustomMappingWithDunderOr(Mapping[_KT, _VT]): + def __or__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ror__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ior__(self, other: Mapping[_KT, _VT]) -> Self: + return self + + +def test_defaultdict_dot_or( + a: defaultdict[int, int], + b: CustomDefaultDictSubclass[int, int], + c: defaultdict[str, str], + d: Mapping[int, int], + e: CustomMappingWithDunderOr[str, str], +) -> None: + assert_type(a | b, defaultdict[int, int]) + + # In contrast to `dict.__or__`, `defaultdict.__or__` returns `Self` if called on a subclass of `defaultdict`: + assert_type(b | a, CustomDefaultDictSubclass[int, int]) + + assert_type(a | c, defaultdict[int | str, int | str]) + + # arbitrary mappings are not accepted by `defaultdict.__or__`; + # it has to be a subclass of `dict` + a | d # type: ignore + + # but Mappings such as `os._Environ` or `CustomMappingWithDunderOr`, + # which define `__ror__` methods that accept `dict`, are fine + # (`os._Environ.__(r)or__` always returns `dict`, even if a `defaultdict` is passed): + assert_type(a | os.environ, dict[int | str, int | str]) + assert_type(os.environ | a, dict[int | str, int | str]) + + assert_type(c | os.environ, dict[str, str]) + assert_type(c | e, dict[str, str]) + + assert_type(os.environ | c, dict[str, str]) + assert_type(e | c, dict[str, str]) + + # store "untainted" `CustomMappingWithDunderOr[str, str]` to test `__ior__` against ` defaultdict[str, str]` later + # Invalid `e |= a` causes pyright to join `Unknown` to `e`'s type + f = e + + e |= c + e |= a # type: ignore + + c |= f + + c |= a # type: ignore diff --git a/stdlib/@tests/test_cases/ctypes/check_CDLL.py b/stdlib/@tests/test_cases/ctypes/check_CDLL.py new file mode 100644 index 000000000000..ca7dc248160b --- /dev/null +++ b/stdlib/@tests/test_cases/ctypes/check_CDLL.py @@ -0,0 +1,11 @@ +import ctypes +import sys +from pathlib import Path +from typing_extensions import assert_type + +assert_type(ctypes.CDLL(None), ctypes.CDLL) +assert_type(ctypes.CDLL("."), ctypes.CDLL) + +# https://github.com/python/cpython/pull/7032 +if sys.version_info >= (3, 12): + assert_type(ctypes.CDLL(Path(".")), ctypes.CDLL) diff --git a/stdlib/@tests/test_cases/ctypes/check_pointer.py b/stdlib/@tests/test_cases/ctypes/check_pointer.py new file mode 100644 index 000000000000..55f6e1365e57 --- /dev/null +++ b/stdlib/@tests/test_cases/ctypes/check_pointer.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +import ctypes +from typing import Type +from typing_extensions import assert_type + +assert_type(ctypes.POINTER(None), Type[ctypes.c_void_p]) +assert_type(ctypes.POINTER(ctypes.c_int), Type[ctypes._Pointer[ctypes.c_int]]) diff --git a/stdlib/@tests/test_cases/email/check_message.py b/stdlib/@tests/test_cases/email/check_message.py new file mode 100644 index 000000000000..7939f2981708 --- /dev/null +++ b/stdlib/@tests/test_cases/email/check_message.py @@ -0,0 +1,18 @@ +from email.headerregistry import Address, BaseHeader +from email.message import EmailMessage, MIMEPart +from typing_extensions import assert_type + +msg = EmailMessage() +msg["To"] = "receiver@example.com" +msg["From"] = Address("Sender Name", "sender", "example.com") + +for a in msg.iter_attachments(): + assert_type(a, EmailMessage) + +generic_msg: EmailMessage[BaseHeader, str] = EmailMessage() +assert_type(generic_msg.get("To"), BaseHeader | None) +assert_type(generic_msg.get_body(), MIMEPart[BaseHeader, str] | None) +for a in generic_msg.iter_attachments(): + assert_type(a, EmailMessage[BaseHeader, str]) +for p in generic_msg.iter_parts(): + assert_type(p, MIMEPart[BaseHeader, str]) diff --git a/stdlib/@tests/test_cases/email/check_mime.py b/stdlib/@tests/test_cases/email/check_mime.py new file mode 100644 index 000000000000..e49d2bfacc21 --- /dev/null +++ b/stdlib/@tests/test_cases/email/check_mime.py @@ -0,0 +1,4 @@ +from email.mime.text import MIMEText +from email.policy import SMTP + +msg = MIMEText("", policy=SMTP) diff --git a/stdlib/@tests/test_cases/email/check_parser.py b/stdlib/@tests/test_cases/email/check_parser.py new file mode 100644 index 000000000000..fd5c24a9f6de --- /dev/null +++ b/stdlib/@tests/test_cases/email/check_parser.py @@ -0,0 +1,16 @@ +import email.policy +from email.message import EmailMessage, Message +from email.parser import BytesParser, Parser +from typing_extensions import assert_type + +p1 = Parser() +p2 = Parser(policy=email.policy.default) + +assert_type(p1, Parser[Message[str, str]]) +assert_type(p2, Parser[EmailMessage]) + +bp1 = BytesParser() +bp2 = BytesParser(policy=email.policy.default) + +assert_type(bp1, BytesParser[Message[str, str]]) +assert_type(bp2, BytesParser[EmailMessage]) diff --git a/stdlib/@tests/test_cases/itertools/check_batched.py b/stdlib/@tests/test_cases/itertools/check_batched.py new file mode 100644 index 000000000000..5e0e2ae77320 --- /dev/null +++ b/stdlib/@tests/test_cases/itertools/check_batched.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import sys +from typing_extensions import assert_type + +if sys.version_info >= (3, 13): + from itertools import batched + + assert_type(batched([0], 1, strict=True), batched[tuple[int]]) + assert_type(batched([0, 0], 2, strict=True), batched[tuple[int, int]]) + assert_type(batched([0, 0, 0], 3, strict=True), batched[tuple[int, int, int]]) + assert_type(batched([0, 0, 0, 0], 4, strict=True), batched[tuple[int, int, int, int]]) + assert_type(batched([0, 0, 0, 0, 0], 5, strict=True), batched[tuple[int, int, int, int, int]]) + + assert_type(batched([0], 2), batched[tuple[int, ...]]) + assert_type(batched([0], 2, strict=False), batched[tuple[int, ...]]) + + def f() -> int: + return 3 + + assert_type(batched([0, 0, 0], f(), strict=True), batched[tuple[int, ...]]) diff --git a/stdlib/@tests/test_cases/itertools/check_itertools_recipes.py b/stdlib/@tests/test_cases/itertools/check_itertools_recipes.py new file mode 100644 index 000000000000..84f4bca5c868 --- /dev/null +++ b/stdlib/@tests/test_cases/itertools/check_itertools_recipes.py @@ -0,0 +1,415 @@ +"""Type-annotated versions of the recipes from the itertools docs. + +These are all meant to be examples of idiomatic itertools usage, +so they should all type-check without error. +""" + +from __future__ import annotations + +import collections +import math +import operator +import sys +from itertools import chain, combinations, count, cycle, filterfalse, groupby, islice, product, repeat, starmap, tee, zip_longest +from typing import ( + Any, + Callable, + Collection, + Hashable, + Iterable, + Iterator, + Literal, + Sequence, + Tuple, + Type, + TypeAlias, + TypeVar, + Union, + overload, +) +from typing_extensions import TypeVarTuple, Unpack + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_HashableT = TypeVar("_HashableT", bound=Hashable) +_Ts = TypeVarTuple("_Ts") + + +def take(n: int, iterable: Iterable[_T]) -> list[_T]: + "Return first n items of the iterable as a list" + return list(islice(iterable, n)) + + +# Note: the itertools docs uses the parameter name "iterator", +# but the function actually accepts any iterable +# as its second argument +def prepend(value: _T1, iterator: Iterable[_T2]) -> Iterator[_T1 | _T2]: + "Prepend a single value in front of an iterator" + # prepend(1, [2, 3, 4]) --> 1 2 3 4 + return chain([value], iterator) + + +def tabulate(function: Callable[[int], _T], start: int = 0) -> Iterator[_T]: + "Return function(0), function(1), ..." + return map(function, count(start)) + + +def repeatfunc(func: Callable[[Unpack[_Ts]], _T], times: int | None = None, *args: Unpack[_Ts]) -> Iterator[_T]: + """Repeat calls to func with specified arguments. + + Example: repeatfunc(random.random) + """ + if times is None: + return starmap(func, repeat(args)) + return starmap(func, repeat(args, times)) + + +def flatten(list_of_lists: Iterable[Iterable[_T]]) -> Iterator[_T]: + "Flatten one level of nesting" + return chain.from_iterable(list_of_lists) + + +def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: + "Returns the sequence elements n times" + return chain.from_iterable(repeat(tuple(iterable), n)) + + +def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: + "Return an iterator over the last n items" + # tail(3, 'ABCDEFG') --> E F G + return iter(collections.deque(iterable, maxlen=n)) + + +# This function *accepts* any iterable, +# but it only *makes sense* to use it with an iterator +def consume(iterator: Iterator[object], n: int | None = None) -> None: + "Advance the iterator n-steps ahead. If n is None, consume entirely." + # Use functions that consume iterators at C speed. + if n is None: + # feed the entire iterator into a zero-length deque + collections.deque(iterator, maxlen=0) + else: + # advance to the empty slice starting at position n + next(islice(iterator, n, n), None) + + +@overload +def nth(iterable: Iterable[_T], n: int, default: None = None) -> _T | None: ... + + +@overload +def nth(iterable: Iterable[_T], n: int, default: _T1) -> _T | _T1: ... + + +def nth(iterable: Iterable[object], n: int, default: object = None) -> object: + "Returns the nth item or a default value" + return next(islice(iterable, n, None), default) + + +@overload +def quantify(iterable: Iterable[object]) -> int: ... + + +@overload +def quantify(iterable: Iterable[_T], pred: Callable[[_T], bool]) -> int: ... + + +def quantify(iterable: Iterable[object], pred: Callable[[Any], bool] = bool) -> int: + "Given a predicate that returns True or False, count the True results." + return sum(map(pred, iterable)) + + +@overload +def first_true( + iterable: Iterable[_T], default: Literal[False] = False, pred: Callable[[_T], bool] | None = None +) -> _T | Literal[False]: ... + + +@overload +def first_true(iterable: Iterable[_T], default: _T1, pred: Callable[[_T], bool] | None = None) -> _T | _T1: ... + + +def first_true(iterable: Iterable[object], default: object = False, pred: Callable[[Any], bool] | None = None) -> object: + """Returns the first true value in the iterable. + If no true value is found, returns *default* + If *pred* is not None, returns the first item + for which pred(item) is true. + """ + # first_true([a,b,c], x) --> a or b or c or x + # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x + return next(filter(pred, iterable), default) + + +_ExceptionOrExceptionTuple: TypeAlias = Union[Type[BaseException], Tuple[Type[BaseException], ...]] + + +@overload +def iter_except(func: Callable[[], _T], exception: _ExceptionOrExceptionTuple, first: None = None) -> Iterator[_T]: ... + + +@overload +def iter_except( + func: Callable[[], _T], exception: _ExceptionOrExceptionTuple, first: Callable[[], _T1] +) -> Iterator[_T | _T1]: ... + + +def iter_except( + func: Callable[[], object], exception: _ExceptionOrExceptionTuple, first: Callable[[], object] | None = None +) -> Iterator[object]: + """Call a function repeatedly until an exception is raised. + Converts a call-until-exception interface to an iterator interface. + Like builtins.iter(func, sentinel) but uses an exception instead + of a sentinel to end the loop. + Examples: + iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator + iter_except(d.popitem, KeyError) # non-blocking dict iterator + iter_except(d.popleft, IndexError) # non-blocking deque iterator + iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue + iter_except(s.pop, KeyError) # non-blocking set iterator + """ + try: + if first is not None: + yield first() # For database APIs needing an initial cast to db.first() + while True: + yield func() + except exception: + pass + + +def sliding_window(iterable: Iterable[_T], n: int) -> Iterator[tuple[_T, ...]]: + # sliding_window('ABCDEFG', 4) --> ABCD BCDE CDEF DEFG + it = iter(iterable) + window = collections.deque(islice(it, n - 1), maxlen=n) + for x in it: + window.append(x) + yield tuple(window) + + +def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: + "roundrobin('ABC', 'D', 'EF') --> A D E B F C" + # Recipe credited to George Sakkis + num_active = len(iterables) + nexts: Iterator[Callable[[], _T]] = cycle(iter(it).__next__ for it in iterables) + while num_active: + try: + for next in nexts: + yield next() + except StopIteration: + # Remove the iterator we just exhausted from the cycle. + num_active -= 1 + nexts = cycle(islice(nexts, num_active)) + + +def partition(pred: Callable[[_T], bool], iterable: Iterable[_T]) -> tuple[Iterator[_T], Iterator[_T]]: + """Partition entries into false entries and true entries. + If *pred* is slow, consider wrapping it with functools.lru_cache(). + """ + # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 + t1, t2 = tee(iterable) + return filterfalse(pred, t1), filter(pred, t2) + + +def subslices(seq: Sequence[_T]) -> Iterator[Sequence[_T]]: + "Return all contiguous non-empty subslices of a sequence" + # subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D + slices = starmap(slice, combinations(range(len(seq) + 1), 2)) + return map(operator.getitem, repeat(seq), slices) + + +def before_and_after(predicate: Callable[[_T], bool], it: Iterable[_T]) -> tuple[Iterator[_T], Iterator[_T]]: + """Variant of takewhile() that allows complete + access to the remainder of the iterator. + >>> it = iter('ABCdEfGhI') + >>> all_upper, remainder = before_and_after(str.isupper, it) + >>> ''.join(all_upper) + 'ABC' + >>> ''.join(remainder) # takewhile() would lose the 'd' + 'dEfGhI' + Note that the first iterator must be fully + consumed before the second iterator can + generate valid results. + """ + it = iter(it) + transition: list[_T] = [] + + def true_iterator() -> Iterator[_T]: + for elem in it: + if predicate(elem): + yield elem + else: + transition.append(elem) + return + + def remainder_iterator() -> Iterator[_T]: + yield from transition + yield from it + + return true_iterator(), remainder_iterator() + + +@overload +def unique_everseen(iterable: Iterable[_HashableT], key: None = None) -> Iterator[_HashableT]: ... + + +@overload +def unique_everseen(iterable: Iterable[_T], key: Callable[[_T], Hashable]) -> Iterator[_T]: ... + + +def unique_everseen(iterable: Iterable[_T], key: Callable[[_T], Hashable] | None = None) -> Iterator[_T]: + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBcCAD', str.lower) --> A B c D + seen: set[Hashable] = set() + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen.add(element) + yield element + # For order preserving deduplication, + # a faster but non-lazy solution is: + # yield from dict.fromkeys(iterable) + else: + for element in iterable: + k = key(element) + if k not in seen: + seen.add(k) + yield element + # For use cases that allow the last matching element to be returned, + # a faster but non-lazy solution is: + # t1, t2 = tee(iterable) + # yield from dict(zip(map(key, t1), t2)).values() + + +# Slightly adapted from the docs recipe; a one-liner was a bit much for pyright +def unique_justseen(iterable: Iterable[_T], key: Callable[[_T], bool] | None = None) -> Iterator[_T]: + "List unique elements, preserving order. Remember only the element just seen." + # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B + # unique_justseen('ABBcCAD', str.lower) --> A B c A D + if key is None: + return map(operator.itemgetter(0), groupby(iterable)) + g: groupby[_T | bool, _T] = groupby(iterable, key) + return map(next, map(operator.itemgetter(1), g)) + + +def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: + "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) + + +def polynomial_derivative(coefficients: Sequence[float]) -> list[float]: + """Compute the first derivative of a polynomial. + f(x) = x³ -4x² -17x + 60 + f'(x) = 3x² -8x -17 + """ + # polynomial_derivative([1, -4, -17, 60]) -> [3, -8, -17] + n = len(coefficients) + powers = reversed(range(1, n)) + return list(map(operator.mul, coefficients, powers)) + + +def nth_combination(iterable: Iterable[_T], r: int, index: int) -> tuple[_T, ...]: + "Equivalent to list(combinations(iterable, r))[index]" + pool = tuple(iterable) + n = len(pool) + c = math.comb(n, r) + if index < 0: + index += c + if index < 0 or index >= c: + raise IndexError + result: list[_T] = [] + while r: + c, n, r = c * r // n, n - 1, r - 1 + while index >= c: + index -= c + c, n = c * (n - r) // n, n - 1 + result.append(pool[-1 - n]) + return tuple(result) + + +@overload +def grouper( + iterable: Iterable[_T], n: int, *, incomplete: Literal["fill"] = "fill", fillvalue: None = None +) -> Iterator[tuple[_T | None, ...]]: ... + + +@overload +def grouper( + iterable: Iterable[_T], n: int, *, incomplete: Literal["fill"] = "fill", fillvalue: _T1 +) -> Iterator[tuple[_T | _T1, ...]]: ... + + +@overload +def grouper( + iterable: Iterable[_T], n: int, *, incomplete: Literal["strict", "ignore"], fillvalue: None = None +) -> Iterator[tuple[_T, ...]]: ... + + +def grouper( + iterable: Iterable[object], n: int, *, incomplete: Literal["fill", "strict", "ignore"] = "fill", fillvalue: object = None +) -> Iterator[tuple[object, ...]]: + "Collect data into non-overlapping fixed-length chunks or blocks" + # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx + # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError + # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF + args = [iter(iterable)] * n + if incomplete == "fill": + return zip_longest(*args, fillvalue=fillvalue) + if incomplete == "strict": + return zip(*args, strict=True) + if incomplete == "ignore": + return zip(*args) + else: + raise ValueError("Expected fill, strict, or ignore") + + +def transpose(it: Iterable[Iterable[_T]]) -> Iterator[tuple[_T, ...]]: + "Swap the rows and columns of the input." + # transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33) + return zip(*it, strict=True) + + +if sys.version_info >= (3, 12): + from itertools import batched + + def sum_of_squares(it: Iterable[float]) -> float: + "Add up the squares of the input values." + # sum_of_squares([10, 20, 30]) -> 1400 + return math.sumprod(*tee(it)) + + def convolve(signal: Iterable[float], kernel: Iterable[float]) -> Iterator[float]: + """Discrete linear convolution of two iterables. + The kernel is fully consumed before the calculations begin. + The signal is consumed lazily and can be infinite. + Convolutions are mathematically commutative. + If the signal and kernel are swapped, + the output will be the same. + Article: https://betterexplained.com/articles/intuitive-convolution/ + Video: https://www.youtube.com/watch?v=KuXjwB4LzSA + """ + # convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur) + # convolve(data, [1/2, 0, -1/2]) --> 1st derivative estimate + # convolve(data, [1, -2, 1]) --> 2nd derivative estimate + kernel = tuple(kernel)[::-1] + n = len(kernel) + padded_signal = chain(repeat(0, n - 1), signal, repeat(0, n - 1)) + windowed_signal = sliding_window(padded_signal, n) + return map(math.sumprod, repeat(kernel), windowed_signal) + + def polynomial_eval(coefficients: Sequence[float], x: float) -> float: + """Evaluate a polynomial at a specific value. + Computes with better numeric stability than Horner's method. + """ + # Evaluate x³ -4x² -17x + 60 at x = 2.5 + # polynomial_eval([1, -4, -17, 60], x=2.5) --> 8.125 + n = len(coefficients) + if not n: + return type(x)(0) + powers = map(pow, repeat(x), reversed(range(n))) + return math.sumprod(coefficients, powers) + + def matmul(m1: Sequence[Collection[float]], m2: Sequence[Collection[float]]) -> Iterator[tuple[float, ...]]: + "Multiply two matrices." + # matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)]) --> (49, 80), (41, 60) + n = len(m2[0]) + return batched(starmap(math.sumprod, product(m1, transpose(m2))), n) diff --git a/stdlib/@tests/test_cases/multiprocessing/check_ctypes.py b/stdlib/@tests/test_cases/multiprocessing/check_ctypes.py new file mode 100644 index 000000000000..42da0a66fa60 --- /dev/null +++ b/stdlib/@tests/test_cases/multiprocessing/check_ctypes.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from ctypes import c_char, c_float, c_int +from multiprocessing import Array, Value +from multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString +from typing_extensions import assert_type + +string = Array(c_char, 12) +assert_type(string, SynchronizedString) +assert_type(string.value, bytes) + +numbers = Array(c_int, 3) +assert_type(numbers, SynchronizedArray[int]) +numbers[0] = 3 +numbers[:] = [0, 1, 2] + +field = Value(c_float, 0.0) +assert_type(field, Synchronized[float]) +field.value = 1.2 diff --git a/stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py b/stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py new file mode 100644 index 000000000000..1d6266a0aabb --- /dev/null +++ b/stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import sys +from multiprocessing.connection import Pipe + +if sys.platform != "win32": + from multiprocessing.connection import Connection +else: + from multiprocessing.connection import PipeConnection as Connection + + +# Unfortunately, we cannot validate that both connections have the same, but inverted generic types, +# since TypeVars scoped entirely within a return annotation is unspecified in the spec. +# Pipe[str, int]() -> tuple[Connection[str, int], Connection[int, str]] + +a: Connection[str, int] +b: Connection[int, str] +a, b = Pipe() + +connections: tuple[Connection[str, int], Connection[int, str]] = Pipe() +a, b = connections + +a.send("test") +a.send(0) # type: ignore +test1: str = b.recv() +test2: int = b.recv() # type: ignore + +b.send("test") # type: ignore +b.send(0) +test3: str = a.recv() # type: ignore +test4: int = a.recv() diff --git a/stdlib/@tests/test_cases/sys/check_jit.py b/stdlib/@tests/test_cases/sys/check_jit.py new file mode 100644 index 000000000000..7916218ceda4 --- /dev/null +++ b/stdlib/@tests/test_cases/sys/check_jit.py @@ -0,0 +1,12 @@ +import sys +from typing_extensions import assert_type + +if sys.version_info >= (3, 14): + assert_type(sys._jit.is_available(), bool) + assert_type(sys._jit.is_enabled(), bool) + assert_type(sys._jit.is_active(), bool) + + def sys_is_not_a_package() -> None: + # This has to be put into a function, because otherwise the presence + # of this import statement causes errors on the above usages of `sys._jit`. + import sys._jit # type: ignore diff --git a/stdlib/@tests/test_cases/typing/check_MutableMapping.py b/stdlib/@tests/test_cases/typing/check_MutableMapping.py new file mode 100644 index 000000000000..776e12018e0f --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_MutableMapping.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from collections.abc import Hashable, Sequence +from typing import Any +from typing_extensions import assert_type + + +def check_update_method__int_key() -> None: + d: dict[int, int] = {} + d.update({1: 2}) + d.update([(1, 2)]) + d.update(a=3) # type: ignore + d.update({1: 2}, a=3) # type: ignore + d.update([(1, 2)], a=3) # type: ignore + d.update({"": 3}) # type: ignore + d.update({1: ""}) # type: ignore + d.update([("", 3)]) # type: ignore + d.update([(3, "")]) # type: ignore + + +def check_update_method__str_key() -> None: + d: dict[str, int] = {} + d.update({"": 2}) + d.update([("", 2)]) + d.update(a=3) + d.update({"": 2}, a=3) + d.update([("", 2)], a=3) + d.update({1: 3}) # type: ignore + d.update({"": ""}) # type: ignore + d.update([(1, 3)]) # type: ignore + d.update([("", "")]) # type: ignore + + +def test_keywords_allowed_on_dict_update_where_key_type_is_str_supertype( + a: dict[object, Any], b: dict[Hashable, Any], c: dict[Sequence[str], Any], d: dict[str, Any] +) -> None: + a.update(keyword_args_are_accepted="whatever") + b.update(here_too="whooo") + c.update(and_here="hooray") + d.update(also_here="yay") + + +def check_setdefault_method() -> None: + d: dict[int, str] = {} + d2: dict[int, str | None] = {} + d3: dict[int, Any] = {} + + d.setdefault(1) # type: ignore + assert_type(d.setdefault(1, "x"), str) + assert_type(d2.setdefault(1), str | None) + assert_type(d2.setdefault(1, None), str | None) + assert_type(d2.setdefault(1, "x"), str | None) + assert_type(d3.setdefault(1), Any | None) + assert_type(d3.setdefault(1, "x"), Any) diff --git a/stdlib/@tests/test_cases/typing/check_all.py b/stdlib/@tests/test_cases/typing/check_all.py new file mode 100644 index 000000000000..7e48fd4351cf --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_all.py @@ -0,0 +1,13 @@ +# pyright: reportWildcardImportFromLibrary=false +""" +This tests that star imports work when using "all += " syntax. +""" + +from __future__ import annotations + +from typing import * +from zipfile import * + +x: Annotated[int, 42] + +p: Path diff --git a/stdlib/@tests/test_cases/typing/check_regression_issue_9296.py b/stdlib/@tests/test_cases/typing/check_regression_issue_9296.py new file mode 100644 index 000000000000..23beaa87ae05 --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_regression_issue_9296.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing import Any, KeysView, TypeVar + +KT = TypeVar("KT") + + +class MyKeysView(KeysView[KT]): + pass + + +d: dict[Any, Any] = {} +dict_keys = type(d.keys()) + +# This should not cause an error like `Member "register" is unknown`: +MyKeysView.register(dict_keys) diff --git a/stdlib/@tests/test_cases/typing/check_typing_io.py b/stdlib/@tests/test_cases/typing/check_typing_io.py new file mode 100644 index 000000000000..67f16dc91765 --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_typing_io.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import mmap +from typing import IO, AnyStr + + +def check_write(io_bytes: IO[bytes], io_str: IO[str], io_anystr: IO[AnyStr], any_str: AnyStr, buf: mmap.mmap) -> None: + io_bytes.write(b"") + io_bytes.write(buf) + io_bytes.write("") # type: ignore + io_bytes.write(any_str) # type: ignore + + io_str.write(b"") # type: ignore + io_str.write(buf) # type: ignore + io_str.write("") + io_str.write(any_str) # type: ignore + + io_anystr.write(b"") # type: ignore + io_anystr.write(buf) # type: ignore + io_anystr.write("") # type: ignore + io_anystr.write(any_str) diff --git a/stdlib/@tests/test_cases/urllib/check_parse.py b/stdlib/@tests/test_cases/urllib/check_parse.py new file mode 100644 index 000000000000..f464f6341fdc --- /dev/null +++ b/stdlib/@tests/test_cases/urllib/check_parse.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from urllib.parse import quote, quote_plus, urlencode + +urlencode({"a": "b"}, quote_via=quote) +urlencode({b"a": b"b"}, quote_via=quote) +urlencode({"a": b"b"}, quote_via=quote) +urlencode({b"a": "b"}, quote_via=quote) +mixed_dict: dict[str | bytes, str | bytes] = {} +urlencode(mixed_dict, quote_via=quote) + +urlencode({"a": "b"}, quote_via=quote_plus) diff --git a/stdlib/VERSIONS b/stdlib/VERSIONS index e82161d97cb6..96eb98131db6 100644 --- a/stdlib/VERSIONS +++ b/stdlib/VERSIONS @@ -1,7 +1,7 @@ # The structure of this file is as follows: # - Blank lines and comments starting with `#` are ignored. # - Lines contain the name of a module, followed by a colon, -# a space, and a version range (for example: `symbol: 2.7-3.9`). +# a space, and a version range (for example: `symbol: 3.0-3.9`). # # Version ranges may be of the form "X.Y-A.B" or "X.Y-". The # first form means that a module was introduced in version X.Y and last @@ -12,273 +12,338 @@ # If a submodule is not listed separately, it has the same lifetime as # its parent module. # -# Python versions before 2.7 are ignored, so any module that was already -# present in 2.7 will have "2.7" as its minimum version. Version ranges -# for unsupported versions of Python 3 (currently 3.5 and lower) are -# generally accurate but we do not guarantee their correctness. +# Python versions before 3.0 are ignored, so any module that was already +# present in 3.0 will have "3.0" as its minimum version. Version ranges +# for unsupported versions of Python 3 are generally accurate but we do +# not guarantee their correctness. -__future__: 2.7- -__main__: 2.7- -_ast: 2.7- -_bisect: 2.7- -_bootlocale: 3.6-3.9 -_codecs: 2.7- +__future__: 3.0- +__main__: 3.0- +_ast: 3.0- +_asyncio: 3.0- +_bisect: 3.0- +_blake2: 3.6- +_bz2: 3.3- +_codecs: 3.0- _collections_abc: 3.3- -_compat_pickle: 3.6- -_compression: 3.6- -_csv: 2.7- -_curses: 2.7- -_decimal: 3.6- -_dummy_thread: 3.6-3.8 -_dummy_threading: 2.7-3.8 -_heapq: 2.7- -_imp: 3.6- -_json: 2.7- -_markupbase: 2.7- -_msi: 2.7- -_operator: 3.6- -_osx_support: 2.7- -_posixsubprocess: 3.6- +_compat_pickle: 3.1- +_compression: 3.5-3.13 +_contextvars: 3.7- +_csv: 3.0- +_ctypes: 3.0- +_curses: 3.0- +_curses_panel: 3.0- +_dbm: 3.0- +_decimal: 3.3- +_frozen_importlib: 3.0- +_frozen_importlib_external: 3.5- +_gdbm: 3.0- +_hashlib: 3.0- +_heapq: 3.0- +_imp: 3.0- +_interpchannels: 3.13- +_interpqueues: 3.13- +_interpreters: 3.13- +_io: 3.0- +_json: 3.0- +_locale: 3.0- +_lsprof: 3.0- +_lzma: 3.3- +_markupbase: 3.0- +_msi: 3.0-3.12 +_multibytecodec: 3.0- +_operator: 3.4- +_osx_support: 3.0- +_pickle: 3.0- +_posixsubprocess: 3.2- _py_abc: 3.7- -_pydecimal: 3.6- -_random: 2.7- -_sitebuiltins: 3.6- -_socket: 3.0- # present in 2.7 at runtime, but not in typeshed -_stat: 3.6- -_thread: 2.7- -_threading_local: 3.6- -_tkinter: 2.7- -_tracemalloc: 3.6- -_typeshed: 2.7- # not present at runtime, only for type checking -_warnings: 2.7- -_weakref: 2.7- -_weakrefset: 2.7- -_winapi: 3.6- -abc: 2.7- -aifc: 2.7- -antigravity: 2.7- -argparse: 2.7- -array: 2.7- -ast: 2.7- -asynchat: 2.7- +_pydecimal: 3.5- +_queue: 3.7- +_random: 3.0- +_remote_debugging: 3.15- +_sitebuiltins: 3.4- +_socket: 3.0- # present in 3.0 at runtime, but not in typeshed +_sqlite3: 3.0- +_ssl: 3.0- +_stat: 3.4- +_struct: 3.0- +_thread: 3.0- +_threading_local: 3.0- +_tkinter: 3.0- +_tracemalloc: 3.4- +_typeshed: 3.0- # not present at runtime, only for type checking +_warnings: 3.0- +_weakref: 3.0- +_weakrefset: 3.0- +_winapi: 3.3- +_zstd: 3.14- +abc: 3.0- +aifc: 3.0-3.12 +annotationlib: 3.14- +antigravity: 3.0- +argparse: 3.0- +array: 3.0- +ast: 3.0- +asynchat: 3.0-3.11 asyncio: 3.4- -asyncore: 2.7- -atexit: 2.7- -audioop: 2.7- -base64: 2.7- -bdb: 2.7- -binascii: 2.7- -binhex: 2.7-3.10 -bisect: 2.7- +asyncio.exceptions: 3.8- +asyncio.format_helpers: 3.7- +asyncio.graph: 3.14- +asyncio.mixins: 3.10- +asyncio.runners: 3.7- +asyncio.staggered: 3.8- +asyncio.taskgroups: 3.11- +asyncio.threads: 3.9- +asyncio.timeouts: 3.11- +asyncio.tools: 3.14- +asyncio.trsock: 3.8- +asyncore: 3.0-3.11 +atexit: 3.0- +audioop: 3.0-3.12 +base64: 3.0- +bdb: 3.0- +binascii: 3.0- +binhex: 3.0-3.10 +bisect: 3.0- builtins: 3.0- -bz2: 2.7- -cProfile: 2.7- -calendar: 2.7- -cgi: 2.7- -cgitb: 2.7- -chunk: 2.7- -cmath: 2.7- -cmd: 2.7- -code: 2.7- -codecs: 2.7- -codeop: 2.7- -collections: 2.7- +bz2: 3.0- +cProfile: 3.0- +calendar: 3.0- +cgi: 3.0-3.12 +cgitb: 3.0-3.12 +chunk: 3.0-3.12 +cmath: 3.0- +cmd: 3.0- +code: 3.0- +codecs: 3.0- +codeop: 3.0- +collections: 3.0- collections.abc: 3.3- -colorsys: 2.7- -compileall: 2.7- +colorsys: 3.0- +compileall: 3.0- +compression: 3.14- concurrent: 3.2- +concurrent.futures.interpreter: 3.14- +concurrent.interpreters: 3.14- configparser: 3.0- -contextlib: 2.7- +contextlib: 3.0- contextvars: 3.7- -copy: 2.7- -copyreg: 2.7- -crypt: 2.7- -csv: 2.7- -ctypes: 2.7- -curses: 2.7- +copy: 3.0- +copyreg: 3.0- +crypt: 3.0-3.12 +csv: 3.0- +ctypes: 3.0- +curses: 3.0- dataclasses: 3.7- -datetime: 2.7- -dbm: 2.7- -decimal: 2.7- -difflib: 2.7- -dis: 2.7- -distutils: 2.7- -distutils.command.bdist_msi: 2.7-3.10 -doctest: 2.7- -dummy_threading: 2.7-3.8 -email: 2.7- -encodings: 2.7- -ensurepip: 2.7- +datetime: 3.0- +dbm: 3.0- +dbm.sqlite3: 3.13- +decimal: 3.0- +difflib: 3.0- +dis: 3.0- +distutils: 3.0-3.11 +distutils.command.bdist_msi: 3.0-3.10 +doctest: 3.0- +email: 3.0- +encodings: 3.0- +encodings.cp1125: 3.4- +encodings.cp273: 3.4- +encodings.cp858: 3.2- +encodings.koi8_t: 3.5- +encodings.kz1048: 3.5- +ensurepip: 3.0- enum: 3.4- -errno: 2.7- +errno: 3.0- faulthandler: 3.3- -fcntl: 2.7- -filecmp: 2.7- -fileinput: 2.7- -fnmatch: 2.7- -formatter: 2.7-3.9 -fractions: 2.7- -ftplib: 2.7- -functools: 2.7- -gc: 2.7- -genericpath: 2.7- -getopt: 2.7- -getpass: 2.7- -gettext: 2.7- -glob: 2.7- +fcntl: 3.0- +filecmp: 3.0- +fileinput: 3.0- +fnmatch: 3.0- +fractions: 3.0- +ftplib: 3.0- +functools: 3.0- +gc: 3.0- +genericpath: 3.0- +getopt: 3.0- +getpass: 3.0- +gettext: 3.0- +glob: 3.0- graphlib: 3.9- -grp: 2.7- -gzip: 2.7- -hashlib: 2.7- -heapq: 2.7- -hmac: 2.7- +grp: 3.0- +gzip: 3.0- +hashlib: 3.0- +heapq: 3.0- +hmac: 3.0- html: 3.0- http: 3.0- -imaplib: 2.7- -imghdr: 2.7- -imp: 2.7- -importlib: 2.7- +imaplib: 3.0- +imghdr: 3.0-3.12 +imp: 3.0-3.11 +importlib: 3.0- +importlib._abc: 3.10- +importlib._bootstrap: 3.0- +importlib._bootstrap_external: 3.5- importlib.metadata: 3.8- importlib.metadata._meta: 3.10- +importlib.metadata.diagnose: 3.13- +importlib.readers: 3.10- importlib.resources: 3.7- -inspect: 2.7- -io: 2.7- +importlib.resources._common: 3.11- +importlib.resources._functional: 3.13- +importlib.resources.abc: 3.11- +importlib.resources.readers: 3.11- +importlib.resources.simple: 3.11- +importlib.simple: 3.11- +inspect: 3.0- +io: 3.0- ipaddress: 3.3- -itertools: 2.7- -json: 2.7- -keyword: 2.7- -lib2to3: 2.7- -linecache: 2.7- -locale: 2.7- -logging: 2.7- +itertools: 3.0- +json: 3.0- +keyword: 3.0- +lib2to3: 3.0-3.12 +linecache: 3.0- +locale: 3.0- +logging: 3.0- lzma: 3.3- -macpath: 2.7-3.7 -macurl2path: 2.7-3.6 -mailbox: 2.7- -mailcap: 2.7- -marshal: 2.7- -math: 2.7- -mimetypes: 2.7- -mmap: 2.7- -modulefinder: 2.7- -msilib: 2.7- -msvcrt: 2.7- -multiprocessing: 2.7- -netrc: 2.7- -nis: 2.7- -nntplib: 2.7- -ntpath: 2.7- -nturl2path: 2.7- -numbers: 2.7- -opcode: 2.7- -operator: 2.7- -optparse: 2.7- -os: 2.7- -ossaudiodev: 2.7- -parser: 2.7-3.9 +mailbox: 3.0- +mailcap: 3.0-3.12 +marshal: 3.0- +math: 3.0- +math.integer: 3.15- +mimetypes: 3.0- +mmap: 3.0- +modulefinder: 3.0- +msilib: 3.0-3.12 +msvcrt: 3.0- +multiprocessing: 3.0- +multiprocessing.resource_tracker: 3.8- +multiprocessing.shared_memory: 3.8- +netrc: 3.0- +nis: 3.0-3.12 +nntplib: 3.0-3.12 +nt: 3.0- +ntpath: 3.0- +nturl2path: 3.0- +numbers: 3.0- +opcode: 3.0- +operator: 3.0- +optparse: 3.0- +os: 3.0- +ossaudiodev: 3.0-3.12 pathlib: 3.4- -pdb: 2.7- -pickle: 2.7- -pickletools: 2.7- -pipes: 2.7- -pkgutil: 2.7- -platform: 2.7- -plistlib: 2.7- -poplib: 2.7- -posix: 2.7- -posixpath: 2.7- -pprint: 2.7- -profile: 2.7- -pstats: 2.7- -pty: 2.7- -pwd: 2.7- -py_compile: 2.7- -pyclbr: 2.7- -pydoc: 2.7- -pydoc_data: 2.7- -pyexpat: 2.7- +pathlib.types: 3.14- +pdb: 3.0- +pickle: 3.0- +pickletools: 3.0- +pipes: 3.0-3.12 +pkgutil: 3.0- +platform: 3.0- +plistlib: 3.0- +poplib: 3.0- +posix: 3.0- +posixpath: 3.0- +pprint: 3.0- +profile: 3.0- +profiling: 3.15- +pstats: 3.0- +pty: 3.0- +pwd: 3.0- +py_compile: 3.0- +pyclbr: 3.0- +pydoc: 3.0- +pydoc_data: 3.0- +pydoc_data.module_docs: 3.13- +pyexpat: 3.0- queue: 3.0- -quopri: 2.7- -random: 2.7- -re: 2.7- -readline: 2.7- +quopri: 3.0- +random: 3.0- +re: 3.0- +readline: 3.0- reprlib: 3.0- -resource: 2.7- -rlcompleter: 2.7- -runpy: 2.7- -sched: 2.7- +resource: 3.0- +rlcompleter: 3.0- +runpy: 3.0- +sched: 3.0- secrets: 3.6- -select: 2.7- +select: 3.0- selectors: 3.4- -shelve: 2.7- -shlex: 2.7- -shutil: 2.7- -signal: 2.7- -site: 2.7- -smtpd: 2.7- -smtplib: 2.7- -sndhdr: 2.7- -socket: 2.7- +shelve: 3.0- +shlex: 3.0- +shutil: 3.0- +signal: 3.0- +site: 3.0- +smtpd: 3.0-3.11 +smtplib: 3.0- +sndhdr: 3.0-3.12 +socket: 3.0- socketserver: 3.0- -spwd: 2.7- -sqlite3: 2.7- -sre_compile: 2.7- -sre_constants: 2.7- -sre_parse: 2.7- -ssl: 2.7- -stat: 2.7- +spwd: 3.0-3.12 +sqlite3: 3.0- +sre_compile: 3.0-3.14 +sre_constants: 3.0-3.14 +sre_parse: 3.0-3.14 +ssl: 3.0- +stat: 3.0- statistics: 3.4- -string: 2.7- -stringprep: 2.7- -struct: 2.7- -subprocess: 2.7- -sunau: 2.7- -symbol: 2.7-3.9 -symtable: 2.7- -sys: 2.7- -sysconfig: 2.7- -syslog: 2.7- -tabnanny: 2.7- -tarfile: 2.7- -telnetlib: 2.7- -tempfile: 2.7- -termios: 2.7- -textwrap: 2.7- -this: 2.7- -threading: 2.7- -time: 2.7- -timeit: 2.7- +string: 3.0- +string.templatelib: 3.14- +stringprep: 3.0- +struct: 3.0- +subprocess: 3.0- +sunau: 3.0-3.12 +symtable: 3.0- +sys: 3.0- +sys.__jit: 3.14- # Similar to sys._monitoring +sys._monitoring: 3.12- # Doesn't actually exist. See comments in the stub. +sysconfig: 3.0- +syslog: 3.0- +tabnanny: 3.0- +tarfile: 3.0- +telnetlib: 3.0-3.12 +tempfile: 3.0- +termios: 3.0- +textwrap: 3.0- +this: 3.0- +threading: 3.0- +time: 3.0- +timeit: 3.0- tkinter: 3.0- -token: 2.7- -tokenize: 2.7- -trace: 2.7- -traceback: 2.7- +tkinter.tix: 3.0-3.12 +token: 3.0- +tokenize: 3.0- +tomllib: 3.11- +trace: 3.0- +traceback: 3.0- tracemalloc: 3.4- -tty: 2.7- -turtle: 2.7- -types: 2.7- +tty: 3.0- +turtle: 3.0- +types: 3.0- typing: 3.5- -typing_extensions: 2.7- -unicodedata: 2.7- -unittest: 2.7- +typing_extensions: 3.0- +unicodedata: 3.0- +unittest: 3.0- unittest._log: 3.9- -urllib: 2.7- -uu: 2.7- -uuid: 2.7- +unittest.async_case: 3.8- +urllib: 3.0- +uu: 3.0-3.12 +uuid: 3.0- venv: 3.3- -warnings: 2.7- -wave: 2.7- -weakref: 2.7- -webbrowser: 2.7- +warnings: 3.0- +wave: 3.0- +weakref: 3.0- +webbrowser: 3.0- winreg: 3.0- -winsound: 2.7- -wsgiref: 2.7- -xdrlib: 2.7- -xml: 2.7- +winsound: 3.0- +wsgiref: 3.0- +wsgiref.types: 3.11- +xdrlib: 3.0-3.12 +xml: 3.0- +xml.utils: 3.15- xmlrpc: 3.0- -xxlimited: 3.6- +xxlimited: 3.2- zipapp: 3.5- -zipfile: 2.7- -zipimport: 2.7- -zlib: 2.7- +zipfile: 3.0- +zipfile._path: 3.12- +zipimport: 3.0- +zlib: 3.0- zoneinfo: 3.9- diff --git a/stdlib/__future__.pyi b/stdlib/__future__.pyi index 1a465c3e213d..aa445d22bd20 100644 --- a/stdlib/__future__.pyi +++ b/stdlib/__future__.pyi @@ -1,9 +1,11 @@ -import sys +from typing import TypeAlias + +_VersionInfo: TypeAlias = tuple[int, int, int, str, int] class _Feature: - def __init__(self, optionalRelease: sys._version_info, mandatoryRelease: sys._version_info, compiler_flag: int) -> None: ... - def getOptionalRelease(self) -> sys._version_info: ... - def getMandatoryRelease(self) -> sys._version_info: ... + def __init__(self, optionalRelease: _VersionInfo, mandatoryRelease: _VersionInfo | None, compiler_flag: int) -> None: ... + def getOptionalRelease(self) -> _VersionInfo: ... + def getMandatoryRelease(self) -> _VersionInfo | None: ... compiler_flag: int absolute_import: _Feature @@ -15,36 +17,20 @@ unicode_literals: _Feature with_statement: _Feature barry_as_FLUFL: _Feature generator_stop: _Feature - -if sys.version_info >= (3, 7): - annotations: _Feature +annotations: _Feature all_feature_names: list[str] # undocumented -if sys.version_info >= (3, 7): - __all__ = [ - "all_feature_names", - "absolute_import", - "division", - "generators", - "nested_scopes", - "print_function", - "unicode_literals", - "with_statement", - "barry_as_FLUFL", - "generator_stop", - "annotations", - ] -else: - __all__ = [ - "all_feature_names", - "absolute_import", - "division", - "generators", - "nested_scopes", - "print_function", - "unicode_literals", - "with_statement", - "barry_as_FLUFL", - "generator_stop", - ] +__all__ = [ + "all_feature_names", + "absolute_import", + "division", + "generators", + "nested_scopes", + "print_function", + "unicode_literals", + "with_statement", + "barry_as_FLUFL", + "generator_stop", + "annotations", +] diff --git a/stdlib/__main__.pyi b/stdlib/__main__.pyi index e27843e53382..3536a6f021c5 100644 --- a/stdlib/__main__.pyi +++ b/stdlib/__main__.pyi @@ -1,3 +1 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... +def __getattr__(name: str, /): ... # incomplete module diff --git a/stdlib/_ast.pyi b/stdlib/_ast.pyi index 08725cfc0b77..fd89973aefe6 100644 --- a/stdlib/_ast.pyi +++ b/stdlib/_ast.pyi @@ -1,412 +1,141 @@ import sys -import typing -from typing import Any, ClassVar -from typing_extensions import Literal - -PyCF_ONLY_AST: int -if sys.version_info >= (3, 8): - PyCF_TYPE_COMMENTS: int - PyCF_ALLOW_TOP_LEVEL_AWAIT: int - -_identifier = str - -class AST: - _attributes: ClassVar[typing.Tuple[str, ...]] - _fields: ClassVar[typing.Tuple[str, ...]] - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - # TODO: Not all nodes have all of the following attributes - lineno: int - col_offset: int - if sys.version_info >= (3, 8): - end_lineno: int | None - end_col_offset: int | None - type_comment: str | None - -class mod(AST): ... - -if sys.version_info >= (3, 8): - class type_ignore(AST): ... - class TypeIgnore(type_ignore): - tag: str - class FunctionType(mod): - argtypes: list[expr] - returns: expr - -class Module(mod): - body: list[stmt] - if sys.version_info >= (3, 8): - type_ignores: list[TypeIgnore] - -class Interactive(mod): - body: list[stmt] - -class Expression(mod): - body: expr - -class stmt(AST): ... - -class FunctionDef(stmt): - name: _identifier - args: arguments - body: list[stmt] - decorator_list: list[expr] - returns: expr | None - -class AsyncFunctionDef(stmt): - name: _identifier - args: arguments - body: list[stmt] - decorator_list: list[expr] - returns: expr | None - -class ClassDef(stmt): - name: _identifier - bases: list[expr] - keywords: list[keyword] - body: list[stmt] - decorator_list: list[expr] - -class Return(stmt): - value: expr | None - -class Delete(stmt): - targets: list[expr] - -class Assign(stmt): - targets: list[expr] - value: expr - -class AugAssign(stmt): - target: expr - op: operator - value: expr - -class AnnAssign(stmt): - target: expr - annotation: expr - value: expr | None - simple: int - -class For(stmt): - target: expr - iter: expr - body: list[stmt] - orelse: list[stmt] - -class AsyncFor(stmt): - target: expr - iter: expr - body: list[stmt] - orelse: list[stmt] - -class While(stmt): - test: expr - body: list[stmt] - orelse: list[stmt] - -class If(stmt): - test: expr - body: list[stmt] - orelse: list[stmt] - -class With(stmt): - items: list[withitem] - body: list[stmt] - -class AsyncWith(stmt): - items: list[withitem] - body: list[stmt] - -class Raise(stmt): - exc: expr | None - cause: expr | None - -class Try(stmt): - body: list[stmt] - handlers: list[ExceptHandler] - orelse: list[stmt] - finalbody: list[stmt] - -class Assert(stmt): - test: expr - msg: expr | None - -class Import(stmt): - names: list[alias] - -class ImportFrom(stmt): - module: _identifier | None - names: list[alias] - level: int - -class Global(stmt): - names: list[_identifier] - -class Nonlocal(stmt): - names: list[_identifier] - -class Expr(stmt): - value: expr - -class Pass(stmt): ... -class Break(stmt): ... -class Continue(stmt): ... -class expr(AST): ... - -class BoolOp(expr): - op: boolop - values: list[expr] - -class BinOp(expr): - left: expr - op: operator - right: expr - -class UnaryOp(expr): - op: unaryop - operand: expr - -class Lambda(expr): - args: arguments - body: expr - -class IfExp(expr): - test: expr - body: expr - orelse: expr - -class Dict(expr): - keys: list[expr | None] - values: list[expr] - -class Set(expr): - elts: list[expr] - -class ListComp(expr): - elt: expr - generators: list[comprehension] - -class SetComp(expr): - elt: expr - generators: list[comprehension] - -class DictComp(expr): - key: expr - value: expr - generators: list[comprehension] - -class GeneratorExp(expr): - elt: expr - generators: list[comprehension] - -class Await(expr): - value: expr - -class Yield(expr): - value: expr | None - -class YieldFrom(expr): - value: expr - -class Compare(expr): - left: expr - ops: list[cmpop] - comparators: list[expr] - -class Call(expr): - func: expr - args: list[expr] - keywords: list[keyword] - -class FormattedValue(expr): - value: expr - conversion: int | None - format_spec: expr | None - -class JoinedStr(expr): - values: list[expr] - -if sys.version_info < (3, 8): - class Num(expr): # Deprecated in 3.8; use Constant - n: complex - class Str(expr): # Deprecated in 3.8; use Constant - s: str - class Bytes(expr): # Deprecated in 3.8; use Constant - s: bytes - class NameConstant(expr): # Deprecated in 3.8; use Constant - value: Any - class Ellipsis(expr): ... # Deprecated in 3.8; use Constant - -class Constant(expr): - value: Any # None, str, bytes, bool, int, float, complex, Ellipsis - kind: str | None - # Aliases for value, for backwards compatibility - s: Any - n: complex - -if sys.version_info >= (3, 8): - class NamedExpr(expr): - target: expr - value: expr - -class Attribute(expr): - value: expr - attr: _identifier - ctx: expr_context - -if sys.version_info >= (3, 9): - _SliceT = expr -else: - class slice(AST): ... - _SliceT = slice - -class Slice(_SliceT): - lower: expr | None - upper: expr | None - step: expr | None - -if sys.version_info < (3, 9): - class ExtSlice(slice): - dims: list[slice] - class Index(slice): - value: expr - -class Subscript(expr): - value: expr - slice: _SliceT - ctx: expr_context - -class Starred(expr): - value: expr - ctx: expr_context - -class Name(expr): - id: _identifier - ctx: expr_context - -class List(expr): - elts: list[expr] - ctx: expr_context - -class Tuple(expr): - elts: list[expr] - ctx: expr_context - -class expr_context(AST): ... - -if sys.version_info < (3, 9): - class AugLoad(expr_context): ... - class AugStore(expr_context): ... - class Param(expr_context): ... - class Suite(mod): - body: list[stmt] - -class Del(expr_context): ... -class Load(expr_context): ... -class Store(expr_context): ... -class boolop(AST): ... -class And(boolop): ... -class Or(boolop): ... -class operator(AST): ... -class Add(operator): ... -class BitAnd(operator): ... -class BitOr(operator): ... -class BitXor(operator): ... -class Div(operator): ... -class FloorDiv(operator): ... -class LShift(operator): ... -class Mod(operator): ... -class Mult(operator): ... -class MatMult(operator): ... -class Pow(operator): ... -class RShift(operator): ... -class Sub(operator): ... -class unaryop(AST): ... -class Invert(unaryop): ... -class Not(unaryop): ... -class UAdd(unaryop): ... -class USub(unaryop): ... -class cmpop(AST): ... -class Eq(cmpop): ... -class Gt(cmpop): ... -class GtE(cmpop): ... -class In(cmpop): ... -class Is(cmpop): ... -class IsNot(cmpop): ... -class Lt(cmpop): ... -class LtE(cmpop): ... -class NotEq(cmpop): ... -class NotIn(cmpop): ... - -class comprehension(AST): - target: expr - iter: expr - ifs: list[expr] - is_async: int - -class excepthandler(AST): ... - -class ExceptHandler(excepthandler): - type: expr | None - name: _identifier | None - body: list[stmt] - -class arguments(AST): - if sys.version_info >= (3, 8): - posonlyargs: list[arg] - args: list[arg] - vararg: arg | None - kwonlyargs: list[arg] - kw_defaults: list[expr | None] - kwarg: arg | None - defaults: list[expr] - -class arg(AST): - arg: _identifier - annotation: expr | None - -class keyword(AST): - arg: _identifier | None - value: expr - -class alias(AST): - name: _identifier - asname: _identifier | None - -class withitem(AST): - context_expr: expr - optional_vars: expr | None - -if sys.version_info >= (3, 10): - class Match(stmt): - subject: expr - cases: list[match_case] - class pattern(AST): ... - # Without the alias, Pyright complains variables named pattern are recursively defined - _pattern = pattern - class match_case(AST): - pattern: _pattern - guard: expr | None - body: list[stmt] - class MatchValue(pattern): - value: expr - class MatchSingleton(pattern): - value: Literal[True, False, None] - class MatchSequence(pattern): - patterns: list[pattern] - class MatchStar(pattern): - name: _identifier | None - class MatchMapping(pattern): - keys: list[expr] - patterns: list[pattern] - rest: _identifier | None - class MatchClass(pattern): - cls: expr - patterns: list[pattern] - kwd_attrs: list[_identifier] - kwd_patterns: list[pattern] - class MatchAs(pattern): - pattern: _pattern | None - name: _identifier | None - class MatchOr(pattern): - patterns: list[pattern] +from ast import ( + AST as AST, + Add as Add, + And as And, + AnnAssign as AnnAssign, + Assert as Assert, + Assign as Assign, + AsyncFor as AsyncFor, + AsyncFunctionDef as AsyncFunctionDef, + AsyncWith as AsyncWith, + Attribute as Attribute, + AugAssign as AugAssign, + Await as Await, + BinOp as BinOp, + BitAnd as BitAnd, + BitOr as BitOr, + BitXor as BitXor, + BoolOp as BoolOp, + Break as Break, + Call as Call, + ClassDef as ClassDef, + Compare as Compare, + Constant as Constant, + Continue as Continue, + Del as Del, + Delete as Delete, + Dict as Dict, + DictComp as DictComp, + Div as Div, + Eq as Eq, + ExceptHandler as ExceptHandler, + Expr as Expr, + Expression as Expression, + FloorDiv as FloorDiv, + For as For, + FormattedValue as FormattedValue, + FunctionDef as FunctionDef, + FunctionType as FunctionType, + GeneratorExp as GeneratorExp, + Global as Global, + Gt as Gt, + GtE as GtE, + If as If, + IfExp as IfExp, + Import as Import, + ImportFrom as ImportFrom, + In as In, + Interactive as Interactive, + Invert as Invert, + Is as Is, + IsNot as IsNot, + JoinedStr as JoinedStr, + Lambda as Lambda, + List as List, + ListComp as ListComp, + Load as Load, + LShift as LShift, + Lt as Lt, + LtE as LtE, + Match as Match, + MatchAs as MatchAs, + MatchClass as MatchClass, + MatchMapping as MatchMapping, + MatchOr as MatchOr, + MatchSequence as MatchSequence, + MatchSingleton as MatchSingleton, + MatchStar as MatchStar, + MatchValue as MatchValue, + MatMult as MatMult, + Mod as Mod, + Module as Module, + Mult as Mult, + Name as Name, + NamedExpr as NamedExpr, + Nonlocal as Nonlocal, + Not as Not, + NotEq as NotEq, + NotIn as NotIn, + Or as Or, + Pass as Pass, + Pow as Pow, + Raise as Raise, + Return as Return, + RShift as RShift, + Set as Set, + SetComp as SetComp, + Slice as Slice, + Starred as Starred, + Store as Store, + Sub as Sub, + Subscript as Subscript, + Try as Try, + Tuple as Tuple, + TypeIgnore as TypeIgnore, + UAdd as UAdd, + UnaryOp as UnaryOp, + USub as USub, + While as While, + With as With, + Yield as Yield, + YieldFrom as YieldFrom, + alias as alias, + arg as arg, + arguments as arguments, + boolop as boolop, + cmpop as cmpop, + comprehension as comprehension, + excepthandler as excepthandler, + expr as expr, + expr_context as expr_context, + keyword as keyword, + match_case as match_case, + mod as mod, + operator as operator, + pattern as pattern, + stmt as stmt, + type_ignore as type_ignore, + unaryop as unaryop, + withitem as withitem, +) +from typing import Final + +if sys.version_info >= (3, 12): + from ast import ( + ParamSpec as ParamSpec, + TypeAlias as TypeAlias, + TypeVar as TypeVar, + TypeVarTuple as TypeVarTuple, + type_param as type_param, + ) + +if sys.version_info >= (3, 11): + from ast import TryStar as TryStar + +PyCF_ALLOW_TOP_LEVEL_AWAIT: Final = 8192 +PyCF_ONLY_AST: Final = 1024 +PyCF_TYPE_COMMENTS: Final = 4096 + +if sys.version_info >= (3, 13): + PyCF_OPTIMIZED_AST: Final = 33792 diff --git a/stdlib/_asyncio.pyi b/stdlib/_asyncio.pyi new file mode 100644 index 000000000000..641c152d985b --- /dev/null +++ b/stdlib/_asyncio.pyi @@ -0,0 +1,114 @@ +import sys +from asyncio.events import AbstractEventLoop +from collections.abc import Awaitable, Callable, Coroutine, Generator +from contextvars import Context +from types import FrameType, GenericAlias +from typing import Any, Literal, TextIO, TypeAlias, TypeVar +from typing_extensions import Self, disjoint_base + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_TaskYieldType: TypeAlias = Future[object] | None + +@disjoint_base +class Future(Awaitable[_T]): + _state: str + @property + def _exception(self) -> BaseException | None: ... + _blocking: bool + + @property + def _log_traceback(self) -> bool: ... + @_log_traceback.setter + def _log_traceback(self, val: Literal[False]) -> None: ... + + _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` + def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... + def __del__(self) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + @property + def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ... + def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: ... + def cancel(self, msg: Any | None = None) -> bool: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + def result(self) -> _T: ... + def exception(self) -> BaseException | None: ... + def remove_done_callback(self, fn: Callable[[Self], object], /) -> int: ... + def set_result(self, result: _T, /) -> None: ... + def set_exception(self, exception: type | BaseException, /) -> None: ... + def __iter__(self) -> Generator[Any, None, _T]: ... + def __await__(self) -> Generator[Any, None, _T]: ... + @property + def _loop(self) -> AbstractEventLoop: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 12): + _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] +else: + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] + +# mypy and pyright complain that a subclass of an invariant class shouldn't be covariant. +# While this is true in general, here it's sort-of okay to have a covariant subclass, +# since the only reason why `asyncio.Future` is invariant is the `set_result()` method, +# and `asyncio.Task.set_result()` always raises. +@disjoint_base +class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-generic-class] # pyrefly: ignore [invalid-variance] + if sys.version_info >= (3, 12): + def __init__( + self, + coro: _TaskCompatibleCoro[_T_co], + *, + loop: AbstractEventLoop | None = None, + name: str | None = None, + context: Context | None = None, + eager_start: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + coro: _TaskCompatibleCoro[_T_co], + *, + loop: AbstractEventLoop | None = None, + name: str | None = None, + context: Context | None = None, + ) -> None: ... + else: + def __init__( + self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop | None = None, name: str | None = None + ) -> None: ... + + if sys.version_info >= (3, 12): + def get_coro(self) -> _TaskCompatibleCoro[_T_co] | None: ... + else: + def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ... + + def get_name(self) -> str: ... + def set_name(self, value: object, /) -> None: ... + if sys.version_info >= (3, 12): + def get_context(self) -> Context: ... + + def get_stack(self, *, limit: int | None = None) -> list[FrameType]: ... + def print_stack(self, *, limit: int | None = None, file: TextIO | None = None) -> None: ... + if sys.version_info >= (3, 11): + def cancelling(self) -> int: ... + def uncancel(self) -> int: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def get_event_loop() -> AbstractEventLoop: ... +def get_running_loop() -> AbstractEventLoop: ... +def _set_running_loop(loop: AbstractEventLoop | None, /) -> None: ... +def _get_running_loop() -> AbstractEventLoop | None: ... +def _register_task(task: Task[Any]) -> None: ... +def _unregister_task(task: Task[Any]) -> None: ... +def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... +def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... + +if sys.version_info >= (3, 12): + def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... + +if sys.version_info >= (3, 14): + def future_discard_from_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ... + def future_add_to_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ... + def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... diff --git a/stdlib/_bisect.pyi b/stdlib/_bisect.pyi index 1f67dadd89a0..b87dd8f3fb87 100644 --- a/stdlib/_bisect.pyi +++ b/stdlib/_bisect.pyi @@ -1,35 +1,103 @@ -import sys -from _typeshed import SupportsRichComparison -from typing import Callable, MutableSequence, Sequence, TypeVar +from _typeshed import SupportsGetItem, SupportsLenAndGetItem, SupportsRichComparisonT +from collections.abc import Callable, MutableSequence +from typing import TypeVar, overload _T = TypeVar("_T") -if sys.version_info >= (3, 10): - def bisect_left( - a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparison] | None = ... - ) -> int: ... - def bisect_right( - a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparison] | None = ... - ) -> int: ... - def insort_left( - a: MutableSequence[_T], - x: _T, - lo: int = ..., - hi: int | None = ..., - *, - key: Callable[[_T], SupportsRichComparison] | None = ..., - ) -> None: ... - def insort_right( - a: MutableSequence[_T], - x: _T, - lo: int = ..., - hi: int | None = ..., - *, - key: Callable[[_T], SupportsRichComparison] | None = ..., - ) -> None: ... +@overload +def bisect_left( + a: SupportsLenAndGetItem[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None +) -> int: ... +@overload +def bisect_left( + a: SupportsLenAndGetItem[_T], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: Callable[[_T], SupportsRichComparisonT], +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... -else: - def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> int: ... - def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> int: ... - def insort_left(a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> None: ... - def insort_right(a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> None: ... +@overload +def bisect_right( + a: SupportsLenAndGetItem[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None +) -> int: ... +@overload +def bisect_right( + a: SupportsLenAndGetItem[_T], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: Callable[[_T], SupportsRichComparisonT], +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... + +@overload +def insort_left( + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> None: ... +@overload +def insort_left( + a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] +) -> None: ... + +@overload +def insort_right( + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> None: ... +@overload +def insort_right( + a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] +) -> None: ... diff --git a/stdlib/_blake2.pyi b/stdlib/_blake2.pyi new file mode 100644 index 000000000000..a6c3869fb851 --- /dev/null +++ b/stdlib/_blake2.pyi @@ -0,0 +1,119 @@ +import sys +from _typeshed import ReadableBuffer +from typing import ClassVar, Final, final +from typing_extensions import Self + +BLAKE2B_MAX_DIGEST_SIZE: Final = 64 +BLAKE2B_MAX_KEY_SIZE: Final = 64 +BLAKE2B_PERSON_SIZE: Final = 16 +BLAKE2B_SALT_SIZE: Final = 16 +BLAKE2S_MAX_DIGEST_SIZE: Final = 32 +BLAKE2S_MAX_KEY_SIZE: Final = 32 +BLAKE2S_PERSON_SIZE: Final = 8 +BLAKE2S_SALT_SIZE: Final = 8 + +@final +class blake2b: + MAX_DIGEST_SIZE: ClassVar[int] = 64 + MAX_KEY_SIZE: ClassVar[int] = 64 + PERSON_SIZE: ClassVar[int] = 16 + SALT_SIZE: ClassVar[int] = 16 + block_size: int + digest_size: int + name: str + if sys.version_info >= (3, 13): + def __new__( + cls, + data: ReadableBuffer = b"", + *, + digest_size: int = 64, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + string: ReadableBuffer | None = None, + ) -> Self: ... + else: + def __new__( + cls, + data: ReadableBuffer = b"", + /, + *, + digest_size: int = 64, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + ) -> Self: ... + + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... + +@final +class blake2s: + MAX_DIGEST_SIZE: ClassVar[int] = 32 + MAX_KEY_SIZE: ClassVar[int] = 32 + PERSON_SIZE: ClassVar[int] = 8 + SALT_SIZE: ClassVar[int] = 8 + block_size: int + digest_size: int + name: str + if sys.version_info >= (3, 13): + def __new__( + cls, + data: ReadableBuffer = b"", + *, + digest_size: int = 32, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + string: ReadableBuffer | None = None, + ) -> Self: ... + else: + def __new__( + cls, + data: ReadableBuffer = b"", + /, + *, + digest_size: int = 32, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + ) -> Self: ... + + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... diff --git a/stdlib/_bootlocale.pyi b/stdlib/_bootlocale.pyi deleted file mode 100644 index ee2d89347a9f..000000000000 --- a/stdlib/_bootlocale.pyi +++ /dev/null @@ -1 +0,0 @@ -def getpreferredencoding(do_setlocale: bool = ...) -> str: ... diff --git a/stdlib/_bz2.pyi b/stdlib/_bz2.pyi new file mode 100644 index 000000000000..fdad932ca22e --- /dev/null +++ b/stdlib/_bz2.pyi @@ -0,0 +1,24 @@ +import sys +from _typeshed import ReadableBuffer +from typing import final +from typing_extensions import Self + +@final +class BZ2Compressor: + if sys.version_info >= (3, 12): + def __new__(cls, compresslevel: int = 9, /) -> Self: ... + else: + def __init__(self, compresslevel: int = 9, /) -> None: ... + + def compress(self, data: ReadableBuffer, /) -> bytes: ... + def flush(self) -> bytes: ... + +@final +class BZ2Decompressor: + def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: ... + @property + def eof(self) -> bool: ... + @property + def needs_input(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... diff --git a/stdlib/_codecs.pyi b/stdlib/_codecs.pyi index a44a8a1a7c2a..e854c80ff375 100644 --- a/stdlib/_codecs.pyi +++ b/stdlib/_codecs.pyi @@ -1,78 +1,125 @@ import codecs import sys -from typing import Any, Callable, Dict, Tuple, Union +from _typeshed import ReadableBuffer, SupportsGetItem +from collections.abc import Callable +from typing import Literal, TypeAlias, final, overload, type_check_only # This type is not exposed; it is defined in unicodeobject.c +# At runtime it calls itself builtins.EncodingMap +@final +@type_check_only class _EncodingMap: def size(self) -> int: ... -_MapT = Union[Dict[int, int], _EncodingMap] -_Handler = Callable[[Exception], Tuple[str, int]] +_DecodeCharMap: TypeAlias = SupportsGetItem[int, str | int | None] +_EncodeCharMap: TypeAlias = SupportsGetItem[int, bytes | int | None] | _EncodingMap +_Handler: TypeAlias = Callable[[UnicodeEncodeError | UnicodeDecodeError | UnicodeTranslateError], tuple[str | bytes, int]] +_SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] -def register(__search_function: Callable[[str], Any]) -> None: ... -def register_error(__errors: str, __handler: _Handler) -> None: ... -def lookup(__encoding: str) -> codecs.CodecInfo: ... -def lookup_error(__name: str) -> _Handler: ... -def decode(obj: Any, encoding: str = ..., errors: str | None = ...) -> Any: ... -def encode(obj: Any, encoding: str = ..., errors: str | None = ...) -> Any: ... -def charmap_build(__map: str) -> _MapT: ... -def ascii_decode(__data: bytes, __errors: str | None = ...) -> tuple[str, int]: ... -def ascii_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def charmap_decode(__data: bytes, __errors: str | None = ..., __mapping: _MapT | None = ...) -> tuple[str, int]: ... -def charmap_encode(__str: str, __errors: str | None = ..., __mapping: _MapT | None = ...) -> tuple[bytes, int]: ... -def escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... -def escape_encode(__data: bytes, __errors: str | None = ...) -> tuple[bytes, int]: ... -def latin_1_decode(__data: bytes, __errors: str | None = ...) -> tuple[str, int]: ... -def latin_1_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... +def register(search_function: _SearchFunction, /) -> None: ... +def unregister(search_function: _SearchFunction, /) -> None: ... +def register_error(errors: str, handler: _Handler, /) -> None: ... +def lookup_error(name: str, /) -> _Handler: ... -if sys.version_info >= (3, 9): - def raw_unicode_escape_decode(__data: str | bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... +# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 +# https://docs.python.org/3/library/codecs.html#binary-transforms +_BytesToBytesEncoding: TypeAlias = Literal[ + "base64", + "base_64", + "base64_codec", + "bz2", + "bz2_codec", + "hex", + "hex_codec", + "quopri", + "quotedprintable", + "quoted_printable", + "quopri_codec", + "uu", + "uu_codec", + "zip", + "zlib", + "zlib_codec", +] +# https://docs.python.org/3/library/codecs.html#text-transforms +_StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"] -else: - def raw_unicode_escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... +@overload +def encode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: ... +@overload +def encode(obj: str, encoding: _StrToStrEncoding, errors: str = "strict") -> str: ... # type: ignore[overload-overlap] +@overload +def encode(obj: str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... -def raw_unicode_escape_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def readbuffer_encode(__data: str | bytes, __errors: str | None = ...) -> tuple[bytes, int]: ... +@overload +def decode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: ... # type: ignore[overload-overlap] +@overload +def decode(obj: str, encoding: _StrToStrEncoding, errors: str = "strict") -> str: ... -if sys.version_info >= (3, 9): - def unicode_escape_decode(__data: str | bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... +# these are documented as text encodings but in practice they also accept str as input +@overload +def decode( + obj: str, + encoding: Literal["unicode_escape", "unicode-escape", "raw_unicode_escape", "raw-unicode-escape"], + errors: str = "strict", +) -> str: ... -else: - def unicode_escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... +# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str +@overload +def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = "strict") -> bytes: ... +@overload +def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ... -def unicode_escape_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... +def lookup(encoding: str, /) -> codecs.CodecInfo: ... +def charmap_build(map: str, /) -> dict[int, int] | _EncodingMap: ... +def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def ascii_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def charmap_decode( + data: ReadableBuffer, errors: str | None = None, mapping: _DecodeCharMap | None = None, / +) -> tuple[str, int]: ... +def charmap_encode(str: str, errors: str | None = None, mapping: _EncodeCharMap | None = None, /) -> tuple[bytes, int]: ... -if sys.version_info < (3, 8): - def unicode_internal_decode(__obj: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... - def unicode_internal_encode(__obj: str | bytes, __errors: str | None = ...) -> tuple[bytes, int]: ... - -def utf_16_be_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_16_be_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def utf_16_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_16_encode(__str: str, __errors: str | None = ..., __byteorder: int = ...) -> tuple[bytes, int]: ... +# Docs say this accepts a bytes-like object, but in practice it also accepts str. +def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... +def escape_encode(data: bytes, errors: str | None = None, /) -> tuple[bytes, int]: ... +def latin_1_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def latin_1_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def raw_unicode_escape_decode( + data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / +) -> tuple[str, int]: ... +def raw_unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def readbuffer_encode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... +def unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... +def unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_16_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_16_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ... def utf_16_ex_decode( - __data: bytes, __errors: str | None = ..., __byteorder: int = ..., __final: int = ... + data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, / ) -> tuple[str, int, int]: ... -def utf_16_le_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_16_le_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def utf_32_be_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_32_be_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def utf_32_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_32_encode(__str: str, __errors: str | None = ..., __byteorder: int = ...) -> tuple[bytes, int]: ... +def utf_16_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_32_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_32_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ... def utf_32_ex_decode( - __data: bytes, __errors: str | None = ..., __byteorder: int = ..., __final: int = ... + data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, / ) -> tuple[str, int, int]: ... -def utf_32_le_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_32_le_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def utf_7_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_7_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def utf_8_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... -def utf_8_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... +def utf_32_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_7_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_7_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_8_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_8_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... if sys.platform == "win32": - def mbcs_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... - def mbcs_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... - def code_page_decode(__codepage: int, __data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... - def code_page_encode(__code_page: int, __str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... - def oem_decode(__data: bytes, __errors: str | None = ..., __final: int = ...) -> tuple[str, int]: ... - def oem_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... + def mbcs_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + def mbcs_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + def code_page_decode( + codepage: int, data: ReadableBuffer, errors: str | None = None, final: bool = False, / + ) -> tuple[str, int]: ... + def code_page_encode(code_page: int, str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + def oem_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + def oem_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... diff --git a/stdlib/_collections_abc.pyi b/stdlib/_collections_abc.pyi index 223b5fb8d62e..363098df8058 100644 --- a/stdlib/_collections_abc.pyi +++ b/stdlib/_collections_abc.pyi @@ -1,6 +1,7 @@ import sys +from abc import abstractmethod from types import MappingProxyType -from typing import ( +from typing import ( # noqa: Y022,Y038,Y057 # ruff: ignore[deprecated-import] AbstractSet as Set, AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, @@ -8,6 +9,7 @@ from typing import ( Awaitable as Awaitable, ByteString as ByteString, Callable as Callable, + ClassVar, Collection as Collection, Container as Container, Coroutine as Coroutine, @@ -23,13 +25,15 @@ from typing import ( MutableMapping as MutableMapping, MutableSequence as MutableSequence, MutableSet as MutableSet, + Protocol, Reversible as Reversible, Sequence as Sequence, Sized as Sized, TypeVar, ValuesView as ValuesView, + final, + runtime_checkable, ) -from typing_extensions import final __all__ = [ "Awaitable", @@ -56,23 +60,46 @@ __all__ = [ "ValuesView", "Sequence", "MutableSequence", - "ByteString", ] +if sys.version_info < (3, 15): + __all__ += ["ByteString"] +if sys.version_info >= (3, 12): + __all__ += ["Buffer"] _KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. @final class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented - if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] + def __eq__(self, value: object, /) -> bool: ... + def __reversed__(self) -> Iterator[_KT_co]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 13): + def isdisjoint(self, other: Iterable[_KT_co], /) -> bool: ... + + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @final class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented - if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] + def __reversed__(self) -> Iterator[_VT_co]: ... + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @final -class dict_items(ItemsView[_KT_co, _VT_co], Generic[_KT_co, _VT_co]): # undocumented - if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] +class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented + def __eq__(self, value: object, /) -> bool: ... + def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 13): + def isdisjoint(self, other: Iterable[tuple[_KT_co, _VT_co]], /) -> bool: ... + + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + +if sys.version_info >= (3, 12): + @runtime_checkable + class Buffer(Protocol): + __slots__ = () + @abstractmethod + def __buffer__(self, flags: int, /) -> memoryview: ... diff --git a/stdlib/_compat_pickle.pyi b/stdlib/_compat_pickle.pyi index 50fb22442cc9..32c0b542d991 100644 --- a/stdlib/_compat_pickle.pyi +++ b/stdlib/_compat_pickle.pyi @@ -1,8 +1,10 @@ -IMPORT_MAPPING: dict[str, str] -NAME_MAPPING: dict[tuple[str, str], tuple[str, str]] -PYTHON2_EXCEPTIONS: tuple[str, ...] -MULTIPROCESSING_EXCEPTIONS: tuple[str, ...] -REVERSE_IMPORT_MAPPING: dict[str, str] -REVERSE_NAME_MAPPING: dict[tuple[str, str], tuple[str, str]] -PYTHON3_OSERROR_EXCEPTIONS: tuple[str, ...] -PYTHON3_IMPORTERROR_EXCEPTIONS: tuple[str, ...] +from typing import Final + +IMPORT_MAPPING: Final[dict[str, str]] +NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]] +PYTHON2_EXCEPTIONS: Final[tuple[str, ...]] +MULTIPROCESSING_EXCEPTIONS: Final[tuple[str, ...]] +REVERSE_IMPORT_MAPPING: Final[dict[str, str]] +REVERSE_NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]] +PYTHON3_OSERROR_EXCEPTIONS: Final[tuple[str, ...]] +PYTHON3_IMPORTERROR_EXCEPTIONS: Final[tuple[str, ...]] diff --git a/stdlib/_compression.pyi b/stdlib/_compression.pyi index 8f81847ff492..6015bcb13f1c 100644 --- a/stdlib/_compression.pyi +++ b/stdlib/_compression.pyi @@ -1,13 +1,28 @@ -from _typeshed import WriteableBuffer -from io import BufferedIOBase, RawIOBase -from typing import Any, Callable, Protocol, Tuple, Type +# _compression is replaced by compression._common._streams on Python 3.14+ (PEP-784) -BUFFER_SIZE: Any +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase +from typing import Any, Protocol, type_check_only +BUFFER_SIZE = DEFAULT_BUFFER_SIZE + +@type_check_only class _Reader(Protocol): - def read(self, __n: int) -> bytes: ... + def read(self, n: int, /) -> bytes: ... def seekable(self) -> bool: ... - def seek(self, __n: int) -> Any: ... + def seek(self, n: int, /) -> Any: ... + +@type_check_only +class _Decompressor(Protocol): + def decompress(self, data: ReadableBuffer, /, max_length: int = ...) -> bytes: ... + @property + def unused_data(self) -> bytes: ... + @property + def eof(self) -> bool: ... + # `zlib._Decompress` does not have next property, but `DecompressReader` calls it: + # @property + # def needs_input(self) -> bool: ... class BaseStream(BufferedIOBase): ... @@ -15,14 +30,10 @@ class DecompressReader(RawIOBase): def __init__( self, fp: _Reader, - decomp_factory: Callable[..., object], - trailing_error: Type[Exception] | Tuple[Type[Exception], ...] = ..., - **decomp_args: Any, + decomp_factory: Callable[..., _Decompressor], + trailing_error: type[Exception] | tuple[type[Exception], ...] = (), + **decomp_args: Any, # These are passed to decomp_factory. ) -> None: ... - def readable(self) -> bool: ... - def close(self) -> None: ... - def seekable(self) -> bool: ... def readinto(self, b: WriteableBuffer) -> int: ... - def read(self, size: int = ...) -> bytes: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... diff --git a/stdlib/_contextvars.pyi b/stdlib/_contextvars.pyi new file mode 100644 index 000000000000..56440884a150 --- /dev/null +++ b/stdlib/_contextvars.pyi @@ -0,0 +1,69 @@ +import sys +from collections.abc import Callable, Iterator, Mapping +from types import GenericAlias, TracebackType +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, final, overload +from typing_extensions import Self + +_T = TypeVar("_T") +_D = TypeVar("_D") +_P = ParamSpec("_P") + +@final +class ContextVar(Generic[_T]): + @overload + def __new__(cls, name: str) -> Self: ... + @overload + def __new__(cls, name: str, *, default: _T) -> Self: ... + + def __hash__(self) -> int: ... + @property + def name(self) -> str: ... + + @overload + def get(self) -> _T: ... + @overload + def get(self, default: _T, /) -> _T: ... + @overload + def get(self, default: _D, /) -> _D | _T: ... + + def set(self, value: _T, /) -> Token[_T]: ... + def reset(self, token: Token[_T], /) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class Token(Generic[_T]): + @property + def var(self) -> ContextVar[_T]: ... + @property + def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express + MISSING: ClassVar[object] + __hash__: ClassVar[None] # type: ignore[assignment] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 14): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +def copy_context() -> Context: ... + +# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have +# a different value. +@final +class Context(Mapping[ContextVar[Any], Any]): + def __init__(self) -> None: ... + + @overload + def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: ... + @overload + def get(self, key: ContextVar[_T], default: _T, /) -> _T: ... + @overload + def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... + + def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... + def copy(self) -> Context: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __getitem__(self, key: ContextVar[_T], /) -> _T: ... + def __iter__(self) -> Iterator[ContextVar[Any]]: ... + def __len__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... diff --git a/stdlib/_csv.pyi b/stdlib/_csv.pyi index 65f0ca27f0ec..d3702be78c3d 100644 --- a/stdlib/_csv.pyi +++ b/stdlib/_csv.pyi @@ -1,12 +1,30 @@ -from typing import Any, Iterable, Iterator, List, Protocol, Type, Union +import csv +import sys +from _typeshed import SupportsWrite +from collections.abc import Iterable +from typing import Any, Final, Literal, TypeAlias +from typing_extensions import Self, disjoint_base -QUOTE_ALL: int -QUOTE_MINIMAL: int -QUOTE_NONE: int -QUOTE_NONNUMERIC: int +__version__: Final[str] + +QUOTE_ALL: Final = 1 +QUOTE_MINIMAL: Final = 0 +QUOTE_NONE: Final = 3 +QUOTE_NONNUMERIC: Final = 2 +if sys.version_info >= (3, 12): + QUOTE_STRINGS: Final = 4 + QUOTE_NOTNULL: Final = 5 + +if sys.version_info >= (3, 12): + _QuotingType: TypeAlias = Literal[0, 1, 2, 3, 4, 5] +else: + _QuotingType: TypeAlias = Literal[0, 1, 2, 3] class Error(Exception): ... +_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect] + +@disjoint_base class Dialect: delimiter: str quotechar: str | None @@ -14,28 +32,84 @@ class Dialect: doublequote: bool skipinitialspace: bool lineterminator: str - quoting: int - strict: int - def __init__(self) -> None: ... + quoting: _QuotingType + strict: bool + def __new__( + cls, + dialect: _DialectLike | None = None, + delimiter: str = ",", + doublequote: bool = True, + escapechar: str | None = None, + lineterminator: str = "\r\n", + quotechar: str | None = '"', + quoting: _QuotingType = 0, + skipinitialspace: bool = False, + strict: bool = False, + ) -> Self: ... -_DialectLike = Union[str, Dialect, Type[Dialect]] - -class _reader(Iterator[List[str]]): - dialect: Dialect +# This class calls itself _csv.reader. +@disjoint_base +class Reader: + @property + def dialect(self) -> Dialect: ... line_num: int + def __iter__(self) -> Self: ... def __next__(self) -> list[str]: ... -class _writer: - dialect: Dialect - def writerow(self, row: Iterable[Any]) -> Any: ... - def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... - -class _Writer(Protocol): - def write(self, __s: str) -> object: ... +# This class calls itself _csv.writer. +@disjoint_base +class Writer: + @property + def dialect(self) -> Dialect: ... + if sys.version_info >= (3, 13): + def writerow(self, row: Iterable[Any], /) -> Any: ... + def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: ... + else: + def writerow(self, row: Iterable[Any]) -> Any: ... + def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... -def writer(csvfile: _Writer, dialect: _DialectLike = ..., **fmtparams: Any) -> _writer: ... -def reader(csvfile: Iterable[str], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... -def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... +def writer( + fileobj: SupportsWrite[str], + /, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, +) -> Writer: ... +def reader( + iterable: Iterable[str], + /, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, +) -> Reader: ... +def register_dialect( + name: str, + /, + dialect: type[Dialect | csv.Dialect] | str = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, +) -> None: ... def unregister_dialect(name: str) -> None: ... def get_dialect(name: str) -> Dialect: ... def list_dialects() -> list[str]: ... diff --git a/stdlib/_ctypes.pyi b/stdlib/_ctypes.pyi new file mode 100644 index 000000000000..83ac60fd0d42 --- /dev/null +++ b/stdlib/_ctypes.pyi @@ -0,0 +1,380 @@ +import _typeshed +import builtins +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from abc import abstractmethod +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from ctypes import CDLL, ArgumentError as ArgumentError, c_void_p +from types import GenericAlias +from typing import Any, ClassVar, Final, Generic, Literal, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self + +_T = TypeVar("_T") +_CT = TypeVar("_CT", bound=_CData) + +FUNCFLAG_CDECL: Final = 0x1 +FUNCFLAG_PYTHONAPI: Final = 0x4 +FUNCFLAG_USE_ERRNO: Final = 0x8 +FUNCFLAG_USE_LASTERROR: Final = 0x10 +RTLD_GLOBAL: Final[int] +RTLD_LOCAL: Final[int] + +if sys.version_info >= (3, 11): + CTYPES_MAX_ARGCOUNT: Final[int] + +if sys.version_info >= (3, 12): + SIZEOF_TIME_T: Final[int] + +if sys.platform == "win32": + # Description, Source, HelpFile, HelpContext, scode + _COMError_Details: TypeAlias = tuple[str | None, str | None, str | None, int | None, int | None] + + class COMError(Exception): + hresult: int + text: str | None + details: _COMError_Details + + def __init__(self, hresult: int, text: str | None, details: _COMError_Details) -> None: ... + + def CopyComPointer(src: _PointerLike, dst: _PointerLike | _CArgObject) -> int: ... + + FUNCFLAG_HRESULT: Final = 0x2 + FUNCFLAG_STDCALL: Final = 0x0 + + def FormatError(code: int = ...) -> str: ... + def get_last_error() -> int: ... + def set_last_error(value: int) -> int: ... + def LoadLibrary(name: str, load_flags: int = 0, /) -> int: ... + def FreeLibrary(handle: int, /) -> None: ... + +else: + def dlclose(handle: int, /) -> None: ... + # The default for flag is RTLD_GLOBAL|RTLD_LOCAL, which is platform dependent. + def dlopen(name: StrOrBytesPath, flag: int = ..., /) -> int: ... + def dlsym(handle: int, name: str, /) -> int: ... + +if sys.version_info >= (3, 13): + # This class is not exposed. It calls itself _ctypes.CType_Type. + @type_check_only + class _CType_Type(type): + # By default mypy complains about the following two methods, because strictly speaking cls + # might not be a Type[_CT]. However this doesn't happen because this is only a + # metaclass for subclasses of _CData. + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + + _CTypeBaseType = _CType_Type + +else: + _CTypeBaseType = type + +# This class is not exposed. +@type_check_only +class _CData: + _b_base_: int + _b_needsfree_: bool + _objects: Mapping[Any, int] | None + def __buffer__(self, flags: int, /) -> memoryview: ... + def __ctypes_from_outparam__(self, /) -> Self: ... + if sys.version_info >= (3, 14): + __pointer_type__: type + +# this is a union of all the subclasses of _CData, which is useful because of +# the methods that are present on each of those subclasses which are not present +# on _CData itself. +_CDataType: TypeAlias = _SimpleCData[Any] | _Pointer[Any] | CFuncPtr | Union | Structure | Array[Any] + +# This class is not exposed. It calls itself _ctypes.PyCSimpleType. +@type_check_only +class _PyCSimpleType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType): + value: _T + # The TypeVar can be unsolved here, + # but we can't use overloads without creating many, many mypy false-positive errors + def __init__(self, value: _T = ...) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] + def __ctypes_from_outparam__(self, /) -> _T: ... # type: ignore[override] + +@type_check_only +class _CanCastTo(_CData): ... + +@type_check_only +class _PointerLike(_CanCastTo): ... + +# This type is not exposed. It calls itself _ctypes.PyCPointerType. +@type_check_only +class _PyCPointerType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + def set_type(self, type: _CTypeBaseType, /) -> None: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType): + _type_: type[_CT] + contents: _CT + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, arg: _CT) -> None: ... + + @overload + def __getitem__(self, key: int, /) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ... + + def __setitem__(self, key: int, value: Any, /) -> None: ... + +if sys.version_info < (3, 14): + @overload + def POINTER(type: None, /) -> type[c_void_p]: ... + @overload + def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ... + + def pointer(obj: _CT, /) -> _Pointer[_CT]: ... + +# This class is not exposed. It calls itself _ctypes.CArgObject. +@final +@type_check_only +class _CArgObject: ... + +if sys.version_info >= (3, 14): + def byref(obj: _CData | _CDataType, offset: int = 0, /) -> _CArgObject: ... + +else: + def byref(obj: _CData | _CDataType, offset: int = 0) -> _CArgObject: ... + +_ECT: TypeAlias = Callable[[_CData | _CDataType | None, CFuncPtr, tuple[_CData | _CDataType, ...]], _CDataType] +_PF: TypeAlias = tuple[int] | tuple[int, str | None] | tuple[int, str | None, Any] + +# This class is not exposed. It calls itself _ctypes.PyCFuncPtrType. +@type_check_only +class _PyCFuncPtrType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType): + restype: type[_CDataType] | Callable[[int], Any] | None + argtypes: Sequence[type[_CDataType]] + errcheck: _ECT + # Abstract attribute that must be defined on subclasses + _flags_: ClassVar[int] + + @overload + def __new__(cls) -> Self: ... + @overload + def __new__(cls, address: int, /) -> Self: ... + @overload + def __new__(cls, callable: Callable[..., Any], /) -> Self: ... + @overload + def __new__(cls, func_spec: tuple[str | int, CDLL], paramflags: tuple[_PF, ...] | None = ..., /) -> Self: ... + if sys.platform == "win32": + @overload + def __new__( + cls, vtbl_index: int, name: str, paramflags: tuple[_PF, ...] | None = ..., iid: _CData | _CDataType | None = ..., / + ) -> Self: ... + + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +_GetT = TypeVar("_GetT") +_SetT = TypeVar("_SetT") + +if sys.version_info >= (3, 14): + @final + class CField(Generic[_CT, _GetT, _SetT]): + offset: int + size: int + name: str + type: builtins.type[_CT] + byte_offset: int + byte_size: int + is_bitfield: bool + bit_offset: int + bit_size: int + is_anonymous: bool + + @overload + def __get__(self, instance: None, owner: builtins.type[Any] | None = None, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: builtins.type[Any] | None = None, /) -> _GetT: ... + + def __set__(self, instance: Any, value: _SetT, /) -> None: ... + + _CField = CField + +else: + @final + @type_check_only + class _CField(Generic[_CT, _GetT, _SetT]): + offset: int + size: int + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> _GetT: ... + + def __set__(self, instance: Any, value: _SetT, /) -> None: ... + +# This class is not exposed. It calls itself _ctypes.UnionType. +@type_check_only +class _UnionType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + # At runtime, various attributes are created on a Union subclass based + # on its _fields_. This method doesn't exist, but represents those + # dynamically created attributes. + def __getattr__(self, name: str, /) -> _CField[Any, Any, Any]: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class Union(_CData, metaclass=_UnionType): + _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] + _pack_: ClassVar[int] + _anonymous_: ClassVar[Sequence[str]] + if sys.version_info >= (3, 13): + _align_: ClassVar[int] + + def __init__(self, *args: Any, **kw: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +# This class is not exposed. It calls itself _ctypes.PyCStructType. +@type_check_only +class _PyCStructType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + # At runtime, various attributes are created on a Structure subclass based + # on its _fields_. This method doesn't exist, but represents those + # dynamically created attributes. + def __getattr__(self, name: str, /) -> _CField[Any, Any, Any]: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class Structure(_CData, metaclass=_PyCStructType): + _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] + _pack_: ClassVar[int] + _anonymous_: ClassVar[Sequence[str]] + if sys.version_info >= (3, 13): + _align_: ClassVar[int] + + if sys.version_info >= (3, 14): + # _layout_ can be defined by the user, but is not always present. + _layout_: ClassVar[Literal["ms", "gcc-sysv"]] + + def __init__(self, *args: Any, **kw: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +# This class is not exposed. It calls itself _ctypes.PyCArrayType. +@type_check_only +class _PyCArrayType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): + @property + @abstractmethod + def _length_(self) -> int: ... + @_length_.setter + def _length_(self, value: int) -> None: ... + + @property + @abstractmethod + def _type_(self) -> type[_CT]: ... + @_type_.setter + def _type_(self, value: type[_CT]) -> None: ... + + # Note: only available if _CT == c_char + @property + def raw(self) -> bytes: ... + @raw.setter + def raw(self, value: ReadableBuffer) -> None: ... + + value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise + # TODO: These methods cannot be annotated correctly at the moment. + # All of these "Any"s stand for the array's element type, but it's not possible to use _CT + # here, because of a special feature of ctypes. + # By default, when accessing an element of an Array[_CT], the returned object has type _CT. + # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object + # and converts it to the corresponding Python primitive. For example, when accessing an element + # of an Array[c_int], a Python int object is returned, not a c_int. + # This behavior does *not* apply to subclasses of "simple types". + # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns + # a MyInt, not an int. + # This special behavior is not easy to model in a stub, so for now all places where + # the array element type would belong are annotated with Any instead. + def __init__(self, *args: Any) -> None: ... + + @overload + def __getitem__(self, key: int, /) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ... + + @overload + def __setitem__(self, key: int, value: Any, /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Any], /) -> None: ... + + def __iter__(self) -> Iterator[Any]: ... + # Can't inherit from Sized because the metaclass conflict between + # Sized and _CData prevents using _CDataMeta. + def __len__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def addressof(obj: _CData | _CDataType, /) -> int: ... +def alignment(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ... +def get_errno() -> int: ... +def resize(obj: _CData | _CDataType, size: int, /) -> None: ... +def set_errno(value: int, /) -> int: ... +def sizeof(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ... +def PyObj_FromPtr(address: int, /) -> Any: ... +def Py_DECREF(o: _T, /) -> _T: ... +def Py_INCREF(o: _T, /) -> _T: ... +def buffer_info(o: _CData | _CDataType | type[_CData | _CDataType], /) -> tuple[str, int, tuple[int, ...]]: ... +def call_cdeclfunction(address: int, arguments: tuple[Any, ...], /) -> Any: ... +def call_function(address: int, arguments: tuple[Any, ...], /) -> Any: ... + +# dllist() is available on Linux and other platforms like NetBSD +if sys.version_info >= (3, 14) and sys.platform != "win32" and sys.platform != "darwin": + # Added in Python 3.14.7 + def dllist() -> list[str]: ... diff --git a/stdlib/_curses.pyi b/stdlib/_curses.pyi index d2eb1e1a4efb..fcd0da4c465c 100644 --- a/stdlib/_curses.pyi +++ b/stdlib/_curses.pyi @@ -1,418 +1,418 @@ import sys -from _typeshed import SupportsRead -from typing import IO, Any, NamedTuple, Union, overload +from _typeshed import ReadOnlyBuffer, SupportsRead, SupportsWrite +from curses import _ncurses_version +from typing import Any, Final, TypeAlias, final, overload -_chtype = Union[str, bytes, int] +# NOTE: This module is ordinarily only available on Unix, but the windows-curses +# package makes it available on Windows as well with the same contents. + +# Handled by PyCurses_ConvertToChtype in _cursesmodule.c. +_ChType: TypeAlias = str | bytes | int # ACS codes are only initialized after initscr is called -ACS_BBSS: int -ACS_BLOCK: int -ACS_BOARD: int -ACS_BSBS: int -ACS_BSSB: int -ACS_BSSS: int -ACS_BTEE: int -ACS_BULLET: int -ACS_CKBOARD: int -ACS_DARROW: int -ACS_DEGREE: int -ACS_DIAMOND: int -ACS_GEQUAL: int -ACS_HLINE: int -ACS_LANTERN: int -ACS_LARROW: int -ACS_LEQUAL: int -ACS_LLCORNER: int -ACS_LRCORNER: int -ACS_LTEE: int -ACS_NEQUAL: int -ACS_PI: int -ACS_PLMINUS: int -ACS_PLUS: int -ACS_RARROW: int -ACS_RTEE: int -ACS_S1: int -ACS_S3: int -ACS_S7: int -ACS_S9: int -ACS_SBBS: int -ACS_SBSB: int -ACS_SBSS: int -ACS_SSBB: int -ACS_SSBS: int -ACS_SSSB: int -ACS_SSSS: int -ACS_STERLING: int -ACS_TTEE: int -ACS_UARROW: int -ACS_ULCORNER: int -ACS_URCORNER: int -ACS_VLINE: int -ALL_MOUSE_EVENTS: int -A_ALTCHARSET: int -A_ATTRIBUTES: int -A_BLINK: int -A_BOLD: int -A_CHARTEXT: int -A_COLOR: int -A_DIM: int -A_HORIZONTAL: int -A_INVIS: int -if sys.version_info >= (3, 7): - A_ITALIC: int -A_LEFT: int -A_LOW: int -A_NORMAL: int -A_PROTECT: int -A_REVERSE: int -A_RIGHT: int -A_STANDOUT: int -A_TOP: int -A_UNDERLINE: int -A_VERTICAL: int -BUTTON1_CLICKED: int -BUTTON1_DOUBLE_CLICKED: int -BUTTON1_PRESSED: int -BUTTON1_RELEASED: int -BUTTON1_TRIPLE_CLICKED: int -BUTTON2_CLICKED: int -BUTTON2_DOUBLE_CLICKED: int -BUTTON2_PRESSED: int -BUTTON2_RELEASED: int -BUTTON2_TRIPLE_CLICKED: int -BUTTON3_CLICKED: int -BUTTON3_DOUBLE_CLICKED: int -BUTTON3_PRESSED: int -BUTTON3_RELEASED: int -BUTTON3_TRIPLE_CLICKED: int -BUTTON4_CLICKED: int -BUTTON4_DOUBLE_CLICKED: int -BUTTON4_PRESSED: int -BUTTON4_RELEASED: int -BUTTON4_TRIPLE_CLICKED: int -# Darwin ncurses doesn't provide BUTTON5_* constants -if sys.version_info >= (3, 10) and sys.platform != "darwin": - BUTTON5_PRESSED: int - BUTTON5_RELEASED: int - BUTTON5_CLICKED: int - BUTTON5_DOUBLE_CLICKED: int - BUTTON5_TRIPLE_CLICKED: int -BUTTON_ALT: int -BUTTON_CTRL: int -BUTTON_SHIFT: int -COLOR_BLACK: int -COLOR_BLUE: int -COLOR_CYAN: int -COLOR_GREEN: int -COLOR_MAGENTA: int -COLOR_RED: int -COLOR_WHITE: int -COLOR_YELLOW: int -ERR: int -KEY_A1: int -KEY_A3: int -KEY_B2: int -KEY_BACKSPACE: int -KEY_BEG: int -KEY_BREAK: int -KEY_BTAB: int -KEY_C1: int -KEY_C3: int -KEY_CANCEL: int -KEY_CATAB: int -KEY_CLEAR: int -KEY_CLOSE: int -KEY_COMMAND: int -KEY_COPY: int -KEY_CREATE: int -KEY_CTAB: int -KEY_DC: int -KEY_DL: int -KEY_DOWN: int -KEY_EIC: int -KEY_END: int -KEY_ENTER: int -KEY_EOL: int -KEY_EOS: int -KEY_EXIT: int -KEY_F0: int -KEY_F1: int -KEY_F10: int -KEY_F11: int -KEY_F12: int -KEY_F13: int -KEY_F14: int -KEY_F15: int -KEY_F16: int -KEY_F17: int -KEY_F18: int -KEY_F19: int -KEY_F2: int -KEY_F20: int -KEY_F21: int -KEY_F22: int -KEY_F23: int -KEY_F24: int -KEY_F25: int -KEY_F26: int -KEY_F27: int -KEY_F28: int -KEY_F29: int -KEY_F3: int -KEY_F30: int -KEY_F31: int -KEY_F32: int -KEY_F33: int -KEY_F34: int -KEY_F35: int -KEY_F36: int -KEY_F37: int -KEY_F38: int -KEY_F39: int -KEY_F4: int -KEY_F40: int -KEY_F41: int -KEY_F42: int -KEY_F43: int -KEY_F44: int -KEY_F45: int -KEY_F46: int -KEY_F47: int -KEY_F48: int -KEY_F49: int -KEY_F5: int -KEY_F50: int -KEY_F51: int -KEY_F52: int -KEY_F53: int -KEY_F54: int -KEY_F55: int -KEY_F56: int -KEY_F57: int -KEY_F58: int -KEY_F59: int -KEY_F6: int -KEY_F60: int -KEY_F61: int -KEY_F62: int -KEY_F63: int -KEY_F7: int -KEY_F8: int -KEY_F9: int -KEY_FIND: int -KEY_HELP: int -KEY_HOME: int -KEY_IC: int -KEY_IL: int -KEY_LEFT: int -KEY_LL: int -KEY_MARK: int -KEY_MAX: int -KEY_MESSAGE: int -KEY_MIN: int -KEY_MOUSE: int -KEY_MOVE: int -KEY_NEXT: int -KEY_NPAGE: int -KEY_OPEN: int -KEY_OPTIONS: int -KEY_PPAGE: int -KEY_PREVIOUS: int -KEY_PRINT: int -KEY_REDO: int -KEY_REFERENCE: int -KEY_REFRESH: int -KEY_REPLACE: int -KEY_RESET: int -KEY_RESIZE: int -KEY_RESTART: int -KEY_RESUME: int -KEY_RIGHT: int -KEY_SAVE: int -KEY_SBEG: int -KEY_SCANCEL: int -KEY_SCOMMAND: int -KEY_SCOPY: int -KEY_SCREATE: int -KEY_SDC: int -KEY_SDL: int -KEY_SELECT: int -KEY_SEND: int -KEY_SEOL: int -KEY_SEXIT: int -KEY_SF: int -KEY_SFIND: int -KEY_SHELP: int -KEY_SHOME: int -KEY_SIC: int -KEY_SLEFT: int -KEY_SMESSAGE: int -KEY_SMOVE: int -KEY_SNEXT: int -KEY_SOPTIONS: int -KEY_SPREVIOUS: int -KEY_SPRINT: int -KEY_SR: int -KEY_SREDO: int -KEY_SREPLACE: int -KEY_SRESET: int -KEY_SRIGHT: int -KEY_SRSUME: int -KEY_SSAVE: int -KEY_SSUSPEND: int -KEY_STAB: int -KEY_SUNDO: int -KEY_SUSPEND: int -KEY_UNDO: int -KEY_UP: int -OK: int -REPORT_MOUSE_POSITION: int +ACS_BBSS: Final[int] +ACS_BLOCK: Final[int] +ACS_BOARD: Final[int] +ACS_BSBS: Final[int] +ACS_BSSB: Final[int] +ACS_BSSS: Final[int] +ACS_BTEE: Final[int] +ACS_BULLET: Final[int] +ACS_CKBOARD: Final[int] +ACS_DARROW: Final[int] +ACS_DEGREE: Final[int] +ACS_DIAMOND: Final[int] +ACS_GEQUAL: Final[int] +ACS_HLINE: Final[int] +ACS_LANTERN: Final[int] +ACS_LARROW: Final[int] +ACS_LEQUAL: Final[int] +ACS_LLCORNER: Final[int] +ACS_LRCORNER: Final[int] +ACS_LTEE: Final[int] +ACS_NEQUAL: Final[int] +ACS_PI: Final[int] +ACS_PLMINUS: Final[int] +ACS_PLUS: Final[int] +ACS_RARROW: Final[int] +ACS_RTEE: Final[int] +ACS_S1: Final[int] +ACS_S3: Final[int] +ACS_S7: Final[int] +ACS_S9: Final[int] +ACS_SBBS: Final[int] +ACS_SBSB: Final[int] +ACS_SBSS: Final[int] +ACS_SSBB: Final[int] +ACS_SSBS: Final[int] +ACS_SSSB: Final[int] +ACS_SSSS: Final[int] +ACS_STERLING: Final[int] +ACS_TTEE: Final[int] +ACS_UARROW: Final[int] +ACS_ULCORNER: Final[int] +ACS_URCORNER: Final[int] +ACS_VLINE: Final[int] +ALL_MOUSE_EVENTS: Final[int] +A_ALTCHARSET: Final[int] +A_ATTRIBUTES: Final[int] +A_BLINK: Final[int] +A_BOLD: Final[int] +A_CHARTEXT: Final[int] +A_COLOR: Final[int] +A_DIM: Final[int] +A_HORIZONTAL: Final[int] +A_INVIS: Final[int] +A_ITALIC: Final[int] +A_LEFT: Final[int] +A_LOW: Final[int] +A_NORMAL: Final[int] +A_PROTECT: Final[int] +A_REVERSE: Final[int] +A_RIGHT: Final[int] +A_STANDOUT: Final[int] +A_TOP: Final[int] +A_UNDERLINE: Final[int] +A_VERTICAL: Final[int] +BUTTON1_CLICKED: Final[int] +BUTTON1_DOUBLE_CLICKED: Final[int] +BUTTON1_PRESSED: Final[int] +BUTTON1_RELEASED: Final[int] +BUTTON1_TRIPLE_CLICKED: Final[int] +BUTTON2_CLICKED: Final[int] +BUTTON2_DOUBLE_CLICKED: Final[int] +BUTTON2_PRESSED: Final[int] +BUTTON2_RELEASED: Final[int] +BUTTON2_TRIPLE_CLICKED: Final[int] +BUTTON3_CLICKED: Final[int] +BUTTON3_DOUBLE_CLICKED: Final[int] +BUTTON3_PRESSED: Final[int] +BUTTON3_RELEASED: Final[int] +BUTTON3_TRIPLE_CLICKED: Final[int] +BUTTON4_CLICKED: Final[int] +BUTTON4_DOUBLE_CLICKED: Final[int] +BUTTON4_PRESSED: Final[int] +BUTTON4_RELEASED: Final[int] +BUTTON4_TRIPLE_CLICKED: Final[int] +# Darwin ncurses doesn't provide BUTTON5_* constants prior to 3.12.10 and 3.13.3 +if sys.version_info >= (3, 12) or sys.platform != "darwin": + BUTTON5_PRESSED: Final[int] + BUTTON5_RELEASED: Final[int] + BUTTON5_CLICKED: Final[int] + BUTTON5_DOUBLE_CLICKED: Final[int] + BUTTON5_TRIPLE_CLICKED: Final[int] +BUTTON_ALT: Final[int] +BUTTON_CTRL: Final[int] +BUTTON_SHIFT: Final[int] +COLOR_BLACK: Final[int] +COLOR_BLUE: Final[int] +COLOR_CYAN: Final[int] +COLOR_GREEN: Final[int] +COLOR_MAGENTA: Final[int] +COLOR_RED: Final[int] +COLOR_WHITE: Final[int] +COLOR_YELLOW: Final[int] +ERR: Final[int] +KEY_A1: Final[int] +KEY_A3: Final[int] +KEY_B2: Final[int] +KEY_BACKSPACE: Final[int] +KEY_BEG: Final[int] +KEY_BREAK: Final[int] +KEY_BTAB: Final[int] +KEY_C1: Final[int] +KEY_C3: Final[int] +KEY_CANCEL: Final[int] +KEY_CATAB: Final[int] +KEY_CLEAR: Final[int] +KEY_CLOSE: Final[int] +KEY_COMMAND: Final[int] +KEY_COPY: Final[int] +KEY_CREATE: Final[int] +KEY_CTAB: Final[int] +KEY_DC: Final[int] +KEY_DL: Final[int] +KEY_DOWN: Final[int] +KEY_EIC: Final[int] +KEY_END: Final[int] +KEY_ENTER: Final[int] +KEY_EOL: Final[int] +KEY_EOS: Final[int] +KEY_EXIT: Final[int] +KEY_F0: Final[int] +KEY_F1: Final[int] +KEY_F10: Final[int] +KEY_F11: Final[int] +KEY_F12: Final[int] +KEY_F13: Final[int] +KEY_F14: Final[int] +KEY_F15: Final[int] +KEY_F16: Final[int] +KEY_F17: Final[int] +KEY_F18: Final[int] +KEY_F19: Final[int] +KEY_F2: Final[int] +KEY_F20: Final[int] +KEY_F21: Final[int] +KEY_F22: Final[int] +KEY_F23: Final[int] +KEY_F24: Final[int] +KEY_F25: Final[int] +KEY_F26: Final[int] +KEY_F27: Final[int] +KEY_F28: Final[int] +KEY_F29: Final[int] +KEY_F3: Final[int] +KEY_F30: Final[int] +KEY_F31: Final[int] +KEY_F32: Final[int] +KEY_F33: Final[int] +KEY_F34: Final[int] +KEY_F35: Final[int] +KEY_F36: Final[int] +KEY_F37: Final[int] +KEY_F38: Final[int] +KEY_F39: Final[int] +KEY_F4: Final[int] +KEY_F40: Final[int] +KEY_F41: Final[int] +KEY_F42: Final[int] +KEY_F43: Final[int] +KEY_F44: Final[int] +KEY_F45: Final[int] +KEY_F46: Final[int] +KEY_F47: Final[int] +KEY_F48: Final[int] +KEY_F49: Final[int] +KEY_F5: Final[int] +KEY_F50: Final[int] +KEY_F51: Final[int] +KEY_F52: Final[int] +KEY_F53: Final[int] +KEY_F54: Final[int] +KEY_F55: Final[int] +KEY_F56: Final[int] +KEY_F57: Final[int] +KEY_F58: Final[int] +KEY_F59: Final[int] +KEY_F6: Final[int] +KEY_F60: Final[int] +KEY_F61: Final[int] +KEY_F62: Final[int] +KEY_F63: Final[int] +KEY_F7: Final[int] +KEY_F8: Final[int] +KEY_F9: Final[int] +KEY_FIND: Final[int] +KEY_HELP: Final[int] +KEY_HOME: Final[int] +KEY_IC: Final[int] +KEY_IL: Final[int] +KEY_LEFT: Final[int] +KEY_LL: Final[int] +KEY_MARK: Final[int] +KEY_MAX: Final[int] +KEY_MESSAGE: Final[int] +KEY_MIN: Final[int] +KEY_MOUSE: Final[int] +KEY_MOVE: Final[int] +KEY_NEXT: Final[int] +KEY_NPAGE: Final[int] +KEY_OPEN: Final[int] +KEY_OPTIONS: Final[int] +KEY_PPAGE: Final[int] +KEY_PREVIOUS: Final[int] +KEY_PRINT: Final[int] +KEY_REDO: Final[int] +KEY_REFERENCE: Final[int] +KEY_REFRESH: Final[int] +KEY_REPLACE: Final[int] +KEY_RESET: Final[int] +KEY_RESIZE: Final[int] +KEY_RESTART: Final[int] +KEY_RESUME: Final[int] +KEY_RIGHT: Final[int] +KEY_SAVE: Final[int] +KEY_SBEG: Final[int] +KEY_SCANCEL: Final[int] +KEY_SCOMMAND: Final[int] +KEY_SCOPY: Final[int] +KEY_SCREATE: Final[int] +KEY_SDC: Final[int] +KEY_SDL: Final[int] +KEY_SELECT: Final[int] +KEY_SEND: Final[int] +KEY_SEOL: Final[int] +KEY_SEXIT: Final[int] +KEY_SF: Final[int] +KEY_SFIND: Final[int] +KEY_SHELP: Final[int] +KEY_SHOME: Final[int] +KEY_SIC: Final[int] +KEY_SLEFT: Final[int] +KEY_SMESSAGE: Final[int] +KEY_SMOVE: Final[int] +KEY_SNEXT: Final[int] +KEY_SOPTIONS: Final[int] +KEY_SPREVIOUS: Final[int] +KEY_SPRINT: Final[int] +KEY_SR: Final[int] +KEY_SREDO: Final[int] +KEY_SREPLACE: Final[int] +KEY_SRESET: Final[int] +KEY_SRIGHT: Final[int] +KEY_SRSUME: Final[int] +KEY_SSAVE: Final[int] +KEY_SSUSPEND: Final[int] +KEY_STAB: Final[int] +KEY_SUNDO: Final[int] +KEY_SUSPEND: Final[int] +KEY_UNDO: Final[int] +KEY_UP: Final[int] +OK: Final[int] +REPORT_MOUSE_POSITION: Final[int] _C_API: Any -version: bytes +version: Final[bytes] def baudrate() -> int: ... def beep() -> None: ... def can_change_color() -> bool: ... -def cbreak(__flag: bool = ...) -> None: ... -def color_content(__color_number: int) -> tuple[int, int, int]: ... - -# Changed in Python 3.8.8 and 3.9.2 -if sys.version_info >= (3, 8): - def color_pair(pair_number: int) -> int: ... - -else: - def color_pair(__color_number: int) -> int: ... - -def curs_set(__visibility: int) -> int: ... +def cbreak(flag: bool = True, /) -> None: ... +def color_content(color_number: int, /) -> tuple[int, int, int]: ... +def color_pair(pair_number: int, /) -> int: ... +def curs_set(visibility: int, /) -> int: ... def def_prog_mode() -> None: ... def def_shell_mode() -> None: ... -def delay_output(__ms: int) -> None: ... +def delay_output(ms: int, /) -> None: ... def doupdate() -> None: ... -def echo(__flag: bool = ...) -> None: ... +def echo(flag: bool = True, /) -> None: ... def endwin() -> None: ... def erasechar() -> bytes: ... def filter() -> None: ... def flash() -> None: ... def flushinp() -> None: ... - -if sys.version_info >= (3, 9): - def get_escdelay() -> int: ... - def get_tabsize() -> int: ... - +def get_escdelay() -> int: ... +def get_tabsize() -> int: ... def getmouse() -> tuple[int, int, int, int, int]: ... def getsyx() -> tuple[int, int]: ... -def getwin(__file: SupportsRead[bytes]) -> _CursesWindow: ... -def halfdelay(__tenths: int) -> None: ... +def getwin(file: SupportsRead[bytes], /) -> window: ... +def halfdelay(tenths: int, /) -> None: ... def has_colors() -> bool: ... +def has_extended_color_support() -> bool: ... -if sys.version_info >= (3, 10): - def has_extended_color_support() -> bool: ... +if sys.version_info >= (3, 14): + def assume_default_colors(fg: int, bg: int, /) -> None: ... def has_ic() -> bool: ... def has_il() -> bool: ... -def has_key(__key: int) -> bool: ... -def init_color(__color_number: int, __r: int, __g: int, __b: int) -> None: ... -def init_pair(__pair_number: int, __fg: int, __bg: int) -> None: ... -def initscr() -> _CursesWindow: ... -def intrflush(__flag: bool) -> None: ... -def is_term_resized(__nlines: int, __ncols: int) -> bool: ... +def has_key(key: int, /) -> bool: ... +def init_color(color_number: int, r: int, g: int, b: int, /) -> None: ... +def init_pair(pair_number: int, fg: int, bg: int, /) -> None: ... +def initscr() -> window: ... +def intrflush(flag: bool, /) -> None: ... +def is_term_resized(nlines: int, ncols: int, /) -> bool: ... def isendwin() -> bool: ... -def keyname(__key: int) -> bytes: ... +def keyname(key: int, /) -> bytes: ... def killchar() -> bytes: ... def longname() -> bytes: ... -def meta(__yes: bool) -> None: ... -def mouseinterval(__interval: int) -> None: ... -def mousemask(__newmask: int) -> tuple[int, int]: ... -def napms(__ms: int) -> int: ... -def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... -def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... -def nl(__flag: bool = ...) -> None: ... +def meta(yes: bool, /) -> None: ... +def mouseinterval(interval: int, /) -> None: ... +def mousemask(newmask: int, /) -> tuple[int, int]: ... +def napms(ms: int, /) -> int: ... +def newpad(nlines: int, ncols: int, /) -> window: ... +def newwin(nlines: int, ncols: int, begin_y: int = 0, begin_x: int = 0, /) -> window: ... +def nl(flag: bool = True, /) -> None: ... def nocbreak() -> None: ... def noecho() -> None: ... def nonl() -> None: ... def noqiflush() -> None: ... def noraw() -> None: ... -def pair_content(__pair_number: int) -> tuple[int, int]: ... -def pair_number(__attr: int) -> int: ... -def putp(__string: bytes) -> None: ... -def qiflush(__flag: bool = ...) -> None: ... -def raw(__flag: bool = ...) -> None: ... +def pair_content(pair_number: int, /) -> tuple[int, int]: ... +def pair_number(attr: int, /) -> int: ... +def putp(string: ReadOnlyBuffer, /) -> None: ... +def qiflush(flag: bool = True, /) -> None: ... +def raw(flag: bool = True, /) -> None: ... def reset_prog_mode() -> None: ... def reset_shell_mode() -> None: ... def resetty() -> None: ... -def resize_term(__nlines: int, __ncols: int) -> None: ... -def resizeterm(__nlines: int, __ncols: int) -> None: ... +def resize_term(nlines: int, ncols: int, /) -> None: ... +def resizeterm(nlines: int, ncols: int, /) -> None: ... def savetty() -> None: ... - -if sys.version_info >= (3, 9): - def set_escdelay(__ms: int) -> None: ... - def set_tabsize(__size: int) -> None: ... - -def setsyx(__y: int, __x: int) -> None: ... -def setupterm(term: str | None = ..., fd: int = ...) -> None: ... +def set_escdelay(ms: int, /) -> None: ... +def set_tabsize(size: int, /) -> None: ... +def setsyx(y: int, x: int, /) -> None: ... +def setupterm(term: str | None = None, fd: int = -1) -> None: ... def start_color() -> None: ... def termattrs() -> int: ... def termname() -> bytes: ... -def tigetflag(__capname: str) -> int: ... -def tigetnum(__capname: str) -> int: ... -def tigetstr(__capname: str) -> bytes | None: ... +def tigetflag(capname: str, /) -> int: ... +def tigetnum(capname: str, /) -> int: ... +def tigetstr(capname: str, /) -> bytes | None: ... def tparm( - __str: bytes, - __i1: int = ..., - __i2: int = ..., - __i3: int = ..., - __i4: int = ..., - __i5: int = ..., - __i6: int = ..., - __i7: int = ..., - __i8: int = ..., - __i9: int = ..., + str: ReadOnlyBuffer, + i1: int = 0, + i2: int = 0, + i3: int = 0, + i4: int = 0, + i5: int = 0, + i6: int = 0, + i7: int = 0, + i8: int = 0, + i9: int = 0, + /, ) -> bytes: ... -def typeahead(__fd: int) -> None: ... -def unctrl(__ch: _chtype) -> bytes: ... -def unget_wch(__ch: int | str) -> None: ... -def ungetch(__ch: _chtype) -> None: ... -def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... +def typeahead(fd: int, /) -> None: ... +def unctrl(ch: _ChType, /) -> bytes: ... +def unget_wch(ch: int | str, /) -> None: ... +def ungetch(ch: _ChType, /) -> None: ... +def ungetmouse(id: int, x: int, y: int, z: int, bstate: int, /) -> None: ... def update_lines_cols() -> None: ... def use_default_colors() -> None: ... -def use_env(__flag: bool) -> None: ... +def use_env(flag: bool, /) -> None: ... class error(Exception): ... -class _CursesWindow: +@final +class window: # undocumented encoding: str + @overload - def addch(self, ch: _chtype, attr: int = ...) -> None: ... + def addch(self, ch: _ChType, attr: int = ...) -> None: ... @overload - def addch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... + @overload def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... @overload def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload def addstr(self, str: str, attr: int = ...) -> None: ... @overload def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... - def attroff(self, __attr: int) -> None: ... - def attron(self, __attr: int) -> None: ... - def attrset(self, __attr: int) -> None: ... - def bkgd(self, __ch: _chtype, __attr: int = ...) -> None: ... - def bkgdset(self, __ch: _chtype, __attr: int = ...) -> None: ... + + def attroff(self, attr: int, /) -> None: ... + def attron(self, attr: int, /) -> None: ... + def attrset(self, attr: int, /) -> None: ... + def bkgd(self, ch: _ChType, attr: int = 0, /) -> None: ... + def bkgdset(self, ch: _ChType, attr: int = 0, /) -> None: ... def border( self, - ls: _chtype = ..., - rs: _chtype = ..., - ts: _chtype = ..., - bs: _chtype = ..., - tl: _chtype = ..., - tr: _chtype = ..., - bl: _chtype = ..., - br: _chtype = ..., + ls: _ChType = ..., + rs: _ChType = ..., + ts: _ChType = ..., + bs: _ChType = ..., + tl: _ChType = ..., + tr: _ChType = ..., + bl: _ChType = ..., + br: _ChType = ..., ) -> None: ... + @overload def box(self) -> None: ... @overload - def box(self, vertch: _chtype = ..., horch: _chtype = ...) -> None: ... + def box(self, vertch: _ChType = 0, horch: _ChType = 0) -> None: ... + @overload def chgat(self, attr: int) -> None: ... @overload @@ -421,39 +421,49 @@ class _CursesWindow: def chgat(self, y: int, x: int, attr: int) -> None: ... @overload def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... + def clear(self) -> None: ... - def clearok(self, yes: int) -> None: ... + def clearok(self, flag: bool, /) -> None: ... def clrtobot(self) -> None: ... def clrtoeol(self) -> None: ... def cursyncup(self) -> None: ... + @overload def delch(self) -> None: ... @overload def delch(self, y: int, x: int) -> None: ... + def deleteln(self) -> None: ... + @overload - def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + def derwin(self, begin_y: int, begin_x: int) -> window: ... @overload - def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - def echochar(self, __ch: _chtype, __attr: int = ...) -> None: ... - def enclose(self, __y: int, __x: int) -> bool: ... + def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + + def echochar(self, ch: _ChType, attr: int = 0, /) -> None: ... + def enclose(self, y: int, x: int, /) -> bool: ... def erase(self) -> None: ... def getbegyx(self) -> tuple[int, int]: ... def getbkgd(self) -> tuple[int, int]: ... + @overload def getch(self) -> int: ... @overload def getch(self, y: int, x: int) -> int: ... + @overload def get_wch(self) -> int | str: ... @overload def get_wch(self, y: int, x: int) -> int | str: ... + @overload def getkey(self) -> str: ... @overload def getkey(self, y: int, x: int) -> str: ... + def getmaxyx(self) -> tuple[int, int]: ... def getparyx(self) -> tuple[int, int]: ... + @overload def getstr(self) -> bytes: ... @overload @@ -462,98 +472,112 @@ class _CursesWindow: def getstr(self, y: int, x: int) -> bytes: ... @overload def getstr(self, y: int, x: int, n: int) -> bytes: ... + def getyx(self) -> tuple[int, int]: ... + @overload - def hline(self, ch: _chtype, n: int) -> None: ... + def hline(self, ch: _ChType, n: int) -> None: ... @overload - def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... - def idcok(self, flag: bool) -> None: ... - def idlok(self, yes: bool) -> None: ... - def immedok(self, flag: bool) -> None: ... + def hline(self, y: int, x: int, ch: _ChType, n: int) -> None: ... + + def idcok(self, flag: bool, /) -> None: ... + def idlok(self, flag: bool, /) -> None: ... + def immedok(self, flag: bool, /) -> None: ... + @overload def inch(self) -> int: ... @overload def inch(self, y: int, x: int) -> int: ... + @overload - def insch(self, ch: _chtype, attr: int = ...) -> None: ... + def insch(self, ch: _ChType, attr: int = ...) -> None: ... @overload - def insch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... - def insdelln(self, nlines: int) -> None: ... + def insch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... + + def insdelln(self, nlines: int, /) -> None: ... def insertln(self) -> None: ... + @overload def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... @overload def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload def insstr(self, str: str, attr: int = ...) -> None: ... @overload def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + @overload - def instr(self, n: int = ...) -> bytes: ... + def instr(self, n: int = 2047) -> bytes: ... @overload - def instr(self, y: int, x: int, n: int = ...) -> bytes: ... - def is_linetouched(self, __line: int) -> bool: ... + def instr(self, y: int, x: int, n: int = 2047) -> bytes: ... + + def is_linetouched(self, line: int, /) -> bool: ... def is_wintouched(self) -> bool: ... - def keypad(self, yes: bool) -> None: ... - def leaveok(self, yes: bool) -> None: ... - def move(self, new_y: int, new_x: int) -> None: ... - def mvderwin(self, y: int, x: int) -> None: ... - def mvwin(self, new_y: int, new_x: int) -> None: ... - def nodelay(self, yes: bool) -> None: ... - def notimeout(self, yes: bool) -> None: ... + def keypad(self, flag: bool, /) -> None: ... + def leaveok(self, flag: bool, /) -> None: ... + def move(self, new_y: int, new_x: int, /) -> None: ... + def mvderwin(self, y: int, x: int, /) -> None: ... + def mvwin(self, new_y: int, new_x: int, /) -> None: ... + def nodelay(self, flag: bool, /) -> None: ... + def notimeout(self, flag: bool, /) -> None: ... + @overload def noutrefresh(self) -> None: ... @overload def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + @overload - def overlay(self, destwin: _CursesWindow) -> None: ... + def overlay(self, destwin: window) -> None: ... @overload def overlay( - self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int ) -> None: ... + @overload - def overwrite(self, destwin: _CursesWindow) -> None: ... + def overwrite(self, destwin: window) -> None: ... @overload def overwrite( - self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int ) -> None: ... - def putwin(self, __file: IO[Any]) -> None: ... - def redrawln(self, __beg: int, __num: int) -> None: ... + + def putwin(self, file: SupportsWrite[bytes], /) -> None: ... + def redrawln(self, beg: int, num: int, /) -> None: ... def redrawwin(self) -> None: ... + @overload def refresh(self) -> None: ... @overload def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... - def resize(self, nlines: int, ncols: int) -> None: ... - def scroll(self, lines: int = ...) -> None: ... - def scrollok(self, flag: bool) -> None: ... - def setscrreg(self, __top: int, __bottom: int) -> None: ... + + def resize(self, nlines: int, ncols: int, /) -> None: ... + def scroll(self, lines: int = 1) -> None: ... + def scrollok(self, flag: bool, /) -> None: ... + def setscrreg(self, top: int, bottom: int, /) -> None: ... def standend(self) -> None: ... def standout(self) -> None: ... + @overload - def subpad(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + def subpad(self, begin_y: int, begin_x: int) -> window: ... @overload - def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + @overload - def subwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + def subwin(self, begin_y: int, begin_x: int) -> window: ... @overload - def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + def syncdown(self) -> None: ... - def syncok(self, flag: bool) -> None: ... + def syncok(self, flag: bool, /) -> None: ... def syncup(self) -> None: ... - def timeout(self, delay: int) -> None: ... - def touchline(self, start: int, count: int, changed: bool = ...) -> None: ... + def timeout(self, delay: int, /) -> None: ... + def touchline(self, start: int, count: int, changed: bool = True) -> None: ... def touchwin(self) -> None: ... def untouchwin(self) -> None: ... + @overload - def vline(self, ch: _chtype, n: int) -> None: ... + def vline(self, ch: _ChType, n: int) -> None: ... @overload - def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... + def vline(self, y: int, x: int, ch: _ChType, n: int) -> None: ... -if sys.version_info >= (3, 8): - class _ncurses_version(NamedTuple): - major: int - minor: int - patch: int - ncurses_version: _ncurses_version - window = _CursesWindow # undocumented +ncurses_version: _ncurses_version diff --git a/stdlib/_curses_panel.pyi b/stdlib/_curses_panel.pyi new file mode 100644 index 000000000000..64205618bf41 --- /dev/null +++ b/stdlib/_curses_panel.pyi @@ -0,0 +1,27 @@ +from _curses import window as _window +from typing import Final, final + +__version__: Final[str] +version: Final[str] + +class error(Exception): ... + +@final +class panel: + def above(self) -> panel: ... + def below(self) -> panel: ... + def bottom(self) -> None: ... + def hidden(self) -> bool: ... + def hide(self) -> None: ... + def move(self, y: int, x: int, /) -> None: ... + def replace(self, win: _window, /) -> None: ... + def set_userptr(self, obj: object, /) -> None: ... + def show(self) -> None: ... + def top(self) -> None: ... + def userptr(self) -> object: ... + def window(self) -> _window: ... + +def bottom_panel() -> panel: ... +def new_panel(win: _window, /) -> panel: ... +def top_panel() -> panel: ... +def update_panels() -> panel: ... diff --git a/stdlib/_dbm.pyi b/stdlib/_dbm.pyi new file mode 100644 index 000000000000..29d9b4c2fadc --- /dev/null +++ b/stdlib/_dbm.pyi @@ -0,0 +1,46 @@ +import sys +from _typeshed import ReadOnlyBuffer, StrOrBytesPath +from types import TracebackType +from typing import Final, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self + +if sys.platform != "win32": + _T = TypeVar("_T") + _KeyType: TypeAlias = str | ReadOnlyBuffer + _ValueType: TypeAlias = str | ReadOnlyBuffer + + class error(OSError): ... + library: Final[str] + + # Actual typename dbm, not exposed by the implementation + @final + @type_check_only + class _dbm: + def close(self) -> None: ... + if sys.version_info >= (3, 13): + def clear(self) -> None: ... + + def __getitem__(self, item: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __len__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + + @overload + def get(self, k: _KeyType, /) -> bytes | None: ... + @overload + def get(self, k: _KeyType, default: _T, /) -> bytes | _T: ... + + def keys(self) -> list[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = b"", /) -> bytes: ... + # This isn't true, but the class can't be instantiated. See #13024 + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + if sys.version_info >= (3, 11): + def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _dbm: ... + else: + def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _dbm: ... diff --git a/stdlib/_decimal.pyi b/stdlib/_decimal.pyi index e58805855b13..75d5be277f95 100644 --- a/stdlib/_decimal.pyi +++ b/stdlib/_decimal.pyi @@ -1 +1,73 @@ -from decimal import * +import sys +from decimal import ( + Clamped as Clamped, + Context as Context, + ConversionSyntax as ConversionSyntax, + Decimal as Decimal, + DecimalException as DecimalException, + DecimalTuple as DecimalTuple, + DivisionByZero as DivisionByZero, + DivisionImpossible as DivisionImpossible, + DivisionUndefined as DivisionUndefined, + FloatOperation as FloatOperation, + Inexact as Inexact, + InvalidContext as InvalidContext, + InvalidOperation as InvalidOperation, + Overflow as Overflow, + Rounded as Rounded, + Subnormal as Subnormal, + Underflow as Underflow, + _ContextManager, +) +from typing import Final, TypeAlias + +_TrapType: TypeAlias = type[DecimalException] + +__version__: Final[str] +__libmpdec_version__: Final[str] +if sys.version_info >= (3, 15): + SPEC_VERSION: Final[str] + +ROUND_DOWN: Final = "ROUND_DOWN" +ROUND_HALF_UP: Final = "ROUND_HALF_UP" +ROUND_HALF_EVEN: Final = "ROUND_HALF_EVEN" +ROUND_CEILING: Final = "ROUND_CEILING" +ROUND_FLOOR: Final = "ROUND_FLOOR" +ROUND_UP: Final = "ROUND_UP" +ROUND_HALF_DOWN: Final = "ROUND_HALF_DOWN" +ROUND_05UP: Final = "ROUND_05UP" +HAVE_CONTEXTVAR: Final[bool] +HAVE_THREADS: Final[bool] +MAX_EMAX: Final[int] +MAX_PREC: Final[int] +MIN_EMIN: Final[int] +MIN_ETINY: Final[int] +if sys.version_info >= (3, 14): + IEEE_CONTEXT_MAX_BITS: Final[int] + +def setcontext(context: Context, /) -> None: ... +def getcontext() -> Context: ... + +if sys.version_info >= (3, 11): + def localcontext( + ctx: Context | None = None, + *, + prec: int | None = None, + rounding: str | None = None, + Emin: int | None = None, + Emax: int | None = None, + capitals: int | None = None, + clamp: int | None = None, + traps: dict[_TrapType, bool] | None = None, + flags: dict[_TrapType, bool] | None = None, + ) -> _ContextManager: ... + +else: + def localcontext(ctx: Context | None = None) -> _ContextManager: ... + +if sys.version_info >= (3, 14): + def IEEEContext(bits: int, /) -> Context: ... + +DefaultContext: Context +BasicContext: Context +ExtendedContext: Context diff --git a/stdlib/_dummy_thread.pyi b/stdlib/_dummy_thread.pyi deleted file mode 100644 index 886d9d739780..000000000000 --- a/stdlib/_dummy_thread.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any, Callable, NoReturn, Tuple - -TIMEOUT_MAX: int -error = RuntimeError - -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: dict[str, Any] = ...) -> None: ... -def exit() -> NoReturn: ... -def get_ident() -> int: ... -def allocate_lock() -> LockType: ... -def stack_size(size: int | None = ...) -> int: ... - -class LockType(object): - locked_status: bool - def __init__(self) -> None: ... - def acquire(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... - def __enter__(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... - def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... - def release(self) -> bool: ... - def locked(self) -> bool: ... - -def interrupt_main() -> None: ... diff --git a/stdlib/_dummy_threading.pyi b/stdlib/_dummy_threading.pyi deleted file mode 100644 index 64998d86bf9f..000000000000 --- a/stdlib/_dummy_threading.pyi +++ /dev/null @@ -1,147 +0,0 @@ -import sys -from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar - -# TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] - -_PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") - -__all__: list[str] - -def active_count() -> int: ... -def current_thread() -> Thread: ... -def currentThread() -> Thread: ... -def get_ident() -> int: ... -def enumerate() -> list[Thread]: ... -def main_thread() -> Thread: ... - -if sys.version_info >= (3, 8): - from _thread import get_native_id as get_native_id - -def settrace(func: _TF) -> None: ... -def setprofile(func: _PF | None) -> None: ... -def stack_size(size: int = ...) -> int: ... - -TIMEOUT_MAX: float - -class ThreadError(Exception): ... - -class local(object): - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... - -class Thread: - name: str - ident: int | None - daemon: bool - def __init__( - self, - group: None = ..., - target: Callable[..., Any] | None = ..., - name: str | None = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] | None = ..., - *, - daemon: bool | None = ..., - ) -> None: ... - def start(self) -> None: ... - def run(self) -> None: ... - def join(self, timeout: float | None = ...) -> None: ... - def getName(self) -> str: ... - def setName(self, name: str) -> None: ... - if sys.version_info >= (3, 8): - @property - def native_id(self) -> int | None: ... # only available on some platforms - def is_alive(self) -> bool: ... - if sys.version_info < (3, 9): - def isAlive(self) -> bool: ... - def isDaemon(self) -> bool: ... - def setDaemon(self, daemonic: bool) -> None: ... - -class _DummyThread(Thread): ... - -class Lock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - def release(self) -> None: ... - def locked(self) -> bool: ... - -class _RLock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - def release(self) -> None: ... - -RLock = _RLock - -class Condition: - def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - def release(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - def wait_for(self, predicate: Callable[[], _T], timeout: float | None = ...) -> _T: ... - def notify(self, n: int = ...) -> None: ... - def notify_all(self) -> None: ... - def notifyAll(self) -> None: ... - -class Semaphore: - def __init__(self, value: int = ...) -> None: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... - def __enter__(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... - if sys.version_info >= (3, 9): - def release(self, n: int = ...) -> None: ... - else: - def release(self) -> None: ... - -class BoundedSemaphore(Semaphore): ... - -class Event: - def __init__(self) -> None: ... - def is_set(self) -> bool: ... - def set(self) -> None: ... - def clear(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - -if sys.version_info >= (3, 8): - from _thread import _excepthook, _ExceptHookArgs - - excepthook = _excepthook - ExceptHookArgs = _ExceptHookArgs - -class Timer(Thread): - def __init__( - self, - interval: float, - function: Callable[..., Any], - args: Iterable[Any] | None = ..., - kwargs: Mapping[str, Any] | None = ..., - ) -> None: ... - def cancel(self) -> None: ... - -class Barrier: - parties: int - n_waiting: int - broken: bool - def __init__(self, parties: int, action: Callable[[], None] | None = ..., timeout: float | None = ...) -> None: ... - def wait(self, timeout: float | None = ...) -> int: ... - def reset(self) -> None: ... - def abort(self) -> None: ... - -class BrokenBarrierError(RuntimeError): ... diff --git a/stdlib/_frozen_importlib.pyi b/stdlib/_frozen_importlib.pyi new file mode 100644 index 000000000000..7bb8d40a932a --- /dev/null +++ b/stdlib/_frozen_importlib.pyi @@ -0,0 +1,121 @@ +import importlib.abc +import importlib.machinery +import sys +import types +from _typeshed.importlib import LoaderProtocol +from collections.abc import Mapping, Sequence +from types import ModuleType +from typing import Any, ClassVar +from typing_extensions import deprecated + +# Signature of `builtins.__import__` should be kept identical to `importlib.__import__` +def __import__( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, +) -> ModuleType: ... + +# TODO: Revise the protocol for 'loader' param +def spec_from_loader( + name: str, loader: LoaderProtocol | None, *, origin: str | None = None, is_package: bool | None = None +) -> importlib.machinery.ModuleSpec | None: ... +def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ... +def _init_module_attrs( + spec: importlib.machinery.ModuleSpec, module: types.ModuleType, *, override: bool = False +) -> types.ModuleType: ... + +class ModuleSpec: + def __init__( + self, + name: str, + loader: importlib.abc.Loader | None, + *, + origin: str | None = None, + loader_state: Any = None, + is_package: bool | None = None, + ) -> None: ... + name: str + loader: importlib.abc.Loader | None + origin: str | None + submodule_search_locations: list[str] | None + loader_state: Any + cached: str | None + @property + def parent(self) -> str | None: ... + has_location: bool + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): + # MetaPathFinder + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + if sys.version_info < (3, 15): + @classmethod + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(cls, fullname: str) -> types.ModuleType: ... + # Loader + if sys.version_info < (3, 12): + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... + +class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): + # MetaPathFinder + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + if sys.version_info < (3, 15): + @classmethod + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(cls, fullname: str) -> types.ModuleType: ... + # Loader + if sys.version_info < (3, 12): + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(m: types.ModuleType) -> str: ... + + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... diff --git a/stdlib/_frozen_importlib_external.pyi b/stdlib/_frozen_importlib_external.pyi new file mode 100644 index 000000000000..cbe7439641b7 --- /dev/null +++ b/stdlib/_frozen_importlib_external.pyi @@ -0,0 +1,218 @@ +import _ast +import importlib.abc +import importlib.machinery +import importlib.readers +import sys +import types +from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath +from _typeshed.importlib import LoaderProtocol +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence, Sequence +from importlib.machinery import ModuleSpec +from importlib.metadata import DistributionFinder, PathDistribution +from typing import Any, Final, Literal, overload +from typing_extensions import deprecated + +if sys.platform == "win32": + path_separators: Literal["\\/"] + path_sep: Literal["\\"] + path_sep_tuple: tuple[Literal["\\"], Literal["/"]] +else: + path_separators: Literal["/"] + path_sep: Literal["/"] + path_sep_tuple: tuple[Literal["/"]] + +MAGIC_NUMBER: Final[bytes] + +if sys.version_info >= (3, 15): + def cache_from_source(path: StrPath, *, optimization: Any | None = None) -> str: ... + +else: + @overload + @deprecated( + "The `debug_override` parameter is deprecated since Python 3.5; removed in Python 3.15. Use `optimization` instead." + ) + def cache_from_source(path: StrPath, debug_override: bool, *, optimization: None = None) -> str: ... + @overload + def cache_from_source(path: StrPath, debug_override: None = None, *, optimization: Any | None = None) -> str: ... + +def source_from_cache(path: StrPath) -> str: ... +def decode_source(source_bytes: ReadableBuffer) -> str: ... +def spec_from_file_location( + name: str, + location: StrOrBytesPath | None = None, + *, + loader: LoaderProtocol | None = None, + submodule_search_locations: list[str] | None = ..., +) -> importlib.machinery.ModuleSpec | None: ... + +@deprecated( + "Deprecated since Python 3.6. Use site configuration instead. " + "Future versions of Python may not enable this finder by default." +) +class WindowsRegistryFinder(importlib.abc.MetaPathFinder): + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + +class PathFinder(importlib.abc.MetaPathFinder): + @staticmethod + def invalidate_caches() -> None: ... + @staticmethod + def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + if sys.version_info >= (3, 15): + @classmethod + def discover(cls, parent: ModuleSpec | None = None) -> Iterator[ModuleSpec]: ... + +SOURCE_SUFFIXES: Final[list[str]] +DEBUG_BYTECODE_SUFFIXES: Final = [".pyc"] +OPTIMIZED_BYTECODE_SUFFIXES: Final = [".pyc"] +BYTECODE_SUFFIXES: Final = [".pyc"] +EXTENSION_SUFFIXES: Final[list[str]] + +class FileFinder(importlib.abc.PathEntryFinder): + path: str + def __init__(self, path: str, *loader_details: tuple[type[importlib.abc.Loader], list[str]]) -> None: ... + @classmethod + def path_hook( + cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]] + ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... + + if sys.version_info >= (3, 15): + def discover(self, parent: ModuleSpec | None = None) -> Iterator[ModuleSpec]: ... + +class _LoaderBasics: + def is_package(self, fullname: str) -> bool: ... + def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + +class SourceLoader(_LoaderBasics): + def path_mtime(self, path: str) -> float: ... + def set_data(self, path: str, data: bytes) -> None: ... + def get_source(self, fullname: str) -> str | None: ... + def path_stats(self, path: str) -> Mapping[str, Any]: ... + if sys.version_info >= (3, 15): + def source_to_code( + self, + data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, + path: bytes | StrPath, + fullname: str | None = None, + *, + _optimize: int = -1, + ) -> types.CodeType: ... + else: + def source_to_code( + self, + data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, + path: bytes | StrPath, + *, + _optimize: int = -1, + ) -> types.CodeType: ... + + def get_code(self, fullname: str) -> types.CodeType | None: ... + +class FileLoader: + name: str + path: str + def __init__(self, fullname: str, path: str) -> None: ... + def get_data(self, path: str) -> bytes: ... + def get_filename(self, fullname: str | None = None) -> str: ... + def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str | None = None) -> types.ModuleType: ... + +class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.SourceLoader, SourceLoader): # type: ignore[misc] # incompatible method arguments in base classes + def set_data(self, path: str, data: ReadableBuffer, *, _mode: int = 0o666) -> None: ... + def path_stats(self, path: str) -> Mapping[str, Any]: ... + +class SourcelessFileLoader(importlib.abc.FileLoader, FileLoader, _LoaderBasics): + def get_code(self, fullname: str) -> types.CodeType | None: ... + def get_source(self, fullname: str) -> None: ... + +class ExtensionFileLoader(FileLoader, _LoaderBasics, importlib.abc.ExecutionLoader): + def __init__(self, name: str, path: str) -> None: ... + def get_filename(self, fullname: str | None = None) -> str: ... + def get_source(self, fullname: str) -> None: ... + def create_module(self, spec: ModuleSpec) -> types.ModuleType: ... + def exec_module(self, module: types.ModuleType) -> None: ... + def get_code(self, fullname: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 15): + class NamespacePath: + def __init__( + self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec | None] + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __getitem__(self, index: int) -> str: ... + def __setitem__(self, index: int, path: str) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, item: str) -> bool: ... + def append(self, item: str) -> None: ... + + _NamespacePath = NamespacePath + +if sys.version_info >= (3, 11): + class NamespaceLoader(importlib.abc.InspectLoader): + def __init__( + self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec | None] + ) -> None: ... + def is_package(self, fullname: str) -> Literal[True]: ... + def get_source(self, fullname: str) -> Literal[""]: ... + def get_code(self, fullname: str) -> types.CodeType: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + if sys.version_info < (3, 12): + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + + _NamespaceLoader = NamespaceLoader +else: + class _NamespaceLoader: + def __init__( + self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec | None] + ) -> None: ... + def is_package(self, fullname: str) -> Literal[True]: ... + def get_source(self, fullname: str) -> Literal[""]: ... + def get_code(self, fullname: str) -> types.CodeType: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ... + +if sys.version_info >= (3, 13): + class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): ... diff --git a/stdlib/_gdbm.pyi b/stdlib/_gdbm.pyi new file mode 100644 index 000000000000..b7a01a453120 --- /dev/null +++ b/stdlib/_gdbm.pyi @@ -0,0 +1,50 @@ +import sys +from _typeshed import ReadOnlyBuffer, StrOrBytesPath +from types import TracebackType +from typing import TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +if sys.platform != "win32": + _T = TypeVar("_T") + _KeyType: TypeAlias = str | ReadOnlyBuffer + _ValueType: TypeAlias = str | ReadOnlyBuffer + + open_flags: str + + class error(OSError): ... + # Actual typename gdbm, not exposed by the implementation + @type_check_only + class _gdbm: + def firstkey(self) -> bytes | None: ... + def nextkey(self, key: _KeyType) -> bytes | None: ... + def reorganize(self) -> None: ... + def sync(self) -> None: ... + def close(self) -> None: ... + if sys.version_info >= (3, 13): + def clear(self) -> None: ... + + def __getitem__(self, item: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __contains__(self, key: _KeyType) -> bool: ... + def __len__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + + @overload + def get(self, k: _KeyType) -> bytes | None: ... + @overload + def get(self, k: _KeyType, default: _T) -> bytes | _T: ... + + def keys(self) -> list[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + if sys.version_info >= (3, 11): + def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ... + else: + def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ... diff --git a/stdlib/_hashlib.pyi b/stdlib/_hashlib.pyi new file mode 100644 index 000000000000..5b8050ebc8d4 --- /dev/null +++ b/stdlib/_hashlib.pyi @@ -0,0 +1,185 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Callable +from types import ModuleType +from typing import AnyStr, Literal, Protocol, TypeAlias, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None +_FixedDigestName: TypeAlias = Literal[ + "md5", + "MD5", + "sha1", + "SHA1", + "sha224", + "SHA224", + "sha256", + "SHA256", + "sha384", + "SHA384", + "sha512", + "SHA512", + "sha3_224", + "sha3-224", + "SHA3-224", + "sha3_256", + "sha3-256", + "SHA3-256", + "sha3_384", + "sha3-384", + "SHA3-384", + "sha3_512", + "sha3-512", + "SHA3-512", +] +_XofDigestName: TypeAlias = Literal[ + "shake_128", "shake128", "SHAKE128", "shake-128", "SHAKE-128", "shake_256", "shake256", "SHAKE256", "shake-256", "SHAKE-256" +] + +openssl_md_meth_names: frozenset[str] + +@type_check_only +class _HashObject(Protocol): + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, obj: ReadableBuffer, /) -> None: ... + +@type_check_only +class _HashObjectWithOptionalLength(Protocol): + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + # Depending on the algorithm, length is either required or not accepted. + def digest(self, length: int = ...) -> bytes: ... + def hexdigest(self, length: int = ...) -> str: ... + def update(self, obj: ReadableBuffer, /) -> None: ... + +@disjoint_base +class HASH(_HashObjectWithOptionalLength): + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... # type: ignore[override] + def hexdigest(self) -> str: ... # type: ignore[override] + def update(self, obj: ReadableBuffer, /) -> None: ... + +class UnsupportedDigestmodError(ValueError): ... + +class HASHXOF(HASH): + def digest(self, length: int) -> bytes: ... # type: ignore[override] + def hexdigest(self, length: int) -> str: ... # type: ignore[override] + +@final +class HMAC: + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, msg: ReadableBuffer) -> None: ... + +@overload +def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ... +@overload +def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... + +def get_fips_mode() -> int: ... +def hmac_new(key: ReadableBuffer, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: ... + +if sys.version_info >= (3, 13): + @overload + def new( + name: _XofDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASHXOF: ... + @overload + def new( + name: _FixedDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + @overload + def new( + name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> _HashObjectWithOptionalLength: ... + + def openssl_md5( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha1( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha224( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha256( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha384( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha512( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_224( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_256( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_384( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_512( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_shake_128( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASHXOF: ... + def openssl_shake_256( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASHXOF: ... +else: + @overload + def new(name: _XofDigestName, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... + @overload + def new(name: _FixedDigestName, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + @overload + def new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _HashObjectWithOptionalLength: ... + + def openssl_md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha1(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_shake_128(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... + def openssl_shake_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... + +def hmac_digest(key: ReadableBuffer, msg: ReadableBuffer, digest: str) -> bytes: ... +def pbkdf2_hmac( + hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None +) -> bytes: ... +def scrypt( + password: ReadableBuffer, *, salt: ReadableBuffer, n: int, r: int, p: int, maxmem: int = 0, dklen: int = 64 +) -> bytes: ... diff --git a/stdlib/_heapq.pyi b/stdlib/_heapq.pyi index 87e0fe0fa777..7664b826ae0b 100644 --- a/stdlib/_heapq.pyi +++ b/stdlib/_heapq.pyi @@ -1,9 +1,18 @@ -from typing import Any, TypeVar +import sys +from _typeshed import SupportsRichComparisonT as _T # All type variable use in this module requires comparability. +from typing import Final -_T = TypeVar("_T") +__about__: Final[str] -def heapify(__heap: list[Any]) -> None: ... -def heappop(__heap: list[_T]) -> _T: ... -def heappush(__heap: list[_T], __item: _T) -> None: ... -def heappushpop(__heap: list[_T], __item: _T) -> _T: ... -def heapreplace(__heap: list[_T], __item: _T) -> _T: ... +def heapify(heap: list[_T], /) -> None: ... # To work around the fact that list is invariant +def heappop(heap: list[_T], /) -> _T: ... +def heappush(heap: list[_T], item: _T, /) -> None: ... +def heappushpop(heap: list[_T], item: _T, /) -> _T: ... +def heapreplace(heap: list[_T], item: _T, /) -> _T: ... + +if sys.version_info >= (3, 14): + def heapify_max(heap: list[_T], /) -> None: ... + def heappop_max(heap: list[_T], /) -> _T: ... + def heappush_max(heap: list[_T], item: _T, /) -> None: ... + def heappushpop_max(heap: list[_T], item: _T, /) -> _T: ... + def heapreplace_max(heap: list[_T], item: _T, /) -> _T: ... diff --git a/stdlib/_imp.pyi b/stdlib/_imp.pyi index 23272591df4c..c12c26d08ba2 100644 --- a/stdlib/_imp.pyi +++ b/stdlib/_imp.pyi @@ -1,21 +1,30 @@ import sys import types +from _typeshed import ReadableBuffer from importlib.machinery import ModuleSpec from typing import Any -if sys.version_info >= (3, 7): - check_hash_based_pycs: str +check_hash_based_pycs: str +if sys.version_info >= (3, 14): + pyc_magic_number_token: int -def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... -def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> None: ... +def source_hash(key: int, source: ReadableBuffer) -> bytes: ... +def create_builtin(spec: ModuleSpec, /) -> types.ModuleType: ... +def create_dynamic(spec: ModuleSpec, file: Any = None, /) -> types.ModuleType: ... def acquire_lock() -> None: ... -def exec_builtin(__mod: types.ModuleType) -> int: ... -def exec_dynamic(__mod: types.ModuleType) -> int: ... +def exec_builtin(mod: types.ModuleType, /) -> int: ... +def exec_dynamic(mod: types.ModuleType, /) -> int: ... def extension_suffixes() -> list[str]: ... -def get_frozen_object(__name: str) -> types.CodeType: ... -def init_frozen(__name: str) -> types.ModuleType: ... -def is_builtin(__name: str) -> int: ... -def is_frozen(__name: str) -> bool: ... -def is_frozen_package(__name: str) -> bool: ... +def init_frozen(name: str, /) -> types.ModuleType: ... +def is_builtin(name: str, /) -> int: ... +def is_frozen(name: str, /) -> bool: ... +def is_frozen_package(name: str, /) -> bool: ... def lock_held() -> bool: ... def release_lock() -> None: ... + +if sys.version_info >= (3, 11): + def find_frozen(name: str, /, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: ... + def get_frozen_object(name: str, data: ReadableBuffer | None = None, /) -> types.CodeType: ... + +else: + def get_frozen_object(name: str, /) -> types.CodeType: ... diff --git a/stdlib/_interpchannels.pyi b/stdlib/_interpchannels.pyi new file mode 100644 index 000000000000..a631a6f16616 --- /dev/null +++ b/stdlib/_interpchannels.pyi @@ -0,0 +1,86 @@ +from _typeshed import structseq +from typing import Any, Final, Literal, SupportsIndex, final +from typing_extensions import Buffer, Self + +class ChannelError(RuntimeError): ... +class ChannelClosedError(ChannelError): ... +class ChannelEmptyError(ChannelError): ... +class ChannelNotEmptyError(ChannelError): ... +class ChannelNotFoundError(ChannelError): ... + +# Mark as final, since instantiating ChannelID is not supported. +@final +class ChannelID: + @property + def end(self) -> Literal["send", "recv", "both"]: ... + @property + def send(self) -> Self: ... + @property + def recv(self) -> Self: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: ChannelID, /) -> bool: ... + def __gt__(self, other: ChannelID, /) -> bool: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __le__(self, other: ChannelID, /) -> bool: ... + def __lt__(self, other: ChannelID, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + +@final +class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]): + __match_args__: Final = ( + "open", + "closing", + "closed", + "count", + "num_interp_send", + "num_interp_send_released", + "num_interp_recv", + "num_interp_recv_released", + ) + @property + def open(self) -> bool: ... + @property + def closing(self) -> bool: ... + @property + def closed(self) -> bool: ... + @property + def count(self) -> int: ... # type: ignore[override] + @property + def num_interp_send(self) -> int: ... + @property + def num_interp_send_released(self) -> int: ... + @property + def num_interp_recv(self) -> int: ... + @property + def num_interp_recv_released(self) -> int: ... + @property + def num_interp_both(self) -> int: ... + @property + def num_interp_both_recv_released(self) -> int: ... + @property + def num_interp_both_send_released(self) -> int: ... + @property + def num_interp_both_released(self) -> int: ... + @property + def recv_associated(self) -> bool: ... + @property + def recv_released(self) -> bool: ... + @property + def send_associated(self) -> bool: ... + @property + def send_released(self) -> bool: ... + +def create(unboundop: Literal[1, 2, 3]) -> ChannelID: ... +def destroy(cid: SupportsIndex) -> None: ... +def list_all() -> list[ChannelID]: ... +def list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: ... +def send(cid: SupportsIndex, obj: object, *, blocking: bool = True, timeout: float | None = None) -> None: ... +def send_buffer(cid: SupportsIndex, obj: Buffer, *, blocking: bool = True, timeout: float | None = None) -> None: ... +def recv(cid: SupportsIndex, default: object = ...) -> tuple[Any, Literal[1, 2, 3]]: ... +def close(cid: SupportsIndex, *, send: bool = False, recv: bool = False) -> None: ... +def get_count(cid: SupportsIndex) -> int: ... +def get_info(cid: SupportsIndex) -> ChannelInfo: ... +def get_channel_defaults(cid: SupportsIndex) -> Literal[1, 2, 3]: ... +def release(cid: SupportsIndex, *, send: bool = False, recv: bool = False, force: bool = False) -> None: ... diff --git a/stdlib/_interpqueues.pyi b/stdlib/_interpqueues.pyi new file mode 100644 index 000000000000..94605e4c0dda --- /dev/null +++ b/stdlib/_interpqueues.pyi @@ -0,0 +1,31 @@ +import sys +from typing import Any, Literal, SupportsIndex, TypeAlias + +_UnboundOp: TypeAlias = Literal[1, 2, 3] + +class QueueError(RuntimeError): ... +class QueueNotFoundError(QueueError): ... + +def bind(qid: SupportsIndex) -> None: ... + +if sys.version_info >= (3, 15): + def create(maxsize: SupportsIndex, unboundop: SupportsIndex = -1, fallback: SupportsIndex = -1) -> int: ... + +else: + def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: ... + +def destroy(qid: SupportsIndex) -> None: ... +def get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: ... +def get_count(qid: SupportsIndex) -> int: ... +def get_maxsize(qid: SupportsIndex) -> int: ... +def get_queue_defaults(qid: SupportsIndex) -> tuple[int, _UnboundOp]: ... +def is_full(qid: SupportsIndex) -> bool: ... +def list_all() -> list[tuple[int, int, _UnboundOp]]: ... + +if sys.version_info >= (3, 15): + def put(qid: SupportsIndex, obj: Any, unboundop: SupportsIndex = -1, fallback: SupportsIndex = -1) -> None: ... + +else: + def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: ... + +def release(qid: SupportsIndex) -> None: ... diff --git a/stdlib/_interpreters.pyi b/stdlib/_interpreters.pyi new file mode 100644 index 000000000000..d9a9a3a05227 --- /dev/null +++ b/stdlib/_interpreters.pyi @@ -0,0 +1,68 @@ +import sys +import types +from collections.abc import Callable +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import disjoint_base + +_R = TypeVar("_R") + +_Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""] +_SharedDict: TypeAlias = dict[str, Any] # many objects can be shared + +class InterpreterError(Exception): ... +class InterpreterNotFoundError(InterpreterError): ... + +if sys.version_info >= (3, 14): + class NotShareableError(TypeError): ... + +else: + class NotShareableError(ValueError): ... + +@disjoint_base +class CrossInterpreterBufferView: + def __buffer__(self, flags: int, /) -> memoryview: ... + +def new_config(name: _Configs = "isolated", /, **overides: object) -> types.SimpleNamespace: ... +def create(config: types.SimpleNamespace | _Configs | None = "isolated", *, reqrefs: bool = False) -> int: ... +def destroy(id: SupportsIndex, *, restrict: bool = False) -> None: ... +def list_all(*, require_ready: bool = False) -> list[tuple[int, _Whence]]: ... +def get_current() -> tuple[int, _Whence]: ... +def get_main() -> tuple[int, _Whence]: ... +def is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: ... +def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: ... +def whence(id: SupportsIndex) -> _Whence: ... +def exec( + id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False +) -> types.SimpleNamespace | None: ... +def call( + id: SupportsIndex, + callable: Callable[..., _R], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] = {}, + *, + preserve_exc: bool = False, + restrict: bool = False, +) -> tuple[_R, types.SimpleNamespace]: ... +def run_string( + id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False +) -> None: ... +def run_func( + id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False +) -> None: ... +def set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: bool = False) -> None: ... +def incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ... +def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ... +def is_shareable(obj: object) -> bool: ... + +@overload +def capture_exception(exc: BaseException) -> types.SimpleNamespace: ... +@overload +def capture_exception(exc: None = None) -> types.SimpleNamespace | None: ... + +_Whence: TypeAlias = Literal[0, 1, 2, 3, 4, 5] +WHENCE_UNKNOWN: Final = 0 +WHENCE_RUNTIME: Final = 1 +WHENCE_LEGACY_CAPI: Final = 2 +WHENCE_CAPI: Final = 3 +WHENCE_XI: Final = 4 +WHENCE_STDLIB: Final = 5 diff --git a/stdlib/_io.pyi b/stdlib/_io.pyi new file mode 100644 index 000000000000..5e216123be98 --- /dev/null +++ b/stdlib/_io.pyi @@ -0,0 +1,330 @@ +import builtins +import codecs +import sys +from _typeshed import FileDescriptorOrPath, MaybeNone, ReadableBuffer, WriteableBuffer +from collections.abc import Callable, Iterable, Iterator +from io import BufferedIOBase, RawIOBase, TextIOBase, UnsupportedOperation as UnsupportedOperation +from os import _Opener +from types import TracebackType +from typing import IO, Any, BinaryIO, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_S = TypeVar("_S", bound=str) + +if sys.version_info >= (3, 14): + DEFAULT_BUFFER_SIZE: Final = 131072 +else: + DEFAULT_BUFFER_SIZE: Final = 8192 + +open = builtins.open + +def open_code(path: str) -> IO[bytes]: ... + +BlockingIOError = builtins.BlockingIOError + +if sys.version_info >= (3, 12): + @disjoint_base + class _IOBase: + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + read: Callable[..., Any] + def readlines(self, hint: int = -1, /) -> list[bytes]: ... + def seek(self, offset: int, whence: int = 0, /) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: int | None = None, /) -> int: ... + def writable(self) -> bool: ... + write: Callable[..., Any] + def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... + def readline(self, size: int | None = -1, /) -> bytes: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... # undocumented + +else: + class _IOBase: + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + read: Callable[..., Any] + def readlines(self, hint: int = -1, /) -> list[bytes]: ... + def seek(self, offset: int, whence: int = 0, /) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: int | None = None, /) -> int: ... + def writable(self) -> bool: ... + write: Callable[..., Any] + def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... + def readline(self, size: int | None = -1, /) -> bytes: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... # undocumented + +class _RawIOBase(_IOBase): + def readall(self) -> bytes: ... + # The following methods can return None if the file is in non-blocking mode + # and no data is available. + def readinto(self, buffer: WriteableBuffer, /) -> int | MaybeNone: ... + def write(self, b: ReadableBuffer, /) -> int | MaybeNone: ... + def read(self, size: int = -1, /) -> bytes | MaybeNone: ... + +class _BufferedIOBase(_IOBase): + def detach(self) -> RawIOBase: ... + def readinto(self, buffer: WriteableBuffer, /) -> int: ... + def write(self, buffer: ReadableBuffer, /) -> int: ... + def readinto1(self, buffer: WriteableBuffer, /) -> int: ... + def read(self, size: int | None = -1, /) -> bytes: ... + def read1(self, size: int = -1, /) -> bytes: ... + +@disjoint_base +class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes + mode: str + # The type of "name" equals the argument passed in to the constructor, + # but that can make FileIO incompatible with other I/O types that assume + # "name" is a str. In the future, making FileIO generic might help. + name: Any + def __init__( + self, file: FileDescriptorOrPath, mode: str = "r", closefd: bool = True, opener: _Opener | None = None + ) -> None: ... + @property + def closefd(self) -> bool: ... + def seek(self, pos: int, whence: int = 0, /) -> int: ... + def read(self, size: int | None = -1, /) -> bytes | MaybeNone: ... + +@disjoint_base +class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes + def __init__(self, initial_bytes: ReadableBuffer = b"") -> None: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> bytes: ... + def getbuffer(self) -> memoryview: ... + def read1(self, size: int | None = -1, /) -> bytes: ... + def readlines(self, size: int | None = None, /) -> list[bytes]: ... + def seek(self, pos: int, whence: int = 0, /) -> int: ... + +@type_check_only +class _BufferedReaderStream(Protocol): + def read(self, n: int = ..., /) -> bytes: ... + # Optional: def readall(self) -> bytes: ... + def readinto(self, b: memoryview, /) -> int | None: ... + def seek(self, pos: int, whence: int, /) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: int, /) -> int: ... + def flush(self) -> object: ... + def close(self) -> object: ... + @property + def closed(self) -> bool: ... + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + + # The following methods just pass through to the underlying stream. Since + # not all streams support them, they are marked as optional here, and will + # raise an AttributeError if called on a stream that does not support them. + + # @property + # def name(self) -> Any: ... # Type is inconsistent between the various I/O types. + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + # def isatty(self) -> bool: ... + +_BufferedReaderStreamT = TypeVar("_BufferedReaderStreamT", bound=_BufferedReaderStream, default=_BufferedReaderStream) + +@disjoint_base +class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedReaderStreamT]): # type: ignore[misc] # incompatible definitions of methods in the base classes + raw: _BufferedReaderStreamT + if sys.version_info >= (3, 14): + def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 131072) -> None: ... + else: + def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ... + + def peek(self, size: int = 0, /) -> bytes: ... + def seek(self, target: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@type_check_only +class _BufferedWriterStream(Protocol): + def write(self, b: WriteableBuffer, /) -> int | None: ... + def seek(self, pos: int, whence: int, /) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: int, /) -> int: ... + def flush(self) -> object: ... + def close(self) -> object: ... + @property + def closed(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + + # The following methods just pass through to the underlying stream. Since + # not all streams support them, they are marked as optional here, and will + # raise an AttributeError if called on a stream that does not support them. + + # @property + # def name(self) -> Any: ... # Type is inconsistent between the various I/O types. + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + # def isatty(self) -> bool: ... + +_BufferedWriterStreamT = TypeVar("_BufferedWriterStreamT", bound=_BufferedWriterStream, default=_BufferedWriterStream) + +@disjoint_base +class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedWriterStreamT]): # type: ignore[misc] # incompatible definitions of writelines in the base classes + raw: _BufferedWriterStreamT + if sys.version_info >= (3, 14): + def __init__(self, raw: _BufferedWriterStreamT, buffer_size: int = 131072) -> None: ... + else: + def __init__(self, raw: _BufferedWriterStreamT, buffer_size: int = 8192) -> None: ... + + def write(self, buffer: ReadableBuffer, /) -> int: ... + def seek(self, target: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes + mode: str + name: Any + raw: RawIOBase + if sys.version_info >= (3, 14): + def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ... + else: + def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... + + def seek(self, target: int, whence: int = 0, /) -> int: ... # stubtest needs this + def peek(self, size: int = 0, /) -> bytes: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT, _BufferedWriterStreamT]): + if sys.version_info >= (3, 14): + def __init__( + self, reader: _BufferedReaderStreamT, writer: _BufferedWriterStreamT, buffer_size: int = 131072, / + ) -> None: ... + else: + def __init__( + self, reader: _BufferedReaderStreamT, writer: _BufferedWriterStreamT, buffer_size: int = 8192, / + ) -> None: ... + + def peek(self, size: int = 0, /) -> bytes: ... + +class _TextIOBase(_IOBase): + encoding: str + errors: str | None + newlines: str | tuple[str, ...] | None + def __iter__(self) -> Iterator[str]: ... # type: ignore[override] + def __next__(self) -> str: ... # type: ignore[override] + def detach(self) -> BinaryIO: ... + def write(self, s: str, /) -> int: ... + def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override] + def readline(self, size: int = -1, /) -> str: ... # type: ignore[override] + def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override] + def read(self, size: int | None = -1, /) -> str: ... + +@type_check_only +class _WrappedBuffer(Protocol): + # "name" is wrapped by TextIOWrapper. Its type is inconsistent between + # the various I/O types. + @property + def name(self) -> Any: ... + @property + def closed(self) -> bool: ... + def read(self, size: int = ..., /) -> ReadableBuffer: ... + # Optional: def read1(self, size: int, /) -> ReadableBuffer: ... + def write(self, b: bytes, /) -> object: ... + def flush(self) -> object: ... + def close(self) -> object: ... + def seekable(self) -> bool: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def truncate(self, size: int, /) -> int: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + # Optional: Only needs to be present if seekable() returns True. + # def seek(self, offset: Literal[0], whence: Literal[2]) -> int: ... + # def tell(self) -> int: ... + +_BufferT_co = TypeVar("_BufferT_co", bound=_WrappedBuffer, default=_WrappedBuffer, covariant=True) + +@disjoint_base +class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # type: ignore[misc] # incompatible definitions of write in the base classes + def __init__( + self, + buffer: _BufferT_co, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> None: ... + # Equals the "buffer" argument passed in to the constructor. + @property + def buffer(self) -> _BufferT_co: ... # type: ignore[override] + @property + def line_buffering(self) -> bool: ... + @property + def write_through(self) -> bool: ... + def reconfigure( + self, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool | None = None, + write_through: bool | None = None, + ) -> None: ... + def readline(self, size: int = -1, /) -> str: ... # type: ignore[override] + # Equals the "buffer" argument passed in to the constructor. + def detach(self) -> _BufferT_co: ... # type: ignore[override] + # TextIOWrapper's version of seek only supports a limited subset of + # operations. + def seek(self, cookie: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes + def __init__(self, initial_value: str | None = "", newline: str | None = "\n") -> None: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> str: ... + @property + def line_buffering(self) -> bool: ... + def seek(self, pos: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class IncrementalNewlineDecoder: + def __init__(self, decoder: codecs.IncrementalDecoder | None, translate: bool, errors: str = "strict") -> None: ... + def decode(self, input: ReadableBuffer | str, final: bool = False) -> str: ... + @property + def newlines(self) -> str | tuple[str, ...] | None: ... + def getstate(self) -> tuple[bytes, int]: ... + def reset(self) -> None: ... + def setstate(self, state: tuple[bytes, int], /) -> None: ... + +@overload +def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: ... +@overload +def text_encoding(encoding: _S, stacklevel: int = 2, /) -> _S: ... diff --git a/stdlib/_json.pyi b/stdlib/_json.pyi index 7395288afdbc..c6c2c97e83aa 100644 --- a/stdlib/_json.pyi +++ b/stdlib/_json.pyi @@ -1,29 +1,44 @@ -from typing import Any, Callable +import sys +from collections.abc import Callable +from typing import Any, final +from typing_extensions import Self +@final class make_encoder: - sort_keys: Any - skipkeys: Any - key_separator: Any - indent: Any - markers: Any - default: Any - encoder: Any - item_separator: Any - def __init__( - self, + @property + def sort_keys(self) -> bool: ... + @property + def skipkeys(self) -> bool: ... + @property + def key_separator(self) -> str: ... + @property + def indent(self) -> str | None: ... + @property + def markers(self) -> dict[int, Any] | None: ... + @property + def default(self) -> Callable[[Any], Any]: ... + @property + def encoder(self) -> Callable[[str], str]: ... + @property + def item_separator(self) -> str: ... + def __new__( + cls, markers: dict[int, Any] | None, default: Callable[[Any], Any], encoder: Callable[[str], str], - indent: int | None, + indent: str | None, key_separator: str, item_separator: str, sort_keys: bool, skipkeys: bool, allow_nan: bool, - ) -> None: ... + ) -> Self: ... def __call__(self, obj: object, _current_indent_level: int) -> Any: ... +@final class make_scanner: + if sys.version_info >= (3, 15): + array_hook: Any object_hook: Any object_pairs_hook: Any parse_int: Any @@ -31,8 +46,14 @@ class make_scanner: parse_float: Any strict: bool # TODO: 'context' needs the attrs above (ducktype), but not __call__. - def __init__(self, context: make_scanner) -> None: ... + def __new__(cls, context: make_scanner) -> Self: ... def __call__(self, string: str, index: int) -> tuple[Any, int]: ... -def encode_basestring_ascii(s: str) -> str: ... -def scanstring(string: str, end: int, strict: bool = ...) -> tuple[str, int]: ... +def encode_basestring(s: str, /) -> str: ... +def encode_basestring_ascii(s: str, /) -> str: ... + +if sys.version_info >= (3, 15): + def scanstring(pystr: str, end: int, strict: bool = True, /) -> tuple[str, int]: ... + +else: + def scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]: ... diff --git a/stdlib/_locale.pyi b/stdlib/_locale.pyi new file mode 100644 index 000000000000..ccce7a0d9d70 --- /dev/null +++ b/stdlib/_locale.pyi @@ -0,0 +1,121 @@ +import sys +from _typeshed import StrPath +from typing import Final, Literal, TypedDict, type_check_only + +@type_check_only +class _LocaleConv(TypedDict): + decimal_point: str + grouping: list[int] + thousands_sep: str + int_curr_symbol: str + currency_symbol: str + p_cs_precedes: Literal[0, 1, 127] + n_cs_precedes: Literal[0, 1, 127] + p_sep_by_space: Literal[0, 1, 127] + n_sep_by_space: Literal[0, 1, 127] + mon_decimal_point: str + frac_digits: int + int_frac_digits: int + mon_thousands_sep: str + mon_grouping: list[int] + positive_sign: str + negative_sign: str + p_sign_posn: Literal[0, 1, 2, 3, 4, 127] + n_sign_posn: Literal[0, 1, 2, 3, 4, 127] + +LC_CTYPE: Final[int] +LC_COLLATE: Final[int] +LC_TIME: Final[int] +LC_MONETARY: Final[int] +LC_NUMERIC: Final[int] +LC_ALL: Final[int] +CHAR_MAX: Final = 127 + +def setlocale(category: int, locale: str | None = None, /) -> str: ... +def localeconv() -> _LocaleConv: ... + +if sys.version_info >= (3, 11): + def getencoding() -> str: ... + +def strcoll(os1: str, os2: str, /) -> int: ... +def strxfrm(string: str, /) -> str: ... + +# native gettext functions +# https://docs.python.org/3/library/locale.html#access-to-message-catalogs +# https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Modules/_localemodule.c#L626 +if sys.platform != "win32": + LC_MESSAGES: int + + ABDAY_1: Final[int] + ABDAY_2: Final[int] + ABDAY_3: Final[int] + ABDAY_4: Final[int] + ABDAY_5: Final[int] + ABDAY_6: Final[int] + ABDAY_7: Final[int] + + ABMON_1: Final[int] + ABMON_2: Final[int] + ABMON_3: Final[int] + ABMON_4: Final[int] + ABMON_5: Final[int] + ABMON_6: Final[int] + ABMON_7: Final[int] + ABMON_8: Final[int] + ABMON_9: Final[int] + ABMON_10: Final[int] + ABMON_11: Final[int] + ABMON_12: Final[int] + + DAY_1: Final[int] + DAY_2: Final[int] + DAY_3: Final[int] + DAY_4: Final[int] + DAY_5: Final[int] + DAY_6: Final[int] + DAY_7: Final[int] + + ERA: Final[int] + ERA_D_T_FMT: Final[int] + ERA_D_FMT: Final[int] + ERA_T_FMT: Final[int] + + MON_1: Final[int] + MON_2: Final[int] + MON_3: Final[int] + MON_4: Final[int] + MON_5: Final[int] + MON_6: Final[int] + MON_7: Final[int] + MON_8: Final[int] + MON_9: Final[int] + MON_10: Final[int] + MON_11: Final[int] + MON_12: Final[int] + + CODESET: Final[int] + D_T_FMT: Final[int] + D_FMT: Final[int] + T_FMT: Final[int] + T_FMT_AMPM: Final[int] + AM_STR: Final[int] + PM_STR: Final[int] + + RADIXCHAR: Final[int] + THOUSEP: Final[int] + YESEXPR: Final[int] + NOEXPR: Final[int] + CRNCYSTR: Final[int] + ALT_DIGITS: Final[int] + + def nl_langinfo(key: int, /) -> str: ... + + # This is dependent on `libintl.h` which is a part of `gettext` + # system dependency. These functions might be missing. + # But, we always say that they are present. + def gettext(msg: str, /) -> str: ... + def dgettext(domain: str | None, msg: str, /) -> str: ... + def dcgettext(domain: str | None, msg: str, category: int, /) -> str: ... + def textdomain(domain: str | None, /) -> str: ... + def bindtextdomain(domain: str, dir: StrPath | None, /) -> str: ... + def bind_textdomain_codeset(domain: str, codeset: str | None, /) -> str | None: ... diff --git a/stdlib/_lsprof.pyi b/stdlib/_lsprof.pyi new file mode 100644 index 000000000000..d04c2a74ee07 --- /dev/null +++ b/stdlib/_lsprof.pyi @@ -0,0 +1,34 @@ +from _typeshed import structseq +from collections.abc import Callable +from types import CodeType +from typing import Any, Final, final +from typing_extensions import disjoint_base + +@disjoint_base +class Profiler: + def __init__( + self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True + ) -> None: ... + def getstats(self) -> list[profiler_entry]: ... + def enable(self, subcalls: bool = True, builtins: bool = True) -> None: ... + def disable(self) -> None: ... + def clear(self) -> None: ... + +@final +class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]): + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls") + code: CodeType | str + callcount: int + reccallcount: int + totaltime: float + inlinetime: float + calls: list[profiler_subentry] + +@final +class profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]): + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime") + code: CodeType | str + callcount: int + reccallcount: int + totaltime: float + inlinetime: float diff --git a/stdlib/_lzma.pyi b/stdlib/_lzma.pyi new file mode 100644 index 000000000000..83cd8fd756b9 --- /dev/null +++ b/stdlib/_lzma.pyi @@ -0,0 +1,71 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Mapping, Sequence +from typing import Any, Final, TypeAlias, final +from typing_extensions import Self + +_FilterChain: TypeAlias = Sequence[Mapping[str, Any]] + +FORMAT_AUTO: Final = 0 +FORMAT_XZ: Final = 1 +FORMAT_ALONE: Final = 2 +FORMAT_RAW: Final = 3 +CHECK_NONE: Final = 0 +CHECK_CRC32: Final = 1 +CHECK_CRC64: Final = 4 +CHECK_SHA256: Final = 10 +CHECK_ID_MAX: Final = 15 +CHECK_UNKNOWN: Final = 16 +FILTER_LZMA1: Final[int] # v big number +FILTER_LZMA2: Final = 33 +FILTER_DELTA: Final = 3 +FILTER_X86: Final = 4 +FILTER_IA64: Final = 6 +FILTER_ARM: Final = 7 +FILTER_ARMTHUMB: Final = 8 +FILTER_SPARC: Final = 9 +FILTER_POWERPC: Final = 5 +MF_HC3: Final = 3 +MF_HC4: Final = 4 +MF_BT2: Final = 18 +MF_BT3: Final = 19 +MF_BT4: Final = 20 +MODE_FAST: Final = 1 +MODE_NORMAL: Final = 2 +PRESET_DEFAULT: Final = 6 +PRESET_EXTREME: Final[int] # v big number + +@final +class LZMADecompressor: + if sys.version_info >= (3, 12): + def __new__(cls, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> Self: ... + else: + def __init__(self, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> None: ... + + def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: ... + @property + def check(self) -> int: ... + @property + def eof(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... + @property + def needs_input(self) -> bool: ... + +@final +class LZMACompressor: + if sys.version_info >= (3, 12): + def __new__( + cls, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None + ) -> Self: ... + else: + def __init__( + self, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None + ) -> None: ... + + def compress(self, data: ReadableBuffer, /) -> bytes: ... + def flush(self) -> bytes: ... + +class LZMAError(Exception): ... + +def is_check_supported(check_id: int, /) -> bool: ... diff --git a/stdlib/_markupbase.pyi b/stdlib/_markupbase.pyi index 2c497f65bb43..acc3ccac7188 100644 --- a/stdlib/_markupbase.pyi +++ b/stdlib/_markupbase.pyi @@ -1,17 +1,10 @@ -import sys -from typing import Any - class ParserBase: - def __init__(self) -> None: ... def reset(self) -> None: ... def getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... - def parse_comment(self, i: int, report: int = ...) -> int: ... # undocumented + def parse_comment(self, i: int, report: bool = True) -> int: ... # undocumented def parse_declaration(self, i: int) -> int: ... # undocumented - def parse_marked_section(self, i: int, report: int = ...) -> int: ... # undocumented + def parse_marked_section(self, i: int, report: bool = True) -> int: ... # undocumented def updatepos(self, i: int, j: int) -> int: ... # undocumented - if sys.version_info < (3, 10): - # Removed from ParserBase: https://bugs.python.org/issue31844 - def error(self, message: str) -> Any: ... # undocumented lineno: int # undocumented offset: int # undocumented diff --git a/stdlib/_msi.pyi b/stdlib/_msi.pyi index b7e852f38ae9..e5b408811ee7 100644 --- a/stdlib/_msi.pyi +++ b/stdlib/_msi.pyi @@ -1,8 +1,10 @@ import sys +from typing import Final, type_check_only if sys.platform == "win32": - + class MSIError(Exception): ... # Actual typename View, not exposed by the implementation + @type_check_only class _View: def Execute(self, params: _Record | None = ...) -> None: ... def GetColumnInfo(self, kind: int) -> _Record: ... @@ -12,25 +14,31 @@ if sys.platform == "win32": # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] - # Actual typename Summary, not exposed by the implementation - class _Summary: - def GetProperty(self, propid: int) -> str | bytes | None: ... + + # Actual typename SummaryInformation, not exposed by the implementation + @type_check_only + class _SummaryInformation: + def GetProperty(self, field: int) -> int | bytes | None: ... def GetPropertyCount(self) -> int: ... - def SetProperty(self, propid: int, value: str | bytes) -> None: ... + def SetProperty(self, field: int, value: int | str) -> None: ... def Persist(self) -> None: ... # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] + # Actual typename Database, not exposed by the implementation + @type_check_only class _Database: def OpenView(self, sql: str) -> _View: ... def Commit(self) -> None: ... - def GetSummaryInformation(self, updateCount: int) -> _Summary: ... + def GetSummaryInformation(self, updateCount: int) -> _SummaryInformation: ... def Close(self) -> None: ... # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] + # Actual typename Record, not exposed by the implementation + @type_check_only class _Record: def GetFieldCount(self) -> int: ... def GetInteger(self, field: int) -> int: ... @@ -42,7 +50,48 @@ if sys.platform == "win32": # Don't exist at runtime __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] + def UuidCreate() -> str: ... - def FCICreate(cabname: str, files: list[str]) -> None: ... - def OpenDatabase(name: str, flags: int) -> _Database: ... - def CreateRecord(count: int) -> _Record: ... + def FCICreate(cabname: str, files: list[tuple[str, str]], /) -> None: ... + def OpenDatabase(path: str, persist: int, /) -> _Database: ... + def CreateRecord(count: int, /) -> _Record: ... + + MSICOLINFO_NAMES: Final[int] + MSICOLINFO_TYPES: Final[int] + MSIDBOPEN_CREATE: Final[int] + MSIDBOPEN_CREATEDIRECT: Final[int] + MSIDBOPEN_DIRECT: Final[int] + MSIDBOPEN_PATCHFILE: Final[int] + MSIDBOPEN_READONLY: Final[int] + MSIDBOPEN_TRANSACT: Final[int] + MSIMODIFY_ASSIGN: Final[int] + MSIMODIFY_DELETE: Final[int] + MSIMODIFY_INSERT: Final[int] + MSIMODIFY_INSERT_TEMPORARY: Final[int] + MSIMODIFY_MERGE: Final[int] + MSIMODIFY_REFRESH: Final[int] + MSIMODIFY_REPLACE: Final[int] + MSIMODIFY_SEEK: Final[int] + MSIMODIFY_UPDATE: Final[int] + MSIMODIFY_VALIDATE: Final[int] + MSIMODIFY_VALIDATE_DELETE: Final[int] + MSIMODIFY_VALIDATE_FIELD: Final[int] + MSIMODIFY_VALIDATE_NEW: Final[int] + + PID_APPNAME: Final[int] + PID_AUTHOR: Final[int] + PID_CHARCOUNT: Final[int] + PID_CODEPAGE: Final[int] + PID_COMMENTS: Final[int] + PID_CREATE_DTM: Final[int] + PID_KEYWORDS: Final[int] + PID_LASTAUTHOR: Final[int] + PID_LASTPRINTED: Final[int] + PID_LASTSAVE_DTM: Final[int] + PID_PAGECOUNT: Final[int] + PID_REVNUMBER: Final[int] + PID_SECURITY: Final[int] + PID_SUBJECT: Final[int] + PID_TEMPLATE: Final[int] + PID_TITLE: Final[int] + PID_WORDCOUNT: Final[int] diff --git a/stdlib/_multibytecodec.pyi b/stdlib/_multibytecodec.pyi new file mode 100644 index 000000000000..abe58cb64f31 --- /dev/null +++ b/stdlib/_multibytecodec.pyi @@ -0,0 +1,49 @@ +from _typeshed import ReadableBuffer +from codecs import _ReadableStream, _WritableStream +from collections.abc import Iterable +from typing import final, type_check_only +from typing_extensions import disjoint_base + +# This class is not exposed. It calls itself _multibytecodec.MultibyteCodec. +@final +@type_check_only +class _MultibyteCodec: + def decode(self, input: ReadableBuffer, errors: str | None = None) -> str: ... + def encode(self, input: str, errors: str | None = None) -> bytes: ... + +@disjoint_base +class MultibyteIncrementalDecoder: + errors: str + def __init__(self, errors: str = "strict") -> None: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + def getstate(self) -> tuple[bytes, int]: ... + def reset(self) -> None: ... + def setstate(self, state: tuple[bytes, int], /) -> None: ... + +@disjoint_base +class MultibyteIncrementalEncoder: + errors: str + def __init__(self, errors: str = "strict") -> None: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + def getstate(self) -> int: ... + def reset(self) -> None: ... + def setstate(self, state: int, /) -> None: ... + +@disjoint_base +class MultibyteStreamReader: + errors: str + stream: _ReadableStream + def __init__(self, stream: _ReadableStream, errors: str = "strict") -> None: ... + def read(self, sizeobj: int | None = None, /) -> str: ... + def readline(self, sizeobj: int | None = None, /) -> str: ... + def readlines(self, sizehintobj: int | None = None, /) -> list[str]: ... + def reset(self) -> None: ... + +@disjoint_base +class MultibyteStreamWriter: + errors: str + stream: _WritableStream + def __init__(self, stream: _WritableStream, errors: str = "strict") -> None: ... + def reset(self) -> None: ... + def write(self, strobj: str, /) -> None: ... + def writelines(self, lines: Iterable[str], /) -> None: ... diff --git a/stdlib/_operator.pyi b/stdlib/_operator.pyi index 408ec7ca28dc..565bb41697f1 100644 --- a/stdlib/_operator.pyi +++ b/stdlib/_operator.pyi @@ -1,142 +1,161 @@ import sys -from _typeshed import SupportsAnyComparison -from typing import ( - Any, - AnyStr, - Callable, - Container, - Generic, - Iterable, - Mapping, - MutableMapping, - MutableSequence, - Protocol, - Sequence, - SupportsAbs, - Tuple, - TypeVar, - overload, +from _typeshed import ( + ReadableBuffer, + SupportsAdd, + SupportsGetItem, + SupportsMod, + SupportsMul, + SupportsRAdd, + SupportsRMod, + SupportsRMul, + SupportsRSub, + SupportsSub, ) -from typing_extensions import ParamSpec, SupportsIndex, final +from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence +from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller +from typing import Any, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import TypeIs _R = TypeVar("_R") _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) _K = TypeVar("_K") _V = TypeVar("_V") _P = ParamSpec("_P") +# The following protocols return "Any" instead of bool, since the comparison +# operators can be overloaded to return an arbitrary object. For example, +# the numpy.array comparison dunders return another numpy.array. + +@type_check_only +class _SupportsDunderLT(Protocol): + def __lt__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsDunderGT(Protocol): + def __gt__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsDunderLE(Protocol): + def __le__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsDunderGE(Protocol): + def __ge__(self, other: Any, /) -> Any: ... + +_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT + +@type_check_only class _SupportsInversion(Protocol[_T_co]): def __invert__(self) -> _T_co: ... +@type_check_only class _SupportsNeg(Protocol[_T_co]): def __neg__(self) -> _T_co: ... +@type_check_only class _SupportsPos(Protocol[_T_co]): def __pos__(self) -> _T_co: ... # All four comparison functions must have the same signature, or we get false-positive errors -def lt(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... -def le(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... -def eq(__a: object, __b: object) -> Any: ... -def ne(__a: object, __b: object) -> Any: ... -def ge(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... -def gt(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... -def not_(__a: object) -> bool: ... -def truth(__a: object) -> bool: ... -def is_(__a: object, __b: object) -> bool: ... -def is_not(__a: object, __b: object) -> bool: ... -def abs(__a: SupportsAbs[_T]) -> _T: ... -def add(__a: Any, __b: Any) -> Any: ... -def and_(__a: Any, __b: Any) -> Any: ... -def floordiv(__a: Any, __b: Any) -> Any: ... -def index(__a: SupportsIndex) -> int: ... -def inv(__a: _SupportsInversion[_T_co]) -> _T_co: ... -def invert(__a: _SupportsInversion[_T_co]) -> _T_co: ... -def lshift(__a: Any, __b: Any) -> Any: ... -def mod(__a: Any, __b: Any) -> Any: ... -def mul(__a: Any, __b: Any) -> Any: ... -def matmul(__a: Any, __b: Any) -> Any: ... -def neg(__a: _SupportsNeg[_T_co]) -> _T_co: ... -def or_(__a: Any, __b: Any) -> Any: ... -def pos(__a: _SupportsPos[_T_co]) -> _T_co: ... -def pow(__a: Any, __b: Any) -> Any: ... -def rshift(__a: Any, __b: Any) -> Any: ... -def sub(__a: Any, __b: Any) -> Any: ... -def truediv(__a: Any, __b: Any) -> Any: ... -def xor(__a: Any, __b: Any) -> Any: ... -def concat(__a: Sequence[_T], __b: Sequence[_T]) -> Sequence[_T]: ... -def contains(__a: Container[object], __b: object) -> bool: ... -def countOf(__a: Iterable[object], __b: object) -> int: ... -@overload -def delitem(__a: MutableSequence[Any], __b: SupportsIndex) -> None: ... -@overload -def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... -@overload -def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... -@overload -def getitem(__a: Sequence[_T], __b: SupportsIndex) -> _T: ... -@overload -def getitem(__a: Sequence[_T], __b: slice) -> Sequence[_T]: ... -@overload -def getitem(__a: Mapping[_K, _V], __b: _K) -> _V: ... -def indexOf(__a: Iterable[_T], __b: _T) -> int: ... -@overload -def setitem(__a: MutableSequence[_T], __b: SupportsIndex, __c: _T) -> None: ... -@overload -def setitem(__a: MutableSequence[_T], __b: slice, __c: Sequence[_T]) -> None: ... -@overload -def setitem(__a: MutableMapping[_K, _V], __b: _K, __c: _V) -> None: ... -def length_hint(__obj: object, __default: int = ...) -> int: ... -@final -class attrgetter(Generic[_T_co]): - @overload - def __new__(cls, attr: str) -> attrgetter[Any]: ... - @overload - def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ... - @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ... - @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ... - @overload - def __new__(cls, attr: str, *attrs: str) -> attrgetter[Tuple[Any, ...]]: ... - def __call__(self, obj: Any) -> _T_co: ... - -@final -class itemgetter(Generic[_T_co]): - @overload - def __new__(cls, item: Any) -> itemgetter[Any]: ... - @overload - def __new__(cls, item: Any, __item2: Any) -> itemgetter[tuple[Any, Any]]: ... - @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[tuple[Any, Any, Any]]: ... - @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[tuple[Any, Any, Any, Any]]: ... - @overload - def __new__(cls, item: Any, *items: Any) -> itemgetter[Tuple[Any, ...]]: ... - def __call__(self, obj: Any) -> _T_co: ... - -@final -class methodcaller: - def __init__(self, __name: str, *args: Any, **kwargs: Any) -> None: ... - def __call__(self, obj: Any) -> Any: ... - -def iadd(__a: Any, __b: Any) -> Any: ... -def iand(__a: Any, __b: Any) -> Any: ... -def iconcat(__a: Any, __b: Any) -> Any: ... -def ifloordiv(__a: Any, __b: Any) -> Any: ... -def ilshift(__a: Any, __b: Any) -> Any: ... -def imod(__a: Any, __b: Any) -> Any: ... -def imul(__a: Any, __b: Any) -> Any: ... -def imatmul(__a: Any, __b: Any) -> Any: ... -def ior(__a: Any, __b: Any) -> Any: ... -def ipow(__a: Any, __b: Any) -> Any: ... -def irshift(__a: Any, __b: Any) -> Any: ... -def isub(__a: Any, __b: Any) -> Any: ... -def itruediv(__a: Any, __b: Any) -> Any: ... -def ixor(__a: Any, __b: Any) -> Any: ... +def lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def eq(a: object, b: object, /) -> Any: ... +def ne(a: object, b: object, /) -> Any: ... +def ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def not_(a: object, /) -> bool: ... +def truth(a: object, /) -> bool: ... +def is_(a: object, b: object, /) -> bool: ... +def is_not(a: object, b: object, /) -> bool: ... +def abs(a: SupportsAbs[_T], /) -> _T: ... + +@overload +def add(a: SupportsAdd[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def add(a: _T_contra, b: SupportsRAdd[_T_contra, _T_co], /) -> _T_co: ... + +def and_(a, b, /): ... +def floordiv(a, b, /): ... +def index(a: SupportsIndex, /) -> int: ... +def inv(a: _SupportsInversion[_T_co], /) -> _T_co: ... +def invert(a: _SupportsInversion[_T_co], /) -> _T_co: ... +def lshift(a, b, /): ... + +@overload +def mod(a: SupportsMod[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def mod(a: _T_contra, b: SupportsRMod[_T_contra, _T_co], /) -> _T_co: ... + +@overload +def mul(a: SupportsMul[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def mul(a: _T_contra, b: SupportsRMul[_T_contra, _T_co], /) -> _T_co: ... + +def matmul(a, b, /): ... +def neg(a: _SupportsNeg[_T_co], /) -> _T_co: ... +def or_(a, b, /): ... +def pos(a: _SupportsPos[_T_co], /) -> _T_co: ... +def pow(a, b, /): ... +def rshift(a, b, /): ... + +@overload +def sub(a: SupportsSub[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def sub(a: _T_contra, b: SupportsRSub[_T_contra, _T_co], /) -> _T_co: ... + +def truediv(a, b, /): ... +def xor(a, b, /): ... +def concat(a: Sequence[_T], b: Sequence[_T], /) -> Sequence[_T]: ... +def contains(a: Container[object], b: object, /) -> bool: ... +def countOf(a: Iterable[object], b: object, /) -> int: ... + +@overload +def delitem(a: MutableSequence[Any], b: int, /) -> None: ... +@overload +def delitem(a: MutableSequence[Any], b: slice[int | None], /) -> None: ... +@overload +def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ... + +@overload +def getitem(a: Sequence[_T], b: slice[int | None], /) -> Sequence[_T]: ... +@overload +def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ... + +def indexOf(a: Iterable[_T], b: _T, /) -> int: ... + +@overload +def setitem(a: MutableSequence[_T], b: int, c: _T, /) -> None: ... +@overload +def setitem(a: MutableSequence[_T], b: slice[int | None], c: Sequence[_T], /) -> None: ... +@overload +def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... + +def length_hint(obj: object, default: int = 0, /) -> int: ... +def iadd(a, b, /): ... +def iand(a, b, /): ... +def iconcat(a, b, /): ... +def ifloordiv(a, b, /): ... +def ilshift(a, b, /): ... +def imod(a, b, /): ... +def imul(a, b, /): ... +def imatmul(a, b, /): ... +def ior(a, b, /): ... +def ipow(a, b, /): ... +def irshift(a, b, /): ... +def isub(a, b, /): ... +def itruediv(a, b, /): ... +def ixor(a, b, /): ... if sys.version_info >= (3, 11): - def call(__obj: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... # type: ignore + def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + +@overload +def _compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ... +@overload +def _compare_digest(a: str, b: str, /) -> bool: ... -def _compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... +if sys.version_info >= (3, 14): + def is_none(a: object, /) -> TypeIs[None]: ... + def is_not_none(a: _T | None, /) -> TypeIs[_T]: ... diff --git a/stdlib/_osx_support.pyi b/stdlib/_osx_support.pyi index 49ebf93c31b7..fb00e6986dd0 100644 --- a/stdlib/_osx_support.pyi +++ b/stdlib/_osx_support.pyi @@ -1,27 +1,21 @@ -import sys -from typing import Iterable, Sequence, Tuple, TypeVar +from collections.abc import Iterable, Sequence +from typing import Final, TypeVar _T = TypeVar("_T") _K = TypeVar("_K") _V = TypeVar("_V") -__all__: list[str] +__all__ = ["compiler_fixup", "customize_config_vars", "customize_compiler", "get_platform_osx"] -_UNIVERSAL_CONFIG_VARS: Tuple[str, ...] # undocumented -_COMPILER_CONFIG_VARS: Tuple[str, ...] # undocumented -_INITPRE: str # undocumented - -def _find_executable(executable: str, path: str | None = ...) -> str | None: ... # undocumented - -if sys.version_info >= (3, 8): - def _read_output(commandstring: str, capture_stderr: bool = ...) -> str | None: ... # undocumented - -else: - def _read_output(commandstring: str) -> str | None: ... # undocumented +_UNIVERSAL_CONFIG_VARS: Final[tuple[str, ...]] # undocumented +_COMPILER_CONFIG_VARS: Final[tuple[str, ...]] # undocumented +_INITPRE: Final[str] # undocumented +def _find_executable(executable: str, path: str | None = None) -> str | None: ... # undocumented +def _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: ... # undocumented def _find_build_tool(toolname: str) -> str: ... # undocumented -_SYSTEM_VERSION: str | None # undocumented +_SYSTEM_VERSION: Final[str | None] # undocumented def _get_system_version() -> str: ... # undocumented def _remove_original_values(_config_vars: dict[str, str]) -> None: ... # undocumented diff --git a/stdlib/_pickle.pyi b/stdlib/_pickle.pyi new file mode 100644 index 000000000000..f8411c6abc4b --- /dev/null +++ b/stdlib/_pickle.pyi @@ -0,0 +1,114 @@ +from _typeshed import ReadableBuffer, SupportsWrite +from collections.abc import Callable, Iterable, Iterator, Mapping +from pickle import PickleBuffer as PickleBuffer +from typing import Any, Protocol, TypeAlias, type_check_only +from typing_extensions import disjoint_base + +@type_check_only +class _ReadableFileobj(Protocol): + def read(self, n: int, /) -> bytes: ... + def readline(self) -> bytes: ... + +_BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None + +_ReducedType: TypeAlias = ( + str + | tuple[Callable[..., Any], tuple[Any, ...]] + | tuple[Callable[..., Any], tuple[Any, ...], Any] + | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None] + | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None] +) + +def dump( + obj: Any, + file: SupportsWrite[bytes], + protocol: int | None = None, + *, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, +) -> None: ... +def dumps( + obj: Any, protocol: int | None = None, *, fix_imports: bool = True, buffer_callback: _BufferCallback = None +) -> bytes: ... +def load( + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), +) -> Any: ... +def loads( + data: ReadableBuffer, + /, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), +) -> Any: ... + +class PickleError(Exception): ... +class PicklingError(PickleError): ... +class UnpicklingError(PickleError): ... + +@type_check_only +class PicklerMemoProxy: + def clear(self, /) -> None: ... + def copy(self, /) -> dict[int, tuple[int, Any]]: ... + +@disjoint_base +class Pickler: + fast: bool + dispatch_table: Mapping[type, Callable[[Any], _ReducedType]] + bin: bool # undocumented + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = None, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, + ) -> None: ... + + @property + def memo(self) -> PicklerMemoProxy: ... + @memo.setter + def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... + + def dump(self, obj: Any, /) -> None: ... + def clear_memo(self) -> None: ... + + # this method has no default implementation for Python < 3.13 + def persistent_id(self, obj: Any, /) -> Any: ... + # The following method is not defined on _Pickler, but can be defined on + # sub-classes. Should return `NotImplemented` if pickling the supplied + # object is not supported and returns the same types as `__reduce__()`. + def reducer_override(self, obj: object, /) -> _ReducedType: ... + +@type_check_only +class UnpicklerMemoProxy: + def clear(self, /) -> None: ... + def copy(self, /) -> dict[int, tuple[int, Any]]: ... + +@disjoint_base +class Unpickler: + def __init__( + self, + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), + ) -> None: ... + + @property + def memo(self) -> UnpicklerMemoProxy: ... + @memo.setter + def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... + + def load(self) -> Any: ... + def find_class(self, module_name: str, global_name: str, /) -> Any: ... + + # this method has no default implementation for Python < 3.13 + def persistent_load(self, pid: Any, /) -> Any: ... diff --git a/stdlib/_posixsubprocess.pyi b/stdlib/_posixsubprocess.pyi index 0eae723e7a67..dd74e316e899 100644 --- a/stdlib/_posixsubprocess.pyi +++ b/stdlib/_posixsubprocess.pyi @@ -1,24 +1,59 @@ -# NOTE: These are incomplete! +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Sequence +from typing import SupportsIndex -from typing import Callable, Sequence - -def cloexec_pipe() -> tuple[int, int]: ... -def fork_exec( - args: Sequence[str], - executable_list: Sequence[bytes], - close_fds: bool, - fds_to_keep: Sequence[int], - cwd: str, - env_list: Sequence[bytes], - p2cread: int, - p2cwrite: int, - c2pred: int, - c2pwrite: int, - errread: int, - errwrite: int, - errpipe_read: int, - errpipe_write: int, - restore_signals: int, - start_new_session: int, - preexec_fn: Callable[[], None], -) -> int: ... +if sys.platform != "win32": + if sys.version_info >= (3, 14): + def fork_exec( + args: Sequence[StrOrBytesPath] | None, + executable_list: Sequence[bytes], + close_fds: bool, + pass_fds: tuple[int, ...], + cwd: str, + env: Sequence[bytes] | None, + p2cread: int, + p2cwrite: int, + c2pread: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: int, + call_setsid: int, + pgid_to_set: int, + gid: SupportsIndex | None, + extra_groups: list[int] | None, + uid: SupportsIndex | None, + child_umask: int, + preexec_fn: Callable[[], None], + /, + ) -> int: ... + else: + def fork_exec( + args: Sequence[StrOrBytesPath] | None, + executable_list: Sequence[bytes], + close_fds: bool, + pass_fds: tuple[int, ...], + cwd: str, + env: Sequence[bytes] | None, + p2cread: int, + p2cwrite: int, + c2pread: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: bool, + call_setsid: bool, + pgid_to_set: int, + gid: SupportsIndex | None, + extra_groups: list[int] | None, + uid: SupportsIndex | None, + child_umask: int, + preexec_fn: Callable[[], None], + allow_vfork: bool, + /, + ) -> int: ... diff --git a/stdlib/_py_abc.pyi b/stdlib/_py_abc.pyi index 8d7938918271..1260717489e4 100644 --- a/stdlib/_py_abc.pyi +++ b/stdlib/_py_abc.pyi @@ -1,10 +1,14 @@ -from typing import Any, Tuple, Type, TypeVar +import _typeshed +from typing import Any, NewType, TypeVar _T = TypeVar("_T") -# TODO: Change the return into a NewType bound to int after pytype/#597 -def get_cache_token() -> object: ... +_CacheToken = NewType("_CacheToken", int) + +def get_cache_token() -> _CacheToken: ... class ABCMeta(type): - def __new__(__mcls, __name: str, __bases: Tuple[Type[Any], ...], __namespace: dict[str, Any]) -> ABCMeta: ... - def register(cls, subclass: Type[_T]) -> Type[_T]: ... + def __new__( + mcls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], namespace: dict[str, Any], / + ) -> _typeshed.Self: ... + def register(cls, subclass: type[_T]) -> type[_T]: ... diff --git a/stdlib/_pydecimal.pyi b/stdlib/_pydecimal.pyi index 56fbddfffa5c..9fabcc640096 100644 --- a/stdlib/_pydecimal.pyi +++ b/stdlib/_pydecimal.pyi @@ -1,3 +1,50 @@ # This is a slight lie, the implementations aren't exactly identical # However, in all likelihood, the differences are inconsequential -from decimal import * +import sys +from _decimal import * + +__all__ = [ + "Decimal", + "Context", + "DecimalTuple", + "DefaultContext", + "BasicContext", + "ExtendedContext", + "DecimalException", + "Clamped", + "InvalidOperation", + "DivisionByZero", + "Inexact", + "Rounded", + "Subnormal", + "Overflow", + "Underflow", + "FloatOperation", + "DivisionImpossible", + "InvalidContext", + "ConversionSyntax", + "DivisionUndefined", + "ROUND_DOWN", + "ROUND_HALF_UP", + "ROUND_HALF_EVEN", + "ROUND_CEILING", + "ROUND_FLOOR", + "ROUND_UP", + "ROUND_HALF_DOWN", + "ROUND_05UP", + "setcontext", + "getcontext", + "localcontext", + "MAX_PREC", + "MAX_EMAX", + "MIN_EMIN", + "MIN_ETINY", + "HAVE_THREADS", + "HAVE_CONTEXTVAR", +] + +if sys.version_info >= (3, 14): + __all__ += ["IEEEContext", "IEEE_CONTEXT_MAX_BITS"] + +if sys.version_info >= (3, 15): + __all__ += ["SPEC_VERSION"] diff --git a/stdlib/_queue.pyi b/stdlib/_queue.pyi new file mode 100644 index 000000000000..edd484a9a71a --- /dev/null +++ b/stdlib/_queue.pyi @@ -0,0 +1,18 @@ +from types import GenericAlias +from typing import Any, Generic, TypeVar +from typing_extensions import disjoint_base + +_T = TypeVar("_T") + +class Empty(Exception): ... + +@disjoint_base +class SimpleQueue(Generic[_T]): + def __init__(self) -> None: ... + def empty(self) -> bool: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def qsize(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/_random.pyi b/stdlib/_random.pyi index fa80c6d98144..e333b00d1084 100644 --- a/stdlib/_random.pyi +++ b/stdlib/_random.pyi @@ -1,12 +1,14 @@ -from typing import Tuple +from typing import TypeAlias +from typing_extensions import disjoint_base # Actually Tuple[(int,) * 625] -_State = Tuple[int, ...] +_State: TypeAlias = tuple[int, ...] -class Random(object): - def __init__(self, seed: object = ...) -> None: ... - def seed(self, __n: object = ...) -> None: ... +@disjoint_base +class Random: + def __init__(self, seed: object = ..., /) -> None: ... + def seed(self, n: object = None, /) -> None: ... def getstate(self) -> _State: ... - def setstate(self, __state: _State) -> None: ... + def setstate(self, state: _State, /) -> None: ... def random(self) -> float: ... - def getrandbits(self, __k: int) -> int: ... + def getrandbits(self, k: int, /) -> int: ... diff --git a/stdlib/_remote_debugging.pyi b/stdlib/_remote_debugging.pyi new file mode 100644 index 000000000000..5c150442c5e3 --- /dev/null +++ b/stdlib/_remote_debugging.pyi @@ -0,0 +1,186 @@ +from _typeshed import StrOrBytesPath, structseq +from collections.abc import Callable +from typing import Final, TypeAlias, final +from typing_extensions import Self + +_Location: TypeAlias = tuple[int, int, int, int] | LocationInfo | None +_Frame: TypeAlias = tuple[str, _Location, str, int | None] | FrameInfo +_Stats: TypeAlias = dict[str, int | float] + +PROCESS_VM_READV_SUPPORTED: Final[int] +THREAD_STATUS_GIL_REQUESTED: Final[int] +THREAD_STATUS_HAS_EXCEPTION: Final[int] +THREAD_STATUS_HAS_GIL: Final[int] +THREAD_STATUS_MAIN_THREAD: Final[int] +THREAD_STATUS_ON_CPU: Final[int] +THREAD_STATUS_UNKNOWN: Final[int] + +@final +class LocationInfo(structseq[int], tuple[int, int, int, int]): + __match_args__: Final = ("lineno", "end_lineno", "col_offset", "end_col_offset") + @property + def lineno(self) -> int: ... + @property + def end_lineno(self) -> int: ... + @property + def col_offset(self) -> int: ... + @property + def end_col_offset(self) -> int: ... + +@final +class FrameInfo(structseq[object], tuple[str, _Location, str, int | None]): + __match_args__: Final = ("filename", "location", "funcname", "opcode") + @property + def filename(self) -> str: ... + @property + def location(self) -> _Location: ... + @property + def funcname(self) -> str: ... + @property + def opcode(self) -> int | None: ... + +@final +class CoroInfo(structseq[object], tuple[list[_Frame], int | str]): + __match_args__: Final = ("call_stack", "task_name") + @property + def call_stack(self) -> list[_Frame]: ... + @property + def task_name(self) -> int | str: ... + +@final +class TaskInfo(structseq[object], tuple[int, str, list[CoroInfo], list[CoroInfo]]): + __match_args__: Final = ("task_id", "task_name", "coroutine_stack", "awaited_by") + @property + def task_id(self) -> int: ... + @property + def task_name(self) -> str: ... + @property + def coroutine_stack(self) -> list[CoroInfo]: ... + @property + def awaited_by(self) -> list[CoroInfo]: ... + +@final +class ThreadInfo(structseq[object], tuple[int, int, list[_Frame]]): + __match_args__: Final = ("thread_id", "status", "frame_info") + @property + def thread_id(self) -> int: ... + @property + def status(self) -> int: ... + @property + def frame_info(self) -> list[_Frame]: ... + +@final +class InterpreterInfo(structseq[object], tuple[int, list[ThreadInfo]]): + __match_args__: Final = ("interpreter_id", "threads") + @property + def interpreter_id(self) -> int: ... + @property + def threads(self) -> list[ThreadInfo]: ... + +@final +class AwaitedInfo(structseq[object], tuple[int, list[TaskInfo]]): + __match_args__: Final = ("thread_id", "awaited_by") + @property + def thread_id(self) -> int: ... + @property + def awaited_by(self) -> list[TaskInfo]: ... + +@final +class GCStatsInfo(structseq[object], tuple[int, int, int, int, int, int, int, int, int, float]): + __match_args__: Final = ( + "gen", + "iid", + "ts_start", + "ts_stop", + "collections", + "collected", + "uncollectable", + "candidates", + "heap_size", + "duration", + ) + @property + def gen(self) -> int: ... + @property + def iid(self) -> int: ... + @property + def ts_start(self) -> int: ... + @property + def ts_stop(self) -> int: ... + @property + def collections(self) -> int: ... + @property + def collected(self) -> int: ... + @property + def uncollectable(self) -> int: ... + @property + def candidates(self) -> int: ... + @property + def heap_size(self) -> int: ... + @property + def duration(self) -> float: ... + +@final +class RemoteUnwinder: + def __init__( + self, + pid: int, + *, + all_threads: bool = False, + only_active_thread: bool = False, + mode: int = 0, + debug: bool = False, + skip_non_matching_threads: bool = True, + native: bool = False, + gc: bool = False, + opcodes: bool = False, + cache_frames: bool = False, + stats: bool = False, + ) -> None: ... + def get_stack_trace(self) -> list[InterpreterInfo]: ... + def get_all_awaited_by(self) -> list[AwaitedInfo]: ... + def get_async_stack_trace(self) -> list[AwaitedInfo]: ... + def get_stats(self) -> _Stats: ... + def pause_threads(self) -> bool: ... + def resume_threads(self) -> bool: ... + +@final +class GCMonitor: + def __init__(self, pid: int, *, debug: bool = False) -> None: ... + def get_gc_stats(self, all_interpreters: bool = False) -> list[GCStatsInfo]: ... + +@final +class BinaryWriter: + def __init__( + self, filename: StrOrBytesPath, sample_interval_us: int, start_time_us: int, *, compression: int = 0 + ) -> None: ... + @property + def total_samples(self) -> int: ... + def write_sample(self, stack_frames: list[InterpreterInfo], timestamp_us: int) -> None: ... + def set_stats( + self, /, duration_sec: float, sample_rate: float, error_rate: float | None = None, missed_samples: float | None = None + ) -> None: ... + def finalize(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object = None, exc_val: object = None, exc_tb: object = None) -> bool: ... + def get_stats(self) -> _Stats: ... + +@final +class BinaryReader: + def __init__(self, filename: StrOrBytesPath) -> None: ... + @property + def sample_count(self) -> int: ... + @property + def sample_interval_us(self) -> int: ... + def replay(self, collector: object, progress_callback: Callable[[int, int], object] | None = None) -> int: ... + def get_info(self) -> dict[str, object]: ... + def get_stats(self) -> _Stats: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object = None, exc_val: object = None, exc_tb: object = None) -> bool: ... + +def zstd_available() -> bool: ... +def get_child_pids(pid: int, *, recursive: bool = True) -> list[int]: ... +def is_python_process(pid: int) -> bool: ... +def get_gc_stats(pid: int, *, all_interpreters: bool = False) -> list[GCStatsInfo]: ... diff --git a/stdlib/_sitebuiltins.pyi b/stdlib/_sitebuiltins.pyi index a71364b8db65..99abd02386b2 100644 --- a/stdlib/_sitebuiltins.pyi +++ b/stdlib/_sitebuiltins.pyi @@ -1,16 +1,18 @@ -from typing import ClassVar, Iterable, NoReturn -from typing_extensions import Literal +import sys +from collections.abc import Iterable +from typing import ClassVar, Literal +from typing_extensions import Never class Quitter: name: str eof: str def __init__(self, name: str, eof: str) -> None: ... - def __call__(self, code: int | None = ...) -> NoReturn: ... + def __call__(self, code: sys._ExitCode = None) -> Never: ... class _Printer: MAXLINES: ClassVar[Literal[23]] - def __init__(self, name: str, data: str, files: Iterable[str] = ..., dirs: Iterable[str] = ...) -> None: ... + def __init__(self, name: str, data: str, files: Iterable[str] = (), dirs: Iterable[str] = ()) -> None: ... def __call__(self) -> None: ... class _Helper: - def __call__(self, request: object) -> None: ... + def __call__(self, request: object = ...) -> None: ... diff --git a/stdlib/_socket.pyi b/stdlib/_socket.pyi index 82898177286b..759fd8265387 100644 --- a/stdlib/_socket.pyi +++ b/stdlib/_socket.pyi @@ -1,635 +1,966 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable -from typing import Any, SupportsInt, Tuple, Union, overload +from socket import error as error, gaierror as gaierror, herror as herror, timeout as timeout +from typing import Any, Final, SupportsIndex, TypeAlias, overload +from typing_extensions import CapsuleType, disjoint_base -if sys.version_info >= (3, 8): - from typing import SupportsIndex +_CMSG: TypeAlias = tuple[int, int, bytes] +_CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] - _FD = SupportsIndex +# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, +# AF_NETLINK, AF_TIPC) or strings/buffers (AF_UNIX). +# See getsockaddrarg() in socketmodule.c. +if sys.version_info >= (3, 14): + # A bare int is accepted for Bluetooth HCI device IDs. + _Address: TypeAlias = tuple[Any, ...] | str | ReadableBuffer | int else: - _FD = SupportsInt + _Address: TypeAlias = tuple[Any, ...] | str | ReadableBuffer +_RetAddress: TypeAlias = Any -_CMSG = Tuple[int, int, bytes] -_CMSGArg = Tuple[int, int, ReadableBuffer] +# ===== Constants ===== +# This matches the order in the CPython documentation +# https://docs.python.org/3/library/socket.html#constants -# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, -# AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] -_RetAddress = Any -# TODO Most methods allow bytes as address objects - -# ----- Constants ----- -# Some socket families are listed in the "Socket families" section of the docs, -# but not the "Constants" section. These are listed at the end of the list of -# constants. -# -# Besides those and the first few constants listed, the constants are listed in -# documentation order. +if sys.platform != "win32": + AF_UNIX: Final[int] -has_ipv6: bool +AF_INET: Final[int] +AF_INET6: Final[int] + +AF_UNSPEC: Final[int] + +SOCK_STREAM: Final[int] +SOCK_DGRAM: Final[int] +SOCK_RAW: Final[int] +SOCK_RDM: Final[int] +SOCK_SEQPACKET: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.6.27 + SOCK_CLOEXEC: Final[int] + SOCK_NONBLOCK: Final[int] + +# -------------------- +# Many constants of these forms, documented in the Unix documentation on +# sockets and/or the IP protocol, are also defined in the socket module. +# SO_* +# socket.SOMAXCONN +# MSG_* +# SOL_* +# SCM_* +# IPPROTO_* +# IPPORT_* +# INADDR_* +# IP_* +# IPV6_* +# EAI_* +# AI_* +# NI_* +# TCP_* +# -------------------- + +SO_ACCEPTCONN: Final[int] +SO_BROADCAST: Final[int] +SO_DEBUG: Final[int] +SO_DONTROUTE: Final[int] +SO_ERROR: Final[int] +SO_KEEPALIVE: Final[int] +SO_LINGER: Final[int] +SO_OOBINLINE: Final[int] +SO_RCVBUF: Final[int] +SO_RCVLOWAT: Final[int] +SO_RCVTIMEO: Final[int] +SO_REUSEADDR: Final[int] +SO_SNDBUF: Final[int] +SO_SNDLOWAT: Final[int] +SO_SNDTIMEO: Final[int] +SO_TYPE: Final[int] +if sys.platform != "linux": + SO_USELOOPBACK: Final[int] +if sys.platform == "win32": + SO_EXCLUSIVEADDRUSE: Final[int] +if sys.platform != "win32": + SO_REUSEPORT: Final[int] + if sys.platform != "darwin" or sys.version_info >= (3, 13): + SO_BINDTODEVICE: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + SO_DOMAIN: Final[int] + SO_MARK: Final[int] + SO_PASSCRED: Final[int] + SO_PASSSEC: Final[int] + SO_PEERCRED: Final[int] + SO_PEERSEC: Final[int] + SO_PRIORITY: Final[int] + SO_PROTOCOL: Final[int] +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + SO_SETFIB: Final[int] +if sys.platform == "linux" and sys.version_info >= (3, 13): + SO_BINDTOIFINDEX: Final[int] + +SOMAXCONN: Final[int] + +MSG_CTRUNC: Final[int] +MSG_DONTROUTE: Final[int] +MSG_OOB: Final[int] +MSG_PEEK: Final[int] +MSG_TRUNC: Final[int] +MSG_WAITALL: Final[int] +if sys.platform != "win32": + MSG_DONTWAIT: Final[int] + MSG_EOR: Final[int] + MSG_NOSIGNAL: Final[int] # Sometimes this exists on darwin, sometimes not +if sys.platform != "darwin": + MSG_ERRQUEUE: Final[int] +if sys.platform == "win32": + MSG_BCAST: Final[int] + MSG_MCAST: Final[int] +if sys.platform != "win32" and sys.platform != "darwin": + MSG_CMSG_CLOEXEC: Final[int] + MSG_CONFIRM: Final[int] + MSG_FASTOPEN: Final[int] + MSG_MORE: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + MSG_EOF: Final[int] +if sys.platform != "win32" and sys.platform != "linux" and sys.platform != "darwin": + MSG_NOTIFICATION: Final[int] + MSG_BTAG: Final[int] # Not FreeBSD either + MSG_ETAG: Final[int] # Not FreeBSD either + +SOL_IP: Final[int] +SOL_SOCKET: Final[int] +SOL_TCP: Final[int] +SOL_UDP: Final[int] +if sys.platform != "win32" and sys.platform != "darwin": + # Defined in socket.h for Linux, but these aren't always present for + # some reason. + SOL_ATALK: Final[int] + SOL_AX25: Final[int] + SOL_HCI: Final[int] + SOL_IPX: Final[int] + SOL_NETROM: Final[int] + SOL_ROSE: Final[int] + +if sys.platform != "win32": + SCM_RIGHTS: Final[int] +if sys.platform != "win32" and sys.platform != "darwin": + SCM_CREDENTIALS: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + SCM_CREDS: Final[int] + +IPPROTO_ICMP: Final[int] +IPPROTO_IP: Final[int] +IPPROTO_RAW: Final[int] +IPPROTO_TCP: Final[int] +IPPROTO_UDP: Final[int] +IPPROTO_AH: Final[int] +IPPROTO_DSTOPTS: Final[int] +IPPROTO_EGP: Final[int] +IPPROTO_ESP: Final[int] +IPPROTO_FRAGMENT: Final[int] +IPPROTO_HOPOPTS: Final[int] +IPPROTO_ICMPV6: Final[int] +IPPROTO_IDP: Final[int] +IPPROTO_IGMP: Final[int] +IPPROTO_IPV6: Final[int] +IPPROTO_NONE: Final[int] +IPPROTO_PIM: Final[int] +IPPROTO_PUP: Final[int] +IPPROTO_ROUTING: Final[int] +IPPROTO_SCTP: Final[int] +if sys.platform != "linux": + IPPROTO_GGP: Final[int] + IPPROTO_IPV4: Final[int] + IPPROTO_MAX: Final[int] + IPPROTO_ND: Final[int] +if sys.platform == "win32": + IPPROTO_CBT: Final[int] + IPPROTO_ICLFXBM: Final[int] + IPPROTO_IGP: Final[int] + IPPROTO_L2TP: Final[int] + IPPROTO_PGM: Final[int] + IPPROTO_RDP: Final[int] + IPPROTO_ST: Final[int] +if sys.platform != "win32": + IPPROTO_GRE: Final[int] + IPPROTO_IPIP: Final[int] + IPPROTO_RSVP: Final[int] + IPPROTO_TP: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + IPPROTO_EON: Final[int] + IPPROTO_HELLO: Final[int] + IPPROTO_IPCOMP: Final[int] + IPPROTO_XTP: Final[int] +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + IPPROTO_BIP: Final[int] # Not FreeBSD either + IPPROTO_MOBILE: Final[int] # Not FreeBSD either + IPPROTO_VRRP: Final[int] # Not FreeBSD either +if sys.platform == "linux": + # Availability: Linux >= 2.6.20, FreeBSD >= 10.1 + IPPROTO_UDPLITE: Final[int] +if sys.platform == "linux": + IPPROTO_MPTCP: Final[int] + +IPPORT_RESERVED: Final[int] +IPPORT_USERRESERVED: Final[int] + +INADDR_ALLHOSTS_GROUP: Final[int] +INADDR_ANY: Final[int] +INADDR_BROADCAST: Final[int] +INADDR_LOOPBACK: Final[int] +INADDR_MAX_LOCAL_GROUP: Final[int] +INADDR_NONE: Final[int] +INADDR_UNSPEC_GROUP: Final[int] + +IP_ADD_MEMBERSHIP: Final[int] +IP_DROP_MEMBERSHIP: Final[int] +IP_HDRINCL: Final[int] +IP_MULTICAST_IF: Final[int] +IP_MULTICAST_LOOP: Final[int] +IP_MULTICAST_TTL: Final[int] +IP_OPTIONS: Final[int] +if sys.platform != "linux": + IP_RECVDSTADDR: Final[int] +IP_RECVTOS: Final[int] +IP_TOS: Final[int] +IP_TTL: Final[int] +if sys.platform != "win32": + IP_DEFAULT_MULTICAST_LOOP: Final[int] + IP_DEFAULT_MULTICAST_TTL: Final[int] + IP_MAX_MEMBERSHIPS: Final[int] + IP_RECVOPTS: Final[int] + IP_RECVRETOPTS: Final[int] + IP_RETOPTS: Final[int] +if sys.version_info >= (3, 13) and sys.platform == "linux": + CAN_RAW_ERR_FILTER: Final[int] +if sys.version_info >= (3, 15): + if sys.platform == "win32" or sys.platform == "linux": + IPV6_HDRINCL: Final[int] +if sys.version_info >= (3, 14): + IP_RECVTTL: Final[int] + + if sys.platform == "win32" or sys.platform == "linux": + IPV6_RECVERR: Final[int] + IP_RECVERR: Final[int] + SO_ORIGINAL_DST: Final[int] -# Per socketmodule.c, only these three families are portable -AF_UNIX: int -AF_INET: int -AF_INET6: int + if sys.platform == "win32": + SOL_RFCOMM: Final[int] + SO_BTH_ENCRYPT: Final[int] + SO_BTH_MTU: Final[int] + SO_BTH_MTU_MAX: Final[int] + SO_BTH_MTU_MIN: Final[int] + TCP_QUICKACK: Final[int] -SOCK_STREAM: int -SOCK_DGRAM: int -SOCK_RAW: int -SOCK_RDM: int -SOCK_SEQPACKET: int + if sys.platform == "linux": + BDADDR_BREDR: Final[int] + BDADDR_LE_PUBLIC: Final[int] + BDADDR_LE_RANDOM: Final[int] + BT_CHANNEL_POLICY: Final[int] + BT_CHANNEL_POLICY_BREDR_ONLY: Final[int] + BT_CHANNEL_POLICY_BREDR_PREFERRED: Final[int] + BT_CODEC: Final[int] + BT_DEFER_SETUP: Final[int] + BT_FLUSHABLE: Final[int] + BT_FLUSHABLE_OFF: Final[int] + BT_FLUSHABLE_ON: Final[int] + BT_ISO_QOS: Final[int] + BT_MODE: Final[int] + BT_MODE_BASIC: Final[int] + BT_MODE_ERTM: Final[int] + BT_MODE_EXT_FLOWCTL: Final[int] + BT_MODE_LE_FLOWCTL: Final[int] + BT_MODE_STREAMING: Final[int] + BT_PHY: Final[int] + BT_PHY_BR_1M_1SLOT: Final[int] + BT_PHY_BR_1M_3SLOT: Final[int] + BT_PHY_BR_1M_5SLOT: Final[int] + BT_PHY_EDR_2M_1SLOT: Final[int] + BT_PHY_EDR_2M_3SLOT: Final[int] + BT_PHY_EDR_2M_5SLOT: Final[int] + BT_PHY_EDR_3M_1SLOT: Final[int] + BT_PHY_EDR_3M_3SLOT: Final[int] + BT_PHY_EDR_3M_5SLOT: Final[int] + BT_PHY_LE_1M_RX: Final[int] + BT_PHY_LE_1M_TX: Final[int] + BT_PHY_LE_2M_RX: Final[int] + BT_PHY_LE_2M_TX: Final[int] + BT_PHY_LE_CODED_RX: Final[int] + BT_PHY_LE_CODED_TX: Final[int] + BT_PKT_STATUS: Final[int] + BT_POWER: Final[int] + BT_POWER_FORCE_ACTIVE_OFF: Final[int] + BT_POWER_FORCE_ACTIVE_ON: Final[int] + BT_RCVMTU: Final[int] + BT_SECURITY: Final[int] + BT_SECURITY_FIPS: Final[int] + BT_SECURITY_HIGH: Final[int] + BT_SECURITY_LOW: Final[int] + BT_SECURITY_MEDIUM: Final[int] + BT_SECURITY_SDP: Final[int] + BT_SNDMTU: Final[int] + BT_VOICE: Final[int] + BT_VOICE_CVSD_16BIT: Final[int] + BT_VOICE_TRANSPARENT: Final[int] + BT_VOICE_TRANSPARENT_16BIT: Final[int] + HCI_CHANNEL_CONTROL: Final[int] + HCI_CHANNEL_LOGGING: Final[int] + HCI_CHANNEL_MONITOR: Final[int] + HCI_CHANNEL_RAW: Final[int] + HCI_CHANNEL_USER: Final[int] + HCI_DEV_NONE: Final[int] + IP_FREEBIND: Final[int] + IP_RECVORIGDSTADDR: Final[int] + L2CAP_LM: Final[int] + L2CAP_LM_AUTH: Final[int] + L2CAP_LM_ENCRYPT: Final[int] + L2CAP_LM_MASTER: Final[int] + L2CAP_LM_RELIABLE: Final[int] + L2CAP_LM_SECURE: Final[int] + L2CAP_LM_TRUSTED: Final[int] + SOL_BLUETOOTH: Final[int] + SOL_L2CAP: Final[int] + SOL_RFCOMM: Final[int] + SOL_SCO: Final[int] + VMADDR_CID_LOCAL: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + IP_TRANSPARENT: Final[int] +if sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 11): + IP_BIND_ADDRESS_NO_PORT: Final[int] +if sys.version_info >= (3, 12): + IP_ADD_SOURCE_MEMBERSHIP: Final[int] + IP_BLOCK_SOURCE: Final[int] + IP_DROP_SOURCE_MEMBERSHIP: Final[int] + IP_PKTINFO: Final[int] + IP_UNBLOCK_SOURCE: Final[int] + +IPV6_CHECKSUM: Final[int] +IPV6_JOIN_GROUP: Final[int] +IPV6_LEAVE_GROUP: Final[int] +IPV6_MULTICAST_HOPS: Final[int] +IPV6_MULTICAST_IF: Final[int] +IPV6_MULTICAST_LOOP: Final[int] +IPV6_RECVTCLASS: Final[int] +IPV6_TCLASS: Final[int] +IPV6_UNICAST_HOPS: Final[int] +IPV6_V6ONLY: Final[int] +IPV6_DONTFRAG: Final[int] +IPV6_HOPLIMIT: Final[int] +IPV6_HOPOPTS: Final[int] +IPV6_PKTINFO: Final[int] +IPV6_RECVRTHDR: Final[int] +IPV6_RTHDR: Final[int] +if sys.platform != "win32": + IPV6_RTHDR_TYPE_0: Final[int] + IPV6_DSTOPTS: Final[int] + IPV6_NEXTHOP: Final[int] + IPV6_PATHMTU: Final[int] + IPV6_RECVDSTOPTS: Final[int] + IPV6_RECVHOPLIMIT: Final[int] + IPV6_RECVHOPOPTS: Final[int] + IPV6_RECVPATHMTU: Final[int] + IPV6_RECVPKTINFO: Final[int] + IPV6_RTHDRDSTOPTS: Final[int] + +if sys.platform != "win32" and sys.platform != "linux": + IPV6_USE_MIN_MTU: Final[int] + +EAI_AGAIN: Final[int] +EAI_BADFLAGS: Final[int] +EAI_FAIL: Final[int] +EAI_FAMILY: Final[int] +EAI_MEMORY: Final[int] +EAI_NODATA: Final[int] +EAI_NONAME: Final[int] +EAI_SERVICE: Final[int] +EAI_SOCKTYPE: Final[int] +if sys.platform != "win32": + EAI_ADDRFAMILY: Final[int] + EAI_OVERFLOW: Final[int] + EAI_SYSTEM: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + EAI_BADHINTS: Final[int] + EAI_MAX: Final[int] + EAI_PROTOCOL: Final[int] + +AI_ADDRCONFIG: Final[int] +AI_ALL: Final[int] +AI_CANONNAME: Final[int] +AI_NUMERICHOST: Final[int] +AI_NUMERICSERV: Final[int] +AI_PASSIVE: Final[int] +AI_V4MAPPED: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + AI_DEFAULT: Final[int] + AI_MASK: Final[int] + AI_V4MAPPED_CFG: Final[int] + +NI_DGRAM: Final[int] +NI_MAXHOST: Final[int] +NI_MAXSERV: Final[int] +NI_NAMEREQD: Final[int] +NI_NOFQDN: Final[int] +NI_NUMERICHOST: Final[int] +NI_NUMERICSERV: Final[int] +if sys.platform == "linux" and sys.version_info >= (3, 13): + NI_IDN: Final[int] + +TCP_FASTOPEN: Final[int] +TCP_KEEPCNT: Final[int] +TCP_KEEPINTVL: Final[int] +TCP_MAXSEG: Final[int] +TCP_NODELAY: Final[int] +if sys.platform != "win32": + TCP_NOTSENT_LOWAT: Final[int] +if sys.platform != "darwin": + TCP_KEEPIDLE: Final[int] +if sys.platform == "darwin": + TCP_KEEPALIVE: Final[int] +if sys.version_info >= (3, 11) and sys.platform == "darwin": + TCP_CONNECTION_INFO: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + TCP_CONGESTION: Final[int] + TCP_CORK: Final[int] + TCP_DEFER_ACCEPT: Final[int] + TCP_INFO: Final[int] + TCP_LINGER2: Final[int] + TCP_QUICKACK: Final[int] + TCP_SYNCNT: Final[int] + TCP_USER_TIMEOUT: Final[int] + TCP_WINDOW_CLAMP: Final[int] +if sys.platform == "linux" and sys.version_info >= (3, 12): + TCP_CC_INFO: Final[int] + TCP_FASTOPEN_CONNECT: Final[int] + TCP_FASTOPEN_KEY: Final[int] + TCP_FASTOPEN_NO_COOKIE: Final[int] + TCP_INQ: Final[int] + TCP_MD5SIG: Final[int] + TCP_MD5SIG_EXT: Final[int] + TCP_QUEUE_SEQ: Final[int] + TCP_REPAIR: Final[int] + TCP_REPAIR_OPTIONS: Final[int] + TCP_REPAIR_QUEUE: Final[int] + TCP_REPAIR_WINDOW: Final[int] + TCP_SAVED_SYN: Final[int] + TCP_SAVE_SYN: Final[int] + TCP_THIN_DUPACK: Final[int] + TCP_THIN_LINEAR_TIMEOUTS: Final[int] + TCP_TIMESTAMP: Final[int] + TCP_TX_DELAY: Final[int] + TCP_ULP: Final[int] + TCP_ZEROCOPY_RECEIVE: Final[int] + +# -------------------- +# Specifically documented constants +# -------------------- if sys.platform == "linux": - SOCK_CLOEXEC: int - SOCK_NONBLOCK: int - -# Address families not mentioned in the docs -AF_AAL5: int -AF_APPLETALK: int -AF_ASH: int -AF_ATMPVC: int -AF_ATMSVC: int -AF_AX25: int -AF_BRIDGE: int -AF_DECnet: int -AF_ECONET: int -AF_IPX: int -AF_IRDA: int -AF_KEY: int -AF_LLC: int -AF_NETBEUI: int -AF_NETROM: int -AF_PPPOX: int -AF_ROSE: int -AF_ROUTE: int -AF_SECURITY: int -AF_SNA: int -AF_SYSTEM: int -AF_UNSPEC: int -AF_WANPIPE: int -AF_X25: int - -# The "many constants" referenced by the docs -SOMAXCONN: int -AI_ADDRCONFIG: int -AI_ALL: int -AI_CANONNAME: int -AI_DEFAULT: int -AI_MASK: int -AI_NUMERICHOST: int -AI_NUMERICSERV: int -AI_PASSIVE: int -AI_V4MAPPED: int -AI_V4MAPPED_CFG: int -EAI_ADDRFAMILY: int -EAI_AGAIN: int -EAI_BADFLAGS: int -EAI_BADHINTS: int -EAI_FAIL: int -EAI_FAMILY: int -EAI_MAX: int -EAI_MEMORY: int -EAI_NODATA: int -EAI_NONAME: int -EAI_OVERFLOW: int -EAI_PROTOCOL: int -EAI_SERVICE: int -EAI_SOCKTYPE: int -EAI_SYSTEM: int -INADDR_ALLHOSTS_GROUP: int -INADDR_ANY: int -INADDR_BROADCAST: int -INADDR_LOOPBACK: int -INADDR_MAX_LOCAL_GROUP: int -INADDR_NONE: int -INADDR_UNSPEC_GROUP: int -IPPORT_RESERVED: int -IPPORT_USERRESERVED: int -IPPROTO_AH: int -IPPROTO_BIP: int -IPPROTO_DSTOPTS: int -IPPROTO_EGP: int -IPPROTO_EON: int -IPPROTO_ESP: int -IPPROTO_FRAGMENT: int -IPPROTO_GGP: int -IPPROTO_GRE: int -IPPROTO_HELLO: int -IPPROTO_HOPOPTS: int -IPPROTO_ICMP: int -IPPROTO_ICMPV6: int -IPPROTO_IDP: int -IPPROTO_IGMP: int -IPPROTO_IP: int -IPPROTO_IPCOMP: int -IPPROTO_IPIP: int -IPPROTO_IPV4: int -IPPROTO_IPV6: int -IPPROTO_MAX: int -IPPROTO_MOBILE: int -IPPROTO_ND: int -IPPROTO_NONE: int -IPPROTO_PIM: int -IPPROTO_PUP: int -IPPROTO_RAW: int -IPPROTO_ROUTING: int -IPPROTO_RSVP: int -IPPROTO_SCTP: int -IPPROTO_TCP: int -IPPROTO_TP: int -IPPROTO_UDP: int -IPPROTO_VRRP: int -IPPROTO_XTP: int -IPV6_CHECKSUM: int -IPV6_DONTFRAG: int -IPV6_DSTOPTS: int -IPV6_HOPLIMIT: int -IPV6_HOPOPTS: int -IPV6_JOIN_GROUP: int -IPV6_LEAVE_GROUP: int -IPV6_MULTICAST_HOPS: int -IPV6_MULTICAST_IF: int -IPV6_MULTICAST_LOOP: int -IPV6_NEXTHOP: int -IPV6_PATHMTU: int -IPV6_PKTINFO: int -IPV6_RECVDSTOPTS: int -IPV6_RECVHOPLIMIT: int -IPV6_RECVHOPOPTS: int -IPV6_RECVPATHMTU: int -IPV6_RECVPKTINFO: int -IPV6_RECVRTHDR: int -IPV6_RECVTCLASS: int -IPV6_RTHDR: int -IPV6_RTHDRDSTOPTS: int -IPV6_RTHDR_TYPE_0: int -IPV6_TCLASS: int -IPV6_UNICAST_HOPS: int -IPV6_USE_MIN_MTU: int -IPV6_V6ONLY: int -IPX_TYPE: int -IP_ADD_MEMBERSHIP: int -IP_DEFAULT_MULTICAST_LOOP: int -IP_DEFAULT_MULTICAST_TTL: int -IP_DROP_MEMBERSHIP: int -IP_HDRINCL: int -IP_MAX_MEMBERSHIPS: int -IP_MULTICAST_IF: int -IP_MULTICAST_LOOP: int -IP_MULTICAST_TTL: int -IP_OPTIONS: int -IP_RECVDSTADDR: int -IP_RECVOPTS: int -IP_RECVRETOPTS: int -IP_RETOPTS: int -IP_TOS: int -IP_TRANSPARENT: int -IP_TTL: int -LOCAL_PEERCRED: int -MSG_BCAST: int -MSG_BTAG: int -MSG_CMSG_CLOEXEC: int -MSG_CONFIRM: int -MSG_CTRUNC: int -MSG_DONTROUTE: int -MSG_DONTWAIT: int -MSG_EOF: int -MSG_EOR: int -MSG_ERRQUEUE: int -MSG_ETAG: int -MSG_FASTOPEN: int -MSG_MCAST: int -MSG_MORE: int -MSG_NOSIGNAL: int -MSG_NOTIFICATION: int -MSG_OOB: int -MSG_PEEK: int -MSG_TRUNC: int -MSG_WAITALL: int -NI_DGRAM: int -NI_MAXHOST: int -NI_MAXSERV: int -NI_NAMEREQD: int -NI_NOFQDN: int -NI_NUMERICHOST: int -NI_NUMERICSERV: int -SCM_CREDENTIALS: int -SCM_CREDS: int -SCM_RIGHTS: int -SHUT_RD: int -SHUT_RDWR: int -SHUT_WR: int -SOL_ATALK: int -SOL_AX25: int -SOL_HCI: int -SOL_IP: int -SOL_IPX: int -SOL_NETROM: int -SOL_ROSE: int -SOL_SOCKET: int -SOL_TCP: int -SOL_UDP: int -SO_ACCEPTCONN: int -SO_BINDTODEVICE: int -SO_BROADCAST: int -SO_DEBUG: int -SO_DONTROUTE: int -SO_ERROR: int -SO_EXCLUSIVEADDRUSE: int -SO_KEEPALIVE: int -SO_LINGER: int -SO_MARK: int -SO_OOBINLINE: int -SO_PASSCRED: int -SO_PEERCRED: int -SO_PRIORITY: int -SO_RCVBUF: int -SO_RCVLOWAT: int -SO_RCVTIMEO: int -SO_REUSEADDR: int -SO_REUSEPORT: int -SO_SETFIB: int -SO_SNDBUF: int -SO_SNDLOWAT: int -SO_SNDTIMEO: int -SO_TYPE: int -SO_USELOOPBACK: int -TCP_CORK: int -TCP_DEFER_ACCEPT: int -TCP_FASTOPEN: int -TCP_INFO: int -TCP_KEEPCNT: int -TCP_KEEPIDLE: int -TCP_KEEPINTVL: int -TCP_LINGER2: int -TCP_MAXSEG: int -TCP_NODELAY: int -TCP_QUICKACK: int -TCP_SYNCNT: int -TCP_WINDOW_CLAMP: int -if sys.version_info >= (3, 7): - TCP_NOTSENT_LOWAT: int - -# Specifically-documented constants + # Availability: Linux >= 2.6.25, NetBSD >= 8 + AF_CAN: Final[int] + PF_CAN: Final[int] + SOL_CAN_BASE: Final[int] + SOL_CAN_RAW: Final[int] + CAN_EFF_FLAG: Final[int] + CAN_EFF_MASK: Final[int] + CAN_ERR_FLAG: Final[int] + CAN_ERR_MASK: Final[int] + CAN_RAW: Final[int] + CAN_RAW_FILTER: Final[int] + CAN_RAW_LOOPBACK: Final[int] + CAN_RAW_RECV_OWN_MSGS: Final[int] + CAN_RTR_FLAG: Final[int] + CAN_SFF_MASK: Final[int] + if sys.version_info < (3, 11): + CAN_RAW_ERR_FILTER: Final[int] if sys.platform == "linux": - AF_CAN: int - PF_CAN: int - SOL_CAN_BASE: int - SOL_CAN_RAW: int - CAN_EFF_FLAG: int - CAN_EFF_MASK: int - CAN_ERR_FLAG: int - CAN_ERR_MASK: int - CAN_RAW: int - CAN_RAW_ERR_FILTER: int - CAN_RAW_FILTER: int - CAN_RAW_LOOPBACK: int - CAN_RAW_RECV_OWN_MSGS: int - CAN_RTR_FLAG: int - CAN_SFF_MASK: int - - CAN_BCM: int - CAN_BCM_TX_SETUP: int - CAN_BCM_TX_DELETE: int - CAN_BCM_TX_READ: int - CAN_BCM_TX_SEND: int - CAN_BCM_RX_SETUP: int - CAN_BCM_RX_DELETE: int - CAN_BCM_RX_READ: int - CAN_BCM_TX_STATUS: int - CAN_BCM_TX_EXPIRED: int - CAN_BCM_RX_STATUS: int - CAN_BCM_RX_TIMEOUT: int - CAN_BCM_RX_CHANGED: int - - CAN_RAW_FD_FRAMES: int - -if sys.platform == "linux" and sys.version_info >= (3, 8): - CAN_BCM_SETTIMER: int - CAN_BCM_STARTTIMER: int - CAN_BCM_TX_COUNTEVT: int - CAN_BCM_TX_ANNOUNCE: int - CAN_BCM_TX_CP_CAN_ID: int - CAN_BCM_RX_FILTER_ID: int - CAN_BCM_RX_CHECK_DLC: int - CAN_BCM_RX_NO_AUTOTIMER: int - CAN_BCM_RX_ANNOUNCE_RESUME: int - CAN_BCM_TX_RESET_MULTI_IDX: int - CAN_BCM_RX_RTR_FRAME: int - CAN_BCM_CAN_FD_FRAME: int - -if sys.platform == "linux" and sys.version_info >= (3, 7): - CAN_ISOTP: int - -if sys.platform == "linux" and sys.version_info >= (3, 9): - CAN_J1939: int - CAN_RAW_JOIN_FILTERS: int - - J1939_MAX_UNICAST_ADDR: int - J1939_IDLE_ADDR: int - J1939_NO_ADDR: int - J1939_NO_NAME: int - J1939_PGN_REQUEST: int - J1939_PGN_ADDRESS_CLAIMED: int - J1939_PGN_ADDRESS_COMMANDED: int - J1939_PGN_PDU1_MAX: int - J1939_PGN_MAX: int - J1939_NO_PGN: int - - SO_J1939_FILTER: int - SO_J1939_PROMISC: int - SO_J1939_SEND_PRIO: int - SO_J1939_ERRQUEUE: int - - SCM_J1939_DEST_ADDR: int - SCM_J1939_DEST_NAME: int - SCM_J1939_PRIO: int - SCM_J1939_ERRQUEUE: int - - J1939_NLA_PAD: int - J1939_NLA_BYTES_ACKED: int - - J1939_EE_INFO_NONE: int - J1939_EE_INFO_TX_ABORT: int - - J1939_FILTER_MAX: int + # Availability: Linux >= 2.6.25 + CAN_BCM: Final[int] + CAN_BCM_TX_SETUP: Final[int] + CAN_BCM_TX_DELETE: Final[int] + CAN_BCM_TX_READ: Final[int] + CAN_BCM_TX_SEND: Final[int] + CAN_BCM_RX_SETUP: Final[int] + CAN_BCM_RX_DELETE: Final[int] + CAN_BCM_RX_READ: Final[int] + CAN_BCM_TX_STATUS: Final[int] + CAN_BCM_TX_EXPIRED: Final[int] + CAN_BCM_RX_STATUS: Final[int] + CAN_BCM_RX_TIMEOUT: Final[int] + CAN_BCM_RX_CHANGED: Final[int] + CAN_BCM_SETTIMER: Final[int] + CAN_BCM_STARTTIMER: Final[int] + CAN_BCM_TX_COUNTEVT: Final[int] + CAN_BCM_TX_ANNOUNCE: Final[int] + CAN_BCM_TX_CP_CAN_ID: Final[int] + CAN_BCM_RX_FILTER_ID: Final[int] + CAN_BCM_RX_CHECK_DLC: Final[int] + CAN_BCM_RX_NO_AUTOTIMER: Final[int] + CAN_BCM_RX_ANNOUNCE_RESUME: Final[int] + CAN_BCM_TX_RESET_MULTI_IDX: Final[int] + CAN_BCM_RX_RTR_FRAME: Final[int] + CAN_BCM_CAN_FD_FRAME: Final[int] if sys.platform == "linux": - AF_PACKET: int - PF_PACKET: int - PACKET_BROADCAST: int - PACKET_FASTROUTE: int - PACKET_HOST: int - PACKET_LOOPBACK: int - PACKET_MULTICAST: int - PACKET_OTHERHOST: int - PACKET_OUTGOING: int + # Availability: Linux >= 3.6 + CAN_RAW_FD_FRAMES: Final[int] + # Availability: Linux >= 4.1 + CAN_RAW_JOIN_FILTERS: Final[int] + # Availability: Linux >= 2.6.25 + CAN_ISOTP: Final[int] + if sys.version_info >= (3, 15): + CAN_ISOTP_CHK_PAD_DATA: Final[int] + CAN_ISOTP_CHK_PAD_LEN: Final[int] + CAN_ISOTP_DEFAULT_EXT_ADDRESS: Final[int] + CAN_ISOTP_DEFAULT_FLAGS: Final[int] + CAN_ISOTP_DEFAULT_FRAME_TXTIME: Final[int] + CAN_ISOTP_DEFAULT_LL_MTU: Final[int] + CAN_ISOTP_DEFAULT_LL_TX_DL: Final[int] + CAN_ISOTP_DEFAULT_LL_TX_FLAGS: Final[int] + CAN_ISOTP_DEFAULT_PAD_CONTENT: Final[int] + CAN_ISOTP_DEFAULT_RECV_BS: Final[int] + CAN_ISOTP_DEFAULT_RECV_STMIN: Final[int] + CAN_ISOTP_DEFAULT_RECV_WFTMAX: Final[int] + CAN_ISOTP_EXTEND_ADDR: Final[int] + CAN_ISOTP_FORCE_RXSTMIN: Final[int] + CAN_ISOTP_FORCE_TXSTMIN: Final[int] + CAN_ISOTP_HALF_DUPLEX: Final[int] + CAN_ISOTP_LL_OPTS: Final[int] + CAN_ISOTP_LISTEN_MODE: Final[int] + CAN_ISOTP_OPTS: Final[int] + CAN_ISOTP_RECV_FC: Final[int] + CAN_ISOTP_RX_EXT_ADDR: Final[int] + CAN_ISOTP_RX_PADDING: Final[int] + CAN_ISOTP_RX_STMIN: Final[int] + CAN_ISOTP_SF_BROADCAST: Final[int] + CAN_ISOTP_TX_PADDING: Final[int] + CAN_ISOTP_TX_STMIN: Final[int] + CAN_ISOTP_WAIT_TX_DONE: Final[int] + SOL_CAN_ISOTP: Final[int] + # Availability: Linux >= 5.4 + CAN_J1939: Final[int] + + J1939_MAX_UNICAST_ADDR: Final[int] + J1939_IDLE_ADDR: Final[int] + J1939_NO_ADDR: Final[int] + J1939_NO_NAME: Final[int] + J1939_PGN_REQUEST: Final[int] + J1939_PGN_ADDRESS_CLAIMED: Final[int] + J1939_PGN_ADDRESS_COMMANDED: Final[int] + J1939_PGN_PDU1_MAX: Final[int] + J1939_PGN_MAX: Final[int] + J1939_NO_PGN: Final[int] + + SO_J1939_FILTER: Final[int] + SO_J1939_PROMISC: Final[int] + SO_J1939_SEND_PRIO: Final[int] + SO_J1939_ERRQUEUE: Final[int] + + SCM_J1939_DEST_ADDR: Final[int] + SCM_J1939_DEST_NAME: Final[int] + SCM_J1939_PRIO: Final[int] + SCM_J1939_ERRQUEUE: Final[int] + + J1939_NLA_PAD: Final[int] + J1939_NLA_BYTES_ACKED: Final[int] + J1939_EE_INFO_NONE: Final[int] + J1939_EE_INFO_TX_ABORT: Final[int] + J1939_FILTER_MAX: Final[int] + +if sys.version_info >= (3, 12) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # Availability: FreeBSD >= 14.0 + AF_DIVERT: Final[int] + PF_DIVERT: Final[int] if sys.platform == "linux": - AF_RDS: int - PF_RDS: int - SOL_RDS: int - RDS_CANCEL_SENT_TO: int - RDS_CMSG_RDMA_ARGS: int - RDS_CMSG_RDMA_DEST: int - RDS_CMSG_RDMA_MAP: int - RDS_CMSG_RDMA_STATUS: int - RDS_CMSG_RDMA_UPDATE: int - RDS_CONG_MONITOR: int - RDS_FREE_MR: int - RDS_GET_MR: int - RDS_GET_MR_FOR_DEST: int - RDS_RDMA_DONTWAIT: int - RDS_RDMA_FENCE: int - RDS_RDMA_INVALIDATE: int - RDS_RDMA_NOTIFY_ME: int - RDS_RDMA_READWRITE: int - RDS_RDMA_SILENT: int - RDS_RDMA_USE_ONCE: int - RDS_RECVERR: int + # Availability: Linux >= 2.2 + AF_PACKET: Final[int] + PF_PACKET: Final[int] + PACKET_BROADCAST: Final[int] + PACKET_FASTROUTE: Final[int] + PACKET_HOST: Final[int] + PACKET_LOOPBACK: Final[int] + PACKET_MULTICAST: Final[int] + PACKET_OTHERHOST: Final[int] + PACKET_OUTGOING: Final[int] + +if sys.version_info >= (3, 12) and sys.platform == "linux": + ETH_P_ALL: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.6.30 + AF_RDS: Final[int] + PF_RDS: Final[int] + SOL_RDS: Final[int] + # These are present in include/linux/rds.h but don't always show up + # here. + RDS_CANCEL_SENT_TO: Final[int] + RDS_CMSG_RDMA_ARGS: Final[int] + RDS_CMSG_RDMA_DEST: Final[int] + RDS_CMSG_RDMA_MAP: Final[int] + RDS_CMSG_RDMA_STATUS: Final[int] + RDS_CONG_MONITOR: Final[int] + RDS_FREE_MR: Final[int] + RDS_GET_MR: Final[int] + RDS_GET_MR_FOR_DEST: Final[int] + RDS_RDMA_DONTWAIT: Final[int] + RDS_RDMA_FENCE: Final[int] + RDS_RDMA_INVALIDATE: Final[int] + RDS_RDMA_NOTIFY_ME: Final[int] + RDS_RDMA_READWRITE: Final[int] + RDS_RDMA_SILENT: Final[int] + RDS_RDMA_USE_ONCE: Final[int] + RDS_RECVERR: Final[int] + + # This is supported by CPython but doesn't seem to be a real thing. + # The closest existing constant in rds.h is RDS_CMSG_CONG_UPDATE + # RDS_CMSG_RDMA_UPDATE: Final[int] if sys.platform == "win32": - SIO_RCVALL: int - SIO_KEEPALIVE_VALS: int - SIO_LOOPBACK_FAST_PATH: int - RCVALL_IPLEVEL: int - RCVALL_MAX: int - RCVALL_OFF: int - RCVALL_ON: int - RCVALL_SOCKETLEVELONLY: int + SIO_RCVALL: Final[int] + SIO_KEEPALIVE_VALS: Final[int] + SIO_LOOPBACK_FAST_PATH: Final[int] + RCVALL_MAX: Final[int] + RCVALL_OFF: Final[int] + RCVALL_ON: Final[int] + RCVALL_SOCKETLEVELONLY: Final[int] + +if sys.platform == "linux": + AF_TIPC: Final[int] + SOL_TIPC: Final[int] + TIPC_ADDR_ID: Final[int] + TIPC_ADDR_NAME: Final[int] + TIPC_ADDR_NAMESEQ: Final[int] + TIPC_CFG_SRV: Final[int] + TIPC_CLUSTER_SCOPE: Final[int] + TIPC_CONN_TIMEOUT: Final[int] + TIPC_CRITICAL_IMPORTANCE: Final[int] + TIPC_DEST_DROPPABLE: Final[int] + TIPC_HIGH_IMPORTANCE: Final[int] + TIPC_IMPORTANCE: Final[int] + TIPC_LOW_IMPORTANCE: Final[int] + TIPC_MEDIUM_IMPORTANCE: Final[int] + TIPC_NODE_SCOPE: Final[int] + TIPC_PUBLISHED: Final[int] + TIPC_SRC_DROPPABLE: Final[int] + TIPC_SUBSCR_TIMEOUT: Final[int] + TIPC_SUB_CANCEL: Final[int] + TIPC_SUB_PORTS: Final[int] + TIPC_SUB_SERVICE: Final[int] + TIPC_TOP_SRV: Final[int] + TIPC_WAIT_FOREVER: Final[int] + TIPC_WITHDRAWN: Final[int] + TIPC_ZONE_SCOPE: Final[int] if sys.platform == "linux": - AF_TIPC: int - SOL_TIPC: int - TIPC_ADDR_ID: int - TIPC_ADDR_NAME: int - TIPC_ADDR_NAMESEQ: int - TIPC_CFG_SRV: int - TIPC_CLUSTER_SCOPE: int - TIPC_CONN_TIMEOUT: int - TIPC_CRITICAL_IMPORTANCE: int - TIPC_DEST_DROPPABLE: int - TIPC_HIGH_IMPORTANCE: int - TIPC_IMPORTANCE: int - TIPC_LOW_IMPORTANCE: int - TIPC_MEDIUM_IMPORTANCE: int - TIPC_NODE_SCOPE: int - TIPC_PUBLISHED: int - TIPC_SRC_DROPPABLE: int - TIPC_SUBSCR_TIMEOUT: int - TIPC_SUB_CANCEL: int - TIPC_SUB_PORTS: int - TIPC_SUB_SERVICE: int - TIPC_TOP_SRV: int - TIPC_WAIT_FOREVER: int - TIPC_WITHDRAWN: int - TIPC_ZONE_SCOPE: int + # Availability: Linux >= 2.6.38 + AF_ALG: Final[int] + SOL_ALG: Final[int] + ALG_OP_DECRYPT: Final[int] + ALG_OP_ENCRYPT: Final[int] + ALG_OP_SIGN: Final[int] + ALG_OP_VERIFY: Final[int] + ALG_SET_AEAD_ASSOCLEN: Final[int] + ALG_SET_AEAD_AUTHSIZE: Final[int] + ALG_SET_IV: Final[int] + ALG_SET_KEY: Final[int] + ALG_SET_OP: Final[int] + ALG_SET_PUBKEY: Final[int] if sys.platform == "linux": - AF_ALG: int - SOL_ALG: int - ALG_OP_DECRYPT: int - ALG_OP_ENCRYPT: int - ALG_OP_SIGN: int - ALG_OP_VERIFY: int - ALG_SET_AEAD_ASSOCLEN: int - ALG_SET_AEAD_AUTHSIZE: int - ALG_SET_IV: int - ALG_SET_KEY: int - ALG_SET_OP: int - ALG_SET_PUBKEY: int - -if sys.platform == "linux" and sys.version_info >= (3, 7): - AF_VSOCK: int - IOCTL_VM_SOCKETS_GET_LOCAL_CID: int - VMADDR_CID_ANY: int - VMADDR_CID_HOST: int - VMADDR_PORT_ANY: int - SO_VM_SOCKETS_BUFFER_MAX_SIZE: int - SO_VM_SOCKETS_BUFFER_SIZE: int - SO_VM_SOCKETS_BUFFER_MIN_SIZE: int - VM_SOCKETS_INVALID_VERSION: int - -AF_LINK: int # Availability: BSD, macOS - -# BDADDR_* and HCI_* listed with other bluetooth constants below - -SO_DOMAIN: int -SO_PASSSEC: int -SO_PEERSEC: int -SO_PROTOCOL: int -TCP_CONGESTION: int -TCP_USER_TIMEOUT: int - -if sys.platform == "linux" and sys.version_info >= (3, 8): - AF_QIPCRTR: int + # Availability: Linux >= 4.8 (or maybe 3.9, CPython docs are confusing) + AF_VSOCK: Final[int] + IOCTL_VM_SOCKETS_GET_LOCAL_CID: Final = 0x7B9 + VMADDR_CID_ANY: Final = 0xFFFFFFFF + VMADDR_CID_HOST: Final = 2 + VMADDR_PORT_ANY: Final = 0xFFFFFFFF + SO_VM_SOCKETS_BUFFER_MAX_SIZE: Final = 2 + SO_VM_SOCKETS_BUFFER_SIZE: Final = 0 + SO_VM_SOCKETS_BUFFER_MIN_SIZE: Final = 1 + VM_SOCKETS_INVALID_VERSION: Final = 0xFFFFFFFF # undocumented + +# Documented as only available on BSD, macOS, but empirically sometimes +# available on Windows +if sys.platform != "linux": + AF_LINK: Final[int] +has_ipv6: bool + +if sys.platform != "darwin": + BDADDR_ANY: Final = "00:00:00:00:00:00" + BDADDR_LOCAL: Final = "00:00:00:FF:FF:FF" + +if sys.platform != "win32" and sys.platform != "darwin": + HCI_FILTER: Final[int] # not in NetBSD or DragonFlyBSD + HCI_TIME_STAMP: Final[int] # not in FreeBSD, NetBSD, or DragonFlyBSD + HCI_DATA_DIR: Final[int] # not in FreeBSD, NetBSD, or DragonFlyBSD + +if sys.platform == "linux": + AF_QIPCRTR: Final[int] # Availability: Linux >= 4.7 + +if sys.version_info >= (3, 11) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # FreeBSD + SCM_CREDS2: Final[int] + LOCAL_CREDS: Final[int] + LOCAL_CREDS_PERSISTENT: Final[int] + +if sys.version_info >= (3, 11) and sys.platform == "linux": + SO_INCOMING_CPU: Final[int] # Availability: Linux >= 3.9 + +if sys.version_info >= (3, 12) and sys.platform == "win32": + # Availability: Windows + AF_HYPERV: Final[int] + HV_PROTOCOL_RAW: Final[int] + HVSOCKET_CONNECT_TIMEOUT: Final[int] + HVSOCKET_CONNECT_TIMEOUT_MAX: Final[int] + HVSOCKET_CONNECTED_SUSPEND: Final[int] + HVSOCKET_ADDRESS_FLAG_PASSTHRU: Final[int] + HV_GUID_ZERO: Final = "00000000-0000-0000-0000-000000000000" + HV_GUID_WILDCARD: Final = "00000000-0000-0000-0000-000000000000" + HV_GUID_BROADCAST: Final = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF" + HV_GUID_CHILDREN: Final = "90DB8B89-0D35-4F79-8CE9-49EA0AC8B7CD" + HV_GUID_LOOPBACK: Final = "E0E16197-DD56-4A10-9195-5EE7A155A838" + HV_GUID_PARENT: Final = "A42E7CDA-D03F-480C-9CC2-A4DE20ABB878" + +if sys.version_info >= (3, 12): + if sys.platform != "win32": + # Availability: Linux, FreeBSD, macOS + ETHERTYPE_ARP: Final[int] + ETHERTYPE_IP: Final[int] + ETHERTYPE_IPV6: Final[int] + ETHERTYPE_VLAN: Final[int] + +# -------------------- # Semi-documented constants -# (Listed under "Socket families" in the docs, but not "Constants") +# These are alluded to under the "Socket families" section in the docs +# https://docs.python.org/3/library/socket.html#socket-families +# -------------------- if sys.platform == "linux": # Netlink is defined by Linux - AF_NETLINK: int - NETLINK_ARPD: int - NETLINK_CRYPTO: int - NETLINK_DNRTMSG: int - NETLINK_FIREWALL: int - NETLINK_IP6_FW: int - NETLINK_NFLOG: int - NETLINK_ROUTE6: int - NETLINK_ROUTE: int - NETLINK_SKIP: int - NETLINK_TAPBASE: int - NETLINK_TCPDIAG: int - NETLINK_USERSOCK: int - NETLINK_W1: int - NETLINK_XFRM: int + AF_NETLINK: Final[int] + NETLINK_CRYPTO: Final[int] + NETLINK_DNRTMSG: Final[int] + NETLINK_FIREWALL: Final[int] + NETLINK_IP6_FW: Final[int] + NETLINK_NFLOG: Final[int] + NETLINK_ROUTE: Final[int] + NETLINK_USERSOCK: Final[int] + NETLINK_XFRM: Final[int] + # Technically still supported by CPython + # NETLINK_ARPD: Final[int] # linux 2.0 to 2.6.12 (EOL August 2005) + # NETLINK_ROUTE6: Final[int] # linux 2.2 to 2.6.12 (EOL August 2005) + # NETLINK_SKIP: Final[int] # linux 2.0 to 2.6.12 (EOL August 2005) + # NETLINK_TAPBASE: Final[int] # linux 2.2 to 2.6.12 (EOL August 2005) + # NETLINK_TCPDIAG: Final[int] # linux 2.6.0 to 2.6.13 (EOL December 2005) + # NETLINK_W1: Final[int] # linux 2.6.13 to 2.6.17 (EOL October 2006) + +if sys.platform == "darwin": + PF_SYSTEM: Final[int] + SYSPROTO_CONTROL: Final[int] + +if sys.platform != "darwin": + AF_BLUETOOTH: Final[int] if sys.platform != "win32" and sys.platform != "darwin": # Linux and some BSD support is explicit in the docs # Windows and macOS do not support in practice - AF_BLUETOOTH: int - BTPROTO_HCI: int - BTPROTO_L2CAP: int - BTPROTO_RFCOMM: int - BTPROTO_SCO: int # not in FreeBSD + BTPROTO_HCI: Final[int] + BTPROTO_L2CAP: Final[int] + BTPROTO_SCO: Final[int] # not in FreeBSD +if sys.platform != "darwin": + BTPROTO_RFCOMM: Final[int] - BDADDR_ANY: str - BDADDR_LOCAL: str +if sys.platform == "linux": + UDPLITE_RECV_CSCOV: Final[int] + UDPLITE_SEND_CSCOV: Final[int] + +# -------------------- +# Documented under socket.shutdown +# -------------------- +SHUT_RD: Final[int] +SHUT_RDWR: Final[int] +SHUT_WR: Final[int] + +# -------------------- +# Undocumented constants +# -------------------- + +# Undocumented address families +AF_APPLETALK: Final[int] +AF_DECnet: Final[int] +AF_IPX: Final[int] +AF_SNA: Final[int] - HCI_FILTER: int # not in NetBSD or DragonFlyBSD - # not in FreeBSD, NetBSD, or DragonFlyBSD - HCI_TIME_STAMP: int - HCI_DATA_DIR: int +if sys.platform != "win32": + AF_ROUTE: Final[int] if sys.platform == "darwin": - # PF_SYSTEM is defined by macOS - PF_SYSTEM: int - SYSPROTO_CONTROL: int + AF_SYSTEM: Final[int] -# ----- Exceptions ----- +if sys.platform != "darwin": + AF_IRDA: Final[int] -error = OSError - -class herror(error): ... -class gaierror(error): ... +if sys.platform != "win32" and sys.platform != "darwin": + AF_ASH: Final[int] + AF_ATMPVC: Final[int] + AF_ATMSVC: Final[int] + AF_AX25: Final[int] + AF_BRIDGE: Final[int] + AF_ECONET: Final[int] + AF_KEY: Final[int] + AF_LLC: Final[int] + AF_NETBEUI: Final[int] + AF_NETROM: Final[int] + AF_PPPOX: Final[int] + AF_ROSE: Final[int] + AF_SECURITY: Final[int] + AF_WANPIPE: Final[int] + AF_X25: Final[int] + +# Miscellaneous undocumented + +if sys.platform != "win32" and sys.platform != "linux": + LOCAL_PEERCRED: Final[int] -if sys.version_info >= (3, 10): - timeout = TimeoutError -else: - class timeout(error): ... +if sys.platform != "win32" and sys.platform != "darwin": + # Defined in linux socket.h, but this isn't always present for + # some reason. + IPX_TYPE: Final[int] -# ----- Classes ----- +# ===== Classes ===== +@disjoint_base class socket: - family: int - type: int - proto: int + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... + # F811: "Redefinition of unused `timeout`" @property def timeout(self) -> float | None: ... - def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: _FD | None = ...) -> None: ... - def bind(self, __address: _Address | bytes) -> None: ... + if sys.platform == "win32": + def __init__( + self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = None + ) -> None: ... + else: + def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = None) -> None: ... + + def bind(self, address: _Address, /) -> None: ... def close(self) -> None: ... - def connect(self, __address: _Address | bytes) -> None: ... - def connect_ex(self, __address: _Address | bytes) -> int: ... + def connect(self, address: _Address, /) -> None: ... + def connect_ex(self, address: _Address, /) -> int: ... def detach(self) -> int: ... def fileno(self) -> int: ... def getpeername(self) -> _RetAddress: ... def getsockname(self) -> _RetAddress: ... + @overload - def getsockopt(self, __level: int, __optname: int) -> int: ... + def getsockopt(self, level: int, optname: int, /) -> int: ... @overload - def getsockopt(self, __level: int, __optname: int, __buflen: int) -> bytes: ... - if sys.version_info >= (3, 7): - def getblocking(self) -> bool: ... + def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ... + + def getblocking(self) -> bool: ... def gettimeout(self) -> float | None: ... if sys.platform == "win32": - def ioctl(self, __control: int, __option: int | tuple[int, int, int] | bool) -> None: ... - def listen(self, __backlog: int = ...) -> None: ... - def recv(self, __bufsize: int, __flags: int = ...) -> bytes: ... - def recvfrom(self, __bufsize: int, __flags: int = ...) -> tuple[bytes, _RetAddress]: ... + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool, /) -> None: ... + + def listen(self, backlog: int = ..., /) -> None: ... + def recv(self, bufsize: int, flags: int = 0, /) -> bytes: ... + def recvfrom(self, bufsize: int, flags: int = 0, /) -> tuple[bytes, _RetAddress]: ... if sys.platform != "win32": - def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... + def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ... def recvmsg_into( - self, __buffers: Iterable[WriteableBuffer], __ancbufsize: int = ..., __flags: int = ... + self, buffers: Iterable[WriteableBuffer], ancbufsize: int = 0, flags: int = 0, / ) -> tuple[int, list[_CMSG], int, Any]: ... - def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... - def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: ... - def send(self, __data: ReadableBuffer, __flags: int = ...) -> int: ... - def sendall(self, __data: ReadableBuffer, __flags: int = ...) -> None: ... + + def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> int: ... + def send(self, data: ReadableBuffer, flags: int = 0, /) -> int: ... + def sendall(self, data: ReadableBuffer, flags: int = 0, /) -> None: ... + @overload - def sendto(self, __data: ReadableBuffer, __address: _Address) -> int: ... + def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: ... @overload - def sendto(self, __data: ReadableBuffer, __flags: int, __address: _Address) -> int: ... + def sendto(self, data: ReadableBuffer, flags: int, address: _Address, /) -> int: ... + if sys.platform != "win32": def sendmsg( self, - __buffers: Iterable[ReadableBuffer], - __ancdata: Iterable[_CMSGArg] = ..., - __flags: int = ..., - __address: _Address = ..., + buffers: Iterable[ReadableBuffer], + ancdata: Iterable[_CMSGArg] = ..., + flags: int = 0, + address: _Address | None = None, + /, ) -> int: ... if sys.platform == "linux": def sendmsg_afalg( - self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 ) -> int: ... - def setblocking(self, __flag: bool) -> None: ... - def settimeout(self, __value: float | None) -> None: ... + + def setblocking(self, flag: bool, /) -> None: ... + def settimeout(self, value: float | None, /) -> None: ... + @overload - def setsockopt(self, __level: int, __optname: int, __value: int | bytes) -> None: ... + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: ... @overload - def setsockopt(self, __level: int, __optname: int, __value: None, __optlen: int) -> None: ... + def setsockopt(self, level: int, optname: int, value: None, optlen: int, /) -> None: ... + if sys.platform == "win32": - def share(self, __process_id: int) -> bytes: ... - def shutdown(self, __how: int) -> None: ... + def share(self, process_id: int, /) -> bytes: ... -SocketType = socket + def shutdown(self, how: int, /) -> None: ... -# ----- Functions ----- +SocketType = socket -if sys.version_info >= (3, 7): - def close(__fd: _FD) -> None: ... +# ===== Functions ===== -def dup(__fd: _FD) -> int: ... +def close(fd: SupportsIndex, /) -> None: ... +def dup(fd: SupportsIndex, /) -> int: ... # the 5th tuple item is an address def getaddrinfo( - host: bytes | str | None, - port: bytes | str | int | None, - family: int = ..., - type: int = ..., - proto: int = ..., - flags: int = ..., -) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... -def gethostbyname(__hostname: str) -> str: ... -def gethostbyname_ex(__hostname: str) -> tuple[str, list[str], list[str]]: ... + host: bytes | str | None, port: bytes | str | int | None, family: int = ..., type: int = 0, proto: int = 0, flags: int = 0 +) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ... +def gethostbyname(hostname: str, /) -> str: ... +def gethostbyname_ex(hostname: str, /) -> tuple[str, list[str], list[str]]: ... def gethostname() -> str: ... -def gethostbyaddr(__ip_address: str) -> tuple[str, list[str], list[str]]: ... -def getnameinfo(__sockaddr: tuple[str, int] | tuple[str, int, int, int], __flags: int) -> tuple[str, str]: ... -def getprotobyname(__protocolname: str) -> int: ... -def getservbyname(__servicename: str, __protocolname: str = ...) -> int: ... -def getservbyport(__port: int, __protocolname: str = ...) -> str: ... -def ntohl(__x: int) -> int: ... # param & ret val are 32-bit ints -def ntohs(__x: int) -> int: ... # param & ret val are 16-bit ints -def htonl(__x: int) -> int: ... # param & ret val are 32-bit ints -def htons(__x: int) -> int: ... # param & ret val are 16-bit ints -def inet_aton(__ip_string: str) -> bytes: ... # ret val 4 bytes in length -def inet_ntoa(__packed_ip: bytes) -> str: ... -def inet_pton(__address_family: int, __ip_string: str) -> bytes: ... -def inet_ntop(__address_family: int, __packed_ip: bytes) -> str: ... -def CMSG_LEN(__length: int) -> int: ... -def CMSG_SPACE(__length: int) -> int: ... +def gethostbyaddr(ip_address: str, /) -> tuple[str, list[str], list[str]]: ... +def getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], flags: int, /) -> tuple[str, str]: ... +def getprotobyname(protocolname: str, /) -> int: ... +def getservbyname(servicename: str, protocolname: str = ..., /) -> int: ... +def getservbyport(port: int, protocolname: str = ..., /) -> str: ... +def ntohl(x: int, /) -> int: ... # param & ret val are 32-bit ints +def ntohs(x: int, /) -> int: ... # param & ret val are 16-bit ints +def htonl(x: int, /) -> int: ... # param & ret val are 32-bit ints +def htons(x: int, /) -> int: ... # param & ret val are 16-bit ints +def inet_aton(ip_addr: str, /) -> bytes: ... # ret val 4 bytes in length +def inet_ntoa(packed_ip: ReadableBuffer, /) -> str: ... +def inet_pton(address_family: int, ip_string: str, /) -> bytes: ... +def inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: ... def getdefaulttimeout() -> float | None: ... -def setdefaulttimeout(__timeout: float | None) -> None: ... -def socketpair(__family: int = ..., __type: int = ..., __proto: int = ...) -> tuple[socket, socket]: ... + +# F811: "Redefinition of unused `timeout`" +def setdefaulttimeout(timeout: float | None, /) -> None: ... if sys.platform != "win32": - def sethostname(__name: str) -> None: ... + def sethostname(name: str, /) -> None: ... + def CMSG_LEN(length: int, /) -> int: ... + def CMSG_SPACE(length: int, /) -> int: ... + def socketpair(family: int = ..., type: int = ..., proto: int = 0, /) -> tuple[socket, socket]: ... + +def if_nameindex() -> list[tuple[int, str]]: ... +def if_nametoindex(oname: str, /) -> int: ... + +if sys.version_info >= (3, 14): + def if_indextoname(if_index: int, /) -> str: ... + +else: + def if_indextoname(index: int, /) -> str: ... -# Windows added these in 3.8, but didn't have them before -if sys.platform != "win32" or sys.version_info >= (3, 8): - def if_nameindex() -> list[tuple[int, str]]: ... - def if_nametoindex(__name: str) -> int: ... - def if_indextoname(__index: int) -> str: ... +CAPI: CapsuleType diff --git a/stdlib/_sqlite3.pyi b/stdlib/_sqlite3.pyi new file mode 100644 index 000000000000..b6d96121afa9 --- /dev/null +++ b/stdlib/_sqlite3.pyi @@ -0,0 +1,311 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath +from collections.abc import Callable +from sqlite3 import ( + Connection as Connection, + Cursor as Cursor, + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + PrepareProtocol as PrepareProtocol, + ProgrammingError as ProgrammingError, + Row as Row, + Warning as Warning, + _IsolationLevel, +) +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + from sqlite3 import Blob as Blob + +_T = TypeVar("_T") +_ConnectionT = TypeVar("_ConnectionT", bound=Connection) +_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None +_Adapter: TypeAlias = Callable[[_T], _SqliteData] +_Converter: TypeAlias = Callable[[bytes], Any] + +PARSE_COLNAMES: Final = 2 +PARSE_DECLTYPES: Final = 1 +SQLITE_ALTER_TABLE: Final = 26 +SQLITE_ANALYZE: Final = 28 +SQLITE_ATTACH: Final = 24 +SQLITE_CREATE_INDEX: Final = 1 +SQLITE_CREATE_TABLE: Final = 2 +SQLITE_CREATE_TEMP_INDEX: Final = 3 +SQLITE_CREATE_TEMP_TABLE: Final = 4 +SQLITE_CREATE_TEMP_TRIGGER: Final = 5 +SQLITE_CREATE_TEMP_VIEW: Final = 6 +SQLITE_CREATE_TRIGGER: Final = 7 +SQLITE_CREATE_VIEW: Final = 8 +SQLITE_CREATE_VTABLE: Final = 29 +SQLITE_DELETE: Final = 9 +SQLITE_DENY: Final = 1 +SQLITE_DETACH: Final = 25 +SQLITE_DONE: Final = 101 +SQLITE_DROP_INDEX: Final = 10 +SQLITE_DROP_TABLE: Final = 11 +SQLITE_DROP_TEMP_INDEX: Final = 12 +SQLITE_DROP_TEMP_TABLE: Final = 13 +SQLITE_DROP_TEMP_TRIGGER: Final = 14 +SQLITE_DROP_TEMP_VIEW: Final = 15 +SQLITE_DROP_TRIGGER: Final = 16 +SQLITE_DROP_VIEW: Final = 17 +SQLITE_DROP_VTABLE: Final = 30 +SQLITE_FUNCTION: Final = 31 +SQLITE_IGNORE: Final = 2 +SQLITE_INSERT: Final = 18 +SQLITE_OK: Final = 0 +SQLITE_PRAGMA: Final = 19 +SQLITE_READ: Final = 20 +SQLITE_RECURSIVE: Final = 33 +SQLITE_REINDEX: Final = 27 +SQLITE_SAVEPOINT: Final = 32 +SQLITE_SELECT: Final = 21 +SQLITE_TRANSACTION: Final = 22 +SQLITE_UPDATE: Final = 23 +if sys.version_info >= (3, 15): + SQLITE_KEYWORDS: tuple[str, ...] +adapters: dict[tuple[type[Any], type[Any]], _Adapter[Any]] +converters: dict[str, _Converter] +sqlite_version: str + +if sys.version_info < (3, 12): + version: str + +if sys.version_info >= (3, 12): + LEGACY_TRANSACTION_CONTROL: Final = -1 + SQLITE_DBCONFIG_DEFENSIVE: Final = 1010 + SQLITE_DBCONFIG_DQS_DDL: Final = 1014 + SQLITE_DBCONFIG_DQS_DML: Final = 1013 + SQLITE_DBCONFIG_ENABLE_FKEY: Final = 1002 + SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final = 1004 + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final = 1005 + SQLITE_DBCONFIG_ENABLE_QPSG: Final = 1007 + SQLITE_DBCONFIG_ENABLE_TRIGGER: Final = 1003 + SQLITE_DBCONFIG_ENABLE_VIEW: Final = 1015 + SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final = 1012 + SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final = 1016 + SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final = 1006 + SQLITE_DBCONFIG_RESET_DATABASE: Final = 1009 + SQLITE_DBCONFIG_TRIGGER_EQP: Final = 1008 + SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final = 1017 + SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final = 1011 + +if sys.version_info >= (3, 11): + SQLITE_ABORT: Final = 4 + SQLITE_ABORT_ROLLBACK: Final = 516 + SQLITE_AUTH: Final = 23 + SQLITE_AUTH_USER: Final = 279 + SQLITE_BUSY: Final = 5 + SQLITE_BUSY_RECOVERY: Final = 261 + SQLITE_BUSY_SNAPSHOT: Final = 517 + SQLITE_BUSY_TIMEOUT: Final = 773 + SQLITE_CANTOPEN: Final = 14 + SQLITE_CANTOPEN_CONVPATH: Final = 1038 + SQLITE_CANTOPEN_DIRTYWAL: Final = 1294 + SQLITE_CANTOPEN_FULLPATH: Final = 782 + SQLITE_CANTOPEN_ISDIR: Final = 526 + SQLITE_CANTOPEN_NOTEMPDIR: Final = 270 + SQLITE_CANTOPEN_SYMLINK: Final = 1550 + SQLITE_CONSTRAINT: Final = 19 + SQLITE_CONSTRAINT_CHECK: Final = 275 + SQLITE_CONSTRAINT_COMMITHOOK: Final = 531 + SQLITE_CONSTRAINT_FOREIGNKEY: Final = 787 + SQLITE_CONSTRAINT_FUNCTION: Final = 1043 + SQLITE_CONSTRAINT_NOTNULL: Final = 1299 + SQLITE_CONSTRAINT_PINNED: Final = 2835 + SQLITE_CONSTRAINT_PRIMARYKEY: Final = 1555 + SQLITE_CONSTRAINT_ROWID: Final = 2579 + SQLITE_CONSTRAINT_TRIGGER: Final = 1811 + SQLITE_CONSTRAINT_UNIQUE: Final = 2067 + SQLITE_CONSTRAINT_VTAB: Final = 2323 + SQLITE_CORRUPT: Final = 11 + SQLITE_CORRUPT_INDEX: Final = 779 + SQLITE_CORRUPT_SEQUENCE: Final = 523 + SQLITE_CORRUPT_VTAB: Final = 267 + SQLITE_EMPTY: Final = 16 + SQLITE_ERROR: Final = 1 + SQLITE_ERROR_MISSING_COLLSEQ: Final = 257 + SQLITE_ERROR_RETRY: Final = 513 + SQLITE_ERROR_SNAPSHOT: Final = 769 + SQLITE_FORMAT: Final = 24 + SQLITE_FULL: Final = 13 + SQLITE_INTERNAL: Final = 2 + SQLITE_INTERRUPT: Final = 9 + SQLITE_IOERR: Final = 10 + SQLITE_IOERR_ACCESS: Final = 3338 + SQLITE_IOERR_AUTH: Final = 7178 + SQLITE_IOERR_BEGIN_ATOMIC: Final = 7434 + SQLITE_IOERR_BLOCKED: Final = 2826 + SQLITE_IOERR_CHECKRESERVEDLOCK: Final = 3594 + SQLITE_IOERR_CLOSE: Final = 4106 + SQLITE_IOERR_COMMIT_ATOMIC: Final = 7690 + SQLITE_IOERR_CONVPATH: Final = 6666 + SQLITE_IOERR_CORRUPTFS: Final = 8458 + SQLITE_IOERR_DATA: Final = 8202 + SQLITE_IOERR_DELETE: Final = 2570 + SQLITE_IOERR_DELETE_NOENT: Final = 5898 + SQLITE_IOERR_DIR_CLOSE: Final = 4362 + SQLITE_IOERR_DIR_FSYNC: Final = 1290 + SQLITE_IOERR_FSTAT: Final = 1802 + SQLITE_IOERR_FSYNC: Final = 1034 + SQLITE_IOERR_GETTEMPPATH: Final = 6410 + SQLITE_IOERR_LOCK: Final = 3850 + SQLITE_IOERR_MMAP: Final = 6154 + SQLITE_IOERR_NOMEM: Final = 3082 + SQLITE_IOERR_RDLOCK: Final = 2314 + SQLITE_IOERR_READ: Final = 266 + SQLITE_IOERR_ROLLBACK_ATOMIC: Final = 7946 + SQLITE_IOERR_SEEK: Final = 5642 + SQLITE_IOERR_SHMLOCK: Final = 5130 + SQLITE_IOERR_SHMMAP: Final = 5386 + SQLITE_IOERR_SHMOPEN: Final = 4618 + SQLITE_IOERR_SHMSIZE: Final = 4874 + SQLITE_IOERR_SHORT_READ: Final = 522 + SQLITE_IOERR_TRUNCATE: Final = 1546 + SQLITE_IOERR_UNLOCK: Final = 2058 + SQLITE_IOERR_VNODE: Final = 6922 + SQLITE_IOERR_WRITE: Final = 778 + SQLITE_LIMIT_ATTACHED: Final = 7 + SQLITE_LIMIT_COLUMN: Final = 2 + SQLITE_LIMIT_COMPOUND_SELECT: Final = 4 + SQLITE_LIMIT_EXPR_DEPTH: Final = 3 + SQLITE_LIMIT_FUNCTION_ARG: Final = 6 + SQLITE_LIMIT_LENGTH: Final = 0 + SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final = 8 + SQLITE_LIMIT_SQL_LENGTH: Final = 1 + SQLITE_LIMIT_TRIGGER_DEPTH: Final = 10 + SQLITE_LIMIT_VARIABLE_NUMBER: Final = 9 + SQLITE_LIMIT_VDBE_OP: Final = 5 + SQLITE_LIMIT_WORKER_THREADS: Final = 11 + SQLITE_LOCKED: Final = 6 + SQLITE_LOCKED_SHAREDCACHE: Final = 262 + SQLITE_LOCKED_VTAB: Final = 518 + SQLITE_MISMATCH: Final = 20 + SQLITE_MISUSE: Final = 21 + SQLITE_NOLFS: Final = 22 + SQLITE_NOMEM: Final = 7 + SQLITE_NOTADB: Final = 26 + SQLITE_NOTFOUND: Final = 12 + SQLITE_NOTICE: Final = 27 + SQLITE_NOTICE_RECOVER_ROLLBACK: Final = 539 + SQLITE_NOTICE_RECOVER_WAL: Final = 283 + SQLITE_OK_LOAD_PERMANENTLY: Final = 256 + SQLITE_OK_SYMLINK: Final = 512 + SQLITE_PERM: Final = 3 + SQLITE_PROTOCOL: Final = 15 + SQLITE_RANGE: Final = 25 + SQLITE_READONLY: Final = 8 + SQLITE_READONLY_CANTINIT: Final = 1288 + SQLITE_READONLY_CANTLOCK: Final = 520 + SQLITE_READONLY_DBMOVED: Final = 1032 + SQLITE_READONLY_DIRECTORY: Final = 1544 + SQLITE_READONLY_RECOVERY: Final = 264 + SQLITE_READONLY_ROLLBACK: Final = 776 + SQLITE_ROW: Final = 100 + SQLITE_SCHEMA: Final = 17 + SQLITE_TOOBIG: Final = 18 + SQLITE_WARNING: Final = 28 + SQLITE_WARNING_AUTOINDEX: Final = 284 + threadsafety: Literal[0, 1, 3] + +# Can take or return anything depending on what's in the registry. +@overload +def adapt(obj: Any, proto: Any, /) -> Any: ... +@overload +def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ... + +def complete_statement(statement: str) -> bool: ... + +if sys.version_info >= (3, 12): + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + cached_statements: int = 128, + uri: bool = False, + *, + autocommit: bool = ..., + ) -> Connection: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float, + detect_types: int, + isolation_level: _IsolationLevel, + check_same_thread: bool, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + *, + autocommit: bool = ..., + ) -> _ConnectionT: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + *, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> _ConnectionT: ... +else: + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + cached_statements: int = 128, + uri: bool = False, + ) -> Connection: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float, + detect_types: int, + isolation_level: _IsolationLevel, + check_same_thread: bool, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + ) -> _ConnectionT: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + *, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + ) -> _ConnectionT: ... + +def enable_callback_tracebacks(enable: bool, /) -> None: ... + +if sys.version_info < (3, 12): + # takes a pos-or-keyword argument because there is a C wrapper + @deprecated( + "Deprecated since Python 3.10; removed in Python 3.12. " + "Open database in URI mode using `cache=shared` parameter instead." + ) + def enable_shared_cache(do_enable: int) -> None: ... # undocumented + +def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ... +def register_converter(typename: str, converter: _Converter, /) -> None: ... diff --git a/stdlib/_ssl.pyi b/stdlib/_ssl.pyi new file mode 100644 index 000000000000..29e50111b8b2 --- /dev/null +++ b/stdlib/_ssl.pyi @@ -0,0 +1,303 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath +from collections.abc import Callable +from ssl import ( + SSLCertVerificationError as SSLCertVerificationError, + SSLContext, + SSLEOFError as SSLEOFError, + SSLError as SSLError, + SSLObject, + SSLSyscallError as SSLSyscallError, + SSLWantReadError as SSLWantReadError, + SSLWantWriteError as SSLWantWriteError, + SSLZeroReturnError as SSLZeroReturnError, +) +from typing import Any, ClassVar, Final, Literal, TypeAlias, TypedDict, final, overload, type_check_only +from typing_extensions import NotRequired, Self, deprecated, disjoint_base + +_PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] +_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT] + +@type_check_only +class _Cipher(TypedDict): + aead: bool + alg_bits: int + auth: str + description: str + digest: str | None + id: int + kea: str + name: str + protocol: str + strength_bits: int + symmetric: str + +@type_check_only +class _CertInfo(TypedDict): + subject: tuple[tuple[tuple[str, str], ...], ...] + issuer: tuple[tuple[tuple[str, str], ...], ...] + version: int + serialNumber: str + notBefore: str + notAfter: str + subjectAltName: NotRequired[tuple[tuple[str, str], ...] | None] + OCSP: NotRequired[tuple[str, ...] | None] + caIssuers: NotRequired[tuple[str, ...] | None] + crlDistributionPoints: NotRequired[tuple[str, ...] | None] + +def RAND_add(string: str | ReadableBuffer, entropy: float, /) -> None: ... +def RAND_bytes(n: int, /) -> bytes: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.6; removed in Python 3.12. Use `ssl.RAND_bytes()` instead.") + def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ... + +def RAND_status() -> bool: ... +def get_default_verify_paths() -> tuple[str, str, str, str]: ... + +if sys.version_info >= (3, 15): + def get_sigalgs() -> list[str]: ... + +if sys.platform == "win32": + _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] + def enum_certificates(store_name: str) -> _EnumRetType: ... + def enum_crls(store_name: str) -> _EnumRetType: ... + +def txt2obj(txt: str, name: bool = False) -> tuple[int, str, str, str]: ... +def nid2obj(nid: int, /) -> tuple[int, str, str, str]: ... + +@disjoint_base +class _SSLContext: + check_hostname: bool + keylog_filename: str | None + maximum_version: int + minimum_version: int + num_tickets: int + options: int + post_handshake_auth: bool + protocol: int + security_level: int + sni_callback: Callable[[SSLObject, str, SSLContext], int | None] | None + verify_flags: int + verify_mode: int + def __new__(cls, protocol: int, /) -> Self: ... + def cert_store_stats(self) -> dict[str, int]: ... + + @overload + def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ... + @overload + def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: bool = False) -> Any: ... + + def get_ciphers(self) -> list[_Cipher]: ... + def load_cert_chain( + self, certfile: StrOrBytesPath, keyfile: StrOrBytesPath | None = None, password: _PasswordType | None = None + ) -> None: ... + def load_dh_params(self, path: str, /) -> None: ... + def load_verify_locations( + self, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, + ) -> None: ... + def session_stats(self) -> dict[str, int]: ... + def set_ciphers(self, cipherlist: str, /) -> None: ... + def set_default_verify_paths(self) -> None: ... + def set_ecdh_curve(self, name: str, /) -> None: ... + if sys.version_info >= (3, 15): + def get_groups(self, *, include_aliases: bool = False) -> list[str]: ... + def set_ciphersuites(self, ciphersuites: str, /) -> None: ... + def set_client_sigalgs(self, sigalgslist: str, /) -> None: ... + def set_groups(self, grouplist: str, /) -> None: ... + def set_server_sigalgs(self, sigalgslist: str, /) -> None: ... + if sys.version_info >= (3, 13): + def set_psk_client_callback(self, callback: Callable[[str | None], tuple[str | None, bytes]] | None) -> None: ... + def set_psk_server_callback( + self, callback: Callable[[str | None], bytes] | None, identity_hint: str | None = None + ) -> None: ... + +@final +class MemoryBIO: + eof: bool + pending: int + def __new__(self) -> Self: ... + def read(self, size: int = -1, /) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int: ... + def write_eof(self) -> None: ... + +@final +class SSLSession: + __hash__: ClassVar[None] # type: ignore[assignment] + @property + def has_ticket(self) -> bool: ... + @property + def id(self) -> bytes: ... + @property + def ticket_lifetime_hint(self) -> int: ... + @property + def time(self) -> int: ... + @property + def timeout(self) -> int: ... + +# _ssl.Certificate is weird: it can't be instantiated or subclassed. +# Instances can only be created via methods of the private _ssl._SSLSocket class, +# for which the relevant method signatures are: +# +# class _SSLSocket: +# def get_unverified_chain(self) -> list[Certificate] | None: ... +# def get_verified_chain(self) -> list[Certificate] | None: ... +# +# You can find a _ssl._SSLSocket object as the _sslobj attribute of a ssl.SSLSocket object + +@final +class Certificate: + def get_info(self) -> _CertInfo: ... + + @overload + def public_bytes(self) -> str: ... + @overload + def public_bytes(self, format: Literal[1] = 1, /) -> str: ... # ENCODING_PEM + @overload + def public_bytes(self, format: Literal[2], /) -> bytes: ... # ENCODING_DER + @overload + def public_bytes(self, format: int, /) -> str | bytes: ... + +if sys.version_info < (3, 12): + err_codes_to_names: dict[tuple[int, int], str] + err_names_to_codes: dict[str, tuple[int, int]] + lib_codes_to_names: dict[int, str] + +_DEFAULT_CIPHERS: Final[str] + +# SSL error numbers +SSL_ERROR_ZERO_RETURN: Final = 6 +SSL_ERROR_WANT_READ: Final = 2 +SSL_ERROR_WANT_WRITE: Final = 3 +SSL_ERROR_WANT_X509_LOOKUP: Final = 4 +SSL_ERROR_SYSCALL: Final = 5 +SSL_ERROR_SSL: Final = 1 +SSL_ERROR_WANT_CONNECT: Final = 7 +SSL_ERROR_EOF: Final = 8 +SSL_ERROR_INVALID_ERROR_CODE: Final = 10 + +# verify modes +CERT_NONE: Final = 0 +CERT_OPTIONAL: Final = 1 +CERT_REQUIRED: Final = 2 + +# verify flags +VERIFY_DEFAULT: Final = 0 +VERIFY_CRL_CHECK_LEAF: Final = 0x04 +VERIFY_CRL_CHECK_CHAIN: Final = 0x0C +VERIFY_X509_STRICT: Final = 0x20 +VERIFY_X509_TRUSTED_FIRST: Final = 0x8000 +VERIFY_ALLOW_PROXY_CERTS: Final = 0x40 +VERIFY_X509_PARTIAL_CHAIN: Final = 0x80000 + +# alert descriptions +ALERT_DESCRIPTION_CLOSE_NOTIFY: Final = 0 +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = 10 +ALERT_DESCRIPTION_BAD_RECORD_MAC: Final = 20 +ALERT_DESCRIPTION_RECORD_OVERFLOW: Final = 22 +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = 30 +ALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = 40 +ALERT_DESCRIPTION_BAD_CERTIFICATE: Final = 42 +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = 43 +ALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = 44 +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = 45 +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = 46 +ALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = 47 +ALERT_DESCRIPTION_UNKNOWN_CA: Final = 48 +ALERT_DESCRIPTION_ACCESS_DENIED: Final = 49 +ALERT_DESCRIPTION_DECODE_ERROR: Final = 50 +ALERT_DESCRIPTION_DECRYPT_ERROR: Final = 51 +ALERT_DESCRIPTION_PROTOCOL_VERSION: Final = 70 +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = 71 +ALERT_DESCRIPTION_INTERNAL_ERROR: Final = 80 +ALERT_DESCRIPTION_USER_CANCELLED: Final = 90 +ALERT_DESCRIPTION_NO_RENEGOTIATION: Final = 100 +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = 110 +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = 111 +ALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = 112 +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = 113 +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = 114 +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = 115 + +# protocol versions +PROTOCOL_SSLv23: Final = 2 +PROTOCOL_TLS: Final = 2 +PROTOCOL_TLS_CLIENT: Final = 16 +PROTOCOL_TLS_SERVER: Final = 17 +PROTOCOL_TLSv1: Final = 3 +PROTOCOL_TLSv1_1: Final = 4 +PROTOCOL_TLSv1_2: Final = 5 + +# protocol options +OP_ALL: Final[int] +OP_NO_SSLv2: Final = 0x0 +OP_NO_SSLv3: Final = 0x2000000 +OP_NO_TLSv1: Final = 0x4000000 +OP_NO_TLSv1_1: Final = 0x10000000 +OP_NO_TLSv1_2: Final = 0x8000000 +OP_NO_TLSv1_3: Final = 0x20000000 +OP_CIPHER_SERVER_PREFERENCE: Final = 0x400000 +OP_SINGLE_DH_USE: Final = 0x0 +OP_NO_TICKET: Final = 0x4000 +OP_SINGLE_ECDH_USE: Final = 0x0 +OP_NO_COMPRESSION: Final = 0x20000 +OP_ENABLE_MIDDLEBOX_COMPAT: Final = 0x100000 +OP_NO_RENEGOTIATION: Final = 0x40000000 +if sys.version_info >= (3, 11) or sys.platform == "linux": + OP_IGNORE_UNEXPECTED_EOF: Final = 0x80 +if sys.version_info >= (3, 12): + OP_LEGACY_SERVER_CONNECT: Final = 0x4 + OP_ENABLE_KTLS: Final = 0x8 + +# host flags +HOSTFLAG_ALWAYS_CHECK_SUBJECT: Final = 0x1 +HOSTFLAG_NEVER_CHECK_SUBJECT: Final = 0x20 +HOSTFLAG_NO_WILDCARDS: Final = 0x2 +HOSTFLAG_NO_PARTIAL_WILDCARDS: Final = 0x4 +HOSTFLAG_MULTI_LABEL_WILDCARDS: Final = 0x8 +HOSTFLAG_SINGLE_LABEL_SUBDOMAINS: Final = 0x10 + +# certificate file types +ENCODING_PEM: Final = 1 +ENCODING_DER: Final = 2 + +# protocol versions +PROTO_MINIMUM_SUPPORTED: Final = -2 +PROTO_MAXIMUM_SUPPORTED: Final = -1 +PROTO_SSLv3: Final[int] +PROTO_TLSv1: Final[int] +PROTO_TLSv1_1: Final[int] +PROTO_TLSv1_2: Final[int] +PROTO_TLSv1_3: Final[int] + +# feature support +HAS_SNI: Final[bool] +HAS_TLS_UNIQUE: Final[bool] +HAS_ECDH: Final[bool] +HAS_NPN: Final[bool] +if sys.version_info >= (3, 13): + HAS_PSK: Final[bool] +if sys.version_info >= (3, 15): + HAS_PSK_TLS13: Final[bool] +HAS_ALPN: Final[bool] +HAS_SSLv2: Final[bool] +HAS_SSLv3: Final[bool] +HAS_TLSv1: Final[bool] +HAS_TLSv1_1: Final[bool] +HAS_TLSv1_2: Final[bool] +HAS_TLSv1_3: Final[bool] +if sys.version_info >= (3, 14): + HAS_PHA: Final[bool] + +# version info +OPENSSL_VERSION_NUMBER: Final[int] +OPENSSL_VERSION_INFO: Final[tuple[int, int, int, int, int]] +OPENSSL_VERSION: Final[str] +_OPENSSL_API_VERSION: Final[tuple[int, int, int, int, int]] diff --git a/stdlib/_stat.pyi b/stdlib/_stat.pyi index 634f7da02563..7129a282b574 100644 --- a/stdlib/_stat.pyi +++ b/stdlib/_stat.pyi @@ -1,65 +1,119 @@ -SF_APPEND: int -SF_ARCHIVED: int -SF_IMMUTABLE: int -SF_NOUNLINK: int -SF_SNAPSHOT: int -ST_ATIME: int -ST_CTIME: int -ST_DEV: int -ST_GID: int -ST_INO: int -ST_MODE: int -ST_MTIME: int -ST_NLINK: int -ST_SIZE: int -ST_UID: int -S_ENFMT: int -S_IEXEC: int -S_IFBLK: int -S_IFCHR: int -S_IFDIR: int -S_IFDOOR: int -S_IFIFO: int -S_IFLNK: int -S_IFPORT: int -S_IFREG: int -S_IFSOCK: int -S_IFWHT: int -S_IREAD: int -S_IRGRP: int -S_IROTH: int -S_IRUSR: int -S_IRWXG: int -S_IRWXO: int -S_IRWXU: int -S_ISGID: int -S_ISUID: int -S_ISVTX: int -S_IWGRP: int -S_IWOTH: int -S_IWRITE: int -S_IWUSR: int -S_IXGRP: int -S_IXOTH: int -S_IXUSR: int -UF_APPEND: int -UF_COMPRESSED: int -UF_HIDDEN: int -UF_IMMUTABLE: int -UF_NODUMP: int -UF_NOUNLINK: int -UF_OPAQUE: int - -def S_IMODE(mode: int) -> int: ... -def S_IFMT(mode: int) -> int: ... -def S_ISBLK(mode: int) -> bool: ... -def S_ISCHR(mode: int) -> bool: ... -def S_ISDIR(mode: int) -> bool: ... -def S_ISDOOR(mode: int) -> bool: ... -def S_ISFIFO(mode: int) -> bool: ... -def S_ISLNK(mode: int) -> bool: ... -def S_ISPORT(mode: int) -> bool: ... -def S_ISREG(mode: int) -> bool: ... -def S_ISSOCK(mode: int) -> bool: ... -def S_ISWHT(mode: int) -> bool: ... -def filemode(mode: int) -> str: ... +import sys +from typing import Final + +SF_APPEND: Final = 0x00040000 +SF_ARCHIVED: Final = 0x00010000 +SF_IMMUTABLE: Final = 0x00020000 +SF_NOUNLINK: Final = 0x00100000 +SF_SNAPSHOT: Final = 0x00200000 + +ST_MODE: Final = 0 +ST_INO: Final = 1 +ST_DEV: Final = 2 +ST_NLINK: Final = 3 +ST_UID: Final = 4 +ST_GID: Final = 5 +ST_SIZE: Final = 6 +ST_ATIME: Final = 7 +ST_MTIME: Final = 8 +ST_CTIME: Final = 9 + +S_IFIFO: Final = 0o010000 +S_IFLNK: Final = 0o120000 +S_IFREG: Final = 0o100000 +S_IFSOCK: Final = 0o140000 +S_IFBLK: Final = 0o060000 +S_IFCHR: Final = 0o020000 +S_IFDIR: Final = 0o040000 + +# These are 0 on systems that don't support the specific kind of file. +# Example: Linux doesn't support door files, so S_IFDOOR is 0 on linux. +S_IFDOOR: Final[int] +S_IFPORT: Final[int] +S_IFWHT: Final[int] + +S_ISUID: Final = 0o4000 +S_ISGID: Final = 0o2000 +S_ISVTX: Final = 0o1000 + +S_IRWXU: Final = 0o0700 +S_IRUSR: Final = 0o0400 +S_IWUSR: Final = 0o0200 +S_IXUSR: Final = 0o0100 + +S_IRWXG: Final = 0o0070 +S_IRGRP: Final = 0o0040 +S_IWGRP: Final = 0o0020 +S_IXGRP: Final = 0o0010 + +S_IRWXO: Final = 0o0007 +S_IROTH: Final = 0o0004 +S_IWOTH: Final = 0o0002 +S_IXOTH: Final = 0o0001 + +S_ENFMT: Final = 0o2000 +S_IREAD: Final = 0o0400 +S_IWRITE: Final = 0o0200 +S_IEXEC: Final = 0o0100 + +UF_APPEND: Final = 0x00000004 +UF_COMPRESSED: Final = 0x00000020 # OS X 10.6+ only +UF_HIDDEN: Final = 0x00008000 # OX X 10.5+ only +UF_IMMUTABLE: Final = 0x00000002 +UF_NODUMP: Final = 0x00000001 +UF_NOUNLINK: Final = 0x00000010 +UF_OPAQUE: Final = 0x00000008 + +def S_IMODE(mode: int, /) -> int: ... +def S_IFMT(mode: int, /) -> int: ... +def S_ISBLK(mode: int, /) -> bool: ... +def S_ISCHR(mode: int, /) -> bool: ... +def S_ISDIR(mode: int, /) -> bool: ... +def S_ISDOOR(mode: int, /) -> bool: ... +def S_ISFIFO(mode: int, /) -> bool: ... +def S_ISLNK(mode: int, /) -> bool: ... +def S_ISPORT(mode: int, /) -> bool: ... +def S_ISREG(mode: int, /) -> bool: ... +def S_ISSOCK(mode: int, /) -> bool: ... +def S_ISWHT(mode: int, /) -> bool: ... +def filemode(mode: int, /) -> str: ... + +if sys.platform == "win32": + IO_REPARSE_TAG_SYMLINK: Final = 0xA000000C + IO_REPARSE_TAG_MOUNT_POINT: Final = 0xA0000003 + IO_REPARSE_TAG_APPEXECLINK: Final = 0x8000001B + +if sys.platform == "win32": + FILE_ATTRIBUTE_ARCHIVE: Final = 32 + FILE_ATTRIBUTE_COMPRESSED: Final = 2048 + FILE_ATTRIBUTE_DEVICE: Final = 64 + FILE_ATTRIBUTE_DIRECTORY: Final = 16 + FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 + FILE_ATTRIBUTE_HIDDEN: Final = 2 + FILE_ATTRIBUTE_INTEGRITY_STREAM: Final = 32768 + FILE_ATTRIBUTE_NORMAL: Final = 128 + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 + FILE_ATTRIBUTE_NO_SCRUB_DATA: Final = 131072 + FILE_ATTRIBUTE_OFFLINE: Final = 4096 + FILE_ATTRIBUTE_READONLY: Final = 1 + FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 + FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 + FILE_ATTRIBUTE_SYSTEM: Final = 4 + FILE_ATTRIBUTE_TEMPORARY: Final = 256 + FILE_ATTRIBUTE_VIRTUAL: Final = 65536 + +if sys.version_info >= (3, 13): + # Varies by platform. + SF_SETTABLE: Final[int] + # https://github.com/python/cpython/issues/114081#issuecomment-2119017790 + # SF_RESTRICTED: Literal[0x00080000] + SF_FIRMLINK: Final = 0x00800000 + SF_DATALESS: Final = 0x40000000 + + if sys.platform == "darwin": + SF_SUPPORTED: Final = 0x9F0000 + SF_SYNTHETIC: Final = 0xC0000000 + + UF_TRACKED: Final = 0x00000040 + UF_DATAVAULT: Final = 0x00000080 + UF_SETTABLE: Final = 0x0000FFFF diff --git a/stdlib/_struct.pyi b/stdlib/_struct.pyi new file mode 100644 index 000000000000..6a877cb82eb1 --- /dev/null +++ b/stdlib/_struct.pyi @@ -0,0 +1,24 @@ +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Iterator +from typing import Any +from typing_extensions import disjoint_base + +def pack(format: str | bytes, /, *values: Any) -> bytes: ... +def pack_into(format: str | bytes, buffer: WriteableBuffer, offset: int, /, *values: Any) -> None: ... +def unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ... +def unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... +def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... +def calcsize(format: str | bytes, /) -> int: ... + +@disjoint_base +class Struct: + @property + def format(self) -> str: ... + @property + def size(self) -> int: ... + def __init__(self, format: str | bytes) -> None: ... + def pack(self, *values: Any) -> bytes: ... + def pack_into(self, buffer: WriteableBuffer, offset: int, /, *values: Any) -> None: ... + def unpack(self, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ... + def unpack_from(self, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... + def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... diff --git a/stdlib/_thread.pyi b/stdlib/_thread.pyi index 55ca3e80c7de..823a91831ee3 100644 --- a/stdlib/_thread.pyi +++ b/stdlib/_thread.pyi @@ -1,47 +1,125 @@ +import signal import sys from _typeshed import structseq +from collections.abc import Callable from threading import Thread from types import TracebackType -from typing import Any, Callable, NoReturn, Optional, Tuple, Type -from typing_extensions import final +from typing import Any, Final, final, overload +from typing_extensions import Never, TypeVarTuple, Unpack, deprecated, disjoint_base + +_Ts = TypeVarTuple("_Ts") error = RuntimeError def _count() -> int: ... -_dangling: Any - @final -class LockType: - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... +class RLock: + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... def release(self) -> None: ... - def locked(self) -> bool: ... - def __enter__(self) -> bool: ... + __enter__ = acquire def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... + +if sys.version_info >= (3, 13): + @final + class _ThreadHandle: + ident: int + + def join(self, timeout: float | None = None, /) -> None: ... + def is_done(self) -> bool: ... + def _set_done(self) -> None: ... + + def start_joinable_thread( + function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True + ) -> _ThreadHandle: ... + + @final + class lock: + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + @deprecated("Obsolete synonym. Use `acquire()` instead.") + def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ... # undocumented + @deprecated("Obsolete synonym. Use `release()` instead.") + def release_lock(self) -> None: ... # undocumented + @deprecated("Obsolete synonym. Use `locked()` instead.") + def locked_lock(self) -> bool: ... # undocumented + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... + + LockType = lock +else: + @final + class LockType: + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + @deprecated("Obsolete synonym. Use `acquire()` instead.") + def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ... # undocumented + @deprecated("Obsolete synonym. Use `release()` instead.") + def release_lock(self) -> None: ... # undocumented + @deprecated("Obsolete synonym. Use `locked()` instead.") + def locked_lock(self) -> bool: ... # undocumented + def __enter__(self) -> bool: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ... -def interrupt_main() -> None: ... -def exit() -> NoReturn: ... +@overload +def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ... +@overload +def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... + +@overload +@deprecated("Obsolete synonym. Use `start_new_thread()` instead.") +def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ... # undocumented +@overload +@deprecated("Obsolete synonym. Use `start_new_thread()` instead.") +def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... # undocumented + +def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ... +def exit() -> Never: ... +@deprecated("Obsolete synonym. Use `exit()` instead.") +def exit_thread() -> Never: ... # undocumented def allocate_lock() -> LockType: ... +@deprecated("Obsolete synonym. Use `allocate_lock()` instead.") +def allocate() -> LockType: ... # undocumented def get_ident() -> int: ... -def stack_size(size: int = ...) -> int: ... +def stack_size(size: int = 0, /) -> int: ... -TIMEOUT_MAX: float +TIMEOUT_MAX: Final[float] -if sys.version_info >= (3, 8): - def get_native_id() -> int: ... # only available on some platforms - @final - class _ExceptHookArgs( - structseq[Any], Tuple[Type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]] - ): - @property - def exc_type(self) -> Type[BaseException]: ... - @property - def exc_value(self) -> BaseException | None: ... - @property - def exc_traceback(self) -> TracebackType | None: ... - @property - def thread(self) -> Thread | None: ... - _excepthook: Callable[[_ExceptHookArgs], Any] +def get_native_id() -> int: ... # only available on some platforms + +@final +class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): + __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") + + @property + def exc_type(self) -> type[BaseException]: ... + @property + def exc_value(self) -> BaseException | None: ... + @property + def exc_traceback(self) -> TracebackType | None: ... + @property + def thread(self) -> Thread | None: ... + +_excepthook: Callable[[_ExceptHookArgs], Any] + +if sys.version_info >= (3, 12): + def daemon_threads_allowed() -> bool: ... + +if sys.version_info >= (3, 14): + def set_name(name: str) -> None: ... + +@disjoint_base +class _local: + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... diff --git a/stdlib/_threading_local.pyi b/stdlib/_threading_local.pyi index bab69a7c2e7d..7d4e61c6f2ec 100644 --- a/stdlib/_threading_local.pyi +++ b/stdlib/_threading_local.pyi @@ -1,16 +1,24 @@ -from typing import Any, Dict +from threading import RLock +from typing import Any, TypeAlias +from typing_extensions import Self from weakref import ReferenceType -localdict = Dict[Any, Any] +__all__ = ["local"] +_LocalDict: TypeAlias = dict[Any, Any] class _localimpl: + __slots__ = ("key", "dicts", "localargs", "locallock", "__weakref__") key: str - dicts: dict[int, tuple[ReferenceType[Any], localdict]] - def __init__(self) -> None: ... - def get_dict(self) -> localdict: ... - def create_dict(self) -> localdict: ... + dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]] + # Keep localargs in sync with the *args, **kwargs annotation on local.__new__ + localargs: tuple[list[Any], dict[str, Any]] + locallock: RLock + def get_dict(self) -> _LocalDict: ... + def create_dict(self) -> _LocalDict: ... class local: + __slots__ = ("_local__impl", "__dict__") + def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... def __getattribute__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... def __delattr__(self, name: str) -> None: ... diff --git a/stdlib/_tkinter.pyi b/stdlib/_tkinter.pyi index b6c8ccd1c380..500345f91e06 100644 --- a/stdlib/_tkinter.pyi +++ b/stdlib/_tkinter.pyi @@ -1,6 +1,8 @@ import sys -from typing import Any -from typing_extensions import Literal, final +from _typeshed import FileDescriptorLike, Incomplete +from collections.abc import Callable +from typing import Any, ClassVar, Final, Literal, TypeAlias, final, overload +from typing_extensions import deprecated # _tkinter is meant to be only used internally by tkinter, but some tkinter # functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl @@ -17,11 +19,22 @@ from typing_extensions import Literal, final # (, ) @final class Tcl_Obj: - string: str # str(tclobj) returns this - typename: str + @property + def string(self) -> str: ... + @property + def typename(self) -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, value, /): ... + def __ge__(self, value, /): ... + def __gt__(self, value, /): ... + def __le__(self, value, /): ... + def __lt__(self, value, /): ... + def __ne__(self, value, /): ... class TclError(Exception): ... +_TkinterTraceFunc: TypeAlias = Callable[[tuple[str, ...]], object] + # This class allows running Tcl code. Tkinter uses it internally a lot, and # it's often handy to drop a piece of Tcl code into a tkinter program. Example: # @@ -42,58 +55,102 @@ class TclError(Exception): ... @final class TkappType: # Please keep in sync with tkinter.Tk - def call(self, __command: Any, *args: Any) -> Any: ... - def eval(self, __script: str) -> str: ... - adderrorinfo: Any - createcommand: Any - createfilehandler: Any - createtimerhandler: Any - deletecommand: Any - deletefilehandler: Any - dooneevent: Any - evalfile: Any - exprboolean: Any - exprdouble: Any - exprlong: Any - exprstring: Any - getboolean: Any - getdouble: Any - getint: Any - getvar: Any - globalgetvar: Any - globalsetvar: Any - globalunsetvar: Any - interpaddr: Any - loadtk: Any - mainloop: Any - quit: Any - record: Any - setvar: Any + def adderrorinfo(self, msg: str, /) -> None: ... + def call(self, command: Any, /, *args: Any) -> Any: ... + # TODO: Figure out what arguments the following `func` callbacks should accept + def createcommand(self, name: str, func: Callable[..., object], /) -> None: ... + if sys.platform != "win32": + def createfilehandler(self, file: FileDescriptorLike, mask: int, func: Callable[..., object], /) -> None: ... + def deletefilehandler(self, file: FileDescriptorLike, /) -> None: ... + + def createtimerhandler(self, milliseconds: int, func: Callable[..., object], /): ... + def deletecommand(self, name: str, /) -> None: ... + def dooneevent(self, flags: int = 0, /) -> int: ... + def eval(self, script: str, /) -> str: ... + def evalfile(self, fileName: str, /) -> str: ... + def exprboolean(self, s: str, /) -> Literal[0, 1]: ... + def exprdouble(self, s: str, /) -> float: ... + def exprlong(self, s: str, /) -> int: ... + def exprstring(self, s: str, /) -> str: ... + def getboolean(self, arg, /) -> bool: ... + def getdouble(self, arg, /) -> float: ... + def getint(self, arg, /) -> int: ... + def getvar(self, *args, **kwargs): ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self) -> int: ... + def loadtk(self) -> None: ... + def mainloop(self, threshold: int = 0, /) -> None: ... + def quit(self) -> None: ... + def record(self, script: str, /) -> str: ... + def setvar(self, *ags, **kwargs): ... if sys.version_info < (3, 11): - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any + @deprecated("Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.") + def split(self, arg, /): ... + + def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ... + def unsetvar(self, *args, **kwargs): ... + + if sys.version_info >= (3, 14): + @overload + def wantobjects(self) -> Literal[0, 1]: ... + else: + @overload + def wantobjects(self) -> bool: ... + + @overload + def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ... + + def willdispatch(self) -> None: ... + if sys.version_info >= (3, 12): + def gettrace(self, /) -> _TkinterTraceFunc | None: ... + def settrace(self, func: _TkinterTraceFunc | None, /) -> None: ... # These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS -ALL_EVENTS: Literal[-3] -FILE_EVENTS: Literal[8] -IDLE_EVENTS: Literal[32] -TIMER_EVENTS: Literal[16] -WINDOW_EVENTS: Literal[4] - -DONT_WAIT: Literal[2] -EXCEPTION: Literal[8] -READABLE: Literal[2] -WRITABLE: Literal[4] - -TCL_VERSION: str -TK_VERSION: str - -# TODO: figure out what these are (with e.g. help()) and get rid of Any -TkttType: Any -_flatten: Any -create: Any -getbusywaitinterval: Any -setbusywaitinterval: Any +ALL_EVENTS: Final = -3 +FILE_EVENTS: Final = 8 +IDLE_EVENTS: Final = 32 +TIMER_EVENTS: Final = 16 +WINDOW_EVENTS: Final = 4 + +DONT_WAIT: Final = 2 +EXCEPTION: Final = 8 +READABLE: Final = 2 +WRITABLE: Final = 4 + +TCL_VERSION: Final[str] +TK_VERSION: Final[str] + +@final +class TkttType: + def deletetimerhandler(self) -> None: ... + +if sys.version_info >= (3, 13): + def create( + screenName: str | None = None, + baseName: str = "", + className: str = "Tk", + interactive: bool = False, + wantobjects: int = 0, + wantTk: bool = True, + sync: bool = False, + use: str | None = None, + /, + ) -> TkappType: ... + +else: + def create( + screenName: str | None = None, + baseName: str = "", + className: str = "Tk", + interactive: bool = False, + wantobjects: bool = False, + wantTk: bool = True, + sync: bool = False, + use: str | None = None, + /, + ) -> TkappType: ... + +def getbusywaitinterval() -> int: ... +def setbusywaitinterval(new_val: int, /) -> None: ... diff --git a/stdlib/_tracemalloc.pyi b/stdlib/_tracemalloc.pyi index fd159dc586cb..e9720f46692c 100644 --- a/stdlib/_tracemalloc.pyi +++ b/stdlib/_tracemalloc.pyi @@ -1,17 +1,13 @@ -import sys -from tracemalloc import _FrameTupleT, _TraceTupleT -from typing import Sequence +from collections.abc import Sequence +from tracemalloc import _FrameTuple, _TraceTuple -def _get_object_traceback(__obj: object) -> Sequence[_FrameTupleT] | None: ... -def _get_traces() -> Sequence[_TraceTupleT]: ... +def _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: ... +def _get_traces() -> Sequence[_TraceTuple]: ... def clear_traces() -> None: ... def get_traceback_limit() -> int: ... def get_traced_memory() -> tuple[int, int]: ... def get_tracemalloc_memory() -> int: ... def is_tracing() -> bool: ... - -if sys.version_info >= (3, 9): - def reset_peak() -> None: ... - -def start(__nframe: int = ...) -> None: ... +def reset_peak() -> None: ... +def start(nframe: int = 1, /) -> None: ... def stop() -> None: ... diff --git a/stdlib/_typeshed/README.md b/stdlib/_typeshed/README.md index f4808944fa7b..3e4f3cb5cd48 100644 --- a/stdlib/_typeshed/README.md +++ b/stdlib/_typeshed/README.md @@ -1,6 +1,6 @@ # Utility types for typeshed -This package and its submodules contains various common types used by +This package and its submodules contain various common types used by typeshed. It can also be used by packages outside typeshed, but beware the API stability guarantees below. diff --git a/stdlib/_typeshed/__init__.pyi b/stdlib/_typeshed/__init__.pyi index a7f8c5147103..fa6ef8150e3a 100644 --- a/stdlib/_typeshed/__init__.pyi +++ b/stdlib/_typeshed/__init__.pyi @@ -2,13 +2,27 @@ # # See the README.md file in this directory for more information. -import array -import ctypes -import mmap import sys +from collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence, Set as AbstractSet, Sized +from dataclasses import Field from os import PathLike -from typing import AbstractSet, Any, Awaitable, ClassVar, Container, Generic, Iterable, Protocol, Type, TypeVar, Union -from typing_extensions import Literal, final +from types import FrameType, NoneType as NoneType, TracebackType +from typing import ( + Any, + AnyStr, + ClassVar, + Final, + Generic, + Literal, + Protocol, + SupportsFloat, + SupportsIndex, + SupportsInt, + TypeAlias, + TypeVar, + overload, +) +from typing_extensions import Buffer, LiteralString, Self as _Self _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -19,13 +33,55 @@ _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) -# Use for "self" annotations: -# def __enter__(self: Self) -> Self: ... -Self = TypeVar("Self") # noqa Y001 +# Alternative to `typing_extensions.Self`, exclusively for use with `__new__` +# in metaclasses: +# def __new__(cls: type[Self], ...) -> Self: ... +# In other cases, use `typing_extensions.Self`. +Self = TypeVar("Self") # noqa: Y001 + +# covariant version of typing.AnyStr, useful for protocols +AnyStr_co = TypeVar("AnyStr_co", str, bytes, covariant=True) # noqa: Y001 + +# For partially known annotations. Usually, fields where type annotations +# haven't been added are left unannotated, but in some situations this +# isn't possible or a type is already partially known. In cases like these, +# use Incomplete instead of Any as a marker. For example, use +# "Incomplete | None" instead of "Any | None". +Incomplete: TypeAlias = Any # stable + +# To describe a function parameter that is unused and will work with anything. +Unused: TypeAlias = object # stable + +# Marker for return types that include None, but where forcing the user to +# check for None can be detrimental. Sometimes called "the Any trick". See +# https://typing.python.org/en/latest/guides/writing_stubs.html#the-any-trick +# for more information. +MaybeNone: TypeAlias = Any # stable + +# typeshed-internal type aliases to facilitate transition from +# `float` to either `float | int` or `float` (and similar for `complex`). +# When you encounter one of these type aliases, you are encouraged to +# replace them with the correct type. Please don't use them outside typeshed. +# See https://github.com/python/typeshed/issues/16059 for details. +FloatInt: TypeAlias = float | int +ComplexInt: TypeAlias = complex | float | int + +# Used to mark arguments that default to a sentinel value. This prevents +# stubtest from complaining about the default value not matching. +# +# def foo(x: int | None = sentinel) -> None: ... +# +# In cases where the sentinel object is exported and can be used by user code, +# a construct like this is better: +# +# _SentinelType = NewType("_SentinelType", object) # does not exist at runtime +# sentinel: Final[_SentinelType] +# def foo(x: int | None | _SentinelType = ...) -> None: ... +sentinel: Any # stable # stable class IdentityFunction(Protocol): - def __call__(self, __x: _T) -> _T: ... + def __call__(self, x: _T, /) -> _T: ... # stable class SupportsNext(Protocol[_T_co]): @@ -35,41 +91,95 @@ class SupportsNext(Protocol[_T_co]): class SupportsAnext(Protocol[_T_co]): def __anext__(self) -> Awaitable[_T_co]: ... -# Comparison protocols +class SupportsBool(Protocol): + def __bool__(self) -> bool: ... -class SupportsDunderLT(Protocol): - def __lt__(self, __other: Any) -> Any: ... +# Comparison protocols +class SupportsDunderLT(Protocol[_T_contra]): + def __lt__(self, other: _T_contra, /) -> SupportsBool: ... -class SupportsDunderGT(Protocol): - def __gt__(self, __other: Any) -> Any: ... +class SupportsDunderGT(Protocol[_T_contra]): + def __gt__(self, other: _T_contra, /) -> SupportsBool: ... -class SupportsDunderLE(Protocol): - def __le__(self, __other: Any) -> Any: ... +class SupportsDunderLE(Protocol[_T_contra]): + def __le__(self, other: _T_contra, /) -> SupportsBool: ... -class SupportsDunderGE(Protocol): - def __ge__(self, __other: Any) -> Any: ... +class SupportsDunderGE(Protocol[_T_contra]): + def __ge__(self, other: _T_contra, /) -> SupportsBool: ... -class SupportsAllComparisons(SupportsDunderLT, SupportsDunderGT, SupportsDunderLE, SupportsDunderGE, Protocol): ... +class SupportsAllComparisons( + SupportsDunderLT[Any], SupportsDunderGT[Any], SupportsDunderLE[Any], SupportsDunderGE[Any], Protocol +): ... -SupportsRichComparison = Union[SupportsDunderLT, SupportsDunderGT] +SupportsRichComparison: TypeAlias = SupportsDunderLT[Any] | SupportsDunderGT[Any] SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichComparison) # noqa: Y001 -SupportsAnyComparison = Union[SupportsDunderLE, SupportsDunderGE, SupportsDunderGT, SupportsDunderLT] + +# Dunder protocols + +class SupportsAdd(Protocol[_T_contra, _T_co]): + def __add__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsRAdd(Protocol[_T_contra, _T_co]): + def __radd__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsSub(Protocol[_T_contra, _T_co]): + def __sub__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsRSub(Protocol[_T_contra, _T_co]): + def __rsub__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsMul(Protocol[_T_contra, _T_co]): + def __mul__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsRMul(Protocol[_T_contra, _T_co]): + def __rmul__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsMod(Protocol[_T_contra, _T_co]): + def __mod__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsRMod(Protocol[_T_contra, _T_co]): + def __rmod__(self, other: _T_contra, /) -> _T_co: ... class SupportsDivMod(Protocol[_T_contra, _T_co]): - def __divmod__(self, __other: _T_contra) -> _T_co: ... + def __divmod__(self, other: _T_contra, /) -> _T_co: ... class SupportsRDivMod(Protocol[_T_contra, _T_co]): - def __rdivmod__(self, __other: _T_contra) -> _T_co: ... + def __rdivmod__(self, other: _T_contra, /) -> _T_co: ... + +# This protocol is generic over the iterator type, while Iterable is +# generic over the type that is iterated over. +class SupportsIter(Protocol[_T_co]): + def __iter__(self) -> _T_co: ... + +# This protocol is generic over the iterator type, while AsyncIterable is +# generic over the type that is iterated over. +class SupportsAiter(Protocol[_T_co]): + def __aiter__(self) -> _T_co: ... + +class SupportsLen(Protocol): + def __len__(self) -> int: ... class SupportsLenAndGetItem(Protocol[_T_co]): def __len__(self) -> int: ... - def __getitem__(self, __k: int) -> _T_co: ... + def __getitem__(self, k: int, /) -> _T_co: ... class SupportsTrunc(Protocol): def __trunc__(self) -> int: ... # Mapping-like protocols +# The second and third overload could technically be combined, but splitting +# them works better with some type checkers. +class SupportsGet(Protocol[_KT_contra, _VT_co]): # type: ignore[misc] # ty:ignore[invalid-protocol] # Covariant type as parameter + @overload + def get(self, key: _KT_contra, /) -> _VT_co | None: ... + @overload + def get( # pyrefly: ignore[invalid-variance] + self, key: _KT_contra, default: _VT_co, / # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter + ) -> _VT_co: ... + @overload + def get(self, key: _KT_contra, default: _T, /) -> _VT_co | _T: ... + # stable class SupportsItems(Protocol[_KT_co, _VT_co]): def items(self) -> AbstractSet[tuple[_KT_co, _VT_co]]: ... @@ -77,23 +187,44 @@ class SupportsItems(Protocol[_KT_co, _VT_co]): # stable class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... - def __getitem__(self, __k: _KT) -> _VT_co: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + +class SupportsKeysAndGet(Protocol[_KT, _VT_co]): # type: ignore[misc] # ty:ignore[invalid-protocol] # Covariant type as parameter + def keys(self) -> Iterable[_KT]: ... + + @overload + def get(self, key: _KT, /) -> _VT_co | None: ... + @overload + def get( # pyrefly: ignore[invalid-variance] + self, key: _KT, default: _VT_co, / # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter + ) -> _VT_co: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT_co | _T: ... + +# stable +class SupportsGetItem(Protocol[_KT_contra, _VT_co]): + def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... # stable -class SupportsGetItem(Container[_KT_contra], Protocol[_KT_contra, _VT_co]): - def __getitem__(self, __k: _KT_contra) -> _VT_co: ... +class SupportsContainsAndGetItem(Protocol[_KT_contra, _VT_co]): + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... # stable -class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, _VT]): - def __setitem__(self, __k: _KT_contra, __v: _VT) -> None: ... - def __delitem__(self, __v: _KT_contra) -> None: ... +class SupportsItemAccess(Protocol[_KT_contra, _VT]): + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT: ... + def __setitem__(self, key: _KT_contra, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT_contra, /) -> None: ... + +# Path and file handling -# These aliases are simple strings in Python 2. -StrPath = Union[str, PathLike[str]] # stable -BytesPath = Union[bytes, PathLike[bytes]] # stable -StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable +StrPath: TypeAlias = str | PathLike[str] # stable +BytesPath: TypeAlias = bytes | PathLike[bytes] # stable +GenericPath: TypeAlias = AnyStr | PathLike[AnyStr] +StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] # stable -OpenTextModeUpdating = Literal[ +OpenTextModeUpdating: TypeAlias = Literal[ "r+", "+r", "rt+", @@ -127,10 +258,10 @@ OpenTextModeUpdating = Literal[ "t+x", "+tx", ] -OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] -OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] -OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] -OpenBinaryModeUpdating = Literal[ +OpenTextModeWriting: TypeAlias = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] +OpenTextModeReading: TypeAlias = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] +OpenTextMode: TypeAlias = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading +OpenBinaryModeUpdating: TypeAlias = Literal[ "rb+", "r+b", "+rb", @@ -156,24 +287,25 @@ OpenBinaryModeUpdating = Literal[ "b+x", "+bx", ] -OpenBinaryModeWriting = Literal["wb", "bw", "ab", "ba", "xb", "bx"] -OpenBinaryModeReading = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] -OpenBinaryMode = Union[OpenBinaryModeUpdating, OpenBinaryModeReading, OpenBinaryModeWriting] +OpenBinaryModeWriting: TypeAlias = Literal["wb", "bw", "ab", "ba", "xb", "bx"] +OpenBinaryModeReading: TypeAlias = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] +OpenBinaryMode: TypeAlias = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting # stable class HasFileno(Protocol): def fileno(self) -> int: ... -FileDescriptor = int # stable -FileDescriptorLike = Union[int, HasFileno] # stable +FileDescriptor: TypeAlias = int # stable +FileDescriptorLike: TypeAlias = int | HasFileno # stable +FileDescriptorOrPath: TypeAlias = int | StrOrBytesPath # stable class SupportsRead(Protocol[_T_co]): - def read(self, __length: int = ...) -> _T_co: ... + def read(self, length: int = ..., /) -> _T_co: ... # stable class SupportsReadline(Protocol[_T_co]): - def readline(self, __length: int = ...) -> _T_co: ... + def readline(self, length: int = ..., /) -> _T_co: ... # stable class SupportsNoArgReadline(Protocol[_T_co]): @@ -181,24 +313,50 @@ class SupportsNoArgReadline(Protocol[_T_co]): # stable class SupportsWrite(Protocol[_T_contra]): - def write(self, __s: _T_contra) -> Any: ... + def write(self, s: _T_contra, /) -> object: ... -ReadOnlyBuffer = bytes # stable +# stable +class SupportsFlush(Protocol): + def flush(self) -> object: ... + +# Suitable for dictionary view objects +class Viewable(Protocol[_T_co]): + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class SupportsGetItemViewable(Protocol[_KT, _VT_co]): + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_KT]: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + +# Unfortunately PEP 688 does not allow us to distinguish read-only +# from writable buffers. We use these aliases for readability for now. +# Perhaps a future extension of the buffer protocol will allow us to +# distinguish these cases in the type system. +ReadOnlyBuffer: TypeAlias = Buffer # stable # Anything that implements the read-write buffer interface. -# The buffer interface is defined purely on the C level, so we cannot define a normal Protocol -# for it. Instead we have to list the most common stdlib buffer classes in a Union. -WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, ctypes._CData] # stable -# Same as _WriteableBuffer, but also includes read-only buffer types (like bytes). -ReadableBuffer = Union[ReadOnlyBuffer, WriteableBuffer] # stable +WriteableBuffer: TypeAlias = Buffer +# Same as WriteableBuffer, but also includes read-only buffer types (like bytes). +ReadableBuffer: TypeAlias = Buffer # stable -# stable -if sys.version_info >= (3, 10): - from types import NoneType as NoneType -else: - # Used by type checkers for checks involving None (does not exist at runtime) - @final - class NoneType: - def __bool__(self) -> Literal[False]: ... +class SliceableBuffer(Buffer, Protocol): + def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ... + +class IndexableBuffer(Buffer, Protocol): + def __getitem__(self, i: int, /) -> int: ... + +class SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol): + def __contains__(self, x: Any, /) -> bool: ... + + @overload + def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ... + @overload + def __getitem__(self, i: int, /) -> int: ... + +class SizedBuffer(Sized, Buffer, Protocol): ... + +ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType] +OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None] # This is an internal CPython type that is like, but subtly different from, a NamedTuple # Subclasses of this type are found in multiple modules. @@ -206,13 +364,64 @@ else: # See discussion at #6546 & #6560 # `structseq` classes are unsubclassable, so are all decorated with `@final`. class structseq(Generic[_T_co]): - n_fields: ClassVar[int] - n_unnamed_fields: ClassVar[int] - n_sequence_fields: ClassVar[int] + n_fields: Final[int] + n_unnamed_fields: Final[int] + n_sequence_fields: Final[int] # The first parameter will generally only take an iterable of a specific length. # E.g. `os.uname_result` takes any iterable of length exactly 5. # # The second parameter will accept a dict of any kind without raising an exception, # but only has any meaning if you supply it a dict where the keys are strings. # https://github.com/python/typeshed/pull/6560#discussion_r767149830 - def __new__(cls: Type[_T], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _T: ... + def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _Self: ... + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> _Self: ... + +# Superset of typing.AnyStr that also includes LiteralString +AnyOrLiteralStr = TypeVar("AnyOrLiteralStr", str, bytes, LiteralString) # noqa: Y001 + +# Represents when str or LiteralStr is acceptable. Useful for string processing +# APIs where literalness of return value depends on literalness of inputs +StrOrLiteralStr = TypeVar("StrOrLiteralStr", LiteralString, str) # noqa: Y001 + +# Objects suitable to be passed to sys.setprofile, threading.setprofile, and similar +ProfileFunction: TypeAlias = Callable[[FrameType, Literal["call", "return", "c_call", "c_return", "c_exception"], Any], object] + +# Objects suitable to be passed to sys.settrace, threading.settrace, and similar +TraceFunction: TypeAlias = Callable[ + [FrameType, Literal["call", "line", "return", "exception", "opcode"], Any], TraceFunction | None +] + +# experimental +# Might not work as expected for pyright, see +# https://github.com/python/typeshed/pull/9362 +# https://github.com/microsoft/pyright/issues/4339 +class DataclassInstance(Protocol): + __dataclass_fields__: ClassVar[dict[str, Field[Any]]] + +# Anything that can be passed to the int/float constructors +if sys.version_info >= (3, 14): + ConvertibleToInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex +else: + ConvertibleToInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc +ConvertibleToFloat: TypeAlias = str | ReadableBuffer | SupportsFloat | SupportsIndex + +# A few classes updated from Foo(str, Enum) to Foo(StrEnum). This is a convenience so these +# can be accurate on all python versions without getting too wordy +if sys.version_info >= (3, 11): + from enum import StrEnum as StrEnum +else: + from enum import Enum + + class StrEnum(str, Enum): ... + +# Objects that appear in annotations or in type expressions. +# Similar to PEP 747's TypeForm but a little broader. +AnnotationForm: TypeAlias = Any + +if sys.version_info >= (3, 14): + from annotationlib import Format + + # These return annotations, which can be arbitrary objects + AnnotateFunc: TypeAlias = Callable[[Format], dict[str, AnnotationForm]] + EvaluateFunc: TypeAlias = Callable[[Format], AnnotationForm] diff --git a/stdlib/_typeshed/_type_checker_internals.pyi b/stdlib/_typeshed/_type_checker_internals.pyi new file mode 100644 index 000000000000..9dad80591006 --- /dev/null +++ b/stdlib/_typeshed/_type_checker_internals.pyi @@ -0,0 +1,102 @@ +# Internals used by some type checkers. +# +# Don't use this module directly. It is only for type checkers to use. + +import sys +import typing_extensions +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import AnnotationForm +from abc import ABCMeta +from collections.abc import Awaitable, Generator, Iterable, Mapping +from typing import Any, ClassVar, Generic, TypeVar, overload +from typing_extensions import Never + +_T = TypeVar("_T") + +# Used for an undocumented mypy feature. Does not exist at runtime. +promote = object() + +# Fallback type providing methods and attributes that appear on all `TypedDict` types. +# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict +class TypedDictFallback(Mapping[str, object], metaclass=ABCMeta): + __total__: ClassVar[bool] + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + # __orig_bases__ sometimes exists on <3.12, but not consistently, + # so we only add it to the stub on 3.12+ + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + if sys.version_info >= (3, 13): + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + if sys.version_info >= (3, 15): + # PEP 728 + __closed__: ClassVar[bool | None] + __extra_items__: ClassVar[AnnotationForm] + + def copy(self) -> typing_extensions.Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: Never, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: typing_extensions.Self, /) -> None: ... + def __delitem__(self, k: Never) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + + @overload + def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of __or__ and __ior__ + def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] + +# Fallback type providing methods and attributes that appear on all `NamedTuple` types. +class NamedTupleFallback(tuple[Any, ...]): + _field_defaults: ClassVar[dict[str, Any]] + _fields: ClassVar[tuple[str, ...]] + __match_args__: ClassVar[tuple[str, ...]] = ... + # __orig_bases__ sometimes exists on <3.12, but not consistently + # So we only add it to the stub on 3.12+. + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + + if sys.version_info >= (3, 15): + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... + else: + @overload + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... + @overload + @typing_extensions.deprecated( + "Creating a typing.NamedTuple using keyword arguments is deprecated; support removed in Python 3.15" + ) + def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... + + @classmethod + def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... + def _asdict(self) -> dict[str, Any]: ... + def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... + +# Non-default variations to accommodate couroutines, and `AwaitableGenerator` having a 4th type parameter. +_S = TypeVar("_S") +_YieldT_co = TypeVar("_YieldT_co", covariant=True) +_SendT_nd_contra = TypeVar("_SendT_nd_contra", contravariant=True) +_ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True) + +# The parameters correspond to Generator, but the 4th is the original type. +class AwaitableGenerator( + Awaitable[_ReturnT_nd_co], + Generator[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co], + Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co, _S], + metaclass=ABCMeta, +): ... diff --git a/stdlib/_typeshed/dbapi.pyi b/stdlib/_typeshed/dbapi.pyi index eee4fc03874e..e08a84553dfc 100644 --- a/stdlib/_typeshed/dbapi.pyi +++ b/stdlib/_typeshed/dbapi.pyi @@ -2,12 +2,12 @@ # https://www.python.org/dev/peps/pep-0249/ from collections.abc import Mapping, Sequence -from typing import Any, Protocol +from typing import Any, Protocol, TypeAlias -DBAPITypeCode = Any | None +DBAPITypeCode: TypeAlias = Any | None # Strictly speaking, this should be a Sequence, but the type system does # not support fixed-length sequences. -DBAPIColumnDescription = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None] +DBAPIColumnDescription: TypeAlias = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None] class DBAPIConnection(Protocol): def close(self) -> object: ... @@ -22,15 +22,15 @@ class DBAPICursor(Protocol): @property def rowcount(self) -> int: ... # optional: - # def callproc(self, __procname: str, __parameters: Sequence[Any] = ...) -> Sequence[Any]: ... + # def callproc(self, procname: str, parameters: Sequence[Any] = ..., /) -> Sequence[Any]: ... def close(self) -> object: ... - def execute(self, __operation: str, __parameters: Sequence[Any] | Mapping[str, Any] = ...) -> object: ... - def executemany(self, __operation: str, __seq_of_parameters: Sequence[Sequence[Any]]) -> object: ... + def execute(self, operation: str, parameters: Sequence[Any] | Mapping[str, Any] = ..., /) -> object: ... + def executemany(self, operation: str, seq_of_parameters: Sequence[Sequence[Any]], /) -> object: ... def fetchone(self) -> Sequence[Any] | None: ... - def fetchmany(self, __size: int = ...) -> Sequence[Sequence[Any]]: ... + def fetchmany(self, size: int = ..., /) -> Sequence[Sequence[Any]]: ... def fetchall(self) -> Sequence[Sequence[Any]]: ... # optional: # def nextset(self) -> None | Literal[True]: ... arraysize: int - def setinputsizes(self, __sizes: Sequence[DBAPITypeCode | int | None]) -> object: ... - def setoutputsize(self, __size: int, __column: int = ...) -> object: ... + def setinputsizes(self, sizes: Sequence[DBAPITypeCode | int | None], /) -> object: ... + def setoutputsize(self, size: int, column: int = ..., /) -> object: ... diff --git a/stdlib/_typeshed/importlib.pyi b/stdlib/_typeshed/importlib.pyi new file mode 100644 index 000000000000..a4e56cdaff62 --- /dev/null +++ b/stdlib/_typeshed/importlib.pyi @@ -0,0 +1,18 @@ +# Implicit protocols used in importlib. +# We intentionally omit deprecated and optional methods. + +from collections.abc import Sequence +from importlib.machinery import ModuleSpec +from types import ModuleType +from typing import Protocol + +__all__ = ["LoaderProtocol", "MetaPathFinderProtocol", "PathEntryFinderProtocol"] + +class LoaderProtocol(Protocol): + def load_module(self, fullname: str, /) -> ModuleType: ... + +class MetaPathFinderProtocol(Protocol): + def find_spec(self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = ..., /) -> ModuleSpec | None: ... + +class PathEntryFinderProtocol(Protocol): + def find_spec(self, fullname: str, target: ModuleType | None = ..., /) -> ModuleSpec | None: ... diff --git a/stdlib/_typeshed/wsgi.pyi b/stdlib/_typeshed/wsgi.pyi index 658b0fed2c6c..980a24122252 100644 --- a/stdlib/_typeshed/wsgi.pyi +++ b/stdlib/_typeshed/wsgi.pyi @@ -1,35 +1,43 @@ # Types to support PEP 3333 (WSGI) # +# Obsolete since Python 3.11: Use wsgiref.types instead. +# # See the README.md file in this directory for more information. -from sys import _OptExcInfo -from typing import Any, Callable, Dict, Iterable, Protocol +import sys +from _typeshed import OptExcInfo +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Protocol, TypeAlias -# stable -class StartResponse(Protocol): - def __call__( - self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ... - ) -> Callable[[bytes], Any]: ... +class _Readable(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + # Optional: def close(self) -> object: ... -WSGIEnvironment = Dict[str, Any] # stable -WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable +if sys.version_info >= (3, 11): + from wsgiref.types import * +else: + # stable + class StartResponse(Protocol): + def __call__( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., / + ) -> Callable[[bytes], object]: ... -# WSGI input streams per PEP 3333, stable -class InputStream(Protocol): - def read(self, size: int = ...) -> bytes: ... - def readline(self, size: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> list[bytes]: ... - def __iter__(self) -> Iterable[bytes]: ... + WSGIEnvironment: TypeAlias = dict[str, Any] # stable + WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable -# WSGI error streams per PEP 3333, stable -class ErrorStream(Protocol): - def flush(self) -> None: ... - def write(self, s: str) -> None: ... - def writelines(self, seq: list[str]) -> None: ... + # WSGI input streams per PEP 3333, stable + class InputStream(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + def readline(self, size: int = ..., /) -> bytes: ... + def readlines(self, hint: int = ..., /) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... -class _Readable(Protocol): - def read(self, size: int = ...) -> bytes: ... + # WSGI error streams per PEP 3333, stable + class ErrorStream(Protocol): + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... + def writelines(self, seq: list[str], /) -> object: ... -# Optional file wrapper in wsgi.file_wrapper -class FileWrapper(Protocol): - def __call__(self, file: _Readable, block_size: int = ...) -> Iterable[bytes]: ... + # Optional file wrapper in wsgi.file_wrapper + class FileWrapper(Protocol): + def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/stdlib/_typeshed/xml.pyi b/stdlib/_typeshed/xml.pyi index 231c2b86e912..6cd1b39af628 100644 --- a/stdlib/_typeshed/xml.pyi +++ b/stdlib/_typeshed/xml.pyi @@ -4,6 +4,6 @@ from typing import Any, Protocol # As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects class DOMImplementation(Protocol): - def hasFeature(self, feature: str, version: str | None) -> bool: ... - def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Any | None) -> Any: ... - def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str) -> Any: ... + def hasFeature(self, feature: str, version: str | None, /) -> bool: ... + def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Any | None, /) -> Any: ... + def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str, /) -> Any: ... diff --git a/stdlib/_warnings.pyi b/stdlib/_warnings.pyi index e5b180b14fea..5f4648259025 100644 --- a/stdlib/_warnings.pyi +++ b/stdlib/_warnings.pyi @@ -1,23 +1,45 @@ -from typing import Any, Type, overload +import sys +from typing import Any, overload _defaultaction: str _onceregistry: dict[Any, Any] -filters: list[tuple[str, str | None, Type[Warning], str | None, int]] +filters: list[tuple[str, str | None, type[Warning], str | None, int]] + +if sys.version_info >= (3, 12): + @overload + def warn( + message: str, + category: type[Warning] | None = None, + stacklevel: int = 1, + source: Any | None = None, + *, + skip_file_prefixes: tuple[str, ...] = (), + ) -> None: ... + @overload + def warn( + message: Warning, + category: Any = None, + stacklevel: int = 1, + source: Any | None = None, + *, + skip_file_prefixes: tuple[str, ...] = (), + ) -> None: ... +else: + @overload + def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: ... + @overload + def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ... -@overload -def warn(message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... -@overload -def warn(message: Warning, category: Any = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... @overload def warn_explicit( message: str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, module: str | None = ..., - registry: dict[str | tuple[str, Type[Warning], int], int] | None = ..., - module_globals: dict[str, Any] | None = ..., - source: Any | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = None, + module_globals: dict[str, Any] | None = None, + source: Any | None = None, ) -> None: ... @overload def warn_explicit( @@ -25,8 +47,8 @@ def warn_explicit( category: Any, filename: str, lineno: int, - module: str | None = ..., - registry: dict[str | tuple[str, Type[Warning], int], int] | None = ..., - module_globals: dict[str, Any] | None = ..., - source: Any | None = ..., + module: str | None = None, + registry: dict[str | tuple[str, type[Warning], int], int] | None = None, + module_globals: dict[str, Any] | None = None, + source: Any | None = None, ) -> None: ... diff --git a/stdlib/_weakref.pyi b/stdlib/_weakref.pyi index 00dc2d5114b8..a744340afaab 100644 --- a/stdlib/_weakref.pyi +++ b/stdlib/_weakref.pyi @@ -1,37 +1,15 @@ -import sys -from typing import Any, Callable, Generic, TypeVar, overload -from typing_extensions import final - -if sys.version_info >= (3, 9): - from types import GenericAlias +from collections.abc import Callable +from typing import Any, TypeVar, overload +from weakref import CallableProxyType as CallableProxyType, ProxyType as ProxyType, ReferenceType as ReferenceType, ref as ref _C = TypeVar("_C", bound=Callable[..., Any]) _T = TypeVar("_T") -@final -class CallableProxyType(Generic[_C]): # "weakcallableproxy" - def __getattr__(self, attr: str) -> Any: ... - __call__: _C - -@final -class ProxyType(Generic[_T]): # "weakproxy" - def __getattr__(self, attr: str) -> Any: ... - -class ReferenceType(Generic[_T]): - __callback__: Callable[[ReferenceType[_T]], Any] - def __init__(self, o: _T, callback: Callable[[ReferenceType[_T]], Any] | None = ...) -> None: ... - def __call__(self) -> _T | None: ... - def __hash__(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -ref = ReferenceType - -def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(object: Any) -> list[Any]: ... -@overload -def proxy(object: _C, callback: Callable[[_C], Any] | None = ...) -> CallableProxyType[_C]: ... +def getweakrefcount(object: Any, /) -> int: ... +def getweakrefs(object: Any, /) -> list[Any]: ... # Return CallableProxyType if object is callable, ProxyType otherwise @overload -def proxy(object: _T, callback: Callable[[_T], Any] | None = ...) -> Any: ... +def proxy(object: _C, callback: Callable[[_C], Any] | None = None, /) -> CallableProxyType[_C]: ... +@overload +def proxy(object: _T, callback: Callable[[_T], Any] | None = None, /) -> Any: ... diff --git a/stdlib/_weakrefset.pyi b/stdlib/_weakrefset.pyi index 1f0132f4c240..82ffa4463f48 100644 --- a/stdlib/_weakrefset.pyi +++ b/stdlib/_weakrefset.pyi @@ -1,34 +1,37 @@ -import sys -from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar +from collections.abc import Iterable, Iterator, MutableSet +from types import GenericAlias +from typing import Any, ClassVar, TypeVar, overload +from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["WeakSet"] _S = TypeVar("_S") _T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) -class WeakSet(MutableSet[_T], Generic[_T]): - def __init__(self, data: Iterable[_T] | None = ...) -> None: ... +class WeakSet(MutableSet[_T]): + @overload + def __init__(self, data: None = None) -> None: ... + @overload + def __init__(self, data: Iterable[_T]) -> None: ... + def add(self, item: _T) -> None: ... - def clear(self) -> None: ... def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... - def pop(self) -> _T: ... + def copy(self) -> Self: ... def remove(self, item: _T) -> None: ... def update(self, other: Iterable[_T]) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] def __contains__(self, item: object) -> bool: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __ior__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __ior__(self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] + def difference(self, other: Iterable[_T]) -> Self: ... + def __sub__(self, other: Iterable[Any]) -> Self: ... + def difference_update(self, other: Iterable[Any]) -> None: ... + def __isub__(self, other: Iterable[Any]) -> Self: ... + def intersection(self, other: Iterable[_T]) -> Self: ... + def __and__(self, other: Iterable[Any]) -> Self: ... + def intersection_update(self, other: Iterable[Any]) -> None: ... + def __iand__(self, other: Iterable[Any]) -> Self: ... def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... @@ -38,10 +41,9 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __eq__(self, other: object) -> bool: ... def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __xor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... - def __ixor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def symmetric_difference_update(self, other: Iterable[_T]) -> None: ... + def __ixor__(self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def isdisjoint(self, other: Iterable[_T]) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/_winapi.pyi b/stdlib/_winapi.pyi index 83089d485c17..3c520028e9c6 100644 --- a/stdlib/_winapi.pyi +++ b/stdlib/_winapi.pyi @@ -1,134 +1,319 @@ import sys -from typing import Any, NoReturn, Sequence, overload -from typing_extensions import Literal, final - -CREATE_NEW_CONSOLE: int -CREATE_NEW_PROCESS_GROUP: int -DUPLICATE_CLOSE_SOURCE: int -DUPLICATE_SAME_ACCESS: int -ERROR_ALREADY_EXISTS: int -ERROR_BROKEN_PIPE: int -ERROR_IO_PENDING: int -ERROR_MORE_DATA: int -ERROR_NETNAME_DELETED: int -ERROR_NO_DATA: int -ERROR_NO_SYSTEM_RESOURCES: int -ERROR_OPERATION_ABORTED: int -ERROR_PIPE_BUSY: int -ERROR_PIPE_CONNECTED: int -ERROR_SEM_TIMEOUT: int -FILE_FLAG_FIRST_PIPE_INSTANCE: int -FILE_FLAG_OVERLAPPED: int -FILE_GENERIC_READ: int -FILE_GENERIC_WRITE: int -GENERIC_READ: int -GENERIC_WRITE: int -INFINITE: int -NMPWAIT_WAIT_FOREVER: int -NULL: int -OPEN_EXISTING: int -PIPE_ACCESS_DUPLEX: int -PIPE_ACCESS_INBOUND: int -PIPE_READMODE_MESSAGE: int -PIPE_TYPE_MESSAGE: int -PIPE_UNLIMITED_INSTANCES: int -PIPE_WAIT: int -PROCESS_ALL_ACCESS: int -PROCESS_DUP_HANDLE: int -STARTF_USESHOWWINDOW: int -STARTF_USESTDHANDLES: int -STD_ERROR_HANDLE: int -STD_INPUT_HANDLE: int -STD_OUTPUT_HANDLE: int -STILL_ACTIVE: int -SW_HIDE: int -WAIT_ABANDONED_0: int -WAIT_OBJECT_0: int -WAIT_TIMEOUT: int - -def CloseHandle(__handle: int) -> None: ... -@overload -def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... -@overload -def ConnectNamedPipe(handle: int, overlapped: Literal[False] = ...) -> None: ... -@overload -def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... -def CreateFile( - __file_name: str, - __desired_access: int, - __share_mode: int, - __security_attributes: int, - __creation_disposition: int, - __flags_and_attributes: int, - __template_file: int, -) -> int: ... -def CreateJunction(__src_path: str, __dst_path: str) -> None: ... -def CreateNamedPipe( - __name: str, - __open_mode: int, - __pipe_mode: int, - __max_instances: int, - __out_buffer_size: int, - __in_buffer_size: int, - __default_timeout: int, - __security_attributes: int, -) -> int: ... -def CreatePipe(__pipe_attrs: Any, __size: int) -> tuple[int, int]: ... -def CreateProcess( - __application_name: str | None, - __command_line: str | None, - __proc_attrs: Any, - __thread_attrs: Any, - __inherit_handles: bool, - __creation_flags: int, - __env_mapping: dict[str, str], - __current_directory: str | None, - __startup_info: Any, -) -> tuple[int, int, int, int]: ... -def DuplicateHandle( - __source_process_handle: int, - __source_handle: int, - __target_process_handle: int, - __desired_access: int, - __inherit_handle: bool, - __options: int = ..., -) -> int: ... -def ExitProcess(__ExitCode: int) -> NoReturn: ... - -if sys.version_info >= (3, 7): +from _typeshed import ReadableBuffer +from collections.abc import Sequence +from typing import Any, Final, Literal, final, overload +from typing_extensions import Never + +if sys.platform == "win32": + ABOVE_NORMAL_PRIORITY_CLASS: Final = 0x8000 + BELOW_NORMAL_PRIORITY_CLASS: Final = 0x4000 + + CREATE_BREAKAWAY_FROM_JOB: Final = 0x1000000 + CREATE_DEFAULT_ERROR_MODE: Final = 0x4000000 + CREATE_NO_WINDOW: Final = 0x8000000 + CREATE_NEW_CONSOLE: Final = 0x10 + CREATE_NEW_PROCESS_GROUP: Final = 0x200 + + DETACHED_PROCESS: Final = 8 + DUPLICATE_CLOSE_SOURCE: Final = 1 + DUPLICATE_SAME_ACCESS: Final = 2 + + ERROR_ALREADY_EXISTS: Final = 183 + ERROR_BROKEN_PIPE: Final = 109 + ERROR_IO_PENDING: Final = 997 + ERROR_MORE_DATA: Final = 234 + ERROR_NETNAME_DELETED: Final = 64 + ERROR_NO_DATA: Final = 232 + ERROR_NO_SYSTEM_RESOURCES: Final = 1450 + ERROR_OPERATION_ABORTED: Final = 995 + ERROR_PIPE_BUSY: Final = 231 + ERROR_PIPE_CONNECTED: Final = 535 + ERROR_SEM_TIMEOUT: Final = 121 + + if sys.version_info >= (3, 15): + EVENTLOG_AUDIT_FAILURE: Final = 16 + EVENTLOG_AUDIT_SUCCESS: Final = 8 + EVENTLOG_ERROR_TYPE: Final = 1 + EVENTLOG_INFORMATION_TYPE: Final = 4 + EVENTLOG_SUCCESS: Final = 0 + EVENTLOG_WARNING_TYPE: Final = 2 + + FILE_FLAG_FIRST_PIPE_INSTANCE: Final = 0x80000 + FILE_FLAG_OVERLAPPED: Final = 0x40000000 + + FILE_GENERIC_READ: Final = 1179785 + FILE_GENERIC_WRITE: Final = 1179926 + + FILE_MAP_ALL_ACCESS: Final = 983071 + FILE_MAP_COPY: Final = 1 + FILE_MAP_EXECUTE: Final = 32 + FILE_MAP_READ: Final = 4 + FILE_MAP_WRITE: Final = 2 + + FILE_TYPE_CHAR: Final = 2 + FILE_TYPE_DISK: Final = 1 + FILE_TYPE_PIPE: Final = 3 + FILE_TYPE_REMOTE: Final = 32768 + FILE_TYPE_UNKNOWN: Final = 0 + + GENERIC_READ: Final = 0x80000000 + GENERIC_WRITE: Final = 0x40000000 + HIGH_PRIORITY_CLASS: Final = 0x80 + INFINITE: Final = 0xFFFFFFFF + # Ignore the Flake8 error -- flake8-pyi assumes + # most numbers this long will be implementation details, + # but here we can see that it's a power of 2 + INVALID_HANDLE_VALUE: Final = 0xFFFFFFFFFFFFFFFF # noqa: Y054 + IDLE_PRIORITY_CLASS: Final = 0x40 + NORMAL_PRIORITY_CLASS: Final = 0x20 + REALTIME_PRIORITY_CLASS: Final = 0x100 + NMPWAIT_WAIT_FOREVER: Final = 0xFFFFFFFF + + MEM_COMMIT: Final = 0x1000 + MEM_FREE: Final = 0x10000 + MEM_IMAGE: Final = 0x1000000 + MEM_MAPPED: Final = 0x40000 + MEM_PRIVATE: Final = 0x20000 + MEM_RESERVE: Final = 0x2000 + + NULL: Final = 0 + OPEN_EXISTING: Final = 3 + + PIPE_ACCESS_DUPLEX: Final = 3 + PIPE_ACCESS_INBOUND: Final = 1 + PIPE_READMODE_MESSAGE: Final = 2 + PIPE_TYPE_MESSAGE: Final = 4 + PIPE_UNLIMITED_INSTANCES: Final = 255 + PIPE_WAIT: Final = 0 + + PAGE_EXECUTE: Final = 0x10 + PAGE_EXECUTE_READ: Final = 0x20 + PAGE_EXECUTE_READWRITE: Final = 0x40 + PAGE_EXECUTE_WRITECOPY: Final = 0x80 + PAGE_GUARD: Final = 0x100 + PAGE_NOACCESS: Final = 0x1 + PAGE_NOCACHE: Final = 0x200 + PAGE_READONLY: Final = 0x2 + PAGE_READWRITE: Final = 0x4 + PAGE_WRITECOMBINE: Final = 0x400 + PAGE_WRITECOPY: Final = 0x8 + + PROCESS_ALL_ACCESS: Final = 0x1FFFFF + PROCESS_DUP_HANDLE: Final = 0x40 + + SEC_COMMIT: Final = 0x8000000 + SEC_IMAGE: Final = 0x1000000 + SEC_LARGE_PAGES: Final = 0x80000000 + SEC_NOCACHE: Final = 0x10000000 + SEC_RESERVE: Final = 0x4000000 + SEC_WRITECOMBINE: Final = 0x40000000 + + if sys.version_info >= (3, 13): + STARTF_FORCEOFFFEEDBACK: Final = 0x80 + STARTF_FORCEONFEEDBACK: Final = 0x40 + STARTF_PREVENTPINNING: Final = 0x2000 + STARTF_RUNFULLSCREEN: Final = 0x20 + STARTF_TITLEISAPPID: Final = 0x1000 + STARTF_TITLEISLINKNAME: Final = 0x800 + STARTF_UNTRUSTEDSOURCE: Final = 0x8000 + STARTF_USECOUNTCHARS: Final = 0x8 + STARTF_USEFILLATTRIBUTE: Final = 0x10 + STARTF_USEHOTKEY: Final = 0x200 + STARTF_USEPOSITION: Final = 0x4 + STARTF_USESIZE: Final = 0x2 + + STARTF_USESHOWWINDOW: Final = 0x1 + STARTF_USESTDHANDLES: Final = 0x100 + + STD_ERROR_HANDLE: Final = 0xFFFFFFF4 + STD_OUTPUT_HANDLE: Final = 0xFFFFFFF5 + STD_INPUT_HANDLE: Final = 0xFFFFFFF6 + + STILL_ACTIVE: Final = 259 + SW_HIDE: Final = 0 + SYNCHRONIZE: Final = 0x100000 + WAIT_ABANDONED_0: Final = 128 + WAIT_OBJECT_0: Final = 0 + WAIT_TIMEOUT: Final = 258 + + LOCALE_NAME_INVARIANT: Final[str] + LOCALE_NAME_MAX_LENGTH: Final[int] + LOCALE_NAME_SYSTEM_DEFAULT: Final[str] + LOCALE_NAME_USER_DEFAULT: Final[str | None] + + LCMAP_FULLWIDTH: Final[int] + LCMAP_HALFWIDTH: Final[int] + LCMAP_HIRAGANA: Final[int] + LCMAP_KATAKANA: Final[int] + LCMAP_LINGUISTIC_CASING: Final[int] + LCMAP_LOWERCASE: Final[int] + LCMAP_SIMPLIFIED_CHINESE: Final[int] + LCMAP_TITLECASE: Final[int] + LCMAP_TRADITIONAL_CHINESE: Final[int] + LCMAP_UPPERCASE: Final[int] + + if sys.version_info >= (3, 12): + COPYFILE2_CALLBACK_CHUNK_STARTED: Final = 1 + COPYFILE2_CALLBACK_CHUNK_FINISHED: Final = 2 + COPYFILE2_CALLBACK_STREAM_STARTED: Final = 3 + COPYFILE2_CALLBACK_STREAM_FINISHED: Final = 4 + COPYFILE2_CALLBACK_POLL_CONTINUE: Final = 5 + COPYFILE2_CALLBACK_ERROR: Final = 6 + + COPYFILE2_PROGRESS_CONTINUE: Final = 0 + COPYFILE2_PROGRESS_CANCEL: Final = 1 + COPYFILE2_PROGRESS_STOP: Final = 2 + COPYFILE2_PROGRESS_QUIET: Final = 3 + COPYFILE2_PROGRESS_PAUSE: Final = 4 + + COPY_FILE_FAIL_IF_EXISTS: Final = 0x1 + COPY_FILE_RESTARTABLE: Final = 0x2 + COPY_FILE_OPEN_SOURCE_FOR_WRITE: Final = 0x4 + COPY_FILE_ALLOW_DECRYPTED_DESTINATION: Final = 0x8 + COPY_FILE_COPY_SYMLINK: Final = 0x800 + COPY_FILE_NO_BUFFERING: Final = 0x1000 + COPY_FILE_REQUEST_SECURITY_PRIVILEGES: Final = 0x2000 + COPY_FILE_RESUME_FROM_PAUSE: Final = 0x4000 + COPY_FILE_NO_OFFLOAD: Final = 0x40000 + COPY_FILE_REQUEST_COMPRESSED_TRAFFIC: Final = 0x10000000 + + ERROR_ACCESS_DENIED: Final = 5 + ERROR_PRIVILEGE_NOT_HELD: Final = 1314 + + if sys.version_info >= (3, 14): + COPY_FILE_DIRECTORY: Final = 0x00000080 + + def CloseHandle(handle: int, /) -> None: ... + + @overload + def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: Literal[False] = False) -> None: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... + + def CreateFile( + file_name: str, + desired_access: int, + share_mode: int, + security_attributes: int, + creation_disposition: int, + flags_and_attributes: int, + template_file: int, + /, + ) -> int: ... + def CreateFileMapping( + file_handle: int, security_attributes: int, protect: int, max_size_high: int, max_size_low: int, name: str, / + ) -> int: ... + def CreateJunction(src_path: str, dst_path: str, /) -> None: ... + def CreateNamedPipe( + name: str, + open_mode: int, + pipe_mode: int, + max_instances: int, + out_buffer_size: int, + in_buffer_size: int, + default_timeout: int, + security_attributes: int, + /, + ) -> int: ... + def CreatePipe(pipe_attrs: Any, size: int, /) -> tuple[int, int]: ... + def CreateProcess( + application_name: str | None, + command_line: str | None, + proc_attrs: Any, + thread_attrs: Any, + inherit_handles: bool, + creation_flags: int, + env_mapping: dict[str, str], + current_directory: str | None, + startup_info: Any, + /, + ) -> tuple[int, int, int, int]: ... + def DuplicateHandle( + source_process_handle: int, + source_handle: int, + target_process_handle: int, + desired_access: int, + inherit_handle: bool, + options: int = 0, + /, + ) -> int: ... + def ExitProcess(ExitCode: int, /) -> Never: ... def GetACP() -> int: ... + if sys.version_info >= (3, 15): + def DeregisterEventSource(handle: int, /) -> None: ... + def GetOEMCP() -> int: ... + def GetFileType(handle: int) -> int: ... + def GetCurrentProcess() -> int: ... + def GetExitCodeProcess(process: int, /) -> int: ... + def GetLastError() -> int: ... + def GetModuleFileName(module_handle: int, /) -> str: ... + def GetStdHandle(std_handle: int, /) -> int: ... + def GetVersion() -> int: ... + def MapViewOfFile( + file_map: int, desired_access: int, file_offset_high: int, file_offset_low: int, number_bytes: int, / + ) -> int: ... + def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int, /) -> int: ... + def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ... + def LCMapStringEx(locale: str, flags: int, src: str) -> str: ... + if sys.version_info >= (3, 15): + def RegisterEventSource(unc_server_name: str | None, source_name: str, /) -> int: ... + def ReportEvent(handle: int, type: int, category: int, event_id: int, string: str, /) -> None: ... + + def UnmapViewOfFile(address: int, /) -> None: ... + + @overload + def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: Literal[False] = False) -> tuple[bytes, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... + + def SetNamedPipeHandleState( + named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, / + ) -> None: ... + def TerminateProcess(handle: int, exit_code: int, /) -> None: ... + def VirtualQuerySize(address: int, /) -> int: ... + def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = 0xFFFFFFFF, /) -> int: ... + def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: ... + def WaitNamedPipe(name: str, timeout: int, /) -> None: ... + + @overload + def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... + @overload + def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[False] = False) -> tuple[int, int]: ... + @overload + def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: int | bool) -> tuple[Any, int]: ... + + @final + class Overlapped: + event: int + def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ... + def cancel(self) -> None: ... + def getbuffer(self) -> bytes | None: ... + + if sys.version_info >= (3, 13): + def BatchedWaitForMultipleObjects( + handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF + ) -> list[int]: ... + def CreateEventW(security_attributes: int, manual_reset: bool, initial_state: bool, name: str | None) -> int: ... + def CreateMutexW(security_attributes: int, initial_owner: bool, name: str) -> int: ... + def GetLongPathName(path: str) -> str: ... + def GetShortPathName(path: str) -> str: ... + def OpenEventW(desired_access: int, inherit_handle: bool, name: str) -> int: ... + def OpenMutexW(desired_access: int, inherit_handle: bool, name: str) -> int: ... + def ReleaseMutex(mutex: int) -> None: ... + def ResetEvent(event: int) -> None: ... + def SetEvent(event: int) -> None: ... + + def OpenFileMapping(desired_access: int, inherit_handle: bool, name: str, /) -> int: ... + + if sys.version_info >= (3, 12): + def CopyFile2(existing_file_name: str, new_file_name: str, flags: int, progress_routine: int | None = None) -> int: ... + def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ... -def GetCurrentProcess() -> int: ... -def GetExitCodeProcess(__process: int) -> int: ... -def GetLastError() -> int: ... -def GetModuleFileName(__module_handle: int) -> str: ... -def GetStdHandle(__std_handle: int) -> int: ... -def GetVersion() -> int: ... -def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... -def PeekNamedPipe(__handle: int, __size: int = ...) -> tuple[int, int] | tuple[bytes, int, int]: ... -@overload -def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... -@overload -def ReadFile(handle: int, size: int, overlapped: Literal[False] = ...) -> tuple[bytes, int]: ... -@overload -def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... -def SetNamedPipeHandleState( - __named_pipe: int, __mode: int | None, __max_collection_count: int | None, __collect_data_timeout: int | None -) -> None: ... -def TerminateProcess(__handle: int, __exit_code: int) -> None: ... -def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = ...) -> int: ... -def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... -def WaitNamedPipe(__name: str, __timeout: int) -> None: ... -@overload -def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... -@overload -def WriteFile(handle: int, buffer: bytes, overlapped: Literal[False] = ...) -> tuple[int, int]: ... -@overload -def WriteFile(handle: int, buffer: bytes, overlapped: int | bool) -> tuple[Any, int]: ... -@final -class Overlapped: - event: int - def GetOverlappedResult(self, __wait: bool) -> tuple[int, int]: ... - def cancel(self) -> None: ... - def getbuffer(self) -> bytes | None: ... + if sys.version_info >= (3, 13): + # Added in Python 3.13.15, 3.14.7 + def GetTickCount64() -> int: ... diff --git a/stdlib/_zstd.pyi b/stdlib/_zstd.pyi new file mode 100644 index 000000000000..34b619f9b0b6 --- /dev/null +++ b/stdlib/_zstd.pyi @@ -0,0 +1,102 @@ +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from compression.zstd import CompressionParameter, DecompressionParameter +from typing import Final, Literal, TypeAlias, final +from typing_extensions import Self + +ZSTD_CLEVEL_DEFAULT: Final = 3 +ZSTD_DStreamOutSize: Final = 131072 +ZSTD_btlazy2: Final = 6 +ZSTD_btopt: Final = 7 +ZSTD_btultra: Final = 8 +ZSTD_btultra2: Final = 9 +ZSTD_c_chainLog: Final = 103 +ZSTD_c_checksumFlag: Final = 201 +ZSTD_c_compressionLevel: Final = 100 +ZSTD_c_contentSizeFlag: Final = 200 +ZSTD_c_dictIDFlag: Final = 202 +ZSTD_c_enableLongDistanceMatching: Final = 160 +ZSTD_c_hashLog: Final = 102 +ZSTD_c_jobSize: Final = 401 +ZSTD_c_ldmBucketSizeLog: Final = 163 +ZSTD_c_ldmHashLog: Final = 161 +ZSTD_c_ldmHashRateLog: Final = 164 +ZSTD_c_ldmMinMatch: Final = 162 +ZSTD_c_minMatch: Final = 105 +ZSTD_c_nbWorkers: Final = 400 +ZSTD_c_overlapLog: Final = 402 +ZSTD_c_searchLog: Final = 104 +ZSTD_c_strategy: Final = 107 +ZSTD_c_targetLength: Final = 106 +ZSTD_c_windowLog: Final = 101 +ZSTD_d_windowLogMax: Final = 100 +ZSTD_dfast: Final = 2 +ZSTD_fast: Final = 1 +ZSTD_greedy: Final = 3 +ZSTD_lazy: Final = 4 +ZSTD_lazy2: Final = 5 + +_ZstdCompressorContinue: TypeAlias = Literal[0] +_ZstdCompressorFlushBlock: TypeAlias = Literal[1] +_ZstdCompressorFlushFrame: TypeAlias = Literal[2] + +@final +class ZstdCompressor: + CONTINUE: Final = 0 + FLUSH_BLOCK: Final = 1 + FLUSH_FRAME: Final = 2 + def __new__( + cls, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + def compress( + self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0 + ) -> bytes: ... + def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: ... + def set_pledged_input_size(self, size: int | None, /) -> None: ... + @property + def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: ... + +@final +class ZstdDecompressor: + def __new__( + cls, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None + ) -> Self: ... + def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes: ... + @property + def eof(self) -> bool: ... + @property + def needs_input(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... + +@final +class ZstdDict: + def __new__(cls, dict_content: ReadableBuffer, /, *, is_raw: bool = False) -> Self: ... + def __len__(self, /) -> int: ... + @property + def as_digested_dict(self) -> tuple[Self, int]: ... + @property + def as_prefix(self) -> tuple[Self, int]: ... + @property + def as_undigested_dict(self) -> tuple[Self, int]: ... + @property + def dict_content(self) -> bytes: ... + @property + def dict_id(self) -> int: ... + +class ZstdError(Exception): ... + +def finalize_dict( + custom_dict_bytes: bytes, samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, compression_level: int, / +) -> bytes: ... +def get_frame_info(frame_buffer: ReadableBuffer) -> tuple[int, int]: ... +def get_frame_size(frame_buffer: ReadableBuffer) -> int: ... +def get_param_bounds(parameter: int, is_compress: bool) -> tuple[int, int]: ... +def set_parameter_types(c_parameter_type: type[CompressionParameter], d_parameter_type: type[DecompressionParameter]) -> None: ... +def train_dict(samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, /) -> bytes: ... + +zstd_version: Final[str] +zstd_version_number: Final[int] diff --git a/stdlib/abc.pyi b/stdlib/abc.pyi index c9dbda103ef3..a43a641489a4 100644 --- a/stdlib/abc.pyi +++ b/stdlib/abc.pyi @@ -1,30 +1,50 @@ +import _typeshed import sys from _typeshed import SupportsWrite -from typing import Any, Callable, Tuple, Type, TypeVar +from collections.abc import Callable +from typing import Any, Concatenate, Literal, ParamSpec, TypeVar +from typing_extensions import deprecated _T = TypeVar("_T") +_R_co = TypeVar("_R_co", covariant=True) _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) +_P = ParamSpec("_P") # These definitions have special processing in mypy class ABCMeta(type): __abstractmethods__: frozenset[str] - def __init__(self, name: str, bases: Tuple[type, ...], namespace: dict[str, Any]) -> None: ... - def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... - def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... - def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = ...) -> None: ... - def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... + if sys.version_info >= (3, 11): + def __new__( + mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwargs: Any + ) -> _typeshed.Self: ... + else: + def __new__( + mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any + ) -> _typeshed.Self: ... + + def __instancecheck__(cls: ABCMeta, instance: Any, /) -> bool: ... + def __subclasscheck__(cls: ABCMeta, subclass: type, /) -> bool: ... + def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = None) -> None: ... + def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ... def abstractmethod(funcobj: _FuncT) -> _FuncT: ... -class abstractproperty(property): ... +@deprecated("Deprecated since Python 3.3. Use `@classmethod` stacked on top of `@abstractmethod` instead.") +class abstractclassmethod(classmethod[_T, _P, _R_co]): + __isabstractmethod__: Literal[True] + def __init__(self, callable: Callable[Concatenate[type[_T], _P], _R_co]) -> None: ... -# These two are deprecated and not supported by mypy -def abstractstaticmethod(callable: _FuncT) -> _FuncT: ... -def abstractclassmethod(callable: _FuncT) -> _FuncT: ... +@deprecated("Deprecated since Python 3.3. Use `@staticmethod` stacked on top of `@abstractmethod` instead.") +class abstractstaticmethod(staticmethod[_P, _R_co]): + __isabstractmethod__: Literal[True] + def __init__(self, callable: Callable[_P, _R_co]) -> None: ... -class ABC(metaclass=ABCMeta): ... +@deprecated("Deprecated since Python 3.3. Use `@property` stacked on top of `@abstractmethod` instead.") +class abstractproperty(property): + __isabstractmethod__: Literal[True] -def get_cache_token() -> object: ... +class ABC(metaclass=ABCMeta): + __slots__ = () -if sys.version_info >= (3, 10): - def update_abstractmethods(cls: Type[_T]) -> Type[_T]: ... +def get_cache_token() -> object: ... +def update_abstractmethods(cls: type[_T]) -> type[_T]: ... diff --git a/stdlib/aifc.pyi b/stdlib/aifc.pyi index 79f470a366bb..afb9029f710e 100644 --- a/stdlib/aifc.pyi +++ b/stdlib/aifc.pyi @@ -1,8 +1,8 @@ -import sys -from _typeshed import Self from types import TracebackType -from typing import IO, Any, NamedTuple, Tuple, Type, Union, overload -from typing_extensions import Literal +from typing import IO, Any, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Self + +__all__ = ["Error", "open"] class Error(Exception): ... @@ -14,14 +14,14 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = Union[str, IO[bytes]] -_Marker = Tuple[int, int, bytes] +_File: TypeAlias = str | IO[bytes] +_Marker: TypeAlias = tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def initfp(self, file: IO[bytes]) -> None: ... def getfp(self) -> IO[bytes]: ... @@ -43,9 +43,9 @@ class Aifc_read: class Aifc_write: def __init__(self, f: _File) -> None: ... def __del__(self) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def initfp(self, file: IO[bytes]) -> None: ... def aiff(self) -> None: ... @@ -76,12 +76,4 @@ def open(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... @overload def open(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... @overload -def open(f: _File, mode: str | None = ...) -> Any: ... - -if sys.version_info < (3, 9): - @overload - def openfp(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... - @overload - def openfp(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... - @overload - def openfp(f: _File, mode: str | None = ...) -> Any: ... +def open(f: _File, mode: str | None = None) -> Any: ... diff --git a/stdlib/annotationlib.pyi b/stdlib/annotationlib.pyi new file mode 100644 index 000000000000..c3e843d95d9a --- /dev/null +++ b/stdlib/annotationlib.pyi @@ -0,0 +1,156 @@ +import sys +from typing import Literal + +if sys.version_info >= (3, 14): + import enum + import types + from _typeshed import AnnotateFunc, AnnotationForm, EvaluateFunc, SupportsItems + from collections.abc import Mapping + from typing import Any, ParamSpec, TypeVar, TypeVarTuple, final, overload + from warnings import deprecated + + __all__ = [ + "Format", + "ForwardRef", + "call_annotate_function", + "call_evaluate_function", + "get_annotate_from_class_namespace", + "get_annotations", + "annotations_to_string", + "type_repr", + ] + + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + @final + class ForwardRef: + __slots__ = ( + "__forward_is_argument__", + "__forward_is_class__", + "__forward_module__", + "__weakref__", + "__arg__", + "__globals__", + "__extra_names__", + "__code__", + "__ast_node__", + "__cell__", + "__owner__", + "__stringifier_dict__", + "__resolved_str_cache__", + ) + __forward_is_argument__: bool + __forward_is_class__: bool + __forward_module__: str | None + __resolved_str_cache__: str | None + def __init__( + self, arg: str, *, module: str | None = None, owner: object = None, is_argument: bool = True, is_class: bool = False + ) -> None: ... + + @overload + def evaluate( + self, + *, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + owner: object = None, + format: Literal[Format.STRING], + ) -> str: ... + @overload + def evaluate( + self, + *, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + owner: object = None, + format: Literal[Format.FORWARDREF], + ) -> AnnotationForm | ForwardRef: ... + @overload + def evaluate( + self, + *, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + owner: object = None, + format: Format = Format.VALUE, # noqa: Y011 + ) -> AnnotationForm: ... + + @deprecated("Use `ForwardRef.evaluate()` or `typing.evaluate_forward_ref()` instead.") + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: Mapping[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ..., + *, + recursive_guard: frozenset[str], + ) -> AnnotationForm: ... + @property + def __forward_arg__(self) -> str: ... + @property + def __forward_code__(self) -> types.CodeType: ... + @property + def __resolved_str__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __or__(self, other: Any) -> types.UnionType: ... + def __ror__(self, other: Any) -> types.UnionType: ... + + @overload + def call_evaluate_function(evaluate: EvaluateFunc, format: Literal[Format.STRING], *, owner: object = None) -> str: ... + @overload + def call_evaluate_function( + evaluate: EvaluateFunc, format: Literal[Format.FORWARDREF], *, owner: object = None + ) -> AnnotationForm | ForwardRef: ... + @overload + def call_evaluate_function(evaluate: EvaluateFunc, format: Format, *, owner: object = None) -> AnnotationForm: ... + + @overload + def call_annotate_function( + annotate: AnnotateFunc, format: Literal[Format.STRING], *, owner: object = None + ) -> dict[str, str]: ... + @overload + def call_annotate_function( + annotate: AnnotateFunc, format: Literal[Format.FORWARDREF], *, owner: object = None + ) -> dict[str, AnnotationForm | ForwardRef]: ... + @overload + def call_annotate_function(annotate: AnnotateFunc, format: Format, *, owner: object = None) -> dict[str, AnnotationForm]: ... + + def get_annotate_from_class_namespace(obj: Mapping[str, object]) -> AnnotateFunc | None: ... + + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: dict[str, object] | None = None, + locals: Mapping[str, object] | None = None, + eval_str: bool = False, + format: Literal[Format.STRING], + ) -> dict[str, str]: ... + @overload + def get_annotations( + obj: Any, + *, + globals: dict[str, object] | None = None, + locals: Mapping[str, object] | None = None, + eval_str: bool = False, + format: Literal[Format.FORWARDREF], + ) -> dict[str, AnnotationForm | ForwardRef]: ... + @overload + def get_annotations( + obj: Any, + *, + globals: dict[str, object] | None = None, + locals: Mapping[str, object] | None = None, + eval_str: bool = False, + format: Format = Format.VALUE, # noqa: Y011 + ) -> dict[str, AnnotationForm]: ... + + def type_repr(value: object) -> str: ... + def annotations_to_string(annotations: SupportsItems[str, object]) -> dict[str, str]: ... diff --git a/stdlib/antigravity.pyi b/stdlib/antigravity.pyi index e30917511030..3986e7d1c9f2 100644 --- a/stdlib/antigravity.pyi +++ b/stdlib/antigravity.pyi @@ -1 +1,3 @@ -def geohash(latitude: float, longitude: float, datedow: bytes) -> None: ... +from _typeshed import ReadableBuffer + +def geohash(latitude: float, longitude: float, datedow: ReadableBuffer) -> None: ... diff --git a/stdlib/argparse.pyi b/stdlib/argparse.pyi index 8e252ddc75c6..da8141e235e0 100644 --- a/stdlib/argparse.pyi +++ b/stdlib/argparse.pyi @@ -1,33 +1,44 @@ import sys -from typing import ( - IO, - Any, - Callable, - Generator, - Generic, - Iterable, - NoReturn, - Pattern, - Protocol, - Sequence, - Tuple, - Type, - TypeVar, - overload, -) +from _typeshed import SupportsWrite, sentinel +from collections.abc import Callable, Generator, Iterable, Sequence +from re import Pattern +from typing import IO, Any, ClassVar, Final, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, deprecated + +__all__ = [ + "ArgumentParser", + "ArgumentError", + "ArgumentTypeError", + "FileType", + "HelpFormatter", + "ArgumentDefaultsHelpFormatter", + "RawDescriptionHelpFormatter", + "RawTextHelpFormatter", + "MetavarTypeHelpFormatter", + "Namespace", + "Action", + "BooleanOptionalAction", + "ONE_OR_MORE", + "OPTIONAL", + "PARSER", + "REMAINDER", + "SUPPRESS", + "ZERO_OR_MORE", +] _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser) _N = TypeVar("_N") +_ActionType: TypeAlias = Callable[[str], Any] | FileType | str -ONE_OR_MORE: str -OPTIONAL: str -PARSER: str -REMAINDER: str -SUPPRESS: str -ZERO_OR_MORE: str -_UNRECOGNIZED_ARGS_ATTR: str # undocumented +ONE_OR_MORE: Final = "+" +OPTIONAL: Final = "?" +PARSER: Final = "A..." +REMAINDER: Final = "..." +SUPPRESS: Final = "==SUPPRESS==" +ZERO_OR_MORE: Final = "*" +_UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented class ArgumentError(Exception): argument_name: str | None @@ -56,40 +67,68 @@ class _ActionsContainer: _has_negative_number_optionals: list[bool] def __init__(self, description: str | None, prefix_chars: str, argument_default: Any, conflict_handler: str) -> None: ... def register(self, registry_name: str, value: Any, object: Any) -> None: ... - def _registry_get(self, registry_name: str, value: Any, default: Any = ...) -> Any: ... + def _registry_get(self, registry_name: str, value: Any, default: Any = None) -> Any: ... def set_defaults(self, **kwargs: Any) -> None: ... def get_default(self, dest: str) -> Any: ... def add_argument( self, *name_or_flags: str, - action: str | Type[Action] = ..., - nargs: int | str = ..., + # str covers predefined actions ("store_true", "count", etc.) + # and user registered actions via the `register` method. + action: str | type[Action] = ..., + # more precisely, Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="], + # but using this would make it hard to annotate callers that don't use a + # literal argument and for subclasses to override this method. + nargs: int | str | None = None, const: Any = ..., default: Any = ..., - type: Callable[[str], _T] | FileType = ..., - choices: Iterable[_T] | None = ..., + type: _ActionType = ..., + choices: Iterable[Any] | None = ..., # choices must match the type specified required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., dest: str | None = ..., version: str = ..., **kwargs: Any, ) -> Action: ... - def add_argument_group(self, *args: Any, **kwargs: Any) -> _ArgumentGroup: ... - def add_mutually_exclusive_group(self, **kwargs: Any) -> _MutuallyExclusiveGroup: ... + + @overload + def add_argument_group( + self, + title: str | None = None, + description: str | None = None, + *, + # argument_default's type must be valid for the arguments in the group + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> _ArgumentGroup: ... + @overload + @deprecated("The `prefix_chars` parameter is deprecated.") + def add_argument_group( + self, + title: str | None = None, + description: str | None = None, + *, + prefix_chars: str, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> _ArgumentGroup: ... + + def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ... def _add_action(self, action: _ActionT) -> _ActionT: ... def _remove_action(self, action: Action) -> None: ... def _add_container_actions(self, container: _ActionsContainer) -> None: ... def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ... def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ... - def _pop_action_class(self, kwargs: Any, default: Type[Action] | None = ...) -> Type[Action]: ... + def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]: ... def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ... def _check_conflict(self, action: Action) -> None: ... - def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> Never: ... def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ... +@type_check_only class _FormatterClass(Protocol): - def __call__(self, prog: str) -> HelpFormatter: ... + def __call__(self, *, prog: str) -> HelpFormatter: ... class ArgumentParser(_AttributeHolder, _ActionsContainer): prog: str @@ -99,145 +138,180 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): fromfile_prefix_chars: str | None add_help: bool allow_abbrev: bool + exit_on_error: bool + + if sys.version_info >= (3, 14): + suggest_on_error: bool + color: bool # undocumented _positionals: _ArgumentGroup _optionals: _ArgumentGroup _subparsers: _ArgumentGroup | None - if sys.version_info >= (3, 9): + # Note: the constructor arguments are also used in _SubParsersAction.add_parser. + if sys.version_info >= (3, 15): def __init__( self, - prog: str | None = ..., - usage: str | None = ..., - description: str | None = ..., - epilog: str | None = ..., - parents: Sequence[ArgumentParser] = ..., + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], formatter_class: _FormatterClass = ..., - prefix_chars: str = ..., - fromfile_prefix_chars: str | None = ..., - argument_default: Any = ..., - conflict_handler: str = ..., - add_help: bool = ..., - allow_abbrev: bool = ..., - exit_on_error: bool = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + *, + suggest_on_error: bool = True, + color: bool = True, + ) -> None: ... + + elif sys.version_info >= (3, 14): + def __init__( + self, + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], + formatter_class: _FormatterClass = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + *, + suggest_on_error: bool = False, + color: bool = True, ) -> None: ... else: def __init__( self, - prog: str | None = ..., - usage: str | None = ..., - description: str | None = ..., - epilog: str | None = ..., - parents: Sequence[ArgumentParser] = ..., + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], formatter_class: _FormatterClass = ..., - prefix_chars: str = ..., - fromfile_prefix_chars: str | None = ..., - argument_default: Any = ..., - conflict_handler: str = ..., - add_help: bool = ..., - allow_abbrev: bool = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, ) -> None: ... - # The type-ignores in these overloads should be temporary. See: - # https://github.com/python/typeshed/pull/2643#issuecomment-442280277 + @overload - def parse_args(self, args: Sequence[str] | None = ...) -> Namespace: ... + def parse_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... @overload - def parse_args(self, args: Sequence[str] | None, namespace: None) -> Namespace: ... # type: ignore[misc] + def parse_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... @overload - def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ... + def parse_args(self, *, namespace: _N) -> _N: ... + @overload - def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore[misc] + def add_subparsers( + self: _ArgumentParserT, + *, + title: str = "subcommands", + description: str | None = None, + prog: str | None = None, + action: str | type[Action] = ..., + option_string: str = ..., + dest: str | None = None, + required: bool = False, + help: str | None = None, + metavar: str | None = None, + ) -> _SubParsersAction[_ArgumentParserT]: ... @overload - def parse_args(self, *, namespace: _N) -> _N: ... - if sys.version_info >= (3, 7): - @overload - def add_subparsers( - self: _ArgumentParserT, - *, - title: str = ..., - description: str | None = ..., - prog: str = ..., - action: Type[Action] = ..., - option_string: str = ..., - dest: str | None = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | None = ..., - ) -> _SubParsersAction[_ArgumentParserT]: ... - @overload - def add_subparsers( - self, - *, - title: str = ..., - description: str | None = ..., - prog: str = ..., - parser_class: Type[_ArgumentParserT] = ..., - action: Type[Action] = ..., - option_string: str = ..., - dest: str | None = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | None = ..., - ) -> _SubParsersAction[_ArgumentParserT]: ... + def add_subparsers( + self, + *, + title: str = "subcommands", + description: str | None = None, + prog: str | None = None, + parser_class: type[_ArgumentParserT], + action: str | type[Action] = ..., + option_string: str = ..., + dest: str | None = None, + required: bool = False, + help: str | None = None, + metavar: str | None = None, + ) -> _SubParsersAction[_ArgumentParserT]: ... + + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ... + def print_help(self, file: SupportsWrite[str] | None = None) -> None: ... + if sys.version_info >= (3, 15): + def format_usage(self, formatter: HelpFormatter | None = None) -> str: ... + def format_help(self, formatter: HelpFormatter | None = None) -> str: ... + else: - @overload - def add_subparsers( - self: _ArgumentParserT, - *, - title: str = ..., - description: str | None = ..., - prog: str = ..., - action: Type[Action] = ..., - option_string: str = ..., - dest: str | None = ..., - help: str | None = ..., - metavar: str | None = ..., - ) -> _SubParsersAction[_ArgumentParserT]: ... - @overload - def add_subparsers( - self, - *, - title: str = ..., - description: str | None = ..., - prog: str = ..., - parser_class: Type[_ArgumentParserT] = ..., - action: Type[Action] = ..., - option_string: str = ..., - dest: str | None = ..., - help: str | None = ..., - metavar: str | None = ..., - ) -> _SubParsersAction[_ArgumentParserT]: ... - def print_usage(self, file: IO[str] | None = ...) -> None: ... - def print_help(self, file: IO[str] | None = ...) -> None: ... - def format_usage(self) -> str: ... - def format_help(self) -> str: ... - def parse_known_args( - self, args: Sequence[str] | None = ..., namespace: Namespace | None = ... - ) -> tuple[Namespace, list[str]]: ... + def format_usage(self) -> str: ... + def format_help(self) -> str: ... + + @overload + def parse_known_args(self, args: Iterable[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ... + @overload + def parse_known_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... + @overload + def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... + def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ... - def exit(self, status: int = ..., message: str | None = ...) -> NoReturn: ... - def error(self, message: str) -> NoReturn: ... - if sys.version_info >= (3, 7): - def parse_intermixed_args(self, args: Sequence[str] | None = ..., namespace: Namespace | None = ...) -> Namespace: ... - def parse_known_intermixed_args( - self, args: Sequence[str] | None = ..., namespace: Namespace | None = ... - ) -> tuple[Namespace, list[str]]: ... + def exit(self, status: int = 0, message: str | None = None) -> Never: ... + def error(self, message: str) -> Never: ... + + @overload + def parse_intermixed_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... + @overload + def parse_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... + @overload + def parse_intermixed_args(self, *, namespace: _N) -> _N: ... + + @overload + def parse_known_intermixed_args( + self, args: Iterable[str] | None = None, namespace: None = None + ) -> tuple[Namespace, list[str]]: ... + @overload + def parse_known_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... + @overload + def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... + # undocumented def _get_optional_actions(self) -> list[Action]: ... def _get_positional_actions(self) -> list[Action]: ... - def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]: ... + if sys.version_info >= (3, 12): + def _parse_known_args( + self, arg_strings: list[str], namespace: Namespace, intermixed: bool + ) -> tuple[Namespace, list[str]]: ... + else: + def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]: ... + def _read_args_from_files(self, arg_strings: list[str]) -> list[str]: ... def _match_argument(self, action: Action, arg_strings_pattern: str) -> int: ... def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> list[int]: ... - def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ... + if sys.version_info >= (3, 12): + def _parse_optional(self, arg_string: str) -> list[tuple[Action | None, str, str | None, str | None]] | None: ... + else: + def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ... + def _get_option_tuples(self, option_string: str) -> list[tuple[Action, str, str | None]]: ... def _get_nargs_pattern(self, action: Action) -> str: ... def _get_values(self, action: Action, arg_strings: list[str]) -> Any: ... def _get_value(self, action: Action, arg_string: str) -> Any: ... def _check_value(self, action: Action, value: Any) -> None: ... - def _get_formatter(self) -> HelpFormatter: ... - def _print_message(self, message: str, file: IO[str] | None = ...) -> None: ... + if sys.version_info >= (3, 15): + def _get_formatter(self, file: SupportsWrite[str] | None = None) -> HelpFormatter: ... + else: + def _get_formatter(self) -> HelpFormatter: ... + + def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ... class HelpFormatter: # undocumented @@ -248,12 +322,33 @@ class HelpFormatter: _current_indent: int _level: int _action_max_length: int - _root_section: Any - _current_section: Any + _root_section: _Section # pyrefly: ignore [unknown-name] + _current_section: _Section # pyrefly: ignore [unknown-name] _whitespace_matcher: Pattern[str] _long_break_matcher: Pattern[str] - _Section: Type[Any] # Nested class - def __init__(self, prog: str, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ...) -> None: ... + + class _Section: + formatter: HelpFormatter + heading: str | None + parent: Self | None + items: list[tuple[Callable[..., str], Iterable[Any]]] + def __init__(self, formatter: HelpFormatter, parent: Self | None, heading: str | None = None) -> None: ... + def format_help(self) -> str: ... + + if sys.version_info >= (3, 15): + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None + ) -> None: ... + + elif sys.version_info >= (3, 14): + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = True + ) -> None: ... + else: + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None + ) -> None: ... + def _indent(self) -> None: ... def _dedent(self) -> None: ... def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None: ... @@ -261,23 +356,26 @@ class HelpFormatter: def end_section(self) -> None: ... def add_text(self, text: str | None) -> None: ... def add_usage( - self, usage: str | None, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: str | None = ... + self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None ) -> None: ... def add_argument(self, action: Action) -> None: ... def add_arguments(self, actions: Iterable[Action]) -> None: ... def format_help(self) -> str: ... def _join_parts(self, part_strings: Iterable[str]) -> str: ... def _format_usage( - self, usage: str, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: str | None + self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None ) -> str: ... - def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> str: ... + if sys.version_info < (3, 14): + # Removed in Python 3.14.3 + def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ... + def _format_text(self, text: str) -> str: ... def _format_action(self, action: Action) -> str: ... def _format_action_invocation(self, action: Action) -> str: ... - def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], Tuple[str, ...]]: ... + def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ... def _format_args(self, action: Action, default_metavar: str) -> str: ... def _expand_help(self, action: Action) -> str: ... - def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... + def _iter_indented_subactions(self, action: Action) -> Generator[Action]: ... def _split_lines(self, text: str, width: int) -> list[str]: ... def _fill_text(self, text: str, width: int, indent: str) -> str: ... def _get_help_string(self, action: Action) -> str | None: ... @@ -295,173 +393,472 @@ class Action(_AttributeHolder): nargs: int | str | None const: Any default: Any - type: Callable[[str], Any] | FileType | None + type: _ActionType | None choices: Iterable[Any] | None required: bool help: str | None - metavar: str | Tuple[str, ...] | None - def __init__( - self, - option_strings: Sequence[str], - dest: str, - nargs: int | str | None = ..., - const: _T | None = ..., - default: _T | str | None = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType | None = ..., - choices: Iterable[_T] | None = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., - ) -> None: ... + metavar: str | tuple[str, ...] | None + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + nargs: int | str | None = None, + const: _T | None = None, + default: _T | str | None = None, + type: Callable[[str], _T] | FileType | None = None, + choices: Iterable[_T] | None = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + nargs: int | str | None = None, + const: _T | None = None, + default: _T | str | None = None, + type: Callable[[str], _T] | FileType | None = None, + choices: Iterable[_T] | None = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + def __call__( - self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = ... + self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None ) -> None: ... - if sys.version_info >= (3, 9): - def format_usage(self) -> str: ... + def format_usage(self) -> str: ... -if sys.version_info >= (3, 9): +if sys.version_info >= (3, 12): class BooleanOptionalAction(Action): + if sys.version_info >= (3, 14): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 13): + @overload + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored; removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, + type: Callable[[str], _T] | FileType | None = sentinel, + choices: Iterable[_T] | None = sentinel, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = sentinel, + deprecated: bool = False, + ) -> None: ... + else: + @overload + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored; removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, + type: Callable[[str], _T] | FileType | None = sentinel, + choices: Iterable[_T] | None = sentinel, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = sentinel, + ) -> None: ... + +else: + class BooleanOptionalAction(Action): + @overload def __init__( self, option_strings: Sequence[str], dest: str, - default: _T | str | None = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType | None = ..., - choices: Iterable[_T] | None = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored; removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, + type: Callable[[str], _T] | FileType | None = None, + choices: Iterable[_T] | None = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, ) -> None: ... class Namespace(_AttributeHolder): def __init__(self, **kwargs: Any) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... def __contains__(self, key: str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] +@deprecated("Deprecated; may leave files open. Open files after parsing arguments instead.") class FileType: # undocumented _mode: str _bufsize: int _encoding: str | None _errors: str | None - def __init__(self, mode: str = ..., bufsize: int = ..., encoding: str | None = ..., errors: str | None = ...) -> None: ... + def __init__(self, mode: str = "r", bufsize: int = -1, encoding: str | None = None, errors: str | None = None) -> None: ... def __call__(self, string: str) -> IO[Any]: ... # undocumented class _ArgumentGroup(_ActionsContainer): title: str | None _group_actions: list[Action] + + @overload def __init__( - self, container: _ActionsContainer, title: str | None = ..., description: str | None = ..., **kwargs: Any + self, + container: _ActionsContainer, + title: str | None = None, + description: str | None = None, + *, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> None: ... + @overload + @deprecated("Undocumented `prefix_chars` parameter is deprecated.") + def __init__( + self, + container: _ActionsContainer, + title: str | None = None, + description: str | None = None, + *, + prefix_chars: str, + argument_default: Any = ..., + conflict_handler: str = ..., ) -> None: ... # undocumented class _MutuallyExclusiveGroup(_ArgumentGroup): required: bool _container: _ActionsContainer - def __init__(self, container: _ActionsContainer, required: bool = ...) -> None: ... + def __init__(self, container: _ActionsContainer, required: bool = False) -> None: ... # undocumented class _StoreAction(Action): ... # undocumented class _StoreConstAction(Action): - def __init__( - self, - option_strings: Sequence[str], - dest: str, - const: Any, - default: Any = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... # undocumented class _StoreTrueAction(_StoreConstAction): - def __init__( - self, option_strings: Sequence[str], dest: str, default: bool = ..., required: bool = ..., help: str | None = ... - ) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool = False, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, option_strings: Sequence[str], dest: str, default: bool = False, required: bool = False, help: str | None = None + ) -> None: ... # undocumented class _StoreFalseAction(_StoreConstAction): - def __init__( - self, option_strings: Sequence[str], dest: str, default: bool = ..., required: bool = ..., help: str | None = ... - ) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool = True, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, option_strings: Sequence[str], dest: str, default: bool = True, required: bool = False, help: str | None = None + ) -> None: ... # undocumented class _AppendAction(Action): ... +# undocumented +class _ExtendAction(_AppendAction): ... + # undocumented class _AppendConstAction(Action): - def __init__( - self, - option_strings: Sequence[str], - dest: str, - const: Any, - default: Any = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... # undocumented class _CountAction(Action): - def __init__( - self, option_strings: Sequence[str], dest: str, default: Any = ..., required: bool = ..., help: str | None = ... - ) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: Any = None, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, option_strings: Sequence[str], dest: str, default: Any = None, required: bool = False, help: str | None = None + ) -> None: ... # undocumented class _HelpAction(Action): - def __init__(self, option_strings: Sequence[str], dest: str = ..., default: str = ..., help: str | None = ...) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + ) -> None: ... # undocumented class _VersionAction(Action): version: str | None - def __init__( - self, option_strings: Sequence[str], version: str | None = ..., dest: str = ..., default: str = ..., help: str = ... - ) -> None: ... + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + version: str | None = None, + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + version: str | None = None, + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + version: str | None = None, + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str = "show program's version number and exit", + ) -> None: ... # undocumented class _SubParsersAction(Action, Generic[_ArgumentParserT]): - _ChoicesPseudoAction: Type[Any] # nested class + _ChoicesPseudoAction: type[Any] # nested class _prog_prefix: str - _parser_class: Type[_ArgumentParserT] + _parser_class: type[_ArgumentParserT] _name_parser_map: dict[str, _ArgumentParserT] choices: dict[str, _ArgumentParserT] _choices_actions: list[Action] - if sys.version_info >= (3, 7): - def __init__( + def __init__( + self, + option_strings: Sequence[str], + prog: str, + parser_class: type[_ArgumentParserT], + dest: str = "==SUPPRESS==", + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + + # Note: `add_parser` accepts all kwargs of `ArgumentParser.__init__`. It also + # accepts its own `help` and `aliases` kwargs. + if sys.version_info >= (3, 14): + def add_parser( self, - option_strings: Sequence[str], - prog: str, - parser_class: Type[_ArgumentParserT], - dest: str = ..., - required: bool = ..., + name: str, + *, + deprecated: bool = False, help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., - ) -> None: ... + aliases: Iterable[str] = ..., + # Kwargs from ArgumentParser constructor + prog: str | None = ..., + usage: str | None = ..., + description: str | None = ..., + epilog: str | None = ..., + parents: Iterable[_ArgumentParserT] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: str | None = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + suggest_on_error: bool = False, + color: bool = False, + **kwargs: Any, # Accepting any additional kwargs for custom parser classes + ) -> _ArgumentParserT: ... + elif sys.version_info >= (3, 13): + def add_parser( + self, + name: str, + *, + deprecated: bool = False, + help: str | None = ..., + aliases: Iterable[str] = ..., + # Kwargs from ArgumentParser constructor + prog: str | None = ..., + usage: str | None = ..., + description: str | None = ..., + epilog: str | None = ..., + parents: Iterable[_ArgumentParserT] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: str | None = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + **kwargs: Any, # Accepting any additional kwargs for custom parser classes + ) -> _ArgumentParserT: ... else: - def __init__( + def add_parser( self, - option_strings: Sequence[str], - prog: str, - parser_class: Type[_ArgumentParserT], - dest: str = ..., + name: str, + *, help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., - ) -> None: ... - # TODO: Type keyword args properly. - def add_parser(self, name: str, **kwargs: Any) -> _ArgumentParserT: ... + aliases: Iterable[str] = ..., + # Kwargs from ArgumentParser constructor + prog: str | None = ..., + usage: str | None = ..., + description: str | None = ..., + epilog: str | None = ..., + parents: Iterable[_ArgumentParserT] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: str | None = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + **kwargs: Any, # Accepting any additional kwargs for custom parser classes + ) -> _ArgumentParserT: ... + def _get_subactions(self) -> list[Action]: ... # undocumented class ArgumentTypeError(Exception): ... -if sys.version_info < (3, 7): - # undocumented - def _ensure_value(namespace: Namespace, name: str, value: Any) -> Any: ... - # undocumented def _get_action_name(argument: Action | None) -> str | None: ... diff --git a/stdlib/array.pyi b/stdlib/array.pyi index f49eb2c916c2..2c83146edbf0 100644 --- a/stdlib/array.pyi +++ b/stdlib/array.pyi @@ -1,69 +1,113 @@ import sys -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, Union, overload -from typing_extensions import Literal, SupportsIndex +from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite +from collections.abc import Iterable, MutableSequence +from types import GenericAlias +from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated, disjoint_base -_IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] -_FloatTypeCode = Literal["f", "d"] -_UnicodeTypeCode = Literal["u"] -_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] +_IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] +if sys.version_info >= (3, 15): + _FloatTypeCode: TypeAlias = Literal["f", "d", "e", "Zf", "Zd"] +else: + _FloatTypeCode: TypeAlias = Literal["f", "d"] +if sys.version_info >= (3, 13): + _UnicodeTypeCode: TypeAlias = Literal["u", "w"] +else: + _UnicodeTypeCode: TypeAlias = Literal["u"] +_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode _T = TypeVar("_T", int, float, str) -typecodes: str +if sys.version_info >= (3, 15): + typecodes: tuple[str, ...] +else: + typecodes: str + +@disjoint_base +class array(MutableSequence[_T]): + @property + def typecode(self) -> _TypeCode: ... + @property + def itemsize(self) -> int: ... -class array(MutableSequence[_T], Generic[_T]): - typecode: _TypeCode - itemsize: int @overload - def __init__(self: array[int], __typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __new__( + cls: type[array[int]], typecode: _IntTypeCode, initializer: bytes | bytearray | Iterable[int] = ..., / + ) -> array[int]: ... @overload - def __init__(self: array[float], __typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __new__( + cls: type[array[float]], typecode: _FloatTypeCode, initializer: bytes | bytearray | Iterable[float] = ..., / + ) -> array[float]: ... + if sys.version_info >= (3, 13): + @overload + def __new__( + cls: type[array[str]], typecode: Literal["w"], initializer: bytes | bytearray | Iterable[str] = ..., / + ) -> array[str]: ... + @overload + @deprecated("Deprecated since Python 3.3; will be removed in Python 3.16. Use 'w' typecode instead.") + def __new__( + cls: type[array[str]], typecode: Literal["u"], initializer: bytes | bytearray | Iterable[str] = ..., / + ) -> array[str]: ... + else: + @overload + @deprecated("Deprecated since Python 3.3; will be removed in Python 3.16.") + def __new__( + cls: type[array[str]], typecode: Literal["u"], initializer: bytes | bytearray | Iterable[str] = ..., / + ) -> array[str]: ... + @overload - def __init__(self: array[str], __typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __new__(cls, typecode: str, initializer: Iterable[_T], /) -> Self: ... @overload - def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ... - def append(self, __v: _T) -> None: ... + def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ... + + def append(self, v: _T, /) -> None: ... def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... - def count(self, __v: Any) -> int: ... - def extend(self, __bb: Iterable[_T]) -> None: ... - def frombytes(self, __buffer: bytes) -> None: ... - def fromfile(self, __f: BinaryIO, __n: int) -> None: ... - def fromlist(self, __list: list[_T]) -> None: ... - def fromunicode(self, __ustr: str) -> None: ... - if sys.version_info >= (3, 10): - def index(self, __v: _T, __start: int = ..., __stop: int = ...) -> int: ... - else: - def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence - def insert(self, __i: int, __v: _T) -> None: ... - def pop(self, __i: int = ...) -> _T: ... - def remove(self, __v: Any) -> None: ... - def reverse(self) -> None: ... + def count(self, v: _T, /) -> int: ... + def extend(self, bb: Iterable[_T], /) -> None: ... + def frombytes(self, buffer: ReadableBuffer, /) -> None: ... + def fromfile(self, f: SupportsRead[bytes], n: int, /) -> None: ... + def fromlist(self, list: list[_T], /) -> None: ... + def fromunicode(self, ustr: str, /) -> None: ... + def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ... + def insert(self, i: int, v: _T, /) -> None: ... + def pop(self, i: int = -1, /) -> _T: ... + def remove(self, v: _T, /) -> None: ... def tobytes(self) -> bytes: ... - def tofile(self, __f: BinaryIO) -> None: ... + def tofile(self, f: SupportsWrite[bytes], /) -> None: ... def tolist(self) -> list[_T]: ... def tounicode(self) -> str: ... - if sys.version_info < (3, 9): - def fromstring(self, __buffer: bytes) -> None: ... - def tostring(self) -> bytes: ... + + __hash__: ClassVar[None] # type: ignore[assignment] + def __contains__(self, value: object, /) -> bool: ... def __len__(self) -> int: ... + @overload - def __getitem__(self, __i: SupportsIndex) -> _T: ... + def __getitem__(self, key: SupportsIndex, /) -> _T: ... @overload - def __getitem__(self, __s: slice) -> array[_T]: ... - @overload # type: ignore # Overrides MutableSequence - def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> array[_T]: ... + + @overload # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... @overload - def __setitem__(self, __s: slice, __o: array[_T]) -> None: ... - def __delitem__(self, __i: SupportsIndex | slice) -> None: ... - def __add__(self, __x: array[_T]) -> array[_T]: ... - def __ge__(self, __other: array[_T]) -> bool: ... - def __gt__(self, __other: array[_T]) -> bool: ... - def __iadd__(self, __x: array[_T]) -> array[_T]: ... # type: ignore # Overrides MutableSequence - def __imul__(self, __n: int) -> array[_T]: ... - def __le__(self, __other: array[_T]) -> bool: ... - def __lt__(self, __other: array[_T]) -> bool: ... - def __mul__(self, __n: int) -> array[_T]: ... - def __rmul__(self, __n: int) -> array[_T]: ... + def __setitem__(self, key: slice[SupportsIndex | None], value: array[_T], /) -> None: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + def __add__(self, value: array[_T], /) -> array[_T]: ... + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: array[_T], /) -> bool: ... + def __gt__(self, value: array[_T], /) -> bool: ... + def __iadd__(self, value: array[_T], /) -> Self: ... # type: ignore[override] + def __imul__(self, value: int, /) -> Self: ... + def __le__(self, value: array[_T], /) -> bool: ... + def __lt__(self, value: array[_T], /) -> bool: ... + def __mul__(self, value: int, /) -> array[_T]: ... + def __rmul__(self, value: int, /) -> array[_T]: ... + def __copy__(self) -> array[_T]: ... + def __deepcopy__(self, unused: Any, /) -> array[_T]: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... ArrayType = array diff --git a/stdlib/ast.pyi b/stdlib/ast.pyi index 8494a3a99126..f84c93e7953e 100644 --- a/stdlib/ast.pyi +++ b/stdlib/ast.pyi @@ -1,43 +1,2050 @@ -# Rename typing to _typing, as not to conflict with typing imported -# from _ast below when loaded in an unorthodox way by the Dropbox -# internal Bazel integration. - -# The same unorthodox Bazel integration causes issues with sys, which -# is imported in both modules. unfortunately we can't just rename sys, -# since mypy only supports version checks with a sys that is named -# sys. +import ast +import builtins +import os import sys -import typing as _typing -from _ast import * -from typing import Any, Iterator, TypeVar, overload -from typing_extensions import Literal - -if sys.version_info >= (3, 8): - class Num(Constant): - value: complex - class Str(Constant): - value: str - # Aliases for value, for backwards compatibility - s: str - class Bytes(Constant): - value: bytes +import typing_extensions +from _ast import ( + PyCF_ALLOW_TOP_LEVEL_AWAIT as PyCF_ALLOW_TOP_LEVEL_AWAIT, + PyCF_ONLY_AST as PyCF_ONLY_AST, + PyCF_TYPE_COMMENTS as PyCF_TYPE_COMMENTS, +) +from _typeshed import ReadableBuffer, Unused +from collections.abc import Iterable, Iterator, Sequence +from types import EllipsisType +from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only +from typing_extensions import Self, Unpack, deprecated, disjoint_base + +if sys.version_info >= (3, 13): + from _ast import PyCF_OPTIMIZED_AST as PyCF_OPTIMIZED_AST + +# Used for node end positions in constructor keyword arguments +_EndPositionT = typing_extensions.TypeVar("_EndPositionT", int, int | None, default=int | None) + +# Corresponds to the names in the `_attributes` class variable which is non-empty in certain AST nodes +@type_check_only +class _Attributes(TypedDict, Generic[_EndPositionT], total=False): + lineno: int + col_offset: int + end_lineno: _EndPositionT + end_col_offset: _EndPositionT + +# The various AST classes are implemented in C, and imported from _ast at runtime, +# but they consider themselves to live in the ast module, +# so we'll define the stubs in this file. +if sys.version_info >= (3, 12): + @disjoint_base + class AST: + __match_args__ = () + _attributes: ClassVar[tuple[str, ...]] + _fields: ClassVar[tuple[str, ...]] + if sys.version_info >= (3, 13): + _field_types: ClassVar[dict[str, Any]] + + if sys.version_info >= (3, 14): + def __replace__(self) -> Self: ... + +else: + class AST: + __match_args__ = () + _attributes: ClassVar[tuple[str, ...]] + _fields: ClassVar[tuple[str, ...]] + +class mod(AST): ... + +class Module(mod): + __match_args__ = ("body", "type_ignores") + body: list[stmt] + type_ignores: list[TypeIgnore] + if sys.version_info >= (3, 13): + def __init__(self, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> None: ... + else: + def __init__(self, body: list[stmt], type_ignores: list[TypeIgnore]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> Self: ... + +class Interactive(mod): + __match_args__ = ("body",) + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__(self, body: list[stmt] = ...) -> None: ... + else: + def __init__(self, body: list[stmt]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, body: list[stmt] = ...) -> Self: ... + +class Expression(mod): + __match_args__ = ("body",) + body: expr + def __init__(self, body: expr) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, body: expr = ...) -> Self: ... + +class FunctionType(mod): + __match_args__ = ("argtypes", "returns") + argtypes: list[expr] + returns: expr + if sys.version_info >= (3, 13): + @overload + def __init__(self, argtypes: list[expr], returns: expr) -> None: ... + @overload + def __init__(self, argtypes: list[expr] = ..., *, returns: expr) -> None: ... + else: + def __init__(self, argtypes: list[expr], returns: expr) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, argtypes: list[expr] = ..., returns: expr = ...) -> Self: ... + +class stmt(AST): + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ... + +class FunctionDef(stmt): + if sys.version_info >= (3, 12): + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") + else: + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") + name: str + args: arguments + body: list[stmt] + decorator_list: list[expr] + returns: expr | None + type_comment: str | None + if sys.version_info >= (3, 12): + type_params: list[type_param] + if sys.version_info >= (3, 13): + def __init__( + self, + name: str, + args: arguments, + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = None, + type_comment: str | None = None, + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 12): + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None, + type_comment: str | None, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + *, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + args: arguments = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = ..., + type_comment: str | None = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AsyncFunctionDef(stmt): + if sys.version_info >= (3, 12): + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") + else: + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") + name: str + args: arguments + body: list[stmt] + decorator_list: list[expr] + returns: expr | None + type_comment: str | None + if sys.version_info >= (3, 12): + type_params: list[type_param] + if sys.version_info >= (3, 13): + def __init__( + self, + name: str, + args: arguments, + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = None, + type_comment: str | None = None, + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 12): + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None, + type_comment: str | None, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + *, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + args: arguments = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = ..., + type_comment: str | None = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class ClassDef(stmt): + if sys.version_info >= (3, 12): + __match_args__ = ("name", "bases", "keywords", "body", "decorator_list", "type_params") + else: + __match_args__ = ("name", "bases", "keywords", "body", "decorator_list") + name: str + bases: list[expr] + keywords: list[keyword] + body: list[stmt] + decorator_list: list[expr] + if sys.version_info >= (3, 12): + type_params: list[type_param] + if sys.version_info >= (3, 13): + def __init__( + self, + name: str, + bases: list[expr] = ..., + keywords: list[keyword] = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 12): + def __init__( + self, + name: str, + bases: list[expr], + keywords: list[keyword], + body: list[stmt], + decorator_list: list[expr], + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + name: str, + bases: list[expr], + keywords: list[keyword], + body: list[stmt], + decorator_list: list[expr], + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + bases: list[expr] = ..., + keywords: list[keyword] = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class Return(stmt): + __match_args__ = ("value",) + value: expr | None + def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Delete(stmt): + __match_args__ = ("targets",) + targets: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, targets: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Assign(stmt): + __match_args__ = ("targets", "value", "type_comment") + targets: list[expr] + value: expr + type_comment: str | None + if sys.version_info >= (3, 13): + @overload + def __init__( + self, targets: list[expr], value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + @overload + def __init__( + self, targets: list[expr] = ..., *, value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__( + self, targets: list[expr], value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, targets: list[expr] = ..., value: expr = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +if sys.version_info >= (3, 12): + class TypeAlias(stmt): + __match_args__ = ("name", "type_params", "value") + name: Name + type_params: list[type_param] + value: expr + if sys.version_info >= (3, 13): + @overload + def __init__( + self, name: Name, type_params: list[type_param], value: expr, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + @overload + def __init__( + self, name: Name, type_params: list[type_param] = ..., *, value: expr, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + else: + def __init__( + self, name: Name, type_params: list[type_param], value: expr, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( # type: ignore[override] + self, + *, + name: Name = ..., + type_params: list[type_param] = ..., + value: expr = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + +class AugAssign(stmt): + __match_args__ = ("target", "op", "value") + target: Name | Attribute | Subscript + op: operator + value: expr + def __init__( + self, target: Name | Attribute | Subscript, op: operator, value: expr, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: Name | Attribute | Subscript = ..., + op: operator = ..., + value: expr = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AnnAssign(stmt): + __match_args__ = ("target", "annotation", "value", "simple") + target: Name | Attribute | Subscript + annotation: expr + value: expr | None + simple: int + + @overload + def __init__( + self, + target: Name | Attribute | Subscript, + annotation: expr, + value: expr | None, + simple: int, + **kwargs: Unpack[_Attributes], + ) -> None: ... + @overload + def __init__( + self, + target: Name | Attribute | Subscript, + annotation: expr, + value: expr | None = None, + *, + simple: int, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: Name | Attribute | Subscript = ..., + annotation: expr = ..., + value: expr | None = ..., + simple: int = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class For(stmt): + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") + target: expr + iter: expr + body: list[stmt] + orelse: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt], + orelse: list[stmt], + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: expr = ..., + iter: expr = ..., + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AsyncFor(stmt): + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") + target: expr + iter: expr + body: list[stmt] + orelse: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt], + orelse: list[stmt], + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: expr = ..., + iter: expr = ..., + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class While(stmt): + __match_args__ = ("test", "body", "orelse") + test: expr + body: list[stmt] + orelse: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, test: expr, body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class If(stmt): + __match_args__ = ("test", "body", "orelse") + test: expr + body: list[stmt] + orelse: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, test: expr, body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class With(stmt): + __match_args__ = ("items", "body", "type_comment") + items: list[withitem] + body: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, items: list[withitem], body: list[stmt], type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AsyncWith(stmt): + __match_args__ = ("items", "body", "type_comment") + items: list[withitem] + body: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, items: list[withitem], body: list[stmt], type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class Raise(stmt): + __match_args__ = ("exc", "cause") + exc: expr | None + cause: expr | None + def __init__(self, exc: expr | None = None, cause: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, exc: expr | None = ..., cause: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Try(stmt): + __match_args__ = ("body", "handlers", "orelse", "finalbody") + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] + finalbody: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + body: list[stmt], + handlers: list[ExceptHandler], + orelse: list[stmt], + finalbody: list[stmt], + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +if sys.version_info >= (3, 11): + class TryStar(stmt): + __match_args__ = ("body", "handlers", "orelse", "finalbody") + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] + finalbody: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + body: list[stmt], + handlers: list[ExceptHandler], + orelse: list[stmt], + finalbody: list[stmt], + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class Assert(stmt): + __match_args__ = ("test", "msg") + test: expr + msg: expr | None + def __init__(self, test: expr, msg: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, test: expr = ..., msg: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Import(stmt): + if sys.version_info >= (3, 15): + __match_args__ = ("names", "is_lazy") + else: + __match_args__ = ("names",) + names: list[alias] + if sys.version_info >= (3, 15): + is_lazy: bool | None + if sys.version_info >= (3, 15): + def __init__(self, names: list[alias] = ..., is_lazy: bool | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + elif sys.version_info >= (3, 13): + def __init__(self, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, names: list[alias], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 15): + def __replace__(self, *, names: list[alias] = ..., is_lazy: bool | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + + elif sys.version_info >= (3, 14): + def __replace__(self, *, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class ImportFrom(stmt): + if sys.version_info >= (3, 15): + __match_args__ = ("module", "names", "level", "is_lazy") + else: + __match_args__ = ("module", "names", "level") + module: str | None + names: list[alias] + level: int + if sys.version_info >= (3, 15): + is_lazy: bool | None + if sys.version_info >= (3, 15): + @overload + def __init__( + self, module: str | None, names: list[alias], level: int, is_lazy: bool | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + @overload + def __init__( + self, + module: str | None = None, + names: list[alias] = ..., + *, + level: int, + is_lazy: bool | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 13): + @overload + def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__( + self, module: str | None = None, names: list[alias] = ..., *, level: int, **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + @overload + def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__( + self, module: str | None = None, *, names: list[alias], level: int, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 15): + def __replace__( + self, + *, + module: str | None = ..., + names: list[alias] = ..., + level: int = ..., + is_lazy: bool | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + + elif sys.version_info >= (3, 14): + def __replace__( + self, *, module: str | None = ..., names: list[alias] = ..., level: int = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Global(stmt): + __match_args__ = ("names",) + names: list[str] + if sys.version_info >= (3, 13): + def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, names: list[str], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Nonlocal(stmt): + __match_args__ = ("names",) + names: list[str] + if sys.version_info >= (3, 13): + def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, names: list[str], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Expr(stmt): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... + +class expr(AST): + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ... + +class BoolOp(expr): + __match_args__ = ("op", "values") + op: boolop + values: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, op: boolop, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, op: boolop, values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, op: boolop = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class NamedExpr(expr): + __match_args__ = ("target", "value") + target: Name + value: expr + def __init__(self, target: Name, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, target: Name = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class BinOp(expr): + __match_args__ = ("left", "op", "right") + left: expr + op: operator + right: expr + def __init__(self, left: expr, op: operator, right: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, left: expr = ..., op: operator = ..., right: expr = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class UnaryOp(expr): + __match_args__ = ("op", "operand") + op: unaryop + operand: expr + def __init__(self, op: unaryop, operand: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, op: unaryop = ..., operand: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Lambda(expr): + __match_args__ = ("args", "body") + args: arguments + body: expr + def __init__(self, args: arguments, body: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, args: arguments = ..., body: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class IfExp(expr): + __match_args__ = ("test", "body", "orelse") + test: expr + body: expr + orelse: expr + def __init__(self, test: expr, body: expr, orelse: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, test: expr = ..., body: expr = ..., orelse: expr = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Dict(expr): + __match_args__ = ("keys", "values") + keys: list[expr | None] + values: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, keys: list[expr | None], values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Set(expr): + __match_args__ = ("elts",) + elts: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elts: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class ListComp(expr): + __match_args__ = ("elt", "generators") + elt: expr + generators: list[comprehension] + if sys.version_info >= (3, 13): + def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class SetComp(expr): + __match_args__ = ("elt", "generators") + elt: expr + generators: list[comprehension] + if sys.version_info >= (3, 13): + def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class DictComp(expr): + __match_args__ = ("key", "value", "generators") + key: expr + if sys.version_info >= (3, 15): + value: expr | None + else: + value: expr + generators: list[comprehension] + if sys.version_info >= (3, 15): + def __init__( + self, key: expr, value: expr | None = None, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + elif sys.version_info >= (3, 13): + def __init__( + self, key: expr, value: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, key: expr, value: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 15): + def __replace__( + self, + *, + key: expr = ..., + value: expr | None = ..., + generators: list[comprehension] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + elif sys.version_info >= (3, 14): + def __replace__( + self, *, key: expr = ..., value: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class GeneratorExp(expr): + __match_args__ = ("elt", "generators") + elt: expr + generators: list[comprehension] + if sys.version_info >= (3, 13): + def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Await(expr): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Yield(expr): + __match_args__ = ("value",) + value: expr | None + def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class YieldFrom(expr): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Compare(expr): + __match_args__ = ("left", "ops", "comparators") + left: expr + ops: list[cmpop] + comparators: list[expr] + if sys.version_info >= (3, 13): + def __init__( + self, left: expr, ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, left: expr, ops: list[cmpop], comparators: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, left: expr = ..., ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Call(expr): + __match_args__ = ("func", "args", "keywords") + func: expr + args: list[expr] + keywords: list[keyword] + if sys.version_info >= (3, 13): + def __init__( + self, func: expr, args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, func: expr, args: list[expr], keywords: list[keyword], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, func: expr = ..., args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class FormattedValue(expr): + __match_args__ = ("value", "conversion", "format_spec") + value: expr + conversion: int + format_spec: expr | None + def __init__(self, value: expr, conversion: int, format_spec: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, value: expr = ..., conversion: int = ..., format_spec: expr | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class JoinedStr(expr): + __match_args__ = ("values",) + values: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +if sys.version_info >= (3, 14): + class TemplateStr(expr): + __match_args__ = ("values",) + values: list[expr] + def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + + class Interpolation(expr): + __match_args__ = ("value", "str", "conversion", "format_spec") + value: expr + str: builtins.str + conversion: int + format_spec: expr | None = None + def __init__( + self, + value: expr = ..., + str: builtins.str = ..., + conversion: int = ..., + format_spec: expr | None = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + def __replace__( + self, + *, + value: expr = ..., + str: builtins.str = ..., + conversion: int = ..., + format_spec: expr | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +_ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | EllipsisType | None + +class Constant(expr): + __match_args__ = ("value", "kind") + value: _ConstantValue + kind: str | None + if sys.version_info < (3, 14): # Aliases for value, for backwards compatibility - s: bytes - class NameConstant(Constant): ... - class Ellipsis(Constant): ... - -if sys.version_info >= (3, 9): - class slice(AST): ... - class ExtSlice(slice): ... - class Index(slice): ... - class Suite(mod): ... - class AugLoad(expr_context): ... - class AugStore(expr_context): ... - class Param(expr_context): ... + @property + @deprecated("Removed in Python 3.14. Use `value` instead.") + def n(self) -> _ConstantValue: ... + @n.setter + @deprecated("Removed in Python 3.14. Use `value` instead.") + def n(self, value: _ConstantValue) -> None: ... + + @property + @deprecated("Removed in Python 3.14. Use `value` instead.") + def s(self) -> _ConstantValue: ... + @s.setter + @deprecated("Removed in Python 3.14. Use `value` instead.") + def s(self, value: _ConstantValue) -> None: ... + + def __init__(self, value: _ConstantValue, kind: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: _ConstantValue = ..., kind: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Attribute(expr): + __match_args__ = ("value", "attr", "ctx") + value: expr + attr: str + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, value: expr, attr: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, value: expr = ..., attr: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Subscript(expr): + __match_args__ = ("value", "slice", "ctx") + value: expr + slice: expr + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, value: expr, slice: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, value: expr = ..., slice: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Starred(expr): + __match_args__ = ("value", "ctx") + value: expr + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, value: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Name(expr): + __match_args__ = ("id", "ctx") + id: str + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, id: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, id: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class List(expr): + __match_args__ = ("elts", "ctx") + elts: list[expr] + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + if sys.version_info >= (3, 13): + def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elts: list[expr], ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Tuple(expr): + __match_args__ = ("elts", "ctx") + elts: list[expr] + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + dims: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elts: list[expr], ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +@deprecated("Deprecated since Python 3.9.") +class slice(AST): ... + +class Slice(expr): + __match_args__ = ("lower", "upper", "step") + lower: expr | None + upper: expr | None + step: expr | None + def __init__( + self, lower: expr | None = None, upper: expr | None = None, step: expr | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, lower: expr | None = ..., upper: expr | None = ..., step: expr | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +@deprecated("Deprecated since Python 3.9. Use `ast.Tuple` instead.") +class ExtSlice(slice): + def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_Attributes]) -> Tuple: ... # type: ignore[misc] + +@deprecated("Deprecated since Python 3.9. Use the index value directly instead.") +class Index(slice): + def __new__(cls, value: expr, **kwargs: Unpack[_Attributes]) -> expr: ... # type: ignore[misc] + +class expr_context(AST): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class AugLoad(expr_context): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class AugStore(expr_context): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class Param(expr_context): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class Suite(mod): ... + +class Load(expr_context): ... +class Store(expr_context): ... +class Del(expr_context): ... +class boolop(AST): ... +class And(boolop): ... +class Or(boolop): ... +class operator(AST): ... +class Add(operator): ... +class Sub(operator): ... +class Mult(operator): ... +class MatMult(operator): ... +class Div(operator): ... +class Mod(operator): ... +class Pow(operator): ... +class LShift(operator): ... +class RShift(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class BitAnd(operator): ... +class FloorDiv(operator): ... +class unaryop(AST): ... +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... +class cmpop(AST): ... +class Eq(cmpop): ... +class NotEq(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class In(cmpop): ... +class NotIn(cmpop): ... + +class comprehension(AST): + __match_args__ = ("target", "iter", "ifs", "is_async") + target: expr + iter: expr + ifs: list[expr] + is_async: int + if sys.version_info >= (3, 13): + @overload + def __init__(self, target: expr, iter: expr, ifs: list[expr], is_async: int) -> None: ... + @overload + def __init__(self, target: expr, iter: expr, ifs: list[expr] = ..., *, is_async: int) -> None: ... + else: + def __init__(self, target: expr, iter: expr, ifs: list[expr], is_async: int) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, target: expr = ..., iter: expr = ..., ifs: list[expr] = ..., is_async: int = ...) -> Self: ... + +class excepthandler(AST): + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int | None = ..., end_col_offset: int | None = ... + ) -> Self: ... + +class ExceptHandler(excepthandler): + __match_args__ = ("type", "name", "body") + type: expr | None + name: str | None + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, type: expr | None = None, name: str | None = None, body: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + @overload + def __init__(self, type: expr | None, name: str | None, body: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__( + self, type: expr | None = None, name: str | None = None, *, body: list[stmt], **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, type: expr | None = ..., name: str | None = ..., body: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class arguments(AST): + __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") + posonlyargs: list[arg] + args: list[arg] + vararg: arg | None + kwonlyargs: list[arg] + kw_defaults: list[expr | None] + kwarg: arg | None + defaults: list[expr] + if sys.version_info >= (3, 13): + def __init__( + self, + posonlyargs: list[arg] = ..., + args: list[arg] = ..., + vararg: arg | None = None, + kwonlyargs: list[arg] = ..., + kw_defaults: list[expr | None] = ..., + kwarg: arg | None = None, + defaults: list[expr] = ..., + ) -> None: ... + else: + @overload + def __init__( + self, + posonlyargs: list[arg], + args: list[arg], + vararg: arg | None, + kwonlyargs: list[arg], + kw_defaults: list[expr | None], + kwarg: arg | None, + defaults: list[expr], + ) -> None: ... + @overload + def __init__( + self, + posonlyargs: list[arg], + args: list[arg], + vararg: arg | None, + kwonlyargs: list[arg], + kw_defaults: list[expr | None], + kwarg: arg | None = None, + *, + defaults: list[expr], + ) -> None: ... + @overload + def __init__( + self, + posonlyargs: list[arg], + args: list[arg], + vararg: arg | None = None, + *, + kwonlyargs: list[arg], + kw_defaults: list[expr | None], + kwarg: arg | None = None, + defaults: list[expr], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + posonlyargs: list[arg] = ..., + args: list[arg] = ..., + vararg: arg | None = ..., + kwonlyargs: list[arg] = ..., + kw_defaults: list[expr | None] = ..., + kwarg: arg | None = ..., + defaults: list[expr] = ..., + ) -> Self: ... + +class arg(AST): + __match_args__ = ("arg", "annotation", "type_comment") + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + arg: str + annotation: expr | None + type_comment: str | None + def __init__( + self, arg: str, annotation: expr | None = None, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, arg: str = ..., annotation: expr | None = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class keyword(AST): + __match_args__ = ("arg", "value") + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + arg: str | None + value: expr + + @overload + def __init__(self, arg: str | None, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__(self, arg: str | None = None, *, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, arg: str | None = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class alias(AST): + __match_args__ = ("name", "asname") + name: str + asname: str | None + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, name: str, asname: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, name: str = ..., asname: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class withitem(AST): + __match_args__ = ("context_expr", "optional_vars") + context_expr: expr + optional_vars: expr | None + def __init__(self, context_expr: expr, optional_vars: expr | None = None) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, context_expr: expr = ..., optional_vars: expr | None = ...) -> Self: ... + +class pattern(AST): + lineno: int + col_offset: int + end_lineno: int + end_col_offset: int + def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ... + ) -> Self: ... + +class match_case(AST): + __match_args__ = ("pattern", "guard", "body") + pattern: ast.pattern + guard: expr | None + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__(self, pattern: ast.pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ... + else: + @overload + def __init__(self, pattern: ast.pattern, guard: expr | None, body: list[stmt]) -> None: ... + @overload + def __init__(self, pattern: ast.pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ... + +class Match(stmt): + __match_args__ = ("subject", "cases") + subject: expr + cases: list[match_case] + if sys.version_info >= (3, 13): + def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class MatchValue(pattern): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchSingleton(pattern): + __match_args__ = ("value",) + value: bool | None + def __init__(self, value: bool | None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchSequence(pattern): + __match_args__ = ("patterns",) + patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchMapping(pattern): + __match_args__ = ("keys", "patterns", "rest") + keys: list[expr] + patterns: list[pattern] + rest: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + keys: list[expr] = ..., + patterns: list[pattern] = ..., + rest: str | None = None, + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + else: + def __init__( + self, keys: list[expr], patterns: list[pattern], rest: str | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + keys: list[expr] = ..., + patterns: list[pattern] = ..., + rest: str | None = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + +class MatchClass(pattern): + __match_args__ = ("cls", "patterns", "kwd_attrs", "kwd_patterns") + cls: expr + patterns: list[pattern] + kwd_attrs: list[str] + kwd_patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__( + self, + cls: expr, + patterns: list[pattern] = ..., + kwd_attrs: list[str] = ..., + kwd_patterns: list[pattern] = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + else: + def __init__( + self, + cls: expr, + patterns: list[pattern], + kwd_attrs: list[str], + kwd_patterns: list[pattern], + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + cls: expr = ..., + patterns: list[pattern] = ..., + kwd_attrs: list[str] = ..., + kwd_patterns: list[pattern] = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + +class MatchStar(pattern): + __match_args__ = ("name",) + name: str | None + def __init__(self, name: str | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchAs(pattern): + __match_args__ = ("pattern", "name") + pattern: ast.pattern | None + name: str | None + def __init__( + self, pattern: ast.pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... + +class MatchOr(pattern): + __match_args__ = ("patterns",) + patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class type_ignore(AST): ... + +class TypeIgnore(type_ignore): + __match_args__ = ("lineno", "tag") + lineno: int + tag: str + def __init__(self, lineno: int, tag: str) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, lineno: int = ..., tag: str = ...) -> Self: ... + +if sys.version_info >= (3, 12): + class type_param(AST): + lineno: int + col_offset: int + end_lineno: int + end_col_offset: int + def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, **kwargs: Unpack[_Attributes[int]]) -> Self: ... + + class TypeVar(type_param): + if sys.version_info >= (3, 13): + __match_args__ = ("name", "bound", "default_value") + else: + __match_args__ = ("name", "bound") + name: str + bound: expr | None + if sys.version_info >= (3, 13): + default_value: expr | None + def __init__( + self, name: str, bound: expr | None = None, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + else: + def __init__(self, name: str, bound: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + bound: expr | None = ..., + default_value: expr | None = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + + class ParamSpec(type_param): + if sys.version_info >= (3, 13): + __match_args__ = ("name", "default_value") + else: + __match_args__ = ("name",) + name: str + if sys.version_info >= (3, 13): + default_value: expr | None + def __init__(self, name: str, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, name: str, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... + + class TypeVarTuple(type_param): + if sys.version_info >= (3, 13): + __match_args__ = ("name", "default_value") + else: + __match_args__ = ("name",) + name: str + if sys.version_info >= (3, 13): + default_value: expr | None + def __init__(self, name: str, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, name: str, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... + +if sys.version_info >= (3, 14): + @type_check_only + class _ABC(type): + def __init__(cls, *args: Unused) -> None: ... + +else: + class _ABC(type): + def __init__(cls, *args: Unused) -> None: ... + +if sys.version_info < (3, 14): + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Num(Constant, metaclass=_ABC): + def __new__(cls, n: complex, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Str(Constant, metaclass=_ABC): + def __new__(cls, s: str, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Bytes(Constant, metaclass=_ABC): + def __new__(cls, s: bytes, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class NameConstant(Constant, metaclass=_ABC): + def __new__(cls, value: _ConstantValue, kind: str | None, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Ellipsis(Constant, metaclass=_ABC): + def __new__(cls, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + +# everything below here is defined in ast.py + +_T = _TypeVar("_T", bound=AST) + +if sys.version_info >= (3, 15): + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> mod: ... +elif sys.version_info >= (3, 13): + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> mod: ... +else: + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: int | tuple[int, int] | None = None, + ) -> mod: ... + +def literal_eval(node_or_string: str | AST) -> Any: ... + +if sys.version_info >= (3, 15): + def dump( + node: AST, + annotate_fields: bool = True, + include_attributes: bool = False, + *, + indent: int | str | None = None, + show_empty: bool = False, + color: bool = False, + ) -> str: ... + +elif sys.version_info >= (3, 13): + def dump( + node: AST, + annotate_fields: bool = True, + include_attributes: bool = False, + *, + indent: int | str | None = None, + show_empty: bool = False, + ) -> str: ... + +else: + def dump( + node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None + ) -> str: ... + +def copy_location(new_node: _T, old_node: AST) -> _T: ... +def fix_missing_locations(node: _T) -> _T: ... +def increment_lineno(node: _T, n: int = 1) -> _T: ... +def iter_fields(node: AST) -> Iterator[tuple[str, Any]]: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def get_docstring(node: AsyncFunctionDef | FunctionDef | ClassDef | Module, clean: bool = True) -> str | None: ... +def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | None: ... +def walk(node: AST) -> Iterator[AST]: ... + +if sys.version_info >= (3, 14): + def compare(left: AST, right: AST, /, *, compare_attributes: bool = False) -> bool: ... class NodeVisitor: + # All visit methods below can be overwritten by subclasses and return an + # arbitrary value, which is passed to the caller. def visit(self, node: AST) -> Any: ... def generic_visit(self, node: AST) -> Any: ... + # The following visit methods are not defined on NodeVisitor, but can + # be implemented by subclasses and are called during a visit if defined. def visit_Module(self, node: Module) -> Any: ... def visit_Interactive(self, node: Interactive) -> Any: ... def visit_Expression(self, node: Expression) -> Any: ... @@ -86,8 +2093,8 @@ class NodeVisitor: def visit_FormattedValue(self, node: FormattedValue) -> Any: ... def visit_JoinedStr(self, node: JoinedStr) -> Any: ... def visit_Constant(self, node: Constant) -> Any: ... - if sys.version_info >= (3, 8): - def visit_NamedExpr(self, node: NamedExpr) -> Any: ... + def visit_NamedExpr(self, node: NamedExpr) -> Any: ... + def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ... def visit_Attribute(self, node: Attribute) -> Any: ... def visit_Subscript(self, node: Subscript) -> Any: ... def visit_Starred(self, node: Starred) -> Any: ... @@ -133,6 +2140,30 @@ class NodeVisitor: def visit_keyword(self, node: keyword) -> Any: ... def visit_alias(self, node: alias) -> Any: ... def visit_withitem(self, node: withitem) -> Any: ... + def visit_Match(self, node: Match) -> Any: ... + def visit_match_case(self, node: match_case) -> Any: ... + def visit_MatchValue(self, node: MatchValue) -> Any: ... + def visit_MatchSequence(self, node: MatchSequence) -> Any: ... + def visit_MatchSingleton(self, node: MatchSingleton) -> Any: ... + def visit_MatchStar(self, node: MatchStar) -> Any: ... + def visit_MatchMapping(self, node: MatchMapping) -> Any: ... + def visit_MatchClass(self, node: MatchClass) -> Any: ... + def visit_MatchAs(self, node: MatchAs) -> Any: ... + def visit_MatchOr(self, node: MatchOr) -> Any: ... + + if sys.version_info >= (3, 11): + def visit_TryStar(self, node: TryStar) -> Any: ... + + if sys.version_info >= (3, 12): + def visit_TypeVar(self, node: TypeVar) -> Any: ... + def visit_ParamSpec(self, node: ParamSpec) -> Any: ... + def visit_TypeVarTuple(self, node: TypeVarTuple) -> Any: ... + def visit_TypeAlias(self, node: TypeAlias) -> Any: ... + + if sys.version_info >= (3, 14): + def visit_TemplateStr(self, node: TemplateStr) -> Any: ... + def visit_Interpolation(self, node: Interpolation) -> Any: ... + # visit methods for deprecated nodes def visit_ExtSlice(self, node: ExtSlice) -> Any: ... def visit_Index(self, node: Index) -> Any: ... @@ -140,11 +2171,18 @@ class NodeVisitor: def visit_AugLoad(self, node: AugLoad) -> Any: ... def visit_AugStore(self, node: AugStore) -> Any: ... def visit_Param(self, node: Param) -> Any: ... - def visit_Num(self, node: Num) -> Any: ... - def visit_Str(self, node: Str) -> Any: ... - def visit_Bytes(self, node: Bytes) -> Any: ... - def visit_NameConstant(self, node: NameConstant) -> Any: ... - def visit_Ellipsis(self, node: Ellipsis) -> Any: ... + + if sys.version_info < (3, 14): + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Num(self, node: Num) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Str(self, node: Str) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Bytes(self, node: Bytes) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_NameConstant(self, node: NameConstant) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Ellipsis(self, node: Ellipsis) -> Any: ... # type: ignore[deprecated] class NodeTransformer(NodeVisitor): def generic_visit(self, node: AST) -> AST: ... @@ -152,114 +2190,10 @@ class NodeTransformer(NodeVisitor): # The usual return type is AST | None, but Iterable[AST] # is also allowed in some cases -- this needs to be mapped. -_T = TypeVar("_T", bound=AST) +def unparse(ast_obj: AST) -> str: ... -if sys.version_info >= (3, 8): - @overload - def parse( - source: str | bytes, - filename: str | bytes = ..., - mode: Literal["exec"] = ..., - *, - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> Module: ... - @overload - def parse( - source: str | bytes, - filename: str | bytes, - mode: Literal["eval"], - *, - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> Expression: ... - @overload - def parse( - source: str | bytes, - filename: str | bytes, - mode: Literal["func_type"], - *, - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> FunctionType: ... - @overload - def parse( - source: str | bytes, - filename: str | bytes, - mode: Literal["single"], - *, - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> Interactive: ... - @overload - def parse( - source: str | bytes, - *, - mode: Literal["eval"], - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> Expression: ... - @overload - def parse( - source: str | bytes, - *, - mode: Literal["func_type"], - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> FunctionType: ... - @overload - def parse( - source: str | bytes, - *, - mode: Literal["single"], - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> Interactive: ... - @overload - def parse( - source: str | bytes, - filename: str | bytes = ..., - mode: str = ..., - *, - type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., - ) -> AST: ... +if sys.version_info >= (3, 14): + def main(args: Sequence[str] | None = None) -> None: ... else: - @overload - def parse(source: str | bytes, filename: str | bytes = ..., mode: Literal["exec"] = ...) -> Module: ... - @overload - def parse(source: str | bytes, filename: str | bytes, mode: Literal["eval"]) -> Expression: ... - @overload - def parse(source: str | bytes, filename: str | bytes, mode: Literal["single"]) -> Interactive: ... - @overload - def parse(source: str | bytes, *, mode: Literal["eval"]) -> Expression: ... - @overload - def parse(source: str | bytes, *, mode: Literal["single"]) -> Interactive: ... - @overload - def parse(source: str | bytes, filename: str | bytes = ..., mode: str = ...) -> AST: ... - -if sys.version_info >= (3, 9): - def unparse(ast_obj: AST) -> str: ... - -def copy_location(new_node: _T, old_node: AST) -> _T: ... - -if sys.version_info >= (3, 9): - def dump( - node: AST, annotate_fields: bool = ..., include_attributes: bool = ..., *, indent: int | str | None = ... - ) -> str: ... - -else: - def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... - -def fix_missing_locations(node: _T) -> _T: ... -def get_docstring(node: AST, clean: bool = ...) -> str | None: ... -def increment_lineno(node: _T, n: int = ...) -> _T: ... -def iter_child_nodes(node: AST) -> Iterator[AST]: ... -def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... -def literal_eval(node_or_string: str | AST) -> Any: ... - -if sys.version_info >= (3, 8): - def get_source_segment(source: str, node: AST, *, padded: bool = ...) -> str | None: ... - -def walk(node: AST) -> Iterator[AST]: ... + def main() -> None: ... diff --git a/stdlib/asynchat.pyi b/stdlib/asynchat.pyi index e1787ca98b4f..79a70d1c1ec8 100644 --- a/stdlib/asynchat.pyi +++ b/stdlib/asynchat.pyi @@ -1,28 +1,21 @@ import asyncore -import socket from abc import abstractmethod class simple_producer: - def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... + def __init__(self, data: bytes, buffer_size: int = 512) -> None: ... def more(self) -> bytes: ... class async_chat(asyncore.dispatcher): ac_in_buffer_size: int ac_out_buffer_size: int - def __init__(self, sock: socket.socket | None = ..., map: asyncore._maptype | None = ...) -> None: ... @abstractmethod def collect_incoming_data(self, data: bytes) -> None: ... @abstractmethod def found_terminator(self) -> None: ... def set_terminator(self, term: bytes | int | None) -> None: ... def get_terminator(self) -> bytes | int | None: ... - def handle_read(self) -> None: ... - def handle_write(self) -> None: ... - def handle_close(self) -> None: ... def push(self, data: bytes) -> None: ... def push_with_producer(self, producer: simple_producer) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... def close_when_done(self) -> None: ... def initiate_send(self) -> None: ... def discard_buffers(self) -> None: ... diff --git a/stdlib/asyncio/__init__.pyi b/stdlib/asyncio/__init__.pyi index f2f7c6b0d165..5748c85af4c6 100644 --- a/stdlib/asyncio/__init__.pyi +++ b/stdlib/asyncio/__init__.pyi @@ -1,125 +1,1022 @@ +# This condition is so big, it's clearer to keep to platform condition in two blocks +# Can't NOQA on a specific line: https://github.com/plinss/flake8-noqa/issues/22 import sys -from typing import Type +from collections.abc import Awaitable, Coroutine, Generator +from typing import Any, TypeAlias, TypeVar -from .base_events import BaseEventLoop as BaseEventLoop -from .coroutines import iscoroutine as iscoroutine, iscoroutinefunction as iscoroutinefunction -from .events import ( - AbstractEventLoop as AbstractEventLoop, - AbstractEventLoopPolicy as AbstractEventLoopPolicy, - AbstractServer as AbstractServer, - Handle as Handle, - TimerHandle as TimerHandle, - _get_running_loop as _get_running_loop, - _set_running_loop as _set_running_loop, - get_child_watcher as get_child_watcher, - get_event_loop as get_event_loop, - get_event_loop_policy as get_event_loop_policy, - new_event_loop as new_event_loop, - set_child_watcher as set_child_watcher, - set_event_loop as set_event_loop, - set_event_loop_policy as set_event_loop_policy, -) -from .futures import Future as Future, isfuture as isfuture, wrap_future as wrap_future -from .locks import ( - BoundedSemaphore as BoundedSemaphore, - Condition as Condition, - Event as Event, - Lock as Lock, - Semaphore as Semaphore, -) -from .protocols import ( - BaseProtocol as BaseProtocol, - DatagramProtocol as DatagramProtocol, - Protocol as Protocol, - SubprocessProtocol as SubprocessProtocol, -) -from .queues import ( - LifoQueue as LifoQueue, - PriorityQueue as PriorityQueue, - Queue as Queue, - QueueEmpty as QueueEmpty, - QueueFull as QueueFull, -) -from .streams import ( - StreamReader as StreamReader, - StreamReaderProtocol as StreamReaderProtocol, - StreamWriter as StreamWriter, - open_connection as open_connection, - start_server as start_server, -) -from .subprocess import create_subprocess_exec as create_subprocess_exec, create_subprocess_shell as create_subprocess_shell -from .tasks import ( - ALL_COMPLETED as ALL_COMPLETED, - FIRST_COMPLETED as FIRST_COMPLETED, - FIRST_EXCEPTION as FIRST_EXCEPTION, - Task as Task, - as_completed as as_completed, - ensure_future as ensure_future, - gather as gather, - run_coroutine_threadsafe as run_coroutine_threadsafe, - shield as shield, - sleep as sleep, - wait as wait, - wait_for as wait_for, -) -from .transports import ( - BaseTransport as BaseTransport, - DatagramTransport as DatagramTransport, - ReadTransport as ReadTransport, - SubprocessTransport as SubprocessTransport, - Transport as Transport, - WriteTransport as WriteTransport, -) +# As at runtime, this depends on all submodules defining __all__ accurately. +from .base_events import * +from .coroutines import * +from .events import * +from .exceptions import * +from .futures import * +from .locks import * +from .protocols import * +from .queues import * +from .runners import * +from .streams import * +from .subprocess import * +from .tasks import * +from .threads import * +from .transports import * -if sys.version_info < (3, 11): - from .coroutines import coroutine as coroutine +if sys.version_info >= (3, 14): + from .graph import * -if sys.version_info >= (3, 9): - from .threads import to_thread as to_thread +if sys.version_info >= (3, 11): + from .taskgroups import * + from .timeouts import * -if sys.version_info >= (3, 8): - from .exceptions import ( - CancelledError as CancelledError, - IncompleteReadError as IncompleteReadError, - InvalidStateError as InvalidStateError, - LimitOverrunError as LimitOverrunError, - TimeoutError as TimeoutError, - ) +if sys.platform == "win32": + from .windows_events import * else: - from .futures import CancelledError as CancelledError, InvalidStateError as InvalidStateError, TimeoutError as TimeoutError - from .streams import IncompleteReadError as IncompleteReadError, LimitOverrunError as LimitOverrunError + from .unix_events import * + +if sys.version_info >= (3, 14): + from .events import _AbstractEventLoopPolicy -if sys.version_info >= (3, 8): - from .exceptions import SendfileNotAvailableError as SendfileNotAvailableError -elif sys.version_info >= (3, 7): - from .events import SendfileNotAvailableError as SendfileNotAvailableError + AbstractEventLoopPolicy = _AbstractEventLoopPolicy + +if sys.platform == "win32": + if sys.version_info >= (3, 14): + from .windows_events import _DefaultEventLoopPolicy, _WindowsProactorEventLoopPolicy, _WindowsSelectorEventLoopPolicy -if sys.version_info >= (3, 7): - from .events import get_running_loop as get_running_loop - from .protocols import BufferedProtocol as BufferedProtocol - from .runners import run as run - from .tasks import ( - _enter_task as _enter_task, - _leave_task as _leave_task, - _register_task as _register_task, - _unregister_task as _unregister_task, - all_tasks as all_tasks, - create_task as create_task, - current_task as current_task, - ) + DefaultEventLoopPolicy = _DefaultEventLoopPolicy + WindowsProactorEventLoopPolicy = _WindowsProactorEventLoopPolicy + WindowsSelectorEventLoopPolicy = _WindowsSelectorEventLoopPolicy +else: + if sys.version_info >= (3, 14): + from .unix_events import _DefaultEventLoopPolicy -DefaultEventLoopPolicy: Type[AbstractEventLoopPolicy] + DefaultEventLoopPolicy = _DefaultEventLoopPolicy if sys.platform == "win32": - from .windows_events import * + if sys.version_info >= (3, 14): + + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "future_discard_from_awaited_by", # from futures + "future_add_to_awaited_by", # from futures + "capture_call_graph", # from graph + "format_call_graph", # from graph + "print_call_graph", # from graph + "FrameCallGraphEntry", # from graph + "FutureCallGraph", # from graph + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "_DefaultEventLoopPolicy", # from windows_events + "_WindowsSelectorEventLoopPolicy", # from windows_events + "_WindowsProactorEventLoopPolicy", # from windows_events + "EventLoop", # from windows_events + ) + elif sys.version_info >= (3, 13): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + "EventLoop", # from windows_events + ) + elif sys.version_info >= (3, 12): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + ) + elif sys.version_info >= (3, 11): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + ) + else: + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "coroutine", # from coroutines + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + ) else: - from .streams import open_unix_connection as open_unix_connection, start_unix_server as start_unix_server - from .unix_events import ( - AbstractChildWatcher as AbstractChildWatcher, - FastChildWatcher as FastChildWatcher, - SafeChildWatcher as SafeChildWatcher, - SelectorEventLoop as SelectorEventLoop, - ) + if sys.version_info >= (3, 14): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "future_discard_from_awaited_by", # from futures + "future_add_to_awaited_by", # from futures + "capture_call_graph", # from graph + "format_call_graph", # from graph + "print_call_graph", # from graph + "FrameCallGraphEntry", # from graph + "FutureCallGraph", # from graph + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "EventLoop", # from unix_events + ) + elif sys.version_info >= (3, 13): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + "EventLoop", # from unix_events + ) + elif sys.version_info >= (3, 12): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + ) + elif sys.version_info >= (3, 11): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + ) + else: + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "coroutine", # from coroutines + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + ) - if sys.version_info >= (3, 8): - from .unix_events import MultiLoopChildWatcher as MultiLoopChildWatcher, ThreadedChildWatcher as ThreadedChildWatcher +_T_co = TypeVar("_T_co", covariant=True) + +# Aliases imported by multiple submodules in typeshed +if sys.version_info >= (3, 12): + _AwaitableLike: TypeAlias = Awaitable[_T_co] # noqa: Y047 + _CoroutineLike: TypeAlias = Coroutine[Any, Any, _T_co] # noqa: Y047 +else: + _AwaitableLike: TypeAlias = Generator[Any, None, _T_co] | Awaitable[_T_co] + _CoroutineLike: TypeAlias = Generator[Any, None, _T_co] | Coroutine[Any, Any, _T_co] diff --git a/stdlib/asyncio/base_events.pyi b/stdlib/asyncio/base_events.pyi index e804c2f5d3bd..29ecbdf7feba 100644 --- a/stdlib/asyncio/base_events.pyi +++ b/stdlib/asyncio/base_events.pyi @@ -1,29 +1,32 @@ import ssl import sys -from _typeshed import FileDescriptorLike -from abc import ABCMeta -from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle +from _typeshed import FileDescriptorLike, ReadableBuffer, WriteableBuffer +from asyncio import _AwaitableLike, _CoroutineLike +from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle, _TaskFactory from asyncio.futures import Future from asyncio.protocols import BaseProtocol from asyncio.tasks import Task -from asyncio.transports import BaseTransport -from collections.abc import Iterable -from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, Union, overload -from typing_extensions import Literal +from asyncio.transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport +from collections.abc import Callable, Iterable, Sequence +from concurrent.futures import Executor, ThreadPoolExecutor +from contextvars import Context +from socket import AddressFamily, AddressInfo, _Address, _GetAddrInfoResult, _RetAddress, socket +from typing import IO, Any, Literal, TypeAlias, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack -if sys.version_info >= (3, 7): - from contextvars import Context +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("BaseEventLoop", "Server") _T = TypeVar("_T") -_Context = Dict[str, Any] -_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] -_ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] -_TransProtPair = Tuple[BaseTransport, BaseProtocol] +_Ts = TypeVarTuple("_Ts") +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) +_Context: TypeAlias = dict[str, Any] +_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object] +_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] +_SSLContext: TypeAlias = bool | ssl.SSLContext | None class Server(AbstractServer): - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): def __init__( self, loop: AbstractEventLoop, @@ -32,340 +35,561 @@ class Server(AbstractServer): ssl_context: _SSLContext, backlog: int, ssl_handshake_timeout: float | None, + ssl_shutdown_timeout: float | None = None, ) -> None: ... else: - def __init__(self, loop: AbstractEventLoop, sockets: list[socket]) -> None: ... - if sys.version_info >= (3, 8): - @property - def sockets(self) -> Tuple[socket, ...]: ... - elif sys.version_info >= (3, 7): - @property - def sockets(self) -> list[socket]: ... - else: - sockets: list[socket] | None + def __init__( + self, + loop: AbstractEventLoop, + sockets: Iterable[socket], + protocol_factory: _ProtocolFactory, + ssl_context: _SSLContext, + backlog: int, + ssl_handshake_timeout: float | None, + ) -> None: ... + + if sys.version_info >= (3, 13): + def close_clients(self) -> None: ... + def abort_clients(self) -> None: ... -class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): + def get_loop(self) -> AbstractEventLoop: ... + def is_serving(self) -> bool: ... + async def start_serving(self) -> None: ... + async def serve_forever(self) -> None: ... + @property + def sockets(self) -> tuple[socket, ...]: ... + def close(self) -> None: ... + async def wait_closed(self) -> None: ... + +class BaseEventLoop(AbstractEventLoop): def run_forever(self) -> None: ... - # Can't use a union, see mypy issue # 1873. - @overload - def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... - @overload - def run_until_complete(self, future: Awaitable[_T]) -> _T: ... + def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ... def stop(self) -> None: ... def is_running(self) -> bool: ... def is_closed(self) -> bool: ... def close(self) -> None: ... async def shutdown_asyncgens(self) -> None: ... # Methods scheduling callbacks. All these return Handles. - if sys.version_info >= (3, 7): - def call_soon(self, callback: Callable[..., Any], *args: Any, context: Context | None = ...) -> Handle: ... - def call_later( - self, delay: float, callback: Callable[..., Any], *args: Any, context: Context | None = ... - ) -> TimerHandle: ... - def call_at( - self, when: float, callback: Callable[..., Any], *args: Any, context: Context | None = ... - ) -> TimerHandle: ... - else: - def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... - def call_later(self, delay: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... - def call_at(self, when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + def call_soon( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + def call_later( + self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... + def call_at( + self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... def time(self) -> float: ... # Future methods def create_future(self) -> Future[Any]: ... # Tasks methods - if sys.version_info >= (3, 8): - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T], *, name: object = ...) -> Task[_T]: ... + # `eager_start` is supported as an arbitrary kwarg starting in 3.13.3. + if sys.version_info >= (3, 13): + def create_task( + self, + coro: _CoroutineLike[_T], + *, + name: object = None, + context: Context | None = None, + eager_start: bool | None = None, + ) -> Task[_T]: ... + elif sys.version_info >= (3, 11): + def create_task(self, coro: _CoroutineLike[_T], *, name: object = None, context: Context | None = None) -> Task[_T]: ... else: - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T]) -> Task[_T]: ... - def set_task_factory(self, factory: Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None) -> None: ... - def get_task_factory(self) -> Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None: ... + def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: ... + + def set_task_factory(self, factory: _TaskFactory | None) -> None: ... + def get_task_factory(self) -> _TaskFactory | None: ... # Methods for interacting with threads - if sys.version_info >= (3, 7): - def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any, context: Context | None = ...) -> Handle: ... - else: - def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... - def run_in_executor(self, executor: Any, func: Callable[..., _T], *args: Any) -> Future[_T]: ... - def set_default_executor(self, executor: Any) -> None: ... + def call_soon_threadsafe( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ... + def set_default_executor(self, executor: ThreadPoolExecutor) -> None: ... # type: ignore[override] # Network I/O methods returning Futures. async def getaddrinfo( - self, host: str | None, port: str | int | None, *, family: int = ..., type: int = ..., proto: int = ..., flags: int = ... - ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... - async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = ...) -> tuple[str, str]: ... - if sys.version_info >= (3, 8): + self, + host: bytes | str | None, + port: bytes | str | int | None, + *, + family: int = 0, + type: int = 0, + proto: int = 0, + flags: int = 0, + ) -> _GetAddrInfoResult: ... + async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... + + if sys.version_info >= (3, 12): @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: None = ..., - local_addr: tuple[str, int] | None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - happy_eyeballs_delay: float | None = ..., - interleave: int | None = ..., - ) -> _TransProtPair: ... + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + all_errors: bool = False, + ) -> tuple[Transport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, sock: socket, - local_addr: None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - happy_eyeballs_delay: float | None = ..., - interleave: int | None = ..., - ) -> _TransProtPair: ... - elif sys.version_info >= (3, 7): + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + all_errors: bool = False, + ) -> tuple[Transport, _ProtocolT]: ... + elif sys.version_info >= (3, 11): @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: None = ..., - local_addr: tuple[str, int] | None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, sock: socket, - local_addr: None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... else: @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: None = ..., - local_addr: tuple[str, int] | None = ..., - server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, sock: socket, - local_addr: None = ..., - server_hostname: str | None = ..., - ) -> _TransProtPair: ... - if sys.version_info >= (3, 7): - async def sock_sendfile( - self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... - ) -> int: ... + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + if sys.version_info >= (3, 13): + # 3.13 added `keep_alive`. @overload async def create_server( self, protocol_factory: _ProtocolFactory, - host: str | Sequence[str] | None = ..., - port: int = ..., + host: str | Sequence[str] | None, + port: int, *, - family: int = ..., - flags: int = ..., - sock: None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - ssl_handshake_timeout: float | None = ..., - start_serving: bool = ..., + family: int = 0, + flags: int = 1, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... @overload async def create_server( self, protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + host: str | Sequence[str], + port: int | None = None, *, - family: int = ..., - flags: int = ..., - sock: socket = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - ssl_handshake_timeout: float | None = ..., - start_serving: bool = ..., + family: int = 0, + flags: int = 1, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... - async def connect_accepted_socket( + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + *, + port: int, + family: int = 0, + flags: int = 1, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( self, protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = 0, + flags: int = 1, sock: socket, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + elif sys.version_info >= (3, 11): + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None, + port: int, *, - ssl: _SSLContext = ..., - ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... - async def sendfile( - self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... - ) -> int: ... - async def start_tls( + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( self, - transport: BaseTransport, - protocol: BaseProtocol, - sslcontext: ssl.SSLContext, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str], + port: int | None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, *, - server_side: bool = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> BaseTransport: ... + port: int, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... else: @overload async def create_server( self, protocol_factory: _ProtocolFactory, - host: str | Sequence[str] | None = ..., - port: int = ..., + host: str | Sequence[str] | None, + port: int, *, - family: int = ..., - flags: int = ..., - sock: None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... @overload async def create_server( self, protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + host: str | Sequence[str], + port: int | None = None, *, - family: int = ..., - flags: int = ..., + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + *, + port: int, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, sock: socket, - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... + + if sys.version_info >= (3, 11): + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> Transport | None: ... + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ) -> Transport | None: ... async def connect_accepted_socket( - self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ... - ) -> _TransProtPair: ... + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool | None = True + ) -> int: ... + async def sendfile( + self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True + ) -> int: ... if sys.version_info >= (3, 11): - async def create_datagram_endpoint( + async def create_datagram_endpoint( # type: ignore[override] self, - protocol_factory: _ProtocolFactory, - local_addr: tuple[str, int] | None = ..., - remote_addr: tuple[str, int] | None = ..., + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | str | None = None, + remote_addr: tuple[str, int] | str | None = None, *, - family: int = ..., - proto: int = ..., - flags: int = ..., - reuse_port: bool | None = ..., - allow_broadcast: bool | None = ..., - sock: socket | None = ..., - ) -> _TransProtPair: ... + family: int = 0, + proto: int = 0, + flags: int = 0, + reuse_port: bool | None = None, + allow_broadcast: bool | None = None, + sock: socket | None = None, + ) -> tuple[DatagramTransport, _ProtocolT]: ... else: async def create_datagram_endpoint( self, - protocol_factory: _ProtocolFactory, - local_addr: tuple[str, int] | None = ..., - remote_addr: tuple[str, int] | None = ..., + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | str | None = None, + remote_addr: tuple[str, int] | str | None = None, *, - family: int = ..., - proto: int = ..., - flags: int = ..., + family: int = 0, + proto: int = 0, + flags: int = 0, reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - allow_broadcast: bool | None = ..., - sock: socket | None = ..., - ) -> _TransProtPair: ... + reuse_port: bool | None = None, + allow_broadcast: bool | None = None, + sock: socket | None = None, + ) -> tuple[DatagramTransport, _ProtocolT]: ... # Pipes and subprocesses. - async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... - async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[ReadTransport, _ProtocolT]: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[WriteTransport, _ProtocolT]: ... async def subprocess_shell( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], cmd: bytes | str, *, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., - text: Literal[False, None] = ..., + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... async def subprocess_exec( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], program: Any, *args: Any, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, **kwargs: Any, - ) -> _TransProtPair: ... - def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... - def remove_reader(self, fd: FileDescriptorLike) -> None: ... - def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... - def remove_writer(self, fd: FileDescriptorLike) -> None: ... - # Completion based I/O methods returning Futures prior to 3.7 - if sys.version_info >= (3, 7): - async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... - async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... - async def sock_sendall(self, sock: socket, data: bytes) -> None: ... - async def sock_connect(self, sock: socket, address: _Address) -> None: ... - async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... - else: - def sock_recv(self, sock: socket, nbytes: int) -> Future[bytes]: ... - def sock_sendall(self, sock: socket, data: bytes) -> Future[None]: ... - def sock_connect(self, sock: socket, address: _Address) -> Future[None]: ... - def sock_accept(self, sock: socket) -> Future[tuple[socket, _RetAddress]]: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def remove_reader(self, fd: FileDescriptorLike) -> bool: ... + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def remove_writer(self, fd: FileDescriptorLike) -> bool: ... + # The sock_* methods (and probably some others) are not actually implemented on + # BaseEventLoop, only on subclasses. We list them here for now for convenience. + async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... + async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ... + async def sock_sendall(self, sock: socket, data: ReadableBuffer) -> None: ... + async def sock_connect(self, sock: socket, address: _Address) -> None: ... + async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... + if sys.version_info >= (3, 11): + async def sock_recvfrom(self, sock: socket, bufsize: int) -> tuple[bytes, _RetAddress]: ... + async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = 0) -> tuple[int, _RetAddress]: ... + async def sock_sendto(self, sock: socket, data: ReadableBuffer, address: _Address) -> int: ... # Signal handling. - def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... + def add_signal_handler(self, sig: int, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... def remove_signal_handler(self, sig: int) -> bool: ... # Error handlers. def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: ... @@ -375,5 +599,9 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): # Debug flag management. def get_debug(self) -> bool: ... def set_debug(self, enabled: bool) -> None: ... - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 12): + async def shutdown_default_executor(self, timeout: float | None = None) -> None: ... + else: async def shutdown_default_executor(self) -> None: ... + + def __del__(self) -> None: ... diff --git a/stdlib/asyncio/base_futures.pyi b/stdlib/asyncio/base_futures.pyi index 72ba6163e9d3..2cd0f2e3a7e4 100644 --- a/stdlib/asyncio/base_futures.pyi +++ b/stdlib/asyncio/base_futures.pyi @@ -1,22 +1,17 @@ -import sys -from typing import Any, Callable, Sequence -from typing_extensions import Literal - -if sys.version_info >= (3, 7): - from contextvars import Context +from _asyncio import Future +from collections.abc import Callable, Sequence +from contextvars import Context +from typing import Any, Final +from typing_extensions import TypeIs from . import futures -_PENDING: Literal["PENDING"] # undocumented -_CANCELLED: Literal["CANCELLED"] # undocumented -_FINISHED: Literal["FINISHED"] # undocumented - -def isfuture(obj: object) -> bool: ... - -if sys.version_info >= (3, 7): - def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented +__all__ = () -else: - def _format_callbacks(cb: Sequence[Callable[[futures.Future[Any]], None]]) -> str: ... # undocumented +_PENDING: Final = "PENDING" # undocumented +_CANCELLED: Final = "CANCELLED" # undocumented +_FINISHED: Final = "FINISHED" # undocumented +def isfuture(obj: object) -> TypeIs[Future[Any]]: ... +def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented def _future_repr_info(future: futures.Future[Any]) -> list[str]: ... # undocumented diff --git a/stdlib/asyncio/base_subprocess.pyi b/stdlib/asyncio/base_subprocess.pyi index 096bce60f7e3..36f0f6099cbc 100644 --- a/stdlib/asyncio/base_subprocess.pyi +++ b/stdlib/asyncio/base_subprocess.pyi @@ -1,13 +1,13 @@ import subprocess from collections import deque -from typing import IO, Any, Callable, Optional, Sequence, Tuple, Union +from collections.abc import Callable, Sequence +from typing import IO, Any, TypeAlias from . import events, futures, protocols, transports -_File = Optional[Union[int, IO[Any]]] +_File: TypeAlias = int | IO[Any] | None class BaseSubprocessTransport(transports.SubprocessTransport): - _closed: bool # undocumented _protocol: protocols.SubprocessProtocol # undocumented _loop: events.AbstractEventLoop # undocumented @@ -15,7 +15,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport): _pid: int | None # undocumented _returncode: int | None # undocumented _exit_waiters: list[futures.Future[Any]] # undocumented - _pending_calls: deque[tuple[Callable[..., Any], Tuple[Any, ...]]] # undocumented + _pending_calls: deque[tuple[Callable[..., Any], tuple[Any, ...]]] # undocumented _pipes: dict[int, _File] # undocumented _finished: bool # undocumented def __init__( @@ -28,8 +28,8 @@ class BaseSubprocessTransport(transports.SubprocessTransport): stdout: _File, stderr: _File, bufsize: int, - waiter: futures.Future[Any] | None = ..., - extra: Any | None = ..., + waiter: futures.Future[Any] | None = None, + extra: Any | None = None, **kwargs: Any, ) -> None: ... def _start( @@ -42,32 +42,21 @@ class BaseSubprocessTransport(transports.SubprocessTransport): bufsize: int, **kwargs: Any, ) -> None: ... # undocumented - def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... - def get_protocol(self) -> protocols.BaseProtocol: ... - def is_closing(self) -> bool: ... - def close(self) -> None: ... def get_pid(self) -> int | None: ... # type: ignore[override] - def get_returncode(self) -> int | None: ... def get_pipe_transport(self, fd: int) -> _File: ... # type: ignore[override] def _check_proc(self) -> None: ... # undocumented - def send_signal(self, signal: int) -> None: ... # type: ignore[override] - def terminate(self) -> None: ... - def kill(self) -> None: ... + def send_signal(self, signal: int) -> None: ... async def _connect_pipes(self, waiter: futures.Future[Any] | None) -> None: ... # undocumented - def _call(self, cb: Callable[..., Any], *data: Any) -> None: ... # undocumented + def _call(self, cb: Callable[..., object], *data: Any) -> None: ... # undocumented def _pipe_connection_lost(self, fd: int, exc: BaseException | None) -> None: ... # undocumented def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented def _process_exited(self, returncode: int) -> None: ... # undocumented async def _wait(self) -> int: ... # undocumented def _try_finish(self) -> None: ... # undocumented def _call_connection_lost(self, exc: BaseException | None) -> None: ... # undocumented + def __del__(self) -> None: ... class WriteSubprocessPipeProto(protocols.BaseProtocol): # undocumented def __init__(self, proc: BaseSubprocessTransport, fd: int) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... - def connection_lost(self, exc: BaseException | None) -> None: ... - def pause_writing(self) -> None: ... - def resume_writing(self) -> None: ... -class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): # undocumented - def data_received(self, data: bytes) -> None: ... +class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): ... # undocumented diff --git a/stdlib/asyncio/base_tasks.pyi b/stdlib/asyncio/base_tasks.pyi index 42e952ffacaf..5b010a9efe3d 100644 --- a/stdlib/asyncio/base_tasks.pyi +++ b/stdlib/asyncio/base_tasks.pyi @@ -1,9 +1,17 @@ +import sys from _typeshed import StrOrBytesPath from types import FrameType from typing import Any -from . import tasks +from .tasks import Task -def _task_repr_info(task: tasks.Task[Any]) -> list[str]: ... # undocumented -def _task_get_stack(task: tasks.Task[Any], limit: int | None) -> list[FrameType]: ... # undocumented -def _task_print_stack(task: tasks.Task[Any], limit: int | None, file: StrOrBytesPath) -> None: ... # undocumented +def _task_repr_info(task: Task[Any]) -> list[str]: ... # undocumented + +if sys.version_info >= (3, 13): + def _task_repr(task: Task[Any]) -> str: ... # undocumented + +elif sys.version_info >= (3, 11): + def _task_repr(self: Task[Any]) -> str: ... # undocumented + +def _task_get_stack(task: Task[Any], limit: int | None) -> list[FrameType]: ... # undocumented +def _task_print_stack(task: Task[Any], limit: int | None, file: StrOrBytesPath) -> None: ... # undocumented diff --git a/stdlib/asyncio/compat.pyi b/stdlib/asyncio/compat.pyi deleted file mode 100644 index 1beeea9d6c3f..000000000000 --- a/stdlib/asyncio/compat.pyi +++ /dev/null @@ -1,7 +0,0 @@ -import sys - -if sys.version_info < (3, 7): - PY34: bool - PY35: bool - PY352: bool - def flatten_list_bytes(list_of_data: list[bytes]) -> bytes: ... diff --git a/stdlib/asyncio/constants.pyi b/stdlib/asyncio/constants.pyi index 2010fe9123ae..5c6456b0e9c0 100644 --- a/stdlib/asyncio/constants.pyi +++ b/stdlib/asyncio/constants.pyi @@ -1,14 +1,20 @@ import enum import sys +from typing import Final -LOG_THRESHOLD_FOR_CONNLOST_WRITES: int -ACCEPT_RETRY_DELAY: int -DEBUG_STACK_DEPTH: int -if sys.version_info >= (3, 7): - SSL_HANDSHAKE_TIMEOUT: float - SENDFILE_FALLBACK_READBUFFER_SIZE: int +LOG_THRESHOLD_FOR_CONNLOST_WRITES: Final = 5 +ACCEPT_RETRY_DELAY: Final = 1 +DEBUG_STACK_DEPTH: Final = 10 +SSL_HANDSHAKE_TIMEOUT: float +SENDFILE_FALLBACK_READBUFFER_SIZE: Final = 262144 +if sys.version_info >= (3, 11): + SSL_SHUTDOWN_TIMEOUT: float + FLOW_CONTROL_HIGH_WATER_SSL_READ: Final = 256 + FLOW_CONTROL_HIGH_WATER_SSL_WRITE: Final = 512 +if sys.version_info >= (3, 12): + THREAD_JOIN_TIMEOUT: Final = 300 class _SendfileMode(enum.Enum): - UNSUPPORTED: int - TRY_NATIVE: int - FALLBACK: int + UNSUPPORTED = 1 + TRY_NATIVE = 2 + FALLBACK = 3 diff --git a/stdlib/asyncio/coroutines.pyi b/stdlib/asyncio/coroutines.pyi index 6c2d8179d1f1..8fafa2e75716 100644 --- a/stdlib/asyncio/coroutines.pyi +++ b/stdlib/asyncio/coroutines.pyi @@ -1,20 +1,45 @@ import sys -import types -from collections.abc import Coroutine -from typing import Any -from typing_extensions import TypeGuard +from collections.abc import Awaitable, Callable, Coroutine +from typing import Any, ParamSpec, TypeGuard, TypeVar, overload +from typing_extensions import TypeIs, deprecated -if sys.version_info < (3, 11): - from collections.abc import Callable - from typing import TypeVar +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ("iscoroutinefunction", "iscoroutine") +else: + __all__ = ("coroutine", "iscoroutinefunction", "iscoroutine") - _F = TypeVar("_F", bound=Callable[..., Any]) - def coroutine(func: _F) -> _F: ... +_T = TypeVar("_T") +_FunctionT = TypeVar("_FunctionT", bound=Callable[..., Any]) +_P = ParamSpec("_P") -def iscoroutinefunction(func: object) -> bool: ... +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `async def` instead.") + def coroutine(func: _FunctionT) -> _FunctionT: ... -if sys.version_info >= (3, 8): - def iscoroutine(obj: object) -> TypeGuard[Coroutine[Any, Any, Any]]: ... +def iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: ... +if sys.version_info >= (3, 11): + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... else: - def iscoroutine(obj: object) -> TypeGuard[types.GeneratorType[Any, Any, Any] | Coroutine[Any, Any, Any]]: ... + # Sometimes needed in Python < 3.11 due to the fact that it supports @coroutine + # which was removed in 3.11 which the inspect version doesn't support. + @overload + def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... + @overload + def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... + @overload + def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... + @overload + def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... diff --git a/stdlib/asyncio/events.pyi b/stdlib/asyncio/events.pyi index 6ef9117b6491..4d1cf3138c7e 100644 --- a/stdlib/asyncio/events.pyi +++ b/stdlib/asyncio/events.pyi @@ -1,81 +1,136 @@ import ssl import sys -from _typeshed import FileDescriptorLike, Self +from _asyncio import ( + _get_running_loop as _get_running_loop, + _set_running_loop as _set_running_loop, + get_event_loop as get_event_loop, + get_running_loop as get_running_loop, +) +from _typeshed import FileDescriptorLike, ReadableBuffer, StrPath, Unused, WriteableBuffer from abc import ABCMeta, abstractmethod -from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, Union, overload -from typing_extensions import Literal +from collections.abc import Callable, Sequence +from concurrent.futures import Executor +from contextvars import Context +from socket import AddressFamily, AddressInfo, _Address, _GetAddrInfoResult, _RetAddress, socket +from typing import IO, Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack, deprecated +from . import _AwaitableLike, _CoroutineLike from .base_events import Server from .futures import Future from .protocols import BaseProtocol from .tasks import Task -from .transports import BaseTransport -from .unix_events import AbstractChildWatcher +from .transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport -if sys.version_info >= (3, 7): - from contextvars import Context +if sys.version_info < (3, 14): + from .unix_events import AbstractChildWatcher + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 14): + __all__ = ( + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) +else: + __all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) _T = TypeVar("_T") -_Context = Dict[str, Any] -_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] -_ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] -_TransProtPair = Tuple[BaseTransport, BaseProtocol] +_Ts = TypeVarTuple("_Ts") +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) +_Context: TypeAlias = dict[str, Any] +_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object] +_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] +_SSLContext: TypeAlias = bool | ssl.SSLContext | None + +@type_check_only +class _TaskFactory(Protocol): + def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ... class Handle: - _cancelled = False + __slots__ = ("_callback", "_args", "_cancelled", "_loop", "_source_traceback", "_repr", "__weakref__", "_context") + _cancelled: bool _args: Sequence[Any] - if sys.version_info >= (3, 7): - def __init__( - self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Context | None = ... - ) -> None: ... - else: - def __init__(self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop) -> None: ... - def __repr__(self) -> str: ... + def __init__( + self, callback: Callable[..., object], args: Sequence[Any], loop: AbstractEventLoop, context: Context | None = None + ) -> None: ... def cancel(self) -> None: ... def _run(self) -> None: ... - if sys.version_info >= (3, 7): - def cancelled(self) -> bool: ... + def cancelled(self) -> bool: ... + if sys.version_info >= (3, 12): + def get_context(self) -> Context: ... class TimerHandle(Handle): - if sys.version_info >= (3, 7): - def __init__( - self, - when: float, - callback: Callable[..., Any], - args: Sequence[Any], - loop: AbstractEventLoop, - context: Context | None = ..., - ) -> None: ... - else: - def __init__(self, when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop) -> None: ... + __slots__ = ["_scheduled", "_when"] + def __init__( + self, + when: float, + callback: Callable[..., object], + args: Sequence[Any], + loop: AbstractEventLoop, + context: Context | None = None, + ) -> None: ... def __hash__(self) -> int: ... - if sys.version_info >= (3, 7): - def when(self) -> float: ... + def when(self) -> float: ... + def __lt__(self, other: TimerHandle) -> bool: ... + def __le__(self, other: TimerHandle) -> bool: ... + def __gt__(self, other: TimerHandle) -> bool: ... + def __ge__(self, other: TimerHandle) -> bool: ... + def __eq__(self, other: object) -> bool: ... class AbstractServer: + @abstractmethod def close(self) -> None: ... - if sys.version_info >= (3, 7): - async def __aenter__(self: Self) -> Self: ... - async def __aexit__(self, *exc: Any) -> None: ... - def get_loop(self) -> AbstractEventLoop: ... - def is_serving(self) -> bool: ... - async def start_serving(self) -> None: ... - async def serve_forever(self) -> None: ... + if sys.version_info >= (3, 13): + @abstractmethod + def close_clients(self) -> None: ... + @abstractmethod + def abort_clients(self) -> None: ... + + async def __aenter__(self) -> Self: ... + async def __aexit__(self, *exc: Unused) -> None: ... + @abstractmethod + def get_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def is_serving(self) -> bool: ... + @abstractmethod + async def start_serving(self) -> None: ... + @abstractmethod + async def serve_forever(self) -> None: ... + @abstractmethod async def wait_closed(self) -> None: ... -class AbstractEventLoop(metaclass=ABCMeta): +class AbstractEventLoop: slow_callback_duration: float @abstractmethod def run_forever(self) -> None: ... - # Can't use a union, see mypy issue # 1873. - @overload @abstractmethod - def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... - @overload - @abstractmethod - def run_until_complete(self, future: Awaitable[_T]) -> _T: ... + def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ... @abstractmethod def stop(self) -> None: ... @abstractmethod @@ -87,362 +142,590 @@ class AbstractEventLoop(metaclass=ABCMeta): @abstractmethod async def shutdown_asyncgens(self) -> None: ... # Methods scheduling callbacks. All these return Handles. + # "context" added in 3.9.10/3.10.2 for call_* @abstractmethod - def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + def call_soon( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... @abstractmethod - def call_later(self, delay: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + def call_later( + self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... @abstractmethod - def call_at(self, when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + def call_at( + self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... @abstractmethod def time(self) -> float: ... # Future methods @abstractmethod def create_future(self) -> Future[Any]: ... # Tasks methods - if sys.version_info >= (3, 8): + # `eager_start` is supported as an arbitrary kwarg starting in 3.13.3. + if sys.version_info >= (3, 13): + @abstractmethod + def create_task( + self, + coro: _CoroutineLike[_T], + *, + name: str | None = None, + context: Context | None = None, + eager_start: bool | None = None, + ) -> Task[_T]: ... + elif sys.version_info >= (3, 11): @abstractmethod - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T], *, name: str | None = ...) -> Task[_T]: ... + def create_task( + self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None + ) -> Task[_T]: ... else: @abstractmethod - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T]) -> Task[_T]: ... + def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... + @abstractmethod - def set_task_factory(self, factory: Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None) -> None: ... + def set_task_factory(self, factory: _TaskFactory | None) -> None: ... @abstractmethod - def get_task_factory(self) -> Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None: ... + def get_task_factory(self) -> _TaskFactory | None: ... # Methods for interacting with threads + # "context" added in 3.9.10/3.10.2 @abstractmethod - def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + def call_soon_threadsafe( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... @abstractmethod - def run_in_executor(self, executor: Any, func: Callable[..., _T], *args: Any) -> Future[_T]: ... + def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ... @abstractmethod - def set_default_executor(self, executor: Any) -> None: ... + def set_default_executor(self, executor: Executor) -> None: ... # Network I/O methods returning Futures. @abstractmethod async def getaddrinfo( - self, host: str | None, port: str | int | None, *, family: int = ..., type: int = ..., proto: int = ..., flags: int = ... - ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... + self, + host: bytes | str | None, + port: bytes | str | int | None, + *, + family: int = 0, + type: int = 0, + proto: int = 0, + flags: int = 0, + ) -> _GetAddrInfoResult: ... @abstractmethod - async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = ...) -> tuple[str, str]: ... - if sys.version_info >= (3, 8): + async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... + + if sys.version_info >= (3, 11): @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: None = ..., - local_addr: tuple[str, int] | None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - happy_eyeballs_delay: float | None = ..., - interleave: int | None = ..., - ) -> _TransProtPair: ... + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, sock: socket, - local_addr: None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - happy_eyeballs_delay: float | None = ..., - interleave: int | None = ..., - ) -> _TransProtPair: ... - elif sys.version_info >= (3, 7): + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: None = ..., - local_addr: tuple[str, int] | None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, sock: socket, - local_addr: None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... - else: + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + if sys.version_info >= (3, 13): + # 3.13 added `keep_alive`. @overload @abstractmethod - async def create_connection( + async def create_server( self, protocol_factory: _ProtocolFactory, - host: str = ..., - port: int = ..., + host: str | Sequence[str] | None, + port: int, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: None = ..., - local_addr: tuple[str, int] | None = ..., - server_hostname: str | None = ..., - ) -> _TransProtPair: ... + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... @overload @abstractmethod - async def create_connection( + async def create_server( self, protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + host: str | Sequence[str], + port: int | None = None, *, - ssl: _SSLContext = ..., - family: int = ..., - proto: int = ..., - flags: int = ..., - sock: socket, - local_addr: None = ..., - server_hostname: str | None = ..., - ) -> _TransProtPair: ... - if sys.version_info >= (3, 7): - @abstractmethod - async def sock_sendfile( - self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... - ) -> int: ... + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... @overload @abstractmethod async def create_server( self, protocol_factory: _ProtocolFactory, - host: str | Sequence[str] | None = ..., - port: int = ..., + host: None = None, *, - family: int = ..., - flags: int = ..., - sock: None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - ssl_handshake_timeout: float | None = ..., - start_serving: bool = ..., + port: int, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... @overload @abstractmethod async def create_server( self, protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + host: None = None, + port: None = None, *, - family: int = ..., - flags: int = ..., - sock: socket = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - ssl_handshake_timeout: float | None = ..., - start_serving: bool = ..., + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... - async def create_unix_connection( + elif sys.version_info >= (3, 11): + @overload + @abstractmethod + async def create_server( self, protocol_factory: _ProtocolFactory, - path: str | None = ..., + host: str | Sequence[str] | None, + port: int, *, - ssl: _SSLContext = ..., - sock: socket | None = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... - async def create_unix_server( + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + @abstractmethod + async def create_server( self, protocol_factory: _ProtocolFactory, - path: str | None = ..., + host: str | Sequence[str], + port: int | None = None, *, - sock: socket | None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - ssl_handshake_timeout: float | None = ..., - start_serving: bool = ..., + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... + @overload @abstractmethod - async def sendfile( - self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... - ) -> int: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + *, + port: int, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload @abstractmethod - async def start_tls( + async def create_server( self, - transport: BaseTransport, - protocol: BaseProtocol, - sslcontext: ssl.SSLContext, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, *, - server_side: bool = ..., - server_hostname: str | None = ..., - ssl_handshake_timeout: float | None = ..., - ) -> BaseTransport: ... + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... else: @overload @abstractmethod async def create_server( self, protocol_factory: _ProtocolFactory, - host: str | Sequence[str] | None = ..., - port: int = ..., + host: str | Sequence[str] | None, + port: int, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str], + port: int | None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, *, - family: int = ..., - flags: int = ..., - sock: None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., + port: int, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... @overload @abstractmethod async def create_server( self, protocol_factory: _ProtocolFactory, - host: None = ..., - port: None = ..., + host: None = None, + port: None = None, *, - family: int = ..., - flags: int = ..., + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, sock: socket, - backlog: int = ..., - ssl: _SSLContext = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... - async def create_unix_connection( + + if sys.version_info >= (3, 11): + @abstractmethod + async def start_tls( + self, + transport: WriteTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> Transport | None: ... + else: + @abstractmethod + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ) -> Transport | None: ... + + if sys.version_info >= (3, 13): + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: StrPath | None = None, + *, + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + cleanup_socket: bool = True, + ) -> Server: ... + elif sys.version_info >= (3, 11): + async def create_unix_server( self, protocol_factory: _ProtocolFactory, - path: str, + path: StrPath | None = None, *, - ssl: _SSLContext = ..., - sock: socket | None = ..., - server_hostname: str | None = ..., - ) -> _TransProtPair: ... + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + else: async def create_unix_server( self, protocol_factory: _ProtocolFactory, - path: str, + path: StrPath | None = None, *, - sock: socket | None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, ) -> Server: ... + + if sys.version_info >= (3, 11): + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + if sys.version_info >= (3, 11): + async def create_unix_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + path: str | None = None, + *, + ssl: _SSLContext = None, + sock: socket | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + async def create_unix_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + path: str | None = None, + *, + ssl: _SSLContext = None, + sock: socket | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + @abstractmethod + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool | None = None + ) -> int: ... + @abstractmethod + async def sendfile( + self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True + ) -> int: ... @abstractmethod async def create_datagram_endpoint( self, - protocol_factory: _ProtocolFactory, - local_addr: tuple[str, int] | None = ..., - remote_addr: tuple[str, int] | None = ..., + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | str | None = None, + remote_addr: tuple[str, int] | str | None = None, *, - family: int = ..., - proto: int = ..., - flags: int = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - allow_broadcast: bool | None = ..., - sock: socket | None = ..., - ) -> _TransProtPair: ... + family: int = 0, + proto: int = 0, + flags: int = 0, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + allow_broadcast: bool | None = None, + sock: socket | None = None, + ) -> tuple[DatagramTransport, _ProtocolT]: ... # Pipes and subprocesses. @abstractmethod - async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[ReadTransport, _ProtocolT]: ... @abstractmethod - async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[WriteTransport, _ProtocolT]: ... @abstractmethod async def subprocess_shell( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], cmd: bytes | str, *, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., - text: Literal[False, None] = ..., + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... @abstractmethod async def subprocess_exec( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], program: Any, *args: Any, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... @abstractmethod - def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... @abstractmethod - def remove_reader(self, fd: FileDescriptorLike) -> None: ... + def remove_reader(self, fd: FileDescriptorLike) -> bool: ... @abstractmethod - def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... @abstractmethod - def remove_writer(self, fd: FileDescriptorLike) -> None: ... - # Completion based I/O methods returning Futures prior to 3.7 - if sys.version_info >= (3, 7): - @abstractmethod - async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... - @abstractmethod - async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... - @abstractmethod - async def sock_sendall(self, sock: socket, data: bytes) -> None: ... - @abstractmethod - async def sock_connect(self, sock: socket, address: _Address) -> None: ... - @abstractmethod - async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... - else: - @abstractmethod - def sock_recv(self, sock: socket, nbytes: int) -> Future[bytes]: ... + def remove_writer(self, fd: FileDescriptorLike) -> bool: ... + @abstractmethod + async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... + @abstractmethod + async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ... + @abstractmethod + async def sock_sendall(self, sock: socket, data: ReadableBuffer) -> None: ... + @abstractmethod + async def sock_connect(self, sock: socket, address: _Address) -> None: ... + @abstractmethod + async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... + if sys.version_info >= (3, 11): @abstractmethod - def sock_sendall(self, sock: socket, data: bytes) -> Future[None]: ... + async def sock_recvfrom(self, sock: socket, bufsize: int) -> tuple[bytes, _RetAddress]: ... @abstractmethod - def sock_connect(self, sock: socket, address: _Address) -> Future[None]: ... + async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = 0) -> tuple[int, _RetAddress]: ... @abstractmethod - def sock_accept(self, sock: socket) -> Future[tuple[socket, _RetAddress]]: ... + async def sock_sendto(self, sock: socket, data: ReadableBuffer, address: _Address) -> int: ... # Signal handling. @abstractmethod - def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... + def add_signal_handler(self, sig: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... @abstractmethod def remove_signal_handler(self, sig: int) -> bool: ... # Error handlers. @@ -459,40 +742,62 @@ class AbstractEventLoop(metaclass=ABCMeta): def get_debug(self) -> bool: ... @abstractmethod def set_debug(self, enabled: bool) -> None: ... - if sys.version_info >= (3, 9): + @abstractmethod + async def shutdown_default_executor(self) -> None: ... + +if sys.version_info >= (3, 14): + class _AbstractEventLoopPolicy: + @abstractmethod + def get_event_loop(self) -> AbstractEventLoop: ... @abstractmethod - async def shutdown_default_executor(self) -> None: ... + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod + def new_event_loop(self) -> AbstractEventLoop: ... -class AbstractEventLoopPolicy(metaclass=ABCMeta): - @abstractmethod - def get_event_loop(self) -> AbstractEventLoop: ... - @abstractmethod - def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... - @abstractmethod - def new_event_loop(self) -> AbstractEventLoop: ... - # Child processes handling (Unix only). - @abstractmethod - def get_child_watcher(self) -> AbstractChildWatcher: ... - @abstractmethod - def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... +else: + @type_check_only + class _AbstractEventLoopPolicy: + @abstractmethod + def get_event_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod + def new_event_loop(self) -> AbstractEventLoop: ... + # Child processes handling (Unix only). + @abstractmethod + @deprecated("Deprecated; removed in Python 3.14.") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + @deprecated("Deprecated; removed in Python 3.14.") + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + + AbstractEventLoopPolicy = _AbstractEventLoopPolicy + +if sys.version_info >= (3, 14): + class _BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): + def get_event_loop(self) -> AbstractEventLoop: ... + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + def new_event_loop(self) -> AbstractEventLoop: ... + +else: + class BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): + def get_event_loop(self) -> AbstractEventLoop: ... + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + def new_event_loop(self) -> AbstractEventLoop: ... -class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): - def __init__(self) -> None: ... - def get_event_loop(self) -> AbstractEventLoop: ... - def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... - def new_event_loop(self) -> AbstractEventLoop: ... +if sys.version_info >= (3, 14): + def _get_event_loop_policy() -> _AbstractEventLoopPolicy: ... + def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... -def get_event_loop_policy() -> AbstractEventLoopPolicy: ... -def set_event_loop_policy(policy: AbstractEventLoopPolicy | None) -> None: ... -def get_event_loop() -> AbstractEventLoop: ... +@deprecated("Deprecated; will be removed in Python 3.16.") +def get_event_loop_policy() -> _AbstractEventLoopPolicy: ... +@deprecated("Deprecated; will be removed in Python 3.16.") +def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... def set_event_loop(loop: AbstractEventLoop | None) -> None: ... def new_event_loop() -> AbstractEventLoop: ... -def get_child_watcher() -> AbstractChildWatcher: ... -def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... -def _set_running_loop(__loop: AbstractEventLoop | None) -> None: ... -def _get_running_loop() -> AbstractEventLoop: ... -if sys.version_info >= (3, 7): - def get_running_loop() -> AbstractEventLoop: ... - if sys.version_info < (3, 8): - class SendfileNotAvailableError(RuntimeError): ... +if sys.version_info < (3, 14): + @deprecated("Deprecated; removed in Python 3.14.") + def get_child_watcher() -> AbstractChildWatcher: ... + @deprecated("Deprecated; removed in Python 3.14.") + def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... diff --git a/stdlib/asyncio/exceptions.pyi b/stdlib/asyncio/exceptions.pyi index 5b99966329ac..759838f45de4 100644 --- a/stdlib/asyncio/exceptions.pyi +++ b/stdlib/asyncio/exceptions.pyi @@ -1,14 +1,44 @@ import sys -if sys.version_info >= (3, 8): - class CancelledError(BaseException): ... +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ( + "BrokenBarrierError", + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", + ) +else: + __all__ = ( + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", + ) + +class CancelledError(BaseException): ... + +if sys.version_info >= (3, 11): + from builtins import TimeoutError as TimeoutError +else: class TimeoutError(Exception): ... - class InvalidStateError(Exception): ... - class SendfileNotAvailableError(RuntimeError): ... - class IncompleteReadError(EOFError): - expected: int | None - partial: bytes - def __init__(self, partial: bytes, expected: int | None) -> None: ... - class LimitOverrunError(Exception): - consumed: int - def __init__(self, message: str, consumed: int) -> None: ... + +class InvalidStateError(Exception): ... +class SendfileNotAvailableError(RuntimeError): ... + +class IncompleteReadError(EOFError): + expected: int | None + partial: bytes + def __init__(self, partial: bytes, expected: int | None) -> None: ... + +class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... + +if sys.version_info >= (3, 11): + class BrokenBarrierError(RuntimeError): ... diff --git a/stdlib/asyncio/format_helpers.pyi b/stdlib/asyncio/format_helpers.pyi index be80efe266b1..ff830a3b73d4 100644 --- a/stdlib/asyncio/format_helpers.pyi +++ b/stdlib/asyncio/format_helpers.pyi @@ -1,20 +1,31 @@ import functools import sys import traceback +from collections.abc import Iterable from types import FrameType, FunctionType -from typing import Any, Iterable, Union, overload +from typing import Any, TypeAlias, overload, type_check_only +@type_check_only class _HasWrapper: __wrapper__: _HasWrapper | FunctionType -_FuncType = Union[FunctionType, _HasWrapper, functools.partial[Any], functools.partialmethod[Any]] +_FuncType: TypeAlias = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any] -if sys.version_info >= (3, 7): - @overload - def _get_function_source(func: _FuncType) -> tuple[str, int]: ... - @overload - def _get_function_source(func: object) -> tuple[str, int] | None: ... +@overload +def _get_function_source(func: _FuncType) -> tuple[str, int]: ... +@overload +def _get_function_source(func: object) -> tuple[str, int] | None: ... + +if sys.version_info >= (3, 13): + def _format_callback_source(func: object, args: Iterable[Any], *, debug: bool = False) -> str: ... + def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False) -> str: ... + def _format_callback( + func: object, args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False, suffix: str = "" + ) -> str: ... + +else: def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any]) -> str: ... - def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = ...) -> str: ... - def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> traceback.StackSummary: ... + def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = "") -> str: ... + +def extract_stack(f: FrameType | None = None, limit: int | None = None) -> traceback.StackSummary: ... diff --git a/stdlib/asyncio/futures.pyi b/stdlib/asyncio/futures.pyi index 9788123f427e..c907c7036b04 100644 --- a/stdlib/asyncio/futures.pyi +++ b/stdlib/asyncio/futures.pyi @@ -1,65 +1,19 @@ import sys -from concurrent.futures._base import Error, Future as _ConcurrentFuture -from typing import Any, Awaitable, Callable, Generator, Iterable, TypeVar +from _asyncio import Future as Future +from concurrent.futures._base import Future as _ConcurrentFuture +from typing import TypeVar +from .base_futures import isfuture as isfuture from .events import AbstractEventLoop -if sys.version_info < (3, 8): - from concurrent.futures import CancelledError as CancelledError, TimeoutError as TimeoutError - class InvalidStateError(Error): ... +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 14): + from _asyncio import future_add_to_awaited_by, future_discard_from_awaited_by -if sys.version_info >= (3, 7): - from contextvars import Context - -if sys.version_info >= (3, 9): - from types import GenericAlias + __all__ = ("Future", "wrap_future", "isfuture", "future_discard_from_awaited_by", "future_add_to_awaited_by") +else: + __all__ = ("Future", "wrap_future", "isfuture") _T = TypeVar("_T") -_S = TypeVar("_S") - -if sys.version_info < (3, 7): - class _TracebackLogger: - exc: BaseException - tb: list[str] - def __init__(self, exc: Any, loop: AbstractEventLoop) -> None: ... - def activate(self) -> None: ... - def clear(self) -> None: ... - def __del__(self) -> None: ... - -def isfuture(obj: object) -> bool: ... - -class Future(Awaitable[_T], Iterable[_T]): - _state: str - _exception: BaseException - _blocking = False - _log_traceback = False - def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... - def __repr__(self) -> str: ... - def __del__(self) -> None: ... - if sys.version_info >= (3, 7): - def get_loop(self) -> AbstractEventLoop: ... - def _callbacks(self: _S) -> list[tuple[Callable[[_S], Any], Context]]: ... - def add_done_callback(self: _S, __fn: Callable[[_S], Any], *, context: Context | None = ...) -> None: ... - else: - @property - def _callbacks(self: _S) -> list[Callable[[_S], Any]]: ... - def add_done_callback(self: _S, __fn: Callable[[_S], Any]) -> None: ... - if sys.version_info >= (3, 9): - def cancel(self, msg: Any | None = ...) -> bool: ... - else: - def cancel(self) -> bool: ... - def cancelled(self) -> bool: ... - def done(self) -> bool: ... - def result(self) -> _T: ... - def exception(self) -> BaseException | None: ... - def remove_done_callback(self: _S, __fn: Callable[[_S], Any]) -> int: ... - def set_result(self, __result: _T) -> None: ... - def set_exception(self, __exception: type | BaseException) -> None: ... - def __iter__(self) -> Generator[Any, None, _T]: ... - def __await__(self) -> Generator[Any, None, _T]: ... - @property - def _loop(self) -> AbstractEventLoop: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... -def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... +def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ... diff --git a/stdlib/asyncio/graph.pyi b/stdlib/asyncio/graph.pyi new file mode 100644 index 000000000000..2f89de71b16b --- /dev/null +++ b/stdlib/asyncio/graph.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import SupportsWrite +from asyncio import Future +from dataclasses import dataclass +from types import FrameType +from typing import Any, overload + +if sys.version_info >= (3, 14): + __all__ = ("capture_call_graph", "format_call_graph", "print_call_graph", "FrameCallGraphEntry", "FutureCallGraph") + + @dataclass(frozen=True, slots=True) + class FrameCallGraphEntry: + frame: FrameType + + @dataclass(frozen=True, slots=True) + class FutureCallGraph: + future: Future[Any] + call_stack: tuple[FrameCallGraphEntry, ...] + awaited_by: tuple[FutureCallGraph, ...] + + @overload + def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... + @overload + def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... + + def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str: ... + def print_call_graph( + future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None + ) -> None: ... diff --git a/stdlib/asyncio/locks.pyi b/stdlib/asyncio/locks.pyi index 7c4f40d9e4ca..4420d02fcd26 100644 --- a/stdlib/asyncio/locks.pyi +++ b/stdlib/asyncio/locks.pyi @@ -1,69 +1,83 @@ +import enum import sys +from _typeshed import Unused from collections import deque +from collections.abc import Callable from types import TracebackType -from typing import Any, Awaitable, Callable, Generator, Type, TypeVar +from typing import Any, Literal, TypeVar +from typing_extensions import Self -from .events import AbstractEventLoop from .futures import Future +from .mixins import _LoopBoundMixin + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore", "Barrier") +else: + __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore") _T = TypeVar("_T") -if sys.version_info >= (3, 9): - class _ContextManagerMixin: - def __init__(self, lock: Lock | Semaphore) -> None: ... - def __aenter__(self) -> Awaitable[None]: ... - def __aexit__( - self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None - ) -> Awaitable[None]: ... +class _ContextManagerMixin: + async def __aenter__(self) -> None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... -else: - class _ContextManager: - def __init__(self, lock: Lock | Semaphore) -> None: ... - def __enter__(self) -> object: ... - def __exit__(self, *args: Any) -> None: ... - class _ContextManagerMixin: - def __init__(self, lock: Lock | Semaphore) -> None: ... - # Apparently this exists to *prohibit* use as a context manager. - def __enter__(self) -> object: ... - def __exit__(self, *args: Any) -> None: ... - def __iter__(self) -> Generator[Any, None, _ContextManager]: ... - def __await__(self) -> Generator[Any, None, _ContextManager]: ... - def __aenter__(self) -> Awaitable[None]: ... - def __aexit__( - self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None - ) -> Awaitable[None]: ... - -class Lock(_ContextManagerMixin): - def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... +class Lock(_ContextManagerMixin, _LoopBoundMixin): + _waiters: deque[Future[Any]] | None + def __init__(self) -> None: ... def locked(self) -> bool: ... - async def acquire(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... -class Event: - def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... +class Event(_LoopBoundMixin): + _waiters: deque[Future[Any]] + def __init__(self) -> None: ... def is_set(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... - async def wait(self) -> bool: ... + async def wait(self) -> Literal[True]: ... -class Condition(_ContextManagerMixin): - def __init__(self, lock: Lock | None = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... +class Condition(_ContextManagerMixin, _LoopBoundMixin): + _waiters: deque[Future[Any]] + def __init__(self, lock: Lock | None = None) -> None: ... def locked(self) -> bool: ... - async def acquire(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... - async def wait(self) -> bool: ... + async def wait(self) -> Literal[True]: ... async def wait_for(self, predicate: Callable[[], _T]) -> _T: ... - def notify(self, n: int = ...) -> None: ... + def notify(self, n: int = 1) -> None: ... def notify_all(self) -> None: ... -class Semaphore(_ContextManagerMixin): +class Semaphore(_ContextManagerMixin, _LoopBoundMixin): _value: int - _waiters: deque[Future[Any]] - def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + _waiters: deque[Future[Any]] | None + def __init__(self, value: int = 1) -> None: ... def locked(self) -> bool: ... - async def acquire(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... def _wake_up_next(self) -> None: ... -class BoundedSemaphore(Semaphore): - def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... +class BoundedSemaphore(Semaphore): ... + +if sys.version_info >= (3, 11): + class _BarrierState(enum.Enum): # undocumented + FILLING = "filling" + DRAINING = "draining" + RESETTING = "resetting" + BROKEN = "broken" + + class Barrier(_LoopBoundMixin): + def __init__(self, parties: int) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__(self, *args: Unused) -> None: ... + async def wait(self) -> int: ... + async def abort(self) -> None: ... + async def reset(self) -> None: ... + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... diff --git a/stdlib/asyncio/mixins.pyi b/stdlib/asyncio/mixins.pyi new file mode 100644 index 000000000000..6ebcf543e6b9 --- /dev/null +++ b/stdlib/asyncio/mixins.pyi @@ -0,0 +1,9 @@ +import sys +import threading +from typing_extensions import Never + +_global_lock: threading.Lock + +class _LoopBoundMixin: + if sys.version_info < (3, 11): + def __init__(self, *, loop: Never = ...) -> None: ... diff --git a/stdlib/asyncio/proactor_events.pyi b/stdlib/asyncio/proactor_events.pyi index 1e9cff1b1dd6..09c096d40f04 100644 --- a/stdlib/asyncio/proactor_events.pyi +++ b/stdlib/asyncio/proactor_events.pyi @@ -1,15 +1,10 @@ -import sys +from collections.abc import Mapping from socket import socket -from typing import Any, Mapping, Protocol, Type -from typing_extensions import Literal +from typing import Any, ClassVar, Literal from . import base_events, constants, events, futures, streams, transports -if sys.version_info >= (3, 8): - class _WarnCallbackProtocol(Protocol): - def __call__( - self, message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... - ) -> None: ... +__all__ = ("BaseProactorEventLoop",) class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): def __init__( @@ -17,16 +12,11 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, ) -> None: ... - def __repr__(self) -> str: ... - if sys.version_info >= (3, 8): - def __del__(self, _warn: _WarnCallbackProtocol = ...) -> None: ... - else: - def __del__(self) -> None: ... - def get_write_buffer_size(self) -> int: ... + def __del__(self) -> None: ... class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): def __init__( @@ -34,50 +24,30 @@ class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTran loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., - ) -> None: ... - -class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): - def __init__( - self, - loop: events.AbstractEventLoop, - sock: socket, - protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., - ) -> None: ... - -class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): - def __init__( - self, - loop: events.AbstractEventLoop, - sock: socket, - protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, + buffer_size: int = 65536, ) -> None: ... +class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): ... +class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ... class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): ... class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): - - _sendfile_compatible: constants._SendfileMode + _sendfile_compatible: ClassVar[constants._SendfileMode] def __init__( self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, ) -> None: ... def _set_extra(self, sock: socket) -> None: ... def can_write_eof(self) -> Literal[True]: ... - def write_eof(self) -> None: ... class BaseProactorEventLoop(base_events.BaseEventLoop): def __init__(self, proactor: Any) -> None: ... + async def sock_recv(self, sock: socket, n: int) -> bytes: ... diff --git a/stdlib/asyncio/protocols.pyi b/stdlib/asyncio/protocols.pyi index 754f02c8bb4b..f63b9e084382 100644 --- a/stdlib/asyncio/protocols.pyi +++ b/stdlib/asyncio/protocols.pyi @@ -1,27 +1,39 @@ -import sys +from _typeshed import ReadableBuffer from asyncio import transports +from typing import Any + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol") class BaseProtocol: + __slots__ = () def connection_made(self, transport: transports.BaseTransport) -> None: ... def connection_lost(self, exc: Exception | None) -> None: ... def pause_writing(self) -> None: ... def resume_writing(self) -> None: ... class Protocol(BaseProtocol): + # Need annotation or mypy will complain about 'Cannot determine type of "__slots__" in base class' + __slots__: tuple[str, ...] = () def data_received(self, data: bytes) -> None: ... def eof_received(self) -> bool | None: ... -if sys.version_info >= (3, 7): - class BufferedProtocol(BaseProtocol): - def get_buffer(self, sizehint: int) -> bytearray: ... - def buffer_updated(self, nbytes: int) -> None: ... +class BufferedProtocol(BaseProtocol): + __slots__ = () + def get_buffer(self, sizehint: int) -> ReadableBuffer: ... + def buffer_updated(self, nbytes: int) -> None: ... + def eof_received(self) -> bool | None: ... class DatagramProtocol(BaseProtocol): + __slots__ = () def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore[override] - def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: ... + # addr is a tuple[str, int] for IPv4 or tuple[str, int, int, int] for IPv6. + # It can also be a tuple[int, int] for unusual protocols like socket.AF_NETLINK. + def datagram_received(self, data: bytes, addr: tuple[Any, ...]) -> None: ... def error_received(self, exc: Exception) -> None: ... class SubprocessProtocol(BaseProtocol): + __slots__: tuple[str, ...] = () def pipe_data_received(self, fd: int, data: bytes) -> None: ... def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: ... def process_exited(self) -> None: ... diff --git a/stdlib/asyncio/queues.pyi b/stdlib/asyncio/queues.pyi index aff4af727b08..de7c4879d348 100644 --- a/stdlib/asyncio/queues.pyi +++ b/stdlib/asyncio/queues.pyi @@ -1,22 +1,30 @@ import sys -from asyncio.events import AbstractEventLoop +from _typeshed import SupportsRichComparisonT +from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias +from .mixins import _LoopBoundMixin class QueueEmpty(Exception): ... class QueueFull(Exception): ... +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 13): + __all__ = ("Queue", "PriorityQueue", "LifoQueue", "QueueFull", "QueueEmpty", "QueueShutDown") + +else: + __all__ = ("Queue", "PriorityQueue", "LifoQueue", "QueueFull", "QueueEmpty") + _T = TypeVar("_T") -class Queue(Generic[_T]): - def __init__(self, maxsize: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... +if sys.version_info >= (3, 13): + class QueueShutDown(Exception): ... + +class Queue(_LoopBoundMixin, Generic[_T]): + def __init__(self, maxsize: int = 0) -> None: ... def _init(self, maxsize: int) -> None: ... def _get(self) -> _T: ... def _put(self, item: _T) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... def _format(self) -> str: ... def qsize(self) -> int: ... @property @@ -29,8 +37,9 @@ class Queue(Generic[_T]): def get_nowait(self) -> _T: ... async def join(self) -> None: ... def task_done(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, type: Any) -> GenericAlias: ... + def __class_getitem__(cls, type: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 13): + def shutdown(self, immediate: bool = False) -> None: ... -class PriorityQueue(Queue[_T]): ... +class PriorityQueue(Queue[SupportsRichComparisonT]): ... class LifoQueue(Queue[_T]): ... diff --git a/stdlib/asyncio/runners.pyi b/stdlib/asyncio/runners.pyi index 3f0f42eef48b..3a1e33aac689 100644 --- a/stdlib/asyncio/runners.pyi +++ b/stdlib/asyncio/runners.pyi @@ -1,10 +1,41 @@ import sys +from _typeshed import Unused +from collections.abc import Awaitable, Callable, Coroutine +from contextvars import Context +from typing import Any, TypeVar, final +from typing_extensions import Self -if sys.version_info >= (3, 7): - from typing import Awaitable, TypeVar +from .events import AbstractEventLoop - _T = TypeVar("_T") - if sys.version_info >= (3, 8): - def run(main: Awaitable[_T], *, debug: bool | None = ...) -> _T: ... - else: - def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ("Runner", "run") +else: + __all__ = ("run",) +_T = TypeVar("_T") + +if sys.version_info >= (3, 11): + @final + class Runner: + def __init__(self, *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: Unused, exc_val: Unused, exc_tb: Unused) -> None: ... + def close(self) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + if sys.version_info >= (3, 14): + def run(self, coro: Awaitable[_T], *, context: Context | None = None) -> _T: ... + else: + def run(self, coro: Coroutine[Any, Any, _T], *, context: Context | None = None) -> _T: ... + +if sys.version_info >= (3, 14): + def run( + main: Awaitable[_T], *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None + ) -> _T: ... + +elif sys.version_info >= (3, 12): + def run( + main: Coroutine[Any, Any, _T], *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None + ) -> _T: ... + +else: + def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: ... diff --git a/stdlib/asyncio/selector_events.pyi b/stdlib/asyncio/selector_events.pyi index bcbcd2fbe4b8..18c5df033e2f 100644 --- a/stdlib/asyncio/selector_events.pyi +++ b/stdlib/asyncio/selector_events.pyi @@ -1,6 +1,10 @@ import selectors +from socket import socket from . import base_events +__all__ = ("BaseSelectorEventLoop",) + class BaseSelectorEventLoop(base_events.BaseEventLoop): - def __init__(self, selector: selectors.BaseSelector | None = ...) -> None: ... + def __init__(self, selector: selectors.BaseSelector | None = None) -> None: ... + async def sock_recv(self, sock: socket, n: int) -> bytes: ... diff --git a/stdlib/asyncio/sslproto.pyi b/stdlib/asyncio/sslproto.pyi index 082e96dc0233..72b4ea449e86 100644 --- a/stdlib/asyncio/sslproto.pyi +++ b/stdlib/asyncio/sslproto.pyi @@ -1,75 +1,96 @@ import ssl import sys from collections import deque -from typing import Any, Callable, ClassVar -from typing_extensions import Literal +from collections.abc import Callable +from enum import Enum +from typing import Any, ClassVar, Final, Literal, TypeAlias from . import constants, events, futures, protocols, transports def _create_transport_context(server_side: bool, server_hostname: str | None) -> ssl.SSLContext: ... -_UNWRAPPED: Literal["UNWRAPPED"] -_DO_HANDSHAKE: Literal["DO_HANDSHAKE"] -_WRAPPED: Literal["WRAPPED"] -_SHUTDOWN: Literal["SHUTDOWN"] +if sys.version_info >= (3, 11): + SSLAgainErrors: tuple[type[ssl.SSLWantReadError], type[ssl.SSLSyscallError]] -class _SSLPipe: + class SSLProtocolState(Enum): + UNWRAPPED = "UNWRAPPED" + DO_HANDSHAKE = "DO_HANDSHAKE" + WRAPPED = "WRAPPED" + FLUSHING = "FLUSHING" + SHUTDOWN = "SHUTDOWN" - max_size: ClassVar[int] + class AppProtocolState(Enum): + STATE_INIT = "STATE_INIT" + STATE_CON_MADE = "STATE_CON_MADE" + STATE_EOF = "STATE_EOF" + STATE_CON_LOST = "STATE_CON_LOST" - _context: ssl.SSLContext - _server_side: bool - _server_hostname: str | None - _state: str - _incoming: ssl.MemoryBIO - _outgoing: ssl.MemoryBIO - _sslobj: ssl.SSLObject | None - _need_ssldata: bool - _handshake_cb: Callable[[BaseException | None], None] | None - _shutdown_cb: Callable[[], None] | None - def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = ...) -> None: ... - @property - def context(self) -> ssl.SSLContext: ... - @property - def ssl_object(self) -> ssl.SSLObject | None: ... - @property - def need_ssldata(self) -> bool: ... - @property - def wrapped(self) -> bool: ... - def do_handshake(self, callback: Callable[[BaseException | None], None] | None = ...) -> list[bytes]: ... - def shutdown(self, callback: Callable[[], None] | None = ...) -> list[bytes]: ... - def feed_eof(self) -> None: ... - def feed_ssldata(self, data: bytes, only_handshake: bool = ...) -> tuple[list[bytes], list[bytes]]: ... - def feed_appdata(self, data: bytes, offset: int = ...) -> tuple[list[bytes], int]: ... + def add_flowcontrol_defaults(high: int | None, low: int | None, kb: int) -> tuple[int, int]: ... -class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): +else: + _UNWRAPPED: Final = "UNWRAPPED" + _DO_HANDSHAKE: Final = "DO_HANDSHAKE" + _WRAPPED: Final = "WRAPPED" + _SHUTDOWN: Final = "SHUTDOWN" + +if sys.version_info < (3, 11): + class _SSLPipe: + max_size: ClassVar[int] + + _context: ssl.SSLContext + _server_side: bool + _server_hostname: str | None + _state: str + _incoming: ssl.MemoryBIO + _outgoing: ssl.MemoryBIO + _sslobj: ssl.SSLObject | None + _need_ssldata: bool + _handshake_cb: Callable[[BaseException | None], None] | None + _shutdown_cb: Callable[[], None] | None + def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = None) -> None: ... + @property + def context(self) -> ssl.SSLContext: ... + @property + def ssl_object(self) -> ssl.SSLObject | None: ... + @property + def need_ssldata(self) -> bool: ... + @property + def wrapped(self) -> bool: ... + def do_handshake(self, callback: Callable[[BaseException | None], object] | None = None) -> list[bytes]: ... + def shutdown(self, callback: Callable[[], object] | None = None) -> list[bytes]: ... + def feed_eof(self) -> None: ... + def feed_ssldata(self, data: bytes, only_handshake: bool = False) -> tuple[list[bytes], list[bytes]]: ... + def feed_appdata(self, data: bytes, offset: int = 0) -> tuple[list[bytes], int]: ... +class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): _sendfile_compatible: ClassVar[constants._SendfileMode] _loop: events.AbstractEventLoop - _ssl_protocol: SSLProtocol + if sys.version_info >= (3, 11): + _ssl_protocol: SSLProtocol | None + else: + _ssl_protocol: SSLProtocol _closed: bool def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... - def get_extra_info(self, name: str, default: Any | None = ...) -> dict[str, Any]: ... - def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... - def get_protocol(self) -> protocols.BaseProtocol: ... - def is_closing(self) -> bool: ... - def close(self) -> None: ... - if sys.version_info >= (3, 7): - def is_reading(self) -> bool: ... - def pause_reading(self) -> None: ... - def resume_reading(self) -> None: ... - def set_write_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... - def get_write_buffer_size(self) -> int: ... - if sys.version_info >= (3, 7): - @property - def _protocol_paused(self) -> bool: ... - def write(self, data: bytes) -> None: ... + def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]: ... + @property + def _protocol_paused(self) -> bool: ... + def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ... # any memoryview format or shape def can_write_eof(self) -> Literal[False]: ... - def abort(self) -> None: ... + if sys.version_info >= (3, 11): + def get_write_buffer_limits(self) -> tuple[int, int]: ... + def get_read_buffer_limits(self) -> tuple[int, int]: ... + def set_read_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ... + def get_read_buffer_size(self) -> int: ... + + def __del__(self) -> None: ... -class SSLProtocol(protocols.Protocol): +if sys.version_info >= (3, 11): + _SSLProtocolBase: TypeAlias = protocols.BufferedProtocol +else: + _SSLProtocolBase: TypeAlias = protocols.Protocol +class SSLProtocol(_SSLProtocolBase): _server_side: bool _server_hostname: str | None _sslcontext: ssl.SSLContext @@ -79,27 +100,32 @@ class SSLProtocol(protocols.Protocol): _waiter: futures.Future[Any] _loop: events.AbstractEventLoop _app_transport: _SSLProtocolTransport - _sslpipe: _SSLPipe | None - _session_established: bool - _in_handshake: bool - _in_shutdown: bool _transport: transports.BaseTransport | None - _call_connection_made: bool _ssl_handshake_timeout: int | None _app_protocol: protocols.BaseProtocol _app_protocol_is_buffer: bool - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): + max_size: ClassVar[int] + else: + _sslpipe: _SSLPipe | None + _session_established: bool + _call_connection_made: bool + _in_handshake: bool + _in_shutdown: bool + + if sys.version_info >= (3, 11): def __init__( self, loop: events.AbstractEventLoop, app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, waiter: futures.Future[Any], - server_side: bool = ..., - server_hostname: str | None = ..., - call_connection_made: bool = ..., - ssl_handshake_timeout: int | None = ..., + server_side: bool = False, + server_hostname: str | None = None, + call_connection_made: bool = True, + ssl_handshake_timeout: int | None = None, + ssl_shutdown_timeout: float | None = None, ) -> None: ... else: def __init__( @@ -108,27 +134,31 @@ class SSLProtocol(protocols.Protocol): app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, waiter: futures.Future[Any], - server_side: bool = ..., - server_hostname: str | None = ..., - call_connection_made: bool = ..., + server_side: bool = False, + server_hostname: str | None = None, + call_connection_made: bool = True, + ssl_handshake_timeout: int | None = None, ) -> None: ... - if sys.version_info >= (3, 7): - def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... - def _wakeup_waiter(self, exc: BaseException | None = ...) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... + + def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... + def _wakeup_waiter(self, exc: BaseException | None = None) -> None: ... def connection_lost(self, exc: BaseException | None) -> None: ... - def pause_writing(self) -> None: ... - def resume_writing(self) -> None: ... - def data_received(self, data: bytes) -> None: ... def eof_received(self) -> None: ... - def _get_extra_info(self, name: str, default: Any | None = ...) -> Any: ... + def _get_extra_info(self, name: str, default: Any | None = None) -> Any: ... def _start_shutdown(self) -> None: ... - def _write_appdata(self, data: bytes) -> None: ... + if sys.version_info >= (3, 11): + def _write_appdata(self, list_of_data: list[bytes]) -> None: ... + else: + def _write_appdata(self, data: bytes) -> None: ... + def _start_handshake(self) -> None: ... - if sys.version_info >= (3, 7): - def _check_handshake_timeout(self) -> None: ... + def _check_handshake_timeout(self) -> None: ... def _on_handshake_complete(self, handshake_exc: BaseException | None) -> None: ... - def _process_write_backlog(self) -> None: ... - def _fatal_error(self, exc: BaseException, message: str = ...) -> None: ... - def _finalize(self) -> None: ... - def _abort(self) -> None: ... + def _fatal_error(self, exc: BaseException, message: str = "Fatal error on transport") -> None: ... + if sys.version_info >= (3, 11): + def _abort(self, exc: BaseException | None) -> None: ... + def get_buffer(self, n: int) -> memoryview: ... + else: + def _abort(self) -> None: ... + def _finalize(self) -> None: ... + def _process_write_backlog(self) -> None: ... diff --git a/stdlib/asyncio/staggered.pyi b/stdlib/asyncio/staggered.pyi index 1d76d382555d..3324777f4168 100644 --- a/stdlib/asyncio/staggered.pyi +++ b/stdlib/asyncio/staggered.pyi @@ -1,9 +1,10 @@ -import sys -from typing import Any, Awaitable, Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable +from typing import Any from . import events -if sys.version_info >= (3, 8): - async def staggered_race( - coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = ... - ) -> tuple[Any, int | None, list[Exception | None]]: ... +__all__ = ("staggered_race",) + +async def staggered_race( + coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = None +) -> tuple[Any, int | None, list[Exception | None]]: ... diff --git a/stdlib/asyncio/streams.pyi b/stdlib/asyncio/streams.pyi index 595222280d58..9e76c69d8732 100644 --- a/stdlib/asyncio/streams.pyi +++ b/stdlib/asyncio/streams.pyi @@ -1,105 +1,124 @@ +import ssl import sys -from _typeshed import StrPath -from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional +from _typeshed import ReadableBuffer, StrPath +from collections.abc import Awaitable, Callable, Iterable, Sequence, Sized +from types import ModuleType +from typing import Any, Protocol, SupportsIndex, TypeAlias, type_check_only +from typing_extensions import Self from . import events, protocols, transports from .base_events import Server -_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.platform == "win32": + __all__ = ("StreamReader", "StreamWriter", "StreamReaderProtocol", "open_connection", "start_server") +else: + __all__ = ( + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "open_unix_connection", + "start_unix_server", + ) -if sys.version_info < (3, 8): - class IncompleteReadError(EOFError): - expected: int | None - partial: bytes - def __init__(self, partial: bytes, expected: int | None) -> None: ... - class LimitOverrunError(Exception): - consumed: int - def __init__(self, message: str, consumed: int) -> None: ... +_ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] + +@type_check_only +class _ReaduntilBuffer(ReadableBuffer, Sized, Protocol): ... async def open_connection( - host: str | None = ..., - port: int | str | None = ..., + host: str | None = None, + port: int | str | None = None, *, - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., - ssl_handshake_timeout: float | None = ..., + limit: int = 65536, + ssl_handshake_timeout: float | None = None, **kwds: Any, ) -> tuple[StreamReader, StreamWriter]: ... async def start_server( client_connected_cb: _ClientConnectedCallback, - host: str | None = ..., - port: int | str | None = ..., + host: str | Sequence[str] | None = None, + port: int | str | None = None, *, - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., - ssl_handshake_timeout: float | None = ..., + limit: int = 65536, + ssl_handshake_timeout: float | None = None, **kwds: Any, ) -> Server: ... if sys.platform != "win32": - if sys.version_info >= (3, 7): - _PathType = StrPath - else: - _PathType = str async def open_unix_connection( - path: _PathType | None = ..., *, loop: events.AbstractEventLoop | None = ..., limit: int = ..., **kwds: Any + path: StrPath | None = None, *, limit: int = 65536, **kwds: Any ) -> tuple[StreamReader, StreamWriter]: ... async def start_unix_server( - client_connected_cb: _ClientConnectedCallback, - path: _PathType | None = ..., - *, - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., - **kwds: Any, + client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any ) -> Server: ... class FlowControlMixin(protocols.Protocol): - def __init__(self, loop: events.AbstractEventLoop | None = ...) -> None: ... + def __init__(self, loop: events.AbstractEventLoop | None = None) -> None: ... class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): def __init__( self, stream_reader: StreamReader, - client_connected_cb: _ClientConnectedCallback | None = ..., - loop: events.AbstractEventLoop | None = ..., + client_connected_cb: _ClientConnectedCallback | None = None, + loop: events.AbstractEventLoop | None = None, ) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... - def connection_lost(self, exc: Exception | None) -> None: ... - def data_received(self, data: bytes) -> None: ... - def eof_received(self) -> bool: ... + def __del__(self) -> None: ... class StreamWriter: def __init__( self, - transport: transports.BaseTransport, + transport: transports.WriteTransport, protocol: protocols.BaseProtocol, reader: StreamReader | None, loop: events.AbstractEventLoop, ) -> None: ... @property - def transport(self) -> transports.BaseTransport: ... - def write(self, data: bytes) -> None: ... - def writelines(self, data: Iterable[bytes]) -> None: ... + def transport(self) -> transports.WriteTransport: ... + def write(self, data: bytes | bytearray | memoryview) -> None: ... + def writelines(self, data: Iterable[bytes | bytearray | memoryview]) -> None: ... def write_eof(self) -> None: ... def can_write_eof(self) -> bool: ... def close(self) -> None: ... - if sys.version_info >= (3, 7): - def is_closing(self) -> bool: ... - async def wait_closed(self) -> None: ... - def get_extra_info(self, name: str, default: Any = ...) -> Any: ... + def is_closing(self) -> bool: ... + async def wait_closed(self) -> None: ... + def get_extra_info(self, name: str, default: Any = None) -> Any: ... async def drain(self) -> None: ... + if sys.version_info >= (3, 12): + async def start_tls( + self, + sslcontext: ssl.SSLContext, + *, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> None: ... + elif sys.version_info >= (3, 11): + async def start_tls( + self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None + ) -> None: ... + + if sys.version_info >= (3, 13): + def __del__(self, warnings: ModuleType = ...) -> None: ... + elif sys.version_info >= (3, 11): + def __del__(self) -> None: ... class StreamReader: - def __init__(self, limit: int = ..., loop: events.AbstractEventLoop | None = ...) -> None: ... - def exception(self) -> Exception: ... + def __init__(self, limit: int = 65536, loop: events.AbstractEventLoop | None = None) -> None: ... + def exception(self) -> Exception | None: ... def set_exception(self, exc: Exception) -> None: ... def set_transport(self, transport: transports.BaseTransport) -> None: ... def feed_eof(self) -> None: ... def at_eof(self) -> bool: ... - def feed_data(self, data: bytes) -> None: ... + def feed_data(self, data: Iterable[SupportsIndex]) -> None: ... async def readline(self) -> bytes: ... - async def readuntil(self, separator: bytes = ...) -> bytes: ... - async def read(self, n: int = ...) -> bytes: ... + if sys.version_info >= (3, 13): + async def readuntil(self, separator: _ReaduntilBuffer | tuple[_ReaduntilBuffer, ...] = b"\n") -> bytes: ... + else: + async def readuntil(self, separator: _ReaduntilBuffer = b"\n") -> bytes: ... + + async def read(self, n: int = -1) -> bytes: ... async def readexactly(self, n: int) -> bytes: ... - def __aiter__(self) -> AsyncIterator[bytes]: ... + def __aiter__(self) -> Self: ... async def __anext__(self) -> bytes: ... diff --git a/stdlib/asyncio/subprocess.pyi b/stdlib/asyncio/subprocess.pyi index d835c12af3d8..7f447cf1d82a 100644 --- a/stdlib/asyncio/subprocess.pyi +++ b/stdlib/asyncio/subprocess.pyi @@ -2,13 +2,11 @@ import subprocess import sys from _typeshed import StrOrBytesPath from asyncio import events, protocols, streams, transports -from typing import IO, Any, Callable, Union -from typing_extensions import Literal +from collections.abc import Callable, Collection +from typing import IO, Any, Literal -if sys.version_info >= (3, 8): - _ExecArg = StrOrBytesPath -else: - _ExecArg = Union[str, bytes] +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("create_subprocess_exec", "create_subprocess_shell") PIPE: int STDOUT: int @@ -19,10 +17,7 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessPro stdout: streams.StreamReader | None stderr: streams.StreamReader | None def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... def pipe_data_received(self, fd: int, data: bytes | str) -> None: ... - def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: ... - def process_exited(self) -> None: ... class Process: stdin: streams.StreamWriter | None @@ -38,114 +33,134 @@ class Process: def send_signal(self, signal: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... - async def communicate(self, input: bytes | None = ...) -> tuple[bytes, bytes]: ... + async def communicate(self, input: bytes | bytearray | memoryview | None = None) -> tuple[bytes, bytes]: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 11): async def create_subprocess_shell( cmd: str | bytes, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - limit: int = ..., + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, *, # These parameters are forced to these values by BaseEventLoop.subprocess_shell - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., - text: Literal[False, None] = ..., + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, # These parameters are taken by subprocess.Popen, which this ultimately delegates to - executable: StrOrBytesPath | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: subprocess._ENV | None = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, + umask: int = -1, + process_group: int | None = None, + pipesize: int = -1, ) -> Process: ... async def create_subprocess_exec( - program: _ExecArg, - *args: _ExecArg, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - limit: int = ..., - # These parameters are forced to these values by BaseEventLoop.subprocess_shell - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., + program: StrOrBytesPath, + *args: StrOrBytesPath, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, + # These parameters are forced to these values by BaseEventLoop.subprocess_exec + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, # These parameters are taken by subprocess.Popen, which this ultimately delegates to - text: bool | None = ..., - executable: StrOrBytesPath | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: subprocess._ENV | None = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, + umask: int = -1, + process_group: int | None = None, + pipesize: int = -1, ) -> Process: ... else: async def create_subprocess_shell( cmd: str | bytes, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, *, # These parameters are forced to these values by BaseEventLoop.subprocess_shell - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., - text: Literal[False, None] = ..., + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, # These parameters are taken by subprocess.Popen, which this ultimately delegates to - executable: StrOrBytesPath | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: subprocess._ENV | None = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, + umask: int = -1, + pipesize: int = -1, ) -> Process: ... async def create_subprocess_exec( - program: _ExecArg, - *args: _ExecArg, - stdin: int | IO[Any] | None = ..., - stdout: int | IO[Any] | None = ..., - stderr: int | IO[Any] | None = ..., - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., - # These parameters are forced to these values by BaseEventLoop.subprocess_shell - universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., - bufsize: Literal[0] = ..., - encoding: None = ..., - errors: None = ..., + program: StrOrBytesPath, + *args: StrOrBytesPath, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, + # These parameters are forced to these values by BaseEventLoop.subprocess_exec + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, # These parameters are taken by subprocess.Popen, which this ultimately delegates to - text: bool | None = ..., - executable: StrOrBytesPath | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: subprocess._ENV | None = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, + umask: int = -1, + pipesize: int = -1, ) -> Process: ... diff --git a/stdlib/asyncio/taskgroups.pyi b/stdlib/asyncio/taskgroups.pyi new file mode 100644 index 000000000000..886a79c4beb5 --- /dev/null +++ b/stdlib/asyncio/taskgroups.pyi @@ -0,0 +1,41 @@ +import sys +from contextvars import Context +from types import TracebackType +from typing import Any, TypeVar +from typing_extensions import Self + +from . import _CoroutineLike +from .events import AbstractEventLoop +from .tasks import Task + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 12): + __all__ = ("TaskGroup",) +else: + __all__ = ["TaskGroup"] + +_T = TypeVar("_T") + +class TaskGroup: + _loop: AbstractEventLoop | None + _tasks: set[Task[Any]] + + async def __aenter__(self) -> Self: ... + async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + if sys.version_info >= (3, 14): + def create_task( + self, + coro: _CoroutineLike[_T], + *, + name: str | None = None, + context: Context | None = None, + eager_start: bool | None = None, + ) -> Task[_T]: ... + else: + def create_task( + self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None + ) -> Task[_T]: ... + + def _on_task_done(self, task: Task[object]) -> None: ... + if sys.version_info >= (3, 15): + def cancel(self) -> None: ... diff --git a/stdlib/asyncio/tasks.pyi b/stdlib/asyncio/tasks.pyi index f12dcbcd79a8..66c31f15e6fb 100644 --- a/stdlib/asyncio/tasks.pyi +++ b/stdlib/asyncio/tasks.pyi @@ -1,299 +1,315 @@ import concurrent.futures import sys -from collections.abc import Awaitable, Generator, Iterable, Iterator -from types import FrameType -from typing import Any, Generic, Optional, TextIO, TypeVar, Union, overload -from typing_extensions import Literal +from _asyncio import ( + Task as Task, + _enter_task as _enter_task, + _leave_task as _leave_task, + _register_task as _register_task, + _unregister_task as _unregister_task, +) +from collections.abc import AsyncIterator, Awaitable, Coroutine, Generator, Iterable, Iterator +from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from . import _CoroutineLike from .events import AbstractEventLoop from .futures import Future -if sys.version_info >= (3, 9): - from types import GenericAlias +if sys.version_info >= (3, 11): + from contextvars import Context + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 12): + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "create_eager_task_factory", + "eager_task_factory", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) +else: + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") _FT = TypeVar("_FT", bound=Future[Any]) -_FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] -_TaskYieldType = Optional[Future[object]] +if sys.version_info >= (3, 12): + _FutureLike: TypeAlias = Future[_T] | Awaitable[_T] +else: + _FutureLike: TypeAlias = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] + +_TaskYieldType: TypeAlias = Future[object] | None + +FIRST_COMPLETED: Final = concurrent.futures.FIRST_COMPLETED +FIRST_EXCEPTION: Final = concurrent.futures.FIRST_EXCEPTION +ALL_COMPLETED: Final = concurrent.futures.ALL_COMPLETED -FIRST_EXCEPTION: str -FIRST_COMPLETED: str -ALL_COMPLETED: str +if sys.version_info >= (3, 13): + @type_check_only + class _SyncAndAsyncIterator(Iterator[Coroutine[Any, Any, _T]], AsyncIterator[Future[_T]], Protocol[_T]): ... -if sys.version_info >= (3, 10): - def as_completed(fs: Iterable[_FutureT[_T]], *, timeout: float | None = ...) -> Iterator[Future[_T]]: ... + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[_T]: ... else: - def as_completed( - fs: Iterable[_FutureT[_T]], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ... - ) -> Iterator[Future[_T]]: ... + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: ... @overload -def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = ...) -> _FT: ... # type: ignore[misc] +def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = None) -> _FT: ... # type: ignore[overload-overlap] @overload -def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | None = ...) -> Task[_T]: ... - -# Prior to Python 3.7 'async' was an alias for 'ensure_future'. -# It became a keyword in 3.7. +def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | None = None) -> Task[_T]: ... # `gather()` actually returns a list with length equal to the number # of tasks passed; however, Tuple is used similar to the annotation for # zip() because typing does not support variadic type variables. See # typing PR #1550 for discussion. -if sys.version_info >= (3, 10): - @overload - def gather(coro_or_future1: _FutureT[_T1], *, return_exceptions: Literal[False] = ...) -> Future[tuple[_T1]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, return_exceptions: Literal[False] = ... - ) -> Future[tuple[_T1, _T2]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - *, - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2, _T3]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - *, - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], - *, - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def gather( - coro_or_future1: _FutureT[Any], - coro_or_future2: _FutureT[Any], - coro_or_future3: _FutureT[Any], - coro_or_future4: _FutureT[Any], - coro_or_future5: _FutureT[Any], - coro_or_future6: _FutureT[Any], - *coros_or_futures: _FutureT[Any], - return_exceptions: bool = ..., - ) -> Future[list[Any]]: ... - @overload - def gather(coro_or_future1: _FutureT[_T1], *, return_exceptions: bool = ...) -> Future[tuple[_T1 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, return_exceptions: bool = ... - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - *, - return_exceptions: bool = ..., - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - *, - return_exceptions: bool = ..., - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], - *, - return_exceptions: bool = ..., - ) -> Future[ - tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException] - ]: ... +# +# N.B. Having overlapping overloads is the only way to get acceptable type inference in all edge cases. +@overload +def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ... # type: ignore[overload-overlap] +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: Literal[False] = False +) -> Future[tuple[_T1, _T2]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: Literal[False] = False) -> Future[list[_T]]: ... # type: ignore[overload-overlap] +@overload +def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: bool +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, + *, + return_exceptions: bool, +) -> Future[ + tuple[ + _T1 | BaseException, + _T2 | BaseException, + _T3 | BaseException, + _T4 | BaseException, + _T5 | BaseException, + _T6 | BaseException, + ] +]: ... +@overload +def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: bool) -> Future[list[_T | BaseException]]: ... + +# unlike some asyncio apis, This does strict runtime checking of actually being a coroutine, not of any future-like. +def run_coroutine_threadsafe(coro: Coroutine[Any, Any, _T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def shield(arg: _FutureLike[_T]) -> Future[_T]: ... + +@overload +async def sleep(delay: float) -> None: ... +@overload +async def sleep(delay: float, result: _T) -> _T: ... + +async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: ... + +if sys.version_info >= (3, 11): + async def wait( + fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[_FT], set[_FT]]: ... else: @overload - def gather( - coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ... - ) -> Future[tuple[_T1]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2, _T3]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: Literal[False] = ..., - ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def gather( - coro_or_future1: _FutureT[Any], - coro_or_future2: _FutureT[Any], - coro_or_future3: _FutureT[Any], - coro_or_future4: _FutureT[Any], - coro_or_future5: _FutureT[Any], - coro_or_future6: _FutureT[Any], - *coros_or_futures: _FutureT[Any], - loop: AbstractEventLoop | None = ..., - return_exceptions: bool = ..., - ) -> Future[list[Any]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ... - ) -> Future[tuple[_T1 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: bool = ..., - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: bool = ..., - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: bool = ..., - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... + async def wait( # type: ignore[overload-overlap] + fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[_FT], set[_FT]]: ... @overload - def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], - *, - loop: AbstractEventLoop | None = ..., - return_exceptions: bool = ..., - ) -> Future[ - tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException] - ]: ... + async def wait( + fs: Iterable[Awaitable[_T]], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... -def run_coroutine_threadsafe(coro: _FutureT[_T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +if sys.version_info >= (3, 12): + _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] +else: + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] -if sys.version_info >= (3, 10): - def shield(arg: _FutureT[_T]) -> Future[_T]: ... - def sleep(delay: float, result: _T = ...) -> Future[_T]: ... - @overload - def wait(fs: Iterable[_FT], *, timeout: float | None = ..., return_when: str = ...) -> Future[tuple[set[_FT], set[_FT]]]: ... # type: ignore[misc] - @overload - def wait( - fs: Iterable[Awaitable[_T]], *, timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[set[Task[_T]], set[Task[_T]]]]: ... - def wait_for(fut: _FutureT[_T], timeout: float | None) -> Future[_T]: ... +def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... + +if sys.version_info >= (3, 14): + def create_task( + coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None, eager_start: bool | None = None + ) -> Task[_T]: ... + +elif sys.version_info >= (3, 11): + def create_task(coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: ... else: - def shield(arg: _FutureT[_T], *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... - def sleep(delay: float, result: _T = ..., *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... - @overload - def wait( # type: ignore[misc] - fs: Iterable[_FT], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[set[_FT], set[_FT]]]: ... - @overload - def wait( - fs: Iterable[Awaitable[_T]], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[set[Task[_T]], set[Task[_T]]]]: ... - def wait_for(fut: _FutureT[_T], timeout: float | None, *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... + def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... + +if sys.version_info >= (3, 12): + from _asyncio import current_task as current_task +else: + def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... + +if sys.version_info >= (3, 14): + def eager_task_factory( + loop: AbstractEventLoop | None, + coro: _TaskCompatibleCoro[_T_co], + *, + name: str | None = None, + context: Context | None = None, + eager_start: bool = True, + ) -> Task[_T_co]: ... + +elif sys.version_info >= (3, 12): + def eager_task_factory( + loop: AbstractEventLoop | None, + coro: _TaskCompatibleCoro[_T_co], + *, + name: str | None = None, + context: Context | None = None, + ) -> Task[_T_co]: ... + +if sys.version_info >= (3, 12): + _TaskT_co = TypeVar("_TaskT_co", bound=Task[Any], covariant=True) + + @type_check_only + class _CustomTaskConstructor(Protocol[_TaskT_co]): + def __call__( + self, + coro: _TaskCompatibleCoro[Any], + /, + *, + loop: AbstractEventLoop, + name: str | None, + context: Context | None, + eager_start: bool, + ) -> _TaskT_co: ... -class Task(Future[_T], Generic[_T]): - if sys.version_info >= (3, 8): - def __init__( + @type_check_only + class _EagerTaskFactoryType(Protocol[_TaskT_co]): + def __call__( self, - coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], + loop: AbstractEventLoop, + coro: _TaskCompatibleCoro[Any], *, - loop: AbstractEventLoop = ..., - name: str | None = ..., - ) -> None: ... - else: - def __init__( - self, coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, loop: AbstractEventLoop = ... - ) -> None: ... - def __repr__(self) -> str: ... - if sys.version_info >= (3, 8): - def get_coro(self) -> Generator[_TaskYieldType, None, _T] | Awaitable[_T]: ... - def get_name(self) -> str: ... - def set_name(self, __value: object) -> None: ... - def get_stack(self, *, limit: int | None = ...) -> list[FrameType]: ... - def print_stack(self, *, limit: int | None = ..., file: TextIO | None = ...) -> None: ... - if sys.version_info >= (3, 9): - def cancel(self, msg: Any | None = ...) -> bool: ... - else: - def cancel(self) -> bool: ... - if sys.version_info < (3, 9): - @classmethod - def current_task(cls, loop: AbstractEventLoop | None = ...) -> Task[Any] | None: ... - @classmethod - def all_tasks(cls, loop: AbstractEventLoop | None = ...) -> set[Task[Any]]: ... - if sys.version_info < (3, 7): - def _wakeup(self, fut: Future[Any]) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + name: str | None = None, + context: Context | None = None, + ) -> _TaskT_co: ... -if sys.version_info >= (3, 7): - def all_tasks(loop: AbstractEventLoop | None = ...) -> set[Task[Any]]: ... - if sys.version_info >= (3, 8): - def create_task(coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, name: str | None = ...) -> Task[_T]: ... - else: - def create_task(coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T]) -> Task[_T]: ... - def current_task(loop: AbstractEventLoop | None = ...) -> Task[Any] | None: ... - def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... - def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... - def _register_task(task: Task[Any]) -> None: ... - def _unregister_task(task: Task[Any]) -> None: ... + def create_eager_task_factory( + custom_task_constructor: _CustomTaskConstructor[_TaskT_co], + ) -> _EagerTaskFactoryType[_TaskT_co]: ... diff --git a/stdlib/asyncio/threads.pyi b/stdlib/asyncio/threads.pyi index c13c0c6d1194..f1d882918098 100644 --- a/stdlib/asyncio/threads.pyi +++ b/stdlib/asyncio/threads.pyi @@ -1,9 +1,9 @@ -import sys -from typing import Callable, TypeVar -from typing_extensions import ParamSpec +from collections.abc import Callable +from typing import ParamSpec, TypeVar +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("to_thread",) _P = ParamSpec("_P") _R = TypeVar("_R") -if sys.version_info >= (3, 9): - async def to_thread(__func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... +async def to_thread(func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... diff --git a/stdlib/asyncio/timeouts.pyi b/stdlib/asyncio/timeouts.pyi new file mode 100644 index 000000000000..668cccbfe8b1 --- /dev/null +++ b/stdlib/asyncio/timeouts.pyi @@ -0,0 +1,20 @@ +from types import TracebackType +from typing import final +from typing_extensions import Self + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("Timeout", "timeout", "timeout_at") + +@final +class Timeout: + def __init__(self, when: float | None) -> None: ... + def when(self) -> float | None: ... + def reschedule(self, when: float | None) -> None: ... + def expired(self) -> bool: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +def timeout(delay: float | None) -> Timeout: ... +def timeout_at(when: float | None) -> Timeout: ... diff --git a/stdlib/asyncio/tools.pyi b/stdlib/asyncio/tools.pyi new file mode 100644 index 000000000000..36c65541c9cd --- /dev/null +++ b/stdlib/asyncio/tools.pyi @@ -0,0 +1,51 @@ +import sys +from collections.abc import Iterable +from enum import Enum +from typing import NamedTuple, SupportsIndex, type_check_only + +@type_check_only +class _AwaitedInfo(NamedTuple): # AwaitedInfo_Type from _remote_debugging + thread_id: int + awaited_by: list[_TaskInfo] + +@type_check_only +class _TaskInfo(NamedTuple): # TaskInfo_Type from _remote_debugging + task_id: int + task_name: str + coroutine_stack: list[_CoroInfo] + awaited_by: list[_CoroInfo] + +@type_check_only +class _CoroInfo(NamedTuple): # CoroInfo_Type from _remote_debugging + call_stack: list[_FrameInfo] + task_name: int | str + +@type_check_only +class _FrameInfo(NamedTuple): # FrameInfo_Type from _remote_debugging + filename: str + lineno: int + funcname: str + +class NodeType(Enum): + COROUTINE = 1 + TASK = 2 + +class CycleFoundException(Exception): + cycles: list[list[int]] + id2name: dict[int, str] + def __init__(self, cycles: list[list[int]], id2name: dict[int, str]) -> None: ... + +def get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ... +def build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = "(T)", cor_emoji: str = "") -> list[list[str]]: ... +def build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: ... + +if sys.version_info >= (3, 14): + def exit_with_permission_help_text() -> None: ... + +if sys.version_info >= (3, 15): + def display_awaited_by_tasks_table(pid: SupportsIndex, retries: SupportsIndex = 3) -> None: ... + def display_awaited_by_tasks_tree(pid: SupportsIndex, retries: SupportsIndex = 3) -> None: ... + +else: + def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: ... + def display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: ... diff --git a/stdlib/asyncio/transports.pyi b/stdlib/asyncio/transports.pyi index acca0e4c28b4..cc870d5e0b9a 100644 --- a/stdlib/asyncio/transports.pyi +++ b/stdlib/asyncio/transports.pyi @@ -1,46 +1,57 @@ -import sys from asyncio.events import AbstractEventLoop from asyncio.protocols import BaseProtocol +from collections.abc import Iterable, Mapping from socket import _Address -from typing import Any, Mapping +from typing import Any + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport") class BaseTransport: - def __init__(self, extra: Mapping[Any, Any] | None = ...) -> None: ... - def get_extra_info(self, name: Any, default: Any = ...) -> Any: ... + __slots__ = ("_extra",) + def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ... + def get_extra_info(self, name: str, default: Any = None) -> Any: ... def is_closing(self) -> bool: ... def close(self) -> None: ... def set_protocol(self, protocol: BaseProtocol) -> None: ... def get_protocol(self) -> BaseProtocol: ... class ReadTransport(BaseTransport): - if sys.version_info >= (3, 7): - def is_reading(self) -> bool: ... + __slots__ = () + def is_reading(self) -> bool: ... def pause_reading(self) -> None: ... def resume_reading(self) -> None: ... class WriteTransport(BaseTransport): - def set_write_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... + __slots__ = () + def set_write_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ... def get_write_buffer_size(self) -> int: ... - def write(self, data: Any) -> None: ... - def writelines(self, list_of_data: list[Any]) -> None: ... + def get_write_buffer_limits(self) -> tuple[int, int]: ... + def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ... # any memoryview format or shape + def writelines( + self, list_of_data: Iterable[bytes | bytearray | memoryview[Any]] + ) -> None: ... # any memoryview format or shape def write_eof(self) -> None: ... def can_write_eof(self) -> bool: ... def abort(self) -> None: ... -class Transport(ReadTransport, WriteTransport): ... +class Transport(ReadTransport, WriteTransport): + __slots__ = () class DatagramTransport(BaseTransport): - def sendto(self, data: Any, addr: _Address | None = ...) -> None: ... + __slots__ = () + def sendto(self, data: bytes | bytearray | memoryview, addr: _Address | None = None) -> None: ... def abort(self) -> None: ... class SubprocessTransport(BaseTransport): + __slots__ = () def get_pid(self) -> int: ... def get_returncode(self) -> int | None: ... def get_pipe_transport(self, fd: int) -> BaseTransport | None: ... - def send_signal(self, signal: int) -> int: ... + def send_signal(self, signal: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... class _FlowControlMixin(Transport): - def __init__(self, extra: Mapping[Any, Any] | None = ..., loop: AbstractEventLoop | None = ...) -> None: ... - def get_write_buffer_limits(self) -> tuple[int, int]: ... + __slots__ = ("_loop", "_protocol_paused", "_high_water", "_low_water") + def __init__(self, extra: Mapping[str, Any] | None = None, loop: AbstractEventLoop | None = None) -> None: ... diff --git a/stdlib/asyncio/trsock.pyi b/stdlib/asyncio/trsock.pyi index 33ec5d67aaf9..d2e972fee49c 100644 --- a/stdlib/asyncio/trsock.pyi +++ b/stdlib/asyncio/trsock.pyi @@ -1,86 +1,137 @@ import socket import sys +from _typeshed import ReadableBuffer +from builtins import type as Type # alias to avoid name clashes with property named "type" +from collections.abc import Iterable from types import TracebackType -from typing import Any, BinaryIO, Iterable, NoReturn, Tuple, Type, Union, overload +from typing import Any, BinaryIO, TypeAlias, overload +from typing_extensions import Never, deprecated -if sys.version_info >= (3, 8): - # These are based in socket, maybe move them out into _typeshed.pyi or such - _Address = Union[Tuple[Any, ...], str] - _RetAddress = Any - _WriteBuffer = Union[bytearray, memoryview] - _CMSG = Tuple[int, int, bytes] - class TransportSocket: - def __init__(self, sock: socket.socket) -> None: ... +# These are based in socket, maybe move them out into _typeshed.pyi or such +_Address: TypeAlias = socket._Address +_RetAddress: TypeAlias = Any +_WriteBuffer: TypeAlias = bytearray | memoryview +_CMSG: TypeAlias = tuple[int, int, bytes] + +class TransportSocket: + __slots__ = ("_sock",) + def __init__(self, sock: socket.socket) -> None: ... + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... + def __getstate__(self) -> Never: ... + def fileno(self) -> int: ... + def dup(self) -> socket.socket: ... + def get_inheritable(self) -> bool: ... + def shutdown(self, how: int) -> None: ... + + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + + @overload + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer) -> None: ... + @overload + def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... + + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + def getsockbyname(self) -> Never: ... # This method doesn't exist on socket, yet is passed through? + def settimeout(self, value: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, flag: bool) -> None: ... + if sys.version_info < (3, 11): def _na(self, what: str) -> None: ... - @property - def family(self) -> int: ... - @property - def type(self) -> int: ... - @property - def proto(self) -> int: ... - def __getstate__(self) -> NoReturn: ... - def fileno(self) -> int: ... - def dup(self) -> socket.socket: ... - def get_inheritable(self) -> bool: ... - def shutdown(self, how: int) -> None: ... - @overload - def getsockopt(self, level: int, optname: int) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - @overload - def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... - @overload - def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... - def getpeername(self) -> _RetAddress: ... - def getsockname(self) -> _RetAddress: ... - def getsockbyname(self) -> NoReturn: ... # This method doesn't exist on socket, yet is passed through? + @deprecated("Removed in Python 3.11") def accept(self) -> tuple[socket.socket, _RetAddress]: ... - def connect(self, address: _Address | bytes) -> None: ... - def connect_ex(self, address: _Address | bytes) -> int: ... - def bind(self, address: _Address | bytes) -> None: ... + @deprecated("Removed in Python 3.11") + def connect(self, address: _Address) -> None: ... + @deprecated("Removed in Python 3.11") + def connect_ex(self, address: _Address) -> int: ... + @deprecated("Removed in Python 3.11") + def bind(self, address: _Address) -> None: ... + if sys.platform == "win32": + @deprecated("Removed in Python 3.11") def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... else: - def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ... - def listen(self, __backlog: int = ...) -> None: ... + @deprecated("Removed in Python 3.11") + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> Never: ... + + @deprecated("Removed in Python 3.11") + def listen(self, backlog: int = ..., /) -> None: ... + @deprecated("Removed in Python 3.11") def makefile(self) -> BinaryIO: ... - def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... + @deprecated("Removed in Python 3.11") + def sendfile(self, file: BinaryIO, offset: int = 0, count: int | None = None) -> int: ... + @deprecated("Removed in Python 3.11") def close(self) -> None: ... + @deprecated("Removed in Python 3.11") def detach(self) -> int: ... + if sys.platform == "linux": + @deprecated("Removed in Python 3.11") def sendmsg_afalg( - self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 ) -> int: ... else: + @deprecated("Removed in Python 3.11.") def sendmsg_afalg( - self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... - ) -> NoReturn: ... + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 + ) -> Never: ... + + @deprecated("Removed in Python 3.11.") def sendmsg( - self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... + self, + buffers: Iterable[ReadableBuffer], + ancdata: Iterable[_CMSG] = ..., + flags: int = 0, + address: _Address | None = None, + /, ) -> int: ... + @overload - def sendto(self, data: bytes, address: _Address) -> int: ... + @deprecated("Removed in Python 3.11.") + def sendto(self, data: ReadableBuffer, address: _Address) -> int: ... @overload - def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... - def send(self, data: bytes, flags: int = ...) -> int: ... - def sendall(self, data: bytes, flags: int = ...) -> None: ... + @deprecated("Removed in Python 3.11.") + def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ... + + @deprecated("Removed in Python 3.11.") + def send(self, data: ReadableBuffer, flags: int = 0) -> int: ... + @deprecated("Removed in Python 3.11.") + def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ... + @deprecated("Removed in Python 3.11.") def set_inheritable(self, inheritable: bool) -> None: ... + if sys.platform == "win32": + @deprecated("Removed in Python 3.11.") def share(self, process_id: int) -> bytes: ... else: - def share(self, process_id: int) -> NoReturn: ... - def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... - def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... + @deprecated("Removed in Python 3.11.") + def share(self, process_id: int) -> Never: ... + + @deprecated("Removed in Python 3.11.") + def recv_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> int: ... + @deprecated("Removed in Python 3.11.") + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ... + @deprecated("Removed in Python 3.11.") def recvmsg_into( - self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... + self, buffers: Iterable[_WriteBuffer], ancbufsize: int = 0, flags: int = 0, / ) -> tuple[int, list[_CMSG], int, Any]: ... - def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... - def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... - def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def settimeout(self, value: float | None) -> None: ... - def gettimeout(self) -> float | None: ... - def setblocking(self, flag: bool) -> None: ... + @deprecated("Removed in Python 3.11.") + def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ... + @deprecated("Removed in Python 3.11.") + def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[bytes, _RetAddress]: ... + @deprecated("Removed in Python 3.11.") + def recv(self, bufsize: int, flags: int = 0) -> bytes: ... + @deprecated("Removed in Python 3.11.") def __enter__(self) -> socket.socket: ... + @deprecated("Removed in Python 3.11.") def __exit__( self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... diff --git a/stdlib/asyncio/unix_events.pyi b/stdlib/asyncio/unix_events.pyi index e8e57a20a765..368cac38302f 100644 --- a/stdlib/asyncio/unix_events.pyi +++ b/stdlib/asyncio/unix_events.pyi @@ -1,61 +1,277 @@ import sys import types -from _typeshed import Self +from _typeshed import StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import Callable from socket import socket -from typing import Any, Callable, Type +from typing import Literal +from typing_extensions import Self, TypeVarTuple, Unpack, deprecated -from .base_events import Server -from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy, _ProtocolFactory, _SSLContext +from . import events +from .base_events import Server, _ProtocolFactory, _SSLContext from .selector_events import BaseSelectorEventLoop -class AbstractChildWatcher: - def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - def close(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - if sys.version_info >= (3, 8): - def is_active(self) -> bool: ... - -class BaseChildWatcher(AbstractChildWatcher): - def __init__(self) -> None: ... - -class SafeChildWatcher(BaseChildWatcher): - def __enter__(self: Self) -> Self: ... - -class FastChildWatcher(BaseChildWatcher): - def __enter__(self: Self) -> Self: ... - -class _UnixSelectorEventLoop(BaseSelectorEventLoop): - if sys.version_info < (3, 7): - async def create_unix_server( - self, - protocol_factory: _ProtocolFactory, - path: str | None = ..., - *, - sock: socket | None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - ) -> Server: ... - -class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): - def get_child_watcher(self) -> AbstractChildWatcher: ... - def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... - -SelectorEventLoop = _UnixSelectorEventLoop - -DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy - -if sys.version_info >= (3, 8): - - from typing import Protocol - class _Warn(Protocol): - def __call__( - self, message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... - ) -> None: ... - class MultiLoopChildWatcher(AbstractChildWatcher): - def __enter__(self: Self) -> Self: ... - class ThreadedChildWatcher(AbstractChildWatcher): - def __enter__(self: Self) -> Self: ... - def __del__(self, _warn: _Warn = ...) -> None: ... +_Ts = TypeVarTuple("_Ts") + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.platform != "win32": + if sys.version_info >= (3, 14): + __all__ = ("SelectorEventLoop", "EventLoop") + elif sys.version_info >= (3, 13): + # Adds EventLoop + __all__ = ( + "SelectorEventLoop", + "AbstractChildWatcher", + "SafeChildWatcher", + "FastChildWatcher", + "PidfdChildWatcher", + "MultiLoopChildWatcher", + "ThreadedChildWatcher", + "DefaultEventLoopPolicy", + "EventLoop", + ) + else: + # adds PidfdChildWatcher + __all__ = ( + "SelectorEventLoop", + "AbstractChildWatcher", + "SafeChildWatcher", + "FastChildWatcher", + "PidfdChildWatcher", + "MultiLoopChildWatcher", + "ThreadedChildWatcher", + "DefaultEventLoopPolicy", + ) + +# This is also technically not available on Win, +# but other parts of typeshed need this definition. +# So, it is special cased. +if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class AbstractChildWatcher: + @abstractmethod + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + @abstractmethod + def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + def __enter__(self) -> Self: ... + @abstractmethod + def __exit__( + self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None + ) -> None: ... + @abstractmethod + def is_active(self) -> bool: ... + + else: + class AbstractChildWatcher: + @abstractmethod + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + @abstractmethod + def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + def __enter__(self) -> Self: ... + @abstractmethod + def __exit__( + self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None + ) -> None: ... + @abstractmethod + def is_active(self) -> bool: ... + +if sys.platform != "win32": + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): + def close(self) -> None: ... + def is_active(self) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class SafeChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class FastChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + else: + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): + def close(self) -> None: ... + def is_active(self) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + class SafeChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + class FastChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + class _UnixSelectorEventLoop(BaseSelectorEventLoop): + if sys.version_info >= (3, 13): + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: StrPath | None = None, + *, + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + cleanup_socket: bool = True, + ) -> Server: ... + + if sys.version_info >= (3, 14): + class _UnixDefaultEventLoopPolicy(events._BaseDefaultEventLoopPolicy): ... + else: + class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + if sys.version_info >= (3, 12): + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + else: + def get_child_watcher(self) -> AbstractChildWatcher: ... + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + + SelectorEventLoop = _UnixSelectorEventLoop + + if sys.version_info >= (3, 14): + _DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy + else: + DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy + + if sys.version_info >= (3, 13): + EventLoop = SelectorEventLoop + + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class MultiLoopChildWatcher(AbstractChildWatcher): + def is_active(self) -> bool: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class ThreadedChildWatcher(AbstractChildWatcher): + def is_active(self) -> Literal[True]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class PidfdChildWatcher(AbstractChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + else: + class MultiLoopChildWatcher(AbstractChildWatcher): + def is_active(self) -> bool: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + class ThreadedChildWatcher(AbstractChildWatcher): + def is_active(self) -> Literal[True]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + class PidfdChildWatcher(AbstractChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... diff --git a/stdlib/asyncio/windows_events.pyi b/stdlib/asyncio/windows_events.pyi index 6d17bada312f..a2428e425f2f 100644 --- a/stdlib/asyncio/windows_events.pyi +++ b/stdlib/asyncio/windows_events.pyi @@ -1,80 +1,122 @@ import socket import sys -from _typeshed import WriteableBuffer -from typing import IO, Any, Callable, ClassVar, NoReturn, Type +from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from typing import IO, Any, ClassVar, Final +from typing_extensions import Never from . import events, futures, proactor_events, selector_events, streams, windows_utils -if sys.version_info >= (3, 7): - __all__ = ( - "SelectorEventLoop", - "ProactorEventLoop", - "IocpProactor", - "DefaultEventLoopPolicy", - "WindowsSelectorEventLoopPolicy", - "WindowsProactorEventLoopPolicy", - ) -else: - __all__ = ["SelectorEventLoop", "ProactorEventLoop", "IocpProactor", "DefaultEventLoopPolicy"] +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.platform == "win32": + if sys.version_info >= (3, 14): + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "_DefaultEventLoopPolicy", + "_WindowsSelectorEventLoopPolicy", + "_WindowsProactorEventLoopPolicy", + "EventLoop", + ) + elif sys.version_info >= (3, 13): + # 3.13 added `EventLoop`. + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", + "EventLoop", + ) + else: + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", + ) -NULL: int -INFINITE: int -ERROR_CONNECTION_REFUSED: int -ERROR_CONNECTION_ABORTED: int -CONNECT_PIPE_INIT_DELAY: float -CONNECT_PIPE_MAX_DELAY: float + NULL: Final = 0 + INFINITE: Final = 0xFFFFFFFF + ERROR_CONNECTION_REFUSED: Final = 1225 + ERROR_CONNECTION_ABORTED: Final = 1236 + CONNECT_PIPE_INIT_DELAY: float + CONNECT_PIPE_MAX_DELAY: float -class PipeServer: - def __init__(self, address: str) -> None: ... - def __del__(self) -> None: ... - def closed(self) -> bool: ... - def close(self) -> None: ... + class PipeServer: + def __init__(self, address: str) -> None: ... + def __del__(self) -> None: ... + def closed(self) -> bool: ... + def close(self) -> None: ... -class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... + class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... -class ProactorEventLoop(proactor_events.BaseProactorEventLoop): - def __init__(self, proactor: IocpProactor | None = ...) -> None: ... - async def create_pipe_connection( - self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str - ) -> tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... - async def start_serving_pipe( - self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str - ) -> list[PipeServer]: ... + class ProactorEventLoop(proactor_events.BaseProactorEventLoop): + def __init__(self, proactor: IocpProactor | None = None) -> None: ... + async def create_pipe_connection( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... + async def start_serving_pipe( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> list[PipeServer]: ... -class IocpProactor: - def __init__(self, concurrency: int = ...) -> None: ... - def __repr__(self) -> str: ... - def __del__(self) -> None: ... - def set_loop(self, loop: events.AbstractEventLoop) -> None: ... - def select(self, timeout: int | None = ...) -> list[futures.Future[Any]]: ... - def recv(self, conn: socket.socket, nbytes: int, flags: int = ...) -> futures.Future[bytes]: ... - if sys.version_info >= (3, 7): - def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... - def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... - def accept(self, listener: socket.socket) -> futures.Future[Any]: ... - def connect(self, conn: socket.socket, address: bytes) -> futures.Future[Any]: ... - if sys.version_info >= (3, 7): + class IocpProactor: + def __init__(self, concurrency: int = 0xFFFFFFFF) -> None: ... + def __del__(self) -> None: ... + def set_loop(self, loop: events.AbstractEventLoop) -> None: ... + def select(self, timeout: int | None = None) -> list[futures.Future[Any]]: ... + def recv(self, conn: socket.socket, nbytes: int, flags: int = 0) -> futures.Future[bytes]: ... + def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0) -> futures.Future[Any]: ... + def recvfrom( + self, conn: socket.socket, nbytes: int, flags: int = 0 + ) -> futures.Future[tuple[bytes, socket._RetAddress]]: ... + def sendto( + self, conn: socket.socket, buf: ReadableBuffer, flags: int = 0, addr: socket._Address | None = None + ) -> futures.Future[int]: ... + def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0) -> futures.Future[Any]: ... + def accept(self, listener: socket.socket) -> futures.Future[Any]: ... + def connect( + self, + conn: socket.socket, + address: tuple[Incomplete, Incomplete] | tuple[Incomplete, Incomplete, Incomplete, Incomplete], + ) -> futures.Future[Any]: ... def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... - def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... - async def connect_pipe(self, address: bytes) -> windows_utils.PipeHandle: ... - def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = ...) -> bool: ... - def close(self) -> None: ... + def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... + async def connect_pipe(self, address: str) -> windows_utils.PipeHandle: ... + def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = None) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 11): + def recvfrom_into( + self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0 + ) -> futures.Future[tuple[int, socket._RetAddress]]: ... -SelectorEventLoop = _WindowsSelectorEventLoop + SelectorEventLoop = _WindowsSelectorEventLoop -if sys.version_info >= (3, 7): - class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[SelectorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... - class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[ProactorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... - DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy -else: - class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[SelectorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... - DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy + if sys.version_info >= (3, 14): + class _WindowsSelectorEventLoopPolicy(events._BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[SelectorEventLoop]] + + class _WindowsProactorEventLoopPolicy(events._BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[ProactorEventLoop]] + + else: + class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[SelectorEventLoop]] + def get_child_watcher(self) -> Never: ... + def set_child_watcher(self, watcher: Any) -> Never: ... + + class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[ProactorEventLoop]] + def get_child_watcher(self) -> Never: ... + def set_child_watcher(self, watcher: Any) -> Never: ... + + if sys.version_info >= (3, 14): + _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy + else: + DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy + if sys.version_info >= (3, 13): + EventLoop = ProactorEventLoop diff --git a/stdlib/asyncio/windows_utils.pyi b/stdlib/asyncio/windows_utils.pyi index bf9cdde25a78..5cedd61b5f4a 100644 --- a/stdlib/asyncio/windows_utils.pyi +++ b/stdlib/asyncio/windows_utils.pyi @@ -1,27 +1,49 @@ +import subprocess import sys -from _typeshed import Self +from collections.abc import Callable from types import TracebackType -from typing import Callable, Protocol, Type +from typing import Any, AnyStr, Final +from typing_extensions import Self -class _WarnFunction(Protocol): - def __call__(self, message: str, category: Type[Warning] = ..., stacklevel: int = ..., source: PipeHandle = ...) -> None: ... +if sys.platform == "win32": + __all__ = ("pipe", "Popen", "PIPE", "PipeHandle") -BUFSIZE: int -PIPE: int -STDOUT: int + BUFSIZE: Final = 8192 + PIPE: Final = subprocess.PIPE + STDOUT: Final = subprocess.STDOUT + def pipe(*, duplex: bool = False, overlapped: tuple[bool, bool] = (True, True), bufsize: int = 8192) -> tuple[int, int]: ... -def pipe(*, duplex: bool = ..., overlapped: tuple[bool, bool] = ..., bufsize: int = ...) -> tuple[int, int]: ... - -class PipeHandle: - def __init__(self, handle: int) -> None: ... - def __repr__(self) -> str: ... - if sys.version_info >= (3, 8): - def __del__(self, _warn: _WarnFunction = ...) -> None: ... - else: + class PipeHandle: + def __init__(self, handle: int) -> None: ... def __del__(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, t: type | None, v: BaseException | None, tb: TracebackType | None) -> None: ... - @property - def handle(self) -> int: ... - def fileno(self) -> int: ... - def close(self, *, CloseHandle: Callable[[int], None] = ...) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + @property + def handle(self) -> int: ... + def fileno(self) -> int: ... + def close(self, *, CloseHandle: Callable[[int], object] = ...) -> None: ... + + class Popen(subprocess.Popen[AnyStr]): + stdin: PipeHandle | None # type: ignore[assignment] + stdout: PipeHandle | None # type: ignore[assignment] + stderr: PipeHandle | None # type: ignore[assignment] + # For simplicity we omit the full overloaded __new__ signature of + # subprocess.Popen. The arguments are mostly the same, but + # subprocess.Popen takes other positional-or-keyword arguments before + # stdin. + def __new__( + cls, + args: subprocess._CMD, + stdin: subprocess._FILE | None = None, + stdout: subprocess._FILE | None = None, + stderr: subprocess._FILE | None = None, + **kwds: Any, + ) -> Self: ... + def __init__( + self, + args: subprocess._CMD, + stdin: subprocess._FILE | None = None, + stdout: subprocess._FILE | None = None, + stderr: subprocess._FILE | None = None, + **kwds: Any, + ) -> None: ... diff --git a/stdlib/asyncore.pyi b/stdlib/asyncore.pyi index e135221134a5..96f9f637c733 100644 --- a/stdlib/asyncore.pyi +++ b/stdlib/asyncore.pyi @@ -1,54 +1,53 @@ import sys -from _typeshed import FileDescriptorLike +from _typeshed import FileDescriptorLike, ReadableBuffer from socket import socket -from typing import Any, Dict, Tuple, overload +from typing import Any, TypeAlias, overload # cyclic dependence with asynchat -_maptype = Dict[int, Any] -_socket = socket +_MapType: TypeAlias = dict[int, Any] +_Socket: TypeAlias = socket -socket_map: _maptype # undocumented +socket_map: _MapType # undocumented class ExitNow(Exception): ... def read(obj: Any) -> None: ... def write(obj: Any) -> None: ... def readwrite(obj: Any, flags: int) -> None: ... -def poll(timeout: float = ..., map: _maptype | None = ...) -> None: ... -def poll2(timeout: float = ..., map: _maptype | None = ...) -> None: ... +def poll(timeout: float = 0.0, map: _MapType | None = None) -> None: ... +def poll2(timeout: float = 0.0, map: _MapType | None = None) -> None: ... poll3 = poll2 -def loop(timeout: float = ..., use_poll: bool = ..., map: _maptype | None = ..., count: int | None = ...) -> None: ... +def loop(timeout: float = 30.0, use_poll: bool = False, map: _MapType | None = None, count: int | None = None) -> None: ... # Not really subclass of socket.socket; it's only delegation. # It is not covariant to it. class dispatcher: - debug: bool connected: bool accepting: bool connecting: bool closing: bool ignore_log_types: frozenset[str] - socket: _socket | None - def __init__(self, sock: _socket | None = ..., map: _maptype | None = ...) -> None: ... - def add_channel(self, map: _maptype | None = ...) -> None: ... - def del_channel(self, map: _maptype | None = ...) -> None: ... + socket: _Socket | None + def __init__(self, sock: _Socket | None = None, map: _MapType | None = None) -> None: ... + def add_channel(self, map: _MapType | None = None) -> None: ... + def del_channel(self, map: _MapType | None = None) -> None: ... def create_socket(self, family: int = ..., type: int = ...) -> None: ... - def set_socket(self, sock: _socket, map: _maptype | None = ...) -> None: ... + def set_socket(self, sock: _Socket, map: _MapType | None = None) -> None: ... def set_reuse_addr(self) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def listen(self, num: int) -> None: ... - def bind(self, addr: Tuple[Any, ...] | str) -> None: ... - def connect(self, address: Tuple[Any, ...] | str) -> None: ... - def accept(self) -> tuple[_socket, Any] | None: ... - def send(self, data: bytes) -> int: ... + def bind(self, addr: tuple[Any, ...] | str) -> None: ... + def connect(self, address: tuple[Any, ...] | str) -> None: ... + def accept(self) -> tuple[_Socket, Any] | None: ... + def send(self, data: ReadableBuffer) -> int: ... def recv(self, buffer_size: int) -> bytes: ... def close(self) -> None: ... def log(self, message: Any) -> None: ... - def log_info(self, message: Any, type: str = ...) -> None: ... + def log_info(self, message: Any, type: str = "info") -> None: ... def handle_read_event(self) -> None: ... def handle_connect_event(self) -> None: ... def handle_write_event(self) -> None: ... @@ -62,14 +61,12 @@ class dispatcher: def handle_close(self) -> None: ... class dispatcher_with_send(dispatcher): - def __init__(self, sock: socket | None = ..., map: _maptype | None = ...) -> None: ... def initiate_send(self) -> None: ... - def handle_write(self) -> None: ... # incompatible signature: # def send(self, data: bytes) -> int | None: ... def compact_traceback() -> tuple[tuple[str, str, str], type, type, str]: ... -def close_all(map: _maptype | None = ..., ignore_all: bool = ...) -> None: ... +def close_all(map: _MapType | None = None, ignore_all: bool = False) -> None: ... if sys.platform != "win32": class file_wrapper: @@ -77,14 +74,18 @@ if sys.platform != "win32": def __init__(self, fd: int) -> None: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... def send(self, data: bytes, flags: int = ...) -> int: ... + @overload - def getsockopt(self, level: int, optname: int, buflen: None = ...) -> int: ... + def getsockopt(self, level: int, optname: int, buflen: None = None) -> int: ... @overload def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + def read(self, bufsize: int, flags: int = ...) -> bytes: ... def write(self, data: bytes, flags: int = ...) -> int: ... def close(self) -> None: ... def fileno(self) -> int: ... + def __del__(self) -> None: ... + class file_dispatcher(dispatcher): - def __init__(self, fd: FileDescriptorLike, map: _maptype | None = ...) -> None: ... + def __init__(self, fd: FileDescriptorLike, map: _MapType | None = None) -> None: ... def set_file(self, fd: int) -> None: ... diff --git a/stdlib/atexit.pyi b/stdlib/atexit.pyi index 9395c60678b8..9177d80169be 100644 --- a/stdlib/atexit.pyi +++ b/stdlib/atexit.pyi @@ -1,5 +1,5 @@ -from typing import Any, Callable, TypeVar -from typing_extensions import ParamSpec +from collections.abc import Callable +from typing import ParamSpec, TypeVar _T = TypeVar("_T") _P = ParamSpec("_P") @@ -7,5 +7,5 @@ _P = ParamSpec("_P") def _clear() -> None: ... def _ncallbacks() -> int: ... def _run_exitfuncs() -> None: ... -def register(func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: ... # type: ignore -def unregister(func: Callable[..., Any]) -> None: ... +def register(func: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: ... +def unregister(func: Callable[..., object], /) -> None: ... diff --git a/stdlib/audioop.pyi b/stdlib/audioop.pyi index 321bfe55c4b0..a7d5e8adb7a5 100644 --- a/stdlib/audioop.pyi +++ b/stdlib/audioop.pyi @@ -1,42 +1,44 @@ -from typing import Tuple +from typing import TypeAlias +from typing_extensions import Buffer -AdpcmState = Tuple[int, int] -RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] +_AdpcmState: TypeAlias = tuple[int, int] +_RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... -def add(__fragment1: bytes, __fragment2: bytes, __width: int) -> bytes: ... -def adpcm2lin(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... -def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... -def avg(__fragment: bytes, __width: int) -> int: ... -def avgpp(__fragment: bytes, __width: int) -> int: ... -def bias(__fragment: bytes, __width: int, __bias: int) -> bytes: ... -def byteswap(__fragment: bytes, __width: int) -> bytes: ... -def cross(__fragment: bytes, __width: int) -> int: ... -def findfactor(__fragment: bytes, __reference: bytes) -> float: ... -def findfit(__fragment: bytes, __reference: bytes) -> tuple[int, float]: ... -def findmax(__fragment: bytes, __length: int) -> int: ... -def getsample(__fragment: bytes, __width: int, __index: int) -> int: ... -def lin2adpcm(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... -def lin2alaw(__fragment: bytes, __width: int) -> bytes: ... -def lin2lin(__fragment: bytes, __width: int, __newwidth: int) -> bytes: ... -def lin2ulaw(__fragment: bytes, __width: int) -> bytes: ... -def max(__fragment: bytes, __width: int) -> int: ... -def maxpp(__fragment: bytes, __width: int) -> int: ... -def minmax(__fragment: bytes, __width: int) -> tuple[int, int]: ... -def mul(__fragment: bytes, __width: int, __factor: float) -> bytes: ... +def add(fragment1: Buffer, fragment2: Buffer, width: int, /) -> bytes: ... +def adpcm2lin(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def alaw2lin(fragment: Buffer, width: int, /) -> bytes: ... +def avg(fragment: Buffer, width: int, /) -> int: ... +def avgpp(fragment: Buffer, width: int, /) -> int: ... +def bias(fragment: Buffer, width: int, bias: int, /) -> bytes: ... +def byteswap(fragment: Buffer, width: int, /) -> bytes: ... +def cross(fragment: Buffer, width: int, /) -> int: ... +def findfactor(fragment: Buffer, reference: Buffer, /) -> float: ... +def findfit(fragment: Buffer, reference: Buffer, /) -> tuple[int, float]: ... +def findmax(fragment: Buffer, length: int, /) -> int: ... +def getsample(fragment: Buffer, width: int, index: int, /) -> int: ... +def lin2adpcm(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def lin2alaw(fragment: Buffer, width: int, /) -> bytes: ... +def lin2lin(fragment: Buffer, width: int, newwidth: int, /) -> bytes: ... +def lin2ulaw(fragment: Buffer, width: int, /) -> bytes: ... +def max(fragment: Buffer, width: int, /) -> int: ... +def maxpp(fragment: Buffer, width: int, /) -> int: ... +def minmax(fragment: Buffer, width: int, /) -> tuple[int, int]: ... +def mul(fragment: Buffer, width: int, factor: float, /) -> bytes: ... def ratecv( - __fragment: bytes, - __width: int, - __nchannels: int, - __inrate: int, - __outrate: int, - __state: RatecvState | None, - __weightA: int = ..., - __weightB: int = ..., -) -> tuple[bytes, RatecvState]: ... -def reverse(__fragment: bytes, __width: int) -> bytes: ... -def rms(__fragment: bytes, __width: int) -> int: ... -def tomono(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... -def tostereo(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... -def ulaw2lin(__fragment: bytes, __width: int) -> bytes: ... + fragment: Buffer, + width: int, + nchannels: int, + inrate: int, + outrate: int, + state: _RatecvState | None, + weightA: int = 1, + weightB: int = 0, + /, +) -> tuple[bytes, _RatecvState]: ... +def reverse(fragment: Buffer, width: int, /) -> bytes: ... +def rms(fragment: Buffer, width: int, /) -> int: ... +def tomono(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def tostereo(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def ulaw2lin(fragment: Buffer, width: int, /) -> bytes: ... diff --git a/stdlib/base64.pyi b/stdlib/base64.pyi index 8610eea17b52..dd4782142852 100644 --- a/stdlib/base64.pyi +++ b/stdlib/base64.pyi @@ -1,30 +1,124 @@ import sys -from typing import IO - -def b64encode(s: bytes, altchars: bytes | None = ...) -> bytes: ... -def b64decode(s: str | bytes, altchars: bytes | None = ..., validate: bool = ...) -> bytes: ... -def standard_b64encode(s: bytes) -> bytes: ... -def standard_b64decode(s: str | bytes) -> bytes: ... -def urlsafe_b64encode(s: bytes) -> bytes: ... -def urlsafe_b64decode(s: str | bytes) -> bytes: ... -def b32encode(s: bytes) -> bytes: ... -def b32decode(s: str | bytes, casefold: bool = ..., map01: bytes | None = ...) -> bytes: ... -def b16encode(s: bytes) -> bytes: ... -def b16decode(s: str | bytes, casefold: bool = ...) -> bytes: ... - -if sys.version_info >= (3, 10): - def b32hexencode(s: bytes) -> bytes: ... - def b32hexdecode(s: str | bytes, casefold: bool = ...) -> bytes: ... - -def a85encode(b: bytes, *, foldspaces: bool = ..., wrapcol: int = ..., pad: bool = ..., adobe: bool = ...) -> bytes: ... -def a85decode(b: str | bytes, *, foldspaces: bool = ..., adobe: bool = ..., ignorechars: str | bytes = ...) -> bytes: ... -def b85encode(b: bytes, pad: bool = ...) -> bytes: ... -def b85decode(b: str | bytes) -> bytes: ... -def decode(input: IO[bytes], output: IO[bytes]) -> None: ... -def encode(input: IO[bytes], output: IO[bytes]) -> None: ... -def encodebytes(s: bytes) -> bytes: ... -def decodebytes(s: bytes) -> bytes: ... - -if sys.version_info < (3, 9): - def encodestring(s: bytes) -> bytes: ... - def decodestring(s: bytes) -> bytes: ... +from _typeshed import ReadableBuffer, SupportsNoArgReadline, SupportsRead, SupportsWrite + +__all__ = [ + "encode", + "decode", + "encodebytes", + "decodebytes", + "b64encode", + "b64decode", + "b32encode", + "b32decode", + "b16encode", + "b16decode", + "b32hexencode", + "b32hexdecode", + "b85encode", + "b85decode", + "a85encode", + "a85decode", + "standard_b64encode", + "standard_b64decode", + "urlsafe_b64encode", + "urlsafe_b64decode", +] + +if sys.version_info >= (3, 13): + __all__ += ["z85decode", "z85encode"] + +if sys.version_info >= (3, 15): + def b64encode( + s: ReadableBuffer, altchars: ReadableBuffer | None = None, *, padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def b64decode( + s: str | ReadableBuffer, + altchars: str | ReadableBuffer | None = None, + validate: bool = ..., + *, + padded: bool = True, + ignorechars: ReadableBuffer = ..., + canonical: bool = False, + ) -> bytes: ... + +else: + def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: ... + def b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = None, validate: bool = False) -> bytes: ... + +def standard_b64encode(s: ReadableBuffer) -> bytes: ... +def standard_b64decode(s: str | ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 15): + def urlsafe_b64encode(s: ReadableBuffer, *, padded: bool = True) -> bytes: ... + def urlsafe_b64decode(s: str | ReadableBuffer, *, padded: bool = False) -> bytes: ... + def b32encode(s: ReadableBuffer, *, padded: bool = True, wrapcol: int = 0) -> bytes: ... + def b32decode( + s: str | ReadableBuffer, + casefold: bool = False, + map01: str | ReadableBuffer | None = None, + *, + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b16encode(s: ReadableBuffer, *, wrapcol: int = 0) -> bytes: ... + def b16decode(s: str | ReadableBuffer, casefold: bool = False, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + +else: + def urlsafe_b64encode(s: ReadableBuffer) -> bytes: ... + def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: ... + def b32encode(s: ReadableBuffer) -> bytes: ... + def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes: ... + def b16encode(s: ReadableBuffer) -> bytes: ... + def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... + +if sys.version_info >= (3, 15): + def b32hexencode(s: ReadableBuffer, *, padded: bool = True, wrapcol: int = 0) -> bytes: ... + def b32hexdecode( + s: str | ReadableBuffer, + casefold: bool = False, + *, + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + +else: + def b32hexencode(s: ReadableBuffer) -> bytes: ... + def b32hexdecode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... + +def a85encode( + b: ReadableBuffer, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False +) -> bytes: ... + +if sys.version_info >= (3, 15): + def a85decode( + b: str | ReadableBuffer, + *, + foldspaces: bool = False, + adobe: bool = False, + ignorechars: bytearray | bytes = b" \t\n\r\x0b", + canonical: bool = False, + ) -> bytes: ... + def b85encode(b: ReadableBuffer, pad: bool = False, *, wrapcol: int = 0) -> bytes: ... + def b85decode(b: str | ReadableBuffer, *, ignorechars: ReadableBuffer = b"", canonical: bool = False) -> bytes: ... + +else: + def a85decode( + b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b" + ) -> bytes: ... + def b85encode(b: ReadableBuffer, pad: bool = False) -> bytes: ... + def b85decode(b: str | ReadableBuffer) -> bytes: ... + +def decode(input: SupportsNoArgReadline[bytes], output: SupportsWrite[bytes]) -> None: ... +def encode(input: SupportsRead[bytes], output: SupportsWrite[bytes]) -> None: ... +def encodebytes(s: ReadableBuffer) -> bytes: ... +def decodebytes(s: ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 13): + if sys.version_info >= (3, 15): + def z85encode(s: ReadableBuffer, pad: bool = False, *, wrapcol: int = 0) -> bytes: ... + def z85decode(s: str | ReadableBuffer, *, ignorechars: ReadableBuffer = b"", canonical: bool = False) -> bytes: ... + else: + def z85encode(s: ReadableBuffer) -> bytes: ... + def z85decode(s: str | ReadableBuffer) -> bytes: ... diff --git a/stdlib/bdb.pyi b/stdlib/bdb.pyi index 1d03ddf19a0e..c2c45e2684b4 100644 --- a/stdlib/bdb.pyi +++ b/stdlib/bdb.pyi @@ -1,16 +1,24 @@ +import sys +from _typeshed import ExcInfo, ReadableBuffer, TraceFunction, Unused +from collections.abc import Callable, Iterable, Iterator, Mapping +from contextlib import contextmanager from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, Tuple, Type, TypeVar +from typing import IO, Any, Final, Literal, ParamSpec, SupportsInt, TypeAlias, TypeVar + +__all__ = ["BdbQuit", "Bdb", "Breakpoint"] _T = TypeVar("_T") -_TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] +_P = ParamSpec("_P") +_Backend: TypeAlias = Literal["settrace", "monitoring"] -GENERATOR_AND_COROUTINE_FLAGS: int +# A union of code-object flags at runtime. +# The exact values of code-object flags are implementation details, +# so we don't include the value of this constant in the stubs. +GENERATOR_AND_COROUTINE_FLAGS: Final[int] class BdbQuit(Exception): ... class Bdb: - skip: set[str] | None breaks: dict[str, list[int]] fncache: dict[str, str] @@ -20,14 +28,26 @@ class Bdb: stopframe: FrameType | None returnframe: FrameType | None stoplineno: int - def __init__(self, skip: Iterable[str] | None = ...) -> None: ... + if sys.version_info >= (3, 14): + backend: _Backend + def __init__(self, skip: Iterable[str] | None = None, backend: _Backend = "settrace") -> None: ... + else: + def __init__(self, skip: Iterable[str] | None = None) -> None: ... + def canonic(self, filename: str) -> str: ... def reset(self) -> None: ... - def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> _TraceDispatch: ... - def dispatch_line(self, frame: FrameType) -> _TraceDispatch: ... - def dispatch_call(self, frame: FrameType, arg: None) -> _TraceDispatch: ... - def dispatch_return(self, frame: FrameType, arg: Any) -> _TraceDispatch: ... - def dispatch_exception(self, frame: FrameType, arg: _ExcInfo) -> _TraceDispatch: ... + if sys.version_info >= (3, 12): + @contextmanager + def set_enterframe(self, frame: FrameType) -> Iterator[None]: ... + + def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> TraceFunction: ... + def dispatch_line(self, frame: FrameType) -> TraceFunction: ... + def dispatch_call(self, frame: FrameType, arg: None) -> TraceFunction: ... + def dispatch_return(self, frame: FrameType, arg: Any) -> TraceFunction: ... + def dispatch_exception(self, frame: FrameType, arg: ExcInfo) -> TraceFunction: ... + if sys.version_info >= (3, 13): + def dispatch_opcode(self, frame: FrameType, arg: Unused) -> Callable[[FrameType, str, Any], TraceFunction]: ... + def is_skipped_module(self, module_name: str) -> bool: ... def stop_here(self, frame: FrameType) -> bool: ... def break_here(self, frame: FrameType) -> bool: ... @@ -36,35 +56,57 @@ class Bdb: def user_call(self, frame: FrameType, argument_list: None) -> None: ... def user_line(self, frame: FrameType) -> None: ... def user_return(self, frame: FrameType, return_value: Any) -> None: ... - def user_exception(self, frame: FrameType, exc_info: _ExcInfo) -> None: ... - def set_until(self, frame: FrameType, lineno: int | None = ...) -> None: ... + def user_exception(self, frame: FrameType, exc_info: ExcInfo) -> None: ... + def set_until(self, frame: FrameType, lineno: int | None = None) -> None: ... + if sys.version_info >= (3, 13): + def user_opcode(self, frame: FrameType) -> None: ... # undocumented + def set_step(self) -> None: ... + if sys.version_info >= (3, 13): + def set_stepinstr(self) -> None: ... # undocumented + def set_next(self, frame: FrameType) -> None: ... def set_return(self, frame: FrameType) -> None: ... - def set_trace(self, frame: FrameType | None = ...) -> None: ... + def set_trace(self, frame: FrameType | None = None) -> None: ... def set_continue(self) -> None: ... def set_quit(self) -> None: ... def set_break( - self, filename: str, lineno: int, temporary: bool = ..., cond: str | None = ..., funcname: str | None = ... - ) -> None: ... - def clear_break(self, filename: str, lineno: int) -> None: ... - def clear_bpbynumber(self, arg: SupportsInt) -> None: ... - def clear_all_file_breaks(self, filename: str) -> None: ... - def clear_all_breaks(self) -> None: ... + self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None + ) -> str | None: ... + def clear_break(self, filename: str, lineno: int) -> str | None: ... + def clear_bpbynumber(self, arg: SupportsInt) -> str | None: ... + def clear_all_file_breaks(self, filename: str) -> str | None: ... + def clear_all_breaks(self) -> str | None: ... def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... def get_break(self, filename: str, lineno: int) -> bool: ... def get_breaks(self, filename: str, lineno: int) -> list[Breakpoint]: ... - def get_file_breaks(self, filename: str) -> list[Breakpoint]: ... - def get_all_breaks(self) -> list[Breakpoint]: ... + def get_file_breaks(self, filename: str) -> list[int]: ... + def get_all_breaks(self) -> dict[str, list[int]]: ... def get_stack(self, f: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: ... - def format_stack_entry(self, frame_lineno: int, lprefix: str = ...) -> str: ... - def run(self, cmd: str | CodeType, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runeval(self, expr: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... + def format_stack_entry(self, frame_lineno: tuple[FrameType, int], lprefix: str = ": ") -> str: ... + def run( # matches `builtins.exec` + self, + cmd: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> None: ... + def runctx( # matches `builtins.exec` + self, cmd: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, object] | None + ) -> None: ... + def runeval( # matches `builtins.eval` + self, + expr: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... + if sys.version_info >= (3, 14): + def start_trace(self) -> None: ... + def stop_trace(self) -> None: ... + def disable_current_event(self) -> None: ... + def restart_events(self) -> None: ... class Breakpoint: - next: int bplist: dict[tuple[str, int], list[Breakpoint]] bpbynumber: list[Breakpoint | None] @@ -80,14 +122,17 @@ class Breakpoint: hits: int number: int def __init__( - self, file: str, line: int, temporary: bool = ..., cond: str | None = ..., funcname: str | None = ... + self, file: str, line: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None ) -> None: ... + if sys.version_info >= (3, 11): + @staticmethod + def clearBreakpoints() -> None: ... + def deleteMe(self) -> None: ... def enable(self) -> None: ... def disable(self) -> None: ... - def bpprint(self, out: IO[str] | None = ...) -> None: ... + def bpprint(self, out: IO[str] | None = None) -> None: ... def bpformat(self) -> str: ... - def __str__(self) -> str: ... def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ... diff --git a/stdlib/binascii.pyi b/stdlib/binascii.pyi index 317bb9979b92..b363f94c1bb5 100644 --- a/stdlib/binascii.pyi +++ b/stdlib/binascii.pyi @@ -1,36 +1,102 @@ import sys +from _typeshed import ReadableBuffer +from typing import SupportsIndex, TypeAlias +from typing_extensions import deprecated -def a2b_uu(__data: str | bytes) -> bytes: ... +# Many functions in binascii accept buffer objects +# or ASCII-only strings. +_AsciiBuffer: TypeAlias = str | ReadableBuffer -if sys.version_info >= (3, 7): - def b2a_uu(__data: bytes, *, backtick: bool = ...) -> bytes: ... +def a2b_uu(data: _AsciiBuffer, /) -> bytes: ... +def b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes: ... + +if sys.version_info >= (3, 15): + ASCII85_ALPHABET: bytes + BINHEX_ALPHABET: bytes + CRYPT_ALPHABET: bytes + UU_ALPHABET: bytes + BASE64_ALPHABET: bytes + URLSAFE_BASE64_ALPHABET: bytes + BASE32_ALPHABET: bytes + BASE32HEX_ALPHABET: bytes + BASE85_ALPHABET: bytes + Z85_ALPHABET: bytes + def a2b_base64( + data: _AsciiBuffer, + /, + *, + strict_mode: bool = False, + alphabet: bytes = ..., + padded: bool = True, + ignorechars: ReadableBuffer = ..., + canonical: bool = False, + ) -> bytes: ... + def b2a_base64( + data: ReadableBuffer, /, *, newline: bool = True, alphabet: ReadableBuffer = ..., padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def b2a_base32( + data: ReadableBuffer, /, *, alphabet: ReadableBuffer = ..., padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def a2b_base32( + data: _AsciiBuffer, + /, + *, + alphabet: bytes = ..., + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b2a_ascii85( + data: ReadableBuffer, /, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False + ) -> bytes: ... + def a2b_ascii85( + data: _AsciiBuffer, + /, + *, + foldspaces: bool = False, + adobe: bool = False, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b2a_base85(data: ReadableBuffer, /, *, alphabet: ReadableBuffer = ..., pad: bool = False, wrapcol: int = 0) -> bytes: ... + def a2b_base85( + data: _AsciiBuffer, /, *, alphabet: bytes = ..., ignorechars: ReadableBuffer = b"", canonical: bool = False + ) -> bytes: ... + +elif sys.version_info >= (3, 11): + def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: ... else: - def b2a_uu(__data: bytes) -> bytes: ... + def a2b_base64(data: _AsciiBuffer, /) -> bytes: ... -def a2b_base64(__data: str | bytes) -> bytes: ... -def b2a_base64(__data: bytes, *, newline: bool = ...) -> bytes: ... -def a2b_qp(data: str | bytes, header: bool = ...) -> bytes: ... -def b2a_qp(data: bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... +if sys.version_info < (3, 15): + def b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: ... + +def a2b_qp(data: _AsciiBuffer, header: bool = False) -> bytes: ... +def b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, header: bool = False) -> bytes: ... if sys.version_info < (3, 11): - def a2b_hqx(__data: str | bytes) -> bytes: ... - def rledecode_hqx(__data: bytes) -> bytes: ... - def rlecode_hqx(__data: bytes) -> bytes: ... - def b2a_hqx(__data: bytes) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def a2b_hqx(data: _AsciiBuffer, /) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def rledecode_hqx(data: ReadableBuffer, /) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def rlecode_hqx(data: ReadableBuffer, /) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def b2a_hqx(data: ReadableBuffer, /) -> bytes: ... -def crc_hqx(__data: bytes, __crc: int) -> int: ... -def crc32(__data: bytes, __crc: int = ...) -> int: ... -def b2a_hex(__data: bytes) -> bytes: ... +def crc_hqx(data: ReadableBuffer, crc: SupportsIndex, /) -> int: ... +def crc32(data: ReadableBuffer, crc: SupportsIndex = 0, /) -> int: ... +def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... +def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... -if sys.version_info >= (3, 8): - def hexlify(data: bytes, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... +if sys.version_info >= (3, 15): + def a2b_hex(hexstr: _AsciiBuffer, /, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + def unhexlify(hexstr: _AsciiBuffer, /, *, ignorechars: ReadableBuffer = b"") -> bytes: ... else: - def hexlify(__data: bytes) -> bytes: ... - -def a2b_hex(__hexstr: str | bytes) -> bytes: ... -def unhexlify(__hexstr: str | bytes) -> bytes: ... + def a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: ... + def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: ... class Error(ValueError): ... class Incomplete(Exception): ... diff --git a/stdlib/binhex.pyi b/stdlib/binhex.pyi index 02d094faf923..f309f4e026a5 100644 --- a/stdlib/binhex.pyi +++ b/stdlib/binhex.pyi @@ -1,19 +1,21 @@ -from typing import IO, Any, Tuple, Union +from _typeshed import SizedBuffer +from typing import IO, Any, Final, TypeAlias + +__all__ = ["binhex", "hexbin", "Error"] class Error(Exception): ... -REASONABLY_LARGE: int -LINELEN: int -RUNCHAR: bytes +REASONABLY_LARGE: Final = 32768 +LINELEN: Final = 64 +RUNCHAR: Final = b"\x90" class FInfo: - def __init__(self) -> None: ... Type: str Creator: str Flags: int -_FileInfoTuple = Tuple[str, FInfo, int, int] -_FileHandleUnion = Union[str, IO[bytes]] +_FileInfoTuple: TypeAlias = tuple[str, FInfo, int, int] +_FileHandleUnion: TypeAlias = str | IO[bytes] def getfileinfo(name: str) -> _FileInfoTuple: ... @@ -25,9 +27,9 @@ class openrsrc: class BinHex: def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ... - def write(self, data: bytes) -> None: ... + def write(self, data: SizedBuffer) -> None: ... def close_data(self) -> None: ... - def write_rsrc(self, data: bytes) -> None: ... + def write_rsrc(self, data: SizedBuffer) -> None: ... def close(self) -> None: ... def binhex(inp: str, out: str) -> None: ... diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi index 0daf9d154227..1f16114ed00f 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -1,68 +1,81 @@ +import _ast +import _sitebuiltins +import _typeshed import sys import types -from _ast import AST from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import ( + AnnotationForm, + ConvertibleToFloat, + ConvertibleToInt, + FileDescriptorOrPath, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, ReadableBuffer, - Self, - StrOrBytesPath, + SupportsAdd, + SupportsAiter, SupportsAnext, SupportsDivMod, + SupportsFlush, + SupportsIter, SupportsKeysAndGetItem, SupportsLenAndGetItem, SupportsNext, + SupportsRAdd, SupportsRDivMod, SupportsRichComparison, SupportsRichComparisonT, - SupportsTrunc, SupportsWrite, ) +from collections.abc import Awaitable, Callable, Hashable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from types import CodeType, TracebackType -from typing import ( +from os import PathLike +from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplementedType, TracebackType, UnionType + +# mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} +# are imported from collections.abc in builtins.pyi +from typing import ( # noqa: Y022 # ruff: ignore[deprecated-import] IO, - AbstractSet, Any, BinaryIO, - ByteString, - Callable, + ClassVar, + Concatenate, + Final, Generic, - Iterable, - Iterator, Mapping, MutableMapping, MutableSequence, - MutableSet, - NoReturn, + ParamSpec, Protocol, - Reversible, Sequence, - Sized, SupportsAbs, SupportsBytes, SupportsComplex, SupportsFloat, - SupportsInt, - SupportsRound, - Tuple, - Type, + SupportsIndex, + TypeAlias, + TypeGuard, TypeVar, - Union, + final, overload, + type_check_only, ) -from typing_extensions import Literal, SupportsIndex, TypeGuard, final -if sys.version_info >= (3, 9): - from types import GenericAlias +# we can't import `Literal` from typing or mypy crashes: see #11247 +# ruff: ignore[deprecated-import] +from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 + +if sys.version_info >= (3, 14): + from _typeshed import AnnotateFunc _T = TypeVar("_T") +_I = TypeVar("_I", default=int) _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) +_R_co = TypeVar("_R_co", covariant=True) _KT = TypeVar("_KT") _VT = TypeVar("_VT") _S = TypeVar("_S") @@ -71,319 +84,452 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") -_R = TypeVar("_R") # Return-type TypeVar -_SupportsNextT = TypeVar("_SupportsNextT", bound=SupportsNext[Any], covariant=True) -_SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant=True) - -class _SupportsIter(Protocol[_T_co]): - def __iter__(self) -> _T_co: ... - -class _SupportsAiter(Protocol[_T_co]): - def __aiter__(self) -> _T_co: ... - +_SupportsNextT_co = TypeVar("_SupportsNextT_co", bound=SupportsNext[Any], covariant=True) +_SupportsAnextT_co = TypeVar("_SupportsAnextT_co", bound=SupportsAnext[Any], covariant=True) +_AwaitableT = TypeVar("_AwaitableT", bound=Awaitable[Any]) +_AwaitableT_co = TypeVar("_AwaitableT_co", bound=Awaitable[Any], covariant=True) +_P = ParamSpec("_P") + +# Type variables for slice +_StartT_co = TypeVar("_StartT_co", covariant=True, default=Any) # slice -> slice[Any, Any, Any] +_StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A] -> slice[A, A, A] +# NOTE: step could differ from start and stop, (e.g. datetime/timedelta)l +# the default (start|stop) is chosen to cater to the most common case of int/index slices. +# FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop) +_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] + +@disjoint_base class object: __doc__: str | None __dict__: dict[str, Any] - __slots__: str | Iterable[str] __module__: str __annotations__: dict[str, Any] + @property - def __class__(self: _T) -> Type[_T]: ... - # Ignore errors about type mismatch between property getter and setter + def __class__(self) -> type[Self]: ... @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # type: ignore # noqa: F811 + def __class__(self, type: type[Self], /) -> None: ... + def __init__(self) -> None: ... - def __new__(cls: Type[_T]) -> _T: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... - def __eq__(self, __o: object) -> bool: ... - def __ne__(self, __o: object) -> bool: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... + def __new__(cls) -> Self: ... + # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers. + # Overriding them in subclasses has different semantics, even if the override has an identical signature. + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 def __hash__(self) -> int: ... - def __format__(self, __format_spec: str) -> str: ... - def __getattribute__(self, __name: str) -> Any: ... - def __delattr__(self, __name: str) -> None: ... + def __format__(self, format_spec: str, /) -> str: ... + def __getattribute__(self, name: str, /) -> Any: ... def __sizeof__(self) -> int: ... # return type of pickle methods is rather hard to express in the current type system # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__ - def __reduce__(self) -> str | Tuple[Any, ...]: ... - if sys.version_info >= (3, 8): - def __reduce_ex__(self, __protocol: SupportsIndex) -> str | Tuple[Any, ...]: ... - else: - def __reduce_ex__(self, __protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: ... + if sys.version_info >= (3, 11): + def __getstate__(self) -> object: ... + def __dir__(self) -> Iterable[str]: ... def __init_subclass__(cls) -> None: ... + @classmethod + def __subclasshook__(cls, subclass: type, /) -> bool: ... -class staticmethod(Generic[_R]): # Special, only valid as a decorator. - __func__: Callable[..., _R] - __isabstractmethod__: bool - def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, __obj: _T, __type: Type[_T] | None = ...) -> Callable[..., _R]: ... - if sys.version_info >= (3, 10): - __name__: str - __qualname__: str - __wrapped__: Callable[..., _R] - def __call__(self, *args: Any, **kwargs: Any) -> _R: ... +@disjoint_base +class staticmethod(Generic[_P, _R_co]): + __name__: str + __qualname__: str + @property + def __func__(self) -> Callable[_P, _R_co]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __init__(self, f: Callable[_P, _R_co], /) -> None: ... -class classmethod(Generic[_R]): # Special, only valid as a decorator. - __func__: Callable[..., _R] - __isabstractmethod__: bool - def __init__(self: classmethod[_R], __f: Callable[..., _R]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, __obj: _T, __type: Type[_T] | None = ...) -> Callable[..., _R]: ... - if sys.version_info >= (3, 10): - __name__: str - __qualname__: str - __wrapped__: Callable[..., _R] + @overload + def __get__(self, instance: None, owner: type, /) -> Callable[_P, _R_co]: ... + @overload + def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... -class type(object): - __base__: type - __bases__: Tuple[type, ...] - __basicsize__: int - __dict__: dict[str, Any] - __dictoffset__: int - __flags__: int - __itemsize__: int + @property + def __wrapped__(self) -> Callable[_P, _R_co]: ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ... + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + __annotate__: AnnotateFunc | None + +@disjoint_base +class classmethod(Generic[_T, _P, _R_co]): + __name__: str + __qualname__: str + @property + def __func__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __init__(self, f: Callable[Concatenate[type[_T], _P], _R_co], /) -> None: ... + + @overload + def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... + @overload + def __get__(self, instance: None, owner: type[_T], /) -> Callable[_P, _R_co]: ... + + @property + def __wrapped__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + __annotate__: AnnotateFunc | None + +@disjoint_base +class type: + # object.__base__ is None. Otherwise, it would be a type. + @property + def __base__(self) -> type | None: ... + __bases__: tuple[type, ...] + @property + def __basicsize__(self) -> int: ... + # type.__dict__ is read-only at runtime, but that can't be expressed currently. + # See https://github.com/python/typeshed/issues/11033 for a discussion. + __dict__: Final[types.MappingProxyType[str, Any]] # type: ignore[assignment] + @property + def __dictoffset__(self) -> int: ... + @property + def __flags__(self) -> int: ... + @property + def __itemsize__(self) -> int: ... __module__: str - __mro__: Tuple[type, ...] + __mro__: Final[tuple[type, ...]] __name__: str __qualname__: str - __text_signature__: str | None - __weakrefoffset__: int + @property + def __text_signature__(self) -> str | None: ... + @property + def __weakrefoffset__(self) -> int: ... + @overload - def __init__(self, __o: object) -> None: ... + def __init__(self, o: object, /) -> None: ... @overload - def __init__(self, __name: str, __bases: Tuple[type, ...], __dict: dict[str, Any], **kwds: Any) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + @overload - def __new__(cls, __o: object) -> type: ... + def __new__(cls, o: object, /) -> type: ... @overload - def __new__(cls: Type[_TT], __name: str, __bases: Tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> _TT: ... + def __new__( + cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any + ) -> _typeshed.Self: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> list[_TT]: ... + def __subclasses__(self: type[_T]) -> list[type[_T]]: ... # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> list[type]: ... - def __instancecheck__(self, __instance: Any) -> bool: ... - def __subclasscheck__(self, __subclass: type) -> bool: ... + def __instancecheck__(self, instance: Any, /) -> bool: ... + def __subclasscheck__(self, subclass: type, /) -> bool: ... @classmethod - def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, object]: ... - if sys.version_info >= (3, 10): - def __or__(self, __t: Any) -> types.UnionType: ... - def __ror__(self, __t: Any) -> types.UnionType: ... + def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ... + # `int | str` produces an instance of `UnionType`, but `int | int` produces an instance of `type`, + # and `abc.ABC | abc.ABC` produces an instance of `abc.ABCMeta`. + def __or__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... + def __ror__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... + if sys.version_info >= (3, 12): + __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None -class super(object): +@disjoint_base +class super: @overload - def __init__(self, __t: Any, __obj: Any) -> None: ... + def __init__(self, t: Any, obj: Any, /) -> None: ... @overload - def __init__(self, __t: Any) -> None: ... + def __init__(self, t: Any, /) -> None: ... @overload def __init__(self) -> None: ... -_PositiveInteger = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] -_NegativeInteger = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] +_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] +_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed +@disjoint_base class int: @overload - def __new__(cls: Type[_T], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> _T: ... + def __new__(cls, x: ConvertibleToInt = 0, /) -> Self: ... @overload - def __new__(cls: Type[_T], __x: str | bytes | bytearray, base: SupportsIndex) -> _T: ... - if sys.version_info >= (3, 8): - def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... + def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ... + + def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property def real(self) -> int: ... @property - def imag(self) -> int: ... + def imag(self) -> Literal[0]: ... @property def numerator(self) -> int: ... @property - def denominator(self) -> int: ... + def denominator(self) -> Literal[1]: ... def conjugate(self) -> int: ... def bit_length(self) -> int: ... - if sys.version_info >= (3, 10): - def bit_count(self) -> int: ... - def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = ...) -> bytes: ... - @classmethod - def from_bytes( - cls, bytes: Iterable[SupportsIndex] | SupportsBytes, byteorder: Literal["little", "big"], *, signed: bool = ... - ) -> int: ... # TODO buffer object argument - def __add__(self, __x: int) -> int: ... - def __sub__(self, __x: int) -> int: ... - def __mul__(self, __x: int) -> int: ... - def __floordiv__(self, __x: int) -> int: ... - def __truediv__(self, __x: int) -> float: ... - def __mod__(self, __x: int) -> int: ... - def __divmod__(self, __x: int) -> tuple[int, int]: ... - def __radd__(self, __x: int) -> int: ... - def __rsub__(self, __x: int) -> int: ... - def __rmul__(self, __x: int) -> int: ... - def __rfloordiv__(self, __x: int) -> int: ... - def __rtruediv__(self, __x: int) -> float: ... - def __rmod__(self, __x: int) -> int: ... - def __rdivmod__(self, __x: int) -> tuple[int, int]: ... - @overload - def __pow__(self, __x: int, __modulo: Literal[0]) -> NoReturn: ... - @overload - def __pow__(self, __x: int, __modulo: int) -> int: ... - @overload - def __pow__(self, __x: _PositiveInteger, __modulo: None = ...) -> int: ... - @overload - def __pow__(self, __x: _NegativeInteger, __modulo: None = ...) -> float: ... - # positive x -> int; negative x -> float + def bit_count(self) -> int: ... + + if sys.version_info >= (3, 11): + def to_bytes( + self, length: SupportsIndex = 1, byteorder: Literal["little", "big"] = "big", *, signed: bool = False + ) -> bytes: ... + @classmethod + def from_bytes( + cls, + bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer, + byteorder: Literal["little", "big"] = "big", + *, + signed: bool = False, + ) -> Self: ... + + else: + def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = False) -> bytes: ... + @classmethod + def from_bytes( + cls, + bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer, + byteorder: Literal["little", "big"], + *, + signed: bool = False, + ) -> Self: ... + + if sys.version_info >= (3, 12): + def is_integer(self) -> Literal[True]: ... + + def __add__(self, value: int, /) -> int: ... + def __sub__(self, value: int, /) -> int: ... + def __mul__(self, value: int, /) -> int: ... + def __floordiv__(self, value: int, /) -> int: ... + def __truediv__(self, value: int, /) -> float: ... + def __mod__(self, value: int, /) -> int: ... + def __divmod__(self, value: int, /) -> tuple[int, int]: ... + def __radd__(self, value: int, /) -> int: ... + def __rsub__(self, value: int, /) -> int: ... + def __rmul__(self, value: int, /) -> int: ... + def __rfloordiv__(self, value: int, /) -> int: ... + def __rtruediv__(self, value: int, /) -> float: ... + def __rmod__(self, value: int, /) -> int: ... + def __rdivmod__(self, value: int, /) -> tuple[int, int]: ... + + @overload + def __pow__(self, x: Literal[0], /) -> Literal[1]: ... + @overload + def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ... + @overload + def __pow__(self, value: _PositiveInteger, mod: None = None, /) -> int: ... + @overload + def __pow__(self, value: _NegativeInteger, mod: None = None, /) -> float: ... + # positive __value -> int; negative __value -> float # return type must be Any as `int | float` causes too many false-positive errors @overload - def __pow__(self, __x: int, __modulo: None = ...) -> Any: ... - def __rpow__(self, __x: int, __mod: int | None = ...) -> Any: ... - def __and__(self, __n: int) -> int: ... - def __or__(self, __n: int) -> int: ... - def __xor__(self, __n: int) -> int: ... - def __lshift__(self, __n: int) -> int: ... - def __rshift__(self, __n: int) -> int: ... - def __rand__(self, __n: int) -> int: ... - def __ror__(self, __n: int) -> int: ... - def __rxor__(self, __n: int) -> int: ... - def __rlshift__(self, __n: int) -> int: ... - def __rrshift__(self, __n: int) -> int: ... + def __pow__(self, value: int, mod: None = None, /) -> Any: ... + @overload + def __pow__(self, value: int, mod: int, /) -> int: ... + + def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ... + def __and__(self, value: int, /) -> int: ... + def __or__(self, value: int, /) -> int: ... + def __xor__(self, value: int, /) -> int: ... + def __lshift__(self, value: int, /) -> int: ... + def __rshift__(self, value: int, /) -> int: ... + def __rand__(self, value: int, /) -> int: ... + def __ror__(self, value: int, /) -> int: ... + def __rxor__(self, value: int, /) -> int: ... + def __rlshift__(self, value: int, /) -> int: ... + def __rrshift__(self, value: int, /) -> int: ... def __neg__(self) -> int: ... def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... def __ceil__(self) -> int: ... def __floor__(self) -> int: ... - def __round__(self, __ndigits: SupportsIndex = ...) -> int: ... + if sys.version_info >= (3, 14): + def __round__(self, ndigits: SupportsIndex | None = None, /) -> int: ... + + else: + def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ... + def __getnewargs__(self) -> tuple[int]: ... - def __eq__(self, __x: object) -> bool: ... - def __ne__(self, __x: object) -> bool: ... - def __lt__(self, __x: int) -> bool: ... - def __le__(self, __x: int) -> bool: ... - def __gt__(self, __x: int) -> bool: ... - def __ge__(self, __x: int) -> bool: ... - def __str__(self) -> str: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: int, /) -> bool: ... + def __le__(self, value: int, /) -> bool: ... + def __gt__(self, value: int, /) -> bool: ... + def __ge__(self, value: int, /) -> bool: ... def __float__(self) -> float: ... def __int__(self) -> int: ... def __abs__(self) -> int: ... def __hash__(self) -> int: ... def __bool__(self) -> bool: ... def __index__(self) -> int: ... + def __format__(self, format_spec: str, /) -> str: ... +@disjoint_base class float: - def __new__(cls: Type[_T], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> _T: ... + def __new__(cls, x: ConvertibleToFloat = 0, /) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod - def fromhex(cls, __s: str) -> float: ... + def fromhex(cls, string: str, /) -> Self: ... @property def real(self) -> float: ... @property def imag(self) -> float: ... def conjugate(self) -> float: ... - def __add__(self, __x: float) -> float: ... - def __sub__(self, __x: float) -> float: ... - def __mul__(self, __x: float) -> float: ... - def __floordiv__(self, __x: float) -> float: ... - def __truediv__(self, __x: float) -> float: ... - def __mod__(self, __x: float) -> float: ... - def __divmod__(self, __x: float) -> tuple[float, float]: ... - @overload - def __pow__(self, __x: int, __mod: None = ...) -> float: ... - # positive x -> float; negative x -> complex + def __add__(self, value: float, /) -> float: ... + def __sub__(self, value: float, /) -> float: ... + def __mul__(self, value: float, /) -> float: ... + def __floordiv__(self, value: float, /) -> float: ... + def __truediv__(self, value: float, /) -> float: ... + def __mod__(self, value: float, /) -> float: ... + def __divmod__(self, value: float, /) -> tuple[float, float]: ... + + @overload + def __pow__(self, value: int, mod: None = None, /) -> float: ... + # positive __value -> float; negative __value -> complex # return type must be Any as `float | complex` causes too many false-positive errors @overload - def __pow__(self, __x: float, __mod: None = ...) -> Any: ... - def __radd__(self, __x: float) -> float: ... - def __rsub__(self, __x: float) -> float: ... - def __rmul__(self, __x: float) -> float: ... - def __rfloordiv__(self, __x: float) -> float: ... - def __rtruediv__(self, __x: float) -> float: ... - def __rmod__(self, __x: float) -> float: ... - def __rdivmod__(self, __x: float) -> tuple[float, float]: ... - def __rpow__(self, __x: float, __mod: None = ...) -> float: ... + def __pow__(self, value: float, mod: None = None, /) -> Any: ... + + def __radd__(self, value: float, /) -> float: ... + def __rsub__(self, value: float, /) -> float: ... + def __rmul__(self, value: float, /) -> float: ... + def __rfloordiv__(self, value: float, /) -> float: ... + def __rtruediv__(self, value: float, /) -> float: ... + def __rmod__(self, value: float, /) -> float: ... + def __rdivmod__(self, value: float, /) -> tuple[float, float]: ... + + @overload + def __rpow__(self, value: _PositiveInteger, mod: None = None, /) -> float: ... + @overload + def __rpow__(self, value: _NegativeInteger, mod: None = None, /) -> complex: ... + # Returning `complex` for the general case gives too many false-positive errors. + @overload + def __rpow__(self, value: float, mod: None = None, /) -> Any: ... + def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... - if sys.version_info >= (3, 9): - def __ceil__(self) -> int: ... - def __floor__(self) -> int: ... - @overload - def __round__(self, __ndigits: None = ...) -> int: ... - @overload - def __round__(self, __ndigits: SupportsIndex) -> float: ... - def __eq__(self, __x: object) -> bool: ... - def __ne__(self, __x: object) -> bool: ... - def __lt__(self, __x: float) -> bool: ... - def __le__(self, __x: float) -> bool: ... - def __gt__(self, __x: float) -> bool: ... - def __ge__(self, __x: float) -> bool: ... + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + + @overload + def __round__(self, ndigits: None = None, /) -> int: ... + @overload + def __round__(self, ndigits: SupportsIndex, /) -> float: ... + + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: float, /) -> bool: ... + def __le__(self, value: float, /) -> bool: ... + def __gt__(self, value: float, /) -> bool: ... + def __ge__(self, value: float, /) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... - def __str__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... def __bool__(self) -> bool: ... + def __format__(self, format_spec: str, /) -> str: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self: ... +@disjoint_base class complex: + # Python doesn't currently accept SupportsComplex for the second argument @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__( + cls, + real: complex | SupportsComplex | SupportsFloat | SupportsIndex = 0, + imag: complex | SupportsFloat | SupportsIndex = 0, + ) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | SupportsIndex | complex) -> _T: ... + def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... + @property def real(self) -> float: ... @property def imag(self) -> float: ... def conjugate(self) -> complex: ... - def __add__(self, __x: complex) -> complex: ... - def __sub__(self, __x: complex) -> complex: ... - def __mul__(self, __x: complex) -> complex: ... - def __pow__(self, __x: complex, mod: None = ...) -> complex: ... - def __truediv__(self, __x: complex) -> complex: ... - def __radd__(self, __x: complex) -> complex: ... - def __rsub__(self, __x: complex) -> complex: ... - def __rmul__(self, __x: complex) -> complex: ... - def __rpow__(self, __x: complex, __mod: None = ...) -> complex: ... - def __rtruediv__(self, __x: complex) -> complex: ... - def __eq__(self, __x: object) -> bool: ... - def __ne__(self, __x: object) -> bool: ... + def __add__(self, value: complex, /) -> complex: ... + def __sub__(self, value: complex, /) -> complex: ... + def __mul__(self, value: complex, /) -> complex: ... + def __pow__(self, value: complex, mod: None = None, /) -> complex: ... + def __truediv__(self, value: complex, /) -> complex: ... + def __radd__(self, value: complex, /) -> complex: ... + def __rsub__(self, value: complex, /) -> complex: ... + def __rmul__(self, value: complex, /) -> complex: ... + def __rpow__(self, value: complex, mod: None = None, /) -> complex: ... + def __rtruediv__(self, value: complex, /) -> complex: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... - def __str__(self) -> str: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... def __bool__(self) -> bool: ... + def __format__(self, format_spec: str, /) -> str: ... if sys.version_info >= (3, 11): def __complex__(self) -> complex: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: complex | SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self: ... +@type_check_only class _FormatMapMapping(Protocol): - def __getitem__(self, __key: str) -> Any: ... + def __getitem__(self, key: str, /) -> Any: ... + +@type_check_only +class _TranslateTable(Protocol): + def __getitem__(self, key: int, /) -> str | int | None: ... +@disjoint_base class str(Sequence[str]): @overload - def __new__(cls: Type[_T], object: object = ...) -> _T: ... + def __new__(cls, object: object = "") -> Self: ... + @overload + def __new__(cls, object: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> Self: ... + + @overload + def capitalize(self: LiteralString) -> LiteralString: ... + @overload + def capitalize(self) -> str: ... # type: ignore[misc] + + @overload + def casefold(self: LiteralString) -> LiteralString: ... @overload - def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... - def capitalize(self) -> str: ... - def casefold(self) -> str: ... - def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... - def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... + def casefold(self) -> str: ... # type: ignore[misc] + + @overload + def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + + def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( - self, __suffix: str | Tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... - if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... - else: - def expandtabs(self, tabsize: int = ...) -> str: ... - def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + + @overload + def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... + @overload + def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] + + def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + + @overload + def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload def format(self, *args: object, **kwargs: object) -> str: ... - def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + + def format_map(self, mapping: _FormatMapMapping, /) -> str: ... + def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... + def isascii(self) -> bool: ... def isdecimal(self) -> bool: ... def isdigit(self) -> bool: ... def isidentifier(self) -> bool: ... @@ -393,1143 +539,1864 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[str]) -> str: ... - def ljust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... - def lower(self) -> str: ... - def lstrip(self, __chars: str | None = ...) -> str: ... - def partition(self, __sep: str) -> tuple[str, str, str]: ... - def replace(self, __old: str, __new: str, __count: SupportsIndex = ...) -> str: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: str) -> str: ... - def removesuffix(self, __suffix: str) -> str: ... - def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... - def rpartition(self, __sep: str) -> tuple[str, str, str]: ... - def rsplit(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... - def rstrip(self, __chars: str | None = ...) -> str: ... - def split(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... - def splitlines(self, keepends: bool = ...) -> list[str]: ... + + @overload + def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... + @overload + def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] + + @overload + def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + + @overload + def lower(self: LiteralString) -> LiteralString: ... + @overload + def lower(self) -> str: ... # type: ignore[misc] + + @overload + def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + + @overload + def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + + if sys.version_info >= (3, 13): + @overload + def replace( + self: LiteralString, old: LiteralString, new: LiteralString, /, count: SupportsIndex = -1 + ) -> LiteralString: ... + @overload + def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ... # type: ignore[misc] + else: + @overload + def replace( + self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, / + ) -> LiteralString: ... + @overload + def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] + + @overload + def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... + @overload + def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] + + @overload + def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... + @overload + def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] + + def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + + @overload + def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + + @overload + def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + + @overload + def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload + def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + + @overload + def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + + @overload + def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload + def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + + @overload + def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... + @overload + def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] + def startswith( - self, __prefix: str | Tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... - def strip(self, __chars: str | None = ...) -> str: ... - def swapcase(self) -> str: ... - def title(self) -> str: ... - def translate(self, __table: Mapping[int, int | str | None] | Sequence[int | str | None]) -> str: ... - def upper(self) -> str: ... - def zfill(self, __width: SupportsIndex) -> str: ... + + @overload + def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + + @overload + def swapcase(self: LiteralString) -> LiteralString: ... + @overload + def swapcase(self) -> str: ... # type: ignore[misc] + + @overload + def title(self: LiteralString) -> LiteralString: ... + @overload + def title(self) -> str: ... # type: ignore[misc] + + def translate(self, table: _TranslateTable, /) -> str: ... + + @overload + def upper(self: LiteralString) -> LiteralString: ... + @overload + def upper(self) -> str: ... # type: ignore[misc] + + @overload + def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... + @overload + def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] + + if sys.version_info >= (3, 15): + @staticmethod + @overload + def maketrans( + x: ( + dict[int, _T] + | dict[str, _T] + | dict[str | int, _T] + | frozendict[int, _T] + | frozendict[str, _T] + | frozendict[str | int, _T] + ), + /, + ) -> dict[int, _T]: ... + else: + @staticmethod + @overload + def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: ... + @staticmethod @overload - def maketrans(__x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... + def maketrans(x: str, y: str, /) -> dict[int, int]: ... @staticmethod @overload - def maketrans(__x: str, __y: str, __z: str | None = ...) -> dict[int, int | None]: ... - def __add__(self, __s: str) -> str: ... + def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... + + @overload + def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... + @overload + def __add__(self, value: str, /) -> str: ... # type: ignore[misc] + # Incompatible with Sequence.__contains__ - def __contains__(self, __o: str) -> bool: ... # type: ignore[override] - def __eq__(self, __x: object) -> bool: ... - def __ge__(self, __x: str) -> bool: ... - def __getitem__(self, __i: SupportsIndex | slice) -> str: ... - def __gt__(self, __x: str) -> bool: ... + def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: str, /) -> bool: ... + + @overload + def __getitem__(self: LiteralString, key: SupportsIndex | slice[SupportsIndex | None], /) -> LiteralString: ... + @overload + def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ... # type: ignore[misc] + + def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... - def __le__(self, __x: str) -> bool: ... + + @overload + def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... + @overload + def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] + + def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: ... - def __lt__(self, __x: str) -> bool: ... - def __mod__(self, __x: Any) -> str: ... - def __mul__(self, __n: SupportsIndex) -> str: ... - def __ne__(self, __x: object) -> bool: ... - def __repr__(self) -> str: ... - def __rmul__(self, n: SupportsIndex) -> str: ... - def __str__(self) -> str: ... - def __getnewargs__(self) -> tuple[str]: ... + def __lt__(self, value: str, /) -> bool: ... + + @overload + def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... + @overload + def __mod__(self, value: object, /) -> str: ... + + def __rmod__(self, value: str, /) -> str: ... + + @overload + def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload + def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + + def __ne__(self, value: object, /) -> bool: ... -class bytes(ByteString): @overload - def __new__(cls: Type[_T], __ints: Iterable[SupportsIndex]) -> _T: ... + def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... @overload - def __new__(cls: Type[_T], __string: str, encoding: str, errors: str = ...) -> _T: ... + def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + + def __getnewargs__(self) -> tuple[str]: ... + def __format__(self, format_spec: str, /) -> str: ... + +@disjoint_base +class bytes(Sequence[int]): @overload - def __new__(cls: Type[_T], __length: SupportsIndex) -> _T: ... + def __new__(cls, o: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, /) -> Self: ... @overload - def __new__(cls: Type[_T]) -> _T: ... + def __new__(cls, string: str, /, encoding: str, errors: str = "strict") -> Self: ... @overload - def __new__(cls: Type[_T], __o: SupportsBytes) -> _T: ... + def __new__(cls) -> Self: ... + def capitalize(self) -> bytes: ... - def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... + def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytes: ... def count( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... - def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: ... def endswith( - self, __suffix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, ) -> bool: ... - if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = ...) -> bytes: ... - else: - def expandtabs(self, tabsize: int = ...) -> bytes: ... + def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ... def find( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... - if sys.version_info >= (3, 8): - def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... - else: - def hex(self) -> str: ... + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ... def index( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... + def isascii(self) -> bool: ... def isdigit(self) -> bool: ... def islower(self) -> bool: ... def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[ByteString | memoryview]) -> bytes: ... - def ljust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... + def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytes: ... + def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: ... def lower(self) -> bytes: ... - def lstrip(self, __bytes: bytes | None = ...) -> bytes: ... - def partition(self, __sep: bytes) -> tuple[bytes, bytes, bytes]: ... - def replace(self, __old: bytes, __new: bytes, __count: SupportsIndex = ...) -> bytes: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytes: ... - def removesuffix(self, __suffix: bytes) -> bytes: ... + def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... + def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... + if sys.version_info >= (3, 15): + def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytes: ... + + else: + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ... + + def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ... def rfind( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... def rindex( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... - def rpartition(self, __sep: bytes) -> tuple[bytes, bytes, bytes]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... - def rstrip(self, __bytes: bytes | None = ...) -> bytes: ... - def split(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... - def splitlines(self, keepends: bool = ...) -> list[bytes]: ... + def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: ... + def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ... + def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... + def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ... + def splitlines(self, keepends: bool = False) -> list[bytes]: ... def startswith( - self, __prefix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, ) -> bool: ... - def strip(self, __bytes: bytes | None = ...) -> bytes: ... + def strip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... def swapcase(self) -> bytes: ... def title(self) -> bytes: ... - def translate(self, __table: bytes | None, delete: bytes = ...) -> bytes: ... + def translate(self, table: ReadableBuffer | None, /, delete: ReadableBuffer = b"") -> bytes: ... def upper(self) -> bytes: ... - def zfill(self, __width: SupportsIndex) -> bytes: ... - @classmethod - def fromhex(cls: Type[_T], __s: str) -> _T: ... + def zfill(self, width: SupportsIndex, /) -> bytes: ... + + if sys.version_info >= (3, 14): + @classmethod + def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ... + else: + @classmethod + def fromhex(cls, string: str, /) -> Self: ... + @staticmethod - def maketrans(__frm: bytes, __to: bytes) -> bytes: ... + def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __hash__(self) -> int: ... + @overload - def __getitem__(self, __i: SupportsIndex) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, __s: slice) -> bytes: ... - def __add__(self, __s: bytes) -> bytes: ... - def __mul__(self, __n: SupportsIndex) -> bytes: ... - def __rmul__(self, __n: SupportsIndex) -> bytes: ... - def __mod__(self, __value: Any) -> bytes: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... + + def __add__(self, value: ReadableBuffer, /) -> bytes: ... + def __mul__(self, value: SupportsIndex, /) -> bytes: ... + def __rmul__(self, value: SupportsIndex, /) -> bytes: ... + # The format string chooses the conversion, including numbers and %a/%r (PEP 461). + def __mod__(self, value: Any, /) -> bytes: ... + def __rmod__(self, value: bytes, /) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, __o: SupportsIndex | bytes) -> bool: ... # type: ignore[override] - def __eq__(self, __x: object) -> bool: ... - def __ne__(self, __x: object) -> bool: ... - def __lt__(self, __x: bytes) -> bool: ... - def __le__(self, __x: bytes) -> bool: ... - def __gt__(self, __x: bytes) -> bool: ... - def __ge__(self, __x: bytes) -> bool: ... + def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: bytes, /) -> bool: ... + def __le__(self, value: bytes, /) -> bool: ... + def __gt__(self, value: bytes, /) -> bool: ... + def __ge__(self, value: bytes, /) -> bool: ... def __getnewargs__(self) -> tuple[bytes]: ... if sys.version_info >= (3, 11): def __bytes__(self) -> bytes: ... -class bytearray(MutableSequence[int], ByteString): + def __buffer__(self, flags: int, /) -> memoryview: ... + +@disjoint_base +class bytearray(MutableSequence[int]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __ints: Iterable[SupportsIndex]) -> None: ... + def __init__(self, ints: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer, /) -> None: ... @overload - def __init__(self, __string: str, encoding: str, errors: str = ...) -> None: ... - @overload - def __init__(self, __length: SupportsIndex) -> None: ... - def append(self, __item: SupportsIndex) -> None: ... + def __init__(self, string: str, /, encoding: str, errors: str = "strict") -> None: ... + + def append(self, item: SupportsIndex, /) -> None: ... def capitalize(self) -> bytearray: ... - def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... + def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytearray: ... def count( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... def copy(self) -> bytearray: ... - def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: ... def endswith( - self, __suffix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, ) -> bool: ... - if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = ...) -> bytearray: ... - else: - def expandtabs(self, tabsize: int = ...) -> bytearray: ... - def extend(self, __iterable_of_ints: Iterable[SupportsIndex]) -> None: ... + def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ... + def extend(self, iterable_of_ints: Iterable[SupportsIndex], /) -> None: ... def find( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... - if sys.version_info >= (3, 8): - def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... - else: - def hex(self) -> str: ... + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ... def index( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... - def insert(self, __index: SupportsIndex, __item: SupportsIndex) -> None: ... + def insert(self, index: SupportsIndex, item: SupportsIndex, /) -> None: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... + def isascii(self) -> bool: ... def isdigit(self) -> bool: ... def islower(self) -> bool: ... def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[ByteString | memoryview]) -> bytearray: ... - def ljust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... + def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytearray: ... + def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: ... def lower(self) -> bytearray: ... - def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytearray: ... - def removesuffix(self, __suffix: bytes) -> bytearray: ... - def replace(self, __old: bytes, __new: bytes, __count: SupportsIndex = ...) -> bytearray: ... + def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... + def partition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... + def pop(self, index: int = -1, /) -> int: ... + def remove(self, value: int, /) -> None: ... + def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... + if sys.version_info >= (3, 15): + def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytearray: ... + + else: + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... + def rfind( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... def rindex( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... - def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... + def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: ... + def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ... + def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... + def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ... + def splitlines(self, keepends: bool = False) -> list[bytearray]: ... def startswith( - self, __prefix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, ) -> bool: ... - def strip(self, __bytes: bytes | None = ...) -> bytearray: ... + def strip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... - def translate(self, __table: bytes | None, delete: bytes = ...) -> bytearray: ... + def translate(self, table: ReadableBuffer | None, /, delete: bytes = b"") -> bytearray: ... + if sys.version_info >= (3, 15): + def take_bytes(self, n: int | None = None, /) -> bytes: ... + def upper(self) -> bytearray: ... - def zfill(self, __width: SupportsIndex) -> bytearray: ... - @classmethod - def fromhex(cls, __string: str) -> bytearray: ... + def zfill(self, width: SupportsIndex, /) -> bytearray: ... + + if sys.version_info >= (3, 14): + @classmethod + def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ... + else: + @classmethod + def fromhex(cls, string: str, /) -> Self: ... + @staticmethod - def maketrans(__frm: bytes, __to: bytes) -> bytes: ... + def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] + @overload - def __getitem__(self, __i: SupportsIndex) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, __s: slice) -> bytearray: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytearray: ... + @overload - def __setitem__(self, __i: SupportsIndex, x: SupportsIndex) -> None: ... + def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: ... @overload - def __setitem__(self, __s: slice, __x: Iterable[SupportsIndex] | bytes) -> None: ... - def __delitem__(self, __i: SupportsIndex | slice) -> None: ... - def __add__(self, __s: bytes) -> bytearray: ... - def __iadd__(self, __s: Iterable[int]) -> bytearray: ... - def __mul__(self, __n: SupportsIndex) -> bytearray: ... - def __rmul__(self, __n: SupportsIndex) -> bytearray: ... - def __imul__(self, __n: SupportsIndex) -> bytearray: ... - def __mod__(self, __value: Any) -> bytes: ... + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[SupportsIndex] | bytes, /) -> None: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + def __add__(self, value: ReadableBuffer, /) -> bytearray: ... + # The superclass wants us to accept Iterable[int], but that fails at runtime. + def __iadd__(self, value: ReadableBuffer, /) -> Self: ... # type: ignore[override] + def __mul__(self, value: SupportsIndex, /) -> bytearray: ... + def __rmul__(self, value: SupportsIndex, /) -> bytearray: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + # The format string chooses the conversion, including numbers and %a/%r (PEP 461). + def __mod__(self, value: Any, /) -> bytearray: ... + def __rmod__(self, value: bytearray, /) -> bytearray: ... # Incompatible with Sequence.__contains__ - def __contains__(self, __o: SupportsIndex | bytes) -> bool: ... # type: ignore[override] - def __eq__(self, __x: object) -> bool: ... - def __ne__(self, __x: object) -> bool: ... - def __lt__(self, __x: bytes) -> bool: ... - def __le__(self, __x: bytes) -> bool: ... - def __gt__(self, __x: bytes) -> bool: ... - def __ge__(self, __x: bytes) -> bool: ... + def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: ReadableBuffer, /) -> bool: ... + def __le__(self, value: ReadableBuffer, /) -> bool: ... + def __gt__(self, value: ReadableBuffer, /) -> bool: ... + def __ge__(self, value: ReadableBuffer, /) -> bool: ... + def __alloc__(self) -> int: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 14): + def resize(self, size: int, /) -> None: ... + +_IntegerFormats: TypeAlias = Literal[ + "b", "B", "@b", "@B", "h", "H", "@h", "@H", "i", "I", "@i", "@I", "l", "L", "@l", "@L", "q", "Q", "@q", "@Q", "P", "@P" +] @final -class memoryview(Sized, Sequence[int]): - format: str - itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None - readonly: bool - ndim: int - - obj: bytes | bytearray - c_contiguous: bool - f_contiguous: bool - contiguous: bool - nbytes: int - def __init__(self, obj: ReadableBuffer) -> None: ... - def __enter__(self: Self) -> Self: ... +class memoryview(Sequence[_I]): + @property + def format(self) -> str: ... + @property + def itemsize(self) -> int: ... + @property + def shape(self) -> tuple[int, ...] | None: ... + @property + def strides(self) -> tuple[int, ...] | None: ... + @property + def suboffsets(self) -> tuple[int, ...] | None: ... + @property + def readonly(self) -> bool: ... + @property + def ndim(self) -> int: ... + @property + def obj(self) -> ReadableBuffer: ... + @property + def c_contiguous(self) -> bool: ... + @property + def f_contiguous(self) -> bool: ... + @property + def contiguous(self) -> bool: ... + @property + def nbytes(self) -> int: ... + def __new__(cls, obj: ReadableBuffer) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + self, + exc_type: type[BaseException] | None, # ruff: ignore[bad-exit-annotation] # This is the module declaring BaseException + exc_val: BaseException | None, + exc_tb: TracebackType | None, + /, ) -> None: ... - def cast(self, format: str, shape: list[int] | Tuple[int, ...] = ...) -> memoryview: ... + @overload - def __getitem__(self, __i: SupportsIndex) -> int: ... + def cast(self, format: Literal["c", "@c"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bytes]: ... @overload - def __getitem__(self, __s: slice) -> memoryview: ... - def __contains__(self, __x: object) -> bool: ... - def __iter__(self) -> Iterator[int]: ... + def cast(self, format: Literal["f", "@f", "d", "@d"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[float]: ... + @overload + def cast(self, format: Literal["?"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bool]: ... + @overload + def cast(self, format: _IntegerFormats, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... + + @overload + def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> _I: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> memoryview[_I]: ... + + def __contains__(self, x: object, /) -> bool: ... + def __iter__(self) -> Iterator[_I]: ... def __len__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + @overload - def __setitem__(self, __s: slice, __o: bytes) -> None: ... + def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ... @overload - def __setitem__(self, __i: SupportsIndex, __o: SupportsIndex) -> None: ... - if sys.version_info >= (3, 8): - def tobytes(self, order: Literal["C", "F", "A"] | None = ...) -> bytes: ... - else: - def tobytes(self) -> bytes: ... + def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: _I, /) -> None: ... + + def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... def tolist(self) -> list[int]: ... - if sys.version_info >= (3, 8): - def toreadonly(self) -> memoryview: ... + def toreadonly(self) -> memoryview[_I]: ... def release(self) -> None: ... - if sys.version_info >= (3, 8): - def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 14): + def index(self, value: object, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def count(self, value: object, /) -> int: ... + else: - def hex(self) -> str: ... + # These are inherited from the Sequence ABC, but don't actually exist on memoryview. + # See https://github.com/python/cpython/issues/125420 + index: ClassVar[None] # type: ignore[assignment] + count: ClassVar[None] # type: ignore[assignment] + + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls, o: object = False, /) -> Self: ... + + # The following overloads could be represented more elegantly with a TypeVar("_B", bool, int), + # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880). @overload - def __and__(self, __x: bool) -> bool: ... + def __and__(self, value: bool, /) -> bool: ... @overload - def __and__(self, __x: int) -> int: ... + def __and__(self, value: int, /) -> int: ... + @overload - def __or__(self, __x: bool) -> bool: ... + def __or__(self, value: bool, /) -> bool: ... @overload - def __or__(self, __x: int) -> int: ... + def __or__(self, value: int, /) -> int: ... + @overload - def __xor__(self, __x: bool) -> bool: ... + def __xor__(self, value: bool, /) -> bool: ... @overload - def __xor__(self, __x: int) -> int: ... + def __xor__(self, value: int, /) -> int: ... + @overload - def __rand__(self, __x: bool) -> bool: ... + def __rand__(self, value: bool, /) -> bool: ... @overload - def __rand__(self, __x: int) -> int: ... + def __rand__(self, value: int, /) -> int: ... + @overload - def __ror__(self, __x: bool) -> bool: ... + def __ror__(self, value: bool, /) -> bool: ... @overload - def __ror__(self, __x: int) -> int: ... + def __ror__(self, value: int, /) -> int: ... + @overload - def __rxor__(self, __x: bool) -> bool: ... + def __rxor__(self, value: bool, /) -> bool: ... @overload - def __rxor__(self, __x: int) -> int: ... + def __rxor__(self, value: int, /) -> int: ... + def __getnewargs__(self) -> tuple[int]: ... + @deprecated("Will throw an error in Python 3.16. Use `not` for logical negation of bools instead.") + def __invert__(self) -> int: ... @final -class slice(object): - start: Any - step: Any - stop: Any +class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): + @property + def start(self) -> _StartT_co: ... + @property + def step(self) -> _StepT_co: ... + @property + def stop(self) -> _StopT_co: ... + + # Note: __new__ overloads map `None` to `Any`, since users expect slice(x, None) + # to be compatible with slice(None, x). + # generic slice -------------------------------------------------------------------- + @overload + def __new__(cls, start: None, stop: None = None, step: None = None, /) -> slice[Any, Any, Any]: ... + # unary overloads ------------------------------------------------------------------ + @overload + def __new__(cls, stop: _T2, /) -> slice[Any, _T2, Any]: ... + # binary overloads ----------------------------------------------------------------- + @overload + def __new__(cls, start: _T1, stop: None, step: None = None, /) -> slice[_T1, Any, Any]: ... @overload - def __init__(self, __stop: Any) -> None: ... + def __new__(cls, start: None, stop: _T2, step: None = None, /) -> slice[Any, _T2, Any]: ... @overload - def __init__(self, __start: Any, __stop: Any, __step: Any = ...) -> None: ... - __hash__: None # type: ignore[assignment] - def indices(self, __len: SupportsIndex) -> tuple[int, int, int]: ... + def __new__(cls, start: _T1, stop: _T2, step: None = None, /) -> slice[_T1, _T2, Any]: ... + # ternary overloads ---------------------------------------------------------------- + @overload + def __new__(cls, start: None, stop: None, step: _T3, /) -> slice[Any, Any, _T3]: ... + @overload + def __new__(cls, start: _T1, stop: None, step: _T3, /) -> slice[_T1, Any, _T3]: ... + @overload + def __new__(cls, start: None, stop: _T2, step: _T3, /) -> slice[Any, _T2, _T3]: ... + @overload + def __new__(cls, start: _T1, stop: _T2, step: _T3, /) -> slice[_T1, _T2, _T3]: ... + + def __eq__(self, value: object, /) -> bool: ... + if sys.version_info >= (3, 12): + def __hash__(self) -> int: ... + + else: + __hash__: ClassVar[None] # type: ignore[assignment] -class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: Type[_T], __iterable: Iterable[_T_co] = ...) -> _T: ... + def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: ... + if sys.version_info >= (3, 15): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class tuple(Sequence[_T_co]): + def __new__(cls, iterable: Iterable[_T_co] = (), /) -> Self: ... def __len__(self) -> int: ... - def __contains__(self, __x: object) -> bool: ... + def __contains__(self, key: object, /) -> bool: ... + @overload - def __getitem__(self, __x: SupportsIndex) -> _T_co: ... + def __getitem__(self, key: SupportsIndex, /) -> _T_co: ... @overload - def __getitem__(self, __x: slice) -> Tuple[_T_co, ...]: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... - def __lt__(self, __x: Tuple[_T_co, ...]) -> bool: ... - def __le__(self, __x: Tuple[_T_co, ...]) -> bool: ... - def __gt__(self, __x: Tuple[_T_co, ...]) -> bool: ... - def __ge__(self, __x: Tuple[_T_co, ...]) -> bool: ... + def __lt__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __le__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __gt__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self: tuple[Hashable, ...]) -> int: ... + @overload - def __add__(self, __x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ... @overload - def __add__(self, __x: Tuple[_T, ...]) -> Tuple[_T_co | _T, ...]: ... - def __mul__(self, __n: SupportsIndex) -> Tuple[_T_co, ...]: ... - def __rmul__(self, __n: SupportsIndex) -> Tuple[_T_co, ...]: ... - def count(self, __value: Any) -> int: ... - def index(self, __value: Any, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __add__(self, value: tuple[_T, ...], /) -> tuple[_T_co | _T, ...]: ... + def __mul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... + def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... + def count(self, value: Any, /) -> int: ... + def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# Doesn't exist at runtime, but deleting this breaks mypy and pyright. See: +# https://github.com/python/typeshed/issues/7580 +# https://github.com/python/mypy/issues/8240 +# Obsolete, use types.FunctionType instead. +@final +@type_check_only class function: - # TODO not defined in builtins! - __name__: str - __module__: str + # Make sure this class definition stays roughly in line with `types.FunctionType` + @property + def __closure__(self) -> tuple[CellType, ...] | None: ... __code__: CodeType + __defaults__: tuple[Any, ...] | None + __dict__: dict[str, Any] + @property + def __globals__(self) -> dict[str, Any]: ... + __name__: str __qualname__: str - __annotations__: dict[str, Any] + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + __kwdefaults__: dict[str, Any] | None + @property + def __builtins__(self) -> dict[str, Any]: ... + if sys.version_info >= (3, 12): + __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] -class list(MutableSequence[_T], Generic[_T]): + __module__: str + if sys.version_info >= (3, 13): + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + kwdefaults: dict[str, object] | None = None, + ) -> Self: ... + + else: + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + ) -> Self: ... + + # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any. + def __get__(self, instance: object, owner: type | None = None, /) -> Any: ... + +@disjoint_base +class list(MutableSequence[_T]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __iterable: Iterable[_T]) -> None: ... + def __init__(self, iterable: Iterable[_T], /) -> None: ... + def copy(self) -> list[_T]: ... - def append(self, __object: _T) -> None: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: SupportsIndex = ...) -> _T: ... + def append(self, object: _T, /) -> None: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def pop(self, index: SupportsIndex = -1, /) -> _T: ... # Signature of `list.index` should be kept in line with `collections.UserList.index()` - def index(self, __value: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... - def count(self, __value: _T) -> int: ... - def insert(self, __index: SupportsIndex, __object: _T) -> None: ... - def remove(self, __value: _T) -> None: ... + # and multiprocessing.managers.ListProxy.index() + def index(self, value: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def count(self, value: _T, /) -> int: ... + def insert(self, index: SupportsIndex, object: _T, /) -> None: ... + def remove(self, value: _T, /) -> None: ... + # Signature of `list.sort` should be kept inline with `collections.UserList.sort()` + # and multiprocessing.managers.ListProxy.sort() + # + # Use list[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] + # to work around invariance @overload - def sort(self: list[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> None: ... + def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... @overload - def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... + def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] + @overload - def __getitem__(self, __i: SupportsIndex) -> _T: ... + def __getitem__(self, i: SupportsIndex, /) -> _T: ... @overload - def __getitem__(self, __s: slice) -> list[_T]: ... + def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ... + @overload - def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... @overload - def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... - def __delitem__(self, __i: SupportsIndex | slice) -> None: ... - def __add__(self, __x: list[_T]) -> list[_T]: ... - def __iadd__(self: _S, __x: Iterable[_T]) -> _S: ... - def __mul__(self, __n: SupportsIndex) -> list[_T]: ... - def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... - def __imul__(self: _S, __n: SupportsIndex) -> _S: ... - def __contains__(self, __o: object) -> bool: ... + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[_T], /) -> None: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + + # Overloading looks unnecessary, but is needed to work around complex mypy problems + @overload + def __add__(self, value: list[_T], /) -> list[_T]: ... + @overload + def __add__(self, value: list[_S], /) -> list[_S | _T]: ... + + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[misc] + def __mul__(self, value: SupportsIndex, /) -> list[_T]: ... + def __rmul__(self, value: SupportsIndex, /) -> list[_T]: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __contains__(self, key: object, /) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... - def __gt__(self, __x: list[_T]) -> bool: ... - def __ge__(self, __x: list[_T]) -> bool: ... - def __lt__(self, __x: list[_T]) -> bool: ... - def __le__(self, __x: list[_T]) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... - -class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + def __gt__(self, value: list[_T], /) -> bool: ... + def __ge__(self, value: list[_T], /) -> bool: ... + def __lt__(self, value: list[_T], /) -> bool: ... + def __le__(self, value: list[_T], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class dict(MutableMapping[_KT, _VT]): # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics + # Also multiprocessing.managers.SyncManager.dict() @overload - def __init__(self: dict[_KT, _VT]) -> None: ... + def __init__(self, /) -> None: ... @overload - def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... + def __init__(self: dict[str, _VT], /, **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 @overload - def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload - def __init__(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - # Next overload is for dict(string.split(sep) for string in iterable) + def __init__( + self: dict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + map: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def __init__( + self: dict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + # Next two overloads are for dict(string.split(sep) for string in iterable) # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload - def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def __init__(self: dict[str, str], iterable: Iterable[list[str]], /) -> None: ... + @overload + def __init__(self: dict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... + + def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: ... def keys(self) -> dict_keys[_KT, _VT]: ... def values(self) -> dict_values[_KT, _VT]: ... def items(self) -> dict_items[_KT, _VT]: ... - # Signature of `dict.fromkeys` should be kept identical to `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` - # TODO: the true signature of `dict.fromkeys` is not expressable in the current type system. + + # Signature of `dict.fromkeys` should be kept identical to + # `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` + # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> dict[_T, Any | None]: ... + def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... + + # Positional-only in dict, but not in MutableMapping + @overload # type: ignore[override] + def get(self, key: _KT, default: None = None, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + def __len__(self) -> int: ... - def __getitem__(self, __k: _KT) -> _VT: ... - def __setitem__(self, __k: _KT, v: _VT) -> None: ... - def __delitem__(self, __v: _KT) -> None: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... def __iter__(self) -> Iterator[_KT]: ... - if sys.version_info >= (3, 8): + def __eq__(self, value: object, /) -> bool: ... + def __reversed__(self) -> Iterator[_KT]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 15): + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + + else: + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + # dict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... + @overload + def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... + +if sys.version_info >= (3, 15): + @disjoint_base + class frozendict(Mapping[_KT, _VT]): + @overload + def __new__(cls, /) -> frozendict[Any, Any]: ... + @overload + def __new__(cls: type[frozendict[str, _VT]], /, **kwargs: _VT) -> frozendict[str, _VT]: ... + @overload + def __new__(cls, map: SupportsKeysAndGetItem[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload + def __new__( + cls: type[frozendict[str, _VT]], map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT + ) -> frozendict[str, _VT]: ... + @overload + def __new__(cls, iterable: Iterable[tuple[_KT, _VT]], /) -> frozendict[_KT, _VT]: ... + @overload + def __new__( + cls: type[frozendict[str, _VT]], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT + ) -> frozendict[str, _VT]: ... + + def copy(self) -> frozendict[_KT, _VT]: ... + + @overload + @classmethod + def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> frozendict[_T, Any | None]: ... + @overload + @classmethod + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> frozendict[_T, _S]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, default: None = None, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + def items(self) -> dict_items[_KT, _VT]: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... def __reversed__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore[assignment] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... - def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... - def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... - def __ior__(self, __value: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ... # type: ignore[misc] - -class set(MutableSet[_T], Generic[_T]): - def __init__(self, __iterable: Iterable[_T] = ...) -> None: ... - def add(self, __element: _T) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + +@disjoint_base +class set(MutableSet[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], /) -> None: ... + + def add(self, element: _T, /) -> None: ... def copy(self) -> set[_T]: ... - def difference(self, *s: Iterable[Any]) -> set[_T]: ... - def difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, __element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> set[_T]: ... - def intersection_update(self, *s: Iterable[Any]) -> None: ... - def isdisjoint(self, __s: Iterable[Any]) -> bool: ... - def issubset(self, __s: Iterable[Any]) -> bool: ... - def issuperset(self, __s: Iterable[Any]) -> bool: ... - def remove(self, __element: _T) -> None: ... - def symmetric_difference(self, __s: Iterable[_T]) -> set[_T]: ... - def symmetric_difference_update(self, __s: Iterable[_T]) -> None: ... + def difference(self, *s: Iterable[object]) -> set[_T]: ... + def difference_update(self, *s: Iterable[object]) -> None: ... + def discard(self, element: object, /) -> None: ... + def intersection(self, *s: Iterable[object]) -> set[_T]: ... + def intersection_update(self, *s: Iterable[object]) -> None: ... + def isdisjoint(self, s: Iterable[object], /) -> bool: ... + def issubset(self, s: Iterable[object], /) -> bool: ... + def issuperset(self, s: Iterable[object], /) -> bool: ... + def remove(self, element: _T, /) -> None: ... + def symmetric_difference(self, s: Iterable[_S], /) -> set[_T | _S]: ... + def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ... def union(self, *s: Iterable[_S]) -> set[_T | _S]: ... def update(self, *s: Iterable[_T]) -> None: ... def __len__(self) -> int: ... - def __contains__(self, __o: object) -> bool: ... + def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - def __and__(self, __s: AbstractSet[object]) -> set[_T]: ... - def __iand__(self, __s: AbstractSet[object]) -> set[_T]: ... - def __or__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... - def __ior__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... - def __sub__(self, __s: AbstractSet[_T | None]) -> set[_T]: ... - def __isub__(self, __s: AbstractSet[_T | None]) -> set[_T]: ... - def __xor__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... - def __ixor__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... - def __le__(self, __s: AbstractSet[object]) -> bool: ... - def __lt__(self, __s: AbstractSet[object]) -> bool: ... - def __ge__(self, __s: AbstractSet[object]) -> bool: ... - def __gt__(self, __s: AbstractSet[object]) -> bool: ... - __hash__: None # type: ignore[assignment] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... - -class frozenset(AbstractSet[_T_co], Generic[_T_co]): - def __init__(self, __iterable: Iterable[_T_co] = ...) -> None: ... + def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __iand__(self, value: AbstractSet[object], /) -> Self: ... + + @overload + def __rand__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rand__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + + def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + + @overload + def __ror__(self, value: set[_S], /) -> set[_T | _S]: ... + @overload + def __ror__(self, value: frozenset[_S], /) -> frozenset[_T | _S]: ... + + def __sub__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __isub__(self, value: AbstractSet[object], /) -> Self: ... + + @overload + def __rsub__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rsub__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + + def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + + @overload + def __rxor__(self, value: set[_S], /) -> set[_T | _S]: ... + @overload + def __rxor__(self, value: frozenset[_S], /) -> frozenset[_T | _S]: ... + + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class frozenset(AbstractSet[_T_co]): + @overload + def __new__(cls) -> Self: ... + @overload + def __new__(cls, iterable: Iterable[_T_co], /) -> Self: ... + def copy(self) -> frozenset[_T_co]: ... def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ... def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ... - def isdisjoint(self, __s: Iterable[_T_co]) -> bool: ... - def issubset(self, __s: Iterable[object]) -> bool: ... - def issuperset(self, __s: Iterable[object]) -> bool: ... - def symmetric_difference(self, __s: Iterable[_T_co]) -> frozenset[_T_co]: ... + def isdisjoint(self, s: Iterable[object], /) -> bool: ... + def issubset(self, s: Iterable[object], /) -> bool: ... + def issuperset(self, s: Iterable[object], /) -> bool: ... + def symmetric_difference(self, s: Iterable[_S], /) -> frozenset[_T_co | _S]: ... def union(self, *s: Iterable[_S]) -> frozenset[_T_co | _S]: ... def __len__(self) -> int: ... - def __contains__(self, __o: object) -> bool: ... + def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... - def __str__(self) -> str: ... - def __and__(self, __s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... - def __or__(self, __s: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... - def __sub__(self, __s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... - def __xor__(self, __s: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... - def __le__(self, __s: AbstractSet[object]) -> bool: ... - def __lt__(self, __s: AbstractSet[object]) -> bool: ... - def __ge__(self, __s: AbstractSet[object]) -> bool: ... - def __gt__(self, __s: AbstractSet[object]) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... - -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): - def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... - def __iter__(self) -> Iterator[tuple[int, _T]]: ... + def __and__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + + @overload + def __rand__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rand__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + + def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + + @overload + def __ror__(self, value: set[_S], /) -> set[_T_co | _S]: ... + @overload + def __ror__(self, value: frozenset[_S], /) -> frozenset[_T_co | _S]: ... + + def __sub__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + + @overload + def __rsub__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rsub__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + + def __xor__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + + @overload + def __rxor__(self, value: set[_S], /) -> set[_T_co | _S]: ... + @overload + def __rxor__(self, value: frozenset[_S], /) -> frozenset[_T_co | _S]: ... + + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class enumerate(Generic[_T]): + def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class range(Sequence[int]): - start: int - stop: int - step: int + @property + def start(self) -> int: ... + @property + def stop(self) -> int: ... + @property + def step(self) -> int: ... + @overload - def __init__(self, __stop: SupportsIndex) -> None: ... + def __new__(cls, stop: SupportsIndex, /) -> Self: ... @overload - def __init__(self, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> None: ... - def count(self, __value: int) -> int: ... - def index(self, __value: int) -> int: ... # type: ignore[override] + def __new__(cls, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = 1, /) -> Self: ... + + def count(self, value: int, /) -> int: ... + def index(self, value: int, /) -> int: ... # type: ignore[override] def __len__(self) -> int: ... - def __contains__(self, __o: object) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __contains__(self, key: object, /) -> bool: ... def __iter__(self) -> Iterator[int]: ... + @overload - def __getitem__(self, __i: SupportsIndex) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, __s: slice) -> range: ... - def __repr__(self) -> str: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> range: ... + def __reversed__(self) -> Iterator[int]: ... -class property(object): +@disjoint_base +class property: fget: Callable[[Any], Any] | None fset: Callable[[Any, Any], None] | None fdel: Callable[[Any], None] | None + __isabstractmethod__: bool + if sys.version_info >= (3, 13): + __name__: str + def __init__( self, - fget: Callable[[Any], Any] | None = ..., - fset: Callable[[Any, Any], None] | None = ..., - fdel: Callable[[Any], None] | None = ..., - doc: str | None = ..., + fget: Callable[[Any], Any] | None = None, + fset: Callable[[Any, Any], None] | None = None, + fdel: Callable[[Any], None] | None = None, + doc: str | None = None, ) -> None: ... - def getter(self, __fget: Callable[[Any], Any]) -> property: ... - def setter(self, __fset: Callable[[Any, Any], None]) -> property: ... - def deleter(self, __fdel: Callable[[Any], None]) -> property: ... - def __get__(self, __obj: Any, __type: type | None = ...) -> Any: ... - def __set__(self, __obj: Any, __value: Any) -> None: ... - def __delete__(self, __obj: Any) -> None: ... + def getter(self, fget: Callable[[Any], Any], /) -> property: ... + def setter(self, fset: Callable[[Any, Any], None], /) -> property: ... + def deleter(self, fdel: Callable[[Any], None], /) -> property: ... -@final -class _NotImplementedType(Any): # type: ignore[misc] - # A little weird, but typing the __call__ as NotImplemented makes the error message - # for NotImplemented() much better - __call__: NotImplemented # type: ignore[valid-type] + @overload + def __get__(self, instance: None, owner: type, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... -NotImplemented: _NotImplementedType + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... -def abs(__x: SupportsAbs[_T]) -> _T: ... -def all(__iterable: Iterable[object]) -> bool: ... -def any(__iterable: Iterable[object]) -> bool: ... -def ascii(__obj: object) -> str: ... -def bin(__number: int | SupportsIndex) -> str: ... +def abs(x: SupportsAbs[_T], /) -> _T: ... +def all(iterable: Iterable[object], /) -> bool: ... +def any(iterable: Iterable[object], /) -> bool: ... +def ascii(obj: object, /) -> str: ... -if sys.version_info >= (3, 7): - def breakpoint(*args: Any, **kws: Any) -> None: ... +if sys.version_info >= (3, 15): + def bin(integer: SupportsIndex, /) -> str: ... -def callable(__obj: object) -> TypeGuard[Callable[..., object]]: ... -def chr(__i: int) -> str: ... +else: + def bin(number: SupportsIndex, /) -> str: ... -# We define this here instead of using os.PathLike to avoid import cycle issues. -# See https://github.com/python/typeshed/pull/991#issuecomment-288160993 -_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) +def breakpoint(*args: Any, **kws: Any) -> None: ... +def callable(obj: object, /) -> TypeIs[Callable[..., object]]: ... +def chr(i: SupportsIndex, /) -> str: ... +def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co: ... -class _PathLike(Protocol[_AnyStr_co]): - def __fspath__(self) -> _AnyStr_co: ... +@type_check_only +class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): + def __anext__(self) -> _AwaitableT_co: ... + +@overload +# `anext` is not, in fact, an async function. When default is not provided +# `anext` is just a passthrough for `obj.__anext__` +# See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 +def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: ... +@overload +async def anext(i: SupportsAnext[_T], default: _VT, /) -> _T | _VT: ... -if sys.version_info >= (3, 10): - def aiter(__async_iterable: _SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... +# compile() returns a CodeType, unless the flags argument includes PyCF_ONLY_AST (=1024), +# in which case it returns ast.AST. We have overloads for flag 0 (the default) and for +# explicitly passing PyCF_ONLY_AST. We fall back to Any for other values of flags. +if sys.version_info >= (3, 15): @overload - async def anext(__i: SupportsAnext[_T]) -> _T: ... + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> CodeType: ... @overload - async def anext(__i: SupportsAnext[_T], default: _VT) -> _T | _VT: ... - -# TODO: `compile` has a more precise return type in reality; work on a way of expressing that? -if sys.version_info >= (3, 8): def compile( - source: str | bytes | AST, - filename: str | bytes | _PathLike[Any], + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], mode: str, - flags: int = ..., - dont_inherit: int = ..., - optimize: int = ..., *, - _feature_version: int = ..., + dont_inherit: bool = False, + optimize: int = -1, + module: str | None = None, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> _ast.AST: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, ) -> Any: ... - else: + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + *, + dont_inherit: bool = False, + optimize: int = -1, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> _ast.AST: ... + @overload def compile( - source: str | bytes | AST, - filename: str | bytes | _PathLike[Any], + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], mode: str, - flags: int = ..., - dont_inherit: int = ..., - optimize: int = ..., + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, ) -> Any: ... -def copyright() -> None: ... -def credits() -> None: ... -def delattr(__obj: object, __name: str) -> None: ... -def dir(__o: object = ...) -> list[str]: ... +copyright: _sitebuiltins._Printer +credits: _sitebuiltins._Printer + +def delattr(obj: object, name: str, /) -> None: ... +def dir(o: object = ..., /) -> list[str]: ... + @overload -def divmod(__x: SupportsDivMod[_T_contra, _T_co], __y: _T_contra) -> _T_co: ... +def divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ... @overload -def divmod(__x: _T_contra, __y: SupportsRDivMod[_T_contra, _T_co]) -> _T_co: ... +def divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ... # The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance. # (The `globals` argument has to be a "real dict", rather than any old mapping, unlike the `locals` argument.) -def eval( - __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... -) -> Any: ... +if sys.version_info >= (3, 15): + def eval( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | frozendict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + +elif sys.version_info >= (3, 13): + def eval( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + +else: + def eval( + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, + ) -> Any: ... # Comment above regarding `eval` applies to `exec` as well -def exec( - __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... -) -> None: ... -def exit(code: object = ...) -> NoReturn: ... +if sys.version_info >= (3, 15): + def exec( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | frozendict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 13): + def exec( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 11): + def exec( + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +else: + def exec( + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, + ) -> None: ... -class filter(Iterator[_T], Generic[_T]): +exit: _sitebuiltins.Quitter + +@disjoint_base +class filter(Generic[_T]): @overload - def __init__(self, __function: None, __iterable: Iterable[_T | None]) -> None: ... + def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload - def __init__(self, __function: Callable[[_T], Any], __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __new__(cls, function: Callable[[_S], TypeGuard[_T]], iterable: Iterable[_S], /) -> Self: ... + @overload + def __new__(cls, function: Callable[[_S], TypeIs[_T]], iterable: Iterable[_S], /) -> Self: ... + @overload + def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ... + + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode +def format(value: object, format_spec: str = "", /) -> str: ... + @overload -def getattr(__o: object, __name: str) -> Any: ... +def getattr(o: object, name: str, /) -> Any: ... # While technically covered by the last overload, spelling out the types for None, bool # and basic containers help mypy out in some tricky situations involving type context # (aka bidirectional inference) @overload -def getattr(__o: object, __name: str, __default: None) -> Any | None: ... +def getattr(o: object, name: str, default: None, /) -> Any | None: ... @overload -def getattr(__o: object, __name: str, __default: bool) -> Any | bool: ... +def getattr(o: object, name: str, default: bool, /) -> Any | bool: ... @overload -def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ... +def getattr(o: object, name: str, default: list[Any], /) -> Any | list[Any]: ... @overload -def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... +def getattr(o: object, name: str, default: dict[Any, Any], /) -> Any | dict[Any, Any]: ... @overload -def getattr(__o: object, __name: str, __default: _T) -> Any | _T: ... +def getattr(o: object, name: str, default: _T, /) -> Any | _T: ... + def globals() -> dict[str, Any]: ... -def hasattr(__obj: object, __name: str) -> bool: ... -def hash(__obj: object) -> int: ... -def help(request: object = ...) -> None: ... -def hex(__number: int | SupportsIndex) -> str: ... -def id(__obj: object) -> int: ... -def input(__prompt: object = ...) -> str: ... +def hasattr(obj: object, name: str, /) -> bool: ... +def hash(obj: object, /) -> int: ... + +help: _sitebuiltins._Helper + +if sys.version_info >= (3, 15): + def hex(integer: SupportsIndex, /) -> str: ... + +else: + def hex(number: SupportsIndex, /) -> str: ... + +def id(obj: object, /) -> int: ... +def input(prompt: object = "", /) -> str: ... + +@type_check_only +class _GetItemIterable(Protocol[_T_co]): + def __getitem__(self, i: int, /) -> _T_co: ... + +@overload +def iter(object: SupportsIter[_SupportsNextT_co], /) -> _SupportsNextT_co: ... @overload -def iter(__iterable: _SupportsIter[_SupportsNextT]) -> _SupportsNextT: ... +def iter(object: _GetItemIterable[_T], /) -> Iterator[_T]: ... @overload -def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... +def iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: ... @overload -def iter(__function: Callable[[], _T], __sentinel: object) -> Iterator[_T]: ... +def iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ... -# We need recursive types to express the type of the second argument to `isinstance` properly, hence the use of `Any` -if sys.version_info >= (3, 10): - def isinstance( - __obj: object, __class_or_tuple: type | types.UnionType | Tuple[type | types.UnionType | Tuple[Any, ...], ...] - ) -> bool: ... - def issubclass( - __cls: type, __class_or_tuple: type | types.UnionType | Tuple[type | types.UnionType | Tuple[Any, ...], ...] - ) -> bool: ... +_ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...] -else: - def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... - def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... +def isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: ... +def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: ... +def len(obj: Sized, /) -> int: ... + +license: _sitebuiltins._Printer -def len(__obj: Sized) -> int: ... -def license() -> None: ... def locals() -> dict[str, Any]: ... -class map(Iterator[_S], Generic[_S]): - @overload - def __init__(self, __func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> None: ... - @overload - def __init__(self, __func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> None: ... - @overload - def __init__( - self, __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] - ) -> None: ... - @overload - def __init__( - self, - __func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - ) -> None: ... - @overload - def __init__( - self, - __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], - ) -> None: ... - @overload - def __init__( - self, - __func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], - ) -> None: ... - def __iter__(self) -> Iterator[_S]: ... +@disjoint_base +class map(Generic[_S]): + # 3.14 adds `strict` argument. + if sys.version_info >= (3, 14): + @overload + def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /, *, strict: bool = False) -> Self: ... + @overload + def __new__( + cls, func: Callable[[_T1, _T2], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + /, + *, + strict: bool = False, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + *, + strict: bool = False, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + strict: bool = False, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[..., _S], + iterable: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + strict: bool = False, + ) -> Self: ... + else: + @overload + def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /) -> Self: ... + @overload + def __new__(cls, func: Callable[[_T1, _T2], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], /) -> Self: ... + @overload + def __new__( + cls, func: Callable[[_T1, _T2, _T3], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[..., _S], + iterable: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + ) -> Self: ... + + def __iter__(self) -> Self: ... def __next__(self) -> _S: ... @overload def max( - __arg1: SupportsRichComparisonT, __arg2: SupportsRichComparisonT, *_args: SupportsRichComparisonT, key: None = ... + arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None ) -> SupportsRichComparisonT: ... @overload -def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def max(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def max(__iterable: Iterable[SupportsRichComparisonT], *, key: None = ...) -> SupportsRichComparisonT: ... +def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ... @overload -def max(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def max(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def max(__iterable: Iterable[SupportsRichComparisonT], *, key: None = ..., default: _T) -> SupportsRichComparisonT | _T: ... +def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... @overload -def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... +def max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... + @overload def min( - __arg1: SupportsRichComparisonT, __arg2: SupportsRichComparisonT, *_args: SupportsRichComparisonT, key: None = ... + arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None ) -> SupportsRichComparisonT: ... @overload -def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def min(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def min(__iterable: Iterable[SupportsRichComparisonT], *, key: None = ...) -> SupportsRichComparisonT: ... +def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ... @overload -def min(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +def min(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... @overload -def min(__iterable: Iterable[SupportsRichComparisonT], *, key: None = ..., default: _T) -> SupportsRichComparisonT | _T: ... +def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... @overload -def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... +def min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... + @overload -def next(__i: SupportsNext[_T]) -> _T: ... +def next(i: SupportsNext[_T], /) -> _T: ... @overload -def next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ... -def oct(__number: int | SupportsIndex) -> str: ... +def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ... -_OpenFile = Union[StrOrBytesPath, int] -_Opener = Callable[[str, int], int] +if sys.version_info >= (3, 15): + def oct(integer: SupportsIndex, /) -> str: ... + +else: + def oct(number: SupportsIndex, /) -> str: ... + +_Opener: TypeAlias = Callable[[str, int], int] # Text mode: always returns a TextIOWrapper @overload def open( - file: _OpenFile, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + file: FileDescriptorOrPath, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> TextIOWrapper: ... # Unbuffered binary mode: returns a FileIO @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryMode, buffering: Literal[0], - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> FileIO: ... # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BufferedRandom: ... @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BufferedWriter: ... @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BufferedReader: ... # Buffering cannot be determined: fall back to BinaryIO @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryMode, - buffering: int, - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BinaryIO: ... # Fallback if mode is not specified @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: str, - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> IO[Any]: ... -def ord(__c: str | bytes) -> int: ... -class _SupportsWriteAndFlush(SupportsWrite[_T_contra], Protocol[_T_contra]): - def flush(self) -> None: ... +def ord(c: str | bytes | bytearray, /) -> int: ... + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ... @overload def print( *values: object, - sep: str | None = ..., - end: str | None = ..., - file: SupportsWrite[str] | None = ..., - flush: Literal[False] = ..., + sep: str | None = " ", + end: str | None = "\n", + file: SupportsWrite[str] | None = None, + flush: Literal[False] = False, ) -> None: ... @overload def print( - *values: object, sep: str | None = ..., end: str | None = ..., file: _SupportsWriteAndFlush[str] | None = ..., flush: bool + *values: object, sep: str | None = " ", end: str | None = "\n", file: _SupportsWriteAndFlush[str] | None = None, flush: bool ) -> None: ... -_E = TypeVar("_E", contravariant=True) -_M = TypeVar("_M", contravariant=True) +_E_contra = TypeVar("_E_contra", contravariant=True) +_M_contra = TypeVar("_M_contra", contravariant=True) -class _SupportsPow2(Protocol[_E, _T_co]): - def __pow__(self, __other: _E) -> _T_co: ... +@type_check_only +class _SupportsPow2(Protocol[_E_contra, _T_co]): + def __pow__(self, other: _E_contra, /) -> _T_co: ... -class _SupportsPow3NoneOnly(Protocol[_E, _T_co]): - def __pow__(self, __other: _E, __modulo: None = ...) -> _T_co: ... +@type_check_only +class _SupportsPow3NoneOnly(Protocol[_E_contra, _T_co]): + def __pow__(self, other: _E_contra, modulo: None = None, /) -> _T_co: ... -class _SupportsPow3(Protocol[_E, _M, _T_co]): - def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... +@type_check_only +class _SupportsPow3(Protocol[_E_contra, _M_contra, _T_co]): + def __pow__(self, other: _E_contra, modulo: _M_contra, /) -> _T_co: ... -_SupportsSomeKindOfPow = Union[_SupportsPow2[Any, Any], _SupportsPow3NoneOnly[Any, Any], _SupportsPow3[Any, Any, Any]] +_SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] +) -if sys.version_info >= (3, 8): - @overload - def pow(base: int, exp: int, mod: Literal[0]) -> NoReturn: ... - @overload - def pow(base: int, exp: int, mod: int) -> int: ... - @overload - def pow(base: int, exp: _PositiveInteger, mod: None = ...) -> int: ... # type: ignore[misc] - @overload - def pow(base: int, exp: _NegativeInteger, mod: None = ...) -> float: ... # type: ignore[misc] - # int base & positive-int exp -> int; int base & negative-int exp -> float - # return type must be Any as `int | float` causes too many false-positive errors - @overload - def pow(base: int, exp: int, mod: None = ...) -> Any: ... - @overload - def pow(base: float, exp: int, mod: None = ...) -> float: ... - # float base & float exp could return float or complex - # return type must be Any (same as complex base, complex exp), - # as `float | complex` causes too many false-positive errors - @overload - def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = ...) -> Any: ... - @overload - def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = ...) -> complex: ... - @overload - def pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = ...) -> _T_co: ... - @overload - def pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = ...) -> _T_co: ... - @overload - def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M = ...) -> _T_co: ... - @overload - def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = ...) -> Any: ... - @overload - def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = ...) -> complex: ... +# TODO: `pow(int, int, Literal[0])` fails at runtime, +# but adding a `Never` overload isn't a good solution for expressing that (see #8566). +@overload +def pow(base: int, exp: int, mod: int) -> int: ... +@overload +def pow(base: int, exp: Literal[0], mod: None = None) -> Literal[1]: ... +@overload +def pow(base: int, exp: _PositiveInteger, mod: None = None) -> int: ... +@overload +def pow(base: int, exp: _NegativeInteger, mod: None = None) -> float: ... -else: - @overload - def pow(__base: int, __exp: int, __mod: Literal[0]) -> NoReturn: ... - @overload - def pow(__base: int, __exp: int, __mod: int) -> int: ... - @overload - def pow(__base: int, __exp: _PositiveInteger, __mod: None = ...) -> int: ... # type: ignore[misc] - @overload - def pow(__base: int, __exp: _NegativeInteger, __mod: None = ...) -> float: ... # type: ignore[misc] - @overload - def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... - @overload - def pow(__base: float, __exp: int, __mod: None = ...) -> float: ... - @overload - def pow(__base: float, __exp: complex | _SupportsSomeKindOfPow, __mod: None = ...) -> Any: ... - @overload - def pow(__base: complex, __exp: complex | _SupportsSomeKindOfPow, __mod: None = ...) -> complex: ... - @overload - def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E, __mod: None = ...) -> _T_co: ... - @overload - def pow(__base: _SupportsPow3NoneOnly[_E, _T_co], __exp: _E, __mod: None = ...) -> _T_co: ... - @overload - def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M = ...) -> _T_co: ... - @overload - def pow(__base: _SupportsSomeKindOfPow, __exp: float, __mod: None = ...) -> Any: ... - @overload - def pow(__base: _SupportsSomeKindOfPow, __exp: complex, __mod: None = ...) -> complex: ... +# int base & positive-int exp -> int; int base & negative-int exp -> float +# return type must be Any as `int | float` causes too many false-positive errors +@overload +def pow(base: int, exp: int, mod: None = None) -> Any: ... +@overload +def pow(base: _PositiveInteger, exp: float, mod: None = None) -> float: ... +@overload +def pow(base: _NegativeInteger, exp: float, mod: None = None) -> complex: ... +@overload +def pow(base: float, exp: int, mod: None = None) -> float: ... -def quit(code: object = ...) -> NoReturn: ... +# float base & float exp could return float or complex +# return type must be Any (same as complex base, complex exp), +# as `float | complex` causes too many false-positive errors +@overload +def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ... +@overload +def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... +@overload +def pow(base: _SupportsPow2[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] +@overload +def pow(base: _SupportsPow3NoneOnly[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] +@overload +def pow(base: _SupportsPow3[_E_contra, _M_contra, _T_co], exp: _E_contra, mod: _M_contra) -> _T_co: ... +@overload +def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ... +@overload +def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ... + +quit: _sitebuiltins.Quitter + +@type_check_only +class _SupportsReversed(Protocol[_T_co]): + def __reversed__(self) -> _T_co: ... -class reversed(Iterator[_T], Generic[_T]): +@disjoint_base +class reversed(Generic[_T_co]): @overload - def __init__(self, __sequence: Reversible[_T]) -> None: ... + def __new__(cls, sequence: _SupportsReversed[_T], /) -> _T: ... # type: ignore[misc] @overload - def __init__(self, __sequence: SupportsLenAndGetItem[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... - def __next__(self) -> _T: ... + def __new__(cls, sequence: SupportsLenAndGetItem[_T_co], /) -> Self: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + def __length_hint__(self) -> int: ... + +def repr(obj: object, /) -> str: ... + +# See https://github.com/python/typeshed/pull/9141 +# and https://github.com/python/typeshed/pull/9151 +# on why we don't use `SupportsRound` from `typing.pyi` + +@type_check_only +class _SupportsRound1(Protocol[_T_co]): + def __round__(self) -> _T_co: ... + +@type_check_only +class _SupportsRound2(Protocol[_T_co]): + def __round__(self, ndigits: int, /) -> _T_co: ... -def repr(__obj: object) -> str: ... -@overload -def round(number: SupportsRound[Any]) -> int: ... @overload -def round(number: SupportsRound[Any], ndigits: None) -> int: ... +def round(number: _SupportsRound1[_T], ndigits: None = None) -> _T: ... @overload -def round(number: SupportsRound[_T], ndigits: SupportsIndex) -> _T: ... +def round(number: _SupportsRound2[_T], ndigits: SupportsIndex) -> _T: ... # See https://github.com/python/typeshed/pull/6292#discussion_r748875189 # for why arg 3 of `setattr` should be annotated with `Any` and not `object` -def setattr(__obj: object, __name: str, __value: Any) -> None: ... +def setattr(obj: object, name: str, value: Any, /) -> None: ... + +if sys.version_info >= (3, 15): + @final + class sentinel: + __name__: str + __module__: str + def __new__(cls, name: str, /, *, repr: str | None = None) -> sentinel: ... + def __copy__(self, /) -> sentinel: ... + def __deepcopy__(self, memo: Any, /) -> sentinel: ... + # `other` can be any legal form for unions. + # `x | x` creates a `sentinel` instance if `x` is a sentinel, not a `UnionType` instance. + def __or__(self, other: Any, /) -> UnionType | sentinel: ... + def __ror__(self, other: Any, /) -> UnionType | sentinel: ... + @overload def sorted( - __iterable: Iterable[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ... + iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False ) -> list[SupportsRichComparisonT]: ... @overload -def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ... +def sorted(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]: ... + +_AddableT1 = TypeVar("_AddableT1", bound=SupportsAdd[Any, Any]) +_AddableT2 = TypeVar("_AddableT2", bound=SupportsAdd[Any, Any]) + +@type_check_only +class _SupportsSumWithNoDefaultGiven(SupportsAdd[Any, Any], SupportsRAdd[int, Any], Protocol): ... -if sys.version_info >= (3, 8): +_SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWithNoDefaultGiven) + +# In general, the return type of `x + x` is *not* guaranteed to be the same type as x. +# However, we can't express that in the stub for `sum()` +# without creating many false-positive errors (see #7578). +# Instead, we special-case the most common examples of this: bool and literal integers. +@overload +def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ... +@overload +def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... +@overload +def sum(iterable: Iterable[_AddableT1], /, start: _AddableT2) -> _AddableT1 | _AddableT2: ... + +# The argument to `vars()` has to have a `__dict__` attribute, so the second overload can't be annotated with `object` +# (A "SupportsDunderDict" protocol doesn't work) +@overload +def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... +@overload +def vars(object: Any = ..., /) -> dict[str, Any]: ... + +@disjoint_base +class zip(Generic[_T_co]): @overload - def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ... + def __new__(cls, *, strict: bool = False) -> zip[Any]: ... @overload - def sum(__iterable: Iterable[_T], start: _S) -> _T | _S: ... - -else: + def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = False) -> zip[tuple[_T1]]: ... @overload - def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False) -> zip[tuple[_T1, _T2]]: ... @overload - def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... - -# The argument to `vars()` has to have a `__dict__` attribute, so can't be annotated with `object` -# (A "SupportsDunderDict" protocol doesn't work) -def vars(__object: Any = ...) -> dict[str, Any]: ... + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = False + ) -> zip[tuple[_T1, _T2, _T3]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, strict: bool = False + ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + strict: bool = False, + ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def __new__( + cls, + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + strict: bool = False, + ) -> zip[tuple[Any, ...]]: ... -class zip(Iterator[_T_co], Generic[_T_co]): - if sys.version_info >= (3, 10): - @overload - def __new__(cls, __iter1: Iterable[_T1], *, strict: bool = ...) -> zip[tuple[_T1]]: ... - @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], *, strict: bool = ...) -> zip[tuple[_T1, _T2]]: ... - @overload - def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], *, strict: bool = ... - ) -> zip[tuple[_T1, _T2, _T3]]: ... - @overload - def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - *, - strict: bool = ..., - ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], - *, - strict: bool = ..., - ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def __new__( - cls, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], - strict: bool = ..., - ) -> zip[Tuple[Any, ...]]: ... - else: - @overload - def __new__(cls, __iter1: Iterable[_T1]) -> zip[tuple[_T1]]: ... - @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip[tuple[_T1, _T2]]: ... - @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> zip[tuple[_T1, _T2, _T3]]: ... - @overload - def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] - ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], - ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def __new__( - cls, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], - ) -> zip[Tuple[Any, ...]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... # Signature of `builtins.__import__` should be kept identical to `importlib.__import__` # Return type of `__import__` should be kept the same as return type of `importlib.import_module` def __import__( name: str, - globals: Mapping[str, object] | None = ..., - locals: Mapping[str, object] | None = ..., - fromlist: Sequence[str] = ..., - level: int = ..., + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, ) -> types.ModuleType: ... -# Actually the type of Ellipsis is , but since it's -# not exposed anywhere under that name, we make it private here. -@final -class ellipsis: ... +if sys.version_info >= (3, 15): + def __lazy_import__( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, + ) -> Any: ... -Ellipsis: ellipsis +def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... -class BaseException(object): - args: Tuple[Any, ...] +Ellipsis: EllipsisType +NotImplemented: NotImplementedType + +@disjoint_base +class BaseException: + args: tuple[Any, ...] __cause__: BaseException | None __context__: BaseException | None __suppress_context__: bool __traceback__: TracebackType | None - if sys.version_info >= (3, 11): - __note__: str | None def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def with_traceback(self: _TBE, __tb: TracebackType | None) -> _TBE: ... + def __new__(cls, /, *args: Any, **kwds: Any) -> Self: ... + def __setstate__(self, state: dict[str, Any] | None, /) -> None: ... + def with_traceback(self, tb: TracebackType | None, /) -> Self: ... + # Necessary for security-focused static analyzers (e.g, pysa) + # See https://github.com/python/typeshed/pull/14900 + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 + if sys.version_info >= (3, 11): + # only present after add_note() is called + __notes__: list[str] + def add_note(self, note: str, /) -> None: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... +@disjoint_base class SystemExit(BaseException): - code: int + code: sys._ExitCode class Exception(BaseException): ... +@disjoint_base class StopIteration(Exception): value: Any -_StandardError = Exception - +@disjoint_base class OSError(Exception): - errno: int - strerror: str + errno: int | None + strerror: str | None # filename, filename2 are actually str | bytes | None filename: Any filename2: Any @@ -1541,49 +2408,73 @@ IOError = OSError if sys.platform == "win32": WindowsError = OSError -class ArithmeticError(_StandardError): ... -class AssertionError(_StandardError): ... +class ArithmeticError(Exception): ... +class AssertionError(Exception): ... -class AttributeError(_StandardError): - if sys.version_info >= (3, 10): - name: str - obj: object +@disjoint_base +class AttributeError(Exception): + def __init__(self, *args: object, name: str | None = None, obj: object = None) -> None: ... + name: str | None + obj: object -class BufferError(_StandardError): ... -class EOFError(_StandardError): ... +class BufferError(Exception): ... +class EOFError(Exception): ... -class ImportError(_StandardError): - def __init__(self, *args: object, name: str | None = ..., path: str | None = ...) -> None: ... +@disjoint_base +class ImportError(Exception): + def __init__(self, *args: object, name: str | None = None, path: str | None = None) -> None: ... name: str | None path: str | None msg: str # undocumented + if sys.version_info >= (3, 12): + name_from: str | None # undocumented -class LookupError(_StandardError): ... -class MemoryError(_StandardError): ... +if sys.version_info >= (3, 15): + class ImportCycleError(ImportError): ... -class NameError(_StandardError): - if sys.version_info >= (3, 10): - name: str +class LookupError(Exception): ... +class MemoryError(Exception): ... -class ReferenceError(_StandardError): ... -class RuntimeError(_StandardError): ... +@disjoint_base +class NameError(Exception): + def __init__(self, *args: object, name: str | None = None) -> None: ... + name: str | None -class StopAsyncIteration(Exception): - value: Any +class ReferenceError(Exception): ... +class RuntimeError(Exception): ... +class StopAsyncIteration(Exception): ... -class SyntaxError(_StandardError): +@disjoint_base +class SyntaxError(Exception): msg: str + filename: str | None lineno: int | None offset: int | None text: str | None - filename: str | None - if sys.version_info >= (3, 10): - end_lineno: int | None - end_offset: int | None + # Errors are displayed differently if this attribute exists on the exception. + # The value is always None. + print_file_and_line: None + end_lineno: int | None + end_offset: int | None -class SystemError(_StandardError): ... -class TypeError(_StandardError): ... -class ValueError(_StandardError): ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, msg: object, /) -> None: ... + # Second argument is the tuple (filename, lineno, offset, text) + @overload + def __init__(self, msg: str, info: tuple[str | None, int | None, int | None, str | None], /) -> None: ... + # end_lineno and end_offset must both be provided if one is. + @overload + def __init__( + self, msg: str, info: tuple[str | None, int | None, int | None, str | None, int | None, int | None], / + ) -> None: ... + # If you provide more than two arguments, it still creates the SyntaxError, but + # the arguments from the info tuple are not parsed. This form is omitted. + +class SystemError(Exception): ... +class TypeError(Exception): ... +class ValueError(Exception): ... class FloatingPointError(ArithmeticError): ... class OverflowError(ArithmeticError): ... class ZeroDivisionError(ArithmeticError): ... @@ -1615,29 +2506,32 @@ class IndentationError(SyntaxError): ... class TabError(IndentationError): ... class UnicodeError(ValueError): ... +@disjoint_base class UnicodeDecodeError(UnicodeError): encoding: str object: bytes start: int end: int reason: str - def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ... +@disjoint_base class UnicodeEncodeError(UnicodeError): encoding: str object: str start: int end: int reason: str - def __init__(self, __encoding: str, __object: str, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ... +@disjoint_base class UnicodeTranslateError(UnicodeError): encoding: None object: str start: int end: int reason: str - def __init__(self, __object: str, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, object: str, start: int, end: int, reason: str, /) -> None: ... class Warning(Exception): ... class UserWarning(Warning): ... @@ -1650,22 +2544,82 @@ class ImportWarning(Warning): ... class UnicodeWarning(Warning): ... class BytesWarning(Warning): ... class ResourceWarning(Warning): ... - -if sys.version_info >= (3, 10): - class EncodingWarning(Warning): ... +class EncodingWarning(Warning): ... if sys.version_info >= (3, 11): - _SplitCondition = type[BaseException] | tuple[type[BaseException, ...]] | Callable[[BaseException], bool] - class BaseExceptionGroup(BaseException): - def __new__(cls, __message: str, __exceptions: Sequence[BaseException]) -> BaseExceptionGroup | ExceptionGroup: ... + _BaseExceptionT_co = TypeVar("_BaseExceptionT_co", bound=BaseException, covariant=True, default=BaseException) + _BaseExceptionT = TypeVar("_BaseExceptionT", bound=BaseException) + _ExceptionT_co = TypeVar("_ExceptionT_co", bound=Exception, covariant=True, default=Exception) + _ExceptionT = TypeVar("_ExceptionT", bound=Exception) + + # See `check_exception_group.py` for use-cases and comments. + @disjoint_base + class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): + def __new__(cls, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> Self: ... + def __init__(self, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> None: ... @property def message(self) -> str: ... @property - def exceptions(self) -> Sequence[BaseException]: ... - def subgroup(self: Self, __condition: _SplitCondition) -> Self | None: ... - def split(self: Self, __condition: _SplitCondition) -> tuple[Self | None, Self | None]: ... - def derive(self: Self, __excs: Sequence[BaseException]) -> Self: ... - class ExceptionGroup(BaseExceptionGroup, Exception): - def __new__(cls, __message: str, exceptions: Sequence[Exception]) -> ExceptionGroup: ... + def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: ... + + @overload + def subgroup( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> ExceptionGroup[_ExceptionT] | None: ... + @overload + def subgroup( + self, matcher_value: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], / + ) -> BaseExceptionGroup[_BaseExceptionT] | None: ... + @overload + def subgroup( + self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], / + ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ... + + @overload + def split( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> tuple[ExceptionGroup[_ExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + @overload + def split( + self, matcher_value: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], / + ) -> tuple[BaseExceptionGroup[_BaseExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + @overload + def split( + self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], / + ) -> tuple[BaseExceptionGroup[_BaseExceptionT_co] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + + # In reality it is `NonEmptySequence`: + @overload + def derive(self, excs: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ... + @overload + def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): + def __new__(cls, message: str, exceptions: Sequence[_ExceptionT_co], /) -> Self: ... + def __init__(self, message: str, exceptions: Sequence[_ExceptionT_co], /) -> None: ... @property - def exceptions(self) -> Sequence[Exception]: ... + def exceptions(self) -> tuple[_ExceptionT_co | ExceptionGroup[_ExceptionT_co], ...]: ... + + # We accept a narrower type, but that's OK. + @overload # type: ignore[override] + def subgroup( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> ExceptionGroup[_ExceptionT] | None: ... + @overload + def subgroup( + self, matcher_value: Callable[[_ExceptionT_co | Self], bool], / + ) -> ExceptionGroup[_ExceptionT_co] | None: ... + + @overload # type: ignore[override] + def split( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> tuple[ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None]: ... + @overload + def split( + self, matcher_value: Callable[[_ExceptionT_co | Self], bool], / + ) -> tuple[ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None]: ... + +if sys.version_info >= (3, 13): + class PythonFinalizationError(RuntimeError): ... diff --git a/stdlib/bz2.pyi b/stdlib/bz2.pyi index c26698d88dd7..fec6b30af2f5 100644 --- a/stdlib/bz2.pyi +++ b/stdlib/bz2.pyi @@ -1,135 +1,121 @@ -import _compression import sys -from _compression import BaseStream -from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import IO, Any, Iterable, Protocol, TextIO, TypeVar, overload -from typing_extensions import Literal, SupportsIndex, final +from _bz2 import BZ2Compressor as BZ2Compressor, BZ2Decompressor as BZ2Decompressor +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from collections.abc import Iterable +from io import TextIOWrapper +from typing import IO, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self + +if sys.version_info >= (3, 14): + from compression._common._streams import BaseStream, _Reader +else: + from _compression import BaseStream, _Reader + +__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"] # The following attributes and methods are optional: # def fileno(self) -> int: ... # def close(self) -> object: ... -class _ReadableFileobj(_compression._Reader, Protocol): ... +@type_check_only +class _ReadableFileobj(_Reader, Protocol): ... +@type_check_only class _WritableFileobj(Protocol): - def write(self, __b: bytes) -> object: ... + def write(self, b: bytes, /) -> object: ... # The following attributes and methods are optional: # def fileno(self) -> int: ... # def close(self) -> object: ... -_T = TypeVar("_T") - -def compress(data: bytes, compresslevel: int = ...) -> bytes: ... -def decompress(data: bytes) -> bytes: ... +def compress(data: ReadableBuffer, compresslevel: int = 9) -> bytes: ... +def decompress(data: ReadableBuffer) -> bytes: ... -_ReadBinaryMode = Literal["", "r", "rb"] -_WriteBinaryMode = Literal["w", "wb", "x", "xb", "a", "ab"] -_ReadTextMode = Literal["rt"] -_WriteTextMode = Literal["wt", "xt", "at"] +_ReadBinaryMode: TypeAlias = Literal["", "r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_ReadTextMode: TypeAlias = Literal["rt"] +_WriteTextMode: TypeAlias = Literal["wt", "xt", "at"] @overload def open( filename: _ReadableFileobj, - mode: _ReadBinaryMode = ..., - compresslevel: int = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + mode: _ReadBinaryMode = "rb", + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> BZ2File: ... @overload def open( filename: _ReadableFileobj, mode: _ReadTextMode, - compresslevel: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> TextIO: ... + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... @overload def open( filename: _WritableFileobj, mode: _WriteBinaryMode, - compresslevel: int = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> BZ2File: ... @overload def open( filename: _WritableFileobj, mode: _WriteTextMode, - compresslevel: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> TextIO: ... + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... @overload def open( filename: StrOrBytesPath, - mode: _ReadBinaryMode | _WriteBinaryMode = ..., - compresslevel: int = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + mode: _ReadBinaryMode | _WriteBinaryMode = "rb", + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> BZ2File: ... @overload def open( filename: StrOrBytesPath, mode: _ReadTextMode | _WriteTextMode, - compresslevel: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> TextIO: ... + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, + mode: str, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> BZ2File | TextIOWrapper: ... class BZ2File(BaseStream, IO[bytes]): - def __enter__(self: Self) -> Self: ... - if sys.version_info >= (3, 9): - @overload - def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = ...) -> None: ... - @overload - def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = ..., *, compresslevel: int = ...) -> None: ... - @overload - def __init__( - self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = ..., *, compresslevel: int = ... - ) -> None: ... - else: - @overload - def __init__( - self, filename: _WritableFileobj, mode: _WriteBinaryMode, buffering: Any | None = ..., compresslevel: int = ... - ) -> None: ... - @overload - def __init__( - self, filename: _ReadableFileobj, mode: _ReadBinaryMode = ..., buffering: Any | None = ..., compresslevel: int = ... - ) -> None: ... - @overload - def __init__( - self, - filename: StrOrBytesPath, - mode: _ReadBinaryMode | _WriteBinaryMode = ..., - buffering: Any | None = ..., - compresslevel: int = ..., - ) -> None: ... - def read(self, size: int | None = ...) -> bytes: ... - def read1(self, size: int = ...) -> bytes: ... - def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore[override] + def __enter__(self) -> Self: ... + + @overload + def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: ... + @overload + def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = "r", *, compresslevel: int = 9) -> None: ... + @overload + def __init__( + self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = "r", *, compresslevel: int = 9 + ) -> None: ... + + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int = -1) -> bytes: ... + def readline(self, size: SupportsIndex = -1) -> bytes: ... # type: ignore[override] def readinto(self, b: WriteableBuffer) -> int: ... - def readlines(self, size: SupportsIndex = ...) -> list[bytes]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... + def readlines(self, size: SupportsIndex = -1) -> list[bytes]: ... + def peek(self, n: int = 0) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... def write(self, data: ReadableBuffer) -> int: ... def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... - -@final -class BZ2Compressor(object): - def __init__(self, compresslevel: int = ...) -> None: ... - def compress(self, __data: bytes) -> bytes: ... - def flush(self) -> bytes: ... - -@final -class BZ2Decompressor(object): - def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... - @property - def eof(self) -> bool: ... - @property - def needs_input(self) -> bool: ... - @property - def unused_data(self) -> bytes: ... diff --git a/stdlib/cProfile.pyi b/stdlib/cProfile.pyi index f4a7ab50cc11..0e414206f515 100644 --- a/stdlib/cProfile.pyi +++ b/stdlib/cProfile.pyi @@ -1,32 +1,33 @@ +import _lsprof import sys -from _typeshed import Self, StrOrBytesPath +from _typeshed import StrOrBytesPath, Unused +from collections.abc import Callable, Mapping from types import CodeType -from typing import Any, Callable, Tuple, TypeVar +from typing import Any, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self -def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... +__all__ = ["run", "runctx", "Profile"] + +def run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: ... def runctx( - statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... + statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1 ) -> None: ... _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_P = ParamSpec("_P") +_Label: TypeAlias = tuple[str, int, str] -class Profile: +class Profile(_lsprof.Profiler): stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented - def __init__( - self, timer: Callable[[], float] = ..., timeunit: float = ..., subcalls: bool = ..., builtins: bool = ... - ) -> None: ... - def enable(self) -> None: ... - def disable(self) -> None: ... - def print_stats(self, sort: str | int = ...) -> None: ... + def print_stats(self, sort: str | int = -1) -> None: ... def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: Self, cmd: str) -> Self: ... - def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... - if sys.version_info >= (3, 8): - def __enter__(self: Self) -> Self: ... - def __exit__(self, *exc_info: Any) -> None: ... + def run(self, cmd: str) -> Self: ... + def runctx(self, cmd: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> Self: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: Unused) -> None: ... -def label(code: str | CodeType) -> _Label: ... # undocumented +if sys.version_info < (3, 15): + def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/stdlib/calendar.pyi b/stdlib/calendar.pyi index 26073fb7281b..79ffb1ad0bf7 100644 --- a/stdlib/calendar.pyi +++ b/stdlib/calendar.pyi @@ -1,17 +1,74 @@ import datetime +import enum import sys +from _typeshed import Unused +from collections.abc import Iterable, Iterator from time import struct_time -from typing import Any, Iterable, Optional, Sequence, Tuple - -_LocaleType = Tuple[Optional[str], Optional[str]] - -class IllegalMonthError(ValueError): +from typing import ClassVar, Final, TypeAlias, overload + +__all__ = [ + "FRIDAY", + "MONDAY", + "SATURDAY", + "SUNDAY", + "THURSDAY", + "TUESDAY", + "WEDNESDAY", + "IllegalMonthError", + "IllegalWeekdayError", + "setfirstweekday", + "firstweekday", + "isleap", + "leapdays", + "weekday", + "monthrange", + "monthcalendar", + "prmonth", + "month", + "prcal", + "calendar", + "timegm", + "month_name", + "month_abbr", + "day_name", + "day_abbr", + "Calendar", + "TextCalendar", + "HTMLCalendar", + "LocaleTextCalendar", + "LocaleHTMLCalendar", + "weekheader", +] + +if sys.version_info >= (3, 12): + __all__ += [ + "Day", + "Month", + "JANUARY", + "FEBRUARY", + "MARCH", + "APRIL", + "MAY", + "JUNE", + "JULY", + "AUGUST", + "SEPTEMBER", + "OCTOBER", + "NOVEMBER", + "DECEMBER", + ] +if sys.version_info >= (3, 15): + __all__ += ["standalone_month_name", "standalone_month_abbr"] + +_LocaleType: TypeAlias = tuple[str | None, str | None] + +class IllegalMonthError(ValueError, IndexError): + month: int def __init__(self, month: int) -> None: ... - def __str__(self) -> str: ... class IllegalWeekdayError(ValueError): + weekday: int def __init__(self, weekday: int) -> None: ... - def __str__(self) -> str: ... def isleap(year: int) -> bool: ... def leapdays(y1: int, y2: int) -> int: ... @@ -20,98 +77,173 @@ def monthrange(year: int, month: int) -> tuple[int, int]: ... class Calendar: firstweekday: int - def __init__(self, firstweekday: int = ...) -> None: ... + def __init__(self, firstweekday: int = 0) -> None: ... def getfirstweekday(self) -> int: ... def setfirstweekday(self, firstweekday: int) -> None: ... - def iterweekdays(self) -> Iterable[int]: ... - def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ... - def itermonthdays2(self, year: int, month: int) -> Iterable[tuple[int, int]]: ... - def itermonthdays(self, year: int, month: int) -> Iterable[int]: ... + def iterweekdays(self) -> Iterator[int]: ... + def itermonthdates(self, year: int, month: int) -> Iterator[datetime.date]: ... + def itermonthdays2(self, year: int, month: int) -> Iterator[tuple[int, int]]: ... + def itermonthdays(self, year: int, month: int) -> Iterator[int]: ... def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: ... def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: ... def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: ... - def yeardatescalendar(self, year: int, width: int = ...) -> list[list[int]]: ... - def yeardays2calendar(self, year: int, width: int = ...) -> list[list[tuple[int, int]]]: ... - def yeardayscalendar(self, year: int, width: int = ...) -> list[list[int]]: ... - if sys.version_info >= (3, 7): - def itermonthdays3(self, year: int, month: int) -> Iterable[tuple[int, int, int]]: ... - def itermonthdays4(self, year: int, month: int) -> Iterable[tuple[int, int, int, int]]: ... + def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[datetime.date]]]]: ... + def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]: ... + def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]: ... + def itermonthdays3(self, year: int, month: int) -> Iterator[tuple[int, int, int]]: ... + def itermonthdays4(self, year: int, month: int) -> Iterator[tuple[int, int, int, int]]: ... class TextCalendar(Calendar): - def prweek(self, theweek: int, width: int) -> None: ... + def prweek(self, theweek: Iterable[tuple[int, int]], width: int) -> None: ... def formatday(self, day: int, weekday: int, width: int) -> str: ... - def formatweek(self, theweek: int, width: int) -> str: ... + def formatweek(self, theweek: Iterable[tuple[int, int]], width: int) -> str: ... def formatweekday(self, day: int, width: int) -> str: ... def formatweekheader(self, width: int) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... - def prmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... - def formatmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... - def formatyear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... - def pryear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... + def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str: ... + def prmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ... + def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ... + def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... + def pryear(self, theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ... def firstweekday() -> int: ... def monthcalendar(year: int, month: int) -> list[list[int]]: ... def prweek(theweek: int, width: int) -> None: ... def week(theweek: int, width: int) -> str: ... def weekheader(width: int) -> str: ... -def prmonth(theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... -def month(theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... -def calendar(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... -def prcal(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... +def prmonth(theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ... +def month(theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ... +def calendar(theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... +def prcal(theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ... class HTMLCalendar(Calendar): + cssclasses: ClassVar[list[str]] + cssclass_noday: ClassVar[str] + cssclasses_weekday_head: ClassVar[list[str]] + cssclass_month_head: ClassVar[str] + cssclass_month: ClassVar[str] + cssclass_year: ClassVar[str] + cssclass_year_head: ClassVar[str] def formatday(self, day: int, weekday: int) -> str: ... def formatweek(self, theweek: int) -> str: ... def formatweekday(self, day: int) -> str: ... def formatweekheader(self) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... - def formatmonth(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... - def formatyear(self, theyear: int, width: int = ...) -> str: ... - def formatyearpage(self, theyear: int, width: int = ..., css: str | None = ..., encoding: str | None = ...) -> str: ... - if sys.version_info >= (3, 7): - cssclasses: list[str] - cssclass_noday: str - cssclasses_weekday_head: list[str] - cssclass_month_head: str - cssclass_month: str - cssclass_year: str - cssclass_year_head: str + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + if sys.version_info >= (3, 15): + def formatmonthpage( + self, theyear: int, themonth: int, *, css: str | None = "calendar.css", encoding: str | None = None + ) -> bytes: ... + + def formatyear(self, theyear: int, width: int = 3) -> str: ... + def formatyearpage( + self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None + ) -> bytes: ... class different_locale: def __init__(self, locale: _LocaleType) -> None: ... - def __enter__(self) -> _LocaleType: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *args: Unused) -> None: ... class LocaleTextCalendar(TextCalendar): - def __init__(self, firstweekday: int = ..., locale: _LocaleType | None = ...) -> None: ... - def formatweekday(self, day: int, width: int) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... + def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... class LocaleHTMLCalendar(HTMLCalendar): - def __init__(self, firstweekday: int = ..., locale: _LocaleType | None = ...) -> None: ... + def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... def formatweekday(self, day: int) -> str: ... - def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... c: TextCalendar def setfirstweekday(firstweekday: int) -> None: ... -def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... -def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... -def timegm(tuple: Tuple[int, ...] | struct_time) -> int: ... +def format(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ... +def formatstring(cols: Iterable[str], colwidth: int = 20, spacing: int = 6) -> str: ... +def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... # Data attributes -day_name: Sequence[str] -day_abbr: Sequence[str] -month_name: Sequence[str] -month_abbr: Sequence[str] - -# Below constants are not in docs or __all__, but enough people have used them -# they are now effectively public. - -MONDAY: int -TUESDAY: int -WEDNESDAY: int -THURSDAY: int -FRIDAY: int -SATURDAY: int -SUNDAY: int +class _localized_month: + format: str + def __init__(self, format: str) -> None: ... + + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, i: slice) -> list[str]: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + +class _localized_day: + format: str + def __init__(self, format: str) -> None: ... + + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, i: slice) -> list[str]: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + +day_name: _localized_day +day_abbr: _localized_day +month_name: _localized_month +month_abbr: _localized_month + +if sys.version_info >= (3, 12): + class Month(enum.IntEnum): + JANUARY = 1 + FEBRUARY = 2 + MARCH = 3 + APRIL = 4 + MAY = 5 + JUNE = 6 + JULY = 7 + AUGUST = 8 + SEPTEMBER = 9 + OCTOBER = 10 + NOVEMBER = 11 + DECEMBER = 12 + + JANUARY: Final = Month.JANUARY + FEBRUARY: Final = Month.FEBRUARY + MARCH: Final = Month.MARCH + APRIL: Final = Month.APRIL + MAY: Final = Month.MAY + JUNE: Final = Month.JUNE + JULY: Final = Month.JULY + AUGUST: Final = Month.AUGUST + SEPTEMBER: Final = Month.SEPTEMBER + OCTOBER: Final = Month.OCTOBER + NOVEMBER: Final = Month.NOVEMBER + DECEMBER: Final = Month.DECEMBER + + class Day(enum.IntEnum): + MONDAY = 0 + TUESDAY = 1 + WEDNESDAY = 2 + THURSDAY = 3 + FRIDAY = 4 + SATURDAY = 5 + SUNDAY = 6 + + MONDAY: Final = Day.MONDAY + TUESDAY: Final = Day.TUESDAY + WEDNESDAY: Final = Day.WEDNESDAY + THURSDAY: Final = Day.THURSDAY + FRIDAY: Final = Day.FRIDAY + SATURDAY: Final = Day.SATURDAY + SUNDAY: Final = Day.SUNDAY +else: + MONDAY: Final = 0 + TUESDAY: Final = 1 + WEDNESDAY: Final = 2 + THURSDAY: Final = 3 + FRIDAY: Final = 4 + SATURDAY: Final = 5 + SUNDAY: Final = 6 + +EPOCH: Final = 1970 + +if sys.version_info >= (3, 15): + standalone_month_name: _localized_month + standalone_month_abbr: _localized_month diff --git a/stdlib/cgi.pyi b/stdlib/cgi.pyi index 3821de46ed75..fd8752aa6532 100644 --- a/stdlib/cgi.pyi +++ b/stdlib/cgi.pyi @@ -1,45 +1,50 @@ -import sys -from _typeshed import SupportsGetItem, SupportsItemAccess -from builtins import type as _type +import os +from _typeshed import SupportsContainsAndGetItem, SupportsGetItem, SupportsItemAccess, Unused +from builtins import list as _list, type as _type from collections.abc import Iterable, Iterator, Mapping -from typing import IO, Any, Protocol, TypeVar +from email.message import Message +from types import TracebackType +from typing import IO, Any, Protocol, type_check_only +from typing_extensions import Self -_T = TypeVar("_T", bound=FieldStorage) +__all__ = [ + "MiniFieldStorage", + "FieldStorage", + "parse", + "parse_multipart", + "parse_header", + "test", + "print_exception", + "print_environ", + "print_form", + "print_directory", + "print_arguments", + "print_environ_usage", +] def parse( - fp: IO[Any] | None = ..., - environ: SupportsItemAccess[str, str] = ..., + fp: IO[Any] | None = None, + environ: SupportsItemAccess[str, str] = os.environ, keep_blank_values: bool = ..., strict_parsing: bool = ..., - separator: str = ..., + separator: str = "&", ) -> dict[str, list[str]]: ... +def parse_multipart( + fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = "utf-8", errors: str = "replace", separator: str = "&" +) -> dict[str, list[Any]]: ... -if sys.version_info < (3, 8): - def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> dict[str, list[str]]: ... - def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> list[tuple[str, str]]: ... - -if sys.version_info >= (3, 7): - def parse_multipart( - fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = ..., errors: str = ..., separator: str = ... - ) -> dict[str, list[Any]]: ... - -else: - def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, list[bytes]]: ... - +@type_check_only class _Environ(Protocol): - def __getitem__(self, __k: str) -> str: ... + def __getitem__(self, k: str, /) -> str: ... def keys(self) -> Iterable[str]: ... def parse_header(line: str) -> tuple[str, dict[str, str]]: ... -def test(environ: _Environ = ...) -> None: ... -def print_environ(environ: _Environ = ...) -> None: ... +def test(environ: _Environ = os.environ) -> None: ... +def print_environ(environ: _Environ = os.environ) -> None: ... def print_form(form: dict[str, Any]) -> None: ... def print_directory() -> None: ... def print_environ_usage() -> None: ... -if sys.version_info < (3, 8): - def escape(s: str, quote: bool | None = ...) -> str: ... - class MiniFieldStorage: # The first five "Any" attributes here are always None, but mypy doesn't support that filename: Any @@ -53,16 +58,13 @@ class MiniFieldStorage: name: Any value: Any def __init__(self, name: Any, value: Any) -> None: ... - def __repr__(self) -> str: ... - -_list = list -class FieldStorage(object): +class FieldStorage: FieldStorageClass: _type | None keep_blank_values: int strict_parsing: int qs_on_post: str | None - headers: Mapping[str, str] + headers: Mapping[str, str] | Message fp: IO[bytes] encoding: str errors: str @@ -79,32 +81,40 @@ class FieldStorage(object): length: int done: int list: _list[Any] | None - value: None | bytes | _list[Any] + value: bytes | _list[Any] | None def __init__( self, - fp: IO[Any] | None = ..., - headers: Mapping[str, str] | None = ..., - outerboundary: bytes = ..., - environ: SupportsGetItem[str, str] = ..., - keep_blank_values: int = ..., - strict_parsing: int = ..., - limit: int | None = ..., - encoding: str = ..., - errors: str = ..., - max_num_fields: int | None = ..., - separator: str = ..., + fp: IO[Any] | None = None, + headers: Mapping[str, str] | Message | None = None, + outerboundary: bytes = b"", + environ: SupportsContainsAndGetItem[str, str] = os.environ, + keep_blank_values: int = 0, + strict_parsing: int = 0, + limit: int | None = None, + encoding: str = "utf-8", + errors: str = "replace", + max_num_fields: int | None = None, + separator: str = "&", ) -> None: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, *args: Any) -> None: ... - def __repr__(self) -> str: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: ... - def getvalue(self, key: str, default: Any = ...) -> Any: ... - def getfirst(self, key: str, default: Any = ...) -> Any: ... + def getvalue(self, key: str, default: Any = None) -> Any: ... + def getfirst(self, key: str, default: Any = None) -> Any: ... def getlist(self, key: str) -> _list[Any]: ... def keys(self) -> _list[str]: ... def __contains__(self, key: str) -> bool: ... def __len__(self) -> int: ... def __bool__(self) -> bool: ... - # In Python 3 it returns bytes or str IO depending on an internal flag + def __del__(self) -> None: ... + # Returns bytes or str IO depending on an internal flag def make_file(self) -> IO[Any]: ... + +def print_exception( + type: type[BaseException] | None = None, + value: BaseException | None = None, + tb: TracebackType | None = None, + limit: int | None = None, +) -> None: ... +def print_arguments() -> None: ... diff --git a/stdlib/cgitb.pyi b/stdlib/cgitb.pyi index 7576740fc1c0..565725801159 100644 --- a/stdlib/cgitb.pyi +++ b/stdlib/cgitb.pyi @@ -1,8 +1,9 @@ -from _typeshed import StrOrBytesPath +from _typeshed import OptExcInfo, StrOrBytesPath +from collections.abc import Callable from types import FrameType, TracebackType -from typing import IO, Any, Callable, Optional, Tuple, Type +from typing import IO, Any, Final -_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +__UNDEF__: Final[object] # undocumented sentinel def reset() -> str: ... # undocumented def small(text: str) -> str: ... # undocumented @@ -12,20 +13,20 @@ def lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | N def scanvars( reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any] ) -> list[tuple[str, str | None, Any]]: ... # undocumented -def html(einfo: _ExcInfo, context: int = ...) -> str: ... -def text(einfo: _ExcInfo, context: int = ...) -> str: ... +def html(einfo: OptExcInfo, context: int = 5) -> str: ... +def text(einfo: OptExcInfo, context: int = 5) -> str: ... class Hook: # undocumented def __init__( self, - display: int = ..., - logdir: StrOrBytesPath | None = ..., - context: int = ..., - file: IO[str] | None = ..., - format: str = ..., + display: int = 1, + logdir: StrOrBytesPath | None = None, + context: int = 5, + file: IO[str] | None = None, + format: str = "html", ) -> None: ... - def __call__(self, etype: Type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... - def handle(self, info: _ExcInfo | None = ...) -> None: ... + def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... + def handle(self, info: OptExcInfo | None = None) -> None: ... -def handler(info: _ExcInfo | None = ...) -> None: ... -def enable(display: int = ..., logdir: StrOrBytesPath | None = ..., context: int = ..., format: str = ...) -> None: ... +def handler(info: OptExcInfo | None = None) -> None: ... +def enable(display: int = 1, logdir: StrOrBytesPath | None = None, context: int = 5, format: str = "html") -> None: ... diff --git a/stdlib/chunk.pyi b/stdlib/chunk.pyi index 50ff267c5436..9788d35f680c 100644 --- a/stdlib/chunk.pyi +++ b/stdlib/chunk.pyi @@ -9,12 +9,12 @@ class Chunk: size_read: int offset: int seekable: bool - def __init__(self, file: IO[bytes], align: bool = ..., bigendian: bool = ..., inclheader: bool = ...) -> None: ... + def __init__(self, file: IO[bytes], align: bool = True, bigendian: bool = True, inclheader: bool = False) -> None: ... def getname(self) -> bytes: ... def getsize(self) -> int: ... def close(self) -> None: ... def isatty(self) -> bool: ... - def seek(self, pos: int, whence: int = ...) -> None: ... + def seek(self, pos: int, whence: int = 0) -> None: ... def tell(self) -> int: ... - def read(self, size: int = ...) -> bytes: ... + def read(self, size: int = -1) -> bytes: ... def skip(self) -> None: ... diff --git a/stdlib/cmath.pyi b/stdlib/cmath.pyi index 04c2b632d411..554eb54e2e4c 100644 --- a/stdlib/cmath.pyi +++ b/stdlib/cmath.pyi @@ -1,42 +1,36 @@ -import sys -from typing import SupportsComplex, SupportsFloat, Union +from typing import Final, SupportsComplex, SupportsFloat, SupportsIndex, TypeAlias -if sys.version_info >= (3, 8): - from typing import SupportsIndex +e: Final[float] +pi: Final[float] +inf: Final[float] +infj: Final[complex] +nan: Final[float] +nanj: Final[complex] +tau: Final[float] -e: float -pi: float -inf: float -infj: complex -nan: float -nanj: complex -tau: float +_F: TypeAlias = SupportsFloat | SupportsIndex +_C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex -if sys.version_info >= (3, 8): - _C = Union[SupportsFloat, SupportsComplex, SupportsIndex, complex] -else: - _C = Union[SupportsFloat, SupportsComplex, complex] - -def acos(__z: _C) -> complex: ... -def acosh(__z: _C) -> complex: ... -def asin(__z: _C) -> complex: ... -def asinh(__z: _C) -> complex: ... -def atan(__z: _C) -> complex: ... -def atanh(__z: _C) -> complex: ... -def cos(__z: _C) -> complex: ... -def cosh(__z: _C) -> complex: ... -def exp(__z: _C) -> complex: ... -def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = ..., abs_tol: SupportsFloat = ...) -> bool: ... -def isinf(__z: _C) -> bool: ... -def isnan(__z: _C) -> bool: ... -def log(__x: _C, __y_obj: _C = ...) -> complex: ... -def log10(__z: _C) -> complex: ... -def phase(__z: _C) -> float: ... -def polar(__z: _C) -> tuple[float, float]: ... -def rect(__r: float, __phi: float) -> complex: ... -def sin(__z: _C) -> complex: ... -def sinh(__z: _C) -> complex: ... -def sqrt(__z: _C) -> complex: ... -def tan(__z: _C) -> complex: ... -def tanh(__z: _C) -> complex: ... -def isfinite(__z: _C) -> bool: ... +def acos(z: _C, /) -> complex: ... +def acosh(z: _C, /) -> complex: ... +def asin(z: _C, /) -> complex: ... +def asinh(z: _C, /) -> complex: ... +def atan(z: _C, /) -> complex: ... +def atanh(z: _C, /) -> complex: ... +def cos(z: _C, /) -> complex: ... +def cosh(z: _C, /) -> complex: ... +def exp(z: _C, /) -> complex: ... +def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = 1e-09, abs_tol: SupportsFloat = 0.0) -> bool: ... +def isinf(z: _C, /) -> bool: ... +def isnan(z: _C, /) -> bool: ... +def log(z: _C, base: _C = ..., /) -> complex: ... +def log10(z: _C, /) -> complex: ... +def phase(z: _C, /) -> float: ... +def polar(z: _C, /) -> tuple[float, float]: ... +def rect(r: _F, phi: _F, /) -> complex: ... +def sin(z: _C, /) -> complex: ... +def sinh(z: _C, /) -> complex: ... +def sqrt(z: _C, /) -> complex: ... +def tan(z: _C, /) -> complex: ... +def tanh(z: _C, /) -> complex: ... +def isfinite(z: _C, /) -> bool: ... diff --git a/stdlib/cmd.pyi b/stdlib/cmd.pyi index f6d818591a4e..6e84133572bf 100644 --- a/stdlib/cmd.pyi +++ b/stdlib/cmd.pyi @@ -1,4 +1,11 @@ -from typing import IO, Any, Callable +from collections.abc import Callable +from typing import IO, Any, Final +from typing_extensions import LiteralString + +__all__ = ["Cmd"] + +PROMPT: Final = "(Cmd) " +IDENTCHARS: Final[LiteralString] # Too big to be `Literal` class Cmd: prompt: str @@ -16,9 +23,9 @@ class Cmd: stdout: IO[str] cmdqueue: list[str] completekey: str - def __init__(self, completekey: str = ..., stdin: IO[str] | None = ..., stdout: IO[str] | None = ...) -> None: ... + def __init__(self, completekey: str = "tab", stdin: IO[str] | None = None, stdout: IO[str] | None = None) -> None: ... old_completer: Callable[[str, int], str | None] | None - def cmdloop(self, intro: Any | None = ...) -> None: ... + def cmdloop(self, intro: Any | None = None) -> None: ... def precmd(self, line: str) -> str: ... def postcmd(self, stop: bool, line: str) -> bool: ... def preloop(self) -> None: ... @@ -26,7 +33,7 @@ class Cmd: def parseline(self, line: str) -> tuple[str | None, str | None, str]: ... def onecmd(self, line: str) -> bool: ... def emptyline(self) -> bool: ... - def default(self, line: str) -> bool: ... + def default(self, line: str) -> None: ... def completedefault(self, *ignored: Any) -> list[str]: ... def completenames(self, text: str, *ignored: Any) -> list[str]: ... completion_matches: list[str] | None @@ -36,4 +43,4 @@ class Cmd: def complete_help(self, *args: Any) -> list[str]: ... def do_help(self, arg: str) -> bool | None: ... def print_topics(self, header: str, cmds: list[str] | None, cmdlen: Any, maxcol: int) -> None: ... - def columnize(self, list: list[str] | None, displaywidth: int = ...) -> None: ... + def columnize(self, list: list[str] | None, displaywidth: int = 80) -> None: ... diff --git a/stdlib/code.pyi b/stdlib/code.pyi index ed00eaf96a5c..478d5aaa320f 100644 --- a/stdlib/code.pyi +++ b/stdlib/code.pyi @@ -1,30 +1,55 @@ -from codeop import CommandCompiler +import sys +from codeop import CommandCompiler, compile_command as compile_command +from collections.abc import Callable from types import CodeType -from typing import Any, Callable, Mapping +from typing import Any + +__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] class InteractiveInterpreter: - locals: Mapping[str, Any] # undocumented + locals: dict[str, Any] # undocumented compile: CommandCompiler # undocumented - def __init__(self, locals: Mapping[str, Any] | None = ...) -> None: ... - def runsource(self, source: str, filename: str = ..., symbol: str = ...) -> bool: ... + def __init__(self, locals: dict[str, Any] | None = None) -> None: ... + def runsource(self, source: str, filename: str = "", symbol: str = "single") -> bool: ... def runcode(self, code: CodeType) -> None: ... - def showsyntaxerror(self, filename: str | None = ...) -> None: ... + if sys.version_info >= (3, 13): + def showsyntaxerror(self, filename: str | None = None, *, source: str = "") -> None: ... + else: + def showsyntaxerror(self, filename: str | None = None) -> None: ... + def showtraceback(self) -> None: ... def write(self, data: str) -> None: ... class InteractiveConsole(InteractiveInterpreter): buffer: list[str] # undocumented filename: str # undocumented - def __init__(self, locals: Mapping[str, Any] | None = ..., filename: str = ...) -> None: ... - def interact(self, banner: str | None = ..., exitmsg: str | None = ...) -> None: ... - def push(self, line: str) -> bool: ... + if sys.version_info >= (3, 13): + local_exit: bool # undocumented + def __init__( + self, locals: dict[str, Any] | None = None, filename: str = "", *, local_exit: bool = False + ) -> None: ... + def push(self, line: str, filename: str | None = None) -> bool: ... + else: + def __init__(self, locals: dict[str, Any] | None = None, filename: str = "") -> None: ... + def push(self, line: str) -> bool: ... + + def interact(self, banner: str | None = None, exitmsg: str | None = None) -> None: ... def resetbuffer(self) -> None: ... - def raw_input(self, prompt: str = ...) -> str: ... + def raw_input(self, prompt: str = "") -> str: ... + +if sys.version_info >= (3, 13): + def interact( + banner: str | None = None, + readfunc: Callable[[str], str] | None = None, + local: dict[str, Any] | None = None, + exitmsg: str | None = None, + local_exit: bool = False, + ) -> None: ... -def interact( - banner: str | None = ..., - readfunc: Callable[[str], str] | None = ..., - local: Mapping[str, Any] | None = ..., - exitmsg: str | None = ..., -) -> None: ... -def compile_command(source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... +else: + def interact( + banner: str | None = None, + readfunc: Callable[[str], str] | None = None, + local: dict[str, Any] | None = None, + exitmsg: str | None = None, + ) -> None: ... diff --git a/stdlib/codecs.pyi b/stdlib/codecs.pyi index 63de22d99188..ee1ab25bac47 100644 --- a/stdlib/codecs.pyi +++ b/stdlib/codecs.pyi @@ -1,153 +1,235 @@ import sys import types -from _typeshed import Self +from _codecs import * +from _typeshed import ReadableBuffer from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, Tuple, Type, TypeVar, overload -from typing_extensions import Literal +from collections.abc import Callable, Generator, Iterable +from typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base -BOM32_BE: bytes -BOM32_LE: bytes -BOM64_BE: bytes -BOM64_LE: bytes +__all__ = [ + "register", + "lookup", + "open", + "EncodedFile", + "BOM", + "BOM_BE", + "BOM_LE", + "BOM32_BE", + "BOM32_LE", + "BOM64_BE", + "BOM64_LE", + "BOM_UTF8", + "BOM_UTF16", + "BOM_UTF16_LE", + "BOM_UTF16_BE", + "BOM_UTF32", + "BOM_UTF32_LE", + "BOM_UTF32_BE", + "CodecInfo", + "Codec", + "IncrementalEncoder", + "IncrementalDecoder", + "StreamReader", + "StreamWriter", + "StreamReaderWriter", + "StreamRecoder", + "getencoder", + "getdecoder", + "getincrementalencoder", + "getincrementaldecoder", + "getreader", + "getwriter", + "encode", + "decode", + "iterencode", + "iterdecode", + "strict_errors", + "ignore_errors", + "replace_errors", + "xmlcharrefreplace_errors", + "backslashreplace_errors", + "namereplace_errors", + "register_error", + "lookup_error", +] + +BOM32_BE: Final = b"\xfe\xff" +BOM32_LE: Final = b"\xff\xfe" +BOM64_BE: Final = b"\x00\x00\xfe\xff" +BOM64_LE: Final = b"\xff\xfe\x00\x00" + +_BufferedEncoding: TypeAlias = Literal[ + "idna", + "raw-unicode-escape", + "unicode-escape", + "utf-16", + "utf-16-be", + "utf-16-le", + "utf-32", + "utf-32-be", + "utf-32-le", + "utf-7", + "utf-8", + "utf-8-sig", +] + +@type_check_only +class _WritableStream(Protocol): + def write(self, data: bytes, /) -> object: ... + def seek(self, offset: int, whence: int, /) -> object: ... + def close(self) -> object: ... + +@type_check_only +class _ReadableStream(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + def seek(self, offset: int, whence: int, /) -> object: ... + def close(self) -> object: ... + +@type_check_only +class _Stream(_WritableStream, _ReadableStream, Protocol): ... # TODO: this only satisfies the most common interface, where # bytes is the raw form and str is the cooked form. # In the long run, both should become template parameters maybe? # There *are* bytes->bytes and str->str encodings in the standard library. -# They are much more common in Python 2 than in Python 3. +# They were much more common in Python 2 than in Python 3. +@type_check_only class _Encoder(Protocol): - def __call__(self, input: str, errors: str = ...) -> tuple[bytes, int]: ... # signature of Codec().encode + def __call__(self, input: str, errors: str = ..., /) -> tuple[bytes, int]: ... # signature of Codec().encode +@type_check_only class _Decoder(Protocol): - def __call__(self, input: bytes, errors: str = ...) -> tuple[str, int]: ... # signature of Codec().decode + def __call__(self, input: ReadableBuffer, errors: str = ..., /) -> tuple[str, int]: ... # signature of Codec().decode +@type_check_only class _StreamReader(Protocol): - def __call__(self, stream: IO[bytes], errors: str = ...) -> StreamReader: ... + def __call__(self, stream: _ReadableStream, errors: str = ..., /) -> StreamReader: ... +@type_check_only class _StreamWriter(Protocol): - def __call__(self, stream: IO[bytes], errors: str = ...) -> StreamWriter: ... + def __call__(self, stream: _WritableStream, errors: str = ..., /) -> StreamWriter: ... +@type_check_only class _IncrementalEncoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalEncoder: ... +@type_check_only class _IncrementalDecoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalDecoder: ... -# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 -# mypy and pytype disagree about where the type ignore can and cannot go, so alias the long type -_BytesToBytesEncodingT = Literal[ - "base64", - "base_64", - "base64_codec", - "bz2", - "bz2_codec", - "hex", - "hex_codec", - "quopri", - "quotedprintable", - "quoted_printable", - "quopri_codec", - "uu", - "uu_codec", - "zip", - "zlib", - "zlib_codec", -] +@type_check_only +class _BufferedIncrementalDecoder(Protocol): + def __call__(self, errors: str = ...) -> BufferedIncrementalDecoder: ... -@overload -def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... -@overload -def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore[misc] -@overload -def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ... -@overload -def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore[misc] -@overload -def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... -@overload -def decode(obj: bytes, encoding: str = ..., errors: str = ...) -> str: ... -def lookup(__encoding: str) -> CodecInfo: ... -def utf_16_be_decode(__data: bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... # undocumented -def utf_16_be_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... # undocumented +if sys.version_info >= (3, 12): + class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): + _is_text_encoding: bool + @property + def encode(self) -> _Encoder: ... + @property + def decode(self) -> _Decoder: ... + @property + def streamreader(self) -> _StreamReader: ... + @property + def streamwriter(self) -> _StreamWriter: ... + @property + def incrementalencoder(self) -> _IncrementalEncoder: ... + @property + def incrementaldecoder(self) -> _IncrementalDecoder: ... + name: str + def __new__( + cls, + encode: _Encoder, + decode: _Decoder, + streamreader: _StreamReader | None = None, + streamwriter: _StreamWriter | None = None, + incrementalencoder: _IncrementalEncoder | None = None, + incrementaldecoder: _IncrementalDecoder | None = None, + name: str | None = None, + *, + _is_text_encoding: bool | None = None, + ) -> Self: ... -class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): - @property - def encode(self) -> _Encoder: ... - @property - def decode(self) -> _Decoder: ... - @property - def streamreader(self) -> _StreamReader: ... - @property - def streamwriter(self) -> _StreamWriter: ... - @property - def incrementalencoder(self) -> _IncrementalEncoder: ... - @property - def incrementaldecoder(self) -> _IncrementalDecoder: ... - name: str - def __new__( - cls, - encode: _Encoder, - decode: _Decoder, - streamreader: _StreamReader | None = ..., - streamwriter: _StreamWriter | None = ..., - incrementalencoder: _IncrementalEncoder | None = ..., - incrementaldecoder: _IncrementalDecoder | None = ..., - name: str | None = ..., - *, - _is_text_encoding: bool | None = ..., - ) -> CodecInfo: ... +else: + @disjoint_base + class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): + _is_text_encoding: bool + @property + def encode(self) -> _Encoder: ... + @property + def decode(self) -> _Decoder: ... + @property + def streamreader(self) -> _StreamReader: ... + @property + def streamwriter(self) -> _StreamWriter: ... + @property + def incrementalencoder(self) -> _IncrementalEncoder: ... + @property + def incrementaldecoder(self) -> _IncrementalDecoder: ... + name: str + def __new__( + cls, + encode: _Encoder, + decode: _Decoder, + streamreader: _StreamReader | None = None, + streamwriter: _StreamWriter | None = None, + incrementalencoder: _IncrementalEncoder | None = None, + incrementaldecoder: _IncrementalDecoder | None = None, + name: str | None = None, + *, + _is_text_encoding: bool | None = None, + ) -> Self: ... def getencoder(encoding: str) -> _Encoder: ... def getdecoder(encoding: str) -> _Decoder: ... def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... + +@overload +def getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDecoder: ... +@overload def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... + def getreader(encoding: str) -> _StreamReader: ... def getwriter(encoding: str) -> _StreamWriter: ... -def register(__search_function: Callable[[str], CodecInfo | None]) -> None: ... +@deprecated("Deprecated. Use `open()` instead.") def open( - filename: str, mode: str = ..., encoding: str | None = ..., errors: str = ..., buffering: int = ... + filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 ) -> StreamReaderWriter: ... -def EncodedFile(file: IO[bytes], data_encoding: str, file_encoding: str | None = ..., errors: str = ...) -> StreamRecoder: ... -def iterencode(iterator: Iterable[str], encoding: str, errors: str = ...) -> Generator[bytes, None, None]: ... -def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = ...) -> Generator[str, None, None]: ... - -if sys.version_info >= (3, 10): - def unregister(__search_function: Callable[[str], CodecInfo | None]) -> None: ... +def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = None, errors: str = "strict") -> StreamRecoder: ... +def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes]: ... +def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str]: ... -BOM: bytes -BOM_BE: bytes -BOM_LE: bytes -BOM_UTF8: bytes -BOM_UTF16: bytes -BOM_UTF16_BE: bytes -BOM_UTF16_LE: bytes -BOM_UTF32: bytes -BOM_UTF32_BE: bytes -BOM_UTF32_LE: bytes +BOM: Final[Literal[b"\xff\xfe", b"\xfe\xff"]] # depends on `sys.byteorder` +BOM_BE: Final = b"\xfe\xff" +BOM_LE: Final = b"\xff\xfe" +BOM_UTF8: Final = b"\xef\xbb\xbf" +BOM_UTF16: Final[Literal[b"\xff\xfe", b"\xfe\xff"]] # depends on `sys.byteorder` +BOM_UTF16_BE: Final = b"\xfe\xff" +BOM_UTF16_LE: Final = b"\xff\xfe" +BOM_UTF32: Final[Literal[b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff"]] # depends on `sys.byteorder` +BOM_UTF32_BE: Final = b"\x00\x00\xfe\xff" +BOM_UTF32_LE: Final = b"\xff\xfe\x00\x00" -# It is expected that different actions be taken depending on which of the -# three subclasses of `UnicodeError` is actually ...ed. However, the Union -# is still needed for at least one of the cases. -def register_error(__errors: str, __handler: Callable[[UnicodeError], tuple[str | bytes, int]]) -> None: ... -def lookup_error(__name: str) -> Callable[[UnicodeError], tuple[str | bytes, int]]: ... -def strict_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... -def replace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... -def ignore_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... -def xmlcharrefreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... -def backslashreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def strict_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def replace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def ignore_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def xmlcharrefreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def backslashreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def namereplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... class Codec: # These are sort of @abstractmethod but sort of not. # The StreamReader and StreamWriter subclasses only implement one. - def encode(self, input: str, errors: str = ...) -> tuple[bytes, int]: ... - def decode(self, input: bytes, errors: str = ...) -> tuple[str, int]: ... + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... class IncrementalEncoder: errors: str - def __init__(self, errors: str = ...) -> None: ... + def __init__(self, errors: str = "strict") -> None: ... @abstractmethod - def encode(self, input: str, final: bool = ...) -> bytes: ... + def encode(self, input: str, final: bool = False) -> bytes: ... def reset(self) -> None: ... # documentation says int but str is needed for the subclass. def getstate(self) -> int | str: ... @@ -155,9 +237,9 @@ class IncrementalEncoder: class IncrementalDecoder: errors: str - def __init__(self, errors: str = ...) -> None: ... + def __init__(self, errors: str = "strict") -> None: ... @abstractmethod - def decode(self, input: bytes, final: bool = ...) -> str: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... def reset(self) -> None: ... def getstate(self) -> tuple[bytes, int]: ... def setstate(self, state: tuple[bytes, int]) -> None: ... @@ -165,61 +247,65 @@ class IncrementalDecoder: # These are not documented but used in encodings/*.py implementations. class BufferedIncrementalEncoder(IncrementalEncoder): buffer: str - def __init__(self, errors: str = ...) -> None: ... + def __init__(self, errors: str = "strict") -> None: ... @abstractmethod - def _buffer_encode(self, input: str, errors: str, final: bool) -> bytes: ... - def encode(self, input: str, final: bool = ...) -> bytes: ... + def _buffer_encode(self, input: str, errors: str, final: bool) -> tuple[bytes, int]: ... + def encode(self, input: str, final: bool = False) -> bytes: ... class BufferedIncrementalDecoder(IncrementalDecoder): buffer: bytes - def __init__(self, errors: str = ...) -> None: ... + def __init__(self, errors: str = "strict") -> None: ... @abstractmethod - def _buffer_decode(self, input: bytes, errors: str, final: bool) -> tuple[str, int]: ... - def decode(self, input: bytes, final: bool = ...) -> str: ... + def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... # TODO: it is not possible to specify the requirement that all other # attributes and methods are passed-through from the stream. class StreamWriter(Codec): + stream: _WritableStream errors: str - def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... + def __init__(self, stream: _WritableStream, errors: str = "strict") -> None: ... def write(self, object: str) -> None: ... def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... + def seek(self, offset: int, whence: int = 0) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: ... class StreamReader(Codec): + stream: _ReadableStream errors: str - def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... - def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> str: ... - def readline(self, size: int | None = ..., keepends: bool = ...) -> str: ... - def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> list[str]: ... + # This is set to str, but some subclasses set to bytes instead. + charbuffertype: ClassVar[type] = ... + def __init__(self, stream: _ReadableStream, errors: str = "strict") -> None: ... + def read(self, size: int = -1, chars: int = -1, firstline: bool = False) -> str: ... + def readline(self, size: int | None = None, keepends: bool = True) -> str: ... + def readlines(self, sizehint: int | None = None, keepends: bool = True) -> list[str]: ... def reset(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... - -_T = TypeVar("_T", bound=StreamReaderWriter) + def seek(self, offset: int, whence: int = 0) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> str: ... + def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: ... # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): - def __init__(self, stream: IO[bytes], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... - def read(self, size: int = ...) -> str: ... - def readline(self, size: int | None = ...) -> str: ... - def readlines(self, sizehint: int | None = ...) -> list[str]: ... + stream: _Stream + def __init__(self, stream: _Stream, Reader: _StreamReader, Writer: _StreamWriter, errors: str = "strict") -> None: ... + def read(self, size: int = -1) -> str: ... + def readline(self, size: int | None = None) -> str: ... + def readlines(self, sizehint: int | None = None) -> list[str]: ... def __next__(self) -> str: ... - def __iter__(self: _T) -> _T: ... - # This actually returns None, but that's incompatible with the supertype - def write(self, data: str) -> int: ... + def __iter__(self) -> Self: ... + def write(self, data: str) -> None: ... # type: ignore[override] def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... - # Same as write() - def seek(self, offset: int, whence: int = ...) -> int: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... # type: ignore[override] + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: ... # These methods don't actually exist directly, but they are needed to satisfy the TextIO # interface. At runtime, they are delegated through __getattr__. @@ -233,32 +319,33 @@ class StreamReaderWriter(TextIO): def tell(self) -> int: ... def writable(self) -> bool: ... -_SRT = TypeVar("_SRT", bound=StreamRecoder) - class StreamRecoder(BinaryIO): + data_encoding: str + file_encoding: str def __init__( self, - stream: IO[bytes], + stream: _Stream, encode: _Encoder, decode: _Decoder, Reader: _StreamReader, Writer: _StreamWriter, - errors: str = ..., + errors: str = "strict", ) -> None: ... - def read(self, size: int = ...) -> bytes: ... - def readline(self, size: int | None = ...) -> bytes: ... - def readlines(self, sizehint: int | None = ...) -> list[bytes]: ... + def read(self, size: int = -1) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, sizehint: int | None = None) -> list[bytes]: ... def __next__(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... - def write(self, data: bytes) -> int: ... - def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None + def __iter__(self) -> Self: ... + # Base class accepts more types than just bytes + def write(self, data: bytes) -> None: ... # type: ignore[override] + def writelines(self, list: Iterable[bytes]) -> None: ... # type: ignore[override] def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... # type: ignore[override] # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO # interface. At runtime, they are delegated through __getattr__. - def seek(self, offset: int, whence: int = ...) -> int: ... def close(self) -> None: ... def fileno(self) -> int: ... def flush(self) -> None: ... diff --git a/stdlib/codeop.pyi b/stdlib/codeop.pyi index 8ed5710c9891..8e311343eb89 100644 --- a/stdlib/codeop.pyi +++ b/stdlib/codeop.pyi @@ -1,13 +1,21 @@ +import sys from types import CodeType -def compile_command(source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... +__all__ = ["compile_command", "Compile", "CommandCompiler"] + +if sys.version_info >= (3, 14): + def compile_command(source: str, filename: str = "", symbol: str = "single", flags: int = 0) -> CodeType | None: ... + +else: + def compile_command(source: str, filename: str = "", symbol: str = "single") -> CodeType | None: ... class Compile: flags: int - def __init__(self) -> None: ... - def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... + if sys.version_info >= (3, 13): + def __call__(self, source: str, filename: str, symbol: str, flags: int = 0) -> CodeType: ... + else: + def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... class CommandCompiler: compiler: Compile - def __init__(self) -> None: ... - def __call__(self, source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... + def __call__(self, source: str, filename: str = "", symbol: str = "single") -> CodeType | None: ... diff --git a/stdlib/collections/__init__.pyi b/stdlib/collections/__init__.pyi index d4808d326efe..bce72464fd75 100644 --- a/stdlib/collections/__init__.pyi +++ b/stdlib/collections/__init__.pyi @@ -1,110 +1,177 @@ import sys from _collections_abc import dict_items, dict_keys, dict_values -from _typeshed import Self, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT -from typing import Any, Dict, Generic, NoReturn, Tuple, Type, TypeVar, overload -from typing_extensions import SupportsIndex, final +from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from collections.abc import ( + Callable, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + MutableMapping, + MutableSequence, + Sequence, + ValuesView, +) +from types import GenericAlias +from typing import Any, ClassVar, Generic, SupportsIndex, TypeVar, final, overload, type_check_only +from typing_extensions import Never, Self, disjoint_base -if sys.version_info >= (3, 9): - from types import GenericAlias +if sys.version_info >= (3, 15): + from builtins import frozendict -if sys.version_info >= (3, 10): - from typing import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Reversible, Sequence -else: - from _collections_abc import * +__all__ = ["ChainMap", "Counter", "OrderedDict", "UserDict", "UserList", "UserString", "defaultdict", "deque", "namedtuple"] _S = TypeVar("_S") _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") _KT_co = TypeVar("_KT_co", covariant=True) _VT_co = TypeVar("_VT_co", covariant=True) # namedtuple is special-cased in the type checker; the initializer is ignored. -if sys.version_info >= (3, 7): - def namedtuple( - typename: str, - field_names: str | Iterable[str], - *, - rename: bool = ..., - module: str | None = ..., - defaults: Iterable[Any] | None = ..., - ) -> Type[Tuple[Any, ...]]: ... - -else: - def namedtuple( - typename: str, field_names: str | Iterable[str], *, verbose: bool = ..., rename: bool = ..., module: str | None = ... - ) -> Type[Tuple[Any, ...]]: ... - -class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): +def namedtuple( + typename: str, + field_names: str | Iterable[str], + *, + rename: bool = False, + module: str | None = None, + defaults: Iterable[Any] | None = None, +) -> type[tuple[Any, ...]]: ... + +class UserDict(MutableMapping[_KT, _VT]): data: dict[_KT, _VT] + # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics @overload - def __init__(self: UserDict[_KT, _VT], __dict: None = ...) -> None: ... + def __init__(self, dict: None = None, /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], __dict: None = ..., **kwargs: _VT) -> None: ... + def __init__( + self: UserDict[str, _VT], dict: None = None, /, **kwargs: _VT # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... @overload - def __init__(self, __dict: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, dict: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... + @overload + def __init__( + self: UserDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + dict: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... @overload - def __init__(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload - def __init__(self: UserDict[str, str], __iterable: Iterable[list[str]]) -> None: ... + def __init__( + self: UserDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self: UserDict[str, str], iterable: Iterable[list[str]], /) -> None: ... + @overload + def __init__(self: UserDict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... + def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, item: _VT) -> None: ... def __delitem__(self, key: _KT) -> None: ... def __iter__(self) -> Iterator[_KT]: ... def __contains__(self, key: object) -> bool: ... - def copy(self: Self) -> Self: ... + def copy(self) -> Self: ... + def __copy__(self) -> Self: ... + # `UserDict.fromkeys` has the same semantics as `dict.fromkeys`, so should be kept in line with `dict.fromkeys`. - # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressable in the current type system. + # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload - def fromkeys(cls, iterable: Iterable[_T], value: None = ...) -> UserDict[_T, Any | None]: ... + def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> UserDict[_T, Any | None]: ... @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ... + @overload + def __or__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ... + @overload + def __or__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ... + @overload + def __ror__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + + # UserDict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + + if sys.version_info >= (3, 12): + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + class UserList(MutableSequence[_T]): data: list[_T] - def __init__(self, initlist: Iterable[_T] | None = ...) -> None: ... + + @overload + def __init__(self, initlist: None = None) -> None: ... + @overload + def __init__(self, initlist: Iterable[_T]) -> None: ... + + __hash__: ClassVar[None] # type: ignore[assignment] def __lt__(self, other: list[_T] | UserList[_T]) -> bool: ... def __le__(self, other: list[_T] | UserList[_T]) -> bool: ... def __gt__(self, other: list[_T] | UserList[_T]) -> bool: ... def __ge__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __eq__(self, other: object) -> bool: ... def __contains__(self, item: object) -> bool: ... def __len__(self) -> int: ... + @overload def __getitem__(self, i: SupportsIndex) -> _T: ... @overload - def __getitem__(self: Self, i: slice) -> Self: ... + def __getitem__(self, i: slice[SupportsIndex | None]) -> Self: ... + @overload - def __setitem__(self, i: SupportsIndex, o: _T) -> None: ... + def __setitem__(self, i: SupportsIndex, item: _T) -> None: ... @overload - def __setitem__(self, i: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: SupportsIndex | slice) -> None: ... - def __add__(self: _S, other: Iterable[_T]) -> _S: ... - def __iadd__(self: _S, other: Iterable[_T]) -> _S: ... - def __mul__(self: _S, n: int) -> _S: ... - def __imul__(self: _S, n: int) -> _S: ... + def __setitem__(self, i: slice[SupportsIndex | None], item: Iterable[_T]) -> None: ... + + def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None]) -> None: ... + def __add__(self, other: Iterable[_T]) -> Self: ... + def __radd__(self, other: Iterable[_T]) -> Self: ... + def __iadd__(self, other: Iterable[_T]) -> Self: ... + def __mul__(self, n: SupportsIndex) -> Self: ... + def __rmul__(self, n: SupportsIndex) -> Self: ... + def __imul__(self, n: SupportsIndex) -> Self: ... def append(self, item: _T) -> None: ... - def insert(self, i: int, item: _T) -> None: ... - def pop(self, i: int = ...) -> _T: ... + def insert(self, i: SupportsIndex, item: _T) -> None: ... + def pop(self, i: SupportsIndex = -1) -> _T: ... def remove(self, item: _T) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self) -> Self: ... + def __copy__(self) -> Self: ... def count(self, item: _T) -> int: ... - # All arguments are passed to `list.index` at runtime, so the signature should be kept in line with `list.index`. - def index(self, item: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... + # The runtime signature is "item, *args", and the arguments are then passed + # to `list.index`. In order to give more precise types, we pretend that the + # `item` argument is positional-only. + def index(self, item: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + # All arguments are passed to `list.sort` at runtime, so the signature should be kept in line with `list.sort`. @overload - def sort(self: UserList[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> None: ... + def sort(self: UserList[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... @overload - def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... - def extend(self, other: Iterable[_T]) -> None: ... + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... -_UserStringT = TypeVar("_UserStringT", bound=UserString) + def extend(self, other: Iterable[_T]) -> None: ... -class UserString(Sequence[str]): +class UserString(Sequence[UserString]): data: str def __init__(self, seq: object) -> None: ... def __int__(self) -> int: ... @@ -115,29 +182,32 @@ class UserString(Sequence[str]): def __le__(self, string: str | UserString) -> bool: ... def __gt__(self, string: str | UserString) -> bool: ... def __ge__(self, string: str | UserString) -> bool: ... + def __eq__(self, string: object) -> bool: ... + def __hash__(self) -> int: ... def __contains__(self, char: object) -> bool: ... def __len__(self) -> int: ... - # It should return a str to implement Sequence correctly, but it doesn't. - def __getitem__(self: _UserStringT, i: SupportsIndex | slice) -> _UserStringT: ... # type: ignore[override] - def __iter__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] - def __reversed__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] - def __add__(self: _UserStringT, other: object) -> _UserStringT: ... - def __mul__(self: _UserStringT, n: int) -> _UserStringT: ... - def __mod__(self: _UserStringT, args: Any) -> _UserStringT: ... - def capitalize(self: _UserStringT) -> _UserStringT: ... - def casefold(self: _UserStringT) -> _UserStringT: ... - def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... - def count(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... - if sys.version_info >= (3, 8): - def encode(self: UserString, encoding: str | None = ..., errors: str | None = ...) -> bytes: ... - else: - def encode(self: _UserStringT, encoding: str | None = ..., errors: str | None = ...) -> _UserStringT: ... - def endswith(self, suffix: str | Tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... - def find(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... + def __getitem__(self, index: SupportsIndex | slice[SupportsIndex | None]) -> Self: ... + def __iter__(self) -> Iterator[Self]: ... + def __reversed__(self) -> Iterator[Self]: ... + def __add__(self, other: object) -> Self: ... + def __radd__(self, other: object) -> Self: ... + def __mul__(self, n: SupportsIndex) -> Self: ... + def __rmul__(self, n: SupportsIndex) -> Self: ... + def __mod__(self, args: Any) -> Self: ... + def __rmod__(self, template: object) -> Self: ... + def capitalize(self) -> Self: ... + def casefold(self) -> Self: ... + def center(self, width: SupportsIndex, *args: Any) -> Self: ... + def count(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... + def encode(self: UserString, encoding: str | None = "utf-8", errors: str | None = "strict") -> bytes: ... + def endswith( + self, suffix: str | tuple[str, ...], start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize + ) -> bool: ... + def expandtabs(self, tabsize: SupportsIndex = 8) -> Self: ... + def find(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... def format(self, *args: Any, **kwds: Any) -> str: ... def format_map(self, mapping: Mapping[str, Any]) -> str: ... - def index(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def index(self, sub: str, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... def isalpha(self) -> bool: ... def isalnum(self) -> bool: ... def isdecimal(self) -> bool: ... @@ -149,189 +219,351 @@ class UserString(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... + def isascii(self) -> bool: ... def join(self, seq: Iterable[str]) -> str: ... - def ljust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... - def lower(self: _UserStringT) -> _UserStringT: ... - def lstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... - @staticmethod - @overload - def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... - @staticmethod - @overload - def maketrans(x: str, y: str, z: str = ...) -> dict[int, int | None]: ... + def ljust(self, width: SupportsIndex, *args: Any) -> Self: ... + def lower(self) -> Self: ... + def lstrip(self, chars: str | None = None) -> Self: ... + maketrans = str.maketrans def partition(self, sep: str) -> tuple[str, str, str]: ... - if sys.version_info >= (3, 9): - def removeprefix(self: _UserStringT, __prefix: str | UserString) -> _UserStringT: ... - def removesuffix(self: _UserStringT, __suffix: str | UserString) -> _UserStringT: ... - def replace(self: _UserStringT, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> _UserStringT: ... - def rfind(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def removeprefix(self, prefix: str | UserString, /) -> Self: ... + def removesuffix(self, suffix: str | UserString, /) -> Self: ... + def replace(self, old: str | UserString, new: str | UserString, maxsplit: SupportsIndex = -1) -> Self: ... + def rfind(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... + def rindex(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... + def rjust(self, width: SupportsIndex, *args: Any) -> Self: ... def rpartition(self, sep: str) -> tuple[str, str, str]: ... - def rstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... - def split(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... - def splitlines(self, keepends: bool = ...) -> list[str]: ... - def startswith(self, prefix: str | Tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... - def swapcase(self: _UserStringT) -> _UserStringT: ... - def title(self: _UserStringT) -> _UserStringT: ... - def translate(self: _UserStringT, *args: Any) -> _UserStringT: ... - def upper(self: _UserStringT) -> _UserStringT: ... - def zfill(self: _UserStringT, width: int) -> _UserStringT: ... - -class deque(MutableSequence[_T], Generic[_T]): + def rstrip(self, chars: str | None = None) -> Self: ... + def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... + def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... + def splitlines(self, keepends: bool = False) -> list[str]: ... + def startswith( + self, prefix: str | tuple[str, ...], start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize + ) -> bool: ... + def strip(self, chars: str | None = None) -> Self: ... + def swapcase(self) -> Self: ... + def title(self) -> Self: ... + def translate(self, *args: Any) -> Self: ... + def upper(self) -> Self: ... + def zfill(self, width: SupportsIndex) -> Self: ... + +@disjoint_base +class deque(MutableSequence[_T]): @property def maxlen(self) -> int | None: ... - def __init__(self, iterable: Iterable[_T] = ..., maxlen: int | None = ...) -> None: ... - def append(self, __x: _T) -> None: ... - def appendleft(self, __x: _T) -> None: ... - def copy(self: _S) -> _S: ... - def count(self, __x: _T) -> int: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def extendleft(self, __iterable: Iterable[_T]) -> None: ... - def insert(self, __i: int, __x: _T) -> None: ... - def index(self, __x: _T, __start: int = ..., __stop: int = ...) -> int: ... + + @overload + def __init__(self, *, maxlen: int | None = None) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ... + + def append(self, x: _T, /) -> None: ... + def appendleft(self, x: _T, /) -> None: ... + def copy(self) -> Self: ... + def count(self, x: _T, /) -> int: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def extendleft(self, iterable: Iterable[_T], /) -> None: ... + def insert(self, i: SupportsIndex, x: _T, /) -> None: ... + def index(self, x: _T, start: SupportsIndex = 0, stop: SupportsIndex = ..., /) -> int: ... def pop(self) -> _T: ... # type: ignore[override] def popleft(self) -> _T: ... - def remove(self, __value: _T) -> None: ... - def rotate(self, __n: int = ...) -> None: ... - def __copy__(self: _S) -> _S: ... + def remove(self, value: _T, /) -> None: ... + def rotate(self, n: SupportsIndex = 1, /) -> None: ... + def __copy__(self) -> Self: ... def __len__(self) -> int: ... - def __str__(self) -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores - def __getitem__(self, __index: SupportsIndex) -> _T: ... # type: ignore[override] - def __setitem__(self, __i: SupportsIndex, __x: _T) -> None: ... # type: ignore[override] - def __delitem__(self, __i: SupportsIndex) -> None: ... # type: ignore[override] - def __contains__(self, __o: object) -> bool: ... - def __reduce__(self: Self) -> tuple[Type[Self], tuple[()], None, Iterator[_T]]: ... - def __iadd__(self: _S, __iterable: Iterable[_T]) -> _S: ... - def __add__(self: _S, __other: _S) -> _S: ... - def __mul__(self: _S, __other: int) -> _S: ... - def __imul__(self: _S, __other: int) -> _S: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... - -class Counter(Dict[_T, int], Generic[_T]): - @overload - def __init__(self, __iterable: None = ..., **kwargs: int) -> None: ... - @overload - def __init__(self, __mapping: SupportsKeysAndGetItem[_T, int]) -> None: ... - @overload - def __init__(self, __iterable: Iterable[_T]) -> None: ... - def copy(self: Self) -> Self: ... - def elements(self) -> Iterator[_T]: ... - def most_common(self, n: int | None = ...) -> list[tuple[_T, int]]: ... - @classmethod - def fromkeys(cls, iterable: Any, v: int | None = ...) -> NoReturn: ... # type: ignore[override] + def __getitem__(self, key: SupportsIndex, /) -> _T: ... # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... # type: ignore[override] + def __delitem__(self, key: SupportsIndex, /) -> None: ... # type: ignore[override] + def __contains__(self, key: object, /) -> bool: ... + def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... + def __iadd__(self, value: Iterable[_T], /) -> Self: ... + def __add__(self, value: Self, /) -> Self: ... + def __mul__(self, value: SupportsIndex, /) -> Self: ... + def __rmul__(self, value: SupportsIndex, /) -> Self: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __lt__(self, value: deque[_T], /) -> bool: ... + def __le__(self, value: deque[_T], /) -> bool: ... + def __gt__(self, value: deque[_T], /) -> bool: ... + def __ge__(self, value: deque[_T], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class Counter(dict[_T, int], Generic[_T]): @overload - def subtract(self, __iterable: None = ...) -> None: ... + def __init__(self, iterable: None = None, /) -> None: ... @overload - def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + def __init__(self: Counter[str], iterable: None = None, /, **kwargs: int) -> None: ... @overload - def subtract(self, __iterable: Iterable[_T]) -> None: ... - # The Iterable[Tuple[...]] argument type is not actually desirable - # (the tuples will be added as keys, breaking type safety) but - # it's included so that the signature is compatible with - # Dict.update. Not sure if we should use '# type: ignore' instead - # and omit the type from the union. + def __init__(self, mapping: SupportsKeysAndGetItem[_T, int], /) -> None: ... @overload - def update(self, __m: SupportsKeysAndGetItem[_T, int], **kwargs: int) -> None: ... + def __init__(self, iterable: Iterable[_T], /) -> None: ... + + def copy(self) -> Self: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... + @classmethod + def fromkeys(cls, iterable: Any, v: int | None = None) -> Never: ... # type: ignore[override] + + @overload + def subtract(self, iterable: None = None, /) -> None: ... @overload - def update(self, __m: Iterable[_T] | Iterable[tuple[_T, int]], **kwargs: int) -> None: ... + def subtract(self, mapping: Mapping[_T, int], /) -> None: ... @overload - def update(self, __m: None = ..., **kwargs: int) -> None: ... - def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def subtract(self, iterable: Iterable[_T], /) -> None: ... + + # Unlike dict.update(), use Mapping instead of SupportsKeysAndGetItem for the first overload + # (source code does an `isinstance(other, Mapping)` check) + # + # The second overload is also deliberately different to dict.update() + # (if it were `Iterable[_T] | Iterable[tuple[_T, int]]`, + # the tuples would be added as keys, breaking type safety) + @overload # type: ignore[override] + def update(self, m: Mapping[_T, int], /, **kwargs: int) -> None: ... + @overload + def update(self, iterable: Iterable[_T], /, **kwargs: int) -> None: ... + @overload + def update(self, iterable: None = None, /, **kwargs: int) -> None: ... + + def total(self) -> int: ... + def __missing__(self, key: _T) -> int: ... + def __delitem__(self, elem: object) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __le__(self, other: Counter[Any]) -> bool: ... + def __lt__(self, other: Counter[Any]) -> bool: ... + def __ge__(self, other: Counter[Any]) -> bool: ... + def __gt__(self, other: Counter[Any]) -> bool: ... + def __add__(self, other: Counter[_S]) -> Counter[_T | _S]: ... def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... def __and__(self, other: Counter[_T]) -> Counter[_T]: ... - def __or__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore[override] + def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] + if sys.version_info >= (3, 15): + def __xor__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] + def __pos__(self) -> Counter[_T]: ... def __neg__(self) -> Counter[_T]: ... - def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... - def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... - def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... - def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore[override] - if sys.version_info >= (3, 10): - def total(self) -> int: ... + # several type: ignores because __iadd__ is supposedly incompatible with __add__, etc. + def __iadd__(self, other: SupportsItems[_T, int]) -> Self: ... # type: ignore[misc] + def __isub__(self, other: SupportsItems[_T, int]) -> Self: ... + def __iand__(self, other: SupportsItems[_T, int]) -> Self: ... + def __ior__(self, other: SupportsItems[_T, int]) -> Self: ... # type: ignore[override,misc] + if sys.version_info >= (3, 15): + def __ixor__(self, other: Counter[_T]) -> Self: ... # type: ignore[misc] + +# The pure-Python implementations of the "views" classes +# These are exposed at runtime in `collections/__init__.py` +class _OrderedDictKeysView(KeysView[_KT_co]): + def __reversed__(self) -> Iterator[_KT_co]: ... + +class _OrderedDictItemsView(ItemsView[_KT_co, _VT_co]): + def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... +class _OrderedDictValuesView(ValuesView[_VT_co]): + def __reversed__(self) -> Iterator[_VT_co]: ... + +# The C implementations of the "views" classes +# (At runtime, these are called `odict_keys`, `odict_items` and `odict_values`, +# but they are not exposed anywhere) +# pyright doesn't have a specific error code for subclassing error! @final -class _OrderedDictKeysView(dict_keys[_KT_co, _VT_co], Reversible[_KT_co]): # type: ignore[misc] +@type_check_only +class _odict_keys(dict_keys[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] def __reversed__(self) -> Iterator[_KT_co]: ... @final -class _OrderedDictItemsView(dict_items[_KT_co, _VT_co], Reversible[Tuple[_KT_co, _VT_co]]): # type: ignore[misc] +@type_check_only +class _odict_items(dict_items[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... @final -class _OrderedDictValuesView(dict_values[_KT_co, _VT_co], Reversible[_VT_co], Generic[_KT_co, _VT_co]): # type: ignore[misc] +@type_check_only +class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] def __reversed__(self) -> Iterator[_VT_co]: ... -class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): - def popitem(self, last: bool = ...) -> tuple[_KT, _VT]: ... - def move_to_end(self, key: _KT, last: bool = ...) -> None: ... - def copy(self: Self) -> Self: ... +@disjoint_base +class OrderedDict(dict[_KT, _VT]): + def popitem(self, last: bool = True) -> tuple[_KT, _VT]: ... + def move_to_end(self, key: _KT, last: bool = True) -> None: ... + def copy(self) -> Self: ... def __reversed__(self) -> Iterator[_KT]: ... - def keys(self) -> _OrderedDictKeysView[_KT, _VT]: ... - def items(self) -> _OrderedDictItemsView[_KT, _VT]: ... - def values(self) -> _OrderedDictValuesView[_KT, _VT]: ... - # `fromkeys` is actually inherited from `dict` at runtime, so the signature should be kept in line with `dict.fromkeys`. - # Ideally we would not redefine it here, but the true signature of `dict.fromkeys` is not expressable in the current type system. + def keys(self) -> _odict_keys[_KT, _VT]: ... + def items(self) -> _odict_items[_KT, _VT]: ... + def values(self) -> _odict_values[_KT, _VT]: ... + + # The signature of OrderedDict.fromkeys should be kept in line with `dict.fromkeys`, modulo positional-only differences. + # Like dict.fromkeys, its true signature is not expressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> OrderedDict[_T, Any | None]: ... + def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> OrderedDict[_T, _S]: ... + def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ... + + # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. + @overload + def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + # Same as dict.pop, but accepts keyword arguments + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + def __eq__(self, value: object, /) -> bool: ... -class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): + if sys.version_info >= (3, 15): + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[override] + def __ror__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> Self: ... # type: ignore[override,misc] + @overload + def __ror__( # type: ignore[misc] + self, value: dict[_T1, _T2] | frozendict[_T1, _T2], / + ) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + else: + @overload + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + +@disjoint_base +class defaultdict(dict[_KT, _VT]): default_factory: Callable[[], _VT] | None + @overload - def __init__(self, **kwargs: _VT) -> None: ... + def __init__(self) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None) -> None: ... + def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 @overload - def __init__(self, __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + def __init__( + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload def __init__( - self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + map: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, ) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload def __init__( - self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, ) -> None: ... - def __missing__(self, __key: _KT) -> _VT: ... - def __copy__(self: _S) -> _S: ... - def copy(self: _S) -> _S: ... -class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + def __missing__(self, key: _KT, /) -> _VT: ... + def __copy__(self) -> Self: ... + def copy(self) -> Self: ... + + # defaultdict rejects frozendict in its direct __or__/__ror__ methods, even though dict accepts it. + # See https://github.com/python/cpython/issues/149534. + @overload # type: ignore[override] + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[override] + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + +class ChainMap(MutableMapping[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] def __init__(self, *maps: MutableMapping[_KT, _VT]) -> None: ... - def new_child(self: Self, m: MutableMapping[_KT, _VT] | None = ...) -> Self: ... + def new_child(self, m: MutableMapping[_KT, _VT] | None = None) -> Self: ... @property - def parents(self: Self) -> Self: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __getitem__(self, k: _KT) -> _VT: ... + def parents(self) -> Self: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... + def __contains__(self, key: object) -> bool: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + def __missing__(self, key: _KT) -> _VT: ... # undocumented - def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + def __bool__(self) -> bool: ... + + # Keep ChainMap.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. + @overload + def setdefault(self: ChainMap[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + @overload def pop(self, key: _KT) -> _VT: ... @overload - def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... - def copy(self: Self) -> Self: ... - # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, so the signature should be kept in line with `dict.fromkeys`. + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + def copy(self) -> Self: ... + __copy__ = copy + # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, + # so the signature should be kept in line with `dict.fromkeys`. + if sys.version_info >= (3, 13): + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], /) -> ChainMap[_T, Any | None]: ... + else: + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: ... + @classmethod @overload - def fromkeys(cls, iterable: Iterable[_T], __value: None = ...) -> ChainMap[_T, Any | None]: ... + # Special-case None: the user probably wants to add non-None values later. + def fromkeys(cls, iterable: Iterable[_T], value: None, /) -> ChainMap[_T, Any | None]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> ChainMap[_T, _S]: ... + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ... + + @overload + def __or__(self, other: Mapping[_KT, _VT]) -> Self: ... + @overload + def __or__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, other: Mapping[_KT, _VT]) -> Self: ... + @overload + def __ror__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + + # ChainMap.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... diff --git a/stdlib/colorsys.pyi b/stdlib/colorsys.pyi index 00c5f9d22cb1..d4edab12ecc7 100644 --- a/stdlib/colorsys.pyi +++ b/stdlib/colorsys.pyi @@ -1,3 +1,7 @@ +from typing import Final + +__all__ = ["rgb_to_yiq", "yiq_to_rgb", "rgb_to_hls", "hls_to_rgb", "rgb_to_hsv", "hsv_to_rgb"] + def rgb_to_yiq(r: float, g: float, b: float) -> tuple[float, float, float]: ... def yiq_to_rgb(y: float, i: float, q: float) -> tuple[float, float, float]: ... def rgb_to_hls(r: float, g: float, b: float) -> tuple[float, float, float]: ... @@ -5,7 +9,7 @@ def hls_to_rgb(h: float, l: float, s: float) -> tuple[float, float, float]: ... def rgb_to_hsv(r: float, g: float, b: float) -> tuple[float, float, float]: ... def hsv_to_rgb(h: float, s: float, v: float) -> tuple[float, float, float]: ... -# TODO undocumented -ONE_SIXTH: float -ONE_THIRD: float -TWO_THIRD: float +# undocumented +ONE_SIXTH: Final[float] +ONE_THIRD: Final[float] +TWO_THIRD: Final[float] diff --git a/stdlib/compileall.pyi b/stdlib/compileall.pyi index 64b4dc2bc5f7..49a4c69dd3fb 100644 --- a/stdlib/compileall.pyi +++ b/stdlib/compileall.pyi @@ -1,110 +1,51 @@ -import sys from _typeshed import StrPath -from typing import Any, Protocol +from py_compile import PycInvalidationMode +from typing import Any, Protocol, type_check_only -if sys.version_info >= (3, 7): - from py_compile import PycInvalidationMode +__all__ = ["compile_dir", "compile_file", "compile_path"] +@type_check_only class _SupportsSearch(Protocol): - def search(self, string: str) -> Any: ... + def search(self, string: str, /) -> Any: ... -if sys.version_info >= (3, 9): - def compile_dir( - dir: StrPath, - maxlevels: int | None = ..., - ddir: StrPath | None = ..., - force: bool = ..., - rx: _SupportsSearch | None = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - workers: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - *, - stripdir: str | None = ..., # TODO: change to StrPath | None once https://bugs.python.org/issue40447 is resolved - prependdir: StrPath | None = ..., - limit_sl_dest: StrPath | None = ..., - hardlink_dupes: bool = ..., - ) -> int: ... - def compile_file( - fullname: StrPath, - ddir: StrPath | None = ..., - force: bool = ..., - rx: _SupportsSearch | None = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - *, - stripdir: str | None = ..., # TODO: change to StrPath | None once https://bugs.python.org/issue40447 is resolved - prependdir: StrPath | None = ..., - limit_sl_dest: StrPath | None = ..., - hardlink_dupes: bool = ..., - ) -> int: ... - -elif sys.version_info >= (3, 7): - def compile_dir( - dir: StrPath, - maxlevels: int = ..., - ddir: StrPath | None = ..., - force: bool = ..., - rx: _SupportsSearch | None = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - workers: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - ) -> int: ... - def compile_file( - fullname: StrPath, - ddir: StrPath | None = ..., - force: bool = ..., - rx: _SupportsSearch | None = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - ) -> int: ... - -else: - def compile_dir( - dir: StrPath, - maxlevels: int = ..., - ddir: StrPath | None = ..., - force: bool = ..., - rx: _SupportsSearch | None = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - workers: int = ..., - ) -> int: ... - def compile_file( - fullname: StrPath, - ddir: StrPath | None = ..., - force: bool = ..., - rx: _SupportsSearch | None = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - ) -> int: ... - -if sys.version_info >= (3, 7): - def compile_path( - skip_curdir: bool = ..., - maxlevels: int = ..., - force: bool = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - ) -> int: ... - -else: - def compile_path( - skip_curdir: bool = ..., - maxlevels: int = ..., - force: bool = ..., - quiet: int = ..., - legacy: bool = ..., - optimize: int = ..., - ) -> int: ... +def compile_dir( + dir: StrPath, + maxlevels: int | None = None, + ddir: StrPath | None = None, + force: bool = False, + rx: _SupportsSearch | None = None, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + workers: int = 1, + invalidation_mode: PycInvalidationMode | None = None, + *, + stripdir: StrPath | None = None, + prependdir: StrPath | None = None, + limit_sl_dest: StrPath | None = None, + hardlink_dupes: bool = False, +) -> bool: ... +def compile_file( + fullname: StrPath, + ddir: StrPath | None = None, + force: bool = False, + rx: _SupportsSearch | None = None, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, + *, + stripdir: StrPath | None = None, + prependdir: StrPath | None = None, + limit_sl_dest: StrPath | None = None, + hardlink_dupes: bool = False, +) -> bool: ... +def compile_path( + skip_curdir: bool = ..., + maxlevels: int = 0, + force: bool = False, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, +) -> bool: ... diff --git a/stdlib/@python2/distutils/__init__.pyi b/stdlib/compression/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/__init__.pyi rename to stdlib/compression/__init__.pyi diff --git a/stdlib/@python2/distutils/command/__init__.pyi b/stdlib/compression/_common/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/__init__.pyi rename to stdlib/compression/_common/__init__.pyi diff --git a/stdlib/compression/_common/_streams.pyi b/stdlib/compression/_common/_streams.pyi new file mode 100644 index 000000000000..96aec24d1c2d --- /dev/null +++ b/stdlib/compression/_common/_streams.pyi @@ -0,0 +1,37 @@ +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase +from typing import Any, Protocol, type_check_only + +BUFFER_SIZE = DEFAULT_BUFFER_SIZE + +@type_check_only +class _Reader(Protocol): + def read(self, n: int, /) -> bytes: ... + def seekable(self) -> bool: ... + def seek(self, n: int, /) -> Any: ... + +@type_check_only +class _Decompressor(Protocol): + def decompress(self, data: ReadableBuffer, /, max_length: int = ...) -> bytes: ... + @property + def unused_data(self) -> bytes: ... + @property + def eof(self) -> bool: ... + # `zlib._Decompress` does not have next property, but `DecompressReader` calls it: + # @property + # def needs_input(self) -> bool: ... + +class BaseStream(BufferedIOBase): ... + +class DecompressReader(RawIOBase): + def __init__( + self, + fp: _Reader, + decomp_factory: Callable[..., _Decompressor], # Consider backporting changes to _compression + trailing_error: type[Exception] | tuple[type[Exception], ...] = (), + **decomp_args: Any, # These are passed to decomp_factory. + ) -> None: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... diff --git a/stdlib/compression/bz2.pyi b/stdlib/compression/bz2.pyi new file mode 100644 index 000000000000..9ddc39f27c28 --- /dev/null +++ b/stdlib/compression/bz2.pyi @@ -0,0 +1 @@ +from bz2 import * diff --git a/stdlib/compression/gzip.pyi b/stdlib/compression/gzip.pyi new file mode 100644 index 000000000000..9422a735c590 --- /dev/null +++ b/stdlib/compression/gzip.pyi @@ -0,0 +1 @@ +from gzip import * diff --git a/stdlib/compression/lzma.pyi b/stdlib/compression/lzma.pyi new file mode 100644 index 000000000000..936c3813db4f --- /dev/null +++ b/stdlib/compression/lzma.pyi @@ -0,0 +1 @@ +from lzma import * diff --git a/stdlib/compression/zlib.pyi b/stdlib/compression/zlib.pyi new file mode 100644 index 000000000000..78d176c03ee8 --- /dev/null +++ b/stdlib/compression/zlib.pyi @@ -0,0 +1 @@ +from zlib import * diff --git a/stdlib/compression/zstd/__init__.pyi b/stdlib/compression/zstd/__init__.pyi new file mode 100644 index 000000000000..8673c59a41c2 --- /dev/null +++ b/stdlib/compression/zstd/__init__.pyi @@ -0,0 +1,94 @@ +import enum +from _typeshed import ReadableBuffer +from collections.abc import Iterable, Mapping +from compression.zstd._zstdfile import ZstdFile, open +from typing import Final, final + +import _zstd +from _zstd import ZstdCompressor, ZstdDecompressor, ZstdDict, ZstdError, get_frame_size, zstd_version + +__all__ = ( + # compression.zstd + "COMPRESSION_LEVEL_DEFAULT", + "compress", + "CompressionParameter", + "decompress", + "DecompressionParameter", + "finalize_dict", + "get_frame_info", + "Strategy", + "train_dict", + # compression.zstd._zstdfile + "open", + "ZstdFile", + # _zstd + "get_frame_size", + "zstd_version", + "zstd_version_info", + "ZstdCompressor", + "ZstdDecompressor", + "ZstdDict", + "ZstdError", +) + +zstd_version_info: Final[tuple[int, int, int]] +COMPRESSION_LEVEL_DEFAULT: Final = _zstd.ZSTD_CLEVEL_DEFAULT + +class FrameInfo: + __slots__ = ("decompressed_size", "dictionary_id") + decompressed_size: int + dictionary_id: int + def __init__(self, decompressed_size: int, dictionary_id: int) -> None: ... + +def get_frame_info(frame_buffer: ReadableBuffer) -> FrameInfo: ... +def train_dict(samples: Iterable[ReadableBuffer], dict_size: int) -> ZstdDict: ... +def finalize_dict(zstd_dict: ZstdDict, /, samples: Iterable[ReadableBuffer], dict_size: int, level: int) -> ZstdDict: ... +def compress( + data: ReadableBuffer, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, +) -> bytes: ... +def decompress( + data: ReadableBuffer, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None +) -> bytes: ... + +@final +class CompressionParameter(enum.IntEnum): + compression_level = _zstd.ZSTD_c_compressionLevel + window_log = _zstd.ZSTD_c_windowLog + hash_log = _zstd.ZSTD_c_hashLog + chain_log = _zstd.ZSTD_c_chainLog + search_log = _zstd.ZSTD_c_searchLog + min_match = _zstd.ZSTD_c_minMatch + target_length = _zstd.ZSTD_c_targetLength + strategy = _zstd.ZSTD_c_strategy + enable_long_distance_matching = _zstd.ZSTD_c_enableLongDistanceMatching + ldm_hash_log = _zstd.ZSTD_c_ldmHashLog + ldm_min_match = _zstd.ZSTD_c_ldmMinMatch + ldm_bucket_size_log = _zstd.ZSTD_c_ldmBucketSizeLog + ldm_hash_rate_log = _zstd.ZSTD_c_ldmHashRateLog + content_size_flag = _zstd.ZSTD_c_contentSizeFlag + checksum_flag = _zstd.ZSTD_c_checksumFlag + dict_id_flag = _zstd.ZSTD_c_dictIDFlag + nb_workers = _zstd.ZSTD_c_nbWorkers + job_size = _zstd.ZSTD_c_jobSize + overlap_log = _zstd.ZSTD_c_overlapLog + def bounds(self) -> tuple[int, int]: ... + +@final +class DecompressionParameter(enum.IntEnum): + window_log_max = _zstd.ZSTD_d_windowLogMax + def bounds(self) -> tuple[int, int]: ... + +@final +class Strategy(enum.IntEnum): + fast = _zstd.ZSTD_fast + dfast = _zstd.ZSTD_dfast + greedy = _zstd.ZSTD_greedy + lazy = _zstd.ZSTD_lazy + lazy2 = _zstd.ZSTD_lazy2 + btlazy2 = _zstd.ZSTD_btlazy2 + btopt = _zstd.ZSTD_btopt + btultra = _zstd.ZSTD_btultra + btultra2 = _zstd.ZSTD_btultra2 diff --git a/stdlib/compression/zstd/_zstdfile.pyi b/stdlib/compression/zstd/_zstdfile.pyi new file mode 100644 index 000000000000..b16b43c1da0a --- /dev/null +++ b/stdlib/compression/zstd/_zstdfile.pyi @@ -0,0 +1,117 @@ +from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsWrite, WriteableBuffer +from collections.abc import Mapping +from compression._common import _streams +from compression.zstd import ZstdDict +from io import TextIOWrapper, _WrappedBuffer +from typing import Literal, Protocol, TypeAlias, overload, type_check_only + +from _zstd import ZstdCompressor, _ZstdCompressorFlushBlock, _ZstdCompressorFlushFrame + +__all__ = ("ZstdFile", "open") + +_ReadBinaryMode: TypeAlias = Literal["r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_ReadTextMode: TypeAlias = Literal["rt"] +_WriteTextMode: TypeAlias = Literal["wt", "xt", "at"] + +@type_check_only +class _FileBinaryRead(_streams._Reader, Protocol): + def close(self) -> None: ... + +@type_check_only +class _FileBinaryWrite(SupportsWrite[bytes], Protocol): + def close(self) -> None: ... + +class ZstdFile(_streams.BaseStream): + FLUSH_BLOCK = ZstdCompressor.FLUSH_BLOCK + FLUSH_FRAME = ZstdCompressor.FLUSH_FRAME + + @overload + def __init__( + self, + file: StrOrBytesPath | _FileBinaryRead, + /, + mode: _ReadBinaryMode = "r", + *, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> None: ... + @overload + def __init__( + self, + file: StrOrBytesPath | _FileBinaryWrite, + /, + mode: _WriteBinaryMode, + *, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> None: ... + + def write(self, data: ReadableBuffer, /) -> int: ... + def flush(self, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 1) -> bytes: ... # type: ignore[override] + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int | None = -1) -> bytes: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... + def readline(self, size: int | None = -1) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def peek(self, size: int = -1) -> bytes: ... + @property + def name(self) -> str | bytes: ... + @property + def mode(self) -> Literal["rb", "wb"]: ... + +@overload +def open( + file: StrOrBytesPath | _FileBinaryRead, + /, + mode: _ReadBinaryMode = "rb", + *, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> ZstdFile: ... +@overload +def open( + file: StrOrBytesPath | _FileBinaryWrite, + /, + mode: _WriteBinaryMode, + *, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> ZstdFile: ... +@overload +def open( + file: StrOrBytesPath | _WrappedBuffer, + /, + mode: _ReadTextMode, + *, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + file: StrOrBytesPath | _WrappedBuffer, + /, + mode: _WriteTextMode, + *, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... diff --git a/stdlib/concurrent/futures/__init__.pyi b/stdlib/concurrent/futures/__init__.pyi index f3b54e54228c..ad4d20ea5445 100644 --- a/stdlib/concurrent/futures/__init__.pyi +++ b/stdlib/concurrent/futures/__init__.pyi @@ -4,9 +4,11 @@ from ._base import ( ALL_COMPLETED as ALL_COMPLETED, FIRST_COMPLETED as FIRST_COMPLETED, FIRST_EXCEPTION as FIRST_EXCEPTION, + BrokenExecutor as BrokenExecutor, CancelledError as CancelledError, Executor as Executor, Future as Future, + InvalidStateError as InvalidStateError, TimeoutError as TimeoutError, as_completed as as_completed, wait as wait, @@ -14,7 +16,56 @@ from ._base import ( from .process import ProcessPoolExecutor as ProcessPoolExecutor from .thread import ThreadPoolExecutor as ThreadPoolExecutor -if sys.version_info >= (3, 8): - from ._base import InvalidStateError as InvalidStateError -if sys.version_info >= (3, 7): - from ._base import BrokenExecutor as BrokenExecutor +if sys.version_info >= (3, 14): + from .interpreter import InterpreterPoolExecutor as InterpreterPoolExecutor + + __all__ = [ + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "InvalidStateError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + "InterpreterPoolExecutor", + ] + +elif sys.version_info >= (3, 13): + __all__ = ( + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "InvalidStateError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + ) +else: + __all__ = ( + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + ) + +def __dir__() -> tuple[str, ...]: ... diff --git a/stdlib/concurrent/futures/_base.pyi b/stdlib/concurrent/futures/_base.pyi index c1a44c997381..05680b5de461 100644 --- a/stdlib/concurrent/futures/_base.pyi +++ b/stdlib/concurrent/futures/_base.pyi @@ -1,124 +1,119 @@ import sys import threading -from _typeshed import Self -from abc import abstractmethod -from collections.abc import Container, Iterable, Iterator, Sequence +from _typeshed import Unused +from collections.abc import Callable, Iterable, Iterator from logging import Logger -from typing import Any, Callable, Generic, Protocol, Set, TypeVar, overload -from typing_extensions import SupportsIndex - -if sys.version_info >= (3, 9): - from types import GenericAlias - -FIRST_COMPLETED: str -FIRST_EXCEPTION: str -ALL_COMPLETED: str -PENDING: str -RUNNING: str -CANCELLED: str -CANCELLED_AND_NOTIFIED: str -FINISHED: str -_FUTURE_STATES: list[str] -_STATE_TO_DESCRIPTION_MAP: dict[str, str] +from types import GenericAlias, TracebackType +from typing import Any, Final, Generic, NamedTuple, ParamSpec, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +FIRST_COMPLETED: Final = "FIRST_COMPLETED" +FIRST_EXCEPTION: Final = "FIRST_EXCEPTION" +ALL_COMPLETED: Final = "ALL_COMPLETED" +PENDING: Final = "PENDING" +RUNNING: Final = "RUNNING" +CANCELLED: Final = "CANCELLED" +CANCELLED_AND_NOTIFIED: Final = "CANCELLED_AND_NOTIFIED" +FINISHED: Final = "FINISHED" +_STATE_TO_DESCRIPTION_MAP: Final[dict[str, str]] LOGGER: Logger class Error(Exception): ... class CancelledError(Error): ... -class TimeoutError(Error): ... -if sys.version_info >= (3, 8): - class InvalidStateError(Error): ... +if sys.version_info >= (3, 11): + from builtins import TimeoutError as TimeoutError +else: + class TimeoutError(Error): ... -if sys.version_info >= (3, 7): - class BrokenExecutor(RuntimeError): ... +class InvalidStateError(Error): ... +class BrokenExecutor(RuntimeError): ... _T = TypeVar("_T") - _T_co = TypeVar("_T_co", covariant=True) - -# Copied over Collection implementation as it does not exist in Python 2 and <3.6. -# Also to solve pytype issues with _Collection. -class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... +_P = ParamSpec("_P") class Future(Generic[_T]): - def __init__(self) -> None: ... + _condition: threading.Condition + _state: str + _result: _T | None + _exception: BaseException | None + _waiters: list[_Waiter] def cancel(self) -> bool: ... def cancelled(self) -> bool: ... def running(self) -> bool: ... def done(self) -> bool: ... - def add_done_callback(self, fn: Callable[[Future[_T]], Any]) -> None: ... - def result(self, timeout: float | None = ...) -> _T: ... + def add_done_callback(self, fn: Callable[[Future[_T]], object]) -> None: ... + def result(self, timeout: float | None = None) -> _T: ... def set_running_or_notify_cancel(self) -> bool: ... def set_result(self, result: _T) -> None: ... - def exception(self, timeout: float | None = ...) -> BaseException | None: ... + def exception(self, timeout: float | None = None) -> BaseException | None: ... def set_exception(self, exception: BaseException | None) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Executor: - if sys.version_info >= (3, 9): - def submit(self, __fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... + if sys.version_info >= (3, 14): + def map( + self, + fn: Callable[..., _T], + *iterables: Iterable[Any], + timeout: float | None = None, + chunksize: int = 1, + buffersize: int | None = None, + ) -> Iterator[_T]: ... else: - def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... - def map( - self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = ..., chunksize: int = ... - ) -> Iterator[_T]: ... - if sys.version_info >= (3, 9): - def shutdown(self, wait: bool = ..., *, cancel_futures: bool = ...) -> None: ... - else: - def shutdown(self, wait: bool = ...) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool | None: ... - -def as_completed(fs: Iterable[Future[_T]], timeout: float | None = ...) -> Iterator[Future[_T]]: ... - -# Ideally this would be a namedtuple, but mypy doesn't support generic tuple types. See #1976 -class DoneAndNotDoneFutures(Sequence[Set[Future[_T]]]): + def map( + self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = None, chunksize: int = 1 + ) -> Iterator[_T]: ... + + def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + +@type_check_only +class _AsCompletedFuture(Protocol[_T_co]): + # as_completed only mutates non-generic aspects of passed Futures and does not do any nominal + # checks. Therefore, we can use a Protocol here to allow as_completed to act covariantly. + # See the tests for concurrent.futures + _condition: threading.Condition + _state: str + _waiters: list[_Waiter] + # Not used by as_completed, but needed to propagate the generic type + def result(self, timeout: float | None = None) -> _T_co: ... + +def as_completed(fs: Iterable[_AsCompletedFuture[_T]], timeout: float | None = None) -> Iterator[Future[_T]]: ... + +class DoneAndNotDoneFutures(NamedTuple, Generic[_T]): done: set[Future[_T]] not_done: set[Future[_T]] - def __new__(_cls, done: set[Future[_T]], not_done: set[Future[_T]]) -> DoneAndNotDoneFutures[_T]: ... - def __len__(self) -> int: ... - @overload - def __getitem__(self, i: SupportsIndex) -> set[Future[_T]]: ... - @overload - def __getitem__(self, s: slice) -> DoneAndNotDoneFutures[_T]: ... -def wait(fs: Iterable[Future[_T]], timeout: float | None = ..., return_when: str = ...) -> DoneAndNotDoneFutures[_T]: ... +def wait( + fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" +) -> DoneAndNotDoneFutures[_T]: ... class _Waiter: event: threading.Event finished_futures: list[Future[Any]] - def __init__(self) -> None: ... def add_result(self, future: Future[Any]) -> None: ... def add_exception(self, future: Future[Any]) -> None: ... def add_cancelled(self, future: Future[Any]) -> None: ... class _AsCompletedWaiter(_Waiter): lock: threading.Lock - def __init__(self) -> None: ... - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... -class _FirstCompletedWaiter(_Waiter): - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... +class _FirstCompletedWaiter(_Waiter): ... class _AllCompletedWaiter(_Waiter): num_pending_calls: int stop_on_exception: bool lock: threading.Lock def __init__(self, num_pending_calls: int, stop_on_exception: bool) -> None: ... - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... class _AcquireFutures: futures: Iterable[Future[Any]] def __init__(self, futures: Iterable[Future[Any]]) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: Unused) -> None: ... diff --git a/stdlib/concurrent/futures/interpreter.pyi b/stdlib/concurrent/futures/interpreter.pyi new file mode 100644 index 000000000000..f6925806a5eb --- /dev/null +++ b/stdlib/concurrent/futures/interpreter.pyi @@ -0,0 +1,82 @@ +import sys +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Literal, ParamSpec, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, TypeVar, TypeVarTuple, Unpack + +_Task: TypeAlias = tuple[bytes, Literal["function", "script"]] +_Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") +_R = TypeVar("_R") + +@type_check_only +class _TaskFunc(Protocol): + @overload + def __call__(self, fn: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> tuple[bytes, Literal["function"]]: ... + @overload + def __call__(self, fn: str) -> tuple[bytes, Literal["script"]]: ... + +if sys.version_info >= (3, 14): + from concurrent.futures.thread import BrokenThreadPool, WorkerContext as ThreadWorkerContext + from concurrent.interpreters import Interpreter, Queue + + def do_call(results: Queue, func: Callable[..., _R], args: tuple[Any, ...], kwargs: dict[str, Any]) -> _R: ... + + class WorkerContext(ThreadWorkerContext): + interp: Interpreter | None + results: Queue | None + + @overload # type: ignore[override] + @classmethod + def prepare( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], Self], _TaskFunc]: ... + @overload + @classmethod + def prepare(cls, initializer: Callable[[], object], initargs: tuple[()]) -> tuple[Callable[[], Self], _TaskFunc]: ... + + def __init__(self, initdata: _Task) -> None: ... + def __del__(self) -> None: ... + def run(self, task: _Task) -> None: ... # type: ignore[override] + + class BrokenInterpreterPool(BrokenThreadPool): ... + + class InterpreterPoolExecutor(ThreadPoolExecutor): + BROKEN: type[BrokenInterpreterPool] + + @overload # type: ignore[override] + @classmethod + def prepare_context( + cls, initializer: Callable[[], object], initargs: tuple[()] + ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ... + @overload + @classmethod + def prepare_context( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ... + + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + thread_name_prefix: str, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... diff --git a/stdlib/concurrent/futures/process.pyi b/stdlib/concurrent/futures/process.pyi index cc48f48f0023..4dfe17afdc7f 100644 --- a/stdlib/concurrent/futures/process.pyi +++ b/stdlib/concurrent/futures/process.pyi @@ -1,60 +1,67 @@ import sys -from collections.abc import Generator, Iterable, Mapping, MutableMapping, MutableSequence +from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping, MutableSequence from multiprocessing.connection import Connection from multiprocessing.context import BaseContext, Process from multiprocessing.queues import Queue, SimpleQueue from threading import Lock, Semaphore, Thread from types import TracebackType -from typing import Any, Callable, Generic, Tuple, TypeVar +from typing import Any, Final, Generic, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack from weakref import ref -from ._base import Executor, Future +from ._base import BrokenExecutor, Executor, Future + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts") _threads_wakeups: MutableMapping[Any, Any] _global_shutdown: bool class _ThreadWakeup: _closed: bool - _reader: Connection - _writer: Connection - def __init__(self) -> None: ... + # Any: Unused send and recv methods + _reader: Connection[Any, Any] + _writer: Connection[Any, Any] def close(self) -> None: ... def wakeup(self) -> None: ... def clear(self) -> None: ... def _python_exit() -> None: ... -EXTRA_QUEUED_CALLS: int +EXTRA_QUEUED_CALLS: Final = 1 -_MAX_WINDOWS_WORKERS: int +_MAX_WINDOWS_WORKERS: Final = 61 class _RemoteTraceback(Exception): tb: str def __init__(self, tb: TracebackType) -> None: ... - def __str__(self) -> str: ... class _ExceptionWithTraceback: exc: BaseException tb: TracebackType def __init__(self, exc: BaseException, tb: TracebackType) -> None: ... - def __reduce__(self) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... def _rebuild_exc(exc: Exception, tb: str) -> Exception: ... -_S = TypeVar("_S") - -class _WorkItem(Generic[_S]): - future: Future[_S] - fn: Callable[..., _S] +class _WorkItem(Generic[_T]): + future: Future[_T] + fn: Callable[..., _T] args: Iterable[Any] kwargs: Mapping[str, Any] - def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... + def __init__(self, future: Future[_T], fn: Callable[..., _T], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... class _ResultItem: work_id: int exception: Exception result: Any - def __init__(self, work_id: int, exception: Exception | None = ..., result: Any | None = ...) -> None: ... + if sys.version_info >= (3, 11): + exit_pid: int | None + def __init__( + self, work_id: int, exception: Exception | None = None, result: Any | None = None, exit_pid: int | None = None + ) -> None: ... + else: + def __init__(self, work_id: int, exception: Exception | None = None, result: Any | None = None) -> None: ... class _CallItem: work_id: int @@ -63,65 +70,93 @@ class _CallItem: kwargs: Mapping[str, Any] def __init__(self, work_id: int, fn: Callable[..., Any], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... -if sys.version_info >= (3, 7): - class _SafeQueue(Queue[Future[Any]]): - pending_work_items: dict[int, _WorkItem[Any]] +class _SafeQueue(Queue[Future[Any]]): + pending_work_items: dict[int, _WorkItem[Any]] + if sys.version_info < (3, 12): shutdown_lock: Lock - thread_wakeup: _ThreadWakeup - if sys.version_info >= (3, 9): - def __init__( - self, - max_size: int | None = ..., - *, - ctx: BaseContext, - pending_work_items: dict[int, _WorkItem[Any]], - shutdown_lock: Lock, - thread_wakeup: _ThreadWakeup, - ) -> None: ... - else: - def __init__( - self, max_size: int | None = ..., *, ctx: BaseContext, pending_work_items: dict[int, _WorkItem[Any]] - ) -> None: ... - def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... - -def _get_chunks(*iterables: Any, chunksize: int) -> Generator[Tuple[Any, ...], None, None]: ... -def _process_chunk(fn: Callable[..., Any], chunk: tuple[Any, None, None]) -> Generator[Any, None, None]: ... -def _sendback_result( - result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = ..., exception: Exception | None = ... -) -> None: ... - -if sys.version_info >= (3, 7): + thread_wakeup: _ThreadWakeup + if sys.version_info >= (3, 12): + def __init__( + self, + max_size: int | None = 0, + *, + ctx: BaseContext, + pending_work_items: dict[int, _WorkItem[Any]], + thread_wakeup: _ThreadWakeup, + ) -> None: ... + else: + def __init__( + self, + max_size: int | None = 0, + *, + ctx: BaseContext, + pending_work_items: dict[int, _WorkItem[Any]], + shutdown_lock: Lock, + thread_wakeup: _ThreadWakeup, + ) -> None: ... + + def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... + +def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...]]: ... +def _process_chunk(fn: Callable[..., _T], chunk: Iterable[tuple[Any, ...]]) -> list[_T]: ... + +if sys.version_info >= (3, 11): + def _sendback_result( + result_queue: SimpleQueue[_WorkItem[Any]], + work_id: int, + result: Any | None = None, + exception: Exception | None = None, + exit_pid: int | None = None, + ) -> None: ... + +else: + def _sendback_result( + result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = None, exception: Exception | None = None + ) -> None: ... + +if sys.version_info >= (3, 11): def _process_worker( call_queue: Queue[_CallItem], result_queue: SimpleQueue[_ResultItem], - initializer: Callable[..., None] | None, - initargs: Tuple[Any, ...], + initializer: Callable[[Unpack[_Ts]], object] | None, + initargs: tuple[Unpack[_Ts]], + max_tasks: int | None = None, ) -> None: ... else: - def _process_worker(call_queue: Queue[_CallItem], result_queue: SimpleQueue[_ResultItem]) -> None: ... + def _process_worker( + call_queue: Queue[_CallItem], + result_queue: SimpleQueue[_ResultItem], + initializer: Callable[[Unpack[_Ts]], object] | None, + initargs: tuple[Unpack[_Ts]], + ) -> None: ... -if sys.version_info >= (3, 9): - class _ExecutorManagerThread(Thread): - thread_wakeup: _ThreadWakeup - shutdown_lock: Lock - executor_reference: ref[Any] - processes: MutableMapping[int, Process] - call_queue: Queue[_CallItem] - result_queue: SimpleQueue[_ResultItem] - work_ids_queue: Queue[int] - pending_work_items: dict[int, _WorkItem[Any]] - def __init__(self, executor: ProcessPoolExecutor) -> None: ... - def run(self) -> None: ... - def add_call_item_to_queue(self) -> None: ... - def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ... - def process_result_item(self, result_item: int | _ResultItem) -> None: ... - def is_shutting_down(self) -> bool: ... +class _ExecutorManagerThread(Thread): + thread_wakeup: _ThreadWakeup + shutdown_lock: Lock + executor_reference: ref[Any] + processes: MutableMapping[int, Process] + call_queue: Queue[_CallItem] + result_queue: SimpleQueue[_ResultItem] + work_ids_queue: Queue[int] + pending_work_items: dict[int, _WorkItem[Any]] + def __init__(self, executor: ProcessPoolExecutor) -> None: ... + def run(self) -> None: ... + def add_call_item_to_queue(self) -> None: ... + def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ... + def process_result_item(self, result_item: int | _ResultItem) -> None: ... + def is_shutting_down(self) -> bool: ... + + if sys.version_info >= (3, 14): + # bpe_message parameter added in 3.14.7 + def terminate_broken(self, cause: str, bpe_message: str | None = None) -> None: ... + else: def terminate_broken(self, cause: str) -> None: ... - def flag_executor_shutting_down(self) -> None: ... - def shutdown_workers(self) -> None: ... - def join_executor_internals(self) -> None: ... - def get_n_children_alive(self) -> int: ... + + def flag_executor_shutting_down(self) -> None: ... + def shutdown_workers(self) -> None: ... + def join_executor_internals(self) -> None: ... + def get_n_children_alive(self) -> int: ... _system_limits_checked: bool _system_limited: bool | None @@ -129,17 +164,12 @@ _system_limited: bool | None def _check_system_limits() -> None: ... def _chain_from_iterable_of_lists(iterable: Iterable[MutableSequence[Any]]) -> Any: ... -if sys.version_info >= (3, 7): - from ._base import BrokenExecutor - class BrokenProcessPool(BrokenExecutor): ... - -else: - class BrokenProcessPool(RuntimeError): ... +class BrokenProcessPool(BrokenExecutor): ... class ProcessPoolExecutor(Executor): - _mp_context: BaseContext | None = ... - _initializer: Callable[..., None] | None = ... - _initargs: Tuple[Any, ...] = ... + _mp_context: BaseContext | None + _initializer: Callable[..., None] | None + _initargs: tuple[Any, ...] _executor_manager_thread: _ThreadWakeup _processes: MutableMapping[int, Process] _shutdown_thread: bool @@ -152,16 +182,67 @@ class ProcessPoolExecutor(Executor): _executor_manager_thread_wakeup: _ThreadWakeup _result_queue: SimpleQueue[Any] _work_ids: Queue[Any] - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + *, + max_tasks_per_child: int | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + max_tasks_per_child: int | None = None, + ) -> None: ... + @overload def __init__( self, - max_workers: int | None = ..., - mp_context: BaseContext | None = ..., - initializer: Callable[..., None] | None = ..., - initargs: Tuple[Any, ...] = ..., + max_workers: int | None, + mp_context: BaseContext | None, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + *, + max_tasks_per_child: int | None = None, ) -> None: ... else: - def __init__(self, max_workers: int | None = ...) -> None: ... - if sys.version_info >= (3, 9): - def _start_executor_manager_thread(self) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + mp_context: BaseContext | None, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + + def _start_executor_manager_thread(self) -> None: ... def _adjust_process_count(self) -> None: ... + + if sys.version_info >= (3, 14): + def kill_workers(self) -> None: ... + def terminate_workers(self) -> None: ... diff --git a/stdlib/concurrent/futures/thread.pyi b/stdlib/concurrent/futures/thread.pyi index 5ad5b65d3bec..685bf1cfc104 100644 --- a/stdlib/concurrent/futures/thread.pyi +++ b/stdlib/concurrent/futures/thread.pyi @@ -1,11 +1,15 @@ import queue import sys -from collections.abc import Iterable, Mapping, Set # equivalent to typing.AbstractSet, not builtins.set +from collections.abc import Callable, Iterable, Mapping, Set as AbstractSet from threading import Lock, Semaphore, Thread -from typing import Any, Callable, Generic, Tuple, TypeVar +from types import GenericAlias +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack from weakref import ref -from ._base import Executor, Future +from ._base import BrokenExecutor, Executor, Future + +_Ts = TypeVarTuple("_Ts") _threads_queues: Mapping[Any, Any] _shutdown: bool @@ -13,60 +17,127 @@ _global_shutdown_lock: Lock def _python_exit() -> None: ... -if sys.version_info >= (3, 9): - from types import GenericAlias - _S = TypeVar("_S") -class _WorkItem(Generic[_S]): - future: Future[_S] - fn: Callable[..., _S] - args: Iterable[Any] - kwargs: Mapping[str, Any] - def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... - def run(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -if sys.version_info >= (3, 7): +_Task: TypeAlias = tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]] + +_C = TypeVar("_C", bound=Callable[..., object]) +_KT = TypeVar("_KT", bound=str) +_VT = TypeVar("_VT") + +@type_check_only +class _ResolveTaskFunc(Protocol): + def __call__( + self, func: _C, args: tuple[Unpack[_Ts]], kwargs: dict[_KT, _VT] + ) -> tuple[_C, tuple[Unpack[_Ts]], dict[_KT, _VT]]: ... + +if sys.version_info >= (3, 14): + class WorkerContext: + @overload + @classmethod + def prepare( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ... + @overload + @classmethod + def prepare( + cls, initializer: Callable[[], object], initargs: tuple[()] + ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ... + + @overload + def __init__(self, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]) -> None: ... + @overload + def __init__(self, initializer: Callable[[], object], initargs: tuple[()]) -> None: ... + + def initialize(self) -> None: ... + def finalize(self) -> None: ... + def run(self, task: _Task) -> None: ... + +if sys.version_info >= (3, 14): + class _WorkItem(Generic[_S]): + future: Future[Any] + task: _Task + def __init__(self, future: Future[Any], task: _Task) -> None: ... + def run(self, ctx: WorkerContext) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + def _worker(executor_reference: ref[Any], ctx: WorkerContext, work_queue: queue.SimpleQueue[Any]) -> None: ... + +else: + class _WorkItem(Generic[_S]): + future: Future[_S] + fn: Callable[..., _S] + args: Iterable[Any] + kwargs: Mapping[str, Any] + def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... + def run(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def _worker( executor_reference: ref[Any], work_queue: queue.SimpleQueue[Any], - initializer: Callable[..., None], - initargs: Tuple[Any, ...], + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], ) -> None: ... -else: - def _worker(executor_reference: ref[Any], work_queue: queue.Queue[Any]) -> None: ... - -if sys.version_info >= (3, 7): - from ._base import BrokenExecutor - class BrokenThreadPool(BrokenExecutor): ... +class BrokenThreadPool(BrokenExecutor): ... class ThreadPoolExecutor(Executor): + if sys.version_info >= (3, 14): + BROKEN: type[BrokenThreadPool] + _max_workers: int _idle_semaphore: Semaphore - _threads: Set[Thread] + _threads: AbstractSet[Thread] _broken: bool _shutdown: bool _shutdown_lock: Lock - _thread_name_prefix: str | None = ... - _initializer: Callable[..., None] | None = ... - _initargs: Tuple[Any, ...] = ... - if sys.version_info >= (3, 7): - _work_queue: queue.SimpleQueue[_WorkItem[Any]] - else: - _work_queue: queue.Queue[_WorkItem[Any]] - if sys.version_info >= (3, 7): - def __init__( - self, - max_workers: int | None = ..., - thread_name_prefix: str = ..., - initializer: Callable[..., None] | None = ..., - initargs: Tuple[Any, ...] = ..., - ) -> None: ... + _thread_name_prefix: str | None + if sys.version_info >= (3, 14): + _create_worker_context: Callable[[], WorkerContext] + _resolve_work_item_task: _ResolveTaskFunc else: - def __init__(self, max_workers: int | None = ..., thread_name_prefix: str = ...) -> None: ... + _initializer: Callable[..., None] | None + _initargs: tuple[Any, ...] + _work_queue: queue.SimpleQueue[_WorkItem[Any]] + + if sys.version_info >= (3, 14): + @overload + @classmethod + def prepare_context( + cls, initializer: Callable[[], object], initargs: tuple[()] + ) -> tuple[Callable[[], WorkerContext], _ResolveTaskFunc]: ... + @overload + @classmethod + def prepare_context( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], WorkerContext], _ResolveTaskFunc]: ... + + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + thread_name_prefix: str, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + def _adjust_thread_count(self) -> None: ... - if sys.version_info >= (3, 7): - def _initializer_failed(self) -> None: ... + def _initializer_failed(self) -> None: ... diff --git a/stdlib/concurrent/interpreters/__init__.pyi b/stdlib/concurrent/interpreters/__init__.pyi new file mode 100644 index 000000000000..d19db0964260 --- /dev/null +++ b/stdlib/concurrent/interpreters/__init__.pyi @@ -0,0 +1,68 @@ +import sys +import threading +import types +from collections.abc import Callable +from typing import Any, Literal, ParamSpec, TypeVar +from typing_extensions import Self + +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 + from _interpreters import ( + InterpreterError as InterpreterError, + InterpreterNotFoundError as InterpreterNotFoundError, + NotShareableError as NotShareableError, + _SharedDict, + _Whence, + is_shareable as is_shareable, + ) + + from ._queues import Queue as Queue, QueueEmpty as QueueEmpty, QueueFull as QueueFull, create as create_queue + + __all__ = [ + "ExecutionFailed", + "Interpreter", + "InterpreterError", + "InterpreterNotFoundError", + "NotShareableError", + "Queue", + "QueueEmpty", + "QueueFull", + "create", + "create_queue", + "get_current", + "get_main", + "is_shareable", + "list_all", + ] + + _R = TypeVar("_R") + _P = ParamSpec("_P") + + class ExecutionFailed(InterpreterError): + excinfo: types.SimpleNamespace + + def __init__(self, excinfo: types.SimpleNamespace) -> None: ... + + def create() -> Interpreter: ... + def list_all() -> list[Interpreter]: ... + def get_current() -> Interpreter: ... + def get_main() -> Interpreter: ... + + class Interpreter: + def __new__(cls, id: int, /, _whence: _Whence | None = None, _ownsref: bool | None = None) -> Self: ... + def __reduce__(self) -> tuple[type[Self], int]: ... + def __hash__(self) -> int: ... + def __del__(self) -> None: ... + @property + def id(self) -> int: ... + @property + def whence( + self, + ) -> Literal["unknown", "runtime init", "legacy C-API", "C-API", "cross-interpreter C-API", "_interpreters module"]: ... + def is_running(self) -> bool: ... + def close(self) -> None: ... + def prepare_main( + self, ns: _SharedDict | None = None, /, **kwargs: Any + ) -> None: ... # kwargs has same value restrictions as _SharedDict + def exec(self, code: str | types.CodeType | Callable[[], object], /) -> None: ... + def call(self, callable: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + def call_in_thread(self, callable: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> threading.Thread: ... diff --git a/stdlib/concurrent/interpreters/_crossinterp.pyi b/stdlib/concurrent/interpreters/_crossinterp.pyi new file mode 100644 index 000000000000..c8e29aaafa18 --- /dev/null +++ b/stdlib/concurrent/interpreters/_crossinterp.pyi @@ -0,0 +1,30 @@ +import sys +from collections.abc import Callable +from typing import Final, NewType, TypeAlias +from typing_extensions import Never, Self + +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 + from _interpqueues import _UnboundOp + + class ItemInterpreterDestroyed(Exception): ... + # Actually a descriptor that behaves similarly to classmethod but prevents + # access from instances. + classonly = classmethod + + class UnboundItem: + __slots__ = () + def __new__(cls) -> Never: ... + @classonly + def singleton(cls, kind: str, module: str, name: str = "UNBOUND") -> Self: ... + + # Sentinel types and alias that don't exist at runtime. + _UnboundErrorType = NewType("_UnboundErrorType", object) + _UnboundRemoveType = NewType("_UnboundRemoveType", object) + _AnyUnbound: TypeAlias = _UnboundErrorType | _UnboundRemoveType | UnboundItem + + UNBOUND_ERROR: Final[_UnboundErrorType] + UNBOUND_REMOVE: Final[_UnboundRemoveType] + UNBOUND: Final[UnboundItem] # analogous to UNBOUND_REPLACE in C + + def serialize_unbound(unbound: _AnyUnbound) -> tuple[_UnboundOp]: ... + def resolve_unbound(flag: _UnboundOp, exctype_destroyed: Callable[[str], BaseException]) -> UnboundItem: ... diff --git a/stdlib/concurrent/interpreters/_queues.pyi b/stdlib/concurrent/interpreters/_queues.pyi new file mode 100644 index 000000000000..b4a4fd56dd45 --- /dev/null +++ b/stdlib/concurrent/interpreters/_queues.pyi @@ -0,0 +1,74 @@ +import queue +import sys +from typing import Final, SupportsIndex +from typing_extensions import Self + +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 + from _interpqueues import QueueError as QueueError, QueueNotFoundError as QueueNotFoundError + + from . import _crossinterp + from ._crossinterp import UNBOUND_ERROR as UNBOUND_ERROR, UNBOUND_REMOVE as UNBOUND_REMOVE, UnboundItem, _AnyUnbound + + __all__ = [ + "UNBOUND", + "UNBOUND_ERROR", + "UNBOUND_REMOVE", + "ItemInterpreterDestroyed", + "Queue", + "QueueEmpty", + "QueueError", + "QueueFull", + "QueueNotFoundError", + "create", + "list_all", + ] + + class QueueEmpty(QueueError, queue.Empty): ... + class QueueFull(QueueError, queue.Full): ... + class ItemInterpreterDestroyed(QueueError, _crossinterp.ItemInterpreterDestroyed): ... + UNBOUND: Final[UnboundItem] + + def create(maxsize: int = 0, *, unbounditems: _AnyUnbound = ...) -> Queue: ... + def list_all() -> list[Queue]: ... + + class Queue: + def __new__(cls, id: int, /) -> Self: ... + def __del__(self) -> None: ... + def __hash__(self) -> int: ... + def __reduce__(self) -> tuple[type[Self], int]: ... + @property + def id(self) -> int: ... + @property + def unbounditems(self) -> _AnyUnbound: ... + @property + def maxsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def qsize(self) -> int: ... + if sys.version_info >= (3, 14): + def put( + self, + obj: object, + block: bool = True, + timeout: SupportsIndex | None = None, + *, + unbounditems: _AnyUnbound | None = None, + _delay: float = 0.01, + ) -> None: ... + else: + def put( + self, + obj: object, + timeout: SupportsIndex | None = None, + *, + unbounditems: _AnyUnbound | None = None, + _delay: float = 0.01, + ) -> None: ... + + def put_nowait(self, obj: object, *, unbounditems: _AnyUnbound | None = None) -> None: ... + if sys.version_info >= (3, 14): + def get(self, block: bool = True, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object: ... + else: + def get(self, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object: ... + + def get_nowait(self) -> object: ... diff --git a/stdlib/configparser.pyi b/stdlib/configparser.pyi index 83d9d969080a..cc27c9d20ea7 100644 --- a/stdlib/configparser.pyi +++ b/stdlib/configparser.pyi @@ -1,37 +1,149 @@ import sys -from _typeshed import StrOrBytesPath, StrPath, SupportsWrite -from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence -from typing import Any, ClassVar, Dict, Optional, Pattern, Type, TypeVar, overload -from typing_extensions import Literal - -# Internal type aliases -_section = Mapping[str, str] -_parser = MutableMapping[str, _section] -_converter = Callable[[str], Any] -_converters = Dict[str, _converter] -_T = TypeVar("_T") +from _typeshed import BytesPath, GenericPath, MaybeNone, StrOrBytesPath, StrPath, SupportsWrite +from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence, ValuesView +from re import Pattern +from typing import Any, AnyStr, ClassVar, Final, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import deprecated + +if sys.version_info >= (3, 14): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "MultilineContinuationError", + "UnnamedSectionDisabledError", + "InvalidWriteError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + "UNNAMED_SECTION", + ) +elif sys.version_info >= (3, 13): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + "UNNAMED_SECTION", + "MultilineContinuationError", + ) +elif sys.version_info >= (3, 12): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + ) +else: + __all__ = [ + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "SafeConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + ] -if sys.version_info >= (3, 7): - _Path = StrOrBytesPath +if sys.version_info >= (3, 13): + @type_check_only + class _UNNAMED_SECTION: ... + + UNNAMED_SECTION: _UNNAMED_SECTION + + _SectionName: TypeAlias = str | _UNNAMED_SECTION + # A list of sections can only include an unnamed section if the parser was initialized with + # allow_unnamed_section=True. Any prevents users from having to use explicit + # type checks if allow_unnamed_section is False (the default). + _SectionNameList: TypeAlias = list[Any] else: - _Path = StrPath + _SectionName: TypeAlias = str + _SectionNameList: TypeAlias = list[str] + +_Section: TypeAlias = Mapping[str, str] +_Parser: TypeAlias = MutableMapping[str, _Section] +_ConverterCallback: TypeAlias = Callable[[str], Any] +_ConvertersMap: TypeAlias = dict[str, _ConverterCallback] +_T = TypeVar("_T") -DEFAULTSECT: str -MAX_INTERPOLATION_DEPTH: int +DEFAULTSECT: Final = "DEFAULT" +MAX_INTERPOLATION_DEPTH: Final = 10 class Interpolation: - def before_get(self, parser: _parser, section: str, option: str, value: str, defaults: _section) -> str: ... - def before_set(self, parser: _parser, section: str, option: str, value: str) -> str: ... - def before_read(self, parser: _parser, section: str, option: str, value: str) -> str: ... - def before_write(self, parser: _parser, section: str, option: str, value: str) -> str: ... + def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, defaults: _Section) -> str: ... + def before_set(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... + def before_read(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... + def before_write(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... class BasicInterpolation(Interpolation): ... class ExtendedInterpolation(Interpolation): ... -class LegacyInterpolation(Interpolation): - def before_get(self, parser: _parser, section: str, option: str, value: str, vars: _section) -> str: ... +if sys.version_info < (3, 13): + @deprecated( + "Deprecated since Python 3.2; removed in Python 3.13. Use `BasicInterpolation` or `ExtendedInterpolation` instead." + ) + class LegacyInterpolation(Interpolation): + def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, vars: _Section) -> str: ... -class RawConfigParser(_parser): +class RawConfigParser(_Parser): _SECT_TMPL: ClassVar[str] # undocumented _OPT_TMPL: ClassVar[str] # undocumented _OPT_NV_TMPL: ClassVar[str] # undocumented @@ -43,102 +155,205 @@ class RawConfigParser(_parser): BOOLEAN_STATES: ClassVar[Mapping[str, bool]] # undocumented default_section: str - @overload - def __init__( - self, - defaults: Mapping[str, str | None] | None = ..., - dict_type: Type[Mapping[str, str]] = ..., - allow_no_value: Literal[True] = ..., - *, - delimiters: Sequence[str] = ..., - comment_prefixes: Sequence[str] = ..., - inline_comment_prefixes: Sequence[str] | None = ..., - strict: bool = ..., - empty_lines_in_values: bool = ..., - default_section: str = ..., - interpolation: Interpolation | None = ..., - converters: _converters = ..., - ) -> None: ... - @overload - def __init__( - self, - defaults: _section | None = ..., - dict_type: Type[Mapping[str, str]] = ..., - allow_no_value: bool = ..., - *, - delimiters: Sequence[str] = ..., - comment_prefixes: Sequence[str] = ..., - inline_comment_prefixes: Sequence[str] | None = ..., - strict: bool = ..., - empty_lines_in_values: bool = ..., - default_section: str = ..., - interpolation: Interpolation | None = ..., - converters: _converters = ..., - ) -> None: ... + if sys.version_info >= (3, 13): + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None = None, + dict_type: type[Mapping[str, str]] = ..., + *, + allow_no_value: Literal[True], + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None, + dict_type: type[Mapping[str, str]], + allow_no_value: Literal[True], + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + @overload + def __init__( + self, + defaults: _Section | None = None, + dict_type: type[Mapping[str, str]] = ..., + allow_no_value: bool = False, + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + else: + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None = None, + dict_type: type[Mapping[str, str]] = ..., + *, + allow_no_value: Literal[True], + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + ) -> None: ... + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None, + dict_type: type[Mapping[str, str]], + allow_no_value: Literal[True], + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + ) -> None: ... + @overload + def __init__( + self, + defaults: _Section | None = None, + dict_type: type[Mapping[str, str]] = ..., + allow_no_value: bool = False, + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + ) -> None: ... + def __len__(self) -> int: ... - def __getitem__(self, section: str) -> SectionProxy: ... - def __setitem__(self, section: str, options: _section) -> None: ... - def __delitem__(self, section: str) -> None: ... + def __getitem__(self, key: _SectionName) -> SectionProxy: ... + def __setitem__(self, key: _SectionName, value: _Section) -> None: ... + def __delitem__(self, key: _SectionName) -> None: ... def __iter__(self) -> Iterator[str]: ... - def defaults(self) -> _section: ... - def sections(self) -> list[str]: ... - def add_section(self, section: str) -> None: ... - def has_section(self, section: str) -> bool: ... - def options(self, section: str) -> list[str]: ... - def has_option(self, section: str, option: str) -> bool: ... - def read(self, filenames: _Path | Iterable[_Path], encoding: str | None = ...) -> list[str]: ... - def read_file(self, f: Iterable[str], source: str | None = ...) -> None: ... - def read_string(self, string: str, source: str = ...) -> None: ... - def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = ...) -> None: ... - def readfp(self, fp: Iterable[str], filename: str | None = ...) -> None: ... + def __contains__(self, key: object) -> bool: ... + def defaults(self) -> _Section: ... + def sections(self) -> _SectionNameList: ... + def add_section(self, section: _SectionName) -> None: ... + def has_section(self, section: _SectionName) -> bool: ... + def options(self, section: _SectionName) -> list[str]: ... + def has_option(self, section: _SectionName, option: str) -> bool: ... + + @overload + def read(self, filenames: GenericPath[AnyStr], encoding: str | None = None) -> list[AnyStr]: ... + @overload + def read(self, filenames: Iterable[StrPath], encoding: str | None = None) -> list[str]: ... + @overload + def read(self, filenames: Iterable[BytesPath], encoding: str | None = None) -> list[bytes]: ... + @overload + def read(self, filenames: Iterable[StrOrBytesPath], encoding: str | None = None) -> list[str | bytes]: ... + + def read_file(self, f: Iterable[str], source: str | None = None) -> None: ... + def read_string(self, string: str, source: str = "") -> None: ... + def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = "") -> None: ... + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `parser.read_file()` instead.") + def readfp(self, fp: Iterable[str], filename: str | None = None) -> None: ... + # These get* methods are partially applied (with the same names) in # SectionProxy; the stubs should be kept updated together @overload - def getint(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ...) -> int: ... + def getint(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> int: ... @overload def getint( - self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ..., fallback: _T = ... + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> int | _T: ... + @overload - def getfloat(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ...) -> float: ... + def getfloat(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> float: ... @overload def getfloat( - self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ..., fallback: _T = ... + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> float | _T: ... + @overload - def getboolean(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ...) -> bool: ... + def getboolean(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool: ... @overload def getboolean( - self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ..., fallback: _T = ... + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> bool | _T: ... + def _get_conv( self, - section: str, + section: _SectionName, option: str, conv: Callable[[str], _T], *, - raw: bool = ..., - vars: _section | None = ..., + raw: bool = False, + vars: _Section | None = None, fallback: _T = ..., ) -> _T: ... + # This is incompatible with MutableMapping so we ignore the type @overload # type: ignore[override] - def get(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ...) -> str: ... + def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str | MaybeNone: ... @overload - def get(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ..., fallback: _T) -> str | _T: ... + def get( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> str | _T | MaybeNone: ... + @overload - def items(self, *, raw: bool = ..., vars: _section | None = ...) -> ItemsView[str, SectionProxy]: ... + def items(self, *, raw: bool = False, vars: _Section | None = None) -> ItemsView[str, SectionProxy]: ... @overload - def items(self, section: str, raw: bool = ..., vars: _section | None = ...) -> list[tuple[str, str]]: ... - def set(self, section: str, option: str, value: str | None = ...) -> None: ... - def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = ...) -> None: ... - def remove_option(self, section: str, option: str) -> bool: ... - def remove_section(self, section: str) -> bool: ... + def items(self, section: _SectionName, raw: bool = False, vars: _Section | None = None) -> list[tuple[str, str]]: ... + + def values(self) -> ValuesView[SectionProxy]: ... + def popitem(self) -> tuple[str, SectionProxy]: ... + def set(self, section: _SectionName, option: str, value: str | None = None) -> None: ... + def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = True) -> None: ... + def remove_option(self, section: _SectionName, option: str) -> bool: ... + def remove_section(self, section: _SectionName) -> bool: ... def optionxform(self, optionstr: str) -> str: ... + @property + def converters(self) -> ConverterMapping: ... -class ConfigParser(RawConfigParser): ... +class ConfigParser(RawConfigParser): + # This is incompatible with MutableMapping so we ignore the type + @overload # type: ignore[override] + def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str: ... + @overload + def get( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> str | _T: ... -if sys.version_info < (3, 11): +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `ConfigParser` instead.") class SafeConfigParser(ConfigParser): ... class SectionProxy(MutableMapping[str, str]): @@ -153,89 +368,142 @@ class SectionProxy(MutableMapping[str, str]): def parser(self) -> RawConfigParser: ... @property def name(self) -> str: ... - def get( # type: ignore[override] + + # This is incompatible with MutableMapping so we ignore the type + @overload # type: ignore[override] + def get( self, option: str, - fallback: str | None = ..., + fallback: None = None, *, - raw: bool = ..., - vars: _section | None = ..., - _impl: Any | None = ..., - **kwargs: Any, - ) -> str: ... + raw: bool = False, + vars: _Section | None = None, + _impl: Any | None = None, + **kwargs: Any, # passed to the underlying parser's get() method + ) -> str | None: ... + @overload + def get( + self, + option: str, + fallback: _T, + *, + raw: bool = False, + vars: _Section | None = None, + _impl: Any | None = None, + **kwargs: Any, # passed to the underlying parser's get() method + ) -> str | _T: ... + # These are partially-applied version of the methods with the same names in # RawConfigParser; the stubs should be kept updated together @overload - def getint(self, option: str, *, raw: bool = ..., vars: _section | None = ...) -> int: ... + def getint(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> int | None: ... @overload - def getint(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _section | None = ...) -> int | _T: ... + def getint(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> int | _T: ... + @overload - def getfloat(self, option: str, *, raw: bool = ..., vars: _section | None = ...) -> float: ... + def getfloat(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> float | None: ... @overload - def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _section | None = ...) -> float | _T: ... + def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> float | _T: ... + @overload - def getboolean(self, option: str, *, raw: bool = ..., vars: _section | None = ...) -> bool: ... + def getboolean(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool | None: ... @overload - def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _section | None = ...) -> bool | _T: ... + def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> bool | _T: ... + # SectionProxy can have arbitrary attributes when custom converters are used def __getattr__(self, key: str) -> Callable[..., Any]: ... -class ConverterMapping(MutableMapping[str, Optional[_converter]]): - GETTERCRE: Pattern[Any] +class ConverterMapping(MutableMapping[str, _ConverterCallback | None]): + GETTERCRE: ClassVar[Pattern[Any]] def __init__(self, parser: RawConfigParser) -> None: ... - def __getitem__(self, key: str) -> _converter: ... - def __setitem__(self, key: str, value: _converter | None) -> None: ... + def __getitem__(self, key: str) -> _ConverterCallback: ... + def __setitem__(self, key: str, value: _ConverterCallback | None) -> None: ... def __delitem__(self, key: str) -> None: ... def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... class Error(Exception): message: str - def __init__(self, msg: str = ...) -> None: ... + def __init__(self, msg: str = "") -> None: ... class NoSectionError(Error): - section: str - def __init__(self, section: str) -> None: ... + section: _SectionName + def __init__(self, section: _SectionName) -> None: ... class DuplicateSectionError(Error): - section: str + section: _SectionName source: str | None lineno: int | None - def __init__(self, section: str, source: str | None = ..., lineno: int | None = ...) -> None: ... + def __init__(self, section: _SectionName, source: str | None = None, lineno: int | None = None) -> None: ... class DuplicateOptionError(Error): - section: str + section: _SectionName option: str source: str | None lineno: int | None - def __init__(self, section: str, option: str, source: str | None = ..., lineno: int | None = ...) -> None: ... + def __init__(self, section: _SectionName, option: str, source: str | None = None, lineno: int | None = None) -> None: ... class NoOptionError(Error): - section: str + section: _SectionName option: str - def __init__(self, option: str, section: str) -> None: ... + def __init__(self, option: str, section: _SectionName) -> None: ... class InterpolationError(Error): - section: str + section: _SectionName option: str - def __init__(self, option: str, section: str, msg: str) -> None: ... + def __init__(self, option: str, section: _SectionName, msg: str) -> None: ... class InterpolationDepthError(InterpolationError): - def __init__(self, option: str, section: str, rawval: object) -> None: ... + def __init__(self, option: str, section: _SectionName, rawval: object) -> None: ... class InterpolationMissingOptionError(InterpolationError): reference: str - def __init__(self, option: str, section: str, rawval: object, reference: str) -> None: ... + def __init__(self, option: str, section: _SectionName, rawval: object, reference: str) -> None: ... class InterpolationSyntaxError(InterpolationError): ... class ParsingError(Error): source: str errors: list[tuple[int, str]] - def __init__(self, source: str | None = ..., filename: str | None = ...) -> None: ... + if sys.version_info >= (3, 13): + def __init__(self, source: str, *args: object) -> None: ... + def combine(self, others: Iterable[ParsingError]) -> ParsingError: ... + elif sys.version_info >= (3, 12): + def __init__(self, source: str) -> None: ... + else: + @overload + def __init__(self, source: str) -> None: ... + @overload + @deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.") + def __init__(self, source: None, filename: str | None) -> None: ... + @overload + @deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.") + def __init__(self, source: None = None, *, filename: str | None) -> None: ... + def append(self, lineno: int, line: str) -> None: ... + if sys.version_info < (3, 12): + @property + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `source` instead.") + def filename(self) -> str: ... + @filename.setter + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `source` instead.") + def filename(self, value: str) -> None: ... + class MissingSectionHeaderError(ParsingError): lineno: int line: str def __init__(self, filename: str, lineno: int, line: str) -> None: ... + +if sys.version_info >= (3, 13): + class MultilineContinuationError(ParsingError): + lineno: int + line: str + def __init__(self, filename: str, lineno: int, line: str) -> None: ... + +if sys.version_info >= (3, 14): + class UnnamedSectionDisabledError(Error): + msg: Final = "Support for UNNAMED_SECTION is disabled." + def __init__(self) -> None: ... + + class InvalidWriteError(Error): ... diff --git a/stdlib/contextlib.pyi b/stdlib/contextlib.pyi index fe72d6dd42d9..c286514af229 100644 --- a/stdlib/contextlib.pyi +++ b/stdlib/contextlib.pyi @@ -1,142 +1,224 @@ +import abc import sys -from _typeshed import Self, StrOrBytesPath +from _typeshed import FileDescriptorOrPath, Unused +from abc import ABC, abstractmethod +from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType -from typing import ( - IO, - Any, - AsyncIterator, - Awaitable, - Callable, - ContextManager, - Generic, - Iterator, - Optional, - Protocol, - Type, - TypeVar, - overload, -) -from typing_extensions import ParamSpec - -AbstractContextManager = ContextManager -if sys.version_info >= (3, 7): - from typing import AsyncContextManager +from typing import Any, Generic, ParamSpec, Protocol, TypeAlias, TypeVar, overload, runtime_checkable, type_check_only +from typing_extensions import Self, deprecated + +__all__ = [ + "aclosing", + "contextmanager", + "closing", + "AbstractContextManager", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", + "AbstractAsyncContextManager", + "AsyncExitStack", + "asynccontextmanager", + "nullcontext", +] - AbstractAsyncContextManager = AsyncContextManager +if sys.version_info >= (3, 11): + __all__ += ["chdir"] _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -_T_io = TypeVar("_T_io", bound=Optional[IO[str]]) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound=bool | None, default=bool | None) _F = TypeVar("_F", bound=Callable[..., Any]) +_G_co = TypeVar("_G_co", bound=Generator[Any, Any, Any] | AsyncGenerator[Any, Any], covariant=True) _P = ParamSpec("_P") -_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] -_CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) - -class ContextDecorator: - def __call__(self, func: _F) -> _F: ... +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None) +_ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) -class _GeneratorContextManager(AbstractContextManager[_T_co], ContextDecorator): ... +_ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] +_CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any, Any] | _ExitFunc) -# type ignore to deal with incomplete ParamSpec support in mypy -def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, _GeneratorContextManager[_T]]: ... # type: ignore[misc] - -if sys.version_info >= (3, 10): - _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) - class AsyncContextDecorator: - def __call__(self, func: _AF) -> _AF: ... - class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co], AsyncContextDecorator): ... +# mypy and pyright object to this being both ABC and Protocol. +# At runtime it inherits from ABC and is not a Protocol, but it is on the +# allowlist for use as a Protocol. +@runtime_checkable +class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + __slots__ = () + def __enter__(self) -> _T_co: ... + @abstractmethod + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +# mypy and pyright object to this being both ABC and Protocol. +# At runtime it inherits from ABC and is not a Protocol, but it is on the +# allowlist for use as a Protocol. +@runtime_checkable +class AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + __slots__ = () + async def __aenter__(self) -> _T_co: ... + @abstractmethod + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... -elif sys.version_info >= (3, 7): - class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co]): ... +class ContextDecorator: + def _recreate_cm(self) -> Self: ... + def __call__(self, func: _F) -> _F: ... -if sys.version_info >= (3, 7): - def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, _AsyncGeneratorContextManager[_T]]: ... # type: ignore[misc] +class _GeneratorContextManagerBase(Generic[_G_co]): + # Ideally this would use ParamSpec, but that requires (*args, **kwargs), which this isn't. see #6676 + def __init__(self, func: Callable[..., _G_co], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... + gen: _G_co + func: Callable[..., _G_co] + args: tuple[Any, ...] + kwds: dict[str, Any] + +class _GeneratorContextManager( + _GeneratorContextManagerBase[Generator[_T_co, _SendT_contra, _ReturnT_co]], + AbstractContextManager[_T_co, bool | None], + ContextDecorator, +): + def __exit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +@overload +def contextmanager(func: Callable[_P, Generator[_T_co, None, object]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... +@overload +@deprecated( + "Annotating the return type as `-> Iterator[Foo]` with `@contextmanager` is deprecated. Use `-> Generator[Foo]` instead." +) +def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... + +_AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) + +class AsyncContextDecorator: + def _recreate_cm(self) -> Self: ... + def __call__(self, func: _AF) -> _AF: ... + +class _AsyncGeneratorContextManager( + _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], + AbstractAsyncContextManager[_T_co, bool | None], + AsyncContextDecorator, +): + async def __aexit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +@overload +def asynccontextmanager(func: Callable[_P, AsyncGenerator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... +@overload +@deprecated( + "Annotating the return type as `-> AsyncIterator[Foo]` with `@asynccontextmanager` is deprecated. " + "Use `-> AsyncGenerator[Foo]` instead." +) +def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... +@type_check_only class _SupportsClose(Protocol): def close(self) -> object: ... _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) -class closing(AbstractContextManager[_SupportsCloseT]): +class closing(AbstractContextManager[_SupportsCloseT, None]): def __init__(self, thing: _SupportsCloseT) -> None: ... + def __exit__(self, *exc_info: Unused) -> None: ... + +@type_check_only +class _SupportsAclose(Protocol): + def aclose(self) -> Awaitable[object]: ... -if sys.version_info >= (3, 10): - class _SupportsAclose(Protocol): - def aclose(self) -> Awaitable[object]: ... - _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) - class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): - def __init__(self, thing: _SupportsAcloseT) -> None: ... +_SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) -class suppress(AbstractContextManager[None]): - def __init__(self, *exceptions: Type[BaseException]) -> None: ... +class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]): + def __init__(self, thing: _SupportsAcloseT) -> None: ... + async def __aexit__(self, *exc_info: Unused) -> None: ... + +class suppress(AbstractContextManager[None, bool]): + def __init__(self, *exceptions: type[BaseException]) -> None: ... def __exit__( - self, exctype: Type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None ) -> bool: ... -class redirect_stdout(AbstractContextManager[_T_io]): - def __init__(self, new_target: _T_io) -> None: ... +# This is trying to describe what is needed for (most?) uses +# of `redirect_stdout` and `redirect_stderr`. +# https://github.com/python/typeshed/issues/14903 +@type_check_only +class _SupportsRedirect(Protocol): + def write(self, s: str, /) -> int: ... + def flush(self) -> None: ... + +_SupportsRedirectT = TypeVar("_SupportsRedirectT", bound=_SupportsRedirect | None) -class redirect_stderr(AbstractContextManager[_T_io]): - def __init__(self, new_target: _T_io) -> None: ... +class _RedirectStream(AbstractContextManager[_SupportsRedirectT, None]): + def __init__(self, new_target: _SupportsRedirectT) -> None: ... + def __exit__( + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + ) -> None: ... + +class redirect_stdout(_RedirectStream[_SupportsRedirectT]): ... +class redirect_stderr(_RedirectStream[_SupportsRedirectT]): ... -class ExitStack(AbstractContextManager[ExitStack]): - def __init__(self) -> None: ... - def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... +class _BaseExitStack(Generic[_ExitT_co]): + def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... - def callback(self, __callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... - def pop_all(self: Self) -> Self: ... + def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... + def pop_all(self) -> Self: ... + +# this class is to avoid putting `metaclass=abc.ABCMeta` on the implementations directly, as this would make them +# appear explicitly abstract to some tools. this is due to the implementations not subclassing `AbstractContextManager` +# see note on the subclasses +@type_check_only +class _BaseExitStackAbstract(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): ... + +# In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__` +# https://discuss.python.org/t/self-as-typevar-default/90939 +class ExitStack(_BaseExitStackAbstract[_ExitT_co]): def close(self) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> bool: ... - -if sys.version_info >= (3, 7): - _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] - _CallbackCoroFunc = Callable[..., Awaitable[Any]] - _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) - class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): - def __init__(self) -> None: ... - def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... - def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> Awaitable[_T]: ... - def push(self, exit: _CM_EF) -> _CM_EF: ... - def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... - def callback(self, __callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... - def push_async_callback(self, __callback: _CallbackCoroFunc, *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... - def pop_all(self: Self) -> Self: ... - def aclose(self) -> Awaitable[None]: ... - def __aenter__(self: Self) -> Awaitable[Self]: ... - def __aexit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> Awaitable[bool]: ... - -if sys.version_info >= (3, 10): - class nullcontext(AbstractContextManager[_T], AbstractAsyncContextManager[_T]): - enter_result: _T - @overload - def __init__(self: nullcontext[None], enter_result: None = ...) -> None: ... - @overload - def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... - def __enter__(self) -> _T: ... - def __exit__(self, *exctype: Any) -> None: ... - async def __aenter__(self) -> _T: ... - async def __aexit__(self, *exctype: Any) -> None: ... - -elif sys.version_info >= (3, 7): - class nullcontext(AbstractContextManager[_T]): - enter_result: _T - @overload - def __init__(self: nullcontext[None], enter_result: None = ...) -> None: ... - @overload - def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... - def __enter__(self) -> _T: ... - def __exit__(self, *exctype: Any) -> None: ... + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +_ExitCoroFunc: TypeAlias = Callable[ + [type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool | None] +] +_ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any, Any] | _ExitCoroFunc) + +# In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__` +# https://discuss.python.org/t/self-as-typevar-default/90939 +class AsyncExitStack(_BaseExitStackAbstract[_ExitT_co]): + async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: ... + def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... + def push_async_callback( + self, callback: Callable[_P, Awaitable[_T]], /, *args: _P.args, **kwds: _P.kwargs + ) -> Callable[_P, Awaitable[_T]]: ... + async def aclose(self) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]): + enter_result: _T + + @overload + def __init__(self: nullcontext[None]) -> None: ... + @overload + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + + def __enter__(self) -> _T: ... + def __exit__(self, *exctype: Unused) -> None: ... + async def __aenter__(self) -> _T: ... + async def __aexit__(self, *exctype: Unused) -> None: ... if sys.version_info >= (3, 11): - _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=int | StrOrBytesPath) - class chdir(AbstractContextManager[None], Generic[_T_fd_or_any_path]): + _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=FileDescriptorOrPath) + + class chdir(AbstractContextManager[None, None], Generic[_T_fd_or_any_path]): path: _T_fd_or_any_path def __init__(self, path: _T_fd_or_any_path) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *excinfo: object) -> None: ... + def __exit__(self, *excinfo: Unused) -> None: ... diff --git a/stdlib/contextvars.pyi b/stdlib/contextvars.pyi index e97f62188dcb..22dc33006e9d 100644 --- a/stdlib/contextvars.pyi +++ b/stdlib/contextvars.pyi @@ -1,46 +1,3 @@ -import sys -from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar, overload +from _contextvars import Context as Context, ContextVar as ContextVar, Token as Token, copy_context as copy_context -if sys.version_info >= (3, 9): - from types import GenericAlias - -_T = TypeVar("_T") -_D = TypeVar("_D") - -class ContextVar(Generic[_T]): - def __init__(self, name: str, *, default: _T = ...) -> None: ... - @property - def name(self) -> str: ... - @overload - def get(self) -> _T: ... - @overload - def get(self, default: _D | _T) -> _D | _T: ... - def set(self, value: _T) -> Token[_T]: ... - def reset(self, token: Token[_T]) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class Token(Generic[_T]): - @property - def var(self) -> ContextVar[_T]: ... - @property - def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express - MISSING: ClassVar[object] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -def copy_context() -> Context: ... - -# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have -# a different value. -class Context(Mapping[ContextVar[Any], Any]): - def __init__(self) -> None: ... - @overload - def get(self, __key: ContextVar[Any]) -> Any | None: ... - @overload - def get(self, __key: ContextVar[Any], __default: Any | None) -> Any: ... - def run(self, callable: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... - def copy(self) -> Context: ... - def __getitem__(self, key: ContextVar[Any]) -> Any: ... - def __iter__(self) -> Iterator[ContextVar[Any]]: ... - def __len__(self) -> int: ... +__all__ = ("Context", "ContextVar", "Token", "copy_context") diff --git a/stdlib/copy.pyi b/stdlib/copy.pyi index a5f9420e3811..e805af61291b 100644 --- a/stdlib/copy.pyi +++ b/stdlib/copy.pyi @@ -1,14 +1,37 @@ -from typing import Any, TypeVar +import sys +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import ParamSpec + +__all__ = ["Error", "copy", "deepcopy"] _T = TypeVar("_T") +_RT_co = TypeVar("_RT_co", covariant=True) +_P = ParamSpec("_P") + +@type_check_only +class _SupportsReplace(Protocol[_P, _RT_co]): + # In reality doesn't support args, but there's no great way to express this. + def __replace__(self, /, *_: _P.args, **changes: _P.kwargs) -> _RT_co: ... # None in CPython but non-None in Jython PyStringMap: Any -# Note: memo and _nil are internal kwargs. -def deepcopy(x: _T, memo: dict[int, Any] | None = ..., _nil: Any = ...) -> _T: ... def copy(x: _T) -> _T: ... +if sys.version_info >= (3, 15): + def deepcopy(x: _T, memo: dict[int, Any] | None = None) -> _T: ... + +else: + # Note: memo and _nil are internal kwargs. + def deepcopy(x: _T, memo: dict[int, Any] | None = None, _nil: Any = []) -> _T: ... + +if sys.version_info >= (3, 13): + __all__ += ["replace"] + + def replace( + obj: _SupportsReplace[_P, _RT_co], /, *_: _P.args, **changes: _P.kwargs # does not accept positional arguments at runtime + ) -> _RT_co: ... + class Error(Exception): ... error = Error diff --git a/stdlib/copyreg.pyi b/stdlib/copyreg.pyi index 320097b3a204..3bfc0de8158f 100644 --- a/stdlib/copyreg.pyi +++ b/stdlib/copyreg.pyi @@ -1,18 +1,20 @@ -from typing import Any, Callable, Hashable, Optional, SupportsInt, Tuple, TypeVar, Union +from collections.abc import Callable, Hashable +from typing import Any, SupportsInt, TypeAlias, TypeVar -_TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] +_T = TypeVar("_T") +_Reduce: TypeAlias = tuple[Callable[..., _T], tuple[Any, ...]] | tuple[Callable[..., _T], tuple[Any, ...], Any | None] -__all__: list[str] +__all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] def pickle( - ob_type: _TypeT, - pickle_function: Callable[[_TypeT], str | _Reduce[_TypeT]], - constructor_ob: Callable[[_Reduce[_TypeT]], _TypeT] | None = ..., + ob_type: type[_T], + pickle_function: Callable[[_T], str | _Reduce[_T]], + constructor_ob: Callable[[_Reduce[_T]], _T] | None = None, ) -> None: ... -def constructor(object: Callable[[_Reduce[_TypeT]], _TypeT]) -> None: ... +def constructor(object: Callable[[_Reduce[_T]], _T]) -> None: ... def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: ... def remove_extension(module: Hashable, name: Hashable, code: int) -> None: ... def clear_extension_cache() -> None: ... -dispatch_table: dict[type, Callable[[type], str | _Reduce[type]]] # undocumented +_DispatchTableType: TypeAlias = dict[type, Callable[[Any], str | _Reduce[Any]]] # imported by multiprocessing.reduction +dispatch_table: _DispatchTableType # undocumented diff --git a/stdlib/crypt.pyi b/stdlib/crypt.pyi index 27e30433f702..f92632196989 100644 --- a/stdlib/crypt.pyi +++ b/stdlib/crypt.pyi @@ -1,20 +1,26 @@ import sys +from typing import Final, NamedTuple, type_check_only +from typing_extensions import disjoint_base -class _Method: ... +if sys.platform != "win32": + @type_check_only + class _MethodBase(NamedTuple): + name: str + ident: str | None + salt_chars: int + total_size: int -METHOD_CRYPT: _Method -METHOD_MD5: _Method -METHOD_SHA256: _Method -METHOD_SHA512: _Method -if sys.version_info >= (3, 7): - METHOD_BLOWFISH: _Method + if sys.version_info >= (3, 12): + class _Method(_MethodBase): ... + else: + @disjoint_base + class _Method(_MethodBase): ... -methods: list[_Method] - -if sys.version_info >= (3, 7): - def mksalt(method: _Method | None = ..., *, rounds: int | None = ...) -> str: ... - -else: - def mksalt(method: _Method | None = ...) -> str: ... - -def crypt(word: str, salt: str | _Method | None = ...) -> str: ... + METHOD_CRYPT: Final[_Method] + METHOD_MD5: Final[_Method] + METHOD_SHA256: Final[_Method] + METHOD_SHA512: Final[_Method] + METHOD_BLOWFISH: Final[_Method] + methods: list[_Method] + def mksalt(method: _Method | None = None, *, rounds: int | None = None) -> str: ... + def crypt(word: str, salt: str | _Method | None = None) -> str: ... diff --git a/stdlib/csv.pyi b/stdlib/csv.pyi index 0b69cb2272d3..751e85566f88 100644 --- a/stdlib/csv.pyi +++ b/stdlib/csv.pyi @@ -4,11 +4,10 @@ from _csv import ( QUOTE_MINIMAL as QUOTE_MINIMAL, QUOTE_NONE as QUOTE_NONE, QUOTE_NONNUMERIC as QUOTE_NONNUMERIC, - Dialect as Dialect, Error as Error, + __version__ as __version__, _DialectLike, - _reader, - _writer, + _QuotingType, field_size_limit as field_size_limit, get_dialect as get_dialect, list_dialects as list_dialects, @@ -17,91 +16,142 @@ from _csv import ( unregister_dialect as unregister_dialect, writer as writer, ) -from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence -from typing import Any, Generic, Type, TypeVar, overload -if sys.version_info >= (3, 8): - from typing import Dict as _DictReadMapping -else: - from collections import OrderedDict as _DictReadMapping +if sys.version_info >= (3, 12): + from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS +from _csv import Reader, Writer +from _typeshed import SupportsWrite +from collections.abc import Collection, Iterable, Mapping, Sequence +from types import GenericAlias +from typing import Any, Generic, Literal, TypeVar, overload +from typing_extensions import Self + +__all__ = [ + "QUOTE_MINIMAL", + "QUOTE_ALL", + "QUOTE_NONNUMERIC", + "QUOTE_NONE", + "Error", + "Dialect", + "excel", + "excel_tab", + "field_size_limit", + "reader", + "writer", + "register_dialect", + "get_dialect", + "list_dialects", + "Sniffer", + "unregister_dialect", + "DictReader", + "DictWriter", + "unix_dialect", +] +if sys.version_info >= (3, 12): + __all__ += ["QUOTE_STRINGS", "QUOTE_NOTNULL"] +if sys.version_info < (3, 13): + __all__ += ["__doc__", "__version__"] _T = TypeVar("_T") -class excel(Dialect): +# Note that this is often the wrong class: it is only useful for sub-classing +# (e.g. csv.excel). Dialect objects returned at runtime, such as the return +# value of get_dialect(), are usually _csv.Dialect, which is not a subclass +# of csv.Dialect. +class Dialect: delimiter: str - quotechar: str + quotechar: str | None + escapechar: str | None doublequote: bool skipinitialspace: bool lineterminator: str - quoting: int + quoting: _QuotingType + strict: bool + def __init__(self) -> None: ... -class excel_tab(excel): - delimiter: str +class excel(Dialect): ... +class excel_tab(excel): ... +class unix_dialect(Dialect): ... -class unix_dialect(Dialect): - delimiter: str - quotechar: str - doublequote: bool - skipinitialspace: bool - lineterminator: str - quoting: int - -class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): +class DictReader(Generic[_T]): fieldnames: Sequence[_T] | None - restkey: str | None - restval: str | None - reader: _reader + restkey: _T | None + restval: str | Any | None + reader: Reader dialect: _DialectLike line_num: int + @overload def __init__( self, f: Iterable[str], fieldnames: Sequence[_T], - restkey: str | None = ..., - restval: str | None = ..., - dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, + restkey: _T | None = None, + restval: str | Any | None = None, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, ) -> None: ... @overload def __init__( self: DictReader[str], f: Iterable[str], - fieldnames: Sequence[str] | None = ..., - restkey: str | None = ..., - restval: str | None = ..., - dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, + fieldnames: Sequence[str] | None = None, + restkey: str | None = None, + restval: str | None = None, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, ) -> None: ... - def __iter__(self) -> DictReader[_T]: ... - def __next__(self) -> _DictReadMapping[_T, str]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> dict[_T | Any, str | Any]: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class DictWriter(Generic[_T]): fieldnames: Collection[_T] restval: Any | None - extrasaction: str - writer: _writer + extrasaction: Literal["raise", "ignore"] + writer: Writer def __init__( self, - f: Any, + f: SupportsWrite[str], fieldnames: Collection[_T], - restval: Any | None = ..., - extrasaction: str = ..., - dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, + restval: Any | None = "", + extrasaction: Literal["raise", "ignore"] = "raise", + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, ) -> None: ... - if sys.version_info >= (3, 8): - def writeheader(self) -> Any: ... - else: - def writeheader(self) -> None: ... + def writeheader(self) -> Any: ... def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class Sniffer(object): +class Sniffer: preferred: list[str] - def __init__(self) -> None: ... - def sniff(self, sample: str, delimiters: str | None = ...) -> Type[Dialect]: ... + def sniff(self, sample: str, delimiters: str | None = None) -> type[Dialect]: ... def has_header(self, sample: str) -> bool: ... diff --git a/stdlib/ctypes/__init__.pyi b/stdlib/ctypes/__init__.pyi index 5cf8ce289148..7d133506af93 100644 --- a/stdlib/ctypes/__init__.pyi +++ b/stdlib/ctypes/__init__.pyi @@ -1,56 +1,102 @@ import sys -from _typeshed import ReadableBuffer, WriteableBuffer -from abc import abstractmethod -from typing import ( - Any, - Callable, - ClassVar, - Generic, - Iterable, - Iterator, - Mapping, - Optional, - Sequence, - Tuple, - Type, - TypeVar, - Union as _UnionT, - overload, +from _ctypes import ( + RTLD_GLOBAL as RTLD_GLOBAL, + RTLD_LOCAL as RTLD_LOCAL, + Array as Array, + CFuncPtr as _CFuncPtr, + Structure as Structure, + Union as Union, + _CanCastTo as _CanCastTo, + _CArgObject as _CArgObject, + _CData as _CData, + _CDataType as _CDataType, + _CField as _CField, + _CTypeBaseType, + _Pointer as _Pointer, + _PointerLike as _PointerLike, + _SimpleCData as _SimpleCData, + addressof as addressof, + alignment as alignment, + byref as byref, + get_errno as get_errno, + resize as resize, + set_errno as set_errno, + sizeof as sizeof, ) +from _typeshed import StrPath, SupportsBool, SupportsLen +from ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure +from types import GenericAlias +from typing import Any, ClassVar, Final, Generic, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated -if sys.version_info >= (3, 9): - from types import GenericAlias +if sys.platform == "win32": + from _ctypes import FormatError as FormatError, get_last_error as get_last_error, set_last_error as set_last_error + + if sys.version_info >= (3, 14): + from _ctypes import COMError as COMError, CopyComPointer as CopyComPointer + +if sys.version_info >= (3, 11): + from ctypes._endian import BigEndianUnion as BigEndianUnion, LittleEndianUnion as LittleEndianUnion -_T = TypeVar("_T") -_DLLT = TypeVar("_DLLT", bound=CDLL) _CT = TypeVar("_CT", bound=_CData) +_T = TypeVar("_T", default=Any) +_DLLT = TypeVar("_DLLT", bound=CDLL) + +if sys.version_info >= (3, 14): + @overload + @deprecated("ctypes.POINTER with string") + def POINTER(cls: str) -> type[Any]: ... + @overload + def POINTER(cls: None) -> type[c_void_p]: ... + @overload + def POINTER(cls: type[_CT]) -> type[_Pointer[_CT]]: ... + + def pointer(obj: _CT) -> _Pointer[_CT]: ... + +else: + from _ctypes import POINTER as POINTER, pointer as pointer + +if sys.version_info >= (3, 14): + CField = _CField + +DEFAULT_MODE: Final[int] + +class ArgumentError(Exception): ... -RTLD_GLOBAL: int -RTLD_LOCAL: int -DEFAULT_MODE: int +# defined within CDLL.__init__ +# Runtime name is ctypes.CDLL.__init__.._FuncPtr +@type_check_only +class _CDLLFuncPointer(_CFuncPtr): + _flags_: ClassVar[int] + _restype_: ClassVar[type[_CDataType]] -class CDLL(object): +# Not a real class; _CDLLFuncPointer with a __name__ set on it. +@type_check_only +class _NamedFuncPointer(_CDLLFuncPointer): + __name__: str + +if sys.version_info >= (3, 12): + _NameTypes: TypeAlias = StrPath | None +else: + _NameTypes: TypeAlias = str | None + +class CDLL: _func_flags_: ClassVar[int] - _func_restype_: ClassVar[_CData] + _func_restype_: ClassVar[type[_CDataType]] _name: str _handle: int - _FuncPtr: Type[_FuncPointer] - if sys.version_info >= (3, 8): - def __init__( - self, - name: str | None, - mode: int = ..., - handle: int | None = ..., - use_errno: bool = ..., - use_last_error: bool = ..., - winmode: int | None = ..., - ) -> None: ... - else: - def __init__( - self, name: str | None, mode: int = ..., handle: int | None = ..., use_errno: bool = ..., use_last_error: bool = ... - ) -> None: ... + _FuncPtr: type[_CDLLFuncPointer] + def __init__( + self, + name: _NameTypes, + mode: int = ..., + handle: int | None = None, + use_errno: bool = False, + use_last_error: bool = False, + winmode: int | None = None, + ) -> None: ... def __getattr__(self, name: str) -> _NamedFuncPointer: ... - def __getitem__(self, name: str) -> _NamedFuncPointer: ... + def __getitem__(self, name_or_ordinal: str) -> _NamedFuncPointer: ... if sys.platform == "win32": class OleDLL(CDLL): ... @@ -59,12 +105,11 @@ if sys.platform == "win32": class PyDLL(CDLL): ... class LibraryLoader(Generic[_DLLT]): - def __init__(self, dlltype: Type[_DLLT]) -> None: ... + def __init__(self, dlltype: type[_DLLT]) -> None: ... def __getattr__(self, name: str) -> _DLLT: ... def __getitem__(self, name: str) -> _DLLT: ... def LoadLibrary(self, name: str) -> _DLLT: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... cdll: LibraryLoader[CDLL] if sys.platform == "win32": @@ -73,238 +118,277 @@ if sys.platform == "win32": pydll: LibraryLoader[PyDLL] pythonapi: PyDLL -class _CDataMeta(type): - # By default mypy complains about the following two methods, because strictly speaking cls - # might not be a Type[_CT]. However this can never actually happen, because the only class that - # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here. - def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore[misc] - def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore[misc] - -class _CData(metaclass=_CDataMeta): - _b_base: int - _b_needsfree_: bool - _objects: Mapping[Any, int] | None - @classmethod - def from_buffer(cls: Type[_CT], source: WriteableBuffer, offset: int = ...) -> _CT: ... - @classmethod - def from_buffer_copy(cls: Type[_CT], source: ReadableBuffer, offset: int = ...) -> _CT: ... - @classmethod - def from_address(cls: Type[_CT], address: int) -> _CT: ... - @classmethod - def from_param(cls: Type[_CT], obj: Any) -> _CT | _CArgObject: ... - @classmethod - def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... +# Class definition within CFUNCTYPE / WINFUNCTYPE / PYFUNCTYPE +# Names at runtime are +# ctypes.CFUNCTYPE..CFunctionType +# ctypes.WINFUNCTYPE..WinFunctionType +# ctypes.PYFUNCTYPE..CFunctionType +@type_check_only +class _CFunctionType(_CFuncPtr): + _argtypes_: ClassVar[list[type[_CData | _CDataType]]] + _restype_: ClassVar[type[_CData | _CDataType] | None] + _flags_: ClassVar[int] -class _CanCastTo(_CData): ... -class _PointerLike(_CanCastTo): ... - -_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData] -_PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] - -class _FuncPointer(_PointerLike, _CData): - restype: Type[_CData] | Callable[[int], Any] | None - argtypes: Sequence[Type[_CData]] - errcheck: _ECT - @overload - def __init__(self, address: int) -> None: ... - @overload - def __init__(self, callable: Callable[..., Any]) -> None: ... - @overload - def __init__(self, func_spec: tuple[str | int, CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ... - @overload - def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - -class _NamedFuncPointer(_FuncPointer): - __name__: str - -class ArgumentError(Exception): ... +# Alias for either function pointer type +_FuncPointer: TypeAlias = _CDLLFuncPointer | _CFunctionType # noqa: Y047 # not used here def CFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... -) -> Type[_FuncPointer]: ... + restype: type[_CData | _CDataType] | None, + *argtypes: type[_CData | _CDataType], + use_errno: bool = False, + use_last_error: bool = False, +) -> type[_CFunctionType]: ... if sys.platform == "win32": def WINFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... - ) -> Type[_FuncPointer]: ... - -def PYFUNCTYPE(restype: Type[_CData] | None, *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... + restype: type[_CData | _CDataType] | None, + *argtypes: type[_CData | _CDataType], + use_errno: bool = False, + use_last_error: bool = False, + ) -> type[_CFunctionType]: ... -class _CArgObject: ... +def PYFUNCTYPE(restype: type[_CData | _CDataType] | None, *argtypes: type[_CData | _CDataType]) -> type[_CFunctionType]: ... # Any type that can be implicitly converted to c_void_p when passed as a C function argument. # (bytes is not included here, see below.) -_CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] +_CVoidPLike: TypeAlias = _PointerLike | Array[Any] | _CArgObject | int # Same as above, but including types known to be read-only (i. e. bytes). # This distinction is not strictly necessary (ctypes doesn't differentiate between const # and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) # when memmove(buf, b'foo', 4) was intended. -_CVoidConstPLike = _UnionT[_CVoidPLike, bytes] - -def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _CData | Type[_CData]) -> int: ... -def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... +_CVoidConstPLike: TypeAlias = _CVoidPLike | bytes _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _CData | _CArgObject | int, typ: Type[_CastT]) -> _CastT: ... -def create_string_buffer(init: int | bytes, size: int | None = ...) -> Array[c_char]: ... +def cast(obj: _CData | _CDataType | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... +def create_string_buffer(init: int | bytes, size: int | None = None) -> Array[c_char]: ... c_buffer = create_string_buffer -def create_unicode_buffer(init: int | str, size: int | None = ...) -> Array[c_wchar]: ... +def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: ... + +if sys.version_info < (3, 15): + @deprecated("Deprecated; removed in Python 3.15.") + def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ... + +@deprecated("Soft deprecated. Use multiplication instead.") +def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... if sys.platform == "win32": def DllCanUnloadNow() -> int: ... - def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented - def FormatError(code: int = ...) -> str: ... - def GetLastError() -> int: ... + def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO: not documented -def get_errno() -> int: ... + # Actually just an instance of _NamedFuncPointer (aka _CDLLFuncPointer), + # but we want to set a more specific __call__ + @type_check_only + class _GetLastErrorFunctionType(_NamedFuncPointer): + def __call__(self) -> int: ... -if sys.platform == "win32": - def get_last_error() -> int: ... - -def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ... -def memset(dst: _CVoidPLike, c: int, count: int) -> None: ... -def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... - -# The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like -# ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, -# it can be instantiated directly (to mimic the behavior of the real pointer function). -class pointer(Generic[_CT], _PointerLike, _CData): - _type_: Type[_CT] - contents: _CT - def __init__(self, arg: _CT = ...) -> None: ... - @overload - def __getitem__(self, i: int) -> _CT: ... - @overload - def __getitem__(self, s: slice) -> list[_CT]: ... - @overload - def __setitem__(self, i: int, o: _CT) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... + GetLastError: _GetLastErrorFunctionType -def resize(obj: _CData, size: int) -> None: ... -def set_errno(value: int) -> int: ... +# Actually just an instance of _CFunctionType, but we want to set a more +# specific __call__. +@type_check_only +class _MemmoveFunctionType(_CFunctionType): + def __call__(self, dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> int: ... -if sys.platform == "win32": - def set_last_error(value: int) -> int: ... +memmove: _MemmoveFunctionType + +# Actually just an instance of _CFunctionType, but we want to set a more +# specific __call__. +@type_check_only +class _MemsetFunctionType(_CFunctionType): + def __call__(self, dst: _CVoidPLike, c: int, count: int) -> int: ... + +memset: _MemsetFunctionType -def sizeof(obj_or_type: _CData | Type[_CData]) -> int: ... -def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... +def string_at(ptr: _CVoidConstPLike, size: int = -1) -> bytes: ... if sys.platform == "win32": - def WinError(code: int | None = ..., descr: str | None = ...) -> OSError: ... + def WinError(code: int | None = None, descr: str | None = None) -> OSError: ... -def wstring_at(address: _CVoidConstPLike, size: int = ...) -> str: ... +def wstring_at(ptr: _CVoidConstPLike, size: int = -1) -> str: ... -class _SimpleCData(Generic[_T], _CData): - value: _T - def __init__(self, value: _T = ...) -> None: ... +if sys.version_info >= (3, 14): + def memoryview_at(ptr: _CVoidConstPLike, size: int, readonly: bool = False) -> memoryview: ... -class c_byte(_SimpleCData[int]): ... +class py_object(_CanCastTo, _SimpleCData[_T]): + _type_: ClassVar[Literal["O"]] + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class c_bool(_SimpleCData[bool]): + _type_: ClassVar[Literal["?"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + def __init__(self, value: SupportsBool | SupportsLen | None = ...) -> None: ... + +class c_byte(_SimpleCData[int]): + _type_: ClassVar[Literal["b"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ubyte(_SimpleCData[int]): + _type_: ClassVar[Literal["B"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_short(_SimpleCData[int]): + _type_: ClassVar[Literal["h"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ushort(_SimpleCData[int]): + _type_: ClassVar[Literal["H"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_long(_SimpleCData[int]): + _type_: ClassVar[Literal["l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ulong(_SimpleCData[int]): + _type_: ClassVar[Literal["L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_int(_SimpleCData[int]): # can be an alias for c_long + _type_: ClassVar[Literal["i", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint(_SimpleCData[int]): # can be an alias for c_ulong + _type_: ClassVar[Literal["I", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_longlong(_SimpleCData[int]): # can be an alias for c_long + _type_: ClassVar[Literal["q", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ulonglong(_SimpleCData[int]): # can be an alias for c_ulong + _type_: ClassVar[Literal["Q", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +c_int8 = c_byte +c_uint8 = c_ubyte + +class c_int16(_SimpleCData[int]): # can be an alias for c_short or c_int + _type_: ClassVar[Literal["h", "i"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint16(_SimpleCData[int]): # can be an alias for c_ushort or c_uint + _type_: ClassVar[Literal["H", "I"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_int32(_SimpleCData[int]): # can be an alias for c_int or c_long + _type_: ClassVar[Literal["i", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint32(_SimpleCData[int]): # can be an alias for c_uint or c_ulong + _type_: ClassVar[Literal["I", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_int64(_SimpleCData[int]): # can be an alias for c_long or c_longlong + _type_: ClassVar[Literal["l", "q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint64(_SimpleCData[int]): # can be an alias for c_ulong or c_ulonglong + _type_: ClassVar[Literal["L", "Q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ssize_t(_SimpleCData[int]): # alias for c_int, c_long, or c_longlong + _type_: ClassVar[Literal["i", "l", "q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_size_t(_SimpleCData[int]): # alias for c_uint, c_ulong, or c_ulonglong + _type_: ClassVar[Literal["I", "L", "Q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_float(_SimpleCData[float]): + _type_: ClassVar[Literal["f"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_double(_SimpleCData[float]): + _type_: ClassVar[Literal["d"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_longdouble(_SimpleCData[float]): # can be an alias for c_double + _type_: ClassVar[Literal["d", "g"]] + +if sys.version_info >= (3, 14) and sys.platform != "win32": + # NOTE: currently (3.14.4) the `__ctype_{be,le}__` attributes of these complex types are missing at runtime: + # https://github.com/python/cpython/issues/148464 + + class c_double_complex(_SimpleCData[complex]): + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zd"]] + else: + _type_: ClassVar[Literal["D"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + + class c_float_complex(_SimpleCData[complex]): + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zf"]] + else: + _type_: ClassVar[Literal["F"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + + class c_longdouble_complex(_SimpleCData[complex]): + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zg"]] + else: + _type_: ClassVar[Literal["G"]] class c_char(_SimpleCData[bytes]): - def __init__(self, value: int | bytes = ...) -> None: ... + _type_: ClassVar[Literal["c"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + def __init__(self, value: int | bytes | bytearray = ...) -> None: ... -class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): +class c_char_p(_PointerLike, _SimpleCData[bytes | None]): + _type_: ClassVar[Literal["z"]] def __init__(self, value: int | bytes | None = ...) -> None: ... + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... -class c_double(_SimpleCData[float]): ... -class c_longdouble(_SimpleCData[float]): ... -class c_float(_SimpleCData[float]): ... -class c_int(_SimpleCData[int]): ... -class c_int8(_SimpleCData[int]): ... -class c_int16(_SimpleCData[int]): ... -class c_int32(_SimpleCData[int]): ... -class c_int64(_SimpleCData[int]): ... -class c_long(_SimpleCData[int]): ... -class c_longlong(_SimpleCData[int]): ... -class c_short(_SimpleCData[int]): ... -class c_size_t(_SimpleCData[int]): ... -class c_ssize_t(_SimpleCData[int]): ... -class c_ubyte(_SimpleCData[int]): ... -class c_uint(_SimpleCData[int]): ... -class c_uint8(_SimpleCData[int]): ... -class c_uint16(_SimpleCData[int]): ... -class c_uint32(_SimpleCData[int]): ... -class c_uint64(_SimpleCData[int]): ... -class c_ulong(_SimpleCData[int]): ... -class c_ulonglong(_SimpleCData[int]): ... -class c_ushort(_SimpleCData[int]): ... -class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ... -class c_wchar(_SimpleCData[str]): ... - -class c_wchar_p(_PointerLike, _SimpleCData[Optional[str]]): - def __init__(self, value: int | str | None = ...) -> None: ... +class c_void_p(_PointerLike, _SimpleCData[int | None]): + _type_: ClassVar[Literal["P"]] + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... -class c_bool(_SimpleCData[bool]): - def __init__(self, value: bool = ...) -> None: ... +c_voidp = c_void_p # backwards compatibility (to a bug) + +class c_wchar(_SimpleCData[str]): + _type_: ClassVar[Literal["u"]] + +class c_wchar_p(_PointerLike, _SimpleCData[str | None]): + _type_: ClassVar[Literal["Z"]] + def __init__(self, value: int | str | None = ...) -> None: ... + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... if sys.platform == "win32": - class HRESULT(_SimpleCData[int]): ... # TODO undocumented - -class py_object(_CanCastTo, _SimpleCData[_T]): ... - -class _CField: - offset: int - size: int - -class _StructUnionMeta(_CDataMeta): - _fields_: Sequence[tuple[str, Type[_CData]] | tuple[str, Type[_CData], int]] - _pack_: int - _anonymous_: Sequence[str] - def __getattr__(self, name: str) -> _CField: ... - -class _StructUnionBase(_CData, metaclass=_StructUnionMeta): - def __init__(self, *args: Any, **kw: Any) -> None: ... - def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - -class Union(_StructUnionBase): ... -class Structure(_StructUnionBase): ... -class BigEndianStructure(Structure): ... -class LittleEndianStructure(Structure): ... - -class Array(Generic[_CT], _CData): - @property - @abstractmethod - def _length_(self) -> int: ... - @_length_.setter - def _length_(self, value: int) -> None: ... - @property - @abstractmethod - def _type_(self) -> Type[_CT]: ... - @_type_.setter - def _type_(self, value: Type[_CT]) -> None: ... - raw: bytes # Note: only available if _CT == c_char - value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise - # TODO These methods cannot be annotated correctly at the moment. - # All of these "Any"s stand for the array's element type, but it's not possible to use _CT - # here, because of a special feature of ctypes. - # By default, when accessing an element of an Array[_CT], the returned object has type _CT. - # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object - # and converts it to the corresponding Python primitive. For example, when accessing an element - # of an Array[c_int], a Python int object is returned, not a c_int. - # This behavior does *not* apply to subclasses of "simple types". - # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns - # a MyInt, not an int. - # This special behavior is not easy to model in a stub, so for now all places where - # the array element type would belong are annotated with Any instead. - def __init__(self, *args: Any) -> None: ... - @overload - def __getitem__(self, i: int) -> Any: ... - @overload - def __getitem__(self, s: slice) -> list[Any]: ... - @overload - def __setitem__(self, i: int, o: Any) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ... - def __iter__(self) -> Iterator[Any]: ... - # Can't inherit from Sized because the metaclass conflict between - # Sized and _CData prevents using _CDataMeta. - def __len__(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + class HRESULT(_SimpleCData[int]): # TODO: undocumented + _type_: ClassVar[Literal["l"]] + +if sys.version_info >= (3, 12): + # At runtime, this is an alias for either c_int32 or c_int64, + # which are themselves an alias for one of c_int, c_long, or c_longlong + # This covers all our bases. + c_time_t: type[c_int32 | c_int64 | c_int | c_long | c_longlong] diff --git a/stdlib/ctypes/_endian.pyi b/stdlib/ctypes/_endian.pyi new file mode 100644 index 000000000000..97852f67aa6e --- /dev/null +++ b/stdlib/ctypes/_endian.pyi @@ -0,0 +1,16 @@ +import sys +from ctypes import Structure, Union + +# At runtime, the native endianness is an alias for Structure, +# while the other is a subclass with a metaclass added in. +class BigEndianStructure(Structure): + __slots__ = () + +class LittleEndianStructure(Structure): ... + +# Same thing for these: one is an alias of Union at runtime +if sys.version_info >= (3, 11): + class BigEndianUnion(Union): + __slots__ = () + + class LittleEndianUnion(Union): ... diff --git a/stdlib/ctypes/macholib/__init__.pyi b/stdlib/ctypes/macholib/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stdlib/ctypes/macholib/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stdlib/ctypes/macholib/dyld.pyi b/stdlib/ctypes/macholib/dyld.pyi new file mode 100644 index 000000000000..c7e94daa2149 --- /dev/null +++ b/stdlib/ctypes/macholib/dyld.pyi @@ -0,0 +1,8 @@ +from collections.abc import Mapping +from ctypes.macholib.dylib import dylib_info as dylib_info +from ctypes.macholib.framework import framework_info as framework_info + +__all__ = ["dyld_find", "framework_find", "framework_info", "dylib_info"] + +def dyld_find(name: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: ... +def framework_find(fn: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: ... diff --git a/stdlib/ctypes/macholib/dylib.pyi b/stdlib/ctypes/macholib/dylib.pyi new file mode 100644 index 000000000000..95945edfd155 --- /dev/null +++ b/stdlib/ctypes/macholib/dylib.pyi @@ -0,0 +1,14 @@ +from typing import TypedDict, type_check_only + +__all__ = ["dylib_info"] + +# Actual result is produced by re.match.groupdict() +@type_check_only +class _DylibInfo(TypedDict): + location: str + name: str + shortname: str + version: str | None + suffix: str | None + +def dylib_info(filename: str) -> _DylibInfo | None: ... diff --git a/stdlib/ctypes/macholib/framework.pyi b/stdlib/ctypes/macholib/framework.pyi new file mode 100644 index 000000000000..e92bf3700e84 --- /dev/null +++ b/stdlib/ctypes/macholib/framework.pyi @@ -0,0 +1,14 @@ +from typing import TypedDict, type_check_only + +__all__ = ["framework_info"] + +# Actual result is produced by re.match.groupdict() +@type_check_only +class _FrameworkInfo(TypedDict): + location: str + name: str + shortname: str + version: str | None + suffix: str | None + +def framework_info(filename: str) -> _FrameworkInfo | None: ... diff --git a/stdlib/ctypes/util.pyi b/stdlib/ctypes/util.pyi index c0274f5e539b..4f18c1d8db34 100644 --- a/stdlib/ctypes/util.pyi +++ b/stdlib/ctypes/util.pyi @@ -4,3 +4,8 @@ def find_library(name: str) -> str | None: ... if sys.platform == "win32": def find_msvcrt() -> str | None: ... + +if sys.version_info >= (3, 14): + def dllist() -> list[str]: ... + +def test() -> None: ... diff --git a/stdlib/ctypes/wintypes.pyi b/stdlib/ctypes/wintypes.pyi index c178a9bdf936..b94c5e74148a 100644 --- a/stdlib/ctypes/wintypes.pyi +++ b/stdlib/ctypes/wintypes.pyi @@ -1,8 +1,10 @@ +import sys +from _ctypes import _CArgObject, _CField from ctypes import ( Array, Structure, + _Pointer, _SimpleCData, - c_byte, c_char, c_char_p, c_double, @@ -18,10 +20,19 @@ from ctypes import ( c_void_p, c_wchar, c_wchar_p, - pointer, ) +from typing import Any, Final, TypeAlias, TypeVar +from typing_extensions import Self + +if sys.version_info >= (3, 12): + from ctypes import c_ubyte + + BYTE = c_ubyte +else: + from ctypes import c_byte + + BYTE = c_byte -BYTE = c_byte WORD = c_ushort DWORD = c_ulong CHAR = c_char @@ -72,6 +83,15 @@ HACCEL = HANDLE HBITMAP = HANDLE HBRUSH = HANDLE HCOLORSPACE = HANDLE +if sys.version_info >= (3, 14): + HCONV = HANDLE + HCONVLIST = HANDLE + HCURSOR = HANDLE + HDDEDATA = HANDLE + HDROP = HANDLE + HFILE = INT + HRESULT = LONG + HSZ = HANDLE HDC = HANDLE HDESK = HANDLE HDWP = HANDLE @@ -100,39 +120,42 @@ HWND = HANDLE SC_HANDLE = HANDLE SERVICE_STATUS_HANDLE = HANDLE +_CIntLikeT = TypeVar("_CIntLikeT", bound=_SimpleCData[int]) +_CIntLikeField: TypeAlias = _CField[_CIntLikeT, int, _CIntLikeT | int] + class RECT(Structure): - left: LONG - top: LONG - right: LONG - bottom: LONG + left: _CIntLikeField[LONG] + top: _CIntLikeField[LONG] + right: _CIntLikeField[LONG] + bottom: _CIntLikeField[LONG] RECTL = RECT _RECTL = RECT tagRECT = RECT class _SMALL_RECT(Structure): - Left: SHORT - Top: SHORT - Right: SHORT - Bottom: SHORT + Left: _CIntLikeField[SHORT] + Top: _CIntLikeField[SHORT] + Right: _CIntLikeField[SHORT] + Bottom: _CIntLikeField[SHORT] SMALL_RECT = _SMALL_RECT class _COORD(Structure): - X: SHORT - Y: SHORT + X: _CIntLikeField[SHORT] + Y: _CIntLikeField[SHORT] class POINT(Structure): - x: LONG - y: LONG + x: _CIntLikeField[LONG] + y: _CIntLikeField[LONG] POINTL = POINT _POINTL = POINT tagPOINT = POINT class SIZE(Structure): - cx: LONG - cy: LONG + cx: _CIntLikeField[LONG] + cy: _CIntLikeField[LONG] SIZEL = SIZE tagSIZE = SIZE @@ -140,95 +163,159 @@ tagSIZE = SIZE def RGB(red: int, green: int, blue: int) -> int: ... class FILETIME(Structure): - dwLowDateTime: DWORD - dwHighDateTime: DWORD + dwLowDateTime: _CIntLikeField[DWORD] + dwHighDateTime: _CIntLikeField[DWORD] _FILETIME = FILETIME class MSG(Structure): - hWnd: HWND - message: UINT - wParam: WPARAM - lParam: LPARAM - time: DWORD - pt: POINT + hWnd: _CField[HWND, int | None, HWND | int | None] + message: _CIntLikeField[UINT] + wParam: _CIntLikeField[WPARAM] + lParam: _CIntLikeField[LPARAM] + time: _CIntLikeField[DWORD] + pt: _CField[POINT, POINT, POINT] tagMSG = MSG -MAX_PATH: int +MAX_PATH: Final = 260 class WIN32_FIND_DATAA(Structure): - dwFileAttributes: DWORD - ftCreationTime: FILETIME - ftLastAccessTime: FILETIME - ftLastWriteTime: FILETIME - nFileSizeHigh: DWORD - nFileSizeLow: DWORD - dwReserved0: DWORD - dwReserved1: DWORD - cFileName: Array[CHAR] - cAlternateFileName: Array[CHAR] + dwFileAttributes: _CIntLikeField[DWORD] + ftCreationTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME] + nFileSizeHigh: _CIntLikeField[DWORD] + nFileSizeLow: _CIntLikeField[DWORD] + dwReserved0: _CIntLikeField[DWORD] + dwReserved1: _CIntLikeField[DWORD] + cFileName: _CField[Array[CHAR], bytes, bytes] + cAlternateFileName: _CField[Array[CHAR], bytes, bytes] class WIN32_FIND_DATAW(Structure): - dwFileAttributes: DWORD - ftCreationTime: FILETIME - ftLastAccessTime: FILETIME - ftLastWriteTime: FILETIME - nFileSizeHigh: DWORD - nFileSizeLow: DWORD - dwReserved0: DWORD - dwReserved1: DWORD - cFileName: Array[WCHAR] - cAlternateFileName: Array[WCHAR] - -# These pointer type definitions use pointer[...] instead of POINTER(...), to allow them -# to be used in type annotations. -PBOOL = pointer[BOOL] -LPBOOL = pointer[BOOL] -PBOOLEAN = pointer[BOOLEAN] -PBYTE = pointer[BYTE] -LPBYTE = pointer[BYTE] -PCHAR = pointer[CHAR] -LPCOLORREF = pointer[COLORREF] -PDWORD = pointer[DWORD] -LPDWORD = pointer[DWORD] -PFILETIME = pointer[FILETIME] -LPFILETIME = pointer[FILETIME] -PFLOAT = pointer[FLOAT] -PHANDLE = pointer[HANDLE] -LPHANDLE = pointer[HANDLE] -PHKEY = pointer[HKEY] -LPHKL = pointer[HKL] -PINT = pointer[INT] -LPINT = pointer[INT] -PLARGE_INTEGER = pointer[LARGE_INTEGER] -PLCID = pointer[LCID] -PLONG = pointer[LONG] -LPLONG = pointer[LONG] -PMSG = pointer[MSG] -LPMSG = pointer[MSG] -PPOINT = pointer[POINT] -LPPOINT = pointer[POINT] -PPOINTL = pointer[POINTL] -PRECT = pointer[RECT] -LPRECT = pointer[RECT] -PRECTL = pointer[RECTL] -LPRECTL = pointer[RECTL] -LPSC_HANDLE = pointer[SC_HANDLE] -PSHORT = pointer[SHORT] -PSIZE = pointer[SIZE] -LPSIZE = pointer[SIZE] -PSIZEL = pointer[SIZEL] -LPSIZEL = pointer[SIZEL] -PSMALL_RECT = pointer[SMALL_RECT] -PUINT = pointer[UINT] -LPUINT = pointer[UINT] -PULARGE_INTEGER = pointer[ULARGE_INTEGER] -PULONG = pointer[ULONG] -PUSHORT = pointer[USHORT] -PWCHAR = pointer[WCHAR] -PWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] -LPWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] -PWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] -LPWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] -PWORD = pointer[WORD] -LPWORD = pointer[WORD] + dwFileAttributes: _CIntLikeField[DWORD] + ftCreationTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME] + nFileSizeHigh: _CIntLikeField[DWORD] + nFileSizeLow: _CIntLikeField[DWORD] + dwReserved0: _CIntLikeField[DWORD] + dwReserved1: _CIntLikeField[DWORD] + cFileName: _CField[Array[WCHAR], str, str] + cAlternateFileName: _CField[Array[WCHAR], str, str] + +# These are all defined with the POINTER() function, which keeps a cache and will +# return a previously created class if it can. The self-reported __name__ +# of these classes is f"LP_{typ.__name__}", where typ is the original class +# passed in to the POINTER() function. + +# LP_c_short +class PSHORT(_Pointer[SHORT]): ... + +# LP_c_ushort +class PUSHORT(_Pointer[USHORT]): ... + +PWORD = PUSHORT +LPWORD = PUSHORT + +# LP_c_long +class PLONG(_Pointer[LONG]): ... + +LPLONG = PLONG +PBOOL = PLONG +LPBOOL = PLONG + +# LP_c_ulong +class PULONG(_Pointer[ULONG]): ... + +PDWORD = PULONG +LPDWORD = PDWORD +LPCOLORREF = PDWORD +PLCID = PDWORD + +# LP_c_int (or LP_c_long if int and long have the same size) +class PINT(_Pointer[INT]): ... + +LPINT = PINT + +# LP_c_uint (or LP_c_ulong if int and long have the same size) +class PUINT(_Pointer[UINT]): ... + +LPUINT = PUINT + +# LP_c_float +class PFLOAT(_Pointer[FLOAT]): ... + +# LP_c_longlong (or LP_c_long if long and long long have the same size) +class PLARGE_INTEGER(_Pointer[LARGE_INTEGER]): ... + +# LP_c_ulonglong (or LP_c_ulong if long and long long have the same size) +class PULARGE_INTEGER(_Pointer[ULARGE_INTEGER]): ... + +# LP_c_byte types +class PBYTE(_Pointer[BYTE]): ... + +LPBYTE = PBYTE +PBOOLEAN = PBYTE + +# LP_c_char +class PCHAR(_Pointer[CHAR]): + # this is inherited from ctypes.c_char_p, kind of. + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +# LP_c_wchar +class PWCHAR(_Pointer[WCHAR]): + # inherited from ctypes.c_wchar_p, kind of + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +# LP_c_void_p +class PHANDLE(_Pointer[HANDLE]): ... + +LPHANDLE = PHANDLE +PHKEY = PHANDLE +LPHKL = PHANDLE +LPSC_HANDLE = PHANDLE + +# LP_FILETIME +class PFILETIME(_Pointer[FILETIME]): ... + +LPFILETIME = PFILETIME + +# LP_MSG +class PMSG(_Pointer[MSG]): ... + +LPMSG = PMSG + +# LP_POINT +class PPOINT(_Pointer[POINT]): ... + +LPPOINT = PPOINT +PPOINTL = PPOINT + +# LP_RECT +class PRECT(_Pointer[RECT]): ... + +LPRECT = PRECT +PRECTL = PRECT +LPRECTL = PRECT + +# LP_SIZE +class PSIZE(_Pointer[SIZE]): ... + +LPSIZE = PSIZE +PSIZEL = PSIZE +LPSIZEL = PSIZE + +# LP__SMALL_RECT +class PSMALL_RECT(_Pointer[SMALL_RECT]): ... + +# LP_WIN32_FIND_DATAA +class PWIN32_FIND_DATAA(_Pointer[WIN32_FIND_DATAA]): ... + +LPWIN32_FIND_DATAA = PWIN32_FIND_DATAA + +# LP_WIN32_FIND_DATAW +class PWIN32_FIND_DATAW(_Pointer[WIN32_FIND_DATAW]): ... + +LPWIN32_FIND_DATAW = PWIN32_FIND_DATAW diff --git a/stdlib/curses/__init__.pyi b/stdlib/curses/__init__.pyi index 73e84fba3763..cf5048110878 100644 --- a/stdlib/curses/__init__.pyi +++ b/stdlib/curses/__init__.pyi @@ -1,15 +1,38 @@ -from _curses import * # noqa: F403 -from _curses import _CursesWindow as _CursesWindow -from typing import Any, Callable, TypeVar +from _curses import * +from _curses import window as window +from _typeshed import structseq +from collections.abc import Callable +from typing import Concatenate, Final, ParamSpec, TypeVar, final, type_check_only + +# NOTE: The _curses module is ordinarily only available on Unix, but the +# windows-curses package makes it available on Windows as well with the same +# contents. _T = TypeVar("_T") +_P = ParamSpec("_P") # available after calling `curses.initscr()` +# not `Final` as it can change during the terminal resize: LINES: int COLS: int # available after calling `curses.start_color()` -COLORS: int -COLOR_PAIRS: int +COLORS: Final[int] +COLOR_PAIRS: Final[int] + +def wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: ... + +# At runtime this class is unexposed and calls itself curses.ncurses_version. +# That name would conflict with the actual curses.ncurses_version, which is +# an instance of this class. +@final +@type_check_only +class _ncurses_version(structseq[int], tuple[int, int, int]): + __match_args__: Final = ("major", "minor", "patch") -def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def patch(self) -> int: ... diff --git a/stdlib/curses/ascii.pyi b/stdlib/curses/ascii.pyi index 66efbe36a7df..0234434b8c3d 100644 --- a/stdlib/curses/ascii.pyi +++ b/stdlib/curses/ascii.pyi @@ -1,45 +1,45 @@ -from typing import TypeVar +from typing import Final, TypeVar _CharT = TypeVar("_CharT", str, int) -NUL: int -SOH: int -STX: int -ETX: int -EOT: int -ENQ: int -ACK: int -BEL: int -BS: int -TAB: int -HT: int -LF: int -NL: int -VT: int -FF: int -CR: int -SO: int -SI: int -DLE: int -DC1: int -DC2: int -DC3: int -DC4: int -NAK: int -SYN: int -ETB: int -CAN: int -EM: int -SUB: int -ESC: int -FS: int -GS: int -RS: int -US: int -SP: int -DEL: int +NUL: Final = 0x00 +SOH: Final = 0x01 +STX: Final = 0x02 +ETX: Final = 0x03 +EOT: Final = 0x04 +ENQ: Final = 0x05 +ACK: Final = 0x06 +BEL: Final = 0x07 +BS: Final = 0x08 +TAB: Final = 0x09 +HT: Final = 0x09 +LF: Final = 0x0A +NL: Final = 0x0A +VT: Final = 0x0B +FF: Final = 0x0C +CR: Final = 0x0D +SO: Final = 0x0E +SI: Final = 0x0F +DLE: Final = 0x10 +DC1: Final = 0x11 +DC2: Final = 0x12 +DC3: Final = 0x13 +DC4: Final = 0x14 +NAK: Final = 0x15 +SYN: Final = 0x16 +ETB: Final = 0x17 +CAN: Final = 0x18 +EM: Final = 0x19 +SUB: Final = 0x1A +ESC: Final = 0x1B +FS: Final = 0x1C +GS: Final = 0x1D +RS: Final = 0x1E +US: Final = 0x1F +SP: Final = 0x20 +DEL: Final = 0x7F -controlnames: list[int] +controlnames: Final[list[int]] def isalnum(c: str | int) -> bool: ... def isalpha(c: str | int) -> bool: ... diff --git a/stdlib/curses/has_key.pyi b/stdlib/curses/has_key.pyi new file mode 100644 index 000000000000..3811060b916a --- /dev/null +++ b/stdlib/curses/has_key.pyi @@ -0,0 +1 @@ +def has_key(ch: int | str) -> bool: ... diff --git a/stdlib/curses/panel.pyi b/stdlib/curses/panel.pyi index e61d7bdcf64d..861559d38bc5 100644 --- a/stdlib/curses/panel.pyi +++ b/stdlib/curses/panel.pyi @@ -1,22 +1 @@ -from _curses import _CursesWindow - -version: str - -class _Curses_Panel: # type is (note the space in the class name) - def above(self) -> _Curses_Panel: ... - def below(self) -> _Curses_Panel: ... - def bottom(self) -> None: ... - def hidden(self) -> bool: ... - def hide(self) -> None: ... - def move(self, y: int, x: int) -> None: ... - def replace(self, win: _CursesWindow) -> None: ... - def set_userptr(self, obj: object) -> None: ... - def show(self) -> None: ... - def top(self) -> None: ... - def userptr(self) -> object: ... - def window(self) -> _CursesWindow: ... - -def bottom_panel() -> _Curses_Panel: ... -def new_panel(__win: _CursesWindow) -> _Curses_Panel: ... -def top_panel() -> _Curses_Panel: ... -def update_panels() -> _Curses_Panel: ... +from _curses_panel import * diff --git a/stdlib/curses/textpad.pyi b/stdlib/curses/textpad.pyi index 578a579fda38..48ef67c9d85f 100644 --- a/stdlib/curses/textpad.pyi +++ b/stdlib/curses/textpad.pyi @@ -1,11 +1,11 @@ -from _curses import _CursesWindow -from typing import Callable +from _curses import window +from collections.abc import Callable -def rectangle(win: _CursesWindow, uly: int, ulx: int, lry: int, lrx: int) -> None: ... +def rectangle(win: window, uly: int, ulx: int, lry: int, lrx: int) -> None: ... class Textbox: stripspaces: bool - def __init__(self, win: _CursesWindow, insert_mode: bool = ...) -> None: ... - def edit(self, validate: Callable[[int], int] | None = ...) -> str: ... + def __init__(self, win: window, insert_mode: bool = False) -> None: ... + def edit(self, validate: Callable[[int], int] | None = None) -> str: ... def do_command(self, ch: str | int) -> None: ... def gather(self) -> str: ... diff --git a/stdlib/dataclasses.pyi b/stdlib/dataclasses.pyi index 6dfe83c2d4a8..abe1f8457434 100644 --- a/stdlib/dataclasses.pyi +++ b/stdlib/dataclasses.pyi @@ -1,85 +1,191 @@ +import enum import sys import types -from typing import Any, Callable, Generic, Iterable, Mapping, Protocol, Tuple, Type, TypeVar, overload - -if sys.version_info >= (3, 9): - from types import GenericAlias +from _typeshed import DataclassInstance +from builtins import type as Type # alias to avoid name clashes with fields named "type" +from collections.abc import Callable, Iterable, Mapping +from types import GenericAlias +from typing import Any, Final, Generic, Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Never, TypeIs _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -class _MISSING_TYPE: ... +__all__ = [ + "dataclass", + "field", + "Field", + "FrozenInstanceError", + "InitVar", + "KW_ONLY", + "MISSING", + "fields", + "asdict", + "astuple", + "make_dataclass", + "replace", + "is_dataclass", +] + +_DataclassT = TypeVar("_DataclassT", bound=DataclassInstance) + +@type_check_only +class _DataclassFactory(Protocol): + def __call__( + self, + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type[_T]: ... + +# define _MISSING_TYPE as an enum within the type stubs, +# even though that is not really its type at runtime +# this allows us to use Literal[_MISSING_TYPE.MISSING] +# for background, see: +# https://github.com/python/typeshed/pull/5900#issuecomment-895513797 +class _MISSING_TYPE(enum.Enum): + MISSING = enum.auto() -MISSING: _MISSING_TYPE +MISSING: Final = _MISSING_TYPE.MISSING -if sys.version_info >= (3, 10): - class KW_ONLY: ... +class KW_ONLY: ... @overload -def asdict(obj: Any) -> dict[str, Any]: ... +def asdict(obj: DataclassInstance) -> dict[str, Any]: ... @overload -def asdict(obj: Any, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... +def asdict(obj: DataclassInstance, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... + @overload -def astuple(obj: Any) -> Tuple[Any, ...]: ... +def astuple(obj: DataclassInstance) -> tuple[Any, ...]: ... @overload -def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... +def astuple(obj: DataclassInstance, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... -if sys.version_info >= (3, 10): - @overload - def dataclass(__cls: Type[_T]) -> Type[_T]: ... - @overload - def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... +if sys.version_info >= (3, 11): @overload def dataclass( + cls: type[_T], + /, *, - init: bool = ..., - repr: bool = ..., - eq: bool = ..., - order: bool = ..., - unsafe_hash: bool = ..., - frozen: bool = ..., - match_args: bool = ..., - kw_only: bool = ..., - slots: bool = ..., - ) -> Callable[[Type[_T]], Type[_T]]: ... - -elif sys.version_info >= (3, 8): - # cls argument is now positional-only - @overload - def dataclass(__cls: Type[_T]) -> Type[_T]: ... - @overload - def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type[_T]: ... @overload def dataclass( - *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... - ) -> Callable[[Type[_T]], Type[_T]]: ... - + cls: None = None, + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> Callable[[type[_T]], type[_T]]: ... else: @overload - def dataclass(_cls: Type[_T]) -> Type[_T]: ... - @overload - def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + def dataclass( + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + ) -> type[_T]: ... @overload def dataclass( - *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... - ) -> Callable[[Type[_T]], Type[_T]]: ... + cls: None = None, + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + ) -> Callable[[type[_T]], type[_T]]: ... # See https://github.com/python/mypy/issues/10750 +@type_check_only class _DefaultFactory(Protocol[_T_co]): def __call__(self) -> _T_co: ... class Field(Generic[_T]): + if sys.version_info >= (3, 14): + __slots__ = ( + "name", + "type", + "default", + "default_factory", + "repr", + "hash", + "init", + "compare", + "metadata", + "kw_only", + "doc", + "_field_type", + ) + else: + __slots__ = ( + "name", + "type", + "default", + "default_factory", + "repr", + "hash", + "init", + "compare", + "metadata", + "kw_only", + "_field_type", + ) name: str - type: Type[_T] - default: _T - default_factory: _DefaultFactory[_T] + type: Type[_T] | str | Any + default: _T | Literal[_MISSING_TYPE.MISSING] + default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING] repr: bool hash: bool | None init: bool compare: bool metadata: types.MappingProxyType[Any, Any] - if sys.version_info >= (3, 10): - kw_only: bool + + if sys.version_info >= (3, 14): + doc: str | None + + kw_only: bool | Literal[_MISSING_TYPE.MISSING] + + if sys.version_info >= (3, 14): def __init__( self, default: _T, @@ -90,6 +196,7 @@ class Field(Generic[_T]): compare: bool, metadata: Mapping[Any, Any], kw_only: bool, + doc: str | None, ) -> None: ... else: def __init__( @@ -101,122 +208,194 @@ class Field(Generic[_T]): hash: bool | None, compare: bool, metadata: Mapping[Any, Any], + kw_only: bool, ) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + + def __set_name__(self, owner: Type[Any], name: str) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # NOTE: Actual return type is 'Field[_T]', but we want to help type checkers # to understand the magic that happens at runtime. -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 14): @overload # `default` and `default_factory` are optional and mutually exclusive. def field( *, default: _T, - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[Any, Any] | None = ..., - kw_only: bool = ..., + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + doc: str | None = None, ) -> _T: ... @overload def field( *, + default: Literal[_MISSING_TYPE.MISSING] = ..., default_factory: Callable[[], _T], - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[Any, Any] | None = ..., - kw_only: bool = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + doc: str | None = None, ) -> _T: ... @overload def field( *, - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[Any, Any] | None = ..., - kw_only: bool = ..., + default: Literal[_MISSING_TYPE.MISSING] = ..., + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + doc: str | None = None, ) -> Any: ... - else: @overload # `default` and `default_factory` are optional and mutually exclusive. def field( *, default: _T, - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[Any, Any] | None = ..., + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., ) -> _T: ... @overload def field( *, + default: Literal[_MISSING_TYPE.MISSING] = ..., default_factory: Callable[[], _T], - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[Any, Any] | None = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., ) -> _T: ... @overload def field( *, - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[Any, Any] | None = ..., + default: Literal[_MISSING_TYPE.MISSING] = ..., + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., ) -> Any: ... -def fields(class_or_instance: Any) -> Tuple[Field[Any], ...]: ... -def is_dataclass(obj: Any) -> bool: ... +def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ... + +# HACK: `obj: Never` typing matches if object argument is using `Any` type. +@overload +def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-type-guard-definition] # pyrefly: ignore [bad-function-definition] +@overload +def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ... +@overload +def is_dataclass(obj: object) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... class FrozenInstanceError(AttributeError): ... class InitVar(Generic[_T]): - type: Type[_T] + __slots__ = ("type",) + type: Type[_T] # ty:ignore[unbound-type-variable] def __init__(self, type: Type[_T]) -> None: ... - if sys.version_info >= (3, 9): - @overload - def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... - @overload - def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... -if sys.version_info >= (3, 10): + @overload + def __class_getitem__( + cls, type: Type[_T] + ) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] # ty:ignore[invalid-type-form] + @overload + def __class_getitem__( + cls, type: Any + ) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] # ty:ignore[invalid-type-form] + +if sys.version_info >= (3, 14): + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], + *, + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + module: str | None = None, + decorator: _DataclassFactory = ..., + ) -> type: ... + +elif sys.version_info >= (3, 12): + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], + *, + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + module: str | None = None, + ) -> type: ... + +elif sys.version_info >= (3, 11): def make_dataclass( cls_name: str, - fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], *, - bases: Tuple[type, ...] = ..., - namespace: dict[str, Any] | None = ..., - init: bool = ..., - repr: bool = ..., - eq: bool = ..., - order: bool = ..., - unsafe_hash: bool = ..., - frozen: bool = ..., - match_args: bool = ..., - kw_only: bool = ..., - slots: bool = ..., + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, ) -> type: ... else: def make_dataclass( cls_name: str, - fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], *, - bases: Tuple[type, ...] = ..., - namespace: dict[str, Any] | None = ..., - init: bool = ..., - repr: bool = ..., - eq: bool = ..., - order: bool = ..., - unsafe_hash: bool = ..., - frozen: bool = ..., + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, ) -> type: ... -def replace(__obj: _T, **changes: Any) -> _T: ... +def replace(obj: _DataclassT, /, **changes: Any) -> _DataclassT: ... diff --git a/stdlib/datetime.pyi b/stdlib/datetime.pyi index e0ce085c2967..0a21f72b09de 100644 --- a/stdlib/datetime.pyi +++ b/stdlib/datetime.pyi @@ -1,54 +1,78 @@ import sys +from abc import abstractmethod from time import struct_time -from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, Type, TypeVar, overload -from typing_extensions import final +from typing import ClassVar, Final, SupportsIndex, TypeAlias, final, overload, type_check_only +from typing_extensions import CapsuleType, Never, Self, deprecated, disjoint_base -_S = TypeVar("_S") -_D = TypeVar("_D", bound=date) +if sys.version_info >= (3, 11): + __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") +else: + __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") -MINYEAR: int -MAXYEAR: int +MINYEAR: Final = 1 +MAXYEAR: Final = 9999 class tzinfo: - def tzname(self, __dt: datetime | None) -> str | None: ... - def utcoffset(self, __dt: datetime | None) -> timedelta | None: ... - def dst(self, __dt: datetime | None) -> timedelta | None: ... - def fromutc(self, __dt: datetime) -> datetime: ... + @abstractmethod + def tzname(self, dt: datetime | None, /) -> str | None: ... + @abstractmethod + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... + @abstractmethod + def dst(self, dt: datetime | None, /) -> timedelta | None: ... + def fromutc(self, dt: datetime, /) -> datetime: ... # Alias required to avoid name conflicts with date(time).tzinfo. -_tzinfo = tzinfo +_TzInfo: TypeAlias = tzinfo @final class timezone(tzinfo): utc: ClassVar[timezone] min: ClassVar[timezone] max: ClassVar[timezone] - def __init__(self, offset: timedelta, name: str = ...) -> None: ... + def __new__(cls, offset: timedelta, name: str = ...) -> Self: ... + def tzname(self, dt: datetime | None, /) -> str: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta: ... + def dst(self, dt: datetime | None, /) -> None: ... def __hash__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... -if sys.version_info >= (3, 9): - class _IsoCalendarDate(NamedTuple): - year: int - week: int - weekday: int +if sys.version_info >= (3, 11): + UTC: timezone +# This class calls itself datetime.IsoCalendarDate. It's neither +# NamedTuple nor structseq. +@final +@type_check_only +class _IsoCalendarDate(tuple[int, int, int]): + @property + def year(self) -> int: ... + @property + def week(self) -> int: ... + @property + def weekday(self) -> int: ... + +@disjoint_base class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... + def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ... @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... + def fromtimestamp(cls, timestamp: float, /) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], __n: int) -> _S: ... - if sys.version_info >= (3, 7): + def fromordinal(cls, n: int, /) -> Self: ... + + if sys.version_info >= (3, 15): @classmethod - def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... - if sys.version_info >= (3, 8): + def fromisoformat(cls, string: str, /) -> Self: ... + else: @classmethod - def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ... + def fromisoformat(cls, date_string: str, /) -> Self: ... + + @classmethod + def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ... @property def year(self) -> int: ... @property @@ -56,57 +80,66 @@ class date: @property def day(self) -> int: ... def ctime(self) -> str: ... - def strftime(self, __format: str) -> str: ... - def __format__(self, __fmt: str) -> str: ... + + if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + + # On <3.12, the name of the parameter in the pure-Python implementation + # didn't match the name in the C implementation, + # meaning it is only *safe* to pass it as a keyword argument on 3.12+ + if sys.version_info >= (3, 12): + def strftime(self, format: str) -> str: ... + else: + def strftime(self, format: str, /) -> str: ... + + def __format__(self, fmt: str, /) -> str: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... - def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... - def __le__(self, __other: date) -> bool: ... - def __lt__(self, __other: date) -> bool: ... - def __ge__(self, __other: date) -> bool: ... - def __gt__(self, __other: date) -> bool: ... - if sys.version_info >= (3, 8): - def __add__(self: _S, __other: timedelta) -> _S: ... - def __radd__(self: _S, __other: timedelta) -> _S: ... - @overload - def __sub__(self: _D, __other: timedelta) -> _D: ... - @overload - def __sub__(self, __other: datetime) -> NoReturn: ... - @overload - def __sub__(self: _D, __other: _D) -> timedelta: ... - else: - # Prior to Python 3.8, arithmetic operations always returned `date`, even in subclasses - def __add__(self, __other: timedelta) -> date: ... - def __radd__(self, __other: timedelta) -> date: ... - @overload - def __sub__(self, __other: timedelta) -> date: ... - @overload - def __sub__(self, __other: datetime) -> NoReturn: ... - @overload - def __sub__(self, __other: date) -> timedelta: ... + if sys.version_info >= (3, 13): + def __replace__(self, /, *, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... + + def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... + def __le__(self, value: date, /) -> bool: ... + def __lt__(self, value: date, /) -> bool: ... + def __ge__(self, value: date, /) -> bool: ... + def __gt__(self, value: date, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __add__(self, value: timedelta, /) -> Self: ... + def __radd__(self, value: timedelta, /) -> Self: ... + + @overload + def __sub__(self, value: datetime, /) -> Never: ... + @overload + def __sub__(self, value: Self, /) -> timedelta: ... + @overload + def __sub__(self, value: timedelta, /) -> Self: ... + def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... - if sys.version_info >= (3, 9): - def isocalendar(self) -> _IsoCalendarDate: ... - else: - def isocalendar(self) -> tuple[int, int, int]: ... + def isocalendar(self) -> _IsoCalendarDate: ... +@disjoint_base class time: min: ClassVar[time] max: ClassVar[time] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., + cls, + hour: SupportsIndex = 0, + minute: SupportsIndex = 0, + second: SupportsIndex = 0, + microsecond: SupportsIndex = 0, + tzinfo: _TzInfo | None = None, *, - fold: int = ..., - ) -> _S: ... + fold: int = 0, + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -116,51 +149,86 @@ class time: @property def microsecond(self) -> int: ... @property - def tzinfo(self) -> _tzinfo | None: ... + def tzinfo(self) -> _TzInfo | None: ... @property def fold(self) -> int: ... - def __le__(self, __other: time) -> bool: ... - def __lt__(self, __other: time) -> bool: ... - def __ge__(self, __other: time) -> bool: ... - def __gt__(self, __other: time) -> bool: ... + def __le__(self, value: time, /) -> bool: ... + def __lt__(self, value: time, /) -> bool: ... + def __ge__(self, value: time, /) -> bool: ... + def __gt__(self, value: time, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... - def isoformat(self, timespec: str = ...) -> str: ... - if sys.version_info >= (3, 7): + def isoformat(self, timespec: str = "auto") -> str: ... + + if sys.version_info >= (3, 15): @classmethod - def fromisoformat(cls: Type[_S], __time_string: str) -> _S: ... - def strftime(self, __format: str) -> str: ... - def __format__(self, __fmt: str) -> str: ... + def fromisoformat(cls, string: str, /) -> Self: ... + else: + @classmethod + def fromisoformat(cls, time_string: str, /) -> Self: ... + + if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + + # On <3.12, the name of the parameter in the pure-Python implementation + # didn't match the name in the C implementation, + # meaning it is only *safe* to pass it as a keyword argument on 3.12+ + if sys.version_info >= (3, 12): + def strftime(self, format: str) -> str: ... + else: + def strftime(self, format: str, /) -> str: ... + + def __format__(self, fmt: str, /) -> str: ... def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... + if sys.version_info >= (3, 13): + def __replace__( + self, + /, + *, + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + fold: int = ..., + ) -> Self: ... + def replace( self, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., *, fold: int = ..., - ) -> time: ... + ) -> Self: ... -_date = date -_time = time +_Date: TypeAlias = date +_Time: TypeAlias = time -class timedelta(SupportsAbs[timedelta]): +@disjoint_base +class timedelta: min: ClassVar[timedelta] max: ClassVar[timedelta] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], - days: float = ..., - seconds: float = ..., - microseconds: float = ..., - milliseconds: float = ..., - minutes: float = ..., - hours: float = ..., - weeks: float = ..., - ) -> _S: ... + cls, + days: float = 0, + seconds: float = 0, + microseconds: float = 0, + milliseconds: float = 0, + minutes: float = 0, + hours: float = 0, + weeks: float = 0, + ) -> Self: ... @property def days(self) -> int: ... @property @@ -168,49 +236,53 @@ class timedelta(SupportsAbs[timedelta]): @property def microseconds(self) -> int: ... def total_seconds(self) -> float: ... - def __add__(self, __other: timedelta) -> timedelta: ... - def __radd__(self, __other: timedelta) -> timedelta: ... - def __sub__(self, __other: timedelta) -> timedelta: ... - def __rsub__(self, __other: timedelta) -> timedelta: ... + def __add__(self, value: timedelta, /) -> timedelta: ... + def __radd__(self, value: timedelta, /) -> timedelta: ... + def __sub__(self, value: timedelta, /) -> timedelta: ... + def __rsub__(self, value: timedelta, /) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... - def __mul__(self, __other: float) -> timedelta: ... - def __rmul__(self, __other: float) -> timedelta: ... + def __mul__(self, value: float, /) -> timedelta: ... + def __rmul__(self, value: float, /) -> timedelta: ... + @overload - def __floordiv__(self, __other: timedelta) -> int: ... + def __floordiv__(self, value: timedelta, /) -> int: ... @overload - def __floordiv__(self, __other: int) -> timedelta: ... + def __floordiv__(self, value: int, /) -> timedelta: ... + @overload - def __truediv__(self, __other: timedelta) -> float: ... + def __truediv__(self, value: timedelta, /) -> float: ... @overload - def __truediv__(self, __other: float) -> timedelta: ... - def __mod__(self, __other: timedelta) -> timedelta: ... - def __divmod__(self, __other: timedelta) -> tuple[int, timedelta]: ... - def __le__(self, __other: timedelta) -> bool: ... - def __lt__(self, __other: timedelta) -> bool: ... - def __ge__(self, __other: timedelta) -> bool: ... - def __gt__(self, __other: timedelta) -> bool: ... + def __truediv__(self, value: float, /) -> timedelta: ... + + def __mod__(self, value: timedelta, /) -> timedelta: ... + def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ... + def __le__(self, value: timedelta, /) -> bool: ... + def __lt__(self, value: timedelta, /) -> bool: ... + def __ge__(self, value: timedelta, /) -> bool: ... + def __gt__(self, value: timedelta, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... def __bool__(self) -> bool: ... def __hash__(self) -> int: ... +@disjoint_base class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] - resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], - year: int, - month: int, - day: int, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., + cls, + year: SupportsIndex, + month: SupportsIndex, + day: SupportsIndex, + hour: SupportsIndex = 0, + minute: SupportsIndex = 0, + second: SupportsIndex = 0, + microsecond: SupportsIndex = 0, + tzinfo: _TzInfo | None = None, *, - fold: int = ..., - ) -> _S: ... + fold: int = 0, + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -220,80 +292,90 @@ class datetime(date): @property def microsecond(self) -> int: ... @property - def tzinfo(self) -> _tzinfo | None: ... + def tzinfo(self) -> _TzInfo | None: ... @property def fold(self) -> int: ... - # The first parameter in `fromtimestamp` is actually positional-or-keyword, - # but it is named "timestamp" in the C implementation and "t" in the Python implementation, - # so it is only truly *safe* to pass it as a positional argument. - @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float, tz: _tzinfo | None = ...) -> _S: ... - @classmethod - def utcfromtimestamp(cls: Type[_S], __t: float) -> _S: ... - if sys.version_info >= (3, 8): + # On <3.12, the name of the first parameter in the pure-Python implementation + # didn't match the name in the C implementation, + # meaning it is only *safe* to pass it as a keyword argument on 3.12+ + if sys.version_info >= (3, 12): @classmethod - def now(cls: Type[_S], tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = None) -> Self: ... else: - @overload - @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... - @overload @classmethod - def now(cls, tz: _tzinfo) -> datetime: ... + def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = None) -> Self: ... + + @classmethod + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.timezone.utc)") + def utcfromtimestamp(cls, t: float, /) -> Self: ... + @classmethod + def now(cls, tz: _TzInfo | None = None) -> Self: ... @classmethod - def utcnow(cls: Type[_S]) -> _S: ... + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.timezone.utc)") + def utcnow(cls) -> Self: ... @classmethod - def combine(cls, date: _date, time: _time, tzinfo: _tzinfo | None = ...) -> datetime: ... - if sys.version_info >= (3, 7): + def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ... + if sys.version_info >= (3, 15): @classmethod - def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls, string: str, /) -> Self: ... + def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... - def date(self) -> _date: ... - def time(self) -> _time: ... - def timetz(self) -> _time: ... + def date(self) -> _Date: ... + def time(self) -> _Time: ... + def timetz(self) -> _Time: ... + if sys.version_info >= (3, 13): + def __replace__( + self, + /, + *, + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + fold: int = ..., + ) -> Self: ... + def replace( self, - year: int = ..., - month: int = ..., - day: int = ..., - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., *, fold: int = ..., - ) -> datetime: ... - if sys.version_info >= (3, 8): - def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... + ) -> Self: ... + def astimezone(self, tz: _TzInfo | None = None) -> Self: ... + def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: ... + + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... else: - def astimezone(self, tz: _tzinfo | None = ...) -> datetime: ... - def ctime(self) -> str: ... - def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... - @classmethod - def strptime(cls, __date_string: str, __format: str) -> datetime: ... + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def __le__(self, __other: datetime) -> bool: ... # type: ignore[override] - def __lt__(self, __other: datetime) -> bool: ... # type: ignore[override] - def __ge__(self, __other: datetime) -> bool: ... # type: ignore[override] - def __gt__(self, __other: datetime) -> bool: ... # type: ignore[override] - if sys.version_info >= (3, 8): - @overload # type: ignore[override] - def __sub__(self: _D, __other: timedelta) -> _D: ... - @overload - def __sub__(self: _D, __other: _D) -> timedelta: ... - else: - # Prior to Python 3.8, arithmetic operations always returned `datetime`, even in subclasses - def __add__(self, __other: timedelta) -> datetime: ... - def __radd__(self, __other: timedelta) -> datetime: ... - @overload # type: ignore[override] - def __sub__(self, __other: datetime) -> timedelta: ... - @overload - def __sub__(self, __other: timedelta) -> datetime: ... - if sys.version_info >= (3, 9): - def isocalendar(self) -> _IsoCalendarDate: ... - else: - def isocalendar(self) -> tuple[int, int, int]: ... + def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + + @overload # type: ignore[override] + def __sub__(self, value: Self, /) -> timedelta: ... + @overload + def __sub__(self, value: timedelta, /) -> Self: ... + +datetime_CAPI: CapsuleType diff --git a/stdlib/dbm/__init__.pyi b/stdlib/dbm/__init__.pyi index 5ecacd91b4ed..0871381e8ec0 100644 --- a/stdlib/dbm/__init__.pyi +++ b/stdlib/dbm/__init__.pyi @@ -1,11 +1,15 @@ -from _typeshed import Self +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union -from typing_extensions import Literal +from typing import Literal, TypeAlias, type_check_only +from typing_extensions import Self -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] -_TFlags = Literal[ +__all__ = ["open", "whichdb", "error"] + +_KeyType: TypeAlias = str | bytes +_ValueType: TypeAlias = str | bytes | bytearray +_TFlags: TypeAlias = Literal[ "r", "w", "c", @@ -72,6 +76,7 @@ _TFlags = Literal[ "nusf", ] +@type_check_only class _Database(MutableMapping[_KeyType, bytes]): def close(self) -> None: ... def __getitem__(self, key: _KeyType) -> bytes: ... @@ -80,14 +85,21 @@ class _Database(MutableMapping[_KeyType, bytes]): def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... +# This class is not exposed. It calls itself dbm.error. +@type_check_only class _error(Exception): ... -error: tuple[Type[_error], Type[OSError]] +error: tuple[type[_error], type[OSError]] + +if sys.version_info >= (3, 11): + def whichdb(filename: StrOrBytesPath) -> str | None: ... + def open(file: StrOrBytesPath, flag: _TFlags = "r", mode: int = 0o666) -> _Database: ... -def whichdb(filename: str) -> str: ... -def open(file: str, flag: _TFlags = ..., mode: int = ...) -> _Database: ... +else: + def whichdb(filename: str) -> str | None: ... + def open(file: str, flag: _TFlags = "r", mode: int = 0o666) -> _Database: ... diff --git a/stdlib/dbm/dumb.pyi b/stdlib/dbm/dumb.pyi index 0a941b070754..d5a769e6a1c2 100644 --- a/stdlib/dbm/dumb.pyi +++ b/stdlib/dbm/dumb.pyi @@ -1,26 +1,41 @@ -from _typeshed import Self +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import TypeAlias +from typing_extensions import Self -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +__all__ = ["error", "open"] + +_KeyType: TypeAlias = str | bytes +_ValueType: TypeAlias = str | bytes error = OSError +# This class doesn't exist at runtime. open() can return an instance of +# any of the three implementations of dbm (dumb, gnu, ndbm), and this +# class is intended to represent the common interface supported by all three. class _Database(MutableMapping[_KeyType, bytes]): - def __init__(self, filebasename: str, mode: str, flag: str = ...) -> None: ... + def __init__(self, filebasename: str, mode: str, flag: str = "c") -> None: ... def sync(self) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... + def iterkeys(self) -> Iterator[bytes]: ... # undocumented def close(self) -> None: ... def __getitem__(self, key: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __setitem__(self, key: _KeyType, val: _ValueType) -> None: ... def __delitem__(self, key: _KeyType) -> None: ... def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... -def open(file: str, flag: str = ..., mode: int = ...) -> _Database: ... +if sys.version_info >= (3, 11): + def open(file: StrOrBytesPath, flag: str = "c", mode: int = 0o666) -> _Database: ... + +else: + def open(file: str, flag: str = "c", mode: int = 0o666) -> _Database: ... diff --git a/stdlib/dbm/gnu.pyi b/stdlib/dbm/gnu.pyi index 702f62d11b75..2dac3d12b0ca 100644 --- a/stdlib/dbm/gnu.pyi +++ b/stdlib/dbm/gnu.pyi @@ -1,39 +1 @@ -from _typeshed import Self -from types import TracebackType -from typing import Type, TypeVar, Union, overload - -_T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] - -open_flags: str - -class error(OSError): ... - -# Actual typename gdbm, not exposed by the implementation -class _gdbm: - def firstkey(self) -> bytes | None: ... - def nextkey(self, key: _KeyType) -> bytes | None: ... - def reorganize(self) -> None: ... - def sync(self) -> None: ... - def close(self) -> None: ... - def __getitem__(self, item: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... - def __delitem__(self, key: _KeyType) -> None: ... - def __contains__(self, key: _KeyType) -> bool: ... - def __len__(self) -> int: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - @overload - def get(self, k: _KeyType) -> bytes | None: ... - @overload - def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> list[bytes]: ... - def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... - # Don't exist at runtime - __new__: None # type: ignore[assignment] - __init__: None # type: ignore[assignment] - -def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... +from _gdbm import * diff --git a/stdlib/dbm/ndbm.pyi b/stdlib/dbm/ndbm.pyi index 7b04c5385dbe..66c943ab640b 100644 --- a/stdlib/dbm/ndbm.pyi +++ b/stdlib/dbm/ndbm.pyi @@ -1,35 +1 @@ -from _typeshed import Self -from types import TracebackType -from typing import Type, TypeVar, Union, overload - -_T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] - -class error(OSError): ... - -library: str - -# Actual typename dbm, not exposed by the implementation -class _dbm: - def close(self) -> None: ... - def __getitem__(self, item: _KeyType) -> bytes: ... - def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... - def __delitem__(self, key: _KeyType) -> None: ... - def __len__(self) -> int: ... - def __del__(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - @overload - def get(self, k: _KeyType) -> bytes | None: ... - @overload - def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> list[bytes]: ... - def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... - # Don't exist at runtime - __new__: None # type: ignore[assignment] - __init__: None # type: ignore[assignment] - -def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... +from _dbm import * diff --git a/stdlib/dbm/sqlite3.pyi b/stdlib/dbm/sqlite3.pyi new file mode 100644 index 000000000000..e7034cfde50d --- /dev/null +++ b/stdlib/dbm/sqlite3.pyi @@ -0,0 +1,34 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, Unused +from collections.abc import Generator, MutableMapping +from typing import Final, Literal, TypeAlias +from typing_extensions import LiteralString, Self + +BUILD_TABLE: Final[LiteralString] +GET_SIZE: Final[LiteralString] +LOOKUP_KEY: Final[LiteralString] +STORE_KV: Final[LiteralString] +DELETE_KEY: Final[LiteralString] +ITER_KEYS: Final[LiteralString] +if sys.version_info >= (3, 15): + REORGANIZE: Final[LiteralString] + +_SqliteData: TypeAlias = str | ReadableBuffer | int | float + +class error(OSError): ... + +class _Database(MutableMapping[bytes, bytes]): + def __init__(self, path: StrOrBytesPath, /, *, flag: Literal["r", "w", "c", "n"], mode: int) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _SqliteData) -> bytes: ... + def __setitem__(self, key: _SqliteData, value: _SqliteData) -> None: ... + def __delitem__(self, key: _SqliteData) -> None: ... + def __iter__(self) -> Generator[bytes]: ... + def close(self) -> None: ... + def keys(self) -> list[bytes]: ... # type: ignore[override] + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... + +def open(filename: StrOrBytesPath, /, flag: Literal["r", "w", "c", "n"] = "r", mode: int = 0o666) -> _Database: ... diff --git a/stdlib/decimal.pyi b/stdlib/decimal.pyi index 959af69675c9..f116603cf0f2 100644 --- a/stdlib/decimal.pyi +++ b/stdlib/decimal.pyi @@ -1,34 +1,59 @@ import numbers import sys +from _decimal import ( + HAVE_CONTEXTVAR as HAVE_CONTEXTVAR, + HAVE_THREADS as HAVE_THREADS, + MAX_EMAX as MAX_EMAX, + MAX_PREC as MAX_PREC, + MIN_EMIN as MIN_EMIN, + MIN_ETINY as MIN_ETINY, + ROUND_05UP as ROUND_05UP, + ROUND_CEILING as ROUND_CEILING, + ROUND_DOWN as ROUND_DOWN, + ROUND_FLOOR as ROUND_FLOOR, + ROUND_HALF_DOWN as ROUND_HALF_DOWN, + ROUND_HALF_EVEN as ROUND_HALF_EVEN, + ROUND_HALF_UP as ROUND_HALF_UP, + ROUND_UP as ROUND_UP, + BasicContext as BasicContext, + DefaultContext as DefaultContext, + ExtendedContext as ExtendedContext, + __libmpdec_version__ as __libmpdec_version__, + __version__ as __version__, + getcontext as getcontext, + localcontext as localcontext, + setcontext as setcontext, +) +from collections.abc import Container, Sequence from types import TracebackType -from typing import Any, Container, NamedTuple, Sequence, Tuple, Type, TypeVar, Union, overload +from typing import Any, ClassVar, Literal, NamedTuple, TypeAlias, final, overload, type_check_only +from typing_extensions import Self, disjoint_base -_Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, str, Tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float, numbers.Rational] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) +if sys.version_info >= (3, 14): + from _decimal import IEEE_CONTEXT_MAX_BITS as IEEE_CONTEXT_MAX_BITS, IEEEContext as IEEEContext +if sys.version_info >= (3, 15): + from _decimal import SPEC_VERSION as SPEC_VERSION -class DecimalTuple(NamedTuple): - sign: int - digits: Tuple[int, ...] - exponent: int +_Decimal: TypeAlias = Decimal | int +_DecimalNew: TypeAlias = Decimal | float | str | tuple[int, Sequence[int], int] +_ComparableNum: TypeAlias = Decimal | float | numbers.Rational +_TrapType: TypeAlias = type[DecimalException] -ROUND_DOWN: str -ROUND_HALF_UP: str -ROUND_HALF_EVEN: str -ROUND_CEILING: str -ROUND_FLOOR: str -ROUND_UP: str -ROUND_HALF_DOWN: str -ROUND_05UP: str +# At runtime, these classes are implemented in C as part of "_decimal". +# However, they consider themselves to live in "decimal", so we'll put them here. -if sys.version_info >= (3, 7): - HAVE_CONTEXTVAR: bool -HAVE_THREADS: bool -MAX_EMAX: int -MAX_PREC: int -MIN_EMIN: int -MIN_ETINY: int +# This type isn't exposed at runtime. It calls itself decimal.ContextManager +@final +@type_check_only +class _ContextManager: + def __init__(self, new_context: Context) -> None: ... + def __enter__(self) -> Context: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +class DecimalTuple(NamedTuple): + sign: int + digits: tuple[int, ...] + exponent: int | Literal["n", "N", "F"] class DecimalException(ArithmeticError): ... class Clamped(DecimalException): ... @@ -45,45 +70,45 @@ class Overflow(Inexact, Rounded): ... class Underflow(Inexact, Rounded, Subnormal): ... class FloatOperation(DecimalException, TypeError): ... -def setcontext(__context: Context) -> None: ... -def getcontext() -> Context: ... -def localcontext(ctx: Context | None = ...) -> _ContextManager: ... +@disjoint_base +class Decimal: + def __new__(cls, value: _DecimalNew = "0", context: Context | None = None) -> Self: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: Decimal | float, /) -> Self: ... -class Decimal(object): - def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... @classmethod - def from_float(cls, __f: float) -> Decimal: ... + def from_float(cls, f: float, /) -> Self: ... def __bool__(self) -> bool: ... - def compare(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def compare(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def __hash__(self) -> int: ... def as_tuple(self) -> DecimalTuple: ... def as_integer_ratio(self) -> tuple[int, int]: ... - def to_eng_string(self, context: Context | None = ...) -> str: ... + def to_eng_string(self, context: Context | None = None) -> str: ... def __abs__(self) -> Decimal: ... - def __add__(self, __other: _Decimal) -> Decimal: ... - def __divmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... - def __eq__(self, __other: object) -> bool: ... - def __floordiv__(self, __other: _Decimal) -> Decimal: ... - def __ge__(self, __other: _ComparableNum) -> bool: ... - def __gt__(self, __other: _ComparableNum) -> bool: ... - def __le__(self, __other: _ComparableNum) -> bool: ... - def __lt__(self, __other: _ComparableNum) -> bool: ... - def __mod__(self, __other: _Decimal) -> Decimal: ... - def __mul__(self, __other: _Decimal) -> Decimal: ... + def __add__(self, value: _Decimal, /) -> Decimal: ... + def __divmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def __eq__(self, value: object, /) -> bool: ... + def __floordiv__(self, value: _Decimal, /) -> Decimal: ... + def __ge__(self, value: _ComparableNum, /) -> bool: ... + def __gt__(self, value: _ComparableNum, /) -> bool: ... + def __le__(self, value: _ComparableNum, /) -> bool: ... + def __lt__(self, value: _ComparableNum, /) -> bool: ... + def __mod__(self, value: _Decimal, /) -> Decimal: ... + def __mul__(self, value: _Decimal, /) -> Decimal: ... def __neg__(self) -> Decimal: ... def __pos__(self) -> Decimal: ... - def __pow__(self, __other: _Decimal, __modulo: _Decimal | None = ...) -> Decimal: ... - def __radd__(self, __other: _Decimal) -> Decimal: ... - def __rdivmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, __other: _Decimal) -> Decimal: ... - def __rmod__(self, __other: _Decimal) -> Decimal: ... - def __rmul__(self, __other: _Decimal) -> Decimal: ... - def __rsub__(self, __other: _Decimal) -> Decimal: ... - def __rtruediv__(self, __other: _Decimal) -> Decimal: ... - def __str__(self) -> str: ... - def __sub__(self, __other: _Decimal) -> Decimal: ... - def __truediv__(self, __other: _Decimal) -> Decimal: ... - def remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def __pow__(self, value: _Decimal, mod: _Decimal | None = None, /) -> Decimal: ... + def __radd__(self, value: _Decimal, /) -> Decimal: ... + def __rdivmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, value: _Decimal, /) -> Decimal: ... + def __rmod__(self, value: _Decimal, /) -> Decimal: ... + def __rmul__(self, value: _Decimal, /) -> Decimal: ... + def __rsub__(self, value: _Decimal, /) -> Decimal: ... + def __rtruediv__(self, value: _Decimal, /) -> Decimal: ... + def __sub__(self, value: _Decimal, /) -> Decimal: ... + def __truediv__(self, value: _Decimal, /) -> Decimal: ... + def remainder_near(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def __float__(self) -> float: ... def __int__(self) -> int: ... def __trunc__(self) -> int: ... @@ -93,74 +118,73 @@ class Decimal(object): def imag(self) -> Decimal: ... def conjugate(self) -> Decimal: ... def __complex__(self) -> complex: ... + @overload def __round__(self) -> int: ... @overload - def __round__(self, __ndigits: int) -> Decimal: ... + def __round__(self, ndigits: int, /) -> Decimal: ... + def __floor__(self) -> int: ... def __ceil__(self) -> int: ... - def fma(self, other: _Decimal, third: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rpow__(self, __other: _Decimal, __context: Context | None = ...) -> Decimal: ... - def normalize(self, context: Context | None = ...) -> Decimal: ... - def quantize(self, exp: _Decimal, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def same_quantum(self, other: _Decimal, context: Context | None = ...) -> bool: ... - def to_integral_exact(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def to_integral_value(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def to_integral(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def sqrt(self, context: Context | None = ...) -> Decimal: ... - def max(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def min(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def fma(self, other: _Decimal, third: _Decimal, context: Context | None = None) -> Decimal: ... + def __rpow__(self, value: _Decimal, mod: Context | None = None, /) -> Decimal: ... + def normalize(self, context: Context | None = None) -> Decimal: ... + def quantize(self, exp: _Decimal, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def same_quantum(self, other: _Decimal, context: Context | None = None) -> bool: ... + def to_integral_exact(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def to_integral_value(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def to_integral(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def sqrt(self, context: Context | None = None) -> Decimal: ... + def max(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def min(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def adjusted(self) -> int: ... def canonical(self) -> Decimal: ... - def compare_signal(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def compare_total(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def compare_total_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def compare_signal(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def compare_total(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def compare_total_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ... def copy_abs(self) -> Decimal: ... def copy_negate(self) -> Decimal: ... - def copy_sign(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def exp(self, context: Context | None = ...) -> Decimal: ... + def copy_sign(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def exp(self, context: Context | None = None) -> Decimal: ... def is_canonical(self) -> bool: ... def is_finite(self) -> bool: ... def is_infinite(self) -> bool: ... def is_nan(self) -> bool: ... - def is_normal(self, context: Context | None = ...) -> bool: ... + def is_normal(self, context: Context | None = None) -> bool: ... def is_qnan(self) -> bool: ... def is_signed(self) -> bool: ... def is_snan(self) -> bool: ... - def is_subnormal(self, context: Context | None = ...) -> bool: ... + def is_subnormal(self, context: Context | None = None) -> bool: ... def is_zero(self) -> bool: ... - def ln(self, context: Context | None = ...) -> Decimal: ... - def log10(self, context: Context | None = ...) -> Decimal: ... - def logb(self, context: Context | None = ...) -> Decimal: ... - def logical_and(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def logical_invert(self, context: Context | None = ...) -> Decimal: ... - def logical_or(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def logical_xor(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def max_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def min_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def next_minus(self, context: Context | None = ...) -> Decimal: ... - def next_plus(self, context: Context | None = ...) -> Decimal: ... - def next_toward(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def number_class(self, context: Context | None = ...) -> str: ... + def ln(self, context: Context | None = None) -> Decimal: ... + def log10(self, context: Context | None = None) -> Decimal: ... + def logb(self, context: Context | None = None) -> Decimal: ... + def logical_and(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def logical_invert(self, context: Context | None = None) -> Decimal: ... + def logical_or(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def logical_xor(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def max_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def min_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def next_minus(self, context: Context | None = None) -> Decimal: ... + def next_plus(self, context: Context | None = None) -> Decimal: ... + def next_toward(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def number_class(self, context: Context | None = None) -> str: ... def radix(self) -> Decimal: ... - def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self) -> tuple[Type[Decimal], tuple[str]]: ... - def __copy__(self) -> Decimal: ... - def __deepcopy__(self, __memo: Any) -> Decimal: ... - def __format__(self, __specifier: str, __context: Context | None = ...) -> str: ... + def rotate(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def scaleb(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def shift(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def __reduce__(self) -> tuple[type[Self], tuple[str]]: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def __format__(self, specifier: str, context: Context | None = None, /) -> str: ... -class _ContextManager(object): - new_context: Context - saved_context: Context - def __init__(self, new_context: Context) -> None: ... - def __enter__(self) -> Context: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... - -_TrapType = Type[DecimalException] - -class Context(object): +@disjoint_base +class Context: + # TODO: Context doesn't allow you to delete *any* attributes from instances of the class at runtime, + # even settable attributes like `prec` and `rounding`, + # but that's inexpressible in the stub. + # Type checkers either ignore it or misinterpret it + # if you add a `def __delattr__(self, name: str, /) -> Never` method to the stub prec: int rounding: str Emin: int @@ -171,91 +195,84 @@ class Context(object): flags: dict[_TrapType, bool] def __init__( self, - prec: int | None = ..., - rounding: str | None = ..., - Emin: int | None = ..., - Emax: int | None = ..., - capitals: int | None = ..., - clamp: int | None = ..., - flags: None | dict[_TrapType, bool] | Container[_TrapType] = ..., - traps: None | dict[_TrapType, bool] | Container[_TrapType] = ..., - _ignored_flags: list[_TrapType] | None = ..., + prec: int | None = None, + rounding: str | None = None, + Emin: int | None = None, + Emax: int | None = None, + capitals: int | None = None, + clamp: int | None = None, + flags: dict[_TrapType, bool] | Container[_TrapType] | None = None, + traps: dict[_TrapType, bool] | Container[_TrapType] | None = None, ) -> None: ... - # __setattr__() only allows to set a specific set of attributes, - # already defined above. - def __delattr__(self, __name: str) -> None: ... - def __reduce__(self) -> tuple[Type[Context], Tuple[Any, ...]]: ... + def __reduce__(self) -> tuple[type[Self], tuple[Any, ...]]: ... def clear_flags(self) -> None: ... def clear_traps(self) -> None: ... def copy(self) -> Context: ... def __copy__(self) -> Context: ... - __hash__: Any + # see https://github.com/python/cpython/issues/94107 + __hash__: ClassVar[None] # type: ignore[assignment] def Etiny(self) -> int: ... def Etop(self) -> int: ... - def create_decimal(self, __num: _DecimalNew = ...) -> Decimal: ... - def create_decimal_from_float(self, __f: float) -> Decimal: ... - def abs(self, __x: _Decimal) -> Decimal: ... - def add(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def canonical(self, __x: Decimal) -> Decimal: ... - def compare(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_signal(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def copy_abs(self, __x: _Decimal) -> Decimal: ... - def copy_decimal(self, __x: _Decimal) -> Decimal: ... - def copy_negate(self, __x: _Decimal) -> Decimal: ... - def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divmod(self, __x: _Decimal, __y: _Decimal) -> tuple[Decimal, Decimal]: ... - def exp(self, __x: _Decimal) -> Decimal: ... - def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... - def is_canonical(self, __x: _Decimal) -> bool: ... - def is_finite(self, __x: _Decimal) -> bool: ... - def is_infinite(self, __x: _Decimal) -> bool: ... - def is_nan(self, __x: _Decimal) -> bool: ... - def is_normal(self, __x: _Decimal) -> bool: ... - def is_qnan(self, __x: _Decimal) -> bool: ... - def is_signed(self, __x: _Decimal) -> bool: ... - def is_snan(self, __x: _Decimal) -> bool: ... - def is_subnormal(self, __x: _Decimal) -> bool: ... - def is_zero(self, __x: _Decimal) -> bool: ... - def ln(self, __x: _Decimal) -> Decimal: ... - def log10(self, __x: _Decimal) -> Decimal: ... - def logb(self, __x: _Decimal) -> Decimal: ... - def logical_and(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_invert(self, __x: _Decimal) -> Decimal: ... - def logical_or(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_xor(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def minus(self, __x: _Decimal) -> Decimal: ... - def multiply(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def next_minus(self, __x: _Decimal) -> Decimal: ... - def next_plus(self, __x: _Decimal) -> Decimal: ... - def next_toward(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def normalize(self, __x: _Decimal) -> Decimal: ... - def number_class(self, __x: _Decimal) -> str: ... - def plus(self, __x: _Decimal) -> Decimal: ... - def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = ...) -> Decimal: ... - def quantize(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def create_decimal(self, num: _DecimalNew = "0", /) -> Decimal: ... + def create_decimal_from_float(self, f: float, /) -> Decimal: ... + def abs(self, x: _Decimal, /) -> Decimal: ... + def add(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def canonical(self, x: Decimal, /) -> Decimal: ... + def compare(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_signal(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_total(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_total_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def copy_abs(self, x: _Decimal, /) -> Decimal: ... + def copy_decimal(self, x: _Decimal, /) -> Decimal: ... + def copy_negate(self, x: _Decimal, /) -> Decimal: ... + def copy_sign(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divide(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divide_int(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divmod(self, x: _Decimal, y: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def exp(self, x: _Decimal, /) -> Decimal: ... + def fma(self, x: _Decimal, y: _Decimal, z: _Decimal, /) -> Decimal: ... + def is_canonical(self, x: _Decimal, /) -> bool: ... + def is_finite(self, x: _Decimal, /) -> bool: ... + def is_infinite(self, x: _Decimal, /) -> bool: ... + def is_nan(self, x: _Decimal, /) -> bool: ... + def is_normal(self, x: _Decimal, /) -> bool: ... + def is_qnan(self, x: _Decimal, /) -> bool: ... + def is_signed(self, x: _Decimal, /) -> bool: ... + def is_snan(self, x: _Decimal, /) -> bool: ... + def is_subnormal(self, x: _Decimal, /) -> bool: ... + def is_zero(self, x: _Decimal, /) -> bool: ... + def ln(self, x: _Decimal, /) -> Decimal: ... + def log10(self, x: _Decimal, /) -> Decimal: ... + def logb(self, x: _Decimal, /) -> Decimal: ... + def logical_and(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def logical_invert(self, x: _Decimal, /) -> Decimal: ... + def logical_or(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def logical_xor(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def max(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def max_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def min(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def min_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def minus(self, x: _Decimal, /) -> Decimal: ... + def multiply(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def next_minus(self, x: _Decimal, /) -> Decimal: ... + def next_plus(self, x: _Decimal, /) -> Decimal: ... + def next_toward(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def normalize(self, x: _Decimal, /) -> Decimal: ... + def number_class(self, x: _Decimal, /) -> str: ... + def plus(self, x: _Decimal, /) -> Decimal: ... + def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = None) -> Decimal: ... + def quantize(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... def radix(self) -> Decimal: ... - def remainder(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def remainder_near(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def rotate(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def same_quantum(self, __x: _Decimal, __y: _Decimal) -> bool: ... - def scaleb(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def shift(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def sqrt(self, __x: _Decimal) -> Decimal: ... - def subtract(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def to_eng_string(self, __x: _Decimal) -> str: ... - def to_sci_string(self, __x: _Decimal) -> str: ... - def to_integral_exact(self, __x: _Decimal) -> Decimal: ... - def to_integral_value(self, __x: _Decimal) -> Decimal: ... - def to_integral(self, __x: _Decimal) -> Decimal: ... - -DefaultContext: Context -BasicContext: Context -ExtendedContext: Context + def remainder(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def remainder_near(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def rotate(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def same_quantum(self, x: _Decimal, y: _Decimal, /) -> bool: ... + def scaleb(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def shift(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def sqrt(self, x: _Decimal, /) -> Decimal: ... + def subtract(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def to_eng_string(self, x: _Decimal, /) -> str: ... + def to_sci_string(self, x: _Decimal, /) -> str: ... + def to_integral_exact(self, x: _Decimal, /) -> Decimal: ... + def to_integral_value(self, x: _Decimal, /) -> Decimal: ... + def to_integral(self, x: _Decimal, /) -> Decimal: ... diff --git a/stdlib/difflib.pyi b/stdlib/difflib.pyi index 944a63966241..a3bda7f9b2d0 100644 --- a/stdlib/difflib.pyi +++ b/stdlib/difflib.pyi @@ -1,11 +1,25 @@ +import re import sys -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, Union, overload +from collections.abc import Callable, Iterable, Iterator, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = [ + "get_close_matches", + "ndiff", + "restore", + "SequenceMatcher", + "Differ", + "IS_CHARACTER_JUNK", + "IS_LINE_JUNK", + "context_diff", + "unified_diff", + "diff_bytes", + "HtmlDiff", + "Match", +] _T = TypeVar("_T") -_JunkCallback = Union[Callable[[str], bool], Callable[[str], bool]] class Match(NamedTuple): a: int @@ -13,101 +27,131 @@ class Match(NamedTuple): size: int class SequenceMatcher(Generic[_T]): + @overload + def __init__(self, isjunk: Callable[[_T], bool] | None, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: ... + @overload + def __init__(self, *, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: ... + @overload def __init__( - self, isjunk: Callable[[_T], bool] | None = ..., a: Sequence[_T] = ..., b: Sequence[_T] = ..., autojunk: bool = ... + self: SequenceMatcher[str], + isjunk: Callable[[str], bool] | None = None, + a: Sequence[str] = "", + b: Sequence[str] = "", + autojunk: bool = True, ) -> None: ... + def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... def set_seq1(self, a: Sequence[_T]) -> None: ... def set_seq2(self, b: Sequence[_T]) -> None: ... - if sys.version_info >= (3, 9): - def find_longest_match(self, alo: int = ..., ahi: int | None = ..., blo: int = ..., bhi: int | None = ...) -> Match: ... - else: - def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... + def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: ... def get_matching_blocks(self) -> list[Match]: ... - def get_opcodes(self) -> list[tuple[str, int, int, int, int]]: ... - def get_grouped_opcodes(self, n: int = ...) -> Iterable[list[tuple[str, int, int, int, int]]]: ... + def get_opcodes(self) -> list[tuple[Literal["replace", "delete", "insert", "equal"], int, int, int, int]]: ... + def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: ... def ratio(self) -> float: ... def quick_ratio(self) -> float: ... def real_quick_ratio(self) -> float: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -# mypy thinks the signatures of the overloads overlap, but the types still work fine @overload -def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ...) -> list[AnyStr]: ... # type: ignore[misc] +def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = 3, cutoff: float = 0.6) -> list[AnyStr]: ... @overload def get_close_matches( - word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... + word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = 3, cutoff: float = 0.6 ) -> list[Sequence[_T]]: ... class Differ: - def __init__(self, linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ...) -> None: ... + def __init__(self, linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = None) -> None: ... def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ... -def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: ... # pat is undocumented -def IS_CHARACTER_JUNK(ch: str, ws: str = ...) -> bool: ... # ws is undocumented -def unified_diff( - a: Sequence[str], - b: Sequence[str], - fromfile: str = ..., - tofile: str = ..., - fromfiledate: str = ..., - tofiledate: str = ..., - n: int = ..., - lineterm: str = ..., -) -> Iterator[str]: ... +if sys.version_info >= (3, 14): + def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] | None = None) -> bool: ... + +else: + def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] = ...) -> bool: ... + +def IS_CHARACTER_JUNK(ch: str, ws: str = " \t") -> bool: ... # ws is undocumented + +if sys.version_info >= (3, 15): + def unified_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", + *, + color: bool = False, + ) -> Iterator[str]: ... + +else: + def unified_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", + ) -> Iterator[str]: ... + def context_diff( a: Sequence[str], b: Sequence[str], - fromfile: str = ..., - tofile: str = ..., - fromfiledate: str = ..., - tofiledate: str = ..., - n: int = ..., - lineterm: str = ..., + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", ) -> Iterator[str]: ... def ndiff( - a: Sequence[str], b: Sequence[str], linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ... + a: Sequence[str], + b: Sequence[str], + linejunk: Callable[[str], bool] | None = None, + charjunk: Callable[[str], bool] | None = ..., ) -> Iterator[str]: ... -class HtmlDiff(object): +class HtmlDiff: def __init__( self, - tabsize: int = ..., - wrapcolumn: int | None = ..., - linejunk: _JunkCallback | None = ..., - charjunk: _JunkCallback | None = ..., + tabsize: int = 8, + wrapcolumn: int | None = None, + linejunk: Callable[[str], bool] | None = None, + charjunk: Callable[[str], bool] | None = ..., ) -> None: ... def make_file( self, fromlines: Sequence[str], tolines: Sequence[str], - fromdesc: str = ..., - todesc: str = ..., - context: bool = ..., - numlines: int = ..., + fromdesc: str = "", + todesc: str = "", + context: bool = False, + numlines: int = 5, *, - charset: str = ..., + charset: str = "utf-8", ) -> str: ... def make_table( self, fromlines: Sequence[str], tolines: Sequence[str], - fromdesc: str = ..., - todesc: str = ..., - context: bool = ..., - numlines: int = ..., + fromdesc: str = "", + todesc: str = "", + context: bool = False, + numlines: int = 5, ) -> str: ... def restore(delta: Iterable[str], which: int) -> Iterator[str]: ... def diff_bytes( dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]], - a: Sequence[bytes], - b: Sequence[bytes], - fromfile: bytes = ..., - tofile: bytes = ..., - fromfiledate: bytes = ..., - tofiledate: bytes = ..., - n: int = ..., - lineterm: bytes = ..., + a: Iterable[bytes | bytearray], + b: Iterable[bytes | bytearray], + fromfile: bytes | bytearray = b"", + tofile: bytes | bytearray = b"", + fromfiledate: bytes | bytearray = b"", + tofiledate: bytes | bytearray = b"", + n: int = 3, + lineterm: bytes | bytearray = b"\n", ) -> Iterator[bytes]: ... diff --git a/stdlib/dis.pyi b/stdlib/dis.pyi index ac0632d25c9c..984f932e3311 100644 --- a/stdlib/dis.pyi +++ b/stdlib/dis.pyi @@ -1,64 +1,302 @@ import sys import types -from opcode import ( - EXTENDED_ARG as EXTENDED_ARG, - HAVE_ARGUMENT as HAVE_ARGUMENT, - cmp_op as cmp_op, - hascompare as hascompare, - hasconst as hasconst, - hasfree as hasfree, - hasjabs as hasjabs, - hasjrel as hasjrel, - haslocal as haslocal, - hasname as hasname, - hasnargs as hasnargs, - opmap as opmap, - opname as opname, - stack_effect as stack_effect, -) -from typing import IO, Any, Callable, Iterator, NamedTuple, Union +from collections.abc import Callable, Iterator +from opcode import * # `dis` re-exports it as a part of public API +from typing import IO, Any, Final, NamedTuple, TypeAlias, overload +from typing_extensions import Self, deprecated, disjoint_base + +__all__ = [ + "code_info", + "dis", + "disassemble", + "distb", + "disco", + "findlinestarts", + "findlabels", + "show_code", + "get_instructions", + "Instruction", + "Bytecode", + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "stack_effect", +] +if sys.version_info >= (3, 13): + __all__ += ["hasjump"] + +if sys.version_info >= (3, 12): + __all__ += ["hasarg", "hasexc"] +else: + __all__ += ["hasnargs"] # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_HaveCodeType = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] -_HaveCodeOrStringType = Union[_HaveCodeType, str, bytes] - -class Instruction(NamedTuple): - opname: str - opcode: int - arg: int | None - argval: Any - argrepr: str - offset: int - starts_line: int | None - is_jump_target: bool +_HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] + +if sys.version_info >= (3, 11): + class Positions(NamedTuple): + lineno: int | None = None + end_lineno: int | None = None + col_offset: int | None = None + end_col_offset: int | None = None + +if sys.version_info >= (3, 13): + class _Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + start_offset: int + starts_line: bool + line_number: int | None + label: int | None = None + positions: Positions | None = None + cache_info: list[tuple[str, int, Any]] | None = None + +elif sys.version_info >= (3, 11): + class _Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + starts_line: int | None + is_jump_target: bool + positions: Positions | None = None + +else: + class _Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + starts_line: int | None + is_jump_target: bool + +if sys.version_info >= (3, 12): + class Instruction(_Instruction): + if sys.version_info < (3, 13): + def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: ... + if sys.version_info >= (3, 13): + @property + def oparg(self) -> int: ... + @property + def baseopcode(self) -> int: ... + @property + def baseopname(self) -> str: ... + @property + def cache_offset(self) -> int: ... + @property + def end_offset(self) -> int: ... + @property + def jump_target(self) -> int: ... + @property + def is_jump_target(self) -> bool: ... + if sys.version_info >= (3, 14): + @staticmethod + def make( + opname: str, + arg: int | None, + argval: Any, + argrepr: str, + offset: int, + start_offset: int, + starts_line: bool, + line_number: int | None, + label: int | None = None, + positions: Positions | None = None, + cache_info: list[tuple[str, int, Any]] | None = None, + ) -> Instruction: ... + +else: + @disjoint_base + class Instruction(_Instruction): + def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: ... class Bytecode: codeobj: types.CodeType first_line: int - def __init__(self, x: _HaveCodeOrStringType, *, first_line: int | None = ..., current_offset: int | None = ...) -> None: ... + if sys.version_info >= (3, 14): + show_positions: bool + # 3.14 added `show_positions` + def __init__( + self, + x: _HaveCodeType | str, + *, + first_line: int | None = None, + current_offset: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 13): + show_offsets: bool + # 3.13 added `show_offsets` + def __init__( + self, + x: _HaveCodeType | str, + *, + first_line: int | None = None, + current_offset: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + x: _HaveCodeType | str, + *, + first_line: int | None = None, + current_offset: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + ) -> None: ... + else: + def __init__( + self, x: _HaveCodeType | str, *, first_line: int | None = None, current_offset: int | None = None + ) -> None: ... + + if sys.version_info >= (3, 11): + @classmethod + def from_traceback(cls, tb: types.TracebackType, *, show_caches: bool = False, adaptive: bool = False) -> Self: ... + else: + @classmethod + def from_traceback(cls, tb: types.TracebackType) -> Self: ... + def __iter__(self) -> Iterator[Instruction]: ... - def __repr__(self) -> str: ... def info(self) -> str: ... def dis(self) -> str: ... - @classmethod - def from_traceback(cls, tb: types.TracebackType) -> Bytecode: ... -COMPILER_FLAG_NAMES: dict[int, str] +COMPILER_FLAG_NAMES: Final[dict[int, str]] def findlabels(code: _HaveCodeType) -> list[int]: ... def findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]: ... def pretty_flags(flags: int) -> str: ... -def code_info(x: _HaveCodeOrStringType) -> str: ... +def code_info(x: _HaveCodeType | str) -> str: ... + +if sys.version_info >= (3, 14): + # 3.14 added `show_positions` + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, + *, + file: IO[str] | None = None, + depth: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + def disassemble( + co: _HaveCodeType, + lasti: int = -1, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + def distb( + tb: types.TracebackType | None = None, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + +elif sys.version_info >= (3, 13): + # 3.13 added `show_offsets` + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, + *, + file: IO[str] | None = None, + depth: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + def disassemble( + co: _HaveCodeType, + lasti: int = -1, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + def distb( + tb: types.TracebackType | None = None, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... -if sys.version_info >= (3, 7): - def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ..., depth: int | None = ...) -> None: ... +elif sys.version_info >= (3, 11): + # 3.11 added `show_caches` and `adaptive` + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, + *, + file: IO[str] | None = None, + depth: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + ) -> None: ... + def disassemble( + co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False + ) -> None: ... + def distb( + tb: types.TracebackType | None = None, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False + ) -> None: ... else: - def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ...) -> None: ... + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, *, file: IO[str] | None = None, depth: int | None = None + ) -> None: ... + def disassemble(co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None) -> None: ... + def distb(tb: types.TracebackType | None = None, *, file: IO[str] | None = None) -> None: ... + +if sys.version_info >= (3, 13): + # 3.13 made `show_caches` `None` by default and has no effect + @overload + def get_instructions(x: _HaveCodeType, *, first_line: int | None = None, adaptive: bool = False) -> Iterator[Instruction]: ... + @overload + @deprecated( + "The `show_caches` parameter is deprecated since Python 3.13. " + "The iterator generates the `Instruction` instances with the `cache_info` field populated." + ) + def get_instructions( + x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool | None = None, adaptive: bool = False + ) -> Iterator[Instruction]: ... + +elif sys.version_info >= (3, 11): + def get_instructions( + x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool = False, adaptive: bool = False + ) -> Iterator[Instruction]: ... + +else: + def get_instructions(x: _HaveCodeType, *, first_line: int | None = None) -> Iterator[Instruction]: ... + +def show_code(co: _HaveCodeType, *, file: IO[str] | None = None) -> None: ... -def distb(tb: types.TracebackType | None = ..., *, file: IO[str] | None = ...) -> None: ... -def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... -def disco(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... -def show_code(co: _HaveCodeType, *, file: IO[str] | None = ...) -> None: ... -def get_instructions(x: _HaveCodeType, *, first_line: int | None = ...) -> Iterator[Instruction]: ... +disco = disassemble diff --git a/stdlib/distutils/__init__.pyi b/stdlib/distutils/__init__.pyi index e69de29bb2d1..328a5b783441 100644 --- a/stdlib/distutils/__init__.pyi +++ b/stdlib/distutils/__init__.pyi @@ -0,0 +1,5 @@ +# Attempts to improve these stubs are probably not the best use of time: +# - distutils is deleted in Python 3.12 and newer +# - Most users already do not use stdlib distutils, due to setuptools monkeypatching +# - We have very little quality assurance on these stubs, since due to the two above issues +# we allowlist all distutils errors in stubtest. diff --git a/stdlib/distutils/_msvccompiler.pyi b/stdlib/distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..bba9373b72db --- /dev/null +++ b/stdlib/distutils/_msvccompiler.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from distutils.ccompiler import CCompiler +from typing import ClassVar, Final + +PLAT_SPEC_TO_RUNTIME: Final[dict[str, str]] +PLAT_TO_VCVARS: Final[dict[str, str]] + +class MSVCCompiler(CCompiler): + compiler_type: ClassVar[str] + executables: ClassVar[dict[Incomplete, Incomplete]] + res_extension: ClassVar[str] + initialized: bool + def initialize(self, plat_name: str | None = None) -> None: ... diff --git a/stdlib/distutils/archive_util.pyi b/stdlib/distutils/archive_util.pyi index 38458fc0e003..5de23bad6bdb 100644 --- a/stdlib/distutils/archive_util.pyi +++ b/stdlib/distutils/archive_util.pyi @@ -1,20 +1,36 @@ +from _typeshed import StrOrBytesPath, StrPath +from typing import Literal, overload + +@overload def make_archive( base_name: str, format: str, - root_dir: str | None = ..., - base_dir: str | None = ..., - verbose: int = ..., - dry_run: int = ..., - owner: str | None = ..., - group: str | None = ..., + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + owner: str | None = None, + group: str | None = None, ) -> str: ... +@overload +def make_archive( + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + owner: str | None = None, + group: str | None = None, +) -> str: ... + def make_tarball( base_name: str, - base_dir: str, - compress: str | None = ..., - verbose: int = ..., - dry_run: int = ..., - owner: str | None = ..., - group: str | None = ..., + base_dir: StrPath, + compress: str | None = "gzip", + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + owner: str | None = None, + group: str | None = None, ) -> str: ... -def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., dry_run: int = ...) -> str: ... +def make_zipfile(base_name: str, base_dir: str, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0) -> str: ... diff --git a/stdlib/distutils/ccompiler.pyi b/stdlib/distutils/ccompiler.pyi index d21de4691503..83bbada6c4c4 100644 --- a/stdlib/distutils/ccompiler.pyi +++ b/stdlib/distutils/ccompiler.pyi @@ -1,14 +1,23 @@ -from typing import Any, Callable, Optional, Tuple, Union +from _typeshed import BytesPath, StrPath, Unused +from collections.abc import Callable, Iterable, Sequence +from distutils.file_util import _BytesPathT, _StrPathT +from typing import Literal, TypeAlias, overload +from typing_extensions import TypeVarTuple, Unpack -_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] +_Macro: TypeAlias = tuple[str] | tuple[str, str | None] +_Ts = TypeVarTuple("_Ts") def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] ) -> list[str]: ... def gen_preprocess_options(macros: list[_Macro], include_dirs: list[str]) -> list[str]: ... -def get_default_compiler(osname: str | None = ..., platform: str | None = ...) -> str: ... +def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: ... def new_compiler( - plat: str | None = ..., compiler: str | None = ..., verbose: int = ..., dry_run: int = ..., force: int = ... + plat: str | None = None, + compiler: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + force: bool | Literal[0, 1] = 0, ) -> CCompiler: ... def show_compilers() -> None: ... @@ -23,7 +32,9 @@ class CCompiler: library_dirs: list[str] runtime_library_dirs: list[str] objects: list[str] - def __init__(self, verbose: int = ..., dry_run: int = ..., force: int = ...) -> None: ... + def __init__( + self, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0, force: bool | Literal[0, 1] = 0 + ) -> None: ... def add_include_dir(self, dir: str) -> None: ... def set_include_dirs(self, dirs: list[str]) -> None: ... def add_library(self, libname: str) -> None: ... @@ -32,19 +43,19 @@ class CCompiler: def set_library_dirs(self, dirs: list[str]) -> None: ... def add_runtime_library_dir(self, dir: str) -> None: ... def set_runtime_library_dirs(self, dirs: list[str]) -> None: ... - def define_macro(self, name: str, value: str | None = ...) -> None: ... + def define_macro(self, name: str, value: str | None = None) -> None: ... def undefine_macro(self, name: str) -> None: ... def add_link_object(self, object: str) -> None: ... def set_link_objects(self, objects: list[str]) -> None: ... def detect_language(self, sources: str | list[str]) -> str | None: ... - def find_library_file(self, dirs: list[str], lib: str, debug: bool = ...) -> str | None: ... + def find_library_file(self, dirs: list[str], lib: str, debug: bool | Literal[0, 1] = 0) -> str | None: ... def has_function( self, funcname: str, - includes: list[str] | None = ..., - include_dirs: list[str] | None = ..., - libraries: list[str] | None = ..., - library_dirs: list[str] | None = ..., + includes: list[str] | None = None, + include_dirs: list[str] | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, ) -> bool: ... def library_dir_option(self, dir: str) -> str: ... def library_option(self, lib: str) -> str: ... @@ -52,99 +63,120 @@ class CCompiler: def set_executables(self, **args: str) -> None: ... def compile( self, - sources: list[str], - output_dir: str | None = ..., - macros: _Macro | None = ..., - include_dirs: list[str] | None = ..., - debug: bool = ..., - extra_preargs: list[str] | None = ..., - extra_postargs: list[str] | None = ..., - depends: list[str] | None = ..., + sources: Sequence[StrPath], + output_dir: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + depends: list[str] | None = None, ) -> list[str]: ... def create_static_lib( self, objects: list[str], output_libname: str, - output_dir: str | None = ..., - debug: bool = ..., - target_lang: str | None = ..., + output_dir: str | None = None, + debug: bool | Literal[0, 1] = 0, + target_lang: str | None = None, ) -> None: ... def link( self, target_desc: str, objects: list[str], output_filename: str, - output_dir: str | None = ..., - libraries: list[str] | None = ..., - library_dirs: list[str] | None = ..., - runtime_library_dirs: list[str] | None = ..., - export_symbols: list[str] | None = ..., - debug: bool = ..., - extra_preargs: list[str] | None = ..., - extra_postargs: list[str] | None = ..., - build_temp: str | None = ..., - target_lang: str | None = ..., + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + export_symbols: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | None = None, + target_lang: str | None = None, ) -> None: ... def link_executable( self, objects: list[str], output_progname: str, - output_dir: str | None = ..., - libraries: list[str] | None = ..., - library_dirs: list[str] | None = ..., - runtime_library_dirs: list[str] | None = ..., - debug: bool = ..., - extra_preargs: list[str] | None = ..., - extra_postargs: list[str] | None = ..., - target_lang: str | None = ..., + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + target_lang: str | None = None, ) -> None: ... def link_shared_lib( self, objects: list[str], output_libname: str, - output_dir: str | None = ..., - libraries: list[str] | None = ..., - library_dirs: list[str] | None = ..., - runtime_library_dirs: list[str] | None = ..., - export_symbols: list[str] | None = ..., - debug: bool = ..., - extra_preargs: list[str] | None = ..., - extra_postargs: list[str] | None = ..., - build_temp: str | None = ..., - target_lang: str | None = ..., + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + export_symbols: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | None = None, + target_lang: str | None = None, ) -> None: ... def link_shared_object( self, objects: list[str], output_filename: str, - output_dir: str | None = ..., - libraries: list[str] | None = ..., - library_dirs: list[str] | None = ..., - runtime_library_dirs: list[str] | None = ..., - export_symbols: list[str] | None = ..., - debug: bool = ..., - extra_preargs: list[str] | None = ..., - extra_postargs: list[str] | None = ..., - build_temp: str | None = ..., - target_lang: str | None = ..., + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + export_symbols: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | None = None, + target_lang: str | None = None, ) -> None: ... def preprocess( self, source: str, - output_file: str | None = ..., - macros: list[_Macro] | None = ..., - include_dirs: list[str] | None = ..., - extra_preargs: list[str] | None = ..., - extra_postargs: list[str] | None = ..., + output_file: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | None = None, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, ) -> None: ... - def executable_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... - def library_filename(self, libname: str, lib_type: str = ..., strip_dir: int = ..., output_dir: str = ...) -> str: ... - def object_filenames(self, source_filenames: list[str], strip_dir: int = ..., output_dir: str = ...) -> list[str]: ... - def shared_object_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... - def execute(self, func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., level: int = ...) -> None: ... - def spawn(self, cmd: list[str]) -> None: ... - def mkpath(self, name: str, mode: int = ...) -> None: ... - def move_file(self, src: str, dst: str) -> str: ... - def announce(self, msg: str, level: int = ...) -> None: ... + + @overload + def executable_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = "") -> str: ... + @overload + def executable_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = "") -> str: ... + + def library_filename( + self, libname: str, lib_type: str = "static", strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath = "" + ) -> str: ... + def object_filenames( + self, source_filenames: Iterable[StrPath], strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath | None = "" + ) -> list[str]: ... + + @overload + def shared_object_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = "") -> str: ... + @overload + def shared_object_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = "") -> str: ... + + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def spawn(self, cmd: Iterable[str]) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT) -> _BytesPathT | bytes: ... + + def announce(self, msg: str, level: int = 1) -> None: ... def warn(self, msg: str) -> None: ... def debug_print(self, msg: str) -> None: ... diff --git a/stdlib/distutils/cmd.pyi b/stdlib/distutils/cmd.pyi index 875e851bed39..35b991aba088 100644 --- a/stdlib/distutils/cmd.pyi +++ b/stdlib/distutils/cmd.pyi @@ -1,9 +1,39 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath, Unused from abc import abstractmethod +from collections.abc import Callable, Iterable +from distutils.command.bdist import bdist +from distutils.command.bdist_dumb import bdist_dumb +from distutils.command.bdist_rpm import bdist_rpm +from distutils.command.build import build +from distutils.command.build_clib import build_clib +from distutils.command.build_ext import build_ext +from distutils.command.build_py import build_py +from distutils.command.build_scripts import build_scripts +from distutils.command.check import check +from distutils.command.clean import clean +from distutils.command.config import config +from distutils.command.install import install +from distutils.command.install_data import install_data +from distutils.command.install_egg_info import install_egg_info +from distutils.command.install_headers import install_headers +from distutils.command.install_lib import install_lib +from distutils.command.install_scripts import install_scripts +from distutils.command.register import register +from distutils.command.sdist import sdist +from distutils.command.upload import upload from distutils.dist import Distribution -from typing import Any, Callable, Iterable +from distutils.file_util import _BytesPathT, _StrPathT +from typing import Any, ClassVar, Literal, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack + +_CommandT = TypeVar("_CommandT", bound=Command) +_Ts = TypeVarTuple("_Ts") class Command: - sub_commands: list[tuple[str, Callable[[Command], bool] | None]] + dry_run: bool | Literal[0, 1] # Exposed from __getattr_. Same as Distribution.dry_run + distribution: Distribution + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] def __init__(self, dist: Distribution) -> None: ... @abstractmethod def initialize_options(self) -> None: ... @@ -11,57 +41,198 @@ class Command: def finalize_options(self) -> None: ... @abstractmethod def run(self) -> None: ... - def announce(self, msg: str, level: int = ...) -> None: ... + def announce(self, msg: str, level: int = 1) -> None: ... def debug_print(self, msg: str) -> None: ... - def ensure_string(self, option: str, default: str | None = ...) -> None: ... - def ensure_string_list(self, option: str | list[str]) -> None: ... + def ensure_string(self, option: str, default: str | None = None) -> None: ... + def ensure_string_list(self, option: str) -> None: ... def ensure_filename(self, option: str) -> None: ... def ensure_dirname(self, option: str) -> None: ... def get_command_name(self) -> str: ... def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: ... - def get_finalized_command(self, command: str, create: int = ...) -> Command: ... - def reinitialize_command(self, command: Command | str, reinit_subcommands: int = ...) -> Command: ... + + # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. + @overload + def get_finalized_command(self, command: Literal["bdist"], create: bool | Literal[0, 1] = 1) -> bdist: ... + @overload + def get_finalized_command(self, command: Literal["bdist_dumb"], create: bool | Literal[0, 1] = 1) -> bdist_dumb: ... + @overload + def get_finalized_command(self, command: Literal["bdist_rpm"], create: bool | Literal[0, 1] = 1) -> bdist_rpm: ... + @overload + def get_finalized_command(self, command: Literal["build"], create: bool | Literal[0, 1] = 1) -> build: ... + @overload + def get_finalized_command(self, command: Literal["build_clib"], create: bool | Literal[0, 1] = 1) -> build_clib: ... + @overload + def get_finalized_command(self, command: Literal["build_ext"], create: bool | Literal[0, 1] = 1) -> build_ext: ... + @overload + def get_finalized_command(self, command: Literal["build_py"], create: bool | Literal[0, 1] = 1) -> build_py: ... + @overload + def get_finalized_command(self, command: Literal["build_scripts"], create: bool | Literal[0, 1] = 1) -> build_scripts: ... + @overload + def get_finalized_command(self, command: Literal["check"], create: bool | Literal[0, 1] = 1) -> check: ... + @overload + def get_finalized_command(self, command: Literal["clean"], create: bool | Literal[0, 1] = 1) -> clean: ... + @overload + def get_finalized_command(self, command: Literal["config"], create: bool | Literal[0, 1] = 1) -> config: ... + @overload + def get_finalized_command(self, command: Literal["install"], create: bool | Literal[0, 1] = 1) -> install: ... + @overload + def get_finalized_command(self, command: Literal["install_data"], create: bool | Literal[0, 1] = 1) -> install_data: ... + @overload + def get_finalized_command( + self, command: Literal["install_egg_info"], create: bool | Literal[0, 1] = 1 + ) -> install_egg_info: ... + @overload + def get_finalized_command(self, command: Literal["install_headers"], create: bool | Literal[0, 1] = 1) -> install_headers: ... + @overload + def get_finalized_command(self, command: Literal["install_lib"], create: bool | Literal[0, 1] = 1) -> install_lib: ... + @overload + def get_finalized_command(self, command: Literal["install_scripts"], create: bool | Literal[0, 1] = 1) -> install_scripts: ... + @overload + def get_finalized_command(self, command: Literal["register"], create: bool | Literal[0, 1] = 1) -> register: ... + @overload + def get_finalized_command(self, command: Literal["sdist"], create: bool | Literal[0, 1] = 1) -> sdist: ... + @overload + def get_finalized_command(self, command: Literal["upload"], create: bool | Literal[0, 1] = 1) -> upload: ... + @overload + def get_finalized_command(self, command: str, create: bool | Literal[0, 1] = 1) -> Command: ... + + @overload + def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist: ... + @overload + def reinitialize_command( + self, command: Literal["bdist_dumb"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> bdist_dumb: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist_rpm: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build: ... + @overload + def reinitialize_command( + self, command: Literal["build_clib"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> build_clib: ... + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build_ext: ... + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build_py: ... + @overload + def reinitialize_command( + self, command: Literal["build_scripts"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> build_scripts: ... + @overload + def reinitialize_command(self, command: Literal["check"], reinit_subcommands: bool | Literal[0, 1] = 0) -> check: ... + @overload + def reinitialize_command(self, command: Literal["clean"], reinit_subcommands: bool | Literal[0, 1] = 0) -> clean: ... + @overload + def reinitialize_command(self, command: Literal["config"], reinit_subcommands: bool | Literal[0, 1] = 0) -> config: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool | Literal[0, 1] = 0) -> install: ... + @overload + def reinitialize_command( + self, command: Literal["install_data"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_data: ... + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_egg_info: ... + @overload + def reinitialize_command( + self, command: Literal["install_headers"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_headers: ... + @overload + def reinitialize_command( + self, command: Literal["install_lib"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_lib: ... + @overload + def reinitialize_command( + self, command: Literal["install_scripts"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_scripts: ... + @overload + def reinitialize_command(self, command: Literal["register"], reinit_subcommands: bool | Literal[0, 1] = 0) -> register: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool | Literal[0, 1] = 0) -> sdist: ... + @overload + def reinitialize_command(self, command: Literal["upload"], reinit_subcommands: bool | Literal[0, 1] = 0) -> upload: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool | Literal[0, 1] = 0) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool | Literal[0, 1] = 0) -> _CommandT: ... + def run_command(self, command: str) -> None: ... def get_sub_commands(self) -> list[str]: ... def warn(self, msg: str) -> None: ... - def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: str | None = ..., level: int = ...) -> None: ... - def mkpath(self, name: str, mode: int = ...) -> None: ... + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload def copy_file( self, - infile: str, - outfile: str, - preserve_mode: int = ..., - preserve_times: int = ..., - link: str | None = ..., - level: Any = ..., - ) -> tuple[str, bool]: ... # level is not used + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_StrPathT | str, bool]: ... + @overload + def copy_file( + self, + infile: BytesPath, + outfile: _BytesPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_BytesPathT | bytes, bool]: ... + def copy_tree( self, - infile: str, + infile: StrPath, outfile: str, - preserve_mode: int = ..., - preserve_times: int = ..., - preserve_symlinks: int = ..., - level: Any = ..., - ) -> list[str]: ... # level is not used - def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used - def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + preserve_symlinks: bool | Literal[0, 1] = 0, + level: Unused = 1, + ) -> list[str]: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ... + + def spawn(self, cmd: Iterable[str], search_path: bool | Literal[0, 1] = 1, level: Unused = 1) -> None: ... + + @overload def make_archive( self, base_name: str, format: str, - root_dir: str | None = ..., - base_dir: str | None = ..., - owner: str | None = ..., - group: str | None = ..., + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, ) -> str: ... + @overload + def make_archive( + self, + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + def make_file( self, - infiles: str | list[str] | tuple[str], - outfile: str, - func: Callable[..., Any], - args: list[Any], - exec_msg: str | None = ..., - skip_msg: str | None = ..., - level: Any = ..., - ) -> None: ... # level is not used + infiles: str | list[str] | tuple[str, ...], + outfile: StrOrBytesPath, + func: Callable[[Unpack[_Ts]], Unused], + args: tuple[Unpack[_Ts]], + exec_msg: str | None = None, + skip_msg: str | None = None, + level: Unused = 1, + ) -> None: ... + def ensure_finalized(self) -> None: ... + def dump_options(self, header=None, indent: str = "") -> None: ... diff --git a/stdlib/distutils/command/__init__.pyi b/stdlib/distutils/command/__init__.pyi index a4b9b1c2bd1b..856c5eb8b44a 100644 --- a/stdlib/distutils/command/__init__.pyi +++ b/stdlib/distutils/command/__init__.pyi @@ -1,20 +1,22 @@ from . import ( - bdist_dumb as bdist_dumb, - bdist_rpm as bdist_rpm, - build as build, - build_clib as build_clib, - build_ext as build_ext, - build_py as build_py, - build_scripts as build_scripts, - check as check, - clean as clean, - install as install, - install_data as install_data, - install_headers as install_headers, - install_lib as install_lib, - register as register, - sdist as sdist, - upload as upload, + bdist, + bdist_dumb, + bdist_rpm, + build, + build_clib, + build_ext, + build_py, + build_scripts, + check, + clean, + install, + install_data, + install_headers, + install_lib, + install_scripts, + register, + sdist, + upload, ) __all__ = [ @@ -34,7 +36,6 @@ __all__ = [ "bdist", "bdist_dumb", "bdist_rpm", - "bdist_wininst", "check", "upload", ] diff --git a/stdlib/distutils/command/bdist.pyi b/stdlib/distutils/command/bdist.pyi index e1f141d3a40f..6f996207077e 100644 --- a/stdlib/distutils/command/bdist.pyi +++ b/stdlib/distutils/command/bdist.pyi @@ -1,4 +1,6 @@ -from typing import Any +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar from ..cmd import Command @@ -6,20 +8,20 @@ def show_formats() -> None: ... class bdist(Command): description: str - user_options: Any - boolean_options: Any - help_options: Any - no_format_option: Any - default_format: Any - format_commands: Any - format_command: Any - bdist_base: Any - plat_name: Any - formats: Any - dist_dir: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + no_format_option: ClassVar[tuple[str, ...]] + default_format: ClassVar[dict[str, str]] + format_commands: ClassVar[list[str]] + format_command: ClassVar[dict[str, tuple[str, str]]] + bdist_base: Incomplete + plat_name: Incomplete + formats: Incomplete + dist_dir: Incomplete skip_build: int - group: Any - owner: Any + group: Incomplete + owner: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stdlib/distutils/command/bdist_dumb.pyi b/stdlib/distutils/command/bdist_dumb.pyi index 74cca4d13cd0..297a0c39ed43 100644 --- a/stdlib/distutils/command/bdist_dumb.pyi +++ b/stdlib/distutils/command/bdist_dumb.pyi @@ -1,21 +1,22 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class bdist_dumb(Command): description: str - user_options: Any - boolean_options: Any - default_format: Any - bdist_dir: Any - plat_name: Any - format: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + default_format: ClassVar[dict[str, str]] + bdist_dir: Incomplete + plat_name: Incomplete + format: Incomplete keep_temp: int - dist_dir: Any - skip_build: Any + dist_dir: Incomplete + skip_build: Incomplete relative: int - owner: Any - group: Any + owner: Incomplete + group: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stdlib/distutils/command/bdist_msi.pyi b/stdlib/distutils/command/bdist_msi.pyi index e4f64ff6a59e..d677f81d1425 100644 --- a/stdlib/distutils/command/bdist_msi.pyi +++ b/stdlib/distutils/command/bdist_msi.pyi @@ -1,40 +1,42 @@ import sys -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar, Literal from ..cmd import Command if sys.platform == "win32": - from msilib import Dialog + from msilib import Control, Dialog + class PyDialog(Dialog): def __init__(self, *args, **kw) -> None: ... def title(self, title) -> None: ... - def back(self, title, next, name: str = ..., active: int = ...): ... - def cancel(self, title, next, name: str = ..., active: int = ...): ... - def next(self, title, next, name: str = ..., active: int = ...): ... - def xbutton(self, name, title, next, xpos): ... + def back(self, title, next, name: str = "Back", active: bool | Literal[0, 1] = 1) -> Control: ... + def cancel(self, title, next, name: str = "Cancel", active: bool | Literal[0, 1] = 1) -> Control: ... + def next(self, title, next, name: str = "Next", active: bool | Literal[0, 1] = 1) -> Control: ... + def xbutton(self, name, title, next, xpos) -> Control: ... + class bdist_msi(Command): description: str - user_options: Any - boolean_options: Any - all_versions: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + all_versions: Incomplete other_version: str - if sys.version_info >= (3, 9): - def __init__(self, *args, **kw) -> None: ... - bdist_dir: Any - plat_name: Any + def __init__(self, *args, **kw) -> None: ... + bdist_dir: Incomplete + plat_name: Incomplete keep_temp: int no_target_compile: int no_target_optimize: int - target_version: Any - dist_dir: Any - skip_build: Any - install_script: Any - pre_install_script: Any - versions: Any + target_version: Incomplete + dist_dir: Incomplete + skip_build: Incomplete + install_script: Incomplete + pre_install_script: Incomplete + versions: Incomplete def initialize_options(self) -> None: ... - install_script_key: Any + install_script_key: Incomplete def finalize_options(self) -> None: ... - db: Any + db: Incomplete def run(self) -> None: ... def add_files(self) -> None: ... def add_find_python(self) -> None: ... diff --git a/stdlib/distutils/command/bdist_rpm.pyi b/stdlib/distutils/command/bdist_rpm.pyi index 76691310b599..83b4161094c5 100644 --- a/stdlib/distutils/command/bdist_rpm.pyi +++ b/stdlib/distutils/command/bdist_rpm.pyi @@ -1,50 +1,51 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class bdist_rpm(Command): description: str - user_options: Any - boolean_options: Any - negative_opt: Any - bdist_base: Any - rpm_base: Any - dist_dir: Any - python: Any - fix_python: Any - spec_only: Any - binary_only: Any - source_only: Any - use_bzip2: Any - distribution_name: Any - group: Any - release: Any - serial: Any - vendor: Any - packager: Any - doc_files: Any - changelog: Any - icon: Any - prep_script: Any - build_script: Any - install_script: Any - clean_script: Any - verify_script: Any - pre_install: Any - post_install: Any - pre_uninstall: Any - post_uninstall: Any - prep: Any - provides: Any - requires: Any - conflicts: Any - build_requires: Any - obsoletes: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + bdist_base: Incomplete + rpm_base: Incomplete + dist_dir: Incomplete + python: Incomplete + fix_python: Incomplete + spec_only: Incomplete + binary_only: Incomplete + source_only: Incomplete + use_bzip2: Incomplete + distribution_name: Incomplete + group: Incomplete + release: Incomplete + serial: Incomplete + vendor: Incomplete + packager: Incomplete + doc_files: Incomplete + changelog: Incomplete + icon: Incomplete + prep_script: Incomplete + build_script: Incomplete + install_script: Incomplete + clean_script: Incomplete + verify_script: Incomplete + pre_install: Incomplete + post_install: Incomplete + pre_uninstall: Incomplete + post_uninstall: Incomplete + prep: Incomplete + provides: Incomplete + requires: Incomplete + conflicts: Incomplete + build_requires: Incomplete + obsoletes: Incomplete keep_temp: int use_rpm_opt_flags: int rpm3_mode: int no_autoreq: int - force_arch: Any + force_arch: Incomplete quiet: int def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... diff --git a/stdlib/distutils/command/build.pyi b/stdlib/distutils/command/build.pyi index cf3c8a562ff3..3ec0c9614d62 100644 --- a/stdlib/distutils/command/build.pyi +++ b/stdlib/distutils/command/build.pyi @@ -1,4 +1,6 @@ -from typing import Any +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import Any, ClassVar from ..cmd import Command @@ -6,21 +8,21 @@ def show_compilers() -> None: ... class build(Command): description: str - user_options: Any - boolean_options: Any - help_options: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] build_base: str - build_purelib: Any - build_platlib: Any - build_lib: Any - build_temp: Any - build_scripts: Any - compiler: Any - plat_name: Any - debug: Any + build_purelib: Incomplete + build_platlib: Incomplete + build_lib: Incomplete + build_temp: Incomplete + build_scripts: Incomplete + compiler: Incomplete + plat_name: Incomplete + debug: Incomplete force: int - executable: Any - parallel: Any + executable: Incomplete + parallel: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... @@ -28,4 +30,5 @@ class build(Command): def has_c_libraries(self): ... def has_ext_modules(self): ... def has_scripts(self): ... - sub_commands: Any + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] diff --git a/stdlib/distutils/command/build_clib.pyi b/stdlib/distutils/command/build_clib.pyi index 32ab182b30d0..69cfbe7120d8 100644 --- a/stdlib/distutils/command/build_clib.pyi +++ b/stdlib/distutils/command/build_clib.pyi @@ -1,4 +1,6 @@ -from typing import Any +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar from ..cmd import Command @@ -6,18 +8,18 @@ def show_compilers() -> None: ... class build_clib(Command): description: str - user_options: Any - boolean_options: Any - help_options: Any - build_clib: Any - build_temp: Any - libraries: Any - include_dirs: Any - define: Any - undef: Any - debug: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_clib: Incomplete + build_temp: Incomplete + libraries: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + debug: Incomplete force: int - compiler: Any + compiler: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stdlib/distutils/command/build_ext.pyi b/stdlib/distutils/command/build_ext.pyi index 80cd78936cb9..c5a9b5d508f0 100644 --- a/stdlib/distutils/command/build_ext.pyi +++ b/stdlib/distutils/command/build_ext.pyi @@ -1,38 +1,40 @@ -from typing import Any +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar from ..cmd import Command -extension_name_re: Any +extension_name_re: Incomplete def show_compilers() -> None: ... class build_ext(Command): description: str - sep_by: Any - user_options: Any - boolean_options: Any - help_options: Any - extensions: Any - build_lib: Any - plat_name: Any - build_temp: Any + sep_by: Incomplete + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + extensions: Incomplete + build_lib: Incomplete + plat_name: Incomplete + build_temp: Incomplete inplace: int - package: Any - include_dirs: Any - define: Any - undef: Any - libraries: Any - library_dirs: Any - rpath: Any - link_objects: Any - debug: Any - force: Any - compiler: Any - swig: Any - swig_cpp: Any - swig_opts: Any - user: Any - parallel: Any + package: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + libraries: Incomplete + library_dirs: Incomplete + rpath: Incomplete + link_objects: Incomplete + debug: Incomplete + force: Incomplete + compiler: Incomplete + swig: Incomplete + swig_cpp: Incomplete + swig_opts: Incomplete + user: Incomplete + parallel: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... @@ -43,8 +45,8 @@ class build_ext(Command): def build_extension(self, ext) -> None: ... def swig_sources(self, sources, extension): ... def find_swig(self): ... - def get_ext_fullpath(self, ext_name): ... - def get_ext_fullname(self, ext_name): ... - def get_ext_filename(self, ext_name): ... + def get_ext_fullpath(self, ext_name: str) -> str: ... + def get_ext_fullname(self, ext_name: str) -> str: ... + def get_ext_filename(self, ext_name: str) -> str: ... def get_export_symbols(self, ext): ... def get_libraries(self, ext): ... diff --git a/stdlib/distutils/command/build_py.pyi b/stdlib/distutils/command/build_py.pyi index 3c6e022c2a10..23ed230bb2d8 100644 --- a/stdlib/distutils/command/build_py.pyi +++ b/stdlib/distutils/command/build_py.pyi @@ -1,24 +1,25 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar, Literal from ..cmd import Command from ..util import Mixin2to3 as Mixin2to3 class build_py(Command): description: str - user_options: Any - boolean_options: Any - negative_opt: Any - build_lib: Any - py_modules: Any - package: Any - package_data: Any - package_dir: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + build_lib: Incomplete + py_modules: Incomplete + package: Incomplete + package_data: Incomplete + package_dir: Incomplete compile: int optimize: int - force: Any + force: Incomplete def initialize_options(self) -> None: ... - packages: Any - data_files: Any + packages: Incomplete + data_files: Incomplete def finalize_options(self) -> None: ... def run(self) -> None: ... def get_data_files(self): ... @@ -32,13 +33,13 @@ class build_py(Command): def find_all_modules(self): ... def get_source_files(self): ... def get_module_outfile(self, build_dir, package, module): ... - def get_outputs(self, include_bytecode: int = ...): ... + def get_outputs(self, include_bytecode: bool | Literal[0, 1] = 1) -> list[str]: ... def build_module(self, module, module_file, package): ... def build_modules(self) -> None: ... def build_packages(self) -> None: ... def byte_compile(self, files) -> None: ... class build_py_2to3(build_py, Mixin2to3): - updated_files: Any + updated_files: Incomplete def run(self) -> None: ... def build_module(self, module, module_file, package): ... diff --git a/stdlib/distutils/command/build_scripts.pyi b/stdlib/distutils/command/build_scripts.pyi index 42135eceafef..8372919bbd53 100644 --- a/stdlib/distutils/command/build_scripts.pyi +++ b/stdlib/distutils/command/build_scripts.pyi @@ -1,19 +1,20 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command from ..util import Mixin2to3 as Mixin2to3 -first_line_re: Any +first_line_re: Incomplete class build_scripts(Command): description: str - user_options: Any - boolean_options: Any - build_dir: Any - scripts: Any - force: Any - executable: Any - outfiles: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + build_dir: Incomplete + scripts: Incomplete + force: Incomplete + executable: Incomplete + outfiles: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def get_source_files(self): ... diff --git a/stdlib/distutils/command/check.pyi b/stdlib/distutils/command/check.pyi index 36895d2c16f1..f2034e6555fc 100644 --- a/stdlib/distutils/command/check.pyi +++ b/stdlib/distutils/command/check.pyi @@ -1,30 +1,33 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Any, ClassVar, Final, Literal, TypeAlias from ..cmd import Command -_Reporter = Any # really docutils.utils.Reporter +_Reporter: TypeAlias = Any # really docutils.utils.Reporter # Only defined if docutils is installed. +# Depends on a third-party stub. Since distutils is deprecated anyway, +# it's easier to just suppress the "any subclassing" error. class SilentReporter(_Reporter): - messages: Any + messages: Incomplete def __init__( self, source, report_level, halt_level, - stream: Any | None = ..., - debug: int = ..., + stream: Incomplete | None = ..., + debug: bool | Literal[0, 1] = 0, encoding: str = ..., error_handler: str = ..., ) -> None: ... def system_message(self, level, message, *children, **kwargs): ... -HAS_DOCUTILS: bool +HAS_DOCUTILS: Final[bool] class check(Command): description: str - user_options: Any - boolean_options: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] restructuredtext: int metadata: int strict: int diff --git a/stdlib/distutils/command/clean.pyi b/stdlib/distutils/command/clean.pyi index 99560aa8a716..0f3768d6dcf4 100644 --- a/stdlib/distutils/command/clean.pyi +++ b/stdlib/distutils/command/clean.pyi @@ -1,17 +1,18 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class clean(Command): description: str - user_options: Any - boolean_options: Any - build_base: Any - build_lib: Any - build_temp: Any - build_scripts: Any - bdist_base: Any - all: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + build_base: Incomplete + build_lib: Incomplete + build_temp: Incomplete + build_scripts: Incomplete + bdist_base: Incomplete + all: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stdlib/distutils/command/config.pyi b/stdlib/distutils/command/config.pyi index 7ad71e185df8..381e8e466bf1 100644 --- a/stdlib/distutils/command/config.pyi +++ b/stdlib/distutils/command/config.pyi @@ -1,15 +1,17 @@ +from _typeshed import StrOrBytesPath from collections.abc import Sequence -from typing import Any, Pattern +from re import Pattern +from typing import ClassVar, Final, Literal from ..ccompiler import CCompiler from ..cmd import Command -LANG_EXT: dict[str, str] +LANG_EXT: Final[dict[str, str]] class config(Command): description: str # Tuple is full name, short name, description - user_options: Sequence[tuple[str, str | None, str]] + user_options: ClassVar[list[tuple[str, str | None, str]]] compiler: str | CCompiler cc: str | None include_dirs: Sequence[str] | None @@ -23,60 +25,60 @@ class config(Command): def run(self) -> None: ... def try_cpp( self, - body: str | None = ..., - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - lang: str = ..., + body: str | None = None, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + lang: str = "c", ) -> bool: ... def search_cpp( self, pattern: Pattern[str] | str, - body: str | None = ..., - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - lang: str = ..., + body: str | None = None, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + lang: str = "c", ) -> bool: ... def try_compile( - self, body: str, headers: Sequence[str] | None = ..., include_dirs: Sequence[str] | None = ..., lang: str = ... + self, body: str, headers: Sequence[str] | None = None, include_dirs: Sequence[str] | None = None, lang: str = "c" ) -> bool: ... def try_link( self, body: str, - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - libraries: Sequence[str] | None = ..., - library_dirs: Sequence[str] | None = ..., - lang: str = ..., + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + libraries: Sequence[str] | None = None, + library_dirs: Sequence[str] | None = None, + lang: str = "c", ) -> bool: ... def try_run( self, body: str, - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - libraries: Sequence[str] | None = ..., - library_dirs: Sequence[str] | None = ..., - lang: str = ..., + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + libraries: Sequence[str] | None = None, + library_dirs: Sequence[str] | None = None, + lang: str = "c", ) -> bool: ... def check_func( self, func: str, - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - libraries: Sequence[str] | None = ..., - library_dirs: Sequence[str] | None = ..., - decl: int = ..., - call: int = ..., + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + libraries: Sequence[str] | None = None, + library_dirs: Sequence[str] | None = None, + decl: bool | Literal[0, 1] = 0, + call: bool | Literal[0, 1] = 0, ) -> bool: ... def check_lib( self, library: str, - library_dirs: Sequence[str] | None = ..., - headers: Sequence[str] | None = ..., - include_dirs: Sequence[str] | None = ..., - other_libraries: list[str] = ..., + library_dirs: Sequence[str] | None = None, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + other_libraries: list[str] = [], ) -> bool: ... def check_header( - self, header: str, include_dirs: Sequence[str] | None = ..., library_dirs: Sequence[str] | None = ..., lang: str = ... + self, header: str, include_dirs: Sequence[str] | None = None, library_dirs: Sequence[str] | None = None, lang: str = "c" ) -> bool: ... -def dump_file(filename: str, head: Any | None = ...) -> None: ... +def dump_file(filename: StrOrBytesPath, head=None) -> None: ... diff --git a/stdlib/distutils/command/install.pyi b/stdlib/distutils/command/install.pyi index 47fa8b08d1b2..7e11cf257c2c 100644 --- a/stdlib/distutils/command/install.pyi +++ b/stdlib/distutils/command/install.pyi @@ -1,44 +1,47 @@ -from typing import Any, Tuple +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, ClassVar, Final, Literal from ..cmd import Command -HAS_USER_SITE: bool -SCHEME_KEYS: Tuple[str, ...] -INSTALL_SCHEMES: dict[str, dict[Any, Any]] +HAS_USER_SITE: Final[bool] + +SCHEME_KEYS: Final[tuple[Literal["purelib"], Literal["platlib"], Literal["headers"], Literal["scripts"], Literal["data"]]] +INSTALL_SCHEMES: Final[dict[str, dict[str, str]]] class install(Command): description: str - user_options: Any - boolean_options: Any - negative_opt: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] prefix: str | None - exec_prefix: Any + exec_prefix: Incomplete home: str | None user: bool - install_base: Any - install_platbase: Any + install_base: Incomplete + install_platbase: Incomplete root: str | None - install_purelib: Any - install_platlib: Any - install_headers: Any + install_purelib: Incomplete + install_platlib: Incomplete + install_headers: Incomplete install_lib: str | None - install_scripts: Any - install_data: Any - install_userbase: Any - install_usersite: Any - compile: Any - optimize: Any - extra_path: Any + install_scripts: Incomplete + install_data: Incomplete + install_userbase: Incomplete + install_usersite: Incomplete + compile: Incomplete + optimize: Incomplete + extra_path: Incomplete install_path_file: int force: int skip_build: int warn_dir: int - build_base: Any - build_lib: Any - record: Any + build_base: Incomplete + build_lib: Incomplete + record: Incomplete def initialize_options(self) -> None: ... - config_vars: Any - install_libbase: Any + config_vars: Incomplete + install_libbase: Incomplete def finalize_options(self) -> None: ... def dump_dirs(self, msg) -> None: ... def finalize_unix(self) -> None: ... @@ -47,8 +50,8 @@ class install(Command): def expand_basedirs(self) -> None: ... def expand_dirs(self) -> None: ... def convert_paths(self, *names) -> None: ... - path_file: Any - extra_dirs: Any + path_file: Incomplete + extra_dirs: Incomplete def handle_extra_path(self) -> None: ... def change_roots(self, *names) -> None: ... def create_home_path(self) -> None: ... @@ -60,4 +63,5 @@ class install(Command): def has_headers(self): ... def has_scripts(self): ... def has_data(self): ... - sub_commands: Any + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] diff --git a/stdlib/distutils/command/install_data.pyi b/stdlib/distutils/command/install_data.pyi index 6cc9b528ac9d..609de62b04b5 100644 --- a/stdlib/distutils/command/install_data.pyi +++ b/stdlib/distutils/command/install_data.pyi @@ -1,16 +1,17 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class install_data(Command): description: str - user_options: Any - boolean_options: Any - install_dir: Any - outfiles: Any - root: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + outfiles: Incomplete + root: Incomplete force: int - data_files: Any + data_files: Incomplete warn_dir: int def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... diff --git a/stdlib/distutils/command/install_egg_info.pyi b/stdlib/distutils/command/install_egg_info.pyi index 776eafc1de09..75bb906ce582 100644 --- a/stdlib/distutils/command/install_egg_info.pyi +++ b/stdlib/distutils/command/install_egg_info.pyi @@ -1,14 +1,15 @@ -from typing import Any, ClassVar +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class install_egg_info(Command): description: ClassVar[str] - user_options: ClassVar[list[tuple[str, str | None, str]]] - install_dir: Any + user_options: ClassVar[list[tuple[str, str, str]]] + install_dir: Incomplete def initialize_options(self) -> None: ... - target: Any - outputs: Any + target: Incomplete + outputs: Incomplete def finalize_options(self) -> None: ... def run(self) -> None: ... def get_outputs(self) -> list[str]: ... diff --git a/stdlib/distutils/command/install_headers.pyi b/stdlib/distutils/command/install_headers.pyi index 795bd1cf8356..3caad8a07dca 100644 --- a/stdlib/distutils/command/install_headers.pyi +++ b/stdlib/distutils/command/install_headers.pyi @@ -1,14 +1,15 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class install_headers(Command): description: str - user_options: Any - boolean_options: Any - install_dir: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete force: int - outfiles: Any + outfiles: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stdlib/distutils/command/install_lib.pyi b/stdlib/distutils/command/install_lib.pyi index a6a5e4e73f4c..a537e254904a 100644 --- a/stdlib/distutils/command/install_lib.pyi +++ b/stdlib/distutils/command/install_lib.pyi @@ -1,20 +1,21 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar, Final from ..cmd import Command -PYTHON_SOURCE_EXTENSION: str +PYTHON_SOURCE_EXTENSION: Final = ".py" class install_lib(Command): description: str - user_options: Any - boolean_options: Any - negative_opt: Any - install_dir: Any - build_dir: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + install_dir: Incomplete + build_dir: Incomplete force: int - compile: Any - optimize: Any - skip_build: Any + compile: Incomplete + optimize: Incomplete + skip_build: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stdlib/distutils/command/install_scripts.pyi b/stdlib/distutils/command/install_scripts.pyi index 92728a16a747..658594f32e43 100644 --- a/stdlib/distutils/command/install_scripts.pyi +++ b/stdlib/distutils/command/install_scripts.pyi @@ -1,18 +1,19 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from ..cmd import Command class install_scripts(Command): description: str - user_options: Any - boolean_options: Any - install_dir: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete force: int - build_dir: Any - skip_build: Any + build_dir: Incomplete + skip_build: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... - outfiles: Any + outfiles: Incomplete def run(self) -> None: ... def get_inputs(self): ... def get_outputs(self): ... diff --git a/stdlib/distutils/command/register.pyi b/stdlib/distutils/command/register.pyi index a1a7a45fb3d7..c3bd62aaa7aa 100644 --- a/stdlib/distutils/command/register.pyi +++ b/stdlib/distutils/command/register.pyi @@ -1,10 +1,12 @@ -from typing import Any +from collections.abc import Callable +from typing import Any, ClassVar from ..config import PyPIRCCommand class register(PyPIRCCommand): description: str - sub_commands: Any + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] list_classifiers: int strict: int def initialize_options(self) -> None: ... @@ -15,4 +17,4 @@ class register(PyPIRCCommand): def verify_metadata(self) -> None: ... def send_metadata(self) -> None: ... def build_post_data(self, action): ... - def post_to_server(self, data, auth: Any | None = ...): ... + def post_to_server(self, data, auth=None): ... diff --git a/stdlib/distutils/command/sdist.pyi b/stdlib/distutils/command/sdist.pyi index 636c4a351d19..48a140714dda 100644 --- a/stdlib/distutils/command/sdist.pyi +++ b/stdlib/distutils/command/sdist.pyi @@ -1,4 +1,6 @@ -from typing import Any +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import Any, ClassVar from ..cmd import Command @@ -7,28 +9,29 @@ def show_formats() -> None: ... class sdist(Command): description: str def checking_metadata(self): ... - user_options: Any - boolean_options: Any - help_options: Any - negative_opt: Any - sub_commands: Any - READMES: Any - template: Any - manifest: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + negative_opt: ClassVar[dict[str, str]] + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] + READMES: ClassVar[tuple[str, ...]] + template: Incomplete + manifest: Incomplete use_defaults: int prune: int manifest_only: int force_manifest: int - formats: Any + formats: Incomplete keep_temp: int - dist_dir: Any - archive_files: Any + dist_dir: Incomplete + archive_files: Incomplete metadata_check: int - owner: Any - group: Any + owner: Incomplete + group: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... - filelist: Any + filelist: Incomplete def run(self) -> None: ... def check_metadata(self) -> None: ... def get_file_list(self) -> None: ... diff --git a/stdlib/distutils/command/upload.pyi b/stdlib/distutils/command/upload.pyi index e6b77825c5f5..afcfbaf48677 100644 --- a/stdlib/distutils/command/upload.pyi +++ b/stdlib/distutils/command/upload.pyi @@ -1,4 +1,5 @@ -from typing import Any, ClassVar +from _typeshed import Incomplete +from typing import ClassVar from ..config import PyPIRCCommand @@ -8,10 +9,10 @@ class upload(PyPIRCCommand): password: str show_response: int sign: bool - identity: Any + identity: Incomplete def initialize_options(self) -> None: ... - repository: Any - realm: Any + repository: Incomplete + realm: Incomplete def finalize_options(self) -> None: ... def run(self) -> None: ... def upload_file(self, command: str, pyversion: str, filename: str) -> None: ... diff --git a/stdlib/distutils/core.pyi b/stdlib/distutils/core.pyi index fc4cd81c4752..174f24991351 100644 --- a/stdlib/distutils/core.pyi +++ b/stdlib/distutils/core.pyi @@ -1,7 +1,16 @@ +from _typeshed import Incomplete, StrOrBytesPath +from collections.abc import Mapping from distutils.cmd import Command as Command from distutils.dist import Distribution as Distribution from distutils.extension import Extension as Extension -from typing import Any, Mapping, Type +from typing import Any, Final, Literal + +USAGE: Final[str] + +def gen_usage(script_name: StrOrBytesPath) -> str: ... + +setup_keywords: tuple[str, ...] +extension_keywords: tuple[str, ...] def setup( *, @@ -20,29 +29,30 @@ def setup( scripts: list[str] = ..., ext_modules: list[Extension] = ..., classifiers: list[str] = ..., - distclass: Type[Distribution] = ..., + distclass: type[Distribution] = ..., script_name: str = ..., script_args: list[str] = ..., - options: Mapping[str, Any] = ..., + options: Mapping[str, Incomplete] = ..., license: str = ..., keywords: list[str] | str = ..., platforms: list[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., + cmdclass: Mapping[str, type[Command]] = ..., data_files: list[tuple[str, list[str]]] = ..., package_dir: Mapping[str, str] = ..., obsoletes: list[str] = ..., provides: list[str] = ..., requires: list[str] = ..., command_packages: list[str] = ..., - command_options: Mapping[str, Mapping[str, tuple[Any, Any]]] = ..., + command_options: Mapping[str, Mapping[str, tuple[Incomplete, Incomplete]]] = ..., package_data: Mapping[str, list[str]] = ..., - include_package_data: bool = ..., + include_package_data: bool | Literal[0, 1] = ..., libraries: list[str] = ..., headers: list[str] = ..., ext_package: str = ..., include_dirs: list[str] = ..., password: str = ..., fullname: str = ..., + # Custom Distributions could accept more params **attrs: Any, -) -> None: ... -def run_setup(script_name: str, script_args: list[str] | None = ..., stop_after: str = ...) -> Distribution: ... +) -> Distribution: ... +def run_setup(script_name: str, script_args: list[str] | None = None, stop_after: str = "run") -> Distribution: ... diff --git a/stdlib/distutils/cygwinccompiler.pyi b/stdlib/distutils/cygwinccompiler.pyi index 1f85b254860b..80924d63e471 100644 --- a/stdlib/distutils/cygwinccompiler.pyi +++ b/stdlib/distutils/cygwinccompiler.pyi @@ -1,4 +1,20 @@ from distutils.unixccompiler import UnixCCompiler +from distutils.version import LooseVersion +from re import Pattern +from typing import Final, Literal + +def get_msvcr() -> list[str] | None: ... class CygwinCCompiler(UnixCCompiler): ... class Mingw32CCompiler(CygwinCCompiler): ... + +CONFIG_H_OK: Final = "ok" +CONFIG_H_NOTOK: Final = "not ok" +CONFIG_H_UNCERTAIN: Final = "uncertain" + +def check_config_h() -> tuple[Literal["ok", "not ok", "uncertain"], str]: ... + +RE_VERSION: Final[Pattern[bytes]] + +def get_versions() -> tuple[LooseVersion | None, ...]: ... +def is_cygwingcc() -> bool: ... diff --git a/stdlib/distutils/debug.pyi b/stdlib/distutils/debug.pyi index 11f28a8bc8ae..30095883b064 100644 --- a/stdlib/distutils/debug.pyi +++ b/stdlib/distutils/debug.pyi @@ -1 +1,3 @@ -DEBUG: bool | None +from typing import Final + +DEBUG: Final[str | None] diff --git a/stdlib/distutils/dep_util.pyi b/stdlib/distutils/dep_util.pyi index 929d6ffd0c81..058377accabc 100644 --- a/stdlib/distutils/dep_util.pyi +++ b/stdlib/distutils/dep_util.pyi @@ -1,3 +1,14 @@ -def newer(source: str, target: str) -> bool: ... -def newer_pairwise(sources: list[str], targets: list[str]) -> list[tuple[str, str]]: ... -def newer_group(sources: list[str], target: str, missing: str = ...) -> bool: ... +from _typeshed import StrOrBytesPath, SupportsLenAndGetItem +from collections.abc import Iterable +from typing import Literal, TypeVar + +_SourcesT = TypeVar("_SourcesT", bound=StrOrBytesPath) +_TargetsT = TypeVar("_TargetsT", bound=StrOrBytesPath) + +def newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool | Literal[1]: ... +def newer_pairwise( + sources: SupportsLenAndGetItem[_SourcesT], targets: SupportsLenAndGetItem[_TargetsT] +) -> tuple[list[_SourcesT], list[_TargetsT]]: ... +def newer_group( + sources: Iterable[StrOrBytesPath], target: StrOrBytesPath, missing: Literal["error", "ignore", "newer"] = "error" +) -> Literal[0, 1]: ... diff --git a/stdlib/distutils/dir_util.pyi b/stdlib/distutils/dir_util.pyi index ffe5ff1cfbd4..23e2c3bc28b9 100644 --- a/stdlib/distutils/dir_util.pyi +++ b/stdlib/distutils/dir_util.pyi @@ -1,13 +1,23 @@ -def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> list[str]: ... -def create_tree(base_dir: str, files: list[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Iterable +from typing import Literal + +def mkpath(name: str, mode: int = 0o777, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> list[str]: ... +def create_tree( + base_dir: StrPath, + files: Iterable[StrPath], + mode: int = 0o777, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> None: ... def copy_tree( - src: str, + src: StrPath, dst: str, - preserve_mode: int = ..., - preserve_times: int = ..., - preserve_symlinks: int = ..., - update: int = ..., - verbose: int = ..., - dry_run: int = ..., + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + preserve_symlinks: bool | Literal[0, 1] = 0, + update: bool | Literal[0, 1] = 0, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, ) -> list[str]: ... -def remove_tree(directory: str, verbose: int = ..., dry_run: int = ...) -> None: ... +def remove_tree(directory: StrOrBytesPath, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> None: ... diff --git a/stdlib/distutils/dist.pyi b/stdlib/distutils/dist.pyi index 5bb04b049995..58650e853cce 100644 --- a/stdlib/distutils/dist.pyi +++ b/stdlib/distutils/dist.pyi @@ -1,9 +1,36 @@ -from _typeshed import StrOrBytesPath, SupportsWrite +from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsWrite +from collections.abc import Iterable, MutableMapping from distutils.cmd import Command -from typing import IO, Any, Iterable, Mapping, Type +from distutils.command.bdist import bdist +from distutils.command.bdist_dumb import bdist_dumb +from distutils.command.bdist_rpm import bdist_rpm +from distutils.command.build import build +from distutils.command.build_clib import build_clib +from distutils.command.build_ext import build_ext +from distutils.command.build_py import build_py +from distutils.command.build_scripts import build_scripts +from distutils.command.check import check +from distutils.command.clean import clean +from distutils.command.config import config +from distutils.command.install import install +from distutils.command.install_data import install_data +from distutils.command.install_egg_info import install_egg_info +from distutils.command.install_headers import install_headers +from distutils.command.install_lib import install_lib +from distutils.command.install_scripts import install_scripts +from distutils.command.register import register +from distutils.command.sdist import sdist +from distutils.command.upload import upload +from re import Pattern +from typing import IO, ClassVar, Literal, TypeAlias, TypeVar, overload + +command_re: Pattern[str] + +_OptionsList: TypeAlias = list[tuple[str, str | None, str, int] | tuple[str, str | None, str]] +_CommandT = TypeVar("_CommandT", bound=Command) class DistributionMetadata: - def __init__(self, path: int | StrOrBytesPath | None = ...) -> None: ... + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... name: str | None version: str | None author: str | None @@ -22,7 +49,7 @@ class DistributionMetadata: requires: list[str] | None obsoletes: list[str] | None def read_pkg_file(self, file: IO[str]) -> None: ... - def write_pkg_info(self, base_dir: str) -> None: ... + def write_pkg_info(self, base_dir: StrPath) -> None: ... def write_pkg_file(self, file: SupportsWrite[str]) -> None: ... def get_name(self) -> str: ... def get_version(self) -> str: ... @@ -50,9 +77,242 @@ class DistributionMetadata: def set_obsoletes(self, value: Iterable[str]) -> None: ... class Distribution: - cmdclass: dict[str, Type[Command]] + cmdclass: dict[str, type[Command]] metadata: DistributionMetadata - def __init__(self, attrs: Mapping[str, Any] | None = ...) -> None: ... + def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ... def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ... - def parse_config_files(self, filenames: Iterable[str] | None = ...) -> None: ... - def get_command_obj(self, command: str, create: bool = ...) -> Command | None: ... + def parse_config_files(self, filenames: Iterable[str] | None = None) -> None: ... + global_options: ClassVar[_OptionsList] + common_usage: ClassVar[str] + display_options: ClassVar[_OptionsList] + display_option_names: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + verbose: bool | Literal[0, 1] + dry_run: bool | Literal[0, 1] + help: bool | Literal[0, 1] + command_packages: list[str] | None + script_name: str | None + script_args: list[str] | None + command_options: dict[str, dict[str, tuple[str, str]]] + dist_files: list[tuple[str, str, str]] + packages: Incomplete + package_data: dict[str, list[str]] + package_dir: Incomplete + py_modules: Incomplete + libraries: Incomplete + headers: Incomplete + ext_modules: Incomplete + ext_package: Incomplete + include_dirs: Incomplete + extra_path: Incomplete + scripts: Incomplete + data_files: Incomplete + password: str + command_obj: Incomplete + have_run: Incomplete + want_user_cfg: bool + def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None: ... + def find_config_files(self): ... + commands: Incomplete + def parse_command_line(self): ... + def finalize_options(self) -> None: ... + def handle_display_options(self, option_order): ... + def print_command_list(self, commands, header, max_length) -> None: ... + def print_commands(self) -> None: ... + def get_command_list(self): ... + def get_command_packages(self): ... + + # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. + @overload + def get_command_obj(self, command: Literal["bdist"], create: Literal[1, True] = 1) -> bdist: ... + @overload + def get_command_obj(self, command: Literal["bdist_dumb"], create: Literal[1, True] = 1) -> bdist_dumb: ... + @overload + def get_command_obj(self, command: Literal["bdist_rpm"], create: Literal[1, True] = 1) -> bdist_rpm: ... + @overload + def get_command_obj(self, command: Literal["build"], create: Literal[1, True] = 1) -> build: ... + @overload + def get_command_obj(self, command: Literal["build_clib"], create: Literal[1, True] = 1) -> build_clib: ... + @overload + def get_command_obj(self, command: Literal["build_ext"], create: Literal[1, True] = 1) -> build_ext: ... + @overload + def get_command_obj(self, command: Literal["build_py"], create: Literal[1, True] = 1) -> build_py: ... + @overload + def get_command_obj(self, command: Literal["build_scripts"], create: Literal[1, True] = 1) -> build_scripts: ... + @overload + def get_command_obj(self, command: Literal["check"], create: Literal[1, True] = 1) -> check: ... + @overload + def get_command_obj(self, command: Literal["clean"], create: Literal[1, True] = 1) -> clean: ... + @overload + def get_command_obj(self, command: Literal["config"], create: Literal[1, True] = 1) -> config: ... + @overload + def get_command_obj(self, command: Literal["install"], create: Literal[1, True] = 1) -> install: ... + @overload + def get_command_obj(self, command: Literal["install_data"], create: Literal[1, True] = 1) -> install_data: ... + @overload + def get_command_obj(self, command: Literal["install_egg_info"], create: Literal[1, True] = 1) -> install_egg_info: ... + @overload + def get_command_obj(self, command: Literal["install_headers"], create: Literal[1, True] = 1) -> install_headers: ... + @overload + def get_command_obj(self, command: Literal["install_lib"], create: Literal[1, True] = 1) -> install_lib: ... + @overload + def get_command_obj(self, command: Literal["install_scripts"], create: Literal[1, True] = 1) -> install_scripts: ... + @overload + def get_command_obj(self, command: Literal["register"], create: Literal[1, True] = 1) -> register: ... + @overload + def get_command_obj(self, command: Literal["sdist"], create: Literal[1, True] = 1) -> sdist: ... + @overload + def get_command_obj(self, command: Literal["upload"], create: Literal[1, True] = 1) -> upload: ... + @overload + def get_command_obj(self, command: str, create: Literal[1, True] = 1) -> Command: ... + # Not replicating the overloads for "Command | None", user may use "isinstance" + @overload + def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ... + + @overload + def get_command_class(self, command: Literal["bdist"]) -> type[bdist]: ... + @overload + def get_command_class(self, command: Literal["bdist_dumb"]) -> type[bdist_dumb]: ... + @overload + def get_command_class(self, command: Literal["bdist_rpm"]) -> type[bdist_rpm]: ... + @overload + def get_command_class(self, command: Literal["build"]) -> type[build]: ... + @overload + def get_command_class(self, command: Literal["build_clib"]) -> type[build_clib]: ... + @overload + def get_command_class(self, command: Literal["build_ext"]) -> type[build_ext]: ... + @overload + def get_command_class(self, command: Literal["build_py"]) -> type[build_py]: ... + @overload + def get_command_class(self, command: Literal["build_scripts"]) -> type[build_scripts]: ... + @overload + def get_command_class(self, command: Literal["check"]) -> type[check]: ... + @overload + def get_command_class(self, command: Literal["clean"]) -> type[clean]: ... + @overload + def get_command_class(self, command: Literal["config"]) -> type[config]: ... + @overload + def get_command_class(self, command: Literal["install"]) -> type[install]: ... + @overload + def get_command_class(self, command: Literal["install_data"]) -> type[install_data]: ... + @overload + def get_command_class(self, command: Literal["install_egg_info"]) -> type[install_egg_info]: ... + @overload + def get_command_class(self, command: Literal["install_headers"]) -> type[install_headers]: ... + @overload + def get_command_class(self, command: Literal["install_lib"]) -> type[install_lib]: ... + @overload + def get_command_class(self, command: Literal["install_scripts"]) -> type[install_scripts]: ... + @overload + def get_command_class(self, command: Literal["register"]) -> type[register]: ... + @overload + def get_command_class(self, command: Literal["sdist"]) -> type[sdist]: ... + @overload + def get_command_class(self, command: Literal["upload"]) -> type[upload]: ... + @overload + def get_command_class(self, command: str) -> type[Command]: ... + + @overload + def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool = False) -> bdist: ... + @overload + def reinitialize_command(self, command: Literal["bdist_dumb"], reinit_subcommands: bool = False) -> bdist_dumb: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool = False) -> bdist_rpm: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool = False) -> build: ... + @overload + def reinitialize_command(self, command: Literal["build_clib"], reinit_subcommands: bool = False) -> build_clib: ... + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool = False) -> build_ext: ... + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool = False) -> build_py: ... + @overload + def reinitialize_command(self, command: Literal["build_scripts"], reinit_subcommands: bool = False) -> build_scripts: ... + @overload + def reinitialize_command(self, command: Literal["check"], reinit_subcommands: bool = False) -> check: ... + @overload + def reinitialize_command(self, command: Literal["clean"], reinit_subcommands: bool = False) -> clean: ... + @overload + def reinitialize_command(self, command: Literal["config"], reinit_subcommands: bool = False) -> config: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool = False) -> install: ... + @overload + def reinitialize_command(self, command: Literal["install_data"], reinit_subcommands: bool = False) -> install_data: ... + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool = False + ) -> install_egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install_headers"], reinit_subcommands: bool = False) -> install_headers: ... + @overload + def reinitialize_command(self, command: Literal["install_lib"], reinit_subcommands: bool = False) -> install_lib: ... + @overload + def reinitialize_command(self, command: Literal["install_scripts"], reinit_subcommands: bool = False) -> install_scripts: ... + @overload + def reinitialize_command(self, command: Literal["register"], reinit_subcommands: bool = False) -> register: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool = False) -> sdist: ... + @overload + def reinitialize_command(self, command: Literal["upload"], reinit_subcommands: bool = False) -> upload: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def announce(self, msg, level: int = 2) -> None: ... + def run_commands(self) -> None: ... + def run_command(self, command: str) -> None: ... + def has_pure_modules(self) -> bool: ... + def has_ext_modules(self) -> bool: ... + def has_c_libraries(self) -> bool: ... + def has_modules(self) -> bool: ... + def has_headers(self) -> bool: ... + def has_scripts(self) -> bool: ... + def has_data_files(self) -> bool: ... + def is_pure(self) -> bool: ... + + # Default getter methods generated in __init__ from self.metadata._METHOD_BASENAMES + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> str | list[str]: ... + def get_platforms(self) -> str | list[str]: ... + def get_classifiers(self) -> str | list[str]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> list[str]: ... + def get_provides(self) -> list[str]: ... + def get_obsoletes(self) -> list[str]: ... + + # Default attributes generated in __init__ from self.display_option_names + help_commands: bool | Literal[0] + name: str | Literal[0] + version: str | Literal[0] + fullname: str | Literal[0] + author: str | Literal[0] + author_email: str | Literal[0] + maintainer: str | Literal[0] + maintainer_email: str | Literal[0] + contact: str | Literal[0] + contact_email: str | Literal[0] + url: str | Literal[0] + license: str | Literal[0] + licence: str | Literal[0] + description: str | Literal[0] + long_description: str | Literal[0] + platforms: str | list[str] | Literal[0] + classifiers: str | list[str] | Literal[0] + keywords: str | list[str] | Literal[0] + provides: list[str] | Literal[0] + requires: list[str] | Literal[0] + obsoletes: list[str] | Literal[0] diff --git a/stdlib/distutils/extension.pyi b/stdlib/distutils/extension.pyi index 655ea1e9e347..789bbf6ec3d1 100644 --- a/stdlib/distutils/extension.pyi +++ b/stdlib/distutils/extension.pyi @@ -1,20 +1,36 @@ class Extension: + name: str + sources: list[str] + include_dirs: list[str] + define_macros: list[tuple[str, str | None]] + undef_macros: list[str] + library_dirs: list[str] + libraries: list[str] + runtime_library_dirs: list[str] + extra_objects: list[str] + extra_compile_args: list[str] + extra_link_args: list[str] + export_symbols: list[str] + swig_opts: list[str] + depends: list[str] + language: str | None + optional: bool | None def __init__( self, name: str, sources: list[str], - include_dirs: list[str] | None = ..., - define_macros: list[tuple[str, str | None]] | None = ..., - undef_macros: list[str] | None = ..., - library_dirs: list[str] | None = ..., - libraries: list[str] | None = ..., - runtime_library_dirs: list[str] | None = ..., - extra_objects: list[str] | None = ..., - extra_compile_args: list[str] | None = ..., - extra_link_args: list[str] | None = ..., - export_symbols: list[str] | None = ..., - swig_opts: str | None = ..., # undocumented - depends: list[str] | None = ..., - language: str | None = ..., - optional: bool | None = ..., + include_dirs: list[str] | None = None, + define_macros: list[tuple[str, str | None]] | None = None, + undef_macros: list[str] | None = None, + library_dirs: list[str] | None = None, + libraries: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + extra_objects: list[str] | None = None, + extra_compile_args: list[str] | None = None, + extra_link_args: list[str] | None = None, + export_symbols: list[str] | None = None, + swig_opts: list[str] | None = None, + depends: list[str] | None = None, + language: str | None = None, + optional: bool | None = None, ) -> None: ... diff --git a/stdlib/distutils/fancy_getopt.pyi b/stdlib/distutils/fancy_getopt.pyi index 06a0847e4687..676ce1bea313 100644 --- a/stdlib/distutils/fancy_getopt.pyi +++ b/stdlib/distutils/fancy_getopt.pyi @@ -1,22 +1,45 @@ -from typing import Any, Iterable, List, Mapping, Optional, Tuple, overload +from collections.abc import Iterable, Mapping +from getopt import _SliceableT, _StrSequenceT_co +from re import Pattern +from typing import Any, Final, TypeAlias, overload -_Option = Tuple[str, Optional[str], str] -_GR = Tuple[List[str], OptionDummy] +_Option: TypeAlias = tuple[str, str | None, str] -def fancy_getopt( - options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: list[str] | None -) -> list[str] | _GR: ... -def wrap_text(text: str, width: int) -> list[str]: ... +longopt_pat: Final = r"[a-zA-Z](?:[a-zA-Z0-9-]*)" +longopt_re: Final[Pattern[str]] +neg_alias_re: Final[Pattern[str]] +longopt_xlate: Final[dict[int, int]] class FancyGetopt: - def __init__(self, option_table: list[_Option] | None = ...) -> None: ... - # TODO kinda wrong, `getopt(object=object())` is invalid + def __init__(self, option_table: list[_Option] | None = None) -> None: ... + + # TODO: kinda wrong, `getopt(object=object())` is invalid @overload - def getopt(self, args: list[str] | None = ...) -> _GR: ... + def getopt( + self, args: _SliceableT[_StrSequenceT_co] | None = None, object: None = None + ) -> tuple[_StrSequenceT_co, OptionDummy]: ... @overload - def getopt(self, args: list[str] | None, object: Any) -> list[str]: ... + def getopt( + self, args: _SliceableT[_StrSequenceT_co] | None, object: Any + ) -> _StrSequenceT_co: ... # object is an arbitrary non-slotted object + def get_option_order(self) -> list[tuple[str, str]]: ... - def generate_help(self, header: str | None = ...) -> list[str]: ... + def generate_help(self, header: str | None = None) -> list[str]: ... + +# Same note as FancyGetopt.getopt +@overload +def fancy_getopt( + options: list[_Option], negative_opt: Mapping[_Option, _Option], object: None, args: _SliceableT[_StrSequenceT_co] | None +) -> tuple[_StrSequenceT_co, OptionDummy]: ... +@overload +def fancy_getopt( + options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: _SliceableT[_StrSequenceT_co] | None +) -> _StrSequenceT_co: ... + +WS_TRANS: Final[dict[int, str]] + +def wrap_text(text: str, width: int) -> list[str]: ... +def translate_longopt(opt: str) -> str: ... class OptionDummy: - def __init__(self, options: Iterable[str] = ...) -> None: ... + def __init__(self, options: Iterable[str] = []) -> None: ... diff --git a/stdlib/distutils/file_util.pyi b/stdlib/distutils/file_util.pyi index a7f24105a678..9d5bf5080b05 100644 --- a/stdlib/distutils/file_util.pyi +++ b/stdlib/distutils/file_util.pyi @@ -1,14 +1,40 @@ -from typing import Sequence +from _typeshed import BytesPath, StrOrBytesPath, StrPath +from collections.abc import Iterable +from typing import Literal, TypeVar, overload +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) + +@overload +def copy_file( + src: StrPath, + dst: _StrPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + update: bool | Literal[0, 1] = 0, + link: str | None = None, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> tuple[_StrPathT | str, bool]: ... +@overload def copy_file( - src: str, - dst: str, - preserve_mode: bool = ..., - preserve_times: bool = ..., - update: bool = ..., - link: str | None = ..., - verbose: bool = ..., - dry_run: bool = ..., -) -> tuple[str, str]: ... -def move_file(src: str, dst: str, verbose: bool = ..., dry_run: bool = ...) -> str: ... -def write_file(filename: str, contents: Sequence[str]) -> None: ... + src: BytesPath, + dst: _BytesPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + update: bool | Literal[0, 1] = 0, + link: str | None = None, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> tuple[_BytesPathT | bytes, bool]: ... + +@overload +def move_file( + src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0 +) -> _StrPathT | str: ... +@overload +def move_file( + src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0 +) -> _BytesPathT | bytes: ... + +def write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None: ... diff --git a/stdlib/distutils/filelist.pyi b/stdlib/distutils/filelist.pyi index 2b436938f13e..c3347fe7d1d2 100644 --- a/stdlib/distutils/filelist.pyi +++ b/stdlib/distutils/filelist.pyi @@ -1,49 +1,61 @@ -from typing import Iterable, Pattern, overload -from typing_extensions import Literal +from collections.abc import Iterable +from re import Pattern +from typing import Literal, overload # class is entirely undocumented class FileList: allfiles: Iterable[str] | None files: list[str] - def __init__(self, warn: None = ..., debug_print: None = ...) -> None: ... + def __init__(self, warn: None = None, debug_print: None = None) -> None: ... def set_allfiles(self, allfiles: Iterable[str]) -> None: ... - def findall(self, dir: str = ...) -> None: ... + def findall(self, dir: str = ".") -> None: ... def debug_print(self, msg: str) -> None: ... def append(self, item: str) -> None: ... def extend(self, items: Iterable[str]) -> None: ... def sort(self) -> None: ... def remove_duplicates(self) -> None: ... def process_template_line(self, line: str) -> None: ... + @overload def include_pattern( - self, pattern: str, anchor: int | bool = ..., prefix: str | None = ..., is_regex: Literal[0, False] = ... + self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 ) -> bool: ... @overload - def include_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1] = ...) -> bool: ... + def include_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> bool: ... @overload def include_pattern( - self, pattern: str | Pattern[str], anchor: int | bool = ..., prefix: str | None = ..., is_regex: int | bool = ... + self, + pattern: str | Pattern[str], + anchor: bool | Literal[0, 1] = 1, + prefix: str | None = None, + is_regex: bool | Literal[0, 1] = 0, ) -> bool: ... + @overload def exclude_pattern( - self, pattern: str, anchor: int | bool = ..., prefix: str | None = ..., is_regex: Literal[0, False] = ... + self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 ) -> bool: ... @overload - def exclude_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1] = ...) -> bool: ... + def exclude_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> bool: ... @overload def exclude_pattern( - self, pattern: str | Pattern[str], anchor: int | bool = ..., prefix: str | None = ..., is_regex: int | bool = ... + self, + pattern: str | Pattern[str], + anchor: bool | Literal[0, 1] = 1, + prefix: str | None = None, + is_regex: bool | Literal[0, 1] = 0, ) -> bool: ... -def findall(dir: str = ...) -> list[str]: ... +def findall(dir: str = ".") -> list[str]: ... def glob_to_re(pattern: str) -> str: ... + @overload def translate_pattern( - pattern: str, anchor: int | bool = ..., prefix: str | None = ..., is_regex: Literal[False, 0] = ... + pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[False, 0] = 0 ) -> Pattern[str]: ... @overload -def translate_pattern(pattern: str | Pattern[str], *, is_regex: Literal[True, 1] = ...) -> Pattern[str]: ... +def translate_pattern(pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> Pattern[str]: ... @overload def translate_pattern( - pattern: str | Pattern[str], anchor: int | bool = ..., prefix: str | None = ..., is_regex: int | bool = ... + pattern: str | Pattern[str], anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: bool | Literal[0, 1] = 0 ) -> Pattern[str]: ... diff --git a/stdlib/distutils/log.pyi b/stdlib/distutils/log.pyi index 549b569e7356..7246dd6be0cd 100644 --- a/stdlib/distutils/log.pyi +++ b/stdlib/distutils/log.pyi @@ -1,13 +1,14 @@ -from typing import Any +from typing import Any, Final -DEBUG: int -INFO: int -WARN: int -ERROR: int -FATAL: int +DEBUG: Final = 1 +INFO: Final = 2 +WARN: Final = 3 +ERROR: Final = 4 +FATAL: Final = 5 class Log: - def __init__(self, threshold: int = ...) -> None: ... + def __init__(self, threshold: int = 3) -> None: ... + # Arbitrary msg args' type depends on the format method def log(self, level: int, msg: str, *args: Any) -> None: ... def debug(self, msg: str, *args: Any) -> None: ... def info(self, msg: str, *args: Any) -> None: ... diff --git a/stdlib/distutils/spawn.pyi b/stdlib/distutils/spawn.pyi index dda05ad7e85a..ae07a49504fe 100644 --- a/stdlib/distutils/spawn.pyi +++ b/stdlib/distutils/spawn.pyi @@ -1,2 +1,10 @@ -def spawn(cmd: list[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... -def find_executable(executable: str, path: str | None = ...) -> str | None: ... +from collections.abc import Iterable +from typing import Literal + +def spawn( + cmd: Iterable[str], + search_path: bool | Literal[0, 1] = 1, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, +) -> None: ... +def find_executable(executable: str, path: str | None = None) -> str | None: ... diff --git a/stdlib/distutils/sysconfig.pyi b/stdlib/distutils/sysconfig.pyi index 3f579be40882..7c8e0e7b149e 100644 --- a/stdlib/distutils/sysconfig.pyi +++ b/stdlib/distutils/sysconfig.pyi @@ -1,13 +1,32 @@ +from collections.abc import Mapping from distutils.ccompiler import CCompiler -from typing import Mapping +from typing import Final, Literal, overload +from typing_extensions import deprecated -PREFIX: str -EXEC_PREFIX: str +PREFIX: Final[str] +EXEC_PREFIX: Final[str] +BASE_PREFIX: Final[str] +BASE_EXEC_PREFIX: Final[str] +project_base: Final[str] +python_build: Final[bool] +def expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: ... + +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") +def get_config_var(name: Literal["SO"]) -> int | str | None: ... +@overload def get_config_var(name: str) -> int | str | None: ... -def get_config_vars(*args: str) -> Mapping[str, int | str]: ... + +@overload +def get_config_vars() -> dict[str, str | int]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... + def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... -def get_python_inc(plat_specific: bool = ..., prefix: str | None = ...) -> str: ... -def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., prefix: str | None = ...) -> str: ... +def get_python_inc(plat_specific: bool | Literal[0, 1] = 0, prefix: str | None = None) -> str: ... +def get_python_lib( + plat_specific: bool | Literal[0, 1] = 0, standard_lib: bool | Literal[0, 1] = 0, prefix: str | None = None +) -> str: ... def customize_compiler(compiler: CCompiler) -> None: ... diff --git a/stdlib/distutils/text_file.pyi b/stdlib/distutils/text_file.pyi index ace642e027cf..54951af7e55d 100644 --- a/stdlib/distutils/text_file.pyi +++ b/stdlib/distutils/text_file.pyi @@ -1,21 +1,21 @@ -from typing import IO +from typing import IO, Literal class TextFile: def __init__( self, - filename: str | None = ..., - file: IO[str] | None = ..., + filename: str | None = None, + file: IO[str] | None = None, *, - strip_comments: bool = ..., - lstrip_ws: bool = ..., - rstrip_ws: bool = ..., - skip_blanks: bool = ..., - join_lines: bool = ..., - collapse_join: bool = ..., + strip_comments: bool | Literal[0, 1] = ..., + lstrip_ws: bool | Literal[0, 1] = ..., + rstrip_ws: bool | Literal[0, 1] = ..., + skip_blanks: bool | Literal[0, 1] = ..., + join_lines: bool | Literal[0, 1] = ..., + collapse_join: bool | Literal[0, 1] = ..., ) -> None: ... def open(self, filename: str) -> None: ... def close(self) -> None: ... - def warn(self, msg: str, line: list[int] | tuple[int, int] | int | None = ...) -> None: ... + def warn(self, msg: str, line: list[int] | tuple[int, int] | int | None = None) -> None: ... def readline(self) -> str | None: ... def readlines(self) -> list[str]: ... def unreadline(self, line: str) -> str: ... diff --git a/stdlib/distutils/util.pyi b/stdlib/distutils/util.pyi index 9b0915570ece..0e1bb4165d99 100644 --- a/stdlib/distutils/util.pyi +++ b/stdlib/distutils/util.pyi @@ -1,41 +1,49 @@ -from _typeshed import StrPath +from _typeshed import StrPath, Unused from collections.abc import Callable, Container, Iterable, Mapping -from typing import Any, Tuple +from typing import Any, Literal +from typing_extensions import TypeVarTuple, Unpack +_Ts = TypeVarTuple("_Ts") + +def get_host_platform() -> str: ... def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... -def change_root(new_root: str, pathname: str) -> str: ... +def change_root(new_root: StrPath, pathname: StrPath) -> str: ... def check_environ() -> None: ... def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... def split_quoted(s: str) -> list[str]: ... def execute( - func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... + func: Callable[[Unpack[_Ts]], Unused], + args: tuple[Unpack[_Ts]], + msg: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, ) -> None: ... -def strtobool(val: str) -> bool: ... +def strtobool(val: str) -> Literal[0, 1]: ... def byte_compile( py_files: list[str], - optimize: int = ..., - force: bool = ..., - prefix: str | None = ..., - base_dir: str | None = ..., - verbose: bool = ..., - dry_run: bool = ..., - direct: bool | None = ..., + optimize: int = 0, + force: bool | Literal[0, 1] = 0, + prefix: str | None = None, + base_dir: str | None = None, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, + direct: bool | None = None, ) -> None: ... def rfc822_escape(header: str) -> str: ... def run_2to3( files: Iterable[str], - fixer_names: Iterable[str] | None = ..., - options: Mapping[str, Any] | None = ..., - explicit: Container[str] | None = ..., # unused + fixer_names: Iterable[str] | None = None, + options: Mapping[str, Any] | None = None, + explicit: Unused = None, ) -> None: ... def copydir_run_2to3( src: StrPath, dest: StrPath, - template: str | None = ..., - fixer_names: Iterable[str] | None = ..., - options: Mapping[str, Any] | None = ..., - explicit: Container[str] | None = ..., + template: str | None = None, + fixer_names: Iterable[str] | None = None, + options: Mapping[str, Any] | None = None, + explicit: Container[str] | None = None, ) -> list[str]: ... class Mixin2to3: diff --git a/stdlib/distutils/version.pyi b/stdlib/distutils/version.pyi index 9921dde39af6..47da65ef87aa 100644 --- a/stdlib/distutils/version.pyi +++ b/stdlib/distutils/version.pyi @@ -1,38 +1,36 @@ from abc import abstractmethod -from typing import Pattern, Tuple, TypeVar - -_T = TypeVar("_T", bound=Version) +from re import Pattern +from typing_extensions import Self class Version: - def __repr__(self) -> str: ... def __eq__(self, other: object) -> bool: ... - def __lt__(self: _T, other: _T | str) -> bool: ... - def __le__(self: _T, other: _T | str) -> bool: ... - def __gt__(self: _T, other: _T | str) -> bool: ... - def __ge__(self: _T, other: _T | str) -> bool: ... + def __lt__(self, other: Self | str) -> bool: ... + def __le__(self, other: Self | str) -> bool: ... + def __gt__(self, other: Self | str) -> bool: ... + def __ge__(self, other: Self | str) -> bool: ... @abstractmethod - def __init__(self, vstring: str | None = ...) -> None: ... + def __init__(self, vstring: str | None = None) -> None: ... @abstractmethod - def parse(self: _T, vstring: str) -> _T: ... + def parse(self, vstring: str) -> Self: ... @abstractmethod def __str__(self) -> str: ... @abstractmethod - def _cmp(self: _T, other: _T | str) -> bool: ... + def _cmp(self, other: Self | str) -> bool: ... class StrictVersion(Version): version_re: Pattern[str] version: tuple[int, int, int] prerelease: tuple[str, int] | None - def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... - def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa: Y029 + def _cmp(self, other: Self | str) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] vstring: str - version: Tuple[str | int, ...] - def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... - def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + version: tuple[str | int, ...] + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa: Y029 + def _cmp(self, other: Self | str) -> bool: ... diff --git a/stdlib/doctest.pyi b/stdlib/doctest.pyi index 9a9f83b0d8fe..000278ae953e 100644 --- a/stdlib/doctest.pyi +++ b/stdlib/doctest.pyi @@ -1,34 +1,85 @@ +import sys import types import unittest -from typing import Any, Callable, NamedTuple, Tuple, Type +from _typeshed import ExcInfo +from collections.abc import Callable +from typing import Any, Final, NamedTuple, TypeAlias, type_check_only +from typing_extensions import Self -class TestResults(NamedTuple): - failed: int - attempted: int +__all__ = [ + "register_optionflag", + "DONT_ACCEPT_TRUE_FOR_1", + "DONT_ACCEPT_BLANKLINE", + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "SKIP", + "IGNORE_EXCEPTION_DETAIL", + "COMPARISON_FLAGS", + "REPORT_UDIFF", + "REPORT_CDIFF", + "REPORT_NDIFF", + "REPORT_ONLY_FIRST_FAILURE", + "REPORTING_FLAGS", + "FAIL_FAST", + "Example", + "DocTest", + "DocTestParser", + "DocTestFinder", + "DocTestRunner", + "OutputChecker", + "DocTestFailure", + "UnexpectedException", + "DebugRunner", + "testmod", + "testfile", + "run_docstring_examples", + "DocTestSuite", + "DocFileSuite", + "set_unittest_reportflags", + "script_from_examples", + "testsource", + "debug_src", + "debug", +] -OPTIONFLAGS_BY_NAME: dict[str, int] +if sys.version_info >= (3, 13): + @type_check_only + class _TestResultsBase(NamedTuple): + failed: int + attempted: int + + class TestResults(_TestResultsBase): + def __new__(cls, failed: int, attempted: int, *, skipped: int = 0) -> Self: ... + skipped: int + +else: + class TestResults(NamedTuple): + failed: int + attempted: int + +OPTIONFLAGS_BY_NAME: Final[dict[str, int]] def register_optionflag(name: str) -> int: ... -DONT_ACCEPT_TRUE_FOR_1: int -DONT_ACCEPT_BLANKLINE: int -NORMALIZE_WHITESPACE: int -ELLIPSIS: int -SKIP: int -IGNORE_EXCEPTION_DETAIL: int +DONT_ACCEPT_TRUE_FOR_1: Final = 1 +DONT_ACCEPT_BLANKLINE: Final = 2 +NORMALIZE_WHITESPACE: Final = 4 +ELLIPSIS: Final = 8 +SKIP: Final = 16 +IGNORE_EXCEPTION_DETAIL: Final = 32 -COMPARISON_FLAGS: int +COMPARISON_FLAGS: Final = 63 -REPORT_UDIFF: int -REPORT_CDIFF: int -REPORT_NDIFF: int -REPORT_ONLY_FIRST_FAILURE: int -FAIL_FAST: int +REPORT_UDIFF: Final = 64 +REPORT_CDIFF: Final = 128 +REPORT_NDIFF: Final = 256 +REPORT_ONLY_FIRST_FAILURE: Final = 512 +FAIL_FAST: Final = 1024 -REPORTING_FLAGS: int +REPORTING_FLAGS: Final = 1984 -BLANKLINE_MARKER: str -ELLIPSIS_MARKER: str +BLANKLINE_MARKER: Final = "" +ELLIPSIS_MARKER: Final = "..." class Example: source: str @@ -41,12 +92,13 @@ class Example: self, source: str, want: str, - exc_msg: str | None = ..., - lineno: int = ..., - indent: int = ..., - options: dict[int, bool] | None = ..., + exc_msg: str | None = None, + lineno: int = 0, + indent: int = 0, + options: dict[int, bool] | None = None, ) -> None: ... def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... class DocTest: examples: list[Example] @@ -66,27 +118,27 @@ class DocTest: ) -> None: ... def __hash__(self) -> int: ... def __lt__(self, other: DocTest) -> bool: ... + def __eq__(self, other: object) -> bool: ... class DocTestParser: - def parse(self, string: str, name: str = ...) -> list[str | Example]: ... + def parse(self, string: str, name: str = "") -> list[str | Example]: ... def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... - def get_examples(self, string: str, name: str = ...) -> list[Example]: ... + def get_examples(self, string: str, name: str = "") -> list[Example]: ... class DocTestFinder: def __init__( - self, verbose: bool = ..., parser: DocTestParser = ..., recurse: bool = ..., exclude_empty: bool = ... + self, verbose: bool = False, parser: DocTestParser = ..., recurse: bool = True, exclude_empty: bool = True ) -> None: ... def find( self, obj: object, - name: str | None = ..., - module: None | bool | types.ModuleType = ..., - globs: dict[str, Any] | None = ..., - extraglobs: dict[str, Any] | None = ..., + name: str | None = None, + module: bool | types.ModuleType | None = None, + globs: dict[str, Any] | None = None, + extraglobs: dict[str, Any] | None = None, ) -> list[DocTest]: ... -_Out = Callable[[str], Any] -_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] +_Out: TypeAlias = Callable[[str], object] class DocTestRunner: DIVIDER: str @@ -94,16 +146,21 @@ class DocTestRunner: original_optionflags: int tries: int failures: int + if sys.version_info >= (3, 13): + skips: int test: DocTest - def __init__(self, checker: OutputChecker | None = ..., verbose: bool | None = ..., optionflags: int = ...) -> None: ... + def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: ... + if sys.version_info >= (3, 15): + def report_skip(self, out: _Out, test: DocTest, example: Example) -> None: ... + def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ... def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... - def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... def run( - self, test: DocTest, compileflags: int | None = ..., out: _Out | None = ..., clear_globs: bool = ... + self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True ) -> TestResults: ... - def summarize(self, verbose: bool | None = ...) -> TestResults: ... + def summarize(self, verbose: bool | None = None) -> TestResults: ... def merge(self, other: DocTestRunner) -> None: ... class OutputChecker: @@ -119,40 +176,45 @@ class DocTestFailure(Exception): class UnexpectedException(Exception): test: DocTest example: Example - exc_info: _ExcInfo - def __init__(self, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + exc_info: ExcInfo + def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... class DebugRunner(DocTestRunner): ... master: DocTestRunner | None def testmod( - m: types.ModuleType | None = ..., - name: str | None = ..., - globs: dict[str, Any] | None = ..., - verbose: bool | None = ..., - report: bool = ..., - optionflags: int = ..., - extraglobs: dict[str, Any] | None = ..., - raise_on_error: bool = ..., - exclude_empty: bool = ..., + m: types.ModuleType | None = None, + name: str | None = None, + globs: dict[str, Any] | None = None, + verbose: bool | None = None, + report: bool = True, + optionflags: int = 0, + extraglobs: dict[str, Any] | None = None, + raise_on_error: bool = False, + exclude_empty: bool = False, ) -> TestResults: ... def testfile( filename: str, - module_relative: bool = ..., - name: str | None = ..., - package: None | str | types.ModuleType = ..., - globs: dict[str, Any] | None = ..., - verbose: bool | None = ..., - report: bool = ..., - optionflags: int = ..., - extraglobs: dict[str, Any] | None = ..., - raise_on_error: bool = ..., + module_relative: bool = True, + name: str | None = None, + package: str | types.ModuleType | None = None, + globs: dict[str, Any] | None = None, + verbose: bool | None = None, + report: bool = True, + optionflags: int = 0, + extraglobs: dict[str, Any] | None = None, + raise_on_error: bool = False, parser: DocTestParser = ..., - encoding: str | None = ..., + encoding: str | None = None, ) -> TestResults: ... def run_docstring_examples( - f: object, globs: dict[str, Any], verbose: bool = ..., name: str = ..., compileflags: int | None = ..., optionflags: int = ... + f: object, + globs: dict[str, Any], + verbose: bool = False, + name: str = "NoName", + compileflags: int | None = None, + optionflags: int = 0, ) -> None: ... def set_unittest_reportflags(flags: int) -> int: ... @@ -160,52 +222,44 @@ class DocTestCase(unittest.TestCase): def __init__( self, test: DocTest, - optionflags: int = ..., - setUp: Callable[[DocTest], Any] | None = ..., - tearDown: Callable[[DocTest], Any] | None = ..., - checker: OutputChecker | None = ..., + optionflags: int = 0, + setUp: Callable[[DocTest], object] | None = None, + tearDown: Callable[[DocTest], object] | None = None, + checker: OutputChecker | None = None, ) -> None: ... - def setUp(self) -> None: ... - def tearDown(self) -> None: ... def runTest(self) -> None: ... def format_failure(self, err: str) -> str: ... - def debug(self) -> None: ... - def id(self) -> str: ... def __hash__(self) -> int: ... - def shortDescription(self) -> str: ... + def __eq__(self, other: object) -> bool: ... class SkipDocTestCase(DocTestCase): def __init__(self, module: types.ModuleType) -> None: ... - def setUp(self) -> None: ... def test_skip(self) -> None: ... - def shortDescription(self) -> str: ... class _DocTestSuite(unittest.TestSuite): ... def DocTestSuite( - module: None | str | types.ModuleType = ..., - globs: dict[str, Any] | None = ..., - extraglobs: dict[str, Any] | None = ..., - test_finder: DocTestFinder | None = ..., + module: str | types.ModuleType | None = None, + globs: dict[str, Any] | None = None, + extraglobs: dict[str, Any] | None = None, + test_finder: DocTestFinder | None = None, **options: Any, ) -> _DocTestSuite: ... -class DocFileCase(DocTestCase): - def id(self) -> str: ... - def format_failure(self, err: str) -> str: ... +class DocFileCase(DocTestCase): ... def DocFileTest( path: str, - module_relative: bool = ..., - package: None | str | types.ModuleType = ..., - globs: dict[str, Any] | None = ..., + module_relative: bool = True, + package: str | types.ModuleType | None = None, + globs: dict[str, Any] | None = None, parser: DocTestParser = ..., - encoding: str | None = ..., + encoding: str | None = None, **options: Any, ) -> DocFileCase: ... def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... def script_from_examples(s: str) -> str: ... -def testsource(module: None | str | types.ModuleType, name: str) -> str: ... -def debug_src(src: str, pm: bool = ..., globs: dict[str, Any] | None = ...) -> None: ... -def debug_script(src: str, pm: bool = ..., globs: dict[str, Any] | None = ...) -> None: ... -def debug(module: None | str | types.ModuleType, name: str, pm: bool = ...) -> None: ... +def testsource(module: str | types.ModuleType | None, name: str) -> str: ... +def debug_src(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ... +def debug_script(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ... +def debug(module: str | types.ModuleType | None, name: str, pm: bool = False) -> None: ... diff --git a/stdlib/dummy_threading.pyi b/stdlib/dummy_threading.pyi deleted file mode 100644 index 757cb8d4bd4c..000000000000 --- a/stdlib/dummy_threading.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from _dummy_threading import * -from _dummy_threading import __all__ as __all__ diff --git a/stdlib/email/__init__.pyi b/stdlib/email/__init__.pyi index e2c22554a092..f2a0a92703e3 100644 --- a/stdlib/email/__init__.pyi +++ b/stdlib/email/__init__.pyi @@ -1,23 +1,68 @@ +from _typeshed import SupportsRead +from collections.abc import Callable +from email._policybase import _MessageT from email.message import Message from email.policy import Policy -from typing import IO, Callable +from io import _WrappedBuffer +from typing import TypeAlias, overload -def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... -def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... -def message_from_file(fp: IO[str], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... -def message_from_binary_file(fp: IO[bytes], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +# At runtime, listing submodules in __all__ without them being imported is +# valid, and causes them to be included in a star import. See #6523 -# Names in __all__ with no definition: -# base64mime -# charset -# encoders -# errors -# feedparser -# generator -# header -# iterators -# message -# mime -# parser -# quoprimime -# utils +__all__ = [ # ruff: ignore[undefined-export] # Undefined names in __all__ + "base64mime", # pyright: ignore[reportUnsupportedDunderAll] + "charset", # pyright: ignore[reportUnsupportedDunderAll] + "encoders", # pyright: ignore[reportUnsupportedDunderAll] + "errors", # pyright: ignore[reportUnsupportedDunderAll] + "feedparser", # pyright: ignore[reportUnsupportedDunderAll] + "generator", # pyright: ignore[reportUnsupportedDunderAll] + "header", # pyright: ignore[reportUnsupportedDunderAll] + "iterators", # pyright: ignore[reportUnsupportedDunderAll] + "message", # pyright: ignore[reportUnsupportedDunderAll] + "message_from_file", + "message_from_binary_file", + "message_from_string", + "message_from_bytes", + "mime", # pyright: ignore[reportUnsupportedDunderAll] + "parser", # pyright: ignore[reportUnsupportedDunderAll] + "quoprimime", # pyright: ignore[reportUnsupportedDunderAll] + "utils", # pyright: ignore[reportUnsupportedDunderAll] +] + +# Definitions imported by multiple submodules in typeshed +_ParamType: TypeAlias = str | tuple[str | None, str | None, str] # noqa: Y047 +_ParamsType: TypeAlias = str | tuple[str, str | None, str] | None # noqa: Y047 + +@overload +def message_from_string(s: str) -> Message[str, str]: ... +@overload +def message_from_string(s: str, _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_string(s: str, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... + +@overload +def message_from_bytes(s: bytes | bytearray) -> Message[str, str]: ... +@overload +def message_from_bytes(s: bytes | bytearray, _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_bytes( + s: bytes | bytearray, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT] +) -> _MessageT: ... + +@overload +def message_from_file(fp: SupportsRead[str]) -> Message[str, str]: ... +@overload +def message_from_file(fp: SupportsRead[str], _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_file( + fp: SupportsRead[str], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT] +) -> _MessageT: ... + +@overload +def message_from_binary_file(fp: _WrappedBuffer) -> Message[str, str]: ... +@overload +def message_from_binary_file(fp: _WrappedBuffer, _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_binary_file( + fp: _WrappedBuffer, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT] +) -> _MessageT: ... diff --git a/stdlib/email/_header_value_parser.pyi b/stdlib/email/_header_value_parser.pyi index a14f5a2d2238..019503cf8538 100644 --- a/stdlib/email/_header_value_parser.pyi +++ b/stdlib/email/_header_value_parser.pyi @@ -1,10 +1,11 @@ import sys +from _typeshed import Incomplete +from collections.abc import Iterable, Iterator from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, List, Pattern, Type, TypeVar, Union -from typing_extensions import Final - -_T = TypeVar("_T") +from re import Pattern +from typing import Final +from typing_extensions import Self WSP: Final[set[str]] CFWS_LEADER: Final[set[str]] @@ -17,18 +18,26 @@ TOKEN_ENDS: Final[set[str]] ASPECIALS: Final[set[str]] ATTRIBUTE_ENDS: Final[set[str]] EXTENDED_ATTRIBUTE_ENDS: Final[set[str]] +# Added in Python 3.10.15, 3.11.10, 3.12.5 +NLSET: Final[set[str]] +# Added in Python 3.10.15, 3.11.10, 3.12.5 +SPECIALSNL: Final[set[str]] + +# Added in Python 3.10.17, 3.11.12, 3.12.9, 3.13.2 +def make_quoted_pairs(value) -> str: ... +def quote_string(value) -> str: ... -def quote_string(value: Any) -> str: ... +# Added in Python 3.10.20, 3.11.15, 3.12.13, 3.13.12, 3.14.3 +def make_parenthesis_pairs(value) -> str: ... -if sys.version_info >= (3, 7): - rfc2047_matcher: Pattern[str] +rfc2047_matcher: Final[Pattern[str]] -class TokenList(List[Union[TokenList, Terminal]]): +class TokenList(list[TokenList | Terminal]): token_type: str | None syntactic_break: bool ew_combine_allowed: bool defects: list[MessageDefect] - def __init__(self, *args: Any, **kw: Any) -> None: ... + def __init__(self, *args, **kw) -> None: ... @property def value(self) -> str: ... @property @@ -39,14 +48,10 @@ class TokenList(List[Union[TokenList, Terminal]]): @property def comments(self) -> list[str]: ... def fold(self, *, policy: Policy) -> str: ... - def pprint(self, indent: str = ...) -> None: ... - def ppstr(self, indent: str = ...) -> str: ... + def pprint(self, indent: str = "") -> None: ... + def ppstr(self, indent: str = "") -> str: ... -class WhiteSpaceTokenList(TokenList): - @property - def value(self) -> str: ... - @property - def comments(self) -> list[str]: ... +class WhiteSpaceTokenList(TokenList): ... class UnstructuredTokenList(TokenList): token_type: str @@ -84,16 +89,12 @@ class QuotedString(TokenList): class BareQuotedString(QuotedString): token_type: str - @property - def value(self) -> str: ... class Comment(WhiteSpaceTokenList): token_type: str - def quote(self, value: Any) -> str: ... + def quote(self, value) -> str: ... @property def content(self) -> str: ... - @property - def comments(self) -> list[str]: ... class AddressList(TokenList): token_type: str @@ -182,10 +183,14 @@ class InvalidMailbox(TokenList): token_type: str @property def display_name(self) -> None: ... - local_part: None - domain: None - route: None - addr_spec: None + @property + def local_part(self) -> None: ... + @property + def domain(self) -> None: ... + @property + def route(self) -> None: ... + @property + def addr_spec(self) -> None: ... class Domain(TokenList): token_type: str @@ -200,10 +205,9 @@ class DotAtomText(TokenList): token_type: str as_ew_allowed: bool -if sys.version_info >= (3, 8): - class NoFoldLiteral(TokenList): - token_type: str - as_ew_allowed: bool +class NoFoldLiteral(TokenList): + token_type: str + as_ew_allowed: bool class AddrSpec(TokenList): token_type: str @@ -213,8 +217,6 @@ class AddrSpec(TokenList): @property def domain(self) -> str: ... @property - def value(self) -> str: ... - @property def addr_spec(self) -> str: ... class ObsLocalPart(TokenList): @@ -223,18 +225,13 @@ class ObsLocalPart(TokenList): class DisplayName(Phrase): token_type: str - ew_combine_allowed: bool @property def display_name(self) -> str: ... - @property - def value(self) -> str: ... class LocalPart(TokenList): token_type: str as_ew_allowed: bool @property - def value(self) -> str: ... - @property def local_part(self) -> str: ... class DomainLiteral(TokenList): @@ -297,7 +294,7 @@ class ContentType(ParameterizedHeaderValue): class ContentDisposition(ParameterizedHeaderValue): token_type: str as_ew_allowed: bool - content_disposition: Any + content_disposition: Incomplete class ContentTransferEncoding(TokenList): token_type: str @@ -308,15 +305,23 @@ class HeaderLabel(TokenList): token_type: str as_ew_allowed: bool -if sys.version_info >= (3, 8): - class MsgID(TokenList): - token_type: str - as_ew_allowed: bool - def fold(self, policy: Policy) -> str: ... - class MessageID(MsgID): - token_type: str - class InvalidMessageID(MessageID): +class MsgID(TokenList): + token_type: str + as_ew_allowed: bool + def fold(self, policy: Policy) -> str: ... + +class MessageID(MsgID): + token_type: str + +class InvalidMessageID(MessageID): + token_type: str + +if sys.version_info >= (3, 13): + # Added in Python 3.13.12, 3.14.3 + class MessageIDList(TokenList): token_type: str + @property + def message_ids(self) -> list[MsgID | Terminal]: ... class Header(TokenList): token_type: str @@ -327,7 +332,7 @@ class Terminal(str): syntactic_break: bool token_type: str defects: list[MessageDefect] - def __new__(cls: Type[_T], value: str, token_type: str) -> _T: ... + def __new__(cls, value: str, token_type: str) -> Self: ... def pprint(self) -> None: ... @property def all_defects(self) -> list[MessageDefect]: ... @@ -346,10 +351,7 @@ class ValueTerminal(Terminal): def value(self) -> ValueTerminal: ... def startswith_fws(self) -> bool: ... -class EWWhiteSpaceTerminal(WhiteSpaceTerminal): - @property - def value(self) -> str: ... - +class EWWhiteSpaceTerminal(WhiteSpaceTerminal): ... class _InvalidEwError(HeaderParseError): ... DOT: Final[ValueTerminal] @@ -357,7 +359,7 @@ ListSeparator: Final[ValueTerminal] RouteComponentMarker: Final[ValueTerminal] def get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]: ... -def get_encoded_word(value: str) -> tuple[EncodedWord, str]: ... +def get_encoded_word(value: str, terminal_type: str = "vtext") -> tuple[EncodedWord, str]: ... def get_unstructured(value: str) -> UnstructuredTokenList: ... def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]: ... def get_qcontent(value: str) -> tuple[ValueTerminal, str]: ... @@ -369,7 +371,7 @@ def get_quoted_string(value: str) -> tuple[QuotedString, str]: ... def get_atom(value: str) -> tuple[Atom, str]: ... def get_dot_atom_text(value: str) -> tuple[DotAtomText, str]: ... def get_dot_atom(value: str) -> tuple[DotAtom, str]: ... -def get_word(value: str) -> tuple[Any, str]: ... +def get_word(value: str) -> tuple[Incomplete, str]: ... def get_phrase(value: str) -> tuple[Phrase, str]: ... def get_local_part(value: str) -> tuple[LocalPart, str]: ... def get_obs_local_part(value: str) -> tuple[ObsLocalPart, str]: ... @@ -388,11 +390,13 @@ def get_group_list(value: str) -> tuple[GroupList, str]: ... def get_group(value: str) -> tuple[Group, str]: ... def get_address(value: str) -> tuple[Address, str]: ... def get_address_list(value: str) -> tuple[AddressList, str]: ... +def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: ... +def get_msg_id(value: str) -> tuple[MsgID, str]: ... +def parse_message_id(value: str) -> MessageID: ... -if sys.version_info >= (3, 8): - def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: ... - def get_msg_id(value: str) -> tuple[MsgID, str]: ... - def parse_message_id(value: str) -> MessageID: ... +if sys.version_info >= (3, 13): + # Added in Python 3.13.12, 3.14.3 + def parse_message_ids(value: str) -> MessageIDList: ... def parse_mime_version(value: str) -> MIMEVersion: ... def get_invalid_parameter(value: str) -> tuple[InvalidParameter, str]: ... diff --git a/stdlib/email/_policybase.pyi b/stdlib/email/_policybase.pyi new file mode 100644 index 000000000000..0fb890d424b1 --- /dev/null +++ b/stdlib/email/_policybase.pyi @@ -0,0 +1,80 @@ +from abc import ABCMeta, abstractmethod +from email.errors import MessageDefect +from email.header import Header +from email.message import Message +from typing import Any, Generic, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +__all__ = ["Policy", "Compat32", "compat32"] + +_MessageT = TypeVar("_MessageT", bound=Message[Any, Any], default=Message[str, str]) +_MessageT_co = TypeVar("_MessageT_co", covariant=True, bound=Message[Any, Any], default=Message[str, str]) + +@type_check_only +class _MessageFactory(Protocol[_MessageT]): + def __call__(self, policy: Policy[_MessageT]) -> _MessageT: ... + +# Policy below is the only known direct subclass of _PolicyBase. We therefore +# assume that the __init__ arguments and attributes of _PolicyBase are +# the same as those of Policy. +class _PolicyBase(Generic[_MessageT_co]): + max_line_length: int | None + linesep: str + cte_type: str + raise_on_defect: bool + mangle_from_: bool + message_factory: _MessageFactory[_MessageT_co] | None + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool + + def __init__( + self, + *, + max_line_length: int | None = 78, + linesep: str = "\n", + cte_type: str = "8bit", + raise_on_defect: bool = False, + mangle_from_: bool = ..., # default depends on sub-class + message_factory: _MessageFactory[_MessageT_co] | None = None, + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = True, + ) -> None: ... + def clone( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: _MessageFactory[_MessageT_co] | None = ..., + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = ..., + ) -> Self: ... + def __add__(self, other: Policy) -> Self: ... + +class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): + # Every Message object has a `defects` attribute, so the following + # methods will work for any Message object. + def handle_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: ... + def register_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: ... + def header_max_count(self, name: str) -> int | None: ... + @abstractmethod + def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... + @abstractmethod + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... + @abstractmethod + def header_fetch_parse(self, name: str, value: str) -> str: ... + @abstractmethod + def fold(self, name: str, value: str) -> str: ... + @abstractmethod + def fold_binary(self, name: str, value: str) -> bytes: ... + +class Compat32(Policy[_MessageT_co]): + def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... + def header_fetch_parse(self, name: str, value: str) -> str | Header: ... # type: ignore[override] + def fold(self, name: str, value: str) -> str: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + +compat32: Compat32[Message[str, str]] diff --git a/stdlib/email/base64mime.pyi b/stdlib/email/base64mime.pyi index a8030a978923..563cd7f669a2 100644 --- a/stdlib/email/base64mime.pyi +++ b/stdlib/email/base64mime.pyi @@ -1,7 +1,13 @@ -def header_length(bytearray: str | bytes) -> int: ... -def header_encode(header_bytes: str | bytes, charset: str = ...) -> str: ... -def body_encode(s: bytes, maxlinelen: int = ..., eol: str = ...) -> str: ... -def decode(string: str | bytes) -> bytes: ... +__all__ = ["body_decode", "body_encode", "decode", "decodestring", "header_encode", "header_length"] + +from _typeshed import ReadableBuffer + +def header_length(bytearray: str | bytes | bytearray) -> int: ... +def header_encode(header_bytes: str | ReadableBuffer, charset: str = "iso-8859-1") -> str: ... + +# First argument should be a buffer that supports slicing and len(). +def body_encode(s: bytes | bytearray, maxlinelen: int = 76, eol: str = "\n") -> str: ... +def decode(string: str | ReadableBuffer) -> bytes: ... body_decode = decode decodestring = decode diff --git a/stdlib/email/charset.pyi b/stdlib/email/charset.pyi index 4bf5d11690eb..353cdeb0b9dd 100644 --- a/stdlib/email/charset.pyi +++ b/stdlib/email/charset.pyi @@ -1,8 +1,19 @@ -from typing import Any, Iterator +from collections.abc import Callable, Iterator +from email.message import Message +from typing import ClassVar, Final, overload -QP: int # undocumented -BASE64: int # undocumented -SHORTEST: int # undocumented +__all__ = ["Charset", "add_alias", "add_charset", "add_codec"] + +QP: Final = 1 # undocumented +BASE64: Final = 2 # undocumented +SHORTEST: Final = 3 # undocumented +RFC2047_CHROME_LEN: Final = 7 # undocumented +DEFAULT_CHARSET: Final = "us-ascii" # undocumented +UNKNOWN8BIT: Final = "unknown-8bit" # undocumented +EMPTYSTRING: Final = "" # undocumented +CHARSETS: Final[dict[str, tuple[int | None, int | None, str | None]]] +ALIASES: Final[dict[str, str]] +CODEC_MAP: Final[dict[str, str | None]] # undocumented class Charset: input_charset: str @@ -11,18 +22,23 @@ class Charset: output_charset: str | None input_codec: str | None output_codec: str | None - def __init__(self, input_charset: str = ...) -> None: ... - def get_body_encoding(self) -> str: ... + def __init__(self, input_charset: str = "us-ascii") -> None: ... + def get_body_encoding(self) -> str | Callable[[Message], None]: ... def get_output_charset(self) -> str | None: ... def header_encode(self, string: str) -> str: ... - def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str]: ... - def body_encode(self, string: str) -> str: ... - def __str__(self) -> str: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str | None]: ... + + @overload + def body_encode(self, string: None) -> None: ... + @overload + def body_encode(self, string: str | bytes) -> str: ... + + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def add_charset( - charset: str, header_enc: int | None = ..., body_enc: int | None = ..., output_charset: str | None = ... + charset: str, header_enc: int | None = None, body_enc: int | None = None, output_charset: str | None = None ) -> None: ... def add_alias(alias: str, canonical: str) -> None: ... def add_codec(charset: str, codecname: str) -> None: ... diff --git a/stdlib/email/contentmanager.pyi b/stdlib/email/contentmanager.pyi index 68fe99c8c09f..343667213a3e 100644 --- a/stdlib/email/contentmanager.pyi +++ b/stdlib/email/contentmanager.pyi @@ -1,11 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Callable from email.message import Message -from typing import Any, Callable class ContentManager: - def __init__(self) -> None: ... - def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ... - def set_content(self, msg: Message, obj: Any, *args: Any, **kw: Any) -> Any: ... - def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ... - def add_set_handler(self, typekey: type, handler: Callable[..., Any]) -> None: ... + def get_content(self, msg: Message, *args, **kw): ... + def set_content(self, msg: Message, obj, *args, **kw): ... + def add_get_handler(self, key: str, handler: Callable[..., Incomplete]) -> None: ... + def add_set_handler(self, typekey: type, handler: Callable[..., Incomplete]) -> None: ... raw_data_manager: ContentManager diff --git a/stdlib/email/encoders.pyi b/stdlib/email/encoders.pyi index e05225e895c4..55223bdc0762 100644 --- a/stdlib/email/encoders.pyi +++ b/stdlib/email/encoders.pyi @@ -1,5 +1,7 @@ from email.message import Message +__all__ = ["encode_7or8bit", "encode_base64", "encode_noop", "encode_quopri"] + def encode_base64(msg: Message) -> None: ... def encode_quopri(msg: Message) -> None: ... def encode_7or8bit(msg: Message) -> None: ... diff --git a/stdlib/email/errors.pyi b/stdlib/email/errors.pyi index 656cbd374ac4..4da60250965e 100644 --- a/stdlib/email/errors.pyi +++ b/stdlib/email/errors.pyi @@ -1,5 +1,3 @@ -import sys - class MessageError(Exception): ... class MessageParseError(MessageError): ... class HeaderParseError(MessageParseError): ... @@ -7,8 +5,11 @@ class BoundaryError(MessageParseError): ... class MultipartConversionError(MessageError, TypeError): ... class CharsetError(MessageError): ... +# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +class HeaderWriteError(MessageError): ... + class MessageDefect(ValueError): - def __init__(self, line: str | None = ...) -> None: ... + def __init__(self, line: str | None = None) -> None: ... class NoBoundaryInMultipartDefect(MessageDefect): ... class StartBoundaryNotFoundDefect(MessageDefect): ... @@ -34,6 +35,4 @@ class NonPrintableDefect(HeaderDefect): class ObsoleteHeaderDefect(HeaderDefect): ... class NonASCIILocalPartDefect(HeaderDefect): ... - -if sys.version_info >= (3, 10): - class InvalidDateDefect(HeaderDefect): ... +class InvalidDateDefect(HeaderDefect): ... diff --git a/stdlib/email/feedparser.pyi b/stdlib/email/feedparser.pyi index ffcf4f0a7c6e..ec92eef67886 100644 --- a/stdlib/email/feedparser.pyi +++ b/stdlib/email/feedparser.pyi @@ -1,21 +1,24 @@ +from collections.abc import Callable +from email._policybase import _MessageT from email.message import Message from email.policy import Policy -from typing import Callable, Generic, TypeVar, overload +from typing import Generic, overload -_M = TypeVar("_M", bound=Message) +__all__ = ["FeedParser", "BytesFeedParser"] -class FeedParser(Generic[_M]): +class FeedParser(Generic[_MessageT]): @overload - def __init__(self: FeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... + def __init__(self: FeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ... @overload - def __init__(self, _factory: Callable[[], _M], *, policy: Policy = ...) -> None: ... + def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + def feed(self, data: str) -> None: ... - def close(self) -> _M: ... + def close(self) -> _MessageT: ... -class BytesFeedParser(Generic[_M]): +class BytesFeedParser(FeedParser[_MessageT]): @overload - def __init__(self: BytesFeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... + def __init__(self: BytesFeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ... @overload - def __init__(self, _factory: Callable[[], _M], *, policy: Policy = ...) -> None: ... - def feed(self, data: bytes) -> None: ... - def close(self) -> _M: ... + def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + + def feed(self, data: bytes | bytearray) -> None: ... # type: ignore[override] diff --git a/stdlib/email/generator.pyi b/stdlib/email/generator.pyi index 1a810558a0da..c2a9bb0921d7 100644 --- a/stdlib/email/generator.pyi +++ b/stdlib/email/generator.pyi @@ -1,30 +1,79 @@ +from _typeshed import SupportsWrite from email.message import Message from email.policy import Policy -from typing import BinaryIO, TextIO +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self -class Generator: - def clone(self, fp: TextIO) -> Generator: ... - def write(self, s: str) -> None: ... +__all__ = ["Generator", "DecodedGenerator", "BytesGenerator"] + +# By default, generators do not have a message policy. +_MessageT = TypeVar("_MessageT", bound=Message[Any, Any], default=Any) + +class Generator(Generic[_MessageT]): + maxheaderlen: int | None + policy: Policy[_MessageT] | None + + @overload def __init__( - self, outfp: TextIO, mangle_from_: bool | None = ..., maxheaderlen: int | None = ..., *, policy: Policy | None = ... + self: Generator[Any], # The Policy of the message is used. + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: None = None, + ) -> None: ... + @overload + def __init__( + self, + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: Policy[_MessageT], ) -> None: ... - def flatten(self, msg: Message, unixfrom: bool = ..., linesep: str | None = ...) -> None: ... -class BytesGenerator: - def clone(self, fp: BinaryIO) -> BytesGenerator: ... def write(self, s: str) -> None: ... + def flatten(self, msg: _MessageT, unixfrom: bool = False, linesep: str | None = None) -> None: ... + def clone(self, fp: SupportsWrite[str]) -> Self: ... + +class BytesGenerator(Generator[_MessageT]): + @overload def __init__( - self, outfp: BinaryIO, mangle_from_: bool | None = ..., maxheaderlen: int | None = ..., *, policy: Policy | None = ... + self: BytesGenerator[Any], # The Policy of the message is used. + outfp: SupportsWrite[bytes], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: None = None, + ) -> None: ... + @overload + def __init__( + self, + outfp: SupportsWrite[bytes], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: Policy[_MessageT], ) -> None: ... - def flatten(self, msg: Message, unixfrom: bool = ..., linesep: str | None = ...) -> None: ... -class DecodedGenerator(Generator): +class DecodedGenerator(Generator[_MessageT]): + @overload + def __init__( + self: DecodedGenerator[Any], # The Policy of the message is used. + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + fmt: str | None = None, + *, + policy: None = None, + ) -> None: ... + @overload def __init__( self, - outfp: TextIO, - mangle_from_: bool | None = ..., - maxheaderlen: int | None = ..., - fmt: str | None = ..., + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + fmt: str | None = None, *, - policy: Policy | None = ..., + policy: Policy[_MessageT], ) -> None: ... diff --git a/stdlib/email/header.pyi b/stdlib/email/header.pyi index 4bebd50c45e4..a26bbb516e09 100644 --- a/stdlib/email/header.pyi +++ b/stdlib/email/header.pyi @@ -1,26 +1,32 @@ +from collections.abc import Iterable from email.charset import Charset -from typing import Any +from typing import Any, ClassVar + +__all__ = ["Header", "decode_header", "make_header"] class Header: def __init__( self, - s: bytes | str | None = ..., - charset: Charset | str | None = ..., - maxlinelen: int | None = ..., - header_name: str | None = ..., - continuation_ws: str = ..., - errors: str = ..., + s: bytes | bytearray | str | None = None, + charset: Charset | str | None = None, + maxlinelen: int | None = None, + header_name: str | None = None, + continuation_ws: str = " ", + errors: str = "strict", ) -> None: ... - def append(self, s: bytes | str, charset: Charset | str | None = ..., errors: str = ...) -> None: ... - def encode(self, splitchars: str = ..., maxlinelen: int | None = ..., linesep: str = ...) -> str: ... - def __str__(self) -> str: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def append(self, s: bytes | bytearray | str, charset: Charset | str | None = None, errors: str = "strict") -> None: ... + def encode(self, splitchars: str = ";, \t", maxlinelen: int | None = None, linesep: str = "\n") -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... -def decode_header(header: Header | str) -> list[tuple[bytes, str | None]]: ... +# decode_header() either returns list[tuple[str, None]] if the header +# contains no encoded parts, or list[tuple[bytes, str | None]] if the header +# contains at least one encoded part. +def decode_header(header: Header | str) -> list[tuple[Any, Any | None]]: ... def make_header( - decoded_seq: list[tuple[bytes, str | None]], - maxlinelen: int | None = ..., - header_name: str | None = ..., - continuation_ws: str = ..., + decoded_seq: Iterable[tuple[bytes | bytearray | str, str | None]], + maxlinelen: int | None = None, + header_name: str | None = None, + continuation_ws: str = " ", ) -> Header: ... diff --git a/stdlib/email/headerregistry.pyi b/stdlib/email/headerregistry.pyi index 6a3d6ca5b2a7..3eaacda0ac77 100644 --- a/stdlib/email/headerregistry.pyi +++ b/stdlib/email/headerregistry.pyi @@ -1,5 +1,6 @@ import sys import types +from _typeshed import Incomplete from collections.abc import Iterable, Mapping from datetime import datetime as _datetime from email._header_value_parser import ( @@ -7,14 +8,15 @@ from email._header_value_parser import ( ContentDisposition, ContentTransferEncoding, ContentType, + MessageID, MIMEVersion, TokenList, UnstructuredTokenList, ) from email.errors import MessageDefect from email.policy import Policy -from typing import Any, ClassVar, Tuple, Type -from typing_extensions import Literal +from typing import ClassVar, Literal, Protocol, type_check_only +from typing_extensions import Self class BaseHeader(str): # max_count is actually more of an abstract ClassVar (not defined on the base class, but expected to be defined in subclasses) @@ -22,8 +24,8 @@ class BaseHeader(str): @property def name(self) -> str: ... @property - def defects(self) -> Tuple[MessageDefect, ...]: ... - def __new__(cls, name: str, value: Any) -> BaseHeader: ... + def defects(self) -> tuple[MessageDefect, ...]: ... + def __new__(cls, name: str, value) -> Self: ... def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... def fold(self, *, policy: Policy) -> str: ... @@ -32,7 +34,7 @@ class UnstructuredHeader: @staticmethod def value_parser(value: str) -> UnstructuredTokenList: ... @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... class UniqueUnstructuredHeader(UnstructuredHeader): max_count: ClassVar[Literal[1]] @@ -41,11 +43,11 @@ class DateHeader: max_count: ClassVar[Literal[1] | None] def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], datetime: _datetime) -> None: ... @property - def datetime(self) -> _datetime: ... + def datetime(self) -> _datetime | None: ... @staticmethod def value_parser(value: str) -> UnstructuredTokenList: ... @classmethod - def parse(cls, value: str | _datetime, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str | _datetime, kwds: dict[str, Incomplete]) -> None: ... class UniqueDateHeader(DateHeader): max_count: ClassVar[Literal[1]] @@ -54,13 +56,13 @@ class AddressHeader: max_count: ClassVar[Literal[1] | None] def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], groups: Iterable[Group]) -> None: ... @property - def groups(self) -> Tuple[Group, ...]: ... + def groups(self) -> tuple[Group, ...]: ... @property - def addresses(self) -> Tuple[Address, ...]: ... + def addresses(self) -> tuple[Address, ...]: ... @staticmethod def value_parser(value: str) -> AddressList: ... @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... class UniqueAddressHeader(AddressHeader): max_count: ClassVar[Literal[1]] @@ -93,15 +95,17 @@ class MIMEVersionHeader: @staticmethod def value_parser(value: str) -> MIMEVersion: ... @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... class ParameterizedMIMEHeader: max_count: ClassVar[Literal[1]] - def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], params: Mapping[str, Any]) -> None: ... + def init( + self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], params: Mapping[str, Incomplete] + ) -> None: ... @property - def params(self) -> types.MappingProxyType[str, Any]: ... + def params(self) -> types.MappingProxyType[str, Incomplete]: ... @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... class ContentTypeHeader(ParameterizedMIMEHeader): @property @@ -126,26 +130,46 @@ class ContentTransferEncodingHeader: @property def cte(self) -> str: ... @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... @staticmethod def value_parser(value: str) -> ContentTransferEncoding: ... -if sys.version_info >= (3, 8): - from email._header_value_parser import MessageID - class MessageIDHeader: +class MessageIDHeader: + max_count: ClassVar[Literal[1]] + @classmethod + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... + @staticmethod + def value_parser(value: str) -> MessageID: ... + +if sys.version_info >= (3, 13): + from email._header_value_parser import MessageIDList + + # Added in Python 3.13.12, 3.14.3 + class ReferencesHeader: max_count: ClassVar[Literal[1]] @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: dict[str, Incomplete]) -> None: ... @staticmethod - def value_parser(value: str) -> MessageID: ... + def value_parser(value: str) -> MessageIDList: ... + +@type_check_only +class _HeaderParser(Protocol): + max_count: ClassVar[Literal[1] | None] + @staticmethod + def value_parser(value: str, /) -> TokenList: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Incomplete], /) -> None: ... class HeaderRegistry: + registry: dict[str, type[_HeaderParser]] + base_class: type[BaseHeader] + default_class: type[_HeaderParser] def __init__( - self, base_class: Type[BaseHeader] = ..., default_class: Type[BaseHeader] = ..., use_default_map: bool = ... + self, base_class: type[BaseHeader] = ..., default_class: type[_HeaderParser] = ..., use_default_map: bool = True ) -> None: ... - def map_to_type(self, name: str, cls: Type[BaseHeader]) -> None: ... - def __getitem__(self, name: str) -> Type[BaseHeader]: ... - def __call__(self, name: str, value: Any) -> BaseHeader: ... + def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: ... + def __getitem__(self, name: str) -> type[BaseHeader]: ... + def __call__(self, name: str, value) -> BaseHeader: ... class Address: @property @@ -157,14 +181,16 @@ class Address: @property def addr_spec(self) -> str: ... def __init__( - self, display_name: str = ..., username: str | None = ..., domain: str | None = ..., addr_spec: str | None = ... + self, display_name: str = "", username: str | None = "", domain: str | None = "", addr_spec: str | None = None ) -> None: ... - def __str__(self) -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... class Group: @property def display_name(self) -> str | None: ... @property - def addresses(self) -> Tuple[Address, ...]: ... - def __init__(self, display_name: str | None = ..., addresses: Iterable[Address] | None = ...) -> None: ... - def __str__(self) -> str: ... + def addresses(self) -> tuple[Address, ...]: ... + def __init__(self, display_name: str | None = None, addresses: Iterable[Address] | None = None) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... diff --git a/stdlib/email/iterators.pyi b/stdlib/email/iterators.pyi index 9081a3e3ba73..b9a8de835401 100644 --- a/stdlib/email/iterators.pyi +++ b/stdlib/email/iterators.pyi @@ -1,5 +1,15 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterator from email.message import Message -from typing import Iterator +from typing import TypeVar -def body_line_iterator(msg: Message, decode: bool = ...) -> Iterator[str]: ... -def typed_subpart_iterator(msg: Message, maintype: str = ..., subtype: str | None = ...) -> Iterator[str]: ... +_T = TypeVar("_T", bound=Message) + +__all__ = ["body_line_iterator", "typed_subpart_iterator", "walk"] + +def body_line_iterator(msg: Message, decode: bool = False) -> Iterator[str]: ... +def typed_subpart_iterator(msg: _T, maintype: str = "text", subtype: str | None = None) -> Iterator[_T]: ... +def walk(self: Message) -> Iterator[Message]: ... + +# We include the seemingly private function because it is documented in the stdlib documentation. +def _structure(msg: Message, fp: SupportsWrite[str] | None = None, level: int = 0, include_default: bool = False) -> None: ... diff --git a/stdlib/email/message.pyi b/stdlib/email/message.pyi index a1749a4cfc2e..e17b98474948 100644 --- a/stdlib/email/message.pyi +++ b/stdlib/email/message.pyi @@ -1,91 +1,191 @@ +from _typeshed import MaybeNone +from collections.abc import Generator, Iterator, Sequence +from email import _ParamsType, _ParamType from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union +from typing import Any, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +__all__ = ["Message", "EmailMessage"] _T = TypeVar("_T") +# Type returned by Policy.header_fetch_parse, often str or Header. +_HeaderT_co = TypeVar("_HeaderT_co", covariant=True, default=str) +_HeaderParamT_contra = TypeVar("_HeaderParamT_contra", contravariant=True, default=str) +# Represents headers constructed by HeaderRegistry. Those are sub-classes +# of BaseHeader and another header type. +_HeaderRegistryT_co = TypeVar("_HeaderRegistryT_co", covariant=True, default=Any) +_HeaderRegistryParamT_contra = TypeVar("_HeaderRegistryParamT_contra", contravariant=True, default=Any) + +_PayloadType: TypeAlias = Message | str +_EncodedPayloadType: TypeAlias = Message | bytes +_MultipartPayloadType: TypeAlias = list[_PayloadType] +_CharsetType: TypeAlias = Charset | str | None + +@type_check_only +class _SupportsEncodeToPayload(Protocol): + def encode(self, encoding: str, /) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ... -_PayloadType = Union[List[Message], str, bytes] -_CharsetType = Union[Charset, str, None] -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] -_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] -_HeaderType = Any +@type_check_only +class _SupportsDecodeToPayload(Protocol): + def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ... -class Message: - policy: Policy # undocumented +class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): + # The policy attributes and arguments in this class and its subclasses + # would ideally use Policy[Self], but this is not possible. + policy: Policy[Any] # undocumented preamble: str | None epilogue: str | None defects: list[MessageDefect] - def __str__(self) -> str: ... + def __init__(self, policy: Policy[Any] = ...) -> None: ... def is_multipart(self) -> bool: ... def set_unixfrom(self, unixfrom: str) -> None: ... def get_unixfrom(self) -> str | None: ... - def attach(self, payload: Message) -> None: ... - def get_payload(self, i: int | None = ..., decode: bool = ...) -> Any: ... # returns _PayloadType | None - def set_payload(self, payload: _PayloadType, charset: _CharsetType = ...) -> None: ... + def attach(self, payload: _PayloadType) -> None: ... + + # `i: int` without a multipart payload results in an error + # `| MaybeNone` acts like `| Any`: can be None for cleared or unset payload, but annoying to check + @overload # multipart + def get_payload(self, i: int, decode: Literal[True]) -> None: ... + @overload # multipart + def get_payload(self, i: int, decode: Literal[False] = False) -> _PayloadType | MaybeNone: ... + @overload # either + def get_payload(self, i: None = None, decode: Literal[False] = False) -> _PayloadType | _MultipartPayloadType | MaybeNone: ... + @overload # not multipart + def get_payload(self, i: None = None, *, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... + @overload # not multipart, IDEM but w/o kwarg + def get_payload(self, i: None, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... + + # If `charset=None` and payload supports both `encode` AND `decode`, + # then an invalid payload could be passed, but this is unlikely + # Not[_SupportsEncodeToPayload] + @overload + def set_payload( + self, payload: _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, charset: None = None + ) -> None: ... + @overload + def set_payload( + self, + payload: _SupportsEncodeToPayload | _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, + charset: Charset | str, + ) -> None: ... + def set_charset(self, charset: _CharsetType) -> None: ... def get_charset(self) -> _CharsetType: ... def __len__(self) -> int: ... def __contains__(self, name: str) -> bool: ... def __iter__(self) -> Iterator[str]: ... - def __getitem__(self, name: str) -> _HeaderType: ... - def __setitem__(self, name: str, val: _HeaderType) -> None: ... + # Same as `get` with `failobj=None`, but with the expectation that it won't return None in most scenarios + # This is important for protocols using __getitem__, like SupportsKeysAndGetItem + # Morally, the return type should be `AnyOf[_HeaderType, None]`, + # so using "the Any trick" instead. + def __getitem__(self, name: str) -> _HeaderT_co | MaybeNone: ... + def __setitem__(self, name: str, val: _HeaderParamT_contra) -> None: ... def __delitem__(self, name: str) -> None: ... def keys(self) -> list[str]: ... - def values(self) -> list[_HeaderType]: ... - def items(self) -> list[tuple[str, _HeaderType]]: ... - def get(self, name: str, failobj: _T = ...) -> _HeaderType | _T: ... - def get_all(self, name: str, failobj: _T = ...) -> list[_HeaderType] | _T: ... + def values(self) -> list[_HeaderT_co]: ... + def items(self) -> list[tuple[str, _HeaderT_co]]: ... + + @overload + def get(self, name: str, failobj: None = None) -> _HeaderT_co | None: ... + @overload + def get(self, name: str, failobj: _T) -> _HeaderT_co | _T: ... + + @overload + def get_all(self, name: str, failobj: None = None) -> list[_HeaderT_co] | None: ... + @overload + def get_all(self, name: str, failobj: _T) -> list[_HeaderT_co] | _T: ... + def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ... - def replace_header(self, _name: str, _value: _HeaderType) -> None: ... + def replace_header(self, _name: str, _value: _HeaderParamT_contra) -> None: ... def get_content_type(self) -> str: ... def get_content_maintype(self) -> str: ... def get_content_subtype(self) -> str: ... def get_default_type(self) -> str: ... def set_default_type(self, ctype: str) -> None: ... - def get_params(self, failobj: _T = ..., header: str = ..., unquote: bool = ...) -> list[tuple[str, str]] | _T: ... - def get_param(self, param: str, failobj: _T = ..., header: str = ..., unquote: bool = ...) -> _T | _ParamType: ... - def del_param(self, param: str, header: str = ..., requote: bool = ...) -> None: ... - def set_type(self, type: str, header: str = ..., requote: bool = ...) -> None: ... - def get_filename(self, failobj: _T = ...) -> _T | str: ... - def get_boundary(self, failobj: _T = ...) -> _T | str: ... + + @overload + def get_params( + self, failobj: None = None, header: str = "content-type", unquote: bool = True + ) -> list[tuple[str, str]] | None: ... + @overload + def get_params(self, failobj: _T, header: str = "content-type", unquote: bool = True) -> list[tuple[str, str]] | _T: ... + + @overload + def get_param( + self, param: str, failobj: None = None, header: str = "content-type", unquote: bool = True + ) -> _ParamType | None: ... + @overload + def get_param(self, param: str, failobj: _T, header: str = "content-type", unquote: bool = True) -> _ParamType | _T: ... + + def del_param(self, param: str, header: str = "content-type", requote: bool = True) -> None: ... + def set_type(self, type: str, header: str = "Content-Type", requote: bool = True) -> None: ... + + @overload + def get_filename(self, failobj: None = None) -> str | None: ... + @overload + def get_filename(self, failobj: _T) -> str | _T: ... + + @overload + def get_boundary(self, failobj: None = None) -> str | None: ... + @overload + def get_boundary(self, failobj: _T) -> str | _T: ... + def set_boundary(self, boundary: str) -> None: ... - def get_content_charset(self, failobj: _T = ...) -> _T | str: ... - def get_charsets(self, failobj: _T = ...) -> _T | list[str]: ... - def walk(self) -> Generator[Message, None, None]: ... + + @overload + def get_content_charset(self) -> str | None: ... + @overload + def get_content_charset(self, failobj: _T) -> str | _T: ... + + @overload + def get_charsets(self, failobj: None = None) -> list[str | None]: ... + @overload + def get_charsets(self, failobj: _T) -> list[str | _T]: ... + + def walk(self) -> Generator[Self]: ... def get_content_disposition(self) -> str | None: ... - def as_string(self, unixfrom: bool = ..., maxheaderlen: int = ..., policy: Policy | None = ...) -> str: ... - def as_bytes(self, unixfrom: bool = ..., policy: Policy | None = ...) -> bytes: ... + def as_string(self, unixfrom: bool = False, maxheaderlen: int = 0, policy: Policy[Any] | None = None) -> str: ... + def as_bytes(self, unixfrom: bool = False, policy: Policy[Any] | None = None) -> bytes: ... def __bytes__(self) -> bytes: ... def set_param( self, param: str, value: str, - header: str = ..., - requote: bool = ..., - charset: str | None = ..., - language: str = ..., - replace: bool = ..., + header: str = "Content-Type", + requote: bool = True, + charset: str | None = None, + language: str = "", + replace: bool = False, ) -> None: ... - def __init__(self, policy: Policy = ...) -> None: ... - -class MIMEPart(Message): - def __init__(self, policy: Policy | None = ...) -> None: ... - def get_body(self, preferencelist: Sequence[str] = ...) -> Message | None: ... - def iter_attachments(self) -> Iterator[Message]: ... - def iter_parts(self) -> Iterator[Message]: ... - def get_content(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> Any: ... - def set_content(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... - def make_related(self, boundary: str | None = ...) -> None: ... - def make_alternative(self, boundary: str | None = ...) -> None: ... - def make_mixed(self, boundary: str | None = ...) -> None: ... - def add_related(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... - def add_alternative(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... - def add_attachment(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... + # The following two methods are undocumented, but a source code comment states that they are public API + def set_raw(self, name: str, value: _HeaderParamT_contra) -> None: ... + def raw_items(self) -> Iterator[tuple[str, _HeaderT_co]]: ... + +class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): + def __init__(self, policy: Policy[Any] | None = None) -> None: ... + def get_body( + self, preferencelist: Sequence[str] = ("related", "html", "plain") + ) -> MIMEPart[_HeaderRegistryT_co, _HeaderRegistryParamT_contra] | None: ... + def attach(self, payload: Self) -> None: ... # type: ignore[override] + # The attachments are created via type(self) in the attach method. It's theoretically + # possible to sneak other attachment types into a MIMEPart instance, but could cause + # cause unforseen consequences. + def iter_attachments(self) -> Iterator[Self]: ... + def iter_parts(self) -> Iterator[MIMEPart[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]]: ... + def get_content(self, *args, content_manager: ContentManager | None = None, **kw): ... + def set_content(self, *args, content_manager: ContentManager | None = None, **kw) -> None: ... + def make_related(self, boundary: str | None = None) -> None: ... + def make_alternative(self, boundary: str | None = None) -> None: ... + def make_mixed(self, boundary: str | None = None) -> None: ... + def add_related(self, *args, content_manager: ContentManager | None = ..., **kw) -> None: ... + def add_alternative(self, *args, content_manager: ContentManager | None = ..., **kw) -> None: ... + def add_attachment(self, *args, content_manager: ContentManager | None = ..., **kw) -> None: ... def clear(self) -> None: ... def clear_content(self) -> None: ... - def as_string(self, unixfrom: bool = ..., maxheaderlen: int | None = ..., policy: Policy | None = ...) -> str: ... + def as_string(self, unixfrom: bool = False, maxheaderlen: int | None = None, policy: Policy[Any] | None = None) -> str: ... def is_attachment(self) -> bool: ... -class EmailMessage(MIMEPart): ... +class EmailMessage(MIMEPart[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): ... diff --git a/stdlib/email/mime/application.pyi b/stdlib/email/mime/application.pyi index 11fc470e9dd1..a7ab9dc75ce2 100644 --- a/stdlib/email/mime/application.pyi +++ b/stdlib/email/mime/application.pyi @@ -1,16 +1,17 @@ +from collections.abc import Callable +from email import _ParamsType from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Tuple, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +__all__ = ["MIMEApplication"] class MIMEApplication(MIMENonMultipart): def __init__( self, - _data: str | bytes, - _subtype: str = ..., - _encoder: Callable[[MIMEApplication], None] = ..., + _data: str | bytes | bytearray, + _subtype: str = "octet-stream", + _encoder: Callable[[MIMEApplication], object] = ..., *, - policy: Policy | None = ..., + policy: Policy | None = None, **_params: _ParamsType, ) -> None: ... diff --git a/stdlib/email/mime/audio.pyi b/stdlib/email/mime/audio.pyi index ee6de410bf53..090dfb960db6 100644 --- a/stdlib/email/mime/audio.pyi +++ b/stdlib/email/mime/audio.pyi @@ -1,16 +1,17 @@ +from collections.abc import Callable +from email import _ParamsType from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Tuple, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +__all__ = ["MIMEAudio"] class MIMEAudio(MIMENonMultipart): def __init__( self, - _audiodata: str | bytes, - _subtype: str | None = ..., - _encoder: Callable[[MIMEAudio], None] = ..., + _audiodata: str | bytes | bytearray, + _subtype: str | None = None, + _encoder: Callable[[MIMEAudio], object] = ..., *, - policy: Policy | None = ..., + policy: Policy | None = None, **_params: _ParamsType, ) -> None: ... diff --git a/stdlib/email/mime/base.pyi b/stdlib/email/mime/base.pyi index b88dfd492554..b733709f1b5a 100644 --- a/stdlib/email/mime/base.pyi +++ b/stdlib/email/mime/base.pyi @@ -1,8 +1,8 @@ import email.message +from email import _ParamsType from email.policy import Policy -from typing import Optional, Tuple, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +__all__ = ["MIMEBase"] class MIMEBase(email.message.Message): - def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = ..., **_params: _ParamsType) -> None: ... + def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = None, **_params: _ParamsType) -> None: ... diff --git a/stdlib/email/mime/image.pyi b/stdlib/email/mime/image.pyi index 886aa74d5fe5..b47afa6ce592 100644 --- a/stdlib/email/mime/image.pyi +++ b/stdlib/email/mime/image.pyi @@ -1,16 +1,17 @@ +from collections.abc import Callable +from email import _ParamsType from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Tuple, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +__all__ = ["MIMEImage"] class MIMEImage(MIMENonMultipart): def __init__( self, - _imagedata: str | bytes, - _subtype: str | None = ..., - _encoder: Callable[[MIMEImage], None] = ..., + _imagedata: str | bytes | bytearray, + _subtype: str | None = None, + _encoder: Callable[[MIMEImage], object] = ..., *, - policy: Policy | None = ..., + policy: Policy | None = None, **_params: _ParamsType, ) -> None: ... diff --git a/stdlib/email/mime/message.pyi b/stdlib/email/mime/message.pyi index 8878741e8db3..a1e370e2eab5 100644 --- a/stdlib/email/mime/message.pyi +++ b/stdlib/email/mime/message.pyi @@ -1,6 +1,8 @@ -from email.message import Message +from email._policybase import _MessageT from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy +__all__ = ["MIMEMessage"] + class MIMEMessage(MIMENonMultipart): - def __init__(self, _msg: Message, _subtype: str = ..., *, policy: Policy | None = ...) -> None: ... + def __init__(self, _msg: _MessageT, _subtype: str = "rfc822", *, policy: Policy[_MessageT] | None = None) -> None: ... diff --git a/stdlib/email/mime/multipart.pyi b/stdlib/email/mime/multipart.pyi index 6259ddf5ab8f..fb9599edbcb8 100644 --- a/stdlib/email/mime/multipart.pyi +++ b/stdlib/email/mime/multipart.pyi @@ -1,17 +1,18 @@ -from email.message import Message +from collections.abc import Sequence +from email import _ParamsType +from email._policybase import _MessageT from email.mime.base import MIMEBase from email.policy import Policy -from typing import Optional, Sequence, Tuple, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +__all__ = ["MIMEMultipart"] class MIMEMultipart(MIMEBase): def __init__( self, - _subtype: str = ..., - boundary: str | None = ..., - _subparts: Sequence[Message] | None = ..., + _subtype: str = "mixed", + boundary: str | None = None, + _subparts: Sequence[_MessageT] | None = None, *, - policy: Policy | None = ..., + policy: Policy[_MessageT] | None = None, **_params: _ParamsType, ) -> None: ... diff --git a/stdlib/email/mime/nonmultipart.pyi b/stdlib/email/mime/nonmultipart.pyi index 4addff18861a..5497d89b1072 100644 --- a/stdlib/email/mime/nonmultipart.pyi +++ b/stdlib/email/mime/nonmultipart.pyi @@ -1,3 +1,5 @@ from email.mime.base import MIMEBase +__all__ = ["MIMENonMultipart"] + class MIMENonMultipart(MIMEBase): ... diff --git a/stdlib/email/mime/text.pyi b/stdlib/email/mime/text.pyi index afcafa66ee60..edfa67a09242 100644 --- a/stdlib/email/mime/text.pyi +++ b/stdlib/email/mime/text.pyi @@ -1,5 +1,9 @@ +from email._policybase import Policy from email.mime.nonmultipart import MIMENonMultipart -from email.policy import Policy + +__all__ = ["MIMEText"] class MIMEText(MIMENonMultipart): - def __init__(self, _text: str, _subtype: str = ..., _charset: str | None = ..., *, policy: Policy | None = ...) -> None: ... + def __init__( + self, _text: str, _subtype: str = "plain", _charset: str | None = None, *, policy: Policy | None = None + ) -> None: ... diff --git a/stdlib/email/parser.pyi b/stdlib/email/parser.pyi index 574c927eeaf5..f1b418ee30a0 100644 --- a/stdlib/email/parser.pyi +++ b/stdlib/email/parser.pyi @@ -1,27 +1,42 @@ -import email.feedparser +from _typeshed import SupportsRead +from collections.abc import Callable +from email._policybase import _MessageT +from email.feedparser import BytesFeedParser as BytesFeedParser, FeedParser as FeedParser from email.message import Message from email.policy import Policy -from typing import BinaryIO, Callable, TextIO - -FeedParser = email.feedparser.FeedParser -BytesFeedParser = email.feedparser.BytesFeedParser - -class Parser: - def __init__(self, _class: Callable[[], Message] | None = ..., *, policy: Policy = ...) -> None: ... - def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... - def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... - -class HeaderParser(Parser): - def __init__(self, _class: Callable[[], Message] | None = ..., *, policy: Policy = ...) -> None: ... - def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... - def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... - -class BytesHeaderParser(BytesParser): - def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... - def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... - def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... - -class BytesParser: - def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... - def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... - def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... +from io import _WrappedBuffer +from typing import Generic, overload + +__all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedParser", "BytesFeedParser"] + +class Parser(Generic[_MessageT]): + @overload + def __init__(self: Parser[Message[str, str]], _class: None = None) -> None: ... + @overload + def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ... + @overload + def __init__(self, _class: Callable[[], _MessageT] | None, *, policy: Policy[_MessageT] = ...) -> None: ... + + def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> _MessageT: ... + def parsestr(self, text: str, headersonly: bool = False) -> _MessageT: ... + +class HeaderParser(Parser[_MessageT]): + def parse(self, fp: SupportsRead[str], headersonly: bool = True) -> _MessageT: ... + def parsestr(self, text: str, headersonly: bool = True) -> _MessageT: ... + +class BytesParser(Generic[_MessageT]): + parser: Parser[_MessageT] + + @overload + def __init__(self: BytesParser[Message[str, str]], _class: None = None) -> None: ... + @overload + def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ... + @overload + def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + + def parse(self, fp: _WrappedBuffer, headersonly: bool = False) -> _MessageT: ... + def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> _MessageT: ... + +class BytesHeaderParser(BytesParser[_MessageT]): + def parse(self, fp: _WrappedBuffer, headersonly: bool = True) -> _MessageT: ... + def parsebytes(self, text: bytes | bytearray, headersonly: bool = True) -> _MessageT: ... diff --git a/stdlib/email/policy.pyi b/stdlib/email/policy.pyi index 15991c7e084b..d964801c8132 100644 --- a/stdlib/email/policy.pyi +++ b/stdlib/email/policy.pyi @@ -1,57 +1,60 @@ -from abc import ABCMeta, abstractmethod +from _typeshed import Incomplete +from collections.abc import Callable +from email._policybase import Compat32 as Compat32, Policy as Policy, _MessageFactory, _MessageT, compat32 as compat32 from email.contentmanager import ContentManager -from email.errors import MessageDefect -from email.header import Header -from email.message import Message -from typing import Any, Callable +from email.message import EmailMessage +from typing import overload +from typing_extensions import Self -class Policy(metaclass=ABCMeta): - max_line_length: int | None - linesep: str - cte_type: str - raise_on_defect: bool - mangle_from_: bool - message_factory: Callable[[Policy], Message] | None +__all__ = ["Compat32", "compat32", "Policy", "EmailPolicy", "default", "strict", "SMTP", "HTTP"] + +class EmailPolicy(Policy[_MessageT]): + utf8: bool + refold_source: str + header_factory: Callable[[str, Incomplete], Incomplete] + content_manager: ContentManager + + @overload + def __init__( + self: EmailPolicy[EmailMessage], + *, + max_line_length: int | None = 78, + linesep: str = "\n", + cte_type: str = "8bit", + raise_on_defect: bool = False, + mangle_from_: bool = ..., # default depends on sub-class + message_factory: None = None, + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = True, + utf8: bool = False, + refold_source: str = "long", + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., + ) -> None: ... + @overload def __init__( self, *, - max_line_length: int | None = ..., - linesep: str = ..., - cte_type: str = ..., - raise_on_defect: bool = ..., - mangle_from_: bool = ..., - message_factory: Callable[[Policy], Message] | None = ..., + max_line_length: int | None = 78, + linesep: str = "\n", + cte_type: str = "8bit", + raise_on_defect: bool = False, + mangle_from_: bool = ..., # default depends on sub-class + message_factory: _MessageFactory[_MessageT], + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = True, + utf8: bool = False, + refold_source: str = "long", + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., ) -> None: ... - def clone(self, **kw: Any) -> Policy: ... - def handle_defect(self, obj: Message, defect: MessageDefect) -> None: ... - def register_defect(self, obj: Message, defect: MessageDefect) -> None: ... - def header_max_count(self, name: str) -> int | None: ... - @abstractmethod - def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... - @abstractmethod - def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... - @abstractmethod - def header_fetch_parse(self, name: str, value: str) -> str: ... - @abstractmethod - def fold(self, name: str, value: str) -> str: ... - @abstractmethod - def fold_binary(self, name: str, value: str) -> bytes: ... -class Compat32(Policy): def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... - def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... - def header_fetch_parse(self, name: str, value: str) -> str | Header: ... # type: ignore[override] - def fold(self, name: str, value: str) -> str: ... + def header_store_parse(self, name: str, value) -> tuple[str, Incomplete]: ... + def header_fetch_parse(self, name: str, value: str): ... + def fold(self, name: str, value: str): ... def fold_binary(self, name: str, value: str) -> bytes: ... - -compat32: Compat32 - -class EmailPolicy(Policy): - utf8: bool - refold_source: str - header_factory: Callable[[str, str], str] - content_manager: ContentManager - def __init__( + def clone( self, *, max_line_length: int | None = ..., @@ -59,20 +62,17 @@ class EmailPolicy(Policy): cte_type: str = ..., raise_on_defect: bool = ..., mangle_from_: bool = ..., - message_factory: Callable[[Policy], Message] | None = ..., + message_factory: _MessageFactory[_MessageT] | None = ..., + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = ..., utf8: bool = ..., refold_source: str = ..., header_factory: Callable[[str, str], str] = ..., content_manager: ContentManager = ..., - ) -> None: ... - def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... - def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... - def header_fetch_parse(self, name: str, value: str) -> str: ... - def fold(self, name: str, value: str) -> str: ... - def fold_binary(self, name: str, value: str) -> bytes: ... + ) -> Self: ... -default: EmailPolicy -SMTP: EmailPolicy -SMTPUTF8: EmailPolicy -HTTP: EmailPolicy -strict: EmailPolicy +default: EmailPolicy[EmailMessage] +SMTP: EmailPolicy[EmailMessage] +SMTPUTF8: EmailPolicy[EmailMessage] +HTTP: EmailPolicy[EmailMessage] +strict: EmailPolicy[EmailMessage] diff --git a/stdlib/email/quoprimime.pyi b/stdlib/email/quoprimime.pyi index 41c4bd8cca9e..87d08eecc70c 100644 --- a/stdlib/email/quoprimime.pyi +++ b/stdlib/email/quoprimime.pyi @@ -1,12 +1,27 @@ +from collections.abc import Iterable + +__all__ = [ + "body_decode", + "body_encode", + "body_length", + "decode", + "decodestring", + "header_decode", + "header_encode", + "header_length", + "quote", + "unquote", +] + def header_check(octet: int) -> bool: ... def body_check(octet: int) -> bool: ... -def header_length(bytearray: bytes) -> int: ... -def body_length(bytearray: bytes) -> int: ... -def unquote(s: str | bytes) -> str: ... -def quote(c: str | bytes) -> str: ... -def header_encode(header_bytes: bytes, charset: str = ...) -> str: ... -def body_encode(body: str, maxlinelen: int = ..., eol: str = ...) -> str: ... -def decode(encoded: str, eol: str = ...) -> str: ... +def header_length(bytearray: Iterable[int]) -> int: ... +def body_length(bytearray: Iterable[int]) -> int: ... +def unquote(s: str | bytes | bytearray) -> str: ... +def quote(c: str | bytes | bytearray) -> str: ... +def header_encode(header_bytes: bytes | bytearray, charset: str = "iso-8859-1") -> str: ... +def body_encode(body: str, maxlinelen: int = 76, eol: str = "\n") -> str: ... +def decode(encoded: str, eol: str = "\n") -> str: ... def header_decode(s: str) -> str: ... body_decode = decode diff --git a/stdlib/email/utils.pyi b/stdlib/email/utils.pyi index 3c07e98079fc..db42aff7d1f3 100644 --- a/stdlib/email/utils.pyi +++ b/stdlib/email/utils.pyi @@ -1,40 +1,72 @@ import datetime import sys +from _typeshed import Unused +from collections.abc import Iterable +from email import _ParamType from email.charset import Charset -from typing import Optional, Tuple, Union, overload +from typing import TypeAlias, overload +from typing_extensions import deprecated -_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] -_PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] +__all__ = [ + "collapse_rfc2231_value", + "decode_params", + "decode_rfc2231", + "encode_rfc2231", + "formataddr", + "formatdate", + "format_datetime", + "getaddresses", + "make_msgid", + "mktime_tz", + "parseaddr", + "parsedate", + "parsedate_tz", + "parsedate_to_datetime", + "unquote", +] + +_PDTZ: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int | None] def quote(str: str) -> str: ... def unquote(str: str) -> str: ... -def parseaddr(addr: str | None) -> tuple[str, str]: ... -def formataddr(pair: tuple[str | None, str], charset: str | Charset = ...) -> str: ... -def getaddresses(fieldvalues: list[str]) -> list[tuple[str, str]]: ... + +# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +def parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]: ... +def formataddr(pair: tuple[str | None, str], charset: str | Charset = "utf-8") -> str: ... + +# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +def getaddresses(fieldvalues: Iterable[str], *, strict: bool = True) -> list[tuple[str, str]]: ... + @overload def parsedate(data: None) -> None: ... @overload def parsedate(data: str) -> tuple[int, int, int, int, int, int, int, int, int] | None: ... + @overload def parsedate_tz(data: None) -> None: ... @overload def parsedate_tz(data: str) -> _PDTZ | None: ... -if sys.version_info >= (3, 10): +def parsedate_to_datetime(data: str) -> datetime.datetime: ... +def mktime_tz(data: _PDTZ) -> int: ... +def formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bool = False) -> str: ... +def format_datetime(dt: datetime.datetime, usegmt: bool = False) -> str: ... + +if sys.version_info >= (3, 14): + def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ... + +elif sys.version_info >= (3, 12): @overload - def parsedate_to_datetime(data: None) -> None: ... + def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ... @overload - def parsedate_to_datetime(data: str) -> datetime.datetime: ... + @deprecated("The `isdst` parameter is ignored; removed in Python 3.14.") + def localtime(dt: datetime.datetime | None = None, isdst: Unused = None) -> datetime.datetime: ... else: - def parsedate_to_datetime(data: str) -> datetime.datetime: ... + def localtime(dt: datetime.datetime | None = None, isdst: int = -1) -> datetime.datetime: ... -def mktime_tz(data: _PDTZ) -> int: ... -def formatdate(timeval: float | None = ..., localtime: bool = ..., usegmt: bool = ...) -> str: ... -def format_datetime(dt: datetime.datetime, usegmt: bool = ...) -> str: ... -def localtime(dt: datetime.datetime | None = ..., isdst: int = ...) -> datetime.datetime: ... -def make_msgid(idstring: str | None = ..., domain: str | None = ...) -> str: ... -def decode_rfc2231(s: str) -> tuple[str | None, str | None, str]: ... -def encode_rfc2231(s: str, charset: str | None = ..., language: str | None = ...) -> str: ... -def collapse_rfc2231_value(value: _ParamType, errors: str = ..., fallback_charset: str = ...) -> str: ... +def make_msgid(idstring: str | None = None, domain: str | None = None) -> str: ... +def decode_rfc2231(s: str) -> tuple[str | None, str | None, str]: ... # May return list[str]. See issue #10431 for details. +def encode_rfc2231(s: str, charset: str | None = None, language: str | None = None) -> str: ... +def collapse_rfc2231_value(value: _ParamType, errors: str = "replace", fallback_charset: str = "us-ascii") -> str: ... def decode_params(params: list[tuple[str, str]]) -> list[tuple[str, _ParamType]]: ... diff --git a/stdlib/encodings/__init__.pyi b/stdlib/encodings/__init__.pyi index d86466762268..e03758ce59a0 100644 --- a/stdlib/encodings/__init__.pyi +++ b/stdlib/encodings/__init__.pyi @@ -1,10 +1,15 @@ +import sys from codecs import CodecInfo -from typing import Any + +from . import aliases as aliases class CodecRegistryError(LookupError, SystemError): ... def normalize_encoding(encoding: str | bytes) -> str: ... def search_function(encoding: str) -> CodecInfo | None: ... +if sys.version_info >= (3, 14) and sys.platform == "win32": + def win32_code_page_search_function(encoding: str) -> CodecInfo | None: ... + # Needed for submodules -def __getattr__(name: str) -> Any: ... # incomplete +def __getattr__(name: str): ... # incomplete module diff --git a/stdlib/encodings/aliases.pyi b/stdlib/encodings/aliases.pyi new file mode 100644 index 000000000000..079af85d51ee --- /dev/null +++ b/stdlib/encodings/aliases.pyi @@ -0,0 +1 @@ +aliases: dict[str, str] diff --git a/stdlib/encodings/ascii.pyi b/stdlib/encodings/ascii.pyi new file mode 100644 index 000000000000..a85585af32ed --- /dev/null +++ b/stdlib/encodings/ascii.pyi @@ -0,0 +1,30 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.ascii_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.ascii_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +# Note: encode being a decode function and decode being an encode function is accurate to runtime. +class StreamConverter(StreamWriter, StreamReader): # type: ignore[misc] # incompatible methods in base classes + # At runtime, this is codecs.ascii_decode + @staticmethod + def encode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... # type: ignore[override] + # At runtime, this is codecs.ascii_encode + @staticmethod + def decode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/base64_codec.pyi b/stdlib/encodings/base64_codec.pyi new file mode 100644 index 000000000000..0c4f1cb1fe59 --- /dev/null +++ b/stdlib/encodings/base64_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def base64_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def base64_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/big5.pyi b/stdlib/encodings/big5.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/big5.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/big5hkscs.pyi b/stdlib/encodings/big5hkscs.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/big5hkscs.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/bz2_codec.pyi b/stdlib/encodings/bz2_codec.pyi new file mode 100644 index 000000000000..468346a93da9 --- /dev/null +++ b/stdlib/encodings/bz2_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def bz2_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def bz2_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/charmap.pyi b/stdlib/encodings/charmap.pyi new file mode 100644 index 000000000000..a65e7c7c836f --- /dev/null +++ b/stdlib/encodings/charmap.pyi @@ -0,0 +1,33 @@ +import codecs +from _codecs import _DecodeCharMap, _EncodeCharMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.charmap_encode + @staticmethod + def encode(str: str, errors: str | None = None, mapping: _EncodeCharMap | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.charmap_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, mapping: _DecodeCharMap | None = None, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + mapping: _EncodeCharMap | None + def __init__(self, errors: str = "strict", mapping: _EncodeCharMap | None = None) -> None: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + mapping: _DecodeCharMap | None + def __init__(self, errors: str = "strict", mapping: _DecodeCharMap | None = None) -> None: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): + mapping: _EncodeCharMap | None + def __init__(self, stream: codecs._WritableStream, errors: str = "strict", mapping: _EncodeCharMap | None = None) -> None: ... + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class StreamReader(Codec, codecs.StreamReader): + mapping: _DecodeCharMap | None + def __init__(self, stream: codecs._ReadableStream, errors: str = "strict", mapping: _DecodeCharMap | None = None) -> None: ... + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/cp037.pyi b/stdlib/encodings/cp037.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp037.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1006.pyi b/stdlib/encodings/cp1006.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1006.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1026.pyi b/stdlib/encodings/cp1026.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1026.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1125.pyi b/stdlib/encodings/cp1125.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp1125.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp1140.pyi b/stdlib/encodings/cp1140.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1140.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1250.pyi b/stdlib/encodings/cp1250.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1250.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1251.pyi b/stdlib/encodings/cp1251.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1251.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1252.pyi b/stdlib/encodings/cp1252.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1252.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1253.pyi b/stdlib/encodings/cp1253.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1253.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1254.pyi b/stdlib/encodings/cp1254.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1254.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1255.pyi b/stdlib/encodings/cp1255.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1255.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1256.pyi b/stdlib/encodings/cp1256.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1256.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1257.pyi b/stdlib/encodings/cp1257.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1257.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1258.pyi b/stdlib/encodings/cp1258.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1258.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp273.pyi b/stdlib/encodings/cp273.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp273.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp424.pyi b/stdlib/encodings/cp424.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp424.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp437.pyi b/stdlib/encodings/cp437.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp437.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp500.pyi b/stdlib/encodings/cp500.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp500.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp720.pyi b/stdlib/encodings/cp720.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp720.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp737.pyi b/stdlib/encodings/cp737.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp737.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp775.pyi b/stdlib/encodings/cp775.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp775.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp850.pyi b/stdlib/encodings/cp850.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp850.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp852.pyi b/stdlib/encodings/cp852.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp852.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp855.pyi b/stdlib/encodings/cp855.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp855.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp856.pyi b/stdlib/encodings/cp856.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp856.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp857.pyi b/stdlib/encodings/cp857.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp857.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp858.pyi b/stdlib/encodings/cp858.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp858.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp860.pyi b/stdlib/encodings/cp860.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp860.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp861.pyi b/stdlib/encodings/cp861.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp861.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp862.pyi b/stdlib/encodings/cp862.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp862.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp863.pyi b/stdlib/encodings/cp863.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp863.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp864.pyi b/stdlib/encodings/cp864.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp864.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp865.pyi b/stdlib/encodings/cp865.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp865.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp866.pyi b/stdlib/encodings/cp866.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp866.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp869.pyi b/stdlib/encodings/cp869.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp869.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp874.pyi b/stdlib/encodings/cp874.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp874.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp875.pyi b/stdlib/encodings/cp875.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp875.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp932.pyi b/stdlib/encodings/cp932.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/cp932.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/cp949.pyi b/stdlib/encodings/cp949.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/cp949.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/cp950.pyi b/stdlib/encodings/cp950.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/cp950.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_jis_2004.pyi b/stdlib/encodings/euc_jis_2004.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_jis_2004.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_jisx0213.pyi b/stdlib/encodings/euc_jisx0213.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_jisx0213.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_jp.pyi b/stdlib/encodings/euc_jp.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_jp.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_kr.pyi b/stdlib/encodings/euc_kr.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_kr.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/gb18030.pyi b/stdlib/encodings/gb18030.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/gb18030.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/gb2312.pyi b/stdlib/encodings/gb2312.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/gb2312.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/gbk.pyi b/stdlib/encodings/gbk.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/gbk.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/hex_codec.pyi b/stdlib/encodings/hex_codec.pyi new file mode 100644 index 000000000000..3fd4fe38898a --- /dev/null +++ b/stdlib/encodings/hex_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def hex_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def hex_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/hp_roman8.pyi b/stdlib/encodings/hp_roman8.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/hp_roman8.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/hz.pyi b/stdlib/encodings/hz.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/hz.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/idna.pyi b/stdlib/encodings/idna.pyi new file mode 100644 index 000000000000..3e2c8baf1cb2 --- /dev/null +++ b/stdlib/encodings/idna.pyi @@ -0,0 +1,26 @@ +import codecs +import re +from _typeshed import ReadableBuffer + +dots: re.Pattern[str] +ace_prefix: bytes +sace_prefix: str + +def nameprep(label: str) -> str: ... +def ToASCII(label: str) -> bytes: ... +def ToUnicode(label: bytes | str) -> str: ... + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: ReadableBuffer | str, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.BufferedIncrementalEncoder): + def _buffer_encode(self, input: str, errors: str, final: bool) -> tuple[bytes, int]: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: ReadableBuffer | str, errors: str, final: bool) -> tuple[str, int]: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp.pyi b/stdlib/encodings/iso2022_jp.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_1.pyi b/stdlib/encodings/iso2022_jp_1.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_1.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_2.pyi b/stdlib/encodings/iso2022_jp_2.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_2.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_2004.pyi b/stdlib/encodings/iso2022_jp_2004.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_2004.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_3.pyi b/stdlib/encodings/iso2022_jp_3.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_3.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_ext.pyi b/stdlib/encodings/iso2022_jp_ext.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_ext.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_kr.pyi b/stdlib/encodings/iso2022_kr.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_kr.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso8859_1.pyi b/stdlib/encodings/iso8859_1.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_1.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_10.pyi b/stdlib/encodings/iso8859_10.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_10.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_11.pyi b/stdlib/encodings/iso8859_11.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_11.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_13.pyi b/stdlib/encodings/iso8859_13.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_13.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_14.pyi b/stdlib/encodings/iso8859_14.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_14.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_15.pyi b/stdlib/encodings/iso8859_15.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_15.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_16.pyi b/stdlib/encodings/iso8859_16.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_16.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_2.pyi b/stdlib/encodings/iso8859_2.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_2.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_3.pyi b/stdlib/encodings/iso8859_3.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_3.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_4.pyi b/stdlib/encodings/iso8859_4.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_4.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_5.pyi b/stdlib/encodings/iso8859_5.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_5.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_6.pyi b/stdlib/encodings/iso8859_6.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_6.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_7.pyi b/stdlib/encodings/iso8859_7.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_7.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_8.pyi b/stdlib/encodings/iso8859_8.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_8.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_9.pyi b/stdlib/encodings/iso8859_9.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_9.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/johab.pyi b/stdlib/encodings/johab.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/johab.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/koi8_r.pyi b/stdlib/encodings/koi8_r.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/koi8_r.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/koi8_t.pyi b/stdlib/encodings/koi8_t.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/koi8_t.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/koi8_u.pyi b/stdlib/encodings/koi8_u.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/koi8_u.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/kz1048.pyi b/stdlib/encodings/kz1048.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/kz1048.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/latin_1.pyi b/stdlib/encodings/latin_1.pyi new file mode 100644 index 000000000000..3b06773eac03 --- /dev/null +++ b/stdlib/encodings/latin_1.pyi @@ -0,0 +1,30 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.latin_1_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.latin_1_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +# Note: encode being a decode function and decode being an encode function is accurate to runtime. +class StreamConverter(StreamWriter, StreamReader): # type: ignore[misc] # incompatible methods in base classes + # At runtime, this is codecs.latin_1_decode + @staticmethod + def encode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... # type: ignore[override] + # At runtime, this is codecs.latin_1_encode + @staticmethod + def decode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/mac_arabic.pyi b/stdlib/encodings/mac_arabic.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/mac_arabic.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/mac_croatian.pyi b/stdlib/encodings/mac_croatian.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_croatian.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_cyrillic.pyi b/stdlib/encodings/mac_cyrillic.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_cyrillic.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_farsi.pyi b/stdlib/encodings/mac_farsi.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_farsi.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_greek.pyi b/stdlib/encodings/mac_greek.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_greek.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_iceland.pyi b/stdlib/encodings/mac_iceland.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_iceland.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_latin2.pyi b/stdlib/encodings/mac_latin2.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_latin2.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_roman.pyi b/stdlib/encodings/mac_roman.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_roman.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_romanian.pyi b/stdlib/encodings/mac_romanian.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_romanian.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_turkish.pyi b/stdlib/encodings/mac_turkish.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_turkish.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mbcs.pyi b/stdlib/encodings/mbcs.pyi new file mode 100644 index 000000000000..2c2917d63f6d --- /dev/null +++ b/stdlib/encodings/mbcs.pyi @@ -0,0 +1,28 @@ +import codecs +import sys +from _typeshed import ReadableBuffer + +if sys.platform == "win32": + encode = codecs.mbcs_encode + + def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + + class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + + class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.mbcs_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.mbcs_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + + class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.mbcs_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/oem.pyi b/stdlib/encodings/oem.pyi new file mode 100644 index 000000000000..376c12c445f4 --- /dev/null +++ b/stdlib/encodings/oem.pyi @@ -0,0 +1,28 @@ +import codecs +import sys +from _typeshed import ReadableBuffer + +if sys.platform == "win32": + encode = codecs.oem_encode + + def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + + class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + + class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.oem_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.oem_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + + class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.oem_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/palmos.pyi b/stdlib/encodings/palmos.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/palmos.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/ptcp154.pyi b/stdlib/encodings/ptcp154.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/ptcp154.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/punycode.pyi b/stdlib/encodings/punycode.pyi new file mode 100644 index 000000000000..eb99e667b416 --- /dev/null +++ b/stdlib/encodings/punycode.pyi @@ -0,0 +1,33 @@ +import codecs +from typing import Literal + +def segregate(str: str) -> tuple[bytes, list[int]]: ... +def selective_len(str: str, max: int) -> int: ... +def selective_find(str: str, char: str, index: int, pos: int) -> tuple[int, int]: ... +def insertion_unsort(str: str, extended: list[int]) -> list[int]: ... +def T(j: int, bias: int) -> int: ... + +digits: Literal[b"abcdefghijklmnopqrstuvwxyz0123456789"] + +def generate_generalized_integer(N: int, bias: int) -> bytes: ... +def adapt(delta: int, first: bool, numchars: int) -> int: ... +def generate_integers(baselen: int, deltas: list[int]) -> bytes: ... +def punycode_encode(text: str) -> bytes: ... +def decode_generalized_number(extended: bytes, extpos: int, bias: int, errors: str) -> tuple[int, int | None]: ... +def insertion_sort(base: str, extended: bytes, errors: str) -> str: ... +def punycode_decode(text: memoryview | bytes | bytearray | str, errors: str) -> str: ... + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: memoryview | bytes | bytearray | str, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: memoryview | bytes | bytearray | str, final: bool = False) -> str: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/quopri_codec.pyi b/stdlib/encodings/quopri_codec.pyi new file mode 100644 index 000000000000..e9deadd8d463 --- /dev/null +++ b/stdlib/encodings/quopri_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def quopri_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def quopri_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/raw_unicode_escape.pyi b/stdlib/encodings/raw_unicode_escape.pyi new file mode 100644 index 000000000000..2887739468f2 --- /dev/null +++ b/stdlib/encodings/raw_unicode_escape.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.raw_unicode_escape_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.raw_unicode_escape_decode + @staticmethod + def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... + +class StreamReader(Codec, codecs.StreamReader): + def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/rot_13.pyi b/stdlib/encodings/rot_13.pyi new file mode 100644 index 000000000000..8d71bc957594 --- /dev/null +++ b/stdlib/encodings/rot_13.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import SupportsRead, SupportsWrite + +# This codec is string to string. + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + def decode(self, input: str, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> str: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: str, final: bool = False) -> str: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +rot13_map: dict[int, int] + +def rot13(infile: SupportsRead[str], outfile: SupportsWrite[str]) -> None: ... diff --git a/stdlib/encodings/shift_jis.pyi b/stdlib/encodings/shift_jis.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/shift_jis.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/shift_jis_2004.pyi b/stdlib/encodings/shift_jis_2004.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/shift_jis_2004.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/shift_jisx0213.pyi b/stdlib/encodings/shift_jisx0213.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/shift_jisx0213.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/tis_620.pyi b/stdlib/encodings/tis_620.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/tis_620.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/undefined.pyi b/stdlib/encodings/undefined.pyi new file mode 100644 index 000000000000..4775dac752f2 --- /dev/null +++ b/stdlib/encodings/undefined.pyi @@ -0,0 +1,20 @@ +import codecs +from _typeshed import ReadableBuffer + +# These return types are just to match the base types. In reality, these always +# raise an error. + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/unicode_escape.pyi b/stdlib/encodings/unicode_escape.pyi new file mode 100644 index 000000000000..ceaa39a3859a --- /dev/null +++ b/stdlib/encodings/unicode_escape.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.unicode_escape_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.unicode_escape_decode + @staticmethod + def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... + +class StreamReader(Codec, codecs.StreamReader): + def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_16.pyi b/stdlib/encodings/utf_16.pyi new file mode 100644 index 000000000000..3b712cde420a --- /dev/null +++ b/stdlib/encodings/utf_16.pyi @@ -0,0 +1,20 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_16_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_16_be.pyi b/stdlib/encodings/utf_16_be.pyi new file mode 100644 index 000000000000..cc7d1534fc69 --- /dev/null +++ b/stdlib/encodings/utf_16_be.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_16_be_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_16_be_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_16_be_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_16_be_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_16_le.pyi b/stdlib/encodings/utf_16_le.pyi new file mode 100644 index 000000000000..ba103eb088e3 --- /dev/null +++ b/stdlib/encodings/utf_16_le.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_16_le_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_16_le_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_16_le_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_16_le_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_32.pyi b/stdlib/encodings/utf_32.pyi new file mode 100644 index 000000000000..c925be712c72 --- /dev/null +++ b/stdlib/encodings/utf_32.pyi @@ -0,0 +1,20 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_32_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_32_be.pyi b/stdlib/encodings/utf_32_be.pyi new file mode 100644 index 000000000000..9d28f5199c50 --- /dev/null +++ b/stdlib/encodings/utf_32_be.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_32_be_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_32_be_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_32_be_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_32_be_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_32_le.pyi b/stdlib/encodings/utf_32_le.pyi new file mode 100644 index 000000000000..5be14a91a3e6 --- /dev/null +++ b/stdlib/encodings/utf_32_le.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_32_le_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_32_le_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_32_le_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_32_le_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_7.pyi b/stdlib/encodings/utf_7.pyi new file mode 100644 index 000000000000..dc1162f34c28 --- /dev/null +++ b/stdlib/encodings/utf_7.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_7_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_7_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_7_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_7_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_8.pyi b/stdlib/encodings/utf_8.pyi index 568fa6013373..918712d80473 100644 --- a/stdlib/encodings/utf_8.pyi +++ b/stdlib/encodings/utf_8.pyi @@ -1,20 +1,26 @@ import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_8_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... class IncrementalEncoder(codecs.IncrementalEncoder): - def encode(self, input: str, final: bool = ...) -> bytes: ... + def encode(self, input: str, final: bool = False) -> bytes: ... class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_8_decode @staticmethod - def _buffer_decode(__data: bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_8_encode @staticmethod - def encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_8_decode @staticmethod - def decode(__data: bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... def getregentry() -> codecs.CodecInfo: ... -def encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def decode(input: bytes, errors: str | None = ...) -> tuple[str, int]: ... diff --git a/stdlib/encodings/utf_8_sig.pyi b/stdlib/encodings/utf_8_sig.pyi new file mode 100644 index 000000000000..af69217d6732 --- /dev/null +++ b/stdlib/encodings/utf_8_sig.pyi @@ -0,0 +1,22 @@ +import codecs +from _typeshed import ReadableBuffer + +class IncrementalEncoder(codecs.IncrementalEncoder): + def __init__(self, errors: str = "strict") -> None: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + def getstate(self) -> int: ... + def setstate(self, state: int) -> None: ... # type: ignore[override] + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def __init__(self, errors: str = "strict") -> None: ... + def _buffer_decode(self, input: ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + def encode(self, input: str, errors: str | None = "strict") -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def decode(self, input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: str, errors: str | None = "strict") -> tuple[bytes, int]: ... +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... diff --git a/stdlib/encodings/uu_codec.pyi b/stdlib/encodings/uu_codec.pyi new file mode 100644 index 000000000000..e32ba8ac0a1a --- /dev/null +++ b/stdlib/encodings/uu_codec.pyi @@ -0,0 +1,28 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def uu_encode( + input: ReadableBuffer, errors: str = "strict", filename: str = "", mode: int = 0o666 +) -> tuple[bytes, int]: ... +def uu_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/zlib_codec.pyi b/stdlib/encodings/zlib_codec.pyi new file mode 100644 index 000000000000..0f13d0e810e9 --- /dev/null +++ b/stdlib/encodings/zlib_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def zlib_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def zlib_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/ensurepip/__init__.pyi b/stdlib/ensurepip/__init__.pyi index 749fedc04424..332fb1845917 100644 --- a/stdlib/ensurepip/__init__.pyi +++ b/stdlib/ensurepip/__init__.pyi @@ -1,10 +1,12 @@ +__all__ = ["version", "bootstrap"] + def version() -> str: ... def bootstrap( *, - root: str | None = ..., - upgrade: bool = ..., - user: bool = ..., - altinstall: bool = ..., - default_pip: bool = ..., - verbosity: int = ..., + root: str | None = None, + upgrade: bool = False, + user: bool = False, + altinstall: bool = False, + default_pip: bool = False, + verbosity: int = 0, ) -> None: ... diff --git a/stdlib/enum.pyi b/stdlib/enum.pyi index e8846ba5293e..f416f38177cc 100644 --- a/stdlib/enum.pyi +++ b/stdlib/enum.pyi @@ -1,12 +1,47 @@ +import _typeshed import sys import types -from abc import ABCMeta +from _typeshed import SupportsKeysAndGetItem, Unused from builtins import property as _builtins_property -from collections.abc import Iterable, Iterator, Mapping -from typing import Any, Dict, Tuple, Type, TypeVar, Union, overload +from collections.abc import Callable, Iterable, Iterator, Mapping +from typing import Any, Final, Generic, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self, disjoint_base -_T = TypeVar("_T") -_S = TypeVar("_S", bound=Type[Enum]) +__all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] + +if sys.version_info >= (3, 11): + __all__ += [ + "CONFORM", + "CONTINUOUS", + "EJECT", + "EnumCheck", + "EnumType", + "FlagBoundary", + "KEEP", + "NAMED_FLAGS", + "ReprEnum", + "STRICT", + "StrEnum", + "UNIQUE", + "global_enum", + "global_enum_repr", + "global_flag_repr", + "global_str", + "member", + "nonmember", + "property", + "verify", + "pickle_by_enum_name", + "pickle_by_global_name", + ] + +if sys.version_info >= (3, 13): + __all__ += ["EnumDict"] +if sys.version_info >= (3, 15): + __all__ += ["show_flag_values", "bin"] + +_EnumMemberT = TypeVar("_EnumMemberT") +_EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) # The following all work: # >>> from enum import Enum @@ -19,70 +54,124 @@ _S = TypeVar("_S", bound=Type[Enum]) # # >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2}) # -_EnumNames = Union[str, Iterable[str], Iterable[Iterable[Union[str, Any]]], Mapping[str, Any]] +_EnumNames: TypeAlias = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] +_Signature: TypeAlias = Any # TODO: Unable to import Signature from inspect module + +if sys.version_info >= (3, 11): + class nonmember(Generic[_EnumMemberT]): + value: _EnumMemberT + def __init__(self, value: _EnumMemberT) -> None: ... + + class member(Generic[_EnumMemberT]): + value: _EnumMemberT + def __init__(self, value: _EnumMemberT) -> None: ... + +class _EnumDict(dict[str, Any]): + if sys.version_info >= (3, 13): + def __init__(self, cls_name: str | None = None) -> None: ... + else: + def __init__(self) -> None: ... + + def __setitem__(self, key: str, value: Any) -> None: ... + if sys.version_info >= (3, 11): + # See comment above `typing.MutableMapping.update` + # for why overloads are preferable to a Union here + # + # Unlike with MutableMapping.update(), the first argument is required, + # hence the type: ignore + @overload # type: ignore[override] + def update(self, members: SupportsKeysAndGetItem[str, Any], **more_members: Any) -> None: ... + @overload + def update(self, members: Iterable[tuple[str, Any]], **more_members: Any) -> None: ... + + if sys.version_info >= (3, 13): + @property + def member_names(self) -> list[str]: ... -class _EnumDict(Dict[str, Any]): - def __init__(self) -> None: ... +if sys.version_info >= (3, 13): + EnumDict = _EnumDict -# Note: EnumMeta actually subclasses type directly, not ABCMeta. -# This is a temporary workaround to allow multiple creation of enums with builtins -# such as str as mixins, which due to the handling of ABCs of builtin types, cause -# spurious inconsistent metaclass structure. See #1595. # Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself -class EnumMeta(ABCMeta): +class EnumMeta(type): if sys.version_info >= (3, 11): def __new__( - metacls: Type[_T], + metacls: type[_typeshed.Self], cls: str, - bases: Tuple[type, ...], + bases: tuple[type, ...], classdict: _EnumDict, *, - boundary: FlagBoundary | None = ..., - _simple: bool = ..., + boundary: FlagBoundary | None = None, + _simple: bool = False, **kwds: Any, - ) -> _T: ... - elif sys.version_info >= (3, 9): - def __new__(metacls: Type[_T], cls: str, bases: Tuple[type, ...], classdict: _EnumDict, **kwds: Any) -> _T: ... # type: ignore + ) -> _typeshed.Self: ... else: - def __new__(metacls: Type[_T], cls: str, bases: Tuple[type, ...], classdict: _EnumDict) -> _T: ... # type: ignore - def __iter__(self: Type[_T]) -> Iterator[_T]: ... - def __reversed__(self: Type[_T]) -> Iterator[_T]: ... - def __contains__(self: Type[Any], member: object) -> bool: ... - def __getitem__(self: Type[_T], name: str) -> _T: ... + def __new__( + metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any + ) -> _typeshed.Self: ... + + @classmethod + def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override] + def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... + def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... + if sys.version_info >= (3, 12): + def __contains__(self: type[Any], value: object) -> bool: ... + elif sys.version_info >= (3, 11): + def __contains__(self: type[Any], member: Enum) -> bool: ... + else: + def __contains__(self: type[Any], obj: Enum) -> bool: ... + + def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT: ... @_builtins_property - def __members__(self: Type[_T]) -> types.MappingProxyType[str, _T]: ... + def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: ... def __len__(self) -> int: ... + def __bool__(self) -> Literal[True]: ... + def __dir__(self) -> list[str]: ... + + # Overload 1: Value lookup on an already existing enum class (simple case) + @overload + def __call__(cls: type[_EnumMemberT], value: Any, names: None = None) -> _EnumMemberT: ... + + # Overload 2: Functional API for constructing new enum classes. if sys.version_info >= (3, 11): - # Simple value lookup - @overload # type: ignore[override] - def __call__(cls: Type[_T], value: Any, names: None = ...) -> _T: ... - # Functional Enum API @overload def __call__( cls, value: str, names: _EnumNames, *, - module: str | None = ..., - qualname: str | None = ..., - type: type | None = ..., - start: int = ..., - boundary: FlagBoundary | None = ..., - ) -> Type[Enum]: ... + module: str | None = None, + qualname: str | None = None, + type: type | None = None, + start: int = 1, + boundary: FlagBoundary | None = None, + ) -> type[Enum]: ... else: - @overload # type: ignore[override] - def __call__(cls: Type[_T], value: Any, names: None = ...) -> _T: ... @overload def __call__( cls, value: str, names: _EnumNames, *, - module: str | None = ..., - qualname: str | None = ..., - type: type | None = ..., - start: int = ..., - ) -> Type[Enum]: ... + module: str | None = None, + qualname: str | None = None, + type: type | None = None, + start: int = 1, + ) -> type[Enum]: ... + + # Overload 3 (py312+ only): Value lookup on an already existing enum class (complex case) + # + # >>> class Foo(enum.Enum): + # ... X = 1, 2, 3 + # >>> Foo(1, 2, 3) + # + # + if sys.version_info >= (3, 12): + @overload + def __call__(cls: type[_EnumMemberT], value: Any, *values: Any) -> _EnumMemberT: ... + if sys.version_info >= (3, 14): + @property + def __signature__(cls) -> _Signature: ... + _member_names_: list[str] # undocumented _member_map_: dict[str, Enum] # undocumented _value2member_map_: dict[Any, Enum] # undocumented @@ -91,110 +180,195 @@ if sys.version_info >= (3, 11): # In 3.11 `EnumMeta` metaclass is renamed to `EnumType`, but old name also exists. EnumType = EnumMeta + class property(types.DynamicClassAttribute): + def __set_name__(self, ownerclass: type[Enum], name: str) -> None: ... + name: str + clsname: str + member: Enum | None + + _magic_enum_attr = property +else: + _magic_enum_attr = types.DynamicClassAttribute + class Enum(metaclass=EnumMeta): - if sys.version_info >= (3, 11): - @property - def name(self) -> str: ... - @property - def value(self) -> Any: ... - else: - @types.DynamicClassAttribute - def name(self) -> str: ... - @types.DynamicClassAttribute - def value(self) -> Any: ... + @_magic_enum_attr + def name(self) -> str: ... + @_magic_enum_attr + def value(self) -> Any: ... _name_: str _value_: Any - if sys.version_info >= (3, 7): - _ignore_: str | list[str] + _ignore_: str | list[str] _order_: str __order__: str @classmethod def _missing_(cls, value: object) -> Any: ... @staticmethod def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: ... - def __new__(cls: Type[_T], value: object) -> _T: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... + # It's not true that `__new__` will accept any argument type, + # so ideally we'd use `Any` to indicate that the argument type is inexpressible. + # However, using `Any` causes too many false-positives for those using mypy's `--disallow-any-expr` + # (see #7752, #2539, mypy/#5788), + # and in practice using `object` here has the same effect as using `Any`. + def __new__(cls, value: object) -> Self: ... def __dir__(self) -> list[str]: ... + def __hash__(self) -> int: ... def __format__(self, format_spec: str) -> str: ... - def __hash__(self) -> Any: ... - def __reduce_ex__(self, proto: object) -> Any: ... - -class IntEnum(int, Enum): - _value_: int + def __reduce_ex__(self, proto: Unused) -> tuple[Any, ...]: ... if sys.version_info >= (3, 11): - @property + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... + if sys.version_info >= (3, 12) and sys.version_info < (3, 14): + @classmethod + def __signature__(cls) -> str: ... + if sys.version_info >= (3, 13): + # Value may be any type, even in special enums. Enabling Enum parsing from + # multiple value types + def _add_value_alias_(self, value: Any) -> None: ... + def _add_alias_(self, name: str) -> None: ... + +if sys.version_info >= (3, 11): + class ReprEnum(Enum): ... + +if sys.version_info >= (3, 12): + class IntEnum(int, ReprEnum): + _value_: int + @_magic_enum_attr def value(self) -> int: ... + def __new__(cls, value: int) -> Self: ... + +else: + if sys.version_info >= (3, 11): + _IntEnumBase = ReprEnum else: - @types.DynamicClassAttribute + _IntEnumBase = Enum + + @disjoint_base + class IntEnum(int, _IntEnumBase): + _value_: int + @_magic_enum_attr def value(self) -> int: ... - def __new__(cls: Type[_T], value: int | _T) -> _T: ... + def __new__(cls, value: int) -> Self: ... -def unique(enumeration: _S) -> _S: ... +def unique(enumeration: _EnumerationT) -> _EnumerationT: ... _auto_null: Any -# subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() -class auto(IntFlag): - _value_: Any - if sys.version_info >= (3, 11): - @property - def value(self) -> Any: ... - else: - @types.DynamicClassAttribute - def value(self) -> Any: ... - def __new__(cls: Type[_T]) -> _T: ... - class Flag(Enum): _name_: str | None # type: ignore[assignment] _value_: int - if sys.version_info >= (3, 11): - @property - def name(self) -> str | None: ... # type: ignore[override] - @property - def value(self) -> int: ... - else: - @types.DynamicClassAttribute - def name(self) -> str | None: ... # type: ignore[override] - @types.DynamicClassAttribute - def value(self) -> int: ... - def __contains__(self: _T, other: _T) -> bool: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... + _numeric_repr_: Callable[[int], str] + @_magic_enum_attr + def name(self) -> str | None: ... # type: ignore[override] + @_magic_enum_attr + def value(self) -> int: ... + def __contains__(self, other: Self) -> bool: ... def __bool__(self) -> bool: ... - def __or__(self: _T, other: _T) -> _T: ... - def __and__(self: _T, other: _T) -> _T: ... - def __xor__(self: _T, other: _T) -> _T: ... - def __invert__(self: _T) -> _T: ... - -class IntFlag(int, Flag): - def __new__(cls: Type[_T], value: int | _T) -> _T: ... - def __or__(self: _T, other: int | _T) -> _T: ... - def __and__(self: _T, other: int | _T) -> _T: ... - def __xor__(self: _T, other: int | _T) -> _T: ... - def __ror__(self: _T, n: int | _T) -> _T: ... - def __rand__(self: _T, n: int | _T) -> _T: ... - def __rxor__(self: _T, n: int | _T) -> _T: ... + def __or__(self, other: Self) -> Self: ... + def __and__(self, other: Self) -> Self: ... + def __xor__(self, other: Self) -> Self: ... + def __invert__(self) -> Self: ... + if sys.version_info >= (3, 11): + def __iter__(self) -> Iterator[Self]: ... + def __len__(self) -> int: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ if sys.version_info >= (3, 11): - class StrEnum(str, Enum): - def __new__(cls: Type[_T], value: str | _T) -> _T: ... + class StrEnum(str, ReprEnum): + def __new__(cls, value: str) -> Self: ... _value_: str - @property + @_magic_enum_attr def value(self) -> str: ... + @staticmethod + def _generate_next_value_(name: str, start: int, count: int, last_values: list[str]) -> str: ... + + class EnumCheck(StrEnum): + CONTINUOUS = "no skipped integer values" + NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags" + UNIQUE = "one name per value" + + CONTINUOUS: Final = EnumCheck.CONTINUOUS + NAMED_FLAGS: Final = EnumCheck.NAMED_FLAGS + UNIQUE: Final = EnumCheck.UNIQUE + + class verify: + def __init__(self, *checks: EnumCheck) -> None: ... + def __call__(self, enumeration: _EnumerationT) -> _EnumerationT: ... + class FlagBoundary(StrEnum): - STRICT: str - CONFORM: str - EJECT: str - KEEP: str - STRICT = FlagBoundary.STRICT - CONFORM = FlagBoundary.CONFORM - EJECT = FlagBoundary.EJECT - KEEP = FlagBoundary.KEEP - class property(types.DynamicClassAttribute): - def __set_name__(self, ownerclass: Type[Enum], name: str) -> None: ... - name: str - clsname: str - def global_enum(cls: _S) -> _S: ... + STRICT = "strict" + CONFORM = "conform" + EJECT = "eject" + KEEP = "keep" + + STRICT: Final = FlagBoundary.STRICT + CONFORM: Final = FlagBoundary.CONFORM + EJECT: Final = FlagBoundary.EJECT + KEEP: Final = FlagBoundary.KEEP + + def global_str(self: Enum) -> str: ... + def global_enum(cls: _EnumerationT, update_str: bool = False) -> _EnumerationT: ... def global_enum_repr(self: Enum) -> str: ... def global_flag_repr(self: Flag) -> str: ... + def show_flag_values(value: int) -> list[int]: ... + def bin(num: SupportsIndex, max_bits: int | None = None) -> str: ... + +if sys.version_info >= (3, 12): + # The body of the class is the same, but the base classes are different. + class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases + def __new__(cls, value: int) -> Self: ... + def __or__(self, other: int) -> Self: ... + def __and__(self, other: int) -> Self: ... + def __xor__(self, other: int) -> Self: ... + def __invert__(self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +elif sys.version_info >= (3, 11): + # The body of the class is the same, but the base classes are different. + @disjoint_base + class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases + def __new__(cls, value: int) -> Self: ... + def __or__(self, other: int) -> Self: ... + def __and__(self, other: int) -> Self: ... + def __xor__(self, other: int) -> Self: ... + def __invert__(self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +else: + @disjoint_base + class IntFlag(int, Flag): # type: ignore[misc] # complaints about incompatible bases + def __new__(cls, value: int) -> Self: ... + def __or__(self, other: int) -> Self: ... + def __and__(self, other: int) -> Self: ... + def __xor__(self, other: int) -> Self: ... + def __invert__(self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +class auto: + _value_: Any + @_magic_enum_attr + def value(self) -> Any: ... + def __new__(cls) -> Self: ... + + # These don't exist, but auto is basically immediately replaced with + # either an int or a str depending on the type of the enum. StrEnum's auto + # shouldn't have these, but they're needed for int versions of auto (mostly the __or__). + # Ideally type checkers would special case auto enough to handle this, + # but until then this is a slightly inaccurate helping hand. + def __or__(self, other: int | Self) -> Self: ... + def __and__(self, other: int | Self) -> Self: ... + def __xor__(self, other: int | Self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +if sys.version_info >= (3, 11): + def pickle_by_global_name(self: Enum, proto: int) -> str: ... + def pickle_by_enum_name(self: _EnumMemberT, proto: int) -> tuple[Callable[..., Any], tuple[type[_EnumMemberT], str]]: ... diff --git a/stdlib/errno.pyi b/stdlib/errno.pyi index b053604fc33a..e025e1fd13b9 100644 --- a/stdlib/errno.pyi +++ b/stdlib/errno.pyi @@ -1,137 +1,227 @@ -from typing import Mapping +import sys +from collections.abc import Mapping +from typing import Final errorcode: Mapping[int, str] -EPERM: int -ENOENT: int -ESRCH: int -EINTR: int -EIO: int -ENXIO: int -E2BIG: int -ENOEXEC: int -EBADF: int -ECHILD: int -EAGAIN: int -ENOMEM: int -EACCES: int -EFAULT: int -ENOTBLK: int -EBUSY: int -EEXIST: int -EXDEV: int -ENODEV: int -ENOTDIR: int -EISDIR: int -EINVAL: int -ENFILE: int -EMFILE: int -ENOTTY: int -ETXTBSY: int -EFBIG: int -ENOSPC: int -ESPIPE: int -EROFS: int -EMLINK: int -EPIPE: int -EDOM: int -ERANGE: int -EDEADLCK: int -ENAMETOOLONG: int -ENOLCK: int -ENOSYS: int -ENOTEMPTY: int -ELOOP: int -EWOULDBLOCK: int -ENOMSG: int -EIDRM: int -ECHRNG: int -EL2NSYNC: int -EL3HLT: int -EL3RST: int -ELNRNG: int -EUNATCH: int -ENOCSI: int -EL2HLT: int -EBADE: int -EBADR: int -EXFULL: int -ENOANO: int -EBADRQC: int -EBADSLT: int -EDEADLOCK: int -EBFONT: int -ENOSTR: int -ENODATA: int -ETIME: int -ENOSR: int -ENONET: int -ENOPKG: int -EREMOTE: int -ENOLINK: int -EADV: int -ESRMNT: int -ECOMM: int -EPROTO: int -EMULTIHOP: int -EDOTDOT: int -EBADMSG: int -EOVERFLOW: int -ENOTUNIQ: int -EBADFD: int -EREMCHG: int -ELIBACC: int -ELIBBAD: int -ELIBSCN: int -ELIBMAX: int -ELIBEXEC: int -EILSEQ: int -ERESTART: int -ESTRPIPE: int -EUSERS: int -ENOTSOCK: int -EDESTADDRREQ: int -EMSGSIZE: int -EPROTOTYPE: int -ENOPROTOOPT: int -EPROTONOSUPPORT: int -ESOCKTNOSUPPORT: int -ENOTSUP: int -EOPNOTSUPP: int -EPFNOSUPPORT: int -EAFNOSUPPORT: int -EADDRINUSE: int -EADDRNOTAVAIL: int -ENETDOWN: int -ENETUNREACH: int -ENETRESET: int -ECONNABORTED: int -ECONNRESET: int -ENOBUFS: int -EISCONN: int -ENOTCONN: int -ESHUTDOWN: int -ETOOMANYREFS: int -ETIMEDOUT: int -ECONNREFUSED: int -EHOSTDOWN: int -EHOSTUNREACH: int -EALREADY: int -EINPROGRESS: int -ESTALE: int -EUCLEAN: int -ENOTNAM: int -ENAVAIL: int -EISNAM: int -EREMOTEIO: int -EDQUOT: int -ECANCELED: int # undocumented -EKEYEXPIRED: int # undocumented -EKEYREJECTED: int # undocumented -EKEYREVOKED: int # undocumented -EMEDIUMTYPE: int # undocumented -ENOKEY: int # undocumented -ENOMEDIUM: int # undocumented -ENOTRECOVERABLE: int # undocumented -EOWNERDEAD: int # undocumented -ERFKILL: int # undocumented +EPERM: Final[int] +ENOENT: Final[int] +ESRCH: Final[int] +EINTR: Final[int] +EIO: Final[int] +ENXIO: Final[int] +E2BIG: Final[int] +ENOEXEC: Final[int] +EBADF: Final[int] +ECHILD: Final[int] +EAGAIN: Final[int] +ENOMEM: Final[int] +EACCES: Final[int] +EFAULT: Final[int] +EBUSY: Final[int] +EEXIST: Final[int] +EXDEV: Final[int] +ENODEV: Final[int] +ENOTDIR: Final[int] +EISDIR: Final[int] +EINVAL: Final[int] +ENFILE: Final[int] +EMFILE: Final[int] +ENOTTY: Final[int] +ETXTBSY: Final[int] +EFBIG: Final[int] +ENOSPC: Final[int] +ESPIPE: Final[int] +EROFS: Final[int] +EMLINK: Final[int] +EPIPE: Final[int] +EDOM: Final[int] +ERANGE: Final[int] +EDEADLK: Final[int] +ENAMETOOLONG: Final[int] +ENOLCK: Final[int] +ENOSYS: Final[int] +ENOTEMPTY: Final[int] +ELOOP: Final[int] +EWOULDBLOCK: Final[int] +ENOMSG: Final[int] +EIDRM: Final[int] +ENOSTR: Final[int] +ENODATA: Final[int] +ETIME: Final[int] +ENOSR: Final[int] +EREMOTE: Final[int] +ENOLINK: Final[int] +EPROTO: Final[int] +EBADMSG: Final[int] +EOVERFLOW: Final[int] +EILSEQ: Final[int] +EUSERS: Final[int] +ENOTSOCK: Final[int] +EDESTADDRREQ: Final[int] +EMSGSIZE: Final[int] +EPROTOTYPE: Final[int] +ENOPROTOOPT: Final[int] +EPROTONOSUPPORT: Final[int] +ESOCKTNOSUPPORT: Final[int] +ENOTSUP: Final[int] +EOPNOTSUPP: Final[int] +EPFNOSUPPORT: Final[int] +EAFNOSUPPORT: Final[int] +EADDRINUSE: Final[int] +EADDRNOTAVAIL: Final[int] +ENETDOWN: Final[int] +ENETUNREACH: Final[int] +ENETRESET: Final[int] +ECONNABORTED: Final[int] +ECONNRESET: Final[int] +ENOBUFS: Final[int] +EISCONN: Final[int] +ENOTCONN: Final[int] +ESHUTDOWN: Final[int] +ETOOMANYREFS: Final[int] +ETIMEDOUT: Final[int] +ECONNREFUSED: Final[int] +EHOSTDOWN: Final[int] +EHOSTUNREACH: Final[int] +EALREADY: Final[int] +EINPROGRESS: Final[int] +ESTALE: Final[int] +EDQUOT: Final[int] +ECANCELED: Final[int] # undocumented +ENOTRECOVERABLE: Final[int] # undocumented +EOWNERDEAD: Final[int] # undocumented + +if sys.platform == "sunos5" or sys.platform == "solaris": # noqa: Y008 + ELOCKUNMAPPED: Final[int] + ENOTACTIVE: Final[int] + +if sys.platform != "win32": + ENOTBLK: Final[int] + EMULTIHOP: Final[int] + +if sys.platform == "darwin": + # All of the below are undocumented + EAUTH: Final[int] + EBADARCH: Final[int] + EBADEXEC: Final[int] + EBADMACHO: Final[int] + EBADRPC: Final[int] + EDEVERR: Final[int] + EFTYPE: Final[int] + ENEEDAUTH: Final[int] + ENOATTR: Final[int] + ENOPOLICY: Final[int] + EPROCLIM: Final[int] + EPROCUNAVAIL: Final[int] + EPROGMISMATCH: Final[int] + EPROGUNAVAIL: Final[int] + EPWROFF: Final[int] + ERPCMISMATCH: Final[int] + ESHLIBVERS: Final[int] + if sys.version_info >= (3, 11): + EQFULL: Final[int] + ENOTCAPABLE: Final[int] # available starting with 3.11.1 + +if sys.platform != "darwin": + EDEADLOCK: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + ECHRNG: Final[int] + EL2NSYNC: Final[int] + EL3HLT: Final[int] + EL3RST: Final[int] + ELNRNG: Final[int] + EUNATCH: Final[int] + ENOCSI: Final[int] + EL2HLT: Final[int] + EBADE: Final[int] + EBADR: Final[int] + EXFULL: Final[int] + ENOANO: Final[int] + EBADRQC: Final[int] + EBADSLT: Final[int] + EBFONT: Final[int] + ENONET: Final[int] + ENOPKG: Final[int] + EADV: Final[int] + ESRMNT: Final[int] + ECOMM: Final[int] + EDOTDOT: Final[int] + ENOTUNIQ: Final[int] + EBADFD: Final[int] + EREMCHG: Final[int] + ELIBACC: Final[int] + ELIBBAD: Final[int] + ELIBSCN: Final[int] + ELIBMAX: Final[int] + ELIBEXEC: Final[int] + ERESTART: Final[int] + ESTRPIPE: Final[int] + EUCLEAN: Final[int] + ENOTNAM: Final[int] + ENAVAIL: Final[int] + EISNAM: Final[int] + EREMOTEIO: Final[int] + # All of the below are undocumented + EKEYEXPIRED: Final[int] + EKEYREJECTED: Final[int] + EKEYREVOKED: Final[int] + EMEDIUMTYPE: Final[int] + ENOKEY: Final[int] + ENOMEDIUM: Final[int] + ERFKILL: Final[int] + + if sys.version_info >= (3, 14): + EHWPOISON: Final[int] + +if sys.platform == "win32": + # All of these are undocumented + WSABASEERR: Final[int] + WSAEACCES: Final[int] + WSAEADDRINUSE: Final[int] + WSAEADDRNOTAVAIL: Final[int] + WSAEAFNOSUPPORT: Final[int] + WSAEALREADY: Final[int] + WSAEBADF: Final[int] + WSAECONNABORTED: Final[int] + WSAECONNREFUSED: Final[int] + WSAECONNRESET: Final[int] + WSAEDESTADDRREQ: Final[int] + WSAEDISCON: Final[int] + WSAEDQUOT: Final[int] + WSAEFAULT: Final[int] + WSAEHOSTDOWN: Final[int] + WSAEHOSTUNREACH: Final[int] + WSAEINPROGRESS: Final[int] + WSAEINTR: Final[int] + WSAEINVAL: Final[int] + WSAEISCONN: Final[int] + WSAELOOP: Final[int] + WSAEMFILE: Final[int] + WSAEMSGSIZE: Final[int] + WSAENAMETOOLONG: Final[int] + WSAENETDOWN: Final[int] + WSAENETRESET: Final[int] + WSAENETUNREACH: Final[int] + WSAENOBUFS: Final[int] + WSAENOPROTOOPT: Final[int] + WSAENOTCONN: Final[int] + WSAENOTEMPTY: Final[int] + WSAENOTSOCK: Final[int] + WSAEOPNOTSUPP: Final[int] + WSAEPFNOSUPPORT: Final[int] + WSAEPROCLIM: Final[int] + WSAEPROTONOSUPPORT: Final[int] + WSAEPROTOTYPE: Final[int] + WSAEREMOTE: Final[int] + WSAESHUTDOWN: Final[int] + WSAESOCKTNOSUPPORT: Final[int] + WSAESTALE: Final[int] + WSAETIMEDOUT: Final[int] + WSAETOOMANYREFS: Final[int] + WSAEUSERS: Final[int] + WSAEWOULDBLOCK: Final[int] + WSANOTINITIALISED: Final[int] + WSASYSNOTREADY: Final[int] + WSAVERNOTSUPPORTED: Final[int] diff --git a/stdlib/faulthandler.pyi b/stdlib/faulthandler.pyi index 7b42b8ec8444..6999933c43b9 100644 --- a/stdlib/faulthandler.pyi +++ b/stdlib/faulthandler.pyi @@ -3,11 +3,59 @@ from _typeshed import FileDescriptorLike def cancel_dump_traceback_later() -> None: ... def disable() -> None: ... -def dump_traceback(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: ... -def dump_traceback_later(timeout: float, repeat: bool = ..., file: FileDescriptorLike = ..., exit: bool = ...) -> None: ... -def enable(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: ... + +if sys.version_info >= (3, 15): + def dump_traceback( + file: FileDescriptorLike = sys.stderr, all_threads: bool = True, *, max_threads: int | None = None + ) -> None: ... + +else: + def dump_traceback(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ... + +if sys.version_info >= (3, 14): + def dump_c_stack(file: FileDescriptorLike = sys.stderr) -> None: ... + +if sys.version_info >= (3, 15): + def dump_traceback_later( + timeout: float, + repeat: bool = False, + file: FileDescriptorLike = sys.stderr, + exit: bool = False, + *, + max_threads: int | None = None, + ) -> None: ... + +else: + def dump_traceback_later( + timeout: float, repeat: bool = False, file: FileDescriptorLike = sys.stderr, exit: bool = False + ) -> None: ... + +if sys.version_info >= (3, 15): + def enable( + file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True, *, max_threads: int | None = None + ) -> None: ... + +elif sys.version_info >= (3, 14): + def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True) -> None: ... + +else: + def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ... + def is_enabled() -> bool: ... if sys.platform != "win32": - def register(signum: int, file: FileDescriptorLike = ..., all_threads: bool = ..., chain: bool = ...) -> None: ... - def unregister(signum: int) -> None: ... + if sys.version_info >= (3, 15): + def register( + signum: int, + file: FileDescriptorLike = sys.stderr, + all_threads: bool = True, + chain: bool = False, + *, + max_threads: int | None = None, + ) -> None: ... + else: + def register( + signum: int, file: FileDescriptorLike = sys.stderr, all_threads: bool = True, chain: bool = False + ) -> None: ... + + def unregister(signum: int, /) -> None: ... diff --git a/stdlib/fcntl.pyi b/stdlib/fcntl.pyi index 141f9ee9360a..dff4ae50277d 100644 --- a/stdlib/fcntl.pyi +++ b/stdlib/fcntl.pyi @@ -1,96 +1,160 @@ import sys from _typeshed import FileDescriptorLike, ReadOnlyBuffer, WriteableBuffer -from typing import Any, overload -from typing_extensions import Literal +from typing import Any, Final, Literal, overload +from typing_extensions import Buffer -FASYNC: int -FD_CLOEXEC: int -DN_ACCESS: int -DN_ATTRIB: int -DN_CREATE: int -DN_DELETE: int -DN_MODIFY: int -DN_MULTISHOT: int -DN_RENAME: int -F_DUPFD: int -F_DUPFD_CLOEXEC: int -F_FULLFSYNC: int -F_EXLCK: int -F_GETFD: int -F_GETFL: int -F_GETLEASE: int -F_GETLK: int -F_GETLK64: int -F_GETOWN: int -F_NOCACHE: int -F_GETSIG: int -F_NOTIFY: int -F_RDLCK: int -F_SETFD: int -F_SETFL: int -F_SETLEASE: int -F_SETLK: int -F_SETLK64: int -F_SETLKW: int -F_SETLKW64: int -if sys.version_info >= (3, 9) and sys.platform == "linux": - F_OFD_GETLK: int - F_OFD_SETLK: int - F_OFD_SETLKW: int -F_SETOWN: int -F_SETSIG: int -F_SHLCK: int -F_UNLCK: int -F_WRLCK: int -I_ATMARK: int -I_CANPUT: int -I_CKBAND: int -I_FDINSERT: int -I_FIND: int -I_FLUSH: int -I_FLUSHBAND: int -I_GETBAND: int -I_GETCLTIME: int -I_GETSIG: int -I_GRDOPT: int -I_GWROPT: int -I_LINK: int -I_LIST: int -I_LOOK: int -I_NREAD: int -I_PEEK: int -I_PLINK: int -I_POP: int -I_PUNLINK: int -I_PUSH: int -I_RECVFD: int -I_SENDFD: int -I_SETCLTIME: int -I_SETSIG: int -I_SRDOPT: int -I_STR: int -I_SWROPT: int -I_UNLINK: int -LOCK_EX: int -LOCK_MAND: int -LOCK_NB: int -LOCK_READ: int -LOCK_RW: int -LOCK_SH: int -LOCK_UN: int -LOCK_WRITE: int +if sys.platform != "win32": + FASYNC: Final[int] + FD_CLOEXEC: Final[int] + F_DUPFD: Final[int] + F_DUPFD_CLOEXEC: Final[int] + F_GETFD: Final[int] + F_GETFL: Final[int] + F_GETLK: Final[int] + F_GETOWN: Final[int] + F_RDLCK: Final[int] + F_SETFD: Final[int] + F_SETFL: Final[int] + F_SETLK: Final[int] + F_SETLKW: Final[int] + F_SETOWN: Final[int] + F_UNLCK: Final[int] + F_WRLCK: Final[int] -@overload -def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = ...) -> int: ... -@overload -def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: bytes) -> bytes: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: int = ..., __mutate_flag: bool = ...) -> int: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[True] = ...) -> int: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[False]) -> bytes: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: ReadOnlyBuffer, __mutate_flag: bool = ...) -> bytes: ... -def flock(__fd: FileDescriptorLike, __operation: int) -> None: ... -def lockf(__fd: FileDescriptorLike, __cmd: int, __len: int = ..., __start: int = ..., __whence: int = ...) -> Any: ... + F_GETLEASE: Final[int] + F_SETLEASE: Final[int] + if sys.platform == "darwin": + F_FULLFSYNC: Final[int] + F_NOCACHE: Final[int] + F_GETPATH: Final[int] + if sys.platform == "linux": + F_SETLKW64: Final[int] + F_SETSIG: Final[int] + F_SHLCK: Final[int] + F_SETLK64: Final[int] + F_GETSIG: Final[int] + F_NOTIFY: Final[int] + F_EXLCK: Final[int] + F_GETLK64: Final[int] + F_ADD_SEALS: Final[int] + F_GET_SEALS: Final[int] + F_SEAL_GROW: Final[int] + F_SEAL_SEAL: Final[int] + F_SEAL_SHRINK: Final[int] + F_SEAL_WRITE: Final[int] + F_OFD_GETLK: Final[int] + F_OFD_SETLK: Final[int] + F_OFD_SETLKW: Final[int] + F_GETPIPE_SZ: Final[int] + F_SETPIPE_SZ: Final[int] + DN_ACCESS: Final[int] + DN_ATTRIB: Final[int] + DN_CREATE: Final[int] + DN_DELETE: Final[int] + DN_MODIFY: Final[int] + DN_MULTISHOT: Final[int] + DN_RENAME: Final[int] + + LOCK_EX: Final[int] + LOCK_NB: Final[int] + LOCK_SH: Final[int] + LOCK_UN: Final[int] + if sys.platform == "linux": + LOCK_MAND: Final[int] + LOCK_READ: Final[int] + LOCK_RW: Final[int] + LOCK_WRITE: Final[int] + + if sys.platform == "linux": + # Constants for the POSIX STREAMS interface. Present in glibc until 2.29 (released February 2019). + # Never implemented on BSD, and considered "obsolescent" starting in POSIX 2008. + # Probably still used on Solaris. + I_ATMARK: Final[int] + I_CANPUT: Final[int] + I_CKBAND: Final[int] + I_FDINSERT: Final[int] + I_FIND: Final[int] + I_FLUSH: Final[int] + I_FLUSHBAND: Final[int] + I_GETBAND: Final[int] + I_GETCLTIME: Final[int] + I_GETSIG: Final[int] + I_GRDOPT: Final[int] + I_GWROPT: Final[int] + I_LINK: Final[int] + I_LIST: Final[int] + I_LOOK: Final[int] + I_NREAD: Final[int] + I_PEEK: Final[int] + I_PLINK: Final[int] + I_POP: Final[int] + I_PUNLINK: Final[int] + I_PUSH: Final[int] + I_RECVFD: Final[int] + I_SENDFD: Final[int] + I_SETCLTIME: Final[int] + I_SETSIG: Final[int] + I_SRDOPT: Final[int] + I_STR: Final[int] + I_SWROPT: Final[int] + I_UNLINK: Final[int] + + if sys.version_info >= (3, 12) and sys.platform == "linux": + FICLONE: Final[int] + FICLONERANGE: Final[int] + + if sys.version_info >= (3, 13) and sys.platform == "linux": + F_OWNER_TID: Final = 0 + F_OWNER_PID: Final = 1 + F_OWNER_PGRP: Final = 2 + F_SETOWN_EX: Final = 15 + F_GETOWN_EX: Final = 16 + F_SEAL_FUTURE_WRITE: Final = 16 + F_GET_RW_HINT: Final = 1035 + F_SET_RW_HINT: Final = 1036 + F_GET_FILE_RW_HINT: Final = 1037 + F_SET_FILE_RW_HINT: Final = 1038 + RWH_WRITE_LIFE_NOT_SET: Final = 0 + RWH_WRITE_LIFE_NONE: Final = 1 + RWH_WRITE_LIFE_SHORT: Final = 2 + RWH_WRITE_LIFE_MEDIUM: Final = 3 + RWH_WRITE_LIFE_LONG: Final = 4 + RWH_WRITE_LIFE_EXTREME: Final = 5 + + if sys.version_info >= (3, 14) and sys.platform == "linux": + F_DUPFD_QUERY: Final[int] + + if sys.version_info >= (3, 11) and sys.platform == "darwin": + F_OFD_SETLK: Final = 90 + F_OFD_SETLKW: Final = 91 + F_OFD_GETLK: Final = 92 + + if sys.version_info >= (3, 13) and sys.platform != "linux": + # OSx and NetBSD + F_GETNOSIGPIPE: Final[int] + F_SETNOSIGPIPE: Final[int] + # OSx and FreeBSD + F_RDAHEAD: Final[int] + + @overload + def fcntl(fd: FileDescriptorLike, cmd: int, arg: int = 0, /) -> int: ... + @overload + def fcntl(fd: FileDescriptorLike, cmd: int, arg: str | ReadOnlyBuffer, /) -> bytes: ... + + # If arg is an int, return int + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: int = 0, mutate_flag: bool = True, /) -> int: ... + # The return type works as follows: + # - If arg is a read-write buffer, return int if mutate_flag is True, otherwise bytes + # - If arg is a read-only buffer, return bytes (and ignore the value of mutate_flag) + # We can't represent that precisely as we can't distinguish between read-write and read-only + # buffers, so we add overloads for a few unambiguous cases and use Any for the rest. + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: bytes, mutate_flag: bool = True, /) -> bytes: ... + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: WriteableBuffer, mutate_flag: Literal[False], /) -> bytes: ... + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: Buffer, mutate_flag: bool = True, /) -> Any: ... + + def flock(fd: FileDescriptorLike, operation: int, /) -> None: ... + def lockf(fd: FileDescriptorLike, cmd: int, len: int = 0, start: int = 0, whence: int = 0, /) -> Any: ... diff --git a/stdlib/filecmp.pyi b/stdlib/filecmp.pyi index 1c3d0a142a33..651fe2bd958b 100644 --- a/stdlib/filecmp.pyi +++ b/stdlib/filecmp.pyi @@ -1,28 +1,40 @@ import sys -from _typeshed import StrOrBytesPath -from os import PathLike -from typing import Any, AnyStr, Callable, Generic, Iterable, Sequence +from _typeshed import GenericPath, StrOrBytesPath +from collections.abc import Callable, Iterable, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Final, Generic, Literal -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["clear_cache", "cmp", "dircmp", "cmpfiles", "DEFAULT_IGNORES"] -DEFAULT_IGNORES: list[str] +DEFAULT_IGNORES: Final[list[str]] +BUFSIZE: Final = 8192 -def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: int | bool = ...) -> bool: ... +def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] = True) -> bool: ... def cmpfiles( - a: AnyStr | PathLike[AnyStr], b: AnyStr | PathLike[AnyStr], common: Iterable[AnyStr], shallow: int | bool = ... + a: GenericPath[AnyStr], b: GenericPath[AnyStr], common: Iterable[GenericPath[AnyStr]], shallow: bool | Literal[0, 1] = True ) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ... class dircmp(Generic[AnyStr]): - def __init__( - self, - a: AnyStr | PathLike[AnyStr], - b: AnyStr | PathLike[AnyStr], - ignore: Sequence[AnyStr] | None = ..., - hide: Sequence[AnyStr] | None = ..., - ) -> None: ... - left: AnyStr - right: AnyStr + if sys.version_info >= (3, 13): + def __init__( + self, + a: GenericPath[AnyStr], + b: GenericPath[AnyStr], + ignore: Sequence[AnyStr] | None = None, + hide: Sequence[AnyStr] | None = None, + *, + shallow: bool = True, + ) -> None: ... + else: + def __init__( + self, + a: GenericPath[AnyStr], + b: GenericPath[AnyStr], + ignore: Sequence[AnyStr] | None = None, + hide: Sequence[AnyStr] | None = None, + ) -> None: ... + left: GenericPath[AnyStr] + right: GenericPath[AnyStr] hide: Sequence[AnyStr] ignore: Sequence[AnyStr] # These properties are created at runtime by __getattr__ @@ -48,7 +60,6 @@ class dircmp(Generic[AnyStr]): def phase3(self) -> None: ... def phase4(self) -> None: ... def phase4_closure(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def clear_cache() -> None: ... diff --git a/stdlib/fileinput.pyi b/stdlib/fileinput.pyi index 576822059560..37783254c70f 100644 --- a/stdlib/fileinput.pyi +++ b/stdlib/fileinput.pyi @@ -1,41 +1,69 @@ import sys -from _typeshed import Self, StrOrBytesPath -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator +from _typeshed import AnyStr_co, StrOrBytesPath +from collections.abc import Callable, Iterable +from types import GenericAlias, TracebackType +from typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = [ + "input", + "close", + "nextfile", + "filename", + "lineno", + "filelineno", + "fileno", + "isfirstline", + "isstdin", + "FileInput", + "hook_compressed", + "hook_encoded", +] -if sys.version_info >= (3, 10): - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., - inplace: bool = ..., - backup: str = ..., - *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> FileInput[AnyStr]: ... +if sys.version_info >= (3, 11): + _TextMode: TypeAlias = Literal["r"] +else: + _TextMode: TypeAlias = Literal["r", "rU", "U"] -elif sys.version_info >= (3, 8): - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., - inplace: bool = ..., - backup: str = ..., - *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - ) -> FileInput[AnyStr]: ... +@type_check_only +class _HasReadlineAndFileno(Protocol[AnyStr_co]): + def readline(self) -> AnyStr_co: ... + def fileno(self) -> int: ... -else: - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., - inplace: bool = ..., - backup: str = ..., - bufsize: int = ..., - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - ) -> FileInput[AnyStr]: ... +# encoding and errors are added +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: _TextMode = "r", + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, + encoding: str | None = None, + errors: str | None = None, +) -> FileInput[str]: ... +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, + encoding: None = None, + errors: None = None, +) -> FileInput[bytes]: ... +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, + encoding: str | None = None, + errors: str | None = None, +) -> FileInput[Any]: ... def close() -> None: ... def nextfile() -> None: ... @@ -46,47 +74,56 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Iterable[AnyStr], Generic[AnyStr]): - if sys.version_info >= (3, 10): - def __init__( - self, - files: None | StrOrBytesPath | Iterable[StrOrBytesPath] = ..., - inplace: bool = ..., - backup: str = ..., - *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> None: ... - elif sys.version_info >= (3, 8): - def __init__( - self, - files: None | StrOrBytesPath | Iterable[StrOrBytesPath] = ..., - inplace: bool = ..., - backup: str = ..., - *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - ) -> None: ... - else: - def __init__( - self, - files: None | StrOrBytesPath | Iterable[StrOrBytesPath] = ..., - inplace: bool = ..., - backup: str = ..., - bufsize: int = ..., - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - ) -> None: ... +class FileInput(Generic[AnyStr]): + # encoding and errors are added + @overload + def __init__( + self: FileInput[str], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: _TextMode = "r", + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, + encoding: str | None = None, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: FileInput[bytes], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, + encoding: None = None, + errors: None = None, + ) -> None: ... + @overload + def __init__( + self: FileInput[Any], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, + encoding: str | None = None, + errors: str | None = None, + ) -> None: ... + def __del__(self) -> None: ... def close(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Self: ... def __next__(self) -> AnyStr: ... if sys.version_info < (3, 11): def __getitem__(self, i: int) -> AnyStr: ... + def nextfile(self) -> None: ... def readline(self) -> AnyStr: ... def filename(self) -> str: ... @@ -95,15 +132,10 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): def fileno(self) -> int: ... def isfirstline(self) -> bool: ... def isstdin(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -if sys.version_info >= (3, 10): - def hook_compressed( - filename: StrOrBytesPath, mode: str, *, encoding: str | None = ..., errors: str | None = ... - ) -> IO[Any]: ... - -else: - def hook_compressed(filename: StrOrBytesPath, mode: str) -> IO[Any]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -def hook_encoded(encoding: str, errors: str | None = ...) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... +def hook_compressed( + filename: StrOrBytesPath, mode: str, *, encoding: str | None = None, errors: str | None = None +) -> IO[Any]: ... +@deprecated("Deprecated since Python 3.10. Use `fileinput.input` or `fileinput.FileInput` instead.") +def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... diff --git a/stdlib/fnmatch.pyi b/stdlib/fnmatch.pyi index 1cbcf00729ed..018139dc482b 100644 --- a/stdlib/fnmatch.pyi +++ b/stdlib/fnmatch.pyi @@ -1,6 +1,16 @@ -from typing import AnyStr, Iterable +import sys +from collections.abc import Iterable +from os import PathLike +from typing import AnyStr -def fnmatch(name: AnyStr, pat: AnyStr) -> bool: ... +__all__ = ["filter", "fnmatch", "fnmatchcase", "translate"] +if sys.version_info >= (3, 14): + __all__ += ["filterfalse"] + +def fnmatch(name: AnyStr | PathLike[AnyStr], pat: AnyStr | PathLike[AnyStr]) -> bool: ... def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ... -def filter(names: Iterable[AnyStr], pat: AnyStr) -> list[AnyStr]: ... +def filter(names: Iterable[AnyStr | PathLike[AnyStr]], pat: AnyStr | PathLike[AnyStr]) -> list[AnyStr]: ... def translate(pat: str) -> str: ... + +if sys.version_info >= (3, 14): + def filterfalse(names: Iterable[AnyStr | PathLike[AnyStr]], pat: AnyStr | PathLike[AnyStr]) -> list[AnyStr]: ... diff --git a/stdlib/formatter.pyi b/stdlib/formatter.pyi deleted file mode 100644 index 7c3b97688dbd..000000000000 --- a/stdlib/formatter.pyi +++ /dev/null @@ -1,103 +0,0 @@ -from typing import IO, Any, Iterable, Tuple - -AS_IS: None -_FontType = Tuple[str, bool, bool, bool] -_StylesType = Tuple[Any, ...] - -class NullFormatter: - writer: NullWriter | None - def __init__(self, writer: NullWriter | None = ...) -> None: ... - def end_paragraph(self, blankline: int) -> None: ... - def add_line_break(self) -> None: ... - def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def add_label_data(self, format: str, counter: int, blankline: int | None = ...) -> None: ... - def add_flowing_data(self, data: str) -> None: ... - def add_literal_data(self, data: str) -> None: ... - def flush_softspace(self) -> None: ... - def push_alignment(self, align: str | None) -> None: ... - def pop_alignment(self) -> None: ... - def push_font(self, x: _FontType) -> None: ... - def pop_font(self) -> None: ... - def push_margin(self, margin: int) -> None: ... - def pop_margin(self) -> None: ... - def set_spacing(self, spacing: str | None) -> None: ... - def push_style(self, *styles: _StylesType) -> None: ... - def pop_style(self, n: int = ...) -> None: ... - def assert_line_data(self, flag: int = ...) -> None: ... - -class AbstractFormatter: - writer: NullWriter - align: str | None - align_stack: list[str | None] - font_stack: list[_FontType] - margin_stack: list[int] - spacing: str | None - style_stack: Any - nospace: int - softspace: int - para_end: int - parskip: int - hard_break: int - have_label: int - def __init__(self, writer: NullWriter) -> None: ... - def end_paragraph(self, blankline: int) -> None: ... - def add_line_break(self) -> None: ... - def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def add_label_data(self, format: str, counter: int, blankline: int | None = ...) -> None: ... - def format_counter(self, format: Iterable[str], counter: int) -> str: ... - def format_letter(self, case: str, counter: int) -> str: ... - def format_roman(self, case: str, counter: int) -> str: ... - def add_flowing_data(self, data: str) -> None: ... - def add_literal_data(self, data: str) -> None: ... - def flush_softspace(self) -> None: ... - def push_alignment(self, align: str | None) -> None: ... - def pop_alignment(self) -> None: ... - def push_font(self, font: _FontType) -> None: ... - def pop_font(self) -> None: ... - def push_margin(self, margin: int) -> None: ... - def pop_margin(self) -> None: ... - def set_spacing(self, spacing: str | None) -> None: ... - def push_style(self, *styles: _StylesType) -> None: ... - def pop_style(self, n: int = ...) -> None: ... - def assert_line_data(self, flag: int = ...) -> None: ... - -class NullWriter: - def __init__(self) -> None: ... - def flush(self) -> None: ... - def new_alignment(self, align: str | None) -> None: ... - def new_font(self, font: _FontType) -> None: ... - def new_margin(self, margin: int, level: int) -> None: ... - def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_label_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - def send_literal_data(self, data: str) -> None: ... - -class AbstractWriter(NullWriter): - def new_alignment(self, align: str | None) -> None: ... - def new_font(self, font: _FontType) -> None: ... - def new_margin(self, margin: int, level: int) -> None: ... - def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_label_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - def send_literal_data(self, data: str) -> None: ... - -class DumbWriter(NullWriter): - file: IO[str] - maxcol: int - def __init__(self, file: IO[str] | None = ..., maxcol: int = ...) -> None: ... - def reset(self) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_literal_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - -def test(file: str | None = ...) -> None: ... diff --git a/stdlib/fractions.pyi b/stdlib/fractions.pyi index 8de5ae20971c..42947f2e2266 100644 --- a/stdlib/fractions.pyi +++ b/stdlib/fractions.pyi @@ -1,141 +1,178 @@ import sys +from collections.abc import Callable from decimal import Decimal -from numbers import Integral, Rational, Real -from typing import Type, TypeVar, Union, overload -from typing_extensions import Literal +from numbers import Rational, Real +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self -_ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") +_ComparableNum: TypeAlias = int | float | Decimal | Real -if sys.version_info < (3, 9): - @overload - def gcd(a: int, b: int) -> int: ... - @overload - def gcd(a: Integral, b: int) -> Integral: ... - @overload - def gcd(a: int, b: Integral) -> Integral: ... - @overload - def gcd(a: Integral, b: Integral) -> Integral: ... +__all__ = ["Fraction"] + +@type_check_only +class _ConvertibleToIntegerRatio(Protocol): + def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ... class Fraction(Rational): + __slots__ = ("_numerator", "_denominator") + @overload - def __new__( - cls: Type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... + def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: ... @overload - def __new__(cls: Type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... + def __new__(cls, numerator: float | Decimal | str) -> Self: ... + if sys.version_info >= (3, 14): + @overload + def __new__(cls, numerator: _ConvertibleToIntegerRatio) -> Self: ... + @classmethod - def from_float(cls, f: float) -> Fraction: ... + def from_float(cls, f: float) -> Self: ... @classmethod - def from_decimal(cls, dec: Decimal) -> Fraction: ... - def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... - if sys.version_info >= (3, 8): - def as_integer_ratio(self) -> tuple[int, int]: ... + def from_decimal(cls, dec: Decimal) -> Self: ... + def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: ... + def as_integer_ratio(self) -> tuple[int, int]: ... + if sys.version_info >= (3, 12): + def is_integer(self) -> bool: ... + @property - def numerator(self) -> int: ... + def numerator(a) -> int: ... @property - def denominator(self) -> int: ... - @overload - def __add__(self, other: int | Fraction) -> Fraction: ... - @overload - def __add__(self, other: float) -> float: ... - @overload - def __add__(self, other: complex) -> complex: ... - @overload - def __radd__(self, other: int | Fraction) -> Fraction: ... - @overload - def __radd__(self, other: float) -> float: ... + def denominator(a) -> int: ... + @overload - def __radd__(self, other: complex) -> complex: ... + def __add__(a, b: int | Fraction) -> Fraction: ... @overload - def __sub__(self, other: int | Fraction) -> Fraction: ... + def __add__(a, b: float) -> float: ... @overload - def __sub__(self, other: float) -> float: ... + def __add__(a, b: complex) -> complex: ... + @overload - def __sub__(self, other: complex) -> complex: ... + def __radd__(b, a: int | Fraction) -> Fraction: ... @overload - def __rsub__(self, other: int | Fraction) -> Fraction: ... + def __radd__(b, a: float) -> float: ... @overload - def __rsub__(self, other: float) -> float: ... + def __radd__(b, a: complex) -> complex: ... + @overload - def __rsub__(self, other: complex) -> complex: ... + def __sub__(a, b: int | Fraction) -> Fraction: ... @overload - def __mul__(self, other: int | Fraction) -> Fraction: ... + def __sub__(a, b: float) -> float: ... @overload - def __mul__(self, other: float) -> float: ... + def __sub__(a, b: complex) -> complex: ... + @overload - def __mul__(self, other: complex) -> complex: ... + def __rsub__(b, a: int | Fraction) -> Fraction: ... @overload - def __rmul__(self, other: int | Fraction) -> Fraction: ... + def __rsub__(b, a: float) -> float: ... @overload - def __rmul__(self, other: float) -> float: ... + def __rsub__(b, a: complex) -> complex: ... + @overload - def __rmul__(self, other: complex) -> complex: ... + def __mul__(a, b: int | Fraction) -> Fraction: ... @overload - def __truediv__(self, other: int | Fraction) -> Fraction: ... + def __mul__(a, b: float) -> float: ... @overload - def __truediv__(self, other: float) -> float: ... + def __mul__(a, b: complex) -> complex: ... + @overload - def __truediv__(self, other: complex) -> complex: ... + def __rmul__(b, a: int | Fraction) -> Fraction: ... @overload - def __rtruediv__(self, other: int | Fraction) -> Fraction: ... + def __rmul__(b, a: float) -> float: ... @overload - def __rtruediv__(self, other: float) -> float: ... + def __rmul__(b, a: complex) -> complex: ... + @overload - def __rtruediv__(self, other: complex) -> complex: ... + def __truediv__(a, b: int | Fraction) -> Fraction: ... @overload - def __floordiv__(self, other: int | Fraction) -> int: ... + def __truediv__(a, b: float) -> float: ... @overload - def __floordiv__(self, other: float) -> float: ... + def __truediv__(a, b: complex) -> complex: ... + @overload - def __rfloordiv__(self, other: int | Fraction) -> int: ... + def __rtruediv__(b, a: int | Fraction) -> Fraction: ... @overload - def __rfloordiv__(self, other: float) -> float: ... + def __rtruediv__(b, a: float) -> float: ... @overload - def __mod__(self, other: int | Fraction) -> Fraction: ... + def __rtruediv__(b, a: complex) -> complex: ... + @overload - def __mod__(self, other: float) -> float: ... + def __floordiv__(a, b: int | Fraction) -> int: ... @overload - def __rmod__(self, other: int | Fraction) -> Fraction: ... + def __floordiv__(a, b: float) -> float: ... + @overload - def __rmod__(self, other: float) -> float: ... + def __rfloordiv__(b, a: int | Fraction) -> int: ... @overload - def __divmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... + def __rfloordiv__(b, a: float) -> float: ... + @overload - def __divmod__(self, other: float) -> tuple[float, Fraction]: ... + def __mod__(a, b: int | Fraction) -> Fraction: ... @overload - def __rdivmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... + def __mod__(a, b: float) -> float: ... + @overload - def __rdivmod__(self, other: float) -> tuple[float, Fraction]: ... + def __rmod__(b, a: int | Fraction) -> Fraction: ... @overload - def __pow__(self, other: int) -> Fraction: ... + def __rmod__(b, a: float) -> float: ... + @overload - def __pow__(self, other: float | Fraction) -> float: ... + def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __pow__(self, other: complex) -> complex: ... + def __divmod__(a, b: float) -> tuple[float, Fraction]: ... + @overload - def __rpow__(self, other: int | float | Fraction) -> float: ... + def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __rpow__(self, other: complex) -> complex: ... - def __pos__(self) -> Fraction: ... - def __neg__(self) -> Fraction: ... - def __abs__(self) -> Fraction: ... - def __trunc__(self) -> int: ... - def __floor__(self) -> int: ... - def __ceil__(self) -> int: ... + def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ... + + if sys.version_info >= (3, 14): + @overload + def __pow__(a, b: int, modulo: None = None) -> Fraction: ... + @overload + def __pow__(a, b: float | Fraction, modulo: None = None) -> float: ... + @overload + def __pow__(a, b: complex, modulo: None = None) -> complex: ... + else: + @overload + def __pow__(a, b: int) -> Fraction: ... + @overload + def __pow__(a, b: float | Fraction) -> float: ... + @overload + def __pow__(a, b: complex) -> complex: ... + + if sys.version_info >= (3, 14): + @overload + def __rpow__(b, a: float | Fraction, modulo: None = None) -> float: ... + @overload + def __rpow__(b, a: complex, modulo: None = None) -> complex: ... + else: + @overload + def __rpow__(b, a: float | Fraction) -> float: ... + @overload + def __rpow__(b, a: complex) -> complex: ... + + def __pos__(a) -> Fraction: ... + def __neg__(a) -> Fraction: ... + def __abs__(a) -> Fraction: ... + def __trunc__(a) -> int: ... + def __floor__(a) -> int: ... + def __ceil__(a) -> int: ... + @overload - def __round__(self, ndigits: None = ...) -> int: ... + def __round__(self, ndigits: None = None) -> int: ... @overload def __round__(self, ndigits: int) -> Fraction: ... - def __hash__(self) -> int: ... - def __eq__(self, other: object) -> bool: ... - def __lt__(self, other: _ComparableNum) -> bool: ... - def __gt__(self, other: _ComparableNum) -> bool: ... - def __le__(self, other: _ComparableNum) -> bool: ... - def __ge__(self, other: _ComparableNum) -> bool: ... - def __bool__(self) -> bool: ... + + def __hash__(self) -> int: ... # type: ignore[override] + def __eq__(a, b: object) -> bool: ... + def __lt__(a, b: _ComparableNum) -> bool: ... + def __gt__(a, b: _ComparableNum) -> bool: ... + def __le__(a, b: _ComparableNum) -> bool: ... + def __ge__(a, b: _ComparableNum) -> bool: ... + def __bool__(a) -> bool: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... if sys.version_info >= (3, 11): - def __int__(self) -> int: ... + def __int__(a, _index: Callable[[SupportsIndex], int] = ...) -> int: ... # Not actually defined within fractions.py, but provides more useful # overrides @property @@ -143,3 +180,6 @@ class Fraction(Rational): @property def imag(self) -> Literal[0]: ... def conjugate(self) -> Fraction: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: float | Rational | _ConvertibleToIntegerRatio) -> Self: ... diff --git a/stdlib/ftplib.pyi b/stdlib/ftplib.pyi index 745669ce0f18..1b7222fc94f7 100644 --- a/stdlib/ftplib.pyi +++ b/stdlib/ftplib.pyi @@ -1,16 +1,19 @@ import sys -from _typeshed import Self, SupportsRead, SupportsReadline +from _typeshed import StrOrBytesPath, SupportsRead, SupportsReadline +from collections.abc import Callable, Iterable, Iterator from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Callable, Iterable, Iterator, TextIO, Tuple, Type -from typing_extensions import Literal +from typing import Any, Final, Literal, TextIO, overload +from typing_extensions import Self, deprecated -MSG_OOB: int -FTP_PORT: int -MAXLINE: int -CRLF: str -B_CRLF: bytes +__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors", "FTP_TLS"] + +MSG_OOB: Final = 1 +FTP_PORT: Final = 21 +MAXLINE: Final = 8192 +CRLF: Final = "\r\n" +B_CRLF: Final = b"\r\n" class Error(Exception): ... class error_reply(Error): ... @@ -18,7 +21,7 @@ class error_temp(Error): ... class error_perm(Error): ... class error_proto(Error): ... -all_errors: Tuple[Type[Exception], ...] +all_errors: tuple[type[Exception], ...] class FTP: debugging: int @@ -28,45 +31,34 @@ class FTP: sock: socket | None welcome: str | None passiveserver: int - timeout: int + timeout: float | None af: int lastresp: str file: TextIO | None encoding: str - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... source_address: tuple[str, int] | None - if sys.version_info >= (3, 9): - def __init__( - self, - host: str = ..., - user: str = ..., - passwd: str = ..., - acct: str = ..., - timeout: float = ..., - source_address: tuple[str, int] | None = ..., - *, - encoding: str = ..., - ) -> None: ... - else: - def __init__( - self, - host: str = ..., - user: str = ..., - passwd: str = ..., - acct: str = ..., - timeout: float = ..., - source_address: tuple[str, int] | None = ..., - ) -> None: ... + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", + ) -> None: ... def connect( - self, host: str = ..., port: int = ..., timeout: float = ..., source_address: tuple[str, int] | None = ... + self, host: str = "", port: int = 0, timeout: float = -999, source_address: tuple[str, int] | None = None ) -> str: ... def getwelcome(self) -> str: ... def set_debuglevel(self, level: int) -> None: ... def debug(self, level: int) -> None: ... - def set_pasv(self, val: bool | int) -> None: ... + def set_pasv(self, val: bool | Literal[0, 1]) -> None: ... def sanitize(self, s: str) -> str: ... def putline(self, line: str) -> None: ... def putcmd(self, line: str) -> None: ... @@ -81,28 +73,28 @@ class FTP: def sendeprt(self, host: str, port: int) -> str: ... def makeport(self) -> socket: ... def makepasv(self) -> tuple[str, int]: ... - def login(self, user: str = ..., passwd: str = ..., acct: str = ...) -> str: ... - # In practice, `rest` rest can actually be anything whose str() is an integer sequence, so to make it simple we allow integers. - def ntransfercmd(self, cmd: str, rest: int | str | None = ...) -> tuple[socket, int]: ... - def transfercmd(self, cmd: str, rest: int | str | None = ...) -> socket: ... + def login(self, user: str = "", passwd: str = "", acct: str = "") -> str: ... + # In practice, `rest` can actually be anything whose str() is an integer sequence, so to make it simple we allow integers + def ntransfercmd(self, cmd: str, rest: int | str | None = None) -> tuple[socket, int | None]: ... + def transfercmd(self, cmd: str, rest: int | str | None = None) -> socket: ... def retrbinary( - self, cmd: str, callback: Callable[[bytes], Any], blocksize: int = ..., rest: int | str | None = ... + self, cmd: str, callback: Callable[[bytes], object], blocksize: int = 8192, rest: int | str | None = None ) -> str: ... def storbinary( self, cmd: str, fp: SupportsRead[bytes], - blocksize: int = ..., - callback: Callable[[bytes], Any] | None = ..., - rest: int | str | None = ..., + blocksize: int = 8192, + callback: Callable[[bytes], object] | None = None, + rest: int | str | None = None, ) -> str: ... - def retrlines(self, cmd: str, callback: Callable[[str], Any] | None = ...) -> str: ... - def storlines(self, cmd: str, fp: SupportsReadline[bytes], callback: Callable[[bytes], Any] | None = ...) -> str: ... + def retrlines(self, cmd: str, callback: Callable[[str], object] | None = None) -> str: ... + def storlines(self, cmd: str, fp: SupportsReadline[bytes], callback: Callable[[bytes], object] | None = None) -> str: ... def acct(self, password: str) -> str: ... def nlst(self, *args: str) -> list[str]: ... # Technically only the last arg can be a Callable but ... - def dir(self, *args: str | Callable[[str], None]) -> None: ... - def mlsd(self, path: str = ..., facts: Iterable[str] = ...) -> Iterator[tuple[str, dict[str, str]]]: ... + def dir(self, *args: str | Callable[[str], object]) -> None: ... + def mlsd(self, path: str = "", facts: Iterable[str] = []) -> Iterator[tuple[str, dict[str, str]]]: ... def rename(self, fromname: str, toname: str) -> str: ... def delete(self, filename: str) -> str: ... def cwd(self, dirname: str) -> str: ... @@ -114,39 +106,60 @@ class FTP: def close(self) -> None: ... class FTP_TLS(FTP): - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 12): def __init__( self, - host: str = ..., - user: str = ..., - passwd: str = ..., - acct: str = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - context: SSLContext | None = ..., - timeout: float = ..., - source_address: tuple[str, int] | None = ..., + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", *, - encoding: str = ..., + context: SSLContext | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + encoding: str = "utf-8", ) -> None: ... else: + @overload + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + keyfile: None = None, + certfile: None = None, + context: SSLContext | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", + ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) def __init__( self, - host: str = ..., - user: str = ..., - passwd: str = ..., - acct: str = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - context: SSLContext | None = ..., - timeout: float = ..., - source_address: tuple[str, int] | None = ..., + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + context: None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", ) -> None: ... - ssl_version: int - keyfile: str | None - certfile: str | None + + ssl_version: int + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None context: SSLContext - def login(self, user: str = ..., passwd: str = ..., acct: str = ..., secure: bool = ...) -> str: ... + def login(self, user: str = "", passwd: str = "", acct: str = "", secure: bool = True) -> str: ... def auth(self) -> str: ... def prot_p(self) -> str: ... def prot_c(self) -> str: ... @@ -157,5 +170,5 @@ def parse227(resp: str) -> tuple[str, int]: ... # undocumented def parse229(resp: str, peer: Any) -> tuple[str, int]: ... # undocumented def parse257(resp: str) -> str: ... # undocumented def ftpcp( - source: FTP, sourcename: str, target: FTP, targetname: str = ..., type: Literal["A", "I"] = ... + source: FTP, sourcename: str, target: FTP, targetname: str = "", type: Literal["A", "I"] = "I" ) -> None: ... # undocumented diff --git a/stdlib/functools.pyi b/stdlib/functools.pyi index 78ed5992a468..07d0ffc7a021 100644 --- a/stdlib/functools.pyi +++ b/stdlib/functools.pyi @@ -1,131 +1,287 @@ import sys import types from _typeshed import SupportsAllComparisons, SupportsItems -from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, Tuple, Type, TypeVar, overload -from typing_extensions import final +from collections.abc import Callable, Hashable, Iterable, Sized +from types import GenericAlias +from typing import ( + Any, + Final, + Generic, + Literal, + NamedTuple, + ParamSpec, + TypeAlias, + TypedDict, + TypeVar, + final, + overload, + type_check_only, +) +from typing_extensions import Self, disjoint_base -if sys.version_info >= (3, 9): - from types import GenericAlias - -_AnyCallable = Callable[..., Any] +__all__ = [ + "update_wrapper", + "wraps", + "WRAPPER_ASSIGNMENTS", + "WRAPPER_UPDATES", + "total_ordering", + "cmp_to_key", + "lru_cache", + "reduce", + "partial", + "partialmethod", + "singledispatch", + "cached_property", + "singledispatchmethod", + "cache", +] _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) _S = TypeVar("_S") +_PWrapped = ParamSpec("_PWrapped") +_RWrapped = TypeVar("_RWrapped") +_PWrapper = ParamSpec("_PWrapper") +_RWrapper = TypeVar("_RWrapper") + +if sys.version_info >= (3, 14): + @overload + def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], /, initial: _T) -> _T: ... +else: + @overload + def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initial: _T, /) -> _T: ... @overload -def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... -@overload -def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... +def reduce(function: Callable[[_T, _T], _T], iterable: Iterable[_T], /) -> _T: ... class _CacheInfo(NamedTuple): hits: int misses: int - maxsize: int + maxsize: int | None currsize: int +@type_check_only +class _CacheParameters(TypedDict): + maxsize: int + typed: bool + @final -class _lru_cache_wrapper(Generic[_T]): - __wrapped__: Callable[..., _T] - def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... +class _lru_cache_wrapper(Generic[_T_co]): + __wrapped__: Callable[..., _T_co] + def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T_co: ... def cache_info(self) -> _CacheInfo: ... def cache_clear(self) -> None: ... + def cache_parameters(self) -> _CacheParameters: ... + def __copy__(self) -> _lru_cache_wrapper[_T_co]: ... + def __deepcopy__(self, memo: Any, /) -> _lru_cache_wrapper[_T_co]: ... -if sys.version_info >= (3, 8): - @overload - def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... - @overload - def lru_cache(maxsize: Callable[..., _T], typed: bool = ...) -> _lru_cache_wrapper[_T]: ... + # as with ``Callable``, we'll assume that these attributes exist + __name__: str + __qualname__: str +@overload +def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... +@overload +def lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ... + +if sys.version_info >= (3, 14): + WRAPPER_ASSIGNMENTS: Final[ + tuple[ + Literal["__module__"], + Literal["__name__"], + Literal["__qualname__"], + Literal["__doc__"], + Literal["__annotate__"], + Literal["__type_params__"], + ] + ] +elif sys.version_info >= (3, 12): + WRAPPER_ASSIGNMENTS: Final[ + tuple[ + Literal["__module__"], + Literal["__name__"], + Literal["__qualname__"], + Literal["__doc__"], + Literal["__annotations__"], + Literal["__type_params__"], + ] + ] else: - def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... + WRAPPER_ASSIGNMENTS: Final[ + tuple[Literal["__module__"], Literal["__name__"], Literal["__qualname__"], Literal["__doc__"], Literal["__annotations__"]] + ] + +WRAPPER_UPDATES: Final[tuple[Literal["__dict__"]]] -WRAPPER_ASSIGNMENTS: Sequence[str] -WRAPPER_UPDATES: Sequence[str] +@type_check_only +class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): + __wrapped__: Callable[_PWrapped, _RWrapped] + def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... + # as with ``Callable``, we'll assume that these attributes exist + __name__: str + __qualname__: str -def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... -def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... -def total_ordering(cls: Type[_T]) -> Type[_T]: ... +@type_check_only +class _Wrapper(Generic[_PWrapped, _RWrapped]): + def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + +if sys.version_info >= (3, 14): + def update_wrapper( + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotate__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + def wraps( + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotate__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapper[_PWrapped, _RWrapped]: ... + +elif sys.version_info >= (3, 12): + def update_wrapper( + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + def wraps( + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapper[_PWrapped, _RWrapped]: ... + +else: + def update_wrapper( + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + def wraps( + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapper[_PWrapped, _RWrapped]: ... + +def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... +@disjoint_base class partial(Generic[_T]): - func: Callable[..., _T] - args: Tuple[Any, ...] - keywords: dict[str, Any] - def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + @property + def func(self) -> Callable[..., _T]: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def keywords(self) -> dict[str, Any]: ... + def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ... + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... + if sys.version_info >= (3, 14): + @overload + def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ... + @overload + def __get__(self, instance: object, owner: type[Any] | None = None, /) -> Callable[..., _T]: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # With protocols, this could change into a generic protocol that defines __get__ and returns _T -_Descriptor = Any +_Descriptor: TypeAlias = Any class partialmethod(Generic[_T]): func: Callable[..., _T] | _Descriptor - args: Tuple[Any, ...] + args: tuple[Any, ...] keywords: dict[str, Any] - @overload - def __init__(self, __func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... - @overload - def __init__(self, __func: _Descriptor, *args: Any, **keywords: Any) -> None: ... - def __get__(self, obj: Any, cls: Type[Any]) -> Callable[..., _T]: ... + if sys.version_info >= (3, 14): + @overload + def __new__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> Self: ... + @overload + def __new__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> Self: ... + else: + @overload + def __init__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> None: ... + @overload + def __init__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> None: ... + + def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... @property def __isabstractmethod__(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 11): + _RegType: TypeAlias = type[Any] | types.UnionType +else: + _RegType: TypeAlias = type[Any] +@type_check_only class _SingleDispatchCallable(Generic[_T]): registry: types.MappingProxyType[Any, Callable[..., _T]] def dispatch(self, cls: Any) -> Callable[..., _T]: ... + # @fun.register(complex) # def _(arg, verbose=False): ... @overload - def register(self, cls: Type[Any], func: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: _RegType, func: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... # @fun.register # def _(arg: int, verbose=False): @overload - def register(self, cls: Callable[..., _T], func: None = ...) -> Callable[..., _T]: ... + def register(self, cls: Callable[..., _T], func: None = None) -> Callable[..., _T]: ... # fun.register(int, lambda x: x) @overload - def register(self, cls: Type[Any], func: Callable[..., _T]) -> Callable[..., _T]: ... + def register(self, cls: _RegType, func: Callable[..., _T]) -> Callable[..., _T]: ... + def _clear_cache(self) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... -if sys.version_info >= (3, 8): - class singledispatchmethod(Generic[_T]): - dispatcher: _SingleDispatchCallable[_T] - func: Callable[..., _T] - def __init__(self, func: Callable[..., _T]) -> None: ... - @overload - def register(self, cls: Type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... - @overload - def register(self, cls: Callable[..., _T], method: None = ...) -> Callable[..., _T]: ... - @overload - def register(self, cls: Type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... - class cached_property(Generic[_T]): - func: Callable[[Any], _T] - attrname: str | None - def __init__(self, func: Callable[[Any], _T]) -> None: ... - @overload - def __get__(self, instance: None, owner: Type[Any] | None = ...) -> cached_property[_T]: ... - @overload - def __get__(self, instance: object, owner: Type[Any] | None = ...) -> _T: ... - def __set_name__(self, owner: Type[Any], name: str) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... +class singledispatchmethod(Generic[_T]): + dispatcher: _SingleDispatchCallable[_T] + func: Callable[..., _T] + def __init__(self, func: Callable[..., _T]) -> None: ... + @property + def __isabstractmethod__(self) -> bool: ... + + @overload + def register(self, cls: _RegType, method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ... + @overload + def register(self, cls: _RegType, method: Callable[..., _T]) -> Callable[..., _T]: ... + + def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... -if sys.version_info >= (3, 9): - def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... +class cached_property(Generic[_T_co]): + func: Callable[[Any], _T_co] + attrname: str | None + def __init__(self, func: Callable[[Any], _T_co]) -> None: ... + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T_co: ... + + def __set_name__(self, owner: type[Any], name: str) -> None: ... + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T_co) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-variance] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ... def _make_key( - args: Tuple[Hashable, ...], + args: tuple[Hashable, ...], kwds: SupportsItems[Any, Any], typed: bool, - kwd_mark: Tuple[object, ...] = ..., + kwd_mark: tuple[object, ...] = ..., fasttypes: set[type] = ..., tuple: type = ..., type: Any = ..., len: Callable[[Sized], int] = ..., ) -> Hashable: ... + +if sys.version_info >= (3, 14): + @final + class _PlaceholderType: ... + + Placeholder: Final[_PlaceholderType] + + __all__ += ["Placeholder"] diff --git a/stdlib/gc.pyi b/stdlib/gc.pyi index 39d2776783ef..dc20a570cc89 100644 --- a/stdlib/gc.pyi +++ b/stdlib/gc.pyi @@ -1,40 +1,32 @@ -import sys -from typing import Any +from collections.abc import Callable +from typing import Any, Final, Literal, TypeAlias -DEBUG_COLLECTABLE: int -DEBUG_LEAK: int -DEBUG_SAVEALL: int -DEBUG_STATS: int -DEBUG_UNCOLLECTABLE: int -callbacks: list[Any] +DEBUG_COLLECTABLE: Final = 2 +DEBUG_LEAK: Final = 38 +DEBUG_SAVEALL: Final = 32 +DEBUG_STATS: Final = 1 +DEBUG_UNCOLLECTABLE: Final = 4 + +_CallbackType: TypeAlias = Callable[[Literal["start", "stop"], dict[str, int]], object] + +callbacks: list[_CallbackType] garbage: list[Any] -def collect(generation: int = ...) -> int: ... +def collect(generation: int = 2) -> int: ... def disable() -> None: ... def enable() -> None: ... def get_count() -> tuple[int, int, int]: ... def get_debug() -> int: ... - -if sys.version_info >= (3, 8): - def get_objects(generation: int | None = ...) -> list[Any]: ... - -else: - def get_objects() -> list[Any]: ... - -if sys.version_info >= (3, 7): - def freeze() -> None: ... - def unfreeze() -> None: ... - def get_freeze_count() -> int: ... - +def get_objects(generation: int | None = None) -> list[Any]: ... +def freeze() -> None: ... +def unfreeze() -> None: ... +def get_freeze_count() -> int: ... def get_referents(*objs: Any) -> list[Any]: ... def get_referrers(*objs: Any) -> list[Any]: ... def get_stats() -> list[dict[str, Any]]: ... def get_threshold() -> tuple[int, int, int]: ... -def is_tracked(__obj: Any) -> bool: ... - -if sys.version_info >= (3, 9): - def is_finalized(__obj: Any) -> bool: ... - +def is_tracked(obj: Any, /) -> bool: ... +def is_finalized(obj: Any, /) -> bool: ... def isenabled() -> bool: ... -def set_debug(__flags: int) -> None: ... -def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ...) -> None: ... +def set_debug(flags: int, /) -> None: ... +def set_threshold(threshold0: int, threshold1: int = 0, threshold2: int = 0, /) -> None: ... diff --git a/stdlib/genericpath.pyi b/stdlib/genericpath.pyi index c9829ae350f1..07c58cc496b6 100644 --- a/stdlib/genericpath.pyi +++ b/stdlib/genericpath.pyi @@ -1,29 +1,98 @@ import os -from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRichComparisonT -from typing import Sequence, Tuple, overload -from typing_extensions import Literal +import sys +from _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRichComparisonT +from collections.abc import Sequence +from typing import Literal, NewType, overload +from typing_extensions import LiteralString, deprecated + +__all__ = [ + "commonprefix", + "exists", + "getatime", + "getctime", + "getmtime", + "getsize", + "isdir", + "isfile", + "samefile", + "sameopenfile", + "samestat", + "ALLOW_MISSING", +] +if sys.version_info >= (3, 12): + __all__ += ["islink"] +if sys.version_info >= (3, 13): + __all__ += ["isjunction", "isdevdrive", "lexists"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] # All overloads can return empty string. Ideally, Literal[""] would be a valid # Iterable[T], so that list[T] | Literal[""] could be used as a return # type. But because this only works when T is str, we need Sequence[T] instead. -@overload -def commonprefix(m: Sequence[StrPath]) -> str: ... -@overload -def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... -@overload -def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ... -@overload -def commonprefix(m: Sequence[Tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... -def exists(path: StrOrBytesPath | int) -> bool: ... -def getsize(filename: StrOrBytesPath | int) -> int: ... -def isfile(path: StrOrBytesPath | int) -> bool: ... -def isdir(s: StrOrBytesPath | int) -> bool: ... +if sys.version_info >= (3, 15): + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[LiteralString], /) -> LiteralString: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[StrPath], /) -> str: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[BytesPath], /) -> bytes | Literal[""]: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[list[SupportsRichComparisonT]], /) -> Sequence[SupportsRichComparisonT]: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]], /) -> Sequence[SupportsRichComparisonT]: ... +else: + @overload + def commonprefix(m: Sequence[LiteralString]) -> LiteralString: ... + @overload + def commonprefix(m: Sequence[StrPath]) -> str: ... + @overload + def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... + @overload + def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ... + @overload + def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... + +def exists(path: FileDescriptorOrPath) -> bool: ... +def isfile(path: FileDescriptorOrPath) -> bool: ... +def isdir(s: FileDescriptorOrPath) -> bool: ... + +if sys.version_info >= (3, 12): + def islink(path: StrOrBytesPath) -> bool: ... # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: StrOrBytesPath | int) -> float: ... -def getmtime(filename: StrOrBytesPath | int) -> float: ... -def getctime(filename: StrOrBytesPath | int) -> float: ... -def samefile(f1: StrOrBytesPath | int, f2: StrOrBytesPath | int) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... -def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 15): + def getsize(filename: FileDescriptorOrPath, /) -> int: ... + def getatime(filename: FileDescriptorOrPath, /) -> float: ... + def getmtime(filename: FileDescriptorOrPath, /) -> float: ... + def getctime(filename: FileDescriptorOrPath, /) -> float: ... + def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath, /) -> bool: ... + def samestat(s1: os.stat_result, s2: os.stat_result, /) -> bool: ... + +else: + def getsize(filename: FileDescriptorOrPath) -> int: ... + def getatime(filename: FileDescriptorOrPath) -> float: ... + def getmtime(filename: FileDescriptorOrPath) -> float: ... + def getctime(filename: FileDescriptorOrPath) -> float: ... + def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath) -> bool: ... + def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 13): + def isjunction(path: StrOrBytesPath) -> bool: ... + def isdevdrive(path: StrOrBytesPath) -> bool: ... + def lexists(path: StrOrBytesPath) -> bool: ... + +# Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4 +_AllowMissingType = NewType("_AllowMissingType", object) +ALLOW_MISSING: _AllowMissingType + +if sys.version_info >= (3, 15): + _AllButLastType = NewType("_AllButLastType", object) + ALL_BUT_LAST: _AllButLastType diff --git a/stdlib/getopt.pyi b/stdlib/getopt.pyi index 6ae226f52972..c15db8122cfc 100644 --- a/stdlib/getopt.pyi +++ b/stdlib/getopt.pyi @@ -1,9 +1,27 @@ -def getopt(args: list[str], shortopts: str, longopts: list[str] = ...) -> tuple[list[tuple[str, str]], list[str]]: ... -def gnu_getopt(args: list[str], shortopts: str, longopts: list[str] = ...) -> tuple[list[tuple[str, str]], list[str]]: ... +from collections.abc import Iterable, Sequence +from typing import Protocol, TypeVar, overload, type_check_only + +_StrSequenceT_co = TypeVar("_StrSequenceT_co", covariant=True, bound=Sequence[str]) + +@type_check_only +class _SliceableT(Protocol[_StrSequenceT_co]): + @overload + def __getitem__(self, key: int, /) -> str: ... + @overload + def __getitem__(self, key: slice, /) -> _StrSequenceT_co: ... + +__all__ = ["GetoptError", "error", "getopt", "gnu_getopt"] + +def getopt( + args: _SliceableT[_StrSequenceT_co], shortopts: str, longopts: Iterable[str] | str = [] +) -> tuple[list[tuple[str, str]], _StrSequenceT_co]: ... +def gnu_getopt( + args: Sequence[str], shortopts: str, longopts: Iterable[str] | str = [] +) -> tuple[list[tuple[str, str]], list[str]]: ... class GetoptError(Exception): msg: str opt: str - def __init__(self, msg: str, opt: str = ...) -> None: ... + def __init__(self, msg: str, opt: str = "") -> None: ... error = GetoptError diff --git a/stdlib/getpass.pyi b/stdlib/getpass.pyi index 27f4c6a9b635..bb3013dfbf39 100644 --- a/stdlib/getpass.pyi +++ b/stdlib/getpass.pyi @@ -1,6 +1,14 @@ +import sys from typing import TextIO -def getpass(prompt: str = ..., stream: TextIO | None = ...) -> str: ... +__all__ = ["getpass", "getuser", "GetPassWarning"] + +if sys.version_info >= (3, 14): + def getpass(prompt: str = "Password: ", stream: TextIO | None = None, *, echo_char: str | None = None) -> str: ... + +else: + def getpass(prompt: str = "Password: ", stream: TextIO | None = None) -> str: ... + def getuser() -> str: ... class GetPassWarning(UserWarning): ... diff --git a/stdlib/gettext.pyi b/stdlib/gettext.pyi index 21be9fb1ff29..aac2d3edf7d9 100644 --- a/stdlib/gettext.pyi +++ b/stdlib/gettext.pyi @@ -1,113 +1,190 @@ +import io import sys from _typeshed import StrPath -from typing import IO, Any, Container, Iterable, Sequence, Type, TypeVar, overload -from typing_extensions import Literal +from collections.abc import Callable, Container, Iterable, Sequence +from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import deprecated + +__all__ = [ + "NullTranslations", + "GNUTranslations", + "Catalog", + "find", + "translation", + "install", + "textdomain", + "bindtextdomain", + "dgettext", + "dngettext", + "gettext", + "ngettext", + "dnpgettext", + "dpgettext", + "npgettext", + "pgettext", +] + +if sys.version_info < (3, 11): + __all__ += ["bind_textdomain_codeset", "ldgettext", "ldngettext", "lgettext", "lngettext"] + +@type_check_only +class _TranslationsReader(Protocol): + def read(self) -> bytes: ... + # optional: + # name: str class NullTranslations: - def __init__(self, fp: IO[str] | None = ...) -> None: ... - def _parse(self, fp: IO[str]) -> None: ... + def __init__(self, fp: _TranslationsReader | None = None) -> None: ... + def _parse(self, fp: _TranslationsReader) -> None: ... def add_fallback(self, fallback: NullTranslations) -> None: ... def gettext(self, message: str) -> str: ... - def lgettext(self, message: str) -> str: ... def ngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... - def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... - if sys.version_info >= (3, 8): - def pgettext(self, context: str, message: str) -> str: ... - def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... - def info(self) -> Any: ... - def charset(self) -> Any: ... + def pgettext(self, context: str, message: str) -> str: ... + def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... + def info(self) -> dict[str, str]: ... + def charset(self) -> str | None: ... if sys.version_info < (3, 11): - def output_charset(self) -> Any: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11.") + def output_charset(self) -> str | None: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11.") def set_output_charset(self, charset: str) -> None: ... - def install(self, names: Container[str] | None = ...) -> None: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `gettext()` instead.") + def lgettext(self, message: str) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `ngettext()` instead.") + def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... + + def install(self, names: Container[str] | None = None) -> None: ... class GNUTranslations(NullTranslations): - LE_MAGIC: int - BE_MAGIC: int + LE_MAGIC: Final[int] + BE_MAGIC: Final[int] CONTEXT: str VERSIONS: Sequence[int] -def find(domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: bool = ...) -> Any: ... +@overload +def find( + domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, all: Literal[False] = False +) -> str | None: ... +@overload +def find( + domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, *, all: Literal[True] +) -> list[str]: ... +@overload +def find(domain: str, localedir: StrPath | None, languages: Iterable[str] | None, all: Literal[True]) -> list[str]: ... +@overload +def find(domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, all: bool = False) -> Any: ... -_T = TypeVar("_T") +_NullTranslationsT = TypeVar("_NullTranslationsT", bound=NullTranslations) if sys.version_info >= (3, 11): @overload def translation( domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: None = ..., - fallback: bool = ..., - ) -> NullTranslations: ... + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: None = None, + fallback: Literal[False] = False, + ) -> GNUTranslations: ... @overload def translation( domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: Type[_T] = ..., - fallback: Literal[False] = ..., - ) -> _T: ... + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + *, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, + ) -> _NullTranslationsT: ... @overload def translation( domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: Type[Any] = ..., - fallback: Literal[True] = ..., - ) -> Any: ... - def install(domain: str, localedir: StrPath | None = ..., names: Container[str] | None = ...) -> None: ... + localedir: StrPath | None, + languages: Iterable[str] | None, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: Callable[[io.BufferedReader], NullTranslations] | None = None, + fallback: bool = False, + ) -> NullTranslations: ... + def install(domain: str, localedir: StrPath | None = None, *, names: Container[str] | None = None) -> None: ... else: @overload def translation( domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: None = ..., - fallback: bool = ..., + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: None = None, + fallback: Literal[False] = False, codeset: str | None = ..., - ) -> NullTranslations: ... + ) -> GNUTranslations: ... @overload def translation( domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: Type[_T] = ..., - fallback: Literal[False] = ..., + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + *, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, codeset: str | None = ..., - ) -> _T: ... + ) -> _NullTranslationsT: ... @overload def translation( domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: Type[Any] = ..., - fallback: Literal[True] = ..., + localedir: StrPath | None, + languages: Iterable[str] | None, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, codeset: str | None = ..., - ) -> Any: ... + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: Callable[[io.BufferedReader], NullTranslations] | None = None, + fallback: bool = False, + codeset: str | None = ..., + ) -> NullTranslations: ... + + @overload + def install(domain: str, localedir: StrPath | None = None, names: Container[str] | None = None) -> None: ... + @overload + @deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.") + def install(domain: str, localedir: StrPath | None, codeset: str | None, /, names: Container[str] | None = None) -> None: ... + @overload + @deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.") def install( - domain: str, localedir: StrPath | None = ..., codeset: str | None = ..., names: Container[str] | None = ... + domain: str, localedir: StrPath | None = None, *, codeset: str | None, names: Container[str] | None = None ) -> None: ... -def textdomain(domain: str | None = ...) -> str: ... -def bindtextdomain(domain: str, localedir: StrPath | None = ...) -> str: ... +def textdomain(domain: str | None = None) -> str: ... +def bindtextdomain(domain: str, localedir: StrPath | None = None) -> str: ... def dgettext(domain: str, message: str) -> str: ... def dngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... def gettext(message: str) -> str: ... def ngettext(msgid1: str, msgid2: str, n: int) -> str: ... - -if sys.version_info >= (3, 8): - def pgettext(context: str, message: str) -> str: ... - def dpgettext(domain: str, context: str, message: str) -> str: ... - def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... - def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... +def pgettext(context: str, message: str) -> str: ... +def dpgettext(domain: str, context: str, message: str) -> str: ... +def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... +def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `gettext()` instead.") def lgettext(message: str) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `dgettext()` instead.") def ldgettext(domain: str, message: str) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `ngettext()` instead.") def lngettext(msgid1: str, msgid2: str, n: int) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `dngettext()` instead.") def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... - def bind_textdomain_codeset(domain: str, codeset: str | None = ...) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `bindtextdomain()` instead.") + def bind_textdomain_codeset(domain: str, codeset: str | None = None) -> str: ... Catalog = translation + +def c2py(plural: str) -> Callable[[int], int]: ... diff --git a/stdlib/glob.pyi b/stdlib/glob.pyi index c1cd176f500c..60de4605cf3c 100644 --- a/stdlib/glob.pyi +++ b/stdlib/glob.pyi @@ -1,21 +1,50 @@ import sys from _typeshed import StrOrBytesPath -from typing import AnyStr, Iterator +from collections.abc import Iterator, Sequence +from typing import AnyStr +from typing_extensions import deprecated -def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... -def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... +__all__ = ["escape", "glob", "iglob"] -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 13): + __all__ += ["translate"] + +if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead.") + def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead.") + def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... + +if sys.version_info >= (3, 11): def glob( - pathname: AnyStr, *, root_dir: StrOrBytesPath | None = ..., dir_fd: int | None = ..., recursive: bool = ... + pathname: AnyStr, + *, + root_dir: StrOrBytesPath | None = None, + dir_fd: int | None = None, + recursive: bool = False, + include_hidden: bool = False, ) -> list[AnyStr]: ... def iglob( - pathname: AnyStr, *, root_dir: StrOrBytesPath | None = ..., dir_fd: int | None = ..., recursive: bool = ... + pathname: AnyStr, + *, + root_dir: StrOrBytesPath | None = None, + dir_fd: int | None = None, + recursive: bool = False, + include_hidden: bool = False, ) -> Iterator[AnyStr]: ... else: - def glob(pathname: AnyStr, *, recursive: bool = ...) -> list[AnyStr]: ... - def iglob(pathname: AnyStr, *, recursive: bool = ...) -> Iterator[AnyStr]: ... + def glob( + pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False + ) -> list[AnyStr]: ... + def iglob( + pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False + ) -> Iterator[AnyStr]: ... def escape(pathname: AnyStr) -> AnyStr: ... def has_magic(s: str | bytes) -> bool: ... # undocumented + +if sys.version_info >= (3, 13): + def translate( + pat: str, *, recursive: bool = False, include_hidden: bool = False, seps: Sequence[str] | None = None + ) -> str: ... diff --git a/stdlib/graphlib.pyi b/stdlib/graphlib.pyi index 0872af4a54a4..f0ac72b6135e 100644 --- a/stdlib/graphlib.pyi +++ b/stdlib/graphlib.pyi @@ -1,16 +1,29 @@ +import sys from _typeshed import SupportsItems -from typing import Generic, Iterable, Tuple, TypeVar +from collections.abc import Iterable +from typing import Any, Generic, TypeVar, overload + +__all__ = ["TopologicalSorter", "CycleError"] _T = TypeVar("_T") +if sys.version_info >= (3, 11): + from types import GenericAlias + class TopologicalSorter(Generic[_T]): - def __init__(self, graph: SupportsItems[_T, Iterable[_T]] | None = ...) -> None: ... + @overload + def __init__(self, graph: None = None) -> None: ... + @overload + def __init__(self, graph: SupportsItems[_T, Iterable[_T]]) -> None: ... + def add(self, node: _T, *predecessors: _T) -> None: ... def prepare(self) -> None: ... def is_active(self) -> bool: ... def __bool__(self) -> bool: ... def done(self, *nodes: _T) -> None: ... - def get_ready(self) -> Tuple[_T, ...]: ... + def get_ready(self) -> tuple[_T, ...]: ... def static_order(self) -> Iterable[_T]: ... + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class CycleError(ValueError): ... diff --git a/stdlib/grp.pyi b/stdlib/grp.pyi index 33f2a9774be8..9f372b4d63dc 100644 --- a/stdlib/grp.pyi +++ b/stdlib/grp.pyi @@ -1,18 +1,21 @@ +import sys from _typeshed import structseq -from typing import Any, List, Optional, Tuple -from typing_extensions import final +from typing import Any, Final, final -@final -class struct_group(structseq[Any], Tuple[str, Optional[str], int, List[str]]): - @property - def gr_name(self) -> str: ... - @property - def gr_passwd(self) -> str | None: ... - @property - def gr_gid(self) -> int: ... - @property - def gr_mem(self) -> list[str]: ... +if sys.platform != "win32": + @final + class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]): + __match_args__: Final = ("gr_name", "gr_passwd", "gr_gid", "gr_mem") -def getgrall() -> list[struct_group]: ... -def getgrgid(id: int) -> struct_group: ... -def getgrnam(name: str) -> struct_group: ... + @property + def gr_name(self) -> str: ... + @property + def gr_passwd(self) -> str | None: ... + @property + def gr_gid(self) -> int: ... + @property + def gr_mem(self) -> list[str]: ... + + def getgrall() -> list[struct_group]: ... + def getgrgid(id: int) -> struct_group: ... + def getgrnam(name: str) -> struct_group: ... diff --git a/stdlib/gzip.pyi b/stdlib/gzip.pyi index 070ceac48282..4322e6c84c90 100644 --- a/stdlib/gzip.pyi +++ b/stdlib/gzip.pyi @@ -1,29 +1,43 @@ -import _compression import sys import zlib -from _typeshed import ReadableBuffer, StrOrBytesPath -from io import FileIO -from typing import Any, Protocol, TextIO, overload -from typing_extensions import Literal +from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, WriteableBuffer +from io import FileIO, TextIOWrapper +from typing import Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import deprecated -_ReadBinaryMode = Literal["r", "rb"] -_WriteBinaryMode = Literal["a", "ab", "w", "wb", "x", "xb"] -_OpenTextMode = Literal["rt", "at", "wt", "xt"] +if sys.version_info >= (3, 14): + from compression._common._streams import BaseStream, DecompressReader +else: + from _compression import BaseStream, DecompressReader + +__all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] + +_ReadBinaryMode: TypeAlias = Literal["r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["a", "ab", "w", "wb", "x", "xb"] +_OpenTextMode: TypeAlias = Literal["rt", "at", "wt", "xt"] + +READ: Final[object] # undocumented +WRITE: Final[object] # undocumented -READ: Literal[1] -WRITE: Literal[2] +FTEXT: Final[int] # actually Literal[1] # undocumented +FHCRC: Final[int] # actually Literal[2] # undocumented +FEXTRA: Final[int] # actually Literal[4] # undocumented +FNAME: Final[int] # actually Literal[8] # undocumented +FCOMMENT: Final[int] # actually Literal[16] # undocumented +@type_check_only class _ReadableFileobj(Protocol): - def read(self, __n: int) -> bytes: ... - def seek(self, __n: int) -> Any: ... + def read(self, n: int, /) -> bytes: ... + def seek(self, n: int, /) -> object: ... # The following attributes and methods are optional: # name: str # mode: str # def fileno() -> int: ... +@type_check_only class _WritableFileobj(Protocol): - def write(self, __b: bytes) -> Any: ... - def flush(self) -> Any: ... + def write(self, b: bytes, /) -> object: ... + def flush(self) -> object: ... # The following attributes and methods are optional: # name: str # mode: str @@ -32,131 +46,136 @@ class _WritableFileobj(Protocol): @overload def open( filename: StrOrBytesPath | _ReadableFileobj, - mode: _ReadBinaryMode = ..., - compresslevel: int = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + mode: _ReadBinaryMode = "rb", + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> GzipFile: ... @overload def open( filename: StrOrBytesPath | _WritableFileobj, mode: _WriteBinaryMode, - compresslevel: int = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> GzipFile: ... @overload def open( - filename: StrOrBytesPath, + filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, mode: _OpenTextMode, - compresslevel: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> TextIO: ... + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... @overload def open( filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, mode: str, - compresslevel: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> GzipFile | TextIO: ... + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> GzipFile | TextIOWrapper: ... class _PaddedFile: file: _ReadableFileobj - def __init__(self, f: _ReadableFileobj, prepend: bytes = ...) -> None: ... + def __init__(self, f: _ReadableFileobj, prepend: bytes = b"") -> None: ... def read(self, size: int) -> bytes: ... - def prepend(self, prepend: bytes = ...) -> None: ... + def prepend(self, prepend: bytes = b"") -> None: ... def seek(self, off: int) -> int: ... def seekable(self) -> bool: ... -if sys.version_info >= (3, 8): - class BadGzipFile(OSError): ... +class BadGzipFile(OSError): ... -class GzipFile(_compression.BaseStream): +class GzipFile(BaseStream): myfileobj: FileIO | None - mode: Literal[1, 2] + mode: object name: str compress: zlib._Compress fileobj: _ReadableFileobj | _WritableFileobj + @overload def __init__( self, filename: StrOrBytesPath | None, mode: _ReadBinaryMode, - compresslevel: int = ..., - fileobj: _ReadableFileobj | None = ..., - mtime: float | None = ..., + compresslevel: int = 9, + fileobj: _ReadableFileobj | None = None, + mtime: float | None = None, ) -> None: ... @overload def __init__( self, *, mode: _ReadBinaryMode, - compresslevel: int = ..., - fileobj: _ReadableFileobj | None = ..., - mtime: float | None = ..., + compresslevel: int = 9, + fileobj: _ReadableFileobj | None = None, + mtime: float | None = None, ) -> None: ... @overload def __init__( self, filename: StrOrBytesPath | None, mode: _WriteBinaryMode, - compresslevel: int = ..., - fileobj: _WritableFileobj | None = ..., - mtime: float | None = ..., + compresslevel: int = 9, + fileobj: _WritableFileobj | None = None, + mtime: float | None = None, ) -> None: ... @overload def __init__( self, *, mode: _WriteBinaryMode, - compresslevel: int = ..., - fileobj: _WritableFileobj | None = ..., - mtime: float | None = ..., + compresslevel: int = 9, + fileobj: _WritableFileobj | None = None, + mtime: float | None = None, ) -> None: ... @overload def __init__( self, - filename: StrOrBytesPath | None = ..., - mode: str | None = ..., - compresslevel: int = ..., - fileobj: _ReadableFileobj | _WritableFileobj | None = ..., - mtime: float | None = ..., + filename: StrOrBytesPath | None = None, + mode: str | None = None, + compresslevel: int = 9, + fileobj: _ReadableFileobj | _WritableFileobj | None = None, + mtime: float | None = None, ) -> None: ... - @property - def filename(self) -> str: ... + + if sys.version_info < (3, 12): + @property + @deprecated("Deprecated since Python 2.6; removed in Python 3.12. Use `name` attribute instead.") + def filename(self) -> str: ... + @property def mtime(self) -> int | None: ... crc: int def write(self, data: ReadableBuffer) -> int: ... - def read(self, size: int | None = ...) -> bytes: ... - def read1(self, size: int = ...) -> bytes: ... + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int = -1) -> bytes: ... def peek(self, n: int) -> bytes: ... - @property - def closed(self) -> bool: ... def close(self) -> None: ... - def flush(self, zlib_mode: int = ...) -> None: ... + def flush(self, zlib_mode: int = 2) -> None: ... def fileno(self) -> int: ... def rewind(self) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def seekable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def readline(self, size: int | None = ...) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def readline(self, size: int | None = -1) -> bytes: ... + + if sys.version_info >= (3, 14): + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... -class _GzipReader(_compression.DecompressReader): +class _GzipReader(DecompressReader): def __init__(self, fp: _ReadableFileobj) -> None: ... - def read(self, size: int = ...) -> bytes: ... -if sys.version_info >= (3, 8): - def compress(data: bytes, compresslevel: int = ..., *, mtime: float | None = ...) -> bytes: ... +if sys.version_info >= (3, 15): + def compress(data: SizedBuffer, compresslevel: int = 6, *, mtime: float = 0) -> bytes: ... + +elif sys.version_info >= (3, 14): + def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float = 0) -> bytes: ... else: - def compress(data: bytes, compresslevel: int = ...) -> bytes: ... + def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: ... -def decompress(data: bytes) -> bytes: ... +def decompress(data: ReadableBuffer) -> bytes: ... diff --git a/stdlib/hashlib.pyi b/stdlib/hashlib.pyi index e39f2f25326e..be1ce7a8efd0 100644 --- a/stdlib/hashlib.pyi +++ b/stdlib/hashlib.pyi @@ -1,123 +1,126 @@ import sys -from _typeshed import ReadableBuffer, Self -from typing import AbstractSet +from _blake2 import blake2b as blake2b, blake2s as blake2s +from _hashlib import ( + HASH, + HASHXOF, + _FixedDigestName, + _HashObject, + _HashObjectWithOptionalLength, + _XofDigestName, + openssl_md5 as md5, + openssl_sha1 as sha1, + openssl_sha3_224 as sha3_224, + openssl_sha3_256 as sha3_256, + openssl_sha3_384 as sha3_384, + openssl_sha3_512 as sha3_512, + openssl_sha224 as sha224, + openssl_sha256 as sha256, + openssl_sha384 as sha384, + openssl_sha512 as sha512, + openssl_shake_128 as shake_128, + openssl_shake_256 as shake_256, + pbkdf2_hmac as pbkdf2_hmac, + scrypt as scrypt, +) +from _typeshed import ReadableBuffer +from collections.abc import Callable, Set as AbstractSet +from typing import Protocol, TypeVar, overload, type_check_only -class _Hash(object): - @property - def digest_size(self) -> int: ... - @property - def block_size(self) -> int: ... - @property - def name(self) -> str: ... - def __init__(self, data: ReadableBuffer = ...) -> None: ... - def copy(self: Self) -> Self: ... - def digest(self) -> bytes: ... - def hexdigest(self) -> str: ... - def update(self, __data: ReadableBuffer) -> None: ... - -if sys.version_info >= (3, 9): - def new(name: str, data: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - def md5(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - def sha1(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - def sha224(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - def sha256(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - def sha384(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - def sha512(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... - -elif sys.version_info >= (3, 8): - def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... - def md5(string: ReadableBuffer = ...) -> _Hash: ... - def sha1(string: ReadableBuffer = ...) -> _Hash: ... - def sha224(string: ReadableBuffer = ...) -> _Hash: ... - def sha256(string: ReadableBuffer = ...) -> _Hash: ... - def sha384(string: ReadableBuffer = ...) -> _Hash: ... - def sha512(string: ReadableBuffer = ...) -> _Hash: ... +_HashT = TypeVar("_HashT", bound=_HashObject) +if sys.version_info >= (3, 15): + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "file_digest", + "pbkdf2_hmac", + "scrypt", + ) +elif sys.version_info >= (3, 11): + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "file_digest", + "pbkdf2_hmac", + ) else: - def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... - def md5(__string: ReadableBuffer = ...) -> _Hash: ... - def sha1(__string: ReadableBuffer = ...) -> _Hash: ... - def sha224(__string: ReadableBuffer = ...) -> _Hash: ... - def sha256(__string: ReadableBuffer = ...) -> _Hash: ... - def sha384(__string: ReadableBuffer = ...) -> _Hash: ... - def sha512(__string: ReadableBuffer = ...) -> _Hash: ... + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "pbkdf2_hmac", + ) + +@overload +def new(name: _XofDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... +@overload +def new(name: _FixedDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +@overload +def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _HashObjectWithOptionalLength: ... algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] -def pbkdf2_hmac( - hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = ... -) -> bytes: ... - -class _VarLenHash(object): - digest_size: int - block_size: int - name: str - def __init__(self, data: ReadableBuffer = ...) -> None: ... - def copy(self) -> _VarLenHash: ... - def digest(self, __length: int) -> bytes: ... - def hexdigest(self, __length: int) -> str: ... - def update(self, __data: ReadableBuffer) -> None: ... - -sha3_224 = _Hash -sha3_256 = _Hash -sha3_384 = _Hash -sha3_512 = _Hash -shake_128 = _VarLenHash -shake_256 = _VarLenHash - -def scrypt( - password: ReadableBuffer, - *, - salt: ReadableBuffer | None = ..., - n: int | None = ..., - r: int | None = ..., - p: int | None = ..., - maxmem: int = ..., - dklen: int = ..., -) -> bytes: ... +if sys.version_info >= (3, 11): + @type_check_only + class _BytesIOLike(Protocol): + def getbuffer(self) -> ReadableBuffer: ... -class _BlakeHash(_Hash): - MAX_DIGEST_SIZE: int - MAX_KEY_SIZE: int - PERSON_SIZE: int - SALT_SIZE: int + @type_check_only + class _FileDigestFileObj(Protocol): + def readinto(self, buf: bytearray, /) -> int: ... + def readable(self) -> bool: ... - if sys.version_info >= (3, 9): - def __init__( - self, - __data: ReadableBuffer = ..., - *, - digest_size: int = ..., - key: ReadableBuffer = ..., - salt: ReadableBuffer = ..., - person: ReadableBuffer = ..., - fanout: int = ..., - depth: int = ..., - leaf_size: int = ..., - node_offset: int = ..., - node_depth: int = ..., - inner_size: int = ..., - last_node: bool = ..., - usedforsecurity: bool = ..., - ) -> None: ... - else: - def __init__( - self, - __data: ReadableBuffer = ..., - *, - digest_size: int = ..., - key: ReadableBuffer = ..., - salt: ReadableBuffer = ..., - person: ReadableBuffer = ..., - fanout: int = ..., - depth: int = ..., - leaf_size: int = ..., - node_offset: int = ..., - node_depth: int = ..., - inner_size: int = ..., - last_node: bool = ..., - ) -> None: ... + @overload + def file_digest(fileobj: _BytesIOLike | _FileDigestFileObj, digest: str, /, *, _bufsize: int = 262144) -> HASH: ... + @overload + def file_digest( + fileobj: _BytesIOLike | _FileDigestFileObj, digest: Callable[[], _HashT], /, *, _bufsize: int = 262144 + ) -> _HashT: ... -blake2b = _BlakeHash -blake2s = _BlakeHash +# Legacy typing-only alias +_Hash = HASH diff --git a/stdlib/heapq.pyi b/stdlib/heapq.pyi index fd3c2db8ad66..7969aa4e0015 100644 --- a/stdlib/heapq.pyi +++ b/stdlib/heapq.pyi @@ -1,14 +1,32 @@ -from _typeshed import SupportsRichComparison -from typing import Any, Callable, Iterable, TypeVar - -_T = TypeVar("_T") - -def heappush(__heap: list[_T], __item: _T) -> None: ... -def heappop(__heap: list[_T]) -> _T: ... -def heappushpop(__heap: list[_T], __item: _T) -> _T: ... -def heapify(__heap: list[Any]) -> None: ... -def heapreplace(__heap: list[_T], __item: _T) -> _T: ... -def merge(*iterables: Iterable[_T], key: Callable[[_T], Any] | None = ..., reverse: bool = ...) -> Iterable[_T]: ... -def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsRichComparison] | None = ...) -> list[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsRichComparison] | None = ...) -> list[_T]: ... -def _heapify_max(__x: list[Any]) -> None: ... # undocumented +import sys +from _heapq import * +from _typeshed import SupportsRichComparison, SupportsRichComparisonT as _T +from collections.abc import Callable, Generator, Iterable +from typing import Final, TypeVar, overload + +__all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"] + +if sys.version_info >= (3, 14): + # Added to __all__ in 3.14.1 + __all__ += ["heapify_max", "heappop_max", "heappush_max", "heappushpop_max", "heapreplace_max"] + +_S = TypeVar("_S") + +__about__: Final[str] + +@overload +def merge(*iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison], reverse: bool = False) -> Generator[_S]: ... +@overload +def merge(*iterables: Iterable[_T], key: None = None, reverse: bool = False) -> Generator[_T]: ... + +@overload +def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison]) -> list[_S]: ... +@overload +def nlargest(n: int, iterable: Iterable[_T], key: None = None) -> list[_T]: ... + +@overload +def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison]) -> list[_S]: ... +@overload +def nsmallest(n: int, iterable: Iterable[_T], key: None = None) -> list[_T]: ... + +def _heapify_max(heap: list[SupportsRichComparison], /) -> None: ... # undocumented diff --git a/stdlib/hmac.pyi b/stdlib/hmac.pyi index 88c88631f99a..9beabcc4dd92 100644 --- a/stdlib/hmac.pyi +++ b/stdlib/hmac.pyi @@ -1,42 +1,33 @@ -import sys -from _typeshed import ReadableBuffer +from _hashlib import _HashObject, compare_digest as compare_digest +from _typeshed import ReadableBuffer, SizedBuffer +from collections.abc import Callable from types import ModuleType -from typing import Any, AnyStr, Callable, Union, overload +from typing import TypeAlias, overload -# TODO more precise type for object of hashlib -_Hash = Any -_DigestMod = Union[str, Callable[[], _Hash], ModuleType] +_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType trans_5C: bytes trans_36: bytes digest_size: None -if sys.version_info >= (3, 8): - # In reality digestmod has a default value, but the function always throws an error - # if the argument is not given, so we pretend it is a required argument. - @overload - def new(key: bytes, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: ... - @overload - def new(key: bytes, *, digestmod: _DigestMod) -> HMAC: ... - -else: - def new(key: bytes, msg: ReadableBuffer | None = ..., digestmod: _DigestMod | None = ...) -> HMAC: ... +# In reality digestmod has a default value, but the function always throws an error +# if the argument is not given, so we pretend it is a required argument. +@overload +def new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: ... +@overload +def new(key: bytes | bytearray, *, digestmod: _DigestMod) -> HMAC: ... class HMAC: + __slots__ = ("_hmac", "_inner", "_outer", "block_size", "digest_size") digest_size: int block_size: int - name: str - def __init__(self, key: bytes, msg: ReadableBuffer | None = ..., digestmod: _DigestMod = ...) -> None: ... + @property + def name(self) -> str: ... + def __init__(self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod = "") -> None: ... def update(self, msg: ReadableBuffer) -> None: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... def copy(self) -> HMAC: ... -@overload -def compare_digest(__a: ReadableBuffer, __b: ReadableBuffer) -> bool: ... -@overload -def compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... - -if sys.version_info >= (3, 7): - def digest(key: bytes, msg: ReadableBuffer, digest: str) -> bytes: ... +def digest(key: SizedBuffer, msg: ReadableBuffer, digest: _DigestMod) -> bytes: ... diff --git a/stdlib/html/__init__.pyi b/stdlib/html/__init__.pyi index af2a80021656..71e971d15044 100644 --- a/stdlib/html/__init__.pyi +++ b/stdlib/html/__init__.pyi @@ -1,4 +1,7 @@ -from typing import AnyStr +import re -def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... -def unescape(s: AnyStr) -> AnyStr: ... +__all__ = ["escape", "unescape"] + +def escape(s: str, quote: bool = True) -> str: ... +def unescape(s: str) -> str: ... +def _replace_charref(s: re.Match[str]) -> str: ... diff --git a/stdlib/html/entities.pyi b/stdlib/html/entities.pyi index 1743fccf32b9..e5890d1ecfbd 100644 --- a/stdlib/html/entities.pyi +++ b/stdlib/html/entities.pyi @@ -1,4 +1,8 @@ -name2codepoint: dict[str, int] -html5: dict[str, str] -codepoint2name: dict[int, str] -entitydefs: dict[str, str] +from typing import Final + +__all__ = ["html5", "name2codepoint", "codepoint2name", "entitydefs"] + +name2codepoint: Final[dict[str, int]] +html5: Final[dict[str, str]] +codepoint2name: Final[dict[int, str]] +entitydefs: Final[dict[str, str]] diff --git a/stdlib/html/parser.pyi b/stdlib/html/parser.pyi index 66515cad03ba..08dc7b936922 100644 --- a/stdlib/html/parser.pyi +++ b/stdlib/html/parser.pyi @@ -1,12 +1,18 @@ from _markupbase import ParserBase -from typing import Pattern, Tuple +from re import Pattern +from typing import Final + +__all__ = ["HTMLParser"] class HTMLParser(ParserBase): - def __init__(self, *, convert_charrefs: bool = ...) -> None: ... + CDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]] + # Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.6 + RCDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]] + + # `scripting` parameter added in Python 3.9.25, 3.10.20, 3.11.15, 3.12.13, 3.13.10, 3.14.1 + def __init__(self, *, convert_charrefs: bool = True, scripting: bool = False) -> None: ... def feed(self, data: str) -> None: ... def close(self) -> None: ... - def reset(self) -> None: ... - def getpos(self) -> tuple[int, int]: ... def get_starttag_text(self) -> str | None: ... def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: ... def handle_endtag(self, tag: str) -> None: ... @@ -17,17 +23,16 @@ class HTMLParser(ParserBase): def handle_comment(self, data: str) -> None: ... def handle_decl(self, decl: str) -> None: ... def handle_pi(self, data: str) -> None: ... - def unknown_decl(self, data: str) -> None: ... - CDATA_CONTENT_ELEMENTS: Tuple[str, ...] def check_for_whole_start_tag(self, i: int) -> int: ... # undocumented def clear_cdata_mode(self) -> None: ... # undocumented def goahead(self, end: bool) -> None: ... # undocumented - def parse_bogus_comment(self, i: int, report: bool = ...) -> int: ... # undocumented + def parse_bogus_comment(self, i: int, report: bool = True) -> int: ... # undocumented def parse_endtag(self, i: int) -> int: ... # undocumented def parse_html_declaration(self, i: int) -> int: ... # undocumented def parse_pi(self, i: int) -> int: ... # undocumented def parse_starttag(self, i: int) -> int: ... # undocumented - def set_cdata_mode(self, elem: str) -> None: ... # undocumented + # `escapable` parameter added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.6 + def set_cdata_mode(self, elem: str, *, escapable: bool = False) -> None: ... # undocumented rawdata: str # undocumented cdata_elem: str | None # undocumented convert_charrefs: bool # undocumented diff --git a/stdlib/http/__init__.pyi b/stdlib/http/__init__.pyi index 93895549cb2a..f60c3909736d 100644 --- a/stdlib/http/__init__.pyi +++ b/stdlib/http/__init__.pyi @@ -1,74 +1,118 @@ import sys from enum import IntEnum -from typing_extensions import Literal + +if sys.version_info >= (3, 11): + from enum import StrEnum + +if sys.version_info >= (3, 11): + __all__ = ["HTTPStatus", "HTTPMethod"] +else: + __all__ = ["HTTPStatus"] class HTTPStatus(IntEnum): @property def phrase(self) -> str: ... @property def description(self) -> str: ... - CONTINUE: int - SWITCHING_PROTOCOLS: int - PROCESSING: int - OK: int - CREATED: int - ACCEPTED: int - NON_AUTHORITATIVE_INFORMATION: int - NO_CONTENT: int - RESET_CONTENT: int - PARTIAL_CONTENT: int - MULTI_STATUS: int - ALREADY_REPORTED: int - IM_USED: int - MULTIPLE_CHOICES: int - MOVED_PERMANENTLY: int - FOUND: int - SEE_OTHER: int - NOT_MODIFIED: int - USE_PROXY: int - TEMPORARY_REDIRECT: int - PERMANENT_REDIRECT: int - BAD_REQUEST: int - UNAUTHORIZED: int - PAYMENT_REQUIRED: int - FORBIDDEN: int - NOT_FOUND: int - METHOD_NOT_ALLOWED: int - NOT_ACCEPTABLE: int - PROXY_AUTHENTICATION_REQUIRED: int - REQUEST_TIMEOUT: int - CONFLICT: int - GONE: int - LENGTH_REQUIRED: int - PRECONDITION_FAILED: int - REQUEST_ENTITY_TOO_LARGE: int - REQUEST_URI_TOO_LONG: int - UNSUPPORTED_MEDIA_TYPE: int - REQUESTED_RANGE_NOT_SATISFIABLE: int - EXPECTATION_FAILED: int - UNPROCESSABLE_ENTITY: int - LOCKED: int - FAILED_DEPENDENCY: int - UPGRADE_REQUIRED: int - PRECONDITION_REQUIRED: int - TOO_MANY_REQUESTS: int - REQUEST_HEADER_FIELDS_TOO_LARGE: int - INTERNAL_SERVER_ERROR: int - NOT_IMPLEMENTED: int - BAD_GATEWAY: int - SERVICE_UNAVAILABLE: int - GATEWAY_TIMEOUT: int - HTTP_VERSION_NOT_SUPPORTED: int - VARIANT_ALSO_NEGOTIATES: int - INSUFFICIENT_STORAGE: int - LOOP_DETECTED: int - NOT_EXTENDED: int - NETWORK_AUTHENTICATION_REQUIRED: int - if sys.version_info >= (3, 7): - MISDIRECTED_REQUEST: int - if sys.version_info >= (3, 8): - UNAVAILABLE_FOR_LEGAL_REASONS: int - if sys.version_info >= (3, 9): - EARLY_HINTS: Literal[103] - IM_A_TEAPOT: Literal[418] - TOO_EARLY: Literal[425] + + # Keep these synced with the global constants in http/client.pyi. + CONTINUE = 100 + SWITCHING_PROTOCOLS = 101 + PROCESSING = 102 + EARLY_HINTS = 103 + + OK = 200 + CREATED = 201 + ACCEPTED = 202 + NON_AUTHORITATIVE_INFORMATION = 203 + NO_CONTENT = 204 + RESET_CONTENT = 205 + PARTIAL_CONTENT = 206 + MULTI_STATUS = 207 + ALREADY_REPORTED = 208 + IM_USED = 226 + + MULTIPLE_CHOICES = 300 + MOVED_PERMANENTLY = 301 + FOUND = 302 + SEE_OTHER = 303 + NOT_MODIFIED = 304 + USE_PROXY = 305 + TEMPORARY_REDIRECT = 307 + PERMANENT_REDIRECT = 308 + + BAD_REQUEST = 400 + UNAUTHORIZED = 401 + PAYMENT_REQUIRED = 402 + FORBIDDEN = 403 + NOT_FOUND = 404 + METHOD_NOT_ALLOWED = 405 + NOT_ACCEPTABLE = 406 + PROXY_AUTHENTICATION_REQUIRED = 407 + REQUEST_TIMEOUT = 408 + CONFLICT = 409 + GONE = 410 + LENGTH_REQUIRED = 411 + PRECONDITION_FAILED = 412 + if sys.version_info >= (3, 13): + CONTENT_TOO_LARGE = 413 + REQUEST_ENTITY_TOO_LARGE = 413 + if sys.version_info >= (3, 13): + URI_TOO_LONG = 414 + REQUEST_URI_TOO_LONG = 414 + UNSUPPORTED_MEDIA_TYPE = 415 + if sys.version_info >= (3, 13): + RANGE_NOT_SATISFIABLE = 416 + REQUESTED_RANGE_NOT_SATISFIABLE = 416 + EXPECTATION_FAILED = 417 + IM_A_TEAPOT = 418 + MISDIRECTED_REQUEST = 421 + if sys.version_info >= (3, 13): + UNPROCESSABLE_CONTENT = 422 + UNPROCESSABLE_ENTITY = 422 + LOCKED = 423 + FAILED_DEPENDENCY = 424 + TOO_EARLY = 425 + UPGRADE_REQUIRED = 426 + PRECONDITION_REQUIRED = 428 + TOO_MANY_REQUESTS = 429 + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 + UNAVAILABLE_FOR_LEGAL_REASONS = 451 + + INTERNAL_SERVER_ERROR = 500 + NOT_IMPLEMENTED = 501 + BAD_GATEWAY = 502 + SERVICE_UNAVAILABLE = 503 + GATEWAY_TIMEOUT = 504 + HTTP_VERSION_NOT_SUPPORTED = 505 + VARIANT_ALSO_NEGOTIATES = 506 + INSUFFICIENT_STORAGE = 507 + LOOP_DETECTED = 508 + NOT_EXTENDED = 510 + NETWORK_AUTHENTICATION_REQUIRED = 511 + + if sys.version_info >= (3, 12): + @property + def is_informational(self) -> bool: ... + @property + def is_success(self) -> bool: ... + @property + def is_redirection(self) -> bool: ... + @property + def is_client_error(self) -> bool: ... + @property + def is_server_error(self) -> bool: ... + +if sys.version_info >= (3, 11): + class HTTPMethod(StrEnum): + @property + def description(self) -> str: ... + CONNECT = "CONNECT" + DELETE = "DELETE" + GET = "GET" + HEAD = "HEAD" + OPTIONS = "OPTIONS" + PATCH = "PATCH" + POST = "POST" + PUT = "PUT" + TRACE = "TRACE" diff --git a/stdlib/http/client.pyi b/stdlib/http/client.pyi index 1558f6ff46e8..d22335b56c54 100644 --- a/stdlib/http/client.pyi +++ b/stdlib/http/client.pyi @@ -3,82 +3,130 @@ import io import ssl import sys import types -from _typeshed import Self, WriteableBuffer +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsRead, SupportsReadline, WriteableBuffer +from collections.abc import Callable, Iterable, Iterator, Mapping +from email._policybase import _MessageT from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, Type, TypeVar, Union, overload +from typing import BinaryIO, Final, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated -_DataType = Union[bytes, IO[Any], Iterable[bytes], str] +__all__ = [ + "HTTPResponse", + "HTTPConnection", + "HTTPException", + "NotConnected", + "UnknownProtocol", + "UnknownTransferEncoding", + "UnimplementedFileMode", + "IncompleteRead", + "InvalidURL", + "ImproperConnectionState", + "CannotSendRequest", + "CannotSendHeader", + "ResponseNotReady", + "BadStatusLine", + "LineTooLong", + "RemoteDisconnected", + "error", + "responses", + "HTTPSConnection", +] + +_DataType: TypeAlias = SupportsRead[bytes] | Iterable[ReadableBuffer] | ReadableBuffer _T = TypeVar("_T") +_HeaderValue: TypeAlias = ReadableBuffer | str | int + +HTTP_PORT: Final = 80 +HTTPS_PORT: Final = 443 + +# Keep these global constants in sync with http.HTTPStatus (http/__init__.pyi). +# They are present for backward compatibility reasons. +CONTINUE: Final = 100 +SWITCHING_PROTOCOLS: Final = 101 +PROCESSING: Final = 102 +EARLY_HINTS: Final = 103 + +OK: Final = 200 +CREATED: Final = 201 +ACCEPTED: Final = 202 +NON_AUTHORITATIVE_INFORMATION: Final = 203 +NO_CONTENT: Final = 204 +RESET_CONTENT: Final = 205 +PARTIAL_CONTENT: Final = 206 +MULTI_STATUS: Final = 207 +ALREADY_REPORTED: Final = 208 +IM_USED: Final = 226 -HTTP_PORT: int -HTTPS_PORT: int - -CONTINUE: int -SWITCHING_PROTOCOLS: int -PROCESSING: int - -OK: int -CREATED: int -ACCEPTED: int -NON_AUTHORITATIVE_INFORMATION: int -NO_CONTENT: int -RESET_CONTENT: int -PARTIAL_CONTENT: int -MULTI_STATUS: int -IM_USED: int - -MULTIPLE_CHOICES: int -MOVED_PERMANENTLY: int -FOUND: int -SEE_OTHER: int -NOT_MODIFIED: int -USE_PROXY: int -TEMPORARY_REDIRECT: int - -BAD_REQUEST: int -UNAUTHORIZED: int -PAYMENT_REQUIRED: int -FORBIDDEN: int -NOT_FOUND: int -METHOD_NOT_ALLOWED: int -NOT_ACCEPTABLE: int -PROXY_AUTHENTICATION_REQUIRED: int -REQUEST_TIMEOUT: int -CONFLICT: int -GONE: int -LENGTH_REQUIRED: int -PRECONDITION_FAILED: int -REQUEST_ENTITY_TOO_LARGE: int -REQUEST_URI_TOO_LONG: int -UNSUPPORTED_MEDIA_TYPE: int -REQUESTED_RANGE_NOT_SATISFIABLE: int -EXPECTATION_FAILED: int -UNPROCESSABLE_ENTITY: int -LOCKED: int -FAILED_DEPENDENCY: int -UPGRADE_REQUIRED: int -PRECONDITION_REQUIRED: int -TOO_MANY_REQUESTS: int -REQUEST_HEADER_FIELDS_TOO_LARGE: int - -INTERNAL_SERVER_ERROR: int -NOT_IMPLEMENTED: int -BAD_GATEWAY: int -SERVICE_UNAVAILABLE: int -GATEWAY_TIMEOUT: int -HTTP_VERSION_NOT_SUPPORTED: int -INSUFFICIENT_STORAGE: int -NOT_EXTENDED: int -NETWORK_AUTHENTICATION_REQUIRED: int +MULTIPLE_CHOICES: Final = 300 +MOVED_PERMANENTLY: Final = 301 +FOUND: Final = 302 +SEE_OTHER: Final = 303 +NOT_MODIFIED: Final = 304 +USE_PROXY: Final = 305 +TEMPORARY_REDIRECT: Final = 307 +PERMANENT_REDIRECT: Final = 308 + +BAD_REQUEST: Final = 400 +UNAUTHORIZED: Final = 401 +PAYMENT_REQUIRED: Final = 402 +FORBIDDEN: Final = 403 +NOT_FOUND: Final = 404 +METHOD_NOT_ALLOWED: Final = 405 +NOT_ACCEPTABLE: Final = 406 +PROXY_AUTHENTICATION_REQUIRED: Final = 407 +REQUEST_TIMEOUT: Final = 408 +CONFLICT: Final = 409 +GONE: Final = 410 +LENGTH_REQUIRED: Final = 411 +PRECONDITION_FAILED: Final = 412 +if sys.version_info >= (3, 13): + CONTENT_TOO_LARGE: Final = 413 +REQUEST_ENTITY_TOO_LARGE: Final = 413 +if sys.version_info >= (3, 13): + URI_TOO_LONG: Final = 414 +REQUEST_URI_TOO_LONG: Final = 414 +UNSUPPORTED_MEDIA_TYPE: Final = 415 +if sys.version_info >= (3, 13): + RANGE_NOT_SATISFIABLE: Final = 416 +REQUESTED_RANGE_NOT_SATISFIABLE: Final = 416 +EXPECTATION_FAILED: Final = 417 +IM_A_TEAPOT: Final = 418 +MISDIRECTED_REQUEST: Final = 421 +if sys.version_info >= (3, 13): + UNPROCESSABLE_CONTENT: Final = 422 +UNPROCESSABLE_ENTITY: Final = 422 +LOCKED: Final = 423 +FAILED_DEPENDENCY: Final = 424 +TOO_EARLY: Final = 425 +UPGRADE_REQUIRED: Final = 426 +PRECONDITION_REQUIRED: Final = 428 +TOO_MANY_REQUESTS: Final = 429 +REQUEST_HEADER_FIELDS_TOO_LARGE: Final = 431 +UNAVAILABLE_FOR_LEGAL_REASONS: Final = 451 + +INTERNAL_SERVER_ERROR: Final = 500 +NOT_IMPLEMENTED: Final = 501 +BAD_GATEWAY: Final = 502 +SERVICE_UNAVAILABLE: Final = 503 +GATEWAY_TIMEOUT: Final = 504 +HTTP_VERSION_NOT_SUPPORTED: Final = 505 +VARIANT_ALSO_NEGOTIATES: Final = 506 +INSUFFICIENT_STORAGE: Final = 507 +LOOP_DETECTED: Final = 508 +NOT_EXTENDED: Final = 510 +NETWORK_AUTHENTICATION_REQUIRED: Final = 511 responses: dict[int, str] -class HTTPMessage(email.message.Message): +class HTTPMessage(email.message.Message[str, str]): def getallmatchingheaders(self, name: str) -> list[str]: ... # undocumented -def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... +@overload +def parse_headers(fp: SupportsReadline[bytes], _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def parse_headers(fp: SupportsReadline[bytes]) -> HTTPMessage: ... -class HTTPResponse(io.BufferedIOBase, BinaryIO): +class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible method definitions in the base classes msg: HTTPMessage headers: HTTPMessage version: int @@ -91,110 +139,153 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): chunk_left: int | None length: int | None will_close: bool - def __init__(self, sock: socket, debuglevel: int = ..., method: str | None = ..., url: str | None = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - def read(self, amt: int | None = ...) -> bytes: ... - def read1(self, n: int = ...) -> bytes: ... + # url is set on instances of the class in urllib.request.AbstractHTTPHandler.do_open + # to match urllib.response.addinfourl's interface. + # It's not set in HTTPResponse.__init__ or any other method on the class + url: str + def __init__(self, sock: socket, debuglevel: int = 0, method: str | None = None, url: str | None = None) -> None: ... + def peek(self, n: int = -1) -> bytes: ... + def read(self, amt: int | None = None) -> bytes: ... + def read1(self, n: int = -1) -> bytes: ... def readinto(self, b: WriteableBuffer) -> int: ... - def readline(self, limit: int = ...) -> bytes: ... # type: ignore[override] + def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] + @overload def getheader(self, name: str) -> str | None: ... @overload def getheader(self, name: str, default: _T) -> str | _T: ... + def getheaders(self) -> list[tuple[str, str]]: ... - def fileno(self) -> int: ... def isclosed(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> bool | None: ... - def info(self) -> email.message.Message: ... + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + @deprecated("Deprecated since Python 3.9. Use `HTTPResponse.headers` attribute instead.") + def info(self) -> HTTPMessage: ... + @deprecated("Deprecated since Python 3.9. Use `HTTPResponse.url` attribute instead.") def geturl(self) -> str: ... + @deprecated("Deprecated since Python 3.9. Use `HTTPResponse.status` attribute instead.") def getcode(self) -> int: ... def begin(self) -> None: ... -# This is an API stub only for the class below, not a class itself. -# urllib.request uses it for a parameter. -class _HTTPConnectionProtocol(Protocol): - if sys.version_info >= (3, 7): - def __call__( - self, - host: str, - port: int | None = ..., - timeout: float = ..., - source_address: tuple[str, int] | None = ..., - blocksize: int = ..., - ) -> HTTPConnection: ... - else: - def __call__( - self, host: str, port: int | None = ..., timeout: float = ..., source_address: tuple[str, int] | None = ... - ) -> HTTPConnection: ... - class HTTPConnection: + blocksize: int auto_open: int # undocumented debuglevel: int default_port: int # undocumented - response_class: Type[HTTPResponse] # undocumented + response_class: type[HTTPResponse] # undocumented timeout: float | None host: str port: int - sock: Any - if sys.version_info >= (3, 7): + sock: socket | MaybeNone # can be `None` if `.connect()` was not called + if sys.version_info >= (3, 15): def __init__( self, host: str, - port: int | None = ..., + port: int | None = None, timeout: float | None = ..., - source_address: tuple[str, int] | None = ..., - blocksize: int = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + *, + max_response_headers: int | None = None, ) -> None: ... else: def __init__( - self, host: str, port: int | None = ..., timeout: float | None = ..., source_address: tuple[str, int] | None = ... + self, + host: str, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, ) -> None: ... + def request( - self, method: str, url: str, body: _DataType | None = ..., headers: Mapping[str, str] = ..., *, encode_chunked: bool = ... + self, + method: str, + url: str, + body: _DataType | str | None = None, + headers: Mapping[str, _HeaderValue] = {}, + *, + encode_chunked: bool = False, ) -> None: ... def getresponse(self) -> HTTPResponse: ... def set_debuglevel(self, level: int) -> None: ... - def set_tunnel(self, host: str, port: int | None = ..., headers: Mapping[str, str] | None = ...) -> None: ... + if sys.version_info >= (3, 12): + def get_proxy_response_headers(self) -> HTTPMessage | None: ... + + def set_tunnel(self, host: str, port: int | None = None, headers: Mapping[str, str] | None = None) -> None: ... def connect(self) -> None: ... def close(self) -> None: ... - def putrequest(self, method: str, url: str, skip_host: bool = ..., skip_accept_encoding: bool = ...) -> None: ... - def putheader(self, header: str, *argument: str) -> None: ... - def endheaders(self, message_body: _DataType | None = ..., *, encode_chunked: bool = ...) -> None: ... - def send(self, data: _DataType) -> None: ... + def putrequest(self, method: str, url: str, skip_host: bool = False, skip_accept_encoding: bool = False) -> None: ... + def putheader(self, header: str | bytes, *values: _HeaderValue) -> None: ... + def endheaders(self, message_body: _DataType | None = None, *, encode_chunked: bool = False) -> None: ... + def send(self, data: _DataType | str) -> None: ... class HTTPSConnection(HTTPConnection): - if sys.version_info >= (3, 7): + # Can be `None` if `.connect()` was not called: + sock: ssl.SSLSocket | MaybeNone + if sys.version_info >= (3, 15): def __init__( self, host: str, - port: int | None = ..., - key_file: str | None = ..., - cert_file: str | None = ..., + port: int | None = None, + *, timeout: float | None = ..., - source_address: tuple[str, int] | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, + max_response_headers: int | None = None, + ) -> None: ... + elif sys.version_info >= (3, 12): + def __init__( + self, + host: str, + port: int | None = None, *, - context: ssl.SSLContext | None = ..., - check_hostname: bool | None = ..., - blocksize: int = ..., + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, ) -> None: ... else: + @overload + def __init__( + self, + host: str, + port: int | None = None, + key_file: None = None, + cert_file: None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + context: ssl.SSLContext | None = None, + check_hostname: None = None, + blocksize: int = 8192, + ) -> None: ... + @overload + @deprecated( + "The `key_file`, `cert_file`, `check_hostname` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) def __init__( self, host: str, - port: int | None = ..., - key_file: str | None = ..., - cert_file: str | None = ..., + port: int | None = None, + key_file: StrOrBytesPath | None = None, + cert_file: StrOrBytesPath | None = None, timeout: float | None = ..., - source_address: tuple[str, int] | None = ..., + source_address: tuple[str, int] | None = None, *, - context: ssl.SSLContext | None = ..., - check_hostname: bool | None = ..., + context: ssl.SSLContext | None = None, + check_hostname: bool | None = None, + blocksize: int = 8192, ) -> None: ... + key_file: StrOrBytesPath | None + cert_file: StrOrBytesPath | None + class HTTPException(Exception): ... error = HTTPException @@ -209,7 +300,7 @@ class UnknownTransferEncoding(HTTPException): ... class UnimplementedFileMode(HTTPException): ... class IncompleteRead(HTTPException): - def __init__(self, partial: bytes, expected: int | None = ...) -> None: ... + def __init__(self, partial: bytes, expected: int | None = None) -> None: ... partial: bytes expected: int | None diff --git a/stdlib/http/cookiejar.pyi b/stdlib/http/cookiejar.pyi index f37fb19cebe9..1bd2fbcbd75d 100644 --- a/stdlib/http/cookiejar.pyi +++ b/stdlib/http/cookiejar.pyi @@ -1,51 +1,57 @@ -import sys from _typeshed import StrPath +from collections.abc import Iterator, Sequence from http.client import HTTPResponse -from typing import ClassVar, Iterable, Iterator, Pattern, Sequence, Tuple, TypeVar, overload +from re import Pattern +from typing import ClassVar, TypeVar, overload from urllib.request import Request +__all__ = [ + "Cookie", + "CookieJar", + "CookiePolicy", + "DefaultCookiePolicy", + "FileCookieJar", + "LWPCookieJar", + "LoadError", + "MozillaCookieJar", +] + _T = TypeVar("_T") class LoadError(OSError): ... -class CookieJar(Iterable[Cookie]): +class CookieJar: non_word_re: ClassVar[Pattern[str]] # undocumented quote_re: ClassVar[Pattern[str]] # undocumented strict_domain_re: ClassVar[Pattern[str]] # undocumented domain_re: ClassVar[Pattern[str]] # undocumented dots_re: ClassVar[Pattern[str]] # undocumented magic_re: ClassVar[Pattern[str]] # undocumented - def __init__(self, policy: CookiePolicy | None = ...) -> None: ... + def __init__(self, policy: CookiePolicy | None = None) -> None: ... def add_cookie_header(self, request: Request) -> None: ... def extract_cookies(self, response: HTTPResponse, request: Request) -> None: ... def set_policy(self, policy: CookiePolicy) -> None: ... def make_cookies(self, response: HTTPResponse, request: Request) -> Sequence[Cookie]: ... def set_cookie(self, cookie: Cookie) -> None: ... def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: ... - def clear(self, domain: str | None = ..., path: str | None = ..., name: str | None = ...) -> None: ... + def clear(self, domain: str | None = None, path: str | None = None, name: str | None = None) -> None: ... def clear_session_cookies(self) -> None: ... def clear_expired_cookies(self) -> None: ... # undocumented def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... class FileCookieJar(CookieJar): - filename: str + filename: str | None delayload: bool - if sys.version_info >= (3, 8): - def __init__(self, filename: StrPath | None = ..., delayload: bool = ..., policy: CookiePolicy | None = ...) -> None: ... - else: - def __init__(self, filename: str | None = ..., delayload: bool = ..., policy: CookiePolicy | None = ...) -> None: ... - def save(self, filename: str | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... - def load(self, filename: str | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... - def revert(self, filename: str | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... + def __init__(self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None: ... + def save(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... + def load(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... + def revert(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... -class MozillaCookieJar(FileCookieJar): - header: ClassVar[str] # undocumented +class MozillaCookieJar(FileCookieJar): ... class LWPCookieJar(FileCookieJar): - def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented + def as_lwp_str(self, ignore_discard: bool = True, ignore_expires: bool = True) -> str: ... # undocumented class CookiePolicy: netscape: bool @@ -69,43 +75,26 @@ class DefaultCookiePolicy(CookiePolicy): DomainRFC2965Match: ClassVar[int] DomainLiberal: ClassVar[int] DomainStrict: ClassVar[int] - if sys.version_info >= (3, 8): - def __init__( - self, - blocked_domains: Sequence[str] | None = ..., - allowed_domains: Sequence[str] | None = ..., - netscape: bool = ..., - rfc2965: bool = ..., - rfc2109_as_netscape: bool | None = ..., - hide_cookie2: bool = ..., - strict_domain: bool = ..., - strict_rfc2965_unverifiable: bool = ..., - strict_ns_unverifiable: bool = ..., - strict_ns_domain: int = ..., - strict_ns_set_initial_dollar: bool = ..., - strict_ns_set_path: bool = ..., - secure_protocols: Sequence[str] = ..., - ) -> None: ... - else: - def __init__( - self, - blocked_domains: Sequence[str] | None = ..., - allowed_domains: Sequence[str] | None = ..., - netscape: bool = ..., - rfc2965: bool = ..., - rfc2109_as_netscape: bool | None = ..., - hide_cookie2: bool = ..., - strict_domain: bool = ..., - strict_rfc2965_unverifiable: bool = ..., - strict_ns_unverifiable: bool = ..., - strict_ns_domain: int = ..., - strict_ns_set_initial_dollar: bool = ..., - strict_ns_set_path: bool = ..., - ) -> None: ... - def blocked_domains(self) -> Tuple[str, ...]: ... + def __init__( + self, + blocked_domains: Sequence[str] | None = None, + allowed_domains: Sequence[str] | None = None, + netscape: bool = True, + rfc2965: bool = False, + rfc2109_as_netscape: bool | None = None, + hide_cookie2: bool = False, + strict_domain: bool = False, + strict_rfc2965_unverifiable: bool = True, + strict_ns_unverifiable: bool = False, + strict_ns_domain: int = 0, + strict_ns_set_initial_dollar: bool = False, + strict_ns_set_path: bool = False, + secure_protocols: Sequence[str] = ("https", "wss"), + ) -> None: ... + def blocked_domains(self) -> tuple[str, ...]: ... def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... def is_blocked(self, domain: str) -> bool: ... - def allowed_domains(self) -> Tuple[str, ...] | None: ... + def allowed_domains(self) -> tuple[str, ...] | None: ... def set_allowed_domains(self, allowed_domains: Sequence[str] | None) -> None: ... def is_not_allowed(self, domain: str) -> bool: ... def set_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented @@ -140,7 +129,7 @@ class Cookie: domain_initial_dot: bool def __init__( self, - version: int | None, + version: int | str | None, name: str, value: str | None, # undocumented port: str | None, @@ -151,17 +140,19 @@ class Cookie: path: str, path_specified: bool, secure: bool, - expires: int | None, + expires: float | str | None, discard: bool, comment: str | None, comment_url: str | None, rest: dict[str, str], - rfc2109: bool = ..., + rfc2109: bool = False, ) -> None: ... def has_nonstandard_attr(self, name: str) -> bool: ... + @overload def get_nonstandard_attr(self, name: str) -> str | None: ... @overload def get_nonstandard_attr(self, name: str, default: _T) -> str | _T: ... + def set_nonstandard_attr(self, name: str, value: str) -> None: ... - def is_expired(self, now: int | None = ...) -> bool: ... + def is_expired(self, now: int | None = None) -> bool: ... diff --git a/stdlib/http/cookies.pyi b/stdlib/http/cookies.pyi index 4244c0c6aa0d..5434f8b8db7d 100644 --- a/stdlib/http/cookies.pyi +++ b/stdlib/http/cookies.pyi @@ -1,16 +1,18 @@ -import sys -from typing import Any, Dict, Generic, Iterable, Mapping, TypeVar, Union, overload +from _typeshed import MaybeNone, SupportsItems, SupportsKeysAndGetItem +from collections.abc import Container, Iterable +from types import GenericAlias +from typing import Any, Generic, TypeVar, overload +from typing_extensions import deprecated -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["CookieError", "BaseCookie", "SimpleCookie"] -_DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] _T = TypeVar("_T") @overload def _quote(str: None) -> None: ... @overload def _quote(str: str) -> str: ... + @overload def _unquote(str: None) -> None: ... @overload @@ -18,35 +20,38 @@ def _unquote(str: str) -> str: ... class CookieError(Exception): ... -class Morsel(Dict[str, Any], Generic[_T]): - value: str - coded_value: _T - key: str +class Morsel(dict[str, Any], Generic[_T]): + @property + def value(self) -> str | MaybeNone: ... + @property + def coded_value(self) -> _T | MaybeNone: ... + @property + def key(self) -> str | MaybeNone: ... def __init__(self) -> None: ... - if sys.version_info >= (3, 7): - def set(self, key: str, val: str, coded_val: _T) -> None: ... - else: - def set(self, key: str, val: str, coded_val: _T, LegalChars: str = ...) -> None: ... - def setdefault(self, key: str, val: str | None = ...) -> str: ... + def copy(self) -> Morsel[_T]: ... + def set(self, key: str, val: str, coded_val: _T) -> None: ... + def setdefault(self, key: str, val: str | None = None) -> str: ... # The dict update can also get a keywords argument so this is incompatible - @overload # type: ignore[override] - def update(self, values: Mapping[str, str]) -> None: ... - @overload - def update(self, values: Iterable[tuple[str, str]]) -> None: ... + def update(self, values: Iterable[tuple[str, str]] | SupportsKeysAndGetItem[str, str]) -> None: ... # type: ignore[override] def isReservedKey(self, K: str) -> bool: ... - def output(self, attrs: list[str] | None = ..., header: str = ...) -> str: ... - def js_output(self, attrs: list[str] | None = ...) -> str: ... - def OutputString(self, attrs: list[str] | None = ...) -> str: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class BaseCookie(Dict[str, Morsel[_T]], Generic[_T]): - def __init__(self, input: _DataType | None = ...) -> None: ... - def value_decode(self, val: str) -> _T: ... - def value_encode(self, val: _T) -> str: ... - def output(self, attrs: list[str] | None = ..., header: str = ..., sep: str = ...) -> str: ... - def js_output(self, attrs: list[str] | None = ...) -> str: ... - def load(self, rawdata: _DataType) -> None: ... + def output(self, attrs: Container[str] | None = None, header: str = "Set-Cookie:") -> str: ... + __str__ = output + @deprecated("Deprecated; will be removed in Python 3.19. Use `output()` instead.") + def js_output(self, attrs: Container[str] | None = None) -> str: ... + def OutputString(self, attrs: Container[str] | None = None) -> str: ... + def __eq__(self, morsel: object) -> bool: ... + def __setitem__(self, K: str, V: Any) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): + def __init__(self, input: str | SupportsItems[str, str | Morsel[Any]] | None = None) -> None: ... + def value_decode(self, val: str) -> tuple[_T, str]: ... + def value_encode(self, val: _T) -> tuple[str, str]: ... + def output(self, attrs: Container[str] | None = None, header: str = "Set-Cookie:", sep: str = "\r\n") -> str: ... + __str__ = output + @deprecated("Deprecated; will be removed in Python 3.19. Use `output()` instead.") + def js_output(self, attrs: Container[str] | None = None) -> str: ... + def load(self, rawdata: str | SupportsItems[str, str | Morsel[Any]]) -> None: ... def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: ... -class SimpleCookie(BaseCookie[_T], Generic[_T]): ... +class SimpleCookie(BaseCookie[str]): ... diff --git a/stdlib/http/server.pyi b/stdlib/http/server.pyi index e3d0a8c318f4..e739c8a55968 100644 --- a/stdlib/http/server.pyi +++ b/stdlib/http/server.pyi @@ -1,21 +1,62 @@ +import _socket import email.message import io import socketserver import sys -from _typeshed import StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, BinaryIO, ClassVar, Mapping, Sequence +from _ssl import _PasswordType +from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Mapping, Sequence +from ssl import Purpose, SSLContext +from typing import Any, AnyStr, BinaryIO, ClassVar, Protocol, type_check_only +from typing_extensions import Self, deprecated + +__all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler"] +if sys.version_info < (3, 15): + __all__ += ["CGIHTTPRequestHandler"] +if sys.version_info >= (3, 14): + __all__ = ["HTTPSServer", "ThreadingHTTPSServer"] class HTTPServer(socketserver.TCPServer): server_name: str server_port: int -if sys.version_info >= (3, 7): - class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): - daemon_threads: bool # undocumented +class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): ... + +if sys.version_info >= (3, 14): + @type_check_only + class _SSLModule(Protocol): + @staticmethod + def create_default_context( + purpose: Purpose = ..., + *, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, + ) -> SSLContext: ... + + class HTTPSServer(HTTPServer): + ssl: _SSLModule + certfile: StrOrBytesPath + keyfile: StrOrBytesPath | None + password: _PasswordType | None + alpn_protocols: Iterable[str] + def __init__( + self, + server_address: socketserver._AfInetAddress, + RequestHandlerClass: Callable[[Any, _socket._RetAddress, Self], socketserver.BaseRequestHandler], + bind_and_activate: bool = True, + *, + certfile: StrOrBytesPath, + keyfile: StrOrBytesPath | None = None, + password: _PasswordType | None = None, + alpn_protocols: Iterable[str] | None = None, + ) -> None: ... + def server_activate(self) -> None: ... + + class ThreadingHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer): ... class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): client_address: tuple[str, int] - server: socketserver.BaseServer close_connection: bool requestline: str command: str @@ -29,37 +70,53 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): protocol_version: str MessageClass: type responses: Mapping[int, tuple[str, str]] + if sys.version_info >= (3, 15): + default_content_type: str default_request_version: str # undocumented weekdayname: ClassVar[Sequence[str]] # undocumented monthname: ClassVar[Sequence[str | None]] # undocumented - def __init__(self, request: bytes, client_address: tuple[str, int], server: socketserver.BaseServer) -> None: ... - def handle(self) -> None: ... def handle_one_request(self) -> None: ... def handle_expect_100(self) -> bool: ... - def send_error(self, code: int, message: str | None = ..., explain: str | None = ...) -> None: ... - def send_response(self, code: int, message: str | None = ...) -> None: ... + def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None: ... + def send_response(self, code: int, message: str | None = None) -> None: ... def send_header(self, keyword: str, value: str) -> None: ... - def send_response_only(self, code: int, message: str | None = ...) -> None: ... + def send_response_only(self, code: int, message: str | None = None) -> None: ... def end_headers(self) -> None: ... def flush_headers(self) -> None: ... - def log_request(self, code: int | str = ..., size: int | str = ...) -> None: ... + def log_request(self, code: int | str = "-", size: int | str = "-") -> None: ... def log_error(self, format: str, *args: Any) -> None: ... def log_message(self, format: str, *args: Any) -> None: ... def version_string(self) -> str: ... - def date_time_string(self, timestamp: int | None = ...) -> str: ... + def date_time_string(self, timestamp: float | None = None) -> str: ... def log_date_time_string(self) -> str: ... def address_string(self) -> str: ... def parse_request(self) -> bool: ... # undocumented class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): - server_version: str extensions_map: dict[str, str] - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 12): + index_pages: ClassVar[tuple[str, ...]] + directory: str + if sys.version_info >= (3, 15): def __init__( - self, request: bytes, client_address: tuple[str, int], server: socketserver.BaseServer, directory: str | None = ... + self, + request: socketserver._RequestType, + client_address: _socket._RetAddress, + server: socketserver.BaseServer, + *, + directory: StrPath | None = None, + extra_response_headers: Mapping[str, str] | None = None, ) -> None: ... else: - def __init__(self, request: bytes, client_address: tuple[str, int], server: socketserver.BaseServer) -> None: ... + def __init__( + self, + request: socketserver._RequestType, + client_address: _socket._RetAddress, + server: socketserver.BaseServer, + *, + directory: StrPath | None = None, + ) -> None: ... + def do_GET(self) -> None: ... def do_HEAD(self) -> None: ... def send_head(self) -> io.BytesIO | BinaryIO | None: ... # undocumented @@ -70,11 +127,13 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def executable(path: StrPath) -> bool: ... # undocumented -class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): - cgi_directories: list[str] - have_fork: bool # undocumented - def do_POST(self) -> None: ... - def is_cgi(self) -> bool: ... # undocumented - def is_executable(self, path: StrPath) -> bool: ... # undocumented - def is_python(self, path: StrPath) -> bool: ... # undocumented - def run_cgi(self) -> None: ... # undocumented +if sys.version_info < (3, 15): + @deprecated("Deprecated and unsafe; removed in Python 3.15.") + class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): + cgi_directories: list[str] + have_fork: bool # undocumented + def do_POST(self) -> None: ... + def is_cgi(self) -> bool: ... # undocumented + def is_executable(self, path: StrPath) -> bool: ... # undocumented + def is_python(self, path: StrPath) -> bool: ... # undocumented + def run_cgi(self) -> None: ... # undocumented diff --git a/stdlib/imaplib.pyi b/stdlib/imaplib.pyi index a9f19048c9ae..bb58d29099e5 100644 --- a/stdlib/imaplib.pyi +++ b/stdlib/imaplib.pyi @@ -1,25 +1,32 @@ import subprocess import sys import time -from _typeshed import Self +from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, Unused +from builtins import list as _list # conflicts with a method named "list" +from collections.abc import Callable, Generator +from datetime import datetime +from re import Pattern from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, List, Pattern, Tuple, Type, Union -from typing_extensions import Literal +from typing import IO, Any, Literal, SupportsAbs, SupportsInt, TypeAlias, overload +from typing_extensions import Self, deprecated + +__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] # TODO: Commands should use their actual return types, not this type alias. # E.g. Tuple[Literal["OK"], List[bytes]] -_CommandResults = Tuple[str, List[Any]] +_CommandResults: TypeAlias = tuple[str, list[Any]] -_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] +_AnyResponseData: TypeAlias = list[None] | list[bytes | tuple[bytes, bytes]] -_list = list # conflicts with a method named "list" +Commands: dict[str, tuple[str, ...]] class IMAP4: - error: Type[Exception] - abort: Type[Exception] - readonly: Type[Exception] + class error(Exception): ... + class abort(error): ... + class readonly(abort): ... + utf8_enabled: bool mustquote: Pattern[str] debug: int state: str @@ -32,27 +39,31 @@ class IMAP4: tagpre: str tagre: Pattern[str] welcome: bytes - capabilities: tuple[str] + capabilities: tuple[str, ...] PROTOCOL_VERSION: str - if sys.version_info >= (3, 9): - def __init__(self, host: str = ..., port: int = ..., timeout: float | None = ...) -> None: ... - def open(self, host: str = ..., port: int = ..., timeout: float | None = ...) -> None: ... + def __init__(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... + def open(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... + if sys.version_info >= (3, 14): + @property + @deprecated("IMAP4.file is unsupported, can cause errors, and may be removed.") + def file(self) -> IO[str] | IO[bytes]: ... else: - def __init__(self, host: str = ..., port: int = ...) -> None: ... - def open(self, host: str = ..., port: int = ...) -> None: ... + file: IO[str] | IO[bytes] + def __getattr__(self, attr: str) -> Any: ... host: str port: int sock: _socket - file: IO[str] | IO[bytes] def read(self, size: int) -> bytes: ... def readline(self) -> bytes: ... - def send(self, data: bytes) -> None: ... + def send(self, data: ReadableBuffer) -> None: ... def shutdown(self) -> None: ... def socket(self) -> _socket: ... def recent(self) -> _CommandResults: ... def response(self, code: str) -> _CommandResults: ... - def append(self, mailbox: str, flags: str, date_time: str, message: str) -> str: ... + def append( + self, mailbox: str | None, flags: str | None, date_time: _TimeLike | None, message: ReadableBuffer + ) -> tuple[str, _list[bytes]]: ... def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> tuple[str, str]: ... def capability(self) -> _CommandResults: ... def check(self) -> _CommandResults: ... @@ -62,19 +73,33 @@ class IMAP4: def delete(self, mailbox: str) -> _CommandResults: ... def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... def enable(self, capability: str) -> _CommandResults: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def expunge(self) -> _CommandResults: ... def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: ... def getacl(self, mailbox: str) -> _CommandResults: ... def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ... def getquota(self, root: str) -> _CommandResults: ... def getquotaroot(self, mailbox: str) -> _CommandResults: ... - def list(self, directory: str = ..., pattern: str = ...) -> tuple[str, _AnyResponseData]: ... + if sys.version_info >= (3, 14): + def idle(self, duration: float | None = None) -> Idler: ... + + if sys.version_info >= (3, 13): + # Default was fixed in Python 3.13.15, 3.14.7 + def list(self, directory: str = "", pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + else: + def list(self, directory: str = '""', pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + def login(self, user: str, password: str) -> tuple[Literal["OK"], _list[bytes]]: ... def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... def logout(self) -> tuple[str, _AnyResponseData]: ... - def lsub(self, directory: str = ..., pattern: str = ...) -> _CommandResults: ... + + if sys.version_info >= (3, 13): + # Default was fixed in Python 3.13.15, 3.14.7 + def lsub(self, directory: str = "", pattern: str = "*") -> _CommandResults: ... + else: + def lsub(self, directory: str = '""', pattern: str = "*") -> _CommandResults: ... + def myrights(self, mailbox: str) -> _CommandResults: ... def namespace(self) -> _CommandResults: ... def noop(self) -> tuple[str, _list[bytes]]: ... @@ -82,88 +107,106 @@ class IMAP4: def proxyauth(self, user: str) -> _CommandResults: ... def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ... def search(self, charset: str | None, *criteria: str) -> _CommandResults: ... - def select(self, mailbox: str = ..., readonly: bool = ...) -> tuple[str, _list[bytes | None]]: ... + def select(self, mailbox: str = "INBOX", readonly: bool = False) -> tuple[str, _list[bytes | None]]: ... def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... - def setannotation(self, *args: str) -> _CommandResults: ... + + if sys.version_info >= (3, 13): + # Parameter "mailbox" was added in Python 3.13.15, 3.14.7 + def setannotation(self, mailbox: str | bytes, *args: str) -> _CommandResults: ... + else: + def setannotation(self, *args: str) -> _CommandResults: ... + def setquota(self, root: str, limits: str) -> _CommandResults: ... def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... - def starttls(self, ssl_context: Any | None = ...) -> tuple[Literal["OK"], _list[None]]: ... + def starttls(self, ssl_context: Any | None = None) -> tuple[Literal["OK"], _list[None]]: ... def status(self, mailbox: str, names: str) -> _CommandResults: ... def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ... def subscribe(self, mailbox: str) -> _CommandResults: ... def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ... def uid(self, command: str, *args: str) -> _CommandResults: ... def unsubscribe(self, mailbox: str) -> _CommandResults: ... - if sys.version_info >= (3, 9): - def unselect(self) -> _CommandResults: ... + def unselect(self) -> _CommandResults: ... def xatom(self, name: str, *args: str) -> _CommandResults: ... def print_log(self) -> None: ... +if sys.version_info >= (3, 14): + class Idler: + def __init__(self, imap: IMAP4, duration: float | None = None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: Unused, exc_tb: Unused) -> Literal[False]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[str, float | None]: ... + def burst(self, interval: float = 0.1) -> Generator[tuple[str, float | None]]: ... + class IMAP4_SSL(IMAP4): - keyfile: str - certfile: str - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 12): def __init__( - self, - host: str = ..., - port: int = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - ssl_context: SSLContext | None = ..., - timeout: float | None = ..., + self, host: str = "", port: int = 993, *, ssl_context: SSLContext | None = None, timeout: float | None = None ) -> None: ... else: + @overload def __init__( self, - host: str = ..., - port: int = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - ssl_context: SSLContext | None = ..., + host: str = "", + port: int = 993, + keyfile: None = None, + certfile: None = None, + ssl_context: SSLContext | None = None, + timeout: float | None = None, ) -> None: ... - host: str - port: int - sock: _socket + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `ssl_context` parameter instead." + ) + def __init__( + self, + host: str = "", + port: int = 993, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + ssl_context: None = None, + timeout: float | None = None, + ) -> None: ... + + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None sslobj: SSLSocket - file: IO[Any] - if sys.version_info >= (3, 9): - def open(self, host: str = ..., port: int | None = ..., timeout: float | None = ...) -> None: ... + if sys.version_info >= (3, 14): + @property + @deprecated("IMAP4_SSL.file is unsupported, can cause errors, and may be removed.") + def file(self) -> IO[Any]: ... else: - def open(self, host: str = ..., port: int | None = ...) -> None: ... - def read(self, size: int) -> bytes: ... - def readline(self) -> bytes: ... - def send(self, data: bytes) -> None: ... - def shutdown(self) -> None: ... - def socket(self) -> _socket: ... + file: IO[Any] + + def open(self, host: str = "", port: int | None = 993, timeout: float | None = None) -> None: ... def ssl(self) -> SSLSocket: ... class IMAP4_stream(IMAP4): command: str def __init__(self, command: str) -> None: ... - host: str - port: int - sock: _socket - file: IO[Any] + if sys.version_info >= (3, 14): + @property + @deprecated("IMAP4_stream.file is unsupported, can cause errors, and may be removed.") + def file(self) -> IO[Any]: ... + else: + file: IO[Any] process: subprocess.Popen[bytes] writefile: IO[Any] readfile: IO[Any] - if sys.version_info >= (3, 9): - def open(self, host: str | None = ..., port: int | None = ..., timeout: float | None = ...) -> None: ... - else: - def open(self, host: str | None = ..., port: int | None = ...) -> None: ... - def read(self, size: int) -> bytes: ... - def readline(self) -> bytes: ... - def send(self, data: bytes) -> None: ... - def shutdown(self) -> None: ... + def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: ... class _Authenticator: - mech: Callable[[bytes], bytes] - def __init__(self, mechinst: Callable[[bytes], bytes]) -> None: ... + mech: Callable[[bytes], bytes | bytearray | memoryview | str | None] + def __init__(self, mechinst: Callable[[bytes], bytes | bytearray | memoryview | str | None]) -> None: ... def process(self, data: str) -> str: ... - def encode(self, inp: bytes) -> str: ... - def decode(self, inp: str) -> bytes: ... + def encode(self, inp: bytes | bytearray | memoryview) -> str: ... + def decode(self, inp: str | SizedBuffer) -> bytes: ... + +def Internaldate2tuple(resp: ReadableBuffer) -> time.struct_time | None: ... +def Int2AP(num: SupportsAbs[SupportsInt]) -> bytes: ... +def ParseFlags(resp: ReadableBuffer) -> tuple[bytes, ...]: ... + +_TimeLike: TypeAlias = float | time.struct_time | time._TimeTuple | datetime | str -def Internaldate2tuple(resp: str) -> time.struct_time: ... -def Int2AP(num: int) -> str: ... -def ParseFlags(resp: str) -> tuple[str]: ... -def Time2Internaldate(date_time: float | time.struct_time | str) -> str: ... +def Time2Internaldate(date_time: _TimeLike) -> str: ... diff --git a/stdlib/imghdr.pyi b/stdlib/imghdr.pyi index 4515cf2269b0..e45ca3eb5bdb 100644 --- a/stdlib/imghdr.pyi +++ b/stdlib/imghdr.pyi @@ -1,13 +1,17 @@ from _typeshed import StrPath -from typing import Any, BinaryIO, Callable, Protocol, overload +from collections.abc import Callable +from typing import Any, BinaryIO, Protocol, overload, type_check_only +__all__ = ["what"] + +@type_check_only class _ReadableBinary(Protocol): def tell(self) -> int: ... - def read(self, size: int) -> bytes: ... - def seek(self, offset: int) -> Any: ... + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> Any: ... @overload -def what(file: StrPath | _ReadableBinary, h: None = ...) -> str | None: ... +def what(file: StrPath | _ReadableBinary, h: None = None) -> str | None: ... @overload def what(file: Any, h: bytes) -> str | None: ... diff --git a/stdlib/imp.pyi b/stdlib/imp.pyi index 88f2e789329b..69351dede052 100644 --- a/stdlib/imp.pyi +++ b/stdlib/imp.pyi @@ -1,8 +1,4 @@ import types -from _typeshed import StrPath -from os import PathLike -from typing import IO, Any, Protocol, TypeVar - from _imp import ( acquire_lock as acquire_lock, create_dynamic as create_dynamic, @@ -14,24 +10,26 @@ from _imp import ( lock_held as lock_held, release_lock as release_lock, ) - -_T = TypeVar("_T") - -SEARCH_ERROR: int -PY_SOURCE: int -PY_COMPILED: int -C_EXTENSION: int -PY_RESOURCE: int -PKG_DIRECTORY: int -C_BUILTIN: int -PY_FROZEN: int -PY_CODERESOURCE: int -IMP_HOOK: int +from _typeshed import StrPath +from os import PathLike +from types import TracebackType +from typing import IO, Any, Final, Protocol, type_check_only + +SEARCH_ERROR: Final = 0 +PY_SOURCE: Final = 1 +PY_COMPILED: Final = 2 +C_EXTENSION: Final = 3 +PY_RESOURCE: Final = 4 +PKG_DIRECTORY: Final = 5 +C_BUILTIN: Final = 6 +PY_FROZEN: Final = 7 +PY_CODERESOURCE: Final = 8 +IMP_HOOK: Final = 9 def new_module(name: str) -> types.ModuleType: ... def get_magic() -> bytes: ... def get_tag() -> str: ... -def cache_from_source(path: StrPath, debug_override: bool | None = ...) -> str: ... +def cache_from_source(path: StrPath, debug_override: bool | None = None) -> str: ... def source_from_cache(path: StrPath) -> str: ... def get_suffixes() -> list[tuple[str, str, int]]: ... @@ -41,24 +39,25 @@ class NullImporter: # Technically, a text file has to support a slightly different set of operations than a binary file, # but we ignore that here. +@type_check_only class _FileLike(Protocol): closed: bool mode: str def read(self) -> str | bytes: ... def close(self) -> Any: ... def __enter__(self) -> Any: ... - def __exit__(self, *args: Any) -> Any: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, /) -> Any: ... # PathLike doesn't work for the pathname argument here -def load_source(name: str, pathname: str, file: _FileLike | None = ...) -> types.ModuleType: ... -def load_compiled(name: str, pathname: str, file: _FileLike | None = ...) -> types.ModuleType: ... +def load_source(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ... +def load_compiled(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ... def load_package(name: str, path: StrPath) -> types.ModuleType: ... def load_module(name: str, file: _FileLike | None, filename: str, details: tuple[str, str, int]) -> types.ModuleType: ... # IO[Any] is a TextIOWrapper if name is a .py file, and a FileIO otherwise. def find_module( - name: str, path: None | list[str] | list[PathLike[str]] | list[StrPath] = ... + name: str, path: list[str] | list[PathLike[str]] | list[StrPath] | None = None ) -> tuple[IO[Any], str, tuple[str, str, int]]: ... def reload(module: types.ModuleType) -> types.ModuleType: ... def init_builtin(name: str) -> types.ModuleType | None: ... -def load_dynamic(name: str, path: str, file: Any = ...) -> types.ModuleType: ... # file argument is ignored +def load_dynamic(name: str, path: str, file: Any = None) -> types.ModuleType: ... # file argument is ignored diff --git a/stdlib/importlib/__init__.pyi b/stdlib/importlib/__init__.pyi index 1b91cc55f2df..d60f90adee19 100644 --- a/stdlib/importlib/__init__.pyi +++ b/stdlib/importlib/__init__.pyi @@ -1,18 +1,17 @@ +import sys +from importlib._bootstrap import __import__ as __import__ from importlib.abc import Loader from types import ModuleType -from typing import Mapping, Sequence +from typing_extensions import deprecated -# Signature of `builtins.__import__` should be kept identical to `importlib.__import__` -def __import__( - name: str, - globals: Mapping[str, object] | None = ..., - locals: Mapping[str, object] | None = ..., - fromlist: Sequence[str] = ..., - level: int = ..., -) -> ModuleType: ... +__all__ = ["__import__", "import_module", "invalidate_caches", "reload"] # `importlib.import_module` return type should be kept the same as `builtins.__import__` -def import_module(name: str, package: str | None = ...) -> ModuleType: ... -def find_loader(name: str, path: str | None = ...) -> Loader | None: ... +def import_module(name: str, package: str | None = None) -> ModuleType: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `importlib.util.find_spec()` instead.") + def find_loader(name: str, path: str | None = None) -> Loader | None: ... + def invalidate_caches() -> None: ... def reload(module: ModuleType) -> ModuleType: ... diff --git a/stdlib/importlib/_abc.pyi b/stdlib/importlib/_abc.pyi new file mode 100644 index 000000000000..bf248ac1fda1 --- /dev/null +++ b/stdlib/importlib/_abc.pyi @@ -0,0 +1,21 @@ +import sys +import types +from abc import ABCMeta +from importlib.machinery import ModuleSpec +from typing_extensions import deprecated + +class Loader(metaclass=ABCMeta): + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + if sys.version_info < (3, 12): + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(self, module: types.ModuleType) -> str: ... + + def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... + # Not defined on the actual class for backwards-compatibility reasons, + # but expected in new code. + def exec_module(self, module: types.ModuleType) -> None: ... diff --git a/stdlib/importlib/_bootstrap.pyi b/stdlib/importlib/_bootstrap.pyi new file mode 100644 index 000000000000..02427ff42062 --- /dev/null +++ b/stdlib/importlib/_bootstrap.pyi @@ -0,0 +1,2 @@ +from _frozen_importlib import * +from _frozen_importlib import __import__ as __import__, _init_module_attrs as _init_module_attrs diff --git a/stdlib/importlib/_bootstrap_external.pyi b/stdlib/importlib/_bootstrap_external.pyi new file mode 100644 index 000000000000..6210ce7083af --- /dev/null +++ b/stdlib/importlib/_bootstrap_external.pyi @@ -0,0 +1,2 @@ +from _frozen_importlib_external import * +from _frozen_importlib_external import _NamespaceLoader as _NamespaceLoader diff --git a/stdlib/importlib/abc.pyi b/stdlib/importlib/abc.pyi index 9bb370dfd7e8..dffe99b86405 100644 --- a/stdlib/importlib/abc.pyi +++ b/stdlib/importlib/abc.pyi @@ -1,100 +1,119 @@ +import _ast import sys import types -from _typeshed import ( - OpenBinaryMode, - OpenBinaryModeReading, - OpenBinaryModeUpdating, - OpenBinaryModeWriting, - OpenTextMode, - StrOrBytesPath, - StrPath, -) +from _typeshed import ReadableBuffer, StrPath from abc import ABCMeta, abstractmethod +from collections.abc import Iterable, Iterator, Mapping, Sequence +from importlib import _bootstrap_external +from importlib._abc import Loader as Loader from importlib.machinery import ModuleSpec -from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, Union, overload, runtime_checkable -from typing_extensions import Literal +from io import BufferedReader +from typing import IO, Any, Literal, Protocol, overload, runtime_checkable +from typing_extensions import deprecated -_Path = Union[bytes, str] +if sys.version_info >= (3, 11): + __all__ = [ + "Loader", + "MetaPathFinder", + "PathEntryFinder", + "ResourceLoader", + "InspectLoader", + "ExecutionLoader", + "FileLoader", + "SourceLoader", + ] -class Finder(metaclass=ABCMeta): ... + if sys.version_info < (3, 12): + __all__ += ["Finder", "ResourceReader", "Traversable", "TraversableResources"] +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use `MetaPathFinder` or `PathEntryFinder` instead.") + class Finder(metaclass=ABCMeta): ... + +@deprecated("Deprecated since Python 3.7. Use `importlib.resources.abc.TraversableResources` instead.") class ResourceLoader(Loader): @abstractmethod - def get_data(self, path: _Path) -> bytes: ... + def get_data(self, path: str) -> bytes: ... class InspectLoader(Loader): def is_package(self, fullname: str) -> bool: ... def get_code(self, fullname: str) -> types.CodeType | None: ... - def load_module(self, fullname: str) -> types.ModuleType: ... @abstractmethod def get_source(self, fullname: str) -> str | None: ... def exec_module(self, module: types.ModuleType) -> None: ... - @staticmethod - def source_to_code(data: bytes | str, path: str = ...) -> types.CodeType: ... + + if sys.version_info >= (3, 15): + @staticmethod + def source_to_code( + data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, + path: bytes | StrPath = "", + fullname: str | None = None, + ) -> types.CodeType: ... + else: + @staticmethod + def source_to_code( + data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: bytes | StrPath = "" + ) -> types.CodeType: ... class ExecutionLoader(InspectLoader): @abstractmethod - def get_filename(self, fullname: str) -> _Path: ... - def get_code(self, fullname: str) -> types.CodeType | None: ... + def get_filename(self, fullname: str) -> str: ... -class SourceLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): - def path_mtime(self, path: _Path) -> float: ... - def set_data(self, path: _Path, data: bytes) -> None: ... +class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): # type: ignore[misc] # incompatible definitions of source_to_code in the base classes + @deprecated("Deprecated since Python 3.3. Use `importlib.resources.abc.SourceLoader.path_stats` instead.") + def path_mtime(self, path: str) -> float: ... + def set_data(self, path: str, data: bytes) -> None: ... def get_source(self, fullname: str) -> str | None: ... - def path_stats(self, path: _Path) -> Mapping[str, Any]: ... + def path_stats(self, path: str) -> Mapping[str, Any]: ... + +# Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol +class MetaPathFinder(metaclass=ABCMeta): + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `MetaPathFinder.find_spec()` instead.") + def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... -# Please keep in sync with sys._MetaPathFinder -class MetaPathFinder(Finder): - def find_module(self, fullname: str, path: Sequence[_Path] | None) -> Loader | None: ... def invalidate_caches(self) -> None: ... # Not defined on the actual class, but expected to exist. def find_spec( - self, fullname: str, path: Sequence[_Path] | None, target: types.ModuleType | None = ... + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / ) -> ModuleSpec | None: ... + if sys.version_info >= (3, 15): + def discover(self, parent: ModuleSpec | None = None) -> Iterable[ModuleSpec]: ... + +class PathEntryFinder(metaclass=ABCMeta): + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `PathEntryFinder.find_spec()` instead.") + def find_module(self, fullname: str) -> Loader | None: ... + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... -class PathEntryFinder(Finder): - def find_module(self, fullname: str) -> Loader | None: ... - def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[_Path]]: ... def invalidate_caches(self) -> None: ... # Not defined on the actual class, but expected to exist. def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... + if sys.version_info >= (3, 15): + def discover(self, parent: ModuleSpec | None = None) -> Iterable[ModuleSpec]: ... -class Loader(metaclass=ABCMeta): - def load_module(self, fullname: str) -> types.ModuleType: ... - def module_repr(self, module: types.ModuleType) -> str: ... - def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... - # Not defined on the actual class for backwards-compatibility reasons, - # but expected in new code. - def exec_module(self, module: types.ModuleType) -> None: ... - -class _LoaderProtocol(Protocol): - def load_module(self, fullname: str) -> types.ModuleType: ... - -class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): +class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): name: str - path: _Path - def __init__(self, fullname: str, path: _Path) -> None: ... - def get_data(self, path: _Path) -> bytes: ... - def get_filename(self, name: str | None = ...) -> _Path: ... - def load_module(self, name: str | None = ...) -> types.ModuleType: ... + path: str + def __init__(self, fullname: str, path: str) -> None: ... + def get_data(self, path: str) -> bytes: ... + def get_filename(self, fullname: str | None = None) -> str: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str | None = None) -> types.ModuleType: ... -if sys.version_info >= (3, 7): +if sys.version_info < (3, 11): class ResourceReader(metaclass=ABCMeta): @abstractmethod - def open_resource(self, resource: StrOrBytesPath) -> IO[bytes]: ... + def open_resource(self, resource: str) -> IO[bytes]: ... @abstractmethod - def resource_path(self, resource: StrOrBytesPath) -> str: ... - if sys.version_info >= (3, 10): - @abstractmethod - def is_resource(self, path: str) -> bool: ... - else: - @abstractmethod - def is_resource(self, name: str) -> bool: ... + def resource_path(self, resource: str) -> str: ... + @abstractmethod + def is_resource(self, path: str) -> bool: ... @abstractmethod def contents(self) -> Iterator[str]: ... -if sys.version_info >= (3, 9): @runtime_checkable class Traversable(Protocol): @abstractmethod @@ -103,80 +122,44 @@ if sys.version_info >= (3, 9): def is_file(self) -> bool: ... @abstractmethod def iterdir(self) -> Iterator[Traversable]: ... - @abstractmethod - def joinpath(self, child: StrPath) -> Traversable: ... - # The .open method comes from pathlib.pyi and should be kept in sync. - @overload - @abstractmethod - def open( - self, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - ) -> TextIOWrapper: ... - # Unbuffered binary mode: returns a FileIO - @overload - @abstractmethod - def open( - self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... - ) -> FileIO: ... - # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter - @overload - @abstractmethod - def open( - self, - mode: OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BufferedRandom: ... - @overload - @abstractmethod - def open( - self, - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BufferedWriter: ... - @overload - @abstractmethod - def open( - self, - mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BufferedReader: ... - # Buffering cannot be determined: fall back to BinaryIO + + if sys.version_info >= (3, 11): + @abstractmethod + def joinpath(self, *descendants: str) -> Traversable: ... + else: + @abstractmethod + def joinpath(self, child: str, /) -> Traversable: ... + + # The documentation and runtime protocol allows *args, **kwargs arguments, + # but this would mean that all implementers would have to support them, + # which is not the case. @overload @abstractmethod - def open( - self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... - ) -> BinaryIO: ... - # Fallback if mode is not specified + def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... @overload @abstractmethod - def open( - self, mode: str, buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ... - ) -> IO[Any]: ... + def open(self, mode: Literal["rb"]) -> IO[bytes]: ... + @property - def name(self) -> str: ... @abstractmethod - def __truediv__(self, key: StrPath) -> Traversable: ... + def name(self) -> str: ... + def __truediv__(self, child: str, /) -> Traversable: ... @abstractmethod def read_bytes(self) -> bytes: ... @abstractmethod - def read_text(self, encoding: str | None = ...) -> str: ... + def read_text(self, encoding: str | None = None) -> str: ... + class TraversableResources(ResourceReader): @abstractmethod def files(self) -> Traversable: ... - def open_resource(self, resource: StrPath) -> BufferedReader: ... # type: ignore[override] - def resource_path(self, resource: Any) -> NoReturn: ... - def is_resource(self, path: StrPath) -> bool: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def resource_path(self, resource: Any) -> str: ... + def is_resource(self, path: str) -> bool: ... def contents(self) -> Iterator[str]: ... + +elif sys.version_info < (3, 14): + from importlib.resources.abc import ( + ResourceReader as ResourceReader, + Traversable as Traversable, + TraversableResources as TraversableResources, + ) diff --git a/stdlib/importlib/machinery.pyi b/stdlib/importlib/machinery.pyi index b73f9c527583..767046b70a3d 100644 --- a/stdlib/importlib/machinery.pyi +++ b/stdlib/importlib/machinery.pyi @@ -1,144 +1,43 @@ -import importlib.abc import sys -import types -from typing import Any, Callable, Iterable, Sequence - -if sys.version_info >= (3, 8): - from importlib.metadata import DistributionFinder, PathDistribution - -class ModuleSpec: - def __init__( - self, - name: str, - loader: importlib.abc.Loader | None, - *, - origin: str | None = ..., - loader_state: Any = ..., - is_package: bool | None = ..., - ) -> None: ... - name: str - loader: importlib.abc.Loader | None - origin: str | None - submodule_search_locations: list[str] | None - loader_state: Any - cached: str | None - parent: str | None - has_location: bool - -class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): - # MetaPathFinder - @classmethod - def find_module(cls, fullname: str, path: Sequence[importlib.abc._Path] | None = ...) -> importlib.abc.Loader | None: ... - @classmethod - def find_spec( - cls, fullname: str, path: Sequence[importlib.abc._Path] | None = ..., target: types.ModuleType | None = ... - ) -> ModuleSpec | None: ... - # InspectLoader - @classmethod - def is_package(cls, fullname: str) -> bool: ... - @classmethod - def load_module(cls, fullname: str) -> types.ModuleType: ... - @classmethod - def get_code(cls, fullname: str) -> None: ... - @classmethod - def get_source(cls, fullname: str) -> None: ... - # Loader - @staticmethod - def module_repr(module: types.ModuleType) -> str: ... - if sys.version_info >= (3, 10): - @staticmethod - def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... - @staticmethod - def exec_module(module: types.ModuleType) -> None: ... - else: - @classmethod - def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... - @classmethod - def exec_module(cls, module: types.ModuleType) -> None: ... - -class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): - # MetaPathFinder - @classmethod - def find_module(cls, fullname: str, path: Sequence[importlib.abc._Path] | None = ...) -> importlib.abc.Loader | None: ... - @classmethod - def find_spec( - cls, fullname: str, path: Sequence[importlib.abc._Path] | None = ..., target: types.ModuleType | None = ... - ) -> ModuleSpec | None: ... - # InspectLoader - @classmethod - def is_package(cls, fullname: str) -> bool: ... - @classmethod - def load_module(cls, fullname: str) -> types.ModuleType: ... - @classmethod - def get_code(cls, fullname: str) -> None: ... - @classmethod - def get_source(cls, fullname: str) -> None: ... - # Loader - @staticmethod - def module_repr(m: types.ModuleType) -> str: ... - if sys.version_info >= (3, 10): - @staticmethod - def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... - else: - @classmethod - def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... - @staticmethod - def exec_module(module: types.ModuleType) -> None: ... - -class WindowsRegistryFinder(importlib.abc.MetaPathFinder): - @classmethod - def find_module(cls, fullname: str, path: Sequence[importlib.abc._Path] | None = ...) -> importlib.abc.Loader | None: ... - @classmethod - def find_spec( - cls, fullname: str, path: Sequence[importlib.abc._Path] | None = ..., target: types.ModuleType | None = ... - ) -> ModuleSpec | None: ... - -class PathFinder: - if sys.version_info >= (3, 10): - @staticmethod - def invalidate_caches() -> None: ... - else: - @classmethod - def invalidate_caches(cls) -> None: ... - if sys.version_info >= (3, 10): - @staticmethod - def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - elif sys.version_info >= (3, 8): - @classmethod - def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - @classmethod - def find_spec( - cls, fullname: str, path: Sequence[bytes | str] | None = ..., target: types.ModuleType | None = ... - ) -> ModuleSpec | None: ... - @classmethod - def find_module(cls, fullname: str, path: Sequence[bytes | str] | None = ...) -> importlib.abc.Loader | None: ... - -SOURCE_SUFFIXES: list[str] -DEBUG_BYTECODE_SUFFIXES: list[str] -OPTIMIZED_BYTECODE_SUFFIXES: list[str] -BYTECODE_SUFFIXES: list[str] -EXTENSION_SUFFIXES: list[str] +from importlib._bootstrap import BuiltinImporter as BuiltinImporter, FrozenImporter as FrozenImporter, ModuleSpec as ModuleSpec +from importlib._bootstrap_external import ( + BYTECODE_SUFFIXES as BYTECODE_SUFFIXES, + DEBUG_BYTECODE_SUFFIXES as DEBUG_BYTECODE_SUFFIXES, + EXTENSION_SUFFIXES as EXTENSION_SUFFIXES, + OPTIMIZED_BYTECODE_SUFFIXES as OPTIMIZED_BYTECODE_SUFFIXES, + SOURCE_SUFFIXES as SOURCE_SUFFIXES, + ExtensionFileLoader as ExtensionFileLoader, + FileFinder as FileFinder, + PathFinder as PathFinder, + SourceFileLoader as SourceFileLoader, + SourcelessFileLoader as SourcelessFileLoader, + WindowsRegistryFinder as WindowsRegistryFinder, +) + +if sys.version_info >= (3, 11): + from importlib._bootstrap_external import NamespaceLoader as NamespaceLoader +if sys.version_info >= (3, 14): + from importlib._bootstrap_external import AppleFrameworkLoader as AppleFrameworkLoader def all_suffixes() -> list[str]: ... -class FileFinder(importlib.abc.PathEntryFinder): - path: str - def __init__(self, path: str, *loader_details: tuple[importlib.abc.Loader, list[str]]) -> None: ... - @classmethod - def path_hook( - cls, *loader_details: tuple[importlib.abc.Loader, list[str]] - ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... - -class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): - def set_data(self, path: importlib.abc._Path, data: bytes, *, _mode: int = ...) -> None: ... - -class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... - -class ExtensionFileLoader(importlib.abc.ExecutionLoader): - def __init__(self, name: str, path: importlib.abc._Path) -> None: ... - def get_filename(self, name: str | None = ...) -> importlib.abc._Path: ... - def get_source(self, fullname: str) -> None: ... - def create_module(self, spec: ModuleSpec) -> types.ModuleType: ... - def exec_module(self, module: types.ModuleType) -> None: ... - def is_package(self, fullname: str) -> bool: ... - def get_code(self, fullname: str) -> None: ... +if sys.version_info >= (3, 14): + __all__ = [ + "AppleFrameworkLoader", + "BYTECODE_SUFFIXES", + "BuiltinImporter", + "DEBUG_BYTECODE_SUFFIXES", + "EXTENSION_SUFFIXES", + "ExtensionFileLoader", + "FileFinder", + "FrozenImporter", + "ModuleSpec", + "NamespaceLoader", + "OPTIMIZED_BYTECODE_SUFFIXES", + "PathFinder", + "SOURCE_SUFFIXES", + "SourceFileLoader", + "SourcelessFileLoader", + "WindowsRegistryFinder", + "all_suffixes", + ] diff --git a/stdlib/importlib/metadata/__init__.pyi b/stdlib/importlib/metadata/__init__.pyi index c5d9efba9ad6..866fd969e2fe 100644 --- a/stdlib/importlib/metadata/__init__.pyi +++ b/stdlib/importlib/metadata/__init__.pyi @@ -1,106 +1,310 @@ import abc import pathlib import sys +import types +from _collections_abc import dict_keys, dict_values from _typeshed import StrPath -from collections.abc import Mapping -from email.message import Message +from collections.abc import Iterable, Iterator, Mapping from importlib.abc import MetaPathFinder +from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath from os import PathLike -from pathlib import Path -from typing import Any, ClassVar, Iterable, NamedTuple, Pattern, Tuple, overload +from re import Pattern +from typing import Any, ClassVar, Generic, NamedTuple, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base -if sys.version_info >= (3, 10): - from importlib.metadata._meta import PackageMetadata as PackageMetadata - def packages_distributions() -> Mapping[str, list[str]]: ... +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") -if sys.version_info >= (3, 8): - class PackageNotFoundError(ModuleNotFoundError): ... +__all__ = [ + "Distribution", + "DistributionFinder", + "PackageMetadata", + "PackageNotFoundError", + "distribution", + "distributions", + "entry_points", + "files", + "metadata", + "packages_distributions", + "requires", + "version", +] + +if sys.version_info >= (3, 15): + __all__ += ["PackagePath", "MetadataNotFound", "SimplePath"] + +_SimplePath: TypeAlias = SimplePath + +def packages_distributions() -> Mapping[str, list[str]]: ... + +class PackageNotFoundError(ModuleNotFoundError): + @property + def name(self) -> str: ... # type: ignore[override] + +if sys.version_info >= (3, 15): + class MetadataNotFound(FileNotFoundError): ... + +if sys.version_info >= (3, 13): + _EntryPointBase = object +elif sys.version_info >= (3, 11): + class DeprecatedTuple: + def __getitem__(self, item: int) -> str: ... + + _EntryPointBase = DeprecatedTuple +else: + @type_check_only class _EntryPointBase(NamedTuple): name: str value: str group: str + +if sys.version_info >= (3, 11): class EntryPoint(_EntryPointBase): pattern: ClassVar[Pattern[str]] + name: str + value: str + group: str + + def __init__(self, name: str, value: str, group: str) -> None: ... def load(self) -> Any: ... # Callable[[], Any] or an importable module @property def extras(self) -> list[str]: ... - if sys.version_info >= (3, 9): - @property - def module(self) -> str: ... - @property - def attr(self) -> str: ... - if sys.version_info >= (3, 10): - dist: ClassVar[Distribution | None] - def matches(self, **params: Any) -> bool: ... # undocumented - class PackagePath(pathlib.PurePosixPath): - def read_text(self, encoding: str = ...) -> str: ... - def read_binary(self) -> bytes: ... - def locate(self) -> PathLike[str]: ... - # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: - hash: FileHash | None - size: int | None - dist: Distribution - class FileHash: - mode: str - value: str - def __init__(self, spec: str) -> None: ... - class Distribution: - @abc.abstractmethod - def read_text(self, filename: str) -> str | None: ... - @abc.abstractmethod - def locate_file(self, path: StrPath) -> PathLike[str]: ... - @classmethod - def from_name(cls, name: str) -> Distribution: ... + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... + dist: ClassVar[Distribution | None] + def matches( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> bool: ... # undocumented + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + if sys.version_info < (3, 12): + def __iter__(self) -> Iterator[Any]: ... # result of iter((str, Self)), really + +else: + @disjoint_base + class EntryPoint(_EntryPointBase): + pattern: ClassVar[Pattern[str]] + + def load(self) -> Any: ... # Callable[[], Any] or an importable module + @property + def extras(self) -> list[str]: ... + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... + dist: ClassVar[Distribution | None] + def matches( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> bool: ... # undocumented + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[Any]: ... # result of iter((str, Self)), really + +if sys.version_info >= (3, 12): + class EntryPoints(tuple[EntryPoint, ...]): + __slots__ = () + def __getitem__(self, name: str) -> EntryPoint: ... # type: ignore[override] + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + @property + def names(self) -> set[str]: ... + @property + def groups(self) -> set[str]: ... + +else: + class DeprecatedList(list[_T]): + __slots__ = () + + class EntryPoints(DeprecatedList[EntryPoint]): # use as list is deprecated since 3.10 + # int argument is deprecated since 3.10 + __slots__ = () + def __getitem__(self, name: int | str) -> EntryPoint: ... # type: ignore[override] + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + @property + def names(self) -> set[str]: ... + @property + def groups(self) -> set[str]: ... + +if sys.version_info < (3, 12): + class Deprecated(Generic[_KT, _VT]): + def __getitem__(self, name: _KT) -> _VT: ... + @overload - @classmethod - def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + def get(self, name: _KT, default: None = None) -> _VT | None: ... @overload + def get(self, name: _KT, default: _VT) -> _VT: ... + @overload + def get(self, name: _KT, default: _T) -> _VT | _T: ... + + def __iter__(self) -> Iterator[_KT]: ... + def __contains__(self, *args: object) -> bool: ... + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `select` instead.") + class SelectableGroups(Deprecated[str, EntryPoints], dict[str, EntryPoints]): # use as dict is deprecated since 3.10 @classmethod - def discover( - cls, *, context: None = ..., name: str | None = ..., path: list[str] = ..., **kwargs: Any - ) -> Iterable[Distribution]: ... - @staticmethod - def at(path: StrPath) -> PathDistribution: ... - @property - def metadata(self) -> Message: ... + def load(cls, eps: Iterable[EntryPoint]) -> Self: ... @property - def version(self) -> str: ... + def groups(self) -> set[str]: ... @property - def entry_points(self) -> list[EntryPoint]: ... + def names(self) -> set[str]: ... + + @overload + def select(self) -> Self: ... + @overload + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + +class PackagePath(pathlib.PurePosixPath): + def read_text(self, encoding: str = "utf-8") -> str: ... + def read_binary(self) -> bytes: ... + def locate(self) -> PathLike[str]: ... + # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: + hash: FileHash | None + size: int | None + dist: Distribution + +class FileHash: + mode: str + value: str + def __init__(self, spec: str) -> None: ... + +if sys.version_info >= (3, 15): + _distribution_parent = abc.ABC +elif sys.version_info >= (3, 12): + class DeprecatedNonAbstract: ... + _distribution_parent = DeprecatedNonAbstract +else: + _distribution_parent = object + +class Distribution(_distribution_parent): + @abc.abstractmethod + def read_text(self, filename: str) -> str | None: ... + @abc.abstractmethod + def locate_file(self, path: StrPath) -> _SimplePath: ... + @classmethod + def from_name(cls, name: str) -> Distribution: ... + + @overload + @classmethod + def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + @overload + @classmethod + def discover( + cls, *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + + @staticmethod + def at(path: StrPath) -> PathDistribution: ... + @property + def metadata(self) -> PackageMetadata: ... + @property + def entry_points(self) -> EntryPoints: ... + @property + def version(self) -> str: ... + @property + def files(self) -> list[PackagePath] | None: ... + @property + def requires(self) -> list[str] | None: ... + @property + def name(self) -> str: ... + if sys.version_info >= (3, 13): @property - def files(self) -> list[PackagePath] | None: ... + def origin(self) -> types.SimpleNamespace | None: ... + +class DistributionFinder(MetaPathFinder): + class Context: + name: str | None + def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ... @property - def requires(self) -> list[str] | None: ... - if sys.version_info >= (3, 10): - @property - def name(self) -> str: ... - class DistributionFinder(MetaPathFinder): - class Context: - name: str | None - def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ... - @property - def path(self) -> list[str]: ... - @abc.abstractmethod - def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... - class MetadataPathFinder(DistributionFinder): + def path(self) -> list[str]: ... + + @abc.abstractmethod + def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... + +class MetadataPathFinder(DistributionFinder): + @classmethod + def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + if sys.version_info >= (3, 11): @classmethod - def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - if sys.version_info >= (3, 10): - # Yes, this is an instance method that has argumend named "cls" - def invalidate_caches(cls) -> None: ... # type: ignore - class PathDistribution(Distribution): - def __init__(self, path: Path) -> None: ... - def read_text(self, filename: StrPath) -> str: ... - def locate_file(self, path: StrPath) -> PathLike[str]: ... - def distribution(distribution_name: str) -> Distribution: ... + def invalidate_caches(cls) -> None: ... + else: + # Yes, this is an instance method that has a parameter named "cls" + def invalidate_caches(cls) -> None: ... + +class PathDistribution(Distribution): + _path: _SimplePath + def __init__(self, path: _SimplePath) -> None: ... + def read_text(self, filename: StrPath) -> str | None: ... + def locate_file(self, path: StrPath) -> _SimplePath: ... + +def distribution(distribution_name: str) -> Distribution: ... + +@overload +def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... +@overload +def distributions( + *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any +) -> Iterable[Distribution]: ... + +def metadata(distribution_name: str) -> PackageMetadata: ... + +if sys.version_info >= (3, 12): + def entry_points( + *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... + ) -> EntryPoints: ... + +else: @overload - def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + def entry_points() -> SelectableGroups: ... @overload - def distributions( - *, context: None = ..., name: str | None = ..., path: list[str] = ..., **kwargs: Any - ) -> Iterable[Distribution]: ... - def metadata(distribution_name: str) -> Message: ... - def version(distribution_name: str) -> str: ... - def entry_points() -> dict[str, Tuple[EntryPoint, ...]]: ... - def files(distribution_name: str) -> list[PackagePath] | None: ... - def requires(distribution_name: str) -> list[str] | None: ... + def entry_points( + *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... + ) -> EntryPoints: ... + +def version(distribution_name: str) -> str: ... +def files(distribution_name: str) -> list[PackagePath] | None: ... +def requires(distribution_name: str) -> list[str] | None: ... diff --git a/stdlib/importlib/metadata/_meta.pyi b/stdlib/importlib/metadata/_meta.pyi index a5e5733396d7..b9bad7b8a6b0 100644 --- a/stdlib/importlib/metadata/_meta.pyi +++ b/stdlib/importlib/metadata/_meta.pyi @@ -1,18 +1,65 @@ -from typing import Any, Iterator, Protocol, TypeVar +import sys +from _typeshed import StrPath +from collections.abc import Iterator +from os import PathLike +from typing import Any, Protocol, overload +from typing_extensions import TypeVar _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True, default=Any) class PackageMetadata(Protocol): def __len__(self) -> int: ... def __contains__(self, item: str) -> bool: ... def __getitem__(self, key: str) -> str: ... def __iter__(self) -> Iterator[str]: ... - def get_all(self, name: str, failobj: _T = ...) -> list[Any] | _T: ... @property def json(self) -> dict[str, str | list[str]]: ... -class SimplePath(Protocol): - def joinpath(self) -> SimplePath: ... - def __div__(self) -> SimplePath: ... - def parent(self) -> SimplePath: ... - def read_text(self) -> str: ... + @overload + def get_all(self, name: str, failobj: None = None) -> list[Any] | None: ... + @overload + def get_all(self, name: str, failobj: _T) -> list[Any] | _T: ... + + if sys.version_info >= (3, 12): + @overload + def get(self, name: str, failobj: None = None) -> str | None: ... + @overload + def get(self, name: str, failobj: _T) -> _T | str: ... + +if sys.version_info >= (3, 13): + class SimplePath(Protocol): + def joinpath(self, other: StrPath, /) -> SimplePath: ... + def __truediv__(self, other: StrPath, /) -> SimplePath: ... + # Incorrect at runtime + @property + def parent(self) -> PathLike[str]: ... + def read_text(self, encoding: str | None = None) -> str: ... + def read_bytes(self) -> bytes: ... + def exists(self) -> bool: ... + +elif sys.version_info >= (3, 12): + class SimplePath(Protocol[_T_co]): + # At runtime this is defined as taking `str | _T`, but that causes trouble. + # See #11436. + def joinpath(self, other: str, /) -> _T_co: ... + @property + def parent(self) -> _T_co: ... + def read_text(self) -> str: ... + # As with joinpath(), this is annotated as taking `str | _T` at runtime. + def __truediv__(self, other: str, /) -> _T_co: ... + +else: + class SimplePath(Protocol): + # Actually takes only self at runtime, but that's clearly wrong + def joinpath(self, other: Any, /) -> SimplePath: ... + # Not defined as a property at runtime, but it should be + @property + def parent(self) -> Any: ... + def read_text(self) -> str: ... + # There was a bug in `SimplePath` definition in cpython, see #8451 + # Strictly speaking `__div__` was defined in 3.10, not __truediv__, + # but it should have always been `__truediv__`. + # Also, the runtime defines this method as taking no arguments, + # which is obviously wrong. + def __truediv__(self, other: Any, /) -> SimplePath: ... diff --git a/stdlib/importlib/metadata/diagnose.pyi b/stdlib/importlib/metadata/diagnose.pyi new file mode 100644 index 000000000000..565872fd976f --- /dev/null +++ b/stdlib/importlib/metadata/diagnose.pyi @@ -0,0 +1,2 @@ +def inspect(path: str) -> None: ... +def run() -> None: ... diff --git a/stdlib/importlib/readers.pyi b/stdlib/importlib/readers.pyi new file mode 100644 index 000000000000..c02f29d0a722 --- /dev/null +++ b/stdlib/importlib/readers.pyi @@ -0,0 +1,69 @@ +# On py311+, things are actually defined in importlib.resources.readers, +# and re-exported here, +# but doing it this way leads to less code duplication for us + +import pathlib +import sys +import zipfile +from _typeshed import StrPath +from collections.abc import Iterable, Iterator +from importlib._bootstrap_external import FileLoader +from io import BufferedReader +from typing import Literal, TypeVar +from typing_extensions import Never +from zipimport import zipimporter + +if sys.version_info >= (3, 11): + from importlib.resources import abc +else: + from importlib import abc + +if sys.version_info >= (3, 11): + __all__ = ["FileReader", "ZipReader", "MultiplexedPath", "NamespaceReader"] + +if sys.version_info < (3, 11): + _T = TypeVar("_T") + + def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ... + +class FileReader(abc.TraversableResources): + path: pathlib.Path + def __init__(self, loader: FileLoader) -> None: ... + def resource_path(self, resource: StrPath) -> str: ... + def files(self) -> pathlib.Path: ... + +class ZipReader(abc.TraversableResources): + prefix: str + archive: str + def __init__(self, loader: zipimporter, module: str) -> None: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def is_resource(self, path: StrPath) -> bool: ... + def files(self) -> zipfile.Path: ... + +class MultiplexedPath(abc.Traversable): + def __init__(self, *paths: abc.Traversable) -> None: ... + def iterdir(self) -> Iterator[abc.Traversable]: ... + def read_bytes(self) -> Never: ... + def read_text(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + def is_dir(self) -> Literal[True]: ... + def is_file(self) -> Literal[False]: ... + + if sys.version_info >= (3, 12): + def joinpath(self, *descendants: StrPath) -> abc.Traversable: ... + elif sys.version_info >= (3, 11): + def joinpath(self, child: StrPath) -> abc.Traversable: ... # type: ignore[override] + else: + def joinpath(self, child: str) -> abc.Traversable: ... + + if sys.version_info < (3, 12): + __truediv__ = joinpath + + def open(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + @property + def name(self) -> str: ... + +class NamespaceReader(abc.TraversableResources): + path: MultiplexedPath + def __init__(self, namespace_path: Iterable[str]) -> None: ... + def resource_path(self, resource: str) -> str: ... + def files(self) -> MultiplexedPath: ... diff --git a/stdlib/importlib/resources.pyi b/stdlib/importlib/resources.pyi deleted file mode 100644 index b484d7126b21..000000000000 --- a/stdlib/importlib/resources.pyi +++ /dev/null @@ -1,28 +0,0 @@ -import sys -from typing import Any - -# This is a >=3.7 module, so we conditionally include its source. -if sys.version_info >= (3, 7): - import os - from contextlib import AbstractContextManager - from pathlib import Path - from types import ModuleType - from typing import BinaryIO, Iterator, TextIO, Union - - Package = Union[str, ModuleType] - Resource = Union[str, os.PathLike[Any]] - def open_binary(package: Package, resource: Resource) -> BinaryIO: ... - def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... - def read_binary(package: Package, resource: Resource) -> bytes: ... - def read_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> str: ... - def path(package: Package, resource: Resource) -> AbstractContextManager[Path]: ... - def is_resource(package: Package, name: str) -> bool: ... - def contents(package: Package) -> Iterator[str]: ... - -if sys.version_info >= (3, 9): - from importlib.abc import Traversable - def files(package: Package) -> Traversable: ... - def as_file(path: Traversable) -> AbstractContextManager[Path]: ... - -if sys.version_info >= (3, 10): - from importlib.abc import ResourceReader as ResourceReader diff --git a/stdlib/importlib/resources/__init__.pyi b/stdlib/importlib/resources/__init__.pyi new file mode 100644 index 000000000000..4d3072ffe854 --- /dev/null +++ b/stdlib/importlib/resources/__init__.pyi @@ -0,0 +1,81 @@ +import os +import sys +from collections.abc import Iterator +from contextlib import AbstractContextManager +from pathlib import Path +from types import ModuleType +from typing import Any, BinaryIO, Literal, TextIO, TypeAlias +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: + from importlib.abc import Traversable + +if sys.version_info >= (3, 11): + from importlib.resources._common import Package as Package +else: + Package: TypeAlias = str | ModuleType + +__all__ = [ + "Package", + "ResourceReader", + "as_file", + "contents", + "files", + "is_resource", + "open_binary", + "open_text", + "path", + "read_binary", + "read_text", +] + +if sys.version_info < (3, 13): + __all__ += ["Resource"] + +if sys.version_info < (3, 11): + Resource: TypeAlias = str | os.PathLike[Any] +elif sys.version_info < (3, 13): + Resource: TypeAlias = str + +if sys.version_info >= (3, 12): + from importlib.resources._common import Anchor as Anchor + + __all__ += ["Anchor"] + +if sys.version_info >= (3, 13): + from importlib.resources._functional import ( + contents as contents, + is_resource as is_resource, + open_binary as open_binary, + open_text as open_text, + path as path, + read_binary as read_binary, + read_text as read_text, + ) + +else: + def open_binary(package: Package, resource: Resource) -> BinaryIO: ... + def open_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> TextIO: ... + def read_binary(package: Package, resource: Resource) -> bytes: ... + def read_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> str: ... + def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: ... + def is_resource(package: Package, name: str) -> bool: ... + @deprecated("Deprecated; limited resource support. Use `files(anchor).iterdir()`.") + def contents(package: Package) -> Iterator[str]: ... + +if sys.version_info >= (3, 11): + from importlib.resources._common import as_file as as_file +else: + def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... + +if sys.version_info >= (3, 11): + from importlib.resources._common import files as files +else: + def files(package: Package) -> Traversable: ... + +if sys.version_info >= (3, 11): + from importlib.resources.abc import ResourceReader as ResourceReader +else: + from importlib.abc import ResourceReader as ResourceReader diff --git a/stdlib/importlib/resources/_common.pyi b/stdlib/importlib/resources/_common.pyi new file mode 100644 index 000000000000..c0a96fa38fa4 --- /dev/null +++ b/stdlib/importlib/resources/_common.pyi @@ -0,0 +1,48 @@ +import sys + +# Even though this file is 3.11+ only, Pyright will complain in stubtest for older versions. +if sys.version_info >= (3, 11): + import types + from collections.abc import Callable + from contextlib import AbstractContextManager + from importlib.resources.abc import ResourceReader, Traversable + from pathlib import Path + from typing import Literal, TypeAlias, overload + from typing_extensions import deprecated + + Package: TypeAlias = str | types.ModuleType + + if sys.version_info >= (3, 15): + Anchor: TypeAlias = Package + + def files(anchor: Anchor | None = None) -> Traversable: ... + elif sys.version_info >= (3, 12): + Anchor: TypeAlias = Package + + @deprecated("Deprecated since Python 3.12; removed in Python 3.15.") + def package_to_anchor( + func: Callable[[Anchor | None], Traversable], + ) -> Callable[[Anchor | None, Anchor | None], Traversable]: ... + + @overload + def files(anchor: Anchor | None = None) -> Traversable: ... + @overload + @deprecated("Deprecated since Python 3.12; removed in Python 3.15. Use `anchor` parameter instead.") + def files(package: Anchor | None = None) -> Traversable: ... + + else: + def files(package: Package) -> Traversable: ... + + def get_resource_reader(package: types.ModuleType) -> ResourceReader | None: ... + + if sys.version_info >= (3, 12): + def resolve(cand: Anchor | None) -> types.ModuleType: ... + + else: + def resolve(cand: Package) -> types.ModuleType: ... + + if sys.version_info < (3, 12): + def get_package(package: Package) -> types.ModuleType: ... + + def from_package(package: types.ModuleType) -> Traversable: ... + def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... diff --git a/stdlib/importlib/resources/_functional.pyi b/stdlib/importlib/resources/_functional.pyi new file mode 100644 index 000000000000..cfd15dc87ce8 --- /dev/null +++ b/stdlib/importlib/resources/_functional.pyi @@ -0,0 +1,35 @@ +import sys + +# Even though this file is 3.13+ only, Pyright will complain in stubtest for older versions. +if sys.version_info >= (3, 13): + from _typeshed import StrPath + from collections.abc import Iterator + from contextlib import AbstractContextManager + from importlib.resources._common import Anchor + from io import TextIOWrapper + from pathlib import Path + from typing import BinaryIO, Literal, overload + from typing_extensions import Unpack, deprecated + + def open_binary(anchor: Anchor, *path_names: StrPath) -> BinaryIO: ... + + @overload + def open_text( + anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" + ) -> TextIOWrapper: ... + @overload + def open_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> TextIOWrapper: ... + + def read_binary(anchor: Anchor, *path_names: StrPath) -> bytes: ... + + @overload + def read_text( + anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" + ) -> str: ... + @overload + def read_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> str: ... + + def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path, Literal[False]]: ... + def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: ... + @deprecated("Deprecated since Python 3.11. Use `files(anchor).iterdir()`.") + def contents(anchor: Anchor, *path_names: StrPath) -> Iterator[str]: ... diff --git a/stdlib/importlib/resources/abc.pyi b/stdlib/importlib/resources/abc.pyi new file mode 100644 index 000000000000..fd604997ff4a --- /dev/null +++ b/stdlib/importlib/resources/abc.pyi @@ -0,0 +1,64 @@ +import sys +from _typeshed import StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import Iterator +from io import BufferedReader +from typing import IO, Any, Literal, Protocol, overload, runtime_checkable +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + @deprecated("Deprecated. Use `importlib.resources.abc.TraversableResources` instead.") + class ResourceReader(metaclass=ABCMeta): + @abstractmethod + def open_resource(self, resource: str) -> IO[bytes]: ... + @abstractmethod + def resource_path(self, resource: str) -> str: ... + @abstractmethod + def is_resource(self, path: str) -> bool: ... + @abstractmethod + def contents(self) -> Iterator[str]: ... + + @runtime_checkable + class Traversable(Protocol): + @abstractmethod + def is_dir(self) -> bool: ... + @abstractmethod + def is_file(self) -> bool: ... + @abstractmethod + def iterdir(self) -> Iterator[Traversable]: ... + @abstractmethod + def joinpath(self, *descendants: StrPath) -> Traversable: ... + + # The documentation and runtime protocol allows *args, **kwargs arguments, + # but this would mean that all implementers would have to support them, + # which is not the case. + @overload + @abstractmethod + def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... + @overload + @abstractmethod + def open(self, mode: Literal["rb"]) -> IO[bytes]: ... + + @property + @abstractmethod + def name(self) -> str: ... + def __truediv__(self, child: StrPath, /) -> Traversable: ... + @abstractmethod + def read_bytes(self) -> bytes: ... + + if sys.version_info >= (3, 15): + @abstractmethod + def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ... + else: + @abstractmethod + def read_text(self, encoding: str | None = None) -> str: ... + + class TraversableResources(ResourceReader): + @abstractmethod + def files(self) -> Traversable: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def resource_path(self, resource: Any) -> str: ... + def is_resource(self, path: str) -> bool: ... + def contents(self) -> Iterator[str]: ... + + __all__ = ["ResourceReader", "Traversable", "TraversableResources"] diff --git a/stdlib/importlib/resources/readers.pyi b/stdlib/importlib/resources/readers.pyi new file mode 100644 index 000000000000..0ab21fd29114 --- /dev/null +++ b/stdlib/importlib/resources/readers.pyi @@ -0,0 +1,14 @@ +# On py311+, things are actually defined here +# and re-exported from importlib.readers, +# but doing it this way leads to less code duplication for us + +import sys +from collections.abc import Iterable, Iterator +from typing import TypeVar + +if sys.version_info >= (3, 11): + from importlib.readers import * + + _T = TypeVar("_T") + + def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ... diff --git a/stdlib/importlib/resources/simple.pyi b/stdlib/importlib/resources/simple.pyi new file mode 100644 index 000000000000..933a6ff164df --- /dev/null +++ b/stdlib/importlib/resources/simple.pyi @@ -0,0 +1,59 @@ +import abc +import sys +from _typeshed import StrPath +from collections.abc import Iterator +from io import TextIOWrapper +from typing import IO, Any, BinaryIO, Literal, overload +from typing_extensions import Never + +if sys.version_info >= (3, 11): + from .abc import Traversable, TraversableResources + + class SimpleReader(abc.ABC): + @property + @abc.abstractmethod + def package(self) -> str: ... + @abc.abstractmethod + def children(self) -> list[SimpleReader]: ... + @abc.abstractmethod + def resources(self) -> list[str]: ... + @abc.abstractmethod + def open_binary(self, resource: str) -> BinaryIO: ... + @property + def name(self) -> str: ... + + class ResourceHandle(Traversable, metaclass=abc.ABCMeta): + parent: ResourceContainer + def __init__(self, parent: ResourceContainer, name: str) -> None: ... + def is_file(self) -> Literal[True]: ... + def is_dir(self) -> Literal[False]: ... + + @overload + def open( + self, + mode: Literal["r"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> TextIOWrapper: ... + @overload + def open(self, mode: Literal["rb"]) -> BinaryIO: ... + @overload + def open(self, mode: str) -> IO[Any]: ... + + def joinpath(self, name: Never) -> Never: ... # type: ignore[override] + + class ResourceContainer(Traversable, metaclass=abc.ABCMeta): + reader: SimpleReader + def __init__(self, reader: SimpleReader) -> None: ... + def is_dir(self) -> Literal[True]: ... + def is_file(self) -> Literal[False]: ... + def iterdir(self) -> Iterator[ResourceHandle | ResourceContainer]: ... + def open(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + if sys.version_info < (3, 12): + def joinpath(self, *descendants: StrPath) -> Traversable: ... + + class TraversableReader(TraversableResources, SimpleReader, metaclass=abc.ABCMeta): + def files(self) -> ResourceContainer: ... diff --git a/stdlib/importlib/simple.pyi b/stdlib/importlib/simple.pyi new file mode 100644 index 000000000000..58d8c6617082 --- /dev/null +++ b/stdlib/importlib/simple.pyi @@ -0,0 +1,11 @@ +import sys + +if sys.version_info >= (3, 11): + from .resources.simple import ( + ResourceContainer as ResourceContainer, + ResourceHandle as ResourceHandle, + SimpleReader as SimpleReader, + TraversableReader as TraversableReader, + ) + + __all__ = ["SimpleReader", "ResourceHandle", "ResourceContainer", "TraversableReader"] diff --git a/stdlib/importlib/util.pyi b/stdlib/importlib/util.pyi index 96db3146863e..785ba6b9a08f 100644 --- a/stdlib/importlib/util.pyi +++ b/stdlib/importlib/util.pyi @@ -1,42 +1,75 @@ -import importlib.abc import importlib.machinery import sys import types -from _typeshed import StrOrBytesPath -from typing import Any, Callable -from typing_extensions import ParamSpec +from _typeshed import ReadableBuffer +from collections.abc import Callable +from importlib._bootstrap import module_from_spec as module_from_spec, spec_from_loader as spec_from_loader +from importlib._bootstrap_external import ( + MAGIC_NUMBER as MAGIC_NUMBER, + cache_from_source as cache_from_source, + decode_source as decode_source, + source_from_cache as source_from_cache, + spec_from_file_location as spec_from_file_location, +) +from importlib.abc import Loader +from types import TracebackType +from typing import Literal, ParamSpec +from typing_extensions import Self, deprecated _P = ParamSpec("_P") -def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... # type: ignore[misc] -def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... # type: ignore[misc] -def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... # type: ignore[misc] -def resolve_name(name: str, package: str | None) -> str: ... - -MAGIC_NUMBER: bytes +if sys.version_info < (3, 12): + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "`__name__`, `__package__` and `__loader__` are now set automatically." + ) + def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "`__name__`, `__package__` and `__loader__` are now set automatically." + ) + def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "`__name__`, `__package__` and `__loader__` are now set automatically." + ) + def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... -def cache_from_source(path: str, debug_override: bool | None = ..., *, optimization: Any | None = ...) -> str: ... -def source_from_cache(path: str) -> str: ... -def decode_source(source_bytes: bytes) -> str: ... -def find_spec(name: str, package: str | None = ...) -> importlib.machinery.ModuleSpec | None: ... -def spec_from_loader( - name: str, loader: importlib.abc.Loader | None, *, origin: str | None = ..., is_package: bool | None = ... -) -> importlib.machinery.ModuleSpec | None: ... -def spec_from_file_location( - name: str, - location: StrOrBytesPath | None = ..., - *, - loader: importlib.abc.Loader | None = ..., - submodule_search_locations: list[str] | None = ..., -) -> importlib.machinery.ModuleSpec | None: ... -def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ... +def resolve_name(name: str, package: str | None) -> str: ... +def find_spec(name: str, package: str | None = None) -> importlib.machinery.ModuleSpec | None: ... -class LazyLoader(importlib.abc.Loader): - def __init__(self, loader: importlib.abc.Loader) -> None: ... +class LazyLoader(Loader): + def __init__(self, loader: Loader) -> None: ... @classmethod - def factory(cls, loader: importlib.abc.Loader) -> Callable[..., LazyLoader]: ... - def create_module(self, spec: importlib.machinery.ModuleSpec) -> types.ModuleType | None: ... + def factory(cls, loader: Loader) -> Callable[..., LazyLoader]: ... def exec_module(self, module: types.ModuleType) -> None: ... -if sys.version_info >= (3, 7): - def source_hash(source_bytes: bytes) -> int: ... +def source_hash(source_bytes: ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 12): + class _incompatible_extension_module_restrictions: + def __init__(self, *, disable_check: bool) -> None: ... + disable_check: bool + old: Literal[-1, 0, 1] # exists only while entered + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + @property + def override(self) -> Literal[-1, 1]: ... # undocumented + +if sys.version_info >= (3, 14): + __all__ = [ + "LazyLoader", + "Loader", + "MAGIC_NUMBER", + "cache_from_source", + "decode_source", + "find_spec", + "module_from_spec", + "resolve_name", + "source_from_cache", + "source_hash", + "spec_from_file_location", + "spec_from_loader", + ] diff --git a/stdlib/inspect.pyi b/stdlib/inspect.pyi index 35c9149c01f0..9bca21ab2dfd 100644 --- a/stdlib/inspect.pyi +++ b/stdlib/inspect.pyi @@ -1,13 +1,14 @@ +import dis import enum import sys import types -from _typeshed import Self -from collections import OrderedDict -from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence, Set as AbstractSet +from _typeshed import AnnotationForm, StrPath +from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine, Generator, Mapping, Sequence, Set as AbstractSet from types import ( AsyncGeneratorType, BuiltinFunctionType, BuiltinMethodType, + ClassMethodDescriptorType, CodeType, CoroutineType, FrameType, @@ -15,16 +16,152 @@ from types import ( GeneratorType, GetSetDescriptorType, LambdaType, + MemberDescriptorType, + MethodDescriptorType, MethodType, + MethodWrapperType, ModuleType, TracebackType, + WrapperDescriptorType, ) - -if sys.version_info >= (3, 7): - from types import ClassMethodDescriptorType, WrapperDescriptorType, MemberDescriptorType, MethodDescriptorType - -from typing import Any, ClassVar, NamedTuple, Protocol, Tuple, Type, TypeVar, Union -from typing_extensions import Literal, TypeGuard +from typing import ( + Any, + ClassVar, + Final, + Literal, + NamedTuple, + ParamSpec, + Protocol, + TypeAlias, + TypeGuard, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import Never, Self, TypeIs, deprecated, disjoint_base + +if sys.version_info >= (3, 14): + from annotationlib import Format + +if sys.version_info >= (3, 11): + __all__ = [ + "ArgInfo", + "Arguments", + "Attribute", + "BlockFinder", + "BoundArguments", + "CORO_CLOSED", + "CORO_CREATED", + "CORO_RUNNING", + "CORO_SUSPENDED", + "CO_ASYNC_GENERATOR", + "CO_COROUTINE", + "CO_GENERATOR", + "CO_ITERABLE_COROUTINE", + "CO_NESTED", + "CO_NEWLOCALS", + "CO_NOFREE", + "CO_OPTIMIZED", + "CO_VARARGS", + "CO_VARKEYWORDS", + "ClassFoundException", + "ClosureVars", + "EndOfBlock", + "FrameInfo", + "FullArgSpec", + "GEN_CLOSED", + "GEN_CREATED", + "GEN_RUNNING", + "GEN_SUSPENDED", + "Parameter", + "Signature", + "TPFLAGS_IS_ABSTRACT", + "Traceback", + "classify_class_attrs", + "cleandoc", + "currentframe", + "findsource", + "formatannotation", + "formatannotationrelativeto", + "formatargvalues", + "get_annotations", + "getabsfile", + "getargs", + "getargvalues", + "getattr_static", + "getblock", + "getcallargs", + "getclasstree", + "getclosurevars", + "getcomments", + "getcoroutinelocals", + "getcoroutinestate", + "getdoc", + "getfile", + "getframeinfo", + "getfullargspec", + "getgeneratorlocals", + "getgeneratorstate", + "getinnerframes", + "getlineno", + "getmembers", + "getmembers_static", + "getmodule", + "getmodulename", + "getmro", + "getouterframes", + "getsource", + "getsourcefile", + "getsourcelines", + "indentsize", + "isabstract", + "isasyncgen", + "isasyncgenfunction", + "isawaitable", + "isbuiltin", + "isclass", + "iscode", + "iscoroutine", + "iscoroutinefunction", + "isdatadescriptor", + "isframe", + "isfunction", + "isgenerator", + "isgeneratorfunction", + "isgetsetdescriptor", + "ismemberdescriptor", + "ismethod", + "ismethoddescriptor", + "ismethodwrapper", + "ismodule", + "isroutine", + "istraceback", + "signature", + "stack", + "trace", + "unwrap", + "walktree", + ] + + if sys.version_info >= (3, 12): + __all__ += [ + "markcoroutinefunction", + "AGEN_CLOSED", + "AGEN_CREATED", + "AGEN_RUNNING", + "AGEN_SUSPENDED", + "getasyncgenlocals", + "getasyncgenstate", + "BufferFlags", + ] + if sys.version_info >= (3, 14): + __all__ += ["CO_HAS_DOCSTRING", "CO_METHOD", "ispackage"] + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) +_T_contra = TypeVar("_T_contra", contravariant=True) +_V_contra = TypeVar("_V_contra", contravariant=True) # # Types and members @@ -41,214 +178,315 @@ class BlockFinder: last: int def tokeneater(self, type: int, token: str, srowcol: tuple[int, int], erowcol: tuple[int, int], line: str) -> None: ... -CO_OPTIMIZED: int -CO_NEWLOCALS: int -CO_VARARGS: int -CO_VARKEYWORDS: int -CO_NESTED: int -CO_GENERATOR: int -CO_NOFREE: int -CO_COROUTINE: int -CO_ITERABLE_COROUTINE: int -CO_ASYNC_GENERATOR: int -TPFLAGS_IS_ABSTRACT: int +CO_OPTIMIZED: Final = 1 +CO_NEWLOCALS: Final = 2 +CO_VARARGS: Final = 4 +CO_VARKEYWORDS: Final = 8 +CO_NESTED: Final = 16 +CO_GENERATOR: Final = 32 +CO_NOFREE: Final = 64 +CO_COROUTINE: Final = 128 +CO_ITERABLE_COROUTINE: Final = 256 +CO_ASYNC_GENERATOR: Final = 512 +TPFLAGS_IS_ABSTRACT: Final = 1048576 +if sys.version_info >= (3, 14): + CO_HAS_DOCSTRING: Final = 67108864 + CO_METHOD: Final = 134217728 modulesbyfile: dict[str, Any] -def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> list[tuple[str, Any]]: ... -def getmodulename(path: str) -> str | None: ... -def ismodule(object: object) -> TypeGuard[ModuleType]: ... -def isclass(object: object) -> TypeGuard[Type[Any]]: ... -def ismethod(object: object) -> TypeGuard[MethodType]: ... -def isfunction(object: object) -> TypeGuard[FunctionType]: ... - -if sys.version_info >= (3, 8): - def isgeneratorfunction(obj: object) -> bool: ... - def iscoroutinefunction(obj: object) -> bool: ... - -else: - def isgeneratorfunction(object: object) -> bool: ... - def iscoroutinefunction(object: object) -> bool: ... - -def isgenerator(object: object) -> TypeGuard[GeneratorType[Any, Any, Any]]: ... -def iscoroutine(object: object) -> TypeGuard[CoroutineType[Any, Any, Any]]: ... -def isawaitable(object: object) -> TypeGuard[Awaitable[Any]]: ... - -if sys.version_info >= (3, 8): - def isasyncgenfunction(obj: object) -> bool: ... - -else: - def isasyncgenfunction(object: object) -> bool: ... - -_T_cont = TypeVar("_T_cont", contravariant=True) -_V_cont = TypeVar("_V_cont", contravariant=True) - -class _SupportsSet(Protocol[_T_cont, _V_cont]): - def __set__(self, __instance: _T_cont, __value: _V_cont) -> None: ... - -class _SupportsDelete(Protocol[_T_cont]): - def __delete__(self, __instance: _T_cont) -> None: ... - -def isasyncgen(object: object) -> TypeGuard[AsyncGeneratorType[Any, Any]]: ... -def istraceback(object: object) -> TypeGuard[TracebackType]: ... -def isframe(object: object) -> TypeGuard[FrameType]: ... -def iscode(object: object) -> TypeGuard[CodeType]: ... -def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... - -if sys.version_info >= (3, 7): - def isroutine( - object: object, - ) -> TypeGuard[ - FunctionType - | LambdaType - | MethodType - | BuiltinFunctionType - | BuiltinMethodType - | WrapperDescriptorType - | MethodDescriptorType - | ClassMethodDescriptorType - ]: ... - def ismethoddescriptor(object: object) -> TypeGuard[MethodDescriptorType]: ... - def ismemberdescriptor(object: object) -> TypeGuard[MemberDescriptorType]: ... - -else: - def isroutine( - object: object, - ) -> TypeGuard[FunctionType | LambdaType | MethodType | BuiltinFunctionType | BuiltinMethodType]: ... - def ismethoddescriptor(object: object) -> bool: ... - def ismemberdescriptor(object: object) -> bool: ... - +_GetMembersPredicateTypeGuard: TypeAlias = Callable[[Any], TypeGuard[_T]] +_GetMembersPredicateTypeIs: TypeAlias = Callable[[Any], TypeIs[_T]] +_GetMembersPredicate: TypeAlias = Callable[[Any], bool] +_GetMembersReturn: TypeAlias = list[tuple[str, _T]] + +@overload +def getmembers(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: ... +@overload +def getmembers(object: object, predicate: _GetMembersPredicateTypeIs[_T]) -> _GetMembersReturn[_T]: ... +@overload +def getmembers(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ... + +if sys.version_info >= (3, 11): + @overload + def getmembers_static(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: ... + @overload + def getmembers_static(object: object, predicate: _GetMembersPredicateTypeIs[_T]) -> _GetMembersReturn[_T]: ... + @overload + def getmembers_static(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ... + +def getmodulename(path: StrPath) -> str | None: ... +def ismodule(object: object) -> TypeIs[ModuleType]: ... +def isclass(object: object) -> TypeIs[type[object]]: ... +def ismethod(object: object) -> TypeIs[MethodType]: ... + +if sys.version_info >= (3, 14): + # Not TypeIs because it does not return True for all modules + def ispackage(object: object) -> TypeGuard[ModuleType]: ... + +def isfunction(object: object) -> TypeIs[FunctionType]: ... + +if sys.version_info >= (3, 12): + def markcoroutinefunction(func: _F) -> _F: ... + +@overload +def isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: ... +@overload +def isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, Generator[Any, Any, Any]]]: ... +@overload +def isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., Generator[Any, Any, Any]]]: ... + +@overload +def iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... +@overload +def iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... +@overload +def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... +@overload +def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... + +def isgenerator(object: object) -> TypeIs[GeneratorType[object, Never, object]]: ... +def iscoroutine(object: object) -> TypeIs[CoroutineType[Any, Any, Any]]: ... +def isawaitable(object: object) -> TypeIs[Awaitable[Any]]: ... + +@overload +def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... +@overload +def isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGenerator[Any, Any]]]: ... +@overload +def isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGenerator[Any, Any]]]: ... + +@type_check_only +class _SupportsSet(Protocol[_T_contra, _V_contra]): + def __set__(self, instance: _T_contra, value: _V_contra, /) -> None: ... + +@type_check_only +class _SupportsDelete(Protocol[_T_contra]): + def __delete__(self, instance: _T_contra, /) -> None: ... + +def isasyncgen(object: object) -> TypeIs[AsyncGeneratorType[object, Never]]: ... +def istraceback(object: object) -> TypeIs[TracebackType]: ... +def isframe(object: object) -> TypeIs[FrameType]: ... +def iscode(object: object) -> TypeIs[CodeType]: ... +def isbuiltin(object: object) -> TypeIs[BuiltinFunctionType]: ... + +if sys.version_info >= (3, 11): + def ismethodwrapper(object: object) -> TypeIs[MethodWrapperType]: ... + +def isroutine( + object: object, +) -> TypeIs[ + FunctionType + | LambdaType + | MethodType + | BuiltinFunctionType + | BuiltinMethodType + | WrapperDescriptorType + | MethodDescriptorType + | ClassMethodDescriptorType +]: ... +def ismethoddescriptor(object: object) -> TypeIs[MethodDescriptorType]: ... +def ismemberdescriptor(object: object) -> TypeIs[MemberDescriptorType]: ... def isabstract(object: object) -> bool: ... -def isgetsetdescriptor(object: object) -> TypeGuard[GetSetDescriptorType]: ... -def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: ... +def isgetsetdescriptor(object: object) -> TypeIs[GetSetDescriptorType]: ... +def isdatadescriptor(object: object) -> TypeIs[_SupportsSet[Never, Never] | _SupportsDelete[Never]]: ... # # Retrieving source code # -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType: TypeAlias = ( + ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] +) def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... -def getabsfile(object: _SourceObjectType, _filename: str | None = ...) -> str: ... +def getabsfile(object: _SourceObjectType, _filename: str | None = None) -> str: ... + +# Special-case the two most common input types here +# to avoid the annoyingly vague `Sequence[str]` return type +@overload +def getblock(lines: list[str]) -> list[str]: ... +@overload +def getblock(lines: tuple[str, ...]) -> tuple[str, ...]: ... +@overload def getblock(lines: Sequence[str]) -> Sequence[str]: ... -def getdoc(object: object) -> str | None: ... + +if sys.version_info >= (3, 15): + def getdoc(object: object, *, inherit_class_doc: bool = True, fallback_to_class_doc: bool = True) -> str | None: ... + +else: + def getdoc(object: object) -> str | None: ... + def getcomments(object: object) -> str | None: ... def getfile(object: _SourceObjectType) -> str: ... -def getmodule(object: object, _filename: str | None = ...) -> ModuleType | None: ... +def getmodule(object: object, _filename: str | None = None) -> ModuleType | None: ... def getsourcefile(object: _SourceObjectType) -> str | None: ... def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: ... def getsource(object: _SourceObjectType) -> str: ... def cleandoc(doc: str) -> str: ... def indentsize(line: str) -> int: ... +_IntrospectableCallable: TypeAlias = Callable[..., Any] + # # Introspecting callables with the Signature object # -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 14): def signature( - obj: Callable[..., Any], + obj: _IntrospectableCallable, *, - follow_wrapped: bool = ..., - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., - eval_str: bool = ..., + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + annotation_format: Format = Format.VALUE, # noqa: Y011 ) -> Signature: ... else: - def signature(obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... + def signature( + obj: _IntrospectableCallable, + *, + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + ) -> Signature: ... class _void: ... class _empty: ... class Signature: + __slots__ = ("_return_annotation", "_parameters") def __init__( - self, parameters: Sequence[Parameter] | None = ..., *, return_annotation: Any = ..., __validate_parameters__: bool = ... + self, parameters: Sequence[Parameter] | None = None, *, return_annotation: Any = ..., __validate_parameters__: bool = True ) -> None: ... empty = _empty @property def parameters(self) -> types.MappingProxyType[str, Parameter]: ... - # TODO: can we be more specific here? @property def return_annotation(self) -> Any: ... def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... - def replace( - self: Self, *, parameters: Sequence[Parameter] | Type[_void] | None = ..., return_annotation: Any = ... - ) -> Self: ... - if sys.version_info >= (3, 10): + def replace(self, *, parameters: Sequence[Parameter] | type[_void] | None = ..., return_annotation: Any = ...) -> Self: ... + __replace__ = replace + if sys.version_info >= (3, 14): @classmethod def from_callable( cls, - obj: Callable[..., Any], + obj: _IntrospectableCallable, *, - follow_wrapped: bool = ..., - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., - eval_str: bool = ..., - ) -> Signature: ... + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + annotation_format: Format = Format.VALUE, # noqa: Y011 + ) -> Self: ... else: @classmethod - def from_callable(cls, obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... - -if sys.version_info >= (3, 10): + def from_callable( + cls, + obj: _IntrospectableCallable, + *, + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + ) -> Self: ... + + if sys.version_info >= (3, 14): + def format(self, *, max_width: int | None = None, quote_annotation_strings: bool = True) -> str: ... + elif sys.version_info >= (3, 13): + def format(self, *, max_width: int | None = None) -> str: ... + + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 14): + from annotationlib import get_annotations as get_annotations +else: def get_annotations( - obj: Callable[..., Any] | Type[Any] | ModuleType, + obj: Callable[..., object] | type[object] | ModuleType, # any callable, class, or module *, - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., - eval_str: bool = ..., - ) -> dict[str, Any]: ... + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + ) -> dict[str, AnnotationForm]: ... # values are type expressions # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): - POSITIONAL_ONLY: int - POSITIONAL_OR_KEYWORD: int - VAR_POSITIONAL: int - KEYWORD_ONLY: int - VAR_KEYWORD: int + POSITIONAL_ONLY = 0 + POSITIONAL_OR_KEYWORD = 1 + VAR_POSITIONAL = 2 + KEYWORD_ONLY = 3 + VAR_KEYWORD = 4 + + @property + def description(self) -> str: ... - if sys.version_info >= (3, 8): - @property - def description(self) -> str: ... +if sys.version_info >= (3, 12): + AGEN_CREATED: Final = "AGEN_CREATED" + AGEN_RUNNING: Final = "AGEN_RUNNING" + AGEN_SUSPENDED: Final = "AGEN_SUSPENDED" + AGEN_CLOSED: Final = "AGEN_CLOSED" + + def getasyncgenstate( + agen: AsyncGenerator[Any, Any], + ) -> Literal["AGEN_CREATED", "AGEN_RUNNING", "AGEN_SUSPENDED", "AGEN_CLOSED"]: ... + def getasyncgenlocals(agen: AsyncGeneratorType[Any, Any]) -> dict[str, Any]: ... class Parameter: + __slots__ = ("_name", "_kind", "_default", "_annotation") def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ... empty = _empty - name: str - default: Any - annotation: Any - kind: _ParameterKind POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]] POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]] KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]] VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]] + @property + def name(self) -> str: ... + @property + def default(self) -> Any: ... + @property + def kind(self) -> _ParameterKind: ... + @property + def annotation(self) -> Any: ... def replace( - self: Self, + self, *, - name: str | Type[_void] = ..., - kind: _ParameterKind | Type[_void] = ..., + name: str | type[_void] = ..., + kind: _ParameterKind | type[_void] = ..., default: Any = ..., annotation: Any = ..., ) -> Self: ... + if sys.version_info >= (3, 13): + __replace__ = replace + + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... class BoundArguments: - arguments: OrderedDict[str, Any] - args: Tuple[Any, ...] - kwargs: dict[str, Any] - signature: Signature - def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... + __slots__ = ("arguments", "_signature", "__weakref__") + arguments: dict[str, Any] + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> dict[str, Any]: ... + @property + def signature(self) -> Signature: ... + def __init__(self, signature: Signature, arguments: dict[str, Any]) -> None: ... def apply_defaults(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] # # Classes and functions # -# TODO: The actual return type should be list[_ClassTreeItem] but mypy doesn't -# seem to be supporting this at the moment: -# _ClassTreeItem = list[_ClassTreeItem] | Tuple[type, Tuple[type, ...]] -def getclasstree(classes: list[type], unique: bool = ...) -> list[Any]: ... -def walktree(classes: list[type], children: dict[Type[Any], list[type]], parent: Type[Any] | None) -> list[Any]: ... +_ClassTreeItem: TypeAlias = list[tuple[type, ...]] | list[_ClassTreeItem] + +def getclasstree(classes: list[type], unique: bool = False) -> _ClassTreeItem: ... +def walktree(classes: list[type], children: Mapping[type[Any], list[type]], parent: type[Any] | None) -> _ClassTreeItem: ... class Arguments(NamedTuple): args: list[str] @@ -258,23 +496,30 @@ class Arguments(NamedTuple): def getargs(co: CodeType) -> Arguments: ... if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.0; removed in Python 3.11.") class ArgSpec(NamedTuple): args: list[str] varargs: str | None keywords: str | None - defaults: Tuple[Any, ...] + defaults: tuple[Any, ...] + + @deprecated("Deprecated since Python 3.0; removed in Python 3.11. Use `inspect.signature()` instead.") def getargspec(func: object) -> ArgSpec: ... class FullArgSpec(NamedTuple): args: list[str] varargs: str | None varkw: str | None - defaults: Tuple[Any, ...] | None + defaults: tuple[Any, ...] | None kwonlyargs: list[str] kwonlydefaults: dict[str, Any] | None annotations: dict[str, Any] -def getfullargspec(func: object) -> FullArgSpec: ... +if sys.version_info >= (3, 15): + def getfullargspec(func: object, *, annotation_format: Format = Format.VALUE) -> FullArgSpec: ... # noqa: Y011 + +else: + def getfullargspec(func: object) -> FullArgSpec: ... class ArgInfo(NamedTuple): args: list[str] @@ -283,18 +528,27 @@ class ArgInfo(NamedTuple): locals: dict[str, Any] def getargvalues(frame: FrameType) -> ArgInfo: ... -def formatannotation(annotation: object, base_module: str | None = ...) -> str: ... + +if sys.version_info >= (3, 14): + def formatannotation(annotation: object, base_module: str | None = None, *, quote_annotation_strings: bool = True) -> str: ... + +else: + def formatannotation(annotation: object, base_module: str | None = None) -> str: ... + def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... if sys.version_info < (3, 11): + @deprecated( + "Deprecated since Python 3.5; removed in Python 3.11. Use `inspect.signature()` and the `Signature` class instead." + ) def formatargspec( args: list[str], - varargs: str | None = ..., - varkw: str | None = ..., - defaults: Tuple[Any, ...] | None = ..., - kwonlyargs: Sequence[str] | None = ..., - kwonlydefaults: dict[str, Any] | None = ..., - annotations: dict[str, Any] = ..., + varargs: str | None = None, + varkw: str | None = None, + defaults: tuple[Any, ...] | None = None, + kwonlyargs: Sequence[str] | None = (), + kwonlydefaults: Mapping[str, Any] | None = {}, + annotations: Mapping[str, Any] = {}, formatarg: Callable[[str], str] = ..., formatvarargs: Callable[[str], str] = ..., formatvarkw: Callable[[str], str] = ..., @@ -307,14 +561,15 @@ def formatargvalues( args: list[str], varargs: str | None, varkw: str | None, - locals: dict[str, Any] | None, + locals: Mapping[str, Any] | None, formatarg: Callable[[str], str] | None = ..., formatvarargs: Callable[[str], str] | None = ..., formatvarkw: Callable[[str], str] | None = ..., formatvalue: Callable[[Any], str] | None = ..., ) -> str: ... -def getmro(cls: type) -> Tuple[type, ...]: ... -def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> dict[str, Any]: ... +def getmro(cls: type) -> tuple[type, ...]: ... +@deprecated("Deprecated since Python 3.5. Use `Signature.bind` and `Signature.bind_partial` instead.") +def getcallargs(func: Callable[_P, Any], /, *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: ... class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] @@ -322,35 +577,110 @@ class ClosureVars(NamedTuple): builtins: Mapping[str, Any] unbound: AbstractSet[str] -def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... -def unwrap(func: Callable[..., Any], *, stop: Callable[[Any], Any] | None = ...) -> Any: ... +def getclosurevars(func: _IntrospectableCallable) -> ClosureVars: ... +def unwrap(func: Callable[..., Any], *, stop: Callable[[Callable[..., Any]], Any] | None = None) -> Any: ... # # The interpreter stack # -class Traceback(NamedTuple): - filename: str - lineno: int - function: str - code_context: list[str] | None - index: int | None # type: ignore[assignment] - -class FrameInfo(NamedTuple): - frame: FrameType - filename: str - lineno: int - function: str - code_context: list[str] | None - index: int | None # type: ignore[assignment] - -def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... -def getouterframes(frame: Any, context: int = ...) -> list[FrameInfo]: ... -def getinnerframes(tb: TracebackType, context: int = ...) -> list[FrameInfo]: ... +if sys.version_info >= (3, 11): + class _Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class _FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + if sys.version_info >= (3, 12): + class Traceback(_Traceback): + positions: dis.Positions | None + def __new__( + cls, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + + class FrameInfo(_FrameInfo): + positions: dis.Positions | None + def __new__( + cls, + frame: FrameType, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + + else: + @disjoint_base + class Traceback(_Traceback): + positions: dis.Positions | None + def __new__( + cls, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + + @disjoint_base + class FrameInfo(_FrameInfo): + positions: dis.Positions | None + def __new__( + cls, + frame: FrameType, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + +else: + class Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + +def getframeinfo(frame: FrameType | TracebackType, context: int = 1) -> Traceback: ... +def getouterframes(frame: Any, context: int = 1) -> list[FrameInfo]: ... +def getinnerframes(tb: TracebackType, context: int = 1) -> list[FrameInfo]: ... def getlineno(frame: FrameType) -> int: ... def currentframe() -> FrameType | None: ... -def stack(context: int = ...) -> list[FrameInfo]: ... -def trace(context: int = ...) -> list[FrameInfo]: ... +def stack(context: int = 1) -> list[FrameInfo]: ... +def trace(context: int = 1) -> list[FrameInfo]: ... # # Fetching attributes statically @@ -362,38 +692,58 @@ def getattr_static(obj: object, attr: str, default: Any | None = ...) -> Any: .. # Current State of Generators and Coroutines # -# TODO In the next two blocks of code, can we be more specific regarding the -# type of the "enums"? +GEN_CREATED: Final = "GEN_CREATED" +GEN_RUNNING: Final = "GEN_RUNNING" +GEN_SUSPENDED: Final = "GEN_SUSPENDED" +GEN_CLOSED: Final = "GEN_CLOSED" -GEN_CREATED: str -GEN_RUNNING: str -GEN_SUSPENDED: str -GEN_CLOSED: str +def getgeneratorstate( + generator: Generator[Any, Any, Any], +) -> Literal["GEN_CREATED", "GEN_RUNNING", "GEN_SUSPENDED", "GEN_CLOSED"]: ... -def getgeneratorstate(generator: Generator[Any, Any, Any]) -> str: ... +CORO_CREATED: Final = "CORO_CREATED" +CORO_RUNNING: Final = "CORO_RUNNING" +CORO_SUSPENDED: Final = "CORO_SUSPENDED" +CORO_CLOSED: Final = "CORO_CLOSED" -CORO_CREATED: str -CORO_RUNNING: str -CORO_SUSPENDED: str -CORO_CLOSED: str -# TODO can we be more specific than "object"? -def getcoroutinestate(coroutine: object) -> str: ... +def getcoroutinestate( + coroutine: Coroutine[Any, Any, Any], +) -> Literal["CORO_CREATED", "CORO_RUNNING", "CORO_SUSPENDED", "CORO_CLOSED"]: ... def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: ... - -# TODO can we be more specific than "object"? -def getcoroutinelocals(coroutine: object) -> dict[str, Any]: ... +def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: ... # Create private type alias to avoid conflict with symbol of same # name created in Attribute class. -_Object = object +_Object: TypeAlias = object class Attribute(NamedTuple): name: str - kind: str + kind: Literal["class method", "static method", "property", "method", "data"] defining_class: type object: _Object def classify_class_attrs(cls: type) -> list[Attribute]: ... -if sys.version_info >= (3, 9): - class ClassFoundException(Exception): ... +class ClassFoundException(Exception): ... + +if sys.version_info >= (3, 12): + class BufferFlags(enum.IntFlag): + SIMPLE = 0 + WRITABLE = 1 + FORMAT = 4 + ND = 8 + STRIDES = 24 + C_CONTIGUOUS = 56 + F_CONTIGUOUS = 88 + ANY_CONTIGUOUS = 152 + INDIRECT = 280 + CONTIG = 9 + CONTIG_RO = 8 + STRIDED = 25 + STRIDED_RO = 24 + RECORDS = 29 + RECORDS_RO = 28 + FULL = 285 + FULL_RO = 284 + READ = 256 + WRITE = 512 diff --git a/stdlib/io.pyi b/stdlib/io.pyi index 29c42ed9da71..d301d700e9d0 100644 --- a/stdlib/io.pyi +++ b/stdlib/io.pyi @@ -1,182 +1,75 @@ -import builtins -import codecs +import abc import sys -from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from os import _Opener -from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, TextIO, Tuple, Type - -DEFAULT_BUFFER_SIZE: int - -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int - -open = builtins.open - -if sys.version_info >= (3, 8): - def open_code(path: str) -> IO[bytes]: ... - -BlockingIOError = builtins.BlockingIOError +from _io import ( + DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE, + BlockingIOError as BlockingIOError, + BufferedRandom as BufferedRandom, + BufferedReader as BufferedReader, + BufferedRWPair as BufferedRWPair, + BufferedWriter as BufferedWriter, + BytesIO as BytesIO, + FileIO as FileIO, + IncrementalNewlineDecoder as IncrementalNewlineDecoder, + StringIO as StringIO, + TextIOWrapper as TextIOWrapper, + _BufferedIOBase, + _IOBase, + _RawIOBase, + _TextIOBase, + _WrappedBuffer as _WrappedBuffer, # used elsewhere in typeshed + open as open, + open_code as open_code, +) +from typing import Final, Protocol, TypeVar + +__all__ = [ + "BlockingIOError", + "open", + "open_code", + "IOBase", + "RawIOBase", + "FileIO", + "BytesIO", + "StringIO", + "BufferedIOBase", + "BufferedReader", + "BufferedWriter", + "BufferedRWPair", + "BufferedRandom", + "TextIOBase", + "TextIOWrapper", + "UnsupportedOperation", + "SEEK_SET", + "SEEK_CUR", + "SEEK_END", +] + +if sys.version_info >= (3, 14): + __all__ += ["Reader", "Writer"] + +if sys.version_info >= (3, 11): + from _io import text_encoding as text_encoding + + __all__ += ["DEFAULT_BUFFER_SIZE", "IncrementalNewlineDecoder", "text_encoding"] + +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) + +SEEK_SET: Final = 0 +SEEK_CUR: Final = 1 +SEEK_END: Final = 2 class UnsupportedOperation(OSError, ValueError): ... - -class IOBase: - def __iter__(self) -> Iterator[bytes]: ... - def __next__(self) -> bytes: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def close(self) -> None: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def readable(self) -> bool: ... - read: Callable[..., Any] - def readlines(self, __hint: int = ...) -> list[bytes]: ... - def seek(self, __offset: int, __whence: int = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def truncate(self, __size: int | None = ...) -> int: ... - def writable(self) -> bool: ... - write: Callable[..., Any] - def writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ... - def readline(self, __size: int | None = ...) -> bytes: ... - def __del__(self) -> None: ... - @property - def closed(self) -> bool: ... - def _checkClosed(self, msg: str | None = ...) -> None: ... # undocumented - -class RawIOBase(IOBase): - def readall(self) -> bytes: ... - def readinto(self, __buffer: WriteableBuffer) -> int | None: ... - def write(self, __b: ReadableBuffer) -> int | None: ... - def read(self, __size: int = ...) -> bytes | None: ... - -class BufferedIOBase(IOBase): - raw: RawIOBase # This is not part of the BufferedIOBase API and may not exist on some implementations. - def detach(self) -> RawIOBase: ... - def readinto(self, __buffer: WriteableBuffer) -> int: ... - def write(self, __buffer: ReadableBuffer) -> int: ... - def readinto1(self, __buffer: WriteableBuffer) -> int: ... - def read(self, __size: int | None = ...) -> bytes: ... - def read1(self, __size: int = ...) -> bytes: ... - -class FileIO(RawIOBase, BinaryIO): - mode: str - name: StrOrBytesPath | int # type: ignore[assignment] - def __init__( - self, file: StrOrBytesPath | int, mode: str = ..., closefd: bool = ..., opener: _Opener | None = ... - ) -> None: ... - @property - def closefd(self) -> bool: ... - def write(self, __b: ReadableBuffer) -> int: ... - def read(self, __size: int = ...) -> bytes: ... - def __enter__(self: Self) -> Self: ... - -class BytesIO(BufferedIOBase, BinaryIO): - def __init__(self, initial_bytes: bytes = ...) -> None: ... - # BytesIO does not contain a "name" field. This workaround is necessary - # to allow BytesIO sub-classes to add this field, as it is defined - # as a read-only property on IO[]. - name: Any - def __enter__(self: Self) -> Self: ... - def getvalue(self) -> bytes: ... - def getbuffer(self) -> memoryview: ... - if sys.version_info >= (3, 7): - def read1(self, __size: int | None = ...) -> bytes: ... - else: - def read1(self, __size: int | None) -> bytes: ... # type: ignore[override] - -class BufferedReader(BufferedIOBase, BinaryIO): - def __enter__(self: Self) -> Self: ... - def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... - def peek(self, __size: int = ...) -> bytes: ... - if sys.version_info >= (3, 7): - def read1(self, __size: int = ...) -> bytes: ... - else: - def read1(self, __size: int) -> bytes: ... # type: ignore[override] - -class BufferedWriter(BufferedIOBase, BinaryIO): - def __enter__(self: Self) -> Self: ... - def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... - def write(self, __buffer: ReadableBuffer) -> int: ... - -class BufferedRandom(BufferedReader, BufferedWriter): - def __enter__(self: Self) -> Self: ... - def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... - def seek(self, __target: int, __whence: int = ...) -> int: ... - if sys.version_info >= (3, 7): - def read1(self, __size: int = ...) -> bytes: ... - else: - def read1(self, __size: int) -> bytes: ... # type: ignore[override] - -class BufferedRWPair(BufferedIOBase): - def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = ...) -> None: ... - def peek(self, __size: int = ...) -> bytes: ... - -class TextIOBase(IOBase): - encoding: str - errors: str | None - newlines: str | Tuple[str, ...] | None - def __iter__(self) -> Iterator[str]: ... # type: ignore[override] - def __next__(self) -> str: ... # type: ignore[override] - def detach(self) -> BinaryIO: ... - def write(self, __s: str) -> int: ... - def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] - def readline(self, __size: int = ...) -> str: ... # type: ignore[override] - def readlines(self, __hint: int = ...) -> list[str]: ... # type: ignore[override] - def read(self, __size: int | None = ...) -> str: ... - def tell(self) -> int: ... - -class TextIOWrapper(TextIOBase, TextIO): - def __init__( - self, - buffer: IO[bytes], - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - line_buffering: bool = ..., - write_through: bool = ..., - ) -> None: ... - @property - def buffer(self) -> BinaryIO: ... - @property - def closed(self) -> bool: ... - @property - def line_buffering(self) -> bool: ... - if sys.version_info >= (3, 7): - @property - def write_through(self) -> bool: ... - def reconfigure( - self, - *, - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - line_buffering: bool | None = ..., - write_through: bool | None = ..., - ) -> None: ... - # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy. - def __enter__(self: Self) -> Self: ... - def __iter__(self) -> Iterator[str]: ... # type: ignore[override] - def __next__(self) -> str: ... # type: ignore[override] - def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] - def readline(self, __size: int = ...) -> str: ... # type: ignore[override] - def readlines(self, __hint: int = ...) -> list[str]: ... # type: ignore[override] - def seek(self, __cookie: int, __whence: int = ...) -> int: ... - -class StringIO(TextIOWrapper): - def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None: ... - # StringIO does not contain a "name" field. This workaround is necessary - # to allow StringIO sub-classes to add this field, as it is defined - # as a read-only property on IO[]. - name: Any - def getvalue(self) -> str: ... - -class IncrementalNewlineDecoder(codecs.IncrementalDecoder): - def __init__(self, decoder: codecs.IncrementalDecoder | None, translate: bool, errors: str = ...) -> None: ... - def decode(self, input: bytes | str, final: bool = ...) -> str: ... - @property - def newlines(self) -> str | Tuple[str, ...] | None: ... +class IOBase(_IOBase, metaclass=abc.ABCMeta): ... +class RawIOBase(_RawIOBase, IOBase): ... +class BufferedIOBase(_BufferedIOBase, IOBase): ... +class TextIOBase(_TextIOBase, IOBase): ... + +if sys.version_info >= (3, 14): + class Reader(Protocol[_T_co]): + __slots__ = () + def read(self, size: int = ..., /) -> _T_co: ... + + class Writer(Protocol[_T_contra]): + __slots__ = () + def write(self, data: _T_contra, /) -> int: ... diff --git a/stdlib/ipaddress.pyi b/stdlib/ipaddress.pyi index 6af3ebc3a2bd..c514abfa569f 100644 --- a/stdlib/ipaddress.pyi +++ b/stdlib/ipaddress.pyi @@ -1,70 +1,78 @@ import sys -from typing import Any, Container, Generic, Iterable, Iterator, SupportsInt, TypeVar, overload +from collections.abc import Iterable, Iterator +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self # Undocumented length constants -IPV4LENGTH: int -IPV6LENGTH: int +IPV4LENGTH: Final = 32 +IPV6LENGTH: Final = 128 _A = TypeVar("_A", IPv4Address, IPv6Address) _N = TypeVar("_N", IPv4Network, IPv6Network) -_T = TypeVar("_T") -def ip_address(address: object) -> IPv4Address | IPv6Address: ... -def ip_network(address: object, strict: bool = ...) -> IPv4Network | IPv6Network: ... -def ip_interface(address: object) -> IPv4Interface | IPv6Interface: ... +_RawIPAddress: TypeAlias = int | str | bytes | IPv4Address | IPv6Address +_RawNetworkPart: TypeAlias = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface + +def ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: ... +def ip_network( + address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], strict: bool = True +) -> IPv4Network | IPv6Network: ... +def ip_interface( + address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], +) -> IPv4Interface | IPv6Interface: ... class _IPAddressBase: - def __eq__(self, other: Any) -> bool: ... - def __ge__(self: _T, other: _T) -> bool: ... - def __gt__(self: _T, other: _T) -> bool: ... - def __le__(self: _T, other: _T) -> bool: ... - def __lt__(self: _T, other: _T) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + __slots__ = () @property def compressed(self) -> str: ... @property def exploded(self) -> str: ... @property def reverse_pointer(self) -> str: ... - @property - def version(self) -> int: ... + if sys.version_info < (3, 14): + @property + def version(self) -> int: ... -class _BaseAddress(_IPAddressBase, SupportsInt): - def __init__(self, address: object) -> None: ... - def __add__(self: _T, other: int) -> _T: ... +class _BaseAddress(_IPAddressBase): + __slots__ = () + def __add__(self, other: int) -> Self: ... def __hash__(self) -> int: ... def __int__(self) -> int: ... - def __sub__(self: _T, other: int) -> _T: ... - @property - def is_global(self) -> bool: ... - @property - def is_link_local(self) -> bool: ... - @property - def is_loopback(self) -> bool: ... - @property - def is_multicast(self) -> bool: ... - @property - def is_private(self) -> bool: ... - @property - def is_reserved(self) -> bool: ... - @property - def is_unspecified(self) -> bool: ... - @property - def max_prefixlen(self) -> int: ... - @property - def packed(self) -> bytes: ... + def __sub__(self, other: int) -> Self: ... + def __format__(self, fmt: str) -> str: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Self) -> bool: ... + if sys.version_info >= (3, 11): + def __ge__(self, other: Self) -> bool: ... + def __gt__(self, other: Self) -> bool: ... + def __le__(self, other: Self) -> bool: ... + else: + def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: ... -class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): +class _BaseNetwork(_IPAddressBase, Generic[_A]): network_address: _A netmask: _A - def __init__(self, address: object, strict: bool = ...) -> None: ... def __contains__(self, other: Any) -> bool: ... def __getitem__(self, n: int) -> _A: ... def __iter__(self) -> Iterator[_A]: ... - def address_exclude(self: _T, other: _T) -> Iterator[_T]: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Self) -> bool: ... + if sys.version_info >= (3, 11): + def __ge__(self, other: Self) -> bool: ... + def __gt__(self, other: Self) -> bool: ... + def __le__(self, other: Self) -> bool: ... + else: + def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + + def address_exclude(self, other: Self) -> Iterator[Self]: ... @property def broadcast_address(self) -> _A: ... - def compare_networks(self: _T, other: _T) -> int: ... + def compare_networks(self, other: Self) -> int: ... def hosts(self) -> Iterator[_A]: ... @property def is_global(self) -> bool: ... @@ -81,17 +89,14 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): @property def is_unspecified(self) -> bool: ... @property - def max_prefixlen(self) -> int: ... - @property def num_addresses(self) -> int: ... - def overlaps(self, other: _BaseNetwork[_A]) -> bool: ... + def overlaps(self, other: _BaseNetwork[IPv4Address] | _BaseNetwork[IPv6Address]) -> bool: ... @property def prefixlen(self) -> int: ... - if sys.version_info >= (3, 7): - def subnet_of(self: _T, other: _T) -> bool: ... - def supernet_of(self: _T, other: _T) -> bool: ... - def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Iterator[_T]: ... - def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> _T: ... + def subnet_of(self, other: Self) -> bool: ... + def supernet_of(self, other: Self) -> bool: ... + def subnets(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Iterator[Self]: ... + def supernet(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Self: ... @property def with_hostmask(self) -> str: ... @property @@ -101,12 +106,52 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): @property def hostmask(self) -> _A: ... -class _BaseInterface(_BaseAddress, Generic[_A, _N]): - hostmask: _A - netmask: _A - network: _N +class _BaseV4: + __slots__ = () + if sys.version_info >= (3, 14): + version: Final = 4 + max_prefixlen: Final = 32 + else: + @property + def version(self) -> Literal[4]: ... + @property + def max_prefixlen(self) -> Literal[32]: ... + +class IPv4Address(_BaseV4, _BaseAddress): + __slots__ = ("_ip", "__weakref__") + def __init__(self, address: object) -> None: ... @property - def ip(self) -> _A: ... + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def packed(self) -> bytes: ... + if sys.version_info >= (3, 13): + @property + def ipv6_mapped(self) -> IPv6Address: ... + +class IPv4Network(_BaseV4, _BaseNetwork[IPv4Address]): + def __init__(self, address: object, strict: bool = True) -> None: ... + +class IPv4Interface(IPv4Address): + netmask: IPv4Address + network: IPv4Network + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + @property + def hostmask(self) -> IPv4Address: ... + @property + def ip(self) -> IPv4Address: ... @property def with_hostmask(self) -> str: ... @property @@ -114,11 +159,36 @@ class _BaseInterface(_BaseAddress, Generic[_A, _N]): @property def with_prefixlen(self) -> str: ... -class IPv4Address(_BaseAddress): ... -class IPv4Network(_BaseNetwork[IPv4Address]): ... -class IPv4Interface(IPv4Address, _BaseInterface[IPv4Address, IPv4Network]): ... +class _BaseV6: + __slots__ = () + if sys.version_info >= (3, 14): + version: Final = 6 + max_prefixlen: Final = 128 + else: + @property + def version(self) -> Literal[6]: ... + @property + def max_prefixlen(self) -> Literal[128]: ... -class IPv6Address(_BaseAddress): +class IPv6Address(_BaseV6, _BaseAddress): + __slots__ = ("_ip", "_scope_id", "__weakref__") + def __init__(self, address: object) -> None: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def packed(self) -> bytes: ... @property def ipv4_mapped(self) -> IPv4Address | None: ... @property @@ -127,15 +197,31 @@ class IPv6Address(_BaseAddress): def sixtofour(self) -> IPv4Address | None: ... @property def teredo(self) -> tuple[IPv4Address, IPv4Address] | None: ... - if sys.version_info >= (3, 9): - @property - def scope_id(self) -> str | None: ... + @property + def scope_id(self) -> str | None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... -class IPv6Network(_BaseNetwork[IPv6Address]): +class IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]): + def __init__(self, address: object, strict: bool = True) -> None: ... @property def is_site_local(self) -> bool: ... -class IPv6Interface(IPv6Address, _BaseInterface[IPv6Address, IPv6Network]): ... +class IPv6Interface(IPv6Address): + netmask: IPv6Address + network: IPv6Network + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + @property + def hostmask(self) -> IPv6Address: ... + @property + def ip(self) -> IPv6Address: ... + @property + def with_hostmask(self) -> str: ... + @property + def with_netmask(self) -> str: ... + @property + def with_prefixlen(self) -> str: ... def v4_int_to_packed(address: int) -> bytes: ... def v6_int_to_packed(address: int) -> bytes: ... @@ -149,7 +235,9 @@ def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[I def summarize_address_range( first: IPv4Address | IPv6Address, last: IPv4Address | IPv6Address ) -> Iterator[IPv4Network] | Iterator[IPv6Network]: ... + def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... + @overload def get_mixed_type_key(obj: _A) -> tuple[int, _A]: ... @overload diff --git a/stdlib/itertools.pyi b/stdlib/itertools.pyi index 1ff7ffc181ed..d26a4e1da21e 100644 --- a/stdlib/itertools.pyi +++ b/stdlib/itertools.pyi @@ -1,189 +1,318 @@ import sys -from _typeshed import _T_co -from typing import ( - Any, - Callable, - Generic, - Iterable, - Iterator, - SupportsComplex, - SupportsFloat, - SupportsInt, - Tuple, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal, SupportsIndex - -if sys.version_info >= (3, 9): - from types import GenericAlias +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable, Iterator +from types import GenericAlias +from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeAlias, TypeVar, overload +from typing_extensions import Self, disjoint_base _T = TypeVar("_T") _S = TypeVar("_S") _N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) -_Step = Union[int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex] +_T_co = TypeVar("_T_co", covariant=True) +_S_co = TypeVar("_S_co", covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") +_T7 = TypeVar("_T7") +_T8 = TypeVar("_T8") +_T9 = TypeVar("_T9") +_T10 = TypeVar("_T10") + +_Step: TypeAlias = SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex -Predicate = Callable[[_T], object] +_Predicate: TypeAlias = Callable[[_T], object] # Technically count can take anything that implements a number protocol and has an add method # but we can't enforce the add method -class count(Iterator[_N], Generic[_N]): +@disjoint_base +class count(Generic[_N]): @overload def __new__(cls) -> count[int]: ... @overload - def __new__(cls, start: _N, step: _Step = ...) -> count[_N]: ... + def __new__(cls, start: _N, step: _Step = 1) -> count[_N]: ... @overload def __new__(cls, *, step: _N) -> count[_N]: ... + def __next__(self) -> _N: ... - def __iter__(self) -> Iterator[_N]: ... + def __iter__(self) -> Self: ... -class cycle(Iterator[_T], Generic[_T]): - def __init__(self, __iterable: Iterable[_T]) -> None: ... +@disjoint_base +class cycle(Generic[_T]): + def __new__(cls, iterable: Iterable[_T], /) -> Self: ... def __next__(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self) -> Self: ... -class repeat(Iterator[_T], Generic[_T]): +@disjoint_base +class repeat(Generic[_T]): @overload - def __init__(self, object: _T) -> None: ... + def __new__(cls, object: _T) -> Self: ... @overload - def __init__(self, object: _T, times: int) -> None: ... + def __new__(cls, object: _T, times: int) -> Self: ... + def __next__(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... - -class accumulate(Iterator[_T], Generic[_T]): - if sys.version_info >= (3, 8): - @overload - def __init__(self, iterable: Iterable[_T], func: None = ..., *, initial: _T | None = ...) -> None: ... - @overload - def __init__(self, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = ...) -> None: ... - else: - def __init__(self, iterable: Iterable[_T], func: Callable[[_T, _T], _T] | None = ...) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self) -> Self: ... + def __length_hint__(self) -> int: ... + +@disjoint_base +class accumulate(Generic[_T]): + @overload + def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ... + @overload + def __new__(cls, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = None) -> Self: ... + + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -class chain(Iterator[_T], Generic[_T]): - def __init__(self, *iterables: Iterable[_T]) -> None: ... +@disjoint_base +class chain(Generic[_T]): + def __new__(cls, *iterables: Iterable[_T]) -> Self: ... def __next__(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self) -> Self: ... @classmethod - # We use Type and not Type[_S] to not lose the type inference from __iterable - def from_iterable(cls: Type[Any], __iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... - -class compress(Iterator[_T], Generic[_T]): - def __init__(self, data: Iterable[_T], selectors: Iterable[Any]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... - def __next__(self) -> _T: ... + # We use type[Any] and not type[_S] to not lose the type inference from __iterable + def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class dropwhile(Iterator[_T], Generic[_T]): - def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... +@disjoint_base +class compress(Generic[_T]): + def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -class filterfalse(Iterator[_T], Generic[_T]): - def __init__(self, __predicate: Predicate[_T] | None, __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... +@disjoint_base +class dropwhile(Generic[_T]): + def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -_T1 = TypeVar("_T1") -_T2 = TypeVar("_T2") +@disjoint_base +class filterfalse(Generic[_T]): + def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... -class groupby(Iterator[Tuple[_T, Iterator[_S]]], Generic[_T, _S]): +@disjoint_base +class groupby(Generic[_T_co, _S_co]): @overload - def __new__(cls, iterable: Iterable[_T1], key: None = ...) -> groupby[_T1, _T1]: ... + def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... @overload def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ... - def __iter__(self) -> Iterator[tuple[_T, Iterator[_S]]]: ... - def __next__(self) -> tuple[_T, Iterator[_S]]: ... -class islice(Iterator[_T], Generic[_T]): + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... + +@disjoint_base +class islice(Generic[_T]): @overload - def __init__(self, __iterable: Iterable[_T], __stop: int | None) -> None: ... + def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... @overload - def __init__(self, __iterable: Iterable[_T], __start: int | None, __stop: int | None, __step: int | None = ...) -> None: ... - def __iter__(self) -> Iterator[_T]: ... - def __next__(self) -> _T: ... + def __new__(cls, iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = 1, /) -> Self: ... -class starmap(Iterator[_T], Generic[_T]): - def __init__(self, __function: Callable[..., _T], __iterable: Iterable[Iterable[Any]]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -class takewhile(Iterator[_T], Generic[_T]): - def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... +@disjoint_base +class starmap(Generic[_T_co]): + def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class takewhile(Generic[_T]): + def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... -def tee(__iterable: Iterable[_T], __n: int = ...) -> Tuple[Iterator[_T], ...]: ... +def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... -class zip_longest(Iterator[Any]): - def __init__(self, *p: Iterable[Any], fillvalue: Any = ...) -> None: ... - def __iter__(self) -> Iterator[Any]: ... - def __next__(self) -> Any: ... +@disjoint_base +class zip_longest(Generic[_T_co]): + # one iterable (fillvalue doesn't matter) + @overload + def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = None) -> zip_longest[tuple[_T1]]: ... + # two iterables + @overload + # In the overloads without fillvalue, all of the tuple members could theoretically be None, + # but we return Any instead to avoid false positives for code where we know one of the iterables + # is longer. + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T]]: ... + # three iterables + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T]]: ... + # four iterables + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T]]: ... + # five iterables + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone, _T5 | MaybeNone]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + fillvalue: _T, + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T, _T5 | _T]]: ... + # six or more iterables + @overload + def __new__( + cls, + iter1: Iterable[_T], + iter2: Iterable[_T], + iter3: Iterable[_T], + iter4: Iterable[_T], + iter5: Iterable[_T], + iter6: Iterable[_T], + /, + *iterables: Iterable[_T], + ) -> zip_longest[tuple[_T | MaybeNone, ...]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T], + iter2: Iterable[_T], + iter3: Iterable[_T], + iter4: Iterable[_T], + iter5: Iterable[_T], + iter6: Iterable[_T], + /, + *iterables: Iterable[_T], + fillvalue: _T, + ) -> zip_longest[tuple[_T, ...]]: ... -_T3 = TypeVar("_T3") -_T4 = TypeVar("_T4") -_T5 = TypeVar("_T5") -_T6 = TypeVar("_T6") + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... -class product(Iterator[_T_co], Generic[_T_co]): +@disjoint_base +class product(Generic[_T_co]): @overload - def __new__(cls, __iter1: Iterable[_T1]) -> product[tuple[_T1]]: ... + def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> product[tuple[_T1, _T2]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]: ... @overload - def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> product[tuple[_T1, _T2, _T3]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]: ... @overload def __new__( - cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / ) -> product[tuple[_T1, _T2, _T3, _T4]]: ... @overload def __new__( - cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def __new__( cls, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], - __iter6: Iterable[_T6], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + /, ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def __new__( cls, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - __iter7: Iterable[Any], - *iterables: Iterable[Any], - ) -> product[Tuple[Any, ...]]: ... - @overload - def __new__(cls, *iterables: Iterable[_T1], repeat: int) -> product[Tuple[_T1, ...]]: ... - @overload - def __new__(cls, *iterables: Iterable[Any], repeat: int = ...) -> product[Tuple[Any, ...]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + iter8: Iterable[_T8], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + iter8: Iterable[_T8], + iter9: Iterable[_T9], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + iter8: Iterable[_T8], + iter9: Iterable[_T9], + iter10: Iterable[_T10], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]: ... + @overload + def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ... + + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... -class permutations(Iterator[Tuple[_T, ...]], Generic[_T]): - def __init__(self, iterable: Iterable[_T], r: int | None = ...) -> None: ... - def __iter__(self) -> Iterator[Tuple[_T, ...]]: ... - def __next__(self) -> Tuple[_T, ...]: ... +@disjoint_base +class permutations(Generic[_T_co]): + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> permutations[tuple[_T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> permutations[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> permutations[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: int | None = None) -> permutations[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... -class combinations(Iterator[_T_co], Generic[_T_co]): +@disjoint_base +class combinations(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ... @overload @@ -193,17 +322,55 @@ class combinations(Iterator[_T_co], Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations[tuple[_T, _T, _T, _T, _T]]: ... @overload - def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[Tuple[_T, ...]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class combinations_with_replacement(Generic[_T_co]): + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> combinations_with_replacement[tuple[_T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> combinations_with_replacement[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations_with_replacement[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: int) -> combinations_with_replacement[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class pairwise(Generic[_T_co]): + def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... -class combinations_with_replacement(Iterator[Tuple[_T, ...]], Generic[_T]): - def __init__(self, iterable: Iterable[_T], r: int) -> None: ... - def __iter__(self) -> Iterator[Tuple[_T, ...]]: ... - def __next__(self) -> Tuple[_T, ...]: ... +if sys.version_info >= (3, 12): + @disjoint_base + class batched(Generic[_T_co]): + if sys.version_info >= (3, 13): + @overload + def __new__(cls, iterable: Iterable[_T], n: Literal[1], *, strict: Literal[True]) -> batched[tuple[_T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], n: Literal[2], *, strict: Literal[True]) -> batched[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], n: Literal[3], *, strict: Literal[True]) -> batched[tuple[_T, _T, _T]]: ... + @overload + def __new__( + cls, iterable: Iterable[_T], n: Literal[4], *, strict: Literal[True] + ) -> batched[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__( + cls, iterable: Iterable[_T], n: Literal[5], *, strict: Literal[True] + ) -> batched[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], n: int, *, strict: bool = False) -> batched[tuple[_T, ...]]: ... + else: + def __new__(cls, iterable: Iterable[_T], n: int) -> batched[tuple[_T, ...]]: ... -if sys.version_info >= (3, 10): - class pairwise(Iterator[_T_co], Generic[_T_co]): - def __new__(cls, __iterable: Iterable[_T]) -> pairwise[tuple[_T, _T]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... diff --git a/stdlib/json/__init__.pyi b/stdlib/json/__init__.pyi index 3e26d1b14f82..d853722c0fc8 100644 --- a/stdlib/json/__init__.pyi +++ b/stdlib/json/__init__.pyi @@ -1,58 +1,93 @@ -from _typeshed import SupportsRead -from typing import IO, Any, Callable, Type +import sys +from _typeshed import SupportsRead, SupportsWrite +from collections.abc import Callable +from typing import Any, Literal from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder from .encoder import JSONEncoder as JSONEncoder +__all__ = ["dump", "dumps", "load", "loads", "JSONDecoder", "JSONDecodeError", "JSONEncoder"] + def dumps( obj: Any, *, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., - indent: None | int | str = ..., - separators: tuple[str, str] | None = ..., - default: Callable[[Any], Any] | None = ..., - sort_keys: bool = ..., + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[JSONEncoder] | None = None, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[[Any], Any] | None = None, + sort_keys: bool = False, **kwds: Any, ) -> str: ... def dump( obj: Any, - fp: IO[str], + fp: SupportsWrite[str], *, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., - indent: None | int | str = ..., - separators: tuple[str, str] | None = ..., - default: Callable[[Any], Any] | None = ..., - sort_keys: bool = ..., + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[JSONEncoder] | None = None, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[[Any], Any] | None = None, + sort_keys: bool = False, **kwds: Any, ) -> None: ... -def loads( - s: str | bytes, - *, - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[dict[Any, Any]], Any] | None = ..., - parse_float: Callable[[str], Any] | None = ..., - parse_int: Callable[[str], Any] | None = ..., - parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., - **kwds: Any, -) -> Any: ... -def load( - fp: SupportsRead[str | bytes], - *, - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[dict[Any, Any]], Any] | None = ..., - parse_float: Callable[[str], Any] | None = ..., - parse_int: Callable[[str], Any] | None = ..., - parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., - **kwds: Any, -) -> Any: ... -def detect_encoding(b: bytes) -> str: ... # undocumented + +if sys.version_info >= (3, 15): + def loads( + s: str | bytes | bytearray, + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def load( + fp: SupportsRead[str | bytes], + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + +else: + def loads( + s: str | bytes | bytearray, + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def load( + fp: SupportsRead[str | bytes], + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + +def detect_encoding( + b: bytes | bytearray, +) -> Literal["utf-8", "utf-8-sig", "utf-16", "utf-16-be", "utf-16-le", "utf-32", "utf-32-be", "utf-32-le"]: ... # undocumented diff --git a/stdlib/json/decoder.pyi b/stdlib/json/decoder.pyi index adf09bb4bb7d..1b09579fb0c4 100644 --- a/stdlib/json/decoder.pyi +++ b/stdlib/json/decoder.pyi @@ -1,4 +1,8 @@ -from typing import Any, Callable +import sys +from collections.abc import Callable +from typing import Any + +__all__ = ["JSONDecoder", "JSONDecodeError"] class JSONDecodeError(ValueError): msg: str @@ -9,21 +13,38 @@ class JSONDecodeError(ValueError): def __init__(self, msg: str, doc: str, pos: int) -> None: ... class JSONDecoder: + if sys.version_info >= (3, 15): + array_hook: Callable[[list[Any]], Any] | None object_hook: Callable[[dict[str, Any]], Any] parse_float: Callable[[str], Any] parse_int: Callable[[str], Any] parse_constant: Callable[[str], Any] strict: bool object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] - def __init__( - self, - *, - object_hook: Callable[[dict[str, Any]], Any] | None = ..., - parse_float: Callable[[str], Any] | None = ..., - parse_int: Callable[[str], Any] | None = ..., - parse_constant: Callable[[str], Any] | None = ..., - strict: bool = ..., - object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + ) -> None: ... + + else: + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + ) -> None: ... + def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: ... # _w is undocumented - def raw_decode(self, s: str, idx: int = ...) -> tuple[Any, int]: ... + def raw_decode(self, s: str, idx: int = 0) -> tuple[Any, int]: ... diff --git a/stdlib/json/encoder.pyi b/stdlib/json/encoder.pyi index 6dd74896e5a0..83b78666d4a7 100644 --- a/stdlib/json/encoder.pyi +++ b/stdlib/json/encoder.pyi @@ -1,13 +1,17 @@ -from typing import Any, Callable, Iterator, Pattern +from collections.abc import Callable, Iterator +from re import Pattern +from typing import Any, Final -ESCAPE: Pattern[str] -ESCAPE_ASCII: Pattern[str] -HAS_UTF8: Pattern[bytes] -ESCAPE_DCT: dict[str, str] -INFINITY: float +ESCAPE: Final[Pattern[str]] # undocumented +ESCAPE_ASCII: Final[Pattern[str]] # undocumented +HAS_UTF8: Final[Pattern[bytes]] # undocumented +ESCAPE_DCT: Final[dict[str, str]] # undocumented +INFINITY: Final[float] # undocumented def py_encode_basestring(s: str) -> str: ... # undocumented def py_encode_basestring_ascii(s: str) -> str: ... # undocumented +def encode_basestring(s: str, /) -> str: ... # undocumented +def encode_basestring_ascii(s: str, /) -> str: ... # undocumented class JSONEncoder: item_separator: str @@ -18,19 +22,19 @@ class JSONEncoder: check_circular: bool allow_nan: bool sort_keys: bool - indent: int + indent: int | str def __init__( self, *, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - sort_keys: bool = ..., - indent: int | None = ..., - separators: tuple[str, str] | None = ..., - default: Callable[..., Any] | None = ..., + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + sort_keys: bool = False, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[..., Any] | None = None, ) -> None: ... def default(self, o: Any) -> Any: ... def encode(self, o: Any) -> str: ... - def iterencode(self, o: Any, _one_shot: bool = ...) -> Iterator[str]: ... + def iterencode(self, o: Any, _one_shot: bool = False) -> Iterator[str]: ... diff --git a/stdlib/json/scanner.pyi b/stdlib/json/scanner.pyi new file mode 100644 index 000000000000..68b42e92d295 --- /dev/null +++ b/stdlib/json/scanner.pyi @@ -0,0 +1,7 @@ +from _json import make_scanner as make_scanner +from re import Pattern +from typing import Final + +__all__ = ["make_scanner"] + +NUMBER_RE: Final[Pattern[str]] # undocumented diff --git a/stdlib/keyword.pyi b/stdlib/keyword.pyi index ac052feeba58..6b8bdad6beb6 100644 --- a/stdlib/keyword.pyi +++ b/stdlib/keyword.pyi @@ -1,10 +1,16 @@ -import sys -from typing import Sequence +from collections.abc import Sequence +from typing import Final -def iskeyword(s: str) -> bool: ... +__all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] -kwlist: Sequence[str] +def iskeyword(s: str, /) -> bool: ... -if sys.version_info >= (3, 9): - def issoftkeyword(s: str) -> bool: ... - softkwlist: Sequence[str] +# a list at runtime, but you're not meant to mutate it; +# type it as a sequence +kwlist: Final[Sequence[str]] + +def issoftkeyword(s: str, /) -> bool: ... + +# a list at runtime, but you're not meant to mutate it; +# type it as a sequence +softkwlist: Final[Sequence[str]] diff --git a/stdlib/lib2to3/btm_matcher.pyi b/stdlib/lib2to3/btm_matcher.pyi new file mode 100644 index 000000000000..4c87b664eb20 --- /dev/null +++ b/stdlib/lib2to3/btm_matcher.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections import defaultdict +from collections.abc import Iterable + +from .fixer_base import BaseFix +from .pytree import Leaf, Node + +class BMNode: + count: Incomplete + transition_table: Incomplete + fixers: Incomplete + id: Incomplete + content: str + def __init__(self) -> None: ... + +class BottomMatcher: + match: Incomplete + root: Incomplete + nodes: Incomplete + fixers: Incomplete + logger: Incomplete + def __init__(self) -> None: ... + def add_fixer(self, fixer: BaseFix) -> None: ... + def add(self, pattern: SupportsGetItem[int | slice, Incomplete] | None, start: BMNode) -> list[BMNode]: ... + def run(self, leaves: Iterable[Leaf]) -> defaultdict[BaseFix, list[Node | Leaf]]: ... + def print_ac(self) -> None: ... + +def type_repr(type_num: int) -> str | int: ... diff --git a/stdlib/lib2to3/fixer_base.pyi b/stdlib/lib2to3/fixer_base.pyi new file mode 100644 index 000000000000..06813c94308a --- /dev/null +++ b/stdlib/lib2to3/fixer_base.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete, StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import MutableMapping +from typing import ClassVar, Literal, TypeVar + +from .pytree import Base, Leaf, Node + +_N = TypeVar("_N", bound=Base) + +class BaseFix: + PATTERN: ClassVar[str | None] + pattern: Incomplete | None + pattern_tree: Incomplete | None + options: Incomplete | None + filename: Incomplete | None + numbers: Incomplete + used_names: Incomplete + order: ClassVar[Literal["post", "pre"]] + explicit: ClassVar[bool] + run_order: ClassVar[int] + keep_line_order: ClassVar[bool] + BM_compatible: ClassVar[bool] + syms: Incomplete + log: Incomplete + def __init__(self, options: MutableMapping[str, Incomplete], log: list[str]) -> None: ... + def compile_pattern(self) -> None: ... + def set_filename(self, filename: StrPath) -> None: ... + def match(self, node: _N) -> Literal[False] | dict[str, _N]: ... + @abstractmethod + def transform(self, node: Base, results: dict[str, Base]) -> Node | Leaf | None: ... + def new_name(self, template: str = "xxx_todo_changeme") -> str: ... + first_log: bool + def log_message(self, message: str) -> None: ... + def cannot_convert(self, node: Base, reason: str | None = None) -> None: ... + def warning(self, node: Base, reason: str) -> None: ... + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def finish_tree(self, tree: Node, filename: StrPath) -> None: ... + +class ConditionalFix(BaseFix, metaclass=ABCMeta): + skip_on: ClassVar[str | None] + def start_tree(self, tree: Node, filename: StrPath, /) -> None: ... + def should_skip(self, node: Base) -> bool: ... diff --git a/stdlib/@python2/email/mime/__init__.pyi b/stdlib/lib2to3/fixes/__init__.pyi similarity index 100% rename from stdlib/@python2/email/mime/__init__.pyi rename to stdlib/lib2to3/fixes/__init__.pyi diff --git a/stdlib/lib2to3/fixes/fix_apply.pyi b/stdlib/lib2to3/fixes/fix_apply.pyi new file mode 100644 index 000000000000..e53e3dd86457 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_apply.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixApply(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_asserts.pyi b/stdlib/lib2to3/fixes/fix_asserts.pyi new file mode 100644 index 000000000000..1bf7db2f76e9 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_asserts.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Final, Literal + +from ..fixer_base import BaseFix + +NAMES: Final[dict[str, str]] + +class FixAsserts(BaseFix): + BM_compatible: ClassVar[Literal[False]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_basestring.pyi b/stdlib/lib2to3/fixes/fix_basestring.pyi new file mode 100644 index 000000000000..8ed5ccaa7fd3 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_basestring.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixBasestring(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[Literal["'basestring'"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_buffer.pyi b/stdlib/lib2to3/fixes/fix_buffer.pyi new file mode 100644 index 000000000000..1efca6228ea2 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_buffer.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixBuffer(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_dict.pyi b/stdlib/lib2to3/fixes/fix_dict.pyi new file mode 100644 index 000000000000..08c54c3bc376 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_dict.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from .. import fixer_base + +iter_exempt: set[str] + +class FixDict(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... + P1: ClassVar[str] + p1: ClassVar[Incomplete] + P2: ClassVar[str] + p2: ClassVar[Incomplete] + def in_special_context(self, node, isiter): ... diff --git a/stdlib/lib2to3/fixes/fix_except.pyi b/stdlib/lib2to3/fixes/fix_except.pyi new file mode 100644 index 000000000000..0d856e6b0b7d --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_except.pyi @@ -0,0 +1,14 @@ +from collections.abc import Generator, Iterable +from typing import ClassVar, Literal, TypeVar + +from .. import fixer_base +from ..pytree import Base + +_N = TypeVar("_N", bound=Base) + +def find_excepts(nodes: Iterable[_N]) -> Generator[tuple[_N, _N]]: ... + +class FixExcept(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_exec.pyi b/stdlib/lib2to3/fixes/fix_exec.pyi new file mode 100644 index 000000000000..71e2a820a564 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_exec.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixExec(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_execfile.pyi b/stdlib/lib2to3/fixes/fix_execfile.pyi new file mode 100644 index 000000000000..8122a6389b12 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_execfile.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixExecfile(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_exitfunc.pyi b/stdlib/lib2to3/fixes/fix_exitfunc.pyi new file mode 100644 index 000000000000..7fc910c0a1bc --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_exitfunc.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete, StrPath +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +from ..pytree import Node + +class FixExitfunc(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def __init__(self, *args) -> None: ... + sys_import: Incomplete | None + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_filter.pyi b/stdlib/lib2to3/fixes/fix_filter.pyi new file mode 100644 index 000000000000..638889be8b65 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_filter.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixFilter(fixer_base.ConditionalFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip_on: ClassVar[Literal["future_builtins.filter"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_funcattrs.pyi b/stdlib/lib2to3/fixes/fix_funcattrs.pyi new file mode 100644 index 000000000000..60487bb1f2a6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_funcattrs.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixFuncattrs(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_future.pyi b/stdlib/lib2to3/fixes/fix_future.pyi new file mode 100644 index 000000000000..12ed93f21223 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_future.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixFuture(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_getcwdu.pyi b/stdlib/lib2to3/fixes/fix_getcwdu.pyi new file mode 100644 index 000000000000..aa3ccf50be9e --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_getcwdu.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixGetcwdu(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_has_key.pyi b/stdlib/lib2to3/fixes/fix_has_key.pyi new file mode 100644 index 000000000000..f6f5a072e21b --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_has_key.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixHasKey(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_idioms.pyi b/stdlib/lib2to3/fixes/fix_idioms.pyi new file mode 100644 index 000000000000..6b2723d09d43 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_idioms.pyi @@ -0,0 +1,15 @@ +from typing import ClassVar, Final, Literal + +from .. import fixer_base + +CMP: Final[str] +TYPE: Final[str] + +class FixIdioms(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + PATTERN: ClassVar[str] + def match(self, node): ... + def transform(self, node, results): ... + def transform_isinstance(self, node, results): ... + def transform_while(self, node, results) -> None: ... + def transform_sort(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_import.pyi b/stdlib/lib2to3/fixes/fix_import.pyi new file mode 100644 index 000000000000..2daa18327ec0 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_import.pyi @@ -0,0 +1,16 @@ +from _typeshed import StrPath +from collections.abc import Generator +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +def traverse_imports(names) -> Generator[str]: ... + +class FixImport(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip: bool + def start_tree(self, tree: Node, name: StrPath) -> None: ... + def transform(self, node, results): ... + def probably_a_local_import(self, imp_name): ... diff --git a/stdlib/lib2to3/fixes/fix_imports.pyi b/stdlib/lib2to3/fixes/fix_imports.pyi new file mode 100644 index 000000000000..d86ebbe215a1 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_imports.pyi @@ -0,0 +1,21 @@ +from _typeshed import StrPath +from collections.abc import Generator +from typing import ClassVar, Final, Literal + +from .. import fixer_base +from ..pytree import Node + +MAPPING: Final[dict[str, str]] + +def alternates(members): ... +def build_pattern(mapping=...) -> Generator[str]: ... + +class FixImports(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + mapping = MAPPING + def build_pattern(self): ... + def compile_pattern(self) -> None: ... + def match(self, node): ... + replace: dict[str, str] + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_imports2.pyi b/stdlib/lib2to3/fixes/fix_imports2.pyi new file mode 100644 index 000000000000..618ecd0424d8 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_imports2.pyi @@ -0,0 +1,8 @@ +from typing import Final + +from . import fix_imports + +MAPPING: Final[dict[str, str]] + +class FixImports2(fix_imports.FixImports): + mapping = MAPPING diff --git a/stdlib/lib2to3/fixes/fix_input.pyi b/stdlib/lib2to3/fixes/fix_input.pyi new file mode 100644 index 000000000000..fc1279535bed --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_input.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from .. import fixer_base + +context: Incomplete + +class FixInput(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_intern.pyi b/stdlib/lib2to3/fixes/fix_intern.pyi new file mode 100644 index 000000000000..804b7b2517a5 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_intern.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixIntern(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_isinstance.pyi b/stdlib/lib2to3/fixes/fix_isinstance.pyi new file mode 100644 index 000000000000..31eefd625317 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_isinstance.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixIsinstance(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_itertools.pyi b/stdlib/lib2to3/fixes/fix_itertools.pyi new file mode 100644 index 000000000000..229d86ee71bb --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_itertools.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixItertools(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + it_funcs: str + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_itertools_imports.pyi b/stdlib/lib2to3/fixes/fix_itertools_imports.pyi new file mode 100644 index 000000000000..39a4da506867 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_itertools_imports.pyi @@ -0,0 +1,7 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixItertoolsImports(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_long.pyi b/stdlib/lib2to3/fixes/fix_long.pyi new file mode 100644 index 000000000000..9ccf2711d7d1 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_long.pyi @@ -0,0 +1,7 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixLong(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[Literal["'long'"]] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_map.pyi b/stdlib/lib2to3/fixes/fix_map.pyi new file mode 100644 index 000000000000..6e60282cf0be --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_map.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixMap(fixer_base.ConditionalFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip_on: ClassVar[Literal["future_builtins.map"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_metaclass.pyi b/stdlib/lib2to3/fixes/fix_metaclass.pyi new file mode 100644 index 000000000000..6ad25e9aac36 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_metaclass.pyi @@ -0,0 +1,17 @@ +from collections.abc import Generator +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Base + +def has_metaclass(parent): ... +def fixup_parse_tree(cls_node) -> None: ... +def fixup_simple_stmt(parent, i, stmt_node) -> None: ... +def remove_trailing_newline(node) -> None: ... +def find_metas(cls_node) -> Generator[tuple[Base, int, Base]]: ... +def fixup_indent(suite) -> None: ... + +class FixMetaclass(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_methodattrs.pyi b/stdlib/lib2to3/fixes/fix_methodattrs.pyi new file mode 100644 index 000000000000..ca9b71e43f85 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_methodattrs.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Final, Literal + +from .. import fixer_base + +MAP: Final[dict[str, str]] + +class FixMethodattrs(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_ne.pyi b/stdlib/lib2to3/fixes/fix_ne.pyi new file mode 100644 index 000000000000..6ff1220b0472 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_ne.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixNe(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + def match(self, node): ... + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_next.pyi b/stdlib/lib2to3/fixes/fix_next.pyi new file mode 100644 index 000000000000..b13914ae8c01 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_next.pyi @@ -0,0 +1,19 @@ +from _typeshed import StrPath +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +bind_warning: str + +class FixNext(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + order: ClassVar[Literal["pre"]] + shadowed_next: bool + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results) -> None: ... + +def is_assign_target(node): ... +def find_assign(node): ... +def is_subtree(root, node): ... diff --git a/stdlib/lib2to3/fixes/fix_nonzero.pyi b/stdlib/lib2to3/fixes/fix_nonzero.pyi new file mode 100644 index 000000000000..5c37fc12ef08 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_nonzero.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixNonzero(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_numliterals.pyi b/stdlib/lib2to3/fixes/fix_numliterals.pyi new file mode 100644 index 000000000000..113145e395f6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_numliterals.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixNumliterals(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + def match(self, node): ... + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_operator.pyi b/stdlib/lib2to3/fixes/fix_operator.pyi new file mode 100644 index 000000000000..b9863d38347b --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_operator.pyi @@ -0,0 +1,12 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +def invocation(s): ... + +class FixOperator(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + methods: str + obj: str + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_paren.pyi b/stdlib/lib2to3/fixes/fix_paren.pyi new file mode 100644 index 000000000000..237df6c5ff2c --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_paren.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixParen(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_print.pyi b/stdlib/lib2to3/fixes/fix_print.pyi new file mode 100644 index 000000000000..e9564b04ac75 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_print.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from .. import fixer_base + +parend_expr: Incomplete + +class FixPrint(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... + def add_kwarg(self, l_nodes, s_kwd, n_expr) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_raise.pyi b/stdlib/lib2to3/fixes/fix_raise.pyi new file mode 100644 index 000000000000..e02c3080f409 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_raise.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixRaise(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_raw_input.pyi b/stdlib/lib2to3/fixes/fix_raw_input.pyi new file mode 100644 index 000000000000..d1a0eb0e0a7e --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_raw_input.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixRawInput(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_reduce.pyi b/stdlib/lib2to3/fixes/fix_reduce.pyi new file mode 100644 index 000000000000..f8ad876c21a6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_reduce.pyi @@ -0,0 +1,8 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixReduce(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_reload.pyi b/stdlib/lib2to3/fixes/fix_reload.pyi new file mode 100644 index 000000000000..820075438eca --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_reload.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixReload(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_renames.pyi b/stdlib/lib2to3/fixes/fix_renames.pyi new file mode 100644 index 000000000000..f095b3083ba8 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_renames.pyi @@ -0,0 +1,17 @@ +from collections.abc import Generator +from typing import ClassVar, Final, Literal + +from .. import fixer_base + +MAPPING: Final[dict[str, dict[str, str]]] +LOOKUP: Final[dict[tuple[str, str], str]] + +def alternates(members): ... +def build_pattern() -> Generator[str]: ... + +class FixRenames(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def match(self, node): ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_repr.pyi b/stdlib/lib2to3/fixes/fix_repr.pyi new file mode 100644 index 000000000000..3b192d396dd6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_repr.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixRepr(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_set_literal.pyi b/stdlib/lib2to3/fixes/fix_set_literal.pyi new file mode 100644 index 000000000000..6962ff326f56 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_set_literal.pyi @@ -0,0 +1,7 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixSetLiteral(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_standarderror.pyi b/stdlib/lib2to3/fixes/fix_standarderror.pyi new file mode 100644 index 000000000000..ba914bcab5d6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_standarderror.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixStandarderror(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_sys_exc.pyi b/stdlib/lib2to3/fixes/fix_sys_exc.pyi new file mode 100644 index 000000000000..0fa1a4787087 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_sys_exc.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixSysExc(fixer_base.BaseFix): + exc_info: ClassVar[list[str]] + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_throw.pyi b/stdlib/lib2to3/fixes/fix_throw.pyi new file mode 100644 index 000000000000..4c99855e5c37 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_throw.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixThrow(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_tuple_params.pyi b/stdlib/lib2to3/fixes/fix_tuple_params.pyi new file mode 100644 index 000000000000..7f4f7f4e8656 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_tuple_params.pyi @@ -0,0 +1,16 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +def is_docstring(stmt): ... + +class FixTupleParams(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... + def transform_lambda(self, node, results) -> None: ... + +def simplify_args(node): ... +def find_params(node): ... +def map_to_index(param_list, prefix=[], d=None): ... +def tuple_name(param_list): ... diff --git a/stdlib/lib2to3/fixes/fix_types.pyi b/stdlib/lib2to3/fixes/fix_types.pyi new file mode 100644 index 000000000000..e26dbec71a97 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_types.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixTypes(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_unicode.pyi b/stdlib/lib2to3/fixes/fix_unicode.pyi new file mode 100644 index 000000000000..85d1315213b9 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_unicode.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrPath +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +class FixUnicode(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + unicode_literals: bool + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_urllib.pyi b/stdlib/lib2to3/fixes/fix_urllib.pyi new file mode 100644 index 000000000000..ab84114f90ea --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_urllib.pyi @@ -0,0 +1,15 @@ +from collections.abc import Generator +from typing import Final, Literal + +from .fix_imports import FixImports + +MAPPING: Final[dict[str, list[tuple[Literal["urllib.request", "urllib.parse", "urllib.error"], list[str]]]]] + +def build_pattern() -> Generator[str]: ... + +class FixUrllib(FixImports): + def build_pattern(self): ... + def transform_import(self, node, results) -> None: ... + def transform_member(self, node, results): ... + def transform_dot(self, node, results) -> None: ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_ws_comma.pyi b/stdlib/lib2to3/fixes/fix_ws_comma.pyi new file mode 100644 index 000000000000..4ce5cb2c4ac1 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_ws_comma.pyi @@ -0,0 +1,12 @@ +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Leaf + +class FixWsComma(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + PATTERN: ClassVar[str] + COMMA: Leaf + COLON: Leaf + SEPS: tuple[Leaf, Leaf] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_xrange.pyi b/stdlib/lib2to3/fixes/fix_xrange.pyi new file mode 100644 index 000000000000..71318b7660b6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_xrange.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete, StrPath +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +class FixXrange(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + transformed_xranges: set[Incomplete] | None + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def finish_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results): ... + def transform_xrange(self, node, results) -> None: ... + def transform_range(self, node, results): ... + P1: ClassVar[str] + p1: ClassVar[Incomplete] + P2: ClassVar[str] + p2: ClassVar[Incomplete] + def in_special_context(self, node): ... diff --git a/stdlib/lib2to3/fixes/fix_xreadlines.pyi b/stdlib/lib2to3/fixes/fix_xreadlines.pyi new file mode 100644 index 000000000000..b4794143a003 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_xreadlines.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixXreadlines(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_zip.pyi b/stdlib/lib2to3/fixes/fix_zip.pyi new file mode 100644 index 000000000000..805886ee3180 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_zip.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixZip(fixer_base.ConditionalFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip_on: ClassVar[Literal["future_builtins.zip"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/main.pyi b/stdlib/lib2to3/main.pyi new file mode 100644 index 000000000000..5b7fdfca5d65 --- /dev/null +++ b/stdlib/lib2to3/main.pyi @@ -0,0 +1,42 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Container, Iterable, Iterator, Mapping, Sequence +from logging import _ExcInfoType +from typing import AnyStr, Literal + +from . import refactor as refactor + +def diff_texts(a: str, b: str, filename: str) -> Iterator[str]: ... + +class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): + nobackups: bool + show_diffs: bool + def __init__( + self, + fixers: Iterable[str], + options: Mapping[str, object] | None, + explicit: Container[str] | None, + nobackups: bool, + show_diffs: bool, + input_base_dir: str = "", + output_dir: str = "", + append_suffix: str = "", + ) -> None: ... + # Same as super.log_error and Logger.error + def log_error( # type: ignore[override] + self, + msg: str, + *args: Iterable[str], + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + # Same as super.write_file but without default values + def write_file( # type: ignore[override] + self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None + ) -> None: ... + # filename has to be str + def print_output(self, old: str, new: str, filename: str, equal: bool) -> None: ... # type: ignore[override] + +def warn(msg: object) -> None: ... +def main(fixer_pkg: str, args: Sequence[AnyStr] | None = None) -> Literal[0, 1, 2]: ... diff --git a/stdlib/lib2to3/pgen2/__init__.pyi b/stdlib/lib2to3/pgen2/__init__.pyi index e69de29bb2d1..3b1cbef7727d 100644 --- a/stdlib/lib2to3/pgen2/__init__.pyi +++ b/stdlib/lib2to3/pgen2/__init__.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from typing import Any, TypeAlias + +from ..pytree import _RawNode +from .grammar import Grammar + +# This is imported in several lib2to3/pgen2 submodules +_Convert: TypeAlias = Callable[[Grammar, _RawNode], Any] # noqa: Y047 diff --git a/stdlib/lib2to3/pgen2/driver.pyi b/stdlib/lib2to3/pgen2/driver.pyi index a8159dccf037..dea13fb9d0f8 100644 --- a/stdlib/lib2to3/pgen2/driver.pyi +++ b/stdlib/lib2to3/pgen2/driver.pyi @@ -1,20 +1,27 @@ from _typeshed import StrPath -from lib2to3.pgen2.grammar import Grammar -from lib2to3.pytree import _NL, _Convert +from collections.abc import Iterable from logging import Logger -from typing import IO, Any, Iterable +from typing import IO + +from ..pytree import _NL +from . import _Convert +from .grammar import Grammar + +__all__ = ["Driver", "load_grammar"] class Driver: grammar: Grammar logger: Logger convert: _Convert - def __init__(self, grammar: Grammar, convert: _Convert | None = ..., logger: Logger | None = ...) -> None: ... - def parse_tokens(self, tokens: Iterable[Any], debug: bool = ...) -> _NL: ... - def parse_stream_raw(self, stream: IO[str], debug: bool = ...) -> _NL: ... - def parse_stream(self, stream: IO[str], debug: bool = ...) -> _NL: ... - def parse_file(self, filename: StrPath, encoding: str | None = ..., debug: bool = ...) -> _NL: ... - def parse_string(self, text: str, debug: bool = ...) -> _NL: ... + def __init__(self, grammar: Grammar, convert: _Convert | None = None, logger: Logger | None = None) -> None: ... + def parse_tokens( + self, tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]], debug: bool = False + ) -> _NL: ... + def parse_stream_raw(self, stream: IO[str], debug: bool = False) -> _NL: ... + def parse_stream(self, stream: IO[str], debug: bool = False) -> _NL: ... + def parse_file(self, filename: StrPath, encoding: str | None = None, debug: bool = False) -> _NL: ... + def parse_string(self, text: str, debug: bool = False) -> _NL: ... def load_grammar( - gt: str = ..., gp: str | None = ..., save: bool = ..., force: bool = ..., logger: Logger | None = ... + gt: str = "Grammar.txt", gp: str | None = None, save: bool = True, force: bool = False, logger: Logger | None = None ) -> Grammar: ... diff --git a/stdlib/lib2to3/pgen2/grammar.pyi b/stdlib/lib2to3/pgen2/grammar.pyi index 48cb4eae916c..5093422ae236 100644 --- a/stdlib/lib2to3/pgen2/grammar.pyi +++ b/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,10 +1,10 @@ from _typeshed import StrPath -from typing import Dict, List, Optional, Tuple, TypeVar +from typing import TypeAlias +from typing_extensions import Self -_P = TypeVar("_P") -_Label = Tuple[int, Optional[str]] -_DFA = List[List[Tuple[int, int]]] -_DFAS = Tuple[_DFA, Dict[int, int]] +_Label: TypeAlias = tuple[int, str | None] +_DFA: TypeAlias = list[list[tuple[int, int]]] +_DFAS: TypeAlias = tuple[_DFA, dict[int, int]] class Grammar: symbol2number: dict[str, int] @@ -16,10 +16,9 @@ class Grammar: tokens: dict[int, int] symbol2label: dict[str, int] start: int - def __init__(self) -> None: ... def dump(self, filename: StrPath) -> None: ... def load(self, filename: StrPath) -> None: ... - def copy(self: _P) -> _P: ... + def copy(self) -> Self: ... def report(self) -> None: ... opmap_raw: str diff --git a/stdlib/lib2to3/pgen2/literals.pyi b/stdlib/lib2to3/pgen2/literals.pyi index 551ece19abd3..c3fabe8a5177 100644 --- a/stdlib/lib2to3/pgen2/literals.pyi +++ b/stdlib/lib2to3/pgen2/literals.pyi @@ -1,4 +1,4 @@ -from typing import Match +from re import Match simple_escapes: dict[str, str] diff --git a/stdlib/lib2to3/pgen2/parse.pyi b/stdlib/lib2to3/pgen2/parse.pyi index e776ed1e5a61..9befe9bf879d 100644 --- a/stdlib/lib2to3/pgen2/parse.pyi +++ b/stdlib/lib2to3/pgen2/parse.pyi @@ -1,8 +1,12 @@ -from lib2to3.pgen2.grammar import _DFAS, Grammar -from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, Sequence +from _typeshed import Incomplete +from collections.abc import Sequence +from typing import TypeAlias -_Context = Sequence[Any] +from ..pytree import _NL, _RawNode +from . import _Convert +from .grammar import _DFAS, Grammar + +_Context: TypeAlias = Sequence[Incomplete] class ParseError(Exception): msg: str @@ -17,8 +21,8 @@ class Parser: stack: list[tuple[_DFAS, int, _RawNode]] rootnode: _NL | None used_names: set[str] - def __init__(self, grammar: Grammar, convert: _Convert | None = ...) -> None: ... - def setup(self, start: int | None = ...) -> None: ... + def __init__(self, grammar: Grammar, convert: _Convert | None = None) -> None: ... + def setup(self, start: int | None = None) -> None: ... def addtoken(self, type: int, value: str | None, context: _Context) -> bool: ... def classify(self, type: int, value: str | None, context: _Context) -> int: ... def shift(self, type: int, value: str | None, newstate: int, context: _Context) -> None: ... diff --git a/stdlib/lib2to3/pgen2/pgen.pyi b/stdlib/lib2to3/pgen2/pgen.pyi index 11680157d199..e0e2b8593a34 100644 --- a/stdlib/lib2to3/pgen2/pgen.pyi +++ b/stdlib/lib2to3/pgen2/pgen.pyi @@ -1,7 +1,10 @@ -from _typeshed import StrPath -from lib2to3.pgen2 import grammar -from lib2to3.pgen2.tokenize import _TokenInfo -from typing import IO, Any, Iterable, Iterator, NoReturn +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Iterator +from typing import IO, ClassVar, overload +from typing_extensions import Never + +from . import grammar +from .tokenize import _TokenInfo class PgenGrammar(grammar.Grammar): ... @@ -10,7 +13,7 @@ class ParserGenerator: stream: IO[str] generator: Iterator[_TokenInfo] first: dict[str, dict[str, int]] - def __init__(self, filename: StrPath, stream: IO[str] | None = ...) -> None: ... + def __init__(self, filename: StrPath, stream: IO[str] | None = None) -> None: ... def make_grammar(self) -> PgenGrammar: ... def make_first(self, c: PgenGrammar, name: str) -> dict[int, int]: ... def make_label(self, c: PgenGrammar, label: str) -> int: ... @@ -25,22 +28,26 @@ class ParserGenerator: def parse_alt(self) -> tuple[NFAState, NFAState]: ... def parse_item(self) -> tuple[NFAState, NFAState]: ... def parse_atom(self) -> tuple[NFAState, NFAState]: ... - def expect(self, type: int, value: Any | None = ...) -> str: ... + def expect(self, type: int, value: str | None = None) -> str: ... def gettoken(self) -> None: ... - def raise_error(self, msg: str, *args: Any) -> NoReturn: ... + + @overload + def raise_error(self, msg: object) -> Never: ... + @overload + def raise_error(self, msg: str, *args: object) -> Never: ... class NFAState: arcs: list[tuple[str | None, NFAState]] - def __init__(self) -> None: ... - def addarc(self, next: NFAState, label: str | None = ...) -> None: ... + def addarc(self, next: NFAState, label: str | None = None) -> None: ... class DFAState: - nfaset: dict[NFAState, Any] + nfaset: dict[NFAState, Incomplete] isfinal: bool arcs: dict[str, DFAState] - def __init__(self, nfaset: dict[NFAState, Any], final: NFAState) -> None: ... + def __init__(self, nfaset: dict[NFAState, Incomplete], final: NFAState) -> None: ... def addarc(self, next: DFAState, label: str) -> None: ... def unifystate(self, old: DFAState, new: DFAState) -> None: ... - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: DFAState) -> bool: ... # type: ignore[override] + __hash__: ClassVar[None] # type: ignore[assignment] -def generate_grammar(filename: StrPath = ...) -> PgenGrammar: ... +def generate_grammar(filename: StrPath = "Grammar.txt") -> PgenGrammar: ... diff --git a/stdlib/lib2to3/pgen2/token.pyi b/stdlib/lib2to3/pgen2/token.pyi index 2f944c40a02c..6898517acee6 100644 --- a/stdlib/lib2to3/pgen2/token.pyi +++ b/stdlib/lib2to3/pgen2/token.pyi @@ -1,68 +1,67 @@ -import sys +from typing import Final -ENDMARKER: int -NAME: int -NUMBER: int -STRING: int -NEWLINE: int -INDENT: int -DEDENT: int -LPAR: int -RPAR: int -LSQB: int -RSQB: int -COLON: int -COMMA: int -SEMI: int -PLUS: int -MINUS: int -STAR: int -SLASH: int -VBAR: int -AMPER: int -LESS: int -GREATER: int -EQUAL: int -DOT: int -PERCENT: int -BACKQUOTE: int -LBRACE: int -RBRACE: int -EQEQUAL: int -NOTEQUAL: int -LESSEQUAL: int -GREATEREQUAL: int -TILDE: int -CIRCUMFLEX: int -LEFTSHIFT: int -RIGHTSHIFT: int -DOUBLESTAR: int -PLUSEQUAL: int -MINEQUAL: int -STAREQUAL: int -SLASHEQUAL: int -PERCENTEQUAL: int -AMPEREQUAL: int -VBAREQUAL: int -CIRCUMFLEXEQUAL: int -LEFTSHIFTEQUAL: int -RIGHTSHIFTEQUAL: int -DOUBLESTAREQUAL: int -DOUBLESLASH: int -DOUBLESLASHEQUAL: int -OP: int -COMMENT: int -NL: int -RARROW: int -AT: int -ATEQUAL: int -AWAIT: int -ASYNC: int -ERRORTOKEN: int -if sys.version_info >= (3, 7): - COLONEQUAL: int -N_TOKENS: int -NT_OFFSET: int +ENDMARKER: Final[int] +NAME: Final[int] +NUMBER: Final[int] +STRING: Final[int] +NEWLINE: Final[int] +INDENT: Final[int] +DEDENT: Final[int] +LPAR: Final[int] +RPAR: Final[int] +LSQB: Final[int] +RSQB: Final[int] +COLON: Final[int] +COMMA: Final[int] +SEMI: Final[int] +PLUS: Final[int] +MINUS: Final[int] +STAR: Final[int] +SLASH: Final[int] +VBAR: Final[int] +AMPER: Final[int] +LESS: Final[int] +GREATER: Final[int] +EQUAL: Final[int] +DOT: Final[int] +PERCENT: Final[int] +BACKQUOTE: Final[int] +LBRACE: Final[int] +RBRACE: Final[int] +EQEQUAL: Final[int] +NOTEQUAL: Final[int] +LESSEQUAL: Final[int] +GREATEREQUAL: Final[int] +TILDE: Final[int] +CIRCUMFLEX: Final[int] +LEFTSHIFT: Final[int] +RIGHTSHIFT: Final[int] +DOUBLESTAR: Final[int] +PLUSEQUAL: Final[int] +MINEQUAL: Final[int] +STAREQUAL: Final[int] +SLASHEQUAL: Final[int] +PERCENTEQUAL: Final[int] +AMPEREQUAL: Final[int] +VBAREQUAL: Final[int] +CIRCUMFLEXEQUAL: Final[int] +LEFTSHIFTEQUAL: Final[int] +RIGHTSHIFTEQUAL: Final[int] +DOUBLESTAREQUAL: Final[int] +DOUBLESLASH: Final[int] +DOUBLESLASHEQUAL: Final[int] +OP: Final[int] +COMMENT: Final[int] +NL: Final[int] +RARROW: Final[int] +AT: Final[int] +ATEQUAL: Final[int] +AWAIT: Final[int] +ASYNC: Final[int] +ERRORTOKEN: Final[int] +COLONEQUAL: Final[int] +N_TOKENS: Final[int] +NT_OFFSET: Final[int] tok_name: dict[int, str] def ISTERMINAL(x: int) -> bool: ... diff --git a/stdlib/lib2to3/pgen2/tokenize.pyi b/stdlib/lib2to3/pgen2/tokenize.pyi index e96a0d8c8eb3..76ff733163af 100644 --- a/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,9 +1,83 @@ -from lib2to3.pgen2.token import * # noqa -from typing import Callable, Iterable, Iterator, Tuple +from collections.abc import Callable, Iterable, Iterator +from typing import TypeAlias -_Coord = Tuple[int, int] -_TokenEater = Callable[[int, str, _Coord, _Coord, str], None] -_TokenInfo = Tuple[int, str, _Coord, _Coord, str] +from .token import * + +__all__ = [ + "AMPER", + "AMPEREQUAL", + "ASYNC", + "AT", + "ATEQUAL", + "AWAIT", + "BACKQUOTE", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "VBAR", + "VBAREQUAL", + "tok_name", + "tokenize", + "generate_tokens", + "untokenize", + "COLONEQUAL", +] + +_Coord: TypeAlias = tuple[int, int] +_TokenEater: TypeAlias = Callable[[int, str, _Coord, _Coord, str], object] +_TokenInfo: TypeAlias = tuple[int, str, _Coord, _Coord, str] class TokenError(Exception): ... class StopTokenizing(Exception): ... @@ -14,7 +88,6 @@ class Untokenizer: tokens: list[str] prev_row: int prev_col: int - def __init__(self) -> None: ... def add_whitespace(self, start: _Coord) -> None: ... def untokenize(self, iterable: Iterable[_TokenInfo]) -> str: ... def compat(self, token: tuple[int, str], iterable: Iterable[_TokenInfo]) -> None: ... diff --git a/stdlib/lib2to3/pygram.pyi b/stdlib/lib2to3/pygram.pyi index bf96a55c41b3..86c74b54888a 100644 --- a/stdlib/lib2to3/pygram.pyi +++ b/stdlib/lib2to3/pygram.pyi @@ -1,4 +1,4 @@ -from lib2to3.pgen2.grammar import Grammar +from .pgen2.grammar import Grammar class Symbols: def __init__(self, grammar: Grammar) -> None: ... @@ -110,4 +110,5 @@ class pattern_symbols(Symbols): python_grammar: Grammar python_grammar_no_print_statement: Grammar +python_grammar_no_print_and_exec_statement: Grammar pattern_grammar: Grammar diff --git a/stdlib/lib2to3/pytree.pyi b/stdlib/lib2to3/pytree.pyi index eab82cbc200d..f634f5065c0e 100644 --- a/stdlib/lib2to3/pytree.pyi +++ b/stdlib/lib2to3/pytree.pyi @@ -1,16 +1,20 @@ -from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union +from _typeshed import SupportsGetItem, SupportsLenAndGetItem, Unused +from abc import abstractmethod +from collections.abc import Iterable, Iterator, MutableSequence +from typing import ClassVar, Final, TypeAlias +from typing_extensions import Self -_P = TypeVar("_P") -_NL = Union[Node, Leaf] -_Context = Tuple[str, int, int] -_Results = Dict[str, _NL] -_RawNode = Tuple[int, str, _Context, Optional[List[_NL]]] -_Convert = Callable[[Grammar, _RawNode], Any] +from .fixer_base import BaseFix +from .pgen2.grammar import Grammar -HUGE: int +_NL: TypeAlias = Node | Leaf +_Context: TypeAlias = tuple[str, int, int] +_Results: TypeAlias = dict[str, _NL] +_RawNode: TypeAlias = tuple[int, str, _Context, list[_NL] | None] -def type_repr(type_num: int) -> str: ... +HUGE: Final = 0x7FFFFFFF + +def type_repr(type_num: int) -> str | int: ... class Base: type: int @@ -19,11 +23,16 @@ class Base: children: list[_NL] was_changed: bool was_checked: bool - def __eq__(self, other: Any) -> bool: ... - def _eq(self: _P, other: _P) -> bool: ... - def clone(self: _P) -> _P: ... - def post_order(self) -> Iterator[_NL]: ... - def pre_order(self) -> Iterator[_NL]: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + @abstractmethod + def _eq(self, other: Base) -> bool: ... + @abstractmethod + def clone(self) -> Self: ... + @abstractmethod + def post_order(self) -> Iterator[Self]: ... + @abstractmethod + def pre_order(self) -> Iterator[Self]: ... def replace(self, new: _NL | list[_NL]) -> None: ... def get_lineno(self) -> int: ... def changed(self) -> None: ... @@ -37,27 +46,46 @@ class Base: def get_suffix(self) -> str: ... class Node(Base): - fixers_applied: list[Any] + fixers_applied: MutableSequence[BaseFix] | None + # Is Unbound until set in refactor.RefactoringTool + future_features: frozenset[str] + # Is Unbound until set in pgen2.parse.Parser.pop + used_names: set[str] def __init__( self, type: int, - children: list[_NL], - context: Any | None = ..., - prefix: str | None = ..., - fixers_applied: list[Any] | None = ..., + children: Iterable[_NL], + context: Unused = None, + prefix: str | None = None, + fixers_applied: MutableSequence[BaseFix] | None = None, ) -> None: ... + def _eq(self, other: Base) -> bool: ... + def clone(self) -> Node: ... + def post_order(self) -> Iterator[Self]: ... + def pre_order(self) -> Iterator[Self]: ... def set_child(self, i: int, child: _NL) -> None: ... def insert_child(self, i: int, child: _NL) -> None: ... def append_child(self, child: _NL) -> None: ... + def __unicode__(self) -> str: ... class Leaf(Base): lineno: int column: int value: str - fixers_applied: list[Any] + fixers_applied: MutableSequence[BaseFix] def __init__( - self, type: int, value: str, context: _Context | None = ..., prefix: str | None = ..., fixers_applied: list[Any] = ... + self, + type: int, + value: str, + context: _Context | None = None, + prefix: str | None = None, + fixers_applied: MutableSequence[BaseFix] = [], ) -> None: ... + def _eq(self, other: Base) -> bool: ... + def clone(self) -> Leaf: ... + def post_order(self) -> Iterator[Self]: ... + def pre_order(self) -> Iterator[Self]: ... + def __unicode__(self) -> str: ... def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... @@ -66,23 +94,25 @@ class BasePattern: content: str | None name: str | None def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns - def match(self, node: _NL, results: _Results | None = ...) -> bool: ... - def match_seq(self, nodes: list[_NL], results: _Results | None = ...) -> bool: ... - def generate_matches(self, nodes: list[_NL]) -> Iterator[tuple[int, _Results]]: ... + def match(self, node: _NL, results: _Results | None = None) -> bool: ... + def match_seq(self, nodes: SupportsLenAndGetItem[_NL], results: _Results | None = None) -> bool: ... + def generate_matches(self, nodes: SupportsGetItem[int, _NL]) -> Iterator[tuple[int, _Results]]: ... class LeafPattern(BasePattern): - def __init__(self, type: int | None = ..., content: str | None = ..., name: str | None = ...) -> None: ... + def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: ... class NodePattern(BasePattern): wildcards: bool - def __init__(self, type: int | None = ..., content: str | None = ..., name: str | None = ...) -> None: ... + def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: ... class WildcardPattern(BasePattern): min: int max: int - def __init__(self, content: str | None = ..., min: int = ..., max: int = ..., name: str | None = ...) -> None: ... + def __init__(self, content: str | None = None, min: int = 0, max: int = 0x7FFFFFFF, name: str | None = None) -> None: ... class NegatedPattern(BasePattern): - def __init__(self, content: str | None = ...) -> None: ... + def __init__(self, content: str | None = None) -> None: ... -def generate_matches(patterns: list[BasePattern], nodes: list[_NL]) -> Iterator[tuple[int, _Results]]: ... +def generate_matches( + patterns: SupportsGetItem[int | slice, BasePattern] | None, nodes: SupportsGetItem[int | slice, _NL] +) -> Iterator[tuple[int, _Results]]: ... diff --git a/stdlib/lib2to3/refactor.pyi b/stdlib/lib2to3/refactor.pyi index 6687092d862c..9031b1009715 100644 --- a/stdlib/lib2to3/refactor.pyi +++ b/stdlib/lib2to3/refactor.pyi @@ -1,13 +1,18 @@ +from _typeshed import FileDescriptorOrPath, StrPath, SupportsGetItem from collections.abc import Container, Generator, Iterable, Mapping -from logging import Logger -from typing import Any, ClassVar, NoReturn +from logging import Logger, _ExcInfoType +from multiprocessing import JoinableQueue +from multiprocessing.synchronize import Lock +from typing import Any, ClassVar, Final, overload +from typing_extensions import Never +from .btm_matcher import BottomMatcher +from .fixer_base import BaseFix +from .pgen2.driver import Driver from .pgen2.grammar import Grammar +from .pytree import Node -_Driver = Any # really lib2to3.driver.Driver -_BottomMatcher = Any # really lib2to3.btm_matcher.BottomMatcher - -def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = ...) -> list[str]: ... +def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = True) -> list[str]: ... def get_fixers_from_package(pkg_name: str) -> list[str]: ... class FixerError(Exception): ... @@ -20,51 +25,62 @@ class RefactoringTool: options: dict[str, Any] grammar: Grammar write_unchanged_files: bool - errors: list[Any] + errors: list[tuple[str, Iterable[str], dict[str, _ExcInfoType]]] logger: Logger - fixer_log: list[Any] + fixer_log: list[str] wrote: bool - driver: _Driver - pre_order: Any - post_order: Any - files: list[Any] - BM: _BottomMatcher - bmi_pre_order: list[Any] - bmi_post_order: list[Any] + driver: Driver + pre_order: list[BaseFix] + post_order: list[BaseFix] + files: list[StrPath] + BM: BottomMatcher + bmi_pre_order: list[BaseFix] + bmi_post_order: list[BaseFix] def __init__( - self, fixer_names: Iterable[str], options: Mapping[str, Any] | None = ..., explicit: Container[str] | None = ... + self, fixer_names: Iterable[str], options: Mapping[str, object] | None = None, explicit: Container[str] | None = None ) -> None: ... - def get_fixers(self) -> tuple[list[Any], list[Any]]: ... - def log_error(self, msg: str, *args: Any, **kwds: Any) -> NoReturn: ... - def log_message(self, msg: str, *args: Any) -> None: ... - def log_debug(self, msg: str, *args: Any) -> None: ... - def print_output(self, old_text: str, new_text: str, filename: str, equal): ... - def refactor(self, items: Iterable[str], write: bool = ..., doctests_only: bool = ...) -> None: ... - def refactor_dir(self, dir_name: str, write: bool = ..., doctests_only: bool = ...) -> None: ... - def _read_python_source(self, filename: str) -> tuple[str, str]: ... - def refactor_file(self, filename: str, write: bool = ..., doctests_only: bool = ...) -> None: ... - def refactor_string(self, data: str, name: str): ... - def refactor_stdin(self, doctests_only: bool = ...) -> None: ... - def refactor_tree(self, tree, name: str) -> bool: ... - def traverse_by(self, fixers, traversal) -> None: ... + def get_fixers(self) -> tuple[list[BaseFix], list[BaseFix]]: ... + def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> Never: ... + + @overload + def log_message(self, msg: object) -> None: ... + @overload + def log_message(self, msg: str, *args: object) -> None: ... + + @overload + def log_debug(self, msg: object) -> None: ... + @overload + def log_debug(self, msg: str, *args: object) -> None: ... + + def print_output(self, old_text: str, new_text: str, filename: StrPath, equal: bool) -> None: ... + def refactor(self, items: Iterable[str], write: bool = False, doctests_only: bool = False) -> None: ... + def refactor_dir(self, dir_name: str, write: bool = False, doctests_only: bool = False) -> None: ... + def _read_python_source(self, filename: FileDescriptorOrPath) -> tuple[str, str]: ... + def refactor_file(self, filename: StrPath, write: bool = False, doctests_only: bool = False) -> None: ... + def refactor_string(self, data: str, name: str) -> Node | None: ... + def refactor_stdin(self, doctests_only: bool = False) -> None: ... + def refactor_tree(self, tree: Node, name: str) -> bool: ... + def traverse_by(self, fixers: SupportsGetItem[int, Iterable[BaseFix]] | None, traversal: Iterable[Node]) -> None: ... def processed_file( - self, new_text: str, filename: str, old_text: str | None = ..., write: bool = ..., encoding: str | None = ... + self, new_text: str, filename: StrPath, old_text: str | None = None, write: bool = False, encoding: str | None = None ) -> None: ... - def write_file(self, new_text: str, filename: str, old_text: str, encoding: str | None = ...) -> None: ... - PS1: ClassVar[str] - PS2: ClassVar[str] - def refactor_docstring(self, input: str, filename: str) -> str: ... - def refactor_doctest(self, block: list[str], lineno: int, indent: int, filename: str) -> list[str]: ... + def write_file(self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None = None) -> None: ... + PS1: Final = ">>> " + PS2: Final = "... " + def refactor_docstring(self, input: str, filename: StrPath) -> str: ... + def refactor_doctest(self, block: list[str], lineno: int, indent: int, filename: StrPath) -> list[str]: ... def summarize(self) -> None: ... - def parse_block(self, block: Iterable[str], lineno: int, indent: int): ... + def parse_block(self, block: Iterable[str], lineno: int, indent: int) -> Node: ... def wrap_toks( self, block: Iterable[str], lineno: int, indent: int - ) -> Generator[tuple[Any, Any, tuple[int, int], tuple[int, int], str], None, None]: ... - def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str, None, None]: ... + ) -> Generator[tuple[int, str, tuple[int, int], tuple[int, int], str]]: ... + def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str]: ... class MultiprocessingUnsupported(Exception): ... class MultiprocessRefactoringTool(RefactoringTool): - queue: Any | None - output_lock: Any | None - def refactor(self, items: Iterable[str], write: bool = ..., doctests_only: bool = ..., num_processes: int = ...) -> None: ... + queue: JoinableQueue[tuple[Iterable[str], bool | int] | None] | None + output_lock: Lock | None + def refactor( + self, items: Iterable[str], write: bool = False, doctests_only: bool = False, num_processes: int = 1 + ) -> None: ... diff --git a/stdlib/linecache.pyi b/stdlib/linecache.pyi index a66614bf6b37..f527e7084ced 100644 --- a/stdlib/linecache.pyi +++ b/stdlib/linecache.pyi @@ -1,16 +1,18 @@ -from typing import Any, Dict, List, Protocol, Tuple +from collections.abc import Callable +from typing import Any, TypeAlias -_ModuleGlobals = Dict[str, Any] -_ModuleMetadata = Tuple[int, float, List[str], str] +__all__ = ["getline", "clearcache", "checkcache", "lazycache"] -class _SourceLoader(Protocol): - def __call__(self) -> str | None: ... +_ModuleGlobals: TypeAlias = dict[str, Any] +_ModuleMetadata: TypeAlias = tuple[int, float | None, list[str], str] + +_SourceLoader: TypeAlias = tuple[Callable[[], str | None]] cache: dict[str, _SourceLoader | _ModuleMetadata] # undocumented -def getline(filename: str, lineno: int, module_globals: _ModuleGlobals | None = ...) -> str: ... +def getline(filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> str: ... def clearcache() -> None: ... -def getlines(filename: str, module_globals: _ModuleGlobals | None = ...) -> list[str]: ... -def checkcache(filename: str | None = ...) -> None: ... -def updatecache(filename: str, module_globals: _ModuleGlobals | None = ...) -> list[str]: ... +def getlines(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: ... +def checkcache(filename: str | None = None) -> None: ... +def updatecache(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: ... def lazycache(filename: str, module_globals: _ModuleGlobals) -> bool: ... diff --git a/stdlib/locale.pyi b/stdlib/locale.pyi index c6289f27da2c..d234a08d779c 100644 --- a/stdlib/locale.pyi +++ b/stdlib/locale.pyi @@ -1,104 +1,156 @@ import sys +from _locale import ( + CHAR_MAX as CHAR_MAX, + LC_ALL as LC_ALL, + LC_COLLATE as LC_COLLATE, + LC_CTYPE as LC_CTYPE, + LC_MONETARY as LC_MONETARY, + LC_NUMERIC as LC_NUMERIC, + LC_TIME as LC_TIME, + localeconv as localeconv, + strcoll as strcoll, + strxfrm as strxfrm, +) # This module defines a function "str()", which is why "str" can't be used # as a type annotation or type alias. from builtins import str as _str +from collections.abc import Callable, Iterable from decimal import Decimal -from typing import Any, Callable, Iterable, Mapping, Sequence, Tuple +from typing import Any +from typing_extensions import deprecated -CODESET: int -D_T_FMT: int -D_FMT: int -T_FMT: int -T_FMT_AMPM: int -AM_STR: int -PM_STR: int +if sys.version_info >= (3, 11): + from _locale import getencoding as getencoding -DAY_1: int -DAY_2: int -DAY_3: int -DAY_4: int -DAY_5: int -DAY_6: int -DAY_7: int -ABDAY_1: int -ABDAY_2: int -ABDAY_3: int -ABDAY_4: int -ABDAY_5: int -ABDAY_6: int -ABDAY_7: int +# Some parts of the `_locale` module are platform-specific: +if sys.platform != "win32": + from _locale import ( + ABDAY_1 as ABDAY_1, + ABDAY_2 as ABDAY_2, + ABDAY_3 as ABDAY_3, + ABDAY_4 as ABDAY_4, + ABDAY_5 as ABDAY_5, + ABDAY_6 as ABDAY_6, + ABDAY_7 as ABDAY_7, + ABMON_1 as ABMON_1, + ABMON_2 as ABMON_2, + ABMON_3 as ABMON_3, + ABMON_4 as ABMON_4, + ABMON_5 as ABMON_5, + ABMON_6 as ABMON_6, + ABMON_7 as ABMON_7, + ABMON_8 as ABMON_8, + ABMON_9 as ABMON_9, + ABMON_10 as ABMON_10, + ABMON_11 as ABMON_11, + ABMON_12 as ABMON_12, + ALT_DIGITS as ALT_DIGITS, + AM_STR as AM_STR, + CODESET as CODESET, + CRNCYSTR as CRNCYSTR, + D_FMT as D_FMT, + D_T_FMT as D_T_FMT, + DAY_1 as DAY_1, + DAY_2 as DAY_2, + DAY_3 as DAY_3, + DAY_4 as DAY_4, + DAY_5 as DAY_5, + DAY_6 as DAY_6, + DAY_7 as DAY_7, + ERA as ERA, + ERA_D_FMT as ERA_D_FMT, + ERA_D_T_FMT as ERA_D_T_FMT, + ERA_T_FMT as ERA_T_FMT, + LC_MESSAGES as LC_MESSAGES, + MON_1 as MON_1, + MON_2 as MON_2, + MON_3 as MON_3, + MON_4 as MON_4, + MON_5 as MON_5, + MON_6 as MON_6, + MON_7 as MON_7, + MON_8 as MON_8, + MON_9 as MON_9, + MON_10 as MON_10, + MON_11 as MON_11, + MON_12 as MON_12, + NOEXPR as NOEXPR, + PM_STR as PM_STR, + RADIXCHAR as RADIXCHAR, + T_FMT as T_FMT, + T_FMT_AMPM as T_FMT_AMPM, + THOUSEP as THOUSEP, + YESEXPR as YESEXPR, + bind_textdomain_codeset as bind_textdomain_codeset, + bindtextdomain as bindtextdomain, + dcgettext as dcgettext, + dgettext as dgettext, + gettext as gettext, + nl_langinfo as nl_langinfo, + textdomain as textdomain, + ) -MON_1: int -MON_2: int -MON_3: int -MON_4: int -MON_5: int -MON_6: int -MON_7: int -MON_8: int -MON_9: int -MON_10: int -MON_11: int -MON_12: int -ABMON_1: int -ABMON_2: int -ABMON_3: int -ABMON_4: int -ABMON_5: int -ABMON_6: int -ABMON_7: int -ABMON_8: int -ABMON_9: int -ABMON_10: int -ABMON_11: int -ABMON_12: int +__all__ = [ + "getlocale", + "getdefaultlocale", + "getpreferredencoding", + "Error", + "setlocale", + "localeconv", + "strcoll", + "strxfrm", + "str", + "atof", + "atoi", + "format_string", + "currency", + "normalize", + "LC_CTYPE", + "LC_COLLATE", + "LC_TIME", + "LC_MONETARY", + "LC_NUMERIC", + "LC_ALL", + "CHAR_MAX", +] -RADIXCHAR: int -THOUSEP: int -YESEXPR: int -NOEXPR: int -CRNCYSTR: int +if sys.version_info >= (3, 11): + __all__ += ["getencoding"] -ERA: int -ERA_D_T_FMT: int -ERA_D_FMT: int -ERA_T_FMT: int +if sys.version_info < (3, 12): + __all__ += ["format"] -ALT_DIGITS: int +if sys.version_info < (3, 13): + __all__ += ["resetlocale"] -LC_CTYPE: int -LC_COLLATE: int -LC_TIME: int -LC_MONETARY: int -LC_MESSAGES: int -LC_NUMERIC: int -LC_ALL: int - -CHAR_MAX: int +if sys.platform != "win32": + __all__ += ["LC_MESSAGES"] class Error(Exception): ... -def setlocale(category: int, locale: _str | Iterable[_str] | None = ...) -> _str: ... -def localeconv() -> Mapping[_str, int | _str | list[int]]: ... -def nl_langinfo(__key: int) -> _str: ... -def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> tuple[_str | None, _str | None]: ... -def getlocale(category: int = ...) -> Sequence[_str]: ... -def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... +def getdefaultlocale( + envvars: tuple[_str, ...] = ("LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE") +) -> tuple[_str | None, _str | None]: ... +def getlocale(category: int = ...) -> tuple[_str | None, _str | None]: ... +def setlocale(category: int, locale: _str | Iterable[_str | None] | None = None) -> _str: ... +def getpreferredencoding(do_setlocale: bool = True) -> _str: ... def normalize(localename: _str) -> _str: ... -def resetlocale(category: int = ...) -> None: ... -def strcoll(__os1: _str, __os2: _str) -> int: ... -def strxfrm(__string: _str) -> _str: ... -def format(percent: _str, value: float | Decimal, grouping: bool = ..., monetary: bool = ..., *additional: Any) -> _str: ... -if sys.version_info >= (3, 7): - def format_string(f: _str, val: Any, grouping: bool = ..., monetary: bool = ...) -> _str: ... +if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.") + def resetlocale(category: int = ...) -> None: ... -else: - def format_string(f: _str, val: Any, grouping: bool = ...) -> _str: ... +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.7; removed in Python 3.12. Use `locale.format_string()` instead.") + def format( + percent: _str, value: float | Decimal, grouping: bool = False, monetary: bool = False, *additional: Any + ) -> _str: ... -def currency(val: int | float | Decimal, symbol: bool = ..., grouping: bool = ..., international: bool = ...) -> _str: ... +def format_string(f: _str, val: Any, grouping: bool = False, monetary: bool = False) -> _str: ... +def currency(val: float | Decimal, symbol: bool = True, grouping: bool = False, international: bool = False) -> _str: ... def delocalize(string: _str) -> _str: ... +def localize(string: _str, grouping: bool = False, monetary: bool = False) -> _str: ... def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... def atoi(string: _str) -> int: ... def str(val: float) -> _str: ... diff --git a/stdlib/logging/__init__.pyi b/stdlib/logging/__init__.pyi index 7d4fa279155c..f0864154b9e1 100644 --- a/stdlib/logging/__init__.pyi +++ b/stdlib/logging/__init__.pyi @@ -1,20 +1,83 @@ import sys import threading -from _typeshed import Self, StrPath, SupportsWrite +from _typeshed import StrPath, SupportsWrite from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from io import TextIOWrapper +from re import Pattern from string import Template from time import struct_time -from types import FrameType, TracebackType -from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, Tuple, Type, TypeVar, Union, overload -from typing_extensions import Literal +from types import FrameType, GenericAlias, TracebackType +from typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated + +__all__ = [ + "BASIC_FORMAT", + "BufferingFormatter", + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "FileHandler", + "Filter", + "Formatter", + "Handler", + "INFO", + "LogRecord", + "Logger", + "LoggerAdapter", + "NOTSET", + "NullHandler", + "StreamHandler", + "WARN", + "WARNING", + "addLevelName", + "basicConfig", + "captureWarnings", + "critical", + "debug", + "disable", + "error", + "exception", + "fatal", + "getLevelName", + "getLogger", + "getLoggerClass", + "info", + "log", + "makeLogRecord", + "setLoggerClass", + "shutdown", + "warning", + "getLogRecordFactory", + "setLogRecordFactory", + "lastResort", + "raiseExceptions", + "warn", +] + +if sys.version_info >= (3, 11): + __all__ += ["getLevelNamesMapping"] +if sys.version_info >= (3, 12): + __all__ += ["getHandlerByName", "getHandlerNames"] + +_SysExcInfoType: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] | tuple[None, None, None] +_ExcInfoType: TypeAlias = bool | _SysExcInfoType | BaseException | None +_ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object] +_Level: TypeAlias = int | str +_FormatStyle: TypeAlias = Literal["%", "{", "$"] + +if sys.version_info >= (3, 12): + @type_check_only + class _SupportsFilter(Protocol): + def filter(self, record: LogRecord, /) -> bool | LogRecord: ... + + _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool | LogRecord] | _SupportsFilter +else: + @type_check_only + class _SupportsFilter(Protocol): + def filter(self, record: LogRecord, /) -> bool: ... -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]] -_ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] -_ArgsType = Union[Tuple[object, ...], Mapping[str, object]] -_FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, str] -_FormatStyle = Literal["%", "{", "$"] + _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool] | _SupportsFilter raiseExceptions: bool logThreads: bool @@ -27,23 +90,25 @@ def currentframe() -> FrameType: ... _levelToName: dict[int, str] _nameToLevel: dict[str, int] -class Filterer(object): - filters: list[Filter] - def __init__(self) -> None: ... +class Filterer: + filters: list[_FilterType] def addFilter(self, filter: _FilterType) -> None: ... def removeFilter(self, filter: _FilterType) -> None: ... - def filter(self, record: LogRecord) -> bool: ... + if sys.version_info >= (3, 12): + def filter(self, record: LogRecord) -> bool | LogRecord: ... + else: + def filter(self, record: LogRecord) -> bool: ... -class Manager(object): # undocumented +class Manager: # undocumented root: RootLogger disable: int emittedNoHandlerWarning: bool loggerDict: dict[str, Logger | PlaceHolder] - loggerClass: Type[Logger] | None + loggerClass: type[Logger] | None logRecordFactory: Callable[..., LogRecord] | None def __init__(self, rootnode: RootLogger) -> None: ... def getLogger(self, name: str) -> Logger: ... - def setLoggerClass(self, klass: Type[Logger]) -> None: ... + def setLoggerClass(self, klass: type[Logger]) -> None: ... def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: ... class Logger(Filterer): @@ -55,178 +120,102 @@ class Logger(Filterer): disabled: bool # undocumented root: ClassVar[RootLogger] # undocumented manager: Manager # undocumented - def __init__(self, name: str, level: _Level = ...) -> None: ... + def __init__(self, name: str, level: _Level = 0) -> None: ... def setLevel(self, level: _Level) -> None: ... def isEnabledFor(self, level: int) -> bool: ... def getEffectiveLevel(self) -> int: ... - def getChild(self: Self, suffix: str) -> Self: ... # see python/typing#980 - if sys.version_info >= (3, 8): - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def _log( - self, - level: int, - msg: object, - args: _ArgsType, - exc_info: _ExcInfoType | None = ..., - extra: Mapping[str, object] | None = ..., - stack_info: bool = ..., - stacklevel: int = ..., - ) -> None: ... # undocumented - else: - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def _log( - self, - level: int, - msg: object, - args: _ArgsType, - exc_info: _ExcInfoType | None = ..., - extra: Mapping[str, object] | None = ..., - stack_info: bool = ..., - ) -> None: ... # undocumented + def getChild(self, suffix: str) -> Self: ... # see python/typing#980 + if sys.version_info >= (3, 12): + def getChildren(self) -> set[Logger]: ... + + def debug( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + @deprecated("Deprecated since Python 3.3. Use `Logger.warning()` instead.") + def warn( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + stacklevel: int = 1, + ) -> None: ... # undocumented fatal = critical - def filter(self, record: LogRecord) -> bool: ... def addHandler(self, hdlr: Handler) -> None: ... def removeHandler(self, hdlr: Handler) -> None: ... - if sys.version_info >= (3, 8): - def findCaller(self, stack_info: bool = ..., stacklevel: int = ...) -> tuple[str, int, str, str | None]: ... - else: - def findCaller(self, stack_info: bool = ...) -> tuple[str, int, str, str | None]: ... + def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple[str, int, str, str | None]: ... def handle(self, record: LogRecord) -> None: ... def makeRecord( self, @@ -236,29 +225,29 @@ class Logger(Filterer): lno: int, msg: object, args: _ArgsType, - exc_info: _SysExcInfoType | None, - func: str | None = ..., - extra: Mapping[str, object] | None = ..., - sinfo: str | None = ..., + exc_info: _SysExcInfoType | Literal[False] | None, + func: str | None = None, + extra: Mapping[str, object] | None = None, + sinfo: str | None = None, ) -> LogRecord: ... def hasHandlers(self) -> bool: ... def callHandlers(self, record: LogRecord) -> None: ... # undocumented -CRITICAL: Literal[50] -FATAL: Literal[50] -ERROR: Literal[40] -WARNING: Literal[30] -WARN: Literal[30] -INFO: Literal[20] -DEBUG: Literal[10] -NOTSET: Literal[0] +CRITICAL: Final = 50 +FATAL: Final = CRITICAL +ERROR: Final = 40 +WARNING: Final = 30 +WARN: Final = WARNING +INFO: Final = 20 +DEBUG: Final = 10 +NOTSET: Final = 0 class Handler(Filterer): level: int # undocumented formatter: Formatter | None # undocumented - lock: threading.Lock | None # undocumented + lock: threading.RLock | None # undocumented name: str | None # undocumented - def __init__(self, level: _Level = ...) -> None: ... + def __init__(self, level: _Level = 0) -> None: ... def get_name(self) -> str: ... # undocumented def set_name(self, name: str) -> None: ... # undocumented def createLock(self) -> None: ... @@ -266,7 +255,6 @@ class Handler(Filterer): def release(self) -> None: ... def setLevel(self, level: _Level) -> None: ... def setFormatter(self, fmt: Formatter | None) -> None: ... - def filter(self, record: LogRecord) -> bool: ... def flush(self) -> None: ... def close(self) -> None: ... def handle(self, record: LogRecord) -> bool: ... @@ -274,35 +262,29 @@ class Handler(Filterer): def format(self, record: LogRecord) -> str: ... def emit(self, record: LogRecord) -> None: ... +if sys.version_info >= (3, 12): + def getHandlerByName(name: str) -> Handler | None: ... + def getHandlerNames() -> frozenset[str]: ... + class Formatter: converter: Callable[[float | None], struct_time] _fmt: str | None # undocumented datefmt: str | None # undocumented _style: PercentStyle # undocumented default_time_format: str - if sys.version_info >= (3, 9): - default_msec_format: str | None - else: - default_msec_format: str + default_msec_format: str | None - if sys.version_info >= (3, 10): - def __init__( - self, - fmt: str | None = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - validate: bool = ..., - *, - defaults: Mapping[str, Any] | None = ..., - ) -> None: ... - elif sys.version_info >= (3, 8): - def __init__( - self, fmt: str | None = ..., datefmt: str | None = ..., style: _FormatStyle = ..., validate: bool = ... - ) -> None: ... - else: - def __init__(self, fmt: str | None = ..., datefmt: str | None = ..., style: _FormatStyle = ...) -> None: ... + def __init__( + self, + fmt: str | None = None, + datefmt: str | None = None, + style: _FormatStyle = "%", + validate: bool = True, + *, + defaults: Mapping[str, Any] | None = None, + ) -> None: ... def format(self, record: LogRecord) -> str: ... - def formatTime(self, record: LogRecord, datefmt: str | None = ...) -> str: ... + def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ... def formatException(self, ei: _SysExcInfoType) -> str: ... def formatMessage(self, record: LogRecord) -> str: ... # undocumented def formatStack(self, stack_info: str) -> str: ... @@ -310,7 +292,7 @@ class Formatter: class BufferingFormatter: linefmt: Formatter - def __init__(self, linefmt: Formatter | None = ...) -> None: ... + def __init__(self, linefmt: Formatter | None = None) -> None: ... def formatHeader(self, records: Sequence[LogRecord]) -> str: ... def formatFooter(self, records: Sequence[LogRecord]) -> str: ... def format(self, records: Sequence[LogRecord]) -> str: ... @@ -318,8 +300,11 @@ class BufferingFormatter: class Filter: name: str # undocumented nlen: int # undocumented - def __init__(self, name: str = ...) -> None: ... - def filter(self, record: LogRecord) -> bool: ... + def __init__(self, name: str = "") -> None: ... + if sys.version_info >= (3, 12): + def filter(self, record: LogRecord) -> bool | LogRecord: ... + else: + def filter(self, record: LogRecord) -> bool: ... class LogRecord: # args can be set to None by logging.handlers.QueueHandler @@ -327,7 +312,9 @@ class LogRecord: args: _ArgsType | None asctime: str created: float - exc_info: _SysExcInfoType | None + # Logger._log() only normalizes truthy exc_info values so + # exc_info=False ends up on the record unchanged. + exc_info: _SysExcInfoType | Literal[False] | None exc_text: str | None filename: str funcName: str @@ -338,7 +325,7 @@ class LogRecord: msecs: float # Only created when logging.Formatter.format is called. See #6132. message: str - msg: str + msg: str | Any # The runtime accepts any object, but will be a str in 99% of cases name: str pathname: str process: int | None @@ -347,6 +334,9 @@ class LogRecord: stack_info: str | None thread: int | None threadName: str | None + if sys.version_info >= (3, 12): + taskName: str | None + def __init__( self, name: str, @@ -355,384 +345,297 @@ class LogRecord: lineno: int, msg: object, args: _ArgsType | None, - exc_info: _SysExcInfoType | None, - func: str | None = ..., - sinfo: str | None = ..., + exc_info: _SysExcInfoType | Literal[False] | None, + func: str | None = None, + sinfo: str | None = None, ) -> None: ... def getMessage(self) -> str: ... + # Allows setting contextual information on LogRecord objects as per the docs, see #7833 + def __setattr__(self, name: str, value: Any, /) -> None: ... -_L = TypeVar("_L", Logger, LoggerAdapter[Logger], LoggerAdapter[Any]) +_L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) class LoggerAdapter(Generic[_L]): logger: _L manager: Manager # undocumented - if sys.version_info >= (3, 10): - extra: Mapping[str, object] | None - def __init__(self, logger: _L, extra: Mapping[str, object] | None = ...) -> None: ... - else: - extra: Mapping[str, object] - def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: ... - def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... - if sys.version_info >= (3, 8): - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... + extra: Mapping[str, object] | None + + if sys.version_info >= (3, 13): + def __init__(self, logger: _L, extra: Mapping[str, object] | None = None, merge_extra: bool = False) -> None: ... else: - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., - **kwargs: object, - ) -> None: ... - def isEnabledFor(self, level: int) -> bool: ... - def getEffectiveLevel(self) -> int: ... - def setLevel(self, level: _Level) -> None: ... - def hasHandlers(self) -> bool: ... - def _log( - self, - level: int, - msg: object, - args: _ArgsType, - exc_info: _ExcInfoType | None = ..., - extra: Mapping[str, object] | None = ..., - stack_info: bool = ..., - ) -> None: ... # undocumented - @property - def name(self) -> str: ... # undocumented + def __init__(self, logger: _L, extra: Mapping[str, object] | None = None) -> None: ... -def getLogger(name: str | None = ...) -> Logger: ... -def getLoggerClass() -> Type[Logger]: ... -def getLogRecordFactory() -> Callable[..., LogRecord]: ... + if sys.version_info >= (3, 13): + merge_extra: bool -if sys.version_info >= (3, 8): + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... def debug( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def info( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def warning( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... + @deprecated("Deprecated since Python 3.3. Use `LoggerAdapter.warning()` instead.") def warn( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def error( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - def critical( - msg: object, - *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def exception( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... - def log( - level: int, + def critical( + self, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - stacklevel: int = ..., - extra: Mapping[str, object] | None = ..., - ) -> None: ... - -else: - def debug( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... - ) -> None: ... - def info( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... - ) -> None: ... - def warning( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... - ) -> None: ... - def warn( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... - ) -> None: ... - def error( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... - ) -> None: ... - def critical( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... - ) -> None: ... - def exception( - msg: object, *args: object, exc_info: _ExcInfoType = ..., stack_info: bool = ..., extra: Mapping[str, object] | None = ... + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def log( + self, level: int, msg: object, *args: object, - exc_info: _ExcInfoType = ..., - stack_info: bool = ..., - extra: Mapping[str, object] | None = ..., + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def setLevel(self, level: _Level) -> None: ... + def hasHandlers(self) -> bool: ... + if sys.version_info >= (3, 11): + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + *, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + ) -> None: ... # undocumented + else: + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + ) -> None: ... # undocumented -fatal = critical + @property + def name(self) -> str: ... # undocumented + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -if sys.version_info >= (3, 7): - def disable(level: int = ...) -> None: ... +def getLogger(name: str | None = None) -> Logger: ... +def getLoggerClass() -> type[Logger]: ... +def getLogRecordFactory() -> Callable[..., LogRecord]: ... +def debug( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def info( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def warning( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +@deprecated("Deprecated since Python 3.3. Use `warning()` instead.") +def warn( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def error( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def critical( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def exception( + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def log( + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... -else: - def disable(level: int) -> None: ... +fatal = critical +def disable(level: int = 50) -> None: ... def addLevelName(level: int, levelName: str) -> None: ... -def getLevelName(level: _Level) -> Any: ... -def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ... -if sys.version_info >= (3, 9): - def basicConfig( - *, - filename: StrPath | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - level: _Level | None = ..., - stream: SupportsWrite[str] | None = ..., - handlers: Iterable[Handler] | None = ..., - force: bool | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> None: ... +@overload +def getLevelName(level: int) -> str: ... +@overload +@deprecated("The str -> int case is considered a mistake.") +def getLevelName(level: str) -> Any: ... -elif sys.version_info >= (3, 8): - def basicConfig( - *, - filename: StrPath | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - level: _Level | None = ..., - stream: SupportsWrite[str] | None = ..., - handlers: Iterable[Handler] | None = ..., - force: bool = ..., - ) -> None: ... +if sys.version_info >= (3, 11): + def getLevelNamesMapping() -> dict[str, int]: ... -else: - def basicConfig( - *, - filename: StrPath | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - level: _Level | None = ..., - stream: SupportsWrite[str] | None = ..., - handlers: Iterable[Handler] | None = ..., - ) -> None: ... +def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ... + +@overload # handlers is non-None +def basicConfig( + *, + format: str = ..., # default value depends on the value of `style` + datefmt: str | None = None, + style: _FormatStyle = "%", + level: _Level | None = None, + handlers: Iterable[Handler], + force: bool | None = False, +) -> None: ... +@overload # handlers is None, filename is passed (but possibly None) +def basicConfig( + *, + filename: StrPath | None, + filemode: str = "a", + format: str = ..., # default value depends on the value of `style` + datefmt: str | None = None, + style: _FormatStyle = "%", + level: _Level | None = None, + handlers: None = None, + force: bool | None = False, + encoding: str | None = None, + errors: str | None = "backslashreplace", +) -> None: ... +@overload # handlers is None, filename is not passed +def basicConfig( + *, + format: str = ..., # default value depends on the value of `style` + datefmt: str | None = None, + style: _FormatStyle = "%", + level: _Level | None = None, + stream: SupportsWrite[str] | None = None, + handlers: None = None, + force: bool | None = False, +) -> None: ... def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented -def setLoggerClass(klass: Type[Logger]) -> None: ... +def setLoggerClass(klass: type[Logger]) -> None: ... def captureWarnings(capture: bool) -> None: ... def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... -lastResort: StreamHandler[Any] | None +lastResort: Handler | None _StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) class StreamHandler(Handler, Generic[_StreamT]): stream: _StreamT # undocumented terminator: str + @overload - def __init__(self: StreamHandler[TextIO], stream: None = ...) -> None: ... + def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ... @overload - def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... - if sys.version_info >= (3, 7): - def setStream(self, stream: _StreamT) -> _StreamT | None: ... + def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + + def setStream(self, stream: _StreamT) -> _StreamT | None: ... + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class FileHandler(StreamHandler[TextIOWrapper]): baseFilename: str # undocumented mode: str # undocumented encoding: str | None # undocumented delay: bool # undocumented - if sys.version_info >= (3, 9): - errors: str | None # undocumented - def __init__( - self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ..., errors: str | None = ... - ) -> None: ... - else: - def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... + errors: str | None # undocumented + stream: TextIOWrapper | None # type: ignore[assignment] # None when delay=True or after close() + def __init__( + self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... def _open(self) -> TextIOWrapper: ... # undocumented class NullHandler(Handler): ... @@ -749,29 +652,25 @@ class RootLogger(Logger): root: RootLogger -class PercentStyle(object): # undocumented +class PercentStyle: # undocumented default_format: str asctime_format: str asctime_search: str - if sys.version_info >= (3, 8): - validation_pattern: Pattern[str] + validation_pattern: Pattern[str] _fmt: str - if sys.version_info >= (3, 10): - def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = ...) -> None: ... - else: - def __init__(self, fmt: str) -> None: ... + + def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ... def usesTime(self) -> bool: ... - if sys.version_info >= (3, 8): - def validate(self) -> None: ... + def validate(self) -> None: ... def format(self, record: Any) -> str: ... class StrFormatStyle(PercentStyle): # undocumented - fmt_spec = Any - field_spec = Any + fmt_spec: Pattern[str] + field_spec: Pattern[str] class StringTemplateStyle(PercentStyle): # undocumented _tpl: Template -_STYLES: dict[str, tuple[PercentStyle, str]] +_STYLES: Final[dict[str, tuple[PercentStyle, str]]] -BASIC_FORMAT: str +BASIC_FORMAT: Final = "%(levelname)s:%(name)s:%(message)s" diff --git a/stdlib/logging/config.pyi b/stdlib/logging/config.pyi index 8ee9e7b339b5..1c870edc80f8 100644 --- a/stdlib/logging/config.pyi +++ b/stdlib/logging/config.pyi @@ -1,68 +1,141 @@ import sys -from _typeshed import StrOrBytesPath, StrPath -from collections.abc import Callable +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence from configparser import RawConfigParser +from re import Pattern from threading import Thread -from typing import IO, Any, Pattern, Sequence +from typing import IO, Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Required, disjoint_base -from . import _Level +from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level -if sys.version_info >= (3, 8): - from typing import Literal, TypedDict -else: - from typing_extensions import Literal, TypedDict - -if sys.version_info >= (3, 7): - _Path = StrOrBytesPath -else: - _Path = StrPath +DEFAULT_LOGGING_CONFIG_PORT: Final = 9030 +RESET_ERROR: Final[int] # undocumented +IDENTIFIER: Final[Pattern[str]] # undocumented -DEFAULT_LOGGING_CONFIG_PORT: int -RESET_ERROR: int # undocumented -IDENTIFIER: Pattern[str] # undocumented +if sys.version_info >= (3, 11): + @type_check_only + class _RootLoggerConfiguration(TypedDict, total=False): + level: _Level + filters: Sequence[str | _FilterType] + handlers: Sequence[str] -class _RootLoggerConfiguration(TypedDict, total=False): - level: _Level - filters: Sequence[str] - handlers: Sequence[str] +else: + @type_check_only + class _RootLoggerConfiguration(TypedDict, total=False): + level: _Level + filters: Sequence[str] + handlers: Sequence[str] +@type_check_only class _LoggerConfiguration(_RootLoggerConfiguration, TypedDict, total=False): propagate: bool -class _OptionalDictConfigArgs(TypedDict, total=False): - # these two can have custom factories (key: `()`) which can have extra keys - formatters: dict[str, dict[str, Any]] - filters: dict[str, dict[str, Any]] - # type checkers would warn about extra keys if this was a TypedDict - handlers: dict[str, dict[str, Any]] +_FormatterConfigurationTypedDict = TypedDict( + "_FormatterConfigurationTypedDict", {"class": str, "format": str, "datefmt": str, "style": _FormatStyle}, total=False +) + +@type_check_only +class _FilterConfigurationTypedDict(TypedDict): + name: str + +# Formatter and filter configs can specify custom factories via the special `()` key. +# If that is the case, the dictionary can contain any additional keys +# https://docs.python.org/3/library/logging.config.html#user-defined-objects +_FormatterConfiguration: TypeAlias = _FormatterConfigurationTypedDict | dict[str, Any] +_FilterConfiguration: TypeAlias = _FilterConfigurationTypedDict | dict[str, Any] +# Handler config can have additional keys even when not providing a custom factory so we just use `dict`. +_HandlerConfiguration: TypeAlias = dict[str, Any] + +@type_check_only +class _DictConfigArgs(TypedDict, total=False): + version: Required[Literal[1]] + formatters: dict[str, _FormatterConfiguration] + filters: dict[str, _FilterConfiguration] + handlers: dict[str, _HandlerConfiguration] loggers: dict[str, _LoggerConfiguration] - root: _RootLoggerConfiguration | None + root: _RootLoggerConfiguration incremental: bool disable_existing_loggers: bool -class _DictConfigArgs(_OptionalDictConfigArgs, TypedDict): - version: Literal[1] - # Accept dict[str, Any] to avoid false positives if called with a dict # type, since dict types are not compatible with TypedDicts. # # Also accept a TypedDict type, to allow callers to use TypedDict # types, and for somewhat stricter type checking of dict literals. def dictConfig(config: _DictConfigArgs | dict[str, Any]) -> None: ... +def fileConfig( + fname: StrOrBytesPath | IO[str] | RawConfigParser, + defaults: Mapping[str, str] | None = None, + disable_existing_loggers: bool = True, + encoding: str | None = None, +) -> None: ... +def valid_ident(s: str) -> Literal[True]: ... # undocumented +def listen(port: int = 9030, verify: Callable[[bytes], bytes | None] | None = None) -> Thread: ... +def stopListening() -> None: ... -if sys.version_info >= (3, 10): - def fileConfig( - fname: _Path | IO[str] | RawConfigParser, - defaults: dict[str, str] | None = ..., - disable_existing_loggers: bool = ..., - encoding: str | None = ..., - ) -> None: ... +class ConvertingMixin: # undocumented + def convert_with_key(self, key: Any, value: Any, replace: bool = True) -> Any: ... + def convert(self, value: Any) -> Any: ... + +class ConvertingDict(dict[Hashable, Any], ConvertingMixin): # undocumented + def __getitem__(self, key: Hashable) -> Any: ... + def get(self, key: Hashable, default: Any = None) -> Any: ... + def pop(self, key: Hashable, default: Any = None) -> Any: ... + +class ConvertingList(list[Any], ConvertingMixin): # undocumented + @overload + def __getitem__(self, key: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... + + def pop(self, idx: SupportsIndex = -1) -> Any: ... + +if sys.version_info >= (3, 12): + class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented + @overload + def __getitem__(self, key: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... else: - def fileConfig( - fname: _Path | IO[str] | RawConfigParser, defaults: dict[str, str] | None = ..., disable_existing_loggers: bool = ... - ) -> None: ... + @disjoint_base + class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented + @overload + def __getitem__(self, key: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... -def valid_ident(s: str) -> Literal[True]: ... # undocumented -def listen(port: int = ..., verify: Callable[[bytes], bytes | None] | None = ...) -> Thread: ... -def stopListening() -> None: ... +class BaseConfigurator: + CONVERT_PATTERN: Pattern[str] + WORD_PATTERN: Pattern[str] + DOT_PATTERN: Pattern[str] + INDEX_PATTERN: Pattern[str] + DIGIT_PATTERN: Pattern[str] + value_converters: dict[str, str] + importer: Callable[..., Any] + + config: dict[str, Any] # undocumented + + def __init__(self, config: _DictConfigArgs | dict[str, Any]) -> None: ... + def resolve(self, s: str) -> Any: ... + def ext_convert(self, value: str) -> Any: ... + def cfg_convert(self, value: str) -> Any: ... + def convert(self, value: Any) -> Any: ... + def configure_custom(self, config: dict[str, Any]) -> Any: ... + def as_tuple(self, value: list[Any] | tuple[Any, ...]) -> tuple[Any, ...]: ... + +class DictConfigurator(BaseConfigurator): + def configure(self) -> None: ... # undocumented + def configure_formatter(self, config: _FormatterConfiguration) -> Formatter | Any: ... # undocumented + def configure_filter(self, config: _FilterConfiguration) -> Filter | Any: ... # undocumented + def add_filters(self, filterer: Filterer, filters: Iterable[_FilterType]) -> None: ... # undocumented + def configure_handler(self, config: _HandlerConfiguration) -> Handler | Any: ... # undocumented + def add_handlers(self, logger: Logger, handlers: Iterable[str]) -> None: ... # undocumented + def common_logger_config( + self, logger: Logger, config: _LoggerConfiguration, incremental: bool = False + ) -> None: ... # undocumented + def configure_logger(self, name: str, config: _LoggerConfiguration, incremental: bool = False) -> None: ... # undocumented + def configure_root(self, config: _LoggerConfiguration, incremental: bool = False) -> None: ... # undocumented + +dictConfigClass = DictConfigurator diff --git a/stdlib/logging/handlers.pyi b/stdlib/logging/handlers.pyi index 50d6d0583556..535f1c685183 100644 --- a/stdlib/logging/handlers.pyi +++ b/stdlib/logging/handlers.pyi @@ -2,72 +2,56 @@ import datetime import http.client import ssl import sys -from _typeshed import StrPath +from _typeshed import ReadableBuffer, StrPath from collections.abc import Callable from logging import FileHandler, Handler, LogRecord +from re import Pattern from socket import SocketKind, socket -from typing import Any, ClassVar, Pattern +from threading import Thread +from types import TracebackType +from typing import Any, ClassVar, Final, Protocol, TypeVar, type_check_only +from typing_extensions import Self -if sys.version_info >= (3, 7): - from queue import Queue, SimpleQueue -else: - from queue import Queue +_T = TypeVar("_T") -DEFAULT_TCP_LOGGING_PORT: int -DEFAULT_UDP_LOGGING_PORT: int -DEFAULT_HTTP_LOGGING_PORT: int -DEFAULT_SOAP_LOGGING_PORT: int -SYSLOG_UDP_PORT: int -SYSLOG_TCP_PORT: int +DEFAULT_TCP_LOGGING_PORT: Final = 9020 +DEFAULT_UDP_LOGGING_PORT: Final = 9021 +DEFAULT_HTTP_LOGGING_PORT: Final = 9022 +DEFAULT_SOAP_LOGGING_PORT: Final = 9023 +SYSLOG_UDP_PORT: Final = 514 +SYSLOG_TCP_PORT: Final = 514 class WatchedFileHandler(FileHandler): dev: int # undocumented ino: int # undocumented - if sys.version_info >= (3, 9): - def __init__( - self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ..., errors: str | None = ... - ) -> None: ... - else: - def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... + def __init__( + self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... def _statstream(self) -> None: ... # undocumented def reopenIfNeeded(self) -> None: ... class BaseRotatingHandler(FileHandler): namer: Callable[[str], str] | None rotator: Callable[[str, str], None] | None - if sys.version_info >= (3, 9): - def __init__( - self, filename: StrPath, mode: str, encoding: str | None = ..., delay: bool = ..., errors: str | None = ... - ) -> None: ... - else: - def __init__(self, filename: StrPath, mode: str, encoding: str | None = ..., delay: bool = ...) -> None: ... + def __init__( + self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... def rotation_filename(self, default_name: str) -> str: ... def rotate(self, source: str, dest: str) -> None: ... class RotatingFileHandler(BaseRotatingHandler): - maxBytes: str # undocumented + maxBytes: int # undocumented backupCount: int # undocumented - if sys.version_info >= (3, 9): - def __init__( - self, - filename: StrPath, - mode: str = ..., - maxBytes: int = ..., - backupCount: int = ..., - encoding: str | None = ..., - delay: bool = ..., - errors: str | None = ..., - ) -> None: ... - else: - def __init__( - self, - filename: StrPath, - mode: str = ..., - maxBytes: int = ..., - backupCount: int = ..., - encoding: str | None = ..., - delay: bool = ..., - ) -> None: ... + def __init__( + self, + filename: StrPath, + mode: str = "a", + maxBytes: int = 0, + backupCount: int = 0, + encoding: str | None = None, + delay: bool = False, + errors: str | None = None, + ) -> None: ... def doRollover(self) -> None: ... def shouldRollover(self, record: LogRecord) -> int: ... # undocumented @@ -75,37 +59,24 @@ class TimedRotatingFileHandler(BaseRotatingHandler): when: str # undocumented backupCount: int # undocumented utc: bool # undocumented - atTime: datetime.datetime | None # undocumented + atTime: datetime.time | None # undocumented interval: int # undocumented suffix: str # undocumented dayOfWeek: int # undocumented rolloverAt: int # undocumented extMatch: Pattern[str] # undocumented - if sys.version_info >= (3, 9): - def __init__( - self, - filename: StrPath, - when: str = ..., - interval: int = ..., - backupCount: int = ..., - encoding: str | None = ..., - delay: bool = ..., - utc: bool = ..., - atTime: datetime.datetime | None = ..., - errors: str | None = ..., - ) -> None: ... - else: - def __init__( - self, - filename: StrPath, - when: str = ..., - interval: int = ..., - backupCount: int = ..., - encoding: str | None = ..., - delay: bool = ..., - utc: bool = ..., - atTime: datetime.datetime | None = ..., - ) -> None: ... + def __init__( + self, + filename: StrPath, + when: str = "h", + interval: int = 1, + backupCount: int = 0, + encoding: str | None = None, + delay: bool = False, + utc: bool = False, + atTime: datetime.time | None = None, + errors: str | None = None, + ) -> None: ... def doRollover(self) -> None: ... def shouldRollover(self, record: LogRecord) -> int: ... # undocumented def computeRollover(self, currentTime: int) -> int: ... # undocumented @@ -122,9 +93,9 @@ class SocketHandler(Handler): retryFactor: float # undocumented retryMax: float # undocumented def __init__(self, host: str, port: int | None) -> None: ... - def makeSocket(self, timeout: float = ...) -> socket: ... # timeout is undocumented + def makeSocket(self, timeout: float = 1) -> socket: ... # timeout is undocumented def makePickle(self, record: LogRecord) -> bytes: ... - def send(self, s: bytes) -> None: ... + def send(self, s: ReadableBuffer) -> None: ... def createSocket(self) -> None: ... class DatagramHandler(SocketHandler): @@ -152,13 +123,10 @@ class SysLogHandler(Handler): LOG_CRON: int LOG_AUTHPRIV: int LOG_FTP: int - - if sys.version_info >= (3, 9): - LOG_NTP: int - LOG_SECURITY: int - LOG_CONSOLE: int - LOG_SOLCRON: int - + LOG_NTP: int + LOG_SECURITY: int + LOG_CONSOLE: int + LOG_SOLCRON: int LOG_LOCAL0: int LOG_LOCAL1: int LOG_LOCAL2: int @@ -176,14 +144,29 @@ class SysLogHandler(Handler): priority_names: ClassVar[dict[str, int]] # undocumented facility_names: ClassVar[dict[str, int]] # undocumented priority_map: ClassVar[dict[str, str]] # undocumented - def __init__(self, address: tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... + if sys.version_info >= (3, 14): + timeout: float | None + def __init__( + self, + address: tuple[str, int] | str = ("localhost", 514), + facility: str | int = 1, + socktype: SocketKind | None = None, + timeout: float | None = None, + ) -> None: ... + else: + def __init__( + self, address: tuple[str, int] | str = ("localhost", 514), facility: str | int = 1, socktype: SocketKind | None = None + ) -> None: ... + if sys.version_info >= (3, 11): + def createSocket(self) -> None: ... + def encodePriority(self, facility: int | str, priority: int | str) -> int: ... def mapPriority(self, levelName: str) -> str: ... class NTEventLogHandler(Handler): - def __init__(self, appname: str, dllname: str | None = ..., logtype: str = ...) -> None: ... + def __init__(self, appname: str, dllname: str | None = None, logtype: str = "Application") -> None: ... def getEventCategory(self, record: LogRecord) -> int: ... - # TODO correct return value? + # TODO: correct return value? def getEventType(self, record: LogRecord) -> int: ... def getMessageID(self, record: LogRecord) -> int: ... @@ -204,9 +187,9 @@ class SMTPHandler(Handler): fromaddr: str, toaddrs: str | list[str], subject: str, - credentials: tuple[str, str] | None = ..., - secure: tuple[()] | tuple[str] | tuple[str, str] | None = ..., - timeout: float = ..., + credentials: tuple[str, str] | None = None, + secure: tuple[()] | tuple[str] | tuple[str, str] | None = None, + timeout: float = 5.0, ) -> None: ... def getSubject(self, record: LogRecord) -> str: ... @@ -220,7 +203,7 @@ class MemoryHandler(BufferingHandler): flushLevel: int # undocumented target: Handler | None # undocumented flushOnClose: bool # undocumented - def __init__(self, capacity: int, flushLevel: int = ..., target: Handler | None = ..., flushOnClose: bool = ...) -> None: ... + def __init__(self, capacity: int, flushLevel: int = 40, target: Handler | None = None, flushOnClose: bool = True) -> None: ... def setTarget(self, target: Handler | None) -> None: ... class HTTPHandler(Handler): @@ -234,39 +217,42 @@ class HTTPHandler(Handler): self, host: str, url: str, - method: str = ..., - secure: bool = ..., - credentials: tuple[str, str] | None = ..., - context: ssl.SSLContext | None = ..., + method: str = "GET", + secure: bool = False, + credentials: tuple[str, str] | None = None, + context: ssl.SSLContext | None = None, ) -> None: ... def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ... - if sys.version_info >= (3, 9): - def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ... # undocumented + def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ... # undocumented + +@type_check_only +class _QueueLike(Protocol[_T]): + def get(self) -> _T: ... + def put_nowait(self, item: _T, /) -> None: ... class QueueHandler(Handler): - if sys.version_info >= (3, 7): - queue: SimpleQueue[Any] | Queue[Any] # undocumented - def __init__(self, queue: SimpleQueue[Any] | Queue[Any]) -> None: ... - else: - queue: Queue[Any] # undocumented - def __init__(self, queue: Queue[Any]) -> None: ... + queue: _QueueLike[Any] + def __init__(self, queue: _QueueLike[Any]) -> None: ... def prepare(self, record: LogRecord) -> Any: ... def enqueue(self, record: LogRecord) -> None: ... + if sys.version_info >= (3, 12): + listener: QueueListener | None class QueueListener: - handlers: tuple[Handler] # undocumented + handlers: tuple[Handler, ...] # undocumented respect_handler_level: bool # undocumented - if sys.version_info >= (3, 7): - queue: SimpleQueue[Any] | Queue[Any] # undocumented - def __init__( - self, queue: SimpleQueue[Any] | Queue[Any], *handlers: Handler, respect_handler_level: bool = ... - ) -> None: ... - else: - queue: Queue[Any] # undocumented - def __init__(self, queue: Queue[Any], *handlers: Handler, respect_handler_level: bool = ...) -> None: ... + queue: _QueueLike[Any] # undocumented + _thread: Thread | None # undocumented + def __init__(self, queue: _QueueLike[Any], *handlers: Handler, respect_handler_level: bool = False) -> None: ... def dequeue(self, block: bool) -> LogRecord: ... def prepare(self, record: LogRecord) -> Any: ... def start(self) -> None: ... def stop(self) -> None: ... def enqueue_sentinel(self) -> None: ... def handle(self, record: LogRecord) -> None: ... + + if sys.version_info >= (3, 14): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... diff --git a/stdlib/lzma.pyi b/stdlib/lzma.pyi index e1da3024c4ac..656ecb168c95 100644 --- a/stdlib/lzma.pyi +++ b/stdlib/lzma.pyi @@ -1,163 +1,181 @@ -import io -from _typeshed import ReadableBuffer, Self, StrOrBytesPath -from typing import IO, Any, Mapping, Sequence, TextIO, Union, overload -from typing_extensions import Literal, final +import sys +from _lzma import ( + CHECK_CRC32 as CHECK_CRC32, + CHECK_CRC64 as CHECK_CRC64, + CHECK_ID_MAX as CHECK_ID_MAX, + CHECK_NONE as CHECK_NONE, + CHECK_SHA256 as CHECK_SHA256, + CHECK_UNKNOWN as CHECK_UNKNOWN, + FILTER_ARM as FILTER_ARM, + FILTER_ARMTHUMB as FILTER_ARMTHUMB, + FILTER_DELTA as FILTER_DELTA, + FILTER_IA64 as FILTER_IA64, + FILTER_LZMA1 as FILTER_LZMA1, + FILTER_LZMA2 as FILTER_LZMA2, + FILTER_POWERPC as FILTER_POWERPC, + FILTER_SPARC as FILTER_SPARC, + FILTER_X86 as FILTER_X86, + FORMAT_ALONE as FORMAT_ALONE, + FORMAT_AUTO as FORMAT_AUTO, + FORMAT_RAW as FORMAT_RAW, + FORMAT_XZ as FORMAT_XZ, + MF_BT2 as MF_BT2, + MF_BT3 as MF_BT3, + MF_BT4 as MF_BT4, + MF_HC3 as MF_HC3, + MF_HC4 as MF_HC4, + MODE_FAST as MODE_FAST, + MODE_NORMAL as MODE_NORMAL, + PRESET_DEFAULT as PRESET_DEFAULT, + PRESET_EXTREME as PRESET_EXTREME, + LZMACompressor as LZMACompressor, + LZMADecompressor as LZMADecompressor, + LZMAError as LZMAError, + _FilterChain, + is_check_supported as is_check_supported, +) +from _typeshed import ReadableBuffer, StrOrBytesPath +from io import TextIOWrapper +from typing import IO, Literal, TypeAlias, overload +from typing_extensions import Self -_OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] -_OpenTextWritingMode = Literal["wt", "xt", "at"] +if sys.version_info >= (3, 14): + from compression._common._streams import BaseStream +else: + from _compression import BaseStream -_PathOrFile = Union[StrOrBytesPath, IO[bytes]] +__all__ = [ + "CHECK_NONE", + "CHECK_CRC32", + "CHECK_CRC64", + "CHECK_SHA256", + "CHECK_ID_MAX", + "CHECK_UNKNOWN", + "FILTER_LZMA1", + "FILTER_LZMA2", + "FILTER_DELTA", + "FILTER_X86", + "FILTER_IA64", + "FILTER_ARM", + "FILTER_ARMTHUMB", + "FILTER_POWERPC", + "FILTER_SPARC", + "FORMAT_AUTO", + "FORMAT_XZ", + "FORMAT_ALONE", + "FORMAT_RAW", + "MF_HC3", + "MF_HC4", + "MF_BT2", + "MF_BT3", + "MF_BT4", + "MODE_FAST", + "MODE_NORMAL", + "PRESET_DEFAULT", + "PRESET_EXTREME", + "LZMACompressor", + "LZMADecompressor", + "LZMAFile", + "LZMAError", + "open", + "compress", + "decompress", + "is_check_supported", +] -_FilterChain = Sequence[Mapping[str, Any]] +_OpenBinaryWritingMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_OpenTextWritingMode: TypeAlias = Literal["wt", "xt", "at"] -FORMAT_AUTO: int -FORMAT_XZ: int -FORMAT_ALONE: int -FORMAT_RAW: int -CHECK_NONE: int -CHECK_CRC32: int -CHECK_CRC64: int -CHECK_SHA256: int -CHECK_ID_MAX: int -CHECK_UNKNOWN: int -FILTER_LZMA1: int -FILTER_LZMA2: int -FILTER_DELTA: int -FILTER_X86: int -FILTER_IA64: int -FILTER_ARM: int -FILTER_ARMTHUMB: int -FILTER_SPARC: int -FILTER_POWERPC: int -MF_HC3: int -MF_HC4: int -MF_BT2: int -MF_BT3: int -MF_BT4: int -MODE_FAST: int -MODE_NORMAL: int -PRESET_DEFAULT: int -PRESET_EXTREME: int +_PathOrFile: TypeAlias = StrOrBytesPath | IO[bytes] -# from _lzma.c -@final -class LZMADecompressor(object): - def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> None: ... - def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... - @property - def check(self) -> int: ... - @property - def eof(self) -> bool: ... - @property - def unused_data(self) -> bytes: ... - @property - def needs_input(self) -> bool: ... - -# from _lzma.c -@final -class LZMACompressor(object): - def __init__( - self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... - ) -> None: ... - def compress(self, __data: bytes) -> bytes: ... - def flush(self) -> bytes: ... - -class LZMAError(Exception): ... - -class LZMAFile(io.BufferedIOBase, IO[bytes]): +class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible definitions of writelines in the base classes def __init__( self, - filename: _PathOrFile | None = ..., - mode: str = ..., + filename: _PathOrFile | None = None, + mode: str = "r", *, - format: int | None = ..., - check: int = ..., - preset: int | None = ..., - filters: _FilterChain | None = ..., + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, ) -> None: ... - def __enter__(self: Self) -> Self: ... - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - def fileno(self) -> int: ... - def seekable(self) -> bool: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def peek(self, size: int = ...) -> bytes: ... - def read(self, size: int | None = ...) -> bytes: ... - def read1(self, size: int = ...) -> bytes: ... - def readline(self, size: int | None = ...) -> bytes: ... + def __enter__(self) -> Self: ... + def peek(self, size: int = -1) -> bytes: ... + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int = -1) -> bytes: ... + def readline(self, size: int | None = -1) -> bytes: ... def write(self, data: ReadableBuffer) -> int: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... + def seek(self, offset: int, whence: int = 0) -> int: ... @overload def open( filename: _PathOrFile, - mode: Literal["r", "rb"] = ..., + mode: Literal["r", "rb"] = "rb", *, - format: int | None = ..., - check: Literal[-1] = ..., - preset: None = ..., - filters: _FilterChain | None = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + format: int | None = None, + check: Literal[-1] = -1, + preset: None = None, + filters: _FilterChain | None = None, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> LZMAFile: ... @overload def open( filename: _PathOrFile, mode: _OpenBinaryWritingMode, *, - format: int | None = ..., - check: int = ..., - preset: int | None = ..., - filters: _FilterChain | None = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + encoding: None = None, + errors: None = None, + newline: None = None, ) -> LZMAFile: ... @overload def open( filename: StrOrBytesPath, mode: Literal["rt"], *, - format: int | None = ..., - check: Literal[-1] = ..., - preset: None = ..., - filters: _FilterChain | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> TextIO: ... + format: int | None = None, + check: Literal[-1] = -1, + preset: None = None, + filters: _FilterChain | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... @overload def open( filename: StrOrBytesPath, mode: _OpenTextWritingMode, *, - format: int | None = ..., - check: int = ..., - preset: int | None = ..., - filters: _FilterChain | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> TextIO: ... + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... @overload def open( filename: _PathOrFile, mode: str, *, - format: int | None = ..., - check: int = ..., - preset: int | None = ..., - filters: _FilterChain | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., -) -> LZMAFile | TextIO: ... + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> LZMAFile | TextIOWrapper: ... + def compress( - data: bytes, format: int = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... + data: ReadableBuffer, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None +) -> bytes: ... +def decompress( + data: ReadableBuffer, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None ) -> bytes: ... -def decompress(data: bytes, format: int = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> bytes: ... -def is_check_supported(__check_id: int) -> bool: ... diff --git a/stdlib/macpath.pyi b/stdlib/macpath.pyi deleted file mode 100644 index 2512e086b735..000000000000 --- a/stdlib/macpath.pyi +++ /dev/null @@ -1,69 +0,0 @@ -from _typeshed import BytesPath, StrOrBytesPath, StrPath -from genericpath import ( - commonprefix as commonprefix, - exists as exists, - getatime as getatime, - getctime as getctime, - getmtime as getmtime, - getsize as getsize, - isdir as isdir, - isfile as isfile, - samefile as samefile, - sameopenfile as sameopenfile, - samestat as samestat, -) -from os import PathLike - -# Re-export common definitions from posixpath to reduce duplication -from posixpath import ( - abspath as abspath, - curdir as curdir, - defpath as defpath, - devnull as devnull, - expanduser as expanduser, - expandvars as expandvars, - extsep as extsep, - isabs as isabs, - lexists as lexists, - pardir as pardir, - pathsep as pathsep, - sep as sep, - splitdrive as splitdrive, - splitext as splitext, - supports_unicode_filenames as supports_unicode_filenames, -) -from typing import AnyStr, overload - -altsep: str | None - -@overload -def basename(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def basename(s: AnyStr) -> AnyStr: ... -@overload -def dirname(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def dirname(s: AnyStr) -> AnyStr: ... -@overload -def normcase(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def normcase(path: AnyStr) -> AnyStr: ... -@overload -def normpath(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def normpath(s: AnyStr) -> AnyStr: ... -@overload -def realpath(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def realpath(path: AnyStr) -> AnyStr: ... -def islink(s: StrOrBytesPath) -> bool: ... - -# Mypy complains that the signatures overlap, but things seem to behave correctly anyway. -@overload -def join(s: StrPath, *paths: StrPath) -> str: ... -@overload -def join(s: BytesPath, *paths: BytesPath) -> bytes: ... -@overload -def split(s: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def split(s: AnyStr) -> tuple[AnyStr, AnyStr]: ... diff --git a/stdlib/macurl2path.pyi b/stdlib/macurl2path.pyi deleted file mode 100644 index 6aac6dfeace5..000000000000 --- a/stdlib/macurl2path.pyi +++ /dev/null @@ -1,3 +0,0 @@ -def url2pathname(pathname: str) -> str: ... -def pathname2url(pathname: str) -> str: ... -def _pncomp2url(component: str | bytes) -> str: ... diff --git a/stdlib/mailbox.pyi b/stdlib/mailbox.pyi index ffd9c3005cec..7f3024094b43 100644 --- a/stdlib/mailbox.pyi +++ b/stdlib/mailbox.pyi @@ -1,92 +1,169 @@ import email.message +import io import sys -from _typeshed import Self, StrOrBytesPath -from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - Protocol, - Sequence, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal - -if sys.version_info >= (3, 9): - from types import GenericAlias +from _typeshed import StrPath, SupportsItems, SupportsNoArgReadline, SupportsRead, SupportsWrite, Unused +from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from types import GenericAlias, TracebackType +from typing import Any, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +__all__ = [ + "Mailbox", + "Maildir", + "mbox", + "MH", + "Babyl", + "MMDF", + "Message", + "MaildirMessage", + "mboxMessage", + "MHMessage", + "BabylMessage", + "MMDFMessage", + "Error", + "NoSuchMailboxError", + "NotEmptyError", + "ExternalClashError", + "FormatError", +] _T = TypeVar("_T") -_MessageT = TypeVar("_MessageT", bound=Message) -_MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] +@type_check_only +class _SupportsReadAndReadline(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ... + +# As opposed to _MessageT_co in email._policybase, this type is bound to +# mailbox.Message instead of email.message.Message. +_MessageT_co = TypeVar("_MessageT_co", bound=Message, default=Message, covariant=True) + +_MessageData: TypeAlias = email.message.Message | bytes | str | io.StringIO | _SupportsReadAndReadline + +@type_check_only class _HasIteritems(Protocol): def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... -class _HasItems(Protocol): - def items(self) -> Iterator[tuple[str, _MessageData]]: ... - linesep: bytes -class Mailbox(Generic[_MessageT]): +# Common interface for get_file() return types. +@type_check_only +class _GetFileReturn(Protocol): + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, / + ) -> bool | None: ... + def read(self, size: int | None = None, /) -> bytes: ... + def read1(self, size: int | None = None, /) -> bytes: ... + def readline(self, size: int | None = None, /) -> bytes: ... + def readlines(self, sizehint: int | None = None, /) -> list[bytes]: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: int = 0, /) -> object: ... + def close(self) -> object: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def flush(self) -> object: ... + @property + def closed(self) -> bool: ... + +class Mailbox(Generic[_MessageT_co]): + _path: str # undocumented + _factory: Callable[[_GetFileReturn], _MessageT_co] | None # undocumented - _path: bytes | str # undocumented - _factory: Callable[[IO[Any]], _MessageT] | None # undocumented - def __init__( - self, path: StrOrBytesPath, factory: Callable[[IO[Any]], _MessageT] | None = ..., create: bool = ... - ) -> None: ... + @overload + def __init__(self, path: StrPath, factory: Callable[[_GetFileReturn], _MessageT_co], create: bool = True) -> None: ... + @overload + def __init__(self, path: StrPath, factory: None = None, create: bool = True) -> None: ... + + @abstractmethod def add(self, message: _MessageData) -> str: ... + @abstractmethod def remove(self, key: str) -> None: ... def __delitem__(self, key: str) -> None: ... def discard(self, key: str) -> None: ... + @abstractmethod def __setitem__(self, key: str, message: _MessageData) -> None: ... + @overload - def get(self, key: str, default: None = ...) -> _MessageT | None: ... + def get(self, key: str, default: None = None) -> _MessageT_co | None: ... @overload - def get(self, key: str, default: _T) -> _MessageT | _T: ... - def __getitem__(self, key: str) -> _MessageT: ... - def get_message(self, key: str) -> _MessageT: ... + def get(self, key: str, default: _T) -> _MessageT_co | _T: ... + + def __getitem__(self, key: str) -> _MessageT_co: ... + @abstractmethod + def get_message(self, key: str) -> _MessageT_co: ... def get_string(self, key: str) -> str: ... + @abstractmethod def get_bytes(self, key: str) -> bytes: ... - # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here - def get_file(self, key: str) -> Any: ... + @abstractmethod + def get_file(self, key: str) -> _GetFileReturn: ... + @abstractmethod def iterkeys(self) -> Iterator[str]: ... def keys(self) -> list[str]: ... - def itervalues(self) -> Iterator[_MessageT]: ... - def __iter__(self) -> Iterator[_MessageT]: ... - def values(self) -> list[_MessageT]: ... - def iteritems(self) -> Iterator[tuple[str, _MessageT]]: ... - def items(self) -> list[tuple[str, _MessageT]]: ... + def itervalues(self) -> Iterator[_MessageT_co]: ... + def __iter__(self) -> Iterator[_MessageT_co]: ... + def values(self) -> list[_MessageT_co]: ... + def iteritems(self) -> Iterator[tuple[str, _MessageT_co]]: ... + def items(self) -> list[tuple[str, _MessageT_co]]: ... + @abstractmethod def __contains__(self, key: str) -> bool: ... + @abstractmethod def __len__(self) -> int: ... def clear(self) -> None: ... + @overload - def pop(self, key: str, default: None = ...) -> _MessageT | None: ... + def pop(self, key: str, default: None = None) -> _MessageT_co | None: ... @overload - def pop(self, key: str, default: _T = ...) -> _MessageT | _T: ... - def popitem(self) -> tuple[str, _MessageT]: ... - def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = ...) -> None: ... + def pop(self, key: str, default: _T) -> _MessageT_co | _T: ... + + def popitem(self) -> tuple[str, _MessageT_co]: ... + def update( + self, arg: _HasIteritems | SupportsItems[str, _MessageData] | Iterable[tuple[str, _MessageData]] | None = None + ) -> None: ... + @abstractmethod def flush(self) -> None: ... + @abstractmethod def lock(self) -> None: ... + @abstractmethod def unlock(self) -> None: ... + @abstractmethod def close(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + if sys.version_info >= (3, 15): + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + # Undocumented, called by subclasses to parse added messages. + def _dump_message(self, message: _MessageData, target: SupportsWrite[bytes], mangle_from_: bool = False) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Maildir(Mailbox[MaildirMessage]): - colon: str def __init__( - self, dirname: StrOrBytesPath, factory: Callable[[IO[Any]], MaildirMessage] | None = ..., create: bool = ... + self, dirname: StrPath, factory: Callable[[_GetFileReturn], MaildirMessage] | None = None, create: bool = True ) -> None: ... - def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def add(self, message: _MessageData | MaildirMessage) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData | MaildirMessage) -> None: ... + def get_message(self, key: str) -> MaildirMessage: ... + def get_bytes(self, key: str) -> bytes: ... + def get_file(self, key: str) -> _ProxyFile: ... + if sys.version_info >= (3, 13): + def get_info(self, key: str) -> str: ... + def set_info(self, key: str, info: str) -> None: ... + def get_flags(self, key: str) -> str: ... + def set_flags(self, key: str, flags: str) -> None: ... + def add_flag(self, key: str, flag: str) -> None: ... + def remove_flag(self, key: str, flag: str) -> None: ... + + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... def list_folders(self) -> list[str]: ... def get_folder(self, folder: str) -> Maildir: ... def add_folder(self, folder: str) -> Maildir: ... @@ -94,45 +171,70 @@ class Maildir(Mailbox[MaildirMessage]): def clean(self) -> None: ... def next(self) -> str | None: ... -class _singlefileMailbox(Mailbox[_MessageT]): ... +class _singlefileMailbox(Mailbox[_MessageT_co], metaclass=ABCMeta): + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... -class _mboxMMDF(_singlefileMailbox[_MessageT]): - def get_file(self, key: str, from_: bool = ...) -> _PartialFile[bytes]: ... - def get_bytes(self, key: str, from_: bool = ...) -> bytes: ... - def get_string(self, key: str, from_: bool = ...) -> str: ... +class _mboxMMDF(_singlefileMailbox[_MessageT_co]): + def get_message(self, key: str) -> _MessageT_co: ... + def get_file(self, key: str, from_: bool = False) -> _PartialFile: ... + def get_bytes(self, key: str, from_: bool = False) -> bytes: ... + def get_string(self, key: str, from_: bool = False) -> str: ... class mbox(_mboxMMDF[mboxMessage]): def __init__( - self, path: StrOrBytesPath, factory: Callable[[IO[Any]], mboxMessage] | None = ..., create: bool = ... + self, path: StrPath, factory: Callable[[_GetFileReturn], mboxMessage] | None = None, create: bool = True ) -> None: ... class MMDF(_mboxMMDF[MMDFMessage]): def __init__( - self, path: StrOrBytesPath, factory: Callable[[IO[Any]], MMDFMessage] | None = ..., create: bool = ... + self, path: StrPath, factory: Callable[[_GetFileReturn], MMDFMessage] | None = None, create: bool = True ) -> None: ... class MH(Mailbox[MHMessage]): def __init__( - self, path: StrOrBytesPath, factory: Callable[[IO[Any]], MHMessage] | None = ..., create: bool = ... + self, path: StrPath, factory: Callable[[_GetFileReturn], MHMessage] | None = None, create: bool = True ) -> None: ... - def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def get_message(self, key: str) -> MHMessage: ... + def get_bytes(self, key: str) -> bytes: ... + def get_file(self, key: str) -> _ProxyFile: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... def list_folders(self) -> list[str]: ... - def get_folder(self, folder: StrOrBytesPath) -> MH: ... - def add_folder(self, folder: StrOrBytesPath) -> MH: ... - def remove_folder(self, folder: StrOrBytesPath) -> None: ... + def get_folder(self, folder: StrPath) -> MH: ... + def add_folder(self, folder: StrPath) -> MH: ... + def remove_folder(self, folder: StrPath) -> None: ... def get_sequences(self) -> dict[str, list[int]]: ... def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... def pack(self) -> None: ... class Babyl(_singlefileMailbox[BabylMessage]): def __init__( - self, path: StrOrBytesPath, factory: Callable[[IO[Any]], BabylMessage] | None = ..., create: bool = ... + self, path: StrPath, factory: Callable[[_GetFileReturn], BabylMessage] | None = None, create: bool = True ) -> None: ... - def get_file(self, key: str) -> IO[bytes]: ... + def get_message(self, key: str) -> BabylMessage: ... + def get_bytes(self, key: str) -> bytes: ... + def get_file(self, key: str) -> io.BytesIO: ... def get_labels(self) -> list[str]: ... -class Message(email.message.Message): - def __init__(self, message: _MessageData | None = ...) -> None: ... +class Message(email.message.Message[str, str]): + def __init__(self, message: _MessageData | None = None) -> None: ... class MaildirMessage(Message): def get_subdir(self) -> str: ... @@ -148,7 +250,7 @@ class MaildirMessage(Message): class _mboxMMDFMessage(Message): def get_from(self) -> str: ... - def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = ...) -> None: ... + def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = None) -> None: ... def get_flags(self) -> str: ... def set_flags(self, flags: Iterable[str]) -> None: ... def add_flag(self, flag: str) -> None: ... @@ -173,29 +275,30 @@ class BabylMessage(Message): class MMDFMessage(_mboxMMDFMessage): ... -class _ProxyFile(Generic[AnyStr]): - def __init__(self, f: IO[AnyStr], pos: int | None = ...) -> None: ... - def read(self, size: int | None = ...) -> AnyStr: ... - def read1(self, size: int | None = ...) -> AnyStr: ... - def readline(self, size: int | None = ...) -> AnyStr: ... - def readlines(self, sizehint: int | None = ...) -> list[AnyStr]: ... - def __iter__(self) -> Iterator[AnyStr]: ... +# Until Python 3.14, this class was technically - but unnecessarily - generic at runtime. +class _ProxyFile: + def __init__(self, f: _GetFileReturn, pos: int | None = None) -> None: ... + def read(self, size: int | None = None) -> bytes: ... + def read1(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, sizehint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... def tell(self) -> int: ... - def seek(self, offset: int, whence: int = ...) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... def close(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc: Unused) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def seekable(self) -> bool: ... def flush(self) -> None: ... @property def closed(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + if sys.version_info < (3, 15): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class _PartialFile(_ProxyFile[AnyStr]): - def __init__(self, f: IO[AnyStr], start: int | None = ..., stop: int | None = ...) -> None: ... +class _PartialFile(_ProxyFile): + def __init__(self, f: _GetFileReturn, start: int | None = None, stop: int | None = None) -> None: ... class Error(Exception): ... class NoSuchMailboxError(Error): ... diff --git a/stdlib/mailcap.pyi b/stdlib/mailcap.pyi index 9eaa771ed3d3..74c32694a7f9 100644 --- a/stdlib/mailcap.pyi +++ b/stdlib/mailcap.pyi @@ -1,8 +1,11 @@ -from typing import Dict, Mapping, Sequence, Union +from collections.abc import Mapping, Sequence +from typing import TypeAlias -_Cap = Dict[str, Union[str, int]] +_Cap: TypeAlias = dict[str, str | int] + +__all__ = ["getcaps", "findmatch"] def findmatch( - caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... + caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = "view", filename: str = "/dev/null", plist: Sequence[str] = [] ) -> tuple[str | None, _Cap | None]: ... def getcaps() -> dict[str, list[_Cap]]: ... diff --git a/stdlib/marshal.pyi b/stdlib/marshal.pyi index b2fde674a647..04cdf05b1934 100644 --- a/stdlib/marshal.pyi +++ b/stdlib/marshal.pyi @@ -1,8 +1,51 @@ -from typing import IO, Any +import sys +import types +from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite +from typing import Any, Final, TypeAlias -version: int +version: Final[int] -def dump(__value: Any, __file: IO[Any], __version: int = ...) -> None: ... -def load(__file: IO[Any]) -> Any: ... -def dumps(__value: Any, __version: int = ...) -> bytes: ... -def loads(__bytes: bytes) -> Any: ... +_Marshallable: TypeAlias = ( + # handled in w_complex_object() in marshal.c + int + | float + | complex + | bytes + | str + | tuple[_Marshallable, ...] + | list[Any] + | dict[Any, Any] + | set[Any] + | frozenset[_Marshallable] + | types.CodeType + | ReadableBuffer + # handled in w_object() in marshal.c + | type[StopIteration] + | types.EllipsisType + | bool + | None +) + +if sys.version_info >= (3, 15): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 6, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 6, /, *, allow_code: bool = True) -> bytes: ... + +elif sys.version_info >= (3, 14): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 5, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 5, /, *, allow_code: bool = True) -> bytes: ... + +elif sys.version_info >= (3, 13): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 4, /, *, allow_code: bool = True) -> bytes: ... + +else: + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /) -> None: ... + def dumps(value: _Marshallable, version: int = 4, /) -> bytes: ... + +if sys.version_info >= (3, 13): + def load(file: SupportsRead[bytes], /, *, allow_code: bool = True) -> Any: ... + def loads(bytes: ReadableBuffer, /, *, allow_code: bool = True) -> Any: ... + +else: + def load(file: SupportsRead[bytes], /) -> Any: ... + def loads(bytes: ReadableBuffer, /) -> Any: ... diff --git a/stdlib/math.pyi b/stdlib/math.pyi deleted file mode 100644 index d5e6f99dfa68..000000000000 --- a/stdlib/math.pyi +++ /dev/null @@ -1,123 +0,0 @@ -import sys -from _typeshed import SupportsTrunc -from typing import Iterable, SupportsFloat, Union, overload -from typing_extensions import SupportsIndex - -if sys.version_info >= (3, 8): - _SupportsFloatOrIndex = Union[SupportsFloat, SupportsIndex] -else: - _SupportsFloatOrIndex = SupportsFloat - -e: float -pi: float -inf: float -nan: float -tau: float - -def acos(__x: _SupportsFloatOrIndex) -> float: ... -def acosh(__x: _SupportsFloatOrIndex) -> float: ... -def asin(__x: _SupportsFloatOrIndex) -> float: ... -def asinh(__x: _SupportsFloatOrIndex) -> float: ... -def atan(__x: _SupportsFloatOrIndex) -> float: ... -def atan2(__y: _SupportsFloatOrIndex, __x: _SupportsFloatOrIndex) -> float: ... -def atanh(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 11): - def cbrt(__x: _SupportsFloatOrIndex) -> float: ... - -def ceil(__x: _SupportsFloatOrIndex) -> int: ... - -if sys.version_info >= (3, 8): - def comb(__n: SupportsIndex, __k: SupportsIndex) -> int: ... - -def copysign(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... -def cos(__x: _SupportsFloatOrIndex) -> float: ... -def cosh(__x: _SupportsFloatOrIndex) -> float: ... -def degrees(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - def dist(__p: Iterable[_SupportsFloatOrIndex], __q: Iterable[_SupportsFloatOrIndex]) -> float: ... - -def erf(__x: _SupportsFloatOrIndex) -> float: ... -def erfc(__x: _SupportsFloatOrIndex) -> float: ... -def exp(__x: _SupportsFloatOrIndex) -> float: ... -def expm1(__x: _SupportsFloatOrIndex) -> float: ... -def fabs(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - def factorial(__x: SupportsIndex) -> int: ... - -else: - def factorial(__x: int) -> int: ... - -def floor(__x: _SupportsFloatOrIndex) -> int: ... -def fmod(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... -def frexp(__x: _SupportsFloatOrIndex) -> tuple[float, int]: ... -def fsum(__seq: Iterable[_SupportsFloatOrIndex]) -> float: ... -def gamma(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 9): - def gcd(*integers: SupportsIndex) -> int: ... - -else: - def gcd(__x: SupportsIndex, __y: SupportsIndex) -> int: ... - -if sys.version_info >= (3, 8): - def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... - -else: - def hypot(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... - -def isclose( - a: _SupportsFloatOrIndex, - b: _SupportsFloatOrIndex, - *, - rel_tol: _SupportsFloatOrIndex = ..., - abs_tol: _SupportsFloatOrIndex = ..., -) -> bool: ... -def isinf(__x: _SupportsFloatOrIndex) -> bool: ... -def isfinite(__x: _SupportsFloatOrIndex) -> bool: ... -def isnan(__x: _SupportsFloatOrIndex) -> bool: ... - -if sys.version_info >= (3, 8): - def isqrt(__n: SupportsIndex) -> int: ... - -if sys.version_info >= (3, 9): - def lcm(*integers: SupportsIndex) -> int: ... - -def ldexp(__x: _SupportsFloatOrIndex, __i: int) -> float: ... -def lgamma(__x: _SupportsFloatOrIndex) -> float: ... -def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ...) -> float: ... -def log10(__x: _SupportsFloatOrIndex) -> float: ... -def log1p(__x: _SupportsFloatOrIndex) -> float: ... -def log2(__x: _SupportsFloatOrIndex) -> float: ... -def modf(__x: _SupportsFloatOrIndex) -> tuple[float, float]: ... - -if sys.version_info >= (3, 9): - def nextafter(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - def perm(__n: SupportsIndex, __k: SupportsIndex | None = ...) -> int: ... - -def pow(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - @overload - def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = ...) -> int: ... # type: ignore[misc] - @overload - def prod(__iterable: Iterable[_SupportsFloatOrIndex], *, start: _SupportsFloatOrIndex = ...) -> float: ... - -def radians(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 7): - def remainder(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... - -def sin(__x: _SupportsFloatOrIndex) -> float: ... -def sinh(__x: _SupportsFloatOrIndex) -> float: ... -def sqrt(__x: _SupportsFloatOrIndex) -> float: ... -def tan(__x: _SupportsFloatOrIndex) -> float: ... -def tanh(__x: _SupportsFloatOrIndex) -> float: ... -def trunc(__x: SupportsTrunc) -> int: ... - -if sys.version_info >= (3, 9): - def ulp(__x: _SupportsFloatOrIndex) -> float: ... diff --git a/stdlib/math/__init__.pyi b/stdlib/math/__init__.pyi new file mode 100644 index 000000000000..b11324c4ae9a --- /dev/null +++ b/stdlib/math/__init__.pyi @@ -0,0 +1,157 @@ +import sys +from _typeshed import SupportsMul, SupportsRMul +from collections.abc import Iterable +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +_SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex + +e: Final[float] +pi: Final[float] +inf: Final[float] +nan: Final[float] +tau: Final[float] + +def acos(x: _SupportsFloatOrIndex, /) -> float: ... +def acosh(x: _SupportsFloatOrIndex, /) -> float: ... +def asin(x: _SupportsFloatOrIndex, /) -> float: ... +def asinh(x: _SupportsFloatOrIndex, /) -> float: ... +def atan(x: _SupportsFloatOrIndex, /) -> float: ... +def atan2(y: _SupportsFloatOrIndex, x: _SupportsFloatOrIndex, /) -> float: ... +def atanh(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 11): + def cbrt(x: _SupportsFloatOrIndex, /) -> float: ... + +@type_check_only +class _SupportsCeil(Protocol[_T_co]): + def __ceil__(self) -> _T_co: ... + +@overload +def ceil(x: _SupportsCeil[_T], /) -> _T: ... +@overload +def ceil(x: _SupportsFloatOrIndex, /) -> int: ... + +def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... +def copysign(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def cos(x: _SupportsFloatOrIndex, /) -> float: ... +def cosh(x: _SupportsFloatOrIndex, /) -> float: ... +def degrees(x: _SupportsFloatOrIndex, /) -> float: ... +def dist(p: Iterable[_SupportsFloatOrIndex], q: Iterable[_SupportsFloatOrIndex], /) -> float: ... +def erf(x: _SupportsFloatOrIndex, /) -> float: ... +def erfc(x: _SupportsFloatOrIndex, /) -> float: ... +def exp(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 11): + def exp2(x: _SupportsFloatOrIndex, /) -> float: ... + +def expm1(x: _SupportsFloatOrIndex, /) -> float: ... +def fabs(x: _SupportsFloatOrIndex, /) -> float: ... +def factorial(x: SupportsIndex, /) -> int: ... + +@type_check_only +class _SupportsFloor(Protocol[_T_co]): + def __floor__(self) -> _T_co: ... + +@overload +def floor(x: _SupportsFloor[_T], /) -> _T: ... +@overload +def floor(x: _SupportsFloatOrIndex, /) -> int: ... + +def fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 15): + def fmax(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + def fmin(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +def frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: ... +def fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: ... +def gamma(x: _SupportsFloatOrIndex, /) -> float: ... +def gcd(*integers: SupportsIndex) -> int: ... +def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... +def isclose( + a: _SupportsFloatOrIndex, + b: _SupportsFloatOrIndex, + *, + rel_tol: _SupportsFloatOrIndex = 1e-09, + abs_tol: _SupportsFloatOrIndex = 0.0, +) -> bool: ... +def isinf(x: _SupportsFloatOrIndex, /) -> bool: ... +def isfinite(x: _SupportsFloatOrIndex, /) -> bool: ... +def isnan(x: _SupportsFloatOrIndex, /) -> bool: ... + +if sys.version_info >= (3, 15): + def isnormal(x: _SupportsFloatOrIndex, /) -> bool: ... + def issubnormal(x: _SupportsFloatOrIndex, /) -> bool: ... + +def isqrt(n: SupportsIndex, /) -> int: ... +def lcm(*integers: SupportsIndex) -> int: ... +def ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: ... +def lgamma(x: _SupportsFloatOrIndex, /) -> float: ... +def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ..., /) -> float: ... +def log10(x: _SupportsFloatOrIndex, /) -> float: ... +def log1p(x: _SupportsFloatOrIndex, /) -> float: ... +def log2(x: _SupportsFloatOrIndex, /) -> float: ... +def modf(x: _SupportsFloatOrIndex, /) -> tuple[float, float]: ... + +if sys.version_info >= (3, 12): + def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /, *, steps: SupportsIndex | None = None) -> float: ... + +else: + def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... +def pow(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] +_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + +_MultiplicableT1 = TypeVar("_MultiplicableT1", bound=SupportsMul[Any, Any]) +_MultiplicableT2 = TypeVar("_MultiplicableT2", bound=SupportsMul[Any, Any]) + +@type_check_only +class _SupportsProdWithNoDefaultGiven(SupportsMul[Any, Any], SupportsRMul[int, Any], Protocol): ... + +_SupportsProdNoDefaultT = TypeVar("_SupportsProdNoDefaultT", bound=_SupportsProdWithNoDefaultGiven) + +# This stub is based on the type stub for `builtins.sum`. +# Like `builtins.sum`, it cannot be precisely represented in a type stub +# without introducing many false positives. +# For more details on its limitations and false positives, see #13572. +# Instead, just like `builtins.sum`, we explicitly handle several useful cases. +@overload +def prod(iterable: Iterable[bool | _LiteralInteger], /, *, start: int = 1) -> int: ... # type: ignore[overload-overlap] +@overload +def prod(iterable: Iterable[_SupportsProdNoDefaultT], /) -> _SupportsProdNoDefaultT | Literal[1]: ... +@overload +def prod(iterable: Iterable[_MultiplicableT1], /, *, start: _MultiplicableT2) -> _MultiplicableT1 | _MultiplicableT2: ... + +def radians(x: _SupportsFloatOrIndex, /) -> float: ... +def remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def sin(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 15): + def signbit(x: _SupportsFloatOrIndex, /) -> bool: ... + +def sinh(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 12): + def sumprod(p: Iterable[float], q: Iterable[float], /) -> float: ... + +def sqrt(x: _SupportsFloatOrIndex, /) -> float: ... +def tan(x: _SupportsFloatOrIndex, /) -> float: ... +def tanh(x: _SupportsFloatOrIndex, /) -> float: ... + +# Is different from `_typeshed.SupportsTrunc`, which is not generic +@type_check_only +class _SupportsTrunc(Protocol[_T_co]): + def __trunc__(self) -> _T_co: ... + +def trunc(x: _SupportsTrunc[_T], /) -> _T: ... +def ulp(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 13): + def fma(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, z: _SupportsFloatOrIndex, /) -> float: ... diff --git a/stdlib/math/integer.pyi b/stdlib/math/integer.pyi new file mode 100644 index 000000000000..6d6d6b3e82dc --- /dev/null +++ b/stdlib/math/integer.pyi @@ -0,0 +1,8 @@ +from typing import SupportsIndex + +def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... +def factorial(n: SupportsIndex, /) -> int: ... +def gcd(*integers: SupportsIndex) -> int: ... +def isqrt(n: SupportsIndex, /) -> int: ... +def lcm(*integers: SupportsIndex) -> int: ... +def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... diff --git a/stdlib/mimetypes.pyi b/stdlib/mimetypes.pyi index 90c87d2cf385..2390b2ce39f8 100644 --- a/stdlib/mimetypes.pyi +++ b/stdlib/mimetypes.pyi @@ -1,21 +1,39 @@ import sys from _typeshed import StrPath -from typing import IO, Sequence, Tuple +from collections.abc import Iterable +from typing import IO -if sys.version_info >= (3, 8): - def guess_type(url: StrPath, strict: bool = ...) -> tuple[str | None, str | None]: ... +__all__ = [ + "knownfiles", + "inited", + "MimeTypes", + "guess_type", + "guess_all_extensions", + "guess_extension", + "add_type", + "init", + "read_mime_types", + "suffix_map", + "encodings_map", + "types_map", + "common_types", +] -else: - def guess_type(url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... +if sys.version_info >= (3, 13): + __all__ += ["guess_file_type"] -def guess_all_extensions(type: str, strict: bool = ...) -> list[str]: ... -def guess_extension(type: str, strict: bool = ...) -> str | None: ... -def init(files: Sequence[str] | None = ...) -> None: ... -def read_mime_types(file: str) -> dict[str, str] | None: ... -def add_type(type: str, ext: str, strict: bool = ...) -> None: ... +def guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... +def guess_all_extensions(type: str, strict: bool = True) -> list[str]: ... +def guess_extension(type: str, strict: bool = True) -> str | None: ... +def init(files: Iterable[StrPath] | None = None) -> None: ... +def read_mime_types(file: StrPath) -> dict[str, str] | None: ... +def add_type(type: str, ext: str, strict: bool = True) -> None: ... + +if sys.version_info >= (3, 13): + def guess_file_type(path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: ... inited: bool -knownfiles: list[str] +knownfiles: list[StrPath] suffix_map: dict[str, str] encodings_map: dict[str, str] types_map: dict[str, str] @@ -26,11 +44,13 @@ class MimeTypes: encodings_map: dict[str, str] types_map: tuple[dict[str, str], dict[str, str]] types_map_inv: tuple[dict[str, str], dict[str, str]] - def __init__(self, filenames: Tuple[str, ...] = ..., strict: bool = ...) -> None: ... - def guess_extension(self, type: str, strict: bool = ...) -> str | None: ... - def guess_type(self, url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... - def guess_all_extensions(self, type: str, strict: bool = ...) -> list[str]: ... - def read(self, filename: str, strict: bool = ...) -> None: ... - def readfp(self, fp: IO[str], strict: bool = ...) -> None: ... - if sys.platform == "win32": - def read_windows_registry(self, strict: bool = ...) -> None: ... + def __init__(self, filenames: Iterable[StrPath] = (), strict: bool = True) -> None: ... + def add_type(self, type: str, ext: str, strict: bool = True) -> None: ... + def guess_extension(self, type: str, strict: bool = True) -> str | None: ... + def guess_type(self, url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... + def guess_all_extensions(self, type: str, strict: bool = True) -> list[str]: ... + def read(self, filename: StrPath, strict: bool = True) -> None: ... + def readfp(self, fp: IO[str], strict: bool = True) -> None: ... + def read_windows_registry(self, strict: bool = True) -> None: ... + if sys.version_info >= (3, 13): + def guess_file_type(self, path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: ... diff --git a/stdlib/mmap.pyi b/stdlib/mmap.pyi index b79ab92f0c87..442a7807753a 100644 --- a/stdlib/mmap.pyi +++ b/stdlib/mmap.pyi @@ -1,102 +1,191 @@ +import os import sys -from _typeshed import ReadableBuffer -from contextlib import AbstractContextManager -from typing import Iterable, Iterator, NoReturn, Sized, overload +from _typeshed import ReadableBuffer, Unused +from collections.abc import Iterator +from typing import Final, Literal, SupportsIndex, overload +from typing_extensions import Never, Self, disjoint_base -ACCESS_DEFAULT: int -ACCESS_READ: int -ACCESS_WRITE: int -ACCESS_COPY: int +ACCESS_DEFAULT: Final = 0 +ACCESS_READ: Final = 1 +ACCESS_WRITE: Final = 2 +ACCESS_COPY: Final = 3 -ALLOCATIONGRANULARITY: int +ALLOCATIONGRANULARITY: Final[int] if sys.platform == "linux": - MAP_DENYWRITE: int - MAP_EXECUTABLE: int + MAP_DENYWRITE: Final[int] + MAP_EXECUTABLE: Final[int] + MAP_POPULATE: Final[int] +if sys.version_info >= (3, 11) and sys.platform != "win32" and sys.platform != "darwin": + MAP_STACK: Final[int] if sys.platform != "win32": - MAP_ANON: int - MAP_ANONYMOUS: int - MAP_PRIVATE: int - MAP_SHARED: int - PROT_EXEC: int - PROT_READ: int - PROT_WRITE: int + MAP_ANON: Final[int] + MAP_ANONYMOUS: Final[int] + MAP_PRIVATE: Final[int] + MAP_SHARED: Final[int] + PROT_EXEC: Final[int] + PROT_READ: Final[int] + PROT_WRITE: Final[int] + if sys.version_info >= (3, 15): + MS_ASYNC: Final[int] + MS_INVALIDATE: Final[int] + MS_SYNC: Final[int] - PAGESIZE: int +PAGESIZE: Final[int] -class mmap(AbstractContextManager[mmap], Iterable[int], Sized): +@disjoint_base +class mmap: if sys.platform == "win32": - def __init__(self, fileno: int, length: int, tagname: str | None = ..., access: int = ..., offset: int = ...) -> None: ... + if sys.version_info >= (3, 15): + def __new__( + cls, + fileno: int, + length: int, + tagname: str | None = None, + access: int = 0, + offset: int = 0, + *, + trackfd: bool = True, + ) -> Self: ... + else: + def __new__(cls, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> Self: ... else: - def __init__( - self, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = ..., offset: int = ... - ) -> None: ... + if sys.version_info >= (3, 13): + def __new__( + cls, + fileno: int, + length: int, + flags: int = ..., + prot: int = ..., + access: int = 0, + offset: int = 0, + *, + trackfd: bool = True, + ) -> Self: ... + else: + def __new__( + cls, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = 0, offset: int = 0 + ) -> Self: ... + def close(self) -> None: ... - if sys.version_info >= (3, 8): - def flush(self, offset: int = ..., size: int = ...) -> None: ... + if sys.version_info >= (3, 15): + def flush(self, offset: int = 0, size: int = -1, /, *, flags: int = 0) -> None: ... + elif sys.version_info >= (3, 14): + # size default changed in Python 3.14.1 + def flush(self, offset: int = 0, size: int | None = None, /) -> None: ... else: - def flush(self, offset: int = ..., size: int = ...) -> int: ... - def move(self, dest: int, src: int, count: int) -> None: ... + def flush(self, offset: int = 0, size: int = ..., /) -> None: ... + + def move(self, dest: int, src: int, count: int, /) -> None: ... def read_byte(self) -> int: ... def readline(self) -> bytes: ... - def resize(self, newsize: int) -> None: ... - def seek(self, pos: int, whence: int = ...) -> None: ... + if sys.version_info < (3, 15) or sys.platform != "darwin": + def resize(self, newsize: int, /) -> None: ... + if sys.platform != "win32": + def seek(self, pos: int, whence: Literal[0, 1, 2, 3, 4] = os.SEEK_SET, /) -> None: ... + else: + def seek(self, pos: int, whence: Literal[0, 1, 2] = os.SEEK_SET, /) -> None: ... + def size(self) -> int: ... def tell(self) -> int: ... - def write_byte(self, byte: int) -> None: ... + def write_byte(self, byte: int, /) -> None: ... def __len__(self) -> int: ... closed: bool - if sys.version_info >= (3, 8) and sys.platform != "win32": - def madvise(self, option: int, start: int = ..., length: int = ...) -> None: ... - def find(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... - def rfind(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... - def read(self, n: int | None = ...) -> bytes: ... - def write(self, bytes: ReadableBuffer) -> int: ... + if sys.platform != "win32": + if sys.version_info >= (3, 15): + def madvise(self, option: int, start: int = 0, length: int | None = None, /) -> None: ... + else: + def madvise(self, option: int, start: int = 0, length: int = ..., /) -> None: ... + + if sys.version_info >= (3, 14): + # default values changed in Python 3.14.1 + def find(self, view: ReadableBuffer, start: int | None = None, end: int | None = None, /) -> int: ... + def rfind(self, view: ReadableBuffer, start: int | None = None, end: int | None = None, /) -> int: ... + + else: + def find(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... + def rfind(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... + + def read(self, n: int | None = None, /) -> bytes: ... + def write(self, bytes: ReadableBuffer, /) -> int: ... + if sys.version_info >= (3, 15): + def set_name(self, name: str, /) -> None: ... + @overload - def __getitem__(self, index: int) -> int: ... + def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload - def __getitem__(self, index: slice) -> bytes: ... - def __delitem__(self, index: int | slice) -> NoReturn: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> Never: ... + @overload - def __setitem__(self, index: int, object: int) -> None: ... + def __setitem__(self, key: SupportsIndex, value: int, /) -> None: ... @overload - def __setitem__(self, index: slice, object: ReadableBuffer) -> None: ... - # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and - # __len__, so we claim that there is also an __iter__ to help type checkers. + def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ... + + # Doesn't actually exist, but the object actually supports "in" because it has __getitem__, + # so we claim that there is also a __contains__ to help type checkers. + def __contains__(self, o: object, /) -> bool: ... + # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and __len__, + # so we claim that there is also an __iter__ to help type checkers. def __iter__(self) -> Iterator[int]: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: Unused, exc_value: Unused, traceback: Unused, /) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 13): + def seekable(self) -> Literal[True]: ... + +if sys.platform != "win32": + MADV_NORMAL: Final[int] + MADV_RANDOM: Final[int] + MADV_SEQUENTIAL: Final[int] + MADV_WILLNEED: Final[int] + MADV_DONTNEED: Final[int] + MADV_FREE: Final[int] + +if sys.platform == "linux": + MADV_REMOVE: Final[int] + MADV_DONTFORK: Final[int] + MADV_DOFORK: Final[int] + MADV_HWPOISON: Final[int] + MADV_MERGEABLE: Final[int] + MADV_UNMERGEABLE: Final[int] + # Seems like this constant is not defined in glibc. + # See https://github.com/python/typeshed/pull/5360 for details + # MADV_SOFT_OFFLINE: Final[int] + MADV_HUGEPAGE: Final[int] + MADV_NOHUGEPAGE: Final[int] + MADV_DONTDUMP: Final[int] + MADV_DODUMP: Final[int] + +# This Values are defined for FreeBSD but type checkers do not support conditions for these +if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": + MADV_NOSYNC: Final[int] + MADV_AUTOSYNC: Final[int] + MADV_NOCORE: Final[int] + MADV_CORE: Final[int] + MADV_PROTECT: Final[int] + +if sys.platform == "darwin": + MADV_FREE_REUSABLE: Final[int] + MADV_FREE_REUSE: Final[int] + +if sys.version_info >= (3, 13) and sys.platform != "win32": + MAP_32BIT: Final[int] + +if sys.version_info >= (3, 13) and sys.platform == "darwin": + MAP_NORESERVE: Final = 64 + MAP_NOEXTEND: Final = 256 + MAP_HASSEMAPHORE: Final = 512 + MAP_NOCACHE: Final = 1024 + MAP_JIT: Final = 2048 + MAP_RESILIENT_CODESIGN: Final = 8192 + MAP_RESILIENT_MEDIA: Final = 16384 + MAP_TRANSLATED_ALLOW_EXECUTE: Final = 131072 + MAP_UNIX03: Final = 262144 + MAP_TPRO: Final = 524288 -if sys.version_info >= (3, 8) and sys.platform != "win32": - MADV_NORMAL: int - MADV_RANDOM: int - MADV_SEQUENTIAL: int - MADV_WILLNEED: int - MADV_DONTNEED: int - - if sys.platform == "linux": - MADV_REMOVE: int - MADV_DONTFORK: int - MADV_DOFORK: int - MADV_HWPOISON: int - MADV_MERGEABLE: int - MADV_UNMERGEABLE: int - # Seems like this constant is not defined in glibc. - # See https://github.com/python/typeshed/pull/5360 for details - # MADV_SOFT_OFFLINE: int - MADV_HUGEPAGE: int - MADV_NOHUGEPAGE: int - MADV_DONTDUMP: int - MADV_DODUMP: int - MADV_FREE: int - - # This Values are defined for FreeBSD but type checkers do not support conditions for these - if sys.platform != "linux" and sys.platform != "darwin": - MADV_NOSYNC: int - MADV_AUTOSYNC: int - MADV_NOCORE: int - MADV_CORE: int - MADV_PROTECT: int - -if sys.version_info >= (3, 10) and sys.platform == "darwin": - MADV_FREE_REUSABLE: int - MADV_FREE_REUSE: int +if sys.version_info >= (3, 13) and sys.platform == "linux": + MAP_NORESERVE: Final = 16384 diff --git a/stdlib/modulefinder.pyi b/stdlib/modulefinder.pyi index e77a108e9525..6db665a18e69 100644 --- a/stdlib/modulefinder.pyi +++ b/stdlib/modulefinder.pyi @@ -1,13 +1,15 @@ import sys +from collections.abc import Container, Iterable, Iterator, Sequence from types import CodeType -from typing import IO, Any, Container, Iterable, Iterator, Sequence, Tuple +from typing import IO, Any, Final -LOAD_CONST: int # undocumented -IMPORT_NAME: int # undocumented -STORE_NAME: int # undocumented -STORE_GLOBAL: int # undocumented -STORE_OPS: tuple[int, int] # undocumented -EXTENDED_ARG: int # undocumented +if sys.version_info < (3, 11): + LOAD_CONST: Final[int] # undocumented + IMPORT_NAME: Final[int] # undocumented + STORE_NAME: Final[int] # undocumented + STORE_GLOBAL: Final[int] # undocumented + STORE_OPS: Final[tuple[int, int]] # undocumented + EXTENDED_ARG: Final[int] # undocumented packagePathMap: dict[str, list[str]] # undocumented @@ -18,11 +20,9 @@ replacePackageMap: dict[str, str] # undocumented def ReplacePackage(oldname: str, newname: str) -> None: ... class Module: # undocumented - def __init__(self, name: str, file: str | None = ..., path: str | None = ...) -> None: ... - def __repr__(self) -> str: ... + def __init__(self, name: str, file: str | None = None, path: str | None = None) -> None: ... class ModuleFinder: - modules: dict[str, Module] path: list[str] # undocumented badmodules: dict[str, dict[str, int]] # undocumented @@ -31,45 +31,38 @@ class ModuleFinder: excludes: Container[str] # undocumented replace_paths: Sequence[tuple[str, str]] # undocumented - if sys.version_info >= (3, 8): - def __init__( - self, - path: list[str] | None = ..., - debug: int = ..., - excludes: Container[str] | None = ..., - replace_paths: Sequence[tuple[str, str]] | None = ..., - ) -> None: ... - else: - def __init__( - self, - path: list[str] | None = ..., - debug: int = ..., - excludes: Container[str] = ..., - replace_paths: Sequence[tuple[str, str]] = ..., - ) -> None: ... + def __init__( + self, + path: list[str] | None = None, + debug: int = 0, + excludes: Container[str] | None = None, + replace_paths: Sequence[tuple[str, str]] | None = None, + ) -> None: ... def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented def msgin(self, *args: Any) -> None: ... # undocumented def msgout(self, *args: Any) -> None: ... # undocumented def run_script(self, pathname: str) -> None: ... def load_file(self, pathname: str) -> None: ... # undocumented def import_hook( - self, name: str, caller: Module | None = ..., fromlist: list[str] | None = ..., level: int = ... + self, name: str, caller: Module | None = None, fromlist: list[str] | None = None, level: int = -1 ) -> Module | None: ... # undocumented - def determine_parent(self, caller: Module | None, level: int = ...) -> Module | None: ... # undocumented + def determine_parent(self, caller: Module | None, level: int = -1) -> Module | None: ... # undocumented def find_head_package(self, parent: Module, name: str) -> tuple[Module, str]: ... # undocumented def load_tail(self, q: Module, tail: str) -> Module: ... # undocumented - def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = ...) -> None: ... # undocumented + def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = 0) -> None: ... # undocumented def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented def import_module(self, partname: str, fqname: str, parent: Module) -> Module | None: ... # undocumented def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: tuple[str, str, str]) -> Module: ... # undocumented - def scan_opcodes(self, co: CodeType) -> Iterator[tuple[str, Tuple[Any, ...]]]: ... # undocumented + def scan_opcodes(self, co: CodeType) -> Iterator[tuple[str, tuple[Any, ...]]]: ... # undocumented def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented def add_module(self, fqname: str) -> Module: ... # undocumented def find_module( - self, name: str, path: str | None, parent: Module | None = ... + self, name: str, path: str | None, parent: Module | None = None ) -> tuple[IO[Any] | None, str | None, tuple[str, str, int]]: ... # undocumented def report(self) -> None: ... def any_missing(self) -> list[str]: ... # undocumented def any_missing_maybe(self) -> tuple[list[str], list[str]]: ... # undocumented def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented + +def test() -> ModuleFinder | None: ... # undocumented diff --git a/stdlib/msilib/__init__.pyi b/stdlib/msilib/__init__.pyi index 4e1a7e6a7c02..565a52d53499 100644 --- a/stdlib/msilib/__init__.pyi +++ b/stdlib/msilib/__init__.pyi @@ -1,43 +1,44 @@ import sys +from _typeshed import MaybeNone +from collections.abc import Container, Iterable from types import ModuleType -from typing import Any, Container, Iterable, Sequence, Tuple, Type -from typing_extensions import Literal +from typing import Any, Final if sys.platform == "win32": + from _msi import * from _msi import _Database - AMD64: bool - if sys.version_info < (3, 7): - Itanium: bool - Win64: bool + from .sequence import _SequenceType - datasizemask: Literal[0x00FF] - type_valid: Literal[0x0100] - type_localizable: Literal[0x0200] - typemask: Literal[0x0C00] - type_long: Literal[0x0000] - type_short: Literal[0x0400] - type_string: Literal[0x0C00] - type_binary: Literal[0x0800] - type_nullable: Literal[0x1000] - type_key: Literal[0x2000] - knownbits: Literal[0x3FFF] - class Table: + AMD64: Final[bool] + Win64: Final[bool] + + datasizemask: Final = 0x00FF + type_valid: Final = 0x0100 + type_localizable: Final = 0x0200 + typemask: Final = 0x0C00 + type_long: Final = 0x0000 + type_short: Final = 0x0400 + type_string: Final = 0x0C00 + type_binary: Final = 0x0800 + type_nullable: Final = 0x1000 + type_key: Final = 0x2000 + knownbits: Final = 0x3FFF + class Table: name: str fields: list[tuple[int, str, int]] def __init__(self, name: str) -> None: ... def add_field(self, index: int, name: str, type: int) -> None: ... def sql(self) -> str: ... def create(self, db: _Database) -> None: ... + class _Unspecified: ... + def change_sequence( - seq: Sequence[tuple[str, str | None, int]], - action: str, - seqno: int | Type[_Unspecified] = ..., - cond: str | Type[_Unspecified] = ..., + seq: _SequenceType, action: str, seqno: int | type[_Unspecified] = ..., cond: str | type[_Unspecified] = ... ) -> None: ... - def add_data(db: _Database, table: str, values: Iterable[Tuple[Any, ...]]) -> None: ... + def add_data(db: _Database, table: str, values: Iterable[tuple[Any, ...]]) -> None: ... def add_stream(db: _Database, name: str, path: str) -> None: ... def init_database( name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str @@ -45,22 +46,23 @@ if sys.platform == "win32": def add_tables(db: _Database, module: ModuleType) -> None: ... def make_id(str: str) -> str: ... def gen_uuid() -> str: ... - class CAB: + class CAB: name: str files: list[tuple[str, str]] filenames: set[str] index: int def __init__(self, name: str) -> None: ... def gen_id(self, file: str) -> str: ... - def append(self, full: str, file: str, logical: str) -> tuple[int, str]: ... + def append(self, full: str, file: str, logical: str | None) -> tuple[int, str] | MaybeNone: ... def commit(self, db: _Database) -> None: ... + _directories: set[str] - class Directory: + class Directory: db: _Database cab: CAB - basedir: str + basedir: Directory | None physical: str logical: str component: str | None @@ -73,31 +75,30 @@ if sys.platform == "win32": self, db: _Database, cab: CAB, - basedir: str, + basedir: Directory | None, physical: str, _logical: str, default: str, - componentflags: int | None = ..., + componentflags: int | None = None, ) -> None: ... def start_component( self, - component: str | None = ..., - feature: Feature | None = ..., - flags: int | None = ..., - keyfile: str | None = ..., - uuid: str | None = ..., + component: str | None = None, + feature: Feature | None = None, + flags: int | None = None, + keyfile: str | None = None, + uuid: str | None = None, ) -> None: ... def make_short(self, file: str) -> str: ... - def add_file(self, file: str, src: str | None = ..., version: str | None = ..., language: str | None = ...) -> str: ... - def glob(self, pattern: str, exclude: Container[str] | None = ...) -> list[str]: ... + def add_file(self, file: str, src: str | None = None, version: str | None = None, language: str | None = None) -> str: ... + def glob(self, pattern: str, exclude: Container[str] | None = None) -> list[str]: ... def remove_pyc(self) -> None: ... - class Binary: + class Binary: name: str def __init__(self, fname: str) -> None: ... - def __repr__(self) -> str: ... - class Feature: + class Feature: id: str def __init__( self, @@ -106,28 +107,28 @@ if sys.platform == "win32": title: str, desc: str, display: int, - level: int = ..., - parent: Feature | None = ..., - directory: str | None = ..., - attributes: int = ..., + level: int = 1, + parent: Feature | None = None, + directory: str | None = None, + attributes: int = 0, ) -> None: ... def set_current(self) -> None: ... - class Control: + class Control: dlg: Dialog name: str def __init__(self, dlg: Dialog, name: str) -> None: ... - def event(self, event: str, argument: str, condition: str = ..., ordering: int | None = ...) -> None: ... + def event(self, event: str, argument: str, condition: str = "1", ordering: int | None = None) -> None: ... def mapping(self, event: str, attribute: str) -> None: ... def condition(self, action: str, condition: str) -> None: ... - class RadioButtonGroup(Control): + class RadioButtonGroup(Control): property: str index: int def __init__(self, dlg: Dialog, name: str, property: str) -> None: ... - def add(self, name: str, x: int, y: int, w: int, h: int, text: str, value: str | None = ...) -> None: ... - class Dialog: + def add(self, name: str, x: int, y: int, w: int, h: int, text: str, value: str | None = None) -> None: ... + class Dialog: db: _Database name: str x: int @@ -145,8 +146,8 @@ if sys.platform == "win32": attr: int, title: str, first: str, - default: str, - cancel: str, + default: str | None, + cancel: str | None, ) -> None: ... def control( self, diff --git a/stdlib/msilib/schema.pyi b/stdlib/msilib/schema.pyi index 4ad9a1783fcd..3bbdc41a1e8e 100644 --- a/stdlib/msilib/schema.pyi +++ b/stdlib/msilib/schema.pyi @@ -1,4 +1,5 @@ import sys +from typing import Final if sys.platform == "win32": from . import Table @@ -89,6 +90,6 @@ if sys.platform == "win32": Upgrade: Table Verb: Table - tables: list[Table] + tables: Final[list[Table]] _Validation_records: list[tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] diff --git a/stdlib/msilib/sequence.pyi b/stdlib/msilib/sequence.pyi index 123d232886f7..9b01c416f1d6 100644 --- a/stdlib/msilib/sequence.pyi +++ b/stdlib/msilib/sequence.pyi @@ -1,14 +1,13 @@ import sys -from typing import List, Optional, Tuple +from typing import Final, TypeAlias if sys.platform == "win32": + _SequenceType: TypeAlias = list[tuple[str, str | None, int]] - _SequenceType = List[Tuple[str, Optional[str], int]] + AdminExecuteSequence: Final[_SequenceType] + AdminUISequence: Final[_SequenceType] + AdvtExecuteSequence: Final[_SequenceType] + InstallExecuteSequence: Final[_SequenceType] + InstallUISequence: Final[_SequenceType] - AdminExecuteSequence: _SequenceType - AdminUISequence: _SequenceType - AdvtExecuteSequence: _SequenceType - InstallExecuteSequence: _SequenceType - InstallUISequence: _SequenceType - - tables: list[str] + tables: Final[list[str]] diff --git a/stdlib/msilib/text.pyi b/stdlib/msilib/text.pyi index 879429ecea85..da3c5fd0fb7a 100644 --- a/stdlib/msilib/text.pyi +++ b/stdlib/msilib/text.pyi @@ -1,8 +1,8 @@ import sys +from typing import Final if sys.platform == "win32": - - ActionText: list[tuple[str, str, str | None]] - UIText: list[tuple[str, str | None]] - - tables: list[str] + ActionText: Final[list[tuple[str, str, str | None]]] + UIText: Final[list[tuple[str, str | None]]] + dirname: str + tables: Final[list[str]] diff --git a/stdlib/msvcrt.pyi b/stdlib/msvcrt.pyi index 0441ed8acd24..1518f7974de7 100644 --- a/stdlib/msvcrt.pyi +++ b/stdlib/msvcrt.pyi @@ -1,23 +1,31 @@ import sys +from typing import Final # This module is only available on Windows if sys.platform == "win32": - LK_LOCK: int - LK_NBLCK: int - LK_NBRLCK: int - LK_RLCK: int - LK_UNLCK: int - def locking(__fd: int, __mode: int, __nbytes: int) -> None: ... - def setmode(__fd: int, __mode: int) -> int: ... - def open_osfhandle(__handle: int, __flags: int) -> int: ... - def get_osfhandle(__fd: int) -> int: ... + CRT_ASSEMBLY_VERSION: Final[str] + LK_UNLCK: Final = 0 + LK_LOCK: Final = 1 + LK_NBLCK: Final = 2 + LK_RLCK: Final = 3 + LK_NBRLCK: Final = 4 + SEM_FAILCRITICALERRORS: Final = 0x0001 + SEM_NOALIGNMENTFAULTEXCEPT: Final = 0x0004 + SEM_NOGPFAULTERRORBOX: Final = 0x0002 + SEM_NOOPENFILEERRORBOX: Final = 0x8000 + def locking(fd: int, mode: int, nbytes: int, /) -> None: ... + def setmode(fd: int, mode: int, /) -> int: ... + def open_osfhandle(handle: int, flags: int, /) -> int: ... + def get_osfhandle(fd: int, /) -> int: ... def kbhit() -> bool: ... def getch() -> bytes: ... def getwch() -> str: ... def getche() -> bytes: ... def getwche() -> str: ... - def putch(__char: bytes) -> None: ... - def putwch(__unicode_char: str) -> None: ... - def ungetch(__char: bytes) -> None: ... - def ungetwch(__unicode_char: str) -> None: ... + def putch(char: bytes | bytearray, /) -> None: ... + def putwch(unicode_char: str, /) -> None: ... + def ungetch(char: bytes | bytearray, /) -> None: ... + def ungetwch(unicode_char: str, /) -> None: ... def heapmin() -> None: ... + def SetErrorMode(mode: int, /) -> int: ... + def GetErrorMode() -> int: ... # undocumented diff --git a/stdlib/multiprocessing/__init__.pyi b/stdlib/multiprocessing/__init__.pyi index 000fed79f3e4..2bd6e2883ddb 100644 --- a/stdlib/multiprocessing/__init__.pyi +++ b/stdlib/multiprocessing/__init__.pyi @@ -1,108 +1,90 @@ -import sys -from collections.abc import Callable, Iterable -from logging import Logger -from multiprocessing import connection, context, pool, synchronize +from multiprocessing import context, reduction as reducer from multiprocessing.context import ( AuthenticationError as AuthenticationError, - BaseContext, BufferTooShort as BufferTooShort, - DefaultContext, Process as Process, ProcessError as ProcessError, - SpawnContext, TimeoutError as TimeoutError, ) -from multiprocessing.managers import SyncManager -from multiprocessing.process import active_children as active_children, current_process as current_process +from multiprocessing.process import ( + active_children as active_children, + current_process as current_process, + parent_process as parent_process, +) # These are technically functions that return instances of these Queue classes. -# Using them as annotations is deprecated. Either use imports from -# multiprocessing.queues or the aliases defined below. See #4266 for discussion. +# The stub here doesn't reflect reality exactly -- +# while e.g. `multiprocessing.queues.Queue` is a class, +# `multiprocessing.Queue` is actually a function at runtime. +# Avoid using `multiprocessing.Queue` as a type annotation; +# use imports from multiprocessing.queues instead. +# See #4266 and #8450 for discussion. from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support -from typing import Any, Union, overload -from typing_extensions import Literal - -if sys.version_info >= (3, 8): - from multiprocessing.process import parent_process as parent_process - -if sys.platform != "win32": - from multiprocessing.context import ForkContext, ForkServerContext - -# The following type aliases can be used to annotate the return values of -# the corresponding functions. They are not defined at runtime. -# -# from multiprocessing import Lock -# from typing import TYPE_CHECKING -# if TYPE_CHECKING: -# from multiprocessing import _LockType -# lock: _LockType = Lock() - -_QueueType = Queue -_SimpleQueueType = SimpleQueue -_JoinableQueueType = JoinableQueue -_BarrierType = synchronize.Barrier -_BoundedSemaphoreType = synchronize.BoundedSemaphore -_ConditionType = synchronize.Condition -_EventType = synchronize.Event -_LockType = synchronize.Lock -_RLockType = synchronize.RLock -_SemaphoreType = synchronize.Semaphore -# N.B. The functions below are generated at runtime by partially applying -# multiprocessing.context.BaseContext's methods, so the two signatures should -# be identical (modulo self). +__all__ = [ + "Array", + "AuthenticationError", + "Barrier", + "BoundedSemaphore", + "BufferTooShort", + "Condition", + "Event", + "JoinableQueue", + "Lock", + "Manager", + "Pipe", + "Pool", + "Process", + "ProcessError", + "Queue", + "RLock", + "RawArray", + "RawValue", + "Semaphore", + "SimpleQueue", + "TimeoutError", + "Value", + "active_children", + "allow_connection_pickling", + "cpu_count", + "current_process", + "freeze_support", + "get_all_start_methods", + "get_context", + "get_logger", + "get_start_method", + "log_to_stderr", + "parent_process", + "reducer", + "set_executable", + "set_forkserver_preload", + "set_start_method", +] -# Synchronization primitives -_LockLike = Union[synchronize.Lock, synchronize.RLock] +# These functions (really bound methods) +# are all autogenerated at runtime here: https://github.com/python/cpython/blob/600c65c094b0b48704d8ec2416930648052ba715/Lib/multiprocessing/__init__.py#L23 RawValue = context._default_context.RawValue RawArray = context._default_context.RawArray Value = context._default_context.Value Array = context._default_context.Array - -def Barrier(parties: int, action: Callable[..., Any] | None = ..., timeout: float | None = ...) -> _BarrierType: ... -def BoundedSemaphore(value: int = ...) -> _BoundedSemaphoreType: ... -def Condition(lock: _LockLike | None = ...) -> _ConditionType: ... -def Event() -> _EventType: ... -def Lock() -> _LockType: ... -def RLock() -> _RLockType: ... -def Semaphore(value: int = ...) -> _SemaphoreType: ... -def Pipe(duplex: bool = ...) -> tuple[connection.Connection, connection.Connection]: ... -def Pool( - processes: int | None = ..., - initializer: Callable[..., Any] | None = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: int | None = ..., -) -> pool.Pool: ... - -# ----- multiprocessing function stubs ----- -def allow_connection_pickling() -> None: ... -def cpu_count() -> int: ... -def get_logger() -> Logger: ... -def log_to_stderr(level: str | int | None = ...) -> Logger: ... -def Manager() -> SyncManager: ... -def set_executable(executable: str) -> None: ... -def set_forkserver_preload(module_names: list[str]) -> None: ... -def get_all_start_methods() -> list[str]: ... -def get_start_method(allow_none: bool = ...) -> str | None: ... -def set_start_method(method: str, force: bool | None = ...) -> None: ... - -if sys.platform != "win32": - @overload - def get_context(method: None = ...) -> DefaultContext: ... - @overload - def get_context(method: Literal["spawn"]) -> SpawnContext: ... - @overload - def get_context(method: Literal["fork"]) -> ForkContext: ... - @overload - def get_context(method: Literal["forkserver"]) -> ForkServerContext: ... - @overload - def get_context(method: str) -> BaseContext: ... - -else: - @overload - def get_context(method: None = ...) -> DefaultContext: ... - @overload - def get_context(method: Literal["spawn"]) -> SpawnContext: ... - @overload - def get_context(method: str) -> BaseContext: ... +Barrier = context._default_context.Barrier +BoundedSemaphore = context._default_context.BoundedSemaphore +Condition = context._default_context.Condition +Event = context._default_context.Event +Lock = context._default_context.Lock +RLock = context._default_context.RLock +Semaphore = context._default_context.Semaphore +Pipe = context._default_context.Pipe +Pool = context._default_context.Pool +allow_connection_pickling = context._default_context.allow_connection_pickling +cpu_count = context._default_context.cpu_count +get_logger = context._default_context.get_logger +log_to_stderr = context._default_context.log_to_stderr +Manager = context._default_context.Manager +set_executable = context._default_context.set_executable +set_forkserver_preload = context._default_context.set_forkserver_preload +get_all_start_methods = context._default_context.get_all_start_methods +get_start_method = context._default_context.get_start_method +set_start_method = context._default_context.set_start_method +get_context = context._default_context.get_context diff --git a/stdlib/multiprocessing/connection.pyi b/stdlib/multiprocessing/connection.pyi index 56ea5c7c0b0b..c63e6920fc46 100644 --- a/stdlib/multiprocessing/connection.pyi +++ b/stdlib/multiprocessing/connection.pyi @@ -1,20 +1,23 @@ import socket import sys -import types -from _typeshed import Self -from typing import Any, Iterable, Tuple, Type, Union +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from types import TracebackType +from typing import Any, Generic, SupportsIndex, TypeAlias, TypeVar +from typing_extensions import Self -if sys.version_info >= (3, 8): - from typing import SupportsIndex +__all__ = ["Client", "Listener", "Pipe", "wait"] # https://docs.python.org/3/library/multiprocessing.html#address-formats -_Address = Union[str, Tuple[str, int]] +# bytes: Linux abstract AF_UNIX socket name (starts with a null byte) +_Address: TypeAlias = str | bytes | tuple[str, int] -class _ConnectionBase: - if sys.version_info >= (3, 8): - def __init__(self, handle: SupportsIndex, readable: bool = ..., writable: bool = ...) -> None: ... - else: - def __init__(self, handle: int, readable: bool = ..., writable: bool = ...) -> None: ... +# Defaulting to Any to avoid forcing generics on a lot of pre-existing code +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=Any) +_RecvT_co = TypeVar("_RecvT_co", covariant=True, default=Any) + +class _ConnectionBase(Generic[_SendT_contra, _RecvT_co]): + def __init__(self, handle: SupportsIndex, readable: bool = True, writable: bool = True) -> None: ... @property def closed(self) -> bool: ... # undocumented @property @@ -23,41 +26,72 @@ class _ConnectionBase: def writable(self) -> bool: ... # undocumented def fileno(self) -> int: ... def close(self) -> None: ... - def send_bytes(self, buf: bytes, offset: int = ..., size: int | None = ...) -> None: ... - def send(self, obj: Any) -> None: ... - def recv_bytes(self, maxlength: int | None = ...) -> bytes: ... - def recv_bytes_into(self, buf: Any, offset: int = ...) -> int: ... - def recv(self) -> Any: ... - def poll(self, timeout: float | None = ...) -> bool: ... - def __enter__(self: Self) -> Self: ... + def send_bytes(self, buf: ReadableBuffer, offset: int = 0, size: int | None = None) -> None: ... + def send(self, obj: _SendT_contra) -> None: ... + def recv_bytes(self, maxlength: int | None = None) -> bytes: ... + def recv_bytes_into(self, buf: Any, offset: int = 0) -> int: ... + def recv(self) -> _RecvT_co: ... + def poll(self, timeout: float | None = 0.0) -> bool: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None ) -> None: ... + def __del__(self) -> None: ... -class Connection(_ConnectionBase): ... +class Connection(_ConnectionBase[_SendT_contra, _RecvT_co]): ... if sys.platform == "win32": - class PipeConnection(_ConnectionBase): ... + class PipeConnection(_ConnectionBase[_SendT_contra, _RecvT_co]): ... class Listener: def __init__( - self, address: _Address | None = ..., family: str | None = ..., backlog: int = ..., authkey: bytes | None = ... + self, address: _Address | None = None, family: str | None = None, backlog: int = 1, authkey: bytes | None = None ) -> None: ... - def accept(self) -> Connection: ... + if sys.platform != "win32": + def accept(self) -> Connection[Incomplete, Incomplete]: ... + else: + def accept(self) -> Connection[Incomplete, Incomplete] | PipeConnection[Incomplete, Incomplete]: ... + def close(self) -> None: ... + # Any: the concrete type depends on the address family and platform + # (e.g. str or bytes for AF_UNIX), cf. _socket._RetAddress @property - def address(self) -> _Address: ... + def address(self) -> Any: ... @property - def last_accepted(self) -> _Address | None: ... - def __enter__(self: Self) -> Self: ... + def last_accepted(self) -> Any | None: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None ) -> None: ... -def deliver_challenge(connection: Connection, authkey: bytes) -> None: ... -def answer_challenge(connection: Connection, authkey: bytes) -> None: ... +# Any: send and recv methods unused +if sys.version_info >= (3, 12): + def deliver_challenge(connection: _ConnectionBase[Any, Any], authkey: bytes, digest_name: str = "sha256") -> None: ... + +else: + def deliver_challenge(connection: _ConnectionBase[Any, Any], authkey: bytes) -> None: ... + +def answer_challenge(connection: _ConnectionBase[Any, Any], authkey: bytes) -> None: ... def wait( - object_list: Iterable[Connection | socket.socket | int], timeout: float | None = ... -) -> list[Connection | socket.socket | int]: ... -def Client(address: _Address, family: str | None = ..., authkey: bytes | None = ...) -> Connection: ... -def Pipe(duplex: bool = ...) -> tuple[Connection, Connection]: ... + object_list: Iterable[_ConnectionBase[_SendT_contra, _RecvT_co] | socket.socket | int], timeout: float | None = None +) -> list[_ConnectionBase[_SendT_contra, _RecvT_co] | socket.socket | int]: ... + +if sys.platform != "win32": + def Client(address: _Address, family: str | None = None, authkey: bytes | None = None) -> Connection[Any, Any]: ... + +else: + def Client( + address: _Address, family: str | None = None, authkey: bytes | None = None + ) -> Connection[Any, Any] | PipeConnection[Any, Any]: ... + +# N.B. Keep this in sync with multiprocessing.context.BaseContext.Pipe. +# _ConnectionBase is the common base class of Connection and PipeConnection +# and can be used in cross-platform code. +# +# The two connections should have the same generic types but inverted (Connection[_T1, _T2], Connection[_T2, _T1]). +# However, TypeVars scoped entirely within a return annotation is unspecified in the spec. +if sys.platform != "win32": + def Pipe(duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: ... + +else: + def Pipe(duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ... diff --git a/stdlib/multiprocessing/context.pyi b/stdlib/multiprocessing/context.pyi index e65a387819bc..13fd967515d0 100644 --- a/stdlib/multiprocessing/context.pyi +++ b/stdlib/multiprocessing/context.pyi @@ -1,17 +1,25 @@ import ctypes -import multiprocessing import sys +from _ctypes import _CData from collections.abc import Callable, Iterable, Sequence -from ctypes import _CData -from logging import Logger -from multiprocessing import queues, synchronize +from ctypes import _SimpleCData, c_char +from logging import Logger, _Level as _LoggingLevel +from multiprocessing import popen_fork, popen_forkserver, popen_spawn_posix, popen_spawn_win32, queues, synchronize +from multiprocessing.managers import SyncManager from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess -from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase -from typing import Any, Type, TypeVar, Union, overload -from typing_extensions import Literal +from multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString +from typing import Any, ClassVar, Literal, TypeAlias, TypeVar, overload -_LockLike = Union[synchronize.Lock, synchronize.RLock] +if sys.platform != "win32": + from multiprocessing.connection import Connection +else: + from multiprocessing.connection import PipeConnection + +__all__ = () + +_LockLike: TypeAlias = synchronize.Lock | synchronize.RLock +_T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) class ProcessError(Exception): ... @@ -19,106 +27,139 @@ class BufferTooShort(ProcessError): ... class TimeoutError(ProcessError): ... class AuthenticationError(ProcessError): ... -class BaseContext(object): - Process: Type[BaseProcess] - ProcessError: Type[Exception] - BufferTooShort: Type[Exception] - TimeoutError: Type[Exception] - AuthenticationError: Type[Exception] +class BaseContext: + ProcessError: ClassVar[type[ProcessError]] + BufferTooShort: ClassVar[type[BufferTooShort]] + TimeoutError: ClassVar[type[TimeoutError]] + AuthenticationError: ClassVar[type[AuthenticationError]] # N.B. The methods below are applied at runtime to generate # multiprocessing.*, so the signatures should be identical (modulo self). @staticmethod def current_process() -> BaseProcess: ... - if sys.version_info >= (3, 8): - @staticmethod - def parent_process() -> BaseProcess | None: ... + @staticmethod + def parent_process() -> BaseProcess | None: ... @staticmethod def active_children() -> list[BaseProcess]: ... def cpu_count(self) -> int: ... - # TODO: change return to SyncManager once a stub exists in multiprocessing.managers - def Manager(self) -> Any: ... - # TODO: change return to Pipe once a stub exists in multiprocessing.connection - def Pipe(self, duplex: bool = ...) -> Any: ... + def Manager(self) -> SyncManager: ... + + # N.B. Keep this in sync with multiprocessing.connection.Pipe. + # _ConnectionBase is the common base class of Connection and PipeConnection + # and can be used in cross-platform code. + # + # The two connections should have the same generic types but inverted (Connection[_T1, _T2], Connection[_T2, _T1]). + # However, TypeVars scoped entirely within a return annotation is unspecified in the spec. + if sys.platform != "win32": + def Pipe(self, duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: ... + else: + def Pipe(self, duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ... + def Barrier( - self, parties: int, action: Callable[..., Any] | None = ..., timeout: float | None = ... + self, parties: int, action: Callable[..., object] | None = None, timeout: float | None = None ) -> synchronize.Barrier: ... - def BoundedSemaphore(self, value: int = ...) -> synchronize.BoundedSemaphore: ... - def Condition(self, lock: _LockLike | None = ...) -> synchronize.Condition: ... + def BoundedSemaphore(self, value: int = 1) -> synchronize.BoundedSemaphore: ... + def Condition(self, lock: _LockLike | None = None) -> synchronize.Condition: ... def Event(self) -> synchronize.Event: ... def Lock(self) -> synchronize.Lock: ... def RLock(self) -> synchronize.RLock: ... - def Semaphore(self, value: int = ...) -> synchronize.Semaphore: ... - def Queue(self, maxsize: int = ...) -> queues.Queue[Any]: ... - def JoinableQueue(self, maxsize: int = ...) -> queues.JoinableQueue[Any]: ... + def Semaphore(self, value: int = 1) -> synchronize.Semaphore: ... + def Queue(self, maxsize: int = 0) -> queues.Queue[Any]: ... + def JoinableQueue(self, maxsize: int = 0) -> queues.JoinableQueue[Any]: ... def SimpleQueue(self) -> queues.SimpleQueue[Any]: ... def Pool( self, - processes: int | None = ..., - initializer: Callable[..., Any] | None = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: int | None = ..., + processes: int | None = None, + initializer: Callable[..., object] | None = None, + initargs: Iterable[Any] = (), + maxtasksperchild: int | None = None, ) -> _Pool: ... + @overload - def RawValue(self, typecode_or_type: Type[_CT], *args: Any) -> _CT: ... + def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ... + @overload - def RawArray(self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... + def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... + + @overload + def Value( + self, typecode_or_type: type[_SimpleCData[_T]], *args: Any, lock: Literal[True] | _LockLike = True + ) -> Synchronized[_T]: ... + @overload + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> Synchronized[_CT]: ... @overload - def Value(self, typecode_or_type: Type[_CT], *args: Any, lock: Literal[False]) -> _CT: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[_CT]: ... @overload - def Value(self, typecode_or_type: Type[_CT], *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[_CT]: ... + def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[Any]: ... @overload - def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[Any]: ... + def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ... + @overload - def Value(self, typecode_or_type: str | Type[_CData], *args: Any, lock: bool | _LockLike = ...) -> Any: ... + def Array( + self, typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] + ) -> SynchronizedArray[_T]: ... @overload - def Array(self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]) -> _CT: ... + def Array( + self, typecode_or_type: type[c_char], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True + ) -> SynchronizedString: ... @overload def Array( - self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike - ) -> SynchronizedArray[_CT]: ... + self, + typecode_or_type: type[_SimpleCData[_T]], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ) -> SynchronizedArray[_T]: ... @overload def Array( - self, typecode_or_type: str, size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike + self, typecode_or_type: str, size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True ) -> SynchronizedArray[Any]: ... @overload def Array( - self, typecode_or_type: str | Type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ... + self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = True ) -> Any: ... + def freeze_support(self) -> None: ... def get_logger(self) -> Logger: ... - def log_to_stderr(self, level: str | None = ...) -> Logger: ... + def log_to_stderr(self, level: _LoggingLevel | None = None) -> Logger: ... def allow_connection_pickling(self) -> None: ... def set_executable(self, executable: str) -> None: ... - def set_forkserver_preload(self, module_names: list[str]) -> None: ... + if sys.version_info >= (3, 15): + def set_forkserver_preload( + self, module_names: list[str], *, on_error: Literal["ignore", "warn", "fail"] = "ignore" + ) -> None: ... + else: + def set_forkserver_preload(self, module_names: list[str]) -> None: ... + + @overload + def get_context(self, method: None = None) -> DefaultContext: ... + @overload + def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... if sys.platform != "win32": - @overload - def get_context(self, method: None = ...) -> DefaultContext: ... - @overload - def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... @overload def get_context(self, method: Literal["fork"]) -> ForkContext: ... @overload def get_context(self, method: Literal["forkserver"]) -> ForkServerContext: ... - @overload - def get_context(self, method: str) -> BaseContext: ... - else: - @overload - def get_context(self, method: None = ...) -> DefaultContext: ... - @overload - def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... - @overload - def get_context(self, method: str) -> BaseContext: ... - def get_start_method(self, allow_none: bool = ...) -> str: ... - def set_start_method(self, method: str | None, force: bool = ...) -> None: ... + + @overload + def get_context(self, method: str) -> BaseContext: ... + + @overload + def get_start_method(self, allow_none: Literal[False] = False) -> str: ... + @overload + def get_start_method(self, allow_none: bool) -> str | None: ... + + def set_start_method(self, method: str | None, force: bool = False) -> None: ... + @property def reducer(self) -> str: ... @reducer.setter def reducer(self, reduction: str) -> None: ... + def _check_available(self) -> None: ... class Process(BaseProcess): @@ -127,47 +168,53 @@ class Process(BaseProcess): def _Popen(process_obj: BaseProcess) -> DefaultContext: ... class DefaultContext(BaseContext): - Process: Type[multiprocessing.Process] + Process: ClassVar[type[Process]] def __init__(self, context: BaseContext) -> None: ... - def set_start_method(self, method: str | None, force: bool = ...) -> None: ... - def get_start_method(self, allow_none: bool = ...) -> str: ... + def get_start_method(self, allow_none: bool = False) -> str: ... def get_all_start_methods(self) -> list[str]: ... _default_context: DefaultContext +class SpawnProcess(BaseProcess): + _start_method: str + if sys.platform != "win32": + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_spawn_posix.Popen: ... + else: + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_spawn_win32.Popen: ... + +class SpawnContext(BaseContext): + _name: str + Process: ClassVar[type[SpawnProcess]] + if sys.platform != "win32": class ForkProcess(BaseProcess): _start_method: str @staticmethod - def _Popen(process_obj: BaseProcess) -> Any: ... - class SpawnProcess(BaseProcess): - _start_method: str - @staticmethod - def _Popen(process_obj: BaseProcess) -> SpawnProcess: ... + def _Popen(process_obj: BaseProcess) -> popen_fork.Popen: ... + class ForkServerProcess(BaseProcess): _start_method: str @staticmethod - def _Popen(process_obj: BaseProcess) -> Any: ... + def _Popen(process_obj: BaseProcess) -> popen_forkserver.Popen: ... + class ForkContext(BaseContext): _name: str - Process: Type[ForkProcess] - class SpawnContext(BaseContext): - _name: str - Process: Type[SpawnProcess] + Process: ClassVar[type[ForkProcess]] + class ForkServerContext(BaseContext): _name: str - Process: Type[ForkServerProcess] + Process: ClassVar[type[ForkServerProcess]] + +def _force_start_method(method: str) -> None: ... + +if sys.platform != "win32": + def get_spawning_popen() -> popen_forkserver.Popen | popen_spawn_posix.Popen | None: ... + def set_spawning_popen(popen: popen_forkserver.Popen | popen_spawn_posix.Popen | None) -> None: ... else: - class SpawnProcess(BaseProcess): - _start_method: str - @staticmethod - def _Popen(process_obj: BaseProcess) -> Any: ... - class SpawnContext(BaseContext): - _name: str - Process: Type[SpawnProcess] + def get_spawning_popen() -> popen_spawn_win32.Popen | None: ... + def set_spawning_popen(popen: popen_spawn_win32.Popen | None) -> None: ... -def _force_start_method(method: str) -> None: ... -def get_spawning_popen() -> Any | None: ... -def set_spawning_popen(popen: Any) -> None: ... def assert_spawning(obj: Any) -> None: ... diff --git a/stdlib/multiprocessing/dummy/__init__.pyi b/stdlib/multiprocessing/dummy/__init__.pyi index b4d1c8404d8d..b7e64dabfc80 100644 --- a/stdlib/multiprocessing/dummy/__init__.pyi +++ b/stdlib/multiprocessing/dummy/__init__.pyi @@ -1,50 +1,89 @@ import array +import sys import threading import weakref +from collections.abc import Callable, Iterable, Mapping, Sequence from queue import Queue as Queue -from typing import Any, Callable, Iterable, Mapping, Sequence +from threading import ( + Barrier as Barrier, + BoundedSemaphore as BoundedSemaphore, + Condition as Condition, + Event as Event, + Lock as Lock, + RLock as RLock, + Semaphore as Semaphore, +) +from typing import Any, Literal + +from .connection import Pipe as Pipe + +__all__ = [ + "Process", + "current_process", + "active_children", + "freeze_support", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Condition", + "Event", + "Barrier", + "Queue", + "Manager", + "Pipe", + "Pool", + "JoinableQueue", +] JoinableQueue = Queue -Barrier = threading.Barrier -BoundedSemaphore = threading.BoundedSemaphore -Condition = threading.Condition -Event = threading.Event -Lock = threading.Lock -RLock = threading.RLock -Semaphore = threading.Semaphore class DummyProcess(threading.Thread): _children: weakref.WeakKeyDictionary[Any, Any] _parent: threading.Thread _pid: None _start_called: int - exitcode: int | None - def __init__( - self, - group: Any = ..., - target: Callable[..., Any] | None = ..., - name: str | None = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] = ..., - ) -> None: ... + @property + def exitcode(self) -> Literal[0] | None: ... + if sys.version_info >= (3, 14): + # kwargs default changed in Python 3.14.1 + def __init__( + self, + group: Any = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> None: ... + else: + def __init__( + self, + group: Any = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = {}, + ) -> None: ... Process = DummyProcess class Namespace: def __init__(self, **kwds: Any) -> None: ... - def __getattr__(self, __name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... class Value: _typecode: Any _value: Any value: Any - def __init__(self, typecode: Any, value: Any, lock: Any = ...) -> None: ... + def __init__(self, typecode: Any, value: Any, lock: Any = True) -> None: ... -def Array(typecode: Any, sequence: Sequence[Any], lock: Any = ...) -> array.array[Any]: ... +def Array(typecode: Any, sequence: Sequence[Any], lock: Any = True) -> array.array[Any]: ... def Manager() -> Any: ... -def Pool(processes: int | None = ..., initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ...) -> Any: ... +def Pool(processes: int | None = None, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> Any: ... def active_children() -> list[Any]: ... -def current_process() -> threading.Thread: ... + +current_process = threading.current_thread + def freeze_support() -> None: ... def shutdown() -> None: ... diff --git a/stdlib/multiprocessing/dummy/connection.pyi b/stdlib/multiprocessing/dummy/connection.pyi index 4ef3d095911f..d7e982129466 100644 --- a/stdlib/multiprocessing/dummy/connection.pyi +++ b/stdlib/multiprocessing/dummy/connection.pyi @@ -1,38 +1,39 @@ -from _typeshed import Self +from multiprocessing.connection import _Address from queue import Queue from types import TracebackType -from typing import Any, Tuple, Type, Union +from typing import Any +from typing_extensions import Self -families: list[None] +__all__ = ["Client", "Listener", "Pipe"] -_Address = Union[str, Tuple[str, int]] +families: list[None] -class Connection(object): +class Connection: _in: Any _out: Any recv: Any recv_bytes: Any send: Any send_bytes: Any - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def __init__(self, _in: Any, _out: Any) -> None: ... def close(self) -> None: ... - def poll(self, timeout: float = ...) -> bool: ... + def poll(self, timeout: float = 0.0) -> bool: ... -class Listener(object): +class Listener: _backlog_queue: Queue[Any] | None @property def address(self) -> Queue[Any] | None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None ) -> None: ... - def __init__(self, address: _Address | None = ..., family: int | None = ..., backlog: int = ...) -> None: ... + def __init__(self, address: _Address | None = None, family: int | None = None, backlog: int = 1) -> None: ... def accept(self) -> Connection: ... def close(self) -> None: ... def Client(address: _Address) -> Connection: ... -def Pipe(duplex: bool = ...) -> tuple[Connection, Connection]: ... +def Pipe(duplex: bool = True) -> tuple[Connection, Connection]: ... diff --git a/stdlib/multiprocessing/forkserver.pyi b/stdlib/multiprocessing/forkserver.pyi new file mode 100644 index 000000000000..e48be5f07949 --- /dev/null +++ b/stdlib/multiprocessing/forkserver.pyi @@ -0,0 +1,78 @@ +import sys +from _typeshed import FileDescriptorLike, Unused +from collections.abc import Sequence +from struct import Struct +from typing import Any, Final, Literal + +__all__ = ["ensure_running", "get_inherited_fds", "connect_to_new_process", "set_forkserver_preload"] + +MAXFDS_TO_SEND: Final = 256 +SIGNED_STRUCT: Final[Struct] + +class ForkServer: + if sys.version_info >= (3, 15): + def set_forkserver_preload( + self, modules_names: list[str], *, on_error: Literal["ignore", "warn", "fail"] = "ignore" + ) -> None: ... + else: + def set_forkserver_preload(self, modules_names: list[str]) -> None: ... + + def get_inherited_fds(self) -> list[int] | None: ... + def connect_to_new_process(self, fds: Sequence[int]) -> tuple[int, int]: ... + def ensure_running(self) -> None: ... + +if sys.version_info >= (3, 15): + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + authkey_r: int | None = None, + on_error: str = "ignore", + ) -> None: ... + +elif sys.version_info >= (3, 14): + # `sys_argv` parameter added in Python 3.14.3 + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + authkey_r: int | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 13): + # `sys_argv` parameter added in Python 3.13.12 + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + ) -> None: ... + +else: + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: Unused = None, + ) -> None: ... + +def read_signed(fd: int) -> Any: ... +def write_signed(fd: int, n: int) -> None: ... + +_forkserver: ForkServer +ensure_running = _forkserver.ensure_running +get_inherited_fds = _forkserver.get_inherited_fds +connect_to_new_process = _forkserver.connect_to_new_process +set_forkserver_preload = _forkserver.set_forkserver_preload diff --git a/stdlib/multiprocessing/heap.pyi b/stdlib/multiprocessing/heap.pyi new file mode 100644 index 000000000000..bf6f853a9760 --- /dev/null +++ b/stdlib/multiprocessing/heap.pyi @@ -0,0 +1,41 @@ +import sys +from collections.abc import Callable +from mmap import mmap +from multiprocessing import popen_forkserver, popen_spawn_posix, resource_sharer +from typing import Protocol, TypeAlias, type_check_only + +__all__ = ["BufferWrapper"] + +class Arena: + size: int + buffer: mmap + if sys.platform == "win32": + name: str + def __init__(self, size: int) -> None: ... + else: + fd: int + def __init__(self, size: int, fd: int = -1) -> None: ... + +_Block: TypeAlias = tuple[Arena, int, int] + +if sys.platform != "win32": + @type_check_only + class _SupportsDetach(Protocol): + def detach(self) -> int: ... + + def reduce_arena( + a: Arena, + ) -> tuple[ + Callable[[int, _SupportsDetach], Arena], + tuple[int, popen_forkserver._DupFd | popen_spawn_posix._DupFd | resource_sharer.DupFd], + ]: ... + def rebuild_arena(size: int, dupfd: _SupportsDetach) -> Arena: ... + +class Heap: + def __init__(self, size: int = ...) -> None: ... + def free(self, block: _Block) -> None: ... + def malloc(self, size: int) -> _Block: ... + +class BufferWrapper: + def __init__(self, size: int) -> None: ... + def create_memoryview(self) -> memoryview: ... diff --git a/stdlib/multiprocessing/managers.pyi b/stdlib/multiprocessing/managers.pyi index 6d406bc4e4da..0f1d4e87b0dc 100644 --- a/stdlib/multiprocessing/managers.pyi +++ b/stdlib/multiprocessing/managers.pyi @@ -1,58 +1,69 @@ -# NOTE: These are incomplete! - +import builtins import queue import sys import threading -from contextlib import AbstractContextManager -from typing import Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, Tuple, TypeVar +from _typeshed import SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from collections.abc import ( + Callable, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + MutableSet, + Sequence, + Set as AbstractSet, +) +from types import GenericAlias, TracebackType +from typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self -from .connection import Connection +from . import pool +from .connection import Connection, _Address from .context import BaseContext +from .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory +from .util import Finalize as _Finalize -if sys.version_info >= (3, 8): - from .shared_memory import _SLT, ShareableList, SharedMemory - - _SharedMemory = SharedMemory - _ShareableList = ShareableList - -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") +_S = TypeVar("_S") class Namespace: def __init__(self, **kwds: Any) -> None: ... - def __getattr__(self, __name: str) -> Any: ... - def __setattr__(self, __name: str, __value: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... -_Namespace = Namespace +_Namespace: TypeAlias = Namespace -class Token(object): +class Token: + __slots__ = ("typeid", "address", "id") typeid: str | bytes | None - address: tuple[str | bytes, int] + address: _Address | None id: str | bytes | int | None - def __init__(self, typeid: bytes | str | None, address: tuple[str | bytes, int], id: str | bytes | int | None) -> None: ... - def __repr__(self) -> str: ... + def __init__(self, typeid: bytes | str | None, address: _Address | None, id: str | bytes | int | None) -> None: ... def __getstate__(self) -> tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]: ... def __setstate__(self, state: tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]) -> None: ... -class BaseProxy(object): - _address_to_local: dict[Any, Any] +class BaseProxy: + _address_to_local: dict[_Address, Any] _mutex: Any def __init__( self, token: Any, serializer: str, - manager: Any = ..., - authkey: AnyStr | None = ..., - exposed: Any = ..., - incref: bool = ..., - manager_owned: bool = ..., + manager: Any = None, + authkey: AnyStr | None = None, + exposed: Any = None, + incref: bool = True, + manager_owned: bool = False, ) -> None: ... def __deepcopy__(self, memo: Any | None) -> Any: ... - def _callmethod(self, methodname: str, args: Tuple[Any, ...] = ..., kwds: dict[Any, Any] = ...) -> None: ... + def _callmethod(self, methodname: str, args: tuple[Any, ...] = (), kwds: dict[Any, Any] = {}) -> None: ... def _getvalue(self) -> Any: ... def __reduce__(self) -> tuple[Any, tuple[Any, Any, str, dict[Any, Any]]]: ... @@ -60,63 +71,320 @@ class ValueProxy(BaseProxy, Generic[_T]): def get(self) -> _T: ... def set(self, value: _T) -> None: ... value: _T - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 13): + class _BaseDictProxy(BaseProxy, MutableMapping[_KT, _VT]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> dict[_KT, _VT]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> list[_KT]: ... # type: ignore[override] + def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> list[_VT]: ... # type: ignore[override] + if sys.version_info >= (3, 14): + # Next methods are copied from builtins.dict + @overload + def fromkeys(self, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ... + @overload + def fromkeys(self, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... + + def __reversed__(self) -> Iterator[_KT]: ... + + @overload + def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[misc] + def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... + @overload + def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... + + class DictProxy(_BaseDictProxy[_KT, _VT]): + def __class_getitem__(cls, args: Any, /) -> GenericAlias: ... + +else: + class DictProxy(BaseProxy, MutableMapping[_KT, _VT]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> dict[_KT, _VT]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> list[_KT]: ... # type: ignore[override] + def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> list[_VT]: ... # type: ignore[override] + +if sys.version_info >= (3, 14): + class _BaseSetProxy(BaseProxy, MutableSet[_T]): + __builtins__: ClassVar[dict[str, Any]] + # Copied from builtins.set + def add(self, element: _T, /) -> None: ... + def copy(self) -> set[_T]: ... + def clear(self) -> None: ... + def difference(self, *s: Iterable[Any]) -> set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T, /) -> None: ... + def intersection(self, *s: Iterable[Any]) -> set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any], /) -> bool: ... + def issubset(self, s: Iterable[Any], /) -> bool: ... + def issuperset(self, s: Iterable[Any], /) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T, /) -> None: ... + def symmetric_difference(self, s: Iterable[_T], /) -> set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ... + def union(self, *s: Iterable[_S]) -> set[_T | _S]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object, /) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __iand__(self, value: AbstractSet[object], /) -> Self: ... + def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __sub__(self, value: AbstractSet[_T | None], /) -> set[_T]: ... + def __isub__(self, value: AbstractSet[object], /) -> Self: ... + def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __rand__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __ror__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... # type: ignore[misc] + def __rsub__(self, value: AbstractSet[_T], /) -> set[_T]: ... + def __rxor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... # type: ignore[misc] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + class SetProxy(_BaseSetProxy[_T]): ... + +class BaseListProxy(BaseProxy, MutableSequence[_T]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __add__(self, x: list[_T], /) -> list[_T]: ... + def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + + @overload + def __getitem__(self, i: SupportsIndex, /) -> _T: ... + @overload + def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ... + + @overload + def __setitem__(self, i: SupportsIndex, o: _T, /) -> None: ... + @overload + def __setitem__(self, s: slice[SupportsIndex | None], o: Iterable[_T], /) -> None: ... + + def __mul__(self, n: SupportsIndex, /) -> list[_T]: ... + def __rmul__(self, n: SupportsIndex, /) -> list[_T]: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __reversed__(self) -> Iterator[_T]: ... + def append(self, object: _T, /) -> None: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def pop(self, index: SupportsIndex = ..., /) -> _T: ... + def index(self, value: _T, start: SupportsIndex = ..., stop: SupportsIndex = ..., /) -> int: ... + def count(self, value: _T, /) -> int: ... + def insert(self, index: SupportsIndex, object: _T, /) -> None: ... + def remove(self, value: _T, /) -> None: ... + if sys.version_info >= (3, 14): + # Next methods are copied from builtins.list + def clear(self) -> None: ... + def copy(self) -> list[_T]: ... + + # Use BaseListProxy[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] + # to work around invariance + @overload + def sort(self: BaseListProxy[SupportsRichComparisonT], *, key: None = None, reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... + +class ListProxy(BaseListProxy[_T]): + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[override] + def __imul__(self, value: SupportsIndex, /) -> Self: ... # type: ignore[override] + if sys.version_info >= (3, 13): + def __class_getitem__(cls, args: Any, /) -> Any: ... + +# Send is (kind, result) +# Receive is (id, methodname, args, kwds) +_ServerConnection: TypeAlias = Connection[tuple[str, Any], tuple[str, str, Iterable[Any], Mapping[str, Any]]] # Returned by BaseManager.get_server() class Server: - address: Any + address: _Address | None + id_to_obj: dict[str, tuple[Any, set[str], dict[str, str]]] + fallback_mapping: dict[str, Callable[[_ServerConnection, str, Any], Any]] + public: list[str] + # Registry values are (callable, exposed, method_to_typeid, proxytype) def __init__( - self, registry: dict[str, tuple[Callable[..., Any], Any, Any, Any]], address: Any, authkey: bytes, serializer: str + self, + registry: dict[str, tuple[Callable[..., Any], Iterable[str], dict[str, str], Any]], + address: _Address | None, + authkey: bytes, + serializer: str, ) -> None: ... def serve_forever(self) -> None: ... - def accept_connection(self, c: Connection, name: str) -> None: ... + def accepter(self) -> None: ... + def handle_request(self, conn: _ServerConnection) -> None: ... + def serve_client(self, conn: _ServerConnection) -> None: ... + def fallback_getvalue(self, conn: _ServerConnection, ident: str, obj: _T) -> _T: ... + def fallback_str(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... + def fallback_repr(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... + def dummy(self, c: _ServerConnection) -> None: ... + def debug_info(self, c: _ServerConnection) -> str: ... + def number_of_objects(self, c: _ServerConnection) -> int: ... + def shutdown(self, c: _ServerConnection) -> None: ... + def create(self, c: _ServerConnection, typeid: str, /, *args: Any, **kwds: Any) -> tuple[str, tuple[str, ...]]: ... + def get_methods(self, c: _ServerConnection, token: Token) -> set[str]: ... + def accept_connection(self, c: _ServerConnection, name: str) -> None: ... + def incref(self, c: _ServerConnection, ident: str) -> None: ... + def decref(self, c: _ServerConnection, ident: str) -> None: ... + +class BaseManager: + if sys.version_info >= (3, 11): + def __init__( + self, + address: _Address | None = None, + authkey: bytes | None = None, + serializer: str = "pickle", + ctx: BaseContext | None = None, + *, + shutdown_timeout: float = 1.0, + ) -> None: ... + else: + def __init__( + self, + address: _Address | None = None, + authkey: bytes | None = None, + serializer: str = "pickle", + ctx: BaseContext | None = None, + ) -> None: ... -class BaseManager(AbstractContextManager[BaseManager]): - def __init__( - self, address: Any | None = ..., authkey: bytes | None = ..., serializer: str = ..., ctx: BaseContext | None = ... - ) -> None: ... def get_server(self) -> Server: ... def connect(self) -> None: ... - def start(self, initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ...) -> None: ... - def shutdown(self) -> None: ... # only available after start() was called - def join(self, timeout: float | None = ...) -> None: ... # undocumented + def start(self, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> None: ... + shutdown: _Finalize # only available after start() was called + def join(self, timeout: float | None = None) -> None: ... # undocumented @property - def address(self) -> Any: ... + def address(self) -> _Address | None: ... @classmethod def register( cls, typeid: str, - callable: Callable[..., Any] | None = ..., - proxytype: Any = ..., - exposed: Sequence[str] | None = ..., - method_to_typeid: Mapping[str, str] | None = ..., - create_method: bool = ..., + callable: Callable[..., object] | None = None, + proxytype: Any = None, + exposed: Sequence[str] | None = None, + method_to_typeid: Mapping[str, str] | None = None, + create_method: bool = True, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... -# Conflicts with method names -_dict = dict -_list = list - -class SyncManager(BaseManager, AbstractContextManager[SyncManager]): - def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... - def Condition(self, lock: Any = ...) -> threading.Condition: ... +class SyncManager(BaseManager): + def Barrier( + self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None + ) -> threading.Barrier: ... + def BoundedSemaphore(self, value: int = 1) -> threading.BoundedSemaphore: ... + def Condition(self, lock: threading.Lock | threading._RLock | None = None) -> threading.Condition: ... def Event(self) -> threading.Event: ... def Lock(self) -> threading.Lock: ... def Namespace(self) -> _Namespace: ... + def Pool( + self, + processes: int | None = None, + initializer: Callable[..., object] | None = None, + initargs: Iterable[Any] = (), + maxtasksperchild: int | None = None, + context: Any | None = None, + ) -> pool.Pool: ... def Queue(self, maxsize: int = ...) -> queue.Queue[Any]: ... + def JoinableQueue(self, maxsize: int = ...) -> queue.Queue[Any]: ... def RLock(self) -> threading.RLock: ... - def Semaphore(self, value: Any = ...) -> threading.Semaphore: ... + def Semaphore(self, value: int = 1) -> threading.Semaphore: ... def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ... def Value(self, typecode: Any, value: _T) -> ValueProxy[_T]: ... - def dict(self, sequence: Mapping[_KT, _VT] = ...) -> _dict[_KT, _VT]: ... - def list(self, sequence: Sequence[_T] = ...) -> _list[_T]: ... + + # Overloads are copied from builtins.dict.__init__ + @overload + def dict(self) -> DictProxy[Any, Any]: ... + @overload + def dict(self, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, iterable: Iterable[tuple[_KT, _VT]], /) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, iterable: Iterable[builtins.list[str]], /) -> DictProxy[str, str]: ... + @overload + def dict(self, iterable: Iterable[builtins.list[bytes]], /) -> DictProxy[bytes, bytes]: ... + + # Overloads are copied from builtins.list.__init__ + @overload + def list(self, iterable: Iterable[_T], /) -> ListProxy[_T]: ... + @overload + def list(self) -> ListProxy[Any]: ... + + if sys.version_info >= (3, 14): + @overload + def set(self, iterable: Iterable[_T], /) -> SetProxy[_T]: ... + @overload + def set(self) -> SetProxy[Any]: ... class RemoteError(Exception): ... -if sys.version_info >= (3, 8): - class SharedMemoryServer(Server): ... - class SharedMemoryManager(BaseManager): - def get_server(self) -> SharedMemoryServer: ... - def SharedMemory(self, size: int) -> _SharedMemory: ... - def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: ... +class SharedMemoryServer(Server): + def track_segment(self, c: _ServerConnection, segment_name: str) -> None: ... + def release_segment(self, c: _ServerConnection, segment_name: str) -> None: ... + def list_segments(self, c: _ServerConnection) -> list[str]: ... + +class SharedMemoryManager(BaseManager): + def get_server(self) -> SharedMemoryServer: ... + def SharedMemory(self, size: int) -> _SharedMemory: ... + def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: ... + def __del__(self) -> None: ... diff --git a/stdlib/multiprocessing/pool.pyi b/stdlib/multiprocessing/pool.pyi index 40fb8ef170ab..5642e50d0e76 100644 --- a/stdlib/multiprocessing/pool.pyi +++ b/stdlib/multiprocessing/pool.pyi @@ -1,125 +1,101 @@ -import sys -from _typeshed import Self -from contextlib import AbstractContextManager -from typing import Any, Callable, Generic, Iterable, Iterator, List, Mapping, TypeVar +from collections.abc import Callable, Iterable, Mapping +from multiprocessing.context import DefaultContext, Process as _Process +from types import GenericAlias, TracebackType +from typing import Any, Final, Generic, TypeVar +from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["Pool", "ThreadPool"] -_PT = TypeVar("_PT", bound=Pool) _S = TypeVar("_S") _T = TypeVar("_T") class ApplyResult(Generic[_T]): - if sys.version_info >= (3, 8): - def __init__( - self, pool: Pool, callback: Callable[[_T], None] | None, error_callback: Callable[[BaseException], None] | None - ) -> None: ... - else: - def __init__( - self, - cache: dict[int, ApplyResult[Any]], - callback: Callable[[_T], None] | None, - error_callback: Callable[[BaseException], None] | None, - ) -> None: ... - def get(self, timeout: float | None = ...) -> _T: ... - def wait(self, timeout: float | None = ...) -> None: ... + def __init__( + self, pool: Pool, callback: Callable[[_T], object] | None, error_callback: Callable[[BaseException], object] | None + ) -> None: ... + def get(self, timeout: float | None = None) -> _T: ... + def wait(self, timeout: float | None = None) -> None: ... def ready(self) -> bool: ... def successful(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # alias created during issue #17805 AsyncResult = ApplyResult -class MapResult(ApplyResult[List[_T]]): - if sys.version_info >= (3, 8): - def __init__( - self, - pool: Pool, - chunksize: int, - length: int, - callback: Callable[[list[_T]], None] | None, - error_callback: Callable[[BaseException], None] | None, - ) -> None: ... - else: - def __init__( - self, - cache: dict[int, ApplyResult[Any]], - chunksize: int, - length: int, - callback: Callable[[list[_T]], None] | None, - error_callback: Callable[[BaseException], None] | None, - ) -> None: ... +class MapResult(ApplyResult[list[_T]]): + def __init__( + self, + pool: Pool, + chunksize: int, + length: int, + callback: Callable[[list[_T]], object] | None, + error_callback: Callable[[BaseException], object] | None, + ) -> None: ... -class IMapIterator(Iterator[_T]): - if sys.version_info >= (3, 8): - def __init__(self, pool: Pool) -> None: ... - else: - def __init__(self, cache: dict[int, IMapIterator[Any]]) -> None: ... - def __iter__(self: _S) -> _S: ... - def next(self, timeout: float | None = ...) -> _T: ... - def __next__(self, timeout: float | None = ...) -> _T: ... +class IMapIterator(Generic[_T]): + def __init__(self, pool: Pool) -> None: ... + def __iter__(self) -> Self: ... + def next(self, timeout: float | None = None) -> _T: ... + def __next__(self, timeout: float | None = None) -> _T: ... class IMapUnorderedIterator(IMapIterator[_T]): ... -class Pool(AbstractContextManager[Pool]): +class Pool: def __init__( self, - processes: int | None = ..., - initializer: Callable[..., None] | None = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: int | None = ..., - context: Any | None = ..., + processes: int | None = None, + initializer: Callable[..., object] | None = None, + initargs: Iterable[Any] = (), + maxtasksperchild: int | None = None, + context: Any | None = None, ) -> None: ... - def apply(self, func: Callable[..., _T], args: Iterable[Any] = ..., kwds: Mapping[str, Any] = ...) -> _T: ... + @staticmethod + def Process(ctx: DefaultContext, *args: Any, **kwds: Any) -> _Process: ... + def apply(self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Mapping[str, Any] = {}) -> _T: ... def apply_async( self, func: Callable[..., _T], - args: Iterable[Any] = ..., - kwds: Mapping[str, Any] = ..., - callback: Callable[[_T], None] | None = ..., - error_callback: Callable[[BaseException], None] | None = ..., + args: Iterable[Any] = (), + kwds: Mapping[str, Any] = {}, + callback: Callable[[_T], object] | None = None, + error_callback: Callable[[BaseException], object] | None = None, ) -> AsyncResult[_T]: ... - def map(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = ...) -> list[_T]: ... + def map(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = None) -> list[_T]: ... def map_async( self, func: Callable[[_S], _T], iterable: Iterable[_S], - chunksize: int | None = ..., - callback: Callable[[_T], None] | None = ..., - error_callback: Callable[[BaseException], None] | None = ..., + chunksize: int | None = None, + callback: Callable[[list[_T]], object] | None = None, + error_callback: Callable[[BaseException], object] | None = None, ) -> MapResult[_T]: ... - def imap(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = ...) -> IMapIterator[_T]: ... - def imap_unordered( - self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = ... - ) -> IMapIterator[_T]: ... - def starmap(self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], chunksize: int | None = ...) -> list[_T]: ... + def imap(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: ... + def imap_unordered(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: ... + def starmap(self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], chunksize: int | None = None) -> list[_T]: ... def starmap_async( self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], - chunksize: int | None = ..., - callback: Callable[[_T], None] | None = ..., - error_callback: Callable[[BaseException], None] | None = ..., + chunksize: int | None = None, + callback: Callable[[list[_T]], object] | None = None, + error_callback: Callable[[BaseException], object] | None = None, ) -> AsyncResult[list[_T]]: ... def close(self) -> None: ... def terminate(self) -> None: ... def join(self) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... -class ThreadPool(Pool, AbstractContextManager[ThreadPool]): +class ThreadPool(Pool): def __init__( - self, processes: int | None = ..., initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ... + self, processes: int | None = None, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = () ) -> None: ... # undocumented -if sys.version_info >= (3, 8): - INIT: str - RUN: str - CLOSE: str - TERMINATE: str -else: - RUN: int - CLOSE: int - TERMINATE: int +INIT: Final = "INIT" +RUN: Final = "RUN" +CLOSE: Final = "CLOSE" +TERMINATE: Final = "TERMINATE" diff --git a/stdlib/multiprocessing/popen_fork.pyi b/stdlib/multiprocessing/popen_fork.pyi new file mode 100644 index 000000000000..5e53b055cc79 --- /dev/null +++ b/stdlib/multiprocessing/popen_fork.pyi @@ -0,0 +1,26 @@ +import sys +from typing import ClassVar + +from .process import BaseProcess +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class Popen: + finalizer: Finalize | None + method: ClassVar[str] + pid: int + returncode: int | None + sentinel: int # doesn't exist if os.fork in _launch returns 0 + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, fd: int) -> int: ... + def poll(self, flag: int = 1) -> int | None: ... + def wait(self, timeout: float | None = None) -> int | None: ... + if sys.version_info >= (3, 14): + def interrupt(self) -> None: ... + + def terminate(self) -> None: ... + def kill(self) -> None: ... + def close(self) -> None: ... diff --git a/stdlib/multiprocessing/popen_forkserver.pyi b/stdlib/multiprocessing/popen_forkserver.pyi new file mode 100644 index 000000000000..f7d53bbb3e41 --- /dev/null +++ b/stdlib/multiprocessing/popen_forkserver.pyi @@ -0,0 +1,16 @@ +import sys +from typing import ClassVar + +from . import popen_fork +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class _DupFd: + def __init__(self, ind: int) -> None: ... + def detach(self) -> int: ... + + class Popen(popen_fork.Popen): + DupFd: ClassVar[type[_DupFd]] + finalizer: Finalize diff --git a/stdlib/multiprocessing/popen_spawn_posix.pyi b/stdlib/multiprocessing/popen_spawn_posix.pyi new file mode 100644 index 000000000000..7e81d39600ad --- /dev/null +++ b/stdlib/multiprocessing/popen_spawn_posix.pyi @@ -0,0 +1,20 @@ +import sys +from typing import ClassVar + +from . import popen_fork +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class _DupFd: + fd: int + + def __init__(self, fd: int) -> None: ... + def detach(self) -> int: ... + + class Popen(popen_fork.Popen): + DupFd: ClassVar[type[_DupFd]] + finalizer: Finalize + pid: int # may not exist if _launch raises in second try / except + sentinel: int # may not exist if _launch raises in second try / except diff --git a/stdlib/multiprocessing/popen_spawn_win32.pyi b/stdlib/multiprocessing/popen_spawn_win32.pyi new file mode 100644 index 000000000000..481b9eec5a37 --- /dev/null +++ b/stdlib/multiprocessing/popen_spawn_win32.pyi @@ -0,0 +1,30 @@ +import sys +from multiprocessing.process import BaseProcess +from typing import ClassVar, Final + +from .util import Finalize + +if sys.platform == "win32": + __all__ = ["Popen"] + + TERMINATE: Final[int] + WINEXE: Final[bool] + WINSERVICE: Final[bool] + WINENV: Final[bool] + + class Popen: + finalizer: Finalize + method: ClassVar[str] + pid: int + returncode: int | None + sentinel: int + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, handle: int) -> int: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def poll(self) -> int | None: ... + def terminate(self) -> None: ... + + kill = terminate + + def close(self) -> None: ... diff --git a/stdlib/multiprocessing/process.pyi b/stdlib/multiprocessing/process.pyi index 32c22d19f6e5..1975da301ed0 100644 --- a/stdlib/multiprocessing/process.pyi +++ b/stdlib/multiprocessing/process.pyi @@ -1,28 +1,47 @@ import sys -from typing import Any, Callable, Mapping, Tuple +from collections.abc import Callable, Iterable, Mapping +from typing import Any + +__all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] class BaseProcess: name: str daemon: bool authkey: bytes - _identity: Tuple[int, ...] # undocumented - def __init__( - self, - group: None = ..., - target: Callable[..., Any] | None = ..., - name: str | None = ..., - args: Tuple[Any, ...] = ..., - kwargs: Mapping[str, Any] = ..., - *, - daemon: bool | None = ..., - ) -> None: ... + _identity: tuple[int, ...] # undocumented + if sys.version_info >= (3, 14): + # kwargs default changed in Python 3.14.1 + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + *, + daemon: bool | None = None, + ) -> None: ... + else: + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] = {}, + *, + daemon: bool | None = None, + ) -> None: ... + def run(self) -> None: ... def start(self) -> None: ... + if sys.version_info >= (3, 14): + def interrupt(self) -> None: ... + def terminate(self) -> None: ... - if sys.version_info >= (3, 7): - def kill(self) -> None: ... - def close(self) -> None: ... - def join(self, timeout: float | None = ...) -> None: ... + def kill(self) -> None: ... + def close(self) -> None: ... + def join(self, timeout: float | None = None) -> None: ... def is_alive(self) -> bool: ... @property def exitcode(self) -> int | None: ... @@ -35,6 +54,4 @@ class BaseProcess: def current_process() -> BaseProcess: ... def active_children() -> list[BaseProcess]: ... - -if sys.version_info >= (3, 8): - def parent_process() -> BaseProcess | None: ... +def parent_process() -> BaseProcess | None: ... diff --git a/stdlib/multiprocessing/queues.pyi b/stdlib/multiprocessing/queues.pyi index 1c9d76917292..8f0feb834619 100644 --- a/stdlib/multiprocessing/queues.pyi +++ b/stdlib/multiprocessing/queues.pyi @@ -1,37 +1,46 @@ -import queue import sys -from typing import Any, Generic, TypeVar +from types import GenericAlias +from typing import Any, Generic, NewType, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["Queue", "SimpleQueue", "JoinableQueue"] _T = TypeVar("_T") -class Queue(queue.Queue[_T]): +_QueueState = NewType("_QueueState", object) +_JoinableQueueState = NewType("_JoinableQueueState", object) +_SimpleQueueState = NewType("_SimpleQueueState", object) + +class Queue(Generic[_T]): # FIXME: `ctx` is a circular dependency and it's not actually optional. # It's marked as such to be able to use the generic Queue in __init__.pyi. - def __init__(self, maxsize: int = ..., *, ctx: Any = ...) -> None: ... - def get(self, block: bool = ..., timeout: float | None = ...) -> _T: ... - def put(self, obj: _T, block: bool = ..., timeout: float | None = ...) -> None: ... + def __init__(self, maxsize: int = 0, *, ctx: Any = ...) -> None: ... + def __getstate__(self) -> _QueueState: ... + def __setstate__(self, state: _QueueState) -> None: ... + def put(self, obj: _T, block: bool = True, timeout: float | None = None) -> None: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... def qsize(self) -> int: ... def empty(self) -> bool: ... def full(self) -> bool: ... - def put_nowait(self, item: _T) -> None: ... def get_nowait(self) -> _T: ... + def put_nowait(self, obj: _T) -> None: ... def close(self) -> None: ... def join_thread(self) -> None: ... def cancel_join_thread(self) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class JoinableQueue(Queue[_T]): + def __getstate__(self) -> _JoinableQueueState: ... # type: ignore[override] + def __setstate__(self, state: _JoinableQueueState) -> None: ... # type: ignore[override] def task_done(self) -> None: ... def join(self) -> None: ... class SimpleQueue(Generic[_T]): def __init__(self, *, ctx: Any = ...) -> None: ... - if sys.version_info >= (3, 9): - def close(self) -> None: ... + def close(self) -> None: ... def empty(self) -> bool: ... + def __getstate__(self) -> _SimpleQueueState: ... + def __setstate__(self, state: _SimpleQueueState) -> None: ... def get(self) -> _T: ... - def put(self, item: _T) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def put(self, obj: _T) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/multiprocessing/reduction.pyi b/stdlib/multiprocessing/reduction.pyi new file mode 100644 index 000000000000..476cf9b26f71 --- /dev/null +++ b/stdlib/multiprocessing/reduction.pyi @@ -0,0 +1,95 @@ +import pickle +import sys +from _pickle import _BufferCallback, _ReducedType +from _typeshed import HasFileno, SupportsWrite, Unused +from abc import ABCMeta +from builtins import type as Type # alias to avoid name clash +from collections.abc import Callable +from copyreg import _DispatchTableType +from multiprocessing import connection, popen_forkserver, popen_spawn_posix, resource_sharer +from socket import socket +from typing import Any, Final + +if sys.platform == "win32": + __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupHandle", "duplicate", "steal_handle"] +else: + __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupFd", "sendfds", "recvfds"] + +HAVE_SEND_HANDLE: Final[bool] + +class ForkingPickler(pickle.Pickler): + dispatch_table: _DispatchTableType + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = None, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, + /, + ) -> None: ... + @classmethod + def register(cls, type: Type, reduce: Callable[[Any], _ReducedType]) -> None: ... + @classmethod + def dumps(cls, obj: Any, protocol: int | None = None) -> memoryview: ... + loads = pickle.loads + +register = ForkingPickler.register + +def dump(obj: Any, file: SupportsWrite[bytes], protocol: int | None = None) -> None: ... + +if sys.platform == "win32": + def duplicate( + handle: int, target_process: int | None = None, inheritable: bool = False, *, source_process: int | None = None + ) -> int: ... + def steal_handle(source_pid: int, handle: int) -> int: ... + def send_handle(conn: connection.PipeConnection[DupHandle, Any], handle: int, destination_pid: int) -> None: ... + def recv_handle(conn: connection.PipeConnection[Any, DupHandle]) -> int: ... + + class DupHandle: + def __init__(self, handle: int, access: int, pid: int | None = None) -> None: ... + def detach(self) -> int: ... + +else: + if sys.version_info < (3, 14): + ACKNOWLEDGE: Final[bool] + + def recvfds(sock: socket, size: int) -> list[int]: ... + def send_handle(conn: HasFileno, handle: int, destination_pid: Unused) -> None: ... + def recv_handle(conn: HasFileno) -> int: ... + def sendfds(sock: socket, fds: list[int]) -> None: ... + def DupFd(fd: int) -> popen_forkserver._DupFd | popen_spawn_posix._DupFd | resource_sharer.DupFd: ... + +# These aliases are to work around pyright complaints. +# Pyright doesn't like it when a class object is defined as an alias +# of a global object with the same name. +_ForkingPickler = ForkingPickler +_register = register +_dump = dump +_send_handle = send_handle +_recv_handle = recv_handle + +if sys.platform == "win32": + _steal_handle = steal_handle + _duplicate = duplicate + _DupHandle = DupHandle +else: + _sendfds = sendfds + _recvfds = recvfds + _DupFd = DupFd + +class AbstractReducer(metaclass=ABCMeta): + ForkingPickler = _ForkingPickler + register = _register + dump = _dump + send_handle = _send_handle + recv_handle = _recv_handle + if sys.platform == "win32": + steal_handle = _steal_handle + duplicate = _duplicate + DupHandle = _DupHandle + else: + sendfds = _sendfds + recvfds = _recvfds + DupFd = _DupFd + + def __init__(self, *args: Unused) -> None: ... diff --git a/stdlib/multiprocessing/resource_sharer.pyi b/stdlib/multiprocessing/resource_sharer.pyi new file mode 100644 index 000000000000..5fee7cf31e17 --- /dev/null +++ b/stdlib/multiprocessing/resource_sharer.pyi @@ -0,0 +1,20 @@ +import sys +from socket import socket + +__all__ = ["stop"] + +if sys.platform == "win32": + __all__ += ["DupSocket"] + + class DupSocket: + def __init__(self, sock: socket) -> None: ... + def detach(self) -> socket: ... + +else: + __all__ += ["DupFd"] + + class DupFd: + def __init__(self, fd: int) -> None: ... + def detach(self) -> int: ... + +def stop(timeout: float | None = None) -> None: ... diff --git a/stdlib/multiprocessing/resource_tracker.pyi b/stdlib/multiprocessing/resource_tracker.pyi new file mode 100644 index 000000000000..cb2f27a62861 --- /dev/null +++ b/stdlib/multiprocessing/resource_tracker.pyi @@ -0,0 +1,21 @@ +import sys +from _typeshed import FileDescriptorOrPath +from collections.abc import Sized + +__all__ = ["ensure_running", "register", "unregister"] + +class ResourceTracker: + def getfd(self) -> int | None: ... + def ensure_running(self) -> None: ... + def register(self, name: Sized, rtype: str) -> None: ... + def unregister(self, name: Sized, rtype: str) -> None: ... + if sys.version_info >= (3, 12): + def __del__(self) -> None: ... + +_resource_tracker: ResourceTracker +ensure_running = _resource_tracker.ensure_running +register = _resource_tracker.register +unregister = _resource_tracker.unregister +getfd = _resource_tracker.getfd + +def main(fd: FileDescriptorOrPath) -> None: ... diff --git a/stdlib/multiprocessing/shared_memory.pyi b/stdlib/multiprocessing/shared_memory.pyi index 6ffc2542087a..90777a4e771b 100644 --- a/stdlib/multiprocessing/shared_memory.pyi +++ b/stdlib/multiprocessing/shared_memory.pyi @@ -1,33 +1,43 @@ import sys -from typing import Any, Generic, Iterable, Tuple, TypeVar +from collections.abc import Iterable +from types import GenericAlias +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["SharedMemory", "ShareableList"] -_S = TypeVar("_S") _SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) -if sys.version_info >= (3, 8): - class SharedMemory: - def __init__(self, name: str | None = ..., create: bool = ..., size: int = ...) -> None: ... - @property - def buf(self) -> memoryview: ... - @property - def name(self) -> str: ... - @property - def size(self) -> int: ... - def close(self) -> None: ... - def unlink(self) -> None: ... - class ShareableList(Generic[_SLT]): - shm: SharedMemory - def __init__(self, sequence: Iterable[_SLT] | None = ..., *, name: str | None = ...) -> None: ... - def __getitem__(self, position: int) -> _SLT: ... - def __setitem__(self, position: int, value: _SLT) -> None: ... - def __reduce__(self: _S) -> tuple[_S, Tuple[_SLT, ...]]: ... - def __len__(self) -> int: ... - @property - def format(self) -> str: ... - def count(self, value: _SLT) -> int: ... - def index(self, value: _SLT) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... +class SharedMemory: + if sys.version_info >= (3, 13): + def __init__(self, name: str | None = None, create: bool = False, size: int = 0, *, track: bool = True) -> None: ... + else: + def __init__(self, name: str | None = None, create: bool = False, size: int = 0) -> None: ... + + @property + def buf(self) -> memoryview | None: ... + @property + def name(self) -> str: ... + @property + def size(self) -> int: ... + def close(self) -> None: ... + def unlink(self) -> None: ... + def __del__(self) -> None: ... + +class ShareableList(Generic[_SLT]): + shm: SharedMemory + + @overload + def __init__(self, sequence: None = None, *, name: str | None = None) -> None: ... + @overload + def __init__(self, sequence: Iterable[_SLT], *, name: str | None = None) -> None: ... + + def __getitem__(self, position: int) -> _SLT: ... + def __setitem__(self, position: int, value: _SLT) -> None: ... + def __reduce__(self) -> tuple[Self, tuple[_SLT, ...]]: ... + def __len__(self) -> int: ... + @property + def format(self) -> str: ... + def count(self, value: _SLT) -> int: ... + def index(self, value: _SLT) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/multiprocessing/sharedctypes.pyi b/stdlib/multiprocessing/sharedctypes.pyi index bd9d8f089875..693fd2f70139 100644 --- a/stdlib/multiprocessing/sharedctypes.pyi +++ b/stdlib/multiprocessing/sharedctypes.pyi @@ -1,97 +1,140 @@ import ctypes +from _ctypes import _CData from collections.abc import Callable, Iterable, Sequence -from ctypes import _CData, _SimpleCData, c_char +from ctypes import _SimpleCData, c_char from multiprocessing.context import BaseContext from multiprocessing.synchronize import _LockLike -from typing import Any, Generic, Protocol, Type, TypeVar, overload -from typing_extensions import Literal +from types import TracebackType +from typing import Any, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only + +__all__ = ["RawValue", "RawArray", "Value", "Array", "copy", "synchronized"] _T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) @overload -def RawValue(typecode_or_type: Type[_CT], *args: Any) -> _CT: ... +def RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(typecode_or_type: str, *args: Any) -> Any: ... + @overload -def RawArray(typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... +def RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... + @overload -def Value(typecode_or_type: Type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = ...) -> _CT: ... +def Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = None) -> _CT: ... @overload def Value( - typecode_or_type: Type[_CT], *args: Any, lock: Literal[True] | _LockLike, ctx: BaseContext | None = ... + typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None ) -> SynchronizedBase[_CT]: ... @overload def Value( - typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike, ctx: BaseContext | None = ... + typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None ) -> SynchronizedBase[Any]: ... @overload def Value( - typecode_or_type: str | Type[_CData], *args: Any, lock: bool | _LockLike = ..., ctx: BaseContext | None = ... + typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True, ctx: BaseContext | None = None ) -> Any: ... + @overload def Array( - typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = ... + typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = None ) -> _CT: ... @overload def Array( - typecode_or_type: Type[_CT], + typecode_or_type: type[c_char], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, +) -> SynchronizedString: ... +@overload +def Array( + typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, - lock: Literal[True] | _LockLike, - ctx: BaseContext | None = ..., -) -> SynchronizedArray[_CT]: ... + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, +) -> SynchronizedArray[_T]: ... @overload def Array( typecode_or_type: str, size_or_initializer: int | Sequence[Any], *, - lock: Literal[True] | _LockLike, - ctx: BaseContext | None = ..., + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, ) -> SynchronizedArray[Any]: ... @overload def Array( - typecode_or_type: str | Type[_CData], + typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, - lock: bool | _LockLike = ..., - ctx: BaseContext | None = ..., + lock: bool | _LockLike = True, + ctx: BaseContext | None = None, ) -> Any: ... + def copy(obj: _CT) -> _CT: ... + @overload -def synchronized(obj: _SimpleCData[_T], lock: _LockLike | None = ..., ctx: Any | None = ...) -> Synchronized[_T]: ... +def synchronized(obj: _SimpleCData[_T], lock: _LockLike | None = None, ctx: Any | None = None) -> Synchronized[_T]: ... @overload -def synchronized(obj: ctypes.Array[c_char], lock: _LockLike | None = ..., ctx: Any | None = ...) -> SynchronizedString: ... +def synchronized(obj: ctypes.Array[c_char], lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedString: ... @overload -def synchronized(obj: ctypes.Array[_CT], lock: _LockLike | None = ..., ctx: Any | None = ...) -> SynchronizedArray[_CT]: ... +def synchronized( + obj: ctypes.Array[_SimpleCData[_T]], lock: _LockLike | None = None, ctx: Any | None = None +) -> SynchronizedArray[_T]: ... @overload -def synchronized(obj: _CT, lock: _LockLike | None = ..., ctx: Any | None = ...) -> SynchronizedBase[_CT]: ... +def synchronized(obj: _CT, lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedBase[_CT]: ... +@type_check_only class _AcquireFunc(Protocol): - def __call__(self, block: bool = ..., timeout: float | None = ...) -> bool: ... + def __call__(self, block: bool = ..., timeout: float | None = ..., /) -> bool: ... class SynchronizedBase(Generic[_CT]): acquire: _AcquireFunc release: Callable[[], None] - def __init__(self, obj: Any, lock: _LockLike | None = ..., ctx: Any | None = ...) -> None: ... - def __reduce__(self) -> tuple[Callable[..., Any], tuple[Any, _LockLike]]: ... + def __init__(self, obj: Any, lock: _LockLike | None = None, ctx: Any | None = None) -> None: ... + def __reduce__(self) -> tuple[Callable[[Any, _LockLike], SynchronizedBase[Any]], tuple[Any, _LockLike]]: ... def get_obj(self) -> _CT: ... def get_lock(self) -> _LockLike: ... def __enter__(self) -> bool: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): value: _T -class SynchronizedArray(SynchronizedBase[ctypes.Array[_CT]], Generic[_CT]): +class SynchronizedArray(SynchronizedBase[ctypes.Array[_SimpleCData[_T]]], Generic[_T]): def __len__(self) -> int: ... - def __getitem__(self, i: int) -> _CT: ... - def __setitem__(self, i: int, o: _CT) -> None: ... - def __getslice__(self, start: int, stop: int) -> list[_CT]: ... - def __setslice__(self, start: int, stop: int, values: Iterable[_CT]) -> None: ... -class SynchronizedString(SynchronizedArray[c_char]): + @overload + def __getitem__(self, i: slice[SupportsIndex | None]) -> list[_T]: ... + @overload + def __getitem__(self, i: SupportsIndex) -> _T: ... + + @overload + def __setitem__(self, i: slice[SupportsIndex | None], value: Iterable[_T]) -> None: ... + @overload + def __setitem__(self, i: SupportsIndex, value: _T) -> None: ... + + def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> list[_T]: ... + def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: Iterable[_T]) -> None: ... + +class SynchronizedString(SynchronizedArray[bytes]): + @overload # type: ignore[override] + def __getitem__(self, i: slice[SupportsIndex | None]) -> bytes: ... + @overload + def __getitem__(self, i: SupportsIndex) -> bytes: ... + + @overload # type: ignore[override] + def __setitem__(self, i: slice[SupportsIndex | None], value: bytes) -> None: ... + @overload + def __setitem__(self, i: SupportsIndex, value: bytes) -> None: ... + + def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> bytes: ... # type: ignore[override] + def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: bytes) -> None: ... # type: ignore[override] + value: bytes raw: bytes diff --git a/stdlib/multiprocessing/spawn.pyi b/stdlib/multiprocessing/spawn.pyi index 34c7322e0d46..4a9753222897 100644 --- a/stdlib/multiprocessing/spawn.pyi +++ b/stdlib/multiprocessing/spawn.pyi @@ -1,18 +1,29 @@ +from collections.abc import Mapping, Sequence from types import ModuleType -from typing import Any, Mapping, Sequence +from typing import Any, Final -WINEXE: bool -WINSERVICE: bool +__all__ = [ + "_main", + "freeze_support", + "set_executable", + "get_executable", + "get_preparation_data", + "get_command_line", + "import_main_path", +] + +WINEXE: Final[bool] +WINSERVICE: Final[bool] def set_executable(exe: str) -> None: ... def get_executable() -> str: ... def is_forking(argv: Sequence[str]) -> bool: ... def freeze_support() -> None: ... def get_command_line(**kwds: Any) -> list[str]: ... -def spawn_main(pipe_handle: int, parent_pid: int | None = ..., tracker_fd: int | None = ...) -> None: ... +def spawn_main(pipe_handle: int, parent_pid: int | None = None, tracker_fd: int | None = None) -> None: ... # undocumented -def _main(fd: int) -> Any: ... +def _main(fd: int, parent_sentinel: int) -> int: ... def get_preparation_data(name: str) -> dict[str, Any]: ... old_main_modules: list[ModuleType] diff --git a/stdlib/multiprocessing/synchronize.pyi b/stdlib/multiprocessing/synchronize.pyi index c32c9aafe9a4..889e71c061e1 100644 --- a/stdlib/multiprocessing/synchronize.pyi +++ b/stdlib/multiprocessing/synchronize.pyi @@ -1,37 +1,53 @@ import sys import threading -from contextlib import AbstractContextManager +from collections.abc import Callable from multiprocessing.context import BaseContext -from typing import Any, Callable, Union +from types import TracebackType +from typing import TypeAlias -_LockLike = Union[Lock, RLock] +__all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] + +_LockLike: TypeAlias = Lock | RLock class Barrier(threading.Barrier): def __init__( - self, parties: int, action: Callable[..., Any] | None = ..., timeout: float | None = ..., *ctx: BaseContext + self, parties: int, action: Callable[[], object] | None = None, timeout: float | None = None, *, ctx: BaseContext ) -> None: ... -class BoundedSemaphore(Semaphore): - def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... - -class Condition(AbstractContextManager[bool]): - def __init__(self, lock: _LockLike | None = ..., *, ctx: BaseContext) -> None: ... - if sys.version_info >= (3, 7): - def notify(self, n: int = ...) -> None: ... - else: - def notify(self) -> None: ... +class Condition: + def __init__(self, lock: _LockLike | None = None, *, ctx: BaseContext) -> None: ... + def notify(self, n: int = 1) -> None: ... def notify_all(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - def wait_for(self, predicate: Callable[[], bool], timeout: float | None = ...) -> bool: ... - def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... + def wait(self, timeout: float | None = None) -> bool: ... + def wait_for(self, predicate: Callable[[], bool], timeout: float | None = None) -> bool: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... + # These methods are copied from the lock passed to the constructor, or an + # instance of ctx.RLock() if lock was None. + def acquire(self, block: bool = True, timeout: float | None = None) -> bool: ... def release(self) -> None: ... -class Event(AbstractContextManager[bool]): - def __init__(self, lock: _LockLike | None = ..., *, ctx: BaseContext) -> None: ... +class Event: + def __init__(self, *, ctx: BaseContext) -> None: ... def is_set(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... + def wait(self, timeout: float | None = None) -> bool: ... + +# Not part of public API +class SemLock: + def __init__(self, kind: int, value: int, maxvalue: int, *, ctx: BaseContext | None) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... + # These methods are copied from the wrapped _multiprocessing.SemLock object + def acquire(self, block: bool = True, timeout: float | None = None) -> bool: ... + def release(self) -> None: ... + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... class Lock(SemLock): def __init__(self, *, ctx: BaseContext) -> None: ... @@ -40,9 +56,8 @@ class RLock(SemLock): def __init__(self, *, ctx: BaseContext) -> None: ... class Semaphore(SemLock): - def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... + def __init__(self, value: int = 1, *, ctx: BaseContext) -> None: ... + def get_value(self) -> int: ... -# Not part of public API -class SemLock(AbstractContextManager[bool]): - def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... - def release(self) -> None: ... +class BoundedSemaphore(Semaphore): + def __init__(self, value: int = 1, *, ctx: BaseContext) -> None: ... diff --git a/stdlib/multiprocessing/util.pyi b/stdlib/multiprocessing/util.pyi new file mode 100644 index 000000000000..5eb31de77f0f --- /dev/null +++ b/stdlib/multiprocessing/util.pyi @@ -0,0 +1,109 @@ +import sys +import threading +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from logging import Logger, _Level as _LoggingLevel +from typing import Any, Final, Generic, TypeVar, overload + +__all__ = [ + "sub_debug", + "debug", + "info", + "sub_warning", + "get_logger", + "log_to_stderr", + "get_temp_dir", + "register_after_fork", + "is_exiting", + "Finalize", + "ForkAwareThreadLock", + "ForkAwareLocal", + "close_all_fds_except", + "SUBDEBUG", + "SUBWARNING", +] + +if sys.version_info >= (3, 14): + __all__ += ["warn"] + +_T = TypeVar("_T") +_R_co = TypeVar("_R_co", default=Any, covariant=True) + +NOTSET: Final = 0 +SUBDEBUG: Final = 5 +DEBUG: Final = 10 +INFO: Final = 20 +SUBWARNING: Final = 25 +if sys.version_info >= (3, 14): + WARNING: Final = 30 + +LOGGER_NAME: Final[str] +DEFAULT_LOGGING_FORMAT: Final[str] + +def sub_debug(msg: object, *args: object) -> None: ... +def debug(msg: object, *args: object) -> None: ... +def info(msg: object, *args: object) -> None: ... + +if sys.version_info >= (3, 14): + def warn(msg: object, *args: object) -> None: ... + +def sub_warning(msg: object, *args: object) -> None: ... +def get_logger() -> Logger: ... +def log_to_stderr(level: _LoggingLevel | None = None) -> Logger: ... +def is_abstract_socket_namespace(address: str | bytes | None) -> bool: ... + +abstract_sockets_supported: Final[bool] + +def get_temp_dir() -> str: ... +def register_after_fork(obj: _T, func: Callable[[_T], object]) -> None: ... + +class Finalize(Generic[_R_co]): + # "args" and "kwargs" are passed as arguments to "callback". + @overload + def __init__( + self, + obj: None, + callback: Callable[..., _R_co], + *, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + exitpriority: int, + ) -> None: ... + @overload + def __init__( + self, obj: None, callback: Callable[..., _R_co], args: Sequence[Any], kwargs: Mapping[str, Any] | None, exitpriority: int + ) -> None: ... + @overload + def __init__( + self, + obj: Any, + callback: Callable[..., _R_co], + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + exitpriority: int | None = None, + ) -> None: ... + + def __call__( + self, + wr: Unused = None, + _finalizer_registry: MutableMapping[Incomplete, Incomplete] = {}, + sub_debug: Callable[..., object] = ..., + getpid: Callable[[], int] = ..., + ) -> _R_co: ... + def cancel(self) -> None: ... + def still_active(self) -> bool: ... + +def is_exiting() -> bool: ... + +class ForkAwareThreadLock: + acquire: Callable[[bool, float], bool] + release: Callable[[], None] + def __enter__(self) -> bool: ... + def __exit__(self, *args: Unused) -> None: ... + +class ForkAwareLocal(threading.local): ... + +MAXFD: Final[int] + +def close_all_fds_except(fds: Iterable[int]) -> None: ... +def spawnv_passfds(path: bytes, args: Sequence[ConvertibleToInt], passfds: Sequence[int]) -> int: ... diff --git a/stdlib/netrc.pyi b/stdlib/netrc.pyi index b8eac307740a..4b7035c3e565 100644 --- a/stdlib/netrc.pyi +++ b/stdlib/netrc.pyi @@ -1,17 +1,23 @@ +import sys from _typeshed import StrOrBytesPath -from typing import Optional, Tuple +from typing import TypeAlias + +__all__ = ["netrc", "NetrcParseError"] class NetrcParseError(Exception): filename: str | None lineno: int | None msg: str - def __init__(self, msg: str, filename: StrOrBytesPath | None = ..., lineno: int | None = ...) -> None: ... + def __init__(self, msg: str, filename: StrOrBytesPath | None = None, lineno: int | None = None) -> None: ... # (login, account, password) tuple -_NetrcTuple = Tuple[str, Optional[str], Optional[str]] +if sys.version_info >= (3, 11): + _NetrcTuple: TypeAlias = tuple[str, str, str] +else: + _NetrcTuple: TypeAlias = tuple[str, str | None, str | None] class netrc: hosts: dict[str, _NetrcTuple] macros: dict[str, list[str]] - def __init__(self, file: StrOrBytesPath | None = ...) -> None: ... + def __init__(self, file: StrOrBytesPath | None = None) -> None: ... def authenticators(self, host: str) -> _NetrcTuple | None: ... diff --git a/stdlib/nis.pyi b/stdlib/nis.pyi index b762ae46241c..10eef2336a83 100644 --- a/stdlib/nis.pyi +++ b/stdlib/nis.pyi @@ -5,4 +5,5 @@ if sys.platform != "win32": def get_default_domain() -> str: ... def maps(domain: str = ...) -> list[str]: ... def match(key: str, map: str, domain: str = ...) -> str: ... + class error(Exception): ... diff --git a/stdlib/nntplib.pyi b/stdlib/nntplib.pyi index 508b5f679bc3..926b07be79e6 100644 --- a/stdlib/nntplib.pyi +++ b/stdlib/nntplib.pyi @@ -1,11 +1,25 @@ import datetime import socket import ssl -import sys -from _typeshed import Self -from typing import IO, Any, Iterable, NamedTuple, Tuple, Union +from _typeshed import Unused +from builtins import list as _list # conflicts with a method named "list" +from collections.abc import Iterable +from typing import IO, Any, Final, NamedTuple, TypeAlias +from typing_extensions import Self -_File = Union[IO[bytes], bytes, str, None] +__all__ = [ + "NNTP", + "NNTPError", + "NNTPReplyError", + "NNTPTemporaryError", + "NNTPPermanentError", + "NNTPProtocolError", + "NNTPDataError", + "decode_header", + "NNTP_SSL", +] + +_File: TypeAlias = IO[bytes] | bytes | str | None class NNTPError(Exception): response: str @@ -16,8 +30,8 @@ class NNTPPermanentError(NNTPError): ... class NNTPProtocolError(NNTPError): ... class NNTPDataError(NNTPError): ... -NNTP_PORT: int -NNTP_SSL_PORT: int +NNTP_PORT: Final = 119 +NNTP_SSL_PORT: Final = 563 class GroupInfo(NamedTuple): group: str @@ -32,13 +46,13 @@ class ArticleInfo(NamedTuple): def decode_header(header_str: str) -> str: ... -_list = list # conflicts with a method named "list" - -class _NNTPBase: +class NNTP: encoding: str errors: str host: str + port: int + sock: socket.socket file: IO[bytes] debugging: int welcome: str @@ -47,67 +61,60 @@ class _NNTPBase: authenticated: bool nntp_implementation: str nntp_version: int - def __init__(self, file: IO[bytes], host: str, readermode: bool | None = ..., timeout: float = ...) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __init__( + self, + host: str, + port: int = 119, + user: str | None = None, + password: str | None = None, + readermode: bool | None = None, + usenetrc: bool = False, + timeout: float = ..., + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... def getwelcome(self) -> str: ... def getcapabilities(self) -> dict[str, _list[str]]: ... def set_debuglevel(self, level: int) -> None: ... def debug(self, level: int) -> None: ... def capabilities(self) -> tuple[str, dict[str, _list[str]]]: ... - def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = ...) -> tuple[str, _list[str]]: ... - def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = ...) -> tuple[str, _list[str]]: ... - def list(self, group_pattern: str | None = ..., *, file: _File = ...) -> tuple[str, _list[str]]: ... + def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: ... + def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: ... + def list(self, group_pattern: str | None = None, *, file: _File = None) -> tuple[str, _list[str]]: ... def description(self, group: str) -> str: ... def descriptions(self, group_pattern: str) -> tuple[str, dict[str, str]]: ... def group(self, name: str) -> tuple[str, int, int, int, str]: ... - def help(self, *, file: _File = ...) -> tuple[str, _list[str]]: ... - def stat(self, message_spec: Any = ...) -> tuple[str, int, str]: ... + def help(self, *, file: _File = None) -> tuple[str, _list[str]]: ... + def stat(self, message_spec: Any = None) -> tuple[str, int, str]: ... def next(self) -> tuple[str, int, str]: ... def last(self) -> tuple[str, int, str]: ... - def head(self, message_spec: Any = ..., *, file: _File = ...) -> tuple[str, ArticleInfo]: ... - def body(self, message_spec: Any = ..., *, file: _File = ...) -> tuple[str, ArticleInfo]: ... - def article(self, message_spec: Any = ..., *, file: _File = ...) -> tuple[str, ArticleInfo]: ... + def head(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ... + def body(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ... + def article(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ... def slave(self) -> str: ... - def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> tuple[str, _list[str]]: ... - def xover(self, start: int, end: int, *, file: _File = ...) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... + def xhdr(self, hdr: str, str: Any, *, file: _File = None) -> tuple[str, _list[str]]: ... + def xover(self, start: int, end: int, *, file: _File = None) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... def over( - self, message_spec: None | str | _list[Any] | Tuple[Any, ...], *, file: _File = ... + self, message_spec: str | _list[Any] | tuple[Any, ...] | None, *, file: _File = None ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... - if sys.version_info < (3, 9): - def xgtitle(self, group: str, *, file: _File = ...) -> tuple[str, _list[tuple[str, str]]]: ... - def xpath(self, id: Any) -> tuple[str, str]: ... def date(self) -> tuple[str, datetime.datetime]: ... def post(self, data: bytes | Iterable[bytes]) -> str: ... def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... def quit(self) -> str: ... - def login(self, user: str | None = ..., password: str | None = ..., usenetrc: bool = ...) -> None: ... - def starttls(self, context: ssl.SSLContext | None = ...) -> None: ... + def login(self, user: str | None = None, password: str | None = None, usenetrc: bool = True) -> None: ... + def starttls(self, context: ssl.SSLContext | None = None) -> None: ... -class NNTP(_NNTPBase): - port: int - sock: socket.socket - def __init__( - self, - host: str, - port: int = ..., - user: str | None = ..., - password: str | None = ..., - readermode: bool | None = ..., - usenetrc: bool = ..., - timeout: float = ..., - ) -> None: ... - -class NNTP_SSL(_NNTPBase): - sock: socket.socket +class NNTP_SSL(NNTP): + ssl_context: ssl.SSLContext | None + sock: ssl.SSLSocket def __init__( self, host: str, - port: int = ..., - user: str | None = ..., - password: str | None = ..., - ssl_context: ssl.SSLContext | None = ..., - readermode: bool | None = ..., - usenetrc: bool = ..., + port: int = 563, + user: str | None = None, + password: str | None = None, + ssl_context: ssl.SSLContext | None = None, + readermode: bool | None = None, + usenetrc: bool = False, timeout: float = ..., ) -> None: ... diff --git a/stdlib/nt.pyi b/stdlib/nt.pyi new file mode 100644 index 000000000000..0c87444d18f4 --- /dev/null +++ b/stdlib/nt.pyi @@ -0,0 +1,116 @@ +import sys + +if sys.platform == "win32": + # Actually defined here and re-exported from os at runtime, + # but this leads to less code duplication + from os import ( + F_OK as F_OK, + O_APPEND as O_APPEND, + O_BINARY as O_BINARY, + O_CREAT as O_CREAT, + O_EXCL as O_EXCL, + O_NOINHERIT as O_NOINHERIT, + O_RANDOM as O_RANDOM, + O_RDONLY as O_RDONLY, + O_RDWR as O_RDWR, + O_SEQUENTIAL as O_SEQUENTIAL, + O_SHORT_LIVED as O_SHORT_LIVED, + O_TEMPORARY as O_TEMPORARY, + O_TEXT as O_TEXT, + O_TRUNC as O_TRUNC, + O_WRONLY as O_WRONLY, + P_DETACH as P_DETACH, + P_NOWAIT as P_NOWAIT, + P_NOWAITO as P_NOWAITO, + P_OVERLAY as P_OVERLAY, + P_WAIT as P_WAIT, + R_OK as R_OK, + TMP_MAX as TMP_MAX, + W_OK as W_OK, + X_OK as X_OK, + DirEntry as DirEntry, + abort as abort, + access as access, + chdir as chdir, + chmod as chmod, + close as close, + closerange as closerange, + cpu_count as cpu_count, + device_encoding as device_encoding, + dup as dup, + dup2 as dup2, + error as error, + execv as execv, + execve as execve, + fspath as fspath, + fstat as fstat, + fsync as fsync, + ftruncate as ftruncate, + get_handle_inheritable as get_handle_inheritable, + get_inheritable as get_inheritable, + get_terminal_size as get_terminal_size, + getcwd as getcwd, + getcwdb as getcwdb, + getlogin as getlogin, + getpid as getpid, + getppid as getppid, + isatty as isatty, + kill as kill, + link as link, + listdir as listdir, + lseek as lseek, + lstat as lstat, + mkdir as mkdir, + open as open, + pipe as pipe, + putenv as putenv, + read as read, + readlink as readlink, + remove as remove, + rename as rename, + replace as replace, + rmdir as rmdir, + scandir as scandir, + set_handle_inheritable as set_handle_inheritable, + set_inheritable as set_inheritable, + spawnv as spawnv, + spawnve as spawnve, + startfile as startfile, + stat as stat, + stat_result as stat_result, + statvfs_result as statvfs_result, + strerror as strerror, + symlink as symlink, + system as system, + terminal_size as terminal_size, + times as times, + times_result as times_result, + truncate as truncate, + umask as umask, + uname_result as uname_result, + unlink as unlink, + unsetenv as unsetenv, + urandom as urandom, + utime as utime, + waitpid as waitpid, + waitstatus_to_exitcode as waitstatus_to_exitcode, + write as write, + ) + + if sys.version_info >= (3, 11): + from os import EX_OK as EX_OK + if sys.version_info >= (3, 12): + from os import ( + get_blocking as get_blocking, + listdrives as listdrives, + listmounts as listmounts, + listvolumes as listvolumes, + set_blocking as set_blocking, + ) + if sys.version_info >= (3, 13): + from os import fchmod as fchmod, lchmod as lchmod + + if sys.version_info >= (3, 14): + from os import readinto as readinto + + environ: dict[str, str] diff --git a/stdlib/ntpath.pyi b/stdlib/ntpath.pyi index 45d715704157..c912d77158ec 100644 --- a/stdlib/ntpath.pyi +++ b/stdlib/ntpath.pyi @@ -1,6 +1,8 @@ import sys -from _typeshed import BytesPath, StrPath +from _typeshed import BytesPath, StrOrBytesPath, StrPath from genericpath import ( + ALLOW_MISSING as ALLOW_MISSING, + _AllowMissingType, commonprefix as commonprefix, exists as exists, getatime as getatime, @@ -43,28 +45,90 @@ from posixpath import ( supports_unicode_filenames as supports_unicode_filenames, ) from typing import AnyStr, overload +from typing_extensions import LiteralString -altsep: str -if sys.version_info < (3, 7) and sys.platform == "win32": - def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated +if sys.version_info >= (3, 12): + from posixpath import isjunction as isjunction, splitroot as splitroot +if sys.version_info >= (3, 13): + from genericpath import isdevdrive as isdevdrive +if sys.version_info >= (3, 15): + from genericpath import ALL_BUT_LAST as ALL_BUT_LAST -# Similar to posixpath, but have slightly different argument names +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "samefile", + "sameopenfile", + "samestat", + "commonpath", + "ALLOW_MISSING", +] +if sys.version_info >= (3, 12): + __all__ += ["isjunction", "splitroot"] +if sys.version_info >= (3, 13): + __all__ += ["isdevdrive", "isreserved"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] + +altsep: LiteralString + +# First parameter is not actually pos-only, +# but must be defined as pos-only in the stub or cross-platform code doesn't type-check, +# as the parameter name is different in posixpath.join() +@overload +def join(path: LiteralString, /, *paths: LiteralString) -> LiteralString: ... @overload -def join(path: StrPath, *paths: StrPath) -> str: ... +def join(path: StrPath, /, *paths: StrPath) -> str: ... @overload -def join(path: BytesPath, *paths: BytesPath) -> bytes: ... +def join(path: BytesPath, /, *paths: BytesPath) -> bytes: ... -if sys.platform == "win32": - if sys.version_info >= (3, 10): +if sys.version_info >= (3, 15): + @overload + def realpath(path: PathLike[AnyStr], /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(path: AnyStr, /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + +else: + if sys.platform == "win32": @overload - def realpath(path: PathLike[AnyStr], *, strict: bool = ...) -> AnyStr: ... + def realpath(path: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... @overload - def realpath(path: AnyStr, *, strict: bool = ...) -> AnyStr: ... + def realpath(path: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + else: - @overload - def realpath(path: PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... + realpath = abspath -else: - realpath = abspath +if sys.version_info >= (3, 13): + def isreserved(path: StrOrBytesPath) -> bool: ... diff --git a/stdlib/nturl2path.pyi b/stdlib/nturl2path.pyi index b8ad8d682155..3871f263f4e3 100644 --- a/stdlib/nturl2path.pyi +++ b/stdlib/nturl2path.pyi @@ -1,2 +1,6 @@ +from typing_extensions import deprecated + +@deprecated("Deprecated; use `urllib.request` file-URL helpers instead.") def url2pathname(url: str) -> str: ... +@deprecated("Deprecated; use `urllib.request` file-URL helpers instead.") def pathname2url(p: str) -> str: ... diff --git a/stdlib/numbers.pyi b/stdlib/numbers.pyi index eaf53d25347a..434e52c4cac8 100644 --- a/stdlib/numbers.pyi +++ b/stdlib/numbers.pyi @@ -1,124 +1,220 @@ # Note: these stubs are incomplete. The more complex type # signatures are currently omitted. +# +# Use _ComplexLike, _RealLike and _IntegralLike for return types in this module +# rather than `numbers.Complex`, `numbers.Real` and `numbers.Integral`, +# to avoid an excessive number of `type: ignore`s in subclasses of these ABCs +# (since type checkers don't see `complex` as a subtype of `numbers.Complex`, +# nor `float` as a subtype of `numbers.Real`, etc.) from abc import ABCMeta, abstractmethod -from typing import Any, SupportsFloat, overload +from typing import ClassVar, Literal, Protocol, overload, type_check_only + +__all__ = ["Number", "Complex", "Real", "Rational", "Integral"] + +############################ +# Protocols for return types +############################ + +# `_ComplexLike` is a structural-typing approximation +# of the `Complex` ABC, which is not (and cannot be) a protocol +# +# NOTE: We can't include `__complex__` here, +# as we want `int` to be seen as a subtype of `_ComplexLike`, +# and `int.__complex__` does not exist :( +@type_check_only +class _ComplexLike(Protocol): + def __neg__(self) -> _ComplexLike: ... + def __pos__(self) -> _ComplexLike: ... + def __abs__(self) -> _RealLike: ... + +# _RealLike is a structural-typing approximation +# of the `Real` ABC, which is not (and cannot be) a protocol +@type_check_only +class _RealLike(_ComplexLike, Protocol): + def __trunc__(self) -> _IntegralLike: ... + def __floor__(self) -> _IntegralLike: ... + def __ceil__(self) -> _IntegralLike: ... + def __float__(self) -> float: ... + # Overridden from `_ComplexLike` + # for a more precise return type: + def __neg__(self) -> _RealLike: ... + def __pos__(self) -> _RealLike: ... + +# _IntegralLike is a structural-typing approximation +# of the `Integral` ABC, which is not (and cannot be) a protocol +@type_check_only +class _IntegralLike(_RealLike, Protocol): + def __invert__(self) -> _IntegralLike: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + # Overridden from `_ComplexLike` + # for a more precise return type: + def __abs__(self) -> _IntegralLike: ... + # Overridden from `RealLike` + # for a more precise return type: + def __neg__(self) -> _IntegralLike: ... + def __pos__(self) -> _IntegralLike: ... + +################# +# Module "proper" +################# class Number(metaclass=ABCMeta): + __slots__ = () @abstractmethod def __hash__(self) -> int: ... -class Complex(Number): +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Complex(Number, _ComplexLike): + __slots__ = () @abstractmethod def __complex__(self) -> complex: ... def __bool__(self) -> bool: ... @property @abstractmethod - def real(self) -> Any: ... + def real(self) -> _RealLike: ... @property @abstractmethod - def imag(self) -> Any: ... + def imag(self) -> _RealLike: ... + @abstractmethod + def __add__(self, other) -> _ComplexLike: ... + @abstractmethod + def __radd__(self, other) -> _ComplexLike: ... + @abstractmethod + def __neg__(self) -> _ComplexLike: ... @abstractmethod - def __add__(self, other: Any) -> Any: ... + def __pos__(self) -> _ComplexLike: ... + def __sub__(self, other) -> _ComplexLike: ... + def __rsub__(self, other) -> _ComplexLike: ... @abstractmethod - def __radd__(self, other: Any) -> Any: ... + def __mul__(self, other) -> _ComplexLike: ... @abstractmethod - def __neg__(self) -> Any: ... + def __rmul__(self, other) -> _ComplexLike: ... @abstractmethod - def __pos__(self) -> Any: ... - def __sub__(self, other: Any) -> Any: ... - def __rsub__(self, other: Any) -> Any: ... + def __truediv__(self, other) -> _ComplexLike: ... @abstractmethod - def __mul__(self, other: Any) -> Any: ... + def __rtruediv__(self, other) -> _ComplexLike: ... @abstractmethod - def __rmul__(self, other: Any) -> Any: ... + def __pow__(self, exponent) -> _ComplexLike: ... @abstractmethod - def __truediv__(self, other: Any) -> Any: ... + def __rpow__(self, base) -> _ComplexLike: ... @abstractmethod - def __rtruediv__(self, other: Any) -> Any: ... + def __abs__(self) -> _RealLike: ... @abstractmethod - def __pow__(self, exponent: Any) -> Any: ... + def conjugate(self) -> _ComplexLike: ... @abstractmethod - def __rpow__(self, base: Any) -> Any: ... - def __abs__(self) -> Real: ... - def conjugate(self) -> Any: ... - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] -class Real(Complex, SupportsFloat): +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Real(Complex, _RealLike): + __slots__ = () @abstractmethod def __float__(self) -> float: ... @abstractmethod - def __trunc__(self) -> int: ... + def __trunc__(self) -> _IntegralLike: ... @abstractmethod - def __floor__(self) -> int: ... + def __floor__(self) -> _IntegralLike: ... @abstractmethod - def __ceil__(self) -> int: ... + def __ceil__(self) -> _IntegralLike: ... + @abstractmethod @overload - def __round__(self, ndigits: None = ...) -> int: ... + def __round__(self, ndigits: None = None) -> _IntegralLike: ... @abstractmethod @overload - def __round__(self, ndigits: int) -> Any: ... - def __divmod__(self, other: Any) -> Any: ... - def __rdivmod__(self, other: Any) -> Any: ... + def __round__(self, ndigits: int) -> _RealLike: ... + + def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ... + def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ... @abstractmethod - def __floordiv__(self, other: Any) -> int: ... + def __floordiv__(self, other) -> _RealLike: ... @abstractmethod - def __rfloordiv__(self, other: Any) -> int: ... + def __rfloordiv__(self, other) -> _RealLike: ... @abstractmethod - def __mod__(self, other: Any) -> Any: ... + def __mod__(self, other) -> _RealLike: ... @abstractmethod - def __rmod__(self, other: Any) -> Any: ... + def __rmod__(self, other) -> _RealLike: ... @abstractmethod - def __lt__(self, other: Any) -> bool: ... + def __lt__(self, other) -> bool: ... @abstractmethod - def __le__(self, other: Any) -> bool: ... + def __le__(self, other) -> bool: ... def __complex__(self) -> complex: ... @property - def real(self) -> Any: ... + def real(self) -> _RealLike: ... @property - def imag(self) -> Any: ... - def conjugate(self) -> Any: ... + def imag(self) -> Literal[0]: ... + def conjugate(self) -> _RealLike: ... + # Not actually overridden at runtime, + # but we override these in the stub to give them more precise return types: + @abstractmethod + def __pos__(self) -> _RealLike: ... + @abstractmethod + def __neg__(self) -> _RealLike: ... +# See comment at the top of the file +# for why some of these return types are purposefully vague class Rational(Real): + __slots__ = () @property @abstractmethod - def numerator(self) -> int: ... + def numerator(self) -> _IntegralLike: ... @property @abstractmethod - def denominator(self) -> int: ... + def denominator(self) -> _IntegralLike: ... def __float__(self) -> float: ... -class Integral(Rational): +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Integral(Rational, _IntegralLike): + __slots__ = () @abstractmethod def __int__(self) -> int: ... def __index__(self) -> int: ... @abstractmethod - def __pow__(self, exponent: Any, modulus: Any | None = ...) -> Any: ... + def __pow__(self, exponent, modulus=None) -> _IntegralLike: ... @abstractmethod - def __lshift__(self, other: Any) -> Any: ... + def __lshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __rlshift__(self, other: Any) -> Any: ... + def __rlshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __rshift__(self, other: Any) -> Any: ... + def __rshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __rrshift__(self, other: Any) -> Any: ... + def __rrshift__(self, other) -> _IntegralLike: ... @abstractmethod - def __and__(self, other: Any) -> Any: ... + def __and__(self, other) -> _IntegralLike: ... @abstractmethod - def __rand__(self, other: Any) -> Any: ... + def __rand__(self, other) -> _IntegralLike: ... @abstractmethod - def __xor__(self, other: Any) -> Any: ... + def __xor__(self, other) -> _IntegralLike: ... @abstractmethod - def __rxor__(self, other: Any) -> Any: ... + def __rxor__(self, other) -> _IntegralLike: ... @abstractmethod - def __or__(self, other: Any) -> Any: ... + def __or__(self, other) -> _IntegralLike: ... @abstractmethod - def __ror__(self, other: Any) -> Any: ... + def __ror__(self, other) -> _IntegralLike: ... @abstractmethod - def __invert__(self) -> Any: ... + def __invert__(self) -> _IntegralLike: ... def __float__(self) -> float: ... @property - def numerator(self) -> int: ... + def numerator(self) -> _IntegralLike: ... @property - def denominator(self) -> int: ... + def denominator(self) -> Literal[1]: ... + # Not actually overridden at runtime, + # but we override these in the stub to give them more precise return types: + @abstractmethod + def __pos__(self) -> _IntegralLike: ... + @abstractmethod + def __neg__(self) -> _IntegralLike: ... + @abstractmethod + def __abs__(self) -> _IntegralLike: ... + + @abstractmethod + @overload + def __round__(self, ndigits: None = None) -> _IntegralLike: ... + @abstractmethod + @overload + def __round__(self, ndigits: int) -> _IntegralLike: ... diff --git a/stdlib/opcode.pyi b/stdlib/opcode.pyi index 982ddee43a63..3bc41db42bb6 100644 --- a/stdlib/opcode.pyi +++ b/stdlib/opcode.pyi @@ -1,24 +1,53 @@ import sys -from typing import Sequence +from typing import Final, Literal -cmp_op: Sequence[str] -hasconst: list[int] -hasname: list[int] -hasjrel: list[int] -hasjabs: list[int] -haslocal: list[int] -hascompare: list[int] -hasfree: list[int] -opname: list[str] +if sys.version_info >= (3, 15): + from builtins import frozendict -opmap: dict[str, int] -HAVE_ARGUMENT: int -EXTENDED_ARG: int +__all__ = [ + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "stack_effect", +] +if sys.version_info >= (3, 12): + __all__ += ["hasarg", "hasexc"] +else: + __all__ += ["hasnargs"] +if sys.version_info >= (3, 13): + __all__ += ["hasjump"] -if sys.version_info >= (3, 8): - def stack_effect(__opcode: int, __oparg: int | None = ..., *, jump: bool | None = ...) -> int: ... +cmp_op: tuple[Literal["<"], Literal["<="], Literal["=="], Literal["!="], Literal[">"], Literal[">="]] +hasconst: Final[list[int]] +hasname: Final[list[int]] +hasjrel: Final[list[int]] +hasjabs: Final[list[int]] +haslocal: Final[list[int]] +hascompare: Final[list[int]] +hasfree: Final[list[int]] +if sys.version_info >= (3, 12): + hasarg: Final[list[int]] + hasexc: Final[list[int]] +else: + hasnargs: Final[list[int]] +if sys.version_info >= (3, 13): + hasjump: Final[list[int]] +opname: Final[list[str]] +if sys.version_info >= (3, 15): + opmap: Final[frozendict[str, int]] else: - def stack_effect(__opcode: int, __oparg: int | None = ...) -> int: ... + opmap: Final[dict[str, int]] +HAVE_ARGUMENT: Final[int] +EXTENDED_ARG: Final[int] -hasnargs: list[int] +def stack_effect(opcode: int, oparg: int | None = None, /, *, jump: bool | None = None) -> int: ... diff --git a/stdlib/operator.pyi b/stdlib/operator.pyi index 180bd161c045..5998d6d16e98 100644 --- a/stdlib/operator.pyi +++ b/stdlib/operator.pyi @@ -1,6 +1,133 @@ import sys +from _operator import ( + abs as abs, + add as add, + and_ as and_, + concat as concat, + contains as contains, + countOf as countOf, + delitem as delitem, + eq as eq, + floordiv as floordiv, + ge as ge, + getitem as getitem, + gt as gt, + iadd as iadd, + iand as iand, + iconcat as iconcat, + ifloordiv as ifloordiv, + ilshift as ilshift, + imatmul as imatmul, + imod as imod, + imul as imul, + index as index, + indexOf as indexOf, + inv as inv, + invert as invert, + ior as ior, + ipow as ipow, + irshift as irshift, + is_ as is_, + is_not as is_not, + isub as isub, + itruediv as itruediv, + ixor as ixor, + le as le, + length_hint as length_hint, + lshift as lshift, + lt as lt, + matmul as matmul, + mod as mod, + mul as mul, + ne as ne, + neg as neg, + not_ as not_, + or_ as or_, + pos as pos, + pow as pow, + rshift as rshift, + setitem as setitem, + sub as sub, + truediv as truediv, + truth as truth, + xor as xor, +) +from _typeshed import SupportsGetItem +from typing import Any, Generic, TypeVar, final, overload +from typing_extensions import Self, TypeVarTuple, Unpack -from _operator import * +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_Ts = TypeVarTuple("_Ts") + +__all__ = [ + "abs", + "add", + "and_", + "attrgetter", + "concat", + "contains", + "countOf", + "delitem", + "eq", + "floordiv", + "ge", + "getitem", + "gt", + "iadd", + "iand", + "iconcat", + "ifloordiv", + "ilshift", + "imatmul", + "imod", + "imul", + "index", + "indexOf", + "inv", + "invert", + "ior", + "ipow", + "irshift", + "is_", + "is_not", + "isub", + "itemgetter", + "itruediv", + "ixor", + "le", + "length_hint", + "lshift", + "lt", + "matmul", + "methodcaller", + "mod", + "mul", + "ne", + "neg", + "not_", + "or_", + "pos", + "pow", + "rshift", + "setitem", + "sub", + "truediv", + "truth", + "xor", +] + +if sys.version_info >= (3, 11): + from _operator import call as call + + __all__ += ["call"] + +if sys.version_info >= (3, 14): + from _operator import is_none as is_none, is_not_none as is_not_none + + __all__ += ["is_none", "is_not_none"] __lt__ = lt __le__ = le @@ -49,3 +176,44 @@ __itruediv__ = itruediv __ixor__ = ixor if sys.version_info >= (3, 11): __call__ = call + +# At runtime, these classes are implemented in C as part of the _operator module +# However, they consider themselves to live in the operator module, so we'll put +# them here. +@final +class attrgetter(Generic[_T_co]): + @overload + def __new__(cls, attr: str, /) -> attrgetter[Any]: ... + @overload + def __new__(cls, attr: str, attr2: str, /) -> attrgetter[tuple[Any, Any]]: ... + @overload + def __new__(cls, attr: str, attr2: str, attr3: str, /) -> attrgetter[tuple[Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... + + def __call__(self, obj: Any, /) -> _T_co: ... + +@final +class itemgetter(Generic[_T_co]): + @overload + def __new__(cls, item: _T, /) -> itemgetter[_T]: ... + @overload + def __new__(cls, item1: _T1, item2: _T2, /, *items: Unpack[_Ts]) -> itemgetter[tuple[_T1, _T2, Unpack[_Ts]]]: ... + + # __key: _KT_contra in SupportsGetItem seems to be causing variance issues, ie: + # TypeVar "_KT_contra@SupportsGetItem" is contravariant + # "tuple[int, int]" is incompatible with protocol "SupportsIndex" + # preventing [_T_co, ...] instead of [Any, ...] + # + # If we can't infer a literal key from __new__ (ie: `itemgetter[Literal[0]]` for `itemgetter(0)`), + # then we can't annotate __call__'s return type or it'll break on tuples + # + # These issues are best demonstrated by the `itertools.check_itertools_recipes.unique_justseen` test. + def __call__(self, obj: SupportsGetItem[Any, Any]) -> Any: ... + +@final +class methodcaller: + def __new__(cls, name: str, /, *args: Any, **kwargs: Any) -> Self: ... + def __call__(self, obj: Any) -> Any: ... diff --git a/stdlib/optparse.pyi b/stdlib/optparse.pyi index b8ea9d2fff38..35dfc54a9d49 100644 --- a/stdlib/optparse.pyi +++ b/stdlib/optparse.pyi @@ -1,11 +1,36 @@ -from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Tuple, Type, overload +import builtins +from _typeshed import MaybeNone, SupportsWrite +from abc import abstractmethod +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, ClassVar, Final, Literal, overload +from typing_extensions import Never, Self -NO_DEFAULT: Tuple[str, ...] -SUPPRESS_HELP: str -SUPPRESS_USAGE: str +__all__ = [ + "Option", + "make_option", + "SUPPRESS_HELP", + "SUPPRESS_USAGE", + "Values", + "OptionContainer", + "OptionGroup", + "OptionParser", + "HelpFormatter", + "IndentedHelpFormatter", + "TitledHelpFormatter", + "OptParseError", + "OptionError", + "OptionConflictError", + "OptionValueError", + "BadOptionError", + "check_choice", +] +NO_DEFAULT: Final = ("NO", "DEFAULT") +SUPPRESS_HELP: Final = "SUPPRESSHELP" +SUPPRESS_USAGE: Final = "SUPPRESSUSAGE" -def check_builtin(option: Option, opt: Any, value: str) -> Any: ... -def check_choice(option: Option, opt: Any, value: str) -> Any: ... +# Can return complex, float, or int depending on the option's type +def check_builtin(option: Option, opt: str, value: str) -> complex: ... +def check_choice(option: Option, opt: str, value: str) -> str: ... class OptParseError(Exception): msg: str @@ -20,7 +45,6 @@ class AmbiguousOptionError(BadOptionError): def __init__(self, opt_str: str, possibilities: Sequence[str]) -> None: ... class OptionError(OptParseError): - msg: str option_id: str def __init__(self, msg: str, option: Option) -> None: ... @@ -33,24 +57,28 @@ class HelpFormatter: _short_opt_fmt: str current_indent: int default_tag: str - help_position: Any - help_width: Any + help_position: int + help_width: int | MaybeNone # initialized as None and computed later as int when storing option strings indent_increment: int level: int max_help_position: int option_strings: dict[Option, str] parser: OptionParser - short_first: Any + short_first: bool | Literal[0, 1] width: int - def __init__(self, indent_increment: int, max_help_position: int, width: int | None, short_first: int) -> None: ... + def __init__( + self, indent_increment: int, max_help_position: int, width: int | None, short_first: bool | Literal[0, 1] + ) -> None: ... def dedent(self) -> None: ... def expand_default(self, option: Option) -> str: ... - def format_description(self, description: str) -> str: ... - def format_epilog(self, epilog: str) -> str: ... - def format_heading(self, heading: Any) -> str: ... + def format_description(self, description: str | None) -> str: ... + def format_epilog(self, epilog: str | None) -> str: ... + @abstractmethod + def format_heading(self, heading: str) -> str: ... def format_option(self, option: Option) -> str: ... def format_option_strings(self, option: Option) -> str: ... - def format_usage(self, usage: Any) -> str: ... + @abstractmethod + def format_usage(self, usage: str) -> str: ... def indent(self) -> None: ... def set_long_opt_delimiter(self, delim: str) -> None: ... def set_parser(self, parser: OptionParser) -> None: ... @@ -59,41 +87,70 @@ class HelpFormatter: class IndentedHelpFormatter(HelpFormatter): def __init__( - self, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ..., short_first: int = ... + self, + indent_increment: int = 2, + max_help_position: int = 24, + width: int | None = None, + short_first: bool | Literal[0, 1] = 1, ) -> None: ... def format_heading(self, heading: str) -> str: ... def format_usage(self, usage: str) -> str: ... class TitledHelpFormatter(HelpFormatter): def __init__( - self, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ..., short_first: int = ... + self, + indent_increment: int = 0, + max_help_position: int = 24, + width: int | None = None, + short_first: bool | Literal[0, 1] = 0, ) -> None: ... def format_heading(self, heading: str) -> str: ... def format_usage(self, usage: str) -> str: ... class Option: - ACTIONS: Tuple[str, ...] - ALWAYS_TYPED_ACTIONS: Tuple[str, ...] + ACTIONS: tuple[str, ...] + ALWAYS_TYPED_ACTIONS: tuple[str, ...] ATTRS: list[str] - CHECK_METHODS: list[Callable[..., Any]] | None - CONST_ACTIONS: Tuple[str, ...] - STORE_ACTIONS: Tuple[str, ...] - TYPED_ACTIONS: Tuple[str, ...] - TYPES: Tuple[str, ...] - TYPE_CHECKER: dict[str, Callable[..., Any]] + CHECK_METHODS: list[Callable[[Self], object]] | None + CONST_ACTIONS: tuple[str, ...] + STORE_ACTIONS: tuple[str, ...] + TYPED_ACTIONS: tuple[str, ...] + TYPES: tuple[str, ...] + TYPE_CHECKER: dict[str, Callable[[Option, str, str], object]] _long_opts: list[str] _short_opts: list[str] action: str + type: str | None dest: str | None - default: Any + default: Any # default can be "any" type nargs: int - type: Any - callback: Callable[..., Any] | None - callback_args: Tuple[Any, ...] | None + const: Any | None # const can be "any" type + choices: list[str] | tuple[str, ...] | None + # Callback args and kwargs cannot be expressed in Python's type system. + # Revisit if ParamSpec is ever changed to work with packed args/kwargs. + callback: Callable[..., object] | None + callback_args: tuple[Any, ...] | None callback_kwargs: dict[str, Any] | None help: str | None metavar: str | None - def __init__(self, *opts: str | None, **attrs: Any) -> None: ... + def __init__( + self, + *opts: str | None, + # The following keywords are handled by the _set_attrs method. All default to + # `None` except for `default`, which defaults to `NO_DEFAULT`. + action: str | None = None, + type: str | builtins.type | None = None, + dest: str | None = None, + default: Any = ..., # = NO_DEFAULT + nargs: int | None = None, + const: Any | None = None, + choices: list[str] | tuple[str, ...] | None = None, + callback: Callable[..., object] | None = None, + callback_args: tuple[Any, ...] | None = None, + callback_kwargs: dict[str, Any] | None = None, + help: str | None = None, + metavar: str | None = None, + ) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... @@ -102,13 +159,14 @@ class Option: def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[str | None]) -> list[str]: ... def _check_type(self) -> None: ... - def _set_attrs(self, attrs: dict[str, Any]) -> None: ... + def _set_attrs(self, attrs: dict[str, Any]) -> None: ... # accepted attrs depend on the ATTRS attribute def _set_opt_strings(self, opts: Iterable[str]) -> None: ... - def check_value(self, opt: str, value: Any) -> Any: ... - def convert_value(self, opt: str, value: Any) -> Any: ... + def check_value(self, opt: str, value: str) -> Any: ... # return type cannot be known statically + def convert_value(self, opt: str, value: str | tuple[str, ...] | None) -> Any: ... # return type cannot be known statically def get_opt_string(self) -> str: ... - def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... - def take_action(self, action: str, dest: str, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def process(self, opt: str, value: str | tuple[str, ...] | None, values: Values, parser: OptionParser) -> int: ... + # value of take_action can be "any" type + def take_action(self, action: str, dest: str, opt: str, value: Any, values: Values, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... make_option = Option @@ -117,47 +175,74 @@ class OptionContainer: _long_opt: dict[str, Option] _short_opt: dict[str, Option] conflict_handler: str - defaults: dict[str, Any] - description: Any - option_class: Type[Option] - def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... - def _check_conflict(self, option: Any) -> None: ... + defaults: dict[str, Any] # default values can be "any" type + description: str | None + option_class: type[Option] + def __init__( + self, option_class: type[Option], conflict_handler: Literal["error", "resolve"], description: str | None + ) -> None: ... + def _check_conflict(self, option: Option) -> None: ... def _create_option_mappings(self) -> None: ... def _share_option_mappings(self, parser: OptionParser) -> None: ... + @overload - def add_option(self, opt: Option) -> Option: ... + def add_option(self, opt: Option, /) -> Option: ... @overload - def add_option(self, *args: str | None, **kwargs: Any) -> Any: ... + def add_option( + self, + opt_str: str, + /, + *opts: str | None, + action: str | None = None, + type: str | builtins.type | None = None, + dest: str | None = None, + default: Any = ..., # = NO_DEFAULT + nargs: int | None = None, + const: Any | None = None, + choices: list[str] | tuple[str, ...] | None = None, + callback: Callable[..., object] | None = None, + callback_args: tuple[Any, ...] | None = None, + callback_kwargs: dict[str, Any] | None = None, + help: str | None = None, + metavar: str | None = None, + **kwargs: Any, # Allow arbitrary keyword arguments for user defined option_class + ) -> Option: ... + def add_options(self, option_list: Iterable[Option]) -> None: ... def destroy(self) -> None: ... - def format_description(self, formatter: HelpFormatter | None) -> Any: ... - def format_help(self, formatter: HelpFormatter | None) -> str: ... - def format_option_help(self, formatter: HelpFormatter | None) -> str: ... - def get_description(self) -> Any: ... + def format_option_help(self, formatter: HelpFormatter) -> str: ... + def format_description(self, formatter: HelpFormatter) -> str: ... + def format_help(self, formatter: HelpFormatter) -> str: ... + def get_description(self) -> str | None: ... def get_option(self, opt_str: str) -> Option | None: ... def has_option(self, opt_str: str) -> bool: ... def remove_option(self, opt_str: str) -> None: ... - def set_conflict_handler(self, handler: Any) -> None: ... - def set_description(self, description: Any) -> None: ... + def set_conflict_handler(self, handler: Literal["error", "resolve"]) -> None: ... + def set_description(self, description: str | None) -> None: ... class OptionGroup(OptionContainer): option_list: list[Option] parser: OptionParser title: str - def __init__(self, parser: OptionParser, title: str, description: str | None = ...) -> None: ... + def __init__(self, parser: OptionParser, title: str, description: str | None = None) -> None: ... def _create_option_list(self) -> None: ... def set_title(self, title: str) -> None: ... class Values: - def __init__(self, defaults: Mapping[str, Any] | None = ...) -> None: ... - def _update(self, dict: Mapping[str, Any], mode: Any) -> None: ... - def _update_careful(self, dict: Mapping[str, Any]) -> None: ... - def _update_loose(self, dict: Mapping[str, Any]) -> None: ... - def ensure_value(self, attr: str, value: Any) -> Any: ... - def read_file(self, filename: str, mode: str = ...) -> None: ... - def read_module(self, modname: str, mode: str = ...) -> None: ... + def __init__(self, defaults: Mapping[str, object] | None = None) -> None: ... + def _update(self, dict: Mapping[str, object], mode: Literal["careful", "loose"]) -> None: ... + def _update_careful(self, dict: Mapping[str, object]) -> None: ... + def _update_loose(self, dict: Mapping[str, object]) -> None: ... + def ensure_value(self, attr: str, value: object) -> Any: ... # return type cannot be known statically + def read_file(self, filename: str, mode: Literal["careful", "loose"] = "careful") -> None: ... + def read_module(self, modname: str, mode: Literal["careful", "loose"] = "careful") -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + # __getattr__ doesn't exist, but anything passed as a default to __init__ + # is set on the instance. def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... + # TODO: mypy infers -> object for __getattr__ if __setattr__ has `value: object` + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __eq__(self, other: object) -> bool: ... class OptionParser(OptionContainer): allow_interspersed_args: bool @@ -166,60 +251,62 @@ class OptionParser(OptionContainer): largs: list[str] | None option_groups: list[OptionGroup] option_list: list[Option] - process_default_values: Any + process_default_values: bool prog: str | None - rargs: list[Any] | None + rargs: list[str] | None standard_option_list: list[Option] usage: str | None values: Values | None version: str def __init__( self, - usage: str | None = ..., - option_list: Iterable[Option] | None = ..., - option_class: Type[Option] = ..., - version: str | None = ..., - conflict_handler: str = ..., - description: str | None = ..., - formatter: HelpFormatter | None = ..., - add_help_option: bool = ..., - prog: str | None = ..., - epilog: str | None = ..., + usage: str | None = None, + option_list: Iterable[Option] | None = None, + option_class: type[Option] = ..., + version: str | None = None, + conflict_handler: str = "error", + description: str | None = None, + formatter: HelpFormatter | None = None, + add_help_option: bool = True, + prog: str | None = None, + epilog: str | None = None, ) -> None: ... def _add_help_option(self) -> None: ... def _add_version_option(self) -> None: ... def _create_option_list(self) -> None: ... def _get_all_options(self) -> list[Option]: ... - def _get_args(self, args: Iterable[Any]) -> list[Any]: ... + def _get_args(self, args: list[str] | None) -> list[str]: ... def _init_parsing_state(self) -> None: ... def _match_long_opt(self, opt: str) -> str: ... - def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ... - def _process_args(self, largs: list[Any], rargs: list[Any], values: Values) -> None: ... - def _process_long_opt(self, rargs: list[Any], values: Any) -> None: ... - def _process_short_opts(self, rargs: list[Any], values: Any) -> None: ... + def _populate_option_list(self, option_list: Iterable[Option] | None, add_help: bool = True) -> None: ... + def _process_args(self, largs: list[str], rargs: list[str], values: Values) -> None: ... + def _process_long_opt(self, rargs: list[str], values: Values) -> None: ... + def _process_short_opts(self, rargs: list[str], values: Values) -> None: ... + @overload - def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... + def add_option_group(self, opt_group: OptionGroup, /) -> OptionGroup: ... @overload - def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... + def add_option_group(self, title: str, /, description: str | None = None) -> OptionGroup: ... + def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: ... def disable_interspersed_args(self) -> None: ... def enable_interspersed_args(self) -> None: ... - def error(self, msg: str) -> None: ... - def exit(self, status: int = ..., msg: str | None = ...) -> None: ... - def expand_prog_name(self, s: str | None) -> Any: ... - def format_epilog(self, formatter: HelpFormatter) -> Any: ... - def format_help(self, formatter: HelpFormatter | None = ...) -> str: ... - def format_option_help(self, formatter: HelpFormatter | None = ...) -> str: ... + def error(self, msg: str) -> Never: ... + def exit(self, status: int = 0, msg: str | None = None) -> Never: ... + def expand_prog_name(self, s: str) -> str: ... + def format_epilog(self, formatter: HelpFormatter) -> str: ... + def format_help(self, formatter: HelpFormatter | None = None) -> str: ... + def format_option_help(self, formatter: HelpFormatter | None = None) -> str: ... def get_default_values(self) -> Values: ... - def get_option_group(self, opt_str: str) -> Any: ... + def get_option_group(self, opt_str: str) -> OptionGroup | None: ... def get_prog_name(self) -> str: ... def get_usage(self) -> str: ... def get_version(self) -> str: ... - def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> tuple[Values, list[AnyStr]]: ... - def print_usage(self, file: IO[str] | None = ...) -> None: ... - def print_help(self, file: IO[str] | None = ...) -> None: ... - def print_version(self, file: IO[str] | None = ...) -> None: ... - def set_default(self, dest: Any, value: Any) -> None: ... - def set_defaults(self, **kwargs: Any) -> None: ... - def set_process_default_values(self, process: Any) -> None: ... - def set_usage(self, usage: str) -> None: ... + def parse_args(self, args: list[str] | None = None, values: Values | None = None) -> tuple[Values, list[str]]: ... + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ... + def print_help(self, file: SupportsWrite[str] | None = None) -> None: ... + def print_version(self, file: SupportsWrite[str] | None = None) -> None: ... + def set_default(self, dest: str, value: Any) -> None: ... # default value can be "any" type + def set_defaults(self, **kwargs: Any) -> None: ... # default values can be "any" type + def set_process_default_values(self, process: bool) -> None: ... + def set_usage(self, usage: str | None) -> None: ... diff --git a/stdlib/os/__init__.pyi b/stdlib/os/__init__.pyi index 5d4b6b246662..89b9bd866420 100644 --- a/stdlib/os/__init__.pyi +++ b/stdlib/os/__init__.pyi @@ -1,53 +1,542 @@ import sys from _typeshed import ( + AnyStr_co, + BytesPath, + FileDescriptor, FileDescriptorLike, + FileDescriptorOrPath, + GenericPath, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, - Self, + ReadableBuffer, StrOrBytesPath, StrPath, + SupportsLenAndGetItem, + Unused, + WriteableBuffer, structseq, ) +from abc import ABC, abstractmethod from builtins import OSError -from contextlib import AbstractContextManager -from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from subprocess import Popen +from types import GenericAlias, TracebackType from typing import ( IO, Any, AnyStr, BinaryIO, - Callable, + Final, Generic, - Iterable, - Iterator, - List, - Mapping, - MutableMapping, - NoReturn, + Literal, Protocol, - Sequence, - Tuple, + TypeAlias, TypeVar, - Union, + final, overload, runtime_checkable, + type_check_only, ) -from typing_extensions import Literal, final +from typing_extensions import LiteralString, Never, Self, Unpack, deprecated from . import path as _path -if sys.version_info >= (3, 9): - from types import GenericAlias +# Re-export common definitions from os.path to reduce duplication +from .path import ( + altsep as altsep, + curdir as curdir, + defpath as defpath, + devnull as devnull, + extsep as extsep, + pardir as pardir, + pathsep as pathsep, + sep as sep, +) + +__all__ = [ + "F_OK", + "O_APPEND", + "O_CREAT", + "O_EXCL", + "O_RDONLY", + "O_RDWR", + "O_TRUNC", + "O_WRONLY", + "P_NOWAIT", + "P_NOWAITO", + "P_WAIT", + "R_OK", + "SEEK_CUR", + "SEEK_END", + "SEEK_SET", + "TMP_MAX", + "W_OK", + "X_OK", + "DirEntry", + "_exit", + "abort", + "access", + "altsep", + "chdir", + "chmod", + "close", + "closerange", + "cpu_count", + "curdir", + "defpath", + "device_encoding", + "devnull", + "dup", + "dup2", + "environ", + "error", + "execl", + "execle", + "execlp", + "execlpe", + "execv", + "execve", + "execvp", + "execvpe", + "extsep", + "fdopen", + "fsdecode", + "fsencode", + "fspath", + "fstat", + "fsync", + "ftruncate", + "get_exec_path", + "get_inheritable", + "get_terminal_size", + "getcwd", + "getcwdb", + "getenv", + "getlogin", + "getpid", + "getppid", + "isatty", + "kill", + "linesep", + "link", + "listdir", + "lseek", + "lstat", + "makedirs", + "mkdir", + "name", + "open", + "pardir", + "path", + "pathsep", + "pipe", + "popen", + "putenv", + "read", + "readlink", + "remove", + "removedirs", + "rename", + "renames", + "replace", + "rmdir", + "scandir", + "sep", + "set_inheritable", + "spawnl", + "spawnle", + "spawnv", + "spawnve", + "stat", + "stat_result", + "statvfs_result", + "strerror", + "supports_bytes_environ", + "symlink", + "system", + "terminal_size", + "times", + "times_result", + "truncate", + "umask", + "uname_result", + "unlink", + "unsetenv", + "urandom", + "utime", + "waitpid", + "waitstatus_to_exitcode", + "walk", + "write", +] +if sys.version_info >= (3, 14): + # reload_environ was added to __all__ in Python 3.14.1 + __all__ += ["readinto", "reload_environ"] +if sys.platform == "linux" and sys.version_info >= (3, 15): + __all__ += ["_clearenv"] +if sys.platform == "darwin" and sys.version_info >= (3, 12): + __all__ += ["PRIO_DARWIN_BG", "PRIO_DARWIN_NONUI", "PRIO_DARWIN_PROCESS", "PRIO_DARWIN_THREAD"] +if sys.platform == "darwin": + __all__ += ["O_EVTONLY", "O_NOFOLLOW_ANY", "O_SYMLINK"] +if sys.platform == "linux": + __all__ += [ + "GRND_NONBLOCK", + "GRND_RANDOM", + "MFD_ALLOW_SEALING", + "MFD_CLOEXEC", + "MFD_HUGETLB", + "MFD_HUGE_16GB", + "MFD_HUGE_16MB", + "MFD_HUGE_1GB", + "MFD_HUGE_1MB", + "MFD_HUGE_256MB", + "MFD_HUGE_2GB", + "MFD_HUGE_2MB", + "MFD_HUGE_32MB", + "MFD_HUGE_512KB", + "MFD_HUGE_512MB", + "MFD_HUGE_64KB", + "MFD_HUGE_8MB", + "MFD_HUGE_MASK", + "MFD_HUGE_SHIFT", + "O_DIRECT", + "O_LARGEFILE", + "O_NOATIME", + "O_PATH", + "O_RSYNC", + "O_TMPFILE", + "P_PIDFD", + "RTLD_DEEPBIND", + "SCHED_BATCH", + "SCHED_IDLE", + "SCHED_RESET_ON_FORK", + "XATTR_CREATE", + "XATTR_REPLACE", + "XATTR_SIZE_MAX", + "copy_file_range", + "getrandom", + "getxattr", + "listxattr", + "memfd_create", + "pidfd_open", + "removexattr", + "setxattr", + ] +if sys.platform == "linux" and sys.version_info >= (3, 14): + __all__ += ["SCHED_DEADLINE", "SCHED_NORMAL"] +if sys.platform == "linux" and sys.version_info >= (3, 15): + __all__ += [ + "AT_NO_AUTOMOUNT", + "AT_STATX_DONT_SYNC", + "AT_STATX_FORCE_SYNC", + "AT_STATX_SYNC_AS_STAT", + "STATX_ATIME", + "STATX_BASIC_STATS", + "STATX_BLOCKS", + "STATX_BTIME", + "STATX_CTIME", + "STATX_DIOALIGN", + "STATX_GID", + "STATX_INO", + "STATX_MNT_ID", + "STATX_MNT_ID_UNIQUE", + "STATX_MODE", + "STATX_MTIME", + "STATX_NLINK", + "STATX_SIZE", + "STATX_TYPE", + "STATX_UID", + "statx", + "statx_result", + ] +if sys.platform == "linux" and sys.version_info >= (3, 13): + __all__ += [ + "POSIX_SPAWN_CLOSEFROM", + "TFD_CLOEXEC", + "TFD_NONBLOCK", + "TFD_TIMER_ABSTIME", + "TFD_TIMER_CANCEL_ON_SET", + "timerfd_create", + "timerfd_gettime", + "timerfd_gettime_ns", + "timerfd_settime", + "timerfd_settime_ns", + ] +if sys.platform == "linux" and sys.version_info >= (3, 12): + __all__ += [ + "CLONE_FILES", + "CLONE_FS", + "CLONE_NEWCGROUP", + "CLONE_NEWIPC", + "CLONE_NEWNET", + "CLONE_NEWNS", + "CLONE_NEWPID", + "CLONE_NEWTIME", + "CLONE_NEWUSER", + "CLONE_NEWUTS", + "CLONE_SIGHAND", + "CLONE_SYSVSEM", + "CLONE_THREAD", + "CLONE_VM", + "setns", + "unshare", + "PIDFD_NONBLOCK", + ] +if sys.platform == "linux": + __all__ += [ + "EFD_CLOEXEC", + "EFD_NONBLOCK", + "EFD_SEMAPHORE", + "RWF_APPEND", + "SPLICE_F_MORE", + "SPLICE_F_MOVE", + "SPLICE_F_NONBLOCK", + "eventfd", + "eventfd_read", + "eventfd_write", + "splice", + ] +if sys.platform == "win32": + __all__ += [ + "O_BINARY", + "O_NOINHERIT", + "O_RANDOM", + "O_SEQUENTIAL", + "O_SHORT_LIVED", + "O_TEMPORARY", + "O_TEXT", + "P_DETACH", + "P_OVERLAY", + "get_handle_inheritable", + "set_handle_inheritable", + "startfile", + ] +if sys.platform == "win32" and sys.version_info >= (3, 12): + __all__ += ["listdrives", "listmounts", "listvolumes"] +if sys.platform != "win32": + __all__ += [ + "CLD_CONTINUED", + "CLD_DUMPED", + "CLD_EXITED", + "CLD_KILLED", + "CLD_STOPPED", + "CLD_TRAPPED", + "EX_CANTCREAT", + "EX_CONFIG", + "EX_DATAERR", + "EX_IOERR", + "EX_NOHOST", + "EX_NOINPUT", + "EX_NOPERM", + "EX_NOUSER", + "EX_OSERR", + "EX_OSFILE", + "EX_PROTOCOL", + "EX_SOFTWARE", + "EX_TEMPFAIL", + "EX_UNAVAILABLE", + "EX_USAGE", + "F_LOCK", + "F_TEST", + "F_TLOCK", + "F_ULOCK", + "NGROUPS_MAX", + "O_ACCMODE", + "O_ASYNC", + "O_CLOEXEC", + "O_DIRECTORY", + "O_DSYNC", + "O_NDELAY", + "O_NOCTTY", + "O_NOFOLLOW", + "O_NONBLOCK", + "O_SYNC", + "POSIX_SPAWN_CLOSE", + "POSIX_SPAWN_DUP2", + "POSIX_SPAWN_OPEN", + "PRIO_PGRP", + "PRIO_PROCESS", + "PRIO_USER", + "P_ALL", + "P_PGID", + "P_PID", + "RTLD_GLOBAL", + "RTLD_LAZY", + "RTLD_LOCAL", + "RTLD_NODELETE", + "RTLD_NOLOAD", + "RTLD_NOW", + "SCHED_FIFO", + "SCHED_OTHER", + "SCHED_RR", + "SEEK_DATA", + "SEEK_HOLE", + "ST_NOSUID", + "ST_RDONLY", + "WCONTINUED", + "WCOREDUMP", + "WEXITED", + "WEXITSTATUS", + "WIFCONTINUED", + "WIFEXITED", + "WIFSIGNALED", + "WIFSTOPPED", + "WNOHANG", + "WNOWAIT", + "WSTOPPED", + "WSTOPSIG", + "WTERMSIG", + "WUNTRACED", + "chown", + "chroot", + "confstr", + "confstr_names", + "ctermid", + "environb", + "fchdir", + "fchown", + "fork", + "forkpty", + "fpathconf", + "fstatvfs", + "fwalk", + "getegid", + "getenvb", + "geteuid", + "getgid", + "getgrouplist", + "getgroups", + "getloadavg", + "getpgid", + "getpgrp", + "getpriority", + "getsid", + "getuid", + "initgroups", + "killpg", + "lchown", + "lockf", + "major", + "makedev", + "minor", + "mkfifo", + "mknod", + "nice", + "openpty", + "pathconf", + "pathconf_names", + "posix_spawn", + "posix_spawnp", + "pread", + "preadv", + "pwrite", + "pwritev", + "readv", + "register_at_fork", + "sched_get_priority_max", + "sched_get_priority_min", + "sched_yield", + "sendfile", + "setegid", + "seteuid", + "setgid", + "setgroups", + "setpgid", + "setpgrp", + "setpriority", + "setregid", + "setreuid", + "setsid", + "setuid", + "spawnlp", + "spawnlpe", + "spawnvp", + "spawnvpe", + "statvfs", + "sync", + "sysconf", + "sysconf_names", + "tcgetpgrp", + "tcsetpgrp", + "ttyname", + "uname", + "wait", + "wait3", + "wait4", + "writev", + ] +if sys.platform != "win32" and sys.version_info >= (3, 13): + __all__ += ["grantpt", "posix_openpt", "ptsname", "unlockpt"] +if sys.platform != "win32" and sys.version_info >= (3, 11): + __all__ += ["login_tty"] +if sys.platform != "win32" and sys.version_info >= (3, 15): + __all__ += ["NODEV", "O_FSYNC"] +elif sys.platform != "win32": + __all__ += ["O_FSYNC"] +if sys.platform != "darwin" and sys.platform != "win32": + __all__ += [ + "POSIX_FADV_DONTNEED", + "POSIX_FADV_NOREUSE", + "POSIX_FADV_NORMAL", + "POSIX_FADV_RANDOM", + "POSIX_FADV_SEQUENTIAL", + "POSIX_FADV_WILLNEED", + "RWF_DSYNC", + "RWF_HIPRI", + "RWF_NOWAIT", + "RWF_SYNC", + "ST_APPEND", + "ST_MANDLOCK", + "ST_NOATIME", + "ST_NODEV", + "ST_NODIRATIME", + "ST_NOEXEC", + "ST_RELATIME", + "ST_SYNCHRONOUS", + "ST_WRITE", + "fdatasync", + "getresgid", + "getresuid", + "pipe2", + "posix_fadvise", + "posix_fallocate", + "sched_getaffinity", + "sched_getparam", + "sched_getscheduler", + "sched_param", + "sched_rr_get_interval", + "sched_setaffinity", + "sched_setparam", + "sched_setscheduler", + "setresgid", + "setresuid", + ] +if sys.platform != "linux" and sys.platform != "win32": + __all__ += ["O_EXLOCK", "O_SHLOCK", "chflags", "lchflags"] +if sys.platform != "linux" and sys.platform != "win32" and sys.version_info >= (3, 13): + __all__ += ["O_EXEC", "O_SEARCH"] +if sys.platform != "darwin" or sys.version_info >= (3, 13): + if sys.platform != "win32": + __all__ += ["waitid", "waitid_result"] +if sys.platform != "win32" or sys.version_info >= (3, 13): + __all__ += ["fchmod"] + if sys.platform != "linux": + __all__ += ["lchmod"] +if sys.platform != "win32" or sys.version_info >= (3, 12): + __all__ += ["get_blocking", "set_blocking"] +if sys.platform != "win32" or sys.version_info >= (3, 11): + __all__ += ["EX_OK"] # This unnecessary alias is to work around various errors path = _path _T = TypeVar("_T") -_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") # ----- os variables ----- @@ -62,229 +551,311 @@ supports_follow_symlinks: set[Callable[..., Any]] if sys.platform != "win32": # Unix only - PRIO_PROCESS: int - PRIO_PGRP: int - PRIO_USER: int + PRIO_PROCESS: Final[int] + PRIO_PGRP: Final[int] + PRIO_USER: Final[int] - F_LOCK: int - F_TLOCK: int - F_ULOCK: int - F_TEST: int + F_LOCK: Final[int] + F_TLOCK: Final[int] + F_ULOCK: Final[int] + F_TEST: Final[int] if sys.platform != "darwin": - POSIX_FADV_NORMAL: int - POSIX_FADV_SEQUENTIAL: int - POSIX_FADV_RANDOM: int - POSIX_FADV_NOREUSE: int - POSIX_FADV_WILLNEED: int - POSIX_FADV_DONTNEED: int + POSIX_FADV_NORMAL: Final[int] + POSIX_FADV_SEQUENTIAL: Final[int] + POSIX_FADV_RANDOM: Final[int] + POSIX_FADV_NOREUSE: Final[int] + POSIX_FADV_WILLNEED: Final[int] + POSIX_FADV_DONTNEED: Final[int] + + if sys.platform != "linux" and sys.platform != "darwin": + # In the os-module docs, these are marked as being available + # on "Unix, not Emscripten, not WASI." + # However, in the source code, a comment indicates they're "FreeBSD constants". + # sys.platform could have one of many values on a FreeBSD Python build, + # so the sys-module docs recommend doing `if sys.platform.startswith('freebsd')` + # to detect FreeBSD builds. Unfortunately that would be too dynamic + # for type checkers, however. + SF_NODISKIO: Final[int] + SF_MNOWAIT: Final[int] + SF_SYNC: Final[int] + + if sys.version_info >= (3, 11): + SF_NOCACHE: Final[int] - SF_NODISKIO: int - SF_MNOWAIT: int - SF_SYNC: int + if sys.platform == "linux": + XATTR_SIZE_MAX: Final[int] + XATTR_CREATE: Final[int] + XATTR_REPLACE: Final[int] + + P_PID: Final[int] + P_PGID: Final[int] + P_ALL: Final[int] if sys.platform == "linux": - XATTR_SIZE_MAX: int - XATTR_CREATE: int - XATTR_REPLACE: int - - P_PID: int - P_PGID: int - P_ALL: int - - WEXITED: int - WSTOPPED: int - WNOWAIT: int - - CLD_EXITED: int - CLD_DUMPED: int - CLD_TRAPPED: int - CLD_CONTINUED: int - - # TODO: SCHED_RESET_ON_FORK not available on darwin? - # TODO: SCHED_BATCH and SCHED_IDLE are linux only? - SCHED_OTHER: int # some flavors of Unix - SCHED_BATCH: int # some flavors of Unix - SCHED_IDLE: int # some flavors of Unix - SCHED_SPORADIC: int # some flavors of Unix - SCHED_FIFO: int # some flavors of Unix - SCHED_RR: int # some flavors of Unix - SCHED_RESET_ON_FORK: int # some flavors of Unix + P_PIDFD: Final[int] + + WEXITED: Final[int] + WSTOPPED: Final[int] + WNOWAIT: Final[int] + + CLD_EXITED: Final[int] + CLD_DUMPED: Final[int] + CLD_TRAPPED: Final[int] + CLD_CONTINUED: Final[int] + CLD_KILLED: Final[int] + CLD_STOPPED: Final[int] + + SCHED_OTHER: Final[int] + SCHED_FIFO: Final[int] + SCHED_RR: Final[int] + if sys.platform != "darwin" and sys.platform != "linux": + SCHED_SPORADIC: Final[int] + +if sys.platform == "linux": + SCHED_BATCH: Final[int] + SCHED_IDLE: Final[int] + SCHED_RESET_ON_FORK: Final[int] + +if sys.version_info >= (3, 14) and sys.platform == "linux": + SCHED_DEADLINE: Final[int] + SCHED_NORMAL: Final[int] if sys.platform != "win32": - RTLD_LAZY: int - RTLD_NOW: int - RTLD_GLOBAL: int - RTLD_LOCAL: int - RTLD_NODELETE: int - RTLD_NOLOAD: int + RTLD_LAZY: Final[int] + RTLD_NOW: Final[int] + RTLD_GLOBAL: Final[int] + RTLD_LOCAL: Final[int] + RTLD_NODELETE: Final[int] + RTLD_NOLOAD: Final[int] if sys.platform == "linux": - RTLD_DEEPBIND: int - GRND_NONBLOCK: int - GRND_RANDOM: int + RTLD_DEEPBIND: Final[int] + GRND_NONBLOCK: Final[int] + GRND_RANDOM: Final[int] + +if sys.platform == "darwin" and sys.version_info >= (3, 12): + PRIO_DARWIN_BG: Final[int] + PRIO_DARWIN_NONUI: Final[int] + PRIO_DARWIN_PROCESS: Final[int] + PRIO_DARWIN_THREAD: Final[int] + +SEEK_SET: Final = 0 +SEEK_CUR: Final = 1 +SEEK_END: Final = 2 +if sys.platform == "linux": + SEEK_DATA: Final = 3 + SEEK_HOLE: Final = 4 +elif sys.platform == "darwin": + SEEK_HOLE: Final = 3 + SEEK_DATA: Final = 4 + +O_RDONLY: Final[int] +O_WRONLY: Final[int] +O_RDWR: Final[int] +O_APPEND: Final[int] +O_CREAT: Final[int] +O_EXCL: Final[int] +O_TRUNC: Final[int] +if sys.platform == "win32": + O_BINARY: Final[int] + O_NOINHERIT: Final[int] + O_SHORT_LIVED: Final[int] + O_TEMPORARY: Final[int] + O_RANDOM: Final[int] + O_SEQUENTIAL: Final[int] + O_TEXT: Final[int] -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int if sys.platform != "win32": - SEEK_DATA: int # some flavors of Unix - SEEK_HOLE: int # some flavors of Unix - -O_RDONLY: int -O_WRONLY: int -O_RDWR: int -O_APPEND: int -O_CREAT: int -O_EXCL: int -O_TRUNC: int -# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, -# including tests for mypy, use a more finer way than sys.platform before using these APIs -# See https://github.com/python/typeshed/pull/2286 for discussions -O_DSYNC: int # Unix only -O_RSYNC: int # Unix only -O_SYNC: int # Unix only -O_NDELAY: int # Unix only -O_NONBLOCK: int # Unix only -O_NOCTTY: int # Unix only -O_CLOEXEC: int # Unix only -O_SHLOCK: int # Unix only -O_EXLOCK: int # Unix only -O_BINARY: int # Windows only -O_NOINHERIT: int # Windows only -O_SHORT_LIVED: int # Windows only -O_TEMPORARY: int # Windows only -O_RANDOM: int # Windows only -O_SEQUENTIAL: int # Windows only -O_TEXT: int # Windows only -O_ASYNC: int # Gnu extension if in C library -O_DIRECT: int # Gnu extension if in C library -O_DIRECTORY: int # Gnu extension if in C library -O_NOFOLLOW: int # Gnu extension if in C library -O_NOATIME: int # Gnu extension if in C library -O_PATH: int # Gnu extension if in C library -O_TMPFILE: int # Gnu extension if in C library -O_LARGEFILE: int # Gnu extension if in C library -O_ACCMODE: int # TODO: when does this exist? + O_DSYNC: Final[int] + O_SYNC: Final[int] + O_NDELAY: Final[int] + O_NONBLOCK: Final[int] + O_NOCTTY: Final[int] + O_CLOEXEC: Final[int] + O_ASYNC: Final[int] # Gnu extension if in C library + O_DIRECTORY: Final[int] # Gnu extension if in C library + O_NOFOLLOW: Final[int] # Gnu extension if in C library + O_ACCMODE: Final[int] # TODO: when does this exist? + +if sys.platform == "linux": + O_RSYNC: Final[int] + O_DIRECT: Final[int] # Gnu extension if in C library + O_NOATIME: Final[int] # Gnu extension if in C library + O_PATH: Final[int] # Gnu extension if in C library + O_TMPFILE: Final[int] # Gnu extension if in C library + O_LARGEFILE: Final[int] # Gnu extension if in C library + +if sys.platform != "linux" and sys.platform != "win32": + O_SHLOCK: Final[int] + O_EXLOCK: Final[int] + +if sys.platform == "darwin": + O_EVTONLY: Final[int] + O_NOFOLLOW_ANY: Final[int] + O_SYMLINK: Final[int] + +if sys.platform != "win32" and sys.version_info >= (3, 15): + NODEV: Final[int] + +if sys.platform == "linux" and sys.version_info >= (3, 15): + AT_NO_AUTOMOUNT: Final[int] + AT_STATX_DONT_SYNC: Final[int] + AT_STATX_FORCE_SYNC: Final[int] + AT_STATX_SYNC_AS_STAT: Final[int] + STATX_ATIME: Final[int] + STATX_BASIC_STATS: Final[int] + STATX_BLOCKS: Final[int] + STATX_BTIME: Final[int] + STATX_CTIME: Final[int] + STATX_DIOALIGN: Final[int] + STATX_GID: Final[int] + STATX_INO: Final[int] + STATX_MNT_ID: Final[int] + STATX_MNT_ID_UNIQUE: Final[int] + STATX_MODE: Final[int] + STATX_MTIME: Final[int] + STATX_NLINK: Final[int] + STATX_SIZE: Final[int] + STATX_TYPE: Final[int] + STATX_UID: Final[int] + +if sys.platform != "win32": + O_FSYNC: Final[int] + +if sys.platform != "linux" and sys.platform != "win32" and sys.version_info >= (3, 13): + O_EXEC: Final[int] + O_SEARCH: Final[int] if sys.platform != "win32" and sys.platform != "darwin": # posix, but apparently missing on macos - ST_APPEND: int - ST_MANDLOCK: int - ST_NOATIME: int - ST_NODEV: int - ST_NODIRATIME: int - ST_NOEXEC: int - ST_NOSUID: int - ST_RDONLY: int - ST_RELATIME: int - ST_SYNCHRONOUS: int - ST_WRITE: int + ST_APPEND: Final[int] + ST_MANDLOCK: Final[int] + ST_NOATIME: Final[int] + ST_NODEV: Final[int] + ST_NODIRATIME: Final[int] + ST_NOEXEC: Final[int] + ST_RELATIME: Final[int] + ST_SYNCHRONOUS: Final[int] + ST_WRITE: Final[int] if sys.platform != "win32": - NGROUPS_MAX: int + NGROUPS_MAX: Final[int] + ST_NOSUID: Final[int] + ST_RDONLY: Final[int] -curdir: str -pardir: str -sep: str -if sys.platform == "win32": - altsep: str -else: - altsep: str | None -extsep: str -pathsep: str -defpath: str -linesep: str -devnull: str -name: str +linesep: Literal["\n", "\r\n"] +name: LiteralString -F_OK: int -R_OK: int -W_OK: int -X_OK: int +F_OK: Final = 0 +R_OK: Final = 4 +W_OK: Final = 2 +X_OK: Final = 1 -_EnvironCodeFunc = Callable[[AnyStr], AnyStr] +_EnvironCodeFunc: TypeAlias = Callable[[AnyStr], AnyStr] class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): encodekey: _EnvironCodeFunc[AnyStr] decodekey: _EnvironCodeFunc[AnyStr] encodevalue: _EnvironCodeFunc[AnyStr] decodevalue: _EnvironCodeFunc[AnyStr] - if sys.version_info >= (3, 9): - def __init__( - self, - data: MutableMapping[AnyStr, AnyStr], - encodekey: _EnvironCodeFunc[AnyStr], - decodekey: _EnvironCodeFunc[AnyStr], - encodevalue: _EnvironCodeFunc[AnyStr], - decodevalue: _EnvironCodeFunc[AnyStr], - ) -> None: ... - else: - putenv: Callable[[AnyStr, AnyStr], None] - unsetenv: Callable[[AnyStr, AnyStr], None] - def __init__( - self, - data: MutableMapping[AnyStr, AnyStr], - encodekey: _EnvironCodeFunc[AnyStr], - decodekey: _EnvironCodeFunc[AnyStr], - encodevalue: _EnvironCodeFunc[AnyStr], - decodevalue: _EnvironCodeFunc[AnyStr], - putenv: Callable[[AnyStr, AnyStr], None], - unsetenv: Callable[[AnyStr, AnyStr], None], - ) -> None: ... - def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... # type: ignore[override] + def __init__( + self, + data: MutableMapping[AnyStr, AnyStr], + encodekey: _EnvironCodeFunc[AnyStr], + decodekey: _EnvironCodeFunc[AnyStr], + encodevalue: _EnvironCodeFunc[AnyStr], + decodevalue: _EnvironCodeFunc[AnyStr], + ) -> None: ... + + @overload + def get(self, key: AnyStr, default: None = None) -> AnyStr | None: ... + @overload + def get(self, key: AnyStr, default: AnyStr) -> AnyStr: ... + @overload + def get(self, key: AnyStr, default: _T) -> AnyStr | _T: ... + + @overload + def pop(self, key: AnyStr) -> AnyStr: ... + @overload + def pop(self, key: AnyStr, default: AnyStr) -> AnyStr: ... + @overload + def pop(self, key: AnyStr, default: _T) -> AnyStr | _T: ... + + def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... def copy(self) -> dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... def __getitem__(self, key: AnyStr) -> AnyStr: ... def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __len__(self) -> int: ... + def __or__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + + # We use @overload instead of a Union for reasons similar to those given for + # overloading MutableMapping.update in stdlib/typing.pyi + # The type: ignore is needed due to incompatible __or__/__ior__ signatures + @overload # type: ignore[misc] + def __ior__(self, other: Mapping[AnyStr, AnyStr]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ... environ: _Environ[str] if sys.platform != "win32": environb: _Environ[bytes] +if sys.version_info >= (3, 14): + def reload_environ() -> None: ... + +if sys.platform == "linux" and sys.version_info >= (3, 15): + def _clearenv() -> None: ... + +if sys.version_info >= (3, 11) or sys.platform != "win32": + EX_OK: Final[int] + if sys.platform != "win32": confstr_names: dict[str, int] pathconf_names: dict[str, int] sysconf_names: dict[str, int] - EX_OK: int - EX_USAGE: int - EX_DATAERR: int - EX_NOINPUT: int - EX_NOUSER: int - EX_NOHOST: int - EX_UNAVAILABLE: int - EX_SOFTWARE: int - EX_OSERR: int - EX_OSFILE: int - EX_CANTCREAT: int - EX_IOERR: int - EX_TEMPFAIL: int - EX_PROTOCOL: int - EX_NOPERM: int - EX_CONFIG: int - EX_NOTFOUND: int - -P_NOWAIT: int -P_NOWAITO: int -P_WAIT: int + EX_USAGE: Final[int] + EX_DATAERR: Final[int] + EX_NOINPUT: Final[int] + EX_NOUSER: Final[int] + EX_NOHOST: Final[int] + EX_UNAVAILABLE: Final[int] + EX_SOFTWARE: Final[int] + EX_OSERR: Final[int] + EX_OSFILE: Final[int] + EX_CANTCREAT: Final[int] + EX_IOERR: Final[int] + EX_TEMPFAIL: Final[int] + EX_PROTOCOL: Final[int] + EX_NOPERM: Final[int] + EX_CONFIG: Final[int] + +# Exists on some Unix platforms, e.g. Solaris. +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + EX_NOTFOUND: Final[int] + +P_NOWAIT: Final[int] +P_NOWAITO: Final[int] +P_WAIT: Final[int] if sys.platform == "win32": - P_DETACH: int - P_OVERLAY: int + P_DETACH: Final[int] + P_OVERLAY: Final[int] # wait()/waitpid() options if sys.platform != "win32": - WNOHANG: int # Unix only - WCONTINUED: int # some Unix systems - WUNTRACED: int # Unix only + WNOHANG: Final[int] # Unix only + WCONTINUED: Final[int] # some Unix systems + WUNTRACED: Final[int] # Unix only -TMP_MAX: int # Undocumented, but used by tempfile +TMP_MAX: Final[int] # Undocumented, but used by tempfile # ----- os classes (structures) ----- @final -class stat_result(structseq[float], Tuple[int, int, int, int, int, int, int, float, float, float]): +class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, float, float, float]): # The constructor of this class takes an iterable of variable length (though it must be at least 10). # # However, this class behaves like a tuple of 10 elements, @@ -295,6 +866,8 @@ class stat_result(structseq[float], Tuple[int, int, int, int, int, int, int, flo # st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. # # More items may be added at the end by some implementations. + __match_args__: Final = ("st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size") + @property def st_mode(self) -> int: ... # protection bits, @property @@ -314,8 +887,16 @@ class stat_result(structseq[float], Tuple[int, int, int, int, int, int, int, flo @property def st_mtime(self) -> float: ... # time of most recent content modification, # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) - @property - def st_ctime(self) -> float: ... + if sys.version_info >= (3, 12) and sys.platform == "win32": + @property + @deprecated("""\ +Use st_birthtime instead to retrieve the file creation time. \ +In the future, this property will contain the last metadata change time.""") + def st_ctime(self) -> float: ... + else: + @property + def st_ctime(self) -> float: ... + @property def st_atime_ns(self) -> int: ... # time of most recent access, in nanoseconds @property @@ -326,9 +907,13 @@ class stat_result(structseq[float], Tuple[int, int, int, int, int, int, int, flo if sys.platform == "win32": @property def st_file_attributes(self) -> int: ... - if sys.version_info >= (3, 8): + @property + def st_reparse_tag(self) -> int: ... + if sys.version_info >= (3, 12): @property - def st_reparse_tag(self) -> int: ... + def st_birthtime(self) -> float: ... # time of file creation in seconds + @property + def st_birthtime_ns(self) -> int: ... # time of file creation in nanoseconds else: @property def st_blocks(self) -> int: ... # number of blocks allocated for file @@ -337,117 +922,114 @@ class stat_result(structseq[float], Tuple[int, int, int, int, int, int, int, flo @property def st_rdev(self) -> int: ... # type of device if an inode device if sys.platform != "linux": - # These properties are available on MacOS, but not on Windows or Ubuntu. + # These properties are available on MacOS, but not Ubuntu. # On other Unix systems (such as FreeBSD), the following attributes may be # available (but may be only filled out if root tries to use them): @property def st_gen(self) -> int: ... # file generation number @property - def st_birthtime(self) -> int: ... # time of file creation + def st_birthtime(self) -> float: ... # time of file creation in seconds if sys.platform == "darwin": @property def st_flags(self) -> int: ... # user defined flags for file - # Atributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`. + # Attributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`. # See https://github.com/python/typeshed/pull/6560#issuecomment-991253327 +# mypy and pyright object to this being both ABC and Protocol. +# At runtime it inherits from ABC and is not a Protocol, but it will be +# on the allowlist for use as a Protocol starting in 3.14. @runtime_checkable -class PathLike(Protocol[_AnyStr_co]): - def __fspath__(self) -> _AnyStr_co: ... +class PathLike(ABC, Protocol[AnyStr_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + __slots__ = () + @abstractmethod + def __fspath__(self) -> AnyStr_co: ... @overload -def listdir(path: str | None = ...) -> list[str]: ... +def listdir(path: StrPath | None = None) -> list[str]: ... @overload -def listdir(path: bytes) -> list[bytes]: ... +def listdir(path: BytesPath) -> list[bytes]: ... @overload def listdir(path: int) -> list[str]: ... -@overload -def listdir(path: PathLike[str]) -> list[str]: ... - -_FdOrAnyPath = Union[int, StrOrBytesPath] @final class DirEntry(Generic[AnyStr]): # This is what the scandir iterator yields # The constructor is hidden - name: AnyStr - path: AnyStr + @property + def name(self) -> AnyStr: ... + @property + def path(self) -> AnyStr: ... def inode(self) -> int: ... - def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... - def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_dir(self, *, follow_symlinks: bool = True) -> bool: ... + def is_file(self, *, follow_symlinks: bool = True) -> bool: ... def is_symlink(self) -> bool: ... - def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... def __fspath__(self) -> AnyStr: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 12): + def is_junction(self) -> bool: ... -if sys.version_info >= (3, 7): - @final - class statvfs_result(structseq[int], Tuple[int, int, int, int, int, int, int, int, int, int, int]): - @property - def f_bsize(self) -> int: ... - @property - def f_frsize(self) -> int: ... - @property - def f_blocks(self) -> int: ... - @property - def f_bfree(self) -> int: ... - @property - def f_bavail(self) -> int: ... - @property - def f_files(self) -> int: ... - @property - def f_ffree(self) -> int: ... - @property - def f_favail(self) -> int: ... - @property - def f_flag(self) -> int: ... - @property - def f_namemax(self) -> int: ... - @property - def f_fsid(self) -> int: ... +@final +class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]): + __match_args__: Final = ( + "f_bsize", + "f_frsize", + "f_blocks", + "f_bfree", + "f_bavail", + "f_files", + "f_ffree", + "f_favail", + "f_flag", + "f_namemax", + ) -else: - @final - class statvfs_result(structseq[int], Tuple[int, int, int, int, int, int, int, int, int, int]): - @property - def f_bsize(self) -> int: ... - @property - def f_frsize(self) -> int: ... - @property - def f_blocks(self) -> int: ... - @property - def f_bfree(self) -> int: ... - @property - def f_bavail(self) -> int: ... - @property - def f_files(self) -> int: ... - @property - def f_ffree(self) -> int: ... - @property - def f_favail(self) -> int: ... - @property - def f_flag(self) -> int: ... - @property - def f_namemax(self) -> int: ... + @property + def f_bsize(self) -> int: ... + @property + def f_frsize(self) -> int: ... + @property + def f_blocks(self) -> int: ... + @property + def f_bfree(self) -> int: ... + @property + def f_bavail(self) -> int: ... + @property + def f_files(self) -> int: ... + @property + def f_ffree(self) -> int: ... + @property + def f_favail(self) -> int: ... + @property + def f_flag(self) -> int: ... + @property + def f_namemax(self) -> int: ... + @property + def f_fsid(self) -> int: ... # ----- os function stubs ----- def fsencode(filename: StrOrBytesPath) -> bytes: ... def fsdecode(filename: StrOrBytesPath) -> str: ... + @overload def fspath(path: str) -> str: ... @overload def fspath(path: bytes) -> bytes: ... @overload def fspath(path: PathLike[AnyStr]) -> AnyStr: ... -def get_exec_path(env: Mapping[str, str] | None = ...) -> list[str]: ... + +def get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: ... def getlogin() -> str: ... def getpid() -> int: ... def getppid() -> int: ... -def strerror(__code: int) -> str: ... -def umask(__mask: int) -> int: ... +def strerror(code: int, /) -> str: ... +def umask(mask: int, /) -> int: ... + @final -class uname_result(structseq[str], Tuple[str, str, str, str, str]): +class uname_result(structseq[str], tuple[str, str, str, str, str]): + __match_args__: Final = ("sysname", "nodename", "release", "version", "machine") + @property def sysname(self) -> str: ... @property @@ -464,9 +1046,9 @@ if sys.platform != "win32": def getegid() -> int: ... def geteuid() -> int: ... def getgid() -> int: ... - def getgrouplist(__user: str, __group: int) -> list[int]: ... + def getgrouplist(user: str, group: int, /) -> list[int]: ... def getgroups() -> list[int]: ... # Unix only, behaves differently on Mac - def initgroups(__username: str, __gid: int) -> None: ... + def initgroups(username: str, gid: int, /) -> None: ... def getpgid(pid: int) -> int: ... def getpgrp() -> int: ... def getpriority(which: int, who: int) -> int: ... @@ -474,21 +1056,23 @@ if sys.platform != "win32": if sys.platform != "darwin": def getresuid() -> tuple[int, int, int]: ... def getresgid() -> tuple[int, int, int]: ... + def getuid() -> int: ... - def setegid(__egid: int) -> None: ... - def seteuid(__euid: int) -> None: ... - def setgid(__gid: int) -> None: ... - def setgroups(__groups: Sequence[int]) -> None: ... + def setegid(egid: int, /) -> None: ... + def seteuid(euid: int, /) -> None: ... + def setgid(gid: int, /) -> None: ... + def setgroups(groups: Sequence[int], /) -> None: ... def setpgrp() -> None: ... - def setpgid(__pid: int, __pgrp: int) -> None: ... - def setregid(__rgid: int, __egid: int) -> None: ... + def setpgid(pid: int, pgrp: int, /) -> None: ... + def setregid(rgid: int, egid: int, /) -> None: ... if sys.platform != "darwin": - def setresgid(rgid: int, egid: int, sgid: int) -> None: ... - def setresuid(ruid: int, euid: int, suid: int) -> None: ... - def setreuid(__ruid: int, __euid: int) -> None: ... - def getsid(__pid: int) -> int: ... + def setresgid(rgid: int, egid: int, sgid: int, /) -> None: ... + def setresuid(ruid: int, euid: int, suid: int, /) -> None: ... + + def setreuid(ruid: int, euid: int, /) -> None: ... + def getsid(pid: int, /) -> int: ... def setsid() -> None: ... - def setuid(__uid: int) -> None: ... + def setuid(uid: int, /) -> None: ... def uname() -> uname_result: ... @overload @@ -502,363 +1086,483 @@ if sys.platform != "win32": @overload def getenvb(key: bytes, default: _T) -> bytes | _T: ... -def putenv(__name: bytes | str, __value: bytes | str) -> None: ... + def putenv(name: StrOrBytesPath, value: StrOrBytesPath, /) -> None: ... + def unsetenv(name: StrOrBytesPath, /) -> None: ... -if sys.platform != "win32" or sys.version_info >= (3, 9): - def unsetenv(__name: bytes | str) -> None: ... +else: + def putenv(name: str, value: str, /) -> None: ... + def unsetenv(name: str, /) -> None: ... -_Opener = Callable[[str, int], int] +_Opener: TypeAlias = Callable[[str, int], int] @overload def fdopen( fd: int, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., -) -> _TextIOWrapper: ... + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> TextIOWrapper: ... @overload def fdopen( fd: int, mode: OpenBinaryMode, buffering: Literal[0], - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> FileIO: ... @overload def fdopen( fd: int, mode: OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BufferedRandom: ... @overload def fdopen( fd: int, mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BufferedWriter: ... @overload def fdopen( fd: int, mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BufferedReader: ... @overload def fdopen( fd: int, mode: OpenBinaryMode, - buffering: int, - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> BinaryIO: ... @overload def fdopen( fd: int, mode: str, - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, ) -> IO[Any]: ... + def close(fd: int) -> None: ... -def closerange(__fd_low: int, __fd_high: int) -> None: ... +def closerange(fd_low: int, fd_high: int, /) -> None: ... def device_encoding(fd: int) -> str | None: ... -def dup(__fd: int) -> int: ... +def dup(fd: int, /) -> int: ... +def dup2(fd: int, fd2: int, inheritable: bool = True) -> int: ... +def fstat(fd: int) -> stat_result: ... +def ftruncate(fd: int, length: int, /) -> None: ... +def fsync(fd: FileDescriptorLike) -> None: ... +def isatty(fd: int, /) -> bool: ... -if sys.version_info >= (3, 7): - def dup2(fd: int, fd2: int, inheritable: bool = ...) -> int: ... +if sys.platform != "win32" and sys.version_info >= (3, 11): + def login_tty(fd: int, /) -> None: ... + +if sys.version_info >= (3, 11): + def lseek(fd: int, position: int, whence: int, /) -> int: ... else: - def dup2(fd: int, fd2: int, inheritable: bool = ...) -> None: ... + def lseek(fd: int, position: int, how: int, /) -> int: ... -def fstat(fd: int) -> stat_result: ... -def ftruncate(__fd: int, __length: int) -> None: ... -def fsync(fd: FileDescriptorLike) -> None: ... -def isatty(__fd: int) -> bool: ... -def lseek(__fd: int, __position: int, __how: int) -> int: ... -def open(path: StrOrBytesPath, flags: int, mode: int = ..., *, dir_fd: int | None = ...) -> int: ... +def open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: ... def pipe() -> tuple[int, int]: ... -def read(__fd: int, __length: int) -> bytes: ... +def read(fd: int, length: int, /) -> bytes: ... + +if sys.version_info >= (3, 12) or sys.platform != "win32": + def get_blocking(fd: int, /) -> bool: ... + def set_blocking(fd: int, blocking: bool, /) -> None: ... if sys.platform != "win32": - # Unix only - def fchmod(fd: int, mode: int) -> None: ... def fchown(fd: int, uid: int, gid: int) -> None: ... - def fpathconf(__fd: int, __name: str | int) -> int: ... - def fstatvfs(__fd: int) -> statvfs_result: ... - def get_blocking(__fd: int) -> bool: ... - def set_blocking(__fd: int, __blocking: bool) -> None: ... - def lockf(__fd: int, __command: int, __length: int) -> None: ... + def fpathconf(fd: int, name: str | int, /) -> int: ... + def fstatvfs(fd: int, /) -> statvfs_result: ... + def lockf(fd: int, command: int, length: int, /) -> None: ... def openpty() -> tuple[int, int]: ... # some flavors of Unix if sys.platform != "darwin": def fdatasync(fd: FileDescriptorLike) -> None: ... - def pipe2(__flags: int) -> tuple[int, int]: ... # some flavors of Unix - def posix_fallocate(fd: int, offset: int, length: int) -> None: ... - def posix_fadvise(fd: int, offset: int, length: int, advice: int) -> None: ... - def pread(__fd: int, __length: int, __offset: int) -> bytes: ... - def pwrite(__fd: int, __buffer: bytes, __offset: int) -> int: ... - @overload - def sendfile(out_fd: int, in_fd: int, offset: int | None, count: int) -> int: ... - @overload - def sendfile( - out_fd: int, - in_fd: int, - offset: int, - count: int, - headers: Sequence[bytes] = ..., - trailers: Sequence[bytes] = ..., - flags: int = ..., - ) -> int: ... # FreeBSD and Mac OS X only - def readv(__fd: int, __buffers: Sequence[bytearray]) -> int: ... - def writev(__fd: int, __buffers: Sequence[bytes]) -> int: ... + def pipe2(flags: int, /) -> tuple[int, int]: ... # some flavors of Unix + def posix_fallocate(fd: int, offset: int, length: int, /) -> None: ... + def posix_fadvise(fd: int, offset: int, length: int, advice: int, /) -> None: ... + + def pread(fd: int, length: int, offset: int, /) -> bytes: ... + def pwrite(fd: int, buffer: ReadableBuffer, offset: int, /) -> int: ... + # In CI, stubtest sometimes reports that these are available on MacOS, sometimes not + def preadv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], offset: int, flags: int = 0, /) -> int: ... + def pwritev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], offset: int, flags: int = 0, /) -> int: ... + if sys.platform != "darwin": + RWF_APPEND: Final[int] + RWF_DSYNC: Final[int] + RWF_SYNC: Final[int] + RWF_HIPRI: Final[int] + RWF_NOWAIT: Final[int] + + if sys.platform == "linux": + def sendfile(out_fd: FileDescriptor, in_fd: FileDescriptor, offset: int | None, count: int) -> int: ... + else: + def sendfile( + out_fd: FileDescriptor, + in_fd: FileDescriptor, + offset: int, + count: int, + headers: Sequence[ReadableBuffer] = (), + trailers: Sequence[ReadableBuffer] = (), + flags: int = 0, + ) -> int: ... # FreeBSD and Mac OS X only + + def readv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], /) -> int: ... + def writev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], /) -> int: ... + +if sys.version_info >= (3, 14): + def readinto(fd: int, buffer: ReadableBuffer, /) -> int: ... @final -class terminal_size(structseq[int], Tuple[int, int]): +class terminal_size(structseq[int], tuple[int, int]): + __match_args__: Final = ("columns", "lines") + @property def columns(self) -> int: ... @property def lines(self) -> int: ... -def get_terminal_size(fd: int = ...) -> terminal_size: ... -def get_inheritable(__fd: int) -> bool: ... -def set_inheritable(__fd: int, __inheritable: bool) -> None: ... +def get_terminal_size(fd: int = ..., /) -> terminal_size: ... +def get_inheritable(fd: int, /) -> bool: ... +def set_inheritable(fd: int, inheritable: bool, /) -> None: ... + +if sys.platform == "win32": + def get_handle_inheritable(handle: int, /) -> bool: ... + def set_handle_inheritable(handle: int, inheritable: bool, /) -> None: ... if sys.platform != "win32": # Unix only - def tcgetpgrp(__fd: int) -> int: ... - def tcsetpgrp(__fd: int, __pgid: int) -> None: ... - def ttyname(__fd: int) -> str: ... + def tcgetpgrp(fd: int, /) -> int: ... + def tcsetpgrp(fd: int, pgid: int, /) -> None: ... + def ttyname(fd: int, /) -> str: ... -def write(__fd: int, __data: bytes) -> int: ... +def write(fd: int, data: ReadableBuffer, /) -> int: ... def access( - path: _FdOrAnyPath, mode: int, *, dir_fd: int | None = ..., effective_ids: bool = ..., follow_symlinks: bool = ... + path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True ) -> bool: ... -def chdir(path: _FdOrAnyPath) -> None: ... +def chdir(path: FileDescriptorOrPath) -> None: ... if sys.platform != "win32": def fchdir(fd: FileDescriptorLike) -> None: ... def getcwd() -> str: ... def getcwdb() -> bytes: ... -def chmod(path: _FdOrAnyPath, mode: int, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> None: ... +def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None: ... if sys.platform != "win32" and sys.platform != "linux": - def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = ...) -> None: ... # some flavors of Unix + def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = True) -> None: ... # some flavors of Unix def lchflags(path: StrOrBytesPath, flags: int) -> None: ... - def lchmod(path: StrOrBytesPath, mode: int) -> None: ... if sys.platform != "win32": def chroot(path: StrOrBytesPath) -> None: ... - def chown(path: _FdOrAnyPath, uid: int, gid: int, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> None: ... + def chown( + path: FileDescriptorOrPath, uid: int, gid: int, *, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> None: ... def lchown(path: StrOrBytesPath, uid: int, gid: int) -> None: ... def link( src: StrOrBytesPath, dst: StrOrBytesPath, *, - src_dir_fd: int | None = ..., - dst_dir_fd: int | None = ..., - follow_symlinks: bool = ..., + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + follow_symlinks: bool = True, ) -> None: ... -def lstat(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> stat_result: ... -def mkdir(path: StrOrBytesPath, mode: int = ..., *, dir_fd: int | None = ...) -> None: ... +def lstat(path: StrOrBytesPath, *, dir_fd: int | None = None) -> stat_result: ... +def mkdir(path: StrOrBytesPath, mode: int = 0o777, *, dir_fd: int | None = None) -> None: ... if sys.platform != "win32": - def mkfifo(path: StrOrBytesPath, mode: int = ..., *, dir_fd: int | None = ...) -> None: ... # Unix only + def mkfifo(path: StrOrBytesPath, mode: int = 0o666, *, dir_fd: int | None = None) -> None: ... # Unix only -def makedirs(name: StrOrBytesPath, mode: int = ..., exist_ok: bool = ...) -> None: ... +if sys.version_info >= (3, 15): + def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False, *, parent_mode: int | None = None) -> None: ... + +else: + def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False) -> None: ... if sys.platform != "win32": - def mknod(path: StrOrBytesPath, mode: int = ..., device: int = ..., *, dir_fd: int | None = ...) -> None: ... - def major(__device: int) -> int: ... - def minor(__device: int) -> int: ... - def makedev(__major: int, __minor: int) -> int: ... - def pathconf(path: _FdOrAnyPath, name: str | int) -> int: ... # Unix only - -def readlink(path: AnyStr | PathLike[AnyStr], *, dir_fd: int | None = ...) -> AnyStr: ... -def remove(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... + def mknod(path: StrOrBytesPath, mode: int = 0o600, device: int = 0, *, dir_fd: int | None = None) -> None: ... + def major(device: int, /) -> int: ... + def minor(device: int, /) -> int: ... + def makedev(major: int, minor: int, /) -> int: ... + def pathconf(path: FileDescriptorOrPath, name: str | int) -> int: ... # Unix only + +def readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = None) -> AnyStr: ... +def remove(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... def removedirs(name: StrOrBytesPath) -> None: ... -def rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = ..., dst_dir_fd: int | None = ...) -> None: ... +def rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None) -> None: ... def renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: ... -def replace(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = ..., dst_dir_fd: int | None = ...) -> None: ... -def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... +def replace( + src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None +) -> None: ... +def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... -class _ScandirIterator(Iterator[DirEntry[AnyStr]], AbstractContextManager[_ScandirIterator[AnyStr]]): +@final +@type_check_only +class _ScandirIterator(Generic[AnyStr]): + def __del__(self) -> None: ... + def __iter__(self) -> Self: ... def __next__(self) -> DirEntry[AnyStr]: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... def close(self) -> None: ... -if sys.version_info >= (3, 7): - @overload - def scandir(path: None = ...) -> _ScandirIterator[str]: ... - @overload - def scandir(path: int) -> _ScandirIterator[str]: ... - @overload - def scandir(path: AnyStr | PathLike[AnyStr]) -> _ScandirIterator[AnyStr]: ... +@overload +def scandir(path: None = None) -> _ScandirIterator[str]: ... +@overload +def scandir(path: int) -> _ScandirIterator[str]: ... +@overload +def scandir(path: GenericPath[AnyStr]) -> _ScandirIterator[AnyStr]: ... -else: - @overload - def scandir(path: None = ...) -> _ScandirIterator[str]: ... - @overload - def scandir(path: AnyStr | PathLike[AnyStr]) -> _ScandirIterator[AnyStr]: ... +def stat(path: FileDescriptorOrPath, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> stat_result: ... -def stat(path: _FdOrAnyPath, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> stat_result: ... +if sys.platform != "win32": + def statvfs(path: FileDescriptorOrPath) -> statvfs_result: ... # Unix only -if sys.version_info < (3, 7): - @overload - def stat_float_times() -> bool: ... - @overload - def stat_float_times(__newvalue: bool) -> None: ... +if sys.platform == "linux" and sys.version_info >= (3, 15): + @final + class statx_result: + @property + def stx_mask(self) -> int: ... + @property + def stx_blksize(self) -> int: ... + @property + def stx_attributes(self) -> int: ... + @property + def stx_attributes_mask(self) -> int: ... + @property + def stx_rdev_major(self) -> int: ... + @property + def stx_rdev_minor(self) -> int: ... + @property + def stx_rdev(self) -> int: ... + @property + def stx_dev_major(self) -> int: ... + @property + def stx_dev_minor(self) -> int: ... + @property + def stx_dev(self) -> int: ... + @property + def stx_mode(self) -> int | None: ... + @property + def stx_nlink(self) -> int | None: ... + @property + def stx_uid(self) -> int | None: ... + @property + def stx_gid(self) -> int | None: ... + @property + def stx_ino(self) -> int | None: ... + @property + def stx_size(self) -> int | None: ... + @property + def stx_blocks(self) -> int | None: ... + @property + def stx_atime(self) -> float | None: ... + @property + def stx_atime_ns(self) -> int | None: ... + @property + def stx_btime(self) -> float | None: ... + @property + def stx_btime_ns(self) -> int | None: ... + @property + def stx_ctime(self) -> float | None: ... + @property + def stx_ctime_ns(self) -> int | None: ... + @property + def stx_mtime(self) -> float | None: ... + @property + def stx_mtime_ns(self) -> int | None: ... + @property + def stx_mnt_id(self) -> int | None: ... + @property + def stx_dio_mem_align(self) -> int | None: ... + @property + def stx_dio_offset_align(self) -> int | None: ... -if sys.platform != "win32": - def statvfs(path: _FdOrAnyPath) -> statvfs_result: ... # Unix only + def statx( + path: FileDescriptorOrPath, mask: int, *, flags: int = 0, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> statx_result: ... -def symlink(src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = ..., *, dir_fd: int | None = ...) -> None: ... +def symlink( + src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = False, *, dir_fd: int | None = None +) -> None: ... if sys.platform != "win32": def sync() -> None: ... # Unix only -def truncate(path: _FdOrAnyPath, length: int) -> None: ... # Unix only up to version 3.4 -def unlink(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... +def truncate(path: FileDescriptorOrPath, length: int) -> None: ... # Unix only up to version 3.4 +def unlink(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... def utime( - path: _FdOrAnyPath, - times: tuple[int, int] | tuple[float, float] | None = ..., + path: FileDescriptorOrPath, + times: tuple[int, int] | tuple[float, float] | None = None, *, ns: tuple[int, int] = ..., - dir_fd: int | None = ..., - follow_symlinks: bool = ..., + dir_fd: int | None = None, + follow_symlinks: bool = True, ) -> None: ... -_OnError = Callable[[OSError], Any] +_OnError: TypeAlias = Callable[[OSError], object] def walk( - top: AnyStr | PathLike[AnyStr], topdown: bool = ..., onerror: _OnError | None = ..., followlinks: bool = ... + top: GenericPath[AnyStr], topdown: bool = True, onerror: _OnError | None = None, followlinks: bool = False ) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ... if sys.platform != "win32": - if sys.version_info >= (3, 7): - @overload - def fwalk( - top: StrPath = ..., - topdown: bool = ..., - onerror: _OnError | None = ..., - *, - follow_symlinks: bool = ..., - dir_fd: int | None = ..., - ) -> Iterator[tuple[str, list[str], list[str], int]]: ... - @overload - def fwalk( - top: bytes, - topdown: bool = ..., - onerror: _OnError | None = ..., - *, - follow_symlinks: bool = ..., - dir_fd: int | None = ..., - ) -> Iterator[tuple[bytes, list[bytes], list[bytes], int]]: ... - else: - def fwalk( - top: StrPath = ..., - topdown: bool = ..., - onerror: _OnError | None = ..., - *, - follow_symlinks: bool = ..., - dir_fd: int | None = ..., - ) -> Iterator[tuple[str, list[str], list[str], int]]: ... + @overload + def fwalk( + top: StrPath = ".", + topdown: bool = True, + onerror: _OnError | None = None, + *, + follow_symlinks: bool = False, + dir_fd: int | None = None, + ) -> Iterator[tuple[str, list[str], list[str], int]]: ... + @overload + def fwalk( + top: BytesPath, + topdown: bool = True, + onerror: _OnError | None = None, + *, + follow_symlinks: bool = False, + dir_fd: int | None = None, + ) -> Iterator[tuple[bytes, list[bytes], list[bytes], int]]: ... + if sys.platform == "linux": - def getxattr(path: _FdOrAnyPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = ...) -> bytes: ... - def listxattr(path: _FdOrAnyPath | None = ..., *, follow_symlinks: bool = ...) -> list[str]: ... - def removexattr(path: _FdOrAnyPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = ...) -> None: ... + def getxattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> bytes: ... + def listxattr(path: FileDescriptorOrPath | None = None, *, follow_symlinks: bool = True) -> list[str]: ... + def removexattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... def setxattr( - path: _FdOrAnyPath, attribute: StrOrBytesPath, value: bytes, flags: int = ..., *, follow_symlinks: bool = ... + path: FileDescriptorOrPath, + attribute: StrOrBytesPath, + value: ReadableBuffer, + flags: int = 0, + *, + follow_symlinks: bool = True, ) -> None: ... -def abort() -> NoReturn: ... +def abort() -> Never: ... # These are defined as execl(file, *args) but the first *arg is mandatory. -def execl(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: StrOrBytesPath) -> NoReturn: ... -def execlp(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: StrOrBytesPath) -> NoReturn: ... +def execl(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> Never: ... +def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> Never: ... # These are: execle(file, *args, env) but env is pulled from the last element of the args. -def execle(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoReturn: ... -def execlpe(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoReturn: ... +def execle(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]]) -> Never: ... +def execlpe( + file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]] +) -> Never: ... # The docs say `args: tuple or list of strings` # The implementation enforces tuple or list so we can't use Sequence. # Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference # in practice, and doing so would explode the number of combinations in this already long union. # All these combinations are necessary due to list being invariant. -_ExecVArgs = Union[ - Tuple[StrOrBytesPath, ...], - List[bytes], - List[str], - List[PathLike[Any]], - List[Union[bytes, str]], - List[Union[bytes, PathLike[Any]]], - List[Union[str, PathLike[Any]]], - List[Union[bytes, str, PathLike[Any]]], -] -_ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] - -def execv(__path: StrOrBytesPath, __argv: _ExecVArgs) -> NoReturn: ... -def execve(path: _FdOrAnyPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... -def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: ... -def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... -def _exit(status: int) -> NoReturn: ... -def kill(__pid: int, __signal: int) -> None: ... +_ExecVArgs: TypeAlias = ( + tuple[StrOrBytesPath, ...] + | list[bytes] + | list[str] + | list[PathLike[Any]] + | list[bytes | str] + | list[bytes | PathLike[Any]] + | list[str | PathLike[Any]] + | list[bytes | str | PathLike[Any]] +) +# Depending on the OS, the keys and values are passed either to +# PyUnicode_FSDecoder (which accepts str | ReadableBuffer) or to +# PyUnicode_FSConverter (which accepts StrOrBytesPath). For simplicity, +# we limit to str | bytes. +_ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] + +def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> Never: ... +def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> Never: ... +def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> Never: ... +def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> Never: ... +def _exit(status: int) -> Never: ... +def kill(pid: int, signal: int, /) -> None: ... if sys.platform != "win32": # Unix only def fork() -> int: ... def forkpty() -> tuple[int, int]: ... # some flavors of Unix - def killpg(__pgid: int, __signal: int) -> None: ... - def nice(__increment: int) -> int: ... - if sys.platform != "darwin": - def plock(op: int) -> None: ... # ???op is int? - -class _wrap_close(_TextIOWrapper): - def __init__(self, stream: _TextIOWrapper, proc: Popen[str]) -> None: ... - def close(self) -> int | None: ... # type: ignore[override] - -def popen(cmd: str, mode: str = ..., buffering: int = ...) -> _wrap_close: ... + def killpg(pgid: int, signal: int, /) -> None: ... + def nice(increment: int, /) -> int: ... + if sys.platform != "darwin" and sys.platform != "linux": + def plock(op: int, /) -> None: ... + +class _wrap_close: + def __init__(self, stream: TextIOWrapper, proc: Popen[str]) -> None: ... + def close(self) -> int | None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + # Methods below here don't exist directly on the _wrap_close object, but + # are copied from the wrapped TextIOWrapper object via __getattr__. + # The full set of TextIOWrapper methods are technically available this way, + # but undocumented. Only a subset are currently included here. + def read(self, size: int | None = -1, /) -> str: ... + def readable(self) -> bool: ... + def readline(self, size: int = -1, /) -> str: ... + def readlines(self, hint: int = -1, /) -> list[str]: ... + def writable(self) -> bool: ... + def write(self, s: str, /) -> int: ... + def writelines(self, lines: Iterable[str], /) -> None: ... + +@deprecated("Soft deprecated. Use the subprocess module instead.") +def popen(cmd: str, mode: str = "r", buffering: int = -1) -> _wrap_close: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise sig if sys.platform != "win32": + @deprecated("Soft deprecated. Use the subprocess module instead.") def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... - else: - def spawnv(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs) -> int: ... - def spawnve(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs, __env: _ExecEnv) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... def system(command: StrOrBytesPath) -> int: ... + @final -class times_result(structseq[float], Tuple[float, float, float, float, float]): +class times_result(structseq[float], tuple[float, float, float, float, float]): + __match_args__: Final = ("user", "system", "children_user", "children_system", "elapsed") + @property def user(self) -> float: ... @property @@ -871,20 +1575,29 @@ class times_result(structseq[float], Tuple[float, float, float, float, float]): def elapsed(self) -> float: ... def times() -> times_result: ... -def waitpid(__pid: int, __options: int) -> tuple[int, int]: ... +def waitpid(pid: int, options: int, /) -> tuple[int, int]: ... if sys.platform == "win32": - def startfile(path: StrOrBytesPath, operation: str | None = ...) -> None: ... + def startfile( + filepath: StrOrBytesPath, operation: str = ..., arguments: str = "", cwd: StrOrBytesPath | None = None, show_cmd: int = 1 + ) -> None: ... else: + @deprecated("Soft deprecated. Use the subprocess module instead.") def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature + @deprecated("Soft deprecated. Use the subprocess module instead.") def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... def wait() -> tuple[int, int]: ... # Unix only - if sys.platform != "darwin": + # Added to MacOS in 3.13 + if sys.platform != "darwin" or sys.version_info >= (3, 13): @final - class waitid_result(structseq[int], Tuple[int, int, int, int, int]): + class waitid_result(structseq[int], tuple[int, int, int, int, int]): + __match_args__: Final = ("si_pid", "si_uid", "si_signo", "si_status", "si_code") + @property def si_pid(self) -> int: ... @property @@ -895,10 +1608,14 @@ else: def si_status(self) -> int: ... @property def si_code(self) -> int: ... - def waitid(idtype: int, ident: int, options: int) -> waitid_result: ... - def wait3(options: int) -> tuple[int, int, Any]: ... - def wait4(pid: int, options: int) -> tuple[int, int, Any]: ... - def WCOREDUMP(__status: int) -> bool: ... + + def waitid(idtype: int, ident: int, options: int, /) -> waitid_result | None: ... + + from resource import struct_rusage + + def wait3(options: int) -> tuple[int, int, struct_rusage]: ... + def wait4(pid: int, options: int) -> tuple[int, int, struct_rusage]: ... + def WCOREDUMP(status: int, /) -> bool: ... def WIFCONTINUED(status: int) -> bool: ... def WIFSTOPPED(status: int) -> bool: ... def WIFSIGNALED(status: int) -> bool: ... @@ -906,66 +1623,142 @@ else: def WEXITSTATUS(status: int) -> int: ... def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... - if sys.version_info >= (3, 8): + + if sys.version_info >= (3, 15): + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int | None = None, # None allowed starting in 3.15 + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] | None = None, # None allowed starting in 3.15 + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int | None = None, # None allowed starting in 3.15 + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] | None = None, # None allowed starting in 3.15 + ) -> int: ... + elif sys.version_info >= (3, 13): + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, # None allowed starting in 3.13 + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, # None allowed starting in 3.13 + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., + ) -> int: ... + else: def posix_spawn( path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, + /, *, - file_actions: Sequence[Tuple[Any, ...]] | None = ..., - setpgroup: int | None = ..., - resetids: bool = ..., - setsid: bool = ..., - setsigmask: Iterable[int] = ..., - setsigdef: Iterable[int] = ..., - scheduler: tuple[Any, sched_param] | None = ..., + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., ) -> int: ... def posix_spawnp( path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, + /, *, - file_actions: Sequence[Tuple[Any, ...]] | None = ..., - setpgroup: int | None = ..., - resetids: bool = ..., - setsid: bool = ..., - setsigmask: Iterable[int] = ..., - setsigdef: Iterable[int] = ..., - scheduler: tuple[Any, sched_param] | None = ..., + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., ) -> int: ... + POSIX_SPAWN_OPEN: Final = 0 + POSIX_SPAWN_CLOSE: Final = 1 + POSIX_SPAWN_DUP2: Final = 2 + if sys.platform != "win32": @final - class sched_param(structseq[int], Tuple[int]): - def __new__(cls, sched_priority: int) -> sched_param: ... + class sched_param(structseq[int], tuple[int]): + __match_args__: Final = ("sched_priority",) + + def __new__(cls, sched_priority: int) -> Self: ... @property def sched_priority(self) -> int: ... + def sched_get_priority_min(policy: int) -> int: ... # some flavors of Unix def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix def sched_yield() -> None: ... # some flavors of Unix if sys.platform != "darwin": - def sched_setscheduler(pid: int, policy: int, param: sched_param) -> None: ... # some flavors of Unix - def sched_getscheduler(pid: int) -> int: ... # some flavors of Unix - def sched_rr_get_interval(pid: int) -> float: ... # some flavors of Unix - def sched_setparam(pid: int, param: sched_param) -> None: ... # some flavors of Unix - def sched_getparam(pid: int) -> sched_param: ... # some flavors of Unix - def sched_setaffinity(pid: int, mask: Iterable[int]) -> None: ... # some flavors of Unix - def sched_getaffinity(pid: int) -> set[int]: ... # some flavors of Unix + def sched_setscheduler(pid: int, policy: int, param: sched_param, /) -> None: ... # some flavors of Unix + def sched_getscheduler(pid: int, /) -> int: ... # some flavors of Unix + def sched_rr_get_interval(pid: int, /) -> float: ... # some flavors of Unix + def sched_setparam(pid: int, param: sched_param, /) -> None: ... # some flavors of Unix + def sched_getparam(pid: int, /) -> sched_param: ... # some flavors of Unix + def sched_setaffinity(pid: int, mask: Iterable[int], /) -> None: ... # some flavors of Unix + def sched_getaffinity(pid: int, /) -> set[int]: ... # some flavors of Unix def cpu_count() -> int | None: ... +if sys.version_info >= (3, 13): + # Documented to return `int | None`, but falls back to `len(sched_getaffinity(0))` when + # available. See https://github.com/python/cpython/blob/417c130/Lib/os.py#L1175-L1186. + if sys.platform != "win32" and sys.platform != "darwin": + def process_cpu_count() -> int: ... + else: + def process_cpu_count() -> int | None: ... + if sys.platform != "win32": # Unix only - def confstr(__name: str | int) -> str | None: ... + def confstr(name: str | int, /) -> str | None: ... def getloadavg() -> tuple[float, float, float]: ... - def sysconf(__name: str | int) -> int: ... + def sysconf(name: str | int, /) -> int: ... if sys.platform == "linux": - def getrandom(size: int, flags: int = ...) -> bytes: ... + def getrandom(size: int, flags: int = 0) -> bytes: ... -def urandom(__size: int) -> bytes: ... +def urandom(size: int, /) -> bytes: ... -if sys.version_info >= (3, 7) and sys.platform != "win32": +if sys.platform != "win32": def register_at_fork( *, before: Callable[..., Any] | None = ..., @@ -973,34 +1766,113 @@ if sys.version_info >= (3, 7) and sys.platform != "win32": after_in_child: Callable[..., Any] | None = ..., ) -> None: ... -if sys.version_info >= (3, 8): - if sys.platform == "win32": - class _AddedDllDirectory: - path: str | None - def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], Any]) -> None: ... - def close(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... - def add_dll_directory(path: str) -> _AddedDllDirectory: ... - if sys.platform == "linux": - MFD_CLOEXEC: int - MFD_ALLOW_SEALING: int - MFD_HUGETLB: int - MFD_HUGE_SHIFT: int - MFD_HUGE_MASK: int - MFD_HUGE_64KB: int - MFD_HUGE_512KB: int - MFD_HUGE_1MB: int - MFD_HUGE_2MB: int - MFD_HUGE_8MB: int - MFD_HUGE_16MB: int - MFD_HUGE_32MB: int - MFD_HUGE_256MB: int - MFD_HUGE_512MB: int - MFD_HUGE_1GB: int - MFD_HUGE_2GB: int - MFD_HUGE_16GB: int - def memfd_create(name: str, flags: int = ...) -> int: ... - -if sys.version_info >= (3, 9): - def waitstatus_to_exitcode(status: int) -> int: ... +if sys.platform == "win32": + class _AddedDllDirectory: + path: str | None + def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], object]) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + + def add_dll_directory(path: str) -> _AddedDllDirectory: ... + +if sys.platform == "linux": + MFD_CLOEXEC: Final[int] + MFD_ALLOW_SEALING: Final[int] + MFD_HUGETLB: Final[int] + MFD_HUGE_SHIFT: Final[int] + MFD_HUGE_MASK: Final[int] + MFD_HUGE_64KB: Final[int] + MFD_HUGE_512KB: Final[int] + MFD_HUGE_1MB: Final[int] + MFD_HUGE_2MB: Final[int] + MFD_HUGE_8MB: Final[int] + MFD_HUGE_16MB: Final[int] + MFD_HUGE_32MB: Final[int] + MFD_HUGE_256MB: Final[int] + MFD_HUGE_512MB: Final[int] + MFD_HUGE_1GB: Final[int] + MFD_HUGE_2GB: Final[int] + MFD_HUGE_16GB: Final[int] + def memfd_create(name: str, flags: int = ...) -> int: ... + def copy_file_range(src: int, dst: int, count: int, offset_src: int | None = None, offset_dst: int | None = None) -> int: ... + +def waitstatus_to_exitcode(status: int) -> int: ... + +if sys.platform == "linux": + def pidfd_open(pid: int, flags: int = 0) -> int: ... + +if sys.version_info >= (3, 12) and sys.platform == "linux": + PIDFD_NONBLOCK: Final = 2048 + +if sys.version_info >= (3, 12) and sys.platform == "win32": + def listdrives() -> list[str]: ... + def listmounts(volume: str) -> list[str]: ... + def listvolumes() -> list[str]: ... + +if sys.platform == "linux": + EFD_CLOEXEC: Final[int] + EFD_NONBLOCK: Final[int] + EFD_SEMAPHORE: Final[int] + SPLICE_F_MORE: Final[int] + SPLICE_F_MOVE: Final[int] + SPLICE_F_NONBLOCK: Final[int] + def eventfd(initval: int, flags: int = 524288) -> FileDescriptor: ... + def eventfd_read(fd: FileDescriptor) -> int: ... + def eventfd_write(fd: FileDescriptor, value: int) -> None: ... + def splice( + src: FileDescriptor, + dst: FileDescriptor, + count: int, + offset_src: int | None = None, + offset_dst: int | None = None, + flags: int = 0, + ) -> int: ... + +if sys.version_info >= (3, 12) and sys.platform == "linux": + CLONE_FILES: Final[int] + CLONE_FS: Final[int] + CLONE_NEWCGROUP: Final[int] # Linux 4.6+ + CLONE_NEWIPC: Final[int] # Linux 2.6.19+ + CLONE_NEWNET: Final[int] # Linux 2.6.24+ + CLONE_NEWNS: Final[int] + CLONE_NEWPID: Final[int] # Linux 3.8+ + CLONE_NEWTIME: Final[int] # Linux 5.6+ + CLONE_NEWUSER: Final[int] # Linux 3.8+ + CLONE_NEWUTS: Final[int] # Linux 2.6.19+ + CLONE_SIGHAND: Final[int] + CLONE_SYSVSEM: Final[int] # Linux 2.6.26+ + CLONE_THREAD: Final[int] + CLONE_VM: Final[int] + def unshare(flags: int) -> None: ... + def setns(fd: FileDescriptorLike, nstype: int = 0) -> None: ... + +if sys.version_info >= (3, 13) and sys.platform != "win32": + def posix_openpt(oflag: int, /) -> int: ... + def grantpt(fd: FileDescriptorLike, /) -> None: ... + def unlockpt(fd: FileDescriptorLike, /) -> None: ... + def ptsname(fd: FileDescriptorLike, /) -> str: ... + +if sys.version_info >= (3, 13) and sys.platform == "linux": + TFD_TIMER_ABSTIME: Final = 1 + TFD_TIMER_CANCEL_ON_SET: Final = 2 + TFD_NONBLOCK: Final[int] + TFD_CLOEXEC: Final[int] + POSIX_SPAWN_CLOSEFROM: Final[int] + + def timerfd_create(clockid: int, /, *, flags: int = 0) -> int: ... + def timerfd_settime( + fd: FileDescriptor, /, *, flags: int = 0, initial: float = 0.0, interval: float = 0.0 + ) -> tuple[float, float]: ... + def timerfd_settime_ns(fd: FileDescriptor, /, *, flags: int = 0, initial: int = 0, interval: int = 0) -> tuple[int, int]: ... + def timerfd_gettime(fd: FileDescriptor, /) -> tuple[float, float]: ... + def timerfd_gettime_ns(fd: FileDescriptor, /) -> tuple[int, int]: ... + +if sys.version_info >= (3, 13) or sys.platform != "win32": + # Added to Windows in 3.13. + def fchmod(fd: int, mode: int) -> None: ... + +if sys.platform != "linux": + if sys.version_info >= (3, 13) or sys.platform != "win32": + # Added to Windows in 3.13. + def lchmod(path: StrOrBytesPath, mode: int) -> None: ... diff --git a/stdlib/os/path.pyi b/stdlib/os/path.pyi index 4533738983f7..dc688a9f877f 100644 --- a/stdlib/os/path.pyi +++ b/stdlib/os/path.pyi @@ -2,5 +2,7 @@ import sys if sys.platform == "win32": from ntpath import * + from ntpath import __all__ as __all__ else: from posixpath import * + from posixpath import __all__ as __all__ diff --git a/stdlib/ossaudiodev.pyi b/stdlib/ossaudiodev.pyi index f221c95b8036..f8230b4f0212 100644 --- a/stdlib/ossaudiodev.pyi +++ b/stdlib/ossaudiodev.pyi @@ -1,131 +1,132 @@ -from typing import Any, overload -from typing_extensions import Literal +import sys +from typing import Any, Final, Literal, overload -AFMT_AC3: int -AFMT_A_LAW: int -AFMT_IMA_ADPCM: int -AFMT_MPEG: int -AFMT_MU_LAW: int -AFMT_QUERY: int -AFMT_S16_BE: int -AFMT_S16_LE: int -AFMT_S16_NE: int -AFMT_S8: int -AFMT_U16_BE: int -AFMT_U16_LE: int -AFMT_U8: int -SNDCTL_COPR_HALT: int -SNDCTL_COPR_LOAD: int -SNDCTL_COPR_RCODE: int -SNDCTL_COPR_RCVMSG: int -SNDCTL_COPR_RDATA: int -SNDCTL_COPR_RESET: int -SNDCTL_COPR_RUN: int -SNDCTL_COPR_SENDMSG: int -SNDCTL_COPR_WCODE: int -SNDCTL_COPR_WDATA: int -SNDCTL_DSP_BIND_CHANNEL: int -SNDCTL_DSP_CHANNELS: int -SNDCTL_DSP_GETBLKSIZE: int -SNDCTL_DSP_GETCAPS: int -SNDCTL_DSP_GETCHANNELMASK: int -SNDCTL_DSP_GETFMTS: int -SNDCTL_DSP_GETIPTR: int -SNDCTL_DSP_GETISPACE: int -SNDCTL_DSP_GETODELAY: int -SNDCTL_DSP_GETOPTR: int -SNDCTL_DSP_GETOSPACE: int -SNDCTL_DSP_GETSPDIF: int -SNDCTL_DSP_GETTRIGGER: int -SNDCTL_DSP_MAPINBUF: int -SNDCTL_DSP_MAPOUTBUF: int -SNDCTL_DSP_NONBLOCK: int -SNDCTL_DSP_POST: int -SNDCTL_DSP_PROFILE: int -SNDCTL_DSP_RESET: int -SNDCTL_DSP_SAMPLESIZE: int -SNDCTL_DSP_SETDUPLEX: int -SNDCTL_DSP_SETFMT: int -SNDCTL_DSP_SETFRAGMENT: int -SNDCTL_DSP_SETSPDIF: int -SNDCTL_DSP_SETSYNCRO: int -SNDCTL_DSP_SETTRIGGER: int -SNDCTL_DSP_SPEED: int -SNDCTL_DSP_STEREO: int -SNDCTL_DSP_SUBDIVIDE: int -SNDCTL_DSP_SYNC: int -SNDCTL_FM_4OP_ENABLE: int -SNDCTL_FM_LOAD_INSTR: int -SNDCTL_MIDI_INFO: int -SNDCTL_MIDI_MPUCMD: int -SNDCTL_MIDI_MPUMODE: int -SNDCTL_MIDI_PRETIME: int -SNDCTL_SEQ_CTRLRATE: int -SNDCTL_SEQ_GETINCOUNT: int -SNDCTL_SEQ_GETOUTCOUNT: int -SNDCTL_SEQ_GETTIME: int -SNDCTL_SEQ_NRMIDIS: int -SNDCTL_SEQ_NRSYNTHS: int -SNDCTL_SEQ_OUTOFBAND: int -SNDCTL_SEQ_PANIC: int -SNDCTL_SEQ_PERCMODE: int -SNDCTL_SEQ_RESET: int -SNDCTL_SEQ_RESETSAMPLES: int -SNDCTL_SEQ_SYNC: int -SNDCTL_SEQ_TESTMIDI: int -SNDCTL_SEQ_THRESHOLD: int -SNDCTL_SYNTH_CONTROL: int -SNDCTL_SYNTH_ID: int -SNDCTL_SYNTH_INFO: int -SNDCTL_SYNTH_MEMAVL: int -SNDCTL_SYNTH_REMOVESAMPLE: int -SNDCTL_TMR_CONTINUE: int -SNDCTL_TMR_METRONOME: int -SNDCTL_TMR_SELECT: int -SNDCTL_TMR_SOURCE: int -SNDCTL_TMR_START: int -SNDCTL_TMR_STOP: int -SNDCTL_TMR_TEMPO: int -SNDCTL_TMR_TIMEBASE: int -SOUND_MIXER_ALTPCM: int -SOUND_MIXER_BASS: int -SOUND_MIXER_CD: int -SOUND_MIXER_DIGITAL1: int -SOUND_MIXER_DIGITAL2: int -SOUND_MIXER_DIGITAL3: int -SOUND_MIXER_IGAIN: int -SOUND_MIXER_IMIX: int -SOUND_MIXER_LINE: int -SOUND_MIXER_LINE1: int -SOUND_MIXER_LINE2: int -SOUND_MIXER_LINE3: int -SOUND_MIXER_MIC: int -SOUND_MIXER_MONITOR: int -SOUND_MIXER_NRDEVICES: int -SOUND_MIXER_OGAIN: int -SOUND_MIXER_PCM: int -SOUND_MIXER_PHONEIN: int -SOUND_MIXER_PHONEOUT: int -SOUND_MIXER_RADIO: int -SOUND_MIXER_RECLEV: int -SOUND_MIXER_SPEAKER: int -SOUND_MIXER_SYNTH: int -SOUND_MIXER_TREBLE: int -SOUND_MIXER_VIDEO: int -SOUND_MIXER_VOLUME: int +if sys.platform != "win32" and sys.platform != "darwin": + # Depends on soundcard.h + AFMT_AC3: Final[int] + AFMT_A_LAW: Final[int] + AFMT_IMA_ADPCM: Final[int] + AFMT_MPEG: Final[int] + AFMT_MU_LAW: Final[int] + AFMT_QUERY: Final[int] + AFMT_S16_BE: Final[int] + AFMT_S16_LE: Final[int] + AFMT_S16_NE: Final[int] + AFMT_S8: Final[int] + AFMT_U16_BE: Final[int] + AFMT_U16_LE: Final[int] + AFMT_U8: Final[int] + SNDCTL_COPR_HALT: Final[int] + SNDCTL_COPR_LOAD: Final[int] + SNDCTL_COPR_RCODE: Final[int] + SNDCTL_COPR_RCVMSG: Final[int] + SNDCTL_COPR_RDATA: Final[int] + SNDCTL_COPR_RESET: Final[int] + SNDCTL_COPR_RUN: Final[int] + SNDCTL_COPR_SENDMSG: Final[int] + SNDCTL_COPR_WCODE: Final[int] + SNDCTL_COPR_WDATA: Final[int] + SNDCTL_DSP_BIND_CHANNEL: Final[int] + SNDCTL_DSP_CHANNELS: Final[int] + SNDCTL_DSP_GETBLKSIZE: Final[int] + SNDCTL_DSP_GETCAPS: Final[int] + SNDCTL_DSP_GETCHANNELMASK: Final[int] + SNDCTL_DSP_GETFMTS: Final[int] + SNDCTL_DSP_GETIPTR: Final[int] + SNDCTL_DSP_GETISPACE: Final[int] + SNDCTL_DSP_GETODELAY: Final[int] + SNDCTL_DSP_GETOPTR: Final[int] + SNDCTL_DSP_GETOSPACE: Final[int] + SNDCTL_DSP_GETSPDIF: Final[int] + SNDCTL_DSP_GETTRIGGER: Final[int] + SNDCTL_DSP_MAPINBUF: Final[int] + SNDCTL_DSP_MAPOUTBUF: Final[int] + SNDCTL_DSP_NONBLOCK: Final[int] + SNDCTL_DSP_POST: Final[int] + SNDCTL_DSP_PROFILE: Final[int] + SNDCTL_DSP_RESET: Final[int] + SNDCTL_DSP_SAMPLESIZE: Final[int] + SNDCTL_DSP_SETDUPLEX: Final[int] + SNDCTL_DSP_SETFMT: Final[int] + SNDCTL_DSP_SETFRAGMENT: Final[int] + SNDCTL_DSP_SETSPDIF: Final[int] + SNDCTL_DSP_SETSYNCRO: Final[int] + SNDCTL_DSP_SETTRIGGER: Final[int] + SNDCTL_DSP_SPEED: Final[int] + SNDCTL_DSP_STEREO: Final[int] + SNDCTL_DSP_SUBDIVIDE: Final[int] + SNDCTL_DSP_SYNC: Final[int] + SNDCTL_FM_4OP_ENABLE: Final[int] + SNDCTL_FM_LOAD_INSTR: Final[int] + SNDCTL_MIDI_INFO: Final[int] + SNDCTL_MIDI_MPUCMD: Final[int] + SNDCTL_MIDI_MPUMODE: Final[int] + SNDCTL_MIDI_PRETIME: Final[int] + SNDCTL_SEQ_CTRLRATE: Final[int] + SNDCTL_SEQ_GETINCOUNT: Final[int] + SNDCTL_SEQ_GETOUTCOUNT: Final[int] + SNDCTL_SEQ_GETTIME: Final[int] + SNDCTL_SEQ_NRMIDIS: Final[int] + SNDCTL_SEQ_NRSYNTHS: Final[int] + SNDCTL_SEQ_OUTOFBAND: Final[int] + SNDCTL_SEQ_PANIC: Final[int] + SNDCTL_SEQ_PERCMODE: Final[int] + SNDCTL_SEQ_RESET: Final[int] + SNDCTL_SEQ_RESETSAMPLES: Final[int] + SNDCTL_SEQ_SYNC: Final[int] + SNDCTL_SEQ_TESTMIDI: Final[int] + SNDCTL_SEQ_THRESHOLD: Final[int] + SNDCTL_SYNTH_CONTROL: Final[int] + SNDCTL_SYNTH_ID: Final[int] + SNDCTL_SYNTH_INFO: Final[int] + SNDCTL_SYNTH_MEMAVL: Final[int] + SNDCTL_SYNTH_REMOVESAMPLE: Final[int] + SNDCTL_TMR_CONTINUE: Final[int] + SNDCTL_TMR_METRONOME: Final[int] + SNDCTL_TMR_SELECT: Final[int] + SNDCTL_TMR_SOURCE: Final[int] + SNDCTL_TMR_START: Final[int] + SNDCTL_TMR_STOP: Final[int] + SNDCTL_TMR_TEMPO: Final[int] + SNDCTL_TMR_TIMEBASE: Final[int] + SOUND_MIXER_ALTPCM: Final[int] + SOUND_MIXER_BASS: Final[int] + SOUND_MIXER_CD: Final[int] + SOUND_MIXER_DIGITAL1: Final[int] + SOUND_MIXER_DIGITAL2: Final[int] + SOUND_MIXER_DIGITAL3: Final[int] + SOUND_MIXER_IGAIN: Final[int] + SOUND_MIXER_IMIX: Final[int] + SOUND_MIXER_LINE: Final[int] + SOUND_MIXER_LINE1: Final[int] + SOUND_MIXER_LINE2: Final[int] + SOUND_MIXER_LINE3: Final[int] + SOUND_MIXER_MIC: Final[int] + SOUND_MIXER_MONITOR: Final[int] + SOUND_MIXER_NRDEVICES: Final[int] + SOUND_MIXER_OGAIN: Final[int] + SOUND_MIXER_PCM: Final[int] + SOUND_MIXER_PHONEIN: Final[int] + SOUND_MIXER_PHONEOUT: Final[int] + SOUND_MIXER_RADIO: Final[int] + SOUND_MIXER_RECLEV: Final[int] + SOUND_MIXER_SPEAKER: Final[int] + SOUND_MIXER_SYNTH: Final[int] + SOUND_MIXER_TREBLE: Final[int] + SOUND_MIXER_VIDEO: Final[int] + SOUND_MIXER_VOLUME: Final[int] -control_labels: list[str] -control_names: list[str] + control_labels: list[str] + control_names: list[str] -# TODO: oss_audio_device return type -@overload -def open(mode: Literal["r", "w", "rw"]) -> Any: ... -@overload -def open(device: str, mode: Literal["r", "w", "rw"]) -> Any: ... + # TODO: oss_audio_device return type + @overload + def open(mode: Literal["r", "w", "rw"]) -> Any: ... + @overload + def open(device: str, mode: Literal["r", "w", "rw"]) -> Any: ... -# TODO: oss_mixer_device return type -def openmixer(device: str = ...) -> Any: ... + # TODO: oss_mixer_device return type + def openmixer(device: str = ...) -> Any: ... -class OSSAudioError(Exception): ... - -error = OSSAudioError + class OSSAudioError(Exception): ... + error = OSSAudioError diff --git a/stdlib/parser.pyi b/stdlib/parser.pyi deleted file mode 100644 index aecf3244ca8d..000000000000 --- a/stdlib/parser.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from _typeshed import StrOrBytesPath -from types import CodeType -from typing import Any, Sequence, Tuple - -def expr(source: str) -> STType: ... -def suite(source: str) -> STType: ... -def sequence2st(sequence: Sequence[Any]) -> STType: ... -def tuple2st(sequence: Sequence[Any]) -> STType: ... -def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... -def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any, ...]: ... -def compilest(st: STType, filename: StrOrBytesPath = ...) -> CodeType: ... -def isexpr(st: STType) -> bool: ... -def issuite(st: STType) -> bool: ... - -class ParserError(Exception): ... - -class STType: - def compile(self, filename: StrOrBytesPath = ...) -> CodeType: ... - def isexpr(self) -> bool: ... - def issuite(self) -> bool: ... - def tolist(self, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... - def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any, ...]: ... diff --git a/stdlib/pathlib.pyi b/stdlib/pathlib.pyi deleted file mode 100644 index 7d5f7ff2dba8..000000000000 --- a/stdlib/pathlib.pyi +++ /dev/null @@ -1,186 +0,0 @@ -import sys -from _typeshed import ( - OpenBinaryMode, - OpenBinaryModeReading, - OpenBinaryModeUpdating, - OpenBinaryModeWriting, - OpenTextMode, - Self, - StrPath, -) -from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from os import PathLike, stat_result -from types import TracebackType -from typing import IO, Any, BinaryIO, Generator, Sequence, Tuple, Type, TypeVar, overload -from typing_extensions import Literal - -if sys.version_info >= (3, 9): - from types import GenericAlias - -_P = TypeVar("_P", bound=PurePath) - -class PurePath(PathLike[str]): - parts: Tuple[str, ...] - drive: str - root: str - anchor: str - name: str - suffix: str - suffixes: list[str] - stem: str - def __new__(cls: Type[_P], *args: StrPath) -> _P: ... - def __hash__(self) -> int: ... - def __lt__(self, other: PurePath) -> bool: ... - def __le__(self, other: PurePath) -> bool: ... - def __gt__(self, other: PurePath) -> bool: ... - def __ge__(self, other: PurePath) -> bool: ... - def __truediv__(self: _P, key: StrPath) -> _P: ... - def __rtruediv__(self: _P, key: StrPath) -> _P: ... - def __bytes__(self) -> bytes: ... - def as_posix(self) -> str: ... - def as_uri(self) -> str: ... - def is_absolute(self) -> bool: ... - def is_reserved(self) -> bool: ... - if sys.version_info >= (3, 9): - def is_relative_to(self, *other: StrPath) -> bool: ... - def match(self, path_pattern: str) -> bool: ... - def relative_to(self: _P, *other: StrPath) -> _P: ... - def with_name(self: _P, name: str) -> _P: ... - if sys.version_info >= (3, 9): - def with_stem(self: _P, stem: str) -> _P: ... - def with_suffix(self: _P, suffix: str) -> _P: ... - def joinpath(self: _P, *other: StrPath) -> _P: ... - @property - def parents(self: _P) -> Sequence[_P]: ... - @property - def parent(self: _P) -> _P: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, type: Any) -> GenericAlias: ... - -class PurePosixPath(PurePath): ... -class PureWindowsPath(PurePath): ... - -class Path(PurePath): - def __new__(cls: Type[_P], *args: StrPath, **kwargs: Any) -> _P: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... - @classmethod - def cwd(cls: Type[_P]) -> _P: ... - if sys.version_info >= (3, 10): - def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... - def chmod(self, mode: int, *, follow_symlinks: bool = ...) -> None: ... - else: - def stat(self) -> stat_result: ... - def chmod(self, mode: int) -> None: ... - def exists(self) -> bool: ... - def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... - def group(self) -> str: ... - def is_dir(self) -> bool: ... - def is_file(self) -> bool: ... - if sys.version_info >= (3, 7): - def is_mount(self) -> bool: ... - def is_symlink(self) -> bool: ... - def is_socket(self) -> bool: ... - def is_fifo(self) -> bool: ... - def is_block_device(self) -> bool: ... - def is_char_device(self) -> bool: ... - def iterdir(self: _P) -> Generator[_P, None, None]: ... - def lchmod(self, mode: int) -> None: ... - def lstat(self) -> stat_result: ... - def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... - # Adapted from builtins.open - # Text mode: always returns a TextIOWrapper - # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this. - @overload - def open( - self, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - ) -> TextIOWrapper: ... - # Unbuffered binary mode: returns a FileIO - @overload - def open( - self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... - ) -> FileIO: ... - # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter - @overload - def open( - self, - mode: OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BufferedRandom: ... - @overload - def open( - self, - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BufferedWriter: ... - @overload - def open( - self, - mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BufferedReader: ... - # Buffering cannot be determined: fall back to BinaryIO - @overload - def open( - self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... - ) -> BinaryIO: ... - # Fallback if mode is not specified - @overload - def open( - self, mode: str, buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ... - ) -> IO[Any]: ... - def owner(self) -> str: ... - if sys.version_info >= (3, 9): - def readlink(self: _P) -> _P: ... - if sys.version_info >= (3, 8): - def rename(self: _P, target: str | PurePath) -> _P: ... - def replace(self: _P, target: str | PurePath) -> _P: ... - else: - def rename(self, target: str | PurePath) -> None: ... - def replace(self, target: str | PurePath) -> None: ... - def resolve(self: _P, strict: bool = ...) -> _P: ... - def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... - def rmdir(self) -> None: ... - def symlink_to(self, target: str | Path, target_is_directory: bool = ...) -> None: ... - if sys.version_info >= (3, 10): - def hardlink_to(self, target: str | Path) -> None: ... - def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... - if sys.version_info >= (3, 8): - def unlink(self, missing_ok: bool = ...) -> None: ... - else: - def unlink(self) -> None: ... - @classmethod - def home(cls: Type[_P]) -> _P: ... - def absolute(self: _P) -> _P: ... - def expanduser(self: _P) -> _P: ... - def read_bytes(self) -> bytes: ... - def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... - def samefile(self, other_path: str | bytes | int | Path) -> bool: ... - def write_bytes(self, data: bytes) -> int: ... - if sys.version_info >= (3, 10): - def write_text( - self, data: str, encoding: str | None = ..., errors: str | None = ..., newline: str | None = ... - ) -> int: ... - else: - def write_text(self, data: str, encoding: str | None = ..., errors: str | None = ...) -> int: ... - if sys.version_info >= (3, 8): - def link_to(self, target: StrPath | bytes) -> None: ... - -class PosixPath(Path, PurePosixPath): ... -class WindowsPath(Path, PureWindowsPath): ... diff --git a/stdlib/pathlib/__init__.pyi b/stdlib/pathlib/__init__.pyi new file mode 100644 index 000000000000..dfd85087642a --- /dev/null +++ b/stdlib/pathlib/__init__.pyi @@ -0,0 +1,357 @@ +import sys +from _typeshed import ( + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + StrOrBytesPath, + StrPath, + Unused, +) +from collections.abc import Callable, Generator, Iterator, Sequence +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from os import PathLike, stat_result +from types import GenericAlias, ModuleType, TracebackType +from typing import IO, Any, BinaryIO, ClassVar, Literal, TypeVar, overload +from typing_extensions import Never, Self, deprecated + +_PathT = TypeVar("_PathT", bound=PurePath) + +__all__ = ["PurePath", "PurePosixPath", "PureWindowsPath", "Path", "PosixPath", "WindowsPath"] + +if sys.version_info >= (3, 14): + from pathlib.types import PathInfo + +if sys.version_info >= (3, 13): + __all__ += ["UnsupportedOperation"] + +class PurePath(PathLike[str]): + if sys.version_info < (3, 15): + if sys.version_info >= (3, 13): + __slots__ = ( + "_raw_paths", + "_drv", + "_root", + "_tail_cached", + "_str", + "_str_normcase_cached", + "_parts_normcase_cached", + "_hash", + ) + elif sys.version_info >= (3, 12): + __slots__ = ( + "_raw_paths", + "_drv", + "_root", + "_tail_cached", + "_str", + "_str_normcase_cached", + "_parts_normcase_cached", + "_lines_cached", + "_hash", + ) + else: + __slots__ = ("_drv", "_root", "_parts", "_str", "_hash", "_pparts", "_cached_cparts") + if sys.version_info >= (3, 13): + parser: ClassVar[ModuleType] + def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ... + + @property + def parts(self) -> tuple[str, ...]: ... + @property + def drive(self) -> str: ... + @property + def root(self) -> str: ... + @property + def anchor(self) -> str: ... + @property + def name(self) -> str: ... + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + if sys.version_info >= (3, 12): + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... + def __init__(self, *args: StrPath) -> None: ... # pyright: ignore[reportInconsistentConstructor] + else: + def __new__(cls, *args: StrPath) -> Self: ... + + def __hash__(self) -> int: ... + def __fspath__(self) -> str: ... + if sys.version_info >= (3, 15): + def __vfspath__(self) -> str: ... + + def __lt__(self, other: PurePath) -> bool: ... + def __le__(self, other: PurePath) -> bool: ... + def __gt__(self, other: PurePath) -> bool: ... + def __ge__(self, other: PurePath) -> bool: ... + def __truediv__(self, key: StrPath) -> Self: ... + def __rtruediv__(self, key: StrPath) -> Self: ... + def __bytes__(self) -> bytes: ... + def as_posix(self) -> str: ... + @deprecated("Deprecated; will be removed in Python 3.19. Use `Path.as_uri()` instead.") + def as_uri(self) -> str: ... + def is_absolute(self) -> bool: ... + if sys.version_info < (3, 15): + if sys.version_info >= (3, 13): + @deprecated( + "Deprecated since Python 3.13; removed in Python 3.15. " + "Use `os.path.isreserved()` to detect reserved paths on Windows." + ) + def is_reserved(self) -> bool: ... + else: + def is_reserved(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_relative_to(self, other: StrPath) -> bool: ... + else: + @overload + def is_relative_to(self, other: StrPath, /) -> bool: ... + @overload + @deprecated("Passing additional arguments is deprecated; removed in Python 3.14.") + def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ... + + if sys.version_info >= (3, 12): + def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ... + else: + def match(self, path_pattern: str) -> bool: ... + + if sys.version_info >= (3, 14): + def relative_to(self, other: StrPath, *, walk_up: bool = False) -> Self: ... + elif sys.version_info >= (3, 12): + @overload + def relative_to(self, other: StrPath, /, *, walk_up: bool = False) -> Self: ... + @overload + @deprecated("Passing additional arguments is deprecated since Python 3.12; removed in Python 3.14.") + def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: ... + else: + def relative_to(self, *other: StrPath) -> Self: ... + + def with_name(self, name: str) -> Self: ... + def with_stem(self, stem: str) -> Self: ... + def with_suffix(self, suffix: str) -> Self: ... + def joinpath(self, *other: StrPath) -> Self: ... + @property + def parents(self) -> Sequence[Self]: ... + @property + def parent(self) -> Self: ... + if sys.version_info < (3, 11): + def __class_getitem__(cls, type: Any) -> GenericAlias: ... + + if sys.version_info >= (3, 12): + def with_segments(self, *args: StrPath) -> Self: ... + +class PurePosixPath(PurePath): + __slots__ = () + +class PureWindowsPath(PurePath): + __slots__ = () + +class Path(PurePath): + if sys.version_info >= (3, 14): + __slots__ = ("_info",) + else: + __slots__ = () + + if sys.version_info >= (3, 12): + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor] + else: + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... + + @classmethod + def cwd(cls) -> Self: ... + def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... + def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ... + + if sys.version_info >= (3, 13): + @classmethod + def from_uri(cls, uri: str) -> Self: ... + def is_dir(self, *, follow_symlinks: bool = True) -> bool: ... + def is_file(self, *, follow_symlinks: bool = True) -> bool: ... + def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: ... + else: + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ... + + if sys.version_info >= (3, 13): + def glob(self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False) -> Iterator[Self]: ... + def rglob( + self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False + ) -> Iterator[Self]: ... + elif sys.version_info >= (3, 12): + def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self]: ... + def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self]: ... + else: + def glob(self, pattern: str) -> Generator[Self]: ... + def rglob(self, pattern: str) -> Generator[Self]: ... + + if sys.version_info >= (3, 12): + def exists(self, *, follow_symlinks: bool = True) -> bool: ... + else: + def exists(self) -> bool: ... + + def is_symlink(self) -> bool: ... + def is_socket(self) -> bool: ... + def is_fifo(self) -> bool: ... + def is_block_device(self) -> bool: ... + def is_char_device(self) -> bool: ... + if sys.version_info >= (3, 12): + def is_junction(self) -> bool: ... + + def iterdir(self) -> Generator[Self]: ... + def lchmod(self, mode: int) -> None: ... + def lstat(self) -> stat_result: ... + if sys.version_info >= (3, 15): + def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False, *, parent_mode: int | None = None + ) -> None: ... + else: + def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ... + + if sys.version_info >= (3, 14): + @property + def info(self) -> PathInfo: ... + + @overload + def move_into(self, target_dir: _PathT) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def move_into(self, target_dir: StrPath) -> Self: ... # type: ignore[overload-overlap] + + @overload + def move(self, target: _PathT) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def move(self, target: StrPath) -> Self: ... # type: ignore[overload-overlap] + + @overload + def copy_into(self, target_dir: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def copy_into(self, target_dir: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] + + @overload + def copy(self, target: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def copy(self, target: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] + + # Adapted from builtins.open + # Text mode: always returns a TextIOWrapper + # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this. + @overload + def open( + self, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> TextIOWrapper: ... + # Unbuffered binary mode: returns a FileIO + @overload + def open( + self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None + ) -> FileIO: ... + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def open( + self, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + ) -> BufferedRandom: ... + @overload + def open( + self, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + ) -> BufferedWriter: ... + @overload + def open( + self, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + ) -> BufferedReader: ... + # Buffering cannot be determined: fall back to BinaryIO + @overload + def open( + self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None + ) -> BinaryIO: ... + # Fallback if mode is not specified + @overload + def open( + self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None + ) -> IO[Any]: ... + + # These methods do "exist" on Windows, but they always raise NotImplementedError. + if sys.platform == "win32": + if sys.version_info >= (3, 13): + # raises UnsupportedOperation: + def owner(self: Never, *, follow_symlinks: bool = True) -> str: ... # type: ignore[misc] + def group(self: Never, *, follow_symlinks: bool = True) -> str: ... # type: ignore[misc] + else: + def owner(self: Never) -> str: ... # type: ignore[misc] + def group(self: Never) -> str: ... # type: ignore[misc] + else: + if sys.version_info >= (3, 13): + def owner(self, *, follow_symlinks: bool = True) -> str: ... + def group(self, *, follow_symlinks: bool = True) -> str: ... + else: + def owner(self) -> str: ... + def group(self) -> str: ... + + # This method does "exist" on Windows on <3.12, but always raises NotImplementedError + # On py312+, it works properly on Windows, as with all other platforms + if sys.platform == "win32" and sys.version_info < (3, 12): + def is_mount(self: Never) -> bool: ... # type: ignore[misc] + else: + def is_mount(self) -> bool: ... + + def readlink(self) -> Self: ... + def rename(self, target: StrPath) -> Self: ... + def replace(self, target: StrPath) -> Self: ... + def resolve(self, strict: bool = False) -> Self: ... + def rmdir(self) -> None: ... + def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ... + def hardlink_to(self, target: StrOrBytesPath) -> None: ... + def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ... + def unlink(self, missing_ok: bool = False) -> None: ... + @classmethod + def home(cls) -> Self: ... + def absolute(self) -> Self: ... + def expanduser(self) -> Self: ... + def read_bytes(self) -> bytes: ... + def samefile(self, other_path: StrPath) -> bool: ... + def write_bytes(self, data: ReadableBuffer) -> int: ... + def write_text( + self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None + ) -> int: ... + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `hardlink_to()` instead.") + def link_to(self, target: StrOrBytesPath) -> None: ... + if sys.version_info >= (3, 12): + def walk( + self, top_down: bool = True, on_error: Callable[[OSError], object] | None = None, follow_symlinks: bool = False + ) -> Iterator[tuple[Self, list[str], list[str]]]: ... + + def as_uri(self) -> str: ... + +class PosixPath(Path, PurePosixPath): + __slots__ = () + +class WindowsPath(Path, PureWindowsPath): + __slots__ = () + +if sys.version_info >= (3, 13): + class UnsupportedOperation(NotImplementedError): ... diff --git a/stdlib/pathlib/types.pyi b/stdlib/pathlib/types.pyi new file mode 100644 index 000000000000..9f9a650846de --- /dev/null +++ b/stdlib/pathlib/types.pyi @@ -0,0 +1,8 @@ +from typing import Protocol, runtime_checkable + +@runtime_checkable +class PathInfo(Protocol): + def exists(self, *, follow_symlinks: bool = True) -> bool: ... + def is_dir(self, *, follow_symlinks: bool = True) -> bool: ... + def is_file(self, *, follow_symlinks: bool = True) -> bool: ... + def is_symlink(self) -> bool: ... diff --git a/stdlib/pdb.pyi b/stdlib/pdb.pyi index 83bd32d76450..289637cb5f04 100644 --- a/stdlib/pdb.pyi +++ b/stdlib/pdb.pyi @@ -1,29 +1,48 @@ import signal import sys -from bdb import Bdb +from _typeshed import ReadableBuffer +from bdb import Bdb, _Backend from cmd import Cmd -from inspect import _SourceObjectType +from collections.abc import Callable, Iterable, Mapping, Sequence +from linecache import _ModuleGlobals +from rlcompleter import Completer from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, Sequence, TypeVar +from typing import IO, Any, ClassVar, Final, Literal, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self, deprecated + +__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] +if sys.version_info >= (3, 14): + __all__ += ["set_default_backend", "get_default_backend"] _T = TypeVar("_T") +_P = ParamSpec("_P") +_Mode: TypeAlias = Literal["inline", "cli"] -line_prefix: str # undocumented +line_prefix: Final[str] # undocumented class Restart(Exception): ... -def run(statement: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... -def runeval(expression: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... -def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... -def runcall(func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... +def run( # matches `builtins.exec` + statement: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None +) -> None: ... +def runctx( # matches `builtins.exec` + statement: str | ReadableBuffer | CodeType, globals: dict[str, Any], locals: Mapping[str, object] +) -> None: ... +def runeval( # matches `builtins.eval` + expression: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None +) -> Any: ... +def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... -if sys.version_info >= (3, 7): - def set_trace(*, header: str | None = ...) -> None: ... +if sys.version_info >= (3, 14): + def set_default_backend(backend: _Backend) -> None: ... + def get_default_backend() -> _Backend: ... + def set_trace(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: ... + async def set_trace_async(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: ... else: - def set_trace() -> None: ... + def set_trace(*, header: str | None = None) -> None: ... -def post_mortem(t: TracebackType | None = ...) -> None: ... +def post_mortem(t: TracebackType | None = None) -> None: ... def pm() -> None: ... class Pdb(Bdb, Cmd): @@ -31,6 +50,9 @@ class Pdb(Bdb, Cmd): commands_resuming: ClassVar[list[str]] + if sys.version_info >= (3, 13): + MAX_CHAINED_EXCEPTION_DEPTH: Final = 999 + aliases: dict[str, str] mainpyfile: str _wait_for_mainpyfile: bool @@ -44,33 +66,97 @@ class Pdb(Bdb, Cmd): stack: list[tuple[FrameType, int]] curindex: int curframe: FrameType | None - curframe_locals: Mapping[str, Any] - def __init__( - self, - completekey: str = ..., - stdin: IO[str] | None = ..., - stdout: IO[str] | None = ..., - skip: Iterable[str] | None = ..., - nosigint: bool = ..., - readrc: bool = ..., - ) -> None: ... + if sys.version_info >= (3, 13): + @property + @deprecated("The frame locals reference is no longer cached. Use 'curframe.f_locals' instead.") + def curframe_locals(self) -> Mapping[str, Any]: ... + @curframe_locals.setter + @deprecated( + "Setting 'curframe_locals' no longer has any effect as of 3.14. Update the contents of 'curframe.f_locals' instead." + ) + def curframe_locals(self, value: Mapping[str, Any]) -> None: ... + else: + curframe_locals: Mapping[str, Any] + if sys.version_info >= (3, 14): + mode: _Mode | None + colorize: bool + def __init__( + self, + completekey: str = "tab", + stdin: IO[str] | None = None, + stdout: IO[str] | None = None, + skip: Iterable[str] | None = None, + nosigint: bool = False, + readrc: bool = True, + mode: _Mode | None = None, + backend: _Backend | None = None, + colorize: bool = False, + ) -> None: ... + else: + def __init__( + self, + completekey: str = "tab", + stdin: IO[str] | None = None, + stdout: IO[str] | None = None, + skip: Iterable[str] | None = None, + nosigint: bool = False, + readrc: bool = True, + ) -> None: ... + if sys.version_info >= (3, 14): + def set_trace(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: ... + async def set_trace_async(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: ... + def forget(self) -> None: ... def setup(self, f: FrameType | None, tb: TracebackType | None) -> None: ... - def execRcLines(self) -> None: ... + if sys.version_info < (3, 11): + def execRcLines(self) -> None: ... + + if sys.version_info >= (3, 13): + user_opcode = Bdb.user_line + def bp_commands(self, frame: FrameType) -> bool: ... - def interaction(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ... + + if sys.version_info >= (3, 13): + def interaction(self, frame: FrameType | None, tb_or_exc: TracebackType | BaseException | None) -> None: ... + else: + def interaction(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ... + def displayhook(self, obj: object) -> None: ... def handle_command_def(self, line: str) -> bool: ... def defaultFile(self) -> str: ... def lineinfo(self, identifier: str) -> tuple[None, None, None] | tuple[str, str, int]: ... - def checkline(self, filename: str, lineno: int) -> int: ... + if sys.version_info >= (3, 14): + def checkline(self, filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> int: ... + else: + def checkline(self, filename: str, lineno: int) -> int: ... + def _getval(self, arg: str) -> object: ... - def print_stack_trace(self) -> None: ... - def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... + if sys.version_info >= (3, 14): + def print_stack_trace(self, count: int | None = None) -> None: ... + else: + def print_stack_trace(self) -> None: ... + + if sys.version_info >= (3, 15): + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str | None = None) -> None: ... + else: + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> ") -> None: ... + def lookupmodule(self, filename: str) -> str | None: ... - def _runscript(self, filename: str) -> None: ... + if sys.version_info < (3, 11): + def _runscript(self, filename: str) -> None: ... + + if sys.version_info >= (3, 14): + def complete_multiline_names(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + + if sys.version_info >= (3, 13): + def completedefault(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + def do_commands(self, arg: str) -> bool | None: ... - def do_break(self, arg: str, temporary: bool = ...) -> bool | None: ... + if sys.version_info >= (3, 14): + def do_break(self, arg: str, temporary: bool = False) -> bool | None: ... + else: + def do_break(self, arg: str, temporary: bool | Literal[0, 1] = 0) -> bool | None: ... + def do_tbreak(self, arg: str) -> bool | None: ... def do_enable(self, arg: str) -> bool | None: ... def do_disable(self, arg: str) -> bool | None: ... @@ -78,6 +164,9 @@ class Pdb(Bdb, Cmd): def do_ignore(self, arg: str) -> bool | None: ... def do_clear(self, arg: str) -> bool | None: ... def do_where(self, arg: str) -> bool | None: ... + if sys.version_info >= (3, 13): + def do_exceptions(self, arg: str) -> bool | None: ... + def do_up(self, arg: str) -> bool | None: ... def do_down(self, arg: str) -> bool | None: ... def do_until(self, arg: str) -> bool | None: ... @@ -122,12 +211,25 @@ class Pdb(Bdb, Cmd): def help_exec(self) -> None: ... def help_pdb(self) -> None: ... def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ... - def message(self, msg: str) -> None: ... + if sys.version_info >= (3, 13): + def message(self, msg: str, end: str = "\n") -> None: ... + else: + def message(self, msg: str) -> None: ... + def error(self, msg: str) -> None: ... + if sys.version_info >= (3, 13): + def completenames(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... # type: ignore[override] + if sys.version_info >= (3, 12): + def set_convenience_variable(self, frame: FrameType, name: str, value: Any) -> None: ... + if sys.version_info >= (3, 13): + # Added in 3.13.8 and 3.14.1 + @property + def rlcompleter(self) -> type[Completer]: ... + def _select_frame(self, number: int) -> None: ... - def _getval_except(self, arg: str, frame: FrameType | None = ...) -> object: ... + def _getval_except(self, arg: str, frame: FrameType | None = None) -> object: ... def _print_lines( - self, lines: Sequence[str], start: int, breaks: Sequence[int] = ..., frame: FrameType | None = ... + self, lines: Sequence[str], start: int, breaks: Sequence[int] = (), frame: FrameType | None = None ) -> None: ... def _cmdloop(self) -> None: ... def do_display(self, arg: str) -> bool | None: ... @@ -159,7 +261,7 @@ class Pdb(Bdb, Cmd): complete_whatis = _complete_expression complete_display = _complete_expression - if sys.version_info >= (3, 7): + if sys.version_info < (3, 11): def _runmodule(self, module_name: str) -> None: ... # undocumented @@ -167,8 +269,7 @@ class Pdb(Bdb, Cmd): def find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ... def main() -> None: ... def help() -> None: ... -def getsourcelines(obj: _SourceObjectType) -> tuple[list[str], int]: ... def lasti2lineno(code: CodeType, lasti: int) -> int: ... class _rstr(str): - def __repr__(self) -> _rstr: ... + def __repr__(self) -> Self: ... diff --git a/stdlib/pickle.pyi b/stdlib/pickle.pyi index cef1ffe9eb9b..03ba6c12cd4a 100644 --- a/stdlib/pickle.pyi +++ b/stdlib/pickle.pyi @@ -1,196 +1,240 @@ import sys -from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Tuple, Type, Union -from typing_extensions import final - -HIGHEST_PROTOCOL: int -DEFAULT_PROTOCOL: int - -bytes_types: Tuple[Type[Any], ...] # undocumented - -class _ReadableFileobj(Protocol): - def read(self, __n: int) -> bytes: ... - def readline(self) -> bytes: ... +from _pickle import ( + PickleError as PickleError, + Pickler as Pickler, + PicklingError as PicklingError, + Unpickler as Unpickler, + UnpicklingError as UnpicklingError, + _BufferCallback, + _ReadableFileobj, + _ReducedType, + dump as dump, + dumps as dumps, + load as load, + loads as loads, +) +from _typeshed import ReadableBuffer, SupportsWrite +from collections.abc import Callable, Iterable, Mapping +from typing import Any, ClassVar, Final, SupportsBytes, SupportsIndex, final +from typing_extensions import Self + +__all__ = [ + "PickleBuffer", + "PickleError", + "PicklingError", + "UnpicklingError", + "Pickler", + "Unpickler", + "dump", + "dumps", + "load", + "loads", + "ADDITEMS", + "APPEND", + "APPENDS", + "BINBYTES", + "BINBYTES8", + "BINFLOAT", + "BINGET", + "BININT", + "BININT1", + "BININT2", + "BINPERSID", + "BINPUT", + "BINSTRING", + "BINUNICODE", + "BINUNICODE8", + "BUILD", + "BYTEARRAY8", + "DEFAULT_PROTOCOL", + "DICT", + "DUP", + "EMPTY_DICT", + "EMPTY_LIST", + "EMPTY_SET", + "EMPTY_TUPLE", + "EXT1", + "EXT2", + "EXT4", + "FALSE", + "FLOAT", + "FRAME", + "FROZENSET", + "GET", + "GLOBAL", + "HIGHEST_PROTOCOL", + "INST", + "INT", + "LIST", + "LONG", + "LONG1", + "LONG4", + "LONG_BINGET", + "LONG_BINPUT", + "MARK", + "MEMOIZE", + "NEWFALSE", + "NEWOBJ", + "NEWOBJ_EX", + "NEWTRUE", + "NEXT_BUFFER", + "NONE", + "OBJ", + "PERSID", + "POP", + "POP_MARK", + "PROTO", + "PUT", + "READONLY_BUFFER", + "REDUCE", + "SETITEM", + "SETITEMS", + "SHORT_BINBYTES", + "SHORT_BINSTRING", + "SHORT_BINUNICODE", + "STACK_GLOBAL", + "STOP", + "STRING", + "TRUE", + "TUPLE", + "TUPLE1", + "TUPLE2", + "TUPLE3", + "UNICODE", +] -class _WritableFileobj(Protocol): - def write(self, __b: bytes) -> Any: ... +HIGHEST_PROTOCOL: Final = 5 +if sys.version_info >= (3, 14): + DEFAULT_PROTOCOL: Final = 5 +else: + DEFAULT_PROTOCOL: Final = 4 + +bytes_types: tuple[type[Any], ...] # undocumented + +@final +class PickleBuffer: + def __new__(cls, buffer: ReadableBuffer) -> Self: ... + def raw(self) -> memoryview: ... + def release(self) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + +MARK: Final = b"(" +STOP: Final = b"." +POP: Final = b"0" +POP_MARK: Final = b"1" +DUP: Final = b"2" +FLOAT: Final = b"F" +INT: Final = b"I" +BININT: Final = b"J" +BININT1: Final = b"K" +LONG: Final = b"L" +BININT2: Final = b"M" +NONE: Final = b"N" +PERSID: Final = b"P" +BINPERSID: Final = b"Q" +REDUCE: Final = b"R" +STRING: Final = b"S" +BINSTRING: Final = b"T" +SHORT_BINSTRING: Final = b"U" +UNICODE: Final = b"V" +BINUNICODE: Final = b"X" +APPEND: Final = b"a" +BUILD: Final = b"b" +GLOBAL: Final = b"c" +DICT: Final = b"d" +EMPTY_DICT: Final = b"}" +APPENDS: Final = b"e" +GET: Final = b"g" +BINGET: Final = b"h" +INST: Final = b"i" +LONG_BINGET: Final = b"j" +LIST: Final = b"l" +EMPTY_LIST: Final = b"]" +OBJ: Final = b"o" +PUT: Final = b"p" +BINPUT: Final = b"q" +LONG_BINPUT: Final = b"r" +SETITEM: Final = b"s" +TUPLE: Final = b"t" +EMPTY_TUPLE: Final = b")" +SETITEMS: Final = b"u" +BINFLOAT: Final = b"G" + +TRUE: Final = b"I01\n" +FALSE: Final = b"I00\n" -if sys.version_info >= (3, 8): - # TODO: holistic design for buffer interface (typing.Buffer?) - @final - class PickleBuffer: - # buffer must be a buffer-providing object - def __init__(self, buffer: Any) -> None: ... - def raw(self) -> memoryview: ... - def release(self) -> None: ... - _BufferCallback = Optional[Callable[[PickleBuffer], Any]] - def dump( - obj: Any, - file: _WritableFileobj, - protocol: int | None = ..., - *, - fix_imports: bool = ..., - buffer_callback: _BufferCallback = ..., - ) -> None: ... - def dumps( - obj: Any, protocol: int | None = ..., *, fix_imports: bool = ..., buffer_callback: _BufferCallback = ... - ) -> bytes: ... - def load( - file: _ReadableFileobj, - *, - fix_imports: bool = ..., - encoding: str = ..., - errors: str = ..., - buffers: Iterable[Any] | None = ..., - ) -> Any: ... - def loads( - __data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ..., buffers: Iterable[Any] | None = ... - ) -> Any: ... +# protocol 2 +PROTO: Final = b"\x80" +NEWOBJ: Final = b"\x81" +EXT1: Final = b"\x82" +EXT2: Final = b"\x83" +EXT4: Final = b"\x84" +TUPLE1: Final = b"\x85" +TUPLE2: Final = b"\x86" +TUPLE3: Final = b"\x87" +NEWTRUE: Final = b"\x88" +NEWFALSE: Final = b"\x89" +LONG1: Final = b"\x8a" +LONG4: Final = b"\x8b" -else: - def dump(obj: Any, file: _WritableFileobj, protocol: int | None = ..., *, fix_imports: bool = ...) -> None: ... - def dumps(obj: Any, protocol: int | None = ..., *, fix_imports: bool = ...) -> bytes: ... - def load(file: _ReadableFileobj, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... - def loads(data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... +# protocol 3 +BINBYTES: Final = b"B" +SHORT_BINBYTES: Final = b"C" -class PickleError(Exception): ... -class PicklingError(PickleError): ... -class UnpicklingError(PickleError): ... +# protocol 4 +SHORT_BINUNICODE: Final = b"\x8c" +BINUNICODE8: Final = b"\x8d" +BINBYTES8: Final = b"\x8e" +EMPTY_SET: Final = b"\x8f" +ADDITEMS: Final = b"\x90" +FROZENSET: Final = b"\x91" +NEWOBJ_EX: Final = b"\x92" +STACK_GLOBAL: Final = b"\x93" +MEMOIZE: Final = b"\x94" +FRAME: Final = b"\x95" + +# protocol 5 +BYTEARRAY8: Final = b"\x96" +NEXT_BUFFER: Final = b"\x97" +READONLY_BUFFER: Final = b"\x98" -_reducedtype = Union[ - str, - Tuple[Callable[..., Any], Tuple[Any, ...]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], -] +def encode_long(x: int) -> bytes: ... # undocumented +def decode_long(data: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer) -> int: ... # undocumented -class Pickler: +# undocumented pure-Python implementations +class _Pickler: fast: bool - dispatch_table: Mapping[type, Callable[[Any], _reducedtype]] + dispatch_table: Mapping[type, Callable[[Any], _ReducedType]] bin: bool # undocumented dispatch: ClassVar[dict[type, Callable[[Unpickler, Any], None]]] # undocumented, _Pickler only - - if sys.version_info >= (3, 8): - def __init__( - self, - file: _WritableFileobj, - protocol: int | None = ..., - *, - fix_imports: bool = ..., - buffer_callback: _BufferCallback = ..., - ) -> None: ... - def reducer_override(self, obj: Any) -> Any: ... - else: - def __init__(self, file: _WritableFileobj, protocol: int | None = ..., *, fix_imports: bool = ...) -> None: ... - def dump(self, __obj: Any) -> None: ... + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = None, + *, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, + ) -> None: ... + def dump(self, obj: Any) -> None: ... def clear_memo(self) -> None: ... def persistent_id(self, obj: Any) -> Any: ... + # The following method is not defined on _Pickler, but can be defined on + # sub-classes. Should return `NotImplemented` if pickling the supplied + # object is not supported and returns the same types as `__reduce__()`. + def reducer_override(self, obj: object, /) -> _ReducedType: ... -class Unpickler: +class _Unpickler: dispatch: ClassVar[dict[int, Callable[[Unpickler], None]]] # undocumented, _Unpickler only - - if sys.version_info >= (3, 8): - def __init__( - self, - file: _ReadableFileobj, - *, - fix_imports: bool = ..., - encoding: str = ..., - errors: str = ..., - buffers: Iterable[Any] | None = ..., - ) -> None: ... - else: - def __init__( - self, file: _ReadableFileobj, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ... - ) -> None: ... + def __init__( + self, + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = None, + ) -> None: ... def load(self) -> Any: ... - def find_class(self, __module_name: str, __global_name: str) -> Any: ... + def find_class(self, module: str, name: str) -> Any: ... def persistent_load(self, pid: Any) -> Any: ... - -MARK: bytes -STOP: bytes -POP: bytes -POP_MARK: bytes -DUP: bytes -FLOAT: bytes -INT: bytes -BININT: bytes -BININT1: bytes -LONG: bytes -BININT2: bytes -NONE: bytes -PERSID: bytes -BINPERSID: bytes -REDUCE: bytes -STRING: bytes -BINSTRING: bytes -SHORT_BINSTRING: bytes -UNICODE: bytes -BINUNICODE: bytes -APPEND: bytes -BUILD: bytes -GLOBAL: bytes -DICT: bytes -EMPTY_DICT: bytes -APPENDS: bytes -GET: bytes -BINGET: bytes -INST: bytes -LONG_BINGET: bytes -LIST: bytes -EMPTY_LIST: bytes -OBJ: bytes -PUT: bytes -BINPUT: bytes -LONG_BINPUT: bytes -SETITEM: bytes -TUPLE: bytes -EMPTY_TUPLE: bytes -SETITEMS: bytes -BINFLOAT: bytes - -TRUE: bytes -FALSE: bytes - -# protocol 2 -PROTO: bytes -NEWOBJ: bytes -EXT1: bytes -EXT2: bytes -EXT4: bytes -TUPLE1: bytes -TUPLE2: bytes -TUPLE3: bytes -NEWTRUE: bytes -NEWFALSE: bytes -LONG1: bytes -LONG4: bytes - -# protocol 3 -BINBYTES: bytes -SHORT_BINBYTES: bytes - -# protocol 4 -SHORT_BINUNICODE: bytes -BINUNICODE8: bytes -BINBYTES8: bytes -EMPTY_SET: bytes -ADDITEMS: bytes -FROZENSET: bytes -NEWOBJ_EX: bytes -STACK_GLOBAL: bytes -MEMOIZE: bytes -FRAME: bytes - -if sys.version_info >= (3, 8): - # Protocol 5 - BYTEARRAY8: bytes - NEXT_BUFFER: bytes - READONLY_BUFFER: bytes - -def encode_long(x: int) -> bytes: ... # undocumented -def decode_long(data: bytes) -> int: ... # undocumented - -# pure-Python implementations -_Pickler = Pickler # undocumented -_Unpickler = Unpickler # undocumented diff --git a/stdlib/pickletools.pyi b/stdlib/pickletools.pyi index 9fa51a3848ee..98353d960888 100644 --- a/stdlib/pickletools.pyi +++ b/stdlib/pickletools.pyi @@ -1,15 +1,20 @@ -from typing import IO, Any, Callable, Iterator, MutableMapping, Tuple, Type +import sys +from collections.abc import Callable, Iterator, MutableMapping +from typing import IO, Any, Final, TypeAlias -_Reader = Callable[[IO[bytes]], Any] -bytes_types: Tuple[Type[Any], ...] +__all__ = ["dis", "genops", "optimize"] -UP_TO_NEWLINE: int -TAKEN_FROM_ARGUMENT1: int -TAKEN_FROM_ARGUMENT4: int -TAKEN_FROM_ARGUMENT4U: int -TAKEN_FROM_ARGUMENT8U: int +_Reader: TypeAlias = Callable[[IO[bytes]], Any] +bytes_types: tuple[type[Any], ...] -class ArgumentDescriptor(object): +UP_TO_NEWLINE: Final = -1 +TAKEN_FROM_ARGUMENT1: Final = -2 +TAKEN_FROM_ARGUMENT4: Final = -3 +TAKEN_FROM_ARGUMENT4U: Final = -4 +TAKEN_FROM_ARGUMENT8U: Final = -5 + +class ArgumentDescriptor: + __slots__ = ("name", "n", "reader", "doc") name: str n: int reader: _Reader @@ -36,7 +41,13 @@ def read_uint8(f: IO[bytes]) -> int: ... uint8: ArgumentDescriptor -def read_stringnl(f: IO[bytes], decode: bool = ..., stripquotes: bool = ...) -> bytes | str: ... +if sys.version_info >= (3, 12): + def read_stringnl( + f: IO[bytes], decode: bool = True, stripquotes: bool = True, *, encoding: str = "latin-1" + ) -> bytes | str: ... + +else: + def read_stringnl(f: IO[bytes], decode: bool = True, stripquotes: bool = True) -> bytes | str: ... stringnl: ArgumentDescriptor @@ -106,11 +117,12 @@ def read_long4(f: IO[bytes]) -> int: ... long4: ArgumentDescriptor -class StackObject(object): +class StackObject: + __slots__ = ("name", "obtype", "doc") name: str - obtype: Type[Any] | Tuple[Type[Any], ...] + obtype: type[Any] | tuple[type[Any], ...] doc: str - def __init__(self, name: str, obtype: Type[Any] | Tuple[Type[Any], ...], doc: str) -> None: ... + def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ... pyint: StackObject pylong: StackObject @@ -131,7 +143,8 @@ anyobject: StackObject markobject: StackObject stackslice: StackObject -class OpcodeInfo(object): +class OpcodeInfo: + __slots__ = ("name", "code", "arg", "stack_before", "stack_after", "proto", "doc") name: str code: str arg: ArgumentDescriptor | None @@ -152,12 +165,12 @@ class OpcodeInfo(object): opcodes: list[OpcodeInfo] -def genops(pickle: bytes | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: ... -def optimize(p: bytes | IO[bytes]) -> bytes: ... +def genops(pickle: bytes | bytearray | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: ... +def optimize(p: bytes | bytearray | IO[bytes]) -> bytes: ... def dis( - pickle: bytes | IO[bytes], - out: IO[str] | None = ..., - memo: MutableMapping[int, Any] | None = ..., - indentlevel: int = ..., - annotate: int = ..., + pickle: bytes | bytearray | IO[bytes], + out: IO[str] | None = None, + memo: MutableMapping[int, Any] | None = None, + indentlevel: int = 4, + annotate: int = 0, ) -> None: ... diff --git a/stdlib/pipes.pyi b/stdlib/pipes.pyi index fb9d7e4e1d16..fe680bfddf5f 100644 --- a/stdlib/pipes.pyi +++ b/stdlib/pipes.pyi @@ -1,7 +1,8 @@ import os +__all__ = ["Template"] + class Template: - def __init__(self) -> None: ... def reset(self) -> None: ... def clone(self) -> Template: ... def debug(self, flag: bool) -> None: ... diff --git a/stdlib/pkgutil.pyi b/stdlib/pkgutil.pyi index e0f392fd91d8..6fdb01e728f4 100644 --- a/stdlib/pkgutil.pyi +++ b/stdlib/pkgutil.pyi @@ -1,31 +1,60 @@ import sys -from _typeshed import SupportsRead -from importlib.abc import Loader, MetaPathFinder, PathEntryFinder -from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple +from _typeshed import StrOrBytesPath, SupportsRead +from _typeshed.importlib import LoaderProtocol, MetaPathFinderProtocol, PathEntryFinderProtocol +from collections.abc import Callable, Iterable, Iterator +from typing import IO, Any, NamedTuple, TypeVar +from typing_extensions import deprecated + +__all__ = [ + "get_importer", + "iter_importers", + "walk_packages", + "iter_modules", + "get_data", + "read_code", + "extend_path", + "ModuleInfo", +] +if sys.version_info < (3, 14): + __all__ += ["get_loader", "find_loader"] +if sys.version_info < (3, 12): + __all__ += ["ImpImporter", "ImpLoader"] + +_PathT = TypeVar("_PathT", bound=Iterable[str]) class ModuleInfo(NamedTuple): - module_finder: MetaPathFinder | PathEntryFinder + module_finder: MetaPathFinderProtocol | PathEntryFinderProtocol name: str ispkg: bool -def extend_path(path: list[str], name: str) -> list[str]: ... +def extend_path(path: _PathT, name: str) -> _PathT: ... -class ImpImporter: - def __init__(self, path: str | None = ...) -> None: ... +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use the `importlib` module instead.") + class ImpImporter: + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... -class ImpLoader: - def __init__(self, fullname: str, file: IO[str], filename: str, etc: tuple[str, str, int]) -> None: ... + @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use the `importlib` module instead.") + class ImpLoader: + def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ... -def find_loader(fullname: str) -> Loader | None: ... -def get_importer(path_item: str) -> PathEntryFinder | None: ... -def get_loader(module_or_name: str) -> Loader: ... -def iter_importers(fullname: str = ...) -> Iterator[MetaPathFinder | PathEntryFinder]: ... -def iter_modules(path: Iterable[str] | None = ..., prefix: str = ...) -> Iterator[ModuleInfo]: ... +if sys.version_info < (3, 14): + @deprecated("Deprecated; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + def find_loader(fullname: str) -> LoaderProtocol | None: ... + @deprecated("Deprecated; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + def get_loader(module_or_name: str) -> LoaderProtocol | None: ... + +def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: ... +def iter_importers(fullname: str = "") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: ... +def iter_modules(path: Iterable[StrOrBytesPath] | None = None, prefix: str = "") -> Iterator[ModuleInfo]: ... def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented def walk_packages( - path: Iterable[str] | None = ..., prefix: str = ..., onerror: Callable[[str], None] | None = ... + path: Iterable[StrOrBytesPath] | None = None, prefix: str = "", onerror: Callable[[str], object] | None = None ) -> Iterator[ModuleInfo]: ... def get_data(package: str, resource: str) -> bytes | None: ... -if sys.version_info >= (3, 9): +if sys.version_info >= (3, 15): + def resolve_name(name: str, *, strict: bool = False) -> Any: ... + +else: def resolve_name(name: str) -> Any: ... diff --git a/stdlib/platform.pyi b/stdlib/platform.pyi index aa8cea4dc01a..8e35fdea92d1 100644 --- a/stdlib/platform.pyi +++ b/stdlib/platform.pyi @@ -1,52 +1,59 @@ import sys +from typing import NamedTuple, type_check_only +from typing_extensions import Self, deprecated, disjoint_base -if sys.version_info < (3, 8): - import os - - DEV_NULL = os.devnull -from typing import NamedTuple, Tuple - -if sys.version_info >= (3, 8): - def libc_ver(executable: str | None = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> tuple[str, str]: ... - -else: - def libc_ver(executable: str = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> tuple[str, str]: ... - -if sys.version_info < (3, 8): - def linux_distribution( - distname: str = ..., - version: str = ..., - id: str = ..., - supported_dists: Tuple[str, ...] = ..., - full_distribution_name: bool = ..., - ) -> tuple[str, str, str]: ... - def dist( - distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ... - ) -> tuple[str, str, str]: ... - -def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> tuple[str, str, str, str]: ... - -if sys.version_info >= (3, 8): - def win32_edition() -> str: ... - def win32_is_iot() -> bool: ... - +def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]: ... +def win32_ver(release: str = "", version: str = "", csd: str = "", ptype: str = "") -> tuple[str, str, str, str]: ... +def win32_edition() -> str: ... +def win32_is_iot() -> bool: ... def mac_ver( - release: str = ..., versioninfo: tuple[str, str, str] = ..., machine: str = ... + release: str = "", versioninfo: tuple[str, str, str] = ("", "", ""), machine: str = "" ) -> tuple[str, tuple[str, str, str], str]: ... -def java_ver( - release: str = ..., vendor: str = ..., vminfo: tuple[str, str, str] = ..., osinfo: tuple[str, str, str] = ... -) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ... + +if sys.version_info < (3, 15): + @deprecated("Deprecated; removed in Python 3.15.") + def java_ver( + release: str = "", + vendor: str = "", + vminfo: tuple[str, str, str] = ("", "", ""), + osinfo: tuple[str, str, str] = ("", "", ""), + ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ... + def system_alias(system: str, release: str, version: str) -> tuple[str, str, str]: ... -def architecture(executable: str = ..., bits: str = ..., linkage: str = ...) -> tuple[str, str]: ... +def architecture(executable: str = sys.executable, bits: str = "", linkage: str = "") -> tuple[str, str]: ... -class uname_result(NamedTuple): +# This class is not exposed. It calls itself platform.uname_result_base. +# At runtime it only has 5 fields. +@type_check_only +class _uname_result_base(NamedTuple): system: str node: str release: str version: str machine: str + # This base class doesn't have this field at runtime, but claiming it + # does is the least bad way to handle the situation. Nobody really + # sees this class anyway. See #13068 processor: str +# uname_result emulates a 6-field named tuple, but the processor field +# is lazily evaluated rather than being passed in to the constructor. +if sys.version_info >= (3, 12): + class uname_result(_uname_result_base): + __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] + + def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... + @property + def processor(self) -> str: ... # ty:ignore[invalid-named-tuple-override] + +else: + @disjoint_base + class uname_result(_uname_result_base): + __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] + def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... + @property + def processor(self) -> str: ... # ty:ignore[invalid-named-tuple-override] + def uname() -> uname_result: ... def system() -> str: ... def node() -> str: ... @@ -61,7 +68,33 @@ def python_branch() -> str: ... def python_revision() -> str: ... def python_build() -> tuple[str, str]: ... def python_compiler() -> str: ... -def platform(aliased: bool = ..., terse: bool = ...) -> str: ... +def platform(aliased: bool = False, terse: bool = False) -> str: ... +def freedesktop_os_release() -> dict[str, str]: ... + +if sys.version_info >= (3, 13): + class AndroidVer(NamedTuple): + release: str + api_level: int + manufacturer: str + model: str + device: str + is_emulator: bool + + class IOSVersionInfo(NamedTuple): + system: str + release: str + model: str + is_simulator: bool + + def android_ver( + release: str = "", + api_level: int = 0, + manufacturer: str = "", + model: str = "", + device: str = "", + is_emulator: bool = False, + ) -> AndroidVer: ... + def ios_ver(system: str = "", release: str = "", model: str = "", is_simulator: bool = False) -> IOSVersionInfo: ... -if sys.version_info >= (3, 10): - def freedesktop_os_release() -> dict[str, str]: ... +if sys.version_info >= (3, 14): + def invalidate_caches() -> None: ... diff --git a/stdlib/plistlib.pyi b/stdlib/plistlib.pyi index 07b6963746be..dc3247ee47fb 100644 --- a/stdlib/plistlib.pyi +++ b/stdlib/plistlib.pyi @@ -1,75 +1,84 @@ import sys +from _typeshed import ReadableBuffer +from collections.abc import Mapping, MutableMapping from datetime import datetime from enum import Enum -from typing import IO, Any, Dict as _Dict, Mapping, MutableMapping, Tuple, Type +from typing import IO, Any, Final +from typing_extensions import Self -class PlistFormat(Enum): - FMT_XML: int - FMT_BINARY: int - -FMT_XML = PlistFormat.FMT_XML -FMT_BINARY = PlistFormat.FMT_BINARY +__all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] -if sys.version_info >= (3, 9): - def load(fp: IO[bytes], *, fmt: PlistFormat | None = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... - def loads(value: bytes, *, fmt: PlistFormat | None = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... +class PlistFormat(Enum): + FMT_XML = 1 + FMT_BINARY = 2 -else: +FMT_XML: Final = PlistFormat.FMT_XML +FMT_BINARY: Final = PlistFormat.FMT_BINARY +if sys.version_info >= (3, 13): def load( fp: IO[bytes], *, - fmt: PlistFormat | None = ..., - use_builtin_types: bool = ..., - dict_type: Type[MutableMapping[str, Any]] = ..., + fmt: PlistFormat | None = None, + dict_type: type[MutableMapping[str, Any]] = ..., + aware_datetime: bool = False, ) -> Any: ... def loads( - value: bytes, + value: ReadableBuffer | str, *, - fmt: PlistFormat | None = ..., - use_builtin_types: bool = ..., - dict_type: Type[MutableMapping[str, Any]] = ..., + fmt: PlistFormat | None = None, + dict_type: type[MutableMapping[str, Any]] = ..., + aware_datetime: bool = False, ) -> Any: ... -def dump( - value: Mapping[str, Any] | list[Any] | Tuple[Any, ...] | str | bool | float | bytes | datetime, - fp: IO[bytes], - *, - fmt: PlistFormat = ..., - sort_keys: bool = ..., - skipkeys: bool = ..., -) -> None: ... -def dumps( - value: Mapping[str, Any] | list[Any] | Tuple[Any, ...] | str | bool | float | bytes | datetime, - *, - fmt: PlistFormat = ..., - skipkeys: bool = ..., - sort_keys: bool = ..., -) -> bytes: ... - -if sys.version_info < (3, 9): - def readPlist(pathOrFile: str | IO[bytes]) -> Any: ... - def writePlist(value: Mapping[str, Any], pathOrFile: str | IO[bytes]) -> None: ... - def readPlistFromBytes(data: bytes) -> Any: ... - def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... +else: + def load(fp: IO[bytes], *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... + def loads( + value: ReadableBuffer, *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ... + ) -> Any: ... -if sys.version_info < (3, 7): - class Dict(_Dict[str, Any]): - def __getattr__(self, attr: str) -> Any: ... - def __setattr__(self, attr: str, value: Any) -> None: ... - def __delattr__(self, attr: str) -> None: ... +if sys.version_info >= (3, 13): + def dump( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + fp: IO[bytes], + *, + fmt: PlistFormat = ..., + sort_keys: bool = True, + skipkeys: bool = False, + aware_datetime: bool = False, + ) -> None: ... + def dumps( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + *, + fmt: PlistFormat = ..., + skipkeys: bool = False, + sort_keys: bool = True, + aware_datetime: bool = False, + ) -> bytes: ... -if sys.version_info < (3, 9): - class Data: - data: bytes - def __init__(self, data: bytes) -> None: ... +else: + def dump( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + fp: IO[bytes], + *, + fmt: PlistFormat = ..., + sort_keys: bool = True, + skipkeys: bool = False, + ) -> None: ... + def dumps( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + *, + fmt: PlistFormat = ..., + skipkeys: bool = False, + sort_keys: bool = True, + ) -> bytes: ... -if sys.version_info >= (3, 8): - class UID: - data: int - def __init__(self, data: int) -> None: ... - def __index__(self) -> int: ... - def __reduce__(self) -> Any: ... - def __hash__(self) -> int: ... +class UID: + data: int + def __init__(self, data: int) -> None: ... + def __index__(self) -> int: ... + def __reduce__(self) -> tuple[type[Self], tuple[int]]: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... class InvalidFileException(ValueError): - def __init__(self, message: str = ...) -> None: ... + def __init__(self, message: str = "Invalid file") -> None: ... diff --git a/stdlib/poplib.pyi b/stdlib/poplib.pyi index 28fba4ce951f..59d95c0882f1 100644 --- a/stdlib/poplib.pyi +++ b/stdlib/poplib.pyi @@ -1,18 +1,24 @@ import socket import ssl -from typing import Any, BinaryIO, List, Pattern, Tuple, overload +import sys +from _typeshed import StrOrBytesPath +from builtins import list as _list # conflicts with a method named "list" +from re import Pattern +from typing import Any, BinaryIO, Final, TypeAlias, overload +from typing_extensions import Never, deprecated -_LongResp = Tuple[bytes, List[bytes], int] +__all__ = ["POP3", "error_proto", "POP3_SSL"] -class error_proto(Exception): ... +_LongResp: TypeAlias = tuple[bytes, list[bytes], int] -POP3_PORT: int -POP3_SSL_PORT: int -CR: bytes -LF: bytes -CRLF: bytes +class error_proto(Exception): ... -_list = list # conflicts with a method named "list" +POP3_PORT: Final = 110 +POP3_SSL_PORT: Final = 995 +CR: Final = b"\r" +LF: Final = b"\n" +CRLF: Final = b"\r\n" +HAVE_SSL: Final[bool] class POP3: encoding: str @@ -21,13 +27,13 @@ class POP3: sock: socket.socket file: BinaryIO welcome: bytes - def __init__(self, host: str, port: int = ..., timeout: float = ...) -> None: ... + def __init__(self, host: str, port: int = 110, timeout: float = ...) -> None: ... def getwelcome(self) -> bytes: ... def set_debuglevel(self, level: int) -> None: ... def user(self, user: str) -> bytes: ... def pass_(self, pswd: str) -> bytes: ... def stat(self) -> tuple[int, int]: ... - def list(self, which: Any | None = ...) -> _LongResp: ... + def list(self, which: Any | None = None) -> _LongResp: ... def retr(self, which: Any) -> _LongResp: ... def dele(self, which: Any) -> bytes: ... def noop(self) -> bytes: ... @@ -38,23 +44,50 @@ class POP3: timestamp: Pattern[str] def apop(self, user: str, password: str) -> bytes: ... def top(self, which: Any, howmuch: int) -> _LongResp: ... + @overload def uidl(self) -> _LongResp: ... @overload def uidl(self, which: Any) -> bytes: ... + def utf8(self) -> bytes: ... def capa(self) -> dict[str, _list[str]]: ... - def stls(self, context: ssl.SSLContext | None = ...) -> bytes: ... + def stls(self, context: ssl.SSLContext | None = None) -> bytes: ... class POP3_SSL(POP3): - def __init__( - self, - host: str, - port: int = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - timeout: float = ..., - context: ssl.SSLContext | None = ..., - ) -> None: ... - # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored - def stls(self, context: Any = ..., keyfile: Any = ..., certfile: Any = ...) -> bytes: ... + if sys.version_info >= (3, 12): + def __init__( + self, host: str, port: int = 995, *, timeout: float = ..., context: ssl.SSLContext | None = None + ) -> None: ... + def stls(self, context: Any = None) -> Never: ... + else: + @overload + def __init__( + self, + host: str, + port: int = 995, + keyfile: None = None, + certfile: None = None, + timeout: float = ..., + context: ssl.SSLContext | None = None, + ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def __init__( + self, + host: str, + port: int = 995, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + timeout: float = ..., + context: None = None, + ) -> None: ... + + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None + # "context" is actually the last argument, + # but that breaks LSP and it doesn't really matter because all the arguments are ignored + def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> Never: ... diff --git a/stdlib/posix.pyi b/stdlib/posix.pyi index cdca4235d3ba..36bb5be18e88 100644 --- a/stdlib/posix.pyi +++ b/stdlib/posix.pyi @@ -6,6 +6,8 @@ if sys.platform != "win32": CLD_CONTINUED as CLD_CONTINUED, CLD_DUMPED as CLD_DUMPED, CLD_EXITED as CLD_EXITED, + CLD_KILLED as CLD_KILLED, + CLD_STOPPED as CLD_STOPPED, CLD_TRAPPED as CLD_TRAPPED, EX_CANTCREAT as EX_CANTCREAT, EX_CONFIG as EX_CONFIG, @@ -14,7 +16,6 @@ if sys.platform != "win32": EX_NOHOST as EX_NOHOST, EX_NOINPUT as EX_NOINPUT, EX_NOPERM as EX_NOPERM, - EX_NOTFOUND as EX_NOTFOUND, EX_NOUSER as EX_NOUSER, EX_OK as EX_OK, EX_OSERR as EX_OSERR, @@ -29,28 +30,31 @@ if sys.platform != "win32": F_TEST as F_TEST, F_TLOCK as F_TLOCK, F_ULOCK as F_ULOCK, + NGROUPS_MAX as NGROUPS_MAX, + O_ACCMODE as O_ACCMODE, O_APPEND as O_APPEND, O_ASYNC as O_ASYNC, + O_CLOEXEC as O_CLOEXEC, O_CREAT as O_CREAT, - O_DIRECT as O_DIRECT, O_DIRECTORY as O_DIRECTORY, O_DSYNC as O_DSYNC, O_EXCL as O_EXCL, - O_LARGEFILE as O_LARGEFILE, + O_FSYNC as O_FSYNC, O_NDELAY as O_NDELAY, - O_NOATIME as O_NOATIME, O_NOCTTY as O_NOCTTY, O_NOFOLLOW as O_NOFOLLOW, O_NONBLOCK as O_NONBLOCK, O_RDONLY as O_RDONLY, O_RDWR as O_RDWR, - O_RSYNC as O_RSYNC, O_SYNC as O_SYNC, O_TRUNC as O_TRUNC, O_WRONLY as O_WRONLY, P_ALL as P_ALL, P_PGID as P_PGID, P_PID as P_PID, + POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE, + POSIX_SPAWN_DUP2 as POSIX_SPAWN_DUP2, + POSIX_SPAWN_OPEN as POSIX_SPAWN_OPEN, PRIO_PGRP as PRIO_PGRP, PRIO_PROCESS as PRIO_PROCESS, PRIO_USER as PRIO_USER, @@ -61,15 +65,13 @@ if sys.platform != "win32": RTLD_NODELETE as RTLD_NODELETE, RTLD_NOLOAD as RTLD_NOLOAD, RTLD_NOW as RTLD_NOW, - SCHED_BATCH as SCHED_BATCH, SCHED_FIFO as SCHED_FIFO, - SCHED_IDLE as SCHED_IDLE, SCHED_OTHER as SCHED_OTHER, - SCHED_RESET_ON_FORK as SCHED_RESET_ON_FORK, SCHED_RR as SCHED_RR, - SCHED_SPORADIC as SCHED_SPORADIC, SEEK_DATA as SEEK_DATA, SEEK_HOLE as SEEK_HOLE, + ST_NOSUID as ST_NOSUID, + ST_RDONLY as ST_RDONLY, TMP_MAX as TMP_MAX, W_OK as W_OK, WCONTINUED as WCONTINUED, @@ -159,12 +161,17 @@ if sys.platform != "win32": pathconf as pathconf, pathconf_names as pathconf_names, pipe as pipe, + posix_spawn as posix_spawn, + posix_spawnp as posix_spawnp, pread as pread, + preadv as preadv, putenv as putenv, pwrite as pwrite, + pwritev as pwritev, read as read, readlink as readlink, readv as readv, + register_at_fork as register_at_fork, remove as remove, rename as rename, replace as replace, @@ -216,26 +223,75 @@ if sys.platform != "win32": wait3 as wait3, wait4 as wait4, waitpid as waitpid, + waitstatus_to_exitcode as waitstatus_to_exitcode, write as write, writev as writev, ) - if sys.platform == "linux": + if sys.version_info >= (3, 11): + from os import login_tty as login_tty + + if sys.version_info >= (3, 13): + from os import grantpt as grantpt, posix_openpt as posix_openpt, ptsname as ptsname, unlockpt as unlockpt + + if sys.version_info >= (3, 13) and sys.platform == "linux": from os import ( - GRND_NONBLOCK as GRND_NONBLOCK, - GRND_RANDOM as GRND_RANDOM, - RTLD_DEEPBIND as RTLD_DEEPBIND, - XATTR_CREATE as XATTR_CREATE, - XATTR_REPLACE as XATTR_REPLACE, - XATTR_SIZE_MAX as XATTR_SIZE_MAX, - getrandom as getrandom, - getxattr as getxattr, - listxattr as listxattr, - removexattr as removexattr, - setxattr as setxattr, + POSIX_SPAWN_CLOSEFROM as POSIX_SPAWN_CLOSEFROM, + TFD_CLOEXEC as TFD_CLOEXEC, + TFD_NONBLOCK as TFD_NONBLOCK, + TFD_TIMER_ABSTIME as TFD_TIMER_ABSTIME, + TFD_TIMER_CANCEL_ON_SET as TFD_TIMER_CANCEL_ON_SET, + timerfd_create as timerfd_create, + timerfd_gettime as timerfd_gettime, + timerfd_gettime_ns as timerfd_gettime_ns, + timerfd_settime as timerfd_settime, + timerfd_settime_ns as timerfd_settime_ns, + ) + + if sys.version_info >= (3, 14): + from os import readinto as readinto + + if sys.version_info >= (3, 14) and sys.platform == "linux": + from os import SCHED_DEADLINE as SCHED_DEADLINE, SCHED_NORMAL as SCHED_NORMAL + + if sys.platform != "linux": + from os import O_EXLOCK as O_EXLOCK, O_SHLOCK as O_SHLOCK, chflags as chflags, lchflags as lchflags, lchmod as lchmod + + if sys.platform != "linux" and sys.platform != "darwin": + from os import EX_NOTFOUND as EX_NOTFOUND, SCHED_SPORADIC as SCHED_SPORADIC + + if sys.platform != "linux" and sys.version_info >= (3, 13): + from os import O_EXEC as O_EXEC, O_SEARCH as O_SEARCH + + if sys.version_info >= (3, 15): + from os import NODEV as NODEV + + if sys.version_info >= (3, 15) and sys.platform == "linux": + from os import ( + AT_NO_AUTOMOUNT as AT_NO_AUTOMOUNT, + AT_STATX_DONT_SYNC as AT_STATX_DONT_SYNC, + AT_STATX_FORCE_SYNC as AT_STATX_FORCE_SYNC, + AT_STATX_SYNC_AS_STAT as AT_STATX_SYNC_AS_STAT, + STATX_ATIME as STATX_ATIME, + STATX_BASIC_STATS as STATX_BASIC_STATS, + STATX_BLOCKS as STATX_BLOCKS, + STATX_BTIME as STATX_BTIME, + STATX_CTIME as STATX_CTIME, + STATX_DIOALIGN as STATX_DIOALIGN, + STATX_GID as STATX_GID, + STATX_INO as STATX_INO, + STATX_MNT_ID as STATX_MNT_ID, + STATX_MNT_ID_UNIQUE as STATX_MNT_ID_UNIQUE, + STATX_MODE as STATX_MODE, + STATX_MTIME as STATX_MTIME, + STATX_NLINK as STATX_NLINK, + STATX_SIZE as STATX_SIZE, + STATX_TYPE as STATX_TYPE, + STATX_UID as STATX_UID, + _clearenv as _clearenv, + statx as statx, + statx_result as statx_result, ) - else: - from os import chflags as chflags, lchflags as lchflags, lchmod as lchmod if sys.platform != "darwin": from os import ( @@ -245,6 +301,20 @@ if sys.platform != "win32": POSIX_FADV_RANDOM as POSIX_FADV_RANDOM, POSIX_FADV_SEQUENTIAL as POSIX_FADV_SEQUENTIAL, POSIX_FADV_WILLNEED as POSIX_FADV_WILLNEED, + RWF_APPEND as RWF_APPEND, + RWF_DSYNC as RWF_DSYNC, + RWF_HIPRI as RWF_HIPRI, + RWF_NOWAIT as RWF_NOWAIT, + RWF_SYNC as RWF_SYNC, + ST_APPEND as ST_APPEND, + ST_MANDLOCK as ST_MANDLOCK, + ST_NOATIME as ST_NOATIME, + ST_NODEV as ST_NODEV, + ST_NODIRATIME as ST_NODIRATIME, + ST_NOEXEC as ST_NOEXEC, + ST_RELATIME as ST_RELATIME, + ST_SYNCHRONOUS as ST_SYNCHRONOUS, + ST_WRITE as ST_WRITE, fdatasync as fdatasync, getresgid as getresgid, getresuid as getresuid, @@ -260,38 +330,97 @@ if sys.platform != "win32": sched_setscheduler as sched_setscheduler, setresgid as setresgid, setresuid as setresuid, - waitid as waitid, - waitid_result as waitid_result, ) - if sys.version_info >= (3, 9): - from os import waitstatus_to_exitcode as waitstatus_to_exitcode - if sys.version_info >= (3, 8): - from os import posix_spawn as posix_spawn, posix_spawnp as posix_spawnp + if sys.platform != "darwin" or sys.version_info >= (3, 13): + from os import waitid as waitid, waitid_result as waitid_result + + if sys.platform == "linux": + from os import ( + EFD_CLOEXEC as EFD_CLOEXEC, + EFD_NONBLOCK as EFD_NONBLOCK, + EFD_SEMAPHORE as EFD_SEMAPHORE, + GRND_NONBLOCK as GRND_NONBLOCK, + GRND_RANDOM as GRND_RANDOM, + MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, + MFD_CLOEXEC as MFD_CLOEXEC, + MFD_HUGE_1GB as MFD_HUGE_1GB, + MFD_HUGE_1MB as MFD_HUGE_1MB, + MFD_HUGE_2GB as MFD_HUGE_2GB, + MFD_HUGE_2MB as MFD_HUGE_2MB, + MFD_HUGE_8MB as MFD_HUGE_8MB, + MFD_HUGE_16GB as MFD_HUGE_16GB, + MFD_HUGE_16MB as MFD_HUGE_16MB, + MFD_HUGE_32MB as MFD_HUGE_32MB, + MFD_HUGE_64KB as MFD_HUGE_64KB, + MFD_HUGE_256MB as MFD_HUGE_256MB, + MFD_HUGE_512KB as MFD_HUGE_512KB, + MFD_HUGE_512MB as MFD_HUGE_512MB, + MFD_HUGE_MASK as MFD_HUGE_MASK, + MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, + MFD_HUGETLB as MFD_HUGETLB, + O_DIRECT as O_DIRECT, + O_LARGEFILE as O_LARGEFILE, + O_NOATIME as O_NOATIME, + O_PATH as O_PATH, + O_RSYNC as O_RSYNC, + O_TMPFILE as O_TMPFILE, + P_PIDFD as P_PIDFD, + RTLD_DEEPBIND as RTLD_DEEPBIND, + SCHED_BATCH as SCHED_BATCH, + SCHED_IDLE as SCHED_IDLE, + SCHED_RESET_ON_FORK as SCHED_RESET_ON_FORK, + SPLICE_F_MORE as SPLICE_F_MORE, + SPLICE_F_MOVE as SPLICE_F_MOVE, + SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK, + XATTR_CREATE as XATTR_CREATE, + XATTR_REPLACE as XATTR_REPLACE, + XATTR_SIZE_MAX as XATTR_SIZE_MAX, + copy_file_range as copy_file_range, + eventfd as eventfd, + eventfd_read as eventfd_read, + eventfd_write as eventfd_write, + getrandom as getrandom, + getxattr as getxattr, + listxattr as listxattr, + memfd_create as memfd_create, + pidfd_open as pidfd_open, + removexattr as removexattr, + setxattr as setxattr, + splice as splice, + ) + + if sys.version_info >= (3, 12): + from os import ( + CLONE_FILES as CLONE_FILES, + CLONE_FS as CLONE_FS, + CLONE_NEWCGROUP as CLONE_NEWCGROUP, + CLONE_NEWIPC as CLONE_NEWIPC, + CLONE_NEWNET as CLONE_NEWNET, + CLONE_NEWNS as CLONE_NEWNS, + CLONE_NEWPID as CLONE_NEWPID, + CLONE_NEWTIME as CLONE_NEWTIME, + CLONE_NEWUSER as CLONE_NEWUSER, + CLONE_NEWUTS as CLONE_NEWUTS, + CLONE_SIGHAND as CLONE_SIGHAND, + CLONE_SYSVSEM as CLONE_SYSVSEM, + CLONE_THREAD as CLONE_THREAD, + CLONE_VM as CLONE_VM, + PIDFD_NONBLOCK as PIDFD_NONBLOCK, + setns as setns, + unshare as unshare, + ) + + if sys.platform == "darwin": + from os import O_EVTONLY as O_EVTONLY, O_NOFOLLOW_ANY as O_NOFOLLOW_ANY, O_SYMLINK as O_SYMLINK - if sys.platform == "linux": + if sys.version_info >= (3, 12): from os import ( - MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, - MFD_CLOEXEC as MFD_CLOEXEC, - MFD_HUGE_1GB as MFD_HUGE_1GB, - MFD_HUGE_1MB as MFD_HUGE_1MB, - MFD_HUGE_2GB as MFD_HUGE_2GB, - MFD_HUGE_2MB as MFD_HUGE_2MB, - MFD_HUGE_8MB as MFD_HUGE_8MB, - MFD_HUGE_16GB as MFD_HUGE_16GB, - MFD_HUGE_16MB as MFD_HUGE_16MB, - MFD_HUGE_32MB as MFD_HUGE_32MB, - MFD_HUGE_64KB as MFD_HUGE_64KB, - MFD_HUGE_256MB as MFD_HUGE_256MB, - MFD_HUGE_512KB as MFD_HUGE_512KB, - MFD_HUGE_512MB as MFD_HUGE_512MB, - MFD_HUGE_MASK as MFD_HUGE_MASK, - MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, - MFD_HUGETLB as MFD_HUGETLB, - memfd_create as memfd_create, + PRIO_DARWIN_BG as PRIO_DARWIN_BG, + PRIO_DARWIN_NONUI as PRIO_DARWIN_NONUI, + PRIO_DARWIN_PROCESS as PRIO_DARWIN_PROCESS, + PRIO_DARWIN_THREAD as PRIO_DARWIN_THREAD, ) - if sys.version_info >= (3, 7): - from os import register_at_fork as register_at_fork # Not same as os.environ or os.environb # Because of this variable, we can't do "from posix import *" in os/__init__.pyi diff --git a/stdlib/posixpath.pyi b/stdlib/posixpath.pyi index ae3d0d5cc65f..b4068629b698 100644 --- a/stdlib/posixpath.pyi +++ b/stdlib/posixpath.pyi @@ -1,6 +1,9 @@ import sys -from _typeshed import BytesPath, StrOrBytesPath, StrPath +from _typeshed import AnyOrLiteralStr, BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath +from collections.abc import Iterable from genericpath import ( + ALLOW_MISSING as ALLOW_MISSING, + _AllowMissingType, commonprefix as commonprefix, exists as exists, getatime as getatime, @@ -13,87 +16,215 @@ from genericpath import ( sameopenfile as sameopenfile, samestat as samestat, ) + +if sys.version_info >= (3, 15): + from genericpath import ALL_BUT_LAST as ALL_BUT_LAST + +if sys.version_info >= (3, 13): + from genericpath import isdevdrive as isdevdrive from os import PathLike -from typing import AnyStr, Sequence, overload +from typing import AnyStr, overload +from typing_extensions import LiteralString + +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "samefile", + "sameopenfile", + "samestat", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "commonpath", +] +__all__ += ["ALLOW_MISSING"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] +if sys.version_info >= (3, 12): + __all__ += ["isjunction", "splitroot"] +if sys.version_info >= (3, 13): + __all__ += ["isdevdrive"] supports_unicode_filenames: bool # aliases (also in os) -curdir: str -pardir: str -sep: str -altsep: str | None -extsep: str -pathsep: str -defpath: str -devnull: str +curdir: LiteralString +pardir: LiteralString +sep: LiteralString +altsep: LiteralString | None +extsep: LiteralString +pathsep: LiteralString +defpath: LiteralString +devnull: LiteralString -# Overloads are necessary to work around python/mypy#3644. +# Overloads are necessary to work around python/mypy#17952 & python/mypy#11880 @overload def abspath(path: PathLike[AnyStr]) -> AnyStr: ... @overload def abspath(path: AnyStr) -> AnyStr: ... -@overload -def basename(p: PathLike[AnyStr]) -> AnyStr: ... -@overload -def basename(p: AnyStr) -> AnyStr: ... -@overload -def dirname(p: PathLike[AnyStr]) -> AnyStr: ... -@overload -def dirname(p: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 15): + @overload + def basename(p: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def basename(p: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... + + @overload + def dirname(p: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def dirname(p: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... +else: + @overload + def basename(p: PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + + @overload + def dirname(p: PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + @overload def expanduser(path: PathLike[AnyStr]) -> AnyStr: ... @overload def expanduser(path: AnyStr) -> AnyStr: ... + @overload def expandvars(path: PathLike[AnyStr]) -> AnyStr: ... @overload def expandvars(path: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 15): + @overload + def normcase(s: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def normcase(s: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... +else: + @overload + def normcase(s: PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + @overload -def normcase(s: PathLike[AnyStr]) -> AnyStr: ... +def normpath(path: PathLike[AnyStr]) -> AnyStr: ... @overload -def normcase(s: AnyStr) -> AnyStr: ... +def normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + @overload -def normpath(path: PathLike[AnyStr]) -> AnyStr: ... +def commonpath(paths: Iterable[LiteralString]) -> LiteralString: ... @overload -def normpath(path: AnyStr) -> AnyStr: ... +def commonpath(paths: Iterable[StrPath]) -> str: ... @overload -def commonpath(paths: Sequence[StrPath]) -> str: ... +def commonpath(paths: Iterable[BytesPath]) -> bytes: ... + +# First parameter is not actually pos-only before Python 3.15, +# but must be defined as pos-only in the stub or cross-platform code doesn't type-check, +# as the parameter name is different in ntpath.join() @overload -def commonpath(paths: Sequence[BytesPath]) -> bytes: ... +def join(a: LiteralString, /, *paths: LiteralString) -> LiteralString: ... @overload -def join(a: StrPath, *paths: StrPath) -> str: ... +def join(a: StrPath, /, *paths: StrPath) -> str: ... @overload -def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +def join(a: BytesPath, /, *paths: BytesPath) -> bytes: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 15): @overload - def realpath(filename: PathLike[AnyStr], *, strict: bool = ...) -> AnyStr: ... + def realpath(filename: PathLike[AnyStr], /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... @overload - def realpath(filename: AnyStr, *, strict: bool = ...) -> AnyStr: ... - + def realpath(filename: AnyStr, /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... else: @overload - def realpath(filename: PathLike[AnyStr]) -> AnyStr: ... + def realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... @overload - def realpath(filename: AnyStr) -> AnyStr: ... + def realpath(filename: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... @overload -def relpath(path: BytesPath, start: BytesPath | None = ...) -> bytes: ... -@overload -def relpath(path: StrPath, start: StrPath | None = ...) -> str: ... -@overload -def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... +def relpath(path: LiteralString, start: LiteralString | None = None) -> LiteralString: ... @overload -def split(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def relpath(path: BytesPath, start: BytesPath | None = None) -> bytes: ... @overload -def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def splitdrive(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... -@overload -def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def splitext(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... -def isabs(s: StrOrBytesPath) -> bool: ... -def islink(path: StrOrBytesPath | int) -> bool: ... -def ismount(path: StrOrBytesPath | int) -> bool: ... -def lexists(path: StrOrBytesPath | int) -> bool: ... +def relpath(path: StrPath, start: StrPath | None = None) -> str: ... + +if sys.version_info >= (3, 15): + @overload + def split(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + + @overload + def splitdrive(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... +else: + @overload + def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + + @overload + def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + +if sys.version_info >= (3, 15): + @overload + def splitext(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... +else: + @overload + def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + +if sys.version_info >= (3, 15): + def isabs(s: StrOrBytesPath, /) -> bool: ... + +else: + def isabs(s: StrOrBytesPath) -> bool: ... + +def islink(path: FileDescriptorOrPath) -> bool: ... +def ismount(path: FileDescriptorOrPath) -> bool: ... +def lexists(path: FileDescriptorOrPath) -> bool: ... + +if sys.version_info >= (3, 12): + def isjunction(path: StrOrBytesPath) -> bool: ... + + if sys.version_info >= (3, 15): + @overload + def splitroot(path: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(path: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr, AnyStr]: ... + else: + @overload + def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr, AnyStr]: ... diff --git a/stdlib/pprint.pyi b/stdlib/pprint.pyi index 9e343feb49bc..dd2902021657 100644 --- a/stdlib/pprint.pyi +++ b/stdlib/pprint.pyi @@ -1,91 +1,90 @@ import sys -from typing import IO, Any +from _typeshed import SupportsWrite +from collections import deque +from typing import IO -if sys.version_info >= (3, 10): +__all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter", "pp"] + +if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. def pformat( object: object, - indent: int = ..., - width: int = ..., - depth: int | None = ..., + indent: int = 1, + width: int = 80, + depth: int | None = None, *, - compact: bool = ..., - sort_dicts: bool = ..., - underscore_numbers: bool = ..., + compact: bool = False, + expand: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> str: ... -elif sys.version_info >= (3, 8): +else: def pformat( object: object, - indent: int = ..., - width: int = ..., - depth: int | None = ..., + indent: int = 1, + width: int = 80, + depth: int | None = None, *, - compact: bool = ..., - sort_dicts: bool = ..., + compact: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> str: ... -else: - def pformat(object: object, indent: int = ..., width: int = ..., depth: int | None = ..., *, compact: bool = ...) -> str: ... - -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. def pp( object: object, - stream: IO[str] | None = ..., - indent: int = ..., - width: int = ..., - depth: int | None = ..., + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, *, - compact: bool = ..., - sort_dicts: bool = ..., - underscore_numbers: bool = ..., + compact: bool = False, + expand: bool = False, + sort_dicts: bool = False, + underscore_numbers: bool = False, ) -> None: ... -elif sys.version_info >= (3, 8): +else: def pp( object: object, - stream: IO[str] | None = ..., - indent: int = ..., - width: int = ..., - depth: int | None = ..., - *, - compact: bool = ..., - sort_dicts: bool = ..., - ) -> None: ... - -if sys.version_info >= (3, 10): - def pprint( - object: object, - stream: IO[str] | None = ..., - indent: int = ..., - width: int = ..., - depth: int | None = ..., + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, *, - compact: bool = ..., - sort_dicts: bool = ..., - underscore_numbers: bool = ..., + compact: bool = False, + sort_dicts: bool = False, + underscore_numbers: bool = False, ) -> None: ... -elif sys.version_info >= (3, 8): +if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. def pprint( object: object, - stream: IO[str] | None = ..., - indent: int = ..., - width: int = ..., - depth: int | None = ..., + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, *, - compact: bool = ..., - sort_dicts: bool = ..., + compact: bool = False, + expand: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> None: ... else: def pprint( object: object, - stream: IO[str] | None = ..., - indent: int = ..., - width: int = ..., - depth: int | None = ..., + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, *, - compact: bool = ..., + compact: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> None: ... def isreadable(object: object) -> bool: ... @@ -93,41 +92,79 @@ def isrecursive(object: object) -> bool: ... def saferepr(object: object) -> str: ... class PrettyPrinter: - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. def __init__( self, - indent: int = ..., - width: int = ..., - depth: int | None = ..., - stream: IO[str] | None = ..., + indent: int = 1, + width: int = 80, + depth: int | None = None, + stream: IO[str] | None = None, *, - compact: bool = ..., - sort_dicts: bool = ..., - underscore_numbers: bool = ..., - ) -> None: ... - elif sys.version_info >= (3, 8): - def __init__( - self, - indent: int = ..., - width: int = ..., - depth: int | None = ..., - stream: IO[str] | None = ..., - *, - compact: bool = ..., - sort_dicts: bool = ..., + compact: bool = False, + expand: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> None: ... else: def __init__( self, - indent: int = ..., - width: int = ..., - depth: int | None = ..., - stream: IO[str] | None = ..., + indent: int = 1, + width: int = 80, + depth: int | None = None, + stream: IO[str] | None = None, *, - compact: bool = ..., + compact: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> None: ... + def pformat(self, object: object) -> str: ... def pprint(self, object: object) -> None: ... def isreadable(self, object: object) -> bool: ... def isrecursive(self, object: object) -> bool: ... - def format(self, object: object, context: dict[int, Any], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... + def format(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... + def _format( + self, object: object, stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _pprint_dict( + self, + object: dict[object, object], + stream: SupportsWrite[str], + indent: int, + allowance: int, + context: dict[int, int], + level: int, + ) -> None: ... + def _pprint_list( + self, object: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _pprint_tuple( + self, + object: tuple[object, ...], + stream: SupportsWrite[str], + indent: int, + allowance: int, + context: dict[int, int], + level: int, + ) -> None: ... + def _pprint_set( + self, object: set[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _pprint_deque( + self, object: deque[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _format_dict_items( + self, + items: list[tuple[object, object]], + stream: SupportsWrite[str], + indent: int, + allowance: int, + context: dict[int, int], + level: int, + ) -> None: ... + def _format_items( + self, items: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _repr(self, object: object, context: dict[int, int], level: int) -> str: ... + def _safe_repr(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... diff --git a/stdlib/profile.pyi b/stdlib/profile.pyi index cb0cbf7c9388..06ce9a0e44c8 100644 --- a/stdlib/profile.pyi +++ b/stdlib/profile.pyi @@ -1,27 +1,31 @@ from _typeshed import StrOrBytesPath -from typing import Any, Callable, Tuple, TypeVar +from collections.abc import Callable, Mapping +from typing import Any, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self -def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... +__all__ = ["run", "runctx", "Profile"] + +def run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: ... def runctx( - statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... + statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1 ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_P = ParamSpec("_P") +_Label: TypeAlias = tuple[str, int, str] class Profile: bias: int stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented - def __init__(self, timer: Callable[[], float] | None = ..., bias: int | None = ...) -> None: ... + def __init__(self, timer: Callable[[], float] | None = None, bias: int | None = None) -> None: ... def set_cmd(self, cmd: str) -> None: ... def simulate_call(self, name: str) -> None: ... def simulate_cmd_complete(self) -> None: ... - def print_stats(self, sort: str | int = ...) -> None: ... + def print_stats(self, sort: str | int = -1) -> None: ... def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> _SelfT: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... - def calibrate(self, m: int, verbose: int = ...) -> float: ... + def run(self, cmd: str) -> Self: ... + def runctx(self, cmd: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> Self: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... + def calibrate(self, m: int, verbose: int = 0) -> float: ... diff --git a/stdlib/profiling/__init__.pyi b/stdlib/profiling/__init__.pyi new file mode 100644 index 000000000000..435f5a6cc66c --- /dev/null +++ b/stdlib/profiling/__init__.pyi @@ -0,0 +1,3 @@ +from . import sampling as sampling, tracing as tracing + +__all__ = ("tracing", "sampling") diff --git a/stdlib/profiling/sampling/__init__.pyi b/stdlib/profiling/sampling/__init__.pyi new file mode 100644 index 000000000000..1f8b3f7d98fe --- /dev/null +++ b/stdlib/profiling/sampling/__init__.pyi @@ -0,0 +1,17 @@ +from .collector import Collector as Collector +from .gecko_collector import GeckoCollector as GeckoCollector +from .heatmap_collector import HeatmapCollector as HeatmapCollector +from .jsonl_collector import JsonlCollector as JsonlCollector +from .pstats_collector import PstatsCollector as PstatsCollector +from .stack_collector import CollapsedStackCollector as CollapsedStackCollector +from .string_table import StringTable as StringTable + +__all__ = ( + "Collector", + "PstatsCollector", + "CollapsedStackCollector", + "HeatmapCollector", + "GeckoCollector", + "JsonlCollector", + "StringTable", +) diff --git a/stdlib/profiling/sampling/collector.pyi b/stdlib/profiling/sampling/collector.pyi new file mode 100644 index 000000000000..a72a185a2fb7 --- /dev/null +++ b/stdlib/profiling/sampling/collector.pyi @@ -0,0 +1,25 @@ +from _typeshed import StrOrBytesPath +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import ClassVar, TypeAlias + +from _remote_debugging import AwaitedInfo, FrameInfo, InterpreterInfo, LocationInfo + +_Location: TypeAlias = int | tuple[int, int, int, int] | LocationInfo | None +_Frame: TypeAlias = FrameInfo | tuple[str, _Location, str, int | None] +_Timestamps: TypeAlias = Sequence[int] | None + +def normalize_location(location: _Location) -> tuple[int, int, int, int]: ... +def extract_lineno(location: _Location) -> int: ... +def filter_internal_frames(frames: Sequence[_Frame]) -> list[_Frame]: ... +def iter_async_frames(awaited_info_list: Sequence[AwaitedInfo]) -> object: ... + +class Collector(ABC): + aggregating: ClassVar[bool] # undocumented + @abstractmethod + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def collect_failed_sample(self) -> None: ... + @abstractmethod + def export(self, filename: StrOrBytesPath) -> None: ... diff --git a/stdlib/profiling/sampling/gecko_collector.pyi b/stdlib/profiling/sampling/gecko_collector.pyi new file mode 100644 index 000000000000..666fd42c3ea5 --- /dev/null +++ b/stdlib/profiling/sampling/gecko_collector.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath +from collections.abc import Generator, Sequence +from tempfile import TemporaryDirectory +from typing import Any, ClassVar, Final, TypedDict, type_check_only + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Timestamps + +@type_check_only +class _GeckoCategory(TypedDict): + name: str + color: str + subcategories: list[str] + +THREAD_STATUS_HAS_GIL: Final[int] +THREAD_STATUS_ON_CPU: Final[int] +THREAD_STATUS_UNKNOWN: Final[int] +THREAD_STATUS_GIL_REQUESTED: Final[int] +THREAD_STATUS_HAS_EXCEPTION: Final[int] +THREAD_STATUS_MAIN_THREAD: Final[int] + +GECKO_CATEGORIES: Final[list[_GeckoCategory]] + +CATEGORY_OTHER: Final = 0 +CATEGORY_PYTHON: Final = 1 +CATEGORY_NATIVE: Final = 2 +CATEGORY_GC: Final = 3 +CATEGORY_GIL: Final = 4 +CATEGORY_CPU: Final = 5 +CATEGORY_CODE_TYPE: Final = 6 +CATEGORY_OPCODES: Final = 7 +CATEGORY_EXCEPTION: Final = 8 + +DEFAULT_SUBCATEGORY: Final = 0 + +GECKO_FORMAT_VERSION: Final = 32 +GECKO_PREPROCESSED_VERSION: Final = 57 + +RESOURCE_TYPE_LIBRARY: Final = 1 + +FRAME_ADDRESS_NONE: Final = -1 +FRAME_INLINE_DEPTH_ROOT: Final = 0 + +PROCESS_TYPE_MAIN: Final = 0 +STACKWALK_DISABLED: Final = 0 + +DEFAULT_SPILL_BUFFER_BYTES: Final[int] + +class SpillColumn: + path: str + buffer: bytearray + + def __init__(self, directory: StrPath, basename: StrPath, *, buffer_bytes: int | None = None) -> None: ... + # "value" accepts the same types as json.JSONEncoder.encode() + def append(self, value: Any) -> None: ... + def flush(self) -> None: ... + def iter_tokens(self) -> Generator[str]: ... + +class GeckoThreadSpill: + sample_count: int + marker_count: int + def __init__(self, directory: StrPath, tid: int) -> None: ... + def append_sample(self, stack_index: int, time_ms: float) -> None: ... + def append_marker( + self, name_idx: int, start_time: float, end_time: float, phase: int, category: int, data: dict[str, Any] + ) -> None: ... + def prepare_read(self) -> None: ... + +class GeckoCollector(Collector): + aggregating: ClassVar[bool] + + sample_interval_usec: int + skip_idle: bool + opcodes_enabled: bool + start_time: float + + global_strings: list[str] + global_string_map: dict[str, int] + + threads: dict[int, dict[str, Any]] + spill_dir: TemporaryDirectory[str] | None + exported: bool + + libs: list[Incomplete] + + sample_count: int + last_sample_time: float + interval: float + + has_gil_start: dict[Incomplete, Incomplete] + no_gil_start: dict[Incomplete, Incomplete] + on_cpu_start: dict[Incomplete, Incomplete] + off_cpu_start: dict[Incomplete, Incomplete] + python_code_start: dict[Incomplete, Incomplete] + native_code_start: dict[Incomplete, Incomplete] + gil_wait_start: dict[Incomplete, Incomplete] + exception_start: dict[Incomplete, Incomplete] + no_exception_start: dict[Incomplete, Incomplete] + + gc_start_per_thread: dict[int, float] + + initialized_threads: set[Incomplete] + + opcode_state: dict[int, tuple[Incomplete, int, int, str, str, float]] + + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False, opcodes: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... diff --git a/stdlib/profiling/sampling/heatmap_collector.pyi b/stdlib/profiling/sampling/heatmap_collector.pyi new file mode 100644 index 000000000000..bd523bc38245 --- /dev/null +++ b/stdlib/profiling/sampling/heatmap_collector.pyi @@ -0,0 +1,24 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Frame, _Timestamps + +class HeatmapCollector(Collector): + FILE_INDEX_FORMAT: str + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, output_path: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + def set_stats( + self, + sample_interval_usec: int, + duration_sec: float, + sample_rate: float, + error_rate: float | None = None, + missed_samples: float | None = None, + **kwargs: object, + ) -> None: ... diff --git a/stdlib/profiling/sampling/jsonl_collector.pyi b/stdlib/profiling/sampling/jsonl_collector.pyi new file mode 100644 index 000000000000..3bdc4b81c01d --- /dev/null +++ b/stdlib/profiling/sampling/jsonl_collector.pyi @@ -0,0 +1,15 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import _Frame, _Timestamps +from .stack_collector import StackTraceCollector + +class JsonlCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False, mode: int | None = None) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], _thread_id: int, weight: int = 1) -> None: ... diff --git a/stdlib/profiling/sampling/pstats_collector.pyi b/stdlib/profiling/sampling/pstats_collector.pyi new file mode 100644 index 000000000000..178d55a7af8e --- /dev/null +++ b/stdlib/profiling/sampling/pstats_collector.pyi @@ -0,0 +1,17 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Timestamps + +class PstatsCollector(Collector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def create_stats(self) -> None: ... + def print_stats( + self, sort: int = -1, limit: int | None = None, show_summary: bool = True, mode: int | None = None + ) -> None: ... diff --git a/stdlib/profiling/sampling/stack_collector.pyi b/stdlib/profiling/sampling/stack_collector.pyi new file mode 100644 index 000000000000..8ea1db6bc41c --- /dev/null +++ b/stdlib/profiling/sampling/stack_collector.pyi @@ -0,0 +1,87 @@ +from _typeshed import StrOrBytesPath, SupportsGet, SupportsKeysAndGet +from abc import ABCMeta +from collections import Counter +from collections.abc import Sequence +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Required + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Frame, _Location, _Timestamps + +# type check only +# TODO: move to binary_collector.pyi when that is added +_CaptureFeatureKeys: TypeAlias = Literal["all_threads", "native", "gc", "opcodes", "blocking"] + +class StackTraceCollector(Collector, metaclass=ABCMeta): + sample_interval_usec: int + skip_idle: bool + + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + +class CollapsedStackCollector(StackTraceCollector): + stack_counter: Counter[tuple[tuple[str, _Location, str], int]] + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + +@type_check_only +class _FlamegraphCollectorStats(TypedDict, total=False): + sample_interval_usec: Required[int] + duration_sec: float + sample_rate: float + error_rate: float | None + missed_samples: float | None + mode: int | None + +@type_check_only +class _ThreadStatusCounts(TypedDict): + has_gil: int + on_cpu: int + gil_requested: int + unknown: int + has_exception: int + total: int + +class FlamegraphCollector(StackTraceCollector): + stats: _FlamegraphCollectorStats + thread_status_counts: _ThreadStatusCounts + samples_with_gc_frames: int + per_thread_stats: dict[int, _ThreadStatusCounts] + + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def set_stats( + self, + sample_interval_usec: int, + duration_sec: float, + sample_rate: float, + error_rate: float | None = None, + missed_samples: float | None = None, + mode: int | None = None, + ) -> None: ... + def set_replay_stats(self, info: SupportsGet[str, float | None]) -> None: ... + def set_mode(self, mode: int | None) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + +class DiffFlamegraphCollector(FlamegraphCollector): + baseline_binary_path: StrOrBytesPath + mode: int | None + capture_config: SupportsKeysAndGet[_CaptureFeatureKeys, bool] | None + + def __init__( + self, + sample_interval_usec: int, + *, + baseline_binary_path: StrOrBytesPath, + skip_idle: bool = False, + mode: int | None = None, + capture_config: SupportsKeysAndGet[_CaptureFeatureKeys, bool] | None = None, + ) -> None: ... diff --git a/stdlib/profiling/sampling/string_table.pyi b/stdlib/profiling/sampling/string_table.pyi new file mode 100644 index 000000000000..cb71e82ec036 --- /dev/null +++ b/stdlib/profiling/sampling/string_table.pyi @@ -0,0 +1,5 @@ +class StringTable: + def intern(self, string: object) -> int: ... + def get_string(self, index: int) -> str: ... + def get_strings(self) -> list[str]: ... + def __len__(self) -> int: ... diff --git a/stdlib/profiling/tracing.pyi b/stdlib/profiling/tracing.pyi new file mode 100644 index 000000000000..af4ab508406a --- /dev/null +++ b/stdlib/profiling/tracing.pyi @@ -0,0 +1,9 @@ +from cProfile import Profile as Profile, run as run, runctx as runctx +from types import CodeType +from typing import TypeAlias + +__all__ = ("run", "runctx", "Profile") + +_Label: TypeAlias = tuple[str, int, str] + +def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/stdlib/pstats.pyi b/stdlib/pstats.pyi index e8256f9f98ab..8f244fde02c3 100644 --- a/stdlib/pstats.pyi +++ b/stdlib/pstats.pyi @@ -1,52 +1,96 @@ import sys from _typeshed import StrOrBytesPath +from collections.abc import Iterable from cProfile import Profile as _cProfile +from dataclasses import dataclass from profile import Profile -from typing import IO, Any, Iterable, Tuple, TypeVar, Union, overload +from typing import IO, Any, Literal, TypeAlias, overload +from typing_extensions import Self -_Selector = Union[str, float, int] -_T = TypeVar("_T", bound=Stats) - -if sys.version_info >= (3, 7): +if sys.version_info >= (3, 11): + from enum import StrEnum +else: from enum import Enum + +__all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] + +_Selector: TypeAlias = str | float | int + +if sys.version_info >= (3, 11): + class SortKey(StrEnum): + CALLS = "calls" + CUMULATIVE = "cumulative" + FILENAME = "filename" + LINE = "line" + NAME = "name" + NFL = "nfl" + PCALLS = "pcalls" + STDNAME = "stdname" + TIME = "time" + +else: class SortKey(str, Enum): - CALLS: str - CUMULATIVE: str - FILENAME: str - LINE: str - NAME: str - NFL: str - PCALLS: str - STDNAME: str - TIME: str + CALLS = "calls" + CUMULATIVE = "cumulative" + FILENAME = "filename" + LINE = "line" + NAME = "name" + NFL = "nfl" + PCALLS = "pcalls" + STDNAME = "stdname" + TIME = "time" + +@dataclass(unsafe_hash=True) +class FunctionProfile: + ncalls: str + tottime: float + percall_tottime: float + cumtime: float + percall_cumtime: float + file_name: str + line_number: int + +@dataclass(unsafe_hash=True) +class StatsProfile: + total_tt: float + func_profiles: dict[str, FunctionProfile] + +_SortArgDict: TypeAlias = dict[str, tuple[tuple[tuple[int, int], ...], str]] class Stats: - sort_arg_dict_default: dict[str, tuple[Any, str]] + sort_arg_dict_default: _SortArgDict def __init__( - self: _T, - __arg: None | str | Profile | _cProfile = ..., - *args: None | str | Profile | _cProfile | _T, - stream: IO[Any] | None = ..., + self, + arg: str | Profile | _cProfile | None = None, + /, + *args: str | Profile | _cProfile | Self | None, + stream: IO[Any] | None = None, ) -> None: ... - def init(self, arg: None | str | Profile | _cProfile) -> None: ... - def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ... + def init(self, arg: str | Profile | _cProfile | None) -> None: ... + def load_stats(self, arg: str | Profile | _cProfile | None) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Profile | _cProfile | _T) -> _T: ... + def add(self, *arg_list: str | Profile | _cProfile | Self | None) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: ... - def get_sort_arg_defs(self) -> dict[str, tuple[Tuple[tuple[int, int], ...], str]]: ... + def get_sort_arg_defs(self) -> _SortArgDict: ... + @overload - def sort_stats(self: _T, field: int) -> _T: ... + def sort_stats(self, field: Literal[-1, 0, 1, 2]) -> Self: ... @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... + def sort_stats(self, *field: str) -> Self: ... + + def reverse_order(self) -> Self: ... + def strip_dirs(self) -> Self: ... def calc_callees(self) -> None: ... def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... + def get_stats_profile(self) -> StatsProfile: ... def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ... - def print_stats(self: _T, *amount: _Selector) -> _T: ... - def print_callees(self: _T, *amount: _Selector) -> _T: ... - def print_callers(self: _T, *amount: _Selector) -> _T: ... + def print_stats(self, *amount: _Selector) -> Self: ... + def print_callees(self, *amount: _Selector) -> Self: ... + def print_callers(self, *amount: _Selector) -> Self: ... def print_call_heading(self, name_size: int, column_title: str) -> None: ... - def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = ...) -> None: ... + if sys.version_info >= (3, 15): + def print_call_subheading(self, name_size: int) -> None: ... + + def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = "->") -> None: ... def print_title(self) -> None: ... def print_line(self, func: str) -> None: ... diff --git a/stdlib/pty.pyi b/stdlib/pty.pyi index f943cebdb157..2bb48d782de6 100644 --- a/stdlib/pty.pyi +++ b/stdlib/pty.pyi @@ -1,15 +1,24 @@ -from typing import Callable, Iterable +import sys +from collections.abc import Callable, Iterable +from typing import Final, TypeAlias +from typing_extensions import deprecated -_Reader = Callable[[int], bytes] +if sys.platform != "win32": + __all__ = ["openpty", "fork", "spawn"] + _Reader: TypeAlias = Callable[[int], bytes] -STDIN_FILENO: int -STDOUT_FILENO: int -STDERR_FILENO: int + STDIN_FILENO: Final = 0 + STDOUT_FILENO: Final = 1 + STDERR_FILENO: Final = 2 -CHILD: int + CHILD: Final = 0 + def openpty() -> tuple[int, int]: ... -def openpty() -> tuple[int, int]: ... -def master_open() -> tuple[int, str]: ... -def slave_open(tty_name: str) -> int: ... -def fork() -> tuple[int, int]: ... -def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... + if sys.version_info < (3, 14): + @deprecated("Deprecated; removed in Python 3.14. Use `openpty()` instead.") + def master_open() -> tuple[int, str]: ... + @deprecated("Deprecated; removed in Python 3.14. Use `openpty()` instead.") + def slave_open(tty_name: str) -> int: ... + + def fork() -> tuple[int, int]: ... + def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... diff --git a/stdlib/pwd.pyi b/stdlib/pwd.pyi index a16175879f67..6a7e24f78125 100644 --- a/stdlib/pwd.pyi +++ b/stdlib/pwd.pyi @@ -1,24 +1,27 @@ +import sys from _typeshed import structseq -from typing import Any, Tuple -from typing_extensions import final +from typing import Any, Final, final -@final -class struct_passwd(structseq[Any], Tuple[str, str, int, int, str, str, str]): - @property - def pw_name(self) -> str: ... - @property - def pw_passwd(self) -> str: ... - @property - def pw_uid(self) -> int: ... - @property - def pw_gid(self) -> int: ... - @property - def pw_gecos(self) -> str: ... - @property - def pw_dir(self) -> str: ... - @property - def pw_shell(self) -> str: ... +if sys.platform != "win32": + @final + class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): + __match_args__: Final = ("pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell") -def getpwall() -> list[struct_passwd]: ... -def getpwuid(__uid: int) -> struct_passwd: ... -def getpwnam(__name: str) -> struct_passwd: ... + @property + def pw_name(self) -> str: ... + @property + def pw_passwd(self) -> str: ... + @property + def pw_uid(self) -> int: ... + @property + def pw_gid(self) -> int: ... + @property + def pw_gecos(self) -> str: ... + @property + def pw_dir(self) -> str: ... + @property + def pw_shell(self) -> str: ... + + def getpwall() -> list[struct_passwd]: ... + def getpwuid(uid: int, /) -> struct_passwd: ... + def getpwnam(name: str, /) -> struct_passwd: ... diff --git a/stdlib/py_compile.pyi b/stdlib/py_compile.pyi index 1df818509d0e..e0ee67c5e93f 100644 --- a/stdlib/py_compile.pyi +++ b/stdlib/py_compile.pyi @@ -1,45 +1,28 @@ -import sys -from typing import AnyStr, Type +import enum +from typing import AnyStr + +__all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"] class PyCompileError(Exception): exc_type_name: str exc_value: BaseException file: str msg: str - def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... - -if sys.version_info >= (3, 7): - import enum - class PycInvalidationMode(enum.Enum): - TIMESTAMP: int - CHECKED_HASH: int - UNCHECKED_HASH: int - def _get_default_invalidation_mode() -> PycInvalidationMode: ... - -if sys.version_info >= (3, 8): - def compile( - file: AnyStr, - cfile: AnyStr | None = ..., - dfile: AnyStr | None = ..., - doraise: bool = ..., - optimize: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - quiet: int = ..., - ) -> AnyStr | None: ... - -elif sys.version_info >= (3, 7): - def compile( - file: AnyStr, - cfile: AnyStr | None = ..., - dfile: AnyStr | None = ..., - doraise: bool = ..., - optimize: int = ..., - invalidation_mode: PycInvalidationMode | None = ..., - ) -> AnyStr | None: ... + def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = "") -> None: ... -else: - def compile( - file: AnyStr, cfile: AnyStr | None = ..., dfile: AnyStr | None = ..., doraise: bool = ..., optimize: int = ... - ) -> AnyStr | None: ... +class PycInvalidationMode(enum.Enum): + TIMESTAMP = 1 + CHECKED_HASH = 2 + UNCHECKED_HASH = 3 -def main(args: list[str] | None = ...) -> int: ... +def _get_default_invalidation_mode() -> PycInvalidationMode: ... +def compile( + file: AnyStr, + cfile: AnyStr | None = None, + dfile: AnyStr | None = None, + doraise: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, + quiet: int = 0, +) -> AnyStr | None: ... +def main() -> None: ... diff --git a/stdlib/pyclbr.pyi b/stdlib/pyclbr.pyi index 10d106b4f511..541f962d33e1 100644 --- a/stdlib/pyclbr.pyi +++ b/stdlib/pyclbr.pyi @@ -1,31 +1,57 @@ -import sys -from typing import Sequence +from collections.abc import Mapping, Sequence -class Class: +__all__ = ["readmodule", "readmodule_ex", "Class", "Function"] + +class _Object: module: str name: str - super: list[Class | str] | None - methods: dict[str, int] file: int lineno: int + end_lineno: int | None + parent: _Object | None - if sys.version_info >= (3, 7): - def __init__( - self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int, parent: Class | None = ... - ) -> None: ... - else: - def __init__(self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int) -> None: ... + # This is a dict at runtime, but we're typing it as Mapping to + # avoid variance issues in the subclasses + children: Mapping[str, _Object] -class Function: - module: str - name: str - file: int - lineno: int + def __init__( + self, module: str, name: str, file: str, lineno: int, end_lineno: int | None, parent: _Object | None + ) -> None: ... + +class Function(_Object): + is_async: bool + parent: Function | Class | None + children: dict[str, Class | Function] + + def __init__( + self, + module: str, + name: str, + file: str, + lineno: int, + parent: Function | Class | None = None, + is_async: bool = False, + *, + end_lineno: int | None = None, + ) -> None: ... + +class Class(_Object): + super: list[Class | str] | None + methods: dict[str, int] + parent: Class | None + children: dict[str, Class | Function] - if sys.version_info >= (3, 7): - def __init__(self, module: str, name: str, file: str, lineno: int, parent: Function | None = ...) -> None: ... - else: - def __init__(self, module: str, name: str, file: str, lineno: int) -> None: ... + def __init__( + self, + module: str, + name: str, + super_: list[Class | str] | None, + file: str, + lineno: int, + parent: Class | None = None, + *, + end_lineno: int | None = None, + ) -> None: ... -def readmodule(module: str, path: Sequence[str] | None = ...) -> dict[str, Class]: ... -def readmodule_ex(module: str, path: Sequence[str] | None = ...) -> dict[str, Class | Function | list[str]]: ... +def readmodule(module: str, path: Sequence[str] | None = None) -> dict[str, Class]: ... +def readmodule_ex(module: str, path: Sequence[str] | None = None) -> dict[str, Class | Function | list[str]]: ... diff --git a/stdlib/pydoc.pyi b/stdlib/pydoc.pyi index b60ef8f9bcb3..dd9a365dff0b 100644 --- a/stdlib/pydoc.pyi +++ b/stdlib/pydoc.pyi @@ -1,15 +1,25 @@ -from _typeshed import SupportsWrite +import sys +from _typeshed import OptExcInfo, StrPath, SupportsWrite, Unused +from abc import abstractmethod +from builtins import list as _list # "list" conflicts with method name +from collections.abc import Callable, Container, Mapping, MutableMapping from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional, Tuple, Type +from typing import IO, Any, AnyStr, Final, Protocol, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated -# the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +__all__ = ["help"] -__author__: str -__date__: str -__version__: str -__credits__: str +_T = TypeVar("_T") + +__author__: Final[str] +__date__: Final[str] +__version__: Final[str] +__credits__: Final[str] + +@type_check_only +class _Pager(Protocol): + def __call__(self, text: str, title: str = "") -> None: ... def pathdirs() -> list[str]: ... def getdoc(object: object) -> str: ... @@ -20,40 +30,55 @@ def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ... def cram(text: str, maxlen: int) -> str: ... def stripid(text: str) -> str: ... def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... -def visiblename(name: str, all: Container[str] | None = ..., obj: object | None = ...) -> bool: ... +def visiblename(name: str, all: Container[str] | None = None, obj: object = None) -> bool: ... def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ... -def ispackage(path: str) -> bool: ... +@deprecated("Deprecated.") +def ispackage(path: StrPath) -> bool: ... # undocumented def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... -def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = ...) -> str | None: ... +def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = {}) -> str | None: ... class ErrorDuringImport(Exception): filename: str - exc: Type[BaseException] | None + exc: type[BaseException] | None value: BaseException | None tb: TracebackType | None - def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... + if sys.version_info >= (3, 12): + @overload + def __init__(self, filename: str, exc_info: BaseException) -> None: ... + @overload + @deprecated("A tuple value for `exc_info` parameter is deprecated since Python 3.12. Use an exception instance.") + def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ... + else: + def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ... def importfile(path: str) -> ModuleType: ... -def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = ...) -> ModuleType: ... +def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = {}) -> ModuleType | None: ... class Doc: PYTHONDOCS: str - def document(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def fail(self, object: object, name: str | None = ..., *args: Any) -> NoReturn: ... - def docmodule(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docclass(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docroutine(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docother(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docproperty(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def docdata(self, object: object, name: str | None = ..., *args: Any) -> str: ... - def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... + if sys.version_info >= (3, 15): + STDLIB_DIR: str + + def document(self, object: object, name: str | None = None, *args: Any) -> str: ... + def fail(self, object: object, name: str | None = None, *args: Any) -> Never: ... + @abstractmethod + def docmodule(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docclass(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docroutine(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docother(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docproperty(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docdata(self, object: object, name: str | None = None, *args: Any) -> str: ... + if sys.version_info >= (3, 15): + def getdocloc(self, object: object, basedir: str | None = None) -> str | None: ... + else: + def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... class HTMLRepr(Repr): - maxlist: int - maxtuple: int - maxdict: int - maxstring: int - maxother: int def __init__(self) -> None: ... def escape(self, text: str) -> str: ... def repr(self, object: object) -> str: ... @@ -64,24 +89,40 @@ class HTMLRepr(Repr): def repr_unicode(self, x: AnyStr, level: complex) -> str: ... class HTMLDoc(Doc): - repr: Callable[[object], str] - escape: Callable[[str], str] + _repr_instance: HTMLRepr + repr = _repr_instance.repr # pyrefly: ignore [unknown-name] + escape = _repr_instance.escape # pyrefly: ignore [unknown-name] def page(self, title: str, contents: str) -> str: ... - def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... - def section( - self, - title: str, - fgcol: str, - bgcol: str, - contents: str, - width: int = ..., - prelude: str = ..., - marginalia: str | None = ..., - gap: str = ..., - ) -> str: ... + if sys.version_info >= (3, 11): + def heading(self, title: str, extras: str = "") -> str: ... + def section( + self, + title: str, + cls: str, + contents: str, + width: int = 6, + prelude: str = "", + marginalia: str | None = None, + gap: str = " ", + ) -> str: ... + def multicolumn(self, list: list[_T], format: Callable[[_T], str]) -> str: ... + else: + def heading(self, title: str, fgcol: str, bgcol: str, extras: str = "") -> str: ... + def section( + self, + title: str, + fgcol: str, + bgcol: str, + contents: str, + width: int = 6, + prelude: str = "", + marginalia: str | None = None, + gap: str = " ", + ) -> str: ... + def multicolumn(self, list: list[_T], format: Callable[[_T], str], cols: int = 4) -> str: ... + def bigsection(self, title: str, *args: Any) -> str: ... def preformat(self, text: str) -> str: ... - def multicolumn(self, list: list[Any], format: Callable[[Any], str], cols: int = ...) -> str: ... def grey(self, text: str) -> str: ... def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... def classlink(self, object: object, modname: str) -> str: ... @@ -90,47 +131,64 @@ class HTMLDoc(Doc): def markup( self, text: str, - escape: Callable[[str], str] | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - methods: Mapping[str, str] = ..., + escape: Callable[[str], str] | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, ) -> str: ... def formattree( - self, tree: list[tuple[type, Tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None ) -> str: ... - def docmodule(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... + def docmodule(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: ... def docclass( self, object: object, - name: str | None = ..., - mod: str | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - *ignored: Any, + name: str | None = None, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + *ignored: Unused, ) -> str: ... def formatvalue(self, object: object) -> str: ... - def docroutine( # type: ignore[override] - self, - object: object, - name: str | None = ..., - mod: str | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - methods: Mapping[str, str] = ..., - cl: type | None = ..., - ) -> str: ... - def docproperty(self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] - def docother(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... - def docdata(self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] - def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = ...) -> str: ... + def docother(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: ... + if sys.version_info >= (3, 11): + def docroutine( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + cl: type | None = None, + homecls: type | None = None, + ) -> str: ... + def docproperty( + self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + def docdata( + self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + else: + def docroutine( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + cl: type | None = None, + ) -> str: ... + def docproperty(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docdata(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + if sys.version_info >= (3, 11): + def parentlink(self, object: type | ModuleType, modname: str) -> str: ... + + def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = None) -> str: ... def filelink(self, url: str, path: str) -> str: ... class TextRepr(Repr): - maxlist: int - maxtuple: int - maxdict: int - maxstring: int - maxother: int def __init__(self) -> None: ... def repr1(self, x: object, level: complex) -> str: ... def repr_string(self, x: str, level: complex) -> str: ... @@ -138,93 +196,153 @@ class TextRepr(Repr): def repr_instance(self, x: object, level: complex) -> str: ... class TextDoc(Doc): - repr: Callable[[object], str] + _repr_instance: TextRepr + repr = _repr_instance.repr # pyrefly: ignore [unknown-name] def bold(self, text: str) -> str: ... - def indent(self, text: str, prefix: str = ...) -> str: ... + def indent(self, text: str, prefix: str = " ") -> str: ... def section(self, title: str, contents: str) -> str: ... def formattree( - self, tree: list[tuple[type, Tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ..., prefix: str = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None, prefix: str = "" ) -> str: ... - def docmodule(self, object: object, name: str | None = ..., mod: Any | None = ...) -> str: ... # type: ignore[override] - def docclass(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... + def docclass(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: ... def formatvalue(self, object: object) -> str: ... - def docroutine(self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] - def docproperty(self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] - def docdata(self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] - def docother( # type: ignore[override] - self, - object: object, - name: str | None = ..., - mod: str | None = ..., - parent: str | None = ..., - maxlen: int | None = ..., - doc: Any | None = ..., - ) -> str: ... + if sys.version_info >= (3, 11): + def docroutine( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + cl: Any | None = None, + homecls: Any | None = None, + ) -> str: ... + def docmodule(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: ... + def docproperty( + self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + def docdata( + self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + def docother( + self, + object: object, + name: str | None = None, + mod: str | None = None, + parent: str | None = None, + *ignored: Unused, + maxlen: int | None = None, + doc: Any | None = None, + ) -> str: ... + else: + def docroutine(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docmodule(self, object: object, name: str | None = None, mod: Any | None = None) -> str: ... # type: ignore[override] + def docproperty(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docdata(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docother( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + parent: str | None = None, + maxlen: int | None = None, + doc: Any | None = None, + ) -> str: ... + +if sys.version_info >= (3, 13): + def pager(text: str, title: str = "") -> None: ... + +else: + def pager(text: str) -> None: ... -def pager(text: str) -> None: ... -def getpager() -> Callable[[str], None]: ... def plain(text: str) -> str: ... -def pipepager(text: str, cmd: str) -> None: ... -def tempfilepager(text: str, cmd: str) -> None: ... -def ttypager(text: str) -> None: ... -def plainpager(text: str) -> None: ... def describe(thing: Any) -> str: ... def locate(path: str, forceload: bool = ...) -> object: ... +if sys.version_info >= (3, 13): + def get_pager() -> _Pager: ... + def pipe_pager(text: str, cmd: str, title: str = "") -> None: ... + def tempfile_pager(text: str, cmd: str, title: str = "") -> None: ... + def tty_pager(text: str, title: str = "") -> None: ... + def plain_pager(text: str, title: str = "") -> None: ... + + # For backwards compatibility. + getpager = get_pager + pipepager = pipe_pager + tempfilepager = tempfile_pager + ttypager = tty_pager + plainpager = plain_pager +else: + def getpager() -> Callable[[str], None]: ... + def pipepager(text: str, cmd: str) -> None: ... + def tempfilepager(text: str, cmd: str) -> None: ... + def ttypager(text: str) -> None: ... + def plainpager(text: str) -> None: ... + text: TextDoc html: HTMLDoc -class _OldStyleClass: ... - def resolve(thing: str | object, forceload: bool = ...) -> tuple[object, str] | None: ... -def render_doc(thing: str | object, title: str = ..., forceload: bool = ..., renderer: Doc | None = ...) -> str: ... -def doc(thing: str | object, title: str = ..., forceload: bool = ..., output: SupportsWrite[str] | None = ...) -> None: ... -def writedoc(thing: str | object, forceload: bool = ...) -> None: ... -def writedocs(dir: str, pkgpath: str = ..., done: Any | None = ...) -> None: ... +def render_doc( + thing: str | object, title: str = "Python Library Documentation: %s", forceload: bool = ..., renderer: Doc | None = None +) -> str: ... -_list = list # "list" conflicts with method name +if sys.version_info >= (3, 11): + def doc( + thing: str | object, + title: str = "Python Library Documentation: %s", + forceload: bool = ..., + output: SupportsWrite[str] | None = None, + is_cli: bool = False, + ) -> None: ... + +else: + def doc( + thing: str | object, + title: str = "Python Library Documentation: %s", + forceload: bool = ..., + output: SupportsWrite[str] | None = None, + ) -> None: ... + +def writedoc(thing: str | object, forceload: bool = ...) -> None: ... +def writedocs(dir: str, pkgpath: str = "", done: Any | None = None) -> None: ... class Helper: keywords: dict[str, str | tuple[str, str]] symbols: dict[str, str] - topics: dict[str, str | Tuple[str, ...]] - def __init__(self, input: IO[str] | None = ..., output: IO[str] | None = ...) -> None: ... - input: IO[str] - output: IO[str] + topics: dict[str, str | tuple[str, ...]] + def __init__(self, input: IO[str] | None = None, output: IO[str] | None = None) -> None: ... + @property + def input(self) -> IO[str]: ... + @property + def output(self) -> IO[str]: ... def __call__(self, request: str | Helper | object = ...) -> None: ... def interact(self) -> None: ... def getline(self, prompt: str) -> str: ... - def help(self, request: Any) -> None: ... + if sys.version_info >= (3, 11): + def help(self, request: Any, is_cli: bool = False) -> None: ... + else: + def help(self, request: Any) -> None: ... + def intro(self) -> None: ... - def list(self, items: _list[str], columns: int = ..., width: int = ...) -> None: ... + def list(self, items: _list[str], columns: int = 4, width: int = 80) -> None: ... def listkeywords(self) -> None: ... def listsymbols(self) -> None: ... def listtopics(self) -> None: ... - def showtopic(self, topic: str, more_xrefs: str = ...) -> None: ... + def showtopic(self, topic: str, more_xrefs: str = "") -> None: ... def showsymbol(self, symbol: str) -> None: ... - def listmodules(self, key: str = ...) -> None: ... + def listmodules(self, key: str = "") -> None: ... help: Helper -# See Python issue #11182: "remove the unused and undocumented pydoc.Scanner class" -# class Scanner: -# roots = ... # type: Any -# state = ... # type: Any -# children = ... # type: Any -# descendp = ... # type: Any -# def __init__(self, roots, children, descendp) -> None: ... -# def next(self): ... - class ModuleScanner: quit: bool def run( self, - callback: Callable[[str | None, str, str], None], - key: Any | None = ..., - completer: Callable[[], None] | None = ..., - onerror: Callable[[str], None] | None = ..., + callback: Callable[[str | None, str, str], object], + key: str | None = None, + completer: Callable[[], object] | None = None, + onerror: Callable[[str], object] | None = None, ) -> None: ... def apropos(key: str) -> None: ... -def ispath(x: Any) -> bool: ... +def ispath(x: object) -> TypeGuard[str]: ... def cli() -> None: ... diff --git a/stdlib/pydoc_data/module_docs.pyi b/stdlib/pydoc_data/module_docs.pyi new file mode 100644 index 000000000000..e3f716c0b292 --- /dev/null +++ b/stdlib/pydoc_data/module_docs.pyi @@ -0,0 +1,3 @@ +from typing import Final + +module_docs: Final[dict[str, str]] diff --git a/stdlib/pydoc_data/topics.pyi b/stdlib/pydoc_data/topics.pyi index 091d34300106..ce907a41c005 100644 --- a/stdlib/pydoc_data/topics.pyi +++ b/stdlib/pydoc_data/topics.pyi @@ -1 +1,3 @@ -topics: dict[str, str] +from typing import Final + +topics: Final[dict[str, str]] diff --git a/stdlib/pyexpat/__init__.pyi b/stdlib/pyexpat/__init__.pyi index 6a3d6cd56791..de2471f92acd 100644 --- a/stdlib/pyexpat/__init__.pyi +++ b/stdlib/pyexpat/__init__.pyi @@ -1,37 +1,42 @@ -import pyexpat.errors as errors -import pyexpat.model as model -from _typeshed import SupportsRead -from typing import Any, Callable, Optional, Tuple -from typing_extensions import final +from _typeshed import ReadableBuffer, SupportsRead +from collections.abc import Callable +from pyexpat import errors as errors, model as model +from typing import Any, Final, TypeAlias, final +from typing_extensions import CapsuleType +from xml.parsers.expat import ExpatError as ExpatError -EXPAT_VERSION: str # undocumented +EXPAT_VERSION: Final[str] # undocumented version_info: tuple[int, int, int] # undocumented native_encoding: str # undocumented features: list[tuple[str, int]] # undocumented -class ExpatError(Exception): - code: int - lineno: int - offset: int - error = ExpatError +XML_PARAM_ENTITY_PARSING_NEVER: Final = 0 +XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: Final = 1 +XML_PARAM_ENTITY_PARSING_ALWAYS: Final = 2 -XML_PARAM_ENTITY_PARSING_NEVER: int -XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int -XML_PARAM_ENTITY_PARSING_ALWAYS: int - -_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] +_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] @final -class XMLParserType(object): - def Parse(self, __data: str | bytes, __isfinal: bool = ...) -> int: ... - def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... - def SetBase(self, __base: str) -> None: ... +class XMLParserType: + def Parse(self, data: str | ReadableBuffer, isfinal: bool = False, /) -> int: ... + def ParseFile(self, file: SupportsRead[bytes], /) -> int: ... + def SetBase(self, base: str, /) -> None: ... def GetBase(self) -> str | None: ... def GetInputContext(self) -> bytes | None: ... - def ExternalEntityParserCreate(self, __context: str | None, __encoding: str = ...) -> XMLParserType: ... - def SetParamEntityParsing(self, __flag: int) -> int: ... - def UseForeignDTD(self, __flag: bool = ...) -> None: ... + def ExternalEntityParserCreate(self, context: str | None, encoding: str = ..., /) -> XMLParserType: ... + def SetParamEntityParsing(self, flag: int, /) -> int: ... + def UseForeignDTD(self, flag: bool = True, /) -> None: ... + def GetReparseDeferralEnabled(self) -> bool: ... + def SetReparseDeferralEnabled(self, enabled: bool, /) -> None: ... + # Added in Python 3.10.20, 3.11.15, 3.12.3, 3.13.10, 3.14.1 + def SetAllocTrackerActivationThreshold(self, threshold: int, /) -> None: ... + def SetAllocTrackerMaximumAmplification(self, max_factor: float, /) -> None: ... + # Added in Python 3.10.19, 3.11.14, 3.12.12, 3.13.4, 3.14.6 + def SetBillionLaughsAttackProtectionActivationThreshold(self, threshold: int, /) -> None: ... + def SetBillionLaughsAttackProtectionMaximumAmplification(self, max_factor: float, /) -> None: ... + @property + def intern(self) -> dict[str, str]: ... buffer_size: int buffer_text: bool buffer_used: int @@ -50,9 +55,12 @@ class XMLParserType(object): EndDoctypeDeclHandler: Callable[[], Any] | None ElementDeclHandler: Callable[[str, _Model], Any] | None AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None - StartElementHandler: Callable[[str, dict[str, str]], Any] | Callable[[str, list[str]], Any] | Callable[ - [str, dict[str, str], list[str]], Any - ] | None + StartElementHandler: ( + Callable[[str, dict[str, str]], Any] + | Callable[[str, list[str]], Any] + | Callable[[str, dict[str, str], list[str]], Any] + | None + ) EndElementHandler: Callable[[str], Any] | None ProcessingInstructionHandler: Callable[[str, str], Any] | None CharacterDataHandler: Callable[[str], Any] | None @@ -68,10 +76,13 @@ class XMLParserType(object): DefaultHandlerExpand: Callable[[str], Any] | None NotStandaloneHandler: Callable[[], int] | None ExternalEntityRefHandler: Callable[[str, str | None, str | None, str | None], int] | None + SkippedEntityHandler: Callable[[str, bool], Any] | None -def ErrorString(__code: int) -> str: ... +def ErrorString(code: int, /) -> str: ... # intern is undocumented def ParserCreate( - encoding: str | None = ..., namespace_separator: str | None = ..., intern: dict[str, Any] | None = ... + encoding: str | None = None, namespace_separator: str | None = None, intern: dict[str, Any] | None = None ) -> XMLParserType: ... + +expat_CAPI: CapsuleType diff --git a/stdlib/pyexpat/errors.pyi b/stdlib/pyexpat/errors.pyi index 61826e12da00..493ae0345604 100644 --- a/stdlib/pyexpat/errors.pyi +++ b/stdlib/pyexpat/errors.pyi @@ -1,40 +1,53 @@ +import sys +from typing import Final +from typing_extensions import LiteralString + codes: dict[str, int] messages: dict[int, str] -XML_ERROR_ABORTED: str -XML_ERROR_ASYNC_ENTITY: str -XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: str -XML_ERROR_BAD_CHAR_REF: str -XML_ERROR_BINARY_ENTITY_REF: str -XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: str -XML_ERROR_DUPLICATE_ATTRIBUTE: str -XML_ERROR_ENTITY_DECLARED_IN_PE: str -XML_ERROR_EXTERNAL_ENTITY_HANDLING: str -XML_ERROR_FEATURE_REQUIRES_XML_DTD: str -XML_ERROR_FINISHED: str -XML_ERROR_INCOMPLETE_PE: str -XML_ERROR_INCORRECT_ENCODING: str -XML_ERROR_INVALID_TOKEN: str -XML_ERROR_JUNK_AFTER_DOC_ELEMENT: str -XML_ERROR_MISPLACED_XML_PI: str -XML_ERROR_NOT_STANDALONE: str -XML_ERROR_NOT_SUSPENDED: str -XML_ERROR_NO_ELEMENTS: str -XML_ERROR_NO_MEMORY: str -XML_ERROR_PARAM_ENTITY_REF: str -XML_ERROR_PARTIAL_CHAR: str -XML_ERROR_PUBLICID: str -XML_ERROR_RECURSIVE_ENTITY_REF: str -XML_ERROR_SUSPENDED: str -XML_ERROR_SUSPEND_PE: str -XML_ERROR_SYNTAX: str -XML_ERROR_TAG_MISMATCH: str -XML_ERROR_TEXT_DECL: str -XML_ERROR_UNBOUND_PREFIX: str -XML_ERROR_UNCLOSED_CDATA_SECTION: str -XML_ERROR_UNCLOSED_TOKEN: str -XML_ERROR_UNDECLARING_PREFIX: str -XML_ERROR_UNDEFINED_ENTITY: str -XML_ERROR_UNEXPECTED_STATE: str -XML_ERROR_UNKNOWN_ENCODING: str -XML_ERROR_XML_DECL: str +XML_ERROR_ABORTED: Final[LiteralString] +XML_ERROR_ASYNC_ENTITY: Final[LiteralString] +XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: Final[LiteralString] +XML_ERROR_BAD_CHAR_REF: Final[LiteralString] +XML_ERROR_BINARY_ENTITY_REF: Final[LiteralString] +XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: Final[LiteralString] +XML_ERROR_DUPLICATE_ATTRIBUTE: Final[LiteralString] +XML_ERROR_ENTITY_DECLARED_IN_PE: Final[LiteralString] +XML_ERROR_EXTERNAL_ENTITY_HANDLING: Final[LiteralString] +XML_ERROR_FEATURE_REQUIRES_XML_DTD: Final[LiteralString] +XML_ERROR_FINISHED: Final[LiteralString] +XML_ERROR_INCOMPLETE_PE: Final[LiteralString] +XML_ERROR_INCORRECT_ENCODING: Final[LiteralString] +XML_ERROR_INVALID_TOKEN: Final[LiteralString] +XML_ERROR_JUNK_AFTER_DOC_ELEMENT: Final[LiteralString] +XML_ERROR_MISPLACED_XML_PI: Final[LiteralString] +XML_ERROR_NOT_STANDALONE: Final[LiteralString] +XML_ERROR_NOT_SUSPENDED: Final[LiteralString] +XML_ERROR_NO_ELEMENTS: Final[LiteralString] +XML_ERROR_NO_MEMORY: Final[LiteralString] +XML_ERROR_PARAM_ENTITY_REF: Final[LiteralString] +XML_ERROR_PARTIAL_CHAR: Final[LiteralString] +XML_ERROR_PUBLICID: Final[LiteralString] +XML_ERROR_RECURSIVE_ENTITY_REF: Final[LiteralString] +XML_ERROR_SUSPENDED: Final[LiteralString] +XML_ERROR_SUSPEND_PE: Final[LiteralString] +XML_ERROR_SYNTAX: Final[LiteralString] +XML_ERROR_TAG_MISMATCH: Final[LiteralString] +XML_ERROR_TEXT_DECL: Final[LiteralString] +XML_ERROR_UNBOUND_PREFIX: Final[LiteralString] +XML_ERROR_UNCLOSED_CDATA_SECTION: Final[LiteralString] +XML_ERROR_UNCLOSED_TOKEN: Final[LiteralString] +XML_ERROR_UNDECLARING_PREFIX: Final[LiteralString] +XML_ERROR_UNDEFINED_ENTITY: Final[LiteralString] +XML_ERROR_UNEXPECTED_STATE: Final[LiteralString] +XML_ERROR_UNKNOWN_ENCODING: Final[LiteralString] +XML_ERROR_XML_DECL: Final[LiteralString] +if sys.version_info >= (3, 11): + XML_ERROR_RESERVED_PREFIX_XML: Final[LiteralString] + XML_ERROR_RESERVED_PREFIX_XMLNS: Final[LiteralString] + XML_ERROR_RESERVED_NAMESPACE_URI: Final[LiteralString] + XML_ERROR_INVALID_ARGUMENT: Final[LiteralString] + XML_ERROR_NO_BUFFER: Final[LiteralString] + XML_ERROR_AMPLIFICATION_LIMIT_BREACH: Final[LiteralString] +if sys.version_info >= (3, 14): + XML_ERROR_NOT_STARTED: Final[LiteralString] diff --git a/stdlib/pyexpat/model.pyi b/stdlib/pyexpat/model.pyi index f357cf6511a2..bac8f3692ce5 100644 --- a/stdlib/pyexpat/model.pyi +++ b/stdlib/pyexpat/model.pyi @@ -1,11 +1,13 @@ -XML_CTYPE_ANY: int -XML_CTYPE_CHOICE: int -XML_CTYPE_EMPTY: int -XML_CTYPE_MIXED: int -XML_CTYPE_NAME: int -XML_CTYPE_SEQ: int +from typing import Final -XML_CQUANT_NONE: int -XML_CQUANT_OPT: int -XML_CQUANT_PLUS: int -XML_CQUANT_REP: int +XML_CTYPE_ANY: Final = 2 +XML_CTYPE_EMPTY: Final = 1 +XML_CTYPE_MIXED: Final = 3 +XML_CTYPE_NAME: Final = 4 +XML_CTYPE_CHOICE: Final = 5 +XML_CTYPE_SEQ: Final = 6 + +XML_CQUANT_NONE: Final = 0 +XML_CQUANT_OPT: Final = 1 +XML_CQUANT_REP: Final = 2 +XML_CQUANT_PLUS: Final = 3 diff --git a/stdlib/queue.pyi b/stdlib/queue.pyi index 9671155b7eb6..65e2ac1559ad 100644 --- a/stdlib/queue.pyi +++ b/stdlib/queue.pyi @@ -1,15 +1,21 @@ import sys +from _queue import Empty as Empty, SimpleQueue as SimpleQueue +from _typeshed import SupportsRichComparisonT from threading import Condition, Lock +from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = ["Empty", "Full", "Queue", "PriorityQueue", "LifoQueue", "SimpleQueue"] +if sys.version_info >= (3, 13): + __all__ += ["ShutDown"] _T = TypeVar("_T") -class Empty(Exception): ... class Full(Exception): ... +if sys.version_info >= (3, 13): + class ShutDown(Exception): ... + class Queue(Generic[_T]): maxsize: int @@ -18,35 +24,32 @@ class Queue(Generic[_T]): not_full: Condition # undocumented all_tasks_done: Condition # undocumented unfinished_tasks: int # undocumented + if sys.version_info >= (3, 13): + is_shutdown: bool # undocumented + # Despite the fact that `queue` has `deque` type, + # we treat it as `Any` to allow different implementations in subtypes. queue: Any # undocumented - def __init__(self, maxsize: int = ...) -> None: ... + def __init__(self, maxsize: int = 0) -> None: ... def _init(self, maxsize: int) -> None: ... def empty(self) -> bool: ... def full(self) -> bool: ... - def get(self, block: bool = ..., timeout: float | None = ...) -> _T: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... def get_nowait(self) -> _T: ... + if sys.version_info >= (3, 13): + def shutdown(self, immediate: bool = False) -> None: ... + def _get(self) -> _T: ... - def put(self, item: _T, block: bool = ..., timeout: float | None = ...) -> None: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... def put_nowait(self, item: _T) -> None: ... def _put(self, item: _T) -> None: ... def join(self) -> None: ... def qsize(self) -> int: ... def _qsize(self) -> int: ... def task_done(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class PriorityQueue(Queue[_T]): ... -class LifoQueue(Queue[_T]): ... - -if sys.version_info >= (3, 7): - class SimpleQueue(Generic[_T]): - def __init__(self) -> None: ... - def empty(self) -> bool: ... - def get(self, block: bool = ..., timeout: float | None = ...) -> _T: ... - def get_nowait(self) -> _T: ... - def put(self, item: _T, block: bool = ..., timeout: float | None = ...) -> None: ... - def put_nowait(self, item: _T) -> None: ... - def qsize(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class PriorityQueue(Queue[SupportsRichComparisonT]): + queue: list[SupportsRichComparisonT] + +class LifoQueue(Queue[_T]): + queue: list[_T] diff --git a/stdlib/quopri.pyi b/stdlib/quopri.pyi index c2ffabe7d531..be6892fcbcd7 100644 --- a/stdlib/quopri.pyi +++ b/stdlib/quopri.pyi @@ -1,6 +1,12 @@ -from typing import BinaryIO +from _typeshed import ReadableBuffer, SupportsNoArgReadline, SupportsRead, SupportsWrite +from typing import Protocol, type_check_only -def encode(input: BinaryIO, output: BinaryIO, quotetabs: int, header: int = ...) -> None: ... -def encodestring(s: bytes, quotetabs: int = ..., header: int = ...) -> bytes: ... -def decode(input: BinaryIO, output: BinaryIO, header: int = ...) -> None: ... -def decodestring(s: bytes, header: int = ...) -> bytes: ... +__all__ = ["encode", "decode", "encodestring", "decodestring"] + +@type_check_only +class _Input(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ... + +def encode(input: _Input, output: SupportsWrite[bytes], quotetabs: int, header: bool = False) -> None: ... +def encodestring(s: ReadableBuffer, quotetabs: bool = False, header: bool = False) -> bytes: ... +def decode(input: _Input, output: SupportsWrite[bytes], header: bool = False) -> None: ... +def decodestring(s: str | ReadableBuffer, header: bool = False) -> bytes: ... diff --git a/stdlib/random.pyi b/stdlib/random.pyi index 4834dab6552e..c70c8364684c 100644 --- a/stdlib/random.pyi +++ b/stdlib/random.pyi @@ -3,46 +3,100 @@ import sys from _typeshed import SupportsLenAndGetItem from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet from fractions import Fraction -from typing import Any, ClassVar, NoReturn, Tuple, TypeVar +from typing import Any, ClassVar, TypeVar, overload +from typing_extensions import Never, deprecated + +__all__ = [ + "Random", + "seed", + "random", + "uniform", + "randint", + "choice", + "sample", + "randrange", + "shuffle", + "normalvariate", + "lognormvariate", + "expovariate", + "vonmisesvariate", + "gammavariate", + "triangular", + "gauss", + "betavariate", + "paretovariate", + "weibullvariate", + "getstate", + "setstate", + "getrandbits", + "choices", + "SystemRandom", + "randbytes", +] + +if sys.version_info >= (3, 12): + __all__ += ["binomialvariate"] _T = TypeVar("_T") class Random(_random.Random): VERSION: ClassVar[int] - def __init__(self, x: Any = ...) -> None: ... - def seed(self, a: Any = ..., version: int = ...) -> None: ... - def getstate(self) -> Tuple[Any, ...]: ... - def setstate(self, state: Tuple[Any, ...]) -> None: ... - def getrandbits(self, __k: int) -> int: ... - def randrange(self, start: int, stop: int | None = ..., step: int = ...) -> int: ... + def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: ... # noqa: Y041 + # Using other `seed` types is deprecated since 3.9 and removed in 3.11 + # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit + # int better documents conventional usage of random.seed. + + def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: ... # type: ignore[override] # noqa: Y041 + def getstate(self) -> tuple[Any, ...]: ... + def setstate(self, state: tuple[Any, ...]) -> None: ... + def randrange(self, start: int, stop: int | None = None, step: int = 1) -> int: ... def randint(self, a: int, b: int) -> int: ... - if sys.version_info >= (3, 9): - def randbytes(self, n: int) -> bytes: ... + def randbytes(self, n: int) -> bytes: ... def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: ... def choices( self, population: SupportsLenAndGetItem[_T], - weights: Sequence[float | Fraction] | None = ..., + weights: Sequence[float | Fraction] | None = None, *, - cum_weights: Sequence[float | Fraction] | None = ..., - k: int = ..., + cum_weights: Sequence[float | Fraction] | None = None, + k: int = 1, ) -> list[_T]: ... - def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 11): + def shuffle(self, x: MutableSequence[Any]) -> None: ... + else: + @overload + def shuffle(self, x: MutableSequence[Any]) -> None: ... + @overload + @deprecated("The `random` parameter is deprecated since Python 3.9; removed in Python 3.11.") + def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = None) -> None: ... + + if sys.version_info >= (3, 11): + def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = None) -> list[_T]: ... + else: def sample( - self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[_T] | None = ... + self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = None ) -> list[_T]: ... - else: - def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int) -> list[_T]: ... - def random(self) -> float: ... + def uniform(self, a: float, b: float) -> float: ... - def triangular(self, low: float = ..., high: float = ..., mode: float | None = ...) -> float: ... + def triangular(self, low: float = 0.0, high: float = 1.0, mode: float | None = None) -> float: ... + if sys.version_info >= (3, 12): + def binomialvariate(self, n: int = 1, p: float = 0.5) -> int: ... + def betavariate(self, alpha: float, beta: float) -> float: ... - def expovariate(self, lambd: float) -> float: ... + if sys.version_info >= (3, 12): + def expovariate(self, lambd: float = 1.0) -> float: ... + else: + def expovariate(self, lambd: float) -> float: ... + def gammavariate(self, alpha: float, beta: float) -> float: ... - def gauss(self, mu: float, sigma: float) -> float: ... + if sys.version_info >= (3, 11): + def gauss(self, mu: float = 0.0, sigma: float = 1.0) -> float: ... + def normalvariate(self, mu: float = 0.0, sigma: float = 1.0) -> float: ... + else: + def gauss(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + def lognormvariate(self, mu: float, sigma: float) -> float: ... - def normalvariate(self, mu: float, sigma: float) -> float: ... def vonmisesvariate(self, mu: float, kappa: float) -> float: ... def paretovariate(self, alpha: float) -> float: ... def weibullvariate(self, alpha: float, beta: float) -> float: ... @@ -50,45 +104,32 @@ class Random(_random.Random): # SystemRandom is not implemented for all OS's; good on Windows & Linux class SystemRandom(Random): def getrandbits(self, k: int) -> int: ... # k can be passed by keyword - def getstate(self, *args: Any, **kwds: Any) -> NoReturn: ... - def setstate(self, *args: Any, **kwds: Any) -> NoReturn: ... - -# ----- random function stubs ----- -def seed(a: Any = ..., version: int = ...) -> None: ... -def getstate() -> object: ... -def setstate(state: object) -> None: ... -def getrandbits(__k: int) -> int: ... -def randrange(start: int, stop: None | int = ..., step: int = ...) -> int: ... -def randint(a: int, b: int) -> int: ... - -if sys.version_info >= (3, 9): - def randbytes(n: int) -> bytes: ... - -def choice(seq: SupportsLenAndGetItem[_T]) -> _T: ... -def choices( - population: SupportsLenAndGetItem[_T], - weights: Sequence[float] | None = ..., - *, - cum_weights: Sequence[float] | None = ..., - k: int = ..., -) -> list[_T]: ... -def shuffle(x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... - -if sys.version_info >= (3, 9): - def sample(population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... - -else: - def sample(population: Sequence[_T] | AbstractSet[_T], k: int) -> list[_T]: ... + def getstate(self, *args: Any, **kwds: Any) -> Never: ... + def setstate(self, *args: Any, **kwds: Any) -> Never: ... -def random() -> float: ... -def uniform(a: float, b: float) -> float: ... -def triangular(low: float = ..., high: float = ..., mode: float | None = ...) -> float: ... -def betavariate(alpha: float, beta: float) -> float: ... -def expovariate(lambd: float) -> float: ... -def gammavariate(alpha: float, beta: float) -> float: ... -def gauss(mu: float, sigma: float) -> float: ... -def lognormvariate(mu: float, sigma: float) -> float: ... -def normalvariate(mu: float, sigma: float) -> float: ... -def vonmisesvariate(mu: float, kappa: float) -> float: ... -def paretovariate(alpha: float) -> float: ... -def weibullvariate(alpha: float, beta: float) -> float: ... +_inst: Random +seed = _inst.seed +random = _inst.random +uniform = _inst.uniform +triangular = _inst.triangular +randint = _inst.randint +choice = _inst.choice +randrange = _inst.randrange +sample = _inst.sample +shuffle = _inst.shuffle +choices = _inst.choices +normalvariate = _inst.normalvariate +lognormvariate = _inst.lognormvariate +expovariate = _inst.expovariate +vonmisesvariate = _inst.vonmisesvariate +gammavariate = _inst.gammavariate +gauss = _inst.gauss +if sys.version_info >= (3, 12): + binomialvariate = _inst.binomialvariate +betavariate = _inst.betavariate +paretovariate = _inst.paretovariate +weibullvariate = _inst.weibullvariate +getstate = _inst.getstate +setstate = _inst.setstate +getrandbits = _inst.getrandbits +randbytes = _inst.randbytes diff --git a/stdlib/re.pyi b/stdlib/re.pyi index 01a60d170c50..f0a892c797e9 100644 --- a/stdlib/re.pyi +++ b/stdlib/re.pyi @@ -1,117 +1,347 @@ import enum import sys -from sre_constants import error as error -from typing import Any, AnyStr, Callable, Iterator, Union, overload +from _typeshed import MaybeNone, ReadableBuffer +from collections.abc import Callable, Iterator, Mapping +from types import GenericAlias +from typing import Any, AnyStr, Final, Generic, Literal, TypeAlias, TypeVar, final, overload +from typing_extensions import deprecated + +__all__ = [ + "match", + "fullmatch", + "search", + "sub", + "subn", + "split", + "findall", + "finditer", + "compile", + "purge", + "escape", + "error", + "A", + "I", + "L", + "M", + "S", + "X", + "U", + "ASCII", + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "VERBOSE", + "UNICODE", + "Match", + "Pattern", +] +if sys.version_info >= (3, 15): + __all__ += ["prefixmatch"] +if sys.version_info < (3, 13): + __all__ += ["template"] + +if sys.version_info >= (3, 11): + __all__ += ["NOFLAG", "RegexFlag"] + +if sys.version_info >= (3, 13): + __all__ += ["PatternError"] + +_T = TypeVar("_T") + +# The implementation defines this in re._constants (version_info >= 3, 11) or +# sre_constants. Typeshed has it here because its __module__ attribute is set to "re". +class error(Exception): + msg: str + pattern: str | bytes | None + pos: int | None + lineno: int + colno: int + def __init__(self, msg: str, pattern: str | bytes | None = None, pos: int | None = None) -> None: ... + +if sys.version_info >= (3, 13): + PatternError = error + +@final +class Match(Generic[AnyStr]): + @property + def pos(self) -> int: ... + @property + def endpos(self) -> int: ... + @property + def lastindex(self) -> int | None: ... + @property + def lastgroup(self) -> str | None: ... + @property + def string(self) -> AnyStr: ... + + # The regular expression object whose match() or search() method produced + # this match instance. + @property + def re(self) -> Pattern[AnyStr]: ... + + @overload + def expand(self: Match[str], template: str) -> str: ... + @overload + def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... + @overload + def expand(self, template: AnyStr) -> AnyStr: ... + + # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. + @overload + def group(self, group: Literal[0] = 0, /) -> AnyStr: ... + @overload + def group(self, group: str | int, /) -> AnyStr | MaybeNone: ... + @overload + def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | MaybeNone, ...]: ... + + # Each item of groups()'s return tuple is either "AnyStr" or + # "AnyStr | None", depending on the pattern. + @overload + def groups(self) -> tuple[AnyStr | MaybeNone, ...]: ... + @overload + def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... + + # Each value in groupdict()'s return dict is either "AnyStr" or + # "AnyStr | None", depending on the pattern. + @overload + def groupdict(self) -> dict[str, AnyStr | MaybeNone]: ... + @overload + def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... + + def start(self, group: int | str = 0, /) -> int: ... + def end(self, group: int | str = 0, /) -> int: ... + def span(self, group: int | str = 0, /) -> tuple[int, int]: ... + @property + def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented + + # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. + @overload + def __getitem__(self, key: Literal[0], /) -> AnyStr: ... + @overload + def __getitem__(self, key: int | str, /) -> AnyStr | MaybeNone: ... + + def __copy__(self) -> Match[AnyStr]: ... + def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class Pattern(Generic[AnyStr]): + @property + def flags(self) -> int: ... + @property + def groupindex(self) -> Mapping[str, int]: ... + @property + def groups(self) -> int: ... + @property + def pattern(self) -> AnyStr: ... + + @overload + def search(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... + @overload + def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... + @overload + def search(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + @overload + def match(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... + @overload + def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... + @overload + def match(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + if sys.version_info >= (3, 15): + prefixmatch = match + + @overload + def fullmatch(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... + @overload + def fullmatch( + self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize + ) -> Match[bytes] | None: ... + @overload + def fullmatch(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + @overload + def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | MaybeNone]: ... + @overload + def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | MaybeNone]: ... + @overload + def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | MaybeNone]: ... + + # return type is either list[str/bytes] or list[tuple[str/bytes, ...]] + @overload + def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... + @overload + def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... + @overload + def findall(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> list[AnyStr]: ... + + @overload + def finditer(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[str]]: ... + @overload + def finditer( + self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize + ) -> Iterator[Match[bytes]]: ... + @overload + def finditer(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[AnyStr]]: ... + + @overload + def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> str: ... + @overload + def sub( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + ) -> bytes: ... + @overload + def sub(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> AnyStr: ... + + @overload + def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> tuple[str, int]: ... + @overload + def subn( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + ) -> tuple[bytes, int]: ... + @overload + def subn(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> tuple[AnyStr, int]: ... + + def __copy__(self) -> Pattern[AnyStr]: ... + def __deepcopy__(self, memo: Any, /) -> Pattern[AnyStr]: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # ----- re variables and constants ----- -if sys.version_info >= (3, 7): - from typing import Match as Match, Pattern as Pattern -else: - from typing import Match, Pattern class RegexFlag(enum.IntFlag): - A: int - ASCII: int - DEBUG: int - I: int - IGNORECASE: int - L: int - LOCALE: int - M: int - MULTILINE: int - S: int - DOTALL: int - X: int - VERBOSE: int - U: int - UNICODE: int - T: int - TEMPLATE: int + A = 256 + ASCII = A + DEBUG = 128 + I = 2 + IGNORECASE = I + L = 4 + LOCALE = L + M = 8 + MULTILINE = M + S = 16 + DOTALL = S + X = 64 + VERBOSE = X + U = 32 + UNICODE = U + if sys.version_info < (3, 13): + T = 1 + TEMPLATE = T + if sys.version_info >= (3, 11): + NOFLAG = 0 -A = RegexFlag.A -ASCII = RegexFlag.ASCII -DEBUG = RegexFlag.DEBUG -I = RegexFlag.I -IGNORECASE = RegexFlag.IGNORECASE -L = RegexFlag.L -LOCALE = RegexFlag.LOCALE -M = RegexFlag.M -MULTILINE = RegexFlag.MULTILINE -S = RegexFlag.S -DOTALL = RegexFlag.DOTALL -X = RegexFlag.X -VERBOSE = RegexFlag.VERBOSE -U = RegexFlag.U -UNICODE = RegexFlag.UNICODE -T = RegexFlag.T -TEMPLATE = RegexFlag.TEMPLATE -_FlagsType = Union[int, RegexFlag] +A: Final = RegexFlag.A +ASCII: Final = RegexFlag.ASCII +DEBUG: Final = RegexFlag.DEBUG +I: Final = RegexFlag.I +IGNORECASE: Final = RegexFlag.IGNORECASE +L: Final = RegexFlag.L +LOCALE: Final = RegexFlag.LOCALE +M: Final = RegexFlag.M +MULTILINE: Final = RegexFlag.MULTILINE +S: Final = RegexFlag.S +DOTALL: Final = RegexFlag.DOTALL +X: Final = RegexFlag.X +VERBOSE: Final = RegexFlag.VERBOSE +U: Final = RegexFlag.U +UNICODE: Final = RegexFlag.UNICODE +if sys.version_info < (3, 13): + T: Final = RegexFlag.T + TEMPLATE: Final = RegexFlag.TEMPLATE +if sys.version_info >= (3, 11): + NOFLAG: Final = RegexFlag.NOFLAG +_FlagsType: TypeAlias = int | RegexFlag -if sys.version_info < (3, 7): - # undocumented - _pattern_type: type +# Type-wise the compile() overloads are unnecessary, they could also be modeled using +# unions in the parameter types. However mypy has a bug regarding TypeVar +# constraints (https://github.com/python/mypy/issues/11880), +# which limits us here because AnyStr is a constrained TypeVar. +# pattern arguments do *not* accept arbitrary buffers such as bytearray, +# because the pattern must be hashable. @overload -def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... +def compile(pattern: AnyStr, flags: _FlagsType = 0) -> Pattern[AnyStr]: ... @overload -def compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... +def compile(pattern: Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... + @overload -def search(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def search(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... @overload -def search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def search(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + @overload -def match(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... @overload -def match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + +if sys.version_info >= (3, 15): + @overload + def prefixmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... + @overload + def prefixmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... -# New in Python 3.4 @overload -def fullmatch(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... @overload -def fullmatch(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + @overload -def split(pattern: AnyStr, string: AnyStr, maxsplit: int = ..., flags: _FlagsType = ...) -> list[AnyStr | Any]: ... +def split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | MaybeNone]: ... @overload -def split(pattern: Pattern[AnyStr], string: AnyStr, maxsplit: int = ..., flags: _FlagsType = ...) -> list[AnyStr | Any]: ... +def split( + pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0 +) -> list[bytes | MaybeNone]: ... + +# return type is either list[str/bytes] or list[tuple[str/bytes, ...]] @overload -def findall(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> list[Any]: ... +def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: ... @overload -def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> list[Any]: ... +def findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> list[Any]: ... -# Return an iterator yielding match objects over all non-overlapping matches -# for the RE pattern in string. The string is scanned left-to-right, and -# matches are returned in the order found. Empty matches are included in the -# result unless they touch the beginning of another match. -@overload -def finditer(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... @overload -def finditer(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... +def finditer(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Iterator[Match[str]]: ... @overload -def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... +def finditer(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Iterator[Match[bytes]]: ... + @overload def sub( - pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> AnyStr: ... -@overload -def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... + pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 +) -> str: ... @overload def sub( - pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> AnyStr: ... -@overload -def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> tuple[AnyStr, int]: ... -@overload -def subn( - pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> tuple[AnyStr, int]: ... + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: _FlagsType = 0, +) -> bytes: ... + @overload def subn( - pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> tuple[AnyStr, int]: ... + pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 +) -> tuple[str, int]: ... @overload def subn( - pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> tuple[AnyStr, int]: ... + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: _FlagsType = 0, +) -> tuple[bytes, int]: ... + def escape(pattern: AnyStr) -> AnyStr: ... def purge() -> None: ... -def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... + +if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13. Use `re.compile()` instead.") + def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... # undocumented diff --git a/stdlib/readline.pyi b/stdlib/readline.pyi index 2de749b2c216..aff1e504a174 100644 --- a/stdlib/readline.pyi +++ b/stdlib/readline.pyi @@ -1,33 +1,39 @@ +import sys from _typeshed import StrOrBytesPath -from typing import Callable, Optional, Sequence +from collections.abc import Callable, Sequence +from typing import Literal, TypeAlias -_CompleterT = Optional[Callable[[str, int], Optional[str]]] -_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] +if sys.platform != "win32": + _Completer: TypeAlias = Callable[[str, int], str | None] + _CompDisp: TypeAlias = Callable[[str, Sequence[str], int], None] -def parse_and_bind(__string: str) -> None: ... -def read_init_file(__filename: StrOrBytesPath | None = ...) -> None: ... -def get_line_buffer() -> str: ... -def insert_text(__string: str) -> None: ... -def redisplay() -> None: ... -def read_history_file(__filename: StrOrBytesPath | None = ...) -> None: ... -def write_history_file(__filename: StrOrBytesPath | None = ...) -> None: ... -def append_history_file(__nelements: int, __filename: StrOrBytesPath | None = ...) -> None: ... -def get_history_length() -> int: ... -def set_history_length(__length: int) -> None: ... -def clear_history() -> None: ... -def get_current_history_length() -> int: ... -def get_history_item(__index: int) -> str: ... -def remove_history_item(__pos: int) -> None: ... -def replace_history_item(__pos: int, __line: str) -> None: ... -def add_history(__string: str) -> None: ... -def set_auto_history(__enabled: bool) -> None: ... -def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_completer(__function: _CompleterT = ...) -> None: ... -def get_completer() -> _CompleterT: ... -def get_completion_type() -> int: ... -def get_begidx() -> int: ... -def get_endidx() -> int: ... -def set_completer_delims(__string: str) -> None: ... -def get_completer_delims() -> str: ... -def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... + def parse_and_bind(string: str, /) -> None: ... + def read_init_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def get_line_buffer() -> str: ... + def insert_text(string: str, /) -> None: ... + def redisplay() -> None: ... + def read_history_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def write_history_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def append_history_file(nelements: int, filename: StrOrBytesPath | None = None, /) -> None: ... + def get_history_length() -> int: ... + def set_history_length(length: int, /) -> None: ... + def clear_history() -> None: ... + def get_current_history_length() -> int: ... + def get_history_item(index: int, /) -> str: ... + def remove_history_item(pos: int, /) -> None: ... + def replace_history_item(pos: int, line: str, /) -> None: ... + def add_history(string: str, /) -> None: ... + def set_auto_history(enabled: bool, /) -> None: ... + def set_startup_hook(function: Callable[[], object] | None = None, /) -> None: ... + def set_pre_input_hook(function: Callable[[], object] | None = None, /) -> None: ... + def set_completer(function: _Completer | None = None, /) -> None: ... + def get_completer() -> _Completer | None: ... + def get_completion_type() -> int: ... + def get_begidx() -> int: ... + def get_endidx() -> int: ... + def set_completer_delims(string: str, /) -> None: ... + def get_completer_delims() -> str: ... + def set_completion_display_matches_hook(function: _CompDisp | None = None, /) -> None: ... + + if sys.version_info >= (3, 13): + backend: Literal["readline", "editline"] diff --git a/stdlib/reprlib.pyi b/stdlib/reprlib.pyi index 4d400554a4ff..d990c2708ae9 100644 --- a/stdlib/reprlib.pyi +++ b/stdlib/reprlib.pyi @@ -1,10 +1,14 @@ +import sys from array import array from collections import deque -from typing import Any, Callable, Tuple +from collections.abc import Callable +from typing import Any, TypeAlias -_ReprFunc = Callable[[Any], str] +__all__ = ["Repr", "repr", "recursive_repr"] -def recursive_repr(fillvalue: str = ...) -> Callable[[_ReprFunc], _ReprFunc]: ... +_ReprFunc: TypeAlias = Callable[[Any], str] + +def recursive_repr(fillvalue: str = "...") -> Callable[[_ReprFunc], _ReprFunc]: ... class Repr: maxlevel: int @@ -18,10 +22,33 @@ class Repr: maxlong: int maxstring: int maxother: int - def __init__(self) -> None: ... + if sys.version_info >= (3, 11): + fillvalue: str + if sys.version_info >= (3, 12): + indent: str | int | None + + if sys.version_info >= (3, 12): + def __init__( + self, + *, + maxlevel: int = 6, + maxtuple: int = 6, + maxlist: int = 6, + maxarray: int = 5, + maxdict: int = 4, + maxset: int = 6, + maxfrozenset: int = 6, + maxdeque: int = 6, + maxstring: int = 30, + maxlong: int = 40, + maxother: int = 30, + fillvalue: str = "...", + indent: str | int | None = None, + ) -> None: ... + def repr(self, x: Any) -> str: ... def repr1(self, x: Any, level: int) -> str: ... - def repr_tuple(self, x: Tuple[Any, ...], level: int) -> str: ... + def repr_tuple(self, x: tuple[Any, ...], level: int) -> str: ... def repr_list(self, x: list[Any], level: int) -> str: ... def repr_array(self, x: array[Any], level: int) -> str: ... def repr_set(self, x: set[Any], level: int) -> str: ... diff --git a/stdlib/resource.pyi b/stdlib/resource.pyi index ff6f1d79e483..7e72b28cc6dd 100644 --- a/stdlib/resource.pyi +++ b/stdlib/resource.pyi @@ -1,74 +1,102 @@ import sys from _typeshed import structseq -from typing import Tuple, overload -from typing_extensions import final +from typing import Final, final -RLIMIT_AS: int -RLIMIT_CORE: int -RLIMIT_CPU: int -RLIMIT_DATA: int -RLIMIT_FSIZE: int -RLIMIT_MEMLOCK: int -RLIMIT_NOFILE: int -RLIMIT_NPROC: int -RLIMIT_RSS: int -RLIMIT_STACK: int -RLIM_INFINITY: int -RUSAGE_CHILDREN: int -RUSAGE_SELF: int -if sys.platform == "linux": - RLIMIT_MSGQUEUE: int - RLIMIT_NICE: int - RLIMIT_OFILE: int - RLIMIT_RTPRIO: int - RLIMIT_RTTIME: int - RLIMIT_SIGPENDING: int - RUSAGE_THREAD: int +if sys.platform != "win32": + # Depends on resource.h + RLIMIT_AS: Final[int] + RLIMIT_CORE: Final[int] + RLIMIT_CPU: Final[int] + RLIMIT_DATA: Final[int] + RLIMIT_FSIZE: Final[int] + RLIMIT_MEMLOCK: Final[int] + RLIMIT_NOFILE: Final[int] + RLIMIT_NPROC: Final[int] + RLIMIT_RSS: Final[int] + RLIMIT_STACK: Final[int] + RLIM_INFINITY: Final[int] + if sys.version_info >= (3, 15): + RLIM_SAVED_CUR: Final[int] + RLIM_SAVED_MAX: Final[int] + RUSAGE_CHILDREN: Final[int] + RUSAGE_SELF: Final[int] + if sys.platform == "linux": + RLIMIT_MSGQUEUE: Final[int] + RLIMIT_NICE: Final[int] + RLIMIT_OFILE: Final[int] + RLIMIT_RTPRIO: Final[int] + RLIMIT_RTTIME: Final[int] + RLIMIT_SIGPENDING: Final[int] + RUSAGE_THREAD: Final[int] + if sys.version_info >= (3, 15) and sys.platform != "linux" and sys.platform != "darwin": + RLIMIT_NTHR: Final[int] + RLIMIT_PIPEBUF: Final[int] + RLIMIT_THREADS: Final[int] + RLIMIT_UMTXP: Final[int] -@final -class struct_rusage(structseq[float], Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int]): - @property - def ru_utime(self) -> float: ... - @property - def ru_stime(self) -> float: ... - @property - def ru_maxrss(self) -> int: ... - @property - def ru_ixrss(self) -> int: ... - @property - def ru_idrss(self) -> int: ... - @property - def ru_isrss(self) -> int: ... - @property - def ru_minflt(self) -> int: ... - @property - def ru_majflt(self) -> int: ... - @property - def ru_nswap(self) -> int: ... - @property - def ru_inblock(self) -> int: ... - @property - def ru_oublock(self) -> int: ... - @property - def ru_msgsnd(self) -> int: ... - @property - def ru_msgrcv(self) -> int: ... - @property - def ru_nsignals(self) -> int: ... - @property - def ru_nvcsw(self) -> int: ... - @property - def ru_nivcsw(self) -> int: ... + @final + class struct_rusage( + structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] + ): + __match_args__: Final = ( + "ru_utime", + "ru_stime", + "ru_maxrss", + "ru_ixrss", + "ru_idrss", + "ru_isrss", + "ru_minflt", + "ru_majflt", + "ru_nswap", + "ru_inblock", + "ru_oublock", + "ru_msgsnd", + "ru_msgrcv", + "ru_nsignals", + "ru_nvcsw", + "ru_nivcsw", + ) -def getpagesize() -> int: ... -def getrlimit(__resource: int) -> tuple[int, int]: ... -def getrusage(__who: int) -> struct_rusage: ... -def setrlimit(__resource: int, __limits: tuple[int, int]) -> None: ... + @property + def ru_utime(self) -> float: ... + @property + def ru_stime(self) -> float: ... + @property + def ru_maxrss(self) -> int: ... + @property + def ru_ixrss(self) -> int: ... + @property + def ru_idrss(self) -> int: ... + @property + def ru_isrss(self) -> int: ... + @property + def ru_minflt(self) -> int: ... + @property + def ru_majflt(self) -> int: ... + @property + def ru_nswap(self) -> int: ... + @property + def ru_inblock(self) -> int: ... + @property + def ru_oublock(self) -> int: ... + @property + def ru_msgsnd(self) -> int: ... + @property + def ru_msgrcv(self) -> int: ... + @property + def ru_nsignals(self) -> int: ... + @property + def ru_nvcsw(self) -> int: ... + @property + def ru_nivcsw(self) -> int: ... -if sys.platform == "linux": - @overload - def prlimit(pid: int, resource: int, limits: tuple[int, int]) -> tuple[int, int]: ... - @overload - def prlimit(pid: int, resource: int) -> tuple[int, int]: ... - -error = OSError + def getpagesize() -> int: ... + def getrlimit(resource: int, /) -> tuple[int, int]: ... + def getrusage(who: int, /) -> struct_rusage: ... + def setrlimit(resource: int, limits: tuple[int, int], /) -> None: ... + if sys.platform == "linux": + if sys.version_info >= (3, 12): + def prlimit(pid: int, resource: int, limits: tuple[int, int] | None = None, /) -> tuple[int, int]: ... + else: + def prlimit(pid: int, resource: int, limits: tuple[int, int] = ..., /) -> tuple[int, int]: ... + error = OSError diff --git a/stdlib/rlcompleter.pyi b/stdlib/rlcompleter.pyi index f971c424213d..8d9477e3ee45 100644 --- a/stdlib/rlcompleter.pyi +++ b/stdlib/rlcompleter.pyi @@ -1,5 +1,9 @@ from typing import Any +__all__ = ["Completer"] + class Completer: - def __init__(self, namespace: dict[str, Any] | None = ...) -> None: ... + def __init__(self, namespace: dict[str, Any] | None = None) -> None: ... def complete(self, text: str, state: int) -> str | None: ... + def attr_matches(self, text: str) -> list[str]: ... + def global_matches(self, text: str) -> list[str]: ... diff --git a/stdlib/runpy.pyi b/stdlib/runpy.pyi index 371fa9d07cf8..d4406ea4ac41 100644 --- a/stdlib/runpy.pyi +++ b/stdlib/runpy.pyi @@ -1,21 +1,24 @@ -from _typeshed import Self +from _typeshed import Unused from types import ModuleType from typing import Any +from typing_extensions import Self + +__all__ = ["run_module", "run_path"] class _TempModule: mod_name: str module: ModuleType def __init__(self, mod_name: str) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... class _ModifiedArgv0: value: Any def __init__(self, value: Any) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: Unused) -> None: ... def run_module( - mod_name: str, init_globals: dict[str, Any] | None = ..., run_name: str | None = ..., alter_sys: bool = ... + mod_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None, alter_sys: bool = False ) -> dict[str, Any]: ... -def run_path(path_name: str, init_globals: dict[str, Any] | None = ..., run_name: str | None = ...) -> dict[str, Any]: ... +def run_path(path_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None) -> dict[str, Any]: ... diff --git a/stdlib/sched.pyi b/stdlib/sched.pyi index cb96dc2bbf4a..54eb6ed0cd53 100644 --- a/stdlib/sched.pyi +++ b/stdlib/sched.pyi @@ -1,31 +1,33 @@ -from typing import Any, Callable, NamedTuple, Tuple +import time +from collections.abc import Callable +from typing import Any, NamedTuple, TypeAlias + +__all__ = ["scheduler"] + +_ActionCallback: TypeAlias = Callable[..., Any] class Event(NamedTuple): time: float priority: Any - action: Callable[..., Any] - argument: Tuple[Any, ...] + sequence: int + action: _ActionCallback + argument: tuple[Any, ...] kwargs: dict[str, Any] class scheduler: - def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], None] = ...) -> None: ... + timefunc: Callable[[], float] + delayfunc: Callable[[float], object] + + def __init__( + self, timefunc: Callable[[], float] = time.monotonic, delayfunc: Callable[[float], object] = time.sleep + ) -> None: ... def enterabs( - self, - time: float, - priority: Any, - action: Callable[..., Any], - argument: Tuple[Any, ...] = ..., - kwargs: dict[str, Any] = ..., + self, time: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ... ) -> Event: ... def enter( - self, - delay: float, - priority: Any, - action: Callable[..., Any], - argument: Tuple[Any, ...] = ..., - kwargs: dict[str, Any] = ..., + self, delay: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ... ) -> Event: ... - def run(self, blocking: bool = ...) -> float | None: ... + def run(self, blocking: bool = True) -> float | None: ... def cancel(self, event: Event) -> None: ... def empty(self) -> bool: ... @property diff --git a/stdlib/secrets.pyi b/stdlib/secrets.pyi index f57eef8492d7..76479af97a07 100644 --- a/stdlib/secrets.pyi +++ b/stdlib/secrets.pyi @@ -1,13 +1,17 @@ from _typeshed import SupportsLenAndGetItem from hmac import compare_digest as compare_digest from random import SystemRandom as SystemRandom -from typing import TypeVar +from typing import Final, TypeVar + +__all__ = ["choice", "randbelow", "randbits", "SystemRandom", "token_bytes", "token_hex", "token_urlsafe", "compare_digest"] _T = TypeVar("_T") +DEFAULT_ENTROPY: Final[int] + def randbelow(exclusive_upper_bound: int) -> int: ... def randbits(k: int) -> int: ... def choice(seq: SupportsLenAndGetItem[_T]) -> _T: ... -def token_bytes(nbytes: int | None = ...) -> bytes: ... -def token_hex(nbytes: int | None = ...) -> str: ... -def token_urlsafe(nbytes: int | None = ...) -> str: ... +def token_bytes(nbytes: int | None = None) -> bytes: ... +def token_hex(nbytes: int | None = None) -> str: ... +def token_urlsafe(nbytes: int | None = None) -> str: ... diff --git a/stdlib/select.pyi b/stdlib/select.pyi index 5650ed4c9a2c..ad93cb0b7055 100644 --- a/stdlib/select.pyi +++ b/stdlib/select.pyi @@ -1,39 +1,51 @@ import sys -from _typeshed import FileDescriptorLike, Self +from _typeshed import FileDescriptorLike +from collections.abc import Iterable from types import TracebackType -from typing import Any, Iterable, Type +from typing import Any, ClassVar, Final, TypeVar, final, overload +from typing_extensions import Never, Self, deprecated if sys.platform != "win32": - PIPE_BUF: int - POLLERR: int - POLLHUP: int - POLLIN: int - POLLMSG: int - POLLNVAL: int - POLLOUT: int - POLLPRI: int - POLLRDBAND: int - POLLRDHUP: int - POLLRDNORM: int - POLLWRBAND: int - POLLWRNORM: int + PIPE_BUF: Final[int] + POLLERR: Final[int] + POLLHUP: Final[int] + POLLIN: Final[int] + if sys.platform == "linux": + POLLMSG: Final[int] + POLLNVAL: Final[int] + POLLOUT: Final[int] + POLLPRI: Final[int] + POLLRDBAND: Final[int] + if sys.platform == "linux": + POLLRDHUP: Final[int] + POLLRDNORM: Final[int] + POLLWRBAND: Final[int] + POLLWRNORM: Final[int] -class poll: - def __init__(self) -> None: ... - def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... - def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... - def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ...) -> list[tuple[int, int]]: ... + # This is actually a function that returns an instance of a class. + # The class is not accessible directly, and also calls itself select.poll. + @final + class poll: + # default value is select.POLLIN | select.POLLPRI | select.POLLOUT + def register(self, fd: FileDescriptorLike, eventmask: int = 7, /) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int, /) -> None: ... + def unregister(self, fd: FileDescriptorLike, /) -> None: ... + def poll(self, timeout: float | None = None, /) -> list[tuple[int, int]]: ... + +_R = TypeVar("_R", default=Never, bound=FileDescriptorLike) +_W = TypeVar("_W", default=Never, bound=FileDescriptorLike) +_X = TypeVar("_X", default=Never, bound=FileDescriptorLike) def select( - __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: float | None = ... -) -> tuple[list[Any], list[Any], list[Any]]: ... + rlist: Iterable[_R], wlist: Iterable[_W], xlist: Iterable[_X], timeout: float | None = None, / +) -> tuple[list[_R], list[_W], list[_X]]: ... error = OSError if sys.platform != "linux" and sys.platform != "win32": # BSD only - class kevent(object): + @final + class kevent: data: Any fflags: int filter: int @@ -41,73 +53,82 @@ if sys.platform != "linux" and sys.platform != "win32": ident: int udata: Any def __init__( - self, - ident: FileDescriptorLike, - filter: int = ..., - flags: int = ..., - fflags: int = ..., - data: Any = ..., - udata: Any = ..., + self, ident: FileDescriptorLike, filter: int = ..., flags: int = ..., fflags: int = 0, data: Any = 0, udata: Any = 0 ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + # BSD only - class kqueue(object): + @final + class kqueue: closed: bool def __init__(self) -> None: ... def close(self) -> None: ... def control( - self, __changelist: Iterable[kevent] | None, __maxevents: int, __timeout: float | None = ... + self, changelist: Iterable[kevent] | None, maxevents: int, timeout: float | None = None, / ) -> list[kevent]: ... def fileno(self) -> int: ... @classmethod - def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... - KQ_EV_ADD: int - KQ_EV_CLEAR: int - KQ_EV_DELETE: int - KQ_EV_DISABLE: int - KQ_EV_ENABLE: int - KQ_EV_EOF: int - KQ_EV_ERROR: int - KQ_EV_FLAG1: int - KQ_EV_ONESHOT: int - KQ_EV_SYSFLAGS: int - KQ_FILTER_AIO: int - KQ_FILTER_NETDEV: int - KQ_FILTER_PROC: int - KQ_FILTER_READ: int - KQ_FILTER_SIGNAL: int - KQ_FILTER_TIMER: int - KQ_FILTER_VNODE: int - KQ_FILTER_WRITE: int - KQ_NOTE_ATTRIB: int - KQ_NOTE_CHILD: int - KQ_NOTE_DELETE: int - KQ_NOTE_EXEC: int - KQ_NOTE_EXIT: int - KQ_NOTE_EXTEND: int - KQ_NOTE_FORK: int - KQ_NOTE_LINK: int + def fromfd(cls, fd: FileDescriptorLike, /) -> kqueue: ... + + KQ_EV_ADD: Final[int] + KQ_EV_CLEAR: Final[int] + KQ_EV_DELETE: Final[int] + KQ_EV_DISABLE: Final[int] + KQ_EV_ENABLE: Final[int] + KQ_EV_EOF: Final[int] + KQ_EV_ERROR: Final[int] + KQ_EV_FLAG1: Final[int] + KQ_EV_ONESHOT: Final[int] + KQ_EV_SYSFLAGS: Final[int] + KQ_FILTER_AIO: Final[int] if sys.platform != "darwin": - KQ_NOTE_LINKDOWN: int - KQ_NOTE_LINKINV: int - KQ_NOTE_LINKUP: int - KQ_NOTE_LOWAT: int - KQ_NOTE_PCTRLMASK: int - KQ_NOTE_PDATAMASK: int - KQ_NOTE_RENAME: int - KQ_NOTE_REVOKE: int - KQ_NOTE_TRACK: int - KQ_NOTE_TRACKERR: int - KQ_NOTE_WRITE: int + KQ_FILTER_NETDEV: Final[int] + KQ_FILTER_PROC: Final[int] + KQ_FILTER_READ: Final[int] + KQ_FILTER_SIGNAL: Final[int] + KQ_FILTER_TIMER: Final[int] + KQ_FILTER_VNODE: Final[int] + KQ_FILTER_WRITE: Final[int] + KQ_NOTE_ATTRIB: Final[int] + KQ_NOTE_CHILD: Final[int] + KQ_NOTE_DELETE: Final[int] + KQ_NOTE_EXEC: Final[int] + KQ_NOTE_EXIT: Final[int] + KQ_NOTE_EXTEND: Final[int] + KQ_NOTE_FORK: Final[int] + KQ_NOTE_LINK: Final[int] + if sys.platform != "darwin": + KQ_NOTE_LINKDOWN: Final[int] + KQ_NOTE_LINKINV: Final[int] + KQ_NOTE_LINKUP: Final[int] + KQ_NOTE_LOWAT: Final[int] + KQ_NOTE_PCTRLMASK: Final[int] + KQ_NOTE_PDATAMASK: Final[int] + KQ_NOTE_RENAME: Final[int] + KQ_NOTE_REVOKE: Final[int] + KQ_NOTE_TRACK: Final[int] + KQ_NOTE_TRACKERR: Final[int] + KQ_NOTE_WRITE: Final[int] if sys.platform == "linux": - class epoll(object): - def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... - def __enter__(self: Self) -> Self: ... + @final + class epoll: + @overload + def __new__(self, sizehint: int = -1) -> Self: ... + @overload + @deprecated( + "The `flags` parameter is deprecated since Python 3.4. " + "Use `os.set_inheritable()` to make the file descriptor inheritable." + ) + def __new__(self, sizehint: int = -1, flags: int = 0) -> Self: ... + + def __enter__(self) -> Self: ... def __exit__( self, - exc_type: Type[BaseException] | None = ..., - exc_val: BaseException | None = ..., - exc_tb: TracebackType | None = ..., + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + exc_tb: TracebackType | None = None, + /, ) -> None: ... def close(self) -> None: ... closed: bool @@ -115,28 +136,31 @@ if sys.platform == "linux": def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ..., maxevents: int = ...) -> list[tuple[int, int]]: ... + def poll(self, timeout: float | None = None, maxevents: int = -1) -> list[tuple[int, int]]: ... @classmethod - def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... - EPOLLERR: int - EPOLLEXCLUSIVE: int - EPOLLET: int - EPOLLHUP: int - EPOLLIN: int - EPOLLMSG: int - EPOLLONESHOT: int - EPOLLOUT: int - EPOLLPRI: int - EPOLLRDBAND: int - EPOLLRDHUP: int - EPOLLRDNORM: int - EPOLLWRBAND: int - EPOLLWRNORM: int - EPOLL_RDHUP: int - EPOLL_CLOEXEC: int + def fromfd(cls, fd: FileDescriptorLike, /) -> epoll: ... + + EPOLLERR: Final[int] + EPOLLEXCLUSIVE: Final[int] + EPOLLET: Final[int] + EPOLLHUP: Final[int] + EPOLLIN: Final[int] + EPOLLMSG: Final[int] + EPOLLONESHOT: Final[int] + EPOLLOUT: Final[int] + EPOLLPRI: Final[int] + EPOLLRDBAND: Final[int] + EPOLLRDHUP: Final[int] + EPOLLRDNORM: Final[int] + EPOLLWRBAND: Final[int] + EPOLLWRNORM: Final[int] + EPOLL_CLOEXEC: Final[int] + if sys.version_info >= (3, 14): + EPOLLWAKEUP: Final[int] if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": # Solaris only + @final class devpoll: def close(self) -> None: ... closed: bool @@ -144,4 +168,4 @@ if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... def modify(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ...) -> list[tuple[int, int]]: ... + def poll(self, timeout: float | None = None) -> list[tuple[int, int]]: ... diff --git a/stdlib/selectors.pyi b/stdlib/selectors.pyi index c3fe7ec47ace..4a3478a67552 100644 --- a/stdlib/selectors.pyi +++ b/stdlib/selectors.pyi @@ -1,71 +1,67 @@ import sys -from _typeshed import FileDescriptor, FileDescriptorLike, Self +from _typeshed import FileDescriptor, FileDescriptorLike, Unused from abc import ABCMeta, abstractmethod -from typing import Any, Mapping, NamedTuple +from collections.abc import Mapping +from typing import Any, Final, NamedTuple +from typing_extensions import Self -_EventMask = int - -EVENT_READ: _EventMask -EVENT_WRITE: _EventMask +EVENT_READ: Final = 1 +EVENT_WRITE: Final = 2 class SelectorKey(NamedTuple): fileobj: FileDescriptorLike fd: FileDescriptor - events: _EventMask + events: int data: Any class BaseSelector(metaclass=ABCMeta): @abstractmethod - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... @abstractmethod def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def modify(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... @abstractmethod - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... def close(self) -> None: ... def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ... @abstractmethod def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... -class SelectSelector(BaseSelector): - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... +class _BaseSelectorImpl(BaseSelector, metaclass=ABCMeta): + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... + def modify(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... +class SelectSelector(_BaseSelectorImpl): + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + +class _PollLikeSelector(_BaseSelectorImpl): + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + if sys.platform != "win32": - class PollSelector(BaseSelector): - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... - def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + class PollSelector(_PollLikeSelector): ... if sys.platform == "linux": - class EpollSelector(BaseSelector): + class EpollSelector(_PollLikeSelector): def fileno(self) -> int: ... - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... - def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... -class DevpollSelector(BaseSelector): - def fileno(self) -> int: ... - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... - def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... +if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": + # Solaris only + class DevpollSelector(_PollLikeSelector): + def fileno(self) -> int: ... -class KqueueSelector(BaseSelector): - def fileno(self) -> int: ... - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... - def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... +if sys.platform != "win32" and sys.platform != "linux": + class KqueueSelector(_BaseSelectorImpl): + def fileno(self) -> int: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... -class DefaultSelector(BaseSelector): - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def select(self, timeout: float | None = ...) -> list[tuple[SelectorKey, _EventMask]]: ... - def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... +# Not a real class at runtime, it is just a conditional alias to other real selectors. +# The runtime logic is more fine-grained than a `sys.platform` check; +# not really expressible in the stubs +class DefaultSelector(_BaseSelectorImpl): + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + if sys.platform != "win32": + def fileno(self) -> int: ... diff --git a/stdlib/shelve.pyi b/stdlib/shelve.pyi index 90b2aafa4f03..c599b0af6138 100644 --- a/stdlib/shelve.pyi +++ b/stdlib/shelve.pyi @@ -1,30 +1,66 @@ -from _typeshed import Self -from collections.abc import Iterator, MutableMapping +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterator, MutableMapping +from dbm import _TFlags from types import TracebackType -from typing import Type, TypeVar, overload +from typing import Any, TypeVar, overload +from typing_extensions import Self + +__all__ = ["Shelf", "BsdDbShelf", "DbfilenameShelf", "open"] +if sys.version_info >= (3, 15): + __all__ += ["ShelveError"] _T = TypeVar("_T") _VT = TypeVar("_VT") +if sys.version_info >= (3, 15): + class ShelveError(Exception): ... + class Shelf(MutableMapping[str, _VT]): - def __init__( - self, dict: MutableMapping[bytes, bytes], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... - ) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + dict: MutableMapping[bytes, bytes], + protocol: int | None = None, + writeback: bool = False, + keyencoding: str = "utf-8", + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> None: ... + + else: + def __init__( + self, + dict: MutableMapping[bytes, bytes], + protocol: int | None = None, + writeback: bool = False, + keyencoding: str = "utf-8", + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... + + @overload # type: ignore[override] + def get(self, key: str, default: None = None) -> _VT | None: ... @overload - def get(self, key: str) -> _VT | None: ... + def get(self, key: str, default: _VT) -> _VT: ... @overload def get(self, key: str, default: _T) -> _VT | _T: ... + def __getitem__(self, key: str) -> _VT: ... def __setitem__(self, key: str, value: _VT) -> None: ... def __delitem__(self, key: str) -> None: ... - def __enter__(self: Self) -> Self: ... + def __contains__(self, key: str) -> bool: ... # type: ignore[override] + def __enter__(self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... + def __del__(self) -> None: ... def close(self) -> None: ... def sync(self) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... class BsdDbShelf(Shelf[_VT]): def set_location(self, key: str) -> tuple[str, _VT]: ... @@ -34,6 +70,41 @@ class BsdDbShelf(Shelf[_VT]): def last(self) -> tuple[str, _VT]: ... class DbfilenameShelf(Shelf[_VT]): - def __init__(self, filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + filename: StrOrBytesPath, + flag: _TFlags = "c", + protocol: int | None = None, + writeback: bool = False, + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> None: ... + + elif sys.version_info >= (3, 11): + def __init__( + self, filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False + ) -> None: ... + + else: + def __init__(self, filename: str, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> None: ... + +if sys.version_info >= (3, 15): + def open( + filename: StrOrBytesPath, + flag: _TFlags = "c", + protocol: int | None = None, + writeback: bool = False, + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> Shelf[Any]: ... + +elif sys.version_info >= (3, 11): + def open( + filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False + ) -> Shelf[Any]: ... -def open(filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> Shelf[object]: ... +else: + def open(filename: str, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> Shelf[Any]: ... diff --git a/stdlib/shlex.pyi b/stdlib/shlex.pyi index dfe554b0a773..1c27483782fb 100644 --- a/stdlib/shlex.pyi +++ b/stdlib/shlex.pyi @@ -1,16 +1,33 @@ import sys -from typing import Any, Iterable, TextIO, TypeVar +from collections import deque +from collections.abc import Iterable +from io import TextIOWrapper +from typing import Literal, Protocol, overload, type_check_only +from typing_extensions import Self, deprecated -def split(s: str, comments: bool = ..., posix: bool = ...) -> list[str]: ... +__all__ = ["shlex", "split", "quote", "join"] -if sys.version_info >= (3, 8): - def join(split_command: Iterable[str]) -> str: ... +@type_check_only +class _ShlexInstream(Protocol): + def read(self, size: Literal[1], /) -> str: ... + def readline(self) -> object: ... + def close(self) -> object: ... -def quote(s: str) -> str: ... +if sys.version_info >= (3, 12): + def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ... + +else: + @overload + def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ... + @overload + @deprecated("Passing None for 's' to shlex.split() is deprecated and will raise an error in Python 3.12.") + def split(s: None, comments: bool = False, posix: bool = True) -> list[str]: ... -_SLT = TypeVar("_SLT", bound=shlex) +def join(split_command: Iterable[str]) -> str: ... +def quote(s: str) -> str: ... -class shlex(Iterable[str]): +# TODO: Make generic over infile once PEP 696 is implemented. +class shlex: commenters: str wordchars: str whitespace: str @@ -18,28 +35,29 @@ class shlex(Iterable[str]): quotes: str escapedquotes: str whitespace_split: bool - infile: str - instream: TextIO + infile: str | None + instream: _ShlexInstream source: str debug: int lineno: int token: str - eof: str - punctuation_chars: str + filestack: deque[tuple[str | None, _ShlexInstream, int]] + eof: str | None + @property + def punctuation_chars(self) -> str: ... def __init__( self, - instream: str | TextIO | None = ..., - infile: str | None = ..., - posix: bool = ..., - punctuation_chars: bool | str = ..., + instream: str | _ShlexInstream | None = None, + infile: str | None = None, + posix: bool = False, + punctuation_chars: bool | str = False, ) -> None: ... - def get_token(self) -> str: ... + def get_token(self) -> str | None: ... def push_token(self, tok: str) -> None: ... - def read_token(self) -> str: ... - def sourcehook(self, newfile: str) -> tuple[str, TextIO]: ... - # TODO argument types - def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... + def read_token(self) -> str | None: ... + def sourcehook(self, newfile: str) -> tuple[str, TextIOWrapper] | None: ... + def push_source(self, newstream: str | _ShlexInstream, newfile: str | None = None) -> None: ... def pop_source(self) -> None: ... - def error_leader(self, infile: str | None = ..., lineno: int | None = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... + def error_leader(self, infile: str | None = None, lineno: int | None = None) -> str: ... + def __iter__(self) -> Self: ... def __next__(self) -> str: ... diff --git a/stdlib/shutil.pyi b/stdlib/shutil.pyi index f4c492caccaf..920157948ada 100644 --- a/stdlib/shutil.pyi +++ b/stdlib/shutil.pyi @@ -1,107 +1,243 @@ import os import sys -from _typeshed import StrOrBytesPath, StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, Union, overload - -_PathT = TypeVar("_PathT", str, os.PathLike[str]) -# Return value of some functions that may either return a path-like object that was passed in or -# a string -_PathReturn = Any +from _typeshed import BytesPath, ExcInfo, FileDescriptorOrPath, MaybeNone, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Sequence +from tarfile import _TarfileFilter +from typing import Any, AnyStr, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated + +__all__ = [ + "copyfileobj", + "copyfile", + "copymode", + "copystat", + "copy", + "copy2", + "copytree", + "move", + "rmtree", + "Error", + "SpecialFileError", + "make_archive", + "get_archive_formats", + "register_archive_format", + "unregister_archive_format", + "get_unpack_formats", + "register_unpack_format", + "unregister_unpack_format", + "unpack_archive", + "ignore_patterns", + "chown", + "which", + "get_terminal_size", + "SameFileError", + "disk_usage", +] +if sys.version_info < (3, 14): + __all__ += ["ExecError"] + +_StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath) +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) class Error(OSError): ... class SameFileError(Error): ... class SpecialFileError(OSError): ... -class ExecError(OSError): ... -class ReadError(OSError): ... -class RegistryError(Exception): ... - -def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... -def copyfile(src: StrPath, dst: _PathT, *, follow_symlinks: bool = ...) -> _PathT: ... -def copymode(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... -def copystat(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... -def copy(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... -def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... -def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... -if sys.version_info >= (3, 8): - def copytree( - src: StrPath, - dst: StrPath, - symlinks: bool = ..., - ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = ..., - copy_function: Callable[[str, str], None] = ..., - ignore_dangling_symlinks: bool = ..., - dirs_exist_ok: bool = ..., - ) -> _PathReturn: ... +if sys.version_info >= (3, 14): + ExecError = RuntimeError # Deprecated in Python 3.14; removal scheduled for Python 3.16 else: - def copytree( - src: StrPath, - dst: StrPath, - symlinks: bool = ..., - ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = ..., - copy_function: Callable[[str, str], None] = ..., - ignore_dangling_symlinks: bool = ..., - ) -> _PathReturn: ... + class ExecError(OSError): ... -def rmtree(path: bytes | StrPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... +class ReadError(OSError): ... +class RegistryError(Exception): ... -_CopyFn = Union[Callable[[str, str], None], Callable[[StrPath, StrPath], None]] +def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 0) -> None: ... +def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = True) -> _StrOrBytesPathT: ... +def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... +def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... -if sys.version_info >= (3, 9): - def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... +@overload +def copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... +@overload +def copy(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... -else: - # See https://bugs.python.org/issue32689 - def move(src: str, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... +@overload +def copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... +@overload +def copy2(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... + +def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... +def copytree( + src: StrPath, + dst: _StrPathT, + symlinks: bool = False, + ignore: Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] | None = None, + copy_function: Callable[[str, str], object] = ..., + ignore_dangling_symlinks: bool = False, + dirs_exist_ok: bool = False, +) -> _StrPathT: ... + +_OnErrorCallback: TypeAlias = Callable[[Callable[..., Any], str, ExcInfo], object] +_OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object] + +@type_check_only +class _RmtreeType(Protocol): + avoids_symlink_attacks: bool + if sys.version_info >= (3, 12): + @overload + @deprecated("The `onerror` parameter is deprecated. Use `onexc` instead.") + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool, + onerror: _OnErrorCallback | None, + *, + onexc: None = None, + dir_fd: int | None = None, + ) -> None: ... + @overload + @deprecated("The `onerror` parameter is deprecated. Use `onexc` instead.") + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool = False, + *, + onerror: _OnErrorCallback | None, + onexc: None = None, + dir_fd: int | None = None, + ) -> None: ... + @overload + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool = False, + *, + onexc: _OnExcCallback | None = None, + dir_fd: int | None = None, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool = False, + onerror: _OnErrorCallback | None = None, + *, + dir_fd: int | None = None, + ) -> None: ... + + else: + def __call__( + self, path: StrOrBytesPath, ignore_errors: bool = False, onerror: _OnErrorCallback | None = None + ) -> None: ... + +rmtree: _RmtreeType + +_CopyFn: TypeAlias = Callable[[str, str], object] | Callable[[StrPath, StrPath], object] + +# N.B. shutil.move appears to take bytes arguments, however, +# this does not work when dst is (or is within) an existing directory. +# (#6832) +def move(src: StrPath, dst: _StrPathT, copy_function: _CopyFn = ...) -> _StrPathT | str | MaybeNone: ... class _ntuple_diskusage(NamedTuple): total: int used: int free: int -def disk_usage(path: int | StrOrBytesPath) -> _ntuple_diskusage: ... -def chown(path: StrPath, user: str | int | None = ..., group: str | int | None = ...) -> None: ... +def disk_usage(path: FileDescriptorOrPath) -> _ntuple_diskusage: ... -if sys.version_info >= (3, 8): +# While chown can be imported on Windows, it doesn't actually work; +# see https://bugs.python.org/issue33140. We keep it here because it's +# in __all__. +if sys.version_info >= (3, 13): @overload - def which(cmd: StrPath, mode: int = ..., path: StrPath | None = ...) -> str | None: ... + def chown( + path: FileDescriptorOrPath, + user: str | int, + group: None = None, + *, + dir_fd: int | None = None, + follow_symlinks: bool = True, + ) -> None: ... @overload - def which(cmd: bytes, mode: int = ..., path: StrPath | None = ...) -> bytes | None: ... - + def chown( + path: FileDescriptorOrPath, + user: None = None, + *, + group: str | int, + dir_fd: int | None = None, + follow_symlinks: bool = True, + ) -> None: ... + @overload + def chown( + path: FileDescriptorOrPath, user: None, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> None: ... + @overload + def chown( + path: FileDescriptorOrPath, user: str | int, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> None: ... else: - def which(cmd: StrPath, mode: int = ..., path: StrPath | None = ...) -> str | None: ... + @overload + def chown(path: FileDescriptorOrPath, user: str | int, group: None = None) -> None: ... + @overload + def chown(path: FileDescriptorOrPath, user: None = None, *, group: str | int) -> None: ... + @overload + def chown(path: FileDescriptorOrPath, user: None, group: str | int) -> None: ... + @overload + def chown(path: FileDescriptorOrPath, user: str | int, group: str | int) -> None: ... + +if sys.platform == "win32" and sys.version_info < (3, 12): + @overload + @deprecated("On Windows before Python 3.12, using a PathLike as `cmd` would always fail or return `None`.") + def which(cmd: os.PathLike[str], mode: int = 1, path: StrPath | None = None) -> Never: ... + +@overload +def which(cmd: StrPath, mode: int = 1, path: StrPath | None = None) -> str | None: ... +@overload +def which(cmd: bytes, mode: int = 1, path: StrPath | None = None) -> bytes | None: ... def make_archive( base_name: str, format: str, - root_dir: StrPath | None = ..., - base_dir: StrPath | None = ..., + root_dir: StrPath | None = None, + base_dir: StrPath | None = None, verbose: bool = ..., dry_run: bool = ..., - owner: str | None = ..., - group: str | None = ..., - logger: Any | None = ..., + owner: str | None = None, + group: str | None = None, + logger: Any | None = None, ) -> str: ... def get_archive_formats() -> list[tuple[str, str]]: ... + +@overload def register_archive_format( - name: str, - function: Callable[..., Any], - extra_args: Sequence[tuple[str, Any] | list[Any]] | None = ..., - description: str = ..., + name: str, function: Callable[..., object], extra_args: Sequence[tuple[str, Any] | list[Any]], description: str = "" +) -> None: ... +@overload +def register_archive_format( + name: str, function: Callable[[str, str], object], extra_args: None = None, description: str = "" ) -> None: ... -def unregister_archive_format(name: str) -> None: ... - -if sys.version_info >= (3, 7): - def unpack_archive(filename: StrPath, extract_dir: StrPath | None = ..., format: str | None = ...) -> None: ... -else: - # See http://bugs.python.org/issue30218 - def unpack_archive(filename: str, extract_dir: StrPath | None = ..., format: str | None = ...) -> None: ... +def unregister_archive_format(name: str) -> None: ... +def unpack_archive( + filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None +) -> None: ... +@overload def register_unpack_format( - name: str, extensions: list[str], function: Any, extra_args: Sequence[tuple[str, Any]] | None = ..., description: str = ... + name: str, + extensions: list[str], + function: Callable[..., object], + extra_args: Sequence[tuple[str, Any]], + description: str = "", +) -> None: ... +@overload +def register_unpack_format( + name: str, extensions: list[str], function: Callable[[str, str], object], extra_args: None = None, description: str = "" ) -> None: ... + def unregister_unpack_format(name: str) -> None: ... def get_unpack_formats() -> list[tuple[str, list[str], str]]: ... -def get_terminal_size(fallback: tuple[int, int] = ...) -> os.terminal_size: ... +def get_terminal_size(fallback: tuple[int, int] = (80, 24)) -> os.terminal_size: ... diff --git a/stdlib/signal.pyi b/stdlib/signal.pyi index 6c93662fb326..a6a8853671e2 100644 --- a/stdlib/signal.pyi +++ b/stdlib/signal.pyi @@ -1,138 +1,152 @@ import sys from _typeshed import structseq +from collections.abc import Callable, Iterable from enum import IntEnum from types import FrameType -from typing import Any, Callable, Iterable, Optional, Tuple, Union -from typing_extensions import final +from typing import Any, Final, TypeAlias, final +from typing_extensions import Never NSIG: int class Signals(IntEnum): - SIGABRT: int - SIGEMT: int - SIGFPE: int - SIGILL: int - SIGINFO: int - SIGINT: int - SIGSEGV: int - SIGTERM: int + SIGFPE = 8 + SIGILL = 4 + SIGINT = 2 + SIGSEGV = 11 + SIGTERM = 15 if sys.platform == "win32": - SIGBREAK: int - CTRL_C_EVENT: int - CTRL_BREAK_EVENT: int + SIGABRT = 22 + SIGBREAK = 21 + CTRL_C_EVENT = 0 + CTRL_BREAK_EVENT = 1 else: - SIGALRM: int - SIGBUS: int - SIGCHLD: int - SIGCONT: int - SIGHUP: int - SIGIO: int - SIGIOT: int - SIGKILL: int - SIGPIPE: int - SIGPROF: int - SIGQUIT: int - SIGSTOP: int - SIGSYS: int - SIGTRAP: int - SIGTSTP: int - SIGTTIN: int - SIGTTOU: int - SIGURG: int - SIGUSR1: int - SIGUSR2: int - SIGVTALRM: int - SIGWINCH: int - SIGXCPU: int - SIGXFSZ: int + SIGABRT = 6 + SIGALRM = 14 + SIGBUS = 7 + SIGCHLD = 17 + SIGCONT = 18 + SIGHUP = 1 + SIGIO = 29 + SIGIOT = 6 + SIGKILL = 9 + SIGPIPE = 13 + SIGPROF = 27 + SIGQUIT = 3 + SIGSTOP = 19 + SIGSYS = 31 + SIGTRAP = 5 + SIGTSTP = 20 + SIGTTIN = 21 + SIGTTOU = 22 + SIGURG = 23 + SIGUSR1 = 10 + SIGUSR2 = 12 + SIGVTALRM = 26 + SIGWINCH = 28 + SIGXCPU = 24 + SIGXFSZ = 25 + if sys.platform != "linux": + SIGEMT = 7 + SIGINFO = 29 if sys.platform != "darwin": - SIGCLD: int - SIGPOLL: int - SIGPWR: int - SIGRTMAX: int - SIGRTMIN: int + SIGCLD = 17 + SIGPOLL = 29 + SIGPWR = 30 + SIGRTMAX = 64 + SIGRTMIN = 34 + if sys.version_info >= (3, 11): + SIGSTKFLT = 16 class Handlers(IntEnum): - SIG_DFL: int - SIG_IGN: int + SIG_DFL = 0 + SIG_IGN = 1 -SIG_DFL: Handlers -SIG_IGN: Handlers +SIG_DFL: Final = Handlers.SIG_DFL +SIG_IGN: Final = Handlers.SIG_IGN -_SIGNUM = Union[int, Signals] -_HANDLER = Union[Callable[[int, Optional[FrameType]], Any], int, Handlers, None] +_SIGNUM: TypeAlias = int | Signals +_HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None -def default_int_handler(signum: int, frame: FrameType | None) -> None: ... -def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... -def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... +def default_int_handler(signalnum: int, frame: FrameType | None, /) -> Never: ... +def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... +def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... -SIGABRT: Signals -SIGEMT: Signals -SIGFPE: Signals -SIGILL: Signals -SIGINFO: Signals -SIGINT: Signals -SIGSEGV: Signals -SIGTERM: Signals +SIGABRT: Final = Signals.SIGABRT +SIGFPE: Final = Signals.SIGFPE +SIGILL: Final = Signals.SIGILL +SIGINT: Final = Signals.SIGINT +SIGSEGV: Final = Signals.SIGSEGV +SIGTERM: Final = Signals.SIGTERM if sys.platform == "win32": - SIGBREAK: Signals - CTRL_C_EVENT: Signals - CTRL_BREAK_EVENT: Signals + SIGBREAK: Final = Signals.SIGBREAK + CTRL_C_EVENT: Final = Signals.CTRL_C_EVENT + CTRL_BREAK_EVENT: Final = Signals.CTRL_BREAK_EVENT else: - SIGALRM: Signals - SIGBUS: Signals - SIGCHLD: Signals - SIGCONT: Signals - SIGHUP: Signals - SIGIO: Signals - SIGIOT: Signals - SIGKILL: Signals - SIGPIPE: Signals - SIGPROF: Signals - SIGQUIT: Signals - SIGSTOP: Signals - SIGSYS: Signals - SIGTRAP: Signals - SIGTSTP: Signals - SIGTTIN: Signals - SIGTTOU: Signals - SIGURG: Signals - SIGUSR1: Signals - SIGUSR2: Signals - SIGVTALRM: Signals - SIGWINCH: Signals - SIGXCPU: Signals - SIGXFSZ: Signals - class ItimerError(IOError): ... + if sys.platform != "linux": + SIGINFO: Final = Signals.SIGINFO + SIGEMT: Final = Signals.SIGEMT + SIGALRM: Final = Signals.SIGALRM + SIGBUS: Final = Signals.SIGBUS + SIGCHLD: Final = Signals.SIGCHLD + SIGCONT: Final = Signals.SIGCONT + SIGHUP: Final = Signals.SIGHUP + SIGIO: Final = Signals.SIGIO + SIGIOT: Final = Signals.SIGABRT # alias + SIGKILL: Final = Signals.SIGKILL + SIGPIPE: Final = Signals.SIGPIPE + SIGPROF: Final = Signals.SIGPROF + SIGQUIT: Final = Signals.SIGQUIT + SIGSTOP: Final = Signals.SIGSTOP + SIGSYS: Final = Signals.SIGSYS + SIGTRAP: Final = Signals.SIGTRAP + SIGTSTP: Final = Signals.SIGTSTP + SIGTTIN: Final = Signals.SIGTTIN + SIGTTOU: Final = Signals.SIGTTOU + SIGURG: Final = Signals.SIGURG + SIGUSR1: Final = Signals.SIGUSR1 + SIGUSR2: Final = Signals.SIGUSR2 + SIGVTALRM: Final = Signals.SIGVTALRM + SIGWINCH: Final = Signals.SIGWINCH + SIGXCPU: Final = Signals.SIGXCPU + SIGXFSZ: Final = Signals.SIGXFSZ + + class ItimerError(OSError): ... ITIMER_PROF: int ITIMER_REAL: int ITIMER_VIRTUAL: int + class Sigmasks(IntEnum): - SIG_BLOCK: int - SIG_UNBLOCK: int - SIG_SETMASK: int - SIG_BLOCK = Sigmasks.SIG_BLOCK - SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK - SIG_SETMASK = Sigmasks.SIG_SETMASK - def alarm(__seconds: int) -> int: ... - def getitimer(__which: int) -> tuple[float, float]: ... + SIG_BLOCK = 0 + SIG_UNBLOCK = 1 + SIG_SETMASK = 2 + + SIG_BLOCK: Final = Sigmasks.SIG_BLOCK + SIG_UNBLOCK: Final = Sigmasks.SIG_UNBLOCK + SIG_SETMASK: Final = Sigmasks.SIG_SETMASK + def alarm(seconds: int, /) -> int: ... + def getitimer(which: int, /) -> tuple[float, float]: ... def pause() -> None: ... - def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... - def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... - def setitimer(__which: int, __seconds: float, __interval: float = ...) -> tuple[float, float]: ... - def siginterrupt(__signalnum: int, __flag: bool) -> None: ... + def pthread_kill(thread_id: int, signalnum: int, /) -> None: ... + def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ... + def setitimer(which: int, seconds: float, interval: float = 0.0, /) -> tuple[float, float]: ... + def siginterrupt(signalnum: int, flag: bool, /) -> None: ... def sigpending() -> Any: ... - def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... + def sigwait(sigset: Iterable[int]) -> _SIGNUM: ... if sys.platform != "darwin": - SIGCLD: Signals - SIGPOLL: Signals - SIGPWR: Signals - SIGRTMAX: Signals - SIGRTMIN: Signals + SIGCLD: Final = Signals.SIGCHLD # alias + SIGPOLL: Final = Signals.SIGIO # alias + SIGPWR: Final = Signals.SIGPWR + SIGRTMAX: Final = Signals.SIGRTMAX + SIGRTMIN: Final = Signals.SIGRTMIN + if sys.version_info >= (3, 11): + SIGSTKFLT: Final = Signals.SIGSTKFLT + @final - class struct_siginfo(structseq[int], Tuple[int, int, int, int, int, int, int]): + class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): + __match_args__: Final = ("si_signo", "si_code", "si_errno", "si_pid", "si_uid", "si_status", "si_band") + @property def si_signo(self) -> int: ... @property @@ -147,16 +161,14 @@ else: def si_status(self) -> int: ... @property def si_band(self) -> int: ... - def sigtimedwait(sigset: Iterable[int], timeout: float) -> struct_siginfo | None: ... - def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... -if sys.version_info >= (3, 8): - def strsignal(__signalnum: _SIGNUM) -> str | None: ... - def valid_signals() -> set[Signals]: ... - def raise_signal(__signalnum: _SIGNUM) -> None: ... + def sigtimedwait(sigset: Iterable[int], timeout: float, /) -> struct_siginfo | None: ... + def sigwaitinfo(sigset: Iterable[int], /) -> struct_siginfo: ... -if sys.version_info >= (3, 7): - def set_wakeup_fd(fd: int, *, warn_on_full_buffer: bool = ...) -> int: ... +def strsignal(signalnum: _SIGNUM, /) -> str | None: ... +def valid_signals() -> set[Signals]: ... +def raise_signal(signalnum: _SIGNUM, /) -> None: ... +def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = True) -> int: ... -else: - def set_wakeup_fd(fd: int) -> int: ... +if sys.platform == "linux": + def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = 0, /) -> None: ... diff --git a/stdlib/site.pyi b/stdlib/site.pyi index a73d188a7e5c..b6e0ec8fd934 100644 --- a/stdlib/site.pyi +++ b/stdlib/site.pyi @@ -1,5 +1,6 @@ +import sys from _typeshed import StrPath -from typing import Iterable +from collections.abc import Iterable PREFIXES: list[str] ENABLE_USER_SITE: bool | None @@ -9,14 +10,32 @@ USER_BASE: str | None def main() -> None: ... def abs_paths() -> None: ... # undocumented def addpackage(sitedir: StrPath, name: StrPath, known_paths: set[str] | None) -> set[str] | None: ... # undocumented -def addsitedir(sitedir: str, known_paths: set[str] | None = ...) -> None: ... -def addsitepackages(known_paths: set[str] | None, prefixes: Iterable[str] | None = ...) -> set[str] | None: ... # undocumented -def addusersitepackages(known_paths: set[str] | None) -> set[str] | None: ... # undocumented + +if sys.version_info >= (3, 15): + class StartupState: + __slots__ = ("_known_paths", "_processed_sitedirs", "_path_entries", "_importexecs", "_entrypoints") + def __init__(self, known_paths: set[str] | None = None) -> None: ... + def addsitedir(self, sitedir: str) -> None: ... + def addusersitepackages(self) -> None: ... + def addsitepackages(self, prefixes: Iterable[str] | None = None) -> None: ... + def process(self) -> None: ... + +def addsitedir(sitedir: str, known_paths: set[str] | None = None) -> None: ... +def addsitepackages(known_paths: set[str], prefixes: Iterable[str] | None = None) -> set[str]: ... # undocumented +def addusersitepackages(known_paths: set[str]) -> set[str]: ... # undocumented def check_enableusersite() -> bool | None: ... # undocumented + +if sys.version_info >= (3, 13): + def gethistoryfile() -> str: ... # undocumented + def enablerlcompleter() -> None: ... # undocumented + +if sys.version_info >= (3, 13): + def register_readline() -> None: ... # undocumented + def execsitecustomize() -> None: ... # undocumented def execusercustomize() -> None: ... # undocumented -def getsitepackages(prefixes: Iterable[str] | None = ...) -> list[str]: ... +def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: ... def getuserbase() -> str: ... def getusersitepackages() -> str: ... def makepath(*paths: StrPath) -> tuple[str, str]: ... # undocumented diff --git a/stdlib/smtpd.pyi b/stdlib/smtpd.pyi index ef0ada2c72de..cc9ac391a441 100644 --- a/stdlib/smtpd.pyi +++ b/stdlib/smtpd.pyi @@ -1,10 +1,17 @@ import asynchat import asyncore import socket +import sys from collections import defaultdict -from typing import Any, Tuple, Type +from typing import Any, TypeAlias +from typing_extensions import deprecated -_Address = Tuple[str, int] # (host, port) +if sys.version_info >= (3, 11): + __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy"] +else: + __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy", "MailmanProxy"] + +_Address: TypeAlias = tuple[str, int] # (host, port) class SMTPChannel(asynchat.async_chat): COMMAND: int @@ -34,10 +41,10 @@ class SMTPChannel(asynchat.async_chat): server: SMTPServer, conn: socket.socket, addr: Any, - data_size_limit: int = ..., - map: asyncore._maptype | None = ..., - enable_SMTPUTF8: bool = ..., - decode_data: bool = ..., + data_size_limit: int = 33554432, + map: asyncore._MapType | None = None, + enable_SMTPUTF8: bool = False, + decode_data: bool = False, ) -> None: ... # base asynchat.async_chat.push() accepts bytes def push(self, msg: str) -> None: ... # type: ignore[override] @@ -56,7 +63,7 @@ class SMTPChannel(asynchat.async_chat): def smtp_EXPN(self, arg: str) -> None: ... class SMTPServer(asyncore.dispatcher): - channel_class: Type[SMTPChannel] + channel_class: type[SMTPChannel] data_size_limit: int enable_SMTPUTF8: bool @@ -64,10 +71,10 @@ class SMTPServer(asyncore.dispatcher): self, localaddr: _Address, remoteaddr: _Address, - data_size_limit: int = ..., - map: asyncore._maptype | None = ..., - enable_SMTPUTF8: bool = ..., - decode_data: bool = ..., + data_size_limit: int = 33554432, + map: asyncore._MapType | None = None, + enable_SMTPUTF8: bool = False, + decode_data: bool = False, ) -> None: ... def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... def process_message( @@ -79,5 +86,7 @@ class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] -class MailmanProxy(PureProxy): - def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + class MailmanProxy(PureProxy): + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] diff --git a/stdlib/smtplib.pyi b/stdlib/smtplib.pyi index a6f7d07ee7ec..1aaa5b49664b 100644 --- a/stdlib/smtplib.pyi +++ b/stdlib/smtplib.pyi @@ -1,22 +1,41 @@ import sys -from _typeshed import Self +from _socket import _Address as _SourceAddress +from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath +from collections.abc import Sequence from email.message import Message as _Message +from re import Pattern from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Dict, Pattern, Protocol, Sequence, Tuple, Type, Union, overload +from typing import Any, Final, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated -_Reply = Tuple[int, bytes] -_SendErrs = Dict[str, _Reply] -# Should match source_address for socket.create_connection -_SourceAddress = Tuple[Union[bytearray, bytes, str], int] +__all__ = [ + "SMTPException", + "SMTPServerDisconnected", + "SMTPResponseException", + "SMTPSenderRefused", + "SMTPRecipientsRefused", + "SMTPDataError", + "SMTPConnectError", + "SMTPHeloError", + "SMTPAuthenticationError", + "quoteaddr", + "quotedata", + "SMTP", + "SMTP_SSL", + "SMTPNotSupportedError", +] -SMTP_PORT: int -SMTP_SSL_PORT: int -CRLF: str -bCRLF: bytes +_Reply: TypeAlias = tuple[int, bytes] +_SendErrs: TypeAlias = dict[str, _Reply] -OLDSTYLE_AUTH: Pattern[str] +SMTP_PORT: Final = 25 +SMTP_SSL_PORT: Final = 465 +CRLF: Final[str] +bCRLF: Final[bytes] + +OLDSTYLE_AUTH: Final[Pattern[str]] class SMTPException(OSError): ... class SMTPNotSupportedError(SMTPException): ... @@ -29,7 +48,6 @@ class SMTPResponseException(SMTPException): def __init__(self, code: int, msg: bytes | str) -> None: ... class SMTPSenderRefused(SMTPResponseException): - smtp_code: int smtp_error: bytes sender: str args: tuple[int, bytes, str] @@ -48,11 +66,12 @@ class SMTPAuthenticationError(SMTPResponseException): ... def quoteaddr(addrstring: str) -> str: ... def quotedata(data: str) -> str: ... +@type_check_only class _AuthObject(Protocol): @overload - def __call__(self, challenge: None = ...) -> str | None: ... + def __call__(self, challenge: None = None, /) -> str | None: ... @overload - def __call__(self, challenge: bytes) -> str: ... + def __call__(self, challenge: bytes, /) -> str: ... class SMTP: debuglevel: int @@ -71,95 +90,134 @@ class SMTP: local_hostname: str def __init__( self, - host: str = ..., - port: int = ..., - local_hostname: str | None = ..., + host: str = "", + port: int = 0, + local_hostname: str | None = None, timeout: float = ..., - source_address: _SourceAddress | None = ..., + source_address: _SourceAddress | None = None, ) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: ... - def connect(self, host: str = ..., port: int = ..., source_address: _SourceAddress | None = ...) -> _Reply: ... - def send(self, s: bytes | str) -> None: ... - def putcmd(self, cmd: str, args: str = ...) -> None: ... + def connect(self, host: str = "localhost", port: int = 0, source_address: _SourceAddress | None = None) -> _Reply: ... + def send(self, s: ReadableBuffer | str) -> None: ... + def putcmd(self, cmd: str, args: str = "") -> None: ... def getreply(self) -> _Reply: ... - def docmd(self, cmd: str, args: str = ...) -> _Reply: ... - def helo(self, name: str = ...) -> _Reply: ... - def ehlo(self, name: str = ...) -> _Reply: ... + def docmd(self, cmd: str, args: str = "") -> _Reply: ... + def helo(self, name: str = "") -> _Reply: ... + def ehlo(self, name: str = "") -> _Reply: ... def has_extn(self, opt: str) -> bool: ... - def help(self, args: str = ...) -> bytes: ... + def help(self, args: str = "") -> bytes: ... def rset(self) -> _Reply: ... def noop(self) -> _Reply: ... - def mail(self, sender: str, options: Sequence[str] = ...) -> _Reply: ... - def rcpt(self, recip: str, options: Sequence[str] = ...) -> _Reply: ... - def data(self, msg: bytes | str) -> _Reply: ... + def mail(self, sender: str, options: Sequence[str] = ()) -> _Reply: ... + def rcpt(self, recip: str, options: Sequence[str] = ()) -> _Reply: ... + def data(self, msg: ReadableBuffer | str) -> _Reply: ... def verify(self, address: str) -> _Reply: ... vrfy = verify def expn(self, address: str) -> _Reply: ... def ehlo_or_helo_if_needed(self) -> None: ... user: str password: str - def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = ...) -> _Reply: ... + def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = True) -> _Reply: ... + @overload - def auth_cram_md5(self, challenge: None = ...) -> None: ... + def auth_cram_md5(self, challenge: None = None) -> None: ... @overload - def auth_cram_md5(self, challenge: bytes) -> str: ... - def auth_plain(self, challenge: bytes | None = ...) -> str: ... - def auth_login(self, challenge: bytes | None = ...) -> str: ... - def login(self, user: str, password: str, *, initial_response_ok: bool = ...) -> _Reply: ... - def starttls(self, keyfile: str | None = ..., certfile: str | None = ..., context: SSLContext | None = ...) -> _Reply: ... + def auth_cram_md5(self, challenge: ReadableBuffer) -> str: ... + + def auth_plain(self, challenge: ReadableBuffer | None = None) -> str: ... + def auth_login(self, challenge: ReadableBuffer | None = None) -> str: ... + def login(self, user: str, password: str, *, initial_response_ok: bool = True) -> _Reply: ... + if sys.version_info >= (3, 12): + def starttls(self, *, context: SSLContext | None = None) -> _Reply: ... + else: + @overload + def starttls(self, keyfile: None = None, certfile: None = None, context: SSLContext | None = None) -> _Reply: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def starttls( + self, keyfile: StrOrBytesPath | None = None, certfile: StrOrBytesPath | None = None, context: None = None + ) -> _Reply: ... + def sendmail( self, from_addr: str, to_addrs: str | Sequence[str], - msg: bytes | str, - mail_options: Sequence[str] = ..., - rcpt_options: Sequence[str] = ..., + msg: SizedBuffer | str, + mail_options: Sequence[str] = (), + rcpt_options: Sequence[str] = (), ) -> _SendErrs: ... def send_message( self, msg: _Message, - from_addr: str | None = ..., - to_addrs: str | Sequence[str] | None = ..., - mail_options: Sequence[str] = ..., - rcpt_options: Sequence[str] = ..., + from_addr: str | None = None, + to_addrs: str | Sequence[str] | None = None, + mail_options: Sequence[str] = (), + rcpt_options: Sequence[str] = (), ) -> _SendErrs: ... def close(self) -> None: ... def quit(self) -> _Reply: ... class SMTP_SSL(SMTP): - default_port: int - keyfile: str | None - certfile: str | None context: SSLContext - def __init__( - self, - host: str = ..., - port: int = ..., - local_hostname: str | None = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - timeout: float = ..., - source_address: _SourceAddress | None = ..., - context: SSLContext | None = ..., - ) -> None: ... - -LMTP_PORT: int - -class LMTP(SMTP): - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 12): def __init__( self, - host: str = ..., - port: int = ..., - local_hostname: str | None = ..., - source_address: _SourceAddress | None = ..., + host: str = "", + port: int = 0, + local_hostname: str | None = None, + *, timeout: float = ..., + source_address: _SourceAddress | None = None, + context: SSLContext | None = None, ) -> None: ... else: + @overload def __init__( - self, host: str = ..., port: int = ..., local_hostname: str | None = ..., source_address: _SourceAddress | None = ... + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + keyfile: None = None, + certfile: None = None, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: SSLContext | None = None, ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: None = None, + ) -> None: ... + + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None + +LMTP_PORT: Final = 2003 + +class LMTP(SMTP): + def __init__( + self, + host: str = "", + port: int = 2003, + local_hostname: str | None = None, + source_address: _SourceAddress | None = None, + timeout: float = ..., + ) -> None: ... diff --git a/stdlib/sndhdr.pyi b/stdlib/sndhdr.pyi index 84d6441a83b1..f4d487607fbb 100644 --- a/stdlib/sndhdr.pyi +++ b/stdlib/sndhdr.pyi @@ -1,6 +1,8 @@ from _typeshed import StrOrBytesPath from typing import NamedTuple +__all__ = ["what", "whathdr"] + class SndHeaders(NamedTuple): filetype: str framerate: int diff --git a/stdlib/socket.pyi b/stdlib/socket.pyi index 430fef4ff344..4731aeab82c1 100644 --- a/stdlib/socket.pyi +++ b/stdlib/socket.pyi @@ -1,34 +1,19 @@ -import sys -from _typeshed import ReadableBuffer, Self, WriteableBuffer -from collections.abc import Iterable -from enum import IntEnum, IntFlag -from io import RawIOBase -from typing import Any, BinaryIO, TextIO, TypeVar, overload -from typing_extensions import Literal - # Ideally, we'd just do "from _socket import *". Unfortunately, socket # overrides some definitions from _socket incompatibly. mypy incorrectly # prefers the definitions from _socket over those defined here. import _socket +import sys from _socket import ( - _FD, - CMSG_LEN as CMSG_LEN, - CMSG_SPACE as CMSG_SPACE, - EAI_ADDRFAMILY as EAI_ADDRFAMILY, + CAPI as CAPI, EAI_AGAIN as EAI_AGAIN, EAI_BADFLAGS as EAI_BADFLAGS, - EAI_BADHINTS as EAI_BADHINTS, EAI_FAIL as EAI_FAIL, EAI_FAMILY as EAI_FAMILY, - EAI_MAX as EAI_MAX, EAI_MEMORY as EAI_MEMORY, EAI_NODATA as EAI_NODATA, EAI_NONAME as EAI_NONAME, - EAI_OVERFLOW as EAI_OVERFLOW, - EAI_PROTOCOL as EAI_PROTOCOL, EAI_SERVICE as EAI_SERVICE, EAI_SOCKTYPE as EAI_SOCKTYPE, - EAI_SYSTEM as EAI_SYSTEM, INADDR_ALLHOSTS_GROUP as INADDR_ALLHOSTS_GROUP, INADDR_ANY as INADDR_ANY, INADDR_BROADCAST as INADDR_BROADCAST, @@ -37,62 +22,39 @@ from _socket import ( INADDR_NONE as INADDR_NONE, INADDR_UNSPEC_GROUP as INADDR_UNSPEC_GROUP, IP_ADD_MEMBERSHIP as IP_ADD_MEMBERSHIP, - IP_DEFAULT_MULTICAST_LOOP as IP_DEFAULT_MULTICAST_LOOP, - IP_DEFAULT_MULTICAST_TTL as IP_DEFAULT_MULTICAST_TTL, IP_DROP_MEMBERSHIP as IP_DROP_MEMBERSHIP, IP_HDRINCL as IP_HDRINCL, - IP_MAX_MEMBERSHIPS as IP_MAX_MEMBERSHIPS, IP_MULTICAST_IF as IP_MULTICAST_IF, IP_MULTICAST_LOOP as IP_MULTICAST_LOOP, IP_MULTICAST_TTL as IP_MULTICAST_TTL, IP_OPTIONS as IP_OPTIONS, - IP_RECVDSTADDR as IP_RECVDSTADDR, - IP_RECVOPTS as IP_RECVOPTS, - IP_RECVRETOPTS as IP_RECVRETOPTS, - IP_RETOPTS as IP_RETOPTS, + IP_RECVTOS as IP_RECVTOS, IP_TOS as IP_TOS, - IP_TRANSPARENT as IP_TRANSPARENT, IP_TTL as IP_TTL, IPPORT_RESERVED as IPPORT_RESERVED, IPPORT_USERRESERVED as IPPORT_USERRESERVED, IPPROTO_AH as IPPROTO_AH, - IPPROTO_BIP as IPPROTO_BIP, IPPROTO_DSTOPTS as IPPROTO_DSTOPTS, IPPROTO_EGP as IPPROTO_EGP, - IPPROTO_EON as IPPROTO_EON, IPPROTO_ESP as IPPROTO_ESP, IPPROTO_FRAGMENT as IPPROTO_FRAGMENT, - IPPROTO_GGP as IPPROTO_GGP, - IPPROTO_GRE as IPPROTO_GRE, - IPPROTO_HELLO as IPPROTO_HELLO, IPPROTO_HOPOPTS as IPPROTO_HOPOPTS, IPPROTO_ICMP as IPPROTO_ICMP, IPPROTO_ICMPV6 as IPPROTO_ICMPV6, IPPROTO_IDP as IPPROTO_IDP, IPPROTO_IGMP as IPPROTO_IGMP, IPPROTO_IP as IPPROTO_IP, - IPPROTO_IPCOMP as IPPROTO_IPCOMP, - IPPROTO_IPIP as IPPROTO_IPIP, - IPPROTO_IPV4 as IPPROTO_IPV4, IPPROTO_IPV6 as IPPROTO_IPV6, - IPPROTO_MAX as IPPROTO_MAX, - IPPROTO_MOBILE as IPPROTO_MOBILE, - IPPROTO_ND as IPPROTO_ND, IPPROTO_NONE as IPPROTO_NONE, IPPROTO_PIM as IPPROTO_PIM, IPPROTO_PUP as IPPROTO_PUP, IPPROTO_RAW as IPPROTO_RAW, IPPROTO_ROUTING as IPPROTO_ROUTING, - IPPROTO_RSVP as IPPROTO_RSVP, IPPROTO_SCTP as IPPROTO_SCTP, IPPROTO_TCP as IPPROTO_TCP, - IPPROTO_TP as IPPROTO_TP, IPPROTO_UDP as IPPROTO_UDP, - IPPROTO_VRRP as IPPROTO_VRRP, - IPPROTO_XTP as IPPROTO_XTP, IPV6_CHECKSUM as IPV6_CHECKSUM, IPV6_DONTFRAG as IPV6_DONTFRAG, - IPV6_DSTOPTS as IPV6_DSTOPTS, IPV6_HOPLIMIT as IPV6_HOPLIMIT, IPV6_HOPOPTS as IPV6_HOPOPTS, IPV6_JOIN_GROUP as IPV6_JOIN_GROUP, @@ -100,25 +62,13 @@ from _socket import ( IPV6_MULTICAST_HOPS as IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF as IPV6_MULTICAST_IF, IPV6_MULTICAST_LOOP as IPV6_MULTICAST_LOOP, - IPV6_NEXTHOP as IPV6_NEXTHOP, - IPV6_PATHMTU as IPV6_PATHMTU, IPV6_PKTINFO as IPV6_PKTINFO, - IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS, - IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT, - IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS, - IPV6_RECVPATHMTU as IPV6_RECVPATHMTU, - IPV6_RECVPKTINFO as IPV6_RECVPKTINFO, IPV6_RECVRTHDR as IPV6_RECVRTHDR, IPV6_RECVTCLASS as IPV6_RECVTCLASS, IPV6_RTHDR as IPV6_RTHDR, - IPV6_RTHDR_TYPE_0 as IPV6_RTHDR_TYPE_0, - IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS, IPV6_TCLASS as IPV6_TCLASS, IPV6_UNICAST_HOPS as IPV6_UNICAST_HOPS, - IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU, IPV6_V6ONLY as IPV6_V6ONLY, - IPX_TYPE as IPX_TYPE, - LOCAL_PEERCRED as LOCAL_PEERCRED, NI_DGRAM as NI_DGRAM, NI_MAXHOST as NI_MAXHOST, NI_MAXSERV as NI_MAXSERV, @@ -126,67 +76,40 @@ from _socket import ( NI_NOFQDN as NI_NOFQDN, NI_NUMERICHOST as NI_NUMERICHOST, NI_NUMERICSERV as NI_NUMERICSERV, - SCM_CREDENTIALS as SCM_CREDENTIALS, - SCM_CREDS as SCM_CREDS, - SCM_RIGHTS as SCM_RIGHTS, SHUT_RD as SHUT_RD, SHUT_RDWR as SHUT_RDWR, SHUT_WR as SHUT_WR, SO_ACCEPTCONN as SO_ACCEPTCONN, - SO_BINDTODEVICE as SO_BINDTODEVICE, SO_BROADCAST as SO_BROADCAST, SO_DEBUG as SO_DEBUG, SO_DONTROUTE as SO_DONTROUTE, SO_ERROR as SO_ERROR, - SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE, SO_KEEPALIVE as SO_KEEPALIVE, SO_LINGER as SO_LINGER, - SO_MARK as SO_MARK, SO_OOBINLINE as SO_OOBINLINE, - SO_PASSCRED as SO_PASSCRED, - SO_PEERCRED as SO_PEERCRED, - SO_PRIORITY as SO_PRIORITY, SO_RCVBUF as SO_RCVBUF, SO_RCVLOWAT as SO_RCVLOWAT, SO_RCVTIMEO as SO_RCVTIMEO, SO_REUSEADDR as SO_REUSEADDR, - SO_REUSEPORT as SO_REUSEPORT, - SO_SETFIB as SO_SETFIB, SO_SNDBUF as SO_SNDBUF, SO_SNDLOWAT as SO_SNDLOWAT, SO_SNDTIMEO as SO_SNDTIMEO, SO_TYPE as SO_TYPE, - SO_USELOOPBACK as SO_USELOOPBACK, - SOL_ATALK as SOL_ATALK, - SOL_AX25 as SOL_AX25, - SOL_HCI as SOL_HCI, SOL_IP as SOL_IP, - SOL_IPX as SOL_IPX, - SOL_NETROM as SOL_NETROM, - SOL_ROSE as SOL_ROSE, SOL_SOCKET as SOL_SOCKET, SOL_TCP as SOL_TCP, SOL_UDP as SOL_UDP, SOMAXCONN as SOMAXCONN, - TCP_CORK as TCP_CORK, - TCP_DEFER_ACCEPT as TCP_DEFER_ACCEPT, TCP_FASTOPEN as TCP_FASTOPEN, - TCP_INFO as TCP_INFO, TCP_KEEPCNT as TCP_KEEPCNT, - TCP_KEEPIDLE as TCP_KEEPIDLE, TCP_KEEPINTVL as TCP_KEEPINTVL, - TCP_LINGER2 as TCP_LINGER2, TCP_MAXSEG as TCP_MAXSEG, TCP_NODELAY as TCP_NODELAY, - TCP_QUICKACK as TCP_QUICKACK, - TCP_SYNCNT as TCP_SYNCNT, - TCP_WINDOW_CLAMP as TCP_WINDOW_CLAMP, SocketType as SocketType, _Address as _Address, _RetAddress as _RetAddress, + close as close, dup as dup, - error as error, - gaierror as gaierror, getdefaulttimeout as getdefaulttimeout, gethostbyaddr as gethostbyaddr, gethostbyname as gethostbyname, @@ -197,9 +120,11 @@ from _socket import ( getservbyname as getservbyname, getservbyport as getservbyport, has_ipv6 as has_ipv6, - herror as herror, htonl as htonl, htons as htons, + if_indextoname as if_indextoname, + if_nameindex as if_nameindex, + if_nametoindex as if_nametoindex, inet_aton as inet_aton, inet_ntoa as inet_ntoa, inet_ntop as inet_ntop, @@ -207,15 +132,406 @@ from _socket import ( ntohl as ntohl, ntohs as ntohs, setdefaulttimeout as setdefaulttimeout, - timeout as timeout, ) +from _typeshed import ReadableBuffer, Unused, WriteableBuffer +from collections.abc import Iterable +from enum import IntEnum, IntFlag +from io import BufferedReader, BufferedRWPair, BufferedWriter, IOBase, RawIOBase, TextIOWrapper +from typing import Any, Final, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self + +__all__ = [ + "fromfd", + "getfqdn", + "create_connection", + "create_server", + "has_dualstack_ipv6", + "AddressFamily", + "SocketKind", + "AF_APPLETALK", + "AF_DECnet", + "AF_INET", + "AF_INET6", + "AF_IPX", + "AF_SNA", + "AF_UNSPEC", + "AI_ADDRCONFIG", + "AI_ALL", + "AI_CANONNAME", + "AI_NUMERICHOST", + "AI_NUMERICSERV", + "AI_PASSIVE", + "AI_V4MAPPED", + "CAPI", + "EAI_AGAIN", + "EAI_BADFLAGS", + "EAI_FAIL", + "EAI_FAMILY", + "EAI_MEMORY", + "EAI_NODATA", + "EAI_NONAME", + "EAI_SERVICE", + "EAI_SOCKTYPE", + "INADDR_ALLHOSTS_GROUP", + "INADDR_ANY", + "INADDR_BROADCAST", + "INADDR_LOOPBACK", + "INADDR_MAX_LOCAL_GROUP", + "INADDR_NONE", + "INADDR_UNSPEC_GROUP", + "IPPORT_RESERVED", + "IPPORT_USERRESERVED", + "IPPROTO_AH", + "IPPROTO_DSTOPTS", + "IPPROTO_EGP", + "IPPROTO_ESP", + "IPPROTO_FRAGMENT", + "IPPROTO_HOPOPTS", + "IPPROTO_ICMP", + "IPPROTO_ICMPV6", + "IPPROTO_IDP", + "IPPROTO_IGMP", + "IPPROTO_IP", + "IPPROTO_IPV6", + "IPPROTO_NONE", + "IPPROTO_PIM", + "IPPROTO_PUP", + "IPPROTO_RAW", + "IPPROTO_ROUTING", + "IPPROTO_SCTP", + "IPPROTO_TCP", + "IPPROTO_UDP", + "IPV6_CHECKSUM", + "IPV6_DONTFRAG", + "IPV6_HOPLIMIT", + "IPV6_HOPOPTS", + "IPV6_JOIN_GROUP", + "IPV6_LEAVE_GROUP", + "IPV6_MULTICAST_HOPS", + "IPV6_MULTICAST_IF", + "IPV6_MULTICAST_LOOP", + "IPV6_PKTINFO", + "IPV6_RECVRTHDR", + "IPV6_RECVTCLASS", + "IPV6_RTHDR", + "IPV6_TCLASS", + "IPV6_UNICAST_HOPS", + "IPV6_V6ONLY", + "IP_ADD_MEMBERSHIP", + "IP_DROP_MEMBERSHIP", + "IP_HDRINCL", + "IP_MULTICAST_IF", + "IP_MULTICAST_LOOP", + "IP_MULTICAST_TTL", + "IP_OPTIONS", + "IP_RECVTOS", + "IP_TOS", + "IP_TTL", + "MSG_CTRUNC", + "MSG_DONTROUTE", + "MSG_OOB", + "MSG_PEEK", + "MSG_TRUNC", + "MSG_WAITALL", + "NI_DGRAM", + "NI_MAXHOST", + "NI_MAXSERV", + "NI_NAMEREQD", + "NI_NOFQDN", + "NI_NUMERICHOST", + "NI_NUMERICSERV", + "SHUT_RD", + "SHUT_RDWR", + "SHUT_WR", + "SOCK_DGRAM", + "SOCK_RAW", + "SOCK_RDM", + "SOCK_SEQPACKET", + "SOCK_STREAM", + "SOL_IP", + "SOL_SOCKET", + "SOL_TCP", + "SOL_UDP", + "SOMAXCONN", + "SO_ACCEPTCONN", + "SO_BROADCAST", + "SO_DEBUG", + "SO_DONTROUTE", + "SO_ERROR", + "SO_KEEPALIVE", + "SO_LINGER", + "SO_OOBINLINE", + "SO_RCVBUF", + "SO_RCVLOWAT", + "SO_RCVTIMEO", + "SO_REUSEADDR", + "SO_SNDBUF", + "SO_SNDLOWAT", + "SO_SNDTIMEO", + "SO_TYPE", + "SocketType", + "TCP_FASTOPEN", + "TCP_KEEPCNT", + "TCP_KEEPINTVL", + "TCP_MAXSEG", + "TCP_NODELAY", + "close", + "dup", + "error", + "gaierror", + "getaddrinfo", + "getdefaulttimeout", + "gethostbyaddr", + "gethostbyname", + "gethostbyname_ex", + "gethostname", + "getnameinfo", + "getprotobyname", + "getservbyname", + "getservbyport", + "has_ipv6", + "herror", + "htonl", + "htons", + "if_indextoname", + "if_nameindex", + "if_nametoindex", + "inet_aton", + "inet_ntoa", + "inet_ntop", + "inet_pton", + "ntohl", + "ntohs", + "setdefaulttimeout", + "socket", + "socketpair", + "timeout", +] + +if sys.platform == "win32": + from _socket import ( + IPPROTO_CBT as IPPROTO_CBT, + IPPROTO_ICLFXBM as IPPROTO_ICLFXBM, + IPPROTO_IGP as IPPROTO_IGP, + IPPROTO_L2TP as IPPROTO_L2TP, + IPPROTO_PGM as IPPROTO_PGM, + IPPROTO_RDP as IPPROTO_RDP, + IPPROTO_ST as IPPROTO_ST, + RCVALL_MAX as RCVALL_MAX, + RCVALL_OFF as RCVALL_OFF, + RCVALL_ON as RCVALL_ON, + RCVALL_SOCKETLEVELONLY as RCVALL_SOCKETLEVELONLY, + SIO_KEEPALIVE_VALS as SIO_KEEPALIVE_VALS, + SIO_LOOPBACK_FAST_PATH as SIO_LOOPBACK_FAST_PATH, + SIO_RCVALL as SIO_RCVALL, + SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE, + ) + + __all__ += [ + "IPPROTO_CBT", + "IPPROTO_ICLFXBM", + "IPPROTO_IGP", + "IPPROTO_L2TP", + "IPPROTO_PGM", + "IPPROTO_RDP", + "IPPROTO_ST", + "RCVALL_MAX", + "RCVALL_OFF", + "RCVALL_ON", + "RCVALL_SOCKETLEVELONLY", + "SIO_KEEPALIVE_VALS", + "SIO_LOOPBACK_FAST_PATH", + "SIO_RCVALL", + "SO_EXCLUSIVEADDRUSE", + "fromshare", + "errorTab", + "MSG_BCAST", + "MSG_MCAST", + ] + +if sys.platform == "darwin": + from _socket import PF_SYSTEM as PF_SYSTEM, SYSPROTO_CONTROL as SYSPROTO_CONTROL + + __all__ += ["PF_SYSTEM", "SYSPROTO_CONTROL", "AF_SYSTEM"] + +if sys.platform != "darwin": + from _socket import TCP_KEEPIDLE as TCP_KEEPIDLE + + __all__ += ["TCP_KEEPIDLE", "AF_IRDA", "MSG_ERRQUEUE"] + +if sys.platform != "win32" and sys.platform != "darwin": + from _socket import ( + IP_TRANSPARENT as IP_TRANSPARENT, + IPX_TYPE as IPX_TYPE, + SCM_CREDENTIALS as SCM_CREDENTIALS, + SO_DOMAIN as SO_DOMAIN, + SO_MARK as SO_MARK, + SO_PASSCRED as SO_PASSCRED, + SO_PASSSEC as SO_PASSSEC, + SO_PEERCRED as SO_PEERCRED, + SO_PEERSEC as SO_PEERSEC, + SO_PRIORITY as SO_PRIORITY, + SO_PROTOCOL as SO_PROTOCOL, + SOL_ATALK as SOL_ATALK, + SOL_AX25 as SOL_AX25, + SOL_HCI as SOL_HCI, + SOL_IPX as SOL_IPX, + SOL_NETROM as SOL_NETROM, + SOL_ROSE as SOL_ROSE, + TCP_CONGESTION as TCP_CONGESTION, + TCP_CORK as TCP_CORK, + TCP_DEFER_ACCEPT as TCP_DEFER_ACCEPT, + TCP_INFO as TCP_INFO, + TCP_LINGER2 as TCP_LINGER2, + TCP_QUICKACK as TCP_QUICKACK, + TCP_SYNCNT as TCP_SYNCNT, + TCP_USER_TIMEOUT as TCP_USER_TIMEOUT, + TCP_WINDOW_CLAMP as TCP_WINDOW_CLAMP, + ) + + __all__ += [ + "IP_TRANSPARENT", + "SCM_CREDENTIALS", + "SO_DOMAIN", + "SO_MARK", + "SO_PASSCRED", + "SO_PASSSEC", + "SO_PEERCRED", + "SO_PEERSEC", + "SO_PRIORITY", + "SO_PROTOCOL", + "TCP_CONGESTION", + "TCP_CORK", + "TCP_DEFER_ACCEPT", + "TCP_INFO", + "TCP_LINGER2", + "TCP_QUICKACK", + "TCP_SYNCNT", + "TCP_USER_TIMEOUT", + "TCP_WINDOW_CLAMP", + "AF_ASH", + "AF_ATMPVC", + "AF_ATMSVC", + "AF_AX25", + "AF_BRIDGE", + "AF_ECONET", + "AF_KEY", + "AF_LLC", + "AF_NETBEUI", + "AF_NETROM", + "AF_PPPOX", + "AF_ROSE", + "AF_SECURITY", + "AF_WANPIPE", + "AF_X25", + "MSG_CMSG_CLOEXEC", + "MSG_CONFIRM", + "MSG_FASTOPEN", + "MSG_MORE", + ] + +if sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 11): + from _socket import IP_BIND_ADDRESS_NO_PORT as IP_BIND_ADDRESS_NO_PORT + + __all__ += ["IP_BIND_ADDRESS_NO_PORT"] -if sys.version_info >= (3, 7): - from _socket import close as close if sys.platform != "win32": - from _socket import sethostname as sethostname -if sys.platform != "win32" or sys.version_info >= (3, 8): - from _socket import if_indextoname as if_indextoname, if_nameindex as if_nameindex, if_nametoindex as if_nametoindex + from _socket import ( + CMSG_LEN as CMSG_LEN, + CMSG_SPACE as CMSG_SPACE, + EAI_ADDRFAMILY as EAI_ADDRFAMILY, + EAI_OVERFLOW as EAI_OVERFLOW, + EAI_SYSTEM as EAI_SYSTEM, + IP_DEFAULT_MULTICAST_LOOP as IP_DEFAULT_MULTICAST_LOOP, + IP_DEFAULT_MULTICAST_TTL as IP_DEFAULT_MULTICAST_TTL, + IP_MAX_MEMBERSHIPS as IP_MAX_MEMBERSHIPS, + IP_RECVOPTS as IP_RECVOPTS, + IP_RECVRETOPTS as IP_RECVRETOPTS, + IP_RETOPTS as IP_RETOPTS, + IPPROTO_GRE as IPPROTO_GRE, + IPPROTO_IPIP as IPPROTO_IPIP, + IPPROTO_RSVP as IPPROTO_RSVP, + IPPROTO_TP as IPPROTO_TP, + IPV6_RTHDR_TYPE_0 as IPV6_RTHDR_TYPE_0, + SCM_RIGHTS as SCM_RIGHTS, + SO_REUSEPORT as SO_REUSEPORT, + TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT, + sethostname as sethostname, + ) + + __all__ += [ + "CMSG_LEN", + "CMSG_SPACE", + "EAI_ADDRFAMILY", + "EAI_OVERFLOW", + "EAI_SYSTEM", + "IP_DEFAULT_MULTICAST_LOOP", + "IP_DEFAULT_MULTICAST_TTL", + "IP_MAX_MEMBERSHIPS", + "IP_RECVOPTS", + "IP_RECVRETOPTS", + "IP_RETOPTS", + "IPPROTO_GRE", + "IPPROTO_IPIP", + "IPPROTO_RSVP", + "IPPROTO_TP", + "IPV6_RTHDR_TYPE_0", + "SCM_RIGHTS", + "SO_REUSEPORT", + "TCP_NOTSENT_LOWAT", + "sethostname", + "AF_ROUTE", + "AF_UNIX", + "MSG_DONTWAIT", + "MSG_EOR", + "MSG_NOSIGNAL", + ] + + from _socket import ( + IPV6_DSTOPTS as IPV6_DSTOPTS, + IPV6_NEXTHOP as IPV6_NEXTHOP, + IPV6_PATHMTU as IPV6_PATHMTU, + IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS, + IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT, + IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS, + IPV6_RECVPATHMTU as IPV6_RECVPATHMTU, + IPV6_RECVPKTINFO as IPV6_RECVPKTINFO, + IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS, + ) + + __all__ += [ + "IPV6_DSTOPTS", + "IPV6_NEXTHOP", + "IPV6_PATHMTU", + "IPV6_RECVDSTOPTS", + "IPV6_RECVHOPLIMIT", + "IPV6_RECVHOPOPTS", + "IPV6_RECVPATHMTU", + "IPV6_RECVPKTINFO", + "IPV6_RTHDRDSTOPTS", + ] + + if sys.platform != "darwin" or sys.version_info >= (3, 13): + from _socket import SO_BINDTODEVICE as SO_BINDTODEVICE + + __all__ += ["SO_BINDTODEVICE"] + +if sys.platform != "darwin": + from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM + +if sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["BDADDR_ANY", "BDADDR_LOCAL", "BTPROTO_RFCOMM"] + +if sys.platform == "darwin": + from _socket import TCP_KEEPALIVE as TCP_KEEPALIVE + + __all__ += ["TCP_KEEPALIVE"] + +if sys.platform == "darwin" and sys.version_info >= (3, 11): + from _socket import TCP_CONNECTION_INFO as TCP_CONNECTION_INFO + + __all__ += ["TCP_CONNECTION_INFO"] + if sys.platform == "linux": from _socket import ( ALG_OP_DECRYPT as ALG_OP_DECRYPT, @@ -229,15 +545,27 @@ if sys.platform == "linux": ALG_SET_OP as ALG_SET_OP, ALG_SET_PUBKEY as ALG_SET_PUBKEY, CAN_BCM as CAN_BCM, + CAN_BCM_CAN_FD_FRAME as CAN_BCM_CAN_FD_FRAME, + CAN_BCM_RX_ANNOUNCE_RESUME as CAN_BCM_RX_ANNOUNCE_RESUME, CAN_BCM_RX_CHANGED as CAN_BCM_RX_CHANGED, + CAN_BCM_RX_CHECK_DLC as CAN_BCM_RX_CHECK_DLC, CAN_BCM_RX_DELETE as CAN_BCM_RX_DELETE, + CAN_BCM_RX_FILTER_ID as CAN_BCM_RX_FILTER_ID, + CAN_BCM_RX_NO_AUTOTIMER as CAN_BCM_RX_NO_AUTOTIMER, CAN_BCM_RX_READ as CAN_BCM_RX_READ, + CAN_BCM_RX_RTR_FRAME as CAN_BCM_RX_RTR_FRAME, CAN_BCM_RX_SETUP as CAN_BCM_RX_SETUP, CAN_BCM_RX_STATUS as CAN_BCM_RX_STATUS, CAN_BCM_RX_TIMEOUT as CAN_BCM_RX_TIMEOUT, + CAN_BCM_SETTIMER as CAN_BCM_SETTIMER, + CAN_BCM_STARTTIMER as CAN_BCM_STARTTIMER, + CAN_BCM_TX_ANNOUNCE as CAN_BCM_TX_ANNOUNCE, + CAN_BCM_TX_COUNTEVT as CAN_BCM_TX_COUNTEVT, + CAN_BCM_TX_CP_CAN_ID as CAN_BCM_TX_CP_CAN_ID, CAN_BCM_TX_DELETE as CAN_BCM_TX_DELETE, CAN_BCM_TX_EXPIRED as CAN_BCM_TX_EXPIRED, CAN_BCM_TX_READ as CAN_BCM_TX_READ, + CAN_BCM_TX_RESET_MULTI_IDX as CAN_BCM_TX_RESET_MULTI_IDX, CAN_BCM_TX_SEND as CAN_BCM_TX_SEND, CAN_BCM_TX_SETUP as CAN_BCM_TX_SETUP, CAN_BCM_TX_STATUS as CAN_BCM_TX_STATUS, @@ -245,14 +573,23 @@ if sys.platform == "linux": CAN_EFF_MASK as CAN_EFF_MASK, CAN_ERR_FLAG as CAN_ERR_FLAG, CAN_ERR_MASK as CAN_ERR_MASK, + CAN_ISOTP as CAN_ISOTP, CAN_RAW as CAN_RAW, - CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES as CAN_RAW_FD_FRAMES, CAN_RAW_FILTER as CAN_RAW_FILTER, CAN_RAW_LOOPBACK as CAN_RAW_LOOPBACK, CAN_RAW_RECV_OWN_MSGS as CAN_RAW_RECV_OWN_MSGS, CAN_RTR_FLAG as CAN_RTR_FLAG, CAN_SFF_MASK as CAN_SFF_MASK, + IOCTL_VM_SOCKETS_GET_LOCAL_CID as IOCTL_VM_SOCKETS_GET_LOCAL_CID, + NETLINK_CRYPTO as NETLINK_CRYPTO, + NETLINK_DNRTMSG as NETLINK_DNRTMSG, + NETLINK_FIREWALL as NETLINK_FIREWALL, + NETLINK_IP6_FW as NETLINK_IP6_FW, + NETLINK_NFLOG as NETLINK_NFLOG, + NETLINK_ROUTE as NETLINK_ROUTE, + NETLINK_USERSOCK as NETLINK_USERSOCK, + NETLINK_XFRM as NETLINK_XFRM, PACKET_BROADCAST as PACKET_BROADCAST, PACKET_FASTROUTE as PACKET_FASTROUTE, PACKET_HOST as PACKET_HOST, @@ -268,7 +605,6 @@ if sys.platform == "linux": RDS_CMSG_RDMA_DEST as RDS_CMSG_RDMA_DEST, RDS_CMSG_RDMA_MAP as RDS_CMSG_RDMA_MAP, RDS_CMSG_RDMA_STATUS as RDS_CMSG_RDMA_STATUS, - RDS_CMSG_RDMA_UPDATE as RDS_CMSG_RDMA_UPDATE, RDS_CONG_MONITOR as RDS_CONG_MONITOR, RDS_FREE_MR as RDS_FREE_MR, RDS_GET_MR as RDS_GET_MR, @@ -281,6 +617,9 @@ if sys.platform == "linux": RDS_RDMA_SILENT as RDS_RDMA_SILENT, RDS_RDMA_USE_ONCE as RDS_RDMA_USE_ONCE, RDS_RECVERR as RDS_RECVERR, + SO_VM_SOCKETS_BUFFER_MAX_SIZE as SO_VM_SOCKETS_BUFFER_MAX_SIZE, + SO_VM_SOCKETS_BUFFER_MIN_SIZE as SO_VM_SOCKETS_BUFFER_MIN_SIZE, + SO_VM_SOCKETS_BUFFER_SIZE as SO_VM_SOCKETS_BUFFER_SIZE, SOL_ALG as SOL_ALG, SOL_CAN_BASE as SOL_CAN_BASE, SOL_CAN_RAW as SOL_CAN_RAW, @@ -309,39 +648,202 @@ if sys.platform == "linux": TIPC_WAIT_FOREVER as TIPC_WAIT_FOREVER, TIPC_WITHDRAWN as TIPC_WITHDRAWN, TIPC_ZONE_SCOPE as TIPC_ZONE_SCOPE, - ) -if sys.platform == "linux" and sys.version_info >= (3, 7): - from _socket import ( - CAN_ISOTP as CAN_ISOTP, - IOCTL_VM_SOCKETS_GET_LOCAL_CID as IOCTL_VM_SOCKETS_GET_LOCAL_CID, - SO_VM_SOCKETS_BUFFER_MAX_SIZE as SO_VM_SOCKETS_BUFFER_MAX_SIZE, - SO_VM_SOCKETS_BUFFER_MIN_SIZE as SO_VM_SOCKETS_BUFFER_MIN_SIZE, - SO_VM_SOCKETS_BUFFER_SIZE as SO_VM_SOCKETS_BUFFER_SIZE, - TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT, VM_SOCKETS_INVALID_VERSION as VM_SOCKETS_INVALID_VERSION, VMADDR_CID_ANY as VMADDR_CID_ANY, VMADDR_CID_HOST as VMADDR_CID_HOST, VMADDR_PORT_ANY as VMADDR_PORT_ANY, ) -if sys.platform == "linux" and sys.version_info >= (3, 8): - from _socket import ( - CAN_BCM_CAN_FD_FRAME as CAN_BCM_CAN_FD_FRAME, - CAN_BCM_RX_ANNOUNCE_RESUME as CAN_BCM_RX_ANNOUNCE_RESUME, - CAN_BCM_RX_CHECK_DLC as CAN_BCM_RX_CHECK_DLC, - CAN_BCM_RX_FILTER_ID as CAN_BCM_RX_FILTER_ID, - CAN_BCM_RX_NO_AUTOTIMER as CAN_BCM_RX_NO_AUTOTIMER, - CAN_BCM_RX_RTR_FRAME as CAN_BCM_RX_RTR_FRAME, - CAN_BCM_SETTIMER as CAN_BCM_SETTIMER, - CAN_BCM_STARTTIMER as CAN_BCM_STARTTIMER, - CAN_BCM_TX_ANNOUNCE as CAN_BCM_TX_ANNOUNCE, - CAN_BCM_TX_COUNTEVT as CAN_BCM_TX_COUNTEVT, - CAN_BCM_TX_CP_CAN_ID as CAN_BCM_TX_CP_CAN_ID, - CAN_BCM_TX_RESET_MULTI_IDX as CAN_BCM_TX_RESET_MULTI_IDX, - ) -if sys.platform == "linux" and sys.version_info >= (3, 9): + + __all__ += [ + "ALG_OP_DECRYPT", + "ALG_OP_ENCRYPT", + "ALG_OP_SIGN", + "ALG_OP_VERIFY", + "ALG_SET_AEAD_ASSOCLEN", + "ALG_SET_AEAD_AUTHSIZE", + "ALG_SET_IV", + "ALG_SET_KEY", + "ALG_SET_OP", + "ALG_SET_PUBKEY", + "CAN_BCM", + "CAN_BCM_CAN_FD_FRAME", + "CAN_BCM_RX_ANNOUNCE_RESUME", + "CAN_BCM_RX_CHANGED", + "CAN_BCM_RX_CHECK_DLC", + "CAN_BCM_RX_DELETE", + "CAN_BCM_RX_FILTER_ID", + "CAN_BCM_RX_NO_AUTOTIMER", + "CAN_BCM_RX_READ", + "CAN_BCM_RX_RTR_FRAME", + "CAN_BCM_RX_SETUP", + "CAN_BCM_RX_STATUS", + "CAN_BCM_RX_TIMEOUT", + "CAN_BCM_SETTIMER", + "CAN_BCM_STARTTIMER", + "CAN_BCM_TX_ANNOUNCE", + "CAN_BCM_TX_COUNTEVT", + "CAN_BCM_TX_CP_CAN_ID", + "CAN_BCM_TX_DELETE", + "CAN_BCM_TX_EXPIRED", + "CAN_BCM_TX_READ", + "CAN_BCM_TX_RESET_MULTI_IDX", + "CAN_BCM_TX_SEND", + "CAN_BCM_TX_SETUP", + "CAN_BCM_TX_STATUS", + "CAN_EFF_FLAG", + "CAN_EFF_MASK", + "CAN_ERR_FLAG", + "CAN_ERR_MASK", + "CAN_ISOTP", + "CAN_RAW", + "CAN_RAW_FD_FRAMES", + "CAN_RAW_FILTER", + "CAN_RAW_LOOPBACK", + "CAN_RAW_RECV_OWN_MSGS", + "CAN_RTR_FLAG", + "CAN_SFF_MASK", + "IOCTL_VM_SOCKETS_GET_LOCAL_CID", + "NETLINK_CRYPTO", + "NETLINK_DNRTMSG", + "NETLINK_FIREWALL", + "NETLINK_IP6_FW", + "NETLINK_NFLOG", + "NETLINK_ROUTE", + "NETLINK_USERSOCK", + "NETLINK_XFRM", + "PACKET_BROADCAST", + "PACKET_FASTROUTE", + "PACKET_HOST", + "PACKET_LOOPBACK", + "PACKET_MULTICAST", + "PACKET_OTHERHOST", + "PACKET_OUTGOING", + "PF_CAN", + "PF_PACKET", + "PF_RDS", + "SO_VM_SOCKETS_BUFFER_MAX_SIZE", + "SO_VM_SOCKETS_BUFFER_MIN_SIZE", + "SO_VM_SOCKETS_BUFFER_SIZE", + "SOL_ALG", + "SOL_CAN_BASE", + "SOL_CAN_RAW", + "SOL_RDS", + "SOL_TIPC", + "TIPC_ADDR_ID", + "TIPC_ADDR_NAME", + "TIPC_ADDR_NAMESEQ", + "TIPC_CFG_SRV", + "TIPC_CLUSTER_SCOPE", + "TIPC_CONN_TIMEOUT", + "TIPC_CRITICAL_IMPORTANCE", + "TIPC_DEST_DROPPABLE", + "TIPC_HIGH_IMPORTANCE", + "TIPC_IMPORTANCE", + "TIPC_LOW_IMPORTANCE", + "TIPC_MEDIUM_IMPORTANCE", + "TIPC_NODE_SCOPE", + "TIPC_PUBLISHED", + "TIPC_SRC_DROPPABLE", + "TIPC_SUB_CANCEL", + "TIPC_SUB_PORTS", + "TIPC_SUB_SERVICE", + "TIPC_SUBSCR_TIMEOUT", + "TIPC_TOP_SRV", + "TIPC_WAIT_FOREVER", + "TIPC_WITHDRAWN", + "TIPC_ZONE_SCOPE", + "VM_SOCKETS_INVALID_VERSION", + "VMADDR_CID_ANY", + "VMADDR_CID_HOST", + "VMADDR_PORT_ANY", + "AF_CAN", + "AF_PACKET", + "AF_RDS", + "AF_TIPC", + "AF_ALG", + "AF_NETLINK", + "AF_VSOCK", + "AF_QIPCRTR", + "SOCK_CLOEXEC", + "SOCK_NONBLOCK", + ] + + if sys.version_info < (3, 11): + from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER + + __all__ += ["CAN_RAW_ERR_FILTER"] + if sys.version_info >= (3, 13): + from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER + + __all__ += ["CAN_RAW_ERR_FILTER"] + if sys.version_info >= (3, 15): + from _socket import ( + CAN_ISOTP_CHK_PAD_DATA as CAN_ISOTP_CHK_PAD_DATA, + CAN_ISOTP_CHK_PAD_LEN as CAN_ISOTP_CHK_PAD_LEN, + CAN_ISOTP_DEFAULT_EXT_ADDRESS as CAN_ISOTP_DEFAULT_EXT_ADDRESS, + CAN_ISOTP_DEFAULT_FLAGS as CAN_ISOTP_DEFAULT_FLAGS, + CAN_ISOTP_DEFAULT_FRAME_TXTIME as CAN_ISOTP_DEFAULT_FRAME_TXTIME, + CAN_ISOTP_DEFAULT_LL_MTU as CAN_ISOTP_DEFAULT_LL_MTU, + CAN_ISOTP_DEFAULT_LL_TX_DL as CAN_ISOTP_DEFAULT_LL_TX_DL, + CAN_ISOTP_DEFAULT_LL_TX_FLAGS as CAN_ISOTP_DEFAULT_LL_TX_FLAGS, + CAN_ISOTP_DEFAULT_PAD_CONTENT as CAN_ISOTP_DEFAULT_PAD_CONTENT, + CAN_ISOTP_DEFAULT_RECV_BS as CAN_ISOTP_DEFAULT_RECV_BS, + CAN_ISOTP_DEFAULT_RECV_STMIN as CAN_ISOTP_DEFAULT_RECV_STMIN, + CAN_ISOTP_DEFAULT_RECV_WFTMAX as CAN_ISOTP_DEFAULT_RECV_WFTMAX, + CAN_ISOTP_EXTEND_ADDR as CAN_ISOTP_EXTEND_ADDR, + CAN_ISOTP_FORCE_RXSTMIN as CAN_ISOTP_FORCE_RXSTMIN, + CAN_ISOTP_FORCE_TXSTMIN as CAN_ISOTP_FORCE_TXSTMIN, + CAN_ISOTP_HALF_DUPLEX as CAN_ISOTP_HALF_DUPLEX, + CAN_ISOTP_LISTEN_MODE as CAN_ISOTP_LISTEN_MODE, + CAN_ISOTP_LL_OPTS as CAN_ISOTP_LL_OPTS, + CAN_ISOTP_OPTS as CAN_ISOTP_OPTS, + CAN_ISOTP_RECV_FC as CAN_ISOTP_RECV_FC, + CAN_ISOTP_RX_EXT_ADDR as CAN_ISOTP_RX_EXT_ADDR, + CAN_ISOTP_RX_PADDING as CAN_ISOTP_RX_PADDING, + CAN_ISOTP_RX_STMIN as CAN_ISOTP_RX_STMIN, + CAN_ISOTP_SF_BROADCAST as CAN_ISOTP_SF_BROADCAST, + CAN_ISOTP_TX_PADDING as CAN_ISOTP_TX_PADDING, + CAN_ISOTP_TX_STMIN as CAN_ISOTP_TX_STMIN, + CAN_ISOTP_WAIT_TX_DONE as CAN_ISOTP_WAIT_TX_DONE, + SOL_CAN_ISOTP as SOL_CAN_ISOTP, + ) + + __all__ += [ + "CAN_ISOTP_CHK_PAD_DATA", + "CAN_ISOTP_CHK_PAD_LEN", + "CAN_ISOTP_DEFAULT_EXT_ADDRESS", + "CAN_ISOTP_DEFAULT_FLAGS", + "CAN_ISOTP_DEFAULT_FRAME_TXTIME", + "CAN_ISOTP_DEFAULT_LL_MTU", + "CAN_ISOTP_DEFAULT_LL_TX_DL", + "CAN_ISOTP_DEFAULT_LL_TX_FLAGS", + "CAN_ISOTP_DEFAULT_PAD_CONTENT", + "CAN_ISOTP_DEFAULT_RECV_BS", + "CAN_ISOTP_DEFAULT_RECV_STMIN", + "CAN_ISOTP_DEFAULT_RECV_WFTMAX", + "CAN_ISOTP_EXTEND_ADDR", + "CAN_ISOTP_FORCE_RXSTMIN", + "CAN_ISOTP_FORCE_TXSTMIN", + "CAN_ISOTP_HALF_DUPLEX", + "CAN_ISOTP_LL_OPTS", + "CAN_ISOTP_LISTEN_MODE", + "CAN_ISOTP_OPTS", + "CAN_ISOTP_RECV_FC", + "CAN_ISOTP_RX_EXT_ADDR", + "CAN_ISOTP_RX_PADDING", + "CAN_ISOTP_RX_STMIN", + "CAN_ISOTP_SF_BROADCAST", + "CAN_ISOTP_TX_PADDING", + "CAN_ISOTP_TX_STMIN", + "CAN_ISOTP_WAIT_TX_DONE", + "SOL_CAN_ISOTP", + ] + +if sys.platform == "linux": from _socket import ( CAN_J1939 as CAN_J1939, CAN_RAW_JOIN_FILTERS as CAN_RAW_JOIN_FILTERS, + IPPROTO_UDPLITE as IPPROTO_UDPLITE, J1939_EE_INFO_NONE as J1939_EE_INFO_NONE, J1939_EE_INFO_TX_ABORT as J1939_EE_INFO_TX_ABORT, J1939_FILTER_MAX as J1939_FILTER_MAX, @@ -365,236 +867,683 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): SO_J1939_FILTER as SO_J1939_FILTER, SO_J1939_PROMISC as SO_J1939_PROMISC, SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO, + UDPLITE_RECV_CSCOV as UDPLITE_RECV_CSCOV, + UDPLITE_SEND_CSCOV as UDPLITE_SEND_CSCOV, ) -if sys.platform == "win32": + + __all__ += [ + "CAN_J1939", + "CAN_RAW_JOIN_FILTERS", + "IPPROTO_UDPLITE", + "J1939_EE_INFO_NONE", + "J1939_EE_INFO_TX_ABORT", + "J1939_FILTER_MAX", + "J1939_IDLE_ADDR", + "J1939_MAX_UNICAST_ADDR", + "J1939_NLA_BYTES_ACKED", + "J1939_NLA_PAD", + "J1939_NO_ADDR", + "J1939_NO_NAME", + "J1939_NO_PGN", + "J1939_PGN_ADDRESS_CLAIMED", + "J1939_PGN_ADDRESS_COMMANDED", + "J1939_PGN_MAX", + "J1939_PGN_PDU1_MAX", + "J1939_PGN_REQUEST", + "SCM_J1939_DEST_ADDR", + "SCM_J1939_DEST_NAME", + "SCM_J1939_ERRQUEUE", + "SCM_J1939_PRIO", + "SO_J1939_ERRQUEUE", + "SO_J1939_FILTER", + "SO_J1939_PROMISC", + "SO_J1939_SEND_PRIO", + "UDPLITE_RECV_CSCOV", + "UDPLITE_SEND_CSCOV", + ] +if sys.platform == "linux": + from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP + + __all__ += ["IPPROTO_MPTCP"] +if sys.platform == "linux" and sys.version_info >= (3, 11): + from _socket import SO_INCOMING_CPU as SO_INCOMING_CPU + + __all__ += ["SO_INCOMING_CPU"] +if sys.platform == "linux" and sys.version_info >= (3, 12): from _socket import ( - RCVALL_IPLEVEL as RCVALL_IPLEVEL, - RCVALL_MAX as RCVALL_MAX, - RCVALL_OFF as RCVALL_OFF, - RCVALL_ON as RCVALL_ON, - RCVALL_SOCKETLEVELONLY as RCVALL_SOCKETLEVELONLY, - SIO_KEEPALIVE_VALS as SIO_KEEPALIVE_VALS, - SIO_LOOPBACK_FAST_PATH as SIO_LOOPBACK_FAST_PATH, - SIO_RCVALL as SIO_RCVALL, + TCP_CC_INFO as TCP_CC_INFO, + TCP_FASTOPEN_CONNECT as TCP_FASTOPEN_CONNECT, + TCP_FASTOPEN_KEY as TCP_FASTOPEN_KEY, + TCP_FASTOPEN_NO_COOKIE as TCP_FASTOPEN_NO_COOKIE, + TCP_INQ as TCP_INQ, + TCP_MD5SIG as TCP_MD5SIG, + TCP_MD5SIG_EXT as TCP_MD5SIG_EXT, + TCP_QUEUE_SEQ as TCP_QUEUE_SEQ, + TCP_REPAIR as TCP_REPAIR, + TCP_REPAIR_OPTIONS as TCP_REPAIR_OPTIONS, + TCP_REPAIR_QUEUE as TCP_REPAIR_QUEUE, + TCP_REPAIR_WINDOW as TCP_REPAIR_WINDOW, + TCP_SAVE_SYN as TCP_SAVE_SYN, + TCP_SAVED_SYN as TCP_SAVED_SYN, + TCP_THIN_DUPACK as TCP_THIN_DUPACK, + TCP_THIN_LINEAR_TIMEOUTS as TCP_THIN_LINEAR_TIMEOUTS, + TCP_TIMESTAMP as TCP_TIMESTAMP, + TCP_TX_DELAY as TCP_TX_DELAY, + TCP_ULP as TCP_ULP, + TCP_ZEROCOPY_RECEIVE as TCP_ZEROCOPY_RECEIVE, ) -_T = TypeVar("_T") + __all__ += [ + "TCP_CC_INFO", + "TCP_FASTOPEN_CONNECT", + "TCP_FASTOPEN_KEY", + "TCP_FASTOPEN_NO_COOKIE", + "TCP_INQ", + "TCP_MD5SIG", + "TCP_MD5SIG_EXT", + "TCP_QUEUE_SEQ", + "TCP_REPAIR", + "TCP_REPAIR_OPTIONS", + "TCP_REPAIR_QUEUE", + "TCP_REPAIR_WINDOW", + "TCP_SAVED_SYN", + "TCP_SAVE_SYN", + "TCP_THIN_DUPACK", + "TCP_THIN_LINEAR_TIMEOUTS", + "TCP_TIMESTAMP", + "TCP_TX_DELAY", + "TCP_ULP", + "TCP_ZEROCOPY_RECEIVE", + ] + +if sys.platform == "linux" and sys.version_info >= (3, 13): + from _socket import NI_IDN as NI_IDN, SO_BINDTOIFINDEX as SO_BINDTOIFINDEX + + __all__ += ["NI_IDN", "SO_BINDTOIFINDEX"] + +if sys.version_info >= (3, 12): + from _socket import ( + IP_ADD_SOURCE_MEMBERSHIP as IP_ADD_SOURCE_MEMBERSHIP, + IP_BLOCK_SOURCE as IP_BLOCK_SOURCE, + IP_DROP_SOURCE_MEMBERSHIP as IP_DROP_SOURCE_MEMBERSHIP, + IP_PKTINFO as IP_PKTINFO, + IP_UNBLOCK_SOURCE as IP_UNBLOCK_SOURCE, + ) + + __all__ += ["IP_ADD_SOURCE_MEMBERSHIP", "IP_BLOCK_SOURCE", "IP_DROP_SOURCE_MEMBERSHIP", "IP_PKTINFO", "IP_UNBLOCK_SOURCE"] + + if sys.platform == "win32": + from _socket import ( + HV_GUID_BROADCAST as HV_GUID_BROADCAST, + HV_GUID_CHILDREN as HV_GUID_CHILDREN, + HV_GUID_LOOPBACK as HV_GUID_LOOPBACK, + HV_GUID_PARENT as HV_GUID_PARENT, + HV_GUID_WILDCARD as HV_GUID_WILDCARD, + HV_GUID_ZERO as HV_GUID_ZERO, + HV_PROTOCOL_RAW as HV_PROTOCOL_RAW, + HVSOCKET_ADDRESS_FLAG_PASSTHRU as HVSOCKET_ADDRESS_FLAG_PASSTHRU, + HVSOCKET_CONNECT_TIMEOUT as HVSOCKET_CONNECT_TIMEOUT, + HVSOCKET_CONNECT_TIMEOUT_MAX as HVSOCKET_CONNECT_TIMEOUT_MAX, + HVSOCKET_CONNECTED_SUSPEND as HVSOCKET_CONNECTED_SUSPEND, + ) + + __all__ += [ + "HV_GUID_BROADCAST", + "HV_GUID_CHILDREN", + "HV_GUID_LOOPBACK", + "HV_GUID_PARENT", + "HV_GUID_WILDCARD", + "HV_GUID_ZERO", + "HV_PROTOCOL_RAW", + "HVSOCKET_ADDRESS_FLAG_PASSTHRU", + "HVSOCKET_CONNECT_TIMEOUT", + "HVSOCKET_CONNECT_TIMEOUT_MAX", + "HVSOCKET_CONNECTED_SUSPEND", + ] + else: + from _socket import ( + ETHERTYPE_ARP as ETHERTYPE_ARP, + ETHERTYPE_IP as ETHERTYPE_IP, + ETHERTYPE_IPV6 as ETHERTYPE_IPV6, + ETHERTYPE_VLAN as ETHERTYPE_VLAN, + ) + + __all__ += ["ETHERTYPE_ARP", "ETHERTYPE_IP", "ETHERTYPE_IPV6", "ETHERTYPE_VLAN"] + + if sys.platform == "linux": + from _socket import ETH_P_ALL as ETH_P_ALL + + __all__ += ["ETH_P_ALL"] + + if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # FreeBSD >= 14.0 + from _socket import PF_DIVERT as PF_DIVERT + + __all__ += ["PF_DIVERT", "AF_DIVERT"] + +if sys.platform != "win32": + __all__ += ["send_fds", "recv_fds"] + +if sys.platform != "linux": + __all__ += ["AF_LINK"] +if sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["AF_BLUETOOTH"] + +if sys.platform != "win32" and sys.platform != "darwin": + from _socket import BTPROTO_HCI as BTPROTO_HCI, BTPROTO_L2CAP as BTPROTO_L2CAP, BTPROTO_SCO as BTPROTO_SCO + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["BTPROTO_HCI", "BTPROTO_L2CAP", "BTPROTO_SCO"] + +if sys.platform != "win32" and sys.platform != "darwin": + from _socket import HCI_DATA_DIR as HCI_DATA_DIR, HCI_FILTER as HCI_FILTER, HCI_TIME_STAMP as HCI_TIME_STAMP + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["HCI_FILTER", "HCI_TIME_STAMP", "HCI_DATA_DIR"] + +if sys.version_info >= (3, 11) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from _socket import LOCAL_CREDS as LOCAL_CREDS, LOCAL_CREDS_PERSISTENT as LOCAL_CREDS_PERSISTENT, SCM_CREDS2 as SCM_CREDS2 + + __all__ += ["SCM_CREDS2", "LOCAL_CREDS", "LOCAL_CREDS_PERSISTENT"] + +if sys.platform == "win32" and sys.version_info >= (3, 12): + __all__ += ["AF_HYPERV"] + +if sys.platform != "win32" and sys.platform != "linux": + from _socket import ( + EAI_BADHINTS as EAI_BADHINTS, + EAI_MAX as EAI_MAX, + EAI_PROTOCOL as EAI_PROTOCOL, + IPPROTO_EON as IPPROTO_EON, + IPPROTO_HELLO as IPPROTO_HELLO, + IPPROTO_IPCOMP as IPPROTO_IPCOMP, + IPPROTO_XTP as IPPROTO_XTP, + IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU, + LOCAL_PEERCRED as LOCAL_PEERCRED, + SCM_CREDS as SCM_CREDS, + ) + + __all__ += [ + "EAI_BADHINTS", + "EAI_MAX", + "EAI_PROTOCOL", + "IPPROTO_EON", + "IPPROTO_HELLO", + "IPPROTO_IPCOMP", + "IPPROTO_XTP", + "IPV6_USE_MIN_MTU", + "LOCAL_PEERCRED", + "SCM_CREDS", + "AI_DEFAULT", + "AI_MASK", + "AI_V4MAPPED_CFG", + "MSG_EOF", + ] + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + from _socket import ( + IPPROTO_BIP as IPPROTO_BIP, + IPPROTO_MOBILE as IPPROTO_MOBILE, + IPPROTO_VRRP as IPPROTO_VRRP, + MSG_BTAG as MSG_BTAG, + MSG_ETAG as MSG_ETAG, + SO_SETFIB as SO_SETFIB, + ) + + __all__ += ["SO_SETFIB", "MSG_BTAG", "MSG_ETAG", "IPPROTO_BIP", "IPPROTO_MOBILE", "IPPROTO_VRRP", "MSG_NOTIFICATION"] + +if sys.platform != "linux": + from _socket import ( + IP_RECVDSTADDR as IP_RECVDSTADDR, + IPPROTO_GGP as IPPROTO_GGP, + IPPROTO_IPV4 as IPPROTO_IPV4, + IPPROTO_MAX as IPPROTO_MAX, + IPPROTO_ND as IPPROTO_ND, + SO_USELOOPBACK as SO_USELOOPBACK, + ) + + __all__ += ["IPPROTO_GGP", "IPPROTO_IPV4", "IPPROTO_MAX", "IPPROTO_ND", "IP_RECVDSTADDR", "SO_USELOOPBACK"] + +if sys.version_info >= (3, 15): + if sys.platform == "win32" or sys.platform == "linux": + from _socket import IPV6_HDRINCL as IPV6_HDRINCL + + __all__ += ["IPV6_HDRINCL"] + +if sys.version_info >= (3, 14): + from _socket import IP_RECVTTL as IP_RECVTTL + + __all__ += ["IP_RECVTTL"] + + if sys.platform == "win32" or sys.platform == "linux": + from _socket import IP_RECVERR as IP_RECVERR, IPV6_RECVERR as IPV6_RECVERR, SO_ORIGINAL_DST as SO_ORIGINAL_DST + + __all__ += ["IP_RECVERR", "IPV6_RECVERR", "SO_ORIGINAL_DST"] + + if sys.platform == "win32": + from _socket import ( + SO_BTH_ENCRYPT as SO_BTH_ENCRYPT, + SO_BTH_MTU as SO_BTH_MTU, + SO_BTH_MTU_MAX as SO_BTH_MTU_MAX, + SO_BTH_MTU_MIN as SO_BTH_MTU_MIN, + SOL_RFCOMM as SOL_RFCOMM, + TCP_QUICKACK as TCP_QUICKACK, + ) + + __all__ += ["SOL_RFCOMM", "SO_BTH_ENCRYPT", "SO_BTH_MTU", "SO_BTH_MTU_MAX", "SO_BTH_MTU_MIN", "TCP_QUICKACK"] + + if sys.platform == "linux": + from _socket import ( + BDADDR_BREDR as BDADDR_BREDR, + BDADDR_LE_PUBLIC as BDADDR_LE_PUBLIC, + BDADDR_LE_RANDOM as BDADDR_LE_RANDOM, + BT_CHANNEL_POLICY as BT_CHANNEL_POLICY, + BT_CHANNEL_POLICY_BREDR_ONLY as BT_CHANNEL_POLICY_BREDR_ONLY, + BT_CHANNEL_POLICY_BREDR_PREFERRED as BT_CHANNEL_POLICY_BREDR_PREFERRED, + BT_CODEC as BT_CODEC, + BT_DEFER_SETUP as BT_DEFER_SETUP, + BT_FLUSHABLE as BT_FLUSHABLE, + BT_FLUSHABLE_OFF as BT_FLUSHABLE_OFF, + BT_FLUSHABLE_ON as BT_FLUSHABLE_ON, + BT_ISO_QOS as BT_ISO_QOS, + BT_MODE as BT_MODE, + BT_MODE_BASIC as BT_MODE_BASIC, + BT_MODE_ERTM as BT_MODE_ERTM, + BT_MODE_EXT_FLOWCTL as BT_MODE_EXT_FLOWCTL, + BT_MODE_LE_FLOWCTL as BT_MODE_LE_FLOWCTL, + BT_MODE_STREAMING as BT_MODE_STREAMING, + BT_PHY as BT_PHY, + BT_PHY_BR_1M_1SLOT as BT_PHY_BR_1M_1SLOT, + BT_PHY_BR_1M_3SLOT as BT_PHY_BR_1M_3SLOT, + BT_PHY_BR_1M_5SLOT as BT_PHY_BR_1M_5SLOT, + BT_PHY_EDR_2M_1SLOT as BT_PHY_EDR_2M_1SLOT, + BT_PHY_EDR_2M_3SLOT as BT_PHY_EDR_2M_3SLOT, + BT_PHY_EDR_2M_5SLOT as BT_PHY_EDR_2M_5SLOT, + BT_PHY_EDR_3M_1SLOT as BT_PHY_EDR_3M_1SLOT, + BT_PHY_EDR_3M_3SLOT as BT_PHY_EDR_3M_3SLOT, + BT_PHY_EDR_3M_5SLOT as BT_PHY_EDR_3M_5SLOT, + BT_PHY_LE_1M_RX as BT_PHY_LE_1M_RX, + BT_PHY_LE_1M_TX as BT_PHY_LE_1M_TX, + BT_PHY_LE_2M_RX as BT_PHY_LE_2M_RX, + BT_PHY_LE_2M_TX as BT_PHY_LE_2M_TX, + BT_PHY_LE_CODED_RX as BT_PHY_LE_CODED_RX, + BT_PHY_LE_CODED_TX as BT_PHY_LE_CODED_TX, + BT_PKT_STATUS as BT_PKT_STATUS, + BT_POWER as BT_POWER, + BT_POWER_FORCE_ACTIVE_OFF as BT_POWER_FORCE_ACTIVE_OFF, + BT_POWER_FORCE_ACTIVE_ON as BT_POWER_FORCE_ACTIVE_ON, + BT_RCVMTU as BT_RCVMTU, + BT_SECURITY as BT_SECURITY, + BT_SECURITY_FIPS as BT_SECURITY_FIPS, + BT_SECURITY_HIGH as BT_SECURITY_HIGH, + BT_SECURITY_LOW as BT_SECURITY_LOW, + BT_SECURITY_MEDIUM as BT_SECURITY_MEDIUM, + BT_SECURITY_SDP as BT_SECURITY_SDP, + BT_SNDMTU as BT_SNDMTU, + BT_VOICE as BT_VOICE, + BT_VOICE_CVSD_16BIT as BT_VOICE_CVSD_16BIT, + BT_VOICE_TRANSPARENT as BT_VOICE_TRANSPARENT, + BT_VOICE_TRANSPARENT_16BIT as BT_VOICE_TRANSPARENT_16BIT, + HCI_CHANNEL_CONTROL as HCI_CHANNEL_CONTROL, + HCI_CHANNEL_LOGGING as HCI_CHANNEL_LOGGING, + HCI_CHANNEL_MONITOR as HCI_CHANNEL_MONITOR, + HCI_CHANNEL_RAW as HCI_CHANNEL_RAW, + HCI_CHANNEL_USER as HCI_CHANNEL_USER, + HCI_DEV_NONE as HCI_DEV_NONE, + IP_FREEBIND as IP_FREEBIND, + IP_RECVORIGDSTADDR as IP_RECVORIGDSTADDR, + L2CAP_LM as L2CAP_LM, + L2CAP_LM_AUTH as L2CAP_LM_AUTH, + L2CAP_LM_ENCRYPT as L2CAP_LM_ENCRYPT, + L2CAP_LM_MASTER as L2CAP_LM_MASTER, + L2CAP_LM_RELIABLE as L2CAP_LM_RELIABLE, + L2CAP_LM_SECURE as L2CAP_LM_SECURE, + L2CAP_LM_TRUSTED as L2CAP_LM_TRUSTED, + SOL_BLUETOOTH as SOL_BLUETOOTH, + SOL_L2CAP as SOL_L2CAP, + SOL_RFCOMM as SOL_RFCOMM, + SOL_SCO as SOL_SCO, + VMADDR_CID_LOCAL as VMADDR_CID_LOCAL, + ) + + __all__ += ["IP_FREEBIND", "IP_RECVORIGDSTADDR", "VMADDR_CID_LOCAL"] # Re-exported from errno -EBADF: int -EAGAIN: int -EWOULDBLOCK: int +EBADF: Final[int] +EAGAIN: Final[int] +EWOULDBLOCK: Final[int] + +# These errors are implemented in _socket at runtime +# but they consider themselves to live in socket so we'll put them here. +error = OSError + +class herror(error): ... +class gaierror(error): ... + +timeout = TimeoutError class AddressFamily(IntEnum): - AF_UNIX: int - AF_INET: int - AF_INET6: int - AF_AAL5: int - AF_ALG: int - AF_APPLETALK: int - AF_ASH: int - AF_ATMPVC: int - AF_ATMSVC: int - AF_AX25: int - AF_BLUETOOTH: int - AF_BRIDGE: int - AF_CAN: int - AF_DECnet: int - AF_ECONET: int - AF_IPX: int - AF_IRDA: int - AF_KEY: int - AF_LINK: int - AF_LLC: int - AF_NETBEUI: int - AF_NETLINK: int - AF_NETROM: int - AF_PACKET: int - AF_PPPOX: int - AF_QIPCRTR: int - AF_RDS: int - AF_ROSE: int - AF_ROUTE: int - AF_SECURITY: int - AF_SNA: int - AF_SYSTEM: int - AF_TIPC: int - AF_UNSPEC: int - AF_VSOCK: int - AF_WANPIPE: int - AF_X25: int - -AF_UNIX: AddressFamily -AF_INET: AddressFamily -AF_INET6: AddressFamily -AF_AAL5: AddressFamily -AF_APPLETALK: AddressFamily -AF_ASH: AddressFamily -AF_ATMPVC: AddressFamily -AF_ATMSVC: AddressFamily -AF_AX25: AddressFamily -AF_BRIDGE: AddressFamily -AF_DECnet: AddressFamily -AF_ECONET: AddressFamily -AF_IPX: AddressFamily -AF_IRDA: AddressFamily -AF_KEY: AddressFamily -AF_LLC: AddressFamily -AF_NETBEUI: AddressFamily -AF_NETROM: AddressFamily -AF_PPPOX: AddressFamily -AF_ROSE: AddressFamily -AF_ROUTE: AddressFamily -AF_SECURITY: AddressFamily -AF_SNA: AddressFamily -AF_SYSTEM: AddressFamily -AF_UNSPEC: AddressFamily -AF_WANPIPE: AddressFamily -AF_X25: AddressFamily -if sys.platform == "linux": - AF_CAN: AddressFamily - AF_PACKET: AddressFamily - AF_RDS: AddressFamily - AF_TIPC: AddressFamily - AF_ALG: AddressFamily - AF_NETLINK: AddressFamily - if sys.version_info >= (3, 7): - AF_VSOCK: AddressFamily - if sys.version_info >= (3, 8): - AF_QIPCRTR: AddressFamily -AF_LINK: AddressFamily # availability: BSD, macOS + AF_INET = 2 + AF_INET6 = 10 + AF_APPLETALK = 5 + AF_IPX = 4 + AF_SNA = 22 + AF_UNSPEC = 0 + if sys.platform != "darwin": + AF_IRDA = 23 + if sys.platform != "win32": + AF_ROUTE = 16 + AF_UNIX = 1 + if sys.platform == "darwin": + AF_SYSTEM = 32 + if sys.platform != "win32" and sys.platform != "darwin": + AF_ASH = 18 + AF_ATMPVC = 8 + AF_ATMSVC = 20 + AF_AX25 = 3 + AF_BRIDGE = 7 + AF_ECONET = 19 + AF_KEY = 15 + AF_LLC = 26 + AF_NETBEUI = 13 + AF_NETROM = 6 + AF_PPPOX = 24 + AF_ROSE = 11 + AF_SECURITY = 14 + AF_WANPIPE = 25 + AF_X25 = 9 + if sys.platform == "linux": + AF_CAN = 29 + AF_PACKET = 17 + AF_RDS = 21 + AF_TIPC = 30 + AF_ALG = 38 + AF_NETLINK = 16 + AF_VSOCK = 40 + AF_QIPCRTR = 42 + if sys.platform != "linux": + AF_LINK = 33 + if sys.platform != "darwin": + AF_BLUETOOTH = 32 + if sys.platform == "win32" and sys.version_info >= (3, 12): + AF_HYPERV = 34 + if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 12): + # FreeBSD >= 14.0 + AF_DIVERT = 44 + +AF_INET: Final = AddressFamily.AF_INET +AF_INET6: Final = AddressFamily.AF_INET6 +AF_APPLETALK: Final = AddressFamily.AF_APPLETALK +AF_DECnet: Final = 12 +AF_IPX: Final = AddressFamily.AF_IPX +AF_SNA: Final = AddressFamily.AF_SNA +AF_UNSPEC: Final = AddressFamily.AF_UNSPEC + +if sys.platform != "darwin": + AF_IRDA: Final = AddressFamily.AF_IRDA + +if sys.platform != "win32": + AF_ROUTE: Final = AddressFamily.AF_ROUTE + AF_UNIX: Final = AddressFamily.AF_UNIX + +if sys.platform == "darwin": + AF_SYSTEM: Final = AddressFamily.AF_SYSTEM + if sys.platform != "win32" and sys.platform != "darwin": - AF_BLUETOOTH: AddressFamily + AF_ASH: Final = AddressFamily.AF_ASH + AF_ATMPVC: Final = AddressFamily.AF_ATMPVC + AF_ATMSVC: Final = AddressFamily.AF_ATMSVC + AF_AX25: Final = AddressFamily.AF_AX25 + AF_BRIDGE: Final = AddressFamily.AF_BRIDGE + AF_ECONET: Final = AddressFamily.AF_ECONET + AF_KEY: Final = AddressFamily.AF_KEY + AF_LLC: Final = AddressFamily.AF_LLC + AF_NETBEUI: Final = AddressFamily.AF_NETBEUI + AF_NETROM: Final = AddressFamily.AF_NETROM + AF_PPPOX: Final = AddressFamily.AF_PPPOX + AF_ROSE: Final = AddressFamily.AF_ROSE + AF_SECURITY: Final = AddressFamily.AF_SECURITY + AF_WANPIPE: Final = AddressFamily.AF_WANPIPE + AF_X25: Final = AddressFamily.AF_X25 + +if sys.platform == "linux": + AF_CAN: Final = AddressFamily.AF_CAN + AF_PACKET: Final = AddressFamily.AF_PACKET + AF_RDS: Final = AddressFamily.AF_RDS + AF_TIPC: Final = AddressFamily.AF_TIPC + AF_ALG: Final = AddressFamily.AF_ALG + AF_NETLINK: Final = AddressFamily.AF_NETLINK + AF_VSOCK: Final = AddressFamily.AF_VSOCK + AF_QIPCRTR: Final = AddressFamily.AF_QIPCRTR + +if sys.platform != "linux": + AF_LINK: Final = AddressFamily.AF_LINK +if sys.platform != "darwin": + AF_BLUETOOTH: Final = AddressFamily.AF_BLUETOOTH +if sys.platform == "win32" and sys.version_info >= (3, 12): + AF_HYPERV: Final = AddressFamily.AF_HYPERV +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 12): + # FreeBSD >= 14.0 + AF_DIVERT: Final = AddressFamily.AF_DIVERT class SocketKind(IntEnum): - SOCK_STREAM: int - SOCK_DGRAM: int - SOCK_RAW: int - SOCK_RDM: int - SOCK_SEQPACKET: int - SOCK_CLOEXEC: int - SOCK_NONBLOCK: int - -SOCK_STREAM: SocketKind -SOCK_DGRAM: SocketKind -SOCK_RAW: SocketKind -SOCK_RDM: SocketKind -SOCK_SEQPACKET: SocketKind + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 + SOCK_RDM = 4 + SOCK_SEQPACKET = 5 + if sys.platform == "linux": + SOCK_CLOEXEC = 524288 + SOCK_NONBLOCK = 2048 + +SOCK_STREAM: Final = SocketKind.SOCK_STREAM +SOCK_DGRAM: Final = SocketKind.SOCK_DGRAM +SOCK_RAW: Final = SocketKind.SOCK_RAW +SOCK_RDM: Final = SocketKind.SOCK_RDM +SOCK_SEQPACKET: Final = SocketKind.SOCK_SEQPACKET if sys.platform == "linux": - SOCK_CLOEXEC: SocketKind - SOCK_NONBLOCK: SocketKind + SOCK_CLOEXEC: Final = SocketKind.SOCK_CLOEXEC + SOCK_NONBLOCK: Final = SocketKind.SOCK_NONBLOCK class MsgFlag(IntFlag): - MSG_CTRUNC: int - MSG_DONTROUTE: int - MSG_DONTWAIT: int - MSG_EOR: int - MSG_OOB: int - MSG_PEEK: int - MSG_TRUNC: int - MSG_WAITALL: int - -MSG_BCAST: MsgFlag -MSG_BTAG: MsgFlag -MSG_CMSG_CLOEXEC: MsgFlag -MSG_CONFIRM: MsgFlag -MSG_CTRUNC: MsgFlag -MSG_DONTROUTE: MsgFlag -MSG_DONTWAIT: MsgFlag -MSG_EOF: MsgFlag -MSG_EOR: MsgFlag -MSG_ERRQUEUE: MsgFlag -MSG_ETAG: MsgFlag -MSG_FASTOPEN: MsgFlag -MSG_MCAST: MsgFlag -MSG_MORE: MsgFlag -MSG_NOSIGNAL: MsgFlag -MSG_NOTIFICATION: MsgFlag -MSG_OOB: MsgFlag -MSG_PEEK: MsgFlag -MSG_TRUNC: MsgFlag -MSG_WAITALL: MsgFlag + MSG_CTRUNC = 8 + MSG_DONTROUTE = 4 + MSG_OOB = 1 + MSG_PEEK = 2 + MSG_TRUNC = 32 + MSG_WAITALL = 256 + if sys.platform == "win32": + MSG_BCAST = 1024 + MSG_MCAST = 2048 + + if sys.platform != "darwin": + MSG_ERRQUEUE = 8192 + + if sys.platform != "win32" and sys.platform != "darwin": + MSG_CMSG_CLOEXEC = 1073741821 + MSG_CONFIRM = 2048 + MSG_FASTOPEN = 536870912 + MSG_MORE = 32768 + + if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + MSG_NOTIFICATION = 8192 + + if sys.platform != "win32": + MSG_DONTWAIT = 64 + MSG_EOR = 128 + MSG_NOSIGNAL = 16384 # sometimes this exists on darwin, sometimes not + if sys.platform != "win32" and sys.platform != "linux": + MSG_EOF = 256 + +MSG_CTRUNC: Final = MsgFlag.MSG_CTRUNC +MSG_DONTROUTE: Final = MsgFlag.MSG_DONTROUTE +MSG_OOB: Final = MsgFlag.MSG_OOB +MSG_PEEK: Final = MsgFlag.MSG_PEEK +MSG_TRUNC: Final = MsgFlag.MSG_TRUNC +MSG_WAITALL: Final = MsgFlag.MSG_WAITALL + +if sys.platform == "win32": + MSG_BCAST: Final = MsgFlag.MSG_BCAST + MSG_MCAST: Final = MsgFlag.MSG_MCAST + +if sys.platform != "darwin": + MSG_ERRQUEUE: Final = MsgFlag.MSG_ERRQUEUE + +if sys.platform != "win32": + MSG_DONTWAIT: Final = MsgFlag.MSG_DONTWAIT + MSG_EOR: Final = MsgFlag.MSG_EOR + MSG_NOSIGNAL: Final = MsgFlag.MSG_NOSIGNAL # Sometimes this exists on darwin, sometimes not + +if sys.platform != "win32" and sys.platform != "darwin": + MSG_CMSG_CLOEXEC: Final = MsgFlag.MSG_CMSG_CLOEXEC + MSG_CONFIRM: Final = MsgFlag.MSG_CONFIRM + MSG_FASTOPEN: Final = MsgFlag.MSG_FASTOPEN + MSG_MORE: Final = MsgFlag.MSG_MORE + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + MSG_NOTIFICATION: Final = MsgFlag.MSG_NOTIFICATION + +if sys.platform != "win32" and sys.platform != "linux": + MSG_EOF: Final = MsgFlag.MSG_EOF class AddressInfo(IntFlag): - AI_ADDRCONFIG: int - AI_ALL: int - AI_CANONNAME: int - AI_NUMERICHOST: int - AI_NUMERICSERV: int - AI_PASSIVE: int - AI_V4MAPPED: int - -AI_ADDRCONFIG: AddressInfo -AI_ALL: AddressInfo -AI_CANONNAME: AddressInfo -AI_DEFAULT: AddressInfo -AI_MASK: AddressInfo -AI_NUMERICHOST: AddressInfo -AI_NUMERICSERV: AddressInfo -AI_PASSIVE: AddressInfo -AI_V4MAPPED: AddressInfo -AI_V4MAPPED_CFG: AddressInfo + AI_ADDRCONFIG = 32 + AI_ALL = 16 + AI_CANONNAME = 2 + AI_NUMERICHOST = 4 + AI_NUMERICSERV = 1024 + AI_PASSIVE = 1 + AI_V4MAPPED = 8 + if sys.platform != "win32" and sys.platform != "linux": + AI_DEFAULT = 1536 + AI_MASK = 5127 + AI_V4MAPPED_CFG = 512 + +AI_ADDRCONFIG: Final = AddressInfo.AI_ADDRCONFIG +AI_ALL: Final = AddressInfo.AI_ALL +AI_CANONNAME: Final = AddressInfo.AI_CANONNAME +AI_NUMERICHOST: Final = AddressInfo.AI_NUMERICHOST +AI_NUMERICSERV: Final = AddressInfo.AI_NUMERICSERV +AI_PASSIVE: Final = AddressInfo.AI_PASSIVE +AI_V4MAPPED: Final = AddressInfo.AI_V4MAPPED + +if sys.platform != "win32" and sys.platform != "linux": + AI_DEFAULT: Final = AddressInfo.AI_DEFAULT + AI_MASK: Final = AddressInfo.AI_MASK + AI_V4MAPPED_CFG: Final = AddressInfo.AI_V4MAPPED_CFG if sys.platform == "win32": errorTab: dict[int, str] # undocumented +@type_check_only +class _SendableFile(Protocol): + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> object: ... + + # optional fields: + # + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + class socket(_socket.socket): + __slots__ = ["__weakref__", "_io_refs", "_closed"] def __init__( - self, family: AddressFamily | int = ..., type: SocketKind | int = ..., proto: int = ..., fileno: int | None = ... + self, family: AddressFamily | int = -1, type: SocketKind | int = -1, proto: int = -1, fileno: int | None = None ) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: object) -> None: ... - def dup(self: _T) -> _T: ... # noqa: F811 + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def dup(self) -> Self: ... def accept(self) -> tuple[socket, _RetAddress]: ... + # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded @overload def makefile( self, - mode: Literal["r", "w", "rw", "wr", ""] = ..., - buffering: int | None = ..., + mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Literal[0], + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> SocketIO: ... + @overload + def makefile( + self, + mode: Literal["rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Literal[-1, 1] | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> BufferedRWPair: ... + @overload + def makefile( + self, + mode: Literal["rb", "br"], + buffering: Literal[-1, 1] | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> BufferedReader: ... + @overload + def makefile( + self, + mode: Literal["wb", "bw"], + buffering: Literal[-1, 1] | None = None, *, - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - ) -> TextIO: ... + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> BufferedWriter: ... @overload def makefile( self, mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], - buffering: int | None = ..., + buffering: int, *, - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - ) -> BinaryIO: ... - def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> IOBase: ... + @overload + def makefile( + self, + mode: Literal["r", "w", "rw", "wr", ""] = "r", + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> TextIOWrapper: ... + + def sendfile(self, file: _SendableFile, offset: int = 0, count: int | None = None) -> int: ... @property - def family(self) -> AddressFamily: ... # type: ignore[override] + def family(self) -> AddressFamily: ... @property - def type(self) -> SocketKind: ... # type: ignore[override] + def type(self) -> SocketKind: ... def get_inheritable(self) -> bool: ... def set_inheritable(self, inheritable: bool) -> None: ... -def fromfd(fd: _FD, family: AddressFamily | int, type: SocketKind | int, proto: int = ...) -> socket: ... +def fromfd(fd: SupportsIndex, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: ... if sys.platform != "win32": - if sys.version_info >= (3, 9): - # flags and address appear to be unused in send_fds and recv_fds - def send_fds( - sock: socket, buffers: Iterable[bytes], fds: bytes | Iterable[int], flags: int = ..., address: None = ... - ) -> int: ... - def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = ...) -> tuple[bytes, list[int], int, Any]: ... + def send_fds( + sock: socket, buffers: Iterable[ReadableBuffer], fds: Iterable[int], flags: Unused = 0, address: Unused = None + ) -> int: ... + def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = 0) -> tuple[bytes, list[int], int, Any]: ... if sys.platform == "win32": def fromshare(info: bytes) -> socket: ... if sys.platform == "win32": - def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> tuple[socket, socket]: ... + def socketpair(family: int = ..., type: int = ..., proto: int = 0) -> tuple[socket, socket]: ... else: def socketpair( - family: int | AddressFamily | None = ..., type: SocketType | int = ..., proto: int = ... + family: int | AddressFamily | None = None, type: SocketKind | int = ..., proto: int = 0 ) -> tuple[socket, socket]: ... class SocketIO(RawIOBase): @@ -606,25 +1555,33 @@ class SocketIO(RawIOBase): @property def mode(self) -> Literal["rb", "wb", "rwb"]: ... -def getfqdn(name: str = ...) -> str: ... -def create_connection( - address: tuple[str | None, int], - timeout: float | None = ..., # noqa: F811 - source_address: tuple[bytearray | bytes | str, int] | None = ..., -) -> socket: ... +def getfqdn(name: str = "") -> str: ... -if sys.version_info >= (3, 8): - def has_dualstack_ipv6() -> bool: ... - def create_server( - address: _Address, *, family: int = ..., backlog: int | None = ..., reuse_port: bool = ..., dualstack_ipv6: bool = ... +if sys.version_info >= (3, 11): + def create_connection( + address: tuple[str | None, bytes | str | int | None], + timeout: float | None = ..., + source_address: _Address | None = None, + *, + all_errors: bool = False, ) -> socket: ... -# the 5th tuple item is an address +else: + def create_connection( + address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None + ) -> socket: ... + +def has_dualstack_ipv6() -> bool: ... +def create_server( + address: _Address, *, family: int = ..., backlog: int | None = None, reuse_port: bool = False, dualstack_ipv6: bool = False +) -> socket: ... + +# The 5th tuple item is the socket address, for IP4, IP6, or IP6 if Python is compiled with --disable-ipv6, respectively. +_GetAddrInfoResult: TypeAlias = list[ + tuple[Literal[AddressFamily.AF_INET], SocketKind, int, str, tuple[str, int]] + | tuple[Literal[AddressFamily.AF_INET6], SocketKind, int, str, tuple[str, int, int, int] | tuple[int, bytes]] +] + def getaddrinfo( - host: bytearray | bytes | str | None, - port: str | int | None, - family: int = ..., - type: int = ..., - proto: int = ..., - flags: int = ..., -) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... + host: bytes | str | None, port: bytes | str | int | None, family: int = 0, type: int = 0, proto: int = 0, flags: int = 0 +) -> _GetAddrInfoResult: ... diff --git a/stdlib/socketserver.pyi b/stdlib/socketserver.pyi index c64408cfab07..05e0025d6a15 100644 --- a/stdlib/socketserver.pyi +++ b/stdlib/socketserver.pyi @@ -1,89 +1,109 @@ import sys import types -from _typeshed import Self +from _socket import _Address, _RetAddress +from _typeshed import ReadableBuffer +from collections.abc import Callable +from io import BufferedIOBase from socket import socket as _socket -from typing import Any, BinaryIO, Callable, ClassVar, Tuple, Type, TypeVar, Union +from typing import Any, ClassVar, TypeAlias +from typing_extensions import Self -_T = TypeVar("_T") -_RequestType = Union[_socket, Tuple[bytes, _socket]] -_AddressType = Union[Tuple[str, int], str] +__all__ = [ + "BaseServer", + "TCPServer", + "UDPServer", + "ThreadingUDPServer", + "ThreadingTCPServer", + "BaseRequestHandler", + "StreamRequestHandler", + "DatagramRequestHandler", + "ThreadingMixIn", +] +if sys.platform != "win32": + __all__ += [ + "ForkingMixIn", + "ForkingTCPServer", + "ForkingUDPServer", + "ThreadingUnixDatagramServer", + "ThreadingUnixStreamServer", + "UnixDatagramServer", + "UnixStreamServer", + ] + if sys.version_info >= (3, 12): + __all__ += ["ForkingUnixStreamServer", "ForkingUnixDatagramServer"] + +_RequestType: TypeAlias = _socket | tuple[bytes, _socket] +_AfUnixAddress: TypeAlias = str | ReadableBuffer # address acceptable for an AF_UNIX socket +_AfInetAddress: TypeAlias = tuple[str | bytes | bytearray, int] # address acceptable for an AF_INET socket +_AfInet6Address: TypeAlias = tuple[str | bytes | bytearray, int, int, int] # address acceptable for an AF_INET6 socket +# This can possibly be generic at some point: class BaseServer: - address_family: int - RequestHandlerClass: Callable[..., BaseRequestHandler] - server_address: tuple[str, int] - socket: _socket - allow_reuse_address: bool - request_queue_size: int - socket_type: int + server_address: _Address timeout: float | None - def __init__(self, server_address: Any, RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... - def fileno(self) -> int: ... + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler] + def __init__( + self, server_address: _Address, RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler] + ) -> None: ... def handle_request(self) -> None: ... - def serve_forever(self, poll_interval: float = ...) -> None: ... + def serve_forever(self, poll_interval: float = 0.5) -> None: ... def shutdown(self) -> None: ... def server_close(self) -> None: ... - def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def get_request(self) -> tuple[Any, Any]: ... - def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... + def finish_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... + def get_request(self) -> tuple[Any, Any]: ... # Not implemented here, but expected to exist on subclasses + def handle_error(self, request: _RequestType, client_address: _RetAddress) -> None: ... def handle_timeout(self) -> None: ... - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... def server_activate(self) -> None: ... - def server_bind(self) -> None: ... - def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... - def __enter__(self: Self) -> Self: ... + def verify_request(self, request: _RequestType, client_address: _RetAddress) -> bool: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def service_actions(self) -> None: ... def shutdown_request(self, request: _RequestType) -> None: ... # undocumented def close_request(self, request: _RequestType) -> None: ... # undocumented class TCPServer(BaseServer): + address_family: int + socket: _socket + allow_reuse_address: bool + request_queue_size: int + socket_type: int + if sys.version_info >= (3, 11): + allow_reuse_port: bool + server_address: _AfInetAddress | _AfInet6Address def __init__( self, - server_address: tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., + server_address: _AfInetAddress | _AfInet6Address, + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], + bind_and_activate: bool = True, ) -> None: ... - def get_request(self) -> tuple[_socket, Any]: ... - def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... - def shutdown_request(self, request: _RequestType) -> None: ... # undocumented - def close_request(self, request: _RequestType) -> None: ... # undocumented + def fileno(self) -> int: ... + def get_request(self) -> tuple[_socket, _RetAddress]: ... + def server_bind(self) -> None: ... -class UDPServer(BaseServer): +class UDPServer(TCPServer): max_packet_size: ClassVar[int] - def __init__( - self, - server_address: tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., - ) -> None: ... - def get_request(self) -> tuple[tuple[bytes, _socket], Any]: ... - def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... - def shutdown_request(self, request: _RequestType) -> None: ... # undocumented - def close_request(self, request: _RequestType) -> None: ... # undocumented + def get_request(self) -> tuple[tuple[bytes, _socket], _RetAddress]: ... # type: ignore[override] if sys.platform != "win32": - class UnixStreamServer(BaseServer): + class UnixStreamServer(TCPServer): + server_address: _AfUnixAddress # type: ignore[assignment] def __init__( self, - server_address: str | bytes, - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., + server_address: _AfUnixAddress, + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], + bind_and_activate: bool = True, ) -> None: ... - class UnixDatagramServer(BaseServer): + + class UnixDatagramServer(UDPServer): + server_address: _AfUnixAddress # type: ignore[assignment] def __init__( self, - server_address: str | bytes, - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., + server_address: _AfUnixAddress, + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], + bind_and_activate: bool = True, ) -> None: ... if sys.platform != "win32": @@ -91,25 +111,26 @@ if sys.platform != "win32": timeout: float | None # undocumented active_children: set[int] | None # undocumented max_children: int # undocumented - if sys.version_info >= (3, 7): - block_on_close: bool - def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented + block_on_close: bool + def collect_children(self, *, blocking: bool = False) -> None: ... # undocumented def handle_timeout(self) -> None: ... # undocumented def service_actions(self) -> None: ... # undocumented - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... def server_close(self) -> None: ... class ThreadingMixIn: daemon_threads: bool - if sys.version_info >= (3, 7): - block_on_close: bool - def process_request_thread(self, request: _RequestType, client_address: _AddressType) -> None: ... # undocumented - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + block_on_close: bool + def process_request_thread(self, request: _RequestType, client_address: _RetAddress) -> None: ... # undocumented + def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... def server_close(self) -> None: ... if sys.platform != "win32": class ForkingTCPServer(ForkingMixIn, TCPServer): ... class ForkingUDPServer(ForkingMixIn, UDPServer): ... + if sys.version_info >= (3, 12): + class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): ... + class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): ... class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... @@ -119,16 +140,16 @@ if sys.platform != "win32": class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... class BaseRequestHandler: - # Those are technically of types, respectively: - # * _RequestType - # * _AddressType - # But there are some concerns that having unions here would cause + # `request` is technically of type _RequestType, + # but there are some concerns that having a union here would cause # too much inconvenience to people using it (see # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + # + # Note also that _RetAddress is also just an alias for `Any` request: Any - client_address: Any + client_address: _RetAddress server: BaseServer - def __init__(self, request: _RequestType, client_address: _AddressType, server: BaseServer) -> None: ... + def __init__(self, request: _RequestType, client_address: _RetAddress, server: BaseServer) -> None: ... def setup(self) -> None: ... def handle(self) -> None: ... def finish(self) -> None: ... @@ -138,12 +159,12 @@ class StreamRequestHandler(BaseRequestHandler): wbufsize: ClassVar[int] # undocumented timeout: ClassVar[float | None] # undocumented disable_nagle_algorithm: ClassVar[bool] # undocumented - connection: _socket # undocumented - rfile: BinaryIO - wfile: BinaryIO + connection: Any # undocumented + rfile: BufferedIOBase + wfile: BufferedIOBase class DatagramRequestHandler(BaseRequestHandler): - packet: _socket # undocumented + packet: bytes # undocumented socket: _socket # undocumented - rfile: BinaryIO - wfile: BinaryIO + rfile: BufferedIOBase + wfile: BufferedIOBase diff --git a/stdlib/spwd.pyi b/stdlib/spwd.pyi index fc3d8ce90021..0a06cdfeef64 100644 --- a/stdlib/spwd.pyi +++ b/stdlib/spwd.pyi @@ -1,27 +1,45 @@ +import sys from _typeshed import structseq -from typing import Any, Tuple -from typing_extensions import final +from typing import Any, Final, final -@final -class struct_spwd(structseq[Any], Tuple[str, str, int, int, int, int, int, int, int]): - @property - def sp_namp(self) -> str: ... - @property - def sp_pwdp(self) -> str: ... - @property - def sp_lstchg(self) -> int: ... - @property - def sp_min(self) -> int: ... - @property - def sp_max(self) -> int: ... - @property - def sp_warn(self) -> int: ... - @property - def sp_inact(self) -> int: ... - @property - def sp_expire(self) -> int: ... - @property - def sp_flag(self) -> int: ... +if sys.platform != "win32": + @final + class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]): + __match_args__: Final = ( + "sp_namp", + "sp_pwdp", + "sp_lstchg", + "sp_min", + "sp_max", + "sp_warn", + "sp_inact", + "sp_expire", + "sp_flag", + ) -def getspall() -> list[struct_spwd]: ... -def getspnam(__arg: str) -> struct_spwd: ... + @property + def sp_namp(self) -> str: ... + @property + def sp_pwdp(self) -> str: ... + @property + def sp_lstchg(self) -> int: ... + @property + def sp_min(self) -> int: ... + @property + def sp_max(self) -> int: ... + @property + def sp_warn(self) -> int: ... + @property + def sp_inact(self) -> int: ... + @property + def sp_expire(self) -> int: ... + @property + def sp_flag(self) -> int: ... + # Deprecated aliases below. + @property + def sp_nam(self) -> str: ... + @property + def sp_pwd(self) -> str: ... + + def getspall() -> list[struct_spwd]: ... + def getspnam(arg: str, /) -> struct_spwd: ... diff --git a/stdlib/sqlite3/__init__.pyi b/stdlib/sqlite3/__init__.pyi index d5d20d67b58e..80a02079dd05 100644 --- a/stdlib/sqlite3/__init__.pyi +++ b/stdlib/sqlite3/__init__.pyi @@ -1 +1,510 @@ -from sqlite3.dbapi2 import * # noqa: F403 +import sys +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence +from sqlite3.dbapi2 import ( + PARSE_COLNAMES as PARSE_COLNAMES, + PARSE_DECLTYPES as PARSE_DECLTYPES, + SQLITE_ALTER_TABLE as SQLITE_ALTER_TABLE, + SQLITE_ANALYZE as SQLITE_ANALYZE, + SQLITE_ATTACH as SQLITE_ATTACH, + SQLITE_CREATE_INDEX as SQLITE_CREATE_INDEX, + SQLITE_CREATE_TABLE as SQLITE_CREATE_TABLE, + SQLITE_CREATE_TEMP_INDEX as SQLITE_CREATE_TEMP_INDEX, + SQLITE_CREATE_TEMP_TABLE as SQLITE_CREATE_TEMP_TABLE, + SQLITE_CREATE_TEMP_TRIGGER as SQLITE_CREATE_TEMP_TRIGGER, + SQLITE_CREATE_TEMP_VIEW as SQLITE_CREATE_TEMP_VIEW, + SQLITE_CREATE_TRIGGER as SQLITE_CREATE_TRIGGER, + SQLITE_CREATE_VIEW as SQLITE_CREATE_VIEW, + SQLITE_CREATE_VTABLE as SQLITE_CREATE_VTABLE, + SQLITE_DELETE as SQLITE_DELETE, + SQLITE_DENY as SQLITE_DENY, + SQLITE_DETACH as SQLITE_DETACH, + SQLITE_DONE as SQLITE_DONE, + SQLITE_DROP_INDEX as SQLITE_DROP_INDEX, + SQLITE_DROP_TABLE as SQLITE_DROP_TABLE, + SQLITE_DROP_TEMP_INDEX as SQLITE_DROP_TEMP_INDEX, + SQLITE_DROP_TEMP_TABLE as SQLITE_DROP_TEMP_TABLE, + SQLITE_DROP_TEMP_TRIGGER as SQLITE_DROP_TEMP_TRIGGER, + SQLITE_DROP_TEMP_VIEW as SQLITE_DROP_TEMP_VIEW, + SQLITE_DROP_TRIGGER as SQLITE_DROP_TRIGGER, + SQLITE_DROP_VIEW as SQLITE_DROP_VIEW, + SQLITE_DROP_VTABLE as SQLITE_DROP_VTABLE, + SQLITE_FUNCTION as SQLITE_FUNCTION, + SQLITE_IGNORE as SQLITE_IGNORE, + SQLITE_INSERT as SQLITE_INSERT, + SQLITE_OK as SQLITE_OK, + SQLITE_PRAGMA as SQLITE_PRAGMA, + SQLITE_READ as SQLITE_READ, + SQLITE_RECURSIVE as SQLITE_RECURSIVE, + SQLITE_REINDEX as SQLITE_REINDEX, + SQLITE_SAVEPOINT as SQLITE_SAVEPOINT, + SQLITE_SELECT as SQLITE_SELECT, + SQLITE_TRANSACTION as SQLITE_TRANSACTION, + SQLITE_UPDATE as SQLITE_UPDATE, + Binary as Binary, + Date as Date, + DateFromTicks as DateFromTicks, + Time as Time, + TimeFromTicks as TimeFromTicks, + TimestampFromTicks as TimestampFromTicks, + adapt as adapt, + adapters as adapters, + apilevel as apilevel, + complete_statement as complete_statement, + connect as connect, + converters as converters, + enable_callback_tracebacks as enable_callback_tracebacks, + paramstyle as paramstyle, + register_adapter as register_adapter, + register_converter as register_converter, + sqlite_version as sqlite_version, + sqlite_version_info as sqlite_version_info, + threadsafety as threadsafety, +) +from types import TracebackType +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +if sys.version_info < (3, 14): + from sqlite3.dbapi2 import version_info as version_info + +if sys.version_info >= (3, 15): + from sqlite3.dbapi2 import SQLITE_KEYWORDS as SQLITE_KEYWORDS + +if sys.version_info >= (3, 12): + from sqlite3.dbapi2 import ( + LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL, + SQLITE_DBCONFIG_DEFENSIVE as SQLITE_DBCONFIG_DEFENSIVE, + SQLITE_DBCONFIG_DQS_DDL as SQLITE_DBCONFIG_DQS_DDL, + SQLITE_DBCONFIG_DQS_DML as SQLITE_DBCONFIG_DQS_DML, + SQLITE_DBCONFIG_ENABLE_FKEY as SQLITE_DBCONFIG_ENABLE_FKEY, + SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER as SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION as SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, + SQLITE_DBCONFIG_ENABLE_QPSG as SQLITE_DBCONFIG_ENABLE_QPSG, + SQLITE_DBCONFIG_ENABLE_TRIGGER as SQLITE_DBCONFIG_ENABLE_TRIGGER, + SQLITE_DBCONFIG_ENABLE_VIEW as SQLITE_DBCONFIG_ENABLE_VIEW, + SQLITE_DBCONFIG_LEGACY_ALTER_TABLE as SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, + SQLITE_DBCONFIG_LEGACY_FILE_FORMAT as SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, + SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE as SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, + SQLITE_DBCONFIG_RESET_DATABASE as SQLITE_DBCONFIG_RESET_DATABASE, + SQLITE_DBCONFIG_TRIGGER_EQP as SQLITE_DBCONFIG_TRIGGER_EQP, + SQLITE_DBCONFIG_TRUSTED_SCHEMA as SQLITE_DBCONFIG_TRUSTED_SCHEMA, + SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA, + ) + +if sys.version_info >= (3, 11): + from sqlite3.dbapi2 import ( + SQLITE_ABORT as SQLITE_ABORT, + SQLITE_ABORT_ROLLBACK as SQLITE_ABORT_ROLLBACK, + SQLITE_AUTH as SQLITE_AUTH, + SQLITE_AUTH_USER as SQLITE_AUTH_USER, + SQLITE_BUSY as SQLITE_BUSY, + SQLITE_BUSY_RECOVERY as SQLITE_BUSY_RECOVERY, + SQLITE_BUSY_SNAPSHOT as SQLITE_BUSY_SNAPSHOT, + SQLITE_BUSY_TIMEOUT as SQLITE_BUSY_TIMEOUT, + SQLITE_CANTOPEN as SQLITE_CANTOPEN, + SQLITE_CANTOPEN_CONVPATH as SQLITE_CANTOPEN_CONVPATH, + SQLITE_CANTOPEN_DIRTYWAL as SQLITE_CANTOPEN_DIRTYWAL, + SQLITE_CANTOPEN_FULLPATH as SQLITE_CANTOPEN_FULLPATH, + SQLITE_CANTOPEN_ISDIR as SQLITE_CANTOPEN_ISDIR, + SQLITE_CANTOPEN_NOTEMPDIR as SQLITE_CANTOPEN_NOTEMPDIR, + SQLITE_CANTOPEN_SYMLINK as SQLITE_CANTOPEN_SYMLINK, + SQLITE_CONSTRAINT as SQLITE_CONSTRAINT, + SQLITE_CONSTRAINT_CHECK as SQLITE_CONSTRAINT_CHECK, + SQLITE_CONSTRAINT_COMMITHOOK as SQLITE_CONSTRAINT_COMMITHOOK, + SQLITE_CONSTRAINT_FOREIGNKEY as SQLITE_CONSTRAINT_FOREIGNKEY, + SQLITE_CONSTRAINT_FUNCTION as SQLITE_CONSTRAINT_FUNCTION, + SQLITE_CONSTRAINT_NOTNULL as SQLITE_CONSTRAINT_NOTNULL, + SQLITE_CONSTRAINT_PINNED as SQLITE_CONSTRAINT_PINNED, + SQLITE_CONSTRAINT_PRIMARYKEY as SQLITE_CONSTRAINT_PRIMARYKEY, + SQLITE_CONSTRAINT_ROWID as SQLITE_CONSTRAINT_ROWID, + SQLITE_CONSTRAINT_TRIGGER as SQLITE_CONSTRAINT_TRIGGER, + SQLITE_CONSTRAINT_UNIQUE as SQLITE_CONSTRAINT_UNIQUE, + SQLITE_CONSTRAINT_VTAB as SQLITE_CONSTRAINT_VTAB, + SQLITE_CORRUPT as SQLITE_CORRUPT, + SQLITE_CORRUPT_INDEX as SQLITE_CORRUPT_INDEX, + SQLITE_CORRUPT_SEQUENCE as SQLITE_CORRUPT_SEQUENCE, + SQLITE_CORRUPT_VTAB as SQLITE_CORRUPT_VTAB, + SQLITE_EMPTY as SQLITE_EMPTY, + SQLITE_ERROR as SQLITE_ERROR, + SQLITE_ERROR_MISSING_COLLSEQ as SQLITE_ERROR_MISSING_COLLSEQ, + SQLITE_ERROR_RETRY as SQLITE_ERROR_RETRY, + SQLITE_ERROR_SNAPSHOT as SQLITE_ERROR_SNAPSHOT, + SQLITE_FORMAT as SQLITE_FORMAT, + SQLITE_FULL as SQLITE_FULL, + SQLITE_INTERNAL as SQLITE_INTERNAL, + SQLITE_INTERRUPT as SQLITE_INTERRUPT, + SQLITE_IOERR as SQLITE_IOERR, + SQLITE_IOERR_ACCESS as SQLITE_IOERR_ACCESS, + SQLITE_IOERR_AUTH as SQLITE_IOERR_AUTH, + SQLITE_IOERR_BEGIN_ATOMIC as SQLITE_IOERR_BEGIN_ATOMIC, + SQLITE_IOERR_BLOCKED as SQLITE_IOERR_BLOCKED, + SQLITE_IOERR_CHECKRESERVEDLOCK as SQLITE_IOERR_CHECKRESERVEDLOCK, + SQLITE_IOERR_CLOSE as SQLITE_IOERR_CLOSE, + SQLITE_IOERR_COMMIT_ATOMIC as SQLITE_IOERR_COMMIT_ATOMIC, + SQLITE_IOERR_CONVPATH as SQLITE_IOERR_CONVPATH, + SQLITE_IOERR_CORRUPTFS as SQLITE_IOERR_CORRUPTFS, + SQLITE_IOERR_DATA as SQLITE_IOERR_DATA, + SQLITE_IOERR_DELETE as SQLITE_IOERR_DELETE, + SQLITE_IOERR_DELETE_NOENT as SQLITE_IOERR_DELETE_NOENT, + SQLITE_IOERR_DIR_CLOSE as SQLITE_IOERR_DIR_CLOSE, + SQLITE_IOERR_DIR_FSYNC as SQLITE_IOERR_DIR_FSYNC, + SQLITE_IOERR_FSTAT as SQLITE_IOERR_FSTAT, + SQLITE_IOERR_FSYNC as SQLITE_IOERR_FSYNC, + SQLITE_IOERR_GETTEMPPATH as SQLITE_IOERR_GETTEMPPATH, + SQLITE_IOERR_LOCK as SQLITE_IOERR_LOCK, + SQLITE_IOERR_MMAP as SQLITE_IOERR_MMAP, + SQLITE_IOERR_NOMEM as SQLITE_IOERR_NOMEM, + SQLITE_IOERR_RDLOCK as SQLITE_IOERR_RDLOCK, + SQLITE_IOERR_READ as SQLITE_IOERR_READ, + SQLITE_IOERR_ROLLBACK_ATOMIC as SQLITE_IOERR_ROLLBACK_ATOMIC, + SQLITE_IOERR_SEEK as SQLITE_IOERR_SEEK, + SQLITE_IOERR_SHMLOCK as SQLITE_IOERR_SHMLOCK, + SQLITE_IOERR_SHMMAP as SQLITE_IOERR_SHMMAP, + SQLITE_IOERR_SHMOPEN as SQLITE_IOERR_SHMOPEN, + SQLITE_IOERR_SHMSIZE as SQLITE_IOERR_SHMSIZE, + SQLITE_IOERR_SHORT_READ as SQLITE_IOERR_SHORT_READ, + SQLITE_IOERR_TRUNCATE as SQLITE_IOERR_TRUNCATE, + SQLITE_IOERR_UNLOCK as SQLITE_IOERR_UNLOCK, + SQLITE_IOERR_VNODE as SQLITE_IOERR_VNODE, + SQLITE_IOERR_WRITE as SQLITE_IOERR_WRITE, + SQLITE_LIMIT_ATTACHED as SQLITE_LIMIT_ATTACHED, + SQLITE_LIMIT_COLUMN as SQLITE_LIMIT_COLUMN, + SQLITE_LIMIT_COMPOUND_SELECT as SQLITE_LIMIT_COMPOUND_SELECT, + SQLITE_LIMIT_EXPR_DEPTH as SQLITE_LIMIT_EXPR_DEPTH, + SQLITE_LIMIT_FUNCTION_ARG as SQLITE_LIMIT_FUNCTION_ARG, + SQLITE_LIMIT_LENGTH as SQLITE_LIMIT_LENGTH, + SQLITE_LIMIT_LIKE_PATTERN_LENGTH as SQLITE_LIMIT_LIKE_PATTERN_LENGTH, + SQLITE_LIMIT_SQL_LENGTH as SQLITE_LIMIT_SQL_LENGTH, + SQLITE_LIMIT_TRIGGER_DEPTH as SQLITE_LIMIT_TRIGGER_DEPTH, + SQLITE_LIMIT_VARIABLE_NUMBER as SQLITE_LIMIT_VARIABLE_NUMBER, + SQLITE_LIMIT_VDBE_OP as SQLITE_LIMIT_VDBE_OP, + SQLITE_LIMIT_WORKER_THREADS as SQLITE_LIMIT_WORKER_THREADS, + SQLITE_LOCKED as SQLITE_LOCKED, + SQLITE_LOCKED_SHAREDCACHE as SQLITE_LOCKED_SHAREDCACHE, + SQLITE_LOCKED_VTAB as SQLITE_LOCKED_VTAB, + SQLITE_MISMATCH as SQLITE_MISMATCH, + SQLITE_MISUSE as SQLITE_MISUSE, + SQLITE_NOLFS as SQLITE_NOLFS, + SQLITE_NOMEM as SQLITE_NOMEM, + SQLITE_NOTADB as SQLITE_NOTADB, + SQLITE_NOTFOUND as SQLITE_NOTFOUND, + SQLITE_NOTICE as SQLITE_NOTICE, + SQLITE_NOTICE_RECOVER_ROLLBACK as SQLITE_NOTICE_RECOVER_ROLLBACK, + SQLITE_NOTICE_RECOVER_WAL as SQLITE_NOTICE_RECOVER_WAL, + SQLITE_OK_LOAD_PERMANENTLY as SQLITE_OK_LOAD_PERMANENTLY, + SQLITE_OK_SYMLINK as SQLITE_OK_SYMLINK, + SQLITE_PERM as SQLITE_PERM, + SQLITE_PROTOCOL as SQLITE_PROTOCOL, + SQLITE_RANGE as SQLITE_RANGE, + SQLITE_READONLY as SQLITE_READONLY, + SQLITE_READONLY_CANTINIT as SQLITE_READONLY_CANTINIT, + SQLITE_READONLY_CANTLOCK as SQLITE_READONLY_CANTLOCK, + SQLITE_READONLY_DBMOVED as SQLITE_READONLY_DBMOVED, + SQLITE_READONLY_DIRECTORY as SQLITE_READONLY_DIRECTORY, + SQLITE_READONLY_RECOVERY as SQLITE_READONLY_RECOVERY, + SQLITE_READONLY_ROLLBACK as SQLITE_READONLY_ROLLBACK, + SQLITE_ROW as SQLITE_ROW, + SQLITE_SCHEMA as SQLITE_SCHEMA, + SQLITE_TOOBIG as SQLITE_TOOBIG, + SQLITE_WARNING as SQLITE_WARNING, + SQLITE_WARNING_AUTOINDEX as SQLITE_WARNING_AUTOINDEX, + ) + +if sys.version_info < (3, 12): + from sqlite3.dbapi2 import enable_shared_cache as enable_shared_cache, version as version + +_CursorT = TypeVar("_CursorT", bound=Cursor) +_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None +# Data that is passed through adapters can be of any type accepted by an adapter. +_AdaptedInputData: TypeAlias = _SqliteData | Any +# The Mapping must really be a dict, but making it invariant is too annoying. +_Parameters: TypeAlias = SupportsLenAndGetItem[_AdaptedInputData] | Mapping[str, _AdaptedInputData] +# Controls the legacy transaction handling mode of sqlite3. +_IsolationLevel: TypeAlias = Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None +_RowFactoryOptions: TypeAlias = type[Row] | Callable[[Cursor, tuple[Any, ...]], object] | None + +@type_check_only +class _AnyParamWindowAggregateClass(Protocol): + def step(self, *args: Any) -> object: ... + def inverse(self, *args: Any) -> object: ... + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +@type_check_only +class _WindowAggregateClass(Protocol): + step: Callable[..., object] + inverse: Callable[..., object] + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +@type_check_only +class _AggregateProtocol(Protocol): + def step(self, value: int, /) -> object: ... + def finalize(self) -> int: ... + +@type_check_only +class _SingleParamWindowAggregateClass(Protocol): + def step(self, param: Any, /) -> object: ... + def inverse(self, param: Any, /) -> object: ... + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +# These classes are implemented in the C module _sqlite3. At runtime, they're imported +# from there into sqlite3.dbapi2 and from that module to here. However, they +# consider themselves to live in the sqlite3.* namespace, so we'll define them here. + +class Error(Exception): + if sys.version_info >= (3, 11): + sqlite_errorcode: int + sqlite_errorname: str + +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InterfaceError(Error): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class Warning(Exception): ... + +_DataError: TypeAlias = DataError +_DatabaseError: TypeAlias = DatabaseError +_Error: TypeAlias = Error +_IntegrityError: TypeAlias = IntegrityError +_InterfaceError: TypeAlias = InterfaceError +_InternalError: TypeAlias = InternalError +_NotSupportedError: TypeAlias = NotSupportedError +_OperationalError: TypeAlias = OperationalError +_ProgrammingError: TypeAlias = ProgrammingError +_Warning: TypeAlias = Warning + +@disjoint_base +class Connection: + @property + def DataError(self) -> type[_DataError]: ... + @property + def DatabaseError(self) -> type[_DatabaseError]: ... + @property + def Error(self) -> type[_Error]: ... + @property + def IntegrityError(self) -> type[_IntegrityError]: ... + @property + def InterfaceError(self) -> type[_InterfaceError]: ... + @property + def InternalError(self) -> type[_InternalError]: ... + @property + def NotSupportedError(self) -> type[_NotSupportedError]: ... + @property + def OperationalError(self) -> type[_OperationalError]: ... + @property + def ProgrammingError(self) -> type[_ProgrammingError]: ... + @property + def Warning(self) -> type[_Warning]: ... + @property + def in_transaction(self) -> bool: ... + isolation_level: _IsolationLevel + @property + def total_changes(self) -> int: ... + if sys.version_info >= (3, 12): + @property + def autocommit(self) -> int: ... + @autocommit.setter + def autocommit(self, val: int) -> None: ... + + row_factory: _RowFactoryOptions + text_factory: Any + if sys.version_info >= (3, 12): + def __init__( + self, + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + factory: type[Connection] | None = ..., + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> None: ... + else: + def __init__( + self, + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + factory: type[Connection] | None = ..., + cached_statements: int = 128, + uri: bool = False, + ) -> None: ... + + def close(self) -> None: ... + if sys.version_info >= (3, 11): + def blobopen(self, table: str, column: str, row: int, /, *, readonly: bool = False, name: str = "main") -> Blob: ... + + def commit(self) -> None: ... + if sys.version_info >= (3, 15): + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol], /) -> None: ... + else: + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... + if sys.version_info >= (3, 11): + # num_params determines how many params will be passed to the aggregate class. We provide an overload + # for the case where num_params = 1, which is expected to be the common case. + @overload + def create_window_function( + self, name: str, num_params: Literal[1], aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None, / + ) -> None: ... + # And for num_params = -1, which means the aggregate must accept any number of parameters. + @overload + def create_window_function( + self, name: str, num_params: Literal[-1], aggregate_class: Callable[[], _AnyParamWindowAggregateClass] | None, / + ) -> None: ... + @overload + def create_window_function( + self, name: str, num_params: int, aggregate_class: Callable[[], _WindowAggregateClass] | None, / + ) -> None: ... + + def create_collation(self, name: str, callback: Callable[[str, str], SupportsIndex] | None, /) -> None: ... + if sys.version_info >= (3, 15): + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, /, *, deterministic: bool = False + ) -> None: ... + else: + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False + ) -> None: ... + + @overload + def cursor(self, factory: None = None) -> Cursor: ... + @overload + def cursor(self, factory: Callable[[Connection], _CursorT]) -> _CursorT: ... + + def execute(self, sql: str, parameters: _Parameters = ..., /) -> Cursor: ... + def executemany(self, sql: str, parameters: Iterable[_Parameters], /) -> Cursor: ... + def executescript(self, sql_script: str, /) -> Cursor: ... + def interrupt(self) -> None: ... + if sys.version_info >= (3, 13): + def iterdump(self, *, filter: str | None = None) -> Generator[str]: ... + else: + def iterdump(self) -> Generator[str]: ... + + def rollback(self) -> None: ... + if sys.version_info >= (3, 15): + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None, / + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, /, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None, /) -> None: ... + else: + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... + # enable_load_extension and load_extension is not available on python distributions compiled + # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 + def enable_load_extension(self, enable: bool, /) -> None: ... + if sys.version_info >= (3, 12): + def load_extension(self, name: str, /, *, entrypoint: str | None = None) -> None: ... + else: + def load_extension(self, name: str, /) -> None: ... + + def backup( + self, + target: Connection, + *, + pages: int = -1, + progress: Callable[[int, int, int], object] | None = None, + name: str = "main", + sleep: float = 0.25, + ) -> None: ... + if sys.version_info >= (3, 11): + def setlimit(self, category: int, limit: int, /) -> int: ... + def getlimit(self, category: int, /) -> int: ... + def serialize(self, *, name: str = "main") -> bytes: ... + def deserialize(self, data: ReadableBuffer, /, *, name: str = "main") -> None: ... + if sys.version_info >= (3, 12): + def getconfig(self, op: int, /) -> bool: ... + def setconfig(self, op: int, enable: bool = True, /) -> bool: ... + + def __call__(self, sql: str, /) -> _Statement: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / + ) -> Literal[False]: ... + +@disjoint_base +class Cursor: + arraysize: int + @property + def connection(self) -> Connection: ... + # May be None, but using `| MaybeNone` (`| Any`) instead to avoid slightly annoying false positives. + @property + def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | MaybeNone: ... + @property + def lastrowid(self) -> int | None: ... + row_factory: _RowFactoryOptions + @property + def rowcount(self) -> int: ... + def __init__(self, cursor: Connection, /) -> None: ... + def close(self) -> None: ... + def execute(self, sql: str, parameters: _Parameters = (), /) -> Self: ... + def executemany(self, sql: str, seq_of_parameters: Iterable[_Parameters], /) -> Self: ... + def executescript(self, sql_script: str, /) -> Cursor: ... + def fetchall(self) -> list[Any]: ... + def fetchmany(self, size: int | None = 1) -> list[Any]: ... + # Returns either a row (as created by the row_factory) or None, but + # putting None in the return annotation causes annoying false positives. + def fetchone(self) -> Any: ... + def setinputsizes(self, sizes: Unused, /) -> None: ... # does nothing + def setoutputsize(self, size: Unused, column: Unused = None, /) -> None: ... # does nothing + def __iter__(self) -> Self: ... + def __next__(self) -> Any: ... + +@final +class PrepareProtocol: + def __init__(self, *args: object, **kwargs: object) -> None: ... + +@disjoint_base +class Row(Sequence[Any]): + def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ... + def keys(self) -> list[str]: ... + + @overload # Note: really needs int instead of SupportsIndex + def __getitem__(self, key: int | str, /) -> Any: ... + @overload # Note: SupportsIndex does work within slices. + def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[Any, ...]: ... + + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[Any]: ... + def __len__(self) -> int: ... + # These return NotImplemented for anything that is not a Row. + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: object, /) -> bool: ... + def __gt__(self, value: object, /) -> bool: ... + def __le__(self, value: object, /) -> bool: ... + def __lt__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + +# This class is not exposed. It calls itself sqlite3.Statement. +@final +@type_check_only +class _Statement: ... + +if sys.version_info >= (3, 11): + @final + class Blob: + def close(self) -> None: ... + def read(self, length: int = -1, /) -> bytes: ... + def write(self, data: ReadableBuffer, /) -> None: ... + def tell(self) -> int: ... + # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END + def seek(self, offset: int, origin: int = 0, /) -> None: ... + def __len__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: object, val: object, tb: object, /) -> Literal[False]: ... + def __getitem__(self, key: SupportsIndex | slice, /) -> int: ... + def __setitem__(self, key: SupportsIndex | slice, value: int, /) -> None: ... diff --git a/stdlib/sqlite3/dbapi2.pyi b/stdlib/sqlite3/dbapi2.pyi index 0c52c1c2e6a1..0cd676f9bfc8 100644 --- a/stdlib/sqlite3/dbapi2.pyi +++ b/stdlib/sqlite3/dbapi2.pyi @@ -1,13 +1,233 @@ import sys -from _typeshed import Self, StrOrBytesPath +from _sqlite3 import ( + PARSE_COLNAMES as PARSE_COLNAMES, + PARSE_DECLTYPES as PARSE_DECLTYPES, + SQLITE_ALTER_TABLE as SQLITE_ALTER_TABLE, + SQLITE_ANALYZE as SQLITE_ANALYZE, + SQLITE_ATTACH as SQLITE_ATTACH, + SQLITE_CREATE_INDEX as SQLITE_CREATE_INDEX, + SQLITE_CREATE_TABLE as SQLITE_CREATE_TABLE, + SQLITE_CREATE_TEMP_INDEX as SQLITE_CREATE_TEMP_INDEX, + SQLITE_CREATE_TEMP_TABLE as SQLITE_CREATE_TEMP_TABLE, + SQLITE_CREATE_TEMP_TRIGGER as SQLITE_CREATE_TEMP_TRIGGER, + SQLITE_CREATE_TEMP_VIEW as SQLITE_CREATE_TEMP_VIEW, + SQLITE_CREATE_TRIGGER as SQLITE_CREATE_TRIGGER, + SQLITE_CREATE_VIEW as SQLITE_CREATE_VIEW, + SQLITE_CREATE_VTABLE as SQLITE_CREATE_VTABLE, + SQLITE_DELETE as SQLITE_DELETE, + SQLITE_DENY as SQLITE_DENY, + SQLITE_DETACH as SQLITE_DETACH, + SQLITE_DONE as SQLITE_DONE, + SQLITE_DROP_INDEX as SQLITE_DROP_INDEX, + SQLITE_DROP_TABLE as SQLITE_DROP_TABLE, + SQLITE_DROP_TEMP_INDEX as SQLITE_DROP_TEMP_INDEX, + SQLITE_DROP_TEMP_TABLE as SQLITE_DROP_TEMP_TABLE, + SQLITE_DROP_TEMP_TRIGGER as SQLITE_DROP_TEMP_TRIGGER, + SQLITE_DROP_TEMP_VIEW as SQLITE_DROP_TEMP_VIEW, + SQLITE_DROP_TRIGGER as SQLITE_DROP_TRIGGER, + SQLITE_DROP_VIEW as SQLITE_DROP_VIEW, + SQLITE_DROP_VTABLE as SQLITE_DROP_VTABLE, + SQLITE_FUNCTION as SQLITE_FUNCTION, + SQLITE_IGNORE as SQLITE_IGNORE, + SQLITE_INSERT as SQLITE_INSERT, + SQLITE_OK as SQLITE_OK, + SQLITE_PRAGMA as SQLITE_PRAGMA, + SQLITE_READ as SQLITE_READ, + SQLITE_RECURSIVE as SQLITE_RECURSIVE, + SQLITE_REINDEX as SQLITE_REINDEX, + SQLITE_SAVEPOINT as SQLITE_SAVEPOINT, + SQLITE_SELECT as SQLITE_SELECT, + SQLITE_TRANSACTION as SQLITE_TRANSACTION, + SQLITE_UPDATE as SQLITE_UPDATE, + adapt as adapt, + adapters as adapters, + complete_statement as complete_statement, + connect as connect, + converters as converters, + enable_callback_tracebacks as enable_callback_tracebacks, + register_adapter as register_adapter, + register_converter as register_converter, + sqlite_version as sqlite_version, +) from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, Type, TypeVar +from sqlite3 import ( + Connection as Connection, + Cursor as Cursor, + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + PrepareProtocol as PrepareProtocol, + ProgrammingError as ProgrammingError, + Row as Row, + Warning as Warning, +) +from typing import Final, Literal +from typing_extensions import deprecated + +if sys.version_info >= (3, 12): + from _sqlite3 import ( + LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL, + SQLITE_DBCONFIG_DEFENSIVE as SQLITE_DBCONFIG_DEFENSIVE, + SQLITE_DBCONFIG_DQS_DDL as SQLITE_DBCONFIG_DQS_DDL, + SQLITE_DBCONFIG_DQS_DML as SQLITE_DBCONFIG_DQS_DML, + SQLITE_DBCONFIG_ENABLE_FKEY as SQLITE_DBCONFIG_ENABLE_FKEY, + SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER as SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION as SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, + SQLITE_DBCONFIG_ENABLE_QPSG as SQLITE_DBCONFIG_ENABLE_QPSG, + SQLITE_DBCONFIG_ENABLE_TRIGGER as SQLITE_DBCONFIG_ENABLE_TRIGGER, + SQLITE_DBCONFIG_ENABLE_VIEW as SQLITE_DBCONFIG_ENABLE_VIEW, + SQLITE_DBCONFIG_LEGACY_ALTER_TABLE as SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, + SQLITE_DBCONFIG_LEGACY_FILE_FORMAT as SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, + SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE as SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, + SQLITE_DBCONFIG_RESET_DATABASE as SQLITE_DBCONFIG_RESET_DATABASE, + SQLITE_DBCONFIG_TRIGGER_EQP as SQLITE_DBCONFIG_TRIGGER_EQP, + SQLITE_DBCONFIG_TRUSTED_SCHEMA as SQLITE_DBCONFIG_TRUSTED_SCHEMA, + SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA, + ) + +if sys.version_info >= (3, 15): + from _sqlite3 import SQLITE_KEYWORDS as SQLITE_KEYWORDS -_T = TypeVar("_T") - -paramstyle: str -threadsafety: int -apilevel: str +if sys.version_info >= (3, 11): + from _sqlite3 import ( + SQLITE_ABORT as SQLITE_ABORT, + SQLITE_ABORT_ROLLBACK as SQLITE_ABORT_ROLLBACK, + SQLITE_AUTH as SQLITE_AUTH, + SQLITE_AUTH_USER as SQLITE_AUTH_USER, + SQLITE_BUSY as SQLITE_BUSY, + SQLITE_BUSY_RECOVERY as SQLITE_BUSY_RECOVERY, + SQLITE_BUSY_SNAPSHOT as SQLITE_BUSY_SNAPSHOT, + SQLITE_BUSY_TIMEOUT as SQLITE_BUSY_TIMEOUT, + SQLITE_CANTOPEN as SQLITE_CANTOPEN, + SQLITE_CANTOPEN_CONVPATH as SQLITE_CANTOPEN_CONVPATH, + SQLITE_CANTOPEN_DIRTYWAL as SQLITE_CANTOPEN_DIRTYWAL, + SQLITE_CANTOPEN_FULLPATH as SQLITE_CANTOPEN_FULLPATH, + SQLITE_CANTOPEN_ISDIR as SQLITE_CANTOPEN_ISDIR, + SQLITE_CANTOPEN_NOTEMPDIR as SQLITE_CANTOPEN_NOTEMPDIR, + SQLITE_CANTOPEN_SYMLINK as SQLITE_CANTOPEN_SYMLINK, + SQLITE_CONSTRAINT as SQLITE_CONSTRAINT, + SQLITE_CONSTRAINT_CHECK as SQLITE_CONSTRAINT_CHECK, + SQLITE_CONSTRAINT_COMMITHOOK as SQLITE_CONSTRAINT_COMMITHOOK, + SQLITE_CONSTRAINT_FOREIGNKEY as SQLITE_CONSTRAINT_FOREIGNKEY, + SQLITE_CONSTRAINT_FUNCTION as SQLITE_CONSTRAINT_FUNCTION, + SQLITE_CONSTRAINT_NOTNULL as SQLITE_CONSTRAINT_NOTNULL, + SQLITE_CONSTRAINT_PINNED as SQLITE_CONSTRAINT_PINNED, + SQLITE_CONSTRAINT_PRIMARYKEY as SQLITE_CONSTRAINT_PRIMARYKEY, + SQLITE_CONSTRAINT_ROWID as SQLITE_CONSTRAINT_ROWID, + SQLITE_CONSTRAINT_TRIGGER as SQLITE_CONSTRAINT_TRIGGER, + SQLITE_CONSTRAINT_UNIQUE as SQLITE_CONSTRAINT_UNIQUE, + SQLITE_CONSTRAINT_VTAB as SQLITE_CONSTRAINT_VTAB, + SQLITE_CORRUPT as SQLITE_CORRUPT, + SQLITE_CORRUPT_INDEX as SQLITE_CORRUPT_INDEX, + SQLITE_CORRUPT_SEQUENCE as SQLITE_CORRUPT_SEQUENCE, + SQLITE_CORRUPT_VTAB as SQLITE_CORRUPT_VTAB, + SQLITE_EMPTY as SQLITE_EMPTY, + SQLITE_ERROR as SQLITE_ERROR, + SQLITE_ERROR_MISSING_COLLSEQ as SQLITE_ERROR_MISSING_COLLSEQ, + SQLITE_ERROR_RETRY as SQLITE_ERROR_RETRY, + SQLITE_ERROR_SNAPSHOT as SQLITE_ERROR_SNAPSHOT, + SQLITE_FORMAT as SQLITE_FORMAT, + SQLITE_FULL as SQLITE_FULL, + SQLITE_INTERNAL as SQLITE_INTERNAL, + SQLITE_INTERRUPT as SQLITE_INTERRUPT, + SQLITE_IOERR as SQLITE_IOERR, + SQLITE_IOERR_ACCESS as SQLITE_IOERR_ACCESS, + SQLITE_IOERR_AUTH as SQLITE_IOERR_AUTH, + SQLITE_IOERR_BEGIN_ATOMIC as SQLITE_IOERR_BEGIN_ATOMIC, + SQLITE_IOERR_BLOCKED as SQLITE_IOERR_BLOCKED, + SQLITE_IOERR_CHECKRESERVEDLOCK as SQLITE_IOERR_CHECKRESERVEDLOCK, + SQLITE_IOERR_CLOSE as SQLITE_IOERR_CLOSE, + SQLITE_IOERR_COMMIT_ATOMIC as SQLITE_IOERR_COMMIT_ATOMIC, + SQLITE_IOERR_CONVPATH as SQLITE_IOERR_CONVPATH, + SQLITE_IOERR_CORRUPTFS as SQLITE_IOERR_CORRUPTFS, + SQLITE_IOERR_DATA as SQLITE_IOERR_DATA, + SQLITE_IOERR_DELETE as SQLITE_IOERR_DELETE, + SQLITE_IOERR_DELETE_NOENT as SQLITE_IOERR_DELETE_NOENT, + SQLITE_IOERR_DIR_CLOSE as SQLITE_IOERR_DIR_CLOSE, + SQLITE_IOERR_DIR_FSYNC as SQLITE_IOERR_DIR_FSYNC, + SQLITE_IOERR_FSTAT as SQLITE_IOERR_FSTAT, + SQLITE_IOERR_FSYNC as SQLITE_IOERR_FSYNC, + SQLITE_IOERR_GETTEMPPATH as SQLITE_IOERR_GETTEMPPATH, + SQLITE_IOERR_LOCK as SQLITE_IOERR_LOCK, + SQLITE_IOERR_MMAP as SQLITE_IOERR_MMAP, + SQLITE_IOERR_NOMEM as SQLITE_IOERR_NOMEM, + SQLITE_IOERR_RDLOCK as SQLITE_IOERR_RDLOCK, + SQLITE_IOERR_READ as SQLITE_IOERR_READ, + SQLITE_IOERR_ROLLBACK_ATOMIC as SQLITE_IOERR_ROLLBACK_ATOMIC, + SQLITE_IOERR_SEEK as SQLITE_IOERR_SEEK, + SQLITE_IOERR_SHMLOCK as SQLITE_IOERR_SHMLOCK, + SQLITE_IOERR_SHMMAP as SQLITE_IOERR_SHMMAP, + SQLITE_IOERR_SHMOPEN as SQLITE_IOERR_SHMOPEN, + SQLITE_IOERR_SHMSIZE as SQLITE_IOERR_SHMSIZE, + SQLITE_IOERR_SHORT_READ as SQLITE_IOERR_SHORT_READ, + SQLITE_IOERR_TRUNCATE as SQLITE_IOERR_TRUNCATE, + SQLITE_IOERR_UNLOCK as SQLITE_IOERR_UNLOCK, + SQLITE_IOERR_VNODE as SQLITE_IOERR_VNODE, + SQLITE_IOERR_WRITE as SQLITE_IOERR_WRITE, + SQLITE_LIMIT_ATTACHED as SQLITE_LIMIT_ATTACHED, + SQLITE_LIMIT_COLUMN as SQLITE_LIMIT_COLUMN, + SQLITE_LIMIT_COMPOUND_SELECT as SQLITE_LIMIT_COMPOUND_SELECT, + SQLITE_LIMIT_EXPR_DEPTH as SQLITE_LIMIT_EXPR_DEPTH, + SQLITE_LIMIT_FUNCTION_ARG as SQLITE_LIMIT_FUNCTION_ARG, + SQLITE_LIMIT_LENGTH as SQLITE_LIMIT_LENGTH, + SQLITE_LIMIT_LIKE_PATTERN_LENGTH as SQLITE_LIMIT_LIKE_PATTERN_LENGTH, + SQLITE_LIMIT_SQL_LENGTH as SQLITE_LIMIT_SQL_LENGTH, + SQLITE_LIMIT_TRIGGER_DEPTH as SQLITE_LIMIT_TRIGGER_DEPTH, + SQLITE_LIMIT_VARIABLE_NUMBER as SQLITE_LIMIT_VARIABLE_NUMBER, + SQLITE_LIMIT_VDBE_OP as SQLITE_LIMIT_VDBE_OP, + SQLITE_LIMIT_WORKER_THREADS as SQLITE_LIMIT_WORKER_THREADS, + SQLITE_LOCKED as SQLITE_LOCKED, + SQLITE_LOCKED_SHAREDCACHE as SQLITE_LOCKED_SHAREDCACHE, + SQLITE_LOCKED_VTAB as SQLITE_LOCKED_VTAB, + SQLITE_MISMATCH as SQLITE_MISMATCH, + SQLITE_MISUSE as SQLITE_MISUSE, + SQLITE_NOLFS as SQLITE_NOLFS, + SQLITE_NOMEM as SQLITE_NOMEM, + SQLITE_NOTADB as SQLITE_NOTADB, + SQLITE_NOTFOUND as SQLITE_NOTFOUND, + SQLITE_NOTICE as SQLITE_NOTICE, + SQLITE_NOTICE_RECOVER_ROLLBACK as SQLITE_NOTICE_RECOVER_ROLLBACK, + SQLITE_NOTICE_RECOVER_WAL as SQLITE_NOTICE_RECOVER_WAL, + SQLITE_OK_LOAD_PERMANENTLY as SQLITE_OK_LOAD_PERMANENTLY, + SQLITE_OK_SYMLINK as SQLITE_OK_SYMLINK, + SQLITE_PERM as SQLITE_PERM, + SQLITE_PROTOCOL as SQLITE_PROTOCOL, + SQLITE_RANGE as SQLITE_RANGE, + SQLITE_READONLY as SQLITE_READONLY, + SQLITE_READONLY_CANTINIT as SQLITE_READONLY_CANTINIT, + SQLITE_READONLY_CANTLOCK as SQLITE_READONLY_CANTLOCK, + SQLITE_READONLY_DBMOVED as SQLITE_READONLY_DBMOVED, + SQLITE_READONLY_DIRECTORY as SQLITE_READONLY_DIRECTORY, + SQLITE_READONLY_RECOVERY as SQLITE_READONLY_RECOVERY, + SQLITE_READONLY_ROLLBACK as SQLITE_READONLY_ROLLBACK, + SQLITE_ROW as SQLITE_ROW, + SQLITE_SCHEMA as SQLITE_SCHEMA, + SQLITE_TOOBIG as SQLITE_TOOBIG, + SQLITE_WARNING as SQLITE_WARNING, + SQLITE_WARNING_AUTOINDEX as SQLITE_WARNING_AUTOINDEX, + ) + from sqlite3 import Blob as Blob + +if sys.version_info < (3, 14): + # Deprecated and removed from _sqlite3 in 3.12, but removed from here in 3.14. + version: Final[str] + +if sys.version_info < (3, 12): + # deprecation wrapper that has a different name for the argument... + @deprecated( + "Deprecated since Python 3.10; removed in Python 3.12. " + "Open database in URI mode using `cache=shared` parameter instead." + ) + def enable_shared_cache(enable: int) -> None: ... + +paramstyle: Final = "qmark" +threadsafety: Literal[0, 1, 3] +apilevel: Final[str] Date = date Time = time Timestamp = datetime @@ -16,232 +236,9 @@ def DateFromTicks(ticks: float) -> Date: ... def TimeFromTicks(ticks: float) -> Time: ... def TimestampFromTicks(ticks: float) -> Timestamp: ... -version_info: tuple[int, int, int] -sqlite_version_info: tuple[int, int, int] -Binary = memoryview - -# The remaining definitions are imported from _sqlite3. - -PARSE_COLNAMES: int -PARSE_DECLTYPES: int -SQLITE_ALTER_TABLE: int -SQLITE_ANALYZE: int -SQLITE_ATTACH: int -SQLITE_CREATE_INDEX: int -SQLITE_CREATE_TABLE: int -SQLITE_CREATE_TEMP_INDEX: int -SQLITE_CREATE_TEMP_TABLE: int -SQLITE_CREATE_TEMP_TRIGGER: int -SQLITE_CREATE_TEMP_VIEW: int -SQLITE_CREATE_TRIGGER: int -SQLITE_CREATE_VIEW: int -if sys.version_info >= (3, 7): - SQLITE_CREATE_VTABLE: int -SQLITE_DELETE: int -SQLITE_DENY: int -SQLITE_DETACH: int -if sys.version_info >= (3, 7): - SQLITE_DONE: int -SQLITE_DROP_INDEX: int -SQLITE_DROP_TABLE: int -SQLITE_DROP_TEMP_INDEX: int -SQLITE_DROP_TEMP_TABLE: int -SQLITE_DROP_TEMP_TRIGGER: int -SQLITE_DROP_TEMP_VIEW: int -SQLITE_DROP_TRIGGER: int -SQLITE_DROP_VIEW: int -if sys.version_info >= (3, 7): - SQLITE_DROP_VTABLE: int - SQLITE_FUNCTION: int -SQLITE_IGNORE: int -SQLITE_INSERT: int -SQLITE_OK: int -if sys.version_info >= (3, 11): - SQLITE_LIMIT_LENGTH: int - SQLITE_LIMIT_SQL_LENGTH: int - SQLITE_LIMIT_COLUMN: int - SQLITE_LIMIT_EXPR_DEPTH: int - SQLITE_LIMIT_COMPOUND_SELECT: int - SQLITE_LIMIT_VDBE_OP: int - SQLITE_LIMIT_FUNCTION_ARG: int - SQLITE_LIMIT_ATTACHED: int - SQLITE_LIMIT_LIKE_PATTERN_LENGTH: int - SQLITE_LIMIT_VARIABLE_NUMBER: int - SQLITE_LIMIT_TRIGGER_DEPTH: int - SQLITE_LIMIT_WORKER_THREADS: int -SQLITE_PRAGMA: int -SQLITE_READ: int -SQLITE_REINDEX: int -if sys.version_info >= (3, 7): - SQLITE_RECURSIVE: int - SQLITE_SAVEPOINT: int -SQLITE_SELECT: int -SQLITE_TRANSACTION: int -SQLITE_UPDATE: int -adapters: Any -converters: Any -sqlite_version: str -version: str - -# TODO: adapt needs to get probed -def adapt(obj, protocol, alternate): ... -def complete_statement(statement: str) -> bool: ... - -if sys.version_info >= (3, 7): - def connect( - database: StrOrBytesPath, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., - ) -> Connection: ... - -else: - def connect( - database: bytes | str, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., - ) -> Connection: ... - -def enable_callback_tracebacks(__enable: bool) -> None: ... -def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: Type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... -def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... - -if sys.version_info < (3, 8): - class Cache(object): - def __init__(self, *args, **kwargs) -> None: ... - def display(self, *args, **kwargs) -> None: ... - def get(self, *args, **kwargs) -> None: ... - -class _AggregateProtocol(Protocol): - def step(self, value: int) -> None: ... - def finalize(self) -> int: ... +if sys.version_info < (3, 14): + # Deprecated in 3.12, removed in 3.14. + version_info: Final[tuple[int, int, int]] -class Connection(object): - DataError: Any - DatabaseError: Any - Error: Any - IntegrityError: Any - InterfaceError: Any - InternalError: Any - NotSupportedError: Any - OperationalError: Any - ProgrammingError: Any - Warning: Any - in_transaction: Any - isolation_level: Any - row_factory: Any - text_factory: Any - total_changes: Any - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def close(self) -> None: ... - def commit(self) -> None: ... - def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... - def create_collation(self, __name: str, __callback: Any) -> None: ... - if sys.version_info >= (3, 8): - def create_function(self, name: str, narg: int, func: Any, *, deterministic: bool = ...) -> None: ... - else: - def create_function(self, name: str, num_params: int, func: Any) -> None: ... - def cursor(self, cursorClass: type | None = ...) -> Cursor: ... - def execute(self, sql: str, parameters: Iterable[Any] = ...) -> Cursor: ... - # TODO: please check in executemany() if seq_of_parameters type is possible like this - def executemany(self, __sql: str, __parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: bytes | str) -> Cursor: ... - def interrupt(self) -> None: ... - def iterdump(self) -> Generator[str, None, None]: ... - def rollback(self) -> None: ... - def set_authorizer( - self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None - ) -> None: ... - def set_progress_handler(self, progress_handler: Callable[[], bool | None] | None, n: int) -> None: ... - def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... - # enable_load_extension and load_extension is not available on python distributions compiled - # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 - def enable_load_extension(self, enabled: bool) -> None: ... - def load_extension(self, path: str) -> None: ... - if sys.version_info >= (3, 7): - def backup( - self, - target: Connection, - *, - pages: int = ..., - progress: Callable[[int, int, int], object] | None = ..., - name: str = ..., - sleep: float = ..., - ) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, t: type | None, exc: BaseException | None, tb: Any | None) -> None: ... - -class Cursor(Iterator[Any]): - arraysize: Any - connection: Any - description: Any - lastrowid: Any - row_factory: Any - rowcount: int - # TODO: Cursor class accepts exactly 1 argument - # required type is sqlite3.Connection (which is imported as _Connection) - # however, the name of the __init__ variable is unknown - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def close(self) -> None: ... - def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... - def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: bytes | str) -> Cursor: ... - def fetchall(self) -> list[Any]: ... - def fetchmany(self, size: int | None = ...) -> list[Any]: ... - def fetchone(self) -> Any: ... - def setinputsizes(self, __sizes: object) -> None: ... # does nothing - def setoutputsize(self, __size: object, __column: object = ...) -> None: ... # does nothing - def __iter__(self) -> Cursor: ... - def __next__(self) -> Any: ... - -class DataError(DatabaseError): ... -class DatabaseError(Error): ... - -class Error(Exception): - if sys.version_info >= (3, 11): - sqlite_errorcode: int - sqlite_errorname: str - -class IntegrityError(DatabaseError): ... -class InterfaceError(Error): ... -class InternalError(DatabaseError): ... -class NotSupportedError(DatabaseError): ... -class OperationalError(DatabaseError): ... - -OptimizedUnicode = str - -class PrepareProtocol(object): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - -class ProgrammingError(DatabaseError): ... - -class Row(object): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def keys(self): ... - def __eq__(self, other): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... - def __gt__(self, other): ... - def __hash__(self): ... - def __iter__(self): ... - def __le__(self, other): ... - def __len__(self): ... - def __lt__(self, other): ... - def __ne__(self, other): ... - -if sys.version_info < (3, 8): - class Statement(object): - def __init__(self, *args, **kwargs): ... - -class Warning(Exception): ... +sqlite_version_info: Final[tuple[int, int, int]] +Binary = memoryview diff --git a/stdlib/sqlite3/dump.pyi b/stdlib/sqlite3/dump.pyi new file mode 100644 index 000000000000..ed95fa46e1c7 --- /dev/null +++ b/stdlib/sqlite3/dump.pyi @@ -0,0 +1,2 @@ +# This file is intentionally empty. The runtime module contains only +# private functions. diff --git a/stdlib/sre_compile.pyi b/stdlib/sre_compile.pyi index 98a9f4dad008..486b2f743eeb 100644 --- a/stdlib/sre_compile.pyi +++ b/stdlib/sre_compile.pyi @@ -1,10 +1,12 @@ +from re import Pattern from sre_constants import * from sre_constants import _NamedIntConstant from sre_parse import SubPattern -from typing import Any, Pattern +from typing import Any, Final +from typing_extensions import TypeIs -MAXCODE: int +MAXCODE: Final[int] def dis(code: list[_NamedIntConstant]) -> None: ... -def isstring(obj: Any) -> bool: ... -def compile(p: str | bytes | SubPattern, flags: int = ...) -> Pattern[Any]: ... +def isstring(obj: object) -> TypeIs[str | bytes]: ... +def compile(p: str | bytes | SubPattern, flags: int = 0) -> Pattern[Any]: ... diff --git a/stdlib/sre_constants.pyi b/stdlib/sre_constants.pyi index df7e1a28007b..9a1da4ac89e7 100644 --- a/stdlib/sre_constants.pyi +++ b/stdlib/sre_constants.pyi @@ -1,128 +1,135 @@ import sys -from typing import Any +from re import error as error +from typing import Final +from typing_extensions import Self, disjoint_base -MAXGROUPS: int +MAXGROUPS: Final[int] -MAGIC: int +MAGIC: Final[int] -class error(Exception): - msg: str - pattern: str | bytes | None - pos: int | None - lineno: int - colno: int - def __init__(self, msg: str, pattern: str | bytes | None = ..., pos: int | None = ...) -> None: ... +if sys.version_info >= (3, 12): + class _NamedIntConstant(int): + name: str + def __new__(cls, value: int, name: str) -> Self: ... -class _NamedIntConstant(int): - name: Any - def __new__(cls, value: int, name: str) -> _NamedIntConstant: ... +else: + @disjoint_base + class _NamedIntConstant(int): + name: str + def __new__(cls, value: int, name: str) -> Self: ... -MAXREPEAT: _NamedIntConstant +MAXREPEAT: Final[_NamedIntConstant] OPCODES: list[_NamedIntConstant] ATCODES: list[_NamedIntConstant] CHCODES: list[_NamedIntConstant] OP_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] -if sys.version_info >= (3, 7): - OP_LOCALE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] - OP_UNICODE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] +OP_LOCALE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] +OP_UNICODE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] AT_MULTILINE: dict[_NamedIntConstant, _NamedIntConstant] AT_LOCALE: dict[_NamedIntConstant, _NamedIntConstant] AT_UNICODE: dict[_NamedIntConstant, _NamedIntConstant] CH_LOCALE: dict[_NamedIntConstant, _NamedIntConstant] CH_UNICODE: dict[_NamedIntConstant, _NamedIntConstant] -SRE_FLAG_TEMPLATE: int -SRE_FLAG_IGNORECASE: int -SRE_FLAG_LOCALE: int -SRE_FLAG_MULTILINE: int -SRE_FLAG_DOTALL: int -SRE_FLAG_UNICODE: int -SRE_FLAG_VERBOSE: int -SRE_FLAG_DEBUG: int -SRE_FLAG_ASCII: int -SRE_INFO_PREFIX: int -SRE_INFO_LITERAL: int -SRE_INFO_CHARSET: int +if sys.version_info >= (3, 14): + CH_NEGATE: dict[_NamedIntConstant, _NamedIntConstant] +# flags +if sys.version_info < (3, 13): + SRE_FLAG_TEMPLATE: Final = 1 +SRE_FLAG_IGNORECASE: Final = 2 +SRE_FLAG_LOCALE: Final = 4 +SRE_FLAG_MULTILINE: Final = 8 +SRE_FLAG_DOTALL: Final = 16 +SRE_FLAG_UNICODE: Final = 32 +SRE_FLAG_VERBOSE: Final = 64 +SRE_FLAG_DEBUG: Final = 128 +SRE_FLAG_ASCII: Final = 256 +# flags for INFO primitive +SRE_INFO_PREFIX: Final = 1 +SRE_INFO_LITERAL: Final = 2 +SRE_INFO_CHARSET: Final = 4 # Stubgen above; manually defined constants below (dynamic at runtime) # from OPCODES -FAILURE: _NamedIntConstant -SUCCESS: _NamedIntConstant -ANY: _NamedIntConstant -ANY_ALL: _NamedIntConstant -ASSERT: _NamedIntConstant -ASSERT_NOT: _NamedIntConstant -AT: _NamedIntConstant -BRANCH: _NamedIntConstant -CALL: _NamedIntConstant -CATEGORY: _NamedIntConstant -CHARSET: _NamedIntConstant -BIGCHARSET: _NamedIntConstant -GROUPREF: _NamedIntConstant -GROUPREF_EXISTS: _NamedIntConstant -GROUPREF_IGNORE: _NamedIntConstant -IN: _NamedIntConstant -IN_IGNORE: _NamedIntConstant -INFO: _NamedIntConstant -JUMP: _NamedIntConstant -LITERAL: _NamedIntConstant -LITERAL_IGNORE: _NamedIntConstant -MARK: _NamedIntConstant -MAX_UNTIL: _NamedIntConstant -MIN_UNTIL: _NamedIntConstant -NOT_LITERAL: _NamedIntConstant -NOT_LITERAL_IGNORE: _NamedIntConstant -NEGATE: _NamedIntConstant -RANGE: _NamedIntConstant -REPEAT: _NamedIntConstant -REPEAT_ONE: _NamedIntConstant -SUBPATTERN: _NamedIntConstant -MIN_REPEAT_ONE: _NamedIntConstant -if sys.version_info >= (3, 7): - RANGE_UNI_IGNORE: _NamedIntConstant - GROUPREF_LOC_IGNORE: _NamedIntConstant - GROUPREF_UNI_IGNORE: _NamedIntConstant - IN_LOC_IGNORE: _NamedIntConstant - IN_UNI_IGNORE: _NamedIntConstant - LITERAL_LOC_IGNORE: _NamedIntConstant - LITERAL_UNI_IGNORE: _NamedIntConstant - NOT_LITERAL_LOC_IGNORE: _NamedIntConstant - NOT_LITERAL_UNI_IGNORE: _NamedIntConstant -else: - RANGE_IGNORE: _NamedIntConstant -MIN_REPEAT: _NamedIntConstant -MAX_REPEAT: _NamedIntConstant +FAILURE: Final[_NamedIntConstant] +SUCCESS: Final[_NamedIntConstant] +ANY: Final[_NamedIntConstant] +ANY_ALL: Final[_NamedIntConstant] +ASSERT: Final[_NamedIntConstant] +ASSERT_NOT: Final[_NamedIntConstant] +AT: Final[_NamedIntConstant] +BRANCH: Final[_NamedIntConstant] +if sys.version_info < (3, 11): + CALL: Final[_NamedIntConstant] +CATEGORY: Final[_NamedIntConstant] +CHARSET: Final[_NamedIntConstant] +BIGCHARSET: Final[_NamedIntConstant] +GROUPREF: Final[_NamedIntConstant] +GROUPREF_EXISTS: Final[_NamedIntConstant] +GROUPREF_IGNORE: Final[_NamedIntConstant] +IN: Final[_NamedIntConstant] +IN_IGNORE: Final[_NamedIntConstant] +INFO: Final[_NamedIntConstant] +JUMP: Final[_NamedIntConstant] +LITERAL: Final[_NamedIntConstant] +LITERAL_IGNORE: Final[_NamedIntConstant] +MARK: Final[_NamedIntConstant] +MAX_UNTIL: Final[_NamedIntConstant] +MIN_UNTIL: Final[_NamedIntConstant] +NOT_LITERAL: Final[_NamedIntConstant] +NOT_LITERAL_IGNORE: Final[_NamedIntConstant] +NEGATE: Final[_NamedIntConstant] +RANGE: Final[_NamedIntConstant] +REPEAT: Final[_NamedIntConstant] +REPEAT_ONE: Final[_NamedIntConstant] +SUBPATTERN: Final[_NamedIntConstant] +MIN_REPEAT_ONE: Final[_NamedIntConstant] +if sys.version_info >= (3, 11): + ATOMIC_GROUP: Final[_NamedIntConstant] + POSSESSIVE_REPEAT: Final[_NamedIntConstant] + POSSESSIVE_REPEAT_ONE: Final[_NamedIntConstant] +RANGE_UNI_IGNORE: Final[_NamedIntConstant] +GROUPREF_LOC_IGNORE: Final[_NamedIntConstant] +GROUPREF_UNI_IGNORE: Final[_NamedIntConstant] +IN_LOC_IGNORE: Final[_NamedIntConstant] +IN_UNI_IGNORE: Final[_NamedIntConstant] +LITERAL_LOC_IGNORE: Final[_NamedIntConstant] +LITERAL_UNI_IGNORE: Final[_NamedIntConstant] +NOT_LITERAL_LOC_IGNORE: Final[_NamedIntConstant] +NOT_LITERAL_UNI_IGNORE: Final[_NamedIntConstant] +MIN_REPEAT: Final[_NamedIntConstant] +MAX_REPEAT: Final[_NamedIntConstant] # from ATCODES -AT_BEGINNING: _NamedIntConstant -AT_BEGINNING_LINE: _NamedIntConstant -AT_BEGINNING_STRING: _NamedIntConstant -AT_BOUNDARY: _NamedIntConstant -AT_NON_BOUNDARY: _NamedIntConstant -AT_END: _NamedIntConstant -AT_END_LINE: _NamedIntConstant -AT_END_STRING: _NamedIntConstant -AT_LOC_BOUNDARY: _NamedIntConstant -AT_LOC_NON_BOUNDARY: _NamedIntConstant -AT_UNI_BOUNDARY: _NamedIntConstant -AT_UNI_NON_BOUNDARY: _NamedIntConstant +AT_BEGINNING: Final[_NamedIntConstant] +AT_BEGINNING_LINE: Final[_NamedIntConstant] +AT_BEGINNING_STRING: Final[_NamedIntConstant] +AT_BOUNDARY: Final[_NamedIntConstant] +AT_NON_BOUNDARY: Final[_NamedIntConstant] +AT_END: Final[_NamedIntConstant] +AT_END_LINE: Final[_NamedIntConstant] +AT_END_STRING: Final[_NamedIntConstant] +AT_LOC_BOUNDARY: Final[_NamedIntConstant] +AT_LOC_NON_BOUNDARY: Final[_NamedIntConstant] +AT_UNI_BOUNDARY: Final[_NamedIntConstant] +AT_UNI_NON_BOUNDARY: Final[_NamedIntConstant] # from CHCODES -CATEGORY_DIGIT: _NamedIntConstant -CATEGORY_NOT_DIGIT: _NamedIntConstant -CATEGORY_SPACE: _NamedIntConstant -CATEGORY_NOT_SPACE: _NamedIntConstant -CATEGORY_WORD: _NamedIntConstant -CATEGORY_NOT_WORD: _NamedIntConstant -CATEGORY_LINEBREAK: _NamedIntConstant -CATEGORY_NOT_LINEBREAK: _NamedIntConstant -CATEGORY_LOC_WORD: _NamedIntConstant -CATEGORY_LOC_NOT_WORD: _NamedIntConstant -CATEGORY_UNI_DIGIT: _NamedIntConstant -CATEGORY_UNI_NOT_DIGIT: _NamedIntConstant -CATEGORY_UNI_SPACE: _NamedIntConstant -CATEGORY_UNI_NOT_SPACE: _NamedIntConstant -CATEGORY_UNI_WORD: _NamedIntConstant -CATEGORY_UNI_NOT_WORD: _NamedIntConstant -CATEGORY_UNI_LINEBREAK: _NamedIntConstant -CATEGORY_UNI_NOT_LINEBREAK: _NamedIntConstant +CATEGORY_DIGIT: Final[_NamedIntConstant] +CATEGORY_NOT_DIGIT: Final[_NamedIntConstant] +CATEGORY_SPACE: Final[_NamedIntConstant] +CATEGORY_NOT_SPACE: Final[_NamedIntConstant] +CATEGORY_WORD: Final[_NamedIntConstant] +CATEGORY_NOT_WORD: Final[_NamedIntConstant] +CATEGORY_LINEBREAK: Final[_NamedIntConstant] +CATEGORY_NOT_LINEBREAK: Final[_NamedIntConstant] +CATEGORY_LOC_WORD: Final[_NamedIntConstant] +CATEGORY_LOC_NOT_WORD: Final[_NamedIntConstant] +CATEGORY_UNI_DIGIT: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_DIGIT: Final[_NamedIntConstant] +CATEGORY_UNI_SPACE: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_SPACE: Final[_NamedIntConstant] +CATEGORY_UNI_WORD: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_WORD: Final[_NamedIntConstant] +CATEGORY_UNI_LINEBREAK: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_LINEBREAK: Final[_NamedIntConstant] diff --git a/stdlib/sre_parse.pyi b/stdlib/sre_parse.pyi index 598e61d6a8e0..6b873f4043b0 100644 --- a/stdlib/sre_parse.pyi +++ b/stdlib/sre_parse.pyi @@ -1,67 +1,62 @@ import sys +from collections.abc import Iterable +from re import Match, Pattern as _Pattern from sre_constants import * from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Iterable, List, Match, Optional, Pattern as _Pattern, Tuple, Union, overload +from typing import Any, Final, TypeAlias, overload -SPECIAL_CHARS: str -REPEAT_CHARS: str -DIGITS: frozenset[str] -OCTDIGITS: frozenset[str] -HEXDIGITS: frozenset[str] -ASCIILETTERS: frozenset[str] -WHITESPACE: frozenset[str] -ESCAPES: dict[str, tuple[_NIC, int]] -CATEGORIES: dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]] -FLAGS: dict[str, int] -if sys.version_info >= (3, 7): - TYPE_FLAGS: int -GLOBAL_FLAGS: int +SPECIAL_CHARS: Final = ".\\[{()*+?^$|" +REPEAT_CHARS: Final = "*+?{" +DIGITS: Final[frozenset[str]] +OCTDIGITS: Final[frozenset[str]] +HEXDIGITS: Final[frozenset[str]] +ASCIILETTERS: Final[frozenset[str]] +WHITESPACE: Final[frozenset[str]] +ESCAPES: Final[dict[str, tuple[_NIC, int]]] +CATEGORIES: Final[dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]]] +FLAGS: Final[dict[str, int]] +TYPE_FLAGS: Final[int] +GLOBAL_FLAGS: Final[int] -class Verbose(Exception): ... +if sys.version_info >= (3, 11): + MAXWIDTH: Final[int] -class _State: +if sys.version_info < (3, 11): + class Verbose(Exception): ... + +_OpSubpatternType: TypeAlias = tuple[int | None, int, int, SubPattern] +_OpGroupRefExistsType: TypeAlias = tuple[int, SubPattern, SubPattern] +_OpInType: TypeAlias = list[tuple[_NIC, int]] +_OpBranchType: TypeAlias = tuple[None, list[SubPattern]] +_AvType: TypeAlias = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType +_CodeType: TypeAlias = tuple[_NIC, _AvType] + +class State: flags: int groupdict: dict[str, int] groupwidths: list[int | None] lookbehindgroups: int | None - def __init__(self) -> None: ... @property def groups(self) -> int: ... - def opengroup(self, name: str | None = ...) -> int: ... + def opengroup(self, name: str | None = None) -> int: ... def closegroup(self, gid: int, p: SubPattern) -> None: ... def checkgroup(self, gid: int) -> bool: ... def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... -if sys.version_info >= (3, 8): - State = _State -else: - Pattern = _State - -_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] -_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] -_OpInType = List[Tuple[_NIC, int]] -_OpBranchType = Tuple[None, List[SubPattern]] -_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] -_CodeType = Tuple[_NIC, _AvType] - class SubPattern: data: list[_CodeType] width: int | None + state: State - if sys.version_info >= (3, 8): - state: State - def __init__(self, state: State, data: list[_CodeType] | None = ...) -> None: ... - else: - pattern: Pattern - def __init__(self, pattern: Pattern, data: list[_CodeType] | None = ...) -> None: ... - def dump(self, level: int = ...) -> None: ... + def __init__(self, state: State, data: list[_CodeType] | None = None) -> None: ... + def dump(self, level: int = 0) -> None: ... def __len__(self) -> int: ... def __delitem__(self, index: int | slice) -> None: ... def __getitem__(self, index: int | slice) -> SubPattern | _CodeType: ... def __setitem__(self, index: int | slice, code: _CodeType) -> None: ... def insert(self, index: int, code: _CodeType) -> None: ... def append(self, code: _CodeType) -> None: ... - def getwidth(self) -> int: ... + def getwidth(self) -> tuple[int, int]: ... class Tokenizer: istext: bool @@ -73,32 +68,35 @@ class Tokenizer: def match(self, char: str) -> bool: ... def get(self) -> str | None: ... def getwhile(self, n: int, charset: Iterable[str]) -> str: ... - if sys.version_info >= (3, 8): - def getuntil(self, terminator: str, name: str) -> str: ... - else: - def getuntil(self, terminator: str) -> str: ... + def getuntil(self, terminator: str, name: str) -> str: ... @property def pos(self) -> int: ... def tell(self) -> int: ... def seek(self, index: int) -> None: ... - def error(self, msg: str, offset: int = ...) -> _Error: ... + def error(self, msg: str, offset: int = 0) -> _Error: ... + + if sys.version_info >= (3, 12): + def checkgroupname(self, name: str, offset: int) -> None: ... + elif sys.version_info >= (3, 11): + def checkgroupname(self, name: str, offset: int, nested: int) -> None: ... def fix_flags(src: str | bytes, flags: int) -> int: ... -_TemplateType = Tuple[List[Tuple[int, int]], List[Optional[str]]] -_TemplateByteType = Tuple[List[Tuple[int, int]], List[Optional[bytes]]] -if sys.version_info >= (3, 8): - def parse(str: str, flags: int = ..., state: State | None = ...) -> SubPattern: ... - @overload - def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... - @overload - def parse_template(source: bytes, state: _Pattern[Any]) -> _TemplateByteType: ... +_TemplateType: TypeAlias = tuple[list[tuple[int, int]], list[str | None]] +_TemplateByteType: TypeAlias = tuple[list[tuple[int, int]], list[bytes | None]] -else: - def parse(str: str, flags: int = ..., pattern: Pattern | None = ...) -> SubPattern: ... +if sys.version_info >= (3, 12): @overload def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ... @overload def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ... +else: + @overload + def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... + @overload + def parse_template(source: bytes, state: _Pattern[Any]) -> _TemplateByteType: ... + +def parse(str: str, flags: int = 0, state: State | None = None) -> SubPattern: ... -def expand_template(template: _TemplateType, match: Match[Any]) -> str: ... +if sys.version_info < (3, 12): + def expand_template(template: _TemplateType, match: Match[Any]) -> str: ... diff --git a/stdlib/ssl.pyi b/stdlib/ssl.pyi index 628139634bac..dde30685599c 100644 --- a/stdlib/ssl.pyi +++ b/stdlib/ssl.pyi @@ -1,19 +1,59 @@ import enum import socket import sys -from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Type, Union, overload -from typing_extensions import Literal, TypedDict +from _ssl import ( + _DEFAULT_CIPHERS as _DEFAULT_CIPHERS, + _OPENSSL_API_VERSION as _OPENSSL_API_VERSION, + HAS_ALPN as HAS_ALPN, + HAS_ECDH as HAS_ECDH, + HAS_NPN as HAS_NPN, + HAS_SNI as HAS_SNI, + OPENSSL_VERSION as OPENSSL_VERSION, + OPENSSL_VERSION_INFO as OPENSSL_VERSION_INFO, + OPENSSL_VERSION_NUMBER as OPENSSL_VERSION_NUMBER, + HAS_SSLv2 as HAS_SSLv2, + HAS_SSLv3 as HAS_SSLv3, + HAS_TLSv1 as HAS_TLSv1, + HAS_TLSv1_1 as HAS_TLSv1_1, + HAS_TLSv1_2 as HAS_TLSv1_2, + HAS_TLSv1_3 as HAS_TLSv1_3, + MemoryBIO as MemoryBIO, + RAND_add as RAND_add, + RAND_bytes as RAND_bytes, + RAND_status as RAND_status, + SSLSession as SSLSession, + _PasswordType as _PasswordType, # typeshed only, but re-export for other type stubs to use + _SSLContext, +) +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from collections.abc import Callable, Iterable +from typing import Any, Final, Literal, NamedTuple, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Never, Self, deprecated + +if sys.version_info >= (3, 13): + from _ssl import HAS_PSK as HAS_PSK + +if sys.version_info >= (3, 15): + from _ssl import HAS_PSK_TLS13 as HAS_PSK_TLS13 + +if sys.version_info >= (3, 14): + from _ssl import HAS_PHA as HAS_PHA + +if sys.version_info < (3, 12): + from _ssl import RAND_pseudo_bytes as RAND_pseudo_bytes -_PCTRTT = Tuple[Tuple[str, str], ...] -_PCTRTTT = Tuple[_PCTRTT, ...] -_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] -_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] -_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] -_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] +if sys.platform == "win32": + from _ssl import enum_certificates as enum_certificates, enum_crls as enum_crls + +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] +_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType: TypeAlias = _PeerCertRetDictType | bytes | None +_SrvnmeCbType: TypeAlias = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] -_SrvnmeCbType = Callable[[Union[SSLSocket, SSLObject], Optional[str], SSLSocket], Optional[int]] +socket_error = OSError +@type_check_only class _Cipher(TypedDict): aead: bool alg_bits: int @@ -37,82 +77,11 @@ class SSLWantWriteError(SSLError): ... class SSLSyscallError(SSLError): ... class SSLEOFError(SSLError): ... -if sys.version_info >= (3, 7): - class SSLCertVerificationError(SSLError, ValueError): - verify_code: int - verify_message: str - CertificateError = SSLCertVerificationError -else: - class CertificateError(ValueError): ... - -def wrap_socket( - sock: socket.socket, - keyfile: StrOrBytesPath | None = ..., - certfile: StrOrBytesPath | None = ..., - server_side: bool = ..., - cert_reqs: int = ..., - ssl_version: int = ..., - ca_certs: str | None = ..., - do_handshake_on_connect: bool = ..., - suppress_ragged_eofs: bool = ..., - ciphers: str | None = ..., -) -> SSLSocket: ... -def create_default_context( - purpose: Purpose = ..., - *, - cafile: StrOrBytesPath | None = ..., - capath: StrOrBytesPath | None = ..., - cadata: str | bytes | None = ..., -) -> SSLContext: ... - -if sys.version_info >= (3, 7): - def _create_unverified_context( - protocol: int = ..., - *, - cert_reqs: int = ..., - check_hostname: bool = ..., - purpose: Purpose = ..., - certfile: StrOrBytesPath | None = ..., - keyfile: StrOrBytesPath | None = ..., - cafile: StrOrBytesPath | None = ..., - capath: StrOrBytesPath | None = ..., - cadata: str | bytes | None = ..., - ) -> SSLContext: ... - -else: - def _create_unverified_context( - protocol: int = ..., - *, - cert_reqs: int | None = ..., - check_hostname: bool = ..., - purpose: Purpose = ..., - certfile: StrOrBytesPath | None = ..., - keyfile: StrOrBytesPath | None = ..., - cafile: StrOrBytesPath | None = ..., - capath: StrOrBytesPath | None = ..., - cadata: str | bytes | None = ..., - ) -> SSLContext: ... - -_create_default_https_context: Callable[..., SSLContext] - -def RAND_bytes(__num: int) -> bytes: ... -def RAND_pseudo_bytes(__num: int) -> tuple[bytes, bool]: ... -def RAND_status() -> bool: ... -def RAND_egd(path: str) -> None: ... -def RAND_add(__s: bytes, __entropy: float) -> None: ... -def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ... -def cert_time_to_seconds(cert_time: str) -> int: ... - -if sys.version_info >= (3, 10): - def get_server_certificate( - addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ..., timeout: float = ... - ) -> str: ... - -else: - def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... +class SSLCertVerificationError(SSLError, ValueError): + verify_code: int + verify_message: str -def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... -def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... +CertificateError = SSLCertVerificationError class DefaultVerifyPaths(NamedTuple): cafile: str @@ -124,391 +93,448 @@ class DefaultVerifyPaths(NamedTuple): def get_default_verify_paths() -> DefaultVerifyPaths: ... -if sys.platform == "win32": - def enum_certificates(store_name: str) -> _EnumRetType: ... - def enum_crls(store_name: str) -> _EnumRetType: ... - class VerifyMode(enum.IntEnum): - CERT_NONE: int - CERT_OPTIONAL: int - CERT_REQUIRED: int + CERT_NONE = 0 + CERT_OPTIONAL = 1 + CERT_REQUIRED = 2 -CERT_NONE: VerifyMode -CERT_OPTIONAL: VerifyMode -CERT_REQUIRED: VerifyMode +CERT_NONE: Final = VerifyMode.CERT_NONE +CERT_OPTIONAL: Final = VerifyMode.CERT_OPTIONAL +CERT_REQUIRED: Final = VerifyMode.CERT_REQUIRED class VerifyFlags(enum.IntFlag): - VERIFY_DEFAULT: int - VERIFY_CRL_CHECK_LEAF: int - VERIFY_CRL_CHECK_CHAIN: int - VERIFY_X509_STRICT: int - VERIFY_X509_TRUSTED_FIRST: int - if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS: int - VERIFY_X509_PARTIAL_CHAIN: int - -VERIFY_DEFAULT: VerifyFlags -VERIFY_CRL_CHECK_LEAF: VerifyFlags -VERIFY_CRL_CHECK_CHAIN: VerifyFlags -VERIFY_X509_STRICT: VerifyFlags -VERIFY_X509_TRUSTED_FIRST: VerifyFlags - -if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS: VerifyFlags - VERIFY_X509_PARTIAL_CHAIN: VerifyFlags + VERIFY_DEFAULT = 0x00 + VERIFY_CRL_CHECK_LEAF = 0x04 + VERIFY_CRL_CHECK_CHAIN = 0x0C + VERIFY_X509_STRICT = 0x20 + VERIFY_X509_TRUSTED_FIRST = 0x8000 + VERIFY_ALLOW_PROXY_CERTS = 0x40 + VERIFY_X509_PARTIAL_CHAIN = 0x80000 + +VERIFY_DEFAULT: Final = VerifyFlags.VERIFY_DEFAULT +VERIFY_CRL_CHECK_LEAF: Final = VerifyFlags.VERIFY_CRL_CHECK_LEAF +VERIFY_CRL_CHECK_CHAIN: Final = VerifyFlags.VERIFY_CRL_CHECK_CHAIN +VERIFY_X509_STRICT: Final = VerifyFlags.VERIFY_X509_STRICT +VERIFY_X509_TRUSTED_FIRST: Final = VerifyFlags.VERIFY_X509_TRUSTED_FIRST +VERIFY_ALLOW_PROXY_CERTS: Final = VerifyFlags.VERIFY_ALLOW_PROXY_CERTS +VERIFY_X509_PARTIAL_CHAIN: Final = VerifyFlags.VERIFY_X509_PARTIAL_CHAIN class _SSLMethod(enum.IntEnum): - PROTOCOL_SSLv23: int - PROTOCOL_SSLv2: int - PROTOCOL_SSLv3: int - PROTOCOL_TLSv1: int - PROTOCOL_TLSv1_1: int - PROTOCOL_TLSv1_2: int - PROTOCOL_TLS: int - PROTOCOL_TLS_CLIENT: int - PROTOCOL_TLS_SERVER: int - -PROTOCOL_SSLv23: _SSLMethod -PROTOCOL_SSLv2: _SSLMethod -PROTOCOL_SSLv3: _SSLMethod -PROTOCOL_TLSv1: _SSLMethod -PROTOCOL_TLSv1_1: _SSLMethod -PROTOCOL_TLSv1_2: _SSLMethod -PROTOCOL_TLS: _SSLMethod -PROTOCOL_TLS_CLIENT: _SSLMethod -PROTOCOL_TLS_SERVER: _SSLMethod + PROTOCOL_SSLv23 = 2 + PROTOCOL_SSLv2 = ... + PROTOCOL_SSLv3 = ... + PROTOCOL_TLSv1 = 3 + PROTOCOL_TLSv1_1 = 4 + PROTOCOL_TLSv1_2 = 5 + PROTOCOL_TLS = 2 + PROTOCOL_TLS_CLIENT = 16 + PROTOCOL_TLS_SERVER = 17 + +PROTOCOL_SSLv23: Final = _SSLMethod.PROTOCOL_SSLv23 +PROTOCOL_SSLv2: Final = _SSLMethod.PROTOCOL_SSLv2 +PROTOCOL_SSLv3: Final = _SSLMethod.PROTOCOL_SSLv3 +PROTOCOL_TLSv1: Final = _SSLMethod.PROTOCOL_TLSv1 +PROTOCOL_TLSv1_1: Final = _SSLMethod.PROTOCOL_TLSv1_1 +PROTOCOL_TLSv1_2: Final = _SSLMethod.PROTOCOL_TLSv1_2 +PROTOCOL_TLS: Final = _SSLMethod.PROTOCOL_TLS +PROTOCOL_TLS_CLIENT: Final = _SSLMethod.PROTOCOL_TLS_CLIENT +PROTOCOL_TLS_SERVER: Final = _SSLMethod.PROTOCOL_TLS_SERVER class Options(enum.IntFlag): - OP_ALL: int - OP_NO_SSLv2: int - OP_NO_SSLv3: int - OP_NO_TLSv1: int - OP_NO_TLSv1_1: int - OP_NO_TLSv1_2: int - OP_NO_TLSv1_3: int - OP_CIPHER_SERVER_PREFERENCE: int - OP_SINGLE_DH_USE: int - OP_SINGLE_ECDH_USE: int - OP_NO_COMPRESSION: int - OP_NO_TICKET: int - if sys.version_info >= (3, 7): - OP_NO_RENEGOTIATION: int - if sys.version_info >= (3, 8): - OP_ENABLE_MIDDLEBOX_COMPAT: int - -OP_ALL: Options -OP_NO_SSLv2: Options -OP_NO_SSLv3: Options -OP_NO_TLSv1: Options -OP_NO_TLSv1_1: Options -OP_NO_TLSv1_2: Options -OP_NO_TLSv1_3: Options -OP_CIPHER_SERVER_PREFERENCE: Options -OP_SINGLE_DH_USE: Options -OP_SINGLE_ECDH_USE: Options -OP_NO_COMPRESSION: Options -OP_NO_TICKET: Options -if sys.version_info >= (3, 7): - OP_NO_RENEGOTIATION: Options -if sys.version_info >= (3, 8): - OP_ENABLE_MIDDLEBOX_COMPAT: Options - -if sys.version_info >= (3, 7): - HAS_NEVER_CHECK_COMMON_NAME: bool - HAS_SSLv2: bool - HAS_SSLv3: bool - HAS_TLSv1: bool - HAS_TLSv1_1: bool - HAS_TLSv1_2: bool -HAS_TLSv1_3: bool -HAS_ALPN: bool -HAS_ECDH: bool -HAS_SNI: bool -HAS_NPN: bool -CHANNEL_BINDING_TYPES: list[str] - -OPENSSL_VERSION: str -OPENSSL_VERSION_INFO: tuple[int, int, int, int, int] -OPENSSL_VERSION_NUMBER: int + OP_ALL = ... + OP_NO_SSLv2 = 0 + OP_NO_SSLv3 = 33554432 + OP_NO_TLSv1 = 67108864 + OP_NO_TLSv1_1 = 268435456 + OP_NO_TLSv1_2 = 134217728 + OP_NO_TLSv1_3 = 536870912 + OP_CIPHER_SERVER_PREFERENCE = 4194304 + OP_SINGLE_DH_USE = 0 + OP_SINGLE_ECDH_USE = 0 + OP_NO_COMPRESSION = 131072 + OP_NO_TICKET = 16384 + OP_NO_RENEGOTIATION = 1073741824 + OP_ENABLE_MIDDLEBOX_COMPAT = 1048576 + if sys.version_info >= (3, 12): + OP_LEGACY_SERVER_CONNECT = 4 + OP_ENABLE_KTLS = 8 + if sys.version_info >= (3, 11) or sys.platform == "linux": + OP_IGNORE_UNEXPECTED_EOF = 128 + +OP_ALL: Final = Options.OP_ALL +OP_NO_SSLv2: Final = Options.OP_NO_SSLv2 +OP_NO_SSLv3: Final = Options.OP_NO_SSLv3 +OP_NO_TLSv1: Final = Options.OP_NO_TLSv1 +OP_NO_TLSv1_1: Final = Options.OP_NO_TLSv1_1 +OP_NO_TLSv1_2: Final = Options.OP_NO_TLSv1_2 +OP_NO_TLSv1_3: Final = Options.OP_NO_TLSv1_3 +OP_CIPHER_SERVER_PREFERENCE: Final = Options.OP_CIPHER_SERVER_PREFERENCE +OP_SINGLE_DH_USE: Final = Options.OP_SINGLE_DH_USE +OP_SINGLE_ECDH_USE: Final = Options.OP_SINGLE_ECDH_USE +OP_NO_COMPRESSION: Final = Options.OP_NO_COMPRESSION +OP_NO_TICKET: Final = Options.OP_NO_TICKET +OP_NO_RENEGOTIATION: Final = Options.OP_NO_RENEGOTIATION +OP_ENABLE_MIDDLEBOX_COMPAT: Final = Options.OP_ENABLE_MIDDLEBOX_COMPAT +if sys.version_info >= (3, 12): + OP_LEGACY_SERVER_CONNECT: Final = Options.OP_LEGACY_SERVER_CONNECT + OP_ENABLE_KTLS: Final = Options.OP_ENABLE_KTLS +if sys.version_info >= (3, 11) or sys.platform == "linux": + OP_IGNORE_UNEXPECTED_EOF: Final = Options.OP_IGNORE_UNEXPECTED_EOF + +HAS_NEVER_CHECK_COMMON_NAME: Final[bool] + +CHANNEL_BINDING_TYPES: Final[list[str]] class AlertDescription(enum.IntEnum): - ALERT_DESCRIPTION_ACCESS_DENIED: int - ALERT_DESCRIPTION_BAD_CERTIFICATE: int - ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int - ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int - ALERT_DESCRIPTION_BAD_RECORD_MAC: int - ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int - ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int - ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int - ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int - ALERT_DESCRIPTION_CLOSE_NOTIFY: int - ALERT_DESCRIPTION_DECODE_ERROR: int - ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int - ALERT_DESCRIPTION_DECRYPT_ERROR: int - ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int - ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int - ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int - ALERT_DESCRIPTION_INTERNAL_ERROR: int - ALERT_DESCRIPTION_NO_RENEGOTIATION: int - ALERT_DESCRIPTION_PROTOCOL_VERSION: int - ALERT_DESCRIPTION_RECORD_OVERFLOW: int - ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int - ALERT_DESCRIPTION_UNKNOWN_CA: int - ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int - ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int - ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int - ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int - ALERT_DESCRIPTION_USER_CANCELLED: int - -ALERT_DESCRIPTION_HANDSHAKE_FAILURE: AlertDescription -ALERT_DESCRIPTION_INTERNAL_ERROR: AlertDescription -ALERT_DESCRIPTION_ACCESS_DENIED: AlertDescription -ALERT_DESCRIPTION_BAD_CERTIFICATE: AlertDescription -ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: AlertDescription -ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: AlertDescription -ALERT_DESCRIPTION_BAD_RECORD_MAC: AlertDescription -ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: AlertDescription -ALERT_DESCRIPTION_CERTIFICATE_REVOKED: AlertDescription -ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: AlertDescription -ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: AlertDescription -ALERT_DESCRIPTION_CLOSE_NOTIFY: AlertDescription -ALERT_DESCRIPTION_DECODE_ERROR: AlertDescription -ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: AlertDescription -ALERT_DESCRIPTION_DECRYPT_ERROR: AlertDescription -ALERT_DESCRIPTION_ILLEGAL_PARAMETER: AlertDescription -ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: AlertDescription -ALERT_DESCRIPTION_NO_RENEGOTIATION: AlertDescription -ALERT_DESCRIPTION_PROTOCOL_VERSION: AlertDescription -ALERT_DESCRIPTION_RECORD_OVERFLOW: AlertDescription -ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: AlertDescription -ALERT_DESCRIPTION_UNKNOWN_CA: AlertDescription -ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: AlertDescription -ALERT_DESCRIPTION_UNRECOGNIZED_NAME: AlertDescription -ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: AlertDescription -ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: AlertDescription -ALERT_DESCRIPTION_USER_CANCELLED: AlertDescription - -class _ASN1Object(NamedTuple): + ALERT_DESCRIPTION_ACCESS_DENIED = 49 + ALERT_DESCRIPTION_BAD_CERTIFICATE = 42 + ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = 114 + ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = 113 + ALERT_DESCRIPTION_BAD_RECORD_MAC = 20 + ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = 45 + ALERT_DESCRIPTION_CERTIFICATE_REVOKED = 44 + ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = 46 + ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = 111 + ALERT_DESCRIPTION_CLOSE_NOTIFY = 0 + ALERT_DESCRIPTION_DECODE_ERROR = 50 + ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = 30 + ALERT_DESCRIPTION_DECRYPT_ERROR = 51 + ALERT_DESCRIPTION_HANDSHAKE_FAILURE = 40 + ALERT_DESCRIPTION_ILLEGAL_PARAMETER = 47 + ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = 71 + ALERT_DESCRIPTION_INTERNAL_ERROR = 80 + ALERT_DESCRIPTION_NO_RENEGOTIATION = 100 + ALERT_DESCRIPTION_PROTOCOL_VERSION = 70 + ALERT_DESCRIPTION_RECORD_OVERFLOW = 22 + ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = 10 + ALERT_DESCRIPTION_UNKNOWN_CA = 48 + ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = 115 + ALERT_DESCRIPTION_UNRECOGNIZED_NAME = 112 + ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = 43 + ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = 110 + ALERT_DESCRIPTION_USER_CANCELLED = 90 + +ALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = AlertDescription.ALERT_DESCRIPTION_HANDSHAKE_FAILURE +ALERT_DESCRIPTION_INTERNAL_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_INTERNAL_ERROR +ALERT_DESCRIPTION_ACCESS_DENIED: Final = AlertDescription.ALERT_DESCRIPTION_ACCESS_DENIED +ALERT_DESCRIPTION_BAD_CERTIFICATE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE +ALERT_DESCRIPTION_BAD_RECORD_MAC: Final = AlertDescription.ALERT_DESCRIPTION_BAD_RECORD_MAC +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_EXPIRED +ALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_REVOKED +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE +ALERT_DESCRIPTION_CLOSE_NOTIFY: Final = AlertDescription.ALERT_DESCRIPTION_CLOSE_NOTIFY +ALERT_DESCRIPTION_DECODE_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_DECODE_ERROR +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = AlertDescription.ALERT_DESCRIPTION_DECOMPRESSION_FAILURE +ALERT_DESCRIPTION_DECRYPT_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_DECRYPT_ERROR +ALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = AlertDescription.ALERT_DESCRIPTION_ILLEGAL_PARAMETER +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = AlertDescription.ALERT_DESCRIPTION_INSUFFICIENT_SECURITY +ALERT_DESCRIPTION_NO_RENEGOTIATION: Final = AlertDescription.ALERT_DESCRIPTION_NO_RENEGOTIATION +ALERT_DESCRIPTION_PROTOCOL_VERSION: Final = AlertDescription.ALERT_DESCRIPTION_PROTOCOL_VERSION +ALERT_DESCRIPTION_RECORD_OVERFLOW: Final = AlertDescription.ALERT_DESCRIPTION_RECORD_OVERFLOW +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = AlertDescription.ALERT_DESCRIPTION_UNEXPECTED_MESSAGE +ALERT_DESCRIPTION_UNKNOWN_CA: Final = AlertDescription.ALERT_DESCRIPTION_UNKNOWN_CA +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = AlertDescription.ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY +ALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = AlertDescription.ALERT_DESCRIPTION_UNRECOGNIZED_NAME +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = AlertDescription.ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = AlertDescription.ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION +ALERT_DESCRIPTION_USER_CANCELLED: Final = AlertDescription.ALERT_DESCRIPTION_USER_CANCELLED + +# This class is not exposed. It calls itself ssl._ASN1Object. +@type_check_only +class _ASN1ObjectBase(NamedTuple): nid: int shortname: str longname: str oid: str + +class _ASN1Object(_ASN1ObjectBase): + def __new__(cls, oid: str) -> Self: ... @classmethod - def fromnid(cls: Type[Self], nid: int) -> Self: ... + def fromnid(cls, nid: int) -> Self: ... @classmethod - def fromname(cls: Type[Self], name: str) -> Self: ... + def fromname(cls, name: str) -> Self: ... class Purpose(_ASN1Object, enum.Enum): - SERVER_AUTH: _ASN1Object - CLIENT_AUTH: _ASN1Object + # Normally this class would inherit __new__ from _ASN1Object, but + # because this is an enum, the inherited __new__ is replaced at runtime with + # Enum.__new__. + def __new__(cls, value: object) -> Self: ... + SERVER_AUTH = ( # ty:ignore[invalid-assignment] + 129, + "serverAuth", + "TLS Web Server Authentication", + "1.3.6.1.5.5.7.3.2", + ) # pyright: ignore[reportCallIssue] + CLIENT_AUTH = ( # ty:ignore[invalid-assignment] + 130, + "clientAuth", + "TLS Web Client Authentication", + "1.3.6.1.5.5.7.3.1", + ) # pyright: ignore[reportCallIssue] class SSLSocket(socket.socket): context: SSLContext server_side: bool server_hostname: str | None session: SSLSession | None - session_reused: bool | None - if sys.version_info >= (3, 7): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - else: - def __init__( - self, - sock: socket.socket | None = ..., - keyfile: str | None = ..., - certfile: str | None = ..., - server_side: bool = ..., - cert_reqs: int = ..., - ssl_version: int = ..., - ca_certs: str | None = ..., - do_handshake_on_connect: bool = ..., - family: int = ..., - type: int = ..., - proto: int = ..., - fileno: int | None = ..., - suppress_ragged_eofs: bool = ..., - npn_protocols: Iterable[str] | None = ..., - ciphers: str | None = ..., - server_hostname: str | None = ..., - _context: SSLContext | None = ..., - _session: Any | None = ..., - ) -> None: ... - def connect(self, addr: socket._Address | bytes) -> None: ... - def connect_ex(self, addr: socket._Address | bytes) -> int: ... - def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... - def recv_into(self, buffer: WriteableBuffer, nbytes: int | None = ..., flags: int = ...) -> int: ... - def recvfrom(self, buflen: int = ..., flags: int = ...) -> tuple[bytes, socket._RetAddress]: ... + @property + def session_reused(self) -> bool | None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def connect(self, addr: socket._Address) -> None: ... + def connect_ex(self, addr: socket._Address) -> int: ... + def recv(self, buflen: int = 1024, flags: int = 0) -> bytes: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int | None = None, flags: int = 0) -> int: ... + def recvfrom(self, buflen: int = 1024, flags: int = 0) -> tuple[bytes, socket._RetAddress]: ... def recvfrom_into( - self, buffer: WriteableBuffer, nbytes: int | None = ..., flags: int = ... + self, buffer: WriteableBuffer, nbytes: int | None = None, flags: int = 0 ) -> tuple[int, socket._RetAddress]: ... - def send(self, data: ReadableBuffer, flags: int = ...) -> int: ... - def sendall(self, data: ReadableBuffer, flags: int = ...) -> None: ... + def send(self, data: ReadableBuffer, flags: int = 0) -> int: ... + def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ... + @overload - def sendto(self, data: ReadableBuffer, flags_or_addr: socket._Address) -> int: ... + def sendto(self, data: ReadableBuffer, flags_or_addr: socket._Address, addr: None = None) -> int: ... @overload - def sendto(self, data: ReadableBuffer, flags_or_addr: int | socket._Address, addr: socket._Address | None = ...) -> int: ... + def sendto(self, data: ReadableBuffer, flags_or_addr: int, addr: socket._Address) -> int: ... + def shutdown(self, how: int) -> None: ... - def read(self, len: int = ..., buffer: bytearray | None = ...) -> bytes: ... - def write(self, data: bytes) -> int: ... - def do_handshake(self, block: bool = ...) -> None: ... # block is undocumented + @deprecated("Deprecated since Python 3.6. Use `SSLSocket.recv` method instead.") + def read(self, len: int = 1024, buffer: WriteableBuffer | None = None) -> bytes: ... + @deprecated("Deprecated since Python 3.6. Use `SSLSocket.send` method instead.") + def write(self, data: ReadableBuffer) -> int: ... + def do_handshake(self, block: bool = False) -> None: ... # block is undocumented + @overload - def getpeercert(self, binary_form: Literal[False] = ...) -> _PeerCertRetDictType | None: ... + def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ... @overload def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + def cipher(self) -> tuple[str, str, int] | None: ... def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ... def compression(self) -> str | None: ... - def get_channel_binding(self, cb_type: str = ...) -> bytes | None: ... + if sys.version_info >= (3, 15): + def group(self) -> str | None: ... + def client_sigalg(self) -> str | None: ... + def server_sigalg(self) -> str | None: ... + + def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... def selected_alpn_protocol(self) -> str | None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") def selected_npn_protocol(self) -> str | None: ... def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ... def unwrap(self) -> socket.socket: ... def version(self) -> str | None: ... def pending(self) -> int: ... - if sys.version_info >= (3, 8): - def verify_client_post_handshake(self) -> None: ... - -if sys.version_info >= (3, 7): - class TLSVersion(enum.IntEnum): - MINIMUM_SUPPORTED: int - MAXIMUM_SUPPORTED: int - SSLv3: int - TLSv1: int - TLSv1_1: int - TLSv1_2: int - TLSv1_3: int - -class SSLContext: - check_hostname: bool + def verify_client_post_handshake(self) -> None: ... + # These methods always raise `NotImplementedError`: + def recvmsg(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + def recvmsg_into(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + def sendmsg(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + if sys.version_info >= (3, 13): + def get_verified_chain(self) -> list[bytes]: ... + def get_unverified_chain(self) -> list[bytes]: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.7; removed in Python 3.12. Use `SSLContext.wrap_socket()` instead.") + def wrap_socket( + sock: socket.socket, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + server_side: bool = False, + cert_reqs: int = VerifyMode.CERT_NONE, + ssl_version: int = _SSLMethod.PROTOCOL_TLS, + ca_certs: str | None = None, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str | None = None, + ) -> SSLSocket: ... + @deprecated("Deprecated since Python 3.7; removed in Python 3.12.") + def match_hostname(cert: _PeerCertRetDictType, hostname: str) -> None: ... + +def cert_time_to_seconds(cert_time: str) -> int: ... +def DER_cert_to_PEM_cert(der_cert_bytes: ReadableBuffer) -> str: ... +def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... +def get_server_certificate( + addr: tuple[str, int], ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT, ca_certs: str | None = None, timeout: float = ... +) -> str: ... + +class TLSVersion(enum.IntEnum): + MINIMUM_SUPPORTED = -2 + MAXIMUM_SUPPORTED = -1 + SSLv3 = 768 + TLSv1 = 769 + TLSv1_1 = 770 + TLSv1_2 = 771 + TLSv1_3 = 772 + +class SSLContext(_SSLContext): options: Options verify_flags: VerifyFlags verify_mode: VerifyMode @property - def protocol(self) -> _SSLMethod: ... - if sys.version_info >= (3, 7): - hostname_checks_common_name: bool - maximum_version: TLSVersion - minimum_version: TLSVersion - sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None - sslobject_class: ClassVar[Type[SSLObject]] - sslsocket_class: ClassVar[Type[SSLSocket]] - if sys.version_info >= (3, 8): - keylog_filename: str - post_handshake_auth: bool - def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> SSLContext: ... - def __init__(self, protocol: int = ...) -> None: ... - def cert_store_stats(self) -> dict[str, int]: ... - def load_cert_chain( - self, certfile: StrOrBytesPath, keyfile: StrOrBytesPath | None = ..., password: _PasswordType | None = ... - ) -> None: ... - def load_default_certs(self, purpose: Purpose = ...) -> None: ... + def protocol(self) -> _SSLMethod: ... # type: ignore[override] + hostname_checks_common_name: bool + maximum_version: TLSVersion + minimum_version: TLSVersion + # The following two attributes have class-level defaults. + # However, the docs explicitly state that it's OK to override these attributes on instances, + # so making these ClassVars wouldn't be appropriate + sslobject_class: type[SSLObject] + sslsocket_class: type[SSLSocket] + keylog_filename: str + post_handshake_auth: bool + security_level: int + + @overload + def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> Self: ... + @overload + @deprecated("Deprecated since Python 3.10. Use a specific version of the SSL protocol.") + def __new__(cls, protocol: None = None, *args: Any, **kwargs: Any) -> Self: ... + + def load_default_certs(self, purpose: Purpose = Purpose.SERVER_AUTH) -> None: ... def load_verify_locations( - self, cafile: StrOrBytesPath | None = ..., capath: StrOrBytesPath | None = ..., cadata: str | bytes | None = ... + self, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, ) -> None: ... - def get_ca_certs(self, binary_form: bool = ...) -> list[_PeerCertRetDictType] | list[bytes]: ... + + @overload + def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ... + @overload + def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: bool = False) -> Any: ... + def get_ciphers(self) -> list[_Cipher]: ... + if sys.version_info >= (3, 15): + def set_ciphersuites(self, ciphersuites: str, /) -> None: ... + def get_groups(self, /, *, include_aliases: bool = False) -> list[str]: ... + def set_groups(self, grouplist: str, /) -> None: ... + def set_client_sigalgs(self, sigalgs: str, /) -> None: ... + def set_server_sigalgs(self, sigalgs: str, /) -> None: ... + def set_default_verify_paths(self) -> None: ... - def set_ciphers(self, __cipherlist: str) -> None: ... + def set_ciphers(self, cipherlist: str, /) -> None: ... def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... - if sys.version_info >= (3, 7): - def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ... - else: - def set_servername_callback(self, __method: _SrvnmeCbType | None) -> None: ... - def load_dh_params(self, __path: str) -> None: ... - def set_ecdh_curve(self, __name: str) -> None: ... + def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ... + def load_dh_params(self, path: str, /) -> None: ... + def set_ecdh_curve(self, name: str, /) -> None: ... def wrap_socket( self, sock: socket.socket, - server_side: bool = ..., - do_handshake_on_connect: bool = ..., - suppress_ragged_eofs: bool = ..., - server_hostname: str | None = ..., - session: SSLSession | None = ..., + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: str | bytes | None = None, + session: SSLSession | None = None, ) -> SSLSocket: ... def wrap_bio( self, incoming: MemoryBIO, outgoing: MemoryBIO, - server_side: bool = ..., - server_hostname: str | None = ..., - session: SSLSession | None = ..., + server_side: bool = False, + server_hostname: str | bytes | None = None, + session: SSLSession | None = None, ) -> SSLObject: ... - def session_stats(self) -> dict[str, int]: ... + +def create_default_context( + purpose: Purpose = Purpose.SERVER_AUTH, + *, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, +) -> SSLContext: ... +def _create_unverified_context( + protocol: int | None = None, + *, + cert_reqs: int = VerifyMode.CERT_NONE, + check_hostname: bool = False, + purpose: Purpose = Purpose.SERVER_AUTH, + certfile: StrOrBytesPath | None = None, + keyfile: StrOrBytesPath | None = None, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, +) -> SSLContext: ... + +_create_default_https_context = create_default_context class SSLObject: context: SSLContext - server_side: bool - server_hostname: str | None + @property + def server_side(self) -> bool: ... + @property + def server_hostname(self) -> str | None: ... session: SSLSession | None - session_reused: bool - if sys.version_info >= (3, 7): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - else: - def __init__(self, sslobj: Any, owner: SSLSocket | SSLObject | None = ..., session: Any | None = ...) -> None: ... - def read(self, len: int = ..., buffer: bytearray | None = ...) -> bytes: ... - def write(self, data: bytes) -> int: ... + @property + def session_reused(self) -> bool: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def read(self, len: int = 1024, buffer: WriteableBuffer | None = None) -> bytes: ... + def write(self, data: ReadableBuffer) -> int: ... + @overload - def getpeercert(self, binary_form: Literal[False] = ...) -> _PeerCertRetDictType | None: ... + def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ... @overload def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + def selected_alpn_protocol(self) -> str | None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") def selected_npn_protocol(self) -> str | None: ... def cipher(self) -> tuple[str, str, int] | None: ... def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ... def compression(self) -> str | None: ... + if sys.version_info >= (3, 15): + def group(self) -> str | None: ... + def client_sigalg(self) -> str | None: ... + def server_sigalg(self) -> str | None: ... + def pending(self) -> int: ... def do_handshake(self) -> None: ... def unwrap(self) -> None: ... def version(self) -> str | None: ... - def get_channel_binding(self, cb_type: str = ...) -> bytes | None: ... - if sys.version_info >= (3, 8): - def verify_client_post_handshake(self) -> None: ... - -class MemoryBIO: - pending: int - eof: bool - def read(self, __size: int = ...) -> bytes: ... - def write(self, __buf: bytes) -> int: ... - def write_eof(self) -> None: ... - -class SSLSession: - id: bytes - time: int - timeout: int - ticket_lifetime_hint: int - has_ticket: bool + def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... + def verify_client_post_handshake(self) -> None: ... + if sys.version_info >= (3, 13): + def get_verified_chain(self) -> list[bytes]: ... + def get_unverified_chain(self) -> list[bytes]: ... class SSLErrorNumber(enum.IntEnum): - SSL_ERROR_EOF: int - SSL_ERROR_INVALID_ERROR_CODE: int - SSL_ERROR_SSL: int - SSL_ERROR_SYSCALL: int - SSL_ERROR_WANT_CONNECT: int - SSL_ERROR_WANT_READ: int - SSL_ERROR_WANT_WRITE: int - SSL_ERROR_WANT_X509_LOOKUP: int - SSL_ERROR_ZERO_RETURN: int - -SSL_ERROR_EOF: SSLErrorNumber # undocumented -SSL_ERROR_INVALID_ERROR_CODE: SSLErrorNumber # undocumented -SSL_ERROR_SSL: SSLErrorNumber # undocumented -SSL_ERROR_SYSCALL: SSLErrorNumber # undocumented -SSL_ERROR_WANT_CONNECT: SSLErrorNumber # undocumented -SSL_ERROR_WANT_READ: SSLErrorNumber # undocumented -SSL_ERROR_WANT_WRITE: SSLErrorNumber # undocumented -SSL_ERROR_WANT_X509_LOOKUP: SSLErrorNumber # undocumented -SSL_ERROR_ZERO_RETURN: SSLErrorNumber # undocumented + SSL_ERROR_EOF = 8 + SSL_ERROR_INVALID_ERROR_CODE = 10 + SSL_ERROR_SSL = 1 + SSL_ERROR_SYSCALL = 5 + SSL_ERROR_WANT_CONNECT = 7 + SSL_ERROR_WANT_READ = 2 + SSL_ERROR_WANT_WRITE = 3 + SSL_ERROR_WANT_X509_LOOKUP = 4 + SSL_ERROR_ZERO_RETURN = 6 + +SSL_ERROR_EOF: Final = SSLErrorNumber.SSL_ERROR_EOF # undocumented +SSL_ERROR_INVALID_ERROR_CODE: Final = SSLErrorNumber.SSL_ERROR_INVALID_ERROR_CODE # undocumented +SSL_ERROR_SSL: Final = SSLErrorNumber.SSL_ERROR_SSL # undocumented +SSL_ERROR_SYSCALL: Final = SSLErrorNumber.SSL_ERROR_SYSCALL # undocumented +SSL_ERROR_WANT_CONNECT: Final = SSLErrorNumber.SSL_ERROR_WANT_CONNECT # undocumented +SSL_ERROR_WANT_READ: Final = SSLErrorNumber.SSL_ERROR_WANT_READ # undocumented +SSL_ERROR_WANT_WRITE: Final = SSLErrorNumber.SSL_ERROR_WANT_WRITE # undocumented +SSL_ERROR_WANT_X509_LOOKUP: Final = SSLErrorNumber.SSL_ERROR_WANT_X509_LOOKUP # undocumented +SSL_ERROR_ZERO_RETURN: Final = SSLErrorNumber.SSL_ERROR_ZERO_RETURN # undocumented def get_protocol_name(protocol_code: int) -> str: ... -if sys.version_info < (3, 9): - AF_INET: int -PEM_FOOTER: str -PEM_HEADER: str -SOCK_STREAM: int -SOL_SOCKET: int -SO_TYPE: int +if sys.version_info >= (3, 15): + def get_sigalgs() -> list[str]: ... + +PEM_FOOTER: Final[str] +PEM_HEADER: Final[str] +SOCK_STREAM: Final = socket.SOCK_STREAM +SOL_SOCKET: Final = socket.SOL_SOCKET +SO_TYPE: Final = socket.SO_TYPE diff --git a/stdlib/stat.pyi b/stdlib/stat.pyi index f49ff711daf3..155d765d2b16 100644 --- a/stdlib/stat.pyi +++ b/stdlib/stat.pyi @@ -1,96 +1,126 @@ import sys +from _stat import ( + S_ENFMT as S_ENFMT, + S_IEXEC as S_IEXEC, + S_IFBLK as S_IFBLK, + S_IFCHR as S_IFCHR, + S_IFDIR as S_IFDIR, + S_IFDOOR as S_IFDOOR, + S_IFIFO as S_IFIFO, + S_IFLNK as S_IFLNK, + S_IFMT as S_IFMT, + S_IFPORT as S_IFPORT, + S_IFREG as S_IFREG, + S_IFSOCK as S_IFSOCK, + S_IFWHT as S_IFWHT, + S_IMODE as S_IMODE, + S_IREAD as S_IREAD, + S_IRGRP as S_IRGRP, + S_IROTH as S_IROTH, + S_IRUSR as S_IRUSR, + S_IRWXG as S_IRWXG, + S_IRWXO as S_IRWXO, + S_IRWXU as S_IRWXU, + S_ISBLK as S_ISBLK, + S_ISCHR as S_ISCHR, + S_ISDIR as S_ISDIR, + S_ISDOOR as S_ISDOOR, + S_ISFIFO as S_ISFIFO, + S_ISGID as S_ISGID, + S_ISLNK as S_ISLNK, + S_ISPORT as S_ISPORT, + S_ISREG as S_ISREG, + S_ISSOCK as S_ISSOCK, + S_ISUID as S_ISUID, + S_ISVTX as S_ISVTX, + S_ISWHT as S_ISWHT, + S_IWGRP as S_IWGRP, + S_IWOTH as S_IWOTH, + S_IWRITE as S_IWRITE, + S_IWUSR as S_IWUSR, + S_IXGRP as S_IXGRP, + S_IXOTH as S_IXOTH, + S_IXUSR as S_IXUSR, + SF_APPEND as SF_APPEND, + SF_ARCHIVED as SF_ARCHIVED, + SF_IMMUTABLE as SF_IMMUTABLE, + SF_NOUNLINK as SF_NOUNLINK, + SF_SNAPSHOT as SF_SNAPSHOT, + ST_ATIME as ST_ATIME, + ST_CTIME as ST_CTIME, + ST_DEV as ST_DEV, + ST_GID as ST_GID, + ST_INO as ST_INO, + ST_MODE as ST_MODE, + ST_MTIME as ST_MTIME, + ST_NLINK as ST_NLINK, + ST_SIZE as ST_SIZE, + ST_UID as ST_UID, + UF_APPEND as UF_APPEND, + UF_COMPRESSED as UF_COMPRESSED, + UF_HIDDEN as UF_HIDDEN, + UF_IMMUTABLE as UF_IMMUTABLE, + UF_NODUMP as UF_NODUMP, + UF_NOUNLINK as UF_NOUNLINK, + UF_OPAQUE as UF_OPAQUE, + filemode as filemode, +) +from typing import Final -def S_ISDIR(mode: int) -> bool: ... -def S_ISCHR(mode: int) -> bool: ... -def S_ISBLK(mode: int) -> bool: ... -def S_ISREG(mode: int) -> bool: ... -def S_ISFIFO(mode: int) -> bool: ... -def S_ISLNK(mode: int) -> bool: ... -def S_ISSOCK(mode: int) -> bool: ... -def S_IMODE(mode: int) -> int: ... -def S_IFMT(mode: int) -> int: ... -def S_ISDOOR(mode: int) -> int: ... -def S_ISPORT(mode: int) -> int: ... -def S_ISWHT(mode: int) -> int: ... -def filemode(mode: int) -> str: ... +if sys.platform == "win32": + from _stat import ( + IO_REPARSE_TAG_APPEXECLINK as IO_REPARSE_TAG_APPEXECLINK, + IO_REPARSE_TAG_MOUNT_POINT as IO_REPARSE_TAG_MOUNT_POINT, + IO_REPARSE_TAG_SYMLINK as IO_REPARSE_TAG_SYMLINK, + ) -ST_MODE: int -ST_INO: int -ST_DEV: int -ST_NLINK: int -ST_UID: int -ST_GID: int -ST_SIZE: int -ST_ATIME: int -ST_MTIME: int -ST_CTIME: int +if sys.version_info >= (3, 13): + from _stat import ( + SF_DATALESS as SF_DATALESS, + SF_FIRMLINK as SF_FIRMLINK, + SF_SETTABLE as SF_SETTABLE, + UF_DATAVAULT as UF_DATAVAULT, + UF_SETTABLE as UF_SETTABLE, + UF_TRACKED as UF_TRACKED, + ) -S_IFSOCK: int -S_IFLNK: int -S_IFREG: int -S_IFBLK: int -S_IFDIR: int -S_IFCHR: int -S_IFIFO: int -S_IFDOOR: int -S_IFPORT: int -S_IFWHT: int -S_ISUID: int -S_ISGID: int -S_ISVTX: int + if sys.platform == "darwin": + from _stat import SF_SUPPORTED as SF_SUPPORTED, SF_SYNTHETIC as SF_SYNTHETIC -S_IRWXU: int -S_IRUSR: int -S_IWUSR: int -S_IXUSR: int +# _stat.c defines FILE_ATTRIBUTE_* constants conditionally, +# making them available only at runtime on Windows. +# stat.py unconditionally redefines the same FILE_ATTRIBUTE_* constants +# on all platforms. +FILE_ATTRIBUTE_ARCHIVE: Final = 32 +FILE_ATTRIBUTE_COMPRESSED: Final = 2048 +FILE_ATTRIBUTE_DEVICE: Final = 64 +FILE_ATTRIBUTE_DIRECTORY: Final = 16 +FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 +FILE_ATTRIBUTE_HIDDEN: Final = 2 +FILE_ATTRIBUTE_INTEGRITY_STREAM: Final = 32768 +FILE_ATTRIBUTE_NORMAL: Final = 128 +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 +FILE_ATTRIBUTE_NO_SCRUB_DATA: Final = 131072 +FILE_ATTRIBUTE_OFFLINE: Final = 4096 +FILE_ATTRIBUTE_READONLY: Final = 1 +FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 +FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 +FILE_ATTRIBUTE_SYSTEM: Final = 4 +FILE_ATTRIBUTE_TEMPORARY: Final = 256 +FILE_ATTRIBUTE_VIRTUAL: Final = 65536 -S_IRWXG: int -S_IRGRP: int -S_IWGRP: int -S_IXGRP: int +if sys.version_info >= (3, 13): + # https://github.com/python/cpython/issues/114081#issuecomment-2119017790 + SF_RESTRICTED: Final = 0x00080000 -S_IRWXO: int -S_IROTH: int -S_IWOTH: int -S_IXOTH: int - -S_ENFMT: int -S_IREAD: int -S_IWRITE: int -S_IEXEC: int - -UF_NODUMP: int -UF_IMMUTABLE: int -UF_APPEND: int -UF_OPAQUE: int -UF_NOUNLINK: int -UF_COMPRESSED: int # OS X 10.6+ only -UF_HIDDEN: int # OX X 10.5+ only -SF_ARCHIVED: int -SF_IMMUTABLE: int -SF_APPEND: int -SF_NOUNLINK: int -SF_SNAPSHOT: int - -FILE_ATTRIBUTE_ARCHIVE: int -FILE_ATTRIBUTE_COMPRESSED: int -FILE_ATTRIBUTE_DEVICE: int -FILE_ATTRIBUTE_DIRECTORY: int -FILE_ATTRIBUTE_ENCRYPTED: int -FILE_ATTRIBUTE_HIDDEN: int -FILE_ATTRIBUTE_INTEGRITY_STREAM: int -FILE_ATTRIBUTE_NORMAL: int -FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: int -FILE_ATTRIBUTE_NO_SCRUB_DATA: int -FILE_ATTRIBUTE_OFFLINE: int -FILE_ATTRIBUTE_READONLY: int -FILE_ATTRIBUTE_REPARSE_POINT: int -FILE_ATTRIBUTE_SPARSE_FILE: int -FILE_ATTRIBUTE_SYSTEM: int -FILE_ATTRIBUTE_TEMPORARY: int -FILE_ATTRIBUTE_VIRTUAL: int - -if sys.platform == "win32" and sys.version_info >= (3, 8): - IO_REPARSE_TAG_SYMLINK: int - IO_REPARSE_TAG_MOUNT_POINT: int - IO_REPARSE_TAG_APPEXECLINK: int +if sys.version_info >= (3, 15): + STATX_ATTR_COMPRESSED: Final = 0x00000004 + STATX_ATTR_IMMUTABLE: Final = 0x00000010 + STATX_ATTR_APPEND: Final = 0x00000020 + STATX_ATTR_NODUMP: Final = 0x00000040 + STATX_ATTR_ENCRYPTED: Final = 0x00000800 + STATX_ATTR_AUTOMOUNT: Final = 0x00001000 + STATX_ATTR_MOUNT_ROOT: Final = 0x00002000 + STATX_ATTR_VERITY: Final = 0x00100000 + STATX_ATTR_DAX: Final = 0x00200000 + STATX_ATTR_WRITE_ATOMIC: Final = 0x00400000 diff --git a/stdlib/statistics.pyi b/stdlib/statistics.pyi index 908d6adaf45d..8cae237f7e0b 100644 --- a/stdlib/statistics.pyi +++ b/stdlib/statistics.pyi @@ -1,87 +1,161 @@ import sys from _typeshed import SupportsRichComparisonT +from collections.abc import Callable, Hashable, Iterable, Sequence, Sized from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, Type, TypeVar, Union +from typing import Literal, NamedTuple, Protocol, SupportsFloat, SupportsIndex, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self + +__all__ = [ + "StatisticsError", + "covariance", + "correlation", + "fmean", + "geometric_mean", + "linear_regression", + "mean", + "harmonic_mean", + "pstdev", + "pvariance", + "stdev", + "variance", + "median", + "median_low", + "median_high", + "median_grouped", + "mode", + "multimode", + "NormalDist", + "quantiles", +] + +if sys.version_info >= (3, 13): + __all__ += ["kde", "kde_random"] -_T = TypeVar("_T") # Most functions in this module accept homogeneous collections of one of these types -_Number = Union[float, Decimal, Fraction] +_Number: TypeAlias = float | Decimal | Fraction _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) # Used in mode, multimode _HashableT = TypeVar("_HashableT", bound=Hashable) -class StatisticsError(ValueError): ... +# Used in NormalDist.samples and kde_random +_Seed: TypeAlias = int | float | str | bytes | bytearray # noqa: Y041 -if sys.version_info >= (3, 8): - def fmean(data: Iterable[SupportsFloat]) -> float: ... - def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... +# Used in linear_regression +_T_co = TypeVar("_T_co", covariant=True) -def mean(data: Iterable[_NumberT]) -> _NumberT: ... +@type_check_only +class _SizedIterable(Iterable[_T_co], Sized, Protocol[_T_co]): ... -if sys.version_info >= (3, 10): - def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = ...) -> _NumberT: ... +class StatisticsError(ValueError): ... + +if sys.version_info >= (3, 11): + def fmean(data: Iterable[SupportsFloat], weights: Iterable[SupportsFloat] | None = None) -> float: ... else: - def harmonic_mean(data: Iterable[_NumberT]) -> _NumberT: ... + def fmean(data: Iterable[SupportsFloat]) -> float: ... +def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... +def mean(data: Iterable[_NumberT]) -> _NumberT: ... +def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = None) -> _NumberT: ... def median(data: Iterable[_NumberT]) -> _NumberT: ... def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... -def median_grouped(data: Iterable[_NumberT], interval: _NumberT = ...) -> _NumberT: ... + +if sys.version_info >= (3, 11): + def median_grouped(data: Iterable[SupportsFloat], interval: SupportsFloat = 1.0) -> float: ... + +else: + def median_grouped(data: Iterable[_NumberT], interval: _NumberT | float = 1) -> _NumberT | float: ... + def mode(data: Iterable[_HashableT]) -> _HashableT: ... +def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: ... +def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ... +def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ... +def quantiles( + data: Iterable[_NumberT], *, n: int = 4, method: Literal["inclusive", "exclusive"] = "exclusive" +) -> list[_NumberT]: ... +def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ... +def variance(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ... + +class NormalDist: + __slots__ = {"_mu": "Arithmetic mean of a normal distribution", "_sigma": "Standard deviation of a normal distribution"} + def __init__(self, mu: float = 0.0, sigma: float = 1.0) -> None: ... + @property + def mean(self) -> float: ... + @property + def median(self) -> float: ... + @property + def mode(self) -> float: ... + @property + def stdev(self) -> float: ... + @property + def variance(self) -> float: ... + @classmethod + def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: ... + def samples(self, n: SupportsIndex, *, seed: _Seed | None = None) -> list[float]: ... + def pdf(self, x: float) -> float: ... + def cdf(self, x: float) -> float: ... + def inv_cdf(self, p: float) -> float: ... + def overlap(self, other: NormalDist) -> float: ... + def quantiles(self, n: int = 4) -> list[float]: ... + def zscore(self, x: float) -> float: ... + def __eq__(x1, x2: object) -> bool: ... + def __add__(x1, x2: float | NormalDist) -> NormalDist: ... + def __sub__(x1, x2: float | NormalDist) -> NormalDist: ... + def __mul__(x1, x2: float) -> NormalDist: ... + def __truediv__(x1, x2: float) -> NormalDist: ... + def __pos__(x1) -> NormalDist: ... + def __neg__(x1) -> NormalDist: ... + __radd__ = __add__ + def __rsub__(x1, x2: float | NormalDist) -> NormalDist: ... + __rmul__ = __mul__ + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 12): + def correlation( + x: Sequence[_Number], y: Sequence[_Number], /, *, method: Literal["linear", "ranked"] = "linear" + ) -> float: ... + +else: + def correlation(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... + +def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... + +class LinearRegression(NamedTuple): + slope: float + intercept: float + +if sys.version_info >= (3, 11): + def linear_regression( + regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], /, *, proportional: bool = False + ) -> LinearRegression: ... + +else: + def linear_regression( + regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], / + ) -> LinearRegression: ... -if sys.version_info >= (3, 8): - def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: ... - -def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = ...) -> _NumberT: ... -def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = ...) -> _NumberT: ... - -if sys.version_info >= (3, 8): - def quantiles(data: Iterable[_NumberT], *, n: int = ..., method: str = ...) -> list[_NumberT]: ... - -def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = ...) -> _NumberT: ... -def variance(data: Iterable[_NumberT], xbar: _NumberT | None = ...) -> _NumberT: ... - -if sys.version_info >= (3, 8): - class NormalDist: - def __init__(self, mu: float = ..., sigma: float = ...) -> None: ... - @property - def mean(self) -> float: ... - @property - def median(self) -> float: ... - @property - def mode(self) -> float: ... - @property - def stdev(self) -> float: ... - @property - def variance(self) -> float: ... - @classmethod - def from_samples(cls: Type[_T], data: Iterable[SupportsFloat]) -> _T: ... - def samples(self, n: int, *, seed: Any | None = ...) -> list[float]: ... - def pdf(self, x: float) -> float: ... - def cdf(self, x: float) -> float: ... - def inv_cdf(self, p: float) -> float: ... - def overlap(self, other: NormalDist) -> float: ... - def quantiles(self, n: int = ...) -> list[float]: ... - if sys.version_info >= (3, 9): - def zscore(self, x: float) -> float: ... - def __add__(self, x2: float | NormalDist) -> NormalDist: ... - def __sub__(self, x2: float | NormalDist) -> NormalDist: ... - def __mul__(self, x2: float) -> NormalDist: ... - def __truediv__(self, x2: float) -> NormalDist: ... - def __pos__(self) -> NormalDist: ... - def __neg__(self) -> NormalDist: ... - __radd__ = __add__ - def __rsub__(self, x2: float | NormalDist) -> NormalDist: ... - __rmul__ = __mul__ - def __hash__(self) -> int: ... - -if sys.version_info >= (3, 10): - def correlation(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... - def covariance(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... - class LinearRegression(NamedTuple): - slope: float - intercept: float - def linear_regression(__regressor: Sequence[_Number], __dependent_variable: Sequence[_Number]) -> LinearRegression: ... +if sys.version_info >= (3, 13): + _Kernel: TypeAlias = Literal[ + "normal", + "gauss", + "logistic", + "sigmoid", + "rectangular", + "uniform", + "triangular", + "parabolic", + "epanechnikov", + "quartic", + "biweight", + "triweight", + "cosine", + ] + def kde( + data: Sequence[float], h: float, kernel: _Kernel = "normal", *, cumulative: bool = False + ) -> Callable[[float], float]: ... + def kde_random( + data: Sequence[float], h: float, kernel: _Kernel = "normal", *, seed: _Seed | None = None + ) -> Callable[[], float]: ... diff --git a/stdlib/string.pyi b/stdlib/string.pyi deleted file mode 100644 index 374d59959ac9..000000000000 --- a/stdlib/string.pyi +++ /dev/null @@ -1,42 +0,0 @@ -import sys -from re import RegexFlag -from typing import Any, Iterable, Mapping, Sequence - -if sys.version_info >= (3, 8): - from re import Pattern -else: - from typing import Pattern - -ascii_letters: str -ascii_lowercase: str -ascii_uppercase: str -digits: str -hexdigits: str -octdigits: str -punctuation: str -printable: str -whitespace: str - -def capwords(s: str, sep: str | None = ...) -> str: ... - -class Template: - template: str - delimiter: str - idpattern: str - braceidpattern: str | None - flags: RegexFlag - pattern: Pattern[str] - def __init__(self, template: str) -> None: ... - def substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... - def safe_substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... - -# TODO(MichalPokorny): This is probably badly and/or loosely typed. -class Formatter: - def format(self, __format_string: str, *args: Any, **kwargs: Any) -> str: ... - def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... - def parse(self, format_string: str) -> Iterable[tuple[str, str | None, str | None, str | None]]: ... - def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... - def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... - def check_unused_args(self, used_args: Sequence[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... - def format_field(self, value: Any, format_spec: str) -> Any: ... - def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/stdlib/string/__init__.pyi b/stdlib/string/__init__.pyi new file mode 100644 index 000000000000..df70cdc6b21c --- /dev/null +++ b/stdlib/string/__init__.pyi @@ -0,0 +1,81 @@ +import sys +from _typeshed import StrOrLiteralStr +from collections.abc import Iterable, Mapping, Sequence +from re import Pattern, RegexFlag +from typing import Any, ClassVar, Final, overload +from typing_extensions import LiteralString + +__all__ = [ + "ascii_letters", + "ascii_lowercase", + "ascii_uppercase", + "capwords", + "digits", + "hexdigits", + "octdigits", + "printable", + "punctuation", + "whitespace", + "Formatter", + "Template", +] + +whitespace: Final = " \t\n\r\v\f" +ascii_lowercase: Final = "abcdefghijklmnopqrstuvwxyz" +ascii_uppercase: Final = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +ascii_letters: Final[LiteralString] # string too long +digits: Final = "0123456789" +hexdigits: Final = "0123456789abcdefABCDEF" +octdigits: Final = "01234567" +punctuation: Final = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" +printable: Final[LiteralString] # string too long + +def capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLiteralStr: ... + +class Template: + template: str + delimiter: ClassVar[str] + idpattern: ClassVar[str] + braceidpattern: ClassVar[str | None] + if sys.version_info >= (3, 14): + flags: ClassVar[RegexFlag | None] + else: + flags: ClassVar[RegexFlag] + pattern: ClassVar[Pattern[str]] + def __init__(self, template: str) -> None: ... + def substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ... + def safe_substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ... + if sys.version_info >= (3, 11): + def get_identifiers(self) -> list[str]: ... + def is_valid(self) -> bool: ... + +class Formatter: + @overload + def format(self, format_string: LiteralString, /, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload + def format(self, format_string: str, /, *args: Any, **kwargs: Any) -> str: ... + + @overload + def vformat( + self, format_string: LiteralString, args: Sequence[LiteralString], kwargs: Mapping[LiteralString, LiteralString] + ) -> LiteralString: ... + @overload + def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... + + def _vformat( # undocumented + self, + format_string: str, + args: Sequence[Any], + kwargs: Mapping[str, Any], + used_args: set[int | str], + recursion_depth: int, + auto_arg_index: int = 0, + ) -> tuple[str, int]: ... + def parse( + self, format_string: StrOrLiteralStr + ) -> Iterable[tuple[StrOrLiteralStr, StrOrLiteralStr | None, StrOrLiteralStr | None, StrOrLiteralStr | None]]: ... + def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def check_unused_args(self, used_args: set[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str | None) -> Any: ... diff --git a/stdlib/string/templatelib.pyi b/stdlib/string/templatelib.pyi new file mode 100644 index 000000000000..ee901cdc43b8 --- /dev/null +++ b/stdlib/string/templatelib.pyi @@ -0,0 +1,36 @@ +from collections.abc import Iterator +from types import GenericAlias +from typing import Any, Generic, Literal, TypeVar, final, overload + +_T = TypeVar("_T") + +@final +class Template: # TODO: consider making `Template` generic on `TypeVarTuple` + strings: tuple[str, ...] + interpolations: tuple[Interpolation[Any], ...] + + def __new__(cls, *args: str | Interpolation[Any]) -> Template: ... + def __iter__(self) -> Iterator[str | Interpolation[Any]]: ... + def __add__(self, other: Template, /) -> Template: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + @property + def values(self) -> tuple[Any, ...]: ... # Tuple of interpolation values, which can have any type + +@final +class Interpolation(Generic[_T]): + value: _T + expression: str + conversion: Literal["a", "r", "s"] | None + format_spec: str + + __match_args__ = ("value", "expression", "conversion", "format_spec") + + def __new__( + cls, value: _T, expression: str = "", conversion: Literal["a", "r", "s"] | None = None, format_spec: str = "" + ) -> Interpolation[_T]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@overload +def convert(obj: _T, /, conversion: None) -> _T: ... +@overload +def convert(obj: object, /, conversion: Literal["r", "s", "a"]) -> str: ... diff --git a/stdlib/stringprep.pyi b/stdlib/stringprep.pyi index fc28c027ca9b..d67955e499c8 100644 --- a/stdlib/stringprep.pyi +++ b/stdlib/stringprep.pyi @@ -1,10 +1,12 @@ -b1_set: set[int] -b3_exceptions: dict[int, str] -c22_specials: set[int] -c6_set: set[int] -c7_set: set[int] -c8_set: set[int] -c9_set: set[int] +from typing import Final + +b1_set: Final[set[int]] +b3_exceptions: Final[dict[int, str]] +c22_specials: Final[set[int]] +c6_set: Final[set[int]] +c7_set: Final[set[int]] +c8_set: Final[set[int]] +c9_set: Final[set[int]] def in_table_a1(code: str) -> bool: ... def in_table_b1(code: str) -> bool: ... diff --git a/stdlib/struct.pyi b/stdlib/struct.pyi index d7c9cbef7dce..2c26908746ec 100644 --- a/stdlib/struct.pyi +++ b/stdlib/struct.pyi @@ -1,25 +1,5 @@ -import sys -from _typeshed import ReadableBuffer, WriteableBuffer -from typing import Any, Iterator, Tuple +from _struct import * -class error(Exception): ... - -def pack(fmt: str | bytes, *v: Any) -> bytes: ... -def pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... -def unpack(__format: str | bytes, __buffer: ReadableBuffer) -> Tuple[Any, ...]: ... -def unpack_from(__format: str | bytes, buffer: ReadableBuffer, offset: int = ...) -> Tuple[Any, ...]: ... -def iter_unpack(__format: str | bytes, __buffer: ReadableBuffer) -> Iterator[Tuple[Any, ...]]: ... -def calcsize(__format: str | bytes) -> int: ... +__all__ = ["calcsize", "pack", "pack_into", "unpack", "unpack_from", "iter_unpack", "Struct", "error"] -class Struct: - if sys.version_info >= (3, 7): - format: str - else: - format: bytes - size: int - def __init__(self, format: str | bytes) -> None: ... - def pack(self, *v: Any) -> bytes: ... - def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... - def unpack(self, __buffer: ReadableBuffer) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: ReadableBuffer, offset: int = ...) -> Tuple[Any, ...]: ... - def iter_unpack(self, __buffer: ReadableBuffer) -> Iterator[Tuple[Any, ...]]: ... +class error(Exception): ... diff --git a/stdlib/subprocess.pyi b/stdlib/subprocess.pyi index fce517745ee6..bac7d6978f68 100644 --- a/stdlib/subprocess.pyi +++ b/stdlib/subprocess.pyi @@ -1,11 +1,49 @@ import sys -from _typeshed import Self, StrOrBytesPath -from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, Type, TypeVar, Union, overload -from typing_extensions import Literal +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence +from types import GenericAlias, TracebackType +from typing import IO, Any, AnyStr, Final, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = [ + "Popen", + "PIPE", + "STDOUT", + "call", + "check_call", + "getstatusoutput", + "getoutput", + "check_output", + "run", + "CalledProcessError", + "DEVNULL", + "SubprocessError", + "TimeoutExpired", + "CompletedProcess", +] + +if sys.platform == "win32": + __all__ += [ + "CREATE_NEW_CONSOLE", + "CREATE_NEW_PROCESS_GROUP", + "STARTF_USESHOWWINDOW", + "STARTF_USESTDHANDLES", + "STARTUPINFO", + "STD_ERROR_HANDLE", + "STD_INPUT_HANDLE", + "STD_OUTPUT_HANDLE", + "SW_HIDE", + "ABOVE_NORMAL_PRIORITY_CLASS", + "BELOW_NORMAL_PRIORITY_CLASS", + "CREATE_BREAKAWAY_FROM_JOB", + "CREATE_DEFAULT_ERROR_MODE", + "CREATE_NO_WINDOW", + "DETACHED_PROCESS", + "HIGH_PRIORITY_CLASS", + "IDLE_PRIORITY_CLASS", + "NORMAL_PRIORITY_CLASS", + "REALTIME_PRIORITY_CLASS", + ] # We prefer to annotate inputs to methods (eg subprocess.check_call) with these # union types. @@ -21,21 +59,21 @@ if sys.version_info >= (3, 9): # reveal_type(x) # bytes, based on the overloads # except TimeoutError as e: # reveal_type(e.cmd) # Any, but morally is _CMD -_FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, str] -if sys.version_info >= (3, 8): - _CMD = Union[StrOrBytesPath, Sequence[StrOrBytesPath]] -else: - # Python 3.6 doesn't support _CMD being a single PathLike. - # See: https://bugs.python.org/issue31961 - _CMD = Union[_TXT, Sequence[StrOrBytesPath]] +_FILE: TypeAlias = int | IO[Any] | None +_InputString: TypeAlias = ReadableBuffer | str +_CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath] if sys.platform == "win32": - _ENV = Mapping[str, str] + _ENV: TypeAlias = Mapping[str, str] else: - _ENV = Union[Mapping[bytes, StrOrBytesPath], Mapping[str, StrOrBytesPath]] + _ENV: TypeAlias = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath] _T = TypeVar("_T") +# These two are private but documented +if sys.version_info >= (3, 11): + _USE_VFORK: Final[bool] +_USE_POSIX_SPAWN: Final[bool] + class CompletedProcess(Generic[_T]): # morally: _CMD args: Any @@ -44,665 +82,951 @@ class CompletedProcess(Generic[_T]): # and writing all the overloads would be horrific. stdout: _T stderr: _T - def __init__(self, args: _CMD, returncode: int, stdout: _T | None = ..., stderr: _T | None = ...) -> None: ... + def __init__(self, args: _CMD, returncode: int, stdout: _T | None = None, stderr: _T | None = None) -> None: ... def check_returncode(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -if sys.version_info >= (3, 7): - # Nearly the same args as for 3.6, except for capture_output and text - @overload +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + @overload # text is True def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - capture_output: bool = ..., - check: bool = ..., - encoding: str | None = ..., - errors: str | None = ..., - input: str | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, text: Literal[True], - timeout: float | None = ..., + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # encoding is str def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - capture_output: bool = ..., - check: bool = ..., + capture_output: bool = False, + check: bool = False, encoding: str, - errors: str | None = ..., - input: str | None = ..., - text: bool | None = ..., - timeout: float | None = ..., + errors: str | None = None, + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # errors is str def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - capture_output: bool = ..., - check: bool = ..., - encoding: str | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, errors: str, - input: str | None = ..., - text: bool | None = ..., - timeout: float | None = ..., + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines is True def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, *, universal_newlines: Literal[True], - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), # where the *real* keyword only args start - capture_output: bool = ..., - check: bool = ..., - encoding: str | None = ..., - errors: str | None = ..., - input: str | None = ..., - text: bool | None = ..., - timeout: float | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines and text are False, None, or missing def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - capture_output: bool = ..., - check: bool = ..., - encoding: None = ..., - errors: None = ..., - input: bytes | None = ..., - text: Literal[None, False] = ..., - timeout: float | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: None = None, + errors: None = None, + input: ReadableBuffer | None = None, + text: Literal[False] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> CompletedProcess[bytes]: ... - @overload + @overload # fallback def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - capture_output: bool = ..., - check: bool = ..., - encoding: str | None = ..., - errors: str | None = ..., - input: _TXT | None = ..., - text: bool | None = ..., - timeout: float | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: _InputString | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> CompletedProcess[Any]: ... - else: - # Nearly same args as Popen.__init__ except for timeout, input, and check - @overload + # 3.10 adds "pipesize" argument + @overload # text is True + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True], + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[str]: ... + @overload # encoding is str def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - check: bool = ..., + capture_output: bool = False, + check: bool = False, encoding: str, - errors: str | None = ..., - input: str | None = ..., - timeout: float | None = ..., + errors: str | None = None, + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # errors is str def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - check: bool = ..., - encoding: str | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, errors: str, - input: str | None = ..., - timeout: float | None = ..., + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines is True def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, *, universal_newlines: Literal[True], - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), # where the *real* keyword only args start - check: bool = ..., - encoding: str | None = ..., - errors: str | None = ..., - input: str | None = ..., - timeout: float | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines and text are False, None, or missing def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - check: bool = ..., - encoding: None = ..., - errors: None = ..., - input: bytes | None = ..., - timeout: float | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: None = None, + errors: None = None, + input: ReadableBuffer | None = None, + text: Literal[False] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> CompletedProcess[bytes]: ... - @overload + @overload # fallback def run( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - check: bool = ..., - encoding: str | None = ..., - errors: str | None = ..., - input: _TXT | None = ..., - timeout: float | None = ..., + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: _InputString | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> CompletedProcess[Any]: ... # Same args as Popen.__init__ -def call( - args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: float | None = ..., -) -> int: ... +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + def call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + encoding: str | None = None, + timeout: float | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> int: ... + +else: + # 3.10 adds "pipesize" argument + def call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + encoding: str | None = None, + timeout: float | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> int: ... # Same args as Popen.__init__ -def check_call( - args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - timeout: float | None = ..., -) -> int: ... +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + def check_call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + timeout: float | None = None, + *, + encoding: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> int: ... -if sys.version_info >= (3, 7): - # 3.7 added text - @overload +else: + # 3.10 adds "pipesize" argument + def check_call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + timeout: float | None = None, + *, + encoding: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> int: ... + +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + @overload # text is True def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., - errors: str | None = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, text: Literal[True], + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # encoding is str def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., + timeout: float | None = None, + input: _InputString | None = None, encoding: str, - errors: str | None = ..., - text: bool | None = ..., + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # errors is str def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, errors: str, - text: bool | None = ..., + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # universal_newlines is True def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, *, universal_newlines: Literal[True], - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), # where the real keyword only ones start - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - text: bool | None = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # universal_newlines and text are False, None, or missing def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: None = ..., - errors: None = ..., - text: Literal[None, False] = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, ) -> bytes: ... - @overload + @overload # fallback def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - text: bool | None = ..., - ) -> Any: ... # morally: -> _TXT - + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> Any: ... # morally: -> str | bytes else: - @overload + # 3.10 adds "pipesize" argument + @overload # text is True def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True], + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> str: ... + @overload # encoding is str + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, encoding: str, - errors: str | None = ..., + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # errors is str def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, errors: str, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # universal_newlines is True def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, *, universal_newlines: Literal[True], - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., - errors: str | None = ..., + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the real keyword only ones start + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # universal_newlines and text are False, None, or missing def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: None = ..., - errors: None = ..., + timeout: float | None = None, + input: _InputString | None = None, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, ) -> bytes: ... - @overload + @overload # fallback def check_output( args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - timeout: float | None = ..., - input: _TXT | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> Any: ... # morally: -> _TXT + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> Any: ... # morally: -> str | bytes -PIPE: int -STDOUT: int -DEVNULL: int +PIPE: Final[int] +STDOUT: Final[int] +DEVNULL: Final[int] class SubprocessError(Exception): ... class TimeoutExpired(SubprocessError): - def __init__(self, cmd: _CMD, timeout: float, output: _TXT | None = ..., stderr: _TXT | None = ...) -> None: ... + def __init__( + self, cmd: _CMD, timeout: float, output: str | bytes | None = None, stderr: str | bytes | None = None + ) -> None: ... # morally: _CMD cmd: Any timeout: float - # morally: _TXT | None + # morally: str | bytes | None output: Any - stdout: Any - stderr: Any + stdout: bytes | None + stderr: bytes | None class CalledProcessError(SubprocessError): returncode: int # morally: _CMD cmd: Any - # morally: _TXT | None + # morally: str | bytes | None output: Any - # morally: _TXT | None + # morally: str | bytes | None stdout: Any stderr: Any - def __init__(self, returncode: int, cmd: _CMD, output: _TXT | None = ..., stderr: _TXT | None = ...) -> None: ... + def __init__( + self, returncode: int, cmd: _CMD, output: str | bytes | None = None, stderr: str | bytes | None = None + ) -> None: ... class Popen(Generic[AnyStr]): args: _CMD @@ -710,355 +1034,451 @@ class Popen(Generic[AnyStr]): stdout: IO[AnyStr] | None stderr: IO[AnyStr] | None pid: int - returncode: int + returncode: int | MaybeNone universal_newlines: bool - # Technically it is wrong that Popen provides __new__ instead of __init__ - # but this shouldn't come up hopefully? - - if sys.version_info >= (3, 7): - # text is added in 3.7 - @overload - def __new__( - cls, + if sys.version_info >= (3, 11): + # process_group is added in 3.11 + @overload # encoding is str + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - text: bool | None = ..., + text: bool | None = None, encoding: str, - errors: str | None = ..., - ) -> Popen[str]: ... - @overload - def __new__( - cls, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # errors is str + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - text: bool | None = ..., - encoding: str | None = ..., + text: bool | None = None, + encoding: str | None = None, errors: str, - ) -> Popen[str]: ... - @overload - def __new__( - cls, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # universal_newlines is True + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, *, universal_newlines: Literal[True], - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), # where the *real* keyword only args start - text: bool | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> Popen[str]: ... - @overload - def __new__( - cls, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # text is True + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, text: Literal[True], - encoding: str | None = ..., - errors: str | None = ..., - ) -> Popen[str]: ... - @overload - def __new__( - cls, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # universal_newlines and text are False, None, or missing + def __init__( + self: Popen[bytes], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - text: Literal[None, False] = ..., - encoding: None = ..., - errors: None = ..., - ) -> Popen[bytes]: ... - @overload - def __new__( - cls, + text: Literal[False] | None = None, + encoding: None = None, + errors: None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # fallback + def __init__( + self: Popen[Any], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - text: bool | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> Popen[Any]: ... + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... else: - @overload - def __new__( - cls, + # pipesize is added in 3.10 + @overload # encoding is str + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, + text: bool | None = None, encoding: str, - errors: str | None = ..., - ) -> Popen[str]: ... - @overload - def __new__( - cls, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # errors is str + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - encoding: str | None = ..., + text: bool | None = None, + encoding: str | None = None, errors: str, - ) -> Popen[str]: ... - @overload - def __new__( - cls, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # universal_newlines is True + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, *, universal_newlines: Literal[True], - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), # where the *real* keyword only args start - encoding: str | None = ..., - errors: str | None = ..., - ) -> Popen[str]: ... - @overload - def __new__( - cls, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # text is True + def __init__( + self: Popen[str], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - encoding: None = ..., - errors: None = ..., - ) -> Popen[bytes]: ... - @overload - def __new__( - cls, + text: Literal[True], + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # universal_newlines and text are False, None, or missing + def __init__( + self: Popen[bytes], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: Literal[False] | None = None, + encoding: None = None, + errors: None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # fallback + def __init__( + self: Popen[Any], args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE | None = ..., - stdout: _FILE | None = ..., - stderr: _FILE | None = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any | None = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), *, - encoding: str | None = ..., - errors: str | None = ..., - ) -> Popen[Any]: ... + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + def poll(self) -> int | None: ... - if sys.version_info >= (3, 7): - def wait(self, timeout: float | None = ...) -> int: ... - else: - def wait(self, timeout: float | None = ..., endtime: float | None = ...) -> int: ... - # Return str/bytes - def communicate( - self, - input: AnyStr | None = ..., - timeout: float | None = ..., - # morally this should be optional - ) -> tuple[AnyStr, AnyStr]: ... + def wait(self, timeout: float | None = None) -> int: ... + # morally the members of the returned tuple should be optional + # TODO: this should allow ReadableBuffer for Popen[bytes], but adding + # overloads for that runs into a mypy bug (python/mypy#14070). + def communicate(self, input: AnyStr | None = None, timeout: float | None = None) -> tuple[AnyStr, AnyStr]: ... def send_signal(self, sig: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __del__(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # The result really is always a str. -def getstatusoutput(cmd: _TXT) -> tuple[int, str]: ... -def getoutput(cmd: _TXT) -> str: ... - -if sys.version_info >= (3, 8): - def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented +if sys.version_info >= (3, 11): + def getstatusoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> tuple[int, str]: ... + def getoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> str: ... else: - def list2cmdline(seq: Iterable[str]) -> str: ... # undocumented + def getstatusoutput(cmd: _CMD) -> tuple[int, str]: ... + def getoutput(cmd: _CMD) -> str: ... + +def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented if sys.platform == "win32": + if sys.version_info >= (3, 13): + from _winapi import STARTF_FORCEOFFFEEDBACK, STARTF_FORCEONFEEDBACK + + __all__ += ["STARTF_FORCEOFFFEEDBACK", "STARTF_FORCEONFEEDBACK"] + class STARTUPINFO: - if sys.version_info >= (3, 7): - def __init__( - self, - *, - dwFlags: int = ..., - hStdInput: Any | None = ..., - hStdOutput: Any | None = ..., - hStdError: Any | None = ..., - wShowWindow: int = ..., - lpAttributeList: Mapping[str, Any] | None = ..., - ) -> None: ... + def __init__( + self, + *, + dwFlags: int = 0, + hStdInput: Any | None = None, + hStdOutput: Any | None = None, + hStdError: Any | None = None, + wShowWindow: int = 0, + lpAttributeList: Mapping[str, Any] | None = None, + ) -> None: ... dwFlags: int hStdInput: Any | None hStdOutput: Any | None hStdError: Any | None wShowWindow: int - if sys.version_info >= (3, 7): - lpAttributeList: Mapping[str, Any] - STD_INPUT_HANDLE: Any - STD_OUTPUT_HANDLE: Any - STD_ERROR_HANDLE: Any - SW_HIDE: int - STARTF_USESTDHANDLES: int - STARTF_USESHOWWINDOW: int - CREATE_NEW_CONSOLE: int - CREATE_NEW_PROCESS_GROUP: int - if sys.version_info >= (3, 7): - ABOVE_NORMAL_PRIORITY_CLASS: int - BELOW_NORMAL_PRIORITY_CLASS: int - HIGH_PRIORITY_CLASS: int - IDLE_PRIORITY_CLASS: int - NORMAL_PRIORITY_CLASS: int - REALTIME_PRIORITY_CLASS: int - CREATE_NO_WINDOW: int - DETACHED_PROCESS: int - CREATE_DEFAULT_ERROR_MODE: int - CREATE_BREAKAWAY_FROM_JOB: int + lpAttributeList: Mapping[str, Any] + def copy(self) -> STARTUPINFO: ... + + from _winapi import ( + ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, + BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, + CREATE_BREAKAWAY_FROM_JOB as CREATE_BREAKAWAY_FROM_JOB, + CREATE_DEFAULT_ERROR_MODE as CREATE_DEFAULT_ERROR_MODE, + CREATE_NEW_CONSOLE as CREATE_NEW_CONSOLE, + CREATE_NEW_PROCESS_GROUP as CREATE_NEW_PROCESS_GROUP, + CREATE_NO_WINDOW as CREATE_NO_WINDOW, + DETACHED_PROCESS as DETACHED_PROCESS, + HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, + IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, + NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, + REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, + STARTF_USESHOWWINDOW as STARTF_USESHOWWINDOW, + STARTF_USESTDHANDLES as STARTF_USESTDHANDLES, + STD_ERROR_HANDLE as STD_ERROR_HANDLE, + STD_INPUT_HANDLE as STD_INPUT_HANDLE, + STD_OUTPUT_HANDLE as STD_OUTPUT_HANDLE, + SW_HIDE as SW_HIDE, + ) diff --git a/stdlib/sunau.pyi b/stdlib/sunau.pyi index 8393136aa795..e4b9fcb6b8ca 100644 --- a/stdlib/sunau.pyi +++ b/stdlib/sunau.pyi @@ -1,25 +1,25 @@ -import sys -from _typeshed import Self -from typing import IO, Any, NamedTuple, NoReturn, Union +from _typeshed import Unused +from typing import IO, Any, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Never, Self -_File = Union[str, IO[bytes]] +_File: TypeAlias = str | IO[bytes] class Error(Exception): ... -AUDIO_FILE_MAGIC: int -AUDIO_FILE_ENCODING_MULAW_8: int -AUDIO_FILE_ENCODING_LINEAR_8: int -AUDIO_FILE_ENCODING_LINEAR_16: int -AUDIO_FILE_ENCODING_LINEAR_24: int -AUDIO_FILE_ENCODING_LINEAR_32: int -AUDIO_FILE_ENCODING_FLOAT: int -AUDIO_FILE_ENCODING_DOUBLE: int -AUDIO_FILE_ENCODING_ADPCM_G721: int -AUDIO_FILE_ENCODING_ADPCM_G722: int -AUDIO_FILE_ENCODING_ADPCM_G723_3: int -AUDIO_FILE_ENCODING_ADPCM_G723_5: int -AUDIO_FILE_ENCODING_ALAW_8: int -AUDIO_UNKNOWN_SIZE: int +AUDIO_FILE_MAGIC: Final = 0x2E736E64 +AUDIO_FILE_ENCODING_MULAW_8: Final = 1 +AUDIO_FILE_ENCODING_LINEAR_8: Final = 2 +AUDIO_FILE_ENCODING_LINEAR_16: Final = 3 +AUDIO_FILE_ENCODING_LINEAR_24: Final = 4 +AUDIO_FILE_ENCODING_LINEAR_32: Final = 5 +AUDIO_FILE_ENCODING_FLOAT: Final = 6 +AUDIO_FILE_ENCODING_DOUBLE: Final = 7 +AUDIO_FILE_ENCODING_ADPCM_G721: Final = 23 +AUDIO_FILE_ENCODING_ADPCM_G722: Final = 24 +AUDIO_FILE_ENCODING_ADPCM_G723_3: Final = 25 +AUDIO_FILE_ENCODING_ADPCM_G723_5: Final = 26 +AUDIO_FILE_ENCODING_ALAW_8: Final = 27 +AUDIO_UNKNOWN_SIZE: Final = 0xFFFFFFFF class _sunau_params(NamedTuple): nchannels: int @@ -31,8 +31,9 @@ class _sunau_params(NamedTuple): class Au_read: def __init__(self, f: _File) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... def getfp(self) -> IO[bytes] | None: ... def rewind(self) -> None: ... def close(self) -> None: ... @@ -45,14 +46,15 @@ class Au_read: def getcompname(self) -> str: ... def getparams(self) -> _sunau_params: ... def getmarkers(self) -> None: ... - def getmark(self, id: Any) -> NoReturn: ... + def getmark(self, id: Any) -> Never: ... def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes | None: ... class Au_write: def __init__(self, f: _File) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... def setsampwidth(self, sampwidth: int) -> None: ... @@ -72,8 +74,9 @@ class Au_write: def writeframes(self, data: bytes) -> None: ... def close(self) -> None: ... -# Returns a Au_read if mode is rb and Au_write if mode is wb -def open(f: _File, mode: str | None = ...) -> Any: ... - -if sys.version_info < (3, 9): - openfp = open +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Au_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Au_write: ... +@overload +def open(f: _File, mode: str | None = None) -> Any: ... diff --git a/stdlib/symbol.pyi b/stdlib/symbol.pyi deleted file mode 100644 index 234c814b55b5..000000000000 --- a/stdlib/symbol.pyi +++ /dev/null @@ -1,98 +0,0 @@ -import sys - -single_input: int -file_input: int -eval_input: int -decorator: int -decorators: int -decorated: int -async_funcdef: int -funcdef: int -parameters: int -typedargslist: int -tfpdef: int -varargslist: int -vfpdef: int -stmt: int -simple_stmt: int -small_stmt: int -expr_stmt: int -annassign: int -testlist_star_expr: int -augassign: int -del_stmt: int -pass_stmt: int -flow_stmt: int -break_stmt: int -continue_stmt: int -return_stmt: int -yield_stmt: int -raise_stmt: int -import_stmt: int -import_name: int -import_from: int -import_as_name: int -dotted_as_name: int -import_as_names: int -dotted_as_names: int -dotted_name: int -global_stmt: int -nonlocal_stmt: int -assert_stmt: int -compound_stmt: int -async_stmt: int -if_stmt: int -while_stmt: int -for_stmt: int -try_stmt: int -with_stmt: int -with_item: int -except_clause: int -suite: int -test: int -test_nocond: int -lambdef: int -lambdef_nocond: int -or_test: int -and_test: int -not_test: int -comparison: int -comp_op: int -star_expr: int -expr: int -xor_expr: int -and_expr: int -shift_expr: int -arith_expr: int -term: int -factor: int -power: int -atom_expr: int -atom: int -testlist_comp: int -trailer: int -subscriptlist: int -subscript: int -sliceop: int -exprlist: int -testlist: int -dictorsetmaker: int -classdef: int -arglist: int -argument: int -comp_iter: int -comp_for: int -comp_if: int -encoding_decl: int -yield_expr: int -yield_arg: int -if sys.version_info >= (3, 7): - sync_comp_for: int -if sys.version_info >= (3, 8): - func_body_suite: int - func_type: int - func_type_input: int - namedexpr_test: int - typelist: int - -sym_name: dict[int, str] diff --git a/stdlib/symtable.pyi b/stdlib/symtable.pyi index 2f8961faa5f6..3c6a828fad2a 100644 --- a/stdlib/symtable.pyi +++ b/stdlib/symtable.pyi @@ -1,57 +1,95 @@ import sys -from typing import Any, Sequence, Tuple +from _collections_abc import dict_keys +from collections.abc import Sequence +from typing import Any +from typing_extensions import deprecated -def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... +__all__ = ["symtable", "SymbolTable", "Class", "Function", "Symbol"] -class SymbolTable(object): +if sys.version_info >= (3, 13): + __all__ += ["SymbolTableType"] + +if sys.version_info >= (3, 15): + def symtable(code: str, filename: str, compile_type: str, *, module: str | None = None) -> SymbolTable: ... + +else: + def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... + +if sys.version_info >= (3, 13): + from enum import StrEnum + + class SymbolTableType(StrEnum): + MODULE = "module" + FUNCTION = "function" + CLASS = "class" + ANNOTATION = "annotation" + TYPE_ALIAS = "type alias" + TYPE_PARAMETERS = "type parameters" + TYPE_VARIABLE = "type variable" + +class SymbolTable: def __init__(self, raw_table: Any, filename: str) -> None: ... - def get_type(self) -> str: ... + if sys.version_info >= (3, 13): + def get_type(self) -> SymbolTableType: ... + else: + def get_type(self) -> str: ... + def get_id(self) -> int: ... def get_name(self) -> str: ... def get_lineno(self) -> int: ... def is_optimized(self) -> bool: ... def is_nested(self) -> bool: ... def has_children(self) -> bool: ... - def has_exec(self) -> bool: ... - def get_identifiers(self) -> Sequence[str]: ... + def get_identifiers(self) -> dict_keys[str, int]: ... def lookup(self, name: str) -> Symbol: ... def get_symbols(self) -> list[Symbol]: ... def get_children(self) -> list[SymbolTable]: ... class Function(SymbolTable): - def get_parameters(self) -> Tuple[str, ...]: ... - def get_locals(self) -> Tuple[str, ...]: ... - def get_globals(self) -> Tuple[str, ...]: ... - def get_frees(self) -> Tuple[str, ...]: ... - if sys.version_info >= (3, 8): - def get_nonlocals(self) -> Tuple[str, ...]: ... + def get_parameters(self) -> tuple[str, ...]: ... + def get_locals(self) -> tuple[str, ...]: ... + def get_globals(self) -> tuple[str, ...]: ... + def get_frees(self) -> tuple[str, ...]: ... + if sys.version_info >= (3, 15): + def get_cells(self) -> tuple[str, ...]: ... + + def get_nonlocals(self) -> tuple[str, ...]: ... class Class(SymbolTable): - def get_methods(self) -> Tuple[str, ...]: ... - -class Symbol(object): - if sys.version_info >= (3, 8): - def __init__( - self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ..., *, module_scope: bool = ... - ) -> None: ... - def is_nonlocal(self) -> bool: ... - else: - def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ...) -> None: ... + @deprecated("Deprecated; will be removed in Python 3.16.") + def get_methods(self) -> tuple[str, ...]: ... + +class Symbol: + def __init__( + self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None, *, module_scope: bool = False + ) -> None: ... + def is_nonlocal(self) -> bool: ... def get_name(self) -> str: ... def is_referenced(self) -> bool: ... def is_parameter(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_type_parameter(self) -> bool: ... + def is_global(self) -> bool: ... def is_declared_global(self) -> bool: ... def is_local(self) -> bool: ... def is_annotated(self) -> bool: ... def is_free(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_free_class(self) -> bool: ... + def is_imported(self) -> bool: ... def is_assigned(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_comp_iter(self) -> bool: ... + def is_comp_cell(self) -> bool: ... + if sys.version_info >= (3, 15): + def is_cell(self) -> bool: ... + def is_namespace(self) -> bool: ... def get_namespaces(self) -> Sequence[SymbolTable]: ... def get_namespace(self) -> SymbolTable: ... -class SymbolTableFactory(object): - def __init__(self) -> None: ... +class SymbolTableFactory: def new(self, table: Any, filename: str) -> SymbolTable: ... def __call__(self, table: Any, filename: str) -> SymbolTable: ... diff --git a/stdlib/sys.pyi b/stdlib/sys.pyi deleted file mode 100644 index b5829884482a..000000000000 --- a/stdlib/sys.pyi +++ /dev/null @@ -1,251 +0,0 @@ -import sys -from builtins import object as _object -from importlib.abc import PathEntryFinder -from importlib.machinery import ModuleSpec -from io import TextIOWrapper -from types import FrameType, ModuleType, TracebackType -from typing import ( - Any, - AsyncGenerator, - Callable, - NoReturn, - Optional, - Protocol, - Sequence, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal - -_T = TypeVar("_T") - -# The following type alias are stub-only and do not exist during runtime -_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] - -# Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` -class _MetaPathFinder(Protocol): - def find_spec(self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = ...) -> ModuleSpec | None: ... - -# ----- sys variables ----- -if sys.platform != "win32": - abiflags: str -argv: list[str] -base_exec_prefix: str -base_prefix: str -byteorder: Literal["little", "big"] -builtin_module_names: Sequence[str] # actually a tuple of strings -copyright: str -if sys.platform == "win32": - dllhandle: int -dont_write_bytecode: bool -displayhook: Callable[[object], Any] -excepthook: Callable[[Type[BaseException], BaseException, TracebackType | None], Any] -exec_prefix: str -executable: str -float_repr_style: str -hexversion: int -last_type: Type[BaseException] | None -last_value: BaseException | None -last_traceback: TracebackType | None -maxsize: int -maxunicode: int -meta_path: list[_MetaPathFinder] -modules: dict[str, ModuleType] -if sys.version_info >= (3, 10): - orig_argv: list[str] -path: list[str] -path_hooks: list[Any] # TODO precise type; function, path to finder -path_importer_cache: dict[str, PathEntryFinder | None] -platform: str -if sys.version_info >= (3, 9): - platlibdir: str -prefix: str -if sys.version_info >= (3, 8): - pycache_prefix: str | None -ps1: object -ps2: object -stdin: TextIO -stdout: TextIO -stderr: TextIO -if sys.version_info >= (3, 10): - stdlib_module_names: frozenset[str] -__stdin__: TextIOWrapper -__stdout__: TextIOWrapper -__stderr__: TextIOWrapper -tracebacklimit: int -version: str -api_version: int -warnoptions: Any -# Each entry is a tuple of the form (action, message, category, module, -# lineno) -if sys.platform == "win32": - winver: str -_xoptions: dict[Any, Any] - -flags: _flags - -class _flags: - debug: int - division_warning: int - inspect: int - interactive: int - optimize: int - dont_write_bytecode: int - no_user_site: int - no_site: int - ignore_environment: int - verbose: int - bytes_warning: int - quiet: int - hash_randomization: int - if sys.version_info >= (3, 7): - dev_mode: int - utf8_mode: int - -float_info: _float_info - -class _float_info: - epsilon: float # DBL_EPSILON - dig: int # DBL_DIG - mant_dig: int # DBL_MANT_DIG - max: float # DBL_MAX - max_exp: int # DBL_MAX_EXP - max_10_exp: int # DBL_MAX_10_EXP - min: float # DBL_MIN - min_exp: int # DBL_MIN_EXP - min_10_exp: int # DBL_MIN_10_EXP - radix: int # FLT_RADIX - rounds: int # FLT_ROUNDS - -hash_info: _hash_info - -class _hash_info: - width: int - modulus: int - inf: int - nan: int - imag: int - -implementation: _implementation - -class _implementation: - name: str - version: _version_info - hexversion: int - cache_tag: str - _multiarch: str - -int_info: _int_info - -class _int_info: - bits_per_digit: int - sizeof_digit: int - -class _version_info(Tuple[int, int, int, str, int]): - major: int - minor: int - micro: int - releaselevel: str - serial: int - -version_info: _version_info - -def call_tracing(__func: Callable[..., _T], __args: Any) -> _T: ... -def _clear_type_cache() -> None: ... -def _current_frames() -> dict[int, FrameType]: ... -def _getframe(__depth: int = ...) -> FrameType: ... -def _debugmallocstats() -> None: ... -def __displayhook__(value: object) -> None: ... -def __excepthook__(type_: Type[BaseException], value: BaseException, traceback: TracebackType | None) -> None: ... -def exc_info() -> _OptExcInfo: ... - -# sys.exit() accepts an optional argument of anything printable -def exit(__status: object = ...) -> NoReturn: ... -def getallocatedblocks() -> int: ... -def getdefaultencoding() -> str: ... - -if sys.platform != "win32": - def getdlopenflags() -> int: ... - -def getfilesystemencoding() -> str: ... -def getfilesystemencodeerrors() -> str: ... -def getrefcount(__object: Any) -> int: ... -def getrecursionlimit() -> int: ... -@overload -def getsizeof(obj: object) -> int: ... -@overload -def getsizeof(obj: object, default: int) -> int: ... -def getswitchinterval() -> float: ... - -_ProfileFunc = Callable[[FrameType, str, Any], Any] - -def getprofile() -> _ProfileFunc | None: ... -def setprofile(profilefunc: _ProfileFunc | None) -> None: ... - -_TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, Any], Any]]] - -def gettrace() -> _TraceFunc | None: ... -def settrace(tracefunc: _TraceFunc | None) -> None: ... - -class _WinVersion(Tuple[int, int, int, int, str, int, int, int, int, Tuple[int, int, int]]): - major: int - minor: int - build: int - platform: int - service_pack: str - service_pack_minor: int - service_pack_major: int - suite_mast: int - product_type: int - platform_version: tuple[int, int, int] - -if sys.platform == "win32": - def getwindowsversion() -> _WinVersion: ... - -def intern(__string: str) -> str: ... -def is_finalizing() -> bool: ... - -if sys.version_info >= (3, 7): - __breakpointhook__: Any # contains the original value of breakpointhook - def breakpointhook(*args: Any, **kwargs: Any) -> Any: ... - -if sys.platform != "win32": - def setdlopenflags(__flags: int) -> None: ... - -def setrecursionlimit(__limit: int) -> None: ... -def setswitchinterval(__interval: float) -> None: ... -def gettotalrefcount() -> int: ... # Debug builds only - -if sys.version_info < (3, 9): - def getcheckinterval() -> int: ... # deprecated - def setcheckinterval(__n: int) -> None: ... # deprecated - -if sys.version_info >= (3, 8): - # not exported by sys - class UnraisableHookArgs: - exc_type: Type[BaseException] - exc_value: BaseException | None - exc_traceback: TracebackType | None - err_msg: str | None - object: _object | None - unraisablehook: Callable[[UnraisableHookArgs], Any] - def addaudithook(hook: Callable[[str, Tuple[Any, ...]], Any]) -> None: ... - def audit(__event: str, *args: Any) -> None: ... - -_AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] - -class _asyncgen_hooks(Tuple[_AsyncgenHook, _AsyncgenHook]): - firstiter: _AsyncgenHook - finalizer: _AsyncgenHook - -def get_asyncgen_hooks() -> _asyncgen_hooks: ... -def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... - -if sys.version_info >= (3, 7): - def get_coroutine_origin_tracking_depth() -> int: ... - def set_coroutine_origin_tracking_depth(depth: int) -> None: ... diff --git a/stdlib/sys/__init__.pyi b/stdlib/sys/__init__.pyi new file mode 100644 index 000000000000..847895fb65b1 --- /dev/null +++ b/stdlib/sys/__init__.pyi @@ -0,0 +1,538 @@ +import sys +from _typeshed import MaybeNone, OptExcInfo, ProfileFunction, StrOrBytesPath, TraceFunction, structseq +from _typeshed.importlib import MetaPathFinderProtocol, PathEntryFinderProtocol +from builtins import object as _object +from collections.abc import AsyncGenerator, Callable, Sequence +from io import TextIOWrapper +from types import FrameType, ModuleType, SimpleNamespace, TracebackType +from typing import Any, Final, Literal, Protocol, TextIO, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import LiteralString, Never, deprecated + +_T = TypeVar("_T") +_LazyImportMode: TypeAlias = Literal["normal", "all", "none"] +_LazyImportFilter: TypeAlias = Callable[[str | None, str, tuple[str, ...] | None], bool] + +# see https://github.com/python/typeshed/issues/8513#issue-1333671093 for the rationale behind this alias +_ExitCode: TypeAlias = str | int | None + +if sys.version_info >= (3, 15): + @type_check_only + class _AbiInfo(SimpleNamespace): + pointer_bits: int + free_threaded: bool + debug: bool + byteorder: Literal["little", "big"] + +# ----- sys variables ----- +if sys.platform != "win32": + abiflags: str +if sys.version_info >= (3, 15): + abi_info: _AbiInfo +argv: list[str] +base_exec_prefix: str +base_prefix: str +byteorder: Literal["little", "big"] +builtin_module_names: Sequence[str] # actually a tuple of strings +copyright: str +if sys.platform == "win32": + dllhandle: int +dont_write_bytecode: bool +displayhook: Callable[[object], Any] +excepthook: Callable[[type[BaseException], BaseException, TracebackType | None], Any] +exec_prefix: str +executable: str +float_repr_style: Literal["short", "legacy"] +_framework: str # empty string on non-macOS platforms +hexversion: int +last_type: type[BaseException] | None +last_value: BaseException | None +last_traceback: TracebackType | None +if sys.version_info >= (3, 12): + last_exc: BaseException # or undefined. +maxsize: int +maxunicode: int +meta_path: list[MetaPathFinderProtocol] +modules: dict[str, ModuleType] +if sys.version_info >= (3, 15): + lazy_modules: set[str] +orig_argv: list[str] +path: list[str] +path_hooks: list[Callable[[str], PathEntryFinderProtocol]] +path_importer_cache: dict[str, PathEntryFinderProtocol | None] +platform: LiteralString +platlibdir: str +prefix: str +pycache_prefix: str | None +ps1: object +ps2: object + +# TextIO is used instead of more specific types for the standard streams, +# since they are often monkeypatched at runtime. At startup, the objects +# are initialized to instances of TextIOWrapper, but can also be None under +# some circumstances. +# +# To use methods from TextIOWrapper, use an isinstance check to ensure that +# the streams have not been overridden: +# +# if isinstance(sys.stdout, io.TextIOWrapper): +# sys.stdout.reconfigure(...) +stdin: TextIO | MaybeNone +stdout: TextIO | MaybeNone +stderr: TextIO | MaybeNone +stdlib_module_names: frozenset[str] + +__stdin__: Final[TextIOWrapper | None] # Contains the original value of stdin +__stdout__: Final[TextIOWrapper | None] # Contains the original value of stdout +__stderr__: Final[TextIOWrapper | None] # Contains the original value of stderr +tracebacklimit: int | None +version: str +api_version: int +warnoptions: Any +# Each entry is a tuple of the form (action, message, category, module, +# lineno) +if sys.platform == "win32": + winver: str +_xoptions: dict[Any, Any] + +# Type alias used as a mixin for structseq classes that cannot be instantiated at runtime +# This can't be represented in the type system, so we just use `structseq[Any]` +_UninstantiableStructseq: TypeAlias = structseq[Any] + +flags: _flags + +# This class is not exposed at runtime. It calls itself sys.flags. +# As a tuple, it can have a length between 15 and 18. We don't model +# the exact length here because that varies by patch version due to +# the backported security fix int_max_str_digits. The exact length shouldn't +# be relied upon. See #13031 +# This can be re-visited when typeshed drops support for 3.10, +# at which point all supported versions will include int_max_str_digits +# in all patch versions. +# 3.9 is 15 or 16-tuple +# 3.10 is 16 or 17-tuple +# 3.11+ is an 18-tuple. +@final +@type_check_only +class _flags(_UninstantiableStructseq, tuple[int, ...]): + # `safe_path` was added in py311 + if sys.version_info >= (3, 11): + __match_args__: Final = ( + "debug", + "inspect", + "interactive", + "optimize", + "dont_write_bytecode", + "no_user_site", + "no_site", + "ignore_environment", + "verbose", + "bytes_warning", + "quiet", + "hash_randomization", + "isolated", + "dev_mode", + "utf8_mode", + "warn_default_encoding", + "safe_path", + "int_max_str_digits", + ) + else: + __match_args__: Final = ( + "debug", + "inspect", + "interactive", + "optimize", + "dont_write_bytecode", + "no_user_site", + "no_site", + "ignore_environment", + "verbose", + "bytes_warning", + "quiet", + "hash_randomization", + "isolated", + "dev_mode", + "utf8_mode", + "warn_default_encoding", + "int_max_str_digits", + ) + + @property + def debug(self) -> int: ... + @property + def inspect(self) -> int: ... + @property + def interactive(self) -> int: ... + @property + def optimize(self) -> int: ... + @property + def dont_write_bytecode(self) -> int: ... + @property + def no_user_site(self) -> int: ... + @property + def no_site(self) -> int: ... + @property + def ignore_environment(self) -> int: ... + @property + def verbose(self) -> int: ... + @property + def bytes_warning(self) -> int: ... + @property + def quiet(self) -> int: ... + @property + def hash_randomization(self) -> int: ... + @property + def isolated(self) -> int: ... + @property + def dev_mode(self) -> bool: ... + @property + def utf8_mode(self) -> int: ... + @property + def warn_default_encoding(self) -> int: ... + if sys.version_info >= (3, 11): + @property + def safe_path(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def gil(self) -> Literal[0, 1]: ... + if sys.version_info >= (3, 14): + @property + def thread_inherit_context(self) -> Literal[0, 1]: ... + @property + def context_aware_warnings(self) -> Literal[0, 1]: ... + # Whether or not this exists on lower versions of Python + # may depend on which patch release you're using + # (it was backported to all Python versions on 3.8+ as a security fix) + # Added in: 3.9.14, 3.10.7 + # and present in all versions of 3.11 and later. + @property + def int_max_str_digits(self) -> int: ... + +float_info: _float_info + +# This class is not exposed at runtime. It calls itself sys.float_info. +@final +@type_check_only +class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]): + __match_args__: Final = ( + "max", + "max_exp", + "max_10_exp", + "min", + "min_exp", + "min_10_exp", + "dig", + "mant_dig", + "epsilon", + "radix", + "rounds", + ) + + @property + def max(self) -> float: ... # DBL_MAX + @property + def max_exp(self) -> int: ... # DBL_MAX_EXP + @property + def max_10_exp(self) -> int: ... # DBL_MAX_10_EXP + @property + def min(self) -> float: ... # DBL_MIN + @property + def min_exp(self) -> int: ... # DBL_MIN_EXP + @property + def min_10_exp(self) -> int: ... # DBL_MIN_10_EXP + @property + def dig(self) -> int: ... # DBL_DIG + @property + def mant_dig(self) -> int: ... # DBL_MANT_DIG + @property + def epsilon(self) -> float: ... # DBL_EPSILON + @property + def radix(self) -> int: ... # FLT_RADIX + @property + def rounds(self) -> int: ... # FLT_ROUNDS + +hash_info: _hash_info + +# This class is not exposed at runtime. It calls itself sys.hash_info. +@final +@type_check_only +class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]): + __match_args__: Final = ("width", "modulus", "inf", "nan", "imag", "algorithm", "hash_bits", "seed_bits", "cutoff") + + @property + def width(self) -> int: ... + @property + def modulus(self) -> int: ... + @property + def inf(self) -> int: ... + @property + def nan(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def algorithm(self) -> str: ... + @property + def hash_bits(self) -> int: ... + @property + def seed_bits(self) -> int: ... + @property + def cutoff(self) -> int: ... # undocumented + +implementation: _implementation + +# This class isn't really a thing. At runtime, implementation is an instance +# of types.SimpleNamespace. This allows for better typing. +@type_check_only +class _implementation: + name: str + version: _version_info + hexversion: int + cache_tag: str + # Define __getattr__, as the documentation states: + # > sys.implementation may contain additional attributes specific to the Python implementation. + # > These non-standard attributes must start with an underscore, and are not described here. + def __getattr__(self, name: str) -> Any: ... + +int_info: _int_info + +# This class is not exposed at runtime. It calls itself sys.int_info. +@final +@type_check_only +class _int_info(structseq[int], tuple[int, int, int, int]): + __match_args__: Final = ("bits_per_digit", "sizeof_digit", "default_max_str_digits", "str_digits_check_threshold") + + @property + def bits_per_digit(self) -> int: ... + @property + def sizeof_digit(self) -> int: ... + @property + def default_max_str_digits(self) -> int: ... + @property + def str_digits_check_threshold(self) -> int: ... + +_ThreadInfoName: TypeAlias = Literal["nt", "pthread", "pthread-stubs", "solaris"] +_ThreadInfoLock: TypeAlias = Literal["semaphore", "mutex+cond"] | None + +# This class is not exposed at runtime. It calls itself sys.thread_info. +@final +@type_check_only +class _thread_info(_UninstantiableStructseq, tuple[_ThreadInfoName, _ThreadInfoLock, str | None]): + __match_args__: Final = ("name", "lock", "version") + + @property + def name(self) -> _ThreadInfoName: ... + @property + def lock(self) -> _ThreadInfoLock: ... + @property + def version(self) -> str | None: ... + +thread_info: _thread_info +_ReleaseLevel: TypeAlias = Literal["alpha", "beta", "candidate", "final"] + +# This class is not exposed at runtime. It calls itself sys.version_info. +@final +@type_check_only +class _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel, int]): + __match_args__: Final = ("major", "minor", "micro", "releaselevel", "serial") + + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... + @property + def releaselevel(self) -> _ReleaseLevel: ... + @property + def serial(self) -> int: ... + +version_info: _version_info + +def call_tracing(func: Callable[..., _T], args: Any, /) -> _T: ... + +if sys.version_info >= (3, 13): + @deprecated("Deprecated since Python 3.13. Use `_clear_internal_caches()` instead.") + def _clear_type_cache() -> None: ... + +else: + def _clear_type_cache() -> None: ... + +def _current_frames() -> dict[int, FrameType]: ... +def _getframe(depth: int = 0, /) -> FrameType: ... + +# documented -- see https://docs.python.org/3/library/sys.html#sys._current_exceptions +if sys.version_info >= (3, 12): + def _current_exceptions() -> dict[int, BaseException | None]: ... + +else: + def _current_exceptions() -> dict[int, OptExcInfo]: ... + +if sys.version_info >= (3, 12): + def _getframemodulename(depth: int = 0) -> str | None: ... + +def _debugmallocstats() -> None: ... +def __displayhook__(object: object, /) -> None: ... +def __excepthook__(exctype: type[BaseException], value: BaseException, traceback: TracebackType | None, /) -> None: ... +def exc_info() -> OptExcInfo: ... + +if sys.version_info >= (3, 11): + def exception() -> BaseException | None: ... + +def exit(status: _ExitCode = None, /) -> Never: ... + +if sys.platform == "android": # noqa: Y008 + def getandroidapilevel() -> int: ... + +def getallocatedblocks() -> int: ... +def getdefaultencoding() -> Literal["utf-8"]: ... + +if sys.platform != "win32": + def getdlopenflags() -> int: ... + +def getfilesystemencoding() -> LiteralString: ... +def getfilesystemencodeerrors() -> LiteralString: ... + +if sys.version_info >= (3, 15): + def get_lazy_imports() -> _LazyImportMode: ... + def get_lazy_imports_filter() -> _LazyImportFilter | None: ... + +def getrefcount(object: Any, /) -> int: ... +def getrecursionlimit() -> int: ... +def getsizeof(obj: object, default: int = ...) -> int: ... +def getswitchinterval() -> float: ... +def getprofile() -> ProfileFunction | None: ... +def setprofile(function: ProfileFunction | None, /) -> None: ... +def gettrace() -> TraceFunction | None: ... +def settrace(function: TraceFunction | None, /) -> None: ... + +if sys.platform == "win32": + # A tuple of length 5, even though it has more than 5 attributes. + @final + @type_check_only + class _WinVersion(_UninstantiableStructseq, tuple[int, int, int, int, str]): + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def build(self) -> int: ... + @property + def platform(self) -> int: ... + @property + def service_pack(self) -> str: ... + @property + def service_pack_minor(self) -> int: ... + @property + def service_pack_major(self) -> int: ... + @property + def suite_mask(self) -> int: ... + @property + def product_type(self) -> int: ... + @property + def platform_version(self) -> tuple[int, int, int]: ... + + def getwindowsversion() -> _WinVersion: ... + +@overload +def intern(string: LiteralString, /) -> LiteralString: ... +@overload +def intern(string: str, /) -> str: ... # type: ignore[misc] + +__interactivehook__: Callable[[], object] + +if sys.version_info >= (3, 13): + def _is_gil_enabled() -> bool: ... + def _clear_internal_caches() -> None: ... + def _is_interned(string: str, /) -> bool: ... + +def is_finalizing() -> bool: ... +def breakpointhook(*args: Any, **kwargs: Any) -> Any: ... + +__breakpointhook__ = breakpointhook # Contains the original value of breakpointhook + +if sys.platform != "win32": + def setdlopenflags(flags: int, /) -> None: ... + +def setrecursionlimit(limit: int, /) -> None: ... +def setswitchinterval(interval: float, /) -> None: ... +def gettotalrefcount() -> int: ... # Debug builds only + +# Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. +@type_check_only +class UnraisableHookArgs(Protocol): + exc_type: type[BaseException] + exc_value: BaseException | None + exc_traceback: TracebackType | None + err_msg: str | None + object: _object + +unraisablehook: Callable[[UnraisableHookArgs], Any] + +def __unraisablehook__(unraisable: UnraisableHookArgs, /) -> Any: ... +def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... +def audit(event: str, /, *args: Any) -> None: ... + +_AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None + +# This class is not exposed at runtime. It calls itself builtins.asyncgen_hooks. +@final +@type_check_only +class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): + __match_args__: Final = ("firstiter", "finalizer") + + @property + def firstiter(self) -> _AsyncgenHook: ... + @property + def finalizer(self) -> _AsyncgenHook: ... + +def get_asyncgen_hooks() -> _asyncgen_hooks: ... +def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... + +if sys.platform == "win32": + if sys.version_info >= (3, 13): + @deprecated( + "Deprecated since Python 3.13; will be removed in Python 3.16. " + "Use the `PYTHONLEGACYWINDOWSFSENCODING` environment variable instead." + ) + def _enablelegacywindowsfsencoding() -> None: ... + else: + def _enablelegacywindowsfsencoding() -> None: ... + +def get_coroutine_origin_tracking_depth() -> int: ... +def set_coroutine_origin_tracking_depth(depth: int) -> None: ... + +# The following two functions were added in 3.11.0, 3.10.7, and 3.9.14, +# as part of the response to CVE-2020-10735 +def set_int_max_str_digits(maxdigits: int) -> None: ... +def get_int_max_str_digits() -> int: ... + +if sys.version_info >= (3, 15): + def set_lazy_imports(mode: _LazyImportMode) -> None: ... + def set_lazy_imports_filter(filter: _LazyImportFilter | None) -> None: ... + +if sys.version_info >= (3, 12): + if sys.version_info >= (3, 13): + def getunicodeinternedsize(*, _only_immortal: bool = False) -> int: ... + else: + def getunicodeinternedsize() -> int: ... + + def deactivate_stack_trampoline() -> None: ... + def is_stack_trampoline_active() -> bool: ... + # It always exists, but raises on non-linux platforms: + if sys.platform == "linux": + def activate_stack_trampoline(backend: str, /) -> None: ... + else: + def activate_stack_trampoline(backend: str, /) -> Never: ... + + from . import _monitoring + + monitoring = _monitoring + +if sys.version_info >= (3, 14): + def is_remote_debug_enabled() -> bool: ... + def remote_exec(pid: int, script: StrOrBytesPath) -> None: ... + def _is_immortal(op: object, /) -> bool: ... + + from . import __jit + + _jit = __jit diff --git a/stdlib/sys/__jit.pyi b/stdlib/sys/__jit.pyi new file mode 100644 index 000000000000..90fb65c1d9ef --- /dev/null +++ b/stdlib/sys/__jit.pyi @@ -0,0 +1,11 @@ +# This py314+ module provides annotations for `sys._jit`. +# It's named `sys.__jit` in typeshed, +# because trying to import `sys._jit` will fail at runtime! +# At runtime, `sys._jit` has the unusual status +# of being a `types.ModuleType` instance that cannot be directly imported, +# (same as sys.monitoring) +# and exists in the `sys`-module namespace despite `sys` not being a package. + +def is_available() -> bool: ... +def is_enabled() -> bool: ... +def is_active() -> bool: ... diff --git a/stdlib/sys/_monitoring.pyi b/stdlib/sys/_monitoring.pyi new file mode 100644 index 000000000000..b999d63f6470 --- /dev/null +++ b/stdlib/sys/_monitoring.pyi @@ -0,0 +1,69 @@ +# This py312+ module provides annotations for `sys.monitoring`. +# It's named `sys._monitoring` in typeshed, +# because trying to import `sys.monitoring` will fail at runtime! +# At runtime, `sys.monitoring` has the unusual status +# of being a `types.ModuleType` instance that cannot be directly imported, +# (same as sys._jit) +# and exists in the `sys`-module namespace despite `sys` not being a package. + +import sys +from collections.abc import Callable +from types import CodeType +from typing import Any, Final, type_check_only +from typing_extensions import deprecated + +DEBUGGER_ID: Final = 0 +COVERAGE_ID: Final = 1 +PROFILER_ID: Final = 2 +OPTIMIZER_ID: Final = 5 + +def use_tool_id(tool_id: int, name: str, /) -> None: ... + +if sys.version_info >= (3, 14): + def clear_tool_id(tool_id: int, /) -> None: ... + +def free_tool_id(tool_id: int, /) -> None: ... +def get_tool(tool_id: int, /) -> str | None: ... + +events: Final[_events] + +@type_check_only +class _events: + CALL: Final[int] + C_RAISE: Final[int] + C_RETURN: Final[int] + EXCEPTION_HANDLED: Final[int] + INSTRUCTION: Final[int] + JUMP: Final[int] + LINE: Final[int] + NO_EVENTS: Final[int] + PY_RESUME: Final[int] + PY_RETURN: Final[int] + PY_START: Final[int] + PY_THROW: Final[int] + PY_UNWIND: Final[int] + PY_YIELD: Final[int] + RAISE: Final[int] + RERAISE: Final[int] + STOP_ITERATION: Final[int] + if sys.version_info >= (3, 14): + BRANCH_LEFT: Final[int] + BRANCH_RIGHT: Final[int] + + @property + @deprecated("Deprecated since Python 3.14. Use `BRANCH_LEFT` or `BRANCH_RIGHT` instead.") + def BRANCH(self) -> int: ... + + else: + BRANCH: Final[int] + +def get_events(tool_id: int, /) -> int: ... +def set_events(tool_id: int, event_set: int, /) -> None: ... +def get_local_events(tool_id: int, code: CodeType, /) -> int: ... +def set_local_events(tool_id: int, code: CodeType, event_set: int, /) -> None: ... +def restart_events() -> None: ... + +DISABLE: Final[object] +MISSING: Final[object] + +def register_callback(tool_id: int, event: int, func: Callable[..., object] | None, /) -> Callable[..., Any] | None: ... diff --git a/stdlib/sysconfig.pyi b/stdlib/sysconfig.pyi index ff828d519912..bd20113e9df5 100644 --- a/stdlib/sysconfig.pyi +++ b/stdlib/sysconfig.pyi @@ -1,17 +1,59 @@ -from typing import IO, Any, Tuple, overload +import sys +from typing import IO, Any, Literal, overload +from typing_extensions import LiteralString, deprecated + +__all__ = [ + "get_config_h_filename", + "get_config_var", + "get_config_vars", + "get_makefile_filename", + "get_path", + "get_path_names", + "get_paths", + "get_platform", + "get_python_version", + "get_scheme_names", + "parse_config_h", +] + +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") +def get_config_var(name: Literal["SO"]) -> Any: ... +@overload +def get_config_var(name: str) -> Any: ... -def get_config_var(name: str) -> str | None: ... @overload def get_config_vars() -> dict[str, Any]: ... @overload -def get_config_vars(arg: str, *args: str) -> list[Any]: ... -def get_scheme_names() -> Tuple[str, ...]: ... -def get_path_names() -> Tuple[str, ...]: ... -def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> str: ... -def get_paths(scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> dict[str, str]: ... +def get_config_vars(arg: str, /, *args: str) -> list[Any]: ... + +def get_scheme_names() -> tuple[str, ...]: ... +def get_default_scheme() -> LiteralString: ... +def get_preferred_scheme(key: Literal["prefix", "home", "user"]) -> LiteralString: ... + +# Documented -- see https://docs.python.org/3/library/sysconfig.html#sysconfig._get_preferred_schemes +def _get_preferred_schemes() -> dict[Literal["prefix", "home", "user"], LiteralString]: ... +def get_path_names() -> tuple[str, ...]: ... +def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> str: ... +def get_paths(scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... -def is_python_build(check_home: bool = ...) -> bool: ... -def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = ...) -> dict[str, Any]: ... + +if sys.version_info >= (3, 15): + def is_python_build() -> bool: ... +elif sys.version_info >= (3, 11): + @overload + def is_python_build() -> bool: ... + @overload + @deprecated("The `check_home` parameter is deprecated; removed in Python 3.15.") + def is_python_build(check_home: object = None) -> bool: ... +else: + @overload + def is_python_build() -> bool: ... + @overload + @deprecated("The `check_home` parameter is deprecated; removed in Python 3.15.") + def is_python_build(check_home: bool = False) -> bool: ... + +def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = None) -> dict[str, Any]: ... def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... diff --git a/stdlib/syslog.pyi b/stdlib/syslog.pyi index d284634f8667..0cb97dcd3ca7 100644 --- a/stdlib/syslog.pyi +++ b/stdlib/syslog.pyi @@ -1,46 +1,58 @@ -from typing import overload -from typing_extensions import Literal +import sys +from typing import Final, overload -LOG_ALERT: int -LOG_AUTH: int -LOG_AUTHPRIV: Literal[80] -LOG_CONS: int -LOG_CRIT: int -LOG_CRON: int -LOG_DAEMON: int -LOG_DEBUG: int -LOG_EMERG: int -LOG_ERR: int -LOG_INFO: int -LOG_KERN: int -LOG_LOCAL0: int -LOG_LOCAL1: int -LOG_LOCAL2: int -LOG_LOCAL3: int -LOG_LOCAL4: int -LOG_LOCAL5: int -LOG_LOCAL6: int -LOG_LOCAL7: int -LOG_LPR: int -LOG_MAIL: int -LOG_NDELAY: int -LOG_NEWS: int -LOG_NOTICE: int -LOG_NOWAIT: int -LOG_ODELAY: Literal[4] -LOG_PERROR: int -LOG_PID: int -LOG_SYSLOG: int -LOG_USER: int -LOG_UUCP: int -LOG_WARNING: int +if sys.platform != "win32": + LOG_ALERT: Final = 1 + LOG_AUTH: Final = 32 + LOG_AUTHPRIV: Final = 80 + LOG_CONS: Final = 2 + LOG_CRIT: Final = 2 + LOG_CRON: Final = 72 + LOG_DAEMON: Final = 24 + LOG_DEBUG: Final = 7 + LOG_EMERG: Final = 0 + LOG_ERR: Final = 3 + LOG_INFO: Final = 6 + LOG_KERN: Final = 0 + LOG_LOCAL0: Final = 128 + LOG_LOCAL1: Final = 136 + LOG_LOCAL2: Final = 144 + LOG_LOCAL3: Final = 152 + LOG_LOCAL4: Final = 160 + LOG_LOCAL5: Final = 168 + LOG_LOCAL6: Final = 176 + LOG_LOCAL7: Final = 184 + LOG_LPR: Final = 48 + LOG_MAIL: Final = 16 + LOG_NDELAY: Final = 8 + LOG_NEWS: Final = 56 + LOG_NOTICE: Final = 5 + LOG_NOWAIT: Final = 16 + LOG_ODELAY: Final = 4 + LOG_PERROR: Final = 32 + LOG_PID: Final = 1 + LOG_SYSLOG: Final = 40 + LOG_USER: Final = 8 + LOG_UUCP: Final = 64 + LOG_WARNING: Final = 4 -def LOG_MASK(a: int) -> int: ... -def LOG_UPTO(a: int) -> int: ... -def closelog() -> None: ... -def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... -def setlogmask(x: int) -> int: ... -@overload -def syslog(priority: int, message: str) -> None: ... -@overload -def syslog(message: str) -> None: ... + if sys.version_info >= (3, 13): + LOG_FTP: Final = 88 + + if sys.platform == "darwin": + LOG_INSTALL: Final = 112 + LOG_LAUNCHD: Final = 192 + LOG_NETINFO: Final = 96 + LOG_RAS: Final = 120 + LOG_REMOTEAUTH: Final = 104 + + def LOG_MASK(pri: int, /) -> int: ... + def LOG_UPTO(pri: int, /) -> int: ... + def closelog() -> None: ... + def openlog(ident: str = ..., logoption: int = 0, facility: int = ...) -> None: ... + def setlogmask(maskpri: int, /) -> int: ... + + @overload + def syslog(priority: int, message: str) -> None: ... + @overload + def syslog(message: str) -> None: ... diff --git a/stdlib/tabnanny.pyi b/stdlib/tabnanny.pyi index 4c7be83b0511..8a8592f44124 100644 --- a/stdlib/tabnanny.pyi +++ b/stdlib/tabnanny.pyi @@ -1,5 +1,7 @@ from _typeshed import StrOrBytesPath -from typing import Iterable +from collections.abc import Iterable + +__all__ = ["check", "NannyNag", "process_tokens"] verbose: int filename_only: int diff --git a/stdlib/tarfile.pyi b/stdlib/tarfile.pyi index 0134316d8107..5def3717a0a2 100644 --- a/stdlib/tarfile.pyi +++ b/stdlib/tarfile.pyi @@ -1,273 +1,707 @@ import bz2 import io import sys -from _typeshed import Self, StrOrBytesPath, StrPath +from _typeshed import FileDescriptorOrPath, ReadableBuffer, StrOrBytesPath, StrPath, SupportsRead, WriteableBuffer +from builtins import list as _list # aliases to avoid name clashes with fields named "type" or "list" from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, Protocol, Tuple, Type, TypeVar, overload -from typing_extensions import Literal +from typing import IO, ClassVar, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated -_TF = TypeVar("_TF", bound=TarFile) +if sys.version_info >= (3, 14): + from compression.zstd import ZstdDict +__all__ = [ + "TarFile", + "TarInfo", + "is_tarfile", + "TarError", + "ReadError", + "CompressionError", + "StreamError", + "ExtractError", + "HeaderError", + "ENCODING", + "USTAR_FORMAT", + "GNU_FORMAT", + "PAX_FORMAT", + "DEFAULT_FORMAT", + "open", +] +if sys.version_info >= (3, 12): + __all__ += [ + "fully_trusted_filter", + "data_filter", + "tar_filter", + "FilterError", + "AbsoluteLinkError", + "OutsideDestinationError", + "SpecialFileError", + "AbsolutePathError", + "LinkOutsideDestinationError", + ] +if sys.version_info >= (3, 13): + __all__ += ["LinkFallbackError"] + +_FilterFunction: TypeAlias = Callable[[TarInfo, str], TarInfo | None] +_TarfileFilter: TypeAlias = Literal["fully_trusted", "tar", "data"] | _FilterFunction + +@type_check_only class _Fileobj(Protocol): - def read(self, __size: int) -> bytes: ... - def write(self, __b: bytes) -> object: ... + def read(self, size: int, /) -> bytes: ... + def write(self, b: bytes, /) -> object: ... def tell(self) -> int: ... - def seek(self, __pos: int) -> object: ... + def seek(self, pos: int, /) -> object: ... def close(self) -> object: ... # Optional fields: # name: str | bytes # mode: Literal["rb", "r+b", "wb", "xb"] +@type_check_only class _Bz2ReadableFileobj(bz2._ReadableFileobj): def close(self) -> object: ... +@type_check_only class _Bz2WritableFileobj(bz2._WritableFileobj): def close(self) -> object: ... # tar constants -NUL: bytes -BLOCKSIZE: int -RECORDSIZE: int -GNU_MAGIC: bytes -POSIX_MAGIC: bytes - -LENGTH_NAME: int -LENGTH_LINK: int -LENGTH_PREFIX: int - -REGTYPE: bytes -AREGTYPE: bytes -LNKTYPE: bytes -SYMTYPE: bytes -CONTTYPE: bytes -BLKTYPE: bytes -DIRTYPE: bytes -FIFOTYPE: bytes -CHRTYPE: bytes - -GNUTYPE_LONGNAME: bytes -GNUTYPE_LONGLINK: bytes -GNUTYPE_SPARSE: bytes - -XHDTYPE: bytes -XGLTYPE: bytes -SOLARIS_XHDTYPE: bytes - -USTAR_FORMAT: int -GNU_FORMAT: int -PAX_FORMAT: int -DEFAULT_FORMAT: int +NUL: Final = b"\0" +BLOCKSIZE: Final = 512 +RECORDSIZE: Final = 10240 +GNU_MAGIC: Final = b"ustar \0" +POSIX_MAGIC: Final = b"ustar\x0000" + +LENGTH_NAME: Final = 100 +LENGTH_LINK: Final = 100 +LENGTH_PREFIX: Final = 155 + +REGTYPE: Final = b"0" +AREGTYPE: Final = b"\0" +LNKTYPE: Final = b"1" +SYMTYPE: Final = b"2" +CHRTYPE: Final = b"3" +BLKTYPE: Final = b"4" +DIRTYPE: Final = b"5" +FIFOTYPE: Final = b"6" +CONTTYPE: Final = b"7" + +GNUTYPE_LONGNAME: Final = b"L" +GNUTYPE_LONGLINK: Final = b"K" +GNUTYPE_SPARSE: Final = b"S" + +XHDTYPE: Final = b"x" +XGLTYPE: Final = b"g" +SOLARIS_XHDTYPE: Final = b"X" + +_TarFormat: TypeAlias = Literal[0, 1, 2] # does not exist at runtime +USTAR_FORMAT: Final = 0 +GNU_FORMAT: Final = 1 +PAX_FORMAT: Final = 2 +DEFAULT_FORMAT: Final = PAX_FORMAT # tarfile constants -SUPPORTED_TYPES: Tuple[bytes, ...] -REGULAR_TYPES: Tuple[bytes, ...] -GNU_TYPES: Tuple[bytes, ...] -PAX_FIELDS: Tuple[str, ...] -PAX_NUMBER_FIELDS: dict[str, type] -PAX_NAME_FIELDS: set[str] - -ENCODING: str - -def open( - name: StrOrBytesPath | None = ..., - mode: str = ..., - fileobj: IO[bytes] | None = ..., # depends on mode - bufsize: int = ..., - *, - format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., - dereference: bool | None = ..., - ignore_zeros: bool | None = ..., - encoding: str | None = ..., - errors: str = ..., - pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - compresslevel: int | None = ..., -) -> TarFile: ... - -class ExFileObject(io.BufferedReader): - def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... +SUPPORTED_TYPES: Final[tuple[bytes, ...]] +REGULAR_TYPES: Final[tuple[bytes, ...]] +GNU_TYPES: Final[tuple[bytes, ...]] +PAX_FIELDS: Final[tuple[str, ...]] +PAX_NUMBER_FIELDS: Final[dict[str, type]] +PAX_NAME_FIELDS: Final[set[str]] + +ENCODING: Final[str] -_list = list # conflicts with method name +class ExFileObject(io.BufferedReader): # undocumented + def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... class TarFile: - OPEN_METH: Mapping[str, str] + OPEN_METH: ClassVar[Mapping[str, str]] name: StrOrBytesPath | None mode: Literal["r", "a", "w", "x"] - fileobj: _Fileobj | None - format: int | None - tarinfo: Type[TarInfo] - dereference: bool | None - ignore_zeros: bool | None - encoding: str | None + fileobj: _Fileobj + format: _TarFormat + tarinfo: type[TarInfo] + dereference: bool + ignore_zeros: bool + encoding: str errors: str - fileobject: Type[ExFileObject] - pax_headers: Mapping[str, str] | None - debug: int | None - errorlevel: int | None + fileobject: type[ExFileObject] # undocumented + pax_headers: Mapping[str, str] + debug: Literal[0, 1, 2, 3] + errorlevel: Literal[0, 1, 2] offset: int # undocumented - def __init__( - self, - name: StrOrBytesPath | None = ..., - mode: Literal["r", "a", "w", "x"] = ..., - fileobj: _Fileobj | None = ..., + extraction_filter: _FilterFunction | None + if sys.version_info >= (3, 13): + stream: bool + if sys.version_info >= (3, 15): + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + stream: bool = False, + mtime: float | None = None, + ) -> None: ... + elif sys.version_info >= (3, 13): + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + stream: bool = False, + ) -> None: ... + else: + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + ) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Iterator[TarInfo]: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + mode: Literal["r", "r:*", "r:", "r:gz", "r:bz2", "r:xz"] = "r", + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., errors: str = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - copybufsize: int | None = ..., # undocumented - ) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - def __iter__(self) -> Iterator[TarInfo]: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + + if sys.version_info >= (3, 14): + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["r:zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x", "x:", "a", "a:", "w", "w:", "w:tar"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x", "x:", "a", "a:", "w", "w:", "w:tar"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x:gz", "x:bz2", "w:gz", "w:bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x:gz", "x:bz2", "w:gz", "w:bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x:xz", "w:xz"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + preset: int | None = ..., + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x:xz", "w:xz"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + preset: int | None = ..., + ) -> Self: ... + if sys.version_info >= (3, 14): + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x:zst", "w:zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x:zst", "w:zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | ReadableBuffer | None, + mode: Literal["r|*", "r|", "r|gz", "r|bz2", "r|xz", "r|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | ReadableBuffer | None = None, + *, + mode: Literal["r|*", "r|", "r|gz", "r|bz2", "r|xz", "r|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None, + mode: Literal["w|", "w|xz", "w|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None = None, + *, + mode: Literal["w|", "w|xz", "w|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None, + mode: Literal["w|gz", "w|bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @overload @classmethod def open( - cls: Type[_TF], - name: StrOrBytesPath | None = ..., - mode: str = ..., - fileobj: IO[bytes] | None = ..., # depends on mode - bufsize: int = ..., + cls, + name: StrOrBytesPath | WriteableBuffer | None = None, *, + mode: Literal["w|gz", "w|bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., errors: str = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @classmethod def taropen( - cls: Type[_TF], + cls, name: StrOrBytesPath | None, - mode: Literal["r", "a", "w", "x"] = ..., - fileobj: _Fileobj | None = ..., + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, *, compresslevel: int = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload @classmethod def gzopen( - cls: Type[_TF], + cls, name: StrOrBytesPath | None, - mode: Literal["r"] = ..., - fileobj: _GzipReadableFileobj | None = ..., - compresslevel: int = ..., + mode: Literal["r"] = "r", + fileobj: _GzipReadableFileobj | None = None, + compresslevel: int = 9, *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... @overload @classmethod def gzopen( - cls: Type[_TF], + cls, name: StrOrBytesPath | None, mode: Literal["w", "x"], - fileobj: _GzipWritableFileobj | None = ..., - compresslevel: int = ..., + fileobj: _GzipWritableFileobj | None = None, + compresslevel: int = 9, *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload @classmethod def bz2open( - cls: Type[_TF], + cls, name: StrOrBytesPath | None, mode: Literal["w", "x"], - fileobj: _Bz2WritableFileobj | None = ..., - compresslevel: int = ..., + fileobj: _Bz2WritableFileobj | None = None, + compresslevel: int = 9, *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... @overload @classmethod def bz2open( - cls: Type[_TF], + cls, name: StrOrBytesPath | None, - mode: Literal["r"] = ..., - fileobj: _Bz2ReadableFileobj | None = ..., - compresslevel: int = ..., + mode: Literal["r"] = "r", + fileobj: _Bz2ReadableFileobj | None = None, + compresslevel: int = 9, *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @classmethod def xzopen( - cls: Type[_TF], + cls, name: StrOrBytesPath | None, - mode: Literal["r", "w", "x"] = ..., - fileobj: IO[bytes] | None = ..., - preset: int | None = ..., + mode: Literal["r", "w", "x"] = "r", + fileobj: IO[bytes] | None = None, + preset: int | None = None, *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., - debug: int | None = ..., - errorlevel: int | None = ..., - ) -> _TF: ... + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + if sys.version_info >= (3, 14): + @overload + @classmethod + def zstopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["r"] = "r", + fileobj: IO[bytes] | None = None, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def zstopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["w", "x"], + fileobj: IO[bytes] | None = None, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> _list[TarInfo]: ... def getnames(self) -> _list[str]: ... - def list(self, verbose: bool = ..., *, members: _list[TarInfo] | None = ...) -> None: ... + def list(self, verbose: bool = True, *, members: Iterable[TarInfo] | None = None) -> None: ... def next(self) -> TarInfo | None: ... + # Calling this method without `filter` is deprecated, but it may be set either on the class or in an + # individual call, so we can't mark it as @deprecated here. def extractall( - self, path: StrOrBytesPath = ..., members: Iterable[TarInfo] | None = ..., *, numeric_owner: bool = ... + self, + path: StrOrBytesPath = ".", + members: Iterable[TarInfo] | None = None, + *, + numeric_owner: bool = False, + filter: _TarfileFilter | None = None, ) -> None: ... + # Same situation as for `extractall`. def extract( - self, member: str | TarInfo, path: StrOrBytesPath = ..., set_attrs: bool = ..., *, numeric_owner: bool = ... + self, + member: str | TarInfo, + path: StrOrBytesPath = "", + set_attrs: bool = True, + *, + numeric_owner: bool = False, + filter: _TarfileFilter | None = None, ) -> None: ... def _extract_member( - self, tarinfo: TarInfo, targetpath: str, set_attrs: bool = ..., numeric_owner: bool = ... + self, + tarinfo: TarInfo, + targetpath: str, + set_attrs: bool = True, + numeric_owner: bool = False, + *, + filter_function: _FilterFunction | None = None, + extraction_root: str | None = None, ) -> None: ... # undocumented def extractfile(self, member: str | TarInfo) -> IO[bytes] | None: ... def makedir(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented @@ -276,40 +710,29 @@ class TarFile: def makefifo(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented def makedev(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented def makelink(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makelink_with_filter( + self, tarinfo: TarInfo, targetpath: StrOrBytesPath, filter_function: _FilterFunction, extraction_root: str + ) -> None: ... # undocumented def chown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath, numeric_owner: bool) -> None: ... # undocumented def chmod(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented def utime(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented - if sys.version_info >= (3, 7): - def add( - self, - name: StrPath, - arcname: StrPath | None = ..., - recursive: bool = ..., - *, - filter: Callable[[TarInfo], TarInfo | None] | None = ..., - ) -> None: ... - else: - def add( - self, - name: StrPath, - arcname: StrPath | None = ..., - recursive: bool = ..., - exclude: Callable[[str], bool] | None = ..., - *, - filter: Callable[[TarInfo], TarInfo | None] | None = ..., - ) -> None: ... - def addfile(self, tarinfo: TarInfo, fileobj: IO[bytes] | None = ...) -> None: ... - def gettarinfo(self, name: str | None = ..., arcname: str | None = ..., fileobj: IO[bytes] | None = ...) -> TarInfo: ... + def add( + self, + name: StrPath, + arcname: StrPath | None = None, + recursive: bool = True, + *, + filter: Callable[[TarInfo], TarInfo | None] | None = None, + ) -> None: ... + def addfile(self, tarinfo: TarInfo, fileobj: SupportsRead[bytes] | None = None) -> None: ... + def gettarinfo( + self, name: StrOrBytesPath | None = None, arcname: str | None = None, fileobj: IO[bytes] | None = None + ) -> TarInfo: ... def close(self) -> None: ... -if sys.version_info >= (3, 9): - def is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: ... +open = TarFile.open -else: - def is_tarfile(name: StrOrBytesPath) -> bool: ... - -if sys.version_info < (3, 8): - def filemode(mode: int) -> str: ... # undocumented +def is_tarfile(name: FileDescriptorOrPath | IO[bytes]) -> bool: ... class TarError(Exception): ... class ReadError(TarError): ... @@ -318,37 +741,112 @@ class StreamError(TarError): ... class ExtractError(TarError): ... class HeaderError(TarError): ... +class FilterError(TarError): + # This attribute is only set directly on the subclasses, but the documentation guarantees + # that it is always present on FilterError. + tarinfo: TarInfo + +class AbsolutePathError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... + +class OutsideDestinationError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... + +class SpecialFileError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... + +class AbsoluteLinkError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... + +class LinkOutsideDestinationError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... + +class LinkFallbackError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... + +def fully_trusted_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def tar_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def data_filter(member: TarInfo, dest_path: str) -> TarInfo: ... + class TarInfo: + __slots__ = ( + "name", + "mode", + "uid", + "gid", + "size", + "mtime", + "chksum", + "type", + "linkname", + "uname", + "gname", + "devmajor", + "devminor", + "offset", + "offset_data", + "pax_headers", + "sparse", + "_tarfile", + "_sparse_structs", + "_link_target", + ) name: str - path: str size: int - mtime: int + mtime: int | float chksum: int devmajor: int devminor: int offset: int offset_data: int sparse: bytes | None - tarfile: TarFile | None mode: int - type: bytes + type: bytes # usually one of the TYPE constants, but could be an arbitrary byte linkname: str uid: int gid: int uname: str gname: str pax_headers: Mapping[str, str] - def __init__(self, name: str = ...) -> None: ... + def __init__(self, name: str = "") -> None: ... + + @property + @deprecated("Deprecated; will be removed in Python 3.16.") + def tarfile(self) -> TarFile | None: ... + @tarfile.setter + @deprecated("Deprecated; will be removed in Python 3.16.") + def tarfile(self, tarfile: TarFile | None) -> None: ... + @classmethod - def frombuf(cls, buf: bytes, encoding: str, errors: str) -> TarInfo: ... + def frombuf(cls, buf: bytes | bytearray, encoding: str, errors: str) -> Self: ... @classmethod - def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... + def fromtarfile(cls, tarfile: TarFile) -> Self: ... + + @property + def path(self) -> str: ... + @path.setter + def path(self, name: str) -> None: ... + @property def linkpath(self) -> str: ... @linkpath.setter def linkpath(self, linkname: str) -> None: ... + + def replace( + self, + *, + name: str = ..., + mtime: float = ..., + mode: int = ..., + linkname: str = ..., + uid: int = ..., + gid: int = ..., + uname: str = ..., + gname: str = ..., + deep: bool = True, + ) -> Self: ... def get_info(self) -> Mapping[str, str | int | bytes | Mapping[str, str]]: ... - def tobuf(self, format: int | None = ..., encoding: str | None = ..., errors: str = ...) -> bytes: ... + def tobuf(self, format: _TarFormat | None = 2, encoding: str | None = "utf-8", errors: str = "surrogateescape") -> bytes: ... def create_ustar_header( self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str ) -> bytes: ... diff --git a/stdlib/telnetlib.pyi b/stdlib/telnetlib.pyi index cf00856d9332..88aa43d24899 100644 --- a/stdlib/telnetlib.pyi +++ b/stdlib/telnetlib.pyi @@ -1,97 +1,103 @@ import socket -from _typeshed import Self -from typing import Any, Callable, Match, Pattern, Sequence +from collections.abc import Callable, MutableSequence, Sequence +from re import Match, Pattern +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self -DEBUGLEVEL: int -TELNET_PORT: int +__all__ = ["Telnet"] -IAC: bytes -DONT: bytes -DO: bytes -WONT: bytes -WILL: bytes -theNULL: bytes +DEBUGLEVEL: Final = 0 +TELNET_PORT: Final = 23 -SE: bytes -NOP: bytes -DM: bytes -BRK: bytes -IP: bytes -AO: bytes -AYT: bytes -EC: bytes -EL: bytes -GA: bytes -SB: bytes +IAC: Final = b"\xff" +DONT: Final = b"\xfe" +DO: Final = b"\xfd" +WONT: Final = b"\xfc" +WILL: Final = b"\xfb" +theNULL: Final = b"\x00" -BINARY: bytes -ECHO: bytes -RCP: bytes -SGA: bytes -NAMS: bytes -STATUS: bytes -TM: bytes -RCTE: bytes -NAOL: bytes -NAOP: bytes -NAOCRD: bytes -NAOHTS: bytes -NAOHTD: bytes -NAOFFD: bytes -NAOVTS: bytes -NAOVTD: bytes -NAOLFD: bytes -XASCII: bytes -LOGOUT: bytes -BM: bytes -DET: bytes -SUPDUP: bytes -SUPDUPOUTPUT: bytes -SNDLOC: bytes -TTYPE: bytes -EOR: bytes -TUID: bytes -OUTMRK: bytes -TTYLOC: bytes -VT3270REGIME: bytes -X3PAD: bytes -NAWS: bytes -TSPEED: bytes -LFLOW: bytes -LINEMODE: bytes -XDISPLOC: bytes -OLD_ENVIRON: bytes -AUTHENTICATION: bytes -ENCRYPT: bytes -NEW_ENVIRON: bytes +SE: Final = b"\xf0" +NOP: Final = b"\xf1" +DM: Final = b"\xf2" +BRK: Final = b"\xf3" +IP: Final = b"\xf4" +AO: Final = b"\xf5" +AYT: Final = b"\xf6" +EC: Final = b"\xf7" +EL: Final = b"\xf8" +GA: Final = b"\xf9" +SB: Final = b"\xfa" -TN3270E: bytes -XAUTH: bytes -CHARSET: bytes -RSP: bytes -COM_PORT_OPTION: bytes -SUPPRESS_LOCAL_ECHO: bytes -TLS: bytes -KERMIT: bytes -SEND_URL: bytes -FORWARD_X: bytes -PRAGMA_LOGON: bytes -SSPI_LOGON: bytes -PRAGMA_HEARTBEAT: bytes -EXOPL: bytes -NOOPT: bytes +BINARY: Final = b"\x00" +ECHO: Final = b"\x01" +RCP: Final = b"\x02" +SGA: Final = b"\x03" +NAMS: Final = b"\x04" +STATUS: Final = b"\x05" +TM: Final = b"\x06" +RCTE: Final = b"\x07" +NAOL: Final = b"\x08" +NAOP: Final = b"\t" +NAOCRD: Final = b"\n" +NAOHTS: Final = b"\x0b" +NAOHTD: Final = b"\x0c" +NAOFFD: Final = b"\r" +NAOVTS: Final = b"\x0e" +NAOVTD: Final = b"\x0f" +NAOLFD: Final = b"\x10" +XASCII: Final = b"\x11" +LOGOUT: Final = b"\x12" +BM: Final = b"\x13" +DET: Final = b"\x14" +SUPDUP: Final = b"\x15" +SUPDUPOUTPUT: Final = b"\x16" +SNDLOC: Final = b"\x17" +TTYPE: Final = b"\x18" +EOR: Final = b"\x19" +TUID: Final = b"\x1a" +OUTMRK: Final = b"\x1b" +TTYLOC: Final = b"\x1c" +VT3270REGIME: Final = b"\x1d" +X3PAD: Final = b"\x1e" +NAWS: Final = b"\x1f" +TSPEED: Final = b" " +LFLOW: Final = b"!" +LINEMODE: Final = b'"' +XDISPLOC: Final = b"#" +OLD_ENVIRON: Final = b"$" +AUTHENTICATION: Final = b"%" +ENCRYPT: Final = b"&" +NEW_ENVIRON: Final = b"'" + +TN3270E: Final = b"(" +XAUTH: Final = b")" +CHARSET: Final = b"*" +RSP: Final = b"+" +COM_PORT_OPTION: Final = b"," +SUPPRESS_LOCAL_ECHO: Final = b"-" +TLS: Final = b"." +KERMIT: Final = b"/" +SEND_URL: Final = b"0" +FORWARD_X: Final = b"1" +PRAGMA_LOGON: Final = b"\x8a" +SSPI_LOGON: Final = b"\x8b" +PRAGMA_HEARTBEAT: Final = b"\x8c" +EXOPL: Final = b"\xff" +NOOPT: Final = b"\x00" class Telnet: host: str | None # undocumented - def __init__(self, host: str | None = ..., port: int = ..., timeout: float = ...) -> None: ... - def open(self, host: str, port: int = ..., timeout: float = ...) -> None: ... + sock: socket.socket | None # undocumented + def __init__(self, host: str | None = None, port: int = 0, timeout: float = ...) -> None: ... + def open(self, host: str, port: int = 0, timeout: float = ...) -> None: ... def msg(self, msg: str, *args: Any) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: ... def close(self) -> None: ... def get_socket(self) -> socket.socket: ... def fileno(self) -> int: ... def write(self, buffer: bytes) -> None: ... - def read_until(self, match: bytes, timeout: float | None = ...) -> bytes: ... + def read_until(self, match: bytes, timeout: float | None = None) -> bytes: ... def read_all(self) -> bytes: ... def read_some(self) -> bytes: ... def read_very_eager(self) -> bytes: ... @@ -99,7 +105,7 @@ class Telnet: def read_lazy(self) -> bytes: ... def read_very_lazy(self) -> bytes: ... def read_sb_data(self) -> bytes: ... - def set_option_negotiation_callback(self, callback: Callable[[socket.socket, bytes, bytes], Any] | None) -> None: ... + def set_option_negotiation_callback(self, callback: Callable[[socket.socket, bytes, bytes], object] | None) -> None: ... def process_rawq(self) -> None: ... def rawq_getchar(self) -> bytes: ... def fill_rawq(self) -> None: ... @@ -108,7 +114,10 @@ class Telnet: def mt_interact(self) -> None: ... def listener(self) -> None: ... def expect( - self, list: Sequence[Pattern[bytes] | bytes], timeout: float | None = ... + self, list: MutableSequence[Pattern[bytes] | bytes] | Sequence[Pattern[bytes]], timeout: float | None = None ) -> tuple[int, Match[bytes] | None, bytes]: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... diff --git a/stdlib/tempfile.pyi b/stdlib/tempfile.pyi index 119c111bc4e1..1df04a3d3667 100644 --- a/stdlib/tempfile.pyi +++ b/stdlib/tempfile.pyi @@ -1,175 +1,226 @@ -import os +import io import sys -from _typeshed import Self -from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Tuple, Type, Union, overload -from typing_extensions import Literal +from _typeshed import ( + BytesPath, + GenericPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + StrPath, + WriteableBuffer, +) +from collections.abc import Iterable, Iterator +from types import GenericAlias, TracebackType +from typing import IO, Any, AnyStr, Final, Generic, Literal, overload +from typing_extensions import Self, deprecated -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = [ + "NamedTemporaryFile", + "TemporaryFile", + "SpooledTemporaryFile", + "TemporaryDirectory", + "mkstemp", + "mkdtemp", + "mktemp", + "TMP_MAX", + "gettempprefix", + "tempdir", + "gettempdir", + "gettempprefixb", + "gettempdirb", +] # global variables -TMP_MAX: int +TMP_MAX: Final[int] tempdir: str | None template: str -_DirT = Union[AnyStr, os.PathLike[AnyStr]] - -if sys.version_info >= (3, 8): +if sys.version_info >= (3, 12): @overload def NamedTemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - delete: bool = ..., + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, *, - errors: str | None = ..., + errors: str | None = None, + delete_on_close: bool = True, ) -> _TemporaryFileWrapper[str]: ... @overload def NamedTemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - delete: bool = ..., + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, *, - errors: str | None = ..., + errors: str | None = None, + delete_on_close: bool = True, ) -> _TemporaryFileWrapper[bytes]: ... @overload def NamedTemporaryFile( - mode: str = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - delete: bool = ..., + mode: str = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, *, - errors: str | None = ..., + errors: str | None = None, + delete_on_close: bool = True, ) -> _TemporaryFileWrapper[Any]: ... - else: @overload def NamedTemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - delete: bool = ..., + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, ) -> _TemporaryFileWrapper[str]: ... @overload def NamedTemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - delete: bool = ..., + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, ) -> _TemporaryFileWrapper[bytes]: ... @overload def NamedTemporaryFile( - mode: str = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - delete: bool = ..., + mode: str = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, ) -> _TemporaryFileWrapper[Any]: ... if sys.platform == "win32": TemporaryFile = NamedTemporaryFile else: - if sys.version_info >= (3, 8): - @overload - def TemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - *, - errors: str | None = ..., - ) -> IO[str]: ... - @overload - def TemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - *, - errors: str | None = ..., - ) -> IO[bytes]: ... - @overload - def TemporaryFile( - mode: str = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - *, - errors: str | None = ..., - ) -> IO[Any]: ... - else: - @overload - def TemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - ) -> IO[str]: ... - @overload - def TemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - ) -> IO[bytes]: ... - @overload - def TemporaryFile( - mode: str = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - ) -> IO[Any]: ... + # See the comments for builtins.open() for an explanation of the overloads. + @overload + def TemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.TextIOWrapper: ... + @overload + def TemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.FileIO: ... + @overload + def TemporaryFile( + *, + buffering: Literal[0], + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + errors: str | None = None, + ) -> io.FileIO: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedWriter: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedReader: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedRandom: ... + @overload + def TemporaryFile( + mode: str = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> IO[Any]: ... -class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): +class _TemporaryFileWrapper(IO[AnyStr]): file: IO[AnyStr] # io.TextIOWrapper, io.BufferedReader or io.BufferedWriter name: str delete: bool - def __init__(self, file: IO[AnyStr], name: str, delete: bool = ...) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, exc: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> bool | None: ... + if sys.version_info >= (3, 12): + def __init__(self, file: IO[AnyStr], name: str, delete: bool = True, delete_on_close: bool = True) -> None: ... + else: + def __init__(self, file: IO[AnyStr], name: str, delete: bool = True) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: ... def close(self) -> None: ... # These methods don't exist directly on this object, but @@ -197,104 +248,115 @@ class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> int: ... def writable(self) -> bool: ... - def write(self, s: AnyStr) -> int: ... + + @overload + def write(self: _TemporaryFileWrapper[str], s: str, /) -> int: ... + @overload + def write(self: _TemporaryFileWrapper[bytes], s: ReadableBuffer, /) -> int: ... + @overload + def write(self, s: AnyStr, /) -> int: ... + + @overload + def writelines(self: _TemporaryFileWrapper[str], lines: Iterable[str]) -> None: ... + @overload + def writelines(self: _TemporaryFileWrapper[bytes], lines: Iterable[ReadableBuffer]) -> None: ... + @overload def writelines(self, lines: Iterable[AnyStr]) -> None: ... -# It does not actually derive from IO[AnyStr], but it does implement the -# protocol. -class SpooledTemporaryFile(IO[AnyStr]): + @property + def closed(self) -> bool: ... + +if sys.version_info >= (3, 11): + _SpooledTemporaryFileBase = io.IOBase +else: + _SpooledTemporaryFileBase = object + +# It does not actually derive from IO[AnyStr], but it does mostly behave +# like one. +class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): + _file: IO[AnyStr] @property def encoding(self) -> str: ... # undocumented @property - def newlines(self) -> str | Tuple[str, ...] | None: ... # undocumented + def newlines(self) -> str | tuple[str, ...] | None: ... # undocumented + # bytes needs to go first, as default mode is to open as bytes - if sys.version_info >= (3, 8): - @overload - def __init__( - self: SpooledTemporaryFile[bytes], - max_size: int = ..., - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ) -> None: ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int = ..., - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ) -> None: ... - @overload - def __init__( - self, - max_size: int = ..., - mode: str = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ) -> None: ... - @property - def errors(self) -> str | None: ... - else: - @overload - def __init__( - self: SpooledTemporaryFile[bytes], - max_size: int = ..., - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - ) -> None: ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int = ..., - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - ) -> None: ... - @overload - def __init__( - self, - max_size: int = ..., - mode: str = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = 0, + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = 0, + *, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_size: int, + mode: str, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_size: int = 0, + *, + mode: str, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + errors: str | None = None, + ) -> None: ... + + @property + def errors(self) -> str | None: ... def rollover(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... # These methods are copied from the abstract methods of IO, because # SpooledTemporaryFile implements IO. # See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918. @@ -302,69 +364,110 @@ class SpooledTemporaryFile(IO[AnyStr]): def fileno(self) -> int: ... def flush(self) -> None: ... def isatty(self) -> bool: ... - def read(self, n: int = ...) -> AnyStr: ... - def readline(self, limit: int = ...) -> AnyStr: ... - def readlines(self, hint: int = ...) -> list[AnyStr]: ... + if sys.version_info >= (3, 11): + # These three work only if the SpooledTemporaryFile is opened in binary mode, + # because the underlying object in text mode does not have these methods. + def read1(self, size: int = ..., /) -> AnyStr: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... + def detach(self) -> io.RawIOBase: ... + + def read(self, n: int = ..., /) -> AnyStr: ... + def readline(self, limit: int | None = ..., /) -> AnyStr: ... # type: ignore[override] + def readlines(self, hint: int = ..., /) -> list[AnyStr]: ... # type: ignore[override] def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... + if sys.version_info >= (3, 11): + def truncate(self, size: int | None = None) -> int: ... + else: + def truncate(self, size: int | None = None) -> None: ... # type: ignore[override] + + @overload + def write(self: SpooledTemporaryFile[str], s: str) -> int: ... + @overload + def write(self: SpooledTemporaryFile[bytes], s: ReadableBuffer) -> int: ... + @overload def write(self, s: AnyStr) -> int: ... + + @overload # type: ignore[override] + def writelines(self: SpooledTemporaryFile[str], iterable: Iterable[str]) -> None: ... + @overload + def writelines(self: SpooledTemporaryFile[bytes], iterable: Iterable[ReadableBuffer]) -> None: ... + @overload def writelines(self, iterable: Iterable[AnyStr]) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... - # Other than the following methods, which do not exist on SpooledTemporaryFile + + def __iter__(self) -> Iterator[AnyStr]: ... # type: ignore[override] + # These exist at runtime only on 3.11+. def readable(self) -> bool: ... def seekable(self) -> bool: ... def writable(self) -> bool: ... - def __next__(self) -> AnyStr: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __next__(self) -> AnyStr: ... # type: ignore[override] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class TemporaryDirectory(Generic[AnyStr]): name: AnyStr - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 12): @overload def __init__( self: TemporaryDirectory[str], - suffix: None = ..., - prefix: None = ..., - dir: None = ..., - ignore_cleanup_errors: bool = ..., + suffix: str | None = None, + prefix: str | None = None, + dir: StrPath | None = None, + ignore_cleanup_errors: bool = False, + *, + delete: bool = True, ) -> None: ... @overload def __init__( - self, - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., - ignore_cleanup_errors: bool = ..., + self: TemporaryDirectory[bytes], + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: BytesPath | None = None, + ignore_cleanup_errors: bool = False, + *, + delete: bool = True, ) -> None: ... else: @overload - def __init__(self: TemporaryDirectory[str], suffix: None = ..., prefix: None = ..., dir: None = ...) -> None: ... + def __init__( + self: TemporaryDirectory[str], + suffix: str | None = None, + prefix: str | None = None, + dir: StrPath | None = None, + ignore_cleanup_errors: bool = False, + ) -> None: ... @overload - def __init__(self, suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> None: ... + def __init__( + self: TemporaryDirectory[bytes], + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: BytesPath | None = None, + ignore_cleanup_errors: bool = False, + ) -> None: ... + def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -@overload -def mkstemp() -> tuple[int, str]: ... +# The overloads overlap, but they should still work fine. @overload def mkstemp( - suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ..., text: bool = ... -) -> tuple[int, AnyStr]: ... -@overload -def mkdtemp() -> str: ... + suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None, text: bool = False +) -> tuple[int, str]: ... @overload -def mkdtemp(suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> AnyStr: ... +def mkstemp( + suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None, text: bool = False +) -> tuple[int, bytes]: ... + +# The overloads overlap, but they should still work fine. @overload -def mktemp() -> str: ... +def mkdtemp(suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None) -> str: ... @overload -def mktemp(suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> AnyStr: ... +def mkdtemp(suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None) -> bytes: ... + +@deprecated("Deprecated since Python 2.3. Use `mkstemp()` or `NamedTemporaryFile(delete=False)` instead.") +def mktemp(suffix: str = "", prefix: str = "tmp", dir: StrPath | None = None) -> str: ... def gettempdirb() -> bytes: ... def gettempprefixb() -> bytes: ... def gettempdir() -> str: ... diff --git a/stdlib/termios.pyi b/stdlib/termios.pyi index ed8522dccc51..5d9c81ed5488 100644 --- a/stdlib/termios.pyi +++ b/stdlib/termios.pyi @@ -1,246 +1,306 @@ +import sys from _typeshed import FileDescriptorLike -from typing import Any, List, Union +from typing import Any, Final, TypeAlias -_Attr = List[Union[int, List[Union[bytes, int]]]] +# Must be a list of length 7, containing 6 ints and a list of NCCS 1-character bytes or ints. +_Attr: TypeAlias = list[int | list[bytes | int]] | list[int | list[bytes]] | list[int | list[int]] +# Same as _Attr for return types; we use Any to avoid a union. +_AttrReturn: TypeAlias = list[Any] -# TODO constants not really documented -B0: int -B1000000: int -B110: int -B115200: int -B1152000: int -B1200: int -B134: int -B150: int -B1500000: int -B1800: int -B19200: int -B200: int -B2000000: int -B230400: int -B2400: int -B2500000: int -B300: int -B3000000: int -B3500000: int -B38400: int -B4000000: int -B460800: int -B4800: int -B50: int -B500000: int -B57600: int -B576000: int -B600: int -B75: int -B921600: int -B9600: int -BRKINT: int -BS0: int -BS1: int -BSDLY: int -CBAUD: int -CBAUDEX: int -CDSUSP: int -CEOF: int -CEOL: int -CEOT: int -CERASE: int -CFLUSH: int -CIBAUD: int -CINTR: int -CKILL: int -CLNEXT: int -CLOCAL: int -CQUIT: int -CR0: int -CR1: int -CR2: int -CR3: int -CRDLY: int -CREAD: int -CRPRNT: int -CRTSCTS: int -CS5: int -CS6: int -CS7: int -CS8: int -CSIZE: int -CSTART: int -CSTOP: int -CSTOPB: int -CSUSP: int -CWERASE: int -ECHO: int -ECHOCTL: int -ECHOE: int -ECHOK: int -ECHOKE: int -ECHONL: int -ECHOPRT: int -EXTA: int -EXTB: int -FF0: int -FF1: int -FFDLY: int -FIOASYNC: int -FIOCLEX: int -FIONBIO: int -FIONCLEX: int -FIONREAD: int -FLUSHO: int -HUPCL: int -ICANON: int -ICRNL: int -IEXTEN: int -IGNBRK: int -IGNCR: int -IGNPAR: int -IMAXBEL: int -INLCR: int -INPCK: int -IOCSIZE_MASK: int -IOCSIZE_SHIFT: int -ISIG: int -ISTRIP: int -IUCLC: int -IXANY: int -IXOFF: int -IXON: int -NCC: int -NCCS: int -NL0: int -NL1: int -NLDLY: int -NOFLSH: int -N_MOUSE: int -N_PPP: int -N_SLIP: int -N_STRIP: int -N_TTY: int -OCRNL: int -OFDEL: int -OFILL: int -OLCUC: int -ONLCR: int -ONLRET: int -ONOCR: int -OPOST: int -PARENB: int -PARMRK: int -PARODD: int -PENDIN: int -TAB0: int -TAB1: int -TAB2: int -TAB3: int -TABDLY: int -TCFLSH: int -TCGETA: int -TCGETS: int -TCIFLUSH: int -TCIOFF: int -TCIOFLUSH: int -TCION: int -TCOFLUSH: int -TCOOFF: int -TCOON: int -TCSADRAIN: int -TCSAFLUSH: int -TCSANOW: int -TCSBRK: int -TCSBRKP: int -TCSETA: int -TCSETAF: int -TCSETAW: int -TCSETS: int -TCSETSF: int -TCSETSW: int -TCXONC: int -TIOCCONS: int -TIOCEXCL: int -TIOCGETD: int -TIOCGICOUNT: int -TIOCGLCKTRMIOS: int -TIOCGPGRP: int -TIOCGSERIAL: int -TIOCGSOFTCAR: int -TIOCGWINSZ: int -TIOCINQ: int -TIOCLINUX: int -TIOCMBIC: int -TIOCMBIS: int -TIOCMGET: int -TIOCMIWAIT: int -TIOCMSET: int -TIOCM_CAR: int -TIOCM_CD: int -TIOCM_CTS: int -TIOCM_DSR: int -TIOCM_DTR: int -TIOCM_LE: int -TIOCM_RI: int -TIOCM_RNG: int -TIOCM_RTS: int -TIOCM_SR: int -TIOCM_ST: int -TIOCNOTTY: int -TIOCNXCL: int -TIOCOUTQ: int -TIOCPKT: int -TIOCPKT_DATA: int -TIOCPKT_DOSTOP: int -TIOCPKT_FLUSHREAD: int -TIOCPKT_FLUSHWRITE: int -TIOCPKT_NOSTOP: int -TIOCPKT_START: int -TIOCPKT_STOP: int -TIOCSCTTY: int -TIOCSERCONFIG: int -TIOCSERGETLSR: int -TIOCSERGETMULTI: int -TIOCSERGSTRUCT: int -TIOCSERGWILD: int -TIOCSERSETMULTI: int -TIOCSERSWILD: int -TIOCSER_TEMT: int -TIOCSETD: int -TIOCSLCKTRMIOS: int -TIOCSPGRP: int -TIOCSSERIAL: int -TIOCSSOFTCAR: int -TIOCSTI: int -TIOCSWINSZ: int -TOSTOP: int -VDISCARD: int -VEOF: int -VEOL: int -VEOL2: int -VERASE: int -VINTR: int -VKILL: int -VLNEXT: int -VMIN: int -VQUIT: int -VREPRINT: int -VSTART: int -VSTOP: int -VSUSP: int -VSWTC: int -VSWTCH: int -VT0: int -VT1: int -VTDLY: int -VTIME: int -VWERASE: int -XCASE: int -XTABS: int +if sys.platform != "win32": + # Values depends on the platform + B0: Final[int] + B110: Final[int] + B115200: Final[int] + B1200: Final[int] + B134: Final[int] + B150: Final[int] + B1800: Final[int] + B19200: Final[int] + B200: Final[int] + B230400: Final[int] + B2400: Final[int] + B300: Final[int] + B38400: Final[int] + B4800: Final[int] + B50: Final[int] + B57600: Final[int] + B600: Final[int] + B75: Final[int] + B9600: Final[int] + BRKINT: Final[int] + BS0: Final[int] + BS1: Final[int] + BSDLY: Final[int] + CDSUSP: Final[int] + CEOF: Final[int] + CEOL: Final[int] + CEOT: Final[int] + CERASE: Final[int] + CFLUSH: Final[int] + CINTR: Final[int] + CKILL: Final[int] + CLNEXT: Final[int] + CLOCAL: Final[int] + CQUIT: Final[int] + CR0: Final[int] + CR1: Final[int] + CR2: Final[int] + CR3: Final[int] + CRDLY: Final[int] + CREAD: Final[int] + CRPRNT: Final[int] + CRTSCTS: Final[int] + CS5: Final[int] + CS6: Final[int] + CS7: Final[int] + CS8: Final[int] + CSIZE: Final[int] + CSTART: Final[int] + CSTOP: Final[int] + CSTOPB: Final[int] + CSUSP: Final[int] + CWERASE: Final[int] + ECHO: Final[int] + ECHOCTL: Final[int] + ECHOE: Final[int] + ECHOK: Final[int] + ECHOKE: Final[int] + ECHONL: Final[int] + ECHOPRT: Final[int] + EXTA: Final[int] + EXTB: Final[int] + FF0: Final[int] + FF1: Final[int] + FFDLY: Final[int] + FIOASYNC: Final[int] + FIOCLEX: Final[int] + FIONBIO: Final[int] + FIONCLEX: Final[int] + FIONREAD: Final[int] + FLUSHO: Final[int] + HUPCL: Final[int] + ICANON: Final[int] + ICRNL: Final[int] + IEXTEN: Final[int] + IGNBRK: Final[int] + IGNCR: Final[int] + IGNPAR: Final[int] + IMAXBEL: Final[int] + INLCR: Final[int] + INPCK: Final[int] + ISIG: Final[int] + ISTRIP: Final[int] + IXANY: Final[int] + IXOFF: Final[int] + IXON: Final[int] + NCCS: Final[int] + NL0: Final[int] + NL1: Final[int] + NLDLY: Final[int] + NOFLSH: Final[int] + OCRNL: Final[int] + OFDEL: Final[int] + OFILL: Final[int] + ONLCR: Final[int] + ONLRET: Final[int] + ONOCR: Final[int] + OPOST: Final[int] + PARENB: Final[int] + PARMRK: Final[int] + PARODD: Final[int] + PENDIN: Final[int] + TAB0: Final[int] + TAB1: Final[int] + TAB2: Final[int] + TAB3: Final[int] + TABDLY: Final[int] + TCIFLUSH: Final[int] + TCIOFF: Final[int] + TCIOFLUSH: Final[int] + TCION: Final[int] + TCOFLUSH: Final[int] + TCOOFF: Final[int] + TCOON: Final[int] + TCSADRAIN: Final[int] + TCSAFLUSH: Final[int] + TCSANOW: Final[int] + TIOCCONS: Final[int] + TIOCEXCL: Final[int] + TIOCGETD: Final[int] + TIOCGPGRP: Final[int] + TIOCGWINSZ: Final[int] + TIOCM_CAR: Final[int] + TIOCM_CD: Final[int] + TIOCM_CTS: Final[int] + TIOCM_DSR: Final[int] + TIOCM_DTR: Final[int] + TIOCM_LE: Final[int] + TIOCM_RI: Final[int] + TIOCM_RNG: Final[int] + TIOCM_RTS: Final[int] + TIOCM_SR: Final[int] + TIOCM_ST: Final[int] + TIOCMBIC: Final[int] + TIOCMBIS: Final[int] + TIOCMGET: Final[int] + TIOCMSET: Final[int] + TIOCNOTTY: Final[int] + TIOCNXCL: Final[int] + TIOCOUTQ: Final[int] + TIOCPKT_DATA: Final[int] + TIOCPKT_DOSTOP: Final[int] + TIOCPKT_FLUSHREAD: Final[int] + TIOCPKT_FLUSHWRITE: Final[int] + TIOCPKT_NOSTOP: Final[int] + TIOCPKT_START: Final[int] + TIOCPKT_STOP: Final[int] + TIOCPKT: Final[int] + TIOCSCTTY: Final[int] + TIOCSETD: Final[int] + TIOCSPGRP: Final[int] + TIOCSTI: Final[int] + TIOCSWINSZ: Final[int] + TOSTOP: Final[int] + VDISCARD: Final[int] + VEOF: Final[int] + VEOL: Final[int] + VEOL2: Final[int] + VERASE: Final[int] + VINTR: Final[int] + VKILL: Final[int] + VLNEXT: Final[int] + VMIN: Final[int] + VQUIT: Final[int] + VREPRINT: Final[int] + VSTART: Final[int] + VSTOP: Final[int] + VSUSP: Final[int] + VT0: Final[int] + VT1: Final[int] + VTDLY: Final[int] + VTIME: Final[int] + VWERASE: Final[int] -def tcgetattr(__fd: FileDescriptorLike) -> list[Any]: ... -def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... -def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... -def tcdrain(__fd: FileDescriptorLike) -> None: ... -def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... -def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + if sys.version_info >= (3, 13): + EXTPROC: Final[int] + IUTF8: Final[int] -class error(Exception): ... + # On Linux, only available when Python was built against glibc 2.42 or newer. + B14400: Final[int] + B28800: Final[int] + B7200: Final[int] + B76800: Final[int] + + if sys.platform == "darwin" and sys.version_info >= (3, 13): + ALTWERASE: Final[int] + CCAR_OFLOW: Final[int] + CCTS_OFLOW: Final[int] + CDSR_OFLOW: Final[int] + CDTR_IFLOW: Final[int] + CIGNORE: Final[int] + CRTS_IFLOW: Final[int] + MDMBUF: Final[int] + NL2: Final[int] + NL3: Final[int] + NOKERNINFO: Final[int] + ONOEOT: Final[int] + OXTABS: Final[int] + VDSUSP: Final[int] + VSTATUS: Final[int] + + if sys.platform == "darwin" and sys.version_info >= (3, 11): + TIOCGSIZE: Final[int] + TIOCSSIZE: Final[int] + + if sys.platform == "linux": + B1152000: Final[int] + B576000: Final[int] + CBAUD: Final[int] + CBAUDEX: Final[int] + CIBAUD: Final[int] + IOCSIZE_MASK: Final[int] + IOCSIZE_SHIFT: Final[int] + IUCLC: Final[int] + N_MOUSE: Final[int] + N_PPP: Final[int] + N_SLIP: Final[int] + N_STRIP: Final[int] + N_TTY: Final[int] + NCC: Final[int] + OLCUC: Final[int] + TCFLSH: Final[int] + TCGETA: Final[int] + TCGETS: Final[int] + TCSBRK: Final[int] + TCSBRKP: Final[int] + TCSETA: Final[int] + TCSETAF: Final[int] + TCSETAW: Final[int] + TCSETS: Final[int] + TCSETSF: Final[int] + TCSETSW: Final[int] + TCXONC: Final[int] + TIOCGICOUNT: Final[int] + TIOCGLCKTRMIOS: Final[int] + TIOCGSERIAL: Final[int] + TIOCGSOFTCAR: Final[int] + TIOCINQ: Final[int] + TIOCLINUX: Final[int] + TIOCMIWAIT: Final[int] + TIOCTTYGSTRUCT: Final[int] + TIOCSER_TEMT: Final[int] + TIOCSERCONFIG: Final[int] + TIOCSERGETLSR: Final[int] + TIOCSERGETMULTI: Final[int] + TIOCSERGSTRUCT: Final[int] + TIOCSERGWILD: Final[int] + TIOCSERSETMULTI: Final[int] + TIOCSERSWILD: Final[int] + TIOCSLCKTRMIOS: Final[int] + TIOCSSERIAL: Final[int] + TIOCSSOFTCAR: Final[int] + VSWTC: Final[int] + VSWTCH: Final[int] + XCASE: Final[int] + XTABS: Final[int] + + if sys.platform != "darwin": + B1000000: Final[int] + B1500000: Final[int] + B2000000: Final[int] + B2500000: Final[int] + B3000000: Final[int] + B3500000: Final[int] + B4000000: Final[int] + B460800: Final[int] + B500000: Final[int] + B921600: Final[int] + # On Linux, only available when Python was built against glibc 2.42 or newer. + IBSHIFT: Final[int] + + if sys.platform != "linux": + TCSASOFT: Final[int] + + if sys.platform != "darwin" and sys.platform != "linux": + # not available on FreeBSD either. + CDEL: Final[int] + CEOL2: Final[int] + CESC: Final[int] + CNUL: Final[int] + COMMON: Final[int] + CSWTCH: Final[int] + INIT_C_CC: Final[int] + NSWTCH: Final[int] + + def tcgetattr(fd: FileDescriptorLike, /) -> _AttrReturn: ... + def tcsetattr(fd: FileDescriptorLike, when: int, attributes: _Attr, /) -> None: ... + def tcsendbreak(fd: FileDescriptorLike, duration: int, /) -> None: ... + def tcdrain(fd: FileDescriptorLike, /) -> None: ... + def tcflush(fd: FileDescriptorLike, queue: int, /) -> None: ... + def tcflow(fd: FileDescriptorLike, action: int, /) -> None: ... + if sys.version_info >= (3, 11): + def tcgetwinsize(fd: FileDescriptorLike, /) -> tuple[int, int]: ... + def tcsetwinsize(fd: FileDescriptorLike, winsize: tuple[int, int], /) -> None: ... + + class error(Exception): ... diff --git a/stdlib/textwrap.pyi b/stdlib/textwrap.pyi index 3b8fd5c0349a..c00cce3c2d57 100644 --- a/stdlib/textwrap.pyi +++ b/stdlib/textwrap.pyi @@ -1,4 +1,7 @@ -from typing import Callable, Pattern +from collections.abc import Callable +from re import Pattern + +__all__ = ["TextWrapper", "wrap", "fill", "dedent", "indent", "shorten"] class TextWrapper: width: int @@ -24,19 +27,19 @@ class TextWrapper: x: str # leaked loop variable def __init__( self, - width: int = ..., - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ..., - tabsize: int = ..., + width: int = 70, + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + drop_whitespace: bool = True, + break_on_hyphens: bool = True, + tabsize: int = 8, *, - max_lines: int | None = ..., - placeholder: str = ..., + max_lines: int | None = None, + placeholder: str = " [...]", ) -> None: ... # Private methods *are* part of the documented API for subclasses. def _munge_whitespace(self, text: str) -> str: ... @@ -50,51 +53,51 @@ class TextWrapper: def wrap( text: str, - width: int = ..., + width: int = 70, *, - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - tabsize: int = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - break_on_hyphens: bool = ..., - drop_whitespace: bool = ..., - max_lines: int = ..., - placeholder: str = ..., + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + tabsize: int = 8, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, + max_lines: int | None = None, + placeholder: str = " [...]", ) -> list[str]: ... def fill( text: str, - width: int = ..., + width: int = 70, *, - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - tabsize: int = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - break_on_hyphens: bool = ..., - drop_whitespace: bool = ..., - max_lines: int = ..., - placeholder: str = ..., + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + tabsize: int = 8, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, + max_lines: int | None = None, + placeholder: str = " [...]", ) -> str: ... def shorten( text: str, width: int, *, - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - tabsize: int = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - break_on_hyphens: bool = ..., - drop_whitespace: bool = ..., + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + tabsize: int = 8, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, # Omit `max_lines: int = None`, it is forced to 1 here. - placeholder: str = ..., + placeholder: str = " [...]", ) -> str: ... def dedent(text: str) -> str: ... -def indent(text: str, prefix: str, predicate: Callable[[str], bool] | None = ...) -> str: ... +def indent(text: str, prefix: str, predicate: Callable[[str], bool] | None = None) -> str: ... diff --git a/stdlib/threading.pyi b/stdlib/threading.pyi index d6ac9f7251c2..6b51b424cee6 100644 --- a/stdlib/threading.pyi +++ b/stdlib/threading.pyi @@ -1,155 +1,220 @@ +import _thread import sys -from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from _thread import _ExceptHookArgs, get_native_id as get_native_id +from _typeshed import ProfileFunction, TraceFunction +from collections.abc import Callable, Iterable, Iterator, Mapping +from contextvars import Context +from types import TracebackType +from typing import Any, Final, TypeVar, final +from typing_extensions import Self, deprecated -# TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] - -_PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") -__all__: list[str] +__all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "ExceptHookArgs", + "getprofile", + "gettrace", + "setprofile", + "settrace", + "local", + "stack_size", + "excepthook", + "get_native_id", +] + +if sys.version_info >= (3, 12): + __all__ += ["setprofile_all_threads", "settrace_all_threads"] + +if sys.version_info >= (3, 15): + __all__ += ["concurrent_tee", "serialize_iterator", "synchronized_iterator"] + +_profile_hook: ProfileFunction | None def active_count() -> int: ... -def activeCount() -> int: ... # deprecated alias for active_count() +@deprecated("Deprecated since Python 3.10. Use `active_count()` instead.") +def activeCount() -> int: ... def current_thread() -> Thread: ... -def currentThread() -> Thread: ... # deprecated alias for current_thread() +@deprecated("Deprecated since Python 3.10. Use `current_thread()` instead.") +def currentThread() -> Thread: ... def get_ident() -> int: ... def enumerate() -> list[Thread]: ... def main_thread() -> Thread: ... +def settrace(func: TraceFunction | None) -> None: ... +def setprofile(func: ProfileFunction | None) -> None: ... -if sys.version_info >= (3, 8): - from _thread import get_native_id as get_native_id +if sys.version_info >= (3, 12): + def setprofile_all_threads(func: ProfileFunction | None) -> None: ... + def settrace_all_threads(func: TraceFunction | None) -> None: ... -def settrace(func: _TF) -> None: ... -def setprofile(func: _PF | None) -> None: ... +def gettrace() -> TraceFunction | None: ... +def getprofile() -> ProfileFunction | None: ... -if sys.version_info >= (3, 10): - def gettrace() -> _TF | None: ... - def getprofile() -> _PF | None: ... +if sys.version_info >= (3, 15): + @final + class serialize_iterator(Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + def send(self, value: Any, /) -> _T: ... + def throw(self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ...) -> _T: ... + def close(self) -> None: ... -def stack_size(size: int = ...) -> int: ... + def synchronized_iterator(func: Callable[..., Iterable[_T]]) -> Callable[..., Iterator[_T]]: ... + def concurrent_tee(iterable: Iterable[_T], n: int = 2) -> tuple[Iterator[_T], ...]: ... -TIMEOUT_MAX: float +def stack_size(size: int = 0, /) -> int: ... -class ThreadError(Exception): ... +TIMEOUT_MAX: Final[float] -class local(object): - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... +ThreadError = _thread.error +local = _thread._local class Thread: name: str - ident: int | None + @property + def ident(self) -> int | None: ... daemon: bool - def __init__( - self, - group: None = ..., - target: Callable[..., Any] | None = ..., - name: str | None = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] | None = ..., - *, - daemon: bool | None = ..., - ) -> None: ... + if sys.version_info >= (3, 14): + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + *, + daemon: bool | None = None, + context: Context | None = None, + ) -> None: ... + else: + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + *, + daemon: bool | None = None, + ) -> None: ... + def start(self) -> None: ... def run(self) -> None: ... - def join(self, timeout: float | None = ...) -> None: ... - if sys.version_info >= (3, 8): - @property - def native_id(self) -> int | None: ... # only available on some platforms + def join(self, timeout: float | None = None) -> None: ... + @property + def native_id(self) -> int | None: ... # only available on some platforms def is_alive(self) -> bool: ... - if sys.version_info < (3, 9): - def isAlive(self) -> bool: ... - # the following methods are all deprecated - def getName(self) -> str: ... - def setName(self, name: str) -> None: ... + @deprecated("Deprecated since Python 3.10. Read the `daemon` attribute instead.") def isDaemon(self) -> bool: ... + @deprecated("Deprecated since Python 3.10. Set the `daemon` attribute instead.") def setDaemon(self, daemonic: bool) -> None: ... + @deprecated("Deprecated since Python 3.10. Read the `name` attribute instead.") + def getName(self) -> str: ... + @deprecated("Deprecated since Python 3.10. Set the `name` attribute instead.") + def setName(self, name: str) -> None: ... class _DummyThread(Thread): def __init__(self) -> None: ... -class Lock: - def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - def release(self) -> None: ... - def locked(self) -> bool: ... +# This is actually the function _thread.allocate_lock for <= 3.12 +Lock = _thread.LockType +# Python implementation of RLock. +@final class _RLock: - def __init__(self) -> None: ... - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + _count: int + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... def release(self) -> None: ... __enter__ = acquire - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... -RLock = _RLock +RLock = _thread.RLock # Actually a function at runtime. class Condition: - def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... + def __init__(self, lock: Lock | _RLock | RLock | None = None) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... def release(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - def wait_for(self, predicate: Callable[[], _T], timeout: float | None = ...) -> _T: ... - def notify(self, n: int = ...) -> None: ... + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... + + def wait(self, timeout: float | None = None) -> bool: ... + def wait_for(self, predicate: Callable[[], _T], timeout: float | None = None) -> _T: ... + def notify(self, n: int = 1) -> None: ... def notify_all(self) -> None: ... - def notifyAll(self) -> None: ... # deprecated alias for notify_all() + @deprecated("Deprecated since Python 3.10. Use `notify_all()` instead.") + def notifyAll(self) -> None: ... class Semaphore: - def __init__(self, value: int = ...) -> None: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... - def __enter__(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... - if sys.version_info >= (3, 9): - def release(self, n: int = ...) -> None: ... - else: - def release(self) -> None: ... + _value: int + def __init__(self, value: int = 1) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def __enter__(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def release(self, n: int = 1) -> None: ... class BoundedSemaphore(Semaphore): ... class Event: - def __init__(self) -> None: ... def is_set(self) -> bool: ... - def isSet(self) -> bool: ... # deprecated alias for is_set() + @deprecated("Deprecated since Python 3.10. Use `is_set()` instead.") + def isSet(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... - def wait(self, timeout: float | None = ...) -> bool: ... - -if sys.version_info >= (3, 8): - from _thread import _excepthook, _ExceptHookArgs + def wait(self, timeout: float | None = None) -> bool: ... - excepthook = _excepthook - ExceptHookArgs = _ExceptHookArgs +excepthook: Callable[[_ExceptHookArgs], object] +__excepthook__: Callable[[_ExceptHookArgs], object] +ExceptHookArgs = _ExceptHookArgs class Timer(Thread): + args: Iterable[Any] # undocumented + finished: Event # undocumented + function: Callable[..., Any] # undocumented + interval: float # undocumented + kwargs: Mapping[str, Any] # undocumented + def __init__( self, interval: float, - function: Callable[..., Any], - args: Iterable[Any] | None = ..., - kwargs: Mapping[str, Any] | None = ..., + function: Callable[..., object], + args: Iterable[Any] | None = None, + kwargs: Mapping[str, Any] | None = None, ) -> None: ... def cancel(self) -> None: ... class Barrier: - parties: int - n_waiting: int - broken: bool - def __init__(self, parties: int, action: Callable[[], None] | None = ..., timeout: float | None = ...) -> None: ... - def wait(self, timeout: float | None = ...) -> int: ... + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... + def __init__(self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None) -> None: ... + def wait(self, timeout: float | None = None) -> int: ... def reset(self) -> None: ... def abort(self) -> None: ... diff --git a/stdlib/time.pyi b/stdlib/time.pyi index fc929b112185..ac53089b8d82 100644 --- a/stdlib/time.pyi +++ b/stdlib/time.pyi @@ -1,44 +1,53 @@ import sys from _typeshed import structseq -from types import SimpleNamespace -from typing import Any, Tuple, Union -from typing_extensions import final +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, final, type_check_only -_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] +_TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int] + +if sys.version_info >= (3, 15): + # anticipate on https://github.com/python/cpython/pull/139224 + _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex +else: + # before, time functions only accept (subclass of) float, *not* SupportsFloat + _SupportsFloatOrIndex: TypeAlias = float | SupportsIndex altzone: int daylight: int timezone: int tzname: tuple[str, str] -if sys.version_info >= (3, 7): - if sys.platform == "linux": - CLOCK_BOOTTIME: int - if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": - CLOCK_PROF: int # FreeBSD, NetBSD, OpenBSD - CLOCK_UPTIME: int # FreeBSD, OpenBSD +if sys.platform == "linux": + CLOCK_BOOTTIME: Final[int] +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + CLOCK_PROF: Final[int] # FreeBSD, NetBSD, OpenBSD + CLOCK_UPTIME: Final[int] # FreeBSD, OpenBSD if sys.platform != "win32": - CLOCK_MONOTONIC: int - CLOCK_MONOTONIC_RAW: int - CLOCK_PROCESS_CPUTIME_ID: int - CLOCK_REALTIME: int - CLOCK_THREAD_CPUTIME_ID: int + CLOCK_MONOTONIC: Final[int] + CLOCK_MONOTONIC_RAW: Final[int] + CLOCK_PROCESS_CPUTIME_ID: Final[int] + CLOCK_REALTIME: Final[int] + CLOCK_THREAD_CPUTIME_ID: Final[int] if sys.platform != "linux" and sys.platform != "darwin": - CLOCK_HIGHRES: int # Solaris only + CLOCK_HIGHRES: Final[int] # Solaris only -if sys.version_info >= (3, 8) and sys.platform == "darwin": - CLOCK_UPTIME_RAW: int +if sys.platform == "darwin": + CLOCK_UPTIME_RAW: Final[int] + if sys.version_info >= (3, 13): + CLOCK_UPTIME_RAW_APPROX: Final[int] + CLOCK_MONOTONIC_RAW_APPROX: Final[int] -if sys.version_info >= (3, 9) and sys.platform == "linux": - CLOCK_TAI: int +if sys.platform == "linux": + CLOCK_TAI: Final[int] # Constructor takes an iterable of any type, of length between 9 and 11 elements. # However, it always *behaves* like a tuple of 9 elements, # even if an iterable with length >9 is passed. # https://github.com/python/typeshed/pull/6560#discussion_r767162532 @final -class struct_time(structseq[Union[Any, int]], _TimeTuple): +class struct_time(structseq[Any | int], _TimeTuple): + __match_args__: Final = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst") + @property def tm_year(self) -> int: ... @property @@ -63,40 +72,46 @@ class struct_time(structseq[Union[Any, int]], _TimeTuple): @property def tm_gmtoff(self) -> int: ... -def asctime(t: _TimeTuple | struct_time = ...) -> str: ... - -if sys.version_info < (3, 8): - def clock() -> float: ... - -def ctime(secs: float | None = ...) -> str: ... -def gmtime(secs: float | None = ...) -> struct_time: ... -def localtime(secs: float | None = ...) -> struct_time: ... -def mktime(t: _TimeTuple | struct_time) -> float: ... -def sleep(secs: float) -> None: ... -def strftime(format: str, t: _TimeTuple | struct_time = ...) -> str: ... -def strptime(string: str, format: str = ...) -> struct_time: ... +def asctime(time_tuple: _TimeTuple | struct_time = ..., /) -> str: ... +def ctime(seconds: _SupportsFloatOrIndex | None = None, /) -> str: ... +def gmtime(seconds: _SupportsFloatOrIndex | None = None, /) -> struct_time: ... +def localtime(seconds: _SupportsFloatOrIndex | None = None, /) -> struct_time: ... +def mktime(time_tuple: _TimeTuple | struct_time, /) -> float: ... +def sleep(seconds: _SupportsFloatOrIndex, /) -> None: ... +def strftime(format: str, time_tuple: _TimeTuple | struct_time = ..., /) -> str: ... +def strptime(data_string: str, format: str = "%a %b %d %H:%M:%S %Y", /) -> struct_time: ... def time() -> float: ... if sys.platform != "win32": def tzset() -> None: ... # Unix only -def get_clock_info(name: str) -> SimpleNamespace: ... +@type_check_only +class _ClockInfo(Protocol): + adjustable: bool + implementation: str + monotonic: bool + resolution: float + +def get_clock_info(name: Literal["monotonic", "perf_counter", "process_time", "time", "thread_time"], /) -> _ClockInfo: ... def monotonic() -> float: ... def perf_counter() -> float: ... def process_time() -> float: ... if sys.platform != "win32": - def clock_getres(clk_id: int) -> float: ... # Unix only - def clock_gettime(clk_id: int) -> float: ... # Unix only - def clock_settime(clk_id: int, time: float) -> None: ... # Unix only - -if sys.version_info >= (3, 7): - if sys.platform != "win32": - def clock_gettime_ns(clock_id: int) -> int: ... - def clock_settime_ns(clock_id: int, time: int) -> int: ... - def monotonic_ns() -> int: ... - def perf_counter_ns() -> int: ... - def process_time_ns() -> int: ... - def time_ns() -> int: ... - def thread_time() -> float: ... - def thread_time_ns() -> int: ... + def clock_getres(clk_id: int, /) -> float: ... # Unix only + def clock_gettime(clk_id: int, /) -> float: ... # Unix only + def clock_settime(clk_id: int, time: float, /) -> None: ... # Unix only + +if sys.platform != "win32": + def clock_gettime_ns(clk_id: int, /) -> int: ... + def clock_settime_ns(clock_id: int, time: int, /) -> int: ... + +if sys.platform == "linux": + def pthread_getcpuclockid(thread_id: int, /) -> int: ... + +def monotonic_ns() -> int: ... +def perf_counter_ns() -> int: ... +def process_time_ns() -> int: ... +def time_ns() -> int: ... +def thread_time() -> float: ... +def thread_time_ns() -> int: ... diff --git a/stdlib/timeit.pyi b/stdlib/timeit.pyi index d82dd80598dc..cc2b2027a820 100644 --- a/stdlib/timeit.pyi +++ b/stdlib/timeit.pyi @@ -1,31 +1,46 @@ -from typing import IO, Any, Callable, Sequence, Union +import sys +import time +from collections.abc import Callable, Sequence +from typing import IO, Any, TypeAlias -_Timer = Callable[[], float] -_Stmt = Union[str, Callable[[], Any]] +__all__ = ["Timer", "timeit", "repeat", "default_timer"] + +_Timer: TypeAlias = Callable[[], float] +_Stmt: TypeAlias = str | Callable[[], object] default_timer: _Timer class Timer: def __init__( - self, stmt: _Stmt = ..., setup: _Stmt = ..., timer: _Timer = ..., globals: dict[str, Any] | None = ... + self, + stmt: _Stmt = "pass", + setup: _Stmt = "pass", + timer: _Timer = time.perf_counter, + globals: dict[str, Any] | None = None, ) -> None: ... - def print_exc(self, file: IO[str] | None = ...) -> None: ... - def timeit(self, number: int = ...) -> float: ... - def repeat(self, repeat: int = ..., number: int = ...) -> list[float]: ... - def autorange(self, callback: Callable[[int, float], Any] | None = ...) -> tuple[int, float]: ... + def print_exc(self, file: IO[str] | None = None) -> None: ... + def timeit(self, number: int = 1000000) -> float: ... + def repeat(self, repeat: int = 5, number: int = 1000000) -> list[float]: ... + if sys.version_info >= (3, 15): + def autorange( + self, callback: Callable[[int, float], object] | None = None, target_time: float = 0.2 + ) -> tuple[int, float]: ... + else: + def autorange(self, callback: Callable[[int, float], object] | None = None) -> tuple[int, float]: ... def timeit( - stmt: _Stmt = ..., setup: _Stmt = ..., timer: _Timer = ..., number: int = ..., globals: dict[str, Any] | None = ... + stmt: _Stmt = "pass", + setup: _Stmt = "pass", + timer: _Timer = time.perf_counter, + number: int = 1000000, + globals: dict[str, Any] | None = None, ) -> float: ... def repeat( - stmt: _Stmt = ..., - setup: _Stmt = ..., - timer: _Timer = ..., - repeat: int = ..., - number: int = ..., - globals: dict[str, Any] | None = ..., + stmt: _Stmt = "pass", + setup: _Stmt = "pass", + timer: _Timer = time.perf_counter, + repeat: int = 5, + number: int = 1000000, + globals: dict[str, Any] | None = None, ) -> list[float]: ... - -_timerFunc = Callable[[], float] - -def main(args: Sequence[str] | None = ..., *, _wrap_timer: Callable[[_timerFunc], _timerFunc] | None = ...) -> None: ... +def main(args: Sequence[str] | None = None, *, _wrap_timer: Callable[[_Timer], _Timer] | None = None) -> None: ... diff --git a/stdlib/tkinter/__init__.pyi b/stdlib/tkinter/__init__.pyi index a32fe5554157..59cbc4401e51 100644 --- a/stdlib/tkinter/__init__.pyi +++ b/stdlib/tkinter/__init__.pyi @@ -1,12 +1,165 @@ import _tkinter import sys -from _typeshed import StrOrBytesPath -from enum import Enum +from _typeshed import FileDescriptorLike, Incomplete, MaybeNone, StrOrBytesPath +from collections.abc import Callable, Iterable, Mapping, Sequence from tkinter.constants import * from tkinter.font import _FontDescription -from types import TracebackType -from typing import Any, Callable, Generic, List, Mapping, Optional, Protocol, Sequence, Tuple, Type, TypeVar, Union, overload -from typing_extensions import Literal, TypedDict +from types import GenericAlias, TracebackType +from typing import ( + Any, + ClassVar, + Final, + Generic, + Literal, + NamedTuple, + ParamSpec, + Protocol, + TypeAlias, + TypedDict, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import TypeVarTuple, Unpack, deprecated, disjoint_base + +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + from enum import Enum + +__all__ = [ + "TclError", + "NO", + "FALSE", + "OFF", + "YES", + "TRUE", + "ON", + "N", + "S", + "W", + "E", + "NW", + "SW", + "NE", + "SE", + "NS", + "EW", + "NSEW", + "CENTER", + "NONE", + "X", + "Y", + "BOTH", + "LEFT", + "TOP", + "RIGHT", + "BOTTOM", + "RAISED", + "SUNKEN", + "FLAT", + "RIDGE", + "GROOVE", + "SOLID", + "HORIZONTAL", + "VERTICAL", + "NUMERIC", + "CHAR", + "WORD", + "BASELINE", + "INSIDE", + "OUTSIDE", + "SEL", + "SEL_FIRST", + "SEL_LAST", + "END", + "INSERT", + "CURRENT", + "ANCHOR", + "ALL", + "NORMAL", + "DISABLED", + "ACTIVE", + "HIDDEN", + "CASCADE", + "CHECKBUTTON", + "COMMAND", + "RADIOBUTTON", + "SEPARATOR", + "SINGLE", + "BROWSE", + "MULTIPLE", + "EXTENDED", + "DOTBOX", + "UNDERLINE", + "PIESLICE", + "CHORD", + "ARC", + "FIRST", + "LAST", + "BUTT", + "PROJECTING", + "ROUND", + "BEVEL", + "MITER", + "MOVETO", + "SCROLL", + "UNITS", + "PAGES", + "TkVersion", + "TclVersion", + "READABLE", + "WRITABLE", + "EXCEPTION", + "EventType", + "Event", + "NoDefaultRoot", + "Variable", + "StringVar", + "IntVar", + "DoubleVar", + "BooleanVar", + "mainloop", + "getint", + "getdouble", + "getboolean", + "Misc", + "CallWrapper", + "XView", + "YView", + "Wm", + "Tk", + "Tcl", + "Pack", + "Place", + "Grid", + "BaseWidget", + "Widget", + "Toplevel", + "Button", + "Canvas", + "Checkbutton", + "Entry", + "Frame", + "Label", + "Listbox", + "Menu", + "Menubutton", + "Message", + "Radiobutton", + "Scale", + "Scrollbar", + "Text", + "OptionMenu", + "Image", + "PhotoImage", + "BitmapImage", + "image_names", + "image_types", + "Spinbox", + "LabelFrame", + "PanedWindow", +] # Using anything from tkinter.font in this file means that 'import tkinter' # seems to also load tkinter.font. That's not how it actually works, but @@ -14,11 +167,11 @@ from typing_extensions import Literal, TypedDict TclError = _tkinter.TclError wantobjects: int -TkVersion: float -TclVersion: float -READABLE = _tkinter.READABLE -WRITABLE = _tkinter.WRITABLE -EXCEPTION = _tkinter.EXCEPTION +TkVersion: Final[float] +TclVersion: Final[float] +READABLE: Final = _tkinter.READABLE +WRITABLE: Final = _tkinter.WRITABLE +EXCEPTION: Final = _tkinter.EXCEPTION # Quick guide for figuring out which widget class to choose: # - Misc: any widget (don't use BaseWidget because Tk doesn't inherit from BaseWidget) @@ -34,76 +187,111 @@ EXCEPTION = _tkinter.EXCEPTION # # You can also read the manual pages online: https://www.tcl.tk/doc/ -# Some widgets have an option named -compound that accepts different values -# than the _Compound defined here. Many other options have similar things. -_Anchor = Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] # manual page: Tk_GetAnchor -_Bitmap = str # manual page: Tk_GetBitmap -_ButtonCommand = Union[str, Callable[[], Any]] # accepts string of tcl code, return value is returned from Button.invoke() -_CanvasItemId = int -_Color = str # typically '#rrggbb', '#rgb' or color names. -_Compound = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' -_Cursor = Union[str, Tuple[str], Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]] # manual page: Tk_GetCursor -_EntryValidateCommand = Union[ - Callable[[], bool], str, List[str], Tuple[str, ...] -] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] -_GridIndex = Union[int, str, Literal["all"]] -_ImageSpec = Union[_Image, str] # str can be from e.g. tkinter.image_names() -_Padding = Union[ - _ScreenUnits, - Tuple[_ScreenUnits], - Tuple[_ScreenUnits, _ScreenUnits], - Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits], - Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], -] -_Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief -_ScreenUnits = Union[str, float] # Often the right type instead of int. Manual page: Tk_GetPixels -_XYScrollCommand = Union[str, Callable[[float, float], Any]] # -xscrollcommand and -yscrollcommand in 'options' manual page -_TakeFocusValue = Union[int, Literal[""], Callable[[str], Optional[bool]]] # -takefocus in manual page named 'options' - -class EventType(str, Enum): - Activate: str - ButtonPress: str - Button = ButtonPress - ButtonRelease: str - Circulate: str - CirculateRequest: str - ClientMessage: str - Colormap: str - Configure: str - ConfigureRequest: str - Create: str - Deactivate: str - Destroy: str - Enter: str - Expose: str - FocusIn: str - FocusOut: str - GraphicsExpose: str - Gravity: str - KeyPress: str - Key = KeyPress - KeyRelease: str - Keymap: str - Leave: str - Map: str - MapRequest: str - Mapping: str - Motion: str - MouseWheel: str - NoExpose: str - Property: str - Reparent: str - ResizeRequest: str - Selection: str - SelectionClear: str - SelectionRequest: str - Unmap: str - VirtualEvent: str - Visibility: str - -_W = TypeVar("_W", bound="Misc") +# manual page: Tk_GetCursor +_Cursor: TypeAlias = str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] + +if sys.version_info >= (3, 11): + @type_check_only + class _VersionInfoTypeBase(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + + if sys.version_info >= (3, 12): + class _VersionInfoType(_VersionInfoTypeBase): ... + else: + @disjoint_base + class _VersionInfoType(_VersionInfoTypeBase): ... + +if sys.version_info >= (3, 11): + class EventType(StrEnum): + Activate = "36" + ButtonPress = "4" + Button = ButtonPress + ButtonRelease = "5" + Circulate = "26" + CirculateRequest = "27" + ClientMessage = "33" + Colormap = "32" + Configure = "22" + ConfigureRequest = "23" + Create = "16" + Deactivate = "37" + Destroy = "17" + Enter = "7" + Expose = "12" + FocusIn = "9" + FocusOut = "10" + GraphicsExpose = "13" + Gravity = "24" + KeyPress = "2" + Key = "2" + KeyRelease = "3" + Keymap = "11" + Leave = "8" + Map = "19" + MapRequest = "20" + Mapping = "34" + Motion = "6" + MouseWheel = "38" + NoExpose = "14" + Property = "28" + Reparent = "21" + ResizeRequest = "25" + Selection = "31" + SelectionClear = "29" + SelectionRequest = "30" + Unmap = "18" + VirtualEvent = "35" + Visibility = "15" + +else: + class EventType(str, Enum): + Activate = "36" + ButtonPress = "4" + Button = ButtonPress + ButtonRelease = "5" + Circulate = "26" + CirculateRequest = "27" + ClientMessage = "33" + Colormap = "32" + Configure = "22" + ConfigureRequest = "23" + Create = "16" + Deactivate = "37" + Destroy = "17" + Enter = "7" + Expose = "12" + FocusIn = "9" + FocusOut = "10" + GraphicsExpose = "13" + Gravity = "24" + KeyPress = "2" + Key = KeyPress + KeyRelease = "3" + Keymap = "11" + Leave = "8" + Map = "19" + MapRequest = "20" + Mapping = "34" + Motion = "6" + MouseWheel = "38" + NoExpose = "14" + Property = "28" + Reparent = "21" + ResizeRequest = "25" + Selection = "31" + SelectionClear = "29" + SelectionRequest = "30" + Unmap = "18" + VirtualEvent = "35" + Visibility = "15" + +_W = TypeVar("_W", bound=Misc) # Events considered covariant because you should never assign to event.widget. -_W_co = TypeVar("_W_co", covariant=True, bound="Misc") +_W_co = TypeVar("_W_co", covariant=True, bound=Misc, default=Misc) class Event(Generic[_W_co]): serial: int @@ -125,79 +313,100 @@ class Event(Generic[_W_co]): type: EventType widget: _W_co delta: int + if sys.version_info >= (3, 15): + detail: str + user_data: str + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -def NoDefaultRoot(): ... - -_TraceMode = Literal["array", "read", "write", "unset"] +def NoDefaultRoot() -> None: ... class Variable: - def __init__(self, master: Misc | None = ..., value: Any | None = ..., name: str | None = ...) -> None: ... - def set(self, value: Any) -> None: ... + def __init__(self, master: Misc | None = None, value=None, name: str | None = None) -> None: ... + def set(self, value) -> None: ... initialize = set - def get(self) -> Any: ... - def trace_add(self, mode: _TraceMode, callback: Callable[[str, str, str], Any]) -> str: ... - def trace_remove(self, mode: _TraceMode, cbname: str) -> None: ... - def trace_info(self) -> list[tuple[Tuple[_TraceMode, ...], str]]: ... - def trace_variable(self, mode, callback): ... # deprecated - def trace_vdelete(self, mode, cbname): ... # deprecated - def trace_vinfo(self): ... # deprecated - trace = trace_variable # deprecated + def get(self): ... + def trace_add(self, mode: Literal["array", "read", "write", "unset"], callback: Callable[[str, str, str], object]) -> str: ... + def trace_remove(self, mode: Literal["array", "read", "write", "unset"], cbname: str) -> None: ... + def trace_info(self) -> list[tuple[tuple[Literal["array", "read", "write", "unset"], ...], str]]: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_add()` instead.") + def trace(self, mode, callback) -> str: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_add()` instead.") + def trace_variable(self, mode, callback) -> str: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_remove()` instead.") + def trace_vdelete(self, mode, cbname) -> None: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_info()` instead.") + def trace_vinfo(self) -> list[Incomplete]: ... + def __eq__(self, other: object) -> bool: ... + def __del__(self) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] class StringVar(Variable): - def __init__(self, master: Misc | None = ..., value: str | None = ..., name: str | None = ...) -> None: ... + def __init__(self, master: Misc | None = None, value: str | None = None, name: str | None = None) -> None: ... def set(self, value: str) -> None: ... initialize = set def get(self) -> str: ... class IntVar(Variable): - def __init__(self, master: Misc | None = ..., value: int | None = ..., name: str | None = ...) -> None: ... + def __init__(self, master: Misc | None = None, value: int | None = None, name: str | None = None) -> None: ... def set(self, value: int) -> None: ... initialize = set def get(self) -> int: ... class DoubleVar(Variable): - def __init__(self, master: Misc | None = ..., value: float | None = ..., name: str | None = ...) -> None: ... + def __init__(self, master: Misc | None = None, value: float | None = None, name: str | None = None) -> None: ... def set(self, value: float) -> None: ... initialize = set def get(self) -> float: ... class BooleanVar(Variable): - def __init__(self, master: Misc | None = ..., value: bool | None = ..., name: str | None = ...) -> None: ... + def __init__(self, master: Misc | None = None, value: bool | None = None, name: str | None = None) -> None: ... def set(self, value: bool) -> None: ... initialize = set def get(self) -> bool: ... -def mainloop(n: int = ...) -> None: ... +def mainloop(n: int = 0) -> None: ... + +getint = int +getdouble = float -getint: Any -getdouble: Any +def getboolean(s) -> bool: ... -def getboolean(s): ... +_Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") +@type_check_only class _GridIndexInfo(TypedDict, total=False): - minsize: _ScreenUnits - pad: _ScreenUnits + minsize: float | str + pad: float | str uniform: str | None weight: int +@type_check_only +class _BusyInfo(TypedDict): + cursor: _Cursor + class Misc: master: Misc | None tk: _tkinter.TkappType children: dict[str, Widget] + if sys.version_info >= (3, 15): + __iter__: ClassVar[None] # prevent using __getitem__ for iteration + def destroy(self) -> None: ... def deletecommand(self, name: str) -> None: ... - def tk_strictMotif(self, boolean: Any | None = ...): ... - def tk_bisque(self): ... - def tk_setPalette(self, *args, **kw): ... - def wait_variable(self, name: str | Variable = ...) -> None: ... + def tk_strictMotif(self, boolean=None): ... + def tk_bisque(self) -> None: ... + def tk_setPalette(self, *args, **kw) -> None: ... + def wait_variable(self, name: str | Variable = "PY_VAR") -> None: ... waitvar = wait_variable - def wait_window(self, window: Misc | None = ...) -> None: ... - def wait_visibility(self, window: Misc | None = ...) -> None: ... - def setvar(self, name: str = ..., value: str = ...): ... - def getvar(self, name: str = ...): ... - def getint(self, s): ... - def getdouble(self, s): ... - def getboolean(self, s): ... + def wait_window(self, window: Misc | None = None) -> None: ... + def wait_visibility(self, window: Misc | None = None) -> None: ... + def setvar(self, name: str = "PY_VAR", value: str = "1") -> None: ... + def getvar(self, name: str = "PY_VAR"): ... + def getint(self, s) -> int: ... + def getdouble(self, s) -> float: ... + def getboolean(self, s) -> bool: ... def focus_set(self) -> None: ... focus = focus_set def focus_force(self) -> None: ... @@ -207,61 +416,95 @@ class Misc: def tk_focusFollowsMouse(self) -> None: ... def tk_focusNext(self) -> Misc | None: ... def tk_focusPrev(self) -> Misc | None: ... - @overload - def after(self, ms: int, func: None = ...) -> None: ... - @overload - def after(self, ms: int | Literal["idle"], func: Callable[..., Any], *args: Any) -> str: ... - # after_idle is essentially partialmethod(after, "idle") - def after_idle(self, func: Callable[..., Any], *args: Any) -> str: ... + if sys.version_info >= (3, 14): + # .after() can be called without the "func" argument, but it is basically never what you want. + # It behaves like time.sleep() and freezes the GUI app. + def after(self, ms: int | Literal["idle"], func: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> str: ... + else: + # .after() can be called without the "func" argument, but it is basically never what you want. + # It behaves like time.sleep() and freezes the GUI app. + def after(self, ms: int | Literal["idle"], func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + def after_cancel(self, id: str) -> None: ... - def bell(self, displayof: Literal[0] | Misc | None = ...): ... + if sys.version_info >= (3, 13): + def after_info(self, id: str | None = None) -> tuple[str, ...]: ... + + def bell(self, displayof: Literal[0] | Misc | None = 0) -> None: ... + if sys.version_info >= (3, 13): + # Supports options from `_BusyInfo`` + def tk_busy_cget(self, option: Literal["cursor"]) -> _Cursor: ... + busy_cget = tk_busy_cget + def tk_busy_configure(self, cnf: Any = None, **kw: Any) -> Any: ... + tk_busy_config = tk_busy_configure + busy_configure = tk_busy_configure + busy_config = tk_busy_configure + def tk_busy_current(self, pattern: str | None = None) -> list[Misc]: ... + busy_current = tk_busy_current + def tk_busy_forget(self) -> None: ... + busy_forget = tk_busy_forget + def tk_busy_hold(self, **kw: Unpack[_BusyInfo]) -> None: ... + tk_busy = tk_busy_hold + busy_hold = tk_busy_hold + busy = tk_busy_hold + def tk_busy_status(self) -> bool: ... + busy_status = tk_busy_status + def clipboard_get(self, *, displayof: Misc = ..., type: str = ...) -> str: ... def clipboard_clear(self, *, displayof: Misc = ...) -> None: ... - def clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...): ... + def clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...) -> None: ... def grab_current(self): ... - def grab_release(self): ... + def grab_release(self) -> None: ... def grab_set(self) -> None: ... def grab_set_global(self) -> None: ... - def grab_status(self): ... - def option_add(self, pattern, value, priority: Any | None = ...): ... - def option_clear(self): ... + def grab_status(self) -> Literal["local", "global"] | None: ... + def option_add( + self, pattern, value, priority: int | Literal["widgetDefault", "startupFile", "userDefault", "interactive"] | None = None + ) -> None: ... + def option_clear(self) -> None: ... def option_get(self, name, className): ... - def option_readfile(self, fileName, priority: Any | None = ...): ... - def selection_clear(self, **kw): ... + def option_readfile(self, fileName, priority=None) -> None: ... + def selection_clear(self, **kw) -> None: ... def selection_get(self, **kw): ... - def selection_handle(self, command, **kw): ... - def selection_own(self, **kw): ... + def selection_handle(self, command, **kw) -> None: ... + def selection_own(self, **kw) -> None: ... def selection_own_get(self, **kw): ... def send(self, interp, cmd, *args): ... - def lower(self, belowThis: Any | None = ...): ... - def tkraise(self, aboveThis: Any | None = ...): ... + def lower(self, belowThis=None) -> None: ... + def tkraise(self, aboveThis=None) -> None: ... lift = tkraise - def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = ...): ... - def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = ...): ... + if sys.version_info >= (3, 11): + def info_patchlevel(self) -> _VersionInfoType: ... + + def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = 0) -> int: ... + def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = 0) -> str: ... def winfo_cells(self) -> int: ... - def winfo_children(self) -> list[Widget]: ... # Widget because it can't be Toplevel or Tk + def winfo_children(self) -> list[Widget | Toplevel]: ... def winfo_class(self) -> str: ... def winfo_colormapfull(self) -> bool: ... - def winfo_containing(self, rootX: int, rootY: int, displayof: Literal[0] | Misc | None = ...) -> Misc | None: ... + def winfo_containing(self, rootX: int, rootY: int, displayof: Literal[0] | Misc | None = 0) -> Misc | None: ... def winfo_depth(self) -> int: ... def winfo_exists(self) -> bool: ... - def winfo_fpixels(self, number: _ScreenUnits) -> float: ... + def winfo_fpixels(self, number: float | str) -> float: ... def winfo_geometry(self) -> str: ... def winfo_height(self) -> int: ... def winfo_id(self) -> int: ... - def winfo_interps(self, displayof: Literal[0] | Misc | None = ...) -> Tuple[str, ...]: ... + def winfo_interps(self, displayof: Literal[0] | Misc | None = 0) -> tuple[str, ...]: ... def winfo_ismapped(self) -> bool: ... def winfo_manager(self) -> str: ... def winfo_name(self) -> str: ... def winfo_parent(self) -> str: ... # return value needs nametowidget() - def winfo_pathname(self, id: int, displayof: Literal[0] | Misc | None = ...): ... - def winfo_pixels(self, number: _ScreenUnits) -> int: ... + def winfo_pathname(self, id: int, displayof: Literal[0] | Misc | None = 0): ... + def winfo_pixels(self, number: float | str) -> int: ... def winfo_pointerx(self) -> int: ... def winfo_pointerxy(self) -> tuple[int, int]: ... def winfo_pointery(self) -> int: ... def winfo_reqheight(self) -> int: ... def winfo_reqwidth(self) -> int: ... - def winfo_rgb(self, color: _Color) -> tuple[int, int, int]: ... + def winfo_rgb(self, color: str) -> tuple[int, int, int]: ... def winfo_rootx(self) -> int: ... def winfo_rooty(self) -> int: ... def winfo_screen(self) -> str: ... @@ -277,7 +520,7 @@ class Misc: def winfo_viewable(self) -> bool: ... def winfo_visual(self) -> str: ... def winfo_visualid(self) -> str: ... - def winfo_visualsavailable(self, includeids: int = ...) -> list[tuple[str, int]]: ... + def winfo_visualsavailable(self, includeids: bool = False) -> list[tuple[str, int]]: ... def winfo_vrootheight(self) -> int: ... def winfo_vrootwidth(self) -> int: ... def winfo_vrootx(self) -> int: ... @@ -287,105 +530,127 @@ class Misc: def winfo_y(self) -> int: ... def update(self) -> None: ... def update_idletasks(self) -> None: ... - def bindtags(self, tagList: Any | None = ...): ... + + @overload + def bindtags(self, tagList: None = None) -> tuple[str, ...]: ... + @overload + def bindtags(self, tagList: list[str] | tuple[str, ...]) -> None: ... + # bind with isinstance(func, str) doesn't return anything, but all other # binds do. The default value of func is not str. @overload def bind( self, - sequence: str | None = ..., - func: Callable[[Event[Misc]], Any] | None = ..., - add: Literal["", "+"] | bool | None = ..., + sequence: str | None = None, + func: Callable[[Event[Misc]], object] | None = None, + add: Literal["", "+"] | bool | None = None, ) -> str: ... @overload - def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload - def bind(self, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + # There's no way to know what type of widget bind_all and bind_class # callbacks will get, so those are Misc. @overload def bind_all( self, - sequence: str | None = ..., - func: Callable[[Event[Misc]], Any] | None = ..., - add: Literal["", "+"] | bool | None = ..., + sequence: str | None = None, + func: Callable[[Event[Misc]], object] | None = None, + add: Literal["", "+"] | bool | None = None, ) -> str: ... @overload - def bind_all(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind_all(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload - def bind_all(self, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind_all(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + @overload def bind_class( self, className: str, - sequence: str | None = ..., - func: Callable[[Event[Misc]], Any] | None = ..., - add: Literal["", "+"] | bool | None = ..., + sequence: str | None = None, + func: Callable[[Event[Misc]], object] | None = None, + add: Literal["", "+"] | bool | None = None, ) -> str: ... @overload - def bind_class(self, className: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind_class(self, className: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload - def bind_class(self, className: str, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... - def unbind(self, sequence: str, funcid: str | None = ...) -> None: ... + def bind_class(self, className: str, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + def unbind(self, sequence: str, funcid: str | None = None) -> None: ... def unbind_all(self, sequence: str) -> None: ... def unbind_class(self, className: str, sequence: str) -> None: ... - def mainloop(self, n: int = ...) -> None: ... - def quit(self): ... + def mainloop(self, n: int = 0) -> None: ... + def quit(self) -> None: ... + @property + def _windowingsystem(self) -> Literal["win32", "aqua", "x11"]: ... def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: ... def register( - self, func: Callable[..., Any], subst: Callable[..., Sequence[Any]] | None = ..., needcleanup: int = ... + self, func: Callable[..., object], subst: Callable[..., Sequence[Any]] | None = None, needcleanup: int = 1 ) -> str: ... def keys(self) -> list[str]: ... + @overload def pack_propagate(self, flag: bool) -> bool | None: ... @overload def pack_propagate(self) -> None: ... + propagate = pack_propagate - def grid_anchor(self, anchor: _Anchor | None = ...) -> None: ... + def grid_anchor(self, anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] | None = None) -> None: ... anchor = grid_anchor + @overload def grid_bbox( - self, column: None = ..., row: None = ..., col2: None = ..., row2: None = ... + self, column: None = None, row: None = None, col2: None = None, row2: None = None ) -> tuple[int, int, int, int] | None: ... @overload - def grid_bbox(self, column: int, row: int, col2: None = ..., row2: None = ...) -> tuple[int, int, int, int] | None: ... + def grid_bbox(self, column: int, row: int, col2: None = None, row2: None = None) -> tuple[int, int, int, int] | None: ... @overload def grid_bbox(self, column: int, row: int, col2: int, row2: int) -> tuple[int, int, int, int] | None: ... + bbox = grid_bbox def grid_columnconfigure( self, - index: _GridIndex, - cnf: _GridIndexInfo = ..., + index: int | str | list[int] | tuple[int, ...], + cnf: _GridIndexInfo = {}, *, - minsize: _ScreenUnits = ..., - pad: _ScreenUnits = ..., + minsize: float | str = ..., + pad: float | str = ..., uniform: str = ..., weight: int = ..., - ) -> _GridIndexInfo | Any: ... # can be None but annoying to check + ) -> _GridIndexInfo | MaybeNone: ... # can be None but annoying to check def grid_rowconfigure( self, - index: _GridIndex, - cnf: _GridIndexInfo = ..., + index: int | str | list[int] | tuple[int, ...], + cnf: _GridIndexInfo = {}, *, - minsize: _ScreenUnits = ..., - pad: _ScreenUnits = ..., + minsize: float | str = ..., + pad: float | str = ..., uniform: str = ..., weight: int = ..., - ) -> _GridIndexInfo | Any: ... # can be None but annoying to check + ) -> _GridIndexInfo | MaybeNone: ... # can be None but annoying to check columnconfigure = grid_columnconfigure rowconfigure = grid_rowconfigure - def grid_location(self, x: _ScreenUnits, y: _ScreenUnits) -> tuple[int, int]: ... + def grid_location(self, x: float | str, y: float | str) -> tuple[int, int]: ... + @overload def grid_propagate(self, flag: bool) -> None: ... @overload def grid_propagate(self) -> bool: ... + def grid_size(self) -> tuple[int, int]: ... size = grid_size # Widget because Toplevel or Tk is never a slave def pack_slaves(self) -> list[Widget]: ... - def grid_slaves(self, row: int | None = ..., column: int | None = ...) -> list[Widget]: ... + def grid_slaves(self, row: int | None = None, column: int | None = None) -> list[Widget]: ... def place_slaves(self) -> list[Widget]: ... slaves = pack_slaves + if sys.version_info >= (3, 15): + def pack_content(self) -> list[Widget]: ... + def grid_content(self, row: int | None = None, column: int | None = None) -> list[Widget]: ... + def place_content(self) -> list[Widget]: ... + content = pack_content + def event_add(self, virtual: str, *sequences: str) -> None: ... def event_delete(self, virtual: str, *sequences: str) -> None: ... def event_generate( @@ -393,274 +658,479 @@ class Misc: sequence: str, *, above: Misc | int = ..., - borderwidth: _ScreenUnits = ..., + borderwidth: float | str = ..., button: int = ..., count: int = ..., data: Any = ..., # anything with usable str() value delta: int = ..., detail: str = ..., focus: bool = ..., - height: _ScreenUnits = ..., + height: float | str = ..., keycode: int = ..., keysym: str = ..., mode: str = ..., override: bool = ..., place: Literal["PlaceOnTop", "PlaceOnBottom"] = ..., root: Misc | int = ..., - rootx: _ScreenUnits = ..., - rooty: _ScreenUnits = ..., + rootx: float | str = ..., + rooty: float | str = ..., sendevent: bool = ..., serial: int = ..., state: int | str = ..., subwindow: Misc | int = ..., time: int = ..., warp: bool = ..., - width: _ScreenUnits = ..., + width: float | str = ..., when: Literal["now", "tail", "head", "mark"] = ..., - x: _ScreenUnits = ..., - y: _ScreenUnits = ..., + x: float | str = ..., + y: float | str = ..., ) -> None: ... - def event_info(self, virtual: str | None = ...) -> Tuple[str, ...]: ... - def image_names(self) -> Tuple[str, ...]: ... - def image_types(self) -> Tuple[str, ...]: ... + def event_info(self, virtual: str | None = None) -> tuple[str, ...]: ... + def image_names(self) -> tuple[str, ...]: ... + def image_types(self) -> tuple[str, ...]: ... # See #4363 and #4891 def __setitem__(self, key: str, value: Any) -> None: ... def __getitem__(self, key: str) -> Any: ... def cget(self, key: str) -> Any: ... - def configure(self, cnf: Any = ...) -> Any: ... - # TODO: config is an alias of configure, but adding that here creates lots of mypy errors + def configure(self, cnf: Any = None) -> Any: ... + config = configure class CallWrapper: - func: Any - subst: Any - widget: Any - def __init__(self, func, subst, widget): ... + func: Incomplete + subst: Incomplete + widget: Incomplete + def __init__(self, func, subst, widget) -> None: ... def __call__(self, *args): ... class XView: @overload def xview(self) -> tuple[float, float]: ... @overload - def xview(self, *args: Any) -> Any: ... + def xview(self, *args) -> None: ... + def xview_moveto(self, fraction: float) -> None: ... + @overload def xview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... @overload - def xview_scroll(self, number: _ScreenUnits, what: Literal["pixels"]) -> None: ... + def xview_scroll(self, number: float | str, what: Literal["pixels"]) -> None: ... class YView: @overload def yview(self) -> tuple[float, float]: ... @overload - def yview(self, *args: Any) -> Any: ... + def yview(self, *args) -> None: ... + def yview_moveto(self, fraction: float) -> None: ... + @overload def yview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... @overload - def yview_scroll(self, number: _ScreenUnits, what: Literal["pixels"]) -> None: ... + def yview_scroll(self, number: float | str, what: Literal["pixels"]) -> None: ... + +if sys.platform == "darwin": + @type_check_only + class _WmAttributes(TypedDict): + alpha: float + fullscreen: bool + modified: bool + notify: bool + titlepath: str + topmost: bool + transparent: bool + type: str # Present, but not actually used on darwin + +elif sys.platform == "win32": + @type_check_only + class _WmAttributes(TypedDict): + alpha: float + transparentcolor: str + disabled: bool + fullscreen: bool + toolwindow: bool + topmost: bool + +else: + # X11 + @type_check_only + class _WmAttributes(TypedDict): + alpha: float + topmost: bool + zoomed: bool + fullscreen: bool + type: str class Wm: @overload def wm_aspect(self, minNumer: int, minDenom: int, maxNumer: int, maxDenom: int) -> None: ... @overload def wm_aspect( - self, minNumer: None = ..., minDenom: None = ..., maxNumer: None = ..., maxDenom: None = ... + self, minNumer: None = None, minDenom: None = None, maxNumer: None = None, maxDenom: None = None ) -> tuple[int, int, int, int] | None: ... + aspect = wm_aspect + + # wm_attributes: Get all attributes + if sys.version_info >= (3, 13): + @overload + def wm_attributes(self, *, return_python_dict: Literal[False] = False) -> tuple[Any, ...]: ... + @overload + def wm_attributes(self, *, return_python_dict: Literal[True]) -> _WmAttributes: ... + else: + @overload + def wm_attributes(self) -> tuple[Any, ...]: ... + + # wm_attributes: Get one attribute (old variant using string that starts with "-") @overload - def wm_attributes(self) -> Tuple[Any, ...]: ... + def wm_attributes(self, option: Literal["-alpha"], /) -> float: ... @overload - def wm_attributes(self, __option: str) -> Any: ... + def wm_attributes(self, option: Literal["-fullscreen"], /) -> bool: ... @overload - def wm_attributes(self, __option: str, __value: Any, *__other_option_value_pairs: Any) -> None: ... + def wm_attributes(self, option: Literal["-topmost"], /) -> bool: ... + if sys.platform == "darwin": + @overload + def wm_attributes(self, option: Literal["-modified"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-notify"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-titlepath"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["-transparent"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-type"], /) -> str: ... + elif sys.platform == "win32": + @overload + def wm_attributes(self, option: Literal["-transparentcolor"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["-disabled"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-toolwindow"], /) -> bool: ... + else: + # X11 + @overload + def wm_attributes(self, option: Literal["-zoomed"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-type"], /) -> str: ... + if sys.version_info >= (3, 13): + # wm_attributes: Get one attribute (new variant without "-") + @overload + def wm_attributes(self, option: Literal["alpha"], /) -> float: ... + @overload + def wm_attributes(self, option: Literal["fullscreen"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["topmost"], /) -> bool: ... + if sys.platform == "darwin": + @overload + def wm_attributes(self, option: Literal["modified"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["notify"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["titlepath"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["transparent"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["type"], /) -> str: ... + elif sys.platform == "win32": + @overload + def wm_attributes(self, option: Literal["transparentcolor"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["disabled"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["toolwindow"], /) -> bool: ... + else: + # X11 + @overload + def wm_attributes(self, option: Literal["zoomed"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["type"], /) -> str: ... + + # wm_attributes: Set an attribute (old variant using string that starts with "-") + @overload + def wm_attributes(self, option: str, /): ... + @overload + def wm_attributes(self, option: Literal["-alpha"], value: float, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-fullscreen"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-topmost"], value: bool, /) -> Literal[""]: ... + if sys.platform == "darwin": + @overload + def wm_attributes(self, option: Literal["-modified"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-notify"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-titlepath"], value: str, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-transparent"], value: bool, /) -> Literal[""]: ... + elif sys.platform == "win32": + @overload + def wm_attributes(self, option: Literal["-transparentcolor"], value: str, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-disabled"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-toolwindow"], value: bool, /) -> Literal[""]: ... + else: + # X11 + @overload + def wm_attributes(self, option: Literal["-zoomed"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-type"], value: str, /) -> Literal[""]: ... + + # wm_attributes: Set multiple attributes (old variant using strings that start with "-") + @overload + def wm_attributes(self, option: str, value, /, *__other_option_value_pairs: Any) -> Literal[""]: ... + + # wm_attributes: Set an attribute (new variant with kwarg instead of string) + if sys.version_info >= (3, 13): + if sys.platform == "darwin": + @overload + def wm_attributes( + self, + *, + alpha: float = ..., + fullscreen: bool = ..., + modified: bool = ..., + notify: bool = ..., + titlepath: str = ..., + topmost: bool = ..., + transparent: bool = ..., + ) -> None: ... + elif sys.platform == "win32": + @overload + def wm_attributes( + self, + *, + alpha: float = ..., + transparentcolor: str = ..., + disabled: bool = ..., + fullscreen: bool = ..., + toolwindow: bool = ..., + topmost: bool = ..., + ) -> None: ... + else: + # X11 + @overload + def wm_attributes( + self, *, alpha: float = ..., topmost: bool = ..., zoomed: bool = ..., fullscreen: bool = ..., type: str = ... + ) -> None: ... + attributes = wm_attributes - def wm_client(self, name: str | None = ...) -> str: ... + def wm_client(self, name: str | None = None) -> str: ... client = wm_client + @overload def wm_colormapwindows(self) -> list[Misc]: ... @overload - def wm_colormapwindows(self, __wlist: list[Misc] | Tuple[Misc, ...]) -> None: ... + def wm_colormapwindows(self, wlist: list[Misc] | tuple[Misc, ...], /) -> None: ... @overload - def wm_colormapwindows(self, __first_wlist_item: Misc, *other_wlist_items: Misc) -> None: ... + def wm_colormapwindows(self, first_wlist_item: Misc, /, *other_wlist_items: Misc) -> None: ... + colormapwindows = wm_colormapwindows - def wm_command(self, value: str | None = ...) -> str: ... + def wm_command(self, value: str | None = None) -> str: ... command = wm_command # Some of these always return empty string, but return type is set to None to prevent accidentally using it def wm_deiconify(self) -> None: ... deiconify = wm_deiconify - def wm_focusmodel(self, model: Any | None = ...): ... + def wm_focusmodel(self, model: Literal["active", "passive"] | None = None) -> Literal["active", "passive", ""]: ... focusmodel = wm_focusmodel def wm_forget(self, window: Wm) -> None: ... forget = wm_forget - def wm_frame(self): ... + def wm_frame(self) -> str: ... frame = wm_frame + @overload - def wm_geometry(self, newGeometry: None = ...) -> str: ... + def wm_geometry(self, newGeometry: None = None) -> str: ... @overload def wm_geometry(self, newGeometry: str) -> None: ... + geometry = wm_geometry - def wm_grid( - self, baseWidth: Any | None = ..., baseHeight: Any | None = ..., widthInc: Any | None = ..., heightInc: Any | None = ... - ): ... + def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): ... grid = wm_grid - def wm_group(self, pathName: Any | None = ...): ... + def wm_group(self, pathName=None): ... group = wm_group - def wm_iconbitmap(self, bitmap: Any | None = ..., default: Any | None = ...): ... + def wm_iconbitmap(self, bitmap=None, default=None): ... iconbitmap = wm_iconbitmap def wm_iconify(self) -> None: ... iconify = wm_iconify - def wm_iconmask(self, bitmap: Any | None = ...): ... + def wm_iconmask(self, bitmap=None): ... iconmask = wm_iconmask - def wm_iconname(self, newName: Any | None = ...): ... + def wm_iconname(self, newName=None) -> str: ... iconname = wm_iconname - def wm_iconphoto(self, default: bool, __image1: Image, *args: Image) -> None: ... + def wm_iconphoto(self, default: bool, image1: _PhotoImageLike | str, /, *args: _PhotoImageLike | str) -> None: ... iconphoto = wm_iconphoto - def wm_iconposition(self, x: Any | None = ..., y: Any | None = ...): ... + def wm_iconposition(self, x: int | None = None, y: int | None = None) -> tuple[int, int] | None: ... iconposition = wm_iconposition - def wm_iconwindow(self, pathName: Any | None = ...): ... + def wm_iconwindow(self, pathName=None): ... iconwindow = wm_iconwindow - def wm_manage(self, widget): ... + def wm_manage(self, widget) -> None: ... manage = wm_manage + @overload - def wm_maxsize(self, width: None = ..., height: None = ...) -> tuple[int, int]: ... + def wm_maxsize(self, width: None = None, height: None = None) -> tuple[int, int]: ... @overload def wm_maxsize(self, width: int, height: int) -> None: ... + maxsize = wm_maxsize + @overload - def wm_minsize(self, width: None = ..., height: None = ...) -> tuple[int, int]: ... + def wm_minsize(self, width: None = None, height: None = None) -> tuple[int, int]: ... @overload def wm_minsize(self, width: int, height: int) -> None: ... + minsize = wm_minsize + @overload - def wm_overrideredirect(self, boolean: None = ...) -> bool | None: ... # returns True or None + def wm_overrideredirect(self, boolean: None = None) -> bool | None: ... # returns True or None @overload def wm_overrideredirect(self, boolean: bool) -> None: ... + overrideredirect = wm_overrideredirect - def wm_positionfrom(self, who: Any | None = ...): ... + def wm_positionfrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: ... positionfrom = wm_positionfrom + @overload - def wm_protocol(self, name: str, func: Callable[[], Any] | str) -> None: ... + def wm_protocol(self, name: str, func: Callable[[], object] | str) -> None: ... @overload - def wm_protocol(self, name: str, func: None = ...) -> str: ... + def wm_protocol(self, name: str, func: None = None) -> str: ... @overload - def wm_protocol(self, name: None = ..., func: None = ...) -> Tuple[str, ...]: ... + def wm_protocol(self, name: None = None, func: None = None) -> tuple[str, ...]: ... + protocol = wm_protocol + @overload - def wm_resizable(self, width: None = ..., height: None = ...) -> tuple[bool, bool]: ... + def wm_resizable(self, width: None = None, height: None = None) -> tuple[bool, bool]: ... @overload def wm_resizable(self, width: bool, height: bool) -> None: ... + resizable = wm_resizable - def wm_sizefrom(self, who: Any | None = ...): ... + def wm_sizefrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: ... sizefrom = wm_sizefrom + @overload - def wm_state(self, newstate: None = ...) -> str: ... + def wm_state(self, newstate: None = None) -> str: ... @overload def wm_state(self, newstate: str) -> None: ... + state = wm_state + @overload - def wm_title(self, string: None = ...) -> str: ... + def wm_title(self, string: None = None) -> str: ... @overload def wm_title(self, string: str) -> None: ... + title = wm_title + @overload - def wm_transient(self, master: None = ...) -> _tkinter.Tcl_Obj: ... + def wm_transient(self, master: None = None) -> _tkinter.Tcl_Obj: ... @overload def wm_transient(self, master: Wm | _tkinter.Tcl_Obj) -> None: ... + transient = wm_transient def wm_withdraw(self) -> None: ... withdraw = wm_withdraw -class _ExceptionReportingCallback(Protocol): - def __call__(self, __exc: Type[BaseException], __val: BaseException, __tb: TracebackType | None) -> Any: ... - class Tk(Misc, Wm): master: None def __init__( - # please update ttkthemes stub if you change this - self, - screenName: str | None = ..., - baseName: str | None = ..., - className: str = ..., - useTk: bool = ..., - sync: bool = ..., - use: str | None = ..., + # Make sure to keep in sync with other functions that use the same + # args. + # use `git grep screenName` to find them + self, + screenName: str | None = None, + baseName: str | None = None, + className: str = "Tk", + useTk: bool = True, + sync: bool = False, + use: str | None = None, ) -> None: ... + + # Keep this in sync with ttktheme.ThemedTk. See issue #13858 @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., menu: Menu = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - width: _ScreenUnits = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def loadtk(self) -> None: ... # differs from _tkinter.TkappType.loadtk def destroy(self) -> None: ... def readprofile(self, baseName: str, className: str) -> None: ... - report_callback_exception: _ExceptionReportingCallback + report_callback_exception: Callable[[type[BaseException], BaseException, TracebackType | None], object] # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo - # Please keep in sync with _tkinter.TkappType - call: Callable[..., Any] - def eval(self, __code: str) -> str: ... - adderrorinfo: Any - createcommand: Any - createfilehandler: Any - createtimerhandler: Any - deletecommand: Any - deletefilehandler: Any - dooneevent: Any - evalfile: Any - exprboolean: Any - exprdouble: Any - exprlong: Any - exprstring: Any - getboolean: Any - getdouble: Any - getint: Any - getvar: Any - globalgetvar: Any - globalsetvar: Any - globalunsetvar: Any - interpaddr: Any - mainloop: Any - quit: Any - record: Any - setvar: Any + # Please keep in sync with _tkinter.TkappType. + # Some methods are intentionally missing because they are inherited from Misc instead. + def adderrorinfo(self, msg: str, /) -> None: ... + def call(self, command: Any, /, *args: Any) -> Any: ... + # TODO: Figure out what arguments the following `func` callbacks should accept + def createcommand(self, name: str, func: Callable[..., object], /) -> None: ... + if sys.platform != "win32": + def createfilehandler(self, file: FileDescriptorLike, mask: int, func: Callable[..., object], /) -> None: ... + def deletefilehandler(self, file: FileDescriptorLike, /) -> None: ... + + def createtimerhandler(self, milliseconds: int, func: Callable[..., object], /): ... + def dooneevent(self, flags: int = 0, /) -> int: ... + def eval(self, script: str, /) -> str: ... + def evalfile(self, fileName: str, /) -> str: ... + def exprboolean(self, s: str, /) -> Literal[0, 1]: ... + def exprdouble(self, s: str, /) -> float: ... + def exprlong(self, s: str, /) -> int: ... + def exprstring(self, s: str, /) -> str: ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self) -> int: ... + def loadtk(self) -> None: ... + def record(self, script: str, /) -> str: ... if sys.version_info < (3, 11): - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any + @deprecated("Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.") + def split(self, arg, /): ... + + def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ... + def unsetvar(self, *args, **kwargs): ... + + if sys.version_info >= (3, 14): + @overload + def wantobjects(self) -> Literal[0, 1]: ... + else: + @overload + def wantobjects(self) -> bool: ... + + @overload + def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ... + + def willdispatch(self) -> None: ... -def Tcl(screenName: Any | None = ..., baseName: Any | None = ..., className: str = ..., useTk: bool = ...): ... +def Tcl(screenName: str | None = None, baseName: str | None = None, className: str = "Tk", useTk: bool = False) -> Tk: ... _InMiscTotal = TypedDict("_InMiscTotal", {"in": Misc}) _InMiscNonTotal = TypedDict("_InMiscNonTotal", {"in": Misc}, total=False) +@type_check_only class _PackInfo(_InMiscTotal): # 'before' and 'after' never appear in _PackInfo - anchor: _Anchor + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] expand: bool fill: Literal["none", "x", "y", "both"] side: Literal["left", "right", "top", "bottom"] - # Paddings come out as int or tuple of int, even though any _ScreenUnits + # Paddings come out as int or tuple of int, even though any screen units # can be specified in pack(). ipadx: int ipady: int @@ -669,23 +1139,23 @@ class _PackInfo(_InMiscTotal): class Pack: # _PackInfo is not the valid type for cnf because pad stuff accepts any - # _ScreenUnits instead of int only. I didn't bother to create another + # screen units instead of int only. I didn't bother to create another # TypedDict for cnf because it appears to be a legacy thing that was # replaced by **kwargs. def pack_configure( self, - cnf: Mapping[str, Any] | None = ..., + cnf: Mapping[str, Any] | None = {}, *, after: Misc = ..., - anchor: _Anchor = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., before: Misc = ..., - expand: int = ..., + expand: bool | Literal[0, 1] = 0, fill: Literal["none", "x", "y", "both"] = ..., side: Literal["left", "right", "top", "bottom"] = ..., - ipadx: _ScreenUnits = ..., - ipady: _ScreenUnits = ..., - padx: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ..., - pady: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ..., + ipadx: float | str = ..., + ipady: float | str = ..., + padx: float | str | tuple[float | str, float | str] = ..., + pady: float | str | tuple[float | str, float | str] = ..., in_: Misc = ..., **kw: Any, # allow keyword argument named 'in', see #4836 ) -> None: ... @@ -695,8 +1165,9 @@ class Pack: forget = pack_forget propagate = Misc.pack_propagate +@type_check_only class _PlaceInfo(_InMiscNonTotal): # empty dict if widget hasn't been placed - anchor: _Anchor + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] bordermode: Literal["inside", "outside", "ignore"] width: str # can be int()ed (even after e.g. widget.place(height='2.3c') or similar) height: str # can be int()ed @@ -710,14 +1181,14 @@ class _PlaceInfo(_InMiscNonTotal): # empty dict if widget hasn't been placed class Place: def place_configure( self, - cnf: Mapping[str, Any] | None = ..., + cnf: Mapping[str, Any] | None = {}, *, - anchor: _Anchor = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., bordermode: Literal["inside", "outside", "ignore"] = ..., - width: _ScreenUnits = ..., - height: _ScreenUnits = ..., - x: _ScreenUnits = ..., - y: _ScreenUnits = ..., + width: float | str = ..., + height: float | str = ..., + x: float | str = ..., + y: float | str = ..., # str allowed for compatibility with place_info() relheight: str | float = ..., relwidth: str | float = ..., @@ -731,6 +1202,7 @@ class Place: place = place_configure info = place_info +@type_check_only class _GridInfo(_InMiscNonTotal): # empty dict if widget hasn't been gridded column: int columnspan: int @@ -745,17 +1217,19 @@ class _GridInfo(_InMiscNonTotal): # empty dict if widget hasn't been gridded class Grid: def grid_configure( self, - cnf: Mapping[str, Any] | None = ..., + cnf: Mapping[str, Any] | None = {}, *, column: int = ..., columnspan: int = ..., row: int = ..., rowspan: int = ..., - ipadx: _ScreenUnits = ..., - ipady: _ScreenUnits = ..., - padx: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ..., - pady: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ..., - sticky: str = ..., # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty + ipadx: float | str = ..., + ipady: float | str = ..., + padx: float | str | tuple[float | str, float | str] = ..., + pady: float | str | tuple[float | str, float | str] = ..., + sticky: ( + str | list[str] | tuple[str, ...] + ) = ..., # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty in_: Misc = ..., **kw: Any, # allow keyword argument named 'in', see #4836 ) -> None: ... @@ -768,8 +1242,8 @@ class Grid: class BaseWidget(Misc): master: Misc - widgetName: Any - def __init__(self, master, widgetName, cnf=..., kw=..., extra=...): ... + widgetName: str + def __init__(self, master, widgetName: str, cnf={}, kw={}, extra=()) -> None: ... def destroy(self) -> None: ... # This class represents any widget except Toplevel or Tk. @@ -780,14 +1254,14 @@ class Widget(BaseWidget, Pack, Place, Grid): @overload def bind( self: _W, - sequence: str | None = ..., - func: Callable[[Event[_W]], Any] | None = ..., - add: Literal["", "+"] | bool | None = ..., + sequence: str | None = None, + func: Callable[[Event[_W]], object] | None = None, + add: Literal["", "+"] | bool | None = None, ) -> str: ... @overload - def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload - def bind(self, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def bind(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... class Toplevel(BaseWidget, Wm): # Toplevel and Tk have the same options because they correspond to the same @@ -795,681 +1269,859 @@ class Toplevel(BaseWidget, Wm): # copy/pasted here instead of aliasing as 'config = Tk.config'. def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - class_: str = ..., - colormap: Literal["new", ""] | Misc = ..., - container: bool = ..., - cursor: _Cursor = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 0, + bg: str = ..., + border: float | str = 0, + borderwidth: float | str = 0, + class_: str = "Toplevel", + colormap: Literal["new", ""] | Misc = "", + container: bool = False, + cursor: _Cursor = "", + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, menu: Menu = ..., name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - screen: str = ..., # can't be changed after creating widget - takefocus: _TakeFocusValue = ..., + padx: float | str = 0, + pady: float | str = 0, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + screen: str = "", # can't be changed after creating widget + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, use: int = ..., - visual: str | tuple[str, int] = ..., - width: _ScreenUnits = ..., + visual: str | tuple[str, int] = "", + width: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., menu: Menu = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - width: _ScreenUnits = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Button(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., # same as borderwidth - bg: _Color = ..., # same as background - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., # same as borderwidth - borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - default: Literal["normal", "active", "disabled"] = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., # same as foreground - font: _FontDescription = ..., - foreground: _Color = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., # same as borderwidth + bg: str = ..., # same as background + bitmap: str = "", + border: float | str = ..., # same as borderwidth + borderwidth: float | str = ..., + command: str | Callable[[], Any] = "", + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + default: Literal["normal", "active", "disabled"] = "disabled", + disabledforeground: str = ..., + fg: str = ..., # same as foreground + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., # width and height must be int for buttons containing just text, but - # ints are also valid _ScreenUnits - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - justify: Literal["left", "center", "right"] = ..., + # buttons with an image accept any screen units. + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 1, + image: _Image | str = "", + justify: Literal["left", "center", "right"] = "center", name: str = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = "", + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., repeatdelay: int = ..., repeatinterval: int = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", # We allow the textvariable to be any Variable, not necessarily # StringVar. This is useful for e.g. a button that displays the value # of an IntVar. textvariable: Variable = ..., - underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + underline: int = -1, + width: float | str = 0, + wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., cursor: _Cursor = ..., default: Literal["normal", "active", "disabled"] = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., justify: Literal["left", "center", "right"] = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., repeatdelay: int = ..., repeatinterval: int = ..., state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: Variable = ..., underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = ..., + wraplength: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def flash(self): ... + def flash(self) -> None: ... def invoke(self) -> Any: ... class Canvas(Widget, XView, YView): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - closeenough: float = ..., - confine: bool = ..., - cursor: _Cursor = ..., - # canvas manual page has a section named COORDINATES, and the first - # part of it describes _ScreenUnits. - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., - insertwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = 0, + bg: str = ..., + border: float | str = 0, + borderwidth: float | str = 0, + closeenough: float = 1.0, + confine: bool = True, + cursor: _Cursor = "", + height: float | str = ..., # see COORDINATES in canvas manual page + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: float | str = 2, name: str = ..., - offset: Any = ..., # undocumented - relief: _Relief = ..., + offset=..., # undocumented + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", # Setting scrollregion to None doesn't reset it back to empty, # but setting it to () does. - scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., + scrollregion: tuple[float | str, float | str, float | str, float | str] | tuple[()] = (), + selectbackground: str = ..., + selectborderwidth: float | str = 1, + selectforeground: str = ..., # man page says that state can be 'hidden', but it can't - state: Literal["normal", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - width: _ScreenUnits = ..., - xscrollcommand: _XYScrollCommand = ..., - xscrollincrement: _ScreenUnits = ..., - yscrollcommand: _XYScrollCommand = ..., - yscrollincrement: _ScreenUnits = ..., + state: Literal["normal", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: float | str = ..., + xscrollcommand: str | Callable[[float, float], object] = "", + xscrollincrement: float | str = 0, + yscrollcommand: str | Callable[[float, float], object] = "", + yscrollincrement: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., closeenough: float = ..., confine: bool = ..., cursor: _Cursor = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., insertofftime: int = ..., insertontime: int = ..., - insertwidth: _ScreenUnits = ..., - offset: Any = ..., # undocumented - relief: _Relief = ..., - scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., + insertwidth: float | str = ..., + offset=..., # undocumented + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + scrollregion: tuple[float | str, float | str, float | str, float | str] | tuple[()] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., state: Literal["normal", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - width: _ScreenUnits = ..., - xscrollcommand: _XYScrollCommand = ..., - xscrollincrement: _ScreenUnits = ..., - yscrollcommand: _XYScrollCommand = ..., - yscrollincrement: _ScreenUnits = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + xscrollincrement: float | str = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., + yscrollincrement: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def addtag(self, *args): ... # internal method - def addtag_above(self, newtag: str, tagOrId: str | _CanvasItemId) -> None: ... + def addtag_above(self, newtag: str, tagOrId: str | int) -> None: ... def addtag_all(self, newtag: str) -> None: ... - def addtag_below(self, newtag: str, tagOrId: str | _CanvasItemId) -> None: ... + def addtag_below(self, newtag: str, tagOrId: str | int) -> None: ... def addtag_closest( - self, - newtag: str, - x: _ScreenUnits, - y: _ScreenUnits, - halo: _ScreenUnits | None = ..., - start: str | _CanvasItemId | None = ..., + self, newtag: str, x: float | str, y: float | str, halo: float | str | None = None, start: str | int | None = None ) -> None: ... - def addtag_enclosed(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> None: ... - def addtag_overlapping(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> None: ... - def addtag_withtag(self, newtag: str, tagOrId: str | _CanvasItemId) -> None: ... + def addtag_enclosed(self, newtag: str, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> None: ... + def addtag_overlapping(self, newtag: str, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> None: ... + def addtag_withtag(self, newtag: str, tagOrId: str | int) -> None: ... def find(self, *args): ... # internal method - def find_above(self, tagOrId: str | _CanvasItemId) -> Tuple[_CanvasItemId, ...]: ... - def find_all(self) -> Tuple[_CanvasItemId, ...]: ... - def find_below(self, tagOrId: str | _CanvasItemId) -> Tuple[_CanvasItemId, ...]: ... + def find_above(self, tagOrId: str | int) -> tuple[int, ...]: ... + def find_all(self) -> tuple[int, ...]: ... + def find_below(self, tagOrId: str | int) -> tuple[int, ...]: ... def find_closest( - self, x: _ScreenUnits, y: _ScreenUnits, halo: _ScreenUnits | None = ..., start: str | _CanvasItemId | None = ... - ) -> Tuple[_CanvasItemId, ...]: ... - def find_enclosed( - self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits - ) -> Tuple[_CanvasItemId, ...]: ... - def find_overlapping(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: float) -> Tuple[_CanvasItemId, ...]: ... - def find_withtag(self, tagOrId: str | _CanvasItemId) -> Tuple[_CanvasItemId, ...]: ... + self, x: float | str, y: float | str, halo: float | str | None = None, start: str | int | None = None + ) -> tuple[int, ...]: ... + def find_enclosed(self, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> tuple[int, ...]: ... + def find_overlapping(self, x1: float | str, y1: float | str, x2: float | str, y2: float) -> tuple[int, ...]: ... + def find_withtag(self, tagOrId: str | int) -> tuple[int, ...]: ... # Incompatible with Misc.bbox(), tkinter violates LSP - def bbox(self, *args: str | _CanvasItemId) -> tuple[int, int, int, int]: ... # type: ignore[override] + def bbox(self, *args: str | int) -> tuple[int, int, int, int]: ... # type: ignore[override] + @overload def tag_bind( self, tagOrId: str | int, - sequence: str | None = ..., - func: Callable[[Event[Canvas]], Any] | None = ..., - add: Literal["", "+"] | bool | None = ..., + sequence: str | None = None, + func: Callable[[Event[Canvas]], object] | None = None, + add: Literal["", "+"] | bool | None = None, ) -> str: ... @overload def tag_bind( - self, tagOrId: str | int, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ... + self, tagOrId: str | int, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None ) -> None: ... @overload - def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... - def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = ...) -> None: ... - def canvasx(self, screenx, gridspacing: Any | None = ...): ... - def canvasy(self, screeny, gridspacing: Any | None = ...): ... + def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = None) -> None: ... + def canvasx(self, screenx: float | str, gridspacing: float | str | None = None) -> float: ... + def canvasy(self, screeny: float | str, gridspacing: float | str | None = None) -> float: ... + @overload - def coords(self) -> list[float]: ... + def coords(self, tagOrId: str | int, /) -> list[float]: ... @overload - def coords(self, __args: list[int] | list[float] | Tuple[float, ...]) -> None: ... + def coords(self, tagOrId: str | int, args: list[int] | list[float] | tuple[float, ...], /) -> None: ... @overload - def coords(self, __x1: float, __y1: float, *args: float) -> None: ... - # create_foo() methods accept coords as a list, a tuple, or as separate arguments. - # Keyword arguments should be the same in each pair of overloads. - def create_arc(self, *args, **kw) -> _CanvasItemId: ... - def create_bitmap(self, *args, **kw) -> _CanvasItemId: ... - def create_image(self, *args, **kw) -> _CanvasItemId: ... + def coords(self, tagOrId: str | int, x1: float, y1: float, /, *args: float) -> None: ... + + # create_foo() methods accept coords as a list or tuple, or as separate arguments. + # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)]. + # Keyword arguments should be the same in all overloads of each method. + def create_arc(self, *args, **kw) -> int: ... + def create_bitmap(self, *args, **kw) -> int: ... + def create_image(self, *args, **kw) -> int: ... + @overload def create_line( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., + activewidth: float | str = ..., arrow: Literal["first", "last", "both"] = ..., arrowshape: tuple[float, float, float] = ..., capstyle: Literal["round", "projecting", "butt"] = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., joinstyle: Literal["round", "bevel", "miter"] = ..., - offset: _ScreenUnits = ..., + offset: float | str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... @overload def create_line( self, - __coords: tuple[float, float, float, float] | list[int] | list[float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., + activewidth: float | str = ..., arrow: Literal["first", "last", "both"] = ..., arrowshape: tuple[float, float, float] = ..., capstyle: Literal["round", "projecting", "butt"] = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., joinstyle: Literal["round", "bevel", "miter"] = ..., - offset: _ScreenUnits = ..., + offset: float | str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_line( + self, + coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + arrow: Literal["first", "last", "both"] = ..., + arrowshape: tuple[float, float, float] = ..., + capstyle: Literal["round", "projecting", "butt"] = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload def create_oval( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., - activeoutline: _Color = ..., - activeoutlinestipple: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledoutline: _Color = ..., - disabledoutlinestipple: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., - offset: _ScreenUnits = ..., - outline: _Color = ..., - outlineoffset: _ScreenUnits = ..., - outlinestipple: _Bitmap = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... @overload def create_oval( self, - __coords: tuple[float, float, float, float] | list[int] | list[float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., - activeoutline: _Color = ..., - activeoutlinestipple: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledoutline: _Color = ..., - disabledoutlinestipple: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., - offset: _ScreenUnits = ..., - outline: _Color = ..., - outlineoffset: _ScreenUnits = ..., - outlinestipple: _Bitmap = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_oval( + self, + coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload def create_polygon( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *xy_pairs: float, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., - activeoutline: _Color = ..., - activeoutlinestipple: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledoutline: _Color = ..., - disabledoutlinestipple: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., joinstyle: Literal["round", "bevel", "miter"] = ..., - offset: _ScreenUnits = ..., - outline: _Color = ..., - outlineoffset: _ScreenUnits = ..., - outlinestipple: _Bitmap = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_polygon( + self, + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, + *xy_pairs: tuple[float, float], + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... @overload def create_polygon( self, - __coords: Tuple[float, ...] | list[int] | list[float], + coords: ( + tuple[float, ...] + | tuple[tuple[float, float], ...] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., - activeoutline: _Color = ..., - activeoutlinestipple: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledoutline: _Color = ..., - disabledoutlinestipple: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., joinstyle: Literal["round", "bevel", "miter"] = ..., - offset: _ScreenUnits = ..., - outline: _Color = ..., - outlineoffset: _ScreenUnits = ..., - outlinestipple: _Bitmap = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload def create_rectangle( self, - __x0: float, - __y0: float, - __x1: float, - __y1: float, + x0: float, + y0: float, + x1: float, + y1: float, + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., - activeoutline: _Color = ..., - activeoutlinestipple: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledoutline: _Color = ..., - disabledoutlinestipple: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., - offset: _ScreenUnits = ..., - outline: _Color = ..., - outlineoffset: _ScreenUnits = ..., - outlinestipple: _Bitmap = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... @overload def create_rectangle( self, - __coords: tuple[float, float, float, float] | list[int] | list[float], + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, *, - activedash: str | list[int] | Tuple[int, ...] = ..., - activefill: _Color = ..., - activeoutline: _Color = ..., - activeoutlinestipple: _Color = ..., + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., activestipple: str = ..., - activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., - dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., - disabledfill: _Color = ..., - disabledoutline: _Color = ..., - disabledoutlinestipple: _Color = ..., - disabledstipple: _Bitmap = ..., - disabledwidth: _ScreenUnits = ..., - fill: _Color = ..., - offset: _ScreenUnits = ..., - outline: _Color = ..., - outlineoffset: _ScreenUnits = ..., - outlinestipple: _Bitmap = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_rectangle( + self, + coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload def create_text( self, - __x: float, - __y: float, + x: float, + y: float, + /, *, - activefill: _Color = ..., + activefill: str = ..., activestipple: str = ..., - anchor: _Anchor = ..., - disabledfill: _Color = ..., - disabledstipple: _Bitmap = ..., - fill: _Color = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + angle: float | str = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + fill: str = ..., font: _FontDescription = ..., justify: Literal["left", "center", "right"] = ..., - offset: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + offset: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., text: float | str = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + width: float | str = ..., + ) -> int: ... @overload def create_text( self, - __coords: tuple[float, float] | list[int] | list[float], + coords: tuple[float, float] | list[int] | list[float], + /, *, - activefill: _Color = ..., + activefill: str = ..., activestipple: str = ..., - anchor: _Anchor = ..., - disabledfill: _Color = ..., - disabledstipple: _Bitmap = ..., - fill: _Color = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + angle: float | str = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + fill: str = ..., font: _FontDescription = ..., justify: Literal["left", "center", "right"] = ..., - offset: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., - stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + offset: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., text: float | str = ..., - width: _ScreenUnits = ..., - ) -> _CanvasItemId: ... + width: float | str = ..., + ) -> int: ... + @overload def create_window( self, - __x: float, - __y: float, + x: float, + y: float, + /, *, - anchor: _Anchor = ..., - height: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + height: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., window: Widget = ..., - ) -> _CanvasItemId: ... + ) -> int: ... @overload def create_window( self, - __coords: tuple[float, float] | list[int] | list[float], + coords: tuple[float, float] | list[int] | list[float], + /, *, - anchor: _Anchor = ..., - height: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - width: _ScreenUnits = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + height: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., window: Widget = ..., - ) -> _CanvasItemId: ... - def dchars(self, *args): ... - def delete(self, *tagsOrCanvasIds: str | _CanvasItemId) -> None: ... + ) -> int: ... + + def dchars(self, *args) -> None: ... + def delete(self, *tagsOrCanvasIds: str | int) -> None: ... + @overload - def dtag(self, __tag: str, __tag_to_delete: str | None = ...) -> None: ... + def dtag(self, tag: str, tag_to_delete: str | None = ..., /) -> None: ... @overload - def dtag(self, __id: _CanvasItemId, __tag_to_delete: str) -> None: ... + def dtag(self, id: int, tag_to_delete: str, /) -> None: ... + def focus(self, *args): ... - def gettags(self, __tagOrId: str | _CanvasItemId) -> Tuple[str, ...]: ... - def icursor(self, *args): ... + def gettags(self, tagOrId: str | int, /) -> tuple[str, ...]: ... + def icursor(self, *args) -> None: ... def index(self, *args): ... - def insert(self, *args): ... + def insert(self, *args) -> None: ... def itemcget(self, tagOrId, option): ... # itemconfigure kwargs depend on item type, which is not known when type checking def itemconfigure( - self, tagOrId: str | _CanvasItemId, cnf: dict[str, Any] | None = ..., **kw: Any + self, tagOrId: str | int, cnf: dict[str, Any] | None = None, **kw: Any ) -> dict[str, tuple[str, str, str, str, str]] | None: ... itemconfig = itemconfigure - def move(self, *args): ... - if sys.version_info >= (3, 8): - def moveto(self, tagOrId: str | _CanvasItemId, x: Literal[""] | float = ..., y: Literal[""] | float = ...) -> None: ... - def postscript(self, cnf=..., **kw): ... + def move(self, *args) -> None: ... + def moveto(self, tagOrId: str | int, x: Literal[""] | float = "", y: Literal[""] | float = "") -> None: ... + def postscript(self, cnf={}, **kw): ... # tkinter does: # lower = tag_lower # lift = tkraise = tag_raise # # But mypy doesn't like aliasing here (maybe because Misc defines the same names) - def tag_lower(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... - def lower(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] - def tag_raise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... - def tkraise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] - def lift(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] - def scale(self, *args): ... - def scan_mark(self, x, y): ... - def scan_dragto(self, x, y, gain: int = ...): ... - def select_adjust(self, tagOrId, index): ... - def select_clear(self): ... - def select_from(self, tagOrId, index): ... + def tag_lower(self, first: str | int, second: str | int | None = ..., /) -> None: ... + def lower(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def tag_raise(self, first: str | int, second: str | int | None = ..., /) -> None: ... + def tkraise(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def lift(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def scale(self, tagOrId: str | int, xOrigin: float | str, yOrigin: float | str, xScale: float, yScale: float, /) -> None: ... + def scan_mark(self, x, y) -> None: ... + def scan_dragto(self, x, y, gain: int = 10) -> None: ... + def select_adjust(self, tagOrId, index) -> None: ... + def select_clear(self) -> None: ... + def select_from(self, tagOrId, index) -> None: ... def select_item(self): ... - def select_to(self, tagOrId, index): ... - def type(self, tagOrId): ... + def select_to(self, tagOrId, index) -> None: ... + def type(self, tagOrId: str | int) -> int | None: ... class Checkbutton(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - indicatoron: bool = ..., - justify: Literal["left", "center", "right"] = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = "", + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 1, + image: _Image | str = "", + indicatoron: bool = True, + justify: Literal["left", "center", "right"] = "center", name: str = ..., - offrelief: _Relief = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., # The checkbutton puts a value to its variable when it's checked or # unchecked. We don't restrict the type of that value here, so # Any-typing is fine. @@ -1480,188 +2132,190 @@ class Checkbutton(Widget): # and list[int] are incompatible. Also, we would need a way to # specify "Checkbutton not associated with any variable", which is # done by setting variable to empty string (the default). - offvalue: Any = ..., - onvalue: Any = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + offvalue: Any = 0, + onvalue: Any = 1, + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = "", + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + selectcolor: str = ..., + selectimage: _Image | str = "", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", textvariable: Variable = ..., - tristateimage: _ImageSpec = ..., - tristatevalue: Any = ..., - underline: int = ..., + tristateimage: _Image | str = "", + tristatevalue: Any = "", + underline: int = -1, variable: Variable | Literal[""] = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = 0, + wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., indicatoron: bool = ..., justify: Literal["left", "center", "right"] = ..., - offrelief: _Relief = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., offvalue: Any = ..., onvalue: Any = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: Variable = ..., - tristateimage: _ImageSpec = ..., + tristateimage: _Image | str = ..., tristatevalue: Any = ..., underline: int = ..., variable: Variable | Literal[""] = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = ..., + wraplength: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def deselect(self): ... - def flash(self): ... + def deselect(self) -> None: ... + def flash(self) -> None: ... def invoke(self) -> Any: ... - def select(self): ... - def toggle(self): ... - -_EntryIndex = Union[str, int] # "INDICES" in manual page + def select(self) -> None: ... + def toggle(self) -> None: ... class Entry(Widget, XView): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - disabledbackground: _Color = ..., - disabledforeground: _Color = ..., - exportselection: bool = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., - insertwidth: _ScreenUnits = ..., - invalidcommand: _EntryValidateCommand = ..., - invcmd: _EntryValidateCommand = ..., # same as invalidcommand - justify: Literal["left", "center", "right"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = "xterm", + disabledbackground: str = ..., + disabledforeground: str = ..., + exportselection: bool = True, + fg: str = ..., + font: _FontDescription = "TkTextFont", + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = "", + invcmd: str | list[str] | tuple[str, ...] | Callable[[], object] = "", # same as invalidcommand + justify: Literal["left", "center", "right"] = "left", name: str = ..., - readonlybackground: _Color = ..., - relief: _Relief = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., - show: str = ..., - state: Literal["normal", "disabled", "readonly"] = ..., - takefocus: _TakeFocusValue = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "sunken", + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + show: str = "", + state: Literal["normal", "disabled", "readonly"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", textvariable: Variable = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: _EntryValidateCommand = ..., - vcmd: _EntryValidateCommand = ..., # same as validatecommand - width: int = ..., - xscrollcommand: _XYScrollCommand = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", # same as validatecommand + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - disabledbackground: _Color = ..., - disabledforeground: _Color = ..., + disabledbackground: str = ..., + disabledforeground: str = ..., exportselection: bool = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., insertofftime: int = ..., insertontime: int = ..., - insertwidth: _ScreenUnits = ..., - invalidcommand: _EntryValidateCommand = ..., - invcmd: _EntryValidateCommand = ..., + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., + invcmd: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., justify: Literal["left", "center", "right"] = ..., - readonlybackground: _Color = ..., - relief: _Relief = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., show: str = ..., state: Literal["normal", "disabled", "readonly"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: _EntryValidateCommand = ..., - vcmd: _EntryValidateCommand = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., width: int = ..., - xscrollcommand: _XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def delete(self, first: _EntryIndex, last: _EntryIndex | None = ...) -> None: ... + def delete(self, first: str | int, last: str | int | None = None) -> None: ... def get(self) -> str: ... - def icursor(self, index: _EntryIndex) -> None: ... - def index(self, index: _EntryIndex) -> int: ... - def insert(self, index: _EntryIndex, string: str) -> None: ... - def scan_mark(self, x): ... - def scan_dragto(self, x): ... - def selection_adjust(self, index: _EntryIndex) -> None: ... + def icursor(self, index: str | int) -> None: ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, string: str) -> None: ... + def scan_mark(self, x) -> None: ... + def scan_dragto(self, x) -> None: ... + def selection_adjust(self, index: str | int) -> None: ... def selection_clear(self) -> None: ... # type: ignore[override] - def selection_from(self, index: _EntryIndex) -> None: ... + def selection_from(self, index: str | int) -> None: ... def selection_present(self) -> bool: ... - def selection_range(self, start: _EntryIndex, end: _EntryIndex) -> None: ... - def selection_to(self, index: _EntryIndex) -> None: ... + def selection_range(self, start: str | int, end: str | int) -> None: ... + def selection_to(self, index: str | int) -> None: ... select_adjust = selection_adjust select_clear = selection_clear select_from = selection_from @@ -1672,158 +2326,162 @@ class Entry(Widget, XView): class Frame(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - class_: str = ..., # can't be changed with configure() - colormap: Literal["new", ""] | Misc = ..., # can't be changed with configure() - container: bool = ..., # can't be changed with configure() - cursor: _Cursor = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 0, + bg: str = ..., + border: float | str = 0, + borderwidth: float | str = 0, + class_: str = "Frame", # can't be changed with configure() + colormap: Literal["new", ""] | Misc = "", # can't be changed with configure() + container: bool = False, # can't be changed with configure() + cursor: _Cursor = "", + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - visual: str | tuple[str, int] = ..., # can't be changed with configure() - width: _ScreenUnits = ..., + padx: float | str = 0, + pady: float | str = 0, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + visual: str | tuple[str, int] = "", # can't be changed with configure() + width: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - width: _ScreenUnits = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Label(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - justify: Literal["left", "center", "right"] = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + image: _Image | str = "", + justify: Literal["left", "center", "right"] = "center", name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", textvariable: Variable = ..., - underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + underline: int = -1, + width: float | str = 0, + wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - compound: _Compound = ..., + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., justify: Literal["left", "center", "right"] = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: Variable = ..., underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = ..., + wraplength: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Listbox(Widget, XView, YView): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, activestyle: Literal["dotbox", "none", "underline"] = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - disabledforeground: _Color = ..., - exportselection: int = ..., - fg: _Color = ..., + background: str = ..., + bd: float | str = 1, + bg: str = ..., + border: float | str = 1, + borderwidth: float | str = 1, + cursor: _Cursor = "", + disabledforeground: str = ..., + exportselection: bool | Literal[0, 1] = 1, + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: int = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - justify: Literal["left", "center", "right"] = ..., + foreground: str = ..., + height: int = 10, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + justify: Literal["left", "center", "right"] = "left", # There's no tkinter.ListVar, but seems like bare tkinter.Variable # actually works for this: # @@ -1835,169 +2493,172 @@ class Listbox(Widget, XView, YView): # ('foo', 'bar', 'baz') listvariable: Variable = ..., name: str = ..., - relief: _Relief = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = 0, + selectforeground: str = ..., # from listbox man page: "The value of the [selectmode] option may be - # arbitrary, but the default bindings expect it to be ..." + # arbitrary, but the default bindings expect it to be either single, + # browse, multiple, or extended" # # I have never seen anyone setting this to something else than what # "the default bindings expect", but let's support it anyway. - selectmode: str = ..., - setgrid: bool = ..., - state: Literal["normal", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - width: int = ..., - xscrollcommand: _XYScrollCommand = ..., - yscrollcommand: _XYScrollCommand = ..., + selectmode: str | Literal["single", "browse", "multiple", "extended"] = "browse", # noqa: Y051 + setgrid: bool = False, + state: Literal["normal", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = "", + yscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, activestyle: Literal["dotbox", "none", "underline"] = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - disabledforeground: _Color = ..., + disabledforeground: str = ..., exportselection: bool = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., height: int = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., justify: Literal["left", "center", "right"] = ..., listvariable: Variable = ..., - relief: _Relief = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., - selectmode: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + selectmode: str | Literal["single", "browse", "multiple", "extended"] = ..., # noqa: Y051 setgrid: bool = ..., state: Literal["normal", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., width: int = ..., - xscrollcommand: _XYScrollCommand = ..., - yscrollcommand: _XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def activate(self, index): ... - def bbox(self, index): ... + def activate(self, index: str | int) -> None: ... + def bbox(self, index: str | int) -> tuple[int, int, int, int] | None: ... # type: ignore[override] def curselection(self): ... - def delete(self, first, last: Any | None = ...): ... - def get(self, first, last: Any | None = ...): ... - def index(self, index): ... - def insert(self, index, *elements): ... + def delete(self, first: str | int, last: str | int | None = None) -> None: ... + def get(self, first: str | int, last: str | int | None = None): ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, *elements: str | float) -> None: ... def nearest(self, y): ... - def scan_mark(self, x, y): ... - def scan_dragto(self, x, y): ... - def see(self, index): ... - def selection_anchor(self, index): ... - select_anchor: Any - def selection_clear(self, first, last: Any | None = ...): ... # type: ignore[override] - select_clear: Any - def selection_includes(self, index): ... - select_includes: Any - def selection_set(self, first, last: Any | None = ...): ... - select_set: Any - def size(self): ... - def itemcget(self, index, option): ... - def itemconfigure(self, index, cnf: Any | None = ..., **kw): ... - itemconfig: Any - -_MenuIndex = Union[str, int] + def scan_mark(self, x, y) -> None: ... + def scan_dragto(self, x, y) -> None: ... + def see(self, index: str | int) -> None: ... + def selection_anchor(self, index: str | int) -> None: ... + select_anchor = selection_anchor + def selection_clear(self, first: str | int, last: str | int | None = None) -> None: ... # type: ignore[override] + select_clear = selection_clear + def selection_includes(self, index: str | int): ... + select_includes = selection_includes + def selection_set(self, first: str | int, last: str | int | None = None) -> None: ... + select_set = selection_set + def size(self) -> int: ... # type: ignore[override] + def itemcget(self, index: str | int, option): ... + def itemconfigure(self, index: str | int, cnf=None, **kw): ... + itemconfig = itemconfigure class Menu(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeborderwidth: _ScreenUnits = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeborderwidth: float | str = ..., + activeforeground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = "arrow", + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., name: str = ..., - postcommand: Callable[[], Any] | str = ..., - relief: _Relief = ..., - selectcolor: _Color = ..., - takefocus: _TakeFocusValue = ..., - tearoff: int = ..., + postcommand: Callable[[], object] | str = "", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + tearoff: bool | Literal[0, 1] = 1, # I guess tearoffcommand arguments are supposed to be widget objects, # but they are widget name strings. Use nametowidget() to handle the # arguments of tearoffcommand. - tearoffcommand: Callable[[str, str], Any] | str = ..., - title: str = ..., - type: Literal["menubar", "tearoff", "normal"] = ..., + tearoffcommand: Callable[[str, str], object] | str = "", + title: str = "", + type: Literal["menubar", "tearoff", "normal"] = "normal", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - activebackground: _Color = ..., - activeborderwidth: _ScreenUnits = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + activebackground: str = ..., + activeborderwidth: float | str = ..., + activeforeground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - postcommand: Callable[[], Any] | str = ..., - relief: _Relief = ..., - selectcolor: _Color = ..., - takefocus: _TakeFocusValue = ..., + foreground: str = ..., + postcommand: Callable[[], object] | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., tearoff: bool = ..., - tearoffcommand: Callable[[str, str], Any] | str = ..., + tearoffcommand: Callable[[str, str], object] | str = ..., title: str = ..., type: Literal["menubar", "tearoff", "normal"] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def tk_popup(self, x: int, y: int, entry: _MenuIndex = ...) -> None: ... - def activate(self, index: _MenuIndex) -> None: ... - def add(self, itemType, cnf=..., **kw): ... # docstring says "Internal function." - def insert(self, index, itemType, cnf=..., **kw): ... # docstring says "Internal function." + def tk_popup(self, x: int, y: int, entry: str | int = "") -> None: ... + def activate(self, index: str | int) -> None: ... + def add(self, itemType, cnf={}, **kw): ... # docstring says "Internal function." + def insert(self, index, itemType, cnf={}, **kw): ... # docstring says "Internal function." def add_cascade( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., label: str = ..., menu: Menu = ..., state: Literal["normal", "active", "disabled"] = ..., @@ -2005,93 +2666,93 @@ class Menu(Widget): ) -> None: ... def add_checkbutton( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., indicatoron: bool = ..., label: str = ..., offvalue: Any = ..., onvalue: Any = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., variable: Variable = ..., ) -> None: ... def add_command( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., label: str = ..., state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., ) -> None: ... def add_radiobutton( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., indicatoron: bool = ..., label: str = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., value: Any = ..., variable: Variable = ..., ) -> None: ... - def add_separator(self, cnf: dict[str, Any] | None = ..., *, background: _Color = ...) -> None: ... + def add_separator(self, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: ... def insert_cascade( self, - index: _MenuIndex, - cnf: dict[str, Any] | None = ..., + index: str | int, + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., label: str = ..., menu: Menu = ..., state: Literal["normal", "active", "disabled"] = ..., @@ -2099,635 +2760,837 @@ class Menu(Widget): ) -> None: ... def insert_checkbutton( self, - index: _MenuIndex, - cnf: dict[str, Any] | None = ..., + index: str | int, + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., indicatoron: bool = ..., label: str = ..., offvalue: Any = ..., onvalue: Any = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., variable: Variable = ..., ) -> None: ... def insert_command( self, - index: _MenuIndex, - cnf: dict[str, Any] | None = ..., + index: str | int, + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., label: str = ..., state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., ) -> None: ... def insert_radiobutton( self, - index: _MenuIndex, - cnf: dict[str, Any] | None = ..., + index: str | int, + cnf: dict[str, Any] | None = {}, *, accelerator: str = ..., - activebackground: _Color = ..., - activeforeground: _Color = ..., - background: _Color = ..., - bitmap: _Bitmap = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., - compound: _Compound = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., hidemargin: bool = ..., - image: _ImageSpec = ..., + image: _Image | str = ..., indicatoron: bool = ..., label: str = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., value: Any = ..., variable: Variable = ..., ) -> None: ... - def insert_separator(self, index: _MenuIndex, cnf: dict[str, Any] | None = ..., *, background: _Color = ...) -> None: ... - def delete(self, index1: _MenuIndex, index2: _MenuIndex | None = ...) -> None: ... - def entrycget(self, index: _MenuIndex, option: str) -> Any: ... + def insert_separator(self, index: str | int, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: ... + def delete(self, index1: str | int, index2: str | int | None = None) -> None: ... + def entrycget(self, index: str | int, option: str) -> Any: ... def entryconfigure( - self, index: _MenuIndex, cnf: dict[str, Any] | None = ..., **kw: Any + self, index: str | int, cnf: dict[str, Any] | None = None, **kw: Any ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... entryconfig = entryconfigure - def index(self, index: _MenuIndex) -> int | None: ... - def invoke(self, index: _MenuIndex) -> Any: ... + def index(self, index: str | int) -> int | None: ... + def invoke(self, index: str | int) -> Any: ... def post(self, x: int, y: int) -> None: ... - def type(self, index: _MenuIndex) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: ... + def type(self, index: str | int) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: ... def unpost(self) -> None: ... - def xposition(self, index: _MenuIndex) -> int: ... - def yposition(self, index: _MenuIndex) -> int: ... + def xposition(self, index: str | int) -> int: ... + def yposition(self, index: str | int) -> int: ... class Menubutton(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - direction: Literal["above", "below", "left", "right", "flush"] = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + image: _Image | str = "", indicatoron: bool = ..., justify: Literal["left", "center", "right"] = ..., menu: Menu = ..., name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", textvariable: Variable = ..., - underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + underline: int = -1, + width: float | str = 0, + wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - compound: _Compound = ..., + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., cursor: _Cursor = ..., direction: Literal["above", "below", "left", "right", "flush"] = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., indicatoron: bool = ..., justify: Literal["left", "center", "right"] = ..., menu: Menu = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: Variable = ..., underline: int = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = ..., + wraplength: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Message(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - anchor: _Anchor = ..., - aspect: int = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - justify: Literal["left", "center", "right"] = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + aspect: int = 150, + background: str = ..., + bd: float | str = 1, + bg: str = ..., + border: float | str = 1, + borderwidth: float | str = 1, + cursor: _Cursor = "", + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + justify: Literal["left", "center", "right"] = "left", name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", textvariable: Variable = ..., # there's width but no height - width: _ScreenUnits = ..., + width: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - anchor: _Anchor = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., aspect: int = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., justify: Literal["left", "center", "right"] = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: Variable = ..., - width: _ScreenUnits = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Radiobutton(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., - cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., - indicatoron: bool = ..., - justify: Literal["left", "center", "right"] = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = "", + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 1, + image: _Image | str = "", + indicatoron: bool = True, + justify: Literal["left", "center", "right"] = "center", name: str = ..., - offrelief: _Relief = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = "", + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + selectcolor: str = ..., + selectimage: _Image | str = "", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", textvariable: Variable = ..., - tristateimage: _ImageSpec = ..., - tristatevalue: Any = ..., - underline: int = ..., - value: Any = ..., + tristateimage: _Image | str = "", + tristatevalue: Any = "", + underline: int = -1, + value: Any = "", variable: Variable | Literal[""] = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = 0, + wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., - *, - activebackground: _Color = ..., - activeforeground: _Color = ..., - anchor: _Anchor = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bitmap: _Bitmap = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - command: _ButtonCommand = ..., - compound: _Compound = ..., + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., cursor: _Cursor = ..., - disabledforeground: _Color = ..., - fg: _Color = ..., + disabledforeground: str = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - image: _ImageSpec = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., indicatoron: bool = ..., justify: Literal["left", "center", "right"] = ..., - offrelief: _Relief = ..., - overrelief: _Relief = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - selectcolor: _Color = ..., - selectimage: _ImageSpec = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: Variable = ..., - tristateimage: _ImageSpec = ..., + tristateimage: _Image | str = ..., tristatevalue: Any = ..., underline: int = ..., value: Any = ..., variable: Variable | Literal[""] = ..., - width: _ScreenUnits = ..., - wraplength: _ScreenUnits = ..., + width: float | str = ..., + wraplength: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def deselect(self): ... - def flash(self): ... + def deselect(self) -> None: ... + def flash(self) -> None: ... def invoke(self) -> Any: ... - def select(self): ... + def select(self) -> None: ... class Scale(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - activebackground: _Color = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - bigincrement: float = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + activebackground: str = ..., + background: str = ..., + bd: float | str = 1, + bg: str = ..., + bigincrement: float = 0.0, + border: float | str = 1, + borderwidth: float | str = 1, # don't know why the callback gets string instead of float - command: str | Callable[[str], Any] = ..., - cursor: _Cursor = ..., - digits: int = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - from_: float = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - label: str = ..., - length: _ScreenUnits = ..., + command: str | Callable[[str], object] = "", + cursor: _Cursor = "", + digits: int = 0, + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + from_: float = 0.0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + label: str = "", + length: float | str = 100, name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - relief: _Relief = ..., - repeatdelay: int = ..., - repeatinterval: int = ..., - resolution: float = ..., - showvalue: bool = ..., - sliderlength: _ScreenUnits = ..., - sliderrelief: _Relief = ..., - state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., - tickinterval: float = ..., - to: float = ..., - troughcolor: _Color = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + repeatdelay: int = 300, + repeatinterval: int = 100, + resolution: float = 1.0, + showvalue: bool = True, + sliderlength: float | str = 30, + sliderrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "raised", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + tickinterval: float = 0.0, + to: float = 100.0, + troughcolor: str = ..., variable: IntVar | DoubleVar = ..., - width: _ScreenUnits = ..., + width: float | str = 15, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - activebackground: _Color = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., + activebackground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., bigincrement: float = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - command: str | Callable[[str], Any] = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[str], object] = ..., cursor: _Cursor = ..., digits: int = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., from_: float = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., label: str = ..., - length: _ScreenUnits = ..., + length: float | str = ..., orient: Literal["horizontal", "vertical"] = ..., - relief: _Relief = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., repeatdelay: int = ..., repeatinterval: int = ..., resolution: float = ..., showvalue: bool = ..., - sliderlength: _ScreenUnits = ..., - sliderrelief: _Relief = ..., + sliderlength: float | str = ..., + sliderrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., state: Literal["normal", "active", "disabled"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., tickinterval: float = ..., to: float = ..., - troughcolor: _Color = ..., + troughcolor: str = ..., variable: IntVar | DoubleVar = ..., - width: _ScreenUnits = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def get(self): ... - def set(self, value): ... - def coords(self, value: Any | None = ...): ... - def identify(self, x, y): ... + def get(self) -> float: ... + def set(self, value) -> None: ... + def coords(self, value: float | None = None) -> tuple[int, int]: ... + def identify(self, x, y) -> Literal["", "slider", "trough1", "trough2"]: ... class Scrollbar(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - activebackground: _Color = ..., - activerelief: _Relief = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + activebackground: str = ..., + activerelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "raised", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., # There are many ways how the command may get called. Search for # 'SCROLLING COMMANDS' in scrollbar man page. There doesn't seem to # be any way to specify an overloaded callback function, so we say # that it can take any args while it can't in reality. - command: Callable[..., tuple[float, float] | None] | str = ..., - cursor: _Cursor = ..., - elementborderwidth: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - jump: bool = ..., + command: Callable[..., tuple[float, float] | None] | str = "", + cursor: _Cursor = "", + elementborderwidth: float | str = -1, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + jump: bool = False, name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - relief: _Relief = ..., - repeatdelay: int = ..., - repeatinterval: int = ..., - takefocus: _TakeFocusValue = ..., - troughcolor: _Color = ..., - width: _ScreenUnits = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = 300, + repeatinterval: int = 100, + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + troughcolor: str = ..., + width: float | str = ..., ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - activebackground: _Color = ..., - activerelief: _Relief = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + activebackground: str = ..., + activerelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., command: Callable[..., tuple[float, float] | None] | str = ..., cursor: _Cursor = ..., - elementborderwidth: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + elementborderwidth: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., jump: bool = ..., orient: Literal["horizontal", "vertical"] = ..., - relief: _Relief = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., repeatdelay: int = ..., repeatinterval: int = ..., - takefocus: _TakeFocusValue = ..., - troughcolor: _Color = ..., - width: _ScreenUnits = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + troughcolor: str = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def activate(self, index: Any | None = ...): ... - def delta(self, deltax, deltay): ... - def fraction(self, x, y): ... - def identify(self, x, y): ... - def get(self): ... - def set(self, first, last): ... + def activate(self, index=None): ... + def delta(self, deltax: int, deltay: int) -> float: ... + def fraction(self, x: int, y: int) -> float: ... + def identify(self, x: int, y: int) -> Literal["arrow1", "arrow2", "slider", "trough1", "trough2", ""]: ... + def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ... + def set(self, first: float | str, last: float | str) -> None: ... -_TextIndex = Union[_tkinter.Tcl_Obj, str, float, Misc] +_WhatToCount: TypeAlias = Literal[ + "chars", "displaychars", "displayindices", "displaylines", "indices", "lines", "xpixels", "ypixels" +] class Text(Widget, XView, YView): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - autoseparators: bool = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - blockcursor: bool = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - endline: int | Literal[""] = ..., - exportselection: bool = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - # width is always int, but height is allowed to be ScreenUnits. + autoseparators: bool = True, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + blockcursor: bool = False, + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = "xterm", + endline: int | Literal[""] = "", + exportselection: bool = True, + fg: str = ..., + font: _FontDescription = "TkFixedFont", + foreground: str = ..., + # width is always int, but height is allowed to be screen units. # This doesn't make any sense to me, and this isn't documented. # The docs seem to say that both should be integers. - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - inactiveselectbackground: _Color = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., - insertunfocussed: Literal["none", "hollow", "solid"] = ..., - insertwidth: _ScreenUnits = ..., - maxundo: int = ..., + height: float | str = 24, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + inactiveselectbackground: str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertunfocussed: Literal["none", "hollow", "solid"] = "none", + insertwidth: float | str = ..., + maxundo: int = 0, name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., - setgrid: bool = ..., - spacing1: _ScreenUnits = ..., - spacing2: _ScreenUnits = ..., - spacing3: _ScreenUnits = ..., - startline: int | Literal[""] = ..., - state: Literal["normal", "disabled"] = ..., + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + setgrid: bool = False, + spacing1: float | str = 0, + spacing2: float | str = 0, + spacing3: float | str = 0, + startline: int | Literal[""] = "", + state: Literal["normal", "disabled"] = "normal", # Literal inside Tuple doesn't actually work - tabs: _ScreenUnits | str | Tuple[_ScreenUnits | str, ...] = ..., - tabstyle: Literal["tabular", "wordprocessor"] = ..., - takefocus: _TakeFocusValue = ..., - undo: bool = ..., - width: int = ..., - wrap: Literal["none", "char", "word"] = ..., - xscrollcommand: _XYScrollCommand = ..., - yscrollcommand: _XYScrollCommand = ..., + tabs: float | str | tuple[float | str, ...] = "", + tabstyle: Literal["tabular", "wordprocessor"] = "tabular", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + undo: bool = False, + width: int = 80, + wrap: Literal["none", "char", "word"] = "char", + xscrollcommand: str | Callable[[float, float], object] = "", + yscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, autoseparators: bool = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., blockcursor: bool = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., endline: int | Literal[""] = ..., exportselection: bool = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - inactiveselectbackground: _Color = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + inactiveselectbackground: str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., insertofftime: int = ..., insertontime: int = ..., insertunfocussed: Literal["none", "hollow", "solid"] = ..., - insertwidth: _ScreenUnits = ..., + insertwidth: float | str = ..., maxundo: int = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., setgrid: bool = ..., - spacing1: _ScreenUnits = ..., - spacing2: _ScreenUnits = ..., - spacing3: _ScreenUnits = ..., + spacing1: float | str = ..., + spacing2: float | str = ..., + spacing3: float | str = ..., startline: int | Literal[""] = ..., state: Literal["normal", "disabled"] = ..., - tabs: _ScreenUnits | str | Tuple[_ScreenUnits | str, ...] = ..., + tabs: float | str | tuple[float | str, ...] = ..., tabstyle: Literal["tabular", "wordprocessor"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., undo: bool = ..., width: int = ..., wrap: Literal["none", "char", "word"] = ..., - xscrollcommand: _XYScrollCommand = ..., - yscrollcommand: _XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def bbox(self, index: _TextIndex) -> tuple[int, int, int, int] | None: ... # type: ignore[override] - def compare(self, index1: _TextIndex, op: Literal["<", "<=", "==", ">=", ">", "!="], index2: _TextIndex) -> bool: ... - def count(self, index1, index2, *args): ... # TODO + def bbox(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def compare( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + op: Literal["<", "<=", "==", ">=", ">", "!="], + index2: str | float | _tkinter.Tcl_Obj | Widget, + ) -> bool: ... + + if sys.version_info >= (3, 13): + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg: _WhatToCount | Literal["update"], + /, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: Literal["update"], + arg2: _WhatToCount, + /, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: Literal["update"], + /, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: _WhatToCount, + /, + *, + return_ints: Literal[True], + ) -> tuple[int, int]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount | Literal["update"], + arg2: _WhatToCount | Literal["update"], + arg3: _WhatToCount | Literal["update"], + /, + *args: _WhatToCount | Literal["update"], + return_ints: Literal[True], + ) -> tuple[int, ...]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + *, + return_ints: Literal[False] = False, + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg: _WhatToCount | Literal["update"], + /, + *, + return_ints: Literal[False] = False, + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: Literal["update"], + arg2: _WhatToCount, + /, + *, + return_ints: Literal[False] = False, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: Literal["update"], + /, + *, + return_ints: Literal[False] = False, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: _WhatToCount, + /, + *, + return_ints: Literal[False] = False, + ) -> tuple[int, int]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount | Literal["update"], + arg2: _WhatToCount | Literal["update"], + arg3: _WhatToCount | Literal["update"], + /, + *args: _WhatToCount | Literal["update"], + return_ints: Literal[False] = False, + ) -> tuple[int, ...]: ... + else: + @overload + def count( + self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg: _WhatToCount | Literal["update"], + /, + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: Literal["update"], + arg2: _WhatToCount, + /, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: Literal["update"], + /, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: _WhatToCount, + /, + ) -> tuple[int, int]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount | Literal["update"], + arg2: _WhatToCount | Literal["update"], + arg3: _WhatToCount | Literal["update"], + /, + *args: _WhatToCount | Literal["update"], + ) -> tuple[int, ...]: ... + @overload - def debug(self, boolean: None = ...) -> bool: ... + def debug(self, boolean: None = None) -> bool: ... @overload def debug(self, boolean: bool) -> None: ... - def delete(self, index1: _TextIndex, index2: _TextIndex | None = ...) -> None: ... - def dlineinfo(self, index: _TextIndex) -> tuple[int, int, int, int, int] | None: ... + + def delete( + self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None + ) -> None: ... + def dlineinfo(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int, int] | None: ... + @overload def dump( self, - index1: _TextIndex, - index2: _TextIndex | None = ..., - command: None = ..., + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + command: None = None, *, all: bool = ..., image: bool = ..., @@ -2739,9 +3602,9 @@ class Text(Widget, XView, YView): @overload def dump( self, - index1: _TextIndex, - index2: _TextIndex | None, - command: Callable[[str, str, str], Any] | str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None, + command: Callable[[str, str, str], object] | str, *, all: bool = ..., image: bool = ..., @@ -2753,10 +3616,10 @@ class Text(Widget, XView, YView): @overload def dump( self, - index1: _TextIndex, - index2: _TextIndex | None = ..., + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, *, - command: Callable[[str, str, str], Any] | str, + command: Callable[[str, str, str], object] | str, all: bool = ..., image: bool = ..., mark: bool = ..., @@ -2764,167 +3627,339 @@ class Text(Widget, XView, YView): text: bool = ..., window: bool = ..., ) -> None: ... + def edit(self, *args): ... # docstring says "Internal method" + @overload - def edit_modified(self, arg: None = ...) -> bool: ... # actually returns Literal[0, 1] + def edit_modified(self, arg: None = None) -> bool: ... # actually returns Literal[0, 1] @overload def edit_modified(self, arg: bool) -> None: ... # actually returns empty string + def edit_redo(self) -> None: ... # actually returns empty string def edit_reset(self) -> None: ... # actually returns empty string def edit_separator(self) -> None: ... # actually returns empty string def edit_undo(self) -> None: ... # actually returns empty string - def get(self, index1: _TextIndex, index2: _TextIndex | None = ...) -> str: ... - # TODO: image_* methods - def image_cget(self, index, option): ... - def image_configure(self, index, cnf: Any | None = ..., **kw): ... - def image_create(self, index, cnf=..., **kw): ... - def image_names(self): ... - def index(self, index: _TextIndex) -> str: ... - def insert(self, index: _TextIndex, chars: str, *args: str | list[str] | Tuple[str, ...]) -> None: ... + def get( + self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None + ) -> str: ... + + @overload + def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["image", "name"]) -> str: ... + @overload + def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["padx", "pady"]) -> int: ... + @overload + def image_cget( + self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["align"] + ) -> Literal["baseline", "bottom", "center", "top"]: ... + @overload + def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ... + + @overload + def image_configure( + self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str + ) -> tuple[str, str, str, str, str | int]: ... + @overload + def image_configure( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = None, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + image: _Image | str = ..., + name: str = ..., + padx: float | str = ..., + pady: float | str = ..., + ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ... + + def image_create( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = {}, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + image: _Image | str = ..., + name: str = ..., + padx: float | str = ..., + pady: float | str = ..., + ) -> str: ... + def image_names(self) -> tuple[str, ...]: ... + def index(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str: ... + def insert( + self, index: str | float | _tkinter.Tcl_Obj | Widget, chars: str, *args: str | list[str] | tuple[str, ...] + ) -> None: ... + @overload - def mark_gravity(self, markName: str, direction: None = ...) -> Literal["left", "right"]: ... + def mark_gravity(self, markName: str, direction: None = None) -> Literal["left", "right"]: ... @overload def mark_gravity(self, markName: str, direction: Literal["left", "right"]) -> None: ... # actually returns empty string - def mark_names(self) -> Tuple[str, ...]: ... - def mark_set(self, markName: str, index: _TextIndex) -> None: ... + + def mark_names(self) -> tuple[str, ...]: ... + def mark_set(self, markName: str, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ... def mark_unset(self, *markNames: str) -> None: ... - def mark_next(self, index: _TextIndex) -> str | None: ... - def mark_previous(self, index: _TextIndex) -> str | None: ... + def mark_next(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str | None: ... + def mark_previous(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str | None: ... # **kw of peer_create is same as the kwargs of Text.__init__ - def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def peer_names(self) -> Tuple[_tkinter.Tcl_Obj, ...]: ... - def replace(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: str | list[str] | Tuple[str, ...]) -> None: ... + def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = {}, **kw) -> None: ... + def peer_names(self) -> tuple[_tkinter.Tcl_Obj, ...]: ... + def replace( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + chars: str, + *args: str | list[str] | tuple[str, ...], + ) -> None: ... def scan_mark(self, x: int, y: int) -> None: ... def scan_dragto(self, x: int, y: int) -> None: ... - def search( - self, - pattern: str, - index: _TextIndex, - stopindex: _TextIndex | None = ..., - forwards: bool | None = ..., - backwards: bool | None = ..., - exact: bool | None = ..., - regexp: bool | None = ..., - nocase: bool | None = ..., - count: Variable | None = ..., - elide: bool | None = ..., - ) -> str: ... # returns empty string for not found - def see(self, index: _TextIndex) -> None: ... - def tag_add(self, tagName: str, index1: _TextIndex, *args: _TextIndex) -> None: ... + if sys.version_info >= (3, 15): + def search( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + *, + nolinestop: bool | None = None, + strictlimits: bool | None = None, + ) -> str: ... # returns empty string for not found + def search_all( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + *, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + nolinestop: bool | None = None, + overlap: bool | None = None, + strictlimits: bool | None = None, + ) -> tuple[_tkinter.Tcl_Obj, ...]: ... + else: + def search( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + ) -> str: ... # returns empty string for not found + + def see(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ... + def tag_add( + self, tagName: str, index1: str | float | _tkinter.Tcl_Obj | Widget, *args: str | float | _tkinter.Tcl_Obj | Widget + ) -> None: ... + # tag_bind stuff is very similar to Canvas @overload def tag_bind( self, tagName: str, sequence: str | None, - func: Callable[[Event[Text]], Any] | None, - add: Literal["", "+"] | bool | None = ..., + func: Callable[[Event[Text]], object] | None, + add: Literal["", "+"] | bool | None = None, ) -> str: ... @overload - def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... - def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = ...) -> None: ... + def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = None) -> None: ... # allowing any string for cget instead of just Literals because there's no other way to look up tag options - def tag_cget(self, tagName: str, option: str) -> Any: ... + def tag_cget(self, tagName: str, option: str): ... + @overload def tag_configure( self, tagName: str, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bgstipple: _Bitmap = ..., - borderwidth: _ScreenUnits = ..., - border: _ScreenUnits = ..., # alias for borderwidth + background: str = ..., + bgstipple: str = ..., + borderwidth: float | str = ..., + border: float | str = ..., # alias for borderwidth elide: bool = ..., - fgstipple: _Bitmap = ..., + fgstipple: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., justify: Literal["left", "right", "center"] = ..., - lmargin1: _ScreenUnits = ..., - lmargin2: _ScreenUnits = ..., - lmargincolor: _Color = ..., - offset: _ScreenUnits = ..., + lmargin1: float | str = ..., + lmargin2: float | str = ..., + lmargincolor: str = ..., + offset: float | str = ..., overstrike: bool = ..., - overstrikefg: _Color = ..., - relief: _Relief = ..., - rmargin: _ScreenUnits = ..., - rmargincolor: _Color = ..., - selectbackground: _Color = ..., - selectforeground: _Color = ..., - spacing1: _ScreenUnits = ..., - spacing2: _ScreenUnits = ..., - spacing3: _ScreenUnits = ..., + overstrikefg: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + rmargin: float | str = ..., + rmargincolor: str = ..., + selectbackground: str = ..., + selectforeground: str = ..., + spacing1: float | str = ..., + spacing2: float | str = ..., + spacing3: float | str = ..., tabs: Any = ..., # the exact type is kind of complicated, see manual page tabstyle: Literal["tabular", "wordprocessor"] = ..., underline: bool = ..., - underlinefg: _Color = ..., + underlinefg: str = ..., wrap: Literal["none", "char", "word"] = ..., # be careful with "none" vs None ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def tag_configure(self, tagName: str, cnf: str) -> tuple[str, str, str, Any, Any]: ... + tag_config = tag_configure - def tag_delete(self, __first_tag_name: str, *tagNames: str) -> None: ... # error if no tag names given - def tag_lower(self, tagName: str, belowThis: str | None = ...) -> None: ... - def tag_names(self, index: _TextIndex | None = ...) -> Tuple[str, ...]: ... - def tag_nextrange(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> tuple[str, str] | tuple[()]: ... - def tag_prevrange(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> tuple[str, str] | tuple[()]: ... - def tag_raise(self, tagName: str, aboveThis: str | None = ...) -> None: ... - def tag_ranges(self, tagName: str) -> Tuple[_tkinter.Tcl_Obj, ...]: ... + def tag_delete(self, first_tag_name: str, /, *tagNames: str) -> None: ... # error if no tag names given + def tag_lower(self, tagName: str, belowThis: str | None = None) -> None: ... + def tag_names(self, index: str | float | _tkinter.Tcl_Obj | Widget | None = None) -> tuple[str, ...]: ... + def tag_nextrange( + self, + tagName: str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + ) -> tuple[str, str] | tuple[()]: ... + def tag_prevrange( + self, + tagName: str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + ) -> tuple[str, str] | tuple[()]: ... + def tag_raise(self, tagName: str, aboveThis: str | None = None) -> None: ... + def tag_ranges(self, tagName: str) -> tuple[_tkinter.Tcl_Obj, ...]: ... # tag_remove and tag_delete are different - def tag_remove(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> None: ... - # TODO: window_* methods - def window_cget(self, index, option): ... - def window_configure(self, index, cnf: Any | None = ..., **kw): ... + def tag_remove( + self, + tagName: str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + ) -> None: ... + + @overload + def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["padx", "pady"]) -> int: ... + @overload + def window_cget( + self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["stretch"] + ) -> bool: ... # actually returns Literal[0, 1] + @overload + def window_cget( + self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["align"] + ) -> Literal["baseline", "bottom", "center", "top"]: ... + @overload # window is set to a widget, but read as the string name. + def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["create", "window"]) -> str: ... + @overload + def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ... + + @overload + def window_configure( + self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str + ) -> tuple[str, str, str, str, str | int]: ... + @overload + def window_configure( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = None, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + create: str = ..., + padx: float | str = ..., + pady: float | str = ..., + stretch: bool | Literal[0, 1] = ..., + window: Misc | str = ..., + ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ... + window_config = window_configure - def window_create(self, index, cnf=..., **kw): ... - def window_names(self): ... + def window_create( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = {}, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + create: str = ..., + padx: float | str = ..., + pady: float | str = ..., + stretch: bool | Literal[0, 1] = ..., + window: Misc | str = ..., + ) -> None: ... + def window_names(self) -> tuple[str, ...]: ... def yview_pickplace(self, *what): ... # deprecated class _setit: - def __init__(self, var, value, callback: Any | None = ...): ... - def __call__(self, *args): ... + def __init__(self, var, value, callback=None) -> None: ... + def __call__(self, *args) -> None: ... # manual page: tk_optionMenu class OptionMenu(Menubutton): - widgetName: Any - menuname: Any - def __init__( - # differs from other widgets - self, - master: Misc | None, - variable: StringVar, - value: str, - *values: str, - # kwarg only from now on - command: Callable[[StringVar], Any] | None = ..., - ) -> None: ... + menuname: Incomplete + if sys.version_info >= (3, 14): + def __init__( + # differs from other widgets + self, + master: Misc | None, + variable: StringVar, + value: str, + *values: str, + command: Callable[[str], object] | None = ..., + name: str | None = None, + ) -> None: ... + else: + def __init__( + # differs from other widgets + self, + master: Misc | None, + variable: StringVar, + value: str, + *values: str, + command: Callable[[str], object] | None = ..., + ) -> None: ... # configure, config, cget are inherited from Menubutton # destroy and __getitem__ are overridden, signature does not change +# This matches tkinter's image classes (PhotoImage and BitmapImage) +# and PIL's tkinter-compatible class (PIL.ImageTk.PhotoImage), +# but not a plain PIL image that isn't tkinter compatible. +# The reason is that PIL has width and height attributes, not methods. +@type_check_only class _Image(Protocol): - tk: _tkinter.TkappType - def height(self) -> int: ... def width(self) -> int: ... + def height(self) -> int: ... + +@type_check_only +class _BitmapImageLike(_Image): ... -class Image: - name: Any +@type_check_only +class _PhotoImageLike(_Image): ... + +class Image(_Image): + name: Incomplete tk: _tkinter.TkappType - def __init__(self, imgtype, name: Any | None = ..., cnf=..., master: Misc | _tkinter.TkappType | None = ..., **kw): ... - def __del__(self): ... - def __setitem__(self, key, value): ... + if sys.version_info >= (3, 15): + __iter__: ClassVar[None] # prevent using __getitem__ for iteration + + def __init__(self, imgtype, name=None, cnf={}, master: Misc | _tkinter.TkappType | None = None, **kw) -> None: ... + def __del__(self) -> None: ... + def __setitem__(self, key, value) -> None: ... def __getitem__(self, key): ... - configure: Any - config: Any - def height(self) -> int: ... + configure: Incomplete + config: Incomplete def type(self): ... - def width(self) -> int: ... -class PhotoImage(Image): +class PhotoImage(Image, _PhotoImageLike): + # This should be kept in sync with PIL.ImageTK.PhotoImage.__init__() def __init__( self, - name: str | None = ..., - cnf: dict[str, Any] = ..., - master: Misc | _tkinter.TkappType | None = ..., + name: str | None = None, + cnf: dict[str, Any] = {}, + master: Misc | _tkinter.TkappType | None = None, *, data: str | bytes = ..., # not same as data argument of put() format: str = ..., @@ -2949,323 +3984,393 @@ class PhotoImage(Image): def blank(self) -> None: ... def cget(self, option: str) -> str: ... def __getitem__(self, key: str) -> str: ... # always string: image['height'] can be '0' - def copy(self) -> PhotoImage: ... - def zoom(self, x: int, y: int | Literal[""] = ...) -> PhotoImage: ... - def subsample(self, x: int, y: int | Literal[""] = ...) -> PhotoImage: ... + if sys.version_info >= (3, 13): + def copy( + self, + *, + from_coords: Iterable[int] | None = None, + zoom: int | tuple[int, int] | list[int] | None = None, + subsample: int | tuple[int, int] | list[int] | None = None, + ) -> PhotoImage: ... + def subsample(self, x: int, y: int | Literal[""] = "", *, from_coords: Iterable[int] | None = None) -> PhotoImage: ... + def zoom(self, x: int, y: int | Literal[""] = "", *, from_coords: Iterable[int] | None = None) -> PhotoImage: ... + def copy_replace( + self, + sourceImage: PhotoImage | str, + *, + from_coords: Iterable[int] | None = None, + to: Iterable[int] | None = None, + shrink: bool = False, + zoom: int | tuple[int, int] | list[int] | None = None, + subsample: int | tuple[int, int] | list[int] | None = None, + # `None` defaults to overlay. + compositingrule: Literal["overlay", "set"] | None = None, + ) -> None: ... + else: + def copy(self) -> PhotoImage: ... + def zoom(self, x: int, y: int | Literal[""] = "") -> PhotoImage: ... + def subsample(self, x: int, y: int | Literal[""] = "") -> PhotoImage: ... + def get(self, x: int, y: int) -> tuple[int, int, int]: ... def put( self, data: ( str + | bytes | list[str] - | list[list[_Color]] - | list[Tuple[_Color, ...]] - | Tuple[str, ...] - | Tuple[list[_Color], ...] - | Tuple[Tuple[_Color, ...], ...] + | list[list[str]] + | list[tuple[str, ...]] + | tuple[str, ...] + | tuple[list[str], ...] + | tuple[tuple[str, ...], ...] ), - to: tuple[int, int] | None = ..., + to: tuple[int, int] | tuple[int, int, int, int] | None = None, ) -> None: ... - def write(self, filename: StrOrBytesPath, format: str | None = ..., from_coords: tuple[int, int] | None = ...) -> None: ... - if sys.version_info >= (3, 8): - def transparency_get(self, x: int, y: int) -> bool: ... - def transparency_set(self, x: int, y: int, boolean: bool) -> None: ... + if sys.version_info >= (3, 13): + def read( + self, + filename: StrOrBytesPath, + format: str | None = None, + *, + from_coords: Iterable[int] | None = None, + to: Iterable[int] | None = None, + shrink: bool = False, + ) -> None: ... + def write( + self, + filename: StrOrBytesPath, + format: str | None = None, + from_coords: Iterable[int] | None = None, + *, + background: str | None = None, + grayscale: bool = False, + ) -> None: ... + + @overload + def data( + self, format: str, *, from_coords: Iterable[int] | None = None, background: str | None = None, grayscale: bool = False + ) -> bytes: ... + @overload + def data( + self, + format: None = None, + *, + from_coords: Iterable[int] | None = None, + background: str | None = None, + grayscale: bool = False, + ) -> tuple[str, ...]: ... -class BitmapImage(Image): + else: + def write( + self, filename: StrOrBytesPath, format: str | None = None, from_coords: tuple[int, int] | None = None + ) -> None: ... + + def transparency_get(self, x: int, y: int) -> bool: ... + def transparency_set(self, x: int, y: int, boolean: bool) -> None: ... + +class BitmapImage(Image, _BitmapImageLike): + # This should be kept in sync with PIL.ImageTK.BitmapImage.__init__() def __init__( self, - name: Any | None = ..., - cnf: dict[str, Any] = ..., - master: Misc | _tkinter.TkappType | None = ..., + name=None, + cnf: dict[str, Any] = {}, + master: Misc | _tkinter.TkappType | None = None, *, - background: _Color = ..., + background: str = ..., data: str | bytes = ..., file: StrOrBytesPath = ..., - foreground: _Color = ..., + foreground: str = ..., maskdata: str = ..., maskfile: StrOrBytesPath = ..., ) -> None: ... -def image_names() -> Tuple[str, ...]: ... -def image_types() -> Tuple[str, ...]: ... +def image_names() -> tuple[str, ...]: ... +def image_types() -> tuple[str, ...]: ... class Spinbox(Widget, XView): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - activebackground: _Color = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - buttonbackground: _Color = ..., - buttoncursor: _Cursor = ..., - buttondownrelief: _Relief = ..., - buttonuprelief: _Relief = ..., + activebackground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + buttonbackground: str = ..., + buttoncursor: _Cursor = "", + buttondownrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + buttonuprelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., # percent substitutions don't seem to be supported, it's similar to Entry's validation stuff - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., - cursor: _Cursor = ..., - disabledbackground: _Color = ..., - disabledforeground: _Color = ..., - exportselection: bool = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - format: str = ..., - from_: float = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., - increment: float = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., - insertofftime: int = ..., - insertontime: int = ..., - insertwidth: _ScreenUnits = ..., - invalidcommand: _EntryValidateCommand = ..., - invcmd: _EntryValidateCommand = ..., - justify: Literal["left", "center", "right"] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = "", + cursor: _Cursor = "xterm", + disabledbackground: str = ..., + disabledforeground: str = ..., + exportselection: bool = True, + fg: str = ..., + font: _FontDescription = "TkTextFont", + foreground: str = ..., + format: str = "", + from_: float = 0.0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + increment: float = 1.0, + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = "", + invcmd: str | list[str] | tuple[str, ...] | Callable[[], object] = "", + justify: Literal["left", "center", "right"] = "left", name: str = ..., - readonlybackground: _Color = ..., - relief: _Relief = ..., - repeatdelay: int = ..., - repeatinterval: int = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., - state: Literal["normal", "disabled", "readonly"] = ..., - takefocus: _TakeFocusValue = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "sunken", + repeatdelay: int = 400, + repeatinterval: int = 100, + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + state: Literal["normal", "disabled", "readonly"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", textvariable: Variable = ..., - to: float = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: _EntryValidateCommand = ..., - vcmd: _EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., - width: int = ..., - wrap: bool = ..., - xscrollcommand: _XYScrollCommand = ..., + to: float = 0.0, + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + values: list[str] | tuple[str, ...] = ..., + width: int = 20, + wrap: bool = False, + xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - activebackground: _Color = ..., - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - buttonbackground: _Color = ..., + activebackground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + buttonbackground: str = ..., buttoncursor: _Cursor = ..., - buttondownrelief: _Relief = ..., - buttonuprelief: _Relief = ..., - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., + buttondownrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + buttonuprelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., cursor: _Cursor = ..., - disabledbackground: _Color = ..., - disabledforeground: _Color = ..., + disabledbackground: str = ..., + disabledforeground: str = ..., exportselection: bool = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., + foreground: str = ..., format: str = ..., from_: float = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., increment: float = ..., - insertbackground: _Color = ..., - insertborderwidth: _ScreenUnits = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., insertofftime: int = ..., insertontime: int = ..., - insertwidth: _ScreenUnits = ..., - invalidcommand: _EntryValidateCommand = ..., - invcmd: _EntryValidateCommand = ..., + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., + invcmd: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., justify: Literal["left", "center", "right"] = ..., - readonlybackground: _Color = ..., - relief: _Relief = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., repeatdelay: int = ..., repeatinterval: int = ..., - selectbackground: _Color = ..., - selectborderwidth: _ScreenUnits = ..., - selectforeground: _Color = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., state: Literal["normal", "disabled", "readonly"] = ..., - takefocus: _TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: Variable = ..., to: float = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: _EntryValidateCommand = ..., - vcmd: _EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., wrap: bool = ..., - xscrollcommand: _XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def bbox(self, index): ... - def delete(self, first, last: Any | None = ...): ... - def get(self): ... + def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def delete(self, first, last=None) -> Literal[""]: ... + def get(self) -> str: ... def icursor(self, index): ... - def identify(self, x, y): ... - def index(self, index): ... - def insert(self, index, s): ... + def identify(self, x: int, y: int) -> Literal["", "buttondown", "buttonup", "entry"]: ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, s: str) -> Literal[""]: ... # spinbox.invoke("asdf") gives error mentioning .invoke("none"), but it's not documented def invoke(self, element: Literal["none", "buttonup", "buttondown"]) -> Literal[""]: ... def scan(self, *args): ... def scan_mark(self, x): ... def scan_dragto(self, x): ... - def selection(self, *args: Any) -> Tuple[int, ...]: ... + def selection(self, *args) -> tuple[int, ...]: ... def selection_adjust(self, index): ... - def selection_clear(self): ... - def selection_element(self, element: Any | None = ...): ... - if sys.version_info >= (3, 8): - def selection_from(self, index: int) -> None: ... - def selection_present(self) -> None: ... - def selection_range(self, start: int, end: int) -> None: ... - def selection_to(self, index: int) -> None: ... + def selection_clear(self): ... # type: ignore[override] + def selection_element(self, element=None): ... + def selection_from(self, index: int) -> None: ... + def selection_present(self) -> None: ... + def selection_range(self, start: int, end: int) -> None: ... + def selection_to(self, index: int) -> None: ... class LabelFrame(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., - *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - class_: str = ..., # can't be changed with configure() - colormap: Literal["new", ""] | Misc = ..., # can't be changed with configure() - container: bool = ..., # undocumented, can't be changed with configure() - cursor: _Cursor = ..., - fg: _Color = ..., - font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 2, + bg: str = ..., + border: float | str = 2, + borderwidth: float | str = 2, + class_: str = "Labelframe", # can't be changed with configure() + colormap: Literal["new", ""] | Misc = "", # can't be changed with configure() + container: bool = False, # undocumented, can't be changed with configure() + cursor: _Cursor = "", + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, # 'ne' and 'en' are valid labelanchors, but only 'ne' is a valid _Anchor. - labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = "nw", labelwidget: Misc = ..., name: str = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., - text: float | str = ..., - visual: str | tuple[str, int] = ..., # can't be changed with configure() - width: _ScreenUnits = ..., + padx: float | str = 0, + pady: float | str = 0, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "groove", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", + visual: str | tuple[str, int] = "", # can't be changed with configure() + width: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - fg: _Color = ..., + fg: str = ..., font: _FontDescription = ..., - foreground: _Color = ..., - height: _ScreenUnits = ..., - highlightbackground: _Color = ..., - highlightcolor: _Color = ..., - highlightthickness: _ScreenUnits = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., labelwidget: Misc = ..., - padx: _ScreenUnits = ..., - pady: _ScreenUnits = ..., - relief: _Relief = ..., - takefocus: _TakeFocusValue = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., - width: _ScreenUnits = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class PanedWindow(Widget): def __init__( self, - master: Misc | None = ..., - cnf: dict[str, Any] | None = ..., + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., - cursor: _Cursor = ..., - handlepad: _ScreenUnits = ..., - handlesize: _ScreenUnits = ..., - height: _ScreenUnits = ..., + background: str = ..., + bd: float | str = 1, + bg: str = ..., + border: float | str = 1, + borderwidth: float | str = 1, + cursor: _Cursor = "", + handlepad: float | str = 8, + handlesize: float | str = 8, + height: float | str = "", name: str = ..., - opaqueresize: bool = ..., - orient: Literal["horizontal", "vertical"] = ..., - proxybackground: _Color = ..., - proxyborderwidth: _ScreenUnits = ..., - proxyrelief: _Relief = ..., - relief: _Relief = ..., - sashcursor: _Cursor = ..., - sashpad: _ScreenUnits = ..., - sashrelief: _Relief = ..., - sashwidth: _ScreenUnits = ..., - showhandle: bool = ..., - width: _ScreenUnits = ..., + opaqueresize: bool = True, + orient: Literal["horizontal", "vertical"] = "horizontal", + proxybackground: str = "", + proxyborderwidth: float | str = 2, + proxyrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + sashcursor: _Cursor = "", + sashpad: float | str = 0, + sashrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + sashwidth: float | str = 3, + showhandle: bool = False, + width: float | str = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: _Color = ..., - bd: _ScreenUnits = ..., - bg: _Color = ..., - border: _ScreenUnits = ..., - borderwidth: _ScreenUnits = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: _Cursor = ..., - handlepad: _ScreenUnits = ..., - handlesize: _ScreenUnits = ..., - height: _ScreenUnits = ..., + handlepad: float | str = ..., + handlesize: float | str = ..., + height: float | str = ..., opaqueresize: bool = ..., orient: Literal["horizontal", "vertical"] = ..., - proxybackground: _Color = ..., - proxyborderwidth: _ScreenUnits = ..., - proxyrelief: _Relief = ..., - relief: _Relief = ..., + proxybackground: str = ..., + proxyborderwidth: float | str = ..., + proxyrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., sashcursor: _Cursor = ..., - sashpad: _ScreenUnits = ..., - sashrelief: _Relief = ..., - sashwidth: _ScreenUnits = ..., + sashpad: float | str = ..., + sashrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + sashwidth: float | str = ..., showhandle: bool = ..., - width: _ScreenUnits = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def add(self, child: Widget, **kw): ... - def remove(self, child): ... - forget: Any - def identify(self, x, y): ... - def proxy(self, *args): ... - def proxy_coord(self): ... - def proxy_forget(self): ... - def proxy_place(self, x, y): ... - def sash(self, *args): ... - def sash_coord(self, index): ... - def sash_mark(self, index): ... - def sash_place(self, index, x, y): ... + def add(self, child: Widget, **kw) -> None: ... + def remove(self, child) -> None: ... + forget = remove # type: ignore[assignment] + def identify(self, x: int, y: int): ... + def proxy(self, *args) -> tuple[Incomplete, ...]: ... + def proxy_coord(self) -> tuple[Incomplete, ...]: ... + def proxy_forget(self) -> tuple[Incomplete, ...]: ... + def proxy_place(self, x, y) -> tuple[Incomplete, ...]: ... + def sash(self, *args) -> tuple[Incomplete, ...]: ... + def sash_coord(self, index) -> tuple[Incomplete, ...]: ... + def sash_mark(self, index) -> tuple[Incomplete, ...]: ... + def sash_place(self, index, x, y) -> tuple[Incomplete, ...]: ... def panecget(self, child, option): ... - def paneconfigure(self, tagOrId, cnf: Any | None = ..., **kw): ... - paneconfig: Any + def paneconfigure(self, tagOrId, cnf=None, **kw): ... + paneconfig = paneconfigure def panes(self): ... + +def _test() -> None: ... diff --git a/stdlib/tkinter/colorchooser.pyi b/stdlib/tkinter/colorchooser.pyi index b5fdc7c54914..d0d6de842656 100644 --- a/stdlib/tkinter/colorchooser.pyi +++ b/stdlib/tkinter/colorchooser.pyi @@ -1,7 +1,12 @@ +from tkinter import Misc from tkinter.commondialog import Dialog -from typing import Any, ClassVar +from typing import ClassVar + +__all__ = ["Chooser", "askcolor"] class Chooser(Dialog): command: ClassVar[str] -def askcolor(color: str | bytes | None = ..., **options: Any) -> tuple[None, None] | tuple[tuple[float, float, float], str]: ... +def askcolor( + color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ... +) -> tuple[None, None] | tuple[tuple[int, int, int], str]: ... diff --git a/stdlib/tkinter/commondialog.pyi b/stdlib/tkinter/commondialog.pyi index aee58111c73f..6dba6bd60928 100644 --- a/stdlib/tkinter/commondialog.pyi +++ b/stdlib/tkinter/commondialog.pyi @@ -1,8 +1,14 @@ -from typing import Any, ClassVar, Mapping +from collections.abc import Mapping +from tkinter import Misc +from typing import Any, ClassVar + +__all__ = ["Dialog"] class Dialog: command: ClassVar[str | None] - master: Any | None + master: Misc | None + # Types of options are very dynamic. They depend on the command and are + # sometimes changed to a different type. options: Mapping[str, Any] - def __init__(self, master: Any | None = ..., **options) -> None: ... - def show(self, **options) -> Any: ... + def __init__(self, master: Misc | None = None, **options: Any) -> None: ... + def show(self, **options: Any) -> Any: ... diff --git a/stdlib/tkinter/constants.pyi b/stdlib/tkinter/constants.pyi index 1383b0f9bf4b..eb1ef446cf22 100644 --- a/stdlib/tkinter/constants.pyi +++ b/stdlib/tkinter/constants.pyi @@ -1,80 +1,80 @@ -from typing_extensions import Literal +from typing import Final # These are not actually bools. See #4669 -NO: bool -YES: bool -TRUE: bool -FALSE: bool -ON: bool -OFF: bool -N: Literal["n"] -S: Literal["s"] -W: Literal["w"] -E: Literal["e"] -NW: Literal["nw"] -SW: Literal["sw"] -NE: Literal["ne"] -SE: Literal["se"] -NS: Literal["ns"] -EW: Literal["ew"] -NSEW: Literal["nsew"] -CENTER: Literal["center"] -NONE: Literal["none"] -X: Literal["x"] -Y: Literal["y"] -BOTH: Literal["both"] -LEFT: Literal["left"] -TOP: Literal["top"] -RIGHT: Literal["right"] -BOTTOM: Literal["bottom"] -RAISED: Literal["raised"] -SUNKEN: Literal["sunken"] -FLAT: Literal["flat"] -RIDGE: Literal["ridge"] -GROOVE: Literal["groove"] -SOLID: Literal["solid"] -HORIZONTAL: Literal["horizontal"] -VERTICAL: Literal["vertical"] -NUMERIC: Literal["numeric"] -CHAR: Literal["char"] -WORD: Literal["word"] -BASELINE: Literal["baseline"] -INSIDE: Literal["inside"] -OUTSIDE: Literal["outside"] -SEL: Literal["sel"] -SEL_FIRST: Literal["sel.first"] -SEL_LAST: Literal["sel.last"] -END: Literal["end"] -INSERT: Literal["insert"] -CURRENT: Literal["current"] -ANCHOR: Literal["anchor"] -ALL: Literal["all"] -NORMAL: Literal["normal"] -DISABLED: Literal["disabled"] -ACTIVE: Literal["active"] -HIDDEN: Literal["hidden"] -CASCADE: Literal["cascade"] -CHECKBUTTON: Literal["checkbutton"] -COMMAND: Literal["command"] -RADIOBUTTON: Literal["radiobutton"] -SEPARATOR: Literal["separator"] -SINGLE: Literal["single"] -BROWSE: Literal["browse"] -MULTIPLE: Literal["multiple"] -EXTENDED: Literal["extended"] -DOTBOX: Literal["dotbox"] -UNDERLINE: Literal["underline"] -PIESLICE: Literal["pieslice"] -CHORD: Literal["chord"] -ARC: Literal["arc"] -FIRST: Literal["first"] -LAST: Literal["last"] -BUTT: Literal["butt"] -PROJECTING: Literal["projecting"] -ROUND: Literal["round"] -BEVEL: Literal["bevel"] -MITER: Literal["miter"] -MOVETO: Literal["moveto"] -SCROLL: Literal["scroll"] -UNITS: Literal["units"] -PAGES: Literal["pages"] +YES: Final = True +NO: Final = False +TRUE: Final = True +FALSE: Final = False +ON: Final = True +OFF: Final = False +N: Final = "n" +S: Final = "s" +W: Final = "w" +E: Final = "e" +NW: Final = "nw" +SW: Final = "sw" +NE: Final = "ne" +SE: Final = "se" +NS: Final = "ns" +EW: Final = "ew" +NSEW: Final = "nsew" +CENTER: Final = "center" +NONE: Final = "none" +X: Final = "x" +Y: Final = "y" +BOTH: Final = "both" +LEFT: Final = "left" +TOP: Final = "top" +RIGHT: Final = "right" +BOTTOM: Final = "bottom" +RAISED: Final = "raised" +SUNKEN: Final = "sunken" +FLAT: Final = "flat" +RIDGE: Final = "ridge" +GROOVE: Final = "groove" +SOLID: Final = "solid" +HORIZONTAL: Final = "horizontal" +VERTICAL: Final = "vertical" +NUMERIC: Final = "numeric" +CHAR: Final = "char" +WORD: Final = "word" +BASELINE: Final = "baseline" +INSIDE: Final = "inside" +OUTSIDE: Final = "outside" +SEL: Final = "sel" +SEL_FIRST: Final = "sel.first" +SEL_LAST: Final = "sel.last" +END: Final = "end" +INSERT: Final = "insert" +CURRENT: Final = "current" +ANCHOR: Final = "anchor" +ALL: Final = "all" +NORMAL: Final = "normal" +DISABLED: Final = "disabled" +ACTIVE: Final = "active" +HIDDEN: Final = "hidden" +CASCADE: Final = "cascade" +CHECKBUTTON: Final = "checkbutton" +COMMAND: Final = "command" +RADIOBUTTON: Final = "radiobutton" +SEPARATOR: Final = "separator" +SINGLE: Final = "single" +BROWSE: Final = "browse" +MULTIPLE: Final = "multiple" +EXTENDED: Final = "extended" +DOTBOX: Final = "dotbox" +UNDERLINE: Final = "underline" +PIESLICE: Final = "pieslice" +CHORD: Final = "chord" +ARC: Final = "arc" +FIRST: Final = "first" +LAST: Final = "last" +BUTT: Final = "butt" +PROJECTING: Final = "projecting" +ROUND: Final = "round" +BEVEL: Final = "bevel" +MITER: Final = "miter" +MOVETO: Final = "moveto" +SCROLL: Final = "scroll" +UNITS: Final = "units" +PAGES: Final = "pages" diff --git a/stdlib/tkinter/dialog.pyi b/stdlib/tkinter/dialog.pyi index bc927e1f24ac..971b64f09125 100644 --- a/stdlib/tkinter/dialog.pyi +++ b/stdlib/tkinter/dialog.pyi @@ -1,10 +1,13 @@ +from collections.abc import Mapping from tkinter import Widget -from typing import Any, Mapping +from typing import Any, Final -DIALOG_ICON: str +__all__ = ["Dialog"] + +DIALOG_ICON: Final = "questhead" class Dialog(Widget): widgetName: str num: int - def __init__(self, master: Any | None = ..., cnf: Mapping[str, Any] = ..., **kw) -> None: ... + def __init__(self, master=None, cnf: Mapping[str, Any] = {}, **kw) -> None: ... def destroy(self) -> None: ... diff --git a/stdlib/tkinter/dnd.pyi b/stdlib/tkinter/dnd.pyi index 339291a20d0f..521f451a9b2c 100644 --- a/stdlib/tkinter/dnd.pyi +++ b/stdlib/tkinter/dnd.pyi @@ -1,15 +1,19 @@ from tkinter import Event, Misc, Tk, Widget -from typing import ClassVar, Protocol +from typing import ClassVar, Protocol, type_check_only +__all__ = ["dnd_start", "DndHandler"] + +@type_check_only class _DndSource(Protocol): - def dnd_end(self, target: Widget | None, event: Event[Misc] | None) -> None: ... + def dnd_end(self, target: Widget | None, event: Event[Misc] | None, /) -> None: ... class DndHandler: root: ClassVar[Tk | None] def __init__(self, source: _DndSource, event: Event[Misc]) -> None: ... - def cancel(self, event: Event[Misc] | None = ...) -> None: ... - def finish(self, event: Event[Misc] | None, commit: int = ...) -> None: ... + def cancel(self, event: Event[Misc] | None = None) -> None: ... + def finish(self, event: Event[Misc] | None, commit: int = 0) -> None: ... def on_motion(self, event: Event[Misc]) -> None: ... def on_release(self, event: Event[Misc]) -> None: ... + def __del__(self) -> None: ... -def dnd_start(source, event) -> DndHandler | None: ... +def dnd_start(source: _DndSource, event: Event[Misc]) -> DndHandler | None: ... diff --git a/stdlib/tkinter/filedialog.pyi b/stdlib/tkinter/filedialog.pyi index 0fc7d6e8a3bc..b6ef8f45d035 100644 --- a/stdlib/tkinter/filedialog.pyi +++ b/stdlib/tkinter/filedialog.pyi @@ -1,14 +1,30 @@ -from _typeshed import StrOrBytesPath -from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog -from typing import IO, Any, ClassVar, Iterable, Tuple -from typing_extensions import Literal +from _typeshed import Incomplete, StrOrBytesPath, StrPath +from collections.abc import Hashable, Iterable +from tkinter import Button, Entry, Event, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog +from typing import IO, ClassVar, Literal -dialogstates: dict[Any, tuple[Any, Any]] +__all__ = [ + "FileDialog", + "LoadFileDialog", + "SaveFileDialog", + "Open", + "SaveAs", + "Directory", + "askopenfilename", + "asksaveasfilename", + "askopenfilenames", + "askopenfile", + "askopenfiles", + "asksaveasfile", + "askdirectory", +] + +dialogstates: dict[Hashable, tuple[str, str]] class FileDialog: title: str - master: Any - directory: Any | None + master: Misc + directory: str | None top: Toplevel botframe: Frame selection: Entry @@ -22,23 +38,23 @@ class FileDialog: filter_button: Button cancel_button: Button def __init__( - self, master, title: Any | None = ... + self, master: Misc, title: str | None = None ) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either - how: Any | None - def go(self, dir_or_file: Any = ..., pattern: str = ..., default: str = ..., key: Any | None = ...): ... - def quit(self, how: Any | None = ...) -> None: ... - def dirs_double_event(self, event) -> None: ... - def dirs_select_event(self, event) -> None: ... - def files_double_event(self, event) -> None: ... - def files_select_event(self, event) -> None: ... - def ok_event(self, event) -> None: ... + how: str | None + def go(self, dir_or_file: StrPath = ".", pattern: StrPath = "*", default: StrPath = "", key: Hashable | None = None): ... + def quit(self, how: str | None = None) -> None: ... + def dirs_double_event(self, event: Event) -> None: ... + def dirs_select_event(self, event: Event) -> None: ... + def files_double_event(self, event: Event) -> None: ... + def files_select_event(self, event: Event) -> None: ... + def ok_event(self, event: Event) -> None: ... def ok_command(self) -> None: ... - def filter_command(self, event: Any | None = ...) -> None: ... - def get_filter(self): ... - def get_selection(self): ... - def cancel_command(self, event: Any | None = ...) -> None: ... - def set_filter(self, dir, pat) -> None: ... - def set_selection(self, file) -> None: ... + def filter_command(self, event: Event | None = None) -> None: ... + def get_filter(self) -> tuple[str, str]: ... + def get_selection(self) -> str: ... + def cancel_command(self, event: Event | None = None) -> None: ... + def set_filter(self, dir: StrPath, pat: StrPath) -> None: ... + def set_selection(self, file: StrPath) -> None: ... class LoadFileDialog(FileDialog): title: str @@ -46,7 +62,7 @@ class LoadFileDialog(FileDialog): class SaveFileDialog(FileDialog): title: str - def ok_command(self): ... + def ok_command(self) -> None: ... class _Dialog(commondialog.Dialog): ... @@ -62,9 +78,9 @@ class Directory(commondialog.Dialog): # TODO: command kwarg available on macos def asksaveasfilename( *, - confirmoverwrite: bool | None = ..., - defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + confirmoverwrite: bool | None = True, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., @@ -73,8 +89,8 @@ def asksaveasfilename( ) -> str: ... # can be empty string def askopenfilename( *, - defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., @@ -83,51 +99,51 @@ def askopenfilename( ) -> str: ... # can be empty string def askopenfilenames( *, - defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> Literal[""] | Tuple[str, ...]: ... +) -> Literal[""] | tuple[str, ...]: ... def askdirectory( - *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = ..., parent: Misc | None = ..., title: str | None = ... + *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = False, parent: Misc | None = ..., title: str | None = ... ) -> str: ... # can be empty string # TODO: If someone actually uses these, overload to have the actual return type of open(..., mode) def asksaveasfile( - mode: str = ..., + mode: str = "w", *, - confirmoverwrite: bool | None = ..., - defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + confirmoverwrite: bool | None = True, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> IO[Any] | None: ... +) -> IO[Incomplete] | None: ... def askopenfile( - mode: str = ..., + mode: str = "r", *, - defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> IO[Any] | None: ... +) -> IO[Incomplete] | None: ... def askopenfiles( - mode: str = ..., + mode: str = "r", *, - defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> Tuple[IO[Any], ...]: ... # can be empty tuple +) -> tuple[IO[Incomplete], ...]: ... # can be empty tuple def test() -> None: ... diff --git a/stdlib/tkinter/font.pyi b/stdlib/tkinter/font.pyi index fccc0fbf1f0a..72552eb8e251 100644 --- a/stdlib/tkinter/font.pyi +++ b/stdlib/tkinter/font.pyi @@ -1,26 +1,29 @@ import _tkinter +import itertools import sys import tkinter -from typing import Any, List, Tuple, Union, overload -from typing_extensions import Literal, TypedDict +from typing import Any, ClassVar, Final, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Unpack -NORMAL: Literal["normal"] -ROMAN: Literal["roman"] -BOLD: Literal["bold"] -ITALIC: Literal["italic"] +__all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] -_FontDescription = Union[ - # "Helvetica 12" - str, - # A font object constructed in Python - Font, - # ("Helvetica", 12, BOLD) - List[Any], - Tuple[Any, ...], - # A font object constructed in Tcl - _tkinter.Tcl_Obj, -] +NORMAL: Final = "normal" +ROMAN: Final = "roman" +BOLD: Final = "bold" +ITALIC: Final = "italic" +_FontDescription: TypeAlias = ( + str # "Helvetica 12" + | Font # A font object constructed in Python + | list[Any] # ["Helvetica", 12, BOLD] + | tuple[str] # ("Liberation Sans",) needs wrapping in tuple/list to handle spaces + # ("Liberation Sans", 12) or ("Liberation Sans", 12, "bold", "italic", "underline") + | tuple[str, int, Unpack[tuple[str, ...]]] # Any number of trailing options is permitted + | tuple[str, int, list[str] | tuple[str, ...]] # Options can also be passed as list/tuple + | _tkinter.Tcl_Obj # A font object constructed in Tcl +) + +@type_check_only class _FontDict(TypedDict): family: str size: int @@ -29,6 +32,7 @@ class _FontDict(TypedDict): underline: bool overstrike: bool +@type_check_only class _MetricsDict(TypedDict): ascent: int descent: int @@ -38,14 +42,17 @@ class _MetricsDict(TypedDict): class Font: name: str delete_font: bool + if sys.version_info >= (3, 15): + __iter__: ClassVar[None] # prevent using __getitem__ for iteration + counter: ClassVar[itertools.count[int]] # undocumented def __init__( self, # In tkinter, 'root' refers to tkinter.Tk by convention, but the code # actually works with any tkinter widget so we use tkinter.Misc. - root: tkinter.Misc | None = ..., - font: _FontDescription | None = ..., - name: str | None = ..., - exists: bool = ..., + root: tkinter.Misc | None = None, + font: _FontDescription | None = None, + name: str | None = None, + exists: bool = False, *, family: str = ..., size: int = ..., @@ -54,7 +61,9 @@ class Font: underline: bool = ..., overstrike: bool = ..., ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] def __setitem__(self, key: str, value: Any) -> None: ... + @overload def cget(self, option: Literal["family"]) -> str: ... @overload @@ -67,21 +76,24 @@ class Font: def cget(self, option: Literal["underline", "overstrike"]) -> bool: ... @overload def cget(self, option: str) -> Any: ... + __getitem__ = cget + @overload - def actual(self, option: Literal["family"], displayof: tkinter.Misc | None = ...) -> str: ... + def actual(self, option: Literal["family"], displayof: tkinter.Misc | None = None) -> str: ... @overload - def actual(self, option: Literal["size"], displayof: tkinter.Misc | None = ...) -> int: ... + def actual(self, option: Literal["size"], displayof: tkinter.Misc | None = None) -> int: ... @overload - def actual(self, option: Literal["weight"], displayof: tkinter.Misc | None = ...) -> Literal["normal", "bold"]: ... + def actual(self, option: Literal["weight"], displayof: tkinter.Misc | None = None) -> Literal["normal", "bold"]: ... @overload - def actual(self, option: Literal["slant"], displayof: tkinter.Misc | None = ...) -> Literal["roman", "italic"]: ... + def actual(self, option: Literal["slant"], displayof: tkinter.Misc | None = None) -> Literal["roman", "italic"]: ... @overload - def actual(self, option: Literal["underline", "overstrike"], displayof: tkinter.Misc | None = ...) -> bool: ... + def actual(self, option: Literal["underline", "overstrike"], displayof: tkinter.Misc | None = None) -> bool: ... @overload - def actual(self, option: None, displayof: tkinter.Misc | None = ...) -> _FontDict: ... + def actual(self, option: None, displayof: tkinter.Misc | None = None) -> _FontDict: ... @overload - def actual(self, *, displayof: tkinter.Misc | None = ...) -> _FontDict: ... + def actual(self, *, displayof: tkinter.Misc | None = None) -> _FontDict: ... + def config( self, *, @@ -94,19 +106,18 @@ class Font: ) -> _FontDict | None: ... configure = config def copy(self) -> Font: ... + @overload - def metrics(self, __option: Literal["ascent", "descent", "linespace"], *, displayof: tkinter.Misc | None = ...) -> int: ... + def metrics(self, option: Literal["ascent", "descent", "linespace"], /, *, displayof: tkinter.Misc | None = ...) -> int: ... @overload - def metrics(self, __option: Literal["fixed"], *, displayof: tkinter.Misc | None = ...) -> bool: ... + def metrics(self, option: Literal["fixed"], /, *, displayof: tkinter.Misc | None = ...) -> bool: ... @overload def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... - def measure(self, text: str, displayof: tkinter.Misc | None = ...) -> int: ... - -def families(root: tkinter.Misc | None = ..., displayof: tkinter.Misc | None = ...) -> Tuple[str, ...]: ... -def names(root: tkinter.Misc | None = ...) -> Tuple[str, ...]: ... -if sys.version_info >= (3, 10): - def nametofont(name: str, root: tkinter.Misc | None = ...) -> Font: ... + def measure(self, text: str, displayof: tkinter.Misc | None = None) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __del__(self) -> None: ... -else: - def nametofont(name: str) -> Font: ... +def families(root: tkinter.Misc | None = None, displayof: tkinter.Misc | None = None) -> tuple[str, ...]: ... +def names(root: tkinter.Misc | None = None) -> tuple[str, ...]: ... +def nametofont(name: str, root: tkinter.Misc | None = None) -> Font: ... diff --git a/stdlib/tkinter/messagebox.pyi b/stdlib/tkinter/messagebox.pyi index fc4afcef0cc2..cd95f0de5f80 100644 --- a/stdlib/tkinter/messagebox.pyi +++ b/stdlib/tkinter/messagebox.pyi @@ -1,31 +1,98 @@ +from tkinter import Misc from tkinter.commondialog import Dialog -from typing import Any, ClassVar +from typing import ClassVar, Final, Literal -ERROR: str -INFO: str -QUESTION: str -WARNING: str -ABORTRETRYIGNORE: str -OK: str -OKCANCEL: str -RETRYCANCEL: str -YESNO: str -YESNOCANCEL: str -ABORT: str -RETRY: str -IGNORE: str -CANCEL: str -YES: str -NO: str +__all__ = ["showinfo", "showwarning", "showerror", "askquestion", "askokcancel", "askyesno", "askyesnocancel", "askretrycancel"] + +ERROR: Final = "error" +INFO: Final = "info" +QUESTION: Final = "question" +WARNING: Final = "warning" +ABORTRETRYIGNORE: Final = "abortretryignore" +OK: Final = "ok" +OKCANCEL: Final = "okcancel" +RETRYCANCEL: Final = "retrycancel" +YESNO: Final = "yesno" +YESNOCANCEL: Final = "yesnocancel" +ABORT: Final = "abort" +RETRY: Final = "retry" +IGNORE: Final = "ignore" +CANCEL: Final = "cancel" +YES: Final = "yes" +NO: Final = "no" class Message(Dialog): command: ClassVar[str] -def showinfo(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def showwarning(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def showerror(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def askquestion(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def askokcancel(title: str | None = ..., message: str | None = ..., **options: Any) -> bool: ... -def askyesno(title: str | None = ..., message: str | None = ..., **options: Any) -> bool: ... -def askyesnocancel(title: str | None = ..., message: str | None = ..., **options: Any) -> bool | None: ... -def askretrycancel(title: str | None = ..., message: str | None = ..., **options: Any) -> bool: ... +def showinfo( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok"] = "ok", + parent: Misc = ..., +) -> str: ... +def showwarning( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok"] = "ok", + parent: Misc = ..., +) -> str: ... +def showerror( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok"] = "ok", + parent: Misc = ..., +) -> str: ... +def askquestion( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["yes", "no"] = ..., + parent: Misc = ..., +) -> str: ... +def askokcancel( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok", "cancel"] = ..., + parent: Misc = ..., +) -> bool: ... +def askyesno( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["yes", "no"] = ..., + parent: Misc = ..., +) -> bool: ... +def askyesnocancel( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["cancel", "yes", "no"] = ..., + parent: Misc = ..., +) -> bool | None: ... +def askretrycancel( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["retry", "cancel"] = ..., + parent: Misc = ..., +) -> bool: ... diff --git a/stdlib/tkinter/scrolledtext.pyi b/stdlib/tkinter/scrolledtext.pyi index 246979d5afd7..6f1abc714487 100644 --- a/stdlib/tkinter/scrolledtext.pyi +++ b/stdlib/tkinter/scrolledtext.pyi @@ -1,8 +1,9 @@ from tkinter import Frame, Misc, Scrollbar, Text -from typing import Any + +__all__ = ["ScrolledText"] # The methods from Pack, Place, and Grid are dynamically added over the parent's impls class ScrolledText(Text): frame: Frame vbar: Scrollbar - def __init__(self, master: Misc | None = ..., **kwargs: Any) -> None: ... + def __init__(self, master: Misc | None = None, **kwargs) -> None: ... diff --git a/stdlib/tkinter/simpledialog.pyi b/stdlib/tkinter/simpledialog.pyi index ec801afaceee..6f66f0237b45 100644 --- a/stdlib/tkinter/simpledialog.pyi +++ b/stdlib/tkinter/simpledialog.pyi @@ -1,27 +1,58 @@ -from tkinter import Event, Misc, Toplevel -from typing import Any +import sys +from tkinter import Event, Frame, Misc, Toplevel + +if sys.version_info >= (3, 15): + __all__ = ["SimpleDialog", "Dialog", "askinteger", "askfloat", "askstring"] class Dialog(Toplevel): - def __init__(self, parent: Misc | None, title: str | None = ...) -> None: ... - def body(self, master) -> None: ... - def buttonbox(self): ... + def __init__(self, parent: Misc | None, title: str | None = None) -> None: ... + def body(self, master: Frame) -> Misc | None: ... + def buttonbox(self) -> None: ... + def ok(self, event: Event[Misc] | None = None) -> None: ... + def cancel(self, event: Event[Misc] | None = None) -> None: ... + def validate(self) -> bool: ... + def apply(self) -> None: ... class SimpleDialog: def __init__( self, master: Misc | None, - text: str = ..., - buttons: list[str] = ..., - default: int | None = ..., - cancel: int | None = ..., - title: str | None = ..., - class_: str | None = ..., + text: str = "", + buttons: list[str] = [], + default: int | None = None, + cancel: int | None = None, + title: str | None = None, + class_: str | None = None, ) -> None: ... def go(self) -> int | None: ... def return_event(self, event: Event[Misc]) -> None: ... def wm_delete_window(self) -> None: ... def done(self, num: int) -> None: ... -def askfloat(title: str | None, prompt: str, **kwargs: Any) -> float: ... -def askinteger(title: str | None, prompt: str, **kwargs: Any) -> int: ... -def askstring(title: str | None, prompt: str, **kwargs: Any) -> str: ... +def askfloat( + title: str | None, + prompt: str, + *, + initialvalue: float | None = ..., + minvalue: float | None = ..., + maxvalue: float | None = ..., + parent: Misc | None = ..., +) -> float | None: ... +def askinteger( + title: str | None, + prompt: str, + *, + initialvalue: int | None = ..., + minvalue: int | None = ..., + maxvalue: int | None = ..., + parent: Misc | None = ..., +) -> int | None: ... +def askstring( + title: str | None, + prompt: str, + *, + initialvalue: str | None = ..., + show: str | None = ..., + # minvalue/maxvalue is accepted but not useful. + parent: Misc | None = ..., +) -> str | None: ... diff --git a/stdlib/tkinter/tix.pyi b/stdlib/tkinter/tix.pyi index 4914234c4eed..7891364fa02c 100644 --- a/stdlib/tkinter/tix.pyi +++ b/stdlib/tkinter/tix.pyi @@ -1,175 +1,173 @@ import tkinter -from typing import Any, Tuple -from typing_extensions import Literal - -WINDOW: Literal["window"] -TEXT: Literal["text"] -STATUS: Literal["status"] -IMMEDIATE: Literal["immediate"] -IMAGE: Literal["image"] -IMAGETEXT: Literal["imagetext"] -BALLOON: Literal["balloon"] -AUTO: Literal["auto"] -ACROSSTOP: Literal["acrosstop"] - -ASCII: Literal["ascii"] -CELL: Literal["cell"] -COLUMN: Literal["column"] -DECREASING: Literal["decreasing"] -INCREASING: Literal["increasing"] -INTEGER: Literal["integer"] -MAIN: Literal["main"] -MAX: Literal["max"] -REAL: Literal["real"] -ROW: Literal["row"] -S_REGION: Literal["s-region"] -X_REGION: Literal["x-region"] -Y_REGION: Literal["y-region"] +from _typeshed import Incomplete +from typing import Any, Final + +WINDOW: Final = "window" +TEXT: Final = "text" +STATUS: Final = "status" +IMMEDIATE: Final = "immediate" +IMAGE: Final = "image" +IMAGETEXT: Final = "imagetext" +BALLOON: Final = "balloon" +AUTO: Final = "auto" +ACROSSTOP: Final = "acrosstop" + +ASCII: Final = "ascii" +CELL: Final = "cell" +COLUMN: Final = "column" +DECREASING: Final = "decreasing" +INCREASING: Final = "increasing" +INTEGER: Final = "integer" +MAIN: Final = "main" +MAX: Final = "max" +REAL: Final = "real" +ROW: Final = "row" +S_REGION: Final = "s-region" +X_REGION: Final = "x-region" +Y_REGION: Final = "y-region" # These should be kept in sync with _tkinter constants, except TCL_ALL_EVENTS which doesn't match ALL_EVENTS -TCL_DONT_WAIT: Literal[2] -TCL_WINDOW_EVENTS: Literal[4] -TCL_FILE_EVENTS: Literal[8] -TCL_TIMER_EVENTS: Literal[16] -TCL_IDLE_EVENTS: Literal[32] -TCL_ALL_EVENTS: Literal[0] +TCL_DONT_WAIT: Final = 2 +TCL_WINDOW_EVENTS: Final = 4 +TCL_FILE_EVENTS: Final = 8 +TCL_TIMER_EVENTS: Final = 16 +TCL_IDLE_EVENTS: Final = 32 +TCL_ALL_EVENTS: Final = 0 class tixCommand: def tix_addbitmapdir(self, directory: str) -> None: ... def tix_cget(self, option: str) -> Any: ... - def tix_configure(self, cnf: dict[str, Any] | None = ..., **kw: Any) -> Any: ... - def tix_filedialog(self, dlgclass: str | None = ...) -> str: ... + def tix_configure(self, cnf: dict[str, Any] | None = None, **kw: Any) -> Any: ... + def tix_filedialog(self, dlgclass: str | None = None) -> str: ... def tix_getbitmap(self, name: str) -> str: ... def tix_getimage(self, name: str) -> str: ... def tix_option_get(self, name: str) -> Any: ... - def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: str | None = ...) -> None: ... + def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: str | None = None) -> None: ... class Tk(tkinter.Tk, tixCommand): - def __init__(self, screenName: str | None = ..., baseName: str | None = ..., className: str = ...): ... + def __init__(self, screenName: str | None = None, baseName: str | None = None, className: str = "Tix") -> None: ... class TixWidget(tkinter.Widget): def __init__( self, - master: tkinter.Misc | None = ..., - widgetName: str | None = ..., - static_options: list[str] | None = ..., - cnf: dict[str, Any] = ..., - kw: dict[str, Any] = ..., + master: tkinter.Misc | None = None, + widgetName: str | None = None, + static_options: list[str] | None = None, + cnf: dict[str, Any] = {}, + kw: dict[str, Any] = {}, ) -> None: ... - def __getattr__(self, name: str) -> Any: ... + def __getattr__(self, name: str): ... def set_silent(self, value: str) -> None: ... def subwidget(self, name: str) -> tkinter.Widget: ... def subwidgets_all(self) -> list[tkinter.Widget]: ... def config_all(self, option: Any, value: Any) -> None: ... - def image_create(self, imgtype: str, cnf: dict[str, Any] = ..., master: tkinter.Widget | None = ..., **kw: Any) -> None: ... + def image_create(self, imgtype: str, cnf: dict[str, Any] = {}, master: tkinter.Widget | None = None, **kw) -> None: ... def image_delete(self, imgname: str) -> None: ... class TixSubWidget(TixWidget): - def __init__( - self, master: tkinter.Widget, name: str, destroy_physically: int = ..., check_intermediate: int = ... - ) -> None: ... + def __init__(self, master: tkinter.Widget, name: str, destroy_physically: int = 1, check_intermediate: int = 1) -> None: ... class DisplayStyle: - def __init__(self, itemtype: str, cnf: dict[str, Any] = ..., *, master: tkinter.Widget | None = ..., **kw: Any) -> None: ... - def __getitem__(self, key: str) -> Any: ... + def __init__(self, itemtype: str, cnf: dict[str, Any] = {}, *, master: tkinter.Widget | None = None, **kw) -> None: ... + def __getitem__(self, key: str): ... def __setitem__(self, key: str, value: Any) -> None: ... def delete(self) -> None: ... - def config(self, cnf: dict[str, Any] = ..., **kw: Any) -> Any: ... + def config(self, cnf: dict[str, Any] = {}, **kw): ... class Balloon(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = {}, **kw) -> None: ... def unbind_widget(self, widget: tkinter.Widget) -> None: ... class ButtonBox(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... def invoke(self, name: str) -> None: ... class ComboBox(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def add_history(self, str: str) -> None: ... def append_history(self, str: str) -> None: ... def insert(self, index: int, str: str) -> None: ... def pick(self, index: int) -> None: ... class Control(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def decrement(self) -> None: ... def increment(self) -> None: ... def invoke(self) -> None: ... class LabelEntry(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class LabelFrame(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class Meter(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class OptionMenu(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add_command(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add_separator(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add_command(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add_separator(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... def delete(self, name: str) -> None: ... def disable(self, name: str) -> None: ... def enable(self, name: str) -> None: ... class PopupMenu(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def bind_widget(self, widget: tkinter.Widget) -> None: ... def unbind_widget(self, widget: tkinter.Widget) -> None: ... def post_widget(self, widget: tkinter.Widget, x: int, y: int) -> None: ... class Select(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... def invoke(self, name: str) -> None: ... class StdButtonBox(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def invoke(self, name: str) -> None: ... class DirList(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def chdir(self, dir: str) -> None: ... class DirTree(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def chdir(self, dir: str) -> None: ... class DirSelectDialog(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def popup(self) -> None: ... def popdown(self) -> None: ... class DirSelectBox(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... class ExFileSelectBox(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def filter(self) -> None: ... def invoke(self) -> None: ... class FileSelectBox(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def apply_filter(self) -> None: ... def invoke(self) -> None: ... class FileEntry(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... def invoke(self) -> None: ... def file_dialog(self) -> None: ... class HList(TixWidget, tkinter.XView, tkinter.YView): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... - def add_child(self, parent: str | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... + def add_child(self, parent: str | None = None, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... def anchor_set(self, entry: str) -> None: ... def anchor_clear(self) -> None: ... # FIXME: Overload, certain combos return, others don't - def column_width(self, col: int = ..., width: int | None = ..., chars: int | None = ...) -> int | None: ... + def column_width(self, col: int = 0, width: int | None = None, chars: int | None = None) -> int | None: ... def delete_all(self) -> None: ... def delete_entry(self, entry: str) -> None: ... def delete_offsprings(self, entry: str) -> None: ... @@ -178,23 +176,23 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def dragsite_clear(self) -> None: ... def dropsite_set(self, index: int) -> None: ... def dropsite_clear(self) -> None: ... - def header_create(self, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def header_configure(self, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... - def header_cget(self, col: int, opt: Any) -> Any: ... + def header_create(self, col: int, cnf: dict[str, Any] = {}, **kw) -> None: ... + def header_configure(self, col: int, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def header_cget(self, col: int, opt): ... def header_exists(self, col: int) -> bool: ... def header_exist(self, col: int) -> bool: ... def header_delete(self, col: int) -> None: ... def header_size(self, col: int) -> int: ... def hide_entry(self, entry: str) -> None: ... - def indicator_create(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def indicator_configure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... - def indicator_cget(self, entry: str, opt: Any) -> Any: ... + def indicator_create(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def indicator_configure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def indicator_cget(self, entry: str, opt): ... def indicator_exists(self, entry: str) -> bool: ... def indicator_delete(self, entry: str) -> None: ... def indicator_size(self, entry: str) -> int: ... def info_anchor(self) -> str: ... def info_bbox(self, entry: str) -> tuple[int, int, int, int]: ... - def info_children(self, entry: str | None = ...) -> Tuple[str, ...]: ... + def info_children(self, entry: str | None = None) -> tuple[str, ...]: ... def info_data(self, entry: str) -> Any: ... def info_dragsite(self) -> str: ... def info_dropsite(self) -> str: ... @@ -203,84 +201,84 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def info_next(self, entry: str) -> str: ... def info_parent(self, entry: str) -> str: ... def info_prev(self, entry: str) -> str: ... - def info_selection(self) -> Tuple[str, ...]: ... - def item_cget(self, entry: str, col: int, opt: Any) -> Any: ... - def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... - def item_create(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def info_selection(self) -> tuple[str, ...]: ... + def item_cget(self, entry: str, col: int, opt): ... + def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def item_create(self, entry: str, col: int, cnf: dict[str, Any] = {}, **kw) -> None: ... def item_exists(self, entry: str, col: int) -> bool: ... def item_delete(self, entry: str, col: int) -> None: ... - def entrycget(self, entry: str, opt: Any) -> Any: ... - def entryconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... + def entrycget(self, entry: str, opt): ... + def entryconfigure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... def nearest(self, y: int) -> str: ... def see(self, entry: str) -> None: ... - def selection_clear(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def selection_clear(self, cnf: dict[str, Any] = {}, **kw) -> None: ... def selection_includes(self, entry: str) -> bool: ... - def selection_set(self, first: str, last: str | None = ...) -> None: ... + def selection_set(self, first: str, last: str | None = None) -> None: ... def show_entry(self, entry: str) -> None: ... class CheckList(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def autosetmode(self) -> None: ... def close(self, entrypath: str) -> None: ... def getmode(self, entrypath: str) -> str: ... def open(self, entrypath: str) -> None: ... - def getselection(self, mode: str = ...) -> Tuple[str, ...]: ... + def getselection(self, mode: str = "on") -> tuple[str, ...]: ... def getstatus(self, entrypath: str) -> str: ... - def setstatus(self, entrypath: str, mode: str = ...) -> None: ... + def setstatus(self, entrypath: str, mode: str = "on") -> None: ... class Tree(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def autosetmode(self) -> None: ... def close(self, entrypath: str) -> None: ... def getmode(self, entrypath: str) -> str: ... def open(self, entrypath: str) -> None: ... - def setmode(self, entrypath: str, mode: str = ...) -> None: ... + def setmode(self, entrypath: str, mode: str = "none") -> None: ... class TList(TixWidget, tkinter.XView, tkinter.YView): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def active_set(self, index: int) -> None: ... def active_clear(self) -> None: ... def anchor_set(self, index: int) -> None: ... def anchor_clear(self) -> None: ... - def delete(self, from_: int, to: int | None = ...) -> None: ... + def delete(self, from_: int, to: int | None = None) -> None: ... def dragsite_set(self, index: int) -> None: ... def dragsite_clear(self) -> None: ... def dropsite_set(self, index: int) -> None: ... def dropsite_clear(self) -> None: ... - def insert(self, index: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def insert(self, index: int, cnf: dict[str, Any] = {}, **kw) -> None: ... def info_active(self) -> int: ... def info_anchor(self) -> int: ... def info_down(self, index: int) -> int: ... def info_left(self, index: int) -> int: ... def info_right(self, index: int) -> int: ... - def info_selection(self) -> Tuple[int, ...]: ... + def info_selection(self) -> tuple[int, ...]: ... def info_size(self) -> int: ... def info_up(self, index: int) -> int: ... def nearest(self, x: int, y: int) -> int: ... def see(self, index: int) -> None: ... - def selection_clear(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def selection_clear(self, cnf: dict[str, Any] = {}, **kw) -> None: ... def selection_includes(self, index: int) -> bool: ... - def selection_set(self, first: int, last: int | None = ...) -> None: ... + def selection_set(self, first: int, last: int | None = None) -> None: ... class PanedWindow(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... def delete(self, name: str) -> None: ... def forget(self, name: str) -> None: ... # type: ignore[override] - def panecget(self, entry: str, opt: Any) -> Any: ... - def paneconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... + def panecget(self, entry: str, opt): ... + def paneconfigure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... def panes(self) -> list[tkinter.Widget]: ... class ListNoteBook(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... def page(self, name: str) -> tkinter.Widget: ... def pages(self) -> list[tkinter.Widget]: ... def raise_page(self, name: str) -> None: ... class NoteBook(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... def delete(self, name: str) -> None: ... def page(self, name: str) -> tkinter.Widget: ... def pages(self) -> list[tkinter.Widget]: ... @@ -288,14 +286,14 @@ class NoteBook(TixWidget): def raised(self) -> bool: ... class InputOnly(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class Form: def __setitem__(self, key: str, value: Any) -> None: ... - def config(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def form(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def config(self, cnf: dict[str, Any] = {}, **kw) -> None: ... + def form(self, cnf: dict[str, Any] = {}, **kw) -> None: ... def check(self) -> bool: ... def forget(self) -> None: ... - def grid(self, xsize: int = ..., ysize: int = ...) -> tuple[int, int] | None: ... - def info(self, option: str | None = ...) -> Any: ... + def grid(self, xsize: int = 0, ysize: int = 0) -> tuple[int, int] | None: ... + def info(self, option: str | None = None): ... def slaves(self) -> list[tkinter.Widget]: ... diff --git a/stdlib/tkinter/ttk.pyi b/stdlib/tkinter/ttk.pyi index 3ef348d91ab2..bf184bc2e8f8 100644 --- a/stdlib/tkinter/ttk.pyi +++ b/stdlib/tkinter/ttk.pyi @@ -1,76 +1,268 @@ import _tkinter import sys import tkinter +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable, Sequence from tkinter.font import _FontDescription -from typing import Any, Callable, Tuple, Union, overload -from typing_extensions import Literal, TypedDict +from typing import Any, Literal, ParamSpec, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, Unpack -def tclobjs_to_py(adict): ... -def setup_master(master: Any | None = ...): ... +__all__ = [ + "Button", + "Checkbutton", + "Combobox", + "Entry", + "Frame", + "Label", + "Labelframe", + "LabelFrame", + "Menubutton", + "Notebook", + "Panedwindow", + "PanedWindow", + "Progressbar", + "Radiobutton", + "Scale", + "Scrollbar", + "Separator", + "Sizegrip", + "Style", + "Treeview", + "LabeledScale", + "OptionMenu", + "tclobjs_to_py", + "setup_master", + "Spinbox", +] -# from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound -_TtkCompound = Literal["text", "image", tkinter._Compound] +def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... +def setup_master(master: tkinter.Misc | None = None): ... + +_Padding: TypeAlias = ( + float + | str + | tuple[float | str] + | tuple[float | str, float | str] + | tuple[float | str, float | str, float | str] + | tuple[float | str, float | str, float | str, float | str] +) + +# Last item (option value to apply) varies between different options so use Any. +# It could also be any iterable with items matching the tuple, but that case +# hasn't been added here for consistency with _Padding above. +_Statespec: TypeAlias = tuple[Unpack[tuple[str, ...]], Any] +_ImageStatespec: TypeAlias = tuple[Unpack[tuple[str, ...]], tkinter._Image | str] +_VsapiStatespec: TypeAlias = tuple[Unpack[tuple[str, ...]], int] + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +@type_check_only +class _Layout(TypedDict, total=False): + side: Literal["left", "right", "top", "bottom"] + sticky: str # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty + unit: Literal[0, 1] | bool + children: _LayoutSpec + # Note: there seem to be some other undocumented keys sometimes + +# This could be any sequence when passed as a parameter but will always be a list when returned. +_LayoutSpec: TypeAlias = list[tuple[str, _Layout | None]] + +# Keep these in sync with the appropriate methods in Style +@type_check_only +class _ElementCreateImageKwargs(TypedDict, total=False): + border: _Padding + height: float | str + padding: _Padding + sticky: str + width: float | str + +_ElementCreateArgsCrossPlatform: TypeAlias = ( + # Could be any sequence here but types are not homogenous so just type it as tuple + tuple[Literal["image"], tkinter._Image | str, Unpack[tuple[_ImageStatespec, ...]], _ElementCreateImageKwargs] + | tuple[Literal["from"], str, str] + | tuple[Literal["from"], str] # (fromelement is optional) +) +if sys.platform == "win32" and sys.version_info >= (3, 13): + @type_check_only + class _ElementCreateVsapiKwargsPadding(TypedDict, total=False): + padding: _Padding + + @type_check_only + class _ElementCreateVsapiKwargsMargin(TypedDict, total=False): + padding: _Padding + + @type_check_only + class _ElementCreateVsapiKwargsSize(TypedDict): + width: float | str + height: float | str + + _ElementCreateVsapiKwargsDict: TypeAlias = ( + _ElementCreateVsapiKwargsPadding | _ElementCreateVsapiKwargsMargin | _ElementCreateVsapiKwargsSize + ) + _ElementCreateArgs: TypeAlias = ( # noqa: Y047 # It doesn't recognise the usage below for whatever reason + _ElementCreateArgsCrossPlatform + | tuple[Literal["vsapi"], str, int, _ElementCreateVsapiKwargsDict] + | tuple[Literal["vsapi"], str, int, _VsapiStatespec, _ElementCreateVsapiKwargsDict] + ) +else: + _ElementCreateArgs: TypeAlias = _ElementCreateArgsCrossPlatform +_ThemeSettingsValue = TypedDict( + "_ThemeSettingsValue", + { + "configure": dict[str, Any], + "map": dict[str, Iterable[_Statespec]], + "layout": _LayoutSpec, + "element create": _ElementCreateArgs, + }, + total=False, +) +_ThemeSettings: TypeAlias = dict[str, _ThemeSettingsValue] class Style: - master: Any + master: tkinter.Misc tk: _tkinter.TkappType - def __init__(self, master: tkinter.Misc | None = ...): ... - def configure(self, style, query_opt: Any | None = ..., **kw): ... - def map(self, style, query_opt: Any | None = ..., **kw): ... - def lookup(self, style, option, state: Any | None = ..., default: Any | None = ...): ... - def layout(self, style, layoutspec: Any | None = ...): ... - def element_create(self, elementname, etype, *args, **kw): ... - def element_names(self): ... - def element_options(self, elementname): ... - def theme_create(self, themename, parent: Any | None = ..., settings: Any | None = ...): ... - def theme_settings(self, themename, settings): ... - def theme_names(self) -> Tuple[str, ...]: ... + def __init__(self, master: tkinter.Misc | None = None) -> None: ... + + # For these methods, values given vary between options. Returned values + # seem to be str, but this might not always be the case. + @overload + def configure(self, style: str) -> dict[str, Any] | None: ... # Returns None if no configuration. + @overload + def configure(self, style: str, query_opt: str, **kw: Any) -> Any: ... + @overload + def configure(self, style: str, query_opt: None = None, **kw: Any) -> None: ... + + @overload + def map(self, style: str, query_opt: str) -> _Statespec: ... + @overload + def map(self, style: str, query_opt: None = None, **kw: Iterable[_Statespec]) -> dict[str, _Statespec]: ... + + def lookup(self, style: str, option: str, state: Iterable[str] | None = None, default: Any | None = None) -> Any: ... + + @overload + def layout(self, style: str, layoutspec: _LayoutSpec) -> list[Never]: ... # Always seems to return an empty list + @overload + def layout(self, style: str, layoutspec: None = None) -> _LayoutSpec: ... + + @overload + def element_create( + self, + elementname: str, + etype: Literal["image"], + default_image: tkinter._Image | str, + /, + *imagespec: _ImageStatespec, + border: _Padding = ..., + height: float | str = ..., + padding: _Padding = ..., + sticky: str = ..., + width: float | str = ..., + ) -> None: ... + @overload + def element_create(self, elementname: str, etype: Literal["from"], themename: str, fromelement: str = ..., /) -> None: ... + if sys.platform == "win32" and sys.version_info >= (3, 13): # and tk version >= 8.6 + # margin, padding, and (width + height) are mutually exclusive. width + # and height must either both be present or not present at all. Note: + # There are other undocumented options if you look at ttk's source code. + @overload + def element_create( + self, + elementname: str, + etype: Literal["vsapi"], + class_: str, + part: int, + vs_statespec: _VsapiStatespec = ..., + /, + *, + padding: _Padding = ..., + ) -> None: ... + @overload + def element_create( + self, + elementname: str, + etype: Literal["vsapi"], + class_: str, + part: int, + vs_statespec: _VsapiStatespec = ..., + /, + *, + margin: _Padding = ..., + ) -> None: ... + @overload + def element_create( + self, + elementname: str, + etype: Literal["vsapi"], + class_: str, + part: int, + vs_statespec: _VsapiStatespec = ..., + /, + *, + width: float | str, + height: float | str, + ) -> None: ... + + def element_names(self) -> tuple[str, ...]: ... + def element_options(self, elementname: str) -> tuple[str, ...]: ... + def theme_create(self, themename: str, parent: str | None = None, settings: _ThemeSettings | None = None) -> None: ... + def theme_settings(self, themename: str, settings: _ThemeSettings) -> None: ... + def theme_names(self) -> tuple[str, ...]: ... + @overload def theme_use(self, themename: str) -> None: ... @overload - def theme_use(self, themename: None = ...) -> str: ... + def theme_use(self, themename: None = None) -> str: ... class Widget(tkinter.Widget): - def __init__(self, master: tkinter.Misc | None, widgetname, kw: Any | None = ...): ... - def identify(self, x, y): ... - def instate(self, statespec, callback: Any | None = ..., *args, **kw): ... - def state(self, statespec: Any | None = ...): ... + def __init__(self, master: tkinter.Misc | None, widgetname: str | None, kw: dict[str, Any] | None = None) -> None: ... + def identify(self, x: int, y: int) -> str: ... + + @overload + def instate(self, statespec: Sequence[str], callback: None = None) -> bool: ... + @overload + def instate( + self, statespec: Sequence[str], callback: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs + ) -> Literal[False] | _T: ... + + def state(self, statespec: Sequence[str] | None = None) -> tuple[str, ...]: ... class Button(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - default: Literal["normal", "active", "disabled"] = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + command: str | Callable[[], Any] = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + default: Literal["normal", "active", "disabled"] = "normal", + image: tkinter._Image | str = "", name: str = ..., - padding: Any = ..., # undocumented - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - width: int | Literal[""] = ..., + underline: int = -1, + width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., cursor: tkinter._Cursor = ..., default: Literal["normal", "active", "disabled"] = ..., - image: tkinter._ImageSpec = ..., - padding: Any = ..., + image: tkinter._Image | str = ..., + padding=..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: tkinter.Variable = ..., underline: int = ..., @@ -78,50 +270,52 @@ class Button(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self) -> Any: ... class Checkbutton(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + command: str | Callable[[], Any] = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + image: tkinter._Image | str = "", name: str = ..., - offvalue: Any = ..., - onvalue: Any = ..., - padding: Any = ..., # undocumented - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + offvalue: Any = 0, + onvalue: Any = 1, + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., + underline: int = -1, # Seems like variable can be empty string, but actually setting it to # empty string segfaults before Tcl 8.6.9. Search for ttk::checkbutton # here: https://sourceforge.net/projects/tcl/files/Tcl/8.6.9/tcltk-release-notes-8.6.9.txt/view variable: tkinter.Variable = ..., - width: int | Literal[""] = ..., + width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., cursor: tkinter._Cursor = ..., - image: tkinter._ImageSpec = ..., + image: tkinter._Image | str = ..., offvalue: Any = ..., onvalue: Any = ..., - padding: Any = ..., + padding=..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: tkinter.Variable = ..., underline: int = ..., @@ -130,308 +324,323 @@ class Checkbutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self) -> Any: ... class Entry(Widget, tkinter.Entry): def __init__( self, - master: tkinter.Misc | None = ..., - widget: str | None = ..., + master: tkinter.Misc | None = None, + widget: str | None = None, *, - background: tkinter._Color = ..., # undocumented - class_: str = ..., + background: str = ..., # undocumented + class_: str = "", cursor: tkinter._Cursor = ..., - exportselection: bool = ..., - font: _FontDescription = ..., - foreground: tkinter._Color = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., - justify: Literal["left", "center", "right"] = ..., + exportselection: bool = True, + font: _FontDescription = "TkTextFont", + foreground: str = "", + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = "", + justify: Literal["left", "center", "right"] = "left", name: str = ..., - show: str = ..., - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + show: str = "", + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: tkinter.Variable = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., - width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload # type: ignore[override] def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: tkinter._Color = ..., + background: str = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., font: _FontDescription = ..., - foreground: tkinter._Color = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., + foreground: str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., justify: Literal["left", "center", "right"] = ..., show: str = ..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Entry().config is mypy error (don't know why) @overload # type: ignore[override] def config( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: tkinter._Color = ..., + background: str = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., font: _FontDescription = ..., - foreground: tkinter._Color = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., + foreground: str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., justify: Literal["left", "center", "right"] = ..., show: str = ..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - def bbox(self, index): ... - def identify(self, x, y): ... + + def bbox(self, index) -> tuple[int, int, int, int]: ... # type: ignore[override] + def identify(self, x: int, y: int) -> str: ... def validate(self): ... class Combobox(Entry): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - background: tkinter._Color = ..., # undocumented - class_: str = ..., - cursor: tkinter._Cursor = ..., - exportselection: bool = ..., + background: str = ..., # undocumented + class_: str = "", + cursor: tkinter._Cursor = "", + exportselection: bool = True, font: _FontDescription = ..., # undocumented - foreground: tkinter._Color = ..., # undocumented - height: int = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented - justify: Literal["left", "center", "right"] = ..., + foreground: str = ..., # undocumented + height: int = 10, + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., # undocumented + justify: Literal["left", "center", "right"] = "left", name: str = ..., - postcommand: Callable[[], Any] | str = ..., - show: Any = ..., # undocumented - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + postcommand: Callable[[], object] | str = "", + show=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., # undocumented - validatecommand: tkinter._EntryValidateCommand = ..., # undocumented - values: list[str] | Tuple[str, ...] = ..., - width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., # undocumented + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., # undocumented + values: list[str] | tuple[str, ...] = ..., + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = ..., # undocumented ) -> None: ... + @overload # type: ignore[override] def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: tkinter._Color = ..., + background: str = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., font: _FontDescription = ..., - foreground: tkinter._Color = ..., + foreground: str = ..., height: int = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., justify: Literal["left", "center", "right"] = ..., - postcommand: Callable[[], Any] | str = ..., - show: Any = ..., + postcommand: Callable[[], object] | str = ..., + show=..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Combobox().config is mypy error (don't know why) @overload # type: ignore[override] def config( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - background: tkinter._Color = ..., + background: str = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., font: _FontDescription = ..., - foreground: tkinter._Color = ..., + foreground: str = ..., height: int = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., justify: Literal["left", "center", "right"] = ..., - postcommand: Callable[[], Any] | str = ..., - show: Any = ..., + postcommand: Callable[[], object] | str = ..., + show=..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - def current(self, newindex: Any | None = ...): ... - def set(self, value): ... + + def current(self, newindex: int | None = None) -> int: ... + def set(self, value: Any) -> None: ... class Frame(Widget): + # This should be kept in sync with tkinter.ttk.LabeledScale.__init__() + # (all of these keyword-only arguments are also present there) def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - border: tkinter._ScreenUnits = ..., - borderwidth: tkinter._ScreenUnits = ..., - class_: str = ..., - cursor: tkinter._Cursor = ..., - height: tkinter._ScreenUnits = ..., + border: float | str = ..., + borderwidth: float | str = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + height: float | str = 0, name: str = ..., - padding: tkinter._Padding = ..., - relief: tkinter._Relief = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - width: tkinter._ScreenUnits = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - border: tkinter._ScreenUnits = ..., - borderwidth: tkinter._ScreenUnits = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: tkinter._Cursor = ..., - height: tkinter._ScreenUnits = ..., - padding: tkinter._Padding = ..., - relief: tkinter._Relief = ..., + height: float | str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - width: tkinter._ScreenUnits = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Label(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - anchor: tkinter._Anchor = ..., - background: tkinter._Color = ..., - border: tkinter._ScreenUnits = ..., # alias for borderwidth - borderwidth: tkinter._ScreenUnits = ..., # undocumented - class_: str = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = "", + border: float | str = ..., # alias for borderwidth + borderwidth: float | str = ..., # undocumented + class_: str = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", font: _FontDescription = ..., - foreground: tkinter._Color = ..., - image: tkinter._ImageSpec = ..., + foreground: str = "", + image: tkinter._Image | str = "", justify: Literal["left", "center", "right"] = ..., name: str = ..., - padding: tkinter._Padding = ..., - relief: tkinter._Relief = ..., - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - width: int | Literal[""] = ..., - wraplength: tkinter._ScreenUnits = ..., + underline: int = -1, + width: int | Literal[""] = "", + wraplength: float | str = ..., ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - anchor: tkinter._Anchor = ..., - background: tkinter._Color = ..., - border: tkinter._ScreenUnits = ..., - borderwidth: tkinter._ScreenUnits = ..., - compound: _TtkCompound = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., cursor: tkinter._Cursor = ..., font: _FontDescription = ..., - foreground: tkinter._Color = ..., - image: tkinter._ImageSpec = ..., + foreground: str = ..., + image: tkinter._Image | str = ..., justify: Literal["left", "center", "right"] = ..., - padding: tkinter._Padding = ..., - relief: tkinter._Relief = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: tkinter.Variable = ..., underline: int = ..., width: int | Literal[""] = ..., - wraplength: tkinter._ScreenUnits = ..., + wraplength: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Labelframe(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - border: tkinter._ScreenUnits = ..., - borderwidth: tkinter._ScreenUnits = ..., # undocumented - class_: str = ..., - cursor: tkinter._Cursor = ..., - height: tkinter._ScreenUnits = ..., + border: float | str = ..., + borderwidth: float | str = ..., # undocumented + class_: str = "", + cursor: tkinter._Cursor = "", + height: float | str = 0, labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., labelwidget: tkinter.Misc = ..., name: str = ..., - padding: tkinter._Padding = ..., - relief: tkinter._Relief = ..., # undocumented - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., - underline: int = ..., - width: tkinter._ScreenUnits = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., # undocumented + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", + underline: int = -1, + width: float | str = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - border: tkinter._ScreenUnits = ..., - borderwidth: tkinter._ScreenUnits = ..., + border: float | str = ..., + borderwidth: float | str = ..., cursor: tkinter._Cursor = ..., - height: tkinter._ScreenUnits = ..., + height: float | str = ..., labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., labelwidget: tkinter.Misc = ..., - padding: tkinter._Padding = ..., - relief: tkinter._Relief = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., underline: int = ..., - width: tkinter._ScreenUnits = ..., + width: float | str = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure LabelFrame = Labelframe @@ -439,38 +648,39 @@ LabelFrame = Labelframe class Menubutton(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - direction: Literal["above", "below", "left", "right", "flush"] = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + image: tkinter._Image | str = "", menu: tkinter.Menu = ..., name: str = ..., - padding: Any = ..., # undocumented - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - width: int | Literal[""] = ..., + underline: int = -1, + width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - compound: _TtkCompound = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., cursor: tkinter._Cursor = ..., direction: Literal["above", "below", "left", "right", "flush"] = ..., - image: tkinter._ImageSpec = ..., + image: tkinter._Image | str = ..., menu: tkinter.Menu = ..., - padding: Any = ..., + padding=..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: tkinter.Variable = ..., underline: int = ..., @@ -478,36 +688,39 @@ class Menubutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Notebook(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., - height: int = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + height: int = 0, name: str = ..., - padding: tkinter._Padding = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - width: int = ..., + padding: _Padding = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: int = 0, ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, cursor: tkinter._Cursor = ..., height: int = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., width: int = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def add( self, @@ -515,148 +728,156 @@ class Notebook(Widget): *, state: Literal["normal", "disabled", "hidden"] = ..., sticky: str = ..., # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty - padding: tkinter._Padding = ..., + padding: _Padding = ..., text: str = ..., - image: Any = ..., # Sequence of an image name, followed by zero or more (sequences of one or more state names followed by an image name) - compound: tkinter._Compound = ..., + # `image` is a sequence of an image name, followed by zero or more + # (sequences of one or more state names followed by an image name) + image=..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., underline: int = ..., ) -> None: ... - def forget(self, tab_id): ... - def hide(self, tab_id): ... - def identify(self, x, y): ... + def forget(self, tab_id) -> None: ... # type: ignore[override] + def hide(self, tab_id) -> None: ... + def identify(self, x: int, y: int) -> str: ... def index(self, tab_id): ... - def insert(self, pos, child, **kw): ... - def select(self, tab_id: Any | None = ...): ... - def tab(self, tab_id, option: Any | None = ..., **kw): ... + def insert(self, pos, child, **kw) -> None: ... + def select(self, tab_id=None): ... + def tab(self, tab_id, option=None, **kw): ... def tabs(self): ... def enable_traversal(self) -> None: ... class Panedwindow(Widget, tkinter.PanedWindow): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + cursor: tkinter._Cursor = "", # width and height for tkinter.ttk.Panedwindow are int but for tkinter.PanedWindow they are screen units - height: int = ..., + height: int = 0, name: str = ..., - orient: Literal["vertical", "horizontal"] = ..., # can't be changed with configure() - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - width: int = ..., + orient: Literal["vertical", "horizontal"] = "vertical", # can't be changed with configure() + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: int = 0, ) -> None: ... def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: ... + @overload # type: ignore[override] def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, cursor: tkinter._Cursor = ..., height: int = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., width: int = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Panedwindow().config is mypy error (don't know why) @overload # type: ignore[override] def config( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, cursor: tkinter._Cursor = ..., height: int = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., width: int = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - forget: Any - def insert(self, pos, child, **kw): ... - def pane(self, pane, option: Any | None = ..., **kw): ... - def sashpos(self, index, newpos: Any | None = ...): ... + + forget = tkinter.PanedWindow.forget + def insert(self, pos, child, **kw) -> None: ... + def pane(self, pane, option=None, **kw): ... + def sashpos(self, index, newpos=None): ... PanedWindow = Panedwindow class Progressbar(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., - length: tkinter._ScreenUnits = ..., - maximum: float = ..., - mode: Literal["determinate", "indeterminate"] = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + length: float | str = 100, + maximum: float = 100, + mode: Literal["determinate", "indeterminate"] = "determinate", name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - phase: int = ..., # docs say read-only but assigning int to this works - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - value: float = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + phase: int = 0, # docs say read-only but assigning int to this works + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + value: float = 0.0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, cursor: tkinter._Cursor = ..., - length: tkinter._ScreenUnits = ..., + length: float | str = ..., maximum: float = ..., mode: Literal["determinate", "indeterminate"] = ..., orient: Literal["horizontal", "vertical"] = ..., phase: int = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def start(self, interval: Any | None = ...): ... - def step(self, amount: Any | None = ...): ... - def stop(self): ... + def start(self, interval: Literal["idle"] | int | None = None) -> None: ... + def step(self, amount: float | None = None) -> None: ... + def stop(self) -> None: ... class Radiobutton(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., - cursor: tkinter._Cursor = ..., - image: tkinter._ImageSpec = ..., + class_: str = "", + command: str | Callable[[], Any] = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + image: tkinter._Image | str = "", name: str = ..., - padding: Any = ..., # undocumented - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - text: float | str = ..., + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", textvariable: tkinter.Variable = ..., - underline: int = ..., - value: Any = ..., + underline: int = -1, + value: Any = "1", variable: tkinter.Variable | Literal[""] = ..., - width: int | Literal[""] = ..., + width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - command: tkinter._ButtonCommand = ..., - compound: _TtkCompound = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., cursor: tkinter._Cursor = ..., - image: tkinter._ImageSpec = ..., - padding: Any = ..., + image: tkinter._Image | str = ..., + padding=..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., text: float | str = ..., textvariable: tkinter.Variable = ..., underline: int = ..., @@ -666,106 +887,114 @@ class Radiobutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self) -> Any: ... -class Scale(Widget, tkinter.Scale): +# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible +class Scale(Widget, tkinter.Scale): # type: ignore[misc] def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - command: str | Callable[[str], Any] = ..., - cursor: tkinter._Cursor = ..., - from_: float = ..., - length: tkinter._ScreenUnits = ..., + class_: str = "", + command: str | Callable[[str], object] = "", + cursor: tkinter._Cursor = "", + from_: float = 0, + length: float | str = 100, name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", state: str = ..., # undocumented - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - to: float = ..., - value: float = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + to: float = 1.0, + value: float = 0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... + @overload # type: ignore[override] def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: tkinter._Cursor = ..., from_: float = ..., - length: tkinter._ScreenUnits = ..., + length: float | str = ..., orient: Literal["horizontal", "vertical"] = ..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., to: float = ..., value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Scale().config is mypy error (don't know why) @overload # type: ignore[override] def config( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: tkinter._Cursor = ..., from_: float = ..., - length: tkinter._ScreenUnits = ..., + length: float | str = ..., orient: Literal["horizontal", "vertical"] = ..., state: str = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., to: float = ..., value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - def get(self, x: Any | None = ..., y: Any | None = ...): ... -class Scrollbar(Widget, tkinter.Scrollbar): + def get(self, x: int | None = None, y: int | None = None) -> float: ... + +# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible +class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - command: Callable[..., tuple[float, float] | None] | str = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + command: Callable[..., tuple[float, float] | None] | str = "", + cursor: tkinter._Cursor = "", name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", ) -> None: ... + @overload # type: ignore[override] def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, command: Callable[..., tuple[float, float] | None] | str = ..., cursor: tkinter._Cursor = ..., orient: Literal["horizontal", "vertical"] = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Scrollbar().config is mypy error (don't know why) @overload # type: ignore[override] def config( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, command: Callable[..., tuple[float, float] | None] | str = ..., cursor: tkinter._Cursor = ..., orient: Literal["horizontal", "vertical"] = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... @@ -773,119 +1002,125 @@ class Scrollbar(Widget, tkinter.Scrollbar): class Separator(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - cursor: tkinter._Cursor = ..., + class_: str = "", + cursor: tkinter._Cursor = "", name: str = ..., - orient: Literal["horizontal", "vertical"] = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, cursor: tkinter._Cursor = ..., orient: Literal["horizontal", "vertical"] = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Sizegrip(Widget): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., + class_: str = "", cursor: tkinter._Cursor = ..., name: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, cursor: tkinter._Cursor = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure -if sys.version_info >= (3, 7): - class Spinbox(Entry): - def __init__( - self, - master: tkinter.Misc | None = ..., - *, - background: tkinter._Color = ..., # undocumented - class_: str = ..., - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., - cursor: tkinter._Cursor = ..., - exportselection: bool = ..., # undocumented - font: _FontDescription = ..., # undocumented - foreground: tkinter._Color = ..., # undocumented - format: str = ..., - from_: float = ..., - increment: float = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented - justify: Literal["left", "center", "right"] = ..., # undocumented - name: str = ..., - show: Any = ..., # undocumented - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - textvariable: tkinter.Variable = ..., # undocumented - to: float = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., - width: int = ..., # undocumented - wrap: bool = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., - ) -> None: ... - @overload # type: ignore[override] - def configure( - self, - cnf: dict[str, Any] | None = ..., - *, - background: tkinter._Color = ..., - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., - cursor: tkinter._Cursor = ..., - exportselection: bool = ..., - font: _FontDescription = ..., - foreground: tkinter._Color = ..., - format: str = ..., - from_: float = ..., - increment: float = ..., - invalidcommand: tkinter._EntryValidateCommand = ..., - justify: Literal["left", "center", "right"] = ..., - show: Any = ..., - state: str = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - textvariable: tkinter.Variable = ..., - to: float = ..., - validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., - validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., - width: int = ..., - wrap: bool = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., - ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... - @overload - def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - config = configure # type: ignore[assignment] - def set(self, value: Any) -> None: ... +class Spinbox(Entry): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + background: str = ..., # undocumented + class_: str = "", + command: Callable[[], object] | str | list[str] | tuple[str, ...] = "", + cursor: tkinter._Cursor = "", + exportselection: bool = ..., # undocumented + font: _FontDescription = ..., # undocumented + foreground: str = ..., # undocumented + format: str = "", + from_: float = 0, + increment: float = 1, + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., # undocumented + justify: Literal["left", "center", "right"] = ..., # undocumented + name: str = ..., + show=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., # undocumented + to: float = 0, + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + values: list[str] | tuple[str, ...] = ..., + width: int = ..., # undocumented + wrap: bool = False, + xscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: str = ..., + format: str = ..., + from_: float = ..., + increment: float = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], object] = ..., + justify: Literal["left", "center", "right"] = ..., + show=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., + width: int = ..., + wrap: bool = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure # type: ignore[assignment] + def set(self, value: Any) -> None: ... + +@type_check_only class _TreeviewItemDict(TypedDict): text: str image: list[str] | Literal[""] # no idea why it's wrapped in list @@ -893,200 +1128,231 @@ class _TreeviewItemDict(TypedDict): open: bool # actually 0 or 1 tags: list[str] | Literal[""] +@type_check_only class _TreeviewTagDict(TypedDict): # There is also 'text' and 'anchor', but they don't seem to do anything, using them is likely a bug - foreground: tkinter._Color - background: tkinter._Color + foreground: str + background: str font: _FontDescription - image: Literal[""] | str # not wrapped in list :D + image: str # not wrapped in list :D +@type_check_only class _TreeviewHeaderDict(TypedDict): text: str - image: list[str] - anchor: tkinter._Anchor + image: list[str] | Literal[""] + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] command: str state: str # Doesn't seem to appear anywhere else than in these dicts +@type_check_only class _TreeviewColumnDict(TypedDict): width: int minwidth: int stretch: bool # actually 0 or 1 - anchor: tkinter._Anchor + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] id: str -_TreeviewColumnId = Union[int, str] # manual page: "COLUMN IDENTIFIERS" - class Treeview(Widget, tkinter.XView, tkinter.YView): def __init__( self, - master: tkinter.Misc | None = ..., + master: tkinter.Misc | None = None, *, - class_: str = ..., - columns: str | list[str] | Tuple[str, ...] = ..., - cursor: tkinter._Cursor = ..., - displaycolumns: str | list[str] | Tuple[str, ...] | list[int] | Tuple[int, ...] | Literal["#all"] = ..., - height: int = ..., + class_: str = "", + columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = "", + cursor: tkinter._Cursor = "", + displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ("#all",), + height: int = 10, name: str = ..., - padding: tkinter._Padding = ..., - selectmode: Literal["extended", "browse", "none"] = ..., + padding: _Padding = ..., + selectmode: Literal["extended", "browse", "none"] = "extended", # list/tuple of Literal don't actually work in mypy # # 'tree headings' is same as ['tree', 'headings'], and I wouldn't be # surprised if someone is using it. - show: Literal["tree", "headings", "tree headings", ""] | list[str] | Tuple[str, ...] = ..., - style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., - yscrollcommand: tkinter._XYScrollCommand = ..., + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ("tree", "headings"), + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + xscrollcommand: str | Callable[[float, float], object] = "", + yscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, - cnf: dict[str, Any] | None = ..., + cnf: dict[str, Any] | None = None, *, - columns: str | list[str] | Tuple[str, ...] = ..., + columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = ..., cursor: tkinter._Cursor = ..., - displaycolumns: str | list[str] | Tuple[str, ...] | list[int] | Tuple[int, ...] | Literal["#all"] = ..., + displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ..., height: int = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., selectmode: Literal["extended", "browse", "none"] = ..., - show: Literal["tree", "headings", "tree headings", ""] | list[str] | Tuple[str, ...] = ..., + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ..., style: str = ..., - takefocus: tkinter._TakeFocusValue = ..., - xscrollcommand: tkinter._XYScrollCommand = ..., - yscrollcommand: tkinter._XYScrollCommand = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure - def bbox(self, item, column: _TreeviewColumnId | None = ...) -> tuple[int, int, int, int] | Literal[""]: ... # type: ignore[override] - def get_children(self, item: str | None = ...) -> Tuple[str, ...]: ... - def set_children(self, item: str, *newchildren: str) -> None: ... + def bbox(self, item: str | int, column: str | int | None = None) -> tuple[int, int, int, int] | Literal[""]: ... # type: ignore[override] + def get_children(self, item: str | int | None = None) -> tuple[str, ...]: ... + def set_children(self, item: str | int, *newchildren: str | int) -> None: ... + @overload - def column(self, column: _TreeviewColumnId, option: Literal["width", "minwidth"]) -> int: ... + def column(self, column: str | int, option: Literal["width", "minwidth"]) -> int: ... @overload - def column(self, column: _TreeviewColumnId, option: Literal["stretch"]) -> bool: ... # actually 0 or 1 + def column(self, column: str | int, option: Literal["stretch"]) -> bool: ... # actually 0 or 1 @overload - def column(self, column: _TreeviewColumnId, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... + def column(self, column: str | int, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... @overload - def column(self, column: _TreeviewColumnId, option: Literal["id"]) -> str: ... + def column(self, column: str | int, option: Literal["id"]) -> str: ... @overload - def column(self, column: _TreeviewColumnId, option: str) -> Any: ... + def column(self, column: str | int, option: str) -> Any: ... @overload def column( self, - column: _TreeviewColumnId, - option: None = ..., + column: str | int, + option: None = None, *, width: int = ..., minwidth: int = ..., stretch: bool = ..., - anchor: tkinter._Anchor = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., # id is read-only ) -> _TreeviewColumnDict | None: ... - def delete(self, *items: str) -> None: ... - def detach(self, *items: str) -> None: ... - def exists(self, item: str) -> bool: ... + + def delete(self, *items: str | int) -> None: ... + def detach(self, *items: str | int) -> None: ... + def exists(self, item: str | int) -> bool: ... + @overload # type: ignore[override] - def focus(self, item: None = ...) -> str: ... # can return empty string + def focus(self, item: None = None) -> str: ... # can return empty string + @overload + def focus(self, item: str | int) -> Literal[""]: ... + @overload - def focus(self, item: str) -> Literal[""]: ... + def heading(self, column: str | int, option: Literal["text"]) -> str: ... @overload - def heading(self, column: _TreeviewColumnId, option: Literal["text"]) -> str: ... + def heading(self, column: str | int, option: Literal["image"]) -> tuple[str] | str: ... @overload - def heading(self, column: _TreeviewColumnId, option: Literal["image"]) -> tuple[str]: ... + def heading(self, column: str | int, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... @overload - def heading(self, column: _TreeviewColumnId, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... + def heading(self, column: str | int, option: Literal["command"]) -> str: ... @overload - def heading(self, column: _TreeviewColumnId, option: Literal["command"]) -> str: ... + def heading(self, column: str | int, option: str) -> Any: ... @overload - def heading(self, column: _TreeviewColumnId, option: str) -> Any: ... + def heading(self, column: str | int, option: None = None) -> _TreeviewHeaderDict: ... @overload def heading( self, - column: _TreeviewColumnId, - option: None = ..., + column: str | int, + option: None = None, *, text: str = ..., - image: tkinter._ImageSpec = ..., - anchor: tkinter._Anchor = ..., - command: str | Callable[[], Any] = ..., - ) -> _TreeviewHeaderDict | None: ... - def identify(self, component, x, y): ... + image: tkinter._Image | str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + command: str | Callable[[], object] = ..., + ) -> None: ... + + # Internal Method. Leave untyped: + def identify(self, component, x, y): ... # type: ignore[override] def identify_row(self, y: int) -> str: ... def identify_column(self, x: int) -> str: ... def identify_region(self, x: int, y: int) -> Literal["heading", "separator", "tree", "cell", "nothing"]: ... def identify_element(self, x: int, y: int) -> str: ... # don't know what possible return values are - def index(self, item: str) -> int: ... + def index(self, item: str | int) -> int: ... def insert( self, parent: str, index: int | Literal["end"], - iid: str | None = ..., + iid: str | int | None = None, *, - id: str = ..., # same as iid + id: str | int = ..., # same as iid text: str = ..., - image: tkinter._ImageSpec = ..., - values: list[Any] | Tuple[Any, ...] = ..., + image: tkinter._Image | str = ..., + values: list[Any] | tuple[Any, ...] = ..., open: bool = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., ) -> str: ... + @overload - def item(self, item: str, option: Literal["text"]) -> str: ... + def item(self, item: str | int, option: Literal["text"]) -> str: ... @overload - def item(self, item: str, option: Literal["image"]) -> tuple[str] | Literal[""]: ... + def item(self, item: str | int, option: Literal["image"]) -> tuple[str] | Literal[""]: ... @overload - def item(self, item: str, option: Literal["values"]) -> Tuple[Any, ...] | Literal[""]: ... + def item(self, item: str | int, option: Literal["values"]) -> tuple[Any, ...] | Literal[""]: ... @overload - def item(self, item: str, option: Literal["open"]) -> bool: ... # actually 0 or 1 + def item(self, item: str | int, option: Literal["open"]) -> bool: ... # actually 0 or 1 @overload - def item(self, item: str, option: Literal["tags"]) -> Tuple[str, ...] | Literal[""]: ... + def item(self, item: str | int, option: Literal["tags"]) -> tuple[str, ...] | Literal[""]: ... @overload - def item(self, item: str, option: str) -> Any: ... + def item(self, item: str | int, option: str) -> Any: ... + @overload + def item(self, item: str | int, option: None = None) -> _TreeviewItemDict: ... @overload def item( self, - item: str, - option: None = ..., + item: str | int, + option: None = None, *, text: str = ..., - image: tkinter._ImageSpec = ..., - values: list[Any] | Tuple[Any, ...] | Literal[""] = ..., + image: tkinter._Image | str = ..., + values: list[Any] | tuple[Any, ...] | Literal[""] = ..., open: bool = ..., - tags: str | list[str] | Tuple[str, ...] = ..., - ) -> _TreeviewItemDict | None: ... - def move(self, item: str, parent: str, index: int) -> None: ... + tags: str | list[str] | tuple[str, ...] = ..., + ) -> None: ... + + def move(self, item: str | int, parent: str, index: int | Literal["end"]) -> None: ... reattach = move - def next(self, item: str) -> str: ... # returning empty string means last item - def parent(self, item: str) -> str: ... - def prev(self, item: str) -> str: ... # returning empty string means first item - def see(self, item: str) -> None: ... - if sys.version_info >= (3, 8): - def selection(self) -> Tuple[str, ...]: ... - else: - def selection(self, selop: Any | None = ..., items: Any | None = ...) -> Tuple[str, ...]: ... - def selection_set(self, items: str | list[str] | Tuple[str, ...]) -> None: ... - def selection_add(self, items: str | list[str] | Tuple[str, ...]) -> None: ... - def selection_remove(self, items: str | list[str] | Tuple[str, ...]) -> None: ... - def selection_toggle(self, items: str | list[str] | Tuple[str, ...]) -> None: ... + def next(self, item: str | int) -> str: ... # returning empty string means last item + def parent(self, item: str | int) -> str: ... + def prev(self, item: str | int) -> str: ... # returning empty string means first item + def see(self, item: str | int) -> None: ... + def selection(self) -> tuple[str, ...]: ... + + @overload + def selection_set(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_set(self, *items: str | int) -> None: ... + + @overload + def selection_add(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_add(self, *items: str | int) -> None: ... + @overload - def set(self, item: str, column: None = ..., value: None = ...) -> dict[str, Any]: ... + def selection_remove(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload - def set(self, item: str, column: _TreeviewColumnId, value: None = ...) -> Any: ... + def selection_remove(self, *items: str | int) -> None: ... + + @overload + def selection_toggle(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_toggle(self, *items: str | int) -> None: ... + @overload - def set(self, item: str, column: _TreeviewColumnId, value: Any) -> Literal[""]: ... + def set(self, item: str | int, column: None = None, value: None = None) -> dict[str, Any]: ... + @overload + def set(self, item: str | int, column: str | int, value: None = None) -> Any: ... + @overload + def set(self, item: str | int, column: str | int, value: Any) -> Literal[""]: ... + # There's no tag_unbind() or 'add' argument for whatever reason. # Also, it's 'callback' instead of 'func' here. @overload def tag_bind( - self, tagname: str, sequence: str | None = ..., callback: Callable[[tkinter.Event[Treeview]], Any] | None = ... + self, tagname: str, sequence: str | None = None, callback: Callable[[tkinter.Event[Treeview]], object] | None = None ) -> str: ... @overload def tag_bind(self, tagname: str, sequence: str | None, callback: str) -> None: ... @overload def tag_bind(self, tagname: str, *, callback: str) -> None: ... + @overload - def tag_configure(self, tagname: str, option: Literal["foreground", "background"]) -> tkinter._Color: ... + def tag_configure(self, tagname: str, option: Literal["foreground", "background"]) -> str: ... @overload def tag_configure(self, tagname: str, option: Literal["font"]) -> _FontDescription: ... @overload @@ -1095,48 +1361,74 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_configure( self, tagname: str, - option: None = ..., + option: None = None, *, # There is also 'text' and 'anchor', but they don't seem to do anything, using them is likely a bug - foreground: tkinter._Color = ..., - background: tkinter._Color = ..., + foreground: str = ..., + background: str = ..., font: _FontDescription = ..., - image: tkinter._ImageSpec = ..., - ) -> _TreeviewTagDict | Any: ... # can be None but annoying to check + image: tkinter._Image | str = ..., + ) -> _TreeviewTagDict | MaybeNone: ... # can be None but annoying to check + @overload - def tag_has(self, tagname: str, item: None = ...) -> Tuple[str, ...]: ... + def tag_has(self, tagname: str, item: None = None) -> tuple[str, ...]: ... @overload - def tag_has(self, tagname: str, item: str) -> bool: ... + def tag_has(self, tagname: str, item: str | int) -> bool: ... class LabeledScale(Frame): - label: Any - scale: Any - # TODO: don't any-type **kw. That goes to Frame.__init__. + label: Label + scale: Scale + # This should be kept in sync with tkinter.ttk.Frame.__init__() + # (all the keyword-only args except compound are from there) def __init__( self, - master: tkinter.Misc | None = ..., - variable: tkinter.IntVar | tkinter.DoubleVar | None = ..., - from_: float = ..., - to: float = ..., + master: tkinter.Misc | None = None, + variable: tkinter.IntVar | tkinter.DoubleVar | None = None, + from_: float = 0, + to: float = 10, *, - compound: Literal["top"] | Literal["bottom"] = ..., - **kw: Any, + border: float | str = ..., + borderwidth: float | str = ..., + class_: str = "", + compound: Literal["top", "bottom"] = "top", + cursor: tkinter._Cursor = "", + height: float | str = 0, + name: str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: float | str = 0, ) -> None: ... # destroy is overridden, signature does not change value: Any class OptionMenu(Menubutton): - def __init__( - self, - master, - variable, - default: str | None = ..., - *values: str, - # rest of these are keyword-only because *args syntax used above - style: str = ..., - direction: Literal["above"] | Literal["below"] | Literal["left"] | Literal["right"] | Literal["flush"] = ..., - command: Callable[[tkinter.StringVar], Any] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 14): + def __init__( + self, + master: tkinter.Misc | None, + variable: tkinter.StringVar, + default: str | None = None, + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, + name: str | None = None, + ) -> None: ... + else: + def __init__( + self, + master: tkinter.Misc | None, + variable: tkinter.StringVar, + default: str | None = None, + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, + ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton # destroy and __setitem__ are overridden, signature does not change - def set_menu(self, default: Any | None = ..., *values): ... + def set_menu(self, default: str | None = None, *values: str) -> None: ... diff --git a/stdlib/token.pyi b/stdlib/token.pyi index 9451015e9df5..23b43250d60f 100644 --- a/stdlib/token.pyi +++ b/stdlib/token.pyi @@ -1,78 +1,165 @@ import sys +from typing import Final -ENDMARKER: int -NAME: int -NUMBER: int -STRING: int -NEWLINE: int -INDENT: int -DEDENT: int -LPAR: int -RPAR: int -LSQB: int -RSQB: int -COLON: int -COMMA: int -SEMI: int -PLUS: int -MINUS: int -STAR: int -SLASH: int -VBAR: int -AMPER: int -LESS: int -GREATER: int -EQUAL: int -DOT: int -PERCENT: int -LBRACE: int -RBRACE: int -EQEQUAL: int -NOTEQUAL: int -LESSEQUAL: int -GREATEREQUAL: int -TILDE: int -CIRCUMFLEX: int -LEFTSHIFT: int -RIGHTSHIFT: int -DOUBLESTAR: int -PLUSEQUAL: int -MINEQUAL: int -STAREQUAL: int -SLASHEQUAL: int -PERCENTEQUAL: int -AMPEREQUAL: int -VBAREQUAL: int -CIRCUMFLEXEQUAL: int -LEFTSHIFTEQUAL: int -RIGHTSHIFTEQUAL: int -DOUBLESTAREQUAL: int -DOUBLESLASH: int -DOUBLESLASHEQUAL: int -AT: int -RARROW: int -ELLIPSIS: int -ATEQUAL: int -if sys.version_info < (3, 7) or sys.version_info >= (3, 8): - # These were removed in Python 3.7 but added back in Python 3.8 - AWAIT: int - ASYNC: int -OP: int -ERRORTOKEN: int -N_TOKENS: int -NT_OFFSET: int -tok_name: dict[int, str] -if sys.version_info >= (3, 7): - COMMENT: int - NL: int - ENCODING: int -if sys.version_info >= (3, 8): - TYPE_COMMENT: int - TYPE_IGNORE: int - COLONEQUAL: int - EXACT_TOKEN_TYPES: dict[str, int] -if sys.version_info >= (3, 10): - SOFT_KEYWORD: int +__all__ = [ + "AMPER", + "AMPEREQUAL", + "AT", + "ATEQUAL", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COLONEQUAL", + "COMMA", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ELLIPSIS", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "SOFT_KEYWORD", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "TYPE_COMMENT", + "TYPE_IGNORE", + "VBAR", + "VBAREQUAL", + "tok_name", + "ENCODING", + "NL", + "COMMENT", +] +if sys.version_info < (3, 13): + __all__ += ["ASYNC", "AWAIT"] + +if sys.version_info >= (3, 12): + __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START", "EXACT_TOKEN_TYPES"] + +if sys.version_info >= (3, 14): + __all__ += ["TSTRING_START", "TSTRING_MIDDLE", "TSTRING_END"] + +ENDMARKER: Final[int] +NAME: Final[int] +NUMBER: Final[int] +STRING: Final[int] +NEWLINE: Final[int] +INDENT: Final[int] +DEDENT: Final[int] +LPAR: Final[int] +RPAR: Final[int] +LSQB: Final[int] +RSQB: Final[int] +COLON: Final[int] +COMMA: Final[int] +SEMI: Final[int] +PLUS: Final[int] +MINUS: Final[int] +STAR: Final[int] +SLASH: Final[int] +VBAR: Final[int] +AMPER: Final[int] +LESS: Final[int] +GREATER: Final[int] +EQUAL: Final[int] +DOT: Final[int] +PERCENT: Final[int] +LBRACE: Final[int] +RBRACE: Final[int] +EQEQUAL: Final[int] +NOTEQUAL: Final[int] +LESSEQUAL: Final[int] +GREATEREQUAL: Final[int] +TILDE: Final[int] +CIRCUMFLEX: Final[int] +LEFTSHIFT: Final[int] +RIGHTSHIFT: Final[int] +DOUBLESTAR: Final[int] +PLUSEQUAL: Final[int] +MINEQUAL: Final[int] +STAREQUAL: Final[int] +SLASHEQUAL: Final[int] +PERCENTEQUAL: Final[int] +AMPEREQUAL: Final[int] +VBAREQUAL: Final[int] +CIRCUMFLEXEQUAL: Final[int] +LEFTSHIFTEQUAL: Final[int] +RIGHTSHIFTEQUAL: Final[int] +DOUBLESTAREQUAL: Final[int] +DOUBLESLASH: Final[int] +DOUBLESLASHEQUAL: Final[int] +AT: Final[int] +RARROW: Final[int] +ELLIPSIS: Final[int] +ATEQUAL: Final[int] +if sys.version_info < (3, 13): + AWAIT: Final[int] + ASYNC: Final[int] +OP: Final[int] +ERRORTOKEN: Final[int] +N_TOKENS: Final[int] +NT_OFFSET: Final[int] +tok_name: Final[dict[int, str]] +COMMENT: Final[int] +NL: Final[int] +ENCODING: Final[int] +TYPE_COMMENT: Final[int] +TYPE_IGNORE: Final[int] +COLONEQUAL: Final[int] +EXACT_TOKEN_TYPES: Final[dict[str, int]] +SOFT_KEYWORD: Final[int] + +if sys.version_info >= (3, 12): + EXCLAMATION: Final[int] + FSTRING_END: Final[int] + FSTRING_MIDDLE: Final[int] + FSTRING_START: Final[int] + +if sys.version_info >= (3, 14): + TSTRING_START: Final[int] + TSTRING_MIDDLE: Final[int] + TSTRING_END: Final[int] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/stdlib/tokenize.pyi b/stdlib/tokenize.pyi index a8294adb653f..0aa3947a178d 100644 --- a/stdlib/tokenize.pyi +++ b/stdlib/tokenize.pyi @@ -1,19 +1,111 @@ import sys -from _typeshed import StrOrBytesPath -from builtins import open as _builtin_open -from token import * # noqa: F403 -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Tuple, Union - -if sys.version_info < (3, 7): - COMMENT: int - NL: int - ENCODING: int - -cookie_re: Pattern[str] -blank_re: Pattern[bytes] - -_Position = Tuple[int, int] - +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Generator, Iterable, Sequence +from re import Pattern +from token import * +from typing import Any, Final, NamedTuple, TextIO, TypeAlias, type_check_only +from typing_extensions import disjoint_base + +if sys.version_info < (3, 12): + # Avoid double assignment to Final name by imports, which pyright objects to. + # EXACT_TOKEN_TYPES is already defined by 'from token import *' above + # in Python 3.12+. + from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES + +__all__ = [ + "AMPER", + "AMPEREQUAL", + "AT", + "ATEQUAL", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COLONEQUAL", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ELLIPSIS", + "ENCODING", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "SOFT_KEYWORD", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "TYPE_COMMENT", + "TYPE_IGNORE", + "TokenInfo", + "VBAR", + "VBAREQUAL", + "detect_encoding", + "generate_tokens", + "tok_name", + "tokenize", + "untokenize", +] +if sys.version_info < (3, 13): + __all__ += ["ASYNC", "AWAIT"] + +if sys.version_info >= (3, 12): + __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START", "EXACT_TOKEN_TYPES"] + +if sys.version_info >= (3, 13): + __all__ += ["TokenError", "open"] + +if sys.version_info >= (3, 14): + __all__ += ["TSTRING_START", "TSTRING_MIDDLE", "TSTRING_END"] + +cookie_re: Final[Pattern[str]] +blank_re: Final[Pattern[bytes]] + +_Position: TypeAlias = tuple[int, int] + +# This class is not exposed. It calls itself tokenize.TokenInfo. +@type_check_only class _TokenInfo(NamedTuple): type: int string: str @@ -21,81 +113,89 @@ class _TokenInfo(NamedTuple): end: _Position line: str -class TokenInfo(_TokenInfo): - @property - def exact_type(self) -> int: ... +if sys.version_info >= (3, 12): + class TokenInfo(_TokenInfo): + @property + def exact_type(self) -> int: ... + +else: + @disjoint_base + class TokenInfo(_TokenInfo): + @property + def exact_type(self) -> int: ... # Backwards compatible tokens can be sequences of a shorter length too -_Token = Union[TokenInfo, Sequence[Union[int, str, _Position]]] +_Token: TypeAlias = TokenInfo | Sequence[int | str | _Position] class TokenError(Exception): ... -class StopTokenizing(Exception): ... # undocumented + +if sys.version_info < (3, 13): + class StopTokenizing(Exception): ... # undocumented class Untokenizer: tokens: list[str] prev_row: int prev_col: int encoding: str | None - def __init__(self) -> None: ... def add_whitespace(self, start: _Position) -> None: ... + if sys.version_info >= (3, 12): + def add_backslash_continuation(self, start: _Position) -> None: ... + def untokenize(self, iterable: Iterable[_Token]) -> str: ... def compat(self, token: Sequence[int | str], iterable: Iterable[_Token]) -> None: ... - -# the docstring says "returns bytes" but is incorrect -- -# if the ENCODING token is missing, it skips the encode -def untokenize(iterable: Iterable[_Token]) -> Any: ... -def detect_encoding(readline: Callable[[], bytes]) -> tuple[str, Sequence[bytes]]: ... -def tokenize(readline: Callable[[], bytes]) -> Generator[TokenInfo, None, None]: ... -def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: ... # undocumented -def open(filename: StrOrBytesPath | int) -> TextIO: ... + if sys.version_info >= (3, 12): + def escape_brackets(self, token: str) -> str: ... + +# Returns str, unless the ENCODING token is present, in which case it returns bytes. +def untokenize(iterable: Iterable[_Token]) -> str | Any: ... +def detect_encoding(readline: Callable[[], bytes | bytearray]) -> tuple[str, Sequence[bytes]]: ... +def tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo]: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo]: ... +def open(filename: FileDescriptorOrPath) -> TextIO: ... def group(*choices: str) -> str: ... # undocumented def any(*choices: str) -> str: ... # undocumented def maybe(*choices: str) -> str: ... # undocumented -Whitespace: str # undocumented -Comment: str # undocumented -Ignore: str # undocumented -Name: str # undocumented - -Hexnumber: str # undocumented -Binnumber: str # undocumented -Octnumber: str # undocumented -Decnumber: str # undocumented -Intnumber: str # undocumented -Exponent: str # undocumented -Pointfloat: str # undocumented -Expfloat: str # undocumented -Floatnumber: str # undocumented -Imagnumber: str # undocumented -Number: str # undocumented +Whitespace: Final[str] # undocumented +Comment: Final[str] # undocumented +Ignore: Final[str] # undocumented +Name: Final[str] # undocumented + +Hexnumber: Final[str] # undocumented +Binnumber: Final[str] # undocumented +Octnumber: Final[str] # undocumented +Decnumber: Final[str] # undocumented +Intnumber: Final[str] # undocumented +Exponent: Final[str] # undocumented +Pointfloat: Final[str] # undocumented +Expfloat: Final[str] # undocumented +Floatnumber: Final[str] # undocumented +Imagnumber: Final[str] # undocumented +Number: Final[str] # undocumented def _all_string_prefixes() -> set[str]: ... # undocumented -StringPrefix: str # undocumented - -Single: str # undocumented -Double: str # undocumented -Single3: str # undocumented -Double3: str # undocumented -Triple: str # undocumented -String: str # undocumented +StringPrefix: Final[str] # undocumented -if sys.version_info < (3, 7): - Operator: str # undocumented - Bracket: str # undocumented +Single: Final[str] # undocumented +Double: Final[str] # undocumented +Single3: Final[str] # undocumented +Double3: Final[str] # undocumented +Triple: Final[str] # undocumented +String: Final[str] # undocumented -Special: str # undocumented -Funny: str # undocumented +Special: Final[str] # undocumented +Funny: Final[str] # undocumented -PlainToken: str # undocumented -Token: str # undocumented +PlainToken: Final[str] # undocumented +Token: Final[str] # undocumented -ContStr: str # undocumented -PseudoExtras: str # undocumented -PseudoToken: str # undocumented +ContStr: Final[str] # undocumented +PseudoExtras: Final[str] # undocumented +PseudoToken: Final[str] # undocumented -endpats: dict[str, str] # undocumented -single_quoted: set[str] # undocumented -triple_quoted: set[str] # undocumented +endpats: Final[dict[str, str]] # undocumented +single_quoted: Final[set[str]] # undocumented +triple_quoted: Final[set[str]] # undocumented -tabsize: int # undocumented +tabsize: Final = 8 # undocumented diff --git a/stdlib/tomllib.pyi b/stdlib/tomllib.pyi new file mode 100644 index 000000000000..7f6df1d9380c --- /dev/null +++ b/stdlib/tomllib.pyi @@ -0,0 +1,27 @@ +import sys +from _typeshed import SupportsRead +from collections.abc import Callable +from typing import Any, overload +from typing_extensions import deprecated + +__all__ = ("loads", "load", "TOMLDecodeError") + +if sys.version_info >= (3, 14): + class TOMLDecodeError(ValueError): + msg: str + doc: str + pos: int + lineno: int + colno: int + + @overload + def __init__(self, msg: str, doc: str, pos: int) -> None: ... + @overload + @deprecated("Deprecated since Python 3.14. Set the 'msg', 'doc' and 'pos' arguments only.") + def __init__(self, msg: str | type = ..., doc: str | type = ..., pos: int | type = ..., *args: Any) -> None: ... + +else: + class TOMLDecodeError(ValueError): ... + +def load(fp: SupportsRead[bytes], /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... +def loads(s: str, /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... diff --git a/stdlib/trace.pyi b/stdlib/trace.pyi index bab75c9ada8d..708233efe3e6 100644 --- a/stdlib/trace.pyi +++ b/stdlib/trace.pyi @@ -1,56 +1,85 @@ import sys import types -from _typeshed import StrPath -from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, TypeVar -from typing_extensions import ParamSpec +from _typeshed import Incomplete, StrPath, TraceFunction +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, ParamSpec, TypeAlias, TypeVar + +__all__ = ["Trace", "CoverageResults"] _T = TypeVar("_T") _P = ParamSpec("_P") -_localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = Tuple[str, Optional[str], str] +_FileModuleFunction: TypeAlias = tuple[str, str | None, str] class CoverageResults: + counts: dict[tuple[str, int], int] + counter: dict[tuple[str, int], int] + calledfuncs: dict[_FileModuleFunction, int] + callers: dict[tuple[_FileModuleFunction, _FileModuleFunction], int] + inifile: StrPath | None + outfile: StrPath | None def __init__( self, - counts: dict[tuple[str, int], int] | None = ..., - calledfuncs: dict[_fileModuleFunction, int] | None = ..., - infile: StrPath | None = ..., - callers: dict[tuple[_fileModuleFunction, _fileModuleFunction], int] | None = ..., - outfile: StrPath | None = ..., + counts: dict[tuple[str, int], int] | None = None, + calledfuncs: dict[_FileModuleFunction, int] | None = None, + infile: StrPath | None = None, + callers: dict[tuple[_FileModuleFunction, _FileModuleFunction], int] | None = None, + outfile: StrPath | None = None, ) -> None: ... # undocumented def update(self, other: CoverageResults) -> None: ... - def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: StrPath | None = ...) -> None: ... + if sys.version_info >= (3, 13): + def write_results( + self, + show_missing: bool = True, + summary: bool = False, + coverdir: StrPath | None = None, + *, + ignore_missing_files: bool = False, + ) -> None: ... + else: + def write_results(self, show_missing: bool = True, summary: bool = False, coverdir: StrPath | None = None) -> None: ... + def write_results_file( - self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = ... + self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = None ) -> tuple[int, int]: ... def is_ignored_filename(self, filename: str) -> bool: ... # undocumented +class _Ignore: + def __init__(self, modules: Iterable[str] | None = None, dirs: Iterable[StrPath] | None = None) -> None: ... + def names(self, filename: str, modulename: str) -> int: ... + class Trace: + inifile: StrPath | None + outfile: StrPath | None + ignore: _Ignore + counts: dict[str, int] + pathtobasename: dict[Incomplete, Incomplete] + donothing: int + trace: int + start_time: int | None + globaltrace: TraceFunction + localtrace: TraceFunction def __init__( self, - count: int = ..., - trace: int = ..., - countfuncs: int = ..., - countcallers: int = ..., - ignoremods: Sequence[str] = ..., - ignoredirs: Sequence[str] = ..., - infile: StrPath | None = ..., - outfile: StrPath | None = ..., - timing: bool = ..., + count: int = 1, + trace: int = 1, + countfuncs: int = 0, + countcallers: int = 0, + ignoremods: Sequence[str] = (), + ignoredirs: Sequence[str] = (), + infile: StrPath | None = None, + outfile: StrPath | None = None, + timing: bool = False, ) -> None: ... def run(self, cmd: str | types.CodeType) -> None: ... def runctx( - self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ... + self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = None, locals: Mapping[str, Any] | None = None ) -> None: ... - if sys.version_info >= (3, 9): - def runfunc(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... # type: ignore - else: - def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... # type: ignore - def file_module_function_of(self, frame: types.FrameType) -> _fileModuleFunction: ... + def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... + def file_module_function_of(self, frame: types.FrameType) -> _FileModuleFunction: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ... - def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... - def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... - def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ... + def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ... + def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ... def results(self) -> CoverageResults: ... diff --git a/stdlib/traceback.pyi b/stdlib/traceback.pyi index f09a3cc70ade..e5b410afdcbc 100644 --- a/stdlib/traceback.pyi +++ b/stdlib/traceback.pyi @@ -1,161 +1,293 @@ import sys -from _typeshed import SupportsWrite +from _typeshed import SupportsWrite, Unused +from collections.abc import Generator, Iterable, Iterator, Mapping from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, List, Mapping, Optional, Tuple, Type, overload +from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, overload +from typing_extensions import Self, deprecated -_PT = Tuple[str, int, str, Optional[str]] +__all__ = [ + "extract_stack", + "extract_tb", + "format_exception", + "format_exception_only", + "format_list", + "format_stack", + "format_tb", + "print_exc", + "format_exc", + "print_exception", + "print_last", + "print_stack", + "print_tb", + "clear_frames", + "FrameSummary", + "StackSummary", + "TracebackException", + "walk_stack", + "walk_tb", +] -def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... +if sys.version_info >= (3, 14): + __all__ += ["print_list"] -if sys.version_info >= (3, 10): +_FrameSummaryTuple: TypeAlias = tuple[str, int, str, str | None] + +def print_tb(tb: TracebackType | None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ... + +@overload +def print_exception( + exc: type[BaseException] | None, + /, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = None, + file: SupportsWrite[str] | None = None, + chain: bool = True, +) -> None: ... +@overload +def print_exception( + exc: BaseException, /, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True +) -> None: ... + +@overload +def format_exception( + exc: type[BaseException] | None, + /, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = None, + chain: bool = True, +) -> list[str]: ... +@overload +def format_exception(exc: BaseException, /, *, limit: int | None = None, chain: bool = True) -> list[str]: ... + +def print_exc(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... +def print_last(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... +def print_stack(f: FrameType | None = None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ... +def extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSummary: ... +def extract_stack(f: FrameType | None = None, limit: int | None = None) -> StackSummary: ... +def format_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> list[str]: ... +def print_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple], file: SupportsWrite[str] | None = None) -> None: ... + +if sys.version_info >= (3, 13): @overload - def print_exception( - __exc: Type[BaseException] | None, - value: BaseException | None = ..., - tb: TracebackType | None = ..., - limit: int | None = ..., - file: IO[str] | None = ..., - chain: bool = ..., - ) -> None: ... + def format_exception_only(exc: BaseException | None, /, *, show_group: bool = False) -> list[str]: ... @overload - def print_exception( - __exc: BaseException, *, limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ... - ) -> None: ... + def format_exception_only(exc: Unused, /, value: BaseException | None, *, show_group: bool = False) -> list[str]: ... +else: @overload - def format_exception( - __exc: Type[BaseException] | None, - value: BaseException | None = ..., - tb: TracebackType | None = ..., - limit: int | None = ..., - chain: bool = ..., - ) -> list[str]: ... + def format_exception_only(exc: BaseException | None, /) -> list[str]: ... @overload - def format_exception(__exc: BaseException, *, limit: int | None = ..., chain: bool = ...) -> list[str]: ... - -else: - def print_exception( - etype: Type[BaseException] | None, - value: BaseException | None, - tb: TracebackType | None, - limit: int | None = ..., - file: IO[str] | None = ..., - chain: bool = ..., - ) -> None: ... - def format_exception( - etype: Type[BaseException] | None, - value: BaseException | None, - tb: TracebackType | None, - limit: int | None = ..., - chain: bool = ..., - ) -> list[str]: ... - -def print_exc(limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ...) -> None: ... -def print_last(limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ...) -> None: ... -def print_stack(f: FrameType | None = ..., limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> StackSummary: ... -def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> StackSummary: ... -def format_list(extracted_list: list[FrameSummary]) -> list[str]: ... - -# undocumented -def print_list(extracted_list: list[FrameSummary], file: SupportsWrite[str] | None = ...) -> None: ... - -if sys.version_info >= (3, 10): - def format_exception_only(__exc: Type[BaseException] | None, value: BaseException | None = ...) -> list[str]: ... + def format_exception_only(exc: Unused, /, value: BaseException | None) -> list[str]: ... -else: - def format_exception_only(etype: Type[BaseException] | None, value: BaseException | None) -> list[str]: ... - -def format_exc(limit: int | None = ..., chain: bool = ...) -> str: ... -def format_tb(tb: TracebackType | None, limit: int | None = ...) -> list[str]: ... -def format_stack(f: FrameType | None = ..., limit: int | None = ...) -> list[str]: ... -def clear_frames(tb: TracebackType) -> None: ... +def format_exc(limit: int | None = None, chain: bool = True) -> str: ... +def format_tb(tb: TracebackType | None, limit: int | None = None) -> list[str]: ... +def format_stack(f: FrameType | None = None, limit: int | None = None) -> list[str]: ... +def clear_frames(tb: TracebackType | None) -> None: ... def walk_stack(f: FrameType | None) -> Iterator[tuple[FrameType, int]]: ... def walk_tb(tb: TracebackType | None) -> Iterator[tuple[FrameType, int]]: ... +if sys.version_info >= (3, 11): + class _ExceptionPrintContext: + def indent(self) -> str: ... + def emit(self, text_gen: str | Iterable[str], margin_char: str | None = None) -> Generator[str]: ... + class TracebackException: - __cause__: TracebackException - __context__: TracebackException + __cause__: TracebackException | None + __context__: TracebackException | None + if sys.version_info >= (3, 11): + exceptions: list[TracebackException] | None __suppress_context__: bool + if sys.version_info >= (3, 11): + __notes__: list[str] | None stack: StackSummary - exc_type: Type[BaseException] + + # These fields only exist for `SyntaxError`s, but there is no way to express that in the type system. filename: str - lineno: int + lineno: str | None + end_lineno: str | None text: str offset: int + end_offset: int | None msg: str - if sys.version_info >= (3, 10): + + if sys.version_info >= (3, 13): + @property + def exc_type_str(self) -> str: ... + @property + @deprecated("Deprecated since Python 3.13. Use `exc_type_str` instead.") + def exc_type(self) -> type[BaseException] | None: ... + else: + exc_type: type[BaseException] + if sys.version_info >= (3, 13): def __init__( self, - exc_type: Type[BaseException], + exc_type: type[BaseException], exc_value: BaseException, - exc_traceback: TracebackType, + exc_traceback: TracebackType | None, *, - limit: int | None = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - compact: bool = ..., - _seen: set[int] | None = ..., + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + max_group_width: int = 15, + max_group_depth: int = 10, + save_exc_type: bool = True, + _seen: set[int] | None = None, ) -> None: ... - @classmethod - def from_exception( - cls, - exc: BaseException, + elif sys.version_info >= (3, 11): + def __init__( + self, + exc_type: type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType | None, *, - limit: int | None = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - compact: bool = ..., - ) -> TracebackException: ... + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + max_group_width: int = 15, + max_group_depth: int = 10, + _seen: set[int] | None = None, + ) -> None: ... else: def __init__( self, - exc_type: Type[BaseException], + exc_type: type[BaseException], exc_value: BaseException, - exc_traceback: TracebackType, + exc_traceback: TracebackType | None, *, - limit: int | None = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - _seen: set[int] | None = ..., + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + _seen: set[int] | None = None, ) -> None: ... + + if sys.version_info >= (3, 11): + @classmethod + def from_exception( + cls, + exc: BaseException, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + max_group_width: int = 15, + max_group_depth: int = 10, + ) -> Self: ... + else: @classmethod def from_exception( - cls, exc: BaseException, *, limit: int | None = ..., lookup_lines: bool = ..., capture_locals: bool = ... - ) -> TracebackException: ... - def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... - def format_exception_only(self) -> Generator[str, None, None]: ... + cls, + exc: BaseException, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + ) -> Self: ... + + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 11): + def format(self, *, chain: bool = True, _ctx: _ExceptionPrintContext | None = None) -> Generator[str]: ... + else: + def format(self, *, chain: bool = True) -> Generator[str]: ... + + if sys.version_info >= (3, 13): + def format_exception_only(self, *, show_group: bool = False, _depth: int = 0) -> Generator[str]: ... + else: + def format_exception_only(self) -> Generator[str]: ... -class FrameSummary(Iterable[Any]): + if sys.version_info >= (3, 11): + def print(self, *, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... + +class FrameSummary: + if sys.version_info >= (3, 13): + __slots__ = ( + "filename", + "lineno", + "end_lineno", + "colno", + "end_colno", + "name", + "_lines", + "_lines_dedented", + "locals", + "_code", + ) + elif sys.version_info >= (3, 11): + __slots__ = ("filename", "lineno", "end_lineno", "colno", "end_colno", "name", "_line", "locals") + else: + __slots__ = ("filename", "lineno", "name", "_line", "locals") + if sys.version_info >= (3, 11): + def __init__( + self, + filename: str, + lineno: int | None, + name: str, + *, + lookup_line: bool = True, + locals: Mapping[str, str] | None = None, + line: str | None = None, + end_lineno: int | None = None, + colno: int | None = None, + end_colno: int | None = None, + ) -> None: ... + end_lineno: int | None + colno: int | None + end_colno: int | None + else: + def __init__( + self, + filename: str, + lineno: int | None, + name: str, + *, + lookup_line: bool = True, + locals: Mapping[str, str] | None = None, + line: str | None = None, + ) -> None: ... filename: str - lineno: int + lineno: int | None name: str - line: str locals: dict[str, str] | None - def __init__( - self, - filename: str, - lineno: int, - name: str, - *, - lookup_line: bool = ..., - locals: Mapping[str, str] | None = ..., - line: str | None = ..., - ) -> None: ... - # TODO: more precise typing for __getitem__ and __iter__, - # for a namedtuple-like view on (filename, lineno, name, str). - def __getitem__(self, i: int) -> Any: ... + @property + def line(self) -> str | None: ... + + @overload + def __getitem__(self, pos: Literal[0]) -> str: ... + @overload + def __getitem__(self, pos: Literal[1]) -> int: ... + @overload + def __getitem__(self, pos: Literal[2]) -> str: ... + @overload + def __getitem__(self, pos: Literal[3]) -> str | None: ... + @overload + def __getitem__(self, pos: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, pos: slice[SupportsIndex | None]) -> tuple[Any, ...]: ... + def __iter__(self) -> Iterator[Any]: ... + def __eq__(self, other: object) -> bool: ... + def __len__(self) -> Literal[4]: ... + __hash__: ClassVar[None] # type: ignore[assignment] -class StackSummary(List[FrameSummary]): +class StackSummary(list[FrameSummary]): @classmethod def extract( cls, frame_gen: Iterable[tuple[FrameType, int]], *, - limit: int | None = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, ) -> StackSummary: ... @classmethod - def from_list(cls, a_list: list[_PT]) -> StackSummary: ... + def from_list(cls, a_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> StackSummary: ... + if sys.version_info >= (3, 11): + def format_frame_summary(self, frame_summary: FrameSummary) -> str: ... + def format(self) -> list[str]: ... diff --git a/stdlib/tracemalloc.pyi b/stdlib/tracemalloc.pyi index 4666bd1565a0..e56aa19240fd 100644 --- a/stdlib/tracemalloc.pyi +++ b/stdlib/tracemalloc.pyi @@ -1,81 +1,123 @@ import sys from _tracemalloc import * -from typing import Optional, Sequence, Tuple, Union, overload -from typing_extensions import SupportsIndex +from collections.abc import Sequence +from typing import Any, SupportsIndex, TypeAlias, overload def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... -class DomainFilter: +class BaseFilter: inclusive: bool - domain: int + def __init__(self, inclusive: bool) -> None: ... + +class DomainFilter(BaseFilter): + @property + def domain(self) -> int: ... def __init__(self, inclusive: bool, domain: int) -> None: ... -class Filter: +class Filter(BaseFilter): domain: int | None - inclusive: bool lineno: int | None - filename_pattern: str + @property + def filename_pattern(self) -> str: ... all_frames: bool def __init__( - self, inclusive: bool, filename_pattern: str, lineno: int | None = ..., all_frames: bool = ..., domain: int | None = ... + self, + inclusive: bool, + filename_pattern: str, + lineno: int | None = None, + all_frames: bool = False, + domain: int | None = None, ) -> None: ... class Statistic: + __slots__ = ("traceback", "size", "count") count: int size: int traceback: Traceback def __init__(self, traceback: Traceback, size: int, count: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... class StatisticDiff: + __slots__ = ("traceback", "size", "size_diff", "count", "count_diff") count: int count_diff: int size: int size_diff: int traceback: Traceback def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... -_FrameTupleT = Tuple[str, int] +_FrameTuple: TypeAlias = tuple[str, int] class Frame: - filename: str - lineno: int - def __init__(self, frame: _FrameTupleT) -> None: ... + __slots__ = ("_frame",) + @property + def filename(self) -> str: ... + @property + def lineno(self) -> int: ... + def __init__(self, frame: _FrameTuple) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Frame) -> bool: ... + if sys.version_info >= (3, 11): + def __gt__(self, other: Frame) -> bool: ... + def __ge__(self, other: Frame) -> bool: ... + def __le__(self, other: Frame) -> bool: ... + else: + def __gt__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + def __ge__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... -if sys.version_info >= (3, 9): - _TraceTupleT = Union[Tuple[int, int, Sequence[_FrameTupleT], Optional[int]], Tuple[int, int, Sequence[_FrameTupleT]]] -else: - _TraceTupleT = Tuple[int, int, Sequence[_FrameTupleT]] +_TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]] class Trace: - domain: int - size: int - traceback: Traceback - def __init__(self, trace: _TraceTupleT) -> None: ... + __slots__ = ("_trace",) + @property + def domain(self) -> int: ... + @property + def size(self) -> int: ... + @property + def traceback(self) -> Traceback: ... + def __init__(self, trace: _TraceTuple) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... class Traceback(Sequence[Frame]): - if sys.version_info >= (3, 9): - total_nframe: int | None - def __init__(self, frames: Sequence[_FrameTupleT], total_nframe: int | None = ...) -> None: ... - else: - def __init__(self, frames: Sequence[_FrameTupleT]) -> None: ... - if sys.version_info >= (3, 7): - def format(self, limit: int | None = ..., most_recent_first: bool = ...) -> list[str]: ... - else: - def format(self, limit: int | None = ...) -> list[str]: ... + __slots__ = ("_frames", "_total_nframe") + @property + def total_nframe(self) -> int | None: ... + def __init__(self, frames: Sequence[_FrameTuple], total_nframe: int | None = None) -> None: ... + def format(self, limit: int | None = None, most_recent_first: bool = False) -> list[str]: ... + @overload - def __getitem__(self, i: SupportsIndex) -> Frame: ... + def __getitem__(self, index: SupportsIndex) -> Frame: ... @overload - def __getitem__(self, s: slice) -> Sequence[Frame]: ... + def __getitem__(self, index: slice[SupportsIndex | None]) -> Sequence[Frame]: ... + + def __contains__(self, frame: Frame) -> bool: ... # type: ignore[override] def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Traceback) -> bool: ... + if sys.version_info >= (3, 11): + def __gt__(self, other: Traceback) -> bool: ... + def __ge__(self, other: Traceback) -> bool: ... + def __le__(self, other: Traceback) -> bool: ... + else: + def __gt__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + def __ge__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... class Snapshot: - def __init__(self, traces: Sequence[_TraceTupleT], traceback_limit: int) -> None: ... - def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = ...) -> list[StatisticDiff]: ... + def __init__(self, traces: Sequence[_TraceTuple], traceback_limit: int) -> None: ... + def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = False) -> list[StatisticDiff]: ... def dump(self, filename: str) -> None: ... def filter_traces(self, filters: Sequence[DomainFilter | Filter]) -> Snapshot: ... @staticmethod def load(filename: str) -> Snapshot: ... - def statistics(self, key_type: str, cumulative: bool = ...) -> list[Statistic]: ... + def statistics(self, key_type: str, cumulative: bool = False) -> list[Statistic]: ... traceback_limit: int traces: Sequence[Trace] diff --git a/stdlib/tty.pyi b/stdlib/tty.pyi index c0dc418e9933..a0478335a3f3 100644 --- a/stdlib/tty.pyi +++ b/stdlib/tty.pyi @@ -1,15 +1,29 @@ -from typing import IO, Union +import sys +import termios +from typing import IO, Final, TypeAlias -_FD = Union[int, IO[str]] +if sys.platform != "win32": + __all__ = ["setraw", "setcbreak"] + if sys.version_info >= (3, 12): + __all__ += ["cfmakeraw", "cfmakecbreak"] -# XXX: Undocumented integer constants -IFLAG: int -OFLAG: int -CFLAG: int -LFLAG: int -ISPEED: int -OSPEED: int -CC: int + _ModeSetterReturn: TypeAlias = termios._AttrReturn + else: + _ModeSetterReturn: TypeAlias = None -def setraw(fd: _FD, when: int = ...) -> None: ... -def setcbreak(fd: _FD, when: int = ...) -> None: ... + _FD: TypeAlias = int | IO[str] + + # XXX: Undocumented integer constants + IFLAG: Final = 0 + OFLAG: Final = 1 + CFLAG: Final = 2 + LFLAG: Final = 3 + ISPEED: Final = 4 + OSPEED: Final = 5 + CC: Final = 6 + def setraw(fd: _FD, when: int = 2) -> _ModeSetterReturn: ... + def setcbreak(fd: _FD, when: int = 2) -> _ModeSetterReturn: ... + + if sys.version_info >= (3, 12): + def cfmakeraw(mode: termios._Attr) -> None: ... + def cfmakecbreak(mode: termios._Attr) -> None: ... diff --git a/stdlib/turtle.pyi b/stdlib/turtle.pyi index 8542fc8bfa24..1152e9603335 100644 --- a/stdlib/turtle.pyi +++ b/stdlib/turtle.pyi @@ -1,26 +1,214 @@ -from tkinter import Canvas, Frame, PhotoImage -from typing import Any, Callable, ClassVar, Dict, Sequence, Tuple, TypeVar, Union, overload +import sys +from _typeshed import StrPath +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base + +__all__ = [ + "ScrolledCanvas", + "TurtleScreen", + "Screen", + "RawTurtle", + "Turtle", + "RawPen", + "Pen", + "Shape", + "Vec2D", + "addshape", + "bgcolor", + "bgpic", + "bye", + "clearscreen", + "colormode", + "delay", + "exitonclick", + "getcanvas", + "getshapes", + "listen", + "mainloop", + "mode", + "numinput", + "onkey", + "onkeypress", + "onkeyrelease", + "onscreenclick", + "ontimer", + "register_shape", + "resetscreen", + "screensize", + "setup", + "setworldcoordinates", + "textinput", + "title", + "tracer", + "turtles", + "update", + "window_height", + "window_width", + "back", + "backward", + "begin_fill", + "begin_poly", + "bk", + "circle", + "clear", + "clearstamp", + "clearstamps", + "clone", + "color", + "degrees", + "distance", + "dot", + "down", + "end_fill", + "end_poly", + "fd", + "fillcolor", + "filling", + "forward", + "get_poly", + "getpen", + "getscreen", + "get_shapepoly", + "getturtle", + "goto", + "heading", + "hideturtle", + "home", + "ht", + "isdown", + "isvisible", + "left", + "lt", + "onclick", + "ondrag", + "onrelease", + "pd", + "pen", + "pencolor", + "pendown", + "pensize", + "penup", + "pos", + "position", + "pu", + "radians", + "right", + "reset", + "resizemode", + "rt", + "seth", + "setheading", + "setpos", + "setposition", + "setundobuffer", + "setx", + "sety", + "shape", + "shapesize", + "shapetransform", + "shearfactor", + "showturtle", + "speed", + "st", + "stamp", + "tilt", + "tiltangle", + "towards", + "turtlesize", + "undo", + "undobufferentries", + "up", + "width", + "write", + "xcor", + "ycor", + "write_docstringdict", + "done", + "Terminator", +] + +if sys.version_info >= (3, 14): + __all__ += ["fill", "no_animation", "poly", "save"] + +if sys.version_info >= (3, 12): + __all__ += ["teleport"] + +if sys.version_info < (3, 13): + __all__ += ["settiltangle"] # Note: '_Color' is the alias we use for arguments and _AnyColor is the # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color = Union[str, Tuple[float, float, float]] -_AnyColor = Any - -# TODO: Replace this with a TypedDict once it becomes standardized. -_PenState = Dict[str, Any] - -_Speed = Union[str, float] -_PolygonCoords = Sequence[Tuple[float, float]] - -# TODO: Type this more accurately -# Vec2D is actually a custom subclass of 'tuple'. -Vec2D = Tuple[float, float] - -class ScrolledCanvas(Frame): ... +_Color: TypeAlias = str | tuple[float, float, float] +_AnyColor: TypeAlias = Any + +@type_check_only +class _PenState(TypedDict): + shown: bool + pendown: bool + pencolor: _Color + fillcolor: _Color + pensize: int + speed: int + resizemode: Literal["auto", "user", "noresize"] + stretchfactor: tuple[float, float] + shearfactor: float + outline: int + tilt: float + +_Speed: TypeAlias = str | float +_PolygonCoords: TypeAlias = Sequence[tuple[float, float]] + +if sys.version_info >= (3, 12): + class Vec2D(tuple[float, float]): + def __new__(cls, x: float, y: float) -> Self: ... + def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + + @overload # type: ignore[override] + def __mul__(self, other: Vec2D) -> float: ... + @overload + def __mul__(self, other: float) -> Vec2D: ... + + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] + def __sub__(self, other: tuple[float, float]) -> Vec2D: ... + def __neg__(self) -> Vec2D: ... + def __abs__(self) -> float: ... + def rotate(self, angle: float) -> Vec2D: ... + +else: + @disjoint_base + class Vec2D(tuple[float, float]): + def __new__(cls, x: float, y: float) -> Self: ... + def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + + @overload # type: ignore[override] + def __mul__(self, other: Vec2D) -> float: ... + @overload + def __mul__(self, other: float) -> Vec2D: ... + + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] + def __sub__(self, other: tuple[float, float]) -> Vec2D: ... + def __neg__(self) -> Vec2D: ... + def __abs__(self) -> float: ... + def rotate(self, angle: float) -> Vec2D: ... + +# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas +class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + bg: str + hscroll: Scrollbar + vscroll: Scrollbar + def __init__( + self, master: Misc | None, width: int = 500, height: int = 350, canvwidth: int = 600, canvheight: int = 500 + ) -> None: ... + canvwidth: int + canvheight: int + def reset(self, canvwidth: int | None = None, canvheight: int | None = None, bg: str | None = None) -> None: ... -class TurtleScreenBase(object): +class TurtleScreenBase: cv: Canvas canvwidth: int canvheight: int @@ -30,79 +218,103 @@ class TurtleScreenBase(object): def mainloop(self) -> None: ... def textinput(self, title: str, prompt: str) -> str | None: ... def numinput( - self, title: str, prompt: str, default: float | None = ..., minval: float | None = ..., maxval: float | None = ... + self, title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None ) -> float | None: ... class Terminator(Exception): ... class TurtleGraphicsError(Exception): ... -class Shape(object): - def __init__(self, type_: str, data: _PolygonCoords | PhotoImage | None = ...) -> None: ... - def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = ...) -> None: ... +class Shape: + def __init__( + self, type_: Literal["polygon", "image", "compound"], data: _PolygonCoords | PhotoImage | None = None + ) -> None: ... + def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = None) -> None: ... class TurtleScreen(TurtleScreenBase): - def __init__(self, cv: Canvas, mode: str = ..., colormode: float = ..., delay: int = ...) -> None: ... + def __init__( + self, cv: Canvas, mode: Literal["standard", "logo", "world"] = "standard", colormode: float = 1.0, delay: int = 10 + ) -> None: ... def clear(self) -> None: ... + @overload - def mode(self, mode: None = ...) -> str: ... + def mode(self, mode: None = None) -> str: ... @overload - def mode(self, mode: str) -> None: ... + def mode(self, mode: Literal["standard", "logo", "world"]) -> None: ... + def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ... - def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = ...) -> None: ... + def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = None) -> None: ... + @overload - def colormode(self, cmode: None = ...) -> float: ... + def colormode(self, cmode: None = None) -> float: ... @overload def colormode(self, cmode: float) -> None: ... + def reset(self) -> None: ... def turtles(self) -> list[Turtle]: ... + @overload def bgcolor(self) -> _AnyColor: ... @overload def bgcolor(self, color: _Color) -> None: ... @overload def bgcolor(self, r: float, g: float, b: float) -> None: ... + @overload - def tracer(self, n: None = ...) -> int: ... + def tracer(self, n: None = None) -> int: ... @overload - def tracer(self, n: int, delay: int | None = ...) -> None: ... + def tracer(self, n: int, delay: int | None = None) -> None: ... + @overload - def delay(self, delay: None = ...) -> int: ... + def delay(self, delay: None = None) -> int: ... @overload def delay(self, delay: int) -> None: ... + + if sys.version_info >= (3, 14): + @contextmanager + def no_animation(self) -> Generator[None]: ... + def update(self) -> None: ... def window_width(self) -> int: ... def window_height(self) -> int: ... def getcanvas(self) -> Canvas: ... def getshapes(self) -> list[str]: ... - def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... - def onkey(self, fun: Callable[[], Any], key: str) -> None: ... - def listen(self, xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... - def ontimer(self, fun: Callable[[], Any], t: int = ...) -> None: ... + def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def onkey(self, fun: Callable[[], object], key: str) -> None: ... + def listen(self, xdummy: float | None = None, ydummy: float | None = None) -> None: ... + def ontimer(self, fun: Callable[[], object], t: int = 0) -> None: ... + @overload - def bgpic(self, picname: None = ...) -> str: ... + def bgpic(self, picname: None = None) -> str: ... @overload def bgpic(self, picname: str) -> None: ... + @overload - def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ... + def screensize(self, canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ... # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well @overload - def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... + def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ... + + if sys.version_info >= (3, 14): + def save(self, filename: StrPath, *, overwrite: bool = False) -> None: ... onscreenclick = onclick resetscreen = reset clearscreen = clear addshape = register_shape - def onkeypress(self, fun: Callable[[], Any], key: str | None = ...) -> None: ... + def onkeypress(self, fun: Callable[[], object], key: str | None = None) -> None: ... onkeyrelease = onkey -class TNavigator(object): +class TNavigator: START_ORIENTATION: dict[str, Vec2D] DEFAULT_MODE: str DEFAULT_ANGLEOFFSET: int DEFAULT_ANGLEORIENT: int - def __init__(self, mode: str = ...) -> None: ... + def __init__(self, mode: Literal["standard", "logo", "world"] = "standard") -> None: ... def reset(self) -> None: ... - def degrees(self, fullcircle: float = ...) -> None: ... + def degrees(self, fullcircle: float = 360.0) -> None: ... def radians(self) -> None: ... + if sys.version_info >= (3, 12): + def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + def forward(self, distance: float) -> None: ... def back(self, distance: float) -> None: ... def right(self, angle: float) -> None: ... @@ -110,24 +322,30 @@ class TNavigator(object): def pos(self) -> Vec2D: ... def xcor(self) -> float: ... def ycor(self) -> float: ... + @overload - def goto(self, x: tuple[float, float], y: None = ...) -> None: ... + def goto(self, x: tuple[float, float], y: None = None) -> None: ... @overload def goto(self, x: float, y: float) -> None: ... + def home(self) -> None: ... def setx(self, x: float) -> None: ... def sety(self, y: float) -> None: ... + @overload - def distance(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ... + def distance(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def distance(self, x: float, y: float) -> float: ... + @overload - def towards(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ... + def towards(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def towards(self, x: float, y: float) -> float: ... + def heading(self) -> float: ... def setheading(self, to_angle: float) -> None: ... - def circle(self, radius: float, extent: float | None = ..., steps: int | None = ...) -> None: ... + def circle(self, radius: float, extent: float | None = None, steps: int | None = None) -> None: ... + def speed(self, s: int | None = 0) -> int | None: ... fd = forward bk = back backward = back @@ -138,35 +356,42 @@ class TNavigator(object): setposition = goto seth = setheading -class TPen(object): - def __init__(self, resizemode: str = ...) -> None: ... +class TPen: + def __init__(self, resizemode: Literal["auto", "user", "noresize"] = "noresize") -> None: ... + @overload - def resizemode(self, rmode: None = ...) -> str: ... + def resizemode(self, rmode: None = None) -> str: ... @overload - def resizemode(self, rmode: str) -> None: ... + def resizemode(self, rmode: Literal["auto", "user", "noresize"]) -> None: ... + @overload - def pensize(self, width: None = ...) -> int: ... + def pensize(self, width: None = None) -> int: ... @overload def pensize(self, width: int) -> None: ... + def penup(self) -> None: ... def pendown(self) -> None: ... def isdown(self) -> bool: ... + @overload - def speed(self, speed: None = ...) -> int: ... + def speed(self, speed: None = None) -> int: ... @overload def speed(self, speed: _Speed) -> None: ... + @overload def pencolor(self) -> _AnyColor: ... @overload def pencolor(self, color: _Color) -> None: ... @overload def pencolor(self, r: float, g: float, b: float) -> None: ... + @overload def fillcolor(self) -> _AnyColor: ... @overload def fillcolor(self, color: _Color) -> None: ... @overload def fillcolor(self, r: float, g: float, b: float) -> None: ... + @overload def color(self) -> tuple[_AnyColor, _AnyColor]: ... @overload @@ -175,16 +400,21 @@ class TPen(object): def color(self, r: float, g: float, b: float) -> None: ... @overload def color(self, color1: _Color, color2: _Color) -> None: ... + + if sys.version_info >= (3, 12): + def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + def showturtle(self) -> None: ... def hideturtle(self) -> None: ... def isvisible(self) -> bool: ... + # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload - def pen(self) -> _PenState: ... # type: ignore[misc] + def pen(self) -> _PenState: ... @overload def pen( self, - pen: _PenState | None = ..., + pen: _PenState | None = None, *, shown: bool = ..., pendown: bool = ..., @@ -192,11 +422,12 @@ class TPen(object): fillcolor: _Color = ..., pensize: int = ..., speed: int = ..., - resizemode: str = ..., + resizemode: Literal["auto", "user", "noresize"] = ..., stretchfactor: tuple[float, float] = ..., outline: int = ..., tilt: float = ..., ) -> None: ... + width = pensize up = penup pu = penup @@ -205,68 +436,97 @@ class TPen(object): st = showturtle ht = hideturtle -_T = TypeVar("_T") - -class RawTurtle(TPen, TNavigator): +class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods in base classes # pyrefly: ignore [inconsistent-inheritance] screen: TurtleScreen screens: ClassVar[list[TurtleScreen]] def __init__( - self, canvas: Canvas | TurtleScreen | None = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ... + self, + canvas: Canvas | TurtleScreen | None = None, + shape: str = "classic", + undobuffersize: int = 1000, + visible: bool = True, ) -> None: ... def reset(self) -> None: ... def setundobuffer(self, size: int | None) -> None: ... def undobufferentries(self) -> int: ... def clear(self) -> None: ... - def clone(self: _T) -> _T: ... + def clone(self) -> Self: ... + @overload - def shape(self, name: None = ...) -> str: ... + def shape(self, name: None = None) -> str: ... @overload def shape(self, name: str) -> None: ... + # Unsafely overlaps when no arguments are provided @overload - def shapesize(self) -> tuple[float, float, float]: ... # type: ignore[misc] + def shapesize(self) -> tuple[float, float, float]: ... @overload def shapesize( - self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ... + self, stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None ) -> None: ... + @overload - def shearfactor(self, shear: None = ...) -> float: ... + def shearfactor(self, shear: None = None) -> float: ... @overload def shearfactor(self, shear: float) -> None: ... + # Unsafely overlaps when no arguments are provided @overload - def shapetransform(self) -> tuple[float, float, float, float]: ... # type: ignore[misc] + def shapetransform(self) -> tuple[float, float, float, float]: ... @overload def shapetransform( - self, t11: float | None = ..., t12: float | None = ..., t21: float | None = ..., t22: float | None = ... + self, t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None ) -> None: ... + def get_shapepoly(self) -> _PolygonCoords | None: ... - def settiltangle(self, angle: float) -> None: ... + + if sys.version_info < (3, 13): + @deprecated("Deprecated since Python 3.1; removed in Python 3.13. Use `tiltangle()` instead.") + def settiltangle(self, angle: float) -> None: ... + @overload - def tiltangle(self, angle: None = ...) -> float: ... + def tiltangle(self, angle: None = None) -> float: ... @overload def tiltangle(self, angle: float) -> None: ... + def tilt(self, angle: float) -> None: ... # Can return either 'int' or Tuple[int, ...] based on if the stamp is # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp(self) -> Any: ... - def clearstamp(self, stampid: int | Tuple[int, ...]) -> None: ... - def clearstamps(self, n: int | None = ...) -> None: ... + def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ... + def clearstamps(self, n: int | None = None) -> None: ... def filling(self) -> bool: ... + if sys.version_info >= (3, 14): + @contextmanager + def fill(self) -> Generator[None]: ... + def begin_fill(self) -> None: ... def end_fill(self) -> None: ... - def dot(self, size: int | None = ..., *color: _Color) -> None: ... - def write(self, arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...) -> None: ... + + @overload + def dot(self, size: int | _Color | None = None) -> None: ... + @overload + def dot(self, size: int | None, color: _Color, /) -> None: ... + @overload + def dot(self, size: int | None, r: float, g: float, b: float, /) -> None: ... + + def write( + self, arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal") + ) -> None: ... + if sys.version_info >= (3, 14): + @contextmanager + def poly(self) -> Generator[None]: ... + def begin_poly(self) -> None: ... def end_poly(self) -> None: ... def get_poly(self) -> _PolygonCoords | None: ... def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... + def getturtle(self) -> Self: ... getpen = getturtle - def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... - def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... - def ondrag(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... + def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def onrelease(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def ondrag(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... def undo(self) -> None: ... turtlesize = shapesize @@ -274,98 +534,108 @@ class _Screen(TurtleScreen): def __init__(self) -> None: ... # Note int and float are interpreted differently, hence the Union instead of just float def setup( - self, width: int | float = ..., height: int | float = ..., startx: int | None = ..., starty: int | None = ... + self, + width: int | float = 0.5, # noqa: Y041 + height: int | float = 0.75, # noqa: Y041 + startx: int | None = None, + starty: int | None = None, ) -> None: ... def title(self, titlestring: str) -> None: ... def bye(self) -> None: ... def exitonclick(self) -> None: ... class Turtle(RawTurtle): - def __init__(self, shape: str = ..., undobuffersize: int = ..., visible: bool = ...) -> None: ... + def __init__(self, shape: str = "classic", undobuffersize: int = 1000, visible: bool = True) -> None: ... RawPen = RawTurtle Pen = Turtle -def write_docstringdict(filename: str = ...) -> None: ... - -# Note: it's somewhat unfortunate that we have to copy the function signatures. -# It would be nice if we could partially reduce the redundancy by doing something -# like the following: -# -# _screen: Screen -# clear = _screen.clear -# -# However, it seems pytype does not support this type of syntax in pyi files. +def write_docstringdict(filename: str = "turtle_docstringdict") -> None: ... # Functions copied from TurtleScreenBase: -# Note: mainloop() was always present in the global scope, but was added to -# TurtleScreenBase in Python 3.0 def mainloop() -> None: ... def textinput(title: str, prompt: str) -> str | None: ... def numinput( - title: str, prompt: str, default: float | None = ..., minval: float | None = ..., maxval: float | None = ... + title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None ) -> float | None: ... # Functions copied from TurtleScreen: def clear() -> None: ... + @overload -def mode(mode: None = ...) -> str: ... +def mode(mode: None = None) -> str: ... @overload -def mode(mode: str) -> None: ... +def mode(mode: Literal["standard", "logo", "world"]) -> None: ... + def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ... -def register_shape(name: str, shape: _PolygonCoords | Shape | None = ...) -> None: ... +def register_shape(name: str, shape: _PolygonCoords | Shape | None = None) -> None: ... + @overload -def colormode(cmode: None = ...) -> float: ... +def colormode(cmode: None = None) -> float: ... @overload def colormode(cmode: float) -> None: ... + def reset() -> None: ... def turtles() -> list[Turtle]: ... + @overload def bgcolor() -> _AnyColor: ... @overload def bgcolor(color: _Color) -> None: ... @overload def bgcolor(r: float, g: float, b: float) -> None: ... + @overload -def tracer(n: None = ...) -> int: ... +def tracer(n: None = None) -> int: ... @overload -def tracer(n: int, delay: int | None = ...) -> None: ... +def tracer(n: int, delay: int | None = None) -> None: ... + @overload -def delay(delay: None = ...) -> int: ... +def delay(delay: None = None) -> int: ... @overload def delay(delay: int) -> None: ... + +if sys.version_info >= (3, 14): + @contextmanager + def no_animation() -> Generator[None]: ... + def update() -> None: ... def window_width() -> int: ... def window_height() -> int: ... def getcanvas() -> Canvas: ... def getshapes() -> list[str]: ... -def onclick(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... -def onkey(fun: Callable[[], Any], key: str) -> None: ... -def listen(xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... -def ontimer(fun: Callable[[], Any], t: int = ...) -> None: ... +def onclick(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... +def onkey(fun: Callable[[], object], key: str) -> None: ... +def listen(xdummy: float | None = None, ydummy: float | None = None) -> None: ... +def ontimer(fun: Callable[[], object], t: int = 0) -> None: ... + @overload -def bgpic(picname: None = ...) -> str: ... +def bgpic(picname: None = None) -> str: ... @overload def bgpic(picname: str) -> None: ... + @overload -def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ... +def screensize(canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ... @overload -def screensize(canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... +def screensize(canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ... + +if sys.version_info >= (3, 14): + def save(filename: StrPath, *, overwrite: bool = False) -> None: ... onscreenclick = onclick resetscreen = reset clearscreen = clear addshape = register_shape -def onkeypress(fun: Callable[[], Any], key: str | None = ...) -> None: ... +def onkeypress(fun: Callable[[], object], key: str | None = None) -> None: ... onkeyrelease = onkey # Functions copied from _Screen: -def setup(width: float = ..., height: float = ..., startx: int | None = ..., starty: int | None = ...) -> None: ... +def setup(width: float = 0.5, height: float = 0.75, startx: int | None = None, starty: int | None = None) -> None: ... def title(titlestring: str) -> None: ... def bye() -> None: ... def exitonclick() -> None: ... @@ -373,7 +643,7 @@ def Screen() -> _Screen: ... # Functions copied from TNavigator: -def degrees(fullcircle: float = ...) -> None: ... +def degrees(fullcircle: float = 360.0) -> None: ... def radians() -> None: ... def forward(distance: float) -> None: ... def back(distance: float) -> None: ... @@ -382,24 +652,29 @@ def left(angle: float) -> None: ... def pos() -> Vec2D: ... def xcor() -> float: ... def ycor() -> float: ... + @overload -def goto(x: tuple[float, float], y: None = ...) -> None: ... +def goto(x: tuple[float, float], y: None = None) -> None: ... @overload def goto(x: float, y: float) -> None: ... + def home() -> None: ... def setx(x: float) -> None: ... def sety(y: float) -> None: ... + @overload -def distance(x: TNavigator | tuple[float, float], y: None = ...) -> float: ... +def distance(x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def distance(x: float, y: float) -> float: ... + @overload -def towards(x: TNavigator | tuple[float, float], y: None = ...) -> float: ... +def towards(x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def towards(x: float, y: float) -> float: ... + def heading() -> float: ... def setheading(to_angle: float) -> None: ... -def circle(radius: float, extent: float | None = ..., steps: int | None = ...) -> None: ... +def circle(radius: float, extent: float | None = None, steps: int | None = None) -> None: ... fd = forward bk = back @@ -413,32 +688,38 @@ seth = setheading # Functions copied from TPen: @overload -def resizemode(rmode: None = ...) -> str: ... +def resizemode(rmode: None = None) -> str: ... @overload -def resizemode(rmode: str) -> None: ... +def resizemode(rmode: Literal["auto", "user", "noresize"]) -> None: ... + @overload -def pensize(width: None = ...) -> int: ... +def pensize(width: None = None) -> int: ... @overload def pensize(width: int) -> None: ... + def penup() -> None: ... def pendown() -> None: ... def isdown() -> bool: ... + @overload -def speed(speed: None = ...) -> int: ... +def speed(speed: None = None) -> int: ... @overload def speed(speed: _Speed) -> None: ... + @overload def pencolor() -> _AnyColor: ... @overload def pencolor(color: _Color) -> None: ... @overload def pencolor(r: float, g: float, b: float) -> None: ... + @overload def fillcolor() -> _AnyColor: ... @overload def fillcolor(color: _Color) -> None: ... @overload def fillcolor(r: float, g: float, b: float) -> None: ... + @overload def color() -> tuple[_AnyColor, _AnyColor]: ... @overload @@ -447,16 +728,17 @@ def color(color: _Color) -> None: ... def color(r: float, g: float, b: float) -> None: ... @overload def color(color1: _Color, color2: _Color) -> None: ... + def showturtle() -> None: ... def hideturtle() -> None: ... def isvisible() -> bool: ... # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload -def pen() -> _PenState: ... # type: ignore[misc] +def pen() -> _PenState: ... @overload def pen( - pen: _PenState | None = ..., + pen: _PenState | None = None, *, shown: bool = ..., pendown: bool = ..., @@ -464,7 +746,7 @@ def pen( fillcolor: _Color = ..., pensize: int = ..., speed: int = ..., - resizemode: str = ..., + resizemode: Literal["auto", "user", "noresize"] = ..., stretchfactor: tuple[float, float] = ..., outline: int = ..., tilt: float = ..., @@ -482,47 +764,75 @@ ht = hideturtle def setundobuffer(size: int | None) -> None: ... def undobufferentries() -> int: ... + @overload -def shape(name: None = ...) -> str: ... +def shape(name: None = None) -> str: ... @overload def shape(name: str) -> None: ... +if sys.version_info >= (3, 12): + def teleport(x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + # Unsafely overlaps when no arguments are provided @overload -def shapesize() -> tuple[float, float, float]: ... # type: ignore[misc] +def shapesize() -> tuple[float, float, float]: ... @overload -def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ... +def shapesize(stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None) -> None: ... + @overload -def shearfactor(shear: None = ...) -> float: ... +def shearfactor(shear: None = None) -> float: ... @overload def shearfactor(shear: float) -> None: ... # Unsafely overlaps when no arguments are provided @overload -def shapetransform() -> tuple[float, float, float, float]: ... # type: ignore[misc] +def shapetransform() -> tuple[float, float, float, float]: ... @overload def shapetransform( - t11: float | None = ..., t12: float | None = ..., t21: float | None = ..., t22: float | None = ... + t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None ) -> None: ... + def get_shapepoly() -> _PolygonCoords | None: ... -def settiltangle(angle: float) -> None: ... + +if sys.version_info < (3, 13): + @deprecated("Deprecated since Python 3.1; removed in Python 3.13. Use `tiltangle()` instead.") + def settiltangle(angle: float) -> None: ... + @overload -def tiltangle(angle: None = ...) -> float: ... +def tiltangle(angle: None = None) -> float: ... @overload def tiltangle(angle: float) -> None: ... + def tilt(angle: float) -> None: ... # Can return either 'int' or Tuple[int, ...] based on if the stamp is # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp() -> Any: ... -def clearstamp(stampid: int | Tuple[int, ...]) -> None: ... -def clearstamps(n: int | None = ...) -> None: ... +def clearstamp(stampid: int | tuple[int, ...]) -> None: ... +def clearstamps(n: int | None = None) -> None: ... def filling() -> bool: ... + +if sys.version_info >= (3, 14): + @contextmanager + def fill() -> Generator[None]: ... + def begin_fill() -> None: ... def end_fill() -> None: ... -def dot(size: int | None = ..., *color: _Color) -> None: ... -def write(arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...) -> None: ... + +@overload +def dot(size: int | _Color | None = None) -> None: ... +@overload +def dot(size: int | None, color: _Color, /) -> None: ... +@overload +def dot(size: int | None, r: float, g: float, b: float, /) -> None: ... + +def write(arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal")) -> None: ... + +if sys.version_info >= (3, 14): + @contextmanager + def poly() -> Generator[None]: ... + def begin_poly() -> None: ... def end_poly() -> None: ... def get_poly() -> _PolygonCoords | None: ... @@ -531,8 +841,8 @@ def getturtle() -> Turtle: ... getpen = getturtle -def onrelease(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... -def ondrag(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... +def onrelease(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... +def ondrag(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... def undo() -> None: ... turtlesize = shapesize diff --git a/stdlib/types.pyi b/stdlib/types.pyi index b018d56acd6a..39aaa7e9685f 100644 --- a/stdlib/types.pyi +++ b/stdlib/types.pyi @@ -1,93 +1,183 @@ import sys -from _typeshed import SupportsKeysAndGetItem -from importlib.abc import _LoaderProtocol -from importlib.machinery import ModuleSpec -from typing import ( - Any, +from _typeshed import AnnotationForm, MaybeNone, SupportsKeysAndGetItem +from _typeshed.importlib import LoaderProtocol +from collections.abc import ( AsyncGenerator, Awaitable, Callable, Coroutine, Generator, - Generic, ItemsView, Iterable, Iterator, KeysView, Mapping, + MutableMapping, MutableSequence, - Tuple, - Type, - TypeVar, ValuesView, - overload, ) -from typing_extensions import Literal, ParamSpec, final +from importlib.machinery import ModuleSpec +from typing import Any, ClassVar, Literal, ParamSpec, TypeVar, final, overload +from typing_extensions import Self, TypeAliasType, TypeVarTuple, deprecated, disjoint_base + +if sys.version_info >= (3, 14): + from _typeshed import AnnotateFunc + +__all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + "BuiltinMethodType", + "ClassMethodDescriptorType", + "MethodDescriptorType", + "MethodWrapperType", + "WrapperDescriptorType", + "resolve_bases", + "CellType", + "GenericAlias", + "EllipsisType", + "NoneType", + "NotImplementedType", + "UnionType", +] + +if sys.version_info >= (3, 12): + __all__ += ["get_original_bases"] + +if sys.version_info >= (3, 13): + __all__ += ["CapsuleType"] + +if sys.version_info >= (3, 15): + __all__ += ["FrameLocalsProxyType", "LazyImportType"] # Note, all classes "defined" here require special handling. -_T = TypeVar("_T") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") -_T_co = TypeVar("_T_co", covariant=True) -_T_contra = TypeVar("_T_contra", contravariant=True) -_KT = TypeVar("_KT") +_KT_co = TypeVar("_KT_co", covariant=True) _VT_co = TypeVar("_VT_co", covariant=True) -_V_co = TypeVar("_V_co", covariant=True) - -@final -class _Cell: - __hash__: None # type: ignore[assignment] - cell_contents: Any +# Make sure this class definition stays roughly in line with `builtins.function` @final class FunctionType: - __closure__: Tuple[_Cell, ...] | None + @property + def __closure__(self) -> tuple[CellType, ...] | None: ... __code__: CodeType - __defaults__: Tuple[Any, ...] | None + __defaults__: tuple[Any, ...] | None __dict__: dict[str, Any] - __globals__: dict[str, Any] + @property + def __globals__(self) -> dict[str, Any]: ... __name__: str __qualname__: str - __annotations__: dict[str, Any] - __kwdefaults__: dict[str, Any] - def __init__( - self, - code: CodeType, - globals: dict[str, Any], - name: str | None = ..., - argdefs: Tuple[object, ...] | None = ..., - closure: Tuple[_Cell, ...] | None = ..., - ) -> None: ... + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + __kwdefaults__: dict[str, Any] | None + @property + def __builtins__(self) -> dict[str, Any]: ... + if sys.version_info >= (3, 12): + __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] + + __module__: str + if sys.version_info >= (3, 13): + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + kwdefaults: dict[str, object] | None = None, + ) -> Self: ... + else: + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + ) -> Self: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: object | None, type: type | None) -> MethodType: ... + + @overload + def __get__(self, instance: None, owner: type, /) -> FunctionType: ... + @overload + def __get__(self, instance: object, owner: type | None = None, /) -> MethodType: ... LambdaType = FunctionType @final class CodeType: - """Create a code object. Not for the faint of heart.""" - - co_argcount: int - if sys.version_info >= (3, 8): - co_posonlyargcount: int - co_kwonlyargcount: int - co_nlocals: int - co_stacksize: int - co_flags: int - co_code: bytes - co_consts: Tuple[Any, ...] - co_names: Tuple[str, ...] - co_varnames: Tuple[str, ...] - co_filename: str - co_name: str - co_firstlineno: int - co_lnotab: bytes - co_freevars: Tuple[str, ...] - co_cellvars: Tuple[str, ...] - if sys.version_info >= (3, 8): - def __init__( - self, + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + @property + def co_argcount(self) -> int: ... + @property + def co_posonlyargcount(self) -> int: ... + @property + def co_kwonlyargcount(self) -> int: ... + @property + def co_nlocals(self) -> int: ... + @property + def co_stacksize(self) -> int: ... + @property + def co_flags(self) -> int: ... + @property + def co_code(self) -> bytes: ... + @property + def co_consts(self) -> tuple[Any, ...]: ... + @property + def co_names(self) -> tuple[str, ...]: ... + @property + def co_varnames(self) -> tuple[str, ...]: ... + @property + def co_filename(self) -> str: ... + @property + def co_name(self) -> str: ... + @property + def co_firstlineno(self) -> int: ... + if sys.version_info < (3, 15): + @property + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `CodeType.co_lines()` instead.") + def co_lnotab(self) -> bytes: ... + + @property + def co_freevars(self) -> tuple[str, ...]: ... + @property + def co_cellvars(self) -> tuple[str, ...]: ... + @property + def co_linetable(self) -> bytes: ... + def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... + if sys.version_info >= (3, 11): + @property + def co_exceptiontable(self) -> bytes: ... + @property + def co_qualname(self) -> str: ... + def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ... + if sys.version_info >= (3, 14): + def co_branches(self) -> Iterator[tuple[int, int, int]]: ... + + if sys.version_info >= (3, 11): + def __new__( + cls, argcount: int, posonlyargcount: int, kwonlyargcount: int, @@ -95,114 +185,161 @@ class CodeType: stacksize: int, flags: int, codestring: bytes, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], filename: str, name: str, + qualname: str, firstlineno: int, - lnotab: bytes, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., - ) -> None: ... + linetable: bytes, + exceptiontable: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, + ) -> Self: ... else: - def __init__( - self, + def __new__( + cls, argcount: int, + posonlyargcount: int, kwonlyargcount: int, nlocals: int, stacksize: int, flags: int, codestring: bytes, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], filename: str, name: str, firstlineno: int, - lnotab: bytes, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., - ) -> None: ... - if sys.version_info >= (3, 10): + linetable: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, + ) -> Self: ... + if sys.version_info >= (3, 11): def replace( self, *, - co_argcount: int = ..., - co_posonlyargcount: int = ..., - co_kwonlyargcount: int = ..., - co_nlocals: int = ..., - co_stacksize: int = ..., - co_flags: int = ..., - co_firstlineno: int = ..., + co_argcount: int = -1, + co_posonlyargcount: int = -1, + co_kwonlyargcount: int = -1, + co_nlocals: int = -1, + co_stacksize: int = -1, + co_flags: int = -1, + co_firstlineno: int = -1, co_code: bytes = ..., - co_consts: Tuple[Any, ...] = ..., - co_names: Tuple[str, ...] = ..., - co_varnames: Tuple[str, ...] = ..., - co_freevars: Tuple[str, ...] = ..., - co_cellvars: Tuple[str, ...] = ..., + co_consts: tuple[object, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., co_filename: str = ..., co_name: str = ..., - co_linetable: object = ..., - ) -> CodeType: ... - def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... - co_linetable: object - elif sys.version_info >= (3, 8): + co_qualname: str = ..., + co_linetable: bytes = ..., + co_exceptiontable: bytes = ..., + ) -> Self: ... + else: def replace( self, *, - co_argcount: int = ..., - co_posonlyargcount: int = ..., - co_kwonlyargcount: int = ..., - co_nlocals: int = ..., - co_stacksize: int = ..., - co_flags: int = ..., - co_firstlineno: int = ..., + co_argcount: int = -1, + co_posonlyargcount: int = -1, + co_kwonlyargcount: int = -1, + co_nlocals: int = -1, + co_stacksize: int = -1, + co_flags: int = -1, + co_firstlineno: int = -1, co_code: bytes = ..., - co_consts: Tuple[Any, ...] = ..., - co_names: Tuple[str, ...] = ..., - co_varnames: Tuple[str, ...] = ..., - co_freevars: Tuple[str, ...] = ..., - co_cellvars: Tuple[str, ...] = ..., + co_consts: tuple[object, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., co_filename: str = ..., co_name: str = ..., - co_lnotab: bytes = ..., - ) -> CodeType: ... - if sys.version_info >= (3, 11): - def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ... + co_linetable: bytes = ..., + ) -> Self: ... + + if sys.version_info >= (3, 13): + __replace__ = replace @final -class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): - __hash__: None # type: ignore[assignment] - def __init__(self, mapping: SupportsKeysAndGetItem[_KT, _VT_co]) -> None: ... - def __getitem__(self, k: _KT) -> _VT_co: ... - def __iter__(self) -> Iterator[_KT]: ... +class MappingProxyType(Mapping[_KT_co, _VT_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-generic-class] # pyrefly: ignore [invalid-variance] + __hash__: ClassVar[None] # type: ignore[assignment] + def __new__(cls, mapping: SupportsKeysAndGetItem[_KT_co, _VT_co]) -> Self: ... + def __getitem__(self, key: _KT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-variance] + def __iter__(self) -> Iterator[_KT_co]: ... def __len__(self) -> int: ... - def copy(self) -> dict[_KT, _VT_co]: ... - def keys(self) -> KeysView[_KT]: ... + def __eq__(self, value: object, /) -> bool: ... + def copy(self) -> dict[_KT_co, _VT_co]: ... + def keys(self) -> KeysView[_KT_co]: ... def values(self) -> ValuesView[_VT_co]: ... - def items(self) -> ItemsView[_KT, _VT_co]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - def __reversed__(self) -> Iterator[_KT]: ... - def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT_co | _T2]: ... - def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT_co | _T2]: ... - -class SimpleNamespace: - __hash__: None # type: ignore[assignment] - def __init__(self, **kwargs: Any) -> None: ... - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... + def items(self) -> ItemsView[_KT_co, _VT_co]: ... + + @overload + def get(self, key: _KT_co, /) -> _VT_co | None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + @overload + def get(self, key: _KT_co, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + @overload + def get(self, key: _KT_co, default: _T2, /) -> _VT_co | _T2: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __reversed__(self) -> Iterator[_KT_co]: ... + def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ... + def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ... + +if sys.version_info >= (3, 12): + @disjoint_base + class SimpleNamespace: + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 13): + def __init__( + self, mapping_or_iterable: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), /, **kwargs: Any + ) -> None: ... + else: + def __init__(self, **kwargs: Any) -> None: ... + + def __eq__(self, value: object, /) -> bool: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> Self: ... +else: + class SimpleNamespace: + __hash__: ClassVar[None] # type: ignore[assignment] + def __init__(self, **kwargs: Any) -> None: ... + def __eq__(self, value: object, /) -> bool: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + +@disjoint_base class ModuleType: __name__: str __file__: str | None - __dict__: dict[str, Any] - __loader__: _LoaderProtocol | None + @property + def __dict__(self) -> dict[str, Any]: ... # type: ignore[override] + __loader__: LoaderProtocol | None __package__: str | None __path__: MutableSequence[str] __spec__: ModuleSpec | None + # N.B. Although this is the same type as `builtins.object.__doc__`, + # it is deliberately redeclared here. Most symbols declared in the namespace + # of `types.ModuleType` are available as "implicit globals" within a module's + # namespace, but this is not true for symbols declared in the namespace of `builtins.object`. + # Redeclaring `__doc__` here helps some type checkers understand that `__doc__` is available + # as an implicit global in all modules, similar to `__name__`, `__file__`, `__spec__`, etc. + __doc__: str | None + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + def __init__(self, name: str, doc: str | None = ...) -> None: ... # __getattr__ doesn't exist at runtime, # but having it here in typeshed makes dynamic imports @@ -210,136 +347,211 @@ class ModuleType: def __getattr__(self, name: str) -> Any: ... @final -class GeneratorType(Generator[_T_co, _T_contra, _V_co]): - gi_code: CodeType - gi_frame: FrameType - gi_running: bool - gi_yieldfrom: GeneratorType[_T_co, _T_contra, Any] | None - def __iter__(self) -> GeneratorType[_T_co, _T_contra, _V_co]: ... - def __next__(self) -> _T_co: ... - def close(self) -> None: ... - def send(self, __arg: _T_contra) -> _T_co: ... +class CellType: + def __new__(cls, contents: object = ..., /) -> Self: ... + __hash__: ClassVar[None] # type: ignore[assignment] + cell_contents: Any + +_YieldT_co = TypeVar("_YieldT_co", covariant=True) +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None) +_ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) + +@final +class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]): + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType | None: ... + @property + def gi_running(self) -> bool: ... + @property + def gi_yieldfrom(self) -> Iterator[_YieldT_co] | None: ... + if sys.version_info >= (3, 11): + @property + def gi_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def gi_state(self) -> Literal["GEN_CREATED", "GEN_SUSPENDED", "GEN_RUNNING", "GEN_CLOSED"]: ... + __name__: str + __qualname__: str + def __iter__(self) -> Self: ... + def __next__(self) -> _YieldT_co: ... + def send(self, arg: _SendT_contra, /) -> _YieldT_co: ... + @overload def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> _T_co: ... + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / + ) -> _YieldT_co: ... @overload - def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + + if sys.version_info >= (3, 13): + def __class_getitem__(cls, item: Any, /) -> Any: ... @final -class AsyncGeneratorType(AsyncGenerator[_T_co, _T_contra]): - ag_await: Awaitable[Any] | None - ag_frame: FrameType - ag_running: bool - ag_code: CodeType - def __aiter__(self) -> AsyncGeneratorType[_T_co, _T_contra]: ... - def __anext__(self) -> Awaitable[_T_co]: ... - def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... +class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): + @property + def ag_await(self) -> Awaitable[Any] | None: ... + @property + def ag_code(self) -> CodeType: ... + @property + def ag_frame(self) -> FrameType | None: ... + @property + def ag_running(self) -> bool: ... + __name__: str + __qualname__: str + if sys.version_info >= (3, 12): + @property + def ag_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def ag_state(self) -> Literal["AGEN_CREATED", "AGEN_SUSPENDED", "AGEN_RUNNING", "AGEN_CLOSED"]: ... + + def __aiter__(self) -> Self: ... + def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... + def asend(self, val: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... + @overload - def athrow( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> Awaitable[_T_co]: ... + async def athrow( + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / + ) -> _YieldT_co: ... @overload - def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Awaitable[_T_co]: ... - def aclose(self) -> Awaitable[None]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, __item: Any) -> GenericAlias: ... + async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + + def aclose(self) -> Coroutine[Any, Any, None]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# Non-default variations to accommodate coroutines +_SendT_nd_contra = TypeVar("_SendT_nd_contra", contravariant=True) +_ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True) @final -class CoroutineType(Coroutine[_T_co, _T_contra, _V_co]): +class CoroutineType(Coroutine[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]): __name__: str __qualname__: str - cr_await: Any | None - cr_code: CodeType - cr_frame: FrameType - cr_running: bool + @property + def cr_await(self) -> Any | None: ... + @property + def cr_code(self) -> CodeType: ... + @property + def cr_frame(self) -> FrameType | None: ... + @property + def cr_running(self) -> bool: ... + @property + def cr_origin(self) -> tuple[tuple[str, int, str], ...] | None: ... + if sys.version_info >= (3, 11): + @property + def cr_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def cr_state(self) -> Literal["CORO_CREATED", "CORO_SUSPENDED", "CORO_RUNNING", "CORO_CLOSED"]: ... + def close(self) -> None: ... - def __await__(self) -> Generator[Any, None, _V_co]: ... - def send(self, __arg: _T_contra) -> _T_co: ... + def __await__(self) -> Generator[Any, None, _ReturnT_nd_co]: ... + def send(self, arg: _SendT_nd_contra, /) -> _YieldT_co: ... + @overload def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> _T_co: ... + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / + ) -> _YieldT_co: ... @overload - def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... -class _StaticFunctionType: - """Fictional type to correct the type of MethodType.__func__. - - FunctionType is a descriptor, so mypy follows the descriptor protocol and - converts MethodType.__func__ back to MethodType (the return type of - FunctionType.__get__). But this is actually a special case; MethodType is - implemented in C and its attribute access doesn't go through - __getattribute__. - - By wrapping FunctionType in _StaticFunctionType, we get the right result; - similar to wrapping a function in staticmethod() at runtime to prevent it - being bound as a method. - """ - - def __get__(self, obj: object | None, type: type | None) -> FunctionType: ... + if sys.version_info >= (3, 13): + def __class_getitem__(cls, item: Any, /) -> Any: ... @final class MethodType: - __closure__: Tuple[_Cell, ...] | None # inherited from the added function - __defaults__: Tuple[Any, ...] | None # inherited from the added function - __func__: _StaticFunctionType - __self__: object - __name__: str # inherited from the added function - __qualname__: str # inherited from the added function - def __init__(self, func: Callable[..., Any], obj: object) -> None: ... + @property + def __closure__(self) -> tuple[CellType, ...] | None: ... # inherited from the added function + @property + def __code__(self) -> CodeType: ... # inherited from the added function + @property + def __defaults__(self) -> tuple[Any, ...] | None: ... # inherited from the added function + @property + def __func__(self) -> Callable[..., Any]: ... + @property + def __self__(self) -> object: ... + @property + def __name__(self) -> str: ... # inherited from the added function + @property + def __qualname__(self) -> str: ... # inherited from the added function + def __new__(cls, func: Callable[..., Any], instance: object, /) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + if sys.version_info >= (3, 13): + def __get__(self, instance: object, owner: type | None = None, /) -> Self: ... + + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + @final class BuiltinFunctionType: - __self__: object | ModuleType - __name__: str - __qualname__: str + @property + def __self__(self) -> object | ModuleType: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... BuiltinMethodType = BuiltinFunctionType -if sys.version_info >= (3, 7): - @final - class WrapperDescriptorType: - __name__: str - __qualname__: str - __objclass__: type - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: Any, type: type = ...) -> Any: ... - @final - class MethodWrapperType: - __self__: object - __name__: str - __qualname__: str - __objclass__: type - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - @final - class MethodDescriptorType: - __name__: str - __qualname__: str - __objclass__: type - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: Any, type: type = ...) -> Any: ... - @final - class ClassMethodDescriptorType: - __name__: str - __qualname__: str - __objclass__: type - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: Any, type: type = ...) -> Any: ... +@final +class WrapperDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + +@final +class MethodWrapperType: + @property + def __self__(self) -> object: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + +@final +class MethodDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + +@final +class ClassMethodDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... @final class TracebackType: - if sys.version_info >= (3, 7): - def __init__(self, tb_next: TracebackType | None, tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ... - tb_next: TracebackType | None - else: - @property - def tb_next(self) -> TracebackType | None: ... - # the rest are read-only even in 3.7 + def __new__(cls, tb_next: TracebackType | None, tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> Self: ... + tb_next: TracebackType | None + # the rest are read-only @property def tb_frame(self) -> FrameType: ... @property @@ -349,58 +561,120 @@ class TracebackType: @final class FrameType: - f_back: FrameType | None - f_builtins: dict[str, Any] - f_code: CodeType - f_globals: dict[str, Any] - f_lasti: int - f_lineno: int - f_locals: dict[str, Any] + @property + def f_back(self) -> FrameType | None: ... + @property + def f_builtins(self) -> dict[str, Any]: ... + @property + def f_code(self) -> CodeType: ... + @property + def f_globals(self) -> dict[str, Any]: ... + @property + def f_lasti(self) -> int: ... + # see discussion in #6769: f_lineno *can* sometimes be None, + # but you should probably file a bug report with CPython if you encounter it being None in the wild. + # An `int | None` annotation here causes too many false-positive errors, so applying `int | Any`. + @property + def f_lineno(self) -> int | MaybeNone: ... + + if sys.version_info >= (3, 15): + @property + def f_locals(self) -> FrameLocalsProxyType | dict[str, Any]: ... + else: + @property + def f_locals(self) -> dict[str, Any]: ... + f_trace: Callable[[FrameType, str, Any], Any] | None - if sys.version_info >= (3, 7): - f_trace_lines: bool - f_trace_opcodes: bool + f_trace_lines: bool + f_trace_opcodes: bool def clear(self) -> None: ... + if sys.version_info >= (3, 14): + @property + def f_generator(self) -> GeneratorType[Any, Any, Any] | CoroutineType[Any, Any, Any] | None: ... + +if sys.version_info >= (3, 15): + @final + class FrameLocalsProxyType(MutableMapping[str, Any]): + def __new__(cls, frame: FrameType, /) -> Self: ... + def __getitem__(self, key: str, /) -> Any: ... + def __setitem__(self, key: str, value: Any, /) -> None: ... + def __delitem__(self, key: str, /) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: object, /) -> bool: ... + def __reversed__(self) -> Iterator[str]: ... + def __or__(self, other: dict[str, Any] | FrameLocalsProxyType, /) -> dict[str, Any]: ... + # Will raise a NameError if invoked via |= + def __ior__(self, other: dict[str, Any] | FrameLocalsProxyType, /) -> dict[str, Any]: ... # noqa: Y034 + def __ror__(self, other: dict[str, Any] | FrameLocalsProxyType, /) -> dict[str, Any]: ... + def copy(self) -> dict[str, Any]: ... + def pop(self, key: str, default: Any = ..., /) -> Any: ... + def setdefault(self, key: str, default: Any = ..., /) -> Any: ... + def update(self, object: SupportsKeysAndGetItem[str, Any] | Iterable[tuple[str, Any]], /) -> None: ... # type: ignore[override] + + @final + class LazyImportType: + def resolve(self) -> Any: ... @final class GetSetDescriptorType: - __name__: str - __objclass__: type - def __get__(self, __obj: Any, __type: type = ...) -> Any: ... - def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... @final class MemberDescriptorType: - __name__: str - __objclass__: type - def __get__(self, __obj: Any, __type: type = ...) -> Any: ... - def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... - -if sys.version_info >= (3, 7): - def new_class( - name: str, - bases: Iterable[object] = ..., - kwds: dict[str, Any] | None = ..., - exec_body: Callable[[dict[str, Any]], None] | None = ..., - ) -> type: ... - def resolve_bases(bases: Iterable[object]) -> Tuple[Any, ...]: ... - -else: - def new_class( - name: str, - bases: Tuple[type, ...] = ..., - kwds: dict[str, Any] | None = ..., - exec_body: Callable[[dict[str, Any]], None] | None = ..., - ) -> type: ... - + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... + +def new_class( + name: str, + bases: Iterable[object] = (), + kwds: dict[str, Any] | None = None, + exec_body: Callable[[dict[str, Any]], object] | None = None, +) -> type: ... +def resolve_bases(bases: Iterable[object]) -> tuple[Any, ...]: ... def prepare_class( - name: str, bases: Tuple[type, ...] = ..., kwds: dict[str, Any] | None = ... + name: str, bases: tuple[type, ...] = (), kwds: dict[str, Any] | None = None ) -> tuple[type, dict[str, Any], dict[str, Any]]: ... -# Actually a different type, but `property` is special and we want that too. -DynamicClassAttribute = property +if sys.version_info >= (3, 12): + def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... + +# Does not actually inherit from property, but saying it does makes sure that +# pyright handles this class correctly. +class DynamicClassAttribute(property): + fget: Callable[[Any], Any] | None + fset: Callable[[Any, Any], object] | None # type: ignore[assignment] + fdel: Callable[[Any], object] | None # type: ignore[assignment] + overwrite_doc: bool + __isabstractmethod__: bool + def __init__( + self, + fget: Callable[[Any], Any] | None = None, + fset: Callable[[Any, Any], object] | None = None, + fdel: Callable[[Any], object] | None = None, + doc: str | None = None, + ) -> None: ... + def __get__(self, instance: Any, ownerclass: type | None = None) -> Any: ... + def __set__(self, instance: Any, value: Any) -> None: ... + def __delete__(self, instance: Any) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> DynamicClassAttribute: ... + def setter(self, fset: Callable[[Any, Any], object]) -> DynamicClassAttribute: ... + def deleter(self, fdel: Callable[[Any], object]) -> DynamicClassAttribute: ... _Fn = TypeVar("_Fn", bound=Callable[..., object]) _R = TypeVar("_R") @@ -408,31 +682,67 @@ _P = ParamSpec("_P") # it's not really an Awaitable, but can be used in an await expression. Real type: Generator & Awaitable @overload -def coroutine(func: Callable[_P, Generator[_R, Any, Any]]) -> Callable[_P, Awaitable[_R]]: ... # type: ignore[misc] +def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Awaitable[_R]]: ... @overload -def coroutine(func: _Fn) -> _Fn: ... # type: ignore[misc] +def coroutine(func: _Fn) -> _Fn: ... -if sys.version_info >= (3, 8): - CellType = _Cell +@disjoint_base +class GenericAlias: + @property + def __origin__(self) -> type | TypeAliasType: ... + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... + def __new__(cls, origin: type, args: Any, /) -> Self: ... + def __getitem__(self, typeargs: Any, /) -> GenericAlias: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __mro_entries__(self, bases: Iterable[object], /) -> tuple[type, ...]: ... + if sys.version_info >= (3, 11): + @property + def __unpacked__(self) -> bool: ... + @property + def __typing_unpacked_tuple_args__(self) -> tuple[Any, ...] | None: ... -if sys.version_info >= (3, 9): - class GenericAlias: - __origin__: type - __args__: Tuple[Any, ...] - __parameters__: Tuple[Any, ...] - def __init__(self, origin: type, args: Any) -> None: ... - def __getattr__(self, name: str) -> Any: ... # incomplete + # `other` can be any legal form for unions. + # `list[int] | list[int]` creates a `GenericAlias` instance, not a `UnionType` instance + def __or__(self, value: Any, /) -> UnionType | GenericAlias: ... + def __ror__(self, value: Any, /) -> UnionType | GenericAlias: ... -if sys.version_info >= (3, 10): - @final - class NoneType: - def __bool__(self) -> Literal[False]: ... - EllipsisType = ellipsis # noqa F811 from builtins - from builtins import _NotImplementedType + # GenericAlias delegates attr access to `__origin__` + def __getattr__(self, name: str) -> Any: ... + +@final +class NoneType: + def __bool__(self) -> Literal[False]: ... + +@final +class EllipsisType: ... - NotImplementedType = _NotImplementedType # noqa F811 from builtins +@final +class NotImplementedType(Any): ... + +@final +class UnionType: + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... + # `(int | str) | Literal["foo"]` returns a generic alias to an instance of `_SpecialForm` (`Union`). + # Normally we'd express this using the return type of `_SpecialForm.__ror__`, + # but because `UnionType.__or__` accepts `Any`, type checkers will use + # the return type of `UnionType.__or__` to infer the result of this operation + # rather than `_SpecialForm.__ror__`. To mitigate this, we use `| Any` + # in the return type of `UnionType.__(r)or__`. + def __or__(self, value: Any, /) -> UnionType | Any: ... + def __ror__(self, value: Any, /) -> UnionType | Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + # you can only subscript a `UnionType` instance if at least one of the elements + # in the union is a generic alias instance that has a non-empty `__parameters__` + def __getitem__(self, parameters: Any, /) -> object: ... + +if sys.version_info >= (3, 13): @final - class UnionType: - __args__: Tuple[Any, ...] - def __or__(self, obj: Any) -> UnionType: ... - def __ror__(self, obj: Any) -> UnionType: ... + class CapsuleType: ... diff --git a/stdlib/typing.pyi b/stdlib/typing.pyi index c3a7043f9c26..198dd45feedf 100644 --- a/stdlib/typing.pyi +++ b/stdlib/typing.pyi @@ -1,121 +1,439 @@ -import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +# Since this module defines "overload" it is not recognized by Ruff as typing.overload +# TODO: The collections import is required, otherwise mypy crashes. +# https://github.com/python/mypy/issues/16744 +import collections # ruff: ignore[unused-import] # pyright: ignore[reportUnusedImport] import sys -from _typeshed import SupportsKeysAndGetItem +import typing_extensions +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import IdentityFunction, ReadableBuffer, SupportsGetItem, SupportsGetItemViewable, SupportsKeysAndGetItem, Viewable from abc import ABCMeta, abstractmethod -from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final +from re import Match as Match, Pattern as Pattern +from types import ( + BuiltinFunctionType, + CodeType, + FunctionType, + GenericAlias, + MethodDescriptorType, + MethodType, + MethodWrapperType, + ModuleType, + TracebackType, + UnionType, + WrapperDescriptorType, +) +from typing_extensions import Never as _Never, deprecated + +if sys.version_info >= (3, 14): + from _typeshed import EvaluateFunc + + from annotationlib import Format + +__all__ = [ + "AbstractSet", + "Annotated", + "Any", + "AnyStr", + "AsyncContextManager", + "AsyncGenerator", + "AsyncIterable", + "AsyncIterator", + "Awaitable", + "BinaryIO", + "Callable", + "ChainMap", + "ClassVar", + "Collection", + "Concatenate", + "Container", + "ContextManager", + "Coroutine", + "Counter", + "DefaultDict", + "Deque", + "Dict", + "Final", + "ForwardRef", + "FrozenSet", + "Generator", + "Generic", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Literal", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "NamedTuple", + "NewType", + "NoReturn", + "Optional", + "OrderedDict", + "ParamSpec", + "ParamSpecArgs", + "ParamSpecKwargs", + "Pattern", + "Protocol", + "Reversible", + "Sequence", + "Set", + "Sized", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "Text", + "TextIO", + "Tuple", + "Type", + "TypeAlias", + "TypeGuard", + "TypeVar", + "TypedDict", + "Union", + "ValuesView", + "TYPE_CHECKING", + "cast", + "final", + "get_args", + "get_origin", + "get_type_hints", + "is_typeddict", + "no_type_check", + "overload", + "runtime_checkable", +] + +if sys.version_info < (3, 15): + __all__ += ["ByteString", "no_type_check_decorator"] + +if sys.version_info >= (3, 14): + __all__ += ["evaluate_forward_ref"] + +if sys.version_info >= (3, 15): + __all__ += ["NoExtraItems", "TypeForm", "disjoint_base"] + +if sys.version_info >= (3, 11): + __all__ += [ + "LiteralString", + "Never", + "NotRequired", + "Required", + "Self", + "TypeVarTuple", + "Unpack", + "assert_never", + "assert_type", + "clear_overloads", + "dataclass_transform", + "get_overloads", + "reveal_type", + ] -if sys.version_info >= (3, 7): - from types import MethodDescriptorType, MethodWrapperType, WrapperDescriptorType +if sys.version_info >= (3, 12): + __all__ += ["TypeAliasType", "override"] -if sys.version_info >= (3, 9): - from types import GenericAlias +if sys.version_info >= (3, 13): + __all__ += ["get_protocol_members", "is_protocol", "NoDefault", "TypeIs", "ReadOnly"] -Any = object() +# We can't use this name here because it leads to issues with mypy, likely +# due to an import cycle. Below instead we use Any with a comment. +# from _typeshed import AnnotationForm -class TypeVar: - __name__: str - __bound__: Type[Any] | None - __constraints__: Tuple[Type[Any], ...] - __covariant__: bool - __contravariant__: bool - def __init__( - self, - name: str, - *constraints: Type[Any], - bound: None | Type[Any] | str = ..., - covariant: bool = ..., - contravariant: bool = ..., - ) -> None: ... - if sys.version_info >= (3, 10): - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... +class Any: ... -# Used for an undocumented mypy feature. Does not exist at runtime. -_promote = object() +class _Final: + __slots__ = ("__weakref__",) -class _SpecialForm: - def __getitem__(self, typeargs: Any) -> object: ... - if sys.version_info >= (3, 10): - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... +def final(f: _T) -> _T: ... -_F = TypeVar("_F", bound=Callable[..., Any]) -_P = _ParamSpec("_P") -_T = TypeVar("_T") +@final +class TypeVar: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __constraints__(self) -> tuple[Any, ...]: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + if sys.version_info >= (3, 12): + @property + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def __default__(self) -> Any: ... # AnnotationForm + if sys.version_info >= (3, 13): + def __new__( + cls, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + default: Any = ..., # AnnotationForm + ) -> Self: ... + elif sys.version_info >= (3, 12): + def __new__( + cls, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 11): + def __new__( + cls, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + ) -> Self: ... + else: + def __init__( + self, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + ) -> None: ... -def overload(func: _F) -> _F: ... + def __or__(self, right: Any, /) -> _SpecialForm: ... # AnnotationForm + def __ror__(self, left: Any, /) -> _SpecialForm: ... # AnnotationForm + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any, /) -> Any: ... + if sys.version_info >= (3, 13): + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + def has_default(self) -> bool: ... + if sys.version_info >= (3, 14): + @property + def evaluate_bound(self) -> EvaluateFunc | None: ... + @property + def evaluate_constraints(self) -> EvaluateFunc | None: ... + @property + def evaluate_default(self) -> EvaluateFunc | None: ... + +# N.B. Keep this definition in sync with typing_extensions._SpecialForm +@final +class _SpecialForm(_Final): + __slots__ = ("_name", "__doc__", "_getitem") + def __getitem__(self, parameters: Any) -> object: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + +Union: _SpecialForm +Callable: _SpecialForm +Type: _SpecialForm +NoReturn: _SpecialForm +ClassVar: _SpecialForm + +Optional: _SpecialForm +Tuple: _SpecialForm +Final: _SpecialForm + +Literal: _SpecialForm +TypedDict: _SpecialForm + +if sys.version_info >= (3, 11): + Self: _SpecialForm + Never: _SpecialForm + Unpack: _SpecialForm + Required: _SpecialForm + NotRequired: _SpecialForm + LiteralString: _SpecialForm + + @final + class TypeVarTuple: + @property + def __name__(self) -> str: ... + if sys.version_info >= (3, 15): + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def __default__(self) -> Any: ... # AnnotationForm + def has_default(self) -> bool: ... + if sys.version_info >= (3, 15): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + default: Any = ..., # AnnotationForm + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 13): + def __new__(cls, name: str, *, default: Any = ...) -> Self: ... # AnnotationForm + elif sys.version_info >= (3, 12): + def __new__(cls, name: str) -> Self: ... + else: + def __init__(self, name: str) -> None: ... + + def __iter__(self) -> Any: ... + def __typing_subst__(self, arg: Never, /) -> Never: ... + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + if sys.version_info >= (3, 14): + @property + def evaluate_default(self) -> EvaluateFunc | None: ... -Union: _SpecialForm = ... -Optional: _SpecialForm = ... -Tuple: _SpecialForm = ... -Generic: _SpecialForm = ... -# Protocol is only present in 3.8 and later, but mypy needs it unconditionally -Protocol: _SpecialForm = ... -Callable: _SpecialForm = ... -Type: _SpecialForm = ... -ClassVar: _SpecialForm = ... -NoReturn: _SpecialForm = ... -if sys.version_info >= (3, 8): - Final: _SpecialForm = ... - def final(f: _T) -> _T: ... - Literal: _SpecialForm = ... - # TypedDict is a (non-subscriptable) special form. - TypedDict: object - -if sys.version_info < (3, 7): - class GenericMeta(type): ... - -if sys.version_info >= (3, 10): - class ParamSpecArgs: - __origin__: ParamSpec +@final +class ParamSpecArgs: + @property + def __origin__(self) -> ParamSpec: ... + if sys.version_info >= (3, 12): + def __new__(cls, origin: ParamSpec) -> Self: ... + else: def __init__(self, origin: ParamSpec) -> None: ... - class ParamSpecKwargs: - __origin__: ParamSpec + + def __eq__(self, other: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +@final +class ParamSpecKwargs: + @property + def __origin__(self) -> ParamSpec: ... + if sys.version_info >= (3, 12): + def __new__(cls, origin: ParamSpec) -> Self: ... + else: def __init__(self, origin: ParamSpec) -> None: ... - class ParamSpec: - __name__: str - __bound__: Type[Any] | None - __covariant__: bool - __contravariant__: bool + + def __eq__(self, other: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +@final +class ParamSpec: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + if sys.version_info >= (3, 12): + @property + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def __default__(self) -> Any: ... # AnnotationForm + if sys.version_info >= (3, 13): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + default: Any = ..., # AnnotationForm + ) -> Self: ... + elif sys.version_info >= (3, 12): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 11): + def __new__( + cls, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False # AnnotationForm + ) -> Self: ... + else: def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... + self, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False # AnnotationForm ) -> None: ... + + @property + def args(self) -> ParamSpecArgs: ... + @property + def kwargs(self) -> ParamSpecKwargs: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any, /) -> Any: ... + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + if sys.version_info >= (3, 13): + def has_default(self) -> bool: ... + if sys.version_info >= (3, 14): @property - def args(self) -> ParamSpecArgs: ... - @property - def kwargs(self) -> ParamSpecKwargs: ... - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... - Concatenate: _SpecialForm = ... - TypeAlias: _SpecialForm = ... - TypeGuard: _SpecialForm = ... - class NewType: - def __init__(self, name: str, tp: type) -> None: ... + def evaluate_default(self) -> EvaluateFunc | None: ... + +Concatenate: _SpecialForm +TypeAlias: _SpecialForm +TypeGuard: _SpecialForm + +class NewType: + def __init__(self, name: str, tp: Any) -> None: ... # AnnotationForm + if sys.version_info >= (3, 11): + @staticmethod + def __call__(x: _T, /) -> _T: ... + else: def __call__(self, x: _T) -> _T: ... - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... - __supertype__: type -else: - def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + __supertype__: type | NewType + __name__: str + +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") +_T = TypeVar("_T") + +_FT = TypeVar("_FT", bound=Callable[..., Any] | type) # These type variables are used by the container types. _S = TypeVar("_S") _KT = TypeVar("_KT") # Key type. _VT = TypeVar("_VT") # Value type. _T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. -_V_co = TypeVar("_V_co", covariant=True) # Any type covariant containers. _KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. -_T_contra = TypeVar("_T_contra", contravariant=True) # Ditto contravariant. -_TC = TypeVar("_TC", bound=Type[object]) +_TC = TypeVar("_TC", bound=type[object]) +def overload(func: _F) -> _F: ... def no_type_check(arg: _F) -> _F: ... -def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... # type: ignore[misc] + +if sys.version_info < (3, 15): + @deprecated("Deprecated; removed in Python 3.15.") + def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... + +if sys.version_info >= (3, 15): + def disjoint_base(cls: _TC) -> _TC: ... + +# This itself is only available during type checking +def type_check_only(func_or_cls: _FT) -> _FT: ... # Type aliases and type constructors +@type_check_only class _Alias: # Class for defining generic aliases for library types. def __getitem__(self, typeargs: Any) -> Any: ... @@ -129,65 +447,89 @@ Counter = _Alias() Deque = _Alias() ChainMap = _Alias() -if sys.version_info >= (3, 7): - OrderedDict = _Alias() +OrderedDict = _Alias() -if sys.version_info >= (3, 9): - Annotated: _SpecialForm = ... +Annotated: _SpecialForm +if sys.version_info >= (3, 15): + @type_check_only + class _NoExtraItemsType: ... + + NoExtraItems: _NoExtraItemsType + + TypeForm: _SpecialForm # Predefined type variables. -AnyStr = TypeVar("AnyStr", str, bytes) +AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 + +@type_check_only +class _Generic: + if sys.version_info < (3, 12): + __slots__ = () + + @classmethod + def __class_getitem__(cls, args: TypeVar | ParamSpec | tuple[TypeVar | ParamSpec, ...]) -> _Final: ... + +Generic: type[_Generic] -if sys.version_info >= (3, 8): - # This class did actually exist in 3.7, but had a different base. - # We'll just pretend it didn't exist though: the main external use case for _ProtocolMeta is - # to inherit from for your own custom protocol metaclasses. If you're using 3.7, at runtime - # you'd use typing_extensions.Protocol, which would be unrelated to typing._ProtocolMeta and - # so you'd run into metaclass conflicts at runtime if you used typing._ProtocolMeta. - class _ProtocolMeta(ABCMeta): ... +@type_check_only +class _Protocol: ... + +Protocol: type[_Protocol] + +class _ProtocolMeta(ABCMeta): + if sys.version_info >= (3, 12): + def __init__(cls, *args: Any, **kwargs: Any) -> None: ... # Abstract base classes. def runtime_checkable(cls: _TC) -> _TC: ... + @runtime_checkable class SupportsInt(Protocol, metaclass=ABCMeta): + __slots__ = () @abstractmethod def __int__(self) -> int: ... @runtime_checkable class SupportsFloat(Protocol, metaclass=ABCMeta): + __slots__ = () @abstractmethod def __float__(self) -> float: ... @runtime_checkable class SupportsComplex(Protocol, metaclass=ABCMeta): + __slots__ = () @abstractmethod def __complex__(self) -> complex: ... @runtime_checkable class SupportsBytes(Protocol, metaclass=ABCMeta): + __slots__ = () @abstractmethod def __bytes__(self) -> bytes: ... -if sys.version_info >= (3, 8): - @runtime_checkable - class SupportsIndex(Protocol, metaclass=ABCMeta): - @abstractmethod - def __index__(self) -> int: ... +@runtime_checkable +class SupportsIndex(Protocol, metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __index__(self) -> int: ... @runtime_checkable class SupportsAbs(Protocol[_T_co]): + __slots__ = () @abstractmethod def __abs__(self) -> _T_co: ... @runtime_checkable class SupportsRound(Protocol[_T_co]): + __slots__ = () + @overload @abstractmethod def __round__(self) -> int: ... @overload @abstractmethod - def __round__(self, __ndigits: int) -> _T_co: ... + def __round__(self, ndigits: int, /) -> _T_co: ... @runtime_checkable class Sized(Protocol, metaclass=ABCMeta): @@ -218,62 +560,79 @@ class Reversible(Iterable[_T_co], Protocol[_T_co]): @abstractmethod def __reversed__(self) -> Iterator[_T_co]: ... -class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): - def __next__(self) -> _T_co: ... +_YieldT_co = TypeVar("_YieldT_co", covariant=True) +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None) +_ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) + +@runtime_checkable +class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _ReturnT_co]): + def __next__(self) -> _YieldT_co: ... @abstractmethod - def send(self, __value: _T_contra) -> _T_co: ... + def send(self, value: _SendT_contra, /) -> _YieldT_co: ... + @overload @abstractmethod def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> _T_co: ... + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> _YieldT_co: ... @overload @abstractmethod - def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... - def close(self) -> None: ... - def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ... - @property - def gi_code(self) -> CodeType: ... - @property - def gi_frame(self) -> FrameType: ... - @property - def gi_running(self) -> bool: ... - @property - def gi_yieldfrom(self) -> Generator[Any, Any, Any] | None: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... + + if sys.version_info >= (3, 13): + def close(self) -> _ReturnT_co | None: ... + else: + def close(self) -> None: ... + + def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ... + +# NOTE: Prior to Python 3.13 these aliases are lacking the second _ExitT_co parameter +if sys.version_info >= (3, 13): + from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager +else: + from contextlib import AbstractAsyncContextManager, AbstractContextManager + + @runtime_checkable + class ContextManager(AbstractContextManager[_T_co, bool | None], Protocol[_T_co]): ... + + @runtime_checkable + class AsyncContextManager(AbstractAsyncContextManager[_T_co, bool | None], Protocol[_T_co]): ... @runtime_checkable class Awaitable(Protocol[_T_co]): @abstractmethod - def __await__(self) -> Generator[Any, None, _T_co]: ... + def __await__(self) -> Generator[Any, Any, _T_co]: ... -class Coroutine(Awaitable[_V_co], Generic[_T_co, _T_contra, _V_co]): - __name__: str - __qualname__: str - @property - def cr_await(self) -> Any | None: ... - @property - def cr_code(self) -> CodeType: ... - @property - def cr_frame(self) -> FrameType: ... - @property - def cr_running(self) -> bool: ... +# Non-default variations to accommodate coroutines, and `AwaitableGenerator` having a 4th type parameter. +_SendT_nd_contra = TypeVar("_SendT_nd_contra", contravariant=True) +_ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True) + +@runtime_checkable +class Coroutine(Awaitable[_ReturnT_nd_co], Protocol[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]): @abstractmethod - def send(self, __value: _T_contra) -> _T_co: ... + def send(self, value: _SendT_nd_contra, /) -> _YieldT_co: ... + @overload @abstractmethod def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> _T_co: ... + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> _YieldT_co: ... @overload @abstractmethod - def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... + @abstractmethod def close(self) -> None: ... # NOTE: This type does not exist in typing.py or PEP 484 but mypy needs it to exist. # The parameters correspond to Generator, but the 4th is the original type. +# Obsolete, use _typeshed._type_checker_internals.AwaitableGenerator instead. +@type_check_only class AwaitableGenerator( - Awaitable[_V_co], Generator[_T_co, _T_contra, _V_co], Generic[_T_co, _T_contra, _V_co, _S], metaclass=ABCMeta + Awaitable[_ReturnT_nd_co], + Generator[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co], + Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co, _S], + metaclass=ABCMeta, ): ... @runtime_checkable @@ -287,224 +646,262 @@ class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): def __anext__(self) -> Awaitable[_T_co]: ... def __aiter__(self) -> AsyncIterator[_T_co]: ... -class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): - @abstractmethod - def __anext__(self) -> Awaitable[_T_co]: ... +@runtime_checkable +class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra]): + def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... @abstractmethod - def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... + def asend(self, value: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... + @overload @abstractmethod def athrow( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> Awaitable[_T_co]: ... + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> Coroutine[Any, Any, _YieldT_co]: ... @overload @abstractmethod - def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Awaitable[_T_co]: ... - @abstractmethod - def aclose(self) -> Awaitable[None]: ... - @abstractmethod - def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... - @property - def ag_await(self) -> Any: ... - @property - def ag_code(self) -> CodeType: ... - @property - def ag_frame(self) -> FrameType: ... - @property - def ag_running(self) -> bool: ... + def athrow( + self, typ: BaseException, val: None = None, tb: TracebackType | None = None, / + ) -> Coroutine[Any, Any, _YieldT_co]: ... + + def aclose(self) -> Coroutine[Any, Any, None]: ... + +_ContainerT_contra = TypeVar("_ContainerT_contra", contravariant=True, default=Any) @runtime_checkable -class Container(Protocol[_T_co]): +class Container(Protocol[_ContainerT_contra]): + # This is generic more on vibes than anything else @abstractmethod - def __contains__(self, __x: object) -> bool: ... + def __contains__(self, x: _ContainerT_contra, /) -> bool: ... @runtime_checkable -class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): +class Collection(Iterable[_T_co], Container[Any], Protocol[_T_co]): + # Note: need to use Container[Any] instead of Container[_T_co] to ensure covariance. # Implement Sized (but don't have it as a base class). @abstractmethod def __len__(self) -> int: ... -class Sequence(Collection[_T_co], Reversible[_T_co], Generic[_T_co]): +class Sequence(Reversible[_T_co], Collection[_T_co]): @overload @abstractmethod - def __getitem__(self, i: int) -> _T_co: ... + def __getitem__(self, index: int, /) -> _T_co: ... @overload @abstractmethod - def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + def __getitem__(self, index: slice[int | None], /) -> Sequence[_T_co]: ... + # Mixin methods - def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... - def count(self, value: Any) -> int: ... - def __contains__(self, x: object) -> bool: ... + def index(self, value: Any, start: int = 0, stop: int = ..., /) -> int: ... + def count(self, value: Any, /) -> int: ... + def __contains__(self, value: object, /) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... -class MutableSequence(Sequence[_T], Generic[_T]): +class MutableSequence(Sequence[_T]): @abstractmethod - def insert(self, index: int, value: _T) -> None: ... + def insert(self, index: int, value: _T, /) -> None: ... + @overload @abstractmethod - def __getitem__(self, i: int) -> _T: ... + def __getitem__(self, index: int, /) -> _T: ... @overload @abstractmethod - def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + def __getitem__(self, index: slice[int | None], /) -> MutableSequence[_T]: ... + @overload @abstractmethod - def __setitem__(self, i: int, o: _T) -> None: ... + def __setitem__(self, index: int, value: _T, /) -> None: ... @overload @abstractmethod - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __setitem__(self, index: slice[int | None], value: Iterable[_T], /) -> None: ... + @overload @abstractmethod - def __delitem__(self, i: int) -> None: ... + def __delitem__(self, index: int, /) -> None: ... @overload @abstractmethod - def __delitem__(self, i: slice) -> None: ... + def __delitem__(self, index: slice[int | None], /) -> None: ... + # Mixin methods - def append(self, value: _T) -> None: ... + def append(self, value: _T, /) -> None: ... def clear(self) -> None: ... - def extend(self, values: Iterable[_T]) -> None: ... + def extend(self, values: Iterable[_T], /) -> None: ... def reverse(self) -> None: ... - def pop(self, index: int = ...) -> _T: ... - def remove(self, value: _T) -> None: ... - def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + def pop(self, index: int = -1, /) -> _T: ... + def remove(self, value: _T, /) -> None: ... + def __iadd__(self, values: Iterable[_T], /) -> typing_extensions.Self: ... -class AbstractSet(Collection[_T_co], Generic[_T_co]): +class AbstractSet(Collection[_T_co]): @abstractmethod - def __contains__(self, x: object) -> bool: ... + def __contains__(self, x: object, /) -> bool: ... + def _hash(self) -> int: ... # Mixin methods - def __le__(self, s: AbstractSet[Any]) -> bool: ... - def __lt__(self, s: AbstractSet[Any]) -> bool: ... - def __gt__(self, s: AbstractSet[Any]) -> bool: ... - def __ge__(self, s: AbstractSet[Any]) -> bool: ... - def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __or__(self, s: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... - def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... - def isdisjoint(self, other: Iterable[Any]) -> bool: ... - -class MutableSet(AbstractSet[_T], Generic[_T]): - @abstractmethod - def add(self, value: _T) -> None: ... - @abstractmethod - def discard(self, value: _T) -> None: ... + @classmethod + def _from_iterable(cls, it: Iterable[_S], /) -> AbstractSet[_S]: ... + def __le__(self, other: AbstractSet[Any], /) -> bool: ... + def __lt__(self, other: AbstractSet[Any], /) -> bool: ... + def __gt__(self, other: AbstractSet[Any], /) -> bool: ... + def __ge__(self, other: AbstractSet[Any], /) -> bool: ... + def __and__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ... + def __or__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... + def __sub__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ... + def __xor__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... + def __eq__(self, other: object, /) -> bool: ... + def isdisjoint(self, other: Iterable[Any], /) -> bool: ... + +class MutableSet(AbstractSet[_T]): + @abstractmethod + def add(self, value: _T, /) -> None: ... + @abstractmethod + def discard(self, value: _T, /) -> None: ... # Mixin methods def clear(self) -> None: ... def pop(self) -> _T: ... - def remove(self, value: _T) -> None: ... - def __ior__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def remove(self, value: _T, /) -> None: ... + def __ior__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ... # type: ignore[override,misc] + def __iand__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ... + def __ixor__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ... # type: ignore[override,misc] + def __isub__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ... class MappingView(Sized): - def __init__(self, mapping: Mapping[Any, Any]) -> None: ... # undocumented + __slots__ = ("_mapping",) + def __init__(self, mapping: Sized) -> None: ... # undocumented def __len__(self) -> int: ... -class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented - def __and__(self, o: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... - def __rand__(self, o: Iterable[_T]) -> set[_T]: ... - def __contains__(self, o: object) -> bool: ... +class ItemsView(MappingView, AbstractSet[tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __init__(self, mapping: SupportsGetItemViewable[_KT_co, _VT_co]) -> None: ... # undocumented + @classmethod + def _from_iterable(cls, it: Iterable[_S], /) -> set[_S]: ... + def __and__(self, other: Iterable[Any], /) -> set[tuple[_KT_co, _VT_co]]: ... + def __rand__(self, other: Iterable[_T], /) -> set[_T]: ... + def __contains__(self, item: tuple[object, object], /) -> bool: ... # type: ignore[override] def __iter__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... - def __or__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... - def __ror__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... - def __sub__(self, o: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... - def __rsub__(self, o: Iterable[_T]) -> set[_T]: ... - def __xor__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... - def __rxor__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... - -class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): - def __init__(self, mapping: Mapping[_KT_co, Any]) -> None: ... # undocumented - def __and__(self, o: Iterable[Any]) -> set[_KT_co]: ... - def __rand__(self, o: Iterable[_T]) -> set[_T]: ... - def __contains__(self, o: object) -> bool: ... + def __or__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __ror__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __sub__(self, other: Iterable[Any], /) -> set[tuple[_KT_co, _VT_co]]: ... + def __rsub__(self, other: Iterable[_T], /) -> set[_T]: ... + def __xor__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __rxor__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + +class KeysView(MappingView, AbstractSet[_KT_co]): + def __init__(self, mapping: Viewable[_KT_co]) -> None: ... # undocumented + @classmethod + def _from_iterable(cls, it: Iterable[_S], /) -> set[_S]: ... + def __and__(self, other: Iterable[Any], /) -> set[_KT_co]: ... + def __rand__(self, other: Iterable[_T], /) -> set[_T]: ... + def __contains__(self, key: object, /) -> bool: ... def __iter__(self) -> Iterator[_KT_co]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[_KT_co]: ... - def __or__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... - def __ror__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... - def __sub__(self, o: Iterable[Any]) -> set[_KT_co]: ... - def __rsub__(self, o: Iterable[_T]) -> set[_T]: ... - def __xor__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... - def __rxor__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... - -class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): - def __init__(self, mapping: Mapping[Any, _VT_co]) -> None: ... # undocumented - def __contains__(self, o: object) -> bool: ... + def __or__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + def __ror__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + def __sub__(self, other: Iterable[Any], /) -> set[_KT_co]: ... + def __rsub__(self, other: Iterable[_T], /) -> set[_T]: ... + def __xor__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + def __rxor__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + +class ValuesView(MappingView, Collection[_VT_co]): + def __init__(self, mapping: SupportsGetItemViewable[Any, _VT_co]) -> None: ... # undocumented + def __contains__(self, value: object, /) -> bool: ... def __iter__(self) -> Iterator[_VT_co]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[_VT_co]: ... - -@runtime_checkable -class ContextManager(Protocol[_T_co]): - def __enter__(self) -> _T_co: ... - def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> bool | None: ... -@runtime_checkable -class AsyncContextManager(Protocol[_T_co]): - def __aenter__(self) -> Awaitable[_T_co]: ... - def __aexit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> Awaitable[bool | None]: ... +# note for Mapping.get and MutableMapping.pop and MutableMapping.setdefault +# In _collections_abc.py the parameters are positional-or-keyword, +# but dict and types.MappingProxyType (the vast majority of Mapping types) +# don't allow keyword arguments. class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, # see discussion in https://github.com/python/typing/pull/273. @abstractmethod - def __getitem__(self, __k: _KT) -> _VT_co: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + # Mixin methods @overload - def get(self, key: _KT) -> _VT_co | None: ... + def get(self, key: _KT, /) -> _VT_co | None: ... @overload - def get(self, __key: _KT, __default: _VT_co | _T) -> _VT_co | _T: ... + def get(self, key: _KT, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + @overload + def get(self, key: _KT, default: _T, /) -> _VT_co | _T: ... + def items(self) -> ItemsView[_KT, _VT_co]: ... def keys(self) -> KeysView[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... - def __contains__(self, __o: object) -> bool: ... + def __contains__(self, key: object, /) -> bool: ... + def __eq__(self, other: object, /) -> bool: ... -class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): +class MutableMapping(Mapping[_KT, _VT]): @abstractmethod - def __setitem__(self, __k: _KT, __v: _VT) -> None: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... @abstractmethod - def __delitem__(self, __v: _KT) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... def clear(self) -> None: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... @overload - def pop(self, __key: _KT) -> _VT: ... + def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + def popitem(self) -> tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + + # This overload should be allowed only if the value type is compatible with None. + # + # Keep the following methods in line with MutableMapping.setdefault, modulo positional-only differences: + # -- collections.OrderedDict.setdefault + # -- collections.ChainMap.setdefault + # -- weakref.WeakKeyDictionary.setdefault + @overload + def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT, /) -> _VT: ... + # 'update' used to take a Union, but using overloading is better. # The second overloaded type here is a bit too general, because - # Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]], + # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]], # but will always have the behavior of the first overloaded type - # at runtime, leading to keys of a mix of types _KT and Tuple[_KT, _VT]. + # at runtime, leading to keys of a mix of types _KT and tuple[_KT, _VT]. # We don't currently have any way of forcing all Mappings to use # the first overload, but by using overloading rather than a Union, # mypy will commit to using the first overload when the argument is # known to be a Mapping with unknown type parameters, which is closer # to the behavior we want. See mypy issue #1430. + # + # Various mapping classes have __ior__ methods that should be kept roughly in line with .update(): + # -- dict.__ior__ + # -- os._Environ.__ior__ + # -- collections.UserDict.__ior__ + # -- collections.ChainMap.__ior__ + # -- peewee.attrdict.__add__ + # -- peewee.attrdict.__iadd__ + # -- weakref.WeakValueDictionary.__ior__ + # -- weakref.WeakKeyDictionary.__ior__ + @overload + def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... + @overload + def update(self: SupportsGetItem[str, _VT], m: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ... @overload - def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def update(self, m: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload - def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def update(self: SupportsGetItem[str, _VT], m: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... @overload - def update(self, **kwargs: _VT) -> None: ... + def update(self: SupportsGetItem[str, _VT], /, **kwargs: _VT) -> None: ... Text = str -TYPE_CHECKING = True +TYPE_CHECKING: Final[bool] -class IO(Iterator[AnyStr], Generic[AnyStr]): - # TODO use abstract properties +# In stubs, the arguments of the IO class are marked as positional-only. +# This differs from runtime, but better reflects the fact that in reality +# classes deriving from IO use different names for the arguments. +class IO(Generic[AnyStr]): + # At runtime these are all abstract properties, + # but making them abstract in the stub is hugely disruptive, for not much gain. + # See #8726 + __slots__ = () @property def mode(self) -> str: ... + # Usually str, but may be bytes if a bytes path was passed to open(). See #10737. + # If PEP 696 becomes available, we may want to use a defaulted TypeVar here. @property - def name(self) -> str: ... + def name(self) -> str | Any: ... @abstractmethod def close(self) -> None: ... @property @@ -516,27 +913,38 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): @abstractmethod def isatty(self) -> bool: ... @abstractmethod - def read(self, n: int = ...) -> AnyStr: ... + def read(self, n: int = -1, /) -> AnyStr: ... @abstractmethod def readable(self) -> bool: ... @abstractmethod - def readline(self, limit: int = ...) -> AnyStr: ... + def readline(self, limit: int = -1, /) -> AnyStr: ... @abstractmethod - def readlines(self, hint: int = ...) -> list[AnyStr]: ... + def readlines(self, hint: int = -1, /) -> list[AnyStr]: ... @abstractmethod - def seek(self, offset: int, whence: int = ...) -> int: ... + def seek(self, offset: int, whence: int = 0, /) -> int: ... @abstractmethod def seekable(self) -> bool: ... @abstractmethod def tell(self) -> int: ... @abstractmethod - def truncate(self, size: int | None = ...) -> int: ... + def truncate(self, size: int | None = None, /) -> int: ... @abstractmethod def writable(self) -> bool: ... + + @abstractmethod + @overload + def write(self: IO[bytes], s: ReadableBuffer, /) -> int: ... + @abstractmethod + @overload + def write(self, s: AnyStr, /) -> int: ... + @abstractmethod - def write(self, s: AnyStr) -> int: ... + @overload + def writelines(self: IO[bytes], lines: Iterable[ReadableBuffer], /) -> None: ... @abstractmethod - def writelines(self, lines: Iterable[AnyStr]) -> None: ... + @overload + def writelines(self, lines: Iterable[AnyStr], /) -> None: ... + @abstractmethod def __next__(self) -> AnyStr: ... @abstractmethod @@ -545,15 +953,17 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): def __enter__(self) -> IO[AnyStr]: ... @abstractmethod def __exit__( - self, t: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... class BinaryIO(IO[bytes]): + __slots__ = () @abstractmethod def __enter__(self) -> BinaryIO: ... class TextIO(IO[str]): - # TODO use abstractproperty + # See comment regarding the @properties in the `IO` class + __slots__ = () @property def buffer(self) -> BinaryIO: ... @property @@ -567,175 +977,277 @@ class TextIO(IO[str]): @abstractmethod def __enter__(self) -> TextIO: ... -class ByteString(Sequence[int], metaclass=ABCMeta): ... - -@_final -class Match(Generic[AnyStr]): - pos: int - endpos: int - lastindex: int | None - lastgroup: AnyStr | None - string: AnyStr - - # The regular expression object whose match() or search() method produced - # this match instance. - re: Pattern[AnyStr] - def expand(self, template: AnyStr) -> AnyStr: ... - # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. - @overload - def group(self, __group: _Literal[0] = ...) -> AnyStr: ... - @overload - def group(self, __group: str | int) -> AnyStr | Any: ... - @overload - def group(self, __group1: str | int, __group2: str | int, *groups: str | int) -> Tuple[AnyStr | Any, ...]: ... - # Each item of groups()'s return tuple is either "AnyStr" or - # "AnyStr | None", depending on the pattern. - @overload - def groups(self) -> Tuple[AnyStr | Any, ...]: ... - @overload - def groups(self, default: _T) -> Tuple[AnyStr | _T, ...]: ... - # Each value in groupdict()'s return dict is either "AnyStr" or - # "AnyStr | None", depending on the pattern. - @overload - def groupdict(self) -> dict[str, AnyStr | Any]: ... - @overload - def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... - def start(self, __group: int | str = ...) -> int: ... - def end(self, __group: int | str = ...) -> int: ... - def span(self, __group: int | str = ...) -> tuple[int, int]: ... - @property - def regs(self) -> Tuple[tuple[int, int], ...]: ... # undocumented - # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. - @overload - def __getitem__(self, __key: _Literal[0]) -> AnyStr: ... - @overload - def __getitem__(self, __key: int | str) -> AnyStr | Any: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -@_final -class Pattern(Generic[AnyStr]): - flags: int - groupindex: Mapping[str, int] - groups: int - pattern: AnyStr - def search(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def match(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def fullmatch(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ... - def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ... - def finditer(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Iterator[Match[AnyStr]]: ... - @overload - def sub(self, repl: AnyStr, string: AnyStr, count: int = ...) -> AnyStr: ... - @overload - def sub(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ...) -> AnyStr: ... - @overload - def subn(self, repl: AnyStr, string: AnyStr, count: int = ...) -> tuple[AnyStr, int]: ... - @overload - def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ...) -> tuple[AnyStr, int]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... +ByteString: typing_extensions.TypeAlias = bytes | bytearray | memoryview # Functions -if sys.version_info >= (3, 7): - _get_type_hints_obj_allowed_types = Union[ - object, - Callable[..., Any], - FunctionType, - BuiltinFunctionType, - MethodType, - ModuleType, - WrapperDescriptorType, - MethodWrapperType, - MethodDescriptorType, - ] -else: - _get_type_hints_obj_allowed_types = Union[ - object, Callable[..., Any], FunctionType, BuiltinFunctionType, MethodType, ModuleType, - ] - -if sys.version_info >= (3, 9): +_get_type_hints_obj_allowed_types: typing_extensions.TypeAlias = ( # noqa: Y042 + object + | Callable[..., Any] + | FunctionType + | BuiltinFunctionType + | MethodType + | ModuleType + | WrapperDescriptorType + | MethodWrapperType + | MethodDescriptorType +) + +if sys.version_info >= (3, 14): def get_type_hints( obj: _get_type_hints_obj_allowed_types, - globalns: dict[str, Any] | None = ..., - localns: dict[str, Any] | None = ..., - include_extras: bool = ..., - ) -> dict[str, Any]: ... + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, + *, + format: Format | None = None, # Default: Format.VALUE + ) -> dict[str, Any]: ... # AnnotationForm else: def get_type_hints( - obj: _get_type_hints_obj_allowed_types, globalns: dict[str, Any] | None = ..., localns: dict[str, Any] | None = ... - ) -> dict[str, Any]: ... + obj: _get_type_hints_obj_allowed_types, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, + ) -> dict[str, Any]: ... # AnnotationForm + +def get_args(tp: Any) -> tuple[Any, ...]: ... # AnnotationForm -if sys.version_info >= (3, 8): - def get_origin(tp: Any) -> Any | None: ... - def get_args(tp: Any) -> Tuple[Any, ...]: ... +@overload +def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... +@overload +def get_origin(tp: UnionType) -> type[UnionType]: ... +@overload +def get_origin(tp: GenericAlias) -> type: ... +@overload +def get_origin(tp: Any) -> Any | None: ... # AnnotationForm @overload -def cast(typ: Type[_T], val: Any) -> _T: ... +def cast(typ: type[_T], val: Any) -> _T: ... @overload def cast(typ: str, val: Any) -> Any: ... @overload def cast(typ: object, val: Any) -> Any: ... +if sys.version_info >= (3, 11): + def reveal_type(obj: _T, /) -> _T: ... + def assert_never(arg: Never, /) -> Never: ... + def assert_type(val: _T, typ: Any, /) -> _T: ... # AnnotationForm + def clear_overloads() -> None: ... + def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, # on 3.11, runtime accepts it as part of kwargs + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), + **kwargs: Any, + ) -> IdentityFunction: ... + # Type constructors -class NamedTuple(Tuple[Any, ...]): - _field_types: collections.OrderedDict[str, Type[Any]] - _field_defaults: dict[str, Any] - _fields: Tuple[str, ...] - _source: str - @overload - def __init__(self, typename: str, fields: Iterable[tuple[str, Any]] = ...) -> None: ... - @overload - def __init__(self, typename: str, fields: None = ..., **kwargs: Any) -> None: ... - @classmethod - def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... - if sys.version_info >= (3, 8): - def _asdict(self) -> dict[str, Any]: ... +# Obsolete, will be changed to a function. Use _typeshed._type_checker_internals.NamedTupleFallback instead. +class NamedTuple(tuple[Any, ...]): + _field_defaults: ClassVar[dict[str, Any]] + _fields: ClassVar[tuple[str, ...]] + __match_args__: ClassVar[tuple[str, ...]] = ... + # __orig_bases__ sometimes exists on <3.12, but not consistently + # So we only add it to the stub on 3.12+. + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + + if sys.version_info >= (3, 15): + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... else: - def _asdict(self) -> collections.OrderedDict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... + @overload + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... + @overload + @deprecated("Creating a typing.NamedTuple using keyword arguments is deprecated; support removed in Python 3.15") + def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... + + @final + @classmethod + def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] + @final + def _asdict(self) -> dict[str, Any]: ... + @final + def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] # Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict +# Obsolete, use _typeshed._type_checker_internals.TypedDictFallback instead. +@type_check_only class _TypedDict(Mapping[str, object], metaclass=ABCMeta): - def copy(self: _T) -> _T: ... - # Using NoReturn so that only calls using mypy plugin hook that specialize the signature + __total__: ClassVar[bool] + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + # __orig_bases__ sometimes exists on <3.12, but not consistently, + # so we only add it to the stub on 3.12+ + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + if sys.version_info >= (3, 13): + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + if sys.version_info >= (3, 15): + # PEP 728 + __closed__: ClassVar[bool | None] + __extra_items__: ClassVar[Any] # AnnotationForm + + def copy(self) -> typing_extensions.Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature # can go through. - def setdefault(self, k: NoReturn, default: object) -> object: ... + def setdefault(self, k: _Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. - def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... - def __delitem__(self, k: NoReturn) -> None: ... - def items(self) -> ItemsView[str, object]: ... - def keys(self) -> KeysView[str]: ... - def values(self) -> ValuesView[object]: ... - def __or__(self: _T, __value: _T) -> _T: ... - def __ior__(self: _T, __value: _T) -> _T: ... + def pop(self, k: _Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: typing_extensions.Self, /) -> None: ... + def __delitem__(self, k: _Never) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... -# This itself is only available during type checking -def type_check_only(func_or_cls: _F) -> _F: ... + @overload + def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... -if sys.version_info >= (3, 7): - class ForwardRef: + # supposedly incompatible definitions of __or__ and __ior__ + def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] + +if sys.version_info >= (3, 14): + from annotationlib import ForwardRef as ForwardRef + + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: object = None, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar, ParamSpec, TypeVarTuple] | None = None, + format: Format | None = None, + ) -> Any: ... # AnnotationForm + +else: + @final + class ForwardRef(_Final): + __slots__ = ( + "__forward_arg__", + "__forward_code__", + "__forward_evaluated__", + "__forward_value__", + "__forward_is_argument__", + "__forward_is_class__", + "__forward_module__", + ) __forward_arg__: str __forward_code__: CodeType __forward_evaluated__: bool - __forward_value__: Any | None + __forward_value__: Any | None # AnnotationForm __forward_is_argument__: bool - if sys.version_info >= (3, 9): - # The module and is_class arguments were added in later Python 3.9 versions. - def __init__(self, arg: str, is_argument: bool = ..., module: Any | None = ..., *, is_class: bool = ...) -> None: ... + __forward_is_class__: bool + __forward_module__: Any | None + + def __init__(self, arg: str, is_argument: bool = True, module: Any | None = None, *, is_class: bool = False) -> None: ... + + if sys.version_info >= (3, 13): + @overload + @deprecated( + "Failing to pass a value to the 'type_params' parameter of ForwardRef._evaluate() is deprecated, " + "as it leads to incorrect behaviour when evaluating a stringified annotation " + "that references a PEP 695 type parameter. It will be disallowed in Python 3.15." + ) + def _evaluate( + self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, *, recursive_guard: frozenset[str] + ) -> Any | None: ... # AnnotationForm + @overload + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: Mapping[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...], + *, + recursive_guard: frozenset[str], + ) -> Any | None: ... # AnnotationForm + elif sys.version_info >= (3, 12): + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: Mapping[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + *, + recursive_guard: frozenset[str], + ) -> Any | None: ... # AnnotationForm else: - def __init__(self, arg: str, is_argument: bool = ...) -> None: ... - def _evaluate(self, globalns: dict[str, Any] | None, localns: dict[str, Any] | None) -> Any | None: ... - def __eq__(self, other: Any) -> bool: ... + def _evaluate( + self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, recursive_guard: frozenset[str] + ) -> Any | None: ... # AnnotationForm + + def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... - def __repr__(self) -> str: ... if sys.version_info >= (3, 11): def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... -if sys.version_info >= (3, 10): - def is_typeddict(tp: object) -> bool: ... +def is_typeddict(tp: object) -> bool: ... +def _type_repr(obj: object) -> str: ... + +if sys.version_info >= (3, 12): + _TypeParameter: typing_extensions.TypeAlias = ( + TypeVar + | typing_extensions.TypeVar + | ParamSpec + | typing_extensions.ParamSpec + | TypeVarTuple + | typing_extensions.TypeVarTuple + ) + + def override(method: _F, /) -> _F: ... + + @final + class TypeAliasType: + if sys.version_info >= (3, 15): + def __new__( + cls, name: str, value: Any, *, type_params: tuple[_TypeParameter, ...] = (), qualname: str | None = None + ) -> Self: ... + @property + def __qualname__(self) -> str: ... + else: + def __new__(cls, name: str, value: Any, *, type_params: tuple[_TypeParameter, ...] = ()) -> Self: ... + + @property + def __value__(self) -> Any: ... # AnnotationForm + @property + def __type_params__(self) -> tuple[_TypeParameter, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... # AnnotationForm + @property + def __name__(self) -> str: ... + # It's writable on types, but not on instances of TypeAliasType. + @property + def __module__(self) -> str | None: ... # type: ignore[override] + def __getitem__(self, parameters: Any, /) -> GenericAlias: ... # AnnotationForm + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + if sys.version_info >= (3, 14): + def __iter__(self) -> Any: ... # Unpack[Self] + @property + def evaluate_value(self) -> EvaluateFunc: ... + +if sys.version_info >= (3, 13): + def is_protocol(tp: type, /) -> bool: ... + def get_protocol_members(tp: type, /) -> frozenset[str]: ... + + @final + @type_check_only + class _NoDefaultType: ... + + NoDefault: _NoDefaultType + TypeIs: _SpecialForm + ReadOnly: _SpecialForm diff --git a/stdlib/typing_extensions.pyi b/stdlib/typing_extensions.pyi index 3eb41c797f4a..49ddbc2f24bf 100644 --- a/stdlib/typing_extensions.pyi +++ b/stdlib/typing_extensions.pyi @@ -1,125 +1,752 @@ import abc +import enum import sys -from typing import ( - TYPE_CHECKING as TYPE_CHECKING, - Any, - AsyncContextManager as AsyncContextManager, +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import AnnotationForm, IdentityFunction, Incomplete, Unused +from collections.abc import ( AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, AsyncIterator as AsyncIterator, Awaitable as Awaitable, - Callable, + Collection as Collection, + Container as Container, + Coroutine as Coroutine, + Generator as Generator, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Reversible as Reversible, + Sequence as Sequence, + Sized as Sized, + ValuesView as ValuesView, +) +from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager +from re import Match as Match, Pattern as Pattern +from types import GenericAlias, ModuleType, UnionType +from typing import ( # noqa: Y022,Y037,Y038,Y039 # ruff: ignore[deprecated-import] + IO as IO, + TYPE_CHECKING as TYPE_CHECKING, + AbstractSet as AbstractSet, + Any as Any, + AnyStr as AnyStr, + BinaryIO as BinaryIO, + Callable as Callable, ChainMap as ChainMap, ClassVar as ClassVar, - ContextManager as ContextManager, - Coroutine as Coroutine, + Concatenate as Concatenate, Counter as Counter, DefaultDict as DefaultDict, Deque as Deque, - ItemsView, - KeysView, - Mapping, - NewType as NewType, + Dict as Dict, + ForwardRef as ForwardRef, + FrozenSet as FrozenSet, + Generic as Generic, + List as List, NoReturn as NoReturn, + Optional as Optional, + ParamSpecArgs as ParamSpecArgs, + ParamSpecKwargs as ParamSpecKwargs, + Set as Set, Text as Text, - Tuple, + TextIO as TextIO, + Tuple as Tuple, Type as Type, - TypeVar, - ValuesView, + TypeAlias as TypeAlias, + TypeGuard as TypeGuard, + TypeVar as _TypeVar, + Union as Union, _Alias, + _SpecialForm, + cast as cast, + is_typeddict as is_typeddict, + no_type_check as no_type_check, overload as overload, + type_check_only, ) -_T = TypeVar("_T") -_F = TypeVar("_F", bound=Callable[..., Any]) -_TC = TypeVar("_TC", bound=Type[object]) +if sys.version_info >= (3, 14): + from _typeshed import EvaluateFunc + +# Please keep order the same as at runtime. +__all__ = [ + # Super-special typing primitives. + "Any", + "ClassVar", + "Concatenate", + "Final", + "LiteralString", + "ParamSpec", + "ParamSpecArgs", + "ParamSpecKwargs", + "Self", + "Type", + "TypeVar", + "TypeVarTuple", + "Unpack", + # ABCs (from collections.abc). + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "AsyncGenerator", + "AsyncContextManager", + "Buffer", + "ChainMap", + # Concrete collection types. + "ContextManager", + "Counter", + "Deque", + "DefaultDict", + "NamedTuple", + "OrderedDict", + "TypedDict", + # Structural checks, a.k.a. protocols. + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "Reader", + "Writer", + # One-off things. + "Annotated", + "assert_never", + "assert_type", + "clear_overloads", + "dataclass_transform", + "deprecated", + "disjoint_base", + "Doc", + "evaluate_forward_ref", + "get_overloads", + "final", + "Format", + "get_annotations", + "get_args", + "get_origin", + "get_original_bases", + "get_protocol_members", + "get_type_hints", + "IntVar", + "is_protocol", + "is_typeddict", + "Literal", + "NewType", + "overload", + "override", + "Protocol", + "Sentinel", + "sentinel", + "reveal_type", + "runtime", + "runtime_checkable", + "Text", + "TypeAlias", + "TypeAliasType", + "TypeForm", + "TypeGuard", + "TypeIs", + "TYPE_CHECKING", + "type_repr", + "Never", + "NoReturn", + "ReadOnly", + "Required", + "NotRequired", + "NoDefault", + "NoExtraItems", + # Pure aliases, have always been in typing + "AbstractSet", + "AnyStr", + "BinaryIO", + "Callable", + "Collection", + "Container", + "Dict", + "ForwardRef", + "FrozenSet", + "Generator", + "Generic", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Optional", + "Pattern", + "Reversible", + "Sequence", + "Set", + "Sized", + "TextIO", + "Tuple", + "Union", + "ValuesView", + "cast", + "no_type_check", + "no_type_check_decorator", + # Added dynamically + "CapsuleType", +] -class _SpecialForm: - def __getitem__(self, typeargs: Any) -> Any: ... +_T = _TypeVar("_T") +_F = _TypeVar("_F", bound=Callable[..., Any]) +_TC = _TypeVar("_TC", bound=type[object]) +_T_co = _TypeVar("_T_co", covariant=True) # Any type covariant containers. +_T_contra = _TypeVar("_T_contra", contravariant=True) + +if sys.version_info < (3, 15): + def no_type_check_decorator(decorator: _F) -> _F: ... + +@type_check_only +class _Protocol: ... + +# Do not import (and re-export) Protocol or runtime_checkable from +# typing module because type checkers need to be able to distinguish +# typing.Protocol and typing_extensions.Protocol so they can properly +# warn users about potential runtime exceptions when using typing.Protocol +# on older versions of Python. +Protocol: type[_Protocol] def runtime_checkable(cls: _TC) -> _TC: ... # This alias for above is kept here for backwards compatibility. runtime = runtime_checkable -Protocol: _SpecialForm = ... -Final: _SpecialForm = ... -Self: _SpecialForm = ... -Required: _SpecialForm = ... -NotRequired: _SpecialForm = ... +Final: _SpecialForm -def final(f: _F) -> _F: ... +def final(f: _T) -> _T: ... +def disjoint_base(cls: _TC) -> _TC: ... -Literal: _SpecialForm = ... +Literal: _SpecialForm def IntVar(name: str) -> Any: ... # returns a new TypeVar -if sys.version_info < (3, 8): - # Technically in 3.6 this inherited from GenericMeta. But let's not reflect that, since - # type checkers tend to assume that Protocols all have the ABCMeta metaclass. - class _ProtocolMeta(abc.ABCMeta): ... +# Kept as a distinct symbol to `typing.TypedDict` so that type checkers can more easily +# distinguish between the two on Python 3.14, on which `typing_extensions.TypedDict` +# exposes `__closed__` and `__extra_items__` but `typing.TypedDict` does not +TypedDict: _SpecialForm # Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing._TypedDict/mypy_extensions._TypedDict +@type_check_only class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): - __required_keys__: frozenset[str] - __optional_keys__: frozenset[str] - __total__: bool - def copy(self: _T) -> _T: ... - # Using NoReturn so that only calls using mypy plugin hook that specialize the signature + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + __total__: ClassVar[bool] + __orig_bases__: ClassVar[tuple[Any, ...]] + # PEP 705 + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + # PEP 728 + __closed__: ClassVar[bool | None] + __extra_items__: ClassVar[AnnotationForm] + def copy(self) -> Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature # can go through. - def setdefault(self, k: NoReturn, default: object) -> object: ... + def setdefault(self, k: Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. - def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... - def items(self) -> ItemsView[str, object]: ... - def keys(self) -> KeysView[str]: ... - def values(self) -> ValuesView[object]: ... - def __delitem__(self, k: NoReturn) -> None: ... + def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: Self, /) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + def __delitem__(self, k: Never) -> None: ... -# TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... + @overload + def __or__(self, value: Self, /) -> Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: Self, /) -> Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of `__ior__` and `__or__`: + # Since this module defines "Self" it is not recognized by Ruff as typing_extensions.Self + def __ior__(self, value: Self, /) -> Self: ... # type: ignore[misc] OrderedDict = _Alias() -if sys.version_info >= (3, 7): +if sys.version_info >= (3, 13): + from typing import get_type_hints as get_type_hints +else: def get_type_hints( - obj: Callable[..., Any], - globalns: dict[str, Any] | None = ..., - localns: dict[str, Any] | None = ..., - include_extras: bool = ..., - ) -> dict[str, Any]: ... - def get_args(tp: Any) -> Tuple[Any, ...]: ... - def get_origin(tp: Any) -> Any | None: ... - -Annotated: _SpecialForm = ... -_AnnotatedAlias: Any = ... # undocumented - -@runtime_checkable -class SupportsIndex(Protocol, metaclass=abc.ABCMeta): - @abc.abstractmethod - def __index__(self) -> int: ... - -# PEP 612 support for Python < 3.9 -if sys.version_info >= (3, 10): - from typing import Concatenate as Concatenate, ParamSpec as ParamSpec, TypeAlias as TypeAlias, TypeGuard as TypeGuard + obj: Any, globalns: dict[str, Any] | None = None, localns: Mapping[str, Any] | None = None, include_extras: bool = False + ) -> dict[str, AnnotationForm]: ... + +def get_args(tp: AnnotationForm) -> tuple[AnnotationForm, ...]: ... + +@overload +def get_origin(tp: UnionType) -> type[UnionType]: ... +@overload +def get_origin(tp: GenericAlias) -> type: ... +@overload +def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... +@overload +def get_origin(tp: AnnotationForm) -> AnnotationForm | None: ... + +Annotated: _SpecialForm +_AnnotatedAlias: Any # undocumented + +# New and changed things in 3.11 +if sys.version_info >= (3, 11): + from typing import ( + LiteralString as LiteralString, + NamedTuple as NamedTuple, + Never as Never, + NewType as NewType, + NotRequired as NotRequired, + Required as Required, + Self as Self, + Unpack as Unpack, + assert_never as assert_never, + assert_type as assert_type, + clear_overloads as clear_overloads, + dataclass_transform as dataclass_transform, + get_overloads as get_overloads, + reveal_type as reveal_type, + ) else: - class ParamSpecArgs: - __origin__: ParamSpec - def __init__(self, origin: ParamSpec) -> None: ... - class ParamSpecKwargs: - __origin__: ParamSpec - def __init__(self, origin: ParamSpec) -> None: ... - class ParamSpec: + Self: _SpecialForm + Never: _SpecialForm + def reveal_type(obj: _T, /) -> _T: ... + def assert_never(arg: Never, /) -> Never: ... + def assert_type(val: _T, typ: AnnotationForm, /) -> _T: ... + def clear_overloads() -> None: ... + def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... + + Required: _SpecialForm + NotRequired: _SpecialForm + LiteralString: _SpecialForm + Unpack: _SpecialForm + + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), + **kwargs: object, + ) -> IdentityFunction: ... + + class NamedTuple(tuple[Any, ...]): + _field_defaults: ClassVar[dict[str, Any]] + _fields: ClassVar[tuple[str, ...]] + __orig_bases__: ClassVar[tuple[Any, ...]] + + @overload + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]] = ...) -> None: ... + @overload + def __init__(self, typename: str, fields: None = None, **kwargs: Any) -> None: ... + + @classmethod + def _make(cls, iterable: Iterable[Any]) -> Self: ... # ty:ignore[invalid-type-form] + def _asdict(self) -> dict[str, Any]: ... + def _replace(self, **kwargs: Any) -> Self: ... # ty:ignore[invalid-type-form] + + class NewType: + def __init__(self, name: str, tp: AnnotationForm) -> None: ... + def __call__(self, obj: _T, /) -> _T: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + __supertype__: type | NewType __name__: str - __bound__: Type[Any] | None - __covariant__: bool - __contravariant__: bool + +if sys.version_info >= (3, 12): + from collections.abc import Buffer as Buffer + from types import get_original_bases as get_original_bases + from typing import ( + SupportsAbs as SupportsAbs, + SupportsBytes as SupportsBytes, + SupportsComplex as SupportsComplex, + SupportsFloat as SupportsFloat, + SupportsIndex as SupportsIndex, + SupportsInt as SupportsInt, + SupportsRound as SupportsRound, + override as override, + ) +else: + def override(arg: _F, /) -> _F: ... + def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... + + # mypy and pyright object to this being both ABC and Protocol. + # At runtime it inherits from ABC and is not a Protocol, but it is on the + # allowlist for use as a Protocol. + @runtime_checkable + class Buffer(Protocol, abc.ABC): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + # Not actually a Protocol at runtime; see + # https://github.com/python/typeshed/issues/10224 for why we're defining it this way + def __buffer__(self, flags: int, /) -> memoryview: ... + + @runtime_checkable + class SupportsInt(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __int__(self) -> int: ... + + @runtime_checkable + class SupportsFloat(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __float__(self) -> float: ... + + @runtime_checkable + class SupportsComplex(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __complex__(self) -> complex: ... + + @runtime_checkable + class SupportsBytes(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __bytes__(self) -> bytes: ... + + @runtime_checkable + class SupportsIndex(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __index__(self) -> int: ... + + @runtime_checkable + class SupportsAbs(Protocol[_T_co]): + __slots__ = () + @abc.abstractmethod + def __abs__(self) -> _T_co: ... + + @runtime_checkable + class SupportsRound(Protocol[_T_co]): + __slots__ = () + + @overload + @abc.abstractmethod + def __round__(self) -> int: ... + @overload + @abc.abstractmethod + def __round__(self, ndigits: int, /) -> _T_co: ... + +if sys.version_info >= (3, 14): + from io import Reader as Reader, Writer as Writer +else: + @runtime_checkable + class Reader(Protocol[_T_co]): + __slots__ = () + @abc.abstractmethod + def read(self, size: int = ..., /) -> _T_co: ... + + @runtime_checkable + class Writer(Protocol[_T_contra]): + __slots__ = () + @abc.abstractmethod + def write(self, data: _T_contra, /) -> int: ... + +if sys.version_info >= (3, 13): + from types import CapsuleType as CapsuleType + from typing import ( + NoDefault as NoDefault, + ParamSpec as ParamSpec, + ReadOnly as ReadOnly, + TypeIs as TypeIs, + TypeVar as TypeVar, + get_protocol_members as get_protocol_members, + is_protocol as is_protocol, + ) + from warnings import deprecated as deprecated +else: + def is_protocol(tp: type, /) -> bool: ... + def get_protocol_members(tp: type, /) -> frozenset[str]: ... + + @final + @type_check_only + class _NoDefaultType: ... + + NoDefault: _NoDefaultType + @final + class CapsuleType: ... + + class deprecated: + message: LiteralString + category: type[Warning] | None + stacklevel: int + def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... + def __call__(self, arg: _T, /) -> _T: ... + + @final + class TypeVar: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> AnnotationForm | None: ... + @property + def __constraints__(self) -> tuple[AnnotationForm, ...]: ... + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + @property + def __default__(self) -> AnnotationForm: ... + def __init__( + self, + name: str, + *constraints: AnnotationForm, + bound: AnnotationForm | None = None, + covariant: bool = False, + contravariant: bool = False, + default: AnnotationForm = ..., + infer_variance: bool = False, + ) -> None: ... + def has_default(self) -> bool: ... + def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any) -> Any: ... + + @final + class ParamSpec: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> AnnotationForm | None: ... + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + @property + def __default__(self) -> AnnotationForm: ... def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... + self, + name: str, + *, + bound: AnnotationForm | str | None = None, + contravariant: bool = False, + covariant: bool = False, + default: AnnotationForm = ..., ) -> None: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... @property def args(self) -> ParamSpecArgs: ... @property def kwargs(self) -> ParamSpecKwargs: ... - Concatenate: _SpecialForm = ... - TypeAlias: _SpecialForm = ... - TypeGuard: _SpecialForm = ... + def has_default(self) -> bool: ... + def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... + + ReadOnly: _SpecialForm + TypeIs: _SpecialForm + +if sys.version_info >= (3, 15): + from typing import TypeVarTuple as TypeVarTuple +else: + @final + class TypeVarTuple: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> AnnotationForm | None: ... + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + @property + def __default__(self) -> AnnotationForm: ... + if sys.version_info >= (3, 11): + def __new__( + cls, + name: str, + *, + bound: AnnotationForm | None = None, + covariant: bool = False, + contravariant: bool = False, + infer_variance: bool = False, + default: AnnotationForm = ..., + ) -> Self: ... + else: + def __init__( + self, + name: str, + *, + bound: AnnotationForm | None = None, + covariant: bool = False, + contravariant: bool = False, + infer_variance: bool = False, + default: AnnotationForm = ..., + ) -> None: ... + + def __iter__(self) -> Any: ... # Unpack[Self] + def has_default(self) -> bool: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Never, /) -> Never: ... + + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + if sys.version_info >= (3, 14): + @property + def evaluate_default(self) -> EvaluateFunc | None: ... + +# TypeAliasType was added in Python 3.12, but had significant changes in 3.14. +if sys.version_info >= (3, 14): + from typing import TypeAliasType as TypeAliasType +else: + @final + class TypeAliasType: + def __init__( + self, name: str, value: AnnotationForm, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = () + ) -> None: ... + @property + def __value__(self) -> AnnotationForm: ... + @property + def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ... + @property + # `__parameters__` can include special forms if a `TypeVarTuple` was + # passed as a `type_params` element to the constructor method. + def __parameters__(self) -> tuple[TypeVar | ParamSpec | AnnotationForm, ...]: ... + @property + def __name__(self) -> str: ... + # It's writable on types, but not on instances of TypeAliasType. + @property + def __module__(self) -> str | None: ... # type: ignore[override] + # Returns typing._GenericAlias, which isn't stubbed. + def __getitem__(self, parameters: Incomplete | tuple[Incomplete, ...]) -> AnnotationForm: ... + def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> Never: ... + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + +# PEP 727 +class Doc: + documentation: str + def __init__(self, documentation: str, /) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +# PEP 728 +@type_check_only +class _NoExtraItemsType: ... + +NoExtraItems: _NoExtraItemsType + +# PEP 747 +if sys.version_info >= (3, 15): + from typing import TypeForm as TypeForm +else: + TypeForm: _SpecialForm + +# PEP 649/749 +if sys.version_info >= (3, 14): + from typing import evaluate_forward_ref as evaluate_forward_ref + + from annotationlib import Format as Format, get_annotations as get_annotations, type_repr as type_repr +else: + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Literal[Format.STRING], + ) -> dict[str, str]: ... + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Literal[Format.FORWARDREF], + ) -> dict[str, AnnotationForm | ForwardRef]: ... + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Format = Format.VALUE, # noqa: Y011 + ) -> dict[str, AnnotationForm]: ... + + @overload + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Literal[Format.STRING], + _recursive_guard: Container[str] = ..., + ) -> str: ... + @overload + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Literal[Format.FORWARDREF], + _recursive_guard: Container[str] = ..., + ) -> AnnotationForm | ForwardRef: ... + @overload + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Format | None = None, + _recursive_guard: Container[str] = ..., + ) -> AnnotationForm: ... + + def type_repr(value: object) -> str: ... + +# PEP 661 +if sys.version_info >= (3, 15): + from builtins import sentinel as sentinel +else: + class sentinel: + def __init__(self, name: str, /, *, repr: str | None = None) -> None: ... + __name__: str + __module__: str + if sys.version_info >= (3, 14): + # `other`` can be any type form legal for unions. + # `x | x` creates a `sentinel` instance if `x` is a sentinel, not a `UnionType` instance + def __or__(self, other: Any) -> UnionType | sentinel: ... + def __ror__(self, other: Any) -> UnionType | sentinel: ... + else: + # other can be any type form legal for unions + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + +Sentinel = sentinel diff --git a/stdlib/unicodedata.pyi b/stdlib/unicodedata.pyi index 66c93f7439f7..82a73181eed3 100644 --- a/stdlib/unicodedata.pyi +++ b/stdlib/unicodedata.pyi @@ -1,42 +1,94 @@ import sys -from typing import Any, TypeVar +from _typeshed import ReadOnlyBuffer +from collections.abc import Iterator +from typing import Final, Literal, TypeAlias, TypeVar, final, overload ucd_3_2_0: UCD -ucnhash_CAPI: Any -unidata_version: str +unidata_version: Final[str] _T = TypeVar("_T") -def bidirectional(__chr: str) -> str: ... -def category(__chr: str) -> str: ... -def combining(__chr: str) -> int: ... -def decimal(__chr: str, __default: _T = ...) -> int | _T: ... -def decomposition(__chr: str) -> str: ... -def digit(__chr: str, __default: _T = ...) -> int | _T: ... -def east_asian_width(__chr: str) -> str: ... +_NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] -if sys.version_info >= (3, 8): - def is_normalized(__form: str, __unistr: str) -> bool: ... +def bidirectional(chr: str, /) -> str: ... +def category(chr: str, /) -> str: ... +def combining(chr: str, /) -> int: ... -def lookup(__name: str | bytes) -> str: ... -def mirrored(__chr: str) -> int: ... -def name(__chr: str, __default: _T = ...) -> str | _T: ... -def normalize(__form: str, __unistr: str) -> str: ... -def numeric(__chr: str, __default: _T = ...) -> float | _T: ... +@overload +def decimal(chr: str, /) -> int: ... +@overload +def decimal(chr: str, default: _T, /) -> int | _T: ... -class UCD(object): +def decomposition(chr: str, /) -> str: ... + +@overload +def digit(chr: str, /) -> int: ... +@overload +def digit(chr: str, default: _T, /) -> int | _T: ... + +_EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] + +def east_asian_width(chr: str, /) -> _EastAsianWidth: ... +def is_normalized(form: _NormalizationForm, unistr: str, /) -> bool: ... + +if sys.version_info >= (3, 15): + def block(chr: str, /) -> str: ... + def extended_pictographic(chr: str, /) -> bool: ... + def grapheme_cluster_break(chr: str, /) -> str: ... + def indic_conjunct_break(chr: str, /) -> str: ... + def isxidstart(chr: str, /) -> bool: ... + def isxidcontinue(chr: str, /) -> bool: ... + def iter_graphemes(unistr: str, start: int = 0, end: int = sys.maxsize, /) -> Iterator[str]: ... + +def lookup(name: str | ReadOnlyBuffer, /) -> str: ... +def mirrored(chr: str, /) -> int: ... + +@overload +def name(chr: str, /) -> str: ... +@overload +def name(chr: str, default: _T, /) -> str | _T: ... + +def normalize(form: _NormalizationForm, unistr: str, /) -> str: ... + +@overload +def numeric(chr: str, /) -> float: ... +@overload +def numeric(chr: str, default: _T, /) -> float | _T: ... + +@final +class UCD: # The methods below are constructed from the same array in C - # (unicodedata_functions) and hence identical to the methods above. + # (unicodedata_functions) and hence identical to the functions above. unidata_version: str - def bidirectional(self, __chr: str) -> str: ... - def category(self, __chr: str) -> str: ... - def combining(self, __chr: str) -> int: ... - def decimal(self, __chr: str, __default: _T = ...) -> int | _T: ... - def decomposition(self, __chr: str) -> str: ... - def digit(self, __chr: str, __default: _T = ...) -> int | _T: ... - def east_asian_width(self, __chr: str) -> str: ... - def lookup(self, __name: str | bytes) -> str: ... - def mirrored(self, __chr: str) -> int: ... - def name(self, __chr: str, __default: _T = ...) -> str | _T: ... - def normalize(self, __form: str, __unistr: str) -> str: ... - def numeric(self, __chr: str, __default: _T = ...) -> float | _T: ... + def bidirectional(self, chr: str, /) -> str: ... + def category(self, chr: str, /) -> str: ... + def combining(self, chr: str, /) -> int: ... + + @overload + def decimal(self, chr: str, /) -> int: ... + @overload + def decimal(self, chr: str, default: _T, /) -> int | _T: ... + + def decomposition(self, chr: str, /) -> str: ... + + @overload + def digit(self, chr: str, /) -> int: ... + @overload + def digit(self, chr: str, default: _T, /) -> int | _T: ... + + def east_asian_width(self, chr: str, /) -> _EastAsianWidth: ... + def is_normalized(self, form: _NormalizationForm, unistr: str, /) -> bool: ... + def lookup(self, name: str | ReadOnlyBuffer, /) -> str: ... + def mirrored(self, chr: str, /) -> int: ... + + @overload + def name(self, chr: str, /) -> str: ... + @overload + def name(self, chr: str, default: _T, /) -> str | _T: ... + + def normalize(self, form: _NormalizationForm, unistr: str, /) -> str: ... + + @overload + def numeric(self, chr: str, /) -> float: ... + @overload + def numeric(self, chr: str, default: _T, /) -> float | _T: ... diff --git a/stdlib/unittest/__init__.pyi b/stdlib/unittest/__init__.pyi index d3b0efaa83ff..546ea77bb4ca 100644 --- a/stdlib/unittest/__init__.pyi +++ b/stdlib/unittest/__init__.pyi @@ -5,18 +5,13 @@ from .case import ( FunctionTestCase as FunctionTestCase, SkipTest as SkipTest, TestCase as TestCase, + addModuleCleanup as addModuleCleanup, expectedFailure as expectedFailure, skip as skip, skipIf as skipIf, skipUnless as skipUnless, ) -from .loader import ( - TestLoader as TestLoader, - defaultTestLoader as defaultTestLoader, - findTestCases as findTestCases, - getTestCaseNames as getTestCaseNames, - makeSuite as makeSuite, -) +from .loader import TestLoader as TestLoader, defaultTestLoader as defaultTestLoader from .main import TestProgram as TestProgram, main as main from .result import TestResult as TestResult from .runner import TextTestResult as TextTestResult, TextTestRunner as TextTestRunner @@ -28,7 +23,41 @@ from .signals import ( ) from .suite import BaseTestSuite as BaseTestSuite, TestSuite as TestSuite -if sys.version_info >= (3, 8): - from .case import addModuleCleanup as addModuleCleanup +if sys.version_info >= (3, 11): + from .case import doModuleCleanups as doModuleCleanups, enterModuleContext as enterModuleContext + +__all__ = [ + "IsolatedAsyncioTestCase", + "TestResult", + "TestCase", + "TestSuite", + "TextTestRunner", + "TestLoader", + "FunctionTestCase", + "main", + "defaultTestLoader", + "SkipTest", + "skip", + "skipIf", + "skipUnless", + "expectedFailure", + "TextTestResult", + "installHandler", + "registerResult", + "removeResult", + "removeHandler", + "addModuleCleanup", +] + +if sys.version_info < (3, 13): + from .loader import findTestCases as findTestCases, getTestCaseNames as getTestCaseNames, makeSuite as makeSuite + + __all__ += ["getTestCaseNames", "makeSuite", "findTestCases"] + +if sys.version_info >= (3, 11): + __all__ += ["enterModuleContext", "doModuleCleanups"] + +if sys.version_info < (3, 12): + def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... -def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... +def __dir__() -> set[str]: ... diff --git a/stdlib/unittest/_log.pyi b/stdlib/unittest/_log.pyi index f9e406199cd4..da6ce5a5ac7a 100644 --- a/stdlib/unittest/_log.pyi +++ b/stdlib/unittest/_log.pyi @@ -1,8 +1,8 @@ import logging import sys from types import TracebackType -from typing import ClassVar, Generic, NamedTuple, Type, TypeVar -from unittest.case import TestCase +from typing import ClassVar, Generic, NamedTuple, TypeVar +from unittest.case import TestCase, _BaseTestCaseContext _L = TypeVar("_L", None, _LoggingWatcher) @@ -10,18 +10,20 @@ class _LoggingWatcher(NamedTuple): records: list[logging.LogRecord] output: list[str] -class _AssertLogsContext(Generic[_L]): +class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): LOGGING_FORMAT: ClassVar[str] - test_case: TestCase logger_name: str level: int msg: None - if sys.version_info >= (3, 10): - def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ... - no_logs: bool + no_logs: bool + if sys.version_info >= (3, 15): + def __init__( + self, test_case: TestCase, logger_name: str, level: int, no_logs: bool, formatter: logging.Formatter | None = None + ) -> None: ... else: - def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... + def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ... + def __enter__(self) -> _L: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool | None: ... diff --git a/stdlib/unittest/async_case.pyi b/stdlib/unittest/async_case.pyi index bdf534b37c9f..77627a85ef19 100644 --- a/stdlib/unittest/async_case.pyi +++ b/stdlib/unittest/async_case.pyi @@ -1,10 +1,24 @@ import sys -from typing import Any, Awaitable, Callable +from asyncio.events import AbstractEventLoop +from collections.abc import Awaitable, Callable +from typing import ParamSpec, TypeVar from .case import TestCase -if sys.version_info >= (3, 8): - class IsolatedAsyncioTestCase(TestCase): - async def asyncSetUp(self) -> None: ... - async def asyncTearDown(self) -> None: ... - def addAsyncCleanup(self, __func: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> None: ... +if sys.version_info >= (3, 11): + from contextlib import AbstractAsyncContextManager + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +class IsolatedAsyncioTestCase(TestCase): + if sys.version_info >= (3, 13): + loop_factory: Callable[[], AbstractEventLoop] | None = None + + async def asyncSetUp(self) -> None: ... + async def asyncTearDown(self) -> None: ... + def addAsyncCleanup(self, func: Callable[_P, Awaitable[object]], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + if sys.version_info >= (3, 11): + async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... + + def __del__(self) -> None: ... diff --git a/stdlib/unittest/case.pyi b/stdlib/unittest/case.pyi index 602a5020b9d4..1d1206b7fc36 100644 --- a/stdlib/unittest/case.pyi +++ b/stdlib/unittest/case.pyi @@ -1,67 +1,64 @@ -import datetime import logging import sys import unittest.result -from _typeshed import Self -from collections.abc import Set # equivalent to typing.AbstractSet, not builtins.set +from _typeshed import SupportsDunderGE, SupportsDunderGT, SupportsDunderLE, SupportsDunderLT, SupportsRSub, SupportsSub +from builtins import _ClassInfo +from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet from contextlib import AbstractContextManager -from types import TracebackType +from re import Pattern +from types import GenericAlias, TracebackType from typing import ( Any, AnyStr, - Callable, - ClassVar, - Container, + Final, Generic, - Iterable, - Mapping, - NamedTuple, - NoReturn, - Pattern, - Sequence, - Tuple, - Type, + ParamSpec, + Protocol, + SupportsAbs, + SupportsRound, TypeVar, overload, + type_check_only, ) +from typing_extensions import Never, Self +from unittest._log import _AssertLogsContext, _LoggingWatcher from warnings import WarningMessage -if sys.version_info >= (3, 9): - from types import GenericAlias - +_T = TypeVar("_T") +_S = TypeVar("_S", bound=SupportsSub[Any, Any]) _E = TypeVar("_E", bound=BaseException) _FT = TypeVar("_FT", bound=Callable[..., Any]) +_SB = TypeVar("_SB", str, bytes, bytearray) +_P = ParamSpec("_P") -DIFF_OMITTED: str +DIFF_OMITTED: Final[str] class _BaseTestCaseContext: + test_case: TestCase def __init__(self, test_case: TestCase) -> None: ... -if sys.version_info >= (3, 9): - from unittest._log import _AssertLogsContext, _LoggingWatcher -else: - # Unused dummy for _AssertLogsContext. Starting with Python 3.10, - # this is generic over the logging watcher, but in lower versions - # the watcher is hard-coded. - _L = TypeVar("_L") - class _LoggingWatcher(NamedTuple): - records: list[logging.LogRecord] - output: list[str] - class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): - LOGGING_FORMAT: ClassVar[str] - test_case: TestCase - logger_name: str - level: int - msg: None - def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... - def __enter__(self) -> _LoggingWatcher: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - -if sys.version_info >= (3, 8): - def addModuleCleanup(__function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - def doModuleCleanups() -> None: ... +class _AssertRaisesBaseContext(_BaseTestCaseContext): + expected: type[BaseException] | tuple[type[BaseException], ...] + expected_regex: Pattern[str] | None + obj_name: str | None + msg: str | None + + def __init__( + self, + expected: type[BaseException] | tuple[type[BaseException], ...], + test_case: TestCase, + expected_regex: str | Pattern[str] | None = None, + ) -> None: ... + + # This returns Self if args is the empty list, and None otherwise. + # but it's not possible to construct an overload which expresses that + def handle(self, name: str, args: list[Any], kwargs: dict[str, Any]) -> Any: ... + +def addModuleCleanup(function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... +def doModuleCleanups() -> None: ... + +if sys.version_info >= (3, 11): + def enterModuleContext(cm: AbstractContextManager[_T]) -> _T: ... def expectedFailure(test_item: _FT) -> _FT: ... def skip(reason: str) -> Callable[[_FT], _FT]: ... @@ -69,230 +66,287 @@ def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... class SkipTest(Exception): - def __init__(self, reason: str) -> None: ... + def __init__(self, reason: str, /) -> None: ... + +@type_check_only +class _SupportsAbsAndDunderGE(SupportsDunderGE[Any], SupportsAbs[Any], Protocol): ... class TestCase: - failureException: Type[BaseException] + failureException: type[BaseException] longMessage: bool maxDiff: int | None # undocumented _testMethodName: str # undocumented _testMethodDoc: str - def __init__(self, methodName: str = ...) -> None: ... + def __init__(self, methodName: str = "runTest") -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... def setUp(self) -> None: ... def tearDown(self) -> None: ... @classmethod def setUpClass(cls) -> None: ... @classmethod def tearDownClass(cls) -> None: ... - def run(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ... + def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None: ... def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ... - def skipTest(self, reason: Any) -> None: ... + def skipTest(self, reason: Any) -> Never: ... def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ... def debug(self) -> None: ... - def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... - def assertEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertNotEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertTrue(self, expr: Any, msg: Any = ...) -> None: ... - def assertFalse(self, expr: Any, msg: Any = ...) -> None: ... - def assertIs(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... - def assertIsNot(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... - def assertIsNone(self, obj: Any, msg: Any = ...) -> None: ... - def assertIsNotNone(self, obj: Any, msg: Any = ...) -> None: ... - def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = ...) -> None: ... - def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = ...) -> None: ... - def assertIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: Any = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: Any = ...) -> None: ... - def assertGreater(self, a: Any, b: Any, msg: Any = ...) -> None: ... - def assertGreaterEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... - def assertLess(self, a: Any, b: Any, msg: Any = ...) -> None: ... - def assertLessEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... + if sys.version_info < (3, 11): + def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... + + def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None: ... + def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None: ... + def assertTrue(self, expr: Any, msg: Any = None) -> None: ... + def assertFalse(self, expr: Any, msg: Any = None) -> None: ... + def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None: ... + def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None: ... + def assertIsNone(self, obj: object, msg: Any = None) -> None: ... + def assertIsNotNone(self, obj: object, msg: Any = None) -> None: ... + def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ... + def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ... + def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ... + def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ... + + @overload + def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ... + + @overload + def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ... + @overload - def assertRaises( # type: ignore[misc] + def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ... + + @overload + def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ... + + # `assertRaises`, `assertRaisesRegex`, and `assertRaisesRegexp` + # are not using `ParamSpec` intentionally, + # because they might be used with explicitly wrong arg types to raise some error in tests. + @overload + def assertRaises( self, - expected_exception: Type[BaseException] | Tuple[Type[BaseException], ...], - callable: Callable[..., Any], + expected_exception: type[BaseException] | tuple[type[BaseException], ...], + callable: Callable[..., object], *args: Any, **kwargs: Any, ) -> None: ... @overload - def assertRaises(self, expected_exception: Type[_E] | Tuple[Type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def assertRaises( + self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ... + ) -> _AssertRaisesContext[_E]: ... + @overload - def assertRaisesRegex( # type: ignore[misc] + def assertRaisesRegex( self, - expected_exception: Type[BaseException] | Tuple[Type[BaseException], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], + expected_exception: type[BaseException] | tuple[type[BaseException], ...], + expected_regex: str | Pattern[str], + callable: Callable[..., object], *args: Any, **kwargs: Any, ) -> None: ... @overload def assertRaisesRegex( - self, - expected_exception: Type[_E] | Tuple[Type[_E], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - msg: Any = ..., + self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ... ) -> _AssertRaisesContext[_E]: ... + @overload - def assertWarns( # type: ignore[misc] - self, expected_warning: Type[Warning] | Tuple[Type[Warning], ...], callable: Callable[..., Any], *args: Any, **kwargs: Any + def assertWarns( + self, + expected_warning: type[Warning] | tuple[type[Warning], ...], + callable: Callable[_P, object], + *args: _P.args, + **kwargs: _P.kwargs, ) -> None: ... @overload - def assertWarns(self, expected_warning: Type[Warning] | Tuple[Type[Warning], ...], msg: Any = ...) -> _AssertWarnsContext: ... + def assertWarns( + self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ... + ) -> _AssertWarnsContext: ... + @overload - def assertWarnsRegex( # type: ignore[misc] + def assertWarnsRegex( self, - expected_warning: Type[Warning] | Tuple[Type[Warning], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], - *args: Any, - **kwargs: Any, + expected_warning: type[Warning] | tuple[type[Warning], ...], + expected_regex: str | Pattern[str], + callable: Callable[_P, object], + *args: _P.args, + **kwargs: _P.kwargs, ) -> None: ... @overload def assertWarnsRegex( - self, - expected_warning: Type[Warning] | Tuple[Type[Warning], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - msg: Any = ..., + self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ... ) -> _AssertWarnsContext: ... - def assertLogs( - self, logger: str | logging.Logger | None = ..., level: int | str | None = ... - ) -> _AssertLogsContext[_LoggingWatcher]: ... - if sys.version_info >= (3, 10): - def assertNoLogs( - self, logger: str | logging.Logger | None = ..., level: int | str | None = ... - ) -> _AssertLogsContext[None]: ... + + if sys.version_info >= (3, 15): + def assertLogs( + self, + logger: str | logging.Logger | None = None, + level: int | str | None = None, + formatter: logging.Formatter | None = None, + ) -> _AssertLogsContext[_LoggingWatcher]: ... + else: + def assertLogs( + self, logger: str | logging.Logger | None = None, level: int | str | None = None + ) -> _AssertLogsContext[_LoggingWatcher]: ... + + def assertNoLogs( + self, logger: str | logging.Logger | None = None, level: int | str | None = None + ) -> _AssertLogsContext[None]: ... + + @overload + def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... + @overload + def assertAlmostEqual( + self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE + ) -> None: ... @overload def assertAlmostEqual( - self, first: float, second: float, places: int | None = ..., msg: Any = ..., delta: float | None = ... + self, + first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]], + second: _T, + places: int | None = None, + msg: Any = None, + delta: None = None, ) -> None: ... @overload def assertAlmostEqual( self, - first: datetime.datetime, - second: datetime.datetime, - places: int | None = ..., - msg: Any = ..., - delta: datetime.timedelta | None = ..., + first: _T, + second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]], + places: int | None = None, + msg: Any = None, + delta: None = None, ) -> None: ... + @overload - def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ...) -> None: ... + def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, places: int | None = ..., msg: Any = ...) -> None: ... + def assertNotAlmostEqual( + self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE + ) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float | None = ...) -> None: ... + def assertNotAlmostEqual( + self, + first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]], + second: _T, + places: int | None = None, + msg: Any = None, + delta: None = None, + ) -> None: ... @overload def assertNotAlmostEqual( self, - first: datetime.datetime, - second: datetime.datetime, - places: int | None = ..., - msg: Any = ..., - delta: datetime.timedelta | None = ..., + first: _T, + second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]], + places: int | None = None, + msg: Any = None, + delta: None = None, ) -> None: ... - def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... - def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... - def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = ...) -> None: ... - def addTypeEqualityFunc(self, typeobj: Type[Any], function: Callable[..., None]) -> None: ... - def assertMultiLineEqual(self, first: str, second: str, msg: Any = ...) -> None: ... + + def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ... + def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ... + def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: ... + def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None: ... def assertSequenceEqual( - self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = ..., seq_type: Type[Sequence[Any]] | None = ... + self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None ) -> None: ... - def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = ...) -> None: ... - def assertTupleEqual(self, tuple1: Tuple[Any, ...], tuple2: Tuple[Any, ...], msg: Any = ...) -> None: ... - def assertSetEqual(self, set1: Set[object], set2: Set[object], msg: Any = ...) -> None: ... - def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = ...) -> None: ... - def fail(self, msg: Any = ...) -> NoReturn: ... + def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None: ... + def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None: ... + def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None: ... + # assertDictEqual accepts only true dict instances. We can't use that here, since that would make + # assertDictEqual incompatible with TypedDict. + def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None: ... + def fail(self, msg: Any = None) -> Never: ... def countTestCases(self) -> int: ... def defaultTestResult(self) -> unittest.result.TestResult: ... def id(self) -> str: ... def shortDescription(self) -> str | None: ... - if sys.version_info >= (3, 8): - def addCleanup(self, __function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - else: - def addCleanup(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + + if sys.version_info >= (3, 11): + def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ... + def doCleanups(self) -> None: ... - if sys.version_info >= (3, 8): - @classmethod - def addClassCleanup(cls, __function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @classmethod + def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + @classmethod + def doClassCleanups(cls) -> None: ... + + if sys.version_info >= (3, 11): @classmethod - def doClassCleanups(cls) -> None: ... + def enterClassContext(cls, cm: AbstractContextManager[_T]) -> _T: ... + def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented - if sys.version_info < (3, 11): - def failUnlessEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def failIfEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertNotEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def failUnless(self, expr: bool, msg: Any = ...) -> None: ... - def assert_(self, expr: bool, msg: Any = ...) -> None: ... - def failIf(self, expr: bool, msg: Any = ...) -> None: ... - @overload - def failUnlessRaises( # type: ignore[misc] - self, - exception: Type[BaseException] | Tuple[Type[BaseException], ...], - callable: Callable[..., Any] = ..., - *args: Any, - **kwargs: Any, - ) -> None: ... - @overload - def failUnlessRaises(self, exception: Type[_E] | Tuple[Type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... - def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - def assertAlmostEquals( - self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... - ) -> None: ... - def failIfAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - def assertNotAlmostEquals( - self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... - ) -> None: ... - def assertRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... - def assertNotRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... - @overload - def assertRaisesRegexp( # type: ignore[misc] - self, - exception: Type[BaseException] | Tuple[Type[BaseException], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], - *args: Any, - **kwargs: Any, - ) -> None: ... - @overload - def assertRaisesRegexp( - self, - exception: Type[_E] | Tuple[Type[_E], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - msg: Any = ..., - ) -> _AssertRaisesContext[_E]: ... + if sys.version_info < (3, 12): + failUnlessEqual = assertEqual + assertEquals = assertEqual + failIfEqual = assertNotEqual + assertNotEquals = assertNotEqual + failUnless = assertTrue + assert_ = assertTrue + failIf = assertFalse + failUnlessRaises = assertRaises + failUnlessAlmostEqual = assertAlmostEqual + assertAlmostEquals = assertAlmostEqual + failIfAlmostEqual = assertNotAlmostEqual + assertNotAlmostEquals = assertNotAlmostEqual + assertRegexpMatches = assertRegex + assertNotRegexpMatches = assertNotRegex + assertRaisesRegexp = assertRaisesRegex def assertDictContainsSubset( - self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = ... + self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None ) -> None: ... + # Runtime has *args, **kwargs, but will error if any are supplied + def __init_subclass__(cls, *args: Never, **kwargs: Never) -> None: ... + + if sys.version_info >= (3, 14): + def assertIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ... + def assertNotIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ... + def assertHasAttr(self, obj: object, name: str, msg: Any = None) -> None: ... + def assertNotHasAttr(self, obj: object, name: str, msg: Any = None) -> None: ... + def assertStartsWith(self, s: _SB, prefix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + def assertNotStartsWith(self, s: _SB, prefix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + def assertEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + def assertNotEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + class FunctionTestCase(TestCase): def __init__( self, - testFunc: Callable[[], None], - setUp: Callable[[], None] | None = ..., - tearDown: Callable[[], None] | None = ..., - description: str | None = ..., + testFunc: Callable[[], object], + setUp: Callable[[], object] | None = None, + tearDown: Callable[[], object] | None = None, + description: str | None = None, ) -> None: ... def runTest(self) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... -class _AssertRaisesContext(Generic[_E]): +class _AssertRaisesContext(_AssertRaisesBaseContext, Generic[_E]): exception: _E - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class _AssertWarnsContext: +class _AssertWarnsContext(_AssertRaisesBaseContext): warning: WarningMessage filename: str lineno: int warnings: list[WarningMessage] - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> None: ... diff --git a/stdlib/unittest/loader.pyi b/stdlib/unittest/loader.pyi index 394e9c9166eb..106004fadcc2 100644 --- a/stdlib/unittest/loader.pyi +++ b/stdlib/unittest/loader.pyi @@ -1,52 +1,55 @@ import sys import unittest.case -import unittest.result import unittest.suite +from collections.abc import Callable, Sequence +from re import Pattern from types import ModuleType -from typing import Any, Callable, List, Pattern, Sequence, Type +from typing import Any, Final, TypeAlias +from typing_extensions import deprecated -_SortComparisonMethod = Callable[[str, str], int] -_SuiteClass = Callable[[List[unittest.case.TestCase]], unittest.suite.TestSuite] +_SortComparisonMethod: TypeAlias = Callable[[str, str], int] +_SuiteClass: TypeAlias = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] -VALID_MODULE_NAME: Pattern[str] +VALID_MODULE_NAME: Final[Pattern[str]] class TestLoader: - errors: list[Type[BaseException]] + errors: list[type[BaseException]] testMethodPrefix: str sortTestMethodsUsing: _SortComparisonMethod - - if sys.version_info >= (3, 7): - testNamePatterns: list[str] | None - + testNamePatterns: list[str] | None suiteClass: _SuiteClass - def loadTestsFromTestCase(self, testCaseClass: Type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... - def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: Any = ...) -> unittest.suite.TestSuite: ... - def loadTestsFromName(self, name: str, module: ModuleType | None = ...) -> unittest.suite.TestSuite: ... - def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = ...) -> unittest.suite.TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[unittest.case.TestCase]) -> Sequence[str]: ... - def discover(self, start_dir: str, pattern: str = ..., top_level_dir: str | None = ...) -> unittest.suite.TestSuite: ... + def loadTestsFromTestCase(self, testCaseClass: type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... + if sys.version_info >= (3, 12): + def loadTestsFromModule(self, module: ModuleType, *, pattern: str | None = None) -> unittest.suite.TestSuite: ... + else: + def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: str | None = None) -> unittest.suite.TestSuite: ... + + def loadTestsFromName(self, name: str, module: ModuleType | None = None) -> unittest.suite.TestSuite: ... + def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = None) -> unittest.suite.TestSuite: ... + def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: ... + def discover( + self, start_dir: str, pattern: str = "test*.py", top_level_dir: str | None = None + ) -> unittest.suite.TestSuite: ... + def _match_path(self, path: str, full_path: str, pattern: str) -> bool: ... defaultTestLoader: TestLoader -if sys.version_info >= (3, 7): +if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13.") def getTestCaseNames( - testCaseClass: Type[unittest.case.TestCase], + testCaseClass: type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ..., - testNamePatterns: list[str] | None = ..., + testNamePatterns: list[str] | None = None, ) -> Sequence[str]: ... - -else: - def getTestCaseNames( - testCaseClass: Type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ... - ) -> Sequence[str]: ... - -def makeSuite( - testCaseClass: Type[unittest.case.TestCase], - prefix: str = ..., - sortUsing: _SortComparisonMethod = ..., - suiteClass: _SuiteClass = ..., -) -> unittest.suite.TestSuite: ... -def findTestCases( - module: ModuleType, prefix: str = ..., sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... -) -> unittest.suite.TestSuite: ... + @deprecated("Deprecated; removed in Python 3.13.") + def makeSuite( + testCaseClass: type[unittest.case.TestCase], + prefix: str = "test", + sortUsing: _SortComparisonMethod = ..., + suiteClass: _SuiteClass = ..., + ) -> unittest.suite.TestSuite: ... + @deprecated("Deprecated; removed in Python 3.13.") + def findTestCases( + module: ModuleType, prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... + ) -> unittest.suite.TestSuite: ... diff --git a/stdlib/unittest/main.pyi b/stdlib/unittest/main.pyi index 6d1117ecaf79..87200bd02b05 100644 --- a/stdlib/unittest/main.pyi +++ b/stdlib/unittest/main.pyi @@ -3,50 +3,72 @@ import unittest.case import unittest.loader import unittest.result import unittest.suite +from collections.abc import Iterable from types import ModuleType -from typing import Any, Iterable, Protocol, Type +from typing import Any, Final, Protocol, type_check_only +from typing_extensions import deprecated -MAIN_EXAMPLES: str -MODULE_EXAMPLES: str +MAIN_EXAMPLES: Final[str] +MODULE_EXAMPLES: Final[str] +@type_check_only class _TestRunner(Protocol): - def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> unittest.result.TestResult: ... + def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase, /) -> unittest.result.TestResult: ... # not really documented class TestProgram: result: unittest.result.TestResult - module: None | str | ModuleType + module: ModuleType | None verbosity: int failfast: bool | None catchbreak: bool | None buffer: bool | None progName: str | None warnings: str | None + testNamePatterns: list[str] | None + if sys.version_info >= (3, 12): + durations: unittest.result._DurationsType | None + def __init__( + self, + module: ModuleType | str | None = "__main__", + defaultTest: str | Iterable[str] | None = None, + argv: list[str] | None = None, + testRunner: type[_TestRunner] | _TestRunner | None = None, + testLoader: unittest.loader.TestLoader = ..., + exit: bool = True, + verbosity: int = 1, + failfast: bool | None = None, + catchbreak: bool | None = None, + buffer: bool | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + durations: unittest.result._DurationsType | None = None, + ) -> None: ... + else: + def __init__( + self, + module: str | ModuleType | None = "__main__", + defaultTest: str | Iterable[str] | None = None, + argv: list[str] | None = None, + testRunner: type[_TestRunner] | _TestRunner | None = None, + testLoader: unittest.loader.TestLoader = ..., + exit: bool = True, + verbosity: int = 1, + failfast: bool | None = None, + catchbreak: bool | None = None, + buffer: bool | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + ) -> None: ... + + if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13.") + def usageExit(self, msg: Any = None) -> None: ... - if sys.version_info >= (3, 7): - testNamePatterns: list[str] | None - def __init__( - self, - module: None | str | ModuleType = ..., - defaultTest: str | Iterable[str] | None = ..., - argv: list[str] | None = ..., - testRunner: Type[_TestRunner] | _TestRunner | None = ..., - testLoader: unittest.loader.TestLoader = ..., - exit: bool = ..., - verbosity: int = ..., - failfast: bool | None = ..., - catchbreak: bool | None = ..., - buffer: bool | None = ..., - warnings: str | None = ..., - *, - tb_locals: bool = ..., - ) -> None: ... - def usageExit(self, msg: Any = ...) -> None: ... def parseArgs(self, argv: list[str]) -> None: ... - if sys.version_info >= (3, 7): - def createTests(self, from_discovery: bool = ..., Loader: unittest.loader.TestLoader | None = ...) -> None: ... - else: - def createTests(self) -> None: ... + def createTests(self, from_discovery: bool = False, Loader: unittest.loader.TestLoader | None = None) -> None: ... def runTests(self) -> None: ... # undocumented main = TestProgram diff --git a/stdlib/unittest/mock.pyi b/stdlib/unittest/mock.pyi index a84ab67b49f8..de88e30f0fe3 100644 --- a/stdlib/unittest/mock.pyi +++ b/stdlib/unittest/mock.pyi @@ -1,11 +1,20 @@ import sys -from typing import Any, Awaitable, Callable, Generic, Iterable, List, Mapping, Sequence, Tuple, Type, TypeVar, overload +from _typeshed import MaybeNone +from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence +from contextlib import _GeneratorContextManager +from types import TracebackType +from typing import Any, ClassVar, Final, Generic, Literal, ParamSpec, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, disjoint_base _T = TypeVar("_T") -_TT = TypeVar("_TT", bound=Type[Any]) +_TT = TypeVar("_TT", bound=type[Any]) _R = TypeVar("_R") +_F = TypeVar("_F", bound=Callable[..., Any]) +_AF = TypeVar("_AF", bound=Callable[..., Coroutine[Any, Any, Any]]) +_P = ParamSpec("_P") -if sys.version_info >= (3, 8): +if sys.version_info >= (3, 13): + # ThreadingMock added in 3.13 __all__ = ( "Mock", "MagicMock", @@ -15,6 +24,7 @@ if sys.version_info >= (3, 8): "ANY", "call", "create_autospec", + "ThreadingMock", "AsyncMock", "FILTER_DIR", "NonCallableMock", @@ -23,23 +33,6 @@ if sys.version_info >= (3, 8): "PropertyMock", "seal", ) -elif sys.version_info >= (3, 7): - __all__ = ( - "Mock", - "MagicMock", - "patch", - "sentinel", - "DEFAULT", - "ANY", - "call", - "create_autospec", - "FILTER_DIR", - "NonCallableMock", - "NonCallableMagicMock", - "mock_open", - "PropertyMock", - "seal", - ) else: __all__ = ( "Mock", @@ -50,134 +43,189 @@ else: "ANY", "call", "create_autospec", + "AsyncMock", "FILTER_DIR", "NonCallableMock", "NonCallableMagicMock", "mock_open", "PropertyMock", + "seal", ) -__version__: str - -FILTER_DIR: Any -class _slotted: ... +FILTER_DIR: bool # controls the way mock objects respond to `dir` function class _SentinelObject: name: Any def __init__(self, name: Any) -> None: ... class _Sentinel: - def __init__(self) -> None: ... def __getattr__(self, name: str) -> Any: ... -sentinel: Any +sentinel: _Sentinel DEFAULT: Any -class _Call(tuple[Any, ...]): - def __new__( - cls, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... - ) -> Any: ... - name: Any - parent: Any - from_kall: Any - def __init__( - self, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... - ) -> None: ... - def __eq__(self, other: Any) -> bool: ... - __ne__: Any - def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... - def __getattr__(self, attr: Any) -> Any: ... - if sys.version_info >= (3, 8): +_ArgsKwargs: TypeAlias = tuple[tuple[Any, ...], Mapping[str, Any]] +_NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]] +_CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs + +if sys.version_info >= (3, 12): + class _Call(tuple[Any, ...]): + def __new__( + cls, + value: _CallValue = (), + name: str | None = "", + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> Self: ... + def __init__( + self, + value: _CallValue = (), + name: str | None = None, + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: str) -> Any: ... + def __getattribute__(self, attr: str) -> Any: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> Mapping[str, Any]: ... + def call_list(self) -> Any: ... + +else: + @disjoint_base + class _Call(tuple[Any, ...]): + def __new__( + cls, + value: _CallValue = (), + name: str | None = "", + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> Self: ... + def __init__( + self, + value: _CallValue = (), + name: str | None = None, + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: str) -> Any: ... + def __getattribute__(self, attr: str) -> Any: ... @property - def args(self): ... + def args(self) -> tuple[Any, ...]: ... @property - def kwargs(self): ... - def call_list(self) -> Any: ... + def kwargs(self) -> Mapping[str, Any]: ... + def call_list(self) -> Any: ... call: _Call -class _CallList(List[_Call]): +class _CallList(list[_Call]): def __contains__(self, value: Any) -> bool: ... class Base: def __init__(self, *args: Any, **kwargs: Any) -> None: ... +# We subclass with "Any" because mocks are explicitly designed to stand in for other types, +# something that can't be expressed with our static type system. class NonCallableMock(Base, Any): - def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... + if sys.version_info >= (3, 12): + def __new__( + cls, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state: Any | None = None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> Self: ... + else: + def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... + def __init__( self, - spec: list[str] | object | Type[object] | None = ..., - wraps: Any | None = ..., - name: str | None = ..., - spec_set: list[str] | object | Type[object] | None = ..., - parent: NonCallableMock | None = ..., - _spec_state: Any | None = ..., - _new_name: str = ..., - _new_parent: NonCallableMock | None = ..., - _spec_as_instance: bool = ..., - _eat_self: bool | None = ..., - unsafe: bool = ..., + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state: Any | None = None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, **kwargs: Any, ) -> None: ... def __getattr__(self, name: str) -> Any: ... - if sys.version_info >= (3, 8): - def _calls_repr(self, prefix: str = ...) -> str: ... - def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_not_called(self) -> None: ... - def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... - def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = ...) -> str: ... - else: - def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... - def assert_not_called(_mock_self) -> None: ... - def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... - def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ... - if sys.version_info >= (3, 8): - def assert_called(self) -> None: ... - def assert_called_once(self) -> None: ... - else: - def assert_called(_mock_self) -> None: ... - def assert_called_once(_mock_self) -> None: ... - def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... - if sys.version_info >= (3, 7): - def _extract_mock_name(self) -> str: ... - def _get_call_signature_from_name(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __dir__(self) -> list[str]: ... + def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(self) -> None: ... + def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... + def assert_called(self) -> None: ... + def assert_called_once(self) -> None: ... + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + def _extract_mock_name(self) -> str: ... + def _get_call_signature_from_name(self, name: str) -> Any: ... def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... - def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ... - def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... - def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = False) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = False, _eat_self: bool = False) -> None: ... def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... def configure_mock(self, **kwargs: Any) -> None: ... return_value: Any side_effect: Any called: bool call_count: int - call_args: Any + call_args: _Call | MaybeNone call_args_list: _CallList + method_calls: _CallList mock_calls: _CallList def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... - def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ... + def _call_matcher(self, _call: tuple[_Call, ...]) -> _Call: ... def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... + if sys.version_info >= (3, 13): + def _calls_repr(self) -> str: ... + else: + def _calls_repr(self, prefix: str = "Calls") -> str: ... class CallableMixin(Base): side_effect: Any def __init__( self, - spec: Any | None = ..., - side_effect: Any | None = ..., + spec: Any | None = None, + side_effect: Any | None = None, return_value: Any = ..., - wraps: Any | None = ..., - name: Any | None = ..., - spec_set: Any | None = ..., - parent: Any | None = ..., - _spec_state: Any | None = ..., - _new_name: Any = ..., - _new_parent: Any | None = ..., + wraps: Any | None = None, + name: Any | None = None, + spec_set: Any | None = None, + parent: Any | None = None, + _spec_state: Any | None = None, + _new_name: Any = "", + _new_parent: Any | None = None, **kwargs: Any, ) -> None: ... - if sys.version_info >= (3, 8): - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - else: - def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class Mock(CallableMixin, NonCallableMock): ... @@ -196,235 +244,277 @@ class _patch(Generic[_T]): additional_patchers: Any # If new==DEFAULT, self is _patch[Any]. Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], # but that's impossible with the current type system. - if sys.version_info >= (3, 10): - def __init__( - self: _patch[_T], - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Any | None, - create: bool, - spec_set: Any | None, - autospec: Any | None, - new_callable: Any | None, - kwargs: Mapping[str, Any], - *, - unsafe: bool = ..., - ) -> None: ... - else: - def __init__( - self: _patch[_T], - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Any | None, - create: bool, - spec_set: Any | None, - autospec: Any | None, - new_callable: Any | None, - kwargs: Mapping[str, Any], - ) -> None: ... + def __init__( + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Any | None, + create: bool, + spec_set: Any | None, + autospec: Any | None, + new_callable: Any | None, + kwargs: Mapping[str, Any], + *, + unsafe: bool = False, + ) -> None: ... def copy(self) -> _patch[_T]: ... + @overload def __call__(self, func: _TT) -> _TT: ... + # If new==DEFAULT, this should add a MagicMock parameter to the function + # arguments. See the _patch_default_new class below for this functionality. @overload - def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... - if sys.version_info >= (3, 8): - def decoration_helper(self, patched, args, keywargs): ... + def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ... + + def decoration_helper( + self, patched: _patch[Any], args: Sequence[Any], keywargs: Any + ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ... def decorate_class(self, klass: _TT) -> _TT: ... def decorate_callable(self, func: Callable[..., _R]) -> Callable[..., _R]: ... - if sys.version_info >= (3, 8): - def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... + def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... def get_original(self) -> tuple[Any, bool]: ... target: Any temp_original: Any is_local: bool def __enter__(self) -> _T: ... - def __exit__(self, *exc_info: Any) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... def start(self) -> _T: ... def stop(self) -> None: ... +# This class does not exist at runtime, it's a hack to make this work: +# @patch("foo") +# def bar(..., mock: MagicMock) -> None: ... +@type_check_only +class _patch_pass_arg(_patch[_T]): + @overload + def __call__(self, func: _TT) -> _TT: ... + # Can't use the following as ParamSpec is only allowed as last parameter: + # def __call__(self, func: Callable[_P, _R]) -> Callable[Concatenate[_P, MagicMock], _R]: ... + @overload + def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + class _patch_dict: in_dict: Any values: Any clear: Any - def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ... - def __call__(self, f: Any) -> Any: ... - def decorate_class(self, klass: Any) -> Any: ... + def __init__(self, in_dict: Any, values: Any = (), clear: Any = False, **kwargs: Any) -> None: ... + def __call__(self, f: _F) -> _F: ... def __enter__(self) -> Any: ... - def __exit__(self, *args: Any) -> Any: ... + def __exit__(self, *args: object) -> Any: ... + def decorate_callable(self, f: _F) -> _F: ... + def decorate_async_callable(self, f: _AF) -> _AF: ... + def decorate_class(self, klass: Any) -> Any: ... start: Any stop: Any +# This class does not exist at runtime, it's a hack to add methods to the +# patch() function. +@type_check_only class _patcher: TEST_PREFIX: str - dict: Type[_patch_dict] - if sys.version_info >= (3, 8): - # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. - # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], - # but that's impossible with the current type system. - @overload - def __call__( # type: ignore[misc] - self, - target: Any, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def __call__( - self, - target: Any, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock | AsyncMock]: ... - else: - @overload - def __call__( # type: ignore[misc] - self, - target: Any, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def __call__( - self, - target: Any, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock]: ... - if sys.version_info >= (3, 8): - @overload - def object( # type: ignore[misc] - self, - target: Any, - attribute: str, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def object( - self, - target: Any, - attribute: str, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock | AsyncMock]: ... - else: - @overload - def object( # type: ignore[misc] - self, - target: Any, - attribute: str, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def object( - self, - target: Any, - attribute: str, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock]: ... - def multiple( + dict: type[_patch_dict] + + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __call__( # type: ignore[overload-overlap] + self, + target: str, + new: _T, + spec: Literal[False] | None = None, + create: bool = False, + spec_set: Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: None = None, + *, + unsafe: bool = False, + ) -> _patch[_T]: ... + @overload + def __call__( self, + target: str, + *, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None = None, + create: bool = False, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: Callable[..., _T], + unsafe: bool = False, + # kwargs are passed to new_callable + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + def __call__( + self, + target: str, + *, + spec: Any | bool | None = None, + create: bool = False, + spec_set: Any | bool | None = None, + autospec: Any | bool | None = None, + new_callable: None = None, + unsafe: bool = False, + # kwargs are passed to the MagicMock/AsyncMock constructor + **kwargs: Any, + ) -> _patch_pass_arg[MagicMock | AsyncMock]: ... + + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + @staticmethod + def object( + target: Any, + attribute: str, + new: _T, + spec: Literal[False] | None = None, + create: bool = False, + spec_set: Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: None = None, + *, + unsafe: bool = False, + ) -> _patch[_T]: ... + @overload + @staticmethod + def object( + target: Any, + attribute: str, + *, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None = None, + create: bool = False, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: Callable[..., _T], + unsafe: bool = False, + # kwargs are passed to new_callable + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + @staticmethod + def object( target: Any, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., + attribute: str, + *, + spec: Any | bool | None = None, + create: bool = False, + spec_set: Any | bool | None = None, + autospec: Any | bool | None = None, + new_callable: None = None, + unsafe: bool = False, + # kwargs are passed to the MagicMock/AsyncMock constructor + **kwargs: Any, + ) -> _patch_pass_arg[MagicMock | AsyncMock]: ... + + @overload + @staticmethod + def multiple( + target: Any | str, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None = None, + create: bool = False, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None = None, + autospec: Literal[False] | None = None, + *, + new_callable: Callable[..., _T], + # The kwargs must be DEFAULT + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + @staticmethod + def multiple( + target: Any | str, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None, + create: bool, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None, + autospec: Literal[False] | None, + new_callable: Callable[..., _T], + # The kwargs must be DEFAULT + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + @staticmethod + def multiple( + target: Any | str, + spec: Any | bool | None = None, + create: bool = False, + spec_set: Any | bool | None = None, + autospec: Any | bool | None = None, + new_callable: None = None, + # The kwargs are the mock objects or DEFAULT **kwargs: Any, ) -> _patch[Any]: ... - def stopall(self) -> None: ... + + @staticmethod + def stopall() -> None: ... patch: _patcher -class MagicMixin: +class MagicMixin(Base): def __init__(self, *args: Any, **kw: Any) -> None: ... -class NonCallableMagicMock(MagicMixin, NonCallableMock): - def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... - -class MagicMock(MagicMixin, Mock): - def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... - -if sys.version_info >= (3, 8): - class AsyncMockMixin(Base): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... - def assert_awaited(self) -> None: ... - def assert_awaited_once(self) -> None: ... - def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... - def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = ...) -> None: ... - def assert_not_awaited(self) -> None: ... - def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... - await_count: int - await_args: _Call | None - await_args_list: _CallList - class AsyncMagicMixin(MagicMixin): - def __init__(self, *args: Any, **kw: Any) -> None: ... - class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... - -class MagicProxy: - name: Any +class NonCallableMagicMock(MagicMixin, NonCallableMock): ... +class MagicMock(MagicMixin, Mock): ... + +class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... + def assert_awaited(self) -> None: ... + def assert_awaited_once(self) -> None: ... + def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = False) -> None: ... + def assert_not_awaited(self) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + await_count: int + await_args: _Call | None + await_args_list: _CallList + +class AsyncMagicMixin(MagicMixin): + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + +class MagicProxy(Base): + name: str parent: Any - def __init__(self, name, parent) -> None: ... - if sys.version_info < (3, 8): - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def create_mock(self): ... - def __get__(self, obj, _type: Any | None = ...): ... + def __init__(self, name: str, parent: Any) -> None: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Any | None = None) -> Any: ... -class _ANY: - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... +# See https://github.com/python/typeshed/issues/14701 +class _ANY(Any): + def __eq__(self, other: object) -> Literal[True]: ... + def __ne__(self, other: object) -> Literal[False]: ... + __hash__: ClassVar[None] # type: ignore[assignment] -ANY: Any +ANY: _ANY def create_autospec( - spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Any | None = ..., _name: Any | None = ..., **kwargs: Any + spec: Any, + spec_set: Any = False, + instance: Any = False, + _parent: Any | None = None, + _name: Any | None = None, + *, + unsafe: bool = False, + **kwargs: Any, ) -> Any: ... class _SpecState: @@ -437,16 +527,29 @@ class _SpecState: def __init__( self, spec: Any, - spec_set: Any = ..., - parent: Any | None = ..., - name: Any | None = ..., - ids: Any | None = ..., - instance: Any = ..., + spec_set: Any = False, + parent: Any | None = None, + name: Any | None = None, + ids: Any | None = None, + instance: Any = False, ) -> None: ... -def mock_open(mock: Any | None = ..., read_data: Any = ...) -> Any: ... +def mock_open(mock: Any | None = None, read_data: Any = "") -> Any: ... + +class PropertyMock(Mock): + def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ... + def __set__(self, obj: Any, val: Any) -> None: ... + +if sys.version_info >= (3, 13): + class ThreadingMixin(Base): + DEFAULT_TIMEOUT: Final[float | None] = None + + def __init__(self, /, *args: Any, timeout: float | _SentinelObject | None = ..., **kwargs: Any) -> None: ... + # Same as `NonCallableMock.reset_mock.` + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + def wait_until_called(self, *, timeout: float | _SentinelObject | None = ...) -> None: ... + def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: ... -PropertyMock = Any + class ThreadingMock(ThreadingMixin, MagicMixin, Mock): ... -if sys.version_info >= (3, 7): - def seal(mock: Any) -> None: ... +def seal(mock: Any) -> None: ... diff --git a/stdlib/unittest/result.pyi b/stdlib/unittest/result.pyi index 0ec4e9170388..081f6e1328e4 100644 --- a/stdlib/unittest/result.pyi +++ b/stdlib/unittest/result.pyi @@ -1,13 +1,14 @@ +import sys import unittest.case -from types import TracebackType -from typing import Any, Callable, TextIO, Tuple, Type, TypeVar, Union - -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, TracebackType], Tuple[None, None, None]] +from _typeshed import OptExcInfo +from collections.abc import Callable +from typing import Any, Final, TextIO, TypeAlias, TypeVar _F = TypeVar("_F", bound=Callable[..., Any]) +_DurationsType: TypeAlias = list[tuple[str, float]] -STDOUT_LINE: str -STDERR_LINE: str +STDOUT_LINE: Final[str] +STDERR_LINE: Final[str] # undocumented def failfast(method: _F) -> _F: ... @@ -23,7 +24,10 @@ class TestResult: buffer: bool failfast: bool tb_locals: bool - def __init__(self, stream: TextIO | None = ..., descriptions: bool | None = ..., verbosity: int | None = ...) -> None: ... + if sys.version_info >= (3, 12): + collectedDurations: _DurationsType + + def __init__(self, stream: TextIO | None = None, descriptions: bool | None = None, verbosity: int | None = None) -> None: ... def printErrors(self) -> None: ... def wasSuccessful(self) -> bool: ... def stop(self) -> None: ... @@ -31,10 +35,12 @@ class TestResult: def stopTest(self, test: unittest.case.TestCase) -> None: ... def startTestRun(self) -> None: ... def stopTestRun(self) -> None: ... - def addError(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... - def addFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... + def addError(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... + def addFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... def addSuccess(self, test: unittest.case.TestCase) -> None: ... def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: ... - def addExpectedFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... + def addExpectedFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ... - def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: _SysExcInfoType | None) -> None: ... + def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: OptExcInfo | None) -> None: ... + if sys.version_info >= (3, 12): + def addDuration(self, test: unittest.case.TestCase, elapsed: float) -> None: ... diff --git a/stdlib/unittest/runner.pyi b/stdlib/unittest/runner.pyi index bf8f3c05c1cd..3a2e08749e9b 100644 --- a/stdlib/unittest/runner.pyi +++ b/stdlib/unittest/runner.pyi @@ -1,35 +1,93 @@ +import sys import unittest.case import unittest.result import unittest.suite -from typing import Callable, TextIO, Type +from _typeshed import SupportsFlush, SupportsWrite +from collections.abc import Callable, Iterable +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import Never +from warnings import _ActionKind -_ResultClassType = Callable[[TextIO, bool, int], unittest.result.TestResult] +_ResultClassType: TypeAlias = Callable[[_TextTestStream, bool, int], TextTestResult[Any]] -class TextTestResult(unittest.result.TestResult): +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[str], SupportsFlush, Protocol): ... + +# All methods used by unittest.runner.TextTestResult's stream +@type_check_only +class _TextTestStream(_SupportsWriteAndFlush, Protocol): + def writeln(self, arg: str | None = None, /) -> None: ... + +# _WritelnDecorator should have all the same attrs as its stream param. +# But that's not feasible to do Generically +# We can expand the attributes if requested +class _WritelnDecorator: + def __init__(self, stream: _SupportsWriteAndFlush) -> None: ... + def writeln(self, arg: str | None = None) -> None: ... + def __getattr__(self, attr: str) -> Any: ... # Any attribute from the stream type passed to __init__ + # These attributes are prevented by __getattr__ + stream: Never + __getstate__: Never + # Methods proxied from the wrapped stream object via __getattr__ + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... + +_StreamT = TypeVar("_StreamT", bound=_TextTestStream, default=_WritelnDecorator) + +class TextTestResult(unittest.result.TestResult, Generic[_StreamT]): descriptions: bool # undocumented dots: bool # undocumented separator1: str separator2: str - showall: bool # undocumented - stream: TextIO # undocumented - def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + showAll: bool # undocumented + stream: _StreamT # undocumented + if sys.version_info >= (3, 12): + durations: int | None + def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int, *, durations: int | None = None) -> None: ... + else: + def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int) -> None: ... + def getDescription(self, test: unittest.case.TestCase) -> str: ... - def printErrors(self) -> None: ... - def printErrorList(self, flavour: str, errors: tuple[unittest.case.TestCase, str]) -> None: ... + def printErrorList(self, flavour: str, errors: Iterable[tuple[unittest.case.TestCase, str]]) -> None: ... -class TextTestRunner(object): +class TextTestRunner: resultclass: _ResultClassType - def __init__( - self, - stream: TextIO | None = ..., - descriptions: bool = ..., - verbosity: int = ..., - failfast: bool = ..., - buffer: bool = ..., - resultclass: _ResultClassType | None = ..., - warnings: Type[Warning] | None = ..., - *, - tb_locals: bool = ..., - ) -> None: ... - def _makeResult(self) -> unittest.result.TestResult: ... - def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> unittest.result.TestResult: ... + stream: _WritelnDecorator + descriptions: bool + verbosity: int + failfast: bool + buffer: bool + warnings: _ActionKind | None + tb_locals: bool + + if sys.version_info >= (3, 12): + durations: int | None + def __init__( + self, + stream: _SupportsWriteAndFlush | None = None, + descriptions: bool = True, + verbosity: int = 1, + failfast: bool = False, + buffer: bool = False, + resultclass: _ResultClassType | None = None, + warnings: _ActionKind | None = None, + *, + tb_locals: bool = False, + durations: int | None = None, + ) -> None: ... + else: + def __init__( + self, + stream: _SupportsWriteAndFlush | None = None, + descriptions: bool = True, + verbosity: int = 1, + failfast: bool = False, + buffer: bool = False, + resultclass: _ResultClassType | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + ) -> None: ... + + def _makeResult(self) -> TextTestResult: ... + def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> TextTestResult: ... diff --git a/stdlib/unittest/signals.pyi b/stdlib/unittest/signals.pyi index 453bc9caf9e7..928ab68ae65d 100644 --- a/stdlib/unittest/signals.pyi +++ b/stdlib/unittest/signals.pyi @@ -1,6 +1,6 @@ import unittest.result -from typing import Callable, TypeVar, overload -from typing_extensions import ParamSpec +from collections.abc import Callable +from typing import ParamSpec, TypeVar, overload _P = ParamSpec("_P") _T = TypeVar("_T") @@ -8,7 +8,8 @@ _T = TypeVar("_T") def installHandler() -> None: ... def registerResult(result: unittest.result.TestResult) -> None: ... def removeResult(result: unittest.result.TestResult) -> bool: ... + @overload -def removeHandler(method: None = ...) -> None: ... +def removeHandler(method: None = None) -> None: ... @overload -def removeHandler(method: Callable[_P, _T]) -> Callable[_P, _T]: ... # type: ignore[misc] +def removeHandler(method: Callable[_P, _T]) -> Callable[_P, _T]: ... diff --git a/stdlib/unittest/suite.pyi b/stdlib/unittest/suite.pyi index 396b46eadf5a..b7cf75c68271 100644 --- a/stdlib/unittest/suite.pyi +++ b/stdlib/unittest/suite.pyi @@ -1,13 +1,14 @@ import unittest.case import unittest.result -from typing import Iterable, Iterator, Union +from collections.abc import Iterable, Iterator +from typing import ClassVar, TypeAlias -_TestType = Union[unittest.case.TestCase, TestSuite] +_TestType: TypeAlias = unittest.case.TestCase | TestSuite -class BaseTestSuite(Iterable[_TestType]): +class BaseTestSuite: _tests: list[unittest.case.TestCase] _removed_tests: int - def __init__(self, tests: Iterable[_TestType] = ...) -> None: ... + def __init__(self, tests: Iterable[_TestType] = ()) -> None: ... def __call__(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ... def addTest(self, test: _TestType) -> None: ... def addTests(self, tests: Iterable[_TestType]) -> None: ... @@ -15,6 +16,8 @@ class BaseTestSuite(Iterable[_TestType]): def debug(self) -> None: ... def countTestCases(self) -> int: ... def __iter__(self) -> Iterator[_TestType]: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] class TestSuite(BaseTestSuite): - def run(self, result: unittest.result.TestResult, debug: bool = ...) -> unittest.result.TestResult: ... + def run(self, result: unittest.result.TestResult, debug: bool = False) -> unittest.result.TestResult: ... diff --git a/stdlib/unittest/util.pyi b/stdlib/unittest/util.pyi index ab6ed053a6ff..11a6f903932f 100644 --- a/stdlib/unittest/util.pyi +++ b/stdlib/unittest/util.pyi @@ -1,21 +1,39 @@ -from typing import Any, Sequence, Tuple, TypeVar +from collections.abc import MutableSequence, Sequence +from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, type_check_only + +@type_check_only +class _SupportsDunderLT(Protocol): + def __lt__(self, other: Any, /) -> bool: ... + +@type_check_only +class _SupportsDunderGT(Protocol): + def __gt__(self, other: Any, /) -> bool: ... + +@type_check_only +class _SupportsDunderLE(Protocol): + def __le__(self, other: Any, /) -> bool: ... + +@type_check_only +class _SupportsDunderGE(Protocol): + def __ge__(self, other: Any, /) -> bool: ... _T = TypeVar("_T") -_Mismatch = Tuple[_T, _T, int] +_Mismatch: TypeAlias = tuple[_T, _T, int] +_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT -_MAX_LENGTH: int -_PLACEHOLDER_LEN: int -_MIN_BEGIN_LEN: int -_MIN_END_LEN: int -_MIN_COMMON_LEN: int -_MIN_DIFF_LEN: int +_MAX_LENGTH: Final = 80 +_PLACEHOLDER_LEN: Final = 12 +_MIN_BEGIN_LEN: Final = 5 +_MIN_END_LEN: Final = 5 +_MIN_COMMON_LEN: Final = 5 +_MIN_DIFF_LEN: Final = 41 def _shorten(s: str, prefixlen: int, suffixlen: int) -> str: ... -def _common_shorten_repr(*args: str) -> tuple[str]: ... -def safe_repr(obj: object, short: bool = ...) -> str: ... +def _common_shorten_repr(*args: str) -> tuple[str, ...]: ... +def safe_repr(obj: object, short: bool = False) -> str: ... def strclass(cls: type) -> str: ... def sorted_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> tuple[list[_T], list[_T]]: ... -def unorderable_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> tuple[list[_T], list[_T]]: ... -def three_way_cmp(x: Any, y: Any) -> int: ... +def unorderable_list_difference(expected: MutableSequence[_T], actual: MutableSequence[_T]) -> tuple[list[_T], list[_T]]: ... +def three_way_cmp(x: _SupportsComparison, y: _SupportsComparison) -> Literal[-1, 0, 1]: ... def _count_diff_all_purpose(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: ... def _count_diff_hashable(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: ... diff --git a/stdlib/urllib/error.pyi b/stdlib/urllib/error.pyi index 1d91fedceeca..6255f1ae7db0 100644 --- a/stdlib/urllib/error.pyi +++ b/stdlib/urllib/error.pyi @@ -2,14 +2,26 @@ from email.message import Message from typing import IO from urllib.response import addinfourl -# Stubs for urllib.error +__all__ = ["URLError", "HTTPError", "ContentTooShortError"] -class URLError(IOError): +class URLError(OSError): reason: str | BaseException - def __init__(self, reason: str | BaseException, filename: str | None = ...) -> None: ... + # The `filename` attribute only exists if it was provided to `__init__` and wasn't `None`. + filename: str + def __init__(self, reason: str | BaseException, filename: str | None = None) -> None: ... class HTTPError(URLError, addinfourl): + @property + def headers(self) -> Message: ... + @headers.setter + def headers(self, headers: Message) -> None: ... + + @property + def reason(self) -> str: ... # type: ignore[override] code: int + msg: str + hdrs: Message + fp: IO[bytes] def __init__(self, url: str, code: int, msg: str, hdrs: Message, fp: IO[bytes] | None) -> None: ... class ContentTooShortError(URLError): diff --git a/stdlib/urllib/parse.pyi b/stdlib/urllib/parse.pyi index a5afbdc26bf2..a3250b4092f0 100644 --- a/stdlib/urllib/parse.pyi +++ b/stdlib/urllib/parse.pyi @@ -1,142 +1,354 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Tuple, Union, overload +from collections.abc import Iterable, Mapping, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Final, Generic, Literal, NamedTuple, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias +__all__ = [ + "urlparse", + "urlunparse", + "urljoin", + "urldefrag", + "urlsplit", + "urlunsplit", + "urlencode", + "parse_qs", + "parse_qsl", + "quote", + "quote_plus", + "quote_from_bytes", + "unquote", + "unquote_plus", + "unquote_to_bytes", + "DefragResult", + "ParseResult", + "SplitResult", + "DefragResultBytes", + "ParseResultBytes", + "SplitResultBytes", +] -_Str = Union[bytes, str] +uses_relative: Final[list[str]] +uses_netloc: Final[list[str]] +uses_params: Final[list[str]] +non_hierarchical: Final[list[str]] +uses_query: Final[list[str]] +uses_fragment: Final[list[str]] +scheme_chars: Final[str] +if sys.version_info < (3, 11): + MAX_CACHE_SIZE: Final[int] -uses_relative: list[str] -uses_netloc: list[str] -uses_params: list[str] -non_hierarchical: list[str] -uses_query: list[str] -uses_fragment: list[str] -scheme_chars: str -MAX_CACHE_SIZE: int +_ResultStrT = TypeVar("_ResultStrT", str, bytes) +_ResultComponentT = TypeVar("_ResultComponentT", str, bytes, str | None, bytes | None) +_StrComponentT = TypeVar("_StrComponentT", str, str | None, default=str) +_BytesComponentT = TypeVar("_BytesComponentT", bytes, bytes | None, default=bytes) -class _ResultMixinBase(Generic[AnyStr]): - def geturl(self) -> AnyStr: ... +class _ResultMixinStr: + __slots__ = () + def encode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinBytes: ... -class _ResultMixinStr(_ResultMixinBase[str]): - def encode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinBytes: ... - -class _ResultMixinBytes(_ResultMixinBase[str]): - def decode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinStr: ... +class _ResultMixinBytes: + __slots__ = () + def decode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinStr: ... class _NetlocResultMixinBase(Generic[AnyStr]): - username: AnyStr | None - password: AnyStr | None - hostname: AnyStr | None - port: int | None - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... -class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... - -class _DefragResultBase(Tuple[Any, ...], Generic[AnyStr]): - url: AnyStr - fragment: AnyStr - -class _SplitResultBase(NamedTuple): - scheme: str - netloc: str - path: str - query: str - fragment: str - -class _SplitResultBytesBase(NamedTuple): - scheme: bytes - netloc: bytes - path: bytes - query: bytes - fragment: bytes - -class _ParseResultBase(NamedTuple): - scheme: str - netloc: str - path: str - params: str - query: str - fragment: str - -class _ParseResultBytesBase(NamedTuple): - scheme: bytes - netloc: bytes - path: bytes - params: bytes - query: bytes - fragment: bytes - -# Structured result objects for string data -class DefragResult(_DefragResultBase[str], _ResultMixinStr): ... -class SplitResult(_SplitResultBase, _NetlocResultMixinStr): ... -class ParseResult(_ParseResultBase, _NetlocResultMixinStr): ... - -# Structured result objects for bytes data -class DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes): ... -class SplitResultBytes(_SplitResultBytesBase, _NetlocResultMixinBytes): ... -class ParseResultBytes(_ParseResultBytesBase, _NetlocResultMixinBytes): ... + __slots__ = () + @property + def username(self) -> AnyStr | None: ... + @property + def password(self) -> AnyStr | None: ... + @property + def hostname(self) -> AnyStr | None: ... + @property + def port(self) -> int | None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): + __slots__ = () + +class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): + __slots__ = () + +# Need to duplicate the whole class because mypy rejects version-specific +# branches in namedtuple bodies. +if sys.version_info >= (3, 15): + class _DefragResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + url: _ResultStrT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _DefragResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + url: _ResultStrT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + class _SplitResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + query: _ResultComponentT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _SplitResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + query: _ResultComponentT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + class _ParseResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + params: _ResultComponentT + query: _ResultComponentT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _ParseResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + params: _ResultComponentT + query: _ResultComponentT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + # Structured result objects for string data + class DefragResult(_DefragResultBase[str, _StrComponentT], _ResultMixinStr, Generic[_StrComponentT]): ... + class SplitResult(_SplitResultBase[str, _StrComponentT], _NetlocResultMixinStr, Generic[_StrComponentT]): ... + class ParseResult(_ParseResultBase[str, _StrComponentT], _NetlocResultMixinStr, Generic[_StrComponentT]): ... + # Structured result objects for bytes data + class DefragResultBytes(_DefragResultBase[bytes, _BytesComponentT], _ResultMixinBytes, Generic[_BytesComponentT]): ... + class SplitResultBytes(_SplitResultBase[bytes, _BytesComponentT], _NetlocResultMixinBytes, Generic[_BytesComponentT]): ... + class ParseResultBytes(_ParseResultBase[bytes, _BytesComponentT], _NetlocResultMixinBytes, Generic[_BytesComponentT]): ... + +else: + # Structured result objects for string data + class DefragResult(_DefragResultBase[str, str], _ResultMixinStr): + def geturl(self) -> str: ... + + class SplitResult(_SplitResultBase[str, str], _NetlocResultMixinStr): + def geturl(self) -> str: ... + + class ParseResult(_ParseResultBase[str, str], _NetlocResultMixinStr): + def geturl(self) -> str: ... + + # Structured result objects for bytes data + class DefragResultBytes(_DefragResultBase[bytes, bytes], _ResultMixinBytes): + def geturl(self) -> bytes: ... + + class SplitResultBytes(_SplitResultBase[bytes, bytes], _NetlocResultMixinBytes): + def geturl(self) -> bytes: ... + + class ParseResultBytes(_ParseResultBase[bytes, bytes], _NetlocResultMixinBytes): + def geturl(self) -> bytes: ... def parse_qs( qs: AnyStr | None, - keep_blank_values: bool = ..., - strict_parsing: bool = ..., - encoding: str = ..., - errors: str = ..., - max_num_fields: int | None = ..., - separator: str = ..., + keep_blank_values: bool = False, + strict_parsing: bool = False, + encoding: str = "utf-8", + errors: str = "replace", + max_num_fields: int | None = None, + separator: str = "&", ) -> dict[AnyStr, list[AnyStr]]: ... def parse_qsl( qs: AnyStr | None, - keep_blank_values: bool = ..., - strict_parsing: bool = ..., - encoding: str = ..., - errors: str = ..., - max_num_fields: int | None = ..., - separator: str = ..., + keep_blank_values: bool = False, + strict_parsing: bool = False, + encoding: str = "utf-8", + errors: str = "replace", + max_num_fields: int | None = None, + separator: str = "&", ) -> list[tuple[AnyStr, AnyStr]]: ... + @overload -def quote(string: str, safe: _Str = ..., encoding: str | None = ..., errors: str | None = ...) -> str: ... +def quote(string: str, safe: str | Iterable[int] = "/", encoding: str | None = None, errors: str | None = None) -> str: ... @overload -def quote(string: bytes, safe: _Str = ...) -> str: ... -def quote_from_bytes(bs: bytes, safe: _Str = ...) -> str: ... +def quote(string: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... + +def quote_from_bytes(bs: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... + @overload -def quote_plus(string: str, safe: _Str = ..., encoding: str | None = ..., errors: str | None = ...) -> str: ... +def quote_plus(string: str, safe: str | Iterable[int] = "", encoding: str | None = None, errors: str | None = None) -> str: ... @overload -def quote_plus(string: bytes, safe: _Str = ...) -> str: ... -def unquote(string: str, encoding: str = ..., errors: str = ...) -> str: ... -def unquote_to_bytes(string: _Str) -> bytes: ... -def unquote_plus(string: str, encoding: str = ..., errors: str = ...) -> str: ... +def quote_plus(string: bytes | bytearray, safe: str | Iterable[int] = "") -> str: ... + +def unquote(string: str | bytes, encoding: str = "utf-8", errors: str = "replace") -> str: ... +def unquote_to_bytes(string: str | bytes | bytearray) -> bytes: ... +def unquote_plus(string: str, encoding: str = "utf-8", errors: str = "replace") -> str: ... + @overload def urldefrag(url: str) -> DefragResult: ... @overload -def urldefrag(url: bytes | None) -> DefragResultBytes: ... +def urldefrag(url: bytes | bytearray | None) -> DefragResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urldefrag(url: str, *, missing_as_none: Literal[True]) -> DefragResult[str | None]: ... + @overload + def urldefrag(url: str, *, missing_as_none: Literal[False] = False) -> DefragResult[str]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: Literal[True]) -> DefragResultBytes[bytes | None]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: Literal[False] = False) -> DefragResultBytes[bytes]: ... + @overload + def urldefrag(url: str, *, missing_as_none: bool) -> DefragResult[str | None]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: bool) -> DefragResultBytes[bytes | None]: ... + +# The values are passed through `str()` (unless they are bytes), so anything is valid. +_QueryType: TypeAlias = ( + Mapping[str, object] + | Mapping[bytes, object] + | Mapping[str | bytes, object] + | Mapping[str, Sequence[object]] + | Mapping[bytes, Sequence[object]] + | Mapping[str | bytes, Sequence[object]] + | Sequence[tuple[str | bytes, object]] + | Sequence[tuple[str | bytes, Sequence[object]]] +) + +@type_check_only +class _QuoteVia(Protocol): + @overload + def __call__(self, string: str, safe: str | bytes, encoding: str, errors: str, /) -> str: ... + @overload + def __call__(self, string: bytes, safe: str | bytes, /) -> str: ... + def urlencode( - query: Mapping[Any, Any] | Mapping[Any, Sequence[Any]] | Sequence[tuple[Any, Any]] | Sequence[tuple[Any, Sequence[Any]]], - doseq: bool = ..., - safe: _Str = ..., - encoding: str = ..., - errors: str = ..., - quote_via: Callable[[AnyStr, _Str, str, str], str] = ..., + query: _QueryType, + doseq: bool = False, + safe: str | bytes = "", + encoding: str | None = None, + errors: str | None = None, + quote_via: _QuoteVia = ..., ) -> str: ... -def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = ...) -> AnyStr: ... -@overload -def urlparse(url: str, scheme: str | None = ..., allow_fragments: bool = ...) -> ParseResult: ... -@overload -def urlparse(url: bytes | None, scheme: bytes | None = ..., allow_fragments: bool = ...) -> ParseResultBytes: ... -@overload -def urlsplit(url: str, scheme: str | None = ..., allow_fragments: bool = ...) -> SplitResult: ... -@overload -def urlsplit(url: bytes | None, scheme: bytes | None = ..., allow_fragments: bool = ...) -> SplitResultBytes: ... -@overload -def urlunparse( - components: tuple[AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None] -) -> AnyStr: ... +def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> AnyStr: ... + @overload -def urlunparse(components: Sequence[AnyStr | None]) -> AnyStr: ... +def urlparse(url: str, scheme: str = "", allow_fragments: bool = True) -> ParseResult: ... @overload -def urlunsplit(components: tuple[AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None]) -> AnyStr: ... +def urlparse( + url: bytes | bytearray | None, scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True +) -> ParseResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[True] + ) -> ParseResult[str | None]: ... + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False + ) -> ParseResult[str]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | Literal[""] | None = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[True], + ) -> ParseResultBytes[bytes | None]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | Literal[""] | None = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[False] = False, + ) -> ParseResultBytes[bytes]: ... + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> ParseResult[str | None]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | Literal[""] | None = "", + allow_fragments: bool = True, + *, + missing_as_none: bool, + ) -> ParseResultBytes[bytes | None]: ... + @overload -def urlunsplit(components: Sequence[AnyStr | None]) -> AnyStr: ... +def urlsplit(url: str, scheme: str = "", allow_fragments: bool = True) -> SplitResult: ... + +if sys.version_info >= (3, 11): + @overload + def urlsplit( + url: bytes | None, scheme: bytes | Literal[""] | None = "", allow_fragments: bool = True + ) -> SplitResultBytes: ... +else: + @overload + def urlsplit( + url: bytes | bytearray | None, scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True + ) -> SplitResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[True] + ) -> SplitResult[str | None]: ... + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False + ) -> SplitResult[str]: ... + @overload + def urlsplit( + url: bytes | None, + scheme: bytes | Literal[""] | None = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[True], + ) -> SplitResultBytes[bytes | None]: ... + @overload + def urlsplit( + url: bytes | None, + scheme: bytes | Literal[""] | None = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[False] = False, + ) -> SplitResultBytes[bytes]: ... + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> SplitResult[str | None]: ... + @overload + def urlsplit( + url: bytes | None, scheme: bytes | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> SplitResultBytes[bytes | None]: ... + +if sys.version_info >= (3, 15): + # Requires an iterable of length 6 + @overload + def urlunparse(components: Iterable[None], *, keep_empty: bool = ...) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunparse(components: Iterable[AnyStr | None], *, keep_empty: bool = ...) -> AnyStr: ... +else: + # Requires an iterable of length 6 + @overload + def urlunparse(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunparse(components: Iterable[AnyStr | None]) -> AnyStr: ... + +if sys.version_info >= (3, 15): + # Requires an iterable of length 5 + @overload + def urlunsplit(components: Iterable[None], *, keep_empty: bool = ...) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunsplit(components: Iterable[AnyStr | None], *, keep_empty: bool = ...) -> AnyStr: ... +else: + # Requires an iterable of length 5 + @overload + def urlunsplit(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunsplit(components: Iterable[AnyStr | None]) -> AnyStr: ... + +def unwrap(url: str) -> str: ... diff --git a/stdlib/urllib/request.pyi b/stdlib/urllib/request.pyi index 3c8a6facde6f..d81d3a2f8698 100644 --- a/stdlib/urllib/request.pyi +++ b/stdlib/urllib/request.pyi @@ -1,36 +1,117 @@ import ssl import sys -from _typeshed import StrOrBytesPath +from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsItems, SupportsRead +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from email.message import Message -from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol +from http.client import HTTPConnection, HTTPMessage, HTTPResponse from http.cookiejar import CookieJar -from typing import IO, Any, Callable, ClassVar, Mapping, NoReturn, Pattern, Sequence, Tuple, TypeVar, overload -from urllib.error import HTTPError +from re import Pattern +from typing import IO, Any, ClassVar, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated +from urllib.error import HTTPError as HTTPError from urllib.response import addclosehook, addinfourl +__all__ = [ + "Request", + "OpenerDirector", + "BaseHandler", + "HTTPDefaultErrorHandler", + "HTTPRedirectHandler", + "HTTPCookieProcessor", + "ProxyHandler", + "HTTPPasswordMgr", + "HTTPPasswordMgrWithDefaultRealm", + "HTTPPasswordMgrWithPriorAuth", + "AbstractBasicAuthHandler", + "HTTPBasicAuthHandler", + "ProxyBasicAuthHandler", + "AbstractDigestAuthHandler", + "HTTPDigestAuthHandler", + "ProxyDigestAuthHandler", + "HTTPHandler", + "FileHandler", + "FTPHandler", + "CacheFTPHandler", + "DataHandler", + "UnknownHandler", + "HTTPErrorProcessor", + "urlopen", + "install_opener", + "build_opener", + "pathname2url", + "url2pathname", + "getproxies", + "urlretrieve", + "urlcleanup", + "HTTPSHandler", +] +if sys.version_info < (3, 14): + __all__ += ["URLopener", "FancyURLopener"] + _T = TypeVar("_T") -_UrlopenRet = Any - -def urlopen( - url: str | Request, - data: bytes | None = ..., - timeout: float | None = ..., - *, - cafile: str | None = ..., - capath: str | None = ..., - cadefault: bool = ..., - context: ssl.SSLContext | None = ..., -) -> _UrlopenRet: ... -def install_opener(opener: OpenerDirector) -> None: ... + +# The actual type is `addinfourl | HTTPResponse`, but users would need to use `typing.cast` or `isinstance` to narrow the type, +# so we use `Any` instead. +# See +# - https://github.com/python/typeshed/pull/15042 +# - https://github.com/python/typing/issues/566 +_UrlopenRet: TypeAlias = Any + +_DataType: TypeAlias = ReadableBuffer | SupportsRead[bytes] | Iterable[bytes] | None + +if sys.version_info >= (3, 13): + def urlopen( + url: str | Request, data: _DataType | None = None, timeout: float | None = ..., *, context: ssl.SSLContext | None = None + ) -> _UrlopenRet: ... + +else: + @overload + def urlopen( + url: str | Request, + data: _DataType | None = None, + timeout: float | None = ..., + *, + cafile: None = None, + capath: None = None, + cadefault: Literal[False] = False, + context: ssl.SSLContext | None = None, + ) -> _UrlopenRet: ... + @overload + @deprecated( + "The `cafile`, `capath`, `cadefault` parameters are deprecated since Python 3.6; " + "removed in Python 3.13. Use `context` parameter instead." + ) + def urlopen( + url: str | Request, + data: _DataType | None = None, + timeout: float | None = ..., + *, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadefault: bool = False, + context: None = None, + ) -> _UrlopenRet: ... + +def install_opener(opener: OpenerDirector | None) -> None: ... def build_opener(*handlers: BaseHandler | Callable[[], BaseHandler]) -> OpenerDirector: ... -if sys.platform == "win32": - from nturl2path import pathname2url as pathname2url, url2pathname as url2pathname +if sys.version_info >= (3, 14): + def url2pathname(url: str, *, require_scheme: bool = False, resolve_host: bool = False) -> str: ... + def pathname2url(pathname: str, *, add_scheme: bool = False) -> str: ... + else: - def url2pathname(pathname: str) -> str: ... - def pathname2url(pathname: str) -> str: ... + if sys.platform == "win32": + # These functions are implemented in the deprecated ``nturl2path`` module, + # but remain part of the public ``urllib.request`` API. + def url2pathname(url: str) -> str: ... + def pathname2url(p: str) -> str: ... + + else: + def url2pathname(pathname: str) -> str: ... + def pathname2url(pathname: str) -> str: ... def getproxies() -> dict[str, str]: ... +def getproxies_environment() -> dict[str, str]: ... def parse_http_list(s: str) -> list[str]: ... def parse_keqv_list(l: list[str]) -> dict[str, str]: ... @@ -38,7 +119,7 @@ if sys.platform == "win32" or sys.platform == "darwin": def proxy_bypass(host: str) -> Any: ... # undocumented else: - def proxy_bypass(host: str, proxies: Mapping[str, str] | None = ...) -> Any: ... # undocumented + def proxy_bypass(host: str, proxies: Mapping[str, str] | None = None) -> Any: ... # undocumented class Request: @property @@ -47,12 +128,13 @@ class Request: def full_url(self, value: str) -> None: ... @full_url.deleter def full_url(self) -> None: ... + type: str host: str origin_req_host: str selector: str - data: bytes | None - headers: dict[str, str] + data: _DataType + headers: MutableMapping[str, str] unredirected_hdrs: dict[str, str] unverifiable: bool method: str | None @@ -60,11 +142,11 @@ class Request: def __init__( self, url: str, - data: bytes | None = ..., - headers: dict[str, str] = ..., - origin_req_host: str | None = ..., - unverifiable: bool = ..., - method: str | None = ..., + data: _DataType = None, + headers: SupportsItems[str, str] = {}, + origin_req_host: str | None = None, + unverifiable: bool = False, + method: str | None = None, ) -> None: ... def get_method(self) -> str: ... def add_header(self, key: str, val: str) -> None: ... @@ -73,17 +155,19 @@ class Request: def remove_header(self, header_name: str) -> None: ... def get_full_url(self) -> str: ... def set_proxy(self, host: str, type: str) -> None: ... + @overload def get_header(self, header_name: str) -> str | None: ... @overload def get_header(self, header_name: str, default: _T) -> str | _T: ... + def header_items(self) -> list[tuple[str, str]]: ... def has_proxy(self) -> bool: ... class OpenerDirector: addheaders: list[tuple[str, str]] def add_handler(self, handler: BaseHandler) -> None: ... - def open(self, fullurl: str | Request, data: bytes | None = ..., timeout: float | None = ...) -> _UrlopenRet: ... + def open(self, fullurl: str | Request, data: _DataType = None, timeout: float | None = ...) -> _UrlopenRet: ... def error(self, proto: str, *args: Any) -> _UrlopenRet: ... def close(self) -> None: ... @@ -92,6 +176,7 @@ class BaseHandler: parent: OpenerDirector def add_parent(self, parent: OpenerDirector) -> None: ... def close(self) -> None: ... + def __lt__(self, other: object) -> bool: ... class HTTPDefaultErrorHandler(BaseHandler): def http_error_default( @@ -109,25 +194,29 @@ class HTTPRedirectHandler(BaseHandler): def http_error_302(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... def http_error_303(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... def http_error_307(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + if sys.version_info >= (3, 11): + def http_error_308( + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage + ) -> _UrlopenRet | None: ... class HTTPCookieProcessor(BaseHandler): cookiejar: CookieJar - def __init__(self, cookiejar: CookieJar | None = ...) -> None: ... + def __init__(self, cookiejar: CookieJar | None = None) -> None: ... def http_request(self, request: Request) -> Request: ... # undocumented def http_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented def https_request(self, request: Request) -> Request: ... # undocumented def https_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented class ProxyHandler(BaseHandler): - def __init__(self, proxies: dict[str, str] | None = ...) -> None: ... + def __init__(self, proxies: dict[str, str] | None = None) -> None: ... def proxy_open(self, req: Request, proxy: str, type: str) -> _UrlopenRet | None: ... # undocumented - # TODO add a method for every (common) proxy protocol + # TODO: add a method for every (common) proxy protocol class HTTPPasswordMgr: def add_password(self, realm: str, uri: str | Sequence[str], user: str, passwd: str) -> None: ... def find_user_password(self, realm: str, authuri: str) -> tuple[str | None, str | None]: ... def is_suburi(self, base: str, test: str) -> bool: ... # undocumented - def reduce_uri(self, uri: str, default_port: bool = ...) -> str: ... # undocumented + def reduce_uri(self, uri: str, default_port: bool = True) -> tuple[str, str]: ... # undocumented class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): def add_password(self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str) -> None: ... @@ -135,16 +224,16 @@ class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm): def add_password( - self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str, is_authenticated: bool = ... + self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str, is_authenticated: bool = False ) -> None: ... - def update_authenticated(self, uri: str | Sequence[str], is_authenticated: bool = ...) -> None: ... - def is_authenticated(self, authuri: str) -> bool: ... + def update_authenticated(self, uri: str | Sequence[str], is_authenticated: bool = False) -> None: ... + def is_authenticated(self, authuri: str) -> bool | None: ... class AbstractBasicAuthHandler: rx: ClassVar[Pattern[str]] # undocumented passwd: HTTPPasswordMgr add_password: Callable[[str, str | Sequence[str], str, str], None] - def __init__(self, password_mgr: HTTPPasswordMgr | None = ...) -> None: ... + def __init__(self, password_mgr: HTTPPasswordMgr | None = None) -> None: ... def http_error_auth_reqed(self, authreq: str, host: str, req: Request, headers: HTTPMessage) -> None: ... def http_request(self, req: Request) -> Request: ... # undocumented def http_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented @@ -161,14 +250,14 @@ class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... class AbstractDigestAuthHandler: - def __init__(self, passwd: HTTPPasswordMgr | None = ...) -> None: ... + def __init__(self, passwd: HTTPPasswordMgr | None = None) -> None: ... def reset_retry_count(self) -> None: ... def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, headers: HTTPMessage) -> None: ... def retry_http_digest_auth(self, req: Request, auth: str) -> _UrlopenRet | None: ... def get_cnonce(self, nonce: str) -> str: ... - def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str | None: ... def get_algorithm_impls(self, algorithm: str) -> tuple[Callable[[str], str], Callable[[str, str], str]]: ... - def get_entity_digest(self, data: bytes | None, chal: Mapping[str, str]) -> str | None: ... + def get_entity_digest(self, data: ReadableBuffer | None, chal: Mapping[str, str]) -> str | None: ... class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): auth_header: ClassVar[str] # undocumented @@ -178,8 +267,25 @@ class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): auth_header: ClassVar[str] # undocumented def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... +@type_check_only +class _HTTPConnectionProtocol(Protocol): + def __call__( + self, + host: str, + /, + *, + port: int | None = ..., + timeout: float = ..., + source_address: tuple[str, int] | None = ..., + blocksize: int = ..., + ) -> HTTPConnection: ... + class AbstractHTTPHandler(BaseHandler): # undocumented - def __init__(self, debuglevel: int = ...) -> None: ... + if sys.version_info >= (3, 12): + def __init__(self, debuglevel: int | None = None) -> None: ... + else: + def __init__(self, debuglevel: int = 0) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... def do_request_(self, request: Request) -> Request: ... def do_open(self, http_class: _HTTPConnectionProtocol, req: Request, **http_conn_args: Any) -> HTTPResponse: ... @@ -189,16 +295,22 @@ class HTTPHandler(AbstractHTTPHandler): def http_request(self, request: Request) -> Request: ... # undocumented class HTTPSHandler(AbstractHTTPHandler): - def __init__( - self, debuglevel: int = ..., context: ssl.SSLContext | None = ..., check_hostname: bool | None = ... - ) -> None: ... + if sys.version_info >= (3, 12): + def __init__( + self, debuglevel: int | None = None, context: ssl.SSLContext | None = None, check_hostname: bool | None = None + ) -> None: ... + else: + def __init__( + self, debuglevel: int = 0, context: ssl.SSLContext | None = None, check_hostname: bool | None = None + ) -> None: ... + def https_open(self, req: Request) -> HTTPResponse: ... def https_request(self, request: Request) -> Request: ... # undocumented class FileHandler(BaseHandler): - names: ClassVar[Tuple[str, ...] | None] # undocumented + names: ClassVar[tuple[str, ...] | None] # undocumented def file_open(self, req: Request) -> addinfourl: ... - def get_names(self) -> Tuple[str, ...]: ... # undocumented + def get_names(self) -> tuple[str, ...]: ... # undocumented def open_local_file(self, req: Request) -> addinfourl: ... # undocumented class DataHandler(BaseHandler): @@ -206,14 +318,14 @@ class DataHandler(BaseHandler): class ftpwrapper: # undocumented def __init__( - self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float | None = ..., persistent: bool = ... + self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float | None = None, persistent: bool = True ) -> None: ... def close(self) -> None: ... def endtransfer(self) -> None: ... def file_close(self) -> None: ... def init(self) -> None: ... def real_close(self) -> None: ... - def retrfile(self, file: str, type: str) -> tuple[addclosehook, int]: ... + def retrfile(self, file: str, type: str) -> tuple[addclosehook, int | None]: ... class FTPHandler(BaseHandler): def ftp_open(self, req: Request) -> addinfourl: ... @@ -226,12 +338,9 @@ class CacheFTPHandler(FTPHandler): def setMaxConns(self, m: int) -> None: ... def check_cache(self) -> None: ... # undocumented def clear_cache(self) -> None: ... # undocumented - def connect_ftp( - self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float - ) -> ftpwrapper: ... # undocumented class UnknownHandler(BaseHandler): - def unknown_open(self, req: Request) -> NoReturn: ... + def unknown_open(self, req: Request) -> Never: ... class HTTPErrorProcessor(BaseHandler): def http_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... @@ -239,87 +348,100 @@ class HTTPErrorProcessor(BaseHandler): def urlretrieve( url: str, - filename: StrOrBytesPath | None = ..., - reporthook: Callable[[int, int, int], None] | None = ..., - data: bytes | None = ..., + filename: StrOrBytesPath | None = None, + reporthook: Callable[[int, int, int], object] | None = None, + data: _DataType = None, ) -> tuple[str, HTTPMessage]: ... def urlcleanup() -> None: ... -class URLopener: - version: ClassVar[str] - def __init__(self, proxies: dict[str, str] | None = ..., **x509: str) -> None: ... - def open(self, fullurl: str, data: bytes | None = ...) -> _UrlopenRet: ... - def open_unknown(self, fullurl: str, data: bytes | None = ...) -> _UrlopenRet: ... - def retrieve( - self, - url: str, - filename: str | None = ..., - reporthook: Callable[[int, int, int], None] | None = ..., - data: bytes | None = ..., - ) -> tuple[str, Message | None]: ... - def addheader(self, *args: tuple[str, str]) -> None: ... # undocumented - def cleanup(self) -> None: ... # undocumented - def close(self) -> None: ... # undocumented - def http_error( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... - ) -> _UrlopenRet: ... # undocumented - def http_error_default( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage - ) -> _UrlopenRet: ... # undocumented - def open_data(self, url: str, data: bytes | None = ...) -> addinfourl: ... # undocumented - def open_file(self, url: str) -> addinfourl: ... # undocumented - def open_ftp(self, url: str) -> addinfourl: ... # undocumented - def open_http(self, url: str, data: bytes | None = ...) -> _UrlopenRet: ... # undocumented - def open_https(self, url: str, data: bytes | None = ...) -> _UrlopenRet: ... # undocumented - def open_local_file(self, url: str) -> addinfourl: ... # undocumented - def open_unknown_proxy(self, proxy: str, fullurl: str, data: bytes | None = ...) -> None: ... # undocumented - -class FancyURLopener(URLopener): - def prompt_user_passwd(self, host: str, realm: str) -> tuple[str, str]: ... - def get_user_passwd(self, host: str, realm: str, clear_cache: int = ...) -> tuple[str, str]: ... # undocumented - def http_error_301( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... - ) -> _UrlopenRet | addinfourl | None: ... # undocumented - def http_error_302( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... - ) -> _UrlopenRet | addinfourl | None: ... # undocumented - def http_error_303( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... - ) -> _UrlopenRet | addinfourl | None: ... # undocumented - def http_error_307( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... - ) -> _UrlopenRet | addinfourl | None: ... # undocumented - def http_error_401( - self, - url: str, - fp: IO[bytes], - errcode: int, - errmsg: str, - headers: HTTPMessage, - data: bytes | None = ..., - retry: bool = ..., - ) -> _UrlopenRet | None: ... # undocumented - def http_error_407( - self, - url: str, - fp: IO[bytes], - errcode: int, - errmsg: str, - headers: HTTPMessage, - data: bytes | None = ..., - retry: bool = ..., - ) -> _UrlopenRet | None: ... # undocumented - def http_error_default( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage - ) -> addinfourl: ... # undocumented - def redirect_internal( - self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None - ) -> _UrlopenRet | None: ... # undocumented - def retry_http_basic_auth(self, url: str, realm: str, data: bytes | None = ...) -> _UrlopenRet | None: ... # undocumented - def retry_https_basic_auth(self, url: str, realm: str, data: bytes | None = ...) -> _UrlopenRet | None: ... # undocumented - def retry_proxy_http_basic_auth( - self, url: str, realm: str, data: bytes | None = ... - ) -> _UrlopenRet | None: ... # undocumented - def retry_proxy_https_basic_auth( - self, url: str, realm: str, data: bytes | None = ... - ) -> _UrlopenRet | None: ... # undocumented +if sys.version_info < (3, 14): + @deprecated("Deprecated since Python 3.3; removed in Python 3.14. Use newer `urlopen` functions and methods.") + class URLopener: + version: ClassVar[str] + def __init__(self, proxies: dict[str, str] | None = None, **x509: str) -> None: ... + def open(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... + def open_unknown(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... + def retrieve( + self, + url: str, + filename: str | None = None, + reporthook: Callable[[int, int, int], object] | None = None, + data: ReadableBuffer | None = None, + ) -> tuple[str, Message | None]: ... + def addheader(self, *args: tuple[str, str]) -> None: ... # undocumented + def cleanup(self) -> None: ... # undocumented + def close(self) -> None: ... # undocumented + def http_error( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = None + ) -> _UrlopenRet: ... # undocumented + def http_error_default( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage + ) -> _UrlopenRet: ... # undocumented + def open_data(self, url: str, data: ReadableBuffer | None = None) -> addinfourl: ... # undocumented + def open_file(self, url: str) -> addinfourl: ... # undocumented + def open_ftp(self, url: str) -> addinfourl: ... # undocumented + def open_http(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... # undocumented + def open_https(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... # undocumented + def open_local_file(self, url: str) -> addinfourl: ... # undocumented + def open_unknown_proxy(self, proxy: str, fullurl: str, data: ReadableBuffer | None = None) -> None: ... # undocumented + def __del__(self) -> None: ... + + @deprecated("Deprecated since Python 3.3; removed in Python 3.14. Use newer `urlopen` functions and methods.") + class FancyURLopener(URLopener): + def prompt_user_passwd(self, host: str, realm: str) -> tuple[str, str]: ... + def get_user_passwd(self, host: str, realm: str, clear_cache: int = 0) -> tuple[str, str]: ... # undocumented + def http_error_301( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_302( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_303( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_307( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + if sys.version_info >= (3, 11): + def http_error_308( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + + def http_error_401( + self, + url: str, + fp: IO[bytes], + errcode: int, + errmsg: str, + headers: HTTPMessage, + data: ReadableBuffer | None = None, + retry: bool = False, + ) -> _UrlopenRet | None: ... # undocumented + def http_error_407( + self, + url: str, + fp: IO[bytes], + errcode: int, + errmsg: str, + headers: HTTPMessage, + data: ReadableBuffer | None = None, + retry: bool = False, + ) -> _UrlopenRet | None: ... # undocumented + def http_error_default( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage + ) -> addinfourl: ... # undocumented + def redirect_internal( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None + ) -> _UrlopenRet | None: ... # undocumented + def retry_http_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented + def retry_https_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented + def retry_proxy_http_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented + def retry_proxy_https_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented diff --git a/stdlib/urllib/response.pyi b/stdlib/urllib/response.pyi index 647ebf874432..459b9d1bbdda 100644 --- a/stdlib/urllib/response.pyi +++ b/stdlib/urllib/response.pyi @@ -1,43 +1,29 @@ -import sys -from _typeshed import Self +import tempfile +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable from email.message import Message from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Tuple, Type, TypeVar +from typing import IO, Any +from typing_extensions import deprecated -_AIUT = TypeVar("_AIUT", bound=addbase) +__all__ = ["addbase", "addclosehook", "addinfo", "addinfourl"] -class addbase(BinaryIO): +class addbase(tempfile._TemporaryFileWrapper[bytes]): fp: IO[bytes] def __init__(self, fp: IO[bytes]) -> None: ... - def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... - def __iter__(self: _AIUT) -> _AIUT: ... - def __next__(self) -> bytes: ... - def close(self) -> None: ... # These methods don't actually exist, but the class inherits at runtime from # tempfile._TemporaryFileWrapper, which uses __getattr__ to delegate to the # underlying file object. To satisfy the BinaryIO interface, we pretend that this # class has these additional methods. - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def read(self, n: int = ...) -> bytes: ... - def readable(self) -> bool: ... - def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> list[bytes]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def seekable(self) -> bool: ... - def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... - def writable(self) -> bool: ... - def write(self, s: bytes) -> int: ... - def writelines(self, lines: Iterable[bytes]) -> None: ... + def write(self, s: ReadableBuffer) -> int: ... + def writelines(self, lines: Iterable[ReadableBuffer]) -> None: ... class addclosehook(addbase): closehook: Callable[..., object] - hookargs: Tuple[Any, ...] + hookargs: tuple[Any, ...] def __init__(self, fp: IO[bytes], closehook: Callable[..., object], *hookargs: Any) -> None: ... class addinfo(addbase): @@ -47,10 +33,13 @@ class addinfo(addbase): class addinfourl(addinfo): url: str - code: int | None - if sys.version_info >= (3, 9): - @property - def status(self) -> int | None: ... - def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = ...) -> None: ... + code: int | None # Deprecated since Python 3.9. Use `addinfourl.status` attribute instead. + @property + def status(self) -> int | None: ... + def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = None) -> None: ... + @deprecated("Deprecated since Python 3.9. Use `addinfourl.url` attribute instead.") def geturl(self) -> str: ... + @deprecated("Deprecated since Python 3.9. Use `addinfourl.headers` attribute instead.") + def info(self) -> Message: ... + @deprecated("Deprecated since Python 3.9. Use `addinfourl.status` attribute instead.") def getcode(self) -> int | None: ... diff --git a/stdlib/urllib/robotparser.pyi b/stdlib/urllib/robotparser.pyi index 361126327993..14ceef550dab 100644 --- a/stdlib/urllib/robotparser.pyi +++ b/stdlib/urllib/robotparser.pyi @@ -1,12 +1,14 @@ -import sys -from typing import Iterable, NamedTuple +from collections.abc import Iterable +from typing import NamedTuple -class _RequestRate(NamedTuple): +__all__ = ["RobotFileParser"] + +class RequestRate(NamedTuple): requests: int seconds: int class RobotFileParser: - def __init__(self, url: str = ...) -> None: ... + def __init__(self, url: str = "") -> None: ... def set_url(self, url: str) -> None: ... def read(self) -> None: ... def parse(self, lines: Iterable[str]) -> None: ... @@ -14,6 +16,5 @@ class RobotFileParser: def mtime(self) -> int: ... def modified(self) -> None: ... def crawl_delay(self, useragent: str) -> str | None: ... - def request_rate(self, useragent: str) -> _RequestRate | None: ... - if sys.version_info >= (3, 8): - def site_maps(self) -> list[str] | None: ... + def request_rate(self, useragent: str) -> RequestRate | None: ... + def site_maps(self) -> list[str] | None: ... diff --git a/stdlib/uu.pyi b/stdlib/uu.pyi index aacd458c02c7..62bf6cb05f59 100644 --- a/stdlib/uu.pyi +++ b/stdlib/uu.pyi @@ -1,16 +1,12 @@ -import sys -from typing import BinaryIO, Union +from typing import BinaryIO, TypeAlias -_File = Union[str, BinaryIO] +__all__ = ["Error", "encode", "decode"] -class Error(Exception): ... - -if sys.version_info >= (3, 7): - def encode( - in_file: _File, out_file: _File, name: str | None = ..., mode: int | None = ..., *, backtick: bool = ... - ) -> None: ... +_File: TypeAlias = str | BinaryIO -else: - def encode(in_file: _File, out_file: _File, name: str | None = ..., mode: int | None = ...) -> None: ... +class Error(Exception): ... -def decode(in_file: _File, out_file: _File | None = ..., mode: int | None = ..., quiet: int = ...) -> None: ... +def encode( + in_file: _File, out_file: _File, name: str | None = None, mode: int | None = None, *, backtick: bool = False +) -> None: ... +def decode(in_file: _File, out_file: _File | None = None, mode: int | None = None, quiet: bool = False) -> None: ... diff --git a/stdlib/uuid.pyi b/stdlib/uuid.pyi index da13d819fbdf..1b5d0c1fbf5a 100644 --- a/stdlib/uuid.pyi +++ b/stdlib/uuid.pyi @@ -1,93 +1,106 @@ +import builtins import sys -from typing import Any, Tuple +from _typeshed import Unused +from enum import Enum +from typing import Final, TypeAlias +from typing_extensions import LiteralString, Never -# Because UUID has properties called int and bytes we need to rename these temporarily. -_Int = int -_Bytes = bytes -_FieldsType = Tuple[int, int, int, int, int, int] +_FieldsType: TypeAlias = tuple[int, int, int, int, int, int] -if sys.version_info >= (3, 7): - from enum import Enum - class SafeUUID(Enum): - safe: int - unsafe: int - unknown: None +class SafeUUID(Enum): + safe = 0 + unsafe = -1 + unknown = None class UUID: - if sys.version_info >= (3, 7): - def __init__( - self, - hex: str | None = ..., - bytes: _Bytes | None = ..., - bytes_le: _Bytes | None = ..., - fields: _FieldsType | None = ..., - int: _Int | None = ..., - version: _Int | None = ..., - *, - is_safe: SafeUUID = ..., - ) -> None: ... - @property - def is_safe(self) -> SafeUUID: ... - else: - def __init__( - self, - hex: str | None = ..., - bytes: _Bytes | None = ..., - bytes_le: _Bytes | None = ..., - fields: _FieldsType | None = ..., - int: _Int | None = ..., - version: _Int | None = ..., - ) -> None: ... + __slots__ = ("int", "is_safe", "__weakref__") + is_safe: Final[SafeUUID] + int: Final[builtins.int] + + def __init__( + self, + hex: str | None = None, + bytes: builtins.bytes | None = None, + bytes_le: builtins.bytes | None = None, + fields: _FieldsType | None = None, + int: builtins.int | None = None, + version: builtins.int | None = None, + *, + is_safe: SafeUUID = SafeUUID.unknown, + ) -> None: ... @property - def bytes(self) -> _Bytes: ... + def bytes(self) -> builtins.bytes: ... @property - def bytes_le(self) -> _Bytes: ... + def bytes_le(self) -> builtins.bytes: ... @property - def clock_seq(self) -> _Int: ... + def clock_seq(self) -> builtins.int: ... @property - def clock_seq_hi_variant(self) -> _Int: ... + def clock_seq_hi_variant(self) -> builtins.int: ... @property - def clock_seq_low(self) -> _Int: ... + def clock_seq_low(self) -> builtins.int: ... @property def fields(self) -> _FieldsType: ... @property def hex(self) -> str: ... @property - def int(self) -> _Int: ... - @property - def node(self) -> _Int: ... + def node(self) -> builtins.int: ... @property - def time(self) -> _Int: ... + def time(self) -> builtins.int: ... @property - def time_hi_version(self) -> _Int: ... + def time_hi_version(self) -> builtins.int: ... @property - def time_low(self) -> _Int: ... + def time_low(self) -> builtins.int: ... @property - def time_mid(self) -> _Int: ... + def time_mid(self) -> builtins.int: ... @property def urn(self) -> str: ... @property def variant(self) -> str: ... @property - def version(self) -> _Int | None: ... - def __int__(self) -> _Int: ... - def __eq__(self, other: Any) -> bool: ... - def __lt__(self, other: Any) -> bool: ... - def __le__(self, other: Any) -> bool: ... - def __gt__(self, other: Any) -> bool: ... - def __ge__(self, other: Any) -> bool: ... + def version(self) -> builtins.int | None: ... + def __int__(self) -> builtins.int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: UUID) -> bool: ... + def __le__(self, other: UUID) -> bool: ... + def __gt__(self, other: UUID) -> bool: ... + def __ge__(self, other: UUID) -> bool: ... + def __hash__(self) -> builtins.int: ... + def __setattr__(self, name: Unused, value: Unused) -> Never: ... def getnode() -> int: ... -def uuid1(node: _Int | None = ..., clock_seq: _Int | None = ...) -> UUID: ... -def uuid3(namespace: UUID, name: str) -> UUID: ... +def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: ... + +if sys.version_info >= (3, 14): + def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID: ... + def uuid7() -> UUID: ... + def uuid8(a: int | None = None, b: int | None = None, c: int | None = None) -> UUID: ... + +if sys.version_info >= (3, 12): + def uuid3(namespace: UUID, name: str | bytes) -> UUID: ... + +else: + def uuid3(namespace: UUID, name: str) -> UUID: ... + def uuid4() -> UUID: ... -def uuid5(namespace: UUID, name: str) -> UUID: ... -NAMESPACE_DNS: UUID -NAMESPACE_URL: UUID -NAMESPACE_OID: UUID -NAMESPACE_X500: UUID -RESERVED_NCS: str -RFC_4122: str -RESERVED_MICROSOFT: str -RESERVED_FUTURE: str +if sys.version_info >= (3, 12): + def uuid5(namespace: UUID, name: str | bytes) -> UUID: ... + +else: + def uuid5(namespace: UUID, name: str) -> UUID: ... + +if sys.version_info >= (3, 14): + NIL: Final[UUID] + MAX: Final[UUID] + +NAMESPACE_DNS: Final[UUID] +NAMESPACE_URL: Final[UUID] +NAMESPACE_OID: Final[UUID] +NAMESPACE_X500: Final[UUID] +RESERVED_NCS: Final[LiteralString] +RFC_4122: Final[LiteralString] +RESERVED_MICROSOFT: Final[LiteralString] +RESERVED_FUTURE: Final[LiteralString] + +if sys.version_info >= (3, 12): + def main() -> None: ... diff --git a/stdlib/venv/__init__.pyi b/stdlib/venv/__init__.pyi index 7650e87d98b4..14db88523dba 100644 --- a/stdlib/venv/__init__.pyi +++ b/stdlib/venv/__init__.pyi @@ -1,10 +1,13 @@ +import logging import sys from _typeshed import StrOrBytesPath +from collections.abc import Iterable, Sequence from types import SimpleNamespace -from typing import Sequence +from typing import Final -if sys.version_info >= (3, 9): - CORE_VENV_DEPS: tuple[str, ...] +logger: logging.Logger + +CORE_VENV_DEPS: Final[tuple[str, ...]] class EnvBuilder: system_site_packages: bool @@ -14,33 +17,37 @@ class EnvBuilder: with_pip: bool prompt: str | None - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 13): def __init__( self, - system_site_packages: bool = ..., - clear: bool = ..., - symlinks: bool = ..., - upgrade: bool = ..., - with_pip: bool = ..., - prompt: str | None = ..., - upgrade_deps: bool = ..., + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + upgrade: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, + *, + scm_ignore_files: Iterable[str] = ..., ) -> None: ... else: def __init__( self, - system_site_packages: bool = ..., - clear: bool = ..., - symlinks: bool = ..., - upgrade: bool = ..., - with_pip: bool = ..., - prompt: str | None = ..., + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + upgrade: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, ) -> None: ... + def create(self, env_dir: StrOrBytesPath) -> None: ... def clear_directory(self, path: StrOrBytesPath) -> None: ... # undocumented def ensure_directories(self, env_dir: StrOrBytesPath) -> SimpleNamespace: ... def create_configuration(self, context: SimpleNamespace) -> None: ... def symlink_or_copy( - self, src: StrOrBytesPath, dst: StrOrBytesPath, relative_symlinks_ok: bool = ... + self, src: StrOrBytesPath, dst: StrOrBytesPath, relative_symlinks_ok: bool = False ) -> None: ... # undocumented def setup_python(self, context: SimpleNamespace) -> None: ... def _setup_pip(self, context: SimpleNamespace) -> None: ... # undocumented @@ -48,28 +55,32 @@ class EnvBuilder: def post_setup(self, context: SimpleNamespace) -> None: ... def replace_variables(self, text: str, context: SimpleNamespace) -> str: ... # undocumented def install_scripts(self, context: SimpleNamespace, path: str) -> None: ... - if sys.version_info >= (3, 9): - def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... + def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... + if sys.version_info >= (3, 13): + def create_git_ignore_file(self, context: SimpleNamespace) -> None: ... -if sys.version_info >= (3, 9): +if sys.version_info >= (3, 13): def create( env_dir: StrOrBytesPath, - system_site_packages: bool = ..., - clear: bool = ..., - symlinks: bool = ..., - with_pip: bool = ..., - prompt: str | None = ..., - upgrade_deps: bool = ..., + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, + *, + scm_ignore_files: Iterable[str] = ..., ) -> None: ... else: def create( env_dir: StrOrBytesPath, - system_site_packages: bool = ..., - clear: bool = ..., - symlinks: bool = ..., - with_pip: bool = ..., - prompt: str | None = ..., + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, ) -> None: ... -def main(args: Sequence[str] | None = ...) -> None: ... +def main(args: Sequence[str] | None = None) -> None: ... diff --git a/stdlib/warnings.pyi b/stdlib/warnings.pyi index b1c9f4dda8ed..e17b6e3a25b3 100644 --- a/stdlib/warnings.pyi +++ b/stdlib/warnings.pyi @@ -1,62 +1,146 @@ +import re +import sys from _warnings import warn as warn, warn_explicit as warn_explicit +from collections.abc import Sequence from types import ModuleType, TracebackType -from typing import Any, Sequence, TextIO, Type, overload -from typing_extensions import Literal +from typing import Any, Generic, Literal, TextIO, TypeAlias, overload +from typing_extensions import LiteralString, TypeVar -_ActionKind = Literal["default", "error", "ignore", "always", "module", "once"] +__all__ = [ + "warn", + "warn_explicit", + "showwarning", + "formatwarning", + "filterwarnings", + "simplefilter", + "resetwarnings", + "catch_warnings", +] -filters: Sequence[tuple[str, str | None, Type[Warning], str | None, int]] # undocumented, do not mutate +if sys.version_info >= (3, 13): + __all__ += ["deprecated"] + +_T = TypeVar("_T") +_W_co = TypeVar("_W_co", bound=list[WarningMessage] | None, default=list[WarningMessage] | None, covariant=True) + +if sys.version_info >= (3, 14): + _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] +else: + _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "all", "module", "once"] +filters: Sequence[ + tuple[str, re.Pattern[str] | None, type[Warning] | tuple[type[Warning], ...], re.Pattern[str] | None, int] +] # undocumented, do not mutate def showwarning( - message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, ) -> None: ... -def formatwarning(message: Warning | str, category: Type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... +def formatwarning( + message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = None +) -> str: ... def filterwarnings( - action: _ActionKind, - message: str = ..., - category: Type[Warning] = ..., - module: str = ..., - lineno: int = ..., - append: bool = ..., + action: _ActionKind, message: str = "", category: type[Warning] = ..., module: str = "", lineno: int = 0, append: bool = False +) -> None: ... +def simplefilter( + action: _ActionKind, category: type[Warning] | tuple[type[Warning], ...] = ..., lineno: int = 0, append: bool = False ) -> None: ... -def simplefilter(action: _ActionKind, category: Type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... def resetwarnings() -> None: ... class _OptionError(Exception): ... class WarningMessage: message: Warning | str - category: Type[Warning] + category: type[Warning] filename: str lineno: int file: TextIO | None line: str | None source: Any | None - def __init__( - self, - message: Warning | str, - category: Type[Warning], - filename: str, - lineno: int, - file: TextIO | None = ..., - line: str | None = ..., - source: Any | None = ..., - ) -> None: ... + if sys.version_info >= (3, 15): + module: str | None + if sys.version_info >= (3, 15): + def __init__( + self, + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, + source: Any | None = None, + module: str | None = None, + ) -> None: ... -class catch_warnings: - @overload - def __new__(cls, *, record: Literal[False] = ..., module: ModuleType | None = ...) -> _catch_warnings_without_records: ... - @overload - def __new__(cls, *, record: Literal[True], module: ModuleType | None = ...) -> _catch_warnings_with_records: ... - @overload - def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... - def __enter__(self) -> list[WarningMessage] | None: ... + else: + def __init__( + self, + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, + source: Any | None = None, + ) -> None: ... + +class catch_warnings(Generic[_W_co]): + if sys.version_info >= (3, 11): + @overload + def __init__( + self: catch_warnings[None], + *, + record: Literal[False] = False, + module: ModuleType | None = None, + action: _ActionKind | None = None, + category: type[Warning] | tuple[type[Warning], ...] = ..., + lineno: int = 0, + append: bool = False, + ) -> None: ... + @overload + def __init__( + self: catch_warnings[list[WarningMessage]], + *, + record: Literal[True], + module: ModuleType | None = None, + action: _ActionKind | None = None, + category: type[Warning] | tuple[type[Warning], ...] = ..., + lineno: int = 0, + append: bool = False, + ) -> None: ... + @overload + def __init__( + self, + *, + record: bool, + module: ModuleType | None = None, + action: _ActionKind | None = None, + category: type[Warning] | tuple[type[Warning], ...] = ..., + lineno: int = 0, + append: bool = False, + ) -> None: ... + else: + @overload + def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None: ... + @overload + def __init__( + self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None + ) -> None: ... + @overload + def __init__(self, *, record: bool, module: ModuleType | None = None) -> None: ... + + def __enter__(self) -> _W_co: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... -class _catch_warnings_without_records(catch_warnings): - def __enter__(self) -> None: ... - -class _catch_warnings_with_records(catch_warnings): - def __enter__(self) -> list[WarningMessage]: ... +if sys.version_info >= (3, 13): + class deprecated: + message: LiteralString + category: type[Warning] | None + stacklevel: int + def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... + def __call__(self, arg: _T, /) -> _T: ... diff --git a/stdlib/wave.pyi b/stdlib/wave.pyi index 3ce1b88a6835..8ec5ce8154cd 100644 --- a/stdlib/wave.pyi +++ b/stdlib/wave.pyi @@ -1,12 +1,23 @@ import sys -from _typeshed import Self -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Union +from _typeshed import ReadableBuffer, StrOrBytesPath, Unused +from typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Never, Self, deprecated -_File = Union[str, IO[bytes]] +__all__ = ["open", "Error", "Wave_read", "Wave_write"] +if sys.version_info >= (3, 15): + __all__ += ["WAVE_FORMAT_PCM", "WAVE_FORMAT_IEEE_FLOAT", "WAVE_FORMAT_EXTENSIBLE"] + +if sys.version_info >= (3, 15): + _File: TypeAlias = StrOrBytesPath | IO[bytes] +else: + _File: TypeAlias = str | IO[bytes] class Error(Exception): ... -WAVE_FORMAT_PCM: int +WAVE_FORMAT_PCM: Final = 0x0001 +if sys.version_info >= (3, 15): + WAVE_FORMAT_IEEE_FLOAT: Final = 0x0003 + WAVE_FORMAT_EXTENSIBLE: Final = 0xFFFE class _wave_params(NamedTuple): nchannels: int @@ -18,8 +29,9 @@ class _wave_params(NamedTuple): class Wave_read: def __init__(self, f: _File) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... def getfp(self) -> BinaryIO | None: ... def rewind(self) -> None: ... def close(self) -> None: ... @@ -28,42 +40,66 @@ class Wave_read: def getnframes(self) -> int: ... def getsampwidth(self) -> int: ... def getframerate(self) -> int: ... + if sys.version_info >= (3, 15): + def getformat(self) -> int: ... + def getcomptype(self) -> str: ... def getcompname(self) -> str: ... def getparams(self) -> _wave_params: ... - def getmarkers(self) -> None: ... - def getmark(self, id: Any) -> NoReturn: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated; removed in Python 3.15.") + def getmarkers(self) -> None: ... + @deprecated("Deprecated; removed in Python 3.15.") + def getmark(self, id: Any) -> Never: ... + def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes: ... class Wave_write: def __init__(self, f: _File) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... def setsampwidth(self, sampwidth: int) -> None: ... def getsampwidth(self) -> int: ... def setframerate(self, framerate: float) -> None: ... def getframerate(self) -> int: ... + if sys.version_info >= (3, 15): + def setformat(self, format: int) -> None: ... + def getformat(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... def getnframes(self) -> int: ... def setcomptype(self, comptype: str, compname: str) -> None: ... def getcomptype(self) -> str: ... def getcompname(self) -> str: ... - def setparams(self, params: _wave_params) -> None: ... + if sys.version_info >= (3, 15): + def setparams( + self, params: _wave_params | tuple[int, int, int, int, str, str] | tuple[int, int, int, int, str, str, int] + ) -> None: ... + else: + def setparams(self, params: _wave_params | tuple[int, int, int, int, str, str]) -> None: ... + def getparams(self) -> _wave_params: ... - def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... - def getmark(self, id: Any) -> NoReturn: ... - def getmarkers(self) -> None: ... + + if sys.version_info < (3, 15): + @deprecated("Deprecated; removed in Python 3.15.") + def setmark(self, id: Any, pos: Any, name: Any) -> Never: ... + @deprecated("Deprecated; removed in Python 3.15.") + def getmark(self, id: Any) -> Never: ... + @deprecated("Deprecated; removed in Python 3.15.") + def getmarkers(self) -> None: ... + def tell(self) -> int: ... - # should be any bytes-like object after 3.4, but we don't have a type for that - def writeframesraw(self, data: bytes) -> None: ... - def writeframes(self, data: bytes) -> None: ... + def writeframesraw(self, data: ReadableBuffer) -> None: ... + def writeframes(self, data: ReadableBuffer) -> None: ... def close(self) -> None: ... -# Returns a Wave_read if mode is rb and Wave_write if mode is wb -def open(f: _File, mode: str | None = ...) -> Any: ... - -if sys.version_info < (3, 9): - openfp = open +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Wave_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Wave_write: ... +@overload +def open(f: _File, mode: str | None = None) -> Any: ... diff --git a/stdlib/weakref.pyi b/stdlib/weakref.pyi index 16ebba39ef17..e81052de7d26 100644 --- a/stdlib/weakref.pyi +++ b/stdlib/weakref.pyi @@ -1,87 +1,217 @@ +from _typeshed import SupportsKeysAndGetItem +from _weakref import getweakrefcount as getweakrefcount, getweakrefs as getweakrefs, proxy as proxy from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, Tuple, Type, TypeVar, overload - -from _weakref import ( - CallableProxyType as CallableProxyType, - ProxyType as ProxyType, - ReferenceType as ReferenceType, - getweakrefcount as getweakrefcount, - getweakrefs as getweakrefs, - proxy as proxy, - ref as ref, -) - -_S = TypeVar("_S") +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping +from types import GenericAlias +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, final, overload +from typing_extensions import Self, disjoint_base + +__all__ = [ + "ref", + "proxy", + "getweakrefcount", + "getweakrefs", + "WeakKeyDictionary", + "ReferenceType", + "ProxyType", + "CallableProxyType", + "ProxyTypes", + "WeakValueDictionary", + "WeakSet", + "WeakMethod", + "finalize", +] + _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") _CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +ProxyTypes: tuple[type[Any], ...] + +# These classes are implemented in C and imported from _weakref at runtime. However, +# they consider themselves to live in the weakref module for sys.version_info >= (3, 11), +# so defining their stubs here means we match their __module__ value. +# Prior to 3.11 they did not declare a module for themselves and ended up looking like they +# came from the builtin module at runtime, which was just wrong, and we won't attempt to +# duplicate that. + +@final +class CallableProxyType(Generic[_CallableT]): # "weakcallableproxy" + def __eq__(self, value: object, /) -> bool: ... + def __getattr__(self, attr: str) -> Any: ... + __call__: _CallableT + __hash__: ClassVar[None] # type: ignore[assignment] + +@final +class ProxyType(Generic[_T]): # "weakproxy" + def __eq__(self, value: object, /) -> bool: ... + def __getattr__(self, attr: str) -> Any: ... + __hash__: ClassVar[None] # type: ignore[assignment] -ProxyTypes: Tuple[Type[Any], ...] +@disjoint_base +class ReferenceType(Generic[_T]): # "weakref" + __callback__: Callable[[Self], Any] + def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ... + def __call__(self) -> _T | None: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class WeakMethod(ref[_CallableT], Generic[_CallableT]): - def __new__(cls, meth: _CallableT, callback: Callable[[_CallableT], object] | None = ...) -> WeakMethod[_CallableT]: ... +ref = ReferenceType + +# everything below here is implemented in weakref.py + +class WeakMethod(ref[_CallableT]): + __slots__ = ("_func_ref", "_meth_type", "_alive", "__weakref__") + def __new__(cls, meth: _CallableT, callback: Callable[[Self], Any] | None = None) -> Self: ... def __call__(self) -> _CallableT | None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__( + self: WeakValueDictionary[_KT, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], + /, + ) -> None: ... + @overload + def __init__( + self: WeakValueDictionary[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (), + /, + **kwargs: _VT, + ) -> None: ... + def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __contains__(self, o: object) -> bool: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... + __copy__ = copy + def __deepcopy__(self, memo: Any) -> Self: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... - def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + @overload def pop(self, key: _KT) -> _VT: ... @overload - def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + @overload + def update(self, other: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... + @overload + def update(self, other: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... + @overload + def update(self, other: None = None, /, **kwargs: _VT) -> None: ... + + def __or__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + + # WeakValueDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class KeyedRef(ref[_T], Generic[_KT, _T]): + __slots__ = ("key",) key: _KT - # This __new__ method uses a non-standard name for the "cls" parameter - def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... # type: ignore - def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... + def __new__(type, ob: _T, callback: Callable[[Self], Any], key: _KT) -> Self: ... + def __init__(self, ob: _T, callback: Callable[[Self], Any], key: _KT) -> None: ... class WeakKeyDictionary(MutableMapping[_KT, _VT]): @overload - def __init__(self, dict: None = ...) -> None: ... + def __init__(self, dict: None = None) -> None: ... @overload def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __contains__(self, o: object) -> bool: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... + __copy__ = copy + def __deepcopy__(self, memo: Any) -> Self: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def keyrefs(self) -> list[ref[_KT]]: ... - def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + + # Keep WeakKeyDictionary.setdefault in line with MutableMapping.setdefault, modulo positional-only differences + @overload + def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + @overload def pop(self, key: _KT) -> _VT: ... @overload - def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + @overload + def update(self, dict: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... + @overload + def update(self, dict: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... + @overload + def update(self, dict: None = None, /, **kwargs: _VT) -> None: ... + + def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + + # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + +class finalize(Generic[_P, _T]): + __slots__ = () + def __init__(self, obj: _T, func: Callable[_P, Any], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def __call__(self, _: Any = None) -> Any | None: ... + def detach(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: ... + def peek(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: ... + @property + def alive(self) -> bool: ... -class finalize: - def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, _: Any = ...) -> Any | None: ... - def detach(self) -> tuple[Any, Any, Tuple[Any, ...], dict[str, Any]] | None: ... - def peek(self) -> tuple[Any, Any, Tuple[Any, ...], dict[str, Any]] | None: ... - alive: bool - atexit: bool + @property + def atexit(self) -> bool: ... + @atexit.setter + def atexit(self, value: bool) -> None: ... diff --git a/stdlib/webbrowser.pyi b/stdlib/webbrowser.pyi index 459d886ac930..e2c63ee35d74 100644 --- a/stdlib/webbrowser.pyi +++ b/stdlib/webbrowser.pyi @@ -1,38 +1,40 @@ import sys -from typing import Callable, Sequence +from abc import abstractmethod +from collections.abc import Callable, Sequence +from typing import Literal +from typing_extensions import deprecated -class Error(Exception): ... - -if sys.version_info >= (3, 7): - def register( - name: str, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = ..., *, preferred: bool = ... - ) -> None: ... +__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] -else: - def register( - name: str, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = ..., update_tryorder: int = ... - ) -> None: ... +class Error(Exception): ... -def get(using: str | None = ...) -> BaseBrowser: ... -def open(url: str, new: int = ..., autoraise: bool = ...) -> bool: ... +def register( + name: str, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = None, *, preferred: bool = False +) -> None: ... +def get(using: str | None = None) -> BaseBrowser: ... +def open(url: str, new: int = 0, autoraise: bool = True) -> bool: ... def open_new(url: str) -> bool: ... def open_new_tab(url: str) -> bool: ... +def register_standard_browsers() -> None: ... class BaseBrowser: args: list[str] name: str basename: str - def __init__(self, name: str = ...) -> None: ... - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... + def __init__(self, name: str = "") -> None: ... + @abstractmethod + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... def open_new(self, url: str) -> bool: ... def open_new_tab(self, url: str) -> bool: ... class GenericBrowser(BaseBrowser): def __init__(self, name: str | Sequence[str]) -> None: ... + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... class BackgroundBrowser(GenericBrowser): ... class UnixBrowser(BaseBrowser): + def open(self, url: str, new: Literal[0, 1, 2] = 0, autoraise: bool = True) -> bool: ... # type: ignore[override] raise_opts: list[str] | None background: bool redirect_stdout: bool @@ -43,18 +45,49 @@ class UnixBrowser(BaseBrowser): class Mozilla(UnixBrowser): ... -class Galeon(UnixBrowser): - raise_opts: list[str] +if sys.version_info < (3, 12): + class Galeon(UnixBrowser): + raise_opts: list[str] + + class Grail(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... class Chrome(UnixBrowser): ... class Opera(UnixBrowser): ... class Elinks(UnixBrowser): ... -class Konqueror(BaseBrowser): ... -class Grail(BaseBrowser): ... + +class Konqueror(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... if sys.platform == "win32": - class WindowsDefault(BaseBrowser): ... + class WindowsDefault(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... if sys.platform == "darwin": - class MacOSX(BaseBrowser): ... - class MacOSXOSAScript(BaseBrowser): ... # In runtime this class does not have `name` and `basename` + if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13. Use `MacOSXOSAScript` instead.") + class MacOSX(BaseBrowser): + def __init__(self, name: str) -> None: ... + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + + if sys.version_info >= (3, 15): + class MacOS(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + + @deprecated("Deprecated since Python 3.15; will be removed in Python 3.17. Use `MacOS` instead.") + class MacOSXOSAScript(BaseBrowser): # In runtime this class does not have `name` and `basename` + if sys.version_info >= (3, 11): + def __init__(self, name: str = "default") -> None: ... + else: + def __init__(self, name: str) -> None: ... + + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + + else: + class MacOSXOSAScript(BaseBrowser): # In runtime this class does not have `name` and `basename` + if sys.version_info >= (3, 11): + def __init__(self, name: str = "default") -> None: ... + else: + def __init__(self, name: str) -> None: ... + + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... diff --git a/stdlib/winreg.pyi b/stdlib/winreg.pyi index 5fff1104e246..8a886112f8a1 100644 --- a/stdlib/winreg.pyi +++ b/stdlib/winreg.pyi @@ -1,101 +1,137 @@ -from _typeshed import Self +import sys +from _typeshed import ReadableBuffer, Unused from types import TracebackType -from typing import Any, Type, Union -from typing_extensions import final +from typing import Any, Final, Literal, TypeAlias, final, overload +from typing_extensions import Self -_KeyType = Union[HKEYType, int] +if sys.platform == "win32": + _KeyType: TypeAlias = HKEYType | int + def CloseKey(hkey: _KeyType, /) -> None: ... + def ConnectRegistry(computer_name: str | None, key: _KeyType, /) -> HKEYType: ... + def CreateKey(key: _KeyType, sub_key: str | None, /) -> HKEYType: ... + def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: ... + def DeleteKey(key: _KeyType, sub_key: str, /) -> None: ... + def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: ... + if sys.version_info >= (3, 15): + def DeleteTree(key: _KeyType, sub_key: str | None = None, /) -> None: ... -def CloseKey(__hkey: _KeyType) -> None: ... -def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... -def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... -def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = ..., access: int = ...) -> HKEYType: ... -def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... -def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... -def DeleteValue(__key: _KeyType, __value: str) -> None: ... -def EnumKey(__key: _KeyType, __index: int) -> str: ... -def EnumValue(__key: _KeyType, __index: int) -> tuple[str, Any, int]: ... -def ExpandEnvironmentStrings(__str: str) -> str: ... -def FlushKey(__key: _KeyType) -> None: ... -def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... -def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def QueryInfoKey(__key: _KeyType) -> tuple[int, int, int]: ... -def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... -def QueryValueEx(__key: _KeyType, __name: str) -> tuple[Any, int]: ... -def SaveKey(__key: _KeyType, __file_name: str) -> None: ... -def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... -def SetValueEx( - __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int -) -> None: ... # reserved is ignored -def DisableReflectionKey(__key: _KeyType) -> None: ... -def EnableReflectionKey(__key: _KeyType) -> None: ... -def QueryReflectionKey(__key: _KeyType) -> bool: ... + def DeleteValue(key: _KeyType, value: str, /) -> None: ... + def EnumKey(key: _KeyType, index: int, /) -> str: ... + def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: ... + def ExpandEnvironmentStrings(string: str, /) -> str: ... + def FlushKey(key: _KeyType, /) -> None: ... + def LoadKey(key: _KeyType, sub_key: str, file_name: str, /) -> None: ... + def OpenKey(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131097) -> HKEYType: ... + def OpenKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131097) -> HKEYType: ... + def QueryInfoKey(key: _KeyType, /) -> tuple[int, int, int]: ... + def QueryValue(key: _KeyType, sub_key: str | None, /) -> str: ... + def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: ... + def SaveKey(key: _KeyType, file_name: str, /) -> None: ... + def SetValue(key: _KeyType, sub_key: str | None, type: int, value: str, /) -> None: ... -HKEY_CLASSES_ROOT: int -HKEY_CURRENT_USER: int -HKEY_LOCAL_MACHINE: int -HKEY_USERS: int -HKEY_PERFORMANCE_DATA: int -HKEY_CURRENT_CONFIG: int -HKEY_DYN_DATA: int + @overload # type=REG_DWORD|REG_QWORD + def SetValueEx( + key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[4, 5], value: int | None, / + ) -> None: ... + @overload # type=REG_SZ|REG_EXPAND_SZ + def SetValueEx( + key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[1, 2], value: str | None, / + ) -> None: ... + @overload # type=REG_MULTI_SZ + def SetValueEx( + key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[7], value: list[str] | None, / + ) -> None: ... + @overload # type=REG_BINARY and everything else + def SetValueEx( + key: _KeyType, + value_name: str | None, + reserved: Unused, + type: Literal[0, 3, 8, 9, 10, 11], + value: ReadableBuffer | None, + /, + ) -> None: ... + @overload # Unknown or undocumented + def SetValueEx( + key: _KeyType, + value_name: str | None, + reserved: Unused, + type: int, + value: int | str | list[str] | ReadableBuffer | None, + /, + ) -> None: ... -KEY_ALL_ACCESS: int -KEY_WRITE: int -KEY_READ: int -KEY_EXECUTE: int -KEY_QUERY_VALUE: int -KEY_SET_VALUE: int -KEY_CREATE_SUB_KEY: int -KEY_ENUMERATE_SUB_KEYS: int -KEY_NOTIFY: int -KEY_CREATE_LINK: int + def DisableReflectionKey(key: _KeyType, /) -> None: ... + def EnableReflectionKey(key: _KeyType, /) -> None: ... + def QueryReflectionKey(key: _KeyType, /) -> bool: ... -KEY_WOW64_64KEY: int -KEY_WOW64_32KEY: int + HKEY_CLASSES_ROOT: Final[int] + HKEY_CURRENT_USER: Final[int] + HKEY_LOCAL_MACHINE: Final[int] + HKEY_USERS: Final[int] + HKEY_PERFORMANCE_DATA: Final[int] + HKEY_CURRENT_CONFIG: Final[int] + HKEY_DYN_DATA: Final[int] -REG_BINARY: int -REG_DWORD: int -REG_DWORD_LITTLE_ENDIAN: int -REG_DWORD_BIG_ENDIAN: int -REG_EXPAND_SZ: int -REG_LINK: int -REG_MULTI_SZ: int -REG_NONE: int -REG_QWORD: int -REG_QWORD_LITTLE_ENDIAN: int -REG_RESOURCE_LIST: int -REG_FULL_RESOURCE_DESCRIPTOR: int -REG_RESOURCE_REQUIREMENTS_LIST: int -REG_SZ: int + KEY_ALL_ACCESS: Final = 983103 + KEY_WRITE: Final = 131078 + KEY_READ: Final = 131097 + KEY_EXECUTE: Final = 131097 + KEY_QUERY_VALUE: Final = 1 + KEY_SET_VALUE: Final = 2 + KEY_CREATE_SUB_KEY: Final = 4 + KEY_ENUMERATE_SUB_KEYS: Final = 8 + KEY_NOTIFY: Final = 16 + KEY_CREATE_LINK: Final = 32 -REG_CREATED_NEW_KEY: int # undocumented -REG_LEGAL_CHANGE_FILTER: int # undocumented -REG_LEGAL_OPTION: int # undocumented -REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented -REG_NOTIFY_CHANGE_LAST_SET: int # undocumented -REG_NOTIFY_CHANGE_NAME: int # undocumented -REG_NOTIFY_CHANGE_SECURITY: int # undocumented -REG_NO_LAZY_FLUSH: int # undocumented -REG_OPENED_EXISTING_KEY: int # undocumented -REG_OPTION_BACKUP_RESTORE: int # undocumented -REG_OPTION_CREATE_LINK: int # undocumented -REG_OPTION_NON_VOLATILE: int # undocumented -REG_OPTION_OPEN_LINK: int # undocumented -REG_OPTION_RESERVED: int # undocumented -REG_OPTION_VOLATILE: int # undocumented -REG_REFRESH_HIVE: int # undocumented -REG_WHOLE_HIVE_VOLATILE: int # undocumented + KEY_WOW64_64KEY: Final = 256 + KEY_WOW64_32KEY: Final = 512 -error = OSError + REG_BINARY: Final = 3 + REG_DWORD: Final = 4 + REG_DWORD_LITTLE_ENDIAN: Final = 4 + REG_DWORD_BIG_ENDIAN: Final = 5 + REG_EXPAND_SZ: Final = 2 + REG_LINK: Final = 6 + REG_MULTI_SZ: Final = 7 + REG_NONE: Final = 0 + REG_QWORD: Final = 11 + REG_QWORD_LITTLE_ENDIAN: Final = 11 + REG_RESOURCE_LIST: Final = 8 + REG_FULL_RESOURCE_DESCRIPTOR: Final = 9 + REG_RESOURCE_REQUIREMENTS_LIST: Final = 10 + REG_SZ: Final = 1 -# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason -@final -class HKEYType: - def __bool__(self) -> bool: ... - def __int__(self) -> int: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def Close(self) -> None: ... - def Detach(self) -> int: ... + REG_CREATED_NEW_KEY: Final = 1 # undocumented + REG_LEGAL_CHANGE_FILTER: Final = 268435471 # undocumented + REG_LEGAL_OPTION: Final = 31 # undocumented + REG_NOTIFY_CHANGE_ATTRIBUTES: Final = 2 # undocumented + REG_NOTIFY_CHANGE_LAST_SET: Final = 4 # undocumented + REG_NOTIFY_CHANGE_NAME: Final = 1 # undocumented + REG_NOTIFY_CHANGE_SECURITY: Final = 8 # undocumented + REG_NO_LAZY_FLUSH: Final = 4 # undocumented + REG_OPENED_EXISTING_KEY: Final = 2 # undocumented + REG_OPTION_BACKUP_RESTORE: Final = 4 # undocumented + REG_OPTION_CREATE_LINK: Final = 2 # undocumented + REG_OPTION_NON_VOLATILE: Final = 0 # undocumented + REG_OPTION_OPEN_LINK: Final = 8 # undocumented + REG_OPTION_RESERVED: Final = 0 # undocumented + REG_OPTION_VOLATILE: Final = 1 # undocumented + REG_REFRESH_HIVE: Final = 2 # undocumented + REG_WHOLE_HIVE_VOLATILE: Final = 1 # undocumented + + error = OSError + + # Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason + @final + class HKEYType: + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> bool | None: ... + def Close(self) -> None: ... + def Detach(self) -> int: ... + def __hash__(self) -> int: ... + @property + def handle(self) -> int: ... diff --git a/stdlib/winsound.pyi b/stdlib/winsound.pyi index 3d79f3b043f2..9c7f314fd6ca 100644 --- a/stdlib/winsound.pyi +++ b/stdlib/winsound.pyi @@ -1,27 +1,40 @@ import sys -from typing import overload -from typing_extensions import Literal +from _typeshed import ReadableBuffer +from typing import Final, Literal, overload if sys.platform == "win32": - SND_FILENAME: int - SND_ALIAS: int - SND_LOOP: int - SND_MEMORY: int - SND_PURGE: int - SND_ASYNC: int - SND_NODEFAULT: int - SND_NOSTOP: int - SND_NOWAIT: int + SND_APPLICATION: Final = 128 + SND_FILENAME: Final = 131072 + SND_ALIAS: Final = 65536 + SND_LOOP: Final = 8 + SND_MEMORY: Final = 4 + SND_PURGE: Final = 64 + SND_ASYNC: Final = 1 + SND_NODEFAULT: Final = 2 + SND_NOSTOP: Final = 16 + SND_NOWAIT: Final = 8192 + if sys.version_info >= (3, 14): + SND_SENTRY: Final = 524288 + SND_SYNC: Final = 0 + SND_SYSTEM: Final = 2097152 + + MB_ICONASTERISK: Final = 64 + MB_ICONEXCLAMATION: Final = 48 + MB_ICONHAND: Final = 16 + MB_ICONQUESTION: Final = 32 + MB_OK: Final = 0 + if sys.version_info >= (3, 14): + MB_ICONERROR: Final = 16 + MB_ICONINFORMATION: Final = 64 + MB_ICONSTOP: Final = 16 + MB_ICONWARNING: Final = 48 - MB_ICONASTERISK: int - MB_ICONEXCLAMATION: int - MB_ICONHAND: int - MB_ICONQUESTION: int - MB_OK: int def Beep(frequency: int, duration: int) -> None: ... + # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible @overload - def PlaySound(sound: bytes | None, flags: Literal[4]) -> None: ... + def PlaySound(sound: ReadableBuffer | None, flags: Literal[4]) -> None: ... @overload - def PlaySound(sound: str | bytes | None, flags: int) -> None: ... - def MessageBeep(type: int = ...) -> None: ... + def PlaySound(sound: str | ReadableBuffer | None, flags: int) -> None: ... + + def MessageBeep(type: int = 0) -> None: ... diff --git a/stdlib/wsgiref/handlers.pyi b/stdlib/wsgiref/handlers.pyi index ac1e56b7664e..ebead540018e 100644 --- a/stdlib/wsgiref/handlers.pyi +++ b/stdlib/wsgiref/handlers.pyi @@ -1,12 +1,13 @@ +from _typeshed import OptExcInfo +from _typeshed.wsgi import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from abc import abstractmethod -from types import TracebackType -from typing import IO, Callable, MutableMapping, Optional, Tuple, Type +from collections.abc import Callable, MutableMapping +from typing import IO from .headers import Headers -from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper -_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +__all__ = ["BaseHandler", "SimpleHandler", "BaseCGIHandler", "CGIHandler", "IISCGIHandler", "read_environ"] def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: ... @@ -23,8 +24,8 @@ class BaseHandler: os_environ: MutableMapping[str, str] - wsgi_file_wrapper: Type[FileWrapper] | None - headers_class: Type[Headers] # undocumented + wsgi_file_wrapper: type[FileWrapper] | None + headers_class: type[Headers] # undocumented traceback_limit: int | None error_status: str @@ -37,7 +38,7 @@ class BaseHandler: def set_content_length(self) -> None: ... def cleanup_headers(self) -> None: ... def start_response( - self, status: str, headers: list[tuple[str, str]], exc_info: _exc_info | None = ... + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None ) -> Callable[[bytes], None]: ... def send_preamble(self) -> None: ... def write(self, data: bytes) -> None: ... @@ -47,7 +48,7 @@ class BaseHandler: def send_headers(self) -> None: ... def result_is_file(self) -> bool: ... def client_is_modern(self) -> bool: ... - def log_exception(self, exc_info: _exc_info) -> None: ... + def log_exception(self, exc_info: OptExcInfo) -> None: ... def handle_error(self) -> None: ... def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... @abstractmethod @@ -72,8 +73,8 @@ class SimpleHandler(BaseHandler): stdout: IO[bytes], stderr: ErrorStream, environ: MutableMapping[str, str], - multithread: bool = ..., - multiprocess: bool = ..., + multithread: bool = True, + multiprocess: bool = False, ) -> None: ... def get_stdin(self) -> InputStream: ... def get_stderr(self) -> ErrorStream: ... diff --git a/stdlib/wsgiref/headers.pyi b/stdlib/wsgiref/headers.pyi index 531a521d3824..6a0fb571a0d0 100644 --- a/stdlib/wsgiref/headers.pyi +++ b/stdlib/wsgiref/headers.pyi @@ -1,21 +1,24 @@ -from typing import List, Pattern, Tuple, overload +from re import Pattern +from typing import Final, TypeAlias, overload -_HeaderList = List[Tuple[str, str]] +_HeaderList: TypeAlias = list[tuple[str, str]] -tspecials: Pattern[str] # undocumented +tspecials: Final[Pattern[str]] # undocumented class Headers: - def __init__(self, headers: _HeaderList | None = ...) -> None: ... + def __init__(self, headers: _HeaderList | None = None) -> None: ... def __len__(self) -> int: ... def __setitem__(self, name: str, val: str) -> None: ... def __delitem__(self, name: str) -> None: ... def __getitem__(self, name: str) -> str | None: ... def __contains__(self, name: str) -> bool: ... def get_all(self, name: str) -> list[str]: ... + @overload def get(self, name: str, default: str) -> str: ... @overload - def get(self, name: str, default: str | None = ...) -> str | None: ... + def get(self, name: str, default: str | None = None) -> str | None: ... + def keys(self) -> list[str]: ... def values(self) -> list[str]: ... def items(self) -> _HeaderList: ... diff --git a/stdlib/wsgiref/simple_server.pyi b/stdlib/wsgiref/simple_server.pyi index 76d0b269793d..bdf58719c828 100644 --- a/stdlib/wsgiref/simple_server.pyi +++ b/stdlib/wsgiref/simple_server.pyi @@ -1,16 +1,17 @@ +from _typeshed.wsgi import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment from http.server import BaseHTTPRequestHandler, HTTPServer -from typing import Type, TypeVar, overload +from typing import Final, TypeVar, overload from .handlers import SimpleHandler -from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment -server_version: str # undocumented -sys_version: str # undocumented -software_version: str # undocumented +__all__ = ["WSGIServer", "WSGIRequestHandler", "demo_app", "make_server"] + +server_version: Final[str] # undocumented +sys_version: Final[str] # undocumented +software_version: Final[str] # undocumented class ServerHandler(SimpleHandler): # undocumented server_software: str - def close(self) -> None: ... class WSGIServer(HTTPServer): application: WSGIApplication | None @@ -23,15 +24,14 @@ class WSGIRequestHandler(BaseHTTPRequestHandler): server_version: str def get_environ(self) -> WSGIEnvironment: ... def get_stderr(self) -> ErrorStream: ... - def handle(self) -> None: ... def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... _S = TypeVar("_S", bound=WSGIServer) @overload -def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... +def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: type[WSGIRequestHandler] = ...) -> WSGIServer: ... @overload def make_server( - host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ... + host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ... ) -> _S: ... diff --git a/stdlib/wsgiref/types.pyi b/stdlib/wsgiref/types.pyi index c272ae67c391..b7fd99809856 100644 --- a/stdlib/wsgiref/types.pyi +++ b/stdlib/wsgiref/types.pyi @@ -1,3 +1,31 @@ -# Obsolete, use _typeshed.wsgi directly. +from _typeshed import OptExcInfo +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Protocol, TypeAlias -from _typeshed.wsgi import * +__all__ = ["StartResponse", "WSGIEnvironment", "WSGIApplication", "InputStream", "ErrorStream", "FileWrapper"] + +class StartResponse(Protocol): + def __call__( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., / + ) -> Callable[[bytes], object]: ... + +WSGIEnvironment: TypeAlias = dict[str, Any] +WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] + +class InputStream(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + def readline(self, size: int = ..., /) -> bytes: ... + def readlines(self, hint: int = ..., /) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... + +class ErrorStream(Protocol): + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... + def writelines(self, seq: list[str], /) -> object: ... + +class _Readable(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + # Optional: def close(self) -> object: ... + +class FileWrapper(Protocol): + def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/stdlib/wsgiref/util.pyi b/stdlib/wsgiref/util.pyi index c769c77d36e9..3966e17b0d28 100644 --- a/stdlib/wsgiref/util.pyi +++ b/stdlib/wsgiref/util.pyi @@ -1,21 +1,26 @@ import sys -from typing import IO, Any, Callable +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Callable +from typing import IO, Any -from .types import WSGIEnvironment +__all__ = ["FileWrapper", "guess_scheme", "application_uri", "request_uri", "shift_path_info", "setup_testing_defaults"] +if sys.version_info >= (3, 13): + __all__ += ["is_hop_by_hop"] class FileWrapper: filelike: IO[bytes] blksize: int close: Callable[[], None] # only exists if filelike.close exists - def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... + def __init__(self, filelike: IO[bytes], blksize: int = 8192) -> None: ... if sys.version_info < (3, 11): def __getitem__(self, key: Any) -> bytes: ... + def __iter__(self) -> FileWrapper: ... def __next__(self) -> bytes: ... def guess_scheme(environ: WSGIEnvironment) -> str: ... def application_uri(environ: WSGIEnvironment) -> str: ... -def request_uri(environ: WSGIEnvironment, include_query: bool = ...) -> str: ... +def request_uri(environ: WSGIEnvironment, include_query: bool = True) -> str: ... def shift_path_info(environ: WSGIEnvironment) -> str | None: ... def setup_testing_defaults(environ: WSGIEnvironment) -> None: ... def is_hop_by_hop(header_name: str) -> bool: ... diff --git a/stdlib/wsgiref/validate.pyi b/stdlib/wsgiref/validate.pyi index 68e22727bc73..ce3e79f341f9 100644 --- a/stdlib/wsgiref/validate.pyi +++ b/stdlib/wsgiref/validate.pyi @@ -1,5 +1,9 @@ from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication -from typing import Any, Callable, Iterable, Iterator, NoReturn +from collections.abc import Callable, Iterable, Iterator +from typing import Any, TypeAlias +from typing_extensions import Never + +__all__ = ["validator"] class WSGIWarning(Warning): ... @@ -11,8 +15,8 @@ class InputWrapper: def read(self, size: int) -> bytes: ... def readline(self, size: int = ...) -> bytes: ... def readlines(self, hint: int = ...) -> bytes: ... - def __iter__(self) -> Iterable[bytes]: ... - def close(self) -> NoReturn: ... + def __iter__(self) -> Iterator[bytes]: ... + def close(self) -> Never: ... class ErrorWrapper: errors: ErrorStream @@ -20,11 +24,13 @@ class ErrorWrapper: def write(self, s: str) -> None: ... def flush(self) -> None: ... def writelines(self, seq: Iterable[str]) -> None: ... - def close(self) -> NoReturn: ... + def close(self) -> Never: ... + +_WriterCallback: TypeAlias = Callable[[bytes], Any] class WriteWrapper: - writer: Callable[[bytes], Any] - def __init__(self, wsgi_writer: Callable[[bytes], Any]) -> None: ... + writer: _WriterCallback + def __init__(self, wsgi_writer: _WriterCallback) -> None: ... def __call__(self, s: bytes) -> None: ... class PartialIteratorWrapper: diff --git a/stdlib/xdrlib.pyi b/stdlib/xdrlib.pyi index f59843f8ee9d..78f3ecec8d78 100644 --- a/stdlib/xdrlib.pyi +++ b/stdlib/xdrlib.pyi @@ -1,4 +1,7 @@ -from typing import Callable, Sequence, TypeVar +from collections.abc import Callable, Sequence +from typing import TypeVar + +__all__ = ["Error", "Packer", "Unpacker", "ConversionError"] _T = TypeVar("_T") @@ -9,7 +12,6 @@ class Error(Exception): class ConversionError(Error): ... class Packer: - def __init__(self) -> None: ... def reset(self) -> None: ... def get_buffer(self) -> bytes: ... def get_buf(self) -> bytes: ... @@ -26,9 +28,9 @@ class Packer: def pack_string(self, s: bytes) -> None: ... def pack_opaque(self, s: bytes) -> None: ... def pack_bytes(self, s: bytes) -> None: ... - def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... - def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... - def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... + def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... + def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... class Unpacker: def __init__(self, data: bytes) -> None: ... diff --git a/stdlib/xml/__init__.pyi b/stdlib/xml/__init__.pyi index c524ac2b1cfc..969712fd20b0 100644 --- a/stdlib/xml/__init__.pyi +++ b/stdlib/xml/__init__.pyi @@ -1 +1,9 @@ -import xml.parsers as parsers +# At runtime, listing submodules in __all__ without them being imported is +# valid, and causes them to be included in a star import. See #6523 +import sys + +__all__ = ["dom", "parsers", "sax", "etree"] # ruff: ignore[undefined-export] # pyright: ignore[reportUnsupportedDunderAll] + +if sys.version_info >= (3, 15): + __all__ += ["is_valid_name"] # pyright: ignore[reportUnsupportedDunderAll] + from xml.utils import is_valid_name as is_valid_name, is_valid_text as is_valid_text diff --git a/stdlib/xml/dom/NodeFilter.pyi b/stdlib/xml/dom/NodeFilter.pyi index 80fb73d23433..7b301373f528 100644 --- a/stdlib/xml/dom/NodeFilter.pyi +++ b/stdlib/xml/dom/NodeFilter.pyi @@ -1,19 +1,22 @@ +from typing import Final +from xml.dom.minidom import Node + class NodeFilter: - FILTER_ACCEPT: int - FILTER_REJECT: int - FILTER_SKIP: int + FILTER_ACCEPT: Final = 1 + FILTER_REJECT: Final = 2 + FILTER_SKIP: Final = 3 - SHOW_ALL: int - SHOW_ELEMENT: int - SHOW_ATTRIBUTE: int - SHOW_TEXT: int - SHOW_CDATA_SECTION: int - SHOW_ENTITY_REFERENCE: int - SHOW_ENTITY: int - SHOW_PROCESSING_INSTRUCTION: int - SHOW_COMMENT: int - SHOW_DOCUMENT: int - SHOW_DOCUMENT_TYPE: int - SHOW_DOCUMENT_FRAGMENT: int - SHOW_NOTATION: int - def acceptNode(self, node) -> int: ... + SHOW_ALL: Final = 0xFFFFFFFF + SHOW_ELEMENT: Final = 0x00000001 + SHOW_ATTRIBUTE: Final = 0x00000002 + SHOW_TEXT: Final = 0x00000004 + SHOW_CDATA_SECTION: Final = 0x00000008 + SHOW_ENTITY_REFERENCE: Final = 0x00000010 + SHOW_ENTITY: Final = 0x00000020 + SHOW_PROCESSING_INSTRUCTION: Final = 0x00000040 + SHOW_COMMENT: Final = 0x00000080 + SHOW_DOCUMENT: Final = 0x00000100 + SHOW_DOCUMENT_TYPE: Final = 0x00000200 + SHOW_DOCUMENT_FRAGMENT: Final = 0x00000400 + SHOW_NOTATION: Final = 0x00000800 + def acceptNode(self, node: Node) -> int: ... diff --git a/stdlib/xml/dom/__init__.pyi b/stdlib/xml/dom/__init__.pyi index e5b91bf2a795..5dbb6c536f61 100644 --- a/stdlib/xml/dom/__init__.pyi +++ b/stdlib/xml/dom/__init__.pyi @@ -1,69 +1,101 @@ -from typing import Any +from typing import Any, Final, Literal from .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation class Node: - ELEMENT_NODE: int - ATTRIBUTE_NODE: int - TEXT_NODE: int - CDATA_SECTION_NODE: int - ENTITY_REFERENCE_NODE: int - ENTITY_NODE: int - PROCESSING_INSTRUCTION_NODE: int - COMMENT_NODE: int - DOCUMENT_NODE: int - DOCUMENT_TYPE_NODE: int - DOCUMENT_FRAGMENT_NODE: int - NOTATION_NODE: int + __slots__ = () + ELEMENT_NODE: Final = 1 + ATTRIBUTE_NODE: Final = 2 + TEXT_NODE: Final = 3 + CDATA_SECTION_NODE: Final = 4 + ENTITY_REFERENCE_NODE: Final = 5 + ENTITY_NODE: Final = 6 + PROCESSING_INSTRUCTION_NODE: Final = 7 + COMMENT_NODE: Final = 8 + DOCUMENT_NODE: Final = 9 + DOCUMENT_TYPE_NODE: Final = 10 + DOCUMENT_FRAGMENT_NODE: Final = 11 + NOTATION_NODE: Final = 12 # ExceptionCode -INDEX_SIZE_ERR: int -DOMSTRING_SIZE_ERR: int -HIERARCHY_REQUEST_ERR: int -WRONG_DOCUMENT_ERR: int -INVALID_CHARACTER_ERR: int -NO_DATA_ALLOWED_ERR: int -NO_MODIFICATION_ALLOWED_ERR: int -NOT_FOUND_ERR: int -NOT_SUPPORTED_ERR: int -INUSE_ATTRIBUTE_ERR: int -INVALID_STATE_ERR: int -SYNTAX_ERR: int -INVALID_MODIFICATION_ERR: int -NAMESPACE_ERR: int -INVALID_ACCESS_ERR: int -VALIDATION_ERR: int +INDEX_SIZE_ERR: Final = 1 +DOMSTRING_SIZE_ERR: Final = 2 +HIERARCHY_REQUEST_ERR: Final = 3 +WRONG_DOCUMENT_ERR: Final = 4 +INVALID_CHARACTER_ERR: Final = 5 +NO_DATA_ALLOWED_ERR: Final = 6 +NO_MODIFICATION_ALLOWED_ERR: Final = 7 +NOT_FOUND_ERR: Final = 8 +NOT_SUPPORTED_ERR: Final = 9 +INUSE_ATTRIBUTE_ERR: Final = 10 +INVALID_STATE_ERR: Final = 11 +SYNTAX_ERR: Final = 12 +INVALID_MODIFICATION_ERR: Final = 13 +NAMESPACE_ERR: Final = 14 +INVALID_ACCESS_ERR: Final = 15 +VALIDATION_ERR: Final = 16 class DOMException(Exception): code: int def __init__(self, *args: Any, **kw: Any) -> None: ... def _get_code(self) -> int: ... -class IndexSizeErr(DOMException): ... -class DomstringSizeErr(DOMException): ... -class HierarchyRequestErr(DOMException): ... -class WrongDocumentErr(DOMException): ... -class InvalidCharacterErr(DOMException): ... -class NoDataAllowedErr(DOMException): ... -class NoModificationAllowedErr(DOMException): ... -class NotFoundErr(DOMException): ... -class NotSupportedErr(DOMException): ... -class InuseAttributeErr(DOMException): ... -class InvalidStateErr(DOMException): ... -class SyntaxErr(DOMException): ... -class InvalidModificationErr(DOMException): ... -class NamespaceErr(DOMException): ... -class InvalidAccessErr(DOMException): ... -class ValidationErr(DOMException): ... +class IndexSizeErr(DOMException): + code: Literal[1] + +class DomstringSizeErr(DOMException): + code: Literal[2] + +class HierarchyRequestErr(DOMException): + code: Literal[3] + +class WrongDocumentErr(DOMException): + code: Literal[4] + +class InvalidCharacterErr(DOMException): + code: Literal[5] + +class NoDataAllowedErr(DOMException): + code: Literal[6] + +class NoModificationAllowedErr(DOMException): + code: Literal[7] + +class NotFoundErr(DOMException): + code: Literal[8] + +class NotSupportedErr(DOMException): + code: Literal[9] + +class InuseAttributeErr(DOMException): + code: Literal[10] + +class InvalidStateErr(DOMException): + code: Literal[11] + +class SyntaxErr(DOMException): + code: Literal[12] + +class InvalidModificationErr(DOMException): + code: Literal[13] + +class NamespaceErr(DOMException): + code: Literal[14] + +class InvalidAccessErr(DOMException): + code: Literal[15] + +class ValidationErr(DOMException): + code: Literal[16] class UserDataHandler: - NODE_CLONED: int - NODE_IMPORTED: int - NODE_DELETED: int - NODE_RENAMED: int - -XML_NAMESPACE: str -XMLNS_NAMESPACE: str -XHTML_NAMESPACE: str -EMPTY_NAMESPACE: None -EMPTY_PREFIX: None + NODE_CLONED: Final = 1 + NODE_IMPORTED: Final = 2 + NODE_DELETED: Final = 3 + NODE_RENAMED: Final = 4 + +XML_NAMESPACE: Final = "http://www.w3.org/XML/1998/namespace" +XMLNS_NAMESPACE: Final = "http://www.w3.org/2000/xmlns/" +XHTML_NAMESPACE: Final = "http://www.w3.org/1999/xhtml" +EMPTY_NAMESPACE: Final[None] +EMPTY_PREFIX: Final[None] diff --git a/stdlib/xml/dom/domreg.pyi b/stdlib/xml/dom/domreg.pyi index b9e2dd9eb263..346a4bf63bd4 100644 --- a/stdlib/xml/dom/domreg.pyi +++ b/stdlib/xml/dom/domreg.pyi @@ -1,8 +1,8 @@ from _typeshed.xml import DOMImplementation -from typing import Callable, Iterable +from collections.abc import Callable, Iterable well_known_implementations: dict[str, str] registered: dict[str, Callable[[], DOMImplementation]] def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ... -def getDOMImplementation(name: str | None = ..., features: str | Iterable[tuple[str, str | None]] = ...) -> DOMImplementation: ... +def getDOMImplementation(name: str | None = None, features: str | Iterable[tuple[str, str | None]] = ()) -> DOMImplementation: ... diff --git a/stdlib/xml/dom/expatbuilder.pyi b/stdlib/xml/dom/expatbuilder.pyi index 58914e8fabf1..5aef384ff0f2 100644 --- a/stdlib/xml/dom/expatbuilder.pyi +++ b/stdlib/xml/dom/expatbuilder.pyi @@ -1,99 +1,126 @@ -from typing import Any, NoReturn -from xml.dom.minidom import Document, DOMImplementation, Node, TypeInfo +from _typeshed import ReadableBuffer, SupportsRead +from typing import Any, Final, TypeAlias +from typing_extensions import Never +from xml.dom.minidom import Document, DocumentFragment, DOMImplementation, Element, Node, TypeInfo from xml.dom.xmlbuilder import DOMBuilderFilter, Options +from xml.parsers.expat import XMLParserType -TEXT_NODE = Node.TEXT_NODE -CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE -DOCUMENT_NODE = Node.DOCUMENT_NODE -FILTER_ACCEPT = DOMBuilderFilter.FILTER_ACCEPT -FILTER_REJECT = DOMBuilderFilter.FILTER_REJECT -FILTER_SKIP = DOMBuilderFilter.FILTER_SKIP -FILTER_INTERRUPT = DOMBuilderFilter.FILTER_INTERRUPT -theDOMImplementation: DOMImplementation | None +_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] # same as in pyexpat + +TEXT_NODE: Final = Node.TEXT_NODE +CDATA_SECTION_NODE: Final = Node.CDATA_SECTION_NODE +DOCUMENT_NODE: Final = Node.DOCUMENT_NODE +FILTER_ACCEPT: Final = DOMBuilderFilter.FILTER_ACCEPT +FILTER_REJECT: Final = DOMBuilderFilter.FILTER_REJECT +FILTER_SKIP: Final = DOMBuilderFilter.FILTER_SKIP +FILTER_INTERRUPT: Final = DOMBuilderFilter.FILTER_INTERRUPT +theDOMImplementation: DOMImplementation class ElementInfo: - tagName: Any - def __init__(self, tagName, model: Any | None = ...) -> None: ... - def getAttributeType(self, aname) -> TypeInfo: ... - def getAttributeTypeNS(self, namespaceURI, localName) -> TypeInfo: ... + __slots__ = ("_attr_info", "_model", "tagName") + tagName: str + def __init__(self, tagName: str, model: _Model | None = None) -> None: ... + def getAttributeType(self, aname: str) -> TypeInfo: ... + def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ... def isElementContent(self) -> bool: ... def isEmpty(self) -> bool: ... - def isId(self, aname) -> bool: ... - def isIdNS(self, euri, ename, auri, aname) -> bool: ... + def isId(self, aname: str) -> bool: ... + def isIdNS(self, euri: str, ename: str, auri: str, aname: str) -> bool: ... class ExpatBuilder: document: Document # Created in self.reset() - curNode: Any # Created in self.reset() - def __init__(self, options: Options | None = ...) -> None: ... - def createParser(self): ... - def getParser(self): ... + curNode: DocumentFragment | Element | Document # Created in self.reset() + def __init__(self, options: Options | None = None) -> None: ... + def createParser(self) -> XMLParserType: ... + def getParser(self) -> XMLParserType: ... def reset(self) -> None: ... - def install(self, parser) -> None: ... - def parseFile(self, file) -> Document: ... - def parseString(self, string: str) -> Document: ... - def start_doctype_decl_handler(self, doctypeName, systemId, publicId, has_internal_subset) -> None: ... + def install(self, parser: XMLParserType) -> None: ... + def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> Document: ... + def parseString(self, string: str | ReadableBuffer) -> Document: ... + def start_doctype_decl_handler( + self, doctypeName: str, systemId: str | None, publicId: str | None, has_internal_subset: bool + ) -> None: ... def end_doctype_decl_handler(self) -> None: ... - def pi_handler(self, target, data) -> None: ... - def character_data_handler_cdata(self, data) -> None: ... - def character_data_handler(self, data) -> None: ... + def pi_handler(self, target: str, data: str) -> None: ... + def character_data_handler_cdata(self, data: str) -> None: ... + def character_data_handler(self, data: str) -> None: ... def start_cdata_section_handler(self) -> None: ... def end_cdata_section_handler(self) -> None: ... - def entity_decl_handler(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName) -> None: ... - def notation_decl_handler(self, notationName, base, systemId, publicId) -> None: ... - def comment_handler(self, data) -> None: ... - def external_entity_ref_handler(self, context, base, systemId, publicId) -> int: ... - def first_element_handler(self, name, attributes) -> None: ... - def start_element_handler(self, name, attributes) -> None: ... - def end_element_handler(self, name) -> None: ... - def element_decl_handler(self, name, model) -> None: ... - def attlist_decl_handler(self, elem, name, type, default, required) -> None: ... - def xml_decl_handler(self, version, encoding, standalone) -> None: ... + def entity_decl_handler( + self, + entityName: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + systemId: str, + publicId: str | None, + notationName: str | None, + ) -> None: ... + def notation_decl_handler(self, notationName: str, base: str | None, systemId: str, publicId: str | None) -> None: ... + def comment_handler(self, data: str) -> None: ... + def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ... + def first_element_handler(self, name: str, attributes: list[str]) -> None: ... + def start_element_handler(self, name: str, attributes: list[str]) -> None: ... + def end_element_handler(self, name: str) -> None: ... + def element_decl_handler(self, name: str, model: _Model) -> None: ... + def attlist_decl_handler(self, elem: str, name: str, type: str, default: str | None, required: bool) -> None: ... + def xml_decl_handler(self, version: str, encoding: str | None, standalone: int) -> None: ... class FilterVisibilityController: + __slots__ = ("filter",) filter: DOMBuilderFilter def __init__(self, filter: DOMBuilderFilter) -> None: ... def startContainer(self, node: Node) -> int: ... def acceptNode(self, node: Node) -> int: ... class FilterCrutch: - def __init__(self, builder) -> None: ... + __slots__ = ("_builder", "_level", "_old_start", "_old_end") + def __init__(self, builder: ExpatBuilder) -> None: ... class Rejecter(FilterCrutch): + __slots__ = () def start_element_handler(self, *args: Any) -> None: ... def end_element_handler(self, *args: Any) -> None: ... class Skipper(FilterCrutch): + __slots__ = () def start_element_handler(self, *args: Any) -> None: ... def end_element_handler(self, *args: Any) -> None: ... class FragmentBuilder(ExpatBuilder): - fragment: Any | None - originalDocument: Any - context: Any - def __init__(self, context, options: Options | None = ...) -> None: ... + fragment: DocumentFragment | None + originalDocument: Document + context: Node + def __init__(self, context: Node, options: Options | None = None) -> None: ... + def reset(self) -> None: ... + def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> DocumentFragment: ... # type: ignore[override] + def parseString(self, string: ReadableBuffer | str) -> DocumentFragment: ... # type: ignore[override] + def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ... class Namespaces: - def createParser(self): ... - def install(self, parser) -> None: ... - def start_namespace_decl_handler(self, prefix, uri) -> None: ... - def start_element_handler(self, name, attributes) -> None: ... - def end_element_handler(self, name) -> None: ... + def createParser(self) -> XMLParserType: ... + def install(self, parser: XMLParserType) -> None: ... + def start_namespace_decl_handler(self, prefix: str | None, uri: str) -> None: ... + def start_element_handler(self, name: str, attributes: list[str]) -> None: ... + def end_element_handler(self, name: str) -> None: ... # only exists if __debug__ class ExpatBuilderNS(Namespaces, ExpatBuilder): ... class FragmentBuilderNS(Namespaces, FragmentBuilder): ... class ParseEscape(Exception): ... class InternalSubsetExtractor(ExpatBuilder): - subset: Any | None - def getSubset(self) -> Any | None: ... - def parseFile(self, file) -> None: ... # type: ignore[override] - def parseString(self, string: str) -> None: ... # type: ignore[override] - def start_doctype_decl_handler(self, name, publicId, systemId, has_internal_subset) -> None: ... # type: ignore[override] - def end_doctype_decl_handler(self) -> NoReturn: ... - def start_element_handler(self, name, attrs) -> NoReturn: ... + subset: str | list[str] | None = None + def getSubset(self) -> str: ... + def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> None: ... # type: ignore[override] + def parseString(self, string: str | ReadableBuffer) -> None: ... # type: ignore[override] + def start_doctype_decl_handler( # type: ignore[override] + self, name: str, publicId: str | None, systemId: str | None, has_internal_subset: bool + ) -> None: ... + def end_doctype_decl_handler(self) -> Never: ... + def start_element_handler(self, name: str, attrs: list[str]) -> Never: ... -def parse(file, namespaces: bool = ...): ... -def parseString(string: str, namespaces: bool = ...): ... -def parseFragment(file, context, namespaces: bool = ...): ... -def parseFragmentString(string: str, context, namespaces: bool = ...): ... +def parse(file: str | SupportsRead[ReadableBuffer | str], namespaces: bool = True) -> Document: ... +def parseString(string: str | ReadableBuffer, namespaces: bool = True) -> Document: ... +def parseFragment(file: str | SupportsRead[ReadableBuffer | str], context: Node, namespaces: bool = True) -> DocumentFragment: ... +def parseFragmentString(string: str | ReadableBuffer, context: Node, namespaces: bool = True) -> DocumentFragment: ... def makeBuilder(options: Options) -> ExpatBuilderNS | ExpatBuilder: ... diff --git a/stdlib/xml/dom/minicompat.pyi b/stdlib/xml/dom/minicompat.pyi index 46d55c666cb0..6fcaee019dc2 100644 --- a/stdlib/xml/dom/minicompat.pyi +++ b/stdlib/xml/dom/minicompat.pyi @@ -1,17 +1,24 @@ -from typing import Any, Iterable, List, Tuple, Type, TypeVar +from collections.abc import Iterable +from typing import Any, Literal, TypeVar + +__all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] _T = TypeVar("_T") -StringTypes: tuple[Type[str]] +StringTypes: tuple[type[str]] -class NodeList(List[_T]): - length: int +class NodeList(list[_T]): + __slots__ = () + @property + def length(self) -> int: ... def item(self, index: int) -> _T | None: ... -class EmptyNodeList(Tuple[Any, ...]): - length: int +class EmptyNodeList(tuple[()]): + __slots__ = () + @property + def length(self) -> Literal[0]: ... def item(self, index: int) -> None: ... def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore[override] def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... -def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... +def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/stdlib/xml/dom/minidom.pyi b/stdlib/xml/dom/minidom.pyi index e9a26e30d721..7d287a6c9b60 100644 --- a/stdlib/xml/dom/minidom.pyi +++ b/stdlib/xml/dom/minidom.pyi @@ -1,332 +1,693 @@ -import sys import xml.dom -from _typeshed import Self -from typing import IO, Any +from _collections_abc import dict_keys, dict_values +from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, ClassVar, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self +from xml.dom.minicompat import EmptyNodeList, NodeList from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader -def parse(file: str | IO[Any], parser: XMLReader | None = ..., bufsize: int | None = ...): ... -def parseString(string: str | bytes, parser: XMLReader | None = ...): ... -def getDOMImplementation(features=...) -> DOMImplementation | None: ... +_NSName: TypeAlias = tuple[str | None, str] + +# Entity can also have children, but it's not implemented the same way as the +# others, so is deliberately omitted here. +_NodesWithChildren: TypeAlias = DocumentFragment | Attr | Element | Document +_NodesThatAreChildren: TypeAlias = CDATASection | Comment | DocumentType | Element | Notation | ProcessingInstruction | Text + +_AttrChildren: TypeAlias = Text # Also EntityReference, but we don't implement it +_ElementChildren: TypeAlias = Element | ProcessingInstruction | Comment | Text | CDATASection +_EntityChildren: TypeAlias = Text # I think; documentation is a little unclear +_DocumentFragmentChildren: TypeAlias = Element | Text | CDATASection | ProcessingInstruction | Comment | Notation +_DocumentChildren: TypeAlias = Comment | DocumentType | Element | ProcessingInstruction + +_N = TypeVar("_N", bound=Node) +_ChildNodeVar = TypeVar("_ChildNodeVar", bound=_NodesThatAreChildren) +_ChildNodePlusFragmentVar = TypeVar("_ChildNodePlusFragmentVar", bound=_NodesThatAreChildren | DocumentFragment) +_DocumentChildrenVar = TypeVar("_DocumentChildrenVar", bound=_DocumentChildren) +_ImportableNodeVar = TypeVar( + "_ImportableNodeVar", + bound=DocumentFragment + | Attr + | Element + | ProcessingInstruction + | CharacterData + | Text + | Comment + | CDATASection + | Entity + | Notation, +) + +@type_check_only +class _DOMErrorHandler(Protocol): + def handleError(self, error: Exception) -> bool: ... + +@type_check_only +class _UserDataHandler(Protocol): + def handle(self, operation: int, key: str, data: Any, src: Node, dst: Node) -> None: ... + +def parse( + file: str | SupportsRead[ReadableBuffer | str], parser: XMLReader | None = None, bufsize: int | None = None +) -> Document: ... +def parseString(string: str | ReadableBuffer, parser: XMLReader | None = None) -> Document: ... + +@overload +def getDOMImplementation(features: None = None) -> DOMImplementation: ... +@overload +def getDOMImplementation(features: str | Iterable[tuple[str, str | None]]) -> DOMImplementation | None: ... class Node(xml.dom.Node): - namespaceURI: str | None - parentNode: Any - ownerDocument: Any - nextSibling: Any - previousSibling: Any - prefix: Any - @property - def firstChild(self) -> Node | None: ... - @property - def lastChild(self) -> Node | None: ... - @property - def localName(self) -> str | None: ... - if sys.version_info >= (3, 9): - def toxml(self, encoding: Any | None = ..., standalone: Any | None = ...): ... - def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Any | None = ..., standalone: Any | None = ...): ... - else: - def toxml(self, encoding: Any | None = ...): ... - def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Any | None = ...): ... + parentNode: _NodesWithChildren | Entity | None + ownerDocument: Document | None + nextSibling: _NodesThatAreChildren | None + previousSibling: _NodesThatAreChildren | None + namespaceURI: str | None # non-null only for Element and Attr + prefix: str | None # non-null only for NS Element and Attr + + # These aren't defined on Node, but they exist on all Node subclasses + # and various methods of Node require them to exist. + childNodes: ( + NodeList[_DocumentFragmentChildren] + | NodeList[_AttrChildren] + | NodeList[_ElementChildren] + | NodeList[_DocumentChildren] + | NodeList[_EntityChildren] + | EmptyNodeList + ) + nodeType: ClassVar[Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]] + nodeName: str | None # only possibly None on DocumentType + + # Not defined on Node, but exist on all Node subclasses. + nodeValue: str | None # non-null for Attr, ProcessingInstruction, Text, Comment, and CDATASection + attributes: NamedNodeMap | None # non-null only for Element + + @property + def firstChild(self) -> _NodesThatAreChildren | None: ... + @property + def lastChild(self) -> _NodesThatAreChildren | None: ... + @property + def localName(self) -> str | None: ... # non-null only for Element and Attr + def __bool__(self) -> Literal[True]: ... + + @overload + def toxml(self, encoding: str, standalone: bool | None = None) -> bytes: ... + @overload + def toxml(self, encoding: None = None, standalone: bool | None = None) -> str: ... + + @overload + def toprettyxml( + self, + indent: str = "\t", + newl: str = "\n", + # Handle any case where encoding is not provided or where it is passed with None + encoding: None = None, + standalone: bool | None = None, + ) -> str: ... + @overload + def toprettyxml( + self, + indent: str, + newl: str, + # Handle cases where encoding is passed as str *positionally* + encoding: str, + standalone: bool | None = None, + ) -> bytes: ... + @overload + def toprettyxml( + self, + indent: str = "\t", + newl: str = "\n", + # Handle all cases where encoding is passed as a keyword argument; because standalone + # comes after, it will also have to be a keyword arg if encoding is + *, + encoding: str, + standalone: bool | None = None, + ) -> bytes: ... + def hasChildNodes(self) -> bool: ... - def insertBefore(self, newChild, refChild): ... - def appendChild(self, node): ... - def replaceChild(self, newChild, oldChild): ... - def removeChild(self, oldChild): ... - def normalize(self) -> None: ... - def cloneNode(self, deep): ... - def isSupported(self, feature, version): ... - def isSameNode(self, other): ... - def getInterface(self, feature): ... - def getUserData(self, key): ... - def setUserData(self, key, data, handler): ... - childNodes: Any + def insertBefore( # type: ignore[misc] + self: _NodesWithChildren, # pyright: ignore[reportGeneralTypeIssues] + newChild: _ChildNodePlusFragmentVar, + refChild: _NodesThatAreChildren | None, + ) -> _ChildNodePlusFragmentVar: ... + def appendChild( # type: ignore[misc] + self: _NodesWithChildren, node: _ChildNodePlusFragmentVar # pyright: ignore[reportGeneralTypeIssues] + ) -> _ChildNodePlusFragmentVar: ... + + @overload + def replaceChild( # type: ignore[misc] + self: _NodesWithChildren, newChild: DocumentFragment, oldChild: _ChildNodeVar + ) -> _ChildNodeVar | DocumentFragment: ... + @overload + def replaceChild( # type: ignore[misc] + self: _NodesWithChildren, newChild: _NodesThatAreChildren, oldChild: _ChildNodeVar + ) -> _ChildNodeVar | None: ... + + def removeChild(self: _NodesWithChildren, oldChild: _ChildNodeVar) -> _ChildNodeVar: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def normalize(self: _NodesWithChildren) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def cloneNode(self, deep: bool) -> Self | None: ... + def isSupported(self, feature: str, version: str | None) -> bool: ... + def isSameNode(self, other: Node) -> bool: ... + def getInterface(self, feature: str) -> Self | None: ... + def getUserData(self, key: str) -> Any | None: ... + def setUserData(self, key: str, data: Any, handler: _UserDataHandler) -> Any: ... def unlink(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, et, ev, tb) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, et: type[BaseException] | None, ev: BaseException | None, tb: TracebackType | None) -> None: ... + +_DFChildrenVar = TypeVar("_DFChildrenVar", bound=_DocumentFragmentChildren) +_DFChildrenPlusFragment = TypeVar("_DFChildrenPlusFragment", bound=_DocumentFragmentChildren | DocumentFragment) class DocumentFragment(Node): - nodeType: Any - nodeName: str - nodeValue: Any - attributes: Any - parentNode: Any - childNodes: Any + nodeType: ClassVar[Literal[11]] + nodeName: Literal["#document-fragment"] + nodeValue: None + attributes: None + + parentNode: None + nextSibling: None + previousSibling: None + childNodes: NodeList[_DocumentFragmentChildren] + @property + def firstChild(self) -> _DocumentFragmentChildren | None: ... + @property + def lastChild(self) -> _DocumentFragmentChildren | None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... def __init__(self) -> None: ... + def insertBefore( # type: ignore[override] + self, newChild: _DFChildrenPlusFragment, refChild: _DocumentFragmentChildren | None + ) -> _DFChildrenPlusFragment: ... + def appendChild(self, node: _DFChildrenPlusFragment) -> _DFChildrenPlusFragment: ... # type: ignore[override] + + @overload # type: ignore[override] + def replaceChild(self, newChild: DocumentFragment, oldChild: _DFChildrenVar) -> _DFChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _DocumentFragmentChildren, oldChild: _DFChildrenVar) -> _DFChildrenVar | None: ... # type: ignore[override] + + def removeChild(self, oldChild: _DFChildrenVar) -> _DFChildrenVar: ... # type: ignore[override] + +_AttrChildrenVar = TypeVar("_AttrChildrenVar", bound=_AttrChildren) +_AttrChildrenPlusFragment = TypeVar("_AttrChildrenPlusFragment", bound=_AttrChildren | DocumentFragment) class Attr(Node): - name: str - nodeType: Any - attributes: Any - specified: bool - ownerElement: Any + __slots__ = ("_name", "_value", "namespaceURI", "_prefix", "childNodes", "_localName", "ownerDocument", "ownerElement") + nodeType: ClassVar[Literal[2]] + nodeName: str # same as Attr.name + nodeValue: str # same as Attr.value + attributes: None + + parentNode: None + nextSibling: None + previousSibling: None + childNodes: NodeList[_AttrChildren] + @property + def firstChild(self) -> _AttrChildren | None: ... + @property + def lastChild(self) -> _AttrChildren | None: ... + namespaceURI: str | None - childNodes: Any - nodeName: Any - nodeValue: str + prefix: str | None + @property + def localName(self) -> str: ... + + name: str value: str - prefix: Any + specified: bool + ownerElement: Element | None + def __init__( - self, qName: str, namespaceURI: str | None = ..., localName: Any | None = ..., prefix: Any | None = ... + self, qName: str, namespaceURI: str | None = None, localName: str | None = None, prefix: str | None = None ) -> None: ... def unlink(self) -> None: ... @property def isId(self) -> bool: ... @property - def schemaType(self) -> Any: ... + def schemaType(self) -> TypeInfo: ... + def insertBefore(self, newChild: _AttrChildrenPlusFragment, refChild: _AttrChildren | None) -> _AttrChildrenPlusFragment: ... # type: ignore[override] + def appendChild(self, node: _AttrChildrenPlusFragment) -> _AttrChildrenPlusFragment: ... # type: ignore[override] + @overload # type: ignore[override] + def replaceChild(self, newChild: DocumentFragment, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _AttrChildren, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | None: ... # type: ignore[override] + + def removeChild(self, oldChild: _AttrChildrenVar) -> _AttrChildrenVar: ... # type: ignore[override] + +# In the DOM, this interface isn't specific to Attr, but our implementation is +# because that's the only place we use it. class NamedNodeMap: - def __init__(self, attrs, attrsNS, ownerElement) -> None: ... - def item(self, index): ... - def items(self): ... - def itemsNS(self): ... - def __contains__(self, key): ... - def keys(self): ... - def keysNS(self): ... - def values(self): ... - def get(self, name, value: Any | None = ...): ... - def __len__(self) -> int: ... - def __eq__(self, other: Any) -> bool: ... - def __ge__(self, other: Any) -> bool: ... - def __gt__(self, other: Any) -> bool: ... - def __le__(self, other: Any) -> bool: ... - def __lt__(self, other: Any) -> bool: ... - def __getitem__(self, attname_or_tuple): ... - def __setitem__(self, attname, value) -> None: ... - def getNamedItem(self, name): ... - def getNamedItemNS(self, namespaceURI: str, localName): ... - def removeNamedItem(self, name): ... - def removeNamedItemNS(self, namespaceURI: str, localName): ... - def setNamedItem(self, node): ... - def setNamedItemNS(self, node): ... - def __delitem__(self, attname_or_tuple) -> None: ... + __slots__ = ("_attrs", "_attrsNS", "_ownerElement") + def __init__(self, attrs: dict[str, Attr], attrsNS: dict[_NSName, Attr], ownerElement: Element) -> None: ... @property def length(self) -> int: ... + def item(self, index: int) -> Node | None: ... + def items(self) -> list[tuple[str, str]]: ... + def itemsNS(self) -> list[tuple[_NSName, str]]: ... + def __contains__(self, key: str | _NSName) -> bool: ... + def keys(self) -> dict_keys[str, Attr]: ... + def keysNS(self) -> dict_keys[_NSName, Attr]: ... + def values(self) -> dict_values[str, Attr]: ... + def get(self, name: str, value: Attr | None = None) -> Attr | None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __ge__(self, other: NamedNodeMap) -> bool: ... + def __gt__(self, other: NamedNodeMap) -> bool: ... + def __le__(self, other: NamedNodeMap) -> bool: ... + def __lt__(self, other: NamedNodeMap) -> bool: ... + def __getitem__(self, attname_or_tuple: _NSName | str) -> Attr: ... + def __setitem__(self, attname: str, value: Attr | str) -> None: ... + def getNamedItem(self, name: str) -> Attr | None: ... + def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> Attr | None: ... + def removeNamedItem(self, name: str) -> Attr: ... + def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> Attr: ... + def setNamedItem(self, node: Attr) -> Attr | None: ... + def setNamedItemNS(self, node: Attr) -> Attr | None: ... + def __delitem__(self, attname_or_tuple: _NSName | str) -> None: ... AttributeList = NamedNodeMap class TypeInfo: - namespace: Any - name: Any - def __init__(self, namespace, name) -> None: ... + __slots__ = ("namespace", "name") + namespace: str | None + name: str | None + def __init__(self, namespace: Incomplete | None, name: str | None) -> None: ... + +_ElementChildrenVar = TypeVar("_ElementChildrenVar", bound=_ElementChildren) +_ElementChildrenPlusFragment = TypeVar("_ElementChildrenPlusFragment", bound=_ElementChildren | DocumentFragment) class Element(Node): - nodeType: Any - nodeValue: Any - schemaType: Any - parentNode: Any - tagName: str - nodeName: str - prefix: Any + __slots__ = ( + "ownerDocument", + "parentNode", + "tagName", + "nodeName", + "prefix", + "namespaceURI", + "_localName", + "childNodes", + "_attrs", + "_attrsNS", + "nextSibling", + "previousSibling", + ) + nodeType: ClassVar[Literal[1]] + nodeName: str # same as Element.tagName + nodeValue: None + @property + def attributes(self) -> NamedNodeMap: ... # type: ignore[override] + + parentNode: Document | Element | DocumentFragment | None + nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + childNodes: NodeList[_ElementChildren] + @property + def firstChild(self) -> _ElementChildren | None: ... + @property + def lastChild(self) -> _ElementChildren | None: ... + namespaceURI: str | None - childNodes: Any - nextSibling: Any + prefix: str | None + @property + def localName(self) -> str: ... + + schemaType: TypeInfo + tagName: str + def __init__( - self, tagName, namespaceURI: str | None = ..., prefix: Any | None = ..., localName: Any | None = ... + self, tagName: str, namespaceURI: str | None = None, prefix: str | None = None, localName: str | None = None ) -> None: ... def unlink(self) -> None: ... - def getAttribute(self, attname): ... - def getAttributeNS(self, namespaceURI: str, localName): ... - def setAttribute(self, attname, value) -> None: ... - def setAttributeNS(self, namespaceURI: str, qualifiedName: str, value) -> None: ... - def getAttributeNode(self, attrname): ... - def getAttributeNodeNS(self, namespaceURI: str, localName): ... - def setAttributeNode(self, attr): ... - setAttributeNodeNS: Any - def removeAttribute(self, name) -> None: ... - def removeAttributeNS(self, namespaceURI: str, localName) -> None: ... - def removeAttributeNode(self, node): ... - removeAttributeNodeNS: Any + def getAttribute(self, attname: str) -> str: ... + def getAttributeNS(self, namespaceURI: str | None, localName: str) -> str: ... + def setAttribute(self, attname: str, value: str) -> None: ... + def setAttributeNS(self, namespaceURI: str | None, qualifiedName: str, value: str) -> None: ... + def getAttributeNode(self, attrname: str) -> Attr | None: ... + def getAttributeNodeNS(self, namespaceURI: str | None, localName: str) -> Attr | None: ... + def setAttributeNode(self, attr: Attr) -> Attr | None: ... + setAttributeNodeNS = setAttributeNode + def removeAttribute(self, name: str) -> None: ... + def removeAttributeNS(self, namespaceURI: str | None, localName: str) -> None: ... + def removeAttributeNode(self, node: Attr) -> Attr: ... + removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name: str) -> bool: ... - def hasAttributeNS(self, namespaceURI: str, localName) -> bool: ... - def getElementsByTagName(self, name): ... - def getElementsByTagNameNS(self, namespaceURI: str, localName): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + def hasAttributeNS(self, namespaceURI: str | None, localName: str) -> bool: ... + def getElementsByTagName(self, name: str) -> NodeList[Element]: ... + def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... def hasAttributes(self) -> bool: ... - def setIdAttribute(self, name) -> None: ... - def setIdAttributeNS(self, namespaceURI: str, localName) -> None: ... - def setIdAttributeNode(self, idAttr) -> None: ... - @property - def attributes(self) -> NamedNodeMap: ... + def setIdAttribute(self, name: str) -> None: ... + def setIdAttributeNS(self, namespaceURI: str | None, localName: str) -> None: ... + def setIdAttributeNode(self, idAttr: Attr) -> None: ... + def insertBefore( # type: ignore[override] + self, newChild: _ElementChildrenPlusFragment, refChild: _ElementChildren | None + ) -> _ElementChildrenPlusFragment: ... + def appendChild(self, node: _ElementChildrenPlusFragment) -> _ElementChildrenPlusFragment: ... # type: ignore[override] + + @overload # type: ignore[override] + def replaceChild( + self, newChild: DocumentFragment, oldChild: _ElementChildrenVar + ) -> _ElementChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _ElementChildren, oldChild: _ElementChildrenVar) -> _ElementChildrenVar | None: ... # type: ignore[override] + + def removeChild(self, oldChild: _ElementChildrenVar) -> _ElementChildrenVar: ... # type: ignore[override] class Childless: - attributes: Any - childNodes: Any - firstChild: Any - lastChild: Any - def appendChild(self, node) -> None: ... - def hasChildNodes(self) -> bool: ... - def insertBefore(self, newChild, refChild) -> None: ... - def removeChild(self, oldChild) -> None: ... + __slots__ = () + attributes: None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + def appendChild(self, node: _NodesThatAreChildren | DocumentFragment) -> Never: ... + def hasChildNodes(self) -> Literal[False]: ... + def insertBefore( + self, newChild: _NodesThatAreChildren | DocumentFragment, refChild: _NodesThatAreChildren | None + ) -> Never: ... + def removeChild(self, oldChild: _NodesThatAreChildren) -> Never: ... def normalize(self) -> None: ... - def replaceChild(self, newChild, oldChild) -> None: ... + def replaceChild(self, newChild: _NodesThatAreChildren | DocumentFragment, oldChild: _NodesThatAreChildren) -> Never: ... class ProcessingInstruction(Childless, Node): - nodeType: Any - target: Any - data: Any - def __init__(self, target, data) -> None: ... - nodeValue: Any - nodeName: Any - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + __slots__ = ("target", "data") + nodeType: ClassVar[Literal[7]] + nodeName: str # same as ProcessingInstruction.target + nodeValue: str # same as ProcessingInstruction.data + attributes: None + + parentNode: Document | Element | DocumentFragment | None + nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + target: str + data: str + + def __init__(self, target: str, data: str) -> None: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... class CharacterData(Childless, Node): - ownerDocument: Any - previousSibling: Any + __slots__ = ("_data", "ownerDocument", "parentNode", "previousSibling", "nextSibling") + nodeValue: str + attributes: None + + childNodes: EmptyNodeList + nextSibling: _NodesThatAreChildren | None + previousSibling: _NodesThatAreChildren | None + + @property + def localName(self) -> None: ... + + ownerDocument: Document | None + data: str + def __init__(self) -> None: ... + @property + def length(self) -> int: ... def __len__(self) -> int: ... - data: str - nodeValue: Any def substringData(self, offset: int, count: int) -> str: ... def appendData(self, arg: str) -> None: ... def insertData(self, offset: int, arg: str) -> None: ... def deleteData(self, offset: int, count: int) -> None: ... def replaceData(self, offset: int, count: int, arg: str) -> None: ... - @property - def length(self) -> int: ... class Text(CharacterData): - nodeType: Any - nodeName: str - attributes: Any - data: Any - def splitText(self, offset): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - def replaceWholeText(self, content): ... + __slots__ = () + nodeType: ClassVar[Literal[3]] + nodeName: Literal["#text"] + nodeValue: str # same as CharacterData.data, the content of the text node + attributes: None + + parentNode: Attr | Element | DocumentFragment | None + nextSibling: _DocumentFragmentChildren | _ElementChildren | _AttrChildren | None + previousSibling: _DocumentFragmentChildren | _ElementChildren | _AttrChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + data: str + def splitText(self, offset: int) -> Self: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + def replaceWholeText(self, content: str) -> Self | None: ... @property def isWhitespaceInElementContent(self) -> bool: ... @property def wholeText(self) -> str: ... class Comment(CharacterData): - nodeType: Any - nodeName: str - def __init__(self, data) -> None: ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + nodeType: ClassVar[Literal[8]] + nodeName: Literal["#comment"] + nodeValue: str # same as CharacterData.data, the content of the comment + attributes: None + + parentNode: Document | Element | DocumentFragment | None + nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + def __init__(self, data: str) -> None: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... class CDATASection(Text): - nodeType: Any - nodeName: str - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... - -class ReadOnlySequentialNamedNodeMap: - def __init__(self, seq=...) -> None: ... - def __len__(self): ... - def getNamedItem(self, name): ... - def getNamedItemNS(self, namespaceURI: str, localName): ... - def __getitem__(self, name_or_tuple): ... - def item(self, index): ... - def removeNamedItem(self, name) -> None: ... - def removeNamedItemNS(self, namespaceURI: str, localName) -> None: ... - def setNamedItem(self, node) -> None: ... - def setNamedItemNS(self, node) -> None: ... + __slots__ = () + nodeType: ClassVar[Literal[4]] # type: ignore[assignment] + nodeName: Literal["#cdata-section"] # type: ignore[assignment] + nodeValue: str # same as CharacterData.data, the content of the CDATA Section + attributes: None + + parentNode: Element | DocumentFragment | None + nextSibling: _DocumentFragmentChildren | _ElementChildren | None + previousSibling: _DocumentFragmentChildren | _ElementChildren | None + + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + +class ReadOnlySequentialNamedNodeMap(Generic[_N]): + __slots__ = ("_seq",) + def __init__(self, seq: Sequence[_N] = ()) -> None: ... + def __len__(self) -> int: ... + def getNamedItem(self, name: str) -> _N | None: ... + def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> _N | None: ... + def __getitem__(self, name_or_tuple: str | _NSName) -> _N | None: ... + def item(self, index: int) -> _N | None: ... + def removeNamedItem(self, name: str) -> Never: ... + def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> Never: ... + def setNamedItem(self, node: Node) -> Never: ... + def setNamedItemNS(self, node: Node) -> Never: ... @property def length(self) -> int: ... class Identified: - publicId: Any - systemId: Any + __slots__ = ("publicId", "systemId") + publicId: str | None + systemId: str | None class DocumentType(Identified, Childless, Node): - nodeType: Any - nodeValue: Any - name: Any - internalSubset: Any - entities: Any - notations: Any - nodeName: Any - def __init__(self, qualifiedName: str) -> None: ... - def cloneNode(self, deep): ... - def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + nodeType: ClassVar[Literal[10]] + nodeName: str | None # same as DocumentType.name + nodeValue: None + attributes: None + + parentNode: Document | None + nextSibling: _DocumentChildren | None + previousSibling: _DocumentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + name: str | None + internalSubset: str | None + entities: ReadOnlySequentialNamedNodeMap[Entity] + notations: ReadOnlySequentialNamedNodeMap[Notation] + + def __init__(self, qualifiedName: str | None) -> None: ... + def cloneNode(self, deep: bool) -> DocumentType | None: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... class Entity(Identified, Node): - attributes: Any - nodeType: Any - nodeValue: Any - actualEncoding: Any - encoding: Any - version: Any - nodeName: Any - notationName: Any - childNodes: Any - def __init__(self, name, publicId, systemId, notation) -> None: ... - def appendChild(self, newChild) -> None: ... - def insertBefore(self, newChild, refChild) -> None: ... - def removeChild(self, oldChild) -> None: ... - def replaceChild(self, newChild, oldChild) -> None: ... + nodeType: ClassVar[Literal[6]] + nodeName: str # entity name + nodeValue: None + attributes: None + + parentNode: None + nextSibling: None + previousSibling: None + childNodes: NodeList[_EntityChildren] + @property + def firstChild(self) -> _EntityChildren | None: ... + @property + def lastChild(self) -> _EntityChildren | None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + actualEncoding: str | None + encoding: str | None + version: str | None + notationName: str | None + + def __init__(self, name: str, publicId: str | None, systemId: str | None, notation: str | None) -> None: ... + def appendChild(self, newChild: _EntityChildren) -> Never: ... # type: ignore[override] + def insertBefore(self, newChild: _EntityChildren, refChild: _EntityChildren | None) -> Never: ... # type: ignore[override] + def removeChild(self, oldChild: _EntityChildren) -> Never: ... # type: ignore[override] + def replaceChild(self, newChild: _EntityChildren, oldChild: _EntityChildren) -> Never: ... # type: ignore[override] class Notation(Identified, Childless, Node): - nodeType: Any - nodeValue: Any - nodeName: Any - def __init__(self, name, publicId, systemId) -> None: ... + nodeType: ClassVar[Literal[12]] + nodeName: str # notation name + nodeValue: None + attributes: None + + parentNode: DocumentFragment | None + nextSibling: _DocumentFragmentChildren | None + previousSibling: _DocumentFragmentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + def __init__(self, name: str, publicId: str | None, systemId: str | None) -> None: ... class DOMImplementation(DOMImplementationLS): - def hasFeature(self, feature, version) -> bool: ... - def createDocument(self, namespaceURI: str | None, qualifiedName: str | None, doctype): ... - def createDocumentType(self, qualifiedName: str | None, publicId, systemId): ... - def getInterface(self, feature): ... + def hasFeature(self, feature: str, version: str | None) -> bool: ... + def createDocument(self, namespaceURI: str | None, qualifiedName: str | None, doctype: DocumentType | None) -> Document: ... + def createDocumentType(self, qualifiedName: str | None, publicId: str | None, systemId: str | None) -> DocumentType: ... + def getInterface(self, feature: str) -> Self | None: ... class ElementInfo: - tagName: Any - def __init__(self, name) -> None: ... - def getAttributeType(self, aname): ... - def getAttributeTypeNS(self, namespaceURI: str, localName): ... - def isElementContent(self): ... - def isEmpty(self): ... - def isId(self, aname): ... - def isIdNS(self, namespaceURI: str, localName): ... + __slots__ = ("tagName",) + tagName: str + def __init__(self, name: str) -> None: ... + def getAttributeType(self, aname: str) -> TypeInfo: ... + def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ... + def isElementContent(self) -> bool: ... + def isEmpty(self) -> bool: ... + def isId(self, aname: str) -> bool: ... + def isIdNS(self, namespaceURI: str | None, localName: str) -> bool: ... + +_DocumentChildrenPlusFragment = TypeVar("_DocumentChildrenPlusFragment", bound=_DocumentChildren | DocumentFragment) class Document(Node, DocumentLS): - implementation: Any - nodeType: Any - nodeName: str - nodeValue: Any - attributes: Any - parentNode: Any - previousSibling: Any - nextSibling: Any - actualEncoding: Any - encoding: Any - standalone: Any - version: Any + __slots__ = ("_elem_info", "doctype", "_id_search_stack", "childNodes", "_id_cache") + nodeType: ClassVar[Literal[9]] + nodeName: Literal["#document"] + nodeValue: None + attributes: None + + parentNode: None + previousSibling: None + nextSibling: None + childNodes: NodeList[_DocumentChildren] + @property + def firstChild(self) -> _DocumentChildren | None: ... + @property + def lastChild(self) -> _DocumentChildren | None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + implementation: DOMImplementation + actualEncoding: str | None + encoding: str | None + standalone: bool | None + version: str | None strictErrorChecking: bool - errorHandler: Any - documentURI: Any - doctype: Any - childNodes: Any + errorHandler: _DOMErrorHandler | None + documentURI: str | None + doctype: DocumentType | None + documentElement: Element | None + def __init__(self) -> None: ... - def appendChild(self, node): ... - documentElement: Any - def removeChild(self, oldChild): ... + def appendChild(self, node: _DocumentChildrenVar) -> _DocumentChildrenVar: ... # type: ignore[override] + def removeChild(self, oldChild: _DocumentChildrenVar) -> _DocumentChildrenVar: ... # type: ignore[override] def unlink(self) -> None: ... - def cloneNode(self, deep): ... - def createDocumentFragment(self): ... - def createElement(self, tagName: str): ... - def createTextNode(self, data): ... - def createCDATASection(self, data): ... - def createComment(self, data): ... - def createProcessingInstruction(self, target, data): ... - def createAttribute(self, qName) -> Attr: ... - def createElementNS(self, namespaceURI: str, qualifiedName: str): ... - def createAttributeNS(self, namespaceURI: str, qualifiedName: str) -> Attr: ... - def getElementById(self, id): ... - def getElementsByTagName(self, name: str): ... - def getElementsByTagNameNS(self, namespaceURI: str, localName): ... - def isSupported(self, feature, version): ... - def importNode(self, node, deep): ... - if sys.version_info >= (3, 9): - def writexml( - self, - writer, - indent: str = ..., - addindent: str = ..., - newl: str = ..., - encoding: Any | None = ..., - standalone: Any | None = ..., - ) -> None: ... - else: - def writexml( - self, writer, indent: str = ..., addindent: str = ..., newl: str = ..., encoding: Any | None = ... - ) -> None: ... - def renameNode(self, n, namespaceURI: str, name): ... + def cloneNode(self, deep: bool) -> Document | None: ... + def createDocumentFragment(self) -> DocumentFragment: ... + def createElement(self, tagName: str) -> Element: ... + def createTextNode(self, data: str) -> Text: ... + def createCDATASection(self, data: str) -> CDATASection: ... + def createComment(self, data: str) -> Comment: ... + def createProcessingInstruction(self, target: str, data: str) -> ProcessingInstruction: ... + def createAttribute(self, qName: str) -> Attr: ... + def createElementNS(self, namespaceURI: str | None, qualifiedName: str) -> Element: ... + def createAttributeNS(self, namespaceURI: str | None, qualifiedName: str) -> Attr: ... + def getElementById(self, id: str) -> Element | None: ... + def getElementsByTagName(self, name: str) -> NodeList[Element]: ... + def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ... + def isSupported(self, feature: str, version: str | None) -> bool: ... + def importNode(self, node: _ImportableNodeVar, deep: bool) -> _ImportableNodeVar: ... + def writexml( + self, + writer: SupportsWrite[str], + indent: str = "", + addindent: str = "", + newl: str = "", + encoding: str | None = None, + standalone: bool | None = None, + ) -> None: ... + + @overload + def renameNode(self, n: Element, namespaceURI: str, name: str) -> Element: ... + @overload + def renameNode(self, n: Attr, namespaceURI: str, name: str) -> Attr: ... + @overload + def renameNode(self, n: Element | Attr, namespaceURI: str, name: str) -> Element | Attr: ... + + def insertBefore( + self, newChild: _DocumentChildrenPlusFragment, refChild: _DocumentChildren | None # type: ignore[override] + ) -> _DocumentChildrenPlusFragment: ... + + @overload # type: ignore[override] + def replaceChild( + self, newChild: DocumentFragment, oldChild: _DocumentChildrenVar + ) -> _DocumentChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _DocumentChildren, oldChild: _DocumentChildrenVar) -> _DocumentChildrenVar | None: ... diff --git a/stdlib/xml/dom/pulldom.pyi b/stdlib/xml/dom/pulldom.pyi index 530c1988e743..7014c865bcdd 100644 --- a/stdlib/xml/dom/pulldom.pyi +++ b/stdlib/xml/dom/pulldom.pyi @@ -1,89 +1,109 @@ import sys -from typing import IO, Any, Sequence, Tuple, Union -from typing_extensions import Literal -from xml.dom.minidom import Document, DOMImplementation, Element, Text +from _typeshed import Incomplete, Unused +from collections.abc import MutableSequence, Sequence +from typing import Final, Literal, TypeAlias +from typing_extensions import Never, Self +from xml.dom.minidom import Comment, Document, DOMImplementation, Element, ProcessingInstruction, Text +from xml.sax import _SupportsReadClose from xml.sax.handler import ContentHandler -from xml.sax.xmlreader import XMLReader +from xml.sax.xmlreader import AttributesImpl, AttributesNSImpl, Locator, XMLReader -START_ELEMENT: Literal["START_ELEMENT"] -END_ELEMENT: Literal["END_ELEMENT"] -COMMENT: Literal["COMMENT"] -START_DOCUMENT: Literal["START_DOCUMENT"] -END_DOCUMENT: Literal["END_DOCUMENT"] -PROCESSING_INSTRUCTION: Literal["PROCESSING_INSTRUCTION"] -IGNORABLE_WHITESPACE: Literal["IGNORABLE_WHITESPACE"] -CHARACTERS: Literal["CHARACTERS"] +START_ELEMENT: Final = "START_ELEMENT" +END_ELEMENT: Final = "END_ELEMENT" +COMMENT: Final = "COMMENT" +START_DOCUMENT: Final = "START_DOCUMENT" +END_DOCUMENT: Final = "END_DOCUMENT" +PROCESSING_INSTRUCTION: Final = "PROCESSING_INSTRUCTION" +IGNORABLE_WHITESPACE: Final = "IGNORABLE_WHITESPACE" +CHARACTERS: Final = "CHARACTERS" -_DocumentFactory = Union[DOMImplementation, None] -_Node = Union[Document, Element, Text] +_NSName: TypeAlias = tuple[str | None, str] +_DocumentFactory: TypeAlias = DOMImplementation | None -_Event = Tuple[ - Literal[ - Literal["START_ELEMENT"], - Literal["END_ELEMENT"], - Literal["COMMENT"], - Literal["START_DOCUMENT"], - Literal["END_DOCUMENT"], - Literal["PROCESSING_INSTRUCTION"], - Literal["IGNORABLE_WHITESPACE"], - Literal["CHARACTERS"], - ], - _Node, -] +_Event: TypeAlias = ( + tuple[Literal["START_ELEMENT"], Element] + | tuple[Literal["END_ELEMENT"], Element] + | tuple[Literal["COMMENT"], Comment] + | tuple[Literal["START_DOCUMENT"], Document] + | tuple[Literal["END_DOCUMENT"], Document] + | tuple[Literal["PROCESSING_INSTRUCTION"], ProcessingInstruction] + | tuple[Literal["IGNORABLE_WHITESPACE"], Text] + | tuple[Literal["CHARACTERS"], Text] +) class PullDOM(ContentHandler): document: Document | None documentFactory: _DocumentFactory - firstEvent: Any - lastEvent: Any - elementStack: Sequence[Any] - pending_events: Sequence[Any] - def __init__(self, documentFactory: _DocumentFactory = ...) -> None: ... - def pop(self) -> Element: ... - def setDocumentLocator(self, locator) -> None: ... - def startPrefixMapping(self, prefix, uri) -> None: ... - def endPrefixMapping(self, prefix) -> None: ... - def startElementNS(self, name, tagName, attrs) -> None: ... - def endElementNS(self, name, tagName) -> None: ... - def startElement(self, name, attrs) -> None: ... - def endElement(self, name) -> None: ... - def comment(self, s) -> None: ... - def processingInstruction(self, target, data) -> None: ... - def ignorableWhitespace(self, chars) -> None: ... - def characters(self, chars) -> None: ... + + # firstEvent is a list of length 2 + # firstEvent[0] is always None + # firstEvent[1] is None prior to any events, after which it's a + # list of length 2, where the first item is of type _Event + # and the second item is None. + firstEvent: list[Incomplete] + + # lastEvent is also a list of length 2. The second item is always None, + # and the first item is of type _Event + # This is a slight lie: The second item is sometimes temporarily what was just + # described for the type of lastEvent, after which lastEvent is always updated + # with `self.lastEvent = self.lastEvent[1]`. + lastEvent: list[Incomplete] + + elementStack: MutableSequence[Element | Document] + pending_events: ( + list[Sequence[tuple[Literal["COMMENT"], str] | tuple[Literal["PROCESSING_INSTRUCTION"], str, str] | None]] | None + ) + def __init__(self, documentFactory: _DocumentFactory = None) -> None: ... + def pop(self) -> Element | Document: ... + def setDocumentLocator(self, locator: Locator) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ... + def endElementNS(self, name: _NSName, tagName: str | None) -> None: ... + def startElement(self, name: str, attrs: AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def comment(self, s: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def ignorableWhitespace(self, chars: str) -> None: ... + def characters(self, chars: str) -> None: ... def startDocument(self) -> None: ... - def buildDocument(self, uri, tagname): ... + def buildDocument(self, uri: str | None, tagname: str | None) -> Element: ... def endDocument(self) -> None: ... def clear(self) -> None: ... class ErrorHandler: - def warning(self, exception) -> None: ... - def error(self, exception) -> None: ... - def fatalError(self, exception) -> None: ... + def warning(self, exception: BaseException) -> None: ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... class DOMEventStream: - stream: IO[bytes] - parser: XMLReader + stream: _SupportsReadClose[bytes] | _SupportsReadClose[str] + parser: XMLReader # Set to none after .clear() is called bufsize: int - def __init__(self, stream: IO[bytes], parser: XMLReader, bufsize: int) -> None: ... - pulldom: Any + pulldom: PullDOM + def __init__(self, stream: _SupportsReadClose[bytes] | _SupportsReadClose[str], parser: XMLReader, bufsize: int) -> None: ... if sys.version_info < (3, 11): - def __getitem__(self, pos): ... - def __next__(self): ... - def __iter__(self): ... - def getEvent(self) -> _Event: ... - def expandNode(self, node: _Node) -> None: ... + def __getitem__(self, pos: Unused) -> _Event: ... + + def __next__(self) -> _Event: ... + def __iter__(self) -> Self: ... + def getEvent(self) -> _Event | None: ... + def expandNode(self, node: Document) -> None: ... def reset(self) -> None: ... def clear(self) -> None: ... class SAX2DOM(PullDOM): - def startElementNS(self, name, tagName, attrs) -> None: ... - def startElement(self, name, attrs) -> None: ... - def processingInstruction(self, target, data) -> None: ... - def ignorableWhitespace(self, chars) -> None: ... - def characters(self, chars) -> None: ... + def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ... + def startElement(self, name: str, attrs: AttributesImpl) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def ignorableWhitespace(self, chars: str) -> None: ... + def characters(self, chars: str) -> None: ... -default_bufsize: int +default_bufsize: Final[int] -def parse(stream_or_string: str | IO[bytes], parser: XMLReader | None = ..., bufsize: int | None = ...) -> DOMEventStream: ... -def parseString(string: str, parser: XMLReader | None = ...) -> DOMEventStream: ... +def parse( + stream_or_string: str | _SupportsReadClose[bytes] | _SupportsReadClose[str], + parser: XMLReader | None = None, + bufsize: int | None = None, +) -> DOMEventStream: ... +def parseString(string: str, parser: XMLReader | None = None) -> DOMEventStream: ... diff --git a/stdlib/xml/dom/xmlbuilder.pyi b/stdlib/xml/dom/xmlbuilder.pyi index 2738d735e73f..686c9d8efe8f 100644 --- a/stdlib/xml/dom/xmlbuilder.pyi +++ b/stdlib/xml/dom/xmlbuilder.pyi @@ -1,28 +1,9 @@ -from typing import Any, NoReturn, Optional -from typing_extensions import Literal -from urllib.request import OpenerDirector -from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS -from xml.dom.minidom import Node +from _typeshed import SupportsRead +from typing import Any, Final, Literal +from typing_extensions import Never +from xml.dom.minidom import Document, Node, _DOMErrorHandler -# UNKNOWN TYPES: -# - `Options.errorHandler`. -# The same as `_DOMBuilderErrorHandlerType`? -# Maybe `xml.sax.handler.ErrorHandler`? -# - Return type of DOMBuilder.getFeature(). -# We could get rid of the `Any` if we knew more -# about `Options.errorHandler`. - -# ALIASES REPRESENTING MORE UNKNOWN TYPES: - -# probably the same as `Options.errorHandler`? -# Maybe `xml.sax.handler.ErrorHandler`? -_DOMBuilderErrorHandlerType = Optional[Any] -# probably some kind of IO... -_DOMInputSourceCharacterStreamType = Optional[Any] -# probably a string?? -_DOMInputSourceStringDataType = Optional[Any] -# probably a string?? -_DOMInputSourceEncodingType = Optional[Any] +__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] class Options: namespaces: int @@ -42,66 +23,60 @@ class Options: charset_overrides_xml_encoding: bool infoset: bool supported_mediatypes_only: bool - errorHandler: Any | None - filter: DOMBuilderFilter | None # a guess, but seems likely + errorHandler: _DOMErrorHandler | None + filter: DOMBuilderFilter | None class DOMBuilder: - entityResolver: DOMEntityResolver | None # a guess, but seems likely - errorHandler: _DOMBuilderErrorHandlerType - filter: DOMBuilderFilter | None # a guess, but seems likely - ACTION_REPLACE: Literal[1] - ACTION_APPEND_AS_CHILDREN: Literal[2] - ACTION_INSERT_AFTER: Literal[3] - ACTION_INSERT_BEFORE: Literal[4] + entityResolver: DOMEntityResolver | None + errorHandler: _DOMErrorHandler | None + filter: DOMBuilderFilter | None + ACTION_REPLACE: Final = 1 + ACTION_APPEND_AS_CHILDREN: Final = 2 + ACTION_INSERT_AFTER: Final = 3 + ACTION_INSERT_BEFORE: Final = 4 def __init__(self) -> None: ... def setFeature(self, name: str, state: int) -> None: ... def supportsFeature(self, name: str) -> bool: ... - def canSetFeature(self, name: str, state: int) -> bool: ... + def canSetFeature(self, name: str, state: Literal[1, 0]) -> bool: ... # getFeature could return any attribute from an instance of `Options` def getFeature(self, name: str) -> Any: ... - def parseURI(self, uri: str) -> ExpatBuilder | ExpatBuilderNS: ... - def parse(self, input: DOMInputSource) -> ExpatBuilder | ExpatBuilderNS: ... - # `input` and `cnode` argtypes for `parseWithContext` are unknowable - # as the function does nothing with them, and always raises an exception. - # But `input` is *probably* `DOMInputSource`? - def parseWithContext(self, input: object, cnode: object, action: Literal[1, 2, 3, 4]) -> NoReturn: ... + def parseURI(self, uri: str) -> Document: ... + def parse(self, input: DOMInputSource) -> Document: ... + def parseWithContext(self, input: DOMInputSource, cnode: Node, action: Literal[1, 2, 3, 4]) -> Never: ... class DOMEntityResolver: + __slots__ = ("_opener",) def resolveEntity(self, publicId: str | None, systemId: str) -> DOMInputSource: ... class DOMInputSource: - byteStream: OpenerDirector | None - characterStream: _DOMInputSourceCharacterStreamType - stringData: _DOMInputSourceStringDataType - encoding: _DOMInputSourceEncodingType + __slots__ = ("byteStream", "characterStream", "stringData", "encoding", "publicId", "systemId", "baseURI") + byteStream: SupportsRead[bytes] | None + characterStream: SupportsRead[str] | None + stringData: str | None + encoding: str | None publicId: str | None systemId: str | None baseURI: str | None class DOMBuilderFilter: - FILTER_ACCEPT: Literal[1] - FILTER_REJECT: Literal[2] - FILTER_SKIP: Literal[3] - FILTER_INTERRUPT: Literal[4] + FILTER_ACCEPT: Final = 1 + FILTER_REJECT: Final = 2 + FILTER_SKIP: Final = 3 + FILTER_INTERRUPT: Final = 4 whatToShow: int - # The argtypes for acceptNode and startContainer appear to be irrelevant. - def acceptNode(self, element: object) -> Literal[1]: ... - def startContainer(self, element: object) -> Literal[1]: ... + def acceptNode(self, element: Node) -> Literal[1, 2, 3, 4]: ... + def startContainer(self, element: Node) -> Literal[1, 2, 3, 4]: ... class DocumentLS: async_: bool - def abort(self) -> NoReturn: ... - # `load()` and `loadXML()` always raise exceptions - # so the argtypes of `uri` and `source` are unknowable. - # `source` is *probably* `DOMInputSource`? - # `uri` is *probably* a str? (see DOMBuilder.parseURI()) - def load(self, uri: object) -> NoReturn: ... - def loadXML(self, source: object) -> NoReturn: ... + def abort(self) -> Never: ... + def load(self, uri: str) -> Never: ... + def loadXML(self, source: str) -> Never: ... def saveXML(self, snode: Node | None) -> str: ... class DOMImplementationLS: - MODE_SYNCHRONOUS: Literal[1] - MODE_ASYNCHRONOUS: Literal[2] + MODE_SYNCHRONOUS: Final = 1 + MODE_ASYNCHRONOUS: Final = 2 def createDOMBuilder(self, mode: Literal[1], schemaType: None) -> DOMBuilder: ... - def createDOMWriter(self) -> NoReturn: ... + def createDOMWriter(self) -> Never: ... def createDOMInputSource(self) -> DOMInputSource: ... diff --git a/stdlib/xml/etree/ElementInclude.pyi b/stdlib/xml/etree/ElementInclude.pyi index b355bef1208c..5db08fb0df05 100644 --- a/stdlib/xml/etree/ElementInclude.pyi +++ b/stdlib/xml/etree/ElementInclude.pyi @@ -1,26 +1,28 @@ -import sys -from typing import Callable +from _typeshed import FileDescriptorOrPath +from typing import Final, Literal, Protocol, overload, type_check_only from xml.etree.ElementTree import Element -XINCLUDE: str -XINCLUDE_INCLUDE: str -XINCLUDE_FALLBACK: str +@type_check_only +class _Loader(Protocol): + @overload + def __call__(self, href: FileDescriptorOrPath, parse: Literal["xml"], encoding: str | None = None) -> Element: ... + @overload + def __call__(self, href: FileDescriptorOrPath, parse: Literal["text"], encoding: str | None = None) -> str: ... -if sys.version_info >= (3, 9): - DEFAULT_MAX_INCLUSION_DEPTH: int +XINCLUDE: Final = "{http://www.w3.org/2001/XInclude}" + +XINCLUDE_INCLUDE: Final = "{http://www.w3.org/2001/XInclude}include" +XINCLUDE_FALLBACK: Final = "{http://www.w3.org/2001/XInclude}fallback" + +DEFAULT_MAX_INCLUSION_DEPTH: Final = 6 class FatalIncludeError(SyntaxError): ... -def default_loader(href: str | bytes | int, parse: str, encoding: str | None = ...) -> str | Element: ... +@overload +def default_loader(href: FileDescriptorOrPath, parse: Literal["xml"], encoding: str | None = None) -> Element: ... +@overload +def default_loader(href: FileDescriptorOrPath, parse: Literal["text"], encoding: str | None = None) -> str: ... -# TODO: loader is of type default_loader ie it takes a callable that has the -# same signature as default_loader. But default_loader has a keyword argument -# Which can't be represented using Callable... -if sys.version_info >= (3, 9): - def include( - elem: Element, loader: Callable[..., str | Element] | None = ..., base_url: str | None = ..., max_depth: int | None = ... - ) -> None: ... - class LimitedRecursiveIncludeError(FatalIncludeError): ... +def include(elem: Element, loader: _Loader | None = None, base_url: str | None = None, max_depth: int | None = 6) -> None: ... -else: - def include(elem: Element, loader: Callable[..., str | Element] | None = ...) -> None: ... +class LimitedRecursiveIncludeError(FatalIncludeError): ... diff --git a/stdlib/xml/etree/ElementPath.pyi b/stdlib/xml/etree/ElementPath.pyi index db4bd6a4e958..1dd6f86cead6 100644 --- a/stdlib/xml/etree/ElementPath.pyi +++ b/stdlib/xml/etree/ElementPath.pyi @@ -1,31 +1,42 @@ -from typing import Callable, Generator, List, Pattern, Tuple, TypeVar +from collections.abc import Callable, Generator, Iterable +from re import Pattern +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload from xml.etree.ElementTree import Element -xpath_tokenizer_re: Pattern[str] +xpath_tokenizer_re: Final[Pattern[str]] -_token = Tuple[str, str] -_next = Callable[[], _token] -_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] +_Token: TypeAlias = tuple[str, str] +_Next: TypeAlias = Callable[[], _Token] +_Callback: TypeAlias = Callable[[_SelectorContext, Iterable[Element]], Generator[Element]] +_T = TypeVar("_T") -def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = ...) -> Generator[_token, None, None]: ... +def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = None) -> Generator[_Token]: ... def get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ... -def prepare_child(next: _next, token: _token) -> _callback: ... -def prepare_star(next: _next, token: _token) -> _callback: ... -def prepare_self(next: _next, token: _token) -> _callback: ... -def prepare_descendant(next: _next, token: _token) -> _callback: ... -def prepare_parent(next: _next, token: _token) -> _callback: ... -def prepare_predicate(next: _next, token: _token) -> _callback: ... +def prepare_child(next: _Next, token: _Token) -> _Callback: ... +def prepare_star(next: _Next, token: _Token) -> _Callback: ... +def prepare_self(next: _Next, token: _Token) -> _Callback: ... +def prepare_descendant(next: _Next, token: _Token) -> _Callback | None: ... +def prepare_parent(next: _Next, token: _Token) -> _Callback: ... +def prepare_predicate(next: _Next, token: _Token) -> _Callback | None: ... -ops: dict[str, Callable[[_next, _token], _callback]] +ops: Final[dict[str, Callable[[_Next, _Token], _Callback | None]]] class _SelectorContext: parent_map: dict[Element, Element] | None root: Element def __init__(self, root: Element) -> None: ... -_T = TypeVar("_T") +@overload +def iterfind( # type: ignore[overload-overlap] + elem: Element[Any], path: Literal[""], namespaces: dict[str, str] | None = None +) -> None: ... +@overload +def iterfind(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + +def find(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... +def findall(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... -def iterfind(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... -def find(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> Element | None: ... -def findall(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> list[Element]: ... -def findtext(elem: Element, path: str, default: _T | None = ..., namespaces: dict[str, str] | None = ...) -> _T | str: ... +@overload +def findtext(elem: Element[Any], path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... +@overload +def findtext(elem: Element[Any], path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... diff --git a/stdlib/xml/etree/ElementTree.pyi b/stdlib/xml/etree/ElementTree.pyi index 6ee578b9aa81..c77af2cb4dd1 100644 --- a/stdlib/xml/etree/ElementTree.pyi +++ b/stdlib/xml/etree/ElementTree.pyi @@ -1,252 +1,316 @@ import sys -from _typeshed import FileDescriptor, StrOrBytesPath, SupportsWrite -from typing import ( - IO, - Any, - Callable, - Dict, - Generator, - ItemsView, - Iterable, - Iterator, - KeysView, - Mapping, - MutableSequence, - Sequence, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal, SupportsIndex +from _collections_abc import dict_keys +from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite +from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence +from typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeAlias, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import deprecated, disjoint_base +from xml.parsers.expat import XMLParserType + +__all__ = [ + "C14NWriterTarget", + "Comment", + "dump", + "Element", + "ElementTree", + "canonicalize", + "fromstring", + "fromstringlist", + "indent", + "iselement", + "iterparse", + "parse", + "ParseError", + "PI", + "ProcessingInstruction", + "QName", + "SubElement", + "tostring", + "tostringlist", + "TreeBuilder", + "XML", + "XMLID", + "XMLParser", + "XMLPullParser", + "register_namespace", +] +if sys.version_info < (3, 15): + __all__ += ["VERSION"] _T = TypeVar("_T") -_File = Union[StrOrBytesPath, FileDescriptor, IO[Any]] +_FileRead: TypeAlias = FileDescriptorOrPath | SupportsRead[bytes] | SupportsRead[str] +_FileWriteC14N: TypeAlias = FileDescriptorOrPath | SupportsWrite[bytes] +_FileWrite: TypeAlias = _FileWriteC14N | SupportsWrite[str] -VERSION: str +VERSION: Final[str] class ParseError(SyntaxError): code: int position: tuple[int, int] -def iselement(element: object) -> bool: ... +# In reality it works based on `.tag` attribute duck typing. +def iselement(element: object) -> TypeGuard[Element]: ... -if sys.version_info >= (3, 8): - @overload - def canonicalize( - xml_data: str | bytes | None = ..., - *, - out: None = ..., - from_file: _File | None = ..., - with_comments: bool = ..., - strip_text: bool = ..., - rewrite_prefixes: bool = ..., - qname_aware_tags: Iterable[str] | None = ..., - qname_aware_attrs: Iterable[str] | None = ..., - exclude_attrs: Iterable[str] | None = ..., - exclude_tags: Iterable[str] | None = ..., - ) -> str: ... - @overload - def canonicalize( - xml_data: str | bytes | None = ..., - *, - out: SupportsWrite[str], - from_file: _File | None = ..., - with_comments: bool = ..., - strip_text: bool = ..., - rewrite_prefixes: bool = ..., - qname_aware_tags: Iterable[str] | None = ..., - qname_aware_attrs: Iterable[str] | None = ..., - exclude_attrs: Iterable[str] | None = ..., - exclude_tags: Iterable[str] | None = ..., - ) -> None: ... +@overload +def canonicalize( + xml_data: str | ReadableBuffer | None = None, + *, + out: None = None, + from_file: _FileRead | None = None, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, +) -> str: ... +@overload +def canonicalize( + xml_data: str | ReadableBuffer | None = None, + *, + out: SupportsWrite[str], + from_file: _FileRead | None = None, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, +) -> None: ... + +# The tag for Element can be set to the Comment or ProcessingInstruction +# functions defined in this module. +_ElementCallable: TypeAlias = Callable[..., Element[_ElementCallable]] + +_Tag = TypeVar("_Tag", default=str, bound=str | _ElementCallable) +_OtherTag = TypeVar("_OtherTag", default=str, bound=str | _ElementCallable) -class Element(MutableSequence[Element]): - tag: str +@disjoint_base +class Element(Generic[_Tag]): + tag: _Tag attrib: dict[str, str] text: str | None tail: str | None - def __init__(self, tag: str | Callable[..., Element], attrib: dict[str, str] = ..., **extra: str) -> None: ... - def append(self, __subelement: Element) -> None: ... + def __init__(self, tag: _Tag, attrib: dict[str, str] = {}, **extra: str) -> None: ... + def append(self, subelement: Element[Any], /) -> None: ... def clear(self) -> None: ... - def extend(self, __elements: Iterable[Element]) -> None: ... - def find(self, path: str, namespaces: dict[str, str] | None = ...) -> Element | None: ... - def findall(self, path: str, namespaces: dict[str, str] | None = ...) -> list[Element]: ... + def extend(self, elements: Iterable[Element[Any]], /) -> None: ... + def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... + def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + @overload - def findtext(self, path: str, default: None = ..., namespaces: dict[str, str] | None = ...) -> str | None: ... + def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... @overload - def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = ...) -> _T | str: ... + def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... + @overload - def get(self, key: str, default: None = ...) -> str | None: ... + def get(self, key: str, default: None = None) -> str | None: ... @overload def get(self, key: str, default: _T) -> str | _T: ... - def insert(self, __index: int, __subelement: Element) -> None: ... + + def insert(self, index: int, subelement: Element[Any], /) -> None: ... def items(self) -> ItemsView[str, str]: ... - def iter(self, tag: str | None = ...) -> Generator[Element, None, None]: ... - def iterfind(self, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... - def itertext(self) -> Generator[str, None, None]: ... - def keys(self) -> KeysView[str]: ... - def makeelement(self, __tag: str, __attrib: dict[str, str]) -> Element: ... - def remove(self, __subelement: Element) -> None: ... - def set(self, __key: str, __value: str) -> None: ... - def __delitem__(self, i: SupportsIndex | slice) -> None: ... + def iter(self, tag: str | None = None) -> Generator[Element]: ... + + @overload + def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] + @overload + def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + + def itertext(self) -> Generator[str]: ... + def keys(self) -> dict_keys[str, str]: ... + # makeelement returns the type of self in Python impl, but not in C impl + def makeelement(self, tag: _OtherTag, attrib: dict[str, str], /) -> Element[_OtherTag]: ... + def remove(self, subelement: Element[Any], /) -> None: ... + def set(self, key: str, value: str, /) -> None: ... + def __copy__(self) -> Element[_Tag]: ... # returns the type of self in Python impl, but not in C impl + def __deepcopy__(self, memo: Any, /) -> Element: ... # Only exists in C impl + def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... + @overload - def __getitem__(self, i: SupportsIndex) -> Element: ... + def __getitem__(self, key: SupportsIndex, /) -> Element: ... @overload - def __getitem__(self, s: slice) -> MutableSequence[Element]: ... + def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Element]: ... + def __len__(self) -> int: ... + # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__. + def __iter__(self) -> Iterator[Element]: ... + @overload - def __setitem__(self, i: SupportsIndex, o: Element) -> None: ... + def __setitem__(self, key: SupportsIndex, value: Element[Any], /) -> None: ... @overload - def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... - if sys.version_info < (3, 9): - def getchildren(self) -> list[Element]: ... - def getiterator(self, tag: str | None = ...) -> list[Element]: ... + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Element[Any]], /) -> None: ... + + # Doesn't really exist in earlier versions, where __len__ is called implicitly instead + @deprecated("Testing an element's truth value is deprecated.") + def __bool__(self) -> bool: ... -def SubElement(parent: Element, tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ... -def Comment(text: str | None = ...) -> Element: ... -def ProcessingInstruction(target: str, text: str | None = ...) -> Element: ... +def SubElement(parent: Element[Any], tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ... +def Comment(text: str | None = None) -> Element[_ElementCallable]: ... +def ProcessingInstruction(target: str, text: str | None = None) -> Element[_ElementCallable]: ... -PI: Callable[..., Element] +PI = ProcessingInstruction class QName: text: str - def __init__(self, text_or_uri: str, tag: str | None = ...) -> None: ... - -class ElementTree: - def __init__(self, element: Element | None = ..., file: _File | None = ...) -> None: ... - def getroot(self) -> Element: ... - def parse(self, source: _File, parser: XMLParser | None = ...) -> Element: ... - def iter(self, tag: str | None = ...) -> Generator[Element, None, None]: ... - if sys.version_info < (3, 9): - def getiterator(self, tag: str | None = ...) -> list[Element]: ... - def find(self, path: str, namespaces: dict[str, str] | None = ...) -> Element | None: ... + def __init__(self, text_or_uri: str, tag: str | None = None) -> None: ... + def __lt__(self, other: QName | str) -> bool: ... + def __le__(self, other: QName | str) -> bool: ... + def __gt__(self, other: QName | str) -> bool: ... + def __ge__(self, other: QName | str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +_Root = TypeVar("_Root", Element, Element | None, default=Element | None) + +class ElementTree(Generic[_Root]): + def __init__(self, element: Element[Any] | None = None, file: _FileRead | None = None) -> None: ... + def getroot(self) -> _Root: ... + def _setroot(self, element: Element[Any]) -> None: ... + def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ... + def iter(self, tag: str | None = None) -> Generator[Element]: ... + def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... + @overload - def findtext(self, path: str, default: None = ..., namespaces: dict[str, str] | None = ...) -> str | None: ... + def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... @overload - def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = ...) -> _T | str: ... - def findall(self, path: str, namespaces: dict[str, str] | None = ...) -> list[Element]: ... - def iterfind(self, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... + def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... + + def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + + @overload + def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] + @overload + def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + def write( self, - file_or_filename: _File, - encoding: str | None = ..., - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - method: str | None = ..., + file_or_filename: _FileWrite, + encoding: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + method: Literal["xml", "html", "text", "c14n"] | None = None, *, - short_empty_elements: bool = ..., + short_empty_elements: bool = True, ) -> None: ... - def write_c14n(self, file: _File) -> None: ... + def write_c14n(self, file: _FileWriteC14N) -> None: ... + +HTML_EMPTY: Final[set[str]] def register_namespace(prefix: str, uri: str) -> None: ... -if sys.version_info >= (3, 8): - @overload - def tostring( - element: Element, - encoding: None = ..., - method: str | None = ..., - *, - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - short_empty_elements: bool = ..., - ) -> bytes: ... - @overload - def tostring( - element: Element, - encoding: Literal["unicode"], - method: str | None = ..., - *, - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - short_empty_elements: bool = ..., - ) -> str: ... - @overload - def tostring( - element: Element, - encoding: str, - method: str | None = ..., - *, - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - short_empty_elements: bool = ..., - ) -> Any: ... - @overload - def tostringlist( - element: Element, - encoding: None = ..., - method: str | None = ..., - *, - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - short_empty_elements: bool = ..., - ) -> list[bytes]: ... - @overload - def tostringlist( - element: Element, - encoding: Literal["unicode"], - method: str | None = ..., - *, - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - short_empty_elements: bool = ..., - ) -> list[str]: ... - @overload - def tostringlist( - element: Element, - encoding: str, - method: str | None = ..., - *, - xml_declaration: bool | None = ..., - default_namespace: str | None = ..., - short_empty_elements: bool = ..., - ) -> list[Any]: ... +@overload +def tostring( + element: Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> bytes: ... +@overload +def tostring( + element: Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> str: ... +@overload +def tostring( + element: Element[Any], + encoding: str, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> Any: ... -else: - @overload - def tostring( - element: Element, encoding: None = ..., method: str | None = ..., *, short_empty_elements: bool = ... - ) -> bytes: ... - @overload - def tostring( - element: Element, encoding: Literal["unicode"], method: str | None = ..., *, short_empty_elements: bool = ... - ) -> str: ... - @overload - def tostring(element: Element, encoding: str, method: str | None = ..., *, short_empty_elements: bool = ...) -> Any: ... - @overload - def tostringlist( - element: Element, encoding: None = ..., method: str | None = ..., *, short_empty_elements: bool = ... - ) -> list[bytes]: ... - @overload - def tostringlist( - element: Element, encoding: Literal["unicode"], method: str | None = ..., *, short_empty_elements: bool = ... - ) -> list[str]: ... - @overload - def tostringlist( - element: Element, encoding: str, method: str | None = ..., *, short_empty_elements: bool = ... - ) -> list[Any]: ... +@overload +def tostringlist( + element: Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[bytes]: ... +@overload +def tostringlist( + element: Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[str]: ... +@overload +def tostringlist( + element: Element[Any], + encoding: str, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[Any]: ... + +def dump(elem: Element[Any] | ElementTree[Any]) -> None: ... +def indent(tree: Element[Any] | ElementTree[Any], space: str = " ", level: int = 0) -> None: ... +def parse(source: _FileRead, parser: XMLParser[Any] | None = None) -> ElementTree[Element]: ... + +# The type of the second element of the tuple yielded by iterparse depends +# on the event type in the first element of the tuple: +# * start, end: Element[str] +# * comment, pi: Element[_ElementCallable] +# * start-ns: tuple[str, str] (prefix, uri) +# * end-ns: None +_EventT_co = TypeVar("_EventT_co", bound=Element[str] | Element[_ElementCallable] | tuple[str, str] | None, covariant=True) +_EventType: TypeAlias = Literal["start", "end", "comment", "pi", "start-ns", "end-ns"] + +# This class is defined inside the body of iterparse. +@type_check_only +class _IterParseIterator(Iterator[tuple[_EventType, _EventT_co]], Protocol[_EventT_co]): + if sys.version_info >= (3, 13): + def close(self) -> None: ... + if sys.version_info >= (3, 11): + def __del__(self) -> None: ... -def dump(elem: Element) -> None: ... +# See the comment for _EventT_co above for possible iterator types. +@overload +def iterparse(source: _FileRead, events: Iterable[_EventType]) -> _IterParseIterator[Any]: ... +@overload +def iterparse(source: _FileRead, events: None = None) -> _IterParseIterator[Element[str]]: ... -if sys.version_info >= (3, 9): - def indent(tree: Element | ElementTree, space: str = ..., level: int = ...) -> None: ... +# In case a custom parser is passed, the type of the second element of the tuple +# yielded by iterparse depends on the parser. +@overload +@deprecated("The `parser` parameter is deprecated since Python 3.4.") +def iterparse(source: _FileRead, events: Iterable[_EventType], parser: XMLParser | None = None) -> _IterParseIterator[Any]: ... -def parse(source: _File, parser: XMLParser | None = ...) -> ElementTree: ... -def iterparse(source: _File, events: Sequence[str] | None = ..., parser: XMLParser | None = ...) -> Iterator[tuple[str, Any]]: ... +_EventQueue: TypeAlias = tuple[str] | tuple[str, tuple[str, str]] | tuple[str, None] -class XMLPullParser: - def __init__(self, events: Sequence[str] | None = ..., *, _parser: XMLParser | None = ...) -> None: ... - def feed(self, data: bytes) -> None: ... +class XMLPullParser(Generic[_EventT_co]): + def __init__(self, events: Iterable[_EventType] | None = None, *, _parser: XMLParser[_EventT_co] | None = None) -> None: ... + def feed(self, data: str | ReadableBuffer) -> None: ... def close(self) -> None: ... - def read_events(self) -> Iterator[tuple[str, Element]]: ... + def read_events(self) -> Iterator[_EventQueue | tuple[_EventType, _EventT_co]]: ... + def flush(self) -> None: ... -def XML(text: str | bytes, parser: XMLParser | None = ...) -> Element: ... -def XMLID(text: str | bytes, parser: XMLParser | None = ...) -> tuple[Element, dict[str, Element]]: ... +def XML(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: ... +def XMLID(text: str | ReadableBuffer, parser: XMLParser | None = None) -> tuple[Element, dict[str, Element]]: ... # This is aliased to XML in the source. fromstring = XML -def fromstringlist(sequence: Sequence[str | bytes], parser: XMLParser | None = ...) -> Element: ... +def fromstringlist(sequence: Sequence[str | ReadableBuffer], parser: XMLParser | None = None) -> Element: ... # This type is both not precise enough and too precise. The TreeBuilder # requires the elementfactory to accept tag and attrs in its args and produce @@ -257,64 +321,82 @@ def fromstringlist(sequence: Sequence[str | bytes], parser: XMLParser | None = . # TreeBuilder is called by client code (they could pass strs, bytes or whatever); # but we don't want to use a too-broad type, or it would be too hard to write # elementfactories. -_ElementFactory = Callable[[Any, Dict[Any, Any]], Element] +_ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element] +@disjoint_base class TreeBuilder: - if sys.version_info >= (3, 8): - # comment_factory can take None because passing None to Comment is not an error - def __init__( - self, - element_factory: _ElementFactory | None = ..., - *, - comment_factory: Callable[[str | None], Element] | None = ..., - pi_factory: Callable[[str, str | None], Element] | None = ..., - insert_comments: bool = ..., - insert_pis: bool = ..., - ) -> None: ... - insert_comments: bool - insert_pis: bool - else: - def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... + # comment_factory can take None because passing None to Comment is not an error + def __init__( + self, + element_factory: _ElementFactory | None = None, + *, + comment_factory: Callable[[str | None], Element[Any]] | None = None, + pi_factory: Callable[[str, str | None], Element[Any]] | None = None, + insert_comments: bool = False, + insert_pis: bool = False, + ) -> None: ... + insert_comments: bool + insert_pis: bool + def close(self) -> Element: ... - def data(self, __data: str | bytes) -> None: ... - def start(self, __tag: str | bytes, __attrs: dict[str | bytes, str | bytes]) -> Element: ... - def end(self, __tag: str | bytes) -> Element: ... - if sys.version_info >= (3, 8): - # These two methods have pos-only parameters in the C implementation - def comment(self, __text: str | None) -> Element: ... - def pi(self, __target: str, __text: str | None = ...) -> Element: ... - -if sys.version_info >= (3, 8): - class C14NWriterTarget: - def __init__( - self, - write: Callable[[str], Any], - *, - with_comments: bool = ..., - strip_text: bool = ..., - rewrite_prefixes: bool = ..., - qname_aware_tags: Iterable[str] | None = ..., - qname_aware_attrs: Iterable[str] | None = ..., - exclude_attrs: Iterable[str] | None = ..., - exclude_tags: Iterable[str] | None = ..., - ) -> None: ... - def data(self, data: str) -> None: ... - def start_ns(self, prefix: str, uri: str) -> None: ... - def start(self, tag: str, attrs: Mapping[str, str]) -> None: ... - def end(self, tag: str) -> None: ... - def comment(self, text: str) -> None: ... - def pi(self, target: str, data: str) -> None: ... - -class XMLParser: - parser: Any - target: Any - # TODO-what is entity used for??? - entity: Any + def data(self, data: str, /) -> None: ... + # tag and attrs are passed to the element_factory, so they could be anything + # depending on what the particular factory supports. + def start(self, tag: Any, attrs: dict[Any, Any], /) -> Element: ... + def end(self, tag: str, /) -> Element: ... + # These two methods have pos-only parameters in the C implementation + def comment(self, text: str | None, /) -> Element[Any]: ... + def pi(self, target: str, text: str | None = None, /) -> Element[Any]: ... + +class C14NWriterTarget: + def __init__( + self, + write: Callable[[str], object], + *, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, + ) -> None: ... + def data(self, data: str) -> None: ... + def start_ns(self, prefix: str, uri: str) -> None: ... + def start(self, tag: str, attrs: Mapping[str, str]) -> None: ... + def end(self, tag: str) -> None: ... + def comment(self, text: str) -> None: ... + def pi(self, target: str, data: str) -> None: ... + +# The target type is tricky, because the implementation doesn't +# require any particular attribute to be present. This documents the attributes +# that can be present, but uncommenting any of them would require them. +@type_check_only +class _Target(Protocol): + # start: Callable[str, dict[str, str], Any] | None + # end: Callable[[str], Any] | None + # start_ns: Callable[[str, str], Any] | None + # end_ns: Callable[[str], Any] | None + # data: Callable[[str], Any] | None + # comment: Callable[[str], Any] + # pi: Callable[[str, str], Any] | None + # close: Callable[[], Any] | None + ... + +_E = TypeVar("_E", default=Element) + +# This is generic because the return type of close() depends on the target. +# The default target is TreeBuilder, which returns Element. +# C14NWriterTarget does not implement a close method, so using it results +# in a type of XMLParser[None]. +@disjoint_base +class XMLParser(Generic[_E]): + parser: XMLParserType + target: _Target + # TODO: what is entity used for??? + entity: dict[str, str] version: str - if sys.version_info >= (3, 8): - def __init__(self, *, target: Any = ..., encoding: str | None = ...) -> None: ... - else: - def __init__(self, html: int = ..., target: Any = ..., encoding: str | None = ...) -> None: ... - def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... - def close(self) -> Any: ... - def feed(self, __data: str | bytes) -> None: ... + def __init__(self, *, target: _Target | None = None, encoding: str | None = None) -> None: ... + def close(self) -> _E: ... + def feed(self, data: str | ReadableBuffer, /) -> None: ... + def flush(self) -> None: ... diff --git a/stdlib/xml/etree/cElementTree.pyi b/stdlib/xml/etree/cElementTree.pyi index c41e2bee0eb1..02272d803c18 100644 --- a/stdlib/xml/etree/cElementTree.pyi +++ b/stdlib/xml/etree/cElementTree.pyi @@ -1 +1 @@ -from xml.etree.ElementTree import * # noqa: F403 +from xml.etree.ElementTree import * diff --git a/stdlib/xml/parsers/__init__.pyi b/stdlib/xml/parsers/__init__.pyi index cac086235cba..cebdb6a30014 100644 --- a/stdlib/xml/parsers/__init__.pyi +++ b/stdlib/xml/parsers/__init__.pyi @@ -1 +1 @@ -import xml.parsers.expat as expat +from xml.parsers import expat as expat diff --git a/stdlib/xml/parsers/expat/__init__.pyi b/stdlib/xml/parsers/expat/__init__.pyi index 73f3758c61ec..d9b7ea536999 100644 --- a/stdlib/xml/parsers/expat/__init__.pyi +++ b/stdlib/xml/parsers/expat/__init__.pyi @@ -1 +1,7 @@ from pyexpat import * + +# This is actually implemented in the C module pyexpat, but considers itself to live here. +class ExpatError(Exception): + code: int + lineno: int + offset: int diff --git a/stdlib/xml/sax/__init__.pyi b/stdlib/xml/sax/__init__.pyi index a123e7e894e2..9b5c3bf4ddea 100644 --- a/stdlib/xml/sax/__init__.pyi +++ b/stdlib/xml/sax/__init__.pyi @@ -1,33 +1,42 @@ import sys -from typing import IO, Any, Iterable, NoReturn -from xml.sax.handler import ContentHandler, ErrorHandler -from xml.sax.xmlreader import Locator, XMLReader +from _typeshed import ReadableBuffer, StrPath, SupportsRead, _T_co +from collections.abc import Iterable +from typing import Final, Protocol, TypeAlias, type_check_only +from xml.sax._exceptions import ( + SAXException as SAXException, + SAXNotRecognizedException as SAXNotRecognizedException, + SAXNotSupportedException as SAXNotSupportedException, + SAXParseException as SAXParseException, + SAXReaderNotAvailable as SAXReaderNotAvailable, +) +from xml.sax.handler import ContentHandler as ContentHandler, ErrorHandler as ErrorHandler +from xml.sax.xmlreader import InputSource as InputSource, XMLReader -class SAXException(Exception): - def __init__(self, msg: str, exception: Exception | None = ...) -> None: ... - def getMessage(self) -> str: ... - def getException(self) -> Exception: ... - def __getitem__(self, ix: Any) -> NoReturn: ... +@type_check_only +class _SupportsReadClose(SupportsRead[_T_co], Protocol[_T_co]): + def close(self) -> None: ... -class SAXParseException(SAXException): - def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... - def getColumnNumber(self) -> int: ... - def getLineNumber(self) -> int: ... - def getPublicId(self): ... - def getSystemId(self): ... +_Source: TypeAlias = StrPath | _SupportsReadClose[bytes] | _SupportsReadClose[str] -class SAXNotRecognizedException(SAXException): ... -class SAXNotSupportedException(SAXException): ... -class SAXReaderNotAvailable(SAXNotSupportedException): ... +default_parser_list: Final[list[str]] -default_parser_list: list[str] - -if sys.version_info >= (3, 8): - def make_parser(parser_list: Iterable[str] = ...) -> XMLReader: ... - -else: - def make_parser(parser_list: list[str] = ...) -> XMLReader: ... - -def parse(source: str | IO[str] | IO[bytes], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... -def parseString(string: bytes | str, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... +def make_parser(parser_list: Iterable[str] = ()) -> XMLReader: ... +def parse(source: _Source, handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... +def parseString(string: ReadableBuffer | str, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... def _create_parser(parser_name: str) -> XMLReader: ... + +if sys.version_info >= (3, 14): + __all__ = [ + "ContentHandler", + "ErrorHandler", + "InputSource", + "SAXException", + "SAXNotRecognizedException", + "SAXNotSupportedException", + "SAXParseException", + "SAXReaderNotAvailable", + "default_parser_list", + "make_parser", + "parse", + "parseString", + ] diff --git a/stdlib/xml/sax/_exceptions.pyi b/stdlib/xml/sax/_exceptions.pyi new file mode 100644 index 000000000000..8f5e3a827185 --- /dev/null +++ b/stdlib/xml/sax/_exceptions.pyi @@ -0,0 +1,19 @@ +from typing_extensions import Never +from xml.sax.xmlreader import Locator + +class SAXException(Exception): + def __init__(self, msg: str, exception: Exception | None = None) -> None: ... + def getMessage(self) -> str: ... + def getException(self) -> Exception | None: ... + def __getitem__(self, ix: object) -> Never: ... + +class SAXParseException(SAXException): + def __init__(self, msg: str, exception: Exception | None, locator: Locator) -> None: ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int | None: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + +class SAXNotRecognizedException(SAXException): ... +class SAXNotSupportedException(SAXException): ... +class SAXReaderNotAvailable(SAXNotSupportedException): ... diff --git a/stdlib/xml/sax/expatreader.pyi b/stdlib/xml/sax/expatreader.pyi new file mode 100644 index 000000000000..e29853ebc3fe --- /dev/null +++ b/stdlib/xml/sax/expatreader.pyi @@ -0,0 +1,72 @@ +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from typing import Any, Final, Literal, TypeAlias, overload +from xml.sax import _Source, xmlreader +from xml.sax.handler import LexicalHandler, _ContentHandlerProtocol + +_BoolType: TypeAlias = Literal[0, 1] | bool + +version: Final[str] +AttributesImpl = xmlreader.AttributesImpl +AttributesNSImpl = xmlreader.AttributesNSImpl + +class _ClosedParser: + ErrorColumnNumber: int + ErrorLineNumber: int + +class ExpatLocator(xmlreader.Locator): + def __init__(self, parser: ExpatParser) -> None: ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + +class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): + def __init__(self, namespaceHandling: _BoolType = 0, bufsize: int = 65516) -> None: ... + def parse(self, source: xmlreader.InputSource | _Source) -> None: ... + def prepareParser(self, source: xmlreader.InputSource) -> None: ... + def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ... + def getFeature(self, name: str) -> _BoolType: ... + def setFeature(self, name: str, state: _BoolType) -> None: ... + + @overload + def getProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"]) -> LexicalHandler | None: ... + @overload + def getProperty(self, name: Literal["http://www.python.org/sax/properties/interning-dict"]) -> dict[str, Any] | None: ... + @overload + def getProperty(self, name: Literal["http://xml.org/sax/properties/xml-string"]) -> bytes | None: ... + @overload + def getProperty(self, name: str) -> object: ... + + @overload + def setProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"], value: LexicalHandler) -> None: ... + @overload + def setProperty( + self, name: Literal["http://www.python.org/sax/properties/interning-dict"], value: dict[str, Any] + ) -> None: ... + @overload + def setProperty(self, name: str, value: object) -> None: ... + + def feed(self, data: str | ReadableBuffer, isFinal: bool = False) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + def start_element(self, name: str, attrs: Mapping[str, str]) -> None: ... + def end_element(self, name: str) -> None: ... + def start_element_ns(self, name: str, attrs: Mapping[str, str]) -> None: ... + def end_element_ns(self, name: str) -> None: ... + def processing_instruction(self, target: str, data: str) -> None: ... + def character_data(self, data: str) -> None: ... + def start_namespace_decl(self, prefix: str | None, uri: str) -> None: ... + def end_namespace_decl(self, prefix: str | None) -> None: ... + def start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def unparsed_entity_decl(self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str) -> None: ... + def notation_decl(self, name: str, base: str | None, sysid: str, pubid: str | None) -> None: ... + def external_entity_ref(self, context: str, base: str | None, sysid: str, pubid: str | None) -> int: ... + def skipped_entity_handler(self, name: str, is_pe: bool) -> None: ... + +def create_parser(namespaceHandling: int = 0, bufsize: int = 65516) -> ExpatParser: ... diff --git a/stdlib/xml/sax/handler.pyi b/stdlib/xml/sax/handler.pyi index 3a5193300981..654c98866cfb 100644 --- a/stdlib/xml/sax/handler.pyi +++ b/stdlib/xml/sax/handler.pyi @@ -1,46 +1,85 @@ -from typing import Any +from typing import Final, Protocol, type_check_only +from typing_extensions import Never +from xml.sax import xmlreader -version: Any +version: Final[str] + +@type_check_only +class _ErrorHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + def warning(self, exception: BaseException) -> None: ... class ErrorHandler: - def error(self, exception): ... - def fatalError(self, exception): ... - def warning(self, exception): ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + def warning(self, exception: BaseException) -> None: ... + +@type_check_only +class _ContentHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used + def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, whitespace: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def skippedEntity(self, name: str) -> None: ... class ContentHandler: - def __init__(self) -> None: ... - def setDocumentLocator(self, locator): ... - def startDocument(self): ... - def endDocument(self): ... - def startPrefixMapping(self, prefix, uri): ... - def endPrefixMapping(self, prefix): ... - def startElement(self, name, attrs): ... - def endElement(self, name): ... - def startElementNS(self, name, qname, attrs): ... - def endElementNS(self, name, qname): ... - def characters(self, content): ... - def ignorableWhitespace(self, whitespace): ... - def processingInstruction(self, target, data): ... - def skippedEntity(self, name): ... + def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, whitespace: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def skippedEntity(self, name: str) -> None: ... + +@type_check_only +class _DTDHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used + def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ... + def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... class DTDHandler: - def notationDecl(self, name, publicId, systemId): ... - def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... + def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ... + def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... + +@type_check_only +class _EntityResolverProtocol(Protocol): # noqa: Y046 # Protocol is not used + def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... class EntityResolver: - def resolveEntity(self, publicId, systemId): ... - -feature_namespaces: Any -feature_namespace_prefixes: Any -feature_string_interning: Any -feature_validation: Any -feature_external_ges: Any -feature_external_pes: Any -all_features: Any -property_lexical_handler: Any -property_declaration_handler: Any -property_dom_node: Any -property_xml_string: Any -property_encoding: Any -property_interning_dict: Any -all_properties: Any + def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... + +feature_namespaces: Final = "http://xml.org/sax/features/namespaces" +feature_namespace_prefixes: Final = "http://xml.org/sax/features/namespace-prefixes" +feature_string_interning: Final = "http://xml.org/sax/features/string-interning" +feature_validation: Final = "http://xml.org/sax/features/validation" +feature_external_ges: Final[str] # too long string +feature_external_pes: Final[str] # too long string +all_features: Final[list[str]] +property_lexical_handler: Final = "http://xml.org/sax/properties/lexical-handler" +property_declaration_handler: Final = "http://xml.org/sax/properties/declaration-handler" +property_dom_node: Final = "http://xml.org/sax/properties/dom-node" +property_xml_string: Final = "http://xml.org/sax/properties/xml-string" +property_encoding: Final = "http://www.python.org/sax/properties/encoding" +property_interning_dict: Final[str] # too long string +all_properties: Final[list[str]] + +class LexicalHandler: + def comment(self, content: str) -> None: ... + def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> None: ... + def endDTD(self) -> None: ... + def startCDATA(self) -> None: ... + def endCDATA(self) -> None: ... diff --git a/stdlib/xml/sax/saxutils.pyi b/stdlib/xml/sax/saxutils.pyi index c7304f4b5261..0f5251def6b0 100644 --- a/stdlib/xml/sax/saxutils.pyi +++ b/stdlib/xml/sax/saxutils.pyi @@ -1,60 +1,69 @@ from _typeshed import SupportsWrite from codecs import StreamReaderWriter, StreamWriter +from collections.abc import Mapping from io import RawIOBase, TextIOBase -from typing import Mapping -from xml.sax import handler, xmlreader +from typing import Literal +from typing_extensions import Never +from xml.sax import _Source, handler, xmlreader -def escape(data: str, entities: Mapping[str, str] = ...) -> str: ... -def unescape(data: str, entities: Mapping[str, str] = ...) -> str: ... -def quoteattr(data: str, entities: Mapping[str, str] = ...) -> str: ... +def escape(data: str, entities: Mapping[str, str] = {}) -> str: ... +def unescape(data: str, entities: Mapping[str, str] = {}) -> str: ... +def quoteattr(data: str, entities: Mapping[str, str] = {}) -> str: ... class XMLGenerator(handler.ContentHandler): def __init__( self, - out: TextIOBase | RawIOBase | StreamWriter | StreamReaderWriter | SupportsWrite[str] | None = ..., - encoding: str = ..., - short_empty_elements: bool = ..., + out: TextIOBase | RawIOBase | StreamWriter | StreamReaderWriter | SupportsWrite[bytes] | None = None, + encoding: str = "iso-8859-1", + short_empty_elements: bool = False, ) -> None: ... - def startDocument(self): ... - def endDocument(self): ... - def startPrefixMapping(self, prefix, uri): ... - def endPrefixMapping(self, prefix): ... - def startElement(self, name, attrs): ... - def endElement(self, name): ... - def startElementNS(self, name, qname, attrs): ... - def endElementNS(self, name, qname): ... - def characters(self, content): ... - def ignorableWhitespace(self, content): ... - def processingInstruction(self, target, data): ... + def _qname(self, name: tuple[str | None, str]) -> str: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, content: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... class XMLFilterBase(xmlreader.XMLReader): - def __init__(self, parent: xmlreader.XMLReader | None = ...) -> None: ... - def error(self, exception): ... - def fatalError(self, exception): ... - def warning(self, exception): ... - def setDocumentLocator(self, locator): ... - def startDocument(self): ... - def endDocument(self): ... - def startPrefixMapping(self, prefix, uri): ... - def endPrefixMapping(self, prefix): ... - def startElement(self, name, attrs): ... - def endElement(self, name): ... - def startElementNS(self, name, qname, attrs): ... - def endElementNS(self, name, qname): ... - def characters(self, content): ... - def ignorableWhitespace(self, chars): ... - def processingInstruction(self, target, data): ... - def skippedEntity(self, name): ... - def notationDecl(self, name, publicId, systemId): ... - def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... - def resolveEntity(self, publicId, systemId): ... - def parse(self, source): ... - def setLocale(self, locale): ... - def getFeature(self, name): ... - def setFeature(self, name, state): ... - def getProperty(self, name): ... - def setProperty(self, name, value): ... - def getParent(self): ... - def setParent(self, parent): ... + def __init__(self, parent: xmlreader.XMLReader | None = None) -> None: ... + # ErrorHandler methods + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + def warning(self, exception: BaseException) -> None: ... + # ContentHandler methods + def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, chars: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def skippedEntity(self, name: str) -> None: ... + # DTDHandler methods + def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ... + def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... + # EntityResolver methods + def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... + # XMLReader methods + def parse(self, source: xmlreader.InputSource | _Source) -> None: ... + def setLocale(self, locale: str) -> None: ... + def getFeature(self, name: str) -> Literal[1, 0] | bool: ... + def setFeature(self, name: str, state: Literal[1, 0] | bool) -> None: ... + def getProperty(self, name: str) -> object: ... + def setProperty(self, name: str, value: object) -> None: ... + # XMLFilter methods + def getParent(self) -> xmlreader.XMLReader | None: ... + def setParent(self, parent: xmlreader.XMLReader) -> None: ... -def prepare_input_source(source, base=...): ... +def prepare_input_source(source: xmlreader.InputSource | _Source, base: str = "") -> xmlreader.InputSource: ... diff --git a/stdlib/xml/sax/xmlreader.pyi b/stdlib/xml/sax/xmlreader.pyi index 684e9cef1f42..a7ae5edc55d3 100644 --- a/stdlib/xml/sax/xmlreader.pyi +++ b/stdlib/xml/sax/xmlreader.pyi @@ -1,72 +1,94 @@ -from typing import Mapping +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from typing import Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self +from xml.sax import _Source, _SupportsReadClose +from xml.sax.handler import _ContentHandlerProtocol, _DTDHandlerProtocol, _EntityResolverProtocol, _ErrorHandlerProtocol class XMLReader: - def __init__(self) -> None: ... - def parse(self, source): ... - def getContentHandler(self): ... - def setContentHandler(self, handler): ... - def getDTDHandler(self): ... - def setDTDHandler(self, handler): ... - def getEntityResolver(self): ... - def setEntityResolver(self, resolver): ... - def getErrorHandler(self): ... - def setErrorHandler(self, handler): ... - def setLocale(self, locale): ... - def getFeature(self, name): ... - def setFeature(self, name, state): ... - def getProperty(self, name): ... - def setProperty(self, name, value): ... + def parse(self, source: InputSource | _Source) -> None: ... + def getContentHandler(self) -> _ContentHandlerProtocol: ... + def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ... + def getDTDHandler(self) -> _DTDHandlerProtocol: ... + def setDTDHandler(self, handler: _DTDHandlerProtocol) -> None: ... + def getEntityResolver(self) -> _EntityResolverProtocol: ... + def setEntityResolver(self, resolver: _EntityResolverProtocol) -> None: ... + def getErrorHandler(self) -> _ErrorHandlerProtocol: ... + def setErrorHandler(self, handler: _ErrorHandlerProtocol) -> None: ... + def setLocale(self, locale: str) -> None: ... + def getFeature(self, name: str) -> Literal[0, 1] | bool: ... + def setFeature(self, name: str, state: Literal[0, 1] | bool) -> None: ... + def getProperty(self, name: str) -> object: ... + def setProperty(self, name: str, value: object) -> None: ... class IncrementalParser(XMLReader): - def __init__(self, bufsize: int = ...) -> None: ... - def parse(self, source): ... - def feed(self, data): ... - def prepareParser(self, source): ... - def close(self): ... - def reset(self): ... + def __init__(self, bufsize: int = 65536) -> None: ... + def parse(self, source: InputSource | _Source) -> None: ... + def feed(self, data: str | ReadableBuffer) -> None: ... + def prepareParser(self, source: InputSource) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... class Locator: - def getColumnNumber(self): ... - def getLineNumber(self): ... - def getPublicId(self): ... - def getSystemId(self): ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int | None: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... class InputSource: - def __init__(self, system_id: str | None = ...) -> None: ... - def setPublicId(self, public_id): ... - def getPublicId(self): ... - def setSystemId(self, system_id): ... - def getSystemId(self): ... - def setEncoding(self, encoding): ... - def getEncoding(self): ... - def setByteStream(self, bytefile): ... - def getByteStream(self): ... - def setCharacterStream(self, charfile): ... - def getCharacterStream(self): ... + def __init__(self, system_id: str | None = None) -> None: ... + def setPublicId(self, public_id: str | None) -> None: ... + def getPublicId(self) -> str | None: ... + def setSystemId(self, system_id: str | None) -> None: ... + def getSystemId(self) -> str | None: ... + def setEncoding(self, encoding: str | None) -> None: ... + def getEncoding(self) -> str | None: ... + def setByteStream(self, bytefile: _SupportsReadClose[bytes] | None) -> None: ... + def getByteStream(self) -> _SupportsReadClose[bytes] | None: ... + def setCharacterStream(self, charfile: _SupportsReadClose[str] | None) -> None: ... + def getCharacterStream(self) -> _SupportsReadClose[str] | None: ... -class AttributesImpl: - def __init__(self, attrs: Mapping[str, str]) -> None: ... - def getLength(self): ... - def getType(self, name): ... - def getValue(self, name): ... - def getValueByQName(self, name): ... - def getNameByQName(self, name): ... - def getQNameByName(self, name): ... - def getNames(self): ... - def getQNames(self): ... - def __len__(self): ... - def __getitem__(self, name): ... - def keys(self): ... - def __contains__(self, name): ... - def get(self, name, alternative=...): ... - def copy(self): ... - def items(self): ... - def values(self): ... +_AttrKey = TypeVar("_AttrKey", default=str) -class AttributesNSImpl(AttributesImpl): - def __init__(self, attrs: Mapping[tuple[str, str], str], qnames: Mapping[tuple[str, str], str]) -> None: ... - def getValueByQName(self, name): ... - def getNameByQName(self, name): ... - def getQNameByName(self, name): ... - def getQNames(self): ... - def copy(self): ... +class AttributesImpl(Generic[_AttrKey]): + def __init__(self, attrs: Mapping[_AttrKey, str]) -> None: ... + def getLength(self) -> int: ... + def getType(self, name: str) -> str: ... + def getValue(self, name: _AttrKey) -> str: ... + def getValueByQName(self, name: str) -> str: ... + def getNameByQName(self, name: str) -> _AttrKey: ... + def getQNameByName(self, name: _AttrKey) -> str: ... + def getNames(self) -> list[_AttrKey]: ... + def getQNames(self) -> list[str]: ... + def __len__(self) -> int: ... + def __getitem__(self, name: _AttrKey) -> str: ... + def keys(self) -> list[_AttrKey]: ... + def __contains__(self, name: _AttrKey) -> bool: ... + + @overload + def get(self, name: _AttrKey, alternative: None = None) -> str | None: ... + @overload + def get(self, name: _AttrKey, alternative: str) -> str: ... + + def copy(self) -> Self: ... + def items(self) -> list[tuple[_AttrKey, str]]: ... + def values(self) -> list[str]: ... + +_NSName: TypeAlias = tuple[str | None, str] + +class AttributesNSImpl(AttributesImpl[_NSName]): + def __init__(self, attrs: Mapping[_NSName, str], qnames: Mapping[_NSName, str]) -> None: ... + def getValue(self, name: _NSName) -> str: ... + def getNameByQName(self, name: str) -> _NSName: ... + def getQNameByName(self, name: _NSName) -> str: ... + def getNames(self) -> list[_NSName]: ... + def __getitem__(self, name: _NSName) -> str: ... + def keys(self) -> list[_NSName]: ... + def __contains__(self, name: _NSName) -> bool: ... + + @overload + def get(self, name: _NSName, alternative: None = None) -> str | None: ... + @overload + def get(self, name: _NSName, alternative: str) -> str: ... + + def items(self) -> list[tuple[_NSName, str]]: ... diff --git a/stdlib/xml/utils.pyi b/stdlib/xml/utils.pyi new file mode 100644 index 000000000000..1c3bb877a7cc --- /dev/null +++ b/stdlib/xml/utils.pyi @@ -0,0 +1,2 @@ +def is_valid_name(name: str) -> bool: ... +def is_valid_text(data: str) -> bool: ... diff --git a/stdlib/xmlrpc/client.pyi b/stdlib/xmlrpc/client.pyi index b715e8b2928a..3107f1cbb377 100644 --- a/stdlib/xmlrpc/client.pyi +++ b/stdlib/xmlrpc/client.pyi @@ -1,45 +1,60 @@ import gzip import http.client -import sys import time -from _typeshed import Self, SupportsRead, SupportsWrite +from _typeshed import ReadableBuffer, SizedBuffer, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Mapping from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, Callable, Dict, Iterable, List, Mapping, Protocol, Tuple, Type, Union, overload -from typing_extensions import Literal +from typing import Any, ClassVar, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self +@type_check_only class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... -_DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] -_Marshallable = Union[None, bool, int, float, str, bytes, Tuple[Any, ...], List[Any], Dict[Any, Any], datetime, DateTime, Binary] -_XMLDate = Union[int, datetime, Tuple[int, ...], time.struct_time] -_HostType = Union[Tuple[str, Dict[str, str]], str] +_DateTimeComparable: TypeAlias = DateTime | datetime | str | _SupportsTimeTuple +_Marshallable: TypeAlias = ( + bool + | int + | float + | str + | bytes + | bytearray + | tuple[_Marshallable, ...] + # Ideally we'd use _Marshallable for list and dict, but invariance makes that impractical + | list[Any] + | dict[str, Any] + | datetime + | DateTime + | Binary + | None +) +_XMLDate: TypeAlias = int | datetime | tuple[int, ...] | time.struct_time +_HostType: TypeAlias = tuple[str, dict[str, str]] | str def escape(s: str) -> str: ... # undocumented -MAXINT: int # undocumented -MININT: int # undocumented +MAXINT: Final[int] # undocumented +MININT: Final[int] # undocumented -PARSE_ERROR: int # undocumented -SERVER_ERROR: int # undocumented -APPLICATION_ERROR: int # undocumented -SYSTEM_ERROR: int # undocumented -TRANSPORT_ERROR: int # undocumented +PARSE_ERROR: Final[int] # undocumented +SERVER_ERROR: Final[int] # undocumented +APPLICATION_ERROR: Final[int] # undocumented +SYSTEM_ERROR: Final[int] # undocumented +TRANSPORT_ERROR: Final[int] # undocumented -NOT_WELLFORMED_ERROR: int # undocumented -UNSUPPORTED_ENCODING: int # undocumented -INVALID_ENCODING_CHAR: int # undocumented -INVALID_XMLRPC: int # undocumented -METHOD_NOT_FOUND: int # undocumented -INVALID_METHOD_PARAMS: int # undocumented -INTERNAL_ERROR: int # undocumented +NOT_WELLFORMED_ERROR: Final[int] # undocumented +UNSUPPORTED_ENCODING: Final[int] # undocumented +INVALID_ENCODING_CHAR: Final[int] # undocumented +INVALID_XMLRPC: Final[int] # undocumented +METHOD_NOT_FOUND: Final[int] # undocumented +INVALID_METHOD_PARAMS: Final[int] # undocumented +INTERNAL_ERROR: Final[int] # undocumented class Error(Exception): ... class ProtocolError(Error): - url: str errcode: int errmsg: str @@ -49,7 +64,6 @@ class ProtocolError(Error): class ResponseError(Error): ... class Fault(Error): - faultCode: int faultString: str def __init__(self, faultCode: int, faultString: str, **extra: Any) -> None: ... @@ -61,9 +75,9 @@ def _iso8601_format(value: datetime) -> str: ... # undocumented def _strftime(value: _XMLDate) -> str: ... # undocumented class DateTime: - value: str # undocumented - def __init__(self, value: int | str | datetime | time.struct_time | Tuple[int, ...] = ...) -> None: ... + def __init__(self, value: int | str | datetime | time.struct_time | tuple[int, ...] = 0) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] def __lt__(self, other: _DateTimeComparable) -> bool: ... def __le__(self, other: _DateTimeComparable) -> bool: ... def __gt__(self, other: _DateTimeComparable) -> bool: ... @@ -78,50 +92,48 @@ def _datetime(data: Any) -> DateTime: ... # undocumented def _datetime_type(data: str) -> datetime: ... # undocumented class Binary: - data: bytes - def __init__(self, data: bytes | None = ...) -> None: ... - def decode(self, data: bytes) -> None: ... + def __init__(self, data: bytes | bytearray | None = None) -> None: ... + def decode(self, data: ReadableBuffer) -> None: ... def encode(self, out: SupportsWrite[str]) -> None: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] -def _binary(data: bytes) -> Binary: ... # undocumented +def _binary(data: ReadableBuffer) -> Binary: ... # undocumented -WRAPPERS: tuple[Type[DateTime], Type[Binary]] # undocumented +WRAPPERS: Final[tuple[type[DateTime], type[Binary]]] # undocumented class ExpatParser: # undocumented def __init__(self, target: Unmarshaller) -> None: ... - def feed(self, data: str | bytes) -> None: ... + def feed(self, data: str | ReadableBuffer) -> None: ... def close(self) -> None: ... -class Marshaller: - - dispatch: dict[ - Type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None] - ] # TODO: Replace 'Any' with some kind of binding +_WriteCallback: TypeAlias = Callable[[str], object] +class Marshaller: + dispatch: dict[type[_Marshallable] | Literal["_arbitrary_instance"], Callable[[Marshaller, Any, _WriteCallback], None]] memo: dict[Any, None] data: None encoding: str | None allow_none: bool - def __init__(self, encoding: str | None = ..., allow_none: bool = ...) -> None: ... + def __init__(self, encoding: str | None = None, allow_none: bool = False) -> None: ... def dumps(self, values: Fault | Iterable[_Marshallable]) -> str: ... - def __dump(self, value: _Marshallable, write: Callable[[str], Any]) -> None: ... # undocumented - def dump_nil(self, value: None, write: Callable[[str], Any]) -> None: ... - def dump_bool(self, value: bool, write: Callable[[str], Any]) -> None: ... - def dump_long(self, value: int, write: Callable[[str], Any]) -> None: ... - def dump_int(self, value: int, write: Callable[[str], Any]) -> None: ... - def dump_double(self, value: float, write: Callable[[str], Any]) -> None: ... - def dump_unicode(self, value: str, write: Callable[[str], Any], escape: Callable[[str], str] = ...) -> None: ... - def dump_bytes(self, value: bytes, write: Callable[[str], Any]) -> None: ... - def dump_array(self, value: Iterable[_Marshallable], write: Callable[[str], Any]) -> None: ... + def __dump(self, value: _Marshallable, write: _WriteCallback) -> None: ... # undocumented + def dump_nil(self, value: None, write: _WriteCallback) -> None: ... + def dump_bool(self, value: bool, write: _WriteCallback) -> None: ... + def dump_long(self, value: int, write: _WriteCallback) -> None: ... + def dump_int(self, value: int, write: _WriteCallback) -> None: ... + def dump_double(self, value: float, write: _WriteCallback) -> None: ... + def dump_unicode(self, value: str, write: _WriteCallback, escape: Callable[[str], str] = ...) -> None: ... + def dump_bytes(self, value: ReadableBuffer, write: _WriteCallback) -> None: ... + def dump_array(self, value: Iterable[_Marshallable], write: _WriteCallback) -> None: ... def dump_struct( - self, value: Mapping[str, _Marshallable], write: Callable[[str], Any], escape: Callable[[str], str] = ... + self, value: Mapping[str, _Marshallable], write: _WriteCallback, escape: Callable[[str], str] = ... ) -> None: ... - def dump_datetime(self, value: _XMLDate, write: Callable[[str], Any]) -> None: ... - def dump_instance(self, value: object, write: Callable[[str], Any]) -> None: ... + def dump_datetime(self, value: _XMLDate, write: _WriteCallback) -> None: ... + def dump_instance(self, value: object, write: _WriteCallback) -> None: ... class Unmarshaller: - dispatch: dict[str, Callable[[Unmarshaller, str], None]] _type: str | None @@ -134,8 +146,8 @@ class Unmarshaller: append: Callable[[Any], None] _use_datetime: bool _use_builtin_types: bool - def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... - def close(self) -> Tuple[_Marshallable, ...]: ... + def __init__(self, use_datetime: bool = False, use_builtin_types: bool = False) -> None: ... + def close(self) -> tuple[_Marshallable, ...]: ... def getmethodname(self) -> str | None: ... def xml(self, encoding: str, standalone: Any) -> None: ... # Standalone is ignored def start(self, tag: str, attrs: dict[str, str]) -> None: ... @@ -158,25 +170,22 @@ class Unmarshaller: def end_methodName(self, data: str) -> None: ... class _MultiCallMethod: # undocumented - - __call_list: list[tuple[str, Tuple[_Marshallable, ...]]] + __call_list: list[tuple[str, tuple[_Marshallable, ...]]] __name: str def __init__(self, call_list: list[tuple[str, _Marshallable]], name: str) -> None: ... def __getattr__(self, name: str) -> _MultiCallMethod: ... def __call__(self, *args: _Marshallable) -> None: ... class MultiCallIterator: # undocumented - results: list[list[_Marshallable]] def __init__(self, results: list[list[_Marshallable]]) -> None: ... def __getitem__(self, i: int) -> _Marshallable: ... class MultiCall: - __server: ServerProxy - __call_list: list[tuple[str, Tuple[_Marshallable, ...]]] + __call_list: list[tuple[str, tuple[_Marshallable, ...]]] def __init__(self, server: ServerProxy) -> None: ... - def __getattr__(self, item: str) -> _MultiCallMethod: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... def __call__(self) -> MultiCallIterator: ... # A little white lie @@ -184,34 +193,32 @@ FastMarshaller: Marshaller | None FastParser: ExpatParser | None FastUnmarshaller: Unmarshaller | None -def getparser(use_datetime: bool = ..., use_builtin_types: bool = ...) -> tuple[ExpatParser, Unmarshaller]: ... +def getparser(use_datetime: bool = False, use_builtin_types: bool = False) -> tuple[ExpatParser, Unmarshaller]: ... def dumps( - params: Fault | Tuple[_Marshallable, ...], - methodname: str | None = ..., - methodresponse: bool | None = ..., - encoding: str | None = ..., - allow_none: bool = ..., + params: Fault | tuple[_Marshallable, ...], + methodname: str | None = None, + methodresponse: bool | None = None, + encoding: str | None = None, + allow_none: bool = False, ) -> str: ... -def loads(data: str, use_datetime: bool = ..., use_builtin_types: bool = ...) -> tuple[Tuple[_Marshallable, ...], str | None]: ... -def gzip_encode(data: bytes) -> bytes: ... # undocumented -def gzip_decode(data: bytes, max_decode: int = ...) -> bytes: ... # undocumented +def loads( + data: str | ReadableBuffer, use_datetime: bool = False, use_builtin_types: bool = False +) -> tuple[tuple[_Marshallable, ...], str | None]: ... +def gzip_encode(data: ReadableBuffer) -> bytes: ... # undocumented +def gzip_decode(data: ReadableBuffer, max_decode: int = 20971520) -> bytes: ... # undocumented class GzipDecodedResponse(gzip.GzipFile): # undocumented - io: BytesIO - def __init__(self, response: SupportsRead[bytes]) -> None: ... - def close(self) -> None: ... + def __init__(self, response: SupportsRead[ReadableBuffer]) -> None: ... class _Method: # undocumented - - __send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable] + __send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable] __name: str - def __init__(self, send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... + def __init__(self, send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... def __getattr__(self, name: str) -> _Method: ... def __call__(self, *args: _Marshallable) -> _Marshallable: ... class Transport: - user_agent: str accept_gzip_encoding: bool encode_threshold: int | None @@ -222,42 +229,38 @@ class Transport: _headers: list[tuple[str, str]] _extra_headers: list[tuple[str, str]] - if sys.version_info >= (3, 8): - def __init__( - self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[tuple[str, str]] = ... - ) -> None: ... - else: - def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... - def request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> Tuple[_Marshallable, ...]: ... + def __init__( + self, use_datetime: bool = False, use_builtin_types: bool = False, *, headers: Iterable[tuple[str, str]] = () + ) -> None: ... + def request( + self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False + ) -> tuple[_Marshallable, ...]: ... def single_request( - self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ... - ) -> Tuple[_Marshallable, ...]: ... + self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False + ) -> tuple[_Marshallable, ...]: ... def getparser(self) -> tuple[ExpatParser, Unmarshaller]: ... def get_host_info(self, host: _HostType) -> tuple[str, list[tuple[str, str]], dict[str, str]]: ... def make_connection(self, host: _HostType) -> http.client.HTTPConnection: ... def close(self) -> None: ... - def send_request(self, host: _HostType, handler: str, request_body: bytes, debug: bool) -> http.client.HTTPConnection: ... + def send_request( + self, host: _HostType, handler: str, request_body: SizedBuffer, debug: bool + ) -> http.client.HTTPConnection: ... def send_headers(self, connection: http.client.HTTPConnection, headers: list[tuple[str, str]]) -> None: ... - def send_content(self, connection: http.client.HTTPConnection, request_body: bytes) -> None: ... - def parse_response(self, response: http.client.HTTPResponse) -> Tuple[_Marshallable, ...]: ... + def send_content(self, connection: http.client.HTTPConnection, request_body: SizedBuffer) -> None: ... + def parse_response(self, response: http.client.HTTPResponse) -> tuple[_Marshallable, ...]: ... class SafeTransport(Transport): - - if sys.version_info >= (3, 8): - def __init__( - self, - use_datetime: bool = ..., - use_builtin_types: bool = ..., - *, - headers: Iterable[tuple[str, str]] = ..., - context: Any | None = ..., - ) -> None: ... - else: - def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, context: Any | None = ...) -> None: ... + def __init__( + self, + use_datetime: bool = False, + use_builtin_types: bool = False, + *, + headers: Iterable[tuple[str, str]] = (), + context: Any | None = None, + ) -> None: ... def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... class ServerProxy: - __host: str __handler: str __transport: Transport @@ -265,45 +268,33 @@ class ServerProxy: __verbose: bool __allow_none: bool - if sys.version_info >= (3, 8): - def __init__( - self, - uri: str, - transport: Transport | None = ..., - encoding: str | None = ..., - verbose: bool = ..., - allow_none: bool = ..., - use_datetime: bool = ..., - use_builtin_types: bool = ..., - *, - headers: Iterable[tuple[str, str]] = ..., - context: Any | None = ..., - ) -> None: ... - else: - def __init__( - self, - uri: str, - transport: Transport | None = ..., - encoding: str | None = ..., - verbose: bool = ..., - allow_none: bool = ..., - use_datetime: bool = ..., - use_builtin_types: bool = ..., - *, - context: Any | None = ..., - ) -> None: ... + def __init__( + self, + uri: str, + transport: Transport | None = None, + encoding: str | None = None, + verbose: bool = False, + allow_none: bool = False, + use_datetime: bool = False, + use_builtin_types: bool = False, + *, + headers: Iterable[tuple[str, str]] = (), + context: Any | None = None, + ) -> None: ... def __getattr__(self, name: str) -> _Method: ... + @overload def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... @overload def __call__(self, attr: Literal["transport"]) -> Transport: ... @overload def __call__(self, attr: str) -> Callable[[], None] | Transport: ... - def __enter__(self: Self) -> Self: ... + + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def __close(self) -> None: ... # undocumented - def __request(self, methodname: str, params: Tuple[_Marshallable, ...]) -> Tuple[_Marshallable, ...]: ... # undocumented + def __request(self, methodname: str, params: tuple[_Marshallable, ...]) -> tuple[_Marshallable, ...]: ... # undocumented Server = ServerProxy diff --git a/stdlib/xmlrpc/server.pyi b/stdlib/xmlrpc/server.pyi index f84253cef568..7bf397d2b1a4 100644 --- a/stdlib/xmlrpc/server.pyi +++ b/stdlib/xmlrpc/server.pyi @@ -1,60 +1,62 @@ import http.server import pydoc import socketserver -import sys -from datetime import datetime -from typing import Any, Callable, Dict, Iterable, List, Mapping, Pattern, Protocol, Tuple, Type, Union -from xmlrpc.client import Fault - -# TODO: Recursive type on tuple, list, dict -_Marshallable = Union[None, bool, int, float, str, bytes, Tuple[Any, ...], List[Any], Dict[Any, Any], datetime] +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable, Mapping +from re import Pattern +from typing import Any, ClassVar, Protocol, TypeAlias, type_check_only +from xmlrpc.client import Fault, _Marshallable # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy +@type_check_only class _DispatchArity0(Protocol): def __call__(self) -> _Marshallable: ... +@type_check_only class _DispatchArity1(Protocol): - def __call__(self, __arg1: _Marshallable) -> _Marshallable: ... + def __call__(self, arg1: _Marshallable, /) -> _Marshallable: ... +@type_check_only class _DispatchArity2(Protocol): - def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable) -> _Marshallable: ... + def __call__(self, arg1: _Marshallable, arg2: _Marshallable, /) -> _Marshallable: ... +@type_check_only class _DispatchArity3(Protocol): - def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable) -> _Marshallable: ... + def __call__(self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, /) -> _Marshallable: ... +@type_check_only class _DispatchArity4(Protocol): def __call__( - self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable, __arg4: _Marshallable + self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, arg4: _Marshallable, / ) -> _Marshallable: ... +@type_check_only class _DispatchArityN(Protocol): def __call__(self, *args: _Marshallable) -> _Marshallable: ... -_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] +_DispatchProtocol: TypeAlias = ( + _DispatchArity0 | _DispatchArity1 | _DispatchArity2 | _DispatchArity3 | _DispatchArity4 | _DispatchArityN +) -def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = ...) -> Any: ... # undocumented +def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = True) -> Any: ... # undocumented def list_public_methods(obj: Any) -> list[str]: ... # undocumented class SimpleXMLRPCDispatcher: # undocumented - funcs: dict[str, _DispatchProtocol] instance: Any | None allow_none: bool encoding: str use_builtin_types: bool - def __init__(self, allow_none: bool = ..., encoding: str | None = ..., use_builtin_types: bool = ...) -> None: ... - def register_instance(self, instance: Any, allow_dotted_names: bool = ...) -> None: ... - if sys.version_info >= (3, 7): - def register_function(self, function: _DispatchProtocol | None = ..., name: str | None = ...) -> Callable[..., Any]: ... - else: - def register_function(self, function: _DispatchProtocol, name: str | None = ...) -> Callable[..., Any]: ... + def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ... + def register_instance(self, instance: Any, allow_dotted_names: bool = False) -> None: ... + def register_function(self, function: _DispatchProtocol | None = None, name: str | None = None) -> Callable[..., Any]: ... def register_introspection_functions(self) -> None: ... def register_multicall_functions(self) -> None: ... def _marshaled_dispatch( self, - data: str, - dispatch_method: Callable[[str | None, Tuple[_Marshallable, ...]], Fault | Tuple[_Marshallable, ...]] | None = ..., - path: Any | None = ..., + data: str | ReadableBuffer, + dispatch_method: Callable[[str, tuple[_Marshallable, ...]], Fault | tuple[_Marshallable, ...]] | None = None, + path: Any | None = None, ) -> str: ... # undocumented def system_listMethods(self) -> list[str]: ... # undocumented def system_methodSignature(self, method_name: str) -> str: ... # undocumented @@ -63,8 +65,7 @@ class SimpleXMLRPCDispatcher: # undocumented def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: ... # undocumented class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): - - rpc_paths: tuple[str, str] + rpc_paths: ClassVar[tuple[str, ...]] encode_threshold: int # undocumented aepattern: Pattern[str] # undocumented def accept_encodings(self) -> dict[str, float]: ... @@ -72,72 +73,58 @@ class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): def do_POST(self) -> None: ... def decode_request_content(self, data: bytes) -> bytes | None: ... def report_404(self) -> None: ... - def log_request(self, code: int | str = ..., size: int | str = ...) -> None: ... class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): - - allow_reuse_address: bool _send_traceback_handler: bool def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., - logRequests: bool = ..., - allow_none: bool = ..., - encoding: str | None = ..., - bind_and_activate: bool = ..., - use_builtin_types: bool = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = True, + allow_none: bool = False, + encoding: str | None = None, + bind_and_activate: bool = True, + use_builtin_types: bool = False, ) -> None: ... class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented - dispatchers: dict[str, SimpleXMLRPCDispatcher] - allow_none: bool - encoding: str def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., - logRequests: bool = ..., - allow_none: bool = ..., - encoding: str | None = ..., - bind_and_activate: bool = ..., - use_builtin_types: bool = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = True, + allow_none: bool = False, + encoding: str | None = None, + bind_and_activate: bool = True, + use_builtin_types: bool = False, ) -> None: ... def add_dispatcher(self, path: str, dispatcher: SimpleXMLRPCDispatcher) -> SimpleXMLRPCDispatcher: ... def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ... - def _marshaled_dispatch( - self, - data: str, - dispatch_method: Callable[[str | None, Tuple[_Marshallable, ...]], Fault | Tuple[_Marshallable, ...]] | None = ..., - path: Any | None = ..., - ) -> str: ... class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): - def __init__(self, allow_none: bool = ..., encoding: str | None = ..., use_builtin_types: bool = ...) -> None: ... + def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ... def handle_xmlrpc(self, request_text: str) -> None: ... def handle_get(self) -> None: ... - def handle_request(self, request_text: str | None = ...) -> None: ... + def handle_request(self, request_text: str | None = None) -> None: ... class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented def docroutine( # type: ignore[override] self, object: object, name: str, - mod: str | None = ..., - funcs: Mapping[str, str] = ..., - classes: Mapping[str, str] = ..., - methods: Mapping[str, str] = ..., - cl: type | None = ..., + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + cl: type | None = None, ) -> str: ... def docserver(self, server_name: str, package_documentation: str, methods: dict[str, str]) -> str: ... class XMLRPCDocGenerator: # undocumented - server_name: str server_documentation: str server_title: str - def __init__(self) -> None: ... def set_server_title(self, server_title: str) -> None: ... def set_server_name(self, server_name: str) -> None: ... def set_server_documentation(self, server_documentation: str) -> None: ... @@ -150,12 +137,12 @@ class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., - logRequests: bool = ..., - allow_none: bool = ..., - encoding: str | None = ..., - bind_and_activate: bool = ..., - use_builtin_types: bool = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = True, + allow_none: bool = False, + encoding: str | None = None, + bind_and_activate: bool = True, + use_builtin_types: bool = False, ) -> None: ... class DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator): diff --git a/stdlib/xxlimited.pyi b/stdlib/xxlimited.pyi index 0dddbb876638..503caf0183f3 100644 --- a/stdlib/xxlimited.pyi +++ b/stdlib/xxlimited.pyi @@ -1,18 +1,15 @@ import sys -from typing import Any +from typing import Any, final -class Str: ... +class Str(str): ... +@final class Xxo: def demo(self) -> None: ... + if sys.version_info >= (3, 11) and sys.platform != "win32": + x_exports: int -def foo(__i: int, __j: int) -> Any: ... +def foo(i: int, j: int, /) -> Any: ... def new() -> Xxo: ... -if sys.version_info >= (3, 10): - class Error: ... - -else: - class error: ... - class Null: ... - def roj(__b: Any) -> None: ... +class Error(Exception): ... diff --git a/stdlib/zipapp.pyi b/stdlib/zipapp.pyi index 581d2b72a664..48713bced892 100644 --- a/stdlib/zipapp.pyi +++ b/stdlib/zipapp.pyi @@ -1,24 +1,19 @@ -import sys +from collections.abc import Callable from pathlib import Path -from typing import BinaryIO, Callable, Union +from typing import BinaryIO, TypeAlias -_Path = Union[str, Path, BinaryIO] +__all__ = ["ZipAppError", "create_archive", "get_interpreter"] -class ZipAppError(ValueError): ... - -if sys.version_info >= (3, 7): - def create_archive( - source: _Path, - target: _Path | None = ..., - interpreter: str | None = ..., - main: str | None = ..., - filter: Callable[[Path], bool] | None = ..., - compressed: bool = ..., - ) -> None: ... +_Path: TypeAlias = str | Path | BinaryIO -else: - def create_archive( - source: _Path, target: _Path | None = ..., interpreter: str | None = ..., main: str | None = ... - ) -> None: ... +class ZipAppError(ValueError): ... +def create_archive( + source: _Path, + target: _Path | None = None, + interpreter: str | None = None, + main: str | None = None, + filter: Callable[[Path], bool] | None = None, + compressed: bool = False, +) -> None: ... def get_interpreter(archive: _Path) -> str: ... diff --git a/stdlib/zipfile.pyi b/stdlib/zipfile.pyi deleted file mode 100644 index 710b9b237b4c..000000000000 --- a/stdlib/zipfile.pyi +++ /dev/null @@ -1,266 +0,0 @@ -import io -import sys -from _typeshed import Self, StrPath -from os import PathLike -from types import TracebackType -from typing import IO, Any, Callable, Iterable, Iterator, Protocol, Sequence, Tuple, Type, overload -from typing_extensions import Literal - -_DateTuple = Tuple[int, int, int, int, int, int] -_ReadWriteMode = Literal["r", "w"] -_ReadWriteBinaryMode = Literal["r", "w", "rb", "wb"] -_ZipFileMode = Literal["r", "w", "x", "a"] - -class BadZipFile(Exception): ... - -BadZipfile = BadZipFile -error = BadZipfile - -class LargeZipFile(Exception): ... - -class _ZipStream(Protocol): - def read(self, __n: int) -> bytes: ... - # The following methods are optional: - # def seekable(self) -> bool: ... - # def tell(self) -> int: ... - # def seek(self, __n: int) -> object: ... - -class _ClosableZipStream(_ZipStream, Protocol): - def close(self) -> object: ... - -class ZipExtFile(io.BufferedIOBase): - MAX_N: int - MIN_READ_SIZE: int - - if sys.version_info >= (3, 7): - MAX_SEEK_READ: int - - newlines: list[bytes] | None - mode: _ReadWriteMode - name: str - if sys.version_info >= (3, 7): - @overload - def __init__( - self, - fileobj: _ClosableZipStream, - mode: _ReadWriteMode, - zipinfo: ZipInfo, - pwd: bytes | None, - close_fileobj: Literal[True], - ) -> None: ... - @overload - def __init__( - self, - fileobj: _ClosableZipStream, - mode: _ReadWriteMode, - zipinfo: ZipInfo, - pwd: bytes | None = ..., - *, - close_fileobj: Literal[True], - ) -> None: ... - @overload - def __init__( - self, - fileobj: _ZipStream, - mode: _ReadWriteMode, - zipinfo: ZipInfo, - pwd: bytes | None = ..., - close_fileobj: Literal[False] = ..., - ) -> None: ... - else: - @overload - def __init__( - self, - fileobj: _ClosableZipStream, - mode: _ReadWriteMode, - zipinfo: ZipInfo, - decrypter: Callable[[Sequence[int]], bytes] | None, - close_fileobj: Literal[True], - ) -> None: ... - @overload - def __init__( - self, - fileobj: _ClosableZipStream, - mode: _ReadWriteMode, - zipinfo: ZipInfo, - decrypter: Callable[[Sequence[int]], bytes] | None = ..., - *, - close_fileobj: Literal[True], - ) -> None: ... - @overload - def __init__( - self, - fileobj: _ZipStream, - mode: _ReadWriteMode, - zipinfo: ZipInfo, - decrypter: Callable[[Sequence[int]], bytes] | None = ..., - close_fileobj: Literal[False] = ..., - ) -> None: ... - def read(self, n: int | None = ...) -> bytes: ... - def readline(self, limit: int = ...) -> bytes: ... # type: ignore[override] - def __repr__(self) -> str: ... - def peek(self, n: int = ...) -> bytes: ... - def read1(self, n: int | None) -> bytes: ... # type: ignore[override] - if sys.version_info >= (3, 7): - def seek(self, offset: int, whence: int = ...) -> int: ... - -class _Writer(Protocol): - def write(self, __s: str) -> object: ... - -class ZipFile: - filename: str | None - debug: int - comment: bytes - filelist: list[ZipInfo] - fp: IO[bytes] | None - NameToInfo: dict[str, ZipInfo] - start_dir: int # undocumented - compression: int # undocumented - compresslevel: int | None # undocumented - mode: _ZipFileMode # undocumented - pwd: str | None # undocumented - if sys.version_info >= (3, 8): - def __init__( - self, - file: StrPath | IO[bytes], - mode: _ZipFileMode = ..., - compression: int = ..., - allowZip64: bool = ..., - compresslevel: int | None = ..., - *, - strict_timestamps: bool = ..., - ) -> None: ... - elif sys.version_info >= (3, 7): - def __init__( - self, - file: StrPath | IO[bytes], - mode: _ZipFileMode = ..., - compression: int = ..., - allowZip64: bool = ..., - compresslevel: int | None = ..., - ) -> None: ... - else: - def __init__( - self, file: StrPath | IO[bytes], mode: _ZipFileMode = ..., compression: int = ..., allowZip64: bool = ... - ) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - def close(self) -> None: ... - def getinfo(self, name: str) -> ZipInfo: ... - def infolist(self) -> list[ZipInfo]: ... - def namelist(self) -> list[str]: ... - def open( - self, name: str | ZipInfo, mode: _ReadWriteMode = ..., pwd: bytes | None = ..., *, force_zip64: bool = ... - ) -> IO[bytes]: ... - def extract(self, member: str | ZipInfo, path: StrPath | None = ..., pwd: bytes | None = ...) -> str: ... - def extractall( - self, path: StrPath | None = ..., members: Iterable[str | ZipInfo] | None = ..., pwd: bytes | None = ... - ) -> None: ... - def printdir(self, file: _Writer | None = ...) -> None: ... - def setpassword(self, pwd: bytes) -> None: ... - def read(self, name: str | ZipInfo, pwd: bytes | None = ...) -> bytes: ... - def testzip(self) -> str | None: ... - if sys.version_info >= (3, 7): - def write( - self, - filename: StrPath, - arcname: StrPath | None = ..., - compress_type: int | None = ..., - compresslevel: int | None = ..., - ) -> None: ... - else: - def write(self, filename: StrPath, arcname: StrPath | None = ..., compress_type: int | None = ...) -> None: ... - if sys.version_info >= (3, 7): - def writestr( - self, - zinfo_or_arcname: str | ZipInfo, - data: bytes | str, - compress_type: int | None = ..., - compresslevel: int | None = ..., - ) -> None: ... - else: - def writestr(self, zinfo_or_arcname: str | ZipInfo, data: bytes | str, compress_type: int | None = ...) -> None: ... - -class PyZipFile(ZipFile): - def __init__( - self, file: str | IO[bytes], mode: _ZipFileMode = ..., compression: int = ..., allowZip64: bool = ..., optimize: int = ... - ) -> None: ... - def writepy(self, pathname: str, basename: str = ..., filterfunc: Callable[[str], bool] | None = ...) -> None: ... - -class ZipInfo: - filename: str - date_time: _DateTuple - compress_type: int - comment: bytes - extra: bytes - create_system: int - create_version: int - extract_version: int - reserved: int - flag_bits: int - volume: int - internal_attr: int - external_attr: int - header_offset: int - CRC: int - compress_size: int - file_size: int - orig_filename: str # undocumented - def __init__(self, filename: str = ..., date_time: _DateTuple = ...) -> None: ... - if sys.version_info >= (3, 8): - @classmethod - def from_file(cls, filename: StrPath, arcname: StrPath | None = ..., *, strict_timestamps: bool = ...) -> ZipInfo: ... - else: - @classmethod - def from_file(cls, filename: StrPath, arcname: StrPath | None = ...) -> ZipInfo: ... - def is_dir(self) -> bool: ... - def FileHeader(self, zip64: bool | None = ...) -> bytes: ... - -class _PathOpenProtocol(Protocol): - def __call__(self, mode: _ReadWriteMode = ..., pwd: bytes | None = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... - -if sys.version_info >= (3, 8): - class Path: - @property - def name(self) -> str: ... - @property - def parent(self) -> PathLike[str]: ... # undocumented - if sys.version_info >= (3, 10): - @property - def filename(self) -> PathLike[str]: ... # undocumented - def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = ...) -> None: ... - if sys.version_info >= (3, 9): - def open(self, mode: _ReadWriteBinaryMode = ..., *args: Any, pwd: bytes | None = ..., **kwargs: Any) -> IO[bytes]: ... - else: - @property - def open(self) -> _PathOpenProtocol: ... - def iterdir(self) -> Iterator[Path]: ... - def is_dir(self) -> bool: ... - def is_file(self) -> bool: ... - def exists(self) -> bool: ... - def read_text( - self, - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - line_buffering: bool = ..., - write_through: bool = ..., - ) -> str: ... - def read_bytes(self) -> bytes: ... - if sys.version_info >= (3, 10): - def joinpath(self, *other: StrPath) -> Path: ... - else: - def joinpath(self, add: StrPath) -> Path: ... # undocumented - def __truediv__(self, add: StrPath) -> Path: ... - -def is_zipfile(filename: StrPath | IO[bytes]) -> bool: ... - -ZIP_STORED: int -ZIP_DEFLATED: int -ZIP64_LIMIT: int -ZIP_FILECOUNT_LIMIT: int -ZIP_MAX_COMMENT: int -ZIP_BZIP2: int -ZIP_LZMA: int diff --git a/stdlib/zipfile/__init__.pyi b/stdlib/zipfile/__init__.pyi new file mode 100644 index 000000000000..39a621b64027 --- /dev/null +++ b/stdlib/zipfile/__init__.pyi @@ -0,0 +1,411 @@ +import io +import sys +from _typeshed import FileDescriptorOrPath, SizedBuffer, StrPath +from collections.abc import Callable, Iterable, Iterator +from io import TextIOWrapper +from os import PathLike +from types import TracebackType +from typing import IO, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self + +__all__ = [ + "BadZipFile", + "BadZipfile", + "Path", + "error", + "ZIP_STORED", + "ZIP_DEFLATED", + "ZIP_BZIP2", + "ZIP_LZMA", + "is_zipfile", + "ZipInfo", + "ZipFile", + "PyZipFile", + "LargeZipFile", +] + +if sys.version_info >= (3, 14): + __all__ += ["ZIP_ZSTANDARD"] + +# TODO: use TypeAlias for these two when mypy bugs are fixed +# https://github.com/python/mypy/issues/16581 +_DateTuple = tuple[int, int, int, int, int, int] # noqa: Y026 +_ZipFileMode = Literal["r", "w", "x", "a"] # noqa: Y026 + +_ReadWriteMode: TypeAlias = Literal["r", "w"] + +class BadZipFile(Exception): ... + +BadZipfile = BadZipFile +error = BadZipfile + +class LargeZipFile(Exception): ... + +@type_check_only +class _ZipStream(Protocol): + def read(self, n: int, /) -> bytes: ... + # The following methods are optional: + # def seekable(self) -> bool: ... + # def tell(self) -> int: ... + # def seek(self, n: int, /) -> object: ... + +# Stream shape as required by _EndRecData() and _EndRecData64(). +@type_check_only +class _SupportsReadSeekTell(Protocol): + def read(self, n: int = ..., /) -> bytes: ... + def seek(self, cookie: int, whence: int, /) -> object: ... + def tell(self) -> int: ... + +@type_check_only +class _ClosableZipStream(_ZipStream, Protocol): + def close(self) -> object: ... + +class ZipExtFile(io.BufferedIOBase): + MAX_N: int + MIN_READ_SIZE: int + MAX_SEEK_READ: int + newlines: list[bytes] | None + mode: _ReadWriteMode + name: str + + @overload + def __init__( + self, fileobj: _ClosableZipStream, mode: _ReadWriteMode, zipinfo: ZipInfo, pwd: bytes | None, close_fileobj: Literal[True] + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ClosableZipStream, + mode: _ReadWriteMode, + zipinfo: ZipInfo, + pwd: bytes | None = None, + *, + close_fileobj: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ZipStream, + mode: _ReadWriteMode, + zipinfo: ZipInfo, + pwd: bytes | None = None, + close_fileobj: Literal[False] = False, + ) -> None: ... + + def read(self, n: int | None = -1) -> bytes: ... + def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] + def peek(self, n: int = 1) -> bytes: ... + def read1(self, n: int | None) -> bytes: ... # type: ignore[override] + def seek(self, offset: int, whence: int = 0) -> int: ... + +@type_check_only +class _Writer(Protocol): + def write(self, s: str, /) -> object: ... + +@type_check_only +class _ZipReadable(Protocol): + def seek(self, offset: int, whence: int = 0, /) -> int: ... + def read(self, n: int = -1, /) -> bytes: ... + +@type_check_only +class _ZipTellable(Protocol): + def tell(self) -> int: ... + +@type_check_only +class _ZipReadableTellable(_ZipReadable, _ZipTellable, Protocol): ... + +@type_check_only +class _ZipWritable(Protocol): + def flush(self) -> None: ... + def close(self) -> None: ... + def write(self, b: bytes, /) -> int: ... + +class ZipFile: + filename: str | None + debug: int + comment: bytes + filelist: list[ZipInfo] + fp: IO[bytes] | None + NameToInfo: dict[str, ZipInfo] + start_dir: int # undocumented + compression: int # undocumented + compresslevel: int | None # undocumented + mode: _ZipFileMode # undocumented + pwd: bytes | None # undocumented + # metadata_encoding is new in 3.11 + if sys.version_info >= (3, 11): + @overload + def __init__( + self, + file: StrPath | IO[bytes], + mode: _ZipFileMode = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: str | None = None, + ) -> None: ... + # metadata_encoding is only allowed for read mode + @overload + def __init__( + self, + file: StrPath | _ZipReadable, + mode: Literal["r"] = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipWritable, + mode: Literal["w", "x"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: None = None, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipReadableTellable, + mode: Literal["a"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: None = None, + ) -> None: ... + else: + @overload + def __init__( + self, + file: StrPath | IO[bytes], + mode: _ZipFileMode = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipReadable, + mode: Literal["r"] = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipWritable, + mode: Literal["w", "x"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipReadableTellable, + mode: Literal["a"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def close(self) -> None: ... + def getinfo(self, name: str) -> ZipInfo: ... + def infolist(self) -> list[ZipInfo]: ... + def namelist(self) -> list[str]: ... + def open( + self, name: str | ZipInfo, mode: _ReadWriteMode = "r", pwd: bytes | None = None, *, force_zip64: bool = False + ) -> IO[bytes]: ... + def extract(self, member: str | ZipInfo, path: StrPath | None = None, pwd: bytes | None = None) -> str: ... + def extractall( + self, path: StrPath | None = None, members: Iterable[str | ZipInfo] | None = None, pwd: bytes | None = None + ) -> None: ... + def printdir(self, file: _Writer | None = None) -> None: ... + def setpassword(self, pwd: bytes) -> None: ... + def read(self, name: str | ZipInfo, pwd: bytes | None = None) -> bytes: ... + def testzip(self) -> str | None: ... + def write( + self, + filename: StrPath, + arcname: StrPath | None = None, + compress_type: int | None = None, + compresslevel: int | None = None, + ) -> None: ... + def writestr( + self, + zinfo_or_arcname: str | ZipInfo, + data: SizedBuffer | str, + compress_type: int | None = None, + compresslevel: int | None = None, + ) -> None: ... + if sys.version_info >= (3, 11): + def mkdir(self, zinfo_or_directory_name: str | ZipInfo, mode: int = 0o777) -> None: ... + + def __del__(self) -> None: ... + +class PyZipFile(ZipFile): + def __init__( + self, file: str | IO[bytes], mode: _ZipFileMode = "r", compression: int = 0, allowZip64: bool = True, optimize: int = -1 + ) -> None: ... + def writepy(self, pathname: str, basename: str = "", filterfunc: Callable[[str], bool] | None = None) -> None: ... + +class ZipInfo: + __slots__ = ( + "orig_filename", + "filename", + "date_time", + "compress_type", + "compress_level", + "comment", + "extra", + "create_system", + "create_version", + "extract_version", + "reserved", + "flag_bits", + "volume", + "internal_attr", + "external_attr", + "header_offset", + "CRC", + "compress_size", + "file_size", + "_raw_time", + "_end_offset", + ) + filename: str + date_time: _DateTuple + compress_type: int + comment: bytes + extra: bytes + create_system: int + create_version: int + extract_version: int + reserved: int + flag_bits: int + volume: int + internal_attr: int + external_attr: int + header_offset: int + CRC: int + compress_size: int + file_size: int + orig_filename: str # undocumented + if sys.version_info >= (3, 13): + compress_level: int | None + + def __init__(self, filename: str = "NoName", date_time: _DateTuple = (1980, 1, 1, 0, 0, 0)) -> None: ... + @classmethod + def from_file(cls, filename: StrPath, arcname: StrPath | None = None, *, strict_timestamps: bool = True) -> Self: ... + def is_dir(self) -> bool: ... + def FileHeader(self, zip64: bool | None = None) -> bytes: ... + if sys.version_info >= (3, 14): + def _for_archive(self, archive: ZipFile) -> Self: ... + +if sys.version_info >= (3, 12): + from zipfile._path import CompleteDirs as CompleteDirs, Path as Path + +else: + class CompleteDirs(ZipFile): + def resolve_dir(self, name: str) -> str: ... + + @overload + @classmethod + def make(cls, source: ZipFile) -> CompleteDirs: ... + @overload + @classmethod + def make(cls, source: StrPath | IO[bytes]) -> Self: ... + + class Path: + root: CompleteDirs + at: str + def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = "") -> None: ... + @property + def name(self) -> str: ... + @property + def parent(self) -> PathLike[str]: ... # undocumented + @property + def filename(self) -> PathLike[str]: ... # undocumented + if sys.version_info >= (3, 11): + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + + @overload + def open( + self, + mode: Literal["r", "w"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + *, + pwd: bytes | None = None, + ) -> TextIOWrapper: ... + @overload + def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... + + def iterdir(self) -> Iterator[Self]: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def exists(self) -> bool: ... + def read_text( + self, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, *other: StrPath) -> Path: ... + def __truediv__(self, add: StrPath) -> Path: ... + +def is_zipfile(filename: FileDescriptorOrPath | _SupportsReadSeekTell) -> bool: ... + +ZIP64_LIMIT: Final[int] +ZIP_FILECOUNT_LIMIT: Final[int] +ZIP_MAX_COMMENT: Final[int] + +ZIP_STORED: Final = 0 +ZIP_DEFLATED: Final = 8 +ZIP_BZIP2: Final = 12 +ZIP_LZMA: Final = 14 +if sys.version_info >= (3, 14): + ZIP_ZSTANDARD: Final = 93 + +DEFAULT_VERSION: Final[int] +ZIP64_VERSION: Final[int] +BZIP2_VERSION: Final[int] +LZMA_VERSION: Final[int] +if sys.version_info >= (3, 14): + ZSTANDARD_VERSION: Final[int] +MAX_EXTRACT_VERSION: Final[int] diff --git a/stdlib/zipfile/_path/__init__.pyi b/stdlib/zipfile/_path/__init__.pyi new file mode 100644 index 000000000000..e1449dc681ad --- /dev/null +++ b/stdlib/zipfile/_path/__init__.pyi @@ -0,0 +1,87 @@ +import sys +from _typeshed import StrPath +from collections.abc import Iterator, Sequence +from io import TextIOWrapper +from os import PathLike +from typing import IO, Literal, TypeVar, overload +from typing_extensions import Self +from zipfile import ZipFile + +_ZF = TypeVar("_ZF", bound=ZipFile) + +if sys.version_info >= (3, 12): + __all__ = ["Path"] + + class InitializedState: + def __init__(self, *args: object, **kwargs: object) -> None: ... + def __getstate__(self) -> tuple[list[object], dict[object, object]]: ... + def __setstate__(self, state: Sequence[tuple[list[object], dict[object, object]]]) -> None: ... + + class CompleteDirs(InitializedState, ZipFile): + def resolve_dir(self, name: str) -> str: ... + + @overload + @classmethod + def make(cls, source: ZipFile) -> CompleteDirs: ... + @overload + @classmethod + def make(cls, source: StrPath | IO[bytes]) -> Self: ... + + if sys.version_info >= (3, 13): + @classmethod + def inject(cls, zf: _ZF) -> _ZF: ... + + class Path: + root: CompleteDirs + at: str + def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = "") -> None: ... + @property + def name(self) -> str: ... + @property + def parent(self) -> PathLike[str]: ... # undocumented + @property + def filename(self) -> PathLike[str]: ... # undocumented + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + + @overload + def open( + self, + mode: Literal["r", "w"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + *, + pwd: bytes | None = None, + ) -> TextIOWrapper: ... + @overload + def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... + + def iterdir(self) -> Iterator[Self]: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def exists(self) -> bool: ... + def read_text( + self, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, *other: StrPath) -> Path: ... + def glob(self, pattern: str) -> Iterator[Self]: ... + def rglob(self, pattern: str) -> Iterator[Self]: ... + def is_symlink(self) -> Literal[False]: ... + def relative_to(self, other: Path, *extra: StrPath) -> str: ... + def match(self, path_pattern: str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __truediv__(self, add: StrPath) -> Path: ... diff --git a/stdlib/zipfile/_path/glob.pyi b/stdlib/zipfile/_path/glob.pyi new file mode 100644 index 000000000000..f6a661be8cdf --- /dev/null +++ b/stdlib/zipfile/_path/glob.pyi @@ -0,0 +1,26 @@ +import sys +from collections.abc import Iterator +from re import Match + +if sys.version_info >= (3, 13): + class Translator: + if sys.platform == "win32": + def __init__(self, seps: str = "\\/") -> None: ... + else: + def __init__(self, seps: str = "/") -> None: ... + + def translate(self, pattern: str) -> str: ... + def extend(self, pattern: str) -> str: ... + def match_dirs(self, pattern: str) -> str: ... + def translate_core(self, pattern: str) -> str: ... + def replace(self, match: Match[str]) -> str: ... + def restrict_rglob(self, pattern: str) -> None: ... + def star_not_empty(self, pattern: str) -> str: ... + +else: + def translate(pattern: str) -> str: ... + def match_dirs(pattern: str) -> str: ... + def translate_core(pattern: str) -> str: ... + def replace(match: Match[str]) -> str: ... + +def separate(pattern: str) -> Iterator[Match[str]]: ... diff --git a/stdlib/zipimport.pyi b/stdlib/zipimport.pyi index 3acdc729ae3b..4b34f1f2ad3e 100644 --- a/stdlib/zipimport.pyi +++ b/stdlib/zipimport.pyi @@ -1,28 +1,44 @@ -import os import sys +from _frozen_importlib_external import _LoaderBasics +from _typeshed import StrOrBytesPath from importlib.machinery import ModuleSpec +from importlib.readers import ZipReader from types import CodeType, ModuleType -from typing import Any +from typing_extensions import deprecated -if sys.version_info >= (3, 7): - from importlib.abc import ResourceReader +__all__ = ["ZipImportError", "zipimporter"] class ZipImportError(ImportError): ... -class zipimporter(object): +class zipimporter(_LoaderBasics): archive: str prefix: str - def __init__(self, path: str | bytes | os.PathLike[Any]) -> None: ... - def find_loader(self, fullname: str, path: str | None = ...) -> tuple[zipimporter | None, list[str]]: ... # undocumented - def find_module(self, fullname: str, path: str | None = ...) -> zipimporter | None: ... + if sys.version_info >= (3, 11): + def __init__(self, path: str) -> None: ... + else: + def __init__(self, path: StrOrBytesPath) -> None: ... + + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") + def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ... + def get_code(self, fullname: str) -> CodeType: ... - def get_data(self, pathname: str) -> str: ... + def get_data(self, pathname: str) -> bytes: ... def get_filename(self, fullname: str) -> str: ... - if sys.version_info >= (3, 7): - def get_resource_reader(self, fullname: str) -> ResourceReader | None: ... # undocumented + if sys.version_info >= (3, 14): + def get_resource_reader(self, fullname: str) -> ZipReader: ... # undocumented + else: + def get_resource_reader(self, fullname: str) -> ZipReader | None: ... # undocumented + def get_source(self, fullname: str) -> str | None: ... def is_package(self, fullname: str) -> bool: ... - def load_module(self, fullname: str) -> ModuleType: ... - if sys.version_info >= (3, 10): - def find_spec(self, fullname: str, target: ModuleType | None = ...) -> ModuleSpec | None: ... - def invalidate_caches(self) -> None: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> ModuleType: ... + + def exec_module(self, module: ModuleType) -> None: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def find_spec(self, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: ... + def invalidate_caches(self) -> None: ... diff --git a/stdlib/zlib.pyi b/stdlib/zlib.pyi index 646c96bd2bef..b507770601d9 100644 --- a/stdlib/zlib.pyi +++ b/stdlib/zlib.pyi @@ -1,50 +1,81 @@ -from array import array -from typing import Any -from typing_extensions import Literal - -DEFLATED: int -DEF_MEM_LEVEL: int -MAX_WBITS: int -ZLIB_VERSION: str -Z_NO_COMPRESSION: Literal[0] -Z_PARTIAL_FLUSH: Literal[1] -Z_BEST_COMPRESSION: int -Z_BEST_SPEED: int -Z_BLOCK: Literal[5] -Z_DEFAULT_COMPRESSION: int -Z_DEFAULT_STRATEGY: int -Z_FILTERED: int -Z_FINISH: int -Z_FIXED: int -Z_FULL_FLUSH: int -Z_HUFFMAN_ONLY: int -Z_NO_FLUSH: int -Z_RLE: int -Z_SYNC_FLUSH: int -Z_TREES: Literal[6] -DEF_BUF_SIZE: int -ZLIB_RUNTIME_VERSION: str +import sys +from _typeshed import ReadableBuffer +from typing import Any, Final, SupportsIndex, final, type_check_only +from typing_extensions import Self + +DEFLATED: Final = 8 +DEF_MEM_LEVEL: Final[int] +DEF_BUF_SIZE: Final = 16384 +MAX_WBITS: Final[int] +ZLIB_VERSION: Final[str] +ZLIB_RUNTIME_VERSION: Final[str] +Z_NO_COMPRESSION: Final = 0 +Z_PARTIAL_FLUSH: Final = 1 +Z_BEST_COMPRESSION: Final = 9 +Z_BEST_SPEED: Final = 1 +Z_BLOCK: Final = 5 +Z_DEFAULT_COMPRESSION: Final = -1 +Z_DEFAULT_STRATEGY: Final = 0 +Z_FILTERED: Final = 1 +Z_FINISH: Final = 4 +Z_FIXED: Final = 4 +Z_FULL_FLUSH: Final = 3 +Z_HUFFMAN_ONLY: Final = 2 +Z_NO_FLUSH: Final = 0 +Z_RLE: Final = 3 +Z_SYNC_FLUSH: Final = 2 +Z_TREES: Final = 6 + +if sys.version_info >= (3, 14): + # Available when zlib was built with zlib-ng + ZLIBNG_VERSION: Final[str] class error(Exception): ... +# This class is not exposed at runtime. It calls itself zlib.Compress. +@final +@type_check_only class _Compress: - def compress(self, data: bytes) -> bytes: ... - def flush(self, mode: int = ...) -> bytes: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def compress(self, data: ReadableBuffer, /) -> bytes: ... + def flush(self, mode: int = 4, /) -> bytes: ... def copy(self) -> _Compress: ... +# This class is not exposed at runtime. It calls itself zlib.Decompress. +@final +@type_check_only class _Decompress: - unused_data: bytes - unconsumed_tail: bytes - eof: bool - def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... - def flush(self, length: int = ...) -> bytes: ... + @property + def unused_data(self) -> bytes: ... + @property + def unconsumed_tail(self) -> bytes: ... + @property + def eof(self) -> bool: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def decompress(self, data: ReadableBuffer, /, max_length: int = 0) -> bytes: ... + def flush(self, length: int = 16384, /) -> bytes: ... def copy(self) -> _Decompress: ... -def adler32(__data: bytes, __value: int = ...) -> int: ... -def compress(__data: bytes, level: int = ...) -> bytes: ... +def adler32(data: ReadableBuffer, value: SupportsIndex = 1, /) -> int: ... + +if sys.version_info >= (3, 15): + def adler32_combine(adler1: int, adler2: int, len2: int, /) -> int: ... + +if sys.version_info >= (3, 11): + def compress(data: ReadableBuffer, /, level: int = -1, wbits: int = 15) -> bytes: ... + +else: + def compress(data: ReadableBuffer, /, level: int = -1) -> bytes: ... + def compressobj( - level: int = ..., method: int = ..., wbits: int = ..., memLevel: int = ..., strategy: int = ..., zdict: bytes | None = ... + level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None ) -> _Compress: ... -def crc32(__data: array[Any] | bytes, __value: int = ...) -> int: ... -def decompress(__data: bytes, wbits: int = ..., bufsize: int = ...) -> bytes: ... -def decompressobj(wbits: int = ..., zdict: bytes = ...) -> _Decompress: ... +def crc32(data: ReadableBuffer, value: SupportsIndex = 0, /) -> int: ... + +if sys.version_info >= (3, 15): + def crc32_combine(crc1: int, crc2: int, len2: int, /) -> int: ... + +def decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) -> bytes: ... +def decompressobj(wbits: int = 15, zdict: ReadableBuffer = b"") -> _Decompress: ... diff --git a/stdlib/zoneinfo/__init__.pyi b/stdlib/zoneinfo/__init__.pyi index 4f924e0cc4bf..def31546becb 100644 --- a/stdlib/zoneinfo/__init__.pyi +++ b/stdlib/zoneinfo/__init__.pyi @@ -1,32 +1,36 @@ -import typing -from _typeshed import StrPath -from datetime import tzinfo -from typing import Any, Iterable, Protocol, Sequence, Type +import sys +from collections.abc import Iterable +from datetime import datetime, timedelta, tzinfo +from typing_extensions import Self, disjoint_base +from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes +from zoneinfo._tzpath import ( + TZPATH as TZPATH, + InvalidTZPathWarning as InvalidTZPathWarning, + available_timezones as available_timezones, + reset_tzpath as reset_tzpath, +) -_T = typing.TypeVar("_T", bound="ZoneInfo") - -class _IOBytes(Protocol): - def read(self, __size: int) -> bytes: ... - def seek(self, __size: int, __whence: int = ...) -> Any: ... +__all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] +@disjoint_base class ZoneInfo(tzinfo): @property def key(self) -> str: ... - def __init__(self, key: str) -> None: ... - @classmethod - def no_cache(cls: Type[_T], key: str) -> _T: ... + def __new__(cls, key: str) -> Self: ... @classmethod - def from_file(cls: Type[_T], __fobj: _IOBytes, key: str | None = ...) -> _T: ... - @classmethod - def clear_cache(cls, *, only_keys: Iterable[str] = ...) -> None: ... + def no_cache(cls, key: str) -> Self: ... -# Note: Both here and in clear_cache, the types allow the use of `str` where -# a sequence of strings is required. This should be remedied if a solution -# to this typing bug is found: https://github.com/python/typing/issues/256 -def reset_tzpath(to: Sequence[StrPath] | None = ...) -> None: ... -def available_timezones() -> set[str]: ... + if sys.version_info >= (3, 12): + @classmethod + def from_file(cls, file_obj: _IOBytes, /, key: str | None = None) -> Self: ... + else: + @classmethod + def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ... -TZPATH: Sequence[str] + @classmethod + def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: ... + def tzname(self, dt: datetime | None, /) -> str | None: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... + def dst(self, dt: datetime | None, /) -> timedelta | None: ... -class ZoneInfoNotFoundError(KeyError): ... -class InvalidTZPathWarning(RuntimeWarning): ... +def __dir__() -> list[str]: ... diff --git a/stdlib/zoneinfo/_common.pyi b/stdlib/zoneinfo/_common.pyi new file mode 100644 index 000000000000..e6d2d83caac1 --- /dev/null +++ b/stdlib/zoneinfo/_common.pyi @@ -0,0 +1,14 @@ +import io +from typing import Any, Protocol, type_check_only + +@type_check_only +class _IOBytes(Protocol): + def read(self, size: int, /) -> bytes: ... + def seek(self, size: int, whence: int = ..., /) -> Any: ... + +def load_tzdata(key: str) -> io.BufferedReader: ... +def load_data( + fobj: _IOBytes, +) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[str, ...], bytes | None]: ... + +class ZoneInfoNotFoundError(KeyError): ... diff --git a/stdlib/zoneinfo/_tzpath.pyi b/stdlib/zoneinfo/_tzpath.pyi new file mode 100644 index 000000000000..0ef78d03e5f4 --- /dev/null +++ b/stdlib/zoneinfo/_tzpath.pyi @@ -0,0 +1,13 @@ +from _typeshed import StrPath +from collections.abc import Sequence + +# Note: Both here and in clear_cache, the types allow the use of `str` where +# a sequence of strings is required. This should be remedied if a solution +# to this typing bug is found: https://github.com/python/typing/issues/256 +def reset_tzpath(to: Sequence[StrPath] | None = None) -> None: ... +def find_tzfile(key: str) -> str | None: ... +def available_timezones() -> set[str]: ... + +TZPATH: tuple[str, ...] + +class InvalidTZPathWarning(RuntimeWarning): ... diff --git a/stubs/Authlib/@tests/stubtest_allowlist.txt b/stubs/Authlib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..98002c5bac78 --- /dev/null +++ b/stubs/Authlib/@tests/stubtest_allowlist.txt @@ -0,0 +1,49 @@ +# TODO: check these entries +authlib.jose.drafts._jwe_enc_cryptodome + +# Are set to `None` by default, initialized later: +authlib.jose.drafts._jwe_algorithms.ECDH1PUAlgorithm.description +authlib.jose.drafts._jwe_algorithms.ECDH1PUAlgorithm.name +authlib.jose.drafts._jwe_enc_cryptography.C20PEncAlgorithm.description +authlib.jose.drafts._jwe_enc_cryptography.C20PEncAlgorithm.name +authlib.jose.rfc7518.jwe_algs.AESAlgorithm.description +authlib.jose.rfc7518.jwe_algs.AESAlgorithm.name +authlib.jose.rfc7518.jwe_algs.AESGCMAlgorithm.description +authlib.jose.rfc7518.jwe_algs.AESGCMAlgorithm.name +authlib.jose.rfc7518.jwe_algs.ECDHESAlgorithm.description +authlib.jose.rfc7518.jwe_algs.ECDHESAlgorithm.name +authlib.jose.rfc7518.jwe_algs.RSAAlgorithm.description +authlib.jose.rfc7518.jwe_algs.RSAAlgorithm.name +authlib.jose.rfc7518.jwe_encs.CBCHS2EncAlgorithm.CEK_SIZE +authlib.jose.rfc7518.jwe_encs.CBCHS2EncAlgorithm.description +authlib.jose.rfc7518.jwe_encs.CBCHS2EncAlgorithm.name +authlib.jose.rfc7518.jwe_encs.GCMEncAlgorithm.CEK_SIZE +authlib.jose.rfc7518.jwe_encs.GCMEncAlgorithm.description +authlib.jose.rfc7518.jwe_encs.GCMEncAlgorithm.name +authlib.jose.rfc7518.jws_algs.ECAlgorithm.description +authlib.jose.rfc7518.jws_algs.ECAlgorithm.name +authlib.jose.rfc7518.jws_algs.HMACAlgorithm.description +authlib.jose.rfc7518.jws_algs.HMACAlgorithm.name +authlib.jose.rfc7518.jws_algs.RSAAlgorithm.description +authlib.jose.rfc7518.jws_algs.RSAAlgorithm.name +authlib.jose.rfc7518.jws_algs.RSAPSSAlgorithm.description +authlib.jose.rfc7518.jws_algs.RSAPSSAlgorithm.name + +# Methods whose *args and **kwargs arguments are added dynamically due to the @hooked decorator: +authlib.oauth2.rfc6749.grants.authorization_code.AuthorizationCodeGrant.create_token_response +authlib.oauth2.rfc6749.grants.authorization_code.AuthorizationCodeGrant.validate_token_request +authlib.oauth2.rfc6749.grants.base.AuthorizationEndpointMixin.validate_consent_request +authlib.oauth2.rfc6749.grants.client_credentials.ClientCredentialsGrant.create_token_response +authlib.oauth2.rfc6749.grants.implicit.ImplicitGrant.validate_authorization_request +authlib.oauth2.rfc6749.grants.refresh_token.RefreshTokenGrant.create_token_response +authlib.oauth2.rfc6749.grants.resource_owner_password_credentials.ResourceOwnerPasswordCredentialsGrant.create_token_response +authlib.oauth2.rfc8628.device_code.DeviceCodeGrant.create_token_response +authlib.oidc.core.grants.implicit.OpenIDImplicitGrant.validate_consent_request + +# Exclude integrations dirs +# Failed to import, getting ModuleNotFoundError for third-party libs: +authlib.integrations.django_client.* +authlib.integrations.django_oauth1.* +authlib.integrations.django_oauth2.* +authlib.integrations.sqla_oauth2.* +authlib.integrations.starlette_client.* diff --git a/stubs/Authlib/METADATA.toml b/stubs/Authlib/METADATA.toml new file mode 100644 index 000000000000..d4984a274e2d --- /dev/null +++ b/stubs/Authlib/METADATA.toml @@ -0,0 +1,5 @@ +version = "1.8.0" +upstream-repository = "https://github.com/authlib/authlib" +dependencies = ["cryptography"] +# Requires a version of flask with a `py.typed` file +optional-dependencies = ["requests", "httpx2", "Flask>=2.0.0"] diff --git a/stubs/Authlib/authlib/__init__.pyi b/stubs/Authlib/authlib/__init__.pyi new file mode 100644 index 000000000000..a254fc53981c --- /dev/null +++ b/stubs/Authlib/authlib/__init__.pyi @@ -0,0 +1,8 @@ +from typing import Final + +from .consts import author, homepage, version + +__version__: Final = version +__homepage__: Final = homepage +__author__: Final = author +__license__: Final = "BSD-3-Clause" diff --git a/stdlib/@python2/lib2to3/__init__.pyi b/stubs/Authlib/authlib/common/__init__.pyi similarity index 100% rename from stdlib/@python2/lib2to3/__init__.pyi rename to stubs/Authlib/authlib/common/__init__.pyi diff --git a/stubs/Authlib/authlib/common/encoding.pyi b/stubs/Authlib/authlib/common/encoding.pyi new file mode 100644 index 000000000000..42d8ffe8746f --- /dev/null +++ b/stubs/Authlib/authlib/common/encoding.pyi @@ -0,0 +1,28 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Any, SupportsBytes, SupportsIndex, overload + +@overload +def to_bytes(x: None, charset: str = "utf-8", errors: str = "strict") -> None: ... +@overload +def to_bytes( + x: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + charset: str = "utf-8", + errors: str = "strict", +) -> bytes: ... + +@overload +def to_unicode(x: None, charset: str = "utf-8", errors: str = "strict") -> None: ... +@overload +def to_unicode(x: object, charset: str = "utf-8", errors: str = "strict") -> str: ... + +def to_native(x: str | bytes | bytearray, encoding: str = "ascii") -> str: ... +def json_loads(s: str | bytes | bytearray) -> Any: ... # returns json.loads() +def json_dumps(data: Any, ensure_ascii: bool = False) -> str: ... # data pass to json.dumps() +def urlsafe_b64decode(s: bytes | bytearray) -> bytes: ... +def urlsafe_b64encode(s: ReadableBuffer) -> bytes: ... +def base64_to_int(s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer) -> int: ... +def int_to_base64(num: int) -> str: ... +def json_b64encode( + text: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, +) -> bytes: ... diff --git a/stubs/Authlib/authlib/common/errors.pyi b/stubs/Authlib/authlib/common/errors.pyi new file mode 100644 index 000000000000..c6b1276d2571 --- /dev/null +++ b/stubs/Authlib/authlib/common/errors.pyi @@ -0,0 +1,21 @@ +from typing import Literal + +class AuthlibBaseError(Exception): + error: str | None + description: str + uri: str | None + def __init__(self, error: str | None = None, description: str | None = None, uri: str | None = None) -> None: ... + +class AuthlibHTTPError(AuthlibBaseError): + status_code: int + def __init__( + self, error: str | None = None, description: str | None = None, uri: str | None = None, status_code: int | None = None + ) -> None: ... + def get_error_description(self) -> str: ... + def get_body(self) -> list[tuple[Literal["error", "error_description", "error_uri"], str | None]]: ... + def get_headers(self) -> list[tuple[str, str]]: ... + def __call__( + self, uri: str | None = None + ) -> tuple[int, dict[Literal["error", "error_description", "error_uri"], str | None], list[tuple[str, str]]]: ... + +class ContinueIteration(AuthlibBaseError): ... diff --git a/stubs/Authlib/authlib/common/language.pyi b/stubs/Authlib/authlib/common/language.pyi new file mode 100644 index 000000000000..34b1ecf943aa --- /dev/null +++ b/stubs/Authlib/authlib/common/language.pyi @@ -0,0 +1 @@ +def is_valid_language_tag(tag: object) -> bool: ... diff --git a/stubs/Authlib/authlib/common/security.pyi b/stubs/Authlib/authlib/common/security.pyi new file mode 100644 index 000000000000..e57814e44167 --- /dev/null +++ b/stubs/Authlib/authlib/common/security.pyi @@ -0,0 +1,6 @@ +from typing import Final + +UNICODE_ASCII_CHARACTER_SET: Final[str] + +def generate_token(length: int = 30, chars: str = UNICODE_ASCII_CHARACTER_SET) -> str: ... # noqa: Y011 +def is_secure_transport(uri: str) -> bool: ... diff --git a/stubs/Authlib/authlib/common/urls.pyi b/stubs/Authlib/authlib/common/urls.pyi new file mode 100644 index 000000000000..c2f84345f51d --- /dev/null +++ b/stubs/Authlib/authlib/common/urls.pyi @@ -0,0 +1,24 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Final, overload + +always_safe: Final[str] +urlencoded: Final[set[str]] +INVALID_HEX_PATTERN: Final[Pattern[str]] + +def url_encode(params: Iterable[tuple[str, str]]) -> str: ... +def url_decode(query: str) -> list[tuple[str, str]]: ... +def add_params_to_qs(query: str, params: Iterable[tuple[str, str]] | dict[str, str]) -> str: ... +def add_params_to_uri(uri: str, params: Iterable[tuple[str, str]] | dict[str, str], fragment: bool = False) -> str: ... +def quote(s: str | bytes | float, safe: bytes = b"/") -> str: ... +def unquote(s: str | bytes) -> str: ... +def quote_url(s: str | bytes | float) -> str: ... + +@overload +def extract_params(raw: None) -> None: ... +@overload +def extract_params(raw: dict[str, str]) -> list[tuple[str, str]]: ... +@overload +def extract_params(raw: list[tuple[str, str]] | tuple[tuple[str, str], ...] | str) -> list[tuple[str, str]] | None: ... + +def is_valid_url(url: str, fragments_allowed: bool = True) -> bool: ... diff --git a/stubs/Authlib/authlib/consts.pyi b/stubs/Authlib/authlib/consts.pyi new file mode 100644 index 000000000000..f8ec0e9e5e3b --- /dev/null +++ b/stubs/Authlib/authlib/consts.pyi @@ -0,0 +1,8 @@ +from typing import Final + +name: Final = "Authlib" +version: Final[str] +author: Final[str] +homepage: Final[str] +default_user_agent: Final[str] +default_json_headers: Final[list[tuple[str, str]]] diff --git a/stubs/Authlib/authlib/deprecate.pyi b/stubs/Authlib/authlib/deprecate.pyi new file mode 100644 index 000000000000..cb8b6991a7d8 --- /dev/null +++ b/stubs/Authlib/authlib/deprecate.pyi @@ -0,0 +1,3 @@ +class AuthlibDeprecationWarning(DeprecationWarning): ... + +def deprecate(message: str, version: str | None = None, stacklevel: int = 3) -> None: ... diff --git a/stdlib/@python2/lib2to3/pgen2/__init__.pyi b/stubs/Authlib/authlib/integrations/__init__.pyi similarity index 100% rename from stdlib/@python2/lib2to3/pgen2/__init__.pyi rename to stubs/Authlib/authlib/integrations/__init__.pyi diff --git a/stubs/Authlib/authlib/integrations/base_client/__init__.pyi b/stubs/Authlib/authlib/integrations/base_client/__init__.pyi new file mode 100644 index 000000000000..424bfdf05f60 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/__init__.pyi @@ -0,0 +1,29 @@ +from .errors import ( + InvalidTokenError as InvalidTokenError, + MismatchingStateError as MismatchingStateError, + MissingRequestTokenError as MissingRequestTokenError, + MissingTokenError as MissingTokenError, + OAuthError as OAuthError, + TokenExpiredError as TokenExpiredError, + UnsupportedTokenTypeError as UnsupportedTokenTypeError, +) +from .framework_integration import FrameworkIntegration as FrameworkIntegration +from .registry import BaseOAuth as BaseOAuth +from .sync_app import BaseApp as BaseApp, OAuth1Mixin as OAuth1Mixin, OAuth2Mixin as OAuth2Mixin +from .sync_openid import OpenIDMixin as OpenIDMixin + +__all__ = [ + "BaseOAuth", + "BaseApp", + "OAuth1Mixin", + "OAuth2Mixin", + "OpenIDMixin", + "FrameworkIntegration", + "OAuthError", + "MissingRequestTokenError", + "MissingTokenError", + "TokenExpiredError", + "InvalidTokenError", + "UnsupportedTokenTypeError", + "MismatchingStateError", +] diff --git a/stubs/Authlib/authlib/integrations/base_client/async_app.pyi b/stubs/Authlib/authlib/integrations/base_client/async_app.pyi new file mode 100644 index 000000000000..352fd5815b8e --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/async_app.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.integrations.base_client.sync_app import OAuth1Base, OAuth2Base + +log: Logger + +__all__ = ["AsyncOAuth1Mixin", "AsyncOAuth2Mixin"] + +class AsyncOAuth1Mixin(OAuth1Base): + async def request(self, method, url, token=None, **kwargs): ... + async def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + async def fetch_access_token(self, request_token=None, **kwargs): ... + +class AsyncOAuth2Mixin(OAuth2Base): + async def load_server_metadata(self) -> dict[Incomplete, Incomplete]: ... + async def request(self, method, url, token=None, **kwargs): ... + async def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + async def fetch_access_token(self, redirect_uri=None, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi b/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi new file mode 100644 index 000000000000..3213ac6631b0 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi @@ -0,0 +1,12 @@ +from authlib.integrations.base_client.sync_openid import _LogoutData +from authlib.oidc.core.claims import UserInfo + +__all__ = ["AsyncOpenIDMixin"] + +class AsyncOpenIDMixin: + async def fetch_jwk_set(self, force: bool = False): ... + async def userinfo(self, **kwargs) -> UserInfo: ... + async def parse_id_token(self, token, nonce, claims_options=None, claims_cls=None, leeway: int = 120) -> UserInfo: ... + async def create_logout_url( + self, post_logout_redirect_uri=None, id_token_hint=None, state=None, *, client_id=None, logout_hint=None, ui_locales=None + ) -> _LogoutData: ... diff --git a/stubs/Authlib/authlib/integrations/base_client/errors.pyi b/stubs/Authlib/authlib/integrations/base_client/errors.pyi new file mode 100644 index 000000000000..0b5cfd7db6d3 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/errors.pyi @@ -0,0 +1,23 @@ +from authlib.common.errors import AuthlibBaseError + +class OAuthError(AuthlibBaseError): + error: str + +class MissingRequestTokenError(OAuthError): + error: str + +class MissingTokenError(OAuthError): + error: str + +class TokenExpiredError(OAuthError): + error: str + +class InvalidTokenError(OAuthError): + error: str + +class UnsupportedTokenTypeError(OAuthError): + error: str + +class MismatchingStateError(OAuthError): + error: str + description: str diff --git a/stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi b/stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi new file mode 100644 index 000000000000..2c3c871ad658 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class FrameworkIntegration: + expires_in: int + name: Incomplete + cache: Incomplete + def __init__(self, name, cache=None) -> None: ... + def get_state_data(self, session, state): ... + def set_state_data(self, session, state, data): ... + def clear_state_data(self, session, state): ... + def update_token(self, token, refresh_token=None, access_token=None): ... + @staticmethod + def load_config(oauth, name, params): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/registry.pyi b/stubs/Authlib/authlib/integrations/base_client/registry.pyi new file mode 100644 index 000000000000..657eefe452b9 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/registry.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from authlib.integrations.base_client import FrameworkIntegration + +__all__ = ["BaseOAuth"] + +class BaseOAuth: + oauth1_client_cls: Incomplete + oauth2_client_cls: Incomplete + framework_integration_cls: type[FrameworkIntegration] = ... + cache: Incomplete + fetch_token: Incomplete + update_token: Incomplete + def __init__(self, cache=None, fetch_token=None, update_token=None) -> None: ... + def create_client(self, name): ... + def register(self, name, overwrite: bool = False, **kwargs): ... + def generate_client_kwargs(self, name, overwrite, **kwargs) -> dict[Incomplete, Incomplete]: ... + def load_config(self, name, params): ... + def __getattr__(self, key): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/sync_app.pyi b/stubs/Authlib/authlib/integrations/base_client/sync_app.pyi new file mode 100644 index 000000000000..8263f9975674 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/sync_app.pyi @@ -0,0 +1,96 @@ +from _typeshed import Incomplete +from logging import Logger + +log: Logger + +class BaseApp: + client_cls: Incomplete + OAUTH_APP_CONFIG: Incomplete + def request(self, method, url, token=None, **kwargs): ... + def get(self, url, **kwargs): ... + def post(self, url, **kwargs): ... + def patch(self, url, **kwargs): ... + def put(self, url, **kwargs): ... + def delete(self, url, **kwargs): ... + +class _RequestMixin: ... + +class OAuth1Base: + client_cls: Incomplete + framework: Incomplete + name: Incomplete + client_id: Incomplete + client_secret: Incomplete + request_token_url: Incomplete + request_token_params: Incomplete + access_token_url: Incomplete + access_token_params: Incomplete + authorize_url: Incomplete + authorize_params: Incomplete + api_base_url: Incomplete + client_kwargs: Incomplete + def __init__( + self, + framework, + name=None, + fetch_token=None, + client_id=None, + client_secret=None, + request_token_url=None, + request_token_params=None, + access_token_url=None, + access_token_params=None, + authorize_url=None, + authorize_params=None, + api_base_url=None, + client_kwargs=None, + user_agent=None, + **kwargs, + ) -> None: ... + +class OAuth1Mixin(_RequestMixin, OAuth1Base): + def request(self, method, url, token=None, **kwargs): ... + def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + def fetch_access_token(self, request_token=None, **kwargs): ... + +class OAuth2Base: + client_cls: Incomplete + framework: Incomplete + name: Incomplete + client_id: Incomplete + client_secret: Incomplete + access_token_url: Incomplete + access_token_params: Incomplete + authorize_url: Incomplete + authorize_params: Incomplete + api_base_url: Incomplete + client_kwargs: Incomplete + compliance_fix: Incomplete + client_auth_methods: Incomplete + server_metadata: Incomplete + def __init__( + self, + framework, + name=None, + fetch_token=None, + update_token=None, + client_id=None, + client_secret=None, + access_token_url=None, + access_token_params=None, + authorize_url=None, + authorize_params=None, + api_base_url=None, + client_kwargs=None, + server_metadata_url=None, + compliance_fix=None, + client_auth_methods=None, + user_agent=None, + **kwargs, + ) -> None: ... + +class OAuth2Mixin(_RequestMixin, OAuth2Base): + def request(self, method, url, token=None, **kwargs): ... + def load_server_metadata(self) -> dict[Incomplete, Incomplete]: ... + def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + def fetch_access_token(self, redirect_uri=None, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi b/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi new file mode 100644 index 000000000000..5bd8eb1de7da --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +from authlib.oidc.core.claims import UserInfo + +@type_check_only +class _LogoutData(TypedDict): + url: str + state: Incomplete + +class OpenIDMixin: + def fetch_jwk_set(self, force: bool = False): ... + def userinfo(self, **kwargs) -> UserInfo: ... + def parse_id_token(self, token, nonce, claims_options=None, claims_cls=None, leeway: int = 120) -> UserInfo | None: ... + def create_logout_url( + self, post_logout_redirect_uri=None, id_token_hint=None, state=None, *, client_id=None, logout_hint=None, ui_locales=None + ) -> _LogoutData: ... diff --git a/stubs/Authlib/authlib/integrations/django_client/__init__.pyi b/stubs/Authlib/authlib/integrations/django_client/__init__.pyi new file mode 100644 index 000000000000..c5c48e4777c5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_client/__init__.pyi @@ -0,0 +1,10 @@ +from ..base_client import BaseOAuth, OAuthError as OAuthError +from .apps import DjangoOAuth1App as DjangoOAuth1App, DjangoOAuth2App as DjangoOAuth2App +from .integration import DjangoIntegration as DjangoIntegration, token_update as token_update + +class OAuth(BaseOAuth): + oauth1_client_cls = DjangoOAuth1App + oauth2_client_cls = DjangoOAuth2App + framework_integration_cls = DjangoIntegration + +__all__ = ["OAuth", "DjangoOAuth1App", "DjangoOAuth2App", "DjangoIntegration", "token_update", "OAuthError"] diff --git a/stubs/Authlib/authlib/integrations/django_client/apps.pyi b/stubs/Authlib/authlib/integrations/django_client/apps.pyi new file mode 100644 index 000000000000..1325168c1fc4 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_client/apps.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +from ..base_client import BaseApp, OAuth1Mixin, OAuth2Mixin, OpenIDMixin +from ..requests_client import OAuth1Session, OAuth2Session + +_HttpResponseRedirect: TypeAlias = Incomplete # actual type is django.http.response.HttpResponseRedirect + +class DjangoAppMixin: + def save_authorize_data(self, request, **kwargs) -> None: ... + def authorize_redirect(self, request, redirect_uri=None, **kwargs): ... + +class DjangoOAuth1App(DjangoAppMixin, OAuth1Mixin, BaseApp): + client_cls = OAuth1Session + def authorize_access_token(self, request, **kwargs): ... + +class DjangoOAuth2App(DjangoAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): + client_cls = OAuth2Session + def logout_redirect( + self, + request, + post_logout_redirect_uri=None, + id_token_hint=None, + *, + state=None, + client_id=None, + logout_hint=None, + ui_locales=None, + ) -> _HttpResponseRedirect: ... + def validate_logout_response(self, request): ... + def authorize_access_token(self, request, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/django_client/integration.pyi b/stubs/Authlib/authlib/integrations/django_client/integration.pyi new file mode 100644 index 000000000000..91469e1953da --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_client/integration.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from ..base_client import FrameworkIntegration + +# actual type is django.dispatch.Signal +token_update: Incomplete + +class DjangoIntegration(FrameworkIntegration): + def update_token(self, token, refresh_token=None, access_token=None) -> None: ... + @staticmethod + def load_config(oauth, name, params): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi new file mode 100644 index 000000000000..3c684184a795 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi @@ -0,0 +1,4 @@ +from .authorization_server import BaseServer as BaseServer, CacheAuthorizationServer as CacheAuthorizationServer +from .resource_protector import ResourceProtector as ResourceProtector + +__all__ = ["BaseServer", "CacheAuthorizationServer", "ResourceProtector"] diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi new file mode 100644 index 000000000000..2d4b0bacaca5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi @@ -0,0 +1,26 @@ +import logging +from _typeshed import Incomplete + +from authlib.oauth1 import AuthorizationServer as _AuthorizationServer, OAuth1Request, TemporaryCredential + +log: logging.Logger + +class BaseServer(_AuthorizationServer): + token_generator: Incomplete + client_model: Incomplete + token_model: Incomplete + SUPPORTED_SIGNATURE_METHODS: Incomplete + def __init__(self, client_model, token_model, token_generator=None) -> None: ... + def get_client_by_id(self, client_id): ... + def exists_nonce(self, nonce, request) -> bool: ... + def create_token_credential(self, request): ... + def check_authorization_request(self, request) -> OAuth1Request: ... + def create_oauth1_request(self, request) -> OAuth1Request: ... + def handle_response(self, status_code, payload, headers): ... + +class CacheAuthorizationServer(BaseServer): + def __init__(self, client_model, token_model, token_generator=None) -> None: ... + def create_temporary_credential(self, request) -> TemporaryCredential: ... + def get_temporary_credential(self, request) -> TemporaryCredential | None: ... + def delete_temporary_credential(self, request) -> None: ... + def create_authorization_verifier(self, request) -> str: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi new file mode 100644 index 000000000000..b4d93191444c --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi @@ -0,0 +1 @@ +def exists_nonce_in_cache(nonce, request, timeout) -> bool: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi new file mode 100644 index 000000000000..d3e3f568d21b --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from authlib.oauth1 import ResourceProtector as _ResourceProtector + +class ResourceProtector(_ResourceProtector): + client_model: Incomplete + token_model: Incomplete + SUPPORTED_SIGNATURE_METHODS: Incomplete + def __init__(self, client_model, token_model) -> None: ... + def get_client_by_id(self, client_id): ... + def get_token_credential(self, request): ... + def exists_nonce(self, nonce, request) -> bool: ... + def acquire_credential(self, request): ... + def __call__(self, realm=None): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi new file mode 100644 index 000000000000..d627f322cf4d --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi @@ -0,0 +1,8 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .endpoints import RevocationEndpoint as RevocationEndpoint +from .resource_protector import BearerTokenValidator as BearerTokenValidator, ResourceProtector as ResourceProtector +from .signals import ( + client_authenticated as client_authenticated, + token_authenticated as token_authenticated, + token_revoked as token_revoked, +) diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi new file mode 100644 index 000000000000..cecb3d9ae968 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import AuthorizationServer as _AuthorizationServer +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +from .requests import DjangoJsonRequest, DjangoOAuth2Request + +class AuthorizationServer(_AuthorizationServer): + client_model: Incomplete + token_model: Incomplete + def __init__(self, client_model, token_model) -> None: ... + config: Incomplete + scopes_supported: Incomplete + def load_config(self, config) -> None: ... + def query_client(self, client_id): ... + def save_token(self, token, request): ... + def create_oauth2_request(self, request) -> DjangoOAuth2Request: ... + def create_json_request(self, request) -> DjangoJsonRequest: ... + def handle_response(self, status_code, payload, headers): ... + def send_signal(self, name, *args, **kwargs) -> None: ... + def create_bearer_token_generator(self) -> BearerTokenGenerator: ... + +def create_token_generator(token_generator_conf, length: int = 42): ... +def create_token_expires_in_generator(expires_in_conf=None): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi new file mode 100644 index 000000000000..9eb7a277a46b --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi @@ -0,0 +1,5 @@ +from authlib.oauth2.rfc7009 import RevocationEndpoint as _RevocationEndpoint + +class RevocationEndpoint(_RevocationEndpoint): + def query_token(self, token, token_type_hint): ... + def revoke_token(self, token, request) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi new file mode 100644 index 000000000000..05006392b374 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi @@ -0,0 +1,20 @@ +from authlib.oauth2.rfc6749 import JsonPayload, JsonRequest, OAuth2Payload, OAuth2Request + +class DjangoOAuth2Payload(OAuth2Payload): + def __init__(self, request) -> None: ... + +class DjangoOAuth2Request(OAuth2Request): + payload: DjangoOAuth2Payload + def __init__(self, request) -> None: ... + @property + def args(self): ... + @property + def form(self): ... + +class DjangoJsonPayload(JsonPayload): + def __init__(self, request) -> None: ... + def data(self): ... + +class DjangoJsonRequest(JsonRequest): + payload: DjangoJsonPayload + def __init__(self, request) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi new file mode 100644 index 000000000000..1538f368ca44 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import ResourceProtector as _ResourceProtector +from authlib.oauth2.rfc6750 import BearerTokenValidator as _BearerTokenValidator + +class ResourceProtector(_ResourceProtector): + def acquire_token(self, request, scopes=None, **kwargs): ... + def __call__(self, scopes=None, optional=False, **kwargs): ... + +class BearerTokenValidator(_BearerTokenValidator): + token_model: Incomplete + def __init__(self, token_model, realm=None, **extra_attributes): ... + def authenticate_token(self, token_string): ... + +def return_error_response(error): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi new file mode 100644 index 000000000000..c5e48ddef194 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +# actual types is django.dispatch.Signal +client_authenticated: Incomplete +token_revoked: Incomplete +token_authenticated: Incomplete diff --git a/stubs/Authlib/authlib/integrations/flask_client/__init__.pyi b/stubs/Authlib/authlib/integrations/flask_client/__init__.pyi new file mode 100644 index 000000000000..0dcc913e0463 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_client/__init__.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from flask import Flask + +from ..base_client import BaseOAuth, OAuthError as OAuthError +from .apps import FlaskOAuth1App as FlaskOAuth1App, FlaskOAuth2App as FlaskOAuth2App +from .integration import FlaskIntegration as FlaskIntegration, token_update as token_update + +class OAuth(BaseOAuth): + oauth1_client_cls = FlaskOAuth1App + oauth2_client_cls = FlaskOAuth2App + framework_integration_cls = FlaskIntegration + app: Flask | None + def __init__(self, app: Flask | None = None, cache=None, fetch_token=None, update_token=None) -> None: ... + cache: Incomplete + fetch_token: Incomplete + update_token: Incomplete + def init_app(self, app: Flask, cache=None, fetch_token=None, update_token=None) -> None: ... + def create_client(self, name): ... + def register(self, name, overwrite=False, **kwargs): ... + +__all__ = ["OAuth", "FlaskIntegration", "FlaskOAuth1App", "FlaskOAuth2App", "token_update", "OAuthError"] diff --git a/stubs/Authlib/authlib/integrations/flask_client/apps.pyi b/stubs/Authlib/authlib/integrations/flask_client/apps.pyi new file mode 100644 index 000000000000..70bf6bcb4581 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_client/apps.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete + +from werkzeug.wrappers import Response + +from ..base_client import BaseApp, OAuth1Mixin, OAuth2Mixin, OpenIDMixin +from ..requests_client import OAuth1Session, OAuth2Session + +class FlaskAppMixin: + @property + def token(self): ... + @token.setter + def token(self, token): ... + + def save_authorize_data(self, **kwargs) -> None: ... + def authorize_redirect(self, redirect_uri=None, **kwargs) -> Response: ... + +class FlaskOAuth1App(FlaskAppMixin, OAuth1Mixin, BaseApp): + client_cls = OAuth1Session + def authorize_access_token(self, **kwargs) -> dict[Incomplete, Incomplete]: ... + +class FlaskOAuth2App(FlaskAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): + client_cls = OAuth2Session + def logout_redirect( + self, post_logout_redirect_uri=None, id_token_hint=None, *, state=None, client_id=None, logout_hint=None, ui_locales=None + ) -> Response: ... + def validate_logout_response(self): ... + def authorize_access_token(self, **kwargs) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/integrations/flask_client/integration.pyi b/stubs/Authlib/authlib/integrations/flask_client/integration.pyi new file mode 100644 index 000000000000..ccc894f187ea --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_client/integration.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from blinker import NamedSignal + +from ..base_client import FrameworkIntegration + +token_update: NamedSignal + +class FlaskIntegration(FrameworkIntegration): + def update_token(self, token, refresh_token=None, access_token=None) -> None: ... + @staticmethod + def load_config(oauth, name, params) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi new file mode 100644 index 000000000000..fbe0b2b0ad44 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi @@ -0,0 +1,7 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .cache import ( + create_exists_nonce_func as create_exists_nonce_func, + register_nonce_hooks as register_nonce_hooks, + register_temporary_credential_hooks as register_temporary_credential_hooks, +) +from .resource_protector import ResourceProtector as ResourceProtector, current_credential as current_credential diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi new file mode 100644 index 000000000000..be1e84f6d4fe --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi @@ -0,0 +1,30 @@ +import logging +from _typeshed import Incomplete +from collections.abc import Callable + +from authlib.oauth1 import AuthorizationServer as _AuthorizationServer, OAuth1Request +from flask import Flask, Response + +log: logging.Logger + +class AuthorizationServer(_AuthorizationServer): + app: Flask | None + query_client: Incomplete + token_generator: Incomplete + def __init__(self, app: Flask | None = None, query_client=None, token_generator=None) -> None: ... + SUPPORTED_SIGNATURE_METHODS: Incomplete + def init_app(self, app: Flask, query_client=None, token_generator=None) -> None: ... + def register_hook(self, name: str, func) -> None: ... + def create_token_generator(self, app: Flask) -> Callable[[], dict[str, str]]: ... + def get_client_by_id(self, client_id): ... + def exists_nonce(self, nonce, request): ... + def create_temporary_credential(self, request): ... + def get_temporary_credential(self, request): ... + def delete_temporary_credential(self, request): ... + def create_authorization_verifier(self, request): ... + def create_token_credential(self, request): ... + def check_authorization_request(self) -> OAuth1Request: ... + def create_authorization_response(self, request=None, grant_user=None): ... + def create_token_response(self, request=None): ... + def create_oauth1_request(self, request) -> OAuth1Request: ... + def handle_response(self, status_code, payload, headers) -> Response: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi new file mode 100644 index 000000000000..a3ee17809142 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from authlib.oauth1.rfc5849.authorization_server import AuthorizationServer + +def register_temporary_credential_hooks( + authorization_server: AuthorizationServer, cache, key_prefix: str = "temporary_credential:" +) -> None: ... +def create_exists_nonce_func( + cache, key_prefix: str = "nonce:", expires=86400 +) -> Callable[[Incomplete, Incomplete, Incomplete, Incomplete], Incomplete]: ... +def register_nonce_hooks(authorization_server: AuthorizationServer, cache, key_prefix: str = "nonce:", expires=86400) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi new file mode 100644 index 000000000000..b63d437d17bd --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from authlib.oauth1 import ResourceProtector as _ResourceProtector +from flask import Flask +from werkzeug.local import LocalProxy + +class ResourceProtector(_ResourceProtector): + app: Flask | None + query_client: Incomplete + query_token: Incomplete + def __init__(self, app: Flask | None = None, query_client=None, query_token=None, exists_nonce=None) -> None: ... + SUPPORTED_SIGNATURE_METHODS: Incomplete + def init_app(self, app: Flask, query_client=None, query_token=None, exists_nonce=None) -> None: ... + def get_client_by_id(self, client_id): ... + def get_token_credential(self, request): ... + def exists_nonce(self, nonce, request): ... + def acquire_credential(self): ... + def __call__(self, scope=None): ... + +current_credential: LocalProxy[Incomplete] diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi new file mode 100644 index 000000000000..ba510bf3a322 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi @@ -0,0 +1,7 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .resource_protector import ResourceProtector as ResourceProtector, current_token as current_token +from .signals import ( + client_authenticated as client_authenticated, + token_authenticated as token_authenticated, + token_revoked as token_revoked, +) diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi new file mode 100644 index 000000000000..fa3ff6e4e6ce --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import AuthorizationServer as _AuthorizationServer +from authlib.oauth2.rfc6750 import BearerTokenGenerator +from flask import Flask, Response + +from .requests import FlaskJsonRequest, FlaskOAuth2Request + +class AuthorizationServer(_AuthorizationServer): + def __init__(self, app: Flask | None = None, query_client=None, save_token=None) -> None: ... + def init_app(self, app: Flask, query_client=None, save_token=None) -> None: ... + scopes_supported: Incomplete + def load_config(self, config) -> None: ... + def query_client(self, client_id): ... + def save_token(self, token, request): ... + def get_error_uri(self, request, error): ... + def create_oauth2_request(self, request) -> FlaskOAuth2Request: ... + def create_json_request(self, request) -> FlaskJsonRequest: ... + def handle_response(self, status_code, payload, headers) -> Response: ... + def send_signal(self, name, *args, **kwargs) -> None: ... + def create_bearer_token_generator(self, config) -> BearerTokenGenerator: ... + +def create_token_expires_in_generator(expires_in_conf=None): ... +def create_token_generator(token_generator_conf, length: int = 42): ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi new file mode 100644 index 000000000000..4a1b003bea5f --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +from werkzeug.exceptions import HTTPException +from werkzeug.sansio.response import Response as SansIOResponse + +class _HTTPException(HTTPException): + code: Incomplete + body: Incomplete + headers: Incomplete + def __init__(self, code, body, headers, response: SansIOResponse | None = None) -> None: ... + # Params depends on `werkzeug` package version + def get_body(self, environ=None, scope=None): ... + def get_headers(self, environ=None, scope=None): ... + +def raise_http_exception(status, body, headers) -> Never: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi new file mode 100644 index 000000000000..3a8c03d05cfe --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi @@ -0,0 +1,30 @@ +from collections import defaultdict +from functools import cached_property + +from authlib.oauth2.rfc6749 import JsonPayload, JsonRequest, OAuth2Payload, OAuth2Request +from flask.wrappers import Request +from werkzeug.datastructures.structures import CombinedMultiDict, ImmutableMultiDict, MultiDict + +class FlaskOAuth2Payload(OAuth2Payload): + def __init__(self, request: Request) -> None: ... + @property + def data(self) -> CombinedMultiDict[str, str]: ... + @cached_property + def datalist(self) -> defaultdict[str, list[str]]: ... + +class FlaskOAuth2Request(OAuth2Request): + payload: FlaskOAuth2Payload + def __init__(self, request: Request) -> None: ... + @property + def args(self) -> MultiDict[str, str]: ... # type: ignore[override] + @property + def form(self) -> ImmutableMultiDict[str, str]: ... + +class FlaskJsonPayload(JsonPayload): + def __init__(self, request: Request) -> None: ... + @property + def data(self): ... + +class FlaskJsonRequest(JsonRequest): + payload: FlaskJsonPayload + def __init__(self, request: Request) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi new file mode 100644 index 000000000000..d60fd9cce339 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from contextlib import contextmanager +from typing_extensions import Never + +from authlib.oauth2 import ResourceProtector as _ResourceProtector +from werkzeug.local import LocalProxy + +class ResourceProtector(_ResourceProtector): + def raise_error_response(self, error) -> Never: ... + def acquire_token(self, scopes=None, **kwargs): ... + @contextmanager + def acquire(self, scopes=None) -> Generator[Incomplete]: ... + def __call__(self, scopes=None, optional: bool = False, **kwargs): ... + +current_token: LocalProxy[Incomplete] diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi new file mode 100644 index 000000000000..3523fe2a3326 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi @@ -0,0 +1,5 @@ +from blinker import NamedSignal + +client_authenticated: NamedSignal +token_revoked: NamedSignal +token_authenticated: NamedSignal diff --git a/stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi b/stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi new file mode 100644 index 000000000000..58b88a90fb2d --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi @@ -0,0 +1,37 @@ +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, +) + +from ..base_client import OAuthError as OAuthError +from .assertion_client import AssertionClient as AssertionClient, AsyncAssertionClient as AsyncAssertionClient +from .oauth1_client import AsyncOAuth1Client as AsyncOAuth1Client, OAuth1Auth as OAuth1Auth, OAuth1Client as OAuth1Client +from .oauth2_client import ( + AsyncOAuth2Client as AsyncOAuth2Client, + OAuth2Auth as OAuth2Auth, + OAuth2Client as OAuth2Client, + OAuth2ClientAuth as OAuth2ClientAuth, +) + +__all__ = [ + "OAuthError", + "OAuth1Auth", + "AsyncOAuth1Client", + "OAuth1Client", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "OAuth2Auth", + "OAuth2ClientAuth", + "OAuth2Client", + "AsyncOAuth2Client", + "AssertionClient", + "AsyncAssertionClient", +] diff --git a/stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi b/stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi new file mode 100644 index 000000000000..fe8b01939cd4 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete + +import httpx2 +from authlib.oauth2.rfc7521 import AssertionClient as _AssertionClient + +from ..base_client import OAuthError +from .oauth2_client import OAuth2Auth + +USE_CLIENT_DEFAULT = httpx2.USE_CLIENT_DEFAULT +Response = httpx2.Response + +__all__ = ["AsyncAssertionClient"] + +class AsyncAssertionClient(_AssertionClient, httpx2.AsyncClient): + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + JWT_BEARER_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + DEFAULT_GRANT_TYPE: Incomplete + def __init__( + self, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement="header", + scope=None, + client_id=None, + **kwargs, + ) -> None: ... + async def request(self, method, url, withhold_token=False, auth=..., **kwargs): ... + +class AssertionClient(_AssertionClient, httpx2.Client): + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + JWT_BEARER_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + DEFAULT_GRANT_TYPE: Incomplete + def __init__( + self, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement="header", + scope=None, + client_id=None, + **kwargs, + ) -> None: ... + def request(self, method, url, withhold_token=False, auth=..., **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi b/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi new file mode 100644 index 000000000000..19c65b3cd70f --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi @@ -0,0 +1,53 @@ +from collections.abc import Generator +from typing_extensions import Never + +import httpx2 +from authlib.oauth1 import ClientAuth +from authlib.oauth1.client import OAuth1Client as _OAuth1Client + +Auth = httpx2.Auth +Request = httpx2.Request +Response = httpx2.Response + +class OAuth1Auth(Auth, ClientAuth): + requires_request_body: bool + def auth_flow(self, request: Request) -> Generator[Request, Response]: ... + +class AsyncOAuth1Client(_OAuth1Client, httpx2.AsyncClient): # type: ignore[misc] # incompatible definitions of "auth" in the base classes + auth_class = OAuth1Auth + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method=..., + signature_type=..., + force_include_body=False, + **kwargs, + ) -> None: ... + async def fetch_access_token(self, url, verifier=None, **kwargs): ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... + +class OAuth1Client(_OAuth1Client, httpx2.Client): # type: ignore[misc] # incompatible definitions of "auth" in the base classes + auth_class = OAuth1Auth + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method=..., + signature_type=..., + force_include_body=False, + **kwargs, + ) -> None: ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... diff --git a/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi b/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi new file mode 100644 index 000000000000..cba2ec0f2880 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi @@ -0,0 +1,69 @@ +from collections.abc import Generator +from typing_extensions import Never + +import httpx2 +from authlib.oauth2.auth import ClientAuth, TokenAuth +from authlib.oauth2.client import OAuth2Client as _OAuth2Client + +from ..base_client import OAuthError + +USE_CLIENT_DEFAULT = httpx2.USE_CLIENT_DEFAULT +Auth = httpx2.Auth +Request = httpx2.Request +Response = httpx2.Response + +__all__ = ["OAuth2Auth", "OAuth2ClientAuth", "AsyncOAuth2Client", "OAuth2Client"] + +class OAuth2Auth(Auth, TokenAuth): + requires_request_body: bool + def auth_flow(self, request: Request) -> Generator[Request, Response]: ... + +class OAuth2ClientAuth(Auth, ClientAuth): + requires_request_body: bool + def auth_flow(self, request: Request) -> Generator[Request, Response]: ... + +class AsyncOAuth2Client(_OAuth2Client, httpx2.AsyncClient): + SESSION_REQUEST_PARAMS: list[str] + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + def __init__( + self, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + redirect_uri=None, + token=None, + token_placement="header", + update_token=None, + leeway=60, + **kwargs, + ) -> None: ... + async def request(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... + async def stream(self, method, url, withhold_token: bool = False, auth=..., **kwargs) -> Generator[Response]: ... # type: ignore[override] + async def ensure_active_token(self, token): ... # type: ignore[override] + +class OAuth2Client(_OAuth2Client, httpx2.Client): + SESSION_REQUEST_PARAMS: list[str] + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + def __init__( + self, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + redirect_uri=None, + token=None, + token_placement="header", + update_token=None, + **kwargs, + ) -> None: ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... + def request(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... + def stream(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/httpx_client/utils.pyi b/stubs/Authlib/authlib/integrations/httpx_client/utils.pyi new file mode 100644 index 000000000000..14b18cf83602 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/utils.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from typing import Final + +import httpx2 +from httpx2._types import HeaderTypes, RequestContent + +HTTPX_CLIENT_KWARGS: Final[list[str]] + +Request = httpx2.Request + +def extract_client_kwargs(kwargs: dict[str, Incomplete]) -> dict[str, Incomplete]: ... +def build_request( + url: httpx2.URL | str, headers: HeaderTypes | None, body: RequestContent, initial_request: httpx2.Request +) -> httpx2.Request: ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/__init__.pyi b/stubs/Authlib/authlib/integrations/requests_client/__init__.pyi new file mode 100644 index 000000000000..fc7b705e0ce0 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/__init__.pyi @@ -0,0 +1,28 @@ +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, +) + +from ..base_client import OAuthError as OAuthError +from .assertion_session import AssertionSession as AssertionSession +from .oauth1_session import OAuth1Auth as OAuth1Auth, OAuth1Session as OAuth1Session +from .oauth2_session import OAuth2Auth as OAuth2Auth, OAuth2Session as OAuth2Session + +__all__ = [ + "OAuthError", + "OAuth1Session", + "OAuth1Auth", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "OAuth2Session", + "OAuth2Auth", + "AssertionSession", +] diff --git a/stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi b/stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi new file mode 100644 index 000000000000..d229e1dbb852 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from http.cookiejar import CookieJar + +from authlib.oauth2.rfc7521 import AssertionClient +from requests import Response, Session +from requests._types import ( + AuthType, + CertType, + DataType, + FilesType, + HeadersType, + HooksInputType, + JsonType, + ParamsType, + TimeoutType, + UriType, + VerifyType, +) +from requests.cookies import RequestsCookieJar + +from .oauth2_session import OAuth2Auth + +class AssertionAuth(OAuth2Auth): + def ensure_active_token(self): ... + +class AssertionSession(AssertionClient, Session): + token_auth_class = AssertionAuth + JWT_BEARER_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + DEFAULT_GRANT_TYPE: Incomplete + default_timeout: Incomplete + def __init__( + self, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement="header", + scope=None, + client_id=None, + default_timeout=None, + leeway=60, + **kwargs, + ) -> None: ... + def request( # type: ignore[override] + self, + method: str, + url: UriType, + withhold_token: bool = False, + auth: AuthType | None = None, + *, + params: ParamsType = None, + data: DataType = None, + headers: HeadersType = None, + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, + files: FilesType = None, + timeout: TimeoutType = None, + allow_redirects: bool = True, + proxies: dict[str, str] | None = None, + hooks: HooksInputType | None = None, + stream: bool | None = None, + verify: VerifyType | None = None, + cert: CertType = None, + json: JsonType = None, + ) -> Response: ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi b/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi new file mode 100644 index 000000000000..1fe0c4835aca --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi @@ -0,0 +1,30 @@ +from typing_extensions import Never + +from authlib.oauth1 import ClientAuth +from authlib.oauth1.client import OAuth1Client +from requests import PreparedRequest, Response, Session +from requests.auth import AuthBase + +class OAuth1Auth(AuthBase, ClientAuth): + def __call__(self, req: PreparedRequest) -> PreparedRequest: ... + +# Incompatible definitions of "auth" in the base classes +class OAuth1Session(OAuth1Client, Session): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + auth_class = OAuth1Auth + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method="HMAC-SHA1", + signature_type="HEADER", + force_include_body=False, + **kwargs, + ) -> None: ... + def rebuild_auth(self, prepared_request: PreparedRequest, response: Response) -> None: ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi b/stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi new file mode 100644 index 000000000000..ded2533ffa76 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from http.cookiejar import CookieJar + +from authlib.oauth2.auth import ClientAuth, TokenAuth +from authlib.oauth2.client import OAuth2Client +from requests import PreparedRequest, Response, Session +from requests._types import ( + AuthType, + CertType, + DataType, + FilesType, + HeadersType, + HooksInputType, + JsonType, + ParamsType, + TimeoutType, + UriType, + VerifyType, +) +from requests.auth import AuthBase +from requests.cookies import RequestsCookieJar + +from ..base_client import OAuthError + +__all__ = ["OAuth2Session", "OAuth2Auth"] + +class OAuth2Auth(AuthBase, TokenAuth): + def ensure_active_token(self) -> None: ... + def __call__(self, req: PreparedRequest) -> PreparedRequest: ... + +class OAuth2ClientAuth(AuthBase, ClientAuth): + def __call__(self, req: PreparedRequest) -> PreparedRequest: ... + +class OAuth2Session(OAuth2Client, Session): + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + SESSION_REQUEST_PARAMS: tuple[str, ...] # type: ignore[assignment] + default_timeout: Incomplete + def __init__( + self, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + state=None, + redirect_uri=None, + token=None, + token_placement="header", + update_token=None, + leeway=60, + default_timeout=None, + **kwargs, + ) -> None: ... + def fetch_access_token(self, url=None, **kwargs): ... + def request( # type: ignore[override] + self, + method: str, + url: UriType, + withhold_token: bool = False, + auth: AuthType = None, + *, + params: ParamsType = None, + data: DataType = None, + headers: HeadersType = None, + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, + files: FilesType = None, + timeout: TimeoutType = None, + allow_redirects: bool = True, + proxies: dict[str, str] | None = None, + hooks: HooksInputType | None = None, + stream: bool | None = None, + verify: VerifyType | None = None, + cert: CertType = None, + json: JsonType = None, + ) -> Response: ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/utils.pyi b/stubs/Authlib/authlib/integrations/requests_client/utils.pyi new file mode 100644 index 000000000000..f93f9a06f07b --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/utils.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete +from typing import Final + +REQUESTS_SESSION_KWARGS: Final = ["proxies", "hooks", "stream", "verify", "cert", "max_redirects", "trust_env"] + +def update_session_configure(session, kwargs: dict[str, Incomplete]) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi new file mode 100644 index 000000000000..364a0a9fb2eb --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi @@ -0,0 +1,20 @@ +from .client_mixin import OAuth2ClientMixin as OAuth2ClientMixin +from .functions import ( + create_bearer_token_validator as create_bearer_token_validator, + create_query_client_func as create_query_client_func, + create_query_token_func as create_query_token_func, + create_revocation_endpoint as create_revocation_endpoint, + create_save_token_func as create_save_token_func, +) +from .tokens_mixins import OAuth2AuthorizationCodeMixin as OAuth2AuthorizationCodeMixin, OAuth2TokenMixin as OAuth2TokenMixin + +__all__ = [ + "OAuth2ClientMixin", + "OAuth2AuthorizationCodeMixin", + "OAuth2TokenMixin", + "create_query_client_func", + "create_save_token_func", + "create_query_token_func", + "create_revocation_endpoint", + "create_bearer_token_validator", +] diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi new file mode 100644 index 000000000000..94606b7d19e5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6749 import ClientMixin + +class OAuth2ClientMixin(ClientMixin): + client_id: Incomplete + client_secret: Incomplete + client_id_issued_at: Incomplete + client_secret_expires_at: Incomplete + _client_metadata: Incomplete + @property + def client_info(self) -> dict[str, Incomplete]: ... + @property + def client_metadata(self): ... + def set_client_metadata(self, value) -> None: ... + @property + def redirect_uris(self): ... + @property + def token_endpoint_auth_method(self): ... + @property + def grant_types(self): ... + @property + def response_types(self): ... + @property + def client_name(self): ... + @property + def client_uri(self): ... + @property + def logo_uri(self): ... + @property + def scope(self): ... + @property + def contacts(self): ... + @property + def tos_uri(self): ... + @property + def policy_uri(self): ... + @property + def jwks_uri(self): ... + @property + def jwks(self): ... + @property + def software_id(self): ... + @property + def software_version(self): ... + @property + def id_token_signed_response_alg(self): ... + def get_client_id(self): ... + def get_default_redirect_uri(self): ... + def get_allowed_scope(self, scope) -> str: ... + def check_redirect_uri(self, redirect_uri) -> bool: ... + def check_client_secret(self, client_secret) -> bool: ... + def check_endpoint_auth_method(self, method, endpoint) -> bool: ... + def check_response_type(self, response_type) -> bool: ... + def check_grant_type(self, grant_type) -> bool: ... diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi new file mode 100644 index 000000000000..0590b36eda08 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import type_check_only + +from authlib.oauth2.rfc6750 import BearerTokenValidator +from authlib.oauth2.rfc7009 import RevocationEndpoint + +@type_check_only +class _RevocationEndpoint(RevocationEndpoint): + def query_token(self, token, token_type_hint): ... + def revoke_token(self, token, request) -> None: ... + +@type_check_only +class _BearerTokenValidator(BearerTokenValidator): + def authenticate_token(self, token_string): ... + +def create_query_client_func(session, client_model) -> Callable[[Incomplete], Incomplete]: ... +def create_save_token_func(session, token_model) -> Callable[[Incomplete, Incomplete], None]: ... +def create_query_token_func(session, token_model) -> Callable[[Incomplete, Incomplete], Incomplete]: ... +def create_revocation_endpoint(session, token_model) -> type[_RevocationEndpoint]: ... +def create_bearer_token_validator(session, token_model) -> type[_BearerTokenValidator]: ... diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi new file mode 100644 index 000000000000..25166d5f0f4c --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6749 import AuthorizationCodeMixin, TokenMixin + +class OAuth2AuthorizationCodeMixin(AuthorizationCodeMixin): + code: Incomplete + client_id: Incomplete + redirect_uri: Incomplete + response_type: Incomplete + scope: Incomplete + nonce: Incomplete + auth_time: Incomplete + acr: Incomplete + amr: Incomplete + code_challenge: Incomplete + code_challenge_method: Incomplete + def is_expired(self) -> bool: ... + def get_redirect_uri(self): ... + def get_scope(self): ... + def get_auth_time(self): ... + def get_acr(self): ... + def get_amr(self): ... + def get_nonce(self): ... + +class OAuth2TokenMixin(TokenMixin): + client_id: Incomplete + token_type: Incomplete + access_token: Incomplete + refresh_token: Incomplete + scope: Incomplete + issued_at: Incomplete + access_token_revoked_at: Incomplete + refresh_token_revoked_at: Incomplete + expires_in: Incomplete + def check_client(self, client) -> bool: ... + def get_scope(self): ... + def get_expires_in(self): ... + def is_revoked(self): ... + def is_expired(self) -> bool: ... diff --git a/stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi b/stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi new file mode 100644 index 000000000000..ea654f6f55bd --- /dev/null +++ b/stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from ..base_client import BaseOAuth, OAuthError as OAuthError +from .apps import StarletteOAuth1App as StarletteOAuth1App, StarletteOAuth2App as StarletteOAuth2App +from .integration import StarletteIntegration as StarletteIntegration + +class OAuth(BaseOAuth): + oauth1_client_cls = StarletteOAuth1App + oauth2_client_cls = StarletteOAuth2App + framework_integration_cls = StarletteIntegration + config: Incomplete + def __init__(self, config=None, cache=None, fetch_token=None, update_token=None) -> None: ... + +__all__ = ["OAuth", "OAuthError", "StarletteIntegration", "StarletteOAuth1App", "StarletteOAuth2App"] diff --git a/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi b/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi new file mode 100644 index 000000000000..47b6267c4430 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +from ..base_client import BaseApp +from ..base_client.async_app import AsyncOAuth1Mixin, AsyncOAuth2Mixin +from ..base_client.async_openid import AsyncOpenIDMixin +from ..httpx_client import AsyncOAuth1Client, AsyncOAuth2Client + +_RedirectResponse: TypeAlias = Incomplete # actual type is starlette.responses.RedirectResponse + +class StarletteAppMixin: + async def save_authorize_data(self, request, **kwargs) -> None: ... + async def authorize_redirect(self, request, redirect_uri=None, **kwargs) -> _RedirectResponse: ... + +class StarletteOAuth1App(StarletteAppMixin, AsyncOAuth1Mixin, BaseApp): + client_cls = AsyncOAuth1Client + async def authorize_access_token(self, request, **kwargs): ... + +class StarletteOAuth2App(StarletteAppMixin, AsyncOAuth2Mixin, AsyncOpenIDMixin, BaseApp): + client_cls = AsyncOAuth2Client + async def logout_redirect( + self, + request, + post_logout_redirect_uri=None, + id_token_hint=None, + *, + state=None, + client_id=None, + logout_hint=None, + ui_locales=None, + ) -> _RedirectResponse: ... + async def validate_logout_response(self, request): ... + async def authorize_access_token(self, request, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/starlette_client/integration.pyi b/stubs/Authlib/authlib/integrations/starlette_client/integration.pyi new file mode 100644 index 000000000000..6848c50141ee --- /dev/null +++ b/stubs/Authlib/authlib/integrations/starlette_client/integration.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from typing import Any + +from ..base_client import FrameworkIntegration + +class StarletteIntegration(FrameworkIntegration): + # annotated by source code + async def get_state_data(self, session: dict[str, Any] | None, state: str) -> dict[str, Any]: ... + async def set_state_data(self, session: dict[str, Any] | None, state: str, data: Any) -> None: ... + async def clear_state_data(self, session: dict[str, Any] | None, state: str) -> None: ... + def update_token(self, token, refresh_token=None, access_token=None) -> None: ... + @staticmethod + def load_config(oauth, name, params) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/jose/__init__.pyi b/stubs/Authlib/authlib/jose/__init__.pyi new file mode 100644 index 000000000000..3377c3dbdef7 --- /dev/null +++ b/stubs/Authlib/authlib/jose/__init__.pyi @@ -0,0 +1,42 @@ +from .errors import JoseError as JoseError +from .rfc7515 import ( + JsonWebSignature as JsonWebSignature, + JWSAlgorithm as JWSAlgorithm, + JWSHeader as JWSHeader, + JWSObject as JWSObject, +) +from .rfc7516 import ( + JsonWebEncryption as JsonWebEncryption, + JWEAlgorithm as JWEAlgorithm, + JWEEncAlgorithm as JWEEncAlgorithm, + JWEZipAlgorithm as JWEZipAlgorithm, +) +from .rfc7517 import JsonWebKey as JsonWebKey, Key as Key, KeySet as KeySet +from .rfc7518 import ECKey as ECKey, OctKey as OctKey, RSAKey as RSAKey +from .rfc7519 import BaseClaims as BaseClaims, JsonWebToken as JsonWebToken, JWTClaims as JWTClaims +from .rfc8037 import OKPKey as OKPKey + +jwt: JsonWebToken + +__all__ = [ + "JoseError", + "JsonWebSignature", + "JWSAlgorithm", + "JWSHeader", + "JWSObject", + "JsonWebEncryption", + "JWEAlgorithm", + "JWEEncAlgorithm", + "JWEZipAlgorithm", + "JsonWebKey", + "Key", + "KeySet", + "OctKey", + "RSAKey", + "ECKey", + "OKPKey", + "JsonWebToken", + "BaseClaims", + "JWTClaims", + "jwt", +] diff --git a/stubs/Authlib/authlib/jose/drafts/__init__.pyi b/stubs/Authlib/authlib/jose/drafts/__init__.pyi new file mode 100644 index 000000000000..05af39634dfd --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/__init__.pyi @@ -0,0 +1,3 @@ +__all__ = ["register_jwe_draft"] + +def register_jwe_draft(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi b/stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi new file mode 100644 index 000000000000..8e6b423d1bcb --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final + +from authlib.jose.rfc7516 import JWEAlgorithmWithTagAwareKeyAgreement +from authlib.jose.rfc7518 import AESAlgorithm, ECKey +from authlib.jose.rfc8037 import OKPKey + +class ECDH1PUAlgorithm(JWEAlgorithmWithTagAwareKeyAgreement): + EXTRA_HEADERS: ClassVar[Iterable[str]] + ALLOWED_KEY_CLS: tuple[type, ...] + name: str + description: str + key_size: Incomplete + aeskw: AESAlgorithm + def __init__(self, key_size=None) -> None: ... + def prepare_key(self, raw_data) -> ECKey | OKPKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def compute_shared_key(self, shared_key_e, shared_key_s): ... + def compute_fixed_info(self, headers, bit_size, tag) -> bytes: ... + def compute_derived_key(self, shared_key, fixed_info, bit_size) -> bytes: ... + def deliver_at_sender(self, sender_static_key, sender_ephemeral_key, recipient_pubkey, headers, bit_size, tag) -> bytes: ... + def deliver_at_recipient( + self, recipient_key, sender_static_pubkey, sender_ephemeral_pubkey, headers, bit_size, tag + ) -> bytes: ... + def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None) -> dict[str, Incomplete]: ... + def agree_upon_key_and_wrap_cek(self, enc_alg, headers, key, sender_key, epk, cek, tag) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, sender_key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None) -> bytes: ... + +JWE_DRAFT_ALG_ALGORITHMS: Final[list[ECDH1PUAlgorithm]] + +def register_jwe_alg_draft(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi new file mode 100644 index 000000000000..594739d28a22 --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from authlib.jose.rfc7516 import JWEEncAlgorithm + +class XC20PEncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: Incomplete + CEK_SIZE: Incomplete + def __init__(self, key_size) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... diff --git a/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi new file mode 100644 index 000000000000..ab85a51a5233 --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from authlib.jose.rfc7516 import JWEEncAlgorithm + +class C20PEncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: Incomplete + CEK_SIZE: Incomplete + def __init__(self, key_size) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... diff --git a/stubs/Authlib/authlib/jose/errors.pyi b/stubs/Authlib/authlib/jose/errors.pyi new file mode 100644 index 000000000000..29c29a3a9861 --- /dev/null +++ b/stubs/Authlib/authlib/jose/errors.pyi @@ -0,0 +1,76 @@ +from _typeshed import Incomplete + +from authlib.common.errors import AuthlibBaseError + +class JoseError(AuthlibBaseError): ... + +class DecodeError(JoseError): + error: str + +class MissingAlgorithmError(JoseError): + error: str + +class UnsupportedAlgorithmError(JoseError): + error: str + +class BadSignatureError(JoseError): + error: str + result: Incomplete + def __init__(self, result) -> None: ... + +class InvalidHeaderParameterNameError(JoseError): + error: str + def __init__(self, name) -> None: ... + +class InvalidCritHeaderParameterNameError(JoseError): + error: str + def __init__(self, name: str) -> None: ... + +class InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError(JoseError): + error: str + def __init__(self) -> None: ... + +class InvalidAlgorithmForMultipleRecipientsMode(JoseError): + error: str + def __init__(self, alg) -> None: ... + +class KeyMismatchError(JoseError): + error: str + description: str + +class MissingEncryptionAlgorithmError(JoseError): + error: str + description: str + +class UnsupportedEncryptionAlgorithmError(JoseError): + error: str + description: str + +class UnsupportedCompressionAlgorithmError(JoseError): + error: str + description: str + +class InvalidUseError(JoseError): + error: str + description: str + +class InvalidClaimError(JoseError): + error: str + claim_name: Incomplete + def __init__(self, claim) -> None: ... + +class MissingClaimError(JoseError): + error: str + def __init__(self, claim) -> None: ... + +class InsecureClaimError(JoseError): + error: str + def __init__(self, claim) -> None: ... + +class ExpiredTokenError(JoseError): + error: str + description: str + +class InvalidTokenError(JoseError): + error: str + description: str diff --git a/stubs/Authlib/authlib/jose/jwk.pyi b/stubs/Authlib/authlib/jose/jwk.pyi new file mode 100644 index 000000000000..4a90a1bd2e31 --- /dev/null +++ b/stubs/Authlib/authlib/jose/jwk.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +@deprecated("Please use `JsonWebKey` directly.") +def loads(obj, kid=None): ... +@deprecated("Please use `JsonWebKey` directly.") +def dumps(key, kty=None, **params) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/jose/rfc7515/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7515/__init__.pyi new file mode 100644 index 000000000000..cac2e167f330 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7515/__init__.pyi @@ -0,0 +1,4 @@ +from .jws import JsonWebSignature as JsonWebSignature +from .models import JWSAlgorithm as JWSAlgorithm, JWSHeader as JWSHeader, JWSObject as JWSObject + +__all__ = ["JsonWebSignature", "JWSAlgorithm", "JWSHeader", "JWSObject"] diff --git a/stubs/Authlib/authlib/jose/rfc7515/jws.pyi b/stubs/Authlib/authlib/jose/rfc7515/jws.pyi new file mode 100644 index 000000000000..0de9cb372359 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7515/jws.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from typing import SupportsBytes, SupportsIndex + +from .models import JWSAlgorithm, JWSObject + +class JsonWebSignature: + REGISTERED_HEADER_PARAMETER_NAMES: frozenset[str] + MAX_CONTENT_LENGTH: int + ALGORITHMS_REGISTRY: dict[str, JWSAlgorithm] + def __init__(self, algorithms=None, private_headers=None) -> None: ... + @classmethod + def register_algorithm(cls, algorithm: JWSAlgorithm) -> None: ... + def serialize_compact(self, protected, payload, key) -> bytes: ... + def deserialize_compact( + self, s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, key, decode=None + ) -> JWSObject: ... + def serialize_json(self, header_obj, payload, key) -> dict[str, Incomplete]: ... + def deserialize_json(self, obj, key, decode=None) -> JWSObject: ... + def serialize(self, header, payload, key) -> dict[str, Incomplete] | bytes: ... + def deserialize(self, s, key, decode=None) -> JWSObject: ... diff --git a/stubs/Authlib/authlib/jose/rfc7515/models.pyi b/stubs/Authlib/authlib/jose/rfc7515/models.pyi new file mode 100644 index 000000000000..77663de68e55 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7515/models.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +class JWSAlgorithm: + name: str | None + description: str | None + deprecated: bool + algorithm_type: str + algorithm_location: str + def prepare_key(self, raw_data): ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +class JWSHeader(dict[str, object]): + protected: Incomplete + header: Incomplete + def __init__(self, protected, header) -> None: ... + @classmethod + def from_dict(cls, obj) -> Self: ... + +class JWSObject(dict[str, object]): + header: Incomplete + payload: Incomplete + type: str + def __init__(self, header, payload, type: str = "compact") -> None: ... + @property + def headers(self): ... diff --git a/stubs/Authlib/authlib/jose/rfc7516/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7516/__init__.pyi new file mode 100644 index 000000000000..84393afbd11b --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7516/__init__.pyi @@ -0,0 +1,9 @@ +from .jwe import JsonWebEncryption as JsonWebEncryption +from .models import ( + JWEAlgorithm as JWEAlgorithm, + JWEAlgorithmWithTagAwareKeyAgreement as JWEAlgorithmWithTagAwareKeyAgreement, + JWEEncAlgorithm as JWEEncAlgorithm, + JWEZipAlgorithm as JWEZipAlgorithm, +) + +__all__ = ["JsonWebEncryption", "JWEAlgorithm", "JWEAlgorithmWithTagAwareKeyAgreement", "JWEEncAlgorithm", "JWEZipAlgorithm"] diff --git a/stubs/Authlib/authlib/jose/rfc7516/jwe.pyi b/stubs/Authlib/authlib/jose/rfc7516/jwe.pyi new file mode 100644 index 000000000000..c0783698a279 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7516/jwe.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections import OrderedDict +from collections.abc import Iterable +from typing import SupportsBytes, SupportsIndex + +from .models import JWEAlgorithmBase, JWEEncAlgorithm, JWEZipAlgorithm + +class JsonWebEncryption: + REGISTERED_HEADER_PARAMETER_NAMES: frozenset[str] + ALG_REGISTRY: dict[str, JWEAlgorithmBase] + ENC_REGISTRY: dict[str, JWEEncAlgorithm] + ZIP_REGISTRY: dict[str, JWEZipAlgorithm] + def __init__(self, algorithms=None, private_headers=None) -> None: ... + @classmethod + def register_algorithm(cls, algorithm: JWEAlgorithmBase | JWEEncAlgorithm | JWEZipAlgorithm) -> None: ... + def serialize_compact(self, protected, payload, key, sender_key=None) -> bytes: ... + def serialize_json(self, header_obj, payload, keys, sender_key=None) -> OrderedDict[Incomplete, Incomplete]: ... + def serialize(self, header, payload, key, sender_key=None) -> OrderedDict[Incomplete, Incomplete] | bytes: ... + def deserialize_compact( + self, + s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + key, + decode=None, + sender_key=None, + ) -> dict[str, Incomplete]: ... + def deserialize_json(self, obj, key, decode=None, sender_key=None) -> dict[str, Incomplete]: ... + def deserialize(self, obj, key, decode=None, sender_key=None) -> dict[str, Incomplete]: ... + @staticmethod + def parse_json(obj) -> dict[Incomplete, Incomplete]: ... + def get_header_alg(self, header) -> JWEAlgorithmBase: ... + def get_header_enc(self, header) -> JWEEncAlgorithm: ... + def get_header_zip(self, header) -> JWEZipAlgorithm: ... + +def prepare_key(alg, header, key): ... diff --git a/stubs/Authlib/authlib/jose/rfc7516/models.pyi b/stubs/Authlib/authlib/jose/rfc7516/models.pyi new file mode 100644 index 000000000000..e40d84bf486d --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7516/models.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from abc import ABCMeta +from collections.abc import Iterable, Sized +from typing import ClassVar +from typing_extensions import Self + +class JWEAlgorithmBase(metaclass=ABCMeta): + EXTRA_HEADERS: ClassVar[Iterable[str] | None] + name: str | None + description: str | None + deprecated: bool + algorithm_type: str + algorithm_location: str + def prepare_key(self, raw_data): ... + def generate_preset(self, enc_alg, key): ... + +class JWEAlgorithm(JWEAlgorithmBase, metaclass=ABCMeta): + def wrap(self, enc_alg, headers, key, preset=None): ... + def unwrap(self, enc_alg, ek, headers, key): ... + +class JWEAlgorithmWithTagAwareKeyAgreement(JWEAlgorithmBase, metaclass=ABCMeta): + def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None): ... + def agree_upon_key_and_wrap_cek(self, enc_alg, headers, key, sender_key, epk, cek, tag): ... + def wrap(self, enc_alg, headers, key, sender_key, preset=None): ... + def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None): ... + +class JWEEncAlgorithm: + name: str | None + description: str | None + algorithm_type: str + algorithm_location: str + IV_SIZE: int | None + CEK_SIZE: int | None + def generate_cek(self) -> bytes: ... + def generate_iv(self) -> bytes: ... + def check_iv(self, iv: Sized) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... + +class JWEZipAlgorithm: + name: Incomplete + description: Incomplete + algorithm_type: str + algorithm_location: str + def compress(self, s: bytes) -> bytes | None: ... + def decompress(self, s: bytes) -> bytes | None: ... + +class JWESharedHeader(dict[str, object]): + protected: Incomplete + unprotected: Incomplete + def __init__(self, protected, unprotected) -> None: ... + def update_protected(self, addition) -> None: ... + @classmethod + def from_dict(cls, obj) -> Self: ... + +class JWEHeader(dict[str, object]): + protected: Incomplete + unprotected: Incomplete + header: Incomplete + def __init__(self, protected, unprotected, header) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7517/__init__.pyi new file mode 100644 index 000000000000..7a5ebe6a8eac --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/__init__.pyi @@ -0,0 +1,7 @@ +from ._cryptography_key import load_pem_key as load_pem_key +from .asymmetric_key import AsymmetricKey as AsymmetricKey +from .base_key import Key as Key +from .jwk import JsonWebKey as JsonWebKey +from .key_set import KeySet as KeySet + +__all__ = ["Key", "AsymmetricKey", "KeySet", "JsonWebKey", "load_pem_key"] diff --git a/stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi b/stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi new file mode 100644 index 000000000000..86a5476b8963 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi @@ -0,0 +1,35 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Literal, SupportsBytes, SupportsIndex, overload + +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes +from cryptography.hazmat.primitives.serialization.ssh import SSHPublicKeyTypes + +@overload # if ssh_type is None +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: None = None, + key_type: str | None = None, + password: bytes | None = None, +) -> PublicKeyTypes | PrivateKeyTypes: ... +@overload # if key_type == "public" +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: ReadableBuffer | tuple[ReadableBuffer, ...] | None = None, + key_type: Literal["public"] = ..., + password: bytes | None = None, +) -> PublicKeyTypes: ... +@overload # if key_type is not empty, but not "public" +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: ReadableBuffer | tuple[ReadableBuffer, ...] | None = None, + key_type: str = ..., + password: bytes | None = None, +) -> PrivateKeyTypes: ... +@overload # if ssh_type is not empty +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: ReadableBuffer | tuple[ReadableBuffer, ...] = ..., + key_type: str | None = None, + password: bytes | None = None, +) -> SSHPublicKeyTypes | PublicKeyTypes | PrivateKeyTypes: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi b/stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi new file mode 100644 index 000000000000..1361ba23ac48 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from typing import ClassVar, Literal, SupportsBytes, SupportsIndex +from typing_extensions import Self + +from authlib.jose.rfc7517 import Key + +class AsymmetricKey(Key): + PUBLIC_KEY_FIELDS: ClassVar[list[str]] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + PRIVATE_KEY_CLS: ClassVar[type | tuple[type, ...]] + PUBLIC_KEY_CLS: ClassVar[type | tuple[type, ...]] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + private_key: Incomplete + public_key: Incomplete + def __init__(self, private_key=None, public_key=None, options=None) -> None: ... + @property + def public_only(self) -> bool: ... + def get_op_key(self, operation): ... + def get_public_key(self): ... + def get_private_key(self): ... + def load_raw_key(self) -> None: ... + def load_dict_key(self) -> None: ... + def dumps_private_key(self): ... + def dumps_public_key(self): ... + def load_private_key(self): ... + def load_public_key(self): ... + def as_dict(self, is_private: bool = False, **params) -> dict[Incomplete, Incomplete]: ... + def as_key(self, is_private: bool = False): ... + def as_bytes( + self, + encoding: Literal["PEM", "DER"] | None = None, + is_private: bool = False, + password: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + ): ... + def as_pem( + self, + is_private: bool = False, + password: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + ): ... + def as_der( + self, + is_private: bool = False, + password: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + ): ... + @classmethod + def import_dict_key(cls, raw, options=None) -> Self: ... + @classmethod + def import_key(cls, raw, options=None) -> Self: ... + @classmethod + def validate_raw_key(cls, key) -> bool: ... + @classmethod + def generate_key(cls, crv_or_size, options=None, is_private: bool = False) -> AsymmetricKey: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/base_key.pyi b/stubs/Authlib/authlib/jose/rfc7517/base_key.pyi new file mode 100644 index 000000000000..0614eacf2a48 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/base_key.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from typing import ClassVar + +class Key: + kty: str + ALLOWED_PARAMS: ClassVar[list[str]] + PRIVATE_KEY_OPS: ClassVar[list[str]] + PUBLIC_KEY_OPS: ClassVar[list[str]] + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + options: dict[Incomplete, Incomplete] + def __init__(self, options=None) -> None: ... + @property + def tokens(self) -> dict[Incomplete, Incomplete]: ... + @property + def kid(self): ... + def keys(self): ... + def __getitem__(self, item): ... + @property + def public_only(self): ... + def load_raw_key(self): ... + def load_dict_key(self): ... + def check_key_op(self, operation) -> None: ... + def as_dict(self, is_private: bool = False, **params): ... + def as_json(self, is_private: bool = False, **params) -> str: ... + def thumbprint(self) -> str: ... + @classmethod + def check_required_fields(cls, data) -> None: ... + @classmethod + def validate_raw_key(cls, key): ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/jwk.pyi b/stubs/Authlib/authlib/jose/rfc7517/jwk.pyi new file mode 100644 index 000000000000..97ca89d0c872 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/jwk.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Collection, Iterable, Mapping +from typing import SupportsBytes, SupportsIndex + +from authlib.jose.rfc7517 import Key, KeySet + +class JsonWebKey: + JWK_KEY_CLS: dict[Incomplete, Incomplete] + @classmethod + def generate_key(cls, kty, crv_or_size, options=None, is_private: bool = False): ... + @classmethod + def import_key( + cls, + raw: ( + str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | Mapping[str, object] + ), + options: Mapping[str, object] | None = None, + ) -> Key: ... + @classmethod + def import_key_set(cls, raw: str | Collection[str] | dict[str, object]) -> KeySet: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/key_set.pyi b/stubs/Authlib/authlib/jose/rfc7517/key_set.pyi new file mode 100644 index 000000000000..b1538b72401d --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/key_set.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Collection + +from authlib.jose.rfc7517 import Key + +class KeySet: + keys: Collection[Key] + def __init__(self, keys) -> None: ... + def as_dict(self, is_private: bool = False, **params) -> dict[str, list[Incomplete]]: ... + def as_json(self, is_private: bool = False, **params) -> str: ... + def find_by_kid(self, kid, **params): ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7518/__init__.pyi new file mode 100644 index 000000000000..362234a1bdd7 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/__init__.pyi @@ -0,0 +1,20 @@ +from .ec_key import ECKey as ECKey +from .jwe_algs import AESAlgorithm as AESAlgorithm, ECDHESAlgorithm as ECDHESAlgorithm, u32be_len_input as u32be_len_input +from .jwe_encs import CBCHS2EncAlgorithm as CBCHS2EncAlgorithm +from .oct_key import OctKey as OctKey +from .rsa_key import RSAKey as RSAKey + +__all__ = [ + "register_jws_rfc7518", + "register_jwe_rfc7518", + "OctKey", + "RSAKey", + "ECKey", + "u32be_len_input", + "AESAlgorithm", + "ECDHESAlgorithm", + "CBCHS2EncAlgorithm", +] + +def register_jws_rfc7518(cls) -> None: ... +def register_jwe_rfc7518(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi b/stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi new file mode 100644 index 000000000000..ba5f1fd456e6 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi @@ -0,0 +1,24 @@ +from typing import ClassVar + +from authlib.jose.rfc7517 import AsymmetricKey +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey + +class ECKey(AsymmetricKey): + kty: str + DSS_CURVES: dict[str, type] + CURVES_DSS: dict[property, str] + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS # pyrefly: ignore [unknown-name] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_CLS: ClassVar[type] + PRIVATE_KEY_CLS: ClassVar[type] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + def exchange_shared_key(self, pubkey): ... + @property + def curve_key_size(self): ... + def load_private_key(self) -> EllipticCurvePrivateKey: ... + def load_public_key(self) -> EllipticCurvePublicKey: ... + def dumps_private_key(self) -> dict[str, str]: ... + def dumps_public_key(self) -> dict[str, str]: ... + @classmethod + def generate_key(cls, crv: str = "P-256", options=None, is_private: bool = False) -> ECKey: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi b/stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi new file mode 100644 index 000000000000..df9802481aa8 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from typing import ClassVar, Final, SupportsBytes, SupportsIndex + +from authlib.jose.rfc7516 import JWEAlgorithm + +from .ec_key import ECKey +from .oct_key import OctKey +from .rsa_key import RSAKey + +class DirectAlgorithm(JWEAlgorithm): + name: str + description: str + def prepare_key(self, raw_data) -> OctKey: ... + def generate_preset(self, enc_alg, key) -> dict[Incomplete, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key): ... + +class RSAAlgorithm(JWEAlgorithm): + key_size: int + name: str + deprecated: bool + description: str + padding: Incomplete + def __init__(self, name: str, description: str, pad_fn) -> None: ... + def prepare_key(self, raw_data) -> RSAKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key): ... + +class AESAlgorithm(JWEAlgorithm): + name: str + description: str + key_size: int + def __init__(self, key_size: int) -> None: ... + def prepare_key(self, raw_data) -> OctKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def wrap_cek(self, cek, key) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key) -> bytes: ... + +class AESGCMAlgorithm(JWEAlgorithm): + EXTRA_HEADERS: ClassVar[Iterable[str]] + name: str + description: str + key_size: int + def __init__(self, key_size: int) -> None: ... + def prepare_key(self, raw_data) -> OctKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key) -> bytes: ... + +class ECDHESAlgorithm(JWEAlgorithm): + EXTRA_HEADERS: ClassVar[Iterable[str]] + ALLOWED_KEY_CLS = Incomplete + name: str + description: str + key_size: int | None + aeskw: AESAlgorithm + def __init__(self, key_size: int | None = None) -> None: ... + def prepare_key(self, raw_data) -> ECKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def compute_fixed_info(self, headers, bit_size) -> bytes: ... + def compute_derived_key(self, shared_key, fixed_info, bit_size) -> bytes: ... + def deliver(self, key, pubkey, headers, bit_size) -> bytes: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key) -> bytes: ... + +def u32be_len_input( + s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, base64: bool = False +) -> bytes: ... + +JWE_ALG_ALGORITHMS: Final[list[JWEAlgorithm]] diff --git a/stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi b/stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi new file mode 100644 index 000000000000..4fd43557af0f --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import Final + +from authlib.jose.rfc7516 import JWEEncAlgorithm + +class CBCHS2EncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: int + key_len: int + CEK_SIZE: int + hash_alg: Incomplete + def __init__(self, key_size: int, hash_type: int | str) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... + +class GCMEncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: int + CEK_SIZE: int + def __init__(self, key_size: int) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... + +JWE_ENC_ALGORITHMS: Final[list[CBCHS2EncAlgorithm | GCMEncAlgorithm]] diff --git a/stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi b/stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi new file mode 100644 index 000000000000..4bb30cd63311 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi @@ -0,0 +1,14 @@ +from typing import Final + +from authlib.jose.rfc7516 import JWEZipAlgorithm + +GZIP_HEAD: Final[bytes] +MAX_SIZE: Final = 256000 + +class DeflateZipAlgorithm(JWEZipAlgorithm): + name: str + description: str + def compress(self, s: bytes) -> bytes: ... + def decompress(self, s: bytes) -> bytes: ... + +def register_jwe_rfc7518() -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi b/stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi new file mode 100644 index 000000000000..0a7af53cdecb --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi @@ -0,0 +1,70 @@ +import hashlib +from _typeshed import Incomplete + +from authlib.jose.rfc7515 import JWSAlgorithm +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 + +from .ec_key import ECKey +from .oct_key import OctKey +from .rsa_key import RSAKey + +class NoneAlgorithm(JWSAlgorithm): + name: str + description: str + deprecated: bool + def prepare_key(self, raw_data) -> None: ... + def sign(self, msg, key) -> bytes: ... + def verify(self, msg, sig, key) -> bool: ... + +class HMACAlgorithm(JWSAlgorithm): + SHA256 = hashlib.sha256 + SHA384 = hashlib.sha384 + SHA512 = hashlib.sha512 + name: str + description: str + hash_alg: Incomplete + def __init__(self, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> OctKey: ... + def sign(self, msg, key) -> bytes: ... + def verify(self, msg, sig, key) -> bool: ... + +class RSAAlgorithm(JWSAlgorithm): + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + name: str + description: str + hash_alg: Incomplete + padding: PKCS1v15 + def __init__(self, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> RSAKey: ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +class ECAlgorithm(JWSAlgorithm): + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + name: str + curve: Incomplete + description: str + hash_alg: Incomplete + def __init__(self, name: str, curve, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> ECKey: ... + def sign(self, msg, key) -> bytes: ... + def verify(self, msg, sig, key) -> bool: ... + +class RSAPSSAlgorithm(JWSAlgorithm): + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + name: str + description: str + hash_alg: Incomplete + def __init__(self, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> RSAKey: ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +JWS_ALGORITHMS: list[JWSAlgorithm] diff --git a/stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi b/stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi new file mode 100644 index 000000000000..d4fad5a6571c --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from typing import ClassVar, Final +from typing_extensions import Self + +from authlib.jose.rfc7517 import Key + +POSSIBLE_UNSAFE_KEYS: Final[tuple[bytes, ...]] + +class OctKey(Key): + kty: str + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + raw_key: Incomplete + def __init__(self, raw_key=None, options=None) -> None: ... + @property + def public_only(self) -> bool: ... + def get_op_key(self, operation): ... + def load_raw_key(self) -> None: ... + def load_dict_key(self) -> None: ... + def as_dict(self, is_private: bool = False, **params) -> dict[Incomplete, Incomplete]: ... + @classmethod + def validate_raw_key(cls, key) -> bool: ... + @classmethod + def import_key(cls, raw, options=None) -> Self: ... + @classmethod + def generate_key(cls, key_size: int = 256, options=None, is_private: bool = True) -> Self: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi b/stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi new file mode 100644 index 000000000000..0a15f339f6f7 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from typing import ClassVar +from typing_extensions import Self + +from authlib.jose.rfc7517 import AsymmetricKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey + +class RSAKey(AsymmetricKey): + kty: str + PUBLIC_KEY_CLS: ClassVar[type] + PRIVATE_KEY_CLS: ClassVar[type] + PUBLIC_KEY_FIELDS: ClassVar[list[str]] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + def dumps_private_key(self) -> dict[str, str]: ... + def dumps_public_key(self) -> dict[str, str]: ... + def load_private_key(self) -> RSAPrivateKey: ... + def load_public_key(self) -> RSAPublicKey: ... + @classmethod + def generate_key(cls, key_size: int = 2048, options=None, is_private: bool = False) -> RSAKey: ... + @classmethod + def import_dict_key(cls, raw, options=None) -> Self: ... + +def has_all_prime_factors(obj: Iterable[str]) -> bool: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/util.pyi b/stubs/Authlib/authlib/jose/rfc7518/util.pyi new file mode 100644 index 000000000000..1edc796a9716 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/util.pyi @@ -0,0 +1,4 @@ +from _typeshed import ReadableBuffer + +def encode_int(num, bits) -> bytes: ... +def decode_int(b: ReadableBuffer) -> int: ... diff --git a/stubs/Authlib/authlib/jose/rfc7519/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7519/__init__.pyi new file mode 100644 index 000000000000..bb053f7d5142 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7519/__init__.pyi @@ -0,0 +1,4 @@ +from .claims import BaseClaims as BaseClaims, JWTClaims as JWTClaims +from .jwt import JsonWebToken as JsonWebToken + +__all__ = ["JsonWebToken", "BaseClaims", "JWTClaims"] diff --git a/stubs/Authlib/authlib/jose/rfc7519/claims.pyi b/stubs/Authlib/authlib/jose/rfc7519/claims.pyi new file mode 100644 index 000000000000..55ec2dbf9a73 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7519/claims.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Any, ClassVar + +class BaseClaims(dict[str, Any]): # dict values are key-dependent + REGISTERED_CLAIMS: ClassVar[list[str]] + header: Incomplete + options: Incomplete + params: Incomplete + def __init__(self, payload, header, options=None, params=None) -> None: ... + # TODO: Adds an attribute for each key in REGISTERED_CLAIMS + def __getattr__(self, key: str): ... + def get_registered_claims(self) -> dict[str, Incomplete]: ... + +class JWTClaims(BaseClaims): + def validate(self, now: int | None = None, leeway: int = 0) -> None: ... + def validate_iss(self) -> None: ... + def validate_sub(self) -> None: ... + def validate_aud(self) -> None: ... + def validate_exp(self, now: int, leeway: int) -> None: ... + def validate_nbf(self, now: int, leeway: int) -> None: ... + def validate_iat(self, now: int, leeway: int) -> None: ... + def validate_jti(self) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7519/jwt.pyi b/stubs/Authlib/authlib/jose/rfc7519/jwt.pyi new file mode 100644 index 000000000000..b6785ca8f084 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7519/jwt.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from re import Pattern +from typing import Any, Final, Generic, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +from ..rfc7517 import KeySet +from .claims import JWTClaims + +_T = TypeVar("_T") + +_LoadKey: TypeAlias = Callable[[Incomplete, Incomplete], Incomplete] + +class JsonWebToken: + SENSITIVE_NAMES: Final[tuple[str, ...]] + SENSITIVE_VALUES: Final[Pattern[str]] + + def __init__(self, algorithms, private_headers=None) -> None: ... + def check_sensitive_data(self, payload) -> None: ... + def encode(self, header, payload, key, check: bool = True) -> bytes: ... + + @overload + def decode( + self, + s: str | bytes, + key: _LoadKey | KeySet | tuple[Incomplete, ...] | list[Incomplete] | str, + claims_cls: None = None, + claims_options=None, + claims_params=None, + ) -> JWTClaims: ... + @overload + def decode( + self, + s: str | bytes, + key: _LoadKey | KeySet | tuple[Incomplete, ...] | list[Incomplete] | str, + claims_cls: type[_T], + claims_options=None, + claims_params=None, + ) -> _T: ... + +def decode_payload(bytes_payload) -> dict[Incomplete, Incomplete]: ... + +_TL = TypeVar("_TL", bound=tuple[Any, ...] | list[Any]) + +@type_check_only +class _Keys(TypedDict, Generic[_TL]): + keys: _TL + +@overload +def prepare_raw_key(raw: KeySet) -> KeySet: ... +@overload +def prepare_raw_key(raw: str) -> dict[str, Any] | str: ... # dict is a JSON object +@overload +def prepare_raw_key(raw: _TL) -> _Keys[_TL]: ... + +def find_encode_key(key, header): ... +def create_load_key(key: KeySet | _Keys[Incomplete] | Incomplete) -> _LoadKey: ... diff --git a/stubs/Authlib/authlib/jose/rfc8037/__init__.pyi b/stubs/Authlib/authlib/jose/rfc8037/__init__.pyi new file mode 100644 index 000000000000..915582d47ac5 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc8037/__init__.pyi @@ -0,0 +1,4 @@ +from .jws_eddsa import register_jws_rfc8037 as register_jws_rfc8037 +from .okp_key import OKPKey as OKPKey + +__all__ = ["register_jws_rfc8037", "OKPKey"] diff --git a/stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi b/stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi new file mode 100644 index 000000000000..93bb7d3d72d0 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi @@ -0,0 +1,12 @@ +from authlib.jose.rfc7515 import JWSAlgorithm + +from .okp_key import OKPKey + +class EdDSAAlgorithm(JWSAlgorithm): + name: str + description: str + def prepare_key(self, raw_data) -> OKPKey: ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +def register_jws_rfc8037(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi b/stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi new file mode 100644 index 000000000000..f6a39d28e8a9 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi @@ -0,0 +1,28 @@ +from typing import ClassVar, Final + +from authlib.jose.rfc7517 import AsymmetricKey +from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey, Ed448PublicKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.asymmetric.x448 import X448PrivateKey, X448PublicKey +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey + +PUBLIC_KEYS_MAP: Final[dict[str, type]] +PRIVATE_KEYS_MAP: Final[dict[str, type]] + +class OKPKey(AsymmetricKey): + kty: str + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS # pyrefly: ignore [unknown-name] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_CLS: ClassVar[tuple[type, ...]] + PRIVATE_KEY_CLS: ClassVar[tuple[type, ...]] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + def exchange_shared_key(self, pubkey: X25519PrivateKey | X448PublicKey) -> bytes: ... + @staticmethod + def get_key_curve(key) -> str | None: ... + def load_private_key(self) -> Ed25519PrivateKey | Ed448PrivateKey | X25519PrivateKey | X448PrivateKey: ... + def load_public_key(self) -> Ed25519PublicKey | Ed448PublicKey | X25519PublicKey | X448PublicKey: ... + def dumps_private_key(self) -> dict[str, str | None]: ... + def dumps_public_key(self, public_key=None) -> dict[str, str | None]: ... + @classmethod + def generate_key(cls, crv: str = "Ed25519", options=None, is_private: bool = False) -> OKPKey: ... diff --git a/stubs/Authlib/authlib/jose/util.pyi b/stubs/Authlib/authlib/jose/util.pyi new file mode 100644 index 000000000000..780229067d4f --- /dev/null +++ b/stubs/Authlib/authlib/jose/util.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from authlib.common.errors import AuthlibBaseError + +def extract_header(header_segment: bytes, error_cls: AuthlibBaseError) -> dict[Incomplete, Incomplete]: ... +def extract_segment(segment: bytes, error_cls: AuthlibBaseError, name: str = "payload") -> bytes: ... +def ensure_dict(s: object, structure_name: str) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/oauth1/__init__.pyi b/stubs/Authlib/authlib/oauth1/__init__.pyi new file mode 100644 index 000000000000..053e8f1d2c33 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/__init__.pyi @@ -0,0 +1,33 @@ +from .rfc5849 import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, + AuthorizationServer as AuthorizationServer, + ClientAuth as ClientAuth, + ClientMixin as ClientMixin, + OAuth1Request as OAuth1Request, + ResourceProtector as ResourceProtector, + TemporaryCredential as TemporaryCredential, + TemporaryCredentialMixin as TemporaryCredentialMixin, + TokenCredentialMixin as TokenCredentialMixin, +) + +__all__ = [ + "OAuth1Request", + "ClientAuth", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "ClientMixin", + "TemporaryCredentialMixin", + "TokenCredentialMixin", + "TemporaryCredential", + "AuthorizationServer", + "ResourceProtector", +] diff --git a/stubs/Authlib/authlib/oauth1/client.pyi b/stubs/Authlib/authlib/oauth1/client.pyi new file mode 100644 index 000000000000..07b0221f9c15 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/client.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete +from typing import Any +from typing_extensions import Never + +from authlib.oauth1 import ClientAuth + +class OAuth1Client: + auth_class: type[ClientAuth] + session: Incomplete + auth: ClientAuth + def __init__( + self, + session, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method="HMAC-SHA1", + signature_type="HEADER", + force_include_body: bool = False, + realm=None, + **kwargs, + ) -> None: ... + + @property + def redirect_uri(self): ... + @redirect_uri.setter + def redirect_uri(self, uri) -> None: ... + + @property + def token(self) -> dict[Incomplete, Incomplete]: ... + @token.setter + def token(self, token) -> None: ... + + def create_authorization_url(self, url, request_token=None, **kwargs) -> str: ... + def fetch_request_token(self, url: str, **kwargs) -> dict[str, Any]: ... + def fetch_access_token(self, url, verifier=None, **kwargs): ... + def parse_authorization_response(self, url: str) -> dict[str, str]: ... + def parse_response_token(self, status_code: int, text: str): ... + @staticmethod + def handle_error(error_type: str, error_description: str) -> Never: ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth1/errors.pyi b/stubs/Authlib/authlib/oauth1/errors.pyi new file mode 100644 index 000000000000..21c42b76694a --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/errors.pyi @@ -0,0 +1 @@ +from authlib.oauth1.rfc5849.errors import * diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi new file mode 100644 index 000000000000..f6cd313f97d5 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi @@ -0,0 +1,35 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .client_auth import ClientAuth as ClientAuth +from .models import ( + ClientMixin as ClientMixin, + TemporaryCredential as TemporaryCredential, + TemporaryCredentialMixin as TemporaryCredentialMixin, + TokenCredentialMixin as TokenCredentialMixin, +) +from .resource_protector import ResourceProtector as ResourceProtector +from .signature import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, +) +from .wrapper import OAuth1Request as OAuth1Request + +__all__ = [ + "OAuth1Request", + "ClientAuth", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "ClientMixin", + "TemporaryCredentialMixin", + "TokenCredentialMixin", + "TemporaryCredential", + "AuthorizationServer", + "ResourceProtector", +] diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi new file mode 100644 index 000000000000..e77bd50c9227 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi @@ -0,0 +1,19 @@ +from authlib.oauth1.rfc5849.base_server import BaseServer + +class AuthorizationServer(BaseServer): + TOKEN_RESPONSE_HEADER: list[tuple[str, str]] + TEMPORARY_CREDENTIALS_METHOD: str + def create_oauth1_request(self, request): ... + def handle_response(self, status_code, payload, headers): ... + def handle_error_response(self, error): ... + def validate_temporary_credentials_request(self, request): ... + def create_temporary_credentials_response(self, request=None): ... + def validate_authorization_request(self, request): ... + def create_authorization_response(self, request, grant_user=None): ... + def validate_token_request(self, request): ... + def create_token_response(self, request): ... + def create_temporary_credential(self, request): ... + def get_temporary_credential(self, request): ... + def delete_temporary_credential(self, request): ... + def create_authorization_verifier(self, request): ... + def create_token_credential(self, request): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi new file mode 100644 index 000000000000..ac2c014e5144 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable + +class BaseServer: + SIGNATURE_METHODS: dict[str, Callable[..., bool]] + SUPPORTED_SIGNATURE_METHODS: list[str] + EXPIRY_TIME: int + @classmethod + def register_signature_method(cls, name: str, verify: Callable[..., bool]) -> None: ... + def validate_timestamp_and_nonce(self, request) -> None: ... + def validate_oauth_signature(self, request) -> None: ... + def get_client_by_id(self, client_id): ... + def exists_nonce(self, nonce, request) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi new file mode 100644 index 000000000000..4fc70d6c19dc --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Final + +CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data" + +class ClientAuth: + SIGNATURE_METHODS: dict[str, Callable[..., str]] + @classmethod + def register_signature_method(cls, name: str, sign: Callable[..., str]) -> None: ... + client_id: Incomplete + client_secret: Incomplete + token: Incomplete + token_secret: Incomplete + redirect_uri: Incomplete + signature_method: Incomplete + signature_type: Incomplete + rsa_key: Incomplete + verifier: Incomplete + realm: Incomplete + force_include_body: Incomplete + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method="HMAC-SHA1", + signature_type="HEADER", + realm=None, + force_include_body: bool = False, + ) -> None: ... + def get_oauth_signature(self, method, uri, headers, body) -> str: ... + def get_oauth_params(self, nonce, timestamp) -> list[tuple[str, Incomplete]]: ... + def sign(self, method, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def prepare(self, method, uri, headers, body) -> tuple[Incomplete, ...]: ... + +def generate_nonce() -> str: ... +def generate_timestamp() -> str: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi new file mode 100644 index 000000000000..f6140d851d1c --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi @@ -0,0 +1,52 @@ +from authlib.common.errors import AuthlibHTTPError + +class OAuth1Error(AuthlibHTTPError): + def __init__(self, description=None, uri=None, status_code=None) -> None: ... + def get_headers(self) -> list[tuple[str, str]]: ... + +class InsecureTransportError(OAuth1Error): + error: str + description: str + @classmethod + def check(cls, uri) -> None: ... + +class InvalidRequestError(OAuth1Error): + error: str + +class UnsupportedParameterError(OAuth1Error): + error: str + +class UnsupportedSignatureMethodError(OAuth1Error): + error: str + +class MissingRequiredParameterError(OAuth1Error): + error: str + def __init__(self, key) -> None: ... + +class DuplicatedOAuthProtocolParameterError(OAuth1Error): + error: str + +class InvalidClientError(OAuth1Error): + error: str + status_code: int + +class InvalidTokenError(OAuth1Error): + error: str + description: str + status_code: int + +class InvalidSignatureError(OAuth1Error): + error: str + status_code: int + +class InvalidNonceError(OAuth1Error): + error: str + status_code: int + +class AccessDeniedError(OAuth1Error): + error: str + description: str + +class MethodNotAllowedError(OAuth1Error): + error: str + status_code: int diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/models.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/models.pyi new file mode 100644 index 000000000000..98e0cfd55d7c --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/models.pyi @@ -0,0 +1,21 @@ +class ClientMixin: + def get_default_redirect_uri(self): ... + def get_client_secret(self): ... + def get_rsa_public_key(self): ... + +class TokenCredentialMixin: + def get_oauth_token(self): ... + def get_oauth_token_secret(self): ... + +class TemporaryCredentialMixin(TokenCredentialMixin): + def get_client_id(self): ... + def get_redirect_uri(self): ... + def check_verifier(self, verifier) -> bool: ... + +class TemporaryCredential(dict[str, object], TemporaryCredentialMixin): + def get_client_id(self): ... + def get_user_id(self): ... + def get_redirect_uri(self): ... + def check_verifier(self, verifier) -> bool: ... + def get_oauth_token(self): ... + def get_oauth_token_secret(self): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi new file mode 100644 index 000000000000..5bffb2b79730 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi @@ -0,0 +1,10 @@ +from collections.abc import Iterable +from typing import TypeVar + +_K = TypeVar("_K") + +def prepare_headers( + oauth_params: Iterable[tuple[str, str]], headers: dict[str, _K] | None = None, realm=None +) -> dict[str, _K | str]: ... +def prepare_form_encoded_body(oauth_params: Iterable[tuple[str, str]], body: Iterable[tuple[str, str]]) -> str: ... +def prepare_request_uri_query(oauth_params: Iterable[tuple[str, str]], uri: str) -> str: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi new file mode 100644 index 000000000000..45f147d4d80c --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi @@ -0,0 +1,7 @@ +from authlib.oauth1.rfc5849.base_server import BaseServer + +from .wrapper import OAuth1Request + +class ResourceProtector(BaseServer): + def validate_request(self, method, uri, body, headers) -> OAuth1Request: ... + def get_token_credential(self, request): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi new file mode 100644 index 000000000000..8e650fbd9cc9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi @@ -0,0 +1,2 @@ +def sign_sha1(msg, rsa_private_key): ... +def verify_sha1(sig, msg, rsa_public_key) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi new file mode 100644 index 000000000000..1fb8119798cc --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi @@ -0,0 +1,22 @@ +from typing import Final + +SIGNATURE_HMAC_SHA1: Final = "HMAC-SHA1" +SIGNATURE_RSA_SHA1: Final = "RSA-SHA1" +SIGNATURE_PLAINTEXT: Final = "PLAINTEXT" +SIGNATURE_TYPE_HEADER: Final = "HEADER" +SIGNATURE_TYPE_QUERY: Final = "QUERY" +SIGNATURE_TYPE_BODY: Final = "BODY" + +def construct_base_string(method, uri, params, host=None) -> str: ... +def normalize_base_string_uri(uri, host=None): ... +def normalize_parameters(params) -> str: ... +def generate_signature_base_string(request) -> str: ... +def hmac_sha1_signature(base_string, client_secret, token_secret) -> str: ... +def rsa_sha1_signature(base_string, rsa_private_key) -> str: ... +def plaintext_signature(client_secret, token_secret) -> str: ... +def sign_hmac_sha1(client, request) -> str: ... +def sign_rsa_sha1(client, request) -> str: ... +def sign_plaintext(client, request) -> str: ... +def verify_hmac_sha1(request) -> bool: ... +def verify_rsa_sha1(request) -> bool: ... +def verify_plaintext(request) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/util.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/util.pyi new file mode 100644 index 000000000000..9522d3075d45 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/util.pyi @@ -0,0 +1,2 @@ +def escape(s: str | bytes | float) -> str: ... +def unescape(s: str | bytes) -> str: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi new file mode 100644 index 000000000000..973e82fc0bf9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete + +class OAuth1Request: + method: Incomplete + uri: Incomplete + body: Incomplete + headers: Incomplete + client: Incomplete | None + credential: Incomplete | None + user: Incomplete | None + query: Incomplete + query_params: Incomplete + body_params: Incomplete + auth_params: Incomplete + realm: Incomplete + signature_type: str | None + oauth_params: Incomplete + params: list[Incomplete] + def __init__(self, method, uri, body=None, headers=None) -> None: ... + @property + def client_id(self): ... + @property + def client_secret(self): ... + @property + def rsa_public_key(self): ... + @property + def timestamp(self): ... + @property + def redirect_uri(self): ... + @property + def signature(self): ... + @property + def signature_method(self): ... + @property + def token(self): ... + @property + def token_secret(self): ... diff --git a/stubs/Authlib/authlib/oauth2/__init__.pyi b/stubs/Authlib/authlib/oauth2/__init__.pyi new file mode 100644 index 000000000000..716ca9309f0c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/__init__.pyi @@ -0,0 +1,22 @@ +from .auth import ClientAuth as ClientAuth, TokenAuth as TokenAuth +from .base import OAuth2Error as OAuth2Error +from .client import OAuth2Client as OAuth2Client +from .rfc6749 import ( + AuthorizationServer as AuthorizationServer, + ClientAuthentication as ClientAuthentication, + JsonRequest as JsonRequest, + OAuth2Request as OAuth2Request, + ResourceProtector as ResourceProtector, +) + +__all__ = [ + "OAuth2Error", + "ClientAuth", + "TokenAuth", + "OAuth2Client", + "OAuth2Request", + "JsonRequest", + "AuthorizationServer", + "ClientAuthentication", + "ResourceProtector", +] diff --git a/stubs/Authlib/authlib/oauth2/auth.pyi b/stubs/Authlib/authlib/oauth2/auth.pyi new file mode 100644 index 000000000000..5be0ac7fc0f6 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/auth.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +def encode_client_secret_basic(client, method, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def encode_client_secret_post(client, method, uri, headers, body) -> tuple[Incomplete, Incomplete, str]: ... +def encode_none(client, method, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +class ClientAuth: + DEFAULT_AUTH_METHODS: dict[str, Incomplete] + client_id: Incomplete + client_secret: Incomplete + auth_method: Incomplete + def __init__(self, client_id, client_secret, auth_method=None) -> None: ... + def prepare(self, method, uri, headers, body): ... + +class TokenAuth: + DEFAULT_TOKEN_TYPE: str + SIGN_METHODS: dict[str, Incomplete] + token: Incomplete + token_placement: str + client: Incomplete | None + hooks: set[Incomplete] + def __init__(self, token, token_placement: str = "header", client=None) -> None: ... + def set_token(self, token) -> None: ... + def prepare(self, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/base.pyi b/stubs/Authlib/authlib/oauth2/base.pyi new file mode 100644 index 000000000000..91181720ef60 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/base.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from typing import Literal + +from authlib.common.errors import AuthlibHTTPError + +def invalid_error_characters(text: str) -> list[str]: ... + +class OAuth2Error(AuthlibHTTPError): + state: Incomplete + redirect_uri: Incomplete + redirect_fragment: Incomplete + def __init__( + self, + description: str | None = None, + uri=None, + status_code=None, + state=None, + redirect_uri=None, + redirect_fragment: bool = False, + error=None, + ) -> None: ... + def get_body(self) -> list[tuple[Literal["error", "error_description", "error_uri"], str | None]]: ... + def __call__(self, uri: str | None = None): ... diff --git a/stubs/Authlib/authlib/oauth2/claims.pyi b/stubs/Authlib/authlib/oauth2/claims.pyi new file mode 100644 index 000000000000..899113298ca0 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/claims.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import TypedDict + +class ClaimsOption(TypedDict, total=False): + essential: bool + allow_blank: bool | None + value: str | int | bool + values: list[str | int | bool] | list[str] | list[int] | list[bool] + validate: Callable[[BaseClaims, Incomplete], bool] + +class BaseClaims(dict[str, Incomplete]): + registry_cls: Incomplete + REGISTERED_CLAIMS: list[str] + header: dict[str, Incomplete] + options: dict[str, ClaimsOption] + params: dict[str, Incomplete] + def __init__( + self, + claims: dict[str, Incomplete], + header: dict[str, Incomplete], + options: dict[str, ClaimsOption] | None = None, + params: dict[str, Incomplete] | None = None, + ) -> None: ... + def get_registered_claims(self) -> dict[str, Incomplete]: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + +class JWTClaims(BaseClaims): + registry_cls: Incomplete + REGISTERED_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/client.pyi b/stubs/Authlib/authlib/oauth2/client.pyi new file mode 100644 index 000000000000..ec4028af4372 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/client.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import ClientAuth, OAuth2Error, TokenAuth + +DEFAULT_HEADERS: Incomplete + +class OAuth2Client: + client_auth_class = ClientAuth + token_auth_class = TokenAuth + oauth_error_class = OAuth2Error + EXTRA_AUTHORIZE_PARAMS: tuple[str, ...] + SESSION_REQUEST_PARAMS: list[str] + session: Incomplete + client_id: Incomplete + client_secret: Incomplete + state: Incomplete + token_endpoint_auth_method: Incomplete + revocation_endpoint_auth_method: Incomplete + scope: Incomplete + redirect_uri: Incomplete + code_challenge_method: Incomplete + token_auth: Incomplete + update_token: Incomplete + metadata: dict[str, Incomplete] + compliance_hook: dict[str, set[Incomplete]] + leeway: int + def __init__( + self, + session, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + state=None, + redirect_uri=None, + code_challenge_method=None, + token=None, + token_placement: str = "header", + update_token=None, + leeway: int = 60, + *, + token_updater=None, + response_type=None, + grant_type: str | None = None, + token_endpoint=None, + **metadata, + ) -> None: ... + def register_client_auth_method(self, auth) -> None: ... + def client_auth(self, auth_method) -> ClientAuth: ... + + @property + def token(self): ... + @token.setter + def token(self, token) -> None: ... + + def create_authorization_url(self, url, state=None, code_verifier=None, **kwargs) -> tuple[str, Incomplete]: ... + def fetch_token( + self, url=None, body: str = "", method: str = "POST", headers=None, auth=None, grant_type=None, state=None, **kwargs + ): ... + def token_from_fragment(self, authorization_response, state=None) -> dict[Incomplete, Incomplete]: ... + def refresh_token(self, url=None, refresh_token=None, body: str = "", auth=None, headers=None, **kwargs): ... + def ensure_active_token(self, token=None): ... + def revoke_token(self, url, token=None, token_type_hint=None, body=None, auth=None, headers=None, **kwargs): ... + def introspect_token( + self, + url: str, + token: str | None = None, + token_type_hint: str | None = None, + body: str | None = None, + auth=None, + headers=None, + **kwargs, + ): ... + def register_compliance_hook(self, hook_type, hook) -> None: ... + def parse_response_token(self, resp): ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi new file mode 100644 index 000000000000..378c042e688b --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi @@ -0,0 +1,86 @@ +from .authenticate_client import ClientAuthentication as ClientAuthentication +from .authorization_server import AuthorizationServer as AuthorizationServer +from .endpoint import Endpoint, EndpointRequest +from .errors import ( + AccessDeniedError as AccessDeniedError, + InsecureTransportError as InsecureTransportError, + InvalidClientError as InvalidClientError, + InvalidGrantError as InvalidGrantError, + InvalidRequestError as InvalidRequestError, + InvalidScopeError as InvalidScopeError, + MismatchingStateException as MismatchingStateException, + MissingAuthorizationError as MissingAuthorizationError, + MissingCodeException as MissingCodeException, + MissingTokenException as MissingTokenException, + MissingTokenTypeException as MissingTokenTypeException, + OAuth2Error as OAuth2Error, + UnauthorizedClientError as UnauthorizedClientError, + UnsupportedGrantTypeError as UnsupportedGrantTypeError, + UnsupportedResponseTypeError as UnsupportedResponseTypeError, + UnsupportedTokenTypeError as UnsupportedTokenTypeError, +) +from .grants import ( + AuthorizationCodeGrant as AuthorizationCodeGrant, + AuthorizationEndpointMixin as AuthorizationEndpointMixin, + BaseGrant as BaseGrant, + ClientCredentialsGrant as ClientCredentialsGrant, + ImplicitGrant as ImplicitGrant, + RefreshTokenGrant as RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant as ResourceOwnerPasswordCredentialsGrant, + TokenEndpointMixin as TokenEndpointMixin, +) +from .models import AuthorizationCodeMixin as AuthorizationCodeMixin, ClientMixin as ClientMixin, TokenMixin as TokenMixin +from .requests import ( + JsonPayload as JsonPayload, + JsonRequest as JsonRequest, + OAuth2Payload as OAuth2Payload, + OAuth2Request as OAuth2Request, +) +from .resource_protector import ResourceProtector as ResourceProtector, TokenValidator as TokenValidator +from .token_endpoint import TokenEndpoint as TokenEndpoint +from .util import list_to_scope as list_to_scope, scope_to_list as scope_to_list +from .wrappers import OAuth2Token as OAuth2Token + +__all__ = [ + "OAuth2Payload", + "OAuth2Token", + "OAuth2Request", + "JsonPayload", + "JsonRequest", + "OAuth2Error", + "AccessDeniedError", + "MissingAuthorizationError", + "InvalidGrantError", + "InvalidClientError", + "InvalidRequestError", + "InvalidScopeError", + "InsecureTransportError", + "UnauthorizedClientError", + "UnsupportedResponseTypeError", + "UnsupportedGrantTypeError", + "UnsupportedTokenTypeError", + "MissingCodeException", + "MissingTokenException", + "MissingTokenTypeException", + "MismatchingStateException", + "ClientMixin", + "AuthorizationCodeMixin", + "TokenMixin", + "ClientAuthentication", + "AuthorizationServer", + "ResourceProtector", + "TokenValidator", + "Endpoint", + "EndpointRequest", + "TokenEndpoint", + "BaseGrant", + "AuthorizationEndpointMixin", + "TokenEndpointMixin", + "AuthorizationCodeGrant", + "ImplicitGrant", + "ResourceOwnerPasswordCredentialsGrant", + "ClientCredentialsGrant", + "RefreshTokenGrant", + "scope_to_list", + "list_to_scope", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi new file mode 100644 index 000000000000..01af6828efd2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable, Collection + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import ClientMixin + +__all__ = ["ClientAuthentication"] + +class ClientAuthentication: + query_client: Callable[[str], ClientMixin] + def __init__(self, query_client: Callable[[str], ClientMixin]) -> None: ... + def register(self, method: str, func: Callable[[Callable[[str], ClientMixin], OAuth2Request], ClientMixin]) -> None: ... + def authenticate(self, request: OAuth2Request, methods: Collection[str], endpoint: str) -> ClientMixin: ... + def __call__(self, request: OAuth2Request, methods: Collection[str], endpoint: str = "token") -> ClientMixin: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi new file mode 100644 index 000000000000..932bec1278f1 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi @@ -0,0 +1,55 @@ +from collections.abc import Callable, Collection, Mapping +from typing import TypeAlias, overload +from typing_extensions import deprecated + +from authlib.oauth2 import JsonRequest, OAuth2Error, OAuth2Request +from authlib.oauth2.rfc6749 import BaseGrant, ClientMixin +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +from .endpoint import Endpoint, EndpointRequest +from .hooks import Hookable + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +class AuthorizationServer(Hookable): + scopes_supported: Collection[str] | None + def __init__(self, scopes_supported: Collection[str] | None = None) -> None: ... + def query_client(self, client_id: str) -> ClientMixin: ... + def save_token(self, token: dict[str, str | int], request: OAuth2Request) -> None: ... + def generate_token( + self, + grant_type: str, + client: ClientMixin, + user=None, + scope: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... + def register_token_generator(self, grant_type: str, func: BearerTokenGenerator) -> None: ... + def authenticate_client(self, request: OAuth2Request, methods: Collection[str], endpoint: str = "token") -> ClientMixin: ... + def register_client_auth_method(self, method, func) -> None: ... + def register_extension(self, extension) -> None: ... + def get_error_uri(self, request, error): ... + def send_signal(self, name, *args: object, **kwargs: object) -> None: ... + def create_oauth2_request(self, request) -> OAuth2Request: ... + def create_json_request(self, request) -> JsonRequest: ... + def handle_response(self, status: int, body: Mapping[str, object], headers: Mapping[str, str]) -> object: ... + def validate_requested_scope(self, scope: str) -> None: ... + def register_grant( + self, grant_cls: type[BaseGrant], extensions: Collection[Callable[[BaseGrant], None]] | None = None + ) -> None: ... + def register_endpoint(self, endpoint: type[Endpoint] | Endpoint) -> None: ... + def get_authorization_grant(self, request: OAuth2Request) -> BaseGrant: ... + def get_consent_grant(self, request=None, end_user=None): ... + def get_token_grant(self, request: OAuth2Request) -> BaseGrant: ... + def validate_endpoint_request(self, name, request=None) -> EndpointRequest: ... + def create_endpoint_response(self, name, request=None): ... + + @overload + @deprecated("The 'grant' parameter will become mandatory.") + def create_authorization_response(self, request=None, grant_user=None) -> object: ... + @overload + def create_authorization_response(self, request=None, grant_user=None, grant=None) -> object: ... + + def create_token_response(self, request=None) -> _ServerResponse: ... + def handle_error_response(self, request: OAuth2Request, error: OAuth2Error) -> object: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi new file mode 100644 index 000000000000..6fb13da985f7 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from dataclasses import dataclass + +from .requests import OAuth2Request + +@dataclass +class EndpointRequest: + request: OAuth2Request + client: Incomplete | None = None + +class Endpoint: + ENDPOINT_NAME: str | None + server: Incomplete + def __init__(self, server=None) -> None: ... + def create_endpoint_request(self, request): ... + def validate_request(self, request: OAuth2Request) -> EndpointRequest: ... + def create_response(self, validated_request: EndpointRequest) -> tuple[int, Incomplete, list[Incomplete]] | None: ... + def create_endpoint_response(self, request: OAuth2Request) -> tuple[int, Incomplete, list[Incomplete]] | None: ... + def __call__(self, request: OAuth2Request) -> tuple[int, Incomplete, list[Incomplete]] | None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi new file mode 100644 index 000000000000..8436b28f2c11 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi @@ -0,0 +1,102 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Error as OAuth2Error + +__all__ = [ + "OAuth2Error", + "InsecureTransportError", + "InvalidRequestError", + "InvalidClientError", + "UnauthorizedClientError", + "InvalidGrantError", + "UnsupportedResponseTypeError", + "UnsupportedGrantTypeError", + "InvalidScopeError", + "AccessDeniedError", + "MissingAuthorizationError", + "UnsupportedTokenTypeError", + "MissingCodeException", + "MissingTokenException", + "MissingTokenTypeException", + "MismatchingStateException", +] + +class InsecureTransportError(OAuth2Error): + error: str + description: str + @classmethod + def check(cls, uri) -> None: ... + +class InvalidRequestError(OAuth2Error): + error: str + +class InvalidClientError(OAuth2Error): + error: str + status_code: int + def get_headers(self): ... + +class InvalidGrantError(OAuth2Error): + error: str + +class UnauthorizedClientError(OAuth2Error): + error: str + +class UnsupportedResponseTypeError(OAuth2Error): + error: str + response_type: Incomplete + def __init__( + self, + response_type, + description=None, + uri=None, + status_code=None, + state=None, + redirect_uri=None, + redirect_fragment: bool = False, + error=None, + ) -> None: ... + def get_error_description(self): ... + +class UnsupportedGrantTypeError(OAuth2Error): + error: str + grant_type: Incomplete + def __init__(self, grant_type) -> None: ... + def get_error_description(self): ... + +class InvalidScopeError(OAuth2Error): + error: str + description: str + +class AccessDeniedError(OAuth2Error): + error: str + description: str + +class ForbiddenError(OAuth2Error): + status_code: int + auth_type: Incomplete + realm: Incomplete + def __init__(self, auth_type=None, realm=None) -> None: ... + def get_headers(self): ... + +class MissingAuthorizationError(ForbiddenError): + error: str + description: str + +class UnsupportedTokenTypeError(ForbiddenError): + error: str + +class MissingCodeException(OAuth2Error): + error: str + description: str + +class MissingTokenException(OAuth2Error): + error: str + description: str + +class MissingTokenTypeException(OAuth2Error): + error: str + description: str + +class MismatchingStateException(OAuth2Error): + error: str + description: str diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi new file mode 100644 index 000000000000..b0300118a192 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi @@ -0,0 +1,21 @@ +from .authorization_code import AuthorizationCodeGrant as AuthorizationCodeGrant +from .base import ( + AuthorizationEndpointMixin as AuthorizationEndpointMixin, + BaseGrant as BaseGrant, + TokenEndpointMixin as TokenEndpointMixin, +) +from .client_credentials import ClientCredentialsGrant as ClientCredentialsGrant +from .implicit import ImplicitGrant as ImplicitGrant +from .refresh_token import RefreshTokenGrant as RefreshTokenGrant +from .resource_owner_password_credentials import ResourceOwnerPasswordCredentialsGrant as ResourceOwnerPasswordCredentialsGrant + +__all__ = [ + "BaseGrant", + "AuthorizationEndpointMixin", + "TokenEndpointMixin", + "AuthorizationCodeGrant", + "ImplicitGrant", + "ResourceOwnerPasswordCredentialsGrant", + "ClientCredentialsGrant", + "RefreshTokenGrant", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi new file mode 100644 index 000000000000..1ee7e57abbb9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi @@ -0,0 +1,27 @@ +from collections.abc import Collection +from logging import Logger +from typing import TypeAlias + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import AuthorizationEndpointMixin, BaseGrant, ClientMixin, TokenEndpointMixin + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +log: Logger + +class AuthorizationCodeGrant(BaseGrant, AuthorizationEndpointMixin, TokenEndpointMixin): + TOKEN_ENDPOINT_AUTH_METHODS: Collection[str] + AUTHORIZATION_CODE_LENGTH: int + RESPONSE_TYPES: Collection[str] + GRANT_TYPE: str + def validate_authorization_request(self) -> str: ... + def create_authorization_response(self, redirect_uri: str, grant_user) -> _ServerResponse: ... + def validate_token_request(self) -> None: ... + def create_token_response(self) -> _ServerResponse: ... + def generate_authorization_code(self) -> str: ... + def save_authorization_code(self, code: str, request: OAuth2Request): ... + def query_authorization_code(self, code: str, client: ClientMixin): ... + def delete_authorization_code(self, authorization_code): ... + def authenticate_user(self, authorization_code): ... + +def validate_code_authorization_request(grant: AuthorizationCodeGrant) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi new file mode 100644 index 000000000000..82cd47e1c2d3 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from collections.abc import Collection +from typing import TypeAlias + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import ClientMixin + +from ..hooks import Hookable + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +class BaseGrant(Hookable): + TOKEN_ENDPOINT_AUTH_METHODS: Collection[str] + GRANT_TYPE: str | None + TOKEN_RESPONSE_HEADER: Collection[tuple[str, str]] + prompt: Incomplete + redirect_uri: Incomplete + request: OAuth2Request + server: Incomplete + def __init__(self, request: OAuth2Request, server) -> None: ... + @property + def client(self): ... + def generate_token( + self, + user=None, + scope: str | None = None, + grant_type: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... + def authenticate_token_endpoint_client(self) -> ClientMixin: ... + def save_token(self, token): ... + def validate_requested_scope(self) -> None: ... + +class TokenEndpointMixin: + TOKEN_ENDPOINT_HTTP_METHODS: Incomplete + GRANT_TYPE: Incomplete + @classmethod + def check_token_endpoint(cls, request: OAuth2Request) -> bool: ... + def validate_token_request(self) -> None: ... + def create_token_response(self) -> _ServerResponse: ... + +class AuthorizationEndpointMixin: + RESPONSE_TYPES: Collection[str] + ERROR_RESPONSE_FRAGMENT: bool + @classmethod + def check_authorization_endpoint(cls, request: OAuth2Request) -> bool: ... + @staticmethod + def validate_authorization_redirect_uri(request: OAuth2Request, client: ClientMixin) -> str: ... + @staticmethod + def validate_no_multiple_request_parameter(request: OAuth2Request): ... + redirect_uri: str + def validate_consent_request(self) -> str: ... + def validate_authorization_request(self) -> str: ... + def create_authorization_response(self, redirect_uri: str, grant_user) -> _ServerResponse: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi new file mode 100644 index 000000000000..39a26a843f82 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi @@ -0,0 +1,10 @@ +from logging import Logger + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger + +class ClientCredentialsGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE: str + def validate_token_request(self) -> None: ... + def create_token_response(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi new file mode 100644 index 000000000000..69b1946356d2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2.rfc6749 import AuthorizationEndpointMixin, BaseGrant + +log: Logger + +class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin): + AUTHORIZATION_ENDPOINT: bool + TOKEN_ENDPOINT_AUTH_METHODS: Incomplete + RESPONSE_TYPES: Incomplete + GRANT_TYPE: str + ERROR_RESPONSE_FRAGMENT: bool + def validate_authorization_request(self): ... + def create_authorization_response(self, redirect_uri, grant_user): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi new file mode 100644 index 000000000000..670fc27460b8 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi @@ -0,0 +1,18 @@ +from logging import Logger +from typing import TypeAlias + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin, TokenMixin + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +log: Logger + +class RefreshTokenGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE: str + INCLUDE_NEW_REFRESH_TOKEN: bool + def validate_token_request(self) -> None: ... + def create_token_response(self) -> _ServerResponse: ... + def issue_token(self, user, refresh_token: TokenMixin) -> dict[str, str | int]: ... + def authenticate_refresh_token(self, refresh_token: str) -> TokenMixin: ... + def authenticate_user(self, refresh_token): ... + def revoke_old_credential(self, refresh_token: TokenMixin) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi new file mode 100644 index 000000000000..13037ed8d2f6 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi @@ -0,0 +1,11 @@ +from logging import Logger + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger + +class ResourceOwnerPasswordCredentialsGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE: str + def validate_token_request(self) -> None: ... + def create_token_response(self): ... + def authenticate_user(self, username, password): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi new file mode 100644 index 000000000000..78aa94a7a20d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable + +class Hookable: + def __init__(self) -> None: ... + def register_hook(self, hook_type: str, hook: Callable[..., None]) -> None: ... + def execute_hook(self, hook_type: str, *args, **kwargs) -> None: ... + +def hooked(func=None, before: str | None = None, after: str | None = None): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/models.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/models.pyi new file mode 100644 index 000000000000..47c8ed0ebcfc --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/models.pyi @@ -0,0 +1,24 @@ +from collections.abc import Collection + +class ClientMixin: + def get_client_id(self) -> str: ... + def get_default_redirect_uri(self) -> str: ... + def get_allowed_scope(self, scope: Collection[str] | str) -> str: ... + def check_redirect_uri(self, redirect_uri: str) -> bool: ... + def check_client_secret(self, client_secret: str) -> bool: ... + def check_endpoint_auth_method(self, method: str, endpoint: str) -> bool: ... + def check_response_type(self, response_type: str) -> bool: ... + def check_grant_type(self, grant_type: str) -> bool: ... + +class AuthorizationCodeMixin: + def get_redirect_uri(self) -> str: ... + def get_scope(self) -> str: ... + +class TokenMixin: + def check_client(self, client) -> bool: ... + def get_scope(self) -> str: ... + def get_expires_in(self) -> int: ... + def is_expired(self) -> bool: ... + def is_revoked(self) -> bool: ... + def get_user(self): ... + def get_client(self) -> ClientMixin: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi new file mode 100644 index 000000000000..39f65e9381bf --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi @@ -0,0 +1,22 @@ +from collections.abc import Collection, Sequence + +def prepare_grant_uri( + uri: str, + client_id: str, + response_type: str, + redirect_uri: str | None = None, + scope: Collection[str] | str | None = None, + state: str | None = None, + **kwargs: str | Sequence[str | None] | None, +): ... +def prepare_token_request( + grant_type: str, + body: str = "", + redirect_uri: str | None = None, + *, + scope: Collection[str] | str | None = None, + code: str | None = None, + **kwargs: str | None, +) -> str: ... +def parse_authorization_code_response(uri: str, state: str | None = None) -> dict[str, str]: ... +def parse_implicit_response(uri: str, state: str | None = None) -> dict[str, str]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi new file mode 100644 index 000000000000..37cafb6b54c9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi @@ -0,0 +1,98 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import overload +from typing_extensions import deprecated + +from authlib.oauth2.rfc6749 import ClientMixin + +class OAuth2Payload: + @property + def data(self) -> dict[str, str]: ... + @property + def datalist(self) -> dict[str, list[Incomplete]]: ... + @property + def client_id(self) -> str: ... + @property + def response_type(self) -> str: ... + @property + def grant_type(self) -> str: ... + @property + def redirect_uri(self) -> str: ... + @property + def scope(self) -> str: ... + @property + def state(self) -> str | None: ... + +class BasicOAuth2Payload(OAuth2Payload): + def __init__(self, payload: dict[str, str]) -> None: ... + @property + def data(self) -> dict[str, str]: ... + @property + def datalist(self) -> dict[str, list[Incomplete]]: ... + +class OAuth2Request(OAuth2Payload): + method: str + uri: str + headers: Mapping[str, str] | None + payload: OAuth2Payload | None + client: ClientMixin | None + auth_method: str | None + user: Incomplete | None + authorization_code: Incomplete | None + refresh_token: Incomplete | None + credential: Incomplete | None + + @overload + def __init__(self, method: str, uri: str, body: None = None, headers: Mapping[str, str] | None = None) -> None: ... + @overload + @deprecated("The `body` parameter in OAuth2Request is deprecated. Use the payload system instead.") + def __init__(self, method: str, uri: str, body, headers: Mapping[str, str] | None = None) -> None: ... + + @property + def args(self) -> dict[str, str | None]: ... + @property + def form(self) -> dict[str, str]: ... + @property + @deprecated("'request.data' is deprecated in favor of 'request.payload.data'") + def data(self) -> dict[str, str]: ... + @property + @deprecated("'request.datalist' is deprecated in favor of 'request.payload.datalist'") + def datalist(self) -> dict[str, list[Incomplete]]: ... + @property + @deprecated("'request.client_id' is deprecated in favor of 'request.payload.client_id'") + def client_id(self) -> str: ... + @property + @deprecated("'request.response_type' is deprecated in favor of 'request.payload.response_type'") + def response_type(self) -> str: ... + @property + @deprecated("'request.grant_type' is deprecated in favor of 'request.payload.grant_type'") + def grant_type(self) -> str: ... + @property + @deprecated("'request.redirect_uri' is deprecated in favor of 'request.payload.redirect_uri'") + def redirect_uri(self) -> str: ... + + @property + def scope(self) -> str: ... + @scope.setter + def scope(self, value: str) -> None: ... + + @property + @deprecated("'request.state' is deprecated in favor of 'request.payload.state'") + def state(self) -> str | None: ... + @property + @deprecated("'request.body' is deprecated. Use the payload system instead.") + def body(self): ... + +class JsonPayload: + @property + def data(self): ... + +class JsonRequest: + method: str + uri: str + payload: JsonPayload | None + headers: Mapping[str, str] + def __init__(self, method: str, uri: str, headers: Mapping[str, str] | None = None) -> None: ... + @property + @deprecated("'request.data' is deprecated in favor of 'request.payload.data'") + def data(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi new file mode 100644 index 000000000000..930a52fcc21f --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +class TokenValidator: + TOKEN_TYPE: str + realm: Incomplete + extra_attributes: Incomplete + def __init__(self, realm=None, **extra_attributes) -> None: ... + @staticmethod + def scope_insufficient(token_scopes, required_scopes): ... + def authenticate_token(self, token_string): ... + def validate_request(self, request) -> None: ... + def validate_token(self, token, scopes, request) -> None: ... + +class ResourceProtector: + def __init__(self) -> None: ... + def register_token_validator(self, validator: TokenValidator): ... + def get_token_validator(self, token_type): ... + def parse_request_authorization(self, request): ... + def validate_request(self, scopes, request, **kwargs): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi new file mode 100644 index 000000000000..579acec4ab20 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from .endpoint import Endpoint + +class TokenEndpoint(Endpoint): + ENDPOINT_NAME: str | None + SUPPORTED_TOKEN_TYPES: Incomplete + CLIENT_AUTH_METHODS: Incomplete + def authenticate_endpoint_client(self, request): ... + def authenticate_token(self, request, client): ... + def create_endpoint_response(self, request): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/util.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/util.pyi new file mode 100644 index 000000000000..416ec65a8fc1 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/util.pyi @@ -0,0 +1,14 @@ +from collections.abc import Collection +from typing import overload + +@overload +def list_to_scope(scope: str | Collection[str]) -> str: ... +@overload +def list_to_scope(scope: None) -> None: ... + +@overload +def scope_to_list(scope: str | Collection[str]) -> list[str]: ... +@overload +def scope_to_list(scope: None) -> None: ... + +def extract_basic_authorization(headers: dict[str, str]) -> tuple[str, str] | tuple[str, None] | tuple[None, None]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi new file mode 100644 index 000000000000..ab80ddf1a775 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi @@ -0,0 +1,5 @@ +class OAuth2Token(dict[str, object]): + def __init__(self, params) -> None: ... + def is_expired(self, leeway: int = 60) -> bool | None: ... + @classmethod + def from_dict(cls, token): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi new file mode 100644 index 000000000000..5c9b3d97670c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi @@ -0,0 +1,15 @@ +from .errors import InsufficientScopeError as InsufficientScopeError, InvalidTokenError as InvalidTokenError +from .parameters import add_bearer_token as add_bearer_token +from .token import BearerTokenGenerator as BearerTokenGenerator +from .validator import BearerTokenValidator as BearerTokenValidator + +__all__ = [ + "InvalidTokenError", + "InsufficientScopeError", + "add_bearer_token", + "BearerToken", + "BearerTokenGenerator", + "BearerTokenValidator", +] + +BearerToken = BearerTokenGenerator diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi new file mode 100644 index 000000000000..4f1576dd0ac4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Error + +__all__ = ["InvalidTokenError", "InsufficientScopeError"] + +class InvalidTokenError(OAuth2Error): + error: str + description: str + status_code: int + realm: Incomplete + extra_attributes: dict[str, Incomplete] + def __init__( + self, + description=None, + uri=None, + status_code=None, + state=None, + realm=None, + extra_attributes: dict[str, Incomplete] | None = None, + ) -> None: ... + def get_headers(self) -> list[tuple[str, str]]: ... + +class InsufficientScopeError(OAuth2Error): + error: str + description: str + status_code: int diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi new file mode 100644 index 000000000000..cf09bfc8b7e6 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi @@ -0,0 +1,14 @@ +from typing import Literal, TypeVar + +_K = TypeVar("_K") + +def add_to_uri(token: str, uri: str) -> str: ... +def add_to_headers(token: str, headers: dict[str, _K] | None = None) -> dict[str, _K | str]: ... +def add_to_body(token: str, body: str | None = None) -> str: ... +def add_bearer_token( + token: str, + uri: str, + headers: dict[str, _K], + body: str, + placement: Literal["uri", "url", "query", "header", "headers", "body"] = "header", +) -> tuple[str, dict[str, _K | str], str]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/token.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/token.pyi new file mode 100644 index 000000000000..bd521552611f --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/token.pyi @@ -0,0 +1,41 @@ +from collections.abc import Callable +from typing import Protocol, type_check_only + +from authlib.oauth2.rfc6749 import ClientMixin + +@type_check_only +class _TokenGenerator(Protocol): + def __call__(self, *, client: ClientMixin, grant_type: str, user, scope: str) -> str: ... + +class BearerTokenGenerator: + DEFAULT_EXPIRES_IN: int + GRANT_TYPES_EXPIRES_IN: dict[str, int] + access_token_generator: _TokenGenerator + refresh_token_generator: _TokenGenerator + expires_generator: Callable[[ClientMixin, str], int] + def __init__( + self, + access_token_generator: _TokenGenerator, + refresh_token_generator: _TokenGenerator | None = None, + expires_generator: Callable[[ClientMixin, str], int] | None = None, + ) -> None: ... + @staticmethod + def get_allowed_scope(client: ClientMixin, scope: str) -> str: ... + def generate( + self, + grant_type: str, + client: ClientMixin, + user=None, + scope: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... + def __call__( + self, + grant_type: str, + client: ClientMixin, + user=None, + scope: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi new file mode 100644 index 000000000000..87adfb5a67e8 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi @@ -0,0 +1,6 @@ +from authlib.oauth2.rfc6749 import TokenValidator + +class BearerTokenValidator(TokenValidator): + TOKEN_TYPE: str + def authenticate_token(self, token_string): ... + def validate_token(self, token, scopes, request) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi new file mode 100644 index 000000000000..845277693e1f --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi @@ -0,0 +1,4 @@ +from .parameters import prepare_revoke_token_request as prepare_revoke_token_request +from .revocation import RevocationEndpoint as RevocationEndpoint + +__all__ = ["prepare_revoke_token_request", "RevocationEndpoint"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi b/stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi new file mode 100644 index 000000000000..3d7b337691ca --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +_K = TypeVar("_K") + +def prepare_revoke_token_request( + token: str, token_type_hint: str | None = None, body: str | None = None, headers: dict[str, _K] | None = None +) -> tuple[str, dict[str, _K | str]]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi b/stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi new file mode 100644 index 000000000000..7bd58dc41581 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi @@ -0,0 +1,9 @@ +from authlib.oauth2.rfc6749 import TokenEndpoint + +class RevocationEndpoint(TokenEndpoint): + ENDPOINT_NAME: str + def authenticate_token(self, request, client): ... + def check_params(self, request, client) -> None: ... + def create_endpoint_response(self, request): ... + def query_token(self, token_string, token_type_hint): ... + def revoke_token(self, token, request): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi new file mode 100644 index 000000000000..5c15a9779df8 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi @@ -0,0 +1,3 @@ +from .client import AssertionClient as AssertionClient + +__all__ = ["AssertionClient"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7521/client.pyi b/stubs/Authlib/authlib/oauth2/rfc7521/client.pyi new file mode 100644 index 000000000000..c0e6f80d7f40 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7521/client.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Error + +class AssertionClient: + DEFAULT_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + token_auth_class: Incomplete + oauth_error_class = OAuth2Error + session: Incomplete + token_endpoint: Incomplete + grant_type: Incomplete + issuer: Incomplete + subject: Incomplete + audience: Incomplete + claims: Incomplete + scope: Incomplete + client_id: Incomplete + token_auth: Incomplete + leeway: Incomplete + def __init__( + self, + session, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement: str = "header", + scope=None, + client_id=None, + leeway: int = 60, + **kwargs, + ) -> None: ... + + @property + def token(self): ... + @token.setter + def token(self, token) -> None: ... + + def refresh_token(self): ... + def parse_response_token(self, resp): ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi new file mode 100644 index 000000000000..693cfd64285d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi @@ -0,0 +1,18 @@ +from .assertion import client_secret_jwt_sign as client_secret_jwt_sign, private_key_jwt_sign as private_key_jwt_sign +from .auth import ClientSecretJWT as ClientSecretJWT, PrivateKeyJWT as PrivateKeyJWT +from .client import JWTBearerClientAssertion as JWTBearerClientAssertion +from .jwt_bearer import JWTBearerGrant as JWTBearerGrant +from .token import JWTBearerTokenGenerator as JWTBearerTokenGenerator +from .validator import JWTBearerToken as JWTBearerToken, JWTBearerTokenValidator as JWTBearerTokenValidator + +__all__ = [ + "JWTBearerGrant", + "JWTBearerClientAssertion", + "client_secret_jwt_sign", + "private_key_jwt_sign", + "ClientSecretJWT", + "PrivateKeyJWT", + "JWTBearerToken", + "JWTBearerTokenGenerator", + "JWTBearerTokenValidator", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi new file mode 100644 index 000000000000..e4b5986a41ee --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi @@ -0,0 +1,27 @@ +def sign_jwt_bearer_assertion( + key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, header=None, *, alg=None, expires_in=3600 +) -> str: ... +def client_secret_jwt_sign( + client_secret, + client_id, + token_endpoint, + alg: str = "HS256", + claims=None, + *, + issued_at=None, + expires_at=None, + header=None, + expires_in=3600, +) -> str: ... +def private_key_jwt_sign( + private_key, + client_id, + token_endpoint, + alg: str = "RS256", + claims=None, + *, + issued_at=None, + expires_at=None, + header=None, + expires_in=3600, +) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi new file mode 100644 index 000000000000..c6c88e80c984 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +class ClientSecretJWT: + name: str + alg: str + token_endpoint: Incomplete + claims: Incomplete + headers: Incomplete + def __init__(self, token_endpoint=None, claims=None, headers=None, alg=None) -> None: ... + def sign(self, auth, token_endpoint) -> str: ... + def __call__(self, auth, method, uri, headers, body): ... + +class PrivateKeyJWT(ClientSecretJWT): + name: str + alg: str + def sign(self, auth, token_endpoint) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi new file mode 100644 index 000000000000..a58719ac613a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Final, overload +from typing_extensions import deprecated + +ASSERTION_TYPE: Final[str] +log: Logger + +class JWTBearerClientAssertion: + CLIENT_ASSERTION_TYPE: Final[str] + CLIENT_AUTH_METHOD: Final[str] + token_url: str | None + leeway: int + + @overload + @deprecated("The `token_url` parameter is deprecated. Override `get_audiences` instead.") + def __init__(self, token_url: str = ..., validate_jti: bool = True, leeway: int = 60) -> None: ... + @overload + def __init__(self, token_url: None = None, validate_jti: bool = True, leeway: int = 60) -> None: ... + + def __call__(self, query_client, request): ... + def verify_claims(self, claims: dict[str, Incomplete]) -> None: ... + def get_audiences(self) -> list[str]: ... + def process_assertion_claims(self, assertion, resolve_key) -> dict[str, Incomplete]: ... + def authenticate_client(self, client): ... + def extract_assertion(self, assertion: str) -> tuple[dict[str, Incomplete], Incomplete]: ... + def validate_jti(self, claims, jti): ... + def resolve_client_public_key(self, client): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi new file mode 100644 index 000000000000..aa16b6a26f90 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import ClassVar, Final + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger +JWT_BEARER_GRANT_TYPE: Final[str] + +class JWTBearerGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE = JWT_BEARER_GRANT_TYPE + CLAIMS_OPTIONS: ClassVar[dict[str, dict[str, bool]]] + LEEWAY: ClassVar[int] + @staticmethod + def sign(key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, **kwargs): ... + def verify_claims(self, claims: dict[str, Incomplete]) -> None: ... + def process_assertion_claims(self, assertion) -> dict[str, Incomplete]: ... + def extract_assertion(self, assertion: str) -> tuple[dict[str, Incomplete], dict[Incomplete, Incomplete]]: ... + def validate_token_request(self) -> None: ... + def create_token_response(self): ... + def resolve_issuer_client(self, issuer): ... + def resolve_client_public_key(self, client): ... + def authenticate_user(self, subject): ... + def get_audiences(self) -> list[str]: ... + def has_granted_permission(self, client, user) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/token.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/token.pyi new file mode 100644 index 000000000000..d6c8f3800bce --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/token.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +class JWTBearerTokenGenerator: + DEFAULT_EXPIRES_IN: int + secret_key: Incomplete + issuer: Incomplete + alg: Incomplete + def __init__(self, secret_key, issuer=None, alg: str = "RS256") -> None: ... + @staticmethod + def get_allowed_scope(client, scope): ... + @staticmethod + def get_sub_value(user) -> str: ... + def get_token_data(self, grant_type, client, expires_in, user=None, scope=None): ... + def generate(self, grant_type, client, user=None, scope=None, expires_in=None): ... + def __call__(self, grant_type, client, user=None, scope=None, expires_in=None, include_refresh_token: bool = True): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi new file mode 100644 index 000000000000..2143fe867e38 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6749 import TokenMixin +from authlib.oauth2.rfc6750 import BearerTokenValidator + +logger: Incomplete + +class JWTBearerToken(TokenMixin, dict[str, Incomplete]): + def check_client(self, client) -> bool: ... + def get_scope(self): ... + def get_expires_in(self): ... + def is_expired(self) -> bool: ... + def is_revoked(self) -> bool: ... + +class JWTBearerTokenValidator(BearerTokenValidator): + TOKEN_TYPE: str + token_cls = JWTBearerToken + public_key: Incomplete + claims_options: Incomplete + leeway: int + def __init__(self, public_key, issuer=None, realm=None, leeway: int = 60, **extra_attributes) -> None: ... + def authenticate_token(self, token_string: str) -> JWTBearerToken | None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi new file mode 100644 index 000000000000..5cd9f6b3ac5a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi @@ -0,0 +1,17 @@ +from .claims import ClientMetadataClaims as ClientMetadataClaims +from .endpoint import ClientRegistrationEndpoint as ClientRegistrationEndpoint +from .errors import ( + InvalidClientMetadataError as InvalidClientMetadataError, + InvalidRedirectURIError as InvalidRedirectURIError, + InvalidSoftwareStatementError as InvalidSoftwareStatementError, + UnapprovedSoftwareStatementError as UnapprovedSoftwareStatementError, +) + +__all__ = [ + "ClientMetadataClaims", + "ClientRegistrationEndpoint", + "InvalidRedirectURIError", + "InvalidClientMetadataError", + "InvalidSoftwareStatementError", + "UnapprovedSoftwareStatementError", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi new file mode 100644 index 000000000000..15179250147a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from typing import Any + +from authlib.jose import BaseClaims + +class ClientMetadataClaims(BaseClaims): + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + def validate_redirect_uris(self) -> None: ... + def validate_token_endpoint_auth_method(self) -> None: ... + def validate_grant_types(self) -> None: ... + def validate_response_types(self) -> None: ... + def validate_client_name(self) -> None: ... + def validate_client_uri(self) -> None: ... + def validate_logo_uri(self) -> None: ... + def validate_scope(self) -> None: ... + def validate_contacts(self) -> None: ... + def validate_tos_uri(self) -> None: ... + def validate_policy_uri(self) -> None: ... + def validate_jwks_uri(self) -> None: ... + def validate_jwks(self) -> None: ... + def validate_software_id(self) -> None: ... + def validate_software_version(self) -> None: ... + @classmethod + def get_claims_options(cls, metadata: Mapping[str, Incomplete]) -> dict[str, Any]: ... # dict values are key-dependent diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi new file mode 100644 index 000000000000..21dde441cee9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Final + +class ClientRegistrationEndpoint: + ENDPOINT_NAME: Final = "client_registration" + software_statement_alg_values_supported: Incomplete + server: Incomplete + claims_classes: list[type[Incomplete]] + def __init__(self, server=None, claims_classes: list[type[Incomplete]] | None = None) -> None: ... + def __call__(self, request) -> tuple[int, dict[Incomplete, Incomplete], list[tuple[str, str]]]: ... + def create_registration_response(self, request) -> tuple[int, dict[Incomplete, Incomplete], list[tuple[str, str]]]: ... + def extract_client_metadata(self, request) -> dict[Incomplete, Incomplete]: ... + def extract_software_statement(self, software_statement, request) -> dict[str, Incomplete]: ... + def generate_client_info(self, request) -> dict[str, Incomplete]: ... + def generate_client_registration_info(self, client, request) -> Incomplete | None: ... + def create_endpoint_request(self, request): ... + def generate_client_id(self, request) -> str: ... + def generate_client_secret(self, request) -> str: ... + def get_server_metadata(self): ... + def authenticate_token(self, request): ... + def resolve_public_key(self, request): ... + def save_client(self, client_info, client_metadata, request): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi new file mode 100644 index 000000000000..7229ef4e6ede --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi @@ -0,0 +1,13 @@ +from authlib.oauth2 import OAuth2Error + +class InvalidRedirectURIError(OAuth2Error): + error: str + +class InvalidClientMetadataError(OAuth2Error): + error: str + +class InvalidSoftwareStatementError(OAuth2Error): + error: str + +class UnapprovedSoftwareStatementError(OAuth2Error): + error: str diff --git a/stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi new file mode 100644 index 000000000000..e4ff814ea64e --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi @@ -0,0 +1,3 @@ +from .endpoint import ClientConfigurationEndpoint as ClientConfigurationEndpoint + +__all__ = ["ClientConfigurationEndpoint"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi new file mode 100644 index 000000000000..fce1d9d54e94 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from typing import Final + +class ClientConfigurationEndpoint: + ENDPOINT_NAME: Final = "client_configuration" + server: Incomplete + claims_classes: list[type[Incomplete]] + def __init__(self, server=None, claims_classes: list[type[Incomplete]] | None = None) -> None: ... + def __call__(self, request): ... + def create_configuration_response(self, request): ... + def create_endpoint_request(self, request): ... + def create_read_client_response(self, client, request): ... + def create_delete_client_response(self, client, request): ... + def create_update_client_response(self, client, request): ... + def extract_client_metadata(self, request): ... + def introspect_client(self, client): ... + def generate_client_registration_info(self, client, request): ... + def authenticate_token(self, request): ... + def authenticate_client(self, request): ... + def revoke_access_token(self, token, request): ... + def check_permission(self, client, request): ... + def delete_client(self, client, request): ... + def update_client(self, client, client_metadata, request): ... + def get_server_metadata(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi new file mode 100644 index 000000000000..18a2be1b0e43 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi @@ -0,0 +1,3 @@ +from .challenge import CodeChallenge as CodeChallenge, create_s256_code_challenge as create_s256_code_challenge + +__all__ = ["CodeChallenge", "create_s256_code_challenge"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi b/stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi new file mode 100644 index 000000000000..e3d07e846686 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi @@ -0,0 +1,23 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Final + +CODE_VERIFIER_PATTERN: Final[re.Pattern[str]] +CODE_CHALLENGE_PATTERN: Final[re.Pattern[str]] + +def create_s256_code_challenge(code_verifier): ... +def compare_plain_code_challenge(code_verifier, code_challenge): ... +def compare_s256_code_challenge(code_verifier, code_challenge): ... + +class CodeChallenge: + DEFAULT_CODE_CHALLENGE_METHOD: str + SUPPORTED_CODE_CHALLENGE_METHOD: list[str] + CODE_CHALLENGE_METHODS: dict[str, Callable[[Incomplete, Incomplete], Incomplete]] + required: bool + def __init__(self, required: bool = True) -> None: ... + def __call__(self, grant) -> None: ... + def validate_code_challenge(self, grant, redirect_uri) -> None: ... + def validate_code_verifier(self, grant, result) -> None: ... + def get_authorization_code_challenge(self, authorization_code): ... + def get_authorization_code_challenge_method(self, authorization_code): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi new file mode 100644 index 000000000000..8b48b0ce9476 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi @@ -0,0 +1,5 @@ +from .introspection import IntrospectionEndpoint as IntrospectionEndpoint +from .models import IntrospectionToken as IntrospectionToken +from .token_validator import IntrospectTokenValidator as IntrospectTokenValidator + +__all__ = ["IntrospectionEndpoint", "IntrospectionToken", "IntrospectTokenValidator"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi new file mode 100644 index 000000000000..58d178475a51 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi @@ -0,0 +1,11 @@ +from authlib.oauth2.rfc6749 import TokenEndpoint + +class IntrospectionEndpoint(TokenEndpoint): + ENDPOINT_NAME: str + def authenticate_token(self, request, client): ... + def check_params(self, request, client) -> None: ... + def create_endpoint_response(self, request): ... + def create_introspection_payload(self, token): ... + def check_permission(self, token, client, request): ... + def query_token(self, token_string, token_type_hint): ... + def introspect_token(self, token): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/models.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/models.pyi new file mode 100644 index 000000000000..bb583baaa4f4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/models.pyi @@ -0,0 +1,8 @@ +from authlib.oauth2.rfc6749 import TokenMixin + +class IntrospectionToken(dict[str, object], TokenMixin): + def get_client_id(self): ... + def get_scope(self): ... + def get_expires_in(self): ... + def get_expires_at(self): ... + def __getattr__(self, key): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi new file mode 100644 index 000000000000..8b7a74400ae2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi @@ -0,0 +1,7 @@ +from authlib.oauth2.rfc6749 import TokenValidator + +class IntrospectTokenValidator(TokenValidator): + TOKEN_TYPE: str + def introspect_token(self, token_string): ... + def authenticate_token(self, token_string): ... + def validate_token(self, token, scopes, request) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi new file mode 100644 index 000000000000..b7b5b3a03967 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi @@ -0,0 +1,4 @@ +from .models import AuthorizationServerMetadata as AuthorizationServerMetadata +from .well_known import get_well_known_url as get_well_known_url + +__all__ = ["AuthorizationServerMetadata", "get_well_known_url"] diff --git a/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi b/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi new file mode 100644 index 000000000000..54dec12ec5ea --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +class AuthorizationServerMetadata(dict[str, object]): + REGISTRY_KEYS: list[str] + def validate_issuer(self) -> None: ... + def validate_authorization_endpoint(self) -> None: ... + def validate_token_endpoint(self) -> None: ... + def validate_jwks_uri(self) -> None: ... + def validate_registration_endpoint(self) -> None: ... + def validate_scopes_supported(self) -> None: ... + def validate_response_types_supported(self) -> None: ... + def validate_response_modes_supported(self) -> None: ... + def validate_grant_types_supported(self) -> None: ... + def validate_token_endpoint_auth_methods_supported(self) -> None: ... + def validate_token_endpoint_auth_signing_alg_values_supported(self) -> None: ... + def validate_service_documentation(self) -> None: ... + def validate_ui_locales_supported(self) -> None: ... + def validate_op_policy_uri(self) -> None: ... + def validate_op_tos_uri(self) -> None: ... + def validate_revocation_endpoint(self) -> None: ... + def validate_revocation_endpoint_auth_methods_supported(self) -> None: ... + def validate_revocation_endpoint_auth_signing_alg_values_supported(self) -> None: ... + def validate_introspection_endpoint(self) -> None: ... + def validate_introspection_endpoint_auth_methods_supported(self) -> None: ... + def validate_introspection_endpoint_auth_signing_alg_values_supported(self) -> None: ... + def validate_code_challenge_methods_supported(self) -> None: ... + @property + def response_modes_supported(self): ... + @property + def grant_types_supported(self): ... + @property + def token_endpoint_auth_methods_supported(self): ... + @property + def revocation_endpoint_auth_methods_supported(self): ... + @property + def introspection_endpoint_auth_methods_supported(self): ... + def validate(self, metadata_classes: list[type[Incomplete]] | None = None) -> None: ... + def __getattr__(self, key): ... + +def validate_array_value(metadata, key) -> None: ... +def validate_language_tags_array(metadata, key) -> None: ... +def validate_boolean_value(metadata, key) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi b/stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi new file mode 100644 index 000000000000..bcf7aae84e28 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi @@ -0,0 +1 @@ +def get_well_known_url(issuer: str, external: bool = False, suffix: str = "oauth-authorization-server") -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi new file mode 100644 index 000000000000..669437e26bb9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi @@ -0,0 +1,19 @@ +from .device_code import DEVICE_CODE_GRANT_TYPE as DEVICE_CODE_GRANT_TYPE, DeviceCodeGrant as DeviceCodeGrant +from .endpoint import DeviceAuthorizationEndpoint as DeviceAuthorizationEndpoint +from .errors import ( + AuthorizationPendingError as AuthorizationPendingError, + ExpiredTokenError as ExpiredTokenError, + SlowDownError as SlowDownError, +) +from .models import DeviceCredentialDict as DeviceCredentialDict, DeviceCredentialMixin as DeviceCredentialMixin + +__all__ = [ + "DeviceAuthorizationEndpoint", + "DeviceCodeGrant", + "DEVICE_CODE_GRANT_TYPE", + "DeviceCredentialMixin", + "DeviceCredentialDict", + "AuthorizationPendingError", + "SlowDownError", + "ExpiredTokenError", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi new file mode 100644 index 000000000000..da0bd0bd1bb4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger +DEVICE_CODE_GRANT_TYPE: str + +class DeviceCodeGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE = DEVICE_CODE_GRANT_TYPE + TOKEN_ENDPOINT_AUTH_METHODS: Incomplete + def validate_token_request(self) -> None: ... + def create_token_response(self): ... + def validate_device_credential(self, credential): ... + def query_device_credential(self, device_code): ... + def query_user_grant(self, user_code): ... + def should_slow_down(self, credential): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi new file mode 100644 index 000000000000..06d0d884a926 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +class DeviceAuthorizationEndpoint: + ENDPOINT_NAME: str + CLIENT_AUTH_METHODS: Incomplete + USER_CODE_TYPE: str + EXPIRES_IN: int + INTERVAL: int + server: Incomplete + def __init__(self, server) -> None: ... + def __call__(self, request): ... + def create_endpoint_request(self, request): ... + def authenticate_client(self, request): ... + def create_endpoint_response(self, request): ... + def generate_user_code(self): ... + def generate_device_code(self): ... + def get_verification_uri(self): ... + def save_device_credential(self, client_id, scope, data): ... + +def create_string_user_code(): ... +def create_digital_user_code(): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi new file mode 100644 index 000000000000..dc3803877039 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi @@ -0,0 +1,10 @@ +from authlib.oauth2 import OAuth2Error + +class AuthorizationPendingError(OAuth2Error): + error: str + +class SlowDownError(OAuth2Error): + error: str + +class ExpiredTokenError(OAuth2Error): + error: str diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/models.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/models.pyi new file mode 100644 index 000000000000..a9b987cd86f5 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/models.pyi @@ -0,0 +1,13 @@ +class DeviceCredentialMixin: + def get_client_id(self): ... + def get_scope(self): ... + def get_user_code(self): ... + def is_expired(self): ... + +class DeviceCredentialDict(dict[str, object], DeviceCredentialMixin): + def get_client_id(self): ... + def get_scope(self): ... + def get_user_code(self): ... + def get_nonce(self): ... + def get_auth_time(self): ... + def is_expired(self): ... diff --git a/stdlib/@python2/pydoc_data/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc8693/__init__.pyi similarity index 100% rename from stdlib/@python2/pydoc_data/__init__.pyi rename to stubs/Authlib/authlib/oauth2/rfc8693/__init__.pyi diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi new file mode 100644 index 000000000000..f8a3418f836d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi @@ -0,0 +1,6 @@ +from .introspection import JWTIntrospectionEndpoint as JWTIntrospectionEndpoint +from .revocation import JWTRevocationEndpoint as JWTRevocationEndpoint +from .token import JWTBearerTokenGenerator as JWTBearerTokenGenerator +from .token_validator import JWTBearerTokenValidator as JWTBearerTokenValidator + +__all__ = ["JWTBearerTokenGenerator", "JWTBearerTokenValidator", "JWTIntrospectionEndpoint", "JWTRevocationEndpoint"] diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi new file mode 100644 index 000000000000..d91f4321a212 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable + +from authlib.jose import JWTClaims + +# Inherits from joserfc.jwt.JWTClaimsRegistry +class JWTAccessTokenClaimsValidator: + def validate_auth_time(self, auth_time) -> None: ... + def validate_amr(self, amr) -> None: ... + +class JWTAccessTokenClaims(JWTClaims): + registry_cls = JWTAccessTokenClaimsValidator + def validate(self, *, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... # type: ignore[override] diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi new file mode 100644 index 000000000000..c54599bf0a83 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from ..rfc7662 import IntrospectionEndpoint +from .claims import JWTAccessTokenClaims + +class JWTIntrospectionEndpoint(IntrospectionEndpoint): + ENDPOINT_NAME: str + issuer: Incomplete + def __init__(self, issuer, server=None, *args, **kwargs) -> None: ... + def create_endpoint_response(self, request): ... + def authenticate_token(self, request, client) -> JWTAccessTokenClaims | None: ... + def create_introspection_payload(self, token: JWTAccessTokenClaims) -> dict[str, Incomplete]: ... + def get_jwks(self): ... + def get_username(self, user_id: str) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi new file mode 100644 index 000000000000..befb05a1702d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +from authlib.oauth2.rfc7009 import RevocationEndpoint + +class JWTRevocationEndpoint(RevocationEndpoint): + issuer: Incomplete + def __init__(self, issuer, server=None, *args, **kwargs) -> None: ... + def authenticate_token(self, request, client) -> Never: ... + def get_jwks(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi new file mode 100644 index 000000000000..6b559345262d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +class JWTBearerTokenGenerator(BearerTokenGenerator): + issuer: Incomplete + alg: Incomplete + def __init__(self, issuer, alg: str = "RS256", refresh_token_generator=None, expires_generator=None) -> None: ... + def get_jwks(self): ... + def get_extra_claims(self, client, grant_type, user, scope): ... + def get_audiences(self, client, user, scope) -> str | list[str]: ... + def get_acr(self, user) -> str | None: ... + def get_auth_time(self, user) -> int | None: ... + def get_amr(self, user) -> list[str] | None: ... + def get_jti(self, client, grant_type, user, scope) -> str: ... + # Override seems safe, but mypy doesn't like that it's a callable protocol in the base + def access_token_generator(self, client, grant_type, user, scope) -> str: ... # type: ignore[override] diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi new file mode 100644 index 000000000000..c893ec9349f1 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6750.validator import BearerTokenValidator + +from .claims import JWTAccessTokenClaims + +class JWTBearerTokenValidator(BearerTokenValidator): + issuer: Incomplete + resource_server: Incomplete + def __init__(self, issuer, resource_server, *args, **kwargs) -> None: ... + def get_jwks(self): ... + def validate_iss(self, claims, iss: str) -> bool: ... + def authenticate_token(self, token_string) -> JWTAccessTokenClaims: ... + def validate_token( + self, token: JWTAccessTokenClaims, scopes, request, groups=None, roles=None, entitlements=None + ) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi new file mode 100644 index 000000000000..8a6295782b36 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi @@ -0,0 +1,5 @@ +from .authorization_server import JWTAuthenticationRequest as JWTAuthenticationRequest +from .discovery import AuthorizationServerMetadata as AuthorizationServerMetadata +from .registration import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["AuthorizationServerMetadata", "JWTAuthenticationRequest", "ClientMetadataClaims"] diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi new file mode 100644 index 000000000000..5461a00b654c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from ..rfc6749 import AuthorizationServer, ClientMixin +from ..rfc6749.requests import OAuth2Request + +class JWTAuthenticationRequest: + claims_validator: Incomplete + support_request: bool + support_request_uri: bool + def __init__(self, support_request: bool = True, support_request_uri: bool = True) -> None: ... + def __call__(self, authorization_server: AuthorizationServer) -> None: ... + def get_request_object_signing_algorithms(self, client) -> list[str]: ... + def parse_authorization_request(self, authorization_server: AuthorizationServer, request: OAuth2Request) -> None: ... + def get_request_object(self, request_uri: str): ... + def resolve_client_public_key(self, client: ClientMixin): ... + def get_server_metadata(self) -> dict[str, Incomplete]: ... + def get_client_require_signed_request_object(self, client: ClientMixin) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi new file mode 100644 index 000000000000..92b57602e5ef --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi @@ -0,0 +1,3 @@ +class AuthorizationServerMetadata(dict[str, object]): + REGISTRY_KEYS: list[str] + def validate_require_signed_request_object(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi new file mode 100644 index 000000000000..a0bcd96e173b --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi @@ -0,0 +1,23 @@ +from ..base import OAuth2Error + +__all__ = ["InvalidRequestUriError", "InvalidRequestObjectError", "RequestNotSupportedError", "RequestUriNotSupportedError"] + +class InvalidRequestUriError(OAuth2Error): + error: str + description: str + status_code: int + +class InvalidRequestObjectError(OAuth2Error): + error: str + description: str + status_code: int + +class RequestNotSupportedError(OAuth2Error): + error: str + description: str + status_code: int + +class RequestUriNotSupportedError(OAuth2Error): + error: str + description: str + status_code: int diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi new file mode 100644 index 000000000000..66af83e065b4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable + +from authlib.jose import BaseClaims + +class ClientMetadataClaims(BaseClaims): + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + def validate_require_signed_request_object(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi new file mode 100644 index 000000000000..559a1c9263f4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi @@ -0,0 +1,4 @@ +from .discovery import AuthorizationServerMetadata as AuthorizationServerMetadata +from .parameter import IssuerParameter as IssuerParameter + +__all__ = ["AuthorizationServerMetadata", "IssuerParameter"] diff --git a/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi b/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi new file mode 100644 index 000000000000..654d2d31e28a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +class AuthorizationServerMetadata(dict[str, Incomplete]): + REGISTRY_KEYS: list[str] + def validate_authorization_response_iss_parameter_supported(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi b/stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi new file mode 100644 index 000000000000..70e2ee20b7f2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi @@ -0,0 +1,4 @@ +class IssuerParameter: + def __call__(self, authorization_server) -> None: ... + def add_issuer_parameter(self, authorization_server, response) -> None: ... + def get_issuer(self) -> str | None: ... diff --git a/stdlib/@python2/wsgiref/__init__.pyi b/stubs/Authlib/authlib/oidc/__init__.pyi similarity index 100% rename from stdlib/@python2/wsgiref/__init__.pyi rename to stubs/Authlib/authlib/oidc/__init__.pyi diff --git a/stubs/Authlib/authlib/oidc/core/__init__.pyi b/stubs/Authlib/authlib/oidc/core/__init__.pyi new file mode 100644 index 000000000000..0763373dc8ff --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/__init__.pyi @@ -0,0 +1,31 @@ +from .claims import ( + CodeIDToken as CodeIDToken, + HybridIDToken as HybridIDToken, + IDToken as IDToken, + ImplicitIDToken as ImplicitIDToken, + UserInfo as UserInfo, + get_claim_cls_by_response_type as get_claim_cls_by_response_type, +) +from .grants import ( + OpenIDCode as OpenIDCode, + OpenIDHybridGrant as OpenIDHybridGrant, + OpenIDImplicitGrant as OpenIDImplicitGrant, + OpenIDToken as OpenIDToken, +) +from .models import AuthorizationCodeMixin as AuthorizationCodeMixin +from .userinfo import UserInfoEndpoint as UserInfoEndpoint + +__all__ = [ + "AuthorizationCodeMixin", + "IDToken", + "CodeIDToken", + "ImplicitIDToken", + "HybridIDToken", + "UserInfo", + "UserInfoEndpoint", + "get_claim_cls_by_response_type", + "OpenIDToken", + "OpenIDCode", + "OpenIDHybridGrant", + "OpenIDImplicitGrant", +] diff --git a/stubs/Authlib/authlib/oidc/core/claims.pyi b/stubs/Authlib/authlib/oidc/core/claims.pyi new file mode 100644 index 000000000000..f9a24cfbcfa6 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/claims.pyi @@ -0,0 +1,36 @@ +from collections.abc import Callable + +from authlib.jose import JWTClaims + +__all__ = ["IDToken", "CodeIDToken", "ImplicitIDToken", "HybridIDToken", "UserInfo", "get_claim_cls_by_response_type"] + +class IDToken(JWTClaims): + ESSENTIAL_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + def validate_auth_time(self) -> None: ... + def validate_nonce(self) -> None: ... + def validate_amr(self) -> None: ... + def validate_azp(self) -> None: ... + def validate_at_hash(self) -> None: ... + +class CodeIDToken(IDToken): + RESPONSE_TYPES: tuple[str, ...] + +class ImplicitIDToken(IDToken): + RESPONSE_TYPES: tuple[str, ...] + ESSENTIAL_CLAIMS: list[str] + def validate_at_hash(self) -> None: ... + +class HybridIDToken(ImplicitIDToken): + RESPONSE_TYPES: tuple[str, ...] + def validate(self, now=None, leeway: int = 0) -> None: ... + def validate_c_hash(self) -> None: ... + +class UserInfo(dict[str, object]): + REGISTERED_CLAIMS: list[str] + SCOPES_CLAIMS_MAPPING: dict[str, list[str]] + def validate_locale(self) -> None: ... + def filter(self, scope: str) -> UserInfo: ... + def __getattr__(self, key): ... + +def get_claim_cls_by_response_type(response_type) -> type: ... diff --git a/stubs/Authlib/authlib/oidc/core/errors.pyi b/stubs/Authlib/authlib/oidc/core/errors.pyi new file mode 100644 index 000000000000..a7132d25fd7a --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/errors.pyi @@ -0,0 +1,28 @@ +from authlib.oauth2 import OAuth2Error + +class InteractionRequiredError(OAuth2Error): + error: str + +class LoginRequiredError(OAuth2Error): + error: str + +class AccountSelectionRequiredError(OAuth2Error): + error: str + +class ConsentRequiredError(OAuth2Error): + error: str + +class InvalidRequestURIError(OAuth2Error): + error: str + +class InvalidRequestObjectError(OAuth2Error): + error: str + +class RequestNotSupportedError(OAuth2Error): + error: str + +class RequestURINotSupportedError(OAuth2Error): + error: str + +class RegistrationNotSupportedError(OAuth2Error): + error: str diff --git a/stubs/Authlib/authlib/oidc/core/grants/__init__.pyi b/stubs/Authlib/authlib/oidc/core/grants/__init__.pyi new file mode 100644 index 000000000000..d4bc9d9b42e7 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/__init__.pyi @@ -0,0 +1,5 @@ +from .code import OpenIDCode as OpenIDCode, OpenIDToken as OpenIDToken +from .hybrid import OpenIDHybridGrant as OpenIDHybridGrant +from .implicit import OpenIDImplicitGrant as OpenIDImplicitGrant + +__all__ = ["OpenIDToken", "OpenIDCode", "OpenIDImplicitGrant", "OpenIDHybridGrant"] diff --git a/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi b/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi new file mode 100644 index 000000000000..ba67813c9836 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Request + +class LegacyMixin: + DEFAULT_EXPIRES_IN: int + def resolve_client_private_key(self, client): ... + def get_client_algorithm(self, client): ... + def get_client_claims(self, client) -> dict[str, Incomplete]: ... + def get_encode_header(self, client) -> dict[str, Incomplete]: ... + def get_compatible_claims(self, request: OAuth2Request) -> dict[str, Incomplete]: ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/code.pyi b/stubs/Authlib/authlib/oidc/core/grants/code.pyi new file mode 100644 index 000000000000..6c29a87897f2 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/code.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import BaseGrant +from authlib.oidc.core import UserInfo + +from ..models import AuthorizationCodeMixin +from ._legacy import LegacyMixin + +log: Logger + +class OpenIDToken(LegacyMixin): + def get_authorization_code_claims(self, authorization_code: AuthorizationCodeMixin) -> dict[str, Incomplete]: ... + def generate_user_info(self, user, scope: str) -> UserInfo: ... + def encode_id_token(self, token, request: OAuth2Request) -> str: ... + def process_token(self, grant: BaseGrant, response) -> dict[str, Incomplete]: ... + def __call__(self, grant: BaseGrant) -> None: ... + +class OpenIDCode(OpenIDToken): + require_nonce: bool + def __init__(self, require_nonce: bool = False) -> None: ... + def exists_nonce(self, nonce: str, request: OAuth2Request) -> bool: ... + def validate_openid_authorization_request(self, grant: BaseGrant, redirect_uri) -> None: ... + def __call__(self, grant: BaseGrant) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi b/stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi new file mode 100644 index 000000000000..f2652cc1b9cc --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oidc.core import OpenIDImplicitGrant + +log: Logger + +class OpenIDHybridGrant(OpenIDImplicitGrant): + AUTHORIZATION_CODE_LENGTH: int + RESPONSE_TYPES: Incomplete + GRANT_TYPE: str + DEFAULT_RESPONSE_MODE: str + def generate_authorization_code(self) -> str: ... + def save_authorization_code(self, code, request): ... + def validate_authorization_request(self) -> str: ... + def create_granted_params(self, grant_user) -> list[tuple[str, str]]: ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi b/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi new file mode 100644 index 000000000000..959a688b0e35 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2.rfc6749 import ImplicitGrant +from authlib.oidc.core import UserInfo + +from ._legacy import LegacyMixin + +log: Logger + +class OpenIDImplicitGrant(LegacyMixin, ImplicitGrant): + RESPONSE_TYPES: Incomplete + DEFAULT_RESPONSE_MODE: str + def exists_nonce(self, nonce, request) -> bool: ... + def generate_user_info(self, user, scope) -> UserInfo: ... + def get_audiences(self, request) -> list[Incomplete]: ... + def validate_authorization_request(self) -> str: ... + def validate_consent_request(self) -> str: ... + def create_authorization_response(self, redirect_uri, grant_user): ... + def create_granted_params(self, grant_user) -> list[tuple[str, Incomplete]]: ... + def process_implicit_token(self, token, code=None): ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/util.pyi b/stubs/Authlib/authlib/oidc/core/grants/util.pyi new file mode 100644 index 000000000000..fe07d01da6f3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/util.pyi @@ -0,0 +1,33 @@ +from _typeshed import ReadableBuffer +from collections.abc import Collection, Iterable +from typing import Literal, SupportsBytes, SupportsIndex, overload + +from authlib.oidc.core import UserInfo + +def is_openid_scope(scope: Collection[str] | str | None) -> bool: ... +def validate_request_prompt(grant, redirect_uri: str, redirect_fragment: bool = False): ... +def validate_nonce(request, exists_nonce, required: bool = False): ... +def generate_id_token( + token: dict[str, str | int], + user_info: UserInfo, + key: str, + iss: str, + aud: list[str], + alg: str = "RS256", + exp: int = 3600, + nonce: str | None = None, + auth_time: int | None = None, + acr: str | None = None, + amr: list[str] | None = None, + code: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + kid: str | None = None, +) -> str: ... + +@overload +def create_response_mode_response( + redirect_uri: str, params: Iterable[tuple[str, str]], response_mode: Literal["form_post"] +) -> tuple[Literal[200], str, list[tuple[str, str]]]: ... +@overload # `params` can accept dict in another mode +def create_response_mode_response( + redirect_uri: str, params: Iterable[tuple[str, str]] | dict[str, str], response_mode: Literal["query", "fragment"] +) -> tuple[Literal[302], str, list[tuple[str, str]]]: ... diff --git a/stubs/Authlib/authlib/oidc/core/models.pyi b/stubs/Authlib/authlib/oidc/core/models.pyi new file mode 100644 index 000000000000..d204f91d0cb3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/models.pyi @@ -0,0 +1,7 @@ +from authlib.oauth2.rfc6749 import AuthorizationCodeMixin as _AuthorizationCodeMixin + +class AuthorizationCodeMixin(_AuthorizationCodeMixin): + def get_nonce(self) -> str | None: ... + def get_auth_time(self) -> int | None: ... + def get_acr(self) -> str: ... + def get_amr(self) -> list[str]: ... diff --git a/stubs/Authlib/authlib/oidc/core/userinfo.pyi b/stubs/Authlib/authlib/oidc/core/userinfo.pyi new file mode 100644 index 000000000000..cf3bf956cba3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/userinfo.pyi @@ -0,0 +1,19 @@ +from authlib.oauth2.rfc6749.authorization_server import AuthorizationServer +from authlib.oauth2.rfc6749.requests import OAuth2Request +from authlib.oauth2.rfc6749.resource_protector import ResourceProtector + +from .claims import UserInfo + +class UserInfoEndpoint: + ENDPOINT_NAME: str + server: AuthorizationServer | None + resource_protector: ResourceProtector | None + def __init__( + self, server: AuthorizationServer | None = None, resource_protector: ResourceProtector | None = None + ) -> None: ... + def create_endpoint_request(self, request: OAuth2Request) -> OAuth2Request: ... + def __call__(self, request: OAuth2Request) -> tuple[int, str | UserInfo, list[tuple[str, str]]]: ... + def get_supported_algorithms(self) -> list[str]: ... + def generate_user_info(self, user, scope: str) -> UserInfo: ... + def get_issuer(self) -> str: ... + def resolve_private_key(self): ... diff --git a/stubs/Authlib/authlib/oidc/core/util.pyi b/stubs/Authlib/authlib/oidc/core/util.pyi new file mode 100644 index 000000000000..5c0a4bff37f6 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/util.pyi @@ -0,0 +1,7 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import SupportsBytes, SupportsIndex + +def create_half_hash( + s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, alg: str +) -> bytes | None: ... diff --git a/stubs/Authlib/authlib/oidc/discovery/__init__.pyi b/stubs/Authlib/authlib/oidc/discovery/__init__.pyi new file mode 100644 index 000000000000..84d76b371134 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/discovery/__init__.pyi @@ -0,0 +1,4 @@ +from .models import OpenIDProviderMetadata as OpenIDProviderMetadata +from .well_known import get_well_known_url as get_well_known_url + +__all__ = ["OpenIDProviderMetadata", "get_well_known_url"] diff --git a/stubs/Authlib/authlib/oidc/discovery/models.pyi b/stubs/Authlib/authlib/oidc/discovery/models.pyi new file mode 100644 index 000000000000..63f2211780fc --- /dev/null +++ b/stubs/Authlib/authlib/oidc/discovery/models.pyi @@ -0,0 +1,34 @@ +from authlib.oauth2.rfc8414 import AuthorizationServerMetadata + +class OpenIDProviderMetadata(AuthorizationServerMetadata): + REGISTRY_KEYS: list[str] + def validate_jwks_uri(self): ... + def validate_acr_values_supported(self) -> None: ... + def validate_subject_types_supported(self) -> None: ... + def validate_id_token_signing_alg_values_supported(self) -> None: ... + def validate_id_token_encryption_alg_values_supported(self) -> None: ... + def validate_id_token_encryption_enc_values_supported(self) -> None: ... + def validate_userinfo_signing_alg_values_supported(self) -> None: ... + def validate_userinfo_encryption_alg_values_supported(self) -> None: ... + def validate_userinfo_encryption_enc_values_supported(self) -> None: ... + def validate_request_object_signing_alg_values_supported(self) -> None: ... + def validate_request_object_encryption_alg_values_supported(self) -> None: ... + def validate_request_object_encryption_enc_values_supported(self) -> None: ... + def validate_display_values_supported(self) -> None: ... + def validate_claim_types_supported(self) -> None: ... + def validate_claims_supported(self) -> None: ... + def validate_claims_locales_supported(self) -> None: ... + def validate_claims_parameter_supported(self) -> None: ... + def validate_request_parameter_supported(self) -> None: ... + def validate_request_uri_parameter_supported(self) -> None: ... + def validate_require_request_uri_registration(self) -> None: ... + @property + def claim_types_supported(self): ... + @property + def claims_parameter_supported(self): ... + @property + def request_parameter_supported(self): ... + @property + def request_uri_parameter_supported(self): ... + @property + def require_request_uri_registration(self): ... diff --git a/stubs/Authlib/authlib/oidc/discovery/well_known.pyi b/stubs/Authlib/authlib/oidc/discovery/well_known.pyi new file mode 100644 index 000000000000..b10c03b65439 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/discovery/well_known.pyi @@ -0,0 +1 @@ +def get_well_known_url(issuer: str, external: bool = False) -> str: ... diff --git a/stubs/Authlib/authlib/oidc/registration/__init__.pyi b/stubs/Authlib/authlib/oidc/registration/__init__.pyi new file mode 100644 index 000000000000..e0fca8da8da3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/registration/__init__.pyi @@ -0,0 +1,3 @@ +from .claims import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["ClientMetadataClaims"] diff --git a/stubs/Authlib/authlib/oidc/registration/claims.pyi b/stubs/Authlib/authlib/oidc/registration/claims.pyi new file mode 100644 index 000000000000..5327d0704d7e --- /dev/null +++ b/stubs/Authlib/authlib/oidc/registration/claims.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping + +from authlib.jose import BaseClaims + +class ClientMetadataClaims(BaseClaims): + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + # The "cls" argument is called "self" in the actual implementation, + # but stubtest will not allow that. + @classmethod + def get_claims_options(cls, metadata: Mapping[str, Incomplete]) -> dict[str, Incomplete]: ... + def validate_token_endpoint_auth_signing_alg(self) -> None: ... + def validate_application_type(self) -> None: ... + def validate_sector_identifier_uri(self) -> None: ... + def validate_subject_type(self) -> None: ... + def validate_id_token_signed_response_alg(self) -> None: ... + def validate_id_token_encrypted_response_alg(self) -> None: ... + def validate_id_token_encrypted_response_enc(self) -> None: ... + def validate_userinfo_signed_response_alg(self) -> None: ... + def validate_userinfo_encrypted_response_alg(self) -> None: ... + def validate_userinfo_encrypted_response_enc(self) -> None: ... + def validate_default_max_age(self) -> None: ... + def validate_require_auth_time(self) -> None: ... + def validate_default_acr_values(self) -> None: ... + def validate_initiate_login_uri(self) -> None: ... + def validate_request_object_signing_alg(self) -> None: ... + def validate_request_object_encryption_alg(self) -> None: ... + def validate_request_object_encryption_enc(self) -> None: ... + def validate_request_uris(self) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi new file mode 100644 index 000000000000..1da8effafddf --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi @@ -0,0 +1,5 @@ +from .discovery import OpenIDProviderMetadata as OpenIDProviderMetadata +from .end_session import EndSessionEndpoint as EndSessionEndpoint, EndSessionRequest as EndSessionRequest +from .registration import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["EndSessionEndpoint", "EndSessionRequest", "ClientMetadataClaims", "OpenIDProviderMetadata"] diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi new file mode 100644 index 000000000000..b492c7e6654a --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +class OpenIDProviderMetadata(dict[str, Incomplete]): + REGISTRY_KEYS: list[str] + def validate_end_session_endpoint(self) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi new file mode 100644 index 000000000000..85e56a5465e3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from dataclasses import dataclass + +from authlib.oauth2.rfc6749.endpoint import Endpoint, EndpointRequest +from authlib.oauth2.rfc6749.requests import OAuth2Request + +@dataclass +class EndSessionRequest(EndpointRequest): + id_token_claims: dict[Incomplete, Incomplete] | None = None + redirect_uri: str | None = None + logout_hint: str | None = None + ui_locales: str | None = None + @property + def needs_confirmation(self) -> bool: ... + +class EndSessionEndpoint(Endpoint): + ENDPOINT_NAME: str + def validate_request(self, request: OAuth2Request) -> EndSessionRequest: ... + def create_response(self, validated_request: EndSessionRequest) -> tuple[int, Incomplete, list[tuple[str, str]]] | None: ... # type: ignore[override] + def resolve_client_from_id_token_claims(self, id_token_claims: dict[Incomplete, Incomplete]) -> Incomplete | None: ... + def is_post_logout_redirect_uri_legitimate( + self, request: OAuth2Request, post_logout_redirect_uri: str, client, logout_hint: str | None + ) -> bool: ... + def get_server_jwks(self): ... + def get_algorithms(self) -> list[str]: ... + def end_session(self, end_session_request: EndSessionRequest) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi new file mode 100644 index 000000000000..6fe844ac1df3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable + +from authlib.oauth2.claims import BaseClaims + +class ClientMetadataClaims(BaseClaims): + REGISTERED_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... diff --git a/stubs/DateTimeRange/METADATA.toml b/stubs/DateTimeRange/METADATA.toml deleted file mode 100644 index f522021080f9..000000000000 --- a/stubs/DateTimeRange/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "1.2.*" -requires = ["types-python-dateutil"] diff --git a/stubs/DateTimeRange/datetimerange/__init__.pyi b/stubs/DateTimeRange/datetimerange/__init__.pyi deleted file mode 100644 index b38cad3bf897..000000000000 --- a/stubs/DateTimeRange/datetimerange/__init__.pyi +++ /dev/null @@ -1,45 +0,0 @@ -import datetime -from typing import Iterable - -from dateutil.relativedelta import relativedelta - -class DateTimeRange(object): - NOT_A_TIME_STR: str - start_time_format: str - end_time_format: str - is_output_elapse: bool - separator: str - def __init__( - self, - start_datetime: datetime.datetime | str | None = ..., - end_datetime: datetime.datetime | str | None = ..., - start_time_format: str = ..., - end_time_format: str = ..., - ) -> None: ... - def __eq__(self, other: object) -> bool: ... - def __ne__(self, other: object) -> bool: ... - def __add__(self, other: datetime.timedelta) -> DateTimeRange: ... - def __iadd__(self, other: datetime.timedelta) -> DateTimeRange: ... - def __sub__(self, other: datetime.timedelta) -> DateTimeRange: ... - def __isub__(self, other: datetime.timedelta) -> DateTimeRange: ... - def __contains__(self, x: datetime.timedelta | DateTimeRange | str) -> bool: ... - @property - def start_datetime(self) -> datetime.datetime: ... - @property - def end_datetime(self) -> datetime.datetime: ... - @property - def timedelta(self) -> datetime.timedelta: ... - def is_set(self) -> bool: ... - def validate_time_inversion(self) -> None: ... - def is_valid_timerange(self) -> bool: ... - def is_intersection(self, x: DateTimeRange) -> bool: ... - def get_start_time_str(self) -> str: ... - def get_end_time_str(self) -> str: ... - def get_timedelta_second(self) -> float: ... - def set_start_datetime(self, value: datetime.datetime | str | None, timezone: str | None = ...) -> None: ... - def set_end_datetime(self, value: datetime.datetime | str | None, timezone: str | None = ...) -> None: ... - def set_time_range(self, start: datetime.datetime | str | None, end: datetime.datetime | str | None) -> None: ... - def range(self, step: datetime.timedelta | relativedelta) -> Iterable[datetime.datetime]: ... - def intersection(self, x: DateTimeRange) -> DateTimeRange: ... - def encompass(self, x: DateTimeRange) -> DateTimeRange: ... - def truncate(self, percentage: float) -> None: ... diff --git a/stubs/Deprecated/@tests/stubtest_allowlist.txt b/stubs/Deprecated/@tests/stubtest_allowlist.txt deleted file mode 100644 index 5aea61c8a46d..000000000000 --- a/stubs/Deprecated/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,3 +0,0 @@ -deprecated.sphinx.SphinxAdapter.__init__ -deprecated.sphinx.versionadded -deprecated.sphinx.versionchanged diff --git a/stubs/Deprecated/METADATA.toml b/stubs/Deprecated/METADATA.toml index 1f0b2e4bf4a2..4ac49bff8cb7 100644 --- a/stubs/Deprecated/METADATA.toml +++ b/stubs/Deprecated/METADATA.toml @@ -1,3 +1,3 @@ -version = "1.2.*" -python2 = true -requires = [] +version = "~=1.3.1" +upstream-repository = "https://github.com/laurent-laporte-pro/deprecated" +obsolete-since = {version = "3.0.0", date = "2026-09-26"} diff --git a/stubs/Deprecated/deprecated/__init__.pyi b/stubs/Deprecated/deprecated/__init__.pyi index 25df24324da5..3d4b2bfd8a92 100644 --- a/stubs/Deprecated/deprecated/__init__.pyi +++ b/stubs/Deprecated/deprecated/__init__.pyi @@ -1 +1,9 @@ +from typing import Final + from .classic import deprecated as deprecated +from .params import deprecated_params as deprecated_params + +__version__: Final[str] +__author__: Final[str] +__date__: Final[str] +__credits__: Final[str] diff --git a/stubs/Deprecated/deprecated/classic.pyi b/stubs/Deprecated/deprecated/classic.pyi index b6f546235047..99d2bd6e9bfa 100644 --- a/stubs/Deprecated/deprecated/classic.pyi +++ b/stubs/Deprecated/deprecated/classic.pyi @@ -1,23 +1,35 @@ -from typing import Any, Callable, Type, TypeVar, overload -from typing_extensions import Literal +from collections.abc import Callable +from typing import Any, Literal, TypeAlias, TypeVar, overload _F = TypeVar("_F", bound=Callable[..., Any]) -_Actions = Literal["default", "error", "ignore", "always", "module", "once"] +_Actions: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] + +string_types: tuple[type, ...] class ClassicAdapter: reason: str version: str action: _Actions | None - category: Type[Warning] + category: type[Warning] def __init__( - self, reason: str = ..., version: str = ..., action: _Actions | None = ..., category: Type[Warning] = ... + self, + reason: str = "", + version: str = "", + action: _Actions | None = None, + category: type[Warning] = ..., + extra_stacklevel: int = 0, ) -> None: ... def get_deprecated_msg(self, wrapped: Callable[..., Any], instance: object) -> str: ... def __call__(self, wrapped: _F) -> Callable[[_F], _F]: ... @overload -def deprecated(__wrapped: _F) -> _F: ... +def deprecated(wrapped: _F, /) -> _F: ... @overload def deprecated( - reason: str = ..., *, version: str = ..., action: _Actions | None = ..., category: Type[Warning] | None = ... + reason: str = ..., + *, + version: str = ..., + action: _Actions | None = ..., + category: type[Warning] | None = ..., + extra_stacklevel: int = 0, ) -> Callable[[_F], _F]: ... diff --git a/stubs/Deprecated/deprecated/params.pyi b/stubs/Deprecated/deprecated/params.pyi new file mode 100644 index 000000000000..721d2d225900 --- /dev/null +++ b/stubs/Deprecated/deprecated/params.pyi @@ -0,0 +1,21 @@ +from collections.abc import Callable, Iterable +from inspect import Signature +from typing import Any, ParamSpec, TypeVar + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +class DeprecatedParams: + messages: dict[str, str] + category: type[Warning] + def __init__( + self, param: str | dict[str, str], reason: str = "", category: type[Warning] = DeprecationWarning # noqa: Y011 + ) -> None: ... + def populate_messages(self, param: str | dict[str, str], reason: str = "") -> None: ... + def check_params( + self, signature: Signature, *args: Any, **kwargs: Any # args and kwargs passing to Signature.bind method + ) -> list[str]: ... + def warn_messages(self, messages: Iterable[str]) -> None: ... + def __call__(self, f: Callable[_P, _R]) -> Callable[_P, _R]: ... + +deprecated_params = DeprecatedParams diff --git a/stubs/Deprecated/deprecated/sphinx.pyi b/stubs/Deprecated/deprecated/sphinx.pyi index e5acd9406e68..9d8128d1449b 100644 --- a/stubs/Deprecated/deprecated/sphinx.pyi +++ b/stubs/Deprecated/deprecated/sphinx.pyi @@ -1,5 +1,5 @@ -from typing import Any, Callable, Type, TypeVar -from typing_extensions import Literal +from collections.abc import Callable +from typing import Any, Literal, TypeVar from .classic import ClassicAdapter, _Actions @@ -10,24 +10,27 @@ class SphinxAdapter(ClassicAdapter): reason: str version: str action: _Actions | None - category: Type[Warning] + category: type[Warning] def __init__( self, directive: Literal["versionadded", "versionchanged", "deprecated"], - reason: str = ..., - version: str = ..., - action: _Actions | None = ..., - category: Type[Warning] = ..., + reason: str = "", + version: str = "", + action: _Actions | None = None, + category: type[Warning] = DeprecationWarning, # noqa: Y011 + extra_stacklevel: int = 0, + line_length: int = 70, ) -> None: ... def __call__(self, wrapped: _F) -> Callable[[_F], _F]: ... -def versionadded(reason: str = ..., version: str = ...) -> Callable[[_F], _F]: ... -def versionchanged(reason: str = ..., version: str = ...) -> Callable[[_F], _F]: ... +def versionadded(reason: str = "", version: str = "", line_length: int = 70) -> Callable[[_F], _F]: ... +def versionchanged(reason: str = "", version: str = "", line_length: int = 70) -> Callable[[_F], _F]: ... def deprecated( - reason: str = ..., - version: str = ..., - line_length: int = ..., + reason: str = "", + version: str = "", + line_length: int = 70, *, action: _Actions | None = ..., - category: Type[Warning] | None = ..., + category: type[Warning] | None = ..., + extra_stacklevel: int = 0, ) -> Callable[[_F], _F]: ... diff --git a/stubs/Flask-Cors/METADATA.toml b/stubs/Flask-Cors/METADATA.toml new file mode 100644 index 000000000000..beef2e8378bc --- /dev/null +++ b/stubs/Flask-Cors/METADATA.toml @@ -0,0 +1,5 @@ +version = "6.0.3" +upstream-repository = "https://github.com/corydolphin/flask-cors" +# Requires a version of flask with a `py.typed` file +dependencies = ["Flask>=2.0.0"] +obsolete-since = { version = "6.0.4", date = "2026-06-07" } diff --git a/stubs/Flask-Cors/flask_cors/__init__.pyi b/stubs/Flask-Cors/flask_cors/__init__.pyi new file mode 100644 index 000000000000..bb2d755dee6e --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/__init__.pyi @@ -0,0 +1,11 @@ +from logging import Logger +from typing import Final + +from .decorator import cross_origin as cross_origin +from .extension import CORS as CORS + +__version__: Final[str] + +rootlogger: Logger + +__all__ = ["CORS", "__version__", "cross_origin"] diff --git a/stubs/Flask-Cors/flask_cors/core.pyi b/stubs/Flask-Cors/flask_cors/core.pyi new file mode 100644 index 000000000000..5b5e2d78561d --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/core.pyi @@ -0,0 +1,74 @@ +from collections.abc import Iterable +from datetime import timedelta +from logging import Logger +from re import Match, Pattern +from typing import Any, Final, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +import flask + +_IterableT = TypeVar("_IterableT", bound=Iterable[Any]) +_T = TypeVar("_T") +_MultiDict: TypeAlias = Any # werkzeug is not part of typeshed + +@type_check_only +class _Options(TypedDict, total=False): + resources: dict[str, dict[str, Any]] | list[str] | str | None + origins: Iterable[str | Pattern[str]] + methods: str | list[str] | None + expose_headers: str | list[str] | None + allow_headers: Iterable[str | Pattern[str]] + supports_credentials: bool | None + max_age: timedelta | int | str | None + send_wildcard: bool | None + vary_header: bool | None + automatic_options: bool | None + intercept_exceptions: bool | None + always_send: bool | None + +LOG: Logger + +ACL_ORIGIN: Final = "Access-Control-Allow-Origin" +ACL_METHODS: Final = "Access-Control-Allow-Methods" +ACL_ALLOW_HEADERS: Final = "Access-Control-Allow-Headers" +ACL_EXPOSE_HEADERS: Final = "Access-Control-Expose-Headers" +ACL_CREDENTIALS: Final = "Access-Control-Allow-Credentials" +ACL_MAX_AGE: Final = "Access-Control-Max-Age" +ACL_RESPONSE_PRIVATE_NETWORK: Final = "Access-Control-Allow-Private-Network" +ACL_REQUEST_METHOD: Final = "Access-Control-Request-Method" +ACL_REQUEST_HEADERS: Final = "Access-Control-Request-Headers" +ACL_REQUEST_HEADER_PRIVATE_NETWORK: Final = "Access-Control-Request-Private-Network" +ALL_METHODS: Final[list[str]] +CONFIG_OPTIONS: Final[list[str]] +FLASK_CORS_EVALUATED: Final = "_FLASK_CORS_EVALUATED" +RegexObject: Final[type[Pattern[str]]] +DEFAULT_OPTIONS: Final[_Options] + +def parse_resources(resources: dict[str, _Options] | Iterable[str] | str | Pattern[str]) -> list[tuple[str, _Options]]: ... +def get_regexp_pattern(regexp: str | Pattern[str]) -> str: ... +def get_cors_origins(options: _Options, request_origin: str | None) -> list[str] | None: ... +def get_allow_headers(options: _Options, acl_request_headers: str | None) -> str | None: ... +def get_cors_headers(options: _Options, request_headers: dict[str, Any], request_method: str) -> _MultiDict: ... +def set_cors_headers(resp: flask.Response, options: _Options) -> flask.Response: ... + +@overload +def probably_regex(maybe_regex: Pattern[str]) -> Literal[True]: ... +@overload +def probably_regex(maybe_regex: str) -> bool: ... + +def re_fix(reg: str) -> str: ... +def try_match_any_pattern(inst: str, patterns: Iterable[str | Pattern[str]], caseSensitive: bool = True) -> bool: ... +def try_match_pattern(value: str, pattern: str | Pattern[str], caseSensitive: bool = True) -> bool | Match[str]: ... +def get_cors_options(appInstance: flask.Flask | None, *dicts: _Options) -> _Options: ... +def get_app_kwarg_dict(appInstance: flask.Flask | None = None) -> _Options: ... +def flexible_str(obj: object) -> str | None: ... +def serialize_option(options_dict: _Options, key: str, upper: bool = False) -> None: ... + +@overload +def ensure_iterable(inst: str) -> list[str]: ... # type: ignore[overload-overlap] +@overload +def ensure_iterable(inst: _IterableT) -> _IterableT: ... # type: ignore[overload-overlap] +@overload +def ensure_iterable(inst: _T) -> list[_T]: ... + +def sanitize_regex_param(param: str | list[str]) -> list[str]: ... +def serialize_options(opts: _Options) -> _Options: ... diff --git a/stubs/Flask-Cors/flask_cors/decorator.pyi b/stubs/Flask-Cors/flask_cors/decorator.pyi new file mode 100644 index 000000000000..66b846d37f64 --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/decorator.pyi @@ -0,0 +1,22 @@ +from collections.abc import Callable, Iterable +from datetime import timedelta +from logging import Logger +from re import Pattern +from typing import Any, ParamSpec + +_P = ParamSpec("_P") + +LOG: Logger + +def cross_origin( + *args: Any, + origins: str | Pattern[str] | Iterable[str | Pattern[str]] | None = ..., + methods: str | list[str] | None = ..., + expose_headers: str | list[str] | None = ..., + allow_headers: str | Pattern[str] | Iterable[str | Pattern[str]] | None = ..., + supports_credentials: bool | None = ..., + max_age: timedelta | int | str | None = ..., + send_wildcard: bool | None = ..., + vary_header: bool | None = ..., + automatic_options: bool | None = ..., +) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]: ... diff --git a/stubs/Flask-Cors/flask_cors/extension.pyi b/stubs/Flask-Cors/flask_cors/extension.pyi new file mode 100644 index 000000000000..7617107da5da --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/extension.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable, Iterable +from datetime import timedelta +from logging import Logger +from re import Pattern +from typing import Any + +import flask + +LOG: Logger + +class CORS: + def __init__( + self, + app: flask.Flask | flask.Blueprint | None = None, + *, + resources: dict[str, dict[str, Any]] | list[str] | str | None = ..., + origins: str | Pattern[str] | Iterable[str | Pattern[str]] = ..., + methods: str | list[str] | None = ..., + expose_headers: str | list[str] | None = ..., + allow_headers: str | list[str] | None = ..., + supports_credentials: bool | None = ..., + max_age: timedelta | int | str | None = ..., + send_wildcard: bool | None = ..., + vary_header: bool | None = ..., + **kwargs: Any, + ) -> None: ... + def init_app( + self, + app: flask.Flask, + *, + resources: dict[str, dict[str, Any]] | list[str] | str = ..., + origins: str | Pattern[str] | Iterable[str | Pattern[str]] = ..., + methods: str | list[str] = ..., + expose_headers: str | list[str] = ..., + allow_headers: str | list[str] = ..., + supports_credentials: bool = ..., + max_age: timedelta | int | str | None = ..., + send_wildcard: bool = ..., + vary_header: bool = ..., + **kwargs: Any, + ) -> None: ... + +def make_after_request_function(resources: Iterable[tuple[str, dict[str, Any]]]) -> Callable[..., Any]: ... diff --git a/stubs/Flask-Migrate/@tests/stubtest_allowlist.txt b/stubs/Flask-Migrate/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..05ab57df9c75 --- /dev/null +++ b/stubs/Flask-Migrate/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Flask-Migrate users don't need to interact with this undocumented module from within python +flask_migrate.cli diff --git a/stubs/Flask-Migrate/METADATA.toml b/stubs/Flask-Migrate/METADATA.toml new file mode 100644 index 000000000000..526b6c3e0d03 --- /dev/null +++ b/stubs/Flask-Migrate/METADATA.toml @@ -0,0 +1,4 @@ +version = "4.1.*" +upstream-repository = "https://github.com/miguelgrinberg/Flask-Migrate" +# Requires versions of flask and Flask-SQLAlchemy with `py.typed` files +dependencies = ["Flask-SQLAlchemy>=3.0.1", "Flask>=2.0.0"] diff --git a/stubs/Flask-Migrate/flask_migrate/__init__.pyi b/stubs/Flask-Migrate/flask_migrate/__init__.pyi new file mode 100644 index 000000000000..b9235dafed9f --- /dev/null +++ b/stubs/Flask-Migrate/flask_migrate/__init__.pyi @@ -0,0 +1,136 @@ +# pyright: reportInvalidStubStatement=none + +import sys +from _typeshed import StrPath, SupportsFlush, SupportsKeysAndGetItem, SupportsWrite +from argparse import Namespace +from collections.abc import Callable, Iterable, Sequence +from logging import Logger +from typing import Any, ParamSpec, Protocol, TypeAlias, TypeVar, type_check_only + +import flask +from flask_sqlalchemy import SQLAlchemy + +_T = TypeVar("_T") +_T_contra = TypeVar("_T_contra", contravariant=True) +_P = ParamSpec("_P") +_ConfigureCallback: TypeAlias = Callable[[Config], Config] +_AlembicConfigValue: TypeAlias = Any + +alembic_version: tuple[int, int, int] +log: Logger + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol): ... + +class Config: # should inherit from alembic.config.Config which is not possible yet + template_directory: str | None + # Same as alembic.config.Config + template_directory kwarg + def __init__( + self, + file_: StrPath | None = None, + ini_section: str = "alembic", + # Same as buffer argument in TextIOWrapper.__init__.buffer + output_buffer: _SupportsWriteAndFlush[str] | None = None, + # Same as stream argument in alembic.util.messaging + stdout: SupportsWrite[str] = sys.stdout, + cmd_opts: Namespace | None = None, + config_args: SupportsKeysAndGetItem[str, _AlembicConfigValue] | Iterable[tuple[str, _AlembicConfigValue]] = ..., + attributes: ( + SupportsKeysAndGetItem[_AlembicConfigValue, _AlembicConfigValue] + | Iterable[tuple[_AlembicConfigValue, _AlembicConfigValue]] + | None + ) = None, + *, + template_directory: str | None = None, + ) -> None: ... + def get_template_directory(self) -> str: ... + +class Migrate: + configure_callbacks: list[_ConfigureCallback] + db: SQLAlchemy | None + directory: str + alembic_ctx_kwargs: dict[str, _AlembicConfigValue] + def __init__( + self, + app: flask.Flask | None = None, + db: SQLAlchemy | None = None, + directory: str = "migrations", + command: str = "db", + compare_type: bool = True, + render_as_batch: bool = True, + **kwargs: _AlembicConfigValue, + ) -> None: ... + def init_app( + self, + app: flask.Flask, + db: SQLAlchemy | None = None, + directory: str | None = None, + command: str | None = None, + compare_type: bool | None = None, + render_as_batch: bool | None = None, + **kwargs: _AlembicConfigValue, + ) -> None: ... + def configure(self, f: _ConfigureCallback) -> _ConfigureCallback: ... + def call_configure_callbacks(self, config: Config) -> Config: ... + def get_config( + self, directory: str | None = None, x_arg: str | Sequence[str] | None = None, opts: Iterable[str] | None = None + ) -> Config: ... + +def catch_errors(f: Callable[_P, _T]) -> Callable[_P, _T]: ... +def list_templates() -> None: ... +def init(directory: str | None = None, multidb: bool = False, template: str | None = None, package: bool = False) -> None: ... +def revision( + directory: str | None = None, + message: str | None = None, + autogenerate: bool = False, + sql: bool = False, + head: str = "head", + splice: bool = False, + branch_label: str | None = None, + version_path: str | None = None, + rev_id: str | None = None, +) -> None: ... +def migrate( + directory: str | None = None, + message: str | None = None, + sql: bool = False, + head: str = "head", + splice: bool = False, + branch_label: str | None = None, + version_path: str | None = None, + rev_id: str | None = None, + x_arg: str | Sequence[str] | None = None, +) -> None: ... +def edit(directory: str | None = None, revision: str = "current") -> None: ... +def merge( + directory: str | None = None, + revisions: str = "", + message: str | None = None, + branch_label: str | None = None, + rev_id: str | None = None, +) -> None: ... +def upgrade( + directory: str | None = None, + revision: str = "head", + sql: bool = False, + tag: str | None = None, + x_arg: str | Sequence[str] | None = None, +) -> None: ... +def downgrade( + directory: str | None = None, + revision: str = "-1", + sql: bool = False, + tag: str | None = None, + x_arg: str | Sequence[str] | None = None, +) -> None: ... +def show(directory: str | None = None, revision: str = "head") -> None: ... +def history( + directory: str | None = None, rev_range: str | None = None, verbose: bool = False, indicate_current: bool = False +) -> None: ... +def heads(directory: str | None = None, verbose: bool = False, resolve_dependencies: bool = False) -> None: ... +def branches(directory: str | None = None, verbose: bool = False) -> None: ... +def current(directory: str | None = None, verbose: bool = False) -> None: ... +def stamp( + directory: str | None = None, revision: str = "head", sql: bool = False, tag: str | None = None, purge: bool = False +) -> None: ... +def check(directory: str | None = None) -> None: ... diff --git a/stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt b/stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..6e232db3142d --- /dev/null +++ b/stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# private attributes / methods, not present in docs +flask_socketio.test_client.SocketIOTestClient.clients +flask_socketio.gevent_socketio_found +flask_socketio.call diff --git a/stubs/Flask-SocketIO/METADATA.toml b/stubs/Flask-SocketIO/METADATA.toml new file mode 100644 index 000000000000..13115c99f63b --- /dev/null +++ b/stubs/Flask-SocketIO/METADATA.toml @@ -0,0 +1,3 @@ +version = "5.6.*" +upstream-repository = "https://github.com/miguelgrinberg/flask-socketio" +dependencies = ["Flask>=0.9"] diff --git a/stubs/Flask-SocketIO/flask_socketio/__init__.pyi b/stubs/Flask-SocketIO/flask_socketio/__init__.pyi new file mode 100644 index 000000000000..af770c766947 --- /dev/null +++ b/stubs/Flask-SocketIO/flask_socketio/__init__.pyi @@ -0,0 +1,166 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from logging import Logger +from threading import Thread +from typing import Any, Literal, ParamSpec, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +from flask import Flask +from flask.testing import FlaskClient + +from .namespace import Namespace as Namespace +from .test_client import SocketIOTestClient as SocketIOTestClient + +_P = ParamSpec("_P") +_R_co = TypeVar("_R_co", covariant=True) +_ExceptionHandler: TypeAlias = Callable[[BaseException], _R_co] +_Handler: TypeAlias = Callable[_P, _R_co] + +@type_check_only +class _HandlerDecorator(Protocol): + def __call__(self, handler: _Handler[_P, _R_co]) -> _Handler[_P, _R_co]: ... + +@type_check_only +class _ExceptionHandlerDecorator(Protocol): + def __call__(self, exception_handler: _ExceptionHandler[_R_co]) -> _ExceptionHandler[_R_co]: ... + +@type_check_only +class _SocketIOServerOptions(TypedDict, total=False): + client_manager: Incomplete + logger: Logger | bool + json: Incomplete + async_handlers: bool + always_connect: bool + +@type_check_only +class _EngineIOServerConfig(TypedDict, total=False): + async_mode: Literal["threading", "eventlet", "gevent", "gevent_uwsgi"] + ping_interval: float | tuple[float, float] # seconds + ping_timeout: float # seconds + max_http_buffer_size: int + allow_upgrades: bool + http_compression: bool + compression_threshold: int + cookie: str | dict[str, Any] | None + cors_allowed_origins: str | list[str] + cors_credentials: bool + monitor_clients: bool + engineio_logger: Logger | bool + +@type_check_only +class _SocketIOKwargs(_SocketIOServerOptions, _EngineIOServerConfig): ... + +class SocketIO: + # This is an alias for `socketio.Server.reason` in `python-socketio`, which is not typed. + reason: Incomplete + # Many instance attributes are deliberately not included here, + # as the maintainer of Flask-SocketIO considers them private, internal details: + # https://github.com/python/typeshed/pull/10735#discussion_r1330768869 + def __init__( + self, + app: Flask | None = None, + *, + # SocketIO options + manage_session: bool = True, + message_queue: str | None = None, + channel: str = "flask-socketio", + path: str = "socket.io", + resource: str = "socket.io", + **kwargs: Unpack[_SocketIOKwargs], + ) -> None: ... + def init_app( + self, + app: Flask, + *, + # SocketIO options + manage_session: bool = True, + message_queue: str | None = None, + channel: str = "flask-socketio", + path: str = "socket.io", + resource: str = "socket.io", + **kwargs: Unpack[_SocketIOKwargs], + ) -> None: ... + def on(self, message: str, namespace: str | None = None) -> _HandlerDecorator: ... + def on_error(self, namespace: str | None = None) -> _ExceptionHandlerDecorator: ... + def on_error_default(self, exception_handler: _ExceptionHandler[_R_co]) -> _ExceptionHandler[_R_co]: ... + def on_event(self, message: str, handler: _Handler[[Incomplete], object], namespace: str | None = None) -> None: ... + + @overload + def event(self, event_handler: _Handler[_P, _R_co], /) -> _Handler[_P, _R_co]: ... + @overload + def event(self, namespace: str | None = None, *args, **kwargs) -> _HandlerDecorator: ... + + def on_namespace(self, namespace_handler: Namespace) -> None: ... + def emit( + self, + event: str, + *args, + namespace: str = "/", # / is the default (global) namespace + to: str | None = None, + include_self: bool = True, + skip_sid: str | list[str] | None = None, + callback: Callable[..., Incomplete] | None = None, + ) -> None: ... + def call( + self, + event: str, + *args, + namespace: str = "/", # / is the default (global) namespace + to: str | None = None, + timeout: int = 60, # seconds + ignore_queue: bool = False, + ): ... + def send( + self, + data: Any, + json: bool = False, + namespace: str | None = None, + to: str | None = None, + callback: Callable[..., Incomplete] | None = None, + include_self: bool = True, + skip_sid: list[str] | str | None = None, + **kwargs, + ) -> None: ... + def close_room(self, room: str, namespace: str | None = None) -> None: ... + def run( + self, + app, + host: str | None = None, + port: int | None = None, + *, + debug: bool = True, + use_reloader: bool = ..., + reloader_options: dict[str, Incomplete] = {}, + log_output: bool = ..., + allow_unsafe_werkzeug: bool = False, + **kwargs, + ) -> None: ... + def stop(self) -> None: ... + def start_background_task(self, target: Callable[_P, None], *args: _P.args, **kwargs: _P.kwargs) -> Thread: ... + def sleep(self, seconds: int = 0): ... + def test_client( + self, + app: Flask, + namespace: str | None = None, + query_string: str | None = None, + headers: dict[str, Incomplete] | None = None, + auth: dict[str, Incomplete] | None = None, + flask_test_client: FlaskClient | None = None, + ) -> SocketIOTestClient: ... + +def emit( + event: str, + *args, + namespace: str = "/", # / is the default (global) namespace + to: str | None = None, + include_self: bool = True, + skip_sid: str | list[str] | None = None, + callback: Callable[..., Incomplete] | None = None, + broadcast: bool = False, +) -> None: ... +def send(message: str, **kwargs) -> None: ... +def join_room(room: str, sid: str | None = None, namespace: str | None = None) -> None: ... +def leave_room(room: str, sid: str | None = None, namespace: str | None = None) -> None: ... +def close_room(room: str, namespace: str | None = None) -> None: ... +def rooms(sid: str | None = None, namespace: str | None = None) -> list[str]: ... +def disconnect(sid: str | None = None, namespace: str | None = None, silent: bool = False) -> None: ... diff --git a/stubs/Flask-SocketIO/flask_socketio/namespace.pyi b/stubs/Flask-SocketIO/flask_socketio/namespace.pyi new file mode 100644 index 000000000000..94ec7b716dd2 --- /dev/null +++ b/stubs/Flask-SocketIO/flask_socketio/namespace.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Protocol, TypeVar, type_check_only + +_T = TypeVar("_T") + +# at runtime, socketio.namespace.BaseNamespace, but socketio isn't py.typed +@type_check_only +class _BaseNamespace(Protocol): + def is_asyncio_based(self) -> bool: ... + def trigger_event(self, event: str, *args): ... + +# at runtime, socketio.namespace.BaseNamespace, but socketio isn't py.typed +class _Namespace(_BaseNamespace, Protocol): + def emit( + self, + event: str, + data=None, + to=None, + room: str | None = None, + skip_sid=None, + namespace: str | None = None, + callback: Callable[..., Incomplete] | None = None, + ignore_queue: bool = False, + ): ... + def send( + self, + data, + to=None, + room: str | None = None, + skip_sid=None, + namespace: str | None = None, + callback: Callable[..., Incomplete] | None = None, + ignore_queue: bool = False, + ) -> None: ... + def call( + self, event: str, data=None, to=None, sid=None, namespace: str | None = None, timeout=None, ignore_queue: bool = False + ): ... + def enter_room(self, sid, room: str, namespace: str | None = None): ... + def leave_room(self, sid, room: str, namespace: str | None = None): ... + def close_room(self, room: str, namespace: str | None = None): ... + def rooms(self, sid, namespace: str | None = None): ... + def get_session(self, sid, namespace: str | None = None): ... + def save_session(self, sid, session, namespace: str | None = None): ... + def session(self, sid, namespace: str | None = None): ... + def disconnect(self, sid, namespace: str | None = None): ... + +class Namespace(_Namespace): + def __init__(self, namespace: str | None = None) -> None: ... + def trigger_event(self, event: str, *args): ... + def emit( # type: ignore[override] + self, + event: str, + data=None, + room: str | None = None, + include_self: bool = True, + namespace: str | None = None, + callback: Callable[..., _T] | None = None, + ) -> _T | tuple[str, int]: ... + def send( # type: ignore[override] + self, + data, + room: str | None = None, + include_self: bool = True, + namespace: str | None = None, + callback: Callable[..., Any] | None = None, + ) -> None: ... + def close_room(self, room: str, namespace: str | None = None) -> None: ... diff --git a/stubs/Flask-SocketIO/flask_socketio/test_client.pyi b/stubs/Flask-SocketIO/flask_socketio/test_client.pyi new file mode 100644 index 000000000000..15cf426959a0 --- /dev/null +++ b/stubs/Flask-SocketIO/flask_socketio/test_client.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from typing import Any, TypedDict, type_check_only + +from flask import Flask +from flask.testing import FlaskClient + +@type_check_only +class _Packet(TypedDict): + name: str + args: Any + namespace: str + +class SocketIOTestClient: + def __init__( + self, + app: Flask, + socketio, + namespace: str | None = None, + query_string: str | None = None, + headers: dict[str, Incomplete] | None = None, + auth: dict[str, Incomplete] | None = None, + flask_test_client: FlaskClient | None = None, + ) -> None: ... + def is_connected(self, namespace: str | None = None) -> bool: ... + def connect( + self, + namespace: str | None = None, + query_string: str | None = None, + headers: dict[str, Incomplete] | None = None, + auth: dict[str, Incomplete] | None = None, + ) -> None: ... + def disconnect(self, namespace: str | None = None) -> None: ... + def emit(self, event: str, *args, callback: bool = False, namespace: str | None = None) -> Incomplete | None: ... + def send( + self, + data: str | dict[str, Incomplete] | list[Incomplete], + json: bool = False, + callback: bool = False, + namespace: str | None = None, + ): ... + def get_received(self, namespace: str | None = None) -> list[_Packet]: ... diff --git a/stubs/JACK-Client/@tests/stubtest_allowlist.txt b/stubs/JACK-Client/@tests/stubtest_allowlist.txt index b0b1dbc666f0..5a7c05f46db9 100644 --- a/stubs/JACK-Client/@tests/stubtest_allowlist.txt +++ b/stubs/JACK-Client/@tests/stubtest_allowlist.txt @@ -1 +1,2 @@ -jack +# The available constants differ based on the local environment. +(jack\.METADATA_.*)? diff --git a/stubs/JACK-Client/METADATA.toml b/stubs/JACK-Client/METADATA.toml index 1883b870198a..348052b2d333 100644 --- a/stubs/JACK-Client/METADATA.toml +++ b/stubs/JACK-Client/METADATA.toml @@ -1 +1,11 @@ version = "0.5.*" +upstream-repository = "https://github.com/spatialaudio/jackclient-python" +dependencies = ["types-cffi"] + +[tool.stubtest] +# darwin and win32 are equivalent +ci-platforms = ["darwin", "linux"] +apt-dependencies = ["libjack-dev"] +brew-dependencies = ["jack"] +# No need to install on the CI. Leaving here as information for Windows contributors. +# choco-dependencies = ["jack"] diff --git a/stubs/JACK-Client/jack/__init__.pyi b/stubs/JACK-Client/jack/__init__.pyi index 1f62eb116430..24f02d25d936 100644 --- a/stubs/JACK-Client/jack/__init__.pyi +++ b/stubs/JACK-Client/jack/__init__.pyi @@ -1,18 +1,49 @@ -from typing import Any, Callable, Generator, Iterable, Iterator, Sequence, overload +from _typeshed import Unused +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from typing import Any, Final, Literal, overload, type_check_only +from typing_extensions import Never, Self -_NDArray = Any # FIXME: no typings for numpy arrays +from _cffi_backend import _CDataBase -class _JackPositionT: ... +# Aka jack_position_t +# Actual type: _cffi_backend.__CDataOwn +# This is not a real subclassing. Just ensuring type-checkers sees this type as compatible with _CDataBase +# pyright has no error code for subclassing final +@type_check_only +class _JackPositionT(_CDataBase): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] + audio_frames_per_video_frame: float + bar: int + bar_start_tick: float + bbt_offset: int + beat: int + beat_type: float + beats_per_bar: float + beats_per_minute: float + frame: int + frame_rate: int + frame_time: float + next_time: float + padding: _CDataBase # + tick: int + ticks_per_beat: float + unique_1: int + unique_2: int + usecs: int + valid: int + video_offset: int +@type_check_only class _CBufferType: @overload def __getitem__(self, key: int) -> str: ... @overload def __getitem__(self, key: slice) -> bytes: ... + @overload def __setitem__(self, key: int, val: str) -> None: ... @overload def __setitem__(self, key: slice, val: bytes) -> None: ... + def __len__(self) -> int: ... def __bytes__(self) -> bytes: ... @@ -33,33 +64,38 @@ class JackError(Exception): ... class JackErrorCode(JackError): def __init__(self, message: str, code: int) -> None: ... - message: str = ... - code: int = ... + message: str + code: int class JackOpenError(JackError): def __init__(self, name: str, status: Status) -> None: ... - name: str = ... - status: Status = ... + name: str + status: Status class Client: def __init__( self, name: str, - use_exact_name: bool = ..., - no_start_server: bool = ..., - servername: str | None = ..., - session_id: str | None = ..., + use_exact_name: bool = False, + no_start_server: bool = False, + servername: str | None = None, + session_id: str | None = None, ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... @property def name(self) -> str: ... @property def uuid(self) -> str: ... @property def samplerate(self) -> int: ... + @property def blocksize(self) -> int: ... @blocksize.setter def blocksize(self, blocksize: int) -> None: ... + @property def status(self) -> Status: ... @property @@ -80,86 +116,95 @@ class Client: def midi_outports(self) -> Ports: ... def owns(self, port: str | Port) -> bool: ... def activate(self) -> None: ... - def deactivate(self, ignore_errors: bool = ...) -> None: ... + def deactivate(self, ignore_errors: bool = True) -> None: ... def cpu_load(self) -> float: ... - def close(self, ignore_errors: bool = ...) -> None: ... + def close(self, ignore_errors: bool = True) -> None: ... def connect(self, source: str | Port, destination: str | Port) -> None: ... def disconnect(self, source: str | Port, destination: str | Port) -> None: ... def transport_start(self) -> None: ... def transport_stop(self) -> None: ... @property def transport_state(self) -> TransportState: ... + @property def transport_frame(self) -> int: ... @transport_frame.setter def transport_frame(self, frame: int) -> None: ... + def transport_locate(self, frame: int) -> None: ... - def transport_query(self) -> tuple[TransportState, dict[str, Any]]: ... + def transport_query(self) -> tuple[TransportState, dict[str, Any]]: ... # Anyof[int, float, _CDataBase] def transport_query_struct(self) -> tuple[TransportState, _JackPositionT]: ... - def transport_reposition_struct(self, position: _JackPositionT) -> None: ... # TODO + def transport_reposition_struct(self, position: _JackPositionT) -> None: ... def set_sync_timeout(self, timeout: int) -> None: ... def set_freewheel(self, onoff: bool) -> None: ... - def set_shutdown_callback(self, callback: Callable[[Status, str], None]) -> None: ... - def set_process_callback(self, callback: Callable[[int], None]) -> None: ... - def set_freewheel_callback(self, callback: Callable[[bool], None]) -> None: ... - def set_blocksize_callback(self, callback: Callable[[int], None]) -> None: ... - def set_samplerate_callback(self, callback: Callable[[int], None]) -> None: ... - def set_client_registration_callback(self, callback: Callable[[str, bool], None]) -> None: ... + def set_shutdown_callback(self, callback: Callable[[Status, str], object]) -> None: ... + def set_process_callback(self, callback: Callable[[int], object]) -> None: ... + def set_freewheel_callback(self, callback: Callable[[bool], object]) -> None: ... + def set_blocksize_callback(self, callback: Callable[[int], object]) -> None: ... + def set_samplerate_callback(self, callback: Callable[[int], object]) -> None: ... + def set_client_registration_callback(self, callback: Callable[[str, bool], object]) -> None: ... def set_port_registration_callback( - self, callback: Callable[[Port, bool], None] | None = ..., only_available: bool = ... + self, callback: Callable[[Port, bool], object] | None = None, only_available: bool = True ) -> None: ... def set_port_connect_callback( - self, callback: Callable[[Port, Port, bool], None] | None = ..., only_available: bool = ... + self, callback: Callable[[Port, Port, bool], object] | None = None, only_available: bool = True ) -> None: ... def set_port_rename_callback( - self, callback: Callable[[Port, str, str], None] | None = ..., only_available: bool = ... + self, callback: Callable[[Port, str, str], object] | None = None, only_available: bool = True ) -> None: ... - def set_graph_order_callback(self, callback: Callable[[], None]) -> None: ... - def set_xrun_callback(self, callback: Callable[[float], None]) -> None: ... - def set_sync_callback(self, callback: Callable[[int, _JackPositionT], None] | None) -> None: ... + def set_graph_order_callback(self, callback: Callable[[], object]) -> None: ... + def set_xrun_callback(self, callback: Callable[[float], object]) -> None: ... + def set_sync_callback(self, callback: Callable[[int, _JackPositionT], object] | None) -> None: ... def release_timebase(self) -> None: ... def set_timebase_callback( - self, callback: Callable[[int, int, _JackPositionT, bool], None] | None = ..., conditional: bool = ... + self, callback: Callable[[int, int, _JackPositionT, bool], object] | None = None, conditional: bool = False ) -> bool: ... - def set_property_change_callback(self, callback: Callable[[int, str, int], None]) -> None: ... + def set_property_change_callback(self, callback: Callable[[int, str, int], object]) -> None: ... def get_uuid_for_client_name(self, name: str) -> str: ... def get_client_name_by_uuid(self, uuid: str) -> str: ... def get_port_by_name(self, name: str) -> Port: ... def get_all_connections(self, port: Port) -> list[Port]: ... def get_ports( self, - name_pattern: str = ..., - is_audio: bool = ..., - is_midi: bool = ..., - is_input: bool = ..., - is_output: bool = ..., - is_physical: bool = ..., - can_monitor: bool = ..., - is_terminal: bool = ..., + name_pattern: str = "", + is_audio: bool = False, + is_midi: bool = False, + is_input: bool = False, + is_output: bool = False, + is_physical: bool = False, + can_monitor: bool = False, + is_terminal: bool = False, ) -> list[Port]: ... - def set_property(self, subject: int | str, key: str, value: str | bytes, type: str = ...) -> None: ... + def set_property(self, subject: int | str, key: str, value: str | bytes, type: str = "") -> None: ... def remove_property(self, subject: int | str, key: str) -> None: ... def remove_properties(self, subject: int | str) -> int: ... def remove_all_properties(self) -> None: ... class Port: - def __init__(self, port_ptr: Any, client: Client) -> None: ... + # + def __init__(self, port_ptr: _CDataBase, client: Client) -> None: ... def __eq__(self, other: object) -> bool: ... def __ne__(self, other: object) -> bool: ... @property def name(self) -> str: ... + @property def shortname(self) -> str: ... @shortname.setter def shortname(self, shortname: str) -> None: ... + @property def aliases(self) -> list[str]: ... def set_alias(self, alias: str) -> None: ... def unset_alias(self, alias: str) -> None: ... @property - def uuid(self) -> str: ... - is_audio: bool = ... - is_midi: bool = ... + def type(self) -> str: ... + @property + def uuid(self) -> int: ... + @property + def is_audio(self) -> bool: ... + @property + def is_midi(self) -> bool: ... @property def is_input(self) -> bool: ... @property @@ -173,8 +218,16 @@ class Port: def request_monitor(self, onoff: bool) -> None: ... class MidiPort(Port): - is_audio: bool = ... - is_midi: bool = ... + @property + def is_audio(self) -> Literal[False]: ... + @property + def is_midi(self) -> Literal[True]: ... + +class UnknownPort(Port): + @property + def is_audio(self) -> Literal[False]: ... + @property + def is_midi(self) -> Literal[False]: ... class OwnPort(Port): @property @@ -183,30 +236,34 @@ class OwnPort(Port): def connections(self) -> list[Port]: ... def is_connected_to(self, port: str | Port) -> bool: ... def connect(self, port: str | Port) -> None: ... - def disconnect(self, other: str | Port | None = ...) -> None: ... + def disconnect(self, other: str | Port | None = None) -> None: ... def unregister(self) -> None: ... def get_buffer(self) -> _CBufferType: ... - def get_array(self) -> _NDArray: ... + # Returns a numpy.typing.NDArray[numpy.float32], but JACK-Client no longer + # declares NumPy as a dependency, so we cannot depend on it here. + def get_array(self) -> Any: ... class OwnMidiPort(MidiPort, OwnPort): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def get_buffer(self) -> _CBufferType: ... - def get_array(self) -> _NDArray: ... + def __init__(self, port_ptr: _CDataBase, client: Client) -> None: ... + # The implementation raises NotImplementedError, but this is not an abstract class. + # `get_buffer()` and `get_array()` are disabled for OwnMidiPort + def get_buffer(self) -> Never: ... + def get_array(self) -> Never: ... @property def max_event_size(self) -> int: ... @property def lost_midi_events(self) -> int: ... - def incoming_midi_events(self) -> Generator[tuple[int, _CBufferType], None, None]: ... + def incoming_midi_events(self) -> Generator[tuple[int, _CBufferType]]: ... def clear_buffer(self) -> None: ... def write_midi_event(self, time: int, event: bytes | Sequence[int] | _CBufferType) -> None: ... def reserve_midi_event(self, time: int, size: int) -> _CBufferType: ... class Ports: - def __init__(self, client: Client, porttype: Any, flag: Any) -> None: ... + def __init__(self, client: Client, porttype: str, flag: int) -> None: ... def __len__(self) -> int: ... def __getitem__(self, name: str) -> Port: ... def __iter__(self) -> Iterator[Port]: ... - def register(self, shortname: str, is_terminal: bool = ..., is_physical: bool = ...) -> Port: ... + def register(self, shortname: str, is_terminal: bool = False, is_physical: bool = False) -> Port: ... def clear(self) -> None: ... class RingBuffer: @@ -225,11 +282,12 @@ class RingBuffer: def read_buffers(self) -> tuple[_CBufferType, _CBufferType]: ... def read_advance(self, size: int) -> None: ... def mlock(self) -> None: ... - def reset(self, size: int | None = ...) -> None: ... + def reset(self, size: int | None = None) -> None: ... @property def size(self) -> int: ... class Status: + __slots__ = "_code" def __init__(self, code: int) -> None: ... @property def failure(self) -> bool: ... @@ -259,6 +317,7 @@ class Status: def client_zombie(self) -> bool: ... class TransportState: + __slots__ = "_code" def __init__(self, code: int) -> None: ... def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... @@ -267,12 +326,24 @@ class CallbackExit(Exception): ... def get_property(subject: int | str, key: str) -> tuple[bytes, str] | None: ... def get_properties(subject: int | str) -> dict[str, tuple[bytes, str]]: ... -def get_all_properties() -> dict[str, dict[str, tuple[bytes, str]]]: ... -def position2dict(pos: _JackPositionT) -> dict[str, Any]: ... +def get_all_properties() -> dict[int, dict[str, tuple[bytes, str]]]: ... +def position2dict(pos: _JackPositionT) -> dict[str, Any]: ... # Anyof[int, float, _CDataBase] def version() -> tuple[int, int, int, int]: ... def version_string() -> str: ... def client_name_size() -> int: ... def port_name_size() -> int: ... -def set_error_function(callback: Callable[[str], None] | None = ...) -> None: ... -def set_info_function(callback: Callable[[str], None] | None = ...) -> None: ... +def set_error_function(callback: Callable[[str], object] | None = None) -> None: ... +def set_info_function(callback: Callable[[str], object] | None = None) -> None: ... def client_pid(name: str) -> int: ... + +# Some METADATA_ constants are not available on all systems. +METADATA_CONNECTED: Final[str] +METADATA_HARDWARE: Final[str] +METADATA_ICON_LARGE: Final[str] +METADATA_ICON_SMALL: Final[str] +METADATA_PORT_GROUP: Final[str] +METADATA_PRETTY_NAME: Final[str] +METADATA_EVENT_TYPES: Final[str] +METADATA_ICON_NAME: Final[str] +METADATA_ORDER: Final[str] +METADATA_SIGNAL_TYPE: Final[str] diff --git a/stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt b/stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0349b7eb0656 --- /dev/null +++ b/stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt @@ -0,0 +1,9 @@ +# stubtest produces false positives for Jetson.GPIO-related modules in CI +# The high-level Jetson.GPIO library can only be imported on Jetson SBC, +# and requires specific system permissions (/dev/gpiochip0 access). +Jetson.GPIO +Jetson.GPIO.gpio +Jetson.GPIO.gpio_pinmux_lookup + +# This builtin error doesn't need to be re-exported +Jetson.GPIO.gpio_event.InterruptedError diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi new file mode 100644 index 000000000000..9c7fe6b35466 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi @@ -0,0 +1,3 @@ +from .gpio import * + +VERSION: str = ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi new file mode 100644 index 000000000000..8de69f455183 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi @@ -0,0 +1,22 @@ +from typing import Final + +BOARD: Final = 10 +BCM: Final = 11 +TEGRA_SOC: Final = 1000 +CVM: Final = 1001 + +PUD_OFF: Final = 20 +PUD_DOWN: Final = 21 +PUD_UP: Final = 22 + +HIGH: Final = 1 +LOW: Final = 0 + +RISING: Final = 31 +FALLING: Final = 32 +BOTH: Final = 33 + +UNKNOWN: Final = -1 +OUT: Final = 0 +IN: Final = 1 +HARD_PWM: Final = 43 diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi new file mode 100644 index 000000000000..902334cf2eb4 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi @@ -0,0 +1,44 @@ +from collections.abc import Callable, Sequence +from typing import Literal + +from .constants import * + +model = ... +JETSON_INFO = ... +RPI_INFO = ... + +def setwarnings(state: bool) -> None: ... +def setmode(mode: Literal[10, 11, 1000, 1001]) -> None: ... +def getmode() -> Literal[10, 11, 1000, 1001]: ... +def setup( + channels: int | Sequence[int], + direction: Literal[0, 1], + pull_up_down: Literal[20, 21, 22] = ..., + initial: Literal[0, 1] = ..., + consumer: str = ..., +) -> None: ... +def cleanup(channel: int | Sequence[int] | None = ...) -> None: ... +def input(channel: int) -> Literal[0, 1]: ... +def output(channels: int | Sequence[int], values: Literal[0, 1]) -> None: ... +def add_event_detect( + channel: int, + edge: Literal[31, 32, 33], + callback: Callable[[int], None] | None = ..., + bouncetime: int | None = ..., + polltime: float = 0.2, +) -> None: ... +def remove_event_detect(channel: int, timeout: float = 0.5) -> None: ... +def event_detected(channel: int) -> bool: ... +def add_event_callback(channel: int, callback: Callable[[int], None]) -> None: ... +def wait_for_edge( + channel: int, edge: Literal[31, 32, 33], bouncetime: int | None = ..., timeout: float | None = ... +) -> int | None: ... +def gpio_function(channel: int) -> Literal[-1, 0, 1]: ... + +class PWM: + def __init__(self, channel: int, frequency_hz: float) -> None: ... + def __del__(self) -> None: ... + def start(self, duty_cycle_percent: float) -> None: ... + def ChangeFrequency(self, frequency_hz: float) -> None: ... + def ChangeDutyCycle(self, duty_cycle_percent: float) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi new file mode 100644 index 000000000000..20a8b6121349 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi @@ -0,0 +1,84 @@ +import ctypes +from dataclasses import dataclass +from typing import Final, Literal + +from .gpio_pin_data import ChannelInfo + +GPIO_HIGH: Final = 1 + +GPIOHANDLE_REQUEST_INPUT: Final = 0x1 +GPIOHANDLE_REQUEST_OUTPUT: Final = 0x2 + +GPIOEVENT_REQUEST_RISING_EDGE: Final = 0x1 +GPIOEVENT_REQUEST_FALLING_EDGE: Final = 0x2 +GPIOEVENT_REQUEST_BOTH_EDGES: Final = 0x3 + +GPIO_GET_CHIPINFO_IOCTL: Final = 0x8044B401 +GPIO_GET_LINEINFO_IOCTL: Final = 0xC048B402 +GPIO_GET_LINEHANDLE_IOCTL: Final = 0xC16CB403 +GPIOHANDLE_GET_LINE_VALUES_IOCTL: Final = 0xC040B408 +GPIOHANDLE_SET_LINE_VALUES_IOCTL: Final = 0xC040B409 +GPIO_GET_LINEEVENT_IOCTL: Final = 0xC030B404 + +class gpiochip_info(ctypes.Structure): + name: str + label: str + lines: int + +class gpiohandle_request(ctypes.Structure): + lineoffsets: list[int] + flags: int + default_values: list[int] + consumer_label: str + lines: int + fd: int + +class gpiohandle_data(ctypes.Structure): + values: list[int] + +class gpioline_info(ctypes.Structure): + line_offset: int + flags: int + name: str + consumer: str + +class gpioline_info_changed(ctypes.Structure): + line_info: gpioline_info + timestamp: int + event_type: int + padding: list[int] + +class gpioevent_request(ctypes.Structure): + lineoffset: int + handleflags: int + eventflags: int + consumer_label: str + fd: int + +class gpioevent_data(ctypes.Structure): + timestamp: int + id: int + +class GPIOError(IOError): ... + +def chip_open(gpio_chip: str) -> int: ... +def chip_check_info(label: str, gpio_device: str) -> int | None: ... +def chip_open_by_label(label: str) -> int: ... +def close_chip(chip_fd: int) -> None: ... +def open_line(ch_info: ChannelInfo, request: int) -> None: ... +def close_line(line_handle: int) -> None: ... +def request_handle(line_offset: int, direction: Literal[0, 1], initial: Literal[0, 1], consumer: str) -> gpiohandle_request: ... +def request_event(line_offset: int, edge: int, consumer: str) -> gpioevent_request: ... +def get_value(line_handle: int) -> int: ... +def set_value(line_handle: int, value: int) -> None: ... + +@dataclass +class PadCtlRegister: + is_gpio: bool + is_input: bool + is_tristate: bool + def __init__(self, value: int) -> None: ... + @property + def is_bidi(self) -> bool: ... + +def check_pinmux(ch_info: ChannelInfo, direction: int) -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi new file mode 100644 index 000000000000..8e470cba9ed5 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from typing import Any, Final, Literal + +NO_EDGE: Final = 0 +RISING_EDGE: Final = 1 +FALLING_EDGE: Final = 2 +BOTH_EDGE: Final = 3 + +def add_edge_detect( + chip_fd: int, chip_name: str, channel: int, request: int, bouncetime: int, poll_time: float +) -> Literal[1, 2, 0]: ... +def remove_edge_detect(chip_name: str, channel: int, timeout: float = 0.3) -> None: ... +def add_edge_callback(chip_name: str, channel: int, callback: Callable[[int], None]) -> None: ... +def edge_event_detected(chip_name: str, channel: int) -> bool: ... +def gpio_event_added(chip_name: str, channel: int) -> Any: ... +def blocking_wait_for_edge(chip_fd: int, chip_name: str, channel: int, request: int, bouncetime: int, timeout: float) -> int: ... +def event_cleanup(chip_name: str, channel: int) -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi new file mode 100644 index 000000000000..364e5ce79838 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi @@ -0,0 +1,81 @@ +from collections.abc import Sequence +from typing import Any, Final + +CLARA_AGX_XAVIER: Final = "CLARA_AGX_XAVIER" +JETSON_NX: Final = "JETSON_NX" +JETSON_XAVIER: Final = "JETSON_XAVIER" +JETSON_TX2: Final = "JETSON_TX2" +JETSON_TX1: Final = "JETSON_TX1" +JETSON_NANO: Final = "JETSON_NANO" +JETSON_TX2_NX: Final = "JETSON_TX2_NX" +JETSON_ORIN: Final = "JETSON_ORIN" +JETSON_ORIN_NX: Final = "JETSON_ORIN_NX" +JETSON_ORIN_NANO: Final = "JETSON_ORIN_NANO" +JETSON_THOR_REFERENCE: Final = "JETSON_THOR_REFERENCE" + +JETSON_MODELS: list[str] + +JETSON_ORIN_NX_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None, int]] +compats_jetson_orins_nx: Sequence[str] +compats_jetson_orins_nano: Sequence[str] + +JETSON_ORIN_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None, int]] +compats_jetson_orins: Sequence[str] + +CLARA_AGX_XAVIER_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_clara_agx_xavier: Sequence[str] + +JETSON_NX_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_nx: Sequence[str] + +JETSON_XAVIER_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_xavier: Sequence[str] + +JETSON_TX2_NX_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_tx2_nx: Sequence[str] + +JETSON_TX2_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_tx2: Sequence[str] + +JETSON_TX1_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_tx1: Sequence[str] + +JETSON_NANO_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_nano: Sequence[str] + +JETSON_THOR_REFERENCE_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_jetson_thor_reference: Sequence[str] + +jetson_gpio_data: dict[str, tuple[list[tuple[int, str, str, int, int, str, str, str | None, int | None]], dict[str, Any]]] + +class ChannelInfo: + channel: int + chip_fd: int | None + line_handle: int | None + line_offset: int + direction: int | None + edge: int | None + consumer: str + gpio_name: str + gpio_chip: str + pwm_chip_dir: str + pwm_id: int + reg_addr: int | None + def __init__( + self, + channel: int, + line_offset: int, + gpio_name: str, + gpio_chip: str, + pwm_chip_dir: str, + pwm_id: int, + reg_addr: int | None = None, + ) -> None: ... + +ids_warned: bool + +def find_pmgr_board(prefix: str) -> str | None: ... +def warn_if_not_carrier_board(*carrier_boards: str) -> None: ... +def get_compatibles(compatible_path: str) -> list[str]: ... +def get_model() -> str: ... +def get_data() -> tuple[str, Any, dict[str, dict[Any, ChannelInfo]]]: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi new file mode 100644 index 000000000000..1cffa0bf2012 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterable + +def lookup_mux_register( + gpio_pin: int, pin_defs: Iterable[tuple[int, str, str, int, int, str, str, str | None, int | None, int]] +) -> int: ... +def main() -> None: ... diff --git a/stdlib/@python2/xml/etree/__init__.pyi b/stubs/Jetson.GPIO/Jetson/__init__.pyi similarity index 100% rename from stdlib/@python2/xml/etree/__init__.pyi rename to stubs/Jetson.GPIO/Jetson/__init__.pyi diff --git a/stubs/Jetson.GPIO/METADATA.toml b/stubs/Jetson.GPIO/METADATA.toml new file mode 100644 index 000000000000..d5b6d8358e23 --- /dev/null +++ b/stubs/Jetson.GPIO/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.1.13" +upstream-repository = "https://github.com/NVIDIA/jetson-gpio" diff --git a/stubs/Markdown/@tests/stubtest_allowlist.txt b/stubs/Markdown/@tests/stubtest_allowlist.txt index a3981e680983..1523b9aa78d0 100644 --- a/stubs/Markdown/@tests/stubtest_allowlist.txt +++ b/stubs/Markdown/@tests/stubtest_allowlist.txt @@ -1,11 +1,4 @@ -markdown.extensions.abbr.ABBR_REF_RE -markdown.extensions.attr_list.AttrListTreeprocessor.run -markdown.extensions.codehilite.CodeHilite.__init__ -markdown.extensions.fenced_code.FencedBlockPreprocessor.__init__ -markdown.extensions.footnotes.DEF_RE -markdown.extensions.footnotes.FootnotePreprocessor -markdown.extensions.footnotes.TABBED_RE -markdown.extensions.legacy_attrs.LegacyAttrs.run -markdown.extensions.toc.TocTreeprocessor.run -markdown.extensions.toc.slugify -markdown.preprocessors.ReferencePreprocessor +# Deprecated types are infered as functions: +markdown.extensions.abbr.AbbrPreprocessor +markdown.extensions.abbr.AbbrInlineProcessor +markdown.postprocessors.UnescapePostprocessor diff --git a/stubs/Markdown/METADATA.toml b/stubs/Markdown/METADATA.toml index b713bbfd10a8..1e61a2413cbb 100644 --- a/stubs/Markdown/METADATA.toml +++ b/stubs/Markdown/METADATA.toml @@ -1 +1,2 @@ -version = "3.3.*" +version = "~=3.10.2" +upstream-repository = "https://github.com/Python-Markdown/markdown" diff --git a/stubs/Markdown/markdown/__init__.pyi b/stubs/Markdown/markdown/__init__.pyi index 3f57adcc43a2..f9e1394976fb 100644 --- a/stubs/Markdown/markdown/__init__.pyi +++ b/stubs/Markdown/markdown/__init__.pyi @@ -1,2 +1,5 @@ +from .__meta__ import __version__ as __version__, __version_info__ as __version_info__ from .core import Markdown as Markdown, markdown as markdown, markdownFromFile as markdownFromFile from .extensions import Extension as Extension + +__all__ = ["Markdown", "markdown", "markdownFromFile"] diff --git a/stubs/Markdown/markdown/__main__.pyi b/stubs/Markdown/markdown/__main__.pyi new file mode 100644 index 000000000000..ca90cb1fa7f1 --- /dev/null +++ b/stubs/Markdown/markdown/__main__.pyi @@ -0,0 +1,10 @@ +import optparse +from logging import Logger +from typing import Any + +logger: Logger + +def parse_options( + args: list[str] | None = None, values: optparse.Values | None = None +) -> tuple[dict[str, Any], Any]: ... # first item is opts dict, second item is Values.verbose field +def run() -> None: ... diff --git a/stubs/Markdown/markdown/blockparser.pyi b/stubs/Markdown/markdown/blockparser.pyi index a747902f718e..805eb13c47c3 100644 --- a/stubs/Markdown/markdown/blockparser.pyi +++ b/stubs/Markdown/markdown/blockparser.pyi @@ -1,23 +1,22 @@ -from typing import Any, Iterable, List, TypeVar +from collections.abc import Iterable +from typing import Any, TypeVar from xml.etree.ElementTree import Element, ElementTree -from . import Markdown -from .util import Registry +from markdown import blockprocessors as _blockprocessors, util +from markdown.core import Markdown _T = TypeVar("_T") -class State(List[_T]): +class State(list[_T]): def set(self, state: _T) -> None: ... def reset(self) -> None: ... def isstate(self, state: _T) -> bool: ... class BlockParser: - blockprocessors: Registry + blockprocessors: util.Registry[_blockprocessors.BlockProcessor] state: State[Any] # TODO: possible to get rid of Any? md: Markdown def __init__(self, md: Markdown) -> None: ... - @property - def markdown(self): ... # deprecated root: Element def parseDocument(self, lines: Iterable[str]) -> ElementTree: ... def parseChunk(self, parent: Element, text: str) -> None: ... diff --git a/stubs/Markdown/markdown/blockprocessors.pyi b/stubs/Markdown/markdown/blockprocessors.pyi index c0879126e457..0b9461c82134 100644 --- a/stubs/Markdown/markdown/blockprocessors.pyi +++ b/stubs/Markdown/markdown/blockprocessors.pyi @@ -1,24 +1,24 @@ from logging import Logger -from typing import Any, Match, Pattern +from re import Match, Pattern +from typing import Any, ClassVar from xml.etree.ElementTree import Element -from markdown import Markdown - -from .blockparser import BlockParser +from markdown.blockparser import BlockParser +from markdown.core import Markdown logger: Logger -def build_block_parser(md: Markdown, **kwargs: Any): ... +def build_block_parser(md: Markdown, **kwargs: Any) -> BlockParser: ... class BlockProcessor: parser: BlockParser tab_length: int def __init__(self, parser: BlockParser) -> None: ... def lastChild(self, parent: Element) -> Element | None: ... - def detab(self, text: str, length: int | None = ...): ... - def looseDetab(self, text: str, level: int = ...): ... - def test(self, parent: Element, block: str) -> None: ... - def run(self, parent: Element, blocks: list[str]) -> None: ... + def detab(self, text: str, length: int | None = None) -> tuple[str, str]: ... + def looseDetab(self, text: str, level: int = 1) -> str: ... + def test(self, parent: Element, block: str) -> bool: ... + def run(self, parent: Element, blocks: list[str]) -> bool | None: ... class ListIndentProcessor(BlockProcessor): ITEM_TYPES: list[str] @@ -35,10 +35,10 @@ class BlockQuoteProcessor(BlockProcessor): def clean(self, line: str) -> str: ... class OListProcessor(BlockProcessor): - TAG: str = ... - STARTSWITH: str = ... - LAZY_OL: bool = ... - SIBLING_TAGS: list[str] + TAG: ClassVar[str] + STARTSWITH: ClassVar[str] + LAZY_OL: ClassVar[bool] + SIBLING_TAGS: ClassVar[list[str]] RE: Pattern[str] CHILD_RE: Pattern[str] INDENT_RE: Pattern[str] @@ -46,24 +46,22 @@ class OListProcessor(BlockProcessor): def get_items(self, block: str) -> list[str]: ... class UListProcessor(OListProcessor): - TAG: str = ... - RE: Pattern[str] def __init__(self, parser: BlockParser) -> None: ... class HashHeaderProcessor(BlockProcessor): - RE: Pattern[str] + RE: ClassVar[Pattern[str]] class SetextHeaderProcessor(BlockProcessor): - RE: Pattern[str] + RE: ClassVar[Pattern[str]] class HRProcessor(BlockProcessor): - RE: str = ... - SEARCH_RE: Pattern[str] + RE: ClassVar[str] + SEARCH_RE: ClassVar[Pattern[str]] match: Match[str] class EmptyBlockProcessor(BlockProcessor): ... class ReferenceProcessor(BlockProcessor): - RE: Pattern[str] + RE: ClassVar[Pattern[str]] class ParagraphProcessor(BlockProcessor): ... diff --git a/stubs/Markdown/markdown/core.pyi b/stubs/Markdown/markdown/core.pyi index e43df00dfdb1..98972399f1ea 100644 --- a/stubs/Markdown/markdown/core.pyi +++ b/stubs/Markdown/markdown/core.pyi @@ -1,23 +1,40 @@ -from typing import Any, BinaryIO, Callable, ClassVar, Mapping, Sequence, Text, TextIO -from typing_extensions import Literal +from codecs import _ReadableStream, _WritableStream +from collections.abc import Callable, Mapping, Sequence +from logging import Logger +from typing import Any, ClassVar, Literal +from typing_extensions import Self from xml.etree.ElementTree import Element -from .blockparser import BlockParser +from . import ( + blockparser, + inlinepatterns, + postprocessors as _postprocessors, + preprocessors as _preprocessors, + treeprocessors as _treeprocessors, +) from .extensions import Extension from .util import HtmlStash, Registry +__all__ = ["Markdown", "markdown", "markdownFromFile"] + +logger: Logger + class Markdown: - preprocessors: Registry - inlinePatterns: Registry - treeprocessors: Registry - postprocessors: Registry - parser: BlockParser + preprocessors: Registry[_preprocessors.Preprocessor] + inlinePatterns: Registry[inlinepatterns.Pattern] + treeprocessors: Registry[_treeprocessors.Treeprocessor] + postprocessors: Registry[_postprocessors.Postprocessor] + parser: blockparser.BlockParser htmlStash: HtmlStash - output_formats: ClassVar[dict[Literal["xhtml", "html"], Callable[[Element], Text]]] + output_formats: ClassVar[dict[Literal["xhtml", "html"], Callable[[Element], str]]] output_format: Literal["xhtml", "html"] - serializer: Callable[[Element], Text] + serializer: Callable[[Element], str] tab_length: int block_level_elements: list[str] + registeredExtensions: list[Extension] + ESCAPED_CHARS: list[str] + doc_tag: ClassVar[str] + stripTopLevelTags: bool def __init__( self, *, @@ -26,33 +43,30 @@ class Markdown: output_format: Literal["xhtml", "html"] | None = ..., tab_length: int | None = ..., ) -> None: ... - def build_parser(self) -> Markdown: ... - def registerExtensions(self, extensions: Sequence[Extension | str], configs: Mapping[str, Mapping[str, Any]]) -> Markdown: ... - def build_extension(self, ext_name: Text, configs: Mapping[str, str]) -> Extension: ... - def registerExtension(self, extension: Extension) -> Markdown: ... - def reset(self: Markdown) -> Markdown: ... - def set_output_format(self, format: Literal["xhtml", "html"]) -> Markdown: ... - def is_block_level(self, tag: str) -> bool: ... - def convert(self, source: Text) -> Text: ... + def build_parser(self) -> Self: ... + def registerExtensions(self, extensions: Sequence[Extension | str], configs: Mapping[str, dict[str, Any]]) -> Self: ... + def build_extension(self, ext_name: str, configs: Mapping[str, Any]) -> Extension: ... + def registerExtension(self, extension: Extension) -> Self: ... + def reset(self) -> Self: ... + def set_output_format(self, format: Literal["xhtml", "html"]) -> Self: ... + def is_block_level(self, tag: object) -> bool: ... + def convert(self, source: str) -> str: ... def convertFile( - self, - input: str | TextIO | BinaryIO | None = ..., - output: str | TextIO | BinaryIO | None = ..., - encoding: str | None = ..., - ) -> Markdown: ... + self, input: str | _ReadableStream | None = None, output: str | _WritableStream | None = None, encoding: str | None = None + ) -> Self: ... def markdown( - text: Text, + text: str, *, extensions: Sequence[str | Extension] | None = ..., extension_configs: Mapping[str, Mapping[str, Any]] | None = ..., output_format: Literal["xhtml", "html"] | None = ..., tab_length: int | None = ..., -) -> Text: ... +) -> str: ... def markdownFromFile( *, - input: str | TextIO | BinaryIO | None = ..., - output: str | TextIO | BinaryIO | None = ..., + input: str | _ReadableStream | None = ..., + output: str | _WritableStream | None = ..., encoding: str | None = ..., extensions: Sequence[str | Extension] | None = ..., extension_configs: Mapping[str, Mapping[str, Any]] | None = ..., diff --git a/stubs/Markdown/markdown/extensions/__init__.pyi b/stubs/Markdown/markdown/extensions/__init__.pyi index 8b6cd2a4795f..2ae632654e0f 100644 --- a/stubs/Markdown/markdown/extensions/__init__.pyi +++ b/stubs/Markdown/markdown/extensions/__init__.pyi @@ -1,13 +1,14 @@ -from typing import Any, Mapping +from collections.abc import Iterable, Mapping +from typing import Any from markdown.core import Markdown class Extension: - config: Mapping[str, list[Any]] = ... + config: Mapping[str, list[Any]] def __init__(self, **kwargs: Any) -> None: ... - def getConfig(self, key: str, default: Any = ...) -> Any: ... + def getConfig(self, key: str, default: Any = "") -> Any: ... def getConfigs(self) -> dict[str, Any]: ... def getConfigInfo(self) -> list[tuple[str, str]]: ... def setConfig(self, key: str, value: Any) -> None: ... - def setConfigs(self, items: Mapping[str, Any]) -> None: ... + def setConfigs(self, items: Mapping[str, Any] | Iterable[tuple[str, Any]]) -> None: ... def extendMarkdown(self, md: Markdown) -> None: ... diff --git a/stubs/Markdown/markdown/extensions/abbr.pyi b/stubs/Markdown/markdown/extensions/abbr.pyi index a3469d16153e..810ab601625f 100644 --- a/stubs/Markdown/markdown/extensions/abbr.pyi +++ b/stubs/Markdown/markdown/extensions/abbr.pyi @@ -1,16 +1,39 @@ -from typing import Any, Pattern +from re import Pattern +from typing import ClassVar +from typing_extensions import deprecated +from xml.etree.ElementTree import Element +from markdown.blockparser import BlockParser from markdown.blockprocessors import BlockProcessor +from markdown.core import Markdown from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor +from markdown.treeprocessors import Treeprocessor -ABBR_REF_RE: Pattern[str] +class AbbrExtension(Extension): + def reset(self) -> None: ... + def reset_glossary(self) -> None: ... + def load_glossary(self, dictionary: dict[str, str]) -> None: ... -class AbbrExtension(Extension): ... -class AbbrPreprocessor(BlockProcessor): ... +class AbbrTreeprocessor(Treeprocessor): + RE: Pattern[str] | None + abbrs: dict[str, str] + def __init__(self, md: Markdown | None = None, abbrs: dict[str, str] | None = None) -> None: ... + def create_element(self, title: str, text: str, tail: str) -> Element: ... + def iter_element(self, el: Element, parent: Element | None = None) -> None: ... +# Techinically it is the same type as `AbbrPreprocessor` just not deprecated. +class AbbrBlockprocessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + abbrs: dict[str, str] + def __init__(self, parser: BlockParser, abbrs: dict[str, str]) -> None: ... + +@deprecated("This class will be removed in the future; use `AbbrTreeprocessor` instead.") +class AbbrPreprocessor(AbbrBlockprocessor): ... + +@deprecated("This class will be removed in the future; use `AbbrTreeprocessor` instead.") class AbbrInlineProcessor(InlineProcessor): - title: Any - def __init__(self, pattern, title) -> None: ... + title: str + def __init__(self, pattern: str, title: str) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> AbbrExtension: ... diff --git a/stubs/Markdown/markdown/extensions/admonition.pyi b/stubs/Markdown/markdown/extensions/admonition.pyi index 912c6ced01da..0225c528edd7 100644 --- a/stubs/Markdown/markdown/extensions/admonition.pyi +++ b/stubs/Markdown/markdown/extensions/admonition.pyi @@ -1,5 +1,8 @@ -from typing import Any, Pattern +from re import Match, Pattern +from typing import ClassVar +from xml.etree.ElementTree import Element +from markdown import blockparser from markdown.blockprocessors import BlockProcessor from markdown.extensions import Extension @@ -8,8 +11,12 @@ class AdmonitionExtension(Extension): ... class AdmonitionProcessor(BlockProcessor): CLASSNAME: str CLASSNAME_TITLE: str - RE: Pattern[str] - RE_SPACES: Any - def get_class_and_title(self, match): ... + RE: ClassVar[Pattern[str]] + RE_SPACES: ClassVar[Pattern[str]] + current_sibling: Element | None + content_indent: int + def __init__(self, parser: blockparser.BlockParser) -> None: ... + def parse_content(self, parent: Element, block: str) -> tuple[Element | None, str, str]: ... + def get_class_and_title(self, match: Match[str]) -> tuple[str, str | None]: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> AdmonitionExtension: ... diff --git a/stubs/Markdown/markdown/extensions/attr_list.pyi b/stubs/Markdown/markdown/extensions/attr_list.pyi index 416193a54e4f..0a837e583259 100644 --- a/stubs/Markdown/markdown/extensions/attr_list.pyi +++ b/stubs/Markdown/markdown/extensions/attr_list.pyi @@ -1,10 +1,12 @@ -from typing import Pattern +from re import Pattern +from xml.etree.ElementTree import Element from markdown.extensions import Extension from markdown.treeprocessors import Treeprocessor -def get_attrs(str): ... -def isheader(elem): ... +def get_attrs_and_remainder(attrs_string: str) -> tuple[list[tuple[str, str]], str]: ... +def get_attrs(str: str) -> list[tuple[str, str]]: ... +def isheader(elem: Element) -> bool: ... class AttrListTreeprocessor(Treeprocessor): BASE_RE: str @@ -12,9 +14,10 @@ class AttrListTreeprocessor(Treeprocessor): BLOCK_RE: Pattern[str] INLINE_RE: Pattern[str] NAME_RE: Pattern[str] - def assign_attrs(self, elem, attrs) -> None: ... - def sanitize_name(self, name): ... + def run(self, doc: Element) -> None: ... + def assign_attrs(self, elem: Element, attrs_string: str, *, strict: bool = False) -> str: ... + def sanitize_name(self, name: str) -> str: ... class AttrListExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> AttrListExtension: ... diff --git a/stubs/Markdown/markdown/extensions/codehilite.pyi b/stubs/Markdown/markdown/extensions/codehilite.pyi index bcd43c347b94..b7458a80978e 100644 --- a/stubs/Markdown/markdown/extensions/codehilite.pyi +++ b/stubs/Markdown/markdown/extensions/codehilite.pyi @@ -5,41 +5,38 @@ from markdown.treeprocessors import Treeprocessor pygments: bool -def parse_hl_lines(expr): ... +def parse_hl_lines(expr: str) -> list[int]: ... class CodeHilite: - src: Any - lang: Any - linenums: Any - guess_lang: Any - css_class: Any - style: Any - noclasses: Any - tab_length: Any - hl_lines: Any - use_pygments: Any + src: str + lang: str | None + guess_lang: bool + use_pygments: bool + lang_prefix: str + pygments_formatter: Any options: dict[str, Any] def __init__( self, - src: Any | None = ..., + src: str, *, - linenums: Any | None = ..., + linenums: bool | None = None, guess_lang: bool = ..., css_class: str = ..., - lang: Any | None = ..., + lang: str | None = ..., style: str = ..., noclasses: bool = ..., tab_length: int = ..., - hl_lines: Any | None = ..., + hl_lines: list[int] = ..., use_pygments: bool = ..., **options: Any, ) -> None: ... - def hilite(self, shebang: bool = ...) -> str: ... + def hilite(self, shebang: bool = True) -> str: ... class HiliteTreeprocessor(Treeprocessor): - def code_unescape(self, text): ... + config: dict[str, Any] + def code_unescape(self, text: str) -> str: ... class CodeHiliteExtension(Extension): def __init__(self, **kwargs) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> CodeHiliteExtension: ... diff --git a/stubs/Markdown/markdown/extensions/def_list.pyi b/stubs/Markdown/markdown/extensions/def_list.pyi index 187003c8a04e..345ea5077d5b 100644 --- a/stubs/Markdown/markdown/extensions/def_list.pyi +++ b/stubs/Markdown/markdown/extensions/def_list.pyi @@ -1,4 +1,4 @@ -from typing import Pattern +from re import Pattern from markdown.blockprocessors import BlockProcessor, ListIndentProcessor from markdown.extensions import Extension @@ -10,4 +10,4 @@ class DefListProcessor(BlockProcessor): class DefListIndentProcessor(ListIndentProcessor): ... class DefListExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> DefListExtension: ... diff --git a/stubs/Markdown/markdown/extensions/extra.pyi b/stubs/Markdown/markdown/extensions/extra.pyi index 8d761845cd5c..b063970d1a05 100644 --- a/stubs/Markdown/markdown/extensions/extra.pyi +++ b/stubs/Markdown/markdown/extensions/extra.pyi @@ -1,10 +1,8 @@ -from typing import Any - from markdown.extensions import Extension -extensions: Any +extensions: list[str] class ExtraExtension(Extension): def __init__(self, **kwargs) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> ExtraExtension: ... diff --git a/stubs/Markdown/markdown/extensions/fenced_code.pyi b/stubs/Markdown/markdown/extensions/fenced_code.pyi index 9aab6be9ba87..39810ab260c8 100644 --- a/stubs/Markdown/markdown/extensions/fenced_code.pyi +++ b/stubs/Markdown/markdown/extensions/fenced_code.pyi @@ -1,16 +1,21 @@ -from typing import Any, Pattern +from collections.abc import Iterable +from re import Pattern +from typing import Any, ClassVar +from markdown.core import Markdown from markdown.extensions import Extension from markdown.preprocessors import Preprocessor -class FencedCodeExtension(Extension): ... +class FencedCodeExtension(Extension): + def __init__(self, **kwargs) -> None: ... class FencedBlockPreprocessor(Preprocessor): - FENCED_BLOCK_RE: Pattern[str] - CODE_WRAP: str = ... - LANG_TAG: str = ... - checked_for_codehilite: bool = ... - codehilite_conf: Any - def __init__(self, md) -> None: ... + FENCED_BLOCK_RE: ClassVar[Pattern[str]] + checked_for_deps: bool + codehilite_conf: dict[str, Any] + use_attr_list: bool + bool_options: list[str] + def __init__(self, md: Markdown, config: dict[str, Any]) -> None: ... + def handle_attrs(self, attrs: Iterable[tuple[str, str]]) -> tuple[str, list[str], dict[str, Any]]: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> FencedCodeExtension: ... diff --git a/stubs/Markdown/markdown/extensions/footnotes.pyi b/stubs/Markdown/markdown/extensions/footnotes.pyi index b49e3a937841..f1535eb79140 100644 --- a/stubs/Markdown/markdown/extensions/footnotes.pyi +++ b/stubs/Markdown/markdown/extensions/footnotes.pyi @@ -1,57 +1,73 @@ -from typing import Any, Pattern +from collections import OrderedDict +from re import Pattern +from typing import ClassVar +from xml.etree.ElementTree import Element +from markdown.blockparser import BlockParser +from markdown.blockprocessors import BlockProcessor +from markdown.core import Markdown from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor from markdown.postprocessors import Postprocessor -from markdown.preprocessors import Preprocessor from markdown.treeprocessors import Treeprocessor -FN_BACKLINK_TEXT: Any -NBSP_PLACEHOLDER: Any -DEF_RE: Pattern[str] -TABBED_RE: Pattern[str] -RE_REF_ID: Any +FN_BACKLINK_TEXT: str +NBSP_PLACEHOLDER: str +RE_REF_ID: Pattern[str] +RE_REFERENCE: Pattern[str] class FootnoteExtension(Extension): - unique_prefix: int = ... - found_refs: Any - used_refs: Any + unique_prefix: int + found_refs: dict[str, int] + used_refs: set[str] def __init__(self, **kwargs) -> None: ... - parser: Any - md: Any - footnotes: Any + parser: BlockParser + md: Markdown + footnote_order: list[str] + footnotes: OrderedDict[str, str] def reset(self) -> None: ... - def unique_ref(self, reference, found: bool = ...): ... - def findFootnotesPlaceholder(self, root): ... - def setFootnote(self, id, text) -> None: ... - def get_separator(self): ... - def makeFootnoteId(self, id): ... - def makeFootnoteRefId(self, id, found: bool = ...): ... - def makeFootnotesDiv(self, root): ... - -class FootnotePreprocessor(Preprocessor): - footnotes: Any - def __init__(self, footnotes) -> None: ... - def detectTabbed(self, lines): ... + def unique_ref(self, reference: str, found: bool = False) -> str: ... + def findFootnotesPlaceholder(self, root: Element) -> tuple[Element, Element, bool] | None: ... + def setFootnote(self, id: str, text: str) -> None: ... + def addFootnoteRef(self, id: str) -> None: ... + def get_separator(self) -> str: ... + def makeFootnoteId(self, id: str) -> str: ... + def makeFootnoteRefId(self, id: str, found: bool = False) -> str: ... + def makeFootnotesDiv(self, root: Element) -> Element | None: ... + +class FootnoteBlockProcessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def detectTabbed(self, blocks: list[str]) -> list[str]: ... + def detab(self, block: str) -> str: ... # type: ignore[override] class FootnoteInlineProcessor(InlineProcessor): - footnotes: Any - def __init__(self, pattern, footnotes) -> None: ... + footnotes: FootnoteExtension + def __init__(self, pattern: str, footnotes: FootnoteExtension) -> None: ... class FootnotePostTreeprocessor(Treeprocessor): - footnotes: Any - def __init__(self, footnotes) -> None: ... - def add_duplicates(self, li, duplicates) -> None: ... - def get_num_duplicates(self, li): ... - def handle_duplicates(self, parent) -> None: ... - offset: int = ... + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def add_duplicates(self, li: Element, duplicates: int) -> None: ... + def get_num_duplicates(self, li: Element) -> int: ... + def handle_duplicates(self, parent: Element) -> None: ... + def run(self, root: Element) -> None: ... + offset: int class FootnoteTreeprocessor(Treeprocessor): - footnotes: Any - def __init__(self, footnotes) -> None: ... + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def run(self, root: Element) -> None: ... + +class FootnoteReorderingProcessor(Treeprocessor): + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def run(self, root: Element) -> None: ... + def reorder_footnotes(self, parent: Element) -> None: ... class FootnotePostprocessor(Postprocessor): - footnotes: Any - def __init__(self, footnotes) -> None: ... + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> FootnoteExtension: ... diff --git a/stubs/Markdown/markdown/extensions/legacy_attrs.pyi b/stubs/Markdown/markdown/extensions/legacy_attrs.pyi index 6e068277fab5..9464f3dff24d 100644 --- a/stubs/Markdown/markdown/extensions/legacy_attrs.pyi +++ b/stubs/Markdown/markdown/extensions/legacy_attrs.pyi @@ -1,4 +1,5 @@ -from typing import Pattern +from re import Pattern +from xml.etree.ElementTree import Element from markdown.extensions import Extension from markdown.treeprocessors import Treeprocessor @@ -6,8 +7,9 @@ from markdown.treeprocessors import Treeprocessor ATTR_RE: Pattern[str] class LegacyAttrs(Treeprocessor): - def handleAttributes(self, el, txt): ... + def run(self, doc: Element) -> None: ... + def handleAttributes(self, el: Element, txt: str) -> str: ... class LegacyAttrExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> LegacyAttrExtension: ... diff --git a/stubs/Markdown/markdown/extensions/legacy_em.pyi b/stubs/Markdown/markdown/extensions/legacy_em.pyi index dadaa8ee3cff..3ea44f44c74f 100644 --- a/stubs/Markdown/markdown/extensions/legacy_em.pyi +++ b/stubs/Markdown/markdown/extensions/legacy_em.pyi @@ -8,4 +8,4 @@ STRONG_EM_RE: str class LegacyUnderscoreProcessor(UnderscoreProcessor): ... class LegacyEmExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> LegacyEmExtension: ... diff --git a/stubs/Markdown/markdown/extensions/md_in_html.pyi b/stubs/Markdown/markdown/extensions/md_in_html.pyi index 2e7e9823b3ed..29cb8f631c11 100644 --- a/stubs/Markdown/markdown/extensions/md_in_html.pyi +++ b/stubs/Markdown/markdown/extensions/md_in_html.pyi @@ -1,7 +1,41 @@ +from collections.abc import Iterable, Mapping +from typing import Literal +from xml.etree.ElementTree import Element, TreeBuilder + from markdown.blockprocessors import BlockProcessor from markdown.extensions import Extension +from markdown.htmlparser import HTMLExtractor +from markdown.postprocessors import RawHtmlPostprocessor +from markdown.preprocessors import Preprocessor + +class HTMLExtractorExtra(HTMLExtractor): + block_level_tags: set[str] + span_tags: set[str] + raw_tags: set[str] + block_tags: set[str] + span_and_blocks_tags: set[str] + mdstack: list[str] + treebuilder: TreeBuilder + mdstate: list[Literal["block", "span", "off"] | None] + mdstarted: list[bool] + def get_element(self) -> Element: ... + def get_state(self, tag: str, attrs: Mapping[str, str]) -> Literal["block", "span", "off"] | None: ... + def handle_starttag(self, tag: str, attrs: Iterable[tuple[str, str | None]]) -> None: ... + def handle_endtag(self, tag: str) -> None: ... + def handle_startendtag(self, tag: str, attrs: Iterable[tuple[str, str | None]]) -> None: ... + def handle_data(self, data: str) -> None: ... + def handle_empty_tag(self, data: str, is_block: bool) -> None: ... + def parse_pi(self, i: int) -> int: ... + def parse_html_declaration(self, i: int) -> int: ... + +class HtmlBlockPreprocessor(Preprocessor): ... + +class MarkdownInHtmlProcessor(BlockProcessor): + def parse_element_content(self, element: Element) -> None: ... + +class MarkdownInHTMLPostprocessor(RawHtmlPostprocessor): + def stash_to_string(self, text: str | Element) -> str: ... -class MarkdownInHtmlProcessor(BlockProcessor): ... class MarkdownInHtmlExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> MarkdownInHtmlExtension: ... diff --git a/stubs/Markdown/markdown/extensions/meta.pyi b/stubs/Markdown/markdown/extensions/meta.pyi index f6c0621bed64..d6a7f42a807f 100644 --- a/stubs/Markdown/markdown/extensions/meta.pyi +++ b/stubs/Markdown/markdown/extensions/meta.pyi @@ -1,18 +1,20 @@ -from typing import Any, Pattern +from logging import Logger +from re import Pattern +from markdown.core import Markdown from markdown.extensions import Extension from markdown.preprocessors import Preprocessor -log: Any +log: Logger META_RE: Pattern[str] META_MORE_RE: Pattern[str] BEGIN_RE: Pattern[str] END_RE: Pattern[str] class MetaExtension(Extension): - md: Any + md: Markdown def reset(self) -> None: ... class MetaPreprocessor(Preprocessor): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> MetaExtension: ... diff --git a/stubs/Markdown/markdown/extensions/nl2br.pyi b/stubs/Markdown/markdown/extensions/nl2br.pyi index 81dd1fb6feae..914d39554187 100644 --- a/stubs/Markdown/markdown/extensions/nl2br.pyi +++ b/stubs/Markdown/markdown/extensions/nl2br.pyi @@ -4,4 +4,4 @@ BR_RE: str class Nl2BrExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> Nl2BrExtension: ... diff --git a/stubs/Markdown/markdown/extensions/sane_lists.pyi b/stubs/Markdown/markdown/extensions/sane_lists.pyi index 31022c69970a..62404bee41db 100644 --- a/stubs/Markdown/markdown/extensions/sane_lists.pyi +++ b/stubs/Markdown/markdown/extensions/sane_lists.pyi @@ -1,12 +1,13 @@ +from markdown import blockparser from markdown.blockprocessors import OListProcessor, UListProcessor from markdown.extensions import Extension class SaneOListProcessor(OListProcessor): - def __init__(self, parser) -> None: ... + def __init__(self, parser: blockparser.BlockParser) -> None: ... class SaneUListProcessor(UListProcessor): - def __init__(self, parser) -> None: ... + def __init__(self, parser: blockparser.BlockParser) -> None: ... class SaneListExtension(Extension): ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> SaneListExtension: ... diff --git a/stubs/Markdown/markdown/extensions/smarty.pyi b/stubs/Markdown/markdown/extensions/smarty.pyi index 6b237163de36..eca70b7b7027 100644 --- a/stubs/Markdown/markdown/extensions/smarty.pyi +++ b/stubs/Markdown/markdown/extensions/smarty.pyi @@ -1,5 +1,8 @@ -from typing import Any +from collections.abc import Mapping, Sequence +from xml.etree.ElementTree import Element +from markdown import inlinepatterns, util +from markdown.core import Markdown from markdown.extensions import Extension from markdown.inlinepatterns import HtmlInlineProcessor @@ -7,33 +10,35 @@ punctClass: str endOfWordClass: str closeClass: str openingQuotesBase: str -substitutions: Any -singleQuoteStartRe: Any -doubleQuoteStartRe: Any +substitutions: Mapping[str, str] +singleQuoteStartRe: str +doubleQuoteStartRe: str doubleQuoteSetsRe: str singleQuoteSetsRe: str +doubleQuoteSetsRe2: str +singleQuoteSetsRe2: str decadeAbbrRe: str -openingDoubleQuotesRegex: Any +openingDoubleQuotesRegex: str closingDoubleQuotesRegex: str -closingDoubleQuotesRegex2: Any -openingSingleQuotesRegex: Any -closingSingleQuotesRegex: Any -closingSingleQuotesRegex2: Any +closingDoubleQuotesRegex2: str +openingSingleQuotesRegex: str +closingSingleQuotesRegex: str +closingSingleQuotesRegex2: str remainingSingleQuotesRegex: str remainingDoubleQuotesRegex: str HTML_STRICT_RE: str class SubstituteTextPattern(HtmlInlineProcessor): - replace: Any - def __init__(self, pattern, replace, md) -> None: ... + replace: Sequence[int | str | Element] + def __init__(self, pattern: str, replace: Sequence[int | str | Element], md: Markdown) -> None: ... class SmartyExtension(Extension): - substitutions: Any + substitutions: dict[str, str] def __init__(self, **kwargs) -> None: ... - def educateDashes(self, md) -> None: ... - def educateEllipses(self, md) -> None: ... - def educateAngledQuotes(self, md) -> None: ... - def educateQuotes(self, md) -> None: ... - inlinePatterns: Any + def educateDashes(self, md: Markdown) -> None: ... + def educateEllipses(self, md: Markdown) -> None: ... + def educateAngledQuotes(self, md: Markdown) -> None: ... + def educateQuotes(self, md: Markdown) -> None: ... + inlinePatterns: util.Registry[inlinepatterns.Pattern] -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> SmartyExtension: ... diff --git a/stubs/Markdown/markdown/extensions/tables.pyi b/stubs/Markdown/markdown/extensions/tables.pyi index 2250cae7ee12..a6ee99d7aac0 100644 --- a/stubs/Markdown/markdown/extensions/tables.pyi +++ b/stubs/Markdown/markdown/extensions/tables.pyi @@ -1,5 +1,7 @@ -from typing import Any +from re import Pattern +from typing import Any, ClassVar +from markdown import blockparser from markdown.blockprocessors import BlockProcessor from markdown.extensions import Extension @@ -8,12 +10,13 @@ PIPE_LEFT: int PIPE_RIGHT: int class TableProcessor(BlockProcessor): - RE_CODE_PIPES: Any - RE_END_BORDER: Any - border: bool = ... - separator: str = ... - def __init__(self, parser) -> None: ... + RE_CODE_PIPES: ClassVar[Pattern[str]] + RE_END_BORDER: ClassVar[Pattern[str]] + border: bool + separator: str + def __init__(self, parser: blockparser.BlockParser, config: dict[str, Any]) -> None: ... -class TableExtension(Extension): ... +class TableExtension(Extension): + def __init__(self, **kwargs) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> TableExtension: ... diff --git a/stubs/Markdown/markdown/extensions/toc.pyi b/stubs/Markdown/markdown/extensions/toc.pyi index 1315e77e4c1e..27fd77b833ff 100644 --- a/stubs/Markdown/markdown/extensions/toc.pyi +++ b/stubs/Markdown/markdown/extensions/toc.pyi @@ -1,44 +1,70 @@ -from typing import Any, Pattern +from collections.abc import Iterator, MutableSet +from re import Pattern +from typing import Any, TypedDict, type_check_only +from typing_extensions import deprecated +from xml.etree.ElementTree import Element +from markdown.core import Markdown from markdown.extensions import Extension from markdown.treeprocessors import Treeprocessor -def slugify(value, separator): ... - IDCOUNT_RE: Pattern[str] -def unique(id, ids): ... -def get_name(el): ... -def stashedHTML2text(text, md, strip_entities: bool = ...): ... -def unescape(text): ... -def nest_toc_tokens(toc_list): ... +@type_check_only +class _FlatTocToken(TypedDict): + level: int + id: str + name: str + +@type_check_only +class _TocToken(_FlatTocToken): + children: list[_TocToken] + +def slugify(value: str, separator: str, unicode: bool = False) -> str: ... +def slugify_unicode(value: str, separator: str) -> str: ... +def unique(id: str, ids: MutableSet[str]) -> str: ... +@deprecated("Use `render_inner_html` and `striptags` instead.") +def get_name(el: Element) -> str: ... +@deprecated("Use `run_postprocessors`, `render_inner_html` and/or `striptags` instead.") +def stashedHTML2text(text: str, md: Markdown, strip_entities: bool = True) -> str: ... +def unescape(text: str) -> str: ... +def strip_tags(text: str) -> str: ... +def escape_cdata(text: str) -> str: ... +def run_postprocessors(text: str, md: Markdown) -> str: ... +def render_inner_html(el: Element, md: Markdown) -> str: ... +def remove_fnrefs(root: Element) -> Element: ... +def nest_toc_tokens(toc_list: list[_FlatTocToken]) -> list[_TocToken]: ... class TocTreeprocessor(Treeprocessor): - marker: Any - title: Any - base_level: Any + marker: str + title: str + base_level: int slugify: Any sep: Any - use_anchors: Any - anchorlink_class: Any - use_permalinks: Any - permalink_class: Any - permalink_title: Any - header_rgx: Any - toc_top: int = ... - toc_bottom: Any - def __init__(self, md, config) -> None: ... - def iterparent(self, node) -> None: ... - def replace_marker(self, root, elem) -> None: ... - def set_level(self, elem) -> None: ... - def add_anchor(self, c, elem_id) -> None: ... - def add_permalink(self, c, elem_id) -> None: ... - def build_toc_div(self, toc_list): ... + toc_class: Any + title_class: str + use_anchors: bool + anchorlink_class: str + use_permalinks: bool + permalink_class: str + permalink_title: str + permalink_leading: bool + header_rgx: Pattern[str] + toc_top: int + toc_bottom: int + def __init__(self, md: Markdown, config: dict[str, Any]) -> None: ... + def iterparent(self, node: Element) -> Iterator[tuple[Element, Element]]: ... + def replace_marker(self, root: Element, elem: Element) -> None: ... + def set_level(self, elem: Element) -> None: ... + def add_anchor(self, c: Element, elem_id: str) -> None: ... + def add_permalink(self, c: Element, elem_id: str) -> None: ... + def build_toc_div(self, toc_list: list[_TocToken]) -> Element: ... + def run(self, doc: Element) -> None: ... class TocExtension(Extension): - TreeProcessorClass: Any + TreeProcessorClass: type[TocTreeprocessor] def __init__(self, **kwargs) -> None: ... - md: Any + md: Markdown def reset(self) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> TocExtension: ... diff --git a/stubs/Markdown/markdown/extensions/wikilinks.pyi b/stubs/Markdown/markdown/extensions/wikilinks.pyi index 044edb0e33e4..d31983af866a 100644 --- a/stubs/Markdown/markdown/extensions/wikilinks.pyi +++ b/stubs/Markdown/markdown/extensions/wikilinks.pyi @@ -1,16 +1,17 @@ from typing import Any +from markdown.core import Markdown from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor -def build_url(label, base, end): ... +def build_url(label: str, base: str, end: str) -> str: ... class WikiLinkExtension(Extension): def __init__(self, **kwargs) -> None: ... - md: Any + md: Markdown class WikiLinksInlineProcessor(InlineProcessor): - config: Any - def __init__(self, pattern, config) -> None: ... + config: dict[str, Any] + def __init__(self, pattern: str, config: dict[str, Any]) -> None: ... -def makeExtension(**kwargs): ... +def makeExtension(**kwargs) -> WikiLinkExtension: ... diff --git a/stubs/Markdown/markdown/htmlparser.pyi b/stubs/Markdown/markdown/htmlparser.pyi new file mode 100644 index 000000000000..b0d95592ef93 --- /dev/null +++ b/stubs/Markdown/markdown/htmlparser.pyi @@ -0,0 +1,29 @@ +import html.parser as htmlparser +import re +from _frozen_importlib import ModuleSpec +from collections.abc import Sequence + +from markdown import Markdown + +spec: ModuleSpec +commentclose: re.Pattern[str] +blank_line_re: re.Pattern[str] + +class HTMLExtractor(htmlparser.HTMLParser): + empty_tags: set[str] + lineno_start_cache: list[int] + md: Markdown + def __init__(self, md: Markdown, *args, **kwargs): ... + inraw: bool + intail: bool + stack: list[str] + cleandoc: list[str] + @property + def line_offset(self) -> int: ... + def at_line_start(self) -> bool: ... + def get_endtag_text(self, tag: str) -> str: ... + def handle_starttag(self, tag: str, attrs: Sequence[tuple[str, str]]) -> None: ... # type: ignore[override] + def handle_empty_tag(self, data: str, is_block: bool) -> None: ... + def handle_decl(self, data: str) -> None: ... + def parse_bogus_comment(self, i: int, report: int = 0) -> int: ... + def get_starttag_text(self) -> str: ... diff --git a/stubs/Markdown/markdown/inlinepatterns.pyi b/stubs/Markdown/markdown/inlinepatterns.pyi index f534661dc26f..00ee4b4f0516 100644 --- a/stubs/Markdown/markdown/inlinepatterns.pyi +++ b/stubs/Markdown/markdown/inlinepatterns.pyi @@ -1,8 +1,12 @@ -import typing -from typing import Any, Match +import re +from collections.abc import Collection +from typing import ClassVar, NamedTuple from xml.etree.ElementTree import Element -def build_inlinepatterns(md, **kwargs): ... +from markdown import util +from markdown.core import Markdown + +def build_inlinepatterns(md: Markdown, **kwargs) -> util.Registry[Pattern]: ... NOIMG: str BACKTICK_RE: str @@ -28,77 +32,81 @@ HTML_RE: str ENTITY_RE: str LINE_BREAK_RE: str -def dequote(string): ... +def dequote(string: str) -> str: ... -class EmStrongItem: ... +class EmStrongItem(NamedTuple): + pattern: re.Pattern[str] + builder: str + tags: str class Pattern: - ANCESTOR_EXCLUDES: Any - pattern: Any - compiled_re: Any - md: Any - def __init__(self, pattern, md: Any | None = ...) -> None: ... - @property - def markdown(self): ... - def getCompiledRegExp(self): ... - def handleMatch(self, m: Match[str]) -> str | Element | None: ... - def type(self): ... - def unescape(self, text): ... + ANCESTOR_EXCLUDES: ClassVar[Collection[str]] + pattern: str + compiled_re: re.Pattern[str] + md: Markdown + def __init__(self, pattern: str, md: Markdown | None = None) -> None: ... + def getCompiledRegExp(self) -> re.Pattern[str]: ... + def handleMatch(self, m: re.Match[str]) -> str | Element | None: ... + def type(self) -> str: ... + def unescape(self, text: str) -> str: ... class InlineProcessor(Pattern): - safe_mode: bool = ... - def __init__(self, pattern, md: Any | None = ...) -> None: ... - def handleMatch(self, m: Match[str], data) -> tuple[Element, int, int] | tuple[None, None, None]: ... # type: ignore[override] + safe_mode: bool + def __init__(self, pattern: str, md: Markdown | None = None) -> None: ... + def handleMatch(self, m: re.Match[str], data: str) -> tuple[Element | str | None, int | None, int | None]: ... # type: ignore[override] class SimpleTextPattern(Pattern): ... class SimpleTextInlineProcessor(InlineProcessor): ... class EscapeInlineProcessor(InlineProcessor): ... class SimpleTagPattern(Pattern): - tag: Any - def __init__(self, pattern, tag) -> None: ... + tag: str + def __init__(self, pattern: str, tag: str) -> None: ... class SimpleTagInlineProcessor(InlineProcessor): - tag: Any - def __init__(self, pattern, tag) -> None: ... + tag: str + def __init__(self, pattern: str, tag: str) -> None: ... class SubstituteTagPattern(SimpleTagPattern): ... class SubstituteTagInlineProcessor(SimpleTagInlineProcessor): ... class BacktickInlineProcessor(InlineProcessor): - ESCAPED_BSLASH: Any - tag: str = ... - def __init__(self, pattern) -> None: ... + ESCAPED_BSLASH: str + tag: str + def __init__(self, pattern: str) -> None: ... class DoubleTagPattern(SimpleTagPattern): ... class DoubleTagInlineProcessor(SimpleTagInlineProcessor): ... -class HtmlInlineProcessor(InlineProcessor): ... + +class HtmlInlineProcessor(InlineProcessor): + def unescape(self, text: str) -> str: ... + def backslash_unescape(self, text: str) -> str: ... class AsteriskProcessor(InlineProcessor): - PATTERNS: Any - def build_single(self, m, tag, idx): ... - def build_double(self, m, tags, idx): ... - def build_double2(self, m, tags, idx): ... - def parse_sub_patterns(self, data, parent, last, idx) -> None: ... - def build_element(self, m, builder, tags, index): ... + PATTERNS: ClassVar[list[EmStrongItem]] + def build_single(self, m: re.Match[str], tag: str, idx: int) -> Element: ... + def build_double(self, m: re.Match[str], tags: str, idx: int) -> Element: ... + def build_double2(self, m: re.Match[str], tags: str, idx: int) -> Element: ... + def parse_sub_patterns(self, data: str, parent: Element, last: Element | None, idx: int) -> None: ... + def build_element(self, m: re.Match[str], builder: str, tags: str, index: int) -> Element: ... -class UnderscoreProcessor(AsteriskProcessor): - PATTERNS: Any +class UnderscoreProcessor(AsteriskProcessor): ... class LinkInlineProcessor(InlineProcessor): - RE_LINK: Any - RE_TITLE_CLEAN: Any - def getLink(self, data, index): ... - def getText(self, data, index): ... + RE_LINK: ClassVar[re.Pattern[str]] + RE_TITLE_CLEAN: ClassVar[re.Pattern[str]] + def getLink(self, data: str, index: int) -> tuple[str, str | None, int, bool]: ... + def getText(self, data: str, index: int) -> tuple[str, int, bool]: ... class ImageInlineProcessor(LinkInlineProcessor): ... class ReferenceInlineProcessor(LinkInlineProcessor): - NEWLINE_CLEANUP_RE: typing.Pattern - def evalId(self, data, index, text): ... - def makeTag(self, href, title, text): ... + NEWLINE_CLEANUP_RE: ClassVar[re.Pattern[str]] + def evalId(self, data: str, index: int, text: str) -> tuple[str | None, int, bool]: ... + def makeTag(self, href: str, title: str, text: str) -> Element: ... class ShortReferenceInlineProcessor(ReferenceInlineProcessor): ... class ImageReferenceInlineProcessor(ReferenceInlineProcessor): ... +class ShortImageReferenceInlineProcessor(ImageReferenceInlineProcessor): ... class AutolinkInlineProcessor(InlineProcessor): ... class AutomailInlineProcessor(InlineProcessor): ... diff --git a/stubs/Markdown/markdown/pep562.pyi b/stubs/Markdown/markdown/pep562.pyi deleted file mode 100644 index 6246f865783b..000000000000 --- a/stubs/Markdown/markdown/pep562.pyi +++ /dev/null @@ -1,7 +0,0 @@ -class Version: - def __new__(cls, major, minor, micro, release: str = ..., pre: int = ..., post: int = ..., dev: int = ...): ... - -class Pep562: - def __init__(self, name) -> None: ... - def __dir__(self): ... - def __getattr__(self, name): ... diff --git a/stubs/Markdown/markdown/postprocessors.pyi b/stubs/Markdown/markdown/postprocessors.pyi index 47581da2f919..24cb7d4210e0 100644 --- a/stubs/Markdown/markdown/postprocessors.pyi +++ b/stubs/Markdown/markdown/postprocessors.pyi @@ -1,17 +1,27 @@ -from typing import Any, Pattern +import re +from typing import ClassVar +from typing_extensions import deprecated + +from markdown.core import Markdown from . import util -def build_postprocessors(md, **kwargs): ... +def build_postprocessors(md: Markdown, **kwargs) -> util.Registry[Postprocessor]: ... class Postprocessor(util.Processor): - def run(self, text) -> Any: ... + def run(self, text: str) -> str: ... class RawHtmlPostprocessor(Postprocessor): - def isblocklevel(self, html): ... + BLOCK_LEVEL_REGEX: ClassVar[re.Pattern[str]] + def isblocklevel(self, html: str) -> bool: ... + def stash_to_string(self, text: str) -> str: ... class AndSubstitutePostprocessor(Postprocessor): ... +@deprecated( + "This class is deprecated and will be removed in the future; " + "use [`UnescapeTreeprocessor`][markdown.treeprocessors.UnescapeTreeprocessor] instead." +) class UnescapePostprocessor(Postprocessor): - RE: Pattern[str] - def unescape(self, m): ... + RE: ClassVar[re.Pattern[str]] + def unescape(self, m: re.Match[str]) -> str: ... diff --git a/stubs/Markdown/markdown/preprocessors.pyi b/stubs/Markdown/markdown/preprocessors.pyi index e0ebac0bf684..dc55669881e5 100644 --- a/stubs/Markdown/markdown/preprocessors.pyi +++ b/stubs/Markdown/markdown/preprocessors.pyi @@ -1,23 +1,11 @@ -from typing import Any, Pattern +from markdown.core import Markdown from . import util -def build_preprocessors(md, **kwargs): ... +def build_preprocessors(md: Markdown, **kwargs) -> util.Registry[Preprocessor]: ... class Preprocessor(util.Processor): def run(self, lines: list[str]) -> list[str]: ... class NormalizeWhitespace(Preprocessor): ... - -class HtmlBlockPreprocessor(Preprocessor): - right_tag_patterns: Any - attrs_pattern: str = ... - left_tag_pattern: Any - attrs_re: Any - left_tag_re: Any - markdown_in_raw: bool = ... - -class ReferencePreprocessor(Preprocessor): - TITLE: str = ... - RE: Pattern[str] - TITLE_RE: Pattern[str] +class HtmlBlockPreprocessor(Preprocessor): ... diff --git a/stubs/Markdown/markdown/serializers.pyi b/stubs/Markdown/markdown/serializers.pyi index c775a409fc91..0fbcf66b57a8 100644 --- a/stubs/Markdown/markdown/serializers.pyi +++ b/stubs/Markdown/markdown/serializers.pyi @@ -1,2 +1,9 @@ -def to_html_string(element): ... -def to_xhtml_string(element): ... +import re +from xml.etree.ElementTree import Element + +__all__ = ["to_html_string", "to_xhtml_string"] + +RE_AMP: re.Pattern[str] + +def to_html_string(element: Element) -> str: ... +def to_xhtml_string(element: Element) -> str: ... diff --git a/stubs/Markdown/markdown/test_tools.pyi b/stubs/Markdown/markdown/test_tools.pyi new file mode 100644 index 000000000000..8c9f300d2f92 --- /dev/null +++ b/stubs/Markdown/markdown/test_tools.pyi @@ -0,0 +1,30 @@ +import unittest +from _typeshed import Unused +from typing import Any + +__all__ = ["TestCase", "LegacyTestCase", "Kwargs"] + +class TestCase(unittest.TestCase): + default_kwargs: dict[str, Any] # taken from source code + def assertMarkdownRenders( + self, + source: str, + expected: str, + expected_attrs: dict[str, Any] | None = None, # values passing to self.assertEqual() + **kwargs, + ) -> None: ... + def dedent(self, text: str) -> str: ... + +class recursionlimit: + limit: int + old_limit: int + def __init__(self, limit: int) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, type: Unused, value: Unused, tb: Unused) -> None: ... + +class Kwargs(dict[str, Any]): ... + +class LegacyTestMeta(type): + def __new__(cls, name: str, bases: tuple[type, ...], dct: dict[str, Any]): ... # dct is namespace argument for type.__new__() + +class LegacyTestCase(unittest.TestCase, metaclass=LegacyTestMeta): ... diff --git a/stubs/Markdown/markdown/treeprocessors.pyi b/stubs/Markdown/markdown/treeprocessors.pyi index 26cd06b43628..343896f9bb62 100644 --- a/stubs/Markdown/markdown/treeprocessors.pyi +++ b/stubs/Markdown/markdown/treeprocessors.pyi @@ -1,19 +1,26 @@ -from typing import Any +from re import Pattern +from typing import ClassVar, TypeGuard +from xml.etree.ElementTree import Element -from . import util +from markdown import util +from markdown.core import Markdown -def build_treeprocessors(md, **kwargs): ... -def isString(s): ... +def build_treeprocessors(md: Markdown, **kwargs) -> util.Registry[Treeprocessor]: ... +def isString(s: object) -> TypeGuard[str]: ... class Treeprocessor(util.Processor): - def run(self, root) -> Any | None: ... + def run(self, root: Element) -> Element | None: ... class InlineProcessor(Treeprocessor): - inlinePatterns: Any - ancestors: Any - def __init__(self, md) -> None: ... - stashed_nodes: Any - parent_map: Any - def run(self, tree, ancestors: Any | None = ...): ... + inlinePatterns: util.Registry[InlineProcessor] + ancestors: list[str] + def __init__(self, md: Markdown) -> None: ... + stashed_nodes: dict[str, Element | str] + parent_map: dict[Element[str], Element[str]] + def run(self, tree: Element, ancestors: list[str] | None = None) -> Element: ... class PrettifyTreeprocessor(Treeprocessor): ... + +class UnescapeTreeprocessor(Treeprocessor): + RE: ClassVar[Pattern[str]] + def unescape(self, text: str) -> str: ... diff --git a/stubs/Markdown/markdown/util.pyi b/stubs/Markdown/markdown/util.pyi index c252334d3984..567d279a9fb5 100644 --- a/stubs/Markdown/markdown/util.pyi +++ b/stubs/Markdown/markdown/util.pyi @@ -1,55 +1,71 @@ -from typing import Any, Pattern - -PY37: Any -__deprecated__: Any -BLOCK_LEVEL_ELEMENTS: Any -STX: str -ETX: str -INLINE_PLACEHOLDER_PREFIX: Any -INLINE_PLACEHOLDER: Any -INLINE_PLACEHOLDER_RE: Pattern[str] -AMP_SUBSTITUTE: Any -HTML_PLACEHOLDER: Any -HTML_PLACEHOLDER_RE: Pattern[str] -TAG_PLACEHOLDER: Any -INSTALLED_EXTENSIONS: Any -RTL_BIDI_RANGES: Any - -def deprecated(message, stacklevel: int = ...): ... -def isBlockLevel(tag): ... -def parseBoolValue(value, fail_on_errors: bool = ..., preserve_none: bool = ...): ... -def code_escape(text): ... +from collections.abc import Iterator +from importlib import metadata +from re import Pattern +from typing import Final, Generic, TypedDict, TypeVar, overload, type_check_only +from xml.etree.ElementTree import Element + +from markdown.core import Markdown + +_T = TypeVar("_T") + +BLOCK_LEVEL_ELEMENTS: Final[list[str]] +STX: Final[str] +ETX: Final[str] +INLINE_PLACEHOLDER_PREFIX: Final[str] +INLINE_PLACEHOLDER: Final[str] +INLINE_PLACEHOLDER_RE: Final[Pattern[str]] +AMP_SUBSTITUTE: Final[str] +HTML_PLACEHOLDER: Final[str] +HTML_PLACEHOLDER_RE: Final[Pattern[str]] +TAG_PLACEHOLDER: Final[str] +RTL_BIDI_RANGES: Final[tuple[tuple[str, str], tuple[str, str]]] + +def get_installed_extensions() -> metadata.EntryPoints: ... +def deprecated(message: str, stacklevel: int = 2): ... + +@overload +def parseBoolValue(value: str) -> bool: ... +@overload +def parseBoolValue(value: str | None, fail_on_errors: bool = True, preserve_none: bool = False) -> bool | None: ... + +def code_escape(text: str) -> str: ... +def nearing_recursion_limit() -> bool: ... class AtomicString(str): ... class Processor: - md: Any - def __init__(self, md: Any | None = ...) -> None: ... - @property - def markdown(self): ... + md: Markdown + def __init__(self, md: Markdown | None = None) -> None: ... + +@type_check_only +class _TagData(TypedDict): + tag: str + attrs: dict[str, str] + left_index: int + right_index: int class HtmlStash: - html_counter: int = ... - rawHtmlBlocks: Any - tag_counter: int = ... - tag_data: Any + html_counter: int + rawHtmlBlocks: list[str | Element] + tag_counter: int + tag_data: list[_TagData] def __init__(self) -> None: ... - def store(self, html): ... + def store(self, html: str | Element) -> str: ... def reset(self) -> None: ... - def get_placeholder(self, key): ... - def store_tag(self, tag, attrs, left_index, right_index): ... + def get_placeholder(self, key: int) -> str: ... + def store_tag(self, tag: str, attrs: dict[str, str], left_index: int, right_index: int) -> str: ... -class Registry: +class Registry(Generic[_T]): def __init__(self) -> None: ... - def __contains__(self, item): ... - def __iter__(self) -> Any: ... - def __getitem__(self, key): ... - def __len__(self): ... - def get_index_for_name(self, name): ... - def register(self, item, name, priority) -> None: ... - def deregister(self, name, strict: bool = ...) -> None: ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - def add(self, key, value, location) -> None: ... - -def __getattr__(name): ... + def __contains__(self, item: str | _T) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + + @overload + def __getitem__(self, key: slice) -> Registry[_T]: ... + @overload + def __getitem__(self, key: str | int) -> _T: ... + + def __len__(self) -> int: ... + def get_index_for_name(self, name: str) -> int: ... + def register(self, item: _T, name: str, priority: float) -> None: ... + def deregister(self, name: str, strict: bool = True) -> None: ... diff --git a/stubs/Pillow/@tests/stubtest_allowlist.txt b/stubs/Pillow/@tests/stubtest_allowlist.txt deleted file mode 100644 index b0cdde03aa75..000000000000 --- a/stubs/Pillow/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,4 +0,0 @@ -PIL.FpxImagePlugin -PIL.ImageQt.ImageQt -PIL.MicImagePlugin -PIL.WmfImagePlugin.WmfHandler diff --git a/stubs/Pillow/METADATA.toml b/stubs/Pillow/METADATA.toml deleted file mode 100644 index da80f0078d57..000000000000 --- a/stubs/Pillow/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "8.3.*" diff --git a/stubs/Pillow/PIL/BdfFontFile.pyi b/stubs/Pillow/PIL/BdfFontFile.pyi deleted file mode 100644 index 8f6ba64bed40..000000000000 --- a/stubs/Pillow/PIL/BdfFontFile.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from .FontFile import FontFile - -bdf_slant: Any -bdf_spacing: Any - -def bdf_char(f): ... - -class BdfFontFile(FontFile): - def __init__(self, fp) -> None: ... diff --git a/stubs/Pillow/PIL/BlpImagePlugin.pyi b/stubs/Pillow/PIL/BlpImagePlugin.pyi deleted file mode 100644 index 3e004d9df65c..000000000000 --- a/stubs/Pillow/PIL/BlpImagePlugin.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile, PyDecoder - -BLP_FORMAT_JPEG: int -BLP_ENCODING_UNCOMPRESSED: int -BLP_ENCODING_DXT: int -BLP_ENCODING_UNCOMPRESSED_RAW_BGRA: int -BLP_ALPHA_ENCODING_DXT1: int -BLP_ALPHA_ENCODING_DXT3: int -BLP_ALPHA_ENCODING_DXT5: int - -def unpack_565(i): ... -def decode_dxt1(data, alpha: bool = ...): ... -def decode_dxt3(data): ... -def decode_dxt5(data): ... - -class BLPFormatError(NotImplementedError): ... - -class BlpImageFile(ImageFile): - format: str - format_description: str - -class _BLPBaseDecoder(PyDecoder): - magic: Any - def decode(self, buffer): ... - -class BLP1Decoder(_BLPBaseDecoder): ... -class BLP2Decoder(_BLPBaseDecoder): ... diff --git a/stubs/Pillow/PIL/BmpImagePlugin.pyi b/stubs/Pillow/PIL/BmpImagePlugin.pyi deleted file mode 100644 index c1712429e979..000000000000 --- a/stubs/Pillow/PIL/BmpImagePlugin.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -BIT2MODE: Any - -class BmpImageFile(ImageFile): - format_description: str - format: str - COMPRESSIONS: Any - -class DibImageFile(BmpImageFile): - format: str - format_description: str - -SAVE: Any diff --git a/stubs/Pillow/PIL/BufrStubImagePlugin.pyi b/stubs/Pillow/PIL/BufrStubImagePlugin.pyi deleted file mode 100644 index 1fd49e1ba88e..000000000000 --- a/stubs/Pillow/PIL/BufrStubImagePlugin.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import StubImageFile - -def register_handler(handler) -> None: ... - -class BufrStubImageFile(StubImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/ContainerIO.pyi b/stubs/Pillow/PIL/ContainerIO.pyi deleted file mode 100644 index 6ca38fbe1324..000000000000 --- a/stubs/Pillow/PIL/ContainerIO.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Any - -class ContainerIO: - fh: Any - pos: int - offset: Any - length: Any - def __init__(self, file, offset, length) -> None: ... - def isatty(self): ... - def seek(self, offset, mode=...) -> None: ... - def tell(self): ... - def read(self, n: int = ...): ... - def readline(self): ... - def readlines(self): ... diff --git a/stubs/Pillow/PIL/CurImagePlugin.pyi b/stubs/Pillow/PIL/CurImagePlugin.pyi deleted file mode 100644 index a6085cb8b93f..000000000000 --- a/stubs/Pillow/PIL/CurImagePlugin.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from .BmpImagePlugin import BmpImageFile - -class CurImageFile(BmpImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/DcxImagePlugin.pyi b/stubs/Pillow/PIL/DcxImagePlugin.pyi deleted file mode 100644 index 4b0389aae635..000000000000 --- a/stubs/Pillow/PIL/DcxImagePlugin.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from .PcxImagePlugin import PcxImageFile - -MAGIC: int - -class DcxImageFile(PcxImageFile): - format: str - format_description: str - frame: Any - fp: Any - def seek(self, frame) -> None: ... - def tell(self): ... diff --git a/stubs/Pillow/PIL/DdsImagePlugin.pyi b/stubs/Pillow/PIL/DdsImagePlugin.pyi deleted file mode 100644 index 10974403b363..000000000000 --- a/stubs/Pillow/PIL/DdsImagePlugin.pyi +++ /dev/null @@ -1,70 +0,0 @@ -from typing_extensions import Literal - -from .ImageFile import ImageFile - -DDS_MAGIC: int -DDSD_CAPS: int -DDSD_HEIGHT: int -DDSD_WIDTH: int -DDSD_PITCH: int -DDSD_PIXELFORMAT: int -DDSD_MIPMAPCOUNT: int -DDSD_LINEARSIZE: int -DDSD_DEPTH: int -DDSCAPS_COMPLEX: int -DDSCAPS_TEXTURE: int -DDSCAPS_MIPMAP: int -DDSCAPS2_CUBEMAP: int -DDSCAPS2_CUBEMAP_POSITIVEX: int -DDSCAPS2_CUBEMAP_NEGATIVEX: int -DDSCAPS2_CUBEMAP_POSITIVEY: int -DDSCAPS2_CUBEMAP_NEGATIVEY: int -DDSCAPS2_CUBEMAP_POSITIVEZ: int -DDSCAPS2_CUBEMAP_NEGATIVEZ: int -DDSCAPS2_VOLUME: int - -DDPF_ALPHAPIXELS: Literal[0x1] -DDPF_ALPHA: Literal[0x2] -DDPF_FOURCC: Literal[0x4] -DDPF_PALETTEINDEXED8: Literal[0x20] -DDPF_RGB: Literal[0x40] -DDPF_LUMINANCE: Literal[0x20000] - -DDS_FOURCC: Literal[0x4] -DDS_RGB: Literal[0x40] -DDS_RGBA: Literal[0x41] -DDS_LUMINANCE: Literal[0x20000] -DDS_LUMINANCEA: Literal[0x20001] -DDS_ALPHA: Literal[0x2] -DDS_PAL8: Literal[0x20] - -DDS_HEADER_FLAGS_TEXTURE: int -DDS_HEADER_FLAGS_MIPMAP: int -DDS_HEADER_FLAGS_VOLUME: int -DDS_HEADER_FLAGS_PITCH: int -DDS_HEADER_FLAGS_LINEARSIZE: int -DDS_HEIGHT: int -DDS_WIDTH: int -DDS_SURFACE_FLAGS_TEXTURE: int -DDS_SURFACE_FLAGS_MIPMAP: int -DDS_SURFACE_FLAGS_CUBEMAP: int -DDS_CUBEMAP_POSITIVEX: int -DDS_CUBEMAP_NEGATIVEX: int -DDS_CUBEMAP_POSITIVEY: int -DDS_CUBEMAP_NEGATIVEY: int -DDS_CUBEMAP_POSITIVEZ: int -DDS_CUBEMAP_NEGATIVEZ: int -DXT1_FOURCC: int -DXT3_FOURCC: int -DXT5_FOURCC: int -DXGI_FORMAT_R8G8B8A8_TYPELESS: int -DXGI_FORMAT_R8G8B8A8_UNORM: int -DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: int -DXGI_FORMAT_BC7_TYPELESS: int -DXGI_FORMAT_BC7_UNORM: int -DXGI_FORMAT_BC7_UNORM_SRGB: int - -class DdsImageFile(ImageFile): - format: str - format_description: str - def load_seek(self, pos) -> None: ... diff --git a/stubs/Pillow/PIL/EpsImagePlugin.pyi b/stubs/Pillow/PIL/EpsImagePlugin.pyi deleted file mode 100644 index 741f03ec810f..000000000000 --- a/stubs/Pillow/PIL/EpsImagePlugin.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -split: Any -field: Any -gs_windows_binary: Any - -def has_ghostscript(): ... -def Ghostscript(tile, size, fp, scale: int = ...): ... - -class PSFile: - fp: Any - char: Any - def __init__(self, fp) -> None: ... - def seek(self, offset, whence=...) -> None: ... - def readline(self): ... - -class EpsImageFile(ImageFile): - format: str - format_description: str - mode_map: Any - im: Any - mode: Any - tile: Any - def load(self, scale: int = ...) -> None: ... - def load_seek(self, *args, **kwargs) -> None: ... diff --git a/stubs/Pillow/PIL/ExifTags.pyi b/stubs/Pillow/PIL/ExifTags.pyi deleted file mode 100644 index 0ad93f535979..000000000000 --- a/stubs/Pillow/PIL/ExifTags.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Mapping - -TAGS: Mapping[int, str] -GPSTAGS: Mapping[int, str] diff --git a/stubs/Pillow/PIL/FitsStubImagePlugin.pyi b/stubs/Pillow/PIL/FitsStubImagePlugin.pyi deleted file mode 100644 index ec94b35e37b0..000000000000 --- a/stubs/Pillow/PIL/FitsStubImagePlugin.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import StubImageFile - -def register_handler(handler) -> None: ... - -class FITSStubImageFile(StubImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/FliImagePlugin.pyi b/stubs/Pillow/PIL/FliImagePlugin.pyi deleted file mode 100644 index 11f57d49d854..000000000000 --- a/stubs/Pillow/PIL/FliImagePlugin.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import ImageFile - -class FliImageFile(ImageFile): - format: str - format_description: str - def seek(self, frame) -> None: ... - def tell(self): ... diff --git a/stubs/Pillow/PIL/FontFile.pyi b/stubs/Pillow/PIL/FontFile.pyi deleted file mode 100644 index fa8e103b70b5..000000000000 --- a/stubs/Pillow/PIL/FontFile.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -WIDTH: int - -def puti16(fp, values) -> None: ... - -class FontFile: - bitmap: Any - info: Any - glyph: Any - def __init__(self) -> None: ... - def __getitem__(self, ix): ... - ysize: Any - metrics: Any - def compile(self): ... - def save(self, filename) -> None: ... diff --git a/stubs/Pillow/PIL/FpxImagePlugin.pyi b/stubs/Pillow/PIL/FpxImagePlugin.pyi deleted file mode 100644 index 0f88b6639730..000000000000 --- a/stubs/Pillow/PIL/FpxImagePlugin.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -MODES: Any - -class FpxImageFile(ImageFile): - format: str - format_description: str - fp: Any - def load(self): ... diff --git a/stubs/Pillow/PIL/FtexImagePlugin.pyi b/stubs/Pillow/PIL/FtexImagePlugin.pyi deleted file mode 100644 index b123ffe2c3f0..000000000000 --- a/stubs/Pillow/PIL/FtexImagePlugin.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from .ImageFile import ImageFile - -MAGIC: bytes -FORMAT_DXT1: int -FORMAT_UNCOMPRESSED: int - -class FtexImageFile(ImageFile): - format: str - format_description: str - def load_seek(self, pos) -> None: ... diff --git a/stubs/Pillow/PIL/GbrImagePlugin.pyi b/stubs/Pillow/PIL/GbrImagePlugin.pyi deleted file mode 100644 index 070d87d68a05..000000000000 --- a/stubs/Pillow/PIL/GbrImagePlugin.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -class GbrImageFile(ImageFile): - format: str - format_description: str - im: Any - def load(self) -> None: ... diff --git a/stubs/Pillow/PIL/GdImageFile.pyi b/stubs/Pillow/PIL/GdImageFile.pyi deleted file mode 100644 index 185d27b5de70..000000000000 --- a/stubs/Pillow/PIL/GdImageFile.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import ImageFile - -class GdImageFile(ImageFile): - format: str - format_description: str - -def open(fp, mode: str = ...): ... diff --git a/stubs/Pillow/PIL/GifImagePlugin.pyi b/stubs/Pillow/PIL/GifImagePlugin.pyi deleted file mode 100644 index 47827071ff50..000000000000 --- a/stubs/Pillow/PIL/GifImagePlugin.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -class GifImageFile(ImageFile): - format: str - format_description: str - global_palette: Any - def data(self): ... - @property - def n_frames(self): ... - @property - def is_animated(self): ... - im: Any - def seek(self, frame) -> None: ... - def tell(self): ... - -RAWMODE: Any - -def get_interlace(im): ... -def getheader(im, palette: Any | None = ..., info: Any | None = ...): ... -def getdata(im, offset=..., **params): ... diff --git a/stubs/Pillow/PIL/GimpGradientFile.pyi b/stubs/Pillow/PIL/GimpGradientFile.pyi deleted file mode 100644 index f4f61bd7aed8..000000000000 --- a/stubs/Pillow/PIL/GimpGradientFile.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -EPSILON: float - -def linear(middle, pos): ... -def curved(middle, pos): ... -def sine(middle, pos): ... -def sphere_increasing(middle, pos): ... -def sphere_decreasing(middle, pos): ... - -SEGMENTS: Any - -class GradientFile: - gradient: Any - def getpalette(self, entries: int = ...): ... - -class GimpGradientFile(GradientFile): - gradient: Any - def __init__(self, fp) -> None: ... diff --git a/stubs/Pillow/PIL/GimpPaletteFile.pyi b/stubs/Pillow/PIL/GimpPaletteFile.pyi deleted file mode 100644 index 441f85b72a4c..000000000000 --- a/stubs/Pillow/PIL/GimpPaletteFile.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -class GimpPaletteFile: - rawmode: str - palette: Any - def __init__(self, fp) -> None: ... - def getpalette(self): ... diff --git a/stubs/Pillow/PIL/GribStubImagePlugin.pyi b/stubs/Pillow/PIL/GribStubImagePlugin.pyi deleted file mode 100644 index 34c773a25d1d..000000000000 --- a/stubs/Pillow/PIL/GribStubImagePlugin.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import StubImageFile - -def register_handler(handler) -> None: ... - -class GribStubImageFile(StubImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/Hdf5StubImagePlugin.pyi b/stubs/Pillow/PIL/Hdf5StubImagePlugin.pyi deleted file mode 100644 index b036a17abca2..000000000000 --- a/stubs/Pillow/PIL/Hdf5StubImagePlugin.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import StubImageFile - -def register_handler(handler) -> None: ... - -class HDF5StubImageFile(StubImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/IcnsImagePlugin.pyi b/stubs/Pillow/PIL/IcnsImagePlugin.pyi deleted file mode 100644 index 8606fcf13cf3..000000000000 --- a/stubs/Pillow/PIL/IcnsImagePlugin.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -enable_jpeg2k: Any -HEADERSIZE: int - -def nextheader(fobj): ... -def read_32t(fobj, start_length, size): ... -def read_32(fobj, start_length, size): ... -def read_mk(fobj, start_length, size): ... -def read_png_or_jpeg2000(fobj, start_length, size): ... - -class IcnsFile: - SIZES: Any - dct: Any - fobj: Any - def __init__(self, fobj) -> None: ... - def itersizes(self): ... - def bestsize(self): ... - def dataforsize(self, size): ... - def getimage(self, size: Any | None = ...): ... - -class IcnsImageFile(ImageFile): - format: str - format_description: str - @property - def size(self): ... - @size.setter - def size(self, value) -> None: ... - best_size: Any - im: Any - mode: Any - def load(self) -> None: ... diff --git a/stubs/Pillow/PIL/IcoImagePlugin.pyi b/stubs/Pillow/PIL/IcoImagePlugin.pyi deleted file mode 100644 index 536de0adee68..000000000000 --- a/stubs/Pillow/PIL/IcoImagePlugin.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -class IcoFile: - buf: Any - entry: Any - nb_items: Any - def __init__(self, buf): ... - def sizes(self): ... - def getentryindex(self, size, bpp: bool = ...): ... - def getimage(self, size, bpp: bool = ...): ... - def frame(self, idx): ... - -class IcoImageFile(ImageFile): - format: str - format_description: str - @property - def size(self): ... - @size.setter - def size(self, value) -> None: ... - im: Any - mode: Any - def load(self) -> None: ... - def load_seek(self) -> None: ... diff --git a/stubs/Pillow/PIL/ImImagePlugin.pyi b/stubs/Pillow/PIL/ImImagePlugin.pyi deleted file mode 100644 index b6c3d84b6c5c..000000000000 --- a/stubs/Pillow/PIL/ImImagePlugin.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -COMMENT: str -DATE: str -EQUIPMENT: str -FRAMES: str -LUT: str -NAME: str -SCALE: str -SIZE: str -MODE: str -TAGS: Any -OPEN: Any -split: Any - -def number(s): ... - -class ImImageFile(ImageFile): - format: str - format_description: str - @property - def n_frames(self): ... - @property - def is_animated(self): ... - frame: Any - fp: Any - tile: Any - def seek(self, frame) -> None: ... - def tell(self): ... - -SAVE: Any diff --git a/stubs/Pillow/PIL/Image.pyi b/stubs/Pillow/PIL/Image.pyi deleted file mode 100644 index 4d7113496b60..000000000000 --- a/stubs/Pillow/PIL/Image.pyi +++ /dev/null @@ -1,258 +0,0 @@ -from _typeshed import SupportsRead, SupportsWrite -from collections.abc import Iterable, Iterator, MutableMapping -from pathlib import Path -from typing import Any, Callable, Dict, Protocol, Sequence, SupportsBytes, Tuple, Union -from typing_extensions import Literal - -from ._imaging import ( - DEFAULT_STRATEGY as DEFAULT_STRATEGY, - FILTERED as FILTERED, - FIXED as FIXED, - HUFFMAN_ONLY as HUFFMAN_ONLY, - RLE as RLE, -) -from .ImageFilter import Filter -from .ImagePalette import ImagePalette - -_Mode = Literal["1", "CMYK", "F", "HSV", "I", "L", "LAB", "P", "RGB", "RGBA", "RGBX", "YCbCr"] -_Resample = Literal[0, 1, 2, 3, 4, 5] -_Size = Tuple[int, int] -_Box = Tuple[int, int, int, int] - -_ConversionMatrix = Union[ - Tuple[float, float, float, float], Tuple[float, float, float, float, float, float, float, float, float, float, float, float], -] -_Color = Union[float, Tuple[float, ...]] - -class _Writeable(SupportsWrite[bytes], Protocol): - def seek(self, __offset: int) -> Any: ... - -# obsolete -NORMAL: Literal[0] -SEQUENCE: Literal[1] -CONTAINER: Literal[2] - -class DecompressionBombWarning(RuntimeWarning): ... -class DecompressionBombError(Exception): ... - -MAX_IMAGE_PIXELS: int - -NONE: Literal[0] - -FLIP_LEFT_RIGHT: Literal[0] -FLIP_TOP_BOTTOM: Literal[1] -ROTATE_90: Literal[2] -ROTATE_180: Literal[3] -ROTATE_270: Literal[4] -TRANSPOSE: Literal[5] -TRANSVERSE: Literal[6] - -AFFINE: Literal[0] -EXTENT: Literal[1] -PERSPECTIVE: Literal[2] -QUAD: Literal[3] -MESH: Literal[4] - -NEAREST: Literal[0] -BOX: Literal[4] -BILINEAR: Literal[2] -LINEAR: Literal[2] -HAMMING: Literal[5] -BICUBIC: Literal[3] -CUBIC: Literal[3] -LANCZOS: Literal[1] -ANTIALIAS: Literal[1] - -ORDERED: Literal[1] -RASTERIZE: Literal[2] -FLOYDSTEINBERG: Literal[3] - -WEB: Literal[0] -ADAPTIVE: Literal[1] - -MEDIANCUT: Literal[0] -MAXCOVERAGE: Literal[1] -FASTOCTREE: Literal[2] -LIBIMAGEQUANT: Literal[3] - -ID: list[str] -OPEN: dict[str, Any] -MIME: dict[str, str] -SAVE: dict[str, Any] -SAVE_ALL: dict[str, Any] -EXTENSION: dict[str, str] -DECODERS: dict[str, Any] -ENCODERS: dict[str, Any] - -MODES: list[_Mode] - -def getmodebase(mode: _Mode) -> Literal["L", "RGB"]: ... -def getmodetype(mode: _Mode) -> Literal["L", "I", "F"]: ... -def getmodebandnames(mode: _Mode) -> Tuple[str, ...]: ... -def getmodebands(mode: _Mode) -> int: ... -def preinit() -> None: ... -def init() -> None: ... -def coerce_e(value) -> _E: ... - -class _E: - def __init__(self, data) -> None: ... - def __add__(self, other) -> _E: ... - def __mul__(self, other) -> _E: ... - -_ImageState = Tuple[Dict[str, Any], str, Tuple[int, int], Any, bytes] - -class Image: - format: Any - format_description: Any - im: Any - mode: str - palette: Any - info: dict[Any, Any] - readonly: int - pyaccess: Any - @property - def width(self) -> int: ... - @property - def height(self) -> int: ... - @property - def size(self) -> tuple[int, int]: ... - def __enter__(self) -> Image: ... - def __exit__(self, *args: Any) -> None: ... - def close(self) -> None: ... - def __eq__(self, other: object) -> bool: ... - def __array__(self, dtype=...) -> Any: ... # returns numpy.array() - def __getstate__(self) -> _ImageState: ... - def __setstate__(self, state: _ImageState) -> None: ... - def tobytes(self, encoder_name: str = ..., *args) -> bytes: ... - def tobitmap(self, name: str = ...) -> bytes: ... - def frombytes(self, data: bytes, decoder_name: str = ..., *args) -> None: ... - def load(self) -> None: ... - def verify(self) -> None: ... - def convert( - self, - mode: str | None = ..., - matrix: _ConversionMatrix | None = ..., - dither: int | None = ..., - palette: Literal[0, 1] = ..., - colors: int = ..., - ) -> Image: ... - def quantize( - self, - colors: int = ..., - method: Literal[0, 1, 2, 3] | None = ..., - kmeans: int = ..., - palette: Image | None = ..., - dither: int = ..., - ) -> Image: ... - def copy(self) -> Image: ... - __copy__ = copy - def crop(self, box: _Box | None = ...) -> Image: ... - def draft(self, mode: str, size: _Size) -> None: ... - def filter(self, filter: Filter | Callable[[], Filter]) -> Image: ... - def getbands(self) -> Tuple[str, ...]: ... - def getbbox(self) -> tuple[int, int, int, int] | None: ... - def getcolors(self, maxcolors: int = ...) -> list[tuple[int, int]]: ... - def getdata(self, band: int | None = ...): ... - def getextrema(self): ... - def getexif(self) -> Exif: ... - def getim(self): ... - def getpalette(self) -> list[int] | None: ... - def getpixel(self, xy: tuple[int, int]): ... - def getprojection(self) -> tuple[list[int], list[int]]: ... - def histogram(self, mask: Image | None = ..., extrema: tuple[int, int] | tuple[float, float] | None = ...) -> list[int]: ... - def entropy(self, mask: Image | None = ..., extrema: tuple[int, int] | tuple[float, float] | None = ...) -> float: ... - def paste(self, im: Image, box: tuple[float, float] | _Box | None = ..., mask: Image | None = ...) -> None: ... - def alpha_composite(self, im: Image, dest: tuple[int, int] = ..., source: tuple[int, int] = ...) -> None: ... - def point(self, lut, mode: str | None = ...) -> Image: ... - def putalpha(self, alpha: Image | int) -> None: ... - def putdata(self, data: Sequence[int], scale: float = ..., offset: float = ...) -> None: ... - def putpalette(self, data: ImagePalette | bytes | Iterable[int] | SupportsBytes, rawmode: str | None = ...) -> None: ... - def putpixel(self, xy: tuple[int, int], value: _Color | list[float]) -> None: ... - def remap_palette(self, dest_map: Iterable[int], source_palette: Sequence[int] | None = ...) -> Image: ... - def resize( - self, - size: tuple[int, int], - resample: _Resample | None = ..., - box: tuple[float, float, float, float] | None = ..., - reducing_gap: float | None = ..., - ) -> Image: ... - def reduce(self, factor: int | tuple[int, int] | list[int], box: _Box | None = ...) -> Image: ... - def rotate( - self, - angle: float, - resample: _Resample = ..., - expand: bool = ..., - center: tuple[float, float] | None = ..., - translate: tuple[float, float] | None = ..., - fillcolor: _Color | None = ..., - ) -> Image: ... - def save( - self, - fp: str | bytes | Path | _Writeable, - format: str | None = ..., - *, - save_all: bool = ..., - bitmap_format: Literal["bmp", "png"] = ..., # for ICO files - **params: Any, - ) -> None: ... - def seek(self, frame: int) -> None: ... - def show(self, title: str | None = ..., command: str | None = ...) -> None: ... - def split(self) -> Tuple[Image, ...]: ... - def getchannel(self, channel: int | str) -> Image: ... - def tell(self) -> int: ... - def thumbnail(self, size: tuple[int, int], resample: _Resample = ..., reducing_gap: float = ...) -> None: ... - def transform( - self, - size: _Size, - method: Literal[0, 1, 2, 3, 4], - data=..., - resample: _Resample = ..., - fill: int = ..., - fillcolor: _Color | int | None = ..., - ) -> None: ... - def transpose(self, method: Literal[0, 1, 2, 3, 4, 5, 6]) -> Image: ... - def effect_spread(self, distance: int) -> Image: ... - def toqimage(self): ... - def toqpixmap(self): ... - -class ImagePointHandler: ... -class ImageTransformHandler: ... - -def new(mode: _Mode, size: tuple[int, int], color: float | Tuple[float, ...] | str = ...) -> Image: ... -def frombytes(mode: _Mode, size: tuple[int, int], data, decoder_name: str = ..., *args) -> Image: ... -def frombuffer(mode: _Mode, size: tuple[int, int], data, decoder_name: str = ..., *args) -> Image: ... -def fromarray(obj, mode: _Mode | None = ...) -> Image: ... -def fromqimage(im) -> Image: ... -def fromqpixmap(im) -> Image: ... -def open( - fp: str | bytes | Path | SupportsRead[bytes], mode: Literal["r"] = ..., formats: list[str] | tuple[str] | None = ... -) -> Image: ... -def alpha_composite(im1: Image, im2: Image) -> Image: ... -def blend(im1: Image, im2: Image, alpha: float) -> Image: ... -def composite(image1: Image, image2: Image, mask: Image) -> Image: ... -def eval(image: Image, *args) -> Image: ... -def merge(mode: str, bands: Sequence[Image]) -> Image: ... -def register_open(id: str, factory, accept=...) -> None: ... -def register_mime(id: str, mimetype: str) -> None: ... -def register_save(id: str, driver) -> None: ... -def register_save_all(id: str, driver) -> None: ... -def register_extension(id: str, extension: str) -> None: ... -def register_extensions(id: str, extensions: Iterable[str]) -> None: ... -def registered_extensions() -> dict[str, str]: ... -def register_decoder(name: str, decoder) -> None: ... -def register_encoder(name: str, encoder) -> None: ... -def effect_mandelbrot(size: tuple[int, int], extent: tuple[float, float, float, float], quality: int) -> Image: ... -def effect_noise(size: tuple[int, int], sigma: float) -> Image: ... -def linear_gradient(mode: str) -> Image: ... -def radial_gradient(mode: str) -> Image: ... - -class Exif(MutableMapping[int, Any]): - def load(self, data: bytes) -> None: ... - def tobytes(self, offset: int = ...) -> bytes: ... - def get_ifd(self, tag: int): ... - def __len__(self) -> int: ... - def __getitem__(self, tag: int) -> Any: ... - def __contains__(self, tag: object) -> bool: ... - def __setitem__(self, tag: int, value: Any) -> None: ... - def __delitem__(self, tag: int) -> None: ... - def __iter__(self) -> Iterator[int]: ... diff --git a/stubs/Pillow/PIL/ImageChops.pyi b/stubs/Pillow/PIL/ImageChops.pyi deleted file mode 100644 index 0e9f53046de2..000000000000 --- a/stubs/Pillow/PIL/ImageChops.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from .Image import Image - -def constant(image: Image, value: int) -> Image: ... -def duplicate(image: Image) -> Image: ... -def invert(image: Image) -> Image: ... -def lighter(image1: Image, image2: Image) -> Image: ... -def darker(image1: Image, image2: Image) -> Image: ... -def difference(image1: Image, image2: Image) -> Image: ... -def multiply(image1: Image, image2: Image) -> Image: ... -def screen(image1: Image, image2: Image) -> Image: ... -def soft_light(image1: Image, image2: Image) -> Image: ... -def hard_light(image1: Image, image2: Image) -> Image: ... -def overlay(image1: Image, image2: Image) -> Image: ... -def add(image1: Image, image2: Image, scale: float = ..., offset: int = ...) -> Image: ... -def subtract(image1: Image, image2: Image, scale: float = ..., offset: int = ...) -> Image: ... -def add_modulo(image1: Image, image2: Image) -> Image: ... -def subtract_modulo(image1: Image, image2: Image) -> Image: ... -def logical_and(image1: Image, image2: Image) -> Image: ... -def logical_or(image1: Image, image2: Image) -> Image: ... -def logical_xor(image1: Image, image2: Image) -> Image: ... -def blend(image1: Image, image2: Image, alpha: float) -> Image: ... -def composite(image1: Image, image2: Image, mask: Image) -> Image: ... -def offset(image: Image, xoffset: int, yoffset: int | None = ...) -> Image: ... diff --git a/stubs/Pillow/PIL/ImageCms.pyi b/stubs/Pillow/PIL/ImageCms.pyi deleted file mode 100644 index c0d004e96622..000000000000 --- a/stubs/Pillow/PIL/ImageCms.pyi +++ /dev/null @@ -1,59 +0,0 @@ -from typing import Any - -from .Image import ImagePointHandler - -DESCRIPTION: str -VERSION: str -core: Any -INTENT_PERCEPTUAL: int -INTENT_RELATIVE_COLORIMETRIC: int -INTENT_SATURATION: int -INTENT_ABSOLUTE_COLORIMETRIC: int -DIRECTION_INPUT: int -DIRECTION_OUTPUT: int -DIRECTION_PROOF: int -FLAGS: Any - -class ImageCmsProfile: - def __init__(self, profile) -> None: ... - def tobytes(self): ... - -class ImageCmsTransform(ImagePointHandler): - transform: Any - input_mode: Any - output_mode: Any - output_profile: Any - def __init__( - self, input, output, input_mode, output_mode, intent=..., proof: Any | None = ..., proof_intent=..., flags: int = ... - ) -> None: ... - def point(self, im): ... - def apply(self, im, imOut: Any | None = ...): ... - def apply_in_place(self, im): ... - -def get_display_profile(handle: Any | None = ...): ... - -class PyCMSError(Exception): ... - -def profileToProfile( - im, inputProfile, outputProfile, renderingIntent=..., outputMode: Any | None = ..., inPlace: bool = ..., flags: int = ... -): ... -def getOpenProfile(profileFilename): ... -def buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent=..., flags: int = ...): ... -def buildProofTransform( - inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=..., proofRenderingIntent=..., flags=... -): ... - -buildTransformFromOpenProfiles = buildTransform -buildProofTransformFromOpenProfiles = buildProofTransform - -def applyTransform(im, transform, inPlace: bool = ...): ... -def createProfile(colorSpace, colorTemp: int = ...): ... -def getProfileName(profile): ... -def getProfileInfo(profile): ... -def getProfileCopyright(profile): ... -def getProfileManufacturer(profile): ... -def getProfileModel(profile): ... -def getProfileDescription(profile): ... -def getDefaultIntent(profile): ... -def isIntentSupported(profile, intent, direction): ... -def versions(): ... diff --git a/stubs/Pillow/PIL/ImageColor.pyi b/stubs/Pillow/PIL/ImageColor.pyi deleted file mode 100644 index 8e0db5292296..000000000000 --- a/stubs/Pillow/PIL/ImageColor.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Tuple, Union - -_RGB = Union[Tuple[int, int, int], Tuple[int, int, int, int]] -_Ink = Union[str, int, _RGB] -_GreyScale = Tuple[int, int] - -def getrgb(color: _Ink) -> _RGB: ... -def getcolor(color: _Ink, mode: str) -> _RGB | _GreyScale: ... - -colormap: dict[str, str] diff --git a/stubs/Pillow/PIL/ImageDraw.pyi b/stubs/Pillow/PIL/ImageDraw.pyi deleted file mode 100644 index 5ca32e3b3c8f..000000000000 --- a/stubs/Pillow/PIL/ImageDraw.pyi +++ /dev/null @@ -1,155 +0,0 @@ -from collections.abc import Container -from typing import Any, Sequence, Tuple, Union, overload -from typing_extensions import Literal - -from .Image import Image -from .ImageColor import _Ink -from .ImageFont import _Font - -_XY = Sequence[Union[float, Tuple[float, float]]] -_Outline = Any - -class ImageDraw: - def __init__(self, im: Image, mode: str | None = ...) -> None: ... - def getfont(self): ... - def arc(self, xy: _XY, start: float, end: float, fill: _Ink | None = ..., width: float = ...) -> None: ... - def bitmap(self, xy: _XY, bitmap: Image, fill: _Ink | None = ...) -> None: ... - def chord( - self, xy: _XY, start: float, end: float, fill: _Ink | None = ..., outline: _Ink | None = ..., width: float = ... - ) -> None: ... - def ellipse(self, xy: _XY, fill: _Ink | None = ..., outline: _Ink | None = ..., width: float = ...) -> None: ... - def line(self, xy: _XY, fill: _Ink | None = ..., width: float = ..., joint: Literal["curve"] | None = ...) -> None: ... - def shape(self, shape: _Outline, fill: _Ink | None = ..., outline: _Ink | None = ...) -> None: ... - def pieslice( - self, - xy: tuple[tuple[float, float], tuple[float, float]], - start: float, - end: float, - fill: _Ink | None = ..., - outline: _Ink | None = ..., - width: float = ..., - ) -> None: ... - def point(self, xy: _XY, fill: _Ink | None = ...) -> None: ... - def polygon(self, xy: _XY, fill: _Ink | None = ..., outline: _Ink | None = ...) -> None: ... - def regular_polygon( - self, - bounding_circle: tuple[float, float] | tuple[float, float, float] | list[int], - n_sides: int, - rotation: float = ..., - fill: _Ink | None = ..., - outline: _Ink | None = ..., - ) -> None: ... - def rectangle( - self, - xy: tuple[float, float, float, float] | tuple[tuple[float, float], tuple[float, float]], - fill: _Ink | None = ..., - outline: _Ink | None = ..., - width: float = ..., - ) -> None: ... - def rounded_rectangle( - self, - xy: tuple[float, float, float, float] | tuple[tuple[float, float], tuple[float, float]], - radius: float = ..., - fill: _Ink | None = ..., - outline: _Ink | None = ..., - width: float = ..., - ) -> None: ... - def text( - self, - xy: tuple[float, float], - text: str | bytes, - fill: _Ink | None = ..., - font: _Font | None = ..., - anchor: str | None = ..., - spacing: float = ..., - align: Literal["left", "center", "right"] = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Sequence[str] | None = ..., - language: str | None = ..., - stroke_width: int = ..., - stroke_fill: _Ink | None = ..., - embedded_color: bool = ..., - *args, - **kwargs, - ) -> None: ... - def multiline_text( - self, - xy: tuple[float, float], - text: str | bytes, - fill: _Ink | None = ..., - font: _Font | None = ..., - anchor: str | None = ..., - spacing: float = ..., - align: Literal["left", "center", "right"] = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: int = ..., - stroke_fill: _Ink | None = ..., - embedded_color: bool = ..., - ) -> None: ... - def textsize( - self, - text: str | bytes, - font: _Font | None = ..., - spacing: float = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Sequence[str] | None = ..., - language: str | None = ..., - stroke_width: int = ..., - ) -> tuple[int, int]: ... - def multiline_textsize( - self, - text: str | bytes, - font: _Font | None = ..., - spacing: float = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Sequence[str] | None = ..., - language: str | None = ..., - stroke_width: int = ..., - ) -> tuple[int, int]: ... - def textlength( - self, - text: str | bytes, - font: _Font | None = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Sequence[str] | None = ..., - language: str | None = ..., - embedded_color: bool = ..., - ) -> int: ... - def textbbox( - self, - xy: tuple[float, float], - text: str | bytes, - font: _Font | None = ..., - anchor: str | None = ..., - spacing: float = ..., - align: Literal["left", "center", "right"] = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: int = ..., - embedded_color: bool = ..., - ) -> tuple[int, int, int, int]: ... - def multiline_textbbox( - self, - xy: tuple[float, float], - text: str | bytes, - font: _Font | None = ..., - anchor: str | None = ..., - spacing: float = ..., - align: Literal["left", "center", "right"] = ..., - direction: Literal["rtl", "ltr", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: int = ..., - embedded_color: bool = ..., - ) -> tuple[int, int, int, int]: ... - -def Draw(im: Image, mode: str | None = ...) -> ImageDraw: ... -def Outline() -> _Outline: ... -@overload -def getdraw(im: None = ..., hints: Container[Literal["nicest"]] | None = ...) -> tuple[None, Any]: ... -@overload -def getdraw(im: Image, hints: Container[Literal["nicest"]] | None = ...) -> tuple[Image, Any]: ... -def floodfill(image: Image, xy: tuple[float, float], value, border=..., thresh: float = ...) -> None: ... diff --git a/stubs/Pillow/PIL/ImageDraw2.pyi b/stubs/Pillow/PIL/ImageDraw2.pyi deleted file mode 100644 index 5b30711d384e..000000000000 --- a/stubs/Pillow/PIL/ImageDraw2.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Any - -class Pen: - color: Any - width: Any - def __init__(self, color, width: int = ..., opacity: int = ...) -> None: ... - -class Brush: - color: Any - def __init__(self, color, opacity: int = ...) -> None: ... - -class Font: - color: Any - font: Any - def __init__(self, color, file, size: int = ...) -> None: ... - -class Draw: - draw: Any - image: Any - transform: Any - def __init__(self, image, size: Any | None = ..., color: Any | None = ...) -> None: ... - def flush(self): ... - def render(self, op, xy, pen, brush: Any | None = ...) -> None: ... - def settransform(self, offset) -> None: ... - def arc(self, xy, start, end, *options) -> None: ... - def chord(self, xy, start, end, *options) -> None: ... - def ellipse(self, xy, *options) -> None: ... - def line(self, xy, *options) -> None: ... - def pieslice(self, xy, start, end, *options) -> None: ... - def polygon(self, xy, *options) -> None: ... - def rectangle(self, xy, *options) -> None: ... - def text(self, xy, text, font) -> None: ... - def textsize(self, text, font): ... diff --git a/stubs/Pillow/PIL/ImageEnhance.pyi b/stubs/Pillow/PIL/ImageEnhance.pyi deleted file mode 100644 index 6f0afa8d72f3..000000000000 --- a/stubs/Pillow/PIL/ImageEnhance.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from .Image import Image - -class _Enhance: - def enhance(self, factor: float) -> Image: ... - -class Color(_Enhance): - image: Image - intermediate_mode: str - degenerate: Image - def __init__(self, image: Image) -> None: ... - -class Contrast(_Enhance): - image: Image - degenerate: Image - def __init__(self, image: Image) -> None: ... - -class Brightness(_Enhance): - image: Image - degenerate: Image - def __init__(self, image: Image) -> None: ... - -class Sharpness(_Enhance): - image: Image - degenerate: Image - def __init__(self, image: Image) -> None: ... diff --git a/stubs/Pillow/PIL/ImageFile.pyi b/stubs/Pillow/PIL/ImageFile.pyi deleted file mode 100644 index 745509b49699..000000000000 --- a/stubs/Pillow/PIL/ImageFile.pyi +++ /dev/null @@ -1,70 +0,0 @@ -from typing import Any, NoReturn, TypeVar - -from .Image import Image - -_T = TypeVar("_T") - -MAXBLOCK: int -SAFEBLOCK: Any -LOAD_TRUNCATED_IMAGES: bool -ERRORS: Any - -def raise_oserror(error) -> NoReturn: ... -def raise_ioerror(error) -> NoReturn: ... - -class ImageFile(Image): - custom_mimetype: Any - tile: Any - readonly: int - decoderconfig: Any - decodermaxblock: Any - fp: Any - filename: Any - def __init__(self, fp: Any | None = ..., filename: Any | None = ...) -> None: ... - def get_format_mimetype(self): ... - def verify(self) -> None: ... - map: Any - im: Any - def load(self): ... - def load_prepare(self) -> None: ... - def load_end(self) -> None: ... - -class StubImageFile(ImageFile): - def load(self) -> None: ... - -class Parser: - incremental: Any | None - image: Any | None - data: Any | None - decoder: Any | None - offset: int - finished: bool - def reset(self) -> None: ... - decode: Any - def feed(self, data) -> None: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, *args: Any) -> None: ... - def close(self) -> Image: ... - -class PyCodecState: - xsize: int - ysize: int - xoff: int - yoff: int - def extents(self) -> tuple[int, int, int, int]: ... - -class PyDecoder: - im: Any - state: Any - fd: Any - mode: Any - def __init__(self, mode, *args) -> None: ... - args: Any - def init(self, args) -> None: ... - @property - def pulls_fd(self): ... - def decode(self, buffer) -> None: ... - def cleanup(self) -> None: ... - def setfd(self, fd) -> None: ... - def setimage(self, im, extents: Any | None = ...) -> None: ... - def set_as_raw(self, data, rawmode: Any | None = ...) -> None: ... diff --git a/stubs/Pillow/PIL/ImageFilter.pyi b/stubs/Pillow/PIL/ImageFilter.pyi deleted file mode 100644 index af03bce671dd..000000000000 --- a/stubs/Pillow/PIL/ImageFilter.pyi +++ /dev/null @@ -1,137 +0,0 @@ -from _typeshed import Self -from typing import Any, Callable, Iterable, Sequence, Tuple, Type -from typing_extensions import Literal - -from .Image import Image - -_FilterArgs = Tuple[Sequence[int], int, int, Sequence[int]] - -# filter image parameters below are the C images, i.e. Image().im. - -class Filter: ... -class MultibandFilter(Filter): ... - -class BuiltinFilter(MultibandFilter): - def filter(self, image) -> Image: ... - -class Kernel(BuiltinFilter): - name: str - filterargs: _FilterArgs - def __init__(self, size: Sequence[int], kernel: Sequence[int], scale: Any | None = ..., offset: int = ...) -> None: ... - -class RankFilter(Filter): - name: str - size: int - rank: int - def __init__(self, size: int, rank: int) -> None: ... - def filter(self, image) -> Image: ... - -class MedianFilter(RankFilter): - name: str - size: int - rank: int - def __init__(self, size: int = ...) -> None: ... - -class MinFilter(RankFilter): - name: str - size: int - rank: int - def __init__(self, size: int = ...) -> None: ... - -class MaxFilter(RankFilter): - name: str - size: int - rank: int - def __init__(self, size: int = ...) -> None: ... - -class ModeFilter(Filter): - name: str - size: int - def __init__(self, size: int = ...) -> None: ... - def filter(self, image) -> Image: ... - -class GaussianBlur(MultibandFilter): - name: str - radius: float - def __init__(self, radius: float = ...) -> None: ... - def filter(self, image) -> Image: ... - -class BoxBlur(MultibandFilter): - name: str - radius: float - def __init__(self, radius: float) -> None: ... - def filter(self, image) -> Image: ... - -class UnsharpMask(MultibandFilter): - name: str - radius: float - percent: int - threshold: int - def __init__(self, radius: float = ..., percent: int = ..., threshold: int = ...) -> None: ... - def filter(self, image) -> Image: ... - -class BLUR(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class CONTOUR(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class DETAIL(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class EDGE_ENHANCE(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class EDGE_ENHANCE_MORE(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class EMBOSS(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class FIND_EDGES(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class SHARPEN(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class SMOOTH(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class SMOOTH_MORE(BuiltinFilter): - name: str - filterargs: _FilterArgs - -class Color3DLUT(MultibandFilter): - name: str - size: list[int] - channels: int - mode: str | None - table: Any - def __init__( - self, size: int | Iterable[int], table, channels: int = ..., target_mode: str | None = ..., **kwargs - ) -> None: ... - @classmethod - def generate( - cls: Type[Self], - size: int | tuple[int, int, int], - callback: Callable[[float, float, float], Iterable[float]], - channels: int = ..., - target_mode: str | None = ..., - ) -> Self: ... - def transform( - self: Self, - callback: Callable[..., Iterable[float]], - with_normals: bool = ..., - channels: Literal[3, 4] | None = ..., - target_mode: Any | None = ..., - ) -> Self: ... - def filter(self, image) -> Image: ... diff --git a/stubs/Pillow/PIL/ImageFont.pyi b/stubs/Pillow/PIL/ImageFont.pyi deleted file mode 100644 index aa79a956af98..000000000000 --- a/stubs/Pillow/PIL/ImageFont.pyi +++ /dev/null @@ -1,119 +0,0 @@ -from _typeshed import StrOrBytesPath, SupportsRead -from typing import Any, Protocol -from typing_extensions import Literal - -LAYOUT_BASIC: Literal[0] -LAYOUT_RAQM: Literal[1] - -class _Font(Protocol): - def getmask(self, text: str | bytes, mode: str = ..., direction=..., features=...): ... - -class ImageFont: - def getsize(self, text: str | bytes, *args, **kwargs) -> tuple[int, int]: ... - def getmask(self, text: str | bytes, mode: str = ..., direction=..., features=...): ... - -class FreeTypeFont: - path: str | bytes | SupportsRead[bytes] | None - size: int - index: int - encoding: str - layout_engine: Any - def __init__( - self, - font: str | bytes | SupportsRead[bytes] | None = ..., - size: int = ..., - index: int = ..., - encoding: str = ..., - layout_engine: int | None = ..., - ) -> None: ... - def getname(self) -> tuple[str, str]: ... - def getmetrics(self) -> tuple[int, int]: ... - def getlength( - self, - text: str | bytes, - mode: str = ..., - direction: Literal["ltr", "rtl", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - ) -> int: ... - def getbbox( - self, - text: str | bytes, - mode: str = ..., - direction=..., - features=..., - language: str | None = ..., - stroke_width: int = ..., - anchor: str | None = ..., - ) -> tuple[int, int, int, int]: ... - def getsize( - self, - text: str | bytes, - direction: Literal["ltr", "rtl", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: int = ..., - ) -> tuple[int, int]: ... - def getsize_multiline( - self, - text: str | bytes, - direction: Literal["ltr", "rtl", "ttb"] | None = ..., - spacing: float = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: float = ..., - ) -> tuple[int, int]: ... - def getoffset(self, text: str | bytes) -> tuple[int, int]: ... - def getmask( - self, - text: str | bytes, - mode: str = ..., - direction: Literal["ltr", "rtl", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: float = ..., - anchor: str | None = ..., - ink=..., - ): ... - def getmask2( - self, - text: str | bytes, - mode: str = ..., - fill=..., - direction: Literal["ltr", "rtl", "ttb"] | None = ..., - features: Any | None = ..., - language: str | None = ..., - stroke_width: float = ..., - anchor: str | None = ..., - ink=..., - *args, - **kwargs, - ): ... - def font_variant( - self, - font: str | bytes | SupportsRead[bytes] | None = ..., - size: int | None = ..., - index: int | None = ..., - encoding: str | None = ..., - layout_engine: int | None = ..., - ) -> FreeTypeFont: ... - def get_variation_names(self): ... - def set_variation_by_name(self, name): ... - def get_variation_axes(self): ... - def set_variation_by_axes(self, axes): ... - -class TransposedFont: - def __init__(self, font: _Font, orientation: int | None = ...) -> None: ... - def getsize(self, text: str | bytes, *args, **kwargs) -> tuple[int, int]: ... - def getmask(self, text: str | bytes, mode: str = ..., *args, **kwargs): ... - -def load(filename: StrOrBytesPath | int) -> ImageFont: ... -def truetype( - font: str | bytes | SupportsRead[bytes] | None = ..., - size: int = ..., - index: int = ..., - encoding: str = ..., - layout_engine: int | None = ..., -) -> FreeTypeFont: ... -def load_path(filename: str | bytes) -> ImageFont: ... -def load_default() -> ImageFont: ... diff --git a/stubs/Pillow/PIL/ImageGrab.pyi b/stubs/Pillow/PIL/ImageGrab.pyi deleted file mode 100644 index 31411f35d029..000000000000 --- a/stubs/Pillow/PIL/ImageGrab.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any - -from .Image import Image, _Box - -def grab( - bbox: _Box | None = ..., include_layered_windows: bool = ..., all_screens: bool = ..., xdisplay: Any | None = ... -) -> Image: ... -def grabclipboard() -> Image | None: ... diff --git a/stubs/Pillow/PIL/ImageMath.pyi b/stubs/Pillow/PIL/ImageMath.pyi deleted file mode 100644 index de95a29fe40c..000000000000 --- a/stubs/Pillow/PIL/ImageMath.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any - -VERBOSE: int - -class _Operand: - im: Any - def __init__(self, im) -> None: ... - def apply(self, op, im1, im2: Any | None = ..., mode: Any | None = ...): ... - def __bool__(self): ... - def __abs__(self): ... - def __pos__(self): ... - def __neg__(self): ... - def __add__(self, other): ... - def __radd__(self, other): ... - def __sub__(self, other): ... - def __rsub__(self, other): ... - def __mul__(self, other): ... - def __rmul__(self, other): ... - def __truediv__(self, other): ... - def __rtruediv__(self, other): ... - def __mod__(self, other): ... - def __rmod__(self, other): ... - def __pow__(self, other): ... - def __rpow__(self, other): ... - def __invert__(self): ... - def __and__(self, other): ... - def __rand__(self, other): ... - def __or__(self, other): ... - def __ror__(self, other): ... - def __xor__(self, other): ... - def __rxor__(self, other): ... - def __lshift__(self, other): ... - def __rshift__(self, other): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... - -def imagemath_int(self): ... -def imagemath_float(self): ... -def imagemath_equal(self, other): ... -def imagemath_notequal(self, other): ... -def imagemath_min(self, other): ... -def imagemath_max(self, other): ... -def imagemath_convert(self, mode): ... - -ops: Any - -def eval(expression, _dict=..., **kw): ... diff --git a/stubs/Pillow/PIL/ImageMode.pyi b/stubs/Pillow/PIL/ImageMode.pyi deleted file mode 100644 index 0716dea049b6..000000000000 --- a/stubs/Pillow/PIL/ImageMode.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -class ModeDescriptor: - mode: Any - bands: Any - basemode: Any - basetype: Any - def __init__(self, mode, bands, basemode, basetype) -> None: ... - -def getmode(mode): ... diff --git a/stubs/Pillow/PIL/ImageMorph.pyi b/stubs/Pillow/PIL/ImageMorph.pyi deleted file mode 100644 index 2668787b76a7..000000000000 --- a/stubs/Pillow/PIL/ImageMorph.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from _typeshed import StrOrBytesPath - -from .Image import Image - -LUT_SIZE: int -ROTATION_MATRIX: list[int] -MIRROR_MATRIX: list[int] - -class LutBuilder: - patterns: list[str] - lut: bytearray - def __init__(self, patterns: list[str] | None = ..., op_name: str | None = ...) -> None: ... - def add_patterns(self, patterns: list[str]) -> None: ... - def build_default_lut(self) -> None: ... - def get_lut(self) -> bytearray: ... - def build_lut(self) -> bytearray: ... - -class MorphOp: - lut: bytearray - def __init__(self, lut: bytearray | None = ..., op_name: str | None = ..., patterns: list[str] | None = ...) -> None: ... - def apply(self, image: Image) -> tuple[int, Image]: ... - def match(self, image: Image) -> list[tuple[int, int]]: ... - def get_on_pixels(self, image: Image) -> list[tuple[int, int]]: ... - def load_lut(self, filename: StrOrBytesPath) -> None: ... - def save_lut(self, filename: StrOrBytesPath) -> None: ... - def set_lut(self, lut: bytearray) -> None: ... diff --git a/stubs/Pillow/PIL/ImageOps.pyi b/stubs/Pillow/PIL/ImageOps.pyi deleted file mode 100644 index 2c84e4dc6ba1..000000000000 --- a/stubs/Pillow/PIL/ImageOps.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from typing import Any, Iterable, Protocol, Union - -from .Image import Image, _Resample, _Size -from .ImageColor import _Ink - -_Border = Union[int, tuple[int, int], tuple[int, int, int, int]] - -class _Deformer(Protocol): - def getmesh(self, image: Image): ... - -def autocontrast( - image: Image, cutoff: int = ..., ignore: int | None = ..., mask: Image | None = ..., preserve_tone: bool = ... -) -> Image: ... -def colorize( - image: Image, - black: int | str, - white: int | str, - mid: int | str | None = ..., - blackpoint: int = ..., - whitepoint: int = ..., - midpoint: int = ..., -) -> Image: ... -def contain(image: Image, size: _Size, method: _Resample = ...) -> Image: ... -def pad( - image: Image, size: _Size, method: _Resample = ..., color: Any | None = ..., centering: Iterable[float] = ... -) -> Image: ... -def crop(image: Image, border: _Border = ...) -> Image: ... -def scale(image: Image, factor: float, resample: _Resample = ...) -> Image: ... -def deform(image: Image, deformer: _Deformer, resample: _Resample = ...) -> Image: ... -def equalize(image: Image, mask: Any | None = ...) -> Image: ... -def expand(image: Image, border: _Border = ..., fill: _Ink = ...) -> Image: ... -def fit(image: Image, size: _Size, method: _Resample = ..., bleed: float = ..., centering: Iterable[float] = ...) -> Image: ... -def flip(image: Image) -> Image: ... -def grayscale(image: Image) -> Image: ... -def invert(image: Image) -> Image: ... -def mirror(image: Image) -> Image: ... -def posterize(image: Image, bits: int) -> Image: ... -def solarize(image: Image, threshold: int = ...) -> Image: ... -def exif_transpose(image: Image) -> Image: ... diff --git a/stubs/Pillow/PIL/ImagePalette.pyi b/stubs/Pillow/PIL/ImagePalette.pyi deleted file mode 100644 index 7e1f80e1b679..000000000000 --- a/stubs/Pillow/PIL/ImagePalette.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any - -from .Image import Image - -class ImagePalette: - mode: Any - rawmode: Any - palette: Any - colors: Any - dirty: Any - def __init__(self, mode: str = ..., palette: Any | None = ..., size: int = ...) -> None: ... - def copy(self) -> ImagePalette: ... - def getdata(self): ... - def tobytes(self) -> bytes: ... - tostring = tobytes - def getcolor(self, color: tuple[int, int, int], image: Image | None = ...) -> int: ... - def save(self, fp) -> None: ... - -def raw(rawmode, data): ... -def make_linear_lut(black, white): ... -def make_gamma_lut(exp): ... -def negative(mode: str = ...): ... -def random(mode: str = ...): ... -def sepia(white: str = ...): ... -def wedge(mode: str = ...): ... -def load(filename): ... diff --git a/stubs/Pillow/PIL/ImagePath.pyi b/stubs/Pillow/PIL/ImagePath.pyi deleted file mode 100644 index b079651140e2..000000000000 --- a/stubs/Pillow/PIL/ImagePath.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from ._imaging import path - -Path = path diff --git a/stubs/Pillow/PIL/ImageQt.pyi b/stubs/Pillow/PIL/ImageQt.pyi deleted file mode 100644 index b223bba1455d..000000000000 --- a/stubs/Pillow/PIL/ImageQt.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any -from typing_extensions import Literal - -from .Image import Image - -QImage = Any # imported from either of {PyQt6,PySide6,PyQt5,PySide2}.QtGui -QPixmap = Any - -qt_versions: Any -qt_is_installed: bool -qt_version: Any - -def rgb(r: int, g: int, b: int, a: int = ...) -> int: ... -def fromqimage(im: Image | QImage) -> Image: ... -def fromqpixmap(im: Image | QImage) -> Image: ... -def align8to32(bytes: bytes, width: int, mode: Literal["1", "L", "P"]) -> bytes: ... - -class ImageQt(QImage): - def __init__(self, im: Image) -> None: ... - -def toqimage(im: Image) -> ImageQt: ... -def toqpixmap(im: Image) -> QPixmap: ... diff --git a/stubs/Pillow/PIL/ImageSequence.pyi b/stubs/Pillow/PIL/ImageSequence.pyi deleted file mode 100644 index cdcad977cbc0..000000000000 --- a/stubs/Pillow/PIL/ImageSequence.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class Iterator: - im: Any - position: Any - def __init__(self, im) -> None: ... - def __getitem__(self, ix): ... - def __iter__(self): ... - def __next__(self): ... - -def all_frames(im, func: Any | None = ...): ... diff --git a/stubs/Pillow/PIL/ImageShow.pyi b/stubs/Pillow/PIL/ImageShow.pyi deleted file mode 100644 index 27daf3fb46c3..000000000000 --- a/stubs/Pillow/PIL/ImageShow.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Any - -def register(viewer, order: int = ...) -> None: ... -def show(image, title: Any | None = ..., **options): ... - -class Viewer: - def show(self, image, **options): ... - format: Any - options: Any - def get_format(self, image): ... - def get_command(self, file, **options) -> None: ... - def save_image(self, image): ... - def show_image(self, image, **options): ... - def show_file(self, file, **options): ... - -class WindowsViewer(Viewer): - format: str - options: Any - def get_command(self, file, **options): ... - -class MacViewer(Viewer): - format: str - options: Any - def get_command(self, file, **options): ... - def show_file(self, file, **options): ... - -class UnixViewer(Viewer): - format: str - options: Any - def get_command(self, file, **options): ... - def show_file(self, file, **options): ... - -class DisplayViewer(UnixViewer): - def get_command_ex(self, file, **options): ... - -class GmDisplayViewer(UnixViewer): - def get_command_ex(self, file, **options): ... - -class EogViewer(UnixViewer): - def get_command_ex(self, file, **options): ... - -class XVViewer(UnixViewer): - def get_command_ex(self, file, title: Any | None = ..., **options): ... - -class IPythonViewer(Viewer): - def show_image(self, image, **options): ... diff --git a/stubs/Pillow/PIL/ImageStat.pyi b/stubs/Pillow/PIL/ImageStat.pyi deleted file mode 100644 index 13f08c5dc0a5..000000000000 --- a/stubs/Pillow/PIL/ImageStat.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -class Stat: - h: Any - bands: Any - def __init__(self, image_or_list, mask: Any | None = ...) -> None: ... - def __getattr__(self, id): ... - -Global = Stat diff --git a/stubs/Pillow/PIL/ImageTk.pyi b/stubs/Pillow/PIL/ImageTk.pyi deleted file mode 100644 index 87efd5ecd7a1..000000000000 --- a/stubs/Pillow/PIL/ImageTk.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -class PhotoImage: - tk: Any - def __init__(self, image: Any | None = ..., size: Any | None = ..., **kw) -> None: ... - def __del__(self) -> None: ... - def width(self): ... - def height(self): ... - def paste(self, im, box: Any | None = ...) -> None: ... - -class BitmapImage: - def __init__(self, image: Any | None = ..., **kw) -> None: ... - def __del__(self) -> None: ... - def width(self): ... - def height(self): ... - -def getimage(photo): ... diff --git a/stubs/Pillow/PIL/ImageTransform.pyi b/stubs/Pillow/PIL/ImageTransform.pyi deleted file mode 100644 index 7b7d82b335de..000000000000 --- a/stubs/Pillow/PIL/ImageTransform.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from .Image import ImageTransformHandler - -class Transform(ImageTransformHandler): - data: Any - def __init__(self, data) -> None: ... - def getdata(self): ... - def transform(self, size, image, **options): ... - -class AffineTransform(Transform): - method: Any - -class ExtentTransform(Transform): - method: Any - -class QuadTransform(Transform): - method: Any - -class MeshTransform(Transform): - method: Any diff --git a/stubs/Pillow/PIL/ImageWin.pyi b/stubs/Pillow/PIL/ImageWin.pyi deleted file mode 100644 index 4af82167e9fe..000000000000 --- a/stubs/Pillow/PIL/ImageWin.pyi +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any - -class HDC: - dc: Any - def __init__(self, dc) -> None: ... - def __int__(self): ... - -class HWND: - wnd: Any - def __init__(self, wnd) -> None: ... - def __int__(self): ... - -class Dib: - image: Any - mode: Any - size: Any - def __init__(self, image, size: Any | None = ...) -> None: ... - def expose(self, handle): ... - def draw(self, handle, dst, src: Any | None = ...): ... - def query_palette(self, handle): ... - def paste(self, im, box: Any | None = ...) -> None: ... - def frombytes(self, buffer): ... - def tobytes(self): ... - -class Window: - hwnd: Any - def __init__(self, title: str = ..., width: Any | None = ..., height: Any | None = ...) -> None: ... - def ui_handle_clear(self, dc, x0, y0, x1, y1) -> None: ... - def ui_handle_damage(self, x0, y0, x1, y1) -> None: ... - def ui_handle_destroy(self) -> None: ... - def ui_handle_repair(self, dc, x0, y0, x1, y1) -> None: ... - def ui_handle_resize(self, width, height) -> None: ... - def mainloop(self) -> None: ... - -class ImageWindow(Window): - image: Any - def __init__(self, image, title: str = ...) -> None: ... - def ui_handle_repair(self, dc, x0, y0, x1, y1) -> None: ... diff --git a/stubs/Pillow/PIL/ImtImagePlugin.pyi b/stubs/Pillow/PIL/ImtImagePlugin.pyi deleted file mode 100644 index 567cbe42ef20..000000000000 --- a/stubs/Pillow/PIL/ImtImagePlugin.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -field: Any - -class ImtImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/IptcImagePlugin.pyi b/stubs/Pillow/PIL/IptcImagePlugin.pyi deleted file mode 100644 index dac96b3b5c6a..000000000000 --- a/stubs/Pillow/PIL/IptcImagePlugin.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -COMPRESSION: Any -PAD: Any - -def i(c): ... -def dump(c) -> None: ... - -class IptcImageFile(ImageFile): - format: str - format_description: str - def getint(self, key): ... - def field(self): ... - im: Any - def load(self): ... - -def getiptcinfo(im): ... diff --git a/stubs/Pillow/PIL/Jpeg2KImagePlugin.pyi b/stubs/Pillow/PIL/Jpeg2KImagePlugin.pyi deleted file mode 100644 index 72907813434a..000000000000 --- a/stubs/Pillow/PIL/Jpeg2KImagePlugin.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -class Jpeg2KImageFile(ImageFile): - format: str - format_description: str - reduce: Any - tile: Any - def load(self): ... diff --git a/stubs/Pillow/PIL/JpegImagePlugin.pyi b/stubs/Pillow/PIL/JpegImagePlugin.pyi deleted file mode 100644 index 0941106925f3..000000000000 --- a/stubs/Pillow/PIL/JpegImagePlugin.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -def Skip(self, marker) -> None: ... -def APP(self, marker) -> None: ... -def COM(self, marker) -> None: ... -def SOF(self, marker) -> None: ... -def DQT(self, marker) -> None: ... - -MARKER: Any - -class JpegImageFile(ImageFile): - format: str - format_description: str - def load_read(self, read_bytes): ... - mode: Any - tile: Any - decoderconfig: Any - def draft(self, mode, size): ... - im: Any - def load_djpeg(self) -> None: ... - def getxmp(self): ... - -RAWMODE: Any -zigzag_index: Any -samplings: Any - -def convert_dict_qtables(qtables): ... -def get_sampling(im): ... -def jpeg_factory(fp: Any | None = ..., filename: Any | None = ...): ... diff --git a/stubs/Pillow/PIL/JpegPresets.pyi b/stubs/Pillow/PIL/JpegPresets.pyi deleted file mode 100644 index 8b213e668b7b..000000000000 --- a/stubs/Pillow/PIL/JpegPresets.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -presets: Any diff --git a/stubs/Pillow/PIL/McIdasImagePlugin.pyi b/stubs/Pillow/PIL/McIdasImagePlugin.pyi deleted file mode 100644 index c492fe2ac7c0..000000000000 --- a/stubs/Pillow/PIL/McIdasImagePlugin.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from .ImageFile import ImageFile - -class McIdasImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/MicImagePlugin.pyi b/stubs/Pillow/PIL/MicImagePlugin.pyi deleted file mode 100644 index 48fe3c7509e0..000000000000 --- a/stubs/Pillow/PIL/MicImagePlugin.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from .TiffImagePlugin import TiffImageFile - -class MicImageFile(TiffImageFile): - format: str - format_description: str - fp: Any - frame: Any - def seek(self, frame) -> None: ... - def tell(self): ... diff --git a/stubs/Pillow/PIL/MpegImagePlugin.pyi b/stubs/Pillow/PIL/MpegImagePlugin.pyi deleted file mode 100644 index 4cadacb07b02..000000000000 --- a/stubs/Pillow/PIL/MpegImagePlugin.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -class BitStream: - fp: Any - bits: int - bitbuffer: int - def __init__(self, fp) -> None: ... - def next(self): ... - def peek(self, bits): ... - def skip(self, bits) -> None: ... - def read(self, bits): ... - -class MpegImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/MpoImagePlugin.pyi b/stubs/Pillow/PIL/MpoImagePlugin.pyi deleted file mode 100644 index b89dfa2e7b3a..000000000000 --- a/stubs/Pillow/PIL/MpoImagePlugin.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from .JpegImagePlugin import JpegImageFile - -class MpoImageFile(JpegImageFile): - format: str - format_description: str - def load_seek(self, pos) -> None: ... - fp: Any - offset: Any - tile: Any - def seek(self, frame) -> None: ... - def tell(self): ... - @staticmethod - def adopt(jpeg_instance, mpheader: Any | None = ...): ... diff --git a/stubs/Pillow/PIL/MspImagePlugin.pyi b/stubs/Pillow/PIL/MspImagePlugin.pyi deleted file mode 100644 index 2f34b05597d4..000000000000 --- a/stubs/Pillow/PIL/MspImagePlugin.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from .ImageFile import ImageFile, PyDecoder - -class MspImageFile(ImageFile): - format: str - format_description: str - -class MspDecoder(PyDecoder): - def decode(self, buffer): ... diff --git a/stubs/Pillow/PIL/PSDraw.pyi b/stubs/Pillow/PIL/PSDraw.pyi deleted file mode 100644 index 2386f284a980..000000000000 --- a/stubs/Pillow/PIL/PSDraw.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from _typeshed import SupportsWrite - -from .Image import Image - -class PSDraw: - fp: SupportsWrite[bytes] - def __init__(self, fp: SupportsWrite[bytes] | None = ...) -> None: ... - isofont: dict[bytes, int] - def begin_document(self, id: object | None = ...) -> None: ... - def end_document(self) -> None: ... - def setfont(self, font: str, size: int) -> None: ... - def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None: ... - def rectangle(self, box: tuple[int, int, int, int]) -> None: ... - def text(self, xy: tuple[int, int], text: str) -> None: ... - def image(self, box: tuple[int, int, int, int], im: Image, dpi: float | None = ...) -> None: ... - -EDROFF_PS: bytes -VDI_PS: bytes -ERROR_PS: bytes diff --git a/stubs/Pillow/PIL/PaletteFile.pyi b/stubs/Pillow/PIL/PaletteFile.pyi deleted file mode 100644 index 7f478448fc1d..000000000000 --- a/stubs/Pillow/PIL/PaletteFile.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -class PaletteFile: - rawmode: str - palette: Any - def __init__(self, fp) -> None: ... - def getpalette(self): ... diff --git a/stubs/Pillow/PIL/PalmImagePlugin.pyi b/stubs/Pillow/PIL/PalmImagePlugin.pyi deleted file mode 100644 index 1cf530cef2cc..000000000000 --- a/stubs/Pillow/PIL/PalmImagePlugin.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any - -def build_prototype_image(): ... - -Palm8BitColormapImage: Any diff --git a/stubs/Pillow/PIL/PcdImagePlugin.pyi b/stubs/Pillow/PIL/PcdImagePlugin.pyi deleted file mode 100644 index 0c147ca5e452..000000000000 --- a/stubs/Pillow/PIL/PcdImagePlugin.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -class PcdImageFile(ImageFile): - format: str - format_description: str - im: Any - def load_end(self) -> None: ... diff --git a/stubs/Pillow/PIL/PcfFontFile.pyi b/stubs/Pillow/PIL/PcfFontFile.pyi deleted file mode 100644 index 97836cb78ae1..000000000000 --- a/stubs/Pillow/PIL/PcfFontFile.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -from .FontFile import FontFile - -PCF_MAGIC: int -PCF_PROPERTIES: Any -PCF_ACCELERATORS: Any -PCF_METRICS: Any -PCF_BITMAPS: Any -PCF_INK_METRICS: Any -PCF_BDF_ENCODINGS: Any -PCF_SWIDTHS: Any -PCF_GLYPH_NAMES: Any -PCF_BDF_ACCELERATORS: Any -BYTES_PER_ROW: Any - -def sz(s, o): ... - -class PcfFontFile(FontFile): - name: str - charset_encoding: Any - toc: Any - fp: Any - info: Any - def __init__(self, fp, charset_encoding: str = ...) -> None: ... diff --git a/stubs/Pillow/PIL/PcxImagePlugin.pyi b/stubs/Pillow/PIL/PcxImagePlugin.pyi deleted file mode 100644 index 8a47f72a8bed..000000000000 --- a/stubs/Pillow/PIL/PcxImagePlugin.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -logger: Any - -class PcxImageFile(ImageFile): - format: str - format_description: str - -SAVE: Any diff --git a/stubs/Pillow/PIL/PdfParser.pyi b/stubs/Pillow/PIL/PdfParser.pyi deleted file mode 100644 index 4e484ae2a817..000000000000 --- a/stubs/Pillow/PIL/PdfParser.pyi +++ /dev/null @@ -1,158 +0,0 @@ -import collections -from typing import Any, List - -def encode_text(s: str) -> bytes: ... - -PDFDocEncoding: dict[int, str] - -def decode_text(b: bytes) -> str: ... - -class PdfFormatError(RuntimeError): ... - -def check_format_condition(condition, error_message) -> None: ... - -class IndirectReference: - def __bytes__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __hash__(self): ... - -class IndirectObjectDef(IndirectReference): ... - -class XrefTable: - existing_entries: Any - new_entries: Any - deleted_entries: Any - reading_finished: bool - def __init__(self) -> None: ... - def __setitem__(self, key, value) -> None: ... - def __getitem__(self, key): ... - def __delitem__(self, key) -> None: ... - def __contains__(self, key): ... - def __len__(self): ... - def keys(self): ... - def write(self, f): ... - -class PdfName: - name: Any - def __init__(self, name) -> None: ... - def name_as_str(self): ... - def __eq__(self, other): ... - def __hash__(self): ... - @classmethod - def from_pdf_stream(cls, data): ... - allowed_chars: Any - def __bytes__(self): ... - -class PdfArray(List[Any]): - def __bytes__(self): ... - -class PdfDict(collections.UserDict): - def __setattr__(self, key, value) -> None: ... - def __getattr__(self, key): ... - def __bytes__(self): ... - -class PdfBinary: - data: Any - def __init__(self, data) -> None: ... - def __bytes__(self): ... - -class PdfStream: - dictionary: Any - buf: Any - def __init__(self, dictionary, buf) -> None: ... - def decode(self): ... - -def pdf_repr(x: Any) -> bytes: ... - -class PdfParser: - filename: Any - buf: Any - f: Any - start_offset: Any - should_close_buf: bool - should_close_file: bool - cached_objects: Any - file_size_total: int - root: Any - root_ref: Any - info: Any - info_ref: Any - page_tree_root: Any - pages: Any - orig_pages: Any - pages_ref: Any - last_xref_section_offset: Any - trailer_dict: Any - xref_table: Any - def __init__( - self, filename: Any | None = ..., f: Any | None = ..., buf: Any | None = ..., start_offset: int = ..., mode: str = ... - ) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type, exc_value, traceback): ... - def start_writing(self) -> None: ... - def close_buf(self) -> None: ... - def close(self) -> None: ... - def seek_end(self) -> None: ... - def write_header(self) -> None: ... - def write_comment(self, s) -> None: ... - def write_catalog(self): ... - def rewrite_pages(self) -> None: ... - def write_xref_and_trailer(self, new_root_ref: Any | None = ...) -> None: ... - def write_page(self, ref, *objs, **dict_obj): ... - def write_obj(self, ref, *objs, **dict_obj): ... - def del_root(self) -> None: ... - @staticmethod - def get_buf_from_file(f): ... - file_size_this: Any - def read_pdf_info(self) -> None: ... - def next_object_id(self, offset: Any | None = ...): ... - delimiter: bytes - delimiter_or_ws: bytes - whitespace: bytes - whitespace_or_hex: bytes - whitespace_optional: Any - whitespace_mandatory: Any - whitespace_optional_no_nl: bytes - newline_only: bytes - newline: Any - re_trailer_end: Any - re_trailer_prev: Any - def read_trailer(self) -> None: ... - def read_prev_trailer(self, xref_section_offset) -> None: ... - re_whitespace_optional: Any - re_name: Any - re_dict_start: Any - re_dict_end: Any - @classmethod - def interpret_trailer(cls, trailer_data): ... - re_hashes_in_name: Any - @classmethod - def interpret_name(cls, raw, as_text: bool = ...): ... - re_null: Any - re_true: Any - re_false: Any - re_int: Any - re_real: Any - re_array_start: Any - re_array_end: Any - re_string_hex: Any - re_string_lit: Any - re_indirect_reference: Any - re_indirect_def_start: Any - re_indirect_def_end: Any - re_comment: Any - re_stream_start: Any - re_stream_end: Any - @classmethod - def get_value(cls, data, offset, expect_indirect: Any | None = ..., max_nesting: int = ...): ... - re_lit_str_token: Any - escaped_chars: Any - @classmethod - def get_literal_string(cls, data, offset): ... - re_xref_section_start: Any - re_xref_subsection_start: Any - re_xref_entry: Any - def read_xref_table(self, xref_section_offset): ... - def read_indirect(self, ref, max_nesting: int = ...): ... - def linearize_page_tree(self, node: Any | None = ...): ... diff --git a/stubs/Pillow/PIL/PixarImagePlugin.pyi b/stubs/Pillow/PIL/PixarImagePlugin.pyi deleted file mode 100644 index 31890c45d362..000000000000 --- a/stubs/Pillow/PIL/PixarImagePlugin.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from .ImageFile import ImageFile - -class PixarImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/PngImagePlugin.pyi b/stubs/Pillow/PIL/PngImagePlugin.pyi deleted file mode 100644 index 3126f6b23b26..000000000000 --- a/stubs/Pillow/PIL/PngImagePlugin.pyi +++ /dev/null @@ -1,110 +0,0 @@ -from typing import Any - -from ._binary import o8 as o8 -from .ImageFile import ImageFile - -logger: Any -is_cid: Any -MAX_TEXT_CHUNK: Any -MAX_TEXT_MEMORY: Any -APNG_DISPOSE_OP_NONE: int -APNG_DISPOSE_OP_BACKGROUND: int -APNG_DISPOSE_OP_PREVIOUS: int -APNG_BLEND_OP_SOURCE: int -APNG_BLEND_OP_OVER: int - -class ChunkStream: - fp: Any - queue: Any - def __init__(self, fp) -> None: ... - def read(self): ... - def __enter__(self): ... - def __exit__(self, *args) -> None: ... - def close(self) -> None: ... - def push(self, cid, pos, length) -> None: ... - def call(self, cid, pos, length): ... - def crc(self, cid, data) -> None: ... - def crc_skip(self, cid, data) -> None: ... - def verify(self, endchunk: bytes = ...): ... - -class iTXt(str): - lang: Any - tkey: Any - @staticmethod - def __new__(cls, text, lang: Any | None = ..., tkey: Any | None = ...): ... - -class PngInfo: - chunks: Any - def __init__(self) -> None: ... - def add(self, cid, data, after_idat: bool = ...) -> None: ... - def add_itxt(self, key, value, lang: str = ..., tkey: str = ..., zip: bool = ...) -> None: ... - def add_text(self, key, value, zip: bool = ...): ... - -class PngStream(ChunkStream): - im_info: Any - im_text: Any - im_size: Any - im_mode: Any - im_tile: Any - im_palette: Any - im_custom_mimetype: Any - im_n_frames: Any - rewind_state: Any - text_memory: int - def __init__(self, fp) -> None: ... - def check_text_memory(self, chunklen) -> None: ... - def save_rewind(self) -> None: ... - def rewind(self) -> None: ... - def chunk_iCCP(self, pos, length): ... - def chunk_IHDR(self, pos, length): ... - im_idat: Any - def chunk_IDAT(self, pos, length) -> None: ... - def chunk_IEND(self, pos, length) -> None: ... - def chunk_PLTE(self, pos, length): ... - def chunk_tRNS(self, pos, length): ... - def chunk_gAMA(self, pos, length): ... - def chunk_cHRM(self, pos, length): ... - def chunk_sRGB(self, pos, length): ... - def chunk_pHYs(self, pos, length): ... - def chunk_tEXt(self, pos, length): ... - def chunk_zTXt(self, pos, length): ... - def chunk_iTXt(self, pos, length): ... - def chunk_eXIf(self, pos, length): ... - def chunk_acTL(self, pos, length): ... - def chunk_fcTL(self, pos, length): ... - def chunk_fdAT(self, pos, length): ... - -class PngImageFile(ImageFile): - format: str - format_description: str - @property - def text(self): ... - fp: Any - def verify(self) -> None: ... - def seek(self, frame) -> None: ... - def tell(self): ... - decoderconfig: Any - def load_prepare(self) -> None: ... - def load_read(self, read_bytes): ... - png: Any - im: Any - pyaccess: Any - def load_end(self) -> None: ... - def getexif(self): ... - -def putchunk(fp, cid, *data) -> None: ... - -class _idat: - fp: Any - chunk: Any - def __init__(self, fp, chunk) -> None: ... - def write(self, data) -> None: ... - -class _fdat: - fp: Any - chunk: Any - seq_num: Any - def __init__(self, fp, chunk, seq_num) -> None: ... - def write(self, data) -> None: ... - -def getchunks(im, **params): ... diff --git a/stubs/Pillow/PIL/PpmImagePlugin.pyi b/stubs/Pillow/PIL/PpmImagePlugin.pyi deleted file mode 100644 index 2adee46f2c62..000000000000 --- a/stubs/Pillow/PIL/PpmImagePlugin.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -b_whitespace: bytes -MODES: Any - -class PpmImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/PsdImagePlugin.pyi b/stubs/Pillow/PIL/PsdImagePlugin.pyi deleted file mode 100644 index 5a3d381fe61b..000000000000 --- a/stubs/Pillow/PIL/PsdImagePlugin.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -MODES: Any - -class PsdImageFile(ImageFile): - format: str - format_description: str - mode: Any - tile: Any - frame: Any - fp: Any - def seek(self, layer): ... - def tell(self): ... - im: Any - def load_prepare(self) -> None: ... diff --git a/stubs/Pillow/PIL/PyAccess.pyi b/stubs/Pillow/PIL/PyAccess.pyi deleted file mode 100644 index 2d87adf903b9..000000000000 --- a/stubs/Pillow/PIL/PyAccess.pyi +++ /dev/null @@ -1,62 +0,0 @@ -from logging import Logger -from typing import Any - -ffi: Any -logger: Logger - -class PyAccess: - readonly: Any - image8: Any - image32: Any - image: Any - def __init__(self, img, readonly: bool = ...) -> None: ... - def __setitem__(self, xy, color): ... - def __getitem__(self, xy): ... - putpixel: Any - getpixel: Any - def check_xy(self, xy): ... - -class _PyAccess32_2(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccess32_3(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccess32_4(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccess8(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccessI16_N(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccessI16_L(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccessI16_B(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccessI32_N(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccessI32_Swap(PyAccess): - def reverse(self, i): ... - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -class _PyAccessF(PyAccess): - def get_pixel(self, x, y): ... - def set_pixel(self, x, y, color) -> None: ... - -mode_map: Any - -def new(img, readonly: bool = ...): ... diff --git a/stubs/Pillow/PIL/SgiImagePlugin.pyi b/stubs/Pillow/PIL/SgiImagePlugin.pyi deleted file mode 100644 index 2d498dbd28da..000000000000 --- a/stubs/Pillow/PIL/SgiImagePlugin.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile, PyDecoder - -MODES: Any - -class SgiImageFile(ImageFile): - format: str - format_description: str - -class SGI16Decoder(PyDecoder): - def decode(self, buffer): ... diff --git a/stubs/Pillow/PIL/SpiderImagePlugin.pyi b/stubs/Pillow/PIL/SpiderImagePlugin.pyi deleted file mode 100644 index 8a3e213c0396..000000000000 --- a/stubs/Pillow/PIL/SpiderImagePlugin.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any -from typing_extensions import Literal - -from .ImageFile import ImageFile - -def isInt(f: object) -> Literal[0, 1]: ... - -iforms: Any - -def isSpiderHeader(t): ... -def isSpiderImage(filename): ... - -class SpiderImageFile(ImageFile): - format: str - format_description: str - @property - def n_frames(self): ... - @property - def is_animated(self): ... - def tell(self): ... - stkoffset: Any - fp: Any - def seek(self, frame) -> None: ... - def convert2byte(self, depth: int = ...): ... - def tkPhotoImage(self): ... - -def loadImageSeries(filelist: Any | None = ...): ... -def makeSpiderHeader(im): ... diff --git a/stubs/Pillow/PIL/SunImagePlugin.pyi b/stubs/Pillow/PIL/SunImagePlugin.pyi deleted file mode 100644 index 731c7884610a..000000000000 --- a/stubs/Pillow/PIL/SunImagePlugin.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from .ImageFile import ImageFile - -class SunImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/TarIO.pyi b/stubs/Pillow/PIL/TarIO.pyi deleted file mode 100644 index 54748270fcda..000000000000 --- a/stubs/Pillow/PIL/TarIO.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from .ContainerIO import ContainerIO - -class TarIO(ContainerIO): - fh: Any - def __init__(self, tarfile, file) -> None: ... - def __enter__(self): ... - def __exit__(self, *args) -> None: ... - def close(self) -> None: ... diff --git a/stubs/Pillow/PIL/TgaImagePlugin.pyi b/stubs/Pillow/PIL/TgaImagePlugin.pyi deleted file mode 100644 index 3072da3019a4..000000000000 --- a/stubs/Pillow/PIL/TgaImagePlugin.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -MODES: Any - -class TgaImageFile(ImageFile): - format: str - format_description: str - -SAVE: Any diff --git a/stubs/Pillow/PIL/TiffImagePlugin.pyi b/stubs/Pillow/PIL/TiffImagePlugin.pyi deleted file mode 100644 index 5eaaa7b6f734..000000000000 --- a/stubs/Pillow/PIL/TiffImagePlugin.pyi +++ /dev/null @@ -1,190 +0,0 @@ -from collections.abc import MutableMapping -from numbers import Rational -from typing import Any - -from .ImageFile import ImageFile - -logger: Any -READ_LIBTIFF: bool -WRITE_LIBTIFF: bool -IFD_LEGACY_API: bool -II: bytes -MM: bytes -IMAGEWIDTH: int -IMAGELENGTH: int -BITSPERSAMPLE: int -COMPRESSION: int -PHOTOMETRIC_INTERPRETATION: int -FILLORDER: int -IMAGEDESCRIPTION: int -STRIPOFFSETS: int -SAMPLESPERPIXEL: int -ROWSPERSTRIP: int -STRIPBYTECOUNTS: int -X_RESOLUTION: int -Y_RESOLUTION: int -PLANAR_CONFIGURATION: int -RESOLUTION_UNIT: int -TRANSFERFUNCTION: int -SOFTWARE: int -DATE_TIME: int -ARTIST: int -PREDICTOR: int -COLORMAP: int -TILEOFFSETS: int -SUBIFD: int -EXTRASAMPLES: int -SAMPLEFORMAT: int -JPEGTABLES: int -REFERENCEBLACKWHITE: int -COPYRIGHT: int -IPTC_NAA_CHUNK: int -PHOTOSHOP_CHUNK: int -ICCPROFILE: int -EXIFIFD: int -XMP: int -JPEGQUALITY: int -IMAGEJ_META_DATA_BYTE_COUNTS: int -IMAGEJ_META_DATA: int -COMPRESSION_INFO: Any -COMPRESSION_INFO_REV: Any -OPEN_INFO: Any -PREFIXES: Any - -class IFDRational(Rational): - def __init__(self, value, denominator: int = ...) -> None: ... - @property - def numerator(a): ... - @property - def denominator(a): ... - def limit_rational(self, max_denominator): ... - def __hash__(self): ... - def __eq__(self, other): ... - __add__: Any - __radd__: Any - __sub__: Any - __rsub__: Any - __mul__: Any - __rmul__: Any - __truediv__: Any - __rtruediv__: Any - __floordiv__: Any - __rfloordiv__: Any - __mod__: Any - __rmod__: Any - __pow__: Any - __rpow__: Any - __pos__: Any - __neg__: Any - __abs__: Any - __trunc__: Any - __lt__: Any - __gt__: Any - __le__: Any - __ge__: Any - __bool__: Any - __ceil__: Any - __floor__: Any - __round__: Any - -class ImageFileDirectory_v2(MutableMapping[int, Any]): - group: int | None - tagtype: dict[int, int] - def __init__(self, ifh: bytes = ..., prefix: bytes | None = ..., group: int | None = ...) -> None: ... - @property - def prefix(self) -> bytes: ... - @property - def offset(self) -> int | None: ... - @property - def legacy_api(self) -> bool: ... - def reset(self) -> None: ... - def named(self): ... - def __len__(self) -> int: ... - def __getitem__(self, tag): ... - def __contains__(self, tag): ... - def __setitem__(self, tag, value) -> None: ... - def __delitem__(self, tag) -> None: ... - def __iter__(self): ... - def load_byte(self, data, legacy_api: bool = ...): ... - def write_byte(self, data): ... - def load_string(self, data, legacy_api: bool = ...): ... - def write_string(self, value): ... - def load_rational(self, data, legacy_api: bool = ...): ... - def write_rational(self, *values): ... - def load_undefined(self, data, legacy_api: bool = ...): ... - def write_undefined(self, value): ... - def load_signed_rational(self, data, legacy_api: bool = ...): ... - def write_signed_rational(self, *values): ... - def load(self, fp) -> None: ... - def tobytes(self, offset: int = ...): ... - def save(self, fp): ... - -class ImageFileDirectory_v1(ImageFileDirectory_v2): - def __init__(self, *args, **kwargs) -> None: ... - tags: Any - tagdata: Any - tagtype: dict[int, int] - @classmethod - def from_v2(cls, original): ... - def to_v2(self): ... - def __contains__(self, tag): ... - def __len__(self): ... - def __iter__(self): ... - def __setitem__(self, tag, value) -> None: ... - def __getitem__(self, tag): ... - -ImageFileDirectory = ImageFileDirectory_v1 - -class TiffImageFile(ImageFile): - format: str - format_description: str - tag_v2: Any - tag: Any - def __init__(self, fp: Any | None = ..., filename: Any | None = ...) -> None: ... - @property - def n_frames(self): ... - im: Any - def seek(self, frame) -> None: ... - def tell(self): ... - def load(self): ... - def load_end(self) -> None: ... - -SAVE_INFO: Any - -class AppendingTiffWriter: - fieldSizes: Any - Tags: Any - f: Any - close_fp: bool - name: Any - beginning: Any - def __init__(self, fn, new: bool = ...) -> None: ... - whereToWriteNewIFDOffset: Any - offsetOfNewPage: int - IIMM: Any - isFirst: bool - def setup(self) -> None: ... - def finalize(self) -> None: ... - def newFrame(self) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type, exc_value, traceback): ... - def tell(self): ... - def seek(self, offset, whence=...): ... - def goToEnd(self) -> None: ... - endian: Any - longFmt: Any - shortFmt: Any - tagFormat: Any - def setEndian(self, endian) -> None: ... - def skipIFDs(self) -> None: ... - def write(self, data): ... - def readShort(self): ... - def readLong(self): ... - def rewriteLastShortToLong(self, value) -> None: ... - def rewriteLastShort(self, value) -> None: ... - def rewriteLastLong(self, value) -> None: ... - def writeShort(self, value) -> None: ... - def writeLong(self, value) -> None: ... - def close(self) -> None: ... - def fixIFD(self) -> None: ... - def fixOffsets(self, count, isShort: bool = ..., isLong: bool = ...) -> None: ... diff --git a/stubs/Pillow/PIL/TiffTags.pyi b/stubs/Pillow/PIL/TiffTags.pyi deleted file mode 100644 index 5559e169bd5c..000000000000 --- a/stubs/Pillow/PIL/TiffTags.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Any, Dict, NamedTuple, Tuple, Union -from typing_extensions import Literal - -class _TagInfo(NamedTuple): - value: Any - name: str - type: _TagType - length: int - enum: dict[str, int] - -class TagInfo(_TagInfo): - def __new__( - cls, - value: Any | None = ..., - name: str = ..., - type: _TagType | None = ..., - length: int | None = ..., - enum: dict[str, int] | None = ..., - ): ... - def cvt_enum(self, value): ... - -def lookup(tag: int, group: int | None = ...) -> _TagInfo: ... - -BYTE: Literal[1] -ASCII: Literal[2] -SHORT: Literal[3] -LONG: Literal[4] -RATIONAL: Literal[5] -SIGNED_BYTE: Literal[6] -UNDEFINED: Literal[7] -SIGNED_SHORT: Literal[8] -SIGNED_LONG: Literal[9] -SIGNED_RATIONAL: Literal[10] -FLOAT: Literal[11] -DOUBLE: Literal[12] -IFD: Literal[13] - -_TagType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -_TagTuple = Union[Tuple[str, _TagType, int], Tuple[str, _TagInfo, int, Dict[str, int]]] - -TAGS_V2: dict[int, _TagTuple] -TAGS_V2_GROUPS: dict[int, dict[int, _TagTuple]] -TAGS: dict[int, str] -TYPES: dict[int, str] -LIBTIFF_CORE: set[int] diff --git a/stubs/Pillow/PIL/WalImageFile.pyi b/stubs/Pillow/PIL/WalImageFile.pyi deleted file mode 100644 index 6355032c853c..000000000000 --- a/stubs/Pillow/PIL/WalImageFile.pyi +++ /dev/null @@ -1,3 +0,0 @@ -def open(filename): ... - -quake2palette: bytes diff --git a/stubs/Pillow/PIL/WebPImagePlugin.pyi b/stubs/Pillow/PIL/WebPImagePlugin.pyi deleted file mode 100644 index 97614e6d03f1..000000000000 --- a/stubs/Pillow/PIL/WebPImagePlugin.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -SUPPORTED: bool - -class WebPImageFile(ImageFile): - format: str - format_description: str - def seek(self, frame) -> None: ... - fp: Any - tile: Any - def load(self): ... - def tell(self): ... diff --git a/stubs/Pillow/PIL/WmfImagePlugin.pyi b/stubs/Pillow/PIL/WmfImagePlugin.pyi deleted file mode 100644 index b7244948f03a..000000000000 --- a/stubs/Pillow/PIL/WmfImagePlugin.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from .ImageFile import StubImageFile - -def register_handler(handler) -> None: ... - -class WmfHandler: - bbox: Any - def open(self, im) -> None: ... - def load(self, im): ... - -class WmfStubImageFile(StubImageFile): - format: str - format_description: str - def load(self, dpi: Any | None = ...) -> None: ... diff --git a/stubs/Pillow/PIL/XVThumbImagePlugin.pyi b/stubs/Pillow/PIL/XVThumbImagePlugin.pyi deleted file mode 100644 index 3d098da18a06..000000000000 --- a/stubs/Pillow/PIL/XVThumbImagePlugin.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .ImageFile import ImageFile - -PALETTE: bytes - -class XVThumbImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/XbmImagePlugin.pyi b/stubs/Pillow/PIL/XbmImagePlugin.pyi deleted file mode 100644 index f8305c04a35a..000000000000 --- a/stubs/Pillow/PIL/XbmImagePlugin.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -xbm_head: Any - -class XbmImageFile(ImageFile): - format: str - format_description: str diff --git a/stubs/Pillow/PIL/XpmImagePlugin.pyi b/stubs/Pillow/PIL/XpmImagePlugin.pyi deleted file mode 100644 index 600a9e0cd67c..000000000000 --- a/stubs/Pillow/PIL/XpmImagePlugin.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from .ImageFile import ImageFile - -xpm_head: Any - -class XpmImageFile(ImageFile): - format: str - format_description: str - def load_read(self, bytes): ... diff --git a/stubs/Pillow/PIL/__init__.pyi b/stubs/Pillow/PIL/__init__.pyi deleted file mode 100644 index 8873f33c3772..000000000000 --- a/stubs/Pillow/PIL/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -__version__: str - -class UnidentifiedImageError(IOError): ... diff --git a/stubs/Pillow/PIL/_binary.pyi b/stubs/Pillow/PIL/_binary.pyi deleted file mode 100644 index 4db3be89e34e..000000000000 --- a/stubs/Pillow/PIL/_binary.pyi +++ /dev/null @@ -1,12 +0,0 @@ -def i8(c): ... -def o8(i): ... -def i16le(c, o: int = ...): ... -def si16le(c, o: int = ...): ... -def i32le(c, o: int = ...): ... -def si32le(c, o: int = ...): ... -def i16be(c, o: int = ...): ... -def i32be(c, o: int = ...): ... -def o16le(i): ... -def o32le(i): ... -def o16be(i): ... -def o32be(i): ... diff --git a/stubs/Pillow/PIL/_imaging.pyi b/stubs/Pillow/PIL/_imaging.pyi deleted file mode 100644 index 44d41cede7cf..000000000000 --- a/stubs/Pillow/PIL/_imaging.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from collections.abc import Sequence -from typing import Any -from typing_extensions import Literal - -DEFAULT_STRATEGY: Literal[0] -FILTERED: Literal[1] -HUFFMAN_ONLY: Literal[2] -RLE: Literal[3] -FIXED: Literal[4] - -class _Path: - def __getattr__(self, item: str) -> Any: ... # incomplete - -def path(__x: Sequence[tuple[float, float]] | Sequence[float]) -> _Path: ... -def __getattr__(__name: str) -> Any: ... # incomplete diff --git a/stubs/Pillow/PIL/_tkinter_finder.pyi b/stubs/Pillow/PIL/_tkinter_finder.pyi deleted file mode 100644 index c2695c0140e1..000000000000 --- a/stubs/Pillow/PIL/_tkinter_finder.pyi +++ /dev/null @@ -1,2 +0,0 @@ -TKINTER_LIB: str -tk_version: str diff --git a/stubs/Pillow/PIL/_util.pyi b/stubs/Pillow/PIL/_util.pyi deleted file mode 100644 index f5faa8c8fdba..000000000000 --- a/stubs/Pillow/PIL/_util.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import NoReturn - -def isPath(f: object) -> bool: ... -def isDirectory(f: object) -> bool: ... - -class deferred_error: - ex: BaseException - def __init__(self, ex: BaseException) -> None: ... - def __getattr__(self, elt: str) -> NoReturn: ... diff --git a/stubs/Pillow/PIL/features.pyi b/stubs/Pillow/PIL/features.pyi deleted file mode 100644 index ff7304c0fca5..000000000000 --- a/stubs/Pillow/PIL/features.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Any - -modules: Any - -def check_module(feature): ... -def version_module(feature): ... -def get_supported_modules(): ... - -codecs: Any - -def check_codec(feature): ... -def version_codec(feature): ... -def get_supported_codecs(): ... - -features: Any - -def check_feature(feature): ... -def version_feature(feature): ... -def get_supported_features(): ... -def check(feature): ... -def version(feature): ... -def get_supported(): ... -def pilinfo(out: Any | None = ..., supported_formats: bool = ...) -> None: ... diff --git a/stubs/PyAutoGUI/@tests/stubtest_allowlist.txt b/stubs/PyAutoGUI/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..a511c3b35f7d --- /dev/null +++ b/stubs/PyAutoGUI/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +pyautogui.__main__ diff --git a/stubs/PyAutoGUI/METADATA.toml b/stubs/PyAutoGUI/METADATA.toml new file mode 100644 index 000000000000..32947c6d216d --- /dev/null +++ b/stubs/PyAutoGUI/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.9.*" +upstream-repository = "https://github.com/asweigart/pyautogui" +dependencies = ["types-PyScreeze"] diff --git a/stubs/PyAutoGUI/pyautogui/__init__.pyi b/stubs/PyAutoGUI/pyautogui/__init__.pyi new file mode 100644 index 000000000000..17ac847943c7 --- /dev/null +++ b/stubs/PyAutoGUI/pyautogui/__init__.pyi @@ -0,0 +1,252 @@ +import contextlib +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Iterable, Sequence +from datetime import datetime +from typing import Final, NamedTuple, ParamSpec, SupportsIndex, SupportsInt, TypeAlias, TypeVar + +from pyscreeze import ( + center as center, + locate as locate, + locateAll as locateAll, + locateAllOnScreen as locateAllOnScreen, + locateCenterOnScreen as locateCenterOnScreen, + locateOnScreen as locateOnScreen, + locateOnWindow as locateOnWindow, + pixel as pixel, + pixelMatchesColor as pixelMatchesColor, + screenshot as screenshot, +) + +_P = ParamSpec("_P") +_R = TypeVar("_R") +# Explicitly mentioning str despite being in the ConvertibleToInt Alias because it has a different meaning (filename on screen) +# Specifying non-None Y arg when X is a string or sequence raises an error +# TODO: This could be better represented through overloads +_NormalizeableXArg: TypeAlias = str | ConvertibleToInt | Sequence[ConvertibleToInt] + +# Constants +KEY_NAMES: list[str] +KEYBOARD_KEYS: list[str] +LEFT: Final = "left" +MIDDLE: Final = "middle" +RIGHT: Final = "right" +PRIMARY: Final = "primary" +SECONDARY: Final = "secondary" +G_LOG_SCREENSHOTS_FILENAMES: list[str] +# Implementation details +QWERTY: Final[str] +QWERTZ: Final[str] +MINIMUM_SLEEP: Final[float] + +# These are meant to be overridable +LOG_SCREENSHOTS: bool +LOG_SCREENSHOTS_LIMIT: int | None +# https://pyautogui.readthedocs.io/en/latest/index.html#fail-safes +FAILSAFE: bool +PAUSE: float +DARWIN_CATCH_UP_TIME: float +FAILSAFE_POINTS: list[tuple[int, int]] +# https://pyautogui.readthedocs.io/en/latest/mouse.htmln#mouse-movement +MINIMUM_DURATION: float + +class PyAutoGUIException(Exception): ... +class FailSafeException(PyAutoGUIException): ... +class ImageNotFoundException(PyAutoGUIException): ... + +def raisePyAutoGUIImageNotFoundException(wrappedFunction: Callable[_P, _R]) -> Callable[_P, _R]: ... +def mouseInfo() -> None: ... +def useImageNotFoundException(value: bool | None = None) -> None: ... +def isShiftCharacter(character: str) -> bool: ... + +class Point(NamedTuple): + x: int + y: int + +class Size(NamedTuple): + width: int + height: int + +def getPointOnLine(x1: float, y1: float, x2: float, y2: float, n: float) -> tuple[float, float]: ... +def linear(n: float) -> float: ... +def position(x: int | None = None, y: int | None = None) -> Point: ... +def size() -> Size: ... + +resolution = size + +def onScreen(x: _NormalizeableXArg | None, y: SupportsInt | None = None) -> bool: ... +def mouseDown( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def mouseUp( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def click( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + clicks: SupportsIndex = 1, + interval: float = 0.0, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def leftClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def rightClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def middleClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def doubleClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "left", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def tripleClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "left", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def scroll( + clicks: float, + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def hscroll( + clicks: float, + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def vscroll( + clicks: float, + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def moveTo( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool = False, + _pause: bool = True, +) -> None: ... +def moveRel( + xOffset: _NormalizeableXArg | None = None, + yOffset: SupportsInt | None = None, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool = False, + _pause: bool = True, +) -> None: ... + +move = moveRel + +def dragTo( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + logScreenshot: bool | None = None, + _pause: bool = True, + mouseDownUp: bool = True, +) -> None: ... +def dragRel( + xOffset: _NormalizeableXArg | None = 0, + yOffset: SupportsInt | None = 0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + logScreenshot: bool | None = None, + _pause: bool = True, + mouseDownUp: bool = True, +) -> None: ... + +drag = dragRel + +def isValidKey(key: str) -> bool: ... +def keyDown(key: str, logScreenshot: bool | None = None, _pause: bool = True) -> None: ... +def keyUp(key: str, logScreenshot: bool | None = None, _pause: bool = True) -> None: ... +def press( + keys: str | Iterable[str], + presses: SupportsIndex = 1, + interval: float = 0.0, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def hold( + keys: str | Iterable[str], logScreenshot: bool | None = None, _pause: bool = True +) -> contextlib._GeneratorContextManager[None]: ... +def typewrite( + message: str | Sequence[str], interval: float = 0.0, logScreenshot: bool | None = None, _pause: bool = True +) -> None: ... + +write = typewrite + +def hotkey(*args: str, logScreenshot: bool | None = None, interval: float = 0.0) -> None: ... + +shortcut = hotkey + +def failSafeCheck() -> None: ... +def displayMousePosition(xOffset: float = 0, yOffset: float = 0) -> None: ... +def sleep(seconds: float) -> None: ... +def countdown(seconds: SupportsIndex) -> None: ... +def run(commandStr: str, _ssCount: Sequence[int] | None = None) -> None: ... +def printInfo(dontPrint: bool = False) -> str: ... +def getInfo() -> tuple[str, str, str, str, Size, datetime]: ... diff --git a/stubs/PyMeeus/METADATA.toml b/stubs/PyMeeus/METADATA.toml new file mode 100644 index 000000000000..f8508a58ef40 --- /dev/null +++ b/stubs/PyMeeus/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.5.*" +upstream-repository = "https://github.com/architest/pymeeus" diff --git a/stubs/PyMeeus/pymeeus/Angle.pyi b/stubs/PyMeeus/pymeeus/Angle.pyi new file mode 100644 index 000000000000..5f65ee04f79b --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Angle.pyi @@ -0,0 +1,100 @@ +from typing import overload +from typing_extensions import Self + +class Angle: + @overload + def __init__(self, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a: Angle, /, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a: float, /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def __init__(self, a: list[float] | tuple[float, ...], /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def __init__(self, a1: float, a2: float, /, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a1: float, a2: float, a3: float, /, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a1: float, a2: float, a3: float, a4: float, /, *, ra: bool = False) -> None: ... + + @staticmethod + def reduce_deg(deg: float | Angle) -> float: ... + @staticmethod + def reduce_dms(degrees: float, minutes: float, seconds: float = 0.0) -> tuple[int, int, float, float]: ... + @staticmethod + def deg2dms(deg: float | Angle) -> tuple[int, int, float, float]: ... + @staticmethod + def dms2deg(degrees: float, minutes: float, seconds: float = 0.0) -> float: ... + def get_tolerance(self) -> float: ... + def set_tolerance(self, tol: float) -> None: ... + def __call__(self) -> float: ... + + @overload + def set(self, *, ra: bool = False) -> None: ... + @overload + def set(self, a: Angle, /, *, ra: bool = False) -> None: ... + @overload + def set(self, a: float, /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def set(self, a: list[float] | tuple[float, ...], /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def set(self, a1: float, a2: float, /, *, ra: bool = False) -> None: ... + @overload + def set(self, a1: float, a2: float, a3: float, /, *, ra: bool = False) -> None: ... + @overload + def set(self, a1: float, a2: float, a3: float, a4: float, /, *, ra: bool = False) -> None: ... + + def set_radians(self, rads: float) -> None: ... + + @overload + def set_ra(self) -> None: ... + @overload + def set_ra(self, a: float | Angle | list[float] | tuple[float, ...], /) -> None: ... + @overload + def set_ra(self, a1: float, a2: float, /) -> None: ... + @overload + def set_ra(self, a1: float, a2: float, a3: float, /) -> None: ... + @overload + def set_ra(self, a1: float, a2: float, a3: float, a4: float, /) -> None: ... + + def dms_str(self, fancy: bool | None = True, n_dec: int = -1) -> str: ... + def get_ra(self) -> float: ... + def ra_str(self, fancy: bool | None = True, n_dec: int = -1) -> str: ... + def rad(self) -> float: ... + def dms_tuple(self) -> tuple[int, int, float, float]: ... + def ra_tuple(self) -> tuple[int, int, float, float]: ... + def to_positive(self) -> Self: ... + def __eq__(self, b: float | Angle) -> bool: ... # type: ignore[override] + def __ne__(self, b: float | Angle) -> bool: ... # type: ignore[override] + def __lt__(self, b: float | Angle) -> bool: ... + def __ge__(self, b: float | Angle) -> bool: ... + def __gt__(self, b: float | Angle) -> bool: ... + def __le__(self, b: float | Angle) -> bool: ... + def __neg__(self) -> Angle: ... + def __abs__(self) -> Angle: ... + def __mod__(self, b: float | Angle) -> Angle: ... + def __add__(self, b: float | Angle) -> Angle: ... + def __sub__(self, b: float | Angle) -> Angle: ... + def __mul__(self, b: float | Angle) -> Angle: ... + def __div__(self, b: float | Angle) -> Angle: ... + def __truediv__(self, b: float | Angle) -> Angle: ... + def __pow__(self, b: float | Angle) -> Angle: ... + def __imod__(self, b: float | Angle) -> Self: ... + def __iadd__(self, b: float | Angle) -> Self: ... + def __isub__(self, b: float | Angle) -> Self: ... + def __imul__(self, b: float | Angle) -> Self: ... + def __idiv__(self, b: float | Angle) -> Angle: ... + def __itruediv__(self, b: float | Angle) -> Self: ... + def __ipow__(self, b: float | Angle) -> Self: ... + def __rmod__(self, b: float | Angle) -> Angle: ... + def __radd__(self, b: float | Angle) -> Angle: ... + def __rsub__(self, b: float | Angle) -> Angle: ... + def __rmul__(self, b: float | Angle) -> Angle: ... + def __rdiv__(self, b: float | Angle) -> Angle: ... + def __rtruediv__(self, b: float | Angle) -> Angle: ... + def __rpow__(self, b: float | Angle) -> Angle: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __round__(self, n: float = 0) -> Angle: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Coordinates.pyi b/stubs/PyMeeus/pymeeus/Coordinates.pyi new file mode 100644 index 000000000000..05814b68c48f --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Coordinates.pyi @@ -0,0 +1,196 @@ +import datetime +from typing import Final, overload + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +NUTATION_ARG_TABLE: Final[list[list[int]]] +NUTATION_SINE_COEF_TABLE: Final[list[list[float]]] +NUTATION_COSINE_COEF_TABLE: Final[list[list[float]]] + +@overload +def mean_obliquity( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def mean_obliquity( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +@overload +def true_obliquity( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def true_obliquity( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +@overload +def nutation_longitude( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def nutation_longitude( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +@overload +def nutation_obliquity( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def nutation_obliquity( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +def precession_equatorial( + start_epoch: Epoch, + final_epoch: Epoch, + start_ra: Angle, + start_dec: Angle, + p_motion_ra: float | Angle = 0.0, + p_motion_dec: float | Angle = 0.0, +) -> tuple[Angle, Angle]: ... +def precession_ecliptical( + start_epoch: Epoch, + final_epoch: Epoch, + start_lon: Angle, + start_lat: Angle, + p_motion_lon: float | Angle = 0.0, + p_motion_lat: float | Angle = 0.0, +) -> tuple[Angle, Angle]: ... +def p_motion_equa2eclip( + p_motion_ra: Angle, p_motion_dec: Angle, ra: Angle, dec: Angle, lat: Angle, epsilon: Angle +) -> tuple[float, float]: ... +def precession_newcomb( + start_epoch: Epoch, + final_epoch: Epoch, + start_ra: Angle, + start_dec: Angle, + p_motion_ra: float | Angle = 0.0, + p_motion_dec: float | Angle = 0.0, +) -> tuple[Angle, Angle]: ... +def motion_in_space( + start_ra: Angle, + start_dec: Angle, + distance: float, + velocity: float, + p_motion_ra: float | Angle, + p_motion_dec: float | Angle, + time: float, +) -> tuple[Angle, Angle]: ... +def equatorial2ecliptical(right_ascension: Angle, declination: Angle, obliquity: Angle) -> tuple[Angle, Angle]: ... +def ecliptical2equatorial(longitude: Angle, latitude: Angle, obliquity: Angle) -> tuple[Angle, Angle]: ... +def equatorial2horizontal(hour_angle: Angle, declination: Angle, geo_latitude: Angle) -> tuple[Angle, Angle]: ... +def horizontal2equatorial(azimuth: Angle, elevation: Angle, geo_latitude: Angle) -> tuple[Angle, Angle]: ... +def equatorial2galactic(right_ascension: Angle, declination: Angle) -> tuple[Angle, Angle]: ... +def galactic2equatorial(longitude: Angle, latitude: Angle) -> tuple[Angle, Angle]: ... +def parallactic_angle(hour_angle: Angle, declination: Angle, geo_latitude: Angle) -> Angle | None: ... +def ecliptic_horizon(local_sidereal_time: Angle, geo_latitude: Angle, obliquity: Angle) -> tuple[Angle, Angle, Angle]: ... +def ecliptic_equator(longitude: Angle, latitude: Angle, obliquity: Angle) -> Angle: ... +def diurnal_path_horizon(declination: Angle, geo_latitude: Angle) -> Angle: ... +def times_rise_transit_set( + longitude: Angle, + latitude: Angle, + alpha1: Angle, + delta1: Angle, + alpha2: Angle, + delta2: Angle, + alpha3: Angle, + delta3: Angle, + h0: Angle, + delta_t: float, + theta0: Angle, +) -> tuple[float, float, float] | tuple[None, None, None]: ... +def refraction_apparent2true(apparent_elevation: Angle, pressure: float = 1010.0, temperature: float = 10.0) -> Angle: ... +def refraction_true2apparent(true_elevation: Angle, pressure: float = 1010.0, temperature: float = 10.0) -> Angle: ... +def angular_separation(alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle) -> Angle: ... +def minimum_angular_separation( + alpha1_1: Angle, + delta1_1: Angle, + alpha1_2: Angle, + delta1_2: Angle, + alpha1_3: Angle, + delta1_3: Angle, + alpha2_1: Angle, + delta2_1: Angle, + alpha2_2: Angle, + delta2_2: Angle, + alpha2_3: Angle, + delta2_3: Angle, +) -> tuple[float, Angle]: ... +def relative_position_angle(alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle) -> Angle: ... +def planetary_conjunction( + alpha1_list: list[Angle] | tuple[Angle, ...], + delta1_list: list[Angle] | tuple[Angle, ...], + alpha2_list: list[Angle] | tuple[Angle, ...], + delta2_list: list[Angle] | tuple[Angle, ...], +) -> tuple[float, Angle]: ... +def planet_star_conjunction( + alpha_list: list[Angle] | tuple[Angle, ...], delta_list: list[Angle] | tuple[Angle, ...], alpha_star: Angle, delta_star: Angle +) -> tuple[float, Angle]: ... +def planet_stars_in_line( + alpha_list: list[Angle] | tuple[Angle, ...], + delta_list: list[Angle] | tuple[Angle, ...], + alpha_star1: Angle, + delta_star1: Angle, + alpha_star2: Angle, + delta_star2: Angle, +) -> float: ... +def straight_line( + alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle, alpha3: Angle, delta3: Angle +) -> tuple[Angle, Angle]: ... +def circle_diameter(alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle, alpha3: Angle, delta3: Angle) -> Angle: ... +def vsop_pos( + epoch: Epoch, vsop_l: list[list[list[float]]], vsop_b: list[list[list[float]]], vsop_r: list[list[list[float]]] +) -> tuple[Angle, Angle, float]: ... +def geometric_vsop_pos( + epoch: Epoch, + vsop_l: list[list[list[float]]], + vsop_b: list[list[list[float]]], + vsop_r: list[list[list[float]]], + tofk5: bool | None = True, +) -> tuple[Angle, Angle, float]: ... +def apparent_vsop_pos( + epoch: Epoch, + vsop_l: list[list[list[float]]], + vsop_b: list[list[list[float]]], + vsop_r: list[list[list[float]]], + nutation: bool | None = True, +) -> tuple[Angle, Angle, float]: ... +def apparent_position(epoch: Epoch, alpha: Angle, delta: Angle, sun_lon: Angle) -> tuple[Angle, Angle]: ... +def orbital_equinox2equinox(epoch0: Epoch, epoch: Epoch, i0: Angle, arg0: Angle, lon0: Angle) -> tuple[Angle, Angle, Angle]: ... +def kepler_equation(eccentricity: float, mean_anomaly: Angle) -> tuple[Angle, Angle]: ... +def orbital_elements( + epoch: Epoch, parameters1: list[list[float]], parameters2: list[list[float]] +) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... +def velocity(r: float, a: float) -> float: ... +def velocity_perihelion(e: float, a: float) -> float: ... +def velocity_aphelion(e: float, a: float) -> float: ... +def length_orbit(e: float, a: float) -> float: ... +def passage_nodes_elliptic(omega: Angle, e: float, a: float, t: Epoch, ascending: bool | None = True) -> tuple[Epoch, float]: ... +def passage_nodes_parabolic(omega: Angle, q: float, t: Epoch, ascending: bool | None = True) -> tuple[Epoch, float]: ... +def phase_angle(sun_dist: float, earth_dist: float, sun_earth_dist: float) -> Angle: ... +def illuminated_fraction(sun_dist: float, earth_dist: float, sun_earth_dist: float) -> float: ... +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/CurveFitting.pyi b/stubs/PyMeeus/pymeeus/CurveFitting.pyi new file mode 100644 index 000000000000..00ba40a02d7f --- /dev/null +++ b/stubs/PyMeeus/pymeeus/CurveFitting.pyi @@ -0,0 +1,45 @@ +from collections.abc import Callable +from typing import overload + +from pymeeus.Angle import Angle + +class CurveFitting: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, a: CurveFitting, /) -> None: ... + @overload + def __init__(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def __init__( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def __init__( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + @overload + def set(self) -> None: ... + @overload + def set(self, a: CurveFitting, /) -> None: ... + @overload + def set(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def set( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def set( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + def __len__(self) -> int: ... + def correlation_coeff(self) -> float: ... + def linear_fitting(self) -> tuple[float, float]: ... + def quadratic_fitting(self) -> tuple[float, float, float]: ... + def general_fitting( + self, f0: Callable[..., float], f1: Callable[..., float] = ..., f2: Callable[..., float] = ... + ) -> tuple[float, float, float]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Earth.pyi b/stubs/PyMeeus/pymeeus/Earth.pyi new file mode 100644 index 000000000000..764b459f3836 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Earth.pyi @@ -0,0 +1,64 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +VSOP87_L_J2000: Final[list[list[list[float]]]] +VSOP87_B_J2000: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Ellipsoid: + def __init__(self, a: float, f: float, omega: float) -> None: ... + def b(self) -> float: ... + def e(self) -> float: ... + +IAU76: Final[Ellipsoid] +WGS84: Final[Ellipsoid] + +class Earth: + def __init__(self, ellipsoid: Ellipsoid = ...) -> None: ... + def set(self, ellipsoid: Ellipsoid) -> None: ... + def rho(self, latitude: float | Angle) -> float: ... + def rho_sinphi(self, latitude: float | Angle, height: float) -> float: ... + def rho_cosphi(self, latitude: float | Angle, height: float) -> float: ... + def rp(self, latitude: float | Angle) -> float: ... + def linear_velocity(self, latitude: float | Angle) -> float: ... + def rm(self, latitude: float | Angle) -> float: ... + def distance( + self, lon1: float | Angle, lat1: float | Angle, lon2: float | Angle, lat2: float | Angle + ) -> tuple[float, float]: ... + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch, nutation: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def geometric_heliocentric_position_j2000(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def parallax_correction( + right_ascension: Angle, declination: Angle, latitude: Angle, distance: float, hour_angle: Angle, height: float = 0.0 + ) -> tuple[Angle, Angle]: ... + @staticmethod + def parallax_ecliptical( + longitude: Angle, + latitude: Angle, + semidiameter: Angle, + obs_lat: Angle, + obliquity: Angle, + sidereal_time: Angle, + distance: float, + height: float = 0.0, + ) -> tuple[Angle, Angle, Angle]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Epoch.pyi b/stubs/PyMeeus/pymeeus/Epoch.pyi new file mode 100644 index 000000000000..22dce2c398dc --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Epoch.pyi @@ -0,0 +1,139 @@ +import datetime +from typing import Final, Literal, overload +from typing_extensions import Self + +from pymeeus.Angle import Angle + +DAY2SEC: Final = 86400.0 +DAY2MIN: Final = 1440.0 +DAY2HOURS: Final = 24.0 +LEAP_TABLE: Final[dict[float, int]] + +class Epoch: + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self, year: int, month: int, day: int, /, *time: float, leap_seconds: float = 0, local: bool = False, utc: bool = False + ) -> None: ... + @overload + def __init__( + self, + a: float | Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, + ) -> None: ... + + def __hash__(self) -> int: ... + + @overload + def set(self) -> None: ... + @overload + def set( + self, year: int, month: int, day: int, /, *time: float, leap_seconds: float = 0, local: bool = False, utc: bool = False + ) -> None: ... + @overload + def set( + self, + a: float | Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, + ) -> None: ... + + @overload + @overload + @staticmethod + def check_input_date( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, + ) -> Epoch: ... + @overload + @staticmethod + def check_input_date( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False + ) -> Epoch: ... + + @staticmethod + def is_julian(year: int, month: int, day: int) -> bool: ... + def julian(self) -> bool: ... + + @overload + @staticmethod + def get_month(month: float | str, as_string: Literal[True]) -> str: ... + @overload + @staticmethod + def get_month(month: float | str, as_string: Literal[False] | None = False) -> int: ... + + @staticmethod + def is_leap(year: float) -> bool: ... + def leap(self) -> bool: ... + @staticmethod + def get_doy(yyyy: int, mm: int, dd: int) -> float: ... + def doy(self) -> float: ... + @staticmethod + def doy2date(year: int, doy: float) -> tuple[int, int, float]: ... + @staticmethod + def leap_seconds(year: int, month: int) -> int: ... + @staticmethod + def get_last_leap_second() -> tuple[int, int, float, int]: ... + @staticmethod + def utc2local() -> float: ... + @staticmethod + def easter(year: float) -> tuple[int, int]: ... + @staticmethod + def jewish_pesach(year: float) -> tuple[int, int]: ... + @staticmethod + def moslem2gregorian(year: float, month: float, day: float) -> tuple[int, int, int]: ... + @staticmethod + def gregorian2moslem(year: float, month: float, day: float) -> tuple[int, int, int]: ... + def get_date(self, *, utc: bool = False, leap_seconds: float = 0.0, local: bool = ...) -> tuple[int, int, float]: ... + def get_full_date( + self, *, utc: bool = False, leap_seconds: float = 0.0, local: bool = ... + ) -> tuple[int, int, int, int, int, float]: ... + @staticmethod + def tt2ut(year: int, month: int) -> float: ... + + @overload + def dow(self, as_string: Literal[True]) -> str: ... + @overload + def dow(self, as_string: Literal[False] | None = False) -> int: ... + + def mean_sidereal_time(self) -> float: ... + def apparent_sidereal_time(self, true_obliquity: float | Angle, nutation_longitude: float | Angle) -> float: ... + def mjd(self) -> float: ... + def jde(self) -> float: ... + def year(self) -> float: ... + def rise_set(self, latitude: Angle, longitude: Angle, altitude: float = 0.0) -> tuple[Epoch, Epoch]: ... + def __call__(self) -> float: ... + def __add__(self, b: float) -> Epoch: ... + + @overload + def __sub__(self, b: float) -> Epoch: ... + @overload + def __sub__(self, b: Epoch) -> float: ... + + def __iadd__(self, b: float) -> Self: ... + def __isub__(self, b: float) -> Self: ... # type: ignore[misc] # __sub__ and __isub__ are incompatible + def __radd__(self, b: float) -> Epoch: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __eq__(self, b: float | Epoch) -> bool: ... # type: ignore[override] + def __ne__(self, b: float | Epoch) -> bool: ... # type: ignore[override] + def __lt__(self, b: float | Epoch) -> bool: ... + def __ge__(self, b: float | Epoch) -> bool: ... + def __gt__(self, b: float | Epoch) -> bool: ... + def __le__(self, b: float | Epoch) -> bool: ... + +JDE2000: Epoch + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Interpolation.pyi b/stubs/PyMeeus/pymeeus/Interpolation.pyi new file mode 100644 index 000000000000..d3e821633d03 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Interpolation.pyi @@ -0,0 +1,44 @@ +from typing import overload + +from pymeeus.Angle import Angle + +class Interpolation: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, a: Interpolation, /) -> None: ... + @overload + def __init__(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def __init__( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def __init__( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + @overload + def set(self) -> None: ... + @overload + def set(self, a: Interpolation, /) -> None: ... + @overload + def set(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def set( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def set( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + def __len__(self) -> int: ... + def get_tolerance(self) -> float: ... + def set_tolerance(self, tol: float) -> None: ... + def __call__(self, x: float | Angle) -> float | Angle: ... + def derivative(self, x: float | Angle) -> float: ... + def root(self, xl: float | Angle = 0, xh: float | Angle = 0, max_iter: int = 1000) -> float | Angle: ... + def minmax(self, xl: float | Angle = 0, xh: float | Angle = 0, max_iter: int = 1000) -> float | Angle: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Jupiter.pyi b/stubs/PyMeeus/pymeeus/Jupiter.pyi new file mode 100644 index 000000000000..8d62086bc09b --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Jupiter.pyi @@ -0,0 +1,38 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Jupiter: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/JupiterMoons.pyi b/stubs/PyMeeus/pymeeus/JupiterMoons.pyi new file mode 100644 index 000000000000..f86ebf994723 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/JupiterMoons.pyi @@ -0,0 +1,83 @@ +from typing import Literal, overload + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +class JupiterMoons: + @staticmethod + def jupiter_system_angles(epoch: Epoch) -> tuple[float, float]: ... + @staticmethod + def rectangular_positions_jovian_equatorial( + epoch: Epoch, tofk5: bool = True, solar: bool = False, do_correction: bool = True + ) -> tuple[ + tuple[float, float, float], tuple[float, float, float], tuple[float, float, float], tuple[float, float, float] + ]: ... + + @overload + @staticmethod + def apparent_rectangular_coordinates( + epoch: Epoch, + X: float, + Y: float, + Z: float, + OMEGA: float, + psi: float, + i: float, + lambda_0: float, + beta_0: float, + D: float = 0, + isFictional: Literal[True] = ..., + ) -> float: ... + @overload + @staticmethod + def apparent_rectangular_coordinates( + epoch: Epoch, + X: float, + Y: float, + Z: float, + OMEGA: float, + psi: float, + i: float, + lambda_0: float, + beta_0: float, + D: float = 0, + isFictional: Literal[False] | None = False, + ) -> tuple[float, float, float]: ... + + @staticmethod + def calculate_delta( + epoch: Epoch, + ) -> tuple[float, float, Angle, Angle, float] | tuple[float, float, Literal[0], Literal[0], Literal[0]]: ... + + @overload + @staticmethod + def correct_rectangular_positions( + R: float, i_sat: int, DELTA: float, X_coordinate: list[float] | tuple[float, float, float] + ) -> tuple[float, float, float]: ... + @overload + @staticmethod + def correct_rectangular_positions( + R: float, i_sat: int, DELTA: float, X_coordinate: float, Y_coordinate: float = 0, Z_coordinate: float = 0 + ) -> tuple[float, float, float]: ... + + @overload + @staticmethod + def check_phenomena(epoch: Epoch, check_all: Literal[True] = True, i_sat: int = 0) -> list[list[float]]: ... + @overload + @staticmethod + def check_phenomena(epoch: Epoch, check_all: Literal[False] | None, i_sat: int = 0) -> tuple[float, float]: ... + + @staticmethod + def is_phenomena(epoch: Epoch) -> list[list[bool]]: ... + @staticmethod + def check_coordinates(X: float, Y: float) -> float: ... + @staticmethod + def check_occultation( + X: float = 0, Y: float = 0, Z: float = 0, epoch: Epoch | None = None, i_sat: int | None = None + ) -> float: ... + @staticmethod + def check_eclipse( + X_0: float = 0, Y_0: float = 0, Z_0: float = 0, epoch: Epoch | None = None, i_sat: int | None = None + ) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Mars.pyi b/stubs/PyMeeus/pymeeus/Mars.pyi new file mode 100644 index 000000000000..083c06a0b54e --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Mars.pyi @@ -0,0 +1,38 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Mars: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, phase_angle: float | Angle) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Mercury.pyi b/stubs/PyMeeus/pymeeus/Mercury.pyi new file mode 100644 index 000000000000..e5b53a02b941 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Mercury.pyi @@ -0,0 +1,42 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Mercury: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def inferior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def superior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def western_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def eastern_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, phase_angle: float | Angle) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Minor.pyi b/stubs/PyMeeus/pymeeus/Minor.pyi new file mode 100644 index 000000000000..54e6d380204d --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Minor.pyi @@ -0,0 +1,10 @@ +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +class Minor: + def __init__(self, q: float, e: float, i: Angle, omega: Angle, w: Angle, t: Epoch) -> None: ... + def set(self, q: float, e: float, i: Angle, omega: Angle, w: Angle, t: Epoch) -> None: ... + def geocentric_position(self, epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + def heliocentric_ecliptical_position(self, epoch: Epoch) -> tuple[Angle, Angle]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Moon.pyi b/stubs/PyMeeus/pymeeus/Moon.pyi new file mode 100644 index 000000000000..2a4ce12ae5f2 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Moon.pyi @@ -0,0 +1,39 @@ +from typing import Final, Literal + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +PERIODIC_TERMS_LR_TABLE: Final[list[list[float]]] +PERIODIC_TERMS_B_TABLE: Final[list[list[float]]] + +class Moon: + @staticmethod + def geocentric_ecliptical_pos(epoch: Epoch) -> tuple[Angle, Angle, float, Angle]: ... + @staticmethod + def apparent_ecliptical_pos(epoch: Epoch) -> tuple[Angle, Angle, float, Angle]: ... + @staticmethod + def apparent_equatorial_pos(epoch: Epoch) -> tuple[Angle, Angle, float, Angle]: ... + @staticmethod + def longitude_mean_ascending_node(epoch: Epoch) -> Angle: ... + @staticmethod + def longitude_true_ascending_node(epoch: Epoch) -> Angle: ... + @staticmethod + def longitude_mean_perigee(epoch: Epoch) -> Angle: ... + @staticmethod + def illuminated_fraction_disk(epoch: Epoch) -> float: ... + @staticmethod + def position_bright_limb(epoch: Epoch) -> Angle: ... + @staticmethod + def moon_phase(epoch: Epoch, target: Literal["new", "first", "full", "last"] = "new") -> Epoch: ... + @staticmethod + def moon_perigee_apogee(epoch: Epoch, target: Literal["perigee", "apogee"] = "perigee") -> tuple[Epoch, Angle]: ... + @staticmethod + def moon_passage_nodes(epoch: Epoch, target: Literal["ascending", "descending"] = "ascending") -> Epoch: ... + @staticmethod + def moon_maximum_declination(epoch: Epoch, target: Literal["northern", "southern"] = "northern") -> tuple[Epoch, Angle]: ... + @staticmethod + def moon_librations(epoch: Epoch) -> tuple[Angle, Angle, Angle, Angle, Angle, Angle]: ... + @staticmethod + def moon_position_angle_axis(epoch: Epoch) -> Angle: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Neptune.pyi b/stubs/PyMeeus/pymeeus/Neptune.pyi new file mode 100644 index 000000000000..3dd5e2a418b2 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Neptune.pyi @@ -0,0 +1,30 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Neptune: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Pluto.pyi b/stubs/PyMeeus/pymeeus/Pluto.pyi new file mode 100644 index 000000000000..bbe9825c81e9 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Pluto.pyi @@ -0,0 +1,17 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +PLUTO_ARGUMENT: Final[list[tuple[float, float, float]]] +PLUTO_LONGITUDE: Final[list[tuple[float, float]]] +PLUTO_LATITUDE: Final[list[tuple[float, float]]] +PLUTO_RADIUS_VECTOR: Final[list[tuple[float, float]]] + +class Pluto: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Saturn.pyi b/stubs/PyMeeus/pymeeus/Saturn.pyi new file mode 100644 index 000000000000..9794c54542e3 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Saturn.pyi @@ -0,0 +1,44 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Saturn: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, delta_U: float | Angle, B: float | Angle) -> float: ... + @staticmethod + def ring_inclination(epoch: Epoch) -> Angle: ... + @staticmethod + def ring_logitude_ascending_node(epoch: Epoch) -> Angle: ... + @staticmethod + def ring_parameters(epoch: Epoch) -> tuple[Angle, Angle, Angle, Angle, float, float]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Sun.pyi b/stubs/PyMeeus/pymeeus/Sun.pyi new file mode 100644 index 000000000000..d2dfb258ff41 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Sun.pyi @@ -0,0 +1,35 @@ +from typing import Literal + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +class Sun: + def __init__(self) -> None: ... + @staticmethod + def true_longitude_coarse(epoch: Epoch) -> tuple[Angle, float]: ... + @staticmethod + def apparent_longitude_coarse(epoch: Epoch) -> tuple[Angle, float]: ... + @staticmethod + def apparent_rightascension_declination_coarse(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def geometric_geocentric_position(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_geocentric_position(epoch: Epoch, nutation: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def rectangular_coordinates_mean_equinox(epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def rectangular_coordinates_j2000(epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def rectangular_coordinates_b1950(epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def rectangular_coordinates_equinox(epoch: Epoch, equinox_epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def get_equinox_solstice(year: int, target: Literal["spring", "summer", "autumn", "winter"] = "spring") -> Epoch: ... + @staticmethod + def equation_of_time(epoch: Epoch) -> tuple[int, float]: ... + @staticmethod + def ephemeris_physical_observations(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def beginning_synodic_rotation(number: int) -> Epoch: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Uranus.pyi b/stubs/PyMeeus/pymeeus/Uranus.pyi new file mode 100644 index 000000000000..ff2f3885f025 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Uranus.pyi @@ -0,0 +1,34 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Uranus: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Venus.pyi b/stubs/PyMeeus/pymeeus/Venus.pyi new file mode 100644 index 000000000000..3fae751f4af6 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Venus.pyi @@ -0,0 +1,44 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Venus: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def inferior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def superior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def western_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def eastern_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def illuminated_fraction(epoch: Epoch) -> float: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, phase_angle: float | Angle) -> float: ... + +def main() -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/__init__.pyi b/stubs/PyMeeus/pymeeus/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/ext/__init__.pyi rename to stubs/PyMeeus/pymeeus/__init__.pyi diff --git a/stubs/PyMeeus/pymeeus/base.pyi b/stubs/PyMeeus/pymeeus/base.pyi new file mode 100644 index 000000000000..e61004af8567 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/base.pyi @@ -0,0 +1,8 @@ +from typing import Final, Literal + +TOL: Final = 1e-10 + +def machine_accuracy() -> tuple[float, int]: ... +def get_ordinal_suffix(ordinal: float) -> Literal["st", "nd", "rd", "th"]: ... +def iint(number: float) -> int: ... +def main() -> None: ... diff --git a/stubs/PyMySQL/@tests/stubtest_allowlist.txt b/stubs/PyMySQL/@tests/stubtest_allowlist.txt index f8fe06591c4e..1fa41b131417 100644 --- a/stubs/PyMySQL/@tests/stubtest_allowlist.txt +++ b/stubs/PyMySQL/@tests/stubtest_allowlist.txt @@ -1,12 +1,7 @@ -pymysql.connections.byte2int -pymysql.connections.int2byte -pymysql.connections.lenenc_int -pymysql.connections.pack_int24 -pymysql.cursors.Cursor.__del__ # DictCursorMixin changes method types of inherited classes, but doesn't contain much at runtime pymysql.cursors.DictCursorMixin.__iter__ pymysql.cursors.DictCursorMixin.fetch[a-z]* -pymysql.escape_dict -pymysql.escape_sequence -pymysql.escape_string -pymysql.util + +# Placeholder strings kept only for aiomysql compatibility, scheduled for removal in 1.3.0 +pymysql.converters.escape_bytes_prefixed +pymysql.converters.escape_dict diff --git a/stubs/PyMySQL/@tests/test_cases/check_connection.py b/stubs/PyMySQL/@tests/test_cases/check_connection.py new file mode 100644 index 000000000000..24d42664e3c7 --- /dev/null +++ b/stubs/PyMySQL/@tests/test_cases/check_connection.py @@ -0,0 +1,15 @@ +from typing_extensions import assert_type + +from pymysql.connections import Connection +from pymysql.cursors import Cursor + + +class MyCursor(Cursor): + pass + + +assert_type(Connection(), Connection[Cursor]) +assert_type(Connection(cursorclass=Cursor), Connection[Cursor]) +assert_type(Connection(cursorclass=MyCursor), Connection[MyCursor]) + +Connection(cursorclass=None) # type: ignore diff --git a/stubs/PyMySQL/METADATA.toml b/stubs/PyMySQL/METADATA.toml index f3e83f9c456b..b5cd7fc2bafb 100644 --- a/stubs/PyMySQL/METADATA.toml +++ b/stubs/PyMySQL/METADATA.toml @@ -1 +1,2 @@ -version = "1.0.*" +version = "1.2.*" +upstream-repository = "https://github.com/PyMySQL/PyMySQL" diff --git a/stubs/PyMySQL/pymysql/__init__.pyi b/stubs/PyMySQL/pymysql/__init__.pyi index 6babdc3fb4e5..5d4a4a3e2465 100644 --- a/stubs/PyMySQL/pymysql/__init__.pyi +++ b/stubs/PyMySQL/pymysql/__init__.pyi @@ -1,9 +1,9 @@ -import sys -from typing import FrozenSet +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Final, SupportsBytes, SupportsIndex -from .connections import Connection as Connection +from . import connections as connections, constants as constants, converters as converters, cursors as cursors from .constants import FIELD_TYPE as FIELD_TYPE -from .converters import escape_dict as escape_dict, escape_sequence as escape_sequence, escape_string as escape_string from .err import ( DatabaseError as DatabaseError, DataError as DataError, @@ -26,13 +26,21 @@ from .times import ( TimestampFromTicks as TimestampFromTicks, ) +VERSION: Final[tuple[str | int, ...]] +VERSION_STRING: Final[str] +version_info: tuple[int, int, int, str, int] +__version__: str + +def get_client_info() -> str: ... +def install_as_MySQLdb() -> None: ... + threadsafety: int apilevel: str paramstyle: str -class DBAPISet(FrozenSet[int]): - def __ne__(self, other) -> bool: ... - def __eq__(self, other) -> bool: ... +class DBAPISet(frozenset[int]): + def __ne__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... STRING: DBAPISet @@ -44,21 +52,56 @@ TIMESTAMP: DBAPISet DATETIME: DBAPISet ROWID: DBAPISet -if sys.version_info >= (3, 0): - def Binary(x) -> bytes: ... - -else: - def Binary(x) -> bytearray: ... - -def get_client_info() -> str: ... +def Binary(x: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer) -> bytes: ... +def thread_safe() -> bool: ... -__version__: str -version_info: tuple[int, int, int, str, int] NULL: str -# pymysql/__init__.py says "Connect = connect = Connection = connections.Connection" -Connect = Connection -connect = Connection +Connect = connections.Connection +connect = connections.Connection +Connection = connections.Connection -def thread_safe() -> bool: ... -def install_as_MySQLdb() -> None: ... +__all__ = [ + "BINARY", + "Binary", + "Connect", + "Connection", + "DATE", + "Date", + "Time", + "Timestamp", + "DateFromTicks", + "TimeFromTicks", + "TimestampFromTicks", + "DataError", + "DatabaseError", + "Error", + "FIELD_TYPE", + "IntegrityError", + "InterfaceError", + "InternalError", + "MySQLError", + "NULL", + "NUMBER", + "NotSupportedError", + "DBAPISet", + "OperationalError", + "ProgrammingError", + "ROWID", + "STRING", + "TIME", + "TIMESTAMP", + "Warning", + "apilevel", + "connect", + "connections", + "constants", + "converters", + "cursors", + "get_client_info", + "paramstyle", + "threadsafety", + "version_info", + "install_as_MySQLdb", + "__version__", +] diff --git a/stubs/PyMySQL/pymysql/_auth.pyi b/stubs/PyMySQL/pymysql/_auth.pyi new file mode 100644 index 000000000000..d8fe1ba35864 --- /dev/null +++ b/stubs/PyMySQL/pymysql/_auth.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete, ReadableBuffer +from typing import Final + +DEBUG: Final[bool] +SCRAMBLE_LENGTH: Final[int] +sha1_new: Incomplete + +def scramble_native_password(password: ReadableBuffer | None, message: ReadableBuffer | None) -> bytes: ... +def ed25519_password(password: ReadableBuffer, scramble: ReadableBuffer) -> bytes: ... +def sha2_rsa_encrypt(password: bytes, salt: bytes, public_key: bytes) -> bytes: ... +def sha256_password_auth(conn, pkt): ... +def scramble_caching_sha2(password: ReadableBuffer, nonce: ReadableBuffer) -> bytes: ... +def caching_sha2_password_auth(conn, pkt) -> Incomplete | None: ... diff --git a/stubs/PyMySQL/pymysql/charset.pyi b/stubs/PyMySQL/pymysql/charset.pyi index c47679a78b2b..5dce19cce0c1 100644 --- a/stubs/PyMySQL/pymysql/charset.pyi +++ b/stubs/PyMySQL/pymysql/charset.pyi @@ -1,16 +1,22 @@ -from typing import Any +from collections.abc import Callable +from typing import Final -MBLENGTH: Any +MBLENGTH: Final[dict[int, int]] class Charset: - is_default: Any - def __init__(self, id, name, collation, is_default): ... + is_default: bool + def __init__(self, id: int, name: str, collation: str, is_default: bool = False) -> None: ... + @property + def encoding(self) -> str: ... + @property + def is_binary(self) -> bool: ... class Charsets: - def __init__(self): ... - def add(self, c): ... - def by_id(self, id): ... - def by_name(self, name): ... + def __init__(self) -> None: ... + def add(self, c: Charset) -> None: ... + def by_id(self, id: int) -> Charset: ... + def by_name(self, name: str) -> Charset: ... -def charset_by_name(name): ... -def charset_by_id(id): ... +_charsets: Charsets +charset_by_name: Callable[[str], Charset] +charset_by_id: Callable[[int], Charset] diff --git a/stubs/PyMySQL/pymysql/connections.pyi b/stubs/PyMySQL/pymysql/connections.pyi index f30e0366167a..7d03d41f4b25 100644 --- a/stubs/PyMySQL/pymysql/connections.pyi +++ b/stubs/PyMySQL/pymysql/connections.pyi @@ -1,229 +1,276 @@ -from socket import socket as _socket -from typing import Any, AnyStr, Generic, Mapping, Tuple, Type, TypeVar, overload +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from socket import _Address, socket as _socket +from ssl import SSLContext, _PasswordType +from typing import Any, Generic, Literal, overload +from typing_extensions import Self, TypeVar, deprecated from .charset import charset_by_id as charset_by_id, charset_by_name as charset_by_name from .constants import CLIENT as CLIENT, COMMAND as COMMAND, FIELD_TYPE as FIELD_TYPE, SERVER_STATUS as SERVER_STATUS +from .converters import _EscaperMapping from .cursors import Cursor -from .util import byte2int as byte2int, int2byte as int2byte +from .err import ( + DatabaseError, + DataError, + Error, + IntegrityError, + InterfaceError, + InternalError, + NotSupportedError, + OperationalError, + ProgrammingError, + Warning, +) -SSL_ENABLED: Any -DEFAULT_USER: Any -DEBUG: Any -DEFAULT_CHARSET: Any - -_C = TypeVar("_C", bound=Cursor) +_C = TypeVar("_C", bound=Cursor, default=Cursor) _C2 = TypeVar("_C2", bound=Cursor) -def dump_packet(data): ... -def pack_int24(n): ... -def lenenc_int(i: int) -> bytes: ... - -class MysqlPacket: - connection: Any - def __init__(self, data, encoding): ... - def get_all_data(self): ... - def read(self, size): ... - def read_all(self): ... - def advance(self, length): ... - def rewind(self, position: int = ...): ... - def get_bytes(self, position, length: int = ...): ... - def read_string(self) -> bytes: ... - def read_uint8(self) -> Any: ... - def read_uint16(self) -> Any: ... - def read_uint24(self) -> Any: ... - def read_uint32(self) -> Any: ... - def read_uint64(self) -> Any: ... - def read_length_encoded_integer(self) -> int: ... - def read_length_coded_string(self) -> bytes: ... - def read_struct(self, fmt: str) -> Tuple[Any, ...]: ... - def is_ok_packet(self) -> bool: ... - def is_eof_packet(self) -> bool: ... - def is_auth_switch_request(self) -> bool: ... - def is_extra_auth_data(self) -> bool: ... - def is_resultset_packet(self) -> bool: ... - def is_load_local_packet(self) -> bool: ... - def is_error_packet(self) -> bool: ... - def check_error(self): ... - def raise_for_error(self) -> None: ... - def dump(self): ... +SSL_ENABLED: bool +DEFAULT_USER: str | None +DEBUG: bool +DEFAULT_CHARSET: str +TEXT_TYPES: set[int] +MAX_PACKET_LEN: int -class FieldDescriptorPacket(MysqlPacket): - def __init__(self, data, encoding): ... - def description(self): ... - def get_column_length(self): ... +def dump_packet(data): ... +def _lenenc_int(i: int) -> bytes: ... class Connection(Generic[_C]): - ssl: Any - host: Any - port: Any - user: Any - password: Any - db: Any - unix_socket: Any - bind_address: Any - charset: Any - use_unicode: Any - client_flag: Any - cursorclass: Any - connect_timeout: Any - messages: Any - encoders: Any - decoders: Any - host_info: Any - sql_mode: Any - init_command: Any + ssl: bool + host: str + port: int + user: str | bytes | None + password: bytes + db: str | bytes | None + unix_socket: _Address | None + charset: str + collation: str | None + bind_address: str | None + use_unicode: bool + client_flag: int + cursorclass: type[_C] + connect_timeout: float | None + host_info: str + sql_mode: str | None + init_command: str | None max_allowed_packet: int - server_public_key: bytes + server_public_key: bytes | None + encoding: str + autocommit_mode: bool | None + encoders: dict[type[Any], Callable[[Any], str]] # argument type depends on the key + decoders: dict[int, Callable[[str], Any]] # return type depends on the key + + @overload + def __init__( + self, + *, + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: SSLContext | None = None, # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: None = None, # deprecated + db: None = None, # deprecated + ) -> None: ... @overload + @deprecated("Passing a dict for 'ssl' parameter is deprecated. Use 'ssl_*' parameters or 'ssl.SSLContext' instead.") def __init__( - self: Connection[Cursor], # different between overloads + self, *, - host: str | None = ..., - user: Any | None = ..., - password: str = ..., - database: Any | None = ..., - port: int = ..., - unix_socket: Any | None = ..., - charset: str = ..., - sql_mode: Any | None = ..., - read_default_file: Any | None = ..., - conv=..., - use_unicode: bool | None = ..., - client_flag: int = ..., - cursorclass: None = ..., # different between overloads - init_command: Any | None = ..., - connect_timeout: int | None = ..., - ssl: Mapping[Any, Any] | None = ..., - ssl_ca=..., - ssl_cert=..., - ssl_disabled=..., - ssl_key=..., - ssl_verify_cert=..., - ssl_verify_identity=..., - read_default_group: Any | None = ..., - compress: Any | None = ..., - named_pipe: Any | None = ..., - autocommit: bool | None = ..., - db: Any | None = ..., - passwd: Any | None = ..., - local_infile: Any | None = ..., - max_allowed_packet: int = ..., - defer_connect: bool | None = ..., - auth_plugin_map: Mapping[Any, Any] | None = ..., - read_timeout: float | None = ..., - write_timeout: float | None = ..., - bind_address: Any | None = ..., - binary_prefix: bool | None = ..., - program_name: Any | None = ..., - server_public_key: bytes | None = ..., - ): ... + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: dict[str, Incomplete], # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: str | bytes | None = None, # deprecated + db: str | bytes | None = None, # deprecated + ) -> None: ... @overload + @deprecated("'passwd' and 'db' arguments are deprecated. Use 'password' and 'database' instead.") def __init__( - self: Connection[_C], # different between overloads + self, *, - host: str | None = ..., - user: Any | None = ..., - password: str = ..., - database: Any | None = ..., - port: int = ..., - unix_socket: Any | None = ..., - charset: str = ..., - sql_mode: Any | None = ..., - read_default_file: Any | None = ..., - conv=..., - use_unicode: bool | None = ..., - client_flag: int = ..., - cursorclass: Type[_C] = ..., # different between overloads - init_command: Any | None = ..., - connect_timeout: int | None = ..., - ssl: Mapping[Any, Any] | None = ..., - ssl_ca=..., - ssl_cert=..., - ssl_disabled=..., - ssl_key=..., - ssl_verify_cert=..., - ssl_verify_identity=..., - read_default_group: Any | None = ..., - compress: Any | None = ..., - named_pipe: Any | None = ..., - autocommit: bool | None = ..., - db: Any | None = ..., - passwd: Any | None = ..., - local_infile: Any | None = ..., - max_allowed_packet: int = ..., - defer_connect: bool | None = ..., - auth_plugin_map: Mapping[Any, Any] | None = ..., - read_timeout: float | None = ..., - write_timeout: float | None = ..., - bind_address: Any | None = ..., - binary_prefix: bool | None = ..., - program_name: Any | None = ..., - server_public_key: bytes | None = ..., - ): ... - socket: Any - rfile: Any - wfile: Any + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: dict[str, Incomplete] | SSLContext | None = None, # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: str | bytes | None = None, # deprecated + db: str | bytes | None = None, # deprecated + ) -> None: ... + def close(self) -> None: ... @property def open(self) -> bool: ... + def __del__(self) -> None: ... def autocommit(self, value) -> None: ... def get_autocommit(self) -> bool: ... def commit(self) -> None: ... def begin(self) -> None: ... def rollback(self) -> None: ... def select_db(self, db) -> None: ... - def escape(self, obj, mapping: Mapping[Any, Any] | None = ...): ... - def literal(self, obj): ... - def escape_string(self, s: AnyStr) -> AnyStr: ... + def escape(self, obj: object, mapping: _EscaperMapping = None) -> str: ... + @deprecated("literal() is deprecated and will be removed in the next version.") + def literal(self, obj: object) -> str: ... + @overload - def cursor(self, cursor: None = ...) -> _C: ... + def cursor(self, cursor: None = None) -> _C: ... @overload - def cursor(self, cursor: Type[_C2]) -> _C2: ... - def query(self, sql, unbuffered: bool = ...) -> int: ... - def next_result(self, unbuffered: bool = ...) -> int: ... + def cursor(self, cursor: type[_C2]) -> _C2: ... + + def query(self, sql, unbuffered: bool = False) -> int: ... + def next_result(self, unbuffered: bool = False) -> int: ... def affected_rows(self): ... def kill(self, thread_id): ... - def ping(self, reconnect: bool = ...) -> None: ... - def set_charset(self, charset) -> None: ... - def connect(self, sock: _socket | None = ...) -> None: ... + + @overload + def ping(self, reconnect: Literal[False] | None = False) -> None: ... + @overload + @deprecated("The 'reconnect' parameter is deprecated. Create a new connection if you want to reconnect.") + def ping(self, reconnect: Literal[True]) -> None: ... + + @deprecated("Method is deprecated. Use 'set_character_set()' instead.") + def set_charset(self, charset: str) -> None: ... + def set_character_set(self, charset: str, collation: str | None = None) -> None: ... + def connect(self, sock: _socket | None = None) -> None: ... def write_packet(self, payload) -> None: ... def _read_packet(self, packet_type=...): ... def insert_id(self): ... def thread_id(self): ... def character_set_name(self): ... - def get_host_info(self): ... + def get_host_info(self) -> str: ... def get_proto_info(self): ... def get_server_info(self): ... def show_warnings(self): ... - Warning: Any - Error: Any - InterfaceError: Any - DatabaseError: Any - DataError: Any - OperationalError: Any - IntegrityError: Any - InternalError: Any - ProgrammingError: Any - NotSupportedError: Any + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: object) -> None: ... + Warning: type[Warning] + Error: type[Error] + InterfaceError: type[InterfaceError] + DatabaseError: type[DatabaseError] + DataError: type[DataError] + OperationalError: type[OperationalError] + IntegrityError: type[IntegrityError] + InternalError: type[InternalError] + ProgrammingError: type[ProgrammingError] + NotSupportedError: type[NotSupportedError] class MySQLResult: - connection: Any - affected_rows: Any - insert_id: Any - server_status: Any - warning_count: Any - message: Any - field_count: Any - description: Any - rows: Any - has_next: Any + connection: Connection[Any] | None + affected_rows: int | None + insert_id: int | None + server_status: int | None + warning_count: int + message: str | None + field_count: int + description: Incomplete + rows: Incomplete + has_next: bool | None + unbuffered_active: bool def __init__(self, connection: Connection[Any]) -> None: ... - first_packet: Any + def __del__(self) -> None: ... + first_packet: Incomplete def read(self) -> None: ... def init_unbuffered_query(self) -> None: ... - -class LoadLocalFile: - filename: Any - connection: Connection[Any] - def __init__(self, filename: Any, connection: Connection[Any]) -> None: ... - def send_data(self) -> None: ... diff --git a/stubs/PyMySQL/pymysql/constants/CLIENT.pyi b/stubs/PyMySQL/pymysql/constants/CLIENT.pyi index ac8fb5514233..4a1f58c48273 100644 --- a/stubs/PyMySQL/pymysql/constants/CLIENT.pyi +++ b/stubs/PyMySQL/pymysql/constants/CLIENT.pyi @@ -1,18 +1,27 @@ -LONG_PASSWORD: int -FOUND_ROWS: int -LONG_FLAG: int -CONNECT_WITH_DB: int -NO_SCHEMA: int -COMPRESS: int -ODBC: int -LOCAL_FILES: int -IGNORE_SPACE: int -PROTOCOL_41: int -INTERACTIVE: int -SSL: int -IGNORE_SIGPIPE: int -TRANSACTIONS: int -SECURE_CONNECTION: int -MULTI_STATEMENTS: int -MULTI_RESULTS: int -CAPABILITIES: int +from typing import Final + +LONG_PASSWORD: Final[int] +FOUND_ROWS: Final[int] +LONG_FLAG: Final[int] +CONNECT_WITH_DB: Final[int] +NO_SCHEMA: Final[int] +COMPRESS: Final[int] +ODBC: Final[int] +LOCAL_FILES: Final[int] +IGNORE_SPACE: Final[int] +PROTOCOL_41: Final[int] +INTERACTIVE: Final[int] +SSL: Final[int] +IGNORE_SIGPIPE: Final[int] +TRANSACTIONS: Final[int] +SECURE_CONNECTION: Final[int] +MULTI_STATEMENTS: Final[int] +MULTI_RESULTS: Final[int] +PS_MULTI_RESULTS: Final[int] +PLUGIN_AUTH: Final[int] +CONNECT_ATTRS: Final[int] +PLUGIN_AUTH_LENENC_CLIENT_DATA: Final[int] +CAPABILITIES: Final[int] +HANDLE_EXPIRED_PASSWORDS: Final[int] +SESSION_TRACK: Final[int] +DEPRECATE_EOF: Final[int] diff --git a/stubs/PyMySQL/pymysql/constants/COMMAND.pyi b/stubs/PyMySQL/pymysql/constants/COMMAND.pyi index 1163e6b4b6fe..bc3f24fb81f3 100644 --- a/stubs/PyMySQL/pymysql/constants/COMMAND.pyi +++ b/stubs/PyMySQL/pymysql/constants/COMMAND.pyi @@ -1,22 +1,34 @@ -COM_SLEEP: int -COM_QUIT: int -COM_INIT_DB: int -COM_QUERY: int -COM_FIELD_LIST: int -COM_CREATE_DB: int -COM_DROP_DB: int -COM_REFRESH: int -COM_SHUTDOWN: int -COM_STATISTICS: int -COM_PROCESS_INFO: int -COM_CONNECT: int -COM_PROCESS_KILL: int -COM_DEBUG: int -COM_PING: int -COM_TIME: int -COM_DELAYED_INSERT: int -COM_CHANGE_USER: int -COM_BINLOG_DUMP: int -COM_TABLE_DUMP: int -COM_CONNECT_OUT: int -COM_REGISTER_SLAVE: int +from typing import Final + +COM_SLEEP: Final[int] +COM_QUIT: Final[int] +COM_INIT_DB: Final[int] +COM_QUERY: Final[int] +COM_FIELD_LIST: Final[int] +COM_CREATE_DB: Final[int] +COM_DROP_DB: Final[int] +COM_REFRESH: Final[int] +COM_SHUTDOWN: Final[int] +COM_STATISTICS: Final[int] +COM_PROCESS_INFO: Final[int] +COM_CONNECT: Final[int] +COM_PROCESS_KILL: Final[int] +COM_DEBUG: Final[int] +COM_PING: Final[int] +COM_TIME: Final[int] +COM_DELAYED_INSERT: Final[int] +COM_CHANGE_USER: Final[int] +COM_BINLOG_DUMP: Final[int] +COM_TABLE_DUMP: Final[int] +COM_CONNECT_OUT: Final[int] +COM_REGISTER_SLAVE: Final[int] +COM_STMT_PREPARE: Final[int] +COM_STMT_EXECUTE: Final[int] +COM_STMT_SEND_LONG_DATA: Final[int] +COM_STMT_CLOSE: Final[int] +COM_STMT_RESET: Final[int] +COM_SET_OPTION: Final[int] +COM_STMT_FETCH: Final[int] +COM_DAEMON: Final[int] +COM_BINLOG_DUMP_GTID: Final[int] +COM_END: Final[int] diff --git a/stubs/PyMySQL/pymysql/constants/CR.pyi b/stubs/PyMySQL/pymysql/constants/CR.pyi new file mode 100644 index 000000000000..5b6447f64390 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/CR.pyi @@ -0,0 +1,77 @@ +from typing import Final + +CR_ERROR_FIRST: Final = 2000 +CR_UNKNOWN_ERROR: Final = 2000 +CR_SOCKET_CREATE_ERROR: Final = 2001 +CR_CONNECTION_ERROR: Final = 2002 +CR_CONN_HOST_ERROR: Final = 2003 +CR_IPSOCK_ERROR: Final = 2004 +CR_UNKNOWN_HOST: Final = 2005 +CR_SERVER_GONE_ERROR: Final = 2006 +CR_VERSION_ERROR: Final = 2007 +CR_OUT_OF_MEMORY: Final = 2008 +CR_WRONG_HOST_INFO: Final = 2009 +CR_LOCALHOST_CONNECTION: Final = 2010 +CR_TCP_CONNECTION: Final = 2011 +CR_SERVER_HANDSHAKE_ERR: Final = 2012 +CR_SERVER_LOST: Final = 2013 +CR_COMMANDS_OUT_OF_SYNC: Final = 2014 +CR_NAMEDPIPE_CONNECTION: Final = 2015 +CR_NAMEDPIPEWAIT_ERROR: Final = 2016 +CR_NAMEDPIPEOPEN_ERROR: Final = 2017 +CR_NAMEDPIPESETSTATE_ERROR: Final = 2018 +CR_CANT_READ_CHARSET: Final = 2019 +CR_NET_PACKET_TOO_LARGE: Final = 2020 +CR_EMBEDDED_CONNECTION: Final = 2021 +CR_PROBE_SLAVE_STATUS: Final = 2022 +CR_PROBE_SLAVE_HOSTS: Final = 2023 +CR_PROBE_SLAVE_CONNECT: Final = 2024 +CR_PROBE_MASTER_CONNECT: Final = 2025 +CR_SSL_CONNECTION_ERROR: Final = 2026 +CR_MALFORMED_PACKET: Final = 2027 +CR_WRONG_LICENSE: Final = 2028 +CR_NULL_POINTER: Final = 2029 +CR_NO_PREPARE_STMT: Final = 2030 +CR_PARAMS_NOT_BOUND: Final = 2031 +CR_DATA_TRUNCATED: Final = 2032 +CR_NO_PARAMETERS_EXISTS: Final = 2033 +CR_INVALID_PARAMETER_NO: Final = 2034 +CR_INVALID_BUFFER_USE: Final = 2035 +CR_UNSUPPORTED_PARAM_TYPE: Final = 2036 +CR_SHARED_MEMORY_CONNECTION: Final = 2037 +CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR: Final = 2038 +CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR: Final = 2039 +CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR: Final = 2040 +CR_SHARED_MEMORY_CONNECT_MAP_ERROR: Final = 2041 +CR_SHARED_MEMORY_FILE_MAP_ERROR: Final = 2042 +CR_SHARED_MEMORY_MAP_ERROR: Final = 2043 +CR_SHARED_MEMORY_EVENT_ERROR: Final = 2044 +CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR: Final = 2045 +CR_SHARED_MEMORY_CONNECT_SET_ERROR: Final = 2046 +CR_CONN_UNKNOW_PROTOCOL: Final = 2047 +CR_INVALID_CONN_HANDLE: Final = 2048 +CR_SECURE_AUTH: Final = 2049 +CR_FETCH_CANCELED: Final = 2050 +CR_NO_DATA: Final = 2051 +CR_NO_STMT_METADATA: Final = 2052 +CR_NO_RESULT_SET: Final = 2053 +CR_NOT_IMPLEMENTED: Final = 2054 +CR_SERVER_LOST_EXTENDED: Final = 2055 +CR_STMT_CLOSED: Final = 2056 +CR_NEW_STMT_METADATA: Final = 2057 +CR_ALREADY_CONNECTED: Final = 2058 +CR_AUTH_PLUGIN_CANNOT_LOAD: Final = 2059 +CR_DUPLICATE_CONNECTION_ATTR: Final = 2060 +CR_AUTH_PLUGIN_ERR: Final = 2061 +CR_INSECURE_API_ERR: Final = 2062 +CR_FILE_NAME_TOO_LONG: Final = 2063 +CR_SSL_FIPS_MODE_ERR: Final = 2064 +CR_DEPRECATED_COMPRESSION_NOT_SUPPORTED: Final = 2065 +CR_COMPRESSION_WRONGLY_CONFIGURED: Final = 2066 +CR_KERBEROS_USER_NOT_FOUND: Final = 2067 +CR_LOAD_DATA_LOCAL_INFILE_REJECTED: Final = 2068 +CR_LOAD_DATA_LOCAL_INFILE_REALPATH_FAIL: Final = 2069 +CR_DNS_SRV_LOOKUP_FAILED: Final = 2070 +CR_MANDATORY_TRACKER_NOT_FOUND: Final = 2071 +CR_INVALID_FACTOR_NO: Final = 2072 +CR_ERROR_LAST: Final = 2072 diff --git a/stubs/PyMySQL/pymysql/constants/ER.pyi b/stubs/PyMySQL/pymysql/constants/ER.pyi index 5f0a432ee5ed..8bd5e9b79e14 100644 --- a/stubs/PyMySQL/pymysql/constants/ER.pyi +++ b/stubs/PyMySQL/pymysql/constants/ER.pyi @@ -1,471 +1,476 @@ -ERROR_FIRST: int -HASHCHK: int -NISAMCHK: int -NO: int -YES: int -CANT_CREATE_FILE: int -CANT_CREATE_TABLE: int -CANT_CREATE_DB: int -DB_CREATE_EXISTS: int -DB_DROP_EXISTS: int -DB_DROP_DELETE: int -DB_DROP_RMDIR: int -CANT_DELETE_FILE: int -CANT_FIND_SYSTEM_REC: int -CANT_GET_STAT: int -CANT_GET_WD: int -CANT_LOCK: int -CANT_OPEN_FILE: int -FILE_NOT_FOUND: int -CANT_READ_DIR: int -CANT_SET_WD: int -CHECKREAD: int -DISK_FULL: int -DUP_KEY: int -ERROR_ON_CLOSE: int -ERROR_ON_READ: int -ERROR_ON_RENAME: int -ERROR_ON_WRITE: int -FILE_USED: int -FILSORT_ABORT: int -FORM_NOT_FOUND: int -GET_ERRNO: int -ILLEGAL_HA: int -KEY_NOT_FOUND: int -NOT_FORM_FILE: int -NOT_KEYFILE: int -OLD_KEYFILE: int -OPEN_AS_READONLY: int -OUTOFMEMORY: int -OUT_OF_SORTMEMORY: int -UNEXPECTED_EOF: int -CON_COUNT_ERROR: int -OUT_OF_RESOURCES: int -BAD_HOST_ERROR: int -HANDSHAKE_ERROR: int -DBACCESS_DENIED_ERROR: int -ACCESS_DENIED_ERROR: int -NO_DB_ERROR: int -UNKNOWN_COM_ERROR: int -BAD_NULL_ERROR: int -BAD_DB_ERROR: int -TABLE_EXISTS_ERROR: int -BAD_TABLE_ERROR: int -NON_UNIQ_ERROR: int -SERVER_SHUTDOWN: int -BAD_FIELD_ERROR: int -WRONG_FIELD_WITH_GROUP: int -WRONG_GROUP_FIELD: int -WRONG_SUM_SELECT: int -WRONG_VALUE_COUNT: int -TOO_LONG_IDENT: int -DUP_FIELDNAME: int -DUP_KEYNAME: int -DUP_ENTRY: int -WRONG_FIELD_SPEC: int -PARSE_ERROR: int -EMPTY_QUERY: int -NONUNIQ_TABLE: int -INVALID_DEFAULT: int -MULTIPLE_PRI_KEY: int -TOO_MANY_KEYS: int -TOO_MANY_KEY_PARTS: int -TOO_LONG_KEY: int -KEY_COLUMN_DOES_NOT_EXITS: int -BLOB_USED_AS_KEY: int -TOO_BIG_FIELDLENGTH: int -WRONG_AUTO_KEY: int -READY: int -NORMAL_SHUTDOWN: int -GOT_SIGNAL: int -SHUTDOWN_COMPLETE: int -FORCING_CLOSE: int -IPSOCK_ERROR: int -NO_SUCH_INDEX: int -WRONG_FIELD_TERMINATORS: int -BLOBS_AND_NO_TERMINATED: int -TEXTFILE_NOT_READABLE: int -FILE_EXISTS_ERROR: int -LOAD_INFO: int -ALTER_INFO: int -WRONG_SUB_KEY: int -CANT_REMOVE_ALL_FIELDS: int -CANT_DROP_FIELD_OR_KEY: int -INSERT_INFO: int -UPDATE_TABLE_USED: int -NO_SUCH_THREAD: int -KILL_DENIED_ERROR: int -NO_TABLES_USED: int -TOO_BIG_SET: int -NO_UNIQUE_LOGFILE: int -TABLE_NOT_LOCKED_FOR_WRITE: int -TABLE_NOT_LOCKED: int -BLOB_CANT_HAVE_DEFAULT: int -WRONG_DB_NAME: int -WRONG_TABLE_NAME: int -TOO_BIG_SELECT: int -UNKNOWN_ERROR: int -UNKNOWN_PROCEDURE: int -WRONG_PARAMCOUNT_TO_PROCEDURE: int -WRONG_PARAMETERS_TO_PROCEDURE: int -UNKNOWN_TABLE: int -FIELD_SPECIFIED_TWICE: int -INVALID_GROUP_FUNC_USE: int -UNSUPPORTED_EXTENSION: int -TABLE_MUST_HAVE_COLUMNS: int -RECORD_FILE_FULL: int -UNKNOWN_CHARACTER_SET: int -TOO_MANY_TABLES: int -TOO_MANY_FIELDS: int -TOO_BIG_ROWSIZE: int -STACK_OVERRUN: int -WRONG_OUTER_JOIN: int -NULL_COLUMN_IN_INDEX: int -CANT_FIND_UDF: int -CANT_INITIALIZE_UDF: int -UDF_NO_PATHS: int -UDF_EXISTS: int -CANT_OPEN_LIBRARY: int -CANT_FIND_DL_ENTRY: int -FUNCTION_NOT_DEFINED: int -HOST_IS_BLOCKED: int -HOST_NOT_PRIVILEGED: int -PASSWORD_ANONYMOUS_USER: int -PASSWORD_NOT_ALLOWED: int -PASSWORD_NO_MATCH: int -UPDATE_INFO: int -CANT_CREATE_THREAD: int -WRONG_VALUE_COUNT_ON_ROW: int -CANT_REOPEN_TABLE: int -INVALID_USE_OF_NULL: int -REGEXP_ERROR: int -MIX_OF_GROUP_FUNC_AND_FIELDS: int -NONEXISTING_GRANT: int -TABLEACCESS_DENIED_ERROR: int -COLUMNACCESS_DENIED_ERROR: int -ILLEGAL_GRANT_FOR_TABLE: int -GRANT_WRONG_HOST_OR_USER: int -NO_SUCH_TABLE: int -NONEXISTING_TABLE_GRANT: int -NOT_ALLOWED_COMMAND: int -SYNTAX_ERROR: int -DELAYED_CANT_CHANGE_LOCK: int -TOO_MANY_DELAYED_THREADS: int -ABORTING_CONNECTION: int -NET_PACKET_TOO_LARGE: int -NET_READ_ERROR_FROM_PIPE: int -NET_FCNTL_ERROR: int -NET_PACKETS_OUT_OF_ORDER: int -NET_UNCOMPRESS_ERROR: int -NET_READ_ERROR: int -NET_READ_INTERRUPTED: int -NET_ERROR_ON_WRITE: int -NET_WRITE_INTERRUPTED: int -TOO_LONG_STRING: int -TABLE_CANT_HANDLE_BLOB: int -TABLE_CANT_HANDLE_AUTO_INCREMENT: int -DELAYED_INSERT_TABLE_LOCKED: int -WRONG_COLUMN_NAME: int -WRONG_KEY_COLUMN: int -WRONG_MRG_TABLE: int -DUP_UNIQUE: int -BLOB_KEY_WITHOUT_LENGTH: int -PRIMARY_CANT_HAVE_NULL: int -TOO_MANY_ROWS: int -REQUIRES_PRIMARY_KEY: int -NO_RAID_COMPILED: int -UPDATE_WITHOUT_KEY_IN_SAFE_MODE: int -KEY_DOES_NOT_EXITS: int -CHECK_NO_SUCH_TABLE: int -CHECK_NOT_IMPLEMENTED: int -CANT_DO_THIS_DURING_AN_TRANSACTION: int -ERROR_DURING_COMMIT: int -ERROR_DURING_ROLLBACK: int -ERROR_DURING_FLUSH_LOGS: int -ERROR_DURING_CHECKPOINT: int -NEW_ABORTING_CONNECTION: int -DUMP_NOT_IMPLEMENTED: int -FLUSH_MASTER_BINLOG_CLOSED: int -INDEX_REBUILD: int -MASTER: int -MASTER_NET_READ: int -MASTER_NET_WRITE: int -FT_MATCHING_KEY_NOT_FOUND: int -LOCK_OR_ACTIVE_TRANSACTION: int -UNKNOWN_SYSTEM_VARIABLE: int -CRASHED_ON_USAGE: int -CRASHED_ON_REPAIR: int -WARNING_NOT_COMPLETE_ROLLBACK: int -TRANS_CACHE_FULL: int -SLAVE_MUST_STOP: int -SLAVE_NOT_RUNNING: int -BAD_SLAVE: int -MASTER_INFO: int -SLAVE_THREAD: int -TOO_MANY_USER_CONNECTIONS: int -SET_CONSTANTS_ONLY: int -LOCK_WAIT_TIMEOUT: int -LOCK_TABLE_FULL: int -READ_ONLY_TRANSACTION: int -DROP_DB_WITH_READ_LOCK: int -CREATE_DB_WITH_READ_LOCK: int -WRONG_ARGUMENTS: int -NO_PERMISSION_TO_CREATE_USER: int -UNION_TABLES_IN_DIFFERENT_DIR: int -LOCK_DEADLOCK: int -TABLE_CANT_HANDLE_FT: int -CANNOT_ADD_FOREIGN: int -NO_REFERENCED_ROW: int -ROW_IS_REFERENCED: int -CONNECT_TO_MASTER: int -QUERY_ON_MASTER: int -ERROR_WHEN_EXECUTING_COMMAND: int -WRONG_USAGE: int -WRONG_NUMBER_OF_COLUMNS_IN_SELECT: int -CANT_UPDATE_WITH_READLOCK: int -MIXING_NOT_ALLOWED: int -DUP_ARGUMENT: int -USER_LIMIT_REACHED: int -SPECIFIC_ACCESS_DENIED_ERROR: int -LOCAL_VARIABLE: int -GLOBAL_VARIABLE: int -NO_DEFAULT: int -WRONG_VALUE_FOR_VAR: int -WRONG_TYPE_FOR_VAR: int -VAR_CANT_BE_READ: int -CANT_USE_OPTION_HERE: int -NOT_SUPPORTED_YET: int -MASTER_FATAL_ERROR_READING_BINLOG: int -SLAVE_IGNORED_TABLE: int -INCORRECT_GLOBAL_LOCAL_VAR: int -WRONG_FK_DEF: int -KEY_REF_DO_NOT_MATCH_TABLE_REF: int -OPERAND_COLUMNS: int -SUBQUERY_NO_1_ROW: int -UNKNOWN_STMT_HANDLER: int -CORRUPT_HELP_DB: int -CYCLIC_REFERENCE: int -AUTO_CONVERT: int -ILLEGAL_REFERENCE: int -DERIVED_MUST_HAVE_ALIAS: int -SELECT_REDUCED: int -TABLENAME_NOT_ALLOWED_HERE: int -NOT_SUPPORTED_AUTH_MODE: int -SPATIAL_CANT_HAVE_NULL: int -COLLATION_CHARSET_MISMATCH: int -SLAVE_WAS_RUNNING: int -SLAVE_WAS_NOT_RUNNING: int -TOO_BIG_FOR_UNCOMPRESS: int -ZLIB_Z_MEM_ERROR: int -ZLIB_Z_BUF_ERROR: int -ZLIB_Z_DATA_ERROR: int -CUT_VALUE_GROUP_CONCAT: int -WARN_TOO_FEW_RECORDS: int -WARN_TOO_MANY_RECORDS: int -WARN_NULL_TO_NOTNULL: int -WARN_DATA_OUT_OF_RANGE: int -WARN_DATA_TRUNCATED: int -WARN_USING_OTHER_HANDLER: int -CANT_AGGREGATE_2COLLATIONS: int -DROP_USER: int -REVOKE_GRANTS: int -CANT_AGGREGATE_3COLLATIONS: int -CANT_AGGREGATE_NCOLLATIONS: int -VARIABLE_IS_NOT_STRUCT: int -UNKNOWN_COLLATION: int -SLAVE_IGNORED_SSL_PARAMS: int -SERVER_IS_IN_SECURE_AUTH_MODE: int -WARN_FIELD_RESOLVED: int -BAD_SLAVE_UNTIL_COND: int -MISSING_SKIP_SLAVE: int -UNTIL_COND_IGNORED: int -WRONG_NAME_FOR_INDEX: int -WRONG_NAME_FOR_CATALOG: int -WARN_QC_RESIZE: int -BAD_FT_COLUMN: int -UNKNOWN_KEY_CACHE: int -WARN_HOSTNAME_WONT_WORK: int -UNKNOWN_STORAGE_ENGINE: int -WARN_DEPRECATED_SYNTAX: int -NON_UPDATABLE_TABLE: int -FEATURE_DISABLED: int -OPTION_PREVENTS_STATEMENT: int -DUPLICATED_VALUE_IN_TYPE: int -TRUNCATED_WRONG_VALUE: int -TOO_MUCH_AUTO_TIMESTAMP_COLS: int -INVALID_ON_UPDATE: int -UNSUPPORTED_PS: int -GET_ERRMSG: int -GET_TEMPORARY_ERRMSG: int -UNKNOWN_TIME_ZONE: int -WARN_INVALID_TIMESTAMP: int -INVALID_CHARACTER_STRING: int -WARN_ALLOWED_PACKET_OVERFLOWED: int -CONFLICTING_DECLARATIONS: int -SP_NO_RECURSIVE_CREATE: int -SP_ALREADY_EXISTS: int -SP_DOES_NOT_EXIST: int -SP_DROP_FAILED: int -SP_STORE_FAILED: int -SP_LILABEL_MISMATCH: int -SP_LABEL_REDEFINE: int -SP_LABEL_MISMATCH: int -SP_UNINIT_VAR: int -SP_BADSELECT: int -SP_BADRETURN: int -SP_BADSTATEMENT: int -UPDATE_LOG_DEPRECATED_IGNORED: int -UPDATE_LOG_DEPRECATED_TRANSLATED: int -QUERY_INTERRUPTED: int -SP_WRONG_NO_OF_ARGS: int -SP_COND_MISMATCH: int -SP_NORETURN: int -SP_NORETURNEND: int -SP_BAD_CURSOR_QUERY: int -SP_BAD_CURSOR_SELECT: int -SP_CURSOR_MISMATCH: int -SP_CURSOR_ALREADY_OPEN: int -SP_CURSOR_NOT_OPEN: int -SP_UNDECLARED_VAR: int -SP_WRONG_NO_OF_FETCH_ARGS: int -SP_FETCH_NO_DATA: int -SP_DUP_PARAM: int -SP_DUP_VAR: int -SP_DUP_COND: int -SP_DUP_CURS: int -SP_CANT_ALTER: int -SP_SUBSELECT_NYI: int -STMT_NOT_ALLOWED_IN_SF_OR_TRG: int -SP_VARCOND_AFTER_CURSHNDLR: int -SP_CURSOR_AFTER_HANDLER: int -SP_CASE_NOT_FOUND: int -FPARSER_TOO_BIG_FILE: int -FPARSER_BAD_HEADER: int -FPARSER_EOF_IN_COMMENT: int -FPARSER_ERROR_IN_PARAMETER: int -FPARSER_EOF_IN_UNKNOWN_PARAMETER: int -VIEW_NO_EXPLAIN: int -FRM_UNKNOWN_TYPE: int -WRONG_OBJECT: int -NONUPDATEABLE_COLUMN: int -VIEW_SELECT_DERIVED: int -VIEW_SELECT_CLAUSE: int -VIEW_SELECT_VARIABLE: int -VIEW_SELECT_TMPTABLE: int -VIEW_WRONG_LIST: int -WARN_VIEW_MERGE: int -WARN_VIEW_WITHOUT_KEY: int -VIEW_INVALID: int -SP_NO_DROP_SP: int -SP_GOTO_IN_HNDLR: int -TRG_ALREADY_EXISTS: int -TRG_DOES_NOT_EXIST: int -TRG_ON_VIEW_OR_TEMP_TABLE: int -TRG_CANT_CHANGE_ROW: int -TRG_NO_SUCH_ROW_IN_TRG: int -NO_DEFAULT_FOR_FIELD: int -DIVISION_BY_ZERO: int -TRUNCATED_WRONG_VALUE_FOR_FIELD: int -ILLEGAL_VALUE_FOR_TYPE: int -VIEW_NONUPD_CHECK: int -VIEW_CHECK_FAILED: int -PROCACCESS_DENIED_ERROR: int -RELAY_LOG_FAIL: int -PASSWD_LENGTH: int -UNKNOWN_TARGET_BINLOG: int -IO_ERR_LOG_INDEX_READ: int -BINLOG_PURGE_PROHIBITED: int -FSEEK_FAIL: int -BINLOG_PURGE_FATAL_ERR: int -LOG_IN_USE: int -LOG_PURGE_UNKNOWN_ERR: int -RELAY_LOG_INIT: int -NO_BINARY_LOGGING: int -RESERVED_SYNTAX: int -WSAS_FAILED: int -DIFF_GROUPS_PROC: int -NO_GROUP_FOR_PROC: int -ORDER_WITH_PROC: int -LOGGING_PROHIBIT_CHANGING_OF: int -NO_FILE_MAPPING: int -WRONG_MAGIC: int -PS_MANY_PARAM: int -KEY_PART_0: int -VIEW_CHECKSUM: int -VIEW_MULTIUPDATE: int -VIEW_NO_INSERT_FIELD_LIST: int -VIEW_DELETE_MERGE_VIEW: int -CANNOT_USER: int -XAER_NOTA: int -XAER_INVAL: int -XAER_RMFAIL: int -XAER_OUTSIDE: int -XAER_RMERR: int -XA_RBROLLBACK: int -NONEXISTING_PROC_GRANT: int -PROC_AUTO_GRANT_FAIL: int -PROC_AUTO_REVOKE_FAIL: int -DATA_TOO_LONG: int -SP_BAD_SQLSTATE: int -STARTUP: int -LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR: int -CANT_CREATE_USER_WITH_GRANT: int -WRONG_VALUE_FOR_TYPE: int -TABLE_DEF_CHANGED: int -SP_DUP_HANDLER: int -SP_NOT_VAR_ARG: int -SP_NO_RETSET: int -CANT_CREATE_GEOMETRY_OBJECT: int -FAILED_ROUTINE_BREAK_BINLOG: int -BINLOG_UNSAFE_ROUTINE: int -BINLOG_CREATE_ROUTINE_NEED_SUPER: int -EXEC_STMT_WITH_OPEN_CURSOR: int -STMT_HAS_NO_OPEN_CURSOR: int -COMMIT_NOT_ALLOWED_IN_SF_OR_TRG: int -NO_DEFAULT_FOR_VIEW_FIELD: int -SP_NO_RECURSION: int -TOO_BIG_SCALE: int -TOO_BIG_PRECISION: int -M_BIGGER_THAN_D: int -WRONG_LOCK_OF_SYSTEM_TABLE: int -CONNECT_TO_FOREIGN_DATA_SOURCE: int -QUERY_ON_FOREIGN_DATA_SOURCE: int -FOREIGN_DATA_SOURCE_DOESNT_EXIST: int -FOREIGN_DATA_STRING_INVALID_CANT_CREATE: int -FOREIGN_DATA_STRING_INVALID: int -CANT_CREATE_FEDERATED_TABLE: int -TRG_IN_WRONG_SCHEMA: int -STACK_OVERRUN_NEED_MORE: int -TOO_LONG_BODY: int -WARN_CANT_DROP_DEFAULT_KEYCACHE: int -TOO_BIG_DISPLAYWIDTH: int -XAER_DUPID: int -DATETIME_FUNCTION_OVERFLOW: int -CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG: int -VIEW_PREVENT_UPDATE: int -PS_NO_RECURSION: int -SP_CANT_SET_AUTOCOMMIT: int -MALFORMED_DEFINER: int -VIEW_FRM_NO_USER: int -VIEW_OTHER_USER: int -NO_SUCH_USER: int -FORBID_SCHEMA_CHANGE: int -ROW_IS_REFERENCED_2: int -NO_REFERENCED_ROW_2: int -SP_BAD_VAR_SHADOW: int -TRG_NO_DEFINER: int -OLD_FILE_FORMAT: int -SP_RECURSION_LIMIT: int -SP_PROC_TABLE_CORRUPT: int -SP_WRONG_NAME: int -TABLE_NEEDS_UPGRADE: int -SP_NO_AGGREGATE: int -MAX_PREPARED_STMT_COUNT_REACHED: int -VIEW_RECURSIVE: int -NON_GROUPING_FIELD_USED: int -TABLE_CANT_HANDLE_SPKEYS: int -NO_TRIGGERS_ON_SYSTEM_SCHEMA: int -USERNAME: int -HOSTNAME: int -WRONG_STRING_LENGTH: int -ERROR_LAST: int +from typing import Final + +ERROR_FIRST: Final = 1000 +HASHCHK: Final = 1000 +NISAMCHK: Final = 1001 +NO: Final = 1002 +YES: Final = 1003 +CANT_CREATE_FILE: Final = 1004 +CANT_CREATE_TABLE: Final = 1005 +CANT_CREATE_DB: Final = 1006 +DB_CREATE_EXISTS: Final = 1007 +DB_DROP_EXISTS: Final = 1008 +DB_DROP_DELETE: Final = 1009 +DB_DROP_RMDIR: Final = 1010 +CANT_DELETE_FILE: Final = 1011 +CANT_FIND_SYSTEM_REC: Final = 1012 +CANT_GET_STAT: Final = 1013 +CANT_GET_WD: Final = 1014 +CANT_LOCK: Final = 1015 +CANT_OPEN_FILE: Final = 1016 +FILE_NOT_FOUND: Final = 1017 +CANT_READ_DIR: Final = 1018 +CANT_SET_WD: Final = 1019 +CHECKREAD: Final = 1020 +DISK_FULL: Final = 1021 +DUP_KEY: Final = 1022 +ERROR_ON_CLOSE: Final = 1023 +ERROR_ON_READ: Final = 1024 +ERROR_ON_RENAME: Final = 1025 +ERROR_ON_WRITE: Final = 1026 +FILE_USED: Final = 1027 +FILSORT_ABORT: Final = 1028 +FORM_NOT_FOUND: Final = 1029 +GET_ERRNO: Final = 1030 +ILLEGAL_HA: Final = 1031 +KEY_NOT_FOUND: Final = 1032 +NOT_FORM_FILE: Final = 1033 +NOT_KEYFILE: Final = 1034 +OLD_KEYFILE: Final = 1035 +OPEN_AS_READONLY: Final = 1036 +OUTOFMEMORY: Final = 1037 +OUT_OF_SORTMEMORY: Final = 1038 +UNEXPECTED_EOF: Final = 1039 +CON_COUNT_ERROR: Final = 1040 +OUT_OF_RESOURCES: Final = 1041 +BAD_HOST_ERROR: Final = 1042 +HANDSHAKE_ERROR: Final = 1043 +DBACCESS_DENIED_ERROR: Final = 1044 +ACCESS_DENIED_ERROR: Final = 1045 +NO_DB_ERROR: Final = 1046 +UNKNOWN_COM_ERROR: Final = 1047 +BAD_NULL_ERROR: Final = 1048 +BAD_DB_ERROR: Final = 1049 +TABLE_EXISTS_ERROR: Final = 1050 +BAD_TABLE_ERROR: Final = 1051 +NON_UNIQ_ERROR: Final = 1052 +SERVER_SHUTDOWN: Final = 1053 +BAD_FIELD_ERROR: Final = 1054 +WRONG_FIELD_WITH_GROUP: Final = 1055 +WRONG_GROUP_FIELD: Final = 1056 +WRONG_SUM_SELECT: Final = 1057 +WRONG_VALUE_COUNT: Final = 1058 +TOO_LONG_IDENT: Final = 1059 +DUP_FIELDNAME: Final = 1060 +DUP_KEYNAME: Final = 1061 +DUP_ENTRY: Final = 1062 +WRONG_FIELD_SPEC: Final = 1063 +PARSE_ERROR: Final = 1064 +EMPTY_QUERY: Final = 1065 +NONUNIQ_TABLE: Final = 1066 +INVALID_DEFAULT: Final = 1067 +MULTIPLE_PRI_KEY: Final = 1068 +TOO_MANY_KEYS: Final = 1069 +TOO_MANY_KEY_PARTS: Final = 1070 +TOO_LONG_KEY: Final = 1071 +KEY_COLUMN_DOES_NOT_EXITS: Final = 1072 +BLOB_USED_AS_KEY: Final = 1073 +TOO_BIG_FIELDLENGTH: Final = 1074 +WRONG_AUTO_KEY: Final = 1075 +READY: Final = 1076 +NORMAL_SHUTDOWN: Final = 1077 +GOT_SIGNAL: Final = 1078 +SHUTDOWN_COMPLETE: Final = 1079 +FORCING_CLOSE: Final = 1080 +IPSOCK_ERROR: Final = 1081 +NO_SUCH_INDEX: Final = 1082 +WRONG_FIELD_TERMINATORS: Final = 1083 +BLOBS_AND_NO_TERMINATED: Final = 1084 +TEXTFILE_NOT_READABLE: Final = 1085 +FILE_EXISTS_ERROR: Final = 1086 +LOAD_INFO: Final = 1087 +ALTER_INFO: Final = 1088 +WRONG_SUB_KEY: Final = 1089 +CANT_REMOVE_ALL_FIELDS: Final = 1090 +CANT_DROP_FIELD_OR_KEY: Final = 1091 +INSERT_INFO: Final = 1092 +UPDATE_TABLE_USED: Final = 1093 +NO_SUCH_THREAD: Final = 1094 +KILL_DENIED_ERROR: Final = 1095 +NO_TABLES_USED: Final = 1096 +TOO_BIG_SET: Final = 1097 +NO_UNIQUE_LOGFILE: Final = 1098 +TABLE_NOT_LOCKED_FOR_WRITE: Final = 1099 +TABLE_NOT_LOCKED: Final = 1100 +BLOB_CANT_HAVE_DEFAULT: Final = 1101 +WRONG_DB_NAME: Final = 1102 +WRONG_TABLE_NAME: Final = 1103 +TOO_BIG_SELECT: Final = 1104 +UNKNOWN_ERROR: Final = 1105 +UNKNOWN_PROCEDURE: Final = 1106 +WRONG_PARAMCOUNT_TO_PROCEDURE: Final = 1107 +WRONG_PARAMETERS_TO_PROCEDURE: Final = 1108 +UNKNOWN_TABLE: Final = 1109 +FIELD_SPECIFIED_TWICE: Final = 1110 +INVALID_GROUP_FUNC_USE: Final = 1111 +UNSUPPORTED_EXTENSION: Final = 1112 +TABLE_MUST_HAVE_COLUMNS: Final = 1113 +RECORD_FILE_FULL: Final = 1114 +UNKNOWN_CHARACTER_SET: Final = 1115 +TOO_MANY_TABLES: Final = 1116 +TOO_MANY_FIELDS: Final = 1117 +TOO_BIG_ROWSIZE: Final = 1118 +STACK_OVERRUN: Final = 1119 +WRONG_OUTER_JOIN: Final = 1120 +NULL_COLUMN_IN_INDEX: Final = 1121 +CANT_FIND_UDF: Final = 1122 +CANT_INITIALIZE_UDF: Final = 1123 +UDF_NO_PATHS: Final = 1124 +UDF_EXISTS: Final = 1125 +CANT_OPEN_LIBRARY: Final = 1126 +CANT_FIND_DL_ENTRY: Final = 1127 +FUNCTION_NOT_DEFINED: Final = 1128 +HOST_IS_BLOCKED: Final = 1129 +HOST_NOT_PRIVILEGED: Final = 1130 +PASSWORD_ANONYMOUS_USER: Final = 1131 +PASSWORD_NOT_ALLOWED: Final = 1132 +PASSWORD_NO_MATCH: Final = 1133 +UPDATE_INFO: Final = 1134 +CANT_CREATE_THREAD: Final = 1135 +WRONG_VALUE_COUNT_ON_ROW: Final = 1136 +CANT_REOPEN_TABLE: Final = 1137 +INVALID_USE_OF_NULL: Final = 1138 +REGEXP_ERROR: Final = 1139 +MIX_OF_GROUP_FUNC_AND_FIELDS: Final = 1140 +NONEXISTING_GRANT: Final = 1141 +TABLEACCESS_DENIED_ERROR: Final = 1142 +COLUMNACCESS_DENIED_ERROR: Final = 1143 +ILLEGAL_GRANT_FOR_TABLE: Final = 1144 +GRANT_WRONG_HOST_OR_USER: Final = 1145 +NO_SUCH_TABLE: Final = 1146 +NONEXISTING_TABLE_GRANT: Final = 1147 +NOT_ALLOWED_COMMAND: Final = 1148 +SYNTAX_ERROR: Final = 1149 +DELAYED_CANT_CHANGE_LOCK: Final = 1150 +TOO_MANY_DELAYED_THREADS: Final = 1151 +ABORTING_CONNECTION: Final = 1152 +NET_PACKET_TOO_LARGE: Final = 1153 +NET_READ_ERROR_FROM_PIPE: Final = 1154 +NET_FCNTL_ERROR: Final = 1155 +NET_PACKETS_OUT_OF_ORDER: Final = 1156 +NET_UNCOMPRESS_ERROR: Final = 1157 +NET_READ_ERROR: Final = 1158 +NET_READ_INTERRUPTED: Final = 1159 +NET_ERROR_ON_WRITE: Final = 1160 +NET_WRITE_INTERRUPTED: Final = 1161 +TOO_LONG_STRING: Final = 1162 +TABLE_CANT_HANDLE_BLOB: Final = 1163 +TABLE_CANT_HANDLE_AUTO_INCREMENT: Final = 1164 +DELAYED_INSERT_TABLE_LOCKED: Final = 1165 +WRONG_COLUMN_NAME: Final = 1166 +WRONG_KEY_COLUMN: Final = 1167 +WRONG_MRG_TABLE: Final = 1168 +DUP_UNIQUE: Final = 1169 +BLOB_KEY_WITHOUT_LENGTH: Final = 1170 +PRIMARY_CANT_HAVE_NULL: Final = 1171 +TOO_MANY_ROWS: Final = 1172 +REQUIRES_PRIMARY_KEY: Final = 1173 +NO_RAID_COMPILED: Final = 1174 +UPDATE_WITHOUT_KEY_IN_SAFE_MODE: Final = 1175 +KEY_DOES_NOT_EXITS: Final = 1176 +CHECK_NO_SUCH_TABLE: Final = 1177 +CHECK_NOT_IMPLEMENTED: Final = 1178 +CANT_DO_THIS_DURING_AN_TRANSACTION: Final = 1179 +ERROR_DURING_COMMIT: Final = 1180 +ERROR_DURING_ROLLBACK: Final = 1181 +ERROR_DURING_FLUSH_LOGS: Final = 1182 +ERROR_DURING_CHECKPOINT: Final = 1183 +NEW_ABORTING_CONNECTION: Final = 1184 +DUMP_NOT_IMPLEMENTED: Final = 1185 +FLUSH_MASTER_BINLOG_CLOSED: Final = 1186 +INDEX_REBUILD: Final = 1187 +MASTER: Final = 1188 +MASTER_NET_READ: Final = 1189 +MASTER_NET_WRITE: Final = 1190 +FT_MATCHING_KEY_NOT_FOUND: Final = 1191 +LOCK_OR_ACTIVE_TRANSACTION: Final = 1192 +UNKNOWN_SYSTEM_VARIABLE: Final = 1193 +CRASHED_ON_USAGE: Final = 1194 +CRASHED_ON_REPAIR: Final = 1195 +WARNING_NOT_COMPLETE_ROLLBACK: Final = 1196 +TRANS_CACHE_FULL: Final = 1197 +SLAVE_MUST_STOP: Final = 1198 +SLAVE_NOT_RUNNING: Final = 1199 +BAD_SLAVE: Final = 1200 +MASTER_INFO: Final = 1201 +SLAVE_THREAD: Final = 1202 +TOO_MANY_USER_CONNECTIONS: Final = 1203 +SET_CONSTANTS_ONLY: Final = 1204 +LOCK_WAIT_TIMEOUT: Final = 1205 +LOCK_TABLE_FULL: Final = 1206 +READ_ONLY_TRANSACTION: Final = 1207 +DROP_DB_WITH_READ_LOCK: Final = 1208 +CREATE_DB_WITH_READ_LOCK: Final = 1209 +WRONG_ARGUMENTS: Final = 1210 +NO_PERMISSION_TO_CREATE_USER: Final = 1211 +UNION_TABLES_IN_DIFFERENT_DIR: Final = 1212 +LOCK_DEADLOCK: Final = 1213 +TABLE_CANT_HANDLE_FT: Final = 1214 +CANNOT_ADD_FOREIGN: Final = 1215 +NO_REFERENCED_ROW: Final = 1216 +ROW_IS_REFERENCED: Final = 1217 +CONNECT_TO_MASTER: Final = 1218 +QUERY_ON_MASTER: Final = 1219 +ERROR_WHEN_EXECUTING_COMMAND: Final = 1220 +WRONG_USAGE: Final = 1221 +WRONG_NUMBER_OF_COLUMNS_IN_SELECT: Final = 1222 +CANT_UPDATE_WITH_READLOCK: Final = 1223 +MIXING_NOT_ALLOWED: Final = 1224 +DUP_ARGUMENT: Final = 1225 +USER_LIMIT_REACHED: Final = 1226 +SPECIFIC_ACCESS_DENIED_ERROR: Final = 1227 +LOCAL_VARIABLE: Final = 1228 +GLOBAL_VARIABLE: Final = 1229 +NO_DEFAULT: Final = 1230 +WRONG_VALUE_FOR_VAR: Final = 1231 +WRONG_TYPE_FOR_VAR: Final = 1232 +VAR_CANT_BE_READ: Final = 1233 +CANT_USE_OPTION_HERE: Final = 1234 +NOT_SUPPORTED_YET: Final = 1235 +MASTER_FATAL_ERROR_READING_BINLOG: Final = 1236 +SLAVE_IGNORED_TABLE: Final = 1237 +INCORRECT_GLOBAL_LOCAL_VAR: Final = 1238 +WRONG_FK_DEF: Final = 1239 +KEY_REF_DO_NOT_MATCH_TABLE_REF: Final = 1240 +OPERAND_COLUMNS: Final = 1241 +SUBQUERY_NO_1_ROW: Final = 1242 +UNKNOWN_STMT_HANDLER: Final = 1243 +CORRUPT_HELP_DB: Final = 1244 +CYCLIC_REFERENCE: Final = 1245 +AUTO_CONVERT: Final = 1246 +ILLEGAL_REFERENCE: Final = 1247 +DERIVED_MUST_HAVE_ALIAS: Final = 1248 +SELECT_REDUCED: Final = 1249 +TABLENAME_NOT_ALLOWED_HERE: Final = 1250 +NOT_SUPPORTED_AUTH_MODE: Final = 1251 +SPATIAL_CANT_HAVE_NULL: Final = 1252 +COLLATION_CHARSET_MISMATCH: Final = 1253 +SLAVE_WAS_RUNNING: Final = 1254 +SLAVE_WAS_NOT_RUNNING: Final = 1255 +TOO_BIG_FOR_UNCOMPRESS: Final = 1256 +ZLIB_Z_MEM_ERROR: Final = 1257 +ZLIB_Z_BUF_ERROR: Final = 1258 +ZLIB_Z_DATA_ERROR: Final = 1259 +CUT_VALUE_GROUP_CONCAT: Final = 1260 +WARN_TOO_FEW_RECORDS: Final = 1261 +WARN_TOO_MANY_RECORDS: Final = 1262 +WARN_NULL_TO_NOTNULL: Final = 1263 +WARN_DATA_OUT_OF_RANGE: Final = 1264 +WARN_DATA_TRUNCATED: Final = 1265 +WARN_USING_OTHER_HANDLER: Final = 1266 +CANT_AGGREGATE_2COLLATIONS: Final = 1267 +DROP_USER: Final = 1268 +REVOKE_GRANTS: Final = 1269 +CANT_AGGREGATE_3COLLATIONS: Final = 1270 +CANT_AGGREGATE_NCOLLATIONS: Final = 1271 +VARIABLE_IS_NOT_STRUCT: Final = 1272 +UNKNOWN_COLLATION: Final = 1273 +SLAVE_IGNORED_SSL_PARAMS: Final = 1274 +SERVER_IS_IN_SECURE_AUTH_MODE: Final = 1275 +WARN_FIELD_RESOLVED: Final = 1276 +BAD_SLAVE_UNTIL_COND: Final = 1277 +MISSING_SKIP_SLAVE: Final = 1278 +UNTIL_COND_IGNORED: Final = 1279 +WRONG_NAME_FOR_INDEX: Final = 1280 +WRONG_NAME_FOR_CATALOG: Final = 1281 +WARN_QC_RESIZE: Final = 1282 +BAD_FT_COLUMN: Final = 1283 +UNKNOWN_KEY_CACHE: Final = 1284 +WARN_HOSTNAME_WONT_WORK: Final = 1285 +UNKNOWN_STORAGE_ENGINE: Final = 1286 +WARN_DEPRECATED_SYNTAX: Final = 1287 +NON_UPDATABLE_TABLE: Final = 1288 +FEATURE_DISABLED: Final = 1289 +OPTION_PREVENTS_STATEMENT: Final = 1290 +DUPLICATED_VALUE_IN_TYPE: Final = 1291 +TRUNCATED_WRONG_VALUE: Final = 1292 +TOO_MUCH_AUTO_TIMESTAMP_COLS: Final = 1293 +INVALID_ON_UPDATE: Final = 1294 +UNSUPPORTED_PS: Final = 1295 +GET_ERRMSG: Final = 1296 +GET_TEMPORARY_ERRMSG: Final = 1297 +UNKNOWN_TIME_ZONE: Final = 1298 +WARN_INVALID_TIMESTAMP: Final = 1299 +INVALID_CHARACTER_STRING: Final = 1300 +WARN_ALLOWED_PACKET_OVERFLOWED: Final = 1301 +CONFLICTING_DECLARATIONS: Final = 1302 +SP_NO_RECURSIVE_CREATE: Final = 1303 +SP_ALREADY_EXISTS: Final = 1304 +SP_DOES_NOT_EXIST: Final = 1305 +SP_DROP_FAILED: Final = 1306 +SP_STORE_FAILED: Final = 1307 +SP_LILABEL_MISMATCH: Final = 1308 +SP_LABEL_REDEFINE: Final = 1309 +SP_LABEL_MISMATCH: Final = 1310 +SP_UNINIT_VAR: Final = 1311 +SP_BADSELECT: Final = 1312 +SP_BADRETURN: Final = 1313 +SP_BADSTATEMENT: Final = 1314 +UPDATE_LOG_DEPRECATED_IGNORED: Final = 1315 +UPDATE_LOG_DEPRECATED_TRANSLATED: Final = 1316 +QUERY_INTERRUPTED: Final = 1317 +SP_WRONG_NO_OF_ARGS: Final = 1318 +SP_COND_MISMATCH: Final = 1319 +SP_NORETURN: Final = 1320 +SP_NORETURNEND: Final = 1321 +SP_BAD_CURSOR_QUERY: Final = 1322 +SP_BAD_CURSOR_SELECT: Final = 1323 +SP_CURSOR_MISMATCH: Final = 1324 +SP_CURSOR_ALREADY_OPEN: Final = 1325 +SP_CURSOR_NOT_OPEN: Final = 1326 +SP_UNDECLARED_VAR: Final = 1327 +SP_WRONG_NO_OF_FETCH_ARGS: Final = 1328 +SP_FETCH_NO_DATA: Final = 1329 +SP_DUP_PARAM: Final = 1330 +SP_DUP_VAR: Final = 1331 +SP_DUP_COND: Final = 1332 +SP_DUP_CURS: Final = 1333 +SP_CANT_ALTER: Final = 1334 +SP_SUBSELECT_NYI: Final = 1335 +STMT_NOT_ALLOWED_IN_SF_OR_TRG: Final = 1336 +SP_VARCOND_AFTER_CURSHNDLR: Final = 1337 +SP_CURSOR_AFTER_HANDLER: Final = 1338 +SP_CASE_NOT_FOUND: Final = 1339 +FPARSER_TOO_BIG_FILE: Final = 1340 +FPARSER_BAD_HEADER: Final = 1341 +FPARSER_EOF_IN_COMMENT: Final = 1342 +FPARSER_ERROR_IN_PARAMETER: Final = 1343 +FPARSER_EOF_IN_UNKNOWN_PARAMETER: Final = 1344 +VIEW_NO_EXPLAIN: Final = 1345 +FRM_UNKNOWN_TYPE: Final = 1346 +WRONG_OBJECT: Final = 1347 +NONUPDATEABLE_COLUMN: Final = 1348 +VIEW_SELECT_DERIVED: Final = 1349 +VIEW_SELECT_CLAUSE: Final = 1350 +VIEW_SELECT_VARIABLE: Final = 1351 +VIEW_SELECT_TMPTABLE: Final = 1352 +VIEW_WRONG_LIST: Final = 1353 +WARN_VIEW_MERGE: Final = 1354 +WARN_VIEW_WITHOUT_KEY: Final = 1355 +VIEW_INVALID: Final = 1356 +SP_NO_DROP_SP: Final = 1357 +SP_GOTO_IN_HNDLR: Final = 1358 +TRG_ALREADY_EXISTS: Final = 1359 +TRG_DOES_NOT_EXIST: Final = 1360 +TRG_ON_VIEW_OR_TEMP_TABLE: Final = 1361 +TRG_CANT_CHANGE_ROW: Final = 1362 +TRG_NO_SUCH_ROW_IN_TRG: Final = 1363 +NO_DEFAULT_FOR_FIELD: Final = 1364 +DIVISION_BY_ZERO: Final = 1365 +TRUNCATED_WRONG_VALUE_FOR_FIELD: Final = 1366 +ILLEGAL_VALUE_FOR_TYPE: Final = 1367 +VIEW_NONUPD_CHECK: Final = 1368 +VIEW_CHECK_FAILED: Final = 1369 +PROCACCESS_DENIED_ERROR: Final = 1370 +RELAY_LOG_FAIL: Final = 1371 +PASSWD_LENGTH: Final = 1372 +UNKNOWN_TARGET_BINLOG: Final = 1373 +IO_ERR_LOG_INDEX_READ: Final = 1374 +BINLOG_PURGE_PROHIBITED: Final = 1375 +FSEEK_FAIL: Final = 1376 +BINLOG_PURGE_FATAL_ERR: Final = 1377 +LOG_IN_USE: Final = 1378 +LOG_PURGE_UNKNOWN_ERR: Final = 1379 +RELAY_LOG_INIT: Final = 1380 +NO_BINARY_LOGGING: Final = 1381 +RESERVED_SYNTAX: Final = 1382 +WSAS_FAILED: Final = 1383 +DIFF_GROUPS_PROC: Final = 1384 +NO_GROUP_FOR_PROC: Final = 1385 +ORDER_WITH_PROC: Final = 1386 +LOGGING_PROHIBIT_CHANGING_OF: Final = 1387 +NO_FILE_MAPPING: Final = 1388 +WRONG_MAGIC: Final = 1389 +PS_MANY_PARAM: Final = 1390 +KEY_PART_0: Final = 1391 +VIEW_CHECKSUM: Final = 1392 +VIEW_MULTIUPDATE: Final = 1393 +VIEW_NO_INSERT_FIELD_LIST: Final = 1394 +VIEW_DELETE_MERGE_VIEW: Final = 1395 +CANNOT_USER: Final = 1396 +XAER_NOTA: Final = 1397 +XAER_INVAL: Final = 1398 +XAER_RMFAIL: Final = 1399 +XAER_OUTSIDE: Final = 1400 +XAER_RMERR: Final = 1401 +XA_RBROLLBACK: Final = 1402 +NONEXISTING_PROC_GRANT: Final = 1403 +PROC_AUTO_GRANT_FAIL: Final = 1404 +PROC_AUTO_REVOKE_FAIL: Final = 1405 +DATA_TOO_LONG: Final = 1406 +SP_BAD_SQLSTATE: Final = 1407 +STARTUP: Final = 1408 +LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR: Final = 1409 +CANT_CREATE_USER_WITH_GRANT: Final = 1410 +WRONG_VALUE_FOR_TYPE: Final = 1411 +TABLE_DEF_CHANGED: Final = 1412 +SP_DUP_HANDLER: Final = 1413 +SP_NOT_VAR_ARG: Final = 1414 +SP_NO_RETSET: Final = 1415 +CANT_CREATE_GEOMETRY_OBJECT: Final = 1416 +FAILED_ROUTINE_BREAK_BINLOG: Final = 1417 +BINLOG_UNSAFE_ROUTINE: Final = 1418 +BINLOG_CREATE_ROUTINE_NEED_SUPER: Final = 1419 +EXEC_STMT_WITH_OPEN_CURSOR: Final = 1420 +STMT_HAS_NO_OPEN_CURSOR: Final = 1421 +COMMIT_NOT_ALLOWED_IN_SF_OR_TRG: Final = 1422 +NO_DEFAULT_FOR_VIEW_FIELD: Final = 1423 +SP_NO_RECURSION: Final = 1424 +TOO_BIG_SCALE: Final = 1425 +TOO_BIG_PRECISION: Final = 1426 +M_BIGGER_THAN_D: Final = 1427 +WRONG_LOCK_OF_SYSTEM_TABLE: Final = 1428 +CONNECT_TO_FOREIGN_DATA_SOURCE: Final = 1429 +QUERY_ON_FOREIGN_DATA_SOURCE: Final = 1430 +FOREIGN_DATA_SOURCE_DOESNT_EXIST: Final = 1431 +FOREIGN_DATA_STRING_INVALID_CANT_CREATE: Final = 1432 +FOREIGN_DATA_STRING_INVALID: Final = 1433 +CANT_CREATE_FEDERATED_TABLE: Final = 1434 +TRG_IN_WRONG_SCHEMA: Final = 1435 +STACK_OVERRUN_NEED_MORE: Final = 1436 +TOO_LONG_BODY: Final = 1437 +WARN_CANT_DROP_DEFAULT_KEYCACHE: Final = 1438 +TOO_BIG_DISPLAYWIDTH: Final = 1439 +XAER_DUPID: Final = 1440 +DATETIME_FUNCTION_OVERFLOW: Final = 1441 +CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG: Final = 1442 +VIEW_PREVENT_UPDATE: Final = 1443 +PS_NO_RECURSION: Final = 1444 +SP_CANT_SET_AUTOCOMMIT: Final = 1445 +MALFORMED_DEFINER: Final = 1446 +VIEW_FRM_NO_USER: Final = 1447 +VIEW_OTHER_USER: Final = 1448 +NO_SUCH_USER: Final = 1449 +FORBID_SCHEMA_CHANGE: Final = 1450 +ROW_IS_REFERENCED_2: Final = 1451 +NO_REFERENCED_ROW_2: Final = 1452 +SP_BAD_VAR_SHADOW: Final = 1453 +TRG_NO_DEFINER: Final = 1454 +OLD_FILE_FORMAT: Final = 1455 +SP_RECURSION_LIMIT: Final = 1456 +SP_PROC_TABLE_CORRUPT: Final = 1457 +SP_WRONG_NAME: Final = 1458 +TABLE_NEEDS_UPGRADE: Final = 1459 +SP_NO_AGGREGATE: Final = 1460 +MAX_PREPARED_STMT_COUNT_REACHED: Final = 1461 +VIEW_RECURSIVE: Final = 1462 +NON_GROUPING_FIELD_USED: Final = 1463 +TABLE_CANT_HANDLE_SPKEYS: Final = 1464 +NO_TRIGGERS_ON_SYSTEM_SCHEMA: Final = 1465 +USERNAME: Final = 1466 +HOSTNAME: Final = 1467 +WRONG_STRING_LENGTH: Final = 1468 +ERROR_LAST: Final = 1468 +STATEMENT_TIMEOUT: Final = 1969 +QUERY_TIMEOUT: Final = 3024 +CONSTRAINT_FAILED: Final = 4025 diff --git a/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi b/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi index f1938b001e61..ab5a5b71f529 100644 --- a/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi +++ b/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi @@ -1,29 +1,32 @@ -DECIMAL: int -TINY: int -SHORT: int -LONG: int -FLOAT: int -DOUBLE: int -NULL: int -TIMESTAMP: int -LONGLONG: int -INT24: int -DATE: int -TIME: int -DATETIME: int -YEAR: int -NEWDATE: int -VARCHAR: int -BIT: int -NEWDECIMAL: int -ENUM: int -SET: int -TINY_BLOB: int -MEDIUM_BLOB: int -LONG_BLOB: int -BLOB: int -VAR_STRING: int -STRING: int -GEOMETRY: int -CHAR: int -INTERVAL: int +from typing import Final + +DECIMAL: Final = 0 +TINY: Final = 1 +SHORT: Final = 2 +LONG: Final = 3 +FLOAT: Final = 4 +DOUBLE: Final = 5 +NULL: Final = 6 +TIMESTAMP: Final = 7 +LONGLONG: Final = 8 +INT24: Final = 9 +DATE: Final = 10 +TIME: Final = 11 +DATETIME: Final = 12 +YEAR: Final = 13 +NEWDATE: Final = 14 +VARCHAR: Final = 15 +BIT: Final = 16 +JSON: Final = 245 +NEWDECIMAL: Final = 246 +ENUM: Final = 247 +SET: Final = 248 +TINY_BLOB: Final = 249 +MEDIUM_BLOB: Final = 250 +LONG_BLOB: Final = 251 +BLOB: Final = 252 +VAR_STRING: Final = 253 +STRING: Final = 254 +GEOMETRY: Final = 255 +CHAR: Final = TINY +INTERVAL: Final = ENUM diff --git a/stubs/PyMySQL/pymysql/constants/FLAG.pyi b/stubs/PyMySQL/pymysql/constants/FLAG.pyi index 04b99fadc4ee..111e4739fe3d 100644 --- a/stubs/PyMySQL/pymysql/constants/FLAG.pyi +++ b/stubs/PyMySQL/pymysql/constants/FLAG.pyi @@ -1,17 +1,17 @@ -from typing import Any +from typing import Final -NOT_NULL: Any -PRI_KEY: Any -UNIQUE_KEY: Any -MULTIPLE_KEY: Any -BLOB: Any -UNSIGNED: Any -ZEROFILL: Any -BINARY: Any -ENUM: Any -AUTO_INCREMENT: Any -TIMESTAMP: Any -SET: Any -PART_KEY: Any -GROUP: Any -UNIQUE: Any +NOT_NULL: Final = 1 +PRI_KEY: Final = 2 +UNIQUE_KEY: Final = 4 +MULTIPLE_KEY: Final = 8 +BLOB: Final = 16 +UNSIGNED: Final = 32 +ZEROFILL: Final = 64 +BINARY: Final = 128 +ENUM: Final = 256 +AUTO_INCREMENT: Final = 512 +TIMESTAMP: Final = 1024 +SET: Final = 2048 +PART_KEY: Final = 16384 +GROUP: Final = 32767 +UNIQUE: Final = 65536 diff --git a/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi b/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi index 437b89367534..2e006c848e04 100644 --- a/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi +++ b/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi @@ -1,10 +1,12 @@ -SERVER_STATUS_IN_TRANS: int -SERVER_STATUS_AUTOCOMMIT: int -SERVER_MORE_RESULTS_EXISTS: int -SERVER_QUERY_NO_GOOD_INDEX_USED: int -SERVER_QUERY_NO_INDEX_USED: int -SERVER_STATUS_CURSOR_EXISTS: int -SERVER_STATUS_LAST_ROW_SENT: int -SERVER_STATUS_DB_DROPPED: int -SERVER_STATUS_NO_BACKSLASH_ESCAPES: int -SERVER_STATUS_METADATA_CHANGED: int +from typing import Final + +SERVER_STATUS_IN_TRANS: Final = 1 +SERVER_STATUS_AUTOCOMMIT: Final = 2 +SERVER_MORE_RESULTS_EXISTS: Final = 8 +SERVER_QUERY_NO_GOOD_INDEX_USED: Final = 16 +SERVER_QUERY_NO_INDEX_USED: Final = 32 +SERVER_STATUS_CURSOR_EXISTS: Final = 64 +SERVER_STATUS_LAST_ROW_SENT: Final = 128 +SERVER_STATUS_DB_DROPPED: Final = 256 +SERVER_STATUS_NO_BACKSLASH_ESCAPES: Final = 512 +SERVER_STATUS_METADATA_CHANGED: Final = 1024 diff --git a/stubs/PyMySQL/pymysql/converters.pyi b/stubs/PyMySQL/pymysql/converters.pyi index ee2e4ba89aaa..f94dcc5323aa 100644 --- a/stubs/PyMySQL/pymysql/converters.pyi +++ b/stubs/PyMySQL/pymysql/converters.pyi @@ -1,39 +1,51 @@ import datetime +import re import time +from _typeshed import Unused from collections.abc import Callable, Mapping, Sequence from decimal import Decimal -from typing import Any, Optional, Type, TypeVar +from typing import Any, TypeAlias, TypeVar +from typing_extensions import Never, deprecated -_EscaperMapping = Optional[Mapping[Type[object], Callable[..., str]]] +_EscaperMapping: TypeAlias = Mapping[type[object], Callable[..., str]] | None _T = TypeVar("_T") -def escape_item(val: object, charset: object, mapping: _EscaperMapping = ...) -> str: ... -def escape_dict(val: Mapping[str, object], charset: object, mapping: _EscaperMapping = ...) -> dict[str, str]: ... -def escape_sequence(val: Sequence[object], charset: object, mapping: _EscaperMapping = ...) -> str: ... -def escape_set(val: set[object], charset: object, mapping: _EscaperMapping = ...) -> str: ... -def escape_bool(value: bool, mapping: _EscaperMapping = ...) -> str: ... -def escape_int(value: int, mapping: _EscaperMapping = ...) -> str: ... -def escape_float(value: float, mapping: _EscaperMapping = ...) -> str: ... -def escape_string(value: str, mapping: _EscaperMapping = ...) -> str: ... -def escape_bytes_prefixed(value: bytes, mapping: _EscaperMapping = ...) -> str: ... -def escape_bytes(value: bytes, mapping: _EscaperMapping = ...) -> str: ... -def escape_str(value: str, mapping: _EscaperMapping = ...) -> str: ... -def escape_None(value: None, mapping: _EscaperMapping = ...) -> str: ... -def escape_timedelta(obj: datetime.timedelta, mapping: _EscaperMapping = ...) -> str: ... -def escape_time(obj: datetime.time, mapping: _EscaperMapping = ...) -> str: ... -def escape_datetime(obj: datetime.datetime, mapping: _EscaperMapping = ...) -> str: ... -def escape_date(obj: datetime.date, mapping: _EscaperMapping = ...) -> str: ... -def escape_struct_time(obj: time.struct_time, mapping: _EscaperMapping = ...) -> str: ... -def Decimal2Literal(o: Decimal, d: object) -> str: ... +def escape_item(val: object, charset: object = None, mapping: _EscaperMapping = None) -> str: ... +def escape_not_supported(val: object, charset: object = None, mapping: _EscaperMapping = None) -> Never: ... +def escape_sequence(val: Sequence[object], charset: object = None, mapping: _EscaperMapping = None) -> str: ... +@deprecated("escape_set is deprecated") +def escape_set(val: set[object], charset: object = None, mapping: _EscaperMapping = None) -> str: ... +def escape_bool(value: bool, mapping: _EscaperMapping = None) -> str: ... +def escape_int(value: int, mapping: _EscaperMapping = None) -> str: ... +def escape_float(value: float, mapping: _EscaperMapping = None) -> str: ... +def escape_string(value: str, mapping: _EscaperMapping = None) -> str: ... +def escape_bytes(value: bytes, mapping: _EscaperMapping = None) -> str: ... +def escape_str(value: str, mapping: _EscaperMapping = None) -> str: ... +def escape_None(value: None, mapping: _EscaperMapping = None) -> str: ... +def escape_timedelta(obj: datetime.timedelta, mapping: _EscaperMapping = None) -> str: ... +def escape_time(obj: datetime.time, mapping: _EscaperMapping = None) -> str: ... +def escape_datetime(obj: datetime.datetime, mapping: _EscaperMapping = None) -> str: ... +def escape_date(obj: datetime.date, mapping: _EscaperMapping = None) -> str: ... +def escape_struct_time(obj: time.struct_time, mapping: _EscaperMapping = None) -> str: ... +def Decimal2Literal(o: Decimal, d: Unused) -> str: ... + +DATETIME_RE: re.Pattern[str] + def convert_datetime(obj: str | bytes) -> datetime.datetime | str: ... + +TIMEDELTA_RE: re.Pattern[str] + def convert_timedelta(obj: str | bytes) -> datetime.timedelta | str: ... + +TIME_RE: re.Pattern[str] + def convert_time(obj: str | bytes) -> datetime.time | str: ... def convert_date(obj: str | bytes) -> datetime.date | str: ... def through(x: _T) -> _T: ... convert_bit = through -encoders: dict[Type[object], Callable[..., str]] +encoders: dict[type[object], Callable[..., str]] decoders: dict[int, Callable[[str | bytes], Any]] -conversions: dict[Type[object] | int, Callable[..., Any]] +conversions: dict[type[object] | int, Callable[..., Any]] Thing2Literal = escape_str diff --git a/stubs/PyMySQL/pymysql/cursors.pyi b/stubs/PyMySQL/pymysql/cursors.pyi index 45942196111e..4cb666119cf7 100644 --- a/stubs/PyMySQL/pymysql/cursors.pyi +++ b/stubs/PyMySQL/pymysql/cursors.pyi @@ -1,50 +1,70 @@ -from typing import Any, Iterable, Iterator, Text, Tuple, TypeVar +import re +from collections.abc import Iterable, Iterator +from typing import Any, ClassVar, TypeAlias, overload +from typing_extensions import Self, deprecated from .connections import Connection -_SelfT = TypeVar("_SelfT") +RE_INSERT_VALUES: re.Pattern[str] +_Args: TypeAlias = list[Any] | tuple[Any, ...] | dict[str, Any] class Cursor: + max_stmt_length: ClassVar[int] connection: Connection[Any] - description: Tuple[Text, ...] + description: tuple[str, ...] rownumber: int rowcount: int arraysize: int messages: Any errorhandler: Any lastrowid: int + warning_count: int def __init__(self, connection: Connection[Any]) -> None: ... - def __del__(self) -> None: ... def close(self) -> None: ... def setinputsizes(self, *args) -> None: ... def setoutputsizes(self, *args) -> None: ... def nextset(self) -> bool | None: ... - def mogrify(self, query: Text, args: object = ...) -> str: ... - def execute(self, query: Text, args: object = ...) -> int: ... - def executemany(self, query: Text, args: Iterable[object]) -> int | None: ... - def callproc(self, procname: Text, args: Iterable[Any] = ...) -> Any: ... - def scroll(self, value: int, mode: Text = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... - def __exit__(self, *exc_info: Any) -> None: ... + + @overload + def mogrify(self, query: str, args: _Args | None = None) -> str: ... + @overload + @deprecated("single argument is deprecated and will be removed in the next version.") + def mogrify(self, query: str, args: object) -> str: ... + + @overload + def execute(self, query: str, args: _Args | None = None) -> int: ... + @overload + @deprecated("single argument is deprecated and will be removed in the next version.") + def execute(self, query: str, args: object) -> int: ... + + def executemany(self, query: str, args: Iterable[object]) -> int | None: ... + def callproc(self, procname: str, args: Iterable[Any] = ()) -> Any: ... + def scroll(self, value: int, mode: str = "relative") -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: object) -> None: ... # Methods returning result tuples are below. - def fetchone(self) -> Tuple[Any, ...] | None: ... - def fetchmany(self, size: int | None = ...) -> Tuple[Tuple[Any, ...], ...]: ... - def fetchall(self) -> Tuple[Tuple[Any, ...], ...]: ... - def __iter__(self) -> Iterator[Tuple[Any, ...]]: ... + def fetchone(self) -> tuple[Any, ...] | None: ... + def fetchmany(self, size: int | None = None) -> tuple[tuple[Any, ...], ...]: ... + def fetchall(self) -> tuple[tuple[Any, ...], ...]: ... + def __iter__(self) -> Iterator[tuple[Any, ...]]: ... + def __next__(self): ... class DictCursorMixin: dict_type: Any # TODO: add support if someone needs this - def fetchone(self) -> dict[Text, Any] | None: ... - def fetchmany(self, size: int | None = ...) -> Tuple[dict[Text, Any], ...]: ... - def fetchall(self) -> Tuple[dict[Text, Any], ...]: ... - def __iter__(self) -> Iterator[dict[Text, Any]]: ... + def fetchone(self) -> dict[str, Any] | None: ... + def fetchmany(self, size: int | None = ...) -> tuple[dict[str, Any], ...]: ... + def fetchall(self) -> tuple[dict[str, Any], ...]: ... + def __iter__(self) -> Iterator[dict[str, Any]]: ... class SSCursor(Cursor): - def fetchall(self) -> list[Tuple[Any, ...]]: ... # type: ignore[override] - def fetchall_unbuffered(self) -> Iterator[Tuple[Any, ...]]: ... - def scroll(self, value: int, mode: Text = ...) -> None: ... + def __del__(self) -> None: ... + def read_next(self) -> tuple[Any, ...] | None: ... + def fetchall(self) -> list[tuple[Any, ...]]: ... # type: ignore[override] + def fetchall_unbuffered(self) -> Iterator[tuple[Any, ...]]: ... + def scroll(self, value: int, mode: str = "relative") -> None: ... -class DictCursor(DictCursorMixin, Cursor): ... # type: ignore[misc] +class DictCursor(DictCursorMixin, Cursor): ... # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] -class SSDictCursor(DictCursorMixin, SSCursor): # type: ignore[misc] - def fetchall_unbuffered(self) -> Iterator[dict[Text, Any]]: ... # type: ignore[override] +class SSDictCursor(DictCursorMixin, SSCursor): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + def fetchall_unbuffered(self) -> Iterator[dict[str, Any]]: ... # type: ignore[override] + def read_next(self) -> dict[str, Any] | None: ... # type: ignore[override] diff --git a/stubs/PyMySQL/pymysql/err.pyi b/stubs/PyMySQL/pymysql/err.pyi index 2a13b1d893df..d8a2d837761c 100644 --- a/stubs/PyMySQL/pymysql/err.pyi +++ b/stubs/PyMySQL/pymysql/err.pyi @@ -1,11 +1,15 @@ import builtins -from typing import NoReturn, Type +from typing_extensions import Never from .constants import ER as ER class MySQLError(Exception): ... class Warning(builtins.Warning, MySQLError): ... -class Error(MySQLError): ... + +class Error(MySQLError): + sqlstate: str | None + def __init__(self, *args: object, sqlstate: str | None = None) -> None: ... + class InterfaceError(Error): ... class DatabaseError(Error): ... class DataError(DatabaseError): ... @@ -15,6 +19,6 @@ class InternalError(DatabaseError): ... class ProgrammingError(DatabaseError): ... class NotSupportedError(DatabaseError): ... -error_map: dict[int, Type[DatabaseError]] +error_map: dict[int, type[DatabaseError]] -def raise_mysql_exception(data) -> NoReturn: ... +def raise_mysql_exception(data: bytes | bytearray) -> Never: ... diff --git a/stubs/PyMySQL/pymysql/optionfile.pyi b/stubs/PyMySQL/pymysql/optionfile.pyi new file mode 100644 index 000000000000..7848c4e04ec8 --- /dev/null +++ b/stubs/PyMySQL/pymysql/optionfile.pyi @@ -0,0 +1,40 @@ +import configparser +import sys +from collections.abc import Mapping, Sequence + +class Parser(configparser.RawConfigParser): + # __init__ signature was taken from RawConfigParser, but with no allow_no_value argument and all arguments are keyword-only + if sys.version_info >= (3, 13): + def __init__( + self, + *, + defaults: Mapping[str, str] | None = None, + dict_type: type[Mapping[str, str]] = ..., + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: configparser.Interpolation | None = ..., + converters: configparser._ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + else: + def __init__( + self, + *, + defaults: Mapping[str, str] | None = None, + dict_type: type[Mapping[str, str]] = ..., + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: configparser.Interpolation | None = ..., + converters: configparser._ConvertersMap = ..., + ) -> None: ... + + def optionxform(self, key: str) -> str: ... + def get(self, section: configparser._SectionName, option: str) -> str: ... # type: ignore[override] diff --git a/stubs/PyMySQL/pymysql/protocol.pyi b/stubs/PyMySQL/pymysql/protocol.pyi new file mode 100644 index 000000000000..dd742364215a --- /dev/null +++ b/stubs/PyMySQL/pymysql/protocol.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from typing import Final + +DEBUG: Final[bool] +NULL_COLUMN: Final[int] +UNSIGNED_CHAR_COLUMN: Final[int] +UNSIGNED_SHORT_COLUMN: Final[int] +UNSIGNED_INT24_COLUMN: Final[int] +UNSIGNED_INT64_COLUMN: Final[int] + +def dump_packet(data) -> None: ... + +class MysqlPacket: + __slots__ = ("_position", "_data") + def __init__(self, data, encoding) -> None: ... + def get_all_data(self): ... + def read(self, size): ... + def read_all(self): ... + def advance(self, length: int) -> None: ... + def rewind(self, position: int = 0) -> None: ... + def get_bytes(self, position: int, length: int = 1): ... + def read_uint8(self): ... + def read_uint16(self): ... + def read_uint24(self): ... + def read_uint32(self): ... + def read_uint64(self): ... + def read_string(self): ... + def read_length_encoded_integer(self) -> Incomplete | None: ... + def read_length_coded_string(self): ... + def read_struct(self, fmt: str): ... + def is_ok_packet(self) -> bool: ... + def is_eof_packet(self) -> bool: ... + def is_auth_switch_request(self) -> bool: ... + def is_extra_auth_data(self) -> bool: ... + def is_resultset_packet(self) -> bool: ... + def is_load_local_packet(self) -> bool: ... + def is_error_packet(self) -> bool: ... + def check_error(self) -> None: ... + def raise_for_error(self) -> None: ... + def dump(self) -> None: ... + +class FieldDescriptorPacket(MysqlPacket): + def __init__(self, data, encoding) -> None: ... + def description(self): ... + def get_column_length(self): ... + +class OKPacketWrapper: + def __init__(self, from_packet) -> None: ... + # TODO: add attrs from `from_packet` + def __getattr__(self, key: str): ... + +class EOFPacketWrapper: + def __init__(self, from_packet) -> None: ... + # TODO: add attrs from `from_packet` + def __getattr__(self, key: str): ... + +class LoadLocalPacketWrapper: + def __init__(self, from_packet) -> None: ... + # TODO: add attrs from `from_packet` + def __getattr__(self, key: str): ... diff --git a/stubs/PyMySQL/pymysql/times.pyi b/stubs/PyMySQL/pymysql/times.pyi index c798e654518f..2c4f86f7ae31 100644 --- a/stubs/PyMySQL/pymysql/times.pyi +++ b/stubs/PyMySQL/pymysql/times.pyi @@ -1,10 +1,10 @@ -from typing import Any +from datetime import date, datetime, time, timedelta -Date: Any -Time: Any -TimeDelta: Any -Timestamp: Any +Date: type[date] +Time: type[time] +TimeDelta: type[timedelta] +Timestamp: type[datetime] -def DateFromTicks(ticks): ... -def TimeFromTicks(ticks): ... -def TimestampFromTicks(ticks): ... +def DateFromTicks(ticks: float | None) -> date: ... +def TimeFromTicks(ticks: float | None) -> time: ... +def TimestampFromTicks(ticks: float | None) -> datetime: ... diff --git a/stubs/PyMySQL/pymysql/util.pyi b/stubs/PyMySQL/pymysql/util.pyi deleted file mode 100644 index 3d9a65b4b2d3..000000000000 --- a/stubs/PyMySQL/pymysql/util.pyi +++ /dev/null @@ -1,3 +0,0 @@ -def byte2int(b): ... -def int2byte(i): ... -def join_bytes(bs): ... diff --git a/stubs/PyScreeze/@tests/stubtest_allowlist.txt b/stubs/PyScreeze/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2fa942fc98c9 --- /dev/null +++ b/stubs/PyScreeze/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# present but unimplemented +pyscreeze.screenshotWindow diff --git a/stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt b/stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..fa9bd6fa07d7 --- /dev/null +++ b/stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# temp variable used to define scrotExists by checking if the command "scrot" exists +pyscreeze.whichProc diff --git a/stubs/PyScreeze/METADATA.toml b/stubs/PyScreeze/METADATA.toml new file mode 100644 index 000000000000..e14ea274756e --- /dev/null +++ b/stubs/PyScreeze/METADATA.toml @@ -0,0 +1,11 @@ +version = "1.0.1" +upstream-repository = "https://github.com/asweigart/pyscreeze" +dependencies = ["Pillow>=10.3.0"] + +[tool.stubtest] +# Linux has extra constants, win32 has different definitions +ci-platforms = ["linux", "win32"] +# PyScreeze has an odd setup.py file +# that doesn't list Pillow as a dependency for py312+ yet: +# https://github.com/asweigart/pyscreeze/blob/eeca245a135cf171c163b3691300138518efa64e/setup.py#L38-L46 +stubtest-dependencies = ["Pillow"] diff --git a/stubs/PyScreeze/pyscreeze/__init__.pyi b/stubs/PyScreeze/pyscreeze/__init__.pyi new file mode 100644 index 000000000000..5e1e7c7fb771 --- /dev/null +++ b/stubs/PyScreeze/pyscreeze/__init__.pyi @@ -0,0 +1,218 @@ +import sys +from _typeshed import ConvertibleToFloat, Incomplete, StrOrBytesPath, Unused +from collections.abc import Callable, Generator +from typing import Final, NamedTuple, ParamSpec, TypeAlias, TypeVar, overload + +from PIL import Image + +_P = ParamSpec("_P") +_R = TypeVar("_R") +# cv2.typing.MatLike: is an alias for `numpy.ndarray | cv2.mat_wrapper.Mat`, Mat extends ndarray. +# But can't import either, because pyscreeze does not declare them as dependencies, stub_uploader won't let it. +_MatLike: TypeAlias = Incomplete + +PILLOW_VERSION: Final[tuple[int, int, int]] +RUNNING_PYTHON_2: Final = False +SCROT_EXISTS: Final[bool] +GNOMESCREENSHOT_EXISTS: Final[bool] + +if sys.platform == "linux": + RUNNING_X11: Final[bool] + RUNNING_WAYLAND: Final[bool] + +# Meant to be overridable as a setting +GRAYSCALE_DEFAULT: bool +# Meant to be overridable for backward-compatibility +USE_IMAGE_NOT_FOUND_EXCEPTION: bool + +class Box(NamedTuple): + left: int + top: int + width: int + height: int + +class Point(NamedTuple): + x: int + y: int + +class RGB(NamedTuple): + red: int + green: int + blue: int + +class PyScreezeException(Exception): ... +class ImageNotFoundException(PyScreezeException): ... + +def requiresPyGetWindow(wrappedFunction: Callable[_P, _R]) -> Callable[_P, _R]: ... + +# _locateAll_opencv +@overload +def locate( + needleImage: str | Image.Image | _MatLike, + haystackImage: str | Image.Image | _MatLike, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Box | None: ... + +# _locateAll_pillow +@overload +def locate( + needleImage: str | Image.Image, + haystackImage: str | Image.Image, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Box | None: ... + +# _locateAll_opencv +@overload +def locateOnScreen( + image: str | Image.Image | _MatLike, + minSearchTime: float = 0, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Box | None: ... + +# _locateAll_pillow +@overload +def locateOnScreen( + image: str | Image.Image, + minSearchTime: float = 0, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Box | None: ... + +# _locateAll_opencv +@overload +def locateAllOnScreen( + image: str | Image.Image | _MatLike, + *, + grayscale: bool | None = None, + limit: int = 1000, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Generator[Box]: ... + +# _locateAll_pillow +@overload +def locateAllOnScreen( + image: str | Image.Image, + *, + grayscale: bool | None = None, + limit: int | None = None, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Generator[Box]: ... + +# _locateAll_opencv +@overload +def locateCenterOnScreen( + image: str | Image.Image | _MatLike, + *, + minSearchTime: float = 0, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Point | None: ... + +# _locateAll_pillow +@overload +def locateCenterOnScreen( + image: str | Image.Image, + *, + minSearchTime: float = 0, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Point | None: ... + +def locateOnScreenNear(image: str | Image.Image | _MatLike, x: int, y: int) -> Box: ... +def locateCenterOnScreenNear(image: str | Image.Image | _MatLike, x: int, y: int) -> Point | None: ... + +# _locateAll_opencv +@overload +def locateOnWindow( + image: str | Image.Image | _MatLike, + title: str, + *, + grayscale: bool | None = None, + limit: Unused = 1, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Box | None: ... + +# _locateAll_pillow +@overload +def locateOnWindow( + image: str | Image.Image, + title: str, + *, + grayscale: bool | None = None, + limit: Unused = 1, + step: int = 1, + confidence: None = None, +) -> Box | None: ... + +def showRegionOnScreen( + region: tuple[int, int, int, int], outlineColor: str = "red", filename: str = "_showRegionOnScreen.png" +) -> None: ... +def center(coords: tuple[int, int, int, int]) -> Point: ... +def pixelMatchesColor( + x: int, y: int, expectedRGBColor: tuple[int, int, int] | tuple[int, int, int, int], tolerance: int = 0 +) -> bool: ... +def pixel(x: int, y: int) -> tuple[int, int, int]: ... + +if sys.platform == "win32": + def screenshot( + imageFilename: StrOrBytesPath | None = None, region: tuple[int, int, int, int] | None = None, allScreens: bool = False + ) -> Image.Image: ... + +else: + def screenshot( + imageFilename: StrOrBytesPath | None = None, region: tuple[int, int, int, int] | None = None + ) -> Image.Image: ... + +# _locateAll_opencv +@overload +def locateAll( + needleImage: str | Image.Image | _MatLike, + haystackImage: str | Image.Image | _MatLike, + grayscale: bool | None = None, + limit: int = 1000, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Generator[Box]: ... + +# _locateAll_pillow +@overload +def locateAll( + needleImage: str | Image.Image, + haystackImage: str | Image.Image, + grayscale: bool | None = None, + limit: int | None = None, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Generator[Box]: ... diff --git a/stubs/PySocks/@tests/stubtest_allowlist.txt b/stubs/PySocks/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..287b0a1f060f --- /dev/null +++ b/stubs/PySocks/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# Internal variables that were improperly leaked to the outside +socks.method +socks.name diff --git a/stubs/PySocks/METADATA.toml b/stubs/PySocks/METADATA.toml new file mode 100644 index 000000000000..2c0e6928c02f --- /dev/null +++ b/stubs/PySocks/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.7.1" +upstream-repository = "https://github.com/Anorov/PySocks" diff --git a/stubs/PySocks/socks.pyi b/stubs/PySocks/socks.pyi new file mode 100644 index 000000000000..18ecec651ef6 --- /dev/null +++ b/stubs/PySocks/socks.pyi @@ -0,0 +1,144 @@ +import logging +import socket +import types +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable, Mapping +from typing import Final, ParamSpec, TypeAlias, TypeVar, overload + +__version__: Final[str] + +log: logging.Logger # undocumented + +_ProxyType: TypeAlias = int + +PROXY_TYPE_SOCKS4: Final[_ProxyType] +SOCKS4: Final[_ProxyType] +PROXY_TYPE_SOCKS5: Final[_ProxyType] +SOCKS5: Final[_ProxyType] +PROXY_TYPE_HTTP: Final[_ProxyType] +HTTP: Final[_ProxyType] + +PROXY_TYPES: Final[dict[str, _ProxyType]] +PRINTABLE_PROXY_TYPES: Final[dict[_ProxyType, str]] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +def set_self_blocking(function: Callable[_P, _T]) -> Callable[_P, _T]: ... # undocumented + +class ProxyError(IOError): + msg: str + socket_err: socket.error + def __init__(self, msg: str, socket_err: socket.error | None = None) -> None: ... + +class GeneralProxyError(ProxyError): ... +class ProxyConnectionError(ProxyError): ... +class SOCKS5AuthError(ProxyError): ... +class SOCKS5Error(ProxyError): ... +class SOCKS4Error(ProxyError): ... +class HTTPError(ProxyError): ... + +SOCKS4_ERRORS: Final[Mapping[int, str]] +SOCKS5_ERRORS: Final[Mapping[int, str]] +DEFAULT_PORTS: Final[Mapping[_ProxyType, int]] + +_DefaultProxy: TypeAlias = tuple[_ProxyType | None, str | None, int | None, bool, bytes | None, bytes | None] + +def set_default_proxy( + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, +) -> None: ... +def setdefaultproxy( + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + *, + proxytype: _ProxyType = ..., +) -> None: ... +def get_default_proxy() -> _DefaultProxy | None: ... + +getdefaultproxy = get_default_proxy + +def wrap_module(module: types.ModuleType) -> None: ... + +wrapmodule = wrap_module + +_Endpoint: TypeAlias = tuple[str, int] + +def create_connection( + dest_pair: _Endpoint, + timeout: int | None = None, + source_address: _Endpoint | None = None, + proxy_type: _ProxyType | None = None, + proxy_addr: str | None = None, + proxy_port: int | None = None, + proxy_rdns: bool = True, + proxy_username: str | None = None, + proxy_password: str | None = None, + socket_options: ( + Iterable[tuple[int, int, int | ReadableBuffer] | tuple[int, int, None, int]] | None + ) = None, # values passing to `socket.setsockopt` method +) -> socksocket: ... + +class _BaseSocket(socket.socket): # undocumented + ... + +class socksocket(_BaseSocket): + default_proxy: _DefaultProxy | None # undocumented + proxy: _DefaultProxy # undocumented + proxy_sockname: _Endpoint | None # undocumented + proxy_peername: _Endpoint | None # undocumented + def __init__( + self, family: socket.AddressFamily = ..., type: socket.SocketKind = ..., proto: int = 0, fileno: int | None = None + ) -> None: ... + def settimeout(self, timeout: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, v: bool) -> None: ... + def set_proxy( + self, + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + ) -> None: ... + def setproxy( + self, + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + *, + proxytype: _ProxyType = ..., + ) -> None: ... + def bind(self, address: socket._Address, /) -> None: ... + + @overload + def sendto(self, bytes: ReadableBuffer, address: socket._Address) -> int: ... + @overload + def sendto(self, bytes: ReadableBuffer, flags: int, address: socket._Address) -> int: ... + + def send(self, bytes: ReadableBuffer, flags: int = 0) -> int: ... + def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[bytes, _Endpoint]: ... + def recv(self, bufsize: int, flags: int = 0) -> bytes: ... + def close(self) -> None: ... + def get_proxy_sockname(self) -> _Endpoint | None: ... + getproxysockname = get_proxy_sockname + def get_proxy_peername(self) -> _Endpoint | None: ... + getproxypeername = get_proxy_peername + def get_peername(self) -> _Endpoint | None: ... + getpeername = get_peername + @set_self_blocking + def connect(self, dest_pair: _Endpoint, catch_errors: bool | None = None) -> None: ... # type: ignore[override] + @set_self_blocking + def connect_ex(self, dest_pair: _Endpoint) -> int: ... # type: ignore[override] diff --git a/stubs/PySocks/sockshandler.pyi b/stubs/PySocks/sockshandler.pyi new file mode 100644 index 000000000000..94d1ceec399f --- /dev/null +++ b/stubs/PySocks/sockshandler.pyi @@ -0,0 +1,97 @@ +import http.client +import ssl +import sys +import urllib.request +from _typeshed import Incomplete, SupportsKeysAndGetItem +from typing import Any, TypeVar + +import socks + +_K = TypeVar("_K") +_V = TypeVar("_V") + +def merge_dict(a: dict[_K, _V], b: SupportsKeysAndGetItem[_K, _V]) -> dict[_K, _V]: ... # undocumented +def is_ip(s: str) -> bool: ... # undocumented + +socks4_no_rdns: set[str] # undocumented + +class SocksiPyConnection(http.client.HTTPConnection): # undocumented + proxyargs: tuple[int, str, int | None, bool, str | None, str | None] + sock: socks.socksocket + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + ) -> None: ... + def connect(self) -> None: ... + +class SocksiPyConnectionS(http.client.HTTPSConnection): # undocumented + proxyargs: tuple[int, str, int | None, bool, str | None, str | None] + sock: socks.socksocket + if sys.version_info >= (3, 12): + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + *, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, + ) -> None: ... + else: + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + key_file: str | None = None, + cert_file: str | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + context: ssl.SSLContext | None = None, + check_hostname: bool | None = None, + blocksize: int = 8192, + ) -> None: ... + + def connect(self) -> None: ... + +class SocksiPyHandler(urllib.request.HTTPHandler, urllib.request.HTTPSHandler): + args: tuple[Incomplete, ...] # undocumented + kw: dict[str, Incomplete] # undocumented + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + *, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + **kwargs: Any, # any additional arguments to `SocksiPyConnection` or `SocksiPyConnectionS` + ) -> None: ... + def http_open(self, req: urllib.request.Request) -> http.client.HTTPResponse: ... # undocumented + def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse: ... # undocumented diff --git a/stubs/PyYAML/@tests/stubtest_allowlist.txt b/stubs/PyYAML/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..a50b77fb0b53 --- /dev/null +++ b/stubs/PyYAML/@tests/stubtest_allowlist.txt @@ -0,0 +1,11 @@ +# yaml._yaml is for backwards compatibility so none of it matters anyway +yaml._yaml.__test__ + +# Some arguments to these functions are technically positional or keyword +# arguments at runtime, but according to the documentation and other, +# similar functions, it's safer to treat them as keyword-only arguments. +yaml.dump_all +yaml.serialize_all + +# Auto-generated methods by Cython +.*_cython__ diff --git a/stubs/PyYAML/METADATA.toml b/stubs/PyYAML/METADATA.toml index 39a61569b3d7..036c3b255825 100644 --- a/stubs/PyYAML/METADATA.toml +++ b/stubs/PyYAML/METADATA.toml @@ -1 +1,2 @@ version = "6.0.*" +upstream-repository = "https://github.com/yaml/pyyaml" diff --git a/stubs/PyYAML/yaml/__init__.pyi b/stubs/PyYAML/yaml/__init__.pyi index 3e202264ea3d..021152a6edb9 100644 --- a/stubs/PyYAML/yaml/__init__.pyi +++ b/stubs/PyYAML/yaml/__init__.pyi @@ -1,318 +1,450 @@ -from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from typing import IO, Any, Pattern, Type, TypeVar, overload +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Iterator, Mapping +from re import Pattern +from typing import Final, TypeVar, overload from . import resolver as resolver # Help mypy a bit; this is implied by loader and dumper from .constructor import BaseConstructor from .cyaml import * +from .cyaml import _CLoader from .dumper import * +from .dumper import _Inf +from .emitter import _WriteStream, _YAMLObject from .error import * from .events import * from .loader import * +from .loader import _Loader from .nodes import * +from .reader import _ReadStream from .representer import BaseRepresenter from .resolver import BaseResolver from .tokens import * -# FIXME: the functions really return str if encoding is None, otherwise bytes. Waiting for python/mypy#5621 -_Yaml = Any - -__with_libyaml__: Any -__version__: str - _T = TypeVar("_T") _Constructor = TypeVar("_Constructor", bound=BaseConstructor) _Representer = TypeVar("_Representer", bound=BaseRepresenter) -def warnings(settings=...): ... -def scan(stream, Loader=...): ... -def parse(stream, Loader=...): ... -def compose(stream, Loader=...): ... -def compose_all(stream, Loader=...): ... -def load(stream: bytes | IO[bytes] | str | IO[str], Loader) -> Any: ... -def load_all(stream: bytes | IO[bytes] | str | IO[str], Loader) -> Iterator[Any]: ... -def full_load(stream: bytes | IO[bytes] | str | IO[str]) -> Any: ... -def full_load_all(stream: bytes | IO[bytes] | str | IO[str]) -> Iterator[Any]: ... -def safe_load(stream: bytes | IO[bytes] | str | IO[str]) -> Any: ... -def safe_load_all(stream: bytes | IO[bytes] | str | IO[str]) -> Iterator[Any]: ... -def unsafe_load(stream: bytes | IO[bytes] | str | IO[str]) -> Any: ... -def unsafe_load_all(stream: bytes | IO[bytes] | str | IO[str]) -> Iterator[Any]: ... +__with_libyaml__: Final[bool] +__version__: Final[str] + +def warnings(settings=None): ... +def scan(stream, Loader: type[_Loader | _CLoader] = ...): ... +def parse(stream, Loader: type[_Loader | _CLoader] = ...): ... +def compose(stream, Loader: type[_Loader | _CLoader] = ...): ... +def compose_all(stream, Loader: type[_Loader | _CLoader] = ...): ... +def load(stream: _ReadStream, Loader: type[_Loader | _CLoader]) -> _YAMLObject: ... +def load_all(stream: _ReadStream, Loader: type[_Loader | _CLoader]) -> Iterator[_YAMLObject]: ... +def full_load(stream: _ReadStream) -> _YAMLObject: ... +def full_load_all(stream: _ReadStream) -> Iterator[_YAMLObject]: ... +def safe_load(stream: _ReadStream) -> _YAMLObject: ... +def safe_load_all(stream: _ReadStream) -> Iterator[_YAMLObject]: ... +def unsafe_load(stream: _ReadStream) -> _YAMLObject: ... +def unsafe_load_all(stream: _ReadStream) -> Iterator[_YAMLObject]: ... def emit( events, - stream=..., + stream: _WriteStream[_YAMLObject] | None = None, Dumper=..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, ): ... + @overload def serialize_all( nodes, - stream: IO[str], + stream: _WriteStream[_YAMLObject], Dumper=..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, ) -> None: ... @overload def serialize_all( nodes, - stream: None = ..., + stream: None = None, Dumper=..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., -) -> _Yaml: ... + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> str: ... +@overload +def serialize_all( + nodes, + stream: None = None, + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> bytes: ... + @overload def serialize( node, - stream: IO[str], + stream: _WriteStream[_YAMLObject], Dumper=..., *, - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, ) -> None: ... @overload def serialize( node, - stream: None = ..., + stream: None = None, + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> str: ... +@overload +def serialize( + node, + stream: None = None, Dumper=..., *, - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., -) -> _Yaml: ... + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> bytes: ... + @overload def dump_all( - documents: Sequence[Any], - stream: IO[str], + documents: Iterable[_YAMLObject], + stream: _WriteStream[_YAMLObject], Dumper=..., - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... @overload def dump_all( - documents: Sequence[Any], - stream: None = ..., + documents: Iterable[_YAMLObject], + stream: None = None, + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def dump_all( + documents: Iterable[_YAMLObject], + stream: None = None, Dumper=..., - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., -) -> _Yaml: ... + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + @overload def dump( - data: Any, - stream: IO[str], + data: _YAMLObject, + stream: _WriteStream[_YAMLObject], Dumper=..., *, - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... @overload def dump( - data: Any, - stream: None = ..., + data: _YAMLObject, + stream: None = None, Dumper=..., *, - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., -) -> _Yaml: ... + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def dump( + data: _YAMLObject, + stream: None = None, + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + @overload def safe_dump_all( - documents: Sequence[Any], - stream: IO[str], + documents: Iterable[_YAMLObject], + stream: _WriteStream[_YAMLObject], *, - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... @overload def safe_dump_all( - documents: Sequence[Any], - stream: None = ..., + documents: Iterable[_YAMLObject], + stream: None = None, *, - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., -) -> _Yaml: ... + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def safe_dump_all( + documents: Iterable[_YAMLObject], + stream: None = None, + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + @overload def safe_dump( - data: Any, - stream: IO[str], + data: _YAMLObject, + stream: _WriteStream[_YAMLObject], *, - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... @overload def safe_dump( - data: Any, - stream: None = ..., + data: _YAMLObject, + stream: None = None, + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def safe_dump( + data: _YAMLObject, + stream: None = None, *, - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., -) -> _Yaml: ... + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + def add_implicit_resolver( tag: str, regexp: Pattern[str], - first: Iterable[Any] | None = ..., - Loader: Type[BaseResolver] | None = ..., - Dumper: Type[BaseResolver] = ..., + first: Iterable[Incomplete] | None = None, + Loader: type[BaseResolver] | None = None, + Dumper: type[BaseResolver] = ..., ) -> None: ... def add_path_resolver( tag: str, - path: Iterable[Any], - kind: Type[Any] | None = ..., - Loader: Type[BaseResolver] | None = ..., - Dumper: Type[BaseResolver] = ..., + path: Iterable[Incomplete], + kind: type | None = None, + Loader: type[BaseResolver] | None = None, + Dumper: type[BaseResolver] = ..., ) -> None: ... + @overload def add_constructor( - tag: str, constructor: Callable[[Loader | FullLoader | UnsafeLoader, Node], Any], Loader: None = ... + tag: str, constructor: Callable[[Loader | FullLoader | UnsafeLoader, Node], Incomplete], Loader: None = None ) -> None: ... @overload -def add_constructor(tag: str, constructor: Callable[[_Constructor, Node], Any], Loader: Type[_Constructor]) -> None: ... +def add_constructor(tag: str, constructor: Callable[[_Constructor, Node], Incomplete], Loader: type[_Constructor]) -> None: ... + @overload def add_multi_constructor( - tag_prefix: str, multi_constructor: Callable[[Loader | FullLoader | UnsafeLoader, str, Node], Any], Loader: None = ... + tag_prefix: str, multi_constructor: Callable[[Loader | FullLoader | UnsafeLoader, str, Node], Incomplete], Loader: None = None ) -> None: ... @overload def add_multi_constructor( - tag_prefix: str, multi_constructor: Callable[[_Constructor, str, Node], Any], Loader: Type[_Constructor] + tag_prefix: str, multi_constructor: Callable[[_Constructor, str, Node], Incomplete], Loader: type[_Constructor] ) -> None: ... + @overload -def add_representer(data_type: Type[_T], representer: Callable[[Dumper, _T], Node]) -> None: ... +def add_representer(data_type: type[_T], representer: Callable[[Dumper, _T], Node]) -> None: ... @overload -def add_representer(data_type: Type[_T], representer: Callable[[_Representer, _T], Node], Dumper: Type[_Representer]) -> None: ... +def add_representer(data_type: type[_T], representer: Callable[[_Representer, _T], Node], Dumper: type[_Representer]) -> None: ... + @overload -def add_multi_representer(data_type: Type[_T], multi_representer: Callable[[Dumper, _T], Node]) -> None: ... +def add_multi_representer(data_type: type[_T], multi_representer: Callable[[Dumper, _T], Node]) -> None: ... @overload def add_multi_representer( - data_type: Type[_T], multi_representer: Callable[[_Representer, _T], Node], Dumper: Type[_Representer] + data_type: type[_T], multi_representer: Callable[[_Representer, _T], Node], Dumper: type[_Representer] ) -> None: ... class YAMLObjectMetaclass(type): def __init__(cls, name, bases, kwds) -> None: ... class YAMLObject(metaclass=YAMLObjectMetaclass): - yaml_loader: Any - yaml_dumper: Any - yaml_tag: Any - yaml_flow_style: Any + __slots__ = () + yaml_loader: Incomplete + yaml_dumper: Incomplete + yaml_tag: Incomplete + yaml_flow_style: Incomplete @classmethod def from_yaml(cls, loader, node): ... @classmethod diff --git a/stubs/PyYAML/yaml/_yaml.pyi b/stubs/PyYAML/yaml/_yaml.pyi index 5eacde576217..f1cb87c31770 100644 --- a/stubs/PyYAML/yaml/_yaml.pyi +++ b/stubs/PyYAML/yaml/_yaml.pyi @@ -1,6 +1,7 @@ -from _typeshed import SupportsRead +from _typeshed import Incomplete, SupportsRead from collections.abc import Mapping, Sequence from typing import IO, Any +from typing_extensions import disjoint_base from .events import Event from .nodes import Node @@ -9,16 +10,18 @@ from .tokens import Token def get_version_string() -> str: ... def get_version() -> tuple[int, int, int]: ... +@disjoint_base class Mark: - name: Any + name: Incomplete index: int line: int column: int - buffer: Any - pointer: Any + buffer: Incomplete + pointer: Incomplete def __init__(self, name, index: int, line: int, column: int, buffer, pointer) -> None: ... def get_snippet(self): ... +@disjoint_base class CParser: def __init__(self, stream: str | bytes | SupportsRead[str | bytes]) -> None: ... def dispose(self) -> None: ... @@ -34,18 +37,19 @@ class CParser: def raw_parse(self) -> int: ... def raw_scan(self) -> int: ... +@disjoint_base class CEmitter: def __init__( self, stream: IO[Any], - canonical: Any | None = ..., + canonical=..., indent: int | None = ..., width: int | None = ..., - allow_unicode: Any | None = ..., + allow_unicode=..., line_break: str | None = ..., encoding: str | None = ..., - explicit_start: Any | None = ..., - explicit_end: Any | None = ..., + explicit_start=..., + explicit_end=..., version: Sequence[int] | None = ..., tags: Mapping[str, str] | None = ..., ) -> None: ... diff --git a/stubs/PyYAML/yaml/composer.pyi b/stubs/PyYAML/yaml/composer.pyi index 7bc87357c3e1..d353d02220f9 100644 --- a/stubs/PyYAML/yaml/composer.pyi +++ b/stubs/PyYAML/yaml/composer.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete from yaml.error import MarkedYAMLError from yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode @@ -6,13 +6,15 @@ from yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode class ComposerError(MarkedYAMLError): ... class Composer: - anchors: dict[Any, Node] + anchors: dict[Incomplete, Node] def __init__(self) -> None: ... def check_node(self) -> bool: ... def get_node(self) -> Node | None: ... def get_single_node(self) -> Node | None: ... def compose_document(self) -> Node | None: ... def compose_node(self, parent: Node | None, index: int) -> Node | None: ... - def compose_scalar_node(self, anchor: dict[Any, Node]) -> ScalarNode: ... - def compose_sequence_node(self, anchor: dict[Any, Node]) -> SequenceNode: ... - def compose_mapping_node(self, anchor: dict[Any, Node]) -> MappingNode: ... + def compose_scalar_node(self, anchor: dict[Incomplete, Node]) -> ScalarNode: ... + def compose_sequence_node(self, anchor: dict[Incomplete, Node]) -> SequenceNode: ... + def compose_mapping_node(self, anchor: dict[Incomplete, Node]) -> MappingNode: ... + +__all__ = ["Composer", "ComposerError"] diff --git a/stubs/PyYAML/yaml/constructor.pyi b/stubs/PyYAML/yaml/constructor.pyi index e503cba6949a..4c5186840ddd 100644 --- a/stubs/PyYAML/yaml/constructor.pyi +++ b/stubs/PyYAML/yaml/constructor.pyi @@ -1,95 +1,95 @@ -from typing import Any, Pattern, Union +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Hashable +from datetime import date +from re import Pattern +from types import GeneratorType, ModuleType +from typing import ClassVar, TypeVar +from typing_extensions import Never from yaml.error import MarkedYAMLError -from yaml.nodes import ScalarNode +from yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode -_Scalar = Union[str, int, float, bool, None] +from .cyaml import _CLoader +from .emitter import _YAMLObject +from .loader import _Loader + +_L = TypeVar("_L", bound=_Loader | _CLoader) +_N = TypeVar("_N", bound=Node) class ConstructorError(MarkedYAMLError): ... class BaseConstructor: - yaml_constructors: Any - yaml_multi_constructors: Any - constructed_objects: Any - recursive_objects: Any - state_generators: Any - deep_construct: Any + yaml_constructors: ClassVar[dict[str | None, Incomplete]] + yaml_multi_constructors: ClassVar[dict[str | None, Incomplete]] + constructed_objects: dict[Incomplete, Incomplete] + recursive_objects: dict[Incomplete, Incomplete] + state_generators: list[GeneratorType[Incomplete, Incomplete, Incomplete]] + deep_construct: bool def __init__(self) -> None: ... def check_data(self): ... def check_state_key(self, key: str) -> None: ... - def get_data(self): ... - def get_single_data(self) -> Any: ... - def construct_document(self, node): ... - def construct_object(self, node, deep=...): ... - def construct_scalar(self, node: ScalarNode) -> _Scalar: ... - def construct_sequence(self, node, deep=...): ... - def construct_mapping(self, node, deep=...): ... - def construct_pairs(self, node, deep=...): ... + def get_data(self) -> _YAMLObject: ... + def get_single_data(self) -> _YAMLObject: ... + def construct_document(self, node) -> _YAMLObject: ... + def construct_object(self, node, deep: bool = False) -> _YAMLObject: ... + def construct_scalar(self, node: ScalarNode) -> str: ... + def construct_sequence(self, node: SequenceNode, deep: bool = False) -> list[Incomplete]: ... + def construct_mapping(self, node: MappingNode, deep: bool = False) -> dict[Hashable, Incomplete]: ... + def construct_pairs(self, node, deep: bool = False) -> list[tuple[Incomplete, Incomplete]]: ... @classmethod - def add_constructor(cls, tag, constructor): ... + # Use typevars so we can have covariant behaviour in the parameter types + def add_constructor(cls, tag: str, constructor: Callable[[_L, _N], Incomplete]) -> None: ... @classmethod - def add_multi_constructor(cls, tag_prefix, multi_constructor): ... + def add_multi_constructor(cls, tag_prefix: str | None, multi_constructor) -> None: ... class SafeConstructor(BaseConstructor): - def construct_scalar(self, node: ScalarNode) -> _Scalar: ... - def flatten_mapping(self, node): ... - def construct_mapping(self, node, deep=...): ... - def construct_yaml_null(self, node): ... - bool_values: Any - def construct_yaml_bool(self, node): ... - def construct_yaml_int(self, node): ... - inf_value: Any - nan_value: Any - def construct_yaml_float(self, node): ... - def construct_yaml_binary(self, node): ... - timestamp_regexp: Any - def construct_yaml_timestamp(self, node): ... - def construct_yaml_omap(self, node): ... - def construct_yaml_pairs(self, node): ... - def construct_yaml_set(self, node): ... - def construct_yaml_str(self, node): ... - def construct_yaml_seq(self, node): ... - def construct_yaml_map(self, node): ... - def construct_yaml_object(self, node, cls): ... - def construct_undefined(self, node): ... + def construct_scalar(self, node: ScalarNode | MappingNode) -> str: ... + def flatten_mapping(self, node: MappingNode) -> None: ... + def construct_mapping(self, node: MappingNode, deep: bool = False) -> dict[Hashable, Incomplete]: ... + def construct_yaml_null(self, node: ScalarNode) -> None: ... + bool_values: ClassVar[dict[str, bool]] + def construct_yaml_bool(self, node: ScalarNode) -> bool: ... + def construct_yaml_int(self, node: ScalarNode) -> int: ... + inf_value: ClassVar[float] + nan_value: ClassVar[float] + def construct_yaml_float(self, node: ScalarNode) -> float: ... + def construct_yaml_binary(self, node: ScalarNode) -> bytes: ... + timestamp_regexp: ClassVar[Pattern[str]] + def construct_yaml_timestamp(self, node: ScalarNode) -> date: ... + def construct_yaml_omap(self, node) -> Generator[list[tuple[Incomplete, Incomplete]]]: ... + def construct_yaml_pairs(self, node) -> Generator[list[tuple[Incomplete, Incomplete]]]: ... + def construct_yaml_set(self, node) -> Generator[set[dict[Hashable, Incomplete]]]: ... + def construct_yaml_str(self, node) -> str: ... + def construct_yaml_seq(self, node) -> Generator[list[Incomplete]]: ... + def construct_yaml_map(self, node) -> Generator[dict[Incomplete, Incomplete]]: ... + def construct_yaml_object(self, node, cls) -> Generator[Incomplete]: ... + def construct_undefined(self, node) -> Never: ... class FullConstructor(SafeConstructor): def get_state_keys_blacklist(self) -> list[str]: ... def get_state_keys_blacklist_regexp(self) -> Pattern[str]: ... - def construct_python_str(self, node): ... - def construct_python_unicode(self, node): ... - def construct_python_bytes(self, node): ... - def construct_python_long(self, node): ... - def construct_python_complex(self, node): ... - def construct_python_tuple(self, node): ... - def find_python_module(self, name, mark, unsafe=...): ... - def find_python_name(self, name, mark, unsafe=...): ... - def construct_python_name(self, suffix, node): ... - def construct_python_module(self, suffix, node): ... - def make_python_instance(self, suffix, node, args=..., kwds=..., newobj=..., unsafe=...): ... - def set_python_instance_state(self, instance, state, unsafe: bool = ...) -> None: ... - def construct_python_object(self, suffix, node): ... - def construct_python_object_apply(self, suffix, node, newobj=...): ... - def construct_python_object_new(self, suffix, node): ... + def construct_python_str(self, node) -> str: ... + def construct_python_unicode(self, node) -> str: ... + def construct_python_bytes(self, node) -> bytes: ... + def construct_python_long(self, node) -> int: ... + def construct_python_complex(self, node) -> complex: ... + def construct_python_tuple(self, node) -> tuple[Incomplete, ...]: ... + def find_python_module(self, name: str, mark, unsafe: bool = False) -> ModuleType: ... + def find_python_name(self, name: str, mark, unsafe: bool = False): ... + def construct_python_name(self, suffix: str, node): ... + def construct_python_module(self, suffix: str, node) -> ModuleType: ... + def make_python_instance(self, suffix: str, node, args=None, kwds=None, newobj: bool = False, unsafe: bool = False): ... + def set_python_instance_state(self, instance: object, state, unsafe: bool = False) -> None: ... + def construct_python_object(self, suffix: str, node) -> Generator[Incomplete]: ... + def construct_python_object_apply(self, suffix: str, node, newobj: bool = False): ... + def construct_python_object_new(self, suffix: str, node): ... class UnsafeConstructor(FullConstructor): - def find_python_module(self, name, mark): ... - def find_python_name(self, name, mark): ... - def make_python_instance(self, suffix, node, args=..., kwds=..., newobj=...): ... - def set_python_instance_state(self, instance, state): ... + def find_python_module(self, name: str, mark) -> ModuleType: ... # type: ignore[override] + def find_python_name(self, name: str, mark): ... # type: ignore[override] + def make_python_instance(self, suffix: str, node, args=None, kwds=None, newobj: bool = False): ... # type: ignore[override] + def set_python_instance_state(self, instance: object, state) -> None: ... # type: ignore[override] + +class Constructor(SafeConstructor): ... -class Constructor(SafeConstructor): - def construct_python_str(self, node): ... - def construct_python_unicode(self, node): ... - def construct_python_long(self, node): ... - def construct_python_complex(self, node): ... - def construct_python_tuple(self, node): ... - def find_python_module(self, name, mark): ... - def find_python_name(self, name, mark): ... - def construct_python_name(self, suffix, node): ... - def construct_python_module(self, suffix, node): ... - def make_python_instance(self, suffix, node, args=..., kwds=..., newobj=...): ... - def set_python_instance_state(self, instance, state): ... - def construct_python_object(self, suffix, node): ... - def construct_python_object_apply(self, suffix, node, newobj=...): ... - def construct_python_object_new(self, suffix, node): ... +__all__ = ["BaseConstructor", "SafeConstructor", "FullConstructor", "UnsafeConstructor", "Constructor", "ConstructorError"] diff --git a/stubs/PyYAML/yaml/cyaml.pyi b/stubs/PyYAML/yaml/cyaml.pyi index d70b44148bec..abe297bd4da1 100644 --- a/stubs/PyYAML/yaml/cyaml.pyi +++ b/stubs/PyYAML/yaml/cyaml.pyi @@ -1,6 +1,6 @@ from _typeshed import SupportsRead from collections.abc import Mapping, Sequence -from typing import IO, Any, Union +from typing import IO, Any, TypeAlias from ._yaml import CEmitter, CParser from .constructor import BaseConstructor, FullConstructor, SafeConstructor, UnsafeConstructor @@ -9,7 +9,8 @@ from .resolver import BaseResolver, Resolver __all__ = ["CBaseLoader", "CSafeLoader", "CFullLoader", "CUnsafeLoader", "CLoader", "CBaseDumper", "CSafeDumper", "CDumper"] -_Readable = SupportsRead[Union[str, bytes]] +_Readable: TypeAlias = SupportsRead[str | bytes] +_CLoader: TypeAlias = CLoader | CBaseLoader | CFullLoader | CSafeLoader | CUnsafeLoader # noqa: Y047 # Used in other modules class CBaseLoader(CParser, BaseConstructor, BaseResolver): def __init__(self, stream: str | bytes | _Readable) -> None: ... @@ -30,38 +31,38 @@ class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): def __init__( self, stream: IO[Any], - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: Any | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: Any | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: Any | None = ..., - explicit_end: Any | None = ..., - version: Sequence[int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical=None, + indent: int | None = None, + width: int | None = None, + allow_unicode=None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start=None, + explicit_end=None, + version: Sequence[int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... class CDumper(CEmitter, SafeRepresenter, Resolver): def __init__( self, stream: IO[Any], - default_style: str | None = ..., - default_flow_style: bool = ..., - canonical: Any | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: Any | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: Any | None = ..., - explicit_end: Any | None = ..., - version: Sequence[int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + default_style: str | None = None, + default_flow_style: bool = False, + canonical=None, + indent: int | None = None, + width: int | None = None, + allow_unicode=None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start=None, + explicit_end=None, + version: Sequence[int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... CSafeDumper = CDumper diff --git a/stubs/PyYAML/yaml/dumper.pyi b/stubs/PyYAML/yaml/dumper.pyi index 6c89d3f95e3f..a414124d233e 100644 --- a/stubs/PyYAML/yaml/dumper.pyi +++ b/stubs/PyYAML/yaml/dumper.pyi @@ -1,64 +1,72 @@ -from _typeshed import SupportsWrite from collections.abc import Mapping +from typing import TypeAlias from yaml.emitter import Emitter from yaml.representer import BaseRepresenter, Representer, SafeRepresenter from yaml.resolver import BaseResolver, Resolver from yaml.serializer import Serializer +from .emitter import _WriteStream, _YAMLObject + +# Ideally, there would be a way to limit these values to only +/- float("inf"), +# but that's not possible at the moment (https://github.com/python/typing/issues/1160). +_Inf: TypeAlias = float + class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): def __init__( self, - stream: SupportsWrite[bytes | str], - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + stream: _WriteStream[_YAMLObject], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver): def __init__( self, - stream: SupportsWrite[bytes | str], - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + stream: _WriteStream[_YAMLObject], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... class Dumper(Emitter, Serializer, Representer, Resolver): def __init__( self, - stream: SupportsWrite[bytes | str], - default_style: str | None = ..., - default_flow_style: bool | None = ..., - canonical: bool | None = ..., - indent: int | None = ..., - width: int | None = ..., - allow_unicode: bool | None = ..., - line_break: str | None = ..., - encoding: str | None = ..., - explicit_start: bool | None = ..., - explicit_end: bool | None = ..., - version: tuple[int, int] | None = ..., - tags: Mapping[str, str] | None = ..., - sort_keys: bool = ..., + stream: _WriteStream[_YAMLObject], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, ) -> None: ... + +__all__ = ["BaseDumper", "SafeDumper", "Dumper"] diff --git a/stubs/PyYAML/yaml/emitter.pyi b/stubs/PyYAML/yaml/emitter.pyi index 9f44bd771c69..80388523f320 100644 --- a/stubs/PyYAML/yaml/emitter.pyi +++ b/stubs/PyYAML/yaml/emitter.pyi @@ -1,109 +1,138 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Final, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import Never from yaml.error import YAMLError +from .events import Event + +_T_contra = TypeVar("_T_contra", str, bytes, contravariant=True) +_YAMLObject: TypeAlias = Any + +@type_check_only +class _WriteStream(Protocol[_T_contra]): + def write(self, data: _T_contra, /) -> object: ... + # Optional fields: + # encoding: str + # def flush(self) -> object: ... + class EmitterError(YAMLError): ... class ScalarAnalysis: - scalar: Any - empty: Any - multiline: Any - allow_flow_plain: Any - allow_block_plain: Any - allow_single_quoted: Any - allow_double_quoted: Any - allow_block: Any + scalar: Incomplete + empty: Incomplete + multiline: Incomplete + allow_flow_plain: Incomplete + allow_block_plain: Incomplete + allow_single_quoted: Incomplete + allow_double_quoted: Incomplete + allow_block: Incomplete def __init__( self, scalar, empty, multiline, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block ) -> None: ... class Emitter: - DEFAULT_TAG_PREFIXES: Any - stream: Any - encoding: Any - states: Any - state: Any - events: Any - event: Any - indents: Any - indent: Any - flow_level: Any - root_context: Any - sequence_context: Any - mapping_context: Any - simple_key_context: Any - line: Any - column: Any - whitespace: Any - indention: Any - open_ended: Any - canonical: Any - allow_unicode: Any - best_indent: Any - best_width: Any - best_line_break: Any - tag_prefixes: Any - prepared_anchor: Any - prepared_tag: Any - analysis: Any - style: Any - def __init__(self, stream, canonical=..., indent=..., width=..., allow_unicode=..., line_break=...) -> None: ... - def dispose(self): ... - def emit(self, event): ... - def need_more_events(self): ... - def need_events(self, count): ... - def increase_indent(self, flow=..., indentless=...): ... - def expect_stream_start(self): ... - def expect_nothing(self): ... - def expect_first_document_start(self): ... - def expect_document_start(self, first=...): ... - def expect_document_end(self): ... - def expect_document_root(self): ... - def expect_node(self, root=..., sequence=..., mapping=..., simple_key=...): ... - def expect_alias(self): ... - def expect_scalar(self): ... - def expect_flow_sequence(self): ... - def expect_first_flow_sequence_item(self): ... - def expect_flow_sequence_item(self): ... - def expect_flow_mapping(self): ... - def expect_first_flow_mapping_key(self): ... - def expect_flow_mapping_key(self): ... - def expect_flow_mapping_simple_value(self): ... - def expect_flow_mapping_value(self): ... - def expect_block_sequence(self): ... - def expect_first_block_sequence_item(self): ... - def expect_block_sequence_item(self, first=...): ... - def expect_block_mapping(self): ... - def expect_first_block_mapping_key(self): ... - def expect_block_mapping_key(self, first=...): ... - def expect_block_mapping_simple_value(self): ... - def expect_block_mapping_value(self): ... - def check_empty_sequence(self): ... - def check_empty_mapping(self): ... - def check_empty_document(self): ... - def check_simple_key(self): ... - def process_anchor(self, indicator): ... - def process_tag(self): ... - def choose_scalar_style(self): ... - def process_scalar(self): ... - def prepare_version(self, version): ... - def prepare_tag_handle(self, handle): ... - def prepare_tag_prefix(self, prefix): ... - def prepare_tag(self, tag): ... - def prepare_anchor(self, anchor): ... - def analyze_scalar(self, scalar): ... - def flush_stream(self): ... - def write_stream_start(self): ... - def write_stream_end(self): ... - def write_indicator(self, indicator, need_whitespace, whitespace=..., indention=...): ... - def write_indent(self): ... - def write_line_break(self, data=...): ... - def write_version_directive(self, version_text): ... - def write_tag_directive(self, handle_text, prefix_text): ... - def write_single_quoted(self, text, split=...): ... - ESCAPE_REPLACEMENTS: Any - def write_double_quoted(self, text, split=...): ... - def determine_block_hints(self, text): ... - def write_folded(self, text): ... - def write_literal(self, text): ... - def write_plain(self, text, split=...): ... + DEFAULT_TAG_PREFIXES: Final[dict[str, str]] + stream: _WriteStream[_YAMLObject] + encoding: str | None + states: list[Callable[[], None]] + state: Callable[[], None] | None + events: list[Event] + event: Event | None + indents: list[int | None] + indent: int | None + flow_level: int + root_context: bool + sequence_context: bool + mapping_context: bool + simple_key_context: bool + line: int + column: int + whitespace: bool + indention: bool + open_ended: bool + canonical: bool | None + allow_unicode: bool | None + best_indent: int + best_width: int + best_line_break: str + tag_prefixes: dict[str, str] | None + prepared_anchor: str | None + prepared_tag: str | None + analysis: ScalarAnalysis | None + style: str | None + def __init__( + self, + stream: _WriteStream[_YAMLObject], + canonical: bool | None = None, + indent: int | None = None, + width: int | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + ) -> None: ... + def dispose(self) -> None: ... + def emit(self, event: Event) -> None: ... + def need_more_events(self) -> bool: ... + def need_events(self, count: int) -> bool: ... + def increase_indent(self, flow: bool = False, indentless: bool = False) -> None: ... + def expect_stream_start(self) -> None: ... + def expect_nothing(self) -> Never: ... + def expect_first_document_start(self) -> None: ... + def expect_document_start(self, first: bool = False) -> None: ... + def expect_document_end(self) -> None: ... + def expect_document_root(self) -> None: ... + def expect_node( + self, root: bool = False, sequence: bool = False, mapping: bool = False, simple_key: bool = False + ) -> None: ... + def expect_alias(self) -> None: ... + def expect_scalar(self) -> None: ... + def expect_flow_sequence(self) -> None: ... + def expect_first_flow_sequence_item(self) -> None: ... + def expect_flow_sequence_item(self) -> None: ... + def expect_flow_mapping(self) -> None: ... + def expect_first_flow_mapping_key(self) -> None: ... + def expect_flow_mapping_key(self) -> None: ... + def expect_flow_mapping_simple_value(self) -> None: ... + def expect_flow_mapping_value(self) -> None: ... + def expect_block_sequence(self) -> None: ... + def expect_first_block_sequence_item(self) -> None: ... + def expect_block_sequence_item(self, first: bool = False) -> None: ... + def expect_block_mapping(self) -> None: ... + def expect_first_block_mapping_key(self) -> None: ... + def expect_block_mapping_key(self, first: bool = False) -> None: ... + def expect_block_mapping_simple_value(self) -> None: ... + def expect_block_mapping_value(self) -> None: ... + def check_empty_sequence(self) -> bool: ... + def check_empty_mapping(self) -> bool: ... + def check_empty_document(self) -> bool: ... + def check_simple_key(self) -> bool: ... + def process_anchor(self, indicator: str) -> None: ... + def process_tag(self) -> None: ... + def choose_scalar_style(self) -> str: ... + def process_scalar(self) -> None: ... + def prepare_version(self, version) -> str: ... + def prepare_tag_handle(self, handle: str) -> str: ... + def prepare_tag_prefix(self, prefix: str) -> str: ... + def prepare_tag(self, tag: str) -> str: ... + def prepare_anchor(self, anchor: str) -> str: ... + def analyze_scalar(self, scalar: str) -> ScalarAnalysis: ... + def flush_stream(self) -> None: ... + def write_stream_start(self) -> None: ... + def write_stream_end(self) -> None: ... + def write_indicator( + self, indicator: str, need_whitespace: bool, whitespace: bool = False, indention: bool = False + ) -> None: ... + def write_indent(self) -> None: ... + def write_line_break(self, data: str | None = None) -> None: ... + def write_version_directive(self, version_text: str) -> None: ... + def write_tag_directive(self, handle_text: str, prefix_text: str) -> None: ... + def write_single_quoted(self, text: str, split: bool = True) -> None: ... + ESCAPE_REPLACEMENTS: Final[dict[str, str]] + def write_double_quoted(self, text: str, split: bool = True) -> None: ... + def determine_block_hints(self, text: str) -> str: ... + def write_folded(self, text: str) -> None: ... + def write_literal(self, text: str) -> None: ... + def write_plain(self, text: str, split: bool = True) -> None: ... + +__all__ = ["Emitter", "EmitterError"] diff --git a/stubs/PyYAML/yaml/error.pyi b/stubs/PyYAML/yaml/error.pyi index 4bb59d35d56b..9fe53f15d838 100644 --- a/stubs/PyYAML/yaml/error.pyi +++ b/stubs/PyYAML/yaml/error.pyi @@ -6,7 +6,7 @@ class Mark: buffer: str | None pointer: int def __init__(self, name: str, index: int, line: int, column: int, buffer: str | None, pointer: int) -> None: ... - def get_snippet(self, indent: int = ..., max_length: int = ...) -> str | None: ... + def get_snippet(self, indent: int = 4, max_length: int = 75) -> str | None: ... class YAMLError(Exception): ... @@ -18,9 +18,11 @@ class MarkedYAMLError(YAMLError): note: str | None def __init__( self, - context: str | None = ..., - context_mark: Mark | None = ..., - problem: str | None = ..., - problem_mark: Mark | None = ..., - note: str | None = ..., + context: str | None = None, + context_mark: Mark | None = None, + problem: str | None = None, + problem_mark: Mark | None = None, + note: str | None = None, ) -> None: ... + +__all__ = ["Mark", "YAMLError", "MarkedYAMLError"] diff --git a/stubs/PyYAML/yaml/events.pyi b/stubs/PyYAML/yaml/events.pyi index 7096d157ce2d..e6038140a975 100644 --- a/stubs/PyYAML/yaml/events.pyi +++ b/stubs/PyYAML/yaml/events.pyi @@ -1,60 +1,76 @@ -from typing import Any +from collections.abc import Mapping +from typing import TypeAlias + +from ._yaml import Mark as _CMark +from .error import Mark + +_Mark: TypeAlias = Mark | _CMark class Event: - start_mark: Any - end_mark: Any - def __init__(self, start_mark=..., end_mark=...) -> None: ... + start_mark: _Mark | None + end_mark: _Mark | None + def __init__(self, start_mark: _Mark | None = None, end_mark: _Mark | None = None) -> None: ... class NodeEvent(Event): - anchor: Any - start_mark: Any - end_mark: Any - def __init__(self, anchor, start_mark=..., end_mark=...) -> None: ... + anchor: str | None + def __init__(self, anchor: str | None, start_mark: _Mark | None = None, end_mark: _Mark | None = None) -> None: ... class CollectionStartEvent(NodeEvent): - anchor: Any - tag: Any - implicit: Any - start_mark: Any - end_mark: Any - flow_style: Any - def __init__(self, anchor, tag, implicit, start_mark=..., end_mark=..., flow_style=...) -> None: ... + tag: str | None + implicit: bool + flow_style: bool | None + def __init__( + self, + anchor: str | None, + tag: str | None, + implicit: bool, + start_mark: _Mark | None = None, + end_mark: _Mark | None = None, + flow_style: bool | None = None, + ) -> None: ... class CollectionEndEvent(Event): ... class StreamStartEvent(Event): - start_mark: Any - end_mark: Any - encoding: Any - def __init__(self, start_mark=..., end_mark=..., encoding=...) -> None: ... + encoding: str | None + def __init__(self, start_mark: _Mark | None = None, end_mark: _Mark | None = None, encoding: str | None = None) -> None: ... class StreamEndEvent(Event): ... class DocumentStartEvent(Event): - start_mark: Any - end_mark: Any - explicit: Any - version: Any - tags: Any - def __init__(self, start_mark=..., end_mark=..., explicit=..., version=..., tags=...) -> None: ... + explicit: bool | None + version: tuple[int, int] | None + tags: Mapping[str, str] | None + def __init__( + self, + start_mark: _Mark | None = None, + end_mark: _Mark | None = None, + explicit: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + ) -> None: ... class DocumentEndEvent(Event): - start_mark: Any - end_mark: Any - explicit: Any - def __init__(self, start_mark=..., end_mark=..., explicit=...) -> None: ... + explicit: bool | None + def __init__(self, start_mark: _Mark | None = None, end_mark: _Mark | None = None, explicit: bool | None = None) -> None: ... class AliasEvent(NodeEvent): ... class ScalarEvent(NodeEvent): - anchor: Any - tag: Any - implicit: Any - value: Any - start_mark: Any - end_mark: Any - style: Any - def __init__(self, anchor, tag, implicit, value, start_mark=..., end_mark=..., style=...) -> None: ... + tag: str | None + implicit: tuple[bool, bool] + value: str + style: str | None + def __init__( + self, + anchor: str | None, + tag: str | None, + implicit: tuple[bool, bool], + value: str, + start_mark: _Mark | None = None, + end_mark: _Mark | None = None, + style: str | None = None, + ) -> None: ... class SequenceStartEvent(CollectionStartEvent): ... class SequenceEndEvent(CollectionEndEvent): ... diff --git a/stubs/PyYAML/yaml/loader.pyi b/stubs/PyYAML/yaml/loader.pyi index 3782cd365762..5f29f390c2e0 100644 --- a/stubs/PyYAML/yaml/loader.pyi +++ b/stubs/PyYAML/yaml/loader.pyi @@ -1,3 +1,5 @@ +from typing import TypeAlias + from yaml.composer import Composer from yaml.constructor import BaseConstructor, Constructor, FullConstructor, SafeConstructor from yaml.parser import Parser @@ -5,17 +7,23 @@ from yaml.reader import Reader from yaml.resolver import BaseResolver, Resolver from yaml.scanner import Scanner +from .reader import _ReadStream + +_Loader: TypeAlias = Loader | BaseLoader | FullLoader | SafeLoader | UnsafeLoader # noqa: Y047 # Used in other modules + class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): - def __init__(self, stream) -> None: ... + def __init__(self, stream: _ReadStream) -> None: ... class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver): - def __init__(self, stream) -> None: ... + def __init__(self, stream: _ReadStream) -> None: ... class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver): - def __init__(self, stream) -> None: ... + def __init__(self, stream: _ReadStream) -> None: ... class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): - def __init__(self, stream) -> None: ... + def __init__(self, stream: _ReadStream) -> None: ... class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver): - def __init__(self, stream) -> None: ... + def __init__(self, stream: _ReadStream) -> None: ... + +__all__ = ["BaseLoader", "FullLoader", "SafeLoader", "Loader", "UnsafeLoader"] diff --git a/stubs/PyYAML/yaml/nodes.pyi b/stubs/PyYAML/yaml/nodes.pyi index 98e61e296c87..d97634fd5fa3 100644 --- a/stubs/PyYAML/yaml/nodes.pyi +++ b/stubs/PyYAML/yaml/nodes.pyi @@ -1,10 +1,14 @@ +from _typeshed import Incomplete from typing import Any, ClassVar from yaml.error import Mark +# Any Unions: Avoid forcing the user to check for None when they know what Node was instantiated with +# Using generics may be overkill without support for default Generics +# Permissive Unions could also be useful here. class Node: tag: str - value: Any + value: Incomplete start_mark: Mark | Any end_mark: Mark | Any def __init__(self, tag: str, value, start_mark: Mark | None, end_mark: Mark | None) -> None: ... @@ -13,13 +17,13 @@ class ScalarNode(Node): id: ClassVar[str] style: str | Any def __init__( - self, tag: str, value, start_mark: Mark | None = ..., end_mark: Mark | None = ..., style: str | None = ... + self, tag: str, value, start_mark: Mark | None = None, end_mark: Mark | None = None, style: str | None = None ) -> None: ... class CollectionNode(Node): flow_style: bool | Any def __init__( - self, tag: str, value, start_mark: Mark | None = ..., end_mark: Mark | None = ..., flow_style: bool | None = ... + self, tag: str, value, start_mark: Mark | None = None, end_mark: Mark | None = None, flow_style: bool | None = None ) -> None: ... class SequenceNode(CollectionNode): diff --git a/stubs/PyYAML/yaml/parser.pyi b/stubs/PyYAML/yaml/parser.pyi index 9dc41d2ae364..4949665f8153 100644 --- a/stubs/PyYAML/yaml/parser.pyi +++ b/stubs/PyYAML/yaml/parser.pyi @@ -1,32 +1,35 @@ -from typing import Any +from _typeshed import Incomplete +from builtins import _ClassInfo +from typing import Final from yaml.error import MarkedYAMLError +from yaml.events import DocumentEndEvent, MappingEndEvent, ScalarEvent, StreamStartEvent class ParserError(MarkedYAMLError): ... class Parser: - DEFAULT_TAGS: Any - current_event: Any - yaml_version: Any - tag_handles: Any - states: Any - marks: Any - state: Any + DEFAULT_TAGS: Final[dict[str, str]] + current_event: Incomplete + yaml_version: Incomplete + tag_handles: dict[str, str] + states: list[Incomplete] + marks: list[Incomplete] + state: Incomplete def __init__(self) -> None: ... - def dispose(self): ... - def check_event(self, *choices): ... + def dispose(self) -> None: ... + def check_event(self, *choices: _ClassInfo) -> bool: ... def peek_event(self): ... def get_event(self): ... - def parse_stream_start(self): ... + def parse_stream_start(self) -> StreamStartEvent: ... def parse_implicit_document_start(self): ... def parse_document_start(self): ... - def parse_document_end(self): ... + def parse_document_end(self) -> DocumentEndEvent: ... def parse_document_content(self): ... def process_directives(self): ... def parse_block_node(self): ... def parse_flow_node(self): ... def parse_block_node_or_indentless_sequence(self): ... - def parse_node(self, block=..., indentless_sequence=...): ... + def parse_node(self, block: bool = False, indentless_sequence: bool = False): ... def parse_block_sequence_first_entry(self): ... def parse_block_sequence_entry(self): ... def parse_indentless_sequence_entry(self): ... @@ -34,12 +37,14 @@ class Parser: def parse_block_mapping_key(self): ... def parse_block_mapping_value(self): ... def parse_flow_sequence_first_entry(self): ... - def parse_flow_sequence_entry(self, first=...): ... + def parse_flow_sequence_entry(self, first: bool = False): ... def parse_flow_sequence_entry_mapping_key(self): ... def parse_flow_sequence_entry_mapping_value(self): ... - def parse_flow_sequence_entry_mapping_end(self): ... + def parse_flow_sequence_entry_mapping_end(self) -> MappingEndEvent: ... def parse_flow_mapping_first_key(self): ... - def parse_flow_mapping_key(self, first=...): ... + def parse_flow_mapping_key(self, first: bool = False): ... def parse_flow_mapping_value(self): ... - def parse_flow_mapping_empty_value(self): ... - def process_empty_scalar(self, mark): ... + def parse_flow_mapping_empty_value(self) -> ScalarEvent: ... + def process_empty_scalar(self, mark) -> ScalarEvent: ... + +__all__ = ["Parser", "ParserError"] diff --git a/stubs/PyYAML/yaml/reader.pyi b/stubs/PyYAML/yaml/reader.pyi index 18c3c7a9ab5b..cb01d3ca7c8b 100644 --- a/stubs/PyYAML/yaml/reader.pyi +++ b/stubs/PyYAML/yaml/reader.pyi @@ -1,35 +1,41 @@ -from typing import Any +from _typeshed import Incomplete, SupportsRead +from re import Pattern +from typing import Final, TypeAlias -from yaml.error import YAMLError +from yaml.error import Mark, YAMLError + +_ReadStream: TypeAlias = str | bytes | SupportsRead[str] | SupportsRead[bytes] class ReaderError(YAMLError): - name: Any - character: Any - position: Any - encoding: Any - reason: Any + name: Incomplete + character: Incomplete + position: Incomplete + encoding: Incomplete + reason: Incomplete def __init__(self, name, position, character, encoding, reason) -> None: ... class Reader: - name: Any - stream: Any - stream_pointer: Any - eof: Any - buffer: Any - pointer: Any - raw_buffer: Any - raw_decode: Any - encoding: Any - index: Any - line: Any - column: Any - def __init__(self, stream) -> None: ... - def peek(self, index=...): ... - def prefix(self, length=...): ... - def forward(self, length=...): ... - def get_mark(self): ... - def determine_encoding(self): ... - NON_PRINTABLE: Any - def check_printable(self, data): ... - def update(self, length): ... - def update_raw(self, size=...): ... + name: Incomplete + stream: SupportsRead[str] | SupportsRead[bytes] | None + stream_pointer: Incomplete + eof: Incomplete + buffer: Incomplete + pointer: Incomplete + raw_buffer: Incomplete + raw_decode: Incomplete + encoding: Incomplete + index: Incomplete + line: Incomplete + column: Incomplete + def __init__(self, stream: _ReadStream) -> None: ... + def peek(self, index: int = 0): ... + def prefix(self, length: int = 1): ... + def forward(self, length: int = 1) -> None: ... + def get_mark(self) -> Mark: ... + def determine_encoding(self) -> None: ... + NON_PRINTABLE: Final[Pattern[str]] + def check_printable(self, data: str) -> None: ... + def update(self, length: int) -> None: ... + def update_raw(self, size: int = 4096) -> None: ... + +__all__ = ["Reader", "ReaderError"] diff --git a/stubs/PyYAML/yaml/representer.pyi b/stubs/PyYAML/yaml/representer.pyi index 298788a79ea1..38255a636d49 100644 --- a/stubs/PyYAML/yaml/representer.pyi +++ b/stubs/PyYAML/yaml/representer.pyi @@ -1,37 +1,40 @@ import datetime -from _typeshed import SupportsItems +from _typeshed import Incomplete, ReadableBuffer, SupportsItems from collections.abc import Callable, Iterable, Mapping from types import BuiltinFunctionType, FunctionType, ModuleType -from typing import Any, ClassVar, NoReturn, Type, TypeVar +from typing import ClassVar, TypeVar +from typing_extensions import Never, Self from yaml.error import YAMLError as YAMLError from yaml.nodes import MappingNode as MappingNode, Node as Node, ScalarNode as ScalarNode, SequenceNode as SequenceNode _T = TypeVar("_T") -_R = TypeVar("_R", bound=BaseRepresenter) class RepresenterError(YAMLError): ... class BaseRepresenter: - yaml_representers: ClassVar[dict[Type[Any], Callable[[BaseRepresenter, Any], Node]]] - yaml_multi_representers: ClassVar[dict[Type[Any], Callable[[BaseRepresenter, Any], Node]]] - default_style: str | Any + yaml_representers: ClassVar[dict[type[Incomplete], Callable[[BaseRepresenter, Incomplete], Node]]] + yaml_multi_representers: ClassVar[dict[type[Incomplete], Callable[[BaseRepresenter, Incomplete], Node]]] + default_style: str | Incomplete sort_keys: bool default_flow_style: bool represented_objects: dict[int, Node] - object_keeper: list[Any] - alias_key: int | Any - def __init__(self, default_style: str | None = ..., default_flow_style: bool = ..., sort_keys: bool = ...) -> None: ... + object_keeper: list[Incomplete] + alias_key: int | Incomplete + def __init__(self, default_style: str | None = None, default_flow_style: bool = False, sort_keys: bool = True) -> None: ... def represent(self, data) -> None: ... def represent_data(self, data) -> Node: ... @classmethod - def add_representer(cls: Type[_R], data_type: Type[_T], representer: Callable[[_R, _T], Node]) -> None: ... + def add_representer(cls, data_type: type[_T], representer: Callable[[Self, _T], Node]) -> None: ... @classmethod - def add_multi_representer(cls: Type[_R], data_type: Type[_T], representer: Callable[[_R, _T], Node]) -> None: ... - def represent_scalar(self, tag: str, value, style: str | None = ...) -> ScalarNode: ... - def represent_sequence(self, tag: str, sequence: Iterable[Any], flow_style: bool | None = ...) -> SequenceNode: ... + def add_multi_representer(cls, data_type: type[_T], representer: Callable[[Self, _T], Node]) -> None: ... + def represent_scalar(self, tag: str, value, style: str | None = None) -> ScalarNode: ... + def represent_sequence(self, tag: str, sequence: Iterable[Incomplete], flow_style: bool | None = None) -> SequenceNode: ... def represent_mapping( - self, tag: str, mapping: SupportsItems[Any, Any] | Iterable[tuple[Any, Any]], flow_style: bool | None = ... + self, + tag: str, + mapping: SupportsItems[Incomplete, Incomplete] | Iterable[tuple[Incomplete, Incomplete]], + flow_style: bool | None = None, ) -> MappingNode: ... def ignore_aliases(self, data) -> bool: ... @@ -40,22 +43,26 @@ class SafeRepresenter(BaseRepresenter): def ignore_aliases(self, data) -> bool: ... def represent_none(self, data) -> ScalarNode: ... def represent_str(self, data: str) -> ScalarNode: ... - def represent_binary(self, data: bytes) -> ScalarNode: ... + def represent_binary(self, data: ReadableBuffer) -> ScalarNode: ... def represent_bool(self, data: bool) -> ScalarNode: ... def represent_int(self, data: int) -> ScalarNode: ... def represent_float(self, data: float) -> ScalarNode: ... - def represent_list(self, data: Iterable[Any]) -> SequenceNode: ... - def represent_dict(self, data: SupportsItems[Any, Any] | Iterable[tuple[Any, Any]]) -> MappingNode: ... - def represent_set(self, data: Iterable[Any]) -> MappingNode: ... + def represent_list(self, data: Iterable[Incomplete]) -> SequenceNode: ... + def represent_dict( + self, data: SupportsItems[Incomplete, Incomplete] | Iterable[tuple[Incomplete, Incomplete]] + ) -> MappingNode: ... + def represent_set(self, data: Iterable[Incomplete]) -> MappingNode: ... def represent_date(self, data: datetime.date) -> ScalarNode: ... def represent_datetime(self, data: datetime.datetime) -> ScalarNode: ... - def represent_yaml_object(self, tag: str, data, cls, flow_style: bool | None = ...) -> MappingNode: ... - def represent_undefined(self, data) -> NoReturn: ... + def represent_yaml_object(self, tag: str, data, cls, flow_style: bool | None = None) -> MappingNode: ... + def represent_undefined(self, data) -> Never: ... class Representer(SafeRepresenter): def represent_complex(self, data: complex) -> ScalarNode: ... - def represent_tuple(self, data: Iterable[Any]) -> SequenceNode: ... + def represent_tuple(self, data: Iterable[Incomplete]) -> SequenceNode: ... def represent_name(self, data: BuiltinFunctionType | FunctionType) -> ScalarNode: ... def represent_module(self, data: ModuleType) -> ScalarNode: ... def represent_object(self, data) -> SequenceNode | MappingNode: ... - def represent_ordered_dict(self, data: Mapping[Any, Any]) -> SequenceNode: ... + def represent_ordered_dict(self, data: Mapping[Incomplete, Incomplete]) -> SequenceNode: ... + +__all__ = ["BaseRepresenter", "SafeRepresenter", "Representer", "RepresenterError"] diff --git a/stubs/PyYAML/yaml/resolver.pyi b/stubs/PyYAML/yaml/resolver.pyi index f5f534dee4f5..2df705d34825 100644 --- a/stubs/PyYAML/yaml/resolver.pyi +++ b/stubs/PyYAML/yaml/resolver.pyi @@ -1,25 +1,28 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Final from yaml.error import YAMLError class ResolverError(YAMLError): ... class BaseResolver: - DEFAULT_SCALAR_TAG: Any - DEFAULT_SEQUENCE_TAG: Any - DEFAULT_MAPPING_TAG: Any - yaml_implicit_resolvers: Any - yaml_path_resolvers: Any - resolver_exact_paths: Any - resolver_prefix_paths: Any + DEFAULT_SCALAR_TAG: Final = "tag:yaml.org,2002:str" + DEFAULT_SEQUENCE_TAG: Final = "tag:yaml.org,2002:seq" + DEFAULT_MAPPING_TAG: Final = "tag:yaml.org,2002:map" + yaml_implicit_resolvers: dict[Incomplete, Incomplete] + yaml_path_resolvers: dict[Incomplete, Incomplete] + resolver_exact_paths: list[Incomplete] + resolver_prefix_paths: list[Incomplete] def __init__(self) -> None: ... @classmethod - def add_implicit_resolver(cls, tag, regexp, first): ... + def add_implicit_resolver(cls, tag, regexp, first) -> None: ... @classmethod - def add_path_resolver(cls, tag, path, kind=...): ... - def descend_resolver(self, current_node, current_index): ... - def ascend_resolver(self): ... + def add_path_resolver(cls, tag, path, kind=None) -> None: ... + def descend_resolver(self, current_node, current_index) -> None: ... + def ascend_resolver(self) -> None: ... def check_resolver_prefix(self, depth, path, kind, current_node, current_index): ... def resolve(self, kind, value, implicit): ... class Resolver(BaseResolver): ... + +__all__ = ["BaseResolver", "Resolver"] diff --git a/stubs/PyYAML/yaml/scanner.pyi b/stubs/PyYAML/yaml/scanner.pyi index 64890a19a5f6..64c1dfe486c1 100644 --- a/stubs/PyYAML/yaml/scanner.pyi +++ b/stubs/PyYAML/yaml/scanner.pyi @@ -1,97 +1,102 @@ -from typing import Any +from _typeshed import Incomplete +from builtins import _ClassInfo +from typing import Final from yaml.error import MarkedYAMLError +from yaml.tokens import DirectiveToken, ScalarToken, TagToken class ScannerError(MarkedYAMLError): ... class SimpleKey: - token_number: Any - required: Any - index: Any - line: Any - column: Any - mark: Any - def __init__(self, token_number, required, index, line, column, mark) -> None: ... + token_number: Incomplete + required: bool + index: Incomplete + line: Incomplete + column: Incomplete + mark: Incomplete + def __init__(self, token_number, required: bool, index, line, column, mark) -> None: ... class Scanner: - done: Any - flow_level: Any - tokens: Any - tokens_taken: Any - indent: Any - indents: Any - allow_simple_key: Any - possible_simple_keys: Any + done: bool + flow_level: int + tokens: list[Incomplete] + tokens_taken: int + indent: int + indents: list[int] + allow_simple_key: bool + possible_simple_keys: dict[int, SimpleKey] def __init__(self) -> None: ... - def check_token(self, *choices): ... + def check_token(self, *choices: _ClassInfo) -> bool: ... def peek_token(self): ... def get_token(self): ... - def need_more_tokens(self): ... - def fetch_more_tokens(self): ... + def need_more_tokens(self) -> bool | None: ... + def fetch_more_tokens(self) -> None: ... def next_possible_simple_key(self): ... - def stale_possible_simple_keys(self): ... - def save_possible_simple_key(self): ... - def remove_possible_simple_key(self): ... - def unwind_indent(self, column): ... - def add_indent(self, column): ... - def fetch_stream_start(self): ... - def fetch_stream_end(self): ... - def fetch_directive(self): ... - def fetch_document_start(self): ... - def fetch_document_end(self): ... - def fetch_document_indicator(self, TokenClass): ... - def fetch_flow_sequence_start(self): ... - def fetch_flow_mapping_start(self): ... - def fetch_flow_collection_start(self, TokenClass): ... - def fetch_flow_sequence_end(self): ... - def fetch_flow_mapping_end(self): ... - def fetch_flow_collection_end(self, TokenClass): ... - def fetch_flow_entry(self): ... - def fetch_block_entry(self): ... - def fetch_key(self): ... - def fetch_value(self): ... - def fetch_alias(self): ... - def fetch_anchor(self): ... - def fetch_tag(self): ... - def fetch_literal(self): ... - def fetch_folded(self): ... - def fetch_block_scalar(self, style): ... - def fetch_single(self): ... - def fetch_double(self): ... - def fetch_flow_scalar(self, style): ... - def fetch_plain(self): ... + def stale_possible_simple_keys(self) -> None: ... + def save_possible_simple_key(self) -> None: ... + def remove_possible_simple_key(self) -> None: ... + def unwind_indent(self, column) -> None: ... + def add_indent(self, column) -> bool: ... + def fetch_stream_start(self) -> None: ... + def fetch_stream_end(self) -> None: ... + def fetch_directive(self) -> None: ... + def fetch_document_start(self) -> None: ... + def fetch_document_end(self) -> None: ... + def fetch_document_indicator(self, TokenClass) -> None: ... + def fetch_flow_sequence_start(self) -> None: ... + def fetch_flow_mapping_start(self) -> None: ... + def fetch_flow_collection_start(self, TokenClass) -> None: ... + def fetch_flow_sequence_end(self) -> None: ... + def fetch_flow_mapping_end(self) -> None: ... + def fetch_flow_collection_end(self, TokenClass) -> None: ... + def fetch_flow_entry(self) -> None: ... + def fetch_block_entry(self) -> None: ... + def fetch_key(self) -> None: ... + def fetch_value(self) -> None: ... + def fetch_alias(self) -> None: ... + def fetch_anchor(self) -> None: ... + def fetch_tag(self) -> None: ... + def fetch_literal(self) -> None: ... + def fetch_folded(self) -> None: ... + def fetch_block_scalar(self, style) -> None: ... + def fetch_single(self) -> None: ... + def fetch_double(self) -> None: ... + def fetch_flow_scalar(self, style) -> None: ... + def fetch_plain(self) -> None: ... def check_directive(self): ... def check_document_start(self): ... def check_document_end(self): ... - def check_block_entry(self): ... - def check_key(self): ... - def check_value(self): ... - def check_plain(self): ... - def scan_to_next_token(self): ... - def scan_directive(self): ... + def check_block_entry(self) -> bool: ... + def check_key(self) -> bool: ... + def check_value(self) -> bool: ... + def check_plain(self) -> bool: ... + def scan_to_next_token(self) -> None: ... + def scan_directive(self) -> DirectiveToken: ... def scan_directive_name(self, start_mark): ... - def scan_yaml_directive_value(self, start_mark): ... - def scan_yaml_directive_number(self, start_mark): ... - def scan_tag_directive_value(self, start_mark): ... + def scan_yaml_directive_value(self, start_mark) -> tuple[int, int]: ... + def scan_yaml_directive_number(self, start_mark) -> int: ... + def scan_tag_directive_value(self, start_mark) -> tuple[Incomplete, str]: ... def scan_tag_directive_handle(self, start_mark): ... - def scan_tag_directive_prefix(self, start_mark): ... - def scan_directive_ignored_line(self, start_mark): ... + def scan_tag_directive_prefix(self, start_mark) -> str: ... + def scan_directive_ignored_line(self, start_mark) -> None: ... def scan_anchor(self, TokenClass): ... - def scan_tag(self): ... - def scan_block_scalar(self, style): ... - def scan_block_scalar_indicators(self, start_mark): ... - def scan_block_scalar_ignored_line(self, start_mark): ... - def scan_block_scalar_indentation(self): ... - def scan_block_scalar_breaks(self, indent): ... - def scan_flow_scalar(self, style): ... - ESCAPE_REPLACEMENTS: Any - ESCAPE_CODES: Any - def scan_flow_scalar_non_spaces(self, double, start_mark): ... - def scan_flow_scalar_spaces(self, double, start_mark): ... - def scan_flow_scalar_breaks(self, double, start_mark): ... - def scan_plain(self): ... - def scan_plain_spaces(self, indent, start_mark): ... + def scan_tag(self) -> TagToken: ... + def scan_block_scalar(self, style) -> ScalarToken: ... + def scan_block_scalar_indicators(self, start_mark) -> tuple[bool | None, int | None]: ... + def scan_block_scalar_ignored_line(self, start_mark) -> None: ... + def scan_block_scalar_indentation(self) -> tuple[list[Incomplete], int, Incomplete]: ... + def scan_block_scalar_breaks(self, indent) -> tuple[list[Incomplete], Incomplete]: ... + def scan_flow_scalar(self, style) -> ScalarToken: ... + ESCAPE_REPLACEMENTS: Final[dict[str, str]] + ESCAPE_CODES: Final[dict[str, int]] + def scan_flow_scalar_non_spaces(self, double, start_mark) -> list[Incomplete]: ... + def scan_flow_scalar_spaces(self, double, start_mark) -> list[Incomplete]: ... + def scan_flow_scalar_breaks(self, double, start_mark) -> list[Incomplete]: ... + def scan_plain(self) -> ScalarToken: ... + def scan_plain_spaces(self, indent, start_mark) -> list[Incomplete] | None: ... def scan_tag_handle(self, name, start_mark): ... - def scan_tag_uri(self, name, start_mark): ... - def scan_uri_escapes(self, name, start_mark): ... + def scan_tag_uri(self, name, start_mark) -> str: ... + def scan_uri_escapes(self, name, start_mark) -> str: ... def scan_line_break(self): ... + +__all__ = ["Scanner", "ScannerError"] diff --git a/stubs/PyYAML/yaml/serializer.pyi b/stubs/PyYAML/yaml/serializer.pyi index 8b85e3e45eba..16b4ebccda1a 100644 --- a/stubs/PyYAML/yaml/serializer.pyi +++ b/stubs/PyYAML/yaml/serializer.pyi @@ -1,24 +1,28 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar from yaml.error import YAMLError +from yaml.nodes import Node class SerializerError(YAMLError): ... class Serializer: - ANCHOR_TEMPLATE: Any - use_encoding: Any - use_explicit_start: Any - use_explicit_end: Any - use_version: Any - use_tags: Any - serialized_nodes: Any - anchors: Any - last_anchor_id: Any - closed: Any - def __init__(self, encoding=..., explicit_start=..., explicit_end=..., version=..., tags=...) -> None: ... - def open(self): ... - def close(self): ... - def serialize(self, node): ... - def anchor_node(self, node): ... - def generate_anchor(self, node): ... - def serialize_node(self, node, parent, index): ... + ANCHOR_TEMPLATE: ClassVar[str] + use_encoding: Incomplete + use_explicit_start: Incomplete + use_explicit_end: Incomplete + use_version: Incomplete + use_tags: Incomplete + serialized_nodes: dict[Incomplete, Incomplete] + anchors: dict[Incomplete, Incomplete] + last_anchor_id: int + closed: bool | None + def __init__(self, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None) -> None: ... + def open(self) -> None: ... + def close(self) -> None: ... + def serialize(self, node: Node) -> None: ... + def anchor_node(self, node) -> None: ... + def generate_anchor(self, node) -> str: ... + def serialize_node(self, node, parent, index) -> None: ... + +__all__ = ["Serializer", "SerializerError"] diff --git a/stubs/PyYAML/yaml/tokens.pyi b/stubs/PyYAML/yaml/tokens.pyi index b258ec7b2e4b..1034b5791786 100644 --- a/stubs/PyYAML/yaml/tokens.pyi +++ b/stubs/PyYAML/yaml/tokens.pyi @@ -1,93 +1,94 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar class Token: - start_mark: Any - end_mark: Any + start_mark: Incomplete + end_mark: Incomplete def __init__(self, start_mark, end_mark) -> None: ... class DirectiveToken(Token): - id: Any - name: Any - value: Any - start_mark: Any - end_mark: Any + id: ClassVar[str] + name: Incomplete + value: Incomplete + start_mark: Incomplete + end_mark: Incomplete def __init__(self, name, value, start_mark, end_mark) -> None: ... class DocumentStartToken(Token): - id: Any + id: ClassVar[str] class DocumentEndToken(Token): - id: Any + id: ClassVar[str] class StreamStartToken(Token): - id: Any - start_mark: Any - end_mark: Any - encoding: Any - def __init__(self, start_mark=..., end_mark=..., encoding=...) -> None: ... + id: ClassVar[str] + start_mark: Incomplete + end_mark: Incomplete + encoding: Incomplete + def __init__(self, start_mark=None, end_mark=None, encoding=None) -> None: ... class StreamEndToken(Token): - id: Any + id: ClassVar[str] class BlockSequenceStartToken(Token): - id: Any + id: ClassVar[str] class BlockMappingStartToken(Token): - id: Any + id: ClassVar[str] class BlockEndToken(Token): - id: Any + id: ClassVar[str] class FlowSequenceStartToken(Token): - id: Any + id: ClassVar[str] class FlowMappingStartToken(Token): - id: Any + id: ClassVar[str] class FlowSequenceEndToken(Token): - id: Any + id: ClassVar[str] class FlowMappingEndToken(Token): - id: Any + id: ClassVar[str] class KeyToken(Token): - id: Any + id: ClassVar[str] class ValueToken(Token): - id: Any + id: ClassVar[str] class BlockEntryToken(Token): - id: Any + id: ClassVar[str] class FlowEntryToken(Token): - id: Any + id: ClassVar[str] class AliasToken(Token): - id: Any - value: Any - start_mark: Any - end_mark: Any + id: ClassVar[str] + value: Incomplete + start_mark: Incomplete + end_mark: Incomplete def __init__(self, value, start_mark, end_mark) -> None: ... class AnchorToken(Token): - id: Any - value: Any - start_mark: Any - end_mark: Any + id: ClassVar[str] + value: Incomplete + start_mark: Incomplete + end_mark: Incomplete def __init__(self, value, start_mark, end_mark) -> None: ... class TagToken(Token): - id: Any - value: Any - start_mark: Any - end_mark: Any + id: ClassVar[str] + value: Incomplete + start_mark: Incomplete + end_mark: Incomplete def __init__(self, value, start_mark, end_mark) -> None: ... class ScalarToken(Token): - id: Any - value: Any - plain: Any - start_mark: Any - end_mark: Any - style: Any - def __init__(self, value, plain, start_mark, end_mark, style=...) -> None: ... + id: ClassVar[str] + value: Incomplete + plain: Incomplete + start_mark: Incomplete + end_mark: Incomplete + style: Incomplete + def __init__(self, value, plain, start_mark, end_mark, style=None) -> None: ... diff --git a/stubs/Pygments/@tests/requirements-stubtest.txt b/stubs/Pygments/@tests/requirements-stubtest.txt deleted file mode 100644 index 6966869c7054..000000000000 --- a/stubs/Pygments/@tests/requirements-stubtest.txt +++ /dev/null @@ -1 +0,0 @@ -sphinx diff --git a/stubs/Pygments/@tests/stubtest_allowlist.txt b/stubs/Pygments/@tests/stubtest_allowlist.txt index 00d6b1e0eb2f..e4edf8e46e26 100644 --- a/stubs/Pygments/@tests/stubtest_allowlist.txt +++ b/stubs/Pygments/@tests/stubtest_allowlist.txt @@ -2,11 +2,19 @@ pygments.lexer.LexerMeta.__new__ pygments.style.StyleMeta.__new__ -# Defined in lexer classes, intended to be used as static method, but doesn't use @staticmethod -pygments.lexer.LexerMeta.analyse_text - -# Inheriting from tuple seems to do something weird -pygments.token.Number -pygments.token.String -pygments.token.Token -pygments.token.Whitespace +# Inheriting from tuple is weird +pygments.token._TokenType.__init__ + +# Cannot import in stubtest (SystemExit: 2) +pygments.__main__ + +# Class attributes that are set to None in the base class, but are +# always overridden with a non-None value in subclasses. +pygments.lexer.Lexer.name +pygments.lexer.Lexer.url +pygments.lexer.Lexer.version_added +pygments.formatter.Formatter.name + +# Individual lexers and styles submodules are not stubbed at this time. +pygments\.lexers\.(?!get_|find_|load_|guess_).* +pygments\.styles\.(?!get_).* diff --git a/stubs/Pygments/@tests/test_cases/check_pygments.py b/stubs/Pygments/@tests/test_cases/check_pygments.py new file mode 100644 index 000000000000..5c6fafc9b36c --- /dev/null +++ b/stubs/Pygments/@tests/test_cases/check_pygments.py @@ -0,0 +1,10 @@ +from typing_extensions import assert_type + +from pygments.style import Style, _StyleDict +from pygments.token import _TokenType + + +def test_style_class_iterable(style_class: type[Style]) -> None: + for t, d in style_class: + assert_type(t, _TokenType) + assert_type(d, _StyleDict) diff --git a/stubs/Pygments/METADATA.toml b/stubs/Pygments/METADATA.toml index 92f28ce99d9c..ad60f7038a31 100644 --- a/stubs/Pygments/METADATA.toml +++ b/stubs/Pygments/METADATA.toml @@ -1,2 +1,7 @@ -version = "2.9.*" -requires = ["types-docutils"] +version = "2.21.*" +upstream-repository = "https://github.com/pygments/pygments" +optional-dependencies = ["types-docutils"] +partial-stub = true + +[tool.stubtest] +stubtest-dependencies = ["sphinx"] diff --git a/stubs/Pygments/pygments/__init__.pyi b/stubs/Pygments/pygments/__init__.pyi index 1b05e273a1d3..d5fab4ab32db 100644 --- a/stubs/Pygments/pygments/__init__.pyi +++ b/stubs/Pygments/pygments/__init__.pyi @@ -1,5 +1,25 @@ -from typing import Any +from _typeshed import SupportsWrite +from collections.abc import Iterable, Iterator +from typing import Final, TypeVar, overload -def lex(code, lexer): ... -def format(tokens, formatter, outfile: Any | None = ...): ... -def highlight(code, lexer, formatter, outfile: Any | None = ...): ... +from pygments.formatter import Formatter +from pygments.lexer import Lexer +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__version__: Final[str] +__docformat__: Final = "restructuredtext" +__all__ = ["lex", "format", "highlight"] + +def lex(code: str, lexer: Lexer) -> Iterator[tuple[_TokenType, str]]: ... + +@overload +def format(tokens: Iterable[tuple[_TokenType, str]], formatter: Formatter[_T], outfile: SupportsWrite[_T]) -> None: ... +@overload +def format(tokens: Iterable[tuple[_TokenType, str]], formatter: Formatter[_T], outfile: None = None) -> _T: ... + +@overload +def highlight(code: str, lexer: Lexer, formatter: Formatter[_T], outfile: SupportsWrite[_T]) -> None: ... +@overload +def highlight(code: str, lexer: Lexer, formatter: Formatter[_T], outfile: None = None) -> _T: ... diff --git a/stubs/Pygments/pygments/cmdline.pyi b/stubs/Pygments/pygments/cmdline.pyi index 2226b9834a53..a99805b67040 100644 --- a/stubs/Pygments/pygments/cmdline.pyi +++ b/stubs/Pygments/pygments/cmdline.pyi @@ -1,9 +1,9 @@ import argparse -from typing import Any +from collections.abc import Sequence -def main_inner(parser, argns): ... +def main_inner(parser: argparse.ArgumentParser, argns: argparse.Namespace) -> int: ... class HelpFormatter(argparse.HelpFormatter): - def __init__(self, prog, indent_increment: int = ..., max_help_position: int = ..., width: Any | None = ...) -> None: ... + def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 16, width: int | None = None) -> None: ... -def main(args=...): ... +def main(args: Sequence[str] | None = ...) -> int: ... diff --git a/stubs/Pygments/pygments/console.pyi b/stubs/Pygments/pygments/console.pyi index 0de5c60fba94..d76f250ab6fe 100644 --- a/stubs/Pygments/pygments/console.pyi +++ b/stubs/Pygments/pygments/console.pyi @@ -1,10 +1,10 @@ -from typing import Any +from typing import Final -esc: str -codes: Any -dark_colors: Any -light_colors: Any +esc: Final = "\x1b[" +codes: Final[dict[str, str]] +dark_colors: Final[list[str]] +light_colors: Final[list[str]] -def reset_color(): ... -def colorize(color_key, text): ... -def ansiformat(attr, text): ... +def reset_color() -> str: ... +def colorize(color_key: str, text: str) -> str: ... +def ansiformat(attr: str, text: str) -> str: ... diff --git a/stubs/Pygments/pygments/filter.pyi b/stubs/Pygments/pygments/filter.pyi index b1437328bca1..6f05bbdddeb0 100644 --- a/stubs/Pygments/pygments/filter.pyi +++ b/stubs/Pygments/pygments/filter.pyi @@ -1,18 +1,29 @@ from collections.abc import Iterable, Iterator -from typing import Any +from typing import Any, ClassVar, Protocol, type_check_only from pygments.lexer import Lexer from pygments.token import _TokenType -def apply_filters(stream, filters, lexer: Any | None = ...): ... -def simplefilter(f): ... +@type_check_only +class _SimpleFilterFunction(Protocol): + # Function that can looked up as a method on a FunctionFilter subclass. + def __call__( + self, self_: FunctionFilter, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]], options: dict[str, Any], / + ) -> Iterator[tuple[_TokenType, str]]: ... + +def apply_filters( + stream: Iterable[tuple[_TokenType, str]], filters: Iterable[Filter], lexer: Lexer | None = None +) -> Iterator[tuple[_TokenType, str]]: ... +def simplefilter(f: _SimpleFilterFunction) -> type[FunctionFilter]: ... class Filter: - options: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + options: dict[str, Any] # Arbitrary values used by subclasses. + def __init__(self, **options: Any) -> None: ... # ditto. + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class FunctionFilter(Filter): - function: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + # Set to None in class, but overridden with a non-None value in the subclasses created by @simplefilter. + function: ClassVar[_SimpleFilterFunction] + # 'options' gets passed as a dict to 'function'; valid types depends on the wrapped function's signature. + def __init__(self, **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... diff --git a/stubs/Pygments/pygments/filters/__init__.pyi b/stubs/Pygments/pygments/filters/__init__.pyi index 15f60f43d57d..b43a8e9ef047 100644 --- a/stubs/Pygments/pygments/filters/__init__.pyi +++ b/stubs/Pygments/pygments/filters/__init__.pyi @@ -1,58 +1,86 @@ -from collections.abc import Iterable, Iterator -from typing import Any +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Generator, Iterable, Iterator +from re import Pattern +from typing import Any, ClassVar, Final, Literal from pygments.filter import Filter from pygments.lexer import Lexer from pygments.token import _TokenType -def find_filter_class(filtername): ... -def get_filter_by_name(filtername, **options): ... -def get_all_filters(): ... +def find_filter_class(filtername: str) -> type[Filter] | None: ... + +# Keyword arguments are forwarded to the filter class. +def get_filter_by_name(filtername: str, **options: Any) -> Filter: ... +def get_all_filters() -> Generator[str]: ... class CodeTagFilter(Filter): - tag_re: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + tag_re: Pattern[str] + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__( + self, *, codetags: str | list[str] | tuple[str, ...] = ["XXX", "TODO", "FIXME", "BUG", "NOTE"], **options: Any + ) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class SymbolFilter(Filter): - latex_symbols: Any - isabelle_symbols: Any - lang_map: Any - symbols: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + latex_symbols: ClassVar[dict[str, str]] + isabelle_symbols: ClassVar[dict[str, str]] + lang_map: ClassVar[dict[Literal["isabelle", "latex"], dict[str, str]]] + symbols: dict[str, str] # One of latex_symbols or isabelle_symbols. + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, lang: Literal["isabelle", "latex"] = "isabelle", **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class KeywordCaseFilter(Filter): - convert: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + convert: Callable[[str], str] + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, case: Literal["lower", "upper", "capitalize"] = "lower", **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class NameHighlightFilter(Filter): - names: Any - tokentype: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + names: set[str] + tokentype: _TokenType + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__( + self, *, names: str | list[str] | tuple[str, ...] = [], tokentype: str | _TokenType | None = None, **options: Any + ) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class ErrorToken(Exception): ... class RaiseOnErrorTokenFilter(Filter): - exception: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + exception: type[Exception] + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, excclass: type[Exception] = ..., **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class VisibleWhitespaceFilter(Filter): - wstt: Any - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + spaces: str + tabs: str + newlines: str + wstt: bool + def __init__( + self, + *, + spaces: str | bool = False, + tabs: str | bool = False, + newlines: str | bool = False, + tabsize: ConvertibleToInt = 8, + wstokentype: bool | int | str = True, # Any value accepted by get_bool_opt. + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + **options: Any, + ) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class GobbleFilter(Filter): - n: Any - def __init__(self, **options) -> None: ... - def gobble(self, value, left): ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + n: int + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, n: ConvertibleToInt = 0, **options: Any) -> None: ... + def gobble(self, value: str, left: int) -> tuple[str, int]: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... class TokenMergeFilter(Filter): - def __init__(self, **options) -> None: ... - def filter(self, lexer: Lexer, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... -FILTERS: Any +FILTERS: Final[dict[str, type[Filter]]] diff --git a/stubs/Pygments/pygments/formatter.pyi b/stubs/Pygments/pygments/formatter.pyi index 1fbf82f19956..94c4dcdb65f1 100644 --- a/stubs/Pygments/pygments/formatter.pyi +++ b/stubs/Pygments/pygments/formatter.pyi @@ -1,15 +1,60 @@ -from typing import Any - -class Formatter: - name: Any - aliases: Any - filenames: Any - unicodeoutput: bool - style: Any - full: Any - title: Any - encoding: Any - options: Any - def __init__(self, **options) -> None: ... - def get_style_defs(self, arg: str = ...): ... - def format(self, tokensource, outfile): ... +import types +from _typeshed import SupportsWrite +from collections.abc import Iterable, Sequence +from typing import Any, ClassVar, Generic, TypeVar, overload + +from pygments.style import Style +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["Formatter"] + +class Formatter(Generic[_T]): + name: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + aliases: ClassVar[Sequence[str]] # Not intended to be mutable + filenames: ClassVar[Sequence[str]] # Not intended to be mutable + unicodeoutput: ClassVar[bool] + style: type[Style] + full: bool + title: str + encoding: str | None + options: dict[str, Any] # arbitrary values used by subclasses + + @overload + def __init__( + self: Formatter[str], + *, + style: type[Style] | str = "default", + full: bool = False, + title: str = "", + encoding: None = None, + outencoding: None = None, + **options: Any, # arbitrary values used by subclasses + ) -> None: ... + @overload + def __init__( + self: Formatter[bytes], + *, + style: type[Style] | str = "default", + full: bool = False, + title: str = "", + encoding: str, + outencoding: None = None, + **options: Any, # arbitrary values used by subclasses + ) -> None: ... + @overload + def __init__( + self: Formatter[bytes], + *, + style: type[Style] | str = "default", + full: bool = False, + title: str = "", + encoding: None = None, + outencoding: str, + **options: Any, # arbitrary values used by subclasses + ) -> None: ... + + def __class_getitem__(cls, name: Any) -> types.GenericAlias: ... + def get_style_defs(self, arg: str = "") -> str: ... + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/__init__.pyi b/stubs/Pygments/pygments/formatters/__init__.pyi index b77043bb31e1..5fdd2e310cf3 100644 --- a/stubs/Pygments/pygments/formatters/__init__.pyi +++ b/stubs/Pygments/pygments/formatters/__init__.pyi @@ -1,7 +1,9 @@ -from typing import Generator, Type +from _typeshed import Incomplete +from collections.abc import Generator from ..formatter import Formatter from .bbcode import BBCodeFormatter as BBCodeFormatter +from .groff import GroffFormatter as GroffFormatter from .html import HtmlFormatter as HtmlFormatter from .img import ( BmpImageFormatter as BmpImageFormatter, @@ -18,7 +20,32 @@ from .svg import SvgFormatter as SvgFormatter from .terminal import TerminalFormatter as TerminalFormatter from .terminal256 import Terminal256Formatter as Terminal256Formatter, TerminalTrueColorFormatter as TerminalTrueColorFormatter -def get_all_formatters() -> Generator[Type[Formatter], None, None]: ... +__all__ = [ + "get_formatter_by_name", + "get_formatter_for_filename", + "get_all_formatters", + "load_formatter_from_file", + "BBCodeFormatter", + "BmpImageFormatter", + "GifImageFormatter", + "GroffFormatter", + "HtmlFormatter", + "IRCFormatter", + "ImageFormatter", + "JpgImageFormatter", + "LatexFormatter", + "NullFormatter", + "PangoMarkupFormatter", + "RawTokenFormatter", + "RtfFormatter", + "SvgFormatter", + "Terminal256Formatter", + "TerminalFormatter", + "TerminalTrueColorFormatter", + "TestcaseFormatter", +] + +def get_all_formatters() -> Generator[type[Formatter[Incomplete]]]: ... def get_formatter_by_name(_alias, **options): ... -def load_formatter_from_file(filename, formattername: str = ..., **options): ... +def load_formatter_from_file(filename, formattername: str = "CustomFormatter", **options): ... def get_formatter_for_filename(fn, **options): ... diff --git a/stubs/Pygments/pygments/formatters/_mapping.pyi b/stubs/Pygments/pygments/formatters/_mapping.pyi index a9e5864b9cfe..4ca06c4415b0 100644 --- a/stubs/Pygments/pygments/formatters/_mapping.pyi +++ b/stubs/Pygments/pygments/formatters/_mapping.pyi @@ -1,3 +1,3 @@ -from typing import Any +from _typeshed import Incomplete -FORMATTERS: Any +FORMATTERS: Incomplete diff --git a/stubs/Pygments/pygments/formatters/bbcode.pyi b/stubs/Pygments/pygments/formatters/bbcode.pyi index 332c6c13a0bd..2e596b6ec396 100644 --- a/stubs/Pygments/pygments/formatters/bbcode.pyi +++ b/stubs/Pygments/pygments/formatters/bbcode.pyi @@ -1,11 +1,14 @@ -from typing import Any +from _typeshed import SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class BBCodeFormatter(Formatter): - name: str - aliases: Any - filenames: Any - styles: Any - def __init__(self, **options) -> None: ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["BBCodeFormatter"] + +class BBCodeFormatter(Formatter[_T]): + styles: dict[_TokenType, tuple[str, str]] + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/groff.pyi b/stubs/Pygments/pygments/formatters/groff.pyi new file mode 100644 index 000000000000..d6b936a2dff5 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/groff.pyi @@ -0,0 +1,18 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +__all__ = ["GroffFormatter"] + +_T = TypeVar("_T", str, bytes) + +class GroffFormatter(Formatter[_T]): + monospaced: bool + linenos: bool + wrap: int + styles: dict[_TokenType, tuple[str, str]] + def __init__(self, **options) -> None: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/html.pyi b/stubs/Pygments/pygments/formatters/html.pyi index ba3d0696d853..1354b930341a 100644 --- a/stubs/Pygments/pygments/formatters/html.pyi +++ b/stubs/Pygments/pygments/formatters/html.pyi @@ -1,40 +1,43 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class HtmlFormatter(Formatter): - name: str - aliases: Any - filenames: Any - title: Any - nowrap: Any - noclasses: Any - classprefix: Any - cssclass: Any - cssstyles: Any - prestyles: Any - cssfile: Any - noclobber_cssfile: Any - tagsfile: Any - tagurlformat: Any - filename: Any - wrapcode: Any - span_element_openers: Any +_T = TypeVar("_T", str, bytes) + +__all__ = ["HtmlFormatter"] + +class HtmlFormatter(Formatter[_T]): + title: Incomplete + nowrap: Incomplete + noclasses: Incomplete + classprefix: Incomplete + cssclass: Incomplete + cssstyles: Incomplete + prestyles: Incomplete + cssfile: Incomplete + noclobber_cssfile: Incomplete + tagsfile: Incomplete + tagurlformat: Incomplete + filename: Incomplete + wrapcode: Incomplete + span_element_openers: Incomplete linenos: int - linenostart: Any - linenostep: Any - linenospecial: Any - nobackground: Any - lineseparator: Any - lineanchors: Any - linespans: Any - anchorlinenos: Any - hl_lines: Any - def __init__(self, **options) -> None: ... - def get_style_defs(self, arg: Any | None = ...): ... - def get_token_style_defs(self, arg: Any | None = ...): ... - def get_background_style_defs(self, arg: Any | None = ...): ... + linenostart: Incomplete + linenostep: Incomplete + linenospecial: Incomplete + nobackground: Incomplete + lineseparator: Incomplete + lineanchors: Incomplete + linespans: Incomplete + anchorlinenos: Incomplete + hl_lines: Incomplete + def get_style_defs(self, arg=None): ... + def get_token_style_defs(self, arg=None): ... + def get_background_style_defs(self, arg=None): ... def get_linenos_style_defs(self): ... def get_css_prefix(self, arg): ... - def wrap(self, source, outfile): ... - def format_unencoded(self, tokensource, outfile) -> None: ... + def wrap(self, source): ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/img.pyi b/stubs/Pygments/pygments/formatters/img.pyi index 06b50aee8ca4..26c8c131d5c8 100644 --- a/stubs/Pygments/pygments/formatters/img.pyi +++ b/stubs/Pygments/pygments/formatters/img.pyi @@ -1,65 +1,58 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing_extensions import Never from pygments.formatter import Formatter +from pygments.token import _TokenType + +__all__ = ["ImageFormatter", "GifImageFormatter", "JpgImageFormatter", "BmpImageFormatter"] class PilNotAvailable(ImportError): ... class FontNotFound(Exception): ... class FontManager: - font_name: Any - font_size: Any - fonts: Any - encoding: Any - def __init__(self, font_name, font_size: int = ...) -> None: ... + font_name: Incomplete + font_size: Incomplete + fonts: Incomplete + encoding: Incomplete + variable: bool + def __init__(self, font_name, font_size: int = 14) -> None: ... def get_char_size(self): ... def get_text_size(self, text): ... def get_font(self, bold, oblique): ... + def get_style(self, style): ... -class ImageFormatter(Formatter): - name: str - aliases: Any - filenames: Any - unicodeoutput: bool +class ImageFormatter(Formatter[bytes]): default_image_format: str encoding: str - styles: Any + styles: Incomplete background_color: str - image_format: Any - image_pad: Any - line_pad: Any - fonts: Any - line_number_fg: Any - line_number_bg: Any - line_number_chars: Any - line_number_bold: Any - line_number_italic: Any - line_number_pad: Any - line_numbers: Any - line_number_separator: Any - line_number_step: Any - line_number_start: Any - line_number_width: Any - hl_lines: Any - hl_color: Any - drawables: Any - def __init__(self, **options) -> None: ... - def get_style_defs(self, arg: str = ...) -> None: ... - def format(self, tokensource, outfile) -> None: ... + image_format: Incomplete + image_pad: Incomplete + line_pad: Incomplete + fonts: Incomplete + line_number_fg: Incomplete + line_number_bg: Incomplete + line_number_chars: Incomplete + line_number_bold: Incomplete + line_number_italic: Incomplete + line_number_pad: Incomplete + line_numbers: Incomplete + line_number_separator: Incomplete + line_number_step: Incomplete + line_number_start: Incomplete + line_number_width: Incomplete + hl_lines: Incomplete + hl_color: Incomplete + drawables: Incomplete + def get_style_defs(self, arg: str = "") -> Never: ... + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[bytes]) -> None: ... class GifImageFormatter(ImageFormatter): - name: str - aliases: Any - filenames: Any default_image_format: str class JpgImageFormatter(ImageFormatter): - name: str - aliases: Any - filenames: Any default_image_format: str class BmpImageFormatter(ImageFormatter): - name: str - aliases: Any - filenames: Any default_image_format: str diff --git a/stubs/Pygments/pygments/formatters/irc.pyi b/stubs/Pygments/pygments/formatters/irc.pyi index b8bedfd849ac..0d34575c9ae8 100644 --- a/stubs/Pygments/pygments/formatters/irc.pyi +++ b/stubs/Pygments/pygments/formatters/irc.pyi @@ -1,13 +1,16 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class IRCFormatter(Formatter): - name: str - aliases: Any - filenames: Any - darkbg: Any - colorscheme: Any - linenos: Any - def __init__(self, **options) -> None: ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["IRCFormatter"] + +class IRCFormatter(Formatter[_T]): + darkbg: Incomplete + colorscheme: Incomplete + linenos: Incomplete + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/latex.pyi b/stubs/Pygments/pygments/formatters/latex.pyi index a321c7b1ada0..b1c4b7d3fe2e 100644 --- a/stubs/Pygments/pygments/formatters/latex.pyi +++ b/stubs/Pygments/pygments/formatters/latex.pyi @@ -1,33 +1,36 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter from pygments.lexer import Lexer +from pygments.token import _TokenType -class LatexFormatter(Formatter): - name: str - aliases: Any - filenames: Any - docclass: Any - preamble: Any - linenos: Any - linenostart: Any - linenostep: Any - verboptions: Any - nobackground: Any - commandprefix: Any - texcomments: Any - mathescape: Any - escapeinside: Any - left: Any - right: Any - envname: Any - def __init__(self, **options) -> None: ... - def get_style_defs(self, arg: str = ...): ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["LatexFormatter"] + +class LatexFormatter(Formatter[_T]): + docclass: Incomplete + preamble: Incomplete + linenos: Incomplete + linenostart: Incomplete + linenostep: Incomplete + verboptions: Incomplete + nobackground: Incomplete + commandprefix: Incomplete + texcomments: Incomplete + mathescape: Incomplete + escapeinside: Incomplete + left: Incomplete + right: Incomplete + envname: Incomplete + def get_style_defs(self, arg: str = ""): ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... class LatexEmbeddedLexer(Lexer): - left: Any - right: Any - lang: Any + left: Incomplete + right: Incomplete + lang: Incomplete def __init__(self, left, right, lang, **options) -> None: ... def get_tokens_unprocessed(self, text): ... diff --git a/stubs/Pygments/pygments/formatters/other.pyi b/stubs/Pygments/pygments/formatters/other.pyi index 222ab054b96f..c30244da9e39 100644 --- a/stubs/Pygments/pygments/formatters/other.pyi +++ b/stubs/Pygments/pygments/formatters/other.pyi @@ -1,26 +1,22 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class NullFormatter(Formatter): - name: str - aliases: Any - filenames: Any - def format(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) -class RawTokenFormatter(Formatter): - name: str - aliases: Any - filenames: Any - unicodeoutput: bool +__all__ = ["NullFormatter", "RawTokenFormatter", "TestcaseFormatter"] + +class NullFormatter(Formatter[_T]): + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... + +class RawTokenFormatter(Formatter[bytes]): encoding: str - compress: Any - error_color: Any - def __init__(self, **options) -> None: ... - def format(self, tokensource, outfile) -> None: ... + compress: Incomplete + error_color: Incomplete + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[bytes]) -> None: ... -class TestcaseFormatter(Formatter): - name: str - aliases: Any - def __init__(self, **options) -> None: ... - def format(self, tokensource, outfile) -> None: ... +class TestcaseFormatter(Formatter[_T]): + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/pangomarkup.pyi b/stubs/Pygments/pygments/formatters/pangomarkup.pyi index c72b9fd84a63..331eab16ca9a 100644 --- a/stubs/Pygments/pygments/formatters/pangomarkup.pyi +++ b/stubs/Pygments/pygments/formatters/pangomarkup.pyi @@ -1,11 +1,14 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class PangoMarkupFormatter(Formatter): - name: str - aliases: Any - filenames: Any - styles: Any - def __init__(self, **options) -> None: ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["PangoMarkupFormatter"] + +class PangoMarkupFormatter(Formatter[_T]): + styles: Incomplete + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/rtf.pyi b/stubs/Pygments/pygments/formatters/rtf.pyi index 2dcffc66952d..dc374aaf4bcb 100644 --- a/stubs/Pygments/pygments/formatters/rtf.pyi +++ b/stubs/Pygments/pygments/formatters/rtf.pyi @@ -1,12 +1,17 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class RtfFormatter(Formatter): - name: str - aliases: Any - filenames: Any - fontface: Any - fontsize: Any - def __init__(self, **options) -> None: ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["RtfFormatter"] + +class RtfFormatter(Formatter[_T]): + fontface: Incomplete + fontsize: Incomplete + @staticmethod + def hex_to_rtf_color(hex_color: str) -> str: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/svg.pyi b/stubs/Pygments/pygments/formatters/svg.pyi index 8dd0402595d1..900deb19f58c 100644 --- a/stubs/Pygments/pygments/formatters/svg.pyi +++ b/stubs/Pygments/pygments/formatters/svg.pyi @@ -1,21 +1,24 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class SvgFormatter(Formatter): - name: str - aliases: Any - filenames: Any - nowrap: Any - fontfamily: Any - fontsize: Any - xoffset: Any - yoffset: Any - ystep: Any - spacehack: Any - linenos: Any - linenostart: Any - linenostep: Any - linenowidth: Any - def __init__(self, **options) -> None: ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["SvgFormatter"] + +class SvgFormatter(Formatter[_T]): + nowrap: Incomplete + fontfamily: Incomplete + fontsize: Incomplete + xoffset: Incomplete + yoffset: Incomplete + ystep: Incomplete + spacehack: Incomplete + linenos: Incomplete + linenostart: Incomplete + linenostep: Incomplete + linenowidth: Incomplete + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/terminal.pyi b/stubs/Pygments/pygments/formatters/terminal.pyi index 92b2c8b4ee91..c7c82cbdf257 100644 --- a/stubs/Pygments/pygments/formatters/terminal.pyi +++ b/stubs/Pygments/pygments/formatters/terminal.pyi @@ -1,14 +1,17 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType -class TerminalFormatter(Formatter): - name: str - aliases: Any - filenames: Any - darkbg: Any - colorscheme: Any - linenos: Any - def __init__(self, **options) -> None: ... - def format(self, tokensource, outfile): ... - def format_unencoded(self, tokensource, outfile) -> None: ... +_T = TypeVar("_T", str, bytes) + +__all__ = ["TerminalFormatter"] + +class TerminalFormatter(Formatter[_T]): + darkbg: Incomplete + colorscheme: Incomplete + linenos: Incomplete + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/terminal256.pyi b/stubs/Pygments/pygments/formatters/terminal256.pyi index 55786c45dc9b..092a121f95aa 100644 --- a/stubs/Pygments/pygments/formatters/terminal256.pyi +++ b/stubs/Pygments/pygments/formatters/terminal256.pyi @@ -1,37 +1,36 @@ -from typing import Any +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["Terminal256Formatter", "TerminalTrueColorFormatter"] class EscapeSequence: - fg: Any - bg: Any - bold: Any - underline: Any - italic: Any - def __init__( - self, fg: Any | None = ..., bg: Any | None = ..., bold: bool = ..., underline: bool = ..., italic: bool = ... - ) -> None: ... + fg: Incomplete + bg: Incomplete + bold: Incomplete + underline: Incomplete + italic: Incomplete + def __init__(self, fg=None, bg=None, bold: bool = False, underline: bool = False, italic: bool = False) -> None: ... def escape(self, attrs): ... def color_string(self): ... def true_color_string(self): ... def reset_string(self): ... -class Terminal256Formatter(Formatter): - name: str - aliases: Any - filenames: Any - xterm_colors: Any - best_match: Any - style_string: Any - usebold: Any - useunderline: Any - useitalic: Any - linenos: Any - def __init__(self, **options) -> None: ... - def format(self, tokensource, outfile): ... - def format_unencoded(self, tokensource, outfile) -> None: ... +class Terminal256Formatter(Formatter[_T]): + xterm_colors: Incomplete + best_match: Incomplete + style_string: Incomplete + usebold: Incomplete + useunderline: Incomplete + useitalic: Incomplete + linenos: Incomplete + + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... -class TerminalTrueColorFormatter(Terminal256Formatter): - name: str - aliases: Any - filenames: Any +class TerminalTrueColorFormatter(Terminal256Formatter[_T]): ... diff --git a/stubs/Pygments/pygments/lexer.pyi b/stubs/Pygments/pygments/lexer.pyi index 6ede8438bc04..124ba720f15e 100644 --- a/stubs/Pygments/pygments/lexer.pyi +++ b/stubs/Pygments/pygments/lexer.pyi @@ -1,54 +1,76 @@ +from _typeshed import Incomplete from collections.abc import Iterable, Iterator, Sequence -from typing import Any, Tuple +from re import Pattern, RegexFlag +from typing import ClassVar, Final from pygments.token import _TokenType from pygments.util import Future +__all__ = [ + "Lexer", + "RegexLexer", + "ExtendedRegexLexer", + "DelegatingLexer", + "LexerContext", + "include", + "inherit", + "bygroups", + "using", + "this", + "default", + "words", + "line_re", +] + +line_re: Final[Pattern[str]] + class LexerMeta(type): def __new__(cls, name, bases, d): ... - def analyse_text(self, text) -> None: ... # actually defined in class Lexer - # ClassVars of Lexer, but same situation as with StyleMeta and Style - name: str - aliases: Sequence[str] # not intended mutable - filenames: Sequence[str] - alias_filenames: Sequence[str] - mimetypes: Sequence[str] - priority: int class Lexer(metaclass=LexerMeta): - options: Any - stripnl: Any - stripall: Any - ensurenl: Any - tabsize: Any - encoding: Any - filters: Any + name: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + aliases: ClassVar[Sequence[str]] # not intended to be mutable + filenames: ClassVar[Sequence[str]] + alias_filenames: ClassVar[Sequence[str]] + mimetypes: ClassVar[Sequence[str]] + priority: ClassVar[float] + url: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + version_added: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + options: Incomplete + stripnl: Incomplete + stripall: Incomplete + ensurenl: Incomplete + tabsize: Incomplete + encoding: Incomplete + filters: Incomplete def __init__(self, **options) -> None: ... def add_filter(self, filter_, **options) -> None: ... - def get_tokens(self, text: str, unfiltered: bool = ...) -> Iterator[tuple[_TokenType, str]]: ... + @staticmethod # @staticmethod added by special handling in metaclass + def analyse_text(text: str) -> float: ... + def get_tokens(self, text: str, unfiltered: bool = False) -> Iterator[tuple[_TokenType, str]]: ... def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... class DelegatingLexer(Lexer): - root_lexer: Any - language_lexer: Any - needle: Any + root_lexer: Incomplete + language_lexer: Incomplete + needle: Incomplete def __init__(self, _root_lexer, _language_lexer, _needle=..., **options) -> None: ... def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... class include(str): ... class _inherit: ... -inherit: Any +inherit: Incomplete -class combined(Tuple[Any]): +class combined(tuple[Incomplete, ...]): def __new__(cls, *args): ... def __init__(self, *args) -> None: ... class _PseudoMatch: def __init__(self, start, text) -> None: ... - def start(self, arg: Any | None = ...): ... - def end(self, arg: Any | None = ...): ... - def group(self, arg: Any | None = ...): ... + def start(self, arg=None): ... + def end(self, arg=None): ... + def group(self, arg=None): ... def groups(self): ... def groupdict(self): ... @@ -56,44 +78,44 @@ def bygroups(*args): ... class _This: ... -this: Any +this: Incomplete def using(_other, **kwargs): ... class default: - state: Any + state: Incomplete def __init__(self, state) -> None: ... class words(Future): - words: Any - prefix: Any - suffix: Any - def __init__(self, words, prefix: str = ..., suffix: str = ...) -> None: ... + words: Incomplete + prefix: Incomplete + suffix: Incomplete + def __init__(self, words, prefix: str = "", suffix: str = "") -> None: ... def get(self): ... class RegexLexerMeta(LexerMeta): - def process_tokendef(cls, name, tokendefs: Any | None = ...): ... + def process_tokendef(cls, name, tokendefs=None): ... def get_tokendefs(cls): ... def __call__(cls, *args, **kwds): ... class RegexLexer(Lexer, metaclass=RegexLexerMeta): - flags: Any - tokens: Any - def get_tokens_unprocessed(self, text: str, stack: Iterable[str] = ...) -> Iterator[tuple[int, _TokenType, str]]: ... + flags: ClassVar[RegexFlag] + tokens: ClassVar[dict[str, list[Incomplete]]] + def get_tokens_unprocessed(self, text: str, stack: Iterable[str] = ("root",)) -> Iterator[tuple[int, _TokenType, str]]: ... class LexerContext: - text: Any - pos: Any - end: Any - stack: Any - def __init__(self, text, pos, stack: Any | None = ..., end: Any | None = ...) -> None: ... + text: Incomplete + pos: Incomplete + end: Incomplete + stack: Incomplete + def __init__(self, text, pos, stack=None, end=None) -> None: ... class ExtendedRegexLexer(RegexLexer): def get_tokens_unprocessed( # type: ignore[override] - self, text: str | None = ..., context: LexerContext | None = ... + self, text: str | None = None, context: LexerContext | None = None ) -> Iterator[tuple[int, _TokenType, str]]: ... class ProfilingRegexLexerMeta(RegexLexerMeta): ... class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta): - def get_tokens_unprocessed(self, text: str, stack: Iterable[str] = ...) -> Iterator[tuple[int, _TokenType, str]]: ... + def get_tokens_unprocessed(self, text: str, stack: Iterable[str] = ("root",)) -> Iterator[tuple[int, _TokenType, str]]: ... diff --git a/stubs/Pygments/pygments/lexers/__init__.pyi b/stubs/Pygments/pygments/lexers/__init__.pyi index 23a2966c3890..6309716d9ace 100644 --- a/stubs/Pygments/pygments/lexers/__init__.pyi +++ b/stubs/Pygments/pygments/lexers/__init__.pyi @@ -1,22 +1,18 @@ -from _typeshed import StrOrBytesPath, StrPath +from _typeshed import FileDescriptorOrPath, StrPath from collections.abc import Iterator -from typing import Any, Tuple, Union -from pygments.lexer import Lexer, LexerMeta +from pygments.lexer import Lexer -_OpenFile = Union[StrOrBytesPath, int] # copy/pasted from builtins.pyi - -# TODO: use lower-case tuple once mypy updated -def get_all_lexers() -> Iterator[tuple[str, Tuple[str, ...], Tuple[str, ...], Tuple[str, ...]]]: ... -def find_lexer_class(name: str) -> LexerMeta | None: ... -def find_lexer_class_by_name(_alias: str) -> LexerMeta: ... -def get_lexer_by_name(_alias: str, **options: Any) -> Lexer: ... -def load_lexer_from_file(filename: _OpenFile, lexername: str = ..., **options: Any) -> Lexer: ... -def find_lexer_class_for_filename(_fn: StrPath, code: str | bytes | None = ...) -> LexerMeta | None: ... -def get_lexer_for_filename(_fn: StrPath, code: str | bytes | None = ..., **options: Any) -> Lexer: ... -def get_lexer_for_mimetype(_mime: str, **options: Any) -> Lexer: ... -def guess_lexer_for_filename(_fn: StrPath, _text: str, **options: Any) -> LexerMeta | None: ... -def guess_lexer(_text: str | bytes, **options: Any) -> Lexer: ... +def get_all_lexers(plugins: bool = True) -> Iterator[tuple[str, tuple[str, ...], tuple[str, ...], tuple[str, ...]]]: ... +def find_lexer_class(name: str) -> type[Lexer] | None: ... +def find_lexer_class_by_name(_alias: str) -> type[Lexer]: ... +def get_lexer_by_name(_alias: str, **options) -> Lexer: ... +def load_lexer_from_file(filename: FileDescriptorOrPath, lexername: str = "CustomLexer", **options) -> Lexer: ... +def find_lexer_class_for_filename(_fn: StrPath, code: str | bytes | None = None) -> type[Lexer] | None: ... +def get_lexer_for_filename(_fn: StrPath, code: str | bytes | None = None, **options) -> Lexer: ... +def get_lexer_for_mimetype(_mime: str, **options) -> Lexer: ... +def guess_lexer_for_filename(_fn: StrPath, _text: str, **options) -> Lexer: ... +def guess_lexer(_text: str | bytes, **options) -> Lexer: ... # Having every lexer class here doesn't seem to be worth it -def __getattr__(name: str) -> Any: ... +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/Pygments/pygments/lexers/javascript.pyi b/stubs/Pygments/pygments/lexers/javascript.pyi new file mode 100644 index 000000000000..958ca3422c0c --- /dev/null +++ b/stubs/Pygments/pygments/lexers/javascript.pyi @@ -0,0 +1,40 @@ +from collections.abc import Iterator +from typing import Final + +from ..lexer import Lexer, RegexLexer +from ..token import _TokenType + +__all__ = [ + "JavascriptLexer", + "KalLexer", + "LiveScriptLexer", + "DartLexer", + "TypeScriptLexer", + "LassoLexer", + "ObjectiveJLexer", + "CoffeeScriptLexer", + "MaskLexer", + "EarlGreyLexer", + "JuttleLexer", + "NodeConsoleLexer", +] + +JS_IDENT_START: Final[str] +JS_IDENT_PART: Final[str] +JS_IDENT: Final[str] + +class JavascriptLexer(RegexLexer): ... +class TypeScriptLexer(JavascriptLexer): ... +class KalLexer(RegexLexer): ... +class LiveScriptLexer(RegexLexer): ... +class DartLexer(RegexLexer): ... + +class LassoLexer(RegexLexer): + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class ObjectiveJLexer(RegexLexer): ... +class CoffeeScriptLexer(RegexLexer): ... +class MaskLexer(RegexLexer): ... +class EarlGreyLexer(RegexLexer): ... +class JuttleLexer(RegexLexer): ... +class NodeConsoleLexer(Lexer): ... diff --git a/stubs/Pygments/pygments/lexers/jsx.pyi b/stubs/Pygments/pygments/lexers/jsx.pyi new file mode 100644 index 000000000000..2017e214f6b0 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/jsx.pyi @@ -0,0 +1,5 @@ +from .javascript import JavascriptLexer + +__all__ = ["JsxLexer"] + +class JsxLexer(JavascriptLexer): ... diff --git a/stubs/Pygments/pygments/lexers/kusto.pyi b/stubs/Pygments/pygments/lexers/kusto.pyi new file mode 100644 index 000000000000..7130f990315f --- /dev/null +++ b/stubs/Pygments/pygments/lexers/kusto.pyi @@ -0,0 +1,10 @@ +from typing import Final + +from ..lexer import RegexLexer + +__all__ = ["KustoLexer"] + +KUSTO_KEYWORDS: Final[list[str]] +KUSTO_PUNCTUATION: Final[list[str]] + +class KustoLexer(RegexLexer): ... diff --git a/stubs/Pygments/pygments/lexers/ldap.pyi b/stubs/Pygments/pygments/lexers/ldap.pyi new file mode 100644 index 000000000000..da0f4bf8586f --- /dev/null +++ b/stubs/Pygments/pygments/lexers/ldap.pyi @@ -0,0 +1,6 @@ +from ..lexer import RegexLexer + +__all__ = ["LdifLexer", "LdaprcLexer"] + +class LdifLexer(RegexLexer): ... +class LdaprcLexer(RegexLexer): ... diff --git a/stubs/Pygments/pygments/lexers/lean.pyi b/stubs/Pygments/pygments/lexers/lean.pyi new file mode 100644 index 000000000000..54e15be68a32 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/lean.pyi @@ -0,0 +1,7 @@ +from ..lexer import RegexLexer + +__all__ = ["Lean3Lexer"] + +class Lean3Lexer(RegexLexer): ... + +LeanLexer = Lean3Lexer diff --git a/stubs/Pygments/pygments/lexers/lisp.pyi b/stubs/Pygments/pygments/lexers/lisp.pyi new file mode 100644 index 000000000000..9f1cb3a08f84 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/lisp.pyi @@ -0,0 +1,96 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar + +from ..lexer import RegexLexer +from ..token import _TokenType + +__all__ = [ + "SchemeLexer", + "CommonLispLexer", + "HyLexer", + "RacketLexer", + "NewLispLexer", + "EmacsLispLexer", + "ShenLexer", + "CPSALexer", + "XtlangLexer", + "FennelLexer", +] + +class SchemeLexer(RegexLexer): + valid_name: ClassVar[str] + token_end: ClassVar[str] + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + number_rules: ClassVar[dict[Incomplete, Incomplete]] + def decimal_cb(self, match) -> Iterator[tuple[Incomplete, Incomplete, Incomplete]]: ... + +class CommonLispLexer(RegexLexer): + nonmacro: ClassVar[str] + constituent: ClassVar[str] + terminated: ClassVar[str] + symbol: ClassVar[str] + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class HyLexer(RegexLexer): + special_forms: ClassVar[tuple[str, ...]] + declarations: ClassVar[tuple[str, ...]] + hy_builtins: ClassVar[tuple[str, ...]] + hy_core: ClassVar[tuple[str, ...]] + builtins: ClassVar[tuple[str, ...]] + valid_name: ClassVar[str] + +class RacketLexer(RegexLexer): ... + +class NewLispLexer(RegexLexer): + builtins: ClassVar[tuple[str, ...]] + valid_name: ClassVar[str] + +class EmacsLispLexer(RegexLexer): + nonmacro: ClassVar[str] + constituent: ClassVar[str] + terminated: ClassVar[str] + symbol: ClassVar[str] + macros: ClassVar[set[str]] + special_forms: ClassVar[set[str]] + builtin_function: ClassVar[set[str]] + builtin_function_highlighted: ClassVar[set[str]] + lambda_list_keywords: ClassVar[set[str]] + error_keywords: ClassVar[set[str]] + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class ShenLexer(RegexLexer): + DECLARATIONS: ClassVar[tuple[str, ...]] + SPECIAL_FORMS: ClassVar[tuple[str, ...]] + BUILTINS: ClassVar[tuple[str, ...]] + BUILTINS_ANYWHERE: ClassVar[tuple[str, ...]] + MAPPINGS: ClassVar[dict[str, Incomplete]] + + valid_symbol_chars: ClassVar[str] + valid_name: ClassVar[str] + symbol_name: ClassVar[str] + variable: ClassVar[str] + + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class CPSALexer(RegexLexer): + valid_name: ClassVar[str] + +class XtlangLexer(RegexLexer): + common_keywords: ClassVar[tuple[str, ...]] + scheme_keywords: ClassVar[tuple[str, ...]] + xtlang_bind_keywords: ClassVar[tuple[str, ...]] + xtlang_keywords: ClassVar[tuple[str, ...]] + common_functions: ClassVar[tuple[str, ...]] + scheme_functions: ClassVar[tuple[str, ...]] + xtlang_functions: ClassVar[tuple[str, ...]] + + valid_scheme_name: ClassVar[str] + valid_xtlang_name: ClassVar[str] + valid_xtlang_type: ClassVar[str] + +class FennelLexer(RegexLexer): + special_forms: ClassVar[tuple[str, ...]] + declarations: ClassVar[tuple[str, ...]] + builtins: ClassVar[tuple[str, ...]] + valid_name: ClassVar[str] diff --git a/stubs/Pygments/pygments/lexers/prql.pyi b/stubs/Pygments/pygments/lexers/prql.pyi new file mode 100644 index 000000000000..682ff082c93f --- /dev/null +++ b/stubs/Pygments/pygments/lexers/prql.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..lexer import RegexLexer + +__all__ = ["PrqlLexer"] + +class PrqlLexer(RegexLexer): + builtinTypes: ClassVar[Incomplete] + def innerstring_rules(ttype) -> list[tuple[str, Incomplete]]: ... + def fstring_rules(ttype) -> list[tuple[str, Incomplete]]: ... diff --git a/stubs/Pygments/pygments/lexers/vip.pyi b/stubs/Pygments/pygments/lexers/vip.pyi new file mode 100644 index 000000000000..876a05d8bb86 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/vip.pyi @@ -0,0 +1,19 @@ +from typing import ClassVar + +from ..lexer import RegexLexer + +__all__ = ["VisualPrologLexer", "VisualPrologGrammarLexer"] + +class VisualPrologBaseLexer(RegexLexer): + minorendkw: ClassVar[tuple[str, ...]] + minorkwexp: ClassVar[tuple[str, ...]] + dockw: ClassVar[tuple[str, ...]] + +class VisualPrologLexer(VisualPrologBaseLexer): + majorkw: ClassVar[tuple[str, ...]] + minorkw: ClassVar[tuple[str, ...]] + directivekw: ClassVar[tuple[str, ...]] + +class VisualPrologGrammarLexer(VisualPrologBaseLexer): + majorkw: ClassVar[tuple[str, ...]] + directivekw: ClassVar[tuple[str, ...]] diff --git a/stubs/Pygments/pygments/lexers/vyper.pyi b/stubs/Pygments/pygments/lexers/vyper.pyi new file mode 100644 index 000000000000..27a759b0404b --- /dev/null +++ b/stubs/Pygments/pygments/lexers/vyper.pyi @@ -0,0 +1,5 @@ +from ..lexer import RegexLexer + +__all__ = ["VyperLexer"] + +class VyperLexer(RegexLexer): ... diff --git a/stubs/Pygments/pygments/modeline.pyi b/stubs/Pygments/pygments/modeline.pyi index 3bfa98602b86..bf51d03f825a 100644 --- a/stubs/Pygments/pygments/modeline.pyi +++ b/stubs/Pygments/pygments/modeline.pyi @@ -1 +1,3 @@ -def get_filetype_from_buffer(buf, max_lines: int = ...): ... +__all__ = ["get_filetype_from_buffer"] + +def get_filetype_from_buffer(buf: str, max_lines: int = 5) -> str | None: ... diff --git a/stubs/Pygments/pygments/plugin.pyi b/stubs/Pygments/pygments/plugin.pyi index e2115ee9d0fd..49b49c9d7641 100644 --- a/stubs/Pygments/pygments/plugin.pyi +++ b/stubs/Pygments/pygments/plugin.pyi @@ -1,10 +1,20 @@ -LEXER_ENTRY_POINT: str -FORMATTER_ENTRY_POINT: str -STYLE_ENTRY_POINT: str -FILTER_ENTRY_POINT: str +from _typeshed import Incomplete +from collections.abc import Generator +from importlib.metadata import EntryPoints +from typing import Final -def iter_entry_points(group_name): ... -def find_plugin_lexers() -> None: ... -def find_plugin_formatters() -> None: ... -def find_plugin_styles() -> None: ... -def find_plugin_filters() -> None: ... +from pygments.filter import Filter +from pygments.formatter import Formatter +from pygments.lexer import Lexer +from pygments.style import Style + +LEXER_ENTRY_POINT: Final = "pygments.lexers" +FORMATTER_ENTRY_POINT: Final = "pygments.formatters" +STYLE_ENTRY_POINT: Final = "pygments.styles" +FILTER_ENTRY_POINT: Final = "pygments.filters" + +def iter_entry_points(group_name: str) -> EntryPoints: ... +def find_plugin_lexers() -> Generator[type[Lexer]]: ... +def find_plugin_formatters() -> Generator[tuple[str, type[Formatter[Incomplete]]]]: ... +def find_plugin_styles() -> Generator[tuple[str, type[Style]]]: ... +def find_plugin_filters() -> Generator[tuple[str, type[Filter]]]: ... diff --git a/stubs/Pygments/pygments/regexopt.pyi b/stubs/Pygments/pygments/regexopt.pyi index 799bebfc69a0..2429349f90fb 100644 --- a/stubs/Pygments/pygments/regexopt.pyi +++ b/stubs/Pygments/pygments/regexopt.pyi @@ -1,8 +1,12 @@ -from typing import Any +import re +from collections.abc import Iterable, Sequence +from operator import itemgetter +from typing import Final -CS_ESCAPE: Any -FIRST_ELEMENT: Any +CS_ESCAPE: Final[re.Pattern[str]] +FIRST_ELEMENT: Final[itemgetter[int]] -def make_charset(letters): ... -def regex_opt_inner(strings, open_paren): ... -def regex_opt(strings, prefix: str = ..., suffix: str = ...): ... +def commonprefix(m: Iterable[str]) -> str: ... +def make_charset(letters: Iterable[str]) -> str: ... +def regex_opt_inner(strings: Sequence[str], open_paren: str) -> str: ... +def regex_opt(strings: Iterable[str], prefix: str = "", suffix: str = "") -> str: ... diff --git a/stubs/Pygments/pygments/scanner.pyi b/stubs/Pygments/pygments/scanner.pyi index d43e47da12da..1d4557425b9f 100644 --- a/stubs/Pygments/pygments/scanner.pyi +++ b/stubs/Pygments/pygments/scanner.pyi @@ -1,19 +1,19 @@ -from typing import Any +from re import Match, Pattern, RegexFlag class EndOfText(RuntimeError): ... class Scanner: - data: Any - data_length: Any + data: str + data_length: int start_pos: int pos: int - flags: Any - last: Any - match: Any - def __init__(self, text, flags: int = ...) -> None: ... + flags: int | RegexFlag + last: str | None + match: str | None + def __init__(self, text: str, flags: int | RegexFlag = 0) -> None: ... @property - def eos(self): ... - def check(self, pattern): ... - def test(self, pattern): ... - def scan(self, pattern): ... + def eos(self) -> bool: ... + def check(self, pattern: str | Pattern[str]) -> Match[str] | None: ... + def test(self, pattern: str | Pattern[str]) -> bool: ... + def scan(self, pattern: str | Pattern[str]) -> bool: ... def get_char(self) -> None: ... diff --git a/stubs/Pygments/pygments/sphinxext.pyi b/stubs/Pygments/pygments/sphinxext.pyi index ef79a1ea8db0..f0caf6e2fa52 100644 --- a/stubs/Pygments/pygments/sphinxext.pyi +++ b/stubs/Pygments/pygments/sphinxext.pyi @@ -1,22 +1,17 @@ -from typing import Any +from typing import Any, Final from docutils.parsers.rst import Directive -MODULEDOC: str -LEXERDOC: str -FMTERDOC: str -FILTERDOC: str +MODULEDOC: Final[str] +LEXERDOC: Final[str] +FMTERDOC: Final[str] +FILTERDOC: Final[str] class PygmentsDoc(Directive): - has_content: bool - required_arguments: int - optional_arguments: int - final_argument_whitespace: bool - option_spec: Any - filenames: Any - def run(self): ... - def document_lexers(self): ... - def document_formatters(self): ... - def document_filters(self): ... + filenames: set[str] + def document_lexers_overview(self) -> str: ... + def document_lexers(self) -> str: ... + def document_formatters(self) -> str: ... + def document_filters(self) -> str: ... -def setup(app) -> None: ... +def setup(app: Any) -> None: ... # Actual type of 'app' is sphinx.application.Sphinx diff --git a/stubs/Pygments/pygments/style.pyi b/stubs/Pygments/pygments/style.pyi index f6e0072ee75e..6ebe3683dcfc 100644 --- a/stubs/Pygments/pygments/style.pyi +++ b/stubs/Pygments/pygments/style.pyi @@ -1,10 +1,12 @@ -from collections.abc import Iterator, Mapping, Set -from typing_extensions import TypedDict +from _typeshed import Self +from collections.abc import Iterator, Mapping, Sequence, Set as AbstractSet +from typing import Any, ClassVar, TypedDict, type_check_only from pygments.token import _TokenType -ansicolors: Set[str] # not intended to be mutable (== typing.AbstractSet, not builtins.set) +ansicolors: AbstractSet[str] # not intended to be mutable +@type_check_only class _StyleDict(TypedDict): color: str | None bold: bool @@ -19,22 +21,21 @@ class _StyleDict(TypedDict): bgansicolor: str | None class StyleMeta(type): - def __new__(cls, name, bases, dct): ... + def __new__(cls: type[Self], name: str, bases: tuple[type[Any], ...], dct: dict[str, Any]) -> Self: ... def style_for_token(cls, token: _TokenType) -> _StyleDict: ... def styles_token(cls, ttype: _TokenType) -> bool: ... def list_styles(cls) -> list[tuple[_TokenType, _StyleDict]]: ... def __iter__(cls) -> Iterator[tuple[_TokenType, _StyleDict]]: ... def __len__(cls) -> int: ... - # These are a bit tricky. - # Technically should be ClassVar in class Style. - # But then we can't use StyleMeta to denote a style class. - # We need that because Type[Style] is not iterable, for example. - background_color: str - highlight_color: str - line_number_color: str - line_number_background_color: str - line_number_special_color: str - line_number_special_background_color: str - styles: Mapping[_TokenType, str] # not intended to be mutable -class Style(metaclass=StyleMeta): ... +class Style(metaclass=StyleMeta): + background_color: ClassVar[str] + highlight_color: ClassVar[str] + line_number_color: ClassVar[str] + line_number_background_color: ClassVar[str] + line_number_special_color: ClassVar[str] + line_number_special_background_color: ClassVar[str] + styles: ClassVar[Mapping[_TokenType, str]] # not intended to be mutable + name: ClassVar[str] + aliases: ClassVar[Sequence[str]] # not intended to be mutable + web_style_gallery_exclude: ClassVar[bool] diff --git a/stubs/Pygments/pygments/styles/__init__.pyi b/stubs/Pygments/pygments/styles/__init__.pyi index 842f507ab502..6aeb9cf90f95 100644 --- a/stubs/Pygments/pygments/styles/__init__.pyi +++ b/stubs/Pygments/pygments/styles/__init__.pyi @@ -1,13 +1,12 @@ from collections.abc import Iterator, Mapping -from typing import Any -from pygments.style import StyleMeta +from pygments.style import Style from pygments.util import ClassNotFound as ClassNotFound STYLE_MAP: Mapping[str, str] -def get_style_by_name(name) -> StyleMeta: ... +def get_style_by_name(name) -> type[Style]: ... def get_all_styles() -> Iterator[str]: ... # Having every style class here doesn't seem to be worth it -def __getattr__(name: str) -> Any: ... +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/Pygments/pygments/token.pyi b/stubs/Pygments/pygments/token.pyi index 74a918f52dfb..141ff50a1deb 100644 --- a/stubs/Pygments/pygments/token.pyi +++ b/stubs/Pygments/pygments/token.pyi @@ -1,15 +1,15 @@ from collections.abc import Mapping -from typing import Tuple +from typing import Any, Final +from typing_extensions import Self -class _TokenType(Tuple[str]): # TODO: change to lower-case tuple once new mypy released +class _TokenType(tuple[str, ...]): parent: _TokenType | None def split(self) -> list[_TokenType]: ... subtypes: set[_TokenType] - def __init__(self, *args: str) -> None: ... def __contains__(self, val: _TokenType) -> bool: ... # type: ignore[override] def __getattr__(self, name: str) -> _TokenType: ... - def __copy__(self): ... - def __deepcopy__(self, memo): ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... Token: _TokenType Text: _TokenType @@ -27,8 +27,8 @@ Operator: _TokenType Comment: _TokenType Generic: _TokenType -def is_token_subtype(ttype, other): ... -def string_to_tokentype(s): ... +def is_token_subtype(ttype: _TokenType, other: _TokenType) -> bool: ... +def string_to_tokentype(s: str | _TokenType) -> _TokenType: ... # dict, but shouldn't be mutated -STANDARD_TYPES: Mapping[_TokenType, str] +STANDARD_TYPES: Final[Mapping[_TokenType, str]] diff --git a/stubs/Pygments/pygments/unistring.pyi b/stubs/Pygments/pygments/unistring.pyi index 6dd2b3fcea26..895f786c730d 100644 --- a/stubs/Pygments/pygments/unistring.pyi +++ b/stubs/Pygments/pygments/unistring.pyi @@ -1,38 +1,71 @@ -from typing import Any +from typing import Final, Literal, TypeAlias -Cc: str -Cf: str -Cn: str -Co: str -Cs: str -Ll: str -Lm: str -Lo: str -Lt: str -Lu: str -Mc: str -Me: str -Mn: str -Nd: str -Nl: str -No: str -Pc: str -Pd: str -Pe: str -Pf: str -Pi: str -Po: str -Ps: str -Sc: str -Sk: str -Sm: str -So: str -Zl: str -Zp: str -Zs: str -xid_continue: str -xid_start: str -cats: Any +_Cats: TypeAlias = Literal[ + "Cc", + "Cf", + "Cn", + "Co", + "Cs", + "Ll", + "Lm", + "Lo", + "Lt", + "Lu", + "Mc", + "Me", + "Mn", + "Nd", + "Nl", + "No", + "Pc", + "Pd", + "Pe", + "Pf", + "Pi", + "Po", + "Ps", + "Sc", + "Sk", + "Sm", + "So", + "Zl", + "Zp", + "Zs", +] -def combine(*args): ... -def allexcept(*args): ... +Cc: Final[str] +Cf: Final[str] +Cn: Final[str] +Co: Final[str] +Cs: Final[str] +Ll: Final[str] +Lm: Final[str] +Lo: Final[str] +Lt: Final[str] +Lu: Final[str] +Mc: Final[str] +Me: Final[str] +Mn: Final[str] +Nd: Final[str] +Nl: Final[str] +No: Final[str] +Pc: Final[str] +Pd: Final[str] +Pe: Final[str] +Pf: Final[str] +Pi: Final[str] +Po: Final[str] +Ps: Final[str] +Sc: Final[str] +Sk: Final[str] +Sm: Final[str] +So: Final[str] +Zl: Final[str] +Zp: Final[str] +Zs: Final[str] +xid_continue: Final[str] +xid_start: Final[str] +cats: Final[list[_Cats]] + +def combine(*args: _Cats) -> str: ... +def allexcept(*args: _Cats) -> str: ... diff --git a/stubs/Pygments/pygments/util.pyi b/stubs/Pygments/pygments/util.pyi index 23addc163de9..039bd80ab4a0 100644 --- a/stubs/Pygments/pygments/util.pyi +++ b/stubs/Pygments/pygments/util.pyi @@ -1,34 +1,55 @@ +from collections.abc import Callable, Container, Hashable, Iterable from io import TextIOWrapper -from typing import Any +from re import Pattern +from typing import Any, Final, Protocol, TypeVar, type_check_only -split_path_re: Any -doctype_lookup_re: Any -tag_re: Any -xml_decl_re: Any +_T = TypeVar("_T") +_H = TypeVar("_H", bound=Hashable) + +split_path_re: Final[Pattern[str]] +doctype_lookup_re: Final[Pattern[str]] +tag_re: Final[Pattern[str]] +xml_decl_re: Final[Pattern[str]] class ClassNotFound(ValueError): ... class OptionError(Exception): ... -def get_choice_opt(options, optname, allowed, default: Any | None = ..., normcase: bool = ...): ... -def get_bool_opt(options, optname, default: Any | None = ...): ... -def get_int_opt(options, optname, default: Any | None = ...): ... -def get_list_opt(options, optname, default: Any | None = ...): ... -def docstring_headline(obj): ... -def make_analysator(f): ... -def shebang_matches(text, regex): ... -def doctype_matches(text, regex): ... -def html_doctype_matches(text): ... -def looks_like_xml(text): ... -def surrogatepair(c): ... -def format_lines(var_name, seq, raw: bool = ..., indent_level: int = ...): ... -def duplicates_removed(it, already_seen=...): ... +@type_check_only +class _SupportsGetStrWithDefault(Protocol): + def get(self, item: str, default: Any, /) -> Any: ... + +# 'options' contains the **kwargs of an arbitrary function. +def get_choice_opt( + options: _SupportsGetStrWithDefault, optname: str, allowed: Container[_T], default: _T | None = None, normcase: bool = False +) -> _T: ... +def get_bool_opt(options: _SupportsGetStrWithDefault, optname: str, default: bool | None = None) -> bool: ... +def get_int_opt(options: _SupportsGetStrWithDefault, optname: str, default: int | None = None) -> int: ... + +# Return type and type of 'default' depend on the signature of the function whose **kwargs +# are being processed. +def get_list_opt( + options: _SupportsGetStrWithDefault, optname: str, default: list[Any] | tuple[Any, ...] | None = None +) -> list[Any]: ... +def docstring_headline(obj: object) -> str: ... +def make_analysator(f: Callable[[str], float]) -> Callable[[str], float]: ... +def shebang_matches(text: str, regex: str) -> bool: ... +def doctype_matches(text: str, regex: str) -> bool: ... +def html_doctype_matches(text: str) -> bool: ... +def looks_like_xml(text: str) -> bool: ... +def surrogatepair(c: int) -> int: ... +def format_lines(var_name: str, seq: Iterable[str], raw: bool = False, indent_level: int = 0) -> str: ... +def duplicates_removed(it: Iterable[_H], already_seen: Container[_H] = ()) -> list[_H]: ... class Future: def get(self) -> None: ... -def guess_decode(text): ... -def guess_decode_from_terminal(text, term): ... -def terminal_encoding(term): ... +def guess_decode(text: bytes) -> tuple[str, str]: ... + +# If 'term' has an 'encoding' attribute, it should be a str. Otherwise any object is accepted. +def guess_decode_from_terminal(text: bytes, term: Any) -> tuple[str, str]: ... +def terminal_encoding(term: Any) -> str: ... class UnclosingTextIOWrapper(TextIOWrapper): def close(self) -> None: ... + +def html_escape(string: str, quote: bool = True) -> str: ... diff --git a/stubs/RPi.GPIO/METADATA.toml b/stubs/RPi.GPIO/METADATA.toml new file mode 100644 index 000000000000..503497d94a9f --- /dev/null +++ b/stubs/RPi.GPIO/METADATA.toml @@ -0,0 +1,10 @@ +version = "0.7.*" +upstream-repository = "https://sourceforge.net/p/raspberry-gpio-python/code/" + +[tool.stubtest] +# This package is only supported on Raspberry Pi hardware, which identifies +# itself as 'linux'. When run on other hardware, it raises a RuntimeError: +# RPi.GPIO failed to import. RuntimeError: This module can only be run on a Raspberry Pi! +# https://sourceforge.net/p/raspberry-gpio-python/code/ci/08048dd1894a6b09a104557b6eaa6bb68b6baac5/tree/source/py_gpio.c#l1008 +supported-platforms = [] +ci-platforms = [] diff --git a/stubs/RPi.GPIO/RPi/GPIO/__init__.pyi b/stubs/RPi.GPIO/RPi/GPIO/__init__.pyi new file mode 100644 index 000000000000..75b3139f45ae --- /dev/null +++ b/stubs/RPi.GPIO/RPi/GPIO/__init__.pyi @@ -0,0 +1,66 @@ +from collections.abc import Callable +from typing import Final, Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _RPi_Info(TypedDict): + P1_REVISION: int + REVISION: str + TYPE: str + MANUFACTURER: str + PROCESSOR: str + RAM: str + +VERSION: str +RPI_INFO: _RPi_Info +RPI_REVISION: int + +HIGH: Literal[1] +LOW: Literal[0] + +OUT: Final = 0 +IN: Final = 1 +HARD_PWM: Final = 43 +SERIAL: Final = 40 +I2C: Final = 42 +SPI: Final = 41 +UNKNOWN: Final = -1 + +BOARD: Final = 10 +BCM: Final = 11 + +PUD_OFF: Final = 20 +PUD_UP: Final = 22 +PUD_DOWN: Final = 21 + +RISING: Final = 31 +FALLING: Final = 32 +BOTH: Final = 33 + +_EventCallback: TypeAlias = Callable[[int], object] + +def setup( + channel: int | list[int] | tuple[int, ...], direction: Literal[0, 1], pull_up_down: int = 20, initial: int = -1 +) -> None: ... +def cleanup(channel: int | list[int] | tuple[int, ...] = -666) -> None: ... +def output( + channel: int | list[int] | tuple[int, ...], + value: Literal[0, 1] | bool | list[Literal[0, 1] | bool] | tuple[Literal[0, 1] | bool, ...], + /, +) -> None: ... +def input(channel: int, /) -> bool: ... +def setmode(mode: Literal[10, 11], /) -> None: ... +def getmode() -> Literal[10, 11] | None: ... +def add_event_detect(channel: int, edge: int, callback: _EventCallback | None = None, bouncetime: int = -666) -> None: ... +def remove_event_detect(channel: int, /) -> None: ... +def event_detected(channel: int, /) -> bool: ... +def add_event_callback(channel: int, callback: _EventCallback) -> None: ... +def wait_for_edge(channel: int, edge: int, bouncetime: int = -666, timeout: int = -1) -> int | None: ... +def gpio_function(channel: int, /) -> int: ... +def setwarnings(gpio_warnings: bool, /) -> None: ... + +class PWM: + def __init__(self, channel: int, frequency: float, /) -> None: ... + def start(self, dutycycle: float, /) -> None: ... + def ChangeDutyCycle(self, dutycycle: float, /) -> None: ... + def ChangeFrequency(self, frequency: float, /) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/__init__.pyi b/stubs/RPi.GPIO/RPi/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/ext/mypy/__init__.pyi rename to stubs/RPi.GPIO/RPi/__init__.pyi diff --git a/stubs/SQLAlchemy/@tests/stubtest_allowlist.txt b/stubs/SQLAlchemy/@tests/stubtest_allowlist.txt deleted file mode 100644 index 7234e1eb1ae9..000000000000 --- a/stubs/SQLAlchemy/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,113 +0,0 @@ -# wrong argument name in implementation ("self" instead of "cls") -sqlalchemy.engine.URL.__new__ -sqlalchemy.engine.url.URL.__new__ -sqlalchemy.util.langhelpers._symbol.__new__ - -# unnecessary re-exports -sqlalchemy.util._collections.* -sqlalchemy.util.compat.* - -# forwards arguments to another function -sqlalchemy.ext.declarative.as_declarative - -# stdlib re-exports with stubtest issues -sqlalchemy.orm.collections.InstrumentedList.* -sqlalchemy.orm.collections.InstrumentedSet.* -sqlalchemy.orm.collections.MappedCollection.* -sqlalchemy.util.OrderedDict.get -sqlalchemy.util.StringIO.* -sqlalchemy.util.byte_buffer.* -sqlalchemy.util.column_dict.get - -# method arguments starting with double underscores in the implementation -sqlalchemy.testing.resolve_lambda -sqlalchemy.testing.util.resolve_lambda -sqlalchemy.util.WeakSequence.__init__ - -# not always present -sqlalchemy.testing.util.non_refcount_gc_collect - -# replaced at runtime -sqlalchemy.orm.strategy_options.contains_eager -sqlalchemy.orm.strategy_options.load_only -sqlalchemy.orm.strategy_options.joinedload -sqlalchemy.orm.strategy_options.subqueryload -sqlalchemy.orm.strategy_options.selectinload -sqlalchemy.orm.strategy_options.lazyload -sqlalchemy.orm.strategy_options.immediateload -sqlalchemy.orm.strategy_options.noload -sqlalchemy.orm.strategy_options.raiseload -sqlalchemy.orm.strategy_options.defaultload -sqlalchemy.orm.strategy_options.defer -sqlalchemy.orm.strategy_options.undefer -sqlalchemy.orm.strategy_options.undefer_group -sqlalchemy.orm.strategy_options.with_expression -sqlalchemy.orm.strategy_options.selectin_polymorphic -sqlalchemy.testing.provision.configure_follower -sqlalchemy.testing.provision.create_db -sqlalchemy.testing.provision.drop_all_schema_objects_post_tables -sqlalchemy.testing.provision.drop_all_schema_objects_pre_tables -sqlalchemy.testing.provision.drop_db -sqlalchemy.testing.provision.follower_url_from_main -sqlalchemy.testing.provision.generate_driver_url -sqlalchemy.testing.provision.get_temp_table_name -sqlalchemy.testing.provision.post_configure_engine -sqlalchemy.testing.provision.prepare_for_drop_tables -sqlalchemy.testing.provision.run_reap_dbs -sqlalchemy.testing.provision.set_default_schema_on_connection -sqlalchemy.testing.provision.stop_test_class_outside_fixtures -sqlalchemy.testing.provision.temp_table_keyword_args -sqlalchemy.testing.provision.update_db_opts - -# requires other packages -sqlalchemy.testing.plugin.pytestplugin - -# can't be imported -sqlalchemy.testing.fixtures -sqlalchemy.testing.pickleable -sqlalchemy.testing.plugin.bootstrap - -# Initialized to bool during __init__() -sqlalchemy.orm.Mapper.single -sqlalchemy.orm.mapper.Mapper.single - -# Dynamically added methods where the first argument is not named "self" -sqlalchemy.orm.Load.contains_eager -sqlalchemy.orm.Load.defaultload -sqlalchemy.orm.Load.defer -sqlalchemy.orm.Load.immediateload -sqlalchemy.orm.Load.joinedload -sqlalchemy.orm.Load.lazyload -sqlalchemy.orm.Load.load_only -sqlalchemy.orm.Load.noload -sqlalchemy.orm.Load.raiseload -sqlalchemy.orm.Load.selectin_polymorphic -sqlalchemy.orm.Load.selectinload -sqlalchemy.orm.Load.subqueryload -sqlalchemy.orm.Load.undefer -sqlalchemy.orm.Load.undefer_group -sqlalchemy.orm.Load.with_expression -sqlalchemy.orm.strategy_options.Load.contains_eager -sqlalchemy.orm.strategy_options.Load.defaultload -sqlalchemy.orm.strategy_options.Load.defer -sqlalchemy.orm.strategy_options.Load.immediateload -sqlalchemy.orm.strategy_options.Load.joinedload -sqlalchemy.orm.strategy_options.Load.lazyload -sqlalchemy.orm.strategy_options.Load.load_only -sqlalchemy.orm.strategy_options.Load.noload -sqlalchemy.orm.strategy_options.Load.raiseload -sqlalchemy.orm.strategy_options.Load.selectin_polymorphic -sqlalchemy.orm.strategy_options.Load.selectinload -sqlalchemy.orm.strategy_options.Load.subqueryload -sqlalchemy.orm.strategy_options.Load.undefer -sqlalchemy.orm.strategy_options.Load.undefer_group -sqlalchemy.orm.strategy_options.Load.with_expression - -# unclear problems -sqlalchemy.sql.elements.quoted_name.lower -sqlalchemy.sql.elements.quoted_name.upper -sqlalchemy.sql.expression.quoted_name.lower -sqlalchemy.sql.expression.quoted_name.upper -sqlalchemy.sql.quoted_name.lower -sqlalchemy.sql.quoted_name.upper -sqlalchemy.util.callable diff --git a/stubs/SQLAlchemy/METADATA.toml b/stubs/SQLAlchemy/METADATA.toml deleted file mode 100644 index 5a3c17ff016a..000000000000 --- a/stubs/SQLAlchemy/METADATA.toml +++ /dev/null @@ -1,5 +0,0 @@ -version = "1.4.*" -extra_description = """\ - The `sqlalchemy-stubs` package is an alternative to this package and also \ - includes a mypy plugin for more precise types.\ -""" diff --git a/stubs/SQLAlchemy/sqlalchemy/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/__init__.pyi deleted file mode 100644 index dde3cbce262a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/__init__.pyi +++ /dev/null @@ -1,133 +0,0 @@ -from .engine import ( - create_engine as create_engine, - create_mock_engine as create_mock_engine, - engine_from_config as engine_from_config, -) -from .inspection import inspect as inspect -from .schema import ( - BLANK_SCHEMA as BLANK_SCHEMA, - DDL as DDL, - CheckConstraint as CheckConstraint, - Column as Column, - ColumnDefault as ColumnDefault, - Computed as Computed, - Constraint as Constraint, - DefaultClause as DefaultClause, - FetchedValue as FetchedValue, - ForeignKey as ForeignKey, - ForeignKeyConstraint as ForeignKeyConstraint, - Identity as Identity, - Index as Index, - MetaData as MetaData, - PrimaryKeyConstraint as PrimaryKeyConstraint, - Sequence as Sequence, - Table as Table, - ThreadLocalMetaData as ThreadLocalMetaData, - UniqueConstraint as UniqueConstraint, -) -from .sql import ( - LABEL_STYLE_DEFAULT as LABEL_STYLE_DEFAULT, - LABEL_STYLE_DISAMBIGUATE_ONLY as LABEL_STYLE_DISAMBIGUATE_ONLY, - LABEL_STYLE_NONE as LABEL_STYLE_NONE, - LABEL_STYLE_TABLENAME_PLUS_COL as LABEL_STYLE_TABLENAME_PLUS_COL, - alias as alias, - all_ as all_, - and_ as and_, - any_ as any_, - asc as asc, - between as between, - bindparam as bindparam, - case as case, - cast as cast, - collate as collate, - column as column, - delete as delete, - desc as desc, - distinct as distinct, - except_ as except_, - except_all as except_all, - exists as exists, - extract as extract, - false as false, - func as func, - funcfilter as funcfilter, - insert as insert, - intersect as intersect, - intersect_all as intersect_all, - join as join, - lambda_stmt as lambda_stmt, - lateral as lateral, - literal as literal, - literal_column as literal_column, - modifier as modifier, - not_ as not_, - null as null, - nulls_first as nulls_first, - nulls_last as nulls_last, - nullsfirst as nullsfirst, - nullslast as nullslast, - or_ as or_, - outerjoin as outerjoin, - outparam as outparam, - over as over, - select as select, - subquery as subquery, - table as table, - tablesample as tablesample, - text as text, - true as true, - tuple_ as tuple_, - type_coerce as type_coerce, - union as union, - union_all as union_all, - update as update, - values as values, - within_group as within_group, -) -from .types import ( - ARRAY as ARRAY, - BIGINT as BIGINT, - BINARY as BINARY, - BLOB as BLOB, - BOOLEAN as BOOLEAN, - CHAR as CHAR, - CLOB as CLOB, - DATE as DATE, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - INT as INT, - INTEGER as INTEGER, - JSON as JSON, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - VARBINARY as VARBINARY, - VARCHAR as VARCHAR, - BigInteger as BigInteger, - Boolean as Boolean, - Date as Date, - DateTime as DateTime, - Enum as Enum, - Float as Float, - Integer as Integer, - Interval as Interval, - LargeBinary as LargeBinary, - Numeric as Numeric, - PickleType as PickleType, - SmallInteger as SmallInteger, - String as String, - Text as Text, - Time as Time, - TupleType as TupleType, - TypeDecorator as TypeDecorator, - Unicode as Unicode, - UnicodeText as UnicodeText, -) - -__version__: str diff --git a/stubs/SQLAlchemy/sqlalchemy/cimmutabledict.pyi b/stubs/SQLAlchemy/sqlalchemy/cimmutabledict.pyi deleted file mode 100644 index 851872094694..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/cimmutabledict.pyi +++ /dev/null @@ -1,12 +0,0 @@ -class immutabledict: - def __len__(self) -> int: ... - def __getitem__(self, __item): ... - def __iter__(self): ... - def union(self, **kwargs): ... - def merge_with(self, *args): ... - def keys(self): ... - def __contains__(self, __item): ... - def items(self): ... - def values(self): ... - def get(self, __key, __default=...): ... - def __reduce__(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/connectors/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/connectors/__init__.pyi deleted file mode 100644 index b66d337f00a3..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/connectors/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class Connector: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/connectors/mxodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/connectors/mxodbc.pyi deleted file mode 100644 index d3bfccd46d9f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/connectors/mxodbc.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -from . import Connector - -class MxODBCConnector(Connector): - driver: str - supports_sane_multi_rowcount: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - supports_native_decimal: bool - @classmethod - def dbapi(cls): ... - def on_connect(self): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_execute(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/connectors/pyodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/connectors/pyodbc.pyi deleted file mode 100644 index e821b1964453..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/connectors/pyodbc.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from . import Connector - -class PyODBCConnector(Connector): - driver: str - supports_sane_rowcount_returning: bool - supports_sane_multi_rowcount: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - supports_native_decimal: bool - default_paramstyle: str - use_setinputsizes: bool - pyodbc_driver_name: Any - def __init__(self, supports_unicode_binds: Any | None = ..., use_setinputsizes: bool = ..., **kw) -> None: ... - @classmethod - def dbapi(cls): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def do_set_input_sizes(self, cursor, list_of_tuples, context) -> None: ... - def set_isolation_level(self, connection, level) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/cresultproxy.pyi b/stubs/SQLAlchemy/sqlalchemy/cresultproxy.pyi deleted file mode 100644 index a1e830277edd..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/cresultproxy.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class BaseRow: - def __init__(self, parent, processors, keymap, key_style, data) -> None: ... - def __reduce__(self): ... - def __iter__(self): ... - def __len__(self): ... - def __hash__(self): ... - __getitem__: Any - -def safe_rowproxy_reconstructor(__cls, __state): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/databases/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/databases/__init__.pyi deleted file mode 100644 index 58f463cb74e7..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/databases/__init__.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from ..dialects.firebird import base as firebird_base -from ..dialects.mssql import base as mssql_base -from ..dialects.mysql import base as mysql_base -from ..dialects.oracle import base as oracle_base -from ..dialects.postgresql import base as postgresql_base -from ..dialects.sqlite import base as sqlite_base -from ..dialects.sybase import base as sybase_base - -__all__ = ("firebird", "mssql", "mysql", "postgresql", "sqlite", "oracle", "sybase") - -firebird = firebird_base -mssql = mssql_base -mysql = mysql_base -oracle = oracle_base -postgresql = postgresql_base -postgres = postgresql_base -sqlite = sqlite_base -sybase = sybase_base diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/__init__.pyi deleted file mode 100644 index 63292f3709ce..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/__init__.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -from . import ( - firebird as firebird, - mssql as mssql, - mysql as mysql, - oracle as oracle, - postgresql as postgresql, - sqlite as sqlite, - sybase as sybase, -) - -__all__ = ("firebird", "mssql", "mysql", "oracle", "postgresql", "sqlite", "sybase") - -registry: Any -plugins: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/__init__.pyi deleted file mode 100644 index c421f787eb13..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/__init__.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Any - -from sqlalchemy.dialects.firebird.base import ( - BIGINT as BIGINT, - BLOB as BLOB, - CHAR as CHAR, - DATE as DATE, - FLOAT as FLOAT, - NUMERIC as NUMERIC, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - VARCHAR as VARCHAR, -) - -__all__ = ( - "SMALLINT", - "BIGINT", - "FLOAT", - "FLOAT", - "DATE", - "TIME", - "TEXT", - "NUMERIC", - "FLOAT", - "TIMESTAMP", - "VARCHAR", - "CHAR", - "BLOB", - "dialect", -) - -dialect: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/base.pyi deleted file mode 100644 index d6764ab69e2c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/base.pyi +++ /dev/null @@ -1,108 +0,0 @@ -from typing import Any - -from sqlalchemy import sql, types as sqltypes -from sqlalchemy.engine import default -from sqlalchemy.sql import compiler -from sqlalchemy.types import ( - BIGINT as BIGINT, - BLOB as BLOB, - DATE as DATE, - FLOAT as FLOAT, - INTEGER as INTEGER, - NUMERIC as NUMERIC, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - Integer as Integer, -) - -RESERVED_WORDS: Any - -class _StringType(sqltypes.String): - charset: Any - def __init__(self, charset: Any | None = ..., **kw) -> None: ... - -class VARCHAR(_StringType, sqltypes.VARCHAR): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class CHAR(_StringType, sqltypes.CHAR): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class _FBDateTime(sqltypes.DateTime): - def bind_processor(self, dialect): ... - -colspecs: Any -ischema_names: Any - -class FBTypeCompiler(compiler.GenericTypeCompiler): - def visit_boolean(self, type_, **kw): ... - def visit_datetime(self, type_, **kw): ... - def visit_TEXT(self, type_, **kw): ... - def visit_BLOB(self, type_, **kw): ... - def visit_CHAR(self, type_, **kw): ... - def visit_VARCHAR(self, type_, **kw): ... - -class FBCompiler(sql.compiler.SQLCompiler): - ansi_bind_rules: bool - def visit_now_func(self, fn, **kw): ... - def visit_startswith_op_binary(self, binary, operator, **kw): ... - def visit_not_startswith_op_binary(self, binary, operator, **kw): ... - def visit_mod_binary(self, binary, operator, **kw): ... - def visit_alias(self, alias, asfrom: bool = ..., **kwargs): ... # type: ignore[override] - def visit_substring_func(self, func, **kw): ... - def visit_length_func(self, function, **kw): ... - visit_char_length_func: Any - def function_argspec(self, func, **kw): ... - def default_from(self): ... - def visit_sequence(self, seq, **kw): ... - def get_select_precolumns(self, select, **kw): ... - def limit_clause(self, select, **kw): ... - def returning_clause(self, stmt, returning_cols): ... - -class FBDDLCompiler(sql.compiler.DDLCompiler): - def visit_create_sequence(self, create): ... - def visit_drop_sequence(self, drop): ... - def visit_computed_column(self, generated): ... - -class FBIdentifierPreparer(sql.compiler.IdentifierPreparer): - reserved_words: Any - illegal_initial_characters: Any - def __init__(self, dialect) -> None: ... - -class FBExecutionContext(default.DefaultExecutionContext): - def fire_sequence(self, seq, type_): ... - -class FBDialect(default.DefaultDialect): - name: str - supports_statement_cache: bool - max_identifier_length: int - supports_sequences: bool - sequences_optional: bool - supports_default_values: bool - postfetch_lastrowid: bool - supports_native_boolean: bool - requires_name_normalize: bool - supports_empty_insert: bool - statement_compiler: Any - ddl_compiler: Any - preparer: Any - type_compiler: Any - colspecs: Any - ischema_names: Any - construct_arguments: Any - def __init__(self, *args, **kwargs) -> None: ... - implicit_returning: Any - def initialize(self, connection) -> None: ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] - def has_sequence(self, connection, sequence_name, schema: Any | None = ...): ... # type: ignore[override] - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_definition(self, connection, view_name, schema: Any | None = ..., **kw): ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_column_sequence(self, connection, table_name, column_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_indexes(self, connection, table_name, schema: Any | None = ..., **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/fdb.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/fdb.pyi deleted file mode 100644 index 4bc56c5a6659..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/fdb.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from .kinterbasdb import FBDialect_kinterbasdb - -class FBDialect_fdb(FBDialect_kinterbasdb): - supports_statement_cache: bool - def __init__(self, enable_rowcount: bool = ..., retaining: bool = ..., **kwargs) -> None: ... - @classmethod - def dbapi(cls): ... - def create_connect_args(self, url): ... - -dialect = FBDialect_fdb diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/kinterbasdb.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/kinterbasdb.pyi deleted file mode 100644 index a46e1c36198a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/firebird/kinterbasdb.pyi +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any - -from ...types import Float, Numeric -from .base import FBDialect, FBExecutionContext - -class _kinterbasdb_numeric: - def bind_processor(self, dialect): ... - -class _FBNumeric_kinterbasdb(_kinterbasdb_numeric, Numeric): ... -class _FBFloat_kinterbasdb(_kinterbasdb_numeric, Float): ... - -class FBExecutionContext_kinterbasdb(FBExecutionContext): - @property - def rowcount(self): ... - -class FBDialect_kinterbasdb(FBDialect): - driver: str - supports_statement_cache: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_native_decimal: bool - colspecs: Any - enable_rowcount: Any - type_conv: Any - concurrency_level: Any - retaining: Any - def __init__( - self, type_conv: int = ..., concurrency_level: int = ..., enable_rowcount: bool = ..., retaining: bool = ..., **kwargs - ) -> None: ... - @classmethod - def dbapi(cls): ... - def do_execute(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_rollback(self, dbapi_connection) -> None: ... - def do_commit(self, dbapi_connection) -> None: ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = FBDialect_kinterbasdb diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/__init__.pyi deleted file mode 100644 index c4b6c72f6f65..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/__init__.pyi +++ /dev/null @@ -1,76 +0,0 @@ -from typing import Any - -from .base import ( - BIGINT as BIGINT, - BINARY as BINARY, - BIT as BIT, - CHAR as CHAR, - DATE as DATE, - DATETIME as DATETIME, - DATETIME2 as DATETIME2, - DATETIMEOFFSET as DATETIMEOFFSET, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - IMAGE as IMAGE, - INTEGER as INTEGER, - JSON as JSON, - MONEY as MONEY, - NCHAR as NCHAR, - NTEXT as NTEXT, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - REAL as REAL, - ROWVERSION as ROWVERSION, - SMALLDATETIME as SMALLDATETIME, - SMALLINT as SMALLINT, - SMALLMONEY as SMALLMONEY, - SQL_VARIANT as SQL_VARIANT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - TINYINT as TINYINT, - UNIQUEIDENTIFIER as UNIQUEIDENTIFIER, - VARBINARY as VARBINARY, - VARCHAR as VARCHAR, - XML as XML, - try_cast as try_cast, -) - -__all__ = ( - "JSON", - "INTEGER", - "BIGINT", - "SMALLINT", - "TINYINT", - "VARCHAR", - "NVARCHAR", - "CHAR", - "NCHAR", - "TEXT", - "NTEXT", - "DECIMAL", - "NUMERIC", - "FLOAT", - "DATETIME", - "DATETIME2", - "DATETIMEOFFSET", - "DATE", - "TIME", - "SMALLDATETIME", - "BINARY", - "VARBINARY", - "BIT", - "REAL", - "IMAGE", - "TIMESTAMP", - "ROWVERSION", - "MONEY", - "SMALLMONEY", - "UNIQUEIDENTIFIER", - "SQL_VARIANT", - "XML", - "dialect", - "try_cast", -) - -dialect: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/base.pyi deleted file mode 100644 index b1c24b256dfd..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/base.pyi +++ /dev/null @@ -1,316 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from ...engine import default -from ...sql import compiler -from ...sql.elements import Cast -from ...types import ( - BIGINT as BIGINT, - BINARY as BINARY, - CHAR as CHAR, - DATE as DATE, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - INTEGER as INTEGER, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - SMALLINT as SMALLINT, - TEXT as TEXT, - VARCHAR as VARCHAR, -) -from .json import JSON as JSON - -MS_2017_VERSION: Any -MS_2016_VERSION: Any -MS_2014_VERSION: Any -MS_2012_VERSION: Any -MS_2008_VERSION: Any -MS_2005_VERSION: Any -MS_2000_VERSION: Any -RESERVED_WORDS: Any - -class REAL(sqltypes.REAL): - __visit_name__: str - def __init__(self, **kw) -> None: ... - -class TINYINT(sqltypes.Integer): - __visit_name__: str - -class _MSDate(sqltypes.Date): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class TIME(sqltypes.TIME): - precision: Any - def __init__(self, precision: Any | None = ..., **kwargs) -> None: ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -_MSTime = TIME - -class _BASETIMEIMPL(TIME): - __visit_name__: str - -class _DateTimeBase: - def bind_processor(self, dialect): ... - -class _MSDateTime(_DateTimeBase, sqltypes.DateTime): ... - -class SMALLDATETIME(_DateTimeBase, sqltypes.DateTime): - __visit_name__: str - -class DATETIME2(_DateTimeBase, sqltypes.DateTime): - __visit_name__: str - precision: Any - def __init__(self, precision: Any | None = ..., **kw) -> None: ... - -class DATETIMEOFFSET(_DateTimeBase, sqltypes.DateTime): - __visit_name__: str - precision: Any - def __init__(self, precision: Any | None = ..., **kw) -> None: ... - -class _UnicodeLiteral: - def literal_processor(self, dialect): ... - -class _MSUnicode(_UnicodeLiteral, sqltypes.Unicode): ... -class _MSUnicodeText(_UnicodeLiteral, sqltypes.UnicodeText): ... - -class TIMESTAMP(sqltypes._Binary): - __visit_name__: str - length: Any - convert_int: Any - def __init__(self, convert_int: bool = ...) -> None: ... - def result_processor(self, dialect, coltype): ... - -class ROWVERSION(TIMESTAMP): - __visit_name__: str - -class NTEXT(sqltypes.UnicodeText): - __visit_name__: str - -class VARBINARY(sqltypes.VARBINARY, sqltypes.LargeBinary): - __visit_name__: str - -class IMAGE(sqltypes.LargeBinary): - __visit_name__: str - -class XML(sqltypes.Text): - __visit_name__: str - -class BIT(sqltypes.Boolean): - __visit_name__: str - -class MONEY(sqltypes.TypeEngine): - __visit_name__: str - -class SMALLMONEY(sqltypes.TypeEngine): - __visit_name__: str - -class UNIQUEIDENTIFIER(sqltypes.TypeEngine): - __visit_name__: str - -class SQL_VARIANT(sqltypes.TypeEngine): - __visit_name__: str - -class TryCast(Cast): - __visit_name__: str - stringify_dialect: str - inherit_cache: bool - def __init__(self, *arg, **kw) -> None: ... - -try_cast: Any -MSDateTime: Any -MSDate: Any -MSReal = REAL -MSTinyInteger = TINYINT -MSTime = TIME -MSSmallDateTime = SMALLDATETIME -MSDateTime2 = DATETIME2 -MSDateTimeOffset = DATETIMEOFFSET -MSText = TEXT -MSNText = NTEXT -MSString = VARCHAR -MSNVarchar = NVARCHAR -MSChar = CHAR -MSNChar = NCHAR -MSBinary = BINARY -MSVarBinary = VARBINARY -MSImage = IMAGE -MSBit = BIT -MSMoney = MONEY -MSSmallMoney = SMALLMONEY -MSUniqueIdentifier = UNIQUEIDENTIFIER -MSVariant = SQL_VARIANT -ischema_names: Any - -class MSTypeCompiler(compiler.GenericTypeCompiler): - def visit_FLOAT(self, type_, **kw): ... - def visit_TINYINT(self, type_, **kw): ... - def visit_TIME(self, type_, **kw): ... - def visit_TIMESTAMP(self, type_, **kw): ... - def visit_ROWVERSION(self, type_, **kw): ... - def visit_datetime(self, type_, **kw): ... - def visit_DATETIMEOFFSET(self, type_, **kw): ... - def visit_DATETIME2(self, type_, **kw): ... - def visit_SMALLDATETIME(self, type_, **kw): ... - def visit_unicode(self, type_, **kw): ... - def visit_text(self, type_, **kw): ... - def visit_unicode_text(self, type_, **kw): ... - def visit_NTEXT(self, type_, **kw): ... - def visit_TEXT(self, type_, **kw): ... - def visit_VARCHAR(self, type_, **kw): ... - def visit_CHAR(self, type_, **kw): ... - def visit_NCHAR(self, type_, **kw): ... - def visit_NVARCHAR(self, type_, **kw): ... - def visit_date(self, type_, **kw): ... - def visit__BASETIMEIMPL(self, type_, **kw): ... - def visit_time(self, type_, **kw): ... - def visit_large_binary(self, type_, **kw): ... - def visit_IMAGE(self, type_, **kw): ... - def visit_XML(self, type_, **kw): ... - def visit_VARBINARY(self, type_, **kw): ... - def visit_boolean(self, type_, **kw): ... - def visit_BIT(self, type_, **kw): ... - def visit_JSON(self, type_, **kw): ... - def visit_MONEY(self, type_, **kw): ... - def visit_SMALLMONEY(self, type_, **kw): ... - def visit_UNIQUEIDENTIFIER(self, type_, **kw): ... - def visit_SQL_VARIANT(self, type_, **kw): ... - -class MSExecutionContext(default.DefaultExecutionContext): - def pre_exec(self) -> None: ... - cursor_fetch_strategy: Any - def post_exec(self) -> None: ... - def get_lastrowid(self): ... - @property - def rowcount(self): ... - def handle_dbapi_exception(self, e) -> None: ... - def get_result_cursor_strategy(self, result): ... - def fire_sequence(self, seq, type_): ... - def get_insert_default(self, column): ... - -class MSSQLCompiler(compiler.SQLCompiler): - returning_precedes_values: bool - extract_map: Any - tablealiases: Any - def __init__(self, *args, **kwargs) -> None: ... - def visit_now_func(self, fn, **kw): ... - def visit_current_date_func(self, fn, **kw): ... - def visit_length_func(self, fn, **kw): ... - def visit_char_length_func(self, fn, **kw): ... - def visit_concat_op_binary(self, binary, operator, **kw): ... - def visit_true(self, expr, **kw): ... - def visit_false(self, expr, **kw): ... - def visit_match_op_binary(self, binary, operator, **kw): ... - def get_select_precolumns(self, select, **kw): ... - def get_from_hint_text(self, table, text): ... - def get_crud_hint_text(self, table, text): ... - def fetch_clause(self, cs, **kwargs): ... - def limit_clause(self, cs, **kwargs): ... - def visit_try_cast(self, element, **kw): ... - def translate_select_structure(self, select_stmt, **kwargs): ... - def visit_table(self, table, mssql_aliased: bool = ..., iscrud: bool = ..., **kwargs): ... # type: ignore[override] - def visit_alias(self, alias, **kw): ... - def visit_column(self, column, add_to_result_map: Any | None = ..., **kw): ... # type: ignore[override] - def visit_extract(self, extract, **kw): ... - def visit_savepoint(self, savepoint_stmt): ... - def visit_rollback_to_savepoint(self, savepoint_stmt): ... - def visit_binary(self, binary, **kwargs): ... - def returning_clause(self, stmt, returning_cols): ... - def get_cte_preamble(self, recursive): ... - def label_select_column(self, select, column, asfrom): ... - def for_update_clause(self, select, **kw): ... - def order_by_clause(self, select, **kw): ... - def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw): ... - def delete_table_clause(self, delete_stmt, from_table, extra_froms): ... - def delete_extra_from_clause(self, delete_stmt, from_table, extra_froms, from_hints, **kw): ... - def visit_empty_set_expr(self, type_): ... - def visit_is_distinct_from_binary(self, binary, operator, **kw): ... - def visit_is_not_distinct_from_binary(self, binary, operator, **kw): ... - def visit_json_getitem_op_binary(self, binary, operator, **kw): ... - def visit_json_path_getitem_op_binary(self, binary, operator, **kw): ... - def visit_sequence(self, seq, **kw): ... - -class MSSQLStrictCompiler(MSSQLCompiler): - ansi_bind_rules: bool - def visit_in_op_binary(self, binary, operator, **kw): ... - def visit_not_in_op_binary(self, binary, operator, **kw): ... - def render_literal_value(self, value, type_): ... - -class MSDDLCompiler(compiler.DDLCompiler): - def get_column_specification(self, column, **kwargs): ... - def visit_create_index(self, create, include_schema: bool = ...): ... # type: ignore[override] - def visit_drop_index(self, drop): ... - def visit_primary_key_constraint(self, constraint): ... - def visit_unique_constraint(self, constraint): ... - def visit_computed_column(self, generated): ... - def visit_create_sequence(self, create, **kw): ... - def visit_identity_column(self, identity, **kw): ... - -class MSIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words: Any - def __init__(self, dialect) -> None: ... - def quote_schema(self, schema, force: Any | None = ...): ... - -class MSDialect(default.DefaultDialect): - name: str - supports_statement_cache: bool - supports_default_values: bool - supports_empty_insert: bool - use_scope_identity: bool - max_identifier_length: int - schema_name: str - implicit_returning: bool - full_returning: bool - colspecs: Any - engine_config_types: Any - ischema_names: Any - supports_sequences: bool - sequences_optional: bool - default_sequence_base: int - supports_native_boolean: bool - non_native_boolean_check_constraint: bool - supports_unicode_binds: bool - postfetch_lastrowid: bool - legacy_schema_aliasing: bool - server_version_info: Any - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - preparer: Any - construct_arguments: Any - query_timeout: Any - deprecate_large_types: Any - isolation_level: Any - def __init__( - self, - query_timeout: Any | None = ..., - use_scope_identity: bool = ..., - schema_name: str = ..., - isolation_level: Any | None = ..., - deprecate_large_types: Any | None = ..., - json_serializer: Any | None = ..., - json_deserializer: Any | None = ..., - legacy_schema_aliasing: Any | None = ..., - **opts, - ) -> None: ... - def do_savepoint(self, connection, name) -> None: ... - def do_release_savepoint(self, connection, name) -> None: ... - def set_isolation_level(self, connection, level) -> None: ... - def get_isolation_level(self, connection): ... - def initialize(self, connection) -> None: ... - def on_connect(self): ... - def has_table(self, connection, tablename, dbname, owner, schema): ... - def has_sequence(self, connection, sequencename, dbname, owner, schema): ... - def get_sequence_names(self, connection, dbname, owner, schema, **kw): ... - def get_schema_names(self, connection, **kw): ... - def get_table_names(self, connection, dbname, owner, schema, **kw): ... - def get_view_names(self, connection, dbname, owner, schema, **kw): ... - def get_indexes(self, connection, tablename, dbname, owner, schema, **kw): ... - def get_view_definition(self, connection, viewname, dbname, owner, schema, **kw): ... - def get_columns(self, connection, tablename, dbname, owner, schema, **kw): ... - def get_pk_constraint(self, connection, tablename, dbname, owner, schema, **kw): ... - def get_foreign_keys(self, connection, tablename, dbname, owner, schema, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/information_schema.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/information_schema.pyi deleted file mode 100644 index ec1a2504cf10..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/information_schema.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any - -from ...sql import expression -from ...types import TypeDecorator - -ischema: Any - -class CoerceUnicode(TypeDecorator): - impl: Any - cache_ok: bool - def process_bind_param(self, value, dialect): ... - def bind_expression(self, bindvalue): ... - -class _cast_on_2005(expression.ColumnElement): - bindvalue: Any - def __init__(self, bindvalue) -> None: ... - -schemata: Any -tables: Any -columns: Any -mssql_temp_table_columns: Any -constraints: Any -column_constraints: Any -key_constraints: Any -ref_constraints: Any -views: Any -computed_columns: Any -sequences: Any - -class IdentitySqlVariant(TypeDecorator): - impl: Any - cache_ok: bool - def column_expression(self, colexpr): ... - -identity_columns: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/json.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/json.pyi deleted file mode 100644 index 2ced3beece0d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/json.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from ...types import JSON as _JSON - -class JSON(_JSON): ... - -class _FormatTypeMixin: - def bind_processor(self, dialect): ... - def literal_processor(self, dialect): ... - -class JSONIndexType(_FormatTypeMixin, _JSON.JSONIndexType): ... -class JSONPathType(_FormatTypeMixin, _JSON.JSONPathType): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/mxodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/mxodbc.pyi deleted file mode 100644 index bddc1929a4b9..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/mxodbc.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any - -from ...connectors.mxodbc import MxODBCConnector -from .base import VARBINARY, MSDialect, _MSDate, _MSTime -from .pyodbc import MSExecutionContext_pyodbc, _MSNumeric_pyodbc - -class _MSNumeric_mxodbc(_MSNumeric_pyodbc): ... - -class _MSDate_mxodbc(_MSDate): - def bind_processor(self, dialect): ... - -class _MSTime_mxodbc(_MSTime): - def bind_processor(self, dialect): ... - -class _VARBINARY_mxodbc(VARBINARY): - def bind_processor(self, dialect): ... - -class MSExecutionContext_mxodbc(MSExecutionContext_pyodbc): ... - -class MSDialect_mxodbc(MxODBCConnector, MSDialect): - supports_statement_cache: bool - colspecs: Any - description_encoding: Any - def __init__(self, description_encoding: Any | None = ..., **params) -> None: ... - -dialect = MSDialect_mxodbc diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/pymssql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/pymssql.pyi deleted file mode 100644 index b16a0b4f729f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/pymssql.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Any - -from ...types import Numeric -from .base import MSDialect, MSIdentifierPreparer - -class _MSNumeric_pymssql(Numeric): - def result_processor(self, dialect, type_): ... - -class MSIdentifierPreparer_pymssql(MSIdentifierPreparer): - def __init__(self, dialect) -> None: ... - -class MSDialect_pymssql(MSDialect): - supports_statement_cache: bool - supports_native_decimal: bool - driver: str - preparer: Any - colspecs: Any - @classmethod - def dbapi(cls): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def set_isolation_level(self, connection, level) -> None: ... - -dialect = MSDialect_pymssql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/pyodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/pyodbc.pyi deleted file mode 100644 index 907824cea6f3..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/pyodbc.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Any - -from ...connectors.pyodbc import PyODBCConnector -from ...types import DateTime, Float, Numeric -from .base import BINARY, DATETIMEOFFSET, VARBINARY, MSDialect, MSExecutionContext - -class _ms_numeric_pyodbc: - def bind_processor(self, dialect): ... - -class _MSNumeric_pyodbc(_ms_numeric_pyodbc, Numeric): ... -class _MSFloat_pyodbc(_ms_numeric_pyodbc, Float): ... - -class _ms_binary_pyodbc: - def bind_processor(self, dialect): ... - -class _ODBCDateTimeBindProcessor: - has_tz: bool - def bind_processor(self, dialect): ... - -class _ODBCDateTime(_ODBCDateTimeBindProcessor, DateTime): ... - -class _ODBCDATETIMEOFFSET(_ODBCDateTimeBindProcessor, DATETIMEOFFSET): - has_tz: bool - -class _VARBINARY_pyodbc(_ms_binary_pyodbc, VARBINARY): ... -class _BINARY_pyodbc(_ms_binary_pyodbc, BINARY): ... - -class MSExecutionContext_pyodbc(MSExecutionContext): - def pre_exec(self) -> None: ... - def post_exec(self) -> None: ... - -class MSDialect_pyodbc(PyODBCConnector, MSDialect): - supports_statement_cache: bool - supports_sane_rowcount_returning: bool - colspecs: Any - description_encoding: Any - use_scope_identity: Any - fast_executemany: Any - def __init__(self, description_encoding: Any | None = ..., fast_executemany: bool = ..., **params) -> None: ... - def on_connect(self): ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = MSDialect_pyodbc diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/__init__.pyi deleted file mode 100644 index faaa7d6e642a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/__init__.pyi +++ /dev/null @@ -1,85 +0,0 @@ -from typing import Any - -from .base import ( - BIGINT as BIGINT, - BINARY as BINARY, - BIT as BIT, - BLOB as BLOB, - BOOLEAN as BOOLEAN, - CHAR as CHAR, - DATE as DATE, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - DOUBLE as DOUBLE, - ENUM as ENUM, - FLOAT as FLOAT, - INTEGER as INTEGER, - JSON as JSON, - LONGBLOB as LONGBLOB, - LONGTEXT as LONGTEXT, - MEDIUMBLOB as MEDIUMBLOB, - MEDIUMINT as MEDIUMINT, - MEDIUMTEXT as MEDIUMTEXT, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - REAL as REAL, - SET as SET, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - TINYBLOB as TINYBLOB, - TINYINT as TINYINT, - TINYTEXT as TINYTEXT, - VARBINARY as VARBINARY, - VARCHAR as VARCHAR, - YEAR as YEAR, -) -from .dml import Insert as Insert, insert as insert -from .expression import match as match - -__all__ = ( - "BIGINT", - "BINARY", - "BIT", - "BLOB", - "BOOLEAN", - "CHAR", - "DATE", - "DATETIME", - "DECIMAL", - "DOUBLE", - "ENUM", - "DECIMAL", - "FLOAT", - "INTEGER", - "INTEGER", - "JSON", - "LONGBLOB", - "LONGTEXT", - "MEDIUMBLOB", - "MEDIUMINT", - "MEDIUMTEXT", - "NCHAR", - "NVARCHAR", - "NUMERIC", - "SET", - "SMALLINT", - "REAL", - "TEXT", - "TIME", - "TIMESTAMP", - "TINYBLOB", - "TINYINT", - "TINYTEXT", - "VARBINARY", - "VARCHAR", - "YEAR", - "dialect", - "insert", - "Insert", - "match", -) - -dialect: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/aiomysql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/aiomysql.pyi deleted file mode 100644 index 4021fd9061ba..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/aiomysql.pyi +++ /dev/null @@ -1,73 +0,0 @@ -from typing import Any - -from ...engine import AdaptedConnection -from .pymysql import MySQLDialect_pymysql - -class AsyncAdapt_aiomysql_cursor: - server_side: bool - await_: Any - def __init__(self, adapt_connection) -> None: ... - @property - def description(self): ... - @property - def rowcount(self): ... - @property - def arraysize(self): ... - @arraysize.setter - def arraysize(self, value) -> None: ... - @property - def lastrowid(self): ... - def close(self) -> None: ... - def execute(self, operation, parameters: Any | None = ...): ... - def executemany(self, operation, seq_of_parameters): ... - def setinputsizes(self, *inputsizes) -> None: ... - def __iter__(self): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_aiomysql_ss_cursor(AsyncAdapt_aiomysql_cursor): - server_side: bool - await_: Any - def __init__(self, adapt_connection) -> None: ... - def close(self) -> None: ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_aiomysql_connection(AdaptedConnection): - await_: Any - dbapi: Any - def __init__(self, dbapi, connection) -> None: ... - def ping(self, reconnect): ... - def character_set_name(self): ... - def autocommit(self, value) -> None: ... - def cursor(self, server_side: bool = ...): ... - def rollback(self) -> None: ... - def commit(self) -> None: ... - def close(self) -> None: ... - -class AsyncAdaptFallback_aiomysql_connection(AsyncAdapt_aiomysql_connection): - await_: Any - -class AsyncAdapt_aiomysql_dbapi: - aiomysql: Any - pymysql: Any - paramstyle: str - def __init__(self, aiomysql, pymysql) -> None: ... - def connect(self, *arg, **kw): ... - -class MySQLDialect_aiomysql(MySQLDialect_pymysql): - driver: str - supports_statement_cache: bool - supports_server_side_cursors: bool - is_async: bool - @classmethod - def dbapi(cls): ... - @classmethod - def get_pool_class(cls, url): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def get_driver_connection(self, connection): ... - -dialect = MySQLDialect_aiomysql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/asyncmy.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/asyncmy.pyi deleted file mode 100644 index 6c37f8d5ab16..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/asyncmy.pyi +++ /dev/null @@ -1,73 +0,0 @@ -from typing import Any - -from ...engine import AdaptedConnection -from .pymysql import MySQLDialect_pymysql - -class AsyncAdapt_asyncmy_cursor: - server_side: bool - await_: Any - def __init__(self, adapt_connection) -> None: ... - @property - def description(self): ... - @property - def rowcount(self): ... - @property - def arraysize(self): ... - @arraysize.setter - def arraysize(self, value) -> None: ... - @property - def lastrowid(self): ... - def close(self) -> None: ... - def execute(self, operation, parameters: Any | None = ...): ... - def executemany(self, operation, seq_of_parameters): ... - def setinputsizes(self, *inputsizes) -> None: ... - def __iter__(self): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_asyncmy_ss_cursor(AsyncAdapt_asyncmy_cursor): - server_side: bool - await_: Any - def __init__(self, adapt_connection) -> None: ... - def close(self) -> None: ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_asyncmy_connection(AdaptedConnection): - await_: Any - dbapi: Any - def __init__(self, dbapi, connection) -> None: ... - def ping(self, reconnect): ... - def character_set_name(self): ... - def autocommit(self, value) -> None: ... - def cursor(self, server_side: bool = ...): ... - def rollback(self) -> None: ... - def commit(self) -> None: ... - def close(self) -> None: ... - -class AsyncAdaptFallback_asyncmy_connection(AsyncAdapt_asyncmy_connection): - await_: Any - -class AsyncAdapt_asyncmy_dbapi: - asyncmy: Any - pymysql: Any - paramstyle: str - def __init__(self, asyncmy, pymysql) -> None: ... - def connect(self, *arg, **kw): ... - -class MySQLDialect_asyncmy(MySQLDialect_pymysql): - driver: str - supports_statement_cache: bool - supports_server_side_cursors: bool - is_async: bool - @classmethod - def dbapi(cls): ... - @classmethod - def get_pool_class(cls, url): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def get_driver_connection(self, connection): ... - -dialect = MySQLDialect_asyncmy diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/base.pyi deleted file mode 100644 index a7b58f6ea754..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/base.pyi +++ /dev/null @@ -1,239 +0,0 @@ -from typing import Any - -from ...engine import default -from ...sql import compiler -from ...types import BINARY as BINARY, BLOB as BLOB, BOOLEAN as BOOLEAN, DATE as DATE, VARBINARY as VARBINARY -from .enumerated import ENUM as ENUM, SET as SET -from .json import JSON as JSON -from .types import ( - BIGINT as BIGINT, - BIT as BIT, - CHAR as CHAR, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - DOUBLE as DOUBLE, - FLOAT as FLOAT, - INTEGER as INTEGER, - LONGBLOB as LONGBLOB, - LONGTEXT as LONGTEXT, - MEDIUMBLOB as MEDIUMBLOB, - MEDIUMINT as MEDIUMINT, - MEDIUMTEXT as MEDIUMTEXT, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - TINYBLOB as TINYBLOB, - TINYINT as TINYINT, - TINYTEXT as TINYTEXT, - VARCHAR as VARCHAR, - YEAR as YEAR, -) - -AUTOCOMMIT_RE: Any -SET_RE: Any -MSTime = TIME -MSSet = SET -MSEnum = ENUM -MSLongBlob = LONGBLOB -MSMediumBlob = MEDIUMBLOB -MSTinyBlob = TINYBLOB -MSBlob = BLOB -MSBinary = BINARY -MSVarBinary = VARBINARY -MSNChar = NCHAR -MSNVarChar = NVARCHAR -MSChar = CHAR -MSString = VARCHAR -MSLongText = LONGTEXT -MSMediumText = MEDIUMTEXT -MSTinyText = TINYTEXT -MSText = TEXT -MSYear = YEAR -MSTimeStamp = TIMESTAMP -MSBit = BIT -MSSmallInteger = SMALLINT -MSTinyInteger = TINYINT -MSMediumInteger = MEDIUMINT -MSBigInteger = BIGINT -MSNumeric = NUMERIC -MSDecimal = DECIMAL -MSDouble = DOUBLE -MSReal = REAL -MSFloat = FLOAT -MSInteger = INTEGER -colspecs: Any -ischema_names: Any - -class MySQLExecutionContext(default.DefaultExecutionContext): - def should_autocommit_text(self, statement): ... - def create_server_side_cursor(self): ... - def fire_sequence(self, seq, type_): ... - -class MySQLCompiler(compiler.SQLCompiler): - render_table_with_column_in_update_from: bool - extract_map: Any - def default_from(self): ... - def visit_random_func(self, fn, **kw): ... - def visit_sequence(self, seq, **kw): ... - def visit_sysdate_func(self, fn, **kw): ... - def visit_json_getitem_op_binary(self, binary, operator, **kw): ... - def visit_json_path_getitem_op_binary(self, binary, operator, **kw): ... - def visit_on_duplicate_key_update(self, on_duplicate, **kw): ... - def visit_concat_op_binary(self, binary, operator, **kw): ... - def visit_mysql_match(self, element, **kw): ... - def visit_match_op_binary(self, binary, operator, **kw): ... - def get_from_hint_text(self, table, text): ... - def visit_typeclause(self, typeclause, type_: Any | None = ..., **kw): ... - def visit_cast(self, cast, **kw): ... - def render_literal_value(self, value, type_): ... - def visit_true(self, element, **kw): ... - def visit_false(self, element, **kw): ... - def get_select_precolumns(self, select, **kw): ... - def visit_join(self, join, asfrom: bool = ..., from_linter: Any | None = ..., **kwargs): ... - def for_update_clause(self, select, **kw): ... - def limit_clause(self, select, **kw): ... - def update_limit_clause(self, update_stmt): ... - def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw): ... - def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw) -> None: ... - def delete_table_clause(self, delete_stmt, from_table, extra_froms): ... - def delete_extra_from_clause(self, delete_stmt, from_table, extra_froms, from_hints, **kw): ... - def visit_empty_set_expr(self, element_types): ... - def visit_is_distinct_from_binary(self, binary, operator, **kw): ... - def visit_is_not_distinct_from_binary(self, binary, operator, **kw): ... - def visit_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_not_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_regexp_replace_op_binary(self, binary, operator, **kw): ... - -class MySQLDDLCompiler(compiler.DDLCompiler): - def get_column_specification(self, column, **kw): ... - def post_create_table(self, table): ... - def visit_create_index(self, create, **kw): ... - def visit_primary_key_constraint(self, constraint): ... - def visit_drop_index(self, drop): ... - def visit_drop_constraint(self, drop): ... - def define_constraint_match(self, constraint): ... - def visit_set_table_comment(self, create): ... - def visit_drop_table_comment(self, create): ... - def visit_set_column_comment(self, create): ... - -class MySQLTypeCompiler(compiler.GenericTypeCompiler): - def visit_NUMERIC(self, type_, **kw): ... - def visit_DECIMAL(self, type_, **kw): ... - def visit_DOUBLE(self, type_, **kw): ... - def visit_REAL(self, type_, **kw): ... - def visit_FLOAT(self, type_, **kw): ... - def visit_INTEGER(self, type_, **kw): ... - def visit_BIGINT(self, type_, **kw): ... - def visit_MEDIUMINT(self, type_, **kw): ... - def visit_TINYINT(self, type_, **kw): ... - def visit_SMALLINT(self, type_, **kw): ... - def visit_BIT(self, type_, **kw): ... - def visit_DATETIME(self, type_, **kw): ... - def visit_DATE(self, type_, **kw): ... - def visit_TIME(self, type_, **kw): ... - def visit_TIMESTAMP(self, type_, **kw): ... - def visit_YEAR(self, type_, **kw): ... - def visit_TEXT(self, type_, **kw): ... - def visit_TINYTEXT(self, type_, **kw): ... - def visit_MEDIUMTEXT(self, type_, **kw): ... - def visit_LONGTEXT(self, type_, **kw): ... - def visit_VARCHAR(self, type_, **kw): ... - def visit_CHAR(self, type_, **kw): ... - def visit_NVARCHAR(self, type_, **kw): ... - def visit_NCHAR(self, type_, **kw): ... - def visit_VARBINARY(self, type_, **kw): ... - def visit_JSON(self, type_, **kw): ... - def visit_large_binary(self, type_, **kw): ... - def visit_enum(self, type_, **kw): ... - def visit_BLOB(self, type_, **kw): ... - def visit_TINYBLOB(self, type_, **kw): ... - def visit_MEDIUMBLOB(self, type_, **kw): ... - def visit_LONGBLOB(self, type_, **kw): ... - def visit_ENUM(self, type_, **kw): ... - def visit_SET(self, type_, **kw): ... - def visit_BOOLEAN(self, type_, **kw): ... - -class MySQLIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words: Any - def __init__(self, dialect, server_ansiquotes: bool = ..., **kw) -> None: ... - -class MariaDBIdentifierPreparer(MySQLIdentifierPreparer): - reserved_words: Any - -class MySQLDialect(default.DefaultDialect): - logger: Any - name: str - supports_statement_cache: bool - supports_alter: bool - supports_native_boolean: bool - max_identifier_length: int - max_index_name_length: int - max_constraint_name_length: int - supports_native_enum: bool - supports_sequences: bool - sequences_optional: bool - supports_for_update_of: bool - supports_default_values: bool - supports_default_metavalue: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_multivalues_insert: bool - supports_comments: bool - inline_comments: bool - default_paramstyle: str - colspecs: Any - cte_follows_insert: bool - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - ischema_names: Any - preparer: Any - is_mariadb: bool - construct_arguments: Any - isolation_level: Any - def __init__( - self, - isolation_level: Any | None = ..., - json_serializer: Any | None = ..., - json_deserializer: Any | None = ..., - is_mariadb: Any | None = ..., - **kwargs, - ) -> None: ... - def on_connect(self): ... - def set_isolation_level(self, connection, level) -> None: ... - def get_isolation_level(self, connection): ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_recover_twophase(self, connection): ... - def is_disconnect(self, e, connection, cursor): ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] - def has_sequence(self, connection, sequence_name, schema: Any | None = ...): ... # type: ignore[override] - def get_sequence_names(self, connection, schema: Any | None = ..., **kw): ... - identifier_preparer: Any - def initialize(self, connection) -> None: ... - def get_schema_names(self, connection, **kw): ... - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_names(self, connection, schema: Any | None = ..., **kw): ... - def get_table_options(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_check_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_table_comment(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_indexes(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_unique_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_view_definition(self, connection, view_name, schema: Any | None = ..., **kw): ... - -class _DecodingRow: - rowproxy: Any - charset: Any - def __init__(self, rowproxy, charset) -> None: ... - def __getitem__(self, index): ... - def __getattr__(self, attr): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/cymysql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/cymysql.pyi deleted file mode 100644 index 408d931df22d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/cymysql.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from .base import BIT -from .mysqldb import MySQLDialect_mysqldb - -class _cymysqlBIT(BIT): - def result_processor(self, dialect, coltype): ... - -class MySQLDialect_cymysql(MySQLDialect_mysqldb): - driver: str - supports_statement_cache: bool - description_encoding: Any - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_unicode_statements: bool - colspecs: Any - @classmethod - def dbapi(cls): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = MySQLDialect_cymysql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/dml.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/dml.pyi deleted file mode 100644 index 77b095c16b73..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/dml.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Any - -from ...sql.dml import Insert as StandardInsert -from ...sql.elements import ClauseElement -from ...util import memoized_property - -class Insert(StandardInsert): - stringify_dialect: str - inherit_cache: bool - @property - def inserted(self): ... - @memoized_property - def inserted_alias(self): ... - def on_duplicate_key_update(self, *args, **kw) -> None: ... - -insert: Any - -class OnDuplicateClause(ClauseElement): - __visit_name__: str - stringify_dialect: str - inserted_alias: Any - update: Any - def __init__(self, inserted_alias, update) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/enumerated.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/enumerated.pyi deleted file mode 100644 index ba9343513318..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/enumerated.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from ...sql import sqltypes -from .types import _StringType - -class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum, _StringType): # type: ignore[misc] - __visit_name__: str - native_enum: bool - def __init__(self, *enums, **kw) -> None: ... - @classmethod - def adapt_emulated_to_native(cls, impl, **kw): ... - -class SET(_StringType): - __visit_name__: str - retrieve_as_bitwise: Any - values: Any - def __init__(self, *values, **kw) -> None: ... - def column_expression(self, colexpr): ... - def result_processor(self, dialect, coltype): ... - def bind_processor(self, dialect): ... - def adapt(self, impltype, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/expression.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/expression.pyi deleted file mode 100644 index 24d63634ffac..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/expression.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from ...sql import elements -from ...sql.base import Generative - -class match(Generative, elements.BinaryExpression): - __visit_name__: str - inherit_cache: bool - def __init__(self, *cols, **kw) -> None: ... - modifiers: Any - def in_boolean_mode(self) -> None: ... - def in_natural_language_mode(self) -> None: ... - def with_query_expansion(self) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/json.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/json.pyi deleted file mode 100644 index c35f9c440158..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/json.pyi +++ /dev/null @@ -1,10 +0,0 @@ -import sqlalchemy.types as sqltypes - -class JSON(sqltypes.JSON): ... - -class _FormatTypeMixin: - def bind_processor(self, dialect): ... - def literal_processor(self, dialect): ... - -class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType): ... -class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mariadb.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mariadb.pyi deleted file mode 100644 index db8f5abd5f09..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mariadb.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from .base import MySQLDialect - -class MariaDBDialect(MySQLDialect): - is_mariadb: bool - supports_statement_cache: bool - name: str - preparer: Any - -def loader(driver): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mariadbconnector.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mariadbconnector.pyi deleted file mode 100644 index 0735fb75a28e..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mariadbconnector.pyi +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Any - -from .base import MySQLCompiler, MySQLDialect, MySQLExecutionContext - -mariadb_cpy_minimum_version: Any - -class MySQLExecutionContext_mariadbconnector(MySQLExecutionContext): - def create_server_side_cursor(self): ... - def create_default_cursor(self): ... - -class MySQLCompiler_mariadbconnector(MySQLCompiler): ... - -class MySQLDialect_mariadbconnector(MySQLDialect): - driver: str - supports_statement_cache: bool - supports_unicode_statements: bool - encoding: str - convert_unicode: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_native_decimal: bool - default_paramstyle: str - statement_compiler: Any - supports_server_side_cursors: bool - paramstyle: str - def __init__(self, **kwargs) -> None: ... - @classmethod - def dbapi(cls): ... - def is_disconnect(self, e, connection, cursor): ... - def create_connect_args(self, url): ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - -dialect = MySQLDialect_mariadbconnector diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mysqlconnector.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mysqlconnector.pyi deleted file mode 100644 index df0a63589b1c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mysqlconnector.pyi +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any - -from ...util import memoized_property -from .base import BIT, MySQLCompiler, MySQLDialect, MySQLIdentifierPreparer - -class MySQLCompiler_mysqlconnector(MySQLCompiler): - def visit_mod_binary(self, binary, operator, **kw): ... - def post_process_text(self, text): ... - def escape_literal_column(self, text): ... - -class MySQLIdentifierPreparer_mysqlconnector(MySQLIdentifierPreparer): ... - -class _myconnpyBIT(BIT): - def result_processor(self, dialect, coltype) -> None: ... - -class MySQLDialect_mysqlconnector(MySQLDialect): - driver: str - supports_statement_cache: bool - supports_unicode_binds: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_native_decimal: bool - default_paramstyle: str - statement_compiler: Any - preparer: Any - colspecs: Any - def __init__(self, *arg, **kw) -> None: ... - @property - def description_encoding(self): ... - @memoized_property - def supports_unicode_statements(self): ... - @classmethod - def dbapi(cls): ... - def do_ping(self, dbapi_connection): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = MySQLDialect_mysqlconnector diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mysqldb.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mysqldb.pyi deleted file mode 100644 index bb41d161da2f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/mysqldb.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any - -from ...util import memoized_property -from .base import MySQLCompiler, MySQLDialect, MySQLExecutionContext - -class MySQLExecutionContext_mysqldb(MySQLExecutionContext): - @property - def rowcount(self): ... - -class MySQLCompiler_mysqldb(MySQLCompiler): ... - -class MySQLDialect_mysqldb(MySQLDialect): - driver: str - supports_statement_cache: bool - supports_unicode_statements: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_native_decimal: bool - default_paramstyle: str - statement_compiler: Any - preparer: Any - def __init__(self, **kwargs) -> None: ... - @memoized_property - def supports_server_side_cursors(self): ... - @classmethod - def dbapi(cls): ... - def on_connect(self): ... - def do_ping(self, dbapi_connection): ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def create_connect_args(self, url, _translate_args: Any | None = ...): ... - -dialect = MySQLDialect_mysqldb diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/oursql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/oursql.pyi deleted file mode 100644 index 40d1d6919ccb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/oursql.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from typing import Any - -from .base import BIT, MySQLDialect, MySQLExecutionContext - -class _oursqlBIT(BIT): - def result_processor(self, dialect, coltype) -> None: ... - -class MySQLExecutionContext_oursql(MySQLExecutionContext): - @property - def plain_query(self): ... - -class MySQLDialect_oursql(MySQLDialect): - driver: str - supports_statement_cache: bool - supports_unicode_binds: bool - supports_unicode_statements: bool - supports_native_decimal: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - colspecs: Any - @classmethod - def dbapi(cls): ... - def do_execute(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_begin(self, connection) -> None: ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] - def get_table_options(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_view_names(self, connection, schema: Any | None = ..., **kw): ... - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_schema_names(self, connection, **kw): ... - def initialize(self, connection): ... - def is_disconnect(self, e, connection, cursor): ... - def create_connect_args(self, url): ... - -dialect = MySQLDialect_oursql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/pymysql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/pymysql.pyi deleted file mode 100644 index a4f6cb64fc48..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/pymysql.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -from ...util import memoized_property -from .mysqldb import MySQLDialect_mysqldb - -class MySQLDialect_pymysql(MySQLDialect_mysqldb): - driver: str - supports_statement_cache: bool - description_encoding: Any - supports_unicode_statements: bool - supports_unicode_binds: bool - @memoized_property - def supports_server_side_cursors(self): ... - @classmethod - def dbapi(cls): ... - def create_connect_args(self, url, _translate_args: Any | None = ...): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = MySQLDialect_pymysql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/pyodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/pyodbc.pyi deleted file mode 100644 index f9363c3cc0b0..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/pyodbc.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Any - -from ...connectors.pyodbc import PyODBCConnector -from .base import MySQLDialect, MySQLExecutionContext -from .types import TIME - -class _pyodbcTIME(TIME): - def result_processor(self, dialect, coltype): ... - -class MySQLExecutionContext_pyodbc(MySQLExecutionContext): - def get_lastrowid(self): ... - -class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect): - supports_statement_cache: bool - colspecs: Any - supports_unicode_statements: bool - pyodbc_driver_name: str - def on_connect(self): ... - -dialect = MySQLDialect_pyodbc diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/reflection.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/reflection.pyi deleted file mode 100644 index 0df92ff88c10..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/reflection.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -class ReflectedState: - columns: Any - table_options: Any - table_name: Any - keys: Any - fk_constraints: Any - ck_constraints: Any - def __init__(self) -> None: ... - -class MySQLTableDefinitionParser: - logger: Any - dialect: Any - preparer: Any - def __init__(self, dialect, preparer) -> None: ... - def parse(self, show_create, charset): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/reserved_words.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/reserved_words.pyi deleted file mode 100644 index 28a741b2b19d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/reserved_words.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Any - -RESERVED_WORDS_MARIADB: Any -RESERVED_WORDS_MYSQL: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/types.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/types.pyi deleted file mode 100644 index 402a19aa52ca..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/types.pyi +++ /dev/null @@ -1,145 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -class _NumericType: - unsigned: Any - zerofill: Any - def __init__(self, unsigned: bool = ..., zerofill: bool = ..., **kw) -> None: ... - -class _FloatType(_NumericType, sqltypes.Float): - scale: Any - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: bool = ..., **kw) -> None: ... - -class _IntegerType(_NumericType, sqltypes.Integer): - display_width: Any - def __init__(self, display_width: Any | None = ..., **kw) -> None: ... - -class _StringType(sqltypes.String): - charset: Any - ascii: Any - unicode: Any - binary: Any - national: Any - def __init__( - self, - charset: Any | None = ..., - collation: Any | None = ..., - ascii: bool = ..., - binary: bool = ..., - unicode: bool = ..., - national: bool = ..., - **kw, - ) -> None: ... - -class _MatchType(sqltypes.Float, sqltypes.MatchType): # type: ignore[misc] - def __init__(self, **kw) -> None: ... - -class NUMERIC(_NumericType, sqltypes.NUMERIC): - __visit_name__: str - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: bool = ..., **kw) -> None: ... - -class DECIMAL(_NumericType, sqltypes.DECIMAL): - __visit_name__: str - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: bool = ..., **kw) -> None: ... - -class DOUBLE(_FloatType): - __visit_name__: str - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: bool = ..., **kw) -> None: ... - -class REAL(_FloatType, sqltypes.REAL): - __visit_name__: str - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: bool = ..., **kw) -> None: ... - -class FLOAT(_FloatType, sqltypes.FLOAT): - __visit_name__: str - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: bool = ..., **kw) -> None: ... - def bind_processor(self, dialect) -> None: ... - -class INTEGER(_IntegerType, sqltypes.INTEGER): - __visit_name__: str - def __init__(self, display_width: Any | None = ..., **kw) -> None: ... - -class BIGINT(_IntegerType, sqltypes.BIGINT): - __visit_name__: str - def __init__(self, display_width: Any | None = ..., **kw) -> None: ... - -class MEDIUMINT(_IntegerType): - __visit_name__: str - def __init__(self, display_width: Any | None = ..., **kw) -> None: ... - -class TINYINT(_IntegerType): - __visit_name__: str - def __init__(self, display_width: Any | None = ..., **kw) -> None: ... - -class SMALLINT(_IntegerType, sqltypes.SMALLINT): - __visit_name__: str - def __init__(self, display_width: Any | None = ..., **kw) -> None: ... - -class BIT(sqltypes.TypeEngine): - __visit_name__: str - length: Any - def __init__(self, length: Any | None = ...) -> None: ... - def result_processor(self, dialect, coltype): ... - -class TIME(sqltypes.TIME): - __visit_name__: str - fsp: Any - def __init__(self, timezone: bool = ..., fsp: Any | None = ...) -> None: ... - def result_processor(self, dialect, coltype): ... - -class TIMESTAMP(sqltypes.TIMESTAMP): - __visit_name__: str - fsp: Any - def __init__(self, timezone: bool = ..., fsp: Any | None = ...) -> None: ... - -class DATETIME(sqltypes.DATETIME): - __visit_name__: str - fsp: Any - def __init__(self, timezone: bool = ..., fsp: Any | None = ...) -> None: ... - -class YEAR(sqltypes.TypeEngine): - __visit_name__: str - display_width: Any - def __init__(self, display_width: Any | None = ...) -> None: ... - -class TEXT(_StringType, sqltypes.TEXT): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kw) -> None: ... - -class TINYTEXT(_StringType): - __visit_name__: str - def __init__(self, **kwargs) -> None: ... - -class MEDIUMTEXT(_StringType): - __visit_name__: str - def __init__(self, **kwargs) -> None: ... - -class LONGTEXT(_StringType): - __visit_name__: str - def __init__(self, **kwargs) -> None: ... - -class VARCHAR(_StringType, sqltypes.VARCHAR): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class CHAR(_StringType, sqltypes.CHAR): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class NVARCHAR(_StringType, sqltypes.NVARCHAR): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class NCHAR(_StringType, sqltypes.NCHAR): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class TINYBLOB(sqltypes._Binary): - __visit_name__: str - -class MEDIUMBLOB(sqltypes._Binary): - __visit_name__: str - -class LONGBLOB(sqltypes._Binary): - __visit_name__: str diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/__init__.pyi deleted file mode 100644 index 3cc1662ff2f1..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/__init__.pyi +++ /dev/null @@ -1,52 +0,0 @@ -from typing import Any - -from .base import ( - BFILE as BFILE, - BINARY_DOUBLE as BINARY_DOUBLE, - BINARY_FLOAT as BINARY_FLOAT, - BLOB as BLOB, - CHAR as CHAR, - CLOB as CLOB, - DATE as DATE, - DOUBLE_PRECISION as DOUBLE_PRECISION, - FLOAT as FLOAT, - INTERVAL as INTERVAL, - LONG as LONG, - NCHAR as NCHAR, - NCLOB as NCLOB, - NUMBER as NUMBER, - NVARCHAR as NVARCHAR, - NVARCHAR2 as NVARCHAR2, - RAW as RAW, - ROWID as ROWID, - TIMESTAMP as TIMESTAMP, - VARCHAR as VARCHAR, - VARCHAR2 as VARCHAR2, -) - -__all__ = ( - "VARCHAR", - "NVARCHAR", - "CHAR", - "NCHAR", - "DATE", - "NUMBER", - "BLOB", - "BFILE", - "CLOB", - "NCLOB", - "TIMESTAMP", - "RAW", - "FLOAT", - "DOUBLE_PRECISION", - "BINARY_DOUBLE", - "BINARY_FLOAT", - "LONG", - "dialect", - "INTERVAL", - "VARCHAR2", - "NVARCHAR2", - "ROWID", -) - -dialect: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/base.pyi deleted file mode 100644 index 6b9668957b2b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/base.pyi +++ /dev/null @@ -1,219 +0,0 @@ -from typing import Any - -from sqlalchemy.sql import ClauseElement - -from ...engine import default -from ...sql import compiler, sqltypes -from ...types import ( - BLOB as BLOB, - CHAR as CHAR, - CLOB as CLOB, - FLOAT as FLOAT, - INTEGER as INTEGER, - NCHAR as NCHAR, - NVARCHAR as NVARCHAR, - TIMESTAMP as TIMESTAMP, - VARCHAR as VARCHAR, -) - -RESERVED_WORDS: Any -NO_ARG_FNS: Any - -class RAW(sqltypes._Binary): - __visit_name__: str - -OracleRaw = RAW - -class NCLOB(sqltypes.Text): - __visit_name__: str - -class VARCHAR2(VARCHAR): - __visit_name__: str - -NVARCHAR2 = NVARCHAR - -class NUMBER(sqltypes.Numeric, sqltypes.Integer): - __visit_name__: str - def __init__(self, precision: Any | None = ..., scale: Any | None = ..., asdecimal: Any | None = ...) -> None: ... - def adapt(self, impltype): ... - -class DOUBLE_PRECISION(sqltypes.Float): - __visit_name__: str - -class BINARY_DOUBLE(sqltypes.Float): - __visit_name__: str - -class BINARY_FLOAT(sqltypes.Float): - __visit_name__: str - -class BFILE(sqltypes.LargeBinary): - __visit_name__: str - -class LONG(sqltypes.Text): - __visit_name__: str - -class DATE(sqltypes.DateTime): - __visit_name__: str - -class INTERVAL(sqltypes.NativeForEmulated, sqltypes._AbstractInterval): - __visit_name__: str - day_precision: Any - second_precision: Any - def __init__(self, day_precision: Any | None = ..., second_precision: Any | None = ...) -> None: ... - def as_generic(self, allow_nulltype: bool = ...): ... - def coerce_compared_value(self, op, value): ... - -class ROWID(sqltypes.TypeEngine): - __visit_name__: str - -class _OracleBoolean(sqltypes.Boolean): - def get_dbapi_type(self, dbapi): ... - -colspecs: Any -ischema_names: Any - -class OracleTypeCompiler(compiler.GenericTypeCompiler): - def visit_datetime(self, type_, **kw): ... - def visit_float(self, type_, **kw): ... - def visit_unicode(self, type_, **kw): ... - def visit_INTERVAL(self, type_, **kw): ... - def visit_LONG(self, type_, **kw): ... - def visit_TIMESTAMP(self, type_, **kw): ... - def visit_DOUBLE_PRECISION(self, type_, **kw): ... - def visit_BINARY_DOUBLE(self, type_, **kw): ... - def visit_BINARY_FLOAT(self, type_, **kw): ... - def visit_FLOAT(self, type_, **kw): ... - def visit_NUMBER(self, type_, **kw): ... - def visit_string(self, type_, **kw): ... - def visit_VARCHAR2(self, type_, **kw): ... - def visit_NVARCHAR2(self, type_, **kw): ... - visit_NVARCHAR: Any - def visit_VARCHAR(self, type_, **kw): ... - def visit_text(self, type_, **kw): ... - def visit_unicode_text(self, type_, **kw): ... - def visit_large_binary(self, type_, **kw): ... - def visit_big_integer(self, type_, **kw): ... - def visit_boolean(self, type_, **kw): ... - def visit_RAW(self, type_, **kw): ... - def visit_ROWID(self, type_, **kw): ... - -class OracleCompiler(compiler.SQLCompiler): - compound_keywords: Any - def __init__(self, *args, **kwargs) -> None: ... - def visit_mod_binary(self, binary, operator, **kw): ... - def visit_now_func(self, fn, **kw): ... - def visit_char_length_func(self, fn, **kw): ... - def visit_match_op_binary(self, binary, operator, **kw): ... - def visit_true(self, expr, **kw): ... - def visit_false(self, expr, **kw): ... - def get_cte_preamble(self, recursive): ... - def get_select_hint_text(self, byfroms): ... - def function_argspec(self, fn, **kw): ... - def visit_function(self, func, **kw): ... - def visit_table_valued_column(self, element, **kw): ... - def default_from(self): ... - def visit_join(self, join, from_linter: Any | None = ..., **kwargs): ... # type: ignore[override] - def visit_outer_join_column(self, vc, **kw): ... - def visit_sequence(self, seq, **kw): ... - def get_render_as_alias_suffix(self, alias_name_text): ... - has_out_parameters: bool - def returning_clause(self, stmt, returning_cols): ... - def translate_select_structure(self, select_stmt, **kwargs): ... - def limit_clause(self, select, **kw): ... - def visit_empty_set_expr(self, type_): ... - def for_update_clause(self, select, **kw): ... - def visit_is_distinct_from_binary(self, binary, operator, **kw): ... - def visit_is_not_distinct_from_binary(self, binary, operator, **kw): ... - def visit_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_not_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_regexp_replace_op_binary(self, binary, operator, **kw): ... - -class OracleDDLCompiler(compiler.DDLCompiler): - def define_constraint_cascades(self, constraint): ... - def visit_drop_table_comment(self, drop): ... - def visit_create_index(self, create): ... - def post_create_table(self, table): ... - def get_identity_options(self, identity_options): ... - def visit_computed_column(self, generated): ... - def visit_identity_column(self, identity, **kw): ... - -class OracleIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words: Any - illegal_initial_characters: Any - def format_savepoint(self, savepoint): ... - -class OracleExecutionContext(default.DefaultExecutionContext): - def fire_sequence(self, seq, type_): ... - -class OracleDialect(default.DefaultDialect): - name: str - supports_statement_cache: bool - supports_alter: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - max_identifier_length: int - supports_simple_order_by_label: bool - cte_follows_insert: bool - supports_sequences: bool - sequences_optional: bool - postfetch_lastrowid: bool - default_paramstyle: str - colspecs: Any - ischema_names: Any - requires_name_normalize: bool - supports_comments: bool - supports_default_values: bool - supports_default_metavalue: bool - supports_empty_insert: bool - supports_identity_columns: bool - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - preparer: Any - reflection_options: Any - construct_arguments: Any - use_ansi: Any - optimize_limits: Any - exclude_tablespaces: Any - def __init__( - self, - use_ansi: bool = ..., - optimize_limits: bool = ..., - use_binds_for_limits: Any | None = ..., - use_nchar_for_unicode: bool = ..., - exclude_tablespaces=..., - **kwargs, - ) -> None: ... - implicit_returning: Any - def initialize(self, connection) -> None: ... - def do_release_savepoint(self, connection, name) -> None: ... - def get_isolation_level(self, connection) -> None: ... - def get_default_isolation_level(self, dbapi_conn): ... - def set_isolation_level(self, connection, level) -> None: ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] - def has_sequence(self, connection, sequence_name, schema: Any | None = ...): ... # type: ignore[override] - def get_schema_names(self, connection, **kw): ... - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_temp_table_names(self, connection, **kw): ... - def get_view_names(self, connection, schema: Any | None = ..., **kw): ... - def get_sequence_names(self, connection, schema: Any | None = ..., **kw): ... - def get_table_options(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_table_comment( - self, connection, table_name, schema: Any | None = ..., resolve_synonyms: bool = ..., dblink: str = ..., **kw - ): ... - def get_indexes( - self, connection, table_name, schema: Any | None = ..., resolve_synonyms: bool = ..., dblink: str = ..., **kw - ): ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_unique_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_view_definition( - self, connection, view_name, schema: Any | None = ..., resolve_synonyms: bool = ..., dblink: str = ..., **kw - ): ... - def get_check_constraints(self, connection, table_name, schema: Any | None = ..., include_all: bool = ..., **kw): ... - -class _OuterJoinColumn(ClauseElement): - __visit_name__: str - column: Any - def __init__(self, column) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/cx_oracle.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/cx_oracle.pyi deleted file mode 100644 index 05f26b87b3ee..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/cx_oracle.pyi +++ /dev/null @@ -1,127 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from . import base as oracle -from .base import OracleCompiler, OracleDialect, OracleExecutionContext - -class _OracleInteger(sqltypes.Integer): - def get_dbapi_type(self, dbapi): ... - -class _OracleNumeric(sqltypes.Numeric): - is_number: bool - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype) -> None: ... - -class _OracleBinaryFloat(_OracleNumeric): - def get_dbapi_type(self, dbapi): ... - -class _OracleBINARY_FLOAT(_OracleBinaryFloat, oracle.BINARY_FLOAT): ... -class _OracleBINARY_DOUBLE(_OracleBinaryFloat, oracle.BINARY_DOUBLE): ... - -class _OracleNUMBER(_OracleNumeric): - is_number: bool - -class _OracleDate(sqltypes.Date): - def bind_processor(self, dialect) -> None: ... - def result_processor(self, dialect, coltype): ... - -class _OracleChar(sqltypes.CHAR): - def get_dbapi_type(self, dbapi): ... - -class _OracleNChar(sqltypes.NCHAR): - def get_dbapi_type(self, dbapi): ... - -class _OracleUnicodeStringNCHAR(oracle.NVARCHAR2): - def get_dbapi_type(self, dbapi): ... - -class _OracleUnicodeStringCHAR(sqltypes.Unicode): - def get_dbapi_type(self, dbapi): ... - -class _OracleUnicodeTextNCLOB(oracle.NCLOB): - def get_dbapi_type(self, dbapi): ... - -class _OracleUnicodeTextCLOB(sqltypes.UnicodeText): - def get_dbapi_type(self, dbapi): ... - -class _OracleText(sqltypes.Text): - def get_dbapi_type(self, dbapi): ... - -class _OracleLong(oracle.LONG): - def get_dbapi_type(self, dbapi): ... - -class _OracleString(sqltypes.String): ... - -class _OracleEnum(sqltypes.Enum): - def bind_processor(self, dialect): ... - -class _OracleBinary(sqltypes.LargeBinary): - def get_dbapi_type(self, dbapi): ... - def bind_processor(self, dialect) -> None: ... - def result_processor(self, dialect, coltype): ... - -class _OracleInterval(oracle.INTERVAL): - def get_dbapi_type(self, dbapi): ... - -class _OracleRaw(oracle.RAW): ... - -class _OracleRowid(oracle.ROWID): - def get_dbapi_type(self, dbapi): ... - -class OracleCompiler_cx_oracle(OracleCompiler): - def bindparam_string(self, name, **kw): ... - -class OracleExecutionContext_cx_oracle(OracleExecutionContext): - out_parameters: Any - include_set_input_sizes: Any - def pre_exec(self) -> None: ... - cursor_fetch_strategy: Any - def post_exec(self) -> None: ... - def create_cursor(self): ... - def get_out_parameter_values(self, out_param_names): ... - -class OracleDialect_cx_oracle(OracleDialect): - supports_statement_cache: bool - statement_compiler: Any - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - use_setinputsizes: bool - driver: str - colspecs: Any - execute_sequence_format: Any - arraysize: Any - encoding_errors: Any - auto_convert_lobs: Any - coerce_to_unicode: Any - coerce_to_decimal: Any - cx_oracle_ver: Any - def __init__( - self, - auto_convert_lobs: bool = ..., - coerce_to_unicode: bool = ..., - coerce_to_decimal: bool = ..., - arraysize: int = ..., - encoding_errors: Any | None = ..., - threaded: Any | None = ..., - **kwargs, - ): ... - @classmethod - def dbapi(cls): ... - def initialize(self, connection) -> None: ... - def get_isolation_level(self, connection): ... - def set_isolation_level(self, connection, level) -> None: ... - def on_connect(self): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def create_xid(self): ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_set_input_sizes(self, cursor, list_of_tuples, context) -> None: ... - def do_recover_twophase(self, connection) -> None: ... - -dialect = OracleDialect_cx_oracle diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/__init__.pyi deleted file mode 100644 index 67a7995dd236..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/__init__.pyi +++ /dev/null @@ -1,98 +0,0 @@ -import typing - -from .array import ARRAY as ARRAY, All as All, Any as Any, array as array -from .base import ( - BIGINT as BIGINT, - BIT as BIT, - BOOLEAN as BOOLEAN, - BYTEA as BYTEA, - CHAR as CHAR, - CIDR as CIDR, - DATE as DATE, - DOUBLE_PRECISION as DOUBLE_PRECISION, - ENUM as ENUM, - FLOAT as FLOAT, - INET as INET, - INTEGER as INTEGER, - INTERVAL as INTERVAL, - MACADDR as MACADDR, - MONEY as MONEY, - NUMERIC as NUMERIC, - OID as OID, - REAL as REAL, - REGCLASS as REGCLASS, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - TSVECTOR as TSVECTOR, - UUID as UUID, - VARCHAR as VARCHAR, - CreateEnumType as CreateEnumType, - DropEnumType as DropEnumType, -) -from .dml import Insert as Insert, insert as insert -from .ext import ExcludeConstraint as ExcludeConstraint, aggregate_order_by as aggregate_order_by, array_agg as array_agg -from .hstore import HSTORE as HSTORE, hstore as hstore -from .json import JSON as JSON, JSONB as JSONB -from .ranges import ( - DATERANGE as DATERANGE, - INT4RANGE as INT4RANGE, - INT8RANGE as INT8RANGE, - NUMRANGE as NUMRANGE, - TSRANGE as TSRANGE, - TSTZRANGE as TSTZRANGE, -) - -__all__ = ( - "INTEGER", - "BIGINT", - "SMALLINT", - "VARCHAR", - "CHAR", - "TEXT", - "NUMERIC", - "FLOAT", - "REAL", - "INET", - "CIDR", - "UUID", - "BIT", - "MACADDR", - "MONEY", - "OID", - "REGCLASS", - "DOUBLE_PRECISION", - "TIMESTAMP", - "TIME", - "DATE", - "BYTEA", - "BOOLEAN", - "INTERVAL", - "ARRAY", - "ENUM", - "dialect", - "array", - "HSTORE", - "hstore", - "INT4RANGE", - "INT8RANGE", - "NUMRANGE", - "DATERANGE", - "TSVECTOR", - "TSRANGE", - "TSTZRANGE", - "JSON", - "JSONB", - "Any", - "All", - "DropEnumType", - "CreateEnumType", - "ExcludeConstraint", - "aggregate_order_by", - "array_agg", - "insert", - "Insert", -) - -dialect: typing.Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/array.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/array.pyi deleted file mode 100644 index f8c96a4a5abb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/array.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Any as _Any - -import sqlalchemy.types as sqltypes - -from ...sql import expression - -def Any(other, arrexpr, operator=...): ... -def All(other, arrexpr, operator=...): ... - -class array(expression.ClauseList, expression.ColumnElement): - __visit_name__: str - stringify_dialect: str - inherit_cache: bool - type: _Any - def __init__(self, clauses, **kw) -> None: ... - def self_group(self, against: _Any | None = ...): ... - -CONTAINS: _Any -CONTAINED_BY: _Any -OVERLAP: _Any - -class ARRAY(sqltypes.ARRAY): - class Comparator(sqltypes.ARRAY.Comparator): - def contains(self, other, **kwargs): ... - def contained_by(self, other): ... - def overlap(self, other): ... - comparator_factory: _Any - item_type: _Any - as_tuple: _Any - dimensions: _Any - zero_indexes: _Any - def __init__(self, item_type, as_tuple: bool = ..., dimensions: _Any | None = ..., zero_indexes: bool = ...) -> None: ... - @property - def hashable(self): ... - @property - def python_type(self): ... - def compare_values(self, x, y): ... - def bind_expression(self, bindvalue): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/asyncpg.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/asyncpg.pyi deleted file mode 100644 index 217ab044bec6..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/asyncpg.pyi +++ /dev/null @@ -1,199 +0,0 @@ -from typing import Any - -from ...engine import AdaptedConnection -from ...sql import sqltypes -from . import json -from .base import ENUM, INTERVAL, OID, REGCLASS, UUID, PGCompiler, PGDialect, PGExecutionContext, PGIdentifierPreparer - -class AsyncpgTime(sqltypes.Time): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgDate(sqltypes.Date): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgDateTime(sqltypes.DateTime): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgBoolean(sqltypes.Boolean): - def get_dbapi_type(self, dbapi): ... - -class AsyncPgInterval(INTERVAL): - def get_dbapi_type(self, dbapi): ... - @classmethod - def adapt_emulated_to_native(cls, interval, **kw): ... - -class AsyncPgEnum(ENUM): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgInteger(sqltypes.Integer): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgBigInteger(sqltypes.BigInteger): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgJSON(json.JSON): - def get_dbapi_type(self, dbapi): ... - def result_processor(self, dialect, coltype) -> None: ... - -class AsyncpgJSONB(json.JSONB): - def get_dbapi_type(self, dbapi): ... - def result_processor(self, dialect, coltype) -> None: ... - -class AsyncpgJSONIndexType(sqltypes.JSON.JSONIndexType): - def get_dbapi_type(self, dbapi) -> None: ... - -class AsyncpgJSONIntIndexType(sqltypes.JSON.JSONIntIndexType): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgJSONStrIndexType(sqltypes.JSON.JSONStrIndexType): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgJSONPathType(json.JSONPathType): - def bind_processor(self, dialect): ... - -class AsyncpgUUID(UUID): - def get_dbapi_type(self, dbapi): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class AsyncpgNumeric(sqltypes.Numeric): - def get_dbapi_type(self, dbapi): ... - def bind_processor(self, dialect) -> None: ... - def result_processor(self, dialect, coltype): ... - -class AsyncpgFloat(AsyncpgNumeric): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgREGCLASS(REGCLASS): - def get_dbapi_type(self, dbapi): ... - -class AsyncpgOID(OID): - def get_dbapi_type(self, dbapi): ... - -class PGExecutionContext_asyncpg(PGExecutionContext): - def handle_dbapi_exception(self, e) -> None: ... - exclude_set_input_sizes: Any - def pre_exec(self) -> None: ... - def create_server_side_cursor(self): ... - -class PGCompiler_asyncpg(PGCompiler): ... -class PGIdentifierPreparer_asyncpg(PGIdentifierPreparer): ... - -class AsyncAdapt_asyncpg_cursor: - server_side: bool - description: Any - arraysize: int - rowcount: int - def __init__(self, adapt_connection) -> None: ... - def close(self) -> None: ... - def execute(self, operation, parameters: Any | None = ...) -> None: ... - def executemany(self, operation, seq_of_parameters): ... - def setinputsizes(self, *inputsizes) -> None: ... - def __iter__(self): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_asyncpg_ss_cursor(AsyncAdapt_asyncpg_cursor): - server_side: bool - def __init__(self, adapt_connection) -> None: ... - def close(self) -> None: ... - def __aiter__(self): ... - async def __anext__(self) -> None: ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - def executemany(self, operation, seq_of_parameters) -> None: ... - -class AsyncAdapt_asyncpg_connection(AdaptedConnection): - await_: Any - dbapi: Any - isolation_level: str - readonly: bool - deferrable: bool - def __init__(self, dbapi, connection, prepared_statement_cache_size: int = ...) -> None: ... - @property - def autocommit(self): ... - @autocommit.setter - def autocommit(self, value) -> None: ... - def set_isolation_level(self, level) -> None: ... - def cursor(self, server_side: bool = ...): ... - def rollback(self) -> None: ... - def commit(self) -> None: ... - def close(self) -> None: ... - -class AsyncAdaptFallback_asyncpg_connection(AsyncAdapt_asyncpg_connection): - await_: Any - -class AsyncAdapt_asyncpg_dbapi: - asyncpg: Any - paramstyle: str - def __init__(self, asyncpg) -> None: ... - def connect(self, *arg, **kw): ... - class Error(Exception): ... - class Warning(Exception): ... - class InterfaceError(Error): ... - class DatabaseError(Error): ... - class InternalError(DatabaseError): ... - class OperationalError(DatabaseError): ... - class ProgrammingError(DatabaseError): ... - class IntegrityError(DatabaseError): ... - class DataError(DatabaseError): ... - class NotSupportedError(DatabaseError): ... - class InternalServerError(InternalError): ... - class InvalidCachedStatementError(NotSupportedError): - def __init__(self, message) -> None: ... - def Binary(self, value): ... - STRING: Any - TIMESTAMP: Any - TIMESTAMP_W_TZ: Any - TIME: Any - DATE: Any - INTERVAL: Any - NUMBER: Any - FLOAT: Any - BOOLEAN: Any - INTEGER: Any - BIGINTEGER: Any - BYTES: Any - DECIMAL: Any - JSON: Any - JSONB: Any - ENUM: Any - UUID: Any - BYTEA: Any - DATETIME: Any - BINARY: Any - -class PGDialect_asyncpg(PGDialect): - driver: str - supports_statement_cache: bool - supports_unicode_statements: bool - supports_server_side_cursors: bool - supports_unicode_binds: bool - default_paramstyle: str - supports_sane_multi_rowcount: bool - statement_compiler: Any - preparer: Any - use_setinputsizes: bool - use_native_uuid: bool - colspecs: Any - is_async: bool - @classmethod - def dbapi(cls): ... - def set_isolation_level(self, connection, level) -> None: ... - def set_readonly(self, connection, value) -> None: ... - def get_readonly(self, connection): ... - def set_deferrable(self, connection, value) -> None: ... - def get_deferrable(self, connection): ... - def create_connect_args(self, url): ... - @classmethod - def get_pool_class(cls, url): ... - def is_disconnect(self, e, connection, cursor): ... - def do_set_input_sizes(self, cursor, list_of_tuples, context) -> None: ... - async def setup_asyncpg_json_codec(self, conn): ... - async def setup_asyncpg_jsonb_codec(self, conn): ... - def on_connect(self): ... - def get_driver_connection(self, connection): ... - -dialect = PGDialect_asyncpg diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/base.pyi deleted file mode 100644 index 047d14bdc152..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/base.pyi +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any - -from ...engine import characteristics, default, reflection -from ...schema import _CreateDropBase -from ...sql import compiler, elements, sqltypes -from ...sql.ddl import DDLBase -from ...types import ( - BIGINT as BIGINT, - BOOLEAN as BOOLEAN, - CHAR as CHAR, - DATE as DATE, - FLOAT as FLOAT, - INTEGER as INTEGER, - NUMERIC as NUMERIC, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - VARCHAR as VARCHAR, -) - -IDX_USING: Any -AUTOCOMMIT_REGEXP: Any -RESERVED_WORDS: Any - -class BYTEA(sqltypes.LargeBinary): - __visit_name__: str - -class DOUBLE_PRECISION(sqltypes.Float): - __visit_name__: str - -class INET(sqltypes.TypeEngine): - __visit_name__: str - -PGInet = INET - -class CIDR(sqltypes.TypeEngine): - __visit_name__: str - -PGCidr = CIDR - -class MACADDR(sqltypes.TypeEngine): - __visit_name__: str - -PGMacAddr = MACADDR - -class MONEY(sqltypes.TypeEngine): - __visit_name__: str - -class OID(sqltypes.TypeEngine): - __visit_name__: str - -class REGCLASS(sqltypes.TypeEngine): - __visit_name__: str - -class TIMESTAMP(sqltypes.TIMESTAMP): - precision: Any - def __init__(self, timezone: bool = ..., precision: Any | None = ...) -> None: ... - -class TIME(sqltypes.TIME): - precision: Any - def __init__(self, timezone: bool = ..., precision: Any | None = ...) -> None: ... - -class INTERVAL(sqltypes.NativeForEmulated, sqltypes._AbstractInterval): - __visit_name__: str - native: bool - precision: Any - fields: Any - def __init__(self, precision: Any | None = ..., fields: Any | None = ...) -> None: ... - @classmethod - def adapt_emulated_to_native(cls, interval, **kw): ... - def as_generic(self, allow_nulltype: bool = ...): ... - @property - def python_type(self): ... - def coerce_compared_value(self, op, value): ... - -PGInterval = INTERVAL - -class BIT(sqltypes.TypeEngine): - __visit_name__: str - length: Any - varying: Any - def __init__(self, length: Any | None = ..., varying: bool = ...) -> None: ... - -PGBit = BIT - -class UUID(sqltypes.TypeEngine): - __visit_name__: str - as_uuid: Any - def __init__(self, as_uuid: bool = ...) -> None: ... - def coerce_compared_value(self, op, value): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -PGUuid = UUID - -class TSVECTOR(sqltypes.TypeEngine): - __visit_name__: str - -class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): # type: ignore[misc] - native_enum: bool - create_type: Any - def __init__(self, *enums, **kw) -> None: ... - @classmethod - def adapt_emulated_to_native(cls, impl, **kw): ... - def create(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - def drop(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - class EnumGenerator(DDLBase): - checkfirst: Any - def __init__(self, dialect, connection, checkfirst: bool = ..., **kwargs) -> None: ... - def visit_enum(self, enum) -> None: ... - class EnumDropper(DDLBase): - checkfirst: Any - def __init__(self, dialect, connection, checkfirst: bool = ..., **kwargs) -> None: ... - def visit_enum(self, enum) -> None: ... - -class _ColonCast(elements.Cast): - __visit_name__: str - type: Any - clause: Any - typeclause: Any - def __init__(self, expression, type_) -> None: ... - -colspecs: Any -ischema_names: Any - -class PGCompiler(compiler.SQLCompiler): - def visit_colon_cast(self, element, **kw): ... - def visit_array(self, element, **kw): ... - def visit_slice(self, element, **kw): ... - def visit_json_getitem_op_binary(self, binary, operator, _cast_applied: bool = ..., **kw): ... - def visit_json_path_getitem_op_binary(self, binary, operator, _cast_applied: bool = ..., **kw): ... - def visit_getitem_binary(self, binary, operator, **kw): ... - def visit_aggregate_order_by(self, element, **kw): ... - def visit_match_op_binary(self, binary, operator, **kw): ... - def visit_ilike_op_binary(self, binary, operator, **kw): ... - def visit_not_ilike_op_binary(self, binary, operator, **kw): ... - def visit_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_not_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_regexp_replace_op_binary(self, binary, operator, **kw): ... - def visit_empty_set_expr(self, element_types): ... - def render_literal_value(self, value, type_): ... - def visit_sequence(self, seq, **kw): ... - def limit_clause(self, select, **kw): ... - def format_from_hint_text(self, sqltext, table, hint, iscrud): ... - def get_select_precolumns(self, select, **kw): ... - def for_update_clause(self, select, **kw): ... - def returning_clause(self, stmt, returning_cols): ... - def visit_substring_func(self, func, **kw): ... - def visit_on_conflict_do_nothing(self, on_conflict, **kw): ... - def visit_on_conflict_do_update(self, on_conflict, **kw): ... - def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw): ... - def delete_extra_from_clause(self, delete_stmt, from_table, extra_froms, from_hints, **kw): ... - def fetch_clause(self, select, **kw): ... - -class PGDDLCompiler(compiler.DDLCompiler): - def get_column_specification(self, column, **kwargs): ... - def visit_check_constraint(self, constraint): ... - def visit_drop_table_comment(self, drop): ... - def visit_create_enum_type(self, create): ... - def visit_drop_enum_type(self, drop): ... - def visit_create_index(self, create): ... - def visit_drop_index(self, drop): ... - def visit_exclude_constraint(self, constraint, **kw): ... - def post_create_table(self, table): ... - def visit_computed_column(self, generated): ... - def visit_create_sequence(self, create, **kw): ... - -class PGTypeCompiler(compiler.GenericTypeCompiler): - def visit_TSVECTOR(self, type_, **kw): ... - def visit_INET(self, type_, **kw): ... - def visit_CIDR(self, type_, **kw): ... - def visit_MACADDR(self, type_, **kw): ... - def visit_MONEY(self, type_, **kw): ... - def visit_OID(self, type_, **kw): ... - def visit_REGCLASS(self, type_, **kw): ... - def visit_FLOAT(self, type_, **kw): ... - def visit_DOUBLE_PRECISION(self, type_, **kw): ... - def visit_BIGINT(self, type_, **kw): ... - def visit_HSTORE(self, type_, **kw): ... - def visit_JSON(self, type_, **kw): ... - def visit_JSONB(self, type_, **kw): ... - def visit_INT4RANGE(self, type_, **kw): ... - def visit_INT8RANGE(self, type_, **kw): ... - def visit_NUMRANGE(self, type_, **kw): ... - def visit_DATERANGE(self, type_, **kw): ... - def visit_TSRANGE(self, type_, **kw): ... - def visit_TSTZRANGE(self, type_, **kw): ... - def visit_datetime(self, type_, **kw): ... - def visit_enum(self, type_, **kw): ... - def visit_ENUM(self, type_, identifier_preparer: Any | None = ..., **kw): ... - def visit_TIMESTAMP(self, type_, **kw): ... - def visit_TIME(self, type_, **kw): ... - def visit_INTERVAL(self, type_, **kw): ... - def visit_BIT(self, type_, **kw): ... - def visit_UUID(self, type_, **kw): ... - def visit_large_binary(self, type_, **kw): ... - def visit_BYTEA(self, type_, **kw): ... - def visit_ARRAY(self, type_, **kw): ... - -class PGIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words: Any - def format_type(self, type_, use_schema: bool = ...): ... - -class PGInspector(reflection.Inspector): - def get_table_oid(self, table_name, schema: Any | None = ...): ... - def get_enums(self, schema: Any | None = ...): ... - def get_foreign_table_names(self, schema: Any | None = ...): ... - def get_view_names(self, schema: Any | None = ..., include=...): ... - -class CreateEnumType(_CreateDropBase): - __visit_name__: str - -class DropEnumType(_CreateDropBase): - __visit_name__: str - -class PGExecutionContext(default.DefaultExecutionContext): - def fire_sequence(self, seq, type_): ... - def get_insert_default(self, column): ... - def should_autocommit_text(self, statement): ... - -class PGReadOnlyConnectionCharacteristic(characteristics.ConnectionCharacteristic): - transactional: bool - def reset_characteristic(self, dialect, dbapi_conn) -> None: ... - def set_characteristic(self, dialect, dbapi_conn, value) -> None: ... - def get_characteristic(self, dialect, dbapi_conn): ... - -class PGDeferrableConnectionCharacteristic(characteristics.ConnectionCharacteristic): - transactional: bool - def reset_characteristic(self, dialect, dbapi_conn) -> None: ... - def set_characteristic(self, dialect, dbapi_conn, value) -> None: ... - def get_characteristic(self, dialect, dbapi_conn): ... - -class PGDialect(default.DefaultDialect): - name: str - supports_statement_cache: bool - supports_alter: bool - max_identifier_length: int - supports_sane_rowcount: bool - supports_native_enum: bool - supports_native_boolean: bool - supports_smallserial: bool - supports_sequences: bool - sequences_optional: bool - preexecute_autoincrement_sequences: bool - postfetch_lastrowid: bool - supports_comments: bool - supports_default_values: bool - supports_default_metavalue: bool - supports_empty_insert: bool - supports_multivalues_insert: bool - supports_identity_columns: bool - default_paramstyle: str - ischema_names: Any - colspecs: Any - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - preparer: Any - inspector: Any - isolation_level: Any - implicit_returning: bool - full_returning: bool - connection_characteristics: Any - construct_arguments: Any - reflection_options: Any - def __init__( - self, isolation_level: Any | None = ..., json_serializer: Any | None = ..., json_deserializer: Any | None = ..., **kwargs - ) -> None: ... - def initialize(self, connection) -> None: ... - def on_connect(self): ... - def set_isolation_level(self, connection, level) -> None: ... - def get_isolation_level(self, connection): ... - def set_readonly(self, connection, value) -> None: ... - def get_readonly(self, connection) -> None: ... - def set_deferrable(self, connection, value) -> None: ... - def get_deferrable(self, connection) -> None: ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_recover_twophase(self, connection): ... - def has_schema(self, connection, schema): ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] - def has_sequence(self, connection, sequence_name, schema: Any | None = ...): ... # type: ignore[override] - def has_type(self, connection, type_name, schema: Any | None = ...): ... - def get_table_oid(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_schema_names(self, connection, **kw): ... - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_names(self, connection, schema: Any | None = ..., include=..., **kw): ... - def get_sequence_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_definition(self, connection, view_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys( - self, connection, table_name, schema: Any | None = ..., postgresql_ignore_search_path: bool = ..., **kw - ): ... - def get_indexes(self, connection, table_name, schema, **kw): ... - def get_unique_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_table_comment(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_check_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/dml.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/dml.pyi deleted file mode 100644 index cfa9b38b3dad..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/dml.pyi +++ /dev/null @@ -1,47 +0,0 @@ -from typing import Any - -from ...sql.dml import Insert as StandardInsert -from ...sql.elements import ClauseElement -from ...util import memoized_property - -class Insert(StandardInsert): - stringify_dialect: str - inherit_cache: bool - @memoized_property - def excluded(self): ... - def on_conflict_do_update( - self, - constraint: Any | None = ..., - index_elements: Any | None = ..., - index_where: Any | None = ..., - set_: Any | None = ..., - where: Any | None = ..., - ) -> None: ... - def on_conflict_do_nothing( - self, constraint: Any | None = ..., index_elements: Any | None = ..., index_where: Any | None = ... - ) -> None: ... - -insert: Any - -class OnConflictClause(ClauseElement): - stringify_dialect: str - constraint_target: Any - inferred_target_elements: Any - inferred_target_whereclause: Any - def __init__(self, constraint: Any | None = ..., index_elements: Any | None = ..., index_where: Any | None = ...) -> None: ... - -class OnConflictDoNothing(OnConflictClause): - __visit_name__: str - -class OnConflictDoUpdate(OnConflictClause): - __visit_name__: str - update_values_to_set: Any - update_whereclause: Any - def __init__( - self, - constraint: Any | None = ..., - index_elements: Any | None = ..., - index_where: Any | None = ..., - set_: Any | None = ..., - where: Any | None = ..., - ) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/ext.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/ext.pyi deleted file mode 100644 index b205c953cd57..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/ext.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any - -from ...sql import expression -from ...sql.schema import ColumnCollectionConstraint - -class aggregate_order_by(expression.ColumnElement): - __visit_name__: str - stringify_dialect: str - inherit_cache: bool - target: Any - type: Any - order_by: Any - def __init__(self, target, *order_by) -> None: ... - def self_group(self, against: Any | None = ...): ... - def get_children(self, **kwargs): ... - -class ExcludeConstraint(ColumnCollectionConstraint): - __visit_name__: str - where: Any - inherit_cache: bool - create_drop_stringify_dialect: str - operators: Any - using: Any - ops: Any - def __init__(self, *elements, **kw) -> None: ... - -def array_agg(*arg, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/hstore.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/hstore.pyi deleted file mode 100644 index f0cb163b9a11..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/hstore.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from ...sql import functions as sqlfunc - -class HSTORE(sqltypes.Indexable, sqltypes.Concatenable, sqltypes.TypeEngine): - __visit_name__: str - hashable: bool - text_type: Any - def __init__(self, text_type: Any | None = ...) -> None: ... - class Comparator(sqltypes.Indexable.Comparator, sqltypes.Concatenable.Comparator): - def has_key(self, other): ... - def has_all(self, other): ... - def has_any(self, other): ... - def contains(self, other, **kwargs): ... - def contained_by(self, other): ... - def defined(self, key): ... - def delete(self, key): ... - def slice(self, array): ... - def keys(self): ... - def vals(self): ... - def array(self): ... - def matrix(self): ... - comparator_factory: Any - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class hstore(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreDefinedFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreDeleteFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreSliceFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreKeysFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreValsFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreArrayFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool - -class _HStoreMatrixFunction(sqlfunc.GenericFunction): - type: Any - name: str - inherit_cache: bool diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/json.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/json.pyi deleted file mode 100644 index d298402c5cba..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/json.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -class JSONPathType(sqltypes.JSON.JSONPathType): - def bind_processor(self, dialect): ... - def literal_processor(self, dialect): ... - -class JSON(sqltypes.JSON): - astext_type: Any - def __init__(self, none_as_null: bool = ..., astext_type: Any | None = ...) -> None: ... - class Comparator(sqltypes.JSON.Comparator): - @property - def astext(self): ... - comparator_factory: Any - -class JSONB(JSON): - __visit_name__: str - class Comparator(JSON.Comparator): - def has_key(self, other): ... - def has_all(self, other): ... - def has_any(self, other): ... - def contains(self, other, **kwargs): ... - def contained_by(self, other): ... - comparator_factory: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pg8000.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pg8000.pyi deleted file mode 100644 index fc60c10383d7..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pg8000.pyi +++ /dev/null @@ -1,134 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from .array import ARRAY as PGARRAY -from .base import ENUM, INTERVAL, UUID, PGCompiler, PGDialect, PGExecutionContext, PGIdentifierPreparer -from .json import JSON, JSONB, JSONPathType - -class _PGNumeric(sqltypes.Numeric): - def result_processor(self, dialect, coltype): ... - -class _PGNumericNoBind(_PGNumeric): - def bind_processor(self, dialect) -> None: ... - -class _PGJSON(JSON): - def result_processor(self, dialect, coltype) -> None: ... - def get_dbapi_type(self, dbapi): ... - -class _PGJSONB(JSONB): - def result_processor(self, dialect, coltype) -> None: ... - def get_dbapi_type(self, dbapi): ... - -class _PGJSONIndexType(sqltypes.JSON.JSONIndexType): - def get_dbapi_type(self, dbapi) -> None: ... - -class _PGJSONIntIndexType(sqltypes.JSON.JSONIntIndexType): - def get_dbapi_type(self, dbapi): ... - -class _PGJSONStrIndexType(sqltypes.JSON.JSONStrIndexType): - def get_dbapi_type(self, dbapi): ... - -class _PGJSONPathType(JSONPathType): - def get_dbapi_type(self, dbapi): ... - -class _PGUUID(UUID): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _PGEnum(ENUM): - def get_dbapi_type(self, dbapi): ... - -class _PGInterval(INTERVAL): - def get_dbapi_type(self, dbapi): ... - @classmethod - def adapt_emulated_to_native(cls, interval, **kw): ... - -class _PGTimeStamp(sqltypes.DateTime): - def get_dbapi_type(self, dbapi): ... - -class _PGTime(sqltypes.Time): - def get_dbapi_type(self, dbapi): ... - -class _PGInteger(sqltypes.Integer): - def get_dbapi_type(self, dbapi): ... - -class _PGSmallInteger(sqltypes.SmallInteger): - def get_dbapi_type(self, dbapi): ... - -class _PGNullType(sqltypes.NullType): - def get_dbapi_type(self, dbapi): ... - -class _PGBigInteger(sqltypes.BigInteger): - def get_dbapi_type(self, dbapi): ... - -class _PGBoolean(sqltypes.Boolean): - def get_dbapi_type(self, dbapi): ... - -class _PGARRAY(PGARRAY): - def bind_expression(self, bindvalue): ... - -class PGExecutionContext_pg8000(PGExecutionContext): - def create_server_side_cursor(self): ... - def pre_exec(self) -> None: ... - -class ServerSideCursor: - server_side: bool - ident: Any - cursor: Any - def __init__(self, cursor, ident) -> None: ... - @property - def connection(self): ... - @property - def rowcount(self): ... - @property - def description(self): ... - def execute(self, operation, args=..., stream: Any | None = ...): ... - def executemany(self, operation, param_sets): ... - def fetchone(self): ... - def fetchmany(self, num: Any | None = ...): ... - def fetchall(self): ... - def close(self) -> None: ... - def setinputsizes(self, *sizes) -> None: ... - def setoutputsize(self, size, column: Any | None = ...) -> None: ... - -class PGCompiler_pg8000(PGCompiler): - def visit_mod_binary(self, binary, operator, **kw): ... - -class PGIdentifierPreparer_pg8000(PGIdentifierPreparer): - def __init__(self, *args, **kwargs) -> None: ... - -class PGDialect_pg8000(PGDialect): - driver: str - supports_statement_cache: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - default_paramstyle: str - supports_sane_multi_rowcount: bool - statement_compiler: Any - preparer: Any - supports_server_side_cursors: bool - use_setinputsizes: bool - description_encoding: Any - colspecs: Any - client_encoding: Any - def __init__(self, client_encoding: Any | None = ..., **kwargs) -> None: ... - @classmethod - def dbapi(cls): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - def set_isolation_level(self, connection, level) -> None: ... - def set_readonly(self, connection, value) -> None: ... - def get_readonly(self, connection): ... - def set_deferrable(self, connection, value) -> None: ... - def get_deferrable(self, connection): ... - def set_client_encoding(self, connection, client_encoding) -> None: ... - def do_set_input_sizes(self, cursor, list_of_tuples, context) -> None: ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_recover_twophase(self, connection): ... - def on_connect(self): ... - -dialect = PGDialect_pg8000 diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/psycopg2.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/psycopg2.pyi deleted file mode 100644 index 7a5fa9941133..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/psycopg2.pyi +++ /dev/null @@ -1,95 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from .array import ARRAY as PGARRAY -from .base import ENUM, UUID, PGCompiler, PGDialect, PGExecutionContext, PGIdentifierPreparer -from .hstore import HSTORE -from .json import JSON, JSONB - -logger: Any - -class _PGNumeric(sqltypes.Numeric): - def bind_processor(self, dialect) -> None: ... - def result_processor(self, dialect, coltype): ... - -class _PGEnum(ENUM): - def result_processor(self, dialect, coltype): ... - -class _PGHStore(HSTORE): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _PGARRAY(PGARRAY): - def bind_expression(self, bindvalue): ... - -class _PGJSON(JSON): - def result_processor(self, dialect, coltype) -> None: ... - -class _PGJSONB(JSONB): - def result_processor(self, dialect, coltype) -> None: ... - -class _PGUUID(UUID): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class PGExecutionContext_psycopg2(PGExecutionContext): - def create_server_side_cursor(self): ... - cursor_fetch_strategy: Any - def post_exec(self) -> None: ... - -class PGCompiler_psycopg2(PGCompiler): ... -class PGIdentifierPreparer_psycopg2(PGIdentifierPreparer): ... - -EXECUTEMANY_PLAIN: Any -EXECUTEMANY_BATCH: Any -EXECUTEMANY_VALUES: Any -EXECUTEMANY_VALUES_PLUS_BATCH: Any - -class PGDialect_psycopg2(PGDialect): - driver: str - supports_statement_cache: bool - supports_unicode_statements: bool - supports_server_side_cursors: bool - default_paramstyle: str - supports_sane_multi_rowcount: bool - statement_compiler: Any - preparer: Any - psycopg2_version: Any - engine_config_types: Any - colspecs: Any - use_native_unicode: Any - use_native_hstore: Any - use_native_uuid: Any - supports_unicode_binds: Any - client_encoding: Any - executemany_mode: Any - insert_executemany_returning: bool - executemany_batch_page_size: Any - executemany_values_page_size: Any - def __init__( - self, - use_native_unicode: bool = ..., - client_encoding: Any | None = ..., - use_native_hstore: bool = ..., - use_native_uuid: bool = ..., - executemany_mode: str = ..., - executemany_batch_page_size: int = ..., - executemany_values_page_size: int = ..., - **kwargs, - ) -> None: ... - def initialize(self, connection) -> None: ... - @classmethod - def dbapi(cls): ... - def set_isolation_level(self, connection, level) -> None: ... - def set_readonly(self, connection, value) -> None: ... - def get_readonly(self, connection): ... - def set_deferrable(self, connection, value) -> None: ... - def get_deferrable(self, connection): ... - def do_ping(self, dbapi_connection): ... - def on_connect(self): ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = PGDialect_psycopg2 diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/psycopg2cffi.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/psycopg2cffi.pyi deleted file mode 100644 index 4456b3294a70..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/psycopg2cffi.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from .psycopg2 import PGDialect_psycopg2 - -class PGDialect_psycopg2cffi(PGDialect_psycopg2): - driver: str - supports_unicode_statements: bool - supports_statement_cache: bool - FEATURE_VERSION_MAP: Any - @classmethod - def dbapi(cls): ... - -dialect = PGDialect_psycopg2cffi diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pygresql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pygresql.pyi deleted file mode 100644 index a6f0d861b361..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pygresql.pyi +++ /dev/null @@ -1,52 +0,0 @@ -from typing import Any - -from ...types import Numeric -from .base import UUID, PGCompiler, PGDialect, PGIdentifierPreparer -from .hstore import HSTORE -from .json import JSON, JSONB - -class _PGNumeric(Numeric): - def bind_processor(self, dialect) -> None: ... - def result_processor(self, dialect, coltype): ... - -class _PGHStore(HSTORE): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _PGJSON(JSON): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _PGJSONB(JSONB): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _PGUUID(UUID): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _PGCompiler(PGCompiler): - def visit_mod_binary(self, binary, operator, **kw): ... - def post_process_text(self, text): ... - -class _PGIdentifierPreparer(PGIdentifierPreparer): ... - -class PGDialect_pygresql(PGDialect): - driver: str - supports_statement_cache: bool - statement_compiler: Any - preparer: Any - @classmethod - def dbapi(cls): ... - colspecs: Any - dbapi_version: Any - supports_unicode_statements: bool - supports_unicode_binds: bool - has_native_hstore: Any - has_native_json: Any - has_native_uuid: Any - def __init__(self, **kwargs) -> None: ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = PGDialect_pygresql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pypostgresql.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pypostgresql.pyi deleted file mode 100644 index 1b5bed220c5c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/pypostgresql.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from ...util import memoized_property -from .base import PGDialect, PGExecutionContext - -class PGNumeric(sqltypes.Numeric): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class PGExecutionContext_pypostgresql(PGExecutionContext): ... - -class PGDialect_pypostgresql(PGDialect): - driver: str - supports_statement_cache: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - description_encoding: Any - default_paramstyle: str - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - colspecs: Any - @classmethod - def dbapi(cls): ... - @memoized_property - def dbapi_exception_translation_map(self): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = PGDialect_pypostgresql diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/ranges.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/ranges.pyi deleted file mode 100644 index 35146308928b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/ranges.pyi +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -class RangeOperators: - class comparator_factory(sqltypes.Concatenable.Comparator): - def __ne__(self, other): ... - def contains(self, other, **kw): ... - def contained_by(self, other): ... - def overlaps(self, other): ... - def strictly_left_of(self, other): ... - __lshift__: Any - def strictly_right_of(self, other): ... - __rshift__: Any - def not_extend_right_of(self, other): ... - def not_extend_left_of(self, other): ... - def adjacent_to(self, other): ... - def __add__(self, other): ... - -class INT4RANGE(RangeOperators, sqltypes.TypeEngine): - __visit_name__: str - -class INT8RANGE(RangeOperators, sqltypes.TypeEngine): - __visit_name__: str - -class NUMRANGE(RangeOperators, sqltypes.TypeEngine): - __visit_name__: str - -class DATERANGE(RangeOperators, sqltypes.TypeEngine): - __visit_name__: str - -class TSRANGE(RangeOperators, sqltypes.TypeEngine): - __visit_name__: str - -class TSTZRANGE(RangeOperators, sqltypes.TypeEngine): - __visit_name__: str diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/__init__.pyi deleted file mode 100644 index 7dcb0cd7607e..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/__init__.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Any - -from .base import ( - BLOB as BLOB, - BOOLEAN as BOOLEAN, - CHAR as CHAR, - DATE as DATE, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - INTEGER as INTEGER, - JSON as JSON, - NUMERIC as NUMERIC, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - VARCHAR as VARCHAR, -) -from .dml import Insert as Insert, insert as insert - -__all__ = ( - "BLOB", - "BOOLEAN", - "CHAR", - "DATE", - "DATETIME", - "DECIMAL", - "FLOAT", - "INTEGER", - "JSON", - "NUMERIC", - "SMALLINT", - "TEXT", - "TIME", - "TIMESTAMP", - "VARCHAR", - "REAL", - "Insert", - "insert", - "dialect", -) - -dialect: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/aiosqlite.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/aiosqlite.pyi deleted file mode 100644 index dfc3247d5ea1..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/aiosqlite.pyi +++ /dev/null @@ -1,72 +0,0 @@ -from typing import Any - -from ...engine import AdaptedConnection -from .base import SQLiteExecutionContext -from .pysqlite import SQLiteDialect_pysqlite - -class AsyncAdapt_aiosqlite_cursor: - server_side: bool - await_: Any - arraysize: int - rowcount: int - description: Any - def __init__(self, adapt_connection) -> None: ... - def close(self) -> None: ... - lastrowid: int - def execute(self, operation, parameters: Any | None = ...) -> None: ... - def executemany(self, operation, seq_of_parameters) -> None: ... - def setinputsizes(self, *inputsizes) -> None: ... - def __iter__(self): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_aiosqlite_ss_cursor(AsyncAdapt_aiosqlite_cursor): - server_side: bool - def __init__(self, *arg, **kw) -> None: ... - def close(self) -> None: ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - -class AsyncAdapt_aiosqlite_connection(AdaptedConnection): - await_: Any - dbapi: Any - def __init__(self, dbapi, connection) -> None: ... - @property - def isolation_level(self): ... - @isolation_level.setter - def isolation_level(self, value) -> None: ... - def create_function(self, *args, **kw) -> None: ... - def cursor(self, server_side: bool = ...): ... - def execute(self, *args, **kw): ... - def rollback(self) -> None: ... - def commit(self) -> None: ... - def close(self) -> None: ... - -class AsyncAdaptFallback_aiosqlite_connection(AsyncAdapt_aiosqlite_connection): - await_: Any - -class AsyncAdapt_aiosqlite_dbapi: - aiosqlite: Any - sqlite: Any - paramstyle: str - def __init__(self, aiosqlite, sqlite) -> None: ... - def connect(self, *arg, **kw): ... - -class SQLiteExecutionContext_aiosqlite(SQLiteExecutionContext): - def create_server_side_cursor(self): ... - -class SQLiteDialect_aiosqlite(SQLiteDialect_pysqlite): - driver: str - supports_statement_cache: bool - is_async: bool - supports_server_side_cursors: bool - @classmethod - def dbapi(cls): ... - @classmethod - def get_pool_class(cls, url): ... - def is_disconnect(self, e, connection, cursor): ... - def get_driver_connection(self, connection): ... - -dialect = SQLiteDialect_aiosqlite diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/base.pyi deleted file mode 100644 index 31efadb6c920..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/base.pyi +++ /dev/null @@ -1,142 +0,0 @@ -from typing import Any - -import sqlalchemy.types as sqltypes - -from ...engine import default -from ...sql import compiler -from ...types import ( - BLOB as BLOB, - BOOLEAN as BOOLEAN, - CHAR as CHAR, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - INTEGER as INTEGER, - NUMERIC as NUMERIC, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIMESTAMP as TIMESTAMP, - VARCHAR as VARCHAR, -) -from .json import JSON as JSON - -class _SQliteJson(JSON): - def result_processor(self, dialect, coltype): ... - -class _DateTimeMixin: - def __init__(self, storage_format: Any | None = ..., regexp: Any | None = ..., **kw) -> None: ... - @property - def format_is_text_affinity(self): ... - def adapt(self, cls, **kw): ... - def literal_processor(self, dialect): ... - -class DATETIME(_DateTimeMixin, sqltypes.DateTime): - def __init__(self, *args, **kwargs) -> None: ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class DATE(_DateTimeMixin, sqltypes.Date): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class TIME(_DateTimeMixin, sqltypes.Time): - def __init__(self, *args, **kwargs) -> None: ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -colspecs: Any -ischema_names: Any - -class SQLiteCompiler(compiler.SQLCompiler): - extract_map: Any - def visit_now_func(self, fn, **kw): ... - def visit_localtimestamp_func(self, func, **kw): ... - def visit_true(self, expr, **kw): ... - def visit_false(self, expr, **kw): ... - def visit_char_length_func(self, fn, **kw): ... - def visit_cast(self, cast, **kwargs): ... - def visit_extract(self, extract, **kw): ... - def limit_clause(self, select, **kw): ... - def for_update_clause(self, select, **kw): ... - def visit_is_distinct_from_binary(self, binary, operator, **kw): ... - def visit_is_not_distinct_from_binary(self, binary, operator, **kw): ... - def visit_json_getitem_op_binary(self, binary, operator, **kw): ... - def visit_json_path_getitem_op_binary(self, binary, operator, **kw): ... - def visit_empty_set_op_expr(self, type_, expand_op): ... - def visit_empty_set_expr(self, element_types): ... - def visit_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_not_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_on_conflict_do_nothing(self, on_conflict, **kw): ... - def visit_on_conflict_do_update(self, on_conflict, **kw): ... - -class SQLiteDDLCompiler(compiler.DDLCompiler): - def get_column_specification(self, column, **kwargs): ... - def visit_primary_key_constraint(self, constraint): ... - def visit_unique_constraint(self, constraint): ... - def visit_check_constraint(self, constraint): ... - def visit_column_check_constraint(self, constraint): ... - def visit_foreign_key_constraint(self, constraint): ... - def define_constraint_remote_table(self, constraint, table, preparer): ... - def visit_create_index(self, create, include_schema: bool = ..., include_table_schema: bool = ...): ... # type: ignore[override] - def post_create_table(self, table): ... - -class SQLiteTypeCompiler(compiler.GenericTypeCompiler): - def visit_large_binary(self, type_, **kw): ... - def visit_DATETIME(self, type_, **kw): ... - def visit_DATE(self, type_, **kw): ... - def visit_TIME(self, type_, **kw): ... - def visit_JSON(self, type_, **kw): ... - -class SQLiteIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words: Any - -class SQLiteExecutionContext(default.DefaultExecutionContext): ... - -class SQLiteDialect(default.DefaultDialect): - name: str - supports_alter: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - supports_default_values: bool - supports_default_metavalue: bool - supports_empty_insert: bool - supports_cast: bool - supports_multivalues_insert: bool - tuple_in_values: bool - supports_statement_cache: bool - default_paramstyle: str - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - preparer: Any - ischema_names: Any - colspecs: Any - isolation_level: Any - construct_arguments: Any - native_datetime: Any - def __init__( - self, - isolation_level: Any | None = ..., - native_datetime: bool = ..., - json_serializer: Any | None = ..., - json_deserializer: Any | None = ..., - _json_serializer: Any | None = ..., - _json_deserializer: Any | None = ..., - **kwargs, - ) -> None: ... - def set_isolation_level(self, connection, level) -> None: ... - def get_isolation_level(self, connection): ... - def on_connect(self): ... - def get_schema_names(self, connection, **kw): ... - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_temp_table_names(self, connection, **kw): ... - def get_temp_view_names(self, connection, **kw): ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] - def get_view_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_definition(self, connection, view_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_unique_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_check_constraints(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_indexes(self, connection, table_name, schema: Any | None = ..., **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/dml.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/dml.pyi deleted file mode 100644 index 208ceca97e86..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/dml.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any - -from ...sql.dml import Insert as StandardInsert -from ...sql.elements import ClauseElement -from ...util import memoized_property - -class Insert(StandardInsert): - stringify_dialect: str - inherit_cache: bool - @memoized_property - def excluded(self): ... - def on_conflict_do_update( - self, index_elements: Any | None = ..., index_where: Any | None = ..., set_: Any | None = ..., where: Any | None = ... - ) -> None: ... - def on_conflict_do_nothing(self, index_elements: Any | None = ..., index_where: Any | None = ...) -> None: ... - -insert: Any - -class OnConflictClause(ClauseElement): - stringify_dialect: str - constraint_target: Any - inferred_target_elements: Any - inferred_target_whereclause: Any - def __init__(self, index_elements: Any | None = ..., index_where: Any | None = ...) -> None: ... - -class OnConflictDoNothing(OnConflictClause): - __visit_name__: str - -class OnConflictDoUpdate(OnConflictClause): - __visit_name__: str - update_values_to_set: Any - update_whereclause: Any - def __init__( - self, index_elements: Any | None = ..., index_where: Any | None = ..., set_: Any | None = ..., where: Any | None = ... - ) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/json.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/json.pyi deleted file mode 100644 index 2ced3beece0d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/json.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from ...types import JSON as _JSON - -class JSON(_JSON): ... - -class _FormatTypeMixin: - def bind_processor(self, dialect): ... - def literal_processor(self, dialect): ... - -class JSONIndexType(_FormatTypeMixin, _JSON.JSONIndexType): ... -class JSONPathType(_FormatTypeMixin, _JSON.JSONPathType): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/pysqlcipher.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/pysqlcipher.pyi deleted file mode 100644 index cf2d8738ed15..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/pysqlcipher.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -from .pysqlite import SQLiteDialect_pysqlite - -class SQLiteDialect_pysqlcipher(SQLiteDialect_pysqlite): - driver: str - supports_statement_cache: bool - pragmas: Any - @classmethod - def dbapi(cls): ... - @classmethod - def get_pool_class(cls, url): ... - def on_connect_url(self, url): ... - def create_connect_args(self, url): ... - -dialect = SQLiteDialect_pysqlcipher diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/pysqlite.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/pysqlite.pyi deleted file mode 100644 index 5703abbdf573..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/pysqlite.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any - -from .base import DATE, DATETIME, SQLiteDialect - -class _SQLite_pysqliteTimeStamp(DATETIME): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _SQLite_pysqliteDate(DATE): - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class SQLiteDialect_pysqlite(SQLiteDialect): - default_paramstyle: str - supports_statement_cache: bool - colspecs: Any - description_encoding: Any - driver: str - @classmethod - def dbapi(cls): ... - @classmethod - def get_pool_class(cls, url): ... - def set_isolation_level(self, connection, level): ... - def on_connect(self): ... - def create_connect_args(self, url): ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = SQLiteDialect_pysqlite diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/__init__.pyi deleted file mode 100644 index 3b97262f2a6a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/__init__.pyi +++ /dev/null @@ -1,58 +0,0 @@ -from typing import Any - -from .base import ( - BIGINT as BIGINT, - BINARY as BINARY, - BIT as BIT, - CHAR as CHAR, - DATE as DATE, - DATETIME as DATETIME, - FLOAT as FLOAT, - IMAGE as IMAGE, - INT as INT, - INTEGER as INTEGER, - MONEY as MONEY, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - SMALLINT as SMALLINT, - SMALLMONEY as SMALLMONEY, - TEXT as TEXT, - TIME as TIME, - TINYINT as TINYINT, - UNICHAR as UNICHAR, - UNITEXT as UNITEXT, - UNIVARCHAR as UNIVARCHAR, - VARBINARY as VARBINARY, - VARCHAR as VARCHAR, -) - -__all__ = ( - "CHAR", - "VARCHAR", - "TIME", - "NCHAR", - "NVARCHAR", - "TEXT", - "DATE", - "DATETIME", - "FLOAT", - "NUMERIC", - "BIGINT", - "INT", - "INTEGER", - "SMALLINT", - "BINARY", - "VARBINARY", - "UNITEXT", - "UNICHAR", - "UNIVARCHAR", - "IMAGE", - "BIT", - "MONEY", - "SMALLMONEY", - "TINYINT", - "dialect", -) - -dialect: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/base.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/base.pyi deleted file mode 100644 index 40d48d646b76..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/base.pyi +++ /dev/null @@ -1,135 +0,0 @@ -from typing import Any - -from sqlalchemy import types as sqltypes -from sqlalchemy.engine import default, reflection -from sqlalchemy.sql import compiler -from sqlalchemy.types import ( - BIGINT as BIGINT, - BINARY as BINARY, - CHAR as CHAR, - DATE as DATE, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - INT as INT, - INTEGER as INTEGER, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - VARBINARY as VARBINARY, - VARCHAR as VARCHAR, - Unicode as Unicode, -) - -RESERVED_WORDS: Any - -class _SybaseUnitypeMixin: - def result_processor(self, dialect, coltype): ... - -class UNICHAR(_SybaseUnitypeMixin, sqltypes.Unicode): - __visit_name__: str - -class UNIVARCHAR(_SybaseUnitypeMixin, sqltypes.Unicode): - __visit_name__: str - -class UNITEXT(_SybaseUnitypeMixin, sqltypes.UnicodeText): - __visit_name__: str - -class TINYINT(sqltypes.Integer): - __visit_name__: str - -class BIT(sqltypes.TypeEngine): - __visit_name__: str - -class MONEY(sqltypes.TypeEngine): - __visit_name__: str - -class SMALLMONEY(sqltypes.TypeEngine): - __visit_name__: str - -class UNIQUEIDENTIFIER(sqltypes.TypeEngine): - __visit_name__: str - -class IMAGE(sqltypes.LargeBinary): - __visit_name__: str - -class SybaseTypeCompiler(compiler.GenericTypeCompiler): - def visit_large_binary(self, type_, **kw): ... - def visit_boolean(self, type_, **kw): ... - def visit_unicode(self, type_, **kw): ... - def visit_UNICHAR(self, type_, **kw): ... - def visit_UNIVARCHAR(self, type_, **kw): ... - def visit_UNITEXT(self, type_, **kw): ... - def visit_TINYINT(self, type_, **kw): ... - def visit_IMAGE(self, type_, **kw): ... - def visit_BIT(self, type_, **kw): ... - def visit_MONEY(self, type_, **kw): ... - def visit_SMALLMONEY(self, type_, **kw): ... - def visit_UNIQUEIDENTIFIER(self, type_, **kw): ... - -ischema_names: Any - -class SybaseInspector(reflection.Inspector): - def __init__(self, conn) -> None: ... - def get_table_id(self, table_name, schema: Any | None = ...): ... - -class SybaseExecutionContext(default.DefaultExecutionContext): - def set_ddl_autocommit(self, connection, value) -> None: ... - def pre_exec(self) -> None: ... - def post_exec(self) -> None: ... - def get_lastrowid(self): ... - -class SybaseSQLCompiler(compiler.SQLCompiler): - ansi_bind_rules: bool - extract_map: Any - def get_from_hint_text(self, table, text): ... - def limit_clause(self, select, **kw): ... - def visit_extract(self, extract, **kw): ... - def visit_now_func(self, fn, **kw): ... - def for_update_clause(self, select): ... - def order_by_clause(self, select, **kw): ... - def delete_table_clause(self, delete_stmt, from_table, extra_froms): ... - def delete_extra_from_clause(self, delete_stmt, from_table, extra_froms, from_hints, **kw): ... - -class SybaseDDLCompiler(compiler.DDLCompiler): - def get_column_specification(self, column, **kwargs): ... - def visit_drop_index(self, drop): ... - -class SybaseIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words: Any - -class SybaseDialect(default.DefaultDialect): - name: str - supports_unicode_statements: bool - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - supports_statement_cache: bool - supports_native_boolean: bool - supports_unicode_binds: bool - postfetch_lastrowid: bool - colspecs: Any - ischema_names: Any - type_compiler: Any - statement_compiler: Any - ddl_compiler: Any - preparer: Any - inspector: Any - construct_arguments: Any - def __init__(self, *args, **kwargs) -> None: ... - max_identifier_length: int - def initialize(self, connection) -> None: ... - def get_table_id(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_indexes(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw): ... - def get_schema_names(self, connection, **kw): ... - def get_table_names(self, connection, schema: Any | None = ..., **kw): ... - def get_view_definition(self, connection, view_name, schema: Any | None = ..., **kw): ... - def get_view_names(self, connection, schema: Any | None = ..., **kw): ... - def has_table(self, connection, table_name, schema: Any | None = ...): ... # type: ignore[override] diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/mxodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/mxodbc.pyi deleted file mode 100644 index 596496ea18f5..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/mxodbc.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from sqlalchemy.connectors.mxodbc import MxODBCConnector -from sqlalchemy.dialects.sybase.base import SybaseDialect, SybaseExecutionContext - -class SybaseExecutionContext_mxodbc(SybaseExecutionContext): ... - -class SybaseDialect_mxodbc(MxODBCConnector, SybaseDialect): - supports_statement_cache: bool - -dialect = SybaseDialect_mxodbc diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/pyodbc.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/pyodbc.pyi deleted file mode 100644 index 3940f1f665e3..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/pyodbc.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -from sqlalchemy import types as sqltypes -from sqlalchemy.connectors.pyodbc import PyODBCConnector -from sqlalchemy.dialects.sybase.base import SybaseDialect, SybaseExecutionContext - -class _SybNumeric_pyodbc(sqltypes.Numeric): - def bind_processor(self, dialect): ... - -class SybaseExecutionContext_pyodbc(SybaseExecutionContext): - def set_ddl_autocommit(self, connection, value) -> None: ... - -class SybaseDialect_pyodbc(PyODBCConnector, SybaseDialect): - supports_statement_cache: bool - colspecs: Any - @classmethod - def dbapi(cls): ... - -dialect = SybaseDialect_pyodbc diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/pysybase.pyi b/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/pysybase.pyi deleted file mode 100644 index ae8c0591f00e..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/dialects/sybase/pysybase.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any - -from sqlalchemy import types as sqltypes -from sqlalchemy.dialects.sybase.base import SybaseDialect, SybaseExecutionContext, SybaseSQLCompiler - -class _SybNumeric(sqltypes.Numeric): - def result_processor(self, dialect, type_): ... - -class SybaseExecutionContext_pysybase(SybaseExecutionContext): - def set_ddl_autocommit(self, dbapi_connection, value) -> None: ... - def pre_exec(self) -> None: ... - -class SybaseSQLCompiler_pysybase(SybaseSQLCompiler): - def bindparam_string(self, name, **kw): ... - -class SybaseDialect_pysybase(SybaseDialect): - driver: str - statement_compiler: Any - supports_statement_cache: bool - colspecs: Any - @classmethod - def dbapi(cls): ... - def create_connect_args(self, url): ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def is_disconnect(self, e, connection, cursor): ... - -dialect = SybaseDialect_pysybase diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/__init__.pyi deleted file mode 100644 index 48d019b651ac..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/__init__.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from ..sql import ddl as ddl -from . import events as events, util as util -from .base import ( - Connection as Connection, - Engine as Engine, - NestedTransaction as NestedTransaction, - RootTransaction as RootTransaction, - Transaction as Transaction, - TwoPhaseTransaction as TwoPhaseTransaction, -) -from .create import create_engine as create_engine, engine_from_config as engine_from_config -from .cursor import ( - BaseCursorResult as BaseCursorResult, - BufferedColumnResultProxy as BufferedColumnResultProxy, - BufferedColumnRow as BufferedColumnRow, - BufferedRowResultProxy as BufferedRowResultProxy, - CursorResult as CursorResult, - FullyBufferedResultProxy as FullyBufferedResultProxy, - LegacyCursorResult as LegacyCursorResult, - ResultProxy as ResultProxy, -) -from .interfaces import ( - AdaptedConnection as AdaptedConnection, - Compiled as Compiled, - Connectable as Connectable, - CreateEnginePlugin as CreateEnginePlugin, - Dialect as Dialect, - ExceptionContext as ExceptionContext, - ExecutionContext as ExecutionContext, - TypeCompiler as TypeCompiler, -) -from .mock import create_mock_engine as create_mock_engine -from .reflection import Inspector as Inspector -from .result import ( - ChunkedIteratorResult as ChunkedIteratorResult, - FrozenResult as FrozenResult, - IteratorResult as IteratorResult, - MappingResult as MappingResult, - MergedResult as MergedResult, - Result as Result, - ScalarResult as ScalarResult, - result_tuple as result_tuple, -) -from .row import BaseRow as BaseRow, LegacyRow as LegacyRow, Row as Row, RowMapping as RowMapping -from .url import URL as URL, make_url as make_url -from .util import connection_memoize as connection_memoize diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/base.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/base.pyi deleted file mode 100644 index 32640ff8c132..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/base.pyi +++ /dev/null @@ -1,169 +0,0 @@ -from typing import Any - -from .. import log -from .interfaces import Connectable as Connectable, ExceptionContext -from .util import TransactionalContext - -class Connection(Connectable): - engine: Any - dialect: Any - should_close_with_result: bool - dispatch: Any - def __init__( - self, - engine, - connection: Any | None = ..., - close_with_result: bool = ..., - _branch_from: Any | None = ..., - _execution_options: Any | None = ..., - _dispatch: Any | None = ..., - _has_events: Any | None = ..., - _allow_revalidate: bool = ..., - ) -> None: ... - def schema_for_object(self, obj): ... - def __enter__(self): ... - def __exit__(self, type_, value, traceback) -> None: ... - def execution_options(self, **opt): ... - def get_execution_options(self): ... - @property - def closed(self): ... - @property - def invalidated(self): ... - @property - def connection(self): ... - def get_isolation_level(self): ... - @property - def default_isolation_level(self): ... - @property - def info(self): ... - def connect(self, close_with_result: bool = ...): ... # type: ignore[override] - def invalidate(self, exception: Any | None = ...): ... - def detach(self) -> None: ... - def begin(self): ... - def begin_nested(self): ... - def begin_twophase(self, xid: Any | None = ...): ... - def recover_twophase(self): ... - def rollback_prepared(self, xid, recover: bool = ...) -> None: ... - def commit_prepared(self, xid, recover: bool = ...) -> None: ... - def in_transaction(self): ... - def in_nested_transaction(self): ... - def get_transaction(self): ... - def get_nested_transaction(self): ... - def close(self) -> None: ... - def scalar(self, object_, *multiparams, **params): ... - def scalars(self, object_, *multiparams, **params): ... - def execute(self, statement, *multiparams, **params): ... - def exec_driver_sql(self, statement, parameters: Any | None = ..., execution_options: Any | None = ...): ... - def transaction(self, callable_, *args, **kwargs): ... - def run_callable(self, callable_, *args, **kwargs): ... - -class ExceptionContextImpl(ExceptionContext): - engine: Any - connection: Any - sqlalchemy_exception: Any - original_exception: Any - execution_context: Any - statement: Any - parameters: Any - is_disconnect: Any - invalidate_pool_on_disconnect: Any - def __init__( - self, - exception, - sqlalchemy_exception, - engine, - connection, - cursor, - statement, - parameters, - context, - is_disconnect, - invalidate_pool_on_disconnect, - ) -> None: ... - -class Transaction(TransactionalContext): - def __init__(self, connection) -> None: ... - @property - def is_valid(self): ... - def close(self) -> None: ... - def rollback(self) -> None: ... - def commit(self) -> None: ... - -class MarkerTransaction(Transaction): - connection: Any - def __init__(self, connection) -> None: ... - @property - def is_active(self): ... - -class RootTransaction(Transaction): - connection: Any - is_active: bool - def __init__(self, connection) -> None: ... - -class NestedTransaction(Transaction): - connection: Any - is_active: bool - def __init__(self, connection) -> None: ... - -class TwoPhaseTransaction(RootTransaction): - xid: Any - def __init__(self, connection, xid) -> None: ... - def prepare(self) -> None: ... - -class Engine(Connectable, log.Identified): - pool: Any - url: Any - dialect: Any - logging_name: Any - echo: Any - hide_parameters: Any - def __init__( - self, - pool, - dialect, - url, - logging_name: Any | None = ..., - echo: Any | None = ..., - query_cache_size: int = ..., - execution_options: Any | None = ..., - hide_parameters: bool = ..., - ) -> None: ... - @property - def engine(self): ... - def clear_compiled_cache(self) -> None: ... - def update_execution_options(self, **opt) -> None: ... - def execution_options(self, **opt): ... - def get_execution_options(self): ... - @property - def name(self): ... - @property - def driver(self): ... - def dispose(self) -> None: ... - class _trans_ctx: - conn: Any - transaction: Any - close_with_result: Any - def __init__(self, conn, transaction, close_with_result) -> None: ... - def __enter__(self): ... - def __exit__(self, type_, value, traceback) -> None: ... - def begin(self, close_with_result: bool = ...): ... - def transaction(self, callable_, *args, **kwargs): ... - def run_callable(self, callable_, *args, **kwargs): ... - def execute(self, statement, *multiparams, **params): ... - def scalar(self, statement, *multiparams, **params): ... - def connect(self, close_with_result: bool = ...): ... # type: ignore[override] - def table_names(self, schema: Any | None = ..., connection: Any | None = ...): ... - def has_table(self, table_name, schema: Any | None = ...): ... - def raw_connection(self, _connection: Any | None = ...): ... - -class OptionEngineMixin: - url: Any - dialect: Any - logging_name: Any - echo: Any - hide_parameters: Any - dispatch: Any - def __init__(self, proxied, execution_options) -> None: ... - pool: Any - -class OptionEngine(OptionEngineMixin, Engine): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/characteristics.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/characteristics.pyi deleted file mode 100644 index ab5b5f63cddc..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/characteristics.pyi +++ /dev/null @@ -1,18 +0,0 @@ -import abc - -from ..util import ABC - -class ConnectionCharacteristic(ABC, metaclass=abc.ABCMeta): - transactional: bool - @abc.abstractmethod - def reset_characteristic(self, dialect, dbapi_conn): ... - @abc.abstractmethod - def set_characteristic(self, dialect, dbapi_conn, value): ... - @abc.abstractmethod - def get_characteristic(self, dialect, dbapi_conn): ... - -class IsolationLevelCharacteristic(ConnectionCharacteristic): - transactional: bool - def reset_characteristic(self, dialect, dbapi_conn) -> None: ... - def set_characteristic(self, dialect, dbapi_conn, value) -> None: ... - def get_characteristic(self, dialect, dbapi_conn): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/create.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/create.pyi deleted file mode 100644 index b3f86c1fbb3a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/create.pyi +++ /dev/null @@ -1,2 +0,0 @@ -def create_engine(url, **kwargs): ... -def engine_from_config(configuration, prefix: str = ..., **kwargs): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/cursor.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/cursor.pyi deleted file mode 100644 index 557743fb08ff..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/cursor.pyi +++ /dev/null @@ -1,128 +0,0 @@ -import abc -from typing import Any - -from ..util import memoized_property -from .result import Result, ResultMetaData -from .row import LegacyRow - -MD_INDEX: int -MD_RESULT_MAP_INDEX: int -MD_OBJECTS: int -MD_LOOKUP_KEY: int -MD_RENDERED_NAME: int -MD_PROCESSOR: int -MD_UNTRANSLATED: int - -class CursorResultMetaData(ResultMetaData): - returns_rows: bool - case_sensitive: Any - def __init__(self, parent, cursor_description) -> None: ... - -class LegacyCursorResultMetaData(CursorResultMetaData): ... - -class ResultFetchStrategy: - alternate_cursor_description: Any - def soft_close(self, result, dbapi_cursor) -> None: ... - def hard_close(self, result, dbapi_cursor) -> None: ... - def yield_per(self, result, dbapi_cursor, num) -> None: ... - def fetchone(self, result, dbapi_cursor, hard_close: bool = ...) -> None: ... - def fetchmany(self, result, dbapi_cursor, size: Any | None = ...) -> None: ... - def fetchall(self, result) -> None: ... - def handle_exception(self, result, dbapi_cursor, err) -> None: ... - -class NoCursorFetchStrategy(ResultFetchStrategy): - def soft_close(self, result, dbapi_cursor) -> None: ... - def hard_close(self, result, dbapi_cursor) -> None: ... - def fetchone(self, result, dbapi_cursor, hard_close: bool = ...): ... - def fetchmany(self, result, dbapi_cursor, size: Any | None = ...): ... - def fetchall(self, result, dbapi_cursor): ... - -class NoCursorDQLFetchStrategy(NoCursorFetchStrategy): ... -class NoCursorDMLFetchStrategy(NoCursorFetchStrategy): ... - -class CursorFetchStrategy(ResultFetchStrategy): - def soft_close(self, result, dbapi_cursor) -> None: ... - def hard_close(self, result, dbapi_cursor) -> None: ... - def handle_exception(self, result, dbapi_cursor, err) -> None: ... - def yield_per(self, result, dbapi_cursor, num) -> None: ... - def fetchone(self, result, dbapi_cursor, hard_close: bool = ...): ... - def fetchmany(self, result, dbapi_cursor, size: Any | None = ...): ... - def fetchall(self, result, dbapi_cursor): ... - -class BufferedRowCursorFetchStrategy(CursorFetchStrategy): - def __init__(self, dbapi_cursor, execution_options, growth_factor: int = ..., initial_buffer: Any | None = ...) -> None: ... - @classmethod - def create(cls, result): ... - def yield_per(self, result, dbapi_cursor, num) -> None: ... - def soft_close(self, result, dbapi_cursor) -> None: ... - def hard_close(self, result, dbapi_cursor) -> None: ... - def fetchone(self, result, dbapi_cursor, hard_close: bool = ...): ... - def fetchmany(self, result, dbapi_cursor, size: Any | None = ...): ... - def fetchall(self, result, dbapi_cursor): ... - -class FullyBufferedCursorFetchStrategy(CursorFetchStrategy): - alternate_cursor_description: Any - def __init__(self, dbapi_cursor, alternate_description: Any | None = ..., initial_buffer: Any | None = ...) -> None: ... - def yield_per(self, result, dbapi_cursor, num) -> None: ... - def soft_close(self, result, dbapi_cursor) -> None: ... - def hard_close(self, result, dbapi_cursor) -> None: ... - def fetchone(self, result, dbapi_cursor, hard_close: bool = ...): ... - def fetchmany(self, result, dbapi_cursor, size: Any | None = ...): ... - def fetchall(self, result, dbapi_cursor): ... - -class _NoResultMetaData(ResultMetaData): - returns_rows: bool - @property - def keys(self) -> None: ... - -class _LegacyNoResultMetaData(_NoResultMetaData): - @property - def keys(self): ... - -class BaseCursorResult: - out_parameters: Any - closed: bool - context: Any - dialect: Any - cursor: Any - cursor_strategy: Any - connection: Any - def __init__(self, context, cursor_strategy, cursor_description): ... - @property - def inserted_primary_key_rows(self): ... - @property - def inserted_primary_key(self): ... - def last_updated_params(self): ... - def last_inserted_params(self): ... - @property - def returned_defaults_rows(self): ... - @property - def returned_defaults(self): ... - def lastrow_has_defaults(self): ... - def postfetch_cols(self): ... - def prefetch_cols(self): ... - def supports_sane_rowcount(self): ... - def supports_sane_multi_rowcount(self): ... - @memoized_property - def rowcount(self): ... - @property - def lastrowid(self): ... - @property - def returns_rows(self): ... - @property - def is_insert(self): ... - -class CursorResult(BaseCursorResult, Result): - def merge(self, *others): ... - def close(self) -> None: ... - def yield_per(self, num) -> None: ... - -class LegacyCursorResult(CursorResult): - def close(self) -> None: ... - -ResultProxy = LegacyCursorResult - -class BufferedRowResultProxy(ResultProxy): ... -class FullyBufferedResultProxy(ResultProxy): ... -class BufferedColumnRow(LegacyRow, metaclass=abc.ABCMeta): ... -class BufferedColumnResultProxy(ResultProxy): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/default.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/default.pyi deleted file mode 100644 index a461b5f5ac83..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/default.pyi +++ /dev/null @@ -1,220 +0,0 @@ -from typing import Any, ClassVar, Type - -from .. import types as sqltypes -from ..util import memoized_property -from . import interfaces - -AUTOCOMMIT_REGEXP: Any -SERVER_SIDE_CURSOR_RE: Any -CACHE_HIT: Any -CACHE_MISS: Any -CACHING_DISABLED: Any -NO_CACHE_KEY: Any -NO_DIALECT_SUPPORT: Any - -class DefaultDialect(interfaces.Dialect): - execution_ctx_cls: ClassVar[Type[interfaces.ExecutionContext]] - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - preparer: Any - supports_alter: bool - supports_comments: bool - inline_comments: bool - use_setinputsizes: bool - supports_statement_cache: bool - default_sequence_base: int - execute_sequence_format: Any - supports_schemas: bool - supports_views: bool - supports_sequences: bool - sequences_optional: bool - preexecute_autoincrement_sequences: bool - supports_identity_columns: bool - postfetch_lastrowid: bool - implicit_returning: bool - full_returning: bool - insert_executemany_returning: bool - cte_follows_insert: bool - supports_native_enum: bool - supports_native_boolean: bool - non_native_boolean_check_constraint: bool - supports_simple_order_by_label: bool - tuple_in_values: bool - connection_characteristics: Any - engine_config_types: Any - supports_native_decimal: bool - supports_unicode_statements: bool - supports_unicode_binds: bool - returns_unicode_strings: Any - description_encoding: Any - name: str - max_identifier_length: int - isolation_level: Any - max_index_name_length: Any - max_constraint_name_length: Any - supports_sane_rowcount: bool - supports_sane_multi_rowcount: bool - colspecs: Any - default_paramstyle: str - supports_default_values: bool - supports_default_metavalue: bool - supports_empty_insert: bool - supports_multivalues_insert: bool - supports_is_distinct_from: bool - supports_server_side_cursors: bool - server_side_cursors: bool - supports_for_update_of: bool - server_version_info: Any - default_schema_name: Any - construct_arguments: Any - requires_name_normalize: bool - reflection_options: Any - dbapi_exception_translation_map: Any - is_async: bool - CACHE_HIT: Any - CACHE_MISS: Any - CACHING_DISABLED: Any - NO_CACHE_KEY: Any - NO_DIALECT_SUPPORT: Any - convert_unicode: Any - encoding: Any - positional: bool - dbapi: Any - paramstyle: Any - identifier_preparer: Any - case_sensitive: Any - label_length: Any - compiler_linting: Any - def __init__( - self, - convert_unicode: bool = ..., - encoding: str = ..., - paramstyle: Any | None = ..., - dbapi: Any | None = ..., - implicit_returning: Any | None = ..., - case_sensitive: bool = ..., - supports_native_boolean: Any | None = ..., - max_identifier_length: Any | None = ..., - label_length: Any | None = ..., - compiler_linting=..., - server_side_cursors: bool = ..., - **kwargs, - ) -> None: ... - @property - def dialect_description(self): ... - @property - def supports_sane_rowcount_returning(self): ... - @classmethod - def get_pool_class(cls, url): ... - def get_dialect_pool_class(self, url): ... - @classmethod - def load_provisioning(cls) -> None: ... - default_isolation_level: Any - def initialize(self, connection) -> None: ... - def on_connect(self) -> None: ... - def get_default_isolation_level(self, dbapi_conn): ... - def type_descriptor(self, typeobj): ... - def has_index(self, connection, table_name, index_name, schema: Any | None = ...): ... - def validate_identifier(self, ident) -> None: ... - def connect(self, *cargs, **cparams): ... - def create_connect_args(self, url): ... - def set_engine_execution_options(self, engine, opts) -> None: ... - def set_connection_execution_options(self, connection, opts) -> None: ... - def do_begin(self, dbapi_connection) -> None: ... - def do_rollback(self, dbapi_connection) -> None: ... - def do_commit(self, dbapi_connection) -> None: ... - def do_close(self, dbapi_connection) -> None: ... - def do_ping(self, dbapi_connection): ... - def create_xid(self): ... - def do_savepoint(self, connection, name) -> None: ... - def do_rollback_to_savepoint(self, connection, name) -> None: ... - def do_release_savepoint(self, connection, name) -> None: ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_execute(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_execute_no_params(self, cursor, statement, context: Any | None = ...) -> None: ... # type: ignore[override] - def is_disconnect(self, e, connection, cursor): ... - def reset_isolation_level(self, dbapi_conn) -> None: ... - def normalize_name(self, name): ... - def denormalize_name(self, name): ... - def get_driver_connection(self, connection): ... - -class _RendersLiteral: - def literal_processor(self, dialect): ... - -class _StrDateTime(_RendersLiteral, sqltypes.DateTime): ... -class _StrDate(_RendersLiteral, sqltypes.Date): ... -class _StrTime(_RendersLiteral, sqltypes.Time): ... - -class StrCompileDialect(DefaultDialect): - statement_compiler: Any - ddl_compiler: Any - type_compiler: Any - preparer: Any - supports_statement_cache: bool - supports_identity_columns: bool - supports_sequences: bool - sequences_optional: bool - preexecute_autoincrement_sequences: bool - implicit_returning: bool - supports_native_boolean: bool - supports_multivalues_insert: bool - supports_simple_order_by_label: bool - colspecs: Any - -class DefaultExecutionContext(interfaces.ExecutionContext): - isinsert: bool - isupdate: bool - isdelete: bool - is_crud: bool - is_text: bool - isddl: bool - executemany: bool - compiled: Any - statement: Any - result_column_struct: Any - returned_default_rows: Any - execution_options: Any - include_set_input_sizes: Any - exclude_set_input_sizes: Any - cursor_fetch_strategy: Any - cache_stats: Any - invoked_statement: Any - cache_hit: Any - @memoized_property - def identifier_preparer(self): ... - @memoized_property - def engine(self): ... - @memoized_property - def postfetch_cols(self): ... - @memoized_property - def prefetch_cols(self): ... - @memoized_property - def returning_cols(self) -> None: ... - @memoized_property - def no_parameters(self): ... - @memoized_property - def should_autocommit(self): ... - @property - def connection(self): ... - def should_autocommit_text(self, statement): ... - def create_cursor(self): ... - def create_default_cursor(self): ... - def create_server_side_cursor(self) -> None: ... - def pre_exec(self) -> None: ... - def get_out_parameter_values(self, names) -> None: ... - def post_exec(self) -> None: ... - def get_result_processor(self, type_, colname, coltype): ... - def get_lastrowid(self): ... - def handle_dbapi_exception(self, e) -> None: ... - @property - def rowcount(self): ... - def supports_sane_rowcount(self): ... - def supports_sane_multi_rowcount(self): ... - @memoized_property - def inserted_primary_key_rows(self): ... - def lastrow_has_defaults(self): ... - current_parameters: Any - def get_current_parameters(self, isolate_multiinsert_groups: bool = ...): ... - def get_insert_default(self, column): ... - def get_update_default(self, column): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/events.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/events.pyi deleted file mode 100644 index 7cca8b27ce2b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/events.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from .. import event as event - -class ConnectionEvents(event.Events): - def before_execute(self, conn, clauseelement, multiparams, params, execution_options) -> None: ... - def after_execute(self, conn, clauseelement, multiparams, params, execution_options, result) -> None: ... - def before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany) -> None: ... - def after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany) -> None: ... - def handle_error(self, exception_context) -> None: ... - def engine_connect(self, conn, branch) -> None: ... - def set_connection_execution_options(self, conn, opts) -> None: ... - def set_engine_execution_options(self, engine, opts) -> None: ... - def engine_disposed(self, engine) -> None: ... - def begin(self, conn) -> None: ... - def rollback(self, conn) -> None: ... - def commit(self, conn) -> None: ... - def savepoint(self, conn, name) -> None: ... - def rollback_savepoint(self, conn, name, context) -> None: ... - def release_savepoint(self, conn, name, context) -> None: ... - def begin_twophase(self, conn, xid) -> None: ... - def prepare_twophase(self, conn, xid) -> None: ... - def rollback_twophase(self, conn, xid, is_prepared) -> None: ... - def commit_twophase(self, conn, xid, is_prepared) -> None: ... - -class DialectEvents(event.Events): - def do_connect(self, dialect, conn_rec, cargs, cparams) -> None: ... - def do_executemany(self, cursor, statement, parameters, context) -> None: ... - def do_execute_no_params(self, cursor, statement, context) -> None: ... - def do_execute(self, cursor, statement, parameters, context) -> None: ... - def do_setinputsizes(self, inputsizes, cursor, statement, parameters, context) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/interfaces.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/interfaces.pyi deleted file mode 100644 index 24c6ae829c53..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/interfaces.pyi +++ /dev/null @@ -1,102 +0,0 @@ -from typing import Any - -from ..sql.compiler import Compiled as Compiled, TypeCompiler as TypeCompiler - -class Dialect: - supports_statement_cache: bool - def create_connect_args(self, url) -> None: ... - @classmethod - def type_descriptor(cls, typeobj) -> None: ... - def initialize(self, connection) -> None: ... - def get_columns(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def get_pk_constraint(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def get_foreign_keys(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def get_table_names(self, connection, schema: Any | None = ..., **kw) -> None: ... - def get_temp_table_names(self, connection, schema: Any | None = ..., **kw) -> None: ... - def get_view_names(self, connection, schema: Any | None = ..., **kw) -> None: ... - def get_sequence_names(self, connection, schema: Any | None = ..., **kw) -> None: ... - def get_temp_view_names(self, connection, schema: Any | None = ..., **kw) -> None: ... - def get_view_definition(self, connection, view_name, schema: Any | None = ..., **kw) -> None: ... - def get_indexes(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def get_unique_constraints(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def get_check_constraints(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def get_table_comment(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def normalize_name(self, name) -> None: ... - def denormalize_name(self, name) -> None: ... - def has_table(self, connection, table_name, schema: Any | None = ..., **kw) -> None: ... - def has_index(self, connection, table_name, index_name, schema: Any | None = ...) -> None: ... - def has_sequence(self, connection, sequence_name, schema: Any | None = ..., **kw) -> None: ... - def do_begin(self, dbapi_connection) -> None: ... - def do_rollback(self, dbapi_connection) -> None: ... - def do_commit(self, dbapi_connection) -> None: ... - def do_close(self, dbapi_connection) -> None: ... - def do_set_input_sizes(self, cursor, list_of_tuples, context) -> None: ... - def create_xid(self) -> None: ... - def do_savepoint(self, connection, name) -> None: ... - def do_rollback_to_savepoint(self, connection, name) -> None: ... - def do_release_savepoint(self, connection, name) -> None: ... - def do_begin_twophase(self, connection, xid) -> None: ... - def do_prepare_twophase(self, connection, xid) -> None: ... - def do_rollback_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_commit_twophase(self, connection, xid, is_prepared: bool = ..., recover: bool = ...) -> None: ... - def do_recover_twophase(self, connection) -> None: ... - def do_executemany(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_execute(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def do_execute_no_params(self, cursor, statement, parameters, context: Any | None = ...) -> None: ... - def is_disconnect(self, e, connection, cursor) -> None: ... - def connect(self, *cargs, **cparams) -> None: ... - def on_connect_url(self, url): ... - def on_connect(self) -> None: ... - def reset_isolation_level(self, dbapi_conn) -> None: ... - def set_isolation_level(self, dbapi_conn, level) -> None: ... - def get_isolation_level(self, dbapi_conn) -> None: ... - def get_default_isolation_level(self, dbapi_conn) -> None: ... - @classmethod - def get_dialect_cls(cls, url): ... - @classmethod - def load_provisioning(cls) -> None: ... - @classmethod - def engine_created(cls, engine) -> None: ... - def get_driver_connection(self, connection) -> None: ... - -class CreateEnginePlugin: - url: Any - def __init__(self, url, kwargs) -> None: ... - def update_url(self, url) -> None: ... - def handle_dialect_kwargs(self, dialect_cls, dialect_args) -> None: ... - def handle_pool_kwargs(self, pool_cls, pool_args) -> None: ... - def engine_created(self, engine) -> None: ... - -class ExecutionContext: - def create_cursor(self) -> None: ... - def pre_exec(self) -> None: ... - def get_out_parameter_values(self, out_param_names) -> None: ... - def post_exec(self) -> None: ... - def get_result_cursor_strategy(self, result) -> None: ... - def handle_dbapi_exception(self, e) -> None: ... - def should_autocommit_text(self, statement) -> None: ... - def lastrow_has_defaults(self) -> None: ... - def get_rowcount(self) -> None: ... - -class Connectable: - def connect(self, **kwargs) -> None: ... - engine: Any - def execute(self, object_, *multiparams, **params) -> None: ... - def scalar(self, object_, *multiparams, **params) -> None: ... - -class ExceptionContext: - connection: Any - engine: Any - cursor: Any - statement: Any - parameters: Any - original_exception: Any - sqlalchemy_exception: Any - chained_exception: Any - execution_context: Any - is_disconnect: Any - invalidate_pool_on_disconnect: bool - -class AdaptedConnection: - @property - def driver_connection(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/mock.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/mock.pyi deleted file mode 100644 index 47bb1b0fc9da..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/mock.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any - -from . import base - -class MockConnection(base.Connectable): - def __init__(self, dialect, execute) -> None: ... - engine: Any - dialect: Any - name: Any - def schema_for_object(self, obj): ... - def connect(self, **kwargs): ... - def execution_options(self, **kw): ... - def compiler(self, statement, parameters, **kwargs): ... - def create(self, entity, **kwargs) -> None: ... - def drop(self, entity, **kwargs) -> None: ... - def execute(self, object_, *multiparams, **params) -> None: ... - -def create_mock_engine(url, executor, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/reflection.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/reflection.pyi deleted file mode 100644 index fcfd262c2a88..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/reflection.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any - -def cache(fn, self, con, *args, **kw): ... - -class Inspector: - def __init__(self, bind): ... - @classmethod - def from_engine(cls, bind): ... - @property - def default_schema_name(self): ... - def get_schema_names(self): ... - def get_table_names(self, schema: Any | None = ...): ... - def has_table(self, table_name, schema: Any | None = ...): ... - def has_sequence(self, sequence_name, schema: Any | None = ...): ... - def get_sorted_table_and_fkc_names(self, schema: Any | None = ...): ... - def get_temp_table_names(self): ... - def get_temp_view_names(self): ... - def get_table_options(self, table_name, schema: Any | None = ..., **kw): ... - def get_view_names(self, schema: Any | None = ...): ... - def get_sequence_names(self, schema: Any | None = ...): ... - def get_view_definition(self, view_name, schema: Any | None = ...): ... - def get_columns(self, table_name, schema: Any | None = ..., **kw): ... - def get_pk_constraint(self, table_name, schema: Any | None = ..., **kw): ... - def get_foreign_keys(self, table_name, schema: Any | None = ..., **kw): ... - def get_indexes(self, table_name, schema: Any | None = ..., **kw): ... - def get_unique_constraints(self, table_name, schema: Any | None = ..., **kw): ... - def get_table_comment(self, table_name, schema: Any | None = ..., **kw): ... - def get_check_constraints(self, table_name, schema: Any | None = ..., **kw): ... - def reflecttable(self, *args, **kwargs): ... - def reflect_table( - self, table, include_columns, exclude_columns=..., resolve_fks: bool = ..., _extend_on: Any | None = ... - ) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/result.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/result.pyi deleted file mode 100644 index 027a86dd8665..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/result.pyi +++ /dev/null @@ -1,117 +0,0 @@ -from collections.abc import KeysView -from typing import Any - -from ..sql.base import InPlaceGenerative - -class ResultMetaData: - @property - def keys(self): ... - -class RMKeyView(KeysView[Any]): - def __init__(self, parent) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __contains__(self, item): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - -class SimpleResultMetaData(ResultMetaData): - def __init__( - self, - keys, - extra: Any | None = ..., - _processors: Any | None = ..., - _tuplefilter: Any | None = ..., - _translated_indexes: Any | None = ..., - _unique_filters: Any | None = ..., - ) -> None: ... - -def result_tuple(fields, extra: Any | None = ...): ... - -class ResultInternal(InPlaceGenerative): ... - -class _WithKeys: - def keys(self): ... - -class Result(_WithKeys, ResultInternal): - def __init__(self, cursor_metadata) -> None: ... - def close(self) -> None: ... - def yield_per(self, num) -> None: ... - def unique(self, strategy: Any | None = ...) -> None: ... - def columns(self, *col_expressions): ... - def scalars(self, index: int = ...): ... - def mappings(self): ... - def __iter__(self): ... - def __next__(self): ... - def partitions(self, size: Any | None = ...) -> None: ... - def fetchall(self): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def all(self): ... - def first(self): ... - def one_or_none(self): ... - def scalar_one(self): ... - def scalar_one_or_none(self): ... - def one(self): ... - def scalar(self): ... - def freeze(self): ... - def merge(self, *others): ... - -class FilterResult(ResultInternal): ... - -class ScalarResult(FilterResult): - def __init__(self, real_result, index) -> None: ... - def unique(self, strategy: Any | None = ...): ... - def partitions(self, size: Any | None = ...) -> None: ... - def fetchall(self): ... - def fetchmany(self, size: Any | None = ...): ... - def all(self): ... - def __iter__(self): ... - def __next__(self): ... - def first(self): ... - def one_or_none(self): ... - def one(self): ... - -class MappingResult(_WithKeys, FilterResult): - def __init__(self, result) -> None: ... - def unique(self, strategy: Any | None = ...): ... - def columns(self, *col_expressions): ... - def partitions(self, size: Any | None = ...) -> None: ... - def fetchall(self): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def all(self): ... - def __iter__(self): ... - def __next__(self): ... - def first(self): ... - def one_or_none(self): ... - def one(self): ... - -class FrozenResult: - metadata: Any - data: Any - def __init__(self, result) -> None: ... - def rewrite_rows(self): ... - def with_new_rows(self, tuple_data): ... - def __call__(self): ... - -class IteratorResult(Result): - iterator: Any - raw: Any - def __init__(self, cursor_metadata, iterator, raw: Any | None = ..., _source_supports_scalars: bool = ...) -> None: ... - -def null_result(): ... - -class ChunkedIteratorResult(IteratorResult): - chunks: Any - raw: Any - iterator: Any - dynamic_yield_per: Any - def __init__( - self, cursor_metadata, chunks, source_supports_scalars: bool = ..., raw: Any | None = ..., dynamic_yield_per: bool = ... - ) -> None: ... - def yield_per(self, num) -> None: ... - -class MergedResult(IteratorResult): - closed: bool - def __init__(self, cursor_metadata, results) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/row.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/row.pyi deleted file mode 100644 index 31167fca73c9..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/row.pyi +++ /dev/null @@ -1,55 +0,0 @@ -import abc -from collections.abc import ItemsView, KeysView, Mapping, Sequence, ValuesView -from typing import Any - -from ..cresultproxy import BaseRow as BaseRow - -MD_INDEX: int - -def rowproxy_reconstructor(cls, state): ... - -KEY_INTEGER_ONLY: int -KEY_OBJECTS_ONLY: int -KEY_OBJECTS_BUT_WARN: int -KEY_OBJECTS_NO_WARN: int - -class Row(BaseRow, Sequence[Any], metaclass=abc.ABCMeta): - count: Any - index: Any - def __contains__(self, key): ... - __hash__: Any - def __lt__(self, other): ... - def __le__(self, other): ... - def __ge__(self, other): ... - def __gt__(self, other): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def keys(self): ... - -class LegacyRow(Row, metaclass=abc.ABCMeta): - def __contains__(self, key): ... - def has_key(self, key): ... - def items(self): ... - def iterkeys(self): ... - def itervalues(self): ... - def values(self): ... - -BaseRowProxy = BaseRow -RowProxy = Row - -class ROMappingView(KeysView[Any], ValuesView[Any], ItemsView[Any, Any]): - def __init__(self, mapping, items) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __contains__(self, item): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - -class RowMapping(BaseRow, Mapping[Any, Any]): - __getitem__: Any - def __iter__(self): ... - def __len__(self): ... - def __contains__(self, key): ... - def items(self): ... - def keys(self): ... - def values(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/strategies.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/strategies.pyi deleted file mode 100644 index 25239d17b276..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/strategies.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Any - -class MockEngineStrategy: - MockConnection: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/url.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/url.pyi deleted file mode 100644 index 3ea48464fdff..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/url.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Any - -from ..util import memoized_property - -class URL: - def __new__(cls, *arg, **kw): ... - @classmethod - def create( - cls, - drivername, - username: Any | None = ..., - password: Any | None = ..., - host: Any | None = ..., - port: Any | None = ..., - database: Any | None = ..., - query=..., - ): ... - def set( - self, - drivername: Any | None = ..., - username: Any | None = ..., - password: Any | None = ..., - host: Any | None = ..., - port: Any | None = ..., - database: Any | None = ..., - query: Any | None = ..., - ): ... - def update_query_string(self, query_string, append: bool = ...): ... - def update_query_pairs(self, key_value_pairs, append: bool = ...): ... - def update_query_dict(self, query_parameters, append: bool = ...): ... - def difference_update_query(self, names): ... - @memoized_property - def normalized_query(self): ... - def __to_string__(self, hide_password: bool = ...): ... - def render_as_string(self, hide_password: bool = ...): ... - def __copy__(self): ... - def __deepcopy__(self, memo): ... - def __hash__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def get_backend_name(self): ... - def get_driver_name(self): ... - def get_dialect(self): ... - def translate_connect_args(self, names: Any | None = ..., **kw): ... - -def make_url(name_or_url): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/engine/util.pyi b/stubs/SQLAlchemy/sqlalchemy/engine/util.pyi deleted file mode 100644 index 32aea3338740..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/engine/util.pyi +++ /dev/null @@ -1,5 +0,0 @@ -def connection_memoize(key): ... - -class TransactionalContext: - def __enter__(self): ... - def __exit__(self, type_, value, traceback) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/event/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/event/__init__.pyi deleted file mode 100644 index a0b0fcea8bff..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/event/__init__.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from .api import ( - CANCEL as CANCEL, - NO_RETVAL as NO_RETVAL, - contains as contains, - listen as listen, - listens_for as listens_for, - remove as remove, -) -from .attr import RefCollection as RefCollection -from .base import Events as Events, dispatcher as dispatcher diff --git a/stubs/SQLAlchemy/sqlalchemy/event/api.pyi b/stubs/SQLAlchemy/sqlalchemy/event/api.pyi deleted file mode 100644 index bea12af06067..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/event/api.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -CANCEL: Any -NO_RETVAL: Any - -def listen(target, identifier, fn, *args, **kw) -> None: ... -def listens_for(target, identifier, *args, **kw): ... -def remove(target, identifier, fn) -> None: ... -def contains(target, identifier, fn): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/event/attr.pyi b/stubs/SQLAlchemy/sqlalchemy/event/attr.pyi deleted file mode 100644 index f0d04c802b24..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/event/attr.pyi +++ /dev/null @@ -1,85 +0,0 @@ -from typing import Any - -from .. import util - -class RefCollection(util.MemoizedSlots): - ref: Any - -class _empty_collection: - def append(self, element) -> None: ... - def extend(self, other) -> None: ... - def remove(self, element) -> None: ... - def __iter__(self): ... - def clear(self) -> None: ... - -class _ClsLevelDispatch(RefCollection): - name: Any - clsname: Any - arg_names: Any - has_kw: Any - legacy_signatures: Any - def __init__(self, parent_dispatch_cls, fn): ... - def insert(self, event_key, propagate) -> None: ... - def append(self, event_key, propagate) -> None: ... - def update_subclass(self, target) -> None: ... - def remove(self, event_key) -> None: ... - def clear(self) -> None: ... - def for_modify(self, obj): ... - -class _InstanceLevelDispatch(RefCollection): ... - -class _EmptyListener(_InstanceLevelDispatch): - propagate: Any - listeners: Any - parent: Any - parent_listeners: Any - name: Any - def __init__(self, parent, target_cls) -> None: ... - def for_modify(self, obj): ... - exec_once: Any - exec_once_unless_exception: Any - insert: Any - append: Any - remove: Any - clear: Any - def __call__(self, *args, **kw) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __bool__(self): ... - __nonzero__: Any - -class _CompoundListener(_InstanceLevelDispatch): - def exec_once(self, *args, **kw) -> None: ... - def exec_once_unless_exception(self, *args, **kw) -> None: ... - def __call__(self, *args, **kw) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __bool__(self): ... - __nonzero__: Any - -class _ListenerCollection(_CompoundListener): - parent_listeners: Any - parent: Any - name: Any - listeners: Any - propagate: Any - def __init__(self, parent, target_cls) -> None: ... - def for_modify(self, obj): ... - def insert(self, event_key, propagate) -> None: ... - def append(self, event_key, propagate) -> None: ... - def remove(self, event_key) -> None: ... - def clear(self) -> None: ... - -class _JoinedListener(_CompoundListener): - parent: Any - name: Any - local: Any - parent_listeners: Any - def __init__(self, parent, name, local) -> None: ... - @property - def listeners(self): ... - def for_modify(self, obj): ... - def insert(self, event_key, propagate) -> None: ... - def append(self, event_key, propagate) -> None: ... - def remove(self, event_key) -> None: ... - def clear(self) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/event/base.pyi b/stubs/SQLAlchemy/sqlalchemy/event/base.pyi deleted file mode 100644 index 4237aa096102..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/event/base.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Any - -class _UnpickleDispatch: - def __call__(self, _instance_cls): ... - -class _Dispatch: - def __init__(self, parent, instance_cls: Any | None = ...) -> None: ... - def __getattr__(self, name): ... - def __reduce__(self): ... - -class _EventMeta(type): - def __init__(cls, classname, bases, dict_) -> None: ... - -class Events: - dispatch: Any - -class _JoinedDispatcher: - local: Any - parent: Any - def __init__(self, local, parent) -> None: ... - def __getattr__(self, name): ... - -class dispatcher: - dispatch: Any - events: Any - def __init__(self, events) -> None: ... - def __get__(self, obj, cls): ... - -class slots_dispatcher(dispatcher): - def __get__(self, obj, cls): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/event/registry.pyi b/stubs/SQLAlchemy/sqlalchemy/event/registry.pyi deleted file mode 100644 index 54fcc63a98bf..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/event/registry.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -class _EventKey: - target: Any - identifier: Any - fn: Any - fn_key: Any - fn_wrap: Any - dispatch_target: Any - def __init__(self, target, identifier, fn, dispatch_target, _fn_wrap: Any | None = ...) -> None: ... - def with_wrapper(self, fn_wrap): ... - def with_dispatch_target(self, dispatch_target): ... - def listen(self, *args, **kw) -> None: ... - def remove(self) -> None: ... - def contains(self): ... - def base_listen( - self, propagate: bool = ..., insert: bool = ..., named: bool = ..., retval: Any | None = ..., asyncio: bool = ... - ) -> None: ... - def append_to_list(self, owner, list_): ... - def remove_from_list(self, owner, list_) -> None: ... - def prepend_to_list(self, owner, list_): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/events.pyi b/stubs/SQLAlchemy/sqlalchemy/events.pyi deleted file mode 100644 index 8bbbfa58d8d8..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/events.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from .engine.events import ConnectionEvents as ConnectionEvents, DialectEvents as DialectEvents -from .pool.events import PoolEvents as PoolEvents -from .sql.base import SchemaEventTarget as SchemaEventTarget -from .sql.events import DDLEvents as DDLEvents diff --git a/stubs/SQLAlchemy/sqlalchemy/exc.pyi b/stubs/SQLAlchemy/sqlalchemy/exc.pyi deleted file mode 100644 index b8775e9ad799..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/exc.pyi +++ /dev/null @@ -1,139 +0,0 @@ -from typing import Any, ClassVar - -class HasDescriptionCode: - code: str | None - def __init__(self, *arg: Any, code: str | None = ..., **kw: Any) -> None: ... - -class SQLAlchemyError(HasDescriptionCode, Exception): - def __unicode__(self) -> str: ... - -class ArgumentError(SQLAlchemyError): ... - -class ObjectNotExecutableError(ArgumentError): - target: Any - def __init__(self, target) -> None: ... - def __reduce__(self): ... - -class NoSuchModuleError(ArgumentError): ... -class NoForeignKeysError(ArgumentError): ... -class AmbiguousForeignKeysError(ArgumentError): ... - -class CircularDependencyError(SQLAlchemyError): - cycles: Any - edges: Any - def __init__(self, message, cycles, edges, msg: Any | None = ..., code: Any | None = ...) -> None: ... - def __reduce__(self): ... - -class CompileError(SQLAlchemyError): ... - -class UnsupportedCompilationError(CompileError): - code: str - compiler: Any - element_type: Any - message: str | None - def __init__(self, compiler, element_type, message: str | None = ...) -> None: ... - def __reduce__(self): ... - -class IdentifierError(SQLAlchemyError): ... - -class DisconnectionError(SQLAlchemyError): - invalidate_pool: bool - -class InvalidatePoolError(DisconnectionError): - invalidate_pool: bool - -class TimeoutError(SQLAlchemyError): ... -class InvalidRequestError(SQLAlchemyError): ... -class NoInspectionAvailable(InvalidRequestError): ... -class PendingRollbackError(InvalidRequestError): ... -class ResourceClosedError(InvalidRequestError): ... -class NoSuchColumnError(InvalidRequestError, KeyError): ... -class NoResultFound(InvalidRequestError): ... -class MultipleResultsFound(InvalidRequestError): ... -class NoReferenceError(InvalidRequestError): ... - -class AwaitRequired(InvalidRequestError): - code: str - -class MissingGreenlet(InvalidRequestError): - code: str - -class NoReferencedTableError(NoReferenceError): - table_name: Any - def __init__(self, message, tname) -> None: ... - def __reduce__(self): ... - -class NoReferencedColumnError(NoReferenceError): - table_name: Any - column_name: Any - def __init__(self, message, tname, cname) -> None: ... - def __reduce__(self): ... - -class NoSuchTableError(InvalidRequestError): ... -class UnreflectableTableError(InvalidRequestError): ... -class UnboundExecutionError(InvalidRequestError): ... -class DontWrapMixin: ... - -class StatementError(SQLAlchemyError): - statement: Any - params: Any - orig: Any - ismulti: Any - hide_parameters: Any - detail: Any - def __init__( - self, message, statement, params, orig, hide_parameters: bool = ..., code: Any | None = ..., ismulti: Any | None = ... - ) -> None: ... - def add_detail(self, msg) -> None: ... - def __reduce__(self): ... - -class DBAPIError(StatementError): - code: str - @classmethod - def instance( - cls, - statement, - params, - orig, - dbapi_base_err, - hide_parameters: bool = ..., - connection_invalidated: bool = ..., - dialect: Any | None = ..., - ismulti: Any | None = ..., - ): ... - def __reduce__(self): ... - connection_invalidated: Any - def __init__( - self, - statement, - params, - orig, - hide_parameters: bool = ..., - connection_invalidated: bool = ..., - code: Any | None = ..., - ismulti: Any | None = ..., - ) -> None: ... - -class InterfaceError(DBAPIError): ... -class DatabaseError(DBAPIError): ... -class DataError(DatabaseError): ... -class OperationalError(DatabaseError): ... -class IntegrityError(DatabaseError): ... -class InternalError(DatabaseError): ... -class ProgrammingError(DatabaseError): ... -class NotSupportedError(DatabaseError): ... - -class SADeprecationWarning(HasDescriptionCode, DeprecationWarning): - deprecated_since: ClassVar[str | None] - -class Base20DeprecationWarning(SADeprecationWarning): - deprecated_since: ClassVar[str] - -class LegacyAPIWarning(Base20DeprecationWarning): ... -class RemovedIn20Warning(Base20DeprecationWarning): ... -class MovedIn20Warning(RemovedIn20Warning): ... - -class SAPendingDeprecationWarning(PendingDeprecationWarning): - deprecated_since: ClassVar[str | None] - -class SAWarning(HasDescriptionCode, RuntimeWarning): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/associationproxy.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/associationproxy.pyi deleted file mode 100644 index dd2e829043a5..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/associationproxy.pyi +++ /dev/null @@ -1,198 +0,0 @@ -from typing import Any - -from ..orm import interfaces -from ..sql.operators import ColumnOperators -from ..util import memoized_property - -def association_proxy(target_collection, attr, **kw): ... - -ASSOCIATION_PROXY: Any - -class AssociationProxy(interfaces.InspectionAttrInfo): - is_attribute: bool - extension_type: Any - target_collection: Any - value_attr: Any - creator: Any - getset_factory: Any - proxy_factory: Any - proxy_bulk_set: Any - cascade_scalar_deletes: Any - key: Any - info: Any - def __init__( - self, - target_collection, - attr, - creator: Any | None = ..., - getset_factory: Any | None = ..., - proxy_factory: Any | None = ..., - proxy_bulk_set: Any | None = ..., - info: Any | None = ..., - cascade_scalar_deletes: bool = ..., - ) -> None: ... - def __get__(self, obj, class_): ... - def __set__(self, obj, values): ... - def __delete__(self, obj): ... - def for_class(self, class_, obj: Any | None = ...): ... - -class AssociationProxyInstance: - parent: Any - key: Any - owning_class: Any - target_collection: Any - collection_class: Any - target_class: Any - value_attr: Any - def __init__(self, parent, owning_class, target_class, value_attr) -> None: ... - @classmethod - def for_proxy(cls, parent, owning_class, parent_instance): ... - def __clause_element__(self) -> None: ... - @property - def remote_attr(self): ... - @property - def local_attr(self): ... - @property - def attr(self): ... - @memoized_property - def scalar(self): ... - @property - def info(self): ... - def get(self, obj): ... - def set(self, obj, values) -> None: ... - def delete(self, obj) -> None: ... - def any(self, criterion: Any | None = ..., **kwargs): ... - def has(self, criterion: Any | None = ..., **kwargs): ... - -class AmbiguousAssociationProxyInstance(AssociationProxyInstance): - def get(self, obj): ... - def __eq__(self, obj): ... - def __ne__(self, obj): ... - def any(self, criterion: Any | None = ..., **kwargs) -> None: ... - def has(self, criterion: Any | None = ..., **kwargs) -> None: ... - -class ObjectAssociationProxyInstance(AssociationProxyInstance): - def contains(self, obj): ... - def __eq__(self, obj): ... - def __ne__(self, obj): ... - -class ColumnAssociationProxyInstance(ColumnOperators, AssociationProxyInstance): - def __eq__(self, other): ... - def operate(self, op, *other, **kwargs): ... - -class _lazy_collection: - parent: Any - target: Any - def __init__(self, obj, target) -> None: ... - def __call__(self): ... - -class _AssociationCollection: - lazy_collection: Any - creator: Any - getter: Any - setter: Any - parent: Any - def __init__(self, lazy_collection, creator, getter, setter, parent) -> None: ... - col: Any - def __len__(self): ... - def __bool__(self): ... - __nonzero__: Any - -class _AssociationList(_AssociationCollection): - def __getitem__(self, index): ... - def __setitem__(self, index, value) -> None: ... - def __delitem__(self, index) -> None: ... - def __contains__(self, value): ... - def __getslice__(self, start, end): ... - def __setslice__(self, start, end, values) -> None: ... - def __delslice__(self, start, end) -> None: ... - def __iter__(self): ... - def append(self, value) -> None: ... - def count(self, value): ... - def extend(self, values) -> None: ... - def insert(self, index, value) -> None: ... - def pop(self, index: int = ...): ... - def remove(self, value) -> None: ... - def reverse(self) -> None: ... - def sort(self) -> None: ... - def clear(self) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... - def __cmp__(self, other): ... - def __add__(self, iterable): ... - def __radd__(self, iterable): ... - def __mul__(self, n): ... - __rmul__: Any - def __iadd__(self, iterable): ... - def __imul__(self, n): ... - def index(self, item, *args): ... - def copy(self): ... - def __hash__(self): ... - -class _AssociationDict(_AssociationCollection): - def __getitem__(self, key): ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - def __contains__(self, key): ... - def has_key(self, key): ... - def __iter__(self): ... - def clear(self) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... - def __cmp__(self, other): ... - def get(self, key, default: Any | None = ...): ... - def setdefault(self, key, default: Any | None = ...): ... - def keys(self): ... - def items(self): ... - def values(self): ... - def pop(self, key, default=...): ... - def popitem(self): ... - def update(self, *a, **kw) -> None: ... - def copy(self): ... - def __hash__(self): ... - -class _AssociationSet(_AssociationCollection): - def __len__(self): ... - def __bool__(self): ... - __nonzero__: Any - def __contains__(self, value): ... - def __iter__(self): ... - def add(self, value) -> None: ... - def discard(self, value) -> None: ... - def remove(self, value) -> None: ... - def pop(self): ... - def update(self, other) -> None: ... - def __ior__(self, other): ... # type: ignore[misc] - def union(self, other): ... - __or__: Any - def difference(self, other): ... - __sub__: Any - def difference_update(self, other) -> None: ... - def __isub__(self, other): ... # type: ignore[misc] - def intersection(self, other): ... - __and__: Any - def intersection_update(self, other) -> None: ... - def __iand__(self, other): ... # type: ignore[misc] - def symmetric_difference(self, other): ... - __xor__: Any - def symmetric_difference_update(self, other) -> None: ... - def __ixor__(self, other): ... # type: ignore[misc] - def issubset(self, other): ... - def issuperset(self, other): ... - def clear(self) -> None: ... - def copy(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... - def __hash__(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/__init__.pyi deleted file mode 100644 index e065d748f177..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/__init__.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from .engine import ( - AsyncConnection as AsyncConnection, - AsyncEngine as AsyncEngine, - AsyncTransaction as AsyncTransaction, - create_async_engine as create_async_engine, -) -from .events import AsyncConnectionEvents as AsyncConnectionEvents, AsyncSessionEvents as AsyncSessionEvents -from .result import AsyncMappingResult as AsyncMappingResult, AsyncResult as AsyncResult, AsyncScalarResult as AsyncScalarResult -from .scoping import async_scoped_session as async_scoped_session -from .session import ( - AsyncSession as AsyncSession, - AsyncSessionTransaction as AsyncSessionTransaction, - async_object_session as async_object_session, - async_session as async_session, -) diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/base.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/base.pyi deleted file mode 100644 index 8c88946875de..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/base.pyi +++ /dev/null @@ -1,16 +0,0 @@ -import abc - -class ReversibleProxy: ... - -class StartableContext(abc.ABC, metaclass=abc.ABCMeta): - @abc.abstractmethod - async def start(self, is_ctxmanager: bool = ...): ... - def __await__(self): ... - async def __aenter__(self): ... - @abc.abstractmethod - async def __aexit__(self, type_, value, traceback): ... - -class ProxyComparable(ReversibleProxy): - def __hash__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/engine.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/engine.pyi deleted file mode 100644 index 5bb62f98b3fa..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/engine.pyi +++ /dev/null @@ -1,93 +0,0 @@ -from typing import Any - -from .base import ProxyComparable, StartableContext - -def create_async_engine(*arg, **kw): ... - -class AsyncConnectable: ... - -class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable): - engine: Any - sync_engine: Any - sync_connection: Any - def __init__(self, async_engine, sync_connection: Any | None = ...) -> None: ... - async def start(self, is_ctxmanager: bool = ...): ... - @property - def connection(self) -> None: ... - async def get_raw_connection(self): ... - @property - def info(self): ... - def begin(self): ... - def begin_nested(self): ... - async def invalidate(self, exception: Any | None = ...): ... - async def get_isolation_level(self): ... - async def set_isolation_level(self): ... - def in_transaction(self): ... - def in_nested_transaction(self): ... - def get_transaction(self): ... - def get_nested_transaction(self): ... - async def execution_options(self, **opt): ... - async def commit(self) -> None: ... - async def rollback(self) -> None: ... - async def close(self) -> None: ... - async def exec_driver_sql(self, statement, parameters: Any | None = ..., execution_options=...): ... - async def stream(self, statement, parameters: Any | None = ..., execution_options=...): ... - async def execute(self, statement, parameters: Any | None = ..., execution_options=...): ... - async def scalar(self, statement, parameters: Any | None = ..., execution_options=...): ... - async def scalars(self, statement, parameters: Any | None = ..., execution_options=...): ... - async def stream_scalars(self, statement, parameters: Any | None = ..., execution_options=...): ... - async def run_sync(self, fn, *arg, **kw): ... - def __await__(self): ... - async def __aexit__(self, type_, value, traceback) -> None: ... - # proxied from Connection - dialect: Any - @property - def closed(self): ... - @property - def invalidated(self): ... - @property - def default_isolation_level(self): ... - -class AsyncEngine(ProxyComparable, AsyncConnectable): - class _trans_ctx(StartableContext): - conn: Any - def __init__(self, conn) -> None: ... - transaction: Any - async def start(self, is_ctxmanager: bool = ...): ... - async def __aexit__(self, type_, value, traceback) -> None: ... - sync_engine: Any - def __init__(self, sync_engine) -> None: ... - def begin(self): ... - def connect(self): ... - async def raw_connection(self): ... - def execution_options(self, **opt): ... - async def dispose(self): ... - # proxied from Engine - url: Any - pool: Any - dialect: Any - echo: Any - @property - def engine(self): ... - @property - def name(self): ... - @property - def driver(self): ... - def clear_compiled_cache(self) -> None: ... - def update_execution_options(self, **opt) -> None: ... - def get_execution_options(self): ... - -class AsyncTransaction(ProxyComparable, StartableContext): - connection: Any - sync_transaction: Any - nested: Any - def __init__(self, connection, nested: bool = ...) -> None: ... - @property - def is_valid(self): ... - @property - def is_active(self): ... - async def close(self) -> None: ... - async def rollback(self) -> None: ... - async def commit(self) -> None: ... - async def start(self, is_ctxmanager: bool = ...): ... - async def __aexit__(self, type_, value, traceback) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/events.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/events.pyi deleted file mode 100644 index e9a8bf1a5916..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/events.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from ...engine import events as engine_event -from ...orm import events as orm_event - -class AsyncConnectionEvents(engine_event.ConnectionEvents): ... -class AsyncSessionEvents(orm_event.SessionEvents): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/exc.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/exc.pyi deleted file mode 100644 index 56f3b638ab1b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/exc.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from ...exc import InvalidRequestError - -class AsyncMethodRequired(InvalidRequestError): ... -class AsyncContextNotStarted(InvalidRequestError): ... -class AsyncContextAlreadyStarted(InvalidRequestError): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/result.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/result.pyi deleted file mode 100644 index c04258ab192f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/result.pyi +++ /dev/null @@ -1,57 +0,0 @@ -from typing import Any - -from ...engine.result import FilterResult - -class AsyncCommon(FilterResult): - async def close(self) -> None: ... - -class AsyncResult(AsyncCommon): - def __init__(self, real_result) -> None: ... - def keys(self): ... - def unique(self, strategy: Any | None = ...): ... - def columns(self, *col_expressions): ... - async def partitions(self, size: Any | None = ...) -> None: ... - async def fetchone(self): ... - async def fetchmany(self, size: Any | None = ...): ... - async def all(self): ... - def __aiter__(self): ... - async def __anext__(self): ... - async def first(self): ... - async def one_or_none(self): ... - async def scalar_one(self): ... - async def scalar_one_or_none(self): ... - async def one(self): ... - async def scalar(self): ... - async def freeze(self): ... - def merge(self, *others): ... - def scalars(self, index: int = ...): ... - def mappings(self): ... - -class AsyncScalarResult(AsyncCommon): - def __init__(self, real_result, index) -> None: ... - def unique(self, strategy: Any | None = ...): ... - async def partitions(self, size: Any | None = ...) -> None: ... - async def fetchall(self): ... - async def fetchmany(self, size: Any | None = ...): ... - async def all(self): ... - def __aiter__(self): ... - async def __anext__(self): ... - async def first(self): ... - async def one_or_none(self): ... - async def one(self): ... - -class AsyncMappingResult(AsyncCommon): - def __init__(self, result) -> None: ... - def keys(self): ... - def unique(self, strategy: Any | None = ...): ... - def columns(self, *col_expressions): ... - async def partitions(self, size: Any | None = ...) -> None: ... - async def fetchall(self): ... - async def fetchone(self): ... - async def fetchmany(self, size: Any | None = ...): ... - async def all(self): ... - def __aiter__(self): ... - async def __anext__(self): ... - async def first(self): ... - async def one_or_none(self): ... - async def one(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/scoping.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/scoping.pyi deleted file mode 100644 index 90e44bc0de74..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/scoping.pyi +++ /dev/null @@ -1,76 +0,0 @@ -from typing import Any - -from ...orm.scoping import ScopedSessionMixin -from ...util import memoized_property - -class async_scoped_session(ScopedSessionMixin): - session_factory: Any - registry: Any - def __init__(self, session_factory, scopefunc) -> None: ... - async def remove(self) -> None: ... - # proxied from Session - @classmethod - async def close_all(cls): ... - @classmethod - def identity_key(cls, *args, **kwargs): ... - @classmethod - def object_session(cls, instance): ... - bind: Any - identity_map: Any - autoflush: Any - def __contains__(self, instance): ... - def __iter__(self): ... - def add(self, instance, _warn: bool = ...) -> None: ... - def add_all(self, instances) -> None: ... - def begin(self, **kw): ... - def begin_nested(self, **kw): ... - async def close(self): ... - async def commit(self): ... - async def connection(self, **kw): ... - async def delete(self, instance): ... - async def execute( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - def expire(self, instance, attribute_names: Any | None = ...) -> None: ... - def expire_all(self) -> None: ... - def expunge(self, instance) -> None: ... - def expunge_all(self) -> None: ... - async def flush(self, objects: Any | None = ...) -> None: ... - async def get( - self, - entity, - ident, - options: Any | None = ..., - populate_existing: bool = ..., - with_for_update: Any | None = ..., - identity_token: Any | None = ..., - ): ... - def get_bind(self, mapper: Any | None = ..., clause: Any | None = ..., bind: Any | None = ..., **kw): ... - def is_modified(self, instance, include_collections: bool = ...): ... - async def merge(self, instance, load: bool = ..., options: Any | None = ...): ... - async def refresh(self, instance, attribute_names: Any | None = ..., with_for_update: Any | None = ...): ... - async def rollback(self): ... - async def scalar( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def scalars( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def stream( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def stream_scalars( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - @property - def dirty(self): ... - @property - def deleted(self): ... - @property - def new(self): ... - @property - def is_active(self): ... - @property - def no_autoflush(self) -> None: ... - @memoized_property - def info(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/session.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/session.pyi deleted file mode 100644 index 94b3d1bde3ac..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/asyncio/session.pyi +++ /dev/null @@ -1,106 +0,0 @@ -from typing import Any - -from ...util import memoized_property -from .base import ReversibleProxy, StartableContext - -class AsyncSession(ReversibleProxy): - dispatch: Any - bind: Any - binds: Any - sync_session_class: Any - sync_session: Any - def __init__(self, bind: Any | None = ..., binds: Any | None = ..., sync_session_class: Any | None = ..., **kw) -> None: ... - async def refresh(self, instance, attribute_names: Any | None = ..., with_for_update: Any | None = ...): ... - async def run_sync(self, fn, *arg, **kw): ... - async def execute( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def scalar( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def scalars( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def get( - self, - entity, - ident, - options: Any | None = ..., - populate_existing: bool = ..., - with_for_update: Any | None = ..., - identity_token: Any | None = ..., - ): ... - async def stream( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def stream_scalars( - self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw - ): ... - async def delete(self, instance): ... - async def merge(self, instance, load: bool = ..., options: Any | None = ...): ... - async def flush(self, objects: Any | None = ...) -> None: ... - def get_transaction(self): ... - def get_nested_transaction(self): ... - def get_bind(self, mapper: Any | None = ..., clause: Any | None = ..., bind: Any | None = ..., **kw): ... - async def connection(self, **kw): ... - def begin(self, **kw): ... - def begin_nested(self, **kw): ... - async def rollback(self): ... - async def commit(self): ... - async def close(self): ... - @classmethod - async def close_all(cls): ... - async def __aenter__(self): ... - async def __aexit__(self, type_, value, traceback) -> None: ... - # proxied from Session - identity_map: Any - autoflush: Any - @classmethod - def identity_key(cls, *args, **kwargs): ... - @classmethod - def object_session(cls, instance): ... - def __contains__(self, instance): ... - def __iter__(self): ... - def add(self, instance, _warn: bool = ...) -> None: ... - def add_all(self, instances) -> None: ... - def expire(self, instance, attribute_names: Any | None = ...) -> None: ... - def expire_all(self) -> None: ... - def expunge(self, instance) -> None: ... - def expunge_all(self) -> None: ... - def is_modified(self, instance, include_collections: bool = ...): ... - def in_transaction(self): ... - def in_nested_transaction(self): ... - @property - def no_autoflush(self) -> None: ... - @property - def is_active(self): ... - @property - def dirty(self): ... - @property - def deleted(self): ... - @property - def new(self): ... - @memoized_property - def info(self): ... - -class _AsyncSessionContextManager: - async_session: Any - def __init__(self, async_session) -> None: ... - trans: Any - async def __aenter__(self): ... - async def __aexit__(self, type_, value, traceback) -> None: ... - -class AsyncSessionTransaction(ReversibleProxy, StartableContext): - session: Any - nested: Any - sync_transaction: Any - def __init__(self, session, nested: bool = ...) -> None: ... - @property - def is_active(self): ... - async def rollback(self) -> None: ... - async def commit(self) -> None: ... - async def start(self, is_ctxmanager: bool = ...): ... - async def __aexit__(self, type_, value, traceback) -> None: ... - -def async_object_session(instance): ... -def async_session(session): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/automap.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/automap.pyi deleted file mode 100644 index 13b70990366c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/automap.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any - -def classname_for_table(base, tablename, table): ... -def name_for_scalar_relationship(base, local_cls, referred_cls, constraint): ... -def name_for_collection_relationship(base, local_cls, referred_cls, constraint): ... -def generate_relationship(base, direction, return_fn, attrname, local_cls, referred_cls, **kw): ... - -class AutomapBase: - __abstract__: bool - classes: Any - @classmethod - def prepare( - cls, - autoload_with: Any | None = ..., - engine: Any | None = ..., - reflect: bool = ..., - schema: Any | None = ..., - classname_for_table: Any | None = ..., - collection_class: Any | None = ..., - name_for_scalar_relationship: Any | None = ..., - name_for_collection_relationship: Any | None = ..., - generate_relationship: Any | None = ..., - reflection_options=..., - ) -> None: ... - -def automap_base(declarative_base: Any | None = ..., **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/baked.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/baked.pyi deleted file mode 100644 index 664c226aca12..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/baked.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Any - -log: Any - -class Bakery: - cls: Any - cache: Any - def __init__(self, cls_, cache) -> None: ... - def __call__(self, initial_fn, *args): ... - -class BakedQuery: - steps: Any - def __init__(self, bakery, initial_fn, args=...) -> None: ... - @classmethod - def bakery(cls, size: int = ..., _size_alert: Any | None = ...): ... - def __iadd__(self, other): ... - def __add__(self, other): ... - def add_criteria(self, fn, *args): ... - def with_criteria(self, fn, *args): ... - def for_session(self, session): ... - def __call__(self, session): ... - def spoil(self, full: bool = ...): ... - def to_query(self, query_or_session): ... - -class Result: - bq: Any - session: Any - def __init__(self, bq, session) -> None: ... - def params(self, *args, **kw): ... - def with_post_criteria(self, fn): ... - def __iter__(self): ... - def count(self): ... - def scalar(self): ... - def first(self): ... - def one(self): ... - def one_or_none(self): ... - def all(self): ... - def get(self, ident): ... - -def bake_lazy_loaders() -> None: ... -def unbake_lazy_loaders() -> None: ... - -baked_lazyload: Any -baked_lazyload_all: Any -bakery: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/compiler.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/compiler.pyi deleted file mode 100644 index cc2363f1ae59..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/compiler.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -def compiles(class_, *specs): ... -def deregister(class_) -> None: ... - -class _dispatcher: - specs: Any - def __init__(self) -> None: ... - def __call__(self, element, compiler, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/declarative/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/declarative/__init__.pyi deleted file mode 100644 index 7eddf8603c37..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/declarative/__init__.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from ...orm.decl_api import ( - DeclarativeMeta as DeclarativeMeta, - as_declarative as as_declarative, - declarative_base as declarative_base, - declared_attr as declared_attr, - has_inherited_table as has_inherited_table, - synonym_for as synonym_for, -) -from .extensions import ( - AbstractConcreteBase as AbstractConcreteBase, - ConcreteBase as ConcreteBase, - DeferredReflection as DeferredReflection, - instrument_declarative as instrument_declarative, -) - -__all__ = [ - "declarative_base", - "synonym_for", - "has_inherited_table", - "instrument_declarative", - "declared_attr", - "as_declarative", - "ConcreteBase", - "AbstractConcreteBase", - "DeclarativeMeta", - "DeferredReflection", -] diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/declarative/extensions.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/declarative/extensions.pyi deleted file mode 100644 index c4fbf0ff5444..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/declarative/extensions.pyi +++ /dev/null @@ -1,14 +0,0 @@ -def instrument_declarative(cls, cls_registry, metadata) -> None: ... - -class ConcreteBase: - @classmethod - def __declare_first__(cls) -> None: ... - -class AbstractConcreteBase(ConcreteBase): - __no_table__: bool - @classmethod - def __declare_first__(cls) -> None: ... - -class DeferredReflection: - @classmethod - def prepare(cls, engine) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/horizontal_shard.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/horizontal_shard.pyi deleted file mode 100644 index 0ccd17ef2b0d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/horizontal_shard.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Any - -from ..orm.query import Query -from ..orm.session import Session - -class ShardedQuery(Query): - id_chooser: Any - query_chooser: Any - execute_chooser: Any - def __init__(self, *args, **kwargs) -> None: ... - def set_shard(self, shard_id): ... - -class ShardedSession(Session): - shard_chooser: Any - id_chooser: Any - execute_chooser: Any - query_chooser: Any - def __init__( - self, shard_chooser, id_chooser, execute_chooser: Any | None = ..., shards: Any | None = ..., query_cls=..., **kwargs - ): ... - def connection_callable(self, mapper: Any | None = ..., instance: Any | None = ..., shard_id: Any | None = ..., **kwargs): ... - def get_bind(self, mapper: Any | None = ..., shard_id: Any | None = ..., instance: Any | None = ..., clause: Any | None = ..., **kw): ... # type: ignore[override] - def bind_shard(self, shard_id, bind) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/hybrid.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/hybrid.pyi deleted file mode 100644 index 84cc1f5b465b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/hybrid.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any - -from ..orm import interfaces - -HYBRID_METHOD: Any -HYBRID_PROPERTY: Any - -class hybrid_method(interfaces.InspectionAttrInfo): - is_attribute: bool - extension_type: Any - func: Any - def __init__(self, func, expr: Any | None = ...) -> None: ... - def __get__(self, instance, owner): ... - expr: Any - def expression(self, expr): ... - -class hybrid_property(interfaces.InspectionAttrInfo): - is_attribute: bool - extension_type: Any - fget: Any - fset: Any - fdel: Any - expr: Any - custom_comparator: Any - update_expr: Any - def __init__( - self, - fget, - fset: Any | None = ..., - fdel: Any | None = ..., - expr: Any | None = ..., - custom_comparator: Any | None = ..., - update_expr: Any | None = ..., - ) -> None: ... - def __get__(self, instance, owner): ... - def __set__(self, instance, value) -> None: ... - def __delete__(self, instance) -> None: ... - @property - def overrides(self): ... - def getter(self, fget): ... - def setter(self, fset): ... - def deleter(self, fdel): ... - def expression(self, expr): ... - def comparator(self, comparator): ... - def update_expression(self, meth): ... - -class Comparator(interfaces.PropComparator): - property: Any - expression: Any - def __init__(self, expression) -> None: ... - def __clause_element__(self): ... - def adapt_to_entity(self, adapt_to_entity): ... - -_property = property - -class ExprComparator(Comparator): - cls: Any - expression: Any - hybrid: Any - def __init__(self, cls, expression, hybrid) -> None: ... - def __getattr__(self, key): ... - @_property - def info(self): ... - @_property - def property(self): ... - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/indexable.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/indexable.pyi deleted file mode 100644 index 0150ec714b66..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/indexable.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from ..ext.hybrid import hybrid_property - -class index_property(hybrid_property): - attr_name: Any - index: Any - default: Any - datatype: Any - onebased: Any - def __init__(self, attr_name, index, default=..., datatype: Any | None = ..., mutable: bool = ..., onebased: bool = ...): ... - def fget(self, instance): ... - def fset(self, instance, value) -> None: ... - def fdel(self, instance) -> None: ... - def expr(self, model): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/instrumentation.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/instrumentation.pyi deleted file mode 100644 index 6420c913f7dc..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/instrumentation.pyi +++ /dev/null @@ -1,54 +0,0 @@ -from typing import Any - -from ..orm.instrumentation import ClassManager, InstrumentationFactory - -INSTRUMENTATION_MANAGER: str - -def find_native_user_instrumentation_hook(cls): ... - -instrumentation_finders: Any - -class ExtendedInstrumentationRegistry(InstrumentationFactory): - def unregister(self, class_) -> None: ... - def manager_of_class(self, cls): ... - def state_of(self, instance): ... - def dict_of(self, instance): ... - -class InstrumentationManager: - def __init__(self, class_) -> None: ... - def manage(self, class_, manager) -> None: ... - def unregister(self, class_, manager) -> None: ... - def manager_getter(self, class_): ... - def instrument_attribute(self, class_, key, inst) -> None: ... - def post_configure_attribute(self, class_, key, inst) -> None: ... - def install_descriptor(self, class_, key, inst) -> None: ... - def uninstall_descriptor(self, class_, key) -> None: ... - def install_member(self, class_, key, implementation) -> None: ... - def uninstall_member(self, class_, key) -> None: ... - def instrument_collection_class(self, class_, key, collection_class): ... - def get_instance_dict(self, class_, instance): ... - def initialize_instance_dict(self, class_, instance) -> None: ... - def install_state(self, class_, instance, state) -> None: ... - def remove_state(self, class_, instance) -> None: ... - def state_getter(self, class_): ... - def dict_getter(self, class_): ... - -class _ClassInstrumentationAdapter(ClassManager): - def __init__(self, class_, override) -> None: ... - def manage(self) -> None: ... - def unregister(self) -> None: ... - def manager_getter(self): ... - def instrument_attribute(self, key, inst, propagated: bool = ...) -> None: ... - def post_configure_attribute(self, key) -> None: ... - def install_descriptor(self, key, inst) -> None: ... - def uninstall_descriptor(self, key) -> None: ... - def install_member(self, key, implementation) -> None: ... - def uninstall_member(self, key) -> None: ... - def instrument_collection_class(self, key, collection_class): ... - def initialize_collection(self, key, state, factory): ... - def new_instance(self, state: Any | None = ...): ... - def setup_instance(self, instance, state: Any | None = ...): ... - def teardown_instance(self, instance) -> None: ... - def has_state(self, instance): ... - def state_getter(self): ... - def dict_getter(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mutable.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mutable.pyi deleted file mode 100644 index c1e4be44b324..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mutable.pyi +++ /dev/null @@ -1,64 +0,0 @@ -from typing import Any - -class MutableBase: - @classmethod - def coerce(cls, key, value) -> None: ... - -class Mutable(MutableBase): - def changed(self) -> None: ... - @classmethod - def associate_with_attribute(cls, attribute) -> None: ... - @classmethod - def associate_with(cls, sqltype) -> None: ... - @classmethod - def as_mutable(cls, sqltype): ... - -class MutableComposite(MutableBase): - def changed(self) -> None: ... - -class MutableDict(Mutable, dict[Any, Any]): - def __setitem__(self, key, value) -> None: ... - def setdefault(self, key, value): ... - def __delitem__(self, key) -> None: ... - def update(self, *a, **kw) -> None: ... - def pop(self, *arg): ... - def popitem(self): ... - def clear(self) -> None: ... - @classmethod - def coerce(cls, key, value): ... - -class MutableList(Mutable, list[Any]): - def __reduce_ex__(self, proto): ... - def __setitem__(self, index, value) -> None: ... - def __setslice__(self, start, end, value) -> None: ... - def __delitem__(self, index) -> None: ... - def __delslice__(self, start, end) -> None: ... - def pop(self, *arg): ... - def append(self, x) -> None: ... - def extend(self, x) -> None: ... - def __iadd__(self, x): ... # type: ignore[misc] - def insert(self, i, x) -> None: ... - def remove(self, i) -> None: ... - def clear(self) -> None: ... - def sort(self, **kw) -> None: ... - def reverse(self) -> None: ... - @classmethod - def coerce(cls, index, value): ... - -class MutableSet(Mutable, set[Any]): - def update(self, *arg) -> None: ... - def intersection_update(self, *arg) -> None: ... - def difference_update(self, *arg) -> None: ... - def symmetric_difference_update(self, *arg) -> None: ... - def __ior__(self, other): ... # type: ignore[misc] - def __iand__(self, other): ... # type: ignore[misc] - def __ixor__(self, other): ... # type: ignore[misc] - def __isub__(self, other): ... # type: ignore[misc] - def add(self, elem) -> None: ... - def remove(self, elem) -> None: ... - def discard(self, elem) -> None: ... - def pop(self, *arg): ... - def clear(self) -> None: ... - @classmethod - def coerce(cls, index, value): ... - def __reduce_ex__(self, proto): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/apply.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mypy/apply.pyi deleted file mode 100644 index 44aacc72f47f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/apply.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any - -from . import util - -AssignmentStmt = Any # from mypy.nodes -NameExpr = Any # from mypy.nodes -StrExpr = Any # from mypy.nodes -SemanticAnalyzerPluginInterface = Any # from mypy.plugin -ProperType = Any # from mypy.types - -def apply_mypy_mapped_attr( - cls, api: SemanticAnalyzerPluginInterface, item: NameExpr | StrExpr, attributes: list[util.SQLAlchemyAttribute] -) -> None: ... -def re_apply_declarative_assignments( - cls, api: SemanticAnalyzerPluginInterface, attributes: list[util.SQLAlchemyAttribute] -) -> None: ... -def apply_type_to_mapped_statement( - api: SemanticAnalyzerPluginInterface, - stmt: AssignmentStmt, - lvalue: NameExpr, - left_hand_explicit_type: ProperType | None, - python_type_for_type: ProperType | None, -) -> None: ... -def add_additional_orm_attributes( - cls, api: SemanticAnalyzerPluginInterface, attributes: list[util.SQLAlchemyAttribute] -) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/decl_class.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mypy/decl_class.pyi deleted file mode 100644 index 0a417cb58a8f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/decl_class.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from . import util - -SemanticAnalyzerPluginInterface = Any # from mypy.plugin - -def scan_declarative_assignments_and_apply_types( - cls, api: SemanticAnalyzerPluginInterface, is_mixin_scan: bool = ... -) -> list[util.SQLAlchemyAttribute] | None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/infer.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mypy/infer.pyi deleted file mode 100644 index 7faabc366261..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/infer.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from collections.abc import Sequence -from typing import Any - -AssignmentStmt = Any # from mypy.nodes -Expression = Any # from mypy.nodes -RefExpr = Any # from mypy.nodes -TypeInfo = Any # from mypy.nodes -Var = Any # from mypy.nodes -StrExpr = Any # from mypy.nodes -SemanticAnalyzerPluginInterface = Any # from mypy.plugin -ProperType = Any # from mypy.types - -def infer_type_from_right_hand_nameexpr( - api: SemanticAnalyzerPluginInterface, - stmt: AssignmentStmt, - node: Var, - left_hand_explicit_type: ProperType | None, - infer_from_right_side: RefExpr, -) -> ProperType | None: ... -def infer_type_from_left_hand_type_only( - api: SemanticAnalyzerPluginInterface, node: Var, left_hand_explicit_type: ProperType | None -) -> ProperType | None: ... -def extract_python_type_from_typeengine( - api: SemanticAnalyzerPluginInterface, node: TypeInfo, type_args: Sequence[Expression] -) -> ProperType: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/names.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mypy/names.pyi deleted file mode 100644 index f3c4b45c4e48..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/names.pyi +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any - -from ...util import symbol - -ClassDef = Any # from mypy.nodes -Expression = Any # from mypy.nodes -MemberExpr = Any # from mypy.nodes -NameExpr = Any # from mypy.nodes -SymbolNode = Any # from mypy.nodes -TypeInfo = Any # from mypy.nodes -StrExpr = Any # from mypy.nodes -SemanticAnalyzerPluginInterface = Any # from mypy.plugin -UnboundType = Any # from mypy.types - -COLUMN: symbol -RELATIONSHIP: symbol -REGISTRY: symbol -COLUMN_PROPERTY: symbol -TYPEENGINE: symbol -MAPPED: symbol -DECLARATIVE_BASE: symbol -DECLARATIVE_META: symbol -MAPPED_DECORATOR: symbol -SYNONYM_PROPERTY: symbol -COMPOSITE_PROPERTY: symbol -DECLARED_ATTR: symbol -MAPPER_PROPERTY: symbol -AS_DECLARATIVE: symbol -AS_DECLARATIVE_BASE: symbol -DECLARATIVE_MIXIN: symbol -QUERY_EXPRESSION: symbol - -def has_base_type_id(info: TypeInfo, type_id: int) -> bool: ... -def mro_has_id(mro: list[TypeInfo], type_id: int) -> bool: ... -def type_id_for_unbound_type(type_: UnboundType, cls: ClassDef, api: SemanticAnalyzerPluginInterface) -> int | None: ... -def type_id_for_callee(callee: Expression) -> int | None: ... -def type_id_for_named_node(node: NameExpr | MemberExpr | SymbolNode) -> int | None: ... -def type_id_for_fullname(fullname: str) -> int | None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/plugin.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mypy/plugin.pyi deleted file mode 100644 index f89006949f96..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/plugin.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from collections.abc import Callable -from typing import Any, Type as TypingType - -MypyFile = Any # from mypy.nodes -AttributeContext = Any # from mypy.plugin -ClassDefContext = Any # from mypy.plugin -DynamicClassDefContext = Any # from mypy.plugin -Plugin = Any # from mypy.plugin -Type = Any # from mypy.types - -class SQLAlchemyPlugin(Plugin): - def get_dynamic_class_hook(self, fullname: str) -> Callable[[DynamicClassDefContext], None] | None: ... - def get_customize_class_mro_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: ... - def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: ... - def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: ... - def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: ... - def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: ... - def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: ... - -def plugin(version: str) -> TypingType[SQLAlchemyPlugin]: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/util.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/mypy/util.pyi deleted file mode 100644 index 13a6f7e9cd3d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/mypy/util.pyi +++ /dev/null @@ -1,49 +0,0 @@ -from collections.abc import Iterable, Iterator -from typing import Any, Type as TypingType, TypeVar, overload - -CallExpr = Any # from mypy.nodes -Context = Any # from mypy.nodes -Expression = Any # from mypy.nodes -JsonDict = Any # from mypy.nodes -NameExpr = Any # from mypy.nodes -Statement = Any # from mypy.nodes -TypeInfo = Any # from mypy.nodes -AttributeContext = Any # from mypy.plugin -ClassDefContext = Any # from mypy.plugin -DynamicClassDefContext = Any # from mypy.plugin -SemanticAnalyzerPluginInterface = Any # from mypy.plugin -Type = Any # from mypy.types - -_TArgType = TypeVar("_TArgType", bound=CallExpr | NameExpr) - -class SQLAlchemyAttribute: - name: Any - line: Any - column: Any - type: Any - info: Any - def __init__(self, name: str, line: int, column: int, typ: Type | None, info: TypeInfo) -> None: ... - def serialize(self) -> JsonDict: ... - def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None: ... - @classmethod - def deserialize(cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface) -> SQLAlchemyAttribute: ... - -def name_is_dunder(name): ... -def establish_as_sqlalchemy(info: TypeInfo) -> None: ... -def set_is_base(info: TypeInfo) -> None: ... -def get_is_base(info: TypeInfo) -> bool: ... -def has_declarative_base(info: TypeInfo) -> bool: ... -def set_has_table(info: TypeInfo) -> None: ... -def get_has_table(info: TypeInfo) -> bool: ... -def get_mapped_attributes(info: TypeInfo, api: SemanticAnalyzerPluginInterface) -> list[SQLAlchemyAttribute] | None: ... -def set_mapped_attributes(info: TypeInfo, attributes: list[SQLAlchemyAttribute]) -> None: ... -def fail(api: SemanticAnalyzerPluginInterface, msg: str, ctx: Context) -> None: ... -def add_global(ctx: ClassDefContext | DynamicClassDefContext, module: str, symbol_name: str, asname: str) -> None: ... -@overload -def get_callexpr_kwarg(callexpr: CallExpr, name: str, *, expr_types: None = ...) -> CallExpr | NameExpr | None: ... -@overload -def get_callexpr_kwarg(callexpr: CallExpr, name: str, *, expr_types: tuple[TypingType[_TArgType], ...]) -> _TArgType | None: ... -def flatten_typechecking(stmts: Iterable[Statement]) -> Iterator[Statement]: ... -def unbound_to_instance(api: SemanticAnalyzerPluginInterface, typ: Type) -> Type: ... -def info_for_cls(cls, api: SemanticAnalyzerPluginInterface) -> TypeInfo | None: ... -def expr_to_mapped_constructor(expr: Expression) -> CallExpr: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/orderinglist.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/orderinglist.pyi deleted file mode 100644 index a4fe8305f455..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/orderinglist.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -def ordering_list(attr, count_from: Any | None = ..., **kw): ... - -class OrderingList(list[Any]): - ordering_attr: Any - ordering_func: Any - reorder_on_append: Any - def __init__( - self, ordering_attr: Any | None = ..., ordering_func: Any | None = ..., reorder_on_append: bool = ... - ) -> None: ... - def reorder(self) -> None: ... - def append(self, entity) -> None: ... - def insert(self, index, entity) -> None: ... - def remove(self, entity) -> None: ... - def pop(self, index: int = ...): ... # type: ignore[override] - def __setitem__(self, index, entity) -> None: ... - def __delitem__(self, index) -> None: ... - def __setslice__(self, start, end, values) -> None: ... - def __delslice__(self, start, end) -> None: ... - def __reduce__(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/ext/serializer.pyi b/stubs/SQLAlchemy/sqlalchemy/ext/serializer.pyi deleted file mode 100644 index d4a4a2cad506..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/ext/serializer.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -def Serializer(*args, **kw): ... -def Deserializer(file, metadata: Any | None = ..., scoped_session: Any | None = ..., engine: Any | None = ...): ... -def dumps(obj, protocol=...): ... -def loads(data, metadata: Any | None = ..., scoped_session: Any | None = ..., engine: Any | None = ...): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/future/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/future/__init__.pyi deleted file mode 100644 index 00f3a300bcd7..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/future/__init__.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any - -from .engine import Connection as Connection, Engine as Engine, create_engine as create_engine - -select: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/future/engine.pyi b/stubs/SQLAlchemy/sqlalchemy/future/engine.pyi deleted file mode 100644 index 1af2b62ea36c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/future/engine.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Any - -from ..engine import Connection as _LegacyConnection, Engine as _LegacyEngine -from ..engine.base import OptionEngineMixin - -NO_OPTIONS: Any - -def create_engine(*arg, **kw): ... - -class Connection(_LegacyConnection): - def begin(self): ... - def begin_nested(self): ... - def commit(self) -> None: ... - def rollback(self) -> None: ... - def close(self) -> None: ... - def execute(self, statement, parameters: Any | None = ..., execution_options: Any | None = ...): ... # type: ignore[override] - def scalar(self, statement, parameters: Any | None = ..., execution_options: Any | None = ...): ... # type: ignore[override] - -class Engine(_LegacyEngine): - transaction: Any - run_callable: Any - execute: Any - scalar: Any - table_names: Any - has_table: Any - def begin(self) -> None: ... # type: ignore[override] - def connect(self): ... - -class OptionEngine(OptionEngineMixin, Engine): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/inspection.pyi b/stubs/SQLAlchemy/sqlalchemy/inspection.pyi deleted file mode 100644 index d758818c57fc..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/inspection.pyi +++ /dev/null @@ -1 +0,0 @@ -def inspect(subject, raiseerr: bool = ...): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/log.pyi b/stubs/SQLAlchemy/sqlalchemy/log.pyi deleted file mode 100644 index 2f111522845a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/log.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from _typeshed import Self -from logging import Logger -from typing import Any, TypeVar, overload -from typing_extensions import Literal - -_ClsT = TypeVar("_ClsT", bound=type) -_EchoFlag = bool | Literal["debug"] | None - -rootlogger: Any - -def class_logger(cls: _ClsT) -> _ClsT: ... - -class Identified: - logging_name: str | None - -class InstanceLogger: - echo: _EchoFlag - logger: Logger - def __init__(self, echo: _EchoFlag, name: str | None) -> None: ... - def debug(self, msg, *args, **kwargs) -> None: ... - def info(self, msg, *args, **kwargs) -> None: ... - def warning(self, msg, *args, **kwargs) -> None: ... - warn = warning - def error(self, msg, *args, **kwargs) -> None: ... - def exception(self, msg, *args, **kwargs) -> None: ... - def critical(self, msg, *args, **kwargs) -> None: ... - def log(self, level, msg, *args, **kwargs) -> None: ... - def isEnabledFor(self, level): ... - def getEffectiveLevel(self): ... - -def instance_logger(instance: Identified, echoflag: _EchoFlag = ...) -> None: ... - -class echo_property: - __doc__: str - @overload - def __get__(self: Self, instance: None, owner: object) -> Self: ... - @overload - def __get__(self, instance: Identified, owner: object) -> _EchoFlag: ... - def __set__(self, instance: Identified, value: _EchoFlag) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/__init__.pyi deleted file mode 100644 index e4b08eeb92a0..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/__init__.pyi +++ /dev/null @@ -1,125 +0,0 @@ -from typing import Any - -from ..util.langhelpers import public_factory as public_factory -from . import exc as exc, strategy_options as strategy_options -from .attributes import ( - AttributeEvent as AttributeEvent, - InstrumentedAttribute as InstrumentedAttribute, - Mapped as Mapped, - QueryableAttribute as QueryableAttribute, -) -from .context import QueryContext as QueryContext -from .decl_api import ( - DeclarativeMeta as DeclarativeMeta, - as_declarative as as_declarative, - declarative_base as declarative_base, - declarative_mixin as declarative_mixin, - declared_attr as declared_attr, - has_inherited_table as has_inherited_table, - registry as registry, - synonym_for as synonym_for, -) -from .descriptor_props import CompositeProperty as CompositeProperty, SynonymProperty as SynonymProperty -from .dynamic import AppenderQuery as AppenderQuery -from .events import ( - AttributeEvents as AttributeEvents, - InstanceEvents as InstanceEvents, - InstrumentationEvents as InstrumentationEvents, - MapperEvents as MapperEvents, - QueryEvents as QueryEvents, - SessionEvents as SessionEvents, -) -from .identity import IdentityMap as IdentityMap -from .instrumentation import ClassManager as ClassManager -from .interfaces import ( - EXT_CONTINUE as EXT_CONTINUE, - EXT_SKIP as EXT_SKIP, - EXT_STOP as EXT_STOP, - MANYTOMANY as MANYTOMANY, - MANYTOONE as MANYTOONE, - NOT_EXTENSION as NOT_EXTENSION, - ONETOMANY as ONETOMANY, - InspectionAttr as InspectionAttr, - InspectionAttrInfo as InspectionAttrInfo, - MapperProperty as MapperProperty, - PropComparator as PropComparator, - UserDefinedOption as UserDefinedOption, -) -from .loading import merge_frozen_result as merge_frozen_result, merge_result as merge_result -from .mapper import ( - Mapper as Mapper, - class_mapper as class_mapper, - configure_mappers as configure_mappers, - reconstructor as reconstructor, - validates as validates, -) -from .properties import ColumnProperty as ColumnProperty -from .query import AliasOption as AliasOption, FromStatement as FromStatement, Query as Query -from .relationships import RelationshipProperty as RelationshipProperty, foreign as foreign, remote as remote -from .scoping import scoped_session as scoped_session -from .session import ( - ORMExecuteState as ORMExecuteState, - Session as Session, - SessionTransaction as SessionTransaction, - close_all_sessions as close_all_sessions, - make_transient as make_transient, - make_transient_to_detached as make_transient_to_detached, - object_session as object_session, - sessionmaker as sessionmaker, -) -from .state import AttributeState as AttributeState, InstanceState as InstanceState -from .strategy_options import Load as Load -from .unitofwork import UOWTransaction as UOWTransaction -from .util import ( - Bundle as Bundle, - CascadeOptions as CascadeOptions, - LoaderCriteriaOption as LoaderCriteriaOption, - aliased as aliased, - join as join, - object_mapper as object_mapper, - outerjoin as outerjoin, - polymorphic_union as polymorphic_union, - was_deleted as was_deleted, - with_parent as with_parent, - with_polymorphic as with_polymorphic, -) - -def create_session(bind: Any | None = ..., **kwargs): ... - -with_loader_criteria: Any -relationship: Any - -def relation(*arg, **kw): ... -def dynamic_loader(argument, **kw): ... - -column_property: Any -composite: Any - -def backref(name, **kwargs): ... -def deferred(*columns, **kw): ... -def query_expression(default_expr=...): ... - -mapper: Any -synonym: Any - -def clear_mappers() -> None: ... - -joinedload: Any -contains_eager: Any -defer: Any -undefer: Any -undefer_group: Any -with_expression: Any -load_only: Any -lazyload: Any -subqueryload: Any -selectinload: Any -immediateload: Any -noload: Any -raiseload: Any -defaultload: Any -selectin_polymorphic: Any - -def eagerload(*args, **kwargs): ... - -contains_alias: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/attributes.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/attributes.pyi deleted file mode 100644 index bd79f138dadb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/attributes.pyi +++ /dev/null @@ -1,250 +0,0 @@ -from typing import Any, Generic, NamedTuple, TypeVar - -from ..sql import base as sql_base, roles, traversals -from ..util import memoized_property -from . import interfaces - -_T = TypeVar("_T") - -class NoKey(str): ... - -NO_KEY: Any - -class QueryableAttribute( - interfaces._MappedAttribute, - interfaces.InspectionAttr, - interfaces.PropComparator, - traversals.HasCopyInternals, - roles.JoinTargetRole, - roles.OnClauseRole, - sql_base.Immutable, - sql_base.MemoizedHasCacheKey, -): - is_attribute: bool - __visit_name__: str - class_: Any - key: Any - impl: Any - comparator: Any - def __init__( - self, - class_, - key, - parententity, - impl: Any | None = ..., - comparator: Any | None = ..., - of_type: Any | None = ..., - extra_criteria=..., - ) -> None: ... - def __reduce__(self): ... - def get_history(self, instance, passive=...): ... - @memoized_property - def info(self): ... - @memoized_property - def parent(self): ... - @memoized_property - def expression(self): ... - def __clause_element__(self): ... - def adapt_to_entity(self, adapt_to_entity): ... - def of_type(self, entity): ... - def and_(self, *other): ... - def label(self, name): ... - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... - def hasparent(self, state, optimistic: bool = ...): ... - def __getattr__(self, key): ... - @memoized_property - def property(self): ... - -class Mapped(QueryableAttribute, Generic[_T]): - def __get__(self, instance, owner) -> None: ... - def __set__(self, instance, value) -> None: ... - def __delete__(self, instance) -> None: ... - -class InstrumentedAttribute(Mapped[Any]): - inherit_cache: bool - def __set__(self, instance, value) -> None: ... - def __delete__(self, instance) -> None: ... - def __get__(self, instance, owner): ... - -class _HasEntityNamespace(NamedTuple): - entity_namespace: Any - -class HasEntityNamespace(_HasEntityNamespace): - is_mapper: bool - is_aliased_class: bool - -def create_proxied_attribute(descriptor): ... - -OP_REMOVE: Any -OP_APPEND: Any -OP_REPLACE: Any -OP_BULK_REPLACE: Any -OP_MODIFIED: Any - -class AttributeEvent: - impl: Any - op: Any - parent_token: Any - def __init__(self, attribute_impl, op) -> None: ... - def __eq__(self, other): ... - @property - def key(self): ... - def hasparent(self, state): ... - -Event = AttributeEvent - -class AttributeImpl: - class_: Any - key: Any - callable_: Any - dispatch: Any - trackparent: Any - parent_token: Any - send_modified_events: Any - is_equal: Any - accepts_scalar_loader: Any - load_on_unexpire: Any - def __init__( - self, - class_, - key, - callable_, - dispatch, - trackparent: bool = ..., - compare_function: Any | None = ..., - active_history: bool = ..., - parent_token: Any | None = ..., - load_on_unexpire: bool = ..., - send_modified_events: bool = ..., - accepts_scalar_loader: Any | None = ..., - **kwargs, - ) -> None: ... - active_history: Any - def hasparent(self, state, optimistic: bool = ...): ... - def sethasparent(self, state, parent_state, value) -> None: ... - def get_history(self, state, dict_, passive=...) -> None: ... - def get_all_pending(self, state, dict_, passive=...) -> None: ... - def get(self, state, dict_, passive=...): ... - def append(self, state, dict_, value, initiator, passive=...) -> None: ... - def remove(self, state, dict_, value, initiator, passive=...) -> None: ... - def pop(self, state, dict_, value, initiator, passive=...) -> None: ... - def set(self, state, dict_, value, initiator, passive=..., check_old: Any | None = ..., pop: bool = ...) -> None: ... - def get_committed_value(self, state, dict_, passive=...): ... - def set_committed_value(self, state, dict_, value): ... - -class ScalarAttributeImpl(AttributeImpl): - default_accepts_scalar_loader: bool - uses_objects: bool - supports_population: bool - collection: bool - dynamic: bool - def __init__(self, *arg, **kw) -> None: ... - def delete(self, state, dict_) -> None: ... - def get_history(self, state, dict_, passive=...): ... - def set(self, state, dict_, value, initiator, passive=..., check_old: Any | None = ..., pop: bool = ...) -> None: ... - def fire_replace_event(self, state, dict_, value, previous, initiator): ... - def fire_remove_event(self, state, dict_, value, initiator) -> None: ... - @property - def type(self) -> None: ... - -class ScalarObjectAttributeImpl(ScalarAttributeImpl): - default_accepts_scalar_loader: bool - uses_objects: bool - supports_population: bool - collection: bool - def delete(self, state, dict_) -> None: ... - def get_history(self, state, dict_, passive=...): ... - def get_all_pending(self, state, dict_, passive=...): ... - def set(self, state, dict_, value, initiator, passive=..., check_old: Any | None = ..., pop: bool = ...) -> None: ... - def fire_remove_event(self, state, dict_, value, initiator) -> None: ... - def fire_replace_event(self, state, dict_, value, previous, initiator): ... - -class CollectionAttributeImpl(AttributeImpl): - default_accepts_scalar_loader: bool - uses_objects: bool - supports_population: bool - collection: bool - dynamic: bool - copy: Any - collection_factory: Any - def __init__( - self, - class_, - key, - callable_, - dispatch, - typecallable: Any | None = ..., - trackparent: bool = ..., - copy_function: Any | None = ..., - compare_function: Any | None = ..., - **kwargs, - ) -> None: ... - def get_history(self, state, dict_, passive=...): ... - def get_all_pending(self, state, dict_, passive=...): ... - def fire_append_event(self, state, dict_, value, initiator): ... - def fire_append_wo_mutation_event(self, state, dict_, value, initiator): ... - def fire_pre_remove_event(self, state, dict_, initiator) -> None: ... - def fire_remove_event(self, state, dict_, value, initiator) -> None: ... - def delete(self, state, dict_) -> None: ... - def append(self, state, dict_, value, initiator, passive=...) -> None: ... - def remove(self, state, dict_, value, initiator, passive=...) -> None: ... - def pop(self, state, dict_, value, initiator, passive=...) -> None: ... - def set( - self, - state, - dict_, - value, - initiator: Any | None = ..., - passive=..., - check_old: Any | None = ..., - pop: bool = ..., - _adapt: bool = ..., - ) -> None: ... - def set_committed_value(self, state, dict_, value): ... - def get_collection(self, state, dict_, user_data: Any | None = ..., passive=...): ... - -def backref_listeners(attribute, key, uselist): ... - -class History: - def __bool__(self): ... - __nonzero__: Any - def empty(self): ... - def sum(self): ... - def non_deleted(self): ... - def non_added(self): ... - def has_changes(self): ... - def as_state(self): ... - @classmethod - def from_scalar_attribute(cls, attribute, state, current): ... - @classmethod - def from_object_attribute(cls, attribute, state, current, original=...): ... - @classmethod - def from_collection(cls, attribute, state, current): ... - -HISTORY_BLANK: Any - -def get_history(obj, key, passive=...): ... -def get_state_history(state, key, passive=...): ... -def has_parent(cls, obj, key, optimistic: bool = ...): ... -def register_attribute(class_, key, **kw): ... -def register_attribute_impl( - class_, - key, - uselist: bool = ..., - callable_: Any | None = ..., - useobject: bool = ..., - impl_class: Any | None = ..., - backref: Any | None = ..., - **kw, -): ... -def register_descriptor(class_, key, comparator: Any | None = ..., parententity: Any | None = ..., doc: Any | None = ...): ... -def unregister_attribute(class_, key) -> None: ... -def init_collection(obj, key): ... -def init_state_collection(state, dict_, key): ... -def set_committed_value(instance, key, value) -> None: ... -def set_attribute(instance, key, value, initiator: Any | None = ...) -> None: ... -def get_attribute(instance, key): ... -def del_attribute(instance, key) -> None: ... -def flag_modified(instance, key) -> None: ... -def flag_dirty(instance) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/base.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/base.pyi deleted file mode 100644 index 4d247f53c726..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/base.pyi +++ /dev/null @@ -1,75 +0,0 @@ -from typing import Any - -from ..util import memoized_property - -PASSIVE_NO_RESULT: Any -PASSIVE_CLASS_MISMATCH: Any -ATTR_WAS_SET: Any -ATTR_EMPTY: Any -NO_VALUE: Any -NEVER_SET: Any -NO_CHANGE: Any -CALLABLES_OK: Any -SQL_OK: Any -RELATED_OBJECT_OK: Any -INIT_OK: Any -NON_PERSISTENT_OK: Any -LOAD_AGAINST_COMMITTED: Any -NO_AUTOFLUSH: Any -NO_RAISE: Any -DEFERRED_HISTORY_LOAD: Any -PASSIVE_OFF: Any -PASSIVE_RETURN_NO_VALUE: Any -PASSIVE_NO_INITIALIZE: Any -PASSIVE_NO_FETCH: Any -PASSIVE_NO_FETCH_RELATED: Any -PASSIVE_ONLY_PERSISTENT: Any -DEFAULT_MANAGER_ATTR: str -DEFAULT_STATE_ATTR: str -EXT_CONTINUE: Any -EXT_STOP: Any -EXT_SKIP: Any -ONETOMANY: Any -MANYTOONE: Any -MANYTOMANY: Any -NOT_EXTENSION: Any - -_never_set: frozenset[Any] -_none_set: frozenset[Any] - -def manager_of_class(cls): ... - -instance_state: Any -instance_dict: Any - -def instance_str(instance): ... -def state_str(state): ... -def state_class_str(state): ... -def attribute_str(instance, attribute): ... -def state_attribute_str(state, attribute): ... -def object_mapper(instance): ... -def object_state(instance): ... -def _class_to_mapper(class_or_mapper): ... -def _mapper_or_none(entity): ... -def _is_mapped_class(entity): ... - -_state_mapper: Any - -def class_mapper(class_, configure: bool = ...): ... - -class InspectionAttr: - is_selectable: bool - is_aliased_class: bool - is_instance: bool - is_mapper: bool - is_bundle: bool - is_property: bool - is_attribute: bool - is_clause_element: bool - extension_type: Any - -class InspectionAttrInfo(InspectionAttr): - @memoized_property - def info(self): ... - -class _MappedAttribute: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/clsregistry.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/clsregistry.pyi deleted file mode 100644 index 585189669aa2..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/clsregistry.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any - -def add_class(classname, cls, decl_class_registry) -> None: ... -def remove_class(classname, cls, decl_class_registry) -> None: ... - -class _MultipleClassMarker: - on_remove: Any - contents: Any - def __init__(self, classes, on_remove: Any | None = ...) -> None: ... - def remove_item(self, cls) -> None: ... - def __iter__(self): ... - def attempt_get(self, path, key): ... - def add_item(self, item) -> None: ... - -class _ModuleMarker: - parent: Any - name: Any - contents: Any - mod_ns: Any - path: Any - def __init__(self, name, parent) -> None: ... - def __contains__(self, name): ... - def __getitem__(self, name): ... - def resolve_attr(self, key): ... - def get_module(self, name): ... - def add_class(self, name, cls): ... - def remove_class(self, name, cls) -> None: ... - -class _ModNS: - def __init__(self, parent) -> None: ... - def __getattr__(self, key): ... - -class _GetColumns: - cls: Any - def __init__(self, cls) -> None: ... - def __getattr__(self, key): ... - -class _GetTable: - key: Any - metadata: Any - def __init__(self, key, metadata) -> None: ... - def __getattr__(self, key): ... - -class _class_resolver: - cls: Any - prop: Any - arg: Any - fallback: Any - favor_tables: Any - def __init__(self, cls, prop, fallback, arg, favor_tables: bool = ...) -> None: ... - def __call__(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/collections.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/collections.pyi deleted file mode 100644 index fd59745d0ecb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/collections.pyi +++ /dev/null @@ -1,91 +0,0 @@ -from typing import Any - -class _PlainColumnGetter: - cols: Any - composite: Any - def __init__(self, cols) -> None: ... - def __reduce__(self): ... - def __call__(self, value): ... - -class _SerializableColumnGetter: - colkeys: Any - composite: Any - def __init__(self, colkeys) -> None: ... - def __reduce__(self): ... - def __call__(self, value): ... - -class _SerializableColumnGetterV2(_PlainColumnGetter): - colkeys: Any - composite: Any - def __init__(self, colkeys) -> None: ... - def __reduce__(self): ... - -def column_mapped_collection(mapping_spec): ... - -class _SerializableAttrGetter: - name: Any - getter: Any - def __init__(self, name) -> None: ... - def __call__(self, target): ... - def __reduce__(self): ... - -def attribute_mapped_collection(attr_name): ... -def mapped_collection(keyfunc): ... - -class collection: - @staticmethod - def appender(fn): ... - @staticmethod - def remover(fn): ... - @staticmethod - def iterator(fn): ... - @staticmethod - def internally_instrumented(fn): ... - @staticmethod - def converter(fn): ... - @staticmethod - def adds(arg): ... - @staticmethod - def replaces(arg): ... - @staticmethod - def removes(arg): ... - @staticmethod - def removes_return(): ... - -collection_adapter: Any - -class CollectionAdapter: - attr: Any - owner_state: Any - invalidated: bool - empty: bool - def __init__(self, attr, owner_state, data) -> None: ... - @property - def data(self): ... - def bulk_appender(self): ... - def append_with_event(self, item, initiator: Any | None = ...) -> None: ... - def append_without_event(self, item) -> None: ... - def append_multiple_without_event(self, items) -> None: ... - def bulk_remover(self): ... - def remove_with_event(self, item, initiator: Any | None = ...) -> None: ... - def remove_without_event(self, item) -> None: ... - def clear_with_event(self, initiator: Any | None = ...) -> None: ... - def clear_without_event(self) -> None: ... - def __iter__(self): ... - def __len__(self): ... - def __bool__(self): ... - __nonzero__: Any - def fire_append_wo_mutation_event(self, item, initiator: Any | None = ...): ... - def fire_append_event(self, item, initiator: Any | None = ...): ... - def fire_remove_event(self, item, initiator: Any | None = ...) -> None: ... - def fire_pre_remove_event(self, initiator: Any | None = ...) -> None: ... - -class InstrumentedList(list[Any]): ... -class InstrumentedSet(set[Any]): ... -class InstrumentedDict(dict[Any, Any]): ... - -class MappedCollection(dict[Any, Any]): - keyfunc: Any - def __init__(self, keyfunc) -> None: ... - def set(self, value, _sa_initiator: Any | None = ...) -> None: ... - def remove(self, value, _sa_initiator: Any | None = ...) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/context.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/context.pyi deleted file mode 100644 index bc123f007e77..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/context.pyi +++ /dev/null @@ -1,189 +0,0 @@ -from typing import Any - -from ..sql.base import CacheableOptions, CompileState, Options -from ..sql.selectable import SelectState - -LABEL_STYLE_LEGACY_ORM: Any - -class QueryContext: - class default_load_options(Options): ... - load_options: Any - execution_options: Any - bind_arguments: Any - compile_state: Any - query: Any - session: Any - loaders_require_buffering: bool - loaders_require_uniquing: bool - params: Any - create_eager_joins: Any - propagated_loader_options: Any - attributes: Any - runid: Any - partials: Any - post_load_paths: Any - autoflush: Any - populate_existing: Any - invoke_all_eagers: Any - version_check: Any - refresh_state: Any - yield_per: Any - identity_token: Any - def __init__( - self, - compile_state, - statement, - params, - session, - load_options, - execution_options: Any | None = ..., - bind_arguments: Any | None = ..., - ) -> None: ... - -class ORMCompileState(CompileState): - class default_compile_options(CacheableOptions): ... - current_path: Any - def __init__(self, *arg, **kw) -> None: ... - @classmethod - def create_for_statement(cls, statement_container, compiler, **kw) -> None: ... # type: ignore[override] - @classmethod - def get_column_descriptions(cls, statement): ... - @classmethod - def orm_pre_session_exec(cls, session, statement, params, execution_options, bind_arguments, is_reentrant_invoke): ... - @classmethod - def orm_setup_cursor_result(cls, session, statement, params, execution_options, bind_arguments, result): ... - -class ORMFromStatementCompileState(ORMCompileState): - multi_row_eager_loaders: bool - compound_eager_adapter: Any - extra_criteria_entities: Any - eager_joins: Any - use_legacy_query_style: Any - statement_container: Any - requested_statement: Any - dml_table: Any - compile_options: Any - statement: Any - current_path: Any - attributes: Any - global_attributes: Any - primary_columns: Any - secondary_columns: Any - dedupe_columns: Any - create_eager_joins: Any - order_by: Any - @classmethod - def create_for_statement(cls, statement_container, compiler, **kw): ... - -class ORMSelectCompileState(ORMCompileState, SelectState): - multi_row_eager_loaders: bool - compound_eager_adapter: Any - correlate: Any - correlate_except: Any - global_attributes: Any - select_statement: Any - for_statement: Any - use_legacy_query_style: Any - compile_options: Any - label_style: Any - current_path: Any - eager_order_by: Any - attributes: Any - primary_columns: Any - secondary_columns: Any - dedupe_columns: Any - eager_joins: Any - extra_criteria_entities: Any - create_eager_joins: Any - from_clauses: Any - @classmethod - def create_for_statement(cls, statement, compiler, **kw): ... - @classmethod - def determine_last_joined_entity(cls, statement): ... - @classmethod - def all_selected_columns(cls, statement) -> None: ... - @classmethod - def get_columns_clause_froms(cls, statement): ... - @classmethod - def from_statement(cls, statement, from_statement): ... - -class _QueryEntity: - use_id_for_hash: bool - @classmethod - def to_compile_state(cls, compile_state, entities, entities_collection, is_current_entities): ... - -class _MapperEntity(_QueryEntity): - expr: Any - mapper: Any - entity_zero: Any - is_aliased_class: Any - path: Any - selectable: Any - def __init__(self, compile_state, entity, entities_collection, is_current_entities) -> None: ... - supports_single_entity: bool - use_id_for_hash: bool - @property - def type(self): ... - @property - def entity_zero_or_selectable(self): ... - def corresponds_to(self, entity): ... - def row_processor(self, context, result): ... - def setup_compile_state(self, compile_state) -> None: ... - -class _BundleEntity(_QueryEntity): - bundle: Any - expr: Any - type: Any - supports_single_entity: Any - def __init__( - self, compile_state, expr, entities_collection, setup_entities: bool = ..., parent_bundle: Any | None = ... - ) -> None: ... - @property - def mapper(self): ... - @property - def entity_zero(self): ... - def corresponds_to(self, entity): ... - @property - def entity_zero_or_selectable(self): ... - def setup_compile_state(self, compile_state) -> None: ... - def row_processor(self, context, result): ... - -class _ColumnEntity(_QueryEntity): - raw_column_index: Any - translate_raw_column: Any - @property - def type(self): ... - def row_processor(self, context, result): ... - -class _RawColumnEntity(_ColumnEntity): - entity_zero: Any - mapper: Any - supports_single_entity: bool - expr: Any - raw_column_index: Any - translate_raw_column: Any - column: Any - entity_zero_or_selectable: Any - def __init__(self, compile_state, column, entities_collection, raw_column_index, parent_bundle: Any | None = ...) -> None: ... - def corresponds_to(self, entity): ... - def setup_compile_state(self, compile_state) -> None: ... - -class _ORMColumnEntity(_ColumnEntity): - supports_single_entity: bool - expr: Any - translate_raw_column: bool - raw_column_index: Any - entity_zero_or_selectable: Any - entity_zero: Any - mapper: Any - column: Any - def __init__( - self, compile_state, column, entities_collection, parententity, raw_column_index, parent_bundle: Any | None = ... - ) -> None: ... - def corresponds_to(self, entity): ... - def setup_compile_state(self, compile_state) -> None: ... - -class _IdentityTokenEntity(_ORMColumnEntity): - translate_raw_column: bool - def setup_compile_state(self, compile_state) -> None: ... - def row_processor(self, context, result): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/decl_api.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/decl_api.pyi deleted file mode 100644 index 482f4d3fca53..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/decl_api.pyi +++ /dev/null @@ -1,128 +0,0 @@ -from collections.abc import Callable -from typing import Any, ClassVar, TypeVar, overload - -from ..engine.interfaces import Connectable -from ..sql.schema import MetaData -from ..util import hybridproperty -from . import interfaces - -_ClsT = TypeVar("_ClsT", bound=type[Any]) -_DeclT = TypeVar("_DeclT", bound=type[_DeclarativeBase]) - -# Dynamic class as created by registry.generate_base() via DeclarativeMeta -# or another metaclass. This class does not exist at runtime. -class _DeclarativeBase(Any): # super classes are dynamic - registry: ClassVar[registry] - metadata: ClassVar[MetaData] - __abstract__: ClassVar[bool] - # not always existing: - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - __mapper_cls__: ClassVar[Any] - __class_getitem__: ClassVar[Any] - -# Meta class (or function) that creates a _DeclarativeBase class. -_DeclarativeBaseMeta = Callable[[str, tuple[type[Any], ...], dict[str, Any]], _DeclT] - -def has_inherited_table(cls: type[Any]) -> bool: ... - -class DeclarativeMeta(type): - def __init__(cls, classname: str, bases: tuple[type[Any], ...], dict_: dict[str, Any], **kw: object) -> None: ... - def __setattr__(cls, key: str, value: Any) -> None: ... - def __delattr__(cls, key: str) -> None: ... - -def synonym_for(name, map_column: bool = ...): ... - -class declared_attr(interfaces._MappedAttribute, property): - def __init__(self, fget, cascading: bool = ...) -> None: ... - def __get__(self, self_, cls): ... - @hybridproperty - def cascading(self): ... - -class _stateful_declared_attr(declared_attr): - kw: Any - def __init__(self, **kw) -> None: ... - def __call__(self, fn): ... - -def declarative_mixin(cls: _ClsT) -> _ClsT: ... -@overload -def declarative_base( - bind: Connectable | None = ..., - metadata: MetaData | None = ..., - mapper: Any | None = ..., - cls: type[Any] | tuple[type[Any], ...] = ..., - name: str = ..., - constructor: Callable[..., None] = ..., - class_registry: dict[str, type[Any]] | None = ..., -) -> type[_DeclarativeBase]: ... -@overload -def declarative_base( - bind: Connectable | None = ..., - metadata: MetaData | None = ..., - mapper: Any | None = ..., - cls: type[Any] | tuple[type[Any], ...] = ..., - name: str = ..., - constructor: Callable[..., None] = ..., - class_registry: dict[str, type[Any]] | None = ..., - *, - metaclass: _DeclarativeBaseMeta[_DeclT], -) -> _DeclT: ... -@overload -def declarative_base( - bind: Connectable | None, - metadata: MetaData | None, - mapper: Any | None, - cls: type[Any] | tuple[type[Any], ...], - name: str, - constructor: Callable[..., None], - class_registry: dict[str, type[Any]] | None, - metaclass: _DeclarativeBaseMeta[_DeclT], -) -> _DeclT: ... - -class registry: - metadata: MetaData - constructor: Callable[..., None] - def __init__( - self, - metadata: MetaData | None = ..., - class_registry: dict[str, type[Any]] | None = ..., - constructor: Callable[..., None] = ..., - _bind: Connectable | None = ..., - ) -> None: ... - @property - def mappers(self) -> frozenset[Any]: ... - def configure(self, cascade: bool = ...) -> None: ... - def dispose(self, cascade: bool = ...) -> None: ... - @overload - def generate_base( - self, mapper: Any | None = ..., cls: type[Any] | tuple[type[Any], ...] = ..., name: str = ... - ) -> type[_DeclarativeBase]: ... - @overload - def generate_base( - self, - mapper: Any | None = ..., - cls: type[Any] | tuple[type[Any], ...] = ..., - name: str = ..., - *, - metaclass: _DeclarativeBaseMeta[_DeclT], - ) -> _DeclT: ... - @overload - def generate_base( - self, mapper: Any | None, cls: type[Any] | tuple[type[Any], ...], name: str, metaclass: _DeclarativeBaseMeta[_DeclT] - ) -> type[_DeclarativeBase]: ... - def mapped(self, cls: _ClsT) -> _ClsT: ... - # Return type of the callable is a _DeclarativeBase class with the passed in class as base. - # This could be better approximated with Intersection[PassedInClass, _DeclarativeBase]. - def as_declarative_base( - self, *, mapper: Any | None = ..., metaclass: _DeclarativeBaseMeta[_DeclT] = ... - ) -> Callable[[_ClsT], _ClsT | _DeclT | Any]: ... - def map_declaratively(self, cls): ... - def map_imperatively(self, class_, local_table: Any | None = ..., **kw): ... - -def as_declarative( - *, - bind: Connectable | None = ..., - metadata: MetaData | None = ..., - class_registry: dict[str, type[Any]] | None = ..., - mapper: Any | None = ..., - metaclass: _DeclarativeBaseMeta[_DeclT] = ..., -) -> Callable[[_ClsT], _ClsT | _DeclT | Any]: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/decl_base.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/decl_base.pyi deleted file mode 100644 index 9d5dbf1c0723..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/decl_base.pyi +++ /dev/null @@ -1,47 +0,0 @@ -from typing import Any - -class _MapperConfig: - @classmethod - def setup_mapping(cls, registry, cls_, dict_, table, mapper_kw): ... - cls: Any - classname: Any - properties: Any - declared_attr_reg: Any - def __init__(self, registry, cls_, mapper_kw) -> None: ... - def set_cls_attribute(self, attrname, value): ... - -class _ImperativeMapperConfig(_MapperConfig): - dict_: Any - local_table: Any - inherits: Any - def __init__(self, registry, cls_, table, mapper_kw) -> None: ... - def map(self, mapper_kw=...): ... - -class _ClassScanMapperConfig(_MapperConfig): - dict_: Any - local_table: Any - persist_selectable: Any - declared_columns: Any - column_copies: Any - table_args: Any - tablename: Any - mapper_args: Any - mapper_args_fn: Any - inherits: Any - def __init__(self, registry, cls_, dict_, table, mapper_kw) -> None: ... - def map(self, mapper_kw=...): ... - -class _DeferredMapperConfig(_ClassScanMapperConfig): - @property - def cls(self): ... - @cls.setter - def cls(self, class_) -> None: ... - @classmethod - def has_cls(cls, class_): ... - @classmethod - def raise_unmapped_for_cls(cls, class_) -> None: ... - @classmethod - def config_for_cls(cls, class_): ... - @classmethod - def classes_for_base(cls, base_cls, sort: bool = ...): ... - def map(self, mapper_kw=...): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/dependency.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/dependency.pyi deleted file mode 100644 index 8fe92087dc7e..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/dependency.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from typing import Any - -class DependencyProcessor: - prop: Any - cascade: Any - mapper: Any - parent: Any - secondary: Any - direction: Any - post_update: Any - passive_deletes: Any - passive_updates: Any - enable_typechecks: Any - sort_key: Any - key: Any - def __init__(self, prop) -> None: ... - @classmethod - def from_relationship(cls, prop): ... - def hasparent(self, state): ... - def per_property_preprocessors(self, uow) -> None: ... - def per_property_flush_actions(self, uow) -> None: ... - def per_state_flush_actions(self, uow, states, isdelete) -> None: ... - def presort_deletes(self, uowcommit, states): ... - def presort_saves(self, uowcommit, states): ... - def process_deletes(self, uowcommit, states) -> None: ... - def process_saves(self, uowcommit, states) -> None: ... - def prop_has_changes(self, uowcommit, states, isdelete): ... - -class OneToManyDP(DependencyProcessor): - def per_property_dependencies( - self, uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete - ) -> None: ... - def per_state_dependencies( - self, uow, save_parent, delete_parent, child_action, after_save, before_delete, isdelete, childisdelete - ) -> None: ... - def presort_deletes(self, uowcommit, states) -> None: ... - def presort_saves(self, uowcommit, states) -> None: ... - def process_deletes(self, uowcommit, states) -> None: ... - def process_saves(self, uowcommit, states) -> None: ... - -class ManyToOneDP(DependencyProcessor): - def __init__(self, prop) -> None: ... - def per_property_dependencies( - self, uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete - ) -> None: ... - def per_state_dependencies( - self, uow, save_parent, delete_parent, child_action, after_save, before_delete, isdelete, childisdelete - ) -> None: ... - def presort_deletes(self, uowcommit, states) -> None: ... - def presort_saves(self, uowcommit, states) -> None: ... - def process_deletes(self, uowcommit, states) -> None: ... - def process_saves(self, uowcommit, states) -> None: ... - -class DetectKeySwitch(DependencyProcessor): - def per_property_preprocessors(self, uow) -> None: ... - def per_property_flush_actions(self, uow) -> None: ... - def per_state_flush_actions(self, uow, states, isdelete) -> None: ... - def presort_deletes(self, uowcommit, states) -> None: ... - def presort_saves(self, uow, states) -> None: ... - def prop_has_changes(self, uow, states, isdelete): ... - def process_deletes(self, uowcommit, states) -> None: ... - def process_saves(self, uowcommit, states) -> None: ... - -class ManyToManyDP(DependencyProcessor): - def per_property_dependencies( - self, uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete - ) -> None: ... - def per_state_dependencies( - self, uow, save_parent, delete_parent, child_action, after_save, before_delete, isdelete, childisdelete - ) -> None: ... - def presort_deletes(self, uowcommit, states) -> None: ... - def presort_saves(self, uowcommit, states) -> None: ... - def process_deletes(self, uowcommit, states) -> None: ... - def process_saves(self, uowcommit, states) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/descriptor_props.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/descriptor_props.pyi deleted file mode 100644 index 8b5db617008b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/descriptor_props.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Any - -from ..util import memoized_property -from . import util as orm_util -from .interfaces import MapperProperty, PropComparator - -class DescriptorProperty(MapperProperty): - doc: Any - uses_objects: bool - key: Any - descriptor: Any - def instrument_class(self, mapper): ... - -class CompositeProperty(DescriptorProperty): - attrs: Any - composite_class: Any - active_history: Any - deferred: Any - group: Any - comparator_factory: Any - info: Any - def __init__(self, class_, *attrs, **kwargs) -> None: ... - def instrument_class(self, mapper) -> None: ... - def do_init(self) -> None: ... - @memoized_property - def props(self): ... - @property - def columns(self): ... - def get_history(self, state, dict_, passive=...): ... - class CompositeBundle(orm_util.Bundle): - property: Any - def __init__(self, property_, expr) -> None: ... - def create_row_processor(self, query, procs, labels): ... - class Comparator(PropComparator): - __hash__: Any - @memoized_property - def clauses(self): ... - def __clause_element__(self): ... - @memoized_property - def expression(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - -class ConcreteInheritedProperty(DescriptorProperty): - descriptor: Any - def __init__(self): ... - -class SynonymProperty(DescriptorProperty): - name: Any - map_column: Any - descriptor: Any - comparator_factory: Any - doc: Any - info: Any - def __init__( - self, - name, - map_column: Any | None = ..., - descriptor: Any | None = ..., - comparator_factory: Any | None = ..., - doc: Any | None = ..., - info: Any | None = ..., - ) -> None: ... - @property - def uses_objects(self): ... - def get_history(self, *arg, **kw): ... - parent: Any - def set_parent(self, parent, init) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/dynamic.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/dynamic.pyi deleted file mode 100644 index e730ae41bec3..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/dynamic.pyi +++ /dev/null @@ -1,82 +0,0 @@ -from typing import Any - -from . import attributes, strategies -from .query import Query - -class DynaLoader(strategies.AbstractRelationshipLoader): - logger: Any - is_class_level: bool - def init_class_attribute(self, mapper) -> None: ... - -class DynamicAttributeImpl(attributes.AttributeImpl): - uses_objects: bool - default_accepts_scalar_loader: bool - supports_population: bool - collection: bool - dynamic: bool - order_by: Any - target_mapper: Any - query_class: Any - def __init__( - self, class_, key, typecallable, dispatch, target_mapper, order_by, query_class: Any | None = ..., **kw - ) -> None: ... - def get(self, state, dict_, passive=...): ... - def get_collection(self, state, dict_, user_data: Any | None = ..., passive=...): ... - def fire_append_event(self, state, dict_, value, initiator, collection_history: Any | None = ...) -> None: ... - def fire_remove_event(self, state, dict_, value, initiator, collection_history: Any | None = ...) -> None: ... - def set( - self, - state, - dict_, - value, - initiator: Any | None = ..., - passive=..., - check_old: Any | None = ..., - pop: bool = ..., - _adapt: bool = ..., - ) -> None: ... - def delete(self, *args, **kwargs) -> None: ... - def set_committed_value(self, state, dict_, value) -> None: ... - def get_history(self, state, dict_, passive=...): ... - def get_all_pending(self, state, dict_, passive=...): ... - def append(self, state, dict_, value, initiator, passive=...) -> None: ... - def remove(self, state, dict_, value, initiator, passive=...) -> None: ... - def pop(self, state, dict_, value, initiator, passive=...) -> None: ... - -class DynamicCollectionAdapter: - data: Any - def __init__(self, data) -> None: ... - def __iter__(self): ... - def __len__(self): ... - def __bool__(self): ... - __nonzero__: Any - -class AppenderMixin: - query_class: Any - instance: Any - attr: Any - def __init__(self, attr, state) -> None: ... - session: Any - def __getitem__(self, index): ... - def count(self): ... - def extend(self, iterator) -> None: ... - def append(self, item) -> None: ... - def remove(self, item) -> None: ... - -class AppenderQuery(AppenderMixin, Query): ... - -def mixin_user_query(cls): ... - -class CollectionHistory: - unchanged_items: Any - added_items: Any - deleted_items: Any - def __init__(self, attr, state, apply_to: Any | None = ...) -> None: ... - @property - def added_plus_unchanged(self): ... - @property - def all_items(self): ... - def as_history(self): ... - def indexed(self, index): ... - def add_added(self, value) -> None: ... - def add_removed(self, value) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/evaluator.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/evaluator.pyi deleted file mode 100644 index 2e3d6479cb74..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/evaluator.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Any - -from ..sql import operators - -class UnevaluatableError(Exception): ... - -class _NoObject(operators.ColumnOperators): - def operate(self, *arg, **kw) -> None: ... - def reverse_operate(self, *arg, **kw) -> None: ... - -class EvaluatorCompiler: - target_cls: Any - def __init__(self, target_cls: Any | None = ...) -> None: ... - def process(self, *clauses): ... - def visit_grouping(self, clause): ... - def visit_null(self, clause): ... - def visit_false(self, clause): ... - def visit_true(self, clause): ... - def visit_column(self, clause): ... - def visit_tuple(self, clause): ... - def visit_clauselist(self, clause): ... - def visit_binary(self, clause): ... - def visit_unary(self, clause): ... - def visit_bindparam(self, clause): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/events.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/events.pyi deleted file mode 100644 index 1a7c3cad7fbb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/events.pyi +++ /dev/null @@ -1,100 +0,0 @@ -from typing import Any - -from .. import event - -class InstrumentationEvents(event.Events): - def class_instrument(self, cls) -> None: ... - def class_uninstrument(self, cls) -> None: ... - def attribute_instrument(self, cls, key, inst) -> None: ... - -class _InstrumentationEventsHold: - class_: Any - def __init__(self, class_) -> None: ... - dispatch: Any - -class InstanceEvents(event.Events): - def first_init(self, manager, cls) -> None: ... - def init(self, target, args, kwargs) -> None: ... - def init_failure(self, target, args, kwargs) -> None: ... - def load(self, target, context) -> None: ... - def refresh(self, target, context, attrs) -> None: ... - def refresh_flush(self, target, flush_context, attrs) -> None: ... - def expire(self, target, attrs) -> None: ... - def pickle(self, target, state_dict) -> None: ... - def unpickle(self, target, state_dict) -> None: ... - -class _EventsHold(event.RefCollection): - class_: Any - def __init__(self, class_) -> None: ... - class HoldEvents: ... - def remove(self, event_key) -> None: ... - @classmethod - def populate(cls, class_, subject) -> None: ... - -class _InstanceEventsHold(_EventsHold): - all_holds: Any - def resolve(self, class_): ... - class HoldInstanceEvents(_EventsHold.HoldEvents, InstanceEvents): ... - dispatch: Any - -class MapperEvents(event.Events): - def instrument_class(self, mapper, class_) -> None: ... - def before_mapper_configured(self, mapper, class_) -> None: ... - def mapper_configured(self, mapper, class_) -> None: ... - def before_configured(self) -> None: ... - def after_configured(self) -> None: ... - def before_insert(self, mapper, connection, target) -> None: ... - def after_insert(self, mapper, connection, target) -> None: ... - def before_update(self, mapper, connection, target) -> None: ... - def after_update(self, mapper, connection, target) -> None: ... - def before_delete(self, mapper, connection, target) -> None: ... - def after_delete(self, mapper, connection, target) -> None: ... - -class _MapperEventsHold(_EventsHold): - all_holds: Any - def resolve(self, class_): ... - class HoldMapperEvents(_EventsHold.HoldEvents, MapperEvents): ... - dispatch: Any - -class SessionEvents(event.Events): - def do_orm_execute(self, orm_execute_state) -> None: ... - def after_transaction_create(self, session, transaction) -> None: ... - def after_transaction_end(self, session, transaction) -> None: ... - def before_commit(self, session) -> None: ... - def after_commit(self, session) -> None: ... - def after_rollback(self, session) -> None: ... - def after_soft_rollback(self, session, previous_transaction) -> None: ... - def before_flush(self, session, flush_context, instances) -> None: ... - def after_flush(self, session, flush_context) -> None: ... - def after_flush_postexec(self, session, flush_context) -> None: ... - def after_begin(self, session, transaction, connection) -> None: ... - def before_attach(self, session, instance) -> None: ... - def after_attach(self, session, instance) -> None: ... - def after_bulk_update(self, update_context) -> None: ... - def after_bulk_delete(self, delete_context) -> None: ... - def transient_to_pending(self, session, instance) -> None: ... - def pending_to_transient(self, session, instance) -> None: ... - def persistent_to_transient(self, session, instance) -> None: ... - def pending_to_persistent(self, session, instance) -> None: ... - def detached_to_persistent(self, session, instance) -> None: ... - def loaded_as_persistent(self, session, instance) -> None: ... - def persistent_to_deleted(self, session, instance) -> None: ... - def deleted_to_persistent(self, session, instance) -> None: ... - def deleted_to_detached(self, session, instance) -> None: ... - def persistent_to_detached(self, session, instance) -> None: ... - -class AttributeEvents(event.Events): - def append(self, target, value, initiator) -> None: ... - def append_wo_mutation(self, target, value, initiator) -> None: ... - def bulk_replace(self, target, values, initiator) -> None: ... - def remove(self, target, value, initiator) -> None: ... - def set(self, target, value, oldvalue, initiator) -> None: ... - def init_scalar(self, target, value, dict_) -> None: ... - def init_collection(self, target, collection, collection_adapter) -> None: ... - def dispose_collection(self, target, collection, collection_adapter) -> None: ... - def modified(self, target, initiator) -> None: ... - -class QueryEvents(event.Events): - def before_compile(self, query) -> None: ... - def before_compile_update(self, query, update_context) -> None: ... - def before_compile_delete(self, query, delete_context) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/exc.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/exc.pyi deleted file mode 100644 index 28a664a27221..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/exc.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Any - -from .. import exc as sa_exc - -NO_STATE: Any - -class StaleDataError(sa_exc.SQLAlchemyError): ... - -ConcurrentModificationError = StaleDataError - -class FlushError(sa_exc.SQLAlchemyError): ... -class UnmappedError(sa_exc.InvalidRequestError): ... -class ObjectDereferencedError(sa_exc.SQLAlchemyError): ... - -class DetachedInstanceError(sa_exc.SQLAlchemyError): - code: str - -class UnmappedInstanceError(UnmappedError): - def __init__(self, obj, msg: Any | None = ...) -> None: ... - def __reduce__(self): ... - -class UnmappedClassError(UnmappedError): - def __init__(self, cls, msg: Any | None = ...) -> None: ... - def __reduce__(self): ... - -class ObjectDeletedError(sa_exc.InvalidRequestError): - def __init__(self, state, msg: Any | None = ...) -> None: ... - def __reduce__(self): ... - -class UnmappedColumnError(sa_exc.InvalidRequestError): ... - -class LoaderStrategyException(sa_exc.InvalidRequestError): - def __init__(self, applied_to_property_type, requesting_property, applies_to, actual_strategy_type, strategy_key) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/identity.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/identity.pyi deleted file mode 100644 index deb590c27386..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/identity.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any - -class IdentityMap: - def __init__(self) -> None: ... - def keys(self): ... - def replace(self, state) -> None: ... - def add(self, state) -> None: ... - def update(self, dict_) -> None: ... - def clear(self) -> None: ... - def check_modified(self): ... - def has_key(self, key): ... - def popitem(self) -> None: ... - def pop(self, key, *args) -> None: ... - def setdefault(self, key, default: Any | None = ...) -> None: ... - def __len__(self): ... - def copy(self) -> None: ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - -class WeakInstanceDict(IdentityMap): - def __getitem__(self, key): ... - def __contains__(self, key): ... - def contains_state(self, state): ... - def replace(self, state): ... - def add(self, state): ... - def get(self, key, default: Any | None = ...): ... - def items(self): ... - def values(self): ... - def __iter__(self): ... - def all_states(self): ... - def discard(self, state) -> None: ... - def safe_discard(self, state) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/instrumentation.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/instrumentation.pyi deleted file mode 100644 index d3fcb9d9ef4c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/instrumentation.pyi +++ /dev/null @@ -1,87 +0,0 @@ -from typing import Any - -from ..util import HasMemoized, hybridmethod -from . import base - -DEL_ATTR: Any - -class ClassManager(HasMemoized, dict[Any, Any]): - MANAGER_ATTR: Any - STATE_ATTR: Any - expired_attribute_loader: Any - init_method: Any - factory: Any - mapper: Any - declarative_scan: Any - registry: Any - @property - def deferred_scalar_loader(self): ... - @deferred_scalar_loader.setter - def deferred_scalar_loader(self, obj) -> None: ... - class_: Any - info: Any - new_init: Any - local_attrs: Any - originals: Any - def __init__(self, class_) -> None: ... - def __hash__(self): ... - def __eq__(self, other): ... - @property - def is_mapped(self): ... - # Will be overwritten when mapped - # def mapper(self) -> None: ... - def manage(self) -> None: ... - @hybridmethod - def manager_getter(self): ... - @hybridmethod - def state_getter(self): ... - @hybridmethod - def dict_getter(self): ... - def instrument_attribute(self, key, inst, propagated: bool = ...) -> None: ... - def subclass_managers(self, recursive) -> None: ... - def post_configure_attribute(self, key) -> None: ... - def uninstrument_attribute(self, key, propagated: bool = ...) -> None: ... - def unregister(self) -> None: ... - def install_descriptor(self, key, inst) -> None: ... - def uninstall_descriptor(self, key) -> None: ... - def install_member(self, key, implementation) -> None: ... - def uninstall_member(self, key) -> None: ... - def instrument_collection_class(self, key, collection_class): ... - def initialize_collection(self, key, state, factory): ... - def is_instrumented(self, key, search: bool = ...): ... - def get_impl(self, key): ... - @property - def attributes(self): ... - def new_instance(self, state: Any | None = ...): ... - def setup_instance(self, instance, state: Any | None = ...) -> None: ... - def teardown_instance(self, instance) -> None: ... - def has_state(self, instance): ... - def has_parent(self, state, key, optimistic: bool = ...): ... - def __bool__(self): ... - __nonzero__: Any - -class _SerializeManager: - class_: Any - def __init__(self, state, d) -> None: ... - def __call__(self, state, inst, state_dict) -> None: ... - -class InstrumentationFactory: - def create_manager_for_cls(self, class_): ... - def unregister(self, class_) -> None: ... - -instance_state: Any - -instance_dict: Any -manager_of_class = base.manager_of_class - -def register_class( - class_, - finalize: bool = ..., - mapper: Any | None = ..., - registry: Any | None = ..., - declarative_scan: Any | None = ..., - expired_attribute_loader: Any | None = ..., - init_method: Any | None = ..., -): ... -def unregister_class(class_) -> None: ... -def is_instrumented(instance, key): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/interfaces.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/interfaces.pyi deleted file mode 100644 index 1f222f67cb9d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/interfaces.pyi +++ /dev/null @@ -1,128 +0,0 @@ -from typing import Any - -from .. import util -from ..sql import operators, roles -from ..sql.base import ExecutableOption -from ..sql.traversals import HasCacheKey -from .base import ( - EXT_CONTINUE as EXT_CONTINUE, - EXT_SKIP as EXT_SKIP, - EXT_STOP as EXT_STOP, - MANYTOMANY as MANYTOMANY, - MANYTOONE as MANYTOONE, - NOT_EXTENSION as NOT_EXTENSION, - ONETOMANY as ONETOMANY, - InspectionAttr as InspectionAttr, - InspectionAttrInfo as InspectionAttrInfo, - _MappedAttribute as _MappedAttribute, -) - -__all__ = ( - "EXT_CONTINUE", - "EXT_STOP", - "EXT_SKIP", - "ONETOMANY", - "MANYTOMANY", - "MANYTOONE", - "NOT_EXTENSION", - "LoaderStrategy", - "MapperOption", - "LoaderOption", - "MapperProperty", - "PropComparator", - "StrategizedProperty", -) - -class ORMStatementRole(roles.StatementRole): ... -class ORMColumnsClauseRole(roles.ColumnsClauseRole): ... -class ORMEntityColumnsClauseRole(ORMColumnsClauseRole): ... -class ORMFromClauseRole(roles.StrictFromClauseRole): ... - -class MapperProperty(HasCacheKey, _MappedAttribute, InspectionAttr, util.MemoizedSlots): - cascade: Any - is_property: bool - def setup(self, context, query_entity, path, adapter, **kwargs) -> None: ... - def create_row_processor(self, context, query_entity, path, mapper, result, adapter, populators) -> None: ... - def cascade_iterator(self, type_, state, dict_, visited_states, halt_on: Any | None = ...): ... - parent: Any - def set_parent(self, parent, init) -> None: ... - def instrument_class(self, mapper) -> None: ... - def __init__(self) -> None: ... - def init(self) -> None: ... - @property - def class_attribute(self): ... - def do_init(self) -> None: ... - def post_instrument_class(self, mapper) -> None: ... - def merge( - self, session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map - ) -> None: ... - -class PropComparator(operators.ColumnOperators): - __visit_name__: str - prop: Any - property: Any - def __init__(self, prop, parentmapper, adapt_to_entity: Any | None = ...) -> None: ... - def __clause_element__(self) -> None: ... - def adapt_to_entity(self, adapt_to_entity): ... - @property - def adapter(self): ... - @property - def info(self): ... - @staticmethod - def any_op(a, b, **kwargs): ... - @staticmethod - def has_op(a, b, **kwargs): ... - @staticmethod - def of_type_op(a, class_): ... - def of_type(self, class_): ... - def and_(self, *criteria): ... - def any(self, criterion: Any | None = ..., **kwargs): ... - def has(self, criterion: Any | None = ..., **kwargs): ... - -class StrategizedProperty(MapperProperty): - inherit_cache: bool - strategy_wildcard_key: Any - def setup(self, context, query_entity, path, adapter, **kwargs) -> None: ... - def create_row_processor(self, context, query_entity, path, mapper, result, adapter, populators) -> None: ... - strategy: Any - def do_init(self) -> None: ... - def post_instrument_class(self, mapper) -> None: ... - @classmethod - def strategy_for(cls, **kw): ... - -class ORMOption(ExecutableOption): - propagate_to_loaders: bool - -class CompileStateOption(HasCacheKey, ORMOption): - def process_compile_state(self, compile_state) -> None: ... - def process_compile_state_replaced_entities(self, compile_state, mapper_entities) -> None: ... - -class LoaderOption(CompileStateOption): - def process_compile_state_replaced_entities(self, compile_state, mapper_entities) -> None: ... - def process_compile_state(self, compile_state) -> None: ... - -class CriteriaOption(CompileStateOption): - def process_compile_state(self, compile_state) -> None: ... - def get_global_criteria(self, attributes) -> None: ... - -class UserDefinedOption(ORMOption): - propagate_to_loaders: bool - payload: Any - def __init__(self, payload: Any | None = ...) -> None: ... - -class MapperOption(ORMOption): - propagate_to_loaders: bool - def process_query(self, query) -> None: ... - def process_query_conditionally(self, query) -> None: ... - -class LoaderStrategy: - parent_property: Any - is_class_level: bool - parent: Any - key: Any - strategy_key: Any - strategy_opts: Any - def __init__(self, parent, strategy_key) -> None: ... - def init_class_attribute(self, mapper) -> None: ... - def setup_query(self, compile_state, query_entity, path, loadopt, adapter, **kwargs) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/loading.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/loading.pyi deleted file mode 100644 index ce8486f598fb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/loading.pyi +++ /dev/null @@ -1,47 +0,0 @@ -from typing import Any - -def instances(cursor, context): ... -def merge_frozen_result(session, statement, frozen_result, load: bool = ...): ... -def merge_result(query, iterator, load: bool = ...): ... -def get_from_identity(session, mapper, key, passive): ... -def load_on_ident( - session, - statement, - key, - load_options: Any | None = ..., - refresh_state: Any | None = ..., - with_for_update: Any | None = ..., - only_load_props: Any | None = ..., - no_autoflush: bool = ..., - bind_arguments=..., - execution_options=..., -): ... -def load_on_pk_identity( - session, - statement, - primary_key_identity, - load_options: Any | None = ..., - refresh_state: Any | None = ..., - with_for_update: Any | None = ..., - only_load_props: Any | None = ..., - identity_token: Any | None = ..., - no_autoflush: bool = ..., - bind_arguments=..., - execution_options=..., -): ... - -class PostLoad: - loaders: Any - states: Any - load_keys: Any - def __init__(self) -> None: ... - def add_state(self, state, overwrite) -> None: ... - def invoke(self, context, path) -> None: ... - @classmethod - def for_context(cls, context, path, only_load_props): ... - @classmethod - def path_exists(cls, context, path, key): ... - @classmethod - def callable_for_path(cls, context, path, limit_to_mapper, token, loader_callable, *arg, **kw) -> None: ... - -def load_scalar_attributes(mapper, state, attribute_names, passive) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/mapper.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/mapper.pyi deleted file mode 100644 index 931bde703ca9..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/mapper.pyi +++ /dev/null @@ -1,143 +0,0 @@ -from typing import Any - -from ..sql import base as sql_base -from ..util import HasMemoized, memoized_property -from .base import ( - _class_to_mapper as _class_to_mapper, - _state_mapper as _state_mapper, - class_mapper as class_mapper, - state_str as state_str, -) -from .interfaces import InspectionAttr, ORMEntityColumnsClauseRole, ORMFromClauseRole - -NO_ATTRIBUTE: Any - -class Mapper(ORMFromClauseRole, ORMEntityColumnsClauseRole, sql_base.MemoizedHasCacheKey, InspectionAttr): - logger: Any - class_: Any - class_manager: Any - non_primary: Any - always_refresh: Any - version_id_prop: Any - version_id_col: Any - version_id_generator: bool - concrete: Any - single: bool - inherits: Any - local_table: Any - inherit_condition: Any - inherit_foreign_keys: Any - batch: Any - eager_defaults: Any - column_prefix: Any - polymorphic_on: Any - validators: Any - passive_updates: Any - passive_deletes: Any - legacy_is_orphan: Any - allow_partial_pks: Any - confirm_deleted_rows: bool - polymorphic_load: Any - polymorphic_identity: Any - polymorphic_map: Any - include_properties: Any - exclude_properties: Any - def __init__( - self, - class_, - local_table: Any | None = ..., - properties: Any | None = ..., - primary_key: Any | None = ..., - non_primary: bool = ..., - inherits: Any | None = ..., - inherit_condition: Any | None = ..., - inherit_foreign_keys: Any | None = ..., - always_refresh: bool = ..., - version_id_col: Any | None = ..., - version_id_generator: Any | None = ..., - polymorphic_on: Any | None = ..., - _polymorphic_map: Any | None = ..., - polymorphic_identity: Any | None = ..., - concrete: bool = ..., - with_polymorphic: Any | None = ..., - polymorphic_load: Any | None = ..., - allow_partial_pks: bool = ..., - batch: bool = ..., - column_prefix: Any | None = ..., - include_properties: Any | None = ..., - exclude_properties: Any | None = ..., - passive_updates: bool = ..., - passive_deletes: bool = ..., - confirm_deleted_rows: bool = ..., - eager_defaults: bool = ..., - legacy_is_orphan: bool = ..., - _compiled_cache_size: int = ..., - ): ... - is_mapper: bool - represents_outer_join: bool - @property - def mapper(self): ... - @property - def entity(self): ... - persist_selectable: Any - configured: bool - tables: Any - primary_key: Any - base_mapper: Any - columns: Any - c: Any - @property - def mapped_table(self): ... - def add_properties(self, dict_of_properties) -> None: ... - def add_property(self, key, prop) -> None: ... - def has_property(self, key): ... - def get_property(self, key, _configure_mappers: bool = ...): ... - def get_property_by_column(self, column): ... - @property - def iterate_properties(self): ... - with_polymorphic_mappers: Any - def __clause_element__(self): ... - @memoized_property - def select_identity_token(self): ... - @property - def selectable(self): ... - @HasMemoized.memoized_attribute - def attrs(self): ... - @HasMemoized.memoized_attribute - def all_orm_descriptors(self): ... - @HasMemoized.memoized_attribute - def synonyms(self): ... - @property - def entity_namespace(self): ... - @HasMemoized.memoized_attribute - def column_attrs(self): ... - @HasMemoized.memoized_attribute - def relationships(self): ... - @HasMemoized.memoized_attribute - def composites(self): ... - def common_parent(self, other): ... - def is_sibling(self, other): ... - def isa(self, other): ... - def iterate_to_root(self) -> None: ... - @HasMemoized.memoized_attribute - def self_and_descendants(self): ... - def polymorphic_iterator(self): ... - def primary_mapper(self): ... - @property - def primary_base_mapper(self): ... - def identity_key_from_row(self, row, identity_token: Any | None = ..., adapter: Any | None = ...): ... - def identity_key_from_primary_key(self, primary_key, identity_token: Any | None = ...): ... - def identity_key_from_instance(self, instance): ... - def primary_key_from_instance(self, instance): ... - def cascade_iterator(self, type_, state, halt_on: Any | None = ...) -> None: ... - -class _OptGetColumnsNotAvailable(Exception): ... - -def configure_mappers() -> None: ... -def reconstructor(fn): ... -def validates(*names, **kw): ... - -class _ColumnMapping(dict[Any, Any]): - mapper: Any - def __init__(self, mapper) -> None: ... - def __missing__(self, column) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/path_registry.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/path_registry.pyi deleted file mode 100644 index 6d76489c4533..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/path_registry.pyi +++ /dev/null @@ -1,106 +0,0 @@ -from typing import Any, ClassVar - -from ..sql.traversals import HasCacheKey -from ..util import memoized_property -from . import base as orm_base - -log: Any - -class PathRegistry(HasCacheKey): - root: ClassVar[RootRegistry] - is_token: bool - is_root: bool - def __eq__(self, other): ... - def __ne__(self, other): ... - def set(self, attributes, key, value) -> None: ... - def setdefault(self, attributes, key, value) -> None: ... - def get(self, attributes, key, value: Any | None = ...): ... - def __len__(self): ... - def __hash__(self): ... - @property - def length(self): ... - def pairs(self) -> None: ... - def contains_mapper(self, mapper): ... - def contains(self, attributes, key): ... - def __reduce__(self): ... - @classmethod - def serialize_context_dict(cls, dict_, tokens): ... - @classmethod - def deserialize_context_dict(cls, serialized): ... - def serialize(self): ... - @classmethod - def deserialize(cls, path): ... - @classmethod - def per_mapper(cls, mapper): ... - @classmethod - def coerce(cls, raw): ... - def token(self, token): ... - def __add__(self, other): ... - -class RootRegistry(PathRegistry): - inherit_cache: bool - path: Any - natural_path: Any - has_entity: bool - is_aliased_class: bool - is_root: bool - def __getitem__(self, entity): ... - -class PathToken(orm_base.InspectionAttr, HasCacheKey, str): - @classmethod - def intern(cls, strvalue): ... - -class TokenRegistry(PathRegistry): - inherit_cache: bool - token: Any - parent: Any - path: Any - natural_path: Any - def __init__(self, parent, token) -> None: ... - has_entity: bool - is_token: bool - def generate_for_superclasses(self) -> None: ... - def __getitem__(self, entity) -> None: ... - -class PropRegistry(PathRegistry): - is_unnatural: bool - inherit_cache: bool - prop: Any - parent: Any - path: Any - natural_path: Any - def __init__(self, parent, prop) -> None: ... - @memoized_property - def has_entity(self): ... - @memoized_property - def entity(self): ... - @property - def mapper(self): ... - @property - def entity_path(self): ... - def __getitem__(self, entity): ... - -class AbstractEntityRegistry(PathRegistry): - has_entity: bool - key: Any - parent: Any - is_aliased_class: Any - entity: Any - path: Any - natural_path: Any - def __init__(self, parent, entity) -> None: ... - @property - def entity_path(self): ... - @property - def mapper(self): ... - def __bool__(self): ... - __nonzero__: Any - def __getitem__(self, entity): ... - -class SlotsEntityRegistry(AbstractEntityRegistry): - inherit_cache: bool - -class CachingEntityRegistry(AbstractEntityRegistry, dict): # type: ignore[misc] - inherit_cache: bool - def __getitem__(self, entity): ... - def __missing__(self, key): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/persistence.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/persistence.pyi deleted file mode 100644 index 6b9babbfb082..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/persistence.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any - -from ..sql.base import CompileState, Options -from ..sql.dml import DeleteDMLState, UpdateDMLState - -def save_obj(base_mapper, states, uowtransaction, single: bool = ...) -> None: ... -def post_update(base_mapper, states, uowtransaction, post_update_cols) -> None: ... -def delete_obj(base_mapper, states, uowtransaction) -> None: ... - -class BulkUDCompileState(CompileState): - class default_update_options(Options): ... - @classmethod - def orm_pre_session_exec(cls, session, statement, params, execution_options, bind_arguments, is_reentrant_invoke): ... - @classmethod - def orm_setup_cursor_result(cls, session, statement, params, execution_options, bind_arguments, result): ... - -class BulkORMUpdate(UpdateDMLState, BulkUDCompileState): - mapper: Any - extra_criteria_entities: Any - @classmethod - def create_for_statement(cls, statement, compiler, **kw): ... - -class BulkORMDelete(DeleteDMLState, BulkUDCompileState): - mapper: Any - extra_criteria_entities: Any - @classmethod - def create_for_statement(cls, statement, compiler, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/properties.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/properties.pyi deleted file mode 100644 index 963321511bfa..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/properties.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Any - -from .. import util -from .descriptor_props import ( - CompositeProperty as CompositeProperty, - ConcreteInheritedProperty as ConcreteInheritedProperty, - SynonymProperty as SynonymProperty, -) -from .interfaces import PropComparator, StrategizedProperty -from .relationships import RelationshipProperty as RelationshipProperty - -__all__ = ["ColumnProperty", "CompositeProperty", "ConcreteInheritedProperty", "RelationshipProperty", "SynonymProperty"] - -class ColumnProperty(StrategizedProperty): - logger: Any - strategy_wildcard_key: str - inherit_cache: bool - columns: Any - group: Any - deferred: Any - raiseload: Any - instrument: Any - comparator_factory: Any - descriptor: Any - active_history: Any - expire_on_flush: Any - info: Any - doc: Any - strategy_key: Any - def __init__(self, *columns, **kwargs) -> None: ... - def __clause_element__(self): ... - @property - def expression(self): ... - def instrument_class(self, mapper) -> None: ... - def do_init(self) -> None: ... - def copy(self): ... - def merge( - self, session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map - ) -> None: ... - class Comparator(util.MemoizedSlots, PropComparator): - expressions: Any - def _memoized_method___clause_element__(self): ... - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/query.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/query.pyi deleted file mode 100644 index cbaf8c8bf3f7..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/query.pyi +++ /dev/null @@ -1,127 +0,0 @@ -from typing import Any - -from ..sql.annotation import SupportsCloneAnnotations -from ..sql.base import Executable -from ..sql.selectable import GroupedElement, HasHints, HasPrefixes, HasSuffixes, SelectBase, _SelectFromElements -from . import interfaces -from .context import QueryContext as QueryContext -from .util import aliased as aliased - -__all__ = ["Query", "QueryContext", "aliased"] - -class Query(_SelectFromElements, SupportsCloneAnnotations, HasPrefixes, HasSuffixes, HasHints, Executable): - logger: Any - load_options: Any - session: Any - def __init__(self, entities, session: Any | None = ...) -> None: ... - @property - def statement(self): ... - def subquery(self, name: Any | None = ..., with_labels: bool = ..., reduce_columns: bool = ...): ... - def cte(self, name: Any | None = ..., recursive: bool = ..., nesting: bool = ...): ... - def label(self, name): ... - def as_scalar(self): ... - def scalar_subquery(self): ... - @property - def selectable(self): ... - def __clause_element__(self): ... - def only_return_tuples(self, value) -> None: ... - @property - def is_single_entity(self): ... - def enable_eagerloads(self, value) -> None: ... - def with_labels(self): ... - apply_labels: Any - @property - def get_label_style(self): ... - def set_label_style(self, style): ... - def enable_assertions(self, value) -> None: ... - @property - def whereclause(self): ... - def with_polymorphic(self, cls_or_mappers, selectable: Any | None = ..., polymorphic_on: Any | None = ...) -> None: ... - def yield_per(self, count) -> None: ... - def get(self, ident): ... - @property - def lazy_loaded_from(self): ... - def correlate(self, *fromclauses) -> None: ... - def autoflush(self, setting) -> None: ... - def populate_existing(self) -> None: ... - def with_parent(self, instance, property: Any | None = ..., from_entity: Any | None = ...): ... - def add_entity(self, entity, alias: Any | None = ...) -> None: ... - def with_session(self, session) -> None: ... - def from_self(self, *entities): ... - def values(self, *columns): ... - def value(self, column): ... - def with_entities(self, *entities) -> None: ... - def add_columns(self, *column) -> None: ... - def add_column(self, column): ... - def options(self, *args) -> None: ... - def with_transformation(self, fn): ... - def get_execution_options(self): ... - def execution_options(self, **kwargs) -> None: ... - def with_for_update( - self, read: bool = ..., nowait: bool = ..., of: Any | None = ..., skip_locked: bool = ..., key_share: bool = ... - ) -> None: ... - def params(self, *args, **kwargs) -> None: ... - def where(self, *criterion): ... - def filter(self, *criterion) -> None: ... - def filter_by(self, **kwargs): ... - def order_by(self, *clauses) -> None: ... - def group_by(self, *clauses) -> None: ... - def having(self, criterion) -> None: ... - def union(self, *q): ... - def union_all(self, *q): ... - def intersect(self, *q): ... - def intersect_all(self, *q): ... - def except_(self, *q): ... - def except_all(self, *q): ... - def join(self, target, *props, **kwargs) -> None: ... - def outerjoin(self, target, *props, **kwargs): ... - def reset_joinpoint(self) -> None: ... - def select_from(self, *from_obj) -> None: ... - def select_entity_from(self, from_obj) -> None: ... - def __getitem__(self, item): ... - def slice(self, start, stop) -> None: ... - def limit(self, limit) -> None: ... - def offset(self, offset) -> None: ... - def distinct(self, *expr) -> None: ... - def all(self): ... - def from_statement(self, statement) -> None: ... - def first(self): ... - def one_or_none(self): ... - def one(self): ... - def scalar(self): ... - def __iter__(self): ... - @property - def column_descriptions(self): ... - def instances(self, result_proxy, context: Any | None = ...): ... - def merge_result(self, iterator, load: bool = ...): ... - def exists(self): ... - def count(self): ... - def delete(self, synchronize_session: str = ...): ... - def update(self, values, synchronize_session: str = ..., update_args: Any | None = ...): ... - -class FromStatement(GroupedElement, SelectBase, Executable): - __visit_name__: str - element: Any - def __init__(self, entities, element) -> None: ... - def get_label_style(self): ... - def set_label_style(self, label_style): ... - def get_children(self, **kw) -> None: ... # type: ignore[override] - -class AliasOption(interfaces.LoaderOption): - def __init__(self, alias) -> None: ... - inherit_cache: bool - def process_compile_state(self, compile_state) -> None: ... - -class BulkUD: - query: Any - mapper: Any - def __init__(self, query) -> None: ... - @property - def session(self): ... - -class BulkUpdate(BulkUD): - values: Any - update_kwargs: Any - def __init__(self, query, values, update_kwargs) -> None: ... - -class BulkDelete(BulkUD): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/relationships.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/relationships.pyi deleted file mode 100644 index 69b52d7cb2ef..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/relationships.pyi +++ /dev/null @@ -1,174 +0,0 @@ -from typing import Any - -from ..util import memoized_property -from .interfaces import PropComparator, StrategizedProperty - -def remote(expr): ... -def foreign(expr): ... - -class RelationshipProperty(StrategizedProperty): - logger: Any - strategy_wildcard_key: str - inherit_cache: bool - uselist: Any - argument: Any - secondary: Any - primaryjoin: Any - secondaryjoin: Any - post_update: Any - direction: Any - viewonly: Any - sync_backref: Any - lazy: Any - single_parent: Any - collection_class: Any - passive_deletes: Any - cascade_backrefs: Any - passive_updates: Any - remote_side: Any - enable_typechecks: Any - query_class: Any - innerjoin: Any - distinct_target_key: Any - doc: Any - active_history: Any - join_depth: Any - omit_join: Any - local_remote_pairs: Any - bake_queries: Any - load_on_pending: Any - comparator_factory: Any - comparator: Any - info: Any - strategy_key: Any - order_by: Any - back_populates: Any - backref: Any - def __init__( - self, - argument, - secondary: Any | None = ..., - primaryjoin: Any | None = ..., - secondaryjoin: Any | None = ..., - foreign_keys: Any | None = ..., - uselist: Any | None = ..., - order_by: bool = ..., - backref: Any | None = ..., - back_populates: Any | None = ..., - overlaps: Any | None = ..., - post_update: bool = ..., - cascade: bool = ..., - viewonly: bool = ..., - lazy: str = ..., - collection_class: Any | None = ..., - passive_deletes=..., - passive_updates=..., - remote_side: Any | None = ..., - enable_typechecks=..., - join_depth: Any | None = ..., - comparator_factory: Any | None = ..., - single_parent: bool = ..., - innerjoin: bool = ..., - distinct_target_key: Any | None = ..., - doc: Any | None = ..., - active_history=..., - cascade_backrefs=..., - load_on_pending: bool = ..., - bake_queries: bool = ..., - _local_remote_pairs: Any | None = ..., - query_class: Any | None = ..., - info: Any | None = ..., - omit_join: Any | None = ..., - sync_backref: Any | None = ..., - _legacy_inactive_history_style: bool = ..., - ) -> None: ... - def instrument_class(self, mapper) -> None: ... - class Comparator(PropComparator): - prop: Any - def __init__( - self, prop, parentmapper, adapt_to_entity: Any | None = ..., of_type: Any | None = ..., extra_criteria=... - ) -> None: ... - def adapt_to_entity(self, adapt_to_entity): ... - @memoized_property - def entity(self): ... - @memoized_property - def mapper(self): ... - def __clause_element__(self): ... - def of_type(self, cls): ... - def and_(self, *other): ... - def in_(self, other) -> None: ... - __hash__: Any - def __eq__(self, other): ... - def any(self, criterion: Any | None = ..., **kwargs): ... - def has(self, criterion: Any | None = ..., **kwargs): ... - def contains(self, other, **kwargs): ... - def __ne__(self, other): ... - @memoized_property - def property(self): ... - def merge( - self, session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map - ) -> None: ... - def cascade_iterator(self, type_, state, dict_, visited_states, halt_on: Any | None = ...) -> None: ... - @memoized_property - def entity(self): ... - @memoized_property - def mapper(self): ... - def do_init(self) -> None: ... - @property - def cascade(self): ... - @cascade.setter - def cascade(self, cascade) -> None: ... - -class JoinCondition: - parent_persist_selectable: Any - parent_local_selectable: Any - child_persist_selectable: Any - child_local_selectable: Any - parent_equivalents: Any - child_equivalents: Any - primaryjoin: Any - secondaryjoin: Any - secondary: Any - consider_as_foreign_keys: Any - prop: Any - self_referential: Any - support_sync: Any - can_be_synced_fn: Any - def __init__( - self, - parent_persist_selectable, - child_persist_selectable, - parent_local_selectable, - child_local_selectable, - primaryjoin: Any | None = ..., - secondary: Any | None = ..., - secondaryjoin: Any | None = ..., - parent_equivalents: Any | None = ..., - child_equivalents: Any | None = ..., - consider_as_foreign_keys: Any | None = ..., - local_remote_pairs: Any | None = ..., - remote_side: Any | None = ..., - self_referential: bool = ..., - prop: Any | None = ..., - support_sync: bool = ..., - can_be_synced_fn=..., - ): ... - @property - def primaryjoin_minus_local(self): ... - @property - def secondaryjoin_minus_local(self): ... - @memoized_property - def primaryjoin_reverse_remote(self): ... - @memoized_property - def remote_columns(self): ... - @memoized_property - def local_columns(self): ... - @memoized_property - def foreign_key_columns(self): ... - def join_targets(self, source_selectable, dest_selectable, aliased, single_crit: Any | None = ..., extra_criteria=...): ... - def create_lazy_clause(self, reverse_direction: bool = ...): ... - -class _ColInAnnotations: - name: Any - def __init__(self, name) -> None: ... - def __call__(self, c): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/scoping.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/scoping.pyi deleted file mode 100644 index 7d739982b4c1..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/scoping.pyi +++ /dev/null @@ -1,96 +0,0 @@ -from typing import Any - -from ..util import memoized_property - -class ScopedSessionMixin: - def __call__(self, **kw): ... - def configure(self, **kwargs) -> None: ... - -class scoped_session(ScopedSessionMixin): - session_factory: Any - registry: Any - def __init__(self, session_factory, scopefunc: Any | None = ...) -> None: ... - def remove(self) -> None: ... - def query_property(self, query_cls: Any | None = ...): ... - # dynamically proxied from class Session - bind: Any - identity_map: Any - autoflush: Any - autocommit: bool - @property - def dirty(self): ... - @property - def deleted(self): ... - @property - def new(self): ... - @property - def is_active(self): ... - @property - def no_autoflush(self) -> None: ... - @memoized_property - def info(self): ... - @classmethod - def close_all(cls) -> None: ... - @classmethod - def identity_key(cls, *args, **kwargs): ... - @classmethod - def object_session(cls, instance): ... - def __contains__(self, instance): ... - def __iter__(self): ... - def add(self, instance, _warn: bool = ...) -> None: ... - def add_all(self, instances) -> None: ... - def begin(self, subtransactions: bool = ..., nested: bool = ..., _subtrans: bool = ...): ... - def begin_nested(self): ... - def close(self) -> None: ... - def commit(self) -> None: ... - def connection( - self, bind_arguments: Any | None = ..., close_with_result: bool = ..., execution_options: Any | None = ..., **kw - ): ... - def delete(self, instance) -> None: ... - def execute( - self, - statement, - params: Any | None = ..., - execution_options=..., - bind_arguments: Any | None = ..., - _parent_execute_state: Any | None = ..., - _add_event: Any | None = ..., - **kw, - ): ... - def expire(self, instance, attribute_names: Any | None = ...) -> None: ... - def expire_all(self) -> None: ... - def expunge(self, instance) -> None: ... - def expunge_all(self) -> None: ... - def flush(self, objects: Any | None = ...) -> None: ... - def get( - self, - entity, - ident, - options: Any | None = ..., - populate_existing: bool = ..., - with_for_update: Any | None = ..., - identity_token: Any | None = ..., - execution_options: Any | None = ..., - ): ... - def get_bind( - self, - mapper: Any | None = ..., - clause: Any | None = ..., - bind: Any | None = ..., - _sa_skip_events: Any | None = ..., - _sa_skip_for_implicit_returning: bool = ..., - ): ... - def is_modified(self, instance, include_collections: bool = ...): ... - def bulk_save_objects( - self, objects, return_defaults: bool = ..., update_changed_only: bool = ..., preserve_order: bool = ... - ): ... - def bulk_insert_mappings(self, mapper, mappings, return_defaults: bool = ..., render_nulls: bool = ...) -> None: ... - def bulk_update_mappings(self, mapper, mappings) -> None: ... - def merge(self, instance, load: bool = ..., options: Any | None = ...): ... - def query(self, *entities, **kwargs): ... - def refresh(self, instance, attribute_names: Any | None = ..., with_for_update: Any | None = ...) -> None: ... - def rollback(self) -> None: ... - def scalar(self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw): ... - def scalars(self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw): ... - -ScopedSession = scoped_session diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/session.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/session.pyi deleted file mode 100644 index bb7477e077e0..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/session.pyi +++ /dev/null @@ -1,202 +0,0 @@ -from typing import Any - -from ..engine.util import TransactionalContext -from ..util import MemoizedSlots, memoized_property - -class _SessionClassMethods: - @classmethod - def close_all(cls) -> None: ... - @classmethod - def identity_key(cls, *args, **kwargs): ... - @classmethod - def object_session(cls, instance): ... - -class ORMExecuteState(MemoizedSlots): - session: Any - statement: Any - parameters: Any - local_execution_options: Any - execution_options: Any - bind_arguments: Any - def __init__( - self, session, statement, parameters, execution_options, bind_arguments, compile_state_cls, events_todo - ) -> None: ... - def invoke_statement( - self, - statement: Any | None = ..., - params: Any | None = ..., - execution_options: Any | None = ..., - bind_arguments: Any | None = ..., - ): ... - @property - def bind_mapper(self): ... - @property - def all_mappers(self): ... - @property - def is_orm_statement(self): ... - @property - def is_select(self): ... - @property - def is_insert(self): ... - @property - def is_update(self): ... - @property - def is_delete(self): ... - def update_execution_options(self, **opts) -> None: ... - @property - def lazy_loaded_from(self): ... - @property - def loader_strategy_path(self): ... - @property - def is_column_load(self): ... - @property - def is_relationship_load(self): ... - @property - def load_options(self): ... - @property - def update_delete_options(self): ... - @property - def user_defined_options(self): ... - -class SessionTransaction(TransactionalContext): - session: Any - nested: Any - def __init__(self, session, parent: Any | None = ..., nested: bool = ..., autobegin: bool = ...) -> None: ... - @property - def parent(self): ... - @property - def is_active(self): ... - def connection(self, bindkey, execution_options: Any | None = ..., **kwargs): ... - def prepare(self) -> None: ... - def commit(self, _to_root: bool = ...): ... - def rollback(self, _capture_exception: bool = ..., _to_root: bool = ...): ... - def close(self, invalidate: bool = ...) -> None: ... - -class Session(_SessionClassMethods): - identity_map: Any - bind: Any - future: Any - hash_key: Any - autoflush: Any - expire_on_commit: Any - enable_baked_queries: Any - autocommit: bool - twophase: Any - def __init__( - self, - bind: Any | None = ..., - autoflush: bool = ..., - future: bool = ..., - expire_on_commit: bool = ..., - autocommit: bool = ..., - twophase: bool = ..., - binds: Any | None = ..., - enable_baked_queries: bool = ..., - info: Any | None = ..., - query_cls: Any | None = ..., - ) -> None: ... - connection_callable: Any - def __enter__(self): ... - def __exit__(self, type_, value, traceback) -> None: ... - @property - def transaction(self): ... - def in_transaction(self): ... - def in_nested_transaction(self): ... - def get_transaction(self): ... - def get_nested_transaction(self): ... - @memoized_property - def info(self): ... - def begin(self, subtransactions: bool = ..., nested: bool = ..., _subtrans: bool = ...): ... - def begin_nested(self): ... - def rollback(self) -> None: ... - def commit(self) -> None: ... - def prepare(self) -> None: ... - def connection( - self, bind_arguments: Any | None = ..., close_with_result: bool = ..., execution_options: Any | None = ..., **kw - ): ... - def execute( - self, - statement, - params: Any | None = ..., - execution_options=..., - bind_arguments: Any | None = ..., - _parent_execute_state: Any | None = ..., - _add_event: Any | None = ..., - **kw, - ): ... - def scalar(self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw): ... - def scalars(self, statement, params: Any | None = ..., execution_options=..., bind_arguments: Any | None = ..., **kw): ... - def close(self) -> None: ... - def invalidate(self) -> None: ... - def expunge_all(self) -> None: ... - def bind_mapper(self, mapper, bind) -> None: ... - def bind_table(self, table, bind) -> None: ... - def get_bind( - self, - mapper: Any | None = ..., - clause: Any | None = ..., - bind: Any | None = ..., - _sa_skip_events: Any | None = ..., - _sa_skip_for_implicit_returning: bool = ..., - ): ... - def query(self, *entities, **kwargs): ... - @property - def no_autoflush(self) -> None: ... - def refresh(self, instance, attribute_names: Any | None = ..., with_for_update: Any | None = ...) -> None: ... - def expire_all(self) -> None: ... - def expire(self, instance, attribute_names: Any | None = ...) -> None: ... - def expunge(self, instance) -> None: ... - def add(self, instance, _warn: bool = ...) -> None: ... - def add_all(self, instances) -> None: ... - def delete(self, instance) -> None: ... - def get( - self, - entity, - ident, - options: Any | None = ..., - populate_existing: bool = ..., - with_for_update: Any | None = ..., - identity_token: Any | None = ..., - execution_options: Any | None = ..., - ): ... - def merge(self, instance, load: bool = ..., options: Any | None = ...): ... - def enable_relationship_loading(self, obj) -> None: ... - def __contains__(self, instance): ... - def __iter__(self): ... - def flush(self, objects: Any | None = ...) -> None: ... - def bulk_save_objects( - self, objects, return_defaults: bool = ..., update_changed_only: bool = ..., preserve_order: bool = ... - ): ... - def bulk_insert_mappings(self, mapper, mappings, return_defaults: bool = ..., render_nulls: bool = ...) -> None: ... - def bulk_update_mappings(self, mapper, mappings) -> None: ... - def is_modified(self, instance, include_collections: bool = ...): ... - @property - def is_active(self): ... - @property - def dirty(self): ... - @property - def deleted(self): ... - @property - def new(self): ... - -class sessionmaker(_SessionClassMethods): - kw: Any - class_: Any - def __init__( - self, - bind: Any | None = ..., - class_=..., - autoflush: bool = ..., - autocommit: bool = ..., - expire_on_commit: bool = ..., - info: Any | None = ..., - **kw, - ) -> None: ... - def begin(self): ... - def __call__(self, **local_kw): ... - def configure(self, **new_kw) -> None: ... - -def close_all_sessions() -> None: ... -def make_transient(instance) -> None: ... -def make_transient_to_detached(instance) -> None: ... -def object_session(instance): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/state.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/state.pyi deleted file mode 100644 index 134ff2259ef8..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/state.pyi +++ /dev/null @@ -1,83 +0,0 @@ -from typing import Any - -from ..util import memoized_property -from . import interfaces - -class InstanceState(interfaces.InspectionAttrInfo): - session_id: Any - key: Any - runid: Any - load_options: Any - load_path: Any - insert_order: Any - modified: bool - expired: bool - is_instance: bool - identity_token: Any - callables: Any - class_: Any - manager: Any - committed_state: Any - expired_attributes: Any - def __init__(self, obj, manager) -> None: ... - @memoized_property - def attrs(self): ... - @property - def transient(self): ... - @property - def pending(self): ... - @property - def deleted(self): ... - @property - def was_deleted(self): ... - @property - def persistent(self): ... - @property - def detached(self): ... - @property - def session(self): ... - @property - def async_session(self): ... - @property - def object(self): ... - @property - def identity(self): ... - @property - def identity_key(self): ... - @memoized_property - def parents(self): ... - @memoized_property - def mapper(self): ... - @property - def has_identity(self): ... - def obj(self) -> None: ... - @property - def dict(self): ... - def get_history(self, key, passive): ... - def get_impl(self, key): ... - @property - def unmodified(self): ... - def unmodified_intersection(self, keys): ... - @property - def unloaded(self): ... - @property - def unloaded_expirable(self): ... - -class AttributeState: - state: Any - key: Any - def __init__(self, state, key) -> None: ... - @property - def loaded_value(self): ... - @property - def value(self): ... - @property - def history(self): ... - def load_history(self): ... - -class PendingCollection: - deleted_items: Any - added_items: Any - def __init__(self) -> None: ... - def append(self, value) -> None: ... - def remove(self, value) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/strategies.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/strategies.pyi deleted file mode 100644 index cb72a2b51eea..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/strategies.pyi +++ /dev/null @@ -1,138 +0,0 @@ -from typing import Any, NamedTuple - -from .. import util -from .interfaces import LoaderStrategy - -class UninstrumentedColumnLoader(LoaderStrategy): - columns: Any - def __init__(self, parent, strategy_key) -> None: ... - def setup_query( - self, compile_state, query_entity, path, loadopt, adapter, column_collection: Any | None = ..., **kwargs - ) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - -class ColumnLoader(LoaderStrategy): - logger: Any - columns: Any - is_composite: Any - def __init__(self, parent, strategy_key) -> None: ... - def setup_query(self, compile_state, query_entity, path, loadopt, adapter, column_collection, memoized_populators, check_for_adapt: bool = ..., **kwargs) -> None: ... # type: ignore[override] - is_class_level: bool - def init_class_attribute(self, mapper) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - -class ExpressionColumnLoader(ColumnLoader): - logger: Any - def __init__(self, parent, strategy_key) -> None: ... - def setup_query(self, compile_state, query_entity, path, loadopt, adapter, column_collection, memoized_populators, **kwargs) -> None: ... # type: ignore[override] - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - is_class_level: bool - def init_class_attribute(self, mapper) -> None: ... - -class DeferredColumnLoader(LoaderStrategy): - logger: Any - raiseload: Any - columns: Any - group: Any - def __init__(self, parent, strategy_key) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - is_class_level: bool - def init_class_attribute(self, mapper) -> None: ... - def setup_query(self, compile_state, query_entity, path, loadopt, adapter, column_collection, memoized_populators, only_load_props: Any | None = ..., **kw) -> None: ... # type: ignore[override] - -class LoadDeferredColumns: - key: Any - raiseload: Any - def __init__(self, key, raiseload: bool = ...) -> None: ... - def __call__(self, state, passive=...): ... - -class AbstractRelationshipLoader(LoaderStrategy): - mapper: Any - entity: Any - target: Any - uselist: Any - def __init__(self, parent, strategy_key) -> None: ... - -class DoNothingLoader(LoaderStrategy): - logger: Any - -class NoLoader(AbstractRelationshipLoader): - logger: Any - is_class_level: bool - def init_class_attribute(self, mapper) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - -class LazyLoader(AbstractRelationshipLoader, util.MemoizedSlots): - logger: Any - is_aliased_class: Any - use_get: Any - def __init__(self, parent, strategy_key) -> None: ... - is_class_level: bool - def init_class_attribute(self, mapper) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - -class LoadLazyAttribute: - key: Any - strategy_key: Any - loadopt: Any - extra_criteria: Any - def __init__(self, key, initiating_strategy, loadopt, extra_criteria) -> None: ... - def __call__(self, state, passive=...): ... - -class PostLoader(AbstractRelationshipLoader): ... - -class ImmediateLoader(PostLoader): - def init_class_attribute(self, mapper) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - -class SubqueryLoader(PostLoader): - logger: Any - join_depth: Any - def __init__(self, parent, strategy_key) -> None: ... - def init_class_attribute(self, mapper) -> None: ... - class _SubqCollections: - session: Any - execution_options: Any - load_options: Any - params: Any - subq: Any - def __init__(self, context, subq) -> None: ... - def get(self, key, default): ... - def loader(self, state, dict_, row) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators): ... - -class JoinedLoader(AbstractRelationshipLoader): - logger: Any - join_depth: Any - def __init__(self, parent, strategy_key) -> None: ... - def init_class_attribute(self, mapper) -> None: ... - def setup_query( - self, - compile_state, - query_entity, - path, - loadopt, - adapter, - column_collection: Any | None = ..., - parentmapper: Any | None = ..., - chained_from_outerjoin: bool = ..., - **kwargs, - ) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators) -> None: ... - -class SelectInLoader(PostLoader, util.MemoizedSlots): - logger: Any - class query_info(NamedTuple): - load_only_child: Any - load_with_join: Any - in_expr: Any - pk_cols: Any - zero_idx: Any - child_lookup_cols: Any - join_depth: Any - omit_join: Any - def __init__(self, parent, strategy_key) -> None: ... - def init_class_attribute(self, mapper) -> None: ... - def create_row_processor(self, context, query_entity, path, loadopt, mapper, result, adapter, populators): ... - -def single_parent_validator(desc, prop): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/strategy_options.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/strategy_options.pyi deleted file mode 100644 index 5fa175bbe4a2..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/strategy_options.pyi +++ /dev/null @@ -1,66 +0,0 @@ -from typing import Any - -from ..sql.base import Generative -from .interfaces import LoaderOption - -class Load(Generative, LoaderOption): - path: Any - context: Any - local_opts: Any - is_class_strategy: bool - def __init__(self, entity) -> None: ... - @classmethod - def for_existing_path(cls, path): ... - is_opts_only: bool - strategy: Any - propagate_to_loaders: bool - def process_compile_state_replaced_entities(self, compile_state, mapper_entities) -> None: ... - def process_compile_state(self, compile_state) -> None: ... - def options(self, *opts) -> None: ... - def set_relationship_strategy(self, attr, strategy, propagate_to_loaders: bool = ...) -> None: ... - def set_column_strategy(self, attrs, strategy, opts: Any | None = ..., opts_only: bool = ...) -> None: ... - def set_generic_strategy(self, attrs, strategy) -> None: ... - def set_class_strategy(self, strategy, opts) -> None: ... - # added dynamically at runtime - def contains_eager(self, attr, alias: Any | None = ...): ... - def load_only(self, *attrs): ... - def joinedload(self, attr, innerjoin: Any | None = ...): ... - def subqueryload(self, attr): ... - def selectinload(self, attr): ... - def lazyload(self, attr): ... - def immediateload(self, attr): ... - def noload(self, attr): ... - def raiseload(self, attr, sql_only: bool = ...): ... - def defaultload(self, attr): ... - def defer(self, key, raiseload: bool = ...): ... - def undefer(self, key): ... - def undefer_group(self, name): ... - def with_expression(self, key, expression): ... - def selectin_polymorphic(self, classes): ... - -class _UnboundLoad(Load): - path: Any - local_opts: Any - def __init__(self) -> None: ... - -class loader_option: - def __init__(self) -> None: ... - name: Any - fn: Any - def __call__(self, fn): ... - -def contains_eager(loadopt, attr, alias: Any | None = ...): ... -def load_only(loadopt, *attrs): ... -def joinedload(loadopt, attr, innerjoin: Any | None = ...): ... -def subqueryload(loadopt, attr): ... -def selectinload(loadopt, attr): ... -def lazyload(loadopt, attr): ... -def immediateload(loadopt, attr): ... -def noload(loadopt, attr): ... -def raiseload(loadopt, attr, sql_only: bool = ...): ... -def defaultload(loadopt, attr): ... -def defer(loadopt, key, raiseload: bool = ...): ... -def undefer(loadopt, key): ... -def undefer_group(loadopt, name): ... -def with_expression(loadopt, key, expression): ... -def selectin_polymorphic(loadopt, classes): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/sync.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/sync.pyi deleted file mode 100644 index 558c9c848c08..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/sync.pyi +++ /dev/null @@ -1,6 +0,0 @@ -def populate(source, source_mapper, dest, dest_mapper, synchronize_pairs, uowcommit, flag_cascaded_pks) -> None: ... -def bulk_populate_inherit_keys(source_dict, source_mapper, synchronize_pairs) -> None: ... -def clear(dest, dest_mapper, synchronize_pairs) -> None: ... -def update(source, source_mapper, dest, old_prefix, synchronize_pairs) -> None: ... -def populate_dict(source, source_mapper, dict_, synchronize_pairs) -> None: ... -def source_modified(uowcommit, source, source_mapper, synchronize_pairs): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/unitofwork.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/unitofwork.pyi deleted file mode 100644 index 5ca959e0e625..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/unitofwork.pyi +++ /dev/null @@ -1,105 +0,0 @@ -from typing import Any - -def track_cascade_events(descriptor, prop): ... - -class UOWTransaction: - session: Any - attributes: Any - deps: Any - mappers: Any - presort_actions: Any - postsort_actions: Any - dependencies: Any - states: Any - post_update_states: Any - def __init__(self, session): ... - @property - def has_work(self): ... - def was_already_deleted(self, state): ... - def is_deleted(self, state): ... - def memo(self, key, callable_): ... - def remove_state_actions(self, state) -> None: ... - def get_attribute_history(self, state, key, passive=...): ... - def has_dep(self, processor): ... - def register_preprocessor(self, processor, fromparent) -> None: ... - def register_object( - self, - state, - isdelete: bool = ..., - listonly: bool = ..., - cancel_delete: bool = ..., - operation: Any | None = ..., - prop: Any | None = ..., - ): ... - def register_post_update(self, state, post_update_cols) -> None: ... - def filter_states_for_dep(self, dep, states): ... - def states_for_mapper_hierarchy(self, mapper, isdelete, listonly) -> None: ... - def execute(self): ... - def finalize_flush_changes(self) -> None: ... - -class IterateMappersMixin: ... - -class Preprocess(IterateMappersMixin): - dependency_processor: Any - fromparent: Any - processed: Any - setup_flush_actions: bool - def __init__(self, dependency_processor, fromparent) -> None: ... - def execute(self, uow): ... - -class PostSortRec: - disabled: Any - def __new__(cls, uow, *args): ... - def execute_aggregate(self, uow, recs) -> None: ... - -class ProcessAll(IterateMappersMixin, PostSortRec): - dependency_processor: Any - sort_key: Any - isdelete: Any - fromparent: Any - def __init__(self, uow, dependency_processor, isdelete, fromparent) -> None: ... - def execute(self, uow) -> None: ... - def per_state_flush_actions(self, uow): ... - -class PostUpdateAll(PostSortRec): - mapper: Any - isdelete: Any - sort_key: Any - def __init__(self, uow, mapper, isdelete) -> None: ... - def execute(self, uow) -> None: ... - -class SaveUpdateAll(PostSortRec): - mapper: Any - sort_key: Any - def __init__(self, uow, mapper) -> None: ... - def execute(self, uow) -> None: ... - def per_state_flush_actions(self, uow) -> None: ... - -class DeleteAll(PostSortRec): - mapper: Any - sort_key: Any - def __init__(self, uow, mapper) -> None: ... - def execute(self, uow) -> None: ... - def per_state_flush_actions(self, uow) -> None: ... - -class ProcessState(PostSortRec): - dependency_processor: Any - sort_key: Any - isdelete: Any - state: Any - def __init__(self, uow, dependency_processor, isdelete, state) -> None: ... - def execute_aggregate(self, uow, recs) -> None: ... - -class SaveUpdateState(PostSortRec): - state: Any - mapper: Any - sort_key: Any - def __init__(self, uow, state) -> None: ... - def execute_aggregate(self, uow, recs) -> None: ... - -class DeleteState(PostSortRec): - state: Any - mapper: Any - sort_key: Any - def __init__(self, uow, state) -> None: ... - def execute_aggregate(self, uow, recs) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/orm/util.pyi b/stubs/SQLAlchemy/sqlalchemy/orm/util.pyi deleted file mode 100644 index ab249d0af845..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/orm/util.pyi +++ /dev/null @@ -1,179 +0,0 @@ -from typing import Any - -from ..sql import base as sql_base, expression, util as sql_util -from ..sql.annotation import SupportsCloneAnnotations -from .base import ( - InspectionAttr as InspectionAttr, - _class_to_mapper as _class_to_mapper, - _never_set as _never_set, - _none_set as _none_set, - attribute_str as attribute_str, - class_mapper as class_mapper, - instance_str as instance_str, - object_mapper as object_mapper, - object_state as object_state, - state_attribute_str as state_attribute_str, - state_class_str as state_class_str, - state_str as state_str, -) -from .interfaces import CriteriaOption, ORMColumnsClauseRole, ORMEntityColumnsClauseRole, ORMFromClauseRole - -all_cascades: Any - -class CascadeOptions(frozenset[Any]): - save_update: Any - delete: Any - refresh_expire: Any - merge: Any - expunge: Any - delete_orphan: Any - def __new__(cls, value_list): ... - @classmethod - def from_string(cls, arg): ... - -def polymorphic_union(table_map, typecolname, aliasname: str = ..., cast_nulls: bool = ...): ... -def identity_key(*args, **kwargs): ... - -class ORMAdapter(sql_util.ColumnAdapter): - mapper: Any - aliased_class: Any - def __init__( - self, - entity, - equivalents: Any | None = ..., - adapt_required: bool = ..., - allow_label_resolve: bool = ..., - anonymize_labels: bool = ..., - ) -> None: ... - -class AliasedClass: - __name__: Any - def __init__( - self, - mapped_class_or_ac, - alias: Any | None = ..., - name: Any | None = ..., - flat: bool = ..., - adapt_on_names: bool = ..., - with_polymorphic_mappers=..., - with_polymorphic_discriminator: Any | None = ..., - base_alias: Any | None = ..., - use_mapper_path: bool = ..., - represents_outer_join: bool = ..., - ) -> None: ... - def __getattr__(self, key): ... - -class AliasedInsp(ORMEntityColumnsClauseRole, ORMFromClauseRole, sql_base.MemoizedHasCacheKey, InspectionAttr): - mapper: Any - selectable: Any - name: Any - polymorphic_on: Any - represents_outer_join: Any - with_polymorphic_mappers: Any - def __init__( - self, - entity, - inspected, - selectable, - name, - with_polymorphic_mappers, - polymorphic_on, - _base_alias, - _use_mapper_path, - adapt_on_names, - represents_outer_join, - ) -> None: ... - @property - def entity(self): ... - is_aliased_class: bool - def __clause_element__(self): ... - @property - def entity_namespace(self): ... - @property - def class_(self): ... - -class _WrapUserEntity: - subject: Any - def __init__(self, subject) -> None: ... - def __getattribute__(self, name): ... - -class LoaderCriteriaOption(CriteriaOption): - root_entity: Any - entity: Any - deferred_where_criteria: bool - where_criteria: Any - include_aliases: Any - propagate_to_loaders: Any - def __init__( - self, - entity_or_base, - where_criteria, - loader_only: bool = ..., - include_aliases: bool = ..., - propagate_to_loaders: bool = ..., - track_closure_variables: bool = ..., - ) -> None: ... - def process_compile_state_replaced_entities(self, compile_state, mapper_entities): ... - def process_compile_state(self, compile_state) -> None: ... - def get_global_criteria(self, attributes) -> None: ... - -def aliased(element, alias: Any | None = ..., name: Any | None = ..., flat: bool = ..., adapt_on_names: bool = ...): ... -def with_polymorphic( - base, - classes, - selectable: bool = ..., - flat: bool = ..., - polymorphic_on: Any | None = ..., - aliased: bool = ..., - innerjoin: bool = ..., - _use_mapper_path: bool = ..., - _existing_alias: Any | None = ..., -): ... - -class Bundle(ORMColumnsClauseRole, SupportsCloneAnnotations, sql_base.MemoizedHasCacheKey, InspectionAttr): - single_entity: bool - is_clause_element: bool - is_mapper: bool - is_aliased_class: bool - is_bundle: bool - name: Any - exprs: Any - c: Any - def __init__(self, name, *exprs, **kw) -> None: ... - @property - def mapper(self): ... - @property - def entity(self): ... - @property - def entity_namespace(self): ... - columns: Any - def __clause_element__(self): ... - @property - def clauses(self): ... - def label(self, name): ... - def create_row_processor(self, query, procs, labels): ... - -class _ORMJoin(expression.Join): - __visit_name__: Any - inherit_cache: bool - onclause: Any - def __init__( - self, - left, - right, - onclause: Any | None = ..., - isouter: bool = ..., - full: bool = ..., - _left_memo: Any | None = ..., - _right_memo: Any | None = ..., - _extra_criteria=..., - ) -> None: ... - def join(self, right, onclause: Any | None = ..., isouter: bool = ..., full: bool = ..., join_to_left: Any | None = ...): ... - def outerjoin(self, right, onclause: Any | None = ..., full: bool = ..., join_to_left: Any | None = ...): ... - -def join(left, right, onclause: Any | None = ..., isouter: bool = ..., full: bool = ..., join_to_left: Any | None = ...): ... -def outerjoin(left, right, onclause: Any | None = ..., full: bool = ..., join_to_left: Any | None = ...): ... -def with_parent(instance, prop, from_entity: Any | None = ...): ... -def has_identity(object_): ... -def was_deleted(object_): ... -def randomize_unitofwork() -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/pool/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/pool/__init__.pyi deleted file mode 100644 index 977c65ad93f6..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/pool/__init__.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from .base import Pool as Pool, reset_commit as reset_commit, reset_none as reset_none, reset_rollback as reset_rollback -from .dbapi_proxy import clear_managers as clear_managers, manage as manage -from .impl import ( - AssertionPool as AssertionPool, - AsyncAdaptedQueuePool as AsyncAdaptedQueuePool, - FallbackAsyncAdaptedQueuePool as FallbackAsyncAdaptedQueuePool, - NullPool as NullPool, - QueuePool as QueuePool, - SingletonThreadPool as SingletonThreadPool, - StaticPool as StaticPool, -) - -__all__ = [ - "Pool", - "reset_commit", - "reset_none", - "reset_rollback", - "clear_managers", - "manage", - "AssertionPool", - "NullPool", - "QueuePool", - "AsyncAdaptedQueuePool", - "FallbackAsyncAdaptedQueuePool", - "SingletonThreadPool", - "StaticPool", -] diff --git a/stubs/SQLAlchemy/sqlalchemy/pool/base.pyi b/stubs/SQLAlchemy/sqlalchemy/pool/base.pyi deleted file mode 100644 index 9936b2d12377..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/pool/base.pyi +++ /dev/null @@ -1,88 +0,0 @@ -from typing import Any - -from .. import log -from ..util import memoized_property - -reset_rollback: Any -reset_commit: Any -reset_none: Any - -class _ConnDialect: - is_async: bool - def do_rollback(self, dbapi_connection) -> None: ... - def do_commit(self, dbapi_connection) -> None: ... - def do_close(self, dbapi_connection) -> None: ... - def do_ping(self, dbapi_connection) -> None: ... - def get_driver_connection(self, connection): ... - -class _AsyncConnDialect(_ConnDialect): - is_async: bool - -class Pool(log.Identified): - logging_name: Any - echo: Any - def __init__( - self, - creator, - recycle: int = ..., - echo: Any | None = ..., - logging_name: Any | None = ..., - reset_on_return: bool = ..., - events: Any | None = ..., - dialect: Any | None = ..., - pre_ping: bool = ..., - _dispatch: Any | None = ..., - ) -> None: ... - def recreate(self) -> None: ... - def dispose(self) -> None: ... - def connect(self): ... - def status(self) -> None: ... - -class _ConnectionRecord: - finalize_callback: Any - def __init__(self, pool, connect: bool = ...) -> None: ... - fresh: bool - fairy_ref: Any - starttime: Any - dbapi_connection: Any - @property - def driver_connection(self): ... - @property - def connection(self): ... - @connection.setter - def connection(self, value) -> None: ... - @memoized_property - def info(self): ... - @memoized_property - def record_info(self): ... - @classmethod - def checkout(cls, pool): ... - def checkin(self, _fairy_was_created: bool = ...) -> None: ... - @property - def in_use(self): ... - @property - def last_connect_time(self): ... - def close(self) -> None: ... - def invalidate(self, e: Any | None = ..., soft: bool = ...) -> None: ... - def get_connection(self): ... - -class _ConnectionFairy: - dbapi_connection: Any - def __init__(self, dbapi_connection, connection_record, echo) -> None: ... - @property - def driver_connection(self): ... - @property - def connection(self): ... - @connection.setter - def connection(self, value) -> None: ... - @property - def is_valid(self): ... - @memoized_property - def info(self): ... - @property - def record_info(self): ... - def invalidate(self, e: Any | None = ..., soft: bool = ...) -> None: ... - def cursor(self, *args, **kwargs): ... - def __getattr__(self, key): ... - def detach(self) -> None: ... - def close(self) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/pool/dbapi_proxy.pyi b/stubs/SQLAlchemy/sqlalchemy/pool/dbapi_proxy.pyi deleted file mode 100644 index 909b78d852a6..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/pool/dbapi_proxy.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -proxies: Any - -def manage(module, **params): ... -def clear_managers() -> None: ... - -class _DBProxy: - module: Any - kw: Any - poolclass: Any - pools: Any - def __init__(self, module, poolclass=..., **kw) -> None: ... - def close(self) -> None: ... - def __del__(self) -> None: ... - def __getattr__(self, key): ... - def get_pool(self, *args, **kw): ... - def connect(self, *args, **kw): ... - def dispose(self, *args, **kw) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/pool/events.pyi b/stubs/SQLAlchemy/sqlalchemy/pool/events.pyi deleted file mode 100644 index 8a5dde542e3a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/pool/events.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from .. import event - -class PoolEvents(event.Events): - def connect(self, dbapi_connection, connection_record) -> None: ... - def first_connect(self, dbapi_connection, connection_record) -> None: ... - def checkout(self, dbapi_connection, connection_record, connection_proxy) -> None: ... - def checkin(self, dbapi_connection, connection_record) -> None: ... - def reset(self, dbapi_connection, connection_record) -> None: ... - def invalidate(self, dbapi_connection, connection_record, exception) -> None: ... - def soft_invalidate(self, dbapi_connection, connection_record, exception) -> None: ... - def close(self, dbapi_connection, connection_record) -> None: ... - def detach(self, dbapi_connection, connection_record) -> None: ... - def close_detached(self, dbapi_connection) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/pool/impl.pyi b/stubs/SQLAlchemy/sqlalchemy/pool/impl.pyi deleted file mode 100644 index 2646cafd536d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/pool/impl.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Any - -from ..util import memoized_property -from .base import Pool - -class QueuePool(Pool): - def __init__( - self, creator, pool_size: int = ..., max_overflow: int = ..., timeout: float = ..., use_lifo: bool = ..., **kw - ) -> None: ... - def recreate(self): ... - def dispose(self) -> None: ... - def status(self): ... - def size(self): ... - def timeout(self): ... - def checkedin(self): ... - def overflow(self): ... - def checkedout(self): ... - -class AsyncAdaptedQueuePool(QueuePool): ... -class FallbackAsyncAdaptedQueuePool(AsyncAdaptedQueuePool): ... - -class NullPool(Pool): - def status(self): ... - def recreate(self): ... - def dispose(self) -> None: ... - -class SingletonThreadPool(Pool): - size: Any - def __init__(self, creator, pool_size: int = ..., **kw) -> None: ... - def recreate(self): ... - def dispose(self) -> None: ... - def status(self): ... - def connect(self): ... - -class StaticPool(Pool): - @memoized_property - def connection(self): ... - def status(self): ... - def dispose(self) -> None: ... - def recreate(self): ... - -class AssertionPool(Pool): - def __init__(self, *args, **kw) -> None: ... - def status(self): ... - def dispose(self) -> None: ... - def recreate(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/processors.pyi b/stubs/SQLAlchemy/sqlalchemy/processors.pyi deleted file mode 100644 index be304e64ea5d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/processors.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -def str_to_datetime_processor_factory(regexp, type_): ... -def py_fallback(): ... -def to_unicode_processor_factory(encoding, errors: Any | None = ...): ... -def to_conditional_unicode_processor_factory(encoding, errors: Any | None = ...): ... -def to_decimal_processor_factory(target_class, scale): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/schema.pyi b/stubs/SQLAlchemy/sqlalchemy/schema.pyi deleted file mode 100644 index ef2cc1ed91c9..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/schema.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from .sql.base import SchemaVisitor as SchemaVisitor -from .sql.ddl import ( - DDL as DDL, - AddConstraint as AddConstraint, - CreateColumn as CreateColumn, - CreateIndex as CreateIndex, - CreateSchema as CreateSchema, - CreateSequence as CreateSequence, - CreateTable as CreateTable, - DDLBase as DDLBase, - DDLElement as DDLElement, - DropColumnComment as DropColumnComment, - DropConstraint as DropConstraint, - DropIndex as DropIndex, - DropSchema as DropSchema, - DropSequence as DropSequence, - DropTable as DropTable, - DropTableComment as DropTableComment, - SetColumnComment as SetColumnComment, - SetTableComment as SetTableComment, - _CreateDropBase as _CreateDropBase, - _DDLCompiles as _DDLCompiles, - _DropView as _DropView, - sort_tables as sort_tables, - sort_tables_and_constraints as sort_tables_and_constraints, -) -from .sql.naming import conv as conv -from .sql.schema import ( - BLANK_SCHEMA as BLANK_SCHEMA, - CheckConstraint as CheckConstraint, - Column as Column, - ColumnCollectionConstraint as ColumnCollectionConstraint, - ColumnCollectionMixin as ColumnCollectionMixin, - ColumnDefault as ColumnDefault, - Computed as Computed, - Constraint as Constraint, - DefaultClause as DefaultClause, - DefaultGenerator as DefaultGenerator, - FetchedValue as FetchedValue, - ForeignKey as ForeignKey, - ForeignKeyConstraint as ForeignKeyConstraint, - Identity as Identity, - Index as Index, - MetaData as MetaData, - PrimaryKeyConstraint as PrimaryKeyConstraint, - SchemaItem as SchemaItem, - Sequence as Sequence, - Table as Table, - ThreadLocalMetaData as ThreadLocalMetaData, - UniqueConstraint as UniqueConstraint, -) diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/__init__.pyi deleted file mode 100644 index 625094b1e7ab..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/__init__.pyi +++ /dev/null @@ -1,91 +0,0 @@ -from . import sqltypes as sqltypes -from .base import Executable as Executable -from .compiler import ( - COLLECT_CARTESIAN_PRODUCTS as COLLECT_CARTESIAN_PRODUCTS, - FROM_LINTING as FROM_LINTING, - NO_LINTING as NO_LINTING, - WARN_LINTING as WARN_LINTING, -) -from .expression import ( - LABEL_STYLE_DEFAULT as LABEL_STYLE_DEFAULT, - LABEL_STYLE_DISAMBIGUATE_ONLY as LABEL_STYLE_DISAMBIGUATE_ONLY, - LABEL_STYLE_NONE as LABEL_STYLE_NONE, - LABEL_STYLE_TABLENAME_PLUS_COL as LABEL_STYLE_TABLENAME_PLUS_COL, - Alias as Alias, - ClauseElement as ClauseElement, - ColumnCollection as ColumnCollection, - ColumnElement as ColumnElement, - CompoundSelect as CompoundSelect, - Delete as Delete, - False_ as False_, - FromClause as FromClause, - Insert as Insert, - Join as Join, - LambdaElement as LambdaElement, - Select as Select, - Selectable as Selectable, - StatementLambdaElement as StatementLambdaElement, - Subquery as Subquery, - TableClause as TableClause, - TableSample as TableSample, - True_ as True_, - Update as Update, - Values as Values, - alias as alias, - all_ as all_, - and_ as and_, - any_ as any_, - asc as asc, - between as between, - bindparam as bindparam, - case as case, - cast as cast, - collate as collate, - column as column, - cte as cte, - delete as delete, - desc as desc, - distinct as distinct, - except_ as except_, - except_all as except_all, - exists as exists, - extract as extract, - false as false, - func as func, - funcfilter as funcfilter, - insert as insert, - intersect as intersect, - intersect_all as intersect_all, - join as join, - label as label, - lambda_stmt as lambda_stmt, - lateral as lateral, - literal as literal, - literal_column as literal_column, - modifier as modifier, - not_ as not_, - null as null, - nulls_first as nulls_first, - nulls_last as nulls_last, - nullsfirst as nullsfirst, - nullslast as nullslast, - or_ as or_, - outerjoin as outerjoin, - outparam as outparam, - over as over, - quoted_name as quoted_name, - select as select, - subquery as subquery, - table as table, - tablesample as tablesample, - text as text, - true as true, - tuple_ as tuple_, - type_coerce as type_coerce, - union as union, - union_all as union_all, - update as update, - values as values, - within_group as within_group, -) -from .visitors import ClauseVisitor as ClauseVisitor diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/annotation.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/annotation.pyi deleted file mode 100644 index 202412831da0..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/annotation.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -EMPTY_ANNOTATIONS: Any - -class SupportsAnnotations: ... -class SupportsCloneAnnotations(SupportsAnnotations): ... -class SupportsWrappingAnnotations(SupportsAnnotations): ... - -class Annotated: - def __new__(cls, *args): ... - __dict__: Any - def __init__(self, element, values) -> None: ... - def __reduce__(self): ... - def __hash__(self): ... - def __eq__(self, other): ... - @property - def entity_namespace(self): ... - -annotated_classes: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/base.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/base.pyi deleted file mode 100644 index 80036a8005ad..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/base.pyi +++ /dev/null @@ -1,158 +0,0 @@ -from collections.abc import MutableMapping -from typing import Any - -from .. import util -from ..util import HasMemoized, hybridmethod, memoized_property -from . import roles -from .traversals import ( - HasCacheKey as HasCacheKey, - HasCopyInternals as HasCopyInternals, - MemoizedHasCacheKey as MemoizedHasCacheKey, -) -from .visitors import ClauseVisitor - -coercions: Any -elements: Any -type_api: Any -PARSE_AUTOCOMMIT: Any -NO_ARG: Any - -class Immutable: - def unique_params(self, *optionaldict, **kwargs) -> None: ... - def params(self, *optionaldict, **kwargs) -> None: ... - -class SingletonConstant(Immutable): - def __new__(cls, *arg, **kw): ... - -class _DialectArgView(MutableMapping[Any, Any]): - obj: Any - def __init__(self, obj) -> None: ... - def __getitem__(self, key): ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - def __len__(self): ... - def __iter__(self): ... - -class _DialectArgDict(MutableMapping[Any, Any]): - def __init__(self) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __getitem__(self, key): ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - -class DialectKWArgs: - @classmethod - def argument_for(cls, dialect_name, argument_name, default) -> None: ... - @memoized_property - def dialect_kwargs(self): ... - @property - def kwargs(self): ... - @memoized_property - def dialect_options(self): ... - -class CompileState: - plugins: Any - @classmethod - def create_for_statement(cls, statement, compiler, **kw): ... - statement: Any - def __init__(self, statement, compiler, **kw) -> None: ... - @classmethod - def get_plugin_class(cls, statement): ... - @classmethod - def plugin_for(cls, plugin_name, visit_name): ... - -class Generative(HasMemoized): ... -class InPlaceGenerative(HasMemoized): ... -class HasCompileState(Generative): ... - -class _MetaOptions(type): - def __init__(cls, classname, bases, dict_) -> None: ... - def __add__(self, other): ... - -class Options: - def __init__(self, **kw) -> None: ... - def __add__(self, other): ... - def __eq__(self, other): ... - @classmethod - def isinstance(cls, klass): ... - @hybridmethod - def add_to_element(self, name, value): ... - @classmethod - def safe_merge(cls, other): ... - @classmethod - def from_execution_options(cls, key, attrs, exec_options, statement_exec_options): ... - -class CacheableOptions(Options, HasCacheKey): ... - -class ExecutableOption(HasCopyInternals): - __visit_name__: str - -class Executable(roles.StatementRole, Generative): - supports_execution: bool - is_select: bool - is_update: bool - is_insert: bool - is_text: bool - is_delete: bool - is_dml: bool - def options(self, *options) -> None: ... - def execution_options(self, **kw) -> None: ... - def get_execution_options(self): ... - def execute(self, *multiparams, **params): ... - def scalar(self, *multiparams, **params): ... - @property - def bind(self): ... - -class prefix_anon_map(dict[Any, Any]): - def __missing__(self, key): ... - -class SchemaEventTarget: ... - -class SchemaVisitor(ClauseVisitor): - __traverse_options__: Any - -class ColumnCollection: - def __init__(self, columns: Any | None = ...) -> None: ... - def keys(self): ... - def values(self): ... - def items(self): ... - def __bool__(self): ... - def __len__(self): ... - def __iter__(self): ... - def __getitem__(self, key): ... - def __getattr__(self, key): ... - def __contains__(self, key): ... - def compare(self, other): ... - def __eq__(self, other): ... - def get(self, key, default: Any | None = ...): ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - def __setattr__(self, key, obj) -> None: ... - def clear(self) -> None: ... - def remove(self, column) -> None: ... - def update(self, iter_) -> None: ... - __hash__: Any - def add(self, column, key: Any | None = ...) -> None: ... - def contains_column(self, col): ... - def as_immutable(self): ... - def corresponding_column(self, column, require_embedded: bool = ...): ... - -class DedupeColumnCollection(ColumnCollection): - def add(self, column, key: Any | None = ...) -> None: ... - def extend(self, iter_) -> None: ... - def remove(self, column) -> None: ... - def replace(self, column) -> None: ... - -class ImmutableColumnCollection(util.ImmutableContainer, ColumnCollection): - def __init__(self, collection) -> None: ... - add: Any - extend: Any - remove: Any - -class ColumnSet(util.ordered_column_set): - def contains_column(self, col): ... - def extend(self, cols) -> None: ... - def __add__(self, other): ... - def __eq__(self, other): ... - def __hash__(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/coercions.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/coercions.pyi deleted file mode 100644 index 79a24e98d6bd..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/coercions.pyi +++ /dev/null @@ -1,66 +0,0 @@ -from typing import Any - -from . import roles - -elements: Any -lambdas: Any -schema: Any -selectable: Any -sqltypes: Any -traversals: Any - -def expect(role, element, apply_propagate_attrs: Any | None = ..., argname: Any | None = ..., post_inspect: bool = ..., **kw): ... -def expect_as_key(role, element, **kw): ... -def expect_col_expression_collection(role, expressions) -> None: ... - -class RoleImpl: - name: Any - def __init__(self, role_class) -> None: ... - -class _Deannotate: ... -class _StringOnly: ... -class _ReturnsStringKey: ... -class _ColumnCoercions: ... -class _NoTextCoercion: ... -class _CoerceLiterals: ... -class LiteralValueImpl(RoleImpl): ... -class _SelectIsNotFrom: ... -class HasCacheKeyImpl(RoleImpl): ... -class ExecutableOptionImpl(RoleImpl): ... -class ExpressionElementImpl(_ColumnCoercions, RoleImpl): ... -class BinaryElementImpl(ExpressionElementImpl, RoleImpl): ... -class InElementImpl(RoleImpl): ... -class OnClauseImpl(_CoerceLiterals, _ColumnCoercions, RoleImpl): ... -class WhereHavingImpl(_CoerceLiterals, _ColumnCoercions, RoleImpl): ... -class StatementOptionImpl(_CoerceLiterals, RoleImpl): ... -class ColumnArgumentImpl(_NoTextCoercion, RoleImpl): ... -class ColumnArgumentOrKeyImpl(_ReturnsStringKey, RoleImpl): ... -class StrAsPlainColumnImpl(_CoerceLiterals, RoleImpl): ... -class ByOfImpl(_CoerceLiterals, _ColumnCoercions, RoleImpl, roles.ByOfRole): ... -class OrderByImpl(ByOfImpl, RoleImpl): ... -class GroupByImpl(ByOfImpl, RoleImpl): ... -class DMLColumnImpl(_ReturnsStringKey, RoleImpl): ... -class ConstExprImpl(RoleImpl): ... -class TruncatedLabelImpl(_StringOnly, RoleImpl): ... -class DDLExpressionImpl(_Deannotate, _CoerceLiterals, RoleImpl): ... -class DDLConstraintColumnImpl(_Deannotate, _ReturnsStringKey, RoleImpl): ... -class DDLReferredColumnImpl(DDLConstraintColumnImpl): ... -class LimitOffsetImpl(RoleImpl): ... -class LabeledColumnExprImpl(ExpressionElementImpl): ... -class ColumnsClauseImpl(_SelectIsNotFrom, _CoerceLiterals, RoleImpl): ... -class ReturnsRowsImpl(RoleImpl): ... -class StatementImpl(_CoerceLiterals, RoleImpl): ... -class SelectStatementImpl(_NoTextCoercion, RoleImpl): ... -class HasCTEImpl(ReturnsRowsImpl): ... -class IsCTEImpl(RoleImpl): ... -class JoinTargetImpl(RoleImpl): ... -class FromClauseImpl(_SelectIsNotFrom, _NoTextCoercion, RoleImpl): ... -class StrictFromClauseImpl(FromClauseImpl): ... -class AnonymizedFromClauseImpl(StrictFromClauseImpl): ... -class DMLTableImpl(_SelectIsNotFrom, _NoTextCoercion, RoleImpl): ... -class DMLSelectImpl(_NoTextCoercion, RoleImpl): ... -class CompoundElementImpl(_NoTextCoercion, RoleImpl): ... - -cls: Any -name: Any -impl: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/compiler.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/compiler.pyi deleted file mode 100644 index eb96eab18e62..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/compiler.pyi +++ /dev/null @@ -1,472 +0,0 @@ -from typing import Any, NamedTuple - -from ..util import memoized_property -from . import elements - -RESERVED_WORDS: Any -LEGAL_CHARACTERS: Any -LEGAL_CHARACTERS_PLUS_SPACE: Any -ILLEGAL_INITIAL_CHARACTERS: Any -FK_ON_DELETE: Any -FK_ON_UPDATE: Any -FK_INITIALLY: Any -BIND_PARAMS: Any -BIND_PARAMS_ESC: Any -BIND_TEMPLATES: Any -OPERATORS: Any -FUNCTIONS: Any -EXTRACT_MAP: Any -COMPOUND_KEYWORDS: Any -RM_RENDERED_NAME: int -RM_NAME: int -RM_OBJECTS: int -RM_TYPE: int - -class ExpandedState(NamedTuple): - statement: Any - additional_parameters: Any - processors: Any - positiontup: Any - parameter_expansion: Any - -NO_LINTING: Any -COLLECT_CARTESIAN_PRODUCTS: Any -WARN_LINTING: Any -FROM_LINTING: Any - -class FromLinter: - def lint(self, start: Any | None = ...): ... - def warn(self) -> None: ... - -class Compiled: - schema_translate_map: Any - execution_options: Any - compile_state: Any - cache_key: Any - dialect: Any - preparer: Any - statement: Any - can_execute: Any - string: Any - def __init__( - self, dialect, statement, schema_translate_map: Any | None = ..., render_schema_translate: bool = ..., compile_kwargs=... - ) -> None: ... - def visit_unsupported_compilation(self, element, err) -> None: ... - @property - def sql_compiler(self) -> None: ... - def process(self, obj, **kwargs): ... - def construct_params(self, params: Any | None = ..., extracted_parameters: Any | None = ...) -> None: ... - @property - def params(self): ... - -class TypeCompiler: - ensure_kwarg: str - dialect: Any - def __init__(self, dialect) -> None: ... - def process(self, type_, **kw): ... - def visit_unsupported_compilation(self, element, err, **kw) -> None: ... - -class _CompileLabel(elements.ColumnElement): - __visit_name__: str - element: Any - name: Any - def __init__(self, col, name, alt_names=...) -> None: ... - @property - def proxy_set(self): ... - @property - def type(self): ... - def self_group(self, **kw): ... - -class SQLCompiler(Compiled): - extract_map: Any - compound_keywords: Any - isdelete: bool - isinsert: bool - isupdate: bool - isplaintext: bool - returning: Any - returning_precedes_values: bool - render_table_with_column_in_update_from: bool - ansi_bind_rules: bool - insert_single_values_expr: Any - literal_execute_params: Any - post_compile_params: Any - escaped_bind_names: Any - has_out_parameters: bool - insert_prefetch: Any - update_prefetch: Any - postfetch_lastrowid: bool - positiontup: Any - inline: bool - column_keys: Any - cache_key: Any - for_executemany: Any - linting: Any - binds: Any - bind_names: Any - stack: Any - positional: Any - bindtemplate: Any - ctes: Any - label_length: Any - anon_map: Any - truncated_names: Any - def __init__( - self, - dialect, - statement, - cache_key: Any | None = ..., - column_keys: Any | None = ..., - for_executemany: bool = ..., - linting=..., - **kwargs, - ) -> None: ... - @property - def current_executable(self): ... - @property - def prefetch(self): ... - def is_subquery(self): ... - @property - def sql_compiler(self): ... - def construct_params(self, params: Any | None = ..., _group_number: Any | None = ..., _check: bool = ..., extracted_parameters: Any | None = ...): ... # type: ignore[override] - @property - def params(self): ... - def default_from(self): ... - def visit_grouping(self, grouping, asfrom: bool = ..., **kwargs): ... - def visit_select_statement_grouping(self, grouping, **kwargs): ... - def visit_label_reference(self, element, within_columns_clause: bool = ..., **kwargs): ... - def visit_textual_label_reference(self, element, within_columns_clause: bool = ..., **kwargs): ... - def visit_label( - self, - label, - add_to_result_map: Any | None = ..., - within_label_clause: bool = ..., - within_columns_clause: bool = ..., - render_label_as_label: Any | None = ..., - result_map_targets=..., - **kw, - ): ... - def visit_lambda_element(self, element, **kw): ... - def visit_column( - self, column, add_to_result_map: Any | None = ..., include_table: bool = ..., result_map_targets=..., **kwargs - ): ... - def visit_collation(self, element, **kw): ... - def visit_fromclause(self, fromclause, **kwargs): ... - def visit_index(self, index, **kwargs): ... - def visit_typeclause(self, typeclause, **kw): ... - def post_process_text(self, text): ... - def escape_literal_column(self, text): ... - def visit_textclause(self, textclause, add_to_result_map: Any | None = ..., **kw): ... - def visit_textual_select(self, taf, compound_index: Any | None = ..., asfrom: bool = ..., **kw): ... - def visit_null(self, expr, **kw): ... - def visit_true(self, expr, **kw): ... - def visit_false(self, expr, **kw): ... - def visit_tuple(self, clauselist, **kw): ... - def visit_clauselist(self, clauselist, **kw): ... - def visit_case(self, clause, **kwargs): ... - def visit_type_coerce(self, type_coerce, **kw): ... - def visit_cast(self, cast, **kwargs): ... - def visit_over(self, over, **kwargs): ... - def visit_withingroup(self, withingroup, **kwargs): ... - def visit_funcfilter(self, funcfilter, **kwargs): ... - def visit_extract(self, extract, **kwargs): ... - def visit_scalar_function_column(self, element, **kw): ... - def visit_function(self, func, add_to_result_map: Any | None = ..., **kwargs): ... - def visit_next_value_func(self, next_value, **kw): ... - def visit_sequence(self, sequence, **kw) -> None: ... - def function_argspec(self, func, **kwargs): ... - compile_state: Any - def visit_compound_select(self, cs, asfrom: bool = ..., compound_index: Any | None = ..., **kwargs): ... - def visit_unary(self, unary, add_to_result_map: Any | None = ..., result_map_targets=..., **kw): ... - def visit_is_true_unary_operator(self, element, operator, **kw): ... - def visit_is_false_unary_operator(self, element, operator, **kw): ... - def visit_not_match_op_binary(self, binary, operator, **kw): ... - def visit_not_in_op_binary(self, binary, operator, **kw): ... - def visit_empty_set_op_expr(self, type_, expand_op): ... - def visit_empty_set_expr(self, element_types) -> None: ... - def visit_binary( - self, - binary, - override_operator: Any | None = ..., - eager_grouping: bool = ..., - from_linter: Any | None = ..., - lateral_from_linter: Any | None = ..., - **kw, - ): ... - def visit_function_as_comparison_op_binary(self, element, operator, **kw): ... - def visit_mod_binary(self, binary, operator, **kw): ... - def visit_custom_op_binary(self, element, operator, **kw): ... - def visit_custom_op_unary_operator(self, element, operator, **kw): ... - def visit_custom_op_unary_modifier(self, element, operator, **kw): ... - def visit_contains_op_binary(self, binary, operator, **kw): ... - def visit_not_contains_op_binary(self, binary, operator, **kw): ... - def visit_startswith_op_binary(self, binary, operator, **kw): ... - def visit_not_startswith_op_binary(self, binary, operator, **kw): ... - def visit_endswith_op_binary(self, binary, operator, **kw): ... - def visit_not_endswith_op_binary(self, binary, operator, **kw): ... - def visit_like_op_binary(self, binary, operator, **kw): ... - def visit_not_like_op_binary(self, binary, operator, **kw): ... - def visit_ilike_op_binary(self, binary, operator, **kw): ... - def visit_not_ilike_op_binary(self, binary, operator, **kw): ... - def visit_between_op_binary(self, binary, operator, **kw): ... - def visit_not_between_op_binary(self, binary, operator, **kw): ... - def visit_regexp_match_op_binary(self, binary, operator, **kw) -> None: ... - def visit_not_regexp_match_op_binary(self, binary, operator, **kw) -> None: ... - def visit_regexp_replace_op_binary(self, binary, operator, **kw) -> None: ... - def visit_bindparam( - self, - bindparam, - within_columns_clause: bool = ..., - literal_binds: bool = ..., - skip_bind_expression: bool = ..., - literal_execute: bool = ..., - render_postcompile: bool = ..., - **kwargs, - ): ... - def render_literal_bindparam(self, bindparam, render_literal_value=..., **kw): ... - def render_literal_value(self, value, type_): ... - def bindparam_string( - self, - name, - positional_names: Any | None = ..., - post_compile: bool = ..., - expanding: bool = ..., - escaped_from: Any | None = ..., - **kw, - ): ... - execution_options: Any - ctes_recursive: bool - def visit_cte( - self, - cte, - asfrom: bool = ..., - ashint: bool = ..., - fromhints: Any | None = ..., - visiting_cte: Any | None = ..., - from_linter: Any | None = ..., - **kwargs, - ): ... - def visit_table_valued_alias(self, element, **kw): ... - def visit_table_valued_column(self, element, **kw): ... - def visit_alias( - self, - alias, - asfrom: bool = ..., - ashint: bool = ..., - iscrud: bool = ..., - fromhints: Any | None = ..., - subquery: bool = ..., - lateral: bool = ..., - enclosing_alias: Any | None = ..., - from_linter: Any | None = ..., - **kwargs, - ): ... - def visit_subquery(self, subquery, **kw): ... - def visit_lateral(self, lateral_, **kw): ... - def visit_tablesample(self, tablesample, asfrom: bool = ..., **kw): ... - def visit_values(self, element, asfrom: bool = ..., from_linter: Any | None = ..., **kw): ... - def get_render_as_alias_suffix(self, alias_name_text): ... - def format_from_hint_text(self, sqltext, table, hint, iscrud): ... - def get_select_hint_text(self, byfroms) -> None: ... - def get_from_hint_text(self, table, text) -> None: ... - def get_crud_hint_text(self, table, text) -> None: ... - def get_statement_hint_text(self, hint_texts): ... - translate_select_structure: Any - def visit_select( - self, - select_stmt, - asfrom: bool = ..., - insert_into: bool = ..., - fromhints: Any | None = ..., - compound_index: Any | None = ..., - select_wraps_for: Any | None = ..., - lateral: bool = ..., - from_linter: Any | None = ..., - **kwargs, - ): ... - def get_cte_preamble(self, recursive): ... - def get_select_precolumns(self, select, **kw): ... - def group_by_clause(self, select, **kw): ... - def order_by_clause(self, select, **kw): ... - def for_update_clause(self, select, **kw): ... - def returning_clause(self, stmt, returning_cols) -> None: ... - def limit_clause(self, select, **kw): ... - def fetch_clause(self, select, **kw): ... - def visit_table( - self, - table, - asfrom: bool = ..., - iscrud: bool = ..., - ashint: bool = ..., - fromhints: Any | None = ..., - use_schema: bool = ..., - from_linter: Any | None = ..., - **kwargs, - ): ... - def visit_join(self, join, asfrom: bool = ..., from_linter: Any | None = ..., **kwargs): ... - def visit_insert(self, insert_stmt, **kw): ... - def update_limit_clause(self, update_stmt) -> None: ... - def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw): ... - def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw) -> None: ... - def visit_update(self, update_stmt, **kw): ... - def delete_extra_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw) -> None: ... - def delete_table_clause(self, delete_stmt, from_table, extra_froms): ... - def visit_delete(self, delete_stmt, **kw): ... - def visit_savepoint(self, savepoint_stmt): ... - def visit_rollback_to_savepoint(self, savepoint_stmt): ... - def visit_release_savepoint(self, savepoint_stmt): ... - -class StrSQLCompiler(SQLCompiler): - def visit_unsupported_compilation(self, element, err, **kw): ... - def visit_getitem_binary(self, binary, operator, **kw): ... - def visit_json_getitem_op_binary(self, binary, operator, **kw): ... - def visit_json_path_getitem_op_binary(self, binary, operator, **kw): ... - def visit_sequence(self, seq, **kw): ... - def returning_clause(self, stmt, returning_cols): ... - def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw): ... - def delete_extra_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw): ... - def visit_empty_set_expr(self, type_): ... - def get_from_hint_text(self, table, text): ... - def visit_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_not_regexp_match_op_binary(self, binary, operator, **kw): ... - def visit_regexp_replace_op_binary(self, binary, operator, **kw): ... - -class DDLCompiler(Compiled): - @memoized_property - def sql_compiler(self): ... - @memoized_property - def type_compiler(self): ... - def construct_params(self, params: Any | None = ..., extracted_parameters: Any | None = ...) -> None: ... - def visit_ddl(self, ddl, **kwargs): ... - def visit_create_schema(self, create, **kw): ... - def visit_drop_schema(self, drop, **kw): ... - def visit_create_table(self, create, **kw): ... - def visit_create_column(self, create, first_pk: bool = ..., **kw): ... - def create_table_constraints(self, table, _include_foreign_key_constraints: Any | None = ..., **kw): ... - def visit_drop_table(self, drop, **kw): ... - def visit_drop_view(self, drop, **kw): ... - def visit_create_index(self, create, include_schema: bool = ..., include_table_schema: bool = ..., **kw): ... - def visit_drop_index(self, drop, **kw): ... - def visit_add_constraint(self, create, **kw): ... - def visit_set_table_comment(self, create, **kw): ... - def visit_drop_table_comment(self, drop, **kw): ... - def visit_set_column_comment(self, create, **kw): ... - def visit_drop_column_comment(self, drop, **kw): ... - def get_identity_options(self, identity_options): ... - def visit_create_sequence(self, create, prefix: Any | None = ..., **kw): ... - def visit_drop_sequence(self, drop, **kw): ... - def visit_drop_constraint(self, drop, **kw): ... - def get_column_specification(self, column, **kwargs): ... - def create_table_suffix(self, table): ... - def post_create_table(self, table): ... - def get_column_default_string(self, column): ... - def visit_table_or_column_check_constraint(self, constraint, **kw): ... - def visit_check_constraint(self, constraint, **kw): ... - def visit_column_check_constraint(self, constraint, **kw): ... - def visit_primary_key_constraint(self, constraint, **kw): ... - def visit_foreign_key_constraint(self, constraint, **kw): ... - def define_constraint_remote_table(self, constraint, table, preparer): ... - def visit_unique_constraint(self, constraint, **kw): ... - def define_constraint_cascades(self, constraint): ... - def define_constraint_deferrability(self, constraint): ... - def define_constraint_match(self, constraint): ... - def visit_computed_column(self, generated, **kw): ... - def visit_identity_column(self, identity, **kw): ... - -class GenericTypeCompiler(TypeCompiler): - def visit_FLOAT(self, type_, **kw): ... - def visit_REAL(self, type_, **kw): ... - def visit_NUMERIC(self, type_, **kw): ... - def visit_DECIMAL(self, type_, **kw): ... - def visit_INTEGER(self, type_, **kw): ... - def visit_SMALLINT(self, type_, **kw): ... - def visit_BIGINT(self, type_, **kw): ... - def visit_TIMESTAMP(self, type_, **kw): ... - def visit_DATETIME(self, type_, **kw): ... - def visit_DATE(self, type_, **kw): ... - def visit_TIME(self, type_, **kw): ... - def visit_CLOB(self, type_, **kw): ... - def visit_NCLOB(self, type_, **kw): ... - def visit_CHAR(self, type_, **kw): ... - def visit_NCHAR(self, type_, **kw): ... - def visit_VARCHAR(self, type_, **kw): ... - def visit_NVARCHAR(self, type_, **kw): ... - def visit_TEXT(self, type_, **kw): ... - def visit_BLOB(self, type_, **kw): ... - def visit_BINARY(self, type_, **kw): ... - def visit_VARBINARY(self, type_, **kw): ... - def visit_BOOLEAN(self, type_, **kw): ... - def visit_large_binary(self, type_, **kw): ... - def visit_boolean(self, type_, **kw): ... - def visit_time(self, type_, **kw): ... - def visit_datetime(self, type_, **kw): ... - def visit_date(self, type_, **kw): ... - def visit_big_integer(self, type_, **kw): ... - def visit_small_integer(self, type_, **kw): ... - def visit_integer(self, type_, **kw): ... - def visit_real(self, type_, **kw): ... - def visit_float(self, type_, **kw): ... - def visit_numeric(self, type_, **kw): ... - def visit_string(self, type_, **kw): ... - def visit_unicode(self, type_, **kw): ... - def visit_text(self, type_, **kw): ... - def visit_unicode_text(self, type_, **kw): ... - def visit_enum(self, type_, **kw): ... - def visit_null(self, type_, **kw) -> None: ... - def visit_type_decorator(self, type_, **kw): ... - def visit_user_defined(self, type_, **kw): ... - -class StrSQLTypeCompiler(GenericTypeCompiler): - def process(self, type_, **kw): ... - def __getattr__(self, key): ... - def visit_null(self, type_, **kw): ... - def visit_user_defined(self, type_, **kw): ... - -class IdentifierPreparer: - reserved_words: Any - legal_characters: Any - illegal_initial_characters: Any - schema_for_object: Any - dialect: Any - initial_quote: Any - final_quote: Any - escape_quote: Any - escape_to_quote: Any - omit_schema: Any - quote_case_sensitive_collations: Any - def __init__( - self, - dialect, - initial_quote: str = ..., - final_quote: Any | None = ..., - escape_quote: str = ..., - quote_case_sensitive_collations: bool = ..., - omit_schema: bool = ..., - ) -> None: ... - def validate_sql_phrase(self, element, reg): ... - def quote_identifier(self, value): ... - def quote_schema(self, schema, force: Any | None = ...): ... - def quote(self, ident, force: Any | None = ...): ... - def format_collation(self, collation_name): ... - def format_sequence(self, sequence, use_schema: bool = ...): ... - def format_label(self, label, name: Any | None = ...): ... - def format_alias(self, alias, name: Any | None = ...): ... - def format_savepoint(self, savepoint, name: Any | None = ...): ... - def format_constraint(self, constraint, _alembic_quote: bool = ...): ... - def truncate_and_render_index_name(self, name, _alembic_quote: bool = ...): ... - def truncate_and_render_constraint_name(self, name, _alembic_quote: bool = ...): ... - def format_index(self, index): ... - def format_table(self, table, use_schema: bool = ..., name: Any | None = ...): ... - def format_schema(self, name): ... - def format_label_name(self, name, anon_map: Any | None = ...): ... - def format_column( - self, - column, - use_table: bool = ..., - name: Any | None = ..., - table_name: Any | None = ..., - use_schema: bool = ..., - anon_map: Any | None = ..., - ): ... - def format_table_seq(self, table, use_schema: bool = ...): ... - def unformat_identifiers(self, identifiers): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/crud.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/crud.pyi deleted file mode 100644 index 0e263aca4fba..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/crud.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from . import elements - -REQUIRED: Any - -class _multiparam_column(elements.ColumnElement): - index: Any - key: Any - original: Any - default: Any - type: Any - def __init__(self, original, index) -> None: ... - def compare(self, other, **kw) -> None: ... - def __eq__(self, other): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/ddl.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/ddl.pyi deleted file mode 100644 index 4dba7ea2bb74..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/ddl.pyi +++ /dev/null @@ -1,139 +0,0 @@ -from typing import Any - -from . import roles -from .base import Executable, SchemaVisitor -from .elements import ClauseElement - -class _DDLCompiles(ClauseElement): ... - -class DDLElement(roles.DDLRole, Executable, _DDLCompiles): - target: Any - on: Any - dialect: Any - callable_: Any - def execute(self, bind: Any | None = ..., target: Any | None = ...): ... # type: ignore[override] - def against(self, target) -> None: ... - state: Any - def execute_if(self, dialect: Any | None = ..., callable_: Any | None = ..., state: Any | None = ...) -> None: ... - def __call__(self, target, bind, **kw): ... - bind: Any - -class DDL(DDLElement): - __visit_name__: str - statement: Any - context: Any - def __init__(self, statement, context: Any | None = ..., bind: Any | None = ...) -> None: ... - -class _CreateDropBase(DDLElement): - element: Any - bind: Any - if_exists: Any - if_not_exists: Any - def __init__( - self, element, bind: Any | None = ..., if_exists: bool = ..., if_not_exists: bool = ..., _legacy_bind: Any | None = ... - ) -> None: ... - @property - def stringify_dialect(self): ... - -class CreateSchema(_CreateDropBase): - __visit_name__: str - quote: Any - def __init__(self, name, quote: Any | None = ..., **kw) -> None: ... - -class DropSchema(_CreateDropBase): - __visit_name__: str - quote: Any - cascade: Any - def __init__(self, name, quote: Any | None = ..., cascade: bool = ..., **kw) -> None: ... - -class CreateTable(_CreateDropBase): - __visit_name__: str - columns: Any - include_foreign_key_constraints: Any - def __init__( - self, element, bind: Any | None = ..., include_foreign_key_constraints: Any | None = ..., if_not_exists: bool = ... - ) -> None: ... - -class _DropView(_CreateDropBase): - __visit_name__: str - -class CreateColumn(_DDLCompiles): - __visit_name__: str - element: Any - def __init__(self, element) -> None: ... - -class DropTable(_CreateDropBase): - __visit_name__: str - def __init__(self, element, bind: Any | None = ..., if_exists: bool = ...) -> None: ... - -class CreateSequence(_CreateDropBase): - __visit_name__: str - -class DropSequence(_CreateDropBase): - __visit_name__: str - -class CreateIndex(_CreateDropBase): - __visit_name__: str - def __init__(self, element, bind: Any | None = ..., if_not_exists: bool = ...) -> None: ... - -class DropIndex(_CreateDropBase): - __visit_name__: str - def __init__(self, element, bind: Any | None = ..., if_exists: bool = ...) -> None: ... - -class AddConstraint(_CreateDropBase): - __visit_name__: str - def __init__(self, element, *args, **kw) -> None: ... - -class DropConstraint(_CreateDropBase): - __visit_name__: str - cascade: Any - def __init__(self, element, cascade: bool = ..., **kw) -> None: ... - -class SetTableComment(_CreateDropBase): - __visit_name__: str - -class DropTableComment(_CreateDropBase): - __visit_name__: str - -class SetColumnComment(_CreateDropBase): - __visit_name__: str - -class DropColumnComment(_CreateDropBase): - __visit_name__: str - -class DDLBase(SchemaVisitor): - connection: Any - def __init__(self, connection) -> None: ... - -class SchemaGenerator(DDLBase): - checkfirst: Any - tables: Any - preparer: Any - dialect: Any - memo: Any - def __init__(self, dialect, connection, checkfirst: bool = ..., tables: Any | None = ..., **kwargs) -> None: ... - def visit_metadata(self, metadata) -> None: ... - def visit_table( - self, table, create_ok: bool = ..., include_foreign_key_constraints: Any | None = ..., _is_metadata_operation: bool = ... - ) -> None: ... - def visit_foreign_key_constraint(self, constraint) -> None: ... - def visit_sequence(self, sequence, create_ok: bool = ...) -> None: ... - def visit_index(self, index, create_ok: bool = ...) -> None: ... - -class SchemaDropper(DDLBase): - checkfirst: Any - tables: Any - preparer: Any - dialect: Any - memo: Any - def __init__(self, dialect, connection, checkfirst: bool = ..., tables: Any | None = ..., **kwargs) -> None: ... - def visit_metadata(self, metadata): ... - def visit_index(self, index, drop_ok: bool = ...) -> None: ... - def visit_table(self, table, drop_ok: bool = ..., _is_metadata_operation: bool = ..., _ignore_sequences=...) -> None: ... - def visit_foreign_key_constraint(self, constraint) -> None: ... - def visit_sequence(self, sequence, drop_ok: bool = ...) -> None: ... - -def sort_tables(tables, skip_fn: Any | None = ..., extra_dependencies: Any | None = ...): ... -def sort_tables_and_constraints( - tables, filter_fn: Any | None = ..., extra_dependencies: Any | None = ..., _warn_for_cycles: bool = ... -): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/default_comparator.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/default_comparator.pyi deleted file mode 100644 index ac514fdf0146..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/default_comparator.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -operator_lookup: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/dml.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/dml.pyi deleted file mode 100644 index ee31b23435b0..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/dml.pyi +++ /dev/null @@ -1,111 +0,0 @@ -from typing import Any - -from . import roles -from .base import CompileState, DialectKWArgs, Executable, HasCompileState -from .elements import ClauseElement -from .selectable import HasCTE, HasPrefixes, ReturnsRows - -class DMLState(CompileState): - isupdate: bool - isdelete: bool - isinsert: bool - def __init__(self, statement, compiler, **kw) -> None: ... - @property - def dml_table(self): ... - -class InsertDMLState(DMLState): - isinsert: bool - include_table_with_column_exprs: bool - statement: Any - def __init__(self, statement, compiler, **kw) -> None: ... - -class UpdateDMLState(DMLState): - isupdate: bool - include_table_with_column_exprs: bool - statement: Any - is_multitable: Any - def __init__(self, statement, compiler, **kw) -> None: ... - -class DeleteDMLState(DMLState): - isdelete: bool - statement: Any - def __init__(self, statement, compiler, **kw) -> None: ... - -class UpdateBase(roles.DMLRole, HasCTE, HasCompileState, DialectKWArgs, HasPrefixes, ReturnsRows, Executable, ClauseElement): - __visit_name__: str - named_with_column: bool - is_dml: bool - def params(self, *arg, **kw) -> None: ... - def with_dialect_options(self, **opt) -> None: ... - bind: Any - def returning(self, *cols) -> None: ... - @property - def exported_columns(self): ... - def with_hint(self, text, selectable: Any | None = ..., dialect_name: str = ...) -> None: ... - -class ValuesBase(UpdateBase): - __visit_name__: str - select: Any - table: Any - def __init__(self, table, values, prefixes) -> None: ... - def values(self, *args, **kwargs) -> None: ... - def return_defaults(self, *cols) -> None: ... - -class Insert(ValuesBase): - __visit_name__: str - select: Any - include_insert_from_select_defaults: bool - is_insert: bool - def __init__( - self, - table, - values: Any | None = ..., - inline: bool = ..., - bind: Any | None = ..., - prefixes: Any | None = ..., - returning: Any | None = ..., - return_defaults: bool = ..., - **dialect_kw, - ) -> None: ... - def inline(self) -> None: ... - def from_select(self, names, select, include_defaults: bool = ...) -> None: ... - -class DMLWhereBase: - def where(self, *whereclause) -> None: ... - def filter(self, *criteria): ... - def filter_by(self, **kwargs): ... - @property - def whereclause(self): ... - -class Update(DMLWhereBase, ValuesBase): - __visit_name__: str - is_update: bool - def __init__( - self, - table, - whereclause: Any | None = ..., - values: Any | None = ..., - inline: bool = ..., - bind: Any | None = ..., - prefixes: Any | None = ..., - returning: Any | None = ..., - return_defaults: bool = ..., - preserve_parameter_order: bool = ..., - **dialect_kw, - ) -> None: ... - def ordered_values(self, *args) -> None: ... - def inline(self) -> None: ... - -class Delete(DMLWhereBase, UpdateBase): - __visit_name__: str - is_delete: bool - table: Any - def __init__( - self, - table, - whereclause: Any | None = ..., - bind: Any | None = ..., - returning: Any | None = ..., - prefixes: Any | None = ..., - **dialect_kw, - ) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/elements.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/elements.pyi deleted file mode 100644 index ef7345e32547..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/elements.pyi +++ /dev/null @@ -1,452 +0,0 @@ -from typing import Any - -from .. import util -from ..util import HasMemoized, memoized_property -from . import operators, roles -from .annotation import Annotated, SupportsWrappingAnnotations -from .base import Executable, Immutable, SingletonConstant -from .traversals import HasCopyInternals, MemoizedHasCacheKey -from .visitors import Traversible - -def collate(expression, collation): ... -def between(expr, lower_bound, upper_bound, symmetric: bool = ...): ... -def literal(value, type_: Any | None = ...): ... -def outparam(key, type_: Any | None = ...): ... -def not_(clause): ... - -class ClauseElement(roles.SQLRole, SupportsWrappingAnnotations, MemoizedHasCacheKey, HasCopyInternals, Traversible): - __visit_name__: str - supports_execution: bool - stringify_dialect: str - bind: Any - description: Any - is_clause_element: bool - is_selectable: bool - @property - def entity_namespace(self) -> None: ... - def unique_params(self, *optionaldict, **kwargs): ... - def params(self, *optionaldict, **kwargs): ... - def compare(self, other, **kw): ... - def self_group(self, against: Any | None = ...): ... - def compile(self, bind: Any | None = ..., dialect: Any | None = ..., **kw): ... - def __invert__(self): ... - def __bool__(self) -> None: ... - __nonzero__: Any - -class ColumnElement( - roles.ColumnArgumentOrKeyRole, - roles.StatementOptionRole, - roles.WhereHavingRole, - roles.BinaryElementRole, - roles.OrderByRole, - roles.ColumnsClauseRole, - roles.LimitOffsetRole, - roles.DMLColumnRole, - roles.DDLConstraintColumnRole, - roles.DDLExpressionRole, - operators.ColumnOperators, - ClauseElement, -): - __visit_name__: str - primary_key: bool - foreign_keys: Any - key: Any - def self_group(self, against: Any | None = ...): ... - @memoized_property - def type(self): ... - @HasMemoized.memoized_attribute - def comparator(self): ... - def __getattr__(self, key): ... - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... - @property - def expression(self): ... - @memoized_property - def base_columns(self): ... - @memoized_property - def proxy_set(self): ... - def shares_lineage(self, othercolumn): ... - def cast(self, type_): ... - def label(self, name): ... - @property - def anon_label(self): ... - @property - def anon_key_label(self): ... - -class WrapsColumnExpression: - @property - def wrapped_column_expression(self) -> None: ... - -class BindParameter(roles.InElementRole, ColumnElement): - __visit_name__: str - inherit_cache: bool - key: Any - unique: Any - value: Any - callable: Any - isoutparam: Any - required: Any - expanding: Any - expand_op: Any - literal_execute: Any - type: Any - def __init__( - self, - key, - value=..., - type_: Any | None = ..., - unique: bool = ..., - required=..., - quote: Any | None = ..., - callable_: Any | None = ..., - expanding: bool = ..., - isoutparam: bool = ..., - literal_execute: bool = ..., - _compared_to_operator: Any | None = ..., - _compared_to_type: Any | None = ..., - _is_crud: bool = ..., - ) -> None: ... - @property - def effective_value(self): ... - def render_literal_execute(self): ... - -class TypeClause(ClauseElement): - __visit_name__: str - type: Any - def __init__(self, type_) -> None: ... - -class TextClause( - roles.DDLConstraintColumnRole, - roles.DDLExpressionRole, - roles.StatementOptionRole, - roles.WhereHavingRole, - roles.OrderByRole, - roles.FromClauseRole, - roles.SelectStatementRole, - roles.BinaryElementRole, - roles.InElementRole, - Executable, - ClauseElement, -): - __visit_name__: str - def __and__(self, other): ... - key: Any - text: Any - def __init__(self, text, bind: Any | None = ...): ... - def bindparams(self, *binds, **names_to_values) -> None: ... - def columns(self, *cols, **types): ... - @property - def type(self): ... - @property - def comparator(self): ... - def self_group(self, against: Any | None = ...): ... - -class Null(SingletonConstant, roles.ConstExprRole, ColumnElement): - __visit_name__: str - @memoized_property - def type(self): ... - -class False_(SingletonConstant, roles.ConstExprRole, ColumnElement): - __visit_name__: str - @memoized_property - def type(self): ... - -class True_(SingletonConstant, roles.ConstExprRole, ColumnElement): - __visit_name__: str - @memoized_property - def type(self): ... - -class ClauseList(roles.InElementRole, roles.OrderByRole, roles.ColumnsClauseRole, roles.DMLColumnRole, ClauseElement): - __visit_name__: str - operator: Any - group: Any - group_contents: Any - clauses: Any - def __init__(self, *clauses, **kwargs) -> None: ... - def __iter__(self): ... - def __len__(self): ... - def append(self, clause) -> None: ... - def self_group(self, against: Any | None = ...): ... - -class BooleanClauseList(ClauseList, ColumnElement): - __visit_name__: str - inherit_cache: bool - def __init__(self, *arg, **kw) -> None: ... - @classmethod - def and_(cls, *clauses): ... - @classmethod - def or_(cls, *clauses): ... - def self_group(self, against: Any | None = ...): ... - -and_: Any -or_: Any - -class Tuple(ClauseList, ColumnElement): - __visit_name__: str - type: Any - def __init__(self, *clauses, **kw) -> None: ... - def self_group(self, against: Any | None = ...): ... - -class Case(ColumnElement): - __visit_name__: str - value: Any - type: Any - whens: Any - else_: Any - def __init__(self, *whens, **kw) -> None: ... - -def literal_column(text, type_: Any | None = ...): ... - -class Cast(WrapsColumnExpression, ColumnElement): - __visit_name__: str - type: Any - clause: Any - typeclause: Any - def __init__(self, expression, type_) -> None: ... - @property - def wrapped_column_expression(self): ... - -class TypeCoerce(WrapsColumnExpression, ColumnElement): - __visit_name__: str - type: Any - clause: Any - def __init__(self, expression, type_) -> None: ... - @HasMemoized.memoized_attribute - def typed_expression(self): ... - @property - def wrapped_column_expression(self): ... - def self_group(self, against: Any | None = ...): ... - -class Extract(ColumnElement): - __visit_name__: str - type: Any - field: Any - expr: Any - def __init__(self, field, expr, **kwargs) -> None: ... - -class _label_reference(ColumnElement): - __visit_name__: str - element: Any - def __init__(self, element) -> None: ... - -class _textual_label_reference(ColumnElement): - __visit_name__: str - element: Any - def __init__(self, element) -> None: ... - -class UnaryExpression(ColumnElement): - __visit_name__: str - operator: Any - modifier: Any - element: Any - type: Any - wraps_column_expression: Any - def __init__( - self, - element, - operator: Any | None = ..., - modifier: Any | None = ..., - type_: Any | None = ..., - wraps_column_expression: bool = ..., - ) -> None: ... - def self_group(self, against: Any | None = ...): ... - -class CollectionAggregate(UnaryExpression): - inherit_cache: bool - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs) -> None: ... - -class AsBoolean(WrapsColumnExpression, UnaryExpression): - inherit_cache: bool - element: Any - type: Any - operator: Any - negate: Any - modifier: Any - wraps_column_expression: bool - def __init__(self, element, operator, negate) -> None: ... - @property - def wrapped_column_expression(self): ... - def self_group(self, against: Any | None = ...): ... - -class BinaryExpression(ColumnElement): - __visit_name__: str - left: Any - right: Any - operator: Any - type: Any - negate: Any - modifiers: Any - def __init__( - self, left, right, operator, type_: Any | None = ..., negate: Any | None = ..., modifiers: Any | None = ... - ) -> None: ... - def __bool__(self): ... - __nonzero__: Any - @property - def is_comparison(self): ... - def self_group(self, against: Any | None = ...): ... - -class Slice(ColumnElement): - __visit_name__: str - start: Any - stop: Any - step: Any - type: Any - def __init__(self, start, stop, step, _name: Any | None = ...) -> None: ... - def self_group(self, against: Any | None = ...): ... - -class IndexExpression(BinaryExpression): - inherit_cache: bool - -class GroupedElement(ClauseElement): - __visit_name__: str - def self_group(self, against: Any | None = ...): ... - -class Grouping(GroupedElement, ColumnElement): - element: Any - type: Any - def __init__(self, element) -> None: ... - def __getattr__(self, attr): ... - -RANGE_UNBOUNDED: Any -RANGE_CURRENT: Any - -class Over(ColumnElement): - __visit_name__: str - order_by: Any - partition_by: Any - element: Any - range_: Any - rows: Any - def __init__( - self, - element, - partition_by: Any | None = ..., - order_by: Any | None = ..., - range_: Any | None = ..., - rows: Any | None = ..., - ) -> None: ... - def __reduce__(self): ... - @memoized_property - def type(self): ... - -class WithinGroup(ColumnElement): - __visit_name__: str - order_by: Any - element: Any - def __init__(self, element, *order_by) -> None: ... - def __reduce__(self): ... - def over( - self, partition_by: Any | None = ..., order_by: Any | None = ..., range_: Any | None = ..., rows: Any | None = ... - ): ... - @memoized_property - def type(self): ... - -class FunctionFilter(ColumnElement): - __visit_name__: str - criterion: Any - func: Any - def __init__(self, func, *criterion) -> None: ... - def filter(self, *criterion): ... - def over( - self, partition_by: Any | None = ..., order_by: Any | None = ..., range_: Any | None = ..., rows: Any | None = ... - ): ... - def self_group(self, against: Any | None = ...): ... - @memoized_property - def type(self): ... - -class Label(roles.LabeledColumnExprRole, ColumnElement): - __visit_name__: str - name: Any - key: Any - def __init__(self, name, element, type_: Any | None = ...) -> None: ... - def __reduce__(self): ... - @memoized_property - def type(self): ... - @HasMemoized.memoized_attribute - def element(self): ... - def self_group(self, against: Any | None = ...): ... - @property - def primary_key(self): ... - @property - def foreign_keys(self): ... - -class NamedColumn(ColumnElement): - is_literal: bool - table: Any - @memoized_property - def description(self): ... - -class ColumnClause(roles.DDLReferredColumnRole, roles.LabeledColumnExprRole, roles.StrAsPlainColumnRole, Immutable, NamedColumn): - table: Any - is_literal: bool - __visit_name__: str - onupdate: Any - default: Any - server_default: Any - server_onupdate: Any - key: Any - type: Any - def __init__(self, text, type_: Any | None = ..., is_literal: bool = ..., _selectable: Any | None = ...) -> None: ... - def get_children(self, column_tables: bool = ..., **kw): ... # type: ignore[override] - @property - def entity_namespace(self): ... - -class TableValuedColumn(NamedColumn): - __visit_name__: str - scalar_alias: Any - key: Any - type: Any - def __init__(self, scalar_alias, type_) -> None: ... - -class CollationClause(ColumnElement): - __visit_name__: str - collation: Any - def __init__(self, collation) -> None: ... - -class _IdentifiedClause(Executable, ClauseElement): - __visit_name__: str - ident: Any - def __init__(self, ident) -> None: ... - -class SavepointClause(_IdentifiedClause): - __visit_name__: str - inherit_cache: bool - -class RollbackToSavepointClause(_IdentifiedClause): - __visit_name__: str - inherit_cache: bool - -class ReleaseSavepointClause(_IdentifiedClause): - __visit_name__: str - inherit_cache: bool - -class quoted_name(util.MemoizedSlots, util.text_type): - quote: Any - def __new__(cls, value, quote): ... - def __reduce__(self): ... - -class AnnotatedColumnElement(Annotated): - def __init__(self, element, values) -> None: ... - @memoized_property - def name(self): ... - @memoized_property - def table(self): ... - @memoized_property - def key(self): ... - @memoized_property - def info(self): ... - -class _truncated_label(quoted_name): - def __new__(cls, value, quote: Any | None = ...): ... - def __reduce__(self): ... - def apply_map(self, map_): ... - -class conv(_truncated_label): ... - -class _anonymous_label(_truncated_label): - @classmethod - def safe_construct(cls, seed, body, enclosing_label: Any | None = ..., sanitize_key: bool = ...): ... - def __add__(self, other): ... - def __radd__(self, other): ... - def apply_map(self, map_): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/events.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/events.pyi deleted file mode 100644 index 11765c6af968..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/events.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from .. import event - -class DDLEvents(event.Events): - def before_create(self, target, connection, **kw) -> None: ... - def after_create(self, target, connection, **kw) -> None: ... - def before_drop(self, target, connection, **kw) -> None: ... - def after_drop(self, target, connection, **kw) -> None: ... - def before_parent_attach(self, target, parent) -> None: ... - def after_parent_attach(self, target, parent) -> None: ... - def column_reflect(self, inspector, table, column_info) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/expression.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/expression.pyi deleted file mode 100644 index 79df689cef91..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/expression.pyi +++ /dev/null @@ -1,201 +0,0 @@ -from typing import Any - -from .base import PARSE_AUTOCOMMIT as PARSE_AUTOCOMMIT, ColumnCollection as ColumnCollection, Executable as Executable -from .dml import Delete as Delete, Insert as Insert, Update as Update, UpdateBase as UpdateBase, ValuesBase as ValuesBase -from .elements import ( - BinaryExpression as BinaryExpression, - BindParameter as BindParameter, - BooleanClauseList as BooleanClauseList, - Case as Case, - Cast as Cast, - ClauseElement as ClauseElement, - ClauseList as ClauseList, - CollectionAggregate as CollectionAggregate, - ColumnClause as ColumnClause, - ColumnElement as ColumnElement, - Extract as Extract, - False_ as False_, - FunctionFilter as FunctionFilter, - Grouping as Grouping, - Label as Label, - Null as Null, - Over as Over, - ReleaseSavepointClause as ReleaseSavepointClause, - RollbackToSavepointClause as RollbackToSavepointClause, - SavepointClause as SavepointClause, - TextClause as TextClause, - True_ as True_, - Tuple as Tuple, - TypeClause as TypeClause, - TypeCoerce as TypeCoerce, - UnaryExpression as UnaryExpression, - WithinGroup as WithinGroup, - _truncated_label as _truncated_label, - between as between, - collate as collate, - literal as literal, - literal_column as literal_column, - not_ as not_, - outparam as outparam, - quoted_name as quoted_name, -) -from .functions import Function as Function, FunctionElement as FunctionElement, func as func, modifier as modifier -from .lambdas import LambdaElement as LambdaElement, StatementLambdaElement as StatementLambdaElement, lambda_stmt as lambda_stmt -from .operators import ColumnOperators as ColumnOperators, Operators as Operators, custom_op as custom_op -from .selectable import ( - CTE as CTE, - LABEL_STYLE_DEFAULT as LABEL_STYLE_DEFAULT, - LABEL_STYLE_DISAMBIGUATE_ONLY as LABEL_STYLE_DISAMBIGUATE_ONLY, - LABEL_STYLE_NONE as LABEL_STYLE_NONE, - LABEL_STYLE_TABLENAME_PLUS_COL as LABEL_STYLE_TABLENAME_PLUS_COL, - Alias as Alias, - AliasedReturnsRows as AliasedReturnsRows, - CompoundSelect as CompoundSelect, - Exists as Exists, - FromClause as FromClause, - FromGrouping as FromGrouping, - GenerativeSelect as GenerativeSelect, - HasCTE as HasCTE, - HasPrefixes as HasPrefixes, - HasSuffixes as HasSuffixes, - Join as Join, - Lateral as Lateral, - ReturnsRows as ReturnsRows, - ScalarSelect as ScalarSelect, - Select as Select, - Selectable as Selectable, - SelectBase as SelectBase, - Subquery as Subquery, - TableClause as TableClause, - TableSample as TableSample, - TableValuedAlias as TableValuedAlias, - TextAsFrom as TextAsFrom, - TextualSelect as TextualSelect, - Values as Values, - subquery as subquery, -) -from .traversals import CacheKey as CacheKey -from .visitors import Visitable as Visitable - -__all__ = [ - "Alias", - "AliasedReturnsRows", - "any_", - "all_", - "CacheKey", - "ClauseElement", - "ColumnCollection", - "ColumnElement", - "CompoundSelect", - "Delete", - "FromClause", - "Insert", - "Join", - "Lateral", - "LambdaElement", - "StatementLambdaElement", - "Select", - "Selectable", - "TableClause", - "TableValuedAlias", - "Update", - "Values", - "alias", - "and_", - "asc", - "between", - "bindparam", - "case", - "cast", - "column", - "custom_op", - "cte", - "delete", - "desc", - "distinct", - "except_", - "except_all", - "exists", - "extract", - "func", - "modifier", - "collate", - "insert", - "intersect", - "intersect_all", - "join", - "label", - "lateral", - "lambda_stmt", - "literal", - "literal_column", - "not_", - "null", - "nulls_first", - "nulls_last", - "or_", - "outparam", - "outerjoin", - "over", - "select", - "table", - "text", - "tuple_", - "type_coerce", - "quoted_name", - "union", - "union_all", - "update", - "quoted_name", - "within_group", - "Subquery", - "TableSample", - "tablesample", - "values", -] - -all_: Any -any_: Any -and_: Any -alias: Any -tablesample: Any -lateral: Any -or_: Any -bindparam: Any -select: Any -text: Any -table: Any -column: Any -over: Any -within_group: Any -label: Any -case: Any -cast: Any -cte: Any -values: Any -extract: Any -tuple_: Any -except_: Any -except_all: Any -intersect: Any -intersect_all: Any -union: Any -union_all: Any -exists: Any -nulls_first: Any -nullsfirst: Any -nulls_last: Any -nullslast: Any -asc: Any -desc: Any -distinct: Any -type_coerce: Any -true: Any -false: Any -null: Any -join: Any -outerjoin: Any -insert: Any -update: Any -delete: Any -funcfilter: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/functions.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/functions.pyi deleted file mode 100644 index fe0c3ef1606f..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/functions.pyi +++ /dev/null @@ -1,223 +0,0 @@ -from typing import Any - -from ..util import HasMemoized -from .base import Executable, Generative -from .elements import BinaryExpression, ColumnElement, NamedColumn -from .selectable import FromClause -from .visitors import TraversibleType - -def register_function(identifier, fn, package: str = ...) -> None: ... - -class FunctionElement(Executable, ColumnElement, FromClause, Generative): # type: ignore[misc] - packagenames: Any - clause_expr: Any - def __init__(self, *clauses, **kwargs) -> None: ... - def scalar_table_valued(self, name, type_: Any | None = ...): ... - def table_valued(self, *expr, **kw): ... - def column_valued(self, name: Any | None = ...): ... - @property - def columns(self): ... - @property - def exported_columns(self): ... - @HasMemoized.memoized_attribute - def clauses(self): ... - def over( - self, partition_by: Any | None = ..., order_by: Any | None = ..., rows: Any | None = ..., range_: Any | None = ... - ): ... - def within_group(self, *order_by): ... - def filter(self, *criterion): ... - def as_comparison(self, left_index, right_index): ... - def within_group_type(self, within_group) -> None: ... - def alias(self, name: Any | None = ...): ... # type: ignore[override] - def select(self): ... - def scalar(self): ... - def execute(self): ... - def self_group(self, against: Any | None = ...): ... - @property - def entity_namespace(self): ... - -class FunctionAsBinary(BinaryExpression): - sql_function: Any - left_index: Any - right_index: Any - operator: Any - type: Any - negate: Any - modifiers: Any - def __init__(self, fn, left_index, right_index) -> None: ... - @property - def left(self): ... - @left.setter - def left(self, value) -> None: ... - @property - def right(self): ... - @right.setter - def right(self, value) -> None: ... - -class ScalarFunctionColumn(NamedColumn): - __visit_name__: str - is_literal: bool - table: Any - fn: Any - name: Any - type: Any - def __init__(self, fn, name, type_: Any | None = ...) -> None: ... - -class _FunctionGenerator: - opts: Any - def __init__(self, **opts) -> None: ... - def __getattr__(self, name): ... - def __call__(self, *c, **kwargs): ... - -func: Any -modifier: Any - -class Function(FunctionElement): - __visit_name__: str - type: Any - packagenames: Any - name: Any - def __init__(self, name, *clauses, **kw) -> None: ... - -class _GenericMeta(TraversibleType): - def __init__(cls, clsname, bases, clsdict) -> None: ... - -class GenericFunction: - name: Any - identifier: Any - coerce_arguments: bool - inherit_cache: bool - packagenames: Any - clause_expr: Any - type: Any - def __init__(self, *args, **kwargs) -> None: ... - -class next_value(GenericFunction): - type: Any - name: str - sequence: Any - def __init__(self, seq, **kw) -> None: ... - def compare(self, other, **kw): ... - -class AnsiFunction(GenericFunction): - inherit_cache: bool - def __init__(self, *args, **kwargs) -> None: ... - -class ReturnTypeFromArgs(GenericFunction): - inherit_cache: bool - def __init__(self, *args, **kwargs) -> None: ... - -class coalesce(ReturnTypeFromArgs): - inherit_cache: bool - -class max(ReturnTypeFromArgs): - inherit_cache: bool - -class min(ReturnTypeFromArgs): - inherit_cache: bool - -class sum(ReturnTypeFromArgs): - inherit_cache: bool - -class now(GenericFunction): - type: Any - inherit_cache: bool - -class concat(GenericFunction): - type: Any - inherit_cache: bool - -class char_length(GenericFunction): - type: Any - inherit_cache: bool - def __init__(self, arg, **kwargs) -> None: ... - -class random(GenericFunction): - inherit_cache: bool - -class count(GenericFunction): - type: Any - inherit_cache: bool - def __init__(self, expression: Any | None = ..., **kwargs) -> None: ... - -class current_date(AnsiFunction): - type: Any - inherit_cache: bool - -class current_time(AnsiFunction): - type: Any - inherit_cache: bool - -class current_timestamp(AnsiFunction): - type: Any - inherit_cache: bool - -class current_user(AnsiFunction): - type: Any - inherit_cache: bool - -class localtime(AnsiFunction): - type: Any - inherit_cache: bool - -class localtimestamp(AnsiFunction): - type: Any - inherit_cache: bool - -class session_user(AnsiFunction): - type: Any - inherit_cache: bool - -class sysdate(AnsiFunction): - type: Any - inherit_cache: bool - -class user(AnsiFunction): - type: Any - inherit_cache: bool - -class array_agg(GenericFunction): - type: Any - inherit_cache: bool - def __init__(self, *args, **kwargs) -> None: ... - -class OrderedSetAgg(GenericFunction): - array_for_multi_clause: bool - inherit_cache: bool - def within_group_type(self, within_group): ... - -class mode(OrderedSetAgg): - inherit_cache: bool - -class percentile_cont(OrderedSetAgg): - array_for_multi_clause: bool - inherit_cache: bool - -class percentile_disc(OrderedSetAgg): - array_for_multi_clause: bool - inherit_cache: bool - -class rank(GenericFunction): - type: Any - inherit_cache: bool - -class dense_rank(GenericFunction): - type: Any - inherit_cache: bool - -class percent_rank(GenericFunction): - type: Any - inherit_cache: bool - -class cume_dist(GenericFunction): - type: Any - inherit_cache: bool - -class cube(GenericFunction): - inherit_cache: bool - -class rollup(GenericFunction): - inherit_cache: bool - -class grouping_sets(GenericFunction): - inherit_cache: bool diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/lambdas.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/lambdas.pyi deleted file mode 100644 index 6f65d391b363..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/lambdas.pyi +++ /dev/null @@ -1,113 +0,0 @@ -from typing import Any - -from . import elements, roles -from .base import Options -from .operators import ColumnOperators - -class LambdaOptions(Options): - enable_tracking: bool - track_closure_variables: bool - track_on: Any - global_track_bound_values: bool - track_bound_values: bool - lambda_cache: Any - -def lambda_stmt( - lmb, - enable_tracking: bool = ..., - track_closure_variables: bool = ..., - track_on: Any | None = ..., - global_track_bound_values: bool = ..., - track_bound_values: bool = ..., - lambda_cache: Any | None = ..., -): ... - -class LambdaElement(elements.ClauseElement): - __visit_name__: str - parent_lambda: Any - fn: Any - role: Any - tracker_key: Any - opts: Any - def __init__(self, fn, role, opts=..., apply_propagate_attrs: Any | None = ...) -> None: ... - def __getattr__(self, key): ... - -class DeferredLambdaElement(LambdaElement): - lambda_args: Any - def __init__(self, fn, role, opts=..., lambda_args=...) -> None: ... - -class StatementLambdaElement(roles.AllowsLambdaRole, LambdaElement): - def __add__(self, other): ... - def add_criteria( - self, - other, - enable_tracking: bool = ..., - track_on: Any | None = ..., - track_closure_variables: bool = ..., - track_bound_values: bool = ..., - ): ... - def spoil(self): ... - -class NullLambdaStatement(roles.AllowsLambdaRole, elements.ClauseElement): - __visit_name__: str - def __init__(self, statement) -> None: ... - def __getattr__(self, key): ... - def __add__(self, other): ... - def add_criteria(self, other, **kw): ... - -class LinkedLambdaElement(StatementLambdaElement): - role: Any - opts: Any - fn: Any - parent_lambda: Any - tracker_key: Any - def __init__(self, fn, parent_lambda, opts) -> None: ... - -class AnalyzedCode: - @classmethod - def get(cls, fn, lambda_element, lambda_kw, **kw): ... - track_bound_values: Any - track_closure_variables: Any - bindparam_trackers: Any - closure_trackers: Any - build_py_wrappers: Any - def __init__(self, fn, lambda_element, opts) -> None: ... - -class NonAnalyzedFunction: - closure_bindparams: Any - bindparam_trackers: Any - expr: Any - def __init__(self, expr) -> None: ... - @property - def expected_expr(self): ... - -class AnalyzedFunction: - analyzed_code: Any - fn: Any - closure_pywrappers: Any - tracker_instrumented_fn: Any - expr: Any - bindparam_trackers: Any - expected_expr: Any - is_sequence: Any - propagate_attrs: Any - closure_bindparams: Any - def __init__(self, analyzed_code, lambda_element, apply_propagate_attrs, fn) -> None: ... - -class PyWrapper(ColumnOperators): - fn: Any - track_bound_values: Any - def __init__( - self, fn, name, to_evaluate, closure_index: Any | None = ..., getter: Any | None = ..., track_bound_values: bool = ... - ) -> None: ... - def __call__(self, *arg, **kw): ... - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... - def __clause_element__(self): ... - def __bool__(self): ... - def __nonzero__(self): ... - def __getattribute__(self, key): ... - def __iter__(self): ... - def __getitem__(self, key): ... - -def insp(lmb): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/naming.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/naming.pyi deleted file mode 100644 index 50bdacf72a28..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/naming.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from .elements import conv as conv - -class ConventionDict: - const: Any - table: Any - convention: Any - def __init__(self, const, table, convention) -> None: ... - def __getitem__(self, key): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/operators.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/operators.pyi deleted file mode 100644 index 07289f632835..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/operators.pyi +++ /dev/null @@ -1,190 +0,0 @@ -from operator import truediv -from typing import Any - -div = truediv - -class Operators: - def __and__(self, other): ... - def __or__(self, other): ... - def __invert__(self): ... - def op(self, opstring, precedence: int = ..., is_comparison: bool = ..., return_type: Any | None = ...): ... - def bool_op(self, opstring, precedence: int = ...): ... - def operate(self, op, *other, **kwargs) -> None: ... - def reverse_operate(self, op, other, **kwargs) -> None: ... - -class custom_op: - __name__: str - opstring: Any - precedence: Any - is_comparison: Any - natural_self_precedent: Any - eager_grouping: Any - return_type: Any - def __init__( - self, - opstring, - precedence: int = ..., - is_comparison: bool = ..., - return_type: Any | None = ..., - natural_self_precedent: bool = ..., - eager_grouping: bool = ..., - ) -> None: ... - def __eq__(self, other): ... - def __hash__(self): ... - def __call__(self, left, right, **kw): ... - -class ColumnOperators(Operators): - timetuple: Any - def __lt__(self, other): ... - def __le__(self, other): ... - __hash__: Any - def __eq__(self, other): ... - def __ne__(self, other): ... - def is_distinct_from(self, other): ... - def is_not_distinct_from(self, other): ... - isnot_distinct_from: Any - def __gt__(self, other): ... - def __ge__(self, other): ... - def __neg__(self): ... - def __contains__(self, other): ... - def __getitem__(self, index): ... - def __lshift__(self, other): ... - def __rshift__(self, other): ... - def concat(self, other): ... - def like(self, other, escape: Any | None = ...): ... - def ilike(self, other, escape: Any | None = ...): ... - def in_(self, other): ... - def not_in(self, other): ... - notin_: Any - def not_like(self, other, escape: Any | None = ...): ... - notlike: Any - def not_ilike(self, other, escape: Any | None = ...): ... - notilike: Any - def is_(self, other): ... - def is_not(self, other): ... - isnot: Any - def startswith(self, other, **kwargs): ... - def endswith(self, other, **kwargs): ... - def contains(self, other, **kwargs): ... - def match(self, other, **kwargs): ... - def regexp_match(self, pattern, flags: Any | None = ...): ... - def regexp_replace(self, pattern, replacement, flags: Any | None = ...): ... - def desc(self): ... - def asc(self): ... - def nulls_first(self): ... - nullsfirst: Any - def nulls_last(self): ... - nullslast: Any - def collate(self, collation): ... - def __radd__(self, other): ... - def __rsub__(self, other): ... - def __rmul__(self, other): ... - def __rdiv__(self, other): ... - def __rmod__(self, other): ... - def between(self, cleft, cright, symmetric: bool = ...): ... - def distinct(self): ... - def any_(self): ... - def all_(self): ... - def __add__(self, other): ... - def __sub__(self, other): ... - def __mul__(self, other): ... - def __div__(self, other): ... - def __mod__(self, other): ... - def __truediv__(self, other): ... - def __rtruediv__(self, other): ... - -def commutative_op(fn): ... -def comparison_op(fn): ... -def from_() -> None: ... -def function_as_comparison_op() -> None: ... -def as_() -> None: ... -def exists() -> None: ... -def is_true(a) -> None: ... - -istrue = is_true - -def is_false(a) -> None: ... - -isfalse = is_false - -def is_distinct_from(a, b): ... -def is_not_distinct_from(a, b): ... - -isnot_distinct_from = is_not_distinct_from - -def is_(a, b): ... -def is_not(a, b): ... - -isnot = is_not - -def collate(a, b): ... -def op(a, opstring, b): ... -def like_op(a, b, escape: Any | None = ...): ... -def not_like_op(a, b, escape: Any | None = ...): ... - -notlike_op = not_like_op - -def ilike_op(a, b, escape: Any | None = ...): ... -def not_ilike_op(a, b, escape: Any | None = ...): ... - -notilike_op = not_ilike_op - -def between_op(a, b, c, symmetric: bool = ...): ... -def not_between_op(a, b, c, symmetric: bool = ...): ... - -notbetween_op = not_between_op - -def in_op(a, b): ... -def not_in_op(a, b): ... - -notin_op = not_in_op - -def distinct_op(a): ... -def any_op(a): ... -def all_op(a): ... -def startswith_op(a, b, escape: Any | None = ..., autoescape: bool = ...): ... -def not_startswith_op(a, b, escape: Any | None = ..., autoescape: bool = ...): ... - -notstartswith_op = not_startswith_op - -def endswith_op(a, b, escape: Any | None = ..., autoescape: bool = ...): ... -def not_endswith_op(a, b, escape: Any | None = ..., autoescape: bool = ...): ... - -notendswith_op = not_endswith_op - -def contains_op(a, b, escape: Any | None = ..., autoescape: bool = ...): ... -def not_contains_op(a, b, escape: Any | None = ..., autoescape: bool = ...): ... - -notcontains_op = not_contains_op - -def match_op(a, b, **kw): ... -def regexp_match_op(a, b, flags: Any | None = ...): ... -def not_regexp_match_op(a, b, flags: Any | None = ...): ... -def regexp_replace_op(a, b, replacement, flags: Any | None = ...): ... -def not_match_op(a, b, **kw): ... - -notmatch_op = not_match_op - -def comma_op(a, b) -> None: ... -def filter_op(a, b) -> None: ... -def concat_op(a, b): ... -def desc_op(a): ... -def asc_op(a): ... -def nulls_first_op(a): ... - -nullsfirst_op = nulls_first_op - -def nulls_last_op(a): ... - -nullslast_op = nulls_last_op - -def json_getitem_op(a, b) -> None: ... -def json_path_getitem_op(a, b) -> None: ... -def is_comparison(op): ... -def is_commutative(op): ... -def is_ordering_modifier(op): ... -def is_natural_self_precedent(op): ... -def is_boolean(op): ... -def mirror(op): ... -def is_associative(op): ... -def is_precedent(operator, against): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/roles.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/roles.pyi deleted file mode 100644 index e7c290b149c3..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/roles.pyi +++ /dev/null @@ -1,57 +0,0 @@ -class SQLRole: - allows_lambda: bool - uses_inspection: bool - -class UsesInspection: - uses_inspection: bool - -class AllowsLambdaRole: - allows_lambda: bool - -class HasCacheKeyRole(SQLRole): ... -class ExecutableOptionRole(SQLRole): ... -class LiteralValueRole(SQLRole): ... -class ColumnArgumentRole(SQLRole): ... -class ColumnArgumentOrKeyRole(ColumnArgumentRole): ... -class StrAsPlainColumnRole(ColumnArgumentRole): ... -class ColumnListRole(SQLRole): ... -class TruncatedLabelRole(SQLRole): ... -class ColumnsClauseRole(AllowsLambdaRole, UsesInspection, ColumnListRole): ... -class LimitOffsetRole(SQLRole): ... -class ByOfRole(ColumnListRole): ... -class GroupByRole(AllowsLambdaRole, UsesInspection, ByOfRole): ... -class OrderByRole(AllowsLambdaRole, ByOfRole): ... -class StructuralRole(SQLRole): ... -class StatementOptionRole(StructuralRole): ... -class OnClauseRole(AllowsLambdaRole, StructuralRole): ... -class WhereHavingRole(OnClauseRole): ... -class ExpressionElementRole(SQLRole): ... -class ConstExprRole(ExpressionElementRole): ... -class LabeledColumnExprRole(ExpressionElementRole): ... -class BinaryElementRole(ExpressionElementRole): ... -class InElementRole(SQLRole): ... -class JoinTargetRole(AllowsLambdaRole, UsesInspection, StructuralRole): ... -class FromClauseRole(ColumnsClauseRole, JoinTargetRole): ... - -class StrictFromClauseRole(FromClauseRole): - @property - def description(self) -> None: ... - -class AnonymizedFromClauseRole(StrictFromClauseRole): ... -class ReturnsRowsRole(SQLRole): ... -class StatementRole(SQLRole): ... - -class SelectStatementRole(StatementRole, ReturnsRowsRole): - def subquery(self) -> None: ... - -class HasCTERole(ReturnsRowsRole): ... -class IsCTERole(SQLRole): ... -class CompoundElementRole(AllowsLambdaRole, SQLRole): ... -class DMLRole(StatementRole): ... -class DMLTableRole(FromClauseRole): ... -class DMLColumnRole(SQLRole): ... -class DMLSelectRole(SQLRole): ... -class DDLRole(StatementRole): ... -class DDLExpressionRole(StructuralRole): ... -class DDLConstraintColumnRole(SQLRole): ... -class DDLReferredColumnRole(DDLConstraintColumnRole): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/schema.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/schema.pyi deleted file mode 100644 index 66b4197d64f2..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/schema.pyi +++ /dev/null @@ -1,375 +0,0 @@ -from typing import Any - -from ..util import memoized_property -from . import visitors -from .base import DialectKWArgs, Executable, SchemaEventTarget -from .elements import ColumnClause -from .selectable import TableClause - -RETAIN_SCHEMA: Any -BLANK_SCHEMA: Any -NULL_UNSPECIFIED: Any - -class SchemaItem(SchemaEventTarget, visitors.Visitable): - __visit_name__: str - create_drop_stringify_dialect: str - @memoized_property - def info(self): ... - -class Table(DialectKWArgs, SchemaItem, TableClause): - __visit_name__: str - constraints: Any - indexes: Any - def __new__(cls, *args, **kw): ... - def __init__(self, *args, **kw) -> None: ... - @property - def foreign_key_constraints(self): ... - @property - def key(self): ... - @property - def bind(self): ... - def add_is_dependent_on(self, table) -> None: ... - def append_column(self, column, replace_existing: bool = ...) -> None: ... # type: ignore[override] - def append_constraint(self, constraint) -> None: ... - def exists(self, bind: Any | None = ...): ... - def create(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - def drop(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - def tometadata(self, metadata, schema=..., referred_schema_fn: Any | None = ..., name: Any | None = ...): ... - def to_metadata(self, metadata, schema=..., referred_schema_fn: Any | None = ..., name: Any | None = ...): ... - -class Column(DialectKWArgs, SchemaItem, ColumnClause): - __visit_name__: str - inherit_cache: bool - key: Any - primary_key: Any - nullable: Any - default: Any - server_default: Any - server_onupdate: Any - index: Any - unique: Any - system: Any - doc: Any - onupdate: Any - autoincrement: Any - constraints: Any - foreign_keys: Any - comment: Any - computed: Any - identity: Any - info: Any - def __init__(self, *args, **kwargs) -> None: ... - def references(self, column): ... - def append_foreign_key(self, fk) -> None: ... - def copy(self, **kw): ... - -class ForeignKey(DialectKWArgs, SchemaItem): - __visit_name__: str - constraint: Any - parent: Any - use_alter: Any - name: Any - onupdate: Any - ondelete: Any - deferrable: Any - initially: Any - link_to_name: Any - match: Any - info: Any - def __init__( - self, - column, - _constraint: Any | None = ..., - use_alter: bool = ..., - name: Any | None = ..., - onupdate: Any | None = ..., - ondelete: Any | None = ..., - deferrable: Any | None = ..., - initially: Any | None = ..., - link_to_name: bool = ..., - match: Any | None = ..., - info: Any | None = ..., - **dialect_kw, - ) -> None: ... - def copy(self, schema: Any | None = ..., **kw): ... - target_fullname: Any - def references(self, table): ... - def get_referent(self, table): ... - @memoized_property - def column(self): ... - -class DefaultGenerator(Executable, SchemaItem): - __visit_name__: str - is_sequence: bool - is_server_default: bool - column: Any - for_update: Any - def __init__(self, for_update: bool = ...) -> None: ... - def execute(self, bind: Any | None = ...): ... # type: ignore[override] - @property - def bind(self): ... - -class ColumnDefault(DefaultGenerator): - arg: Any - def __init__(self, arg, **kwargs) -> None: ... - @memoized_property - def is_callable(self): ... - @memoized_property - def is_clause_element(self): ... - @memoized_property - def is_scalar(self): ... - -class IdentityOptions: - start: Any - increment: Any - minvalue: Any - maxvalue: Any - nominvalue: Any - nomaxvalue: Any - cycle: Any - cache: Any - order: Any - def __init__( - self, - start: Any | None = ..., - increment: Any | None = ..., - minvalue: Any | None = ..., - maxvalue: Any | None = ..., - nominvalue: Any | None = ..., - nomaxvalue: Any | None = ..., - cycle: Any | None = ..., - cache: Any | None = ..., - order: Any | None = ..., - ) -> None: ... - -class Sequence(IdentityOptions, DefaultGenerator): - __visit_name__: str - is_sequence: bool - name: Any - optional: Any - schema: Any - metadata: Any - data_type: Any - def __init__( - self, - name, - start: Any | None = ..., - increment: Any | None = ..., - minvalue: Any | None = ..., - maxvalue: Any | None = ..., - nominvalue: Any | None = ..., - nomaxvalue: Any | None = ..., - cycle: Any | None = ..., - schema: Any | None = ..., - cache: Any | None = ..., - order: Any | None = ..., - data_type: Any | None = ..., - optional: bool = ..., - quote: Any | None = ..., - metadata: Any | None = ..., - quote_schema: Any | None = ..., - for_update: bool = ..., - ) -> None: ... - @memoized_property - def is_callable(self): ... - @memoized_property - def is_clause_element(self): ... - def next_value(self): ... - @property - def bind(self): ... - def create(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - def drop(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - -class FetchedValue(SchemaEventTarget): - is_server_default: bool - reflected: bool - has_argument: bool - is_clause_element: bool - for_update: Any - def __init__(self, for_update: bool = ...) -> None: ... - -class DefaultClause(FetchedValue): - has_argument: bool - arg: Any - reflected: Any - def __init__(self, arg, for_update: bool = ..., _reflected: bool = ...) -> None: ... - -class Constraint(DialectKWArgs, SchemaItem): - __visit_name__: str - name: Any - deferrable: Any - initially: Any - info: Any - def __init__( - self, - name: Any | None = ..., - deferrable: Any | None = ..., - initially: Any | None = ..., - _create_rule: Any | None = ..., - info: Any | None = ..., - _type_bound: bool = ..., - **dialect_kw, - ) -> None: ... - @property - def table(self): ... - def copy(self, **kw): ... - -class ColumnCollectionMixin: - columns: Any - def __init__(self, *columns, **kw) -> None: ... - -class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint): - def __init__(self, *columns, **kw) -> None: ... - columns: Any - def __contains__(self, x): ... - def copy(self, target_table: Any | None = ..., **kw): ... - def contains_column(self, col): ... - def __iter__(self): ... - def __len__(self): ... - -class CheckConstraint(ColumnCollectionConstraint): - __visit_name__: str - sqltext: Any - def __init__( - self, - sqltext, - name: Any | None = ..., - deferrable: Any | None = ..., - initially: Any | None = ..., - table: Any | None = ..., - info: Any | None = ..., - _create_rule: Any | None = ..., - _autoattach: bool = ..., - _type_bound: bool = ..., - **kw, - ) -> None: ... - @property - def is_column_level(self): ... - def copy(self, target_table: Any | None = ..., **kw): ... - -class ForeignKeyConstraint(ColumnCollectionConstraint): - __visit_name__: str - onupdate: Any - ondelete: Any - link_to_name: Any - use_alter: Any - match: Any - elements: Any - def __init__( - self, - columns, - refcolumns, - name: Any | None = ..., - onupdate: Any | None = ..., - ondelete: Any | None = ..., - deferrable: Any | None = ..., - initially: Any | None = ..., - use_alter: bool = ..., - link_to_name: bool = ..., - match: Any | None = ..., - table: Any | None = ..., - info: Any | None = ..., - **dialect_kw, - ) -> None: ... - columns: Any - @property - def referred_table(self): ... - @property - def column_keys(self): ... - def copy(self, schema: Any | None = ..., target_table: Any | None = ..., **kw): ... # type: ignore[override] - -class PrimaryKeyConstraint(ColumnCollectionConstraint): - __visit_name__: str - def __init__(self, *columns, **kw) -> None: ... - @property - def columns_autoinc_first(self): ... - -class UniqueConstraint(ColumnCollectionConstraint): - __visit_name__: str - -class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): - __visit_name__: str - table: Any - name: Any - unique: Any - info: Any - expressions: Any - def __init__(self, name, *expressions, **kw) -> None: ... - @property - def bind(self): ... - def create(self, bind: Any | None = ..., checkfirst: bool = ...): ... - def drop(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - -DEFAULT_NAMING_CONVENTION: Any - -class MetaData(SchemaItem): - __visit_name__: str - tables: Any - schema: Any - naming_convention: Any - info: Any - def __init__( - self, - bind: Any | None = ..., - schema: Any | None = ..., - quote_schema: Any | None = ..., - naming_convention: Any | None = ..., - info: Any | None = ..., - ) -> None: ... - def __contains__(self, table_or_key): ... - def is_bound(self): ... - bind: Any - def clear(self) -> None: ... - def remove(self, table) -> None: ... - @property - def sorted_tables(self): ... - def reflect( - self, - bind: Any | None = ..., - schema: Any | None = ..., - views: bool = ..., - only: Any | None = ..., - extend_existing: bool = ..., - autoload_replace: bool = ..., - resolve_fks: bool = ..., - **dialect_kwargs, - ) -> None: ... - def create_all(self, bind: Any | None = ..., tables: Any | None = ..., checkfirst: bool = ...) -> None: ... - def drop_all(self, bind: Any | None = ..., tables: Any | None = ..., checkfirst: bool = ...) -> None: ... - -class ThreadLocalMetaData(MetaData): - __visit_name__: str - context: Any - def __init__(self) -> None: ... - bind: Any - def is_bound(self): ... - def dispose(self) -> None: ... - -class Computed(FetchedValue, SchemaItem): - __visit_name__: str - sqltext: Any - persisted: Any - column: Any - def __init__(self, sqltext, persisted: Any | None = ...) -> None: ... - def copy(self, target_table: Any | None = ..., **kw): ... - -class Identity(IdentityOptions, FetchedValue, SchemaItem): - __visit_name__: str - always: Any - on_null: Any - column: Any - def __init__( - self, - always: bool = ..., - on_null: Any | None = ..., - start: Any | None = ..., - increment: Any | None = ..., - minvalue: Any | None = ..., - maxvalue: Any | None = ..., - nominvalue: Any | None = ..., - nomaxvalue: Any | None = ..., - cycle: Any | None = ..., - cache: Any | None = ..., - order: Any | None = ..., - ) -> None: ... - def copy(self, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/selectable.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/selectable.pyi deleted file mode 100644 index 84ac9413ac6c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/selectable.pyi +++ /dev/null @@ -1,416 +0,0 @@ -from typing import Any - -from .. import util -from ..util import HasMemoized, memoized_property -from . import roles, traversals, visitors -from .annotation import Annotated, SupportsCloneAnnotations -from .base import CacheableOptions, CompileState, Executable, Generative, HasCompileState, Immutable -from .elements import ( - BindParameter as BindParameter, - BooleanClauseList as BooleanClauseList, - ClauseElement as ClauseElement, - ClauseList as ClauseList, - ColumnClause as ColumnClause, - GroupedElement as GroupedElement, - Grouping as Grouping, - TableValuedColumn as TableValuedColumn, - UnaryExpression as UnaryExpression, - literal_column as literal_column, -) - -class _OffsetLimitParam(BindParameter): - inherit_cache: bool - -def subquery(alias, *args, **kwargs): ... - -class ReturnsRows(roles.ReturnsRowsRole, ClauseElement): - @property - def selectable(self): ... - @property - def exported_columns(self) -> None: ... - -class Selectable(ReturnsRows): - __visit_name__: str - is_selectable: bool - def lateral(self, name: Any | None = ...): ... - def replace_selectable(self, old, alias): ... - def corresponding_column(self, column, require_embedded: bool = ...): ... - -class HasPrefixes: - def prefix_with(self, *expr, **kw) -> None: ... - -class HasSuffixes: - def suffix_with(self, *expr, **kw) -> None: ... - -class HasHints: - def with_statement_hint(self, text, dialect_name: str = ...): ... - def with_hint(self, selectable, text, dialect_name: str = ...) -> None: ... - -class FromClause(roles.AnonymizedFromClauseRole, Selectable): - __visit_name__: str - named_with_column: bool - schema: Any - is_selectable: bool - def select(self, whereclause: Any | None = ..., **kwargs): ... - def join(self, right, onclause: Any | None = ..., isouter: bool = ..., full: bool = ...): ... - def outerjoin(self, right, onclause: Any | None = ..., full: bool = ...): ... - def alias(self, name: Any | None = ..., flat: bool = ...): ... - def table_valued(self): ... - def tablesample(self, sampling, name: Any | None = ..., seed: Any | None = ...): ... - def is_derived_from(self, fromclause): ... - @property - def description(self): ... - @property - def exported_columns(self): ... - @memoized_property - def columns(self): ... - @property - def entity_namespace(self): ... - @memoized_property - def primary_key(self): ... - @memoized_property - def foreign_keys(self): ... - c: Any - -LABEL_STYLE_NONE: Any -LABEL_STYLE_TABLENAME_PLUS_COL: Any -LABEL_STYLE_DISAMBIGUATE_ONLY: Any -LABEL_STYLE_DEFAULT: Any - -class Join(roles.DMLTableRole, FromClause): - __visit_name__: str - left: Any - right: Any - onclause: Any - isouter: Any - full: Any - def __init__(self, left, right, onclause: Any | None = ..., isouter: bool = ..., full: bool = ...) -> None: ... - @property - def description(self): ... - def is_derived_from(self, fromclause): ... - def self_group(self, against: Any | None = ...): ... - def select(self, whereclause: Any | None = ..., **kwargs): ... - @property - def bind(self): ... - def alias(self, name: Any | None = ..., flat: bool = ...): ... - -class NoInit: - def __init__(self, *arg, **kw) -> None: ... - -class AliasedReturnsRows(NoInit, FromClause): - named_with_column: bool - @property - def description(self): ... - @property - def original(self): ... - def is_derived_from(self, fromclause): ... - @property - def bind(self): ... - -class Alias(roles.DMLTableRole, AliasedReturnsRows): - __visit_name__: str - inherit_cache: bool - -class TableValuedAlias(Alias): - __visit_name__: str - @HasMemoized.memoized_attribute - def column(self): ... - def alias(self, name: Any | None = ...): ... # type: ignore[override] - def lateral(self, name: Any | None = ...): ... - def render_derived(self, name: Any | None = ..., with_types: bool = ...): ... - -class Lateral(AliasedReturnsRows): - __visit_name__: str - inherit_cache: bool - -class TableSample(AliasedReturnsRows): - __visit_name__: str - -class CTE(roles.DMLTableRole, roles.IsCTERole, Generative, HasPrefixes, HasSuffixes, AliasedReturnsRows): - __visit_name__: str - def alias(self, name: Any | None = ..., flat: bool = ...): ... - def union(self, *other): ... - def union_all(self, *other): ... - -class HasCTE(roles.HasCTERole): - def add_cte(self, cte) -> None: ... - def cte(self, name: Any | None = ..., recursive: bool = ..., nesting: bool = ...): ... - -class Subquery(AliasedReturnsRows): - __visit_name__: str - inherit_cache: bool - def as_scalar(self): ... - -class FromGrouping(GroupedElement, FromClause): - element: Any - def __init__(self, element) -> None: ... - @property - def columns(self): ... - @property - def primary_key(self): ... - @property - def foreign_keys(self): ... - def is_derived_from(self, element): ... - def alias(self, **kw): ... - -class TableClause(roles.DMLTableRole, Immutable, FromClause): - __visit_name__: str - named_with_column: bool - implicit_returning: bool - name: Any - primary_key: Any - foreign_keys: Any - schema: Any - fullname: Any - def __init__(self, name, *columns, **kw) -> None: ... - @memoized_property - def description(self): ... - def append_column(self, c, **kw) -> None: ... - def insert(self, values: Any | None = ..., inline: bool = ..., **kwargs): ... - def update(self, whereclause: Any | None = ..., values: Any | None = ..., inline: bool = ..., **kwargs): ... - def delete(self, whereclause: Any | None = ..., **kwargs): ... - -class ForUpdateArg(ClauseElement): - def __eq__(self, other): ... - def __ne__(self, other): ... - def __hash__(self): ... - nowait: Any - read: Any - skip_locked: Any - key_share: Any - of: Any - def __init__( - self, nowait: bool = ..., read: bool = ..., of: Any | None = ..., skip_locked: bool = ..., key_share: bool = ... - ) -> None: ... - -class Values(Generative, FromClause): - named_with_column: bool - __visit_name__: str - name: Any - literal_binds: Any - def __init__(self, *columns, **kw) -> None: ... - def alias(self, name, **kw) -> None: ... # type: ignore[override] - def lateral(self, name: Any | None = ...) -> None: ... - def data(self, values) -> None: ... - -class SelectBase( - roles.SelectStatementRole, - roles.DMLSelectRole, - roles.CompoundElementRole, - roles.InElementRole, - HasCTE, - Executable, - SupportsCloneAnnotations, - Selectable, -): - is_select: bool - @property - def selected_columns(self) -> None: ... - @property - def exported_columns(self): ... - @property - def c(self): ... - @property - def columns(self): ... - def select(self, *arg, **kw): ... - def as_scalar(self): ... - def exists(self): ... - def scalar_subquery(self): ... - def label(self, name): ... - def lateral(self, name: Any | None = ...): ... - def subquery(self, name: Any | None = ...): ... - def alias(self, name: Any | None = ..., flat: bool = ...): ... - -class SelectStatementGrouping(GroupedElement, SelectBase): - __visit_name__: str - element: Any - def __init__(self, element) -> None: ... - def get_label_style(self): ... - def set_label_style(self, label_style): ... - @property - def select_statement(self): ... - def self_group(self, against: Any | None = ...): ... - @property - def selected_columns(self): ... - -class DeprecatedSelectBaseGenerations: - def append_order_by(self, *clauses) -> None: ... - def append_group_by(self, *clauses) -> None: ... - -class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): - def __init__( - self, - _label_style=..., - use_labels: bool = ..., - limit: Any | None = ..., - offset: Any | None = ..., - order_by: Any | None = ..., - group_by: Any | None = ..., - bind: Any | None = ..., - ) -> None: ... - def with_for_update( - self, nowait: bool = ..., read: bool = ..., of: Any | None = ..., skip_locked: bool = ..., key_share: bool = ... - ) -> None: ... - def get_label_style(self): ... - def set_label_style(self, style): ... - def apply_labels(self): ... - def limit(self, limit) -> None: ... - def fetch(self, count, with_ties: bool = ..., percent: bool = ...) -> None: ... - def offset(self, offset) -> None: ... - def slice(self, start, stop) -> None: ... - def order_by(self, *clauses) -> None: ... - def group_by(self, *clauses) -> None: ... - -class CompoundSelectState(CompileState): ... - -class CompoundSelect(HasCompileState, GenerativeSelect): - __visit_name__: str - UNION: Any - UNION_ALL: Any - EXCEPT: Any - EXCEPT_ALL: Any - INTERSECT: Any - INTERSECT_ALL: Any - keyword: Any - selects: Any - def __init__(self, keyword, *selects, **kwargs) -> None: ... - def self_group(self, against: Any | None = ...): ... - def is_derived_from(self, fromclause): ... - @property - def selected_columns(self): ... - @property - def bind(self): ... - @bind.setter - def bind(self, bind) -> None: ... - -class DeprecatedSelectGenerations: - def append_correlation(self, fromclause) -> None: ... - def append_column(self, column) -> None: ... - def append_prefix(self, clause) -> None: ... - def append_whereclause(self, whereclause) -> None: ... - def append_having(self, having) -> None: ... - def append_from(self, fromclause) -> None: ... - -class SelectState(util.MemoizedSlots, CompileState): - class default_select_compile_options(CacheableOptions): ... - statement: Any - from_clauses: Any - froms: Any - columns_plus_names: Any - def __init__(self, statement, compiler, **kw) -> None: ... - @classmethod - def get_column_descriptions(cls, statement) -> None: ... - @classmethod - def from_statement(cls, statement, from_statement) -> None: ... - @classmethod - def get_columns_clause_froms(cls, statement): ... - @classmethod - def determine_last_joined_entity(cls, stmt): ... - @classmethod - def all_selected_columns(cls, statement): ... - -class _SelectFromElements: ... - -class _MemoizedSelectEntities(traversals.HasCacheKey, traversals.HasCopyInternals, visitors.Traversible): - __visit_name__: str - -class Select( - HasPrefixes, HasSuffixes, HasHints, HasCompileState, DeprecatedSelectGenerations, _SelectFromElements, GenerativeSelect -): - __visit_name__: str - @classmethod - def create_legacy_select( - cls, - columns: Any | None = ..., - whereclause: Any | None = ..., - from_obj: Any | None = ..., - distinct: bool = ..., - having: Any | None = ..., - correlate: bool = ..., - prefixes: Any | None = ..., - suffixes: Any | None = ..., - **kwargs, - ): ... - def __init__(self) -> None: ... - def filter(self, *criteria): ... - def filter_by(self, **kwargs): ... - @property - def column_descriptions(self): ... - def from_statement(self, statement): ... - def join(self, target, onclause: Any | None = ..., isouter: bool = ..., full: bool = ...) -> None: ... - def outerjoin_from(self, from_, target, onclause: Any | None = ..., full: bool = ...): ... - def join_from(self, from_, target, onclause: Any | None = ..., isouter: bool = ..., full: bool = ...) -> None: ... - def outerjoin(self, target, onclause: Any | None = ..., full: bool = ...): ... - def get_final_froms(self): ... - @property - def froms(self): ... - @property - def columns_clause_froms(self): ... - @property - def inner_columns(self): ... - def is_derived_from(self, fromclause): ... - def get_children(self, **kwargs): ... - def add_columns(self, *columns) -> None: ... - def column(self, column): ... - def reduce_columns(self, only_synonyms: bool = ...): ... - def with_only_columns(self, *columns, **kw) -> None: ... - @property - def whereclause(self): ... - def where(self, *whereclause) -> None: ... - def having(self, having) -> None: ... - def distinct(self, *expr) -> None: ... - def select_from(self, *froms) -> None: ... - def correlate(self, *fromclauses) -> None: ... - def correlate_except(self, *fromclauses) -> None: ... - @HasMemoized.memoized_attribute - def selected_columns(self): ... - def self_group(self, against: Any | None = ...): ... - def union(self, *other, **kwargs): ... - def union_all(self, *other, **kwargs): ... - def except_(self, *other, **kwargs): ... - def except_all(self, *other, **kwargs): ... - def intersect(self, *other, **kwargs): ... - def intersect_all(self, *other, **kwargs): ... - @property - def bind(self): ... - @bind.setter - def bind(self, bind) -> None: ... - -class ScalarSelect(roles.InElementRole, Generative, Grouping): - inherit_cache: bool - element: Any - type: Any - def __init__(self, element) -> None: ... - @property - def columns(self) -> None: ... - c: Any - def where(self, crit) -> None: ... - def self_group(self, **kwargs): ... - def correlate(self, *fromclauses) -> None: ... - def correlate_except(self, *fromclauses) -> None: ... - -class Exists(UnaryExpression): - inherit_cache: bool - def __init__(self, *args, **kwargs) -> None: ... - def select(self, whereclause: Any | None = ..., **kwargs): ... - def correlate(self, *fromclause): ... - def correlate_except(self, *fromclause): ... - def select_from(self, *froms): ... - def where(self, *clause): ... - -class TextualSelect(SelectBase): - __visit_name__: str - is_text: bool - is_select: bool - element: Any - column_args: Any - positional: Any - def __init__(self, text, columns, positional: bool = ...) -> None: ... - @HasMemoized.memoized_attribute - def selected_columns(self): ... - def bindparams(self, *binds, **bind_as_values) -> None: ... - -TextAsFrom = TextualSelect - -class AnnotatedFromClause(Annotated): - def __init__(self, element, values) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/sqltypes.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/sqltypes.pyi deleted file mode 100644 index f26c34139a71..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/sqltypes.pyi +++ /dev/null @@ -1,356 +0,0 @@ -from typing import Any - -from .base import SchemaEventTarget -from .traversals import HasCacheKey -from .type_api import ( - Emulated as Emulated, - NativeForEmulated as NativeForEmulated, - TypeDecorator as TypeDecorator, - TypeEngine as TypeEngine, - Variant as Variant, - to_instance as to_instance, -) - -class _LookupExpressionAdapter: - class Comparator(TypeEngine.Comparator): ... - comparator_factory: Any - -class Concatenable: - class Comparator(TypeEngine.Comparator): ... - comparator_factory: Any - -class Indexable: - class Comparator(TypeEngine.Comparator): - def __getitem__(self, index): ... - comparator_factory: Any - -class String(Concatenable, TypeEngine): - __visit_name__: str - RETURNS_UNICODE: Any - RETURNS_BYTES: Any - RETURNS_CONDITIONAL: Any - RETURNS_UNKNOWN: Any - length: Any - collation: Any - def __init__( - self, - length: Any | None = ..., - collation: Any | None = ..., - convert_unicode: bool = ..., - unicode_error: Any | None = ..., - _warn_on_bytestring: bool = ..., - _expect_unicode: bool = ..., - ) -> None: ... - def literal_processor(self, dialect): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - @property - def python_type(self): ... - def get_dbapi_type(self, dbapi): ... - -class Text(String): - __visit_name__: str - -class Unicode(String): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class UnicodeText(Text): - __visit_name__: str - def __init__(self, length: Any | None = ..., **kwargs) -> None: ... - -class Integer(_LookupExpressionAdapter, TypeEngine): - __visit_name__: str - def get_dbapi_type(self, dbapi): ... - @property - def python_type(self): ... - def literal_processor(self, dialect): ... - -class SmallInteger(Integer): - __visit_name__: str - -class BigInteger(Integer): - __visit_name__: str - -class Numeric(_LookupExpressionAdapter, TypeEngine): - __visit_name__: str - precision: Any - scale: Any - decimal_return_scale: Any - asdecimal: Any - def __init__( - self, precision: Any | None = ..., scale: Any | None = ..., decimal_return_scale: Any | None = ..., asdecimal: bool = ... - ) -> None: ... - def get_dbapi_type(self, dbapi): ... - def literal_processor(self, dialect): ... - @property - def python_type(self): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class Float(Numeric): - __visit_name__: str - scale: Any - precision: Any - asdecimal: Any - decimal_return_scale: Any - def __init__(self, precision: Any | None = ..., asdecimal: bool = ..., decimal_return_scale: Any | None = ...) -> None: ... - def result_processor(self, dialect, coltype): ... - -class DateTime(_LookupExpressionAdapter, TypeEngine): - __visit_name__: str - timezone: Any - def __init__(self, timezone: bool = ...) -> None: ... - def get_dbapi_type(self, dbapi): ... - @property - def python_type(self): ... - -class Date(_LookupExpressionAdapter, TypeEngine): - __visit_name__: str - def get_dbapi_type(self, dbapi): ... - @property - def python_type(self): ... - -class Time(_LookupExpressionAdapter, TypeEngine): - __visit_name__: str - timezone: Any - def __init__(self, timezone: bool = ...) -> None: ... - def get_dbapi_type(self, dbapi): ... - @property - def python_type(self): ... - -class _Binary(TypeEngine): - length: Any - def __init__(self, length: Any | None = ...) -> None: ... - def literal_processor(self, dialect): ... - @property - def python_type(self): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - def coerce_compared_value(self, op, value): ... - def get_dbapi_type(self, dbapi): ... - -class LargeBinary(_Binary): - __visit_name__: str - def __init__(self, length: Any | None = ...) -> None: ... - -class SchemaType(SchemaEventTarget): - name: Any - schema: Any - metadata: Any - inherit_schema: Any - def __init__( - self, - name: Any | None = ..., - schema: Any | None = ..., - metadata: Any | None = ..., - inherit_schema: bool = ..., - quote: Any | None = ..., - _create_events: bool = ..., - ) -> None: ... - def copy(self, **kw): ... - def adapt(self, impltype, **kw): ... - @property - def bind(self): ... - def create(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - def drop(self, bind: Any | None = ..., checkfirst: bool = ...) -> None: ... - -class Enum(Emulated, String, SchemaType): - __visit_name__: str - def __init__(self, *enums, **kw) -> None: ... - @property - def sort_key_function(self): ... - @property - def native(self): ... - class Comparator(Concatenable.Comparator): ... - comparator_factory: Any - def as_generic(self, allow_nulltype: bool = ...): ... - def adapt_to_emulated(self, impltype, **kw): ... - def adapt(self, impltype, **kw): ... - def literal_processor(self, dialect): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - def copy(self, **kw): ... - @property - def python_type(self): ... - -class PickleType(TypeDecorator): - impl: Any - cache_ok: bool - protocol: Any - pickler: Any - comparator: Any - def __init__(self, protocol=..., pickler: Any | None = ..., comparator: Any | None = ..., impl: Any | None = ...) -> None: ... - def __reduce__(self): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - def compare_values(self, x, y): ... - -class Boolean(Emulated, TypeEngine, SchemaType): # type: ignore[misc] - __visit_name__: str - native: bool - create_constraint: Any - name: Any - def __init__(self, create_constraint: bool = ..., name: Any | None = ..., _create_events: bool = ...) -> None: ... - @property - def python_type(self): ... - def literal_processor(self, dialect): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class _AbstractInterval(_LookupExpressionAdapter, TypeEngine): - def coerce_compared_value(self, op, value): ... - -class Interval(Emulated, _AbstractInterval, TypeDecorator): # type: ignore[misc] - impl: Any - epoch: Any - cache_ok: bool - native: Any - second_precision: Any - day_precision: Any - def __init__(self, native: bool = ..., second_precision: Any | None = ..., day_precision: Any | None = ...) -> None: ... - @property - def python_type(self): ... - def adapt_to_emulated(self, impltype, **kw): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class JSON(Indexable, TypeEngine): - __visit_name__: str - hashable: bool - NULL: Any - none_as_null: Any - def __init__(self, none_as_null: bool = ...) -> None: ... - class JSONElementType(TypeEngine): - def string_bind_processor(self, dialect): ... - def string_literal_processor(self, dialect): ... - def bind_processor(self, dialect): ... - def literal_processor(self, dialect): ... - class JSONIndexType(JSONElementType): ... - class JSONIntIndexType(JSONIndexType): ... - class JSONStrIndexType(JSONIndexType): ... - class JSONPathType(JSONElementType): ... - class Comparator(Indexable.Comparator, Concatenable.Comparator): - def as_boolean(self): ... - def as_string(self): ... - def as_integer(self): ... - def as_float(self): ... - def as_numeric(self, precision, scale, asdecimal: bool = ...): ... - def as_json(self): ... - comparator_factory: Any - @property - def python_type(self): ... - @property # type: ignore[override] - def should_evaluate_none(self): ... - @should_evaluate_none.setter - def should_evaluate_none(self, value) -> None: ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - -class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): - __visit_name__: str - zero_indexes: bool - class Comparator(Indexable.Comparator, Concatenable.Comparator): - def contains(self, *arg, **kw) -> None: ... - def any(self, other, operator: Any | None = ...): ... - def all(self, other, operator: Any | None = ...): ... - comparator_factory: Any - item_type: Any - as_tuple: Any - dimensions: Any - def __init__(self, item_type, as_tuple: bool = ..., dimensions: Any | None = ..., zero_indexes: bool = ...) -> None: ... - @property - def hashable(self): ... - @property - def python_type(self): ... - def compare_values(self, x, y): ... - -class TupleType(TypeEngine): - types: Any - def __init__(self, *types) -> None: ... - def result_processor(self, dialect, coltype) -> None: ... - -class REAL(Float): - __visit_name__: str - -class FLOAT(Float): - __visit_name__: str - -class NUMERIC(Numeric): - __visit_name__: str - -class DECIMAL(Numeric): - __visit_name__: str - -class INTEGER(Integer): - __visit_name__: str - -INT = INTEGER - -class SMALLINT(SmallInteger): - __visit_name__: str - -class BIGINT(BigInteger): - __visit_name__: str - -class TIMESTAMP(DateTime): - __visit_name__: str - def __init__(self, timezone: bool = ...) -> None: ... - def get_dbapi_type(self, dbapi): ... - -class DATETIME(DateTime): - __visit_name__: str - -class DATE(Date): - __visit_name__: str - -class TIME(Time): - __visit_name__: str - -class TEXT(Text): - __visit_name__: str - -class CLOB(Text): - __visit_name__: str - -class VARCHAR(String): - __visit_name__: str - -class NVARCHAR(Unicode): - __visit_name__: str - -class CHAR(String): - __visit_name__: str - -class NCHAR(Unicode): - __visit_name__: str - -class BLOB(LargeBinary): - __visit_name__: str - -class BINARY(_Binary): - __visit_name__: str - -class VARBINARY(_Binary): - __visit_name__: str - -class BOOLEAN(Boolean): - __visit_name__: str - -class NullType(TypeEngine): - __visit_name__: str - def literal_processor(self, dialect): ... - class Comparator(TypeEngine.Comparator): ... - comparator_factory: Any - -class TableValueType(HasCacheKey, TypeEngine): - def __init__(self, *elements) -> None: ... - -class MatchType(Boolean): ... - -NULLTYPE: Any -BOOLEANTYPE: Any -STRINGTYPE: Any -INTEGERTYPE: Any -MATCHTYPE: Any -TABLEVALUE: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/traversals.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/traversals.pyi deleted file mode 100644 index 4ce0715c426e..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/traversals.pyi +++ /dev/null @@ -1,158 +0,0 @@ -from typing import Any - -from .. import util -from ..util import HasMemoized -from .visitors import ExtendedInternalTraversal, InternalTraversal - -SKIP_TRAVERSE: Any -COMPARE_FAILED: bool -COMPARE_SUCCEEDED: bool -NO_CACHE: Any -CACHE_IN_PLACE: Any -CALL_GEN_CACHE_KEY: Any -STATIC_CACHE_KEY: Any -PROPAGATE_ATTRS: Any -ANON_NAME: Any - -def compare(obj1, obj2, **kw): ... - -class HasCacheKey: - inherit_cache: Any - -class MemoizedHasCacheKey(HasCacheKey, HasMemoized): ... - -class CacheKey: - def __hash__(self): ... - def to_offline_string(self, statement_cache, statement, parameters): ... - def __eq__(self, other): ... - -class _CacheKey(ExtendedInternalTraversal): - visit_has_cache_key: Any - visit_clauseelement: Any - visit_clauseelement_list: Any - visit_annotations_key: Any - visit_clauseelement_tuple: Any - visit_memoized_select_entities: Any - visit_string: Any - visit_boolean: Any - visit_operator: Any - visit_plain_obj: Any - visit_statement_hint_list: Any - visit_type: Any - visit_anon_name: Any - visit_propagate_attrs: Any - def visit_with_context_options(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_inspectable(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_string_list(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_multi(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_multi_list(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_has_cache_key_tuples(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_has_cache_key_list(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_executable_options(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_inspectable_list(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_clauseelement_tuples(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_fromclause_ordered_set(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_clauseelement_unordered_set(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_named_ddl_element(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_prefix_sequence(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_setup_join_tuple(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_table_hint_list(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_plain_dict(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_dialect_options(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_string_clauseelement_dict(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_string_multi_dict(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_fromclause_canonical_column_collection(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_unknown_structure(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_dml_ordered_values(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_dml_values(self, attrname, obj, parent, anon_map, bindparams): ... - def visit_dml_multi_values(self, attrname, obj, parent, anon_map, bindparams): ... - -class HasCopyInternals: ... - -class _CopyInternals(InternalTraversal): - def visit_clauseelement(self, attrname, parent, element, clone=..., **kw): ... - def visit_clauseelement_list(self, attrname, parent, element, clone=..., **kw): ... - def visit_clauseelement_tuple(self, attrname, parent, element, clone=..., **kw): ... - def visit_executable_options(self, attrname, parent, element, clone=..., **kw): ... - def visit_clauseelement_unordered_set(self, attrname, parent, element, clone=..., **kw): ... - def visit_clauseelement_tuples(self, attrname, parent, element, clone=..., **kw): ... - def visit_string_clauseelement_dict(self, attrname, parent, element, clone=..., **kw): ... - def visit_setup_join_tuple(self, attrname, parent, element, clone=..., **kw): ... - def visit_memoized_select_entities(self, attrname, parent, element, **kw): ... - def visit_dml_ordered_values(self, attrname, parent, element, clone=..., **kw): ... - def visit_dml_values(self, attrname, parent, element, clone=..., **kw): ... - def visit_dml_multi_values(self, attrname, parent, element, clone=..., **kw): ... - def visit_propagate_attrs(self, attrname, parent, element, clone=..., **kw): ... - -class _GetChildren(InternalTraversal): - def visit_has_cache_key(self, element, **kw): ... - def visit_clauseelement(self, element, **kw): ... - def visit_clauseelement_list(self, element, **kw): ... - def visit_clauseelement_tuple(self, element, **kw): ... - def visit_clauseelement_tuples(self, element, **kw): ... - def visit_fromclause_canonical_column_collection(self, element, **kw): ... - def visit_string_clauseelement_dict(self, element, **kw): ... - def visit_fromclause_ordered_set(self, element, **kw): ... - def visit_clauseelement_unordered_set(self, element, **kw): ... - def visit_setup_join_tuple(self, element, **kw) -> None: ... - def visit_memoized_select_entities(self, element, **kw): ... - def visit_dml_ordered_values(self, element, **kw) -> None: ... - def visit_dml_values(self, element, **kw) -> None: ... - def visit_dml_multi_values(self, element, **kw): ... - def visit_propagate_attrs(self, element, **kw): ... - -class anon_map(dict[Any, Any]): - index: int - def __init__(self) -> None: ... - def __missing__(self, key): ... - -class TraversalComparatorStrategy(InternalTraversal, util.MemoizedSlots): - stack: Any - cache: Any - anon_map: Any - def __init__(self) -> None: ... - def compare(self, obj1, obj2, **kw): ... - def compare_inner(self, obj1, obj2, **kw): ... - def visit_has_cache_key(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_propagate_attrs(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_has_cache_key_list(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_executable_options(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_clauseelement(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_fromclause_canonical_column_collection(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_fromclause_derived_column_collection(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_string_clauseelement_dict(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_clauseelement_tuples(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_clauseelement_list(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_clauseelement_tuple(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_clauseelement_unordered_set(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_fromclause_ordered_set(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_string(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_string_list(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_anon_name(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_boolean(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_operator(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_type(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_plain_dict(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_dialect_options(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_annotations_key(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_with_context_options(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_plain_obj(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_named_ddl_element(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_prefix_sequence(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_setup_join_tuple(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_memoized_select_entities(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_table_hint_list(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_statement_hint_list(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_unknown_structure(self, attrname, left_parent, left, right_parent, right, **kw) -> None: ... - def visit_dml_ordered_values(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_dml_values(self, attrname, left_parent, left, right_parent, right, **kw): ... - def visit_dml_multi_values(self, attrname, left_parent, left, right_parent, right, **kw): ... - def compare_clauselist(self, left, right, **kw): ... - def compare_binary(self, left, right, **kw): ... - def compare_bindparam(self, left, right, **kw): ... - -class ColIdentityComparatorStrategy(TraversalComparatorStrategy): - def compare_column_element(self, left, right, use_proxies: bool = ..., equivalents=..., **kw): ... - def compare_column(self, left, right, **kw): ... - def compare_label(self, left, right, **kw): ... - def compare_table(self, left, right, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/type_api.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/type_api.pyi deleted file mode 100644 index 96ad244e5756..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/type_api.pyi +++ /dev/null @@ -1,110 +0,0 @@ -from typing import Any - -from .. import util -from . import operators -from .base import SchemaEventTarget -from .visitors import Traversible, TraversibleType - -BOOLEANTYPE: Any -INTEGERTYPE: Any -NULLTYPE: Any -STRINGTYPE: Any -MATCHTYPE: Any -INDEXABLE: Any -TABLEVALUE: Any - -class TypeEngine(Traversible): - class Comparator(operators.ColumnOperators): - default_comparator: Any - def __clause_element__(self): ... - expr: Any - type: Any - def __init__(self, expr) -> None: ... - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... - def __reduce__(self): ... - hashable: bool - comparator_factory: Any - sort_key_function: Any - should_evaluate_none: bool - def evaluates_none(self): ... - def copy(self, **kw): ... - def compare_against_backend(self, dialect, conn_type) -> None: ... - def copy_value(self, value): ... - def literal_processor(self, dialect) -> None: ... - def bind_processor(self, dialect) -> None: ... - def result_processor(self, dialect, coltype) -> None: ... - def column_expression(self, colexpr) -> None: ... - def bind_expression(self, bindvalue) -> None: ... - def compare_values(self, x, y): ... - def get_dbapi_type(self, dbapi) -> None: ... - @property - def python_type(self) -> None: ... - def with_variant(self, type_, dialect_name): ... - def as_generic(self, allow_nulltype: bool = ...): ... - def dialect_impl(self, dialect): ... - def adapt(self, cls, **kw): ... - def coerce_compared_value(self, op, value): ... - def compile(self, dialect: Any | None = ...): ... - -class VisitableCheckKWArg(util.EnsureKWArgType, TraversibleType): ... - -class ExternalType: - cache_ok: Any - -class UserDefinedType: - __visit_name__: str - ensure_kwarg: str - def coerce_compared_value(self, op, value): ... - -class Emulated: - def adapt_to_emulated(self, impltype, **kw): ... - def adapt(self, impltype, **kw): ... - -class NativeForEmulated: - @classmethod - def adapt_native_to_emulated(cls, impl, **kw): ... - @classmethod - def adapt_emulated_to_native(cls, impl, **kw): ... - -class TypeDecorator(ExternalType, SchemaEventTarget, TypeEngine): - __visit_name__: str - impl: Any - def __init__(self, *args, **kwargs) -> None: ... - coerce_to_is_types: Any - class Comparator(TypeEngine.Comparator): - def operate(self, op, *other, **kwargs): ... - def reverse_operate(self, op, other, **kwargs): ... - @property - def comparator_factory(self): ... - def type_engine(self, dialect): ... - def load_dialect_impl(self, dialect): ... - def __getattr__(self, key): ... - def process_literal_param(self, value, dialect) -> None: ... - def process_bind_param(self, value, dialect) -> None: ... - def process_result_value(self, value, dialect) -> None: ... - def literal_processor(self, dialect): ... - def bind_processor(self, dialect): ... - def result_processor(self, dialect, coltype): ... - def bind_expression(self, bindparam): ... - def column_expression(self, column): ... - def coerce_compared_value(self, op, value): ... - def copy(self, **kw): ... - def get_dbapi_type(self, dbapi): ... - def compare_values(self, x, y): ... - @property - def sort_key_function(self): ... - -class Variant(TypeDecorator): - cache_ok: bool - impl: Any - mapping: Any - def __init__(self, base, mapping) -> None: ... - def coerce_compared_value(self, operator, value): ... - def load_dialect_impl(self, dialect): ... - def with_variant(self, type_, dialect_name): ... - @property - def comparator_factory(self): ... - -def to_instance(typeobj, *arg, **kw): ... -def adapt_type(typeobj, colspecs): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/util.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/util.pyi deleted file mode 100644 index 965d10654439..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/util.pyi +++ /dev/null @@ -1,101 +0,0 @@ -from typing import Any - -from . import visitors - -join_condition: Any - -def find_join_source(clauses, join_to): ... -def find_left_clause_that_matches_given(clauses, join_from): ... -def find_left_clause_to_join_from(clauses, join_to, onclause): ... -def visit_binary_product(fn, expr) -> None: ... -def find_tables( - clause, - check_columns: bool = ..., - include_aliases: bool = ..., - include_joins: bool = ..., - include_selects: bool = ..., - include_crud: bool = ..., -): ... -def unwrap_order_by(clause): ... -def unwrap_label_reference(element): ... -def expand_column_list_from_order_by(collist, order_by): ... -def clause_is_present(clause, search): ... -def tables_from_leftmost(clause) -> None: ... -def surface_selectables(clause) -> None: ... -def surface_selectables_only(clause) -> None: ... -def extract_first_column_annotation(column, annotation_name): ... -def selectables_overlap(left, right): ... -def bind_values(clause): ... - -class _repr_base: - max_chars: Any - def trunc(self, value): ... - -class _repr_row(_repr_base): - row: Any - max_chars: Any - def __init__(self, row, max_chars: int = ...) -> None: ... - -class _repr_params(_repr_base): - params: Any - ismulti: Any - batches: Any - max_chars: Any - def __init__(self, params, batches, max_chars: int = ..., ismulti: Any | None = ...) -> None: ... - -def adapt_criterion_to_null(crit, nulls): ... -def splice_joins(left, right, stop_on: Any | None = ...): ... -def reduce_columns(columns, *clauses, **kw): ... -def criterion_as_pairs( - expression, - consider_as_foreign_keys: Any | None = ..., - consider_as_referenced_keys: Any | None = ..., - any_operator: bool = ..., -): ... - -class ClauseAdapter(visitors.ReplacingExternalTraversal): - __traverse_options__: Any - selectable: Any - include_fn: Any - exclude_fn: Any - equivalents: Any - adapt_on_names: Any - adapt_from_selectables: Any - def __init__( - self, - selectable, - equivalents: Any | None = ..., - include_fn: Any | None = ..., - exclude_fn: Any | None = ..., - adapt_on_names: bool = ..., - anonymize_labels: bool = ..., - adapt_from_selectables: Any | None = ..., - ) -> None: ... - def replace(self, col, _include_singleton_constants: bool = ...): ... - -class ColumnAdapter(ClauseAdapter): - columns: Any - adapt_required: Any - allow_label_resolve: Any - def __init__( - self, - selectable, - equivalents: Any | None = ..., - adapt_required: bool = ..., - include_fn: Any | None = ..., - exclude_fn: Any | None = ..., - adapt_on_names: bool = ..., - allow_label_resolve: bool = ..., - anonymize_labels: bool = ..., - adapt_from_selectables: Any | None = ..., - ) -> None: ... - class _IncludeExcludeMapping: - parent: Any - columns: Any - def __init__(self, parent, columns) -> None: ... - def __getitem__(self, key): ... - def wrap(self, adapter): ... - def traverse(self, obj): ... - adapt_clause: Any - adapt_list: Any - def adapt_check_present(self, col): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/sql/visitors.pyi b/stubs/SQLAlchemy/sqlalchemy/sql/visitors.pyi deleted file mode 100644 index c3dd44793e24..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/sql/visitors.pyi +++ /dev/null @@ -1,86 +0,0 @@ -from typing import Any - -class TraversibleType(type): - def __init__(cls, clsname, bases, clsdict) -> None: ... - -class Traversible: - def __class_getitem__(cls, key): ... - def get_children(self, omit_attrs=..., **kw): ... - -class _InternalTraversalType(type): - def __init__(cls, clsname, bases, clsdict) -> None: ... - -class InternalTraversal: - def dispatch(self, visit_symbol): ... - def run_generated_dispatch(self, target, internal_dispatch, generate_dispatcher_name): ... - def generate_dispatch(self, target_cls, internal_dispatch, generate_dispatcher_name): ... - dp_has_cache_key: Any - dp_has_cache_key_list: Any - dp_clauseelement: Any - dp_fromclause_canonical_column_collection: Any - dp_clauseelement_tuples: Any - dp_clauseelement_list: Any - dp_clauseelement_tuple: Any - dp_executable_options: Any - dp_with_context_options: Any - dp_fromclause_ordered_set: Any - dp_string: Any - dp_string_list: Any - dp_anon_name: Any - dp_boolean: Any - dp_operator: Any - dp_type: Any - dp_plain_dict: Any - dp_dialect_options: Any - dp_string_clauseelement_dict: Any - dp_string_multi_dict: Any - dp_annotations_key: Any - dp_plain_obj: Any - dp_named_ddl_element: Any - dp_prefix_sequence: Any - dp_table_hint_list: Any - dp_setup_join_tuple: Any - dp_memoized_select_entities: Any - dp_statement_hint_list: Any - dp_unknown_structure: Any - dp_dml_ordered_values: Any - dp_dml_values: Any - dp_dml_multi_values: Any - dp_propagate_attrs: Any - -class ExtendedInternalTraversal(InternalTraversal): - dp_ignore: Any - dp_inspectable: Any - dp_multi: Any - dp_multi_list: Any - dp_has_cache_key_tuples: Any - dp_inspectable_list: Any - -class ExternalTraversal: - __traverse_options__: Any - def traverse_single(self, obj, **kw): ... - def iterate(self, obj): ... - def traverse(self, obj): ... - @property - def visitor_iterator(self) -> None: ... - def chain(self, visitor): ... - -class CloningExternalTraversal(ExternalTraversal): - def copy_and_process(self, list_): ... - def traverse(self, obj): ... - -class ReplacingExternalTraversal(CloningExternalTraversal): - def replace(self, elem) -> None: ... - def traverse(self, obj): ... - -Visitable = Traversible -VisitableType = TraversibleType -ClauseVisitor = ExternalTraversal -CloningVisitor = CloningExternalTraversal -ReplacingCloningVisitor = ReplacingExternalTraversal - -def iterate(obj, opts=...) -> None: ... -def traverse_using(iterator, obj, visitors): ... -def traverse(obj, opts, visitors): ... -def cloned_traverse(obj, opts, visitors): ... -def replacement_traverse(obj, opts, replace): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/__init__.pyi deleted file mode 100644 index a27e338db2f9..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/__init__.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from . import config as config, mock as mock -from .assertions import ( - AssertsCompiledSQL as AssertsCompiledSQL, - AssertsExecutionResults as AssertsExecutionResults, - ComparesTables as ComparesTables, - assert_raises as assert_raises, - assert_raises_context_ok as assert_raises_context_ok, - assert_raises_message as assert_raises_message, - assert_raises_message_context_ok as assert_raises_message_context_ok, - emits_warning as emits_warning, - emits_warning_on as emits_warning_on, - eq_ as eq_, - eq_ignore_whitespace as eq_ignore_whitespace, - eq_regex as eq_regex, - expect_deprecated as expect_deprecated, - expect_deprecated_20 as expect_deprecated_20, - expect_raises as expect_raises, - expect_raises_message as expect_raises_message, - expect_warnings as expect_warnings, - in_ as in_, - is_ as is_, - is_false as is_false, - is_instance_of as is_instance_of, - is_none as is_none, - is_not as is_not, - is_not_ as is_not_, - is_not_none as is_not_none, - is_true as is_true, - le_ as le_, - ne_ as ne_, - not_in as not_in, - not_in_ as not_in_, - startswith_ as startswith_, - uses_deprecated as uses_deprecated, -) -from .config import ( - async_test as async_test, - combinations as combinations, - combinations_list as combinations_list, - db as db, - fixture as fixture, -) -from .exclusions import ( - db_spec as db_spec, - exclude as exclude, - fails as fails, - fails_if as fails_if, - fails_on as fails_on, - fails_on_everything_except as fails_on_everything_except, - future as future, - only_if as only_if, - only_on as only_on, - skip as skip, - skip_if as skip_if, -) -from .schema import eq_clause_element as eq_clause_element, eq_type_affinity as eq_type_affinity -from .util import ( - adict as adict, - fail as fail, - flag_combinations as flag_combinations, - force_drop_names as force_drop_names, - lambda_combinations as lambda_combinations, - metadata_fixture as metadata_fixture, - provide_metadata as provide_metadata, - resolve_lambda as resolve_lambda, - rowset as rowset, - run_as_contextmanager as run_as_contextmanager, - teardown_events as teardown_events, -) -from .warnings import assert_warnings as assert_warnings, warn_test_suite as warn_test_suite - -def against(*queries): ... - -crashes = skip diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/assertions.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/assertions.pyi deleted file mode 100644 index 024be0f28782..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/assertions.pyi +++ /dev/null @@ -1,85 +0,0 @@ -from typing import Any - -def expect_warnings(*messages, **kw): ... -def expect_warnings_on(db, *messages, **kw) -> None: ... -def emits_warning(*messages): ... -def expect_deprecated(*messages, **kw): ... -def expect_deprecated_20(*messages, **kw): ... -def emits_warning_on(db, *messages): ... -def uses_deprecated(*messages): ... -def global_cleanup_assertions() -> None: ... -def eq_regex(a, b, msg: Any | None = ...) -> None: ... -def eq_(a, b, msg: Any | None = ...) -> None: ... -def ne_(a, b, msg: Any | None = ...) -> None: ... -def le_(a, b, msg: Any | None = ...) -> None: ... -def is_instance_of(a, b, msg: Any | None = ...) -> None: ... -def is_none(a, msg: Any | None = ...) -> None: ... -def is_not_none(a, msg: Any | None = ...) -> None: ... -def is_true(a, msg: Any | None = ...) -> None: ... -def is_false(a, msg: Any | None = ...) -> None: ... -def is_(a, b, msg: Any | None = ...) -> None: ... -def is_not(a, b, msg: Any | None = ...) -> None: ... - -is_not_ = is_not - -def in_(a, b, msg: Any | None = ...) -> None: ... -def not_in(a, b, msg: Any | None = ...) -> None: ... - -not_in_ = not_in - -def startswith_(a, fragment, msg: Any | None = ...) -> None: ... -def eq_ignore_whitespace(a, b, msg: Any | None = ...) -> None: ... -def assert_raises(except_cls, callable_, *args, **kw): ... -def assert_raises_context_ok(except_cls, callable_, *args, **kw): ... -def assert_raises_message(except_cls, msg, callable_, *args, **kwargs): ... -def assert_raises_message_context_ok(except_cls, msg, callable_, *args, **kwargs): ... - -class _ErrorContainer: - error: Any - -def expect_raises(except_cls, check_context: bool = ...): ... -def expect_raises_message(except_cls, msg, check_context: bool = ...): ... - -class AssertsCompiledSQL: - test_statement: Any - supports_execution: Any - def assert_compile( - self, - clause, - result, - params: Any | None = ..., - checkparams: Any | None = ..., - for_executemany: bool = ..., - check_literal_execute: Any | None = ..., - check_post_param: Any | None = ..., - dialect: Any | None = ..., - checkpositional: Any | None = ..., - check_prefetch: Any | None = ..., - use_default_dialect: bool = ..., - allow_dialect_select: bool = ..., - supports_default_values: bool = ..., - supports_default_metavalue: bool = ..., - literal_binds: bool = ..., - render_postcompile: bool = ..., - schema_translate_map: Any | None = ..., - render_schema_translate: bool = ..., - default_schema_name: Any | None = ..., - from_linting: bool = ..., - ): ... - -class ComparesTables: - def assert_tables_equal(self, table, reflected_table, strict_types: bool = ...) -> None: ... - def assert_types_base(self, c1, c2) -> None: ... - -class AssertsExecutionResults: - def assert_result(self, result, class_, *objects) -> None: ... - def assert_list(self, result, class_, list_) -> None: ... - def assert_row(self, class_, rowobj, desc) -> None: ... - def assert_unordered_result(self, result, cls, *expected): ... - def sql_execution_asserter(self, db: Any | None = ...): ... - def assert_sql_execution(self, db, callable_, *rules): ... - def assert_sql(self, db, callable_, rules): ... - def assert_sql_count(self, db, callable_, count) -> None: ... - def assert_multiple_sql_count(self, dbs, callable_, counts): ... - def assert_execution(self, db, *rules) -> None: ... - def assert_statement_count(self, db, count): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/assertsql.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/assertsql.pyi deleted file mode 100644 index 6e30c772702e..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/assertsql.pyi +++ /dev/null @@ -1,82 +0,0 @@ -from typing import Any - -class AssertRule: - is_consumed: bool - errormessage: Any - consume_statement: bool - def process_statement(self, execute_observed) -> None: ... - def no_more_statements(self) -> None: ... - -class SQLMatchRule(AssertRule): ... - -class CursorSQL(SQLMatchRule): - statement: Any - params: Any - consume_statement: Any - def __init__(self, statement, params: Any | None = ..., consume_statement: bool = ...) -> None: ... - errormessage: Any - is_consumed: bool - def process_statement(self, execute_observed) -> None: ... - -class CompiledSQL(SQLMatchRule): - statement: Any - params: Any - dialect: Any - def __init__(self, statement, params: Any | None = ..., dialect: str = ...) -> None: ... - is_consumed: bool - errormessage: Any - def process_statement(self, execute_observed) -> None: ... - -class RegexSQL(CompiledSQL): - regex: Any - orig_regex: Any - params: Any - dialect: Any - def __init__(self, regex, params: Any | None = ..., dialect: str = ...) -> None: ... - -class DialectSQL(CompiledSQL): ... - -class CountStatements(AssertRule): - count: Any - def __init__(self, count) -> None: ... - def process_statement(self, execute_observed) -> None: ... - def no_more_statements(self) -> None: ... - -class AllOf(AssertRule): - rules: Any - def __init__(self, *rules) -> None: ... - is_consumed: bool - errormessage: Any - def process_statement(self, execute_observed) -> None: ... - -class EachOf(AssertRule): - rules: Any - def __init__(self, *rules) -> None: ... - errormessage: Any - is_consumed: bool - def process_statement(self, execute_observed) -> None: ... - def no_more_statements(self) -> None: ... - -class Conditional(EachOf): - def __init__(self, condition, rules, else_rules) -> None: ... - -class Or(AllOf): - is_consumed: bool - errormessage: Any - def process_statement(self, execute_observed) -> None: ... - -class SQLExecuteObserved: - context: Any - clauseelement: Any - parameters: Any - statements: Any - def __init__(self, context, clauseelement, multiparams, params) -> None: ... - -class SQLCursorExecuteObserved: ... - -class SQLAsserter: - accumulated: Any - def __init__(self) -> None: ... - def assert_(self, *rules) -> None: ... - -def assert_engine(engine) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/asyncio.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/asyncio.pyi deleted file mode 100644 index 7455e47b8f46..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/asyncio.pyi +++ /dev/null @@ -1 +0,0 @@ -ENABLE_ASYNCIO: bool diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/config.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/config.pyi deleted file mode 100644 index db67aa9cbe9d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/config.pyi +++ /dev/null @@ -1,47 +0,0 @@ -from typing import Any - -requirements: Any -db: Any -db_url: Any -db_opts: Any -file_config: Any -test_schema: Any -test_schema_2: Any -any_async: bool -ident: str - -def combinations(*comb, **kw): ... -def combinations_list(arg_iterable, **kw): ... -def fixture(*arg, **kw): ... -def get_current_test_name(): ... -def mark_base_test_class(): ... - -class Config: - db: Any - db_opts: Any - options: Any - file_config: Any - test_schema: str - test_schema_2: str - is_async: Any - def __init__(self, db, db_opts, options, file_config) -> None: ... - @classmethod - def register(cls, db, db_opts, options, file_config): ... - @classmethod - def set_as_current(cls, config, namespace) -> None: ... - @classmethod - def push_engine(cls, db, namespace) -> None: ... - @classmethod - def push(cls, config, namespace) -> None: ... - @classmethod - def pop(cls, namespace) -> None: ... - @classmethod - def reset(cls, namespace) -> None: ... - @classmethod - def all_configs(cls): ... - @classmethod - def all_dbs(cls) -> None: ... - def skip_test(self, msg) -> None: ... - -def skip_test(msg) -> None: ... -def async_test(fn): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/engines.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/engines.pyi deleted file mode 100644 index 400503ba8462..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/engines.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Any - -class ConnectionKiller: - proxy_refs: Any - testing_engines: Any - dbapi_connections: Any - def __init__(self) -> None: ... - def add_pool(self, pool) -> None: ... - def add_engine(self, engine, scope) -> None: ... - def rollback_all(self) -> None: ... - def checkin_all(self) -> None: ... - def close_all(self) -> None: ... - def prepare_for_drop_tables(self, connection) -> None: ... - def after_test(self) -> None: ... - def after_test_outside_fixtures(self, test) -> None: ... - def stop_test_class_inside_fixtures(self) -> None: ... - def stop_test_class_outside_fixtures(self) -> None: ... - def final_cleanup(self) -> None: ... - def assert_all_closed(self) -> None: ... - -testing_reaper: Any - -def assert_conns_closed(fn, *args, **kw) -> None: ... -def rollback_open_connections(fn, *args, **kw) -> None: ... -def close_first(fn, *args, **kw) -> None: ... -def close_open_connections(fn, *args, **kw) -> None: ... -def all_dialects(exclude: Any | None = ...) -> None: ... - -class ReconnectFixture: - dbapi: Any - connections: Any - is_stopped: bool - def __init__(self, dbapi) -> None: ... - def __getattr__(self, key): ... - def connect(self, *args, **kwargs): ... - def shutdown(self, stop: bool = ...) -> None: ... - def restart(self) -> None: ... - -def reconnecting_engine(url: Any | None = ..., options: Any | None = ...): ... -def testing_engine( - url: Any | None = ..., - options: Any | None = ..., - future: Any | None = ..., - asyncio: bool = ..., - transfer_staticpool: bool = ..., -): ... -def mock_engine(dialect_name: Any | None = ...): ... - -class DBAPIProxyCursor: - engine: Any - connection: Any - cursor: Any - def __init__(self, engine, conn, *args, **kwargs) -> None: ... - def execute(self, stmt, parameters: Any | None = ..., **kw): ... - def executemany(self, stmt, params, **kw): ... - def __iter__(self): ... - def __getattr__(self, key): ... - -class DBAPIProxyConnection: - conn: Any - engine: Any - cursor_cls: Any - def __init__(self, engine, cursor_cls) -> None: ... - def cursor(self, *args, **kwargs): ... - def close(self) -> None: ... - def __getattr__(self, key): ... - -def proxying_engine(conn_cls=..., cursor_cls=...): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/entities.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/entities.pyi deleted file mode 100644 index 0afb34e39941..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/entities.pyi +++ /dev/null @@ -1,9 +0,0 @@ -class BasicEntity: - def __init__(self, **kw) -> None: ... - -class ComparableMixin: - def __ne__(self, other): ... - def __eq__(self, other): ... - -class ComparableEntity(ComparableMixin, BasicEntity): - def __hash__(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/exclusions.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/exclusions.pyi deleted file mode 100644 index 4cc9913e6369..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/exclusions.pyi +++ /dev/null @@ -1,76 +0,0 @@ -from typing import Any - -def skip_if(predicate, reason: Any | None = ...): ... -def fails_if(predicate, reason: Any | None = ...): ... - -class compound: - fails: Any - skips: Any - tags: Any - def __init__(self) -> None: ... - def __add__(self, other): ... - def as_skips(self): ... - def add(self, *others): ... - def not_(self): ... - @property - def enabled(self): ... - def enabled_for_config(self, config): ... - def matching_config_reasons(self, config): ... - def include_test(self, include_tags, exclude_tags): ... - def __call__(self, fn): ... - def fail_if(self) -> None: ... - -def requires_tag(tagname): ... -def tags(tagnames): ... -def only_if(predicate, reason: Any | None = ...): ... -def succeeds_if(predicate, reason: Any | None = ...): ... - -class Predicate: - @classmethod - def as_predicate(cls, predicate, description: Any | None = ...): ... - -class BooleanPredicate(Predicate): - value: Any - description: Any - def __init__(self, value, description: Any | None = ...) -> None: ... - def __call__(self, config): ... - -class SpecPredicate(Predicate): - db: Any - op: Any - spec: Any - description: Any - def __init__(self, db, op: Any | None = ..., spec: Any | None = ..., description: Any | None = ...) -> None: ... - def __call__(self, config): ... - -class LambdaPredicate(Predicate): - lambda_: Any - args: Any - kw: Any - description: Any - def __init__(self, lambda_, description: Any | None = ..., args: Any | None = ..., kw: Any | None = ...): ... - def __call__(self, config): ... - -class NotPredicate(Predicate): - predicate: Any - description: Any - def __init__(self, predicate, description: Any | None = ...) -> None: ... - def __call__(self, config): ... - -class OrPredicate(Predicate): - predicates: Any - description: Any - def __init__(self, predicates, description: Any | None = ...) -> None: ... - def __call__(self, config): ... - -def db_spec(*dbs): ... -def open(): ... -def closed(): ... -def fails(reason: Any | None = ...): ... -def future(fn, *arg): ... -def fails_on(db, reason: Any | None = ...): ... -def fails_on_everything_except(*dbs): ... -def skip(db, reason: Any | None = ...): ... -def only_on(dbs, reason: Any | None = ...): ... -def exclude(db, op, spec, reason: Any | None = ...): ... -def against(config, *queries): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/fixtures.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/fixtures.pyi deleted file mode 100644 index 58c6be2e8aa7..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/fixtures.pyi +++ /dev/null @@ -1,83 +0,0 @@ -from typing import Any - -from . import assertions -from .entities import ComparableEntity as ComparableEntity - -class TestBase: - __requires__: Any - __unsupported_on__: Any - __only_on__: Any - __skip_if__: Any - __leave_connections_for_teardown__: bool - def assert_(self, val, msg: Any | None = ...) -> None: ... - def connection_no_trans(self) -> None: ... - def connection(self) -> None: ... - def registry(self, metadata) -> None: ... - def future_connection(self, future_engine, connection) -> None: ... - def future_engine(self) -> None: ... - def testing_engine(self): ... - def async_testing_engine(self, testing_engine): ... - def metadata(self, request) -> None: ... - def trans_ctx_manager_fixture(self, request, metadata): ... - -class FutureEngineMixin: ... - -class TablesTest(TestBase): - run_setup_bind: str - run_define_tables: str - run_create_tables: str - run_inserts: str - run_deletes: str - run_dispose_bind: Any - bind: Any - tables: Any - other: Any - sequences: Any - @property - def tables_test_metadata(self): ... - @classmethod - def setup_bind(cls): ... - @classmethod - def dispose_bind(cls, bind) -> None: ... - @classmethod - def define_tables(cls, metadata) -> None: ... - @classmethod - def fixtures(cls): ... - @classmethod - def insert_data(cls, connection) -> None: ... - def sql_count_(self, count, fn) -> None: ... - def sql_eq_(self, callable_, statements) -> None: ... - -class NoCache: ... - -class RemovesEvents: - def event_listen(self, target, name, fn, **kw) -> None: ... - -def fixture_session(**kw): ... -def stop_test_class_inside_fixtures(cls) -> None: ... -def after_test() -> None: ... - -class ORMTest(TestBase): ... - -class MappedTest(TablesTest, assertions.AssertsExecutionResults): - run_setup_classes: str - run_setup_mappers: str - classes: Any - @classmethod - def setup_classes(cls) -> None: ... - @classmethod - def setup_mappers(cls) -> None: ... - -class DeclarativeMappedTest(MappedTest): - run_setup_classes: str - run_setup_mappers: str - -class ComputedReflectionFixtureTest(TablesTest): - run_inserts: Any - run_deletes: Any - __backend__: bool - __requires__: Any - regexp: Any - def normalize(self, text): ... - @classmethod - def define_tables(cls, metadata) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/pickleable.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/pickleable.pyi deleted file mode 100644 index 837dfac0409d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/pickleable.pyi +++ /dev/null @@ -1,62 +0,0 @@ -from typing import Any - -from . import fixtures - -class User(fixtures.ComparableEntity): ... -class Order(fixtures.ComparableEntity): ... -class Dingaling(fixtures.ComparableEntity): ... -class EmailUser(User): ... -class Address(fixtures.ComparableEntity): ... -class Child1(fixtures.ComparableEntity): ... -class Child2(fixtures.ComparableEntity): ... -class Parent(fixtures.ComparableEntity): ... - -class Screen: - obj: Any - parent: Any - def __init__(self, obj, parent: Any | None = ...) -> None: ... - -class Foo: - data: str - stuff: Any - moredata: Any - def __init__(self, moredata, stuff: str = ...) -> None: ... - __hash__: Any - def __eq__(self, other): ... - -class Bar: - x: Any - y: Any - def __init__(self, x, y) -> None: ... - __hash__: Any - def __eq__(self, other): ... - -class OldSchool: - x: Any - y: Any - def __init__(self, x, y) -> None: ... - def __eq__(self, other): ... - -class OldSchoolWithoutCompare: - x: Any - y: Any - def __init__(self, x, y) -> None: ... - -class BarWithoutCompare: - x: Any - y: Any - def __init__(self, x, y) -> None: ... - -class NotComparable: - data: Any - def __init__(self, data) -> None: ... - def __hash__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - -class BrokenComparable: - data: Any - def __init__(self, data) -> None: ... - def __hash__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/bootstrap.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/plugin/bootstrap.pyi deleted file mode 100644 index 5c554d0de466..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/bootstrap.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -bootstrap_file: Any -to_bootstrap: Any - -def load_file_as_module(name): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/plugin_base.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/plugin/plugin_base.pyi deleted file mode 100644 index e0cdfbe59f28..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/plugin_base.pyi +++ /dev/null @@ -1,63 +0,0 @@ -import abc -from typing import Any - -bootstrapped_as_sqlalchemy: bool -log: Any -py3k: Any -ABC = abc.ABC - -fixtures: Any -engines: Any -exclusions: Any -warnings: Any -profiling: Any -provision: Any -assertions: Any -requirements: Any -config: Any -testing: Any -util: Any -file_config: Any -include_tags: Any -exclude_tags: Any -options: Any - -def setup_options(make_option) -> None: ... -def configure_follower(follower_ident) -> None: ... -def memoize_important_follower_config(dict_) -> None: ... -def restore_important_follower_config(dict_) -> None: ... -def read_config() -> None: ... -def pre_begin(opt) -> None: ... -def set_coverage_flag(value) -> None: ... -def post_begin() -> None: ... - -pre_configure: Any -post_configure: Any - -def pre(fn): ... -def post(fn): ... -def want_class(name, cls): ... -def want_method(cls, fn): ... -def generate_sub_tests(cls, module) -> None: ... -def start_test_class_outside_fixtures(cls) -> None: ... -def stop_test_class(cls) -> None: ... -def stop_test_class_outside_fixtures(cls) -> None: ... -def final_process_cleanup() -> None: ... -def before_test(test, test_module_name, test_class, test_name) -> None: ... -def after_test(test) -> None: ... -def after_test_fixtures(test) -> None: ... - -class FixtureFunctions(ABC, metaclass=abc.ABCMeta): - @abc.abstractmethod - def skip_test_exception(self, *arg, **kw): ... - @abc.abstractmethod - def combinations(self, *args, **kw): ... - @abc.abstractmethod - def param_ident(self, *args, **kw): ... - @abc.abstractmethod - def fixture(self, *arg, **kw): ... - def get_current_test_name(self) -> None: ... - @abc.abstractmethod - def mark_base_test_class(self): ... - -def set_fixture_functions(fixture_fn_class) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/pytestplugin.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/plugin/pytestplugin.pyi deleted file mode 100644 index ded604f35850..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/pytestplugin.pyi +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Any - -from . import plugin_base - -has_xdist: bool -py2k: Any - -def pytest_addoption(parser) -> None: ... -def pytest_configure(config) -> None: ... - -DUMP_PYANNOTATE: bool - -def collect_types_fixture() -> None: ... -def pytest_sessionstart(session) -> None: ... -def pytest_sessionfinish(session) -> None: ... -def pytest_collection_finish(session): ... -def pytest_configure_node(node) -> None: ... -def pytest_testnodedown(node, error) -> None: ... -def pytest_collection_modifyitems(session, config, items): ... -def pytest_pycollect_makeitem(collector, name, obj): ... -def pytest_runtest_setup(item) -> None: ... -def pytest_runtest_teardown(item, nextitem) -> None: ... -def pytest_runtest_call(item) -> None: ... -def pytest_runtest_logreport(report) -> None: ... -def setup_class_methods(request) -> None: ... -def setup_test_methods(request) -> None: ... -def getargspec(fn): ... - -class PytestFixtureFunctions(plugin_base.FixtureFunctions): - def skip_test_exception(self, *arg, **kw): ... - def mark_base_test_class(self): ... - def combinations(self, *arg_sets, **kw): ... - def param_ident(self, *parameters): ... - def fixture(self, *arg, **kw): ... - def get_current_test_name(self): ... - def async_test(self, fn): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/reinvent_fixtures_py2k.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/plugin/reinvent_fixtures_py2k.pyi deleted file mode 100644 index 83f3da8643b7..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/reinvent_fixtures_py2k.pyi +++ /dev/null @@ -1,6 +0,0 @@ -def add_fixture(fn, fixture) -> None: ... -def scan_for_fixtures_to_use_for_class(item) -> None: ... -def run_class_fixture_setup(request) -> None: ... -def run_class_fixture_teardown(request) -> None: ... -def run_fn_fixture_setup(request) -> None: ... -def run_fn_fixture_teardown(request) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/profiling.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/profiling.pyi deleted file mode 100644 index ff48b0d7e32b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/profiling.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Any - -class ProfileStatsFile: - force_write: Any - write: Any - fname: Any - short_fname: Any - data: Any - dump: Any - sort: Any - def __init__(self, filename, sort: str = ..., dump: Any | None = ...): ... - @property - def platform_key(self): ... - def has_stats(self): ... - def result(self, callcount): ... - def reset_count(self) -> None: ... - def replace(self, callcount) -> None: ... - -def function_call_count(variance: float = ..., times: int = ..., warmup: int = ...): ... -def count_functions(variance: float = ...) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/provision.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/provision.pyi deleted file mode 100644 index ec8c6487d6b0..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/provision.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Any - -log: Any -FOLLOWER_IDENT: Any - -class register: - fns: Any - def __init__(self) -> None: ... - @classmethod - def init(cls, fn): ... - def for_db(self, *dbnames): ... - def __call__(self, cfg, *arg): ... - -def create_follower_db(follower_ident) -> None: ... -def setup_config(db_url, options, file_config, follower_ident): ... -def drop_follower_db(follower_ident) -> None: ... -def generate_db_urls(db_urls, extra_drivers) -> None: ... -def generate_driver_url(url, driver, query_str): ... -def drop_all_schema_objects_pre_tables(cfg, eng) -> None: ... -def drop_all_schema_objects_post_tables(cfg, eng) -> None: ... -def drop_all_schema_objects(cfg, eng) -> None: ... -def create_db(cfg, eng, ident) -> None: ... -def drop_db(cfg, eng, ident) -> None: ... -def update_db_opts(cfg, db_opts) -> None: ... -def post_configure_engine(url, engine, follower_ident) -> None: ... -def follower_url_from_main(url, ident): ... -def configure_follower(cfg, ident) -> None: ... -def run_reap_dbs(url, ident) -> None: ... -def reap_dbs(idents_file) -> None: ... -def temp_table_keyword_args(cfg, eng) -> None: ... -def prepare_for_drop_tables(config, connection) -> None: ... -def stop_test_class_outside_fixtures(config, db, testcls) -> None: ... -def get_temp_table_name(cfg, eng, base_name): ... -def set_default_schema_on_connection(cfg, dbapi_connection, schema_name) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/requirements.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/requirements.pyi deleted file mode 100644 index 5f0a97c1a49a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/requirements.pyi +++ /dev/null @@ -1,381 +0,0 @@ -class Requirements: ... - -class SuiteRequirements(Requirements): - @property - def create_table(self): ... - @property - def drop_table(self): ... - @property - def table_ddl_if_exists(self): ... - @property - def index_ddl_if_exists(self): ... - @property - def foreign_keys(self): ... - @property - def table_value_constructor(self): ... - @property - def standard_cursor_sql(self): ... - @property - def on_update_cascade(self): ... - @property - def non_updating_cascade(self): ... - @property - def deferrable_fks(self): ... - @property - def on_update_or_deferrable_fks(self): ... - @property - def queue_pool(self): ... - @property - def self_referential_foreign_keys(self): ... - @property - def foreign_key_ddl(self): ... - @property - def named_constraints(self): ... - @property - def implicitly_named_constraints(self): ... - @property - def subqueries(self): ... - @property - def offset(self): ... - @property - def bound_limit_offset(self): ... - @property - def sql_expression_limit_offset(self): ... - @property - def parens_in_union_contained_select_w_limit_offset(self): ... - @property - def parens_in_union_contained_select_wo_limit_offset(self): ... - @property - def boolean_col_expressions(self): ... - @property - def nullable_booleans(self): ... - @property - def nullsordering(self): ... - @property - def standalone_binds(self): ... - @property - def standalone_null_binds_whereclause(self): ... - @property - def intersect(self): ... - @property - def except_(self): ... - @property - def window_functions(self): ... - @property - def ctes(self): ... - @property - def ctes_with_update_delete(self): ... - @property - def ctes_on_dml(self): ... - @property - def autoincrement_insert(self): ... - @property - def fetch_rows_post_commit(self): ... - @property - def group_by_complex_expression(self): ... - @property - def sane_rowcount(self): ... - @property - def sane_multi_rowcount(self): ... - @property - def sane_rowcount_w_returning(self): ... - @property - def empty_inserts(self): ... - @property - def empty_inserts_executemany(self): ... - @property - def insert_from_select(self): ... - @property - def full_returning(self): ... - @property - def insert_executemany_returning(self): ... - @property - def returning(self): ... - @property - def tuple_in(self): ... - @property - def tuple_in_w_empty(self): ... - @property - def duplicate_names_in_cursor_description(self): ... - @property - def denormalized_names(self): ... - @property - def multivalues_inserts(self): ... - @property - def implements_get_lastrowid(self): ... - @property - def emulated_lastrowid(self): ... - @property - def emulated_lastrowid_even_with_sequences(self): ... - @property - def dbapi_lastrowid(self): ... - @property - def views(self): ... - @property - def schemas(self): ... - @property - def cross_schema_fk_reflection(self): ... - @property - def foreign_key_constraint_name_reflection(self): ... - @property - def implicit_default_schema(self): ... - @property - def default_schema_name_switch(self): ... - @property - def server_side_cursors(self): ... - @property - def sequences(self): ... - @property - def no_sequences(self): ... - @property - def sequences_optional(self): ... - @property - def supports_lastrowid(self): ... - @property - def no_lastrowid_support(self): ... - @property - def reflects_pk_names(self): ... - @property - def table_reflection(self): ... - @property - def reflect_tables_no_columns(self): ... - @property - def comment_reflection(self): ... - @property - def view_column_reflection(self): ... - @property - def view_reflection(self): ... - @property - def schema_reflection(self): ... - @property - def primary_key_constraint_reflection(self): ... - @property - def foreign_key_constraint_reflection(self): ... - @property - def foreign_key_constraint_option_reflection_ondelete(self): ... - @property - def fk_constraint_option_reflection_ondelete_restrict(self): ... - @property - def fk_constraint_option_reflection_ondelete_noaction(self): ... - @property - def foreign_key_constraint_option_reflection_onupdate(self): ... - @property - def fk_constraint_option_reflection_onupdate_restrict(self): ... - @property - def temp_table_reflection(self): ... - @property - def temp_table_reflect_indexes(self): ... - @property - def temp_table_names(self): ... - @property - def temporary_tables(self): ... - @property - def temporary_views(self): ... - @property - def index_reflection(self): ... - @property - def index_reflects_included_columns(self): ... - @property - def indexes_with_ascdesc(self): ... - @property - def indexes_with_expressions(self): ... - @property - def unique_constraint_reflection(self): ... - @property - def check_constraint_reflection(self): ... - @property - def duplicate_key_raises_integrity_error(self): ... - @property - def unbounded_varchar(self): ... - @property - def unicode_data(self): ... - @property - def unicode_ddl(self): ... - @property - def symbol_names_w_double_quote(self): ... - @property - def datetime_literals(self): ... - @property - def datetime(self): ... - @property - def datetime_microseconds(self): ... - @property - def timestamp_microseconds(self): ... - @property - def datetime_historic(self): ... - @property - def date(self): ... - @property - def date_coerces_from_datetime(self): ... - @property - def date_historic(self): ... - @property - def time(self): ... - @property - def time_microseconds(self): ... - @property - def binary_comparisons(self): ... - @property - def binary_literals(self): ... - @property - def autocommit(self): ... - @property - def isolation_level(self): ... - def get_isolation_levels(self, config) -> None: ... - @property - def json_type(self): ... - @property - def json_array_indexes(self): ... - @property - def json_index_supplementary_unicode_element(self): ... - @property - def legacy_unconditional_json_extract(self): ... - @property - def precision_numerics_general(self): ... - @property - def precision_numerics_enotation_small(self): ... - @property - def precision_numerics_enotation_large(self): ... - @property - def precision_numerics_many_significant_digits(self): ... - @property - def cast_precision_numerics_many_significant_digits(self): ... - @property - def implicit_decimal_binds(self): ... - @property - def nested_aggregates(self): ... - @property - def recursive_fk_cascade(self): ... - @property - def precision_numerics_retains_significant_digits(self): ... - @property - def infinity_floats(self): ... - @property - def precision_generic_float_type(self): ... - @property - def floats_to_four_decimals(self): ... - @property - def fetch_null_from_numeric(self): ... - @property - def text_type(self): ... - @property - def empty_strings_varchar(self): ... - @property - def empty_strings_text(self): ... - @property - def expressions_against_unbounded_text(self): ... - @property - def selectone(self): ... - @property - def savepoints(self): ... - @property - def two_phase_transactions(self): ... - @property - def update_from(self): ... - @property - def delete_from(self): ... - @property - def update_where_target_in_subquery(self): ... - @property - def mod_operator_as_percent_sign(self): ... - @property - def percent_schema_names(self): ... - @property - def order_by_col_from_union(self): ... - @property - def order_by_label_with_expression(self): ... - @property - def order_by_collation(self): ... - def get_order_by_collation(self, config) -> None: ... - @property - def unicode_connections(self): ... - @property - def graceful_disconnects(self): ... - @property - def independent_connections(self): ... - @property - def skip_mysql_on_windows(self): ... - @property - def ad_hoc_engines(self): ... - @property - def no_windows(self): ... - @property - def timing_intensive(self): ... - @property - def memory_intensive(self): ... - @property - def threading_with_mock(self): ... - @property - def sqlalchemy2_stubs(self): ... - @property - def python2(self): ... - @property - def python3(self): ... - @property - def pep520(self): ... - @property - def insert_order_dicts(self): ... - @property - def python36(self): ... - @property - def python37(self): ... - @property - def dataclasses(self): ... - @property - def python38(self): ... - @property - def cpython(self): ... - @property - def patch_library(self): ... - @property - def non_broken_pickle(self): ... - @property - def predictable_gc(self): ... - @property - def no_coverage(self): ... - @property - def sqlite(self): ... - @property - def cextensions(self): ... - @property - def async_dialect(self): ... - @property - def greenlet(self): ... - @property - def computed_columns(self): ... - @property - def computed_columns_stored(self): ... - @property - def computed_columns_virtual(self): ... - @property - def computed_columns_default_persisted(self): ... - @property - def computed_columns_reflect_persisted(self): ... - @property - def supports_distinct_on(self): ... - @property - def supports_is_distinct_from(self): ... - @property - def identity_columns(self): ... - @property - def identity_columns_standard(self): ... - @property - def regexp_match(self): ... - @property - def regexp_replace(self): ... - @property - def fetch_first(self): ... - @property - def fetch_percent(self): ... - @property - def fetch_ties(self): ... - @property - def fetch_no_order_by(self): ... - @property - def fetch_offset_with_options(self): ... - @property - def fetch_expression(self): ... - @property - def autoincrement_without_sequence(self): ... - @property - def generic_classes(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/schema.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/schema.pyi deleted file mode 100644 index dc8b62196f67..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/schema.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -def Table(*args, **kw): ... -def Column(*args, **kw): ... - -class eq_type_affinity: - target: Any - def __init__(self, target) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - -class eq_clause_element: - target: Any - def __init__(self, target) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/util.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/util.pyi deleted file mode 100644 index e716d838a43c..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/util.pyi +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any - -def non_refcount_gc_collect(*args) -> None: ... # only present on Python implementations with non-refcount gc -def gc_collect(generation: int = ...) -> None: ... -def lazy_gc() -> None: ... -def picklers(): ... -def random_choices(population, k: int = ...): ... -def round_decimal(value, prec): ... - -class RandomSet(set[Any]): - def __iter__(self): ... - def pop(self): ... - def union(self, other): ... - def difference(self, other): ... - def intersection(self, other): ... - def copy(self): ... - -def conforms_partial_ordering(tuples, sorted_elements): ... -def all_partial_orderings(tuples, elements): ... -def function_named(fn, name): ... -def run_as_contextmanager(ctx, fn, *arg, **kw): ... -def rowset(results): ... -def fail(msg) -> None: ... -def provide_metadata(fn, *args, **kw): ... -def flag_combinations(*combinations): ... -def lambda_combinations(lambda_arg_sets, **kw): ... -def resolve_lambda(__fn, **kw): ... -def metadata_fixture(ddl: str = ...): ... -def force_drop_names(*names): ... - -class adict(dict[Any, Any]): - def __getattribute__(self, key): ... - def __call__(self, *keys): ... - get_all: Any - -def drop_all_tables_from_metadata(metadata, engine_or_connection) -> None: ... -def drop_all_tables(engine, inspector, schema: Any | None = ..., include_names: Any | None = ...) -> None: ... -def teardown_events(event_cls): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/warnings.pyi b/stubs/SQLAlchemy/sqlalchemy/testing/warnings.pyi deleted file mode 100644 index 9aa4255ceaf6..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/testing/warnings.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from .. import exc as sa_exc - -class SATestSuiteWarning(sa_exc.SAWarning): ... - -def warn_test_suite(message) -> None: ... -def setup_filters() -> None: ... -def assert_warnings(fn, warning_msgs, regex: bool = ...): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/types.pyi b/stubs/SQLAlchemy/sqlalchemy/types.pyi deleted file mode 100644 index ee455334d03a..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/types.pyi +++ /dev/null @@ -1,106 +0,0 @@ -from .sql.sqltypes import ( - ARRAY as ARRAY, - BIGINT as BIGINT, - BINARY as BINARY, - BLOB as BLOB, - BOOLEAN as BOOLEAN, - CHAR as CHAR, - CLOB as CLOB, - DATE as DATE, - DATETIME as DATETIME, - DECIMAL as DECIMAL, - FLOAT as FLOAT, - INT as INT, - INTEGER as INTEGER, - JSON as JSON, - NCHAR as NCHAR, - NUMERIC as NUMERIC, - NVARCHAR as NVARCHAR, - REAL as REAL, - SMALLINT as SMALLINT, - TEXT as TEXT, - TIME as TIME, - TIMESTAMP as TIMESTAMP, - VARBINARY as VARBINARY, - VARCHAR as VARCHAR, - BigInteger as BigInteger, - Boolean as Boolean, - Concatenable as Concatenable, - Date as Date, - DateTime as DateTime, - Enum as Enum, - Float as Float, - Indexable as Indexable, - Integer as Integer, - Interval as Interval, - LargeBinary as LargeBinary, - MatchType as MatchType, - NullType as NullType, - Numeric as Numeric, - PickleType as PickleType, - SmallInteger as SmallInteger, - String as String, - Text as Text, - Time as Time, - TupleType as TupleType, - Unicode as Unicode, - UnicodeText as UnicodeText, - _Binary as _Binary, -) -from .sql.type_api import ( - ExternalType as ExternalType, - TypeDecorator as TypeDecorator, - TypeEngine as TypeEngine, - UserDefinedType as UserDefinedType, -) - -__all__ = [ - "TypeEngine", - "TypeDecorator", - "UserDefinedType", - "ExternalType", - "INT", - "CHAR", - "VARCHAR", - "NCHAR", - "NVARCHAR", - "TEXT", - "Text", - "FLOAT", - "NUMERIC", - "REAL", - "DECIMAL", - "TIMESTAMP", - "DATETIME", - "CLOB", - "BLOB", - "BINARY", - "VARBINARY", - "BOOLEAN", - "BIGINT", - "SMALLINT", - "INTEGER", - "DATE", - "TIME", - "TupleType", - "String", - "Integer", - "SmallInteger", - "BigInteger", - "Numeric", - "Float", - "DateTime", - "Date", - "Time", - "LargeBinary", - "Boolean", - "Unicode", - "Concatenable", - "UnicodeText", - "PickleType", - "Interval", - "Enum", - "Indexable", - "ARRAY", - "JSON", -] diff --git a/stubs/SQLAlchemy/sqlalchemy/util/__init__.pyi b/stubs/SQLAlchemy/sqlalchemy/util/__init__.pyi deleted file mode 100644 index d569a665dcd9..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/__init__.pyi +++ /dev/null @@ -1,174 +0,0 @@ -from collections import defaultdict as defaultdict -from contextlib import contextmanager as contextmanager -from functools import partial as partial, update_wrapper as update_wrapper - -from ._collections import ( - EMPTY_DICT as EMPTY_DICT, - EMPTY_SET as EMPTY_SET, - FacadeDict as FacadeDict, - IdentitySet as IdentitySet, - ImmutableContainer as ImmutableContainer, - ImmutableProperties as ImmutableProperties, - LRUCache as LRUCache, - OrderedDict as OrderedDict, - OrderedIdentitySet as OrderedIdentitySet, - OrderedProperties as OrderedProperties, - OrderedSet as OrderedSet, - PopulateDict as PopulateDict, - Properties as Properties, - ScopedRegistry as ScopedRegistry, - ThreadLocalRegistry as ThreadLocalRegistry, - UniqueAppender as UniqueAppender, - WeakPopulateDict as WeakPopulateDict, - WeakSequence as WeakSequence, - coerce_generator_arg as coerce_generator_arg, - coerce_to_immutabledict as coerce_to_immutabledict, - collections_abc as collections_abc, - column_dict as column_dict, - column_set as column_set, - flatten_iterator as flatten_iterator, - has_dupes as has_dupes, - has_intersection as has_intersection, - immutabledict as immutabledict, - ordered_column_set as ordered_column_set, - sort_dictionary as sort_dictionary, - to_column_set as to_column_set, - to_list as to_list, - to_set as to_set, - unique_list as unique_list, - update_copy as update_copy, -) -from ._preloaded import preload_module as preload_module, preloaded as preloaded -from .compat import ( - ABC as ABC, - TYPE_CHECKING as TYPE_CHECKING, - StringIO as StringIO, - arm as arm, - b as b, - b64decode as b64decode, - b64encode as b64encode, - binary_type as binary_type, - binary_types as binary_types, - byte_buffer as byte_buffer, - callable as callable, - cmp as cmp, - cpython as cpython, - dataclass_fields as dataclass_fields, - decode_backslashreplace as decode_backslashreplace, - dottedgetter as dottedgetter, - has_refcount_gc as has_refcount_gc, - inspect_getfullargspec as inspect_getfullargspec, - int_types as int_types, - iterbytes as iterbytes, - itertools_filter as itertools_filter, - itertools_filterfalse as itertools_filterfalse, - local_dataclass_fields as local_dataclass_fields, - namedtuple as namedtuple, - next as next, - nullcontext as nullcontext, - osx as osx, - parse_qsl as parse_qsl, - perf_counter as perf_counter, - pickle as pickle, - print_ as print_, - py2k as py2k, - py3k as py3k, - py37 as py37, - py38 as py38, - py39 as py39, - pypy as pypy, - quote_plus as quote_plus, - raise_ as raise_, - raise_from_cause as raise_from_cause, - reduce as reduce, - reraise as reraise, - string_types as string_types, - text_type as text_type, - threading as threading, - timezone as timezone, - u as u, - ue as ue, - unquote as unquote, - unquote_plus as unquote_plus, - win32 as win32, - with_metaclass as with_metaclass, - zip_longest as zip_longest, -) -from .concurrency import ( - asyncio as asyncio, - await_fallback as await_fallback, - await_only as await_only, - greenlet_spawn as greenlet_spawn, - is_exit_exception as is_exit_exception, -) -from .deprecations import ( - SQLALCHEMY_WARN_20 as SQLALCHEMY_WARN_20, - deprecated as deprecated, - deprecated_20 as deprecated_20, - deprecated_20_cls as deprecated_20_cls, - deprecated_cls as deprecated_cls, - deprecated_params as deprecated_params, - inject_docstring_text as inject_docstring_text, - moved_20 as moved_20, - warn_deprecated as warn_deprecated, - warn_deprecated_20 as warn_deprecated_20, -) -from .langhelpers import ( - EnsureKWArgType as EnsureKWArgType, - HasMemoized as HasMemoized, - MemoizedSlots as MemoizedSlots, - NoneType as NoneType, - PluginLoader as PluginLoader, - add_parameter_text as add_parameter_text, - as_interface as as_interface, - asbool as asbool, - asint as asint, - assert_arg_type as assert_arg_type, - attrsetter as attrsetter, - bool_or_str as bool_or_str, - chop_traceback as chop_traceback, - class_hierarchy as class_hierarchy, - classproperty as classproperty, - clsname_as_plain_name as clsname_as_plain_name, - coerce_kw_type as coerce_kw_type, - constructor_copy as constructor_copy, - constructor_key as constructor_key, - counter as counter, - create_proxy_methods as create_proxy_methods, - decode_slice as decode_slice, - decorator as decorator, - dictlike_iteritems as dictlike_iteritems, - duck_type_collection as duck_type_collection, - ellipses_string as ellipses_string, - format_argspec_init as format_argspec_init, - format_argspec_plus as format_argspec_plus, - generic_repr as generic_repr, - get_callable_argspec as get_callable_argspec, - get_cls_kwargs as get_cls_kwargs, - get_func_kwargs as get_func_kwargs, - getargspec_init as getargspec_init, - has_compiled_ext as has_compiled_ext, - hybridmethod as hybridmethod, - hybridproperty as hybridproperty, - iterate_attributes as iterate_attributes, - map_bits as map_bits, - md5_hex as md5_hex, - memoized_instancemethod as memoized_instancemethod, - memoized_property as memoized_property, - method_is_overridden as method_is_overridden, - methods_equivalent as methods_equivalent, - monkeypatch_proxied_specials as monkeypatch_proxied_specials, - only_once as only_once, - portable_instancemethod as portable_instancemethod, - quoted_token_parser as quoted_token_parser, - safe_reraise as safe_reraise, - set_creation_order as set_creation_order, - string_or_unprintable as string_or_unprintable, - symbol as symbol, - unbound_method_to_callable as unbound_method_to_callable, - walk_subclasses as walk_subclasses, - warn as warn, - warn_exception as warn_exception, - warn_limited as warn_limited, - wrap_callable as wrap_callable, -) diff --git a/stubs/SQLAlchemy/sqlalchemy/util/_collections.pyi b/stubs/SQLAlchemy/sqlalchemy/util/_collections.pyi deleted file mode 100644 index 49d369ea1713..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/_collections.pyi +++ /dev/null @@ -1,226 +0,0 @@ -import collections.abc -import sys -from _typeshed import Self, SupportsKeysAndGetItem -from collections.abc import Callable, Iterable, Iterator -from typing import Any, Generic, NoReturn, TypeVar, overload - -from ..cimmutabledict import immutabledict as immutabledict -from ..sql.elements import ColumnElement - -_S = TypeVar("_S") -_T = TypeVar("_T") - -collections_abc = collections.abc - -EMPTY_SET: frozenset[Any] - -class ImmutableContainer: - def __delitem__(self, *arg: object, **kw: object) -> NoReturn: ... - def __setitem__(self, *arg: object, **kw: object) -> NoReturn: ... - def __setattr__(self, *arg: object, **kw: object) -> NoReturn: ... - -def coerce_to_immutabledict(d) -> immutabledict: ... - -EMPTY_DICT: immutabledict - -class FacadeDict(ImmutableContainer, dict[Any, Any]): - clear: Any - pop: Any - popitem: Any - setdefault: Any - update: Any - def __new__(cls, *args): ... - def copy(self) -> None: ... # type: ignore[override] - def __reduce__(self): ... - -class Properties(Generic[_T]): - def __init__(self, data: dict[str, _T]) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __dir__(self) -> list[str]: ... - def __add__(self, other: Iterable[_S]) -> list[_S | _T]: ... - def __setitem__(self, key: str, obj: _T) -> None: ... - def __getitem__(self, key: str) -> _T: ... - def __delitem__(self, key: str) -> None: ... - def __setattr__(self, key: str, obj: _T) -> None: ... - def __getattr__(self, key: str) -> _T: ... - def __contains__(self, key: str) -> bool: ... - def as_immutable(self) -> ImmutableProperties[_T]: ... - def update(self, value: Iterable[tuple[str, _T]] | SupportsKeysAndGetItem[str, _T]) -> None: ... - @overload - def get(self, key: str) -> _T | None: ... - @overload - def get(self, key: str, default: _S) -> _T | _S: ... - def keys(self) -> list[str]: ... - def values(self) -> list[_T]: ... - def items(self) -> list[tuple[str, _T]]: ... - def has_key(self, key: str) -> bool: ... - def clear(self) -> None: ... - -class OrderedProperties(Properties[_T], Generic[_T]): - def __init__(self) -> None: ... - -class ImmutableProperties(ImmutableContainer, Properties[_T], Generic[_T]): ... - -if sys.version_info >= (3, 7): - OrderedDict = dict -else: - class OrderedDict(dict[Any, Any]): - def __reduce__(self): ... - def __init__(self, ____sequence: Any | None = ..., **kwargs) -> None: ... - def clear(self) -> None: ... - def copy(self): ... - def __copy__(self): ... - def update(self, ____sequence: Any | None = ..., **kwargs) -> None: ... - def setdefault(self, key, value): ... - def __iter__(self): ... - def keys(self): ... - def values(self): ... - def items(self): ... - def __setitem__(self, key, obj) -> None: ... - def __delitem__(self, key) -> None: ... - def pop(self, key, *default): ... - def popitem(self): ... - -def sort_dictionary(d, key: Any | None = ...): ... - -class OrderedSet(set[_T], Generic[_T]): - def __init__(self, d: Iterable[_T] | None = ...) -> None: ... - def add(self, element: _T) -> None: ... - def remove(self, element: _T) -> None: ... - def insert(self, pos: int, element: _T) -> None: ... - def discard(self, element: _T) -> None: ... - def clear(self) -> None: ... - def __getitem__(self, key: int) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... - def __add__(self, other: Iterable[_S]) -> OrderedSet[_S | _T]: ... - def update(self: Self, iterable: Iterable[_T]) -> Self: ... # type: ignore[override] - __ior__ = update # type: ignore[assignment] - def union(self, other: Iterable[_S]) -> OrderedSet[_S | _T]: ... # type: ignore[override] - __or__ = union # type: ignore[assignment] - def intersection(self: Self, other: Iterable[Any]) -> Self: ... # type: ignore[override] - __and__ = intersection # type: ignore[assignment] - def symmetric_difference(self, other: Iterable[_S]) -> OrderedSet[_S | _T]: ... - __xor__ = symmetric_difference # type: ignore[assignment] - def difference(self: Self, other: Iterable[Any]) -> Self: ... # type: ignore[override] - __sub__ = difference # type: ignore[assignment] - def intersection_update(self: Self, other: Iterable[Any]) -> Self: ... # type: ignore[override] - __iand__ = intersection_update # type: ignore[assignment] - def symmetric_difference_update(self: Self, other: Iterable[_T]) -> Self: ... # type: ignore[override] - __ixor__ = symmetric_difference_update # type: ignore[assignment] - def difference_update(self: Self, other: Iterable[Any]) -> Self: ... # type: ignore[override] - __isub__ = difference_update # type: ignore[assignment] - -class IdentitySet: - def __init__(self, iterable: Any | None = ...) -> None: ... - def add(self, value) -> None: ... - def __contains__(self, value): ... - def remove(self, value) -> None: ... - def discard(self, value) -> None: ... - def pop(self): ... - def clear(self) -> None: ... - def __cmp__(self, other) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def issubset(self, iterable): ... - def __le__(self, other): ... - def __lt__(self, other): ... - def issuperset(self, iterable): ... - def __ge__(self, other): ... - def __gt__(self, other): ... - def union(self, iterable): ... - def __or__(self, other): ... - def update(self, iterable) -> None: ... - def __ior__(self, other): ... - def difference(self, iterable): ... - def __sub__(self, other): ... - def difference_update(self, iterable) -> None: ... - def __isub__(self, other): ... - def intersection(self, iterable): ... - def __and__(self, other): ... - def intersection_update(self, iterable) -> None: ... - def __iand__(self, other): ... - def symmetric_difference(self, iterable): ... - def __xor__(self, other): ... - def symmetric_difference_update(self, iterable) -> None: ... - def __ixor__(self, other): ... - def copy(self): ... - __copy__: Any - def __len__(self): ... - def __iter__(self): ... - def __hash__(self): ... - -class WeakSequence: - def __init__(self, __elements=...) -> None: ... - def append(self, item) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __getitem__(self, index): ... - -class OrderedIdentitySet(IdentitySet): - def __init__(self, iterable: Any | None = ...) -> None: ... - -class PopulateDict(dict[Any, Any]): - creator: Any - def __init__(self, creator) -> None: ... - def __missing__(self, key): ... - -class WeakPopulateDict(dict[Any, Any]): - creator: Any - weakself: Any - def __init__(self, creator_method) -> None: ... - def __missing__(self, key): ... - -column_set = set -column_dict = dict -ordered_column_set = OrderedSet[ColumnElement] - -def unique_list(seq: Iterable[_T], hashfunc: Callable[[_T], Any] | None = ...) -> list[_T]: ... - -class UniqueAppender: - data: Any - def __init__(self, data, via: Any | None = ...) -> None: ... - def append(self, item) -> None: ... - def __iter__(self): ... - -def coerce_generator_arg(arg): ... -def to_list(x, default: Any | None = ...): ... -def has_intersection(set_, iterable): ... -def to_set(x): ... -def to_column_set(x): ... -def update_copy(d, _new: Any | None = ..., **kw): ... -def flatten_iterator(x) -> None: ... - -class LRUCache(dict[Any, Any]): - capacity: Any - threshold: Any - size_alert: Any - def __init__(self, capacity: int = ..., threshold: float = ..., size_alert: Any | None = ...) -> None: ... - def get(self, key, default: Any | None = ...): ... - def __getitem__(self, key): ... - def values(self): ... - def setdefault(self, key, value): ... - def __setitem__(self, key, value) -> None: ... - @property - def size_threshold(self): ... - -class ScopedRegistry: - createfunc: Any - scopefunc: Any - registry: Any - def __init__(self, createfunc, scopefunc) -> None: ... - def __call__(self): ... - def has(self): ... - def set(self, obj) -> None: ... - def clear(self) -> None: ... - -class ThreadLocalRegistry(ScopedRegistry): - createfunc: Any - registry: Any - def __init__(self, createfunc) -> None: ... - def __call__(self): ... - def has(self): ... - def set(self, obj) -> None: ... - def clear(self) -> None: ... - -def has_dupes(sequence, target): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/_compat_py3k.pyi b/stubs/SQLAlchemy/sqlalchemy/util/_compat_py3k.pyi deleted file mode 100644 index d23165bf6456..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/_compat_py3k.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -class _AsyncGeneratorContextManager: - gen: Any - __doc__: Any - def __init__(self, func, args, kwds) -> None: ... - async def __aenter__(self): ... - async def __aexit__(self, typ, value, traceback): ... - -def asynccontextmanager(func): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/_concurrency_py3k.pyi b/stubs/SQLAlchemy/sqlalchemy/util/_concurrency_py3k.pyi deleted file mode 100644 index b900f1a846b2..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/_concurrency_py3k.pyi +++ /dev/null @@ -1,26 +0,0 @@ -import asyncio as asyncio -from collections.abc import Callable, Coroutine -from typing import Any - -from .langhelpers import memoized_property - -_greenlet = Any # actually greenlet.greenlet - -def is_exit_exception(e): ... - -class _AsyncIoGreenlet(_greenlet): - driver: Any - gr_context: Any - def __init__(self, fn, driver) -> None: ... - -def await_only(awaitable: Coroutine[Any, Any, Any]) -> Any: ... -def await_fallback(awaitable: Coroutine[Any, Any, Any]) -> Any: ... -async def greenlet_spawn(fn: Callable[..., Any], *args, _require_await: bool = ..., **kwargs) -> Any: ... - -class AsyncAdaptedLock: - @memoized_property - def mutex(self): ... - def __enter__(self): ... - def __exit__(self, *arg, **kw) -> None: ... - -def get_event_loop(): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/_preloaded.pyi b/stubs/SQLAlchemy/sqlalchemy/util/_preloaded.pyi deleted file mode 100644 index eaabad39009d..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/_preloaded.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class _ModuleRegistry: - module_registry: Any - prefix: Any - def __init__(self, prefix: str = ...) -> None: ... - def preload_module(self, *deps): ... - def import_prefix(self, path) -> None: ... - -preloaded: Any -preload_module: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/util/compat.pyi b/stubs/SQLAlchemy/sqlalchemy/util/compat.pyi deleted file mode 100644 index 38065012f51b..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/compat.pyi +++ /dev/null @@ -1,104 +0,0 @@ -import builtins -import collections -import contextlib -import itertools -import operator -import pickle as pickle -import threading as threading -from abc import ABC as ABC -from datetime import timezone as timezone -from functools import reduce as reduce -from io import BytesIO as BytesIO, StringIO as StringIO -from itertools import zip_longest as zip_longest -from time import perf_counter as perf_counter -from typing import TYPE_CHECKING as TYPE_CHECKING, Any, NamedTuple -from urllib.parse import ( - parse_qsl as parse_qsl, - quote as quote, - quote_plus as quote_plus, - unquote as unquote, - unquote_plus as unquote_plus, -) - -byte_buffer = BytesIO - -py39: Any -py38: Any -py37: Any -py3k: Any -py2k: Any -pypy: Any -cpython: Any -win32: Any -osx: Any -arm: Any -has_refcount_gc: Any -contextmanager = contextlib.contextmanager -dottedgetter = operator.attrgetter -namedtuple = collections.namedtuple -next = builtins.next - -class FullArgSpec(NamedTuple): - args: Any - varargs: Any - varkw: Any - defaults: Any - kwonlyargs: Any - kwonlydefaults: Any - annotations: Any - -class nullcontext: - enter_result: Any - def __init__(self, enter_result: Any | None = ...) -> None: ... - def __enter__(self): ... - def __exit__(self, *excinfo) -> None: ... - -def inspect_getfullargspec(func): ... -def importlib_metadata_get(group): ... - -string_types: tuple[type, ...] -binary_types: tuple[type, ...] -binary_type = bytes -text_type = str -int_types: tuple[type, ...] -iterbytes = iter -long_type = int -itertools_filterfalse = itertools.filterfalse -itertools_filter = filter -itertools_imap = map -exec_: Any -import_: Any -print_: Any - -def b(s): ... -def b64decode(x): ... -def b64encode(x): ... -def decode_backslashreplace(text, encoding): ... -def cmp(a, b): ... -def raise_(exception, with_traceback: Any | None = ..., replace_context: Any | None = ..., from_: bool = ...) -> None: ... -def u(s): ... -def ue(s): ... - -callable = builtins.callable - -def safe_bytestring(text): ... -def inspect_formatargspec( - args, - varargs: Any | None = ..., - varkw: Any | None = ..., - defaults: Any | None = ..., - kwonlyargs=..., - kwonlydefaults=..., - annotations=..., - formatarg=..., - formatvarargs=..., - formatvarkw=..., - formatvalue=..., - formatreturns=..., - formatannotation=..., -): ... -def dataclass_fields(cls): ... -def local_dataclass_fields(cls): ... -def raise_from_cause(exception, exc_info: Any | None = ...) -> None: ... -def reraise(tp, value, tb: Any | None = ..., cause: Any | None = ...) -> None: ... -def with_metaclass(meta, *bases, **kw): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/concurrency.pyi b/stubs/SQLAlchemy/sqlalchemy/util/concurrency.pyi deleted file mode 100644 index 40fbc57509c5..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/concurrency.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from ._compat_py3k import asynccontextmanager as asynccontextmanager -from ._concurrency_py3k import ( - AsyncAdaptedLock as AsyncAdaptedLock, - await_fallback as await_fallback, - await_only as await_only, - greenlet_spawn as greenlet_spawn, - is_exit_exception as is_exit_exception, -) - -have_greenlet: bool -asyncio: Any | None diff --git a/stubs/SQLAlchemy/sqlalchemy/util/deprecations.pyi b/stubs/SQLAlchemy/sqlalchemy/util/deprecations.pyi deleted file mode 100644 index 73f7d1722bae..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/deprecations.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -from .langhelpers import ( - decorator as decorator, - inject_docstring_text as inject_docstring_text, - inject_param_text as inject_param_text, -) - -SQLALCHEMY_WARN_20: bool - -def warn_deprecated(msg, version, stacklevel: int = ..., code: Any | None = ...) -> None: ... -def warn_deprecated_limited(msg, args, version, stacklevel: int = ..., code: Any | None = ...) -> None: ... -def warn_deprecated_20(msg, stacklevel: int = ..., code: Any | None = ...) -> None: ... -def deprecated_cls(version, message, constructor: str = ...): ... -def deprecated_20_cls(clsname, alternative: Any | None = ..., constructor: str = ..., becomes_legacy: bool = ...): ... -def deprecated( - version, - message: Any | None = ..., - add_deprecation_to_docstring: bool = ..., - warning: Any | None = ..., - enable_warnings: bool = ..., -): ... -def moved_20(message, **kw): ... -def deprecated_20(api_name, alternative: Any | None = ..., becomes_legacy: bool = ..., **kw): ... -def deprecated_params(**specs): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi b/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi deleted file mode 100644 index 35fe7c230540..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi +++ /dev/null @@ -1,162 +0,0 @@ -from collections.abc import Callable -from typing import Any, Generic, TypeVar, overload - -from . import compat - -_R = TypeVar("_R") -_T = TypeVar("_T") - -def md5_hex(x): ... - -class safe_reraise: - warn_only: Any - def __init__(self, warn_only: bool = ...) -> None: ... - def __enter__(self) -> None: ... - def __exit__(self, type_, value, traceback) -> None: ... - -def walk_subclasses(cls) -> None: ... -def string_or_unprintable(element): ... -def clsname_as_plain_name(cls): ... -def method_is_overridden(instance_or_cls, against_method): ... -def decode_slice(slc): ... -def map_bits(fn, n) -> None: ... -def decorator(target): ... -def public_factory(target, location, class_location: Any | None = ...): ... - -class PluginLoader: - group: Any - impls: Any - auto_fn: Any - def __init__(self, group, auto_fn: Any | None = ...) -> None: ... - def clear(self) -> None: ... - def load(self, name): ... - def register(self, name, modulepath, objname): ... - -def get_cls_kwargs(cls, _set: Any | None = ...): ... -def get_func_kwargs(func): ... -def get_callable_argspec(fn, no_self: bool = ..., _is_init: bool = ...): ... -def format_argspec_plus(fn, grouped: bool = ...): ... -def format_argspec_init(method, grouped: bool = ...): ... -def create_proxy_methods( - target_cls, target_cls_sphinx_name, proxy_cls_sphinx_name, classmethods=..., methods=..., attributes=... -): ... -def getargspec_init(method): ... -def unbound_method_to_callable(func_or_cls): ... -def generic_repr(obj, additional_kw=..., to_inspect: Any | None = ..., omit_kwarg=...): ... - -class portable_instancemethod: - target: Any - name: Any - kwargs: Any - def __init__(self, meth, kwargs=...) -> None: ... - def __call__(self, *arg, **kw): ... - -def class_hierarchy(cls): ... -def iterate_attributes(cls) -> None: ... -def monkeypatch_proxied_specials( - into_cls, from_cls, skip: Any | None = ..., only: Any | None = ..., name: str = ..., from_instance: Any | None = ... -) -> None: ... -def methods_equivalent(meth1, meth2): ... -def as_interface(obj, cls: Any | None = ..., methods: Any | None = ..., required: Any | None = ...): ... - -class memoized_property(Generic[_R]): - fget: Callable[..., _R] - __doc__: str - __name__: str - def __init__(self, fget: Callable[..., _R], doc: str | None = ...) -> None: ... - @overload - def __get__(self: _T, obj: None, cls: object) -> _T: ... - @overload - def __get__(self, obj: object, cls: object) -> _R: ... - @classmethod - def reset(cls, obj: object, name: str) -> None: ... - -def memoized_instancemethod(fn): ... - -class HasMemoized: - class memoized_attribute(Generic[_R]): - fget: Callable[..., _R] - __doc__: str - __name__: str - def __init__(self, fget: Callable[..., _R], doc: str | None = ...) -> None: ... - @overload - def __get__(self: _T, obj: None, cls: object) -> _T: ... - @overload - def __get__(self, obj: object, cls: object) -> _R: ... - @classmethod - def memoized_instancemethod(cls, fn): ... - -class MemoizedSlots: - def __getattr__(self, key): ... - -def asbool(obj): ... -def bool_or_str(*text): ... -def asint(value): ... -def coerce_kw_type(kw, key, type_, flexi_bool: bool = ..., dest: Any | None = ...) -> None: ... -def constructor_key(obj, cls): ... -def constructor_copy(obj, cls, *args, **kw): ... -def counter(): ... -def duck_type_collection(specimen, default: Any | None = ...): ... -def assert_arg_type(arg, argtype, name): ... -def dictlike_iteritems(dictlike): ... - -class classproperty(property): - __doc__: Any - def __init__(self, fget, *arg, **kw) -> None: ... - def __get__(self, self_, cls): ... - -class hybridproperty(Generic[_R]): - func: Callable[..., _R] - clslevel: Callable[..., _R] - def __init__(self, func: Callable[..., _R]) -> None: ... - @overload - def __get__(self, instance: None, owner: Any) -> _R: ... - @overload - def __get__(self, instance: object, owner: object) -> _R: ... - def classlevel(self: _T, func: Callable[..., _R]) -> _T: ... - -class hybridmethod: - func: Any - clslevel: Any - def __init__(self, func) -> None: ... - def __get__(self, instance, owner): ... - def classlevel(self, func): ... - -class _symbol(int): - def __new__(cls, name, doc: Any | None = ..., canonical: Any | None = ...): ... - def __reduce__(self): ... - -class symbol: - symbols: Any - def __new__(cls, name, doc: Any | None = ..., canonical: Any | None = ...): ... - @classmethod - def parse_user_argument(cls, arg, choices, name, resolve_symbol_names: bool = ...): ... - -def set_creation_order(instance) -> None: ... -def warn_exception(func, *args, **kwargs): ... -def ellipses_string(value, len_: int = ...): ... - -class _hash_limit_string(compat.text_type): - def __new__(cls, value, num, args): ... - def __hash__(self): ... - def __eq__(self, other): ... - -def warn(msg, code: Any | None = ...) -> None: ... -def warn_limited(msg, args) -> None: ... -def only_once(fn, retry_on_exception): ... -def chop_traceback(tb, exclude_prefix=..., exclude_suffix=...): ... - -NoneType: Any - -def attrsetter(attrname): ... - -class EnsureKWArgType(type): - def __init__(cls, clsname, bases, clsdict) -> None: ... - -def wrap_callable(wrapper, fn): ... -def quoted_token_parser(value): ... -def add_parameter_text(params, text): ... -def inject_docstring_text(doctext, injecttext, pos): ... -def inject_param_text(doctext, inject_params): ... -def repr_tuple_names(names): ... -def has_compiled_ext(): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/queue.pyi b/stubs/SQLAlchemy/sqlalchemy/util/queue.pyi deleted file mode 100644 index d7b986a37ccb..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/queue.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Any - -class Empty(Exception): ... -class Full(Exception): ... - -class Queue: - mutex: Any - not_empty: Any - not_full: Any - use_lifo: Any - def __init__(self, maxsize: int = ..., use_lifo: bool = ...) -> None: ... - def qsize(self): ... - def empty(self): ... - def full(self): ... - def put(self, item, block: bool = ..., timeout: Any | None = ...) -> None: ... - def put_nowait(self, item): ... - def get(self, block: bool = ..., timeout: Any | None = ...): ... - def get_nowait(self): ... - -class AsyncAdaptedQueue: - await_: Any - use_lifo: Any - maxsize: Any - def __init__(self, maxsize: int = ..., use_lifo: bool = ...) -> None: ... - def empty(self): ... - def full(self): ... - def qsize(self): ... - def put_nowait(self, item): ... - def put(self, item, block: bool = ..., timeout: Any | None = ...): ... - def get_nowait(self): ... - def get(self, block: bool = ..., timeout: Any | None = ...): ... - -class FallbackAsyncAdaptedQueue(AsyncAdaptedQueue): - await_: Any diff --git a/stubs/SQLAlchemy/sqlalchemy/util/topological.pyi b/stubs/SQLAlchemy/sqlalchemy/util/topological.pyi deleted file mode 100644 index 04428e1ba790..000000000000 --- a/stubs/SQLAlchemy/sqlalchemy/util/topological.pyi +++ /dev/null @@ -1,3 +0,0 @@ -def sort_as_subsets(tuples, allitems) -> None: ... -def sort(tuples, allitems, deterministic_order: bool = ...) -> None: ... -def find_cycles(tuples, allitems): ... diff --git a/stubs/Send2Trash/@tests/stubtest_allowlist.txt b/stubs/Send2Trash/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0463983f46ff --- /dev/null +++ b/stubs/Send2Trash/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Modules that are not meant to be imported by users +send2trash.mac diff --git a/stubs/Send2Trash/METADATA.toml b/stubs/Send2Trash/METADATA.toml index 690242a33e3e..53406caa9583 100644 --- a/stubs/Send2Trash/METADATA.toml +++ b/stubs/Send2Trash/METADATA.toml @@ -1 +1,2 @@ -version = "1.8.*" +version = "2.1.*" +upstream-repository = "https://github.com/arsenetar/send2trash" diff --git a/stubs/Send2Trash/send2trash/__init__.pyi b/stubs/Send2Trash/send2trash/__init__.pyi index 5fa3c599c349..8c2e74a7a055 100644 --- a/stubs/Send2Trash/send2trash/__init__.pyi +++ b/stubs/Send2Trash/send2trash/__init__.pyi @@ -5,6 +5,3 @@ from .exceptions import TrashPermissionError as TrashPermissionError # The list should be list[StrOrBytesPath] but that doesn't work because invariance def send2trash(paths: list[Any] | StrOrBytesPath) -> None: ... - -# Marked as incomplete because there are platform-specific plat_foo modules -def __getattr__(name: str) -> Any: ... # incomplete diff --git a/stubs/Send2Trash/send2trash/__main__.pyi b/stubs/Send2Trash/send2trash/__main__.pyi new file mode 100644 index 000000000000..b75b3a4b3f25 --- /dev/null +++ b/stubs/Send2Trash/send2trash/__main__.pyi @@ -0,0 +1,3 @@ +from collections.abc import Iterable + +def main(args: Iterable[str] | None = None) -> None: ... diff --git a/stubs/Send2Trash/send2trash/compat.pyi b/stubs/Send2Trash/send2trash/compat.pyi deleted file mode 100644 index 91e2bc4de898..000000000000 --- a/stubs/Send2Trash/send2trash/compat.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -PY3: Any -text_type = str -binary_type = bytes -environb: Any diff --git a/stubs/Send2Trash/send2trash/exceptions.pyi b/stubs/Send2Trash/send2trash/exceptions.pyi index 7e2ca98b7594..a263f6551942 100644 --- a/stubs/Send2Trash/send2trash/exceptions.pyi +++ b/stubs/Send2Trash/send2trash/exceptions.pyi @@ -1,2 +1,5 @@ +from typing import Any + class TrashPermissionError(PermissionError): - def __init__(self, filename) -> None: ... + # Typed the same as `filename` in `PermissionError`: + def __init__(self, filename: Any) -> None: ... diff --git a/stubs/Send2Trash/send2trash/util.pyi b/stubs/Send2Trash/send2trash/util.pyi index e23e382a33b3..c89143c4f0f6 100644 --- a/stubs/Send2Trash/send2trash/util.pyi +++ b/stubs/Send2Trash/send2trash/util.pyi @@ -1 +1,5 @@ -def preprocess_paths(paths): ... +from _typeshed import StrOrBytesPath +from typing import Any + +# Should be consistent with `__init__.py` +def preprocess_paths(paths: list[Any] | StrOrBytesPath) -> list[str | bytes]: ... diff --git a/stubs/TgCrypto/@tests/stubtest_allowlist.txt b/stubs/TgCrypto/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..38f87688d4a0 --- /dev/null +++ b/stubs/TgCrypto/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# stubtest doesn't recognize these function as taking only positional-only arguments. +tgcrypto.cbc256_decrypt +tgcrypto.cbc256_encrypt +tgcrypto.ctr256_decrypt +tgcrypto.ctr256_encrypt +tgcrypto.ige256_decrypt +tgcrypto.ige256_encrypt diff --git a/stubs/TgCrypto/METADATA.toml b/stubs/TgCrypto/METADATA.toml new file mode 100644 index 000000000000..d859dd089bf5 --- /dev/null +++ b/stubs/TgCrypto/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.2.*" +upstream-repository = "https://github.com/pyrogram/tgcrypto" diff --git a/stubs/TgCrypto/tgcrypto/__init__.pyi b/stubs/TgCrypto/tgcrypto/__init__.pyi new file mode 100644 index 000000000000..ffee3190d325 --- /dev/null +++ b/stubs/TgCrypto/tgcrypto/__init__.pyi @@ -0,0 +1,8 @@ +from typing_extensions import Buffer + +def ige256_encrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... +def ige256_decrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... +def ctr256_encrypt(data: Buffer, key: Buffer, iv: Buffer, state: Buffer, /) -> bytes: ... +def ctr256_decrypt(data: Buffer, key: Buffer, iv: Buffer, state: Buffer, /) -> bytes: ... +def cbc256_encrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... +def cbc256_decrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... diff --git a/stubs/WTForms/@tests/stubtest_allowlist.txt b/stubs/WTForms/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3d8e733ca9c7 --- /dev/null +++ b/stubs/WTForms/@tests/stubtest_allowlist.txt @@ -0,0 +1,12 @@ +# Error: is not present at runtime +# ============================= +# This is hack to get around Field.__new__ not being able to return +# UnboundField +wtforms.fields.core.Field.__get__ +# Since DefaultMeta can contain arbitrary values we added __getattr__ +# to let mypy know that arbitrary attribute access is possible +wtforms.meta.DefaultMeta.__getattr__ + +# Should allow setting and deleting any attribute +wtforms.fields.core.Flags.__delattr__ +wtforms.fields.core.Flags.__setattr__ diff --git a/stubs/WTForms/@tests/test_cases/check_choices.py b/stubs/WTForms/@tests/test_cases/check_choices.py new file mode 100644 index 000000000000..41204023ad25 --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_choices.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from wtforms import SelectField + +# any way we can specify the choices inline with a literal should work + +# tuple of tuples +SelectField(choices=(("", ""),)) +SelectField(choices=((1, "1"),)) +SelectField(choices=(("", "", {}),)) +SelectField(choices=((True, "t", {}),)) +SelectField(choices=((True, "t"), (False, "f", {}))) + +# list of tuples +SelectField(choices=[("", "")]) +SelectField(choices=[(1, "1")]) +SelectField(choices=[("", "", {})]) +SelectField(choices=[(True, "t", {})]) +SelectField(choices=[(True, "t"), (False, "f", {})]) + +# dict of tuple of tuples +SelectField(choices={"a": (("", ""),)}) +SelectField(choices={"a": ((1, "1"),)}) +SelectField(choices={"a": (("", "", {}),)}) +SelectField(choices={"a": ((True, "t", {}),)}) +SelectField(choices={"a": ((True, "t"), (False, "f", {}))}) +SelectField(choices={"a": ((True, "", {}),), "b": ((False, "f"),)}) + +# dict of list of tuples +SelectField(choices={"a": [("", "")]}) +SelectField(choices={"a": [(1, "1")]}) +SelectField(choices={"a": [("", "", {})]}) +SelectField(choices={"a": [(True, "t", {})]}) +SelectField(choices={"a": [(True, "t"), (False, "f", {})]}) +SelectField(choices={"a": [(True, "", {})], "b": [(False, "f")]}) + +# the same should be true for lambdas + +# tuple of tuples +SelectField(choices=lambda: (("", ""),)) +SelectField(choices=lambda: ((1, "1"),)) +SelectField(choices=lambda: (("", "", {}),)) +SelectField(choices=lambda: ((True, "t", {}),)) +SelectField(choices=lambda: ((True, "t"), (False, "f", {}))) + +# list of tuples +SelectField(choices=lambda: [("", "")]) +SelectField(choices=lambda: [(1, "1")]) +SelectField(choices=lambda: [("", "", {})]) +SelectField(choices=lambda: [(True, "t", {})]) +SelectField(choices=lambda: [(True, "t"), (False, "f", {})]) + +# dict of tuple of tuples +SelectField(choices=lambda: {"a": (("", ""),)}) +SelectField(choices=lambda: {"a": ((1, "1"),)}) +SelectField(choices=lambda: {"a": (("", "", {}),)}) +SelectField(choices=lambda: {"a": ((True, "t", {}),)}) +SelectField(choices=lambda: {"a": ((True, "t"), (False, "f", {}))}) +SelectField(choices=lambda: {"a": ((True, "", {}),), "b": ((False, "f"),)}) + +# dict of list of tuples +SelectField(choices=lambda: {"a": [("", "")]}) +SelectField(choices=lambda: {"a": [(1, "1")]}) +SelectField(choices=lambda: {"a": [("", "", {})]}) +SelectField(choices=lambda: {"a": [(True, "t", {})]}) +SelectField(choices=lambda: {"a": [(True, "t"), (False, "f", {})]}) +SelectField(choices=lambda: {"a": [(True, "", {})], "b": [(False, "f")]}) diff --git a/stubs/WTForms/@tests/test_cases/check_filters.py b/stubs/WTForms/@tests/test_cases/check_filters.py new file mode 100644 index 000000000000..6a5abce57f23 --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_filters.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from wtforms import Field, Form + + +class Filter1: + def __call__(self, value: object) -> None: ... + + +class Filter2: + def __call__(self, input: None) -> None: ... + + +def not_a_filter(a: object, b: object) -> None: ... + + +def also_not_a_filter() -> None: ... + + +# we should accept any mapping of sequences, we can't really validate +# the filter functions when it's this nested +form = Form() +form.process(extra_filters={"foo": (str.upper, str.strip, int), "bar": (Filter1(), Filter2())}) +form.process(extra_filters={"foo": [str.upper, str.strip, int], "bar": [Filter1(), Filter2()]}) + +# regardless of how we pass the filters into Field it should work +field = Field(filters=(str.upper, str.lower, int)) +Field(filters=(Filter1(), Filter2())) +Field(filters=[str.upper, str.lower, int]) +Field(filters=[Filter1(), Filter2()]) +field.process(None, extra_filters=(str.upper, str.lower, int)) +field.process(None, extra_filters=(Filter1(), Filter2())) +field.process(None, extra_filters=[str.upper, str.lower, int]) +field.process(None, extra_filters=[Filter1(), Filter2()]) + +# but if we pass in some callables with an incompatible param spec +# then we should get type errors +Field(filters=(str.upper, str.lower, int, not_a_filter)) # type: ignore +Field(filters=(Filter1(), Filter2(), also_not_a_filter)) # type: ignore +Field(filters=[str.upper, str.lower, int, also_not_a_filter]) # type: ignore +Field(filters=[Filter1(), Filter2(), not_a_filter]) # type: ignore +field.process(None, extra_filters=(str.upper, str.lower, int, not_a_filter)) # type: ignore +field.process(None, extra_filters=(Filter1(), Filter2(), also_not_a_filter)) # type: ignore +field.process(None, extra_filters=[str.upper, str.lower, int, also_not_a_filter]) # type: ignore +field.process(None, extra_filters=[Filter1(), Filter2(), not_a_filter]) # type: ignore diff --git a/stubs/WTForms/@tests/test_cases/check_form.py b/stubs/WTForms/@tests/test_cases/check_form.py new file mode 100644 index 000000000000..250e400a1875 --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_form.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from wtforms import Form, StringField +from wtforms.fields.core import UnboundField + + +class MyForm(Form): + name = StringField() + + +form = MyForm() +assert_type(form, MyForm) +assert_type(form.name, StringField) +assert_type(MyForm.name, UnboundField[StringField]) diff --git a/stubs/WTForms/@tests/test_cases/check_validators.py b/stubs/WTForms/@tests/test_cases/check_validators.py new file mode 100644 index 000000000000..592968c183dd --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_validators.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from wtforms import DateField, Field, Form, StringField +from wtforms.validators import Email, Optional + +form = Form() +# on form we should accept any validator mapping +form.validate({"field": (Optional(),), "string_field": (Optional(), Email())}) +form.validate({"field": [Optional()], "string_field": [Optional(), Email()]}) + +# both StringField validators and Field validators should be valid +# as inputs on a StringField +string_field = StringField(validators=(Optional(), Email())) +string_field.validate(form, (Optional(), Email())) + +# but not on Field +field = Field(validators=(Optional(), Email())) # type: ignore +field.validate(form, (Optional(), Email())) # type: ignore + +# unless we only pass the Field validator +Field(validators=(Optional(),)) +field.validate(form, (Optional(),)) + +# DateField should accept Field validators but not StringField validators +date_field = DateField(validators=(Optional(), Email())) # type: ignore +date_field.validate(form, (Optional(), Email())) # type: ignore +DateField(validators=(Optional(),)) + +# for lists we can't be as strict so we won't get type errors here +Field(validators=[Optional(), Email()]) +field.validate(form, [Optional(), Email()]) +DateField(validators=[Optional(), Email()]) +date_field.validate(form, [Optional(), Email()]) diff --git a/stubs/WTForms/@tests/test_cases/check_widgets.py b/stubs/WTForms/@tests/test_cases/check_widgets.py new file mode 100644 index 000000000000..7935359a08ea --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_widgets.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from wtforms import Field, FieldList, Form, FormField, SelectField, StringField +from wtforms.widgets import Input, ListWidget, Option, Select, TableWidget, TextArea + +# more specific widgets should only work on more specific fields +Field(widget=Input()) +Field(widget=TextArea()) # type: ignore +Field(widget=Select()) # type: ignore + +# less specific widgets are fine, even if they're often not what you want +StringField(widget=Input()) +StringField(widget=TextArea()) + +SelectField(widget=Input(), option_widget=Input()) +SelectField(widget=Select(), option_widget=Option()) +# a more specific type other than Option widget is not allowed +SelectField(widget=Select(), option_widget=TextArea()) # type: ignore + +# we should be able to pass Field() even though it wants an unbound_field +# this gets around __new__ not working in type checking +FieldList(Field(), widget=Input()) +FieldList(Field(), widget=ListWidget()) + +FormField(Form, widget=Input()) +FormField(Form, widget=TableWidget()) diff --git a/stubs/WTForms/METADATA.toml b/stubs/WTForms/METADATA.toml new file mode 100644 index 000000000000..62e6a60d86ce --- /dev/null +++ b/stubs/WTForms/METADATA.toml @@ -0,0 +1,3 @@ +version = "~= 3.2.1" +upstream-repository = "https://github.com/pallets-eco/wtforms" +dependencies = ["MarkupSafe"] diff --git a/stubs/WTForms/wtforms/__init__.pyi b/stubs/WTForms/wtforms/__init__.pyi new file mode 100644 index 000000000000..1bdf94499a55 --- /dev/null +++ b/stubs/WTForms/wtforms/__init__.pyi @@ -0,0 +1,85 @@ +from typing import Final + +from wtforms import validators as validators, widgets as widgets +from wtforms.fields.choices import ( + RadioField as RadioField, + SelectField as SelectField, + SelectFieldBase as SelectFieldBase, + SelectMultipleField as SelectMultipleField, +) +from wtforms.fields.core import Field as Field, Flags as Flags, Label as Label +from wtforms.fields.datetime import ( + DateField as DateField, + DateTimeField as DateTimeField, + DateTimeLocalField as DateTimeLocalField, + MonthField as MonthField, + TimeField as TimeField, + WeekField as WeekField, +) +from wtforms.fields.form import FormField as FormField +from wtforms.fields.list import FieldList as FieldList +from wtforms.fields.numeric import ( + DecimalField as DecimalField, + DecimalRangeField as DecimalRangeField, + FloatField as FloatField, + IntegerField as IntegerField, + IntegerRangeField as IntegerRangeField, +) +from wtforms.fields.simple import ( + BooleanField as BooleanField, + ColorField as ColorField, + EmailField as EmailField, + FileField as FileField, + HiddenField as HiddenField, + MultipleFileField as MultipleFileField, + PasswordField as PasswordField, + SearchField as SearchField, + StringField as StringField, + SubmitField as SubmitField, + TelField as TelField, + TextAreaField as TextAreaField, + URLField as URLField, +) +from wtforms.form import Form as Form +from wtforms.validators import ValidationError as ValidationError + +__version__: Final[str] +__all__ = [ + "validators", + "widgets", + "Form", + "ValidationError", + "SelectField", + "SelectFieldBase", + "SelectMultipleField", + "RadioField", + "Field", + "Flags", + "Label", + "DateTimeField", + "DateField", + "TimeField", + "MonthField", + "DateTimeLocalField", + "WeekField", + "FormField", + "FieldList", + "IntegerField", + "DecimalField", + "FloatField", + "IntegerRangeField", + "DecimalRangeField", + "BooleanField", + "TextAreaField", + "PasswordField", + "FileField", + "MultipleFileField", + "HiddenField", + "SearchField", + "SubmitField", + "StringField", + "TelField", + "URLField", + "EmailField", + "ColorField", +] diff --git a/stubs/SQLAlchemy/sqlalchemy/future/orm/__init__.pyi b/stubs/WTForms/wtforms/csrf/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/future/orm/__init__.pyi rename to stubs/WTForms/wtforms/csrf/__init__.pyi diff --git a/stubs/WTForms/wtforms/csrf/core.pyi b/stubs/WTForms/wtforms/csrf/core.pyi new file mode 100644 index 000000000000..4db69c8c5223 --- /dev/null +++ b/stubs/WTForms/wtforms/csrf/core.pyi @@ -0,0 +1,41 @@ +from abc import abstractmethod +from collections.abc import Callable, Sequence +from typing import Any +from typing_extensions import Self + +from wtforms.fields import HiddenField +from wtforms.fields.core import UnboundField, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("CSRFTokenField", "CSRF") + +class CSRFTokenField(HiddenField): + current_token: str | None + csrf_impl: CSRF + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: str | Callable[[], str] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + *, + csrf_impl: CSRF, + ) -> None: ... + +class CSRF: + field_class: type[CSRFTokenField] + def setup_form(self, form: BaseForm) -> list[tuple[str, UnboundField[Any]]]: ... + @abstractmethod + def generate_csrf_token(self, csrf_token_field: CSRFTokenField) -> str: ... + @abstractmethod + def validate_csrf_token(self, form: BaseForm, field: CSRFTokenField) -> None: ... diff --git a/stubs/WTForms/wtforms/csrf/session.pyi b/stubs/WTForms/wtforms/csrf/session.pyi new file mode 100644 index 000000000000..954734a7b065 --- /dev/null +++ b/stubs/WTForms/wtforms/csrf/session.pyi @@ -0,0 +1,20 @@ +from _typeshed import SupportsItemAccess +from datetime import datetime, timedelta +from typing import Any + +from wtforms.csrf.core import CSRF, CSRFTokenField +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta + +__all__ = ("SessionCSRF",) + +class SessionCSRF(CSRF): + TIME_FORMAT: str + form_meta: DefaultMeta + def generate_csrf_token(self, csrf_token_field: CSRFTokenField) -> str: ... + def validate_csrf_token(self, form: BaseForm, field: CSRFTokenField) -> None: ... + def now(self) -> datetime: ... + @property + def time_limit(self) -> timedelta: ... + @property + def session(self) -> SupportsItemAccess[str, Any]: ... diff --git a/stubs/WTForms/wtforms/fields/__init__.pyi b/stubs/WTForms/wtforms/fields/__init__.pyi new file mode 100644 index 000000000000..b88edf9d427b --- /dev/null +++ b/stubs/WTForms/wtforms/fields/__init__.pyi @@ -0,0 +1,77 @@ +from wtforms.fields.choices import ( + RadioField as RadioField, + SelectField as SelectField, + SelectFieldBase as SelectFieldBase, + SelectMultipleField as SelectMultipleField, +) +from wtforms.fields.core import Field as Field, Flags as Flags, Label as Label +from wtforms.fields.datetime import ( + DateField as DateField, + DateTimeField as DateTimeField, + DateTimeLocalField as DateTimeLocalField, + MonthField as MonthField, + TimeField as TimeField, + WeekField as WeekField, +) +from wtforms.fields.form import FormField as FormField +from wtforms.fields.list import FieldList as FieldList +from wtforms.fields.numeric import ( + DecimalField as DecimalField, + DecimalRangeField as DecimalRangeField, + FloatField as FloatField, + IntegerField as IntegerField, + IntegerRangeField as IntegerRangeField, +) +from wtforms.fields.simple import ( + BooleanField as BooleanField, + ColorField as ColorField, + EmailField as EmailField, + FileField as FileField, + HiddenField as HiddenField, + MultipleFileField as MultipleFileField, + PasswordField as PasswordField, + SearchField as SearchField, + StringField as StringField, + SubmitField as SubmitField, + TelField as TelField, + TextAreaField as TextAreaField, + URLField as URLField, +) +from wtforms.utils import unset_value as _unset_value + +__all__ = [ + "Field", + "Flags", + "Label", + "SelectField", + "SelectFieldBase", + "SelectMultipleField", + "RadioField", + "DateTimeField", + "DateField", + "TimeField", + "MonthField", + "DateTimeLocalField", + "WeekField", + "FormField", + "IntegerField", + "DecimalField", + "FloatField", + "IntegerRangeField", + "DecimalRangeField", + "BooleanField", + "TextAreaField", + "PasswordField", + "FileField", + "MultipleFileField", + "HiddenField", + "SearchField", + "SubmitField", + "StringField", + "TelField", + "URLField", + "EmailField", + "ColorField", + "FieldList", + "_unset_value", +] diff --git a/stubs/WTForms/wtforms/fields/choices.pyi b/stubs/WTForms/wtforms/fields/choices.pyi new file mode 100644 index 000000000000..6ba8d1b40f09 --- /dev/null +++ b/stubs/WTForms/wtforms/fields/choices.pyi @@ -0,0 +1,79 @@ +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, TypeAlias +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("SelectField", "SelectMultipleField", "RadioField") + +# technically this allows a list, but we're more strict for type safety +_Choice: TypeAlias = tuple[Any, str] | tuple[Any, str, dict[str, Any]] +# it's too difficult to get type safety here due to to nested partially invariant collections +_GroupedChoices: TypeAlias = dict[str, Any] # Any should be Collection[_Choice] +_FullChoice: TypeAlias = tuple[Any, str, bool, dict[str, Any]] # value, label, selected, render_kw +_FullGroupedChoices: TypeAlias = tuple[str, Iterable[_FullChoice]] +_Option: TypeAlias = SelectFieldBase._Option + +class SelectFieldBase(Field): + option_widget: _Widget[_Option] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + option_widget: _Widget[_Option] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def iter_choices(self) -> Iterator[_FullChoice]: ... + def has_groups(self) -> bool: ... + def iter_groups(self) -> Iterator[_FullGroupedChoices]: ... + def __iter__(self) -> Iterator[_Option]: ... + + class _Option(Field): + checked: bool + +class SelectField(SelectFieldBase): + coerce: Callable[[Any], Any] + choices: Sequence[_Choice] | _GroupedChoices | None + validate_choice: bool + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + coerce: Callable[[Any], Any] = ..., + choices: Iterable[_Choice] | _GroupedChoices | Callable[[], Iterable[_Choice] | _GroupedChoices] | None = None, + validate_choice: bool = True, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + option_widget: _Widget[_Option] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def iter_choices(self) -> Iterator[_FullChoice]: ... + def has_groups(self) -> bool: ... + def iter_groups(self) -> Iterator[_FullGroupedChoices]: ... + +class SelectMultipleField(SelectField): + data: list[Any] | None + +class RadioField(SelectField): ... diff --git a/stubs/WTForms/wtforms/fields/core.pyi b/stubs/WTForms/wtforms/fields/core.pyi new file mode 100644 index 000000000000..101f31fc03c6 --- /dev/null +++ b/stubs/WTForms/wtforms/fields/core.pyi @@ -0,0 +1,134 @@ +from builtins import type as _type # type is being shadowed in Field +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from markupsafe import Markup +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _MultiDictLikeWithGetlist, _SupportsGettextAndNgettext + +_FormT = TypeVar("_FormT", bound=BaseForm) +_FieldT = TypeVar("_FieldT", bound=Field) +_FormT_contra = TypeVar("_FormT_contra", bound=BaseForm, contravariant=True) +_FieldT_contra = TypeVar("_FieldT_contra", bound=Field, contravariant=True) +# It would be nice to annotate this as invariant, i.e. input type and output type +# needs to be the same, but it will probably be too annoying to use, for now we +# trust, that people won't use it to change the type of data in a field... +_Filter: TypeAlias = Callable[[Any], Any] + +@type_check_only +class _Validator(Protocol[_FormT_contra, _FieldT_contra]): + def __call__(self, form: _FormT_contra, field: _FieldT_contra, /) -> object: ... + +@type_check_only +class _Widget(Protocol[_FieldT_contra]): + def __call__(self, field: _FieldT_contra, **kwargs: Any) -> Markup: ... + +class Field: + errors: Sequence[str] + process_errors: Sequence[str] + raw_data: list[Any] | None + object_data: Any + data: Any + validators: Sequence[_Validator[Any, Self]] + # even though this could be None on the base class, this should + # never actually be None in a real field + widget: _Widget[Self] + do_not_call_in_templates: bool + meta: DefaultMeta + default: Any | None + description: str + render_kw: dict[str, Any] + filters: Sequence[_Filter] + flags: Flags + name: str + short_name: str + id: str + type: str + label: Label + # technically this can return UnboundField, but that is not allowed + # by type checkers, so we use a descriptor hack to get around this + # limitation instead + def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... + def __init__( + self, + label: str | None = None, + # for tuple we can be a bit more type safe and only accept validators + # that would work on this or a less specific field, but in general it + # would be too annoying to restrict to Sequence[_Validator], since mypy + # will infer a list of mixed validators as list[object], since that is + # the common base class between all validators + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def __html__(self) -> str: ... + def __call__(self, **kwargs: object) -> Markup: ... + @classmethod + def check_validators(cls, validators: Iterable[_Validator[_FormT, Self]] | None) -> None: ... + def gettext(self, string: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + def validate(self, form: BaseForm, extra_validators: tuple[_Validator[_FormT, Self], ...] | list[Any] = ()) -> bool: ... + def pre_validate(self, form: BaseForm) -> None: ... + def post_validate(self, form: BaseForm, validation_stopped: bool) -> None: ... + def process( + self, formdata: _MultiDictLikeWithGetlist | None, data: Any = ..., extra_filters: Sequence[_Filter] | None = None + ) -> None: ... + def process_data(self, value: Any) -> None: ... + def process_formdata(self, valuelist: list[Any]) -> None: ... + def populate_obj(self, obj: object, name: str) -> None: ... + + # this is a workaround for what is essentially illegal in static type checking + # Field.__new__ would return an UnboundField, unless the _form parameter is + # specified. We can't really work around it by making UnboundField a subclass + # of Field, since all subclasses of Field still need to return an UnboundField + # and we can't expect third parties to add a __new__ method to every field + # they define... + # This workaround only works for Form, not BaseForm, but we take what we can get + # BaseForm shouldn't really be used anyways + @overload + def __get__(self, obj: None, owner: _type[object] | None = None) -> UnboundField[Self]: ... + @overload + def __get__(self, obj: object, owner: _type[object] | None = None) -> Self: ... + +class UnboundField(Generic[_FieldT]): + creation_counter: int + field_class: type[_FieldT] + name: str | None + args: tuple[Any, ...] + kwargs: dict[str, Any] + def __init__(self, field_class: type[_FieldT], *args: object, name: str | None = None, **kwargs: object) -> None: ... + def bind( + self, + form: BaseForm, + name: str, + prefix: str = "", + translations: _SupportsGettextAndNgettext | None = None, + **kwargs: object, + ) -> _FieldT: ... + +class Flags: + # the API for this is a bit loosey goosey, the intention probably + # was that the values should always be boolean, but __contains__ + # just returns the same thing as __getattr__ and in the widgets + # there are fields that could accept numeric values from Flags + def __getattr__(self, name: str) -> Any | None: ... + def __setattr__(self, name: str, value: object) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __contains__(self, name: str) -> Any | None: ... + +class Label: + field_id: str + text: str + def __init__(self, field_id: str, text: str) -> None: ... + def __html__(self) -> str: ... + def __call__(self, text: str | None = None, **kwargs: Any) -> Markup: ... diff --git a/stubs/WTForms/wtforms/fields/datetime.pyi b/stubs/WTForms/wtforms/fields/datetime.pyi new file mode 100644 index 000000000000..426dbfaec91f --- /dev/null +++ b/stubs/WTForms/wtforms/fields/datetime.pyi @@ -0,0 +1,138 @@ +from collections.abc import Callable, Sequence +from datetime import date, datetime, time +from typing import Any +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("DateTimeField", "DateField", "TimeField", "MonthField", "DateTimeLocalField", "WeekField") + +class DateTimeField(Field): + format: list[str] + strptime_format: list[str] + data: datetime | None + default: datetime | Callable[[], datetime] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-%m-%d %H:%M:%S", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: datetime | Callable[[], datetime] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class DateField(DateTimeField): + data: date | None # type: ignore[assignment] + default: date | Callable[[], date] | None # type: ignore[assignment] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-%m-%d", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: date | Callable[[], date] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class TimeField(DateTimeField): + data: time | None # type: ignore[assignment] + default: time | Callable[[], time] | None # type: ignore[assignment] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%H:%M", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class MonthField(DateField): + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-%m", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class WeekField(DateField): + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-W%W", # only difference is the default value + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class DateTimeLocalField(DateTimeField): + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = ..., + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... diff --git a/stubs/WTForms/wtforms/fields/form.pyi b/stubs/WTForms/wtforms/fields/form.pyi new file mode 100644 index 000000000000..16b7e2016eed --- /dev/null +++ b/stubs/WTForms/wtforms/fields/form.pyi @@ -0,0 +1,40 @@ +from collections.abc import Iterator +from typing import Any, Generic, TypeVar + +from wtforms.fields.core import Field, _Widget +from wtforms.form import BaseForm, _FormErrors +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("FormField",) + +_BoundFormT = TypeVar("_BoundFormT", bound=BaseForm) + +class FormField(Field, Generic[_BoundFormT]): + form_class: type[_BoundFormT] + form: _BoundFormT + separator: str + def __init__( + self: FormField[_BoundFormT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + form_class: type[_BoundFormT], + label: str | None = None, + validators: None = None, + separator: str = "-", + *, + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[FormField[_BoundFormT]] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def __iter__(self) -> Iterator[Field]: ... + def __getitem__(self, name: str) -> Field: ... + def __getattr__(self, name: str) -> Field: ... + @property + def data(self) -> dict[str, Any]: ... + @property + def errors(self) -> _FormErrors: ... # type: ignore[override] diff --git a/stubs/WTForms/wtforms/fields/list.pyi b/stubs/WTForms/wtforms/fields/list.pyi new file mode 100644 index 000000000000..2142009c810d --- /dev/null +++ b/stubs/WTForms/wtforms/fields/list.pyi @@ -0,0 +1,51 @@ +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, Generic, TypeVar + +from wtforms.fields.core import Field, UnboundField, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("FieldList",) + +_BoundFieldT = TypeVar("_BoundFieldT", bound=Field) + +class FieldList(Field, Generic[_BoundFieldT]): + unbound_field: UnboundField[_BoundFieldT] + min_entries: int + max_entries: int | None + last_index: int + entries: list[_BoundFieldT] + object_data: Iterable[Any] + # NOTE: This depends on the shape of errors of the bound field, which usually should + # be a `Sequence[Sequence[str]]`, but can be `Sequence[_FormErrors]` for `FormField` + # we could model this with a fake descriptor with overloads for `FieldList[FormField]` + # but it might not be worth the hassle, for now we'll just leave it lax + errors: Sequence[Any] + def __init__( + self: FieldList[_BoundFieldT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + # because of our workaround we need to accept Field as well + unbound_field: UnboundField[_BoundFieldT] | _BoundFieldT, + label: str | None = None, + validators: tuple[_Validator[_FormT, _BoundFieldT], ...] | list[Any] | None = None, + min_entries: int = 0, + max_entries: int | None = None, + separator: str = "-", + default: Iterable[Any] | Callable[[], Iterable[Any]] = (), + *, + description: str = "", + id: str | None = None, + widget: _Widget[FieldList[Any]] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def append_entry(self, data: Any = ...) -> _BoundFieldT: ... + def pop_entry(self) -> _BoundFieldT: ... + def __iter__(self) -> Iterator[_BoundFieldT]: ... + def __len__(self) -> int: ... + def __getitem__(self, index: int) -> _BoundFieldT: ... + @property + def data(self) -> list[Any]: ... diff --git a/stubs/WTForms/wtforms/fields/numeric.pyi b/stubs/WTForms/wtforms/fields/numeric.pyi new file mode 100644 index 000000000000..e88aad5a7c92 --- /dev/null +++ b/stubs/WTForms/wtforms/fields/numeric.pyi @@ -0,0 +1,146 @@ +from collections.abc import Callable, Sequence +from decimal import Decimal +from typing import Any, Literal, overload +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext +from wtforms.utils import UnsetValue + +__all__ = ("IntegerField", "DecimalField", "FloatField", "IntegerRangeField", "DecimalRangeField") + +class LocaleAwareNumberField(Field): + use_locale: bool + number_format: Any | None + locale: str + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + use_locale: bool = False, + # this accepts a babel.numbers.NumberPattern, but since it + # is an optional dependency we don't want to depend on it + # for annotating this one argument + number_format: str | Any | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class IntegerField(Field): + data: int | None + # technically this is not as strict and will accept anything + # that can be passed into int(), but we might as well be + default: int | Callable[[], int] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: int | Callable[[], int] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class DecimalField(LocaleAwareNumberField): + data: Decimal | None + # technically this is not as strict and will accept anything + # that can be passed into Decimal(), but we might as well be + default: Decimal | Callable[[], Decimal] | None + places: int | None + rounding: str | None + + @overload + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + *, + places: UnsetValue = ..., + rounding: None = None, + use_locale: Literal[True], + # this accepts a babel.numbers.NumberPattern, but since it + # is an optional dependency we don't want to depend on it + # for annotation this one argument + number_format: str | Any | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: Decimal | Callable[[], Decimal] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + @overload + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + places: int | UnsetValue | None = ..., + rounding: str | None = None, + *, + use_locale: Literal[False] = False, + # this accepts a babel.numbers.NumberPattern, but since it + # is an optional dependency we don't want to depend on it + # for annotation this one argument + number_format: str | Any | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: Decimal | Callable[[], Decimal] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class FloatField(Field): + data: float | None + # technically this is not as strict and will accept anything + # that can be passed into float(), but we might as well be + default: float | Callable[[], float] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: float | Callable[[], float] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class IntegerRangeField(IntegerField): ... +class DecimalRangeField(DecimalField): ... diff --git a/stubs/WTForms/wtforms/fields/simple.pyi b/stubs/WTForms/wtforms/fields/simple.pyi new file mode 100644 index 000000000000..13bc3f4ed45d --- /dev/null +++ b/stubs/WTForms/wtforms/fields/simple.pyi @@ -0,0 +1,81 @@ +from collections.abc import Callable, Collection, Sequence +from typing import Any +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ( + "BooleanField", + "TextAreaField", + "PasswordField", + "FileField", + "MultipleFileField", + "HiddenField", + "SearchField", + "SubmitField", + "StringField", + "TelField", + "URLField", + "EmailField", + "ColorField", +) + +class BooleanField(Field): + data: bool + default: bool | Callable[[], bool] | None + false_values: Collection[Any] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + false_values: Collection[Any] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: bool | Callable[[], bool] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class StringField(Field): + data: str | None + default: str | Callable[[], str] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: str | Callable[[], str] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class TextAreaField(StringField): ... +class PasswordField(StringField): ... +class FileField(Field): ... + +class MultipleFileField(FileField): + data: list[Any] + +class HiddenField(StringField): ... +class SubmitField(BooleanField): ... +class SearchField(StringField): ... +class TelField(StringField): ... +class URLField(StringField): ... +class EmailField(StringField): ... +class ColorField(StringField): ... diff --git a/stubs/WTForms/wtforms/form.pyi b/stubs/WTForms/wtforms/form.pyi new file mode 100644 index 000000000000..a8337d394696 --- /dev/null +++ b/stubs/WTForms/wtforms/form.pyi @@ -0,0 +1,87 @@ +from _typeshed import SupportsItems +from collections.abc import Iterable, Iterator, Mapping, Sequence +from typing import Any, ClassVar, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from wtforms.fields.core import Field, UnboundField +from wtforms.meta import DefaultMeta, _MultiDictLike + +_T = TypeVar("_T") +_FormErrors: TypeAlias = dict[str, Sequence[str] | _FormErrors] + +# _unbound_fields will always be a list on an instance, but on a +# class it might be None, if it never has been instantiated, or +# not instantianted after a new field had been added/removed +@type_check_only +class _UnboundFields(Protocol): + @overload + def __get__(self, obj: None, owner: type[object] | None = None, /) -> list[tuple[str, UnboundField[Any]]] | None: ... + @overload + def __get__(self, obj: object, owner: type[object] | None = None, /) -> list[tuple[str, UnboundField[Any]]]: ... + +class BaseForm: + meta: DefaultMeta + form_errors: list[str] + # we document this, because it's the only efficient way to introspect + # the field names of the form, it also seems to be stable API-wise + _fields: dict[str, Field] + def __init__( + self, + fields: SupportsItems[str, UnboundField[Any]] | Iterable[tuple[str, UnboundField[Any]]], + prefix: str = "", + meta: DefaultMeta = ..., + ) -> None: ... + def __iter__(self) -> Iterator[Field]: ... + def __contains__(self, name: str) -> bool: ... + def __getitem__(self, name: str) -> Field: ... + def __setitem__(self, name: str, value: UnboundField[Any]) -> None: ... + def __delitem__(self, name: str) -> None: ... + def populate_obj(self, obj: object) -> None: ... + # while we would like to be more strict on extra_filters, we can't easily do that + # without it being annoying in most situations + def process( + self, + formdata: _MultiDictLike | None = None, + obj: object | None = None, + data: Mapping[str, Any] | None = None, + extra_filters: Mapping[str, Sequence[Any]] | None = None, + **kwargs: object, + ) -> None: ... + # same thing here with extra_validators + def validate(self, extra_validators: Mapping[str, Sequence[Any]] | None = None) -> bool: ... + @property + def data(self) -> dict[str, Any]: ... + # because of the Liskov violation in FormField.errors we need to make errors a recursive type + @property + def errors(self) -> _FormErrors: ... + +class FormMeta(type): + def __init__(cls, name: str, bases: Sequence[type[object]], attrs: Mapping[str, Any]) -> None: ... + def __call__(cls: type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __setattr__(cls, name: str, value: object) -> None: ... + def __delattr__(cls, name: str) -> None: ... + +class Form(BaseForm, metaclass=FormMeta): + # due to the metaclass this should always be a subclass of DefaultMeta + # but if we annotate this as such, then subclasses cannot use it in the + # intended way + Meta: ClassVar[type[Any]] + # this attribute is documented, so we annotate it + _unbound_fields: _UnboundFields + def __init__( + self, + formdata: _MultiDictLike | None = None, + obj: object | None = None, + prefix: str = "", + data: Mapping[str, Any] | None = None, + meta: Mapping[str, Any] | None = None, + *, + # same issue as with process + extra_filters: Mapping[str, Sequence[Any]] | None = None, + **kwargs: object, + ) -> None: ... + # this should emit a type_error, since it's not allowed to be called + def __setitem__(self, name: str, value: None) -> None: ... # type: ignore[override] + def __delitem__(self, name: str) -> None: ... + def __delattr__(self, name: str) -> None: ... + +__all__ = ("BaseForm", "Form") diff --git a/stubs/WTForms/wtforms/i18n.pyi b/stubs/WTForms/wtforms/i18n.pyi new file mode 100644 index 000000000000..f8ac4b504556 --- /dev/null +++ b/stubs/WTForms/wtforms/i18n.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable, Iterable +from gettext import GNUTranslations +from typing import Protocol, TypeVar, overload, type_check_only + +_T = TypeVar("_T") + +@type_check_only +class _SupportsUgettextAndUngettext(Protocol): + def ugettext(self, string: str, /) -> str: ... + def ungettext(self, singular: str, plural: str, n: int, /) -> str: ... + +def messages_path() -> str: ... +def get_builtin_gnu_translations(languages: Iterable[str] | None = None) -> GNUTranslations: ... + +@overload +def get_translations( + languages: Iterable[str] | None = None, getter: Callable[[Iterable[str]], GNUTranslations] = ... +) -> GNUTranslations: ... +@overload +def get_translations(languages: Iterable[str] | None = None, *, getter: Callable[[Iterable[str]], _T]) -> _T: ... +@overload +def get_translations(languages: Iterable[str] | None, getter: Callable[[Iterable[str]], _T]) -> _T: ... + +class DefaultTranslations: + translations: _SupportsUgettextAndUngettext + def __init__(self, translations: _SupportsUgettextAndUngettext) -> None: ... + def gettext(self, string: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + +class DummyTranslations: + def gettext(self, string: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... diff --git a/stubs/WTForms/wtforms/meta.pyi b/stubs/WTForms/wtforms/meta.pyi new file mode 100644 index 000000000000..ee207e7e782d --- /dev/null +++ b/stubs/WTForms/wtforms/meta.pyi @@ -0,0 +1,60 @@ +from _typeshed import SupportsItems +from collections.abc import Collection, Iterator, MutableMapping +from typing import Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from markupsafe import Markup +from wtforms.fields.core import Field, UnboundField +from wtforms.form import BaseForm + +_FieldT = TypeVar("_FieldT", bound=Field) + +@type_check_only +class _SupportsGettextAndNgettext(Protocol): + def gettext(self, string: str, /) -> str: ... + def ngettext(self, singular: str, plural: str, n: int, /) -> str: ... + +# these are the methods WTForms depends on, the dict can either provide +# a getlist or getall, if it only provides getall, it will wrapped, to +# provide getlist instead +@type_check_only +class _MultiDictLikeBase(Protocol): + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: Any, /) -> bool: ... + +# since how file uploads are represented in formdata is implementation-specific +# we have to be generous in what we accept in the return of getlist/getall +# we can make this generic if we ever want to be more specific +@type_check_only +class _MultiDictLikeWithGetlist(_MultiDictLikeBase, Protocol): + def getlist(self, key: str, /) -> list[Any]: ... + +@type_check_only +class _MultiDictLikeWithGetall(_MultiDictLikeBase, Protocol): + def getall(self, key: str, /) -> list[Any]: ... + +_MultiDictLike: TypeAlias = _MultiDictLikeWithGetall | _MultiDictLikeWithGetlist + +class DefaultMeta: + def bind_field(self, form: BaseForm, unbound_field: UnboundField[_FieldT], options: MutableMapping[str, Any]) -> _FieldT: ... + + @overload + def wrap_formdata(self, form: BaseForm, formdata: None) -> None: ... + @overload + def wrap_formdata(self, form: BaseForm, formdata: _MultiDictLike) -> _MultiDictLikeWithGetlist: ... + + def render_field(self, field: Field, render_kw: SupportsItems[str, Any]) -> Markup: ... + csrf: bool + csrf_field_name: str + csrf_secret: Any | None + csrf_context: Any | None + csrf_class: type[Any] | None + def build_csrf(self, form: BaseForm) -> Any: ... + locales: Literal[False] | Collection[str] + cache_translations: bool + translations_cache: dict[str, _SupportsGettextAndNgettext] + def get_translations(self, form: BaseForm) -> _SupportsGettextAndNgettext: ... + def update_values(self, values: SupportsItems[str, Any]) -> None: ... + # since meta can be extended with arbitrary data we add a __getattr__ + # method that returns Any + def __getattr__(self, name: str) -> Any: ... diff --git a/stubs/WTForms/wtforms/utils.pyi b/stubs/WTForms/wtforms/utils.pyi new file mode 100644 index 000000000000..ded0e7bc7e6c --- /dev/null +++ b/stubs/WTForms/wtforms/utils.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable, Iterator +from typing import Any, Literal + +from wtforms.meta import _MultiDictLikeWithGetall + +def clean_datetime_format_for_strptime(formats: Iterable[str]) -> list[str]: ... + +class UnsetValue: + def __bool__(self) -> Literal[False]: ... + +unset_value: UnsetValue + +class WebobInputWrapper: + def __init__(self, multidict: _MultiDictLikeWithGetall) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, name: str) -> bool: ... + def getlist(self, name: str) -> list[Any]: ... diff --git a/stubs/WTForms/wtforms/validators.pyi b/stubs/WTForms/wtforms/validators.pyi new file mode 100644 index 000000000000..0389fcb38779 --- /dev/null +++ b/stubs/WTForms/wtforms/validators.pyi @@ -0,0 +1,214 @@ +from collections.abc import Callable, Collection, Iterable +from decimal import Decimal +from re import Match, Pattern +from typing import Any, TypeVar, overload + +from wtforms.fields import Field, StringField +from wtforms.form import BaseForm + +__all__ = ( + "DataRequired", + "data_required", + "Email", + "email", + "EqualTo", + "equal_to", + "IPAddress", + "ip_address", + "InputRequired", + "input_required", + "Length", + "length", + "NumberRange", + "number_range", + "Optional", + "optional", + "Regexp", + "regexp", + "URL", + "url", + "AnyOf", + "any_of", + "NoneOf", + "none_of", + "MacAddress", + "mac_address", + "UUID", + "ValidationError", + "StopValidation", + "readonly", + "ReadOnly", + "disabled", + "Disabled", +) + +_ValuesT_contra = TypeVar("_ValuesT_contra", bound=Collection[Any], contravariant=True) + +class ValidationError(ValueError): + def __init__(self, message: str = "", *args: object) -> None: ... + +class StopValidation(Exception): + def __init__(self, message: str = "", *args: object) -> None: ... + +class EqualTo: + fieldname: str + message: str | None + def __init__(self, fieldname: str, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Length: + min: int + max: int + message: str | None + field_flags: dict[str, Any] + def __init__(self, min: int = -1, max: int = -1, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + +class NumberRange: + min: float | Decimal | None + max: float | Decimal | None + message: str | None + field_flags: dict[str, Any] + def __init__( + self, min: float | Decimal | None = None, max: float | Decimal | None = None, message: str | None = None + ) -> None: ... + # any numeric field will work, for now we don't try to use a union + # to restrict to the defined numeric fields, since user-defined fields + # will likely not use a common base class, just like the existing + # numeric fields + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Optional: + string_check: Callable[[str], bool] + field_flags: dict[str, Any] + def __init__(self, strip_whitespace: bool = True) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class DataRequired: + message: str | None + field_flags: dict[str, Any] + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class InputRequired: + message: str | None + field_flags: dict[str, Any] + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Regexp: + regex: Pattern[str] + message: str | None + def __init__(self, regex: str | Pattern[str], flags: int = 0, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField, message: str | None = None) -> Match[str]: ... + +class Email: + message: str | None + granular_message: bool + check_deliverability: bool + allow_smtputf8: bool + allow_empty_local: bool + def __init__( + self, + message: str | None = None, + granular_message: bool = False, + check_deliverability: bool = False, + allow_smtputf8: bool = True, + allow_empty_local: bool = False, + ) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + +class IPAddress: + ipv4: bool + ipv6: bool + message: str | None + def __init__(self, ipv4: bool = True, ipv6: bool = False, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + @classmethod + def check_ipv4(cls, value: str | None) -> bool: ... + @classmethod + def check_ipv6(cls, value: str | None) -> bool: ... + +class MacAddress(Regexp): + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... # type: ignore[override] + +class URL(Regexp): + validate_hostname: HostnameValidation + def __init__(self, require_tld: bool = True, allow_ip: bool = True, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... # type: ignore[override] + +class UUID: + message: str | None + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + +class AnyOf: + values: Collection[Any] + message: str | None + values_formatter: Callable[[Any], str] + + @overload + def __init__(self, values: Collection[Any], message: str | None = None, values_formatter: None = None) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None = None, *, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + + def __call__(self, form: BaseForm, field: Field) -> None: ... + @staticmethod + def default_values_formatter(values: Iterable[object]) -> str: ... + +class NoneOf: + values: Collection[Any] + message: str | None + values_formatter: Callable[[Any], str] + + @overload + def __init__(self, values: Collection[Any], message: str | None = None, values_formatter: None = None) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None = None, *, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + + def __call__(self, form: BaseForm, field: Field) -> None: ... + @staticmethod + def default_values_formatter(v: Iterable[object]) -> str: ... + +class HostnameValidation: + hostname_part: Pattern[str] + tld_part: Pattern[str] + require_tld: bool + allow_ip: bool + def __init__(self, require_tld: bool = True, allow_ip: bool = False) -> None: ... + def __call__(self, hostname: str) -> bool: ... + +class ReadOnly: + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Disabled: + def __call__(self, form: BaseForm, field: Field) -> None: ... + +email = Email +equal_to = EqualTo +ip_address = IPAddress +mac_address = MacAddress +length = Length +number_range = NumberRange +optional = Optional +input_required = InputRequired +data_required = DataRequired +regexp = Regexp +url = URL +any_of = AnyOf +none_of = NoneOf +readonly = ReadOnly +disabled = Disabled diff --git a/stubs/WTForms/wtforms/widgets/__init__.pyi b/stubs/WTForms/wtforms/widgets/__init__.pyi new file mode 100644 index 000000000000..919a43b3e49a --- /dev/null +++ b/stubs/WTForms/wtforms/widgets/__init__.pyi @@ -0,0 +1,59 @@ +from wtforms.widgets.core import ( + CheckboxInput as CheckboxInput, + ColorInput as ColorInput, + DateInput as DateInput, + DateTimeInput as DateTimeInput, + DateTimeLocalInput as DateTimeLocalInput, + EmailInput as EmailInput, + FileInput as FileInput, + HiddenInput as HiddenInput, + Input as Input, + ListWidget as ListWidget, + MonthInput as MonthInput, + NumberInput as NumberInput, + Option as Option, + PasswordInput as PasswordInput, + RadioInput as RadioInput, + RangeInput as RangeInput, + SearchInput as SearchInput, + Select as Select, + SubmitInput as SubmitInput, + TableWidget as TableWidget, + TelInput as TelInput, + TextArea as TextArea, + TextInput as TextInput, + TimeInput as TimeInput, + URLInput as URLInput, + WeekInput as WeekInput, + html_params as html_params, +) + +__all__ = [ + "CheckboxInput", + "ColorInput", + "DateInput", + "DateTimeInput", + "DateTimeLocalInput", + "EmailInput", + "FileInput", + "HiddenInput", + "ListWidget", + "MonthInput", + "NumberInput", + "Option", + "PasswordInput", + "RadioInput", + "RangeInput", + "SearchInput", + "Select", + "SubmitInput", + "TableWidget", + "TextArea", + "TextInput", + "TelInput", + "TimeInput", + "URLInput", + "WeekInput", + "html_params", + "Input", +] diff --git a/stubs/WTForms/wtforms/widgets/core.pyi b/stubs/WTForms/wtforms/widgets/core.pyi new file mode 100644 index 000000000000..62861c43cb66 --- /dev/null +++ b/stubs/WTForms/wtforms/widgets/core.pyi @@ -0,0 +1,120 @@ +from decimal import Decimal +from typing import Any, Literal + +from markupsafe import Markup +from wtforms.fields import Field, FormField, StringField +from wtforms.fields.choices import SelectFieldBase, _Option + +__all__ = ( + "CheckboxInput", + "ColorInput", + "DateInput", + "DateTimeInput", + "DateTimeLocalInput", + "EmailInput", + "FileInput", + "HiddenInput", + "ListWidget", + "MonthInput", + "NumberInput", + "Option", + "PasswordInput", + "RadioInput", + "RangeInput", + "SearchInput", + "Select", + "SubmitInput", + "TableWidget", + "TextArea", + "TextInput", + "TelInput", + "TimeInput", + "URLInput", + "WeekInput", +) + +def html_params(**kwargs: object) -> str: ... + +class ListWidget: + html_tag: Literal["ul", "ol"] + prefix_label: bool + def __init__(self, html_tag: Literal["ul", "ol"] = "ul", prefix_label: bool = True) -> None: ... + # any iterable field is fine, since people might define iterable fields + # that are not derived from FieldList, we just punt and accept any field + # with Intersection we could be more specific + def __call__(self, field: Field, **kwargs: object) -> Markup: ... + +class TableWidget: + with_table_tag: bool + def __init__(self, with_table_tag: bool = True) -> None: ... + def __call__(self, field: FormField[Any], **kwargs: object) -> Markup: ... + +class Input: + validation_attrs: list[str] + input_type: str + def __init__(self, input_type: str | None = None) -> None: ... + def __call__(self, field: Field, **kwargs: object) -> Markup: ... + @staticmethod + def html_params(**kwargs: object) -> str: ... + +class TextInput(Input): ... + +class PasswordInput(Input): + hide_value: bool + def __init__(self, hide_value: bool = True) -> None: ... + +class HiddenInput(Input): + field_flags: dict[str, Any] + +class CheckboxInput(Input): ... +class RadioInput(Input): ... + +class FileInput(Input): + multiple: bool + def __init__(self, multiple: bool = False) -> None: ... + +class SubmitInput(Input): ... + +class TextArea: + validation_attrs: list[str] + def __call__(self, field: StringField, **kwargs: object) -> Markup: ... + +class Select: + validation_attrs: list[str] + multiple: bool + def __init__(self, multiple: bool = False) -> None: ... + def __call__(self, field: SelectFieldBase, **kwargs: object) -> Markup: ... + @classmethod + def render_option(cls, value: object, label: str, selected: bool, **kwargs: object) -> Markup: ... + +class Option: + def __call__(self, field: _Option, **kwargs: object) -> Markup: ... + +class SearchInput(Input): ... +class TelInput(Input): ... +class URLInput(Input): ... +class EmailInput(Input): ... +class DateTimeInput(Input): ... +class DateInput(Input): ... +class MonthInput(Input): ... +class WeekInput(Input): ... +class TimeInput(Input): ... +class DateTimeLocalInput(Input): ... + +class NumberInput(Input): + step: Decimal | float | str | None + min: Decimal | float | str | None + max: Decimal | float | str | None + def __init__( + self, + step: Decimal | float | str | None = None, + min: Decimal | float | str | None = None, + max: Decimal | float | str | None = None, + ) -> None: ... + +class RangeInput(Input): + # maybe we should allow any str for this + step: Decimal | float | str | None + def __init__(self, step: Decimal | float | str | None = None) -> None: ... + +class ColorInput(Input): ... diff --git a/stubs/WebOb/@tests/stubtest_allowlist.txt b/stubs/WebOb/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..4379483af587 --- /dev/null +++ b/stubs/WebOb/@tests/stubtest_allowlist.txt @@ -0,0 +1,166 @@ +# Error: is not present in stub +# ============================= +# These are plain strings, regex strings or compiled regex patterns +# which are used internally for parsing, so they should not be public API +webob.acceptparse.Accept.accept_compiled_re +webob.acceptparse.Accept.accept_ext_compiled_re +webob.acceptparse.Accept.accept_ext_re +webob.acceptparse.Accept.accept_params_re +webob.acceptparse.Accept.media_range_n_accept_params_compiled_re +webob.acceptparse.Accept.media_range_n_accept_params_re +webob.acceptparse.Accept.media_range_re +webob.acceptparse.Accept.media_type_compiled_re +webob.acceptparse.Accept.media_type_re +webob.acceptparse.Accept.obs_text_re +webob.acceptparse.Accept.parameter_re +webob.acceptparse.Accept.parameters_compiled_re +webob.acceptparse.Accept.qdtext_re +webob.acceptparse.Accept.quoted_pair_re +webob.acceptparse.Accept.quoted_string_re +webob.acceptparse.Accept.subtype_re +webob.acceptparse.Accept.type_re +webob.acceptparse.Accept.vchar_re +webob.acceptparse.AcceptCharset.accept_charset_compiled_re +webob.acceptparse.AcceptCharset.charset_n_weight_compiled_re +webob.acceptparse.AcceptCharset.charset_n_weight_re +webob.acceptparse.AcceptCharset.charset_re +webob.acceptparse.AcceptEncoding.accept_encoding_compiled_re +webob.acceptparse.AcceptEncoding.codings_n_weight_compiled_re +webob.acceptparse.AcceptEncoding.codings_n_weight_re +webob.acceptparse.AcceptEncoding.codings_re +webob.acceptparse.AcceptLanguage.accept_language_compiled_re +webob.acceptparse.AcceptLanguage.lang_range_n_weight_compiled_re +webob.acceptparse.AcceptLanguage.lang_range_n_weight_re +webob.acceptparse.AcceptLanguage.lang_range_re +webob.acceptparse.OWS_re +webob.acceptparse.qvalue_re +webob.acceptparse.tchar_re +webob.acceptparse.token_compiled_re +webob.acceptparse.token_re +webob.acceptparse.weight_re +webob.cachecontrol.need_quote_re +webob.cachecontrol.token_re +webob.client.SendRequest.MULTILINE_RE +webob.descriptors.CHARSET_RE +webob.descriptors.SCHEME_RE + +webob.acceptparse.MIMEAccept # Deprecated API + +# PY2 compat stuff that has already been removed upstream +webob.compat.PY2 +webob.compat.PY3 +webob.compat.bytes_ +webob.compat.class_types +webob.compat.integer_types +webob.compat.iteritems_ +webob.compat.itervalues_ +webob.compat.long +webob.compat.native_ +webob.compat.parse_qsl_text +webob.compat.reraise +webob.compat.string_types +webob.compat.text_ +webob.compat.text_type +webob.compat.unquote +webob.multidict.MultiDict.iteritems +webob.multidict.MultiDict.iterkeys +webob.multidict.MultiDict.itervalues +webob.multidict.NestedMultiDict.iteritems +webob.multidict.NestedMultiDict.iterkeys +webob.multidict.NestedMultiDict.itervalues +webob.multidict.NoVars.iterkeys + +# The implementation details of cgi_FieldStorage shouldn't matter +webob.compat.cgi_FieldStorage.read_multi + +# NoVars implements the MultiDict interface for better runtime errors +# but it is annoying for type checking, so the methods that are not +# valid to call on NoVars have been removed. In the future we would +# like to switch to a @type_error() decorator +webob.multidict.NoVars.__getitem__ +webob.multidict.NoVars.__setitem__ +webob.multidict.NoVars.__delitem__ +webob.multidict.NoVars.add +webob.multidict.NoVars.setdefault +webob.multidict.NoVars.update +webob.multidict.NoVars.clear +webob.multidict.NoVars.pop +webob.multidict.NoVars.popitem +webob.multidict.NoVars.getone + +# ResponseBodyFile cannot be closed and emits an Exception, so we're better +# off pretending the method doesn't exist +webob.response.ResponseBodyFile.close + +# Error: is inconsistent +# ====================== +# set_cookie has a deprecated argument `expires` which has been removed upstream +webob.response.Response.set_cookie + +# These are here due to the slightly more strict nature of the type annotation +# of these descriptors for type checking, it does not really have any runtime +# consequences since `_IntValueProperty` derives from `value_property` and +# only makes `__set__` slightly more strict. +webob.cachecontrol.UpdateDict.setdefault + +# Even though at runtime the default argument has a default value of `None` +# that will cause an exception, so we're better off pretending the argument +# is required, and that it can't be `None` +webob.headers.ResponseHeaders.setdefault +webob.multidict.GetDict.setdefault + +# These need to be ignored due to how WebOb decided to let people know +# that certain methods on `NestedMultiDict` should not be called since +# they are immutable, compared to a MultiDict, but still can be used +# interchangeably in some parts of the API. So they reuse generic functions +# that accept any parameters and assign them to methods which should still +# satisfy the same interface. The type annotations enforce the correct +# input arguments instead of the generic ones. +webob.multidict.NestedMultiDict.__delitem__ +webob.multidict.NestedMultiDict.__setitem__ +webob.multidict.NestedMultiDict.add +webob.multidict.NestedMultiDict.clear +webob.multidict.NestedMultiDict.pop +webob.multidict.NestedMultiDict.popitem +webob.multidict.NestedMultiDict.setdefault +webob.multidict.NestedMultiDict.update + +# The `DEFAULT` parameter on these dunder methods don't really make sense as +# part of the public API, so they have been removed from the stubs +webob.request.AdhocAttrMixin.__delattr__ +webob.request.AdhocAttrMixin.__getattr__ +webob.request.AdhocAttrMixin.__setattr__ + +# BaseRequest has a bunch of named parameters that have been deprecated and +# removed upstream, since there's a `**kwargs` anyways, it doesn't really +# make sense to annotate them and pretend they're part of the API. +webob.request.BaseRequest.__init__ + +# We needed to add a dummy *_: _P.args in order to support ParamSpec +webob.dec.wsgify.middleware +webob.dec._MiddlewareFactory.__call__ + +# We renamed some of the arguments in positional only overloads for greater +# clarity about what the arguments mean, stubtest should probably be a bit +# more lenient here, since this is only unsafe if that overload accepts +# arbitrary named arguments, that could overlap with the argument in that +# specific position +webob.dec.wsgify.__call__ + +# Error: is not present at runtime +# ============================= +# This attribute is there to help mypy type narrow NoVars based on its static +# falsyness, so it's to make it possible to narrow the type union in request.POST +# without importing MultiDict or NoVars +webob.multidict.NoVars.__bool__ + +# This attribute is set on the instance instead of the class in the `__init__` +# so the type annotation is technically wrong, however I am unsure about +# whether the ResponseBodyFile would satisfy some of the IO Protocols if +# `write` was defined as a Callable instance attribute. It's hard to come up +# with a use-case where the distinction matters, besides inheriting from +# the class and overwriting the __init__ and forgetting to populate `write`. +webob.response.ResponseBodyFile.write + +# A couple of utility types we use in multiple modules +webob._types diff --git a/stubs/WebOb/@tests/test_cases/check_cachecontrol.py b/stubs/WebOb/@tests/test_cases/check_cachecontrol.py new file mode 100644 index 000000000000..d011b01c9586 --- /dev/null +++ b/stubs/WebOb/@tests/test_cases/check_cachecontrol.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import Any, Literal +from typing_extensions import assert_type + +from webob.cachecontrol import CacheControl +from webob.request import BaseRequest +from webob.response import Response + +req = BaseRequest({}) +res = Response() +assert_type(req.cache_control, CacheControl[Literal["request"]]) +assert_type(res.cache_control, CacheControl[Literal["response"]]) + +assert_type(CacheControl.parse(""), CacheControl[None]) +assert_type(CacheControl.parse("", type="request"), CacheControl[Literal["request"]]) +assert_type(CacheControl.parse("", type="response"), CacheControl[Literal["response"]]) + +req_cc = req.cache_control +res_cc = res.cache_control +shared_cc = CacheControl.parse("") +assert_type(req_cc, CacheControl[Literal["request"]]) +assert_type(res_cc, CacheControl[Literal["response"]]) +assert_type(shared_cc, CacheControl[None]) +any_cc = CacheControl[Any]({}, None) + +assert_type(req_cc.max_stale, int | Literal["*"] | None) +res_cc.max_stale # type: ignore +shared_cc.max_stale # type: ignore +assert_type(any_cc.max_stale, int | Literal["*"] | None) + +assert_type(req_cc.min_fresh, int | None) +res_cc.min_fresh # type: ignore +shared_cc.min_fresh # type: ignore +assert_type(any_cc.min_fresh, int | None) + +assert_type(req_cc.only_if_cached, bool) +res_cc.only_if_cached # type: ignore +shared_cc.only_if_cached # type: ignore +assert_type(any_cc.only_if_cached, bool) + +req_cc.public # type: ignore +assert_type(res_cc.public, bool) +shared_cc.public # type: ignore +assert_type(any_cc.public, bool) + +# NOTE: pyright gets confused about the `Literal["*"]` the types match +req_cc.private # type: ignore +assert_type(res_cc.private, str | Literal["*"] | None) # pyright: ignore +shared_cc.private # type: ignore +assert_type(any_cc.private, str | Literal["*"] | None) # pyright: ignore + +assert_type(req_cc.no_cache, str | Literal["*"] | None) # pyright: ignore +assert_type(res_cc.no_cache, str | Literal["*"] | None) # pyright: ignore +assert_type(shared_cc.no_cache, str | Literal["*"] | None) # pyright: ignore +assert_type(any_cc.no_cache, str | Literal["*"] | None) # pyright: ignore + +assert_type(req_cc.no_store, bool) +assert_type(res_cc.no_store, bool) +assert_type(shared_cc.no_store, bool) +assert_type(any_cc.no_store, bool) + +assert_type(req_cc.no_transform, bool) +assert_type(res_cc.no_transform, bool) +assert_type(shared_cc.no_transform, bool) +assert_type(any_cc.no_transform, bool) + +req_cc.must_revalidate # type: ignore +assert_type(res_cc.must_revalidate, bool) +shared_cc.must_revalidate # type: ignore +assert_type(any_cc.must_revalidate, bool) + +req_cc.proxy_revalidate # type: ignore +assert_type(res_cc.proxy_revalidate, bool) +shared_cc.proxy_revalidate # type: ignore +assert_type(any_cc.proxy_revalidate, bool) + +# NOTE: pyright gets confused about the `Literal[-1]` the types match +assert_type(req_cc.max_age, int | Literal[-1] | None) # pyright: ignore +assert_type(res_cc.max_age, int | Literal[-1] | None) # pyright: ignore +assert_type(shared_cc.max_age, int | Literal[-1] | None) # pyright: ignore +assert_type(any_cc.max_age, int | Literal[-1] | None) # pyright: ignore + +req_cc.s_maxage # type: ignore +assert_type(res_cc.s_maxage, int | None) +shared_cc.s_maxage # type: ignore +assert_type(any_cc.s_maxage, int | None) + +req_cc.s_max_age # type: ignore +assert_type(res_cc.s_max_age, int | None) +shared_cc.s_max_age # type: ignore +assert_type(any_cc.s_max_age, int | None) + +req_cc.stale_while_revalidate # type: ignore +assert_type(res_cc.stale_while_revalidate, int | None) +shared_cc.stale_while_revalidate # type: ignore +assert_type(any_cc.stale_while_revalidate, int | None) + +req_cc.stale_if_error # type: ignore +assert_type(res_cc.stale_if_error, int | None) +shared_cc.stale_if_error # type: ignore +assert_type(any_cc.stale_if_error, int | None) diff --git a/stubs/WebOb/@tests/test_cases/check_wsgify.py b/stubs/WebOb/@tests/test_cases/check_wsgify.py new file mode 100644 index 000000000000..93de11429778 --- /dev/null +++ b/stubs/WebOb/@tests/test_cases/check_wsgify.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from typing_extensions import assert_type + +from webob.dec import _AnyResponse, wsgify +from webob.request import Request + + +class App: + @wsgify + def __call__(self, request: Request) -> str: + return "hello" + + +env: WSGIEnvironment = {} +start_response: StartResponse = lambda x, y, z=None: lambda b: None +application: WSGIApplication = lambda e, s: [b""] +request: Request = Request(env) + +x = App() +# since we wsgified our __call__ we should now be a valid WSGIApplication +application = x +assert_type(x(env, start_response), "Iterable[bytes]") +# currently we lose the exact response type, but that should be fine in +# most use-cases, since middlewares operate on an application level, not +# on these raw intermediary functions +assert_type(x(request), _AnyResponse) + +# accessing the method from the class should work as you expect it to +assert_type(App.__call__(x, env, start_response), "Iterable[bytes]") +assert_type(App.__call__(x, request), _AnyResponse) + + +# but we can also wrap it with a middleware that expects to deal with requests +class Middleware: + @wsgify.middleware + def restrict_ip(self, req: Request, app: WSGIApplication, ips: list[str]) -> WSGIApplication: + return app + + __call__ = restrict_ip(x, ips=["127.0.0.1"]) + + +# and we still end up with a valid WSGIApplication +m = Middleware() +application = m +assert_type(m(env, start_response), "Iterable[bytes]") +assert_type(m(request), _AnyResponse) + + +# the same should work with plain functions +@wsgify +def app(request: Request) -> str: + return "hello" + + +application = app +assert_type(app, "wsgify[[], Request]") +assert_type(app(env, start_response), "Iterable[bytes]") +assert_type(app(request), _AnyResponse) +assert_type(app(application), "wsgify[[], Request]") +application = app(application) + + +@wsgify.middleware +def restrict_ip(req: Request, app: WSGIApplication, ips: list[str]) -> WSGIApplication: + return app + + +@restrict_ip(ips=["127.0.0.1"]) +@wsgify +def m_app(request: Request) -> str: + return "hello" + + +application = m_app +assert_type(m_app, "wsgify[[WSGIApplication], Request]") +assert_type(m_app(env, start_response), "Iterable[bytes]") +assert_type(m_app(request), _AnyResponse) +assert_type(m_app(application), "wsgify[[WSGIApplication], Request]") +application = m_app(application) + + +# custom request +class MyRequest(Request): + pass + + +@wsgify(RequestClass=MyRequest) +def my_request_app(request: MyRequest) -> None: + pass + + +application = my_request_app +assert_type(my_request_app, "wsgify[[], MyRequest]") + + +# we are allowed to accept a less specific request class +@wsgify(RequestClass=MyRequest) +def valid_request_app(request: Request) -> None: + pass + + +# but the opposite is not allowed +@wsgify # type: ignore +def invalid_request_app(request: MyRequest) -> None: + pass + + +# we can't really make passing extra arguments directly work +# otherwise we have to give up most of our type safety for +# something that should only be used through wsgify.middleware +wsgify(args=(1,)) # type: ignore +wsgify(kwargs={"ips": ["127.0.0.1"]}) # type: ignore diff --git a/stubs/WebOb/METADATA.toml b/stubs/WebOb/METADATA.toml new file mode 100644 index 000000000000..eae85173da12 --- /dev/null +++ b/stubs/WebOb/METADATA.toml @@ -0,0 +1,2 @@ +version = "~=1.8.11" +upstream-repository = "https://github.com/Pylons/webob" diff --git a/stubs/WebOb/webob/__init__.pyi b/stubs/WebOb/webob/__init__.pyi new file mode 100644 index 000000000000..b190ee568d5a --- /dev/null +++ b/stubs/WebOb/webob/__init__.pyi @@ -0,0 +1,28 @@ +from webob.datetime_utils import ( + UTC as UTC, + day as day, + hour as hour, + minute as minute, + month as month, + second as second, + week as week, + year as year, +) +from webob.request import LegacyRequest as LegacyRequest, Request as Request +from webob.response import Response as Response +from webob.util import html_escape as html_escape + +__all__ = [ + "Request", + "LegacyRequest", + "Response", + "UTC", + "day", + "week", + "hour", + "minute", + "second", + "month", + "year", + "html_escape", +] diff --git a/stubs/WebOb/webob/_types.pyi b/stubs/WebOb/webob/_types.pyi new file mode 100644 index 000000000000..11c28a5efb9a --- /dev/null +++ b/stubs/WebOb/webob/_types.pyi @@ -0,0 +1,23 @@ +from typing import Protocol, TypeAlias, TypeVar, overload, type_check_only + +_T = TypeVar("_T") +_GetterReturnType_co = TypeVar("_GetterReturnType_co", covariant=True) +_SetterValueType_contra = TypeVar("_SetterValueType_contra", contravariant=True) + +@type_check_only +class AsymmetricProperty(Protocol[_GetterReturnType_co, _SetterValueType_contra]): + @overload + def __get__(self, obj: None, type: type[object] | None = ..., /) -> property: ... + @overload + def __get__(self, obj: object, type: type[object] | None = ..., /) -> _GetterReturnType_co: ... + + def __set__(self, obj: object, value: _SetterValueType_contra, /) -> None: ... + +@type_check_only +class AsymmetricPropertyWithDelete( + AsymmetricProperty[_GetterReturnType_co, _SetterValueType_contra], Protocol[_GetterReturnType_co, _SetterValueType_contra] +): + def __delete__(self, obj: object, /) -> None: ... + +SymmetricProperty: TypeAlias = AsymmetricProperty[_T, _T] +SymmetricPropertyWithDelete: TypeAlias = AsymmetricPropertyWithDelete[_T, _T] diff --git a/stubs/WebOb/webob/acceptparse.pyi b/stubs/WebOb/webob/acceptparse.pyi new file mode 100644 index 000000000000..77917501bc6d --- /dev/null +++ b/stubs/WebOb/webob/acceptparse.pyi @@ -0,0 +1,757 @@ +from _typeshed import SupportsItems +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, Literal, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob._types import AsymmetricPropertyWithDelete + +_T = TypeVar("_T") +_ListOrTuple: TypeAlias = list[_T] | tuple[_T, ...] +_ParsedAccept: TypeAlias = tuple[str, float, list[tuple[str, str]], list[str | tuple[str, str]]] + +@type_check_only +class _SupportsStr(Protocol): + def __str__(self) -> str: ... # noqa: Y029 + +_AnyAcceptHeader: TypeAlias = AcceptValidHeader | AcceptInvalidHeader | AcceptNoHeader +_AnyAcceptCharsetHeader: TypeAlias = AcceptCharsetValidHeader | AcceptCharsetInvalidHeader | AcceptCharsetNoHeader +_AnyAcceptEncodingHeader: TypeAlias = AcceptEncodingValidHeader | AcceptEncodingInvalidHeader | AcceptEncodingNoHeader +_AnyAcceptLanguageHeader: TypeAlias = AcceptLanguageValidHeader | AcceptLanguageInvalidHeader | AcceptLanguageNoHeader + +_AcceptProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptHeader, + ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), +] +_AcceptCharsetProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptCharsetHeader, + ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), +] +_AcceptEncodingProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptEncodingHeader, + ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), +] +_AcceptLanguageProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptLanguageHeader, + ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), +] + +@type_check_only +class _AcceptOffer(NamedTuple): + type: str + subtype: str + params: tuple[tuple[str, str], ...] + +class AcceptOffer(_AcceptOffer): + __slots__ = () + +class Accept: + @classmethod + def parse(cls, value: str) -> Iterator[_ParsedAccept]: ... + @classmethod + def parse_offer(cls, offer: str | AcceptOffer) -> AcceptOffer: ... + +class AcceptValidHeader(Accept): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[_ParsedAccept]: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + def __add__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def accept_html(self) -> bool: ... + @property + def accepts_html(self) -> bool: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptInvalidOrNoHeader(Accept): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def accept_html(self) -> bool: ... + @property + def accepts_html(self) -> bool: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float: ... + +class AcceptNoHeader(_AcceptInvalidOrNoHeader): + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + def __init__(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __add__(self, other: AcceptNoHeader | AcceptInvalidHeader | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptValidHeader: ... + + @overload + def __radd__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __radd__(self, other: AcceptNoHeader | AcceptInvalidHeader | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptValidHeader: ... + +class AcceptInvalidHeader(_AcceptInvalidOrNoHeader): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __add__(self, other: AcceptInvalidHeader | AcceptNoHeader | None) -> AcceptNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptValidHeader | AcceptNoHeader: ... + + @overload + def __radd__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __radd__(self, other: AcceptInvalidHeader | AcceptNoHeader | None) -> AcceptNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptValidHeader | AcceptNoHeader: ... + +@overload +def create_accept_header(header_value: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... +@overload +def create_accept_header(header_value: AcceptInvalidHeader) -> AcceptInvalidHeader: ... +@overload +def create_accept_header(header_value: AcceptNoHeader | None) -> AcceptNoHeader: ... +@overload +def create_accept_header(header_value: str) -> AcceptValidHeader | AcceptInvalidHeader: ... +@overload +def create_accept_header(header_value: _AnyAcceptHeader | str | None) -> _AnyAcceptHeader: ... + +def accept_property() -> _AcceptProperty: ... + +class AcceptCharset: + @classmethod + def parse(cls, value: str) -> Iterator[tuple[str, float]]: ... + +class AcceptCharsetValidHeader(AcceptCharset): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[tuple[str, float]]: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + def __add__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptCharsetInvalidOrNoHeader(AcceptCharset): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def acceptable_offers(self, offers: Iterable[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class AcceptCharsetNoHeader(_AcceptCharsetInvalidOrNoHeader): + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + def __init__(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __add__(self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptCharsetValidHeader: ... + + @overload + def __radd__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __radd__(self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptCharsetValidHeader: ... + +class AcceptCharsetInvalidHeader(_AcceptCharsetInvalidOrNoHeader): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __add__( + self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None + ) -> AcceptCharsetNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptCharsetValidHeader | AcceptCharsetNoHeader: ... + + @overload + def __radd__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __radd__( + self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None + ) -> AcceptCharsetNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptCharsetValidHeader | AcceptCharsetNoHeader: ... + +@overload +def create_accept_charset_header(header_value: AcceptCharsetValidHeader | Literal[""]) -> AcceptCharsetValidHeader: ... +@overload +def create_accept_charset_header(header_value: AcceptCharsetInvalidHeader) -> AcceptCharsetInvalidHeader: ... +@overload +def create_accept_charset_header(header_value: AcceptCharsetNoHeader | None) -> AcceptCharsetNoHeader: ... +@overload +def create_accept_charset_header(header_value: str) -> AcceptCharsetValidHeader | AcceptCharsetInvalidHeader: ... +@overload +def create_accept_charset_header(header_value: _AnyAcceptCharsetHeader | str | None) -> _AnyAcceptCharsetHeader: ... + +def accept_charset_property() -> _AcceptCharsetProperty: ... + +class AcceptEncoding: + @classmethod + def parse(cls, value: str) -> Iterator[tuple[str, float]]: ... + +class AcceptEncodingValidHeader(AcceptEncoding): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[tuple[str, float]]: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + def __add__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptEncodingInvalidOrNoHeader(AcceptEncoding): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def acceptable_offers(self, offers: Iterable[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class AcceptEncodingNoHeader(_AcceptEncodingInvalidOrNoHeader): + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + def __init__(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __add__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptEncodingValidHeader: ... + + @overload + def __radd__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __radd__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptEncodingValidHeader: ... + +class AcceptEncodingInvalidHeader(_AcceptEncodingInvalidOrNoHeader): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __add__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> AcceptEncodingNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptEncodingValidHeader | AcceptEncodingNoHeader: ... + + @overload + def __radd__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __radd__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> AcceptEncodingNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptEncodingValidHeader | AcceptEncodingNoHeader: ... + +@overload +def create_accept_encoding_header(header_value: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... +@overload +def create_accept_encoding_header(header_value: AcceptEncodingInvalidHeader) -> AcceptEncodingInvalidHeader: ... +@overload +def create_accept_encoding_header(header_value: AcceptEncodingNoHeader | None) -> AcceptEncodingNoHeader: ... +@overload +def create_accept_encoding_header(header_value: str) -> AcceptEncodingValidHeader | AcceptEncodingInvalidHeader: ... +@overload +def create_accept_encoding_header(header_value: _AnyAcceptEncodingHeader | str | None) -> _AnyAcceptEncodingHeader: ... + +def accept_encoding_property() -> _AcceptEncodingProperty: ... + +class AcceptLanguage: + @classmethod + def parse(cls, value: str) -> Iterator[tuple[str, float]]: ... + +class AcceptLanguageValidHeader(AcceptLanguage): + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[tuple[str, float]]: ... + def __add__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def basic_filtering(self, language_tags: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + @overload + def lookup( + self, language_tags: Sequence[str], default_range: str | None, default_tag: str, default: None = None + ) -> str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], *, default_range: str | None = None, default_tag: str, default: None = None + ) -> str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], default_range: str | None, default_tag: None, default: _T | Callable[[], _T] + ) -> _T | str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], default_range: str | None, default_tag: str, default: _T | Callable[[], _T] + ) -> _T | str: ... + @overload + def lookup( + self, + language_tags: Sequence[str], + *, + default_range: str | None = None, + default_tag: None = None, + default: _T | Callable[[], _T], + ) -> _T | str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], *, default_range: str | None = None, default_tag: str, default: _T | Callable[[], _T] + ) -> _T | str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptLanguageInvalidOrNoHeader(AcceptLanguage): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def basic_filtering(self, language_tags: Iterable[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + @overload + def lookup(self, language_tags: object, default_range: object, default_tag: str, default: object = None) -> str: ... + @overload + def lookup( + self, language_tags: object = None, *, default_range: object = None, default_tag: str, default: object = None + ) -> str: ... + @overload + def lookup(self, language_tags: object, default_range: object, default_tag: None, default: _T | Callable[[], _T]) -> _T: ... + @overload + def lookup( + self, + language_tags: object = None, + *, + default_range: object = None, + default_tag: None = None, + default: _T | Callable[[], _T], + ) -> _T: ... + + def quality(self, offer: str) -> float | None: ... + +class AcceptLanguageNoHeader(_AcceptLanguageInvalidOrNoHeader): + def __init__(self) -> None: ... + def copy(self) -> Self: ... + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + + @overload + def __add__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __add__(self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptLanguageValidHeader: ... + + @overload + def __radd__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __radd__(self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptLanguageValidHeader: ... + +class AcceptLanguageInvalidHeader(_AcceptLanguageInvalidOrNoHeader): + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + + @overload + def __add__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __add__( + self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None + ) -> AcceptLanguageNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptLanguageValidHeader | AcceptLanguageNoHeader: ... + + @overload + def __radd__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __radd__( + self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None + ) -> AcceptLanguageNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptLanguageValidHeader | AcceptLanguageNoHeader: ... + +@overload +def create_accept_language_header(header_value: AcceptLanguageValidHeader | Literal[""]) -> AcceptLanguageValidHeader: ... +@overload +def create_accept_language_header(header_value: AcceptLanguageNoHeader | None) -> AcceptLanguageNoHeader: ... +@overload +def create_accept_language_header(header_value: AcceptLanguageInvalidHeader) -> AcceptLanguageInvalidHeader: ... +@overload +def create_accept_language_header(header_value: str) -> AcceptLanguageValidHeader | AcceptLanguageInvalidHeader: ... +@overload +def create_accept_language_header(header_value: _AnyAcceptLanguageHeader | str | None) -> _AnyAcceptLanguageHeader: ... + +def accept_language_property() -> _AcceptLanguageProperty: ... diff --git a/stubs/WebOb/webob/byterange.pyi b/stubs/WebOb/webob/byterange.pyi new file mode 100644 index 000000000000..6ce07a14c4ae --- /dev/null +++ b/stubs/WebOb/webob/byterange.pyi @@ -0,0 +1,34 @@ +from collections.abc import Iterator +from typing import overload +from typing_extensions import Self + +__all__ = ["Range", "ContentRange"] + +class Range: + start: int | None + end: int | None + + @overload + def __init__(self, start: None, end: None) -> None: ... + @overload + def __init__(self, start: int, end: int | None) -> None: ... + + def range_for_length(self, length: int | None) -> tuple[int, int] | None: ... + def content_range(self, length: int | None) -> ContentRange | None: ... + def __iter__(self) -> Iterator[int | None]: ... + @classmethod + def parse(cls, header: str | None) -> Self | None: ... + +class ContentRange: + start: int | None + stop: int | None + length: int | None + + @overload + def __init__(self, start: None, stop: None, length: int | None) -> None: ... + @overload + def __init__(self, start: int, stop: int, length: int | None) -> None: ... + + def __iter__(self) -> Iterator[int | None]: ... + @classmethod + def parse(cls, value: str | None) -> Self | None: ... diff --git a/stubs/WebOb/webob/cachecontrol.pyi b/stubs/WebOb/webob/cachecontrol.pyi new file mode 100644 index 000000000000..d86d481d1b6f --- /dev/null +++ b/stubs/WebOb/webob/cachecontrol.pyi @@ -0,0 +1,108 @@ +import builtins +from _typeshed import SupportsItems +from collections.abc import Callable +from typing import Any, Generic, Literal, overload +from typing_extensions import Self, TypeVar + +_T = TypeVar("_T") +_DefaultT = TypeVar("_DefaultT", default=None) +_NoneLiteral = TypeVar("_NoneLiteral", default=None) +_ScopeT = TypeVar("_ScopeT", Literal["request"], Literal["response"], None, default=None) +_ScopeT2 = TypeVar("_ScopeT2", Literal["request"], Literal["response"], None) + +class UpdateDict(dict[str, Any]): + updated: Callable[..., Any] | None + updated_args: tuple[Any, ...] | None + +class exists_property(Generic[_ScopeT]): + @overload + def __init__(self: exists_property[None], prop: str) -> None: ... + @overload + def __init__(self, prop: str, type: _ScopeT) -> None: ... + + @overload + def __get__(self, obj: None, type: type[CacheControl[Any]] | None = None) -> Self: ... + @overload + def __get__(self: exists_property[None], obj: CacheControl[Any], type: type[CacheControl[Any]] | None = None) -> bool: ... + @overload + def __get__(self, obj: CacheControl[_ScopeT], type: type[CacheControl[Any]] | None = None) -> bool: ... + + @overload + def __set__(self: exists_property[None], obj: CacheControl[Any], value: bool | None) -> None: ... + @overload + def __set__(self, obj: CacheControl[_ScopeT], value: bool | None) -> None: ... + + @overload + def __delete__(self, obj: CacheControl[Any]) -> None: ... + @overload + def __delete__(self, obj: CacheControl[_ScopeT]) -> None: ... + +class value_property(Generic[_T, _DefaultT, _NoneLiteral, _ScopeT]): + def __init__(self, prop: str, default: _DefaultT = None, none: _NoneLiteral = None, type: _ScopeT = None) -> None: ... # type: ignore[assignment] # ty:ignore[invalid-parameter-default] + + @overload + def __get__(self, obj: None, type: type[CacheControl[Any]] | None = None) -> Self: ... + @overload + def __get__( + self: value_property[_T, _DefaultT, _NoneLiteral, None], + obj: CacheControl[Any] | None, + type: type[CacheControl[Any]] | None = None, + ) -> _T | _DefaultT | _NoneLiteral: ... + @overload + def __get__( + self, obj: CacheControl[_ScopeT] | None, type: type[CacheControl[Any]] | None = None + ) -> _T | _DefaultT | _NoneLiteral: ... + + @overload + def __set__( + self: value_property[_T, _DefaultT, _NoneLiteral, None], + obj: CacheControl[Any], + value: _T | _DefaultT | Literal[True] | None, + ) -> None: ... + @overload + def __set__(self, obj: CacheControl[_ScopeT], value: _T | _DefaultT | Literal[True] | None) -> None: ... + + @overload + def __delete__(self, obj: CacheControl[Any]) -> None: ... + @overload + def __delete__(self, obj: CacheControl[_ScopeT]) -> None: ... + +class CacheControl(Generic[_ScopeT]): + header_value: str + update_dict: builtins.type[UpdateDict] + properties: dict[str, Any] + type: _ScopeT + def __init__(self, properties: dict[str, Any], type: _ScopeT) -> None: ... + + @overload + @classmethod + def parse( + cls, header: str, updates_to: Callable[[dict[str, Any]], Any] | None = None, type: None = None + ) -> CacheControl[None]: ... + @overload + @classmethod + def parse(cls, header: str, updates_to: Callable[[dict[str, Any]], Any] | None, type: _ScopeT2) -> CacheControl[_ScopeT2]: ... + @overload + @classmethod + def parse( + cls, header: str, updates_to: Callable[[dict[str, Any]], Any] | None = None, *, type: _ScopeT2 + ) -> CacheControl[_ScopeT2]: ... + + max_stale: value_property[int, None, Literal["*"], Literal["request"]] + min_fresh: value_property[int, None, None, Literal["request"]] + only_if_cached: exists_property[Literal["request"]] + public: exists_property[Literal["response"]] + private: value_property[str, None, Literal["*"], Literal["response"]] + no_cache: value_property[str, None, Literal["*"], None] + no_store: exists_property[None] + no_transform: exists_property[None] + must_revalidate: exists_property[Literal["response"]] + proxy_revalidate: exists_property[Literal["response"]] + max_age: value_property[int, None, Literal[-1], None] + s_maxage: value_property[int, None, None, Literal["response"]] + s_max_age = s_maxage # pyrefly: ignore [unknown-name] + stale_while_revalidate: value_property[int, None, None, Literal["response"]] + stale_if_error: value_property[int, None, None, Literal["response"]] + def copy(self) -> Self: ... + +def serialize_cache_control(properties: SupportsItems[str, Any] | CacheControl[Any]) -> str: ... diff --git a/stubs/WebOb/webob/client.pyi b/stubs/WebOb/webob/client.pyi new file mode 100644 index 000000000000..cdabe6fd5379 --- /dev/null +++ b/stubs/WebOb/webob/client.pyi @@ -0,0 +1,14 @@ +from _typeshed.wsgi import StartResponse, WSGIEnvironment +from collections.abc import Iterable +from http.client import HTTPConnection, HTTPMessage, HTTPSConnection +from typing import ClassVar + +__all__ = ["send_request_app", "SendRequest"] + +class SendRequest: + def __init__(self, HTTPConnection: type[HTTPConnection] = ..., HTTPSConnection: type[HTTPSConnection] = ...) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + filtered_headers: ClassVar[tuple[str, ...]] + def parse_headers(self, message: HTTPMessage) -> list[tuple[str, str]]: ... + +send_request_app: SendRequest diff --git a/stubs/WebOb/webob/compat.pyi b/stubs/WebOb/webob/compat.pyi new file mode 100644 index 000000000000..66e384c55329 --- /dev/null +++ b/stubs/WebOb/webob/compat.pyi @@ -0,0 +1,24 @@ +import sys +from html import escape as escape +from io import FileIO, TextIOWrapper +from queue import Empty as Empty, Queue as Queue +from typing import IO + +if sys.version_info >= (3, 13): + # NOTE: These are the only attributes we realistically care about + class cgi_FieldStorage: + filename: str + file: IO[bytes] + def make_file(self) -> TextIOWrapper | FileIO: ... + + def parse_header(line: str) -> tuple[str, dict[str, str]]: ... + +else: + from cgi import FieldStorage as _cgi_FieldStorage, parse_header as parse_header + + class cgi_FieldStorage(_cgi_FieldStorage): + # NOTE: The only kinds of objects of this type the user is exposed to + # will contain a file with a filename. We're technically lying + # if people create their own instances, but that shouldn't happen + filename: str + file: IO[bytes] diff --git a/stubs/WebOb/webob/cookies.pyi b/stubs/WebOb/webob/cookies.pyi new file mode 100644 index 000000000000..3bda178fc43f --- /dev/null +++ b/stubs/WebOb/webob/cookies.pyi @@ -0,0 +1,196 @@ +from _typeshed import sentinel +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Collection, ItemsView, Iterator, KeysView, MutableMapping, ValuesView +from datetime import date, datetime, timedelta +from time import _TimeTuple, struct_time +from typing import Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from webob._types import AsymmetricProperty +from webob.request import BaseRequest +from webob.response import Response + +__all__ = [ + "Cookie", + "CookieProfile", + "SignedCookieProfile", + "SignedSerializer", + "JSONSerializer", + "Base64Serializer", + "make_cookie", +] + +_T = TypeVar("_T") +# we accept both the official spelling and the one used in the WebOb docs +# the implementation compares after lower() so technically there are more +# valid spellings, but it seems more natural to support these two spellings +_SameSitePolicy: TypeAlias = Literal["Strict", "Lax", "None", "strict", "lax", "none"] + +@type_check_only +class _Serializer(Protocol): + def dumps(self, appstruct: Any, /) -> bytes: ... + def loads(self, bstruct: bytes, /) -> Any: ... + +class RequestCookies(MutableMapping[str, str]): + def __init__(self, environ: WSGIEnvironment) -> None: ... + def __setitem__(self, name: str, value: str) -> None: ... + def __getitem__(self, name: str) -> str: ... + + @overload + def get(self, name: str, default: None = None) -> str | None: ... + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: _T) -> str | _T: ... + + def __delitem__(self, name: str) -> None: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[str]: ... + def items(self) -> ItemsView[str, str]: ... + def __contains__(self, name: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def clear(self) -> None: ... + +class Cookie(dict[bytes, Morsel]): + def __init__(self, input: str | None = None) -> None: ... + def load(self, data: str) -> None: ... + def add(self, key: str | bytes, val: str | bytes) -> Morsel | dict[bytes, bytes]: ... + def __setitem__(self, key: str | bytes, val: str | bytes) -> Morsel | dict[bytes, bytes]: ... # type: ignore[override] + def serialize(self, full: bool = True) -> str: ... + def values(self) -> list[Morsel]: ... # type: ignore[override] + def __str__(self, full: bool = True) -> str: ... + +class Morsel(dict[bytes, bytes | bool | None]): + __slots__ = ("name", "value") + name: bytes + value: bytes + def __init__(self, name: str | bytes, value: str | bytes) -> None: ... + + @property + def path(self) -> bytes | None: ... + @path.setter + def path(self, v: bytes | None) -> None: ... + + @property + def domain(self) -> bytes | None: ... + @domain.setter + def domain(self, v: bytes | None) -> None: ... + + @property + def comment(self) -> bytes | None: ... + @comment.setter + def comment(self, v: bytes | None) -> None: ... + + expires: AsymmetricProperty[bytes | None, datetime | date | timedelta | _TimeTuple | struct_time | int | str | bytes | None] + max_age: AsymmetricProperty[bytes | None, timedelta | int | str | bytes | None] + httponly: AsymmetricProperty[bool, bool | None] + secure: AsymmetricProperty[bool, bool | None] + samesite: AsymmetricProperty[bytes, _SameSitePolicy | bytes] + def __setitem__(self, k: str | bytes, v: bytes | bool | None) -> None: ... + def serialize(self, full: bool = True) -> str: ... + def __str__(self, full: bool = True) -> str: ... + +def make_cookie( + name: str | bytes, + value: str | bytes | None, + max_age: int | timedelta | None = None, + path: str = "/", + domain: str | None = None, + secure: bool | None = False, + httponly: bool | None = False, + comment: str | None = None, + samesite: _SameSitePolicy | None = None, +) -> str: ... + +class JSONSerializer: + def dumps(self, appstruct: Any) -> bytes: ... + def loads(self, bstruct: bytes | str) -> Any: ... + +class Base64Serializer: + serializer: _Serializer + def __init__(self, serializer: _Serializer | None = None) -> None: ... + def dumps(self, appstruct: Any) -> bytes: ... + def loads(self, bstruct: bytes) -> Any: ... + +class SignedSerializer: + salt: str | bytes + secret: str | bytes + hashalg: str + salted_secret: bytes + digest_size: int + serializer: _Serializer + def __init__( + self, secret: str | bytes, salt: str | bytes, hashalg: str = "sha512", serializer: _Serializer | None = None + ) -> None: ... + def dumps(self, appstruct: Any) -> bytes: ... + def loads(self, bstruct: bytes) -> Any: ... + +class CookieProfile: + cookie_name: str + secure: bool + max_age: int | timedelta | None + httponly: bool | None + samesite: _SameSitePolicy | None + path: str + domains: Collection[str] | None + serializer: _Serializer + request: BaseRequest | None + def __init__( + self, + cookie_name: str, + secure: bool = False, + max_age: int | timedelta | None = None, + httponly: bool | None = None, + samesite: _SameSitePolicy | None = None, + path: str = "/", + # even though the docs claim any iterable is fine, that is + # clearly not the case judging by the implementation + domains: Collection[str] | None = None, + serializer: _Serializer | None = None, + ) -> None: ... + def __call__(self, request: BaseRequest) -> CookieProfile: ... + def bind(self, request: BaseRequest) -> CookieProfile: ... + def get_value(self) -> Any | None: ... + def set_cookies( + self, + response: Response, + value: Any, + domains: Collection[str] = sentinel, + max_age: int | timedelta | None = sentinel, + path: str = sentinel, + secure: bool = sentinel, + httponly: bool = sentinel, + samesite: _SameSitePolicy | None = sentinel, + ) -> Response: ... + def get_headers( + self, + value: Any, + domains: Collection[str] = sentinel, + max_age: int | timedelta | None = sentinel, + path: str = sentinel, + secure: bool = sentinel, + httponly: bool = sentinel, + samesite: _SameSitePolicy | None = sentinel, + ) -> list[tuple[str, str]]: ... + +class SignedCookieProfile(CookieProfile): + secret: str | bytes + salt: str | bytes + hashalg: str + original_serializer: _Serializer + def __init__( + self, + secret: str, + salt: str, + cookie_name: str, + secure: bool = False, + max_age: int | timedelta | None = None, + httponly: bool | None = False, + samesite: _SameSitePolicy | None = None, + path: str = "/", + domains: Collection[str] | None = None, + hashalg: str = "sha512", + serializer: _Serializer | None = None, + ) -> None: ... + def __call__(self, request: BaseRequest) -> SignedCookieProfile: ... + def bind(self, request: BaseRequest) -> SignedCookieProfile: ... diff --git a/stubs/WebOb/webob/datetime_utils.pyi b/stubs/WebOb/webob/datetime_utils.pyi new file mode 100644 index 000000000000..68c45d2f12db --- /dev/null +++ b/stubs/WebOb/webob/datetime_utils.pyi @@ -0,0 +1,40 @@ +from datetime import date, datetime, timedelta, tzinfo +from time import _TimeTuple, struct_time + +__all__ = [ + "UTC", + "timedelta_to_seconds", + "year", + "month", + "week", + "day", + "hour", + "minute", + "second", + "parse_date", + "serialize_date", + "parse_date_delta", + "serialize_date_delta", +] + +class _UTC(tzinfo): + def dst(self, dt: datetime | None) -> timedelta: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def tzname(self, dt: datetime | None) -> str: ... + +UTC: _UTC + +def timedelta_to_seconds(td: timedelta) -> int: ... + +day: timedelta +week: timedelta +hour: timedelta +minute: timedelta +second: timedelta +month: timedelta +year: timedelta + +def parse_date(value: str | bytes | None) -> datetime | None: ... +def serialize_date(dt: datetime | date | timedelta | _TimeTuple | struct_time | float | str | bytes) -> str: ... +def parse_date_delta(value: str | bytes | None) -> datetime | None: ... +def serialize_date_delta(value: datetime | date | timedelta | _TimeTuple | struct_time | float | str | bytes) -> str: ... diff --git a/stubs/WebOb/webob/dec.pyi b/stubs/WebOb/webob/dec.pyi new file mode 100644 index 000000000000..bfb8040ecf45 --- /dev/null +++ b/stubs/WebOb/webob/dec.pyi @@ -0,0 +1,204 @@ +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Concatenate, Generic, ParamSpec, TypeAlias, overload, type_check_only +from typing_extensions import Never, Self, TypeVar + +from webob.request import BaseRequest, Request +from webob.response import Response + +__all__ = ["wsgify"] + +_AnyResponse: TypeAlias = Response | WSGIApplication | str | None +_S = TypeVar("_S") +_AppT = TypeVar("_AppT", bound=WSGIApplication) +_AppT_contra = TypeVar("_AppT_contra", bound=WSGIApplication, contravariant=True) +_RequestT = TypeVar("_RequestT", bound=BaseRequest) +_RequestT_contra = TypeVar("_RequestT_contra", bound=BaseRequest, default=Request, contravariant=True) +_P = ParamSpec("_P") +_P2 = ParamSpec("_P2") + +_RequestHandlerCallable: TypeAlias = Callable[Concatenate[_RequestT, _P], _AnyResponse] +_RequestHandlerMethod: TypeAlias = Callable[Concatenate[Any, _RequestT, _P], _AnyResponse] +_MiddlewareCallable: TypeAlias = Callable[Concatenate[_RequestT, _AppT, _P], _AnyResponse] +_MiddlewareMethod: TypeAlias = Callable[Concatenate[Any, _RequestT, _AppT, _P], _AnyResponse] +_RequestHandler: TypeAlias = _RequestHandlerCallable[_RequestT, _P] | _RequestHandlerMethod[_RequestT, _P] +_Middleware: TypeAlias = _MiddlewareCallable[_RequestT, _AppT, _P] | _MiddlewareMethod[_RequestT, _AppT, _P] + +class wsgify(Generic[_P, _RequestT_contra]): + RequestClass: type[_RequestT_contra] + func: _RequestHandler[_RequestT_contra, _P] | None + args: tuple[Any, ...] + kwargs: dict[str, Any] + middleware_wraps: WSGIApplication | None + + # NOTE: We disallow passing args/kwargs using this direct API, because + # we can't really make it work as a decorator this way, these + # arguments should only really be used indirectly through the + # middleware decorator, where we can be more type safe + @overload + def __init__( + self: wsgify[[], Request], + func: _RequestHandler[Request, []] | None = None, + RequestClass: None = None, + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: None = None, + ) -> None: ... + @overload + def __init__( + self: wsgify[[], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _RequestHandler[_RequestT_contra, []] | None, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: None = None, + ) -> None: ... + @overload + def __init__( + self: wsgify[[], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _RequestHandler[_RequestT_contra, []] | None = None, + *, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: None = None, + ) -> None: ... + @overload + def __init__( + self: wsgify[[_AppT_contra], Request], + func: _Middleware[Request, _AppT_contra, []] | None = None, + RequestClass: None = None, + args: tuple[()] = (), + kwargs: None = None, + *, + middleware_wraps: _AppT_contra, + ) -> None: ... + @overload + def __init__( + self: wsgify[[_AppT_contra], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _Middleware[_RequestT_contra, _AppT_contra, []] | None, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + *, + middleware_wraps: _AppT_contra, + ) -> None: ... + @overload + def __init__( + self: wsgify[[_AppT_contra], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _Middleware[_RequestT_contra, _AppT_contra, []] | None = None, + *, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: _AppT_contra, + ) -> None: ... + + @overload + def __get__(self, obj: None, type: type[_S]) -> _unbound_wsgify[_P, _S, _RequestT_contra]: ... + @overload + def __get__(self, obj: object, type: type | None = None) -> Self: ... + + @overload + def __call__(self, env: WSGIEnvironment, /, start_response: StartResponse) -> Iterable[bytes]: ... + @overload + def __call__(self, func: _RequestHandler[_RequestT_contra, _P], /) -> Self: ... + @overload + def __call__(self, req: _RequestT_contra) -> _AnyResponse: ... + @overload + def __call__(self, req: _RequestT_contra, *args: _P.args, **kw: _P.kwargs) -> _AnyResponse: ... + + def get(self, url: str, **kw: Any) -> _AnyResponse: ... + def post( + self, url: str, POST: str | bytes | Mapping[Any, Any] | Mapping[Any, list[Any] | tuple[Any, ...]] | None = None, **kw: Any + ) -> _AnyResponse: ... + def request(self, url: str, **kw: Any) -> _AnyResponse: ... + def call_func(self, req: _RequestT_contra, *args: _P.args, **kwargs: _P.kwargs) -> _AnyResponse: ... + # technically this could bind different type vars, but we disallow it for safety + def clone(self, func: _RequestHandler[_RequestT_contra, _P] | None = None, **kw: Never) -> Self: ... + @property + def undecorated(self) -> _RequestHandler[_RequestT_contra, _P] | None: ... + + @overload + @classmethod + def middleware( + cls, middle_func: None = None, app: _AppT | None = None, *_: _P.args, **kw: _P.kwargs + ) -> _UnboundMiddleware[_P, _AppT, Any]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareCallable[_RequestT, _AppT, _P2], app: None = None + ) -> _MiddlewareFactory[_P2, _AppT, _RequestT]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: None = None + ) -> _MiddlewareFactory[_P2, _AppT, _RequestT]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: None = None, *_: _P2.args, **kw: _P2.kwargs + ) -> _MiddlewareFactory[_P2, _AppT, _RequestT]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: _AppT + ) -> type[wsgify[Concatenate[_AppT, _P2], _RequestT]]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: _AppT, *_: _P2.args, **kw: _P2.kwargs + ) -> type[wsgify[Concatenate[_AppT, _P2], _RequestT]]: ... + +@type_check_only +class _unbound_wsgify(wsgify[_P, _RequestT_contra], Generic[_P, _S, _RequestT_contra]): + @overload # type: ignore[override] + def __call__(self, __self: _S, env: WSGIEnvironment, /, start_response: StartResponse) -> Iterable[bytes]: ... + @overload + def __call__(self, __self: _S, func: _RequestHandler[_RequestT_contra, _P], /) -> Self: ... + @overload + def __call__(self, __self: _S, /, req: _RequestT_contra) -> _AnyResponse: ... + @overload + def __call__(self, __self: _S, /, req: _RequestT_contra, *args: _P.args, **kw: _P.kwargs) -> _AnyResponse: ... + +class _UnboundMiddleware(Generic[_P, _AppT_contra, _RequestT_contra]): + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]] + app: _AppT_contra | None + kw: dict[str, Any] + def __init__( + self, + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]], + app: _AppT_contra | None, + kw: dict[str, Any], + ) -> None: ... + + @overload + def __call__(self, func: None, app: _AppT_contra | None = None) -> Self: ... + @overload + def __call__( + self, func: _Middleware[_RequestT_contra, _AppT_contra, _P], app: None = None + ) -> wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]: ... + @overload + def __call__( + self, func: _Middleware[_RequestT_contra, _AppT_contra, _P], app: _AppT_contra + ) -> wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]: ... + +class _MiddlewareFactory(Generic[_P, _AppT_contra, _RequestT_contra]): + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]] + middleware: _Middleware[_RequestT_contra, _AppT_contra, _P] + kw: dict[str, Any] + def __init__( + self, + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]], + middleware: _Middleware[_RequestT_contra, _AppT_contra, _P], + kw: dict[str, Any], + ) -> None: ... + + # NOTE: Technically you are not allowed to pass args, but we give up all kinds + # of other safety if we don't use ParamSpec + @overload + def __call__( + self, app: None = None, *_: _P.args, **config: _P.kwargs + ) -> _MiddlewareFactory[[], _AppT_contra, _RequestT_contra]: ... + @overload + def __call__(self, app: _AppT_contra, *_: _P.args, **config: _P.kwargs) -> wsgify[[_AppT_contra], _RequestT_contra]: ... diff --git a/stubs/WebOb/webob/descriptors.pyi b/stubs/WebOb/webob/descriptors.pyi new file mode 100644 index 000000000000..0cc3bfc51cff --- /dev/null +++ b/stubs/WebOb/webob/descriptors.pyi @@ -0,0 +1,100 @@ +from collections.abc import Callable, Iterable +from datetime import date, datetime, timedelta +from time import _TimeTuple, struct_time +from typing import Any, NamedTuple, TypeAlias, TypeVar, overload + +from webob._types import AsymmetricProperty, AsymmetricPropertyWithDelete, SymmetricProperty, SymmetricPropertyWithDelete +from webob.byterange import ContentRange, Range +from webob.etag import IfRange, IfRangeDate + +_DefaultT = TypeVar("_DefaultT") +_GetterReturnType = TypeVar("_GetterReturnType") +_SetterValueType = TypeVar("_SetterValueType") +_ConvertedGetterReturnType = TypeVar("_ConvertedGetterReturnType") +_ConvertedSetterValueType = TypeVar("_ConvertedSetterValueType") +_DescriptorT = TypeVar("_DescriptorT", bound=AsymmetricPropertyWithDelete[Any, Any]) + +_StringProperty: TypeAlias = SymmetricPropertyWithDelete[str | None] +_ListProperty: TypeAlias = AsymmetricPropertyWithDelete[tuple[str, ...] | None, Iterable[str] | str | None] +_DateProperty: TypeAlias = AsymmetricPropertyWithDelete[ + datetime | None, date | datetime | timedelta | _TimeTuple | struct_time | float | str | None +] +_ContentRangeParams: TypeAlias = ( + ContentRange + | list[int] + | list[None] + | list[int | None] + | tuple[int, int] + | tuple[None, None] + | tuple[int, int, int | None] + | tuple[None, None, int | None] + | str + | None +) + +@overload +def environ_getter(key: str, *, rfc_section: str | None = None) -> SymmetricProperty[Any]: ... +@overload +def environ_getter(key: str, default: None, rfc_section: str | None = None) -> SymmetricPropertyWithDelete[Any | None]: ... +@overload +def environ_getter( + key: str, default: _DefaultT, rfc_section: str | None = None +) -> AsymmetricPropertyWithDelete[Any | _DefaultT, Any | _DefaultT | None]: ... + +@overload +def environ_decoder(key: str, *, rfc_section: str | None = None, encattr: str | None = None) -> SymmetricProperty[str]: ... +@overload +def environ_decoder( + key: str, default: str, rfc_section: str | None = None, encattr: str | None = None +) -> AsymmetricPropertyWithDelete[str, str | None]: ... +@overload +def environ_decoder( + key: str, default: None, rfc_section: str | None = None, encattr: str | None = None +) -> SymmetricPropertyWithDelete[str | None]: ... + +def upath_property(key: str) -> SymmetricProperty[str]: ... +def deprecated_property(attr: _DescriptorT, name: str, text: str, version: str) -> _DescriptorT: ... +def header_getter(header: str, rfc_section: str) -> _StringProperty: ... + +@overload +def converter( + prop: AsymmetricPropertyWithDelete[_GetterReturnType, _SetterValueType], + parse: Callable[[_GetterReturnType], _ConvertedGetterReturnType], + serialize: Callable[[_ConvertedSetterValueType], _SetterValueType], + convert_name: str | None = None, +) -> AsymmetricPropertyWithDelete[_ConvertedGetterReturnType, _ConvertedSetterValueType | None]: ... +@overload +def converter( + prop: AsymmetricProperty[_GetterReturnType, _SetterValueType], + parse: Callable[[_GetterReturnType], _ConvertedGetterReturnType], + serialize: Callable[[_ConvertedSetterValueType], _SetterValueType], + convert_name: str | None = None, +) -> AsymmetricProperty[_ConvertedGetterReturnType, _ConvertedSetterValueType | None]: ... + +def list_header(header: str, rfc_section: str) -> _ListProperty: ... +def parse_list(value: str | None) -> tuple[str, ...] | None: ... +def serialize_list(value: Iterable[str] | str) -> str: ... +def converter_date(prop: _StringProperty) -> _DateProperty: ... +def date_header(header: str, rfc_section: str) -> _DateProperty: ... +def parse_etag_response(value: str | None, strong: bool = False) -> str | None: ... +def serialize_etag_response(value: tuple[str, bool] | str) -> str: ... +def serialize_if_range(value: IfRange | IfRangeDate | datetime | date | str) -> str | None: ... +def parse_range(value: str | None) -> Range | None: ... +def serialize_range(value: tuple[int, int | None] | list[int | None] | list[int] | str | None) -> str | None: ... +def parse_int(value: str | None) -> int | None: ... +def parse_int_safe(value: str | None) -> int | None: ... + +serialize_int: Callable[[int], str] + +def parse_content_range(value: str | None) -> ContentRange | None: ... +def serialize_content_range(value: _ContentRangeParams) -> str | None: ... +def parse_auth_params(params: str) -> dict[str, str]: ... + +known_auth_schemes: dict[str, None] + +class _authorization(NamedTuple): + authtype: str + params: dict[str, str] | str + +def parse_auth(val: str | None) -> _authorization | None: ... +def serialize_auth(val: tuple[str, dict[str, str] | str] | list[Any] | str | None) -> str | None: ... diff --git a/stubs/WebOb/webob/etag.pyi b/stubs/WebOb/webob/etag.pyi new file mode 100644 index 000000000000..f6f5502d55f8 --- /dev/null +++ b/stubs/WebOb/webob/etag.pyi @@ -0,0 +1,45 @@ +from collections.abc import Collection +from datetime import datetime +from typing import Literal, TypeAlias + +from webob._types import AsymmetricPropertyWithDelete +from webob.response import Response + +__all__ = ["AnyETag", "NoETag", "ETagMatcher", "IfRange", "etag_property"] + +_ETag: TypeAlias = _AnyETag | _NoETag | ETagMatcher +_ETagProperty: TypeAlias = AsymmetricPropertyWithDelete[_ETag, _ETag | str | None] + +def etag_property(key: str, default: _ETag, rfc_section: str, strong: bool = True) -> _ETagProperty: ... + +class _AnyETag: + def __bool__(self) -> Literal[False]: ... + def __contains__(self, other: str | None) -> Literal[True]: ... + +AnyETag: _AnyETag + +class _NoETag: + def __bool__(self) -> Literal[False]: ... + def __contains__(self, other: str | None) -> Literal[False]: ... + +NoETag: _NoETag + +class ETagMatcher: + etags: Collection[str] + def __init__(self, etags: Collection[str]) -> None: ... + def __contains__(self, other: str | None) -> bool: ... + @classmethod + def parse(cls, value: str, strong: bool = True) -> ETagMatcher | _AnyETag: ... + +class IfRange: + etag: _ETag + def __init__(self, etag: _ETag) -> None: ... + @classmethod + def parse(cls, value: str | None) -> IfRange | IfRangeDate: ... + def __contains__(self, resp: Response) -> bool: ... + def __bool__(self) -> bool: ... + +class IfRangeDate: + date: datetime + def __init__(self, date: datetime) -> None: ... + def __contains__(self, resp: Response) -> bool: ... diff --git a/stubs/WebOb/webob/exc.pyi b/stubs/WebOb/webob/exc.pyi new file mode 100644 index 000000000000..d1671ef356dc --- /dev/null +++ b/stubs/WebOb/webob/exc.pyi @@ -0,0 +1,190 @@ +from _typeshed import SupportsItems, SupportsKeysAndGetItem +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from string import Template +from typing import Any, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Self + +from webob.response import Response + +__all__ = [ + "HTTPAccepted", + "HTTPBadGateway", + "HTTPBadRequest", + "HTTPClientError", + "HTTPConflict", + "HTTPCreated", + "HTTPError", + "HTTPExpectationFailed", + "HTTPFailedDependency", + "HTTPForbidden", + "HTTPFound", + "HTTPGatewayTimeout", + "HTTPGone", + "HTTPInsufficientStorage", + "HTTPInternalServerError", + "HTTPLengthRequired", + "HTTPLocked", + "HTTPMethodNotAllowed", + "HTTPMovedPermanently", + "HTTPMultipleChoices", + "HTTPNetworkAuthenticationRequired", + "HTTPNoContent", + "HTTPNonAuthoritativeInformation", + "HTTPNotAcceptable", + "HTTPNotFound", + "HTTPNotImplemented", + "HTTPNotModified", + "HTTPOk", + "HTTPPartialContent", + "HTTPPaymentRequired", + "HTTPPermanentRedirect", + "HTTPPreconditionFailed", + "HTTPPreconditionRequired", + "HTTPProxyAuthenticationRequired", + "HTTPRedirection", + "HTTPRequestEntityTooLarge", + "HTTPRequestHeaderFieldsTooLarge", + "HTTPRequestRangeNotSatisfiable", + "HTTPRequestTimeout", + "HTTPRequestURITooLong", + "HTTPResetContent", + "HTTPSeeOther", + "HTTPServerError", + "HTTPServiceUnavailable", + "HTTPTemporaryRedirect", + "HTTPTooManyRequests", + "HTTPUnauthorized", + "HTTPUnavailableForLegalReasons", + "HTTPUnprocessableEntity", + "HTTPUnsupportedMediaType", + "HTTPUseProxy", + "HTTPVersionNotSupported", + "WSGIHTTPException", + "HTTPException", + "HTTPExceptionMiddleware", + "status_map", +] + +_Headers: TypeAlias = SupportsItems[str, str] | SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]] + +@type_check_only +class _JSONFormatter(Protocol): + def __call__(self, *, body: str, status: str, title: str, environ: WSGIEnvironment) -> Any: ... + +class HTTPException(Exception): + wsgi_response: Response + def __init__(self, message: str, wsgi_response: Response) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +class WSGIHTTPException(Response, HTTPException): + code: int + title: str + explanation: str + body_template_obj: Template + plain_template_obj: Template + html_template_obj: Template + empty_body: bool + detail: str | None + comment: str | None + def __init__( + self, + detail: str | None = None, + headers: _Headers | None = None, + comment: str | None = None, + body_template: str | None = None, + json_formatter: _JSONFormatter | None = None, + **kw: Any, + ) -> None: ... + def plain_body(self, environ: WSGIEnvironment) -> str: ... + def html_body(self, environ: WSGIEnvironment) -> str: ... + def json_formatter(self, body: str, status: str, title: str, environ: WSGIEnvironment) -> Any: ... + def json_body(self, environ: WSGIEnvironment) -> str: ... # type: ignore[override] + def generate_response(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + @property + def wsgi_response(self) -> Self: ... # type: ignore[override] + def __str__(self) -> str: ... # type: ignore[override] # noqa: Y029 + +class HTTPError(WSGIHTTPException): ... +class HTTPRedirection(WSGIHTTPException): ... +class HTTPOk(WSGIHTTPException): ... +class HTTPCreated(HTTPOk): ... +class HTTPAccepted(HTTPOk): ... +class HTTPNonAuthoritativeInformation(HTTPOk): ... + +class HTTPNoContent(HTTPOk): + empty_body: Literal[True] + +class HTTPResetContent(HTTPOk): + empty_body: Literal[True] + +class HTTPPartialContent(HTTPOk): ... + +class _HTTPMove(HTTPRedirection): + explanation: str + add_slash: bool + def __init__( + self, + detail: str | None = None, + headers: _Headers | None = None, + comment: str | None = None, + body_template: str | None = None, + location: str | None = None, + add_slash: bool = False, + ) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +class HTTPMultipleChoices(_HTTPMove): ... +class HTTPMovedPermanently(_HTTPMove): ... +class HTTPFound(_HTTPMove): ... +class HTTPSeeOther(_HTTPMove): ... + +class HTTPNotModified(HTTPRedirection): + empty_body: Literal[True] + +class HTTPUseProxy(_HTTPMove): ... +class HTTPTemporaryRedirect(_HTTPMove): ... +class HTTPPermanentRedirect(_HTTPMove): ... +class HTTPClientError(HTTPError): ... +class HTTPBadRequest(HTTPClientError): ... +class HTTPUnauthorized(HTTPClientError): ... +class HTTPPaymentRequired(HTTPClientError): ... +class HTTPForbidden(HTTPClientError): ... +class HTTPNotFound(HTTPClientError): ... +class HTTPMethodNotAllowed(HTTPClientError): ... +class HTTPNotAcceptable(HTTPClientError): ... +class HTTPProxyAuthenticationRequired(HTTPClientError): ... +class HTTPRequestTimeout(HTTPClientError): ... +class HTTPConflict(HTTPClientError): ... +class HTTPGone(HTTPClientError): ... +class HTTPLengthRequired(HTTPClientError): ... +class HTTPPreconditionFailed(HTTPClientError): ... +class HTTPRequestEntityTooLarge(HTTPClientError): ... +class HTTPRequestURITooLong(HTTPClientError): ... +class HTTPUnsupportedMediaType(HTTPClientError): ... +class HTTPRequestRangeNotSatisfiable(HTTPClientError): ... +class HTTPExpectationFailed(HTTPClientError): ... +class HTTPUnprocessableEntity(HTTPClientError): ... +class HTTPLocked(HTTPClientError): ... +class HTTPFailedDependency(HTTPClientError): ... +class HTTPPreconditionRequired(HTTPClientError): ... +class HTTPTooManyRequests(HTTPClientError): ... +class HTTPRequestHeaderFieldsTooLarge(HTTPClientError): ... +class HTTPUnavailableForLegalReasons(HTTPClientError): ... +class HTTPServerError(HTTPError): ... +class HTTPInternalServerError(HTTPServerError): ... +class HTTPNotImplemented(HTTPServerError): ... +class HTTPBadGateway(HTTPServerError): ... +class HTTPServiceUnavailable(HTTPServerError): ... +class HTTPGatewayTimeout(HTTPServerError): ... +class HTTPVersionNotSupported(HTTPServerError): ... +class HTTPInsufficientStorage(HTTPServerError): ... +class HTTPNetworkAuthenticationRequired(HTTPServerError): ... + +class HTTPExceptionMiddleware: + application: WSGIApplication + def __init__(self, application: WSGIApplication) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +status_map: dict[int, type[HTTPOk | HTTPRedirection | HTTPClientError | HTTPServerError]] diff --git a/stubs/WebOb/webob/headers.pyi b/stubs/WebOb/webob/headers.pyi new file mode 100644 index 000000000000..5120b86ad866 --- /dev/null +++ b/stubs/WebOb/webob/headers.pyi @@ -0,0 +1,36 @@ +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Iterator, MutableMapping +from typing import TypeVar, overload + +from webob.multidict import MultiDict + +__all__ = ["ResponseHeaders", "EnvironHeaders"] + +_T = TypeVar("_T") + +class ResponseHeaders(MultiDict[str, str]): + def __getitem__(self, key: str) -> str: ... + def getall(self, key: str) -> list[str]: ... + def mixed(self) -> dict[str, str | list[str]]: ... + def dict_of_lists(self) -> dict[str, list[str]]: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + has_key = __contains__ + def setdefault(self, key: str, default: str) -> str: ... # type: ignore[override] + + @overload + def pop(self, key: str) -> str: ... + @overload + def pop(self, key: str, default: _T) -> str | _T: ... + +class EnvironHeaders(MutableMapping[str, str]): + environ: WSGIEnvironment + def __init__(self, environ: WSGIEnvironment) -> None: ... + def __getitem__(self, hname: str) -> str: ... + def __setitem__(self, hname: str, value: str) -> None: ... + def __delitem__(self, hname: str) -> None: ... + def keys(self) -> Iterator[str]: ... # type: ignore[override] + def __contains__(self, hname: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... diff --git a/stubs/WebOb/webob/multidict.pyi b/stubs/WebOb/webob/multidict.pyi new file mode 100644 index 000000000000..c4a64bf11b14 --- /dev/null +++ b/stubs/WebOb/webob/multidict.pyi @@ -0,0 +1,197 @@ +from _typeshed import SupportsGetItem, SupportsKeysAndGetItem +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Collection, Iterable, Iterator, MutableMapping +from typing import Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob.compat import cgi_FieldStorage, cgi_FieldStorage as _FieldStorageWithFile + +__all__ = ["MultiDict", "NestedMultiDict", "NoVars", "GetDict"] + +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) + +@type_check_only +class _SupportsItemsWithIterableResult(Protocol[_KT_co, _VT_co]): + def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ... + +class MultiDict(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self: MultiDict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + @overload + def __init__(self, m: _SupportsItemsWithIterableResult[_KT, _VT], /) -> None: ... + @overload + def __init__( + self: MultiDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + m: _SupportsItemsWithIterableResult[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, m: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def __init__( + self: MultiDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + m: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + + @classmethod + def view_list(cls, lst: list[tuple[_KT, _VT]]) -> Self: ... + @classmethod + def from_fieldstorage(cls, fs: cgi_FieldStorage) -> MultiDict[str, str | _FieldStorageWithFile]: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def add(self, key: _KT, value: _VT) -> None: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + + def getall(self, key: _KT) -> list[_VT]: ... + def getone(self, key: _KT) -> _VT: ... + def mixed(self) -> dict[_KT, _VT | list[_VT]]: ... + def dict_of_lists(self) -> dict[_KT, list[_VT]]: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... + has_key = __contains__ + def clear(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def setdefault(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + def popitem(self) -> tuple[_KT, _VT]: ... + + @overload # type: ignore[override] + def update(self: SupportsGetItem[str, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, m: Collection[tuple[_KT, _VT]], /) -> None: ... + @overload + def update(self: SupportsGetItem[str, _VT], m: Collection[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... + + @overload + def extend(self, other: _SupportsItemsWithIterableResult[_KT, _VT]) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: _SupportsItemsWithIterableResult[str, _VT], **kwargs: _VT) -> None: ... + @overload + def extend(self, other: Iterable[tuple[_KT, _VT]]) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... + @overload + def extend(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: None = None, **kwargs: _VT) -> None: ... + + def __len__(self) -> int: ... + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + __iter__ = keys + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + +class GetDict(MultiDict[str, str]): + env: WSGIEnvironment + + @overload + def __init__(self, data: _SupportsItemsWithIterableResult[str, str], env: WSGIEnvironment) -> None: ... + @overload + def __init__(self, data: Iterable[tuple[str, str]], env: WSGIEnvironment) -> None: ... + + def on_change(self) -> None: ... + def __setitem__(self, key: str, value: str) -> None: ... + def add(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def clear(self) -> None: ... + def setdefault(self, key: str, default: str) -> str: ... # type: ignore[override] + + @overload + def pop(self, key: str) -> str: ... + @overload + def pop(self, key: str, default: _T) -> str | _T: ... + + def popitem(self) -> tuple[str, str]: ... + + @overload # type: ignore[override] + def update(self, **kwargs: str) -> None: ... + @overload + def update(self, m: Collection[tuple[str, str]], /, **kwargs: str) -> None: ... + + @overload + def extend(self, other: _SupportsItemsWithIterableResult[str, str], **kwargs: str) -> None: ... + @overload + def extend(self, other: Iterable[tuple[str, str]], **kwargs: str) -> None: ... + @overload + def extend(self, other: SupportsKeysAndGetItem[str, str], **kwargs: str) -> None: ... + @overload + def extend(self, other: None = None, **kwargs: str) -> None: ... + + def copy(self) -> MultiDict[str, str]: ... # type: ignore[override] + +class NestedMultiDict(MultiDict[_KT, _VT]): + # FIXME: It would be more accurate to use a Protocol here, which has a + # covariant _VT, instead of MultiDict + dicts: tuple[MultiDict[_KT, _VT], ...] + def __init__(self, *dicts: MultiDict[_KT, _VT]) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... + # NOTE: These methods all return exceptions, so this will give us + # somewhat sane type checker errors, we would prefer to use + # something like @type_error here, if it existed. + # This is only really necessary, because the inheritance hierarchy + # is a mess. + __setitem__: None # type: ignore[assignment] + add: None # type: ignore[assignment] + __delitem__: None # type: ignore[assignment] + clear: None # type: ignore[assignment] + setdefault: None # type: ignore[assignment] + pop: None # type: ignore[assignment] + popitem: None # type: ignore[assignment] + update: None # type: ignore[assignment] + def getall(self, key: _KT) -> list[_VT]: ... + def copy(self) -> MultiDict[_KT, _VT]: ... # type: ignore[override] + def __contains__(self, key: object) -> bool: ... + has_key = __contains__ + def __len__(self) -> int: ... + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + __iter__ = keys + +class NoVars: + reason: str + def __init__(self, reason: str | None = None) -> None: ... + + @overload + def get(self, key: str, default: None = None) -> None: ... + @overload + def get(self, key: str, default: _T) -> _T: ... + + def getall(self, key: str) -> list[str]: ... + def mixed(self) -> dict[str, str | list[str]]: ... + def dict_of_lists(self) -> dict[str, list[str]]: ... + def __contains__(self, key: object) -> Literal[False]: ... + has_key = __contains__ + def copy(self) -> Self: ... + def __len__(self) -> Literal[0]: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> Iterator[str]: ... + def values(self) -> Iterator[str]: ... + def items(self) -> Iterator[tuple[str, str]]: ... + def __bool__(self) -> Literal[False]: ... diff --git a/stubs/WebOb/webob/request.pyi b/stubs/WebOb/webob/request.pyi new file mode 100644 index 000000000000..e0135b3f1c74 --- /dev/null +++ b/stubs/WebOb/webob/request.pyi @@ -0,0 +1,259 @@ +import datetime +import io +from _typeshed import OptExcInfo, SupportsKeysAndGetItem, SupportsNoArgReadline, SupportsRead, WriteableBuffer +from _typeshed.wsgi import WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Mapping +from re import Pattern +from typing import IO, Any, ClassVar, Literal, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob._types import AsymmetricProperty, AsymmetricPropertyWithDelete, SymmetricProperty, SymmetricPropertyWithDelete +from webob.acceptparse import _AcceptCharsetProperty, _AcceptEncodingProperty, _AcceptLanguageProperty, _AcceptProperty +from webob.byterange import Range +from webob.cachecontrol import CacheControl +from webob.client import SendRequest +from webob.compat import cgi_FieldStorage +from webob.cookies import RequestCookies +from webob.descriptors import _authorization, _DateProperty +from webob.etag import IfRange, IfRangeDate, _ETagProperty +from webob.headers import EnvironHeaders +from webob.multidict import GetDict, MultiDict, NestedMultiDict, NoVars +from webob.response import Response + +__all__ = ["BaseRequest", "Request", "LegacyRequest"] + +_T = TypeVar("_T") +_HTTPMethod: TypeAlias = Literal["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"] +_ListOrTuple: TypeAlias = list[_T] | tuple[_T, ...] +_RequestCacheControl: TypeAlias = CacheControl[Literal["request"]] + +@type_check_only +class _SupportsReadAndNoArgReadline(SupportsRead[str | bytes], SupportsNoArgReadline[str | bytes], Protocol): ... + +@type_check_only +class _RequestCacheControlDict(TypedDict, total=False): + max_stale: int + min_stale: int + only_if_cached: bool + no_cache: Literal[True] | str + no_store: bool + no_transform: bool + max_age: int + +_FieldStorageWithFile = cgi_FieldStorage + +class _NoDefault: ... + +NoDefault: _NoDefault + +class BaseRequest: + request_body_tempfile_limit: ClassVar[int] + environ: WSGIEnvironment + def __init__(self, environ: WSGIEnvironment, **kw: Any) -> None: ... + + @overload + def encget(self, key: str, default: _T, encattr: str | None = None) -> str | _T: ... + @overload + def encget(self, key: str, *, encattr: str | None = None) -> str: ... + + def encset(self, key: str, val: str, encattr: str | None = None) -> None: ... + @property + def charset(self) -> str | None: ... + def decode(self, charset: str | None = None, errors: str = "strict") -> Self: ... + + @property + def body_file(self) -> SupportsRead[bytes]: ... + @body_file.setter + def body_file(self, value: SupportsRead[bytes]) -> None: ... + @body_file.deleter + def body_file(self) -> None: ... + + content_length: SymmetricPropertyWithDelete[int | None] + body_file_raw: SymmetricProperty[SupportsRead[bytes]] + is_body_seekable: bool + @property + def body_file_seekable(self) -> IO[bytes]: ... + url_encoding: AsymmetricPropertyWithDelete[str, str | None] + scheme: SymmetricProperty[str] + method: AsymmetricPropertyWithDelete[_HTTPMethod, _HTTPMethod | None] + http_version: SymmetricProperty[str] + remote_user: SymmetricPropertyWithDelete[str | None] + remote_host: SymmetricPropertyWithDelete[str | None] + remote_addr: SymmetricPropertyWithDelete[str | None] + query_string: AsymmetricPropertyWithDelete[str, str | None] + server_name: SymmetricProperty[str] + server_port: SymmetricProperty[int] + script_name: AsymmetricPropertyWithDelete[str, str | None] + path_info: SymmetricProperty[str] + uscript_name = script_name # bw compat # pyrefly: ignore [unknown-name] + upath_info = path_info # bw compat # pyrefly: ignore [unknown-name] + content_type: AsymmetricPropertyWithDelete[str, str | None] + headers: AsymmetricProperty[EnvironHeaders, SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]]] + @property + def client_addr(self) -> str | None: ... + @property + def host_port(self) -> str: ... + @property + def host_url(self) -> str: ... + @property + def application_url(self) -> str: ... + @property + def path_url(self) -> str: ... + @property + def path(self) -> str: ... + @property + def path_qs(self) -> str: ... + @property + def url(self) -> str: ... + def relative_url(self, other_url: str, to_application: bool = False) -> str: ... + def path_info_pop(self, pattern: Pattern[str] | None = None) -> str | None: ... + def path_info_peek(self) -> str | None: ... + urlvars: SymmetricPropertyWithDelete[dict[str, str]] + urlargs: SymmetricPropertyWithDelete[tuple[str, ...]] + @property + def is_xhr(self) -> bool: ... + host: SymmetricPropertyWithDelete[str] + @property + def domain(self) -> str: ... + + @property + def body(self) -> bytes: ... + @body.setter + def body(self, value: bytes | None) -> None: ... + @body.deleter + def body(self) -> None: ... + + json: SymmetricPropertyWithDelete[Any] + json_body: SymmetricPropertyWithDelete[Any] + text: SymmetricPropertyWithDelete[str] + @property + def POST(self) -> MultiDict[str, str | _FieldStorageWithFile] | NoVars: ... + @property + def GET(self) -> GetDict: ... + @property + def params(self) -> NestedMultiDict[str, str | _FieldStorageWithFile]: ... + cookies: AsymmetricProperty[RequestCookies, SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]]] + def copy(self) -> Self: ... + def copy_get(self) -> Self: ... + + @property + def is_body_readable(self) -> bool: ... + @is_body_readable.setter + def is_body_readable(self, flag: bool) -> None: ... + + def make_body_seekable(self) -> None: ... + def copy_body(self) -> None: ... + def make_tempfile(self) -> io.BufferedRandom: ... + def remove_conditional_headers( + self, remove_encoding: bool = True, remove_range: bool = True, remove_match: bool = True, remove_modified: bool = True + ) -> None: ... + accept: _AcceptProperty + accept_charset: _AcceptCharsetProperty + accept_encoding: _AcceptEncodingProperty + accept_language: _AcceptLanguageProperty + authorization: AsymmetricPropertyWithDelete[_authorization | None, tuple[str, str | dict[str, str]] | list[Any] | str | None] + cache_control: AsymmetricPropertyWithDelete[ + _RequestCacheControl, _RequestCacheControl | _RequestCacheControlDict | str | None + ] + if_match: _ETagProperty + if_none_match: _ETagProperty + date: _DateProperty + if_modified_since: _DateProperty + if_unmodified_since: _DateProperty + if_range: AsymmetricPropertyWithDelete[ + IfRange | IfRangeDate, IfRange | IfRangeDate | datetime.datetime | datetime.date | str | None + ] + max_forwards: SymmetricPropertyWithDelete[int | None] + pragma: SymmetricPropertyWithDelete[str | None] + range: AsymmetricPropertyWithDelete[Range | None, tuple[int, int | None] | list[int | None] | list[int] | str | None] + referer: SymmetricPropertyWithDelete[str | None] + referrer = referer # pyrefly: ignore [unknown-name] + user_agent: SymmetricPropertyWithDelete[str | None] + def as_bytes(self, skip_body: bool = False) -> bytes: ... + def as_text(self) -> str: ... + @classmethod + def from_bytes(cls, b: bytes) -> Self: ... + @classmethod + def from_text(cls, s: str) -> Self: ... + @classmethod + def from_file(cls, fp: _SupportsReadAndNoArgReadline) -> Self: ... + + @overload + def call_application( + self, application: WSGIApplication, catch_exc_info: Literal[False] = False + ) -> tuple[str, list[tuple[str, str]], Iterable[bytes]]: ... + @overload + def call_application( + self, application: WSGIApplication, catch_exc_info: Literal[True] + ) -> tuple[str, list[tuple[str, str]], Iterable[bytes], OptExcInfo | None]: ... + @overload + def call_application( + self, application: WSGIApplication, catch_exc_info: bool + ) -> ( + tuple[str, list[tuple[str, str]], Iterable[bytes], OptExcInfo | None] | tuple[str, list[tuple[str, str]], Iterable[bytes]] + ): ... + + ResponseClass: type[Response] + def send(self, application: WSGIApplication | None = None, catch_exc_info: bool = False) -> Response: ... + get_response = send + def make_default_send_app(self) -> SendRequest: ... + @classmethod + def blank( + cls, + path: str, + environ: dict[str, None] | None = None, + base_url: str | None = None, + headers: Mapping[str, str] | None = None, + POST: str | bytes | Mapping[Any, Any] | Mapping[Any, _ListOrTuple[Any]] | None = None, + **kw: Any, + ) -> Self: ... + +class LegacyRequest(BaseRequest): + @property # type: ignore[override] + def uscript_name(self) -> str: ... + @uscript_name.setter + def uscript_name(self, value: str) -> None: ... + + @property # type: ignore[override] + def upath_info(self) -> str: ... + @upath_info.setter + def upath_info(self, value: str) -> None: ... + + def encget(self, key: str, default: Any = ..., encattr: str | None = None) -> Any: ... + +class AdhocAttrMixin: + def __setattr__(self, attr: str, value: Any) -> None: ... + def __getattr__(self, attr: str) -> Any: ... + def __delattr__(self, attr: str) -> None: ... + +class Request(AdhocAttrMixin, BaseRequest): + # this is so Request doesn't count as callable, it's not very pretty + # but we run into trouble with overlapping overloads in wsgify if we + # don't exclude __call__ from arbitrary attribute access + __call__: None + +class DisconnectionError(IOError): ... + +def environ_from_url(path: str) -> WSGIEnvironment: ... +def environ_add_POST( + env: WSGIEnvironment, + data: str | bytes | Mapping[Any, Any] | Mapping[Any, _ListOrTuple[Any]] | None, + content_type: str | None = None, +) -> None: ... + +class LimitedLengthFile(io.RawIOBase): + file: SupportsRead[bytes] + maxlen: int + remaining: int + def __init__(self, file: SupportsRead[bytes], maxlen: int) -> None: ... + def fileno(self) -> int: ... + @staticmethod + def readable() -> Literal[True]: ... + def readinto(self, buff: WriteableBuffer) -> int: ... + +class Transcoder: + charset: str + errors: str + def __init__(self, charset: str, errors: str = "strict") -> None: ... + def transcode_query(self, q: str) -> str: ... + def transcode_fs(self, fs: cgi_FieldStorage, content_type: str) -> io.BytesIO: ... diff --git a/stubs/WebOb/webob/response.pyi b/stubs/WebOb/webob/response.pyi new file mode 100644 index 000000000000..3bfa3ae3d643 --- /dev/null +++ b/stubs/WebOb/webob/response.pyi @@ -0,0 +1,181 @@ +from _typeshed import SupportsItems, SupportsRead +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Iterator, Sequence +from datetime import timedelta +from typing import IO, Any, Literal, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob._types import AsymmetricProperty, AsymmetricPropertyWithDelete, SymmetricProperty, SymmetricPropertyWithDelete +from webob.byterange import ContentRange +from webob.cachecontrol import CacheControl +from webob.cookies import _SameSitePolicy +from webob.descriptors import _authorization, _ContentRangeParams, _DateProperty, _ListProperty +from webob.headers import ResponseHeaders +from webob.request import Request + +__all__ = ["Response"] + +_ResponseT = TypeVar("_ResponseT", bound=Response) +_ResponseCacheControl: TypeAlias = CacheControl[Literal["response"]] + +@type_check_only +class _ResponseCacheExpires(Protocol): + def __call__( + self, + seconds: int | timedelta = 0, + *, + public: bool = ..., + private: Literal[True] | str = ..., + no_cache: Literal[True] | str = ..., + no_store: bool = ..., + no_transform: bool = ..., + must_revalidate: bool = ..., + proxy_revalidate: bool = ..., + max_age: int = ..., + s_maxage: int = ..., + s_max_age: int = ..., + stale_while_revalidate: int = ..., + stale_if_error: int = ..., + ) -> None: ... + +@type_check_only +class _ResponseCacheControlDict(TypedDict, total=False): + public: bool + private: Literal[True] | str + no_cache: Literal[True] | str + no_store: bool + no_transform: bool + must_revalidate: bool + proxy_revalidate: bool + max_age: int + s_maxage: int + s_max_age: int + stale_while_revalidate: int + stale_if_error: int + +class Response: + default_content_type: str + default_charset: str + unicode_errors: str + default_conditional_response: bool + default_body_encoding: str + request: Request | None + environ: WSGIEnvironment | None + status: AsymmetricProperty[str, int | str | bytes] + conditional_response: bool + def __init__( + self, + body: bytes | str | None = None, + status: int | str | bytes | None = None, + headerlist: list[tuple[str, str]] | None = None, + app_iter: Iterable[bytes] | None = None, + content_type: str | None = None, + conditional_response: bool | None = None, + charset: str = ..., + **kw: Any, + ) -> None: ... + @classmethod + def from_file(cls, fp: IO[str] | IO[bytes]) -> Response: ... + def copy(self) -> Response: ... + status_code: SymmetricProperty[int] + status_int: SymmetricProperty[int] + headerlist: AsymmetricPropertyWithDelete[list[tuple[str, str]], Iterable[tuple[str, str]] | SupportsItems[str, str]] + headers: AsymmetricProperty[ResponseHeaders, SupportsItems[str, str] | Iterable[tuple[str, str]]] + body: SymmetricPropertyWithDelete[bytes] + json: SymmetricPropertyWithDelete[Any] + json_body: SymmetricPropertyWithDelete[Any] + @property + def has_body(self) -> bool: ... + text: SymmetricPropertyWithDelete[str] + unicode_body: SymmetricPropertyWithDelete[str] # deprecated + ubody: SymmetricPropertyWithDelete[str] # deprecated + body_file: AsymmetricPropertyWithDelete[ResponseBodyFile, SupportsRead[bytes]] + content_length: AsymmetricPropertyWithDelete[int | None, int | str | bytes | None] + def write(self, text: str | bytes) -> int: ... + app_iter: SymmetricPropertyWithDelete[Iterable[bytes]] + allow: _ListProperty + vary: _ListProperty + content_encoding: SymmetricPropertyWithDelete[str | None] + content_language: SymmetricPropertyWithDelete[str | None] + content_location: SymmetricPropertyWithDelete[str | None] + content_md5: SymmetricPropertyWithDelete[str | None] + content_disposition: SymmetricPropertyWithDelete[str | None] + accept_ranges: SymmetricPropertyWithDelete[str | None] + content_range: AsymmetricPropertyWithDelete[ContentRange | None, _ContentRangeParams] + date: _DateProperty + expires: _DateProperty + last_modified: _DateProperty + etag: AsymmetricPropertyWithDelete[str | None, tuple[str, bool] | str | None] + @property + def etag_strong(self) -> str | None: ... + location: SymmetricPropertyWithDelete[str | None] + pragma: SymmetricPropertyWithDelete[str | None] + age: SymmetricPropertyWithDelete[int | None] + retry_after: _DateProperty + server: SymmetricPropertyWithDelete[str | None] + www_authenticate: AsymmetricPropertyWithDelete[ + _authorization | None, tuple[str, str | dict[str, str]] | list[Any] | str | None + ] + charset: SymmetricPropertyWithDelete[str | None] + content_type: SymmetricPropertyWithDelete[str | None] + content_type_params: AsymmetricPropertyWithDelete[dict[str, str], SupportsItems[str, str] | None] + def set_cookie( + self, + name: str | bytes, + value: str | bytes | None = "", + max_age: int | timedelta | None = None, + path: str = "/", + domain: str | None = None, + secure: bool = False, + httponly: bool = False, + comment: str | None = None, + overwrite: bool = False, + samesite: _SameSitePolicy | None = None, + ) -> None: ... + def delete_cookie(self, name: str | bytes, path: str = "/", domain: str | None = None) -> None: ... + def unset_cookie(self, name: str | bytes, strict: bool = True) -> None: ... + + @overload + def merge_cookies(self, resp: _ResponseT) -> _ResponseT: ... + @overload + def merge_cookies(self, resp: WSGIApplication) -> WSGIApplication: ... + + cache_control: AsymmetricProperty[_ResponseCacheControl, _ResponseCacheControl | _ResponseCacheControlDict | str | None] + cache_expires: AsymmetricProperty[_ResponseCacheExpires, timedelta | int | bool | None] + def encode_content(self, encoding: Literal["gzip", "identity"] = "gzip", lazy: bool = False) -> None: ... + def decode_content(self) -> None: ... + def md5_etag(self, body: bytes | None = None, set_content_md5: bool = False) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def conditional_response_app(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def app_iter_range(self, start: int, stop: int | None) -> AppIterRange: ... + def __str__(self, skip_body: bool = False) -> str: ... + +class ResponseBodyFile: + mode: Literal["wb"] + closed: Literal[False] + response: Response + def __init__(self, response: Response) -> None: ... + @property + def encoding(self) -> str | None: ... + # NOTE: Technically this is an instance attribute and not a method + def write(self, text: str | bytes) -> int: ... + def writelines(self, seq: Sequence[str | bytes]) -> None: ... + def flush(self) -> None: ... + def tell(self) -> int: ... + +class AppIterRange: + app_iter: Iterator[bytes] + start: int + stop: int | None + def __init__(self, app_iter: Iterable[bytes], start: int, stop: int | None) -> None: ... + def __iter__(self) -> Self: ... + def next(self) -> bytes: ... + __next__ = next + def close(self) -> None: ... + +class EmptyResponse: + def __init__(self, app_iter: Iterable[bytes] | None = None) -> None: ... + def __iter__(self) -> Self: ... + def __len__(self) -> Literal[0]: ... + def next(self) -> bytes: ... + __next__ = next diff --git a/stubs/WebOb/webob/static.pyi b/stubs/WebOb/webob/static.pyi new file mode 100644 index 000000000000..c74664103a5b --- /dev/null +++ b/stubs/WebOb/webob/static.pyi @@ -0,0 +1,40 @@ +from _typeshed import StrPath +from _typeshed.wsgi import WSGIApplication +from collections.abc import Iterator +from typing import IO, Any + +from webob.dec import wsgify +from webob.request import Request +from webob.response import Response + +__all__ = ["FileApp", "DirectoryApp"] + +BLOCK_SIZE: int + +class FileApp: + filename: StrPath + kw: dict[str, Any] + def __init__(self, filename: StrPath, **kw: Any) -> None: ... + @wsgify + def __call__(self, req: Request) -> WSGIApplication: ... + +class FileIter: + file: IO[bytes] + def __init__(self, file: IO[bytes]) -> None: ... + def app_iter_range( + self, seek: int | None = None, limit: int | None = None, block_size: int | None = None + ) -> Iterator[bytes]: ... + __iter__ = app_iter_range + +class DirectoryApp: + path: StrPath + index_page: str + hide_index_with_redirect: bool + fileapp_kw: dict[str, Any] + def __init__( + self, path: StrPath, index_page: str = "index.html", hide_index_with_redirect: bool = False, **kw: Any + ) -> None: ... + def make_fileapp(self, path: StrPath) -> FileApp: ... + @wsgify + def __call__(self, req: Request) -> Response | FileApp: ... + def index(self, req: Request, path: StrPath) -> Response | FileApp: ... diff --git a/stubs/WebOb/webob/util.pyi b/stubs/WebOb/webob/util.pyi new file mode 100644 index 000000000000..0c1c015c23bc --- /dev/null +++ b/stubs/WebOb/webob/util.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable +from typing import AnyStr + +def html_escape(s: object) -> str: ... +def urljoin(base: str, url: str | None) -> str: ... +def header_docstring(header: str, rfc_section: str) -> str: ... +def warn_deprecation(text: str, version: str, stacklevel: int) -> None: ... + +status_reasons: dict[int, str] +status_generic_reasons: dict[int, str] + +def strings_differ(string1: AnyStr, string2: AnyStr, compare_digest: Callable[[AnyStr, AnyStr], bool] = ...) -> bool: ... diff --git a/stubs/WebTest/@tests/stubtest_allowlist.txt b/stubs/WebTest/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..57f2ad0779b7 --- /dev/null +++ b/stubs/WebTest/@tests/stubtest_allowlist.txt @@ -0,0 +1,19 @@ +# error: failed to find stub +# ========================== +# These modules have been migrated to external packages +# and emit an `ImportError` if people try to use the +# functions/classes defined within +webtest.ext +webtest.sel +# Compatibility/utility modules for internal use that didn't +# seem worth including in the stubs +webtest.compat +webtest.lint +webtest.utils + +# error: variable differs from runtime type +# ========================================= +# Even though this can be `None`, it never should be during +# normal use of WebTest, so it seems more pragmatic to treat +# it as always non-`None` +webtest.response.TestResponse.request diff --git a/stubs/WebTest/METADATA.toml b/stubs/WebTest/METADATA.toml new file mode 100644 index 000000000000..0c917c5cbc93 --- /dev/null +++ b/stubs/WebTest/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.0.*" +upstream-repository = "https://github.com/Pylons/webtest" +dependencies = ["beautifulsoup4", "types-waitress", "types-WebOb"] diff --git a/stubs/WebTest/webtest/__init__.pyi b/stubs/WebTest/webtest/__init__.pyi new file mode 100644 index 000000000000..bad803e222dd --- /dev/null +++ b/stubs/WebTest/webtest/__init__.pyi @@ -0,0 +1,14 @@ +from webtest.app import AppError as AppError, TestApp as TestApp, TestRequest as TestRequest +from webtest.forms import ( + Checkbox as Checkbox, + Field as Field, + Form as Form, + Hidden as Hidden, + Radio as Radio, + Select as Select, + Submit as Submit, + Text as Text, + Textarea as Textarea, + Upload as Upload, +) +from webtest.response import TestResponse as TestResponse diff --git a/stubs/WebTest/webtest/app.pyi b/stubs/WebTest/webtest/app.pyi new file mode 100644 index 000000000000..0d43cc9ff633 --- /dev/null +++ b/stubs/WebTest/webtest/app.pyi @@ -0,0 +1,206 @@ +import json +from _typeshed import SupportsItems, SupportsKeysAndGetItem +from _typeshed.wsgi import WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Sequence +from http.cookiejar import CookieJar, DefaultCookiePolicy +from typing import Any, Generic, Literal, TypeAlias, TypeVar + +from webob.request import BaseRequest +from webtest.forms import File, Upload +from webtest.response import TestResponse + +# NOTE: While it is possible to pass different kinds of values depending on +# the exact configuration of the request, it seems more robust to +# restrict them to the types that are supported by all code paths. +# I don't expect anyone to try to pass different kinds of values +# in a non-JSON request. +_ParamValue: TypeAlias = File | Upload | int | bytes | str +_Params: TypeAlias = SupportsItems[str | bytes, _ParamValue] | Sequence[tuple[str | bytes, _ParamValue]] +# NOTE: Using `Collection` rather than `Iterable` would probably be slightly +# safer since WebTest will check this parameter for truthyness. But since +# objects are truthy by default, this should only lead to issues in truly +# exotic cases. +_ExtraEnviron: TypeAlias = SupportsKeysAndGetItem[str, Any] | Iterable[tuple[str, Any]] +_Files: TypeAlias = Sequence[tuple[str, str] | tuple[str, str, bytes]] +_AppT = TypeVar("_AppT", bound=WSGIApplication, default=WSGIApplication) + +__all__ = ["TestApp", "TestRequest"] + +class AppError(Exception): + def __init__(self, message: str, *args: object) -> None: ... + +class CookiePolicy(DefaultCookiePolicy): ... + +class TestRequest(BaseRequest): + ResponseClass: type[TestResponse] + __test__: Literal[False] + +class TestApp(Generic[_AppT]): + RequestClass: type[TestRequest] + app: _AppT + lint: bool + relative_to: str | None + extra_environ: WSGIEnvironment + use_unicode: bool + cookiejar: CookieJar + JSONEncoder: json.JSONEncoder + __test__: Literal[False] + def __init__( + self, + app: _AppT, + # NOTE: this extra_environ is different from the others and needs to + # support __delitem__, it seems easiest to just treat this like + # a regular WSGIEnvironment. The docs also say that this should + # be a dictionary. + extra_environ: WSGIEnvironment | None = None, + relative_to: str | None = None, + use_unicode: bool = True, + cookiejar: CookieJar | None = None, + parser_features: Sequence[str] | str | None = None, + json_encoder: json.JSONEncoder | None = None, + lint: bool = True, + ) -> None: ... + def get_authorization(self) -> tuple[str, str | tuple[str, str]]: ... + def set_authorization(self, value: tuple[str, str | tuple[str, str]]) -> None: ... + + @property + def authorization(self) -> tuple[str, str | tuple[str, str]]: ... + @authorization.setter + def authorization(self, value: tuple[str, str | tuple[str, str]]) -> None: ... + + @property + def cookies(self) -> dict[str, str | None]: ... + def set_cookie(self, name: str, value: str | None) -> None: ... + def reset(self) -> None: ... + def set_parser_features(self, parser_features: Sequence[str] | str) -> None: ... + def get( + self, + url: str, + params: _Params | str | None = None, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + xhr: bool = False, + ) -> TestResponse: ... + def post( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + upload_files: _Files | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def put( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + upload_files: _Files | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def patch( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + upload_files: _Files | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def delete( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def options( + self, + url: str, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + xhr: bool = False, + ) -> TestResponse: ... + def head( + self, + url: str, + params: _Params | str | None = None, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + xhr: bool = False, + ) -> TestResponse: ... + def post_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def put_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def patch_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def delete_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def encode_multipart(self, params: Iterable[tuple[str | bytes, _ParamValue]], files: _Files) -> tuple[str, bytes]: ... + def request( + self, url_or_req: str | TestRequest, status: int | str | None = None, expect_errors: bool = False, **req_params: Any + ) -> TestResponse: ... + def do_request( + self, req: TestRequest, status: int | str | None = None, expect_errors: bool | None = None + ) -> TestResponse: ... diff --git a/stubs/WebTest/webtest/debugapp.pyi b/stubs/WebTest/webtest/debugapp.pyi new file mode 100644 index 000000000000..ea633f9c8346 --- /dev/null +++ b/stubs/WebTest/webtest/debugapp.pyi @@ -0,0 +1,22 @@ +from _typeshed import StrOrBytesPath +from _typeshed.wsgi import StartResponse, WSGIEnvironment +from collections.abc import Iterable +from typing import TypedDict, type_check_only +from typing_extensions import Unpack + +@type_check_only +class _DebugAppParams(TypedDict, total=False): + form: StrOrBytesPath | bytes | None + show_form: bool + +__all__ = ["DebugApp", "make_debug_app"] + +class DebugApp: + form: bytes | None + show_form: bool + def __init__(self, form: StrOrBytesPath | bytes | None = None, show_form: bool = False) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +debug_app: DebugApp + +def make_debug_app(global_conf: object, **local_conf: Unpack[_DebugAppParams]) -> DebugApp: ... diff --git a/stubs/WebTest/webtest/forms.pyi b/stubs/WebTest/webtest/forms.pyi new file mode 100644 index 000000000000..695b943d7fb1 --- /dev/null +++ b/stubs/WebTest/webtest/forms.pyi @@ -0,0 +1,191 @@ +from collections.abc import Collection, Generator, Iterable, Sequence +from typing import Any, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +from bs4 import BeautifulSoup +from webtest.response import TestResponse + +_T = TypeVar("_T") + +@type_check_only +class _Classes(TypedDict): + submit: type[Submit] + button: type[Submit] + image: type[Submit] + multiple_select: type[MultipleSelect] + select: type[Select] + hidden: type[Hidden] + file: type[File] + text: type[Text] + search: type[Text] + email: type[Email] + password: type[Text] + checkbox: type[Checkbox] + textarea: type[Textarea] + radio: type[Radio] + +# NOTE: It seems unergonomic having to put isinstance checks everywhere +# in your test code where you're accessing a form field, so we +# return `Any` for now. What we would really like to use here is +# `AnyOf`, but that doesn't exist yet. +_AnyField: TypeAlias = Any + +class NoValue: ... + +class Upload: + filename: str + content: bytes | None + content_type: str | None + def __init__(self, filename: str, content: bytes | None = None, content_type: str | None = None) -> None: ... + def __iter__(self) -> Generator[str | bytes]: ... + +class Field: + classes: _Classes + form: Form + tag: str + name: str + pos: int + id: str + attrs: dict[str, str] + def __init__( + self, form: Form, tag: str, name: str, pos: int, value: str | None = None, id: str | None = None, **attrs: str + ) -> None: ... + def value__get(self) -> str: ... + def value__set(self, value: str | None) -> None: ... + + @property + def value(self) -> str: ... + @value.setter + def value(self, value: str | None) -> None: ... + + def force_value(self, value: str | None) -> None: ... + +class Select(Field): + options: list[tuple[str, bool, str]] + optionPositions: list[int] + selectedIndex: int | None + + # NOTE: Even though it's safe to pass any object into text, I don't + # think that follows the spirit of this argument and is more + # likely a consequence of reusing the same utility function + # in order to handle bytes for Py2 compat. + @overload + def select(self, value: None, text: str | bytes) -> None: ... + @overload + def select(self, value: None = None, *, text: str | bytes) -> None: ... + @overload + def select(self, value: object, text: None = None) -> None: ... + + def value__get(self) -> str: ... + def value__set(self, value: object | None) -> None: ... + + @property + def value(self) -> str: ... + @value.setter + def value(self, value: object | None) -> None: ... + +class MultipleSelect(Field): + options: list[tuple[str, bool, str]] + selectedIndices: list[int] + + @overload + def select_multiple(self, value: None, texts: Iterable[str | bytes]) -> None: ... + @overload + def select_multiple(self, value: None = None, *, texts: Iterable[str | bytes]) -> None: ... + @overload + def select_multiple(self, value: Collection[object], texts: None = None) -> None: ... + + def value__get(self) -> list[str] | None: ... # type: ignore[override] + def value__set(self, values: Collection[object] | None) -> None: ... + + @property # type: ignore[override] + def value(self) -> list[str] | None: ... + @value.setter + def value(self, value: Collection[object] | None) -> None: ... + + # NOTE: Since unlike setting the value normally this doesn't perform + # any kind of type conversion, we're better off only allowing + # what `value__get` is supposed to be able to return. + def force_value(self, values: list[str] | None) -> None: ... # type: ignore[override] + +class Radio(Select): ... + +class Checkbox(Field): + def value__get(self) -> str | None: ... # type: ignore[override] + def value__set(self, value: object) -> None: ... + + @property # type: ignore[override] + def value(self) -> str | None: ... + @value.setter + def value(self, value: object) -> None: ... + + def checked__get(self) -> bool: ... + def checked__set(self, value: object) -> None: ... + + @property + def checked(self) -> bool: ... + @checked.setter + def checked(self, value: object) -> None: ... + +class Text(Field): ... +class Email(Field): ... +class File(Field): ... +class Textarea(Text): ... +class Hidden(Text): ... + +class Submit(Field): + def value__get(self) -> None: ... # type: ignore[override] + @property # type: ignore[misc] + def value(self) -> None: ... # type: ignore[override] + def value_if_submitted(self) -> str: ... + +class Form: + FieldClass: type[Field] + response: TestResponse + text: str + html: BeautifulSoup + action: str + method: str + id: str | None + enctype: str + field_order: list[tuple[str, Field]] + fields: dict[str, list[Field]] + def __init__(self, response: TestResponse, text: str, parser_features: Sequence[str] | str = "html.parser") -> None: ... + # NOTE: Technically it is only safe to pass `str | None` for most fields + # but this method is not really usable if we don't lift this + # restriction, we just have to assume people know what they + # are doing + def __setitem__(self, name: str, value: Any | None) -> None: ... + def set(self, name: str, value: Any | None, index: int | None = None) -> None: ... + def __getitem__(self, name: str) -> _AnyField: ... + + @overload + def get(self, name: str, index: int | None = None) -> _AnyField: ... + @overload + def get(self, name: str, index: int | None, default: _T) -> _AnyField | _T: ... + @overload + def get(self, name: str, index: int | None = None, *, default: _T) -> _AnyField | _T: ... + + @overload + def select(self, name: str, value: None, text: str | bytes, index: int | None = None) -> None: ... + @overload + def select(self, name: str, value: None = None, *, text: str | bytes, index: int | None = None) -> None: ... + @overload + def select(self, name: str, value: object, text: None = None, index: int | None = None) -> None: ... + + @overload + def select_multiple(self, name: str, value: None, texts: Iterable[str | bytes], index: int | None = None) -> None: ... + @overload + def select_multiple( + self, name: str, value: None = None, *, texts: Iterable[str | bytes], index: int | None = None + ) -> None: ... + @overload + def select_multiple(self, name: str, value: Iterable[object], texts: None = None, index: int | None = None) -> None: ... + + def submit( + self, name: str | None = None, index: int | None = None, value: str | None = None, **args: Any + ) -> TestResponse: ... + def lint(self) -> None: ... + def upload_fields(self) -> list[tuple[str, str] | tuple[str, str, bytes]]: ... + def submit_fields( + self, name: str | None = None, index: int | None = None, submit_value: str | None = None + ) -> list[tuple[str, str]]: ... diff --git a/stubs/WebTest/webtest/http.pyi b/stubs/WebTest/webtest/http.pyi new file mode 100644 index 000000000000..8c0e3314db38 --- /dev/null +++ b/stubs/WebTest/webtest/http.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from threading import Thread +from typing import Literal, TypeAlias +from typing_extensions import Self + +from waitress.server import TcpWSGIServer + +# NOTE: We may never really be able to complete this, since `create` +# invokes `cls.__init__` which is exempt from LSP violations +# unless we get something like `KwArgsOf[cls.__init__]`. +_WSGIServerParams: TypeAlias = Incomplete + +def get_free_port() -> tuple[str, int]: ... +def check_server(host: str, port: int, path_info: str = "/", timeout: float = 3, retries: int = 30) -> int: ... + +class StopableWSGIServer(TcpWSGIServer): + was_shutdown: bool + runner: Thread + test_app: WSGIApplication + application_url: str + def wrapper(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def run(self) -> None: ... + def shutdown(self, debug: bool = False) -> Literal[True]: ... + # NOTE: This has the same keyword arguments as cls.__init__, which + # we can't express + @classmethod + def create(cls, application: WSGIApplication, **kwargs: _WSGIServerParams) -> Self: ... + def wait(self, retries: int = 30) -> bool: ... diff --git a/stubs/WebTest/webtest/response.pyi b/stubs/WebTest/webtest/response.pyi new file mode 100644 index 000000000000..b6d67b2344c0 --- /dev/null +++ b/stubs/WebTest/webtest/response.pyi @@ -0,0 +1,93 @@ +import re +from _typeshed.wsgi import WSGIApplication +from collections.abc import Callable, Mapping, Sequence +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Unpack +from xml.etree import ElementTree + +from bs4 import BeautifulSoup +from webob import Response +from webtest.app import TestApp, TestRequest, _Files +from webtest.forms import Form + +_Pattern: TypeAlias = str | bytes | re.Pattern[str] | Callable[[str], bool] +# NOTE: These are optional dependencies, so we don't want to depend on them +# in the stubs either. Also there are no stubs for pyquery anyways. +_PyQuery: TypeAlias = Any +_PyQueryParams: TypeAlias = Any +_LxmlElement: TypeAlias = Any + +@type_check_only +class _GetParams(TypedDict, total=False): + params: Mapping[str, str] | str + headers: Mapping[str, str] + extra_environ: Mapping[str, Any] + status: int | str | None + expect_errors: bool + xhr: bool + +@type_check_only +class _PostParams(_GetParams, total=False): + upload_files: _Files + content_type: str + +class TestResponse(Response): + # NOTE: The way WebTest creates responses the request is always set + # we could've used `MaybeNone`, but it seems more pragmatic + # to just assume that this is always set. + request: TestRequest # type: ignore[assignment] + app: WSGIApplication + test_app: TestApp + parser_features: str | Sequence[str] + __test__: Literal[False] + @property + def forms(self) -> dict[str | int, Form]: ... + @property + def form(self) -> Form: ... + @property + def testbody(self) -> str: ... + def follow(self, **kw: Unpack[_GetParams]) -> TestResponse: ... + def maybe_follow(self, **kw: Unpack[_GetParams]) -> TestResponse: ... + def click( + self, + description: _Pattern | None = None, + linkid: _Pattern | None = None, + href: _Pattern | None = None, + index: int | None = None, + verbose: bool = False, + extra_environ: dict[str, Any] | None = None, + ) -> TestResponse: ... + def clickbutton( + self, + description: _Pattern | None = None, + buttonid: _Pattern | None = None, + href: _Pattern | None = None, + onclick: str | None = None, + index: int | None = None, + verbose: bool = False, + ) -> TestResponse: ... + + @overload + def goto(self, href: str, method: Literal["get"] = "get", **args: Unpack[_GetParams]) -> TestResponse: ... + @overload + def goto(self, href: str, method: Literal["post"], **args: Unpack[_PostParams]) -> TestResponse: ... + + @property + def normal_body(self) -> bytes: ... + @property + def unicode_normal_body(self) -> str: ... + def __contains__(self, s: str) -> bool: ... + def mustcontain(self, *strings: str, no: Sequence[str] | str = ...) -> None: ... + @property + def html(self) -> BeautifulSoup: ... + @property + def xml(self) -> ElementTree.Element: ... + @property + def lxml(self) -> _LxmlElement: ... + @property + def json(self) -> Any: ... + @property + def pyquery(self) -> _PyQuery: ... + def PyQuery(self, **kwargs: _PyQueryParams) -> _PyQuery: ... + def showbrowser(self) -> None: ... + def __str__(self) -> str: ... # type: ignore[override] # noqa: Y029 diff --git a/stubs/aiofiles/@tests/stubtest_allowlist.txt b/stubs/aiofiles/@tests/stubtest_allowlist.txt index 0a5668c9a238..6562daed8456 100644 --- a/stubs/aiofiles/@tests/stubtest_allowlist.txt +++ b/stubs/aiofiles/@tests/stubtest_allowlist.txt @@ -1,3 +1,5 @@ +# These all delegate using *args,**kwargs, but stubs use signature of +# method they are being delegated to. aiofiles.threadpool.binary.AsyncBufferedIOBase.close aiofiles.threadpool.binary.AsyncBufferedIOBase.detach aiofiles.threadpool.binary.AsyncBufferedIOBase.fileno @@ -7,6 +9,15 @@ aiofiles.threadpool.binary.AsyncBufferedIOBase.readable aiofiles.threadpool.binary.AsyncBufferedIOBase.seekable aiofiles.threadpool.binary.AsyncBufferedIOBase.tell aiofiles.threadpool.binary.AsyncBufferedIOBase.writable +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.close +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.detach +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.fileno +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.flush +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.isatty +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.readable +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.seekable +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.tell +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.writable aiofiles.threadpool.binary.AsyncFileIO.close aiofiles.threadpool.binary.AsyncFileIO.fileno aiofiles.threadpool.binary.AsyncFileIO.flush @@ -16,6 +27,15 @@ aiofiles.threadpool.binary.AsyncFileIO.readall aiofiles.threadpool.binary.AsyncFileIO.seekable aiofiles.threadpool.binary.AsyncFileIO.tell aiofiles.threadpool.binary.AsyncFileIO.writable +aiofiles.threadpool.binary.AsyncIndirectFileIO.close +aiofiles.threadpool.binary.AsyncIndirectFileIO.fileno +aiofiles.threadpool.binary.AsyncIndirectFileIO.flush +aiofiles.threadpool.binary.AsyncIndirectFileIO.isatty +aiofiles.threadpool.binary.AsyncIndirectFileIO.readable +aiofiles.threadpool.binary.AsyncIndirectFileIO.readall +aiofiles.threadpool.binary.AsyncIndirectFileIO.seekable +aiofiles.threadpool.binary.AsyncIndirectFileIO.tell +aiofiles.threadpool.binary.AsyncIndirectFileIO.writable aiofiles.threadpool.text.AsyncTextIOWrapper.close aiofiles.threadpool.text.AsyncTextIOWrapper.detach aiofiles.threadpool.text.AsyncTextIOWrapper.fileno @@ -25,3 +45,47 @@ aiofiles.threadpool.text.AsyncTextIOWrapper.readable aiofiles.threadpool.text.AsyncTextIOWrapper.seekable aiofiles.threadpool.text.AsyncTextIOWrapper.tell aiofiles.threadpool.text.AsyncTextIOWrapper.writable +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.close +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.detach +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.fileno +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.flush +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.isatty +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.readable +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.seekable +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.tell +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.writable + +# These functions get the wrong signature from functools.wraps() +aiofiles.os.stat +aiofiles.os.rename +aiofiles.os.renames +aiofiles.os.replace +aiofiles.os.remove +aiofiles.os.unlink +aiofiles.os.mkdir +aiofiles.os.makedirs +aiofiles.os.link +aiofiles.os.symlink +aiofiles.os.readlink +aiofiles.os.rmdir +aiofiles.os.removedirs +aiofiles.os.scandir +aiofiles.os.listdir +aiofiles.ospath.exists +aiofiles.ospath.isfile +aiofiles.ospath.isdir +aiofiles.ospath.getsize +aiofiles.ospath.getmtime +aiofiles.ospath.getatime +aiofiles.ospath.getctime +aiofiles.ospath.samefile +aiofiles.ospath.sameopenfile + +# Same issues as above +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.close +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.fileno +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.flush +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.isatty +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.rollover +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.tell +aiofiles.tempfile.temptypes.AsyncTemporaryDirectory.cleanup diff --git a/stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt b/stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..b0ea37bd4388 --- /dev/null +++ b/stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# This function gets the wrong signature from functools.wraps() +aiofiles.os.sendfile diff --git a/stubs/aiofiles/@tests/stubtest_allowlist_linux.txt b/stubs/aiofiles/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..b0ea37bd4388 --- /dev/null +++ b/stubs/aiofiles/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# This function gets the wrong signature from functools.wraps() +aiofiles.os.sendfile diff --git a/stubs/aiofiles/METADATA.toml b/stubs/aiofiles/METADATA.toml index 6b8eeefb1769..c990b4bf835f 100644 --- a/stubs/aiofiles/METADATA.toml +++ b/stubs/aiofiles/METADATA.toml @@ -1,2 +1,6 @@ -version = "0.7.*" -requires = [] +version = "25.1.*" +upstream-repository = "https://github.com/Tinche/aiofiles" + +[tool.stubtest] +# linux and darwin are equivalent +ci-platforms = ["linux", "win32"] diff --git a/stubs/aiofiles/aiofiles/__init__.pyi b/stubs/aiofiles/aiofiles/__init__.pyi index 2bbbc29a428f..64410d4ed529 100644 --- a/stubs/aiofiles/aiofiles/__init__.pyi +++ b/stubs/aiofiles/aiofiles/__init__.pyi @@ -1 +1,12 @@ -from .threadpool import open as open +from . import tempfile as tempfile +from .threadpool import ( + open as open, + stderr as stderr, + stderr_bytes as stderr_bytes, + stdin as stdin, + stdin_bytes as stdin_bytes, + stdout as stdout, + stdout_bytes as stdout_bytes, +) + +__all__ = ["open", "tempfile", "stdin", "stdout", "stderr", "stdin_bytes", "stdout_bytes", "stderr_bytes"] diff --git a/stubs/aiofiles/aiofiles/base.pyi b/stubs/aiofiles/aiofiles/base.pyi index 3859bc5ce660..5723a95d6307 100644 --- a/stubs/aiofiles/aiofiles/base.pyi +++ b/stubs/aiofiles/aiofiles/base.pyi @@ -1,34 +1,31 @@ -from _typeshed import Self -from types import CodeType, FrameType, TracebackType, coroutine -from typing import Any, Coroutine, Generator, Generic, Iterator, Type, TypeVar +from asyncio.events import AbstractEventLoop +from collections.abc import Awaitable, Callable, Generator +from concurrent.futures import Executor +from contextlib import AbstractAsyncContextManager +from types import TracebackType +from typing import Any, BinaryIO, Generic, TextIO, TypeVar +from typing_extensions import Self _T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) _V_co = TypeVar("_V_co", covariant=True) -_T_contra = TypeVar("_T_contra", contravariant=True) + +def wrap(func: Callable[..., _T]) -> Callable[..., Awaitable[_T]]: ... class AsyncBase(Generic[_T]): - def __init__(self, file: str, loop: Any, executor: Any) -> None: ... - def __aiter__(self: Self) -> Self: ... + def __init__(self, file: TextIO | BinaryIO | None, loop: AbstractEventLoop | None, executor: Executor | None) -> None: ... + def __aiter__(self) -> Self: ... async def __anext__(self) -> _T: ... -class AiofilesContextManager(Generic[_T_co, _T_contra, _V_co]): - def __init__(self, coro: Coroutine[_T_co, _T_contra, _V_co]) -> None: ... - def send(self, value: _T_contra) -> _T_co: ... - def throw(self, typ: Type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ...) -> _T_co: ... - def close(self) -> None: ... - @property - def gi_frame(self) -> FrameType: ... - @property - def gi_running(self) -> bool: ... - @property - def gi_code(self) -> CodeType: ... - def __next__(self) -> _T_co: ... - @coroutine - def __iter__(self) -> Iterator[Coroutine[_T_co, _T_contra, _V_co]]: ... - def __await__(self) -> Generator[Any, None, _V_co]: ... - async def __anext__(self) -> _V_co: ... +class AsyncIndirectBase(AsyncBase[_T]): + def __init__( + self, name: str, loop: AbstractEventLoop | None, executor: Executor | None, indirect: Callable[[], TextIO | BinaryIO] + ) -> None: ... + +class AiofilesContextManager(Awaitable[_V_co], AbstractAsyncContextManager[_V_co]): + __slots__ = ("_coro", "_obj") + def __init__(self, coro: Awaitable[_V_co]) -> None: ... + def __await__(self) -> Generator[Any, Any, _V_co]: ... async def __aenter__(self) -> _V_co: ... async def __aexit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... diff --git a/stubs/aiofiles/aiofiles/os.pyi b/stubs/aiofiles/aiofiles/os.pyi index b48884c4430e..506a0f2851bd 100644 --- a/stubs/aiofiles/aiofiles/os.pyi +++ b/stubs/aiofiles/aiofiles/os.pyi @@ -1,28 +1,171 @@ import sys -from _typeshed import StrOrBytesPath -from os import stat_result -from typing import Sequence, Union, overload +from _typeshed import BytesPath, FileDescriptorOrPath, GenericPath, ReadableBuffer, StrOrBytesPath, StrPath +from asyncio.events import AbstractEventLoop +from collections.abc import Sequence +from concurrent.futures import Executor +from os import _ScandirIterator, stat_result +from typing import AnyStr, overload -_FdOrAnyPath = Union[int, StrOrBytesPath] +from aiofiles import ospath +from aiofiles.base import wrap as wrap -async def stat(path: _FdOrAnyPath, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> stat_result: ... +__all__ = [ + "path", + "stat", + "rename", + "renames", + "replace", + "remove", + "unlink", + "mkdir", + "makedirs", + "rmdir", + "removedirs", + "link", + "symlink", + "readlink", + "listdir", + "scandir", + "access", + "wrap", + "getcwd", +] + +if sys.platform != "win32": + __all__ += ["statvfs", "sendfile"] + +path = ospath + +async def stat( + path: FileDescriptorOrPath, + *, + dir_fd: int | None = None, + follow_symlinks: bool = True, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> stat_result: ... async def rename( - src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = ..., dst_dir_fd: int | None = ... + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def renames( + old: StrOrBytesPath, new: StrOrBytesPath, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def replace( + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def remove( + path: StrOrBytesPath, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def unlink( + path: StrOrBytesPath, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def mkdir( + path: StrOrBytesPath, + mode: int = 511, + *, + dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def makedirs( + name: StrOrBytesPath, + mode: int = 511, + exist_ok: bool = False, + *, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def link( + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + follow_symlinks: bool = True, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., ) -> None: ... -async def remove(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... -async def mkdir(path: StrOrBytesPath, mode: int = ..., *, dir_fd: int | None = ...) -> None: ... -async def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... +async def symlink( + src: StrOrBytesPath, + dst: StrOrBytesPath, + target_is_directory: bool = False, + *, + dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def readlink( + path: AnyStr, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> AnyStr: ... +async def rmdir( + path: StrOrBytesPath, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def removedirs(name: StrOrBytesPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> None: ... + +@overload +async def scandir( + path: None = None, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> _ScandirIterator[str]: ... +@overload +async def scandir( + path: int, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> _ScandirIterator[str]: ... +@overload +async def scandir( + path: GenericPath[AnyStr], *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> _ScandirIterator[AnyStr]: ... + +@overload +async def listdir( + path: StrPath | None, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> list[str]: ... +@overload +async def listdir(path: BytesPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> list[bytes]: ... +@overload +async def listdir(path: int, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> list[str]: ... + +async def access( + path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True +) -> bool: ... +async def getcwd() -> str: ... if sys.platform != "win32": + from os import statvfs_result + @overload - async def sendfile(__out_fd: int, __in_fd: int, offset: int | None, count: int) -> int: ... + async def sendfile( + out_fd: int, + in_fd: int, + offset: int | None, + count: int, + *, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., + ) -> int: ... @overload async def sendfile( - __out_fd: int, - __in_fd: int, + out_fd: int, + in_fd: int, offset: int, count: int, - headers: Sequence[bytes] = ..., - trailers: Sequence[bytes] = ..., - flags: int = ..., - ) -> int: ... + headers: Sequence[ReadableBuffer] = (), + trailers: Sequence[ReadableBuffer] = (), + flags: int = 0, + *, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., + ) -> int: ... # FreeBSD and Mac OS X only + + async def statvfs(path: FileDescriptorOrPath) -> statvfs_result: ... # Unix only diff --git a/stubs/aiofiles/aiofiles/ospath.pyi b/stubs/aiofiles/aiofiles/ospath.pyi new file mode 100644 index 000000000000..2ef19d974489 --- /dev/null +++ b/stubs/aiofiles/aiofiles/ospath.pyi @@ -0,0 +1,47 @@ +from _typeshed import FileDescriptorOrPath +from asyncio.events import AbstractEventLoop +from concurrent.futures import Executor +from os import PathLike +from typing import AnyStr + +__all__ = [ + "abspath", + "getatime", + "getctime", + "getmtime", + "getsize", + "exists", + "isdir", + "isfile", + "islink", + "ismount", + "samefile", + "sameopenfile", +] + +async def exists( + path: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> bool: ... +async def isfile( + path: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> bool: ... +async def isdir(s: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> bool: ... +async def islink(path: FileDescriptorOrPath) -> bool: ... +async def ismount(path: FileDescriptorOrPath) -> bool: ... +async def getsize( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> int: ... +async def getmtime( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> float: ... +async def getatime( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> float: ... +async def getctime( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> float: ... +async def samefile( + f1: FileDescriptorOrPath, f2: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> bool: ... +async def sameopenfile(fp1: int, fp2: int, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> bool: ... +async def abspath(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ... diff --git a/stubs/aiofiles/aiofiles/tempfile/__init__.pyi b/stubs/aiofiles/aiofiles/tempfile/__init__.pyi new file mode 100644 index 000000000000..b9806ecd636e --- /dev/null +++ b/stubs/aiofiles/aiofiles/tempfile/__init__.pyi @@ -0,0 +1,324 @@ +import sys +from _typeshed import ( + BytesPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + StrOrBytesPath, + StrPath, +) +from asyncio import AbstractEventLoop +from concurrent.futures import Executor +from typing import AnyStr, Literal, overload + +from ..base import AiofilesContextManager +from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO +from ..threadpool.text import AsyncTextIOWrapper + +# Text mode: always returns AsyncTextIOWrapper +@overload +def TemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + +# Unbuffered binary: returns a FileIO +@overload +def TemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... + +# Buffered binary reading/updating: AsyncBufferedReader +@overload +def TemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedReader]: ... + +# Buffered binary writing: AsyncBufferedIOBase +@overload +def TemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +# 3.12 added `delete_on_close` +if sys.version_info >= (3, 12): + # Text mode: always returns AsyncTextIOWrapper + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + + # Unbuffered binary: returns a FileIO + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncFileIO]: ... + + # Buffered binary reading/updating: AsyncBufferedReader + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedReader]: ... + + # Buffered binary writing: AsyncBufferedIOBase + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedIOBase]: ... +else: + # Text mode: always returns AsyncTextIOWrapper + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + + # Unbuffered binary: returns a FileIO + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncFileIO]: ... + + # Buffered binary reading/updating: AsyncBufferedReader + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedReader]: ... + + # Buffered binary writing: AsyncBufferedIOBase + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +# Text mode: always returns AsyncTextIOWrapper +@overload +def SpooledTemporaryFile( + max_size: int = 0, + *, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... +@overload +def SpooledTemporaryFile( + max_size: int, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + +# Unbuffered binary: returns a FileIO +@overload +def SpooledTemporaryFile( + max_size: int = 0, + mode: OpenBinaryMode = "w+b", + *, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... +@overload +def SpooledTemporaryFile( + max_size: int, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... + +# Buffered binary reading/updating: AsyncBufferedReader +@overload +def SpooledTemporaryFile( + max_size: int = 0, + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedReader]: ... + +# Buffered binary writing: AsyncBufferedIOBase +@overload +def SpooledTemporaryFile( + max_size: int = 0, + *, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... +@overload +def SpooledTemporaryFile( + max_size: int, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +@overload +def TemporaryDirectory( + suffix: str | None = None, + prefix: str | None = None, + dir: StrPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManagerTempDir: ... +@overload +def TemporaryDirectory( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: BytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManagerTempDir: ... + +class AiofilesContextManagerTempDir(AiofilesContextManager[str]): + async def __aenter__(self) -> str: ... + +__all__ = ["NamedTemporaryFile", "TemporaryFile", "SpooledTemporaryFile", "TemporaryDirectory"] diff --git a/stubs/aiofiles/aiofiles/tempfile/temptypes.pyi b/stubs/aiofiles/aiofiles/tempfile/temptypes.pyi new file mode 100644 index 000000000000..b6f05e13c7ce --- /dev/null +++ b/stubs/aiofiles/aiofiles/tempfile/temptypes.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete, OpenBinaryMode, ReadableBuffer +from asyncio import AbstractEventLoop +from collections.abc import Generator, Iterable +from concurrent.futures import Executor +from tempfile import TemporaryDirectory +from typing import TypeVar + +from aiofiles.base import AsyncBase as AsyncBase +from aiofiles.threadpool.utils import ( + cond_delegate_to_executor as cond_delegate_to_executor, + delegate_to_executor as delegate_to_executor, + proxy_property_directly as proxy_property_directly, +) + +_T = TypeVar("_T") + +class AsyncSpooledTemporaryFile(AsyncBase[_T]): + def fileno(self) -> Generator[Incomplete]: ... + def rollover(self) -> Generator[Incomplete]: ... + async def close(self) -> None: ... + async def flush(self) -> None: ... + async def isatty(self) -> bool: ... + async def read(self, n: int = ..., /) -> str | bytes: ... + async def readline(self, limit: int | None = ..., /) -> str | bytes: ... + async def readlines(self, hint: int = ..., /) -> list[str | bytes]: ... + async def seek(self, offset: int, whence: int = ...) -> int: ... + async def tell(self) -> int: ... + async def truncate(self, size: int | None = ...) -> None: ... + @property + def closed(self) -> bool: ... + @property + def encoding(self) -> str: ... + @property + def mode(self) -> OpenBinaryMode: ... + @property + def name(self) -> str | bytes: ... + @property + def newlines(self) -> str: ... + async def write(self, s: str | bytes | ReadableBuffer) -> int: ... + async def writelines(self, iterable: Iterable[str | bytes | ReadableBuffer]) -> None: ... + +class AsyncTemporaryDirectory: + async def cleanup(self) -> None: ... + @property + def name(self) -> str | bytes: ... + def __init__( + self, file: TemporaryDirectory[Incomplete], loop: AbstractEventLoop | None, executor: Executor | None + ) -> None: ... + async def close(self) -> None: ... diff --git a/stubs/aiofiles/aiofiles/threadpool/__init__.pyi b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi index a43b5ab0defb..bd2aea070627 100644 --- a/stubs/aiofiles/aiofiles/threadpool/__init__.pyi +++ b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi @@ -1,98 +1,110 @@ from _typeshed import ( + FileDescriptorOrPath, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, - StrOrBytesPath, ) from asyncio import AbstractEventLoop -from typing import Any, Callable, Union, overload -from typing_extensions import Literal +from collections.abc import Callable +from concurrent.futures import Executor +from functools import _SingleDispatchCallable +from typing import Any, Literal, TypeAlias, overload from ..base import AiofilesContextManager -from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO, _UnknownAsyncBinaryIO -from .text import AsyncTextIOWrapper +from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO, AsyncIndirectBufferedIOBase, _UnknownAsyncBinaryIO +from .text import AsyncTextIndirectIOWrapper, AsyncTextIOWrapper -_OpenFile = Union[StrOrBytesPath, int] -_Opener = Callable[[str, int], int] +_Opener: TypeAlias = Callable[[str, int], int] # Text mode: always returns AsyncTextIOWrapper @overload def open( - file: _OpenFile, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + file: FileDescriptorOrPath, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, *, - loop: AbstractEventLoop | None = ..., - executor: Any | None = ..., -) -> AiofilesContextManager[None, None, AsyncTextIOWrapper]: ... + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... # Unbuffered binary: returns a FileIO @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryMode, buffering: Literal[0], - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, *, - loop: AbstractEventLoop | None = ..., - executor: Any | None = ..., -) -> AiofilesContextManager[None, None, AsyncFileIO]: ... + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... # Buffered binary reading/updating: AsyncBufferedReader @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryModeReading | OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, *, - loop: AbstractEventLoop | None = ..., - executor: Any | None = ..., -) -> AiofilesContextManager[None, None, AsyncBufferedReader]: ... + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedReader]: ... # Buffered binary writing: AsyncBufferedIOBase @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, *, - loop: AbstractEventLoop | None = ..., - executor: Any | None = ..., -) -> AiofilesContextManager[None, None, AsyncBufferedIOBase]: ... + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... # Buffering cannot be determined: fall back to _UnknownAsyncBinaryIO @overload def open( - file: _OpenFile, + file: FileDescriptorOrPath, mode: OpenBinaryMode, - buffering: int, - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: _Opener | None = ..., + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, *, - loop: AbstractEventLoop | None = ..., - executor: Any | None = ..., -) -> AiofilesContextManager[None, None, _UnknownAsyncBinaryIO]: ... + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[_UnknownAsyncBinaryIO]: ... + +wrap: _SingleDispatchCallable[Any] + +stdin: AsyncTextIndirectIOWrapper +stdout: AsyncTextIndirectIOWrapper +stderr: AsyncTextIndirectIOWrapper +stdin_bytes: AsyncIndirectBufferedIOBase +stdout_bytes: AsyncIndirectBufferedIOBase +stderr_bytes: AsyncIndirectBufferedIOBase + +__all__ = ("open", "stdin", "stdout", "stderr", "stdin_bytes", "stdout_bytes", "stderr_bytes") diff --git a/stubs/aiofiles/aiofiles/threadpool/binary.pyi b/stubs/aiofiles/aiofiles/threadpool/binary.pyi index 27bfd7c8516b..2a02d55752ec 100644 --- a/stubs/aiofiles/aiofiles/threadpool/binary.pyi +++ b/stubs/aiofiles/aiofiles/threadpool/binary.pyi @@ -1,24 +1,28 @@ -from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from _typeshed import FileDescriptorOrPath, ReadableBuffer, WriteableBuffer +from collections.abc import Iterable from io import FileIO -from typing import Iterable +from typing import type_check_only -from ..base import AsyncBase +from ..base import AsyncBase, AsyncIndirectBase +# This class does not exist at runtime and instead these methods are +# all dynamically patched in. +@type_check_only class _UnknownAsyncBinaryIO(AsyncBase[bytes]): async def close(self) -> None: ... async def flush(self) -> None: ... async def isatty(self) -> bool: ... - async def read(self, __size: int = ...) -> bytes: ... - async def readinto(self, __buffer: WriteableBuffer) -> int | None: ... - async def readline(self, __size: int | None = ...) -> bytes: ... - async def readlines(self, __hint: int = ...) -> list[bytes]: ... - async def seek(self, __offset: int, __whence: int = ...) -> int: ... + async def read(self, size: int = ..., /) -> bytes: ... + async def readinto(self, buffer: WriteableBuffer, /) -> int | None: ... + async def readline(self, size: int | None = ..., /) -> bytes: ... + async def readlines(self, hint: int = ..., /) -> list[bytes]: ... + async def seek(self, offset: int, whence: int = ..., /) -> int: ... async def seekable(self) -> bool: ... async def tell(self) -> int: ... - async def truncate(self, __size: int | None = ...) -> int: ... + async def truncate(self, size: int | None = ..., /) -> int: ... async def writable(self) -> bool: ... - async def write(self, __b: ReadableBuffer) -> int: ... - async def writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ... + async def write(self, b: ReadableBuffer, /) -> int: ... + async def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... def fileno(self) -> int: ... def readable(self) -> bool: ... @property @@ -26,16 +30,28 @@ class _UnknownAsyncBinaryIO(AsyncBase[bytes]): @property def mode(self) -> str: ... @property - def name(self) -> StrOrBytesPath | int: ... + def name(self) -> FileDescriptorOrPath: ... class AsyncBufferedIOBase(_UnknownAsyncBinaryIO): - async def read1(self, __size: int = ...) -> bytes: ... + async def read1(self, size: int = ..., /) -> bytes: ... + def detach(self) -> FileIO: ... + @property + def raw(self) -> FileIO: ... + +class AsyncIndirectBufferedIOBase(AsyncIndirectBase[bytes], _UnknownAsyncBinaryIO): + async def read1(self, size: int = ..., /) -> bytes: ... def detach(self) -> FileIO: ... @property def raw(self) -> FileIO: ... class AsyncBufferedReader(AsyncBufferedIOBase): - async def peek(self, __size: int = ...) -> bytes: ... + async def peek(self, size: int = ..., /) -> bytes: ... + +class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase): + async def peek(self, size: int = ..., /) -> bytes: ... class AsyncFileIO(_UnknownAsyncBinaryIO): async def readall(self) -> bytes: ... + +class AsyncIndirectFileIO(AsyncIndirectBase[bytes], _UnknownAsyncBinaryIO): + async def readall(self) -> bytes: ... diff --git a/stubs/aiofiles/aiofiles/threadpool/text.pyi b/stubs/aiofiles/aiofiles/threadpool/text.pyi index fd2a90122e2a..6c6bf20a408c 100644 --- a/stubs/aiofiles/aiofiles/threadpool/text.pyi +++ b/stubs/aiofiles/aiofiles/threadpool/text.pyi @@ -1,22 +1,24 @@ -from _typeshed import StrOrBytesPath -from typing import BinaryIO, Iterable, Tuple +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable +from typing import BinaryIO, type_check_only -from ..base import AsyncBase +from ..base import AsyncBase, AsyncIndirectBase -class AsyncTextIOWrapper(AsyncBase[str]): +@type_check_only +class _UnknownAsyncTextIO(AsyncBase[str]): async def close(self) -> None: ... async def flush(self) -> None: ... async def isatty(self) -> bool: ... - async def read(self, __size: int | None = ...) -> str: ... - async def readline(self, __size: int = ...) -> str: ... - async def readlines(self, __hint: int = ...) -> list[str]: ... - async def seek(self, __offset: int, __whence: int = ...) -> int: ... + async def read(self, size: int | None = ..., /) -> str: ... + async def readline(self, size: int = ..., /) -> str: ... + async def readlines(self, hint: int = ..., /) -> list[str]: ... + async def seek(self, offset: int, whence: int = ..., /) -> int: ... async def seekable(self) -> bool: ... async def tell(self) -> int: ... - async def truncate(self, __size: int | None = ...) -> int: ... + async def truncate(self, size: int | None = ..., /) -> int: ... async def writable(self) -> bool: ... - async def write(self, __b: str) -> int: ... - async def writelines(self, __lines: Iterable[str]) -> None: ... + async def write(self, b: str, /) -> int: ... + async def writelines(self, lines: Iterable[str], /) -> None: ... def detach(self) -> BinaryIO: ... def fileno(self) -> int: ... def readable(self) -> bool: ... @@ -31,8 +33,11 @@ class AsyncTextIOWrapper(AsyncBase[str]): @property def line_buffering(self) -> bool: ... @property - def newlines(self) -> str | Tuple[str, ...] | None: ... + def newlines(self) -> str | tuple[str, ...] | None: ... @property - def name(self) -> StrOrBytesPath | int: ... + def name(self) -> FileDescriptorOrPath: ... @property def mode(self) -> str: ... + +class AsyncTextIOWrapper(_UnknownAsyncTextIO): ... +class AsyncTextIndirectIOWrapper(AsyncIndirectBase[str], _UnknownAsyncTextIO): ... diff --git a/stubs/aiofiles/aiofiles/threadpool/utils.pyi b/stubs/aiofiles/aiofiles/threadpool/utils.pyi new file mode 100644 index 000000000000..438a6851ef72 --- /dev/null +++ b/stubs/aiofiles/aiofiles/threadpool/utils.pyi @@ -0,0 +1,10 @@ +from collections.abc import Callable +from typing import TypeVar + +_T = TypeVar("_T", bound=type) + +# All these function actually mutate the given type: +def delegate_to_executor(*attrs: str) -> Callable[[_T], _T]: ... +def proxy_method_directly(*attrs: str) -> Callable[[_T], _T]: ... +def proxy_property_directly(*attrs: str) -> Callable[[_T], _T]: ... +def cond_delegate_to_executor(*attrs: str) -> Callable[[_T], _T]: ... diff --git a/stubs/annoy/METADATA.toml b/stubs/annoy/METADATA.toml deleted file mode 100644 index 74b2b8d57c4f..000000000000 --- a/stubs/annoy/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "1.17.*" -requires = [] diff --git a/stubs/annoy/annoy/__init__.pyi b/stubs/annoy/annoy/__init__.pyi deleted file mode 100644 index 87ecc5c57fc5..000000000000 --- a/stubs/annoy/annoy/__init__.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from _typeshed import SupportsLenAndGetItem -from typing import overload -from typing_extensions import Literal - -_Vector = SupportsLenAndGetItem[float] - -class AnnoyIndex: - f: int - def __init__(self, f: int, metric: Literal["angular", "euclidean", "manhattan", "hamming", "dot"]) -> None: ... - def load(self, fn: str, prefault: bool = ...) -> Literal[True]: ... - def save(self, fn: str, prefault: bool = ...) -> Literal[True]: ... - @overload - def get_nns_by_item(self, i: int, n: int, search_k: int = ..., include_distances: Literal[False] = ...) -> list[int]: ... - @overload - def get_nns_by_item( - self, i: int, n: int, search_k: int, include_distances: Literal[True] - ) -> tuple[list[int], list[float]]: ... - @overload - def get_nns_by_item( - self, i: int, n: int, search_k: int = ..., *, include_distances: Literal[True] - ) -> tuple[list[int], list[float]]: ... - @overload - def get_nns_by_vector( - self, vector: _Vector, n: int, search_k: int = ..., include_distances: Literal[False] = ... - ) -> list[int]: ... - @overload - def get_nns_by_vector( - self, vector: _Vector, n: int, search_k: int, include_distances: Literal[True] - ) -> tuple[list[int], list[float]]: ... - @overload - def get_nns_by_vector( - self, vector: _Vector, n: int, search_k: int = ..., *, include_distances: Literal[True] - ) -> tuple[list[int], list[float]]: ... - def get_item_vector(self, __i: int) -> list[float]: ... - def add_item(self, i: int, vector: _Vector) -> None: ... - def on_disk_build(self, fn: str) -> Literal[True]: ... - def build(self, n_trees: int, n_jobs: int = ...) -> Literal[True]: ... - def unbuild(self) -> Literal[True]: ... - def unload(self) -> Literal[True]: ... - def get_distance(self, __i: int, __j: int) -> float: ... - def get_n_items(self) -> int: ... - def get_n_trees(self) -> int: ... - def verbose(self, __v: bool) -> Literal[True]: ... - def set_seed(self, __s: int) -> None: ... diff --git a/stubs/antlr4-python3-runtime/METADATA.toml b/stubs/antlr4-python3-runtime/METADATA.toml new file mode 100644 index 000000000000..65d20d6ee09d --- /dev/null +++ b/stubs/antlr4-python3-runtime/METADATA.toml @@ -0,0 +1,5 @@ +version = "4.13.*" +upstream-repository = "https://github.com/antlr/antlr4" + +[tool.stubtest] +ci-platforms = ["linux", "win32"] diff --git a/stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi b/stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi new file mode 100644 index 000000000000..b6a2b43973fb --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi @@ -0,0 +1,39 @@ +from antlr4.error.Errors import IllegalStateException as IllegalStateException +from antlr4.Lexer import Lexer as ActualLexer, TokenSource +from antlr4.Token import Token as Token + +Lexer: None + +class TokenStream: ... + +class BufferedTokenStream(TokenStream): + __slots__ = ("tokenSource", "tokens", "index", "fetchedEOF") + tokenSource: TokenSource + tokens: list[Token] + index: int + fetchedEOF: bool + def __init__(self, tokenSource: ActualLexer | None) -> None: ... + def mark(self) -> int: ... + def release(self, marker: int) -> None: ... + def reset(self) -> None: ... + def seek(self, index: int) -> None: ... + def get(self, index: int) -> Token: ... + def consume(self) -> None: ... + def sync(self, i: int) -> bool: ... + def fetch(self, n: int) -> int: ... + def getTokens(self, start: int, stop: int, types: set[int] | None = None) -> list[Token]: ... + def LA(self, i: int) -> int: ... + def LB(self, k: int) -> Token | None: ... + def LT(self, k: int) -> Token | None: ... + def adjustSeekIndex(self, i: int) -> int: ... + def lazyInit(self) -> None: ... + def setup(self) -> None: ... + def setTokenSource(self, tokenSource: ActualLexer | None) -> None: ... + def nextTokenOnChannel(self, i: int, channel: int) -> int: ... + def previousTokenOnChannel(self, i: int, channel: int) -> int: ... + def getHiddenTokensToRight(self, tokenIndex: int, channel: int = -1) -> list[Token] | None: ... + def getHiddenTokensToLeft(self, tokenIndex: int, channel: int = -1) -> list[Token] | None: ... + def filterForChannel(self, left: int, right: int, channel: int) -> list[Token] | None: ... + def getSourceName(self) -> str: ... + def getText(self, start: int | None = None, stop: int | None = None) -> str: ... + def fill(self) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi b/stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi new file mode 100644 index 000000000000..e654055b7258 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi @@ -0,0 +1,23 @@ +from antlr4.InputStream import InputStream +from antlr4.Lexer import TokenSource +from antlr4.Token import CommonToken as CommonToken + +class TokenFactory: ... + +class CommonTokenFactory(TokenFactory): + __slots__ = "copyText" + DEFAULT: CommonTokenFactory | None + copyText: bool + def __init__(self, copyText: bool = False) -> None: ... + def create( + self, + source: tuple[TokenSource, InputStream], + type: int, + text: str, + channel: int, + start: int, + stop: int, + line: int, + column: int, + ) -> CommonToken: ... + def createThin(self, type: int, text: str) -> CommonToken: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi b/stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi new file mode 100644 index 000000000000..ad5d92d3bc9e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi @@ -0,0 +1,12 @@ +from antlr4.BufferedTokenStream import BufferedTokenStream as BufferedTokenStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.Token import Token as Token + +class CommonTokenStream(BufferedTokenStream): + __slots__ = "channel" + channel: int + def __init__(self, lexer: Lexer, channel: int = 0) -> None: ... + def adjustSeekIndex(self, i: int) -> int: ... + def LB(self, k: int) -> Token | None: ... + def LT(self, k: int) -> Token | None: ... + def getNumberOfOnChannelTokens(self) -> int: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/FileStream.pyi b/stubs/antlr4-python3-runtime/antlr4/FileStream.pyi new file mode 100644 index 000000000000..75ae77b2447b --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/FileStream.pyi @@ -0,0 +1,7 @@ +from antlr4.InputStream import InputStream as InputStream + +class FileStream(InputStream): + __slots__ = "fileName" + fileName: str + def __init__(self, fileName: str, encoding: str = "ascii", errors: str = "strict") -> None: ... + def readDataFrom(self, fileName: str, encoding: str, errors: str = "strict") -> str: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/InputStream.pyi b/stubs/antlr4-python3-runtime/antlr4/InputStream.pyi new file mode 100644 index 000000000000..c4afb48832d6 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/InputStream.pyi @@ -0,0 +1,24 @@ +from typing import Literal + +from antlr4.Token import Token as Token + +class InputStream: + __slots__ = ("name", "strdata", "_index", "data", "_size") + name: str + strdata: str + data: list[int] + _index: int + _size: int + def __init__(self, data: str) -> None: ... + @property + def index(self) -> int: ... + @property + def size(self) -> int: ... + def reset(self) -> None: ... + def consume(self) -> None: ... + def LA(self, offset: int) -> int: ... + def LT(self, offset: int) -> int: ... + def mark(self) -> Literal[-1]: ... + def release(self, marker: int) -> None: ... + def seek(self, _index: int) -> None: ... + def getText(self, start: int, stop: int) -> str: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi b/stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi new file mode 100644 index 000000000000..2b84ca4e317e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi @@ -0,0 +1,20 @@ +from antlr4.Token import Token as Token + +class IntervalSet: + __slots__ = ("intervals", "readonly") + intervals: list[range] | None + readonly: bool + def __init__(self) -> None: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def addOne(self, v: int): ... + def addRange(self, v: range): ... + def addSet(self, other: IntervalSet): ... + def reduce(self, k: int): ... + def complement(self, start: int, stop: int): ... + def __contains__(self, item) -> bool: ... + def __len__(self) -> int: ... + def removeRange(self, v) -> None: ... + def removeOne(self, v) -> None: ... + def toString(self, literalNames: list[str], symbolicNames: list[str]): ... + def elementName(self, literalNames: list[str], symbolicNames: list[str], a: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi b/stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi new file mode 100644 index 000000000000..5742e60131ca --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.ATNState import ATNState as ATNState, RuleStopState as RuleStopState +from antlr4.atn.Transition import ( + AbstractPredicateTransition as AbstractPredicateTransition, + NotSetTransition as NotSetTransition, + RuleTransition as RuleTransition, + WildcardTransition as WildcardTransition, +) +from antlr4.IntervalSet import IntervalSet as IntervalSet +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextFromRuleContext as PredictionContextFromRuleContext, + SingletonPredictionContext as SingletonPredictionContext, +) +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token + +class LL1Analyzer: + __slots__ = "atn" + HIT_PRED: Incomplete + atn: Incomplete + def __init__(self, atn: ATN) -> None: ... + def getDecisionLookahead(self, s: ATNState): ... + def LOOK(self, s: ATNState, stopState: ATNState | None = None, ctx: RuleContext | None = None): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Lexer.pyi b/stubs/antlr4-python3-runtime/antlr4/Lexer.pyi new file mode 100644 index 000000000000..3f46d7abe5d0 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Lexer.pyi @@ -0,0 +1,102 @@ +from typing import TextIO + +from antlr4.atn.LexerATNSimulator import LexerATNSimulator as LexerATNSimulator +from antlr4.CommonTokenFactory import CommonTokenFactory as CommonTokenFactory +from antlr4.error.Errors import ( + IllegalStateException as IllegalStateException, + LexerNoViableAltException as LexerNoViableAltException, + RecognitionException as RecognitionException, +) +from antlr4.InputStream import InputStream as InputStream +from antlr4.Recognizer import Recognizer as Recognizer +from antlr4.Token import CommonToken, Token as Token + +class TokenSource: ... + +class Lexer(Recognizer, TokenSource): + __slots__ = ( + "_input", + "_output", + "_factory", + "_tokenFactorySourcePair", + "_token", + "_tokenStartCharIndex", + "_tokenStartLine", + "_tokenStartColumn", + "_hitEOF", + "_channel", + "_type", + "_modeStack", + "_mode", + "_text", + ) + DEFAULT_MODE: int + MORE: int + SKIP: int + DEFAULT_TOKEN_CHANNEL: int + HIDDEN: int + MIN_CHAR_VALUE: int + MAX_CHAR_VALUE: int + _input: InputStream + _output: TextIO + _factory: CommonTokenFactory + _tokenFactorySourcePair: tuple[TokenSource, InputStream] + _interp: LexerATNSimulator + _token: Token | None + _tokenStartCharIndex: int + _tokenStartLine: int + _tokenStartColumn: int + _hitEOF: bool + _channel: int + _type: int + _modeStack: list[int] + _mode: int + _text: str | None + def __init__(self, input: InputStream, output: TextIO = ...) -> None: ... + def reset(self) -> None: ... + def nextToken(self) -> Token | None: ... + def skip(self) -> None: ... + def more(self) -> None: ... + def mode(self, m: int) -> None: ... + def pushMode(self, m: int) -> None: ... + def popMode(self) -> int: ... + + @property + def inputStream(self) -> InputStream: ... + @inputStream.setter + def inputStream(self, input: InputStream) -> None: ... + + @property + def sourceName(self) -> str: ... + def emitToken(self, token: Token) -> None: ... + def emit(self) -> CommonToken: ... + def emitEOF(self) -> CommonToken: ... + + @property + def type(self) -> int: ... + @type.setter + def type(self, type: int) -> None: ... + + @property + def line(self) -> int: ... + @line.setter + def line(self, line: int) -> None: ... + + @property + def column(self) -> int: ... + @column.setter + def column(self, column: int) -> None: ... + + def getCharIndex(self) -> int: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, txt: str) -> None: ... + + def getAllTokens(self) -> list[Token]: ... + def notifyListeners(self, e: LexerNoViableAltException) -> None: ... + def getErrorDisplay(self, s: str) -> str: ... + def getErrorDisplayForChar(self, c: str) -> str: ... + def getCharErrorDisplay(self, c: str) -> str: ... + def recover(self, re: RecognitionException) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi b/stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi new file mode 100644 index 000000000000..e327864814cc --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from antlr4.CommonTokenFactory import CommonTokenFactory as CommonTokenFactory +from antlr4.Lexer import TokenSource as TokenSource +from antlr4.Token import Token as Token + +class ListTokenSource(TokenSource): + __slots__ = ("tokens", "sourceName", "pos", "eofToken", "_factory") + tokens: Incomplete + sourceName: Incomplete + pos: int + eofToken: Incomplete + def __init__(self, tokens: list[Token], sourceName: str | None = None) -> None: ... + @property + def column(self): ... + def nextToken(self): ... + @property + def line(self): ... + def getInputStream(self): ... + def getSourceName(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Parser.pyi b/stubs/antlr4-python3-runtime/antlr4/Parser.pyi new file mode 100644 index 000000000000..3e4409dba8af --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Parser.pyi @@ -0,0 +1,99 @@ +from _typeshed import Incomplete +from typing import Literal, TextIO + +from antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptions as ATNDeserializationOptions +from antlr4.atn.ATNDeserializer import ATNDeserializer as ATNDeserializer +from antlr4.atn.ParserATNSimulator import ParserATNSimulator +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.CommonTokenFactory import TokenFactory as TokenFactory +from antlr4.error.Errors import ( + RecognitionException as RecognitionException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.error.ErrorStrategy import DefaultErrorStrategy as DefaultErrorStrategy +from antlr4.InputStream import InputStream as InputStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.Recognizer import Recognizer as Recognizer +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.tree.ParseTreePattern import ParseTreePattern +from antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcher as ParseTreePatternMatcher +from antlr4.tree.Tree import ErrorNode as ErrorNode, ParseTreeListener as ParseTreeListener, TerminalNode as TerminalNode + +class TraceListener(ParseTreeListener): + __slots__ = "_parser" + def __init__(self, parser) -> None: ... + def enterEveryRule(self, ctx) -> None: ... + def visitTerminal(self, node) -> None: ... + def visitErrorNode(self, node) -> None: ... + def exitEveryRule(self, ctx) -> None: ... + +class Parser(Recognizer): + __slots__ = ( + "_input", + "_output", + "_errHandler", + "_precedenceStack", + "_ctx", + "buildParseTrees", + "_tracer", + "_parseListeners", + "_syntaxErrors", + ) + _input: TokenStream + _output: TextIO + _errHandler: DefaultErrorStrategy + _precedenceStack: list[int] + _ctx: ParserRuleContext | None + _tracer: TraceListener | None + _parseListeners: list[ParseTreeListener] + _syntaxErrors: int + _interp: ParserATNSimulator + bypassAltsAtnCache: dict[Incomplete, Incomplete] + buildParseTrees: bool + def __init__(self, input: TokenStream, output: TextIO = ...) -> None: ... + def reset(self) -> None: ... + def match(self, ttype: int) -> Token: ... + def matchWildcard(self) -> Token: ... + def getParseListeners(self) -> list[ParseTreeListener]: ... + def addParseListener(self, listener: ParseTreeListener) -> None: ... + def removeParseListener(self, listener: ParseTreeListener) -> None: ... + def removeParseListeners(self) -> None: ... + def triggerEnterRuleEvent(self) -> None: ... + def triggerExitRuleEvent(self) -> None: ... + def getNumberOfSyntaxErrors(self) -> int: ... + def getTokenFactory(self) -> TokenFactory: ... + def setTokenFactory(self, factory: TokenFactory) -> None: ... + def getATNWithBypassAlts(self): ... + def compileParseTreePattern(self, pattern: str, patternRuleIndex: int, lexer: Lexer | None = None) -> ParseTreePattern: ... + def getInputStream(self) -> InputStream: ... + def setInputStream(self, input: InputStream) -> None: ... + def getTokenStream(self) -> TokenStream: ... + def setTokenStream(self, input: TokenStream) -> None: ... + def getCurrentToken(self) -> Token | None: ... + def notifyErrorListeners( + self, msg: str, offendingToken: Token | None = None, e: RecognitionException | None = None + ) -> None: ... + def consume(self) -> None: ... + def addContextToParseTree(self) -> None: ... + state: int + def enterRule(self, localctx: ParserRuleContext, state: int, ruleIndex: int) -> None: ... + def exitRule(self) -> None: ... + def enterOuterAlt(self, localctx: ParserRuleContext, altNum: int) -> None: ... + def getPrecedence(self) -> int: ... + def enterRecursionRule(self, localctx: ParserRuleContext, state: int, ruleIndex: int, precedence: int) -> None: ... + def pushNewRecursionContext(self, localctx: ParserRuleContext, state: int, ruleIndex: int) -> None: ... + def unrollRecursionContexts(self, parentCtx: ParserRuleContext) -> None: ... + def getInvokingContext(self, ruleIndex: int) -> RuleContext | None: ... + def precpred(self, localctx: RuleContext, precedence: int) -> bool: ... + def inContext(self, context: str) -> Literal[False]: ... + def isExpectedToken(self, symbol: int) -> bool: ... + def getExpectedTokens(self): ... + def getExpectedTokensWithinCurrentRule(self): ... + def getRuleIndex(self, ruleName: str) -> int: ... + def getRuleInvocationStack(self, p: RuleContext | None = None) -> list[str]: ... + def getDFAStrings(self) -> list[str]: ... + def dumpDFA(self) -> None: ... + def getSourceName(self) -> str: ... + def setTrace(self, trace: bool) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi b/stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi new file mode 100644 index 000000000000..121045923a2e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNState import ATNState as ATNState, LoopEndState as LoopEndState, StarLoopEntryState as StarLoopEntryState +from antlr4.atn.ParserATNSimulator import ParserATNSimulator as ParserATNSimulator +from antlr4.atn.Transition import Transition as Transition +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.dfa.DFA import DFA as DFA +from antlr4.error.Errors import ( + FailedPredicateException as FailedPredicateException, + RecognitionException as RecognitionException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.Lexer import Lexer as Lexer +from antlr4.Parser import Parser as Parser +from antlr4.ParserRuleContext import InterpreterRuleContext as InterpreterRuleContext, ParserRuleContext as ParserRuleContext +from antlr4.PredictionContext import PredictionContextCache as PredictionContextCache +from antlr4.Token import Token as Token + +class ParserInterpreter(Parser): + __slots__ = ( + "grammarFileName", + "atn", + "tokenNames", + "ruleNames", + "decisionToDFA", + "sharedContextCache", + "_parentContextStack", + "pushRecursionContextStates", + ) + grammarFileName: str + atn: ATN + tokenNames: list[Incomplete] + ruleNames: list[str] + decisionToDFA: list[DFA] + sharedContextCache: PredictionContextCache + pushRecursionContextStates: set[int] + def __init__( + self, grammarFileName: str, tokenNames: list[str], ruleNames: list[str], atn: ATN, input: TokenStream + ) -> None: ... + state: int + def parse(self, startRuleIndex: int) -> ParserRuleContext | None: ... + def enterRecursionRule(self, localctx: ParserRuleContext, state: int, ruleIndex: int, precedence: int) -> None: ... + def getATNState(self) -> ATNState: ... + def visitState(self, p: ATNState) -> None: ... + def visitRuleStopState(self, p: ATNState) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi b/stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi new file mode 100644 index 000000000000..37d5b6c9d36c --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi @@ -0,0 +1,49 @@ +from collections.abc import Callable, Generator +from typing import TypeVar + +from antlr4.error.Errors import RecognitionException +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ( + INVALID_INTERVAL as INVALID_INTERVAL, + ErrorNodeImpl as ErrorNodeImpl, + ParseTree as ParseTree, + ParseTreeListener as ParseTreeListener, + TerminalNode as TerminalNode, + TerminalNodeImpl as TerminalNodeImpl, +) + +class ParserRuleContext(RuleContext): + __slots__ = ("children", "start", "stop", "exception") + children: list[ParseTree | TerminalNode] | None + start: Token | None + stop: Token | None + exception: RecognitionException | None + def __init__(self, parent: ParserRuleContext | None = None, invokingStateNumber: int | None = None) -> None: ... + parentCtx: RuleContext | None + invokingState: int + def copyFrom(self, ctx: ParserRuleContext) -> None: ... + def enterRule(self, listener: ParseTreeListener) -> None: ... + def exitRule(self, listener: ParseTreeListener) -> None: ... + def addChild(self, child: _ParseTreeT) -> _ParseTreeT: ... + def removeLastChild(self) -> None: ... + def addTokenNode(self, token: Token) -> TerminalNodeImpl: ... + def addErrorNode(self, badToken: Token) -> ErrorNodeImpl: ... + def getChild(self, i: int, ttype: type[_GenericType] | None = None) -> _GenericType | None: ... + def getChildren( + self, predicate: Callable[[ParseTree | TerminalNode], bool] | None = None + ) -> Generator[ParseTree | TerminalNode]: ... + def getToken(self, ttype: int, i: int) -> TerminalNode | None: ... + def getTokens(self, ttype: int) -> list[TerminalNode]: ... + def getTypedRuleContext(self, ctxType: type[_ParserRuleContextT], i: int) -> _ParserRuleContextT | None: ... + def getTypedRuleContexts(self, ctxType: type[_ParserRuleContextT]) -> list[_ParserRuleContextT]: ... + def getChildCount(self) -> int: ... + def getSourceInterval(self) -> tuple[int | None, int | None]: ... + +_GenericType = TypeVar("_GenericType", bound=type) +_ParseTreeT = TypeVar("_ParseTreeT", bound=ParseTree) +_ParserRuleContextT = TypeVar("_ParserRuleContextT", bound=ParserRuleContext) + +class InterpreterRuleContext(ParserRuleContext): + ruleIndex: int + def __init__(self, parent: ParserRuleContext, invokingStateNumber: int, ruleIndex: int) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi b/stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi new file mode 100644 index 000000000000..e2b27608f629 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi @@ -0,0 +1,87 @@ +from _typeshed import Incomplete, SupportsLenAndGetItem + +from antlr4.atn.ATN import ATN as ATN +from antlr4.error.Errors import IllegalStateException as IllegalStateException +from antlr4.RuleContext import RuleContext as RuleContext + +class PredictionContext: + EMPTY: Incomplete + EMPTY_RETURN_STATE: int + globalNodeCount: int + id = globalNodeCount # pyrefly: ignore [unknown-name] + cachedHashCode: Incomplete + def __init__(self, cachedHashCode: int) -> None: ... + def __len__(self) -> int: ... + def isEmpty(self): ... + def hasEmptyPath(self): ... + def getReturnState(self, index: int): ... + def __hash__(self): ... + +def calculateHashCode(parent: PredictionContext, returnState: int): ... +def calculateListsHashCode(parents: list[PredictionContext], returnStates: list[int]): ... + +class PredictionContextCache: + cache: Incomplete + def __init__(self) -> None: ... + def add(self, ctx: PredictionContext): ... + def get(self, ctx: PredictionContext): ... + def __len__(self) -> int: ... + +class SingletonPredictionContext(PredictionContext): + @staticmethod + def create(parent: PredictionContext, returnState: int): ... + parentCtx: Incomplete + returnState: Incomplete + def __init__(self, parent: PredictionContext, returnState: int) -> None: ... + def __len__(self) -> int: ... + def getParent(self, index: int): ... + def getReturnState(self, index: int): ... + def __eq__(self, other): ... + def __hash__(self): ... + +class EmptyPredictionContext(SingletonPredictionContext): + def __init__(self) -> None: ... + def isEmpty(self): ... + def __eq__(self, other): ... + def __hash__(self): ... + +class ArrayPredictionContext(PredictionContext): + parents: Incomplete + returnStates: Incomplete + def __init__(self, parents: list[PredictionContext], returnStates: list[int]) -> None: ... + def isEmpty(self): ... + def __len__(self) -> int: ... + def getParent(self, index: int): ... + def getReturnState(self, index: int): ... + def __eq__(self, other): ... + def __hash__(self): ... + +def PredictionContextFromRuleContext(atn: ATN, outerContext: RuleContext | None = None): ... +def merge( + a: PredictionContext, + b: PredictionContext, + rootIsWildcard: bool, + mergeCache: dict[tuple[Incomplete, Incomplete], SingletonPredictionContext] | None, +): ... +def mergeSingletons( + a: SingletonPredictionContext, + b: SingletonPredictionContext, + rootIsWildcard: bool, + mergeCache: dict[tuple[Incomplete, Incomplete], SingletonPredictionContext] | None, +): ... +def mergeRoot(a: SingletonPredictionContext, b: SingletonPredictionContext, rootIsWildcard: bool): ... +def mergeArrays( + a: ArrayPredictionContext, + b: ArrayPredictionContext, + rootIsWildcard: bool, + mergeCache: dict[tuple[Incomplete, Incomplete], SingletonPredictionContext] | None, +): ... +def combineCommonParents(parents: SupportsLenAndGetItem[PredictionContext]): ... +def getCachedPredictionContext( + context: PredictionContext, contextCache: PredictionContextCache, visited: dict[PredictionContext, PredictionContext] +): ... +def getAllContextNodes( + context: PredictionContext, + nodes: list[Incomplete] | None = None, + visited: dict[PredictionContext, PredictionContext] | None = None, +): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi b/stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi new file mode 100644 index 000000000000..fc0db8acafbc --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNSimulator import ATNSimulator +from antlr4.error.ErrorListener import ( + ConsoleErrorListener as ConsoleErrorListener, + ErrorListener, + ProxyErrorListener as ProxyErrorListener, +) +from antlr4.error.Errors import RecognitionException +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token + +class Recognizer: + __slots__ = ("_listeners", "_interp", "_stateNumber") + tokenTypeMapCache: dict[Incomplete, int] + ruleIndexMapCache: dict[str, int] + _listeners: list[ErrorListener] + _interp: ATNSimulator | None + _stateNumber: int + def __init__(self) -> None: ... + def extractVersion(self, version: str) -> tuple[str, str]: ... + def checkVersion(self, toolVersion: str) -> None: ... + def addErrorListener(self, listener: ErrorListener) -> None: ... + def removeErrorListener(self, listener: ErrorListener) -> None: ... + def removeErrorListeners(self) -> None: ... + def getTokenTypeMap(self) -> dict[Incomplete, int]: ... + def getRuleIndexMap(self) -> dict[str, int]: ... + def getTokenType(self, tokenName: str) -> int: ... + def getErrorHeader(self, e: RecognitionException) -> str: ... + def getTokenErrorDisplay(self, t: Token | None) -> str: ... + def getErrorListenerDispatch(self) -> ProxyErrorListener: ... + def sempred(self, localctx: RuleContext, ruleIndex: int, actionIndex: int) -> bool: ... + def precpred(self, localctx: RuleContext, precedence: int) -> bool: ... + + @property + def state(self) -> int: ... + @state.setter + def state(self, atnState: int) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi b/stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi new file mode 100644 index 000000000000..4edbedb1e6d7 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi @@ -0,0 +1,31 @@ +from collections.abc import Generator +from typing import Any, Literal +from typing_extensions import Self + +from antlr4.Recognizer import Recognizer +from antlr4.tree.Tree import INVALID_INTERVAL as INVALID_INTERVAL, ParseTreeVisitor as ParseTreeVisitor, RuleNode as RuleNode +from antlr4.tree.Trees import Trees as Trees + +Parser: None + +class RuleContext(RuleNode): + __slots__ = ("parentCtx", "invokingState") + EMPTY: RuleContext | None + parentCtx: RuleContext | None + invokingState: int + def __init__(self, parent: RuleContext | None = None, invokingState: int = -1) -> None: ... + def depth(self) -> int: ... + def isEmpty(self) -> bool: ... + def getSourceInterval(self) -> tuple[int | None, int | None]: ... + def getRuleContext(self) -> Self: ... + def getPayload(self) -> Self: ... + def getText(self) -> str: ... + def getRuleIndex(self) -> Literal[-1]: ... + def getAltNumber(self) -> Literal[0]: ... + def setAltNumber(self, altNumber: int) -> None: ... + def getChild(self, i: int) -> Any: ... + def getChildCount(self) -> int: ... + def getChildren(self) -> Generator[Any]: ... + def accept(self, visitor: ParseTreeVisitor) -> None: ... + def toStringTree(self, ruleNames: list[str] | None = None, recog: Recognizer | None = None) -> str: ... + def toString(self, ruleNames: list[str], stop: RuleContext) -> str: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi b/stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi new file mode 100644 index 000000000000..54d3522b9a03 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi @@ -0,0 +1,4 @@ +from antlr4.InputStream import InputStream as InputStream + +class StdinStream(InputStream): + def __init__(self, encoding: str = "ascii", errors: str = "strict") -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Token.pyi b/stubs/antlr4-python3-runtime/antlr4/Token.pyi new file mode 100644 index 000000000000..dc98e1ace2ce --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Token.pyi @@ -0,0 +1,53 @@ +from antlr4.InputStream import InputStream +from antlr4.Lexer import TokenSource + +class Token: + __slots__ = ("source", "type", "channel", "start", "stop", "tokenIndex", "line", "column", "_text") + INVALID_TYPE: int + EPSILON: int + MIN_USER_TOKEN_TYPE: int + EOF: int + DEFAULT_CHANNEL: int + HIDDEN_CHANNEL: int + source: tuple[TokenSource | None, InputStream | None] + type: int + channel: int + start: int + stop: int + tokenIndex: int | None + line: int + column: int + def __init__(self) -> None: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, text: str) -> None: ... + + def getTokenSource(self) -> TokenSource | None: ... + def getInputStream(self) -> InputStream | None: ... + +class CommonToken(Token): + EMPTY_SOURCE: tuple[None, None] + source: tuple[TokenSource | None, InputStream | None] + type: int + channel: int + start: int + stop: int + tokenIndex: int + line: int + column: int + def __init__( + self, + source: tuple[TokenSource | None, InputStream | None] = (None, None), + type: int | None = None, + channel: int = 0, + start: int = -1, + stop: int = -1, + ) -> None: ... + def clone(self) -> CommonToken: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, text: str) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi b/stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi new file mode 100644 index 000000000000..81e2601e7be6 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from antlr4.CommonTokenStream import CommonTokenStream as CommonTokenStream +from antlr4.Token import Token as Token + +class TokenStreamRewriter: + __slots__ = ("tokens", "programs", "lastRewriteTokenIndexes") + DEFAULT_PROGRAM_NAME: str + PROGRAM_INIT_SIZE: int + MIN_TOKEN_INDEX: int + tokens: Incomplete + programs: Incomplete + lastRewriteTokenIndexes: Incomplete + def __init__(self, tokens) -> None: ... + def getTokenStream(self): ... + def rollback(self, instruction_index, program_name) -> None: ... + def deleteProgram(self, program_name="default") -> None: ... + def insertAfterToken(self, token, text, program_name="default") -> None: ... + def insertAfter(self, index, text, program_name="default") -> None: ... + def insertBeforeIndex(self, index, text) -> None: ... + def insertBeforeToken(self, token, text, program_name="default") -> None: ... + def insertBefore(self, program_name, index, text) -> None: ... + def replaceIndex(self, index, text) -> None: ... + def replaceRange(self, from_idx, to_idx, text) -> None: ... + def replaceSingleToken(self, token, text) -> None: ... + def replaceRangeTokens(self, from_token, to_token, text, program_name="default") -> None: ... + def replace(self, program_name, from_idx, to_idx, text) -> None: ... + def deleteToken(self, token) -> None: ... + def deleteIndex(self, index) -> None: ... + def delete(self, program_name, from_idx, to_idx) -> None: ... + def lastRewriteTokenIndex(self, program_name="default"): ... + def setLastRewriteTokenIndex(self, program_name, i) -> None: ... + def getProgram(self, program_name): ... + def getDefaultText(self): ... + def getText(self, program_name, start: int, stop: int): ... + + class RewriteOperation: + __slots__ = ("tokens", "index", "text", "instructionIndex") + tokens: Incomplete + index: Incomplete + text: Incomplete + instructionIndex: int + def __init__(self, tokens, index, text: str = "") -> None: ... + def execute(self, buf): ... + + class InsertBeforeOp(RewriteOperation): + def __init__(self, tokens, index, text: str = "") -> None: ... + def execute(self, buf): ... + + class InsertAfterOp(InsertBeforeOp): ... + + class ReplaceOp(RewriteOperation): + __slots__ = "last_index" + last_index: Incomplete + def __init__(self, from_idx, to_idx, tokens, text) -> None: ... + def execute(self, buf): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Utils.pyi b/stubs/antlr4-python3-runtime/antlr4/Utils.pyi new file mode 100644 index 000000000000..6c0130df5642 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Utils.pyi @@ -0,0 +1,2 @@ +def str_list(val) -> str: ... +def escapeWhitespace(s: str, escapeSpaces: bool): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/__init__.pyi new file mode 100644 index 000000000000..7d6894a50a79 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/__init__.pyi @@ -0,0 +1,32 @@ +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNDeserializer import ATNDeserializer as ATNDeserializer +from antlr4.atn.LexerATNSimulator import LexerATNSimulator as LexerATNSimulator +from antlr4.atn.ParserATNSimulator import ParserATNSimulator as ParserATNSimulator +from antlr4.atn.PredictionMode import PredictionMode as PredictionMode +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.CommonTokenStream import CommonTokenStream as CommonTokenStream +from antlr4.dfa.DFA import DFA as DFA +from antlr4.error.DiagnosticErrorListener import DiagnosticErrorListener as DiagnosticErrorListener +from antlr4.error.Errors import ( + IllegalStateException as IllegalStateException, + NoViableAltException as NoViableAltException, + RecognitionException as RecognitionException, +) +from antlr4.error.ErrorStrategy import BailErrorStrategy as BailErrorStrategy +from antlr4.FileStream import FileStream as FileStream +from antlr4.InputStream import InputStream as InputStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.Parser import Parser as Parser +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext, RuleContext as RuleContext +from antlr4.PredictionContext import PredictionContextCache as PredictionContextCache +from antlr4.StdinStream import StdinStream as StdinStream +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ( + ErrorNode as ErrorNode, + ParseTreeListener as ParseTreeListener, + ParseTreeVisitor as ParseTreeVisitor, + ParseTreeWalker as ParseTreeWalker, + RuleNode as RuleNode, + TerminalNode as TerminalNode, +) +from antlr4.Utils import str_list as str_list diff --git a/stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi b/stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi new file mode 100644 index 000000000000..c45632a1e4d1 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi @@ -0,0 +1,4 @@ +from antlr4 import * + +def beautify_lisp_string(in_string): ... +def main() -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi new file mode 100644 index 000000000000..f0951194380c --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import ATNState as ATNState, DecisionState as DecisionState +from antlr4.atn.ATNType import ATNType as ATNType +from antlr4.IntervalSet import IntervalSet as IntervalSet +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token + +class ATN: + __slots__ = ( + "grammarType", + "maxTokenType", + "states", + "decisionToState", + "ruleToStartState", + "ruleToStopState", + "modeNameToStartState", + "ruleToTokenType", + "lexerActions", + "modeToStartState", + ) + INVALID_ALT_NUMBER: int + grammarType: Incomplete + maxTokenType: Incomplete + states: Incomplete + decisionToState: Incomplete + ruleToStartState: Incomplete + ruleToStopState: Incomplete + modeNameToStartState: Incomplete + ruleToTokenType: Incomplete + lexerActions: Incomplete + modeToStartState: Incomplete + def __init__(self, grammarType: ATNType, maxTokenType: int) -> None: ... + def nextTokensInContext(self, s: ATNState, ctx: RuleContext): ... + def nextTokensNoContext(self, s: ATNState): ... + def nextTokens(self, s: ATNState, ctx: RuleContext | None = None): ... + def addState(self, state: ATNState): ... + def removeState(self, state: ATNState): ... + def defineDecisionState(self, s: DecisionState): ... + def getDecisionState(self, decision: int): ... + def getExpectedTokens(self, stateNumber: int, ctx: RuleContext): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi new file mode 100644 index 000000000000..12046c969e40 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import ATNState as ATNState, DecisionState as DecisionState +from antlr4.atn.LexerActionExecutor import LexerActionExecutor as LexerActionExecutor +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext +from antlr4.PredictionContext import PredictionContext as PredictionContext + +class ATNConfig: + __slots__ = ("state", "alt", "context", "semanticContext", "reachesIntoOuterContext", "precedenceFilterSuppressed") + state: Incomplete + alt: Incomplete + context: Incomplete + semanticContext: Incomplete + reachesIntoOuterContext: Incomplete + precedenceFilterSuppressed: Incomplete + def __init__( + self, + state: ATNState | None = None, + alt: int | None = None, + context: PredictionContext | None = None, + semantic: SemanticContext | None = None, + config: ATNConfig | None = None, + ) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + def hashCodeForConfigSet(self): ... + def equalsForConfigSet(self, other): ... + +class LexerATNConfig(ATNConfig): + __slots__ = ("lexerActionExecutor", "passedThroughNonGreedyDecision") + lexerActionExecutor: Incomplete + passedThroughNonGreedyDecision: Incomplete + def __init__( + self, + state: ATNState, + alt: int | None = None, + context: PredictionContext | None = None, + semantic: SemanticContext = ..., + lexerActionExecutor: LexerActionExecutor | None = None, + config: LexerATNConfig | None = None, + ) -> None: ... + def __hash__(self): ... + def __eq__(self, other): ... + def hashCodeForConfigSet(self): ... + def equalsForConfigSet(self, other): ... + def checkNonGreedyDecision(self, source: LexerATNConfig, target: ATNState): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi new file mode 100644 index 000000000000..aa82c295ce57 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext +from antlr4.error.Errors import ( + IllegalStateException as IllegalStateException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.PredictionContext import merge as merge +from antlr4.Utils import str_list as str_list + +ATNSimulator: Incomplete + +class ATNConfigSet: + __slots__ = ( + "configLookup", + "fullCtx", + "readonly", + "configs", + "uniqueAlt", + "conflictingAlts", + "hasSemanticContext", + "dipsIntoOuterContext", + "cachedHashCode", + ) + configLookup: Incomplete + fullCtx: Incomplete + readonly: bool + configs: Incomplete + uniqueAlt: int + conflictingAlts: Incomplete + hasSemanticContext: bool + dipsIntoOuterContext: bool + cachedHashCode: int + def __init__(self, fullCtx: bool = True) -> None: ... + def __iter__(self): ... + def add(self, config: ATNConfig, mergeCache=None): ... + def getOrAdd(self, config: ATNConfig): ... + def getStates(self): ... + def getPredicates(self): ... + def get(self, i: int): ... + def optimizeConfigs(self, interpreter: ATNSimulator): ... + def addAll(self, coll: list[Incomplete]): ... + def __eq__(self, other): ... + def __hash__(self): ... + def hashConfigs(self): ... + def __len__(self) -> int: ... + def isEmpty(self): ... + def __contains__(self, config) -> bool: ... + def clear(self) -> None: ... + def setReadonly(self, readonly: bool): ... + +class OrderedATNConfigSet(ATNConfigSet): + def __init__(self) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi new file mode 100644 index 000000000000..9a2021cd7d67 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +class ATNDeserializationOptions: + __slots__ = ("readonly", "verifyATN", "generateRuleBypassTransitions") + defaultOptions: Incomplete + readonly: bool + verifyATN: Incomplete + generateRuleBypassTransitions: Incomplete + def __init__(self, copyFrom: ATNDeserializationOptions | None = None) -> None: ... + def __setattr__(self, key, value) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi new file mode 100644 index 000000000000..ed6b48bf8f84 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptions as ATNDeserializationOptions +from antlr4.atn.ATNState import * +from antlr4.atn.ATNType import ATNType as ATNType +from antlr4.atn.LexerAction import * +from antlr4.atn.Transition import * +from antlr4.Token import Token as Token + +SERIALIZED_VERSION: int + +class ATNDeserializer: + __slots__ = ("deserializationOptions", "data", "pos") + deserializationOptions: Incomplete + def __init__(self, options: ATNDeserializationOptions | None = None) -> None: ... + data: Incomplete + pos: int + def deserialize(self, data: list[int]): ... + def checkVersion(self) -> None: ... + def readATN(self): ... + def readStates(self, atn: ATN): ... + def readRules(self, atn: ATN): ... + def readModes(self, atn: ATN): ... + def readSets(self, atn: ATN, sets: list[Incomplete]): ... + def readEdges(self, atn: ATN, sets: list[Incomplete]): ... + def readDecisions(self, atn: ATN): ... + def readLexerActions(self, atn: ATN): ... + def generateRuleBypassTransitions(self, atn: ATN): ... + def generateRuleBypassTransition(self, atn: ATN, idx: int): ... + def stateIsEndStateFor(self, state: ATNState, idx: int): ... + def markPrecedenceDecisions(self, atn: ATN): ... + def verifyATN(self, atn: ATN): ... + def checkCondition(self, condition: bool, message=None): ... + def readInt(self): ... + edgeFactories: Incomplete + def edgeFactory(self, atn: ATN, type: int, src: int, trg: int, arg1: int, arg2: int, arg3: int, sets: list[Incomplete]): ... + stateFactories: Incomplete + def stateFactory(self, type: int, ruleIndex: int): ... + CHANNEL: int + CUSTOM: int + MODE: int + MORE: int + POP_MODE: int + PUSH_MODE: int + SKIP: int + TYPE: int + actionFactories: Incomplete + def lexerActionFactory(self, type: int, data1: int, data2: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi new file mode 100644 index 000000000000..2ca0b846e9c9 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextCache as PredictionContextCache, + getCachedPredictionContext as getCachedPredictionContext, +) + +class ATNSimulator: + __slots__ = ("atn", "sharedContextCache", "__dict__") + ERROR: Incomplete + atn: Incomplete + sharedContextCache: Incomplete + def __init__(self, atn: ATN, sharedContextCache: PredictionContextCache) -> None: ... + def getCachedContext(self, context: PredictionContext): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi new file mode 100644 index 000000000000..5b432fa26026 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete + +from antlr4.atn.Transition import Transition as Transition + +INITIAL_NUM_TRANSITIONS: int + +class ATNState: + __slots__ = ("atn", "stateNumber", "stateType", "ruleIndex", "epsilonOnlyTransitions", "transitions", "nextTokenWithinRule") + INVALID_TYPE: int + BASIC: int + RULE_START: int + BLOCK_START: int + PLUS_BLOCK_START: int + STAR_BLOCK_START: int + TOKEN_START: int + RULE_STOP: int + BLOCK_END: int + STAR_LOOP_BACK: int + STAR_LOOP_ENTRY: int + PLUS_LOOP_BACK: int + LOOP_END: int + serializationNames: Incomplete + INVALID_STATE_NUMBER: int + atn: Incomplete + stateNumber: Incomplete + stateType: Incomplete + ruleIndex: int + epsilonOnlyTransitions: bool + transitions: Incomplete + nextTokenWithinRule: Incomplete + def __init__(self) -> None: ... + def __hash__(self): ... + def __eq__(self, other): ... + def onlyHasEpsilonTransitions(self): ... + def isNonGreedyExitState(self): ... + def addTransition(self, trans: Transition, index: int = -1): ... + +class BasicState(ATNState): + stateType: Incomplete + def __init__(self) -> None: ... + +class DecisionState(ATNState): + __slots__ = ("decision", "nonGreedy") + decision: int + nonGreedy: bool + def __init__(self) -> None: ... + +class BlockStartState(DecisionState): + __slots__ = "endState" + endState: Incomplete + def __init__(self) -> None: ... + +class BasicBlockStartState(BlockStartState): + stateType: Incomplete + def __init__(self) -> None: ... + +class BlockEndState(ATNState): + __slots__ = "startState" + stateType: Incomplete + startState: Incomplete + def __init__(self) -> None: ... + +class RuleStopState(ATNState): + stateType: Incomplete + def __init__(self) -> None: ... + +class RuleStartState(ATNState): + __slots__ = ("stopState", "isPrecedenceRule") + stateType: Incomplete + stopState: Incomplete + isPrecedenceRule: bool + def __init__(self) -> None: ... + +class PlusLoopbackState(DecisionState): + stateType: Incomplete + def __init__(self) -> None: ... + +class PlusBlockStartState(BlockStartState): + __slots__ = "loopBackState" + stateType: Incomplete + loopBackState: Incomplete + def __init__(self) -> None: ... + +class StarBlockStartState(BlockStartState): + stateType: Incomplete + def __init__(self) -> None: ... + +class StarLoopbackState(ATNState): + stateType: Incomplete + def __init__(self) -> None: ... + +class StarLoopEntryState(DecisionState): + __slots__ = ("loopBackState", "isPrecedenceDecision") + stateType: Incomplete + loopBackState: Incomplete + isPrecedenceDecision: Incomplete + def __init__(self) -> None: ... + +class LoopEndState(ATNState): + __slots__ = "loopBackState" + stateType: Incomplete + loopBackState: Incomplete + def __init__(self) -> None: ... + +class TokensStartState(DecisionState): + stateType: Incomplete + def __init__(self) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi new file mode 100644 index 000000000000..5260cdf242d3 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi @@ -0,0 +1,7 @@ +from enum import IntEnum + +class ATNType(IntEnum): + LEXER = 0 + PARSER = 1 + @classmethod + def fromOrdinal(cls, i: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi new file mode 100644 index 000000000000..0a00ea8445ff --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi @@ -0,0 +1,89 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import LexerATNConfig as LexerATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet, OrderedATNConfigSet as OrderedATNConfigSet +from antlr4.atn.ATNSimulator import ATNSimulator as ATNSimulator +from antlr4.atn.ATNState import ATNState as ATNState, RuleStopState as RuleStopState +from antlr4.atn.LexerActionExecutor import LexerActionExecutor as LexerActionExecutor +from antlr4.atn.Transition import Transition as Transition +from antlr4.dfa.DFA import DFA +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.error.Errors import ( + LexerNoViableAltException as LexerNoViableAltException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.InputStream import InputStream as InputStream +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextCache as PredictionContextCache, + SingletonPredictionContext as SingletonPredictionContext, +) +from antlr4.Token import Token as Token + +class SimState: + __slots__ = ("index", "line", "column", "dfaState") + def __init__(self) -> None: ... + index: int + line: int + column: int + dfaState: Incomplete + def reset(self) -> None: ... + +class LexerATNSimulator(ATNSimulator): + __slots__ = ("decisionToDFA", "recog", "startIndex", "line", "column", "mode", "DEFAULT_MODE", "MAX_CHAR_VALUE", "prevAccept") + debug: bool + dfa_debug: bool + MIN_DFA_EDGE: int + MAX_DFA_EDGE: int + ERROR: Incomplete + decisionToDFA: Incomplete + recog: Incomplete + startIndex: int + line: int + column: int + mode: Incomplete + DEFAULT_MODE: Incomplete + MAX_CHAR_VALUE: Incomplete + prevAccept: Incomplete + def __init__(self, recog, atn: ATN, decisionToDFA: list[DFA], sharedContextCache: PredictionContextCache) -> None: ... + def copyState(self, simulator: LexerATNSimulator): ... + def match(self, input: InputStream, mode: int): ... + def reset(self) -> None: ... + def matchATN(self, input: InputStream): ... + def execATN(self, input: InputStream, ds0: DFAState): ... + def getExistingTargetState(self, s: DFAState, t: int): ... + def computeTargetState(self, input: InputStream, s: DFAState, t: int): ... + def failOrAccept(self, prevAccept: SimState, input: InputStream, reach: ATNConfigSet, t: int): ... + def getReachableConfigSet(self, input: InputStream, closure: ATNConfigSet, reach: ATNConfigSet, t: int): ... + def accept( + self, input: InputStream, lexerActionExecutor: LexerActionExecutor, startIndex: int, index: int, line: int, charPos: int + ): ... + def getReachableTarget(self, trans: Transition, t: int): ... + def computeStartState(self, input: InputStream, p: ATNState): ... + def closure( + self, + input: InputStream, + config: LexerATNConfig, + configs: ATNConfigSet, + currentAltReachedAcceptState: bool, + speculative: bool, + treatEofAsEpsilon: bool, + ): ... + def getEpsilonTarget( + self, + input: InputStream, + config: LexerATNConfig, + t: Transition, + configs: ATNConfigSet, + speculative: bool, + treatEofAsEpsilon: bool, + ): ... + def evaluatePredicate(self, input: InputStream, ruleIndex: int, predIndex: int, speculative: bool): ... + def captureSimState(self, settings: SimState, input: InputStream, dfaState: DFAState): ... + def addDFAEdge(self, from_: DFAState, tk: int, to: DFAState | None = None, cfgs: ATNConfigSet | None = None) -> DFAState: ... + def addDFAState(self, configs: ATNConfigSet) -> DFAState: ... + def getDFA(self, mode: int): ... + def getText(self, input: InputStream): ... + def consume(self, input: InputStream): ... + def getTokenName(self, t: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi new file mode 100644 index 000000000000..255a96f31eb8 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi @@ -0,0 +1,89 @@ +from _typeshed import Incomplete +from enum import IntEnum + +Lexer: Incomplete + +class LexerActionType(IntEnum): + CHANNEL = 0 + CUSTOM = 1 + MODE = 2 + MORE = 3 + POP_MODE = 4 + PUSH_MODE = 5 + SKIP = 6 + TYPE = 7 + +class LexerAction: + __slots__ = ("actionType", "isPositionDependent") + actionType: Incomplete + isPositionDependent: bool + def __init__(self, action: LexerActionType) -> None: ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerSkipAction(LexerAction): + INSTANCE: Incomplete + def __init__(self) -> None: ... + def execute(self, lexer: Lexer): ... + +class LexerTypeAction(LexerAction): + __slots__ = "type" + type: Incomplete + def __init__(self, type: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerPushModeAction(LexerAction): + __slots__ = "mode" + mode: Incomplete + def __init__(self, mode: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerPopModeAction(LexerAction): + INSTANCE: Incomplete + def __init__(self) -> None: ... + def execute(self, lexer: Lexer): ... + +class LexerMoreAction(LexerAction): + INSTANCE: Incomplete + def __init__(self) -> None: ... + def execute(self, lexer: Lexer): ... + +class LexerModeAction(LexerAction): + __slots__ = "mode" + mode: Incomplete + def __init__(self, mode: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerCustomAction(LexerAction): + __slots__ = ("ruleIndex", "actionIndex") + ruleIndex: Incomplete + actionIndex: Incomplete + isPositionDependent: bool + def __init__(self, ruleIndex: int, actionIndex: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerChannelAction(LexerAction): + __slots__ = "channel" + channel: Incomplete + def __init__(self, channel: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerIndexedCustomAction(LexerAction): + __slots__ = ("offset", "action") + offset: Incomplete + action: Incomplete + isPositionDependent: bool + def __init__(self, offset: int, action: LexerAction) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi new file mode 100644 index 000000000000..ff09dd23e400 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from antlr4.atn.LexerAction import LexerAction as LexerAction, LexerIndexedCustomAction as LexerIndexedCustomAction +from antlr4.InputStream import InputStream as InputStream + +class LexerActionExecutor: + __slots__ = ("lexerActions", "hashCode") + lexerActions: Incomplete + hashCode: Incomplete + def __init__(self, lexerActions: list[LexerAction] = []) -> None: ... + @staticmethod + def append(lexerActionExecutor: LexerActionExecutor, lexerAction: LexerAction): ... + def fixOffsetBeforeMatch(self, offset: int): ... + def execute(self, lexer, input: InputStream, startIndex: int): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi new file mode 100644 index 000000000000..aa990870ce3c --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi @@ -0,0 +1,134 @@ +from _typeshed import Incomplete + +from antlr4 import DFA as DFA +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.ATNSimulator import ATNSimulator as ATNSimulator +from antlr4.atn.ATNState import ATNState as ATNState, DecisionState as DecisionState, RuleStopState as RuleStopState +from antlr4.atn.PredictionMode import PredictionMode as PredictionMode +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext, andContext as andContext, orContext as orContext +from antlr4.atn.Transition import ( + ActionTransition as ActionTransition, + AtomTransition as AtomTransition, + NotSetTransition as NotSetTransition, + PrecedencePredicateTransition as PrecedencePredicateTransition, + PredicateTransition as PredicateTransition, + RuleTransition as RuleTransition, + SetTransition as SetTransition, + Transition as Transition, +) +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.dfa.DFAState import DFAState as DFAState, PredPrediction as PredPrediction +from antlr4.error.Errors import NoViableAltException as NoViableAltException +from antlr4.Parser import Parser as Parser +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextCache as PredictionContextCache, + PredictionContextFromRuleContext as PredictionContextFromRuleContext, + SingletonPredictionContext as SingletonPredictionContext, +) +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.Utils import str_list as str_list + +class ParserATNSimulator(ATNSimulator): + __slots__ = ("parser", "decisionToDFA", "predictionMode", "_input", "_startIndex", "_outerContext", "_dfa", "mergeCache") + debug: bool + trace_atn_sim: bool + dfa_debug: bool + retry_debug: bool + parser: Incomplete + decisionToDFA: Incomplete + predictionMode: Incomplete + mergeCache: Incomplete + def __init__( + self, parser: Parser, atn: ATN, decisionToDFA: list[DFA], sharedContextCache: PredictionContextCache + ) -> None: ... + def reset(self) -> None: ... + def adaptivePredict(self, input: TokenStream, decision: int, outerContext: ParserRuleContext): ... + def execATN(self, dfa: DFA, s0: DFAState, input: TokenStream, startIndex: int, outerContext: ParserRuleContext): ... + def getExistingTargetState(self, previousD: DFAState, t: int): ... + def computeTargetState(self, dfa: DFA, previousD: DFAState, t: int): ... + def predicateDFAState(self, dfaState: DFAState, decisionState: DecisionState): ... + def execATNWithFullContext( + self, dfa: DFA, D: DFAState, s0: ATNConfigSet, input: TokenStream, startIndex: int, outerContext: ParserRuleContext + ): ... + def computeReachSet(self, closure: ATNConfigSet, t: int, fullCtx: bool): ... + def removeAllConfigsNotInRuleStopState(self, configs: ATNConfigSet, lookToEndOfRule: bool): ... + def computeStartState(self, p: ATNState, ctx: RuleContext, fullCtx: bool): ... + def applyPrecedenceFilter(self, configs: ATNConfigSet): ... + def getReachableTarget(self, trans: Transition, ttype: int): ... + def getPredsForAmbigAlts(self, ambigAlts: set[int], configs: ATNConfigSet, nalts: int): ... + def getPredicatePredictions(self, ambigAlts: set[int], altToPred: list[int]): ... + def getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(self, configs: ATNConfigSet, outerContext: ParserRuleContext): ... + def getAltThatFinishedDecisionEntryRule(self, configs: ATNConfigSet): ... + def splitAccordingToSemanticValidity(self, configs: ATNConfigSet, outerContext: ParserRuleContext): ... + def evalSemanticContext(self, predPredictions: list[Incomplete], outerContext: ParserRuleContext, complete: bool): ... + def closure( + self, + config: ATNConfig, + configs: ATNConfigSet, + closureBusy: set[Incomplete], + collectPredicates: bool, + fullCtx: bool, + treatEofAsEpsilon: bool, + ): ... + def closureCheckingStopState( + self, + config: ATNConfig, + configs: ATNConfigSet, + closureBusy: set[Incomplete], + collectPredicates: bool, + fullCtx: bool, + depth: int, + treatEofAsEpsilon: bool, + ): ... + def closure_( + self, + config: ATNConfig, + configs: ATNConfigSet, + closureBusy: set[Incomplete], + collectPredicates: bool, + fullCtx: bool, + depth: int, + treatEofAsEpsilon: bool, + ): ... + def canDropLoopEntryEdgeInLeftRecursiveRule(self, config): ... + def getRuleName(self, index: int): ... + epsilonTargetMethods: Incomplete + def getEpsilonTarget( + self, config: ATNConfig, t: Transition, collectPredicates: bool, inContext: bool, fullCtx: bool, treatEofAsEpsilon: bool + ): ... + def actionTransition(self, config: ATNConfig, t: ActionTransition): ... + def precedenceTransition( + self, config: ATNConfig, pt: PrecedencePredicateTransition, collectPredicates: bool, inContext: bool, fullCtx: bool + ): ... + def predTransition( + self, config: ATNConfig, pt: PredicateTransition, collectPredicates: bool, inContext: bool, fullCtx: bool + ): ... + def ruleTransition(self, config: ATNConfig, t: RuleTransition): ... + def getConflictingAlts(self, configs: ATNConfigSet): ... + def getConflictingAltsOrUniqueAlt(self, configs: ATNConfigSet): ... + def getTokenName(self, t: int): ... + def getLookaheadName(self, input: TokenStream): ... + def dumpDeadEndConfigs(self, nvae: NoViableAltException): ... + def noViableAlt(self, input: TokenStream, outerContext: ParserRuleContext, configs: ATNConfigSet, startIndex: int): ... + def getUniqueAlt(self, configs: ATNConfigSet): ... + def addDFAEdge(self, dfa: DFA, from_: DFAState, t: int, to: DFAState): ... + def addDFAState(self, dfa: DFA, D: DFAState): ... + def reportAttemptingFullContext( + self, dfa: DFA, conflictingAlts: set[Incomplete], configs: ATNConfigSet, startIndex: int, stopIndex: int + ): ... + def reportContextSensitivity(self, dfa: DFA, prediction: int, configs: ATNConfigSet, startIndex: int, stopIndex: int): ... + def reportAmbiguity( + self, + dfa: DFA, + D: DFAState, + startIndex: int, + stopIndex: int, + exact: bool, + ambigAlts: set[Incomplete], + configs: ATNConfigSet, + ): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi new file mode 100644 index 000000000000..68fc4601bf91 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi @@ -0,0 +1,41 @@ +from collections.abc import Sequence +from enum import Enum + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.ATNState import RuleStopState as RuleStopState +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext + +class PredictionMode(Enum): + SLL = 0 + LL = 1 + LL_EXACT_AMBIG_DETECTION = 2 + @classmethod + def hasSLLConflictTerminatingPrediction(cls, mode: PredictionMode, configs: ATNConfigSet): ... + @classmethod + def hasConfigInRuleStopState(cls, configs: ATNConfigSet): ... + @classmethod + def allConfigsInRuleStopStates(cls, configs: ATNConfigSet): ... + @classmethod + def resolvesToJustOneViableAlt(cls, altsets: Sequence[set[int]]): ... + @classmethod + def allSubsetsConflict(cls, altsets: Sequence[set[int]]): ... + @classmethod + def hasNonConflictingAltSet(cls, altsets: Sequence[set[int]]): ... + @classmethod + def hasConflictingAltSet(cls, altsets: Sequence[set[int]]): ... + @classmethod + def allSubsetsEqual(cls, altsets: Sequence[set[int]]): ... + @classmethod + def getUniqueAlt(cls, altsets: Sequence[set[int]]): ... + @classmethod + def getAlts(cls, altsets: Sequence[set[int]]): ... + @classmethod + def getConflictingAltSubsets(cls, configs: ATNConfigSet): ... + @classmethod + def getStateToAltMap(cls, configs: ATNConfigSet): ... + @classmethod + def hasStateAssociatedWithOneAlt(cls, configs: ATNConfigSet): ... + @classmethod + def getSingleViableAlt(cls, altsets: Sequence[set[int]]): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi new file mode 100644 index 000000000000..01f9acf5b0af --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete + +from antlr4.Recognizer import Recognizer as Recognizer +from antlr4.RuleContext import RuleContext as RuleContext + +class SemanticContext: + NONE: Incomplete + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... + +def andContext(a: SemanticContext, b: SemanticContext): ... +def orContext(a: SemanticContext, b: SemanticContext): ... +def filterPrecedencePredicates(collection: set[SemanticContext]): ... + +class EmptySemanticContext(SemanticContext): ... + +class Predicate(SemanticContext): + __slots__ = ("ruleIndex", "predIndex", "isCtxDependent") + ruleIndex: Incomplete + predIndex: Incomplete + isCtxDependent: Incomplete + def __init__(self, ruleIndex: int = -1, predIndex: int = -1, isCtxDependent: bool = False) -> None: ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class PrecedencePredicate(SemanticContext): + precedence: Incomplete + def __init__(self, precedence: int = 0) -> None: ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... + def __lt__(self, other): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class AND(SemanticContext): + __slots__ = "opnds" + opnds: Incomplete + def __init__(self, a: SemanticContext, b: SemanticContext) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... + +class OR(SemanticContext): + __slots__ = "opnds" + opnds: Incomplete + def __init__(self, a: SemanticContext, b: SemanticContext) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi new file mode 100644 index 000000000000..608da7480780 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import RuleStartState +from antlr4.IntervalSet import IntervalSet + +class Transition: + __slots__ = ("target", "isEpsilon", "label") + EPSILON: int + RANGE: int + RULE: int + PREDICATE: int + ATOM: int + ACTION: int + SET: int + NOT_SET: int + WILDCARD: int + PRECEDENCE: int + serializationNames: Incomplete + serializationTypes: Incomplete + target: Incomplete + isEpsilon: bool + label: Incomplete + def __init__(self, target) -> None: ... + +class AtomTransition(Transition): + __slots__ = ("label_", "serializationType") + label_: Incomplete + label: Incomplete + serializationType: Incomplete + def __init__(self, target, label: int) -> None: ... + def makeLabel(self): ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class RuleTransition(Transition): + __slots__ = ("ruleIndex", "precedence", "followState", "serializationType") + ruleIndex: Incomplete + precedence: Incomplete + followState: Incomplete + serializationType: Incomplete + isEpsilon: bool + def __init__(self, ruleStart: RuleStartState, ruleIndex: int, precedence: int, followState) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class EpsilonTransition(Transition): + __slots__ = ("serializationType", "outermostPrecedenceReturn") + serializationType: Incomplete + isEpsilon: bool + outermostPrecedenceReturn: Incomplete + def __init__(self, target, outermostPrecedenceReturn: int = -1) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class RangeTransition(Transition): + __slots__ = ("serializationType", "start", "stop") + serializationType: Incomplete + start: Incomplete + stop: Incomplete + label: Incomplete + def __init__(self, target, start: int, stop: int) -> None: ... + def makeLabel(self): ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class AbstractPredicateTransition(Transition): + def __init__(self, target) -> None: ... + +class PredicateTransition(AbstractPredicateTransition): + __slots__ = ("serializationType", "ruleIndex", "predIndex", "isCtxDependent") + serializationType: Incomplete + ruleIndex: Incomplete + predIndex: Incomplete + isCtxDependent: Incomplete + isEpsilon: bool + def __init__(self, target, ruleIndex: int, predIndex: int, isCtxDependent: bool) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + def getPredicate(self): ... + +class ActionTransition(Transition): + __slots__ = ("serializationType", "ruleIndex", "actionIndex", "isCtxDependent") + serializationType: Incomplete + ruleIndex: Incomplete + actionIndex: Incomplete + isCtxDependent: Incomplete + isEpsilon: bool + def __init__(self, target, ruleIndex: int, actionIndex: int = -1, isCtxDependent: bool = False) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class SetTransition(Transition): + __slots__ = "serializationType" + serializationType: Incomplete + label: Incomplete + def __init__(self, target, set: IntervalSet) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class NotSetTransition(SetTransition): + serializationType: Incomplete + def __init__(self, target, set: IntervalSet) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class WildcardTransition(Transition): + __slots__ = "serializationType" + serializationType: Incomplete + def __init__(self, target) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class PrecedencePredicateTransition(AbstractPredicateTransition): + __slots__ = ("serializationType", "precedence") + serializationType: Incomplete + precedence: Incomplete + isEpsilon: bool + def __init__(self, target, precedence: int) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + def getPredicate(self): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/plugin/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/testing/plugin/__init__.pyi rename to stubs/antlr4-python3-runtime/antlr4/atn/__init__.pyi diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi new file mode 100644 index 000000000000..b18b49cb941d --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.ATNState import DecisionState as DecisionState, StarLoopEntryState as StarLoopEntryState +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.error.Errors import IllegalStateException as IllegalStateException + +class DFA: + __slots__ = ("atnStartState", "decision", "_states", "s0", "precedenceDfa") + atnStartState: Incomplete + decision: Incomplete + s0: Incomplete + precedenceDfa: bool + def __init__(self, atnStartState: DecisionState, decision: int = 0) -> None: ... + def getPrecedenceStartState(self, precedence: int): ... + def setPrecedenceStartState(self, precedence: int, startState: DFAState): ... + def setPrecedenceDfa(self, precedenceDfa: bool): ... + @property + def states(self): ... + def sortedStates(self): ... + def toString(self, literalNames: list[str] | None = None, symbolicNames: list[str] | None = None): ... + def toLexerString(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi new file mode 100644 index 000000000000..efd431df7eaf --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from antlr4 import DFA as DFA +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.Utils import str_list as str_list + +class DFASerializer: + __slots__ = ("dfa", "literalNames", "symbolicNames") + dfa: Incomplete + literalNames: list[str] | None + symbolicNames: list[str] | None + def __init__(self, dfa: DFA, literalNames: list[str] | None = None, symbolicNames: list[str] | None = None) -> None: ... + def getEdgeLabel(self, i: int): ... + def getStateString(self, s: DFAState): ... + +class LexerDFASerializer(DFASerializer): + def __init__(self, dfa: DFA) -> None: ... + def getEdgeLabel(self, i: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi new file mode 100644 index 000000000000..55eff18b7840 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext + +class PredPrediction: + __slots__ = ("alt", "pred") + alt: Incomplete + pred: Incomplete + def __init__(self, pred: SemanticContext, alt: int) -> None: ... + +class DFAState: + __slots__ = ( + "stateNumber", + "configs", + "edges", + "isAcceptState", + "prediction", + "lexerActionExecutor", + "requiresFullContext", + "predicates", + ) + stateNumber: Incomplete + configs: Incomplete + edges: Incomplete + isAcceptState: bool + prediction: int + lexerActionExecutor: Incomplete + requiresFullContext: bool + predicates: Incomplete + def __init__(self, stateNumber: int = -1, configs: ATNConfigSet = ...) -> None: ... + def getAltSet(self): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/caldav/caldav/elements/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/__init__.pyi similarity index 100% rename from stubs/caldav/caldav/elements/__init__.pyi rename to stubs/antlr4-python3-runtime/antlr4/dfa/__init__.pyi diff --git a/stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi b/stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi new file mode 100644 index 000000000000..750c04100245 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from antlr4 import DFA as DFA +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.error.ErrorListener import ErrorListener as ErrorListener + +class DiagnosticErrorListener(ErrorListener): + exactOnly: Incomplete + def __init__(self, exactOnly: bool = True) -> None: ... + def reportAmbiguity( + self, recognizer, dfa: DFA, startIndex: int, stopIndex: int, exact: bool, ambigAlts: set[int], configs: ATNConfigSet + ): ... + def reportAttemptingFullContext( + self, recognizer, dfa: DFA, startIndex: int, stopIndex: int, conflictingAlts: set[int], configs: ATNConfigSet + ): ... + def reportContextSensitivity( + self, recognizer, dfa: DFA, startIndex: int, stopIndex: int, prediction: int, configs: ATNConfigSet + ): ... + def getDecisionDescription(self, recognizer, dfa: DFA): ... + def getConflictingAlts(self, reportedAlts: set[int], configs: ATNConfigSet): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi b/stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi new file mode 100644 index 000000000000..34482bde9131 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +class ErrorListener: + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e) -> None: ... + def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) -> None: ... + def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) -> None: ... + def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs) -> None: ... + +class ConsoleErrorListener(ErrorListener): + INSTANCE: Incomplete + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e) -> None: ... + +class ProxyErrorListener(ErrorListener): + delegates: Incomplete + def __init__(self, delegates) -> None: ... + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e) -> None: ... + def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) -> None: ... + def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) -> None: ... + def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi b/stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi new file mode 100644 index 000000000000..cde0e754c0d8 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import ATNState as ATNState +from antlr4.error.Errors import ( + FailedPredicateException as FailedPredicateException, + InputMismatchException as InputMismatchException, + NoViableAltException as NoViableAltException, + ParseCancellationException as ParseCancellationException, + RecognitionException as RecognitionException, +) +from antlr4.IntervalSet import IntervalSet as IntervalSet +from antlr4.Token import Token as Token + +class ErrorStrategy: + def reset(self, recognizer): ... + def recoverInline(self, recognizer): ... + def recover(self, recognizer, e: RecognitionException): ... + def sync(self, recognizer): ... + def inErrorRecoveryMode(self, recognizer): ... + def reportError(self, recognizer, e: RecognitionException): ... + +class DefaultErrorStrategy(ErrorStrategy): + errorRecoveryMode: bool + lastErrorIndex: int + lastErrorStates: Incomplete + nextTokensContext: Incomplete + nextTokenState: int + def __init__(self) -> None: ... + def reset(self, recognizer): ... + def beginErrorCondition(self, recognizer): ... + def inErrorRecoveryMode(self, recognizer): ... + def endErrorCondition(self, recognizer): ... + def reportMatch(self, recognizer): ... + def reportError(self, recognizer, e: RecognitionException): ... + def recover(self, recognizer, e: RecognitionException): ... + nextTokensState: Incomplete + def sync(self, recognizer): ... + def reportNoViableAlternative(self, recognizer, e: NoViableAltException): ... + def reportInputMismatch(self, recognizer, e: InputMismatchException): ... + def reportFailedPredicate(self, recognizer, e) -> None: ... + def reportUnwantedToken(self, recognizer): ... + def reportMissingToken(self, recognizer): ... + def recoverInline(self, recognizer): ... + def singleTokenInsertion(self, recognizer): ... + def singleTokenDeletion(self, recognizer): ... + def getMissingSymbol(self, recognizer): ... + def getExpectedTokens(self, recognizer): ... + def getTokenErrorDisplay(self, t: Token): ... + def escapeWSAndQuote(self, s: str): ... + def getErrorRecoverySet(self, recognizer): ... + def consumeUntil(self, recognizer, set_: set[int]): ... + +class BailErrorStrategy(DefaultErrorStrategy): + def recover(self, recognizer, e: RecognitionException): ... + def recoverInline(self, recognizer): ... + def sync(self, recognizer): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi b/stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi new file mode 100644 index 000000000000..1a4fe8f7d38f --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete + +from antlr4.InputStream import InputStream as InputStream +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.Recognizer import Recognizer as Recognizer + +class UnsupportedOperationException(Exception): + def __init__(self, msg: str) -> None: ... + +class IllegalStateException(Exception): + def __init__(self, msg: str) -> None: ... + +class CancellationException(IllegalStateException): + def __init__(self, msg: str) -> None: ... + +class RecognitionException(Exception): + message: Incomplete + recognizer: Incomplete + input: Incomplete + ctx: Incomplete + offendingToken: Incomplete + offendingState: int + def __init__( + self, message: str | None = None, recognizer: Recognizer | None = None, input: InputStream | None = None, ctx=None + ) -> None: ... + def getExpectedTokens(self): ... + +class LexerNoViableAltException(RecognitionException): + startIndex: Incomplete + deadEndConfigs: Incomplete + message: str + def __init__(self, lexer, input: InputStream, startIndex: int, deadEndConfigs) -> None: ... + +class NoViableAltException(RecognitionException): + deadEndConfigs: Incomplete + startToken: Incomplete + offendingToken: Incomplete + def __init__( + self, + recognizer, + input=None, + startToken=None, + offendingToken=None, + deadEndConfigs=None, + ctx: ParserRuleContext | None = None, + ) -> None: ... + +class InputMismatchException(RecognitionException): + offendingToken: Incomplete + def __init__(self, recognizer) -> None: ... + +class FailedPredicateException(RecognitionException): + ruleIndex: Incomplete + predicateIndex: Incomplete + predicate: Incomplete + offendingToken: Incomplete + def __init__(self, recognizer, predicate: str | None = None, message: str | None = None) -> None: ... + def formatMessage(self, predicate: str, message: str): ... + +class ParseCancellationException(CancellationException): ... diff --git a/stubs/caldav/caldav/lib/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/error/__init__.pyi similarity index 100% rename from stubs/caldav/caldav/lib/__init__.pyi rename to stubs/antlr4-python3-runtime/antlr4/error/__init__.pyi diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi new file mode 100644 index 000000000000..be68b31898e7 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class Chunk: ... + +class TagChunk(Chunk): + __slots__ = ("tag", "label") + tag: Incomplete + label: Incomplete + def __init__(self, tag: str, label: str | None = None) -> None: ... + +class TextChunk(Chunk): + __slots__ = "text" + text: Incomplete + def __init__(self, text: str) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi new file mode 100644 index 000000000000..71b3dd76899e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from antlr4.tree.ParseTreePattern import ParseTreePattern as ParseTreePattern +from antlr4.tree.Tree import ParseTree as ParseTree + +class ParseTreeMatch: + __slots__ = ("tree", "pattern", "labels", "mismatchedNode") + tree: Incomplete + pattern: Incomplete + labels: Incomplete + mismatchedNode: Incomplete + def __init__( + self, tree: ParseTree, pattern: ParseTreePattern, labels: dict[str, list[ParseTree]], mismatchedNode: ParseTree + ) -> None: ... + def get(self, label: str): ... + def getAll(self, label: str): ... + def succeeded(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi new file mode 100644 index 000000000000..ef542c0e1288 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcher as ParseTreePatternMatcher +from antlr4.tree.Tree import ParseTree as ParseTree +from antlr4.xpath.XPathLexer import XPathLexer as XPathLexer + +class ParseTreePattern: + __slots__ = ("matcher", "patternRuleIndex", "pattern", "patternTree") + matcher: Incomplete + patternRuleIndex: Incomplete + pattern: Incomplete + patternTree: Incomplete + def __init__(self, matcher: ParseTreePatternMatcher, pattern: str, patternRuleIndex: int, patternTree: ParseTree) -> None: ... + def match(self, tree: ParseTree): ... + def matches(self, tree: ParseTree): ... + def findAll(self, tree: ParseTree, xpath: str): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi new file mode 100644 index 000000000000..0d94f19c0ec0 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete + +from antlr4.CommonTokenStream import CommonTokenStream as CommonTokenStream +from antlr4.error.Errors import ( + ParseCancellationException as ParseCancellationException, + RecognitionException as RecognitionException, +) +from antlr4.error.ErrorStrategy import BailErrorStrategy as BailErrorStrategy +from antlr4.InputStream import InputStream as InputStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.ListTokenSource import ListTokenSource as ListTokenSource +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.Token import Token as Token +from antlr4.tree.Chunk import TagChunk as TagChunk, TextChunk as TextChunk +from antlr4.tree.RuleTagToken import RuleTagToken as RuleTagToken +from antlr4.tree.TokenTagToken import TokenTagToken as TokenTagToken +from antlr4.tree.Tree import ParseTree as ParseTree, RuleNode as RuleNode, TerminalNode as TerminalNode + +Parser: Incomplete +ParseTreePattern: Incomplete + +class CannotInvokeStartRule(Exception): + def __init__(self, e: Exception) -> None: ... + +class StartRuleDoesNotConsumeFullPattern(Exception): ... + +class ParseTreePatternMatcher: + __slots__ = ("lexer", "parser", "start", "stop", "escape") + lexer: Incomplete + parser: Incomplete + start: str + stop: str + escape: str + def __init__(self, lexer: Lexer, parser: Parser) -> None: ... + def setDelimiters(self, start: str, stop: str, escapeLeft: str): ... + def matchesRuleIndex(self, tree: ParseTree, pattern: str, patternRuleIndex: int): ... + def matchesPattern(self, tree: ParseTree, pattern: ParseTreePattern): ... + def matchRuleIndex(self, tree: ParseTree, pattern: str, patternRuleIndex: int): ... + def matchPattern(self, tree: ParseTree, pattern: ParseTreePattern): ... + def compileTreePattern(self, pattern: str, patternRuleIndex: int): ... + def matchImpl(self, tree: ParseTree, patternTree: ParseTree, labels: dict[str, list[ParseTree]]): ... + def map(self, labels, label, tree) -> None: ... + def getRuleTagToken(self, tree: ParseTree): ... + def tokenize(self, pattern: str): ... + def split(self, pattern: str): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi new file mode 100644 index 000000000000..0594ab3c4f37 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from antlr4.Token import Token as Token + +class RuleTagToken(Token): + __slots__ = ("label", "ruleName") + source: Incomplete + type: Incomplete + channel: Incomplete + start: int + stop: int + tokenIndex: int + line: int + column: int + label: Incomplete + ruleName: Incomplete + def __init__(self, ruleName: str, bypassTokenType: int, label: str | None = None) -> None: ... + def getText(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi new file mode 100644 index 000000000000..902d685b8418 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from antlr4.Token import CommonToken as CommonToken + +class TokenTagToken(CommonToken): + __slots__ = ("tokenName", "label") + tokenName: Incomplete + label: Incomplete + def __init__(self, tokenName: str, type: int, label: str | None = None) -> None: ... + def getText(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi new file mode 100644 index 000000000000..0eca91c7d868 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from typing import Any, Literal, TypeVar + +from antlr4.ParserRuleContext import ParserRuleContext, RuleContext +from antlr4.Token import Token as Token + +INVALID_INTERVAL: Incomplete + +class Tree: ... +class SyntaxTree(Tree): ... +class ParseTree(SyntaxTree): ... +class RuleNode(ParseTree): ... +class TerminalNode(ParseTree): ... +class ErrorNode(TerminalNode): ... + +_GenericType = TypeVar("_GenericType", bound=type) + +class ParseTreeVisitor: + def visit(self, tree: Tree) -> None: ... + def visitChildren(self, node) -> None: ... + def visitTerminal(self, node: TerminalNode) -> None: ... + def visitErrorNode(self, node: ErrorNode) -> None: ... + def defaultResult(self) -> None: ... + def aggregateResult(self, aggregate, nextResult: _GenericType) -> _GenericType: ... + def shouldVisitNextChild(self, node, currentResult) -> Literal[True]: ... + +class ParseTreeListener: + def visitTerminal(self, node: TerminalNode) -> None: ... + def visitErrorNode(self, node: ErrorNode) -> None: ... + def enterEveryRule(self, ctx: ParserRuleContext) -> None: ... + def exitEveryRule(self, ctx: ParserRuleContext) -> None: ... + +class TerminalNodeImpl(TerminalNode): + __slots__ = ("parentCtx", "symbol") + parentCtx: RuleContext | None + symbol: Token + def __init__(self, symbol: Token) -> None: ... + def __setattr__(self, key: str, value: Any) -> None: ... + def getChild(self, i: int) -> None: ... + def getSymbol(self) -> Token: ... + def getParent(self) -> RuleContext | None: ... + def getPayload(self) -> Token: ... + def getSourceInterval(self) -> tuple[Literal[-1], Literal[-2]] | tuple[int | None, int | None]: ... + def getChildCount(self) -> Literal[0]: ... + def accept(self, visitor: ParseTreeVisitor) -> None: ... + def getText(self) -> str: ... + +class ErrorNodeImpl(TerminalNodeImpl, ErrorNode): + def __init__(self, token: Token) -> None: ... + def accept(self, visitor: ParseTreeVisitor) -> None: ... + +class ParseTreeWalker: + DEFAULT: ParseTreeWalker + def walk(self, listener: ParseTreeListener, t: ParseTree) -> None: ... + def enterRule(self, listener: ParseTreeListener, r: RuleNode) -> None: ... + def exitRule(self, listener: ParseTreeListener, r: RuleNode) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi new file mode 100644 index 000000000000..896a4f9da254 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ( + ErrorNode as ErrorNode, + ParseTree as ParseTree, + RuleNode as RuleNode, + TerminalNode as TerminalNode, + Tree as Tree, +) +from antlr4.Utils import escapeWhitespace as escapeWhitespace + +Parser: Incomplete + +class Trees: + @classmethod + def toStringTree(cls, t: Tree, ruleNames: list[str] | None = None, recog: Parser | None = None): ... + @classmethod + def getNodeText(cls, t: Tree, ruleNames: list[str] | None = None, recog: Parser | None = None): ... + @classmethod + def getChildren(cls, t: Tree): ... + @classmethod + def getAncestors(cls, t: Tree): ... + @classmethod + def findAllTokenNodes(cls, t: ParseTree, ttype: int): ... + @classmethod + def findAllRuleNodes(cls, t: ParseTree, ruleIndex: int): ... + @classmethod + def findAllNodes(cls, t: ParseTree, index: int, findTokens: bool): ... + @classmethod + def descendants(cls, t: ParseTree): ... diff --git a/stubs/commonmark/commonmark/render/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/__init__.pyi similarity index 100% rename from stubs/commonmark/commonmark/render/__init__.pyi rename to stubs/antlr4-python3-runtime/antlr4/tree/__init__.pyi diff --git a/stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi b/stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi new file mode 100644 index 000000000000..47ede0ad6bae --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete + +from antlr4 import ( + DFA as DFA, + CommonTokenStream as CommonTokenStream, + Lexer as Lexer, + LexerATNSimulator as LexerATNSimulator, + ParserRuleContext as ParserRuleContext, + PredictionContextCache as PredictionContextCache, + TerminalNode as TerminalNode, +) +from antlr4.atn.ATNDeserializer import ATNDeserializer as ATNDeserializer +from antlr4.error.ErrorListener import ErrorListener as ErrorListener +from antlr4.error.Errors import LexerNoViableAltException as LexerNoViableAltException +from antlr4.InputStream import InputStream as InputStream +from antlr4.Parser import Parser as Parser +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ParseTree as ParseTree +from antlr4.tree.Trees import Trees as Trees +from antlr4.xpath.XPathLexer import XPathLexer as XPathLexer + +class XPath: + WILDCARD: str + NOT: str + parser: Incomplete + path: Incomplete + elements: Incomplete + def __init__(self, parser: Parser, path: str) -> None: ... + def split(self, path: str): ... + def getXPathElement(self, wordToken: Token, anywhere: bool): ... + @staticmethod + def findAll(tree: ParseTree, xpath: str, parser: Parser): ... + def evaluate(self, t: ParseTree): ... + +class XPathElement: + nodeName: Incomplete + invert: bool + def __init__(self, nodeName: str) -> None: ... + +class XPathRuleAnywhereElement(XPathElement): + ruleIndex: Incomplete + def __init__(self, ruleName: str, ruleIndex: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathRuleElement(XPathElement): + ruleIndex: Incomplete + def __init__(self, ruleName: str, ruleIndex: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathTokenAnywhereElement(XPathElement): + tokenType: Incomplete + def __init__(self, ruleName: str, tokenType: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathTokenElement(XPathElement): + tokenType: Incomplete + def __init__(self, ruleName: str, tokenType: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathWildcardAnywhereElement(XPathElement): + def __init__(self) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathWildcardElement(XPathElement): + def __init__(self) -> None: ... + def evaluate(self, t: ParseTree): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi b/stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi new file mode 100644 index 000000000000..5aac6033dbf9 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import TextIO + +from antlr4 import * + +def serializedATN(): ... + +class XPathLexer(Lexer): + atn: Incomplete + decisionsToDFA: Incomplete + TOKEN_REF: int + RULE_REF: int + ANYWHERE: int + ROOT: int + WILDCARD: int + BANG: int + ID: int + STRING: int + channelNames: Incomplete + modeNames: Incomplete + literalNames: Incomplete + symbolicNames: Incomplete + ruleNames: Incomplete + grammarFileName: str + def __init__(self, input=None, output: TextIO = ...) -> None: ... + def action(self, localctx: RuleContext, ruleIndex: int, actionIndex: int): ... + type: Incomplete + def ID_action(self, localctx: RuleContext, actionIndex: int): ... diff --git a/stubs/cryptography/cryptography/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/xpath/__init__.pyi similarity index 100% rename from stubs/cryptography/cryptography/__init__.pyi rename to stubs/antlr4-python3-runtime/antlr4/xpath/__init__.pyi diff --git a/stubs/appdirs/METADATA.toml b/stubs/appdirs/METADATA.toml deleted file mode 100644 index 6d3b92238f58..000000000000 --- a/stubs/appdirs/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "1.4.*" diff --git a/stubs/appdirs/appdirs.pyi b/stubs/appdirs/appdirs.pyi deleted file mode 100644 index d7c1c5526b90..000000000000 --- a/stubs/appdirs/appdirs.pyi +++ /dev/null @@ -1,55 +0,0 @@ -__version_info__: tuple[int, int, int] -PY3: bool -unicode = str -system: str - -def user_data_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., roaming: bool = ... -) -> str: ... -def site_data_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., multipath: bool = ... -) -> str: ... -def user_config_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., roaming: bool = ... -) -> str: ... -def site_config_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., multipath: bool = ... -) -> str: ... -def user_cache_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., opinion: bool = ... -) -> str: ... -def user_state_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., roaming: bool = ... -) -> str: ... -def user_log_dir( - appname: str | None = ..., appauthor: str | None = ..., version: str | None = ..., opinion: bool = ... -) -> str: ... - -class AppDirs: - appname: str - appauthor: str - version: str - roaming: bool - multipath: bool - def __init__( - self, - appname: str | None = ..., - appauthor: str | None = ..., - version: str | None = ..., - roaming: bool = ..., - multipath: bool = ..., - ) -> None: ... - @property - def user_data_dir(self) -> str: ... - @property - def site_data_dir(self) -> str: ... - @property - def user_config_dir(self) -> str: ... - @property - def site_config_dir(self) -> str: ... - @property - def user_cache_dir(self) -> str: ... - @property - def user_state_dir(self) -> str: ... - @property - def user_log_dir(self) -> str: ... diff --git a/stubs/assertpy/@tests/stubtest_allowlist.txt b/stubs/assertpy/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..47dccabd33c1 --- /dev/null +++ b/stubs/assertpy/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Python 2 compatibility cruft: +assertpy\..+\.Iterable(\.__class_getitem__)? +assertpy.contains.str_types +assertpy.contains.xrange +assertpy.extracting.str_types +assertpy.file.str_types +assertpy.string.str_types diff --git a/stubs/assertpy/METADATA.toml b/stubs/assertpy/METADATA.toml new file mode 100644 index 000000000000..506bfdd1124b --- /dev/null +++ b/stubs/assertpy/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1.*" +upstream-repository = "https://github.com/assertpy/assertpy" diff --git a/stubs/assertpy/assertpy/__init__.pyi b/stubs/assertpy/assertpy/__init__.pyi new file mode 100644 index 000000000000..1eba206f802f --- /dev/null +++ b/stubs/assertpy/assertpy/__init__.pyi @@ -0,0 +1,12 @@ +from .assertpy import ( + WarningLoggingAdapter as WarningLoggingAdapter, + __version__ as __version__, + add_extension as add_extension, + assert_that as assert_that, + assert_warn as assert_warn, + fail as fail, + remove_extension as remove_extension, + soft_assertions as soft_assertions, + soft_fail as soft_fail, +) +from .file import contents_of as contents_of diff --git a/stubs/assertpy/assertpy/assertpy.pyi b/stubs/assertpy/assertpy/assertpy.pyi new file mode 100644 index 000000000000..922a86dcf426 --- /dev/null +++ b/stubs/assertpy/assertpy/assertpy.pyi @@ -0,0 +1,73 @@ +import logging +from collections.abc import Callable, Generator +from typing import Any, TypeVar +from typing_extensions import Self + +from .base import BaseMixin +from .collection import CollectionMixin +from .contains import ContainsMixin +from .date import DateMixin +from .dict import DictMixin +from .dynamic import DynamicMixin +from .exception import ExceptionMixin +from .extracting import ExtractingMixin +from .file import FileMixin +from .helpers import HelpersMixin +from .numeric import NumericMixin +from .snapshot import SnapshotMixin +from .string import StringMixin + +_T = TypeVar("_T") +_V = TypeVar("_V", default=Any) + +__version__: str +__tracebackhide__: bool + +class WarningLoggingAdapter(logging.LoggerAdapter[logging.Logger]): + def process(self, msg: str, kwargs: _T) -> tuple[str, _T]: ... + +class AssertionBuilder( + StringMixin, + SnapshotMixin, + NumericMixin, + HelpersMixin, + FileMixin, + ExtractingMixin, + ExceptionMixin, + DynamicMixin, + DictMixin, + DateMixin, + ContainsMixin[_V], + CollectionMixin[_V], + BaseMixin, +): + val: _V + description: str + kind: str | None + expected: BaseException | None + logger: logging.Logger + def __init__( + self, + val: _V, + description: str = "", + kind: str | None = None, + expected: BaseException | None = None, + logger: logging.Logger | None = None, + ) -> None: ... + def builder( + self, + val: _V, + description: str = "", + kind: str | None = None, + expected: BaseException | None = None, + logger: logging.Logger | None = None, + ) -> Self: ... + def error(self, msg: str) -> Self: ... + +def soft_assertions() -> Generator[None]: ... +def assert_that(val: _V, description: str = "") -> AssertionBuilder[_V]: ... +def assert_warn(val: _V, description: str = "", logger: logging.Logger | None = None) -> AssertionBuilder: ... +def fail(msg: str = "") -> None: ... +def soft_fail(msg: str = "") -> None: ... +def add_extension(func: Callable[..., AssertionBuilder[Any]]) -> None: ... +def remove_extension(func: Callable[..., AssertionBuilder[Any]]) -> None: ... diff --git a/stubs/assertpy/assertpy/base.pyi b/stubs/assertpy/assertpy/base.pyi new file mode 100644 index 000000000000..56238d4001e3 --- /dev/null +++ b/stubs/assertpy/assertpy/base.pyi @@ -0,0 +1,21 @@ +from typing import TypeAlias +from typing_extensions import Self + +__tracebackhide__: bool + +_IncludeIgnore: TypeAlias = str | list[str] | list[tuple[str, ...]] | None + +class BaseMixin: + description: str + def described_as(self, description: str) -> Self: ... + def is_equal_to(self, other: object, *, include: _IncludeIgnore = None, ignore: _IncludeIgnore = None) -> Self: ... + def is_not_equal_to(self, other: object) -> Self: ... + def is_same_as(self, other: object) -> Self: ... + def is_not_same_as(self, other: object) -> Self: ... + def is_true(self) -> Self: ... + def is_false(self) -> Self: ... + def is_none(self) -> Self: ... + def is_not_none(self) -> Self: ... + def is_type_of(self, some_type: type) -> Self: ... + def is_instance_of(self, some_class: type) -> Self: ... + def is_length(self, length: int) -> Self: ... diff --git a/stubs/assertpy/assertpy/collection.pyi b/stubs/assertpy/assertpy/collection.pyi new file mode 100644 index 000000000000..79cc4d5fb369 --- /dev/null +++ b/stubs/assertpy/assertpy/collection.pyi @@ -0,0 +1,20 @@ +from _typeshed import SupportsRichComparison +from collections.abc import Callable +from typing import Any, Generic, Literal, TypeVar, overload +from typing_extensions import Self + +__tracebackhide__: bool + +_V = TypeVar("_V", default=Any) + +class CollectionMixin(Generic[_V]): + def is_iterable(self) -> Self: ... + def is_not_iterable(self) -> Self: ... + def is_subset_of(self, *supersets: _V) -> Self: ... + + @overload + def is_sorted(self, key: Callable[[_V], SupportsRichComparison] = ..., reverse: Literal[False] = False) -> Self: ... + @overload + def is_sorted(self, *, reverse: Literal[True]) -> Self: ... + @overload + def is_sorted(self, key: Callable[[_V], SupportsRichComparison], reverse: Literal[True]) -> Self: ... diff --git a/stubs/assertpy/assertpy/contains.pyi b/stubs/assertpy/assertpy/contains.pyi new file mode 100644 index 000000000000..6c59d2a5f81a --- /dev/null +++ b/stubs/assertpy/assertpy/contains.pyi @@ -0,0 +1,18 @@ +from typing import Any, Generic, TypeVar +from typing_extensions import Self + +__tracebackhide__: bool + +_V = TypeVar("_V", default=Any) + +class ContainsMixin(Generic[_V]): + def contains(self, *items: object) -> Self: ... + def does_not_contain(self, *items: object) -> Self: ... + def contains_only(self, *items: object) -> Self: ... + def contains_sequence(self, *items: object) -> Self: ... + def contains_duplicates(self) -> Self: ... + def does_not_contain_duplicates(self) -> Self: ... + def is_empty(self) -> Self: ... + def is_not_empty(self) -> Self: ... + def is_in(self, *items: _V) -> Self: ... + def is_not_in(self, *items: _V) -> Self: ... diff --git a/stubs/assertpy/assertpy/date.pyi b/stubs/assertpy/assertpy/date.pyi new file mode 100644 index 000000000000..5377724ef274 --- /dev/null +++ b/stubs/assertpy/assertpy/date.pyi @@ -0,0 +1,11 @@ +from datetime import date +from typing_extensions import Self + +__tracebackhide__: bool + +class DateMixin: + def is_before(self, other: date) -> Self: ... + def is_after(self, other: date) -> Self: ... + def is_equal_to_ignoring_milliseconds(self, other: date) -> Self: ... + def is_equal_to_ignoring_seconds(self, other: date) -> Self: ... + def is_equal_to_ignoring_time(self, other: date) -> Self: ... diff --git a/stubs/assertpy/assertpy/dict.pyi b/stubs/assertpy/assertpy/dict.pyi new file mode 100644 index 000000000000..ac114fb40888 --- /dev/null +++ b/stubs/assertpy/assertpy/dict.pyi @@ -0,0 +1,13 @@ +from typing import Any +from typing_extensions import Self + +__tracebackhide__: bool + +class DictMixin: + def contains_key(self, *keys: object) -> Self: ... + def does_not_contain_key(self, *keys: object) -> Self: ... + def contains_value(self, *values: object) -> Self: ... + def does_not_contain_value(self, *values: object) -> Self: ... + # The dicts can contain arbitrary keys and values + def contains_entry(self, *args: dict[Any, Any], **kwargs: Any) -> Self: ... + def does_not_contain_entry(self, *args: dict[Any, Any], **kwargs: Any) -> Self: ... diff --git a/stubs/assertpy/assertpy/dynamic.pyi b/stubs/assertpy/assertpy/dynamic.pyi new file mode 100644 index 000000000000..681512a565bb --- /dev/null +++ b/stubs/assertpy/assertpy/dynamic.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable +from typing_extensions import Self + +__tracebackhide__: bool + +class DynamicMixin: + def __getattr__(self, attr: str) -> Callable[[object], Self]: ... diff --git a/stubs/assertpy/assertpy/exception.pyi b/stubs/assertpy/assertpy/exception.pyi new file mode 100644 index 000000000000..b1eb47da6915 --- /dev/null +++ b/stubs/assertpy/assertpy/exception.pyi @@ -0,0 +1,9 @@ +from typing import Any +from typing_extensions import Self + +__tracebackhide__: bool + +class ExceptionMixin: + def raises(self, ex: type[BaseException] | BaseException) -> Self: ... + # The types of some_args and some_kwargs must equal the types of the called function. + def when_called_with(self, *some_args: Any, **some_kwargs: Any) -> Self: ... diff --git a/stubs/assertpy/assertpy/extracting.pyi b/stubs/assertpy/assertpy/extracting.pyi new file mode 100644 index 000000000000..00e82fb26beb --- /dev/null +++ b/stubs/assertpy/assertpy/extracting.pyi @@ -0,0 +1,15 @@ +from _typeshed import SupportsRichComparison +from collections.abc import Callable, Iterable, Mapping +from typing import Any +from typing_extensions import Self + +__tracebackhide__: bool + +class ExtractingMixin: + def extracting( + self, + *names: str, + # The callable must accept the type of the items in the self.val collection. + filter: str | Mapping[str, Any] | Callable[[Any], bool] = ..., + sort: str | Iterable[str] | Callable[[Any], SupportsRichComparison] = ..., + ) -> Self: ... diff --git a/stubs/assertpy/assertpy/file.pyi b/stubs/assertpy/assertpy/file.pyi new file mode 100644 index 000000000000..0bcf39525677 --- /dev/null +++ b/stubs/assertpy/assertpy/file.pyi @@ -0,0 +1,14 @@ +from _typeshed import StrPath, SupportsRead +from typing_extensions import Self + +__tracebackhide__: bool + +def contents_of(file: SupportsRead[str] | StrPath, encoding: str = "utf-8") -> str: ... + +class FileMixin: + def exists(self) -> Self: ... + def does_not_exist(self) -> Self: ... + def is_file(self) -> Self: ... + def is_directory(self) -> Self: ... + def is_named(self, filename: str) -> Self: ... + def is_child_of(self, parent: str) -> Self: ... diff --git a/stubs/assertpy/assertpy/helpers.pyi b/stubs/assertpy/assertpy/helpers.pyi new file mode 100644 index 000000000000..3ef068fa325f --- /dev/null +++ b/stubs/assertpy/assertpy/helpers.pyi @@ -0,0 +1,3 @@ +__tracebackhide__: bool + +class HelpersMixin: ... diff --git a/stubs/assertpy/assertpy/numeric.pyi b/stubs/assertpy/assertpy/numeric.pyi new file mode 100644 index 000000000000..cb3a0a372531 --- /dev/null +++ b/stubs/assertpy/assertpy/numeric.pyi @@ -0,0 +1,25 @@ +from datetime import date +from typing import TypeAlias +from typing_extensions import Self + +__tracebackhide__: bool + +_Numeric: TypeAlias = date | int | float + +class NumericMixin: + def is_zero(self) -> Self: ... + def is_not_zero(self) -> Self: ... + def is_nan(self) -> Self: ... + def is_not_nan(self) -> Self: ... + def is_inf(self) -> Self: ... + def is_not_inf(self) -> Self: ... + def is_greater_than(self, other: _Numeric) -> Self: ... + def is_greater_than_or_equal_to(self, other: _Numeric) -> Self: ... + def is_less_than(self, other: _Numeric) -> Self: ... + def is_less_than_or_equal_to(self, other: _Numeric) -> Self: ... + def is_positive(self) -> Self: ... + def is_negative(self) -> Self: ... + def is_between(self, low: _Numeric, high: _Numeric) -> Self: ... + def is_not_between(self, low: _Numeric, high: _Numeric) -> Self: ... + def is_close_to(self, other: _Numeric, tolerance: _Numeric) -> Self: ... + def is_not_close_to(self, other: _Numeric, tolerance: _Numeric) -> Self: ... diff --git a/stubs/assertpy/assertpy/snapshot.pyi b/stubs/assertpy/assertpy/snapshot.pyi new file mode 100644 index 000000000000..2a7abc9fed7b --- /dev/null +++ b/stubs/assertpy/assertpy/snapshot.pyi @@ -0,0 +1,6 @@ +from typing_extensions import Self + +__tracebackhide__: bool + +class SnapshotMixin: + def snapshot(self, id: str | None = None, path: str = "__snapshots") -> Self: ... diff --git a/stubs/assertpy/assertpy/string.pyi b/stubs/assertpy/assertpy/string.pyi new file mode 100644 index 000000000000..4b6c6717cde6 --- /dev/null +++ b/stubs/assertpy/assertpy/string.pyi @@ -0,0 +1,17 @@ +from typing_extensions import Self + +unicode = str +__tracebackhide__: bool + +class StringMixin: + def is_equal_to_ignoring_case(self, other: str) -> Self: ... + def contains_ignoring_case(self, *items: str) -> Self: ... + def starts_with(self, prefix: str) -> Self: ... + def ends_with(self, suffix: str) -> Self: ... + def matches(self, pattern: str) -> Self: ... + def does_not_match(self, pattern: str) -> Self: ... + def is_alpha(self) -> Self: ... + def is_digit(self) -> Self: ... + def is_lower(self) -> Self: ... + def is_upper(self) -> Self: ... + def is_unicode(self) -> Self: ... diff --git a/stubs/atheris/METADATA.toml b/stubs/atheris/METADATA.toml new file mode 100644 index 000000000000..43ba5cf276b1 --- /dev/null +++ b/stubs/atheris/METADATA.toml @@ -0,0 +1,6 @@ +version = "3.1.*" +upstream-repository = "https://github.com/google/atheris" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/atheris/atheris/__init__.pyi b/stubs/atheris/atheris/__init__.pyi new file mode 100644 index 000000000000..2a3312448ab0 --- /dev/null +++ b/stubs/atheris/atheris/__init__.pyi @@ -0,0 +1,9 @@ +from collections.abc import Callable + +def Setup( + args: list[str], + test_one_input: Callable[[bytes], None], + **kwargs: bool | Callable[[bytes, int, int], str | bytes] | Callable[[bytes, bytes, int, int], str | bytes] | None, +) -> list[str]: ... +def Fuzz() -> None: ... +def Mutate(data: bytes, max_size: int) -> bytes: ... diff --git a/stubs/atheris/atheris/function_hooks.pyi b/stubs/atheris/atheris/function_hooks.pyi new file mode 100644 index 000000000000..92ec044b7f0f --- /dev/null +++ b/stubs/atheris/atheris/function_hooks.pyi @@ -0,0 +1,14 @@ +from typing import Any + +def hook_re_module() -> None: ... + +class EnabledHooks: + def __init__(self) -> None: ... + def add(self, hook: str) -> None: ... + def __contains__(self, hook: str) -> bool: ... + +enabled_hooks: EnabledHooks + +# args[1] is an arbitrary string method that is called +# with the subsequent arguments, so they will vary +def _hook_str(*args: Any, **kwargs: Any) -> bool: ... diff --git a/stubs/atheris/atheris/import_hook.pyi b/stubs/atheris/atheris/import_hook.pyi new file mode 100644 index 000000000000..450923a31de9 --- /dev/null +++ b/stubs/atheris/atheris/import_hook.pyi @@ -0,0 +1,36 @@ +import types +from collections.abc import Sequence +from importlib import abc, machinery +from typing_extensions import Self + +def _should_skip(loader: abc.Loader) -> bool: ... + +class AtherisMetaPathFinder(abc.MetaPathFinder): + def __init__( + self, include_packages: set[str], exclude_modules: set[str], enable_loader_override: bool, trace_dataflow: bool + ) -> None: ... + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = None + ) -> machinery.ModuleSpec | None: ... + def invalidate_caches(self) -> None: ... + +class AtherisSourceFileLoader: + def __init__(self, name: str, path: str, trace_dataflow: bool) -> None: ... + def get_code(self, fullname: str) -> types.CodeType | None: ... + +class AtherisSourcelessFileLoader: + def __init__(self, name: str, path: str, trace_dataflow: bool) -> None: ... + def get_code(self, fullname: str) -> types.CodeType | None: ... + +def make_dynamic_atheris_loader(loader: abc.Loader | type[abc.Loader], trace_dataflow: bool) -> abc.Loader: ... + +class HookManager: + def __init__( + self, include_packages: set[str], exclude_modules: set[str], enable_loader_override: bool, trace_dataflow: bool + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +def instrument_imports( + include: Sequence[str] | None = None, exclude: Sequence[str] | None = None, enable_loader_override: bool = True +) -> HookManager: ... diff --git a/stubs/atheris/atheris/instrument_bytecode.pyi b/stubs/atheris/atheris/instrument_bytecode.pyi new file mode 100644 index 000000000000..b6b935fd1c3b --- /dev/null +++ b/stubs/atheris/atheris/instrument_bytecode.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable +from typing import TypeVar + +_T = TypeVar("_T") + +def instrument_func(func: Callable[..., _T]) -> Callable[..., _T]: ... +def instrument_all() -> None: ... diff --git a/stubs/atheris/atheris/utils.pyi b/stubs/atheris/atheris/utils.pyi new file mode 100644 index 000000000000..481d9880b02b --- /dev/null +++ b/stubs/atheris/atheris/utils.pyi @@ -0,0 +1,20 @@ +from typing import Protocol, type_check_only + +def path() -> str: ... + +@type_check_only +class _Writer(Protocol): + def isatty(self) -> bool: ... + def write(self, content: str, /) -> object: ... + def flush(self) -> object: ... + +class ProgressRenderer: + def __init__(self, stream: _Writer, total_count: int) -> None: ... + def render(self) -> None: ... + def erase(self) -> None: ... + def drop(self) -> None: ... + + @property + def count(self) -> int: ... + @count.setter + def count(self, new_count: int) -> None: ... diff --git a/stubs/atheris/atheris/version_dependent.pyi b/stubs/atheris/atheris/version_dependent.pyi new file mode 100644 index 000000000000..eba864764ec9 --- /dev/null +++ b/stubs/atheris/atheris/version_dependent.pyi @@ -0,0 +1,32 @@ +import types +from typing import Final + +PYTHON_VERSION: Final[tuple[int, int]] +CONDITIONAL_JUMPS: Final[list[str]] +UNCONDITIONAL_JUMPS: Final[list[str]] +ENDS_FUNCTION: Final[list[str]] +HAVE_REL_REFERENCE: Final[list[str]] +HAVE_ABS_REFERENCE: Final[list[str]] +REL_REFERENCE_IS_INVERTED: Final[list[str]] + +def rel_reference_scale(opname: str) -> int: ... + +REVERSE_CMP_OP: Final[list[int]] + +def jump_arg_bytes(arg: int) -> int: ... +def add_bytes_to_jump_arg(arg: int, size: int) -> int: ... + +class ExceptionTableEntry: + def __init__(self, start_offset: int, end_offset: int, target: int, depth: int, lasti: bool) -> None: ... + def __eq__(self, other: object) -> bool: ... + +class ExceptionTable: + def __init__(self, entries: list[ExceptionTableEntry]) -> None: ... + def __eq__(self, other: object) -> bool: ... + +def generate_exceptiontable(original_code: types.CodeType, exception_table_entries: list[ExceptionTableEntry]) -> bytes: ... + +CONST_PUSH_INSTRS: Final[set[str]] + +def is_func_start_resume(opname: str, arg: int | None) -> bool: ... +def has_argument(op: int) -> bool: ... diff --git a/stubs/atomicwrites/@tests/stubtest_allowlist.txt b/stubs/atomicwrites/@tests/stubtest_allowlist.txt deleted file mode 100644 index 3bf9df36c7d2..000000000000 --- a/stubs/atomicwrites/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1 +0,0 @@ -atomicwrites.AtomicWriter.get_fileobject diff --git a/stubs/atomicwrites/METADATA.toml b/stubs/atomicwrites/METADATA.toml deleted file mode 100644 index e20445253656..000000000000 --- a/stubs/atomicwrites/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "1.4.*" -python2 = true diff --git a/stubs/atomicwrites/atomicwrites/__init__.pyi b/stubs/atomicwrites/atomicwrites/__init__.pyi deleted file mode 100644 index 388ac27182fe..000000000000 --- a/stubs/atomicwrites/atomicwrites/__init__.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from _typeshed import StrOrBytesPath -from typing import IO, Any, AnyStr, Callable, ContextManager, Text, Type - -def replace_atomic(src: AnyStr, dst: AnyStr) -> None: ... -def move_atomic(src: AnyStr, dst: AnyStr) -> None: ... - -class AtomicWriter(object): - def __init__(self, path: StrOrBytesPath, mode: Text = ..., overwrite: bool = ...) -> None: ... - def open(self) -> ContextManager[IO[Any]]: ... - def _open(self, get_fileobject: Callable[..., IO[AnyStr]]) -> ContextManager[IO[AnyStr]]: ... - def get_fileobject(self, dir: StrOrBytesPath | None = ..., **kwargs: Any) -> IO[Any]: ... - def sync(self, f: IO[Any]) -> None: ... - def commit(self, f: IO[Any]) -> None: ... - def rollback(self, f: IO[Any]) -> None: ... - -def atomic_write(path: StrOrBytesPath, writer_cls: Type[AtomicWriter] = ..., **cls_kwargs: object) -> ContextManager[IO[Any]]: ... diff --git a/stubs/auth0-python/@tests/stubtest_allowlist.txt b/stubs/auth0-python/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..8ebe98654c0b --- /dev/null +++ b/stubs/auth0-python/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Omit tests +auth0\.test.* + +# Omit _async functions because they aren't present at runtime +# The way these stubs are currently implemented is that we pretend all classes have async methods +# Even though in reality, users need to call `auth0.asyncify.asyncify` to generate async subclasses +auth0\..*_async diff --git a/stubs/auth0-python/METADATA.toml b/stubs/auth0-python/METADATA.toml new file mode 100644 index 000000000000..f05b227f3dd9 --- /dev/null +++ b/stubs/auth0-python/METADATA.toml @@ -0,0 +1,4 @@ +version = "4.10.*" +upstream-repository = "https://github.com/auth0/auth0-python" +dependencies = ["cryptography", "types-requests"] +obsolete-since = { version = "5.4.0", date = "2026-05-04" } diff --git a/stubs/auth0-python/auth0/__init__.pyi b/stubs/auth0-python/auth0/__init__.pyi new file mode 100644 index 000000000000..48e8b1da8e62 --- /dev/null +++ b/stubs/auth0-python/auth0/__init__.pyi @@ -0,0 +1,3 @@ +from auth0.exceptions import Auth0Error, RateLimitError, TokenValidationError + +__all__ = ("Auth0Error", "RateLimitError", "TokenValidationError") diff --git a/stubs/auth0-python/auth0/asyncify.pyi b/stubs/auth0-python/auth0/asyncify.pyi new file mode 100644 index 000000000000..c4109958aad6 --- /dev/null +++ b/stubs/auth0-python/auth0/asyncify.pyi @@ -0,0 +1,6 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +# See note in stubs/auth0-python/@tests/stubtest_allowlist.txt about _async methods +def asyncify(cls: type[_T]) -> type[_T]: ... diff --git a/stubs/auth0-python/auth0/authentication/__init__.pyi b/stubs/auth0-python/auth0/authentication/__init__.pyi new file mode 100644 index 000000000000..24384af11585 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/__init__.pyi @@ -0,0 +1,10 @@ +from .database import Database +from .delegated import Delegated +from .enterprise import Enterprise +from .get_token import GetToken +from .passwordless import Passwordless +from .revoke_token import RevokeToken +from .social import Social +from .users import Users + +__all__ = ("Database", "Delegated", "Enterprise", "GetToken", "Passwordless", "RevokeToken", "Social", "Users") diff --git a/stubs/auth0-python/auth0/authentication/async_token_verifier.pyi b/stubs/auth0-python/auth0/authentication/async_token_verifier.pyi new file mode 100644 index 000000000000..5b18760b06b2 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/async_token_verifier.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from .token_verifier import AsymmetricSignatureVerifier, JwksFetcher, TokenVerifier + +class AsyncAsymmetricSignatureVerifier(AsymmetricSignatureVerifier): + def __init__(self, jwks_url: str, algorithm: str = "RS256") -> None: ... + def set_session(self, session) -> None: ... + +class AsyncJwksFetcher(JwksFetcher): + def __init__(self, *args, **kwargs) -> None: ... + def set_session(self, session) -> None: ... + async def get_key(self, key_id: str): ... + +class AsyncTokenVerifier(TokenVerifier): + iss: str + aud: str + leeway: int + def __init__( + self, signature_verifier: AsyncAsymmetricSignatureVerifier, issuer: str, audience: str, leeway: int = 0 + ) -> None: ... + def set_session(self, session) -> None: ... + async def verify( # type: ignore[override] # Differs from supertype + self, token: str, nonce: str | None = None, max_age: int | None = None, organization: str | None = None + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/authentication/back_channel_login.pyi b/stubs/auth0-python/auth0/authentication/back_channel_login.pyi new file mode 100644 index 000000000000..0f5004a431ad --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/back_channel_login.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from .base import AuthenticationBase + +class BackChannelLogin(AuthenticationBase): + def back_channel_login( + self, + binding_message: str, + login_hint: str, + scope: str, + authorization_details: str | list[dict[str, Incomplete]] | None = None, + **kwargs, + ): ... diff --git a/stubs/auth0-python/auth0/authentication/base.pyi b/stubs/auth0-python/auth0/authentication/base.pyi new file mode 100644 index 000000000000..ca603c1dabb3 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/base.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from typing import Final + +from auth0.rest import RestClient +from auth0.types import RequestData + +UNKNOWN_ERROR: Final[str] + +class AuthenticationBase: + domain: str + client_id: str + client_secret: str | None + client_assertion_signing_key: str | None + client_assertion_signing_alg: str | None + protocol: str + client: RestClient + def __init__( + self, + domain: str, + client_id: str, + client_secret: str | None = None, + client_assertion_signing_key: str | None = None, + client_assertion_signing_alg: str | None = None, + telemetry: bool = True, + timeout: float | tuple[float, float] = 5.0, + protocol: str = "https", + ) -> None: ... + def post(self, url: str, data: RequestData | None = None, headers: dict[str, str] | None = None): ... + def authenticated_post(self, url: str, data: dict[str, Incomplete], headers: dict[str, str] | None = None): ... + def get(self, url: str, params: dict[str, Incomplete] | None = None, headers: dict[str, str] | None = None): ... diff --git a/stubs/auth0-python/auth0/authentication/client_authentication.pyi b/stubs/auth0-python/auth0/authentication/client_authentication.pyi new file mode 100644 index 000000000000..e75647fe00f5 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/client_authentication.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +def create_client_assertion_jwt( + domain: str, client_id: str, client_assertion_signing_key: str, client_assertion_signing_alg: str | None +) -> str: ... +def add_client_authentication( + payload: dict[str, Incomplete], + domain: str, + client_id: str, + client_secret: str | None, + client_assertion_signing_key: str | None, + client_assertion_signing_alg: str | None, +) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/authentication/database.pyi b/stubs/auth0-python/auth0/authentication/database.pyi new file mode 100644 index 000000000000..f5ed2a558afc --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/database.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from .base import AuthenticationBase + +class Database(AuthenticationBase): + def signup( + self, + email: str, + password: str, + connection: str, + username: str | None = None, + user_metadata: dict[str, Incomplete] | None = None, + given_name: str | None = None, + family_name: str | None = None, + name: str | None = None, + nickname: str | None = None, + picture: str | None = None, + ) -> dict[str, Incomplete]: ... + def change_password( + self, email: str, connection: str, password: str | None = None, organization: str | None = None + ) -> str: ... diff --git a/stubs/auth0-python/auth0/authentication/delegated.pyi b/stubs/auth0-python/auth0/authentication/delegated.pyi new file mode 100644 index 000000000000..5be5035f3ac9 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/delegated.pyi @@ -0,0 +1,12 @@ +from .base import AuthenticationBase + +class Delegated(AuthenticationBase): + def get_token( + self, + target: str, + api_type: str, + grant_type: str, + id_token: str | None = None, + refresh_token: str | None = None, + scope: str = "openid", + ): ... diff --git a/stubs/auth0-python/auth0/authentication/enterprise.pyi b/stubs/auth0-python/auth0/authentication/enterprise.pyi new file mode 100644 index 000000000000..0b205ebdb83f --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/enterprise.pyi @@ -0,0 +1,5 @@ +from .base import AuthenticationBase + +class Enterprise(AuthenticationBase): + def saml_metadata(self): ... + def wsfed_metadata(self): ... diff --git a/stubs/auth0-python/auth0/authentication/get_token.pyi b/stubs/auth0-python/auth0/authentication/get_token.pyi new file mode 100644 index 000000000000..5308543ca245 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/get_token.pyi @@ -0,0 +1,29 @@ +from .base import AuthenticationBase + +class GetToken(AuthenticationBase): + def authorization_code(self, code: str, redirect_uri: str | None, grant_type: str = "authorization_code"): ... + def authorization_code_pkce( + self, code_verifier: str, code: str, redirect_uri: str | None, grant_type: str = "authorization_code" + ): ... + def client_credentials(self, audience: str, grant_type: str = "client_credentials", organization: str | None = None): ... + def login( + self, + username: str, + password: str, + scope: str | None = None, + realm: str | None = None, + audience: str | None = None, + grant_type: str = "http://auth0.com/oauth/grant-type/password-realm", + forwarded_for: str | None = None, + ): ... + def refresh_token(self, refresh_token: str, scope: str = "", grant_type: str = "refresh_token"): ... + def passwordless_login(self, username: str, otp: str, realm: str, scope: str, audience: str): ... + def backchannel_login(self, auth_req_id: str, grant_type: str = "urn:openid:params:grant-type:ciba"): ... + def access_token_for_connection( + self, + subject_token_type: str, + subject_token: str, + requested_token_type: str, + connection: str | None = None, + grant_type: str = ..., + ): ... diff --git a/stubs/auth0-python/auth0/authentication/passwordless.pyi b/stubs/auth0-python/auth0/authentication/passwordless.pyi new file mode 100644 index 000000000000..aac13339a26c --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/passwordless.pyi @@ -0,0 +1,5 @@ +from .base import AuthenticationBase + +class Passwordless(AuthenticationBase): + def email(self, email: str, send: str = "link", auth_params: dict[str, str] | None = None): ... + def sms(self, phone_number: str): ... diff --git a/stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi b/stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi new file mode 100644 index 000000000000..6d0f0193c2ae --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi @@ -0,0 +1,4 @@ +from .base import AuthenticationBase + +class PushedAuthorizationRequests(AuthenticationBase): + def pushed_authorization_request(self, response_type: str, redirect_uri: str, **kwargs): ... diff --git a/stubs/auth0-python/auth0/authentication/revoke_token.pyi b/stubs/auth0-python/auth0/authentication/revoke_token.pyi new file mode 100644 index 000000000000..8a26618fdbe7 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/revoke_token.pyi @@ -0,0 +1,4 @@ +from .base import AuthenticationBase + +class RevokeToken(AuthenticationBase): + def revoke_refresh_token(self, token: str): ... diff --git a/stubs/auth0-python/auth0/authentication/social.pyi b/stubs/auth0-python/auth0/authentication/social.pyi new file mode 100644 index 000000000000..c17a225c507b --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/social.pyi @@ -0,0 +1,4 @@ +from .base import AuthenticationBase + +class Social(AuthenticationBase): + def login(self, access_token: str, connection: str, scope: str = "openid"): ... diff --git a/stubs/auth0-python/auth0/authentication/token_verifier.pyi b/stubs/auth0-python/auth0/authentication/token_verifier.pyi new file mode 100644 index 000000000000..8ce69a71fa9d --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/token_verifier.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from typing import ClassVar + +class SignatureVerifier: + DISABLE_JWT_CHECKS: ClassVar[dict[str, bool]] + def __init__(self, algorithm: str) -> None: ... + async def verify_signature(self, token: str) -> dict[str, Incomplete]: ... + +class SymmetricSignatureVerifier(SignatureVerifier): + def __init__(self, shared_secret: str, algorithm: str = "HS256") -> None: ... + +class JwksFetcher: + CACHE_TTL: ClassVar[int] + def __init__(self, jwks_url: str, cache_ttl: int = 600) -> None: ... + def get_key(self, key_id: str): ... + +class AsymmetricSignatureVerifier(SignatureVerifier): + def __init__(self, jwks_url: str, algorithm: str = "RS256", cache_ttl: int = 600) -> None: ... + +class TokenVerifier: + iss: str + aud: str + leeway: int + def __init__(self, signature_verifier: SignatureVerifier, issuer: str, audience: str, leeway: int = 0) -> None: ... + def verify( + self, token: str, nonce: str | None = None, max_age: int | None = None, organization: str | None = None + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/authentication/users.pyi b/stubs/auth0-python/auth0/authentication/users.pyi new file mode 100644 index 000000000000..3484f5f98e78 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/users.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from auth0.rest import RestClient +from auth0.types import TimeoutType + +class Users: + domain: str + protocol: str + client: RestClient + def __init__(self, domain: str, telemetry: bool = True, timeout: TimeoutType = 5.0, protocol: str = "https") -> None: ... + def userinfo(self, access_token: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/exceptions.pyi b/stubs/auth0-python/auth0/exceptions.pyi new file mode 100644 index 000000000000..608d6bb013f7 --- /dev/null +++ b/stubs/auth0-python/auth0/exceptions.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class Auth0Error(Exception): + status_code: int + error_code: str + message: str + content: Incomplete | None + def __init__(self, status_code: int, error_code: str, message: str, content=None) -> None: ... + +class RateLimitError(Auth0Error): + reset_at: int + def __init__(self, error_code: str, message: str, reset_at: int) -> None: ... + +class TokenValidationError(Exception): ... diff --git a/stubs/auth0-python/auth0/management/__init__.pyi b/stubs/auth0-python/auth0/management/__init__.pyi new file mode 100644 index 000000000000..ef02c99b9d43 --- /dev/null +++ b/stubs/auth0-python/auth0/management/__init__.pyi @@ -0,0 +1,65 @@ +from .actions import Actions +from .attack_protection import AttackProtection +from .auth0 import Auth0 +from .blacklists import Blacklists +from .branding import Branding +from .client_credentials import ClientCredentials +from .client_grants import ClientGrants +from .clients import Clients +from .connections import Connections +from .custom_domains import CustomDomains +from .device_credentials import DeviceCredentials +from .email_templates import EmailTemplates +from .emails import Emails +from .grants import Grants +from .guardian import Guardian +from .hooks import Hooks +from .jobs import Jobs +from .log_streams import LogStreams +from .logs import Logs +from .organizations import Organizations +from .resource_servers import ResourceServers +from .roles import Roles +from .rules import Rules +from .rules_configs import RulesConfigs +from .self_service_profiles import SelfServiceProfiles +from .stats import Stats +from .tenants import Tenants +from .tickets import Tickets +from .user_blocks import UserBlocks +from .users import Users +from .users_by_email import UsersByEmail + +__all__ = ( + "Auth0", + "Actions", + "AttackProtection", + "Blacklists", + "Branding", + "ClientCredentials", + "ClientGrants", + "Clients", + "Connections", + "CustomDomains", + "DeviceCredentials", + "EmailTemplates", + "Emails", + "Grants", + "Guardian", + "Hooks", + "Jobs", + "LogStreams", + "Logs", + "Organizations", + "ResourceServers", + "Roles", + "RulesConfigs", + "Rules", + "SelfServiceProfiles", + "Stats", + "Tenants", + "Tickets", + "UserBlocks", + "UsersByEmail", + "Users", +) diff --git a/stubs/auth0-python/auth0/management/actions.pyi b/stubs/auth0-python/auth0/management/actions.pyi new file mode 100644 index 000000000000..8c8179c20c82 --- /dev/null +++ b/stubs/auth0-python/auth0/management/actions.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Actions: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get_actions( + self, + trigger_id: str | None = None, + action_name: str | None = None, + deployed: bool | None = None, + installed: bool = False, + page: int | None = None, + per_page: int | None = None, + ): ... + async def get_actions_async( + self, + trigger_id: str | None = None, + action_name: str | None = None, + deployed: bool | None = None, + installed: bool = False, + page: int | None = None, + per_page: int | None = None, + ): ... + def create_action(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_action_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_action(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_action_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_action(self, id: str) -> dict[str, Incomplete]: ... + async def get_action_async(self, id: str) -> dict[str, Incomplete]: ... + def delete_action(self, id: str, force: bool = False): ... + async def delete_action_async(self, id: str, force: bool = False): ... + def get_triggers(self) -> dict[str, Incomplete]: ... + async def get_triggers_async(self) -> dict[str, Incomplete]: ... + def get_execution(self, id: str) -> dict[str, Incomplete]: ... + async def get_execution_async(self, id: str) -> dict[str, Incomplete]: ... + def get_action_versions(self, id: str, page: int | None = None, per_page: int | None = None) -> dict[str, Incomplete]: ... + async def get_action_versions_async( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> dict[str, Incomplete]: ... + def get_trigger_bindings(self, id: str, page: int | None = None, per_page: int | None = None) -> dict[str, Incomplete]: ... + async def get_trigger_bindings_async( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> dict[str, Incomplete]: ... + def get_action_version(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + async def get_action_version_async(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + def deploy_action(self, id: str) -> dict[str, Incomplete]: ... + async def deploy_action_async(self, id: str) -> dict[str, Incomplete]: ... + def rollback_action_version(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + async def rollback_action_version_async(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + def update_trigger_bindings(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_trigger_bindings_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/async_auth0.pyi b/stubs/auth0-python/auth0/management/async_auth0.pyi new file mode 100644 index 000000000000..f73b2a97fbd7 --- /dev/null +++ b/stubs/auth0-python/auth0/management/async_auth0.pyi @@ -0,0 +1,76 @@ +from types import TracebackType +from typing_extensions import Self + +from auth0.rest import RestClientOptions + +from .actions import Actions +from .attack_protection import AttackProtection +from .blacklists import Blacklists +from .branding import Branding +from .client_credentials import ClientCredentials +from .client_grants import ClientGrants +from .clients import Clients +from .connections import Connections +from .custom_domains import CustomDomains +from .device_credentials import DeviceCredentials +from .email_templates import EmailTemplates +from .emails import Emails +from .grants import Grants +from .guardian import Guardian +from .hooks import Hooks +from .jobs import Jobs +from .log_streams import LogStreams +from .logs import Logs +from .organizations import Organizations +from .prompts import Prompts +from .resource_servers import ResourceServers +from .roles import Roles +from .rules import Rules +from .rules_configs import RulesConfigs +from .stats import Stats +from .tenants import Tenants +from .tickets import Tickets +from .user_blocks import UserBlocks +from .users import Users +from .users_by_email import UsersByEmail + +class AsyncAuth0: + def __init__(self, domain: str, token: str, rest_options: RestClientOptions | None = None) -> None: ... + def set_session(self, session) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + + # Same attributes as Auth0 + # See note in stubs/auth0-python/@tests/stubtest_allowlist.txt about _async methods + actions: Actions + attack_protection: AttackProtection + blacklists: Blacklists + branding: Branding + client_credentials: ClientCredentials + client_grants: ClientGrants + clients: Clients + connections: Connections + custom_domains: CustomDomains + device_credentials: DeviceCredentials + email_templates: EmailTemplates + emails: Emails + grants: Grants + guardian: Guardian + hooks: Hooks + jobs: Jobs + log_streams: LogStreams + logs: Logs + organizations: Organizations + prompts: Prompts + resource_servers: ResourceServers + roles: Roles + rules_configs: RulesConfigs + rules: Rules + stats: Stats + tenants: Tenants + tickets: Tickets + user_blocks: UserBlocks + users_by_email: UsersByEmail + users: Users diff --git a/stubs/auth0-python/auth0/management/attack_protection.pyi b/stubs/auth0-python/auth0/management/attack_protection.pyi new file mode 100644 index 000000000000..d87701e522c7 --- /dev/null +++ b/stubs/auth0-python/auth0/management/attack_protection.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class AttackProtection: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get_breached_password_detection(self) -> dict[str, Incomplete]: ... + async def get_breached_password_detection_async(self) -> dict[str, Incomplete]: ... + def update_breached_password_detection(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_breached_password_detection_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_brute_force_protection(self) -> dict[str, Incomplete]: ... + async def get_brute_force_protection_async(self) -> dict[str, Incomplete]: ... + def update_brute_force_protection(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_brute_force_protection_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_suspicious_ip_throttling(self) -> dict[str, Incomplete]: ... + async def get_suspicious_ip_throttling_async(self) -> dict[str, Incomplete]: ... + def update_suspicious_ip_throttling(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_suspicious_ip_throttling_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/auth0.pyi b/stubs/auth0-python/auth0/management/auth0.pyi new file mode 100644 index 000000000000..817d1700cc93 --- /dev/null +++ b/stubs/auth0-python/auth0/management/auth0.pyi @@ -0,0 +1,67 @@ +from auth0.rest import RestClientOptions + +from .actions import Actions +from .attack_protection import AttackProtection +from .blacklists import Blacklists +from .branding import Branding +from .client_credentials import ClientCredentials +from .client_grants import ClientGrants +from .clients import Clients +from .connections import Connections +from .custom_domains import CustomDomains +from .device_credentials import DeviceCredentials +from .email_templates import EmailTemplates +from .emails import Emails +from .grants import Grants +from .guardian import Guardian +from .hooks import Hooks +from .jobs import Jobs +from .log_streams import LogStreams +from .logs import Logs +from .organizations import Organizations +from .prompts import Prompts +from .resource_servers import ResourceServers +from .roles import Roles +from .rules import Rules +from .rules_configs import RulesConfigs +from .self_service_profiles import SelfServiceProfiles +from .stats import Stats +from .tenants import Tenants +from .tickets import Tickets +from .user_blocks import UserBlocks +from .users import Users +from .users_by_email import UsersByEmail + +class Auth0: + actions: Actions + attack_protection: AttackProtection + blacklists: Blacklists + branding: Branding + client_credentials: ClientCredentials + client_grants: ClientGrants + clients: Clients + connections: Connections + custom_domains: CustomDomains + device_credentials: DeviceCredentials + email_templates: EmailTemplates + emails: Emails + grants: Grants + guardian: Guardian + hooks: Hooks + jobs: Jobs + log_streams: LogStreams + logs: Logs + organizations: Organizations + prompts: Prompts + resource_servers: ResourceServers + roles: Roles + rules_configs: RulesConfigs + rules: Rules + self_service_profiles: SelfServiceProfiles + stats: Stats + tenants: Tenants + tickets: Tickets + user_blocks: UserBlocks + users_by_email: UsersByEmail + users: Users + def __init__(self, domain: str, token: str, rest_options: RestClientOptions | None = None) -> None: ... diff --git a/stubs/auth0-python/auth0/management/blacklists.pyi b/stubs/auth0-python/auth0/management/blacklists.pyi new file mode 100644 index 000000000000..b2793ec1272d --- /dev/null +++ b/stubs/auth0-python/auth0/management/blacklists.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Blacklists: + url: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, aud: str | None = None) -> list[dict[str, str]]: ... + async def get_async(self, aud: str | None = None) -> list[dict[str, str]]: ... + def create(self, jti: str, aud: str | None = None) -> dict[str, str]: ... + async def create_async(self, jti: str, aud: str | None = None) -> dict[str, str]: ... diff --git a/stubs/auth0-python/auth0/management/branding.pyi b/stubs/auth0-python/auth0/management/branding.pyi new file mode 100644 index 000000000000..8350d1a8267f --- /dev/null +++ b/stubs/auth0-python/auth0/management/branding.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Branding: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self) -> dict[str, Incomplete]: ... + async def get_async(self) -> dict[str, Incomplete]: ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_template_universal_login(self) -> dict[str, Incomplete]: ... + async def get_template_universal_login_async(self) -> dict[str, Incomplete]: ... + def delete_template_universal_login(self): ... + async def delete_template_universal_login_async(self): ... + def update_template_universal_login(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_template_universal_login_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_default_branding_theme(self) -> dict[str, Incomplete]: ... + async def get_default_branding_theme_async(self) -> dict[str, Incomplete]: ... + def get_branding_theme(self, theme_id: str) -> dict[str, Incomplete]: ... + async def get_branding_theme_async(self, theme_id: str) -> dict[str, Incomplete]: ... + def delete_branding_theme(self, theme_id: str): ... + async def delete_branding_theme_async(self, theme_id: str): ... + def update_branding_theme(self, theme_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_branding_theme_async(self, theme_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def create_branding_theme(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_branding_theme_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/client_credentials.pyi b/stubs/auth0-python/auth0/management/client_credentials.pyi new file mode 100644 index 000000000000..107534317423 --- /dev/null +++ b/stubs/auth0-python/auth0/management/client_credentials.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class ClientCredentials: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self, client_id: str) -> list[dict[str, Incomplete]]: ... + async def all_async(self, client_id: str) -> list[dict[str, Incomplete]]: ... + def get(self, client_id: str, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, client_id: str, id: str) -> dict[str, Incomplete]: ... + def create(self, client_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, client_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, client_id: str, id: str) -> dict[str, Incomplete]: ... + async def delete_async(self, client_id: str, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/client_grants.pyi b/stubs/auth0-python/auth0/management/client_grants.pyi new file mode 100644 index 000000000000..1938b8c2f29c --- /dev/null +++ b/stubs/auth0-python/auth0/management/client_grants.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class ClientGrants: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + audience: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + client_id: str | None = None, + allow_any_organization: bool | None = None, + ) -> dict[str, Incomplete]: ... + async def all_async( + self, + audience: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + client_id: str | None = None, + allow_any_organization: bool | None = None, + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_organizations( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + async def get_organizations_async( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/clients.pyi b/stubs/auth0-python/auth0/management/clients.pyi new file mode 100644 index 000000000000..21358fc59ddf --- /dev/null +++ b/stubs/auth0-python/auth0/management/clients.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Clients: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + ) -> list[dict[str, Incomplete]]: ... + async def all_async( + self, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + ) -> list[dict[str, Incomplete]]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def rotate_secret(self, id: str) -> dict[str, Incomplete]: ... + async def rotate_secret_async(self, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/connections.pyi b/stubs/auth0-python/auth0/management/connections.pyi new file mode 100644 index 000000000000..69caf1afa4ee --- /dev/null +++ b/stubs/auth0-python/auth0/management/connections.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Connections: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + strategy: str | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + name: str | None = None, + ) -> list[dict[str, Incomplete]]: ... + async def all_async( + self, + strategy: str | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + name: str | None = None, + ) -> list[dict[str, Incomplete]]: ... + def get(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_user_by_email(self, id: str, email: str): ... + async def delete_user_by_email_async(self, id: str, email: str): ... diff --git a/stubs/auth0-python/auth0/management/custom_domains.pyi b/stubs/auth0-python/auth0/management/custom_domains.pyi new file mode 100644 index 000000000000..e6e05a81e5cc --- /dev/null +++ b/stubs/auth0-python/auth0/management/custom_domains.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class CustomDomains: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self) -> list[dict[str, Incomplete]]: ... + async def all_async(self) -> list[dict[str, Incomplete]]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def create_new(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_new_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def verify(self, id: str) -> dict[str, Incomplete]: ... + async def verify_async(self, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/device_credentials.pyi b/stubs/auth0-python/auth0/management/device_credentials.pyi new file mode 100644 index 000000000000..a89bfa418fe0 --- /dev/null +++ b/stubs/auth0-python/auth0/management/device_credentials.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class DeviceCredentials: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get( + self, + user_id: str, + client_id: str, + type: str, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + async def get_async( + self, + user_id: str, + client_id: str, + type: str, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... diff --git a/stubs/auth0-python/auth0/management/email_templates.pyi b/stubs/auth0-python/auth0/management/email_templates.pyi new file mode 100644 index 000000000000..17e9b9c6c11d --- /dev/null +++ b/stubs/auth0-python/auth0/management/email_templates.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class EmailTemplates: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, template_name: str) -> dict[str, Incomplete]: ... + async def get_async(self, template_name: str) -> dict[str, Incomplete]: ... + def update(self, template_name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, template_name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/emails.pyi b/stubs/auth0-python/auth0/management/emails.pyi new file mode 100644 index 000000000000..24421140bd5b --- /dev/null +++ b/stubs/auth0-python/auth0/management/emails.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Emails: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def config(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def config_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self): ... + async def delete_async(self): ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/grants.pyi b/stubs/auth0-python/auth0/management/grants.pyi new file mode 100644 index 000000000000..7354186fd494 --- /dev/null +++ b/stubs/auth0-python/auth0/management/grants.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Grants: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + extra_params: dict[str, Incomplete] | None = None, + ): ... + async def all_async( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + extra_params: dict[str, Incomplete] | None = None, + ): ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... diff --git a/stubs/auth0-python/auth0/management/guardian.pyi b/stubs/auth0-python/auth0/management/guardian.pyi new file mode 100644 index 000000000000..4614fb344f4c --- /dev/null +++ b/stubs/auth0-python/auth0/management/guardian.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Guardian: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all_factors(self) -> list[dict[str, Incomplete]]: ... + async def all_factors_async(self) -> list[dict[str, Incomplete]]: ... + def update_factor(self, name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_factor_async(self, name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_templates(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_templates_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_templates(self) -> dict[str, Incomplete]: ... + async def get_templates_async(self) -> dict[str, Incomplete]: ... + def get_enrollment(self, id: str) -> dict[str, Incomplete]: ... + async def get_enrollment_async(self, id: str) -> dict[str, Incomplete]: ... + def delete_enrollment(self, id: str): ... + async def delete_enrollment_async(self, id: str): ... + def create_enrollment_ticket(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_enrollment_ticket_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_factor_providers(self, factor_name: str, name: str) -> dict[str, Incomplete]: ... + async def get_factor_providers_async(self, factor_name: str, name: str) -> dict[str, Incomplete]: ... + def update_factor_providers(self, factor_name: str, name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_factor_providers_async( + self, factor_name: str, name: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/hooks.pyi b/stubs/auth0-python/auth0/management/hooks.pyi new file mode 100644 index 000000000000..18d7f5c63e9a --- /dev/null +++ b/stubs/auth0-python/auth0/management/hooks.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Hooks: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + async def all_async( + self, + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: list[str] | None = None) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_secrets(self, id: str) -> dict[str, Incomplete]: ... + async def get_secrets_async(self, id: str) -> dict[str, Incomplete]: ... + def add_secrets(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def add_secrets_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_secrets(self, id: str, body: list[str]): ... + async def delete_secrets_async(self, id: str, body: list[str]): ... + def update_secrets(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_secrets_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/jobs.pyi b/stubs/auth0-python/auth0/management/jobs.pyi new file mode 100644 index 000000000000..bd55f89399f3 --- /dev/null +++ b/stubs/auth0-python/auth0/management/jobs.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Jobs: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def get_failed_job(self, id: str) -> dict[str, Incomplete]: ... + async def get_failed_job_async(self, id: str) -> dict[str, Incomplete]: ... + def export_users(self, body: dict[str, Incomplete]): ... + async def export_users_async(self, body: dict[str, Incomplete]): ... + def import_users( + self, + connection_id: str, + file_obj, + upsert: bool = False, + send_completion_email: bool = True, + external_id: str | None = None, + ) -> dict[str, Incomplete]: ... + async def import_users_async( + self, + connection_id: str, + file_obj, + upsert: bool = False, + send_completion_email: bool = True, + external_id: str | None = None, + ) -> dict[str, Incomplete]: ... + def send_verification_email(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def send_verification_email_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/log_streams.pyi b/stubs/auth0-python/auth0/management/log_streams.pyi new file mode 100644 index 000000000000..9990a570ee3a --- /dev/null +++ b/stubs/auth0-python/auth0/management/log_streams.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class LogStreams: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def list(self) -> _list[dict[str, Incomplete]]: ... + async def list_async(self) -> _list[dict[str, Incomplete]]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, id: str) -> dict[str, Incomplete]: ... + async def delete_async(self, id: str) -> dict[str, Incomplete]: ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/logs.pyi b/stubs/auth0-python/auth0/management/logs.pyi new file mode 100644 index 000000000000..800778d2dbf5 --- /dev/null +++ b/stubs/auth0-python/auth0/management/logs.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Logs: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def search( + self, + page: int = 0, + per_page: int = 50, + sort: str | None = None, + q: str | None = None, + include_totals: bool = True, + fields: list[str] | None = None, + from_param: str | None = None, + take: int | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + async def search_async( + self, + page: int = 0, + per_page: int = 50, + sort: str | None = None, + q: str | None = None, + include_totals: bool = True, + fields: list[str] | None = None, + from_param: str | None = None, + take: int | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/organizations.pyi b/stubs/auth0-python/auth0/management/organizations.pyi new file mode 100644 index 000000000000..eb750ff79fd0 --- /dev/null +++ b/stubs/auth0-python/auth0/management/organizations.pyi @@ -0,0 +1,134 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Organizations: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all_organizations( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + async def all_organizations_async( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + def get_organization_by_name(self, name: str | None = None) -> dict[str, Incomplete]: ... + async def get_organization_by_name_async(self, name: str | None = None) -> dict[str, Incomplete]: ... + def get_organization(self, id: str) -> dict[str, Incomplete]: ... + async def get_organization_async(self, id: str) -> dict[str, Incomplete]: ... + def create_organization(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_organization(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_organization_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_organization(self, id: str): ... + async def delete_organization_async(self, id: str): ... + def all_organization_connections( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> list[dict[str, Incomplete]]: ... + async def all_organization_connections_async( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> list[dict[str, Incomplete]]: ... + def get_organization_connection(self, id: str, connection_id: str) -> dict[str, Incomplete]: ... + async def get_organization_connection_async(self, id: str, connection_id: str) -> dict[str, Incomplete]: ... + def create_organization_connection(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_connection_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_organization_connection( + self, id: str, connection_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + async def update_organization_connection_async( + self, id: str, connection_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def delete_organization_connection(self, id: str, connection_id: str): ... + async def delete_organization_connection_async(self, id: str, connection_id: str): ... + def all_organization_members( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + async def all_organization_members_async( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + def create_organization_members(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_members_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_organization_members(self, id: str, body: dict[str, Incomplete]): ... + async def delete_organization_members_async(self, id: str, body: dict[str, Incomplete]): ... + def all_organization_member_roles( + self, id: str, user_id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> list[dict[str, Incomplete]]: ... + async def all_organization_member_roles_async( + self, id: str, user_id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> list[dict[str, Incomplete]]: ... + def create_organization_member_roles(self, id: str, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_member_roles_async( + self, id: str, user_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def delete_organization_member_roles(self, id: str, user_id: str, body: dict[str, Incomplete]): ... + async def delete_organization_member_roles_async(self, id: str, user_id: str, body: dict[str, Incomplete]): ... + def all_organization_invitations( + self, id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + async def all_organization_invitations_async( + self, id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + def get_organization_invitation(self, id: str, invitaton_id: str) -> dict[str, Incomplete]: ... + async def get_organization_invitation_async(self, id: str, invitaton_id: str) -> dict[str, Incomplete]: ... + def create_organization_invitation(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_invitation_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_organization_invitation(self, id: str, invitation_id: str): ... + async def delete_organization_invitation_async(self, id: str, invitation_id: str): ... + def get_client_grants( + self, + id: str, + audience: str | None = None, + client_id: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + async def get_client_grants_async( + self, + id: str, + audience: str | None = None, + client_id: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + def add_client_grant(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... + async def add_client_grant_async(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... + def delete_client_grant(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... + async def delete_client_grant_async(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/prompts.pyi b/stubs/auth0-python/auth0/management/prompts.pyi new file mode 100644 index 000000000000..5b11913678f4 --- /dev/null +++ b/stubs/auth0-python/auth0/management/prompts.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Prompts: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self) -> dict[str, Incomplete]: ... + async def get_async(self) -> dict[str, Incomplete]: ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_custom_text(self, prompt: str, language: str): ... + async def get_custom_text_async(self, prompt: str, language: str): ... + def update_custom_text(self, prompt: str, language: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_custom_text_async( + self, prompt: str, language: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/resource_servers.pyi b/stubs/auth0-python/auth0/management/resource_servers.pyi new file mode 100644 index 000000000000..cb8e175b34dd --- /dev/null +++ b/stubs/auth0-python/auth0/management/resource_servers.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class ResourceServers: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_all(self, page: int | None = None, per_page: int | None = None, include_totals: bool = False): ... + async def get_all_async(self, page: int | None = None, per_page: int | None = None, include_totals: bool = False): ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/roles.pyi b/stubs/auth0-python/auth0/management/roles.pyi new file mode 100644 index 000000000000..5c288c09a5da --- /dev/null +++ b/stubs/auth0-python/auth0/management/roles.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Roles: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def list( + self, page: int = 0, per_page: int = 25, include_totals: bool = True, name_filter: str | None = None + ) -> dict[str, Incomplete]: ... + async def list_async( + self, page: int = 0, per_page: int = 25, include_totals: bool = True, name_filter: str | None = None + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def list_users( + self, + id: str, + page: int = 0, + per_page: int = 25, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + async def list_users_async( + self, + id: str, + page: int = 0, + per_page: int = 25, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + def add_users(self, id: str, users: _list[str]) -> dict[str, Incomplete]: ... + async def add_users_async(self, id: str, users: _list[str]) -> dict[str, Incomplete]: ... + def list_permissions( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + async def list_permissions_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def remove_permissions(self, id: str, permissions: _list[dict[str, str]]): ... + async def remove_permissions_async(self, id: str, permissions: _list[dict[str, str]]): ... + def add_permissions(self, id: str, permissions: _list[dict[str, str]]) -> dict[str, Incomplete]: ... + async def add_permissions_async(self, id: str, permissions: _list[dict[str, str]]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/rules.pyi b/stubs/auth0-python/auth0/management/rules.pyi new file mode 100644 index 000000000000..6cee7f6e151d --- /dev/null +++ b/stubs/auth0-python/auth0/management/rules.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Rules: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + stage: str = "login_success", + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + async def all_async( + self, + stage: str = "login_success", + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/rules_configs.pyi b/stubs/auth0-python/auth0/management/rules_configs.pyi new file mode 100644 index 000000000000..5f2f361d5f46 --- /dev/null +++ b/stubs/auth0-python/auth0/management/rules_configs.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class RulesConfigs: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self) -> list[dict[str, Incomplete]]: ... + async def all_async(self) -> list[dict[str, Incomplete]]: ... + def unset(self, key: str): ... + async def unset_async(self, key: str): ... + def set(self, key: str, value: str) -> dict[str, Incomplete]: ... + async def set_async(self, key: str, value: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/self_service_profiles.pyi b/stubs/auth0-python/auth0/management/self_service_profiles.pyi new file mode 100644 index 000000000000..e75e2a098844 --- /dev/null +++ b/stubs/auth0-python/auth0/management/self_service_profiles.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class SelfServiceProfiles: + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self, page: int = 0, per_page: int = 25, include_totals: bool = True) -> list[dict[str, Incomplete]]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, profile_id: str) -> dict[str, Incomplete]: ... + def delete(self, profile_id: str) -> None: ... + def update(self, profile_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_custom_text(self, profile_id: str, language: str, page: str) -> dict[str, Incomplete]: ... + def update_custom_text( + self, profile_id: str, language: str, page: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def create_sso_ticket(self, profile_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def revoke_sso_ticket(self, profile_id: str, ticket_id: str) -> None: ... diff --git a/stubs/auth0-python/auth0/management/stats.pyi b/stubs/auth0-python/auth0/management/stats.pyi new file mode 100644 index 000000000000..3cff2985672c --- /dev/null +++ b/stubs/auth0-python/auth0/management/stats.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Stats: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def active_users(self) -> int: ... + async def active_users_async(self) -> int: ... + def daily_stats(self, from_date: str | None = None, to_date: str | None = None) -> list[dict[str, Incomplete]]: ... + async def daily_stats_async( + self, from_date: str | None = None, to_date: str | None = None + ) -> list[dict[str, Incomplete]]: ... diff --git a/stubs/auth0-python/auth0/management/tenants.pyi b/stubs/auth0-python/auth0/management/tenants.pyi new file mode 100644 index 000000000000..3df24bf63374 --- /dev/null +++ b/stubs/auth0-python/auth0/management/tenants.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Tenants: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/tickets.pyi b/stubs/auth0-python/auth0/management/tickets.pyi new file mode 100644 index 000000000000..4c0dfaf2c879 --- /dev/null +++ b/stubs/auth0-python/auth0/management/tickets.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Tickets: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def create_email_verification(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_email_verification_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def create_pswd_change(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_pswd_change_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/user_blocks.pyi b/stubs/auth0-python/auth0/management/user_blocks.pyi new file mode 100644 index 000000000000..f6dbb555097f --- /dev/null +++ b/stubs/auth0-python/auth0/management/user_blocks.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class UserBlocks: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get_by_identifier(self, identifier: str) -> dict[str, Incomplete]: ... + async def get_by_identifier_async(self, identifier: str) -> dict[str, Incomplete]: ... + def unblock_by_identifier(self, identifier: dict[str, Incomplete]): ... + async def unblock_by_identifier_async(self, identifier: dict[str, Incomplete]): ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def unblock(self, id: str): ... + async def unblock_async(self, id: str): ... diff --git a/stubs/auth0-python/auth0/management/users.pyi b/stubs/auth0-python/auth0/management/users.pyi new file mode 100644 index 000000000000..2a744f2db6fe --- /dev/null +++ b/stubs/auth0-python/auth0/management/users.pyi @@ -0,0 +1,119 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Users: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def list( + self, + page: int = 0, + per_page: int = 25, + sort: str | None = None, + connection: str | None = None, + q: str | None = None, + search_engine: str | None = None, + include_totals: bool = True, + fields: _list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + async def list_async( + self, + page: int = 0, + per_page: int = 25, + sort: str | None = None, + connection: str | None = None, + q: str | None = None, + search_engine: str | None = None, + include_totals: bool = True, + fields: _list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: _list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async( + self, id: str, fields: _list[str] | None = None, include_fields: bool = True + ) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def list_organizations( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + async def list_organizations_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def list_roles(self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True) -> dict[str, Incomplete]: ... + async def list_roles_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def remove_roles(self, id: str, roles: _list[str]): ... + async def remove_roles_async(self, id: str, roles: _list[str]): ... + def add_roles(self, id: str, roles: _list[str]) -> dict[str, Incomplete]: ... + async def add_roles_async(self, id: str, roles: _list[str]) -> dict[str, Incomplete]: ... + def list_permissions( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + async def list_permissions_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def remove_permissions(self, id: str, permissions: _list[str]): ... + async def remove_permissions_async(self, id: str, permissions: _list[str]): ... + def add_permissions(self, id: str, permissions: _list[str]) -> dict[str, Incomplete]: ... + async def add_permissions_async(self, id: str, permissions: _list[str]) -> dict[str, Incomplete]: ... + def delete_multifactor(self, id: str, provider: str): ... + async def delete_multifactor_async(self, id: str, provider: str): ... + def delete_authenticators(self, id: str): ... + async def delete_authenticators_async(self, id: str): ... + def unlink_user_account(self, id: str, provider: str, user_id: str): ... + async def unlink_user_account_async(self, id: str, provider: str, user_id: str): ... + def link_user_account(self, user_id: str, body: dict[str, Incomplete]) -> _list[dict[str, Incomplete]]: ... + async def link_user_account_async(self, user_id: str, body: dict[str, Incomplete]) -> _list[dict[str, Incomplete]]: ... + def regenerate_recovery_code(self, user_id: str) -> dict[str, Incomplete]: ... + async def regenerate_recovery_code_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_guardian_enrollments(self, user_id: str) -> dict[str, Incomplete]: ... + async def get_guardian_enrollments_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_log_events( + self, user_id: str, page: int = 0, per_page: int = 50, sort: str | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + async def get_log_events_async( + self, user_id: str, page: int = 0, per_page: int = 50, sort: str | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + def invalidate_remembered_browsers(self, user_id: str) -> dict[str, Incomplete]: ... + async def invalidate_remembered_browsers_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_authentication_methods(self, user_id: str) -> dict[str, Incomplete]: ... + async def get_authentication_methods_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_authentication_method_by_id(self, user_id: str, authentication_method_id: str) -> dict[str, Incomplete]: ... + async def get_authentication_method_by_id_async( + self, user_id: str, authentication_method_id: str + ) -> dict[str, Incomplete]: ... + def create_authentication_method(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_authentication_method_async(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_authentication_methods(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_authentication_methods_async(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_authentication_method_by_id( + self, user_id: str, authentication_method_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + async def update_authentication_method_by_id_async( + self, user_id: str, authentication_method_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def delete_authentication_methods(self, user_id: str): ... + async def delete_authentication_methods_async(self, user_id: str): ... + def delete_authentication_method_by_id(self, user_id: str, authentication_method_id: str): ... + async def delete_authentication_method_by_id_async(self, user_id: str, authentication_method_id: str): ... + def list_tokensets(self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True): ... + def delete_tokenset_by_id(self, user_id: str, tokenset_id: str): ... diff --git a/stubs/auth0-python/auth0/management/users_by_email.pyi b/stubs/auth0-python/auth0/management/users_by_email.pyi new file mode 100644 index 000000000000..34b166a046cb --- /dev/null +++ b/stubs/auth0-python/auth0/management/users_by_email.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class UsersByEmail: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def search_users_by_email( + self, email: str, fields: list[str] | None = None, include_fields: bool = True + ) -> list[dict[str, Incomplete]]: ... + async def search_users_by_email_async( + self, email: str, fields: list[str] | None = None, include_fields: bool = True + ) -> list[dict[str, Incomplete]]: ... diff --git a/stubs/auth0-python/auth0/rest.pyi b/stubs/auth0-python/auth0/rest.pyi new file mode 100644 index 000000000000..474716ed553b --- /dev/null +++ b/stubs/auth0-python/auth0/rest.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import Final + +import requests +from auth0.rest_async import RequestsResponse +from auth0.types import RequestData, TimeoutType + +UNKNOWN_ERROR: Final[str] + +class RestClientOptions: + telemetry: bool + timeout: TimeoutType + retries: int + def __init__(self, telemetry: bool = True, timeout: TimeoutType = 5.0, retries: int = 3) -> None: ... + +class RestClient: + options: RestClientOptions + jwt: str | None + base_headers: dict[str, str] + telemetry: bool + timeout: TimeoutType + def __init__( + self, jwt: str | None, telemetry: bool = True, timeout: TimeoutType = 5.0, options: RestClientOptions | None = None + ) -> None: ... + def MAX_REQUEST_RETRIES(self) -> int: ... + def MAX_REQUEST_RETRY_JITTER(self) -> int: ... + def MAX_REQUEST_RETRY_DELAY(self) -> int: ... + def MIN_REQUEST_RETRY_DELAY(self) -> int: ... + def get(self, url: str, params: dict[str, Incomplete] | None = None, headers: dict[str, str] | None = None): ... + def post(self, url: str, data: RequestData | None = None, headers: dict[str, str] | None = None): ... + def file_post(self, url: str, data: RequestData | None = None, files: dict[str, Incomplete] | None = None): ... + def patch(self, url: str, data: RequestData | None = None): ... + def put(self, url: str, data: RequestData | None = None): ... + def delete(self, url: str, params: dict[str, Incomplete] | None = None, data: RequestData | None = None): ... + +class Response: + def __init__(self, status_code: int, content, headers: Mapping[str, str]) -> None: ... + def content(self): ... + +class JsonResponse(Response): + def __init__(self, response: requests.Response | RequestsResponse) -> None: ... + +class PlainResponse(Response): + def __init__(self, response: requests.Response | RequestsResponse) -> None: ... + +class EmptyResponse(Response): + def __init__(self, status_code: int) -> None: ... diff --git a/stubs/auth0-python/auth0/rest_async.pyi b/stubs/auth0-python/auth0/rest_async.pyi new file mode 100644 index 000000000000..56dc43e76804 --- /dev/null +++ b/stubs/auth0-python/auth0/rest_async.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete + +from auth0.types import RequestData + +from .rest import RestClient + +class AsyncRestClient(RestClient): + timeout: Incomplete + def set_session(self, session) -> None: ... + async def get(self, url: str, params: dict[str, Incomplete] | None = None, headers: dict[str, str] | None = None): ... + async def post(self, url: str, data: RequestData | None = None, headers: dict[str, str] | None = None): ... + async def file_post( # type: ignore[override] # Differs from supertype + self, url: str, data: dict[str, Incomplete], files: dict[str, Incomplete] + ): ... + async def patch(self, url: str, data: RequestData | None = None): ... + async def put(self, url: str, data: RequestData | None = None): ... + async def delete(self, url: str, params: dict[str, Incomplete] | None = None, data: RequestData | None = None): ... + +class RequestsResponse: + status_code: int + headers: Incomplete + text: str + def __init__(self, response, text: str) -> None: ... diff --git a/stubs/auth0-python/auth0/types.pyi b/stubs/auth0-python/auth0/types.pyi new file mode 100644 index 000000000000..2d9d79d8cbdb --- /dev/null +++ b/stubs/auth0-python/auth0/types.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +TimeoutType: TypeAlias = float | tuple[float, float] +RequestData: TypeAlias = dict[str, Incomplete] | list[Incomplete] diff --git a/stubs/auth0-python/auth0/utils.pyi b/stubs/auth0-python/auth0/utils.pyi new file mode 100644 index 000000000000..611cd037c258 --- /dev/null +++ b/stubs/auth0-python/auth0/utils.pyi @@ -0,0 +1 @@ +def is_async_available() -> bool: ... diff --git a/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt b/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt index c0f8fbaf47dc..0ccd2bd8b0ab 100644 --- a/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt +++ b/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt @@ -1,4 +1,36 @@ -aws_xray_sdk.core.async_recorder.subsegment_decorator aws_xray_sdk.core.models.subsegment.subsegment_decorator aws_xray_sdk.core.sampling.connector.ServiceConnector.fetch_sampling_rules -aws_xray_sdk.core.sampling.sampler.ServiceConnector.fetch_sampling_rules + +# Inconsistency because `context_missing` param can be passed in *args or **kwargs: +aws_xray_sdk.core.async_context.AsyncContext.__init__ + +# We can not import 3rd-party libraries in teststubs runtime, +# but we can use Protocol to replace this types: +aws_xray_sdk.ext.aiobotocore +aws_xray_sdk.ext.aiobotocore.patch +aws_xray_sdk.ext.aiohttp.client +aws_xray_sdk.ext.aiohttp.middleware +aws_xray_sdk.ext.bottle.middleware +aws_xray_sdk.ext.django.apps +aws_xray_sdk.ext.django.conf +aws_xray_sdk.ext.django.db +aws_xray_sdk.ext.django.middleware +aws_xray_sdk.ext.django.templates +aws_xray_sdk.ext.flask.middleware +aws_xray_sdk.ext.flask_sqlalchemy.query +aws_xray_sdk.ext.httpx +aws_xray_sdk.ext.httpx.patch +aws_xray_sdk.ext.mysql +aws_xray_sdk.ext.mysql.patch +aws_xray_sdk.ext.pg8000 +aws_xray_sdk.ext.pg8000.patch +aws_xray_sdk.ext.pymongo +aws_xray_sdk.ext.pymongo.patch +aws_xray_sdk.ext.pymysql +aws_xray_sdk.ext.pymysql.patch +aws_xray_sdk.ext.pynamodb +aws_xray_sdk.ext.pynamodb.patch +aws_xray_sdk.ext.sqlalchemy.query +aws_xray_sdk.ext.sqlalchemy.util.decorators +aws_xray_sdk.ext.sqlalchemy_core +aws_xray_sdk.ext.sqlalchemy_core.patch diff --git a/stubs/aws-xray-sdk/METADATA.toml b/stubs/aws-xray-sdk/METADATA.toml index fa0e835cbebd..015cbb61e4a0 100644 --- a/stubs/aws-xray-sdk/METADATA.toml +++ b/stubs/aws-xray-sdk/METADATA.toml @@ -1 +1,2 @@ -version = "2.8.*" +version = "2.15.*" +upstream-repository = "https://github.com/aws/aws-xray-sdk-python" diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi index bfaa6ea70292..b42232c23d27 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi @@ -1,4 +1,7 @@ +from .async_recorder import AsyncAWSXRayRecorder as AsyncAWSXRayRecorder from .patcher import patch as patch, patch_all as patch_all from .recorder import AWSXRayRecorder as AWSXRayRecorder -xray_recorder: AWSXRayRecorder +xray_recorder: AsyncAWSXRayRecorder + +__all__ = ["patch", "patch_all", "xray_recorder", "AWSXRayRecorder"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi index ebedf69feccd..85c366e821ee 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi @@ -1,15 +1,23 @@ -from typing import Any +from asyncio.events import AbstractEventLoop +from asyncio.tasks import Task, _TaskCompatibleCoro +from typing import Any, TypeVar from .context import Context as _Context +_T_co = TypeVar("_T_co", covariant=True) + class AsyncContext(_Context): - def __init__(self, *args, loop: Any | None = ..., use_task_factory: bool = ..., **kwargs) -> None: ... + def __init__( + self, context_missing: str = "LOG_ERROR", loop: AbstractEventLoop | None = None, use_task_factory: bool = True + ) -> None: ... def clear_trace_entities(self) -> None: ... class TaskLocalStorage: - def __init__(self, loop: Any | None = ...) -> None: ... - def __setattr__(self, name, value) -> None: ... - def __getattribute__(self, item): ... + def __init__(self, loop: AbstractEventLoop | None = None) -> None: ... + # Sets unknown items on the current task's context attribute + def __setattr__(self, name: str, value: Any) -> None: ... + # Returns unknown items from the current tasks context attribute + def __getattribute__(self, item: str) -> Any | None: ... def clear(self) -> None: ... -def task_factory(loop, coro): ... +def task_factory(loop: AbstractEventLoop | None, coro: _TaskCompatibleCoro[_T_co]) -> Task[_T_co]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi index 58b18e1e858d..f7e4d588fa29 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi @@ -1,25 +1,43 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Awaitable, Callable, Iterable, Mapping +from types import TracebackType +from typing import TypeVar -from .models.segment import SegmentContextManager as SegmentContextManager -from .models.subsegment import ( - SubsegmentContextManager as SubsegmentContextManager, - is_already_recording as is_already_recording, - subsegment_decorator as subsegment_decorator, -) -from .recorder import AWSXRayRecorder as AWSXRayRecorder -from .utils import stacktrace as stacktrace +from .models.dummy_entities import DummySegment, DummySubsegment +from .models.segment import Segment, SegmentContextManager +from .models.subsegment import Subsegment, SubsegmentContextManager +from .recorder import AWSXRayRecorder + +_T = TypeVar("_T") class AsyncSegmentContextManager(SegmentContextManager): - async def __aenter__(self): ... - async def __aexit__(self, exc_type, exc_val, exc_tb): ... + async def __aenter__(self) -> DummySegment | Segment: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... class AsyncSubsegmentContextManager(SubsegmentContextManager): - async def __call__(self, wrapped, instance, args, kwargs): ... - async def __aenter__(self): ... - async def __aexit__(self, exc_type, exc_val, exc_tb): ... + async def __call__( + self, wrapped: Callable[..., Awaitable[_T]], instance, args: Iterable[Incomplete], kwargs: Mapping[str, Incomplete] + ) -> _T: ... + async def __aenter__(self) -> DummySubsegment | Subsegment | None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... class AsyncAWSXRayRecorder(AWSXRayRecorder): - def capture_async(self, name: Any | None = ...): ... - def in_segment_async(self, name: Any | None = ..., **segment_kwargs): ... - def in_subsegment_async(self, name: Any | None = ..., **subsegment_kwargs): ... - async def record_subsegment_async(self, wrapped, instance, args, kwargs, name, namespace, meta_processor): ... + def capture_async(self, name: str | None = None) -> AsyncSubsegmentContextManager: ... + def in_segment_async( + self, name: str | None = None, *, traceid: str | None = None, parent_id: str | None = None, sampling: bool | None = None + ) -> AsyncSegmentContextManager: ... + def in_subsegment_async(self, name: str | None = None, *, namespace: str = "local") -> AsyncSubsegmentContextManager: ... + async def record_subsegment_async( + self, + wrapped: Callable[..., Awaitable[_T]], + instance, + args: Iterable[Incomplete], + kwargs: Mapping[str, Incomplete], + name: str, + namespace: str, + meta_processor: Callable[..., object] | None, + ) -> _T: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi index f495ac64aabe..cb40f81ce44c 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi @@ -1,30 +1,28 @@ import time from logging import Logger -from typing import Any +from typing import Final -from .. import global_sdk_config as global_sdk_config -from .exceptions.exceptions import SegmentNotFoundException as SegmentNotFoundException -from .models.dummy_entities import DummySegment as DummySegment from .models.entity import Entity from .models.segment import Segment from .models.subsegment import Subsegment log: Logger -SUPPORTED_CONTEXT_MISSING: Any -MISSING_SEGMENT_MSG: str -CXT_MISSING_STRATEGY_KEY: str +MISSING_SEGMENT_MSG: Final[str] +SUPPORTED_CONTEXT_MISSING: Final = ("RUNTIME_ERROR", "LOG_ERROR", "IGNORE_ERROR") +CXT_MISSING_STRATEGY_KEY: Final = "AWS_XRAY_CONTEXT_MISSING" class Context: - def __init__(self, context_missing: str = ...) -> None: ... + def __init__(self, context_missing: str = "LOG_ERROR") -> None: ... def put_segment(self, segment: Segment) -> None: ... - def end_segment(self, end_time: time.struct_time | None = ...) -> None: ... + def end_segment(self, end_time: time.struct_time | None = None) -> None: ... def put_subsegment(self, subsegment: Subsegment) -> None: ... - def end_subsegment(self, end_time: time.struct_time | None = ...): ... - def get_trace_entity(self): ... + def end_subsegment(self, end_time: time.struct_time | None = None) -> bool: ... + def get_trace_entity(self) -> Entity: ... def set_trace_entity(self, trace_entity: Entity) -> None: ... def clear_trace_entities(self) -> None: ... def handle_context_missing(self) -> None: ... + @property - def context_missing(self): ... + def context_missing(self) -> str: ... @context_missing.setter def context_missing(self, value: str) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi index 2cbec2ee83e5..35a393a7712b 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi @@ -1,15 +1,15 @@ -from .exceptions.exceptions import InvalidDaemonAddressException as InvalidDaemonAddressException +from typing import Final -DAEMON_ADDRESS_KEY: str -DEFAULT_ADDRESS: str +DAEMON_ADDRESS_KEY: Final = "AWS_XRAY_DAEMON_ADDRESS" +DEFAULT_ADDRESS: Final = "127.0.0.1:2000" class DaemonConfig: - def __init__(self, daemon_address=...) -> None: ... + def __init__(self, daemon_address: str | None = "127.0.0.1:2000") -> None: ... @property - def udp_ip(self): ... + def udp_ip(self) -> str: ... @property - def udp_port(self): ... + def udp_port(self) -> int: ... @property - def tcp_ip(self): ... + def tcp_ip(self) -> str: ... @property - def tcp_port(self): ... + def tcp_port(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi index 4d5bfb3f2df7..affa22d2a484 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi @@ -1,19 +1,18 @@ from logging import Logger +from typing import Final -from aws_xray_sdk.core.daemon_config import DaemonConfig as DaemonConfig - -from ..exceptions.exceptions import InvalidDaemonAddressException as InvalidDaemonAddressException +from aws_xray_sdk.core.models.entity import Entity log: Logger -PROTOCOL_HEADER: str -PROTOCOL_DELIMITER: str -DEFAULT_DAEMON_ADDRESS: str +PROTOCOL_HEADER: Final[str] +PROTOCOL_DELIMITER: Final[str] +DEFAULT_DAEMON_ADDRESS: Final[str] class UDPEmitter: - def __init__(self, daemon_address=...) -> None: ... - def send_entity(self, entity) -> None: ... - def set_daemon_address(self, address) -> None: ... + def __init__(self, daemon_address: str = "127.0.0.1:2000") -> None: ... + def send_entity(self, entity: Entity) -> None: ... + def set_daemon_address(self, address: str | None) -> None: ... @property - def ip(self): ... + def ip(self) -> str: ... @property - def port(self): ... + def port(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi index ee184efd46d1..42f78df47440 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi @@ -1,28 +1,20 @@ from logging import Logger -from typing import Any +from typing import Final -from aws_xray_sdk import global_sdk_config as global_sdk_config - -from .context import Context as Context -from .models.facade_segment import FacadeSegment as FacadeSegment -from .models.trace_header import TraceHeader as TraceHeader +from .context import Context log: Logger -LAMBDA_TRACE_HEADER_KEY: str -LAMBDA_TASK_ROOT_KEY: str -TOUCH_FILE_DIR: str -TOUCH_FILE_PATH: str +LAMBDA_TRACE_HEADER_KEY: Final = "_X_AMZN_TRACE_ID" +LAMBDA_TASK_ROOT_KEY: Final = "LAMBDA_TASK_ROOT" +TOUCH_FILE_DIR: Final = "/tmp/.aws-xray/" +TOUCH_FILE_PATH: Final = "/tmp/.aws-xray/initialized" -def check_in_lambda(): ... +def check_in_lambda() -> LambdaContext | None: ... class LambdaContext(Context): def __init__(self) -> None: ... - def put_segment(self, segment) -> None: ... - def end_segment(self, end_time: Any | None = ...) -> None: ... - def put_subsegment(self, subsegment) -> None: ... - def get_trace_entity(self): ... - @property + + @property # type: ignore[override] def context_missing(self) -> None: ... @context_missing.setter - def context_missing(self, value) -> None: ... - def handle_context_missing(self) -> None: ... + def context_missing(self, value: str) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi index 8103c32a7b03..ed31616245db 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi @@ -1,5 +1,3 @@ -from ..utils.search_pattern import wildcard_match as wildcard_match - class DefaultDynamicNaming: - def __init__(self, pattern, fallback) -> None: ... - def get_name(self, host_name): ... + def __init__(self, pattern: str, fallback: str) -> None: ... + def get_name(self, host_name: str | None) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi index 018d9f3d4695..f10a1208d4b6 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi @@ -1,29 +1,8 @@ -from .noop_traceid import NoOpTraceId as NoOpTraceId -from .segment import Segment as Segment -from .subsegment import Subsegment as Subsegment -from .traceid import TraceId as TraceId +from .segment import Segment +from .subsegment import Subsegment class DummySegment(Segment): - sampled: bool - def __init__(self, name: str = ...) -> None: ... - def set_aws(self, aws_meta) -> None: ... - def put_http_meta(self, key, value) -> None: ... - def put_annotation(self, key, value) -> None: ... - def put_metadata(self, key, value, namespace: str = ...) -> None: ... - def set_user(self, user) -> None: ... - def set_service(self, service_info) -> None: ... - def apply_status_code(self, status_code) -> None: ... - def add_exception(self, exception, stack, remote: bool = ...) -> None: ... - def serialize(self) -> None: ... + def __init__(self, name: str = "dummy") -> None: ... class DummySubsegment(Subsegment): - sampled: bool - def __init__(self, segment, name: str = ...) -> None: ... - def set_aws(self, aws_meta) -> None: ... - def put_http_meta(self, key, value) -> None: ... - def put_annotation(self, key, value) -> None: ... - def put_metadata(self, key, value, namespace: str = ...) -> None: ... - def set_sql(self, sql) -> None: ... - def apply_status_code(self, status_code) -> None: ... - def add_exception(self, exception, stack, remote: bool = ...) -> None: ... - def serialize(self) -> None: ... + def __init__(self, segment, name: str = "dummy") -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi index b1cabd7c2ff3..8b4e17c6e4a1 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi @@ -1,37 +1,42 @@ +from _typeshed import Incomplete from logging import Logger from traceback import StackSummary -from typing import Any +from typing import Any, Final, Literal, overload -from ..exceptions.exceptions import AlreadyEndedException as AlreadyEndedException -from ..utils.compat import annotation_value_types as annotation_value_types, string_types as string_types -from ..utils.conversion import metadata_to_dict as metadata_to_dict -from . import http as http -from .throwable import Throwable as Throwable +from .subsegment import Subsegment +from .throwable import Throwable log: Logger -ORIGIN_TRACE_HEADER_ATTR_KEY: str +ORIGIN_TRACE_HEADER_ATTR_KEY: Final = "_origin_trace_header" class Entity: - id: Any - name: Any - start_time: Any - parent_id: Any + id: str + name: str + start_time: float + parent_id: str | None sampled: bool in_progress: bool - http: Any - annotations: Any - metadata: Any - aws: Any - cause: Any - subsegments: Any - end_time: Any - def __init__(self, name, entity_id: Any | None = ...) -> None: ... - def close(self, end_time: Any | None = ...) -> None: ... - def add_subsegment(self, subsegment) -> None: ... - def remove_subsegment(self, subsegment) -> None: ... - def put_http_meta(self, key, value) -> None: ... - def put_annotation(self, key, value) -> None: ... - def put_metadata(self, key, value, namespace: str = ...) -> None: ... + http: dict[str, dict[str, str | int]] + annotations: dict[str, float | str | bool] + metadata: dict[str, dict[str, Any]] # value is any object that can be serialized into JSON string + aws: dict[str, Incomplete] + cause: dict[str, str | list[Throwable]] + subsegments: list[Subsegment] + end_time: float + def __init__(self, name: str, entity_id: str | None = None) -> None: ... + def close(self, end_time: float | None = None) -> None: ... + def add_subsegment(self, subsegment: Subsegment) -> None: ... + def remove_subsegment(self, subsegment: Subsegment) -> None: ... + + @overload + def put_http_meta(self, key: Literal["status", "content_length"], value: int) -> None: ... + @overload + def put_http_meta(self, key: Literal["url", "method", "user_agent", "client_ip", "x_forwarded_for"], value: str) -> None: ... + + def put_annotation(self, key: str, value: float | str | bool) -> None: ... + def put_metadata( + self, key: str, value: Any, namespace: str = "default" # value is any object that can be serialized into JSON string + ) -> None: ... def set_aws(self, aws_meta) -> None: ... throttle: bool def add_throttle_flag(self) -> None: ... @@ -39,9 +44,9 @@ class Entity: def add_fault_flag(self) -> None: ... error: bool def add_error_flag(self) -> None: ... - def apply_status_code(self, status_code) -> None: ... - def add_exception(self, exception: Exception, stack: StackSummary, remote: bool = ...) -> None: ... + def apply_status_code(self, status_code: int | None) -> None: ... + def add_exception(self, exception: Exception, stack: StackSummary, remote: bool = False) -> None: ... def save_origin_trace_header(self, trace_header) -> None: ... def get_origin_trace_header(self): ... - def serialize(self): ... - def to_dict(self): ... + def serialize(self) -> str: ... + def to_dict(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi index a80c456e022d..2ae599e4c968 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi @@ -1,25 +1,9 @@ -from typing import Any +from typing import Final -from ..exceptions.exceptions import FacadeSegmentMutationException as FacadeSegmentMutationException -from .segment import Segment as Segment +from .segment import Segment -MUTATION_UNSUPPORTED_MESSAGE: str +MUTATION_UNSUPPORTED_MESSAGE: Final = "FacadeSegments cannot be mutated." class FacadeSegment(Segment): - initializing: Any - def __init__(self, name, entityid, traceid, sampled) -> None: ... - def close(self, end_time: Any | None = ...) -> None: ... - def put_http_meta(self, key, value) -> None: ... - def put_annotation(self, key, value) -> None: ... - def put_metadata(self, key, value, namespace: str = ...) -> None: ... - def set_aws(self, aws_meta) -> None: ... - def set_user(self, user) -> None: ... - def add_throttle_flag(self) -> None: ... - def add_fault_flag(self) -> None: ... - def add_error_flag(self) -> None: ... - def add_exception(self, exception, stack, remote: bool = ...) -> None: ... - def apply_status_code(self, status_code) -> None: ... - def serialize(self) -> None: ... - def ready_to_send(self): ... - def increment(self) -> None: ... - def decrement_ref_counter(self) -> None: ... + initializing: bool + def __init__(self, name: str, entityid: str | None, traceid: str | None, sampled: bool | None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi index c42504de43b9..360493f2f829 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi @@ -1,13 +1,13 @@ -from typing import Any +from typing import Final -URL: str -METHOD: str -USER_AGENT: str -CLIENT_IP: str -X_FORWARDED_FOR: str -STATUS: str -CONTENT_LENGTH: str -XRAY_HEADER: str -ALT_XRAY_HEADER: str -request_keys: Any -response_keys: Any +URL: Final = "url" +METHOD: Final = "method" +USER_AGENT: Final = "user_agent" +CLIENT_IP: Final = "client_ip" +X_FORWARDED_FOR: Final = "x_forwarded_for" +STATUS: Final = "status" +CONTENT_LENGTH: Final = "content_length" +XRAY_HEADER: Final = "X-Amzn-Trace-Id" +ALT_XRAY_HEADER: Final = "HTTP_X_AMZN_TRACE_ID" +request_keys: tuple[str, ...] +response_keys: tuple[str, ...] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi index 0185c6b0b8b9..14771ae030b9 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi @@ -1,6 +1,8 @@ +from typing import ClassVar + class NoOpTraceId: - VERSION: str - DELIMITER: str + VERSION: ClassVar[str] + DELIMITER: ClassVar[str] start_time: str def __init__(self) -> None: ... - def to_id(self): ... + def to_id(self) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi index 50c3a859648f..1851d8ea3282 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi @@ -1,43 +1,59 @@ -from typing import Any +from _typeshed import Incomplete +from types import TracebackType +from typing import Final -from ..exceptions.exceptions import SegmentNameMissingException as SegmentNameMissingException from ..recorder import AWSXRayRecorder -from ..utils.atomic_counter import AtomicCounter as AtomicCounter -from .entity import Entity as Entity +from ..utils.atomic_counter import AtomicCounter +from .dummy_entities import DummySegment +from .entity import Entity from .subsegment import Subsegment -from .traceid import TraceId as TraceId -ORIGIN_TRACE_HEADER_ATTR_KEY: str +ORIGIN_TRACE_HEADER_ATTR_KEY: Final = "_origin_trace_header" class SegmentContextManager: - name: str - segment_kwargs: dict[str, Any] + name: str | None + segment_kwargs: dict[str, str | bool | None] recorder: AWSXRayRecorder - segment: Segment - def __init__(self, recorder: AWSXRayRecorder, name: str | None = ..., **segment_kwargs) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + segment: Segment | None + def __init__( + self, + recorder: AWSXRayRecorder, + name: str | None = None, + *, + traceid: str | None = None, + parent_id: str | None = None, + sampling: bool | None = None, + ) -> None: ... + def __enter__(self) -> DummySegment | Segment: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... class Segment(Entity): - trace_id: str | None - id: str | None + trace_id: str + id: str in_progress: bool sampled: bool user: str | None ref_counter: AtomicCounter - parent_id: str | None + parent_id: str service: dict[str, str] def __init__( - self, name, entityid: str | None = ..., traceid: str | None = ..., parent_id: str | None = ..., sampled: bool = ... + self, + name: str, + entityid: str | None = None, + traceid: str | None = None, + parent_id: str | None = None, + sampled: bool = True, ) -> None: ... def add_subsegment(self, subsegment: Subsegment) -> None: ... def increment(self) -> None: ... def decrement_ref_counter(self) -> None: ... - def ready_to_send(self): ... - def get_total_subsegments_size(self): ... - def decrement_subsegments_size(self): ... - def remove_subsegment(self, subsegment) -> None: ... + def ready_to_send(self) -> bool: ... + def get_total_subsegments_size(self) -> int: ... + def decrement_subsegments_size(self) -> int: ... + def remove_subsegment(self, subsegment: Subsegment) -> None: ... def set_user(self, user) -> None: ... - def set_service(self, service_info) -> None: ... - def set_rule_name(self, rule_name) -> None: ... - def to_dict(self): ... + def set_service(self, service_info: dict[str, str]) -> None: ... + def set_rule_name(self, rule_name: str) -> None: ... + def to_dict(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi index 97e5a7a49b83..27481f85870b 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi @@ -1,36 +1,40 @@ -import time -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable +from types import TracebackType +from typing import Final -from ...core import AWSXRayRecorder -from ..exceptions.exceptions import SegmentNotFoundException as SegmentNotFoundException -from .entity import Entity as Entity +from ..recorder import AWSXRayRecorder +from .dummy_entities import DummySubsegment +from .entity import Entity from .segment import Segment -SUBSEGMENT_RECORDING_ATTRIBUTE: str +SUBSEGMENT_RECORDING_ATTRIBUTE: Final = "_self___SUBSEGMENT_RECORDING_ATTRIBUTE__" def set_as_recording(decorated_func, wrapped) -> None: ... -def is_already_recording(func): ... +def is_already_recording(func: Callable[..., object]) -> bool: ... def subsegment_decorator(wrapped, instance, args, kwargs): ... class SubsegmentContextManager: name: str | None - subsegment_kwargs: dict[str, Any] | None + subsegment_kwargs: dict[str, str] recorder: AWSXRayRecorder - subsegment: Subsegment - def __init__(self, recorder: AWSXRayRecorder, name: Any | None = ..., **subsegment_kwargs) -> None: ... - def __call__(self, wrapped, instance, args: list[Any], kwargs: dict[str, Any]): ... - def __enter__(self) -> Subsegment: ... - def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + subsegment: Subsegment | None + def __init__(self, recorder: AWSXRayRecorder, name: str | None = None, *, namespace: str = "local") -> None: ... + def __call__(self, wrapped, instance, args: list[Incomplete], kwargs: dict[str, Incomplete]): ... + def __enter__(self) -> DummySubsegment | Subsegment | None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... class Subsegment(Entity): parent_segment: Segment trace_id: str type: str namespace: str - sql: dict[str, Any] + sql: dict[str, Incomplete] def __init__(self, name: str, namespace: str, segment: Segment) -> None: ... def add_subsegment(self, subsegment: Subsegment) -> None: ... def remove_subsegment(self, subsegment: Subsegment) -> None: ... - def close(self, end_time: time.struct_time | None = ...) -> None: ... - def set_sql(self, sql: dict[str, Any]) -> None: ... - def to_dict(self) -> dict[str, Any]: ... + def close(self, end_time: float | None = None) -> None: ... + def set_sql(self, sql: dict[str, Incomplete]) -> None: ... + def to_dict(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi index bc26c4c26d1e..e4e0f748fd59 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi @@ -1,14 +1,29 @@ -from typing import Any +from logging import Logger +from traceback import StackSummary +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired -from ..utils.compat import string_types as string_types +log: Logger -log: Any +@type_check_only +class _StackInfo(TypedDict): + path: str + line: int + label: str + +@type_check_only +class _ThrowableAttrs(TypedDict): + id: str + message: NotRequired[str] + type: str + remote: bool + stack: NotRequired[list[_StackInfo]] class Throwable: - id: Any - message: Any - type: Any - remote: Any - stack: Any - def __init__(self, exception, stack, remote: bool = ...) -> None: ... - def to_dict(self): ... + id: str + message: str + type: str + remote: bool + stack: list[_StackInfo] | None + def __init__(self, exception: Exception, stack: StackSummary, remote: bool = False) -> None: ... + def to_dict(self) -> _ThrowableAttrs: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi index 490baa42dfd3..d691f30e730f 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi @@ -1,24 +1,36 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger +from typing import Final, Literal, TypeAlias +from typing_extensions import Self -log: Any -ROOT: str -PARENT: str -SAMPLE: str -SELF: str -HEADER_DELIMITER: str +_SampledTrue: TypeAlias = Literal[True, "1", 1] +_SampledFalse: TypeAlias = Literal[False, "0", 0] +_SampledUnknown: TypeAlias = Literal["?"] +_Sampled: TypeAlias = _SampledTrue | _SampledFalse | _SampledUnknown + +log: Logger +ROOT: Final = "Root" +PARENT: Final = "Parent" +SAMPLE: Final = "Sampled" +SELF: Final = "Self" +HEADER_DELIMITER: Final = ";" class TraceHeader: def __init__( - self, root: str | None = ..., parent: str | None = ..., sampled: bool | None = ..., data: dict[str, Any] | None = ... + self, + root: str | None = None, + parent: str | None = None, + sampled: _Sampled | None = None, + data: dict[str, Incomplete] | None = None, ) -> None: ... @classmethod - def from_header_str(cls, header): ... - def to_header_str(self): ... + def from_header_str(cls, header: str | None) -> Self: ... + def to_header_str(self) -> str: ... @property - def root(self): ... + def root(self) -> str | None: ... @property - def parent(self): ... + def parent(self) -> str | None: ... @property - def sampled(self): ... + def sampled(self) -> Literal[1, 0, "?"] | None: ... @property - def data(self): ... + def data(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi index 6c00ccd4f2a6..3d076c862f95 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi @@ -1,8 +1,8 @@ -from typing import Any +from typing import ClassVar class TraceId: - VERSION: str - DELIMITER: str - start_time: Any + VERSION: ClassVar[str] + DELIMITER: ClassVar[str] + start_time: int def __init__(self) -> None: ... - def to_id(self): ... + def to_id(self) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi index 49a46c7b1d65..6b9f5d73226a 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi @@ -1,13 +1,12 @@ +from collections.abc import Iterable from logging import Logger -from typing import Any, Iterable - -from aws_xray_sdk import global_sdk_config as global_sdk_config - -from .utils.compat import PY2 as PY2, is_classmethod as is_classmethod, is_instance_method as is_instance_method +from typing import Final log: Logger -SUPPORTED_MODULES: Any -NO_DOUBLE_PATCH: Any +SUPPORTED_MODULES: Final[tuple[str, ...]] +NO_DOUBLE_PATCH: Final[tuple[str, ...]] -def patch_all(double_patch: bool = ...) -> None: ... -def patch(modules_to_patch: Iterable[str], raise_errors: bool = ..., ignore_module_patterns: str | None = ...) -> None: ... +def patch_all(double_patch: bool = False) -> None: ... +def patch( + modules_to_patch: Iterable[str], raise_errors: bool = True, ignore_module_patterns: Iterable[str] | None = None +) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi index b2ea7957d470..b5af18b73702 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi @@ -1,12 +1,18 @@ -from typing import Any +from collections.abc import MutableMapping +from logging import Logger +from typing import Any, Final, overload -log: Any -SERVICE_NAME: str -ORIGIN: str -IMDS_URL: str +log: Logger +SERVICE_NAME: Final = "ec2" +ORIGIN: Final = "AWS::EC2::Instance" +IMDS_URL: Final = "http://169.254.169.254/latest/" def initialize() -> None: ... -def get_token(): ... -def get_metadata(token: Any | None = ...): ... -def parse_metadata_json(json_str): ... -def do_request(url, headers: Any | None = ..., method: str = ...): ... +def get_token() -> str | None: ... +def get_metadata(token: str | None = None) -> dict[str, Any]: ... # result of parse_metadata_json() +def parse_metadata_json(json_str: str | bytes | bytearray) -> dict[str, Any]: ... # result of json.loads() + +@overload +def do_request(url: str, headers: MutableMapping[str, str] | None = None, method: str = "GET") -> str: ... +@overload +def do_request(url: None, headers: MutableMapping[str, str] | None = None, method: str = "GET") -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi index 56a4a90b0972..019494fb0c57 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi @@ -1,7 +1,8 @@ -from typing import Any +from logging import Logger +from typing import Final -log: Any -SERVICE_NAME: str -ORIGIN: str +log: Logger +SERVICE_NAME: Final = "ecs" +ORIGIN: Final = "AWS::ECS::Container" def initialize() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi index 8fd94a5e18c3..9ac631478457 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi @@ -1,8 +1,9 @@ -from typing import Any +from logging import Logger +from typing import Final -log: Any -CONF_PATH: str -SERVICE_NAME: str -ORIGIN: str +log: Logger +CONF_PATH: Final = "/var/elasticbeanstalk/xray/environment.conf" +SERVICE_NAME: Final = "elastic_beanstalk" +ORIGIN: Final = "AWS::ElasticBeanstalk::Environment" def initialize() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi index 9d521e65160c..6dbc20343cb6 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi @@ -1,8 +1,8 @@ -from typing import Any +from collections.abc import Iterable +from types import ModuleType +from typing import Final -from ..exceptions.exceptions import MissingPluginNames as MissingPluginNames +module_prefix: Final[str] +PLUGIN_MAPPING: Final[dict[str, str]] -module_prefix: str -PLUGIN_MAPPING: Any - -def get_plugin_modules(plugins): ... +def get_plugin_modules(plugins: Iterable[str]) -> tuple[ModuleType, ...]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi index f1c47af48298..905bcb2e7837 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi @@ -1,123 +1,129 @@ import time +from _typeshed import FileDescriptorOrPath, Incomplete +from collections.abc import Callable, Iterable, Mapping from logging import Logger -from typing import Any, Callable, Iterable +from typing import Any, Final, TypeVar -from aws_xray_sdk import global_sdk_config as global_sdk_config -from aws_xray_sdk.version import VERSION as VERSION - -from .context import Context as Context -from .daemon_config import DaemonConfig as DaemonConfig -from .emitters.udp_emitter import UDPEmitter as UDPEmitter -from .exceptions.exceptions import ( - SegmentNameMissingException as SegmentNameMissingException, - SegmentNotFoundException as SegmentNotFoundException, -) -from .lambda_launcher import check_in_lambda as check_in_lambda -from .models.default_dynamic_naming import DefaultDynamicNaming as DefaultDynamicNaming -from .models.dummy_entities import DummySegment as DummySegment, DummySubsegment as DummySubsegment -from .models.segment import Segment as Segment, SegmentContextManager as SegmentContextManager -from .models.subsegment import Subsegment as Subsegment, SubsegmentContextManager as SubsegmentContextManager -from .plugins.utils import get_plugin_modules as get_plugin_modules -from .sampling.local.sampler import LocalSampler as LocalSampler -from .sampling.sampler import DefaultSampler as DefaultSampler -from .streaming.default_streaming import DefaultStreaming as DefaultStreaming -from .utils import stacktrace as stacktrace -from .utils.compat import string_types as string_types +from .context import Context +from .emitters.udp_emitter import UDPEmitter +from .models.default_dynamic_naming import DefaultDynamicNaming +from .models.dummy_entities import DummySegment, DummySubsegment +from .models.segment import Segment, SegmentContextManager +from .models.subsegment import Subsegment, SubsegmentContextManager +from .sampling.local.sampler import LocalSampler +from .sampling.sampler import DefaultSampler +from .streaming.default_streaming import DefaultStreaming log: Logger -TRACING_NAME_KEY: str -DAEMON_ADDR_KEY: str -CONTEXT_MISSING_KEY: str -XRAY_META: Any -SERVICE_INFO: Any +TRACING_NAME_KEY: Final = "AWS_XRAY_TRACING_NAME" +DAEMON_ADDR_KEY: Final = "AWS_XRAY_DAEMON_ADDRESS" +CONTEXT_MISSING_KEY: Final = "AWS_XRAY_CONTEXT_MISSING" +XRAY_META: Final[dict[str, dict[str, str]]] +SERVICE_INFO: Final[dict[str, str]] + +_T = TypeVar("_T") class AWSXRayRecorder: def __init__(self) -> None: ... def configure( self, - sampling: bool | None = ..., - plugins: Iterable[str] | None = ..., - context_missing: str | None = ..., - sampling_rules: dict[str, Any] | str | None = ..., - daemon_address: str | None = ..., - service: str | None = ..., - context: Context | None = ..., - emitter: UDPEmitter | None = ..., - streaming: DefaultStreaming | None = ..., - dynamic_naming: DefaultDynamicNaming | None = ..., - streaming_threshold: int | None = ..., - max_trace_back: int | None = ..., - sampler: LocalSampler | DefaultSampler | None = ..., - stream_sql: bool | None = ..., + sampling: bool | None = None, + plugins: Iterable[str] | None = None, + context_missing: str | None = None, + sampling_rules: dict[str, Any] | FileDescriptorOrPath | None = None, + daemon_address: str | None = None, + service: str | None = None, + context: Context | None = None, + emitter: UDPEmitter | None = None, + streaming: DefaultStreaming | None = None, + dynamic_naming: DefaultDynamicNaming | None = None, + streaming_threshold: int | None = None, + max_trace_back: int | None = None, + sampler: LocalSampler | DefaultSampler | None = None, + stream_sql: bool | None = True, ) -> None: ... - def in_segment(self, name: str | None = ..., **segment_kwargs) -> SegmentContextManager: ... - def in_subsegment(self, name: str | None = ..., **subsegment_kwargs) -> SubsegmentContextManager: ... + def in_segment( + self, name: str | None = None, *, traceid: str | None = None, parent_id: str | None = None, sampling: bool | None = None + ) -> SegmentContextManager: ... + def in_subsegment(self, name: str | None = None, *, namespace: str = "local") -> SubsegmentContextManager: ... def begin_segment( - self, name: str | None = ..., traceid: str | None = ..., parent_id: str | None = ..., sampling: bool | None = ... + self, name: str | None = None, traceid: str | None = None, parent_id: str | None = None, sampling: bool | None = None ) -> Segment | DummySegment: ... - def end_segment(self, end_time: time.struct_time | None = ...) -> None: ... + def end_segment(self, end_time: time.struct_time | None = None) -> None: ... def current_segment(self) -> Segment: ... - def begin_subsegment(self, name: str, namespace: str = ...) -> DummySubsegment | Subsegment | None: ... + def begin_subsegment(self, name: str, namespace: str = "local") -> DummySubsegment | Subsegment | None: ... + def begin_subsegment_without_sampling(self, name: str) -> DummySubsegment | Subsegment | None: ... def current_subsegment(self) -> Subsegment | DummySubsegment | None: ... - def end_subsegment(self, end_time: time.struct_time | None = ...) -> None: ... + def end_subsegment(self, end_time: time.struct_time | None = None) -> None: ... def put_annotation(self, key: str, value: Any) -> None: ... - def put_metadata(self, key: str, value: Any, namespace: str = ...) -> None: ... + def put_metadata(self, key: str, value: Any, namespace: str = "default") -> None: ... def is_sampled(self) -> bool: ... def get_trace_entity(self) -> Segment | Subsegment | DummySegment | DummySubsegment: ... def set_trace_entity(self, trace_entity: Segment | Subsegment | DummySegment | DummySubsegment) -> None: ... def clear_trace_entities(self) -> None: ... def stream_subsegments(self) -> None: ... - def capture(self, name: str | None = ...) -> SubsegmentContextManager: ... + def capture(self, name: str | None = None) -> SubsegmentContextManager: ... def record_subsegment( self, - wrapped: Callable[..., Any], + wrapped: Callable[..., _T], instance: Any, - args: list[Any], - kwargs: dict[str, Any], + args: Iterable[Incomplete], + kwargs: Mapping[str, Incomplete], name: str, namespace: str, - meta_processor: Callable[..., Any], - ) -> Any: ... + meta_processor: Callable[..., object] | None, + ) -> _T: ... + @property def enabled(self) -> bool: ... @enabled.setter def enabled(self, value: bool) -> None: ... + @property def sampling(self) -> bool: ... @sampling.setter def sampling(self, value: bool) -> None: ... + @property def sampler(self) -> LocalSampler | DefaultSampler: ... @sampler.setter def sampler(self, value: LocalSampler | DefaultSampler) -> None: ... + @property def service(self) -> str: ... @service.setter def service(self, value: str) -> None: ... + @property - def dynamic_naming(self) -> Any | DefaultDynamicNaming: ... + def dynamic_naming(self) -> DefaultDynamicNaming | None: ... @dynamic_naming.setter - def dynamic_naming(self, value: Any | DefaultDynamicNaming) -> None: ... + def dynamic_naming(self, value: DefaultDynamicNaming | str) -> None: ... + @property def context(self) -> Context: ... @context.setter def context(self, cxt: Context) -> None: ... + @property def emitter(self) -> UDPEmitter: ... @emitter.setter def emitter(self, value: UDPEmitter) -> None: ... + @property def streaming(self) -> DefaultStreaming: ... @streaming.setter def streaming(self, value: DefaultStreaming) -> None: ... + @property def streaming_threshold(self) -> int: ... @streaming_threshold.setter def streaming_threshold(self, value: int) -> None: ... + @property def max_trace_back(self) -> int: ... @max_trace_back.setter def max_trace_back(self, value: int) -> None: ... + @property def stream_sql(self) -> bool: ... @stream_sql.setter diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi index 8edea3c58133..4fe3bcedb95d 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi @@ -1,17 +1,16 @@ -from datetime import datetime as datetime +from _typeshed import Incomplete -from aws_xray_sdk.core.context import Context as Context -from aws_xray_sdk.core.models.dummy_entities import DummySegment as DummySegment -from aws_xray_sdk.core.utils.compat import PY2 as PY2 +from aws_xray_sdk.core.context import Context -from .sampling_rule import SamplingRule as SamplingRule +from .sampling_rule import SamplingRule class ServiceConnector: def __init__(self) -> None: ... - def fetch_sampling_rules(self): ... - def fetch_sampling_target(self, rules): ... - def setup_xray_client(self, ip, port, client) -> None: ... + def fetch_sampling_rules(self) -> list[SamplingRule]: ... + def fetch_sampling_target(self, rules) -> tuple[Incomplete, int]: ... + def setup_xray_client(self, ip: str, port: str | int, client) -> None: ... + @property - def context(self): ... + def context(self) -> Context: ... @context.setter - def context(self, v) -> None: ... + def context(self, v: Context) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi index aa5836b3e4b2..9263428ef9cf 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi @@ -1,8 +1,6 @@ -from typing import Any - class Reservoir: - traces_per_sec: Any + traces_per_sec: int used_this_sec: int - this_sec: Any - def __init__(self, traces_per_sec: int = ...) -> None: ... - def take(self): ... + this_sec: int + def __init__(self, traces_per_sec: int = 0) -> None: ... + def take(self) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi index 0fc18cd23354..f4bf2f677537 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi @@ -1,12 +1,18 @@ -from typing import Any +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired -from ...exceptions.exceptions import InvalidSamplingManifestError as InvalidSamplingManifestError -from .sampling_rule import SamplingRule as SamplingRule +from .sampling_rule import SamplingRule, _Rule -local_sampling_rule: Any -SUPPORTED_RULE_VERSION: Any +@type_check_only +class _SamplingRule(TypedDict): + version: NotRequired[int] + default: _Rule + rules: list[_Rule] + +local_sampling_rule: _SamplingRule +SUPPORTED_RULE_VERSION: tuple[int, ...] class LocalSampler: - def __init__(self, rules=...) -> None: ... - def should_trace(self, sampling_req: Any | None = ...): ... - def load_local_rules(self, rules) -> None: ... + def __init__(self, rules: _SamplingRule = ...) -> None: ... + def should_trace(self, sampling_req: SamplingRule | None = None) -> bool: ... + def load_local_rules(self, rules: _SamplingRule) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi index ff8f23b7c103..418c386559e6 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi @@ -1,28 +1,38 @@ -from aws_xray_sdk.core.utils.search_pattern import wildcard_match as wildcard_match +from typing import ClassVar, TypedDict, type_check_only +from typing_extensions import NotRequired -from ...exceptions.exceptions import InvalidSamplingManifestError as InvalidSamplingManifestError -from .reservoir import Reservoir as Reservoir +from .reservoir import Reservoir + +@type_check_only +class _Rule(TypedDict): + description: NotRequired[str] + host: NotRequired[str] + service_name: NotRequired[str] + http_method: NotRequired[str] + url_path: NotRequired[str] + fixed_target: NotRequired[int] + rate: NotRequired[float] class SamplingRule: - FIXED_TARGET: str - RATE: str - HOST: str - METHOD: str - PATH: str - SERVICE_NAME: str - def __init__(self, rule_dict, version: int = ..., default: bool = ...) -> None: ... - def applies(self, host, method, path): ... + FIXED_TARGET: ClassVar[str] + RATE: ClassVar[str] + HOST: ClassVar[str] + METHOD: ClassVar[str] + PATH: ClassVar[str] + SERVICE_NAME: ClassVar[str] + def __init__(self, rule_dict: _Rule, version: int = 2, default: bool = False) -> None: ... + def applies(self, host: str | None, method: str | None, path: str | None) -> bool: ... @property - def fixed_target(self): ... + def fixed_target(self) -> int | None: ... @property - def rate(self): ... + def rate(self) -> float | None: ... @property - def host(self): ... + def host(self) -> str | None: ... @property - def method(self): ... + def method(self) -> str | None: ... @property - def path(self): ... + def path(self) -> str | None: ... @property - def reservoir(self): ... + def reservoir(self) -> Reservoir: ... @property def version(self): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi index 322d1d38c3d8..10b5b2b7cad9 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi @@ -2,14 +2,14 @@ from enum import Enum class Reservoir: def __init__(self) -> None: ... - def borrow_or_take(self, now, can_borrow): ... - def load_quota(self, quota, TTL, interval) -> None: ... + def borrow_or_take(self, now: int, can_borrow: bool | None) -> ReservoirDecision | None: ... + def load_quota(self, quota: int | None, TTL: int | None, interval: int | None) -> None: ... @property - def quota(self): ... + def quota(self) -> int | None: ... @property - def TTL(self): ... + def TTL(self) -> int | None: ... class ReservoirDecision(Enum): - TAKE: str - BORROW: str - NO: str + TAKE = "take" + BORROW = "borrow" + NO = "no" diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi index cccd9105b130..e28044cf0880 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi @@ -1,17 +1,19 @@ -from typing import Any +from typing import Final -TTL: Any +TTL: Final = 3600 class RuleCache: def __init__(self) -> None: ... - def get_matched_rule(self, sampling_req, now): ... + def get_matched_rule(self, sampling_req, now: float): ... def load_rules(self, rules) -> None: ... def load_targets(self, targets_dict) -> None: ... + @property def rules(self): ... @rules.setter def rules(self, v) -> None: ... + @property - def last_updated(self): ... + def last_updated(self) -> int | None: ... @last_updated.setter - def last_updated(self, v) -> None: ... + def last_updated(self, v: int | None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi index dc4b3633802b..5f1f6c3caf5a 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi @@ -1,9 +1,13 @@ -from typing import Any +from logging import Logger +from typing import Final -log: Any -DEFAULT_INTERVAL: Any +from .connector import ServiceConnector +from .rule_cache import RuleCache + +log: Logger +DEFAULT_INTERVAL: Final = 300 class RulePoller: - def __init__(self, cache, connector) -> None: ... + def __init__(self, cache: RuleCache, connector: ServiceConnector) -> None: ... def start(self) -> None: ... def wake_up(self) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi index 631109572ed0..4f8ea28cd3d5 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi @@ -1,20 +1,16 @@ -from typing import Any +from logging import Logger -from .connector import ServiceConnector as ServiceConnector -from .local.sampler import LocalSampler as LocalSampler -from .reservoir import ReservoirDecision as ReservoirDecision -from .rule_cache import RuleCache as RuleCache -from .rule_poller import RulePoller as RulePoller -from .target_poller import TargetPoller as TargetPoller +from aws_xray_sdk.core.daemon_config import DaemonConfig -log: Any +log: Logger class DefaultSampler: def __init__(self) -> None: ... def start(self) -> None: ... - def should_trace(self, sampling_req: Any | None = ...): ... + def should_trace(self, sampling_req=None): ... def load_local_rules(self, rules) -> None: ... - def load_settings(self, daemon_config, context, origin: Any | None = ...) -> None: ... + def load_settings(self, daemon_config: DaemonConfig, context, origin=None) -> None: ... + @property def xray_client(self): ... @xray_client.setter diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi index 2b47ac65e65c..440fba9c4aeb 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi @@ -1,47 +1,47 @@ -from typing import Any +from typing import Literal, TypedDict, type_check_only -from ..utils.search_pattern import wildcard_match as wildcard_match -from .reservoir import Reservoir as Reservoir +from .reservoir import Reservoir + +@type_check_only +class _Stats(TypedDict): + request_count: int + borrow_count: int + sampled_count: int class SamplingRule: def __init__( - self, - name, - priority, - rate, - reservoir_size, - host: Any | None = ..., - method: Any | None = ..., - path: Any | None = ..., - service: Any | None = ..., - service_type: Any | None = ..., + self, name: str, priority, rate, reservoir_size, host=None, method=None, path=None, service=None, service_type=None ) -> None: ... - def match(self, sampling_req): ... - def is_default(self): ... - def snapshot_statistics(self): ... + def match(self, sampling_req) -> bool: ... + def is_default(self) -> bool: ... + def snapshot_statistics(self) -> _Stats: ... def merge(self, rule) -> None: ... - def ever_matched(self): ... - def time_to_report(self): ... + def ever_matched(self) -> bool: ... + def time_to_report(self) -> Literal[True] | None: ... def increment_request_count(self) -> None: ... def increment_borrow_count(self) -> None: ... def increment_sampled_count(self) -> None: ... + @property def rate(self): ... @rate.setter def rate(self, v) -> None: ... + @property - def name(self): ... + def name(self) -> str: ... @property def priority(self): ... + @property - def reservoir(self): ... + def reservoir(self) -> Reservoir: ... @reservoir.setter - def reservoir(self, v) -> None: ... + def reservoir(self, v: Reservoir) -> None: ... + @property - def can_borrow(self): ... + def can_borrow(self) -> bool: ... @property - def request_count(self): ... + def request_count(self) -> int: ... @property - def borrow_count(self): ... + def borrow_count(self) -> int: ... @property - def sampled_count(self): ... + def sampled_count(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi index 4be740c6cd0f..7a1a5ff753b1 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi @@ -1,7 +1,11 @@ -from typing import Any +from logging import Logger -log: Any +from .connector import ServiceConnector +from .rule_cache import RuleCache +from .rule_poller import RulePoller + +log: Logger class TargetPoller: - def __init__(self, cache, rule_poller, connector) -> None: ... + def __init__(self, cache: RuleCache, rule_poller: RulePoller, connector: ServiceConnector) -> None: ... def start(self) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi index 21309ebd83e2..cca12298fe5d 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi @@ -1,8 +1,15 @@ +from _typeshed import Unused +from collections.abc import Callable + +from aws_xray_sdk.core.models.entity import Entity +from aws_xray_sdk.core.models.segment import Segment + class DefaultStreaming: - def __init__(self, streaming_threshold: int = ...) -> None: ... - def is_eligible(self, segment): ... - def stream(self, entity, callback) -> None: ... + def __init__(self, streaming_threshold: int = 30) -> None: ... + def is_eligible(self, segment: Segment) -> bool: ... + def stream(self, entity: Entity, callback: Callable[..., Unused]) -> None: ... + @property - def streaming_threshold(self): ... + def streaming_threshold(self) -> int: ... @streaming_threshold.setter - def streaming_threshold(self, value) -> None: ... + def streaming_threshold(self, value: int) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi index 9cf8ebcd0536..66a7fb051c4e 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi @@ -1,9 +1,7 @@ -from typing import Any - class AtomicCounter: - value: Any - def __init__(self, initial: int = ...) -> None: ... - def increment(self, num: int = ...): ... - def decrement(self, num: int = ...): ... - def get_current(self): ... - def reset(self): ... + value: int + def __init__(self, initial: int = 0) -> None: ... + def increment(self, num: int = 1) -> int: ... + def decrement(self, num: int = 1) -> int: ... + def get_current(self) -> int: ... + def reset(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi index 676b8b356d98..f6e9aa45654e 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi @@ -1,9 +1,4 @@ -from typing import Any +annotation_value_types: tuple[type, ...] -PY2: Any -PY35: Any -annotation_value_types: Any -string_types = str - -def is_classmethod(func): ... -def is_instance_method(parent_class, func_name, func): ... +def is_classmethod(func: object) -> bool: ... # argument func is passing to getattr() function +def is_instance_method(parent_class: type, func_name: str, func: object) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi index f8c141418d0d..c5201d5b6e04 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi @@ -1,5 +1,13 @@ -from typing import Any +from logging import Logger +from typing import Any, TypeVar, overload -log: Any +_K = TypeVar("_K") -def metadata_to_dict(obj): ... +log: Logger + +@overload +def metadata_to_dict(obj: dict[_K, Any]) -> dict[_K, Any]: ... +@overload +def metadata_to_dict(obj: type) -> str: ... +@overload +def metadata_to_dict(obj: Any) -> Any: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi index 5206e243f5a7..94b94e569186 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi @@ -1 +1,8 @@ -def wildcard_match(pattern, text, case_insensitive: bool = ...): ... +from typing import Literal, overload + +@overload +def wildcard_match(pattern: None, text: str, case_insensitive: bool = True) -> Literal[False]: ... +@overload +def wildcard_match(pattern: str, text: None, case_insensitive: bool = True) -> Literal[False]: ... +@overload +def wildcard_match(pattern: str, text: str, case_insensitive: bool = True) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi new file mode 100644 index 000000000000..c4c90e27adf6 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import Final + +SQS_XRAY_HEADER: Final = "AWSTraceHeader" + +class SqsMessageHelper: + @staticmethod + def isSampled(sqs_message: Mapping[str, Incomplete]) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi index 8c6c43654a90..fd7daa078301 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi @@ -1,3 +1,3 @@ -from typing import Any +import traceback -def get_stacktrace(limit: Any | None = ...): ... +def get_stacktrace(limit: int | None = None) -> list[traceback.FrameSummary]: ... diff --git a/stubs/cryptography/cryptography/hazmat/bindings/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/__init__.pyi similarity index 100% rename from stubs/cryptography/cryptography/hazmat/bindings/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/bindings/openssl/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/__init__.pyi similarity index 100% rename from stubs/cryptography/cryptography/hazmat/bindings/openssl/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi new file mode 100644 index 000000000000..dd4500f9d662 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi @@ -0,0 +1,10 @@ +from typing import Final + +REMOTE_NAMESPACE: Final = "remote" +LOCAL_NAMESPACE: Final = "local" +LOCAL_EXCEPTIONS: tuple[type[Exception], ...] + +async def begin_subsegment(session, trace_config_ctx, params): ... +async def end_subsegment(session, trace_config_ctx, params): ... +async def end_subsegment_with_exception(session, trace_config_ctx, params): ... +def aws_xray_trace_config(name=None): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi new file mode 100644 index 000000000000..93fab0a1f06c --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi @@ -0,0 +1 @@ +async def middleware(request, handler): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi new file mode 100644 index 000000000000..29a962e55ed0 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +whitelist: Incomplete + +def inject_header(wrapped, instance, args, kwargs): ... +def aws_meta_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/futures/@python2/concurrent/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/__init__.pyi similarity index 100% rename from stubs/futures/@python2/concurrent/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi new file mode 100644 index 000000000000..5470f17a3482 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import ClassVar + +class XRayMiddleware: + name: ClassVar[str] + api: ClassVar[int] + def __init__(self, recorder) -> None: ... + def apply(self, callback: Callable[..., Incomplete], route) -> Callable[..., Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi new file mode 100644 index 000000000000..df291e1040cd --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi @@ -0,0 +1,14 @@ +from typing_extensions import Self + +class XRayTracedConn: + def __init__(self, conn, meta={}) -> None: ... + def cursor(self, *args, **kwargs) -> XRayTracedCursor: ... + +class XRayTracedCursor: + def __init__(self, cursor, meta={}) -> None: ... + def __enter__(self) -> Self: ... + def execute(self, query, *args, **kwargs): ... + def executemany(self, query, *args, **kwargs): ... + def callproc(self, proc, args): ... + +def add_sql_meta(meta) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi new file mode 100644 index 000000000000..c4741233700b --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +default_app_config: Final = "aws_xray_sdk.ext.django.apps.XRayConfig" diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi new file mode 100644 index 000000000000..b00e299307b4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi @@ -0,0 +1,8 @@ +from logging import Logger +from typing import ClassVar + +log: Logger + +class XRayConfig: + name: ClassVar[str] + def ready(self) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi new file mode 100644 index 000000000000..538c47697398 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import Final + +DEFAULTS: dict[str, str | bool | tuple[Incomplete] | list[Incomplete] | None] +XRAY_NAMESPACE: Final = "XRAY_RECORDER" +SUPPORTED_ENV_VARS: tuple[str, ...] + +class XRaySettings: + defaults: dict[str, str | bool | tuple[Incomplete] | list[Incomplete] | None] + def __init__(self, user_settings=None) -> None: ... + @property + def user_settings(self): ... + def __getattr__(self, attr): ... + +settings: XRaySettings + +def reload_settings(*, settings: str | None = None, value=None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi new file mode 100644 index 000000000000..d71b2856e342 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi @@ -0,0 +1,12 @@ +from logging import Logger + +from aws_xray_sdk.ext.dbapi2 import XRayTracedCursor + +log: Logger + +def patch_db() -> None: ... + +class DjangoXRayTracedCursor(XRayTracedCursor): + def execute(self, query, *args, **kwargs): ... + def executemany(self, query, *args, **kwargs): ... + def callproc(self, proc, args): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi new file mode 100644 index 000000000000..d5d5a1faa7cb --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Final + +log: Logger + +USER_AGENT_KEY: Final = "HTTP_USER_AGENT" +X_FORWARDED_KEY: Final = "HTTP_X_FORWARDED_FOR" +REMOTE_ADDR_KEY: Final = "REMOTE_ADDR" +HOST_KEY: Final = "HTTP_HOST" +CONTENT_LENGTH_KEY: Final = "content-length" + +class XRayMiddleware: + get_response: Incomplete + in_lambda_ctx: bool + + def __init__(self, get_response) -> None: ... + def __call__(self, request): ... + def process_exception(self, request, exception: Exception) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi new file mode 100644 index 000000000000..142de83de16e --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi @@ -0,0 +1,5 @@ +from logging import Logger + +log: Logger + +def patch_template() -> None: ... diff --git a/stubs/google-cloud-ndb/google/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/__init__.pyi similarity index 100% rename from stubs/google-cloud-ndb/google/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi new file mode 100644 index 000000000000..ab8e8a2feb4d --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +class XRayMiddleware: + app: Incomplete + in_lambda_ctx: bool + def __init__(self, app, recorder) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/__init__.pyi similarity index 100% rename from stubs/google-cloud-ndb/google/cloud/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi new file mode 100644 index 000000000000..0f0f512d4fa9 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from aws_xray_sdk.ext.sqlalchemy.query import XRaySession + +class XRayBaseQuery: ... + +class XRaySignallingSession(XRaySession): + app: Incomplete + def __init__(self, db, autocommit: bool = False, autoflush: bool = True, **options) -> None: ... + def get_bind(self, mapper=None, clause=None): ... + +class XRayFlaskSqlAlchemy: + def __init__( + self, + app=None, + use_native_unicode: bool = True, + session_options=None, + metadata=None, + query_class: type = ..., + model_class: type = ..., + ) -> None: ... + def create_session(self, options: dict[str, Incomplete]): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi new file mode 100644 index 000000000000..4f5e3a65b1c0 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import add_ignored as add_ignored, patch as patch, reset_ignored as reset_ignored, unpatch as unpatch + +__all__ = ["patch", "unpatch", "add_ignored", "reset_ignored"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi new file mode 100644 index 000000000000..aaa85125c03a --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi @@ -0,0 +1,12 @@ +from typing import Final + +httplib_client_module: Final = "http.client" +PATCH_FLAG: Final = "__xray_patched" + +def add_ignored(subclass=None, hostname=None, urls=None) -> None: ... +def reset_ignored() -> None: ... +def http_response_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... +def http_send_request_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... +def http_read_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... +def patch() -> None: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi new file mode 100644 index 000000000000..b50265a56940 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi @@ -0,0 +1,9 @@ +def patch() -> None: ... + +class SyncInstrumentedTransport: + def __init__(self, transport): ... + def handle_request(self, request): ... + +class AsyncInstrumentedTransport: + def __init__(self, transport): ... + async def handle_async_request(self, request): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi new file mode 100644 index 000000000000..4b8b7d49c3a0 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi @@ -0,0 +1,6 @@ +from typing import Final + +MYSQL_ATTR: Final[dict[str, str]] + +def patch() -> None: ... +def sanitize_db_ver(raw: tuple[str]) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi new file mode 100644 index 000000000000..b65967051d08 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch, unpatch as unpatch + +__all__ = ["patch", "unpatch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi new file mode 100644 index 000000000000..86f5664ff977 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi @@ -0,0 +1,2 @@ +def patch() -> None: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi new file mode 100644 index 000000000000..21c4ac034cb5 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi @@ -0,0 +1,8 @@ +class XrayCommandListener: + record_full_documents: bool + def __init__(self, record_full_documents: bool) -> None: ... + def started(self, event) -> None: ... + def succeeded(self, event) -> None: ... + def failed(self, event) -> None: ... + +def patch(record_full_documents: bool = False) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi new file mode 100644 index 000000000000..b65967051d08 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch, unpatch as unpatch + +__all__ = ["patch", "unpatch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi new file mode 100644 index 000000000000..a8cbba7f52bb --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi @@ -0,0 +1,3 @@ +def patch() -> None: ... +def sanitize_db_ver(raw: tuple[str]) -> str: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi new file mode 100644 index 000000000000..d86fc62fb297 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi @@ -0,0 +1,6 @@ +from typing import Final + +PYNAMODB4: Final[bool] + +def patch() -> None: ... +def pynamodb_meta_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi new file mode 100644 index 000000000000..bd200a3bfbc1 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi @@ -0,0 +1,2 @@ +def patch() -> None: ... +def requests_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... diff --git a/stubs/protobuf/google/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/__init__.pyi similarity index 100% rename from stubs/protobuf/google/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi new file mode 100644 index 000000000000..6a54d0d6e23d --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi @@ -0,0 +1,16 @@ +from typing import Any + +class XRaySession: ... +class XRayQuery: ... + +class XRaySessionMaker: + def __init__( + self, + bind=None, + class_: type = ..., + autoflush: bool = True, + autocommit: bool = False, + expire_on_commit: bool = True, + info: dict[Any, Any] | None = None, # it was taken from sqlalchemy stubs + **kw, + ) -> None: ... diff --git a/stubs/pyOpenSSL/OpenSSL/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/__init__.pyi similarity index 100% rename from stubs/pyOpenSSL/OpenSSL/__init__.pyi rename to stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/__init__.pyi diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi new file mode 100644 index 000000000000..78ffee475aed --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +def decorate_all_functions(function_decorator: Callable[..., Incomplete]) -> Callable[..., Incomplete]: ... +def xray_on_call(cls, func: Callable[..., Incomplete]) -> Callable[..., Incomplete]: ... +def parse_bind(bind) -> dict[str, str]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi new file mode 100644 index 000000000000..b65967051d08 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch, unpatch as unpatch + +__all__ = ["patch", "unpatch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi new file mode 100644 index 000000000000..86f5664ff977 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi @@ -0,0 +1,2 @@ +def patch() -> None: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi new file mode 100644 index 000000000000..71954e425e43 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi @@ -0,0 +1,7 @@ +from aws_xray_sdk.ext.dbapi2 import XRayTracedConn + +def patch() -> None: ... + +class XRayTracedSQLite(XRayTracedConn): + def execute(self, *args, **kwargs): ... + def executemany(self, *args, **kwargs): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi new file mode 100644 index 000000000000..466fceaa1323 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi @@ -0,0 +1,23 @@ +import re +from typing import Final, overload + +from aws_xray_sdk.core.models.trace_header import TraceHeader + +first_cap_re: Final[re.Pattern[str]] +all_cap_re: Final[re.Pattern[str]] +UNKNOWN_HOSTNAME: Final = "UNKNOWN HOST" + +def inject_trace_header(headers, entity) -> None: ... +def calculate_sampling_decision(trace_header, recorder, sampling_req): ... +def construct_xray_header(headers) -> TraceHeader: ... +def calculate_segment_name(host_name, recorder): ... +def prepare_response_header(origin_header, segment) -> str: ... +def to_snake_case(name: str) -> str: ... +def strip_url(url): ... + +@overload +def get_hostname(url: str | None) -> str: ... +@overload +def get_hostname(url: bytes | bytearray | None) -> str | bytes: ... + +def unwrap(obj: object, attr: str) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi index c76b34d0a649..f9a79a65a89e 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi @@ -1,11 +1,12 @@ from logging import Logger +from typing import ClassVar log: Logger class SDKConfig: - XRAY_ENABLED_KEY: str - DISABLED_ENTITY_NAME: str + XRAY_ENABLED_KEY: ClassVar[str] + DISABLED_ENTITY_NAME: ClassVar[str] @classmethod - def sdk_enabled(cls): ... + def sdk_enabled(cls) -> bool: ... @classmethod - def set_sdk_enabled(cls, value) -> None: ... + def set_sdk_enabled(cls, value: bool | None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi index 3acee936dc41..8052b08139fb 100644 --- a/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi +++ b/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi @@ -1 +1,3 @@ -VERSION: str +from typing import Final + +VERSION: Final[str] diff --git a/stubs/babel/@tests/stubtest_allowlist.txt b/stubs/babel/@tests/stubtest_allowlist.txt deleted file mode 100644 index fb000897a30e..000000000000 --- a/stubs/babel/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,3 +0,0 @@ -# In the stub we alias to OrderedDict, but it has positional-only differences -babel.util.odict.fromkeys -babel.util.odict.setdefault diff --git a/stubs/babel/METADATA.toml b/stubs/babel/METADATA.toml deleted file mode 100644 index 0009f38f042f..000000000000 --- a/stubs/babel/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "2.9.*" \ No newline at end of file diff --git a/stubs/babel/babel/__init__.pyi b/stubs/babel/babel/__init__.pyi deleted file mode 100644 index c046a8c081ab..000000000000 --- a/stubs/babel/babel/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from babel.core import ( - Locale as Locale, - UnknownLocaleError as UnknownLocaleError, - default_locale as default_locale, - get_locale_identifier as get_locale_identifier, - negotiate_locale as negotiate_locale, - parse_locale as parse_locale, -) diff --git a/stubs/babel/babel/_compat.pyi b/stubs/babel/babel/_compat.pyi deleted file mode 100644 index 6247814e9887..000000000000 --- a/stubs/babel/babel/_compat.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -PY2: Any -text_type = str -string_types: Any -integer_types: Any -text_to_native: Any -unichr = chr -iterkeys: Any -itervalues: Any -iteritems: Any -izip = zip -imap = map -range_type = range -cmp: Any -array_tobytes: Any -number_types: Any - -def force_text(s, encoding: str = ..., errors: str = ...): ... diff --git a/stubs/babel/babel/core.pyi b/stubs/babel/babel/core.pyi deleted file mode 100644 index 9c274f73ad5e..000000000000 --- a/stubs/babel/babel/core.pyi +++ /dev/null @@ -1,110 +0,0 @@ -from typing import Any - -class UnknownLocaleError(Exception): - identifier: Any - def __init__(self, identifier) -> None: ... - -class Locale: - language: Any - territory: Any - script: Any - variant: Any - def __init__(self, language, territory: Any | None = ..., script: Any | None = ..., variant: Any | None = ...) -> None: ... - @classmethod - def default(cls, category: Any | None = ..., aliases=...): ... - @classmethod - def negotiate(cls, preferred, available, sep: str = ..., aliases=...): ... - @classmethod - def parse(cls, identifier, sep: str = ..., resolve_likely_subtags: bool = ...): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __hash__(self): ... - def get_display_name(self, locale: Any | None = ...): ... - display_name: Any - def get_language_name(self, locale: Any | None = ...): ... - language_name: Any - def get_territory_name(self, locale: Any | None = ...): ... - territory_name: Any - def get_script_name(self, locale: Any | None = ...): ... - script_name: Any - @property - def english_name(self): ... - @property - def languages(self): ... - @property - def scripts(self): ... - @property - def territories(self): ... - @property - def variants(self): ... - @property - def currencies(self): ... - @property - def currency_symbols(self): ... - @property - def number_symbols(self): ... - @property - def decimal_formats(self): ... - @property - def currency_formats(self): ... - @property - def percent_formats(self): ... - @property - def scientific_formats(self): ... - @property - def periods(self): ... - @property - def day_periods(self): ... - @property - def day_period_rules(self): ... - @property - def days(self): ... - @property - def months(self): ... - @property - def quarters(self): ... - @property - def eras(self): ... - @property - def time_zones(self): ... - @property - def meta_zones(self): ... - @property - def zone_formats(self): ... - @property - def first_week_day(self): ... - @property - def weekend_start(self): ... - @property - def weekend_end(self): ... - @property - def min_week_days(self): ... - @property - def date_formats(self): ... - @property - def time_formats(self): ... - @property - def datetime_formats(self): ... - @property - def datetime_skeletons(self): ... - @property - def interval_formats(self): ... - @property - def plural_form(self): ... - @property - def list_patterns(self): ... - @property - def ordinal_form(self): ... - @property - def measurement_systems(self): ... - @property - def character_order(self): ... - @property - def text_direction(self): ... - @property - def unit_display_names(self): ... - -def default_locale(category: Any | None = ..., aliases=...): ... -def negotiate_locale(preferred, available, sep: str = ..., aliases=...): ... -def parse_locale(identifier, sep: str = ...): ... -def get_locale_identifier(tup, sep: str = ...): ... diff --git a/stubs/babel/babel/dates.pyi b/stubs/babel/babel/dates.pyi deleted file mode 100644 index 29b3f8a80439..000000000000 --- a/stubs/babel/babel/dates.pyi +++ /dev/null @@ -1,98 +0,0 @@ -from datetime import date, datetime, time -from typing import Any - -NO_INHERITANCE_MARKER: str -LC_TIME: Any -date_ = date -datetime_ = datetime -time_ = time - -def get_timezone(zone: Any | None = ...): ... -def get_next_timezone_transition(zone: Any | None = ..., dt: Any | None = ...): ... - -class TimezoneTransition: - activates: Any - from_tzinfo: Any - to_tzinfo: Any - reference_date: Any - def __init__(self, activates, from_tzinfo, to_tzinfo, reference_date: Any | None = ...) -> None: ... - @property - def from_tz(self): ... - @property - def to_tz(self): ... - @property - def from_offset(self): ... - @property - def to_offset(self): ... - -def get_period_names(width: str = ..., context: str = ..., locale=...): ... -def get_day_names(width: str = ..., context: str = ..., locale=...): ... -def get_month_names(width: str = ..., context: str = ..., locale=...): ... -def get_quarter_names(width: str = ..., context: str = ..., locale=...): ... -def get_era_names(width: str = ..., locale=...): ... -def get_date_format(format: str = ..., locale=...): ... -def get_datetime_format(format: str = ..., locale=...): ... -def get_time_format(format: str = ..., locale=...): ... -def get_timezone_gmt(datetime: Any | None = ..., width: str = ..., locale=..., return_z: bool = ...): ... -def get_timezone_location(dt_or_tzinfo: Any | None = ..., locale=..., return_city: bool = ...): ... -def get_timezone_name( - dt_or_tzinfo: Any | None = ..., - width: str = ..., - uncommon: bool = ..., - locale=..., - zone_variant: Any | None = ..., - return_zone: bool = ..., -): ... -def format_date(date: Any | None = ..., format: str = ..., locale=...): ... -def format_datetime(datetime: Any | None = ..., format: str = ..., tzinfo: Any | None = ..., locale=...): ... -def format_time(time: Any | None = ..., format: str = ..., tzinfo: Any | None = ..., locale=...): ... -def format_skeleton(skeleton, datetime: Any | None = ..., tzinfo: Any | None = ..., fuzzy: bool = ..., locale=...): ... - -TIMEDELTA_UNITS: Any - -def format_timedelta( - delta, granularity: str = ..., threshold: float = ..., add_direction: bool = ..., format: str = ..., locale=... -): ... -def format_interval(start, end, skeleton: Any | None = ..., tzinfo: Any | None = ..., fuzzy: bool = ..., locale=...): ... -def get_period_id(time, tzinfo: Any | None = ..., type: Any | None = ..., locale=...): ... -def parse_date(string, locale=...): ... -def parse_time(string, locale=...): ... - -class DateTimePattern: - pattern: Any - format: Any - def __init__(self, pattern, format) -> None: ... - def __unicode__(self): ... - def __mod__(self, other): ... - def apply(self, datetime, locale): ... - -class DateTimeFormat: - value: Any - locale: Any - def __init__(self, value, locale) -> None: ... - def __getitem__(self, name): ... - def extract(self, char): ... - def format_era(self, char, num): ... - def format_year(self, char, num): ... - def format_quarter(self, char, num): ... - def format_month(self, char, num): ... - def format_week(self, char, num): ... - def format_weekday(self, char: str = ..., num: int = ...): ... - def format_day_of_year(self, num): ... - def format_day_of_week_in_month(self): ... - def format_period(self, char): ... - def format_frac_seconds(self, num): ... - def format_milliseconds_in_day(self, num): ... - def format_timezone(self, char, num): ... - def format(self, value, length): ... - def get_day_of_year(self, date: Any | None = ...): ... - def get_week_number(self, day_of_period, day_of_week: Any | None = ...): ... - -PATTERN_CHARS: Any -PATTERN_CHAR_ORDER: str - -def parse_pattern(pattern): ... -def tokenize_pattern(pattern): ... -def untokenize_pattern(tokens): ... -def split_interval_pattern(pattern): ... -def match_skeleton(skeleton, options, allow_different_fields: bool = ...): ... diff --git a/stubs/babel/babel/languages.pyi b/stubs/babel/babel/languages.pyi deleted file mode 100644 index 4495c51be194..000000000000 --- a/stubs/babel/babel/languages.pyi +++ /dev/null @@ -1,2 +0,0 @@ -def get_official_languages(territory, regional: bool = ..., de_facto: bool = ...): ... -def get_territory_language_info(territory): ... diff --git a/stubs/babel/babel/lists.pyi b/stubs/babel/babel/lists.pyi deleted file mode 100644 index 1b0c3a036111..000000000000 --- a/stubs/babel/babel/lists.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any - -DEFAULT_LOCALE: Any - -def format_list(lst, style: str = ..., locale=...): ... diff --git a/stubs/babel/babel/localedata.pyi b/stubs/babel/babel/localedata.pyi deleted file mode 100644 index eaff52cf82be..000000000000 --- a/stubs/babel/babel/localedata.pyi +++ /dev/null @@ -1,24 +0,0 @@ -import collections.abc as _abc -from typing import Any - -def normalize_locale(name): ... -def resolve_locale_filename(name): ... -def exists(name): ... -def locale_identifiers(): ... -def load(name, merge_inherited: bool = ...): ... -def merge(dict1, dict2) -> None: ... - -class Alias: - keys: Any - def __init__(self, keys) -> None: ... - def resolve(self, data): ... - -class LocaleDataDict(_abc.MutableMapping): - base: Any - def __init__(self, data, base: Any | None = ...) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def __getitem__(self, key): ... - def __setitem__(self, key, value) -> None: ... - def __delitem__(self, key) -> None: ... - def copy(self): ... diff --git a/stubs/babel/babel/localtime/__init__.pyi b/stubs/babel/babel/localtime/__init__.pyi deleted file mode 100644 index 6f8a5a577af9..000000000000 --- a/stubs/babel/babel/localtime/__init__.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from datetime import tzinfo -from typing import Any - -STDOFFSET: Any -DSTOFFSET: Any -DSTDIFF: Any -ZERO: Any - -class _FallbackLocalTimezone(tzinfo): - def utcoffset(self, dt): ... - def dst(self, dt): ... - def tzname(self, dt): ... - -def get_localzone(): ... - -LOCALTZ: Any diff --git a/stubs/babel/babel/localtime/_win32.pyi b/stubs/babel/babel/localtime/_win32.pyi deleted file mode 100644 index b22c83a6f2ee..000000000000 --- a/stubs/babel/babel/localtime/_win32.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -tz_names: Any - -def valuestodict(key): ... -def get_localzone_name(): ... diff --git a/stubs/babel/babel/messages/__init__.pyi b/stubs/babel/babel/messages/__init__.pyi deleted file mode 100644 index 71d6cecf5e45..000000000000 --- a/stubs/babel/babel/messages/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from babel.messages.catalog import * diff --git a/stubs/babel/babel/messages/catalog.pyi b/stubs/babel/babel/messages/catalog.pyi deleted file mode 100644 index 7a51975fb347..000000000000 --- a/stubs/babel/babel/messages/catalog.pyi +++ /dev/null @@ -1,105 +0,0 @@ -from typing import Any - -class Message: - id: Any - string: Any - locations: Any - flags: Any - auto_comments: Any - user_comments: Any - previous_id: Any - lineno: Any - context: Any - def __init__( - self, - id, - string: str = ..., - locations=..., - flags=..., - auto_comments=..., - user_comments=..., - previous_id=..., - lineno: Any | None = ..., - context: Any | None = ..., - ) -> None: ... - def __cmp__(self, other): ... - def __gt__(self, other): ... - def __lt__(self, other): ... - def __ge__(self, other): ... - def __le__(self, other): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def clone(self): ... - def check(self, catalog: Any | None = ...): ... - @property - def fuzzy(self): ... - @property - def pluralizable(self): ... - @property - def python_format(self): ... - -class TranslationError(Exception): ... - -class Catalog: - domain: Any - locale: Any - project: Any - version: Any - copyright_holder: Any - msgid_bugs_address: Any - last_translator: Any - language_team: Any - charset: Any - creation_date: Any - revision_date: Any - fuzzy: Any - obsolete: Any - def __init__( - self, - locale: Any | None = ..., - domain: Any | None = ..., - header_comment=..., - project: Any | None = ..., - version: Any | None = ..., - copyright_holder: Any | None = ..., - msgid_bugs_address: Any | None = ..., - creation_date: Any | None = ..., - revision_date: Any | None = ..., - last_translator: Any | None = ..., - language_team: Any | None = ..., - charset: Any | None = ..., - fuzzy: bool = ..., - ) -> None: ... - locale_identifier: Any - header_comment: Any - mime_headers: Any - @property - def num_plurals(self): ... - @property - def plural_expr(self): ... - @property - def plural_forms(self): ... - def __contains__(self, id): ... - def __len__(self): ... - def __iter__(self): ... - def __delitem__(self, id) -> None: ... - def __getitem__(self, id): ... - def __setitem__(self, id, message) -> None: ... - def add( - self, - id, - string: Any | None = ..., - locations=..., - flags=..., - auto_comments=..., - user_comments=..., - previous_id=..., - lineno: Any | None = ..., - context: Any | None = ..., - ): ... - def check(self) -> None: ... - def get(self, id, context: Any | None = ...): ... - def delete(self, id, context: Any | None = ...) -> None: ... - def update( - self, template, no_fuzzy_matching: bool = ..., update_header_comment: bool = ..., keep_user_comments: bool = ... - ) -> None: ... diff --git a/stubs/babel/babel/messages/checkers.pyi b/stubs/babel/babel/messages/checkers.pyi deleted file mode 100644 index 6357941180c3..000000000000 --- a/stubs/babel/babel/messages/checkers.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -def num_plurals(catalog, message) -> None: ... -def python_format(catalog, message) -> None: ... - -checkers: Any diff --git a/stubs/babel/babel/messages/extract.pyi b/stubs/babel/babel/messages/extract.pyi deleted file mode 100644 index 6a761a2b686b..000000000000 --- a/stubs/babel/babel/messages/extract.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any - -GROUP_NAME: str -DEFAULT_KEYWORDS: Any -DEFAULT_MAPPING: Any -empty_msgid_warning: str - -def extract_from_dir( - dirname: Any | None = ..., - method_map=..., - options_map: Any | None = ..., - keywords=..., - comment_tags=..., - callback: Any | None = ..., - strip_comment_tags: bool = ..., -) -> None: ... -def check_and_call_extract_file( - filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath: Any | None = ... -) -> None: ... -def extract_from_file( - method, filename, keywords=..., comment_tags=..., options: Any | None = ..., strip_comment_tags: bool = ... -): ... -def extract( - method, fileobj, keywords=..., comment_tags=..., options: Any | None = ..., strip_comment_tags: bool = ... -) -> None: ... -def extract_nothing(fileobj, keywords, comment_tags, options): ... -def extract_python(fileobj, keywords, comment_tags, options): ... -def extract_javascript(fileobj, keywords, comment_tags, options) -> None: ... diff --git a/stubs/babel/babel/messages/frontend.pyi b/stubs/babel/babel/messages/frontend.pyi deleted file mode 100644 index a3e99c8810e5..000000000000 --- a/stubs/babel/babel/messages/frontend.pyi +++ /dev/null @@ -1,120 +0,0 @@ -import abc -from distutils.cmd import Command as _Command -from typing import Any - -po_file_read_mode: Any - -def listify_value(arg, split: Any | None = ...): ... - -class Command(_Command, metaclass=abc.ABCMeta): - as_args: Any - multiple_value_options: Any - boolean_options: Any - option_aliases: Any - option_choices: Any - log: Any - distribution: Any - verbose: bool - force: Any - help: int - finalized: int - def __init__(self, dist: Any | None = ...) -> None: ... - -class compile_catalog(Command): - description: str - user_options: Any - boolean_options: Any - domain: str - directory: Any - input_file: Any - output_file: Any - locale: Any - use_fuzzy: bool - statistics: bool - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self): ... - -class extract_messages(Command): - description: str - user_options: Any - boolean_options: Any - as_args: str - multiple_value_options: Any - option_aliases: Any - option_choices: Any - charset: str - keywords: Any - no_default_keywords: bool - mapping_file: Any - no_location: bool - add_location: Any - omit_header: bool - output_file: Any - input_dirs: Any - input_paths: Any - width: Any - no_wrap: bool - sort_output: bool - sort_by_file: bool - msgid_bugs_address: Any - copyright_holder: Any - project: Any - version: Any - add_comments: Any - strip_comments: bool - include_lineno: bool - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... - -def check_message_extractors(dist, name, value) -> None: ... - -class init_catalog(Command): - description: str - user_options: Any - boolean_options: Any - output_dir: Any - output_file: Any - input_file: Any - locale: Any - domain: str - no_wrap: bool - width: Any - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... - -class update_catalog(Command): - description: str - user_options: Any - boolean_options: Any - domain: str - input_file: Any - output_dir: Any - output_file: Any - omit_header: bool - locale: Any - width: Any - no_wrap: bool - ignore_obsolete: bool - init_missing: bool - no_fuzzy_matching: bool - update_header_comment: bool - previous: bool - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... - -class CommandLineInterface: - usage: str - version: Any - commands: Any - command_classes: Any - log: Any - parser: Any - def run(self, argv: Any | None = ...): ... - -def main(): ... -def parse_mapping(fileobj, filename: Any | None = ...): ... -def parse_keywords(strings=...): ... diff --git a/stubs/babel/babel/messages/jslexer.pyi b/stubs/babel/babel/messages/jslexer.pyi deleted file mode 100644 index b08766d69a5d..000000000000 --- a/stubs/babel/babel/messages/jslexer.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any, NamedTuple - -operators: Any -escapes: Any -name_re: Any -dotted_name_re: Any -division_re: Any -regex_re: Any -line_re: Any -line_join_re: Any -uni_escape_re: Any - -class Token(NamedTuple): - type: Any - value: Any - lineno: Any - -def get_rules(jsx, dotted, template_string): ... -def indicates_division(token): ... -def unquote_string(string): ... -def tokenize(source, jsx: bool = ..., dotted: bool = ..., template_string: bool = ...) -> None: ... diff --git a/stubs/babel/babel/messages/mofile.pyi b/stubs/babel/babel/messages/mofile.pyi deleted file mode 100644 index a7e7362a577d..000000000000 --- a/stubs/babel/babel/messages/mofile.pyi +++ /dev/null @@ -1,5 +0,0 @@ -LE_MAGIC: int -BE_MAGIC: int - -def read_mo(fileobj): ... -def write_mo(fileobj, catalog, use_fuzzy: bool = ...) -> None: ... diff --git a/stubs/babel/babel/messages/plurals.pyi b/stubs/babel/babel/messages/plurals.pyi deleted file mode 100644 index 0f9ac943b0f5..000000000000 --- a/stubs/babel/babel/messages/plurals.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any, Tuple - -LC_CTYPE: Any -PLURALS: Any -DEFAULT_PLURAL: Any - -class _PluralTuple(Tuple[int, str]): - num_plurals: Any - plural_expr: Any - plural_forms: Any - -def get_plural(locale=...): ... diff --git a/stubs/babel/babel/messages/pofile.pyi b/stubs/babel/babel/messages/pofile.pyi deleted file mode 100644 index 29b4511929e7..000000000000 --- a/stubs/babel/babel/messages/pofile.pyi +++ /dev/null @@ -1,59 +0,0 @@ -from typing import Any - -def unescape(string): ... -def denormalize(string): ... - -class PoFileError(Exception): - catalog: Any - line: Any - lineno: Any - def __init__(self, message, catalog, line, lineno) -> None: ... - -class _NormalizedString: - def __init__(self, *args) -> None: ... - def append(self, s) -> None: ... - def denormalize(self): ... - def __nonzero__(self): ... - __bool__: Any - def __cmp__(self, other): ... - def __gt__(self, other): ... - def __lt__(self, other): ... - def __ge__(self, other): ... - def __le__(self, other): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - -class PoFileParser: - catalog: Any - ignore_obsolete: Any - counter: int - offset: int - abort_invalid: Any - def __init__(self, catalog, ignore_obsolete: bool = ..., abort_invalid: bool = ...) -> None: ... - def parse(self, fileobj) -> None: ... - -def read_po( - fileobj, - locale: Any | None = ..., - domain: Any | None = ..., - ignore_obsolete: bool = ..., - charset: Any | None = ..., - abort_invalid: bool = ..., -): ... - -WORD_SEP: Any - -def escape(string): ... -def normalize(string, prefix: str = ..., width: int = ...): ... -def write_po( - fileobj, - catalog, - width: int = ..., - no_location: bool = ..., - omit_header: bool = ..., - sort_output: bool = ..., - sort_by_file: bool = ..., - ignore_obsolete: bool = ..., - include_previous: bool = ..., - include_lineno: bool = ..., -): ... diff --git a/stubs/babel/babel/numbers.pyi b/stubs/babel/babel/numbers.pyi deleted file mode 100644 index c4b27a560328..000000000000 --- a/stubs/babel/babel/numbers.pyi +++ /dev/null @@ -1,94 +0,0 @@ -from typing import Any - -long = int -LC_NUMERIC: Any - -class UnknownCurrencyError(Exception): - identifier: Any - def __init__(self, identifier) -> None: ... - -def list_currencies(locale: Any | None = ...): ... -def validate_currency(currency, locale: Any | None = ...) -> None: ... -def is_currency(currency, locale: Any | None = ...): ... -def normalize_currency(currency, locale: Any | None = ...): ... -def get_currency_name(currency, count: Any | None = ..., locale=...): ... -def get_currency_symbol(currency, locale=...): ... -def get_currency_precision(currency): ... -def get_currency_unit_pattern(currency, count: Any | None = ..., locale=...): ... -def get_territory_currencies( - territory, - start_date: Any | None = ..., - end_date: Any | None = ..., - tender: bool = ..., - non_tender: bool = ..., - include_details: bool = ..., -): ... -def get_decimal_symbol(locale=...): ... -def get_plus_sign_symbol(locale=...): ... -def get_minus_sign_symbol(locale=...): ... -def get_exponential_symbol(locale=...): ... -def get_group_symbol(locale=...): ... -def format_number(number, locale=...): ... -def get_decimal_precision(number): ... -def get_decimal_quantum(precision): ... -def format_decimal( - number, format: Any | None = ..., locale=..., decimal_quantization: bool = ..., group_separator: bool = ... -): ... - -class UnknownCurrencyFormatError(KeyError): ... - -def format_currency( - number, - currency, - format: Any | None = ..., - locale=..., - currency_digits: bool = ..., - format_type: str = ..., - decimal_quantization: bool = ..., - group_separator: bool = ..., -): ... -def format_percent( - number, format: Any | None = ..., locale=..., decimal_quantization: bool = ..., group_separator: bool = ... -): ... -def format_scientific(number, format: Any | None = ..., locale=..., decimal_quantization: bool = ...): ... - -class NumberFormatError(ValueError): - suggestions: Any - def __init__(self, message, suggestions: Any | None = ...) -> None: ... - -def parse_number(string, locale=...): ... -def parse_decimal(string, locale=..., strict: bool = ...): ... - -PREFIX_END: str -NUMBER_TOKEN: str -PREFIX_PATTERN: Any -NUMBER_PATTERN: Any -SUFFIX_PATTERN: str -number_re: Any - -def parse_grouping(p): ... -def parse_pattern(pattern): ... - -class NumberPattern: - pattern: Any - prefix: Any - suffix: Any - grouping: Any - int_prec: Any - frac_prec: Any - exp_prec: Any - exp_plus: Any - scale: Any - def __init__(self, pattern, prefix, suffix, grouping, int_prec, frac_prec, exp_prec, exp_plus) -> None: ... - def compute_scale(self): ... - def scientific_notation_elements(self, value, locale): ... - def apply( - self, - value, - locale, - currency: Any | None = ..., - currency_digits: bool = ..., - decimal_quantization: bool = ..., - force_frac: Any | None = ..., - group_separator: bool = ..., - ): ... diff --git a/stubs/babel/babel/plural.pyi b/stubs/babel/babel/plural.pyi deleted file mode 100644 index ba142e139fd6..000000000000 --- a/stubs/babel/babel/plural.pyi +++ /dev/null @@ -1,95 +0,0 @@ -from typing import Any - -def extract_operands(source): ... - -class PluralRule: - abstract: Any - def __init__(self, rules) -> None: ... - @classmethod - def parse(cls, rules): ... - @property - def rules(self): ... - tags: Any - def __call__(self, n): ... - -def to_javascript(rule): ... -def to_python(rule): ... -def to_gettext(rule): ... -def in_range_list(num, range_list): ... -def within_range_list(num, range_list): ... -def cldr_modulo(a, b): ... - -class RuleError(Exception): ... - -def tokenize_rule(s): ... -def test_next_token(tokens, type_, value: Any | None = ...): ... -def skip_token(tokens, type_, value: Any | None = ...): ... -def value_node(value): ... -def ident_node(name): ... -def range_list_node(range_list): ... -def negate(rv): ... - -class _Parser: - tokens: Any - ast: Any - def __init__(self, string) -> None: ... - def expect(self, type_, value: Any | None = ..., term: Any | None = ...): ... - def condition(self): ... - def and_condition(self): ... - def relation(self): ... - def newfangled_relation(self, left): ... - def range_or_value(self): ... - def range_list(self): ... - def expr(self): ... - def value(self): ... - -compile_zero: Any - -class _Compiler: - def compile(self, arg): ... - compile_n: Any - compile_i: Any - compile_v: Any - compile_w: Any - compile_f: Any - compile_t: Any - compile_value: Any - compile_and: Any - compile_or: Any - compile_not: Any - compile_mod: Any - compile_is: Any - compile_isnot: Any - def compile_relation(self, method, expr, range_list) -> None: ... - -class _PythonCompiler(_Compiler): - compile_and: Any - compile_or: Any - compile_not: Any - compile_mod: Any - def compile_relation(self, method, expr, range_list): ... - -class _GettextCompiler(_Compiler): - compile_i: Any - compile_v: Any - compile_w: Any - compile_f: Any - compile_t: Any - def compile_relation(self, method, expr, range_list): ... - -class _JavaScriptCompiler(_GettextCompiler): - compile_i: Any - compile_v: Any - compile_w: Any - compile_f: Any - compile_t: Any - def compile_relation(self, method, expr, range_list): ... - -class _UnicodeCompiler(_Compiler): - compile_is: Any - compile_isnot: Any - compile_and: Any - compile_or: Any - compile_mod: Any - def compile_not(self, relation): ... - def compile_relation(self, method, expr, range_list, negated: bool = ...): ... diff --git a/stubs/babel/babel/support.pyi b/stubs/babel/babel/support.pyi deleted file mode 100644 index 3755073d5cda..000000000000 --- a/stubs/babel/babel/support.pyi +++ /dev/null @@ -1,91 +0,0 @@ -import gettext -from typing import Any - -class Format: - locale: Any - tzinfo: Any - def __init__(self, locale, tzinfo: Any | None = ...) -> None: ... - def date(self, date: Any | None = ..., format: str = ...): ... - def datetime(self, datetime: Any | None = ..., format: str = ...): ... - def time(self, time: Any | None = ..., format: str = ...): ... - def timedelta(self, delta, granularity: str = ..., threshold: float = ..., format: str = ..., add_direction: bool = ...): ... - def number(self, number): ... - def decimal(self, number, format: Any | None = ...): ... - def currency(self, number, currency): ... - def percent(self, number, format: Any | None = ...): ... - def scientific(self, number): ... - -class LazyProxy: - def __init__(self, func, *args, **kwargs) -> None: ... - @property - def value(self): ... - def __contains__(self, key): ... - def __nonzero__(self): ... - def __dir__(self): ... - def __iter__(self): ... - def __len__(self): ... - def __unicode__(self): ... - def __add__(self, other): ... - def __radd__(self, other): ... - def __mod__(self, other): ... - def __rmod__(self, other): ... - def __mul__(self, other): ... - def __rmul__(self, other): ... - def __call__(self, *args, **kwargs): ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... - def __delattr__(self, name) -> None: ... - def __getattr__(self, name): ... - def __setattr__(self, name, value) -> None: ... - def __delitem__(self, key) -> None: ... - def __getitem__(self, key): ... - def __setitem__(self, key, value) -> None: ... - def __copy__(self): ... - def __deepcopy__(self, memo): ... - -class NullTranslations(gettext.NullTranslations): - DEFAULT_DOMAIN: Any - plural: Any - files: Any - domain: Any - def __init__(self, fp: Any | None = ...): ... - def dgettext(self, domain, message): ... - def ldgettext(self, domain, message): ... - def udgettext(self, domain, message): ... - dugettext: Any - def dngettext(self, domain, singular, plural, num): ... - def ldngettext(self, domain, singular, plural, num): ... - def udngettext(self, domain, singular, plural, num): ... - dungettext: Any - CONTEXT_ENCODING: str - def pgettext(self, context, message): ... - def lpgettext(self, context, message): ... - def npgettext(self, context, singular, plural, num): ... - def lnpgettext(self, context, singular, plural, num): ... - def upgettext(self, context, message): ... - def unpgettext(self, context, singular, plural, num): ... - def dpgettext(self, domain, context, message): ... - def udpgettext(self, domain, context, message): ... - dupgettext: Any - def ldpgettext(self, domain, context, message): ... - def dnpgettext(self, domain, context, singular, plural, num): ... - def udnpgettext(self, domain, context, singular, plural, num): ... - dunpgettext: Any - def ldnpgettext(self, domain, context, singular, plural, num): ... - ugettext: Any - ungettext: Any - -class Translations(NullTranslations, gettext.GNUTranslations): - DEFAULT_DOMAIN: str - domain: Any - def __init__(self, fp: Any | None = ..., domain: Any | None = ...) -> None: ... - ugettext: Any - ungettext: Any - @classmethod - def load(cls, dirname: Any | None = ..., locales: Any | None = ..., domain: Any | None = ...): ... - def add(self, translations, merge: bool = ...): ... - def merge(self, translations): ... diff --git a/stubs/babel/babel/units.pyi b/stubs/babel/babel/units.pyi deleted file mode 100644 index b11b8ad883fd..000000000000 --- a/stubs/babel/babel/units.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -class UnknownUnitError(ValueError): - def __init__(self, unit, locale) -> None: ... - -def get_unit_name(measurement_unit, length: str = ..., locale=...): ... -def format_unit(value, measurement_unit, length: str = ..., format: Any | None = ..., locale=...): ... -def format_compound_unit( - numerator_value, - numerator_unit: Any | None = ..., - denominator_value: int = ..., - denominator_unit: Any | None = ..., - length: str = ..., - format: Any | None = ..., - locale=..., -): ... diff --git a/stubs/babel/babel/util.pyi b/stubs/babel/babel/util.pyi deleted file mode 100644 index 8788030b825d..000000000000 --- a/stubs/babel/babel/util.pyi +++ /dev/null @@ -1,41 +0,0 @@ -import collections -import textwrap -from datetime import tzinfo -from typing import Any - -from babel import localtime as localtime - -missing: Any - -def distinct(iterable) -> None: ... - -PYTHON_MAGIC_COMMENT_re: Any - -def parse_encoding(fp): ... - -PYTHON_FUTURE_IMPORT_re: Any - -def parse_future_flags(fp, encoding: str = ...): ... -def pathmatch(pattern, filename): ... - -class TextWrapper(textwrap.TextWrapper): - wordsep_re: Any - -def wraptext(text, width: int = ..., initial_indent: str = ..., subsequent_indent: str = ...): ... - -odict = collections.OrderedDict - -class FixedOffsetTimezone(tzinfo): - zone: Any - def __init__(self, offset, name: Any | None = ...) -> None: ... - def utcoffset(self, dt): ... - def tzname(self, dt): ... - def dst(self, dt): ... - -UTC: Any -LOCALTZ: Any -get_localzone = localtime.get_localzone -STDOFFSET: Any -DSTOFFSET: Any -DSTDIFF: Any -ZERO: Any diff --git a/stubs/backports.ssl_match_hostname/METADATA.toml b/stubs/backports.ssl_match_hostname/METADATA.toml deleted file mode 100644 index 839f7d3a9b8e..000000000000 --- a/stubs/backports.ssl_match_hostname/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "3.7.*" -python2 = true diff --git a/stubs/backports.ssl_match_hostname/backports/__init__.pyi b/stubs/backports.ssl_match_hostname/backports/__init__.pyi deleted file mode 100644 index cb0474fb0ee0..000000000000 --- a/stubs/backports.ssl_match_hostname/backports/__init__.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Any - -# Explicitly mark this package as incomplete. -def __getattr__(name: str) -> Any: ... diff --git a/stubs/backports.ssl_match_hostname/backports/ssl_match_hostname/__init__.pyi b/stubs/backports.ssl_match_hostname/backports/ssl_match_hostname/__init__.pyi deleted file mode 100644 index c21998013cf2..000000000000 --- a/stubs/backports.ssl_match_hostname/backports/ssl_match_hostname/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -class CertificateError(ValueError): ... - -def match_hostname(cert, hostname): ... diff --git a/stubs/backports_abc/@tests/stubtest_allowlist.txt b/stubs/backports_abc/@tests/stubtest_allowlist.txt deleted file mode 100644 index bc072c4d93b6..000000000000 --- a/stubs/backports_abc/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1 +0,0 @@ -backports_abc.isawaitable diff --git a/stubs/backports_abc/METADATA.toml b/stubs/backports_abc/METADATA.toml deleted file mode 100644 index 22313195c363..000000000000 --- a/stubs/backports_abc/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "0.5.*" -python2 = true diff --git a/stubs/backports_abc/backports_abc.pyi b/stubs/backports_abc/backports_abc.pyi deleted file mode 100644 index b48ae33667e0..000000000000 --- a/stubs/backports_abc/backports_abc.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -def mk_gen(): ... -def mk_awaitable(): ... -def mk_coroutine(): ... - -Generator: Any -Awaitable: Any -Coroutine: Any - -def isawaitable(obj): ... - -PATCHED: Any - -def patch(patch_inspect: bool = ...): ... diff --git a/stubs/beautifulsoup4/@tests/requirements-stubtest.txt b/stubs/beautifulsoup4/@tests/requirements-stubtest.txt deleted file mode 100644 index 5ed6cb7104f6..000000000000 --- a/stubs/beautifulsoup4/@tests/requirements-stubtest.txt +++ /dev/null @@ -1,2 +0,0 @@ -html5lib -lxml diff --git a/stubs/beautifulsoup4/METADATA.toml b/stubs/beautifulsoup4/METADATA.toml deleted file mode 100644 index 39914d078bcf..000000000000 --- a/stubs/beautifulsoup4/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "4.10.*" diff --git a/stubs/beautifulsoup4/bs4/__init__.pyi b/stubs/beautifulsoup4/bs4/__init__.pyi deleted file mode 100644 index d975dfc8f061..000000000000 --- a/stubs/beautifulsoup4/bs4/__init__.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from _typeshed import Self, SupportsRead -from typing import Any, Sequence, Type - -from .builder import TreeBuilder -from .element import PageElement, SoupStrainer, Tag -from .formatter import Formatter - -class GuessedAtParserWarning(UserWarning): ... -class MarkupResemblesLocatorWarning(UserWarning): ... - -class BeautifulSoup(Tag): - ROOT_TAG_NAME: str - DEFAULT_BUILDER_FEATURES: list[str] - ASCII_SPACES: str - NO_PARSER_SPECIFIED_WARNING: str - element_classes: Any - builder: TreeBuilder - is_xml: bool - known_xml: bool - parse_only: SoupStrainer | None - markup: str - def __init__( - self, - markup: str | bytes | SupportsRead[str] | SupportsRead[bytes] = ..., - features: str | Sequence[str] | None = ..., - builder: TreeBuilder | Type[TreeBuilder] | None = ..., - parse_only: SoupStrainer | None = ..., - from_encoding: str | None = ..., - exclude_encodings: Sequence[str] | None = ..., - element_classes: dict[Type[PageElement], Type[Any]] | None = ..., - **kwargs, - ) -> None: ... - def __copy__(self: Self) -> Self: ... - hidden: bool - current_data: Any - currentTag: Any - tagStack: Any - open_tag_counter: Any - preserve_whitespace_tag_stack: Any - string_container_stack: Any - def reset(self) -> None: ... - def new_tag( - self, - name, - namespace: Any | None = ..., - nsprefix: Any | None = ..., - attrs=..., - sourceline: Any | None = ..., - sourcepos: Any | None = ..., - **kwattrs, - ) -> Tag: ... - def string_container(self, base_class: Any | None = ...): ... - def new_string(self, s, subclass: Any | None = ...): ... - def insert_before(self, *args) -> None: ... - def insert_after(self, *args) -> None: ... - def popTag(self): ... - def pushTag(self, tag) -> None: ... - def endData(self, containerClass: Any | None = ...) -> None: ... - def object_was_parsed(self, o, parent: Any | None = ..., most_recent_element: Any | None = ...) -> None: ... - def handle_starttag(self, name, namespace, nsprefix, attrs, sourceline: Any | None = ..., sourcepos: Any | None = ...): ... - def handle_endtag(self, name, nsprefix: Any | None = ...) -> None: ... - def handle_data(self, data) -> None: ... - def decode(self, pretty_print: bool = ..., eventual_encoding: str = ..., formatter: str | Formatter = ...): ... # type: ignore # missing some arguments - -class BeautifulStoneSoup(BeautifulSoup): ... -class StopParsing(Exception): ... -class FeatureNotFound(ValueError): ... diff --git a/stubs/beautifulsoup4/bs4/builder/__init__.pyi b/stubs/beautifulsoup4/bs4/builder/__init__.pyi deleted file mode 100644 index daa6a97220f4..000000000000 --- a/stubs/beautifulsoup4/bs4/builder/__init__.pyi +++ /dev/null @@ -1,66 +0,0 @@ -from typing import Any - -class TreeBuilderRegistry: - builders_for_feature: Any - builders: Any - def __init__(self) -> None: ... - def register(self, treebuilder_class) -> None: ... - def lookup(self, *features): ... - -class TreeBuilder: - NAME: str - ALTERNATE_NAMES: Any - features: Any - is_xml: bool - picklable: bool - empty_element_tags: Any - DEFAULT_CDATA_LIST_ATTRIBUTES: Any - DEFAULT_PRESERVE_WHITESPACE_TAGS: Any - DEFAULT_STRING_CONTAINERS: Any - USE_DEFAULT: Any - TRACKS_LINE_NUMBERS: bool - soup: Any - cdata_list_attributes: Any - preserve_whitespace_tags: Any - store_line_numbers: Any - string_containers: Any - def __init__( - self, multi_valued_attributes=..., preserve_whitespace_tags=..., store_line_numbers=..., string_containers=... - ) -> None: ... - def initialize_soup(self, soup) -> None: ... - def reset(self) -> None: ... - def can_be_empty_element(self, tag_name): ... - def feed(self, markup) -> None: ... - def prepare_markup( - self, - markup, - user_specified_encoding: Any | None = ..., - document_declared_encoding: Any | None = ..., - exclude_encodings: Any | None = ..., - ) -> None: ... - def test_fragment_to_document(self, fragment): ... - def set_up_substitutions(self, tag): ... - -class SAXTreeBuilder(TreeBuilder): - def feed(self, markup) -> None: ... - def close(self) -> None: ... - def startElement(self, name, attrs) -> None: ... - def endElement(self, name) -> None: ... - def startElementNS(self, nsTuple, nodeName, attrs) -> None: ... - def endElementNS(self, nsTuple, nodeName) -> None: ... - def startPrefixMapping(self, prefix, nodeValue) -> None: ... - def endPrefixMapping(self, prefix) -> None: ... - def characters(self, content) -> None: ... - def startDocument(self) -> None: ... - def endDocument(self) -> None: ... - -class HTMLTreeBuilder(TreeBuilder): - empty_element_tags: Any - block_elements: Any - DEFAULT_STRING_CONTAINERS: Any - DEFAULT_CDATA_LIST_ATTRIBUTES: Any - DEFAULT_PRESERVE_WHITESPACE_TAGS: Any - def set_up_substitutions(self, tag): ... - -class ParserRejectedMarkup(Exception): - def __init__(self, message_or_exception) -> None: ... diff --git a/stubs/beautifulsoup4/bs4/builder/_html5lib.pyi b/stubs/beautifulsoup4/bs4/builder/_html5lib.pyi deleted file mode 100644 index 990d45060521..000000000000 --- a/stubs/beautifulsoup4/bs4/builder/_html5lib.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any - -from bs4.builder import HTMLTreeBuilder - -class HTML5TreeBuilder(HTMLTreeBuilder): - NAME: str - features: Any - TRACKS_LINE_NUMBERS: bool - user_specified_encoding: Any - def prepare_markup( # type: ignore # user_specified_encoding doesn't have a default - self, markup, user_specified_encoding, document_declared_encoding: Any | None = ..., exclude_encodings: Any | None = ... - ) -> None: ... - def feed(self, markup) -> None: ... - underlying_builder: Any - def create_treebuilder(self, namespaceHTMLElements): ... - def test_fragment_to_document(self, fragment): ... - -class TreeBuilderForHtml5lib(Any): # type: ignore # html5lib.treebuilders.base.TreeBuilder - soup: Any - parser: Any - store_line_numbers: Any - def __init__(self, namespaceHTMLElements, soup: Any | None = ..., store_line_numbers: bool = ..., **kwargs) -> None: ... - def documentClass(self): ... - def insertDoctype(self, token) -> None: ... - def elementClass(self, name, namespace): ... - def commentClass(self, data): ... - def fragmentClass(self): ... - def appendChild(self, node) -> None: ... - def getDocument(self): ... - def getFragment(self): ... - def testSerializer(self, element): ... - -class AttrList: - element: Any - attrs: Any - def __init__(self, element) -> None: ... - def __iter__(self): ... - def __setitem__(self, name, value) -> None: ... - def items(self): ... - def keys(self): ... - def __len__(self): ... - def __getitem__(self, name): ... - def __contains__(self, name): ... - -class Element(Any): # type: ignore # html5lib.treebuilders.base.Node - element: Any - soup: Any - namespace: Any - def __init__(self, element, soup, namespace) -> None: ... - def appendChild(self, node) -> None: ... - def getAttributes(self): ... - def setAttributes(self, attributes) -> None: ... - attributes: Any - def insertText(self, data, insertBefore: Any | None = ...) -> None: ... - def insertBefore(self, node, refNode) -> None: ... - def removeChild(self, node) -> None: ... - def reparentChildren(self, new_parent) -> None: ... - def cloneNode(self): ... - def hasContent(self): ... - def getNameTuple(self): ... - nameTuple: Any - -class TextNode(Element): - element: Any - soup: Any - def __init__(self, element, soup) -> None: ... - def cloneNode(self) -> None: ... diff --git a/stubs/beautifulsoup4/bs4/builder/_htmlparser.pyi b/stubs/beautifulsoup4/bs4/builder/_htmlparser.pyi deleted file mode 100644 index bca74d70c182..000000000000 --- a/stubs/beautifulsoup4/bs4/builder/_htmlparser.pyi +++ /dev/null @@ -1,41 +0,0 @@ -from html.parser import HTMLParser -from typing import Any - -from bs4.builder import HTMLTreeBuilder - -class HTMLParseError(Exception): ... - -class BeautifulSoupHTMLParser(HTMLParser): - IGNORE: str - REPLACE: str - on_duplicate_attribute: Any - already_closed_empty_element: Any - def __init__(self, *args, **kwargs) -> None: ... - def error(self, msg: str) -> None: ... - def handle_startendtag(self, name, attrs) -> None: ... - def handle_starttag(self, name, attrs, handle_empty_element: bool = ...) -> None: ... - def handle_endtag(self, name, check_already_closed: bool = ...) -> None: ... - def handle_data(self, data) -> None: ... - def handle_charref(self, name) -> None: ... - def handle_entityref(self, name) -> None: ... - def handle_comment(self, data) -> None: ... - def handle_decl(self, data) -> None: ... - def unknown_decl(self, data) -> None: ... - def handle_pi(self, data) -> None: ... - -class HTMLParserTreeBuilder(HTMLTreeBuilder): - is_xml: bool - picklable: bool - NAME: Any - features: Any - TRACKS_LINE_NUMBERS: bool - parser_args: Any - def __init__(self, parser_args: Any | None = ..., parser_kwargs: Any | None = ..., **kwargs) -> None: ... - def prepare_markup( - self, - markup, - user_specified_encoding: Any | None = ..., - document_declared_encoding: Any | None = ..., - exclude_encodings: Any | None = ..., - ) -> None: ... - def feed(self, markup) -> None: ... diff --git a/stubs/beautifulsoup4/bs4/builder/_lxml.pyi b/stubs/beautifulsoup4/bs4/builder/_lxml.pyi deleted file mode 100644 index 492848911ad1..000000000000 --- a/stubs/beautifulsoup4/bs4/builder/_lxml.pyi +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Any - -from bs4.builder import HTMLTreeBuilder, TreeBuilder - -class LXMLTreeBuilderForXML(TreeBuilder): - DEFAULT_PARSER_CLASS: Any - is_xml: bool - processing_instruction_class: Any - NAME: str - ALTERNATE_NAMES: Any - features: Any - CHUNK_SIZE: int - DEFAULT_NSMAPS: Any - DEFAULT_NSMAPS_INVERTED: Any - def initialize_soup(self, soup) -> None: ... - def default_parser(self, encoding): ... - def parser_for(self, encoding): ... - empty_element_tags: Any - soup: Any - nsmaps: Any - def __init__(self, parser: Any | None = ..., empty_element_tags: Any | None = ..., **kwargs) -> None: ... - def prepare_markup( # type: ignore # the order of the parameters is different - self, - markup, - user_specified_encoding: Any | None = ..., - exclude_encodings: Any | None = ..., - document_declared_encoding: Any | None = ..., - ) -> None: ... - parser: Any - def feed(self, markup) -> None: ... - def close(self) -> None: ... - def start(self, name, attrs, nsmap=...) -> None: ... - def end(self, name) -> None: ... - def pi(self, target, data) -> None: ... - def data(self, content) -> None: ... - def doctype(self, name, pubid, system) -> None: ... - def comment(self, content) -> None: ... - def test_fragment_to_document(self, fragment): ... - -class LXMLTreeBuilder(HTMLTreeBuilder, LXMLTreeBuilderForXML): - NAME: Any - ALTERNATE_NAMES: Any - features: Any - is_xml: bool - processing_instruction_class: Any - def default_parser(self, encoding): ... - parser: Any - def feed(self, markup) -> None: ... - def test_fragment_to_document(self, fragment): ... diff --git a/stubs/beautifulsoup4/bs4/dammit.pyi b/stubs/beautifulsoup4/bs4/dammit.pyi deleted file mode 100644 index 97df5bfda88c..000000000000 --- a/stubs/beautifulsoup4/bs4/dammit.pyi +++ /dev/null @@ -1,87 +0,0 @@ -from collections.abc import Iterable, Iterator -from logging import Logger -from typing import Any, Tuple -from typing_extensions import Literal - -chardet_type: Any - -def chardet_dammit(s): ... - -xml_encoding: str -html_meta: str -encoding_res: Any - -class EntitySubstitution: - CHARACTER_TO_HTML_ENTITY: Any - HTML_ENTITY_TO_CHARACTER: Any - CHARACTER_TO_HTML_ENTITY_RE: Any - CHARACTER_TO_XML_ENTITY: Any - BARE_AMPERSAND_OR_BRACKET: Any - AMPERSAND_OR_BRACKET: Any - @classmethod - def quoted_attribute_value(cls, value): ... - @classmethod - def substitute_xml(cls, value, make_quoted_attribute: bool = ...): ... - @classmethod - def substitute_xml_containing_entities(cls, value, make_quoted_attribute: bool = ...): ... - @classmethod - def substitute_html(cls, s): ... - -class EncodingDetector: - known_definite_encodings: list[str] - user_encodings: list[str] - exclude_encodings: set[str] - chardet_encoding: Any | None - is_html: bool - declared_encoding: str | None - markup: Any - sniffed_encoding: str | None - def __init__( - self, - markup, - known_definite_encodings: Iterable[str] | None = ..., - is_html: bool = ..., - exclude_encodings: list[str] | None = ..., - user_encodings: list[str] | None = ..., - override_encodings: list[str] | None = ..., - ) -> None: ... - @property - def encodings(self) -> Iterator[str]: ... - @classmethod - def strip_byte_order_mark(cls, data): ... - @classmethod - def find_declared_encoding(cls, markup, is_html: bool = ..., search_entire_document: bool = ...) -> str | None: ... - -class UnicodeDammit: - CHARSET_ALIASES: dict[str, str] - ENCODINGS_WITH_SMART_QUOTES: list[str] - smart_quotes_to: Literal["ascii", "xml", "html"] | None - tried_encodings: list[tuple[str, str]] - contains_replacement_characters: bool - is_html: bool - log: Logger - detector: EncodingDetector - markup: Any - unicode_markup: str - original_encoding: Any | None - def __init__( - self, - markup, - known_definite_encodings: list[str] | None = ..., - smart_quotes_to: Literal["ascii", "xml", "html"] | None = ..., - is_html: bool = ..., - exclude_encodings: list[str] | None = ..., - user_encodings: list[str] | None = ..., - override_encodings: list[str] | None = ..., - ) -> None: ... - @property - def declared_html_encoding(self) -> str | None: ... - def find_codec(self, charset: str) -> str | None: ... - MS_CHARS: dict[bytes, str | Tuple[str, ...]] - MS_CHARS_TO_ASCII: dict[bytes, str] - WINDOWS_1252_TO_UTF8: dict[int, bytes] - MULTIBYTE_MARKERS_AND_SIZES: list[tuple[int, int, int]] - FIRST_MULTIBYTE_MARKER: int - LAST_MULTIBYTE_MARKER: int - @classmethod - def detwingle(cls, in_bytes: bytes, main_encoding: str = ..., embedded_encoding: str = ...) -> bytes: ... diff --git a/stubs/beautifulsoup4/bs4/diagnose.pyi b/stubs/beautifulsoup4/bs4/diagnose.pyi deleted file mode 100644 index f498f996d625..000000000000 --- a/stubs/beautifulsoup4/bs4/diagnose.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from html.parser import HTMLParser - -def diagnose(data) -> None: ... -def lxml_trace(data, html: bool = ..., **kwargs) -> None: ... - -class AnnouncingParser(HTMLParser): - def handle_starttag(self, name, attrs) -> None: ... - def handle_endtag(self, name) -> None: ... - def handle_data(self, data) -> None: ... - def handle_charref(self, name) -> None: ... - def handle_entityref(self, name) -> None: ... - def handle_comment(self, data) -> None: ... - def handle_decl(self, data) -> None: ... - def unknown_decl(self, data) -> None: ... - def handle_pi(self, data) -> None: ... - -def htmlparser_trace(data) -> None: ... -def rword(length: int = ...): ... -def rsentence(length: int = ...): ... -def rdoc(num_elements: int = ...): ... -def benchmark_parsers(num_elements: int = ...) -> None: ... -def profile(num_elements: int = ..., parser: str = ...) -> None: ... diff --git a/stubs/beautifulsoup4/bs4/element.pyi b/stubs/beautifulsoup4/bs4/element.pyi deleted file mode 100644 index 9e7b2d1c2a35..000000000000 --- a/stubs/beautifulsoup4/bs4/element.pyi +++ /dev/null @@ -1,353 +0,0 @@ -from _typeshed import Self -from collections.abc import Iterator -from typing import Any, Callable, Generic, Iterable, List, Mapping, Pattern, Tuple, Type, TypeVar, Union, overload - -from . import BeautifulSoup -from .builder import TreeBuilder -from .formatter import Formatter, _EntitySubstitution - -DEFAULT_OUTPUT_ENCODING: str -PY3K: bool -nonwhitespace_re: Pattern[str] -whitespace_re: Pattern[str] -PYTHON_SPECIFIC_ENCODINGS: set[str] - -class NamespacedAttribute(str): - def __new__(cls: Type[Self], prefix: str, name: str | None = ..., namespace: str | None = ...) -> Self: ... - -class AttributeValueWithCharsetSubstitution(str): ... - -class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution): - def __new__(cls, original_value): ... - def encode(self, encoding: str) -> str: ... # type: ignore # incompatible with str - -class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution): - CHARSET_RE: Pattern[str] - def __new__(cls, original_value): ... - def encode(self, encoding: str) -> str: ... # type: ignore # incompatible with str - -_PageElementT = TypeVar("_PageElementT", bound=PageElement) -# The wrapping Union[] can be removed once mypy fully supports | in type aliases. -_SimpleStrainable = Union[str, bool, None, bytes, Pattern[str], Callable[[str], bool], Callable[[Tag], bool]] -_Strainable = Union[_SimpleStrainable, Iterable[_SimpleStrainable]] -_SimpleNormalizedStrainable = Union[str, bool, None, Pattern[str], Callable[[str], bool], Callable[[Tag], bool]] -_NormalizedStrainable = Union[_SimpleNormalizedStrainable, Iterable[_SimpleNormalizedStrainable]] - -class PageElement: - parent: Tag | None - previous_element: PageElement | None - next_element: PageElement | None - next_sibling: PageElement | None - previous_sibling: PageElement | None - def setup( - self, - parent: Tag | None = ..., - previous_element: PageElement | None = ..., - next_element: PageElement | None = ..., - previous_sibling: PageElement | None = ..., - next_sibling: PageElement | None = ..., - ) -> None: ... - def format_string(self, s: str, formatter: Formatter | str | None) -> str: ... - def formatter_for_name(self, formatter: Formatter | str | _EntitySubstitution): ... - nextSibling: PageElement | None - previousSibling: PageElement | None - @property - def stripped_strings(self) -> Iterator[str]: ... - def get_text(self, separator: str = ..., strip: bool = ..., types: Tuple[Type[NavigableString], ...] = ...) -> str: ... - getText = get_text - @property - def text(self) -> str: ... - def replace_with(self: Self, *args: PageElement | str) -> Self: ... - replaceWith = replace_with - def unwrap(self: Self) -> Self: ... - replace_with_children = unwrap - replaceWithChildren = unwrap - def wrap(self, wrap_inside: _PageElementT) -> _PageElementT: ... - def extract(self: Self, _self_index: int | None = ...) -> Self: ... - def insert(self, position: int, new_child: PageElement | str) -> None: ... - def append(self, tag: PageElement | str) -> None: ... - def extend(self, tags: Iterable[PageElement | str]) -> None: ... - def insert_before(self, *args: PageElement | str) -> None: ... - def insert_after(self, *args: PageElement | str) -> None: ... - def find_next( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - **kwargs: _Strainable, - ) -> Tag | NavigableString | None: ... - findNext = find_next - def find_all_next( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - limit: int | None = ..., - **kwargs: _Strainable, - ) -> ResultSet[PageElement]: ... - findAllNext = find_all_next - def find_next_sibling( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - **kwargs: _Strainable, - ) -> Tag | NavigableString | None: ... - findNextSibling = find_next_sibling - def find_next_siblings( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - limit: int | None = ..., - **kwargs: _Strainable, - ) -> ResultSet[PageElement]: ... - findNextSiblings = find_next_siblings - fetchNextSiblings = find_next_siblings - def find_previous( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - **kwargs: _Strainable, - ) -> Tag | NavigableString | None: ... - findPrevious = find_previous - def find_all_previous( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - limit: int | None = ..., - **kwargs: _Strainable, - ) -> ResultSet[PageElement]: ... - findAllPrevious = find_all_previous - fetchPrevious = find_all_previous - def find_previous_sibling( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - **kwargs: _Strainable, - ) -> Tag | NavigableString | None: ... - findPreviousSibling = find_previous_sibling - def find_previous_siblings( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - limit: int | None = ..., - **kwargs: _Strainable, - ) -> ResultSet[PageElement]: ... - findPreviousSiblings = find_previous_siblings - fetchPreviousSiblings = find_previous_siblings - def find_parent( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - **kwargs: _Strainable, - ) -> Tag | None: ... - findParent = find_parent - def find_parents( - self, - name: _Strainable | SoupStrainer | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - limit: int | None = ..., - **kwargs: _Strainable, - ) -> ResultSet[Tag]: ... - findParents = find_parents - fetchParents = find_parents - @property - def next(self) -> Tag | NavigableString | None: ... - @property - def previous(self) -> Tag | NavigableString | None: ... - @property - def next_elements(self) -> Iterable[PageElement]: ... - @property - def next_siblings(self) -> Iterable[PageElement]: ... - @property - def previous_elements(self) -> Iterable[PageElement]: ... - @property - def previous_siblings(self) -> Iterable[PageElement]: ... - @property - def parents(self) -> Iterable[Tag]: ... - @property - def decomposed(self) -> bool: ... - def nextGenerator(self) -> Iterable[PageElement]: ... - def nextSiblingGenerator(self) -> Iterable[PageElement]: ... - def previousGenerator(self) -> Iterable[PageElement]: ... - def previousSiblingGenerator(self) -> Iterable[PageElement]: ... - def parentGenerator(self) -> Iterable[Tag]: ... - -class NavigableString(str, PageElement): - PREFIX: str - SUFFIX: str - known_xml: bool | None - def __new__(cls: Type[Self], value: str | bytes) -> Self: ... - def __copy__(self: Self) -> Self: ... - def __getnewargs__(self) -> tuple[str]: ... - def output_ready(self, formatter: Formatter | str | None = ...) -> str: ... - @property - def name(self) -> None: ... - @property - def strings(self) -> Iterable[str]: ... - -class PreformattedString(NavigableString): - PREFIX: str - SUFFIX: str - def output_ready(self, formatter: Formatter | str | None = ...) -> str: ... - -class CData(PreformattedString): - PREFIX: str - SUFFIX: str - -class ProcessingInstruction(PreformattedString): - PREFIX: str - SUFFIX: str - -class XMLProcessingInstruction(ProcessingInstruction): - PREFIX: str - SUFFIX: str - -class Comment(PreformattedString): - PREFIX: str - SUFFIX: str - -class Declaration(PreformattedString): - PREFIX: str - SUFFIX: str - -class Doctype(PreformattedString): - @classmethod - def for_name_and_ids(cls, name: str | None, pub_id: str, system_id: str) -> Doctype: ... - PREFIX: str - SUFFIX: str - -class Stylesheet(NavigableString): ... -class Script(NavigableString): ... -class TemplateString(NavigableString): ... - -class Tag(PageElement): - parser_class: Type[BeautifulSoup] | None - name: str - namespace: str | None - prefix: str | None - sourceline: int | None - sourcepos: int | None - known_xml: bool | None - attrs: Mapping[str, str] - contents: list[PageElement] - hidden: bool - can_be_empty_element: bool | None - cdata_list_attributes: list[str] | None - preserve_whitespace_tags: list[str] | None - def __init__( - self, - parser: BeautifulSoup | None = ..., - builder: TreeBuilder | None = ..., - name: str | None = ..., - namespace: str | None = ..., - prefix: str | None = ..., - attrs: Mapping[str, str] | None = ..., - parent: Tag | None = ..., - previous: PageElement | None = ..., - is_xml: bool | None = ..., - sourceline: int | None = ..., - sourcepos: int | None = ..., - can_be_empty_element: bool | None = ..., - cdata_list_attributes: list[str] | None = ..., - preserve_whitespace_tags: list[str] | None = ..., - interesting_string_types: Type[NavigableString] | Tuple[Type[NavigableString], ...] | None = ..., - ) -> None: ... - parserClass: Type[BeautifulSoup] | None - def __copy__(self: Self) -> Self: ... - @property - def is_empty_element(self) -> bool: ... - isSelfClosing = is_empty_element - @property - def string(self) -> str | None: ... - @string.setter - def string(self, string: str) -> None: ... - DEFAULT_INTERESTING_STRING_TYPES: Tuple[Type[NavigableString], ...] - @property - def strings(self) -> Iterable[str]: ... - def decompose(self) -> None: ... - def clear(self, decompose: bool = ...) -> None: ... - def smooth(self) -> None: ... - def index(self, element: PageElement) -> int: ... - def get(self, key: str, default: str | list[str] | None = ...) -> str | list[str] | None: ... - def get_attribute_list(self, key: str, default: str | list[str] | None = ...) -> list[str]: ... - def has_attr(self, key: str) -> bool: ... - def __hash__(self) -> int: ... - def __getitem__(self, key: str) -> str | list[str]: ... - def __iter__(self) -> Iterable[PageElement]: ... - def __len__(self) -> int: ... - def __contains__(self, x: object) -> bool: ... - def __bool__(self) -> bool: ... - def __setitem__(self, key: str, value: str | list[str]) -> None: ... - def __delitem__(self, key: str) -> None: ... - def __getattr__(self, tag: str) -> Tag | None: ... - def __eq__(self, other: object) -> bool: ... - def __ne__(self, other: object) -> bool: ... - def __unicode__(self) -> str: ... - def encode( - self, encoding: str = ..., indent_level: int | None = ..., formatter: str | Formatter = ..., errors: str = ... - ) -> bytes: ... - def decode(self, indent_level: int | None = ..., eventual_encoding: str = ..., formatter: str | Formatter = ...) -> str: ... - @overload - def prettify(self, encoding: str, formatter: str | Formatter = ...) -> bytes: ... - @overload - def prettify(self, encoding: None = ..., formatter: str | Formatter = ...) -> str: ... - def decode_contents( - self, indent_level: int | None = ..., eventual_encoding: str = ..., formatter: str | Formatter = ... - ) -> str: ... - def encode_contents(self, indent_level: int | None = ..., encoding: str = ..., formatter: str | Formatter = ...) -> bytes: ... - def renderContents(self, encoding: str = ..., prettyPrint: bool = ..., indentLevel: int = ...) -> bytes: ... - def find( - self, - name: _Strainable | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - recursive: bool = ..., - text: _Strainable | None = ..., - **kwargs: _Strainable, - ) -> Tag | NavigableString | None: ... - findChild = find - def find_all( - self, - name: _Strainable | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - recursive: bool = ..., - text: _Strainable | None = ..., - limit: int | None = ..., - **kwargs: _Strainable, - ) -> ResultSet[Any]: ... - __call__ = find_all - findAll = find_all - findChildren = find_all - @property - def children(self) -> Iterable[PageElement]: ... - @property - def descendants(self) -> Iterable[PageElement]: ... - def select_one(self, selector: str, namespaces: Any | None = ..., **kwargs) -> Tag | None: ... - def select(self, selector: str, namespaces: Any | None = ..., limit: int | None = ..., **kwargs) -> ResultSet[Tag]: ... - def childGenerator(self) -> Iterable[PageElement]: ... - def recursiveChildGenerator(self) -> Iterable[PageElement]: ... - def has_key(self, key: str) -> bool: ... - -class SoupStrainer: - name: _NormalizedStrainable - attrs: dict[str, _NormalizedStrainable] - text: _NormalizedStrainable - def __init__( - self, - name: _Strainable | None = ..., - attrs: dict[str, _Strainable] | _Strainable = ..., - text: _Strainable | None = ..., - **kwargs: _Strainable, - ) -> None: ... - def search_tag(self, markup_name: Tag | str | None = ..., markup_attrs=...): ... - searchTag = search_tag - def search(self, markup: PageElement | Iterable[PageElement]): ... - -class ResultSet(List[_PageElementT], Generic[_PageElementT]): - source: SoupStrainer - def __init__(self, source: SoupStrainer, result: Iterable[_PageElementT] = ...) -> None: ... diff --git a/stubs/beautifulsoup4/bs4/formatter.pyi b/stubs/beautifulsoup4/bs4/formatter.pyi deleted file mode 100644 index 4250419fdc47..000000000000 --- a/stubs/beautifulsoup4/bs4/formatter.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Callable - -from .dammit import EntitySubstitution as EntitySubstitution - -_EntitySubstitution = Callable[[str], str] - -class Formatter(EntitySubstitution): - HTML: str - XML: str - HTML_DEFAULTS: dict[str, set[str]] - language: str | None - entity_substitution: _EntitySubstitution - void_element_close_prefix: str - cdata_containing_tags: list[str] - empty_attributes_are_booleans: bool - def __init__( - self, - language: str | None = ..., - entity_substitution: _EntitySubstitution | None = ..., - void_element_close_prefix: str = ..., - cdata_containing_tags: list[str] | None = ..., - empty_attributes_are_booleans: bool = ..., - ) -> None: ... - def substitute(self, ns: str) -> str: ... - def attribute_value(self, value: str) -> str: ... - def attributes(self, tag): ... - -class HTMLFormatter(Formatter): - REGISTRY: dict[str, HTMLFormatter] - def __init__( - self, - entity_substitution: _EntitySubstitution | None = ..., - void_element_close_prefix: str = ..., - cdata_containing_tags: list[str] | None = ..., - ) -> None: ... - -class XMLFormatter(Formatter): - REGISTRY: dict[str, XMLFormatter] - def __init__( - self, - entity_substitution: _EntitySubstitution | None = ..., - void_element_close_prefix: str = ..., - cdata_containing_tags: list[str] | None = ..., - ) -> None: ... diff --git a/stubs/behave/METADATA.toml b/stubs/behave/METADATA.toml new file mode 100644 index 000000000000..937f37b750e4 --- /dev/null +++ b/stubs/behave/METADATA.toml @@ -0,0 +1,6 @@ +version = "1.3.*" +upstream-repository = "https://github.com/behave/behave" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/behave/behave/__init__.pyi b/stubs/behave/behave/__init__.pyi new file mode 100644 index 000000000000..70422a43ef94 --- /dev/null +++ b/stubs/behave/behave/__init__.pyi @@ -0,0 +1,13 @@ +from behave.fixture import fixture as fixture, use_fixture as use_fixture +from behave.step_registry import ( + Given as Given, + Step as Step, + Then as Then, + When as When, + given as given, + step as step, + then as then, + when as when, +) + +__all__ = ["given", "when", "then", "step", "Given", "When", "Then", "Step", "use_fixture", "fixture"] diff --git a/stubs/behave/behave/fixture.pyi b/stubs/behave/behave/fixture.pyi new file mode 100644 index 000000000000..b7a257847a1b --- /dev/null +++ b/stubs/behave/behave/fixture.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Concatenate, ParamSpec, TypeVar + +from behave.runner import Context + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +def use_fixture( + fixture_func: Callable[Concatenate[Context, _P], _T], context: Context, *fixture_args: _P.args, **fixture_kwargs: _P.kwargs +) -> _T: ... +def fixture(func: _F | None = None, name: str | None = None, pattern: str | None = None) -> _F: ... +def __getattr__(name: str) -> Incomplete: ... diff --git a/stubs/behave/behave/runner.pyi b/stubs/behave/behave/runner.pyi new file mode 100644 index 000000000000..a3abfa2d0de2 --- /dev/null +++ b/stubs/behave/behave/runner.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from contextlib import AbstractContextManager +from typing import ClassVar, ParamSpec + +_P = ParamSpec("_P") + +class Context: + LAYER_NAMES: ClassVar[list[str]] + FAIL_ON_CLEANUP_ERRORS: ClassVar[bool] + + feature: Incomplete | None + scenario: Incomplete + tags: set[str] + aborted: bool + failed: bool + table: Incomplete | None + text: str | None + config: Incomplete + active_outline: Incomplete + fail_on_cleanup_errors: bool + + def __init__(self, runner) -> None: ... + def __getattr__(self, name: str) -> Incomplete: ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __contains__(self, name: str) -> bool: ... + def abort(self, reason: str | None = None) -> None: ... + def use_or_assign_param(self, name: str, value): ... + def use_or_create_param(self, name: str, factory_func: Callable[_P, Incomplete], *args: _P.args, **kwargs: _P.kwargs): ... + def use_with_user_mode(self) -> AbstractContextManager[None]: ... + def execute_steps(self, steps_text: str) -> bool: ... + def add_cleanup(self, cleanup_func: Callable[_P, Incomplete], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + @property + def captured(self): ... + def attach(self, mime_type: str, data: bytes) -> None: ... + +def __getattr__(name: str) -> Incomplete: ... diff --git a/stubs/behave/behave/step_registry.pyi b/stubs/behave/behave/step_registry.pyi new file mode 100644 index 000000000000..9b0237896c3d --- /dev/null +++ b/stubs/behave/behave/step_registry.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Concatenate, TypeVar + +from behave.runner import Context + +_F = TypeVar("_F", bound=Callable[Concatenate[Context, ...], None]) + +def given(step_text: str, **kwargs) -> Callable[[_F], _F]: ... +def when(step_text: str, **kwargs) -> Callable[[_F], _F]: ... +def then(step_text: str, **kwargs) -> Callable[[_F], _F]: ... +def step(step_text: str, **kwargs) -> Callable[[_F], _F]: ... + +# Title-case aliases +Given = given +When = when +Then = then +Step = step + +def __getattr__(name: str) -> Incomplete: ... diff --git a/stubs/bleach/@tests/stubtest_allowlist.txt b/stubs/bleach/@tests/stubtest_allowlist.txt index 6189077db5ac..fd5e558aee0b 100644 --- a/stubs/bleach/@tests/stubtest_allowlist.txt +++ b/stubs/bleach/@tests/stubtest_allowlist.txt @@ -1 +1,8 @@ -bleach.html5lib_shim.* +# Internal private stuff: +bleach._vendor.* + +# Is a property returning a method, simplified: +bleach.html5lib_shim.InputStreamWithMemory.changeEncoding + +# Shim for the obsolete six package, used by the vendored html5lib +bleach.six_shim diff --git a/stubs/bleach/METADATA.toml b/stubs/bleach/METADATA.toml index bb8cc449b44f..f43ce83e8f47 100644 --- a/stubs/bleach/METADATA.toml +++ b/stubs/bleach/METADATA.toml @@ -1 +1,6 @@ -version = "4.1.*" +version = "6.4.*" +upstream-repository = "https://github.com/mozilla/bleach" +dependencies = ["types-html5lib"] + +[tool.stubtest] +extras = ["css"] diff --git a/stubs/bleach/bleach/__init__.pyi b/stubs/bleach/bleach/__init__.pyi index 202979e20cc0..7c31c84d592b 100644 --- a/stubs/bleach/bleach/__init__.pyi +++ b/stubs/bleach/bleach/__init__.pyi @@ -1,11 +1,12 @@ from collections.abc import Container, Iterable -from typing import Any +from typing import TypeAlias -from bleach.linkifier import DEFAULT_CALLBACKS as DEFAULT_CALLBACKS, Linker as Linker, _Callback -from bleach.sanitizer import ( +from .callbacks import _Callback +from .css_sanitizer import CSSSanitizer +from .linkifier import DEFAULT_CALLBACKS as DEFAULT_CALLBACKS, Linker as Linker +from .sanitizer import ( ALLOWED_ATTRIBUTES as ALLOWED_ATTRIBUTES, ALLOWED_PROTOCOLS as ALLOWED_PROTOCOLS, - ALLOWED_STYLES as ALLOWED_STYLES, ALLOWED_TAGS as ALLOWED_TAGS, Cleaner as Cleaner, _Attributes, @@ -15,17 +16,18 @@ __all__ = ["clean", "linkify"] __releasedate__: str __version__: str -VERSION: Any # packaging.version.Version + +_HTMLAttrKey: TypeAlias = tuple[str | None, str] # noqa: Y047 def clean( text: str, - tags: Container[str] = ..., + tags: Iterable[str] = ..., attributes: _Attributes = ..., - styles: Container[str] = ..., - protocols: Container[str] = ..., - strip: bool = ..., - strip_comments: bool = ..., + protocols: Iterable[str] = ..., + strip: bool = False, + strip_comments: bool = True, + css_sanitizer: CSSSanitizer | None = None, ) -> str: ... def linkify( - text: str, callbacks: Iterable[_Callback] = ..., skip_tags: Container[str] | None = ..., parse_email: bool = ... + text: str, callbacks: Iterable[_Callback] = ..., skip_tags: Container[str] | None = None, parse_email: bool = False ) -> str: ... diff --git a/stubs/bleach/bleach/callbacks.pyi b/stubs/bleach/bleach/callbacks.pyi index de8a14d93c60..0ea1145fac8f 100644 --- a/stubs/bleach/bleach/callbacks.pyi +++ b/stubs/bleach/bleach/callbacks.pyi @@ -1,7 +1,13 @@ from collections.abc import MutableMapping -from typing import Any +from typing import Protocol, TypeAlias, type_check_only -_Attrs = MutableMapping[Any, str] +from bleach import _HTMLAttrKey -def nofollow(attrs: _Attrs, new: bool = ...) -> _Attrs: ... -def target_blank(attrs: _Attrs, new: bool = ...) -> _Attrs: ... +_HTMLAttrs: TypeAlias = MutableMapping[_HTMLAttrKey, str] + +@type_check_only +class _Callback(Protocol): # noqa: Y046 + def __call__(self, attrs: _HTMLAttrs, new: bool = ..., /) -> _HTMLAttrs: ... + +def nofollow(attrs: _HTMLAttrs, new: bool = False) -> _HTMLAttrs: ... +def target_blank(attrs: _HTMLAttrs, new: bool = False) -> _HTMLAttrs: ... diff --git a/stubs/bleach/bleach/css_sanitizer.pyi b/stubs/bleach/bleach/css_sanitizer.pyi new file mode 100644 index 000000000000..9fa319c6d79c --- /dev/null +++ b/stubs/bleach/bleach/css_sanitizer.pyi @@ -0,0 +1,12 @@ +from collections.abc import Container +from typing import Final + +ALLOWED_CSS_PROPERTIES: Final[frozenset[str]] +ALLOWED_SVG_PROPERTIES: Final[frozenset[str]] + +class CSSSanitizer: + allowed_css_properties: Container[str] + allowed_svg_properties: Container[str] + + def __init__(self, allowed_css_properties: Container[str] = ..., allowed_svg_properties: Container[str] = ...) -> None: ... + def sanitize_css(self, style: str) -> str: ... diff --git a/stubs/bleach/bleach/html5lib_shim.pyi b/stubs/bleach/bleach/html5lib_shim.pyi index 3d69fc0da4e8..d781faa9c7bb 100644 --- a/stubs/bleach/bleach/html5lib_shim.pyi +++ b/stubs/bleach/bleach/html5lib_shim.pyi @@ -1,27 +1,71 @@ -from collections.abc import Generator, Iterable -from typing import Any +import re +from codecs import CodecInfo +from collections.abc import Generator, Iterable, Iterator +from typing import Any, Final, Protocol, type_check_only -class HTMLParser(object): # actually html5lib.HTMLParser - def __getattr__(self, __name: str) -> Any: ... # incomplete +# We don't re-export any `html5lib` types / values here, because they are not +# really public and may change at any time. This is just a helper module, +# import things directly from `html5lib` instead! +from html5lib import HTMLParser +from html5lib._inputstream import HTMLBinaryInputStream, HTMLUnicodeInputStream +from html5lib._tokenizer import HTMLTokenizer +from html5lib._trie import Trie +from html5lib.serializer import HTMLSerializer +from html5lib.treewalkers.base import TreeWalker -class Filter(object): # actually html5lib.filters.base.Filter - def __getattr__(self, __name: str) -> Any: ... # incomplete +# Is actually webencodings.Encoding +@type_check_only +class _Encoding(Protocol): + name: str + codec_info: CodecInfo + def __init__(self, name: str, codec_info: CodecInfo) -> None: ... -class SanitizerFilter(object): # actually html5lib.filters.sanitizer.Filter - def __getattr__(self, __name: str) -> Any: ... # incomplete +HTML_TAGS: Final[frozenset[str]] +HTML_TAGS_BLOCK_LEVEL: Final[frozenset[str]] +AMP_SPLIT_RE: Final[re.Pattern[str]] +ENTITIES: Final[dict[str, str]] +ENTITIES_TRIE: Final[Trie] +TAG_TOKEN_TYPES: Final[set[int]] +TAG_TOKEN_TYPE_CHARACTERS: Final[int] +TAG_TOKEN_TYPE_END: Final[int] +TAG_TOKEN_TYPE_PARSEERROR: Final[int] +TAG_TOKEN_TYPE_START: Final[int] -class HTMLSerializer(object): # actually html5lib.serializer.HTMLSerializer - def __getattr__(self, __name: str) -> Any: ... # incomplete +class InputStreamWithMemory: + position = HTMLUnicodeInputStream.position + reset = HTMLUnicodeInputStream.reset + def __init__(self, inner_stream: HTMLUnicodeInputStream) -> None: ... + @property + def errors(self) -> list[str]: ... + @property + def charEncoding(self) -> tuple[_Encoding, str]: ... + # If inner_stream wasn't a HTMLBinaryInputStream, this will error at runtime + # Is a property returning a method, simplified: + changeEncoding = HTMLBinaryInputStream.changeEncoding + def char(self) -> str: ... + def charsUntil(self, characters: Iterable[str], opposite: bool = False) -> str: ... + def unget(self, char: str | None) -> None: ... + def get_tag(self) -> str: ... + def start_tag(self) -> None: ... + +class BleachHTMLTokenizer(HTMLTokenizer): + consume_entities: bool + stream: InputStreamWithMemory # type: ignore[assignment] + emitted_last_token: dict[str, Any] | None + def __init__(self, consume_entities: bool = False, **kwargs: Any) -> None: ... class BleachHTMLParser(HTMLParser): tags: list[str] | None strip: bool consume_entities: bool - def __init__(self, tags: Iterable[str] | None, strip: bool, consume_entities: bool, **kwargs) -> None: ... + def __init__(self, tags: Iterable[str] | None, strip: bool, consume_entities: bool, **kwargs: Any) -> None: ... class BleachHTMLSerializer(HTMLSerializer): escape_rcdata: bool - def escape_base_amp(self, stoken: str) -> Generator[str, None, None]: ... - def serialize(self, treewalker, encoding: str | None = ...) -> Generator[str, None, None]: ... + def escape_base_amp(self, stoken: str) -> Generator[str]: ... + def serialize(self, treewalker: TreeWalker, encoding: str | None = None) -> Generator[str]: ... # type: ignore[override] -def __getattr__(__name: str) -> Any: ... # incomplete +def convert_entity(value: str) -> str | None: ... +def convert_entities(text: str) -> str: ... +def match_entity(stream: str) -> str | None: ... +def next_possible_entity(text: str) -> Iterator[str]: ... diff --git a/stubs/bleach/bleach/linkifier.pyi b/stubs/bleach/bleach/linkifier.pyi index 05a6728383e2..35d311f13dd1 100644 --- a/stubs/bleach/bleach/linkifier.pyi +++ b/stubs/bleach/bleach/linkifier.pyi @@ -1,45 +1,60 @@ -from collections.abc import Container, Iterable, MutableMapping -from typing import Any, Pattern, Protocol +from collections.abc import Container, Iterable, Iterator, Sequence +from re import Pattern +from typing import Any, Final, TypeAlias -from .html5lib_shim import Filter +from html5lib.filters.base import Filter +from html5lib.treewalkers.base import TreeWalker -_Attrs = MutableMapping[Any, str] +from .callbacks import _Callback, _HTMLAttrs -class _Callback(Protocol): - def __call__(self, attrs: _Attrs, new: bool = ...) -> _Attrs: ... - -DEFAULT_CALLBACKS: list[_Callback] - -TLDS: list[str] +DEFAULT_CALLBACKS: Final[list[_Callback]] +TLDS: Final[list[str]] def build_url_re(tlds: Iterable[str] = ..., protocols: Iterable[str] = ...) -> Pattern[str]: ... -URL_RE: Pattern[str] -PROTO_RE: Pattern[str] +URL_RE: Final[Pattern[str]] +PROTO_RE: Final[Pattern[str]] def build_email_re(tlds: Iterable[str] = ...) -> Pattern[str]: ... -EMAIL_RE: Pattern[str] +EMAIL_RE: Final[Pattern[str]] -class Linker(object): +class Linker: def __init__( self, callbacks: Iterable[_Callback] = ..., - skip_tags: Container[str] | None = ..., - parse_email: bool = ..., + skip_tags: Container[str] | None = None, + parse_email: bool = False, url_re: Pattern[str] = ..., email_re: Pattern[str] = ..., recognized_tags: Container[str] | None = ..., ) -> None: ... def linkify(self, text: str) -> str: ... -class LinkifyFilter(Filter): - callbacks: Any +# TODO: `_Token` might be converted into `TypedDict` +# or `html5lib` token might be reused +_Token: TypeAlias = dict[str, Any] + +class LinkifyFilter(Filter[_Token]): + callbacks: Iterable[_Callback] skip_tags: Container[str] parse_email: bool - url_re: Any - email_re: Any + url_re: Pattern[str] + email_re: Pattern[str] def __init__( - self, source, callbacks=..., skip_tags: Container[str] | None = ..., parse_email: bool = ..., url_re=..., email_re=... + self, + source: TreeWalker, + callbacks: Iterable[_Callback] | None = ..., + skip_tags: Container[str] | None = None, + parse_email: bool = False, + url_re: Pattern[str] = ..., + email_re: Pattern[str] = ..., ) -> None: ... - def __getattr__(self, item: str) -> Any: ... # incomplete + def apply_callbacks(self, attrs: _HTMLAttrs, is_new: bool) -> _HTMLAttrs | None: ... + def extract_character_data(self, token_list: Iterable[_Token]) -> str: ... + def handle_email_addresses(self, src_iter: Iterable[_Token]) -> Iterator[_Token]: ... + def strip_non_url_bits(self, fragment: str) -> tuple[str, str, str]: ... + def handle_links(self, src_iter: Iterable[_Token]) -> Iterator[_Token]: ... + def handle_a_tag(self, token_buffer: Sequence[_Token]) -> Iterator[_Token]: ... + def extract_entities(self, token: _Token) -> Iterator[_Token]: ... + def __iter__(self) -> Iterator[_Token]: ... diff --git a/stubs/bleach/bleach/parse_shim.pyi b/stubs/bleach/bleach/parse_shim.pyi new file mode 100644 index 000000000000..5b1ef5a35a59 --- /dev/null +++ b/stubs/bleach/bleach/parse_shim.pyi @@ -0,0 +1 @@ +from urllib import parse as parse diff --git a/stubs/bleach/bleach/sanitizer.pyi b/stubs/bleach/bleach/sanitizer.pyi index 0966af2096d6..8484b419fd4f 100644 --- a/stubs/bleach/bleach/sanitizer.pyi +++ b/stubs/bleach/bleach/sanitizer.pyi @@ -1,67 +1,91 @@ -from collections.abc import Callable, Container, Iterable -from typing import Any, Dict, List, Pattern, Union +from collections.abc import Callable, Container, Iterable, Iterator +from re import Pattern +from typing import Final, Protocol, TypeAlias, type_check_only -from .html5lib_shim import BleachHTMLParser, BleachHTMLSerializer, SanitizerFilter +from html5lib.filters.base import Filter +from html5lib.filters.sanitizer import Filter as SanitizerFilter +from html5lib.treewalkers.base import TreeWalker -ALLOWED_TAGS: list[str] -ALLOWED_ATTRIBUTES: dict[str, list[str]] -ALLOWED_STYLES: list[str] -ALLOWED_PROTOCOLS: list[str] +from . import _HTMLAttrKey +from .css_sanitizer import CSSSanitizer +from .html5lib_shim import BleachHTMLParser, BleachHTMLSerializer +from .linkifier import _Token -INVISIBLE_CHARACTERS: str -INVISIBLE_CHARACTERS_RE: Pattern[str] -INVISIBLE_REPLACEMENT_CHAR: str +ALLOWED_TAGS: Final[frozenset[str]] +ALLOWED_ATTRIBUTES: Final[dict[str, list[str]]] +ALLOWED_PROTOCOLS: Final[frozenset[str]] -# A html5lib Filter class -_Filter = Any +INVISIBLE_CHARACTERS: Final[str] +INVISIBLE_CHARACTERS_RE: Final[Pattern[str]] +INVISIBLE_REPLACEMENT_CHAR: Final = "?" -class Cleaner(object): - tags: Container[str] +class NoCssSanitizerWarning(UserWarning): ... + +@type_check_only +class _FilterConstructor(Protocol): + def __call__(self, *, source: BleachSanitizerFilter) -> Filter: ... + +# _FilterConstructor used to be called _Filter +# this alias is obsolete and can potentially be removed in the future +_Filter: TypeAlias = _FilterConstructor # noqa: Y047 + +_AttributeFilter: TypeAlias = Callable[[str, str, str], bool] +_AttributeDict: TypeAlias = dict[str, list[str] | _AttributeFilter] | dict[str, list[str]] | dict[str, _AttributeFilter] +_Attributes: TypeAlias = _AttributeFilter | _AttributeDict | list[str] + +class Cleaner: + tags: Iterable[str] attributes: _Attributes - styles: Container[str] - protocols: Container[str] + protocols: Iterable[str] strip: bool strip_comments: bool - filters: Iterable[_Filter] + filters: Iterable[_FilterConstructor] + css_sanitizer: CSSSanitizer | None parser: BleachHTMLParser - walker: Any + walker: TreeWalker serializer: BleachHTMLSerializer def __init__( self, - tags: Container[str] = ..., + tags: Iterable[str] = ..., attributes: _Attributes = ..., - styles: Container[str] = ..., - protocols: Container[str] = ..., - strip: bool = ..., - strip_comments: bool = ..., - filters: Iterable[_Filter] | None = ..., + protocols: Iterable[str] = ..., + strip: bool = False, + strip_comments: bool = True, + filters: Iterable[_FilterConstructor] | None = None, + css_sanitizer: CSSSanitizer | None = None, ) -> None: ... def clean(self, text: str) -> str: ... -_AttributeFilter = Callable[[str, str, str], bool] -_AttributeDict = Union[Dict[str, Union[List[str], _AttributeFilter]], Dict[str, List[str]], Dict[str, _AttributeFilter]] -_Attributes = Union[_AttributeFilter, _AttributeDict, List[str]] - def attribute_filter_factory(attributes: _Attributes) -> _AttributeFilter: ... class BleachSanitizerFilter(SanitizerFilter): + allowed_tags: frozenset[str] + allowed_protocols: frozenset[str] attr_filter: _AttributeFilter - strip_disallowed_elements: bool + strip_disallowed_tags: bool strip_html_comments: bool + attr_val_is_uri: frozenset[_HTMLAttrKey] + svg_attr_val_allows_ref: frozenset[_HTMLAttrKey] + svg_allow_local_href: frozenset[_HTMLAttrKey] + css_sanitizer: CSSSanitizer | None def __init__( self, - source, + source: TreeWalker, + allowed_tags: Iterable[str] = ..., attributes: _Attributes = ..., - strip_disallowed_elements: bool = ..., - strip_html_comments: bool = ..., - **kwargs, + allowed_protocols: Iterable[str] = ..., + attr_val_is_uri: frozenset[_HTMLAttrKey] = ..., + svg_attr_val_allows_ref: frozenset[_HTMLAttrKey] = ..., + svg_allow_local_href: frozenset[_HTMLAttrKey] = ..., + strip_disallowed_tags: bool = False, + strip_html_comments: bool = True, + css_sanitizer: CSSSanitizer | None = None, ) -> None: ... - def sanitize_stream(self, token_iterator): ... - def merge_characters(self, token_iterator): ... - def __iter__(self): ... - def sanitize_token(self, token): ... - def sanitize_characters(self, token): ... - def sanitize_uri_value(self, value, allowed_protocols): ... - def allow_token(self, token): ... - def disallowed_token(self, token): ... - def sanitize_css(self, style): ... + def sanitize_stream(self, token_iterator: Iterable[_Token]) -> Iterator[_Token]: ... + def merge_characters(self, token_iterator: Iterable[_Token]) -> Iterator[_Token]: ... + def __iter__(self) -> Iterator[_Token]: ... + def sanitize_token(self, token: _Token) -> _Token | list[_Token] | None: ... # type: ignore[override] + def sanitize_characters(self, token: _Token) -> _Token | list[_Token]: ... + def sanitize_uri_value(self, value: str, allowed_protocols: Container[str]) -> str | None: ... + def allow_token(self, token: _Token) -> _Token: ... + def disallowed_token(self, token: _Token) -> _Token: ... diff --git a/stubs/bleach/bleach/utils.pyi b/stubs/bleach/bleach/utils.pyi deleted file mode 100644 index 1eff440f0526..000000000000 --- a/stubs/bleach/bleach/utils.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from collections import OrderedDict -from collections.abc import Mapping -from typing import Any, overload - -@overload -def alphabetize_attributes(attrs: None) -> None: ... -@overload -def alphabetize_attributes(attrs: Mapping[Any, str]) -> OrderedDict[Any, str]: ... diff --git a/stubs/boltons/@tests/stubtest_allowlist.txt b/stubs/boltons/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2ad9d612df92 --- /dev/null +++ b/stubs/boltons/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +boltons.funcutils.CachedInstancePartial.__partialmethod__ +boltons.funcutils.InstancePartial.__partialmethod__ diff --git a/stubs/boltons/METADATA.toml b/stubs/boltons/METADATA.toml new file mode 100644 index 000000000000..9c5868f7d067 --- /dev/null +++ b/stubs/boltons/METADATA.toml @@ -0,0 +1,2 @@ +version = "26.1.*" +upstream-repository = "https://github.com/mahmoud/boltons" diff --git a/stubs/boltons/boltons/__init__.pyi b/stubs/boltons/boltons/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/boltons/boltons/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/boltons/boltons/cacheutils.pyi b/stubs/boltons/boltons/cacheutils.pyi new file mode 100644 index 000000000000..978da569d563 --- /dev/null +++ b/stubs/boltons/boltons/cacheutils.pyi @@ -0,0 +1,152 @@ +import weakref +from _typeshed import Incomplete, SupportsItems, SupportsKeysAndGetItem +from collections.abc import Callable, Generator, Hashable, Iterable, Iterator, Mapping +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_T = TypeVar("_T") + +PREV: int +NEXT: int +KEY: int +VALUE: int +DEFAULT_MAX_SIZE: int + +class LRI(dict[_KT, _VT]): + hit_count: int + miss_count: int + soft_miss_count: int + max_size: int + on_miss: Callable[[_KT], _VT] | None + def __init__(self, max_size: int = 128, values=None, on_miss: Callable[[_KT], _VT] | None = None) -> None: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _T | _VT: ... + + def __delitem__(self, key: _KT) -> None: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _T | _VT: ... + + def popitem(self) -> tuple[_KT, _VT]: ... + def clear(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def setdefault(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + def update(self, E: SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]], **F: _VT) -> None: ... # type: ignore[override] + +class LRU(LRI[_KT, _VT]): + def __getitem__(self, key: _KT) -> _VT: ... + +def make_cache_key( + args: Iterable[Hashable], + kwargs: SupportsItems[Hashable, Hashable], + typed: bool = False, + kwarg_mark: object = ..., + fasttypes: frozenset[type] = ..., +): ... + +class CachedFunction: + func: Incomplete + get_cache: Incomplete + scoped: Incomplete + typed: Incomplete + key_func: Incomplete + def __init__( + self, + func, + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, + ): ... + def __call__(self, *args, **kwargs): ... + +class CachedMethod: + func: Incomplete + get_cache: Incomplete + scoped: Incomplete + typed: Incomplete + key_func: Incomplete + bound_to: Incomplete + def __init__( + self, + func, + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, + ): ... + def __get__(self, obj, objtype=None): ... + def __call__(self, *args, **kwargs): ... + +def cached( + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, +): ... +def cachedmethod( + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, +): ... + +class cachedproperty(Generic[_KT, _VT]): + func: Callable[[_KT], _VT] + def __init__(self, func: Callable[[_KT], _VT]) -> None: ... + + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: _KT, objtype: type | None = None) -> _VT: ... + +class ThresholdCounter(Generic[_T]): + total: int + def __init__(self, threshold: float = 0.001) -> None: ... + @property + def threshold(self) -> float: ... + def add(self, key: _T) -> None: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... + def get_common_count(self) -> int: ... + def get_uncommon_count(self) -> int: ... + def get_commonality(self) -> float: ... + def __getitem__(self, key: _T) -> int: ... + def __len__(self) -> int: ... + def __contains__(self, key: _T) -> bool: ... + def iterkeys(self) -> Iterator[_T]: ... + def keys(self) -> list[_T]: ... + def itervalues(self) -> Generator[int]: ... + def values(self) -> list[int]: ... + def iteritems(self) -> Generator[tuple[_T, int]]: ... + def items(self) -> list[tuple[_T, int]]: ... + def get(self, key: _T, default: int = 0) -> int: ... + def update(self, iterable: Iterable[_T] | Mapping[_T, int], **kwargs: Iterable[_T] | Mapping[_T, int]) -> None: ... + +class MinIDMap(Generic[_T]): + mapping: weakref.WeakKeyDictionary[_T, tuple[int, weakref.ReferenceType[_T]]] + ref_map: dict[weakref.ReferenceType[_T], int] + free: list[int] + def __init__(self) -> None: ... + def get(self, a: _T) -> int: ... + def drop(self, a: _T) -> None: ... + def __contains__(self, a: _T) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def iteritems(self) -> Iterator[tuple[_T, int]]: ... diff --git a/stubs/boltons/boltons/debugutils.pyi b/stubs/boltons/boltons/debugutils.pyi new file mode 100644 index 000000000000..6b6f8f6989a4 --- /dev/null +++ b/stubs/boltons/boltons/debugutils.pyi @@ -0,0 +1,10 @@ +from collections.abc import Callable +from typing import Any + +def pdb_on_signal(signalnum: int | None = None) -> None: ... +def pdb_on_exception(limit: int = 100) -> None: ... +def wrap_trace( + obj, hook: Callable[..., Any] = ..., which: str | None = None, events: str | None = None, label: str | None = None +): ... + +__all__ = ["pdb_on_signal", "pdb_on_exception", "wrap_trace"] diff --git a/stubs/boltons/boltons/deprutils.pyi b/stubs/boltons/boltons/deprutils.pyi new file mode 100644 index 000000000000..2e25d98e748e --- /dev/null +++ b/stubs/boltons/boltons/deprutils.pyi @@ -0,0 +1,8 @@ +from types import ModuleType +from typing import Any + +class DeprecatableModule(ModuleType): + def __init__(self, module: ModuleType) -> None: ... + def __getattribute__(self, name: str) -> Any: ... + +def deprecate_module_member(mod_name: str, name: str, message: str) -> None: ... diff --git a/stubs/boltons/boltons/dictutils.pyi b/stubs/boltons/boltons/dictutils.pyi new file mode 100644 index 000000000000..e2a8277fca00 --- /dev/null +++ b/stubs/boltons/boltons/dictutils.pyi @@ -0,0 +1,129 @@ +from _typeshed import SupportsKeysAndGetItem +from collections.abc import Generator, ItemsView, Iterable, Iterator, KeysView, ValuesView +from typing import Any, Generic, TypeAlias, TypeVar, overload +from typing_extensions import Never, Self + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_T = TypeVar("_T") + +class OrderedMultiDict(dict[_KT, _VT]): + def __reduce__(self) -> tuple[type[Self], tuple[()], list[tuple[_KT, _VT]]]: ... + def add(self, k: _KT, v: _VT) -> None: ... + def addlist(self, k: _KT, v: Iterable[_VT]) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Self: ... + def counts(self) -> OrderedMultiDict[_KT, int]: ... + + @overload # type: ignore[override] + @classmethod + def fromkeys(cls, keys: Iterable[_KT], default: None = None) -> OrderedMultiDict[_KT, Any | None]: ... + @overload + @classmethod + def fromkeys(cls, keys: Iterable[_KT], default: _T) -> OrderedMultiDict[_KT, _T]: ... + + @overload # type: ignore[override] + def get(self, k: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, k: _KT, default: _VT) -> _VT: ... + + @overload + def getlist(self, k: _KT) -> list[_VT]: ... + @overload + def getlist(self, k: _KT, default: _T) -> list[_VT] | _T: ... + + def inverted(self) -> OrderedMultiDict[_VT, _KT]: ... + def items(self, multi: bool = False) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def iteritems(self, multi: bool = False) -> Generator[tuple[_KT, _VT]]: ... + def iterkeys(self, multi: bool = False) -> Generator[_KT]: ... + def itervalues(self, multi: bool = False) -> Generator[_VT]: ... + def keys(self, multi: bool = False) -> list[_KT]: ... # type: ignore[override] + def pop(self, k: _KT, default: _VT = ...) -> _VT: ... # type: ignore[override] + def popall(self, k: _KT, default: _VT = ...) -> list[_VT]: ... + def poplast(self, k: _KT = ..., default: _VT = ...) -> _VT: ... + + @overload # type: ignore[override] + def setdefault(self, k: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, k: _KT, default: _VT) -> _VT: ... + + def sorted(self, key: _KT | None = None, reverse: bool = False) -> Self: ... + def sortedvalues(self, key: _KT | None = None, reverse: bool = False) -> Self: ... + def todict(self, multi: bool = False) -> dict[_KT, _VT]: ... + def update(self, E: SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]], **F) -> None: ... # type: ignore[override] + def update_extend(self, E: SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]], **F) -> None: ... + def values(self, multi: bool = False) -> list[_VT]: ... # type: ignore[override] + def viewitems(self) -> ItemsView[_KT, _VT]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + +OMD: TypeAlias = OrderedMultiDict[_KT, _VT] +MultiDict: TypeAlias = OrderedMultiDict[_KT, _VT] + +class FastIterOrderedMultiDict(OrderedMultiDict[_KT, _VT]): # undocumented + def iteritems(self, multi: bool = False) -> Generator[tuple[_KT, _VT]]: ... + def iterkeys(self, multi: bool = False) -> Generator[_KT]: ... + +class OneToOne(dict[_KT, _VT]): + __slots__ = ("inv",) + inv: OneToOne[_VT, _KT] + def clear(self) -> None: ... + def copy(self) -> Self: ... + def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + def popitem(self) -> tuple[_KT, _VT]: ... + + @overload + def setdefault(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @classmethod + def unique(cls, *a, **kw) -> Self: ... + def update(self, dict_or_iterable, **kw) -> None: ... # type: ignore[override] + +class ManyToMany(Generic[_KT, _VT]): + data: dict[_KT, set[_VT]] + inv: ManyToMany[_VT, _KT] + def __contains__(self, key: object) -> bool: ... + def __delitem__(self, key: _KT) -> None: ... + def __eq__(self, other): ... + def __getitem__(self, key: _KT) -> frozenset[_VT]: ... + def __init__( + self, items: ManyToMany[_KT, _VT] | SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None = None + ) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + def __setitem__(self, key: _KT, vals: Iterable[_VT]) -> None: ... + def add(self, key: _KT, val: _VT) -> None: ... + + @overload + def get(self, key: _KT) -> frozenset[_VT]: ... + @overload + def get(self, key: _KT, default: _T) -> frozenset[_VT] | _T: ... + + def iteritems(self) -> Generator[tuple[_KT, _VT]]: ... + def keys(self) -> KeysView[_KT]: ... + def remove(self, key: _KT, val: _VT) -> None: ... + def replace(self, key: _KT, newkey: _KT) -> None: ... + def update(self, iterable: ManyToMany[_KT, _VT] | SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + +def subdict(d: dict[_KT, _VT], keep: Iterable[_KT] | None = None, drop: Iterable[_KT] | None = None) -> dict[_KT, _VT]: ... + +class FrozenHashError(TypeError): ... # undocumented + +class FrozenDict(dict[_KT, _VT]): + __slots__ = ("_hash",) + def __copy__(self) -> Self: ... + @classmethod + def fromkeys(cls, keys: Iterable[_KT], value: _VT | None = None) -> Self: ... # type: ignore[override] + def updated(self, *a, **kw) -> Self: ... + def __ior__(self, *a, **kw) -> Never: ... # type: ignore[misc] # noqa: Y034 # Signature conflicts with superclass + def __setitem__(self, *a, **kw) -> Never: ... + def __delitem__(self, *a, **kw) -> Never: ... + def update(self, *a, **kw) -> Never: ... + def pop(self, *a, **kw) -> Never: ... + def popitem(self, *a, **kw) -> Never: ... + def setdefault(self, *a, **kw) -> Never: ... + def clear(self, *a, **kw) -> Never: ... + +__all__ = ["MultiDict", "OMD", "OrderedMultiDict", "OneToOne", "ManyToMany", "subdict", "FrozenDict"] diff --git a/stubs/boltons/boltons/easterutils.pyi b/stubs/boltons/boltons/easterutils.pyi new file mode 100644 index 000000000000..bea7b390f909 --- /dev/null +++ b/stubs/boltons/boltons/easterutils.pyi @@ -0,0 +1,3 @@ +from typing_extensions import Never + +def gobs_program() -> Never: ... diff --git a/stubs/boltons/boltons/ecoutils.pyi b/stubs/boltons/boltons/ecoutils.pyi new file mode 100644 index 000000000000..c02820701d97 --- /dev/null +++ b/stubs/boltons/boltons/ecoutils.pyi @@ -0,0 +1,26 @@ +from typing import Any + +ECO_VERSION: str +HAVE_URANDOM: bool +INSTANCE_ID: str +IS_64BIT: bool +HAVE_UCS4: bool +HAVE_READLINE: bool +SQLITE_VERSION: str +OPENSSL_VERSION: str +TKINTER_VERSION: str +ZLIB_VERSION: str +EXPAT_VERSION: str +CPU_COUNT: int +HAVE_THREADING: bool +HAVE_IPV6: bool +RLIMIT_FDS_SOFT: int +RLIMIT_FDS_HARD: int +START_TIME_INFO: dict[str, str | float] + +def getrandbits(k: int) -> int: ... +def get_python_info() -> dict[str, Any]: ... +def get_profile(**kwargs) -> dict[str, Any]: ... +def get_profile_json(indent: bool = False) -> str: ... +def main() -> None: ... +def dumps(val: Any, indent: int) -> str: ... diff --git a/stubs/boltons/boltons/excutils.pyi b/stubs/boltons/boltons/excutils.pyi new file mode 100644 index 000000000000..bb6a42dbcd11 --- /dev/null +++ b/stubs/boltons/boltons/excutils.pyi @@ -0,0 +1,11 @@ +from typing import Any +from typing_extensions import Self + +class ExceptionCauseMixin(Exception): + cause: Any + def __new__(cls, *args, **kw) -> Self: ... + def get_str(self) -> str: ... + +class MathError(ExceptionCauseMixin, ValueError): ... + +__all__ = ["ExceptionCauseMixin"] diff --git a/stubs/boltons/boltons/fileutils.pyi b/stubs/boltons/boltons/fileutils.pyi new file mode 100644 index 000000000000..8e2fb8b75b27 --- /dev/null +++ b/stubs/boltons/boltons/fileutils.pyi @@ -0,0 +1,96 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath +from collections.abc import Callable, Generator, Iterable +from os import PathLike +from types import TracebackType +from typing import IO, Any, TypeVar, overload +from typing_extensions import Never, Self + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) + +def mkdir_p(path: StrOrBytesPath) -> None: ... +def rotate_file(filename: PathLike[str], *, keep: int = 5) -> None: ... + +class FilePerms: + user: str + group: str + other: str + def __init__(self, user: str = "", group: str = "", other: str = "") -> None: ... + @classmethod + def from_int(cls, i: int) -> Self: ... + @classmethod + def from_path(cls, path: StrOrBytesPath) -> Self: ... + def __int__(self) -> int: ... + +def atomic_save(dest_path: str, **kwargs) -> AtomicSaver: ... + +class AtomicSaver: + dest_path: str + overwrite: bool + file_perms: int | None + overwrite_part: bool + part_filename: str | None + rm_part_on_exc: bool + text_mode: bool + buffering: int + dest_dir: str + part_path: str + mode: str + open_flags: int + part_file: str | None + def __init__(self, dest_path: str, **kwargs) -> None: ... + def setup(self) -> None: ... + def __enter__(self) -> IO[Any] | None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +def iter_find_files( + directory: str, + patterns: str | Iterable[str], + ignored: str | Iterable[str] | None = None, + include_dirs: bool = False, + max_depth: int | None = None, +) -> Generator[str]: ... + +@overload +def copy_tree( + src: _StrPathT, dst: _StrPathT, symlinks: bool = False, ignore: Callable[[_StrPathT, list[str]], Iterable[str]] | None = None +) -> None: ... +@overload +def copy_tree( + src: _BytesPathT, + dst: _BytesPathT, + symlinks: bool = False, + ignore: Callable[[_BytesPathT, list[bytes]], Iterable[bytes]] | None = None, +) -> None: ... + +copytree = copy_tree + +class DummyFile: + name: StrOrBytesPath + mode: str + closed: bool + errors: None + isatty: bool + encoding: None + newlines: None + softspace: int + def __init__(self, path: StrOrBytesPath, mode: str = "r", buffering: int | None = None) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def next(self) -> Never: ... + def read(self, size: int = 0) -> str: ... + def readline(self, size: int = 0) -> str: ... + def readlines(self, size: int = 0) -> list[str]: ... + def seek(self) -> None: ... + def tell(self) -> int: ... + def truncate(self) -> None: ... + def write(self, string: str) -> None: ... + def writelines(self, list_of_strings: list[str]) -> None: ... + def __next__(self) -> Never: ... + def __enter__(self) -> None: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +__all__ = ["mkdir_p", "atomic_save", "AtomicSaver", "FilePerms", "iter_find_files", "copytree"] diff --git a/stubs/boltons/boltons/formatutils.pyi b/stubs/boltons/boltons/formatutils.pyi new file mode 100644 index 000000000000..b9f3eb897b54 --- /dev/null +++ b/stubs/boltons/boltons/formatutils.pyi @@ -0,0 +1,46 @@ +from collections.abc import Callable +from typing import Generic, TypeVar + +_T = TypeVar("_T") + +def construct_format_field_str(fname: str | None, fspec: str | None, conv: str | None) -> str: ... +def infer_positional_format_args(fstr: str) -> str: ... +def get_format_args(fstr: str) -> tuple[list[tuple[int, type]], list[tuple[str, type]]]: ... +def tokenize_format_str(fstr: str, resolve_pos: bool = True) -> list[str | BaseFormatField]: ... + +class BaseFormatField: + def __init__(self, fname: str, fspec: str = "", conv: str | None = None) -> None: ... + base_name: str + fname: str + subpath: str + is_positional: bool + def set_fname(self, fname: str) -> None: ... + subfields: list[str] + fspec: str + type_char: str + type_func: str + def set_fspec(self, fspec) -> None: ... + conv: str | None + conv_func: str | None + def set_conv(self, conv: str | None) -> None: ... + @property + def fstr(self) -> str: ... + +class DeferredValue(Generic[_T]): + func: Callable[[], _T] + cache_value: bool + def __init__(self, func: Callable[[], _T], cache_value: bool = True) -> None: ... + def get_value(self) -> _T: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __unicode__(self) -> str: ... + def __format__(self, fmt: str) -> str: ... + +__all__ = [ + "DeferredValue", + "get_format_args", + "tokenize_format_str", + "construct_format_field_str", + "infer_positional_format_args", + "BaseFormatField", +] diff --git a/stubs/boltons/boltons/funcutils.pyi b/stubs/boltons/boltons/funcutils.pyi new file mode 100644 index 000000000000..1a964c7d8abc --- /dev/null +++ b/stubs/boltons/boltons/funcutils.pyi @@ -0,0 +1,68 @@ +import functools +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from functools import total_ordering as total_ordering +from typing import TypeVar + +_R = TypeVar("_R") + +NO_DEFAULT: Incomplete + +def inspect_formatargspec( + args, + varargs=None, + varkw=None, + defaults=None, + kwonlyargs=(), + kwonlydefaults={}, + annotations={}, + formatarg=..., + formatvarargs=..., + formatvarkw=..., + formatvalue=..., + formatreturns=..., + formatannotation=..., +): ... +def get_module_callables(mod, ignore=None): ... +def mro_items(type_obj): ... +def dir_dict(obj, raise_exc: bool = False): ... +def copy_function(orig, copy_dict: bool = True): ... +def partial_ordering(cls): ... + +class InstancePartial(functools.partial[Incomplete]): + def __get__(self, obj, obj_type): ... # type: ignore[override] + +class CachedInstancePartial(functools.partial[Incomplete]): + __name__: Incomplete + def __set_name__(self, obj_type, name) -> None: ... + __doc__: Incomplete + __module__: Incomplete + def __get__(self, obj, obj_type): ... # type: ignore[override] + +partial = CachedInstancePartial + +def format_invocation(name: str = "", args=(), kwargs=None, **kw): ... +def format_exp_repr(obj, pos_names, req_names=None, opt_names=None, opt_key=None): ... +def format_nonexp_repr(obj, req_names=None, opt_names=None, opt_key=None): ... +def wraps(func, injected=None, expected=None, **kw): ... +def update_wrapper(wrapper, func, injected=None, expected=None, build_from=None, **kw): ... + +class FunctionBuilder: + name: Incomplete + def __init__(self, name, **kw) -> None: ... + def get_sig_str(self, with_annotations: bool = True): ... + def get_invocation_str(self): ... + @classmethod + def from_func(cls, func): ... + def get_func(self, execdict=None, add_source: bool = True, with_dict: bool = True): ... + def get_defaults_dict(self): ... + def get_arg_names(self, only_required: bool = False): ... + defaults: Incomplete + def add_arg(self, arg_name, default=..., kwonly: bool = False) -> None: ... + def remove_arg(self, arg_name) -> None: ... + +class MissingArgument(ValueError): ... +class ExistingArgument(ValueError): ... + +def noop(*args: Unused, **kwargs: Unused) -> None: ... +def once(func: Callable[[], _R]) -> Callable[[], _R]: ... diff --git a/stubs/boltons/boltons/gcutils.pyi b/stubs/boltons/boltons/gcutils.pyi new file mode 100644 index 000000000000..33e8006102b9 --- /dev/null +++ b/stubs/boltons/boltons/gcutils.pyi @@ -0,0 +1,16 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +def get_all(type_obj: type[_T], include_subtypes: bool = True) -> list[_T]: ... + +class GCToggler: + postcollect: bool + def __init__(self, postcollect: bool = False) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +toggle_gc: GCToggler +toggle_gc_postcollect: GCToggler + +__all__ = ["get_all", "GCToggler", "toggle_gc", "toggle_gc_postcollect"] diff --git a/stubs/boltons/boltons/ioutils.pyi b/stubs/boltons/boltons/ioutils.pyi new file mode 100644 index 000000000000..90bb47dad2e1 --- /dev/null +++ b/stubs/boltons/boltons/ioutils.pyi @@ -0,0 +1,92 @@ +import abc +from _typeshed import Incomplete +from abc import abstractmethod + +READ_CHUNK_SIZE: int +EINVAL: Incomplete + +class SpooledIOBase(metaclass=abc.ABCMeta): + __metaclass__: Incomplete + def __init__(self, max_size: int = 5000000, dir=None) -> None: ... + @abstractmethod + def read(self, n: int = -1): ... + @abstractmethod + def write(self, s): ... + @abstractmethod + def seek(self, pos, mode: int = 0): ... + @abstractmethod + def readline(self, length=None): ... + @abstractmethod + def readlines(self, sizehint: int = 0): ... + def writelines(self, lines) -> None: ... + @abstractmethod + def rollover(self): ... + @abstractmethod + def tell(self): ... + @property + @abc.abstractmethod + def buffer(self): ... + @property + @abc.abstractmethod + def len(self): ... + softspace: Incomplete + def close(self): ... + def flush(self): ... + def isatty(self): ... + def next(self): ... + @property + def closed(self): ... + @property + def pos(self): ... + @property + def buf(self): ... + def fileno(self): ... + def truncate(self, size=None): ... + def getvalue(self): ... + def seekable(self): ... + def readable(self): ... + def writable(self): ... + __next__: Incomplete + def __len__(self): ... + def __iter__(self): ... + def __enter__(self): ... + def __exit__(self, *args) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __bool__(self): ... + def __del__(self) -> None: ... + __nonzero__: Incomplete + +class SpooledBytesIO(SpooledIOBase): + def read(self, n: int = -1): ... + def write(self, s) -> None: ... + def seek(self, pos, mode: int = 0): ... + def readline(self, length=None): ... + def readlines(self, sizehint: int = 0): ... + def rollover(self) -> None: ... + @property + def buffer(self): ... + @property + def len(self): ... + def tell(self): ... + +class SpooledStringIO(SpooledIOBase): + def __init__(self, *args, **kwargs) -> None: ... + def read(self, n: int = -1): ... + def write(self, s) -> None: ... + def seek(self, pos, mode: int = 0): ... + def readline(self, length=None): ... + def readlines(self, sizehint: int = 0): ... + @property + def buffer(self): ... + def rollover(self) -> None: ... + def tell(self): ... + @property + def len(self): ... + +def is_text_fileobj(fileobj) -> bool: ... + +class MultiFileReader: + def __init__(self, *fileobjs) -> None: ... + def read(self, amt=None): ... + def seek(self, offset, whence=0) -> None: ... diff --git a/stubs/boltons/boltons/iterutils.pyi b/stubs/boltons/boltons/iterutils.pyi new file mode 100644 index 000000000000..cf0251567288 --- /dev/null +++ b/stubs/boltons/boltons/iterutils.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterable +from typing import TypeVar +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def is_iterable(obj: Iterable[_T] | object) -> TypeIs[Iterable[_T]]: ... +def is_scalar(obj: object) -> bool: ... +def is_collection(obj: object) -> bool: ... +def split(src, sep=None, maxsplit=None): ... +def split_iter(src, sep=None, maxsplit=None) -> Generator[list[Incomplete]]: ... +def lstrip(iterable, strip_value=None): ... +def lstrip_iter(iterable, strip_value=None) -> Generator[Incomplete]: ... +def rstrip(iterable, strip_value=None): ... +def rstrip_iter(iterable, strip_value=None) -> Generator[Incomplete]: ... +def strip(iterable, strip_value=None): ... +def strip_iter(iterable, strip_value=None): ... +def chunked(src, size, count=None, **kw): ... +def chunked_iter(src, size, **kw) -> Generator[str | bytes]: ... +def chunk_ranges( + input_size: int, chunk_size: int, input_offset: int = 0, overlap_size: int = 0, align: bool = False +) -> Generator[tuple[int, int]]: ... +def pairwise(src, end=...): ... +def pairwise_iter(src, end=...): ... +def windowed(src, size, fill=...): ... +def windowed_iter(src, size, fill=...): ... +def xfrange(stop, start=None, step: float = 1.0) -> Generator[Incomplete]: ... +def frange(stop, start=None, step: float = 1.0): ... +def backoff(start, stop, count=None, factor: float = 2.0, jitter: bool = False): ... +def backoff_iter(start, stop, count=None, factor: float = 2.0, jitter: bool = False) -> Generator[Incomplete]: ... +def bucketize(src, key=..., value_transform=None, key_filter=None): ... +def partition(src, key=..., *keys: str | Callable[..., Incomplete]) -> tuple[list[Incomplete], ...]: ... +def unique(src, key=None): ... +def unique_iter(src, key=None) -> Generator[Incomplete]: ... +def redundant(src, key=None, groups: bool = False): ... +def one(src, default=None, key=None): ... +def first(iterable, default=None, key=None): ... +def flatten_iter(iterable) -> Generator[Incomplete]: ... +def flatten(iterable): ... +def same(iterable, ref=...): ... +def default_visit(path, key, value): ... +def default_enter(path, key, value): ... +def default_exit(path, key, old_parent, new_parent, new_items): ... +def remap(root, visit=..., enter=..., exit=..., cache: bool = True, **kwargs): ... + +class PathAccessError(KeyError, IndexError, TypeError): + exc: Incomplete + seg: Incomplete + path: Incomplete + def __init__(self, exc, seg, path) -> None: ... + +def get_path(root, path, default=...): ... +def research(root, query=..., reraise: bool = False, enter=...): ... + +class GUIDerator: + size: Incomplete + count: Incomplete + def __init__(self, size: int = 24) -> None: ... + pid: Incomplete + salt: Incomplete + def reseed(self) -> None: ... + def __iter__(self): ... + def __next__(self): ... + next: Incomplete + +class SequentialGUIDerator(GUIDerator): + start: Incomplete + def reseed(self) -> None: ... + def __next__(self): ... + next: Incomplete + +guid_iter: Incomplete +seq_guid_iter: Incomplete + +def soft_sorted(iterable, first=None, last=None, key=None, reverse: bool = False): ... +def untyped_sorted(iterable, key=None, reverse: bool = False): ... diff --git a/stubs/boltons/boltons/jsonutils.pyi b/stubs/boltons/boltons/jsonutils.pyi new file mode 100644 index 000000000000..276db26ef881 --- /dev/null +++ b/stubs/boltons/boltons/jsonutils.pyi @@ -0,0 +1,25 @@ +from collections.abc import Generator +from typing import IO, Any, overload +from typing_extensions import Self + +@overload +def reverse_iter_lines( + file_obj: IO[bytes], blocksize: int = 4096, preseek: bool = True, encoding: None = None +) -> Generator[bytes]: ... +@overload +def reverse_iter_lines(file_obj: IO[str], blocksize: int = 4096, preseek: bool = True, *, encoding: str) -> Generator[str]: ... +@overload +def reverse_iter_lines(file_obj: IO[str], blocksize: int, preseek: bool, encoding: str) -> Generator[str]: ... + +class JSONLIterator: + ignore_errors: bool + def __init__( + self, file_obj: IO[str], ignore_errors: bool = False, reverse: bool = False, rel_seek: float | None = None + ) -> None: ... + @property + def cur_byte_pos(self) -> int: ... + def __iter__(self) -> Self: ... + def next(self) -> Any: ... + __next__ = next + +__all__ = ["JSONLIterator", "reverse_iter_lines"] diff --git a/stubs/boltons/boltons/listutils.pyi b/stubs/boltons/boltons/listutils.pyi new file mode 100644 index 000000000000..33be50272087 --- /dev/null +++ b/stubs/boltons/boltons/listutils.pyi @@ -0,0 +1,32 @@ +from collections.abc import Iterable +from typing import SupportsIndex, TypeAlias, TypeVar +from typing_extensions import Self + +_T = TypeVar("_T") + +class BarrelList(list[_T]): + lists: list[list[_T]] + def __init__(self, iterable: Iterable[_T] | None = None) -> None: ... + def insert(self, index: SupportsIndex, item: _T) -> None: ... + def append(self, item: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def pop(self, *a) -> _T: ... + def iter_slice(self, start: int | None, stop: int | None, step: int | None = None) -> Iterable[_T]: ... + def del_slice(self, start: int, stop: int, step: int | None = None) -> None: ... + __delslice__ = del_slice + @classmethod + def from_iterable(cls, it: Iterable[_T]) -> Self: ... + def __getslice__(self, start: int, stop: int): ... + def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, sequence: Iterable[_T]) -> None: ... + def sort(self) -> None: ... # type: ignore[override] + def reverse(self) -> None: ... + def count(self, item: _T) -> int: ... + def index(self, item: _T) -> int: ... # type: ignore[override] + +BList: TypeAlias = BarrelList[_T] + +class SplayList(list[_T]): + def shift(self, item_index: int, dest_index: int = 0) -> None: ... + def swap(self, item_index: SupportsIndex, dest_index: SupportsIndex) -> None: ... + +__all__ = ["BList", "BarrelList"] diff --git a/stubs/boltons/boltons/mathutils.pyi b/stubs/boltons/boltons/mathutils.pyi new file mode 100644 index 000000000000..42920bcf99a4 --- /dev/null +++ b/stubs/boltons/boltons/mathutils.pyi @@ -0,0 +1,43 @@ +from collections.abc import Iterable +from typing import overload + +def clamp(x: float, lower: float = ..., upper: float = ...) -> float: ... + +@overload +def ceil(x: float, options: None = None) -> int: ... +@overload +def ceil(x: float, options: Iterable[float]) -> float: ... + +@overload +def floor(x: float, options: None = None) -> int: ... +@overload +def floor(x: float, options: Iterable[float]) -> float: ... + +class Bits: + __slots__ = ("val", "len") + val: int + len: int + def __init__(self, val: int | list[bool] | str | bytes = 0, len_: int | None = None) -> None: ... + def __getitem__(self, k) -> Bits | bool: ... + def __len__(self) -> int: ... + def __eq__(self, other) -> bool: ... + def __or__(self, other: Bits) -> Bits: ... + def __and__(self, other: Bits) -> Bits: ... + def __lshift__(self, other: int) -> Bits: ... + def __rshift__(self, other: int) -> Bits: ... + def __hash__(self) -> int: ... + def as_list(self) -> list[bool]: ... + def as_bin(self) -> str: ... + def as_hex(self) -> str: ... + def as_int(self) -> int: ... + def as_bytes(self) -> bytes: ... + @classmethod + def from_list(cls, list_): ... + @classmethod + def from_bin(cls, bin): ... + @classmethod + def from_hex(cls, hex): ... + @classmethod + def from_int(cls, int_, len_: int | None = None): ... + @classmethod + def from_bytes(cls, bytes_): ... diff --git a/stubs/boltons/boltons/mboxutils.pyi b/stubs/boltons/boltons/mboxutils.pyi new file mode 100644 index 000000000000..5d1019c9be16 --- /dev/null +++ b/stubs/boltons/boltons/mboxutils.pyi @@ -0,0 +1,17 @@ +import mailbox +from _typeshed import StrPath +from collections.abc import Callable +from typing import IO, Any + +DEFAULT_MAXMEM: int + +class mbox_readonlydir(mailbox.mbox): + maxmem: int + def __init__( + self, + path: StrPath, + factory: Callable[[IO[Any]], mailbox.mboxMessage] | None = None, + create: bool = True, + maxmem: int = 1048576, + ) -> None: ... + def flush(self) -> None: ... diff --git a/stubs/boltons/boltons/namedutils.pyi b/stubs/boltons/boltons/namedutils.pyi new file mode 100644 index 000000000000..ff57445a5998 --- /dev/null +++ b/stubs/boltons/boltons/namedutils.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterable + +def namedtuple(typename: str, field_names: str | Iterable[str], verbose: bool = False, rename: bool = False): ... +def namedlist(typename: str, field_names: str | Iterable[str], verbose: bool = False, rename: bool = False): ... + +__all__ = ["namedlist", "namedtuple"] diff --git a/stubs/boltons/boltons/pathutils.pyi b/stubs/boltons/boltons/pathutils.pyi new file mode 100644 index 000000000000..60566fa0f302 --- /dev/null +++ b/stubs/boltons/boltons/pathutils.pyi @@ -0,0 +1,15 @@ +from _typeshed import StrPath + +def augpath( + path: StrPath, + suffix: str = "", + prefix: str = "", + ext: str | None = None, + base: str | None = None, + dpath: str | None = None, + multidot: bool = False, +) -> str: ... +def shrinkuser(path: StrPath, home: str = "~") -> str: ... +def expandpath(path: StrPath) -> str: ... + +__all__ = ["augpath", "shrinkuser", "expandpath"] diff --git a/stubs/boltons/boltons/queueutils.pyi b/stubs/boltons/boltons/queueutils.pyi new file mode 100644 index 000000000000..83c6dd01e8a5 --- /dev/null +++ b/stubs/boltons/boltons/queueutils.pyi @@ -0,0 +1,16 @@ +from typing import TypeAlias + +class BasePriorityQueue: + def __init__(self, **kw) -> None: ... + def add(self, task, priority: int | None = None) -> None: ... + def remove(self, task) -> None: ... + def peek(self, default=...): ... + def pop(self, default=...): ... + def __len__(self) -> int: ... + +class HeapPriorityQueue(BasePriorityQueue): ... +class SortedPriorityQueue(BasePriorityQueue): ... + +PriorityQueue: TypeAlias = SortedPriorityQueue + +__all__ = ["PriorityQueue", "BasePriorityQueue", "HeapPriorityQueue", "SortedPriorityQueue"] diff --git a/stubs/boltons/boltons/setutils.pyi b/stubs/boltons/boltons/setutils.pyi new file mode 100644 index 000000000000..d94de1967fc0 --- /dev/null +++ b/stubs/boltons/boltons/setutils.pyi @@ -0,0 +1,105 @@ +from collections.abc import Collection, Container, Generator, Iterable, Iterator, MutableSet +from itertools import islice +from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only +from typing_extensions import Self + +_T_co = TypeVar("_T_co", covariant=True) + +@type_check_only +class _RSub(Iterable[_T_co], Protocol): + def __new__(cls: type[_RSub[_T_co]], param: list[_T_co], /) -> _RSub[_T_co]: ... + +class IndexedSet(MutableSet[Any]): + item_index_map: dict[Any, Any] + item_list: list[Any] + dead_indices: list[int] + def __init__(self, other: Iterable[Any] | None = None) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, item: Any) -> bool: ... + def __iter__(self) -> Iterator[Any]: ... + def __reversed__(self) -> Generator[Any]: ... + @classmethod + def from_iterable(cls, it: Iterable[Any]) -> Self: ... + def add(self, item: Any) -> None: ... + def remove(self, item: Any) -> None: ... + def discard(self, item: Any) -> None: ... + def clear(self) -> None: ... + def isdisjoint(self, other: Iterable[Any]) -> bool: ... + def issubset(self, other: Collection[Any]) -> bool: ... + def issuperset(self, other: Collection[Any]) -> bool: ... + def union(self, *others: Iterable[Any]) -> Self: ... + def iter_intersection(self, *others: Container[Any]) -> Generator[Any]: ... + def intersection(self, *others: Container[Any]) -> Self: ... + def iter_difference(self, *others: Iterable[Any]) -> Generator[Any]: ... + def difference(self, *others: Iterable[Any]) -> Self: ... + def symmetric_difference(self, *others: Container[Any]) -> Self: ... + # __or__ = union + __ror__ = union + # __and__ = intersection + __rand__ = intersection + # __sub__ = difference + # __xor__ = symmetric_difference + __rxor__ = symmetric_difference + def __rsub__(self, other: _RSub[_T_co]) -> _RSub[_T_co]: ... + def update(self, *others: Iterable[Any]) -> None: ... + def intersection_update(self, *others: Iterable[Any]) -> None: ... + def difference_update(self, *others: Container[Any]) -> None: ... + def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... + def iter_slice(self, start: int, stop: int, step: int | None = None) -> islice[Iterable[Any]]: ... + + @overload + def __getitem__(self, index: slice) -> Self: ... + @overload + def __getitem__(self, index: SupportsIndex) -> Any: ... + + def pop(self, index: int | None = None) -> Any: ... + def count(self, val: Any) -> Literal[0, 1]: ... + def reverse(self) -> None: ... + def sort(self, **kwargs) -> None: ... + def index(self, val: Any) -> int: ... + +def complement(wrapped: Iterable[Any]) -> _ComplementSet: ... + +class _ComplementSet: + __slots__ = ("_included", "_excluded") + def __init__( + self, included: set[Any] | frozenset[Any] | None = None, excluded: set[Any] | frozenset[Any] | None = None + ) -> None: ... + def complemented(self) -> _ComplementSet: ... + __invert__ = complemented + def complement(self) -> None: ... + def __contains__(self, item: Any) -> bool: ... + def add(self, item: Any) -> None: ... + def remove(self, item: Any) -> None: ... + def pop(self) -> Any: ... + def intersection(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __and__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + __rand__ = __and__ + def __iand__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> Self: ... + def union(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __or__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + __ror__ = __or__ + def __ior__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> Self: ... + def update(self, items: Iterable[Any]) -> None: ... + def discard(self, items: Iterable[Any]) -> None: ... + def symmetric_difference(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __xor__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + __rxor__ = __xor__ + def symmetric_difference_update(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> None: ... + def isdisjoint(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def issubset(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __le__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __lt__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def issuperset(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __ge__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __gt__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def difference(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __sub__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __rsub__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def difference_update(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> None: ... + def __isub__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> Self: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[Any]: ... + def __bool__(self) -> bool: ... + +__all__ = ["IndexedSet", "complement"] diff --git a/stubs/boltons/boltons/socketutils.pyi b/stubs/boltons/boltons/socketutils.pyi new file mode 100644 index 000000000000..30b438e689c3 --- /dev/null +++ b/stubs/boltons/boltons/socketutils.pyi @@ -0,0 +1,72 @@ +import socket +from _typeshed import ReadableBuffer, SliceableBuffer + +DEFAULT_TIMEOUT: int +DEFAULT_MAXSIZE: int + +class BufferedSocket: + sock: socket.socket + rbuf: bytes + sbuf: list[SliceableBuffer] + maxsize: int + timeout: int + def __init__(self, sock: socket.socket, timeout: int = ..., maxsize: int = 32768, recvsize: int = ...) -> None: ... + def settimeout(self, timeout: float) -> None: ... + def gettimeout(self) -> float: ... + def setblocking(self, blocking: bool) -> None: ... + def setmaxsize(self, maxsize) -> None: ... + def getrecvbuffer(self) -> bytes: ... + def getsendbuffer(self) -> bytes: ... + def recv(self, size: int, flags: int = 0, timeout: float = ...) -> bytes: ... + def peek(self, size: int, timeout: float = ...) -> bytes: ... + def recv_close(self, timeout: float = ..., maxsize: int = ...) -> bytes: ... + def recv_until( + self, delimiter: ReadableBuffer, timeout: float = ..., maxsize: int = ..., with_delimiter: bool = False + ) -> bytes: ... + def recv_size(self, size: int, timeout: float = ...) -> bytes: ... + def send(self, data: SliceableBuffer, flags: int = 0, timeout: float = ...) -> str: ... + def sendall(self, data: SliceableBuffer, flags: int = 0, timeout: float = ...) -> str: ... + def flush(self) -> None: ... + def buffer(self, data: SliceableBuffer) -> None: ... + def getsockname(self) -> str: ... + def getpeername(self) -> str: ... + def getsockopt(self, level: int, optname: int, buflen: int | None = None) -> bytes | int: ... + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer | None) -> bytes | int: ... + @property + def type(self) -> int: ... + @property + def family(self) -> int: ... + @property + def proto(self) -> int: ... + def fileno(self) -> int: ... + rbuf_unconsumed: bytes + def close(self) -> None: ... + def shutdown(self, how: int) -> None: ... + +class Error(socket.error): ... +class ConnectionClosed(Error): ... + +class MessageTooLong(Error): + def __init__(self, bytes_read: int | None = None, delimiter: str | None = None) -> None: ... + +class Timeout(socket.timeout, Error): + def __init__(self, timeout: float, extra: str = "") -> None: ... + +class NetstringSocket: + bsock: BufferedSocket + timeout: float + maxsize: int + def __init__(self, sock: socket.socket, timeout: float = 10, maxsize: int = 32768) -> None: ... + def fileno(self) -> int: ... + def settimeout(self, timeout: float) -> None: ... + def setmaxsize(self, maxsize: int) -> None: ... + def read_ns(self, timeout: float = ..., maxsize: int = ...): ... + def write_ns(self, payload: bytes) -> None: ... + +class NetstringProtocolError(Error): ... + +class NetstringInvalidSize(NetstringProtocolError): + def __init__(self, msg: str) -> None: ... + +class NetstringMessageTooLong(NetstringProtocolError): + def __init__(self, size: int, maxsize: int) -> None: ... diff --git a/stubs/boltons/boltons/statsutils.pyi b/stubs/boltons/boltons/statsutils.pyi new file mode 100644 index 000000000000..4165b8a16373 --- /dev/null +++ b/stubs/boltons/boltons/statsutils.pyi @@ -0,0 +1,76 @@ +from _typeshed import ConvertibleToFloat, Incomplete +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Literal, overload +from typing_extensions import Self + +class _StatsProperty: + name: str + func: Callable[..., Any] + internal_name: str + __doc__: str | None + def __init__(self, name: str, func: Callable[..., Any]) -> None: ... + + @overload + def __get__(self, obj: None, objtype: object = None) -> Self: ... + @overload + def __get__(self, obj: Stats, objtype: object = None) -> float: ... + +class Stats: + data: list[float] + default: float + + @overload + def __init__(self, data: list[float], default: float = 0.0, *, use_copy: Literal[False], is_sorted: bool = False) -> None: ... + @overload + def __init__(self, data: list[float], default: float, use_copy: Literal[False], is_sorted: bool = False) -> None: ... + @overload + def __init__( + self, data: Iterable[float], default: float = 0.0, use_copy: Literal[True] = True, is_sorted: bool = False + ) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[float]: ... + def clear_cache(self) -> None: ... + count: _StatsProperty + mean: _StatsProperty + max: _StatsProperty + min: _StatsProperty + median: _StatsProperty + iqr: _StatsProperty + trimean: _StatsProperty + variance: _StatsProperty + std_dev: _StatsProperty + median_abs_dev: _StatsProperty + mad: _StatsProperty + rel_std_dev: _StatsProperty + skewness: _StatsProperty + kurtosis: _StatsProperty + pearson_type: _StatsProperty + def get_quantile(self, q: ConvertibleToFloat) -> float: ... + def get_zscore(self, value: float) -> float: ... + def trim_relative(self, amount: float = 0.15) -> None: ... + def get_histogram_counts(self, bins: int | list[float] | None = None, **kw) -> list[tuple[float, int]]: ... + def format_histogram(self, bins: int | list[float] | None = None, **kw) -> str: ... + def describe( + self, quantiles: Iterable[float] | None = None, format: str | None = None + ) -> dict[str, float] | list[tuple[str, float]] | str: ... + +def describe( + data: Iterable[float], quantiles: Iterable[float] | None = None, format: str | None = None +) -> dict[str, float] | list[tuple[str, float]] | str: ... + +mean: Incomplete +median: Incomplete +iqr: Incomplete +trimean: Incomplete +variance: Incomplete +std_dev: Incomplete +median_abs_dev: Incomplete +rel_std_dev: Incomplete +skewness: Incomplete +kurtosis: Incomplete +pearson_type: Incomplete + +def format_histogram_counts( + bin_counts: list[float], width: int | None = None, format_bin: Callable[..., Any] | None = None +) -> str: ... diff --git a/stubs/boltons/boltons/strutils.pyi b/stubs/boltons/boltons/strutils.pyi new file mode 100644 index 000000000000..2eae46714980 --- /dev/null +++ b/stubs/boltons/boltons/strutils.pyi @@ -0,0 +1,103 @@ +from _typeshed import ReadableBuffer +from collections.abc import Callable, Generator, Iterable, Sequence, Sized +from html.parser import HTMLParser +from re import Pattern +from typing import Literal, overload + +def camel2under(camel_string: str) -> str: ... +def under2camel(under_string: str) -> str: ... + +@overload +def slugify(text: str, delim: str = "_", lower: bool = True, *, ascii: Literal[True]) -> bytes: ... +@overload +def slugify(text: str, delim: str, lower: bool, ascii: Literal[True]) -> bytes: ... +@overload +def slugify(text: str, delim: str = "_", lower: bool = True, ascii: Literal[False] = False) -> str: ... + +def split_punct_ws(text: str) -> list[str]: ... +def unit_len(sized_iterable: Sized, unit_noun: str = "item") -> str: ... +def ordinalize(number: int | str, ext_only: bool = False) -> str: ... +def cardinalize(unit_noun: str, count: int) -> str: ... +def singularize(word: str) -> str: ... +def pluralize(word: str) -> str: ... +def find_hashtags(string: str) -> list[str]: ... +def a10n(string: str) -> str: ... +def strip_ansi(text: str) -> str: ... +def asciify(text: str | bytes | bytearray, ignore: bool = False) -> bytes: ... +def is_ascii(text: str) -> bool: ... + +class DeaccenterDict(dict[int, int]): + def __missing__(self, key: int) -> int: ... + +def bytes2human(nbytes: int, ndigits: int = 0) -> str: ... + +class HTMLTextExtractor(HTMLParser): + result: list[str] + def __init__(self) -> None: ... + def handle_data(self, d: str) -> None: ... + def handle_charref(self, number: str) -> None: ... + def handle_entityref(self, name: str) -> None: ... + def get_text(self) -> str: ... + +def html2text(html: str) -> str: ... +def gunzip_bytes(bytestring: ReadableBuffer) -> bytes: ... +def gzip_bytes(bytestring: ReadableBuffer, level: int = 6) -> int: ... +def iter_splitlines(text: str) -> Generator[str]: ... +def indent(text: str, margin: str, newline: str = "\n", key: Callable[[str], bool] = ...) -> str: ... +def is_uuid(obj, version: int = 4) -> bool: ... +def escape_shell_args(args: Iterable[str], sep: str = " ", style: Literal["cmd", "sh"] | None = None) -> str: ... +def args2sh(args: Iterable[str], sep: str = " ") -> str: ... +def args2cmd(args: Iterable[str], sep: str = " ") -> str: ... +def parse_int_list(range_string: str, delim: str = ",", range_delim: str = "-") -> list[int]: ... +def format_int_list(int_list: list[int], delim: str = ",", range_delim: str = "-", delim_space: bool = False) -> str: ... +def complement_int_list( + range_string: str, range_start: int = 0, range_end: int | None = None, delim: str = ",", range_delim: str = "-" +) -> str: ... +def int_ranges_from_int_list(range_string: str, delim: str = ",", range_delim: str = "-") -> tuple[tuple[int, int], ...]: ... + +class MultiReplace: + group_map: dict[str, str] + combined_pattern: Pattern[str] + def __init__(self, sub_map: dict[str, str], **kwargs) -> None: ... + def sub(self, text: str) -> str: ... + +def multi_replace(text: str, sub_map: dict[str, str], **kwargs) -> str: ... +def unwrap_text(text: str, ending: str | None = "\n\n") -> str: ... +def removeprefix(text: str, prefix: str) -> str: ... +def human_readable_list(items: Sequence[str], delimiter: str = ",", conjunction: str = "and", *, oxford: bool = True) -> str: ... + +__all__ = [ + "camel2under", + "under2camel", + "slugify", + "split_punct_ws", + "unit_len", + "ordinalize", + "cardinalize", + "pluralize", + "singularize", + "asciify", + "is_ascii", + "is_uuid", + "html2text", + "strip_ansi", + "bytes2human", + "find_hashtags", + "a10n", + "gzip_bytes", + "gunzip_bytes", + "iter_splitlines", + "indent", + "escape_shell_args", + "args2cmd", + "args2sh", + "parse_int_list", + "format_int_list", + "complement_int_list", + "int_ranges_from_int_list", + "MultiReplace", + "multi_replace", + "unwrap_text", + "removeprefix", + "human_readable_list", +] diff --git a/stubs/boltons/boltons/tableutils.pyi b/stubs/boltons/boltons/tableutils.pyi new file mode 100644 index 000000000000..19c2ee650767 --- /dev/null +++ b/stubs/boltons/boltons/tableutils.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete + +class UnsupportedData(TypeError): ... + +class InputType: + def __init__(self, *a, **kw) -> None: ... + def get_entry_seq(self, data_seq, headers): ... + +class DictInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj): ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj, headers): ... + +class ObjectInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj): ... + def get_entry(self, obj, headers): ... + +class ListInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj) -> None: ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj_seq, headers): ... + +class TupleInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj) -> None: ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj_seq, headers): ... + +class NamedTupleInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj): ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj_seq, headers): ... + +class Table: + headers: Incomplete + metadata: Incomplete + def __init__(self, data=None, headers=..., metadata=None) -> None: ... + def extend(self, data) -> None: ... + @classmethod + def from_dict(cls, data, headers=..., max_depth: int = 1, metadata=None): ... + @classmethod + def from_list(cls, data, headers=..., max_depth: int = 1, metadata=None): ... + @classmethod + def from_object(cls, data, headers=..., max_depth: int = 1, metadata=None): ... + @classmethod + def from_data(cls, data, headers=..., max_depth: int = 1, **kwargs): ... + def __len__(self): ... + def __getitem__(self, idx): ... + def to_html( + self, + orientation=None, + wrapped: bool = True, + with_headers: bool = True, + with_newlines: bool = True, + with_metadata: bool = False, + max_depth: int = 1, + ): ... + def get_cell_html(self, value): ... + def to_text(self, with_headers: bool = True, maxlen=None): ... + +__all__ = ["Table"] diff --git a/stubs/boltons/boltons/tbutils.pyi b/stubs/boltons/boltons/tbutils.pyi new file mode 100644 index 000000000000..1d4648d6f129 --- /dev/null +++ b/stubs/boltons/boltons/tbutils.pyi @@ -0,0 +1,107 @@ +from collections.abc import Iterable, Iterator, Mapping +from types import FrameType, TracebackType +from typing import Any, Generic, Literal, TypeVar +from typing_extensions import Self + +class Callpoint: + __slots__ = ("func_name", "lineno", "module_name", "module_path", "lasti", "line") + func_name: str + lineno: int + module_name: str + module_path: str + lasti: int + line: str + def __init__( + self, module_name: str, module_path: str, func_name: str, lineno: int, lasti: int, line: str | None = None + ) -> None: ... + def to_dict(self) -> dict[str, Any]: ... + @classmethod + def from_current(cls, level: int = 1) -> Self: ... + @classmethod + def from_frame(cls, frame: FrameType) -> Self: ... + @classmethod + def from_tb(cls, tb: TracebackType) -> Self: ... + def tb_frame_str(self) -> str: ... + +_CallpointT_co = TypeVar("_CallpointT_co", bound=Callpoint, covariant=True, default=Callpoint) + +class TracebackInfo(Generic[_CallpointT_co]): + callpoint_type: type[_CallpointT_co] + frames: list[_CallpointT_co] + def __init__(self, frames: list[_CallpointT_co]) -> None: ... + @classmethod + def from_frame(cls, frame: FrameType | None = None, level: int = 1, limit: int | None = None) -> Self: ... + @classmethod + def from_traceback(cls, tb: TracebackType | None = None, limit: int | None = None) -> Self: ... + @classmethod + def from_dict(cls, d: Mapping[Literal["frames"], list[_CallpointT_co]]) -> Self: ... + def to_dict(self) -> dict[str, list[dict[str, _CallpointT_co]]]: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_CallpointT_co]: ... + def get_formatted(self) -> str: ... + +_TracebackInfoT_co = TypeVar("_TracebackInfoT_co", bound=TracebackInfo, covariant=True, default=TracebackInfo) + +class ExceptionInfo(Generic[_TracebackInfoT_co]): + tb_info_type: type[_TracebackInfoT_co] + exc_type: str + exc_msg: str + tb_info: _TracebackInfoT_co + def __init__(self, exc_type: str, exc_msg: str, tb_info: _TracebackInfoT_co) -> None: ... + @classmethod + def from_exc_info(cls, exc_type: type[BaseException], exc_value: BaseException, traceback: TracebackType) -> Self: ... + @classmethod + def from_current(cls) -> Self: ... + def to_dict(self) -> dict[str, str | dict[str, list[FrameType]]]: ... + def get_formatted(self) -> str: ... + def get_formatted_exception_only(self) -> str: ... + +class ContextualCallpoint(Callpoint): + local_reprs: dict[Any, Any] + pre_lines: list[str] + post_lines: list[str] + def __init__(self, *a, **kw) -> None: ... + @classmethod + def from_frame(cls, frame: FrameType) -> Self: ... + @classmethod + def from_tb(cls, tb: TracebackType) -> Self: ... + def to_dict(self) -> dict[str, Any]: ... + +class ContextualTracebackInfo(TracebackInfo[ContextualCallpoint]): + callpoint_type: type[ContextualCallpoint] + +class ContextualExceptionInfo(ExceptionInfo[ContextualTracebackInfo]): + tb_info_type: type[ContextualTracebackInfo] + +def print_exception( + etype: type[BaseException] | None, + value: BaseException | None, + tb: TracebackType | None, + limit: int | None = None, + file: str | None = None, +) -> None: ... + +class ParsedException: + exc_type: str + exc_msg: str + frames: list[FrameType] + def __init__(self, exc_type_name: str, exc_msg: str, frames: Iterable[Mapping[str, Any]] | None = None) -> None: ... + @property + def source_file(self) -> str | None: ... + def to_dict(self) -> dict[str, str | list[FrameType]]: ... + def to_string(self) -> str: ... + @classmethod + def from_string(cls, tb_str: str) -> Self: ... + +ParsedTB = ParsedException + +__all__ = [ + "ExceptionInfo", + "TracebackInfo", + "Callpoint", + "ContextualExceptionInfo", + "ContextualTracebackInfo", + "ContextualCallpoint", + "print_exception", + "ParsedException", +] diff --git a/stubs/boltons/boltons/timeutils.pyi b/stubs/boltons/boltons/timeutils.pyi new file mode 100644 index 000000000000..7416be362361 --- /dev/null +++ b/stubs/boltons/boltons/timeutils.pyi @@ -0,0 +1,62 @@ +from collections.abc import Generator +from datetime import date, datetime, timedelta, tzinfo + +total_seconds = timedelta.total_seconds + +def dt_to_timestamp(dt: datetime) -> int: ... +def isoparse(iso_str: str) -> datetime: ... +def parse_timedelta(text: str) -> timedelta: ... + +parse_td = parse_timedelta + +def decimal_relative_time( + d: datetime, other: datetime | None = None, ndigits: int = 0, cardinalize: bool = True +) -> tuple[float, str]: ... +def relative_time(d: datetime, other: datetime | None = None, ndigits: int = 0) -> str: ... +def strpdate(string: str, format: str) -> date: ... +def daterange(start: date, stop: date, step: int = 1, inclusive: bool = False) -> Generator[date]: ... + +ZERO: timedelta +HOUR: timedelta + +class ConstantTZInfo(tzinfo): + name: str + offset: timedelta + def __init__(self, name: str = "ConstantTZ", offset: timedelta = ...) -> None: ... + @property + def utcoffset_hours(self) -> str: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def tzname(self, dt: datetime | None) -> str: ... + def dst(self, dt: datetime | None) -> timedelta: ... + +UTC: ConstantTZInfo +EPOCH_AWARE: datetime + +class LocalTZInfo(tzinfo): + def is_dst(self, dt: datetime) -> bool: ... + def utcoffset(self, dt: datetime) -> timedelta: ... # type: ignore[override] # Doesn't support None + def dst(self, dt: datetime) -> timedelta: ... # type: ignore[override] # Doesn't support None + def tzname(self, dt: datetime) -> str: ... # type: ignore[override] # Doesn't support None + +LocalTZ: LocalTZInfo +DSTSTART_2007: datetime +DSTEND_2007: datetime +DSTSTART_1987_2006: datetime +DSTEND_1987_2006: datetime +DSTSTART_1967_1986: datetime +DSTEND_1967_1986: datetime + +class USTimeZone(tzinfo): + stdoffset: timedelta + reprname: str + stdname: str + dstname: str + def __init__(self, hours: int, reprname: str, stdname: str, dstname: str) -> None: ... + def tzname(self, dt: datetime | None) -> str: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def dst(self, dt: datetime | None) -> timedelta: ... + +Eastern: USTimeZone +Central: USTimeZone +Mountain: USTimeZone +Pacific: USTimeZone diff --git a/stubs/boltons/boltons/typeutils.pyi b/stubs/boltons/boltons/typeutils.pyi new file mode 100644 index 000000000000..c2ae45147c94 --- /dev/null +++ b/stubs/boltons/boltons/typeutils.pyi @@ -0,0 +1,17 @@ +from typing import Any, Literal, Protocol, type_check_only +from typing_extensions import Self + +@type_check_only +class _Sentinel(Protocol): + def __bool__(self) -> Literal[False]: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, _memo) -> Self: ... + +def make_sentinel(name: str = "_MISSING", var_name: str | None = None) -> _Sentinel: ... +def issubclass(subclass: type, baseclass: type) -> bool: ... +def get_all_subclasses(cls: type) -> list[type]: ... + +class classproperty: + fn: Any + def __init__(self, fn) -> None: ... + def __get__(self, instance, cls): ... diff --git a/stubs/boltons/boltons/urlutils.pyi b/stubs/boltons/boltons/urlutils.pyi new file mode 100644 index 000000000000..869001e1504a --- /dev/null +++ b/stubs/boltons/boltons/urlutils.pyi @@ -0,0 +1,82 @@ +from _typeshed import Incomplete + +from boltons.dictutils import OrderedMultiDict + +SCHEME_PORT_MAP: Incomplete +NO_NETLOC_SCHEMES: Incomplete + +class URLParseError(ValueError): ... + +DEFAULT_ENCODING: str + +def to_unicode(obj: object) -> str: ... +def find_all_links(text, with_text: bool = False, default_scheme: str = "https", schemes=()): ... +def quote_path_part(text, full_quote: bool = True): ... +def quote_query_part(text, full_quote: bool = True): ... +def quote_fragment_part(text, full_quote: bool = True): ... +def quote_userinfo_part(text, full_quote: bool = True): ... +def unquote(string, encoding: str = "utf-8", errors: str = "replace"): ... +def unquote_to_bytes(string): ... +def register_scheme(text, uses_netloc=None, default_port=None) -> None: ... +def resolve_path_parts(path_parts): ... + +class cachedproperty: + __doc__: Incomplete + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, obj, objtype=None): ... + +class URL: + scheme: Incomplete + username: Incomplete + password: Incomplete + family: Incomplete + host: Incomplete + port: Incomplete + path_parts: Incomplete + fragment: Incomplete + def __init__(self, url: str = "") -> None: ... + @classmethod + def from_parts( + cls, scheme=None, host=None, path_parts=(), query_params=(), fragment: str = "", port=None, username=None, password=None + ): ... + query_params: Incomplete + qp: Incomplete + + @property + def path(self): ... + @path.setter + def path(self, path_text) -> None: ... + + @property + def uses_netloc(self): ... + @property + def default_port(self): ... + def normalize(self, with_case: bool = True) -> None: ... + def navigate(self, dest): ... + def get_authority(self, full_quote: bool = False, with_userinfo: bool = False): ... + def to_text(self, full_quote: bool = False): ... + def __unicode__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + +def parse_host(host): ... +def parse_url(url_text): ... + +DEFAULT_PARSED_URL: Incomplete + +def parse_qsl(qs, keep_blank_values: bool = True, encoding="utf8"): ... + +PREV: Incomplete +NEXT: Incomplete +KEY: Incomplete +VALUE: Incomplete +SPREV: Incomplete +SNEXT: Incomplete + +OMD = OrderedMultiDict + +class QueryParamDict(OrderedMultiDict[Incomplete, Incomplete]): + @classmethod + def from_text(cls, query_string): ... + def to_text(self, full_quote: bool = False): ... diff --git a/stubs/boto/@tests/stubtest_allowlist.txt b/stubs/boto/@tests/stubtest_allowlist.txt deleted file mode 100644 index e5fa8bd1ddbd..000000000000 --- a/stubs/boto/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,9 +0,0 @@ -boto.connection.AWSQueryConnection.make_request -boto.elb -boto.kms.layer1.KMSConnection.make_request -boto.s3.S3RegionInfo.connect -boto.s3.bucket.Bucket.get_location -boto.s3.bucket.Bucket.get_tags -boto.s3.bucket.Bucket.get_xml_tags -boto.s3.connection.S3Connection.make_request -boto.utils.LazyLoadMetadata.get diff --git a/stubs/boto/METADATA.toml b/stubs/boto/METADATA.toml deleted file mode 100644 index aff1a5fd3b7e..000000000000 --- a/stubs/boto/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -version = "2.49.*" -python2 = true -requires = ["types-six"] diff --git a/stubs/boto/boto/__init__.pyi b/stubs/boto/boto/__init__.pyi deleted file mode 100644 index 775be7c5372d..000000000000 --- a/stubs/boto/boto/__init__.pyi +++ /dev/null @@ -1,105 +0,0 @@ -import logging -from typing import Any, Text - -from .s3.connection import S3Connection - -Version: Any -UserAgent: Any -config: Any -BUCKET_NAME_RE: Any -TOO_LONG_DNS_NAME_COMP: Any -GENERATION_RE: Any -VERSION_RE: Any -ENDPOINTS_PATH: Any - -def init_logging(): ... - -class NullHandler(logging.Handler): - def emit(self, record): ... - -log: Any -perflog: Any - -def set_file_logger(name, filepath, level: Any = ..., format_string: Any | None = ...): ... -def set_stream_logger(name, level: Any = ..., format_string: Any | None = ...): ... -def connect_sqs(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_s3(aws_access_key_id: Text | None = ..., aws_secret_access_key: Text | None = ..., **kwargs) -> S3Connection: ... -def connect_gs(gs_access_key_id: Any | None = ..., gs_secret_access_key: Any | None = ..., **kwargs): ... -def connect_ec2(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_elb(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_autoscale(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudwatch(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_sdb(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_fps(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_mturk(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudfront(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_vpc(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_rds(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_rds2(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_emr(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_sns(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_iam(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_route53(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudformation(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_euca( - host: Any | None = ..., - aws_access_key_id: Any | None = ..., - aws_secret_access_key: Any | None = ..., - port: int = ..., - path: str = ..., - is_secure: bool = ..., - **kwargs, -): ... -def connect_glacier(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_ec2_endpoint(url, aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_walrus( - host: Any | None = ..., - aws_access_key_id: Any | None = ..., - aws_secret_access_key: Any | None = ..., - port: int = ..., - path: str = ..., - is_secure: bool = ..., - **kwargs, -): ... -def connect_ses(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_sts(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_ia(ia_access_key_id: Any | None = ..., ia_secret_access_key: Any | None = ..., is_secure: bool = ..., **kwargs): ... -def connect_dynamodb(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_swf(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudsearch(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudsearch2( - aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., sign_request: bool = ..., **kwargs -): ... -def connect_cloudsearchdomain(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_beanstalk(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_elastictranscoder(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_opsworks(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_redshift(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_support(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudtrail(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_directconnect(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_kinesis(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_logs(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_route53domains(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cognito_identity(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cognito_sync(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_kms(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_awslambda(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_codedeploy(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_configservice(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_cloudhsm(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_ec2containerservice(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def connect_machinelearning(aws_access_key_id: Any | None = ..., aws_secret_access_key: Any | None = ..., **kwargs): ... -def storage_uri( - uri_str, - default_scheme: str = ..., - debug: int = ..., - validate: bool = ..., - bucket_storage_uri_class: Any = ..., - suppress_consec_slashes: bool = ..., - is_latest: bool = ..., -): ... -def storage_uri_for_key(key): ... - -# Explicitly mark this package as incomplete. -def __getattr__(name: str) -> Any: ... diff --git a/stubs/boto/boto/auth.pyi b/stubs/boto/boto/auth.pyi deleted file mode 100644 index 2dc77949c110..000000000000 --- a/stubs/boto/boto/auth.pyi +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any - -from boto.auth_handler import AuthHandler - -SIGV4_DETECT: Any - -class HmacKeys: - host: Any - def __init__(self, host, config, provider) -> None: ... - def update_provider(self, provider): ... - def algorithm(self): ... - def sign_string(self, string_to_sign): ... - -class AnonAuthHandler(AuthHandler, HmacKeys): - capability: Any - def __init__(self, host, config, provider) -> None: ... - def add_auth(self, http_request, **kwargs): ... - -class HmacAuthV1Handler(AuthHandler, HmacKeys): - capability: Any - def __init__(self, host, config, provider) -> None: ... - def update_provider(self, provider): ... - def add_auth(self, http_request, **kwargs): ... - -class HmacAuthV2Handler(AuthHandler, HmacKeys): - capability: Any - def __init__(self, host, config, provider) -> None: ... - def update_provider(self, provider): ... - def add_auth(self, http_request, **kwargs): ... - -class HmacAuthV3Handler(AuthHandler, HmacKeys): - capability: Any - def __init__(self, host, config, provider) -> None: ... - def add_auth(self, http_request, **kwargs): ... - -class HmacAuthV3HTTPHandler(AuthHandler, HmacKeys): - capability: Any - def __init__(self, host, config, provider) -> None: ... - def headers_to_sign(self, http_request): ... - def canonical_headers(self, headers_to_sign): ... - def string_to_sign(self, http_request): ... - def add_auth(self, req, **kwargs): ... - -class HmacAuthV4Handler(AuthHandler, HmacKeys): - capability: Any - service_name: Any - region_name: Any - def __init__(self, host, config, provider, service_name: Any | None = ..., region_name: Any | None = ...) -> None: ... - def headers_to_sign(self, http_request): ... - def host_header(self, host, http_request): ... - def query_string(self, http_request): ... - def canonical_query_string(self, http_request): ... - def canonical_headers(self, headers_to_sign): ... - def signed_headers(self, headers_to_sign): ... - def canonical_uri(self, http_request): ... - def payload(self, http_request): ... - def canonical_request(self, http_request): ... - def scope(self, http_request): ... - def split_host_parts(self, host): ... - def determine_region_name(self, host): ... - def determine_service_name(self, host): ... - def credential_scope(self, http_request): ... - def string_to_sign(self, http_request, canonical_request): ... - def signature(self, http_request, string_to_sign): ... - def add_auth(self, req, **kwargs): ... - -class S3HmacAuthV4Handler(HmacAuthV4Handler, AuthHandler): - capability: Any - region_name: Any - def __init__(self, *args, **kwargs) -> None: ... - def clean_region_name(self, region_name): ... - def canonical_uri(self, http_request): ... - def canonical_query_string(self, http_request): ... - def host_header(self, host, http_request): ... - def headers_to_sign(self, http_request): ... - def determine_region_name(self, host): ... - def determine_service_name(self, host): ... - def mangle_path_and_params(self, req): ... - def payload(self, http_request): ... - def add_auth(self, req, **kwargs): ... - def presign(self, req, expires, iso_date: Any | None = ...): ... - -class STSAnonHandler(AuthHandler): - capability: Any - def add_auth(self, http_request, **kwargs): ... - -class QuerySignatureHelper(HmacKeys): - def add_auth(self, http_request, **kwargs): ... - -class QuerySignatureV0AuthHandler(QuerySignatureHelper, AuthHandler): - SignatureVersion: int - capability: Any - -class QuerySignatureV1AuthHandler(QuerySignatureHelper, AuthHandler): - SignatureVersion: int - capability: Any - def __init__(self, *args, **kw) -> None: ... - -class QuerySignatureV2AuthHandler(QuerySignatureHelper, AuthHandler): - SignatureVersion: int - capability: Any - -class POSTPathQSV2AuthHandler(QuerySignatureV2AuthHandler, AuthHandler): - capability: Any - def add_auth(self, req, **kwargs): ... - -def get_auth_handler(host, config, provider, requested_capability: Any | None = ...): ... -def detect_potential_sigv4(func): ... -def detect_potential_s3sigv4(func): ... diff --git a/stubs/boto/boto/auth_handler.pyi b/stubs/boto/boto/auth_handler.pyi deleted file mode 100644 index 7cc874bc8d79..000000000000 --- a/stubs/boto/boto/auth_handler.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from boto.plugin import Plugin - -class NotReadyToAuthenticate(Exception): ... - -class AuthHandler(Plugin): - capability: Any - def __init__(self, host, config, provider) -> None: ... - def add_auth(self, http_request): ... diff --git a/stubs/boto/boto/compat.pyi b/stubs/boto/boto/compat.pyi deleted file mode 100644 index f9e10d658f18..000000000000 --- a/stubs/boto/boto/compat.pyi +++ /dev/null @@ -1,20 +0,0 @@ -import sys -from typing import Any - -if sys.version_info >= (3,): - from base64 import encodebytes as encodebytes -else: - from base64 import encodestring - - encodebytes = encodestring - -expanduser: Any - -if sys.version_info >= (3, 0): - StandardError = Exception -else: - from __builtin__ import StandardError as StandardError - -long_type: Any -unquote_str: Any -parse_qs_safe: Any diff --git a/stubs/boto/boto/connection.pyi b/stubs/boto/boto/connection.pyi deleted file mode 100644 index c47f7414fba3..000000000000 --- a/stubs/boto/boto/connection.pyi +++ /dev/null @@ -1,174 +0,0 @@ -from typing import Any - -from six.moves import http_client - -HAVE_HTTPS_CONNECTION: bool -ON_APP_ENGINE: Any -PORTS_BY_SECURITY: Any -DEFAULT_CA_CERTS_FILE: Any - -class HostConnectionPool: - queue: Any - def __init__(self) -> None: ... - def size(self): ... - def put(self, conn): ... - def get(self): ... - def clean(self): ... - -class ConnectionPool: - CLEAN_INTERVAL: float - STALE_DURATION: float - host_to_pool: Any - last_clean_time: float - mutex: Any - def __init__(self) -> None: ... - def size(self): ... - def get_http_connection(self, host, port, is_secure): ... - def put_http_connection(self, host, port, is_secure, conn): ... - def clean(self): ... - -class HTTPRequest: - method: Any - protocol: Any - host: Any - port: Any - path: Any - auth_path: Any - params: Any - headers: Any - body: Any - def __init__(self, method, protocol, host, port, path, auth_path, params, headers, body) -> None: ... - def authorize(self, connection, **kwargs): ... - -class HTTPResponse(http_client.HTTPResponse): - def __init__(self, *args, **kwargs) -> None: ... - def read(self, amt: Any | None = ...): ... - -class AWSAuthConnection: - suppress_consec_slashes: Any - num_retries: int - is_secure: Any - https_validate_certificates: Any - ca_certificates_file: Any - port: Any - http_exceptions: Any - http_unretryable_exceptions: Any - socket_exception_values: Any - https_connection_factory: Any - protocol: str - host: Any - path: Any - debug: Any - host_header: Any - http_connection_kwargs: Any - provider: Any - auth_service_name: Any - request_hook: Any - def __init__( - self, - host, - aws_access_key_id: Any | None = ..., - aws_secret_access_key: Any | None = ..., - is_secure: bool = ..., - port: Any | None = ..., - proxy: Any | None = ..., - proxy_port: Any | None = ..., - proxy_user: Any | None = ..., - proxy_pass: Any | None = ..., - debug: int = ..., - https_connection_factory: Any | None = ..., - path: str = ..., - provider: str = ..., - security_token: Any | None = ..., - suppress_consec_slashes: bool = ..., - validate_certs: bool = ..., - profile_name: Any | None = ..., - ) -> None: ... - auth_region_name: Any - @property - def connection(self): ... - @property - def aws_access_key_id(self): ... - @property - def gs_access_key_id(self) -> Any: ... - access_key: Any - @property - def aws_secret_access_key(self): ... - @property - def gs_secret_access_key(self): ... - secret_key: Any - @property - def profile_name(self): ... - def get_path(self, path: str = ...): ... - def server_name(self, port: Any | None = ...): ... - proxy: Any - proxy_port: Any - proxy_user: Any - proxy_pass: Any - no_proxy: Any - use_proxy: Any - def handle_proxy(self, proxy, proxy_port, proxy_user, proxy_pass): ... - def get_http_connection(self, host, port, is_secure): ... - def skip_proxy(self, host): ... - def new_http_connection(self, host, port, is_secure): ... - def put_http_connection(self, host, port, is_secure, connection): ... - def proxy_ssl(self, host: Any | None = ..., port: Any | None = ...): ... - def prefix_proxy_to_path(self, path, host: Any | None = ...): ... - def get_proxy_auth_header(self): ... - def get_proxy_url_with_auth(self): ... - def set_host_header(self, request): ... - def set_request_hook(self, hook): ... - def build_base_http_request( - self, - method, - path, - auth_path, - params: Any | None = ..., - headers: Any | None = ..., - data: str = ..., - host: Any | None = ..., - ): ... - def make_request( - self, - method, - path, - headers: Any | None = ..., - data: str = ..., - host: Any | None = ..., - auth_path: Any | None = ..., - sender: Any | None = ..., - override_num_retries: Any | None = ..., - params: Any | None = ..., - retry_handler: Any | None = ..., - ): ... - def close(self): ... - -class AWSQueryConnection(AWSAuthConnection): - APIVersion: str - ResponseError: Any - def __init__( - self, - aws_access_key_id: Any | None = ..., - aws_secret_access_key: Any | None = ..., - is_secure: bool = ..., - port: Any | None = ..., - proxy: Any | None = ..., - proxy_port: Any | None = ..., - proxy_user: Any | None = ..., - proxy_pass: Any | None = ..., - host: Any | None = ..., - debug: int = ..., - https_connection_factory: Any | None = ..., - path: str = ..., - security_token: Any | None = ..., - validate_certs: bool = ..., - profile_name: Any | None = ..., - provider: str = ..., - ) -> None: ... - def get_utf8_value(self, value): ... - def make_request(self, action, params: Any | None = ..., path: str = ..., verb: str = ..., *args, **kwargs): ... # type: ignore # https://github.com/python/mypy/issues/1237 - def build_list_params(self, params, items, label): ... - def build_complex_list_params(self, params, items, label, names): ... - def get_list(self, action, params, markers, path: str = ..., parent: Any | None = ..., verb: str = ...): ... - def get_object(self, action, params, cls, path: str = ..., parent: Any | None = ..., verb: str = ...): ... - def get_status(self, action, params, path: str = ..., parent: Any | None = ..., verb: str = ...): ... diff --git a/stubs/boto/boto/ec2/__init__.pyi b/stubs/boto/boto/ec2/__init__.pyi deleted file mode 100644 index d44f942d0a2e..000000000000 --- a/stubs/boto/boto/ec2/__init__.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -RegionData: Any - -def regions(**kw_params): ... -def connect_to_region(region_name, **kw_params): ... -def get_region(region_name, **kw_params): ... - -# Explicitly mark this package as incomplete. -def __getattr__(name: str) -> Any: ... diff --git a/stubs/boto/boto/elb/__init__.pyi b/stubs/boto/boto/elb/__init__.pyi deleted file mode 100644 index d2a79d5f0b46..000000000000 --- a/stubs/boto/boto/elb/__init__.pyi +++ /dev/null @@ -1,59 +0,0 @@ -from typing import Any - -from boto.connection import AWSQueryConnection - -RegionData: Any - -def regions(): ... -def connect_to_region(region_name, **kw_params): ... - -class ELBConnection(AWSQueryConnection): - APIVersion: Any - DefaultRegionName: Any - DefaultRegionEndpoint: Any - region: Any - def __init__( - self, - aws_access_key_id=..., - aws_secret_access_key=..., - is_secure=..., - port=..., - proxy=..., - proxy_port=..., - proxy_user=..., - proxy_pass=..., - debug=..., - https_connection_factory=..., - region=..., - path=..., - security_token=..., - validate_certs=..., - profile_name=..., - ) -> None: ... - def build_list_params(self, params, items, label): ... - def get_all_load_balancers(self, load_balancer_names=..., marker=...): ... - def create_load_balancer( - self, name, zones, listeners=..., subnets=..., security_groups=..., scheme=..., complex_listeners=... - ): ... - def create_load_balancer_listeners(self, name, listeners=..., complex_listeners=...): ... - def delete_load_balancer(self, name): ... - def delete_load_balancer_listeners(self, name, ports): ... - def enable_availability_zones(self, load_balancer_name, zones_to_add): ... - def disable_availability_zones(self, load_balancer_name, zones_to_remove): ... - def modify_lb_attribute(self, load_balancer_name, attribute, value): ... - def get_all_lb_attributes(self, load_balancer_name): ... - def get_lb_attribute(self, load_balancer_name, attribute): ... - def register_instances(self, load_balancer_name, instances): ... - def deregister_instances(self, load_balancer_name, instances): ... - def describe_instance_health(self, load_balancer_name, instances=...): ... - def configure_health_check(self, name, health_check): ... - def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): ... - def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): ... - def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): ... - def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): ... - def delete_lb_policy(self, lb_name, policy_name): ... - def set_lb_policies_of_listener(self, lb_name, lb_port, policies): ... - def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): ... - def apply_security_groups_to_lb(self, name, security_groups): ... - def attach_lb_to_subnets(self, name, subnets): ... - def detach_lb_from_subnets(self, name, subnets): ... diff --git a/stubs/boto/boto/exception.pyi b/stubs/boto/boto/exception.pyi deleted file mode 100644 index 95ebed39378b..000000000000 --- a/stubs/boto/boto/exception.pyi +++ /dev/null @@ -1,147 +0,0 @@ -from typing import Any - -from boto.compat import StandardError - -class BotoClientError(StandardError): - reason: Any - def __init__(self, reason, *args) -> None: ... - -class SDBPersistenceError(StandardError): ... -class StoragePermissionsError(BotoClientError): ... -class S3PermissionsError(StoragePermissionsError): ... -class GSPermissionsError(StoragePermissionsError): ... - -class BotoServerError(StandardError): - status: Any - reason: Any - body: Any - request_id: Any - error_code: Any - message: str - box_usage: Any - def __init__(self, status, reason, body: Any | None = ..., *args) -> None: ... - def __getattr__(self, name): ... - def __setattr__(self, name, value): ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class ConsoleOutput: - parent: Any - instance_id: Any - timestamp: Any - comment: Any - output: Any - def __init__(self, parent: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class StorageCreateError(BotoServerError): - bucket: Any - def __init__(self, status, reason, body: Any | None = ...) -> None: ... - def endElement(self, name, value, connection): ... - -class S3CreateError(StorageCreateError): ... -class GSCreateError(StorageCreateError): ... -class StorageCopyError(BotoServerError): ... -class S3CopyError(StorageCopyError): ... -class GSCopyError(StorageCopyError): ... - -class SQSError(BotoServerError): - detail: Any - type: Any - def __init__(self, status, reason, body: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class SQSDecodeError(BotoClientError): - message: Any - def __init__(self, reason, message) -> None: ... - -class StorageResponseError(BotoServerError): - resource: Any - def __init__(self, status, reason, body: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class S3ResponseError(StorageResponseError): ... -class GSResponseError(StorageResponseError): ... - -class EC2ResponseError(BotoServerError): - errors: Any - def __init__(self, status, reason, body: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - request_id: Any - def endElement(self, name, value, connection): ... - -class JSONResponseError(BotoServerError): - status: Any - reason: Any - body: Any - error_message: Any - error_code: Any - def __init__(self, status, reason, body: Any | None = ..., *args) -> None: ... - -class DynamoDBResponseError(JSONResponseError): ... -class SWFResponseError(JSONResponseError): ... -class EmrResponseError(BotoServerError): ... - -class _EC2Error: - connection: Any - error_code: Any - error_message: Any - def __init__(self, connection: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class SDBResponseError(BotoServerError): ... -class AWSConnectionError(BotoClientError): ... -class StorageDataError(BotoClientError): ... -class S3DataError(StorageDataError): ... -class GSDataError(StorageDataError): ... - -class InvalidUriError(Exception): - message: Any - def __init__(self, message) -> None: ... - -class InvalidAclError(Exception): - message: Any - def __init__(self, message) -> None: ... - -class InvalidCorsError(Exception): - message: Any - def __init__(self, message) -> None: ... - -class NoAuthHandlerFound(Exception): ... - -class InvalidLifecycleConfigError(Exception): - message: Any - def __init__(self, message) -> None: ... - -class ResumableTransferDisposition: - START_OVER: str - WAIT_BEFORE_RETRY: str - ABORT_CUR_PROCESS: str - ABORT: str - -class ResumableUploadException(Exception): - message: Any - disposition: Any - def __init__(self, message, disposition) -> None: ... - -class ResumableDownloadException(Exception): - message: Any - disposition: Any - def __init__(self, message, disposition) -> None: ... - -class TooManyRecordsException(Exception): - message: Any - def __init__(self, message) -> None: ... - -class PleaseRetryException(Exception): - message: Any - response: Any - def __init__(self, message, response: Any | None = ...) -> None: ... - -class InvalidInstanceMetadataError(Exception): - MSG: str - def __init__(self, msg) -> None: ... diff --git a/stubs/boto/boto/kms/__init__.pyi b/stubs/boto/boto/kms/__init__.pyi deleted file mode 100644 index 9fc301120e0e..000000000000 --- a/stubs/boto/boto/kms/__init__.pyi +++ /dev/null @@ -1,4 +0,0 @@ -import boto.regioninfo - -def regions() -> list[boto.regioninfo.RegionInfo]: ... -def connect_to_region(region_name, **kw_params): ... diff --git a/stubs/boto/boto/kms/exceptions.pyi b/stubs/boto/boto/kms/exceptions.pyi deleted file mode 100644 index 5ac2ecd2061f..000000000000 --- a/stubs/boto/boto/kms/exceptions.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from boto.exception import BotoServerError - -class InvalidGrantTokenException(BotoServerError): ... -class DisabledException(BotoServerError): ... -class LimitExceededException(BotoServerError): ... -class DependencyTimeoutException(BotoServerError): ... -class InvalidMarkerException(BotoServerError): ... -class AlreadyExistsException(BotoServerError): ... -class InvalidCiphertextException(BotoServerError): ... -class KeyUnavailableException(BotoServerError): ... -class InvalidAliasNameException(BotoServerError): ... -class UnsupportedOperationException(BotoServerError): ... -class InvalidArnException(BotoServerError): ... -class KMSInternalException(BotoServerError): ... -class InvalidKeyUsageException(BotoServerError): ... -class MalformedPolicyDocumentException(BotoServerError): ... -class NotFoundException(BotoServerError): ... diff --git a/stubs/boto/boto/kms/layer1.pyi b/stubs/boto/boto/kms/layer1.pyi deleted file mode 100644 index e2755233678d..000000000000 --- a/stubs/boto/boto/kms/layer1.pyi +++ /dev/null @@ -1,77 +0,0 @@ -from typing import Any, Mapping, Type - -from boto.connection import AWSQueryConnection - -class KMSConnection(AWSQueryConnection): - APIVersion: str - DefaultRegionName: str - DefaultRegionEndpoint: str - ServiceName: str - TargetPrefix: str - ResponseError: Type[Exception] - region: Any - def __init__(self, **kwargs) -> None: ... - def create_alias(self, alias_name: str, target_key_id: str) -> dict[str, Any] | None: ... - def create_grant( - self, - key_id: str, - grantee_principal: str, - retiring_principal: str | None = ..., - operations: list[str] | None = ..., - constraints: dict[str, dict[str, str]] | None = ..., - grant_tokens: list[str] | None = ..., - ) -> dict[str, Any] | None: ... - def create_key( - self, policy: str | None = ..., description: str | None = ..., key_usage: str | None = ... - ) -> dict[str, Any] | None: ... - def decrypt( - self, ciphertext_blob: bytes, encryption_context: Mapping[str, Any] | None = ..., grant_tokens: list[str] | None = ... - ) -> dict[str, Any] | None: ... - def delete_alias(self, alias_name: str) -> dict[str, Any] | None: ... - def describe_key(self, key_id: str) -> dict[str, Any] | None: ... - def disable_key(self, key_id: str) -> dict[str, Any] | None: ... - def disable_key_rotation(self, key_id: str) -> dict[str, Any] | None: ... - def enable_key(self, key_id: str) -> dict[str, Any] | None: ... - def enable_key_rotation(self, key_id: str) -> dict[str, Any] | None: ... - def encrypt( - self, - key_id: str, - plaintext: bytes, - encryption_context: Mapping[str, Any] | None = ..., - grant_tokens: list[str] | None = ..., - ) -> dict[str, Any] | None: ... - def generate_data_key( - self, - key_id: str, - encryption_context: Mapping[str, Any] | None = ..., - number_of_bytes: int | None = ..., - key_spec: str | None = ..., - grant_tokens: list[str] | None = ..., - ) -> dict[str, Any] | None: ... - def generate_data_key_without_plaintext( - self, - key_id: str, - encryption_context: Mapping[str, Any] | None = ..., - key_spec: str | None = ..., - number_of_bytes: int | None = ..., - grant_tokens: list[str] | None = ..., - ) -> dict[str, Any] | None: ... - def generate_random(self, number_of_bytes: int | None = ...) -> dict[str, Any] | None: ... - def get_key_policy(self, key_id: str, policy_name: str) -> dict[str, Any] | None: ... - def get_key_rotation_status(self, key_id: str) -> dict[str, Any] | None: ... - def list_aliases(self, limit: int | None = ..., marker: str | None = ...) -> dict[str, Any] | None: ... - def list_grants(self, key_id: str, limit: int | None = ..., marker: str | None = ...) -> dict[str, Any] | None: ... - def list_key_policies(self, key_id: str, limit: int | None = ..., marker: str | None = ...) -> dict[str, Any] | None: ... - def list_keys(self, limit: int | None = ..., marker: str | None = ...) -> dict[str, Any] | None: ... - def put_key_policy(self, key_id: str, policy_name: str, policy: str) -> dict[str, Any] | None: ... - def re_encrypt( - self, - ciphertext_blob: bytes, - destination_key_id: str, - source_encryption_context: Mapping[str, Any] | None = ..., - destination_encryption_context: Mapping[str, Any] | None = ..., - grant_tokens: list[str] | None = ..., - ) -> dict[str, Any] | None: ... - def retire_grant(self, grant_token: str) -> dict[str, Any] | None: ... - def revoke_grant(self, key_id: str, grant_id: str) -> dict[str, Any] | None: ... - def update_key_description(self, key_id: str, description: str) -> dict[str, Any] | None: ... diff --git a/stubs/boto/boto/plugin.pyi b/stubs/boto/boto/plugin.pyi deleted file mode 100644 index 7e9ec2dc6852..000000000000 --- a/stubs/boto/boto/plugin.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -class Plugin: - capability: Any - @classmethod - def is_capable(cls, requested_capability): ... - -def get_plugin(cls, requested_capability: Any | None = ...): ... -def load_plugins(config): ... diff --git a/stubs/boto/boto/regioninfo.pyi b/stubs/boto/boto/regioninfo.pyi deleted file mode 100644 index b8cb71e2c252..000000000000 --- a/stubs/boto/boto/regioninfo.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any - -def load_endpoint_json(path): ... -def merge_endpoints(defaults, additions): ... -def load_regions(): ... -def get_regions(service_name, region_cls: Any | None = ..., connection_cls: Any | None = ...): ... - -class RegionInfo: - connection: Any - name: Any - endpoint: Any - connection_cls: Any - def __init__( - self, connection: Any | None = ..., name: Any | None = ..., endpoint: Any | None = ..., connection_cls: Any | None = ... - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def connect(self, **kw_params): ... diff --git a/stubs/boto/boto/s3/__init__.pyi b/stubs/boto/boto/s3/__init__.pyi deleted file mode 100644 index fa747956ebbe..000000000000 --- a/stubs/boto/boto/s3/__init__.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Text, Type - -from boto.connection import AWSAuthConnection -from boto.regioninfo import RegionInfo - -from .connection import S3Connection - -class S3RegionInfo(RegionInfo): - def connect( - self, - name: Text | None = ..., - endpoint: str | None = ..., - connection_cls: Type[AWSAuthConnection] | None = ..., - **kw_params, - ) -> S3Connection: ... - -def regions() -> list[S3RegionInfo]: ... -def connect_to_region(region_name: Text, **kw_params): ... diff --git a/stubs/boto/boto/s3/acl.pyi b/stubs/boto/boto/s3/acl.pyi deleted file mode 100644 index 55966a1fb1aa..000000000000 --- a/stubs/boto/boto/s3/acl.pyi +++ /dev/null @@ -1,48 +0,0 @@ -from typing import Any, Text - -from .connection import S3Connection -from .user import User - -CannedACLStrings: list[str] - -class Policy: - parent: Any - namespace: Any - acl: ACL - def __init__(self, parent: Any | None = ...) -> None: ... - owner: User - def startElement(self, name: Text, attrs: dict[str, Any], connection: S3Connection) -> None | User | ACL: ... - def endElement(self, name: Text, value: Any, connection: S3Connection) -> None: ... - def to_xml(self) -> str: ... - -class ACL: - policy: Policy - grants: list[Grant] - def __init__(self, policy: Policy | None = ...) -> None: ... - def add_grant(self, grant: Grant) -> None: ... - def add_email_grant(self, permission: Text, email_address: Text) -> None: ... - def add_user_grant(self, permission: Text, user_id: Text, display_name: Text | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name: Text, value: Any, connection: S3Connection) -> None: ... - def to_xml(self) -> str: ... - -class Grant: - NameSpace: Text - permission: Text - id: Text - display_name: Text - uri: Text - email_address: Text - type: Text - def __init__( - self, - permission: Text | None = ..., - type: Text | None = ..., - id: Text | None = ..., - display_name: Text | None = ..., - uri: Text | None = ..., - email_address: Text | None = ..., - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name: Text, value: Any, connection: S3Connection) -> None: ... - def to_xml(self) -> str: ... diff --git a/stubs/boto/boto/s3/bucket.pyi b/stubs/boto/boto/s3/bucket.pyi deleted file mode 100644 index 741772ff3817..000000000000 --- a/stubs/boto/boto/s3/bucket.pyi +++ /dev/null @@ -1,178 +0,0 @@ -from typing import Any, Text, Type - -from .bucketlistresultset import BucketListResultSet -from .connection import S3Connection -from .key import Key - -class S3WebsiteEndpointTranslate: - trans_region: dict[str, str] - @classmethod - def translate_region(cls, reg: Text) -> str: ... - -S3Permissions: list[str] - -class Bucket: - LoggingGroup: str - BucketPaymentBody: str - VersioningBody: str - VersionRE: str - MFADeleteRE: str - name: Text - connection: S3Connection - key_class: Type[Key] - def __init__(self, connection: S3Connection | None = ..., name: Text | None = ..., key_class: Type[Key] = ...) -> None: ... - def __iter__(self): ... - def __contains__(self, key_name) -> bool: ... - def startElement(self, name, attrs, connection): ... - creation_date: Any - def endElement(self, name, value, connection): ... - def set_key_class(self, key_class): ... - def lookup(self, key_name, headers: dict[Text, Text] | None = ...): ... - def get_key( - self, - key_name, - headers: dict[Text, Text] | None = ..., - version_id: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - validate: bool = ..., - ) -> Key: ... - def list( - self, - prefix: Text = ..., - delimiter: Text = ..., - marker: Text = ..., - headers: dict[Text, Text] | None = ..., - encoding_type: Any | None = ..., - ) -> BucketListResultSet: ... - def list_versions( - self, - prefix: str = ..., - delimiter: str = ..., - key_marker: str = ..., - version_id_marker: str = ..., - headers: dict[Text, Text] | None = ..., - encoding_type: Text | None = ..., - ) -> BucketListResultSet: ... - def list_multipart_uploads( - self, - key_marker: str = ..., - upload_id_marker: str = ..., - headers: dict[Text, Text] | None = ..., - encoding_type: Any | None = ..., - ): ... - def validate_kwarg_names(self, kwargs, names): ... - def get_all_keys(self, headers: dict[Text, Text] | None = ..., **params): ... - def get_all_versions(self, headers: dict[Text, Text] | None = ..., **params): ... - def validate_get_all_versions_params(self, params): ... - def get_all_multipart_uploads(self, headers: dict[Text, Text] | None = ..., **params): ... - def new_key(self, key_name: Any | None = ...): ... - def generate_url( - self, - expires_in, - method: str = ..., - headers: dict[Text, Text] | None = ..., - force_http: bool = ..., - response_headers: dict[Text, Text] | None = ..., - expires_in_absolute: bool = ..., - ): ... - def delete_keys(self, keys, quiet: bool = ..., mfa_token: Any | None = ..., headers: dict[Text, Text] | None = ...): ... - def delete_key( - self, key_name, headers: dict[Text, Text] | None = ..., version_id: Any | None = ..., mfa_token: Any | None = ... - ): ... - def copy_key( - self, - new_key_name, - src_bucket_name, - src_key_name, - metadata: Any | None = ..., - src_version_id: Any | None = ..., - storage_class: str = ..., - preserve_acl: bool = ..., - encrypt_key: bool = ..., - headers: dict[Text, Text] | None = ..., - query_args: Any | None = ..., - ): ... - def set_canned_acl( - self, acl_str, key_name: str = ..., headers: dict[Text, Text] | None = ..., version_id: Any | None = ... - ): ... - def get_xml_acl(self, key_name: str = ..., headers: dict[Text, Text] | None = ..., version_id: Any | None = ...): ... - def set_xml_acl( - self, - acl_str, - key_name: str = ..., - headers: dict[Text, Text] | None = ..., - version_id: Any | None = ..., - query_args: str = ..., - ): ... - def set_acl(self, acl_or_str, key_name: str = ..., headers: dict[Text, Text] | None = ..., version_id: Any | None = ...): ... - def get_acl(self, key_name: str = ..., headers: dict[Text, Text] | None = ..., version_id: Any | None = ...): ... - def set_subresource( - self, subresource, value, key_name: str = ..., headers: dict[Text, Text] | None = ..., version_id: Any | None = ... - ): ... - def get_subresource( - self, subresource, key_name: str = ..., headers: dict[Text, Text] | None = ..., version_id: Any | None = ... - ): ... - def make_public(self, recursive: bool = ..., headers: dict[Text, Text] | None = ...): ... - def add_email_grant(self, permission, email_address, recursive: bool = ..., headers: dict[Text, Text] | None = ...): ... - def add_user_grant( - self, permission, user_id, recursive: bool = ..., headers: dict[Text, Text] | None = ..., display_name: Any | None = ... - ): ... - def list_grants(self, headers: dict[Text, Text] | None = ...): ... - def get_location(self): ... - def set_xml_logging(self, logging_str, headers: dict[Text, Text] | None = ...): ... - def enable_logging( - self, target_bucket, target_prefix: str = ..., grants: Any | None = ..., headers: dict[Text, Text] | None = ... - ): ... - def disable_logging(self, headers: dict[Text, Text] | None = ...): ... - def get_logging_status(self, headers: dict[Text, Text] | None = ...): ... - def set_as_logging_target(self, headers: dict[Text, Text] | None = ...): ... - def get_request_payment(self, headers: dict[Text, Text] | None = ...): ... - def set_request_payment(self, payer: str = ..., headers: dict[Text, Text] | None = ...): ... - def configure_versioning( - self, versioning, mfa_delete: bool = ..., mfa_token: Any | None = ..., headers: dict[Text, Text] | None = ... - ): ... - def get_versioning_status(self, headers: dict[Text, Text] | None = ...): ... - def configure_lifecycle(self, lifecycle_config, headers: dict[Text, Text] | None = ...): ... - def get_lifecycle_config(self, headers: dict[Text, Text] | None = ...): ... - def delete_lifecycle_configuration(self, headers: dict[Text, Text] | None = ...): ... - def configure_website( - self, - suffix: Any | None = ..., - error_key: Any | None = ..., - redirect_all_requests_to: Any | None = ..., - routing_rules: Any | None = ..., - headers: dict[Text, Text] | None = ..., - ): ... - def set_website_configuration(self, config, headers: dict[Text, Text] | None = ...): ... - def set_website_configuration_xml(self, xml, headers: dict[Text, Text] | None = ...): ... - def get_website_configuration(self, headers: dict[Text, Text] | None = ...): ... - def get_website_configuration_obj(self, headers: dict[Text, Text] | None = ...): ... - def get_website_configuration_with_xml(self, headers: dict[Text, Text] | None = ...): ... - def get_website_configuration_xml(self, headers: dict[Text, Text] | None = ...): ... - def delete_website_configuration(self, headers: dict[Text, Text] | None = ...): ... - def get_website_endpoint(self): ... - def get_policy(self, headers: dict[Text, Text] | None = ...): ... - def set_policy(self, policy, headers: dict[Text, Text] | None = ...): ... - def delete_policy(self, headers: dict[Text, Text] | None = ...): ... - def set_cors_xml(self, cors_xml, headers: dict[Text, Text] | None = ...): ... - def set_cors(self, cors_config, headers: dict[Text, Text] | None = ...): ... - def get_cors_xml(self, headers: dict[Text, Text] | None = ...): ... - def get_cors(self, headers: dict[Text, Text] | None = ...): ... - def delete_cors(self, headers: dict[Text, Text] | None = ...): ... - def initiate_multipart_upload( - self, - key_name, - headers: dict[Text, Text] | None = ..., - reduced_redundancy: bool = ..., - metadata: Any | None = ..., - encrypt_key: bool = ..., - policy: Any | None = ..., - ): ... - def complete_multipart_upload(self, key_name, upload_id, xml_body, headers: dict[Text, Text] | None = ...): ... - def cancel_multipart_upload(self, key_name, upload_id, headers: dict[Text, Text] | None = ...): ... - def delete(self, headers: dict[Text, Text] | None = ...): ... - def get_tags(self): ... - def get_xml_tags(self): ... - def set_xml_tags(self, tag_str, headers: dict[Text, Text] | None = ..., query_args: str = ...): ... - def set_tags(self, tags, headers: dict[Text, Text] | None = ...): ... - def delete_tags(self, headers: dict[Text, Text] | None = ...): ... diff --git a/stubs/boto/boto/s3/bucketlistresultset.pyi b/stubs/boto/boto/s3/bucketlistresultset.pyi deleted file mode 100644 index e327ac42404c..000000000000 --- a/stubs/boto/boto/s3/bucketlistresultset.pyi +++ /dev/null @@ -1,75 +0,0 @@ -from typing import Any, Iterable, Iterator - -from .key import Key - -def bucket_lister( - bucket, prefix: str = ..., delimiter: str = ..., marker: str = ..., headers: Any | None = ..., encoding_type: Any | None = ... -): ... - -class BucketListResultSet(Iterable[Key]): - bucket: Any - prefix: Any - delimiter: Any - marker: Any - headers: Any - encoding_type: Any - def __init__( - self, - bucket: Any | None = ..., - prefix: str = ..., - delimiter: str = ..., - marker: str = ..., - headers: Any | None = ..., - encoding_type: Any | None = ..., - ) -> None: ... - def __iter__(self) -> Iterator[Key]: ... - -def versioned_bucket_lister( - bucket, - prefix: str = ..., - delimiter: str = ..., - key_marker: str = ..., - version_id_marker: str = ..., - headers: Any | None = ..., - encoding_type: Any | None = ..., -): ... - -class VersionedBucketListResultSet: - bucket: Any - prefix: Any - delimiter: Any - key_marker: Any - version_id_marker: Any - headers: Any - encoding_type: Any - def __init__( - self, - bucket: Any | None = ..., - prefix: str = ..., - delimiter: str = ..., - key_marker: str = ..., - version_id_marker: str = ..., - headers: Any | None = ..., - encoding_type: Any | None = ..., - ) -> None: ... - def __iter__(self) -> Iterator[Key]: ... - -def multipart_upload_lister( - bucket, key_marker: str = ..., upload_id_marker: str = ..., headers: Any | None = ..., encoding_type: Any | None = ... -): ... - -class MultiPartUploadListResultSet: - bucket: Any - key_marker: Any - upload_id_marker: Any - headers: Any - encoding_type: Any - def __init__( - self, - bucket: Any | None = ..., - key_marker: str = ..., - upload_id_marker: str = ..., - headers: Any | None = ..., - encoding_type: Any | None = ..., - ) -> None: ... - def __iter__(self): ... diff --git a/stubs/boto/boto/s3/bucketlogging.pyi b/stubs/boto/boto/s3/bucketlogging.pyi deleted file mode 100644 index f804d172cafa..000000000000 --- a/stubs/boto/boto/s3/bucketlogging.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class BucketLogging: - target: Any - prefix: Any - grants: Any - def __init__(self, target: Any | None = ..., prefix: Any | None = ..., grants: Any | None = ...) -> None: ... - def add_grant(self, grant): ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... diff --git a/stubs/boto/boto/s3/connection.pyi b/stubs/boto/boto/s3/connection.pyi deleted file mode 100644 index 96b8d0de134c..000000000000 --- a/stubs/boto/boto/s3/connection.pyi +++ /dev/null @@ -1,128 +0,0 @@ -from typing import Any, Text, Type - -from boto.connection import AWSAuthConnection -from boto.exception import BotoClientError - -from .bucket import Bucket - -def check_lowercase_bucketname(n): ... -def assert_case_insensitive(f): ... - -class _CallingFormat: - def get_bucket_server(self, server, bucket): ... - def build_url_base(self, connection, protocol, server, bucket, key: str = ...): ... - def build_host(self, server, bucket): ... - def build_auth_path(self, bucket, key: str = ...): ... - def build_path_base(self, bucket, key: str = ...): ... - -class SubdomainCallingFormat(_CallingFormat): - def get_bucket_server(self, server, bucket): ... - -class VHostCallingFormat(_CallingFormat): - def get_bucket_server(self, server, bucket): ... - -class OrdinaryCallingFormat(_CallingFormat): - def get_bucket_server(self, server, bucket): ... - def build_path_base(self, bucket, key: str = ...): ... - -class ProtocolIndependentOrdinaryCallingFormat(OrdinaryCallingFormat): - def build_url_base(self, connection, protocol, server, bucket, key: str = ...): ... - -class Location: - DEFAULT: str - EU: str - EUCentral1: str - USWest: str - USWest2: str - SAEast: str - APNortheast: str - APSoutheast: str - APSoutheast2: str - CNNorth1: str - -class NoHostProvided: ... -class HostRequiredError(BotoClientError): ... - -class S3Connection(AWSAuthConnection): - DefaultHost: Any - DefaultCallingFormat: Any - QueryString: str - calling_format: Any - bucket_class: Type[Bucket] - anon: Any - def __init__( - self, - aws_access_key_id: Any | None = ..., - aws_secret_access_key: Any | None = ..., - is_secure: bool = ..., - port: Any | None = ..., - proxy: Any | None = ..., - proxy_port: Any | None = ..., - proxy_user: Any | None = ..., - proxy_pass: Any | None = ..., - host: Any = ..., - debug: int = ..., - https_connection_factory: Any | None = ..., - calling_format: Any = ..., - path: str = ..., - provider: str = ..., - bucket_class: Type[Bucket] = ..., - security_token: Any | None = ..., - suppress_consec_slashes: bool = ..., - anon: bool = ..., - validate_certs: Any | None = ..., - profile_name: Any | None = ..., - ) -> None: ... - def __iter__(self): ... - def __contains__(self, bucket_name): ... - def set_bucket_class(self, bucket_class: Type[Bucket]) -> None: ... - def build_post_policy(self, expiration_time, conditions): ... - def build_post_form_args( - self, - bucket_name, - key, - expires_in: int = ..., - acl: Any | None = ..., - success_action_redirect: Any | None = ..., - max_content_length: Any | None = ..., - http_method: str = ..., - fields: Any | None = ..., - conditions: Any | None = ..., - storage_class: str = ..., - server_side_encryption: Any | None = ..., - ): ... - def generate_url_sigv4( - self, - expires_in, - method, - bucket: str = ..., - key: str = ..., - headers: dict[Text, Text] | None = ..., - force_http: bool = ..., - response_headers: dict[Text, Text] | None = ..., - version_id: Any | None = ..., - iso_date: Any | None = ..., - ): ... - def generate_url( - self, - expires_in, - method, - bucket: str = ..., - key: str = ..., - headers: dict[Text, Text] | None = ..., - query_auth: bool = ..., - force_http: bool = ..., - response_headers: dict[Text, Text] | None = ..., - expires_in_absolute: bool = ..., - version_id: Any | None = ..., - ): ... - def get_all_buckets(self, headers: dict[Text, Text] | None = ...): ... - def get_canonical_user_id(self, headers: dict[Text, Text] | None = ...): ... - def get_bucket(self, bucket_name: Text, validate: bool = ..., headers: dict[Text, Text] | None = ...) -> Bucket: ... - def head_bucket(self, bucket_name, headers: dict[Text, Text] | None = ...): ... - def lookup(self, bucket_name, validate: bool = ..., headers: dict[Text, Text] | None = ...): ... - def create_bucket( - self, bucket_name, headers: dict[Text, Text] | None = ..., location: Any = ..., policy: Any | None = ... - ): ... - def delete_bucket(self, bucket, headers: dict[Text, Text] | None = ...): ... - def make_request(self, method, bucket: str = ..., key: str = ..., headers: Any | None = ..., data: str = ..., query_args: Any | None = ..., sender: Any | None = ..., override_num_retries: Any | None = ..., retry_handler: Any | None = ..., *args, **kwargs): ... # type: ignore # https://github.com/python/mypy/issues/1237 diff --git a/stubs/boto/boto/s3/cors.pyi b/stubs/boto/boto/s3/cors.pyi deleted file mode 100644 index f31e612f748d..000000000000 --- a/stubs/boto/boto/s3/cors.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any, List - -class CORSRule: - allowed_method: Any - allowed_origin: Any - id: Any - allowed_header: Any - max_age_seconds: Any - expose_header: Any - def __init__( - self, - allowed_method: Any | None = ..., - allowed_origin: Any | None = ..., - id: Any | None = ..., - allowed_header: Any | None = ..., - max_age_seconds: Any | None = ..., - expose_header: Any | None = ..., - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self) -> str: ... - -class CORSConfiguration(List[CORSRule]): - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self) -> str: ... - def add_rule( - self, - allowed_method, - allowed_origin, - id: Any | None = ..., - allowed_header: Any | None = ..., - max_age_seconds: Any | None = ..., - expose_header: Any | None = ..., - ): ... diff --git a/stubs/boto/boto/s3/deletemarker.pyi b/stubs/boto/boto/s3/deletemarker.pyi deleted file mode 100644 index 83f9b53c03bb..000000000000 --- a/stubs/boto/boto/s3/deletemarker.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -class DeleteMarker: - bucket: Any - name: Any - version_id: Any - is_latest: bool - last_modified: Any - owner: Any - def __init__(self, bucket: Any | None = ..., name: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... diff --git a/stubs/boto/boto/s3/key.pyi b/stubs/boto/boto/s3/key.pyi deleted file mode 100644 index 1a8b365a2604..000000000000 --- a/stubs/boto/boto/s3/key.pyi +++ /dev/null @@ -1,231 +0,0 @@ -from typing import Any, Callable, Text, overload - -class Key: - DefaultContentType: str - RestoreBody: str - BufferSize: Any - base_user_settable_fields: Any - base_fields: Any - bucket: Any - name: str - metadata: Any - cache_control: Any - content_type: Any - content_encoding: Any - content_disposition: Any - content_language: Any - filename: Any - etag: Any - is_latest: bool - last_modified: Any - owner: Any - path: Any - resp: Any - mode: Any - size: Any - version_id: Any - source_version_id: Any - delete_marker: bool - encrypted: Any - ongoing_restore: Any - expiry_date: Any - local_hashes: Any - def __init__(self, bucket: Any | None = ..., name: Any | None = ...) -> None: ... - def __iter__(self): ... - @property - def provider(self): ... - key: Any - md5: Any - base64md5: Any - storage_class: Any - def get_md5_from_hexdigest(self, md5_hexdigest): ... - def handle_encryption_headers(self, resp): ... - def handle_version_headers(self, resp, force: bool = ...): ... - def handle_restore_headers(self, response): ... - def handle_addl_headers(self, headers): ... - def open_read( - self, - headers: dict[Text, Text] | None = ..., - query_args: str = ..., - override_num_retries: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - ): ... - def open_write(self, headers: dict[Text, Text] | None = ..., override_num_retries: Any | None = ...): ... - def open( - self, - mode: str = ..., - headers: dict[Text, Text] | None = ..., - query_args: Any | None = ..., - override_num_retries: Any | None = ..., - ): ... - closed: bool - def close(self, fast: bool = ...): ... - def next(self): ... - __next__: Any - def read(self, size: int = ...): ... - def change_storage_class(self, new_storage_class, dst_bucket: Any | None = ..., validate_dst_bucket: bool = ...): ... - def copy( - self, - dst_bucket, - dst_key, - metadata: Any | None = ..., - reduced_redundancy: bool = ..., - preserve_acl: bool = ..., - encrypt_key: bool = ..., - validate_dst_bucket: bool = ..., - ): ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def exists(self, headers: dict[Text, Text] | None = ...): ... - def delete(self, headers: dict[Text, Text] | None = ...): ... - def get_metadata(self, name): ... - def set_metadata(self, name, value): ... - def update_metadata(self, d): ... - def set_acl(self, acl_str, headers: dict[Text, Text] | None = ...): ... - def get_acl(self, headers: dict[Text, Text] | None = ...): ... - def get_xml_acl(self, headers: dict[Text, Text] | None = ...): ... - def set_xml_acl(self, acl_str, headers: dict[Text, Text] | None = ...): ... - def set_canned_acl(self, acl_str, headers: dict[Text, Text] | None = ...): ... - def get_redirect(self): ... - def set_redirect(self, redirect_location, headers: dict[Text, Text] | None = ...): ... - def make_public(self, headers: dict[Text, Text] | None = ...): ... - def generate_url( - self, - expires_in, - method: str = ..., - headers: dict[Text, Text] | None = ..., - query_auth: bool = ..., - force_http: bool = ..., - response_headers: dict[Text, Text] | None = ..., - expires_in_absolute: bool = ..., - version_id: Any | None = ..., - policy: Any | None = ..., - reduced_redundancy: bool = ..., - encrypt_key: bool = ..., - ): ... - def send_file( - self, - fp, - headers: dict[Text, Text] | None = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - query_args: Any | None = ..., - chunked_transfer: bool = ..., - size: Any | None = ..., - ): ... - def should_retry(self, response, chunked_transfer: bool = ...): ... - def compute_md5(self, fp, size: Any | None = ...): ... - def set_contents_from_stream( - self, - fp, - headers: dict[Text, Text] | None = ..., - replace: bool = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - policy: Any | None = ..., - reduced_redundancy: bool = ..., - query_args: Any | None = ..., - size: Any | None = ..., - ): ... - def set_contents_from_file( - self, - fp, - headers: dict[Text, Text] | None = ..., - replace: bool = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - policy: Any | None = ..., - md5: Any | None = ..., - reduced_redundancy: bool = ..., - query_args: Any | None = ..., - encrypt_key: bool = ..., - size: Any | None = ..., - rewind: bool = ..., - ): ... - def set_contents_from_filename( - self, - filename, - headers: dict[Text, Text] | None = ..., - replace: bool = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - policy: Any | None = ..., - md5: Any | None = ..., - reduced_redundancy: bool = ..., - encrypt_key: bool = ..., - ): ... - def set_contents_from_string( - self, - string_data: Text | bytes, - headers: dict[Text, Text] | None = ..., - replace: bool = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - policy: Any | None = ..., - md5: Any | None = ..., - reduced_redundancy: bool = ..., - encrypt_key: bool = ..., - ) -> None: ... - def get_file( - self, - fp, - headers: dict[Text, Text] | None = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - torrent: bool = ..., - version_id: Any | None = ..., - override_num_retries: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - ): ... - def get_torrent_file( - self, fp, headers: dict[Text, Text] | None = ..., cb: Callable[[int, int], Any] | None = ..., num_cb: int = ... - ): ... - def get_contents_to_file( - self, - fp, - headers: dict[Text, Text] | None = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - torrent: bool = ..., - version_id: Any | None = ..., - res_download_handler: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - ): ... - def get_contents_to_filename( - self, - filename, - headers: dict[Text, Text] | None = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - torrent: bool = ..., - version_id: Any | None = ..., - res_download_handler: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - ): ... - @overload - def get_contents_as_string( - self, - headers: dict[Text, Text] | None = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - torrent: bool = ..., - version_id: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - encoding: None = ..., - ) -> bytes: ... - @overload - def get_contents_as_string( - self, - headers: dict[Text, Text] | None = ..., - cb: Callable[[int, int], Any] | None = ..., - num_cb: int = ..., - torrent: bool = ..., - version_id: Any | None = ..., - response_headers: dict[Text, Text] | None = ..., - *, - encoding: Text, - ) -> Text: ... - def add_email_grant(self, permission, email_address, headers: dict[Text, Text] | None = ...): ... - def add_user_grant(self, permission, user_id, headers: dict[Text, Text] | None = ..., display_name: Any | None = ...): ... - def set_remote_metadata(self, metadata_plus, metadata_minus, preserve_acl, headers: dict[Text, Text] | None = ...): ... - def restore(self, days, headers: dict[Text, Text] | None = ...): ... diff --git a/stubs/boto/boto/s3/keyfile.pyi b/stubs/boto/boto/s3/keyfile.pyi deleted file mode 100644 index 121da165a098..000000000000 --- a/stubs/boto/boto/s3/keyfile.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Any - -class KeyFile: - key: Any - location: int - closed: bool - softspace: int - mode: str - encoding: str - errors: str - newlines: str - name: Any - def __init__(self, key) -> None: ... - def tell(self): ... - def seek(self, pos, whence: Any = ...): ... - def read(self, size): ... - def close(self): ... - def isatty(self): ... - def getkey(self): ... - def write(self, buf): ... - def fileno(self): ... - def flush(self): ... - def next(self): ... - def readinto(self): ... - def readline(self): ... - def readlines(self): ... - def truncate(self): ... - def writelines(self): ... - def xreadlines(self): ... diff --git a/stubs/boto/boto/s3/lifecycle.pyi b/stubs/boto/boto/s3/lifecycle.pyi deleted file mode 100644 index bf750bb2e50f..000000000000 --- a/stubs/boto/boto/s3/lifecycle.pyi +++ /dev/null @@ -1,65 +0,0 @@ -from typing import Any, List - -class Rule: - id: Any - prefix: Any - status: Any - expiration: Any - transition: Any - def __init__( - self, - id: Any | None = ..., - prefix: Any | None = ..., - status: Any | None = ..., - expiration: Any | None = ..., - transition: Any | None = ..., - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - -class Expiration: - days: Any - date: Any - def __init__(self, days: Any | None = ..., date: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - -class Transition: - days: Any - date: Any - storage_class: Any - def __init__(self, days: Any | None = ..., date: Any | None = ..., storage_class: Any | None = ...) -> None: ... - def to_xml(self): ... - -class Transitions(List[Transition]): - transition_properties: int - current_transition_property: int - temp_days: Any - temp_date: Any - temp_storage_class: Any - def __init__(self) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - def add_transition(self, days: Any | None = ..., date: Any | None = ..., storage_class: Any | None = ...): ... - @property - def days(self): ... - @property - def date(self): ... - @property - def storage_class(self): ... - -class Lifecycle(List[Rule]): - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - def add_rule( - self, - id: Any | None = ..., - prefix: str = ..., - status: str = ..., - expiration: Any | None = ..., - transition: Any | None = ..., - ): ... diff --git a/stubs/boto/boto/s3/multidelete.pyi b/stubs/boto/boto/s3/multidelete.pyi deleted file mode 100644 index 8d5ab28a5a59..000000000000 --- a/stubs/boto/boto/s3/multidelete.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any - -class Deleted: - key: Any - version_id: Any - delete_marker: Any - delete_marker_version_id: Any - def __init__( - self, - key: Any | None = ..., - version_id: Any | None = ..., - delete_marker: bool = ..., - delete_marker_version_id: Any | None = ..., - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class Error: - key: Any - version_id: Any - code: Any - message: Any - def __init__( - self, key: Any | None = ..., version_id: Any | None = ..., code: Any | None = ..., message: Any | None = ... - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class MultiDeleteResult: - bucket: Any - deleted: Any - errors: Any - def __init__(self, bucket: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... diff --git a/stubs/boto/boto/s3/multipart.pyi b/stubs/boto/boto/s3/multipart.pyi deleted file mode 100644 index 7a231caa4224..000000000000 --- a/stubs/boto/boto/s3/multipart.pyi +++ /dev/null @@ -1,70 +0,0 @@ -from typing import Any - -class CompleteMultiPartUpload: - bucket: Any - location: Any - bucket_name: Any - key_name: Any - etag: Any - version_id: Any - encrypted: Any - def __init__(self, bucket: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -class Part: - bucket: Any - part_number: Any - last_modified: Any - etag: Any - size: Any - def __init__(self, bucket: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - -def part_lister(mpupload, part_number_marker: Any | None = ...): ... - -class MultiPartUpload: - bucket: Any - bucket_name: Any - key_name: Any - id: Any - initiator: Any - owner: Any - storage_class: Any - initiated: Any - part_number_marker: Any - next_part_number_marker: Any - max_parts: Any - is_truncated: bool - def __init__(self, bucket: Any | None = ...) -> None: ... - def __iter__(self): ... - def to_xml(self): ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def get_all_parts( - self, max_parts: Any | None = ..., part_number_marker: Any | None = ..., encoding_type: Any | None = ... - ): ... - def upload_part_from_file( - self, - fp, - part_num, - headers: Any | None = ..., - replace: bool = ..., - cb: Any | None = ..., - num_cb: int = ..., - md5: Any | None = ..., - size: Any | None = ..., - ): ... - def copy_part_from_key( - self, - src_bucket_name, - src_key_name, - part_num, - start: Any | None = ..., - end: Any | None = ..., - src_version_id: Any | None = ..., - headers: Any | None = ..., - ): ... - def complete_upload(self): ... - def cancel_upload(self): ... diff --git a/stubs/boto/boto/s3/prefix.pyi b/stubs/boto/boto/s3/prefix.pyi deleted file mode 100644 index db66a76d701b..000000000000 --- a/stubs/boto/boto/s3/prefix.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -class Prefix: - bucket: Any - name: Any - def __init__(self, bucket: Any | None = ..., name: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - @property - def provider(self): ... diff --git a/stubs/boto/boto/s3/tagging.pyi b/stubs/boto/boto/s3/tagging.pyi deleted file mode 100644 index ad1bcf8039f4..000000000000 --- a/stubs/boto/boto/s3/tagging.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any, List - -class Tag: - key: Any - value: Any - def __init__(self, key: Any | None = ..., value: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - def __eq__(self, other): ... - -class TagSet(List[Tag]): - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def add_tag(self, key, value): ... - def to_xml(self): ... - -class Tags(List[TagSet]): - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - def add_tag_set(self, tag_set): ... diff --git a/stubs/boto/boto/s3/user.pyi b/stubs/boto/boto/s3/user.pyi deleted file mode 100644 index 18d8a0a31d69..000000000000 --- a/stubs/boto/boto/s3/user.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -class User: - type: Any - id: Any - display_name: Any - def __init__(self, parent: Any | None = ..., id: str = ..., display_name: str = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self, element_name: str = ...): ... diff --git a/stubs/boto/boto/s3/website.pyi b/stubs/boto/boto/s3/website.pyi deleted file mode 100644 index 186afdf1fdd1..000000000000 --- a/stubs/boto/boto/s3/website.pyi +++ /dev/null @@ -1,82 +0,0 @@ -from typing import Any, List - -def tag(key, value): ... - -class WebsiteConfiguration: - suffix: Any - error_key: Any - redirect_all_requests_to: Any - routing_rules: Any - def __init__( - self, - suffix: Any | None = ..., - error_key: Any | None = ..., - redirect_all_requests_to: Any | None = ..., - routing_rules: Any | None = ..., - ) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - -class _XMLKeyValue: - translator: Any - container: Any - def __init__(self, translator, container: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - -class RedirectLocation(_XMLKeyValue): - TRANSLATOR: Any - hostname: Any - protocol: Any - def __init__(self, hostname: Any | None = ..., protocol: Any | None = ...) -> None: ... - def to_xml(self): ... - -class RoutingRules(List[RoutingRule]): - def add_rule(self, rule: RoutingRule) -> RoutingRules: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - -class RoutingRule: - condition: Any - redirect: Any - def __init__(self, condition: Any | None = ..., redirect: Any | None = ...) -> None: ... - def startElement(self, name, attrs, connection): ... - def endElement(self, name, value, connection): ... - def to_xml(self): ... - @classmethod - def when(cls, key_prefix: Any | None = ..., http_error_code: Any | None = ...): ... - def then_redirect( - self, - hostname: Any | None = ..., - protocol: Any | None = ..., - replace_key: Any | None = ..., - replace_key_prefix: Any | None = ..., - http_redirect_code: Any | None = ..., - ): ... - -class Condition(_XMLKeyValue): - TRANSLATOR: Any - key_prefix: Any - http_error_code: Any - def __init__(self, key_prefix: Any | None = ..., http_error_code: Any | None = ...) -> None: ... - def to_xml(self): ... - -class Redirect(_XMLKeyValue): - TRANSLATOR: Any - hostname: Any - protocol: Any - replace_key: Any - replace_key_prefix: Any - http_redirect_code: Any - def __init__( - self, - hostname: Any | None = ..., - protocol: Any | None = ..., - replace_key: Any | None = ..., - replace_key_prefix: Any | None = ..., - http_redirect_code: Any | None = ..., - ) -> None: ... - def to_xml(self): ... diff --git a/stubs/boto/boto/utils.pyi b/stubs/boto/boto/utils.pyi deleted file mode 100644 index 3e650b1fea31..000000000000 --- a/stubs/boto/boto/utils.pyi +++ /dev/null @@ -1,154 +0,0 @@ -import datetime -import logging.handlers -import subprocess -import sys -import time -from typing import IO, Any, Callable, ContextManager, Dict, Iterable, Mapping, Sequence, Type, TypeVar - -import boto.connection - -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - -if sys.version_info >= (3,): - # TODO move _StringIO definition into boto.compat once stubs exist and rename to StringIO - import io - - _StringIO = io.StringIO - - from hashlib import _Hash - - _HashType = _Hash - - from email.message import Message as _Message -else: - # TODO move _StringIO definition into boto.compat once stubs exist and rename to StringIO - import StringIO - - _StringIO = StringIO.StringIO[Any] - - from hashlib import _hash - - _HashType = _hash - - # TODO use email.message.Message once stubs exist - _Message = Any - -_Provider = Any # TODO replace this with boto.provider.Provider once stubs exist -_LockType = Any # TODO replace this with _thread.LockType once stubs exist - -JSONDecodeError: Type[ValueError] -qsa_of_interest: list[str] - -def unquote_v(nv: str) -> str | tuple[str, str]: ... -def canonical_string( - method: str, path: str, headers: Mapping[str, str | None], expires: int | None = ..., provider: _Provider | None = ... -) -> str: ... -def merge_meta( - headers: Mapping[str, str], metadata: Mapping[str, str], provider: _Provider | None = ... -) -> Mapping[str, str]: ... -def get_aws_metadata(headers: Mapping[str, str], provider: _Provider | None = ...) -> Mapping[str, str]: ... -def retry_url(url: str, retry_on_404: bool = ..., num_retries: int = ..., timeout: int | None = ...) -> str: ... - -class LazyLoadMetadata(Dict[_KT, _VT]): - def __init__(self, url: str, num_retries: int, timeout: int | None = ...) -> None: ... - -def get_instance_metadata( - version: str = ..., url: str = ..., data: str = ..., timeout: int | None = ..., num_retries: int = ... -) -> LazyLoadMetadata[Any, Any] | None: ... -def get_instance_identity( - version: str = ..., url: str = ..., timeout: int | None = ..., num_retries: int = ... -) -> Mapping[str, Any] | None: ... -def get_instance_userdata( - version: str = ..., sep: str | None = ..., url: str = ..., timeout: int | None = ..., num_retries: int = ... -) -> Mapping[str, str]: ... - -ISO8601: str -ISO8601_MS: str -RFC1123: str -LOCALE_LOCK: _LockType - -def setlocale(name: str | tuple[str, str]) -> ContextManager[str]: ... -def get_ts(ts: time.struct_time | None = ...) -> str: ... -def parse_ts(ts: str) -> datetime.datetime: ... -def find_class(module_name: str, class_name: str | None = ...) -> Type[Any] | None: ... -def update_dme(username: str, password: str, dme_id: str, ip_address: str) -> str: ... -def fetch_file( - uri: str, file: IO[str] | None = ..., username: str | None = ..., password: str | None = ... -) -> IO[str] | None: ... - -class ShellCommand: - exit_code: int - command: subprocess._CMD - log_fp: _StringIO - wait: bool - fail_fast: bool - def __init__( - self, command: subprocess._CMD, wait: bool = ..., fail_fast: bool = ..., cwd: subprocess._TXT | None = ... - ) -> None: ... - process: subprocess.Popen[Any] - def run(self, cwd: subprocess._CMD | None = ...) -> int | None: ... - def setReadOnly(self, value) -> None: ... - def getStatus(self) -> int | None: ... - status: int | None - def getOutput(self) -> str: ... - output: str - -class AuthSMTPHandler(logging.handlers.SMTPHandler): - username: str - password: str - def __init__( - self, mailhost: str, username: str, password: str, fromaddr: str, toaddrs: Sequence[str], subject: str - ) -> None: ... - -class LRUCache(Dict[_KT, _VT]): - class _Item: - previous: LRUCache._Item | None - next: LRUCache._Item | None - key = ... - value = ... - def __init__(self, key, value) -> None: ... - _dict: dict[_KT, LRUCache._Item] - capacity: int - head: LRUCache._Item | None - tail: LRUCache._Item | None - def __init__(self, capacity: int) -> None: ... - -# This exists to work around Password.str's name shadowing the str type -_str = str - -class Password: - hashfunc: Callable[[bytes], _HashType] - str: _str | None - def __init__(self, str: _str | None = ..., hashfunc: Callable[[bytes], _HashType] | None = ...) -> None: ... - def set(self, value: bytes | _str) -> None: ... - def __eq__(self, other: Any) -> bool: ... - def __len__(self) -> int: ... - -def notify( - subject: str, - body: str | None = ..., - html_body: Sequence[str] | str | None = ..., - to_string: str | None = ..., - attachments: Iterable[_Message] | None = ..., - append_instance_id: bool = ..., -) -> None: ... -def get_utf8_value(value: str) -> bytes: ... -def mklist(value: Any) -> list[Any]: ... -def pythonize_name(name: str) -> str: ... -def write_mime_multipart( - content: list[tuple[str, str]], compress: bool = ..., deftype: str = ..., delimiter: str = ... -) -> str: ... -def guess_mime_type(content: str, deftype: str) -> str: ... -def compute_md5(fp: IO[Any], buf_size: int = ..., size: int | None = ...) -> tuple[str, str, int]: ... -def compute_hash(fp: IO[Any], buf_size: int = ..., size: int | None = ..., hash_algorithm: Any = ...) -> tuple[str, str, int]: ... -def find_matching_headers(name: str, headers: Mapping[str, str | None]) -> list[str]: ... -def merge_headers_by_name(name: str, headers: Mapping[str, str | None]) -> str: ... - -class RequestHook: - def handle_request_data( - self, request: boto.connection.HTTPRequest, response: boto.connection.HTTPResponse, error: bool = ... - ) -> Any: ... - -def host_is_ipv6(hostname: str) -> bool: ... -def parse_host(hostname: str) -> str: ... diff --git a/stubs/braintree/@tests/stubtest_allowlist.txt b/stubs/braintree/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f40932c48318 --- /dev/null +++ b/stubs/braintree/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +.*\.AttributeGetter.__repr__ # has an extra argument, but also a million things inherit from it diff --git a/stubs/braintree/METADATA.toml b/stubs/braintree/METADATA.toml index 9c5a4bca25dc..880ac649163e 100644 --- a/stubs/braintree/METADATA.toml +++ b/stubs/braintree/METADATA.toml @@ -1 +1,2 @@ -version = "4.11.*" +version = "4.47.*" +upstream-repository = "https://github.com/braintree/braintree_python" diff --git a/stubs/braintree/braintree/__init__.pyi b/stubs/braintree/braintree/__init__.pyi index f242635c0a75..be8a05595d49 100644 --- a/stubs/braintree/braintree/__init__.pyi +++ b/stubs/braintree/braintree/__init__.pyi @@ -7,6 +7,14 @@ from braintree.amex_express_checkout_card import AmexExpressCheckoutCard as Amex from braintree.android_pay_card import AndroidPayCard as AndroidPayCard from braintree.apple_pay_card import ApplePayCard as ApplePayCard from braintree.apple_pay_gateway import ApplePayGateway as ApplePayGateway +from braintree.bank_account_instant_verification_gateway import ( + BankAccountInstantVerificationGateway as BankAccountInstantVerificationGateway, +) +from braintree.bank_account_instant_verification_jwt import BankAccountInstantVerificationJwt as BankAccountInstantVerificationJwt +from braintree.bank_account_instant_verification_jwt_request import ( + BankAccountInstantVerificationJwtRequest as BankAccountInstantVerificationJwtRequest, +) +from braintree.blik_alias import BlikAlias as BlikAlias from braintree.braintree_gateway import BraintreeGateway as BraintreeGateway from braintree.client_token import ClientToken as ClientToken from braintree.configuration import Configuration as Configuration @@ -32,33 +40,49 @@ from braintree.dispute import Dispute as Dispute from braintree.dispute_search import DisputeSearch as DisputeSearch from braintree.document_upload import DocumentUpload as DocumentUpload from braintree.document_upload_gateway import DocumentUploadGateway as DocumentUploadGateway +from braintree.enriched_customer_data import EnrichedCustomerData as EnrichedCustomerData from braintree.environment import Environment as Environment from braintree.error_codes import ErrorCodes as ErrorCodes from braintree.error_result import ErrorResult as ErrorResult from braintree.errors import Errors as Errors from braintree.europe_bank_account import EuropeBankAccount as EuropeBankAccount +from braintree.graphql import * +from braintree.liability_shift import LiabilityShift as LiabilityShift from braintree.local_payment_completed import LocalPaymentCompleted as LocalPaymentCompleted +from braintree.local_payment_context import LocalPaymentContext as LocalPaymentContext +from braintree.local_payment_context_gateway import LocalPaymentContextGateway as LocalPaymentContextGateway from braintree.local_payment_reversed import LocalPaymentReversed as LocalPaymentReversed +from braintree.local_payment_type import LocalPaymentType as LocalPaymentType from braintree.merchant import Merchant as Merchant from braintree.merchant_account import MerchantAccount as MerchantAccount from braintree.merchant_account_gateway import MerchantAccountGateway as MerchantAccountGateway +from braintree.monetary_amount import MonetaryAmount as MonetaryAmount from braintree.oauth_access_revocation import OAuthAccessRevocation as OAuthAccessRevocation from braintree.partner_merchant import PartnerMerchant as PartnerMerchant +from braintree.payment_facilitator import PaymentFacilitator as PaymentFacilitator from braintree.payment_instrument_type import PaymentInstrumentType as PaymentInstrumentType from braintree.payment_method import PaymentMethod as PaymentMethod +from braintree.payment_method_customer_data_updated_metadata import ( + PaymentMethodCustomerDataUpdatedMetadata as PaymentMethodCustomerDataUpdatedMetadata, +) from braintree.payment_method_nonce import PaymentMethodNonce as PaymentMethodNonce from braintree.payment_method_parser import parse_payment_method as parse_payment_method from braintree.paypal_account import PayPalAccount as PayPalAccount +from braintree.paypal_payment_resource import PayPalPaymentResource as PayPalPaymentResource from braintree.plan import Plan as Plan from braintree.plan_gateway import PlanGateway as PlanGateway from braintree.processor_response_types import ProcessorResponseTypes as ProcessorResponseTypes +from braintree.receiver import Receiver as Receiver from braintree.resource_collection import ResourceCollection as ResourceCollection from braintree.risk_data import RiskData as RiskData from braintree.samsung_pay_card import SamsungPayCard as SamsungPayCard from braintree.search import Search as Search +from braintree.sender import Sender as Sender +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount as SepaDirectDebitAccount from braintree.settlement_batch_summary import SettlementBatchSummary as SettlementBatchSummary from braintree.signature_service import SignatureService as SignatureService from braintree.status_event import StatusEvent as StatusEvent +from braintree.sub_merchant import SubMerchant as SubMerchant from braintree.subscription import Subscription as Subscription from braintree.subscription_gateway import SubscriptionGateway as SubscriptionGateway from braintree.subscription_search import SubscriptionSearch as SubscriptionSearch @@ -72,10 +96,14 @@ from braintree.transaction_details import TransactionDetails as TransactionDetai from braintree.transaction_gateway import TransactionGateway as TransactionGateway from braintree.transaction_line_item import TransactionLineItem as TransactionLineItem from braintree.transaction_search import TransactionSearch as TransactionSearch +from braintree.transaction_us_bank_account_request import TransactionUsBankAccountRequest as TransactionUsBankAccountRequest +from braintree.transfer import Transfer as Transfer from braintree.unknown_payment_method import UnknownPaymentMethod as UnknownPaymentMethod from braintree.us_bank_account import UsBankAccount as UsBankAccount +from braintree.us_bank_account_verification import UsBankAccountVerification as UsBankAccountVerification from braintree.validation_error_collection import ValidationErrorCollection as ValidationErrorCollection from braintree.venmo_account import VenmoAccount as VenmoAccount +from braintree.venmo_profile_data import VenmoProfileData as VenmoProfileData from braintree.version import Version as Version from braintree.webhook_notification import WebhookNotification as WebhookNotification from braintree.webhook_notification_gateway import WebhookNotificationGateway as WebhookNotificationGateway diff --git a/stubs/braintree/braintree/account_updater_daily_report.pyi b/stubs/braintree/braintree/account_updater_daily_report.pyi index 86b343898205..a2c67165b72a 100644 --- a/stubs/braintree/braintree/account_updater_daily_report.pyi +++ b/stubs/braintree/braintree/account_updater_daily_report.pyi @@ -1,9 +1,8 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource +from braintree.resource import Resource class AccountUpdaterDailyReport(Resource): - report_url: Any - report_date: Any + report_url: Incomplete + report_date: Incomplete def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/ach_mandate.pyi b/stubs/braintree/braintree/ach_mandate.pyi index 053c028d18f3..a09111a4d3e8 100644 --- a/stubs/braintree/braintree/ach_mandate.pyi +++ b/stubs/braintree/braintree/ach_mandate.pyi @@ -1,5 +1,4 @@ -from braintree.resource import Resource as Resource -from braintree.util.datetime_parser import parse_datetime as parse_datetime +from braintree.resource import Resource class AchMandate(Resource): def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/add_on.pyi b/stubs/braintree/braintree/add_on.pyi index 6665ada540c4..76f5079c16ac 100644 --- a/stubs/braintree/braintree/add_on.pyi +++ b/stubs/braintree/braintree/add_on.pyi @@ -1,6 +1,5 @@ -from braintree.configuration import Configuration as Configuration -from braintree.modification import Modification as Modification +from braintree.modification import Modification class AddOn(Modification): @staticmethod - def all(): ... + def all() -> list[AddOn]: ... diff --git a/stubs/braintree/braintree/add_on_gateway.pyi b/stubs/braintree/braintree/add_on_gateway.pyi index 131c84cf248f..95bd15bd8c46 100644 --- a/stubs/braintree/braintree/add_on_gateway.pyi +++ b/stubs/braintree/braintree/add_on_gateway.pyi @@ -1,10 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.add_on import AddOn as AddOn -from braintree.resource_collection import ResourceCollection as ResourceCollection +from braintree.add_on import AddOn class AddOnGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def all(self): ... + def all(self) -> list[AddOn]: ... diff --git a/stubs/braintree/braintree/address.pyi b/stubs/braintree/braintree/address.pyi index 63d7531c5a41..eaf4ec201650 100644 --- a/stubs/braintree/braintree/address.pyi +++ b/stubs/braintree/braintree/address.pyi @@ -1,27 +1,31 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Final -from braintree.configuration import Configuration as Configuration -from braintree.error_result import ErrorResult as ErrorResult -from braintree.resource import Resource as Resource -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult class Address(Resource): class ShippingMethod: - SameDay: str - NextDay: str - Priority: str - Ground: str - Electronic: str - ShipToStore: str + SameDay: Final = "same_day" + NextDay: Final = "next_day" + Priority: Final = "priority" + Ground: Final = "ground" + Electronic: Final = "electronic" + ShipToStore: Final = "ship_to_store" + PickupInStore: Final = "pickup_in_store" + @staticmethod - def create(params: Any | None = ...): ... + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def delete(customer_id, address_id): ... + def delete(customer_id: str, address_id: str) -> SuccessfulResult: ... @staticmethod - def find(customer_id, address_id): ... + def find(customer_id: str, address_id: str) -> Address: ... @staticmethod - def update(customer_id, address_id, params: Any | None = ...): ... + def update( + customer_id: str, address_id: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def create_signature(): ... + def create_signature() -> list[str | dict[str, list[str]]]: ... @staticmethod - def update_signature(): ... + def update_signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/address_gateway.pyi b/stubs/braintree/braintree/address_gateway.pyi index bf55fe3f0529..0ecadbe8c924 100644 --- a/stubs/braintree/braintree/address_gateway.pyi +++ b/stubs/braintree/braintree/address_gateway.pyi @@ -1,16 +1,17 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.address import Address as Address -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.resource import Resource as Resource -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.address import Address +from braintree.braintree_gateway import BraintreeGateway +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult class AddressGateway: - gateway: Any - config: Any - def __init__(self, gateway) -> None: ... - def create(self, params: Any | None = ...): ... - def delete(self, customer_id, address_id): ... - def find(self, customer_id, address_id): ... - def update(self, customer_id, address_id, params: Any | None = ...): ... + gateway: BraintreeGateway + config: Incomplete + def __init__(self, gateway: BraintreeGateway) -> None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def delete(self, customer_id: str, address_id: str) -> SuccessfulResult: ... + def find(self, customer_id: str, address_id: str) -> Address: ... + def update( + self, customer_id: str, address_id: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/amex_express_checkout_card.pyi b/stubs/braintree/braintree/amex_express_checkout_card.pyi index 4d736b43e31b..ad0e994fc436 100644 --- a/stubs/braintree/braintree/amex_express_checkout_card.pyi +++ b/stubs/braintree/braintree/amex_express_checkout_card.pyi @@ -1,9 +1,8 @@ -from typing import Any - -from braintree.resource import Resource as Resource +from braintree.resource import Resource +from braintree.subscription import Subscription class AmexExpressCheckoutCard(Resource): - subscriptions: Any + subscriptions: list[Subscription] def __init__(self, gateway, attributes) -> None: ... @property def expiration_date(self): ... diff --git a/stubs/braintree/braintree/android_pay_card.pyi b/stubs/braintree/braintree/android_pay_card.pyi index 2edb683a51b5..41e05930a283 100644 --- a/stubs/braintree/braintree/android_pay_card.pyi +++ b/stubs/braintree/braintree/android_pay_card.pyi @@ -1,10 +1,11 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.resource import Resource as Resource +from braintree.resource import Resource +from braintree.subscription import Subscription class AndroidPayCard(Resource): - is_expired: Any - subscriptions: Any + is_expired: Incomplete + subscriptions: list[Subscription] def __init__(self, gateway, attributes) -> None: ... @property def expiration_date(self): ... @@ -12,3 +13,9 @@ class AndroidPayCard(Resource): def last_4(self): ... @property def card_type(self): ... + @staticmethod + def signature() -> list[str | dict[str, list[str]]]: ... + @staticmethod + def card_signature() -> list[str | dict[str, list[str]]]: ... + @staticmethod + def network_token_signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/apple_pay_card.pyi b/stubs/braintree/braintree/apple_pay_card.pyi index f1cf10754856..0b0e488ac808 100644 --- a/stubs/braintree/braintree/apple_pay_card.pyi +++ b/stubs/braintree/braintree/apple_pay_card.pyi @@ -1,14 +1,21 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Final -from braintree.resource import Resource as Resource +from braintree.credit_card_verification import CreditCardVerification +from braintree.resource import Resource +from braintree.subscription import Subscription class ApplePayCard(Resource): class CardType: - AmEx: str - MasterCard: str - Visa: str - is_expired: Any - subscriptions: Any + AmEx: Final = "Apple Pay - American Express" + MasterCard: Final = "Apple Pay - MasterCard" + Visa: Final = "Apple Pay - Visa" + + is_expired: Incomplete + subscriptions: list[Subscription] + verification: CreditCardVerification | None def __init__(self, gateway, attributes) -> None: ... @property def expiration_date(self): ... + @staticmethod + def signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/apple_pay_gateway.pyi b/stubs/braintree/braintree/apple_pay_gateway.pyi index 37579860600a..55477a1eb30b 100644 --- a/stubs/braintree/braintree/apple_pay_gateway.pyi +++ b/stubs/braintree/braintree/apple_pay_gateway.pyi @@ -1,14 +1,12 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.apple_pay_options import ApplePayOptions as ApplePayOptions -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult class ApplePayGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def register_domain(self, domain): ... - def unregister_domain(self, domain): ... + def register_domain(self, domain: str) -> SuccessfulResult | ErrorResult | None: ... + def unregister_domain(self, domain: str) -> SuccessfulResult: ... def registered_domains(self): ... diff --git a/stubs/braintree/braintree/apple_pay_options.pyi b/stubs/braintree/braintree/apple_pay_options.pyi index 8328c271fb13..c7a6bc4413ef 100644 --- a/stubs/braintree/braintree/apple_pay_options.pyi +++ b/stubs/braintree/braintree/apple_pay_options.pyi @@ -1,3 +1,3 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class ApplePayOptions(AttributeGetter): ... diff --git a/stubs/braintree/braintree/attribute_getter.pyi b/stubs/braintree/braintree/attribute_getter.pyi index bedbb800a3bf..b38cb2a4816a 100644 --- a/stubs/braintree/braintree/attribute_getter.pyi +++ b/stubs/braintree/braintree/attribute_getter.pyi @@ -1,4 +1,7 @@ from typing import Any class AttributeGetter: - def __init__(self, attributes: Any | None = ...) -> None: ... + def __init__(self, attributes: dict[str, Any] | None = None) -> None: ... + # This doesn't exist at runtime, but subclasses should define their own fields populated by attributes in __init__ + # Until that's done, keep __getattribute__ to fill in the gaps + def __getattribute__(self, name: str, /) -> Any: ... diff --git a/stubs/braintree/braintree/authorization_adjustment.pyi b/stubs/braintree/braintree/authorization_adjustment.pyi index 32e9319ee4a2..38f1bb810190 100644 --- a/stubs/braintree/braintree/authorization_adjustment.pyi +++ b/stubs/braintree/braintree/authorization_adjustment.pyi @@ -1,7 +1,7 @@ -from typing import Any +from decimal import Decimal -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class AuthorizationAdjustment(AttributeGetter): - amount: Any + amount: Decimal | None def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi b/stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi new file mode 100644 index 000000000000..989bc822c03a --- /dev/null +++ b/stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class BankAccountInstantVerificationGateway: + gateway: Incomplete + config: Incomplete + graphql_client: Incomplete + CREATE_JWT_MUTATION: Final[str] + def __init__(self, gateway) -> None: ... + def create_jwt(self, request) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi b/stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi new file mode 100644 index 000000000000..3874739b8bff --- /dev/null +++ b/stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi @@ -0,0 +1,9 @@ +from braintree.attribute_getter import AttributeGetter + +class BankAccountInstantVerificationJwt(AttributeGetter): + def __init__(self, jwt) -> None: ... + + @property + def jwt(self): ... + @jwt.setter + def jwt(self, value) -> None: ... diff --git a/stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi b/stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi new file mode 100644 index 000000000000..43ae31462e5a --- /dev/null +++ b/stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi @@ -0,0 +1,18 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _ParamsDict(TypedDict, total=False): + businessName: str + returnUrl: str + cancelUrl: str + +class BankAccountInstantVerificationJwtRequest: + def __init__(self) -> None: ... + def business_name(self, business_name: str) -> Self: ... + def return_url(self, return_url: str) -> Self: ... + def cancel_url(self, cancel_url: str) -> Self: ... + def get_business_name(self) -> str: ... + def get_return_url(self) -> str: ... + def get_cancel_url(self) -> str: ... + def to_graphql_variables(self) -> _ParamsDict: ... diff --git a/stubs/braintree/braintree/bin_data.pyi b/stubs/braintree/braintree/bin_data.pyi index 540fa24965a9..4660a1ec6022 100644 --- a/stubs/braintree/braintree/bin_data.pyi +++ b/stubs/braintree/braintree/bin_data.pyi @@ -1,3 +1,3 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class BinData(AttributeGetter): ... diff --git a/stubs/braintree/braintree/blik_alias.pyi b/stubs/braintree/braintree/blik_alias.pyi new file mode 100644 index 000000000000..7b96548a71cc --- /dev/null +++ b/stubs/braintree/braintree/blik_alias.pyi @@ -0,0 +1,3 @@ +from braintree.resource import Resource + +class BlikAlias(Resource): ... diff --git a/stubs/braintree/braintree/braintree_gateway.pyi b/stubs/braintree/braintree/braintree_gateway.pyi index afa470a8a1a9..28a53728c47c 100644 --- a/stubs/braintree/braintree/braintree_gateway.pyi +++ b/stubs/braintree/braintree/braintree_gateway.pyi @@ -1,60 +1,70 @@ -from typing import Any - -from braintree.add_on_gateway import AddOnGateway as AddOnGateway -from braintree.address_gateway import AddressGateway as AddressGateway -from braintree.apple_pay_gateway import ApplePayGateway as ApplePayGateway -from braintree.client_token_gateway import ClientTokenGateway as ClientTokenGateway -from braintree.configuration import Configuration as Configuration -from braintree.credit_card_gateway import CreditCardGateway as CreditCardGateway -from braintree.credit_card_verification_gateway import CreditCardVerificationGateway as CreditCardVerificationGateway -from braintree.customer_gateway import CustomerGateway as CustomerGateway -from braintree.discount_gateway import DiscountGateway as DiscountGateway -from braintree.dispute_gateway import DisputeGateway as DisputeGateway -from braintree.document_upload_gateway import DocumentUploadGateway as DocumentUploadGateway -from braintree.merchant_account_gateway import MerchantAccountGateway as MerchantAccountGateway -from braintree.merchant_gateway import MerchantGateway as MerchantGateway -from braintree.oauth_gateway import OAuthGateway as OAuthGateway -from braintree.payment_method_gateway import PaymentMethodGateway as PaymentMethodGateway -from braintree.payment_method_nonce_gateway import PaymentMethodNonceGateway as PaymentMethodNonceGateway -from braintree.paypal_account_gateway import PayPalAccountGateway as PayPalAccountGateway -from braintree.plan_gateway import PlanGateway as PlanGateway -from braintree.settlement_batch_summary_gateway import SettlementBatchSummaryGateway as SettlementBatchSummaryGateway -from braintree.subscription_gateway import SubscriptionGateway as SubscriptionGateway -from braintree.testing_gateway import TestingGateway as TestingGateway -from braintree.transaction_gateway import TransactionGateway as TransactionGateway -from braintree.transaction_line_item_gateway import TransactionLineItemGateway as TransactionLineItemGateway -from braintree.us_bank_account_gateway import UsBankAccountGateway as UsBankAccountGateway -from braintree.us_bank_account_verification_gateway import UsBankAccountVerificationGateway as UsBankAccountVerificationGateway -from braintree.webhook_notification_gateway import WebhookNotificationGateway as WebhookNotificationGateway -from braintree.webhook_testing_gateway import WebhookTestingGateway as WebhookTestingGateway +from braintree.add_on_gateway import AddOnGateway +from braintree.address_gateway import AddressGateway +from braintree.apple_pay_gateway import ApplePayGateway +from braintree.bank_account_instant_verification_gateway import BankAccountInstantVerificationGateway +from braintree.client_token_gateway import ClientTokenGateway +from braintree.configuration import Configuration +from braintree.credit_card_gateway import CreditCardGateway +from braintree.credit_card_verification_gateway import CreditCardVerificationGateway +from braintree.customer_gateway import CustomerGateway +from braintree.discount_gateway import DiscountGateway +from braintree.dispute_gateway import DisputeGateway +from braintree.document_upload_gateway import DocumentUploadGateway +from braintree.exchange_rate_quote_gateway import ExchangeRateQuoteGateway +from braintree.local_payment_context_gateway import LocalPaymentContextGateway as LocalPaymentContextGateway +from braintree.merchant_account_gateway import MerchantAccountGateway +from braintree.merchant_gateway import MerchantGateway +from braintree.oauth_gateway import OAuthGateway +from braintree.payment_method_gateway import PaymentMethodGateway +from braintree.payment_method_nonce_gateway import PaymentMethodNonceGateway +from braintree.paypal_account_gateway import PayPalAccountGateway +from braintree.paypal_payment_resource_gateway import PayPalPaymentResourceGateway +from braintree.plan_gateway import PlanGateway +from braintree.sepa_direct_debit_account_gateway import SepaDirectDebitAccountGateway +from braintree.settlement_batch_summary_gateway import SettlementBatchSummaryGateway +from braintree.subscription_gateway import SubscriptionGateway +from braintree.testing_gateway import TestingGateway +from braintree.transaction_gateway import TransactionGateway +from braintree.transaction_line_item_gateway import TransactionLineItemGateway +from braintree.us_bank_account_gateway import UsBankAccountGateway +from braintree.us_bank_account_verification_gateway import UsBankAccountVerificationGateway +from braintree.util.graphql_client import GraphQLClient +from braintree.webhook_notification_gateway import WebhookNotificationGateway +from braintree.webhook_testing_gateway import WebhookTestingGateway class BraintreeGateway: - config: Any - add_on: Any - address: Any - apple_pay: Any - client_token: Any - credit_card: Any - customer: Any - discount: Any - dispute: Any - document_upload: Any - graphql_client: Any - merchant: Any - merchant_account: Any - oauth: Any - payment_method: Any - payment_method_nonce: Any - paypal_account: Any - plan: Any - settlement_batch_summary: Any - subscription: Any - testing: Any - transaction: Any - transaction_line_item: Any - us_bank_account: Any - us_bank_account_verification: Any - verification: Any - webhook_notification: Any - webhook_testing: Any - def __init__(self, config: Any | None = ..., **kwargs) -> None: ... + config: Configuration + add_on: AddOnGateway + address: AddressGateway + apple_pay: ApplePayGateway + bank_account_instant_verification: BankAccountInstantVerificationGateway + client_token: ClientTokenGateway + credit_card: CreditCardGateway + customer: CustomerGateway + discount: DiscountGateway + dispute: DisputeGateway + document_upload: DocumentUploadGateway + exchange_rate_quote: ExchangeRateQuoteGateway + local_payment_context: LocalPaymentContextGateway + graphql_client: GraphQLClient + merchant: MerchantGateway + merchant_account: MerchantAccountGateway + oauth: OAuthGateway + payment_method: PaymentMethodGateway + payment_method_nonce: PaymentMethodNonceGateway + paypal_account: PayPalAccountGateway + paypal_payment_resource: PayPalPaymentResourceGateway + plan: PlanGateway + sepa_direct_debit_account: SepaDirectDebitAccountGateway + settlement_batch_summary: SettlementBatchSummaryGateway + subscription: SubscriptionGateway + testing: TestingGateway + transaction: TransactionGateway + transaction_line_item: TransactionLineItemGateway + us_bank_account: UsBankAccountGateway + us_bank_account_verification: UsBankAccountVerificationGateway + verification: CreditCardVerificationGateway + webhook_notification: WebhookNotificationGateway + webhook_testing: WebhookTestingGateway + def __init__(self, config=None, **kwargs) -> None: ... + def close(self) -> None: ... diff --git a/stubs/braintree/braintree/client_token.pyi b/stubs/braintree/braintree/client_token.pyi index 3e083a2129b1..4855a008da44 100644 --- a/stubs/braintree/braintree/client_token.pyi +++ b/stubs/braintree/braintree/client_token.pyi @@ -1,12 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree import exceptions as exceptions -from braintree.configuration import Configuration as Configuration -from braintree.signature_service import SignatureService as SignatureService -from braintree.util.crypto import Crypto as Crypto +from braintree.braintree_gateway import BraintreeGateway class ClientToken: @staticmethod - def generate(params: Any | None = ..., gateway: Any | None = ...): ... + def generate(params: dict[str, Incomplete] | None = None, gateway: BraintreeGateway | None = None) -> str: ... @staticmethod - def generate_signature(): ... + def generate_signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/client_token_gateway.pyi b/stubs/braintree/braintree/client_token_gateway.pyi index ddb0b12e68ca..b07681cee224 100644 --- a/stubs/braintree/braintree/client_token_gateway.pyi +++ b/stubs/braintree/braintree/client_token_gateway.pyi @@ -1,11 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree import exceptions as exceptions -from braintree.client_token import ClientToken as ClientToken -from braintree.resource import Resource as Resource +from braintree.braintree_gateway import BraintreeGateway class ClientTokenGateway: - gateway: Any - config: Any - def __init__(self, gateway) -> None: ... - def generate(self, params: Any | None = ...): ... + gateway: BraintreeGateway + config: Incomplete + def __init__(self, gateway: BraintreeGateway) -> None: ... + def generate(self, params: dict[str, Incomplete] | None = None) -> str: ... diff --git a/stubs/braintree/braintree/configuration.pyi b/stubs/braintree/braintree/configuration.pyi index 1d8c3fc53db9..25385ba8b292 100644 --- a/stubs/braintree/braintree/configuration.pyi +++ b/stubs/braintree/braintree/configuration.pyi @@ -1,50 +1,70 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.credentials_parser import CredentialsParser as CredentialsParser -from braintree.environment import Environment as Environment -from braintree.exceptions.configuration_error import ConfigurationError as ConfigurationError -from braintree.util.graphql_client import GraphQLClient as GraphQLClient +from braintree.braintree_gateway import BraintreeGateway +from braintree.util.graphql_client import GraphQLClient +from braintree.util.http import Http class Configuration: @staticmethod - def configure(environment, merchant_id, public_key, private_key, **kwargs) -> None: ... + def configure( + environment, + merchant_id: str, + public_key: str, + private_key: str, + *, + http_strategy=None, + timeout: int = 60, + wrap_http_exceptions: bool = False, + ) -> None: ... @staticmethod - def for_partner(environment, partner_id, public_key, private_key, **kwargs): ... + def for_partner( + environment, + partner_id: str, + public_key: str, + private_key: str, + *, + http_strategy=None, + timeout: int = 60, + wrap_http_exceptions: bool = False, + ) -> Configuration: ... @staticmethod - def gateway(): ... + def gateway() -> BraintreeGateway: ... @staticmethod - def instantiate(): ... + def instantiate() -> Configuration: ... @staticmethod - def api_version(): ... + def api_version() -> str: ... @staticmethod - def graphql_api_version(): ... - environment: Any - merchant_id: Any - public_key: Any - private_key: Any - client_id: Any - client_secret: Any - access_token: Any - timeout: Any - wrap_http_exceptions: Any + def graphql_api_version() -> str: ... + environment: Incomplete + merchant_id: str | None + public_key: str | None + private_key: str | None + client_id: str | None + client_secret: str | None + access_token: str | None + timeout: int + wrap_http_exceptions: bool def __init__( self, - environment: Any | None = ..., - merchant_id: Any | None = ..., - public_key: Any | None = ..., - private_key: Any | None = ..., - client_id: Any | None = ..., - client_secret: Any | None = ..., - access_token: Any | None = ..., + environment=None, + merchant_id: str | None = None, + public_key: str | None = None, + private_key: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + access_token: str | None = None, *args, - **kwargs, + timeout: int = 60, + wrap_http_exceptions: bool = False, + http_strategy=None, ) -> None: ... - def base_merchant_path(self): ... - def base_url(self): ... - def graphql_base_url(self): ... - def http(self): ... - def graphql_client(self): ... + def base_merchant_path(self) -> str: ... + def base_url(self) -> str: ... + def graphql_base_url(self) -> str: ... + def http(self) -> Http: ... + def graphql_client(self) -> GraphQLClient: ... def http_strategy(self): ... - def has_client_credentials(self): ... + def close(self) -> None: ... + def has_client_credentials(self) -> bool: ... def assert_has_client_credentials(self) -> None: ... - def has_access_token(self): ... + def has_access_token(self) -> bool: ... diff --git a/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi b/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi index 9f1fe6a152de..27b48b650328 100644 --- a/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi +++ b/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class ConnectedMerchantPayPalStatusChanged(Resource): def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi b/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi index 5b6fa3c2c6c4..c840ac668b6b 100644 --- a/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi +++ b/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class ConnectedMerchantStatusTransitioned(Resource): def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/credentials_parser.pyi b/stubs/braintree/braintree/credentials_parser.pyi index dd1b69ac9c77..bc24ea29893f 100644 --- a/stubs/braintree/braintree/credentials_parser.pyi +++ b/stubs/braintree/braintree/credentials_parser.pyi @@ -1,16 +1,15 @@ -from typing import Any - -from braintree.environment import Environment as Environment -from braintree.exceptions.configuration_error import ConfigurationError as ConfigurationError +from braintree.environment import Environment class CredentialsParser: - client_id: Any - client_secret: Any - access_token: Any - def __init__(self, client_id: Any | None = ..., client_secret: Any | None = ..., access_token: Any | None = ...) -> None: ... - environment: Any + client_id: str | None + client_secret: str | None + access_token: str | None + environment: Environment | None + merchant_id: str + def __init__( + self, client_id: str | None = None, client_secret: str | None = None, access_token: str | None = None + ) -> None: ... def parse_client_credentials(self) -> None: ... - merchant_id: Any def parse_access_token(self) -> None: ... - def get_environment(self, credential): ... - def get_merchant_id(self, credential): ... + def get_environment(self, credential: str) -> Environment | None: ... + def get_merchant_id(self, credential: str) -> str: ... diff --git a/stubs/braintree/braintree/credit_card.pyi b/stubs/braintree/braintree/credit_card.pyi index f6a3738920a5..dd4a30c370e6 100644 --- a/stubs/braintree/braintree/credit_card.pyi +++ b/stubs/braintree/braintree/credit_card.pyi @@ -1,72 +1,96 @@ -from typing import Any +from _typeshed import Incomplete +from datetime import date, datetime +from enum import Enum +from typing import Final, Literal -from braintree.address import Address as Address -from braintree.configuration import Configuration as Configuration -from braintree.credit_card_verification import CreditCardVerification as CreditCardVerification -from braintree.resource import Resource as Resource +from braintree.address import Address +from braintree.credit_card_verification import CreditCardVerification +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.subscription import Subscription +from braintree.successful_result import SuccessfulResult class CreditCard(Resource): class CardType: - AmEx: str - CarteBlanche: str - ChinaUnionPay: str - DinersClubInternational: str - Discover: str - Electron: str - Elo: str - Hiper: str - Hipercard: str - JCB: str - Laser: str - UK_Maestro: str - Maestro: str - MasterCard: str - Solo: str - Switch: str - Visa: str - Unknown: str + AmEx: Final = "American Express" + CarteBlanche: Final = "Carte Blanche" + ChinaUnionPay: Final = "China UnionPay" + DinersClubInternational: Final = "Diners Club" + Discover: Final = "Discover" + Electron: Final = "Electron" + Elo: Final = "Elo" + Hiper: Final = "Hiper" + Hipercard: Final = "Hipercard" + JCB: Final = "JCB" + Laser: Final = "Laser" + UK_Maestro: Final = "UK Maestro" + Maestro: Final = "Maestro" + MasterCard: Final = "MasterCard" + Solo: Final = "Solo" + Switch: Final = "Switch" + Visa: Final = "Visa" + Unknown: Final = "Unknown" + class CustomerLocation: - International: str - US: str + International: Final = "international" + US: Final = "us" + class CardTypeIndicator: - Yes: str - No: str - Unknown: str - Commercial: Any - DurbinRegulated: Any - Debit: Any - Healthcare: Any - CountryOfIssuance: Any - IssuingBank: Any - Payroll: Any - Prepaid: Any - ProductId: Any + Yes: Final = "Yes" + No: Final = "No" + Unknown: Final = "Unknown" + + class DebitNetwork(Enum): + Accel = "ACCEL" + Maestro = "MAESTRO" + Nyce = "NYCE" + Pulse = "PULSE" + Star = "STAR" + Star_Access = "STAR_ACCESS" + + Commercial: type[CardTypeIndicator] + DurbinRegulated: type[CardTypeIndicator] + Debit: type[CardTypeIndicator] + Healthcare: type[CardTypeIndicator] + CountryOfIssuance: type[CardTypeIndicator] + IssuingBank: type[CardTypeIndicator] + Payroll: type[CardTypeIndicator] + Prepaid: type[CardTypeIndicator] + ProductId: type[CardTypeIndicator] + PrepaidReloadable: type[CardTypeIndicator] + Business: type[CardTypeIndicator] + Consumer: type[CardTypeIndicator] + Corporate: type[CardTypeIndicator] + Purchase: type[CardTypeIndicator] @staticmethod - def create(params: Any | None = ...): ... + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def update(credit_card_token, params: Any | None = ...): ... + def update(credit_card_token: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def delete(credit_card_token): ... + def delete(credit_card_token: str) -> SuccessfulResult: ... @staticmethod - def expired(): ... + def expired() -> ResourceCollection: ... @staticmethod - def expiring_between(start_date, end_date): ... + def expiring_between(start_date: date | datetime, end_date: date | datetime) -> ResourceCollection: ... @staticmethod - def find(credit_card_token): ... + def find(credit_card_token: str) -> CreditCard: ... @staticmethod - def from_nonce(nonce): ... + def from_nonce(nonce: str) -> CreditCard: ... @staticmethod - def create_signature(): ... + def create_signature() -> list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]: ... @staticmethod - def update_signature(): ... + def update_signature() -> list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]: ... @staticmethod - def signature(type): ... - is_expired: Any - billing_address: Any - subscriptions: Any - verification: Any - def __init__(self, gateway, attributes): ... + def signature( + type: Literal["create", "update", "update_via_customer"], + ) -> list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]: ... + is_expired = expired + billing_address: Address | None + subscriptions: list[Subscription] + verification: CreditCardVerification + def __init__(self, gateway, attributes) -> None: ... @property - def expiration_date(self): ... + def expiration_date(self) -> str | None: ... @property - def masked_number(self): ... + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/credit_card_gateway.pyi b/stubs/braintree/braintree/credit_card_gateway.pyi index 765f808a7190..2661ad018aea 100644 --- a/stubs/braintree/braintree/credit_card_gateway.pyi +++ b/stubs/braintree/braintree/credit_card_gateway.pyi @@ -1,22 +1,23 @@ -from typing import Any +from _typeshed import Incomplete, Unused +from datetime import date, datetime +from typing_extensions import Never -from braintree.credit_card import CreditCard as CreditCard -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.ids_search import IdsSearch as IdsSearch -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult class CreditCardGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create(self, params: Any | None = ...): ... - def delete(self, credit_card_token): ... - def expired(self): ... - def expiring_between(self, start_date, end_date): ... - def find(self, credit_card_token): ... - def forward(self, credit_card_token, receiving_merchant_id) -> None: ... - def from_nonce(self, nonce): ... - def update(self, credit_card_token, params: Any | None = ...): ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def delete(self, credit_card_token: str) -> SuccessfulResult: ... + def expired(self) -> ResourceCollection: ... + def expiring_between(self, start_date: date | datetime, end_date: date | datetime) -> ResourceCollection: ... + def find(self, credit_card_token: str) -> CreditCard: ... + def forward(self, credit_card_token: Unused, receiving_merchant_id: Unused) -> Never: ... + def from_nonce(self, nonce: str) -> CreditCard: ... + def update( + self, credit_card_token: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/credit_card_verification.pyi b/stubs/braintree/braintree/credit_card_verification.pyi index 29fb9d5d105b..b131e293dd9f 100644 --- a/stubs/braintree/braintree/credit_card_verification.pyi +++ b/stubs/braintree/braintree/credit_card_verification.pyi @@ -1,32 +1,37 @@ -from typing import Any +from _typeshed import Incomplete +from decimal import Decimal +from typing import Final -from braintree.attribute_getter import AttributeGetter as AttributeGetter -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource -from braintree.risk_data import RiskData as RiskData -from braintree.three_d_secure_info import ThreeDSecureInfo as ThreeDSecureInfo +from braintree.attribute_getter import AttributeGetter +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.risk_data import RiskData +from braintree.successful_result import SuccessfulResult +from braintree.three_d_secure_info import ThreeDSecureInfo class CreditCardVerification(AttributeGetter): class Status: - Failed: str - GatewayRejected: str - ProcessorDeclined: str - Verified: str - amount: Any - currency_iso_code: Any - processor_response_code: Any - processor_response_text: Any - network_response_code: Any - network_response_text: Any - risk_data: Any - three_d_secure_info: Any + Failed: Final = "failed" + GatewayRejected: Final = "gateway_rejected" + ProcessorDeclined: Final = "processor_declined" + Verified: Final = "verified" + + amount: Decimal | None + currency_iso_code: Incomplete + mastercard_transaction_link_id: str | None + processor_response_code: Incomplete + processor_response_text: Incomplete + network_response_code: Incomplete + network_response_text: Incomplete + risk_data: RiskData | None + three_d_secure_info: ThreeDSecureInfo | None def __init__(self, gateway, attributes) -> None: ... @staticmethod - def find(verification_id): ... + def find(verification_id: str) -> CreditCardVerification: ... @staticmethod - def search(*query): ... + def search(*query) -> ResourceCollection: ... @staticmethod - def create(params): ... + def create(params) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def create_signature(): ... - def __eq__(self, other): ... + def create_signature() -> list[dict[str, list[str | dict[str, list[str]]]] | dict[str, list[str]] | str]: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/braintree/braintree/credit_card_verification_gateway.pyi b/stubs/braintree/braintree/credit_card_verification_gateway.pyi index 737cf19d8975..fa108beb5f2d 100644 --- a/stubs/braintree/braintree/credit_card_verification_gateway.pyi +++ b/stubs/braintree/braintree/credit_card_verification_gateway.pyi @@ -1,17 +1,14 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.credit_card_verification import CreditCardVerification as CreditCardVerification -from braintree.credit_card_verification_search import CreditCardVerificationSearch as CreditCardVerificationSearch -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.ids_search import IdsSearch as IdsSearch -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.credit_card_verification import CreditCardVerification +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult class CreditCardVerificationGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def find(self, verification_id): ... - def search(self, *query): ... - def create(self, params): ... + def find(self, verification_id: str) -> CreditCardVerification: ... + def search(self, *query) -> ResourceCollection: ... + def create(self, params: dict[str, Incomplete] | None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/credit_card_verification_search.pyi b/stubs/braintree/braintree/credit_card_verification_search.pyi index 4036aaddbdca..8e5444923484 100644 --- a/stubs/braintree/braintree/credit_card_verification_search.pyi +++ b/stubs/braintree/braintree/credit_card_verification_search.pyi @@ -1,20 +1,15 @@ -from typing import Any - -from braintree.credit_card import CreditCard as CreditCard -from braintree.credit_card_verification import CreditCardVerification as CreditCardVerification -from braintree.search import Search as Search -from braintree.util import Constants as Constants +from braintree.search import Search class CreditCardVerificationSearch: - credit_card_cardholder_name: Any - id: Any - credit_card_expiration_date: Any - credit_card_number: Any - credit_card_card_type: Any - ids: Any - created_at: Any - status: Any - billing_postal_code: Any - customer_email: Any - customer_id: Any - payment_method_token: Any + credit_card_cardholder_name: Search.TextNodeBuilder + id: Search.TextNodeBuilder + credit_card_expiration_date: Search.EqualityNodeBuilder + credit_card_number: Search.PartialMatchNodeBuilder + credit_card_card_type: Search.MultipleValueNodeBuilder + ids: Search.MultipleValueNodeBuilder + created_at: Search.RangeNodeBuilder + status: Search.MultipleValueNodeBuilder + billing_postal_code: Search.TextNodeBuilder + customer_email: Search.TextNodeBuilder + customer_id: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder diff --git a/stubs/braintree/braintree/customer.pyi b/stubs/braintree/braintree/customer.pyi index cd0ffa78a5eb..22f5532ae8fb 100644 --- a/stubs/braintree/braintree/customer.pyi +++ b/stubs/braintree/braintree/customer.pyi @@ -1,54 +1,66 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.address import Address as Address -from braintree.amex_express_checkout_card import AmexExpressCheckoutCard as AmexExpressCheckoutCard -from braintree.android_pay_card import AndroidPayCard as AndroidPayCard -from braintree.apple_pay_card import ApplePayCard as ApplePayCard -from braintree.configuration import Configuration as Configuration -from braintree.credit_card import CreditCard as CreditCard -from braintree.error_result import ErrorResult as ErrorResult -from braintree.europe_bank_account import EuropeBankAccount as EuropeBankAccount -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.ids_search import IdsSearch as IdsSearch -from braintree.masterpass_card import MasterpassCard as MasterpassCard -from braintree.paypal_account import PayPalAccount as PayPalAccount -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.samsung_pay_card import SamsungPayCard as SamsungPayCard -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.us_bank_account import UsBankAccount as UsBankAccount -from braintree.util.http import Http as Http -from braintree.venmo_account import VenmoAccount as VenmoAccount -from braintree.visa_checkout_card import VisaCheckoutCard as VisaCheckoutCard +from braintree.address import Address +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.samsung_pay_card import SamsungPayCard +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard class Customer(Resource): @staticmethod - def all(): ... + def all() -> ResourceCollection: ... @staticmethod - def create(params: Any | None = ...): ... + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def delete(customer_id): ... + def delete(customer_id: str) -> SuccessfulResult: ... @staticmethod - def find(customer_id, association_filter_id: Any | None = ...): ... + def find(customer_id: str, association_filter_id: str | None = None) -> Customer: ... @staticmethod - def search(*query): ... + def search(*query) -> ResourceCollection: ... @staticmethod - def update(customer_id, params: Any | None = ...): ... + def update(customer_id: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def create_signature(): ... + def create_signature() -> ( + list[ + str + | dict[str, list[str]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]] + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + ] + ): ... @staticmethod - def update_signature(): ... - payment_methods: Any - credit_cards: Any - addresses: Any - paypal_accounts: Any - apple_pay_cards: Any - android_pay_cards: Any - amex_express_checkout_cards: Any - europe_bank_accounts: Any - venmo_accounts: Any - us_bank_accounts: Any - visa_checkout_cards: Any - masterpass_cards: Any - samsung_pay_cards: Any + def update_signature() -> ( + list[ + str + | dict[str, list[str]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]] + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + ] + ): ... + payment_methods: list[Resource] + credit_cards: list[CreditCard] + addresses: list[Address] + paypal_accounts: list[PayPalAccount] + apple_pay_cards: list[ApplePayCard] + android_pay_cards: list[AndroidPayCard] + amex_express_checkout_cards: list[AmexExpressCheckoutCard] + europe_bank_accounts: list[EuropeBankAccount] + venmo_accounts: list[VenmoAccount] + us_bank_accounts: list[UsBankAccount] + visa_checkout_cards: list[VisaCheckoutCard] + masterpass_cards: list[MasterpassCard] + samsung_pay_cards: list[SamsungPayCard] def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/customer_gateway.pyi b/stubs/braintree/braintree/customer_gateway.pyi index 6b1391ef74a7..18558178134c 100644 --- a/stubs/braintree/braintree/customer_gateway.pyi +++ b/stubs/braintree/braintree/customer_gateway.pyi @@ -1,20 +1,17 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.customer import Customer as Customer -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.ids_search import IdsSearch as IdsSearch -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.customer import Customer +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult class CustomerGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def all(self): ... - def create(self, params: Any | None = ...): ... - def delete(self, customer_id): ... - def find(self, customer_id, association_filter_id: Any | None = ...): ... - def search(self, *query): ... - def update(self, customer_id, params: Any | None = ...): ... + def all(self) -> ResourceCollection: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def delete(self, customer_id: str) -> SuccessfulResult: ... + def find(self, customer_id: str, association_filter_id: str | None = None) -> Customer: ... + def search(self, *query) -> ResourceCollection: ... + def update(self, customer_id: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/customer_search.pyi b/stubs/braintree/braintree/customer_search.pyi index a55ecf7846ed..57b7004602c6 100644 --- a/stubs/braintree/braintree/customer_search.pyi +++ b/stubs/braintree/braintree/customer_search.pyi @@ -1,29 +1,27 @@ -from typing import Any - -from braintree.search import Search as Search +from braintree.search import Search class CustomerSearch: - address_extended_address: Any - address_first_name: Any - address_last_name: Any - address_locality: Any - address_postal_code: Any - address_region: Any - address_street_address: Any - address_country_name: Any - cardholder_name: Any - company: Any - created_at: Any - credit_card_expiration_date: Any - credit_card_number: Any - email: Any - fax: Any - first_name: Any - id: Any - ids: Any - last_name: Any - payment_method_token: Any - payment_method_token_with_duplicates: Any - phone: Any - website: Any - paypal_account_email: Any + address_extended_address: Search.TextNodeBuilder + address_first_name: Search.TextNodeBuilder + address_last_name: Search.TextNodeBuilder + address_locality: Search.TextNodeBuilder + address_postal_code: Search.TextNodeBuilder + address_region: Search.TextNodeBuilder + address_street_address: Search.TextNodeBuilder + address_country_name: Search.TextNodeBuilder + cardholder_name: Search.TextNodeBuilder + company: Search.TextNodeBuilder + created_at: Search.RangeNodeBuilder + credit_card_expiration_date: Search.EqualityNodeBuilder + credit_card_number: Search.TextNodeBuilder + email: Search.TextNodeBuilder + fax: Search.TextNodeBuilder + first_name: Search.TextNodeBuilder + id: Search.TextNodeBuilder + ids: Search.MultipleValueNodeBuilder + last_name: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder + payment_method_token_with_duplicates: Search.IsNodeBuilder + phone: Search.TextNodeBuilder + website: Search.TextNodeBuilder + paypal_account_email: Search.TextNodeBuilder diff --git a/stubs/braintree/braintree/customer_session_gateway.pyi b/stubs/braintree/braintree/customer_session_gateway.pyi new file mode 100644 index 000000000000..dbcf24f78de3 --- /dev/null +++ b/stubs/braintree/braintree/customer_session_gateway.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.graphql import CreateCustomerSessionInput, CustomerRecommendationsInput, UpdateCustomerSessionInput +from braintree.successful_result import SuccessfulResult + +class CustomerSessionGateway: + gateway: Incomplete + graphql_client: Incomplete + def __init__(self, gateway) -> None: ... + def create_customer_session(self, customer_session_input: CreateCustomerSessionInput) -> SuccessfulResult | ErrorResult: ... + def update_customer_session( + self, update_customer_session_input: UpdateCustomerSessionInput + ) -> SuccessfulResult | ErrorResult: ... + def get_customer_recommendations( + self, get_customer_recommendations_input: CustomerRecommendationsInput + ) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/descriptor.pyi b/stubs/braintree/braintree/descriptor.pyi index 0ec66354c80c..bc2526c430f1 100644 --- a/stubs/braintree/braintree/descriptor.pyi +++ b/stubs/braintree/braintree/descriptor.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class Descriptor(Resource): def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/disbursement.pyi b/stubs/braintree/braintree/disbursement.pyi index fc4634d3eedf..f406b972cb12 100644 --- a/stubs/braintree/braintree/disbursement.pyi +++ b/stubs/braintree/braintree/disbursement.pyi @@ -1,16 +1,17 @@ -from typing import Any +from decimal import Decimal +from typing import Final -from braintree.merchant_account import MerchantAccount as MerchantAccount -from braintree.resource import Resource as Resource -from braintree.transaction_search import TransactionSearch as TransactionSearch +from braintree.merchant_account import MerchantAccount +from braintree.resource import Resource class Disbursement(Resource): class Type: - Credit: str - Debit: str - amount: Any - merchant_account: Any + Credit: Final = "credit" + Debit: Final = "debit" + + amount: Decimal + merchant_account: MerchantAccount def __init__(self, gateway, attributes) -> None: ... def transactions(self): ... - def is_credit(self): ... - def is_debit(self): ... + def is_credit(self) -> bool: ... + def is_debit(self) -> bool: ... diff --git a/stubs/braintree/braintree/disbursement_detail.pyi b/stubs/braintree/braintree/disbursement_detail.pyi index 7badea3a87fe..8de304b964fb 100644 --- a/stubs/braintree/braintree/disbursement_detail.pyi +++ b/stubs/braintree/braintree/disbursement_detail.pyi @@ -1,10 +1,10 @@ -from typing import Any +from decimal import Decimal -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class DisbursementDetail(AttributeGetter): - settlement_amount: Any - settlement_currency_exchange_rate: Any + settlement_amount: Decimal | None + settlement_currency_exchange_rate: Decimal | None def __init__(self, attributes) -> None: ... @property - def is_valid(self): ... + def is_valid(self) -> bool: ... diff --git a/stubs/braintree/braintree/discount.pyi b/stubs/braintree/braintree/discount.pyi index e9ff1c91d416..0078843f6265 100644 --- a/stubs/braintree/braintree/discount.pyi +++ b/stubs/braintree/braintree/discount.pyi @@ -1,6 +1,5 @@ -from braintree.configuration import Configuration as Configuration -from braintree.modification import Modification as Modification +from braintree.modification import Modification class Discount(Modification): @staticmethod - def all(): ... + def all() -> list[Discount]: ... diff --git a/stubs/braintree/braintree/discount_gateway.pyi b/stubs/braintree/braintree/discount_gateway.pyi index 45203a328f29..df1da780a7c2 100644 --- a/stubs/braintree/braintree/discount_gateway.pyi +++ b/stubs/braintree/braintree/discount_gateway.pyi @@ -1,10 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.discount import Discount as Discount -from braintree.resource_collection import ResourceCollection as ResourceCollection +from braintree.discount import Discount class DiscountGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def all(self): ... + def all(self) -> list[Discount]: ... diff --git a/stubs/braintree/braintree/dispute.pyi b/stubs/braintree/braintree/dispute.pyi index 64a87eb045bc..338e7101a613 100644 --- a/stubs/braintree/braintree/dispute.pyi +++ b/stubs/braintree/braintree/dispute.pyi @@ -1,63 +1,79 @@ -from typing import Any +from _typeshed import Incomplete +from decimal import Decimal +from typing import Final -from braintree.attribute_getter import AttributeGetter as AttributeGetter -from braintree.configuration import Configuration as Configuration -from braintree.dispute_details import ( - DisputeEvidence as DisputeEvidence, - DisputePayPalMessage as DisputePayPalMessage, - DisputeStatusHistory as DisputeStatusHistory, -) -from braintree.transaction_details import TransactionDetails as TransactionDetails +from braintree.attribute_getter import AttributeGetter +from braintree.dispute_details import DisputeEvidence, DisputePayPalMessage, DisputeStatusHistory +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult +from braintree.transaction_details import TransactionDetails class Dispute(AttributeGetter): class Status: - Accepted: str - Disputed: str - Expired: str - Open: str - Won: str - Lost: str + Accepted: Final = "accepted" + AutoAccepted: Final = "auto_accepted" + Disputed: Final = "disputed" + Expired: Final = "expired" + Lost: Final = "lost" + Open: Final = "open" + UnderReview: Final = "under_review" + Won: Final = "won" + class Reason: - CancelledRecurringTransaction: str - CreditNotProcessed: str - Duplicate: str - Fraud: str - General: str - InvalidAccount: str - NotRecognized: str - ProductNotReceived: str - ProductUnsatisfactory: str - Retrieval: str - TransactionAmountDiffers: str + CancelledRecurringTransaction: Final = "cancelled_recurring_transaction" + CreditNotProcessed: Final = "credit_not_processed" + Duplicate: Final = "duplicate" + Fraud: Final = "fraud" + General: Final = "general" + InvalidAccount: Final = "invalid_account" + NotRecognized: Final = "not_recognized" + ProductNotReceived: Final = "product_not_received" + ProductUnsatisfactory: Final = "product_unsatisfactory" + Retrieval: Final = "retrieval" + TransactionAmountDiffers: Final = "transaction_amount_differs" + class Kind: - Chargeback: str - PreArbitration: str - Retrieval: str + Chargeback: Final = "chargeback" + PreArbitration: Final = "pre_arbitration" + Retrieval: Final = "retrieval" + class ChargebackProtectionLevel: - Effortless: str - Standard: str - NotProtected: str + Effortless: Final = "effortless" + Standard: Final = "standard" + NotProtected: Final = "not_protected" + + class PreDisputeProgram: + NONE: Final = "none" + VisaRdr: Final = "visa_rdr" + + class ProtectionLevel: + EffortlessCBP: Final = "Effortless Chargeback Protection tool" + StandardCBP: Final = "Chargeback Protection tool" + NoProtection: Final = "No Protection" + @staticmethod - def accept(id): ... + def accept(id: str) -> SuccessfulResult | ErrorResult: ... @staticmethod - def add_file_evidence(dispute_id, document_upload_id): ... + def add_file_evidence(dispute_id: str, document_upload_id) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def add_text_evidence(id, content_or_request): ... + def add_text_evidence(id: str, content_or_request) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def finalize(id): ... + def finalize(id: str) -> SuccessfulResult | ErrorResult: ... @staticmethod - def find(id): ... + def find(id: str) -> Dispute: ... @staticmethod - def remove_evidence(id, evidence_id): ... + def remove_evidence(id: str, evidence_id: str) -> SuccessfulResult | ErrorResult: ... @staticmethod - def search(*query): ... - amount: Any - amount_disputed: Any - amount_won: Any - transaction_details: Any - transaction: Any - evidence: Any - paypal_messages: Any - status_history: Any - forwarded_comments: Any + def search(*query) -> SuccessfulResult: ... + amount: Decimal | None + amount_disputed: Decimal | None + amount_won: Decimal | None + protection_level: Incomplete + transaction_details: TransactionDetails + transaction = transaction_details # pyrefly: ignore [unknown-name] + evidence: list[DisputeEvidence] | None + paypal_messages: list[DisputePayPalMessage] | None + status_history: list[DisputeStatusHistory] | None + processor_comments: Incomplete + forwarded_comments: processor_comments # pyrefly: ignore [unknown-name] def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/dispute_details/evidence.pyi b/stubs/braintree/braintree/dispute_details/evidence.pyi index c488be75c0b6..a7dd9100d4d1 100644 --- a/stubs/braintree/braintree/dispute_details/evidence.pyi +++ b/stubs/braintree/braintree/dispute_details/evidence.pyi @@ -1,4 +1,6 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from typing import Any + +from braintree.attribute_getter import AttributeGetter class DisputeEvidence(AttributeGetter): - def __init__(self, attributes) -> None: ... + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/dispute_details/paypal_message.pyi b/stubs/braintree/braintree/dispute_details/paypal_message.pyi index 95504bfd8b58..7d5d8a2441e5 100644 --- a/stubs/braintree/braintree/dispute_details/paypal_message.pyi +++ b/stubs/braintree/braintree/dispute_details/paypal_message.pyi @@ -1,4 +1,6 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from typing import Any + +from braintree.attribute_getter import AttributeGetter class DisputePayPalMessage(AttributeGetter): - def __init__(self, attributes) -> None: ... + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/dispute_details/status_history.pyi b/stubs/braintree/braintree/dispute_details/status_history.pyi index 648315f33333..dd7466ace617 100644 --- a/stubs/braintree/braintree/dispute_details/status_history.pyi +++ b/stubs/braintree/braintree/dispute_details/status_history.pyi @@ -1,4 +1,6 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from typing import Any + +from braintree.attribute_getter import AttributeGetter class DisputeStatusHistory(AttributeGetter): - def __init__(self, attributes) -> None: ... + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/dispute_gateway.pyi b/stubs/braintree/braintree/dispute_gateway.pyi index 72ce19c9091b..4c0a5d66481f 100644 --- a/stubs/braintree/braintree/dispute_gateway.pyi +++ b/stubs/braintree/braintree/dispute_gateway.pyi @@ -1,23 +1,18 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.dispute import Dispute as Dispute -from braintree.dispute_details import DisputeEvidence as DisputeEvidence -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.paginated_collection import PaginatedCollection as PaginatedCollection -from braintree.paginated_result import PaginatedResult as PaginatedResult -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.dispute import Dispute +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult class DisputeGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def accept(self, dispute_id): ... - def add_file_evidence(self, dispute_id, document_upload_id_or_request): ... - def add_text_evidence(self, dispute_id, content_or_request): ... - def finalize(self, dispute_id): ... - def find(self, dispute_id): ... - def remove_evidence(self, dispute_id, evidence_id): ... - search_criteria: Any - def search(self, *query): ... + def accept(self, dispute_id: str) -> SuccessfulResult | ErrorResult: ... + def add_file_evidence(self, dispute_id: str, document_upload_id_or_request) -> SuccessfulResult | ErrorResult | None: ... + def add_text_evidence(self, dispute_id: str, content_or_request) -> SuccessfulResult | ErrorResult | None: ... + def finalize(self, dispute_id: str) -> SuccessfulResult | ErrorResult: ... + def find(self, dispute_id: str) -> Dispute: ... + def remove_evidence(self, dispute_id: str, evidence_id: int) -> SuccessfulResult | ErrorResult: ... + search_criteria: dict[Incomplete, Incomplete] + def search(self, *query) -> SuccessfulResult: ... diff --git a/stubs/braintree/braintree/dispute_search.pyi b/stubs/braintree/braintree/dispute_search.pyi index dddf55e1641d..50bfce33a60f 100644 --- a/stubs/braintree/braintree/dispute_search.pyi +++ b/stubs/braintree/braintree/dispute_search.pyi @@ -1,23 +1,23 @@ -from typing import Any - -from braintree.search import Search as Search +from braintree.search import Search class DisputeSearch: - amount_disputed: Any - amount_won: Any - case_number: Any - chargeback_protection_level: Any - customer_id: Any - disbursement_date: Any - effective_date: Any - id: Any - kind: Any - merchant_account_id: Any - reason: Any - reason_code: Any - received_date: Any - reference_number: Any - reply_by_date: Any - status: Any - transaction_id: Any - transaction_source: Any + amount_disputed: Search.RangeNodeBuilder + amount_won: Search.RangeNodeBuilder + case_number: Search.TextNodeBuilder + chargeback_protection_level: Search.MultipleValueNodeBuilder + protection_level: Search.MultipleValueNodeBuilder + customer_id: Search.TextNodeBuilder + disbursement_date: Search.RangeNodeBuilder + effective_date: Search.RangeNodeBuilder + id: Search.TextNodeBuilder + kind: Search.MultipleValueNodeBuilder + merchant_account_id: Search.MultipleValueNodeBuilder + pre_dispute_program: Search.MultipleValueNodeBuilder + reason: Search.MultipleValueNodeBuilder + reason_code: Search.MultipleValueNodeBuilder + received_date: Search.RangeNodeBuilder + reference_number: Search.TextNodeBuilder + reply_by_date: Search.RangeNodeBuilder + status: Search.MultipleValueNodeBuilder + transaction_id: Search.TextNodeBuilder + transaction_source: Search.MultipleValueNodeBuilder diff --git a/stubs/braintree/braintree/document_upload.pyi b/stubs/braintree/braintree/document_upload.pyi index 428b0d632315..155b5596711e 100644 --- a/stubs/braintree/braintree/document_upload.pyi +++ b/stubs/braintree/braintree/document_upload.pyi @@ -1,14 +1,16 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Final -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult class DocumentUpload(Resource): class Kind: - EvidenceDocument: str + EvidenceDocument: Final = "evidence_document" + @staticmethod - def create(params: Any | None = ...): ... + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... @staticmethod - def create_signature(): ... + def create_signature() -> list[str]: ... def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/document_upload_gateway.pyi b/stubs/braintree/braintree/document_upload_gateway.pyi index 1c7549d65fdc..5dcf510fee1b 100644 --- a/stubs/braintree/braintree/document_upload_gateway.pyi +++ b/stubs/braintree/braintree/document_upload_gateway.pyi @@ -1,12 +1,10 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.document_upload import DocumentUpload as DocumentUpload -from braintree.error_result import ErrorResult as ErrorResult -from braintree.resource import Resource as Resource -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult class DocumentUploadGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create(self, params: Any | None = ...): ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/enriched_customer_data.pyi b/stubs/braintree/braintree/enriched_customer_data.pyi new file mode 100644 index 000000000000..18ad120319ee --- /dev/null +++ b/stubs/braintree/braintree/enriched_customer_data.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class EnrichedCustomerData(Resource): + profile_data: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/environment.pyi b/stubs/braintree/braintree/environment.pyi index 7ebd8bf03a52..cd272b3e434b 100644 --- a/stubs/braintree/braintree/environment.pyi +++ b/stubs/braintree/braintree/environment.pyi @@ -1,33 +1,45 @@ -from typing import Any - -from braintree.exceptions.configuration_error import ConfigurationError as ConfigurationError +from _typeshed import Incomplete +from typing import ClassVar class Environment: - __name__: Any - is_ssl: Any - ssl_certificate: Any + Development: ClassVar[Environment] + QA: ClassVar[Environment] + Sandbox: ClassVar[Environment] + Production: ClassVar[Environment] + All: ClassVar[dict[str, Environment]] + __name__: str + is_ssl: bool + ssl_certificate: Incomplete def __init__( - self, name, server, port, auth_url, is_ssl, ssl_certificate, graphql_server: str = ..., graphql_port: str = ... + self, + name, + server: str, + port, + auth_url: str, + is_ssl: bool, + ssl_certificate, + graphql_server: str = "", + graphql_port: str = "", ) -> None: ... @property - def base_url(self): ... + def base_url(self) -> str: ... @property - def port(self): ... + def port(self) -> int: ... @property - def auth_url(self): ... + def auth_url(self) -> str: ... @property - def protocol(self): ... + def protocol(self) -> str: ... @property - def server(self): ... + def server(self) -> str: ... @property - def server_and_port(self): ... + def server_and_port(self) -> str: ... @property - def graphql_server(self): ... + def graphql_server(self) -> str: ... @property - def graphql_port(self): ... + def graphql_port(self) -> str: ... @property - def graphql_server_and_port(self): ... + def graphql_server_and_port(self) -> str: ... @staticmethod - def parse_environment(environment): ... + def parse_environment(environment: Environment | str | None) -> Environment | None: ... @staticmethod - def braintree_root(): ... + def braintree_root() -> str: ... diff --git a/stubs/braintree/braintree/error_codes.pyi b/stubs/braintree/braintree/error_codes.pyi index 147f54dc4dfd..c2cff63557bd 100644 --- a/stubs/braintree/braintree/error_codes.pyi +++ b/stubs/braintree/braintree/error_codes.pyi @@ -1,722 +1,768 @@ +from typing import Final + class ErrorCodes: class Address: - CannotBeBlank: str - CompanyIsInvalid: str - CompanyIsTooLong: str - CountryCodeAlpha2IsNotAccepted: str - CountryCodeAlpha3IsNotAccepted: str - CountryCodeNumericIsNotAccepted: str - CountryNameIsNotAccepted: str - ExtendedAddressIsInvalid: str - ExtendedAddressIsTooLong: str - FirstNameIsInvalid: str - FirstNameIsTooLong: str - InconsistentCountry: str - IsInvalid: str - LastNameIsInvalid: str - LastNameIsTooLong: str - LocalityIsInvalid: str - LocalityIsTooLong: str - PostalCodeInvalidCharacters: str - PostalCodeIsInvalid: str - PostalCodeIsRequired: str - PostalCodeIsRequiredForCardBrandAndProcessor: str - PostalCodeIsTooLong: str - RegionIsInvalid: str - RegionIsTooLong: str - StateIsInvalidForSellerProtection: str - StreetAddressIsInvalid: str - StreetAddressIsRequired: str - StreetAddressIsTooLong: str - TooManyAddressesPerCustomer: str + CannotBeBlank: Final = "81801" + CompanyIsInvalid: Final = "91821" + CompanyIsTooLong: Final = "81802" + CountryCodeAlpha2IsNotAccepted: Final = "91814" + CountryCodeAlpha3IsNotAccepted: Final = "91816" + CountryCodeNumericIsNotAccepted: Final = "91817" + CountryNameIsNotAccepted: Final = "91803" + ExtendedAddressIsInvalid: Final = "91823" + ExtendedAddressIsTooLong: Final = "81804" + FirstNameIsInvalid: Final = "91819" + FirstNameIsTooLong: Final = "81805" + InconsistentCountry: Final = "91815" + IsInvalid: Final = "91828" + LastNameIsInvalid: Final = "91820" + LastNameIsTooLong: Final = "81806" + LocalityIsInvalid: Final = "91824" + LocalityIsTooLong: Final = "81807" + PostalCodeInvalidCharacters: Final = "81813" + PostalCodeIsInvalid: Final = "91826" + PostalCodeIsRequired: Final = "81808" + PostalCodeIsRequiredForCardBrandAndProcessor: Final = "81828" + PostalCodeIsTooLong: Final = "81809" + RegionIsInvalid: Final = "91825" + RegionIsTooLong: Final = "81810" + StateIsInvalidForSellerProtection: Final = "81827" + StreetAddressIsInvalid: Final = "91822" + StreetAddressIsRequired: Final = "81811" + StreetAddressIsTooLong: Final = "81812" + TooManyAddressesPerCustomer: Final = "91818" + + class AndroidPay: + AndroidPayCardsAreNotAccepted: Final = "83708" + class ApplePay: - ApplePayCardsAreNotAccepted: str - CustomerIdIsRequiredForVaulting: str - TokenIsInUse: str - PaymentMethodNonceConsumed: str - PaymentMethodNonceUnknown: str - PaymentMethodNonceLocked: str - PaymentMethodNonceCardTypeIsNotAccepted: str - CannotUpdateApplePayCardUsingPaymentMethodNonce: str - NumberIsRequired: str - ExpirationMonthIsRequired: str - ExpirationYearIsRequired: str - CryptogramIsRequired: str - DecryptionFailed: str - Disabled: str - MerchantNotConfigured: str - MerchantKeysAlreadyConfigured: str - MerchantKeysNotConfigured: str - CertificateInvalid: str - CertificateMismatch: str - InvalidToken: str - PrivateKeyMismatch: str - KeyMismatchStoringCertificate: str + ApplePayCardsAreNotAccepted: Final = "83501" + CustomerIdIsRequiredForVaulting: Final = "83502" + TokenIsInUse: Final = "93503" + PaymentMethodNonceConsumed: Final = "93504" + PaymentMethodNonceUnknown: Final = "93505" + PaymentMethodNonceLocked: Final = "93506" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "83518" + CannotUpdateApplePayCardUsingPaymentMethodNonce: Final = "93507" + NumberIsRequired: Final = "93508" + ExpirationMonthIsRequired: Final = "93509" + ExpirationYearIsRequired: Final = "93510" + CryptogramIsRequired: Final = "93511" + DecryptionFailed: Final = "83512" + Disabled: Final = "93513" + MerchantNotConfigured: Final = "93514" + MerchantKeysAlreadyConfigured: Final = "93515" + MerchantKeysNotConfigured: Final = "93516" + NetworkTransactionIdNotAllowed: Final = "93532" + CertificateInvalid: Final = "93517" + CertificateMismatch: Final = "93519" + InvalidToken: Final = "83520" + PrivateKeyMismatch: Final = "93521" + KeyMismatchStoringCertificate: Final = "93522" + CustomerIdIsInvalid: Final = "93528" + BillingAddressFormatIsInvalid: Final = "93529" + + class Options: + class Verification: + AccountTypeIsInvalid: Final = "93538" + AccountTypeNotSupported: Final = "93543" + AmountCannotBeNegative: Final = "93535" + AmountFormatIsInvalid: Final = "93534" + AmountIsTooLarge: Final = "93537" + AmountNotSupportedByProcessor: Final = "93536" + MerchantAccountIdIsInvalid: Final = "93540" + MerchantAccountIsSuspended: Final = "93541" + NotSupportedByProcessor: Final = "93533" + class AuthorizationFingerprint: - MissingFingerprint: str - InvalidFormat: str - SignatureRevoked: str - InvalidCreatedAt: str - InvalidPublicKey: str - InvalidSignature: str - OptionsNotAllowedWithoutCustomer: str + MissingFingerprint: Final = "93201" + InvalidFormat: Final = "93202" + SignatureRevoked: Final = "93203" + InvalidCreatedAt: Final = "93204" + InvalidPublicKey: Final = "93205" + InvalidSignature: Final = "93206" + OptionsNotAllowedWithoutCustomer: Final = "93207" + class ClientToken: - MakeDefaultRequiresCustomerId: str - VerifyCardRequiresCustomerId: str - FailOnDuplicatePaymentMethodRequiresCustomerId: str - CustomerDoesNotExist: str - ProxyMerchantDoesNotExist: str - UnsupportedVersion: str - MerchantAccountDoesNotExist: str + CustomerDoesNotExist: Final = "92804" + FailOnDuplicatePaymentMethodRequiresCustomerId: Final = "92803" + FailOnDuplicatePaymentMethodForCustomerRequiresCustomerId: Final = "92805" + InvalidDomainFormat: Final = "92011" + MakeDefaultRequiresCustomerId: Final = "92801" + MerchantAccountDoesNotExist: Final = "92807" + ProxyMerchantDoesNotExist: Final = "92805" + TooManyDomains: Final = "92810" + UnsupportedVersion: Final = "92806" + VerifyCardRequiresCustomerId: Final = "92802" + class CreditCard: - BillingAddressConflict: str - BillingAddressFormatIsInvalid: str - BillingAddressIdIsInvalid: str - CannotUpdateCardUsingPaymentMethodNonce: str - CardholderNameIsTooLong: str - CreditCardTypeIsNotAccepted: str - CreditCardTypeIsNotAcceptedBySubscriptionMerchantAccount: str - CustomerIdIsInvalid: str - CustomerIdIsRequired: str - CvvIsInvalid: str - CvvIsRequired: str - CvvVerificationFailed: str - DuplicateCardExists: str - ExpirationDateConflict: str - ExpirationDateIsInvalid: str - ExpirationDateIsRequired: str - ExpirationDateYearIsInvalid: str - ExpirationMonthIsInvalid: str - ExpirationYearIsInvalid: str - InvalidParamsForCreditCardUpdate: str - InvalidVenmoSDKPaymentMethodCode: str - NumberHasInvalidLength: str - NumberLengthIsInvalid: str - NumberIsInvalid: str - NumberIsProhibited: str - NumberIsRequired: str - NumberMustBeTestNumber: str - PaymentMethodConflict: str - PaymentMethodIsNotACreditCard: str - PaymentMethodNonceCardTypeIsNotAccepted: str - PaymentMethodNonceConsumed: str - PaymentMethodNonceLocked: str - PaymentMethodNonceUnknown: str - PostalCodeVerificationFailed: str - TokenInvalid: str - TokenFormatIsInvalid: str - TokenIsInUse: str - TokenIsNotAllowed: str - TokenIsRequired: str - TokenIsTooLong: str - VenmoSDKPaymentMethodCodeCardTypeIsNotAccepted: str - VerificationNotSupportedOnThisMerchantAccount: str - VerificationAccountTypeIsInvald: str - VerificationAccountTypeNotSupported: str + BillingAddressConflict: Final = "91701" + BillingAddressFormatIsInvalid: Final = "91744" + BillingAddressIdIsInvalid: Final = "91702" + CannotUpdateCardUsingPaymentMethodNonce: Final = "91735" + CardholderNameIsTooLong: Final = "81723" + CreditCardTypeIsNotAccepted: Final = "81703" + CreditCardTypeIsNotAcceptedBySubscriptionMerchantAccount: Final = "81718" + CustomerIdIsInvalid: Final = "91705" + CustomerIdIsRequired: Final = "91704" + CvvIsInvalid: Final = "81707" + CvvIsRequired: Final = "81706" + CvvVerificationFailed: Final = "81736" + DuplicateCardExists: Final = "81724" + DuplicateCardExistsForCustomer: Final = "81763" + ExpirationDateConflict: Final = "91708" + ExpirationDateIsInvalid: Final = "81710" + ExpirationDateIsRequired: Final = "81709" + ExpirationDateYearIsInvalid: Final = "81711" + ExpirationMonthIsInvalid: Final = "81712" + ExpirationYearIsInvalid: Final = "81713" + InvalidParamsForCreditCardUpdate: Final = "91745" + InvalidVenmoSDKPaymentMethodCode: Final = "91727" + LimitExceededforDuplicatePaymentMethodCheckForCustomer: Final = "81764" + NetworkTokenizationAttributeCryptogramIsRequired: Final = "81762" + NumberHasInvalidLength: Final = "81716" + NumberLengthIsInvalid: Final = "81716" + NumberIsInvalid: Final = "81715" + NumberIsProhibited: Final = "81750" + NumberIsRequired: Final = "81714" + NumberMustBeTestNumber: Final = "81717" + PaymentMethodConflict: Final = "81725" + PaymentMethodIsNotACreditCard: Final = "91738" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "91734" + PaymentMethodNonceConsumed: Final = "91731" + PaymentMethodNonceLocked: Final = "91733" + PaymentMethodNonceUnknown: Final = "91732" + PostalCodeVerificationFailed: Final = "81737" + TokenInvalid: Final = "91718" + TokenFormatIsInvalid: Final = "91718" + TokenIsInUse: Final = "91719" + TokenIsNotAllowed: Final = "91721" + TokenIsRequired: Final = "91722" + TokenIsTooLong: Final = "91720" + VenmoSDKPaymentMethodCodeCardTypeIsNotAccepted: Final = "91726" + VerificationNotSupportedOnThisMerchantAccount: Final = "91730" + VerificationAccountTypeIsInvald: Final = "91757" + VerificationAccountTypeNotSupported: Final = "91758" + class Options: - UpdateExistingTokenIsInvalid: str - UpdateExistingTokenNotAllowed: str - VerificationAmountCannotBeNegative: str - VerificationAmountFormatIsInvalid: str - VerificationAmountIsTooLarge: str - VerificationAmountNotSupportedByProcessor: str - VerificationMerchantAccountIdIsInvalid: str - VerificationMerchantAccountIsForbidden: str - VerificationMerchantAccountIsSuspended: str - VerificationMerchantAccountCannotBeSubMerchantAccount: str + UpdateExistingTokenIsInvalid: Final = "91723" + UpdateExistingTokenNotAllowed: Final = "91729" + VerificationAmountCannotBeNegative: Final = "91739" + VerificationAmountFormatIsInvalid: Final = "91740" + VerificationAmountIsTooLarge: Final = "91752" + VerificationAmountNotSupportedByProcessor: Final = "91741" + VerificationMerchantAccountIdIsInvalid: Final = "91728" + VerificationMerchantAccountIsForbidden: Final = "91743" + VerificationMerchantAccountIsSuspended: Final = "91742" + class Customer: - CompanyIsTooLong: str - CustomFieldIsInvalid: str - CustomFieldIsTooLong: str - EmailIsInvalid: str - EmailFormatIsInvalid: str - EmailIsRequired: str - EmailIsTooLong: str - FaxIsTooLong: str - FirstNameIsTooLong: str - IdIsInUse: str - IdIsInvalid: str - IdIsNotAllowed: str - IdIsRequired: str - IdIsTooLong: str - LastNameIsTooLong: str - PhoneIsTooLong: str - VaultedPaymentInstrumentNonceBelongsToDifferentCustomer: str - WebsiteIsInvalid: str - WebsiteFormatIsInvalid: str - WebsiteIsTooLong: str + CompanyIsTooLong: Final = "81601" + CustomFieldIsInvalid: Final = "91602" + CustomFieldIsTooLong: Final = "81603" + EmailIsInvalid: Final = "81604" + EmailFormatIsInvalid: Final = "81604" + EmailIsRequired: Final = "81606" + EmailIsTooLong: Final = "81605" + FaxIsTooLong: Final = "81607" + FirstNameIsTooLong: Final = "81608" + IdIsInUse: Final = "91609" + IdIsInvalid: Final = "91610" + IdIsNotAllowed: Final = "91611" + IdIsRequired: Final = "91613" + IdIsTooLong: Final = "91612" + InternationalPhoneCountryCodeIsInvalid: Final = "91625" + InternationalPhoneNationalNumberIsInvalid: Final = "91626" + LastNameIsTooLong: Final = "81613" + PhoneIsTooLong: Final = "81614" + VaultedPaymentInstrumentNonceBelongsToDifferentCustomer: Final = "91617" + WebsiteIsInvalid: Final = "81616" + WebsiteFormatIsInvalid: Final = "81616" + WebsiteIsTooLong: Final = "81615" + class Descriptor: - DynamicDescriptorsDisabled: str - InternationalNameFormatIsInvalid: str - InternationalPhoneFormatIsInvalid: str - NameFormatIsInvalid: str - PhoneFormatIsInvalid: str - UrlFormatIsInvalid: str + DynamicDescriptorsDisabled: Final = "92203" + InternationalNameFormatIsInvalid: Final = "92204" + InternationalPhoneFormatIsInvalid: Final = "92205" + NameFormatIsInvalid: Final = "92201" + PhoneFormatIsInvalid: Final = "92202" + UrlFormatIsInvalid: Final = "92206" + class Dispute: - CanOnlyAddEvidenceToOpenDispute: str - CanOnlyRemoveEvidenceFromOpenDispute: str - CanOnlyAddEvidenceDocumentToDispute: str - CanOnlyAcceptOpenDispute: str - CanOnlyFinalizeOpenDispute: str - CanOnlyCreateEvidenceWithValidCategory: str - EvidenceContentDateInvalid: str - EvidenceContentTooLong: str - EvidenceContentARNTooLong: str - EvidenceContentPhoneTooLong: str - EvidenceCategoryTextOnly: str - EvidenceCategoryDocumentOnly: str - EvidenceCategoryNotForReasonCode: str - EvidenceCategoryDuplicate: str - EvidenceContentEmailInvalid: str - DigitalGoodsMissingEvidence: str - DigitalGoodsMissingDownloadDate: str - NonDisputedPriorTransactionEvidenceMissingARN: str - NonDisputedPriorTransactionEvidenceMissingDate: str - RecurringTransactionEvidenceMissingDate: str - RecurringTransactionEvidenceMissingARN: str - ValidEvidenceRequiredToFinalize: str + CanOnlyAddEvidenceToOpenDispute: Final = "95701" + CanOnlyRemoveEvidenceFromOpenDispute: Final = "95702" + CanOnlyAddEvidenceDocumentToDispute: Final = "95703" + CanOnlyAcceptOpenDispute: Final = "95704" + CanOnlyFinalizeOpenDispute: Final = "95705" + CanOnlyCreateEvidenceWithValidCategory: Final = "95706" + EvidenceContentDateInvalid: Final = "95707" + EvidenceContentTooLong: Final = "95708" + EvidenceContentARNTooLong: Final = "95709" + EvidenceContentPhoneTooLong: Final = "95710" + EvidenceCategoryTextOnly: Final = "95711" + EvidenceCategoryDocumentOnly: Final = "95712" + EvidenceCategoryNotForReasonCode: Final = "95713" + EvidenceCategoryDuplicate: Final = "95714" + EvidenceContentEmailInvalid: Final = "95715" + DigitalGoodsMissingEvidence: Final = "95720" + DigitalGoodsMissingDownloadDate: Final = "95721" + NonDisputedPriorTransactionEvidenceMissingARN: Final = "95722" + NonDisputedPriorTransactionEvidenceMissingDate: Final = "95723" + RecurringTransactionEvidenceMissingDate: Final = "95724" + RecurringTransactionEvidenceMissingARN: Final = "95725" + ValidEvidenceRequiredToFinalize: Final = "95726" + class DocumentUpload: - KindIsInvalid: str - FileIsTooLarge: str - FileTypeIsInvalid: str - FileIsMalformedOrEncrypted: str - FileIsTooLong: str - FileIsEmpty: str + KindIsInvalid: Final = "84901" + FileIsTooLarge: Final = "84902" + FileTypeIsInvalid: Final = "84903" + FileIsMalformedOrEncrypted: Final = "84904" + FileIsTooLong: Final = "84905" + FileIsEmpty: Final = "84906" + class Merchant: - CountryCannotBeBlank: str - CountryCodeAlpha2IsInvalid: str - CountryCodeAlpha2IsNotAccepted: str - CountryCodeAlpha3IsInvalid: str - CountryCodeAlpha3IsNotAccepted: str - CountryCodeNumericIsInvalid: str - CountryCodeNumericIsNotAccepted: str - CountryNameIsInvalid: str - CountryNameIsNotAccepted: str - CurrenciesAreInvalid: str - EmailFormatIsInvalid: str - EmailIsRequired: str - InconsistentCountry: str - PaymentMethodsAreInvalid: str - PaymentMethodsAreNotAllowed: str - MerchantAccountExistsForCurrency: str - CurrencyIsRequired: str - CurrencyIsInvalid: str - NoMerchantAccounts: str - MerchantAccountExistsForId: str + CountryCannotBeBlank: Final = "83603" + CountryCodeAlpha2IsInvalid: Final = "93607" + CountryCodeAlpha2IsNotAccepted: Final = "93606" + CountryCodeAlpha3IsInvalid: Final = "93605" + CountryCodeAlpha3IsNotAccepted: Final = "93604" + CountryCodeNumericIsInvalid: Final = "93609" + CountryCodeNumericIsNotAccepted: Final = "93608" + CountryNameIsInvalid: Final = "93611" + CountryNameIsNotAccepted: Final = "93610" + CurrenciesAreInvalid: Final = "93614" + EmailFormatIsInvalid: Final = "93602" + EmailIsRequired: Final = "83601" + InconsistentCountry: Final = "93612" + PaymentMethodsAreInvalid: Final = "93613" + PaymentMethodsAreNotAllowed: Final = "93615" + MerchantAccountExistsForCurrency: Final = "93616" + CurrencyIsRequired: Final = "93617" + CurrencyIsInvalid: Final = "93618" + NoMerchantAccounts: Final = "93619" + MerchantAccountExistsForId: Final = "93620" + class MerchantAccount: - IdFormatIsInvalid: str - IdIsInUse: str - IdIsNotAllowed: str - IdIsTooLong: str - MasterMerchantAccountIdIsInvalid: str - MasterMerchantAccountIdIsRequired: str - MasterMerchantAccountMustBeActive: str - TosAcceptedIsRequired: str - CannotBeUpdated: str - IdCannotBeUpdated: str - MasterMerchantAccountIdCannotBeUpdated: str - Declined: str - DeclinedMasterCardMatch: str - DeclinedOFAC: str - DeclinedFailedKYC: str - DeclinedSsnInvalid: str - DeclinedSsnMatchesDeceased: str class ApplicantDetails: - AccountNumberIsRequired: str - CompanyNameIsInvalid: str - CompanyNameIsRequiredWithTaxId: str - DateOfBirthIsRequired: str - Declined: str - DeclinedMasterCardMatch: str - DeclinedOFAC: str - DeclinedFailedKYC: str - DeclinedSsnInvalid: str - DeclinedSsnMatchesDeceased: str - EmailAddressIsInvalid: str - FirstNameIsInvalid: str - FirstNameIsRequired: str - LastNameIsInvalid: str - LastNameIsRequired: str - PhoneIsInvalid: str - RoutingNumberIsInvalid: str - RoutingNumberIsRequired: str - SsnIsInvalid: str - TaxIdIsInvalid: str - TaxIdIsRequiredWithCompanyName: str - DateOfBirthIsInvalid: str - EmailAddressIsRequired: str - AccountNumberIsInvalid: str - TaxIdMustBeBlank: str - class Address: - LocalityIsRequired: str - PostalCodeIsInvalid: str - PostalCodeIsRequired: str - RegionIsRequired: str - StreetAddressIsInvalid: str - StreetAddressIsRequired: str - RegionIsInvalid: str - class Individual: - FirstNameIsRequired: str - LastNameIsRequired: str - DateOfBirthIsRequired: str - SsnIsInvalid: str - EmailAddressIsInvalid: str - FirstNameIsInvalid: str - LastNameIsInvalid: str - PhoneIsInvalid: str - DateOfBirthIsInvalid: str - EmailAddressIsRequired: str - class Address: - StreetAddressIsRequired: str - LocalityIsRequired: str - PostalCodeIsRequired: str - RegionIsRequired: str - StreetAddressIsInvalid: str - PostalCodeIsInvalid: str - RegionIsInvalid: str - class Business: - DbaNameIsInvalid: str - LegalNameIsInvalid: str - LegalNameIsRequiredWithTaxId: str - TaxIdIsInvalid: str - TaxIdIsRequiredWithLegalName: str - TaxIdMustBeBlank: str - class Address: - StreetAddressIsInvalid: str - PostalCodeIsInvalid: str - RegionIsInvalid: str - class Funding: - RoutingNumberIsRequired: str - AccountNumberIsRequired: str - RoutingNumberIsInvalid: str - AccountNumberIsInvalid: str - DestinationIsInvalid: str - DestinationIsRequired: str - EmailAddressIsInvalid: str - EmailAddressIsRequired: str - MobilePhoneIsInvalid: str - MobilePhoneIsRequired: str + Declined: Final = "82626" + DeclinedMasterCardMatch: Final = "82622" + DeclinedOFAC: Final = "82621" + DeclinedFailedKYC: Final = "82623" + DeclinedSsnInvalid: Final = "82624" + DeclinedSsnMatchesDeceased: Final = "82625" + class OAuth: - InvalidGrant: str - InvalidCredentials: str - InvalidScope: str - InvalidRequest: str - UnsupportedGrantType: str + InvalidGrant: Final = "93801" + InvalidCredentials: Final = "93802" + InvalidScope: Final = "93803" + InvalidRequest: Final = "93804" + UnsupportedGrantType: Final = "93805" + class Verification: - ThreeDSecureAuthenticationIdIsInvalid: str - ThreeDSecureAuthenticationIdDoesntMatchNonceThreeDSecureAuthentication: str - ThreeDSecureTransactionPaymentMethodDoesntMatchThreeDSecureAuthenticationPaymentMethod: str - ThreeDSecureAuthenticationIdWithThreeDSecurePassThruIsInvalid: str - ThreeDSecureAuthenticationFailed: str - ThreeDSecureTokenIsInvalid: str - ThreeDSecureVerificationDataDoesntMatchVerify: str - MerchantAccountDoesNotSupport3DSecure: str - MerchantAcountDoesNotMatch3DSecureMerchantAccount: str - AmountDoesNotMatch3DSecureAmount: str + ThreeDSecureAuthenticationIdIsInvalid: Final = "942196" + ThreeDSecureAuthenticationIdDoesntMatchNonceThreeDSecureAuthentication: Final = "942198" + ThreeDSecureTransactionPaymentMethodDoesntMatchThreeDSecureAuthenticationPaymentMethod: Final = "942197" + ThreeDSecureAuthenticationIdWithThreeDSecurePassThruIsInvalid: Final = "942199" + ThreeDSecureAuthenticationFailed: Final = "94271" + ThreeDSecureTokenIsInvalid: Final = "94268" + ThreeDSecureVerificationDataDoesntMatchVerify: Final = "94270" + MerchantAccountDoesNotSupport3DSecure: Final = "942169" + MerchantAcountDoesNotMatch3DSecureMerchantAccount: Final = "94284" + AmountDoesNotMatch3DSecureAmount: Final = "94285" + class ThreeDSecurePassThru: - EciFlagIsRequired: str - EciFlagIsInvalid: str - CavvIsRequired: str - ThreeDSecureVersionIsRequired: str - ThreeDSecureVersionIsInvalid: str - AuthenticationResponseIsInvalid: str - DirectoryResponseIsInvalid: str - CavvAlgorithmIsInvalid: str + EciFlagIsRequired: Final = "942113" + EciFlagIsInvalid: Final = "942114" + CavvIsRequired: Final = "942116" + ThreeDSecureVersionIsRequired: Final = "942117" + ThreeDSecureVersionIsInvalid: Final = "942119" + AuthenticationResponseIsInvalid: Final = "942120" + DirectoryResponseIsInvalid: Final = "942121" + CavvAlgorithmIsInvalid: Final = "942122" + class Options: - AmountCannotBeNegative: str - AmountFormatIsInvalid: str - AmountIsTooLarge: str - AmountNotSupportedByProcessor: str - MerchantAccountIdIsInvalid: str - MerchantAccountIsSuspended: str - MerchantAccountIsForbidden: str - MerchantAccountCannotBeSubMerchantAccount: str - AccountTypeIsInvalid: str - AccountTypeNotSupported: str + AmountCannotBeNegative: Final = "94201" + AmountFormatIsInvalid: Final = "94202" + AmountIsTooLarge: Final = "94207" + AmountNotSupportedByProcessor: Final = "94203" + MerchantAccountIdIsInvalid: Final = "94204" + MerchantAccountIsSuspended: Final = "94205" + MerchantAccountIsForbidden: Final = "94206" + AccountTypeIsInvalid: Final = "942184" + AccountTypeNotSupported: Final = "942185" + class PaymentMethod: - CannotForwardPaymentMethodType: str - PaymentMethodParamsAreRequired: str - NonceIsInvalid: str - NonceIsRequired: str - CustomerIdIsRequired: str - CustomerIdIsInvalid: str - PaymentMethodNonceConsumed: str - PaymentMethodNonceUnknown: str - PaymentMethodNonceLocked: str - PaymentMethodNoLongerSupported: str - AuthExpired: str - CannotHaveFundingSourceWithoutAccessToken: str - InvalidFundingSourceSelection: str - CannotUpdatePayPalAccountUsingPaymentMethodNonce: str + CannotForwardPaymentMethodType: Final = "93106" + PaymentMethodParamsAreRequired: Final = "93101" + NonceIsInvalid: Final = "93102" + NonceIsRequired: Final = "93103" + CustomerIdIsRequired: Final = "93104" + CustomerIdIsInvalid: Final = "93105" + PaymentMethodNonceConsumed: Final = "93107" + PaymentMethodNonceUnknown: Final = "93108" + PaymentMethodNonceLocked: Final = "93109" + PaymentMethodNoLongerSupported: Final = "93117" + AuthExpired: Final = "92911" + CannotHaveFundingSourceWithoutAccessToken: Final = "92912" + InvalidFundingSourceSelection: Final = "92913" + CannotUpdatePayPalAccountUsingPaymentMethodNonce: Final = "92914" + class Options: - UsBankAccountVerificationMethodIsInvalid: str + UsBankAccountVerificationMethodIsInvalid: Final = "93121" + class PayPalAccount: - CannotHaveBothAccessTokenAndConsentCode: str - CannotVaultOneTimeUsePayPalAccount: str - ConsentCodeOrAccessTokenIsRequired: str - CustomerIdIsRequiredForVaulting: str - InvalidParamsForPayPalAccountUpdate: str - PayPalAccountsAreNotAccepted: str - PayPalCommunicationError: str - PaymentMethodNonceConsumed: str - PaymentMethodNonceLocked: str - PaymentMethodNonceUnknown: str - TokenIsInUse: str + CannotHaveBothAccessTokenAndConsentCode: Final = "82903" + CannotVaultOneTimeUsePayPalAccount: Final = "82902" + ConsentCodeOrAccessTokenIsRequired: Final = "82901" + CustomerIdIsRequiredForVaulting: Final = "82905" + EmailFormatIsInvalid: Final = "92963" + EmailIsTooLong: Final = "92964" + InvalidParamsForPayPalAccountUpdate: Final = "92915" + PayPalAccountsAreNotAccepted: Final = "82904" + PayPalCommunicationError: Final = "92910" + PaymentMethodNonceConsumed: Final = "92907" + PaymentMethodNonceLocked: Final = "92909" + PaymentMethodNonceUnknown: Final = "92908" + TokenIsInUse: Final = "92906" + + class PayPalPaymentResource: + NonceExpired: Final = "97301" + IdNotSupported: Final = "97302" + NonceRequired: Final = "97303" + InvalidEmail: Final = "97304" + EmailTooLong: Final = "97305" + ExpectedLineItemCollection: Final = "97306" + ExpectedLineItemHash: Final = "97307" + ExpectedLineItemDebit: Final = "97308" + InvalidUnitAmount: Final = "97309" + InvalidUnitTaxAmount: Final = "97310" + IsoCodeRequired: Final = "97311" + IsoCodeUnsupported: Final = "97312" + ShippingFieldsMissing: Final = "97313" + InvalidAmountBreakdown: Final = "97314" + ExpectedShippingOptionCollection: Final = "97315" + ShippingOptionsRequired: Final = "97316" + ShippingOptionFieldsMissing: Final = "97317" + InvalidShippingOptionType: Final = "97318" + ShippingOptionIdReused: Final = "97319" + TooManyShippingOptionsSelected: Final = "97320" + ShippingOptionMustMatchBreakdown: Final = "97321" + LineItemsShouldMatchTotal: Final = "97322" + LineItemsTaxShouldMatchTotal: Final = "97323" + PatchCallFailed: Final = "97324" + InvalidAmount: Final = "97325" + ShippingIdTooLong: Final = "97326" + ShippingLabelTooLong: Final = "97327" + ShippingFullNameTooLong: Final = "97328" + ShippingAddressTooLong: Final = "97329" + ShippingExtendedAddressTooLong: Final = "97330" + ShippingLocalityTooLong: Final = "97331" + ShippingRegionTooLong: Final = "97332" + CountryCodeTooLong: Final = "97333" + NationalNumberTooLong: Final = "97334" + PostalCodeTooLong: Final = "97335" + DescriptionTooLong: Final = "97336" + CustomFieldTooLong: Final = "97337" + OrderIdTooLong: Final = "97338" + class SettlementBatchSummary: - CustomFieldIsInvalid: str - SettlementDateIsInvalid: str - SettlementDateIsRequired: str + CustomFieldIsInvalid: Final = "82303" + SettlementDateIsInvalid: Final = "82302" + SettlementDateIsRequired: Final = "82301" + class SEPAMandate: - TypeIsRequired: str - IBANInvalidCharacter: str - BICInvalidCharacter: str - BICLengthIsInvalid: str - BICUnsupportedCountry: str - IBANUnsupportedCountry: str - IBANInvalidFormat: str - BillingAddressConflict: str - BillingAddressIdIsInvalid: str - TypeIsInvalid: str + TypeIsRequired: Final = "93304" + IBANInvalidCharacter: Final = "83305" + BICInvalidCharacter: Final = "83306" + BICLengthIsInvalid: Final = "83307" + BICUnsupportedCountry: Final = "83308" + IBANUnsupportedCountry: Final = "83309" + IBANInvalidFormat: Final = "83310" + BillingAddressConflict: Final = "93311" + BillingAddressIdIsInvalid: Final = "93312" + TypeIsInvalid: Final = "93313" + class EuropeBankAccount: - BICIsRequired: str - IBANIsRequired: str - AccountHolderNameIsRequired: str + BICIsRequired: Final = "83302" + IBANIsRequired: Final = "83303" + AccountHolderNameIsRequired: Final = "83301" + + class SepaDirectDebitAccount: + SepaDebitAccountPaymentMethodMandateTypeIsNotSupported: Final = "87115" + SepaDebitAccountPaymentMethodCustomerIdIsInvalid: Final = "87116" + SepaDebitAccountPaymentMethodCustomerIdIsRequired: Final = "87117" + class Subscription: - BillingDayOfMonthCannotBeUpdated: str - BillingDayOfMonthIsInvalid: str - BillingDayOfMonthMustBeNumeric: str - CannotAddDuplicateAddonOrDiscount: str - CannotEditCanceledSubscription: str - CannotEditExpiredSubscription: str - CannotEditPriceChangingFieldsOnPastDueSubscription: str - FirstBillingDateCannotBeInThePast: str - FirstBillingDateCannotBeUpdated: str - FirstBillingDateIsInvalid: str - IdIsInUse: str - InconsistentNumberOfBillingCycles: str - InconsistentStartDate: str - InvalidRequestFormat: str - MerchantAccountDoesNotSupportInstrumentType: str - MerchantAccountIdIsInvalid: str - MismatchCurrencyISOCode: str - NumberOfBillingCyclesCannotBeBlank: str - NumberOfBillingCyclesIsTooSmall: str - NumberOfBillingCyclesMustBeGreaterThanZero: str - NumberOfBillingCyclesMustBeNumeric: str - PaymentMethodNonceCardTypeIsNotAccepted: str - PaymentMethodNonceInstrumentTypeDoesNotSupportSubscriptions: str - PaymentMethodNonceIsInvalid: str - PaymentMethodNonceNotAssociatedWithCustomer: str - PaymentMethodNonceUnvaultedCardIsNotAccepted: str - PaymentMethodTokenCardTypeIsNotAccepted: str - PaymentMethodTokenInstrumentTypeDoesNotSupportSubscriptions: str - PaymentMethodTokenIsInvalid: str - PaymentMethodTokenNotAssociatedWithCustomer: str - PlanBillingFrequencyCannotBeUpdated: str - PlanIdIsInvalid: str - PriceCannotBeBlank: str - PriceFormatIsInvalid: str - PriceIsTooLarge: str - StatusIsCanceled: str - TokenFormatIsInvalid: str - TrialDurationFormatIsInvalid: str - TrialDurationIsRequired: str - TrialDurationUnitIsInvalid: str + BillingDayOfMonthCannotBeUpdated: Final = "91918" + BillingDayOfMonthIsInvalid: Final = "91914" + BillingDayOfMonthMustBeNumeric: Final = "91913" + CannotAddDuplicateAddonOrDiscount: Final = "91911" + CannotEditCanceledSubscription: Final = "81901" + CannotEditExpiredSubscription: Final = "81910" + CannotEditPriceChangingFieldsOnPastDueSubscription: Final = "91920" + FirstBillingDateCannotBeInThePast: Final = "91916" + FirstBillingDateCannotBeUpdated: Final = "91919" + FirstBillingDateIsInvalid: Final = "91915" + IdIsInUse: Final = "81902" + InconsistentNumberOfBillingCycles: Final = "91908" + InconsistentStartDate: Final = "91917" + InvalidRequestFormat: Final = "91921" + MerchantAccountDoesNotSupportInstrumentType: Final = "91930" + MerchantAccountIdIsInvalid: Final = "91901" + MismatchCurrencyISOCode: Final = "91923" + NumberOfBillingCyclesCannotBeBlank: Final = "91912" + NumberOfBillingCyclesIsTooSmall: Final = "91909" + NumberOfBillingCyclesMustBeGreaterThanZero: Final = "91907" + NumberOfBillingCyclesMustBeNumeric: Final = "91906" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "91924" + PaymentMethodNonceInstrumentTypeDoesNotSupportSubscriptions: Final = "91929" + PaymentMethodNonceIsInvalid: Final = "91925" + PaymentMethodNonceNotAssociatedWithCustomer: Final = "91926" + PaymentMethodNonceUnvaultedCardIsNotAccepted: Final = "91927" + PaymentMethodTokenCardTypeIsNotAccepted: Final = "91902" + PaymentMethodTokenInstrumentTypeDoesNotSupportSubscriptions: Final = "91928" + PaymentMethodTokenIsInvalid: Final = "91903" + PaymentMethodTokenNotAssociatedWithCustomer: Final = "91905" + PlanBillingFrequencyCannotBeUpdated: Final = "91922" + PlanIdIsInvalid: Final = "91904" + PriceCannotBeBlank: Final = "81903" + PriceFormatIsInvalid: Final = "81904" + PriceIsTooLarge: Final = "81923" + StatusIsCanceled: Final = "81905" + TokenFormatIsInvalid: Final = "81906" + TrialDurationFormatIsInvalid: Final = "81907" + TrialDurationIsRequired: Final = "81908" + TrialDurationUnitIsInvalid: Final = "81909" + class Modification: - AmountCannotBeBlank: str - AmountIsInvalid: str - AmountIsTooLarge: str - CannotEditModificationsOnPastDueSubscription: str - CannotUpdateAndRemove: str - ExistingIdIsIncorrectKind: str - ExistingIdIsInvalid: str - ExistingIdIsRequired: str - IdToRemoveIsIncorrectKind: str - IdToRemoveIsNotPresent: str - InconsistentNumberOfBillingCycles: str - InheritedFromIdIsInvalid: str - InheritedFromIdIsRequired: str - Missing: str - NumberOfBillingCyclesCannotBeBlank: str - NumberOfBillingCyclesIsInvalid: str - NumberOfBillingCyclesMustBeGreaterThanZero: str - QuantityCannotBeBlank: str - QuantityIsInvalid: str - QuantityMustBeGreaterThanZero: str - IdToRemoveIsInvalid: str + AmountCannotBeBlank: Final = "92003" + AmountIsInvalid: Final = "92002" + AmountIsTooLarge: Final = "92023" + CannotEditModificationsOnPastDueSubscription: Final = "92022" + CannotUpdateAndRemove: Final = "92015" + ExistingIdIsIncorrectKind: Final = "92020" + ExistingIdIsInvalid: Final = "92011" + ExistingIdIsRequired: Final = "92012" + IdToRemoveIsIncorrectKind: Final = "92021" + IdToRemoveIsNotPresent: Final = "92016" + InconsistentNumberOfBillingCycles: Final = "92018" + InheritedFromIdIsInvalid: Final = "92013" + InheritedFromIdIsRequired: Final = "92014" + Missing: Final = "92024" + NumberOfBillingCyclesCannotBeBlank: Final = "92017" + NumberOfBillingCyclesIsInvalid: Final = "92005" + NumberOfBillingCyclesMustBeGreaterThanZero: Final = "92019" + QuantityCannotBeBlank: Final = "92004" + QuantityIsInvalid: Final = "92001" + QuantityMustBeGreaterThanZero: Final = "92010" + IdToRemoveIsInvalid: Final = "92025" + class Transaction: - AdjustmentAmountMustBeGreaterThanZero: str - AmountCannotBeNegative: str - AmountDoesNotMatch3DSecureAmount: str - AmountIsInvalid: str - AmountFormatIsInvalid: str - AmountIsRequired: str - AmountIsTooLarge: str - AmountMustBeGreaterThanZero: str - AmountNotSupportedByProcessor: str - BillingAddressConflict: str - BillingPhoneNumberIsInvalid: str - CannotBeVoided: str - CannotCancelRelease: str - CannotCloneCredit: str - CannotCloneMarketplaceTransaction: str - CannotCloneTransactionWithPayPalAccount: str - CannotCloneTransactionWithVaultCreditCard: str - CannotCloneUnsuccessfulTransaction: str - CannotCloneVoiceAuthorizations: str - CannotHoldInEscrow: str - CannotPartiallyRefundEscrowedTransaction: str - CannotRefundCredit: str - CannotRefundSettlingTransaction: str - CannotRefundUnlessSettled: str - CannotRefundWithPendingMerchantAccount: str - CannotRefundWithSuspendedMerchantAccount: str - CannotReleaseFromEscrow: str - CannotSimulateTransactionSettlement: str - CannotSubmitForPartialSettlement: str - CannotSubmitForSettlement: str - CannotUpdateTransactionDetailsNotSubmittedForSettlement: str - ChannelIsTooLong: str - CreditCardIsRequired: str - CustomFieldIsInvalid: str - CustomFieldIsTooLong: str - CustomerDefaultPaymentMethodCardTypeIsNotAccepted: str - CustomerDoesNotHaveCreditCard: str - CustomerIdIsInvalid: str - DiscountAmountCannotBeNegative: str - DiscountAmountFormatIsInvalid: str - DiscountAmountIsTooLarge: str - ExchangeRateQuoteIdIsTooLong: str - FailedAuthAdjustmentAllowRetry: str - FailedAuthAdjustmentHardDecline: str - FinalAuthSubmitForSettlementForDifferentAmount: str - HasAlreadyBeenRefunded: str - LineItemsExpected: str - MerchantAccountDoesNotMatch3DSecureMerchantAccount: str - MerchantAccountDoesNotSupportMOTO: str - MerchantAccountDoesNotSupportRefunds: str - MerchantAccountIdDoesNotMatchSubscription: str - MerchantAccountIdIsInvalid: str - MerchantAccountIsSuspended: str - NoNetAmountToPerformAuthAdjustment: str - OrderIdIsTooLong: str - PayPalAuthExpired: str - PayPalNotEnabled: str - PayPalVaultRecordMissingData: str - PaymentInstrumentNotSupportedByMerchantAccount: str - PaymentInstrumentTypeIsNotAccepted: str - PaymentInstrumentWithExternalVaultIsInvalid: str - PaymentMethodConflict: str - PaymentMethodConflictWithVenmoSDK: str - PaymentMethodDoesNotBelongToCustomer: str - PaymentMethodDoesNotBelongToSubscription: str - PaymentMethodNonceCardTypeIsNotAccepted: str - PaymentMethodNonceConsumed: str - PaymentMethodNonceHasNoValidPaymentInstrumentType: str - PaymentMethodNonceLocked: str - PaymentMethodNonceUnknown: str - PaymentMethodTokenCardTypeIsNotAccepted: str - PaymentMethodTokenIsInvalid: str - ProcessorAuthorizationCodeCannotBeSet: str - ProcessorAuthorizationCodeIsInvalid: str - ProcessorDoesNotSupportAuths: str - ProcessorDoesNotSupportAuthAdjustment: str - ProcessorDoesNotSupportCredits: str - ProcessorDoesNotSupportIncrementalAuth: str - ProcessorDoesNotSupportMotoForCardType: str - ProcessorDoesNotSupportPartialAuthReversal: str - ProcessorDoesNotSupportPartialSettlement: str - ProcessorDoesNotSupportUpdatingDescriptor: str - ProcessorDoesNotSupportUpdatingOrderId: str - ProcessorDoesNotSupportUpdatingTransactionDetails: str - ProcessorDoesNotSupportVoiceAuthorizations: str - ProductSkuIsInvalid: str - PurchaseOrderNumberIsInvalid: str - PurchaseOrderNumberIsTooLong: str - RefundAmountIsTooLarge: str - RefundAuthHardDeclined: str - RefundAuthSoftDeclined: str - ScaExemptionInvalid: str - ServiceFeeAmountCannotBeNegative: str - ServiceFeeAmountFormatIsInvalid: str - ServiceFeeAmountIsTooLarge: str - ServiceFeeAmountNotAllowedOnMasterMerchantAccount: str - ServiceFeeIsNotAllowedOnCredits: str - ServiceFeeNotAcceptedForPayPal: str - SettlementAmountIsLessThanServiceFeeAmount: str - SettlementAmountIsTooLarge: str - ShippingAddressDoesntMatchCustomer: str - ShippingAmountCannotBeNegative: str - ShippingAmountFormatIsInvalid: str - ShippingAmountIsTooLarge: str - ShippingMethodIsInvalid: str - ShippingPhoneNumberIsInvalid: str - ShipsFromPostalCodeInvalidCharacters: str - ShipsFromPostalCodeIsInvalid: str - ShipsFromPostalCodeIsTooLong: str - SubMerchantAccountRequiresServiceFeeAmount: str - SubscriptionDoesNotBelongToCustomer: str - SubscriptionIdIsInvalid: str - SubscriptionStatusMustBePastDue: str - TaxAmountCannotBeNegative: str - TaxAmountFormatIsInvalid: str - TaxAmountIsRequiredForAibSwedish: str - TaxAmountIsTooLarge: str - ThreeDSecureAuthenticationFailed: str - ThreeDSecureAuthenticationIdDoesntMatchNonceThreeDSecureAuthentication: str - ThreeDSecureAuthenticationIdIsInvalid: str - ThreeDSecureAuthenticationIdWithThreeDSecurePassThruIsInvalid: str - ThreeDSecureAuthenticationResponseIsInvalid: str - ThreeDSecureCavvAlgorithmIsInvalid: str - ThreeDSecureCavvIsRequired: str - ThreeDSecureDirectoryResponseIsInvalid: str - ThreeDSecureEciFlagIsInvalid: str - ThreeDSecureEciFlagIsRequired: str - ThreeDSecureMerchantAccountDoesNotSupportCardType: str - ThreeDSecureTokenIsInvalid: str - ThreeDSecureTransactionDataDoesntMatchVerify: str - ThreeDSecureTransactionPaymentMethodDoesntMatchThreeDSecureAuthenticationPaymentMethod: str - ThreeDSecureXidIsRequired: str - TooManyLineItems: str - TransactionIsNotEligibleForAdjustment: str - TransactionMustBeInStateAuthorized: str - TransactionSourceIsInvalid: str - TypeIsInvalid: str - TypeIsRequired: str - UnsupportedVoiceAuthorization: str - UsBankAccountNonceMustBePlaidVerified: str - UsBankAccountNotVerified: str + OriginalTransactionNotSurcharged: Final = "97605" + AmountCannotBeNegative: Final = "81501" + AmountDoesNotMatch3DSecureAmount: Final = "91585" + AmountIsInvalid: Final = "81503" + AmountFormatIsInvalid: Final = "81503" + AmountIsRequired: Final = "81502" + AmountIsTooLarge: Final = "81528" + AmountMustBeGreaterThanZero: Final = "81531" + AmountNotSupportedByProcessor: Final = "815193" + BillingAddressConflict: Final = "91530" + BillingPhoneNumberIsInvalid: Final = "915206" + CannotBeVoided: Final = "91504" + CannotCancelRelease: Final = "91562" + CannotCloneCredit: Final = "91543" + CannotCloneMarketplaceTransaction: Final = "915137" + CannotCloneThirdPartyCofNetworkTokenTransaction: Final = "915274" + CannotCloneTransactionWithPayPalAccount: Final = "91573" + CannotCloneTransactionWithVaultCreditCard: Final = "91540" + CannotCloneUnsuccessfulTransaction: Final = "91542" + CannotCloneVoiceAuthorizations: Final = "91541" + CannotRefundCredit: Final = "91505" + CannotRefundSettlingTransaction: Final = "91574" + CannotRefundUnlessSettled: Final = "91506" + CannotRefundWithPendingMerchantAccount: Final = "91559" + CannotRefundWithSuspendedMerchantAccount: Final = "91538" + CannotSimulateTransactionSettlement: Final = "91575" + CannotSubmitForPartialSettlement: Final = "915103" + CannotSubmitForSettlement: Final = "91507" + CannotUpdateTransactionDetailsNotSubmittedForSettlement: Final = "915129" + ChannelIsTooLong: Final = "91550" + CreditCardIsRequired: Final = "91508" + CustomFieldIsInvalid: Final = "91526" + CustomFieldIsTooLong: Final = "81527" + CustomerDefaultPaymentMethodCardTypeIsNotAccepted: Final = "81509" + CustomerDoesNotHaveCreditCard: Final = "91511" + CustomerIdIsInvalid: Final = "91510" + DiscountAmountCannotBeNegative: Final = "915160" + DiscountAmountFormatIsInvalid: Final = "915159" + DiscountAmountIsTooLarge: Final = "915161" + ExchangeRateQuoteIdIsTooLong: Final = "915229" + ApiRequestKeyTooLong: Final = "915230" + ApiRequestKeyNotAllowed: Final = "915231" + ApiRequestKeyCanBeReusedOnlyWithTheSameRequest: Final = "915232" + ApiRequestKeyIsInFlight: Final = "915233" + ApiRequestKeyWithFailedRequest: Final = "915234" + ApiRequestKeyServerError: Final = "915235" + FailedAuthAdjustmentAllowRetry: Final = "95603" + FailedAuthAdjustmentHardDecline: Final = "95602" + FinalAuthSubmitForSettlementForDifferentAmount: Final = "95601" + HasAlreadyBeenRefunded: Final = "91512" + LineItemsExpected: Final = "915158" + MerchantAccountDoesNotMatch3DSecureMerchantAccount: Final = "91584" + MerchantAccountDoesNotSupportMOTO: Final = "91558" + MerchantAccountDoesNotSupportRefunds: Final = "91547" + MerchantAccountIdDoesNotMatchSubscription: Final = "915180" + MerchantAccountIdIsInvalid: Final = "91513" + MerchantAccountIsSuspended: Final = "91514" + NoNetAmountToPerformAuthAdjustment: Final = "95606" + OrderIdIsTooLong: Final = "91501" + PayPalAuthExpired: Final = "91579" + PayPalNotEnabled: Final = "91576" + PayPalVaultRecordMissingData: Final = "91583" + PaymentInstrumentNotSupportedByMerchantAccount: Final = "91577" + PaymentInstrumentTypeIsNotAccepted: Final = "915101" + PaymentInstrumentWithExternalVaultIsInvalid: Final = "915176" + PaymentMethodConflict: Final = "91515" + PaymentMethodConflictWithVenmoSDK: Final = "91549" + PaymentMethodDoesNotBelongToCustomer: Final = "91516" + PaymentMethodDoesNotBelongToSubscription: Final = "91527" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "91567" + PaymentMethodNonceConsumed: Final = "91564" + PaymentMethodNonceHasNoValidPaymentInstrumentType: Final = "91569" + PaymentMethodNonceLocked: Final = "91566" + PaymentMethodNonceUnknown: Final = "91565" + PaymentMethodTokenCardTypeIsNotAccepted: Final = "91517" + PaymentMethodTokenIsInvalid: Final = "91518" + ProcessingMerchantCategoryCodeIsInvalid: Final = "915265" + ProcessorAuthorizationCodeCannotBeSet: Final = "91519" + ProcessorAuthorizationCodeIsInvalid: Final = "81520" + ProcessorDoesNotSupportAuths: Final = "915104" + ProcessorDoesNotSupportAuthAdjustment: Final = "915222" + ProcessorDoesNotSupportCredits: Final = "91546" + ProcessorDoesNotSupportIncrementalAuth: Final = "915220" + ProcessorDoesNotSupportMotoForCardType: Final = "915195" + ProcessorDoesNotSupportPartialAuthReversal: Final = "915221" + ProcessorDoesNotSupportPartialSettlement: Final = "915102" + ProcessorDoesNotSupportUpdatingDescriptor: Final = "915108" + ProcessorDoesNotSupportUpdatingOrderId: Final = "915107" + ProcessorDoesNotSupportUpdatingTransactionDetails: Final = "915130" + ProcessorDoesNotSupportVoiceAuthorizations: Final = "91545" + ProductSkuIsInvalid: Final = "915202" + PurchaseOrderNumberIsInvalid: Final = "91548" + PurchaseOrderNumberIsTooLong: Final = "91537" + RefundAmountIsTooLarge: Final = "91521" + RefundAuthHardDeclined: Final = "915200" + RefundAuthSoftDeclined: Final = "915201" + ScaExemptionInvalid: Final = "915213" + ServiceFeeAmountCannotBeNegative: Final = "91554" + ServiceFeeAmountFormatIsInvalid: Final = "91555" + ServiceFeeAmountIsTooLarge: Final = "91556" + ServiceFeeAmountNotAllowedOnMasterMerchantAccount: Final = "91557" + ServiceFeeIsNotAllowedOnCredits: Final = "91552" + ServiceFeeNotAcceptedForPayPal: Final = "91578" + SettlementAmountIsLessThanServiceFeeAmount: Final = "91551" + SettlementAmountIsTooLarge: Final = "91522" + ShippingAddressDoesntMatchCustomer: Final = "91581" + ShippingAmountCannotBeNegative: Final = "915163" + ShippingAmountFormatIsInvalid: Final = "915162" + ShippingAmountIsTooLarge: Final = "915164" + ShippingMethodIsInvalid: Final = "915203" + ShippingPhoneNumberIsInvalid: Final = "915204" + ShipsFromPostalCodeInvalidCharacters: Final = "915167" + ShipsFromPostalCodeIsInvalid: Final = "915166" + ShipsFromPostalCodeIsTooLong: Final = "915165" + SubscriptionDoesNotBelongToCustomer: Final = "91529" + SubscriptionIdIsInvalid: Final = "91528" + SubscriptionStatusMustBePastDue: Final = "91531" + TaxAmountCannotBeNegative: Final = "81534" + TaxAmountFormatIsInvalid: Final = "81535" + TaxAmountIsRequiredForAibSwedish: Final = "815224" + TaxAmountIsTooLarge: Final = "81536" + ThreeDSecureAuthenticationFailed: Final = "81571" + ThreeDSecureAuthenticationIdDoesntMatchNonceThreeDSecureAuthentication: Final = "915198" + ThreeDSecureAuthenticationIdIsInvalid: Final = "915196" + ThreeDSecureAuthenticationIdWithThreeDSecurePassThruIsInvalid: Final = "915199" + ThreeDSecureAuthenticationResponseIsInvalid: Final = "915120" + ThreeDSecureCavvAlgorithmIsInvalid: Final = "915122" + ThreeDSecureCavvIsRequired: Final = "915116" + ThreeDSecureDirectoryResponseIsInvalid: Final = "915121" + ThreeDSecureEciFlagIsInvalid: Final = "915114" + ThreeDSecureEciFlagIsRequired: Final = "915113" + ThreeDSecureMerchantAccountDoesNotSupportCardType: Final = "915131" + ThreeDSecureTokenIsInvalid: Final = "91568" + ThreeDSecureTransactionDataDoesntMatchVerify: Final = "91570" + ThreeDSecureTransactionPaymentMethodDoesntMatchThreeDSecureAuthenticationPaymentMethod: Final = "915197" + ThreeDSecureXidIsRequired: Final = "915115" + TooManyLineItems: Final = "915157" + TransactionIsNotEligibleForAdjustment: Final = "915219" + TransactionMustBeInStateAuthorized: Final = "915218" + TransactionSourceIsInvalid: Final = "915133" + TransferDetailsAreNotApplicableForThisMerchantAccount: Final = "97511" + TransferDetailsAreRequired: Final = "97510" + TransferReceiverAccountReferenceNumberIsNotValid: Final = "97509" + TransferReceiverAccountReferenceNumberTypeIsNotValid: Final = "97514" + TransferReceiverFirstNameIsNotValid: Final = "97507" + TransferReceiverLastNameIsNotValid: Final = "97508" + TransferReceiverTaxIdIsNotValid: Final = "97506" + TransferSenderAccountReferenceNumberIsNotValid: Final = "97505" + TransferSenderAccountReferenceNumberTypeIsNotValid: Final = "97513" + TransferSenderFirstNameIsNotValid: Final = "97503" + TransferSenderLastNameIsNotValid: Final = "97504" + TransferSenderTaxIdIsNotValid: Final = "97502" + TransferTypeIsInvalid: Final = "97501" + TypeIsInvalid: Final = "91523" + TypeIsRequired: Final = "91524" + UnsupportedVoiceAuthorization: Final = "91539" + UsBankAccountNonceMustBePlaidVerified: Final = "915171" + UsBankAccountNotVerified: Final = "915172" + class ExternalVault: - StatusIsInvalid: str - StatusWithPreviousNetworkTransactionIdIsInvalid: str - CardTypeIsInvalid: str - PreviousNetworkTransactionIdIsInvalid: str + StatusIsInvalid: Final = "915175" + StatusWithPreviousNetworkTransactionIdIsInvalid: Final = "915177" + CardTypeIsInvalid: Final = "915178" + PreviousNetworkTransactionIdIsInvalid: Final = "915179" + class Options: - SubmitForSettlementIsRequiredForCloning: str - SubmitForSettlementIsRequiredForPayPalUnilateral: str - UseBillingForShippingDisabled: str - VaultIsDisabled: str + SubmitForSettlementIsRequiredForCloning: Final = "91544" + SubmitForSettlementIsRequiredForPayPalUnilateral: Final = "91582" + UseBillingForShippingDisabled: Final = "91572" + VaultIsDisabled: Final = "91525" + class PayPal: - CustomFieldTooLong: str + CustomFieldTooLong: Final = "91580" + class CreditCard: - AccountTypeIsInvalid: str - AccountTypeNotSupported: str - AccountTypeDebitDoesNotSupportAuths: str + AccountTypeIsInvalid: Final = "915184" + AccountTypeNotSupported: Final = "915185" + AccountTypeDebitDoesNotSupportAuths: Final = "915186" + class Industry: - IndustryTypeIsInvalid: str + IndustryTypeIsInvalid: Final = "93401" + class Lodging: - EmptyData: str - FolioNumberIsInvalid: str - CheckInDateIsInvalid: str - CheckOutDateIsInvalid: str - CheckOutDateMustFollowCheckInDate: str - UnknownDataField: str - RoomRateMustBeGreaterThanZero: str - RoomRateFormatIsInvalid: str - RoomRateIsTooLarge: str - RoomTaxMustBeGreaterThanZero: str - RoomTaxFormatIsInvalid: str - RoomTaxIsTooLarge: str - NoShowIndicatorIsInvalid: str - AdvancedDepositIndicatorIsInvalid: str - FireSafetyIndicatorIsInvalid: str - PropertyPhoneIsInvalid: str + EmptyData: Final = "93402" + FolioNumberIsInvalid: Final = "93403" + CheckInDateIsInvalid: Final = "93404" + CheckOutDateIsInvalid: Final = "93405" + CheckOutDateMustFollowCheckInDate: Final = "93406" + UnknownDataField: Final = "93407" + RoomRateMustBeGreaterThanZero: Final = "93433" + RoomRateFormatIsInvalid: Final = "93434" + RoomRateIsTooLarge: Final = "93435" + RoomTaxMustBeGreaterThanZero: Final = "93436" + RoomTaxFormatIsInvalid: Final = "93437" + RoomTaxIsTooLarge: Final = "93438" + NoShowIndicatorIsInvalid: Final = "93439" + AdvancedDepositIndicatorIsInvalid: Final = "93440" + FireSafetyIndicatorIsInvalid: Final = "93441" + PropertyPhoneIsInvalid: Final = "93442" + class TravelCruise: - EmptyData: str - UnknownDataField: str - TravelPackageIsInvalid: str - DepartureDateIsInvalid: str - LodgingCheckInDateIsInvalid: str - LodgingCheckOutDateIsInvalid: str + EmptyData: Final = "93408" + UnknownDataField: Final = "93409" + TravelPackageIsInvalid: Final = "93410" + DepartureDateIsInvalid: Final = "93411" + LodgingCheckInDateIsInvalid: Final = "93412" + LodgingCheckOutDateIsInvalid: Final = "93413" + class TravelFlight: - EmptyData: str - UnknownDataField: str - CustomerCodeIsTooLong: str - FareAmountCannotBeNegative: str - FareAmountFormatIsInvalid: str - FareAmountIsTooLarge: str - FeeAmountCannotBeNegative: str - FeeAmountFormatIsInvalid: str - FeeAmountIsTooLarge: str - IssuedDateFormatIsInvalid: str - IssuingCarrierCodeIsTooLong: str - PassengerMiddleInitialIsTooLong: str - RestrictedTicketIsRequired: str - TaxAmountCannotBeNegative: str - TaxAmountFormatIsInvalid: str - TaxAmountIsTooLarge: str - TicketNumberIsTooLong: str - LegsExpected: str - TooManyLegs: str + EmptyData: Final = "93414" + UnknownDataField: Final = "93415" + CustomerCodeIsTooLong: Final = "93416" + FareAmountCannotBeNegative: Final = "93417" + FareAmountFormatIsInvalid: Final = "93418" + FareAmountIsTooLarge: Final = "93419" + FeeAmountCannotBeNegative: Final = "93420" + FeeAmountFormatIsInvalid: Final = "93421" + FeeAmountIsTooLarge: Final = "93422" + IssuedDateFormatIsInvalid: Final = "93423" + IssuingCarrierCodeIsTooLong: Final = "93424" + PassengerMiddleInitialIsTooLong: Final = "93425" + RestrictedTicketIsRequired: Final = "93426" + TaxAmountCannotBeNegative: Final = "93427" + TaxAmountFormatIsInvalid: Final = "93428" + TaxAmountIsTooLarge: Final = "93429" + TicketNumberIsTooLong: Final = "93430" + LegsExpected: Final = "93431" + TooManyLegs: Final = "93432" + class Leg: class TravelFlight: - ArrivalAirportCodeIsTooLong: str - ArrivalTimeFormatIsInvalid: str - CarrierCodeIsTooLong: str - ConjunctionTicketIsTooLong: str - CouponNumberIsTooLong: str - DepartureAirportCodeIsTooLong: str - DepartureTimeFormatIsInvalid: str - ExchangeTicketIsTooLong: str - FareAmountCannotBeNegative: str - FareAmountFormatIsInvalid: str - FareAmountIsTooLarge: str - FareBasisCodeIsTooLong: str - FeeAmountCannotBeNegative: str - FeeAmountFormatIsInvalid: str - FeeAmountIsTooLarge: str - ServiceClassIsTooLong: str - TaxAmountCannotBeNegative: str - TaxAmountFormatIsInvalid: str - TaxAmountIsTooLarge: str - TicketNumberIsTooLong: str + ArrivalAirportCodeIsTooLong: Final = "96301" + ArrivalTimeFormatIsInvalid: Final = "96302" + CarrierCodeIsTooLong: Final = "96303" + ConjunctionTicketIsTooLong: Final = "96304" + CouponNumberIsTooLong: Final = "96305" + DepartureAirportCodeIsTooLong: Final = "96306" + DepartureTimeFormatIsInvalid: Final = "96307" + ExchangeTicketIsTooLong: Final = "96308" + FareAmountCannotBeNegative: Final = "96309" + FareAmountFormatIsInvalid: Final = "96310" + FareAmountIsTooLarge: Final = "96311" + FareBasisCodeIsTooLong: Final = "96312" + FeeAmountCannotBeNegative: Final = "96313" + FeeAmountFormatIsInvalid: Final = "96314" + FeeAmountIsTooLarge: Final = "96315" + ServiceClassIsTooLong: Final = "96316" + TaxAmountCannotBeNegative: Final = "96317" + TaxAmountFormatIsInvalid: Final = "96318" + TaxAmountIsTooLarge: Final = "96319" + TicketNumberIsTooLong: Final = "96320" + class AdditionalCharge: - KindIsInvalid: str - KindMustBeUnique: str - AmountMustBeGreaterThanZero: str - AmountFormatIsInvalid: str - AmountIsTooLarge: str - AmountIsRequired: str + KindIsInvalid: Final = "96601" + KindMustBeUnique: Final = "96602" + AmountMustBeGreaterThanZero: Final = "96603" + AmountFormatIsInvalid: Final = "96604" + AmountIsTooLarge: Final = "96605" + AmountIsRequired: Final = "96606" + class LineItem: - CommodityCodeIsTooLong: str - DescriptionIsTooLong: str - DiscountAmountFormatIsInvalid: str - DiscountAmountIsTooLarge: str - DiscountAmountCannotBeNegative: str - KindIsInvalid: str - KindIsRequired: str - NameIsRequired: str - NameIsTooLong: str - ProductCodeIsTooLong: str - QuantityFormatIsInvalid: str - QuantityIsRequired: str - QuantityIsTooLarge: str - TotalAmountFormatIsInvalid: str - TotalAmountIsRequired: str - TotalAmountIsTooLarge: str - TotalAmountMustBeGreaterThanZero: str - UnitAmountFormatIsInvalid: str - UnitAmountIsRequired: str - UnitAmountIsTooLarge: str - UnitAmountMustBeGreaterThanZero: str - UnitOfMeasureIsTooLarge: str - UnitTaxAmountFormatIsInvalid: str - UnitTaxAmountIsTooLarge: str - UnitTaxAmountCannotBeNegative: str - TaxAmountFormatIsInvalid: str - TaxAmountIsTooLarge: str - TaxAmountCannotBeNegative: str + CommodityCodeIsTooLong: Final = "95801" + DescriptionIsTooLong: Final = "95803" + DiscountAmountCannotBeNegative: Final = "95806" + DiscountAmountFormatIsInvalid: Final = "95804" + DiscountAmountIsTooLarge: Final = "95805" + KindIsInvalid: Final = "95807" + KindIsRequired: Final = "95808" + NameIsRequired: Final = "95822" + NameIsTooLong: Final = "95823" + ProductCodeIsTooLong: Final = "95809" + QuantityFormatIsInvalid: Final = "95810" + QuantityIsRequired: Final = "95811" + QuantityIsTooLarge: Final = "95812" + TaxAmountCannotBeNegative: Final = "95829" + TaxAmountFormatIsInvalid: Final = "95827" + TaxAmountIsTooLarge: Final = "95828" + TotalAmountFormatIsInvalid: Final = "95813" + TotalAmountIsRequired: Final = "95814" + TotalAmountIsTooLarge: Final = "95815" + TotalAmountMustBeGreaterThanZero: Final = "95816" + UPCCodeIsMissing: Final = "95830" + UPCCodeIsTooLong: Final = "95831" + UPCTypeIsInvalid: Final = "95833" + UPCTypeIsMissing: Final = "95832" + UnitAmountFormatIsInvalid: Final = "95817" + UnitAmountIsRequired: Final = "95818" + UnitAmountIsTooLarge: Final = "95819" + UnitAmountMustBeGreaterThanZero: Final = "95820" + UnitOfMeasureIsTooLarge: Final = "95821" + UnitTaxAmountCannotBeNegative: Final = "95826" + UnitTaxAmountFormatIsInvalid: Final = "95824" + UnitTaxAmountIsTooLarge: Final = "95825" + class UsBankAccountVerification: - NotConfirmable: str - MustBeMicroTransfersVerification: str - AmountsDoNotMatch: str - TooManyConfirmationAttempts: str - UnableToConfirmDepositAmounts: str - InvalidDepositAmounts: str + NotConfirmable: Final = "96101" + MustBeMicroTransfersVerification: Final = "96102" + AmountsDoNotMatch: Final = "96103" + TooManyConfirmationAttempts: Final = "96104" + UnableToConfirmDepositAmounts: Final = "96105" + InvalidDepositAmounts: Final = "96106" + class RiskData: - CustomerBrowserIsTooLong: str - CustomerDeviceIdIsTooLong: str - CustomerLocationZipInvalidCharacters: str - CustomerLocationZipIsInvalid: str - CustomerLocationZipIsTooLong: str - CustomerTenureIsTooLong: str + CustomerBrowserIsTooLong: Final = "94701" + CustomerDeviceIdIsTooLong: Final = "94702" + CustomerLocationZipInvalidCharacters: Final = "94703" + CustomerLocationZipIsInvalid: Final = "94704" + CustomerLocationZipIsTooLong: Final = "94705" + CustomerTenureIsTooLong: Final = "94706" diff --git a/stubs/braintree/braintree/error_result.pyi b/stubs/braintree/braintree/error_result.pyi index 6869df0dcbc7..9f23d30fa60a 100644 --- a/stubs/braintree/braintree/error_result.pyi +++ b/stubs/braintree/braintree/error_result.pyi @@ -1,16 +1,20 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Literal -from braintree.credit_card_verification import CreditCardVerification as CreditCardVerification -from braintree.errors import Errors as Errors +from braintree.credit_card_verification import CreditCardVerification +from braintree.errors import Errors +from braintree.plan import Plan +from braintree.subscription import Subscription +from braintree.transaction import Transaction class ErrorResult: - params: Any - errors: Any - message: Any - credit_card_verification: Any - transaction: Any - subscription: Any - merchant_account: Any - def __init__(self, gateway, attributes) -> None: ... + params: Incomplete + errors: Errors + message: Incomplete + credit_card_verification: CreditCardVerification | None + transaction: Transaction + subscription: Subscription + merchant_account: Plan + def __init__(self, gateway, attributes: dict[str, Incomplete]) -> None: ... @property - def is_success(self): ... + def is_success(self) -> Literal[False]: ... diff --git a/stubs/braintree/braintree/errors.pyi b/stubs/braintree/braintree/errors.pyi index 52ee0af5338d..fa8d6b33ab48 100644 --- a/stubs/braintree/braintree/errors.pyi +++ b/stubs/braintree/braintree/errors.pyi @@ -1,12 +1,13 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.validation_error_collection import ValidationErrorCollection as ValidationErrorCollection +from braintree.validation_error import ValidationError +from braintree.validation_error_collection import ValidationErrorCollection class Errors: - errors: Any - size: Any - def __init__(self, data) -> None: ... + errors: ValidationErrorCollection + size = errors.deep_size # pyrefly: ignore [unknown-name] + def __init__(self, data: dict[str, Incomplete]) -> None: ... @property - def deep_errors(self): ... - def for_object(self, key): ... - def __len__(self): ... + def deep_errors(self) -> list[ValidationError]: ... + def for_object(self, key: str) -> ValidationErrorCollection: ... + def __len__(self) -> int: ... diff --git a/stubs/braintree/braintree/europe_bank_account.pyi b/stubs/braintree/braintree/europe_bank_account.pyi index 6c6230c5deb4..f9b9632ee832 100644 --- a/stubs/braintree/braintree/europe_bank_account.pyi +++ b/stubs/braintree/braintree/europe_bank_account.pyi @@ -1,9 +1,11 @@ -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource +from typing import Final + +from braintree.resource import Resource class EuropeBankAccount(Resource): class MandateType: - Business: str - Consumer: str + Business: Final = "business" + Consumer: Final = "consumer" + @staticmethod - def signature(): ... + def signature() -> list[str]: ... diff --git a/stubs/braintree/braintree/exceptions/__init__.pyi b/stubs/braintree/braintree/exceptions/__init__.pyi index 343f22a04e8a..38284711b57c 100644 --- a/stubs/braintree/braintree/exceptions/__init__.pyi +++ b/stubs/braintree/braintree/exceptions/__init__.pyi @@ -8,6 +8,9 @@ from braintree.exceptions.not_found_error import NotFoundError as NotFoundError from braintree.exceptions.request_timeout_error import RequestTimeoutError as RequestTimeoutError from braintree.exceptions.server_error import ServerError as ServerError from braintree.exceptions.service_unavailable_error import ServiceUnavailableError as ServiceUnavailableError +from braintree.exceptions.test_operation_performed_in_production_error import ( + TestOperationPerformedInProductionError as TestOperationPerformedInProductionError, +) from braintree.exceptions.too_many_requests_error import TooManyRequestsError as TooManyRequestsError from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError from braintree.exceptions.upgrade_required_error import UpgradeRequiredError as UpgradeRequiredError diff --git a/stubs/braintree/braintree/exceptions/authentication_error.pyi b/stubs/braintree/braintree/exceptions/authentication_error.pyi index 64e3b570286a..cd370a008909 100644 --- a/stubs/braintree/braintree/exceptions/authentication_error.pyi +++ b/stubs/braintree/braintree/exceptions/authentication_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class AuthenticationError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/authorization_error.pyi b/stubs/braintree/braintree/exceptions/authorization_error.pyi index e945a78dd481..60571eea3b93 100644 --- a/stubs/braintree/braintree/exceptions/authorization_error.pyi +++ b/stubs/braintree/braintree/exceptions/authorization_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class AuthorizationError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/configuration_error.pyi b/stubs/braintree/braintree/exceptions/configuration_error.pyi index abf8cb30458f..724af3481279 100644 --- a/stubs/braintree/braintree/exceptions/configuration_error.pyi +++ b/stubs/braintree/braintree/exceptions/configuration_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError +from braintree.exceptions.unexpected_error import UnexpectedError class ConfigurationError(UnexpectedError): ... diff --git a/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi b/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi index 97a8be4dfab0..86fb52e8724c 100644 --- a/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi +++ b/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class GatewayTimeoutError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/http/connection_error.pyi b/stubs/braintree/braintree/exceptions/http/connection_error.pyi index 05b5c933bf5a..7f97331a953f 100644 --- a/stubs/braintree/braintree/exceptions/http/connection_error.pyi +++ b/stubs/braintree/braintree/exceptions/http/connection_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError +from braintree.exceptions.unexpected_error import UnexpectedError class ConnectionError(UnexpectedError): ... diff --git a/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi b/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi index d65b0810feff..37f106d2b186 100644 --- a/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi +++ b/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError +from braintree.exceptions.unexpected_error import UnexpectedError class InvalidResponseError(UnexpectedError): ... diff --git a/stubs/braintree/braintree/exceptions/http/timeout_error.pyi b/stubs/braintree/braintree/exceptions/http/timeout_error.pyi index b00dbb69a9f1..649b9e18770a 100644 --- a/stubs/braintree/braintree/exceptions/http/timeout_error.pyi +++ b/stubs/braintree/braintree/exceptions/http/timeout_error.pyi @@ -1,4 +1,4 @@ -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError +from braintree.exceptions.unexpected_error import UnexpectedError class TimeoutError(UnexpectedError): ... class ConnectTimeoutError(TimeoutError): ... diff --git a/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi b/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi index af1f68bf1fa6..a4ca43f62688 100644 --- a/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi +++ b/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class InvalidChallengeError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi b/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi index 5958f8f58544..d55bc610ac69 100644 --- a/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi +++ b/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class InvalidSignatureError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/not_found_error.pyi b/stubs/braintree/braintree/exceptions/not_found_error.pyi index 50fb02f7f546..955101fa34a3 100644 --- a/stubs/braintree/braintree/exceptions/not_found_error.pyi +++ b/stubs/braintree/braintree/exceptions/not_found_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class NotFoundError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/request_timeout_error.pyi b/stubs/braintree/braintree/exceptions/request_timeout_error.pyi index 65ab265dfdcd..c7dae6b0e27d 100644 --- a/stubs/braintree/braintree/exceptions/request_timeout_error.pyi +++ b/stubs/braintree/braintree/exceptions/request_timeout_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class RequestTimeoutError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/server_error.pyi b/stubs/braintree/braintree/exceptions/server_error.pyi index 1ccc2bed7640..83c3b6e8d3fd 100644 --- a/stubs/braintree/braintree/exceptions/server_error.pyi +++ b/stubs/braintree/braintree/exceptions/server_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class ServerError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi b/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi index d51469ac7914..a1d5a82aa657 100644 --- a/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi +++ b/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class ServiceUnavailableError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi b/stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi new file mode 100644 index 000000000000..583b34429303 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class TestOperationPerformedInProductionError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi b/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi index 1980fcb46b6d..9acc549e9a33 100644 --- a/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi +++ b/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class TooManyRequestsError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/unexpected_error.pyi b/stubs/braintree/braintree/exceptions/unexpected_error.pyi index c141ae5f26dd..7c164d8609e0 100644 --- a/stubs/braintree/braintree/exceptions/unexpected_error.pyi +++ b/stubs/braintree/braintree/exceptions/unexpected_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class UnexpectedError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi b/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi index feae59a2909c..48cdb303008d 100644 --- a/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi +++ b/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi @@ -1,3 +1,3 @@ -from braintree.exceptions.braintree_error import BraintreeError as BraintreeError +from braintree.exceptions.braintree_error import BraintreeError class UpgradeRequiredError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exchange_rate_quote.pyi b/stubs/braintree/braintree/exchange_rate_quote.pyi new file mode 100644 index 000000000000..cc859132d075 --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote.pyi @@ -0,0 +1,4 @@ +from braintree.attribute_getter import AttributeGetter + +class ExchangeRateQuote(AttributeGetter): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_gateway.pyi b/stubs/braintree/braintree/exchange_rate_quote_gateway.pyi new file mode 100644 index 000000000000..ee551915d1e8 --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.exchange_rate_quote_payload import ExchangeRateQuotePayload +from braintree.successful_result import SuccessfulResult + +class ExchangeRateQuoteGateway: + gateway: Incomplete + config: Incomplete + graphql_client: Incomplete + def __init__(self, gateway, graphql_client=None) -> None: ... + exchange_rate_quote_payload: ExchangeRateQuotePayload + def generate(self, request) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_input.pyi b/stubs/braintree/braintree/exchange_rate_quote_input.pyi new file mode 100644 index 000000000000..43ca18533dbc --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_input.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.attribute_getter import AttributeGetter + +class ExchangeRateQuoteInput(AttributeGetter): + parent: Incomplete + def __init__(self, parent, attributes) -> None: ... + def done(self): ... + def to_graphql_variables(self) -> dict[str, Incomplete]: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_payload.pyi b/stubs/braintree/braintree/exchange_rate_quote_payload.pyi new file mode 100644 index 000000000000..39a7ed103bfb --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_payload.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from braintree.exchange_rate_quote import ExchangeRateQuote + +class ExchangeRateQuotePayload: + quotes: list[ExchangeRateQuote] + def __init__(self, data: Mapping[str, Incomplete]) -> None: ... + def get_quotes(self) -> list[ExchangeRateQuote]: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_request.pyi b/stubs/braintree/braintree/exchange_rate_quote_request.pyi new file mode 100644 index 000000000000..e5eec778b32f --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_request.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.exchange_rate_quote_input import ExchangeRateQuoteInput + +class ExchangeRateQuoteRequest: + quotes: list[ExchangeRateQuoteInput] + def __init__(self) -> None: ... + def add_exchange_rate_quote_input(self, attributes) -> ExchangeRateQuoteInput: ... + def to_graphql_variables(self) -> dict[str, Incomplete]: ... diff --git a/stubs/braintree/braintree/facilitated_details.pyi b/stubs/braintree/braintree/facilitated_details.pyi index 724f3f18107c..834dee8abc24 100644 --- a/stubs/braintree/braintree/facilitated_details.pyi +++ b/stubs/braintree/braintree/facilitated_details.pyi @@ -1,3 +1,3 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class FacilitatedDetails(AttributeGetter): ... diff --git a/stubs/braintree/braintree/facilitator_details.pyi b/stubs/braintree/braintree/facilitator_details.pyi index 0557e2d1dd53..e91d76a76bfa 100644 --- a/stubs/braintree/braintree/facilitator_details.pyi +++ b/stubs/braintree/braintree/facilitator_details.pyi @@ -1,3 +1,3 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class FacilitatorDetails(AttributeGetter): ... diff --git a/stubs/braintree/braintree/granted_payment_instrument_update.pyi b/stubs/braintree/braintree/granted_payment_instrument_update.pyi index 73219712dcf3..2394d8843579 100644 --- a/stubs/braintree/braintree/granted_payment_instrument_update.pyi +++ b/stubs/braintree/braintree/granted_payment_instrument_update.pyi @@ -1,7 +1,7 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.resource import Resource as Resource +from braintree.resource import Resource class GrantedPaymentInstrumentUpdate(Resource): - payment_method_nonce: Any + payment_method_nonce: Incomplete def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/graphql/__init__.pyi b/stubs/braintree/braintree/graphql/__init__.pyi new file mode 100644 index 000000000000..c39a227b1fad --- /dev/null +++ b/stubs/braintree/braintree/graphql/__init__.pyi @@ -0,0 +1,20 @@ +from braintree.graphql.enums import Recommendations as Recommendations, RecommendedPaymentOption as RecommendedPaymentOption +from braintree.graphql.inputs import ( + BillingAddressInput as BillingAddressInput, + CreateCustomerSessionInput as CreateCustomerSessionInput, + CreateLocalPaymentContextInput as CreateLocalPaymentContextInput, + CustomerRecommendationsInput as CustomerRecommendationsInput, + CustomerSessionInput as CustomerSessionInput, + MonetaryAmountInput as MonetaryAmountInput, + PayerInfoInput as PayerInfoInput, + PayPalPayeeInput as PayPalPayeeInput, + PayPalPurchaseUnitInput as PayPalPurchaseUnitInput, + PhoneInput as PhoneInput, + UpdateCustomerSessionInput as UpdateCustomerSessionInput, +) +from braintree.graphql.types import ( + CustomerRecommendationsPayload as CustomerRecommendationsPayload, + PaymentOptions as PaymentOptions, + PaymentRecommendation as PaymentRecommendation, +) +from braintree.graphql.unions import CustomerRecommendations as CustomerRecommendations diff --git a/stubs/braintree/braintree/graphql/enums/__init__.pyi b/stubs/braintree/braintree/graphql/enums/__init__.pyi new file mode 100644 index 000000000000..ab73711c6d83 --- /dev/null +++ b/stubs/braintree/braintree/graphql/enums/__init__.pyi @@ -0,0 +1,2 @@ +from braintree.graphql.enums.recommendations import Recommendations as Recommendations +from braintree.graphql.enums.recommended_payment_option import RecommendedPaymentOption as RecommendedPaymentOption diff --git a/stubs/braintree/braintree/graphql/enums/recommendations.pyi b/stubs/braintree/braintree/graphql/enums/recommendations.pyi new file mode 100644 index 000000000000..907e49a1509d --- /dev/null +++ b/stubs/braintree/braintree/graphql/enums/recommendations.pyi @@ -0,0 +1,4 @@ +from enum import Enum + +class Recommendations(Enum): + PAYMENT_RECOMMENDATIONS = "PAYMENT_RECOMMENDATIONS" diff --git a/stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi b/stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi new file mode 100644 index 000000000000..b6e46e339492 --- /dev/null +++ b/stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi @@ -0,0 +1,5 @@ +from enum import Enum + +class RecommendedPaymentOption(Enum): + PAYPAL = "PAYPAL" + VENMO = "VENMO" diff --git a/stubs/braintree/braintree/graphql/inputs/__init__.pyi b/stubs/braintree/braintree/graphql/inputs/__init__.pyi new file mode 100644 index 000000000000..3ff432cc1a70 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/__init__.pyi @@ -0,0 +1,13 @@ +from braintree.graphql.inputs.billing_address_input import BillingAddressInput as BillingAddressInput +from braintree.graphql.inputs.create_customer_session_input import CreateCustomerSessionInput as CreateCustomerSessionInput +from braintree.graphql.inputs.create_local_payment_context_input import ( + CreateLocalPaymentContextInput as CreateLocalPaymentContextInput, +) +from braintree.graphql.inputs.customer_recommendations_input import CustomerRecommendationsInput as CustomerRecommendationsInput +from braintree.graphql.inputs.customer_session_input import CustomerSessionInput as CustomerSessionInput +from braintree.graphql.inputs.monetary_amount_input import MonetaryAmountInput as MonetaryAmountInput +from braintree.graphql.inputs.payer_info_input import PayerInfoInput as PayerInfoInput +from braintree.graphql.inputs.paypal_payee_input import PayPalPayeeInput as PayPalPayeeInput +from braintree.graphql.inputs.paypal_purchase_unit_input import PayPalPurchaseUnitInput as PayPalPurchaseUnitInput +from braintree.graphql.inputs.phone_input import PhoneInput as PhoneInput +from braintree.graphql.inputs.update_customer_session_input import UpdateCustomerSessionInput as UpdateCustomerSessionInput diff --git a/stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi b/stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi new file mode 100644 index 000000000000..94ef587a361d --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi @@ -0,0 +1,22 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + countryCode: str + extendedAddress: str + locality: str + postalCode: str + region: str + streetAddress: str + +class BillingAddressInput: + def __init__( + self, + country_code_alpha2: str | None = None, + extended_address: str | None = None, + locality: str | None = None, + postal_code: str | None = None, + region: str | None = None, + street_address: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi b/stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi new file mode 100644 index 000000000000..28d6ab5385ed --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi @@ -0,0 +1,41 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.customer_session_input import ( + CustomerSessionInput, + _GraphqlVariables as _CustomerSessionGraphqlVariables, +) +from braintree.graphql.inputs.paypal_purchase_unit_input import ( + PayPalPurchaseUnitInput, + _GraphqlVariables as _PayPalPurchaseUnitGraphqlVariables, +) + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + merchantAccountId: str + sessionId: str + customer: _CustomerSessionGraphqlVariables + domain: str + purchaseUnits: list[_PayPalPurchaseUnitGraphqlVariables] + +class CreateCustomerSessionInput: + def __init__( + self, + merchant_account_id: str | None = None, + session_id: str | None = None, + customer: CustomerSessionInput | None = None, + domain: str | None = None, + purchase_units: list[PayPalPurchaseUnitInput] | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def merchant_account_id(self, merchant_account_id: str) -> Self: ... + def session_id(self, session_id: str) -> Self: ... + def customer(self, customer: CustomerSessionInput) -> Self: ... + def purchase_units(self, purchase_units: list[PayPalPurchaseUnitInput]) -> Self: ... + def domain(self, domain: str) -> Self: ... + def build(self) -> CreateCustomerSessionInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi b/stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi new file mode 100644 index 000000000000..dc8ea3b1c223 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +from braintree.graphql.inputs.monetary_amount_input import _GraphqlVariables as _MonetaryAmountGraphqlVariables +from braintree.graphql.inputs.payer_info_input import _GraphqlVariables as _PayerInfoGraphqlVariables + +@type_check_only +class _PaymentContext(TypedDict, total=False): + amount: _MonetaryAmountGraphqlVariables + cancelUrl: str + countryCode: str + expiryDate: str + merchantAccountId: str + orderId: str + payerInfo: _PayerInfoGraphqlVariables + returnUrl: str + type: str + +@type_check_only +class _GraphqlVariables(TypedDict): + paymentContext: _PaymentContext + +class CreateLocalPaymentContextInput: + def __init__( + self, + amount: dict[str, Incomplete] | None = None, + cancel_url: str | None = None, + country_code: str | None = None, + expiry_date: str | None = None, + merchant_account_id: str | None = None, + order_id: str | None = None, + payer_info: dict[str, Incomplete] | None = None, + return_url: str | None = None, + type: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi b/stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi new file mode 100644 index 000000000000..2869cfd04ff1 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi @@ -0,0 +1,41 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Required, Self + +from braintree.graphql.inputs.customer_session_input import ( + CustomerSessionInput, + _GraphqlVariables as _CustomerSessionGraphqlVariables, +) +from braintree.graphql.inputs.paypal_purchase_unit_input import ( + PayPalPurchaseUnitInput, + _GraphqlVariables as _PayPalPurchaseUnitGraphqlVariables, +) + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + sessionId: Required[str] + merchantAccountId: str + purchaseUnits: list[_PayPalPurchaseUnitGraphqlVariables] + domain: str + customer: _CustomerSessionGraphqlVariables + +class CustomerRecommendationsInput: + def __init__( + self, + session_id: str, + merchant_account_id: str | None = None, + purchase_units: list[PayPalPurchaseUnitInput] | None = None, + domain: str | None = None, + customer: CustomerSessionInput | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def session_id(self, session_id: str) -> Self: ... + def merchant_account_id(self, merchant_account_id: str) -> Self: ... + def customer(self, customer: CustomerSessionInput) -> Self: ... + def purchase_units(self, purchase_units: list[PayPalPurchaseUnitInput]) -> Self: ... + def domain(self, domain: str) -> Self: ... + def build(self) -> CustomerRecommendationsInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi b/stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi new file mode 100644 index 000000000000..91f694b892c2 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi @@ -0,0 +1,43 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.phone_input import PhoneInput, _GraphqlVariables as _PhoneInputGraphqlVariables + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + email: str + hashedEmail: str + phone: _PhoneInputGraphqlVariables + hashedPhoneNumber: str + deviceFingerprintId: str + paypalAppInstalled: bool + venmoAppInstalled: bool + userAgent: str + +class CustomerSessionInput: + def __init__( + self, + email: str | None = None, + hashed_email: str | None = None, + phone: PhoneInput | None = None, + hashed_phone_number: str | None = None, + device_fingerprint_id: str | None = None, + paypal_app_installed: bool | None = None, + venmo_app_installed: bool | None = None, + user_agent: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def email(self, email: str) -> Self: ... + def hashed_email(self, hashed_email: str) -> Self: ... + def phone(self, phone: PhoneInput) -> Self: ... + def hashed_phone_number(self, hashed_phone_number: str) -> Self: ... + def device_fingerprint_id(self, device_fingerprint_id: str) -> Self: ... + def paypal_app_installed(self, paypal_app_installed: bool) -> Self: ... + def venmo_app_installed(self, venmo_app_installed: bool) -> Self: ... + def user_agent(self, user_agent: str) -> Self: ... + def build(self) -> CustomerSessionInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi b/stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi new file mode 100644 index 000000000000..f7180db3baa9 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi @@ -0,0 +1,11 @@ +from decimal import Decimal +from typing import TypedDict, type_check_only + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + value: str + currencyCode: str + +class MonetaryAmountInput: + def __init__(self, value: Decimal | None = None, currency_code: str | None = None) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi b/stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi new file mode 100644 index 000000000000..c9dfe835bd52 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +from braintree.graphql.inputs.billing_address_input import _GraphqlVariables as _BillingAddressGraphqlVariables +from braintree.graphql.inputs.shipping_address_input import _GraphqlVariables as _ShippingAddressGraphqlVariables + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + billingAddress: _BillingAddressGraphqlVariables + email: str + givenName: str + phoneCountryCode: str + phoneNumber: str + shippingAddress: _ShippingAddressGraphqlVariables + surname: str + +class PayerInfoInput: + def __init__( + self, + billing_address: dict[str, Incomplete] | None = None, + email: str | None = None, + given_name: str | None = None, + phone_country_code: str | None = None, + phone_number: str | None = None, + shipping_address: dict[str, Incomplete] | None = None, + surname: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi b/stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi new file mode 100644 index 000000000000..92d40b81a679 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi @@ -0,0 +1,19 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + emailAddress: str + clientId: str + +class PayPalPayeeInput: + def __init__(self, email_address: str | None = None, client_id: str | None = None) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def email_address(self, email_address: str) -> Self: ... + def client_id(self, client_id: str) -> Self: ... + def build(self) -> PayPalPayeeInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi b/stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi new file mode 100644 index 000000000000..4f4db97adc29 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi @@ -0,0 +1,24 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.monetary_amount_input import ( + MonetaryAmountInput, + _GraphqlVariables as _MonetaryAmountGraphqlVariables, +) +from braintree.graphql.inputs.paypal_payee_input import PayPalPayeeInput, _GraphqlVariables as _PayPalPayeeGraphqlVariables + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + payee: _PayPalPayeeGraphqlVariables + amount: _MonetaryAmountGraphqlVariables + +class PayPalPurchaseUnitInput: + def __init__(self, amount: MonetaryAmountInput | None = None, payee: PayPalPayeeInput | None = None) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder(amount: MonetaryAmountInput) -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self, amount: MonetaryAmountInput) -> None: ... + def payee(self, payee: PayPalPayeeInput) -> Self: ... + def build(self) -> PayPalPurchaseUnitInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/phone_input.pyi b/stubs/braintree/braintree/graphql/inputs/phone_input.pyi new file mode 100644 index 000000000000..667c1d531809 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/phone_input.pyi @@ -0,0 +1,23 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + countryPhoneCode: str + phoneNumber: str + extensionNumber: str + +class PhoneInput: + def __init__( + self, country_phone_code: str | None = None, phone_number: str | None = None, extension_number: str | None = None + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def country_phone_code(self, country_phone_code: str) -> Self: ... + def phone_number(self, phone_number: str) -> Self: ... + def extension_number(self, extension_number: str) -> Self: ... + def build(self) -> PhoneInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi b/stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi new file mode 100644 index 000000000000..f941611a7d90 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi @@ -0,0 +1,22 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + countryCode: str + extendedAddress: str + locality: str + postalCode: str + region: str + streetAddress: str + +class ShippingAddressInput: + def __init__( + self, + country_code_alpha2: str | None = None, + extended_address: str | None = None, + locality: str | None = None, + postal_code: str | None = None, + region: str | None = None, + street_address: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi b/stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi new file mode 100644 index 000000000000..a8b580e70b2c --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi @@ -0,0 +1,37 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.customer_session_input import ( + CustomerSessionInput, + _GraphqlVariables as _CustomerSessionGraphqlVariables, +) +from braintree.graphql.inputs.paypal_purchase_unit_input import ( + PayPalPurchaseUnitInput, + _GraphqlVariables as _PayPalPurchaseUnitGraphqlVariables, +) + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + sessionId: str + customer: _CustomerSessionGraphqlVariables + merchantAccountId: str + purchaseUnits: list[_PayPalPurchaseUnitGraphqlVariables] + +class UpdateCustomerSessionInput: + def __init__( + self, + session_id: str, + customer: CustomerSessionInput | None = None, + merchant_account_id: str | None = None, + purchase_units: list[PayPalPurchaseUnitInput] | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder(session_id: str) -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self, session_id: str) -> None: ... + def merchant_account_id(self, merchant_account_id: str) -> Self: ... + def customer(self, customer: CustomerSessionInput) -> Self: ... + def purchase_units(self, purchase_units: list[PayPalPurchaseUnitInput]) -> Self: ... + def build(self) -> UpdateCustomerSessionInput: ... diff --git a/stubs/braintree/braintree/graphql/types/__init__.pyi b/stubs/braintree/braintree/graphql/types/__init__.pyi new file mode 100644 index 000000000000..0e2d21a802d7 --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/__init__.pyi @@ -0,0 +1,5 @@ +from braintree.graphql.types.customer_recommendations_payload import ( + CustomerRecommendationsPayload as CustomerRecommendationsPayload, +) +from braintree.graphql.types.payment_options import PaymentOptions as PaymentOptions +from braintree.graphql.types.payment_recommendation import PaymentRecommendation as PaymentRecommendation diff --git a/stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi b/stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi new file mode 100644 index 000000000000..488df1d1de61 --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi @@ -0,0 +1,22 @@ +from typing import Any, overload + +from braintree.graphql.unions.customer_recommendations import CustomerRecommendations + +class CustomerRecommendationsPayload: + session_id: str + is_in_paypal_network: bool + recommendations: CustomerRecommendations + + @overload + def __init__( + self, + session_id: None = None, + is_in_paypal_network: None = None, + recommendations: None = None, + *, + response: dict[str, Any], + ): ... + @overload + def __init__( + self, session_id: str, is_in_paypal_network: bool, recommendations: CustomerRecommendations, response: None = None + ): ... diff --git a/stubs/braintree/braintree/graphql/types/payment_options.pyi b/stubs/braintree/braintree/graphql/types/payment_options.pyi new file mode 100644 index 000000000000..756f4d1410c4 --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/payment_options.pyi @@ -0,0 +1,6 @@ +from braintree.graphql.enums import RecommendedPaymentOption + +class PaymentOptions: + payment_option: RecommendedPaymentOption + recommended_priority: int + def __init__(self, payment_option: RecommendedPaymentOption, recommended_priority: int) -> None: ... diff --git a/stubs/braintree/braintree/graphql/types/payment_recommendation.pyi b/stubs/braintree/braintree/graphql/types/payment_recommendation.pyi new file mode 100644 index 000000000000..34ed4dc436db --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/payment_recommendation.pyi @@ -0,0 +1,6 @@ +from braintree.graphql.enums import RecommendedPaymentOption + +class PaymentRecommendation: + payment_option: RecommendedPaymentOption + recommended_priority: int + def __init__(self, payment_option: RecommendedPaymentOption, recommended_priority: int) -> None: ... diff --git a/stubs/braintree/braintree/graphql/unions/__init__.pyi b/stubs/braintree/braintree/graphql/unions/__init__.pyi new file mode 100644 index 000000000000..6b6217e4c28e --- /dev/null +++ b/stubs/braintree/braintree/graphql/unions/__init__.pyi @@ -0,0 +1 @@ +from braintree.graphql.unions.customer_recommendations import CustomerRecommendations as CustomerRecommendations diff --git a/stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi b/stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi new file mode 100644 index 000000000000..63a3df64fd59 --- /dev/null +++ b/stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi @@ -0,0 +1,7 @@ +from braintree.graphql.types.payment_options import PaymentOptions +from braintree.graphql.types.payment_recommendation import PaymentRecommendation + +class CustomerRecommendations: + payment_options: list[PaymentOptions] + payment_recommendations: list[PaymentRecommendation] + def __init__(self, payment_recommendations: list[PaymentRecommendation] | None = None) -> None: ... diff --git a/stubs/braintree/braintree/iban_bank_account.pyi b/stubs/braintree/braintree/iban_bank_account.pyi index b8c25aba2459..26ac82783207 100644 --- a/stubs/braintree/braintree/iban_bank_account.pyi +++ b/stubs/braintree/braintree/iban_bank_account.pyi @@ -1,3 +1,3 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class IbanBankAccount(Resource): ... diff --git a/stubs/braintree/braintree/ids_search.pyi b/stubs/braintree/braintree/ids_search.pyi index db017bb7e016..bea7f0fb954a 100644 --- a/stubs/braintree/braintree/ids_search.pyi +++ b/stubs/braintree/braintree/ids_search.pyi @@ -1,6 +1,4 @@ -from typing import Any - -from braintree.search import Search as Search +from braintree.search import Search class IdsSearch: - ids: Any + ids: Search.MultipleValueNodeBuilder diff --git a/stubs/braintree/braintree/liability_shift.pyi b/stubs/braintree/braintree/liability_shift.pyi new file mode 100644 index 000000000000..8f9b60d0ec98 --- /dev/null +++ b/stubs/braintree/braintree/liability_shift.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class LiabilityShift(AttributeGetter): ... diff --git a/stubs/braintree/braintree/local_payment.pyi b/stubs/braintree/braintree/local_payment.pyi index 355a1c486abd..bb64eecd2a88 100644 --- a/stubs/braintree/braintree/local_payment.pyi +++ b/stubs/braintree/braintree/local_payment.pyi @@ -1,3 +1,3 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class LocalPayment(Resource): ... diff --git a/stubs/braintree/braintree/local_payment_completed.pyi b/stubs/braintree/braintree/local_payment_completed.pyi index ff8e4ca887ae..4adab3529b4b 100644 --- a/stubs/braintree/braintree/local_payment_completed.pyi +++ b/stubs/braintree/braintree/local_payment_completed.pyi @@ -1,8 +1,6 @@ -from typing import Any - -from braintree.resource import Resource as Resource -from braintree.transaction import Transaction as Transaction +from braintree.resource import Resource +from braintree.transaction import Transaction class LocalPaymentCompleted(Resource): - transaction: Any + transaction: Transaction def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_context.pyi b/stubs/braintree/braintree/local_payment_context.pyi new file mode 100644 index 000000000000..6c7684b01a46 --- /dev/null +++ b/stubs/braintree/braintree/local_payment_context.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +from braintree.attribute_getter import AttributeGetter + +class LocalPaymentContext(AttributeGetter): + def __init__(self, attributes: dict[str, Incomplete] | None = None) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_context_gateway.pyi b/stubs/braintree/braintree/local_payment_context_gateway.pyi new file mode 100644 index 000000000000..d33094c1a900 --- /dev/null +++ b/stubs/braintree/braintree/local_payment_context_gateway.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.graphql import CreateLocalPaymentContextInput +from braintree.successful_result import SuccessfulResult + +class LocalPaymentContextGateway: + CREATE_LOCAL_PAYMENT_CONTEXT: str + FIND_LOCAL_PAYMENT_CONTEXT: str + gateway: Incomplete + graphql_client: Incomplete + def __init__(self, gateway) -> None: ... + def create(self, input: CreateLocalPaymentContextInput) -> SuccessfulResult | ErrorResult: ... + def find(self, id) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/local_payment_expired.pyi b/stubs/braintree/braintree/local_payment_expired.pyi new file mode 100644 index 000000000000..3b69ab08a345 --- /dev/null +++ b/stubs/braintree/braintree/local_payment_expired.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class LocalPaymentExpired(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_funded.pyi b/stubs/braintree/braintree/local_payment_funded.pyi new file mode 100644 index 000000000000..0453a53194de --- /dev/null +++ b/stubs/braintree/braintree/local_payment_funded.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class LocalPaymentFunded(Resource): + transaction: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_reversed.pyi b/stubs/braintree/braintree/local_payment_reversed.pyi index be538ec761ca..8f4e5259162d 100644 --- a/stubs/braintree/braintree/local_payment_reversed.pyi +++ b/stubs/braintree/braintree/local_payment_reversed.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class LocalPaymentReversed(Resource): def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_type.pyi b/stubs/braintree/braintree/local_payment_type.pyi new file mode 100644 index 000000000000..cf897047f2aa --- /dev/null +++ b/stubs/braintree/braintree/local_payment_type.pyi @@ -0,0 +1,5 @@ +from typing import Final + +class LocalPaymentType: + CRYPTO: Final = "CRYPTO" + MBWAY: Final = "MBWAY" diff --git a/stubs/braintree/braintree/masterpass_card.pyi b/stubs/braintree/braintree/masterpass_card.pyi index 2921f9b87ee7..c50678e419b7 100644 --- a/stubs/braintree/braintree/masterpass_card.pyi +++ b/stubs/braintree/braintree/masterpass_card.pyi @@ -1,13 +1,12 @@ -from typing import Any - -from braintree.address import Address as Address -from braintree.resource import Resource as Resource +from braintree.address import Address +from braintree.resource import Resource +from braintree.subscription import Subscription class MasterpassCard(Resource): - billing_address: Any - subscriptions: Any + billing_address: Address | None + subscriptions: list[Subscription] def __init__(self, gateway, attributes) -> None: ... @property - def expiration_date(self): ... + def expiration_date(self) -> str: ... @property - def masked_number(self): ... + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/merchant.pyi b/stubs/braintree/braintree/merchant.pyi index 4a80756aa79d..4f6c03e283c3 100644 --- a/stubs/braintree/braintree/merchant.pyi +++ b/stubs/braintree/braintree/merchant.pyi @@ -1,8 +1,6 @@ -from typing import Any - -from braintree.merchant_account import MerchantAccount as MerchantAccount -from braintree.resource import Resource as Resource +from braintree.merchant_account import MerchantAccount +from braintree.resource import Resource class Merchant(Resource): - merchant_accounts: Any + merchant_accounts: list[MerchantAccount] def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/__init__.pyi b/stubs/braintree/braintree/merchant_account/__init__.pyi index 743f6fa816b9..85c7724f4d94 100644 --- a/stubs/braintree/braintree/merchant_account/__init__.pyi +++ b/stubs/braintree/braintree/merchant_account/__init__.pyi @@ -1,4 +1 @@ -from braintree.merchant_account.business_details import BusinessDetails as BusinessDetails -from braintree.merchant_account.funding_details import FundingDetails as FundingDetails -from braintree.merchant_account.individual_details import IndividualDetails as IndividualDetails from braintree.merchant_account.merchant_account import MerchantAccount as MerchantAccount diff --git a/stubs/braintree/braintree/merchant_account/address_details.pyi b/stubs/braintree/braintree/merchant_account/address_details.pyi index 3a3a9aacd8f9..0ae743222469 100644 --- a/stubs/braintree/braintree/merchant_account/address_details.pyi +++ b/stubs/braintree/braintree/merchant_account/address_details.pyi @@ -1,7 +1,7 @@ -from typing import Any +from typing import ClassVar -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class AddressDetails(AttributeGetter): - detail_list: Any + detail_list: ClassVar[list[str]] def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/business_details.pyi b/stubs/braintree/braintree/merchant_account/business_details.pyi deleted file mode 100644 index d5800497d1a3..000000000000 --- a/stubs/braintree/braintree/merchant_account/business_details.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from braintree.attribute_getter import AttributeGetter as AttributeGetter -from braintree.merchant_account.address_details import AddressDetails as AddressDetails - -class BusinessDetails(AttributeGetter): - detail_list: Any - address_details: Any - def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/funding_details.pyi b/stubs/braintree/braintree/merchant_account/funding_details.pyi deleted file mode 100644 index 220e767f35d4..000000000000 --- a/stubs/braintree/braintree/merchant_account/funding_details.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -from braintree.attribute_getter import AttributeGetter as AttributeGetter - -class FundingDetails(AttributeGetter): - detail_list: Any - def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/individual_details.pyi b/stubs/braintree/braintree/merchant_account/individual_details.pyi deleted file mode 100644 index 1f07477ace62..000000000000 --- a/stubs/braintree/braintree/merchant_account/individual_details.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -from braintree.attribute_getter import AttributeGetter as AttributeGetter -from braintree.merchant_account.address_details import AddressDetails as AddressDetails - -class IndividualDetails(AttributeGetter): - detail_list: Any - address_details: Any - def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/merchant_account.pyi b/stubs/braintree/braintree/merchant_account/merchant_account.pyi index 4bdb762ef00d..2fbe0ac80ed9 100644 --- a/stubs/braintree/braintree/merchant_account/merchant_account.pyi +++ b/stubs/braintree/braintree/merchant_account/merchant_account.pyi @@ -1,30 +1,23 @@ -from typing import Any +from typing import Final -from braintree.configuration import Configuration as Configuration -from braintree.merchant_account import ( - BusinessDetails as BusinessDetails, - FundingDetails as FundingDetails, - IndividualDetails as IndividualDetails, -) -from braintree.resource import Resource as Resource +from braintree.resource import Resource class MerchantAccount(Resource): class Status: - Active: str - Pending: str - Suspended: str + Active: Final = "active" + Pending: Final = "pending" + Suspended: Final = "suspended" + class FundingDestination: - Bank: str - Email: str - MobilePhone: str - FundingDestinations: Any - individual_details: Any - business_details: Any - funding_details: Any - master_merchant_account: Any + Bank: Final = "bank" + Email: Final = "email" + MobilePhone: Final = "mobile_phone" + + FundingDestinations: type[FundingDestination] + master_merchant_account: MerchantAccount def __init__(self, gateway, attributes) -> None: ... @staticmethod - def create(params: Any | None = ...): ... + def create(params=None): ... @staticmethod def update(id, attributes): ... @staticmethod diff --git a/stubs/braintree/braintree/merchant_account_gateway.pyi b/stubs/braintree/braintree/merchant_account_gateway.pyi index 5d653eab7a32..5d426f6b4108 100644 --- a/stubs/braintree/braintree/merchant_account_gateway.pyi +++ b/stubs/braintree/braintree/merchant_account_gateway.pyi @@ -1,20 +1,13 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.merchant_account import MerchantAccount as MerchantAccount -from braintree.paginated_collection import PaginatedCollection as PaginatedCollection -from braintree.paginated_result import PaginatedResult as PaginatedResult -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.merchant_account import MerchantAccount +from braintree.successful_result import SuccessfulResult class MerchantAccountGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create(self, params: Any | None = ...): ... - def update(self, merchant_account_id, params: Any | None = ...): ... - def find(self, merchant_account_id): ... - def create_for_currency(self, params: Any | None = ...): ... - def all(self): ... + def find(self, merchant_account_id: str) -> MerchantAccount: ... + def create_for_currency(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def all(self) -> SuccessfulResult: ... diff --git a/stubs/braintree/braintree/merchant_gateway.pyi b/stubs/braintree/braintree/merchant_gateway.pyi index efbbaaf4325d..54773625e1b7 100644 --- a/stubs/braintree/braintree/merchant_gateway.pyi +++ b/stubs/braintree/braintree/merchant_gateway.pyi @@ -1,15 +1,12 @@ -from typing import Any +from _typeshed import Incomplete +from typing_extensions import deprecated -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.merchant import Merchant as Merchant -from braintree.oauth_credentials import OAuthCredentials as OAuthCredentials -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult class MerchantGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create(self, params): ... + @deprecated("gateway.merchant.create(...) is deprecated and will be removed in a future version.") + def create(self, params: dict[str, Incomplete] | None) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/meta_checkout_card.pyi b/stubs/braintree/braintree/meta_checkout_card.pyi new file mode 100644 index 000000000000..7ee4304b9cfa --- /dev/null +++ b/stubs/braintree/braintree/meta_checkout_card.pyi @@ -0,0 +1,8 @@ +from braintree.resource import Resource + +class MetaCheckoutCard(Resource): + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self) -> str | None: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/meta_checkout_token.pyi b/stubs/braintree/braintree/meta_checkout_token.pyi new file mode 100644 index 000000000000..a9d7bece4d1c --- /dev/null +++ b/stubs/braintree/braintree/meta_checkout_token.pyi @@ -0,0 +1,8 @@ +from braintree.resource import Resource + +class MetaCheckoutToken(Resource): + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self) -> str | None: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/modification.pyi b/stubs/braintree/braintree/modification.pyi index e55fa128b621..aca8b4cd837a 100644 --- a/stubs/braintree/braintree/modification.pyi +++ b/stubs/braintree/braintree/modification.pyi @@ -1,7 +1,7 @@ -from typing import Any +from decimal import Decimal -from braintree.resource import Resource as Resource +from braintree.resource import Resource class Modification(Resource): - amount: Any + amount: Decimal def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/monetary_amount.pyi b/stubs/braintree/braintree/monetary_amount.pyi new file mode 100644 index 000000000000..6da51aaaac91 --- /dev/null +++ b/stubs/braintree/braintree/monetary_amount.pyi @@ -0,0 +1,7 @@ +from decimal import Decimal + +from braintree.attribute_getter import AttributeGetter + +class MonetaryAmount(AttributeGetter): + value: Decimal + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/oauth_access_revocation.pyi b/stubs/braintree/braintree/oauth_access_revocation.pyi index 579dccac8eb8..5e06bcb21083 100644 --- a/stubs/braintree/braintree/oauth_access_revocation.pyi +++ b/stubs/braintree/braintree/oauth_access_revocation.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class OAuthAccessRevocation(Resource): def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/oauth_credentials.pyi b/stubs/braintree/braintree/oauth_credentials.pyi index 487034adeed9..a2e861aee39c 100644 --- a/stubs/braintree/braintree/oauth_credentials.pyi +++ b/stubs/braintree/braintree/oauth_credentials.pyi @@ -1,3 +1,3 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class OAuthCredentials(Resource): ... diff --git a/stubs/braintree/braintree/oauth_gateway.pyi b/stubs/braintree/braintree/oauth_gateway.pyi index 096dfbc72763..53e5af4f3d3f 100644 --- a/stubs/braintree/braintree/oauth_gateway.pyi +++ b/stubs/braintree/braintree/oauth_gateway.pyi @@ -1,15 +1,13 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.oauth_credentials import OAuthCredentials as OAuthCredentials -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult class OAuthGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create_token_from_code(self, params): ... - def create_token_from_refresh_token(self, params): ... - def revoke_access_token(self, access_token): ... - def connect_url(self, raw_params): ... + def create_token_from_code(self, params: dict[str, Incomplete]) -> SuccessfulResult | ErrorResult: ... + def create_token_from_refresh_token(self, params: dict[str, Incomplete]) -> SuccessfulResult | ErrorResult: ... + def revoke_access_token(self, access_token: str) -> type[SuccessfulResult] | ErrorResult: ... + def connect_url(self, raw_params: dict[str, Incomplete]) -> str: ... diff --git a/stubs/braintree/braintree/package_details.pyi b/stubs/braintree/braintree/package_details.pyi new file mode 100644 index 000000000000..10693c94eea4 --- /dev/null +++ b/stubs/braintree/braintree/package_details.pyi @@ -0,0 +1,7 @@ +from typing import ClassVar + +from braintree.attribute_getter import AttributeGetter + +class PackageDetails(AttributeGetter): + detail_list: ClassVar[list[str]] + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/paginated_collection.pyi b/stubs/braintree/braintree/paginated_collection.pyi index 3e2182f6de5f..f370775e7db2 100644 --- a/stubs/braintree/braintree/paginated_collection.pyi +++ b/stubs/braintree/braintree/paginated_collection.pyi @@ -1,8 +1,8 @@ +from _typeshed import Incomplete from collections.abc import Generator -from typing import Any class PaginatedCollection: def __init__(self, method) -> None: ... @property - def items(self) -> Generator[Any, None, None]: ... + def items(self) -> Generator[Incomplete]: ... def __iter__(self): ... diff --git a/stubs/braintree/braintree/paginated_result.pyi b/stubs/braintree/braintree/paginated_result.pyi index a7bbb385ec7d..3511f8708d6e 100644 --- a/stubs/braintree/braintree/paginated_result.pyi +++ b/stubs/braintree/braintree/paginated_result.pyi @@ -1,7 +1,7 @@ -from typing import Any +from _typeshed import Incomplete class PaginatedResult: - total_items: Any - page_size: Any - current_page: Any + total_items: Incomplete + page_size: Incomplete + current_page: Incomplete def __init__(self, total_items, page_size, current_page) -> None: ... diff --git a/stubs/braintree/braintree/partner_merchant.pyi b/stubs/braintree/braintree/partner_merchant.pyi index 06ea8c9f162c..cfb5581a4318 100644 --- a/stubs/braintree/braintree/partner_merchant.pyi +++ b/stubs/braintree/braintree/partner_merchant.pyi @@ -1,12 +1,11 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource +from braintree.resource import Resource class PartnerMerchant(Resource): - partner_merchant_id: Any - private_key: Any - public_key: Any - merchant_public_id: Any - client_side_encryption_key: Any + partner_merchant_id: Incomplete + private_key: Incomplete + public_key: Incomplete + merchant_public_id: Incomplete + client_side_encryption_key: Incomplete def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_facilitator.pyi b/stubs/braintree/braintree/payment_facilitator.pyi new file mode 100644 index 000000000000..905ced231d28 --- /dev/null +++ b/stubs/braintree/braintree/payment_facilitator.pyi @@ -0,0 +1,6 @@ +from braintree.attribute_getter import AttributeGetter +from braintree.sub_merchant import SubMerchant + +class PaymentFacilitator(AttributeGetter): + sub_merchant: SubMerchant + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_instrument_type.pyi b/stubs/braintree/braintree/payment_instrument_type.pyi index b19e7d84091e..ec607ffafcdb 100644 --- a/stubs/braintree/braintree/payment_instrument_type.pyi +++ b/stubs/braintree/braintree/payment_instrument_type.pyi @@ -1,14 +1,19 @@ +from typing import Final + class PaymentInstrumentType: - PayPalAccount: str - PayPalHere: str - EuropeBankAccount: str - CreditCard: str - ApplePayCard: str - AndroidPayCard: str - AmexExpressCheckoutCard: str - VenmoAccount: str - UsBankAccount: str - VisaCheckoutCard: str - MasterpassCard: str - SamsungPayCard: str - LocalPayment: str + AmexExpressCheckoutCard: Final = "amex_express_checkout_card" + AndroidPayCard: Final = "android_pay_card" + ApplePayCard: Final = "apple_pay_card" + CreditCard: Final = "credit_card" + EuropeBankAccount: Final = "europe_bank_account" + LocalPayment: Final = "local_payment" + MasterpassCard: Final = "masterpass_card" + MetaCheckoutCard: Final = "meta_checkout_card" + MetaCheckoutToken: Final = "meta_checkout_token" + PayPalAccount: Final = "paypal_account" + PayPalHere: Final = "paypal_here" + SamsungPayCard: Final = "samsung_pay_card" + SepaDirectDebitAccount: Final = "sepa_debit_account" + UsBankAccount: Final = "us_bank_account" + VenmoAccount: Final = "venmo_account" + VisaCheckoutCard: Final = "visa_checkout_card" diff --git a/stubs/braintree/braintree/payment_method.pyi b/stubs/braintree/braintree/payment_method.pyi index acb99aaca88d..41ac52cb6807 100644 --- a/stubs/braintree/braintree/payment_method.pyi +++ b/stubs/braintree/braintree/payment_method.pyi @@ -1,23 +1,66 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.address import Address as Address -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.resource import Resource +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.successful_result import SuccessfulResult +from braintree.unknown_payment_method import UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard class PaymentMethod(Resource): @staticmethod - def create(params: Any | None = ...): ... + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... @staticmethod - def find(payment_method_token): ... + def find( + payment_method_token: str, + ) -> ( + AndroidPayCard + | ApplePayCard + | EuropeBankAccount + | CreditCard + | PayPalAccount + | UsBankAccount + | VenmoAccount + | VisaCheckoutCard + | AmexExpressCheckoutCard + | SepaDirectDebitAccount + | MasterpassCard + | SamsungPayCard + | UnknownPaymentMethod + ): ... @staticmethod - def update(payment_method_token, params): ... + def update(payment_method_token: str, params) -> SuccessfulResult | ErrorResult: ... @staticmethod - def delete(payment_method_token, options: Any | None = ...): ... + def delete(payment_method_token: str, options=None) -> SuccessfulResult: ... @staticmethod - def create_signature(): ... + def create_signature() -> ( + list[ + str + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + | dict[str, list[str]] + ] + ): ... @staticmethod - def signature(type): ... + def signature( + type: str, + ) -> list[ + str + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + | dict[str, list[str]] + ]: ... @staticmethod - def update_signature(): ... + def update_signature() -> list[str | dict[str, list[str | dict[str, list[str]]]] | dict[str, list[str]]]: ... @staticmethod - def delete_signature(): ... + def delete_signature() -> list[str]: ... diff --git a/stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi b/stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi new file mode 100644 index 000000000000..6bbe0f16bbb6 --- /dev/null +++ b/stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class PaymentMethodCustomerDataUpdatedMetadata(Resource): + payment_method: Incomplete + enriched_customer_data: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_method_gateway.pyi b/stubs/braintree/braintree/payment_method_gateway.pyi index 370f0aafb1dc..16054b4413d5 100644 --- a/stubs/braintree/braintree/payment_method_gateway.pyi +++ b/stubs/braintree/braintree/payment_method_gateway.pyi @@ -1,35 +1,45 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.amex_express_checkout_card import AmexExpressCheckoutCard as AmexExpressCheckoutCard -from braintree.android_pay_card import AndroidPayCard as AndroidPayCard -from braintree.apple_pay_card import ApplePayCard as ApplePayCard -from braintree.credit_card import CreditCard as CreditCard -from braintree.error_result import ErrorResult as ErrorResult -from braintree.europe_bank_account import EuropeBankAccount as EuropeBankAccount -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.ids_search import IdsSearch as IdsSearch -from braintree.masterpass_card import MasterpassCard as MasterpassCard -from braintree.payment_method import PaymentMethod as PaymentMethod -from braintree.payment_method_nonce import PaymentMethodNonce as PaymentMethodNonce -from braintree.payment_method_parser import parse_payment_method as parse_payment_method -from braintree.paypal_account import PayPalAccount as PayPalAccount -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.samsung_pay_card import SamsungPayCard as SamsungPayCard -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.unknown_payment_method import UnknownPaymentMethod as UnknownPaymentMethod -from braintree.us_bank_account import UsBankAccount as UsBankAccount -from braintree.venmo_account import VenmoAccount as VenmoAccount -from braintree.visa_checkout_card import VisaCheckoutCard as VisaCheckoutCard +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.successful_result import SuccessfulResult +from braintree.unknown_payment_method import UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard class PaymentMethodGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create(self, params: Any | None = ...): ... - def find(self, payment_method_token): ... - def update(self, payment_method_token, params): ... - def delete(self, payment_method_token, options: Any | None = ...): ... - options: Any - def grant(self, payment_method_token, options: Any | None = ...): ... - def revoke(self, payment_method_token): ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... + def find( + self, payment_method_token: str + ) -> ( + AndroidPayCard + | ApplePayCard + | EuropeBankAccount + | CreditCard + | PayPalAccount + | UsBankAccount + | VenmoAccount + | VisaCheckoutCard + | AmexExpressCheckoutCard + | SepaDirectDebitAccount + | MasterpassCard + | SamsungPayCard + | UnknownPaymentMethod + ): ... + def update(self, payment_method_token: str, params) -> SuccessfulResult | ErrorResult: ... + def delete(self, payment_method_token: str, options=None) -> SuccessfulResult: ... + options: dict[str, Incomplete] + def grant(self, payment_method_token: str, options=None) -> SuccessfulResult | ErrorResult: ... + def revoke(self, payment_method_token: str) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/payment_method_nonce.pyi b/stubs/braintree/braintree/payment_method_nonce.pyi index 35a804c8e6eb..9848d09b7fe8 100644 --- a/stubs/braintree/braintree/payment_method_nonce.pyi +++ b/stubs/braintree/braintree/payment_method_nonce.pyi @@ -1,16 +1,17 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.bin_data import BinData as BinData -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource -from braintree.three_d_secure_info import ThreeDSecureInfo as ThreeDSecureInfo +from braintree.bin_data import BinData +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult +from braintree.three_d_secure_info import ThreeDSecureInfo class PaymentMethodNonce(Resource): @staticmethod - def create(payment_method_token, params=...): ... + def create(payment_method_token: str, params={}) -> SuccessfulResult | ErrorResult: ... @staticmethod - def find(payment_method_nonce): ... - three_d_secure_info: Any - authentication_insight: Any - bin_data: Any + def find(payment_method_nonce: str) -> PaymentMethodNonce: ... + three_d_secure_info: ThreeDSecureInfo | None + authentication_insight: Incomplete + bin_data: BinData def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_method_nonce_gateway.pyi b/stubs/braintree/braintree/payment_method_nonce_gateway.pyi index a8bd929d4dc6..df513455ac4d 100644 --- a/stubs/braintree/braintree/payment_method_nonce_gateway.pyi +++ b/stubs/braintree/braintree/payment_method_nonce_gateway.pyi @@ -1,15 +1,12 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.payment_method_nonce import PaymentMethodNonce as PaymentMethodNonce -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.payment_method_nonce import PaymentMethodNonce +from braintree.successful_result import SuccessfulResult class PaymentMethodNonceGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def create(self, payment_method_token, params=...): ... - def find(self, payment_method_nonce): ... + def create(self, payment_method_token: str, params=...) -> SuccessfulResult | ErrorResult: ... + def find(self, payment_method_nonce: str) -> PaymentMethodNonce: ... diff --git a/stubs/braintree/braintree/payment_method_parser.pyi b/stubs/braintree/braintree/payment_method_parser.pyi index 17d9fb752793..9881d41f3a9c 100644 --- a/stubs/braintree/braintree/payment_method_parser.pyi +++ b/stubs/braintree/braintree/payment_method_parser.pyi @@ -1,15 +1,31 @@ -from braintree.amex_express_checkout_card import AmexExpressCheckoutCard as AmexExpressCheckoutCard -from braintree.android_pay_card import AndroidPayCard as AndroidPayCard -from braintree.apple_pay_card import ApplePayCard as ApplePayCard -from braintree.credit_card import CreditCard as CreditCard -from braintree.europe_bank_account import EuropeBankAccount as EuropeBankAccount -from braintree.masterpass_card import MasterpassCard as MasterpassCard -from braintree.payment_method import PaymentMethod as PaymentMethod -from braintree.paypal_account import PayPalAccount as PayPalAccount -from braintree.samsung_pay_card import SamsungPayCard as SamsungPayCard -from braintree.unknown_payment_method import UnknownPaymentMethod as UnknownPaymentMethod -from braintree.us_bank_account import UsBankAccount as UsBankAccount -from braintree.venmo_account import VenmoAccount as VenmoAccount -from braintree.visa_checkout_card import VisaCheckoutCard as VisaCheckoutCard +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.unknown_payment_method import UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard -def parse_payment_method(gateway, attributes): ... +def parse_payment_method( + gateway, attributes +) -> ( + PayPalAccount + | CreditCard + | EuropeBankAccount + | ApplePayCard + | AndroidPayCard + | AmexExpressCheckoutCard + | SepaDirectDebitAccount + | VenmoAccount + | UsBankAccount + | VisaCheckoutCard + | MasterpassCard + | SamsungPayCard + | UnknownPaymentMethod +): ... diff --git a/stubs/braintree/braintree/paypal_account.pyi b/stubs/braintree/braintree/paypal_account.pyi index 24a0e923b0d9..984bb08de2d8 100644 --- a/stubs/braintree/braintree/paypal_account.pyi +++ b/stubs/braintree/braintree/paypal_account.pyi @@ -1,16 +1,16 @@ -from typing import Any - -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.subscription import Subscription +from braintree.successful_result import SuccessfulResult class PayPalAccount(Resource): @staticmethod - def find(paypal_account_token): ... + def find(paypal_account_token: str) -> PayPalAccount | None: ... @staticmethod - def delete(paypal_account_token): ... + def delete(paypal_account_token: str) -> SuccessfulResult: ... @staticmethod - def update(paypal_account_token, params: Any | None = ...): ... + def update(paypal_account_token: str, params=None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def signature(): ... - subscriptions: Any + def signature() -> list[str | dict[str, list[str]]]: ... + subscriptions: list[Subscription] def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/paypal_account_gateway.pyi b/stubs/braintree/braintree/paypal_account_gateway.pyi index fa7a306c0ac4..873cca8b10d1 100644 --- a/stubs/braintree/braintree/paypal_account_gateway.pyi +++ b/stubs/braintree/braintree/paypal_account_gateway.pyi @@ -1,15 +1,13 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.paypal_account import PayPalAccount as PayPalAccount -from braintree.resource import Resource as Resource -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.error_result import ErrorResult +from braintree.paypal_account import PayPalAccount +from braintree.successful_result import SuccessfulResult class PayPalAccountGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def find(self, paypal_account_token): ... - def delete(self, paypal_account_token): ... - def update(self, paypal_account_token, params: Any | None = ...): ... + def find(self, paypal_account_token: str) -> PayPalAccount | None: ... + def delete(self, paypal_account_token: str) -> SuccessfulResult: ... + def update(self, paypal_account_token: str, params=None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/paypal_here.pyi b/stubs/braintree/braintree/paypal_here.pyi index 6bfd845a332c..9c187e69eae8 100644 --- a/stubs/braintree/braintree/paypal_here.pyi +++ b/stubs/braintree/braintree/paypal_here.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class PayPalHere(Resource): def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/paypal_payment_resource.pyi b/stubs/braintree/braintree/paypal_payment_resource.pyi new file mode 100644 index 000000000000..81b5e5e3d987 --- /dev/null +++ b/stubs/braintree/braintree/paypal_payment_resource.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult + +class PayPalPaymentResource(Resource): + def __init__(self, gateway, attributes) -> None: ... + @staticmethod + def update(request) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def update_signature() -> list[Incomplete]: ... diff --git a/stubs/braintree/braintree/paypal_payment_resource_gateway.pyi b/stubs/braintree/braintree/paypal_payment_resource_gateway.pyi new file mode 100644 index 000000000000..10eb5fd462a1 --- /dev/null +++ b/stubs/braintree/braintree/paypal_payment_resource_gateway.pyi @@ -0,0 +1,10 @@ +from braintree.braintree_gateway import BraintreeGateway +from braintree.configuration import Configuration +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class PayPalPaymentResourceGateway: + config: Configuration + gateway: BraintreeGateway + def __init__(self, gateway: BraintreeGateway) -> None: ... + def update(self, params) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/plan.pyi b/stubs/braintree/braintree/plan.pyi index 8ff3bcd564a4..47de7b28c147 100644 --- a/stubs/braintree/braintree/plan.pyi +++ b/stubs/braintree/braintree/plan.pyi @@ -1,15 +1,20 @@ -from typing import Any - -from braintree.add_on import AddOn as AddOn -from braintree.configuration import Configuration as Configuration -from braintree.discount import Discount as Discount -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.util.http import Http as Http +from braintree.add_on import AddOn +from braintree.discount import Discount +from braintree.resource import Resource class Plan(Resource): - add_ons: Any - discounts: Any + add_ons: list[AddOn] + discounts: list[Discount] def __init__(self, gateway, attributes) -> None: ... @staticmethod def all(): ... + @staticmethod + def create(params=None): ... + @staticmethod + def find(subscription_id): ... + @staticmethod + def update(subscription_id, params=None): ... + @staticmethod + def create_signature(): ... + @staticmethod + def update_signature(): ... diff --git a/stubs/braintree/braintree/plan_gateway.pyi b/stubs/braintree/braintree/plan_gateway.pyi index 61b37eb77ffb..8d4416170c5d 100644 --- a/stubs/braintree/braintree/plan_gateway.pyi +++ b/stubs/braintree/braintree/plan_gateway.pyi @@ -1,14 +1,10 @@ -from typing import Any - -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.plan import Plan as Plan -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from _typeshed import Incomplete class PlanGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... def all(self): ... + def create(self, params=None): ... + def find(self, plan_id): ... + def update(self, plan_id, params=None): ... diff --git a/stubs/braintree/braintree/processor_response_types.pyi b/stubs/braintree/braintree/processor_response_types.pyi index d17a9841fb69..e8a1751cc402 100644 --- a/stubs/braintree/braintree/processor_response_types.pyi +++ b/stubs/braintree/braintree/processor_response_types.pyi @@ -1,4 +1,6 @@ +from typing import Final + class ProcessorResponseTypes: - Approved: str - SoftDeclined: str - HardDeclined: str + Approved: Final = "approved" + SoftDeclined: Final = "soft_declined" + HardDeclined: Final = "hard_declined" diff --git a/stubs/braintree/braintree/receiver.pyi b/stubs/braintree/braintree/receiver.pyi new file mode 100644 index 000000000000..8c78f46a560a --- /dev/null +++ b/stubs/braintree/braintree/receiver.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class Receiver(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/resource.pyi b/stubs/braintree/braintree/resource.pyi index 1bda497526d7..8f7d9f83e34e 100644 --- a/stubs/braintree/braintree/resource.pyi +++ b/stubs/braintree/braintree/resource.pyi @@ -1,6 +1,6 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter text_type = str raw_type = bytes @@ -8,5 +8,5 @@ raw_type = bytes class Resource(AttributeGetter): @staticmethod def verify_keys(params, signature) -> None: ... - gateway: Any + gateway: Incomplete def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/resource_collection.pyi b/stubs/braintree/braintree/resource_collection.pyi index 6028d17f800a..80b32c2f77b3 100644 --- a/stubs/braintree/braintree/resource_collection.pyi +++ b/stubs/braintree/braintree/resource_collection.pyi @@ -1,7 +1,5 @@ +from _typeshed import Incomplete from collections.abc import Generator -from typing import Any - -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError class ResourceCollection: def __init__(self, query, results, method) -> None: ... @@ -10,7 +8,7 @@ class ResourceCollection: @property def first(self): ... @property - def items(self) -> Generator[Any, None, None]: ... + def items(self) -> Generator[Incomplete]: ... @property def ids(self): ... def __iter__(self): ... diff --git a/stubs/braintree/braintree/revoked_payment_method_metadata.pyi b/stubs/braintree/braintree/revoked_payment_method_metadata.pyi index 60358ffb5e98..b1464e75436e 100644 --- a/stubs/braintree/braintree/revoked_payment_method_metadata.pyi +++ b/stubs/braintree/braintree/revoked_payment_method_metadata.pyi @@ -1,10 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.payment_method_parser import parse_payment_method as parse_payment_method -from braintree.resource import Resource as Resource +from braintree.resource import Resource class RevokedPaymentMethodMetadata(Resource): - revoked_payment_method: Any - customer_id: Any - token: Any + revoked_payment_method: Incomplete + customer_id: Incomplete + token: Incomplete def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/risk_data.pyi b/stubs/braintree/braintree/risk_data.pyi index b0b1c61b83c8..cda4f17551a2 100644 --- a/stubs/braintree/braintree/risk_data.pyi +++ b/stubs/braintree/braintree/risk_data.pyi @@ -1,3 +1,4 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter -class RiskData(AttributeGetter): ... +class RiskData(AttributeGetter): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/samsung_pay_card.pyi b/stubs/braintree/braintree/samsung_pay_card.pyi index ce734bb21661..ef1dad97ebb7 100644 --- a/stubs/braintree/braintree/samsung_pay_card.pyi +++ b/stubs/braintree/braintree/samsung_pay_card.pyi @@ -1,11 +1,10 @@ -from typing import Any - -from braintree.address import Address as Address -from braintree.resource import Resource as Resource +from braintree.address import Address +from braintree.resource import Resource +from braintree.subscription import Subscription class SamsungPayCard(Resource): - billing_address: Any - subscriptions: Any + billing_address: Address | None + subscriptions: list[Subscription] def __init__(self, gateway, attributes) -> None: ... @property def expiration_date(self): ... diff --git a/stubs/braintree/braintree/search.pyi b/stubs/braintree/braintree/search.pyi index a9449ff61657..7943e722d309 100644 --- a/stubs/braintree/braintree/search.pyi +++ b/stubs/braintree/braintree/search.pyi @@ -1,45 +1,60 @@ -from typing import Any +from _typeshed import Incomplete +from typing import overload class Search: class IsNodeBuilder: - name: Any + name: Incomplete def __init__(self, name) -> None: ... def __eq__(self, value): ... def is_equal(self, value): ... + class EqualityNodeBuilder(IsNodeBuilder): def __ne__(self, value): ... def is_not_equal(self, value): ... + class KeyValueNodeBuilder: - name: Any + name: Incomplete def __init__(self, name) -> None: ... def __eq__(self, value): ... def is_equal(self, value): ... def __ne__(self, value): ... def is_not_equal(self, value): ... + class PartialMatchNodeBuilder(EqualityNodeBuilder): def starts_with(self, value): ... def ends_with(self, value): ... + class EndsWithNodeBuilder: - name: Any + name: Incomplete def __init__(self, name) -> None: ... def ends_with(self, value): ... + class TextNodeBuilder(PartialMatchNodeBuilder): def contains(self, value): ... + class Node: - name: Any - dict: Any + name: Incomplete + dict: Incomplete def __init__(self, name, dict) -> None: ... def to_param(self): ... + class MultipleValueNodeBuilder: - name: Any - whitelist: Any - def __init__(self, name, whitelist=...) -> None: ... - def in_list(self, *values): ... + name: Incomplete + whitelist: Incomplete + def __init__(self, name, whitelist=[]) -> None: ... + + @overload + def in_list(self, value: list[str]) -> Search.Node: ... + @overload + def in_list(self, *values: str) -> Search.Node: ... + def __eq__(self, value): ... + class MultipleValueOrTextNodeBuilder(TextNodeBuilder, MultipleValueNodeBuilder): - def __init__(self, name, whitelist=...) -> None: ... + def __init__(self, name, whitelist=[]) -> None: ... + class RangeNodeBuilder: - name: Any + name: Incomplete def __init__(self, name) -> None: ... def __eq__(self, value): ... def is_equal(self, value): ... diff --git a/stubs/braintree/braintree/sender.pyi b/stubs/braintree/braintree/sender.pyi new file mode 100644 index 000000000000..5cd107b52b32 --- /dev/null +++ b/stubs/braintree/braintree/sender.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class Sender(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/sepa_direct_debit_account.pyi b/stubs/braintree/braintree/sepa_direct_debit_account.pyi new file mode 100644 index 000000000000..82b46b220f0d --- /dev/null +++ b/stubs/braintree/braintree/sepa_direct_debit_account.pyi @@ -0,0 +1,10 @@ +from braintree.resource import Resource +from braintree.subscription import Subscription + +class SepaDirectDebitAccount(Resource): + @staticmethod + def find(sepa_direct_debit_account_token): ... + @staticmethod + def delete(sepa_direct_debit_account_token): ... + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi b/stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi new file mode 100644 index 000000000000..f3a6de9f9a54 --- /dev/null +++ b/stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +class SepaDirectDebitAccountGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find(self, sepa_direct_debit_account_token): ... + def delete(self, sepa_direct_debit_account_token): ... diff --git a/stubs/braintree/braintree/settlement_batch_summary.pyi b/stubs/braintree/braintree/settlement_batch_summary.pyi index 6b0a8541106f..0e48629a28d1 100644 --- a/stubs/braintree/braintree/settlement_batch_summary.pyi +++ b/stubs/braintree/braintree/settlement_batch_summary.pyi @@ -1,13 +1,5 @@ -from typing import Any - -from braintree.configuration import Configuration as Configuration -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.util.http import Http as Http +from braintree.resource import Resource class SettlementBatchSummary(Resource): @staticmethod - def generate(settlement_date, group_by_custom_field: Any | None = ...): ... + def generate(settlement_date, group_by_custom_field=None): ... diff --git a/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi b/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi index 31644a72745a..09c324ea0d3e 100644 --- a/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi +++ b/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi @@ -1,12 +1,7 @@ -from typing import Any - -from braintree.error_result import ErrorResult as ErrorResult -from braintree.resource import Resource as Resource -from braintree.settlement_batch_summary import SettlementBatchSummary as SettlementBatchSummary -from braintree.successful_result import SuccessfulResult as SuccessfulResult +from _typeshed import Incomplete class SettlementBatchSummaryGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def generate(self, settlement_date, group_by_custom_field: Any | None = ...): ... + def generate(self, settlement_date, group_by_custom_field=None): ... diff --git a/stubs/braintree/braintree/signature_service.pyi b/stubs/braintree/braintree/signature_service.pyi index abe5ff8b34de..3fa67bd103e2 100644 --- a/stubs/braintree/braintree/signature_service.pyi +++ b/stubs/braintree/braintree/signature_service.pyi @@ -1,10 +1,8 @@ -from typing import Any - -from braintree.util.crypto import Crypto as Crypto +from _typeshed import Incomplete class SignatureService: - private_key: Any - hmac_hash: Any + private_key: Incomplete + hmac_hash: Incomplete def __init__(self, private_key, hashfunc=...) -> None: ... def sign(self, data): ... def hash(self, data): ... diff --git a/stubs/braintree/braintree/status_event.pyi b/stubs/braintree/braintree/status_event.pyi index b4110a2f457e..8f316829d4a6 100644 --- a/stubs/braintree/braintree/status_event.pyi +++ b/stubs/braintree/braintree/status_event.pyi @@ -1,7 +1,7 @@ -from typing import Any +from decimal import Decimal -from braintree.resource import Resource as Resource +from braintree.resource import Resource class StatusEvent(Resource): - amount: Any + amount: Decimal def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/sub_merchant.pyi b/stubs/braintree/braintree/sub_merchant.pyi new file mode 100644 index 000000000000..ad790ceae83e --- /dev/null +++ b/stubs/braintree/braintree/sub_merchant.pyi @@ -0,0 +1,4 @@ +from braintree.attribute_getter import AttributeGetter + +class SubMerchant(AttributeGetter): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/subscription.pyi b/stubs/braintree/braintree/subscription.pyi index 33aa2bc4493a..24bb2a09a05c 100644 --- a/stubs/braintree/braintree/subscription.pyi +++ b/stubs/braintree/braintree/subscription.pyi @@ -1,55 +1,59 @@ -from typing import Any +from _typeshed import Incomplete +from datetime import date +from decimal import Decimal +from typing import Final -from braintree.add_on import AddOn as AddOn -from braintree.configuration import Configuration as Configuration -from braintree.descriptor import Descriptor as Descriptor -from braintree.discount import Discount as Discount -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.subscription_status_event import SubscriptionStatusEvent as SubscriptionStatusEvent -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.transaction import Transaction as Transaction -from braintree.util.http import Http as Http +from braintree.add_on import AddOn +from braintree.descriptor import Descriptor +from braintree.discount import Discount +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.subscription_status_event import SubscriptionStatusEvent +from braintree.successful_result import SuccessfulResult +from braintree.transaction import Transaction class Subscription(Resource): class TrialDurationUnit: - Day: str - Month: str + Day: Final = "day" + Month: Final = "month" + class Source: - Api: str - ControlPanel: str - Recurring: str + Api: Final = "api" + ControlPanel: Final = "control_panel" + Recurring: Final = "recurring" + class Status: - Active: str - Canceled: str - Expired: str - PastDue: str - Pending: str + Active: Final = "Active" + Canceled: Final = "Canceled" + Expired: Final = "Expired" + PastDue: Final = "Past Due" + Pending: Final = "Pending" + @staticmethod - def create(params: Any | None = ...): ... + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod def create_signature(): ... @staticmethod - def find(subscription_id): ... + def find(subscription_id: str) -> Subscription: ... @staticmethod - def retry_charge(subscription_id, amount: Any | None = ..., submit_for_settlement: bool = ...): ... + def retry_charge(subscription_id, amount=None, submit_for_settlement: bool = False): ... @staticmethod - def update(subscription_id, params: Any | None = ...): ... + def update(subscription_id: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def cancel(subscription_id): ... + def cancel(subscription_id: str) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def search(*query): ... + def search(*query) -> ResourceCollection: ... @staticmethod def update_signature(): ... - price: Any - balance: Any - next_billing_period_amount: Any - add_ons: Any - descriptor: Any - description: Any - discounts: Any - status_history: Any - transactions: Any + price: Decimal + balance: Decimal + next_billing_date: date + next_billing_period_amount: Decimal + add_ons: list[AddOn] + descriptor: Descriptor + description: Incomplete + discounts: list[Discount] + status_history: list[SubscriptionStatusEvent] + transactions: list[Transaction] def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/subscription_details.pyi b/stubs/braintree/braintree/subscription_details.pyi index f54a2419f2a1..df2da1daa1a6 100644 --- a/stubs/braintree/braintree/subscription_details.pyi +++ b/stubs/braintree/braintree/subscription_details.pyi @@ -1,3 +1,7 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from datetime import date -class SubscriptionDetails(AttributeGetter): ... +from braintree.attribute_getter import AttributeGetter + +class SubscriptionDetails(AttributeGetter): + billing_period_start_date: date + billing_period_end_date: date diff --git a/stubs/braintree/braintree/subscription_gateway.pyi b/stubs/braintree/braintree/subscription_gateway.pyi index 766dc57e6728..44907bce1d97 100644 --- a/stubs/braintree/braintree/subscription_gateway.pyi +++ b/stubs/braintree/braintree/subscription_gateway.pyi @@ -1,20 +1,19 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.subscription import Subscription as Subscription -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.transaction import Transaction as Transaction +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.subscription import Subscription +from braintree.successful_result import SuccessfulResult class SubscriptionGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def cancel(self, subscription_id): ... - def create(self, params: Any | None = ...): ... - def find(self, subscription_id): ... - def retry_charge(self, subscription_id, amount: Any | None = ..., submit_for_settlement: bool = ...): ... - def search(self, *query): ... - def update(self, subscription_id, params: Any | None = ...): ... + def cancel(self, subscription_id: str) -> SuccessfulResult | ErrorResult | None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def find(self, subscription_id: str) -> Subscription: ... + def retry_charge(self, subscription_id, amount=None, submit_for_settlement: bool = False): ... + def search(self, *query) -> ResourceCollection: ... + def update( + self, subscription_id: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/subscription_search.pyi b/stubs/braintree/braintree/subscription_search.pyi index 43f7759d283f..45b03dccf6c8 100644 --- a/stubs/braintree/braintree/subscription_search.pyi +++ b/stubs/braintree/braintree/subscription_search.pyi @@ -1,19 +1,15 @@ -from typing import Any - -from braintree import Subscription as Subscription -from braintree.search import Search as Search -from braintree.util import Constants as Constants +from braintree.search import Search class SubscriptionSearch: - billing_cycles_remaining: Any - created_at: Any - days_past_due: Any - id: Any - ids: Any - in_trial_period: Any - merchant_account_id: Any - next_billing_date: Any - plan_id: Any - price: Any - status: Any - transaction_id: Any + billing_cycles_remaining: Search.RangeNodeBuilder + created_at: Search.RangeNodeBuilder + days_past_due: Search.RangeNodeBuilder + id: Search.TextNodeBuilder + ids: Search.MultipleValueNodeBuilder + in_trial_period: Search.MultipleValueNodeBuilder + merchant_account_id: Search.MultipleValueNodeBuilder + next_billing_date: Search.RangeNodeBuilder + plan_id: Search.MultipleValueOrTextNodeBuilder + price: Search.RangeNodeBuilder + status: Search.MultipleValueNodeBuilder + transaction_id: Search.TextNodeBuilder diff --git a/stubs/braintree/braintree/subscription_status_event.pyi b/stubs/braintree/braintree/subscription_status_event.pyi index c649e0512643..987f44a788ee 100644 --- a/stubs/braintree/braintree/subscription_status_event.pyi +++ b/stubs/braintree/braintree/subscription_status_event.pyi @@ -1,8 +1,8 @@ -from typing import Any +from decimal import Decimal -from braintree.resource import Resource as Resource +from braintree.resource import Resource class SubscriptionStatusEvent(Resource): - balance: Any - price: Any + balance: Decimal + price: Decimal def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/successful_result.pyi b/stubs/braintree/braintree/successful_result.pyi index 66fbb74e7586..962d23484093 100644 --- a/stubs/braintree/braintree/successful_result.pyi +++ b/stubs/braintree/braintree/successful_result.pyi @@ -1,5 +1,7 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from typing import Literal + +from braintree.attribute_getter import AttributeGetter class SuccessfulResult(AttributeGetter): @property - def is_success(self): ... + def is_success(self) -> Literal[True]: ... diff --git a/stubs/pyvmomi/pyVmomi/__init__.pyi b/stubs/braintree/braintree/test/__init__.pyi similarity index 100% rename from stubs/pyvmomi/pyVmomi/__init__.pyi rename to stubs/braintree/braintree/test/__init__.pyi diff --git a/stubs/braintree/braintree/test/authentication_ids.pyi b/stubs/braintree/braintree/test/authentication_ids.pyi new file mode 100644 index 000000000000..56f4664d370d --- /dev/null +++ b/stubs/braintree/braintree/test/authentication_ids.pyi @@ -0,0 +1,18 @@ +from typing import Final + +class AuthenticationIds: + ThreeDSecureVisaFullAuthentication: Final = "fake-three-d-secure-visa-full-authentication-id" + ThreeDSecureVisaLookupTimeout: Final = "fake-three-d-secure-visa-lookup-timeout-id" + ThreeDSecureVisaFailedSignature: Final = "fake-three-d-secure-visa-failed-signature-id" + ThreeDSecureVisaFailedAuthentication: Final = "fake-three-d-secure-visa-failed-authentication-id" + ThreeDSecureVisaAttemptsNonParticipating: Final[str] + ThreeDSecureVisaNoteEnrolled: Final = "fake-three-d-secure-visa-not-enrolled-id" + ThreeDSecureVisaUnavailable: Final = "fake-three-d-secure-visa-unavailable-id" + ThreeDSecureVisaMPILookupError: Final = "fake-three-d-secure-visa-mpi-lookup-error-id" + ThreeDSecureVisaMPIAuthenticateError: Final = "fake-three-d-secure-visa-mpi-authenticate-error-id" + ThreeDSecureVisaAuthenticationUnavailable: Final[str] + ThreeDSecureVisaBypassedAuthentication: Final[str] + ThreeDSecureTwoVisaSuccessfulFrictionlessAuthentication: Final[str] + ThreeDSecureTwoVisaSuccessfulStepUpAuthentication: Final[str] + ThreeDSecureTwoVisaErrorOnLookup: Final = "fake-three-d-secure-two-visa-error-on-lookup-id" + ThreeDSecureTwoVisaTimeoutOnLookup: Final = "fake-three-d-secure-two-visa-timeout-on-lookup-id" diff --git a/stubs/braintree/braintree/test/credit_card_defaults.pyi b/stubs/braintree/braintree/test/credit_card_defaults.pyi new file mode 100644 index 000000000000..74a1cdc4d67d --- /dev/null +++ b/stubs/braintree/braintree/test/credit_card_defaults.pyi @@ -0,0 +1,5 @@ +from typing import Final + +class CreditCardDefaults: + CountryOfIssuance: Final = "USA" + IssuingBank: Final = "NETWORK ONLY" diff --git a/stubs/braintree/braintree/test/credit_card_numbers.pyi b/stubs/braintree/braintree/test/credit_card_numbers.pyi new file mode 100644 index 000000000000..7ddbb912033b --- /dev/null +++ b/stubs/braintree/braintree/test/credit_card_numbers.pyi @@ -0,0 +1,45 @@ +from typing import Final + +class CreditCardNumbers: + class CardTypeIndicators: + Business: Final = "4229989800000003" + Commercial: Final = "4111111111131010" + Consumer: Final = "4229989700000004" + Corporate: Final = "4229989100000000" + DurbinRegulated: Final = "4111161010101010" + Debit: Final = "4117101010101010" + Healthcare: Final = "4111111510101010" + Payroll: Final = "4111111114101010" + Prepaid: Final = "4111111111111210" + PrepaidReloadable: Final = "4229989900000002" + Purchase: Final = "4229989500000006" + IssuingBank: Final = "4111111141010101" + CountryOfIssuance: Final = "4111111111121102" + No: Final = "4111111111310101" + Unknown: Final = "4111111111112101" + + Maestro: Final = "6304000000000000" + MasterCard: Final = "5555555555554444" + MasterCardInternational: Final = "5105105105105100" + Visa: Final = "4012888888881881" + VisaInternational: Final = "4009348888881881" + VisaPrepaid: Final = "4500600000000061" + Discover: Final = "6011111111111117" + Elo: Final = "5066991111111118" + Hiper: Final = "6370950000000005" + Hipercard: Final = "6062820524845321" + Amex: Final = "378734493671000" + + class FailsSandboxVerification: + AmEx: Final = "378734493671000" + Discover: Final = "6011000990139424" + MasterCard: Final = "5105105105105100" + Visa: Final = "4000111111111115" + + class AmexPayWithPoints: + Success: Final = "371260714673002" + IneligibleCard: Final = "378267515471109" + InsufficientPoints: Final = "371544868764018" + + class Disputes: + Chargeback: Final = "4023898493988028" diff --git a/stubs/braintree/braintree/test/merchant_account.pyi b/stubs/braintree/braintree/test/merchant_account.pyi new file mode 100644 index 000000000000..3c0c6fafdf14 --- /dev/null +++ b/stubs/braintree/braintree/test/merchant_account.pyi @@ -0,0 +1,7 @@ +from typing import Final + +Approve: Final = "approve_me" +InsufficientFundsContactUs: Final = "insufficient_funds__contact" +AccountNotAuthorizedContactUs: Final = "account_not_authorized__contact" +BankRejectedUpdateFundingInformation: Final = "bank_rejected__update" +BankRejectedNone: Final = "bank_rejected__none" diff --git a/stubs/braintree/braintree/test/nonces.pyi b/stubs/braintree/braintree/test/nonces.pyi new file mode 100644 index 000000000000..1c85c2864e91 --- /dev/null +++ b/stubs/braintree/braintree/test/nonces.pyi @@ -0,0 +1,88 @@ +from typing import Final + +class Nonces: + AbstractTransactable: Final = "fake-abstract-transactable-nonce" + AmexExpressCheckoutCard: Final = "fake-amex-express-checkout-nonce" + AndroidPayCard: Final = "fake-android-pay-nonce" + AndroidPayCardAmEx: Final = "fake-android-pay-amex-nonce" + AndroidPayCardDiscover: Final = "fake-android-pay-discover-nonce" + AndroidPayCardMasterCard: Final = "fake-android-pay-mastercard-nonce" + AndroidPayCardVisa: Final = "fake-android-pay-visa-nonce" + ApplePayAmEx: Final = "fake-apple-pay-amex-nonce" + ApplePayMasterCard: Final = "fake-apple-pay-mastercard-nonce" + ApplePayMpan: Final = "fake-apple-pay-mpan-nonce" + ApplePayVisa: Final = "fake-apple-pay-visa-nonce" + Consumed: Final = "fake-consumed-nonce" + Europe: Final = "fake-europe-bank-account-nonce" + GatewayRejectedFraud: Final = "fake-gateway-rejected-fraud-nonce" + GatewayRejectedRiskThreshold: Final = "fake-gateway-rejected-risk-thresholds-nonce" + LocalPayment: Final = "fake-local-payment-method-nonce" + LuhnInvalid: Final = "fake-luhn-invalid-nonce" + MasterpassAmEx: Final = "fake-masterpass-amex-nonce" + MasterpassDiscover: Final = "fake-masterpass-discover-nonce" + MasterpassMasterCard: Final = "fake-masterpass-mastercard-nonce" + MasterpassVisa: Final = "fake-masterpass-visa-nonce" + PayPalBillingAgreement: Final = "fake-paypal-billing-agreement-nonce" + PayPalFuturePayment: Final = "fake-paypal-future-nonce" + PayPalFuturePaymentRefreshToken: Final = "fake-paypal-future-refresh-token-nonce" + PayPalOneTimePayment: Final = "fake-paypal-one-time-nonce" + ProcessorDeclinedAmEx: Final = "fake-processor-declined-amex-nonce" + ProcessorDeclinedDiscover: Final = "fake-processor-declined-discover-nonce" + ProcessorDeclinedMasterCard: Final = "fake-processor-declined-mastercard-nonce" + ProcessorDeclinedVisa: Final = "fake-processor-declined-visa-nonce" + ProcessorFailureJCB: Final = "fake-processor-failure-jcb-nonce" + SEPA: Final = "fake-sepa-bank-account-nonce" + MetaCheckoutCard: Final = "fake-meta-checkout-card-nonce" + MetaCheckoutToken: Final = "fake-meta-checkout-token-nonce" + SamsungPayAmex: Final = "tokensam_fake_american_express" + SamsungPayDiscover: Final = "tokensam_fake_american_express" + SamsungPayMasterCard: Final = "tokensam_fake_mastercard" + SamsungPayVisa: Final = "tokensam_fake_visa" + SepaDirectDebit: Final = "fake-sepa-direct-debit-nonce" + ThreeDSecureTwoVisaErrorOnLookup: Final = "fake-three-d-secure-two-visa-error-on-lookup-nonce" + ThreeDSecureTwoVisaSuccessfulFrictionlessAuthentication: Final[str] + ThreeDSecureTwoVisaSuccessfulStepUpAuthentication: Final[str] + ThreeDSecureTwoVisaTimeoutOnLookup: Final[str] + ThreeDSecureVisaAttemptsNonParticipating: Final[str] + ThreeDSecureVisaAuthenticationUnavailable: Final[str] + ThreeDSecureVisaBypassedAuthentication: Final[str] + ThreeDSecureVisaFailedAuthentication: Final[str] + ThreeDSecureVisaFailedSignature: Final = "fake-three-d-secure-visa-failed-signature-nonce" + ThreeDSecureVisaFullAuthentication: Final = "fake-three-d-secure-visa-full-authentication-nonce" + ThreeDSecureVisaLookupTimeout: Final = "fake-three-d-secure-visa-lookup-timeout-nonce" + ThreeDSecureVisaMPIAuthenticateError: Final[str] + ThreeDSecureVisaMPILookupError: Final = "fake-three-d-secure-visa-mpi-lookup-error-nonce" + ThreeDSecureVisaNoteEnrolled: Final = "fake-three-d-secure-visa-not-enrolled-nonce" + ThreeDSecureVisaUnavailable: Final = "fake-three-d-secure-visa-unavailable-nonce" + Transactable: Final = "fake-valid-nonce" + TransactableAmEx: Final = "fake-valid-amex-nonce" + TransactableBusiness: Final = "fake-valid-business-nonce" + TransactableCommercial: Final = "fake-valid-commercial-nonce" + TransactableConsumer: Final = "fake-valid-consumer-nonce" + TransactableCorporate: Final = "fake-valid-corporate-nonce" + TransactableCountryOfIssuanceCAD: Final = "fake-valid-country-of-issuance-cad-nonce" + TransactableCountryOfIssuanceUSA: Final = "fake-valid-country-of-issuance-usa-nonce" + TransactableDebit: Final = "fake-valid-debit-nonce" + TransactableDinersClub: Final = "fake-valid-dinersclub-nonce" + TransactableDiscover: Final = "fake-valid-discover-nonce" + TransactableDurbinRegulated: Final = "fake-valid-durbin-regulated-nonce" + TransactableHealthcare: Final = "fake-valid-healthcare-nonce" + TransactableIssuingBankNetworkOnly: Final = "fake-valid-issuing-bank-network-only-nonce" + TransactableJCB: Final = "fake-valid-jcb-nonce" + TransactableMaestro: Final = "fake-valid-maestro-nonce" + TransactableMasterCard: Final = "fake-valid-mastercard-nonce" + TransactableNoIndicators: Final = "fake-valid-no-indicators-nonce" + TransactablePayroll: Final = "fake-valid-payroll-nonce" + TransactablePinlessDebitVisa: Final = "fake-pinless-debit-visa-nonce" + TransactablePrepaid: Final = "fake-valid-prepaid-nonce" + TransactablePrepaidReloadable: Final = "fake-valid-prepaid-reloadable-nonce" + TransactablePurchase: Final = "fake-valid-purchase-nonce" + TransactableUnknownIndicators: Final = "fake-valid-unknown-indicators-nonce" + TransactableVisa: Final = "fake-valid-visa-nonce" + VenmoAccount: Final = "fake-venmo-account-nonce" + VenmoAccountTokenIssuanceError: Final = "fake-token-issuance-error-venmo-account-nonce" + VisaCheckoutAmEx: Final = "fake-visa-checkout-amex-nonce" + VisaCheckoutDiscover: Final = "fake-visa-checkout-discover-nonce" + VisaCheckoutMasterCard: Final = "fake-visa-checkout-mastercard-nonce" + VisaCheckoutVisa: Final = "fake-visa-checkout-visa-nonce" + UsBankAccount: Final = "fake-us-bank-account-nonce" diff --git a/stubs/braintree/braintree/test/venmo_sdk.pyi b/stubs/braintree/braintree/test/venmo_sdk.pyi new file mode 100644 index 000000000000..5f749a1e8aa9 --- /dev/null +++ b/stubs/braintree/braintree/test/venmo_sdk.pyi @@ -0,0 +1,9 @@ +from typing import Final + +def generate_test_payment_method_code(number): ... + +VisaPaymentMethodCode: Final = "stub-4111111111111111" +InvalidPaymentMethodCode: Final = "stub-invalid-payment-method-code" + +Session: Final = "stub-session" +InvalidSession: Final = "stub-invalid-session" diff --git a/stubs/braintree/braintree/testing_gateway.pyi b/stubs/braintree/braintree/testing_gateway.pyi index 262997c5db18..54727fdffc97 100644 --- a/stubs/braintree/braintree/testing_gateway.pyi +++ b/stubs/braintree/braintree/testing_gateway.pyi @@ -1,15 +1,10 @@ -from typing import Any - -from braintree.error_result import ErrorResult as ErrorResult -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.transaction import Transaction as Transaction +from _typeshed import Incomplete class TestingGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def make_past_due(self, subscription_id, number_of_days_past_due: int = ...) -> None: ... - def escrow_transaction(self, transaction_id) -> None: ... + def make_past_due(self, subscription_id, number_of_days_past_due: int = 1) -> None: ... def settle_transaction(self, transaction_id): ... def settlement_confirm_transaction(self, transaction_id): ... def settlement_decline_transaction(self, transaction_id): ... diff --git a/stubs/braintree/braintree/three_d_secure_info.pyi b/stubs/braintree/braintree/three_d_secure_info.pyi index 8758b9741dac..466cd4f27ec6 100644 --- a/stubs/braintree/braintree/three_d_secure_info.pyi +++ b/stubs/braintree/braintree/three_d_secure_info.pyi @@ -1,3 +1,3 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class ThreeDSecureInfo(AttributeGetter): ... diff --git a/stubs/braintree/braintree/transaction.pyi b/stubs/braintree/braintree/transaction.pyi index 59cee2fe0b24..7364f51f0f0f 100644 --- a/stubs/braintree/braintree/transaction.pyi +++ b/stubs/braintree/braintree/transaction.pyi @@ -1,120 +1,126 @@ -from typing import Any +from _typeshed import Incomplete +from datetime import datetime +from decimal import Decimal +from typing import Final -from braintree.add_on import AddOn as AddOn -from braintree.address import Address as Address -from braintree.amex_express_checkout_card import AmexExpressCheckoutCard as AmexExpressCheckoutCard -from braintree.android_pay_card import AndroidPayCard as AndroidPayCard -from braintree.apple_pay_card import ApplePayCard as ApplePayCard -from braintree.authorization_adjustment import AuthorizationAdjustment as AuthorizationAdjustment -from braintree.configuration import Configuration as Configuration -from braintree.credit_card import CreditCard as CreditCard -from braintree.customer import Customer as Customer -from braintree.descriptor import Descriptor as Descriptor -from braintree.disbursement_detail import DisbursementDetail as DisbursementDetail -from braintree.discount import Discount as Discount -from braintree.dispute import Dispute as Dispute -from braintree.error_result import ErrorResult as ErrorResult -from braintree.europe_bank_account import EuropeBankAccount as EuropeBankAccount -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.facilitated_details import FacilitatedDetails as FacilitatedDetails -from braintree.facilitator_details import FacilitatorDetails as FacilitatorDetails -from braintree.local_payment import LocalPayment as LocalPayment -from braintree.masterpass_card import MasterpassCard as MasterpassCard -from braintree.payment_instrument_type import PaymentInstrumentType as PaymentInstrumentType -from braintree.paypal_account import PayPalAccount as PayPalAccount -from braintree.paypal_here import PayPalHere as PayPalHere -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.risk_data import RiskData as RiskData -from braintree.samsung_pay_card import SamsungPayCard as SamsungPayCard -from braintree.status_event import StatusEvent as StatusEvent -from braintree.subscription_details import SubscriptionDetails as SubscriptionDetails -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.three_d_secure_info import ThreeDSecureInfo as ThreeDSecureInfo -from braintree.transaction_line_item import TransactionLineItem as TransactionLineItem -from braintree.us_bank_account import UsBankAccount as UsBankAccount -from braintree.venmo_account import VenmoAccount as VenmoAccount -from braintree.visa_checkout_card import VisaCheckoutCard as VisaCheckoutCard +from braintree.add_on import AddOn +from braintree.address import Address +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.authorization_adjustment import AuthorizationAdjustment +from braintree.credit_card import CreditCard +from braintree.customer import Customer +from braintree.descriptor import Descriptor +from braintree.disbursement_detail import DisbursementDetail +from braintree.discount import Discount +from braintree.dispute import Dispute +from braintree.europe_bank_account import EuropeBankAccount +from braintree.facilitated_details import FacilitatedDetails +from braintree.facilitator_details import FacilitatorDetails +from braintree.local_payment import LocalPayment +from braintree.masterpass_card import MasterpassCard +from braintree.meta_checkout_card import MetaCheckoutCard +from braintree.meta_checkout_token import MetaCheckoutToken +from braintree.package_details import PackageDetails +from braintree.payment_facilitator import PaymentFacilitator +from braintree.paypal_account import PayPalAccount +from braintree.paypal_here import PayPalHere +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.risk_data import RiskData +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.status_event import StatusEvent +from braintree.subscription_details import SubscriptionDetails +from braintree.three_d_secure_info import ThreeDSecureInfo +from braintree.transfer import Transfer +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard class Transaction(Resource): + class AchType: + SameDay: Final = "same_day" + Standard: Final = "standard" + class CreatedUsing: - FullInformation: str - Token: str + FullInformation: Final = "full_information" + Token: Final = "token" + class GatewayRejectionReason: - ApplicationIncomplete: str - Avs: str - AvsAndCvv: str - Cvv: str - Duplicate: str - Fraud: str - RiskThreshold: str - ThreeDSecure: str - TokenIssuance: str + ApplicationIncomplete: Final = "application_incomplete" + Avs: Final = "avs" + AvsAndCvv: Final = "avs_and_cvv" + Cvv: Final = "cvv" + Duplicate: Final = "duplicate" + ExcessiveRetry: Final = "excessive_retry" + Fraud: Final = "fraud" + RiskThreshold: Final = "risk_threshold" + ThreeDSecure: Final = "three_d_secure" + TokenIssuance: Final = "token_issuance" + + class ReasonCode: + ANY_REASON_CODE: Final = "any_reason_code" + class Source: - Api: str - ControlPanel: str - Recurring: str - class EscrowStatus: - HoldPending: str - Held: str - ReleasePending: str - Released: str - Refunded: str + Api: Final = "api" + ControlPanel: Final = "control_panel" + Recurring: Final = "recurring" + class Status: - AuthorizationExpired: str - Authorized: str - Authorizing: str - Failed: str - GatewayRejected: str - ProcessorDeclined: str - Settled: str - SettlementConfirmed: str - SettlementDeclined: str - SettlementFailed: str - SettlementPending: str - Settling: str - SubmittedForSettlement: str - Voided: str + AuthorizationExpired: Final = "authorization_expired" + Authorized: Final = "authorized" + Authorizing: Final = "authorizing" + Failed: Final = "failed" + GatewayRejected: Final = "gateway_rejected" + ProcessorDeclined: Final = "processor_declined" + Settled: Final = "settled" + SettlementConfirmed: Final = "settlement_confirmed" + SettlementDeclined: Final = "settlement_declined" + SettlementFailed: Final = "settlement_failed" + SettlementPending: Final = "settlement_pending" + Settling: Final = "settling" + SubmittedForSettlement: Final = "submitted_for_settlement" + Voided: Final = "voided" + class Type: - Credit: str - Sale: str + Credit: Final = "credit" + Sale: Final = "sale" + class IndustryType: - Lodging: str - TravelAndCruise: str - TravelAndFlight: str + Lodging: Final = "lodging" + TravelAndCruise: Final = "travel_cruise" + TravelAndFlight: Final = "travel_flight" + class AdditionalCharge: - Restaurant: str - GiftShop: str - MiniBar: str - Telephone: str - Laundry: str - Other: str + Restaurant: Final = "restaurant" + GiftShop: Final = "gift_shop" + MiniBar: Final = "mini_bar" + Telephone: Final = "telephone" + Laundry: Final = "laundry" + Other: Final = "other" + @staticmethod def adjust_authorization(transaction_id, amount): ... @staticmethod def clone_transaction(transaction_id, params): ... @staticmethod - def cancel_release(transaction_id): ... - @staticmethod - def credit(params: Any | None = ...): ... - @staticmethod - def find(transaction_id): ... - @staticmethod - def hold_in_escrow(transaction_id): ... + def credit(params=None): ... @staticmethod - def refund(transaction_id, amount_or_options: Any | None = ...): ... + def find(transaction_id: str) -> Transaction: ... @staticmethod - def sale(params: Any | None = ...): ... + def refund(transaction_id, amount_or_options=None): ... @staticmethod - def search(*query): ... + def sale(params=None): ... @staticmethod - def release_from_escrow(transaction_id): ... + def search(*query) -> ResourceCollection: ... @staticmethod - def submit_for_settlement(transaction_id, amount: Any | None = ..., params: Any | None = ...): ... + def submit_for_settlement(transaction_id, amount=None, params=None): ... @staticmethod - def update_details(transaction_id, params: Any | None = ...): ... + def update_details(transaction_id, params=None): ... @staticmethod - def void(transaction_id): ... + def void(transaction_id, params=None): ... @staticmethod def create(params): ... @staticmethod @@ -124,46 +130,63 @@ class Transaction(Resource): @staticmethod def submit_for_settlement_signature(): ... @staticmethod + def submit_for_partial_settlement_signature(): ... + @staticmethod + def package_tracking_signature(): ... + @staticmethod + def package_tracking(transaction_id, params=None): ... + @staticmethod def update_details_signature(): ... @staticmethod def refund_signature(): ... @staticmethod - def submit_for_partial_settlement(transaction_id, amount, params: Any | None = ...): ... - amount: Any - tax_amount: Any - discount_amount: Any - shipping_amount: Any - billing_details: Any - credit_card_details: Any - paypal_details: Any - paypal_here_details: Any - local_payment_details: Any - europe_bank_account_details: Any - us_bank_account: Any - apple_pay_details: Any - android_pay_card_details: Any - amex_express_checkout_card_details: Any - venmo_account_details: Any - visa_checkout_card_details: Any - masterpass_card_details: Any - samsung_pay_card_details: Any - sca_exemption_requested: Any - customer_details: Any - shipping_details: Any - add_ons: Any - discounts: Any - status_history: Any - subscription_details: Any - descriptor: Any - disbursement_details: Any - disputes: Any - authorization_adjustments: Any - payment_instrument_type: Any - risk_data: Any - three_d_secure_info: Any - facilitated_details: Any - facilitator_details: Any - network_transaction_id: Any + def submit_for_partial_settlement(transaction_id, amount, params=None): ... + amount: Decimal + tax_amount: Decimal | None + discount_amount: Decimal | None + shipping_amount: Decimal | None + surcharge_amount: Decimal | None + billing_details: Address + credit_card_details: CreditCard + packages: list[PackageDetails] + paypal_details: PayPalAccount + paypal_here_details: PayPalHere + local_payment_details: LocalPayment + sepa_direct_debit_account_details: SepaDirectDebitAccount + europe_bank_account_details: EuropeBankAccount + us_bank_account: UsBankAccount + apple_pay_details: ApplePayCard + android_pay_card_details: AndroidPayCard + amex_express_checkout_card_details: AmexExpressCheckoutCard + venmo_account_details: VenmoAccount + visa_checkout_card_details: VisaCheckoutCard + masterpass_card_details: MasterpassCard + samsung_pay_card_details: SamsungPayCard + meta_checkout_card_details: MetaCheckoutCard + meta_checkout_token_details: MetaCheckoutToken + sca_exemption_requested: Incomplete + customer_details: Customer + shipping_details: Address + add_ons: list[AddOn] + discounts: list[Discount] + status_history: list[StatusEvent] + subscription_details: SubscriptionDetails + descriptor: Descriptor + disbursement_details: DisbursementDetail + disputes: list[Dispute] + authorization_adjustments: list[AuthorizationAdjustment] + payment_instrument_type: Incomplete + risk_data: RiskData | None + three_d_secure_info: ThreeDSecureInfo | None + facilitated_details: FacilitatedDetails + facilitator_details: FacilitatorDetails + network_transaction_id: Incomplete + payment_facilitator: PaymentFacilitator + transfer: Transfer + partially_authorized: bool + mastercard_transaction_link_id: str | None + subscription_id: str + created_at: datetime def __init__(self, gateway, attributes) -> None: ... @property def vault_billing_address(self): ... @@ -172,6 +195,6 @@ class Transaction(Resource): @property def vault_customer(self): ... @property - def is_disbursed(self): ... + def is_disbursed(self) -> bool: ... @property def line_items(self): ... diff --git a/stubs/braintree/braintree/transaction_amounts.pyi b/stubs/braintree/braintree/transaction_amounts.pyi index f6556f48575f..6853fa9807ec 100644 --- a/stubs/braintree/braintree/transaction_amounts.pyi +++ b/stubs/braintree/braintree/transaction_amounts.pyi @@ -1,5 +1,8 @@ +from typing import Final + class TransactionAmounts: - Authorize: str - Decline: str - HardDecline: str - Fail: str + Authorize: Final = "1000.00" + PartiallyAuthorized: Final = "1004.00" + Decline: Final = "2000.00" + HardDecline: Final = "2015.00" + Fail: Final = "3000.00" diff --git a/stubs/braintree/braintree/transaction_details.pyi b/stubs/braintree/braintree/transaction_details.pyi index ceb5b4b19575..4e9909074d34 100644 --- a/stubs/braintree/braintree/transaction_details.pyi +++ b/stubs/braintree/braintree/transaction_details.pyi @@ -1,7 +1,7 @@ -from typing import Any +from decimal import Decimal -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class TransactionDetails(AttributeGetter): - amount: Any + amount: Decimal | None def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/transaction_gateway.pyi b/stubs/braintree/braintree/transaction_gateway.pyi index 07f69feed52a..6c86d2e17397 100644 --- a/stubs/braintree/braintree/transaction_gateway.pyi +++ b/stubs/braintree/braintree/transaction_gateway.pyi @@ -1,29 +1,25 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.exceptions.request_timeout_error import RequestTimeoutError as RequestTimeoutError -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.transaction import Transaction as Transaction +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult +from braintree.transaction import Transaction class TransactionGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def adjust_authorization(self, transaction_id, amount): ... - def clone_transaction(self, transaction_id, params): ... - def cancel_release(self, transaction_id): ... - def create(self, params): ... - def credit(self, params): ... - def find(self, transaction_id): ... - def hold_in_escrow(self, transaction_id): ... - def refund(self, transaction_id, amount_or_options: Any | None = ...): ... - def sale(self, params): ... - def search(self, *query): ... - def release_from_escrow(self, transaction_id): ... - def submit_for_settlement(self, transaction_id, amount: Any | None = ..., params: Any | None = ...): ... - def update_details(self, transaction_id, params: Any | None = ...): ... - def submit_for_partial_settlement(self, transaction_id, amount, params: Any | None = ...): ... - def void(self, transaction_id): ... + def adjust_authorization(self, transaction_id, amount) -> SuccessfulResult | ErrorResult | None: ... + def clone_transaction(self, transaction_id, params) -> SuccessfulResult | ErrorResult | None: ... + def cancel_release(self, transaction_id) -> SuccessfulResult | ErrorResult | None: ... + def create(self, params) -> SuccessfulResult | ErrorResult | None: ... + def credit(self, params) -> SuccessfulResult | ErrorResult | None: ... + def find(self, transaction_id: str) -> Transaction: ... + def refund(self, transaction_id, amount_or_options=None) -> SuccessfulResult | ErrorResult | None: ... + def sale(self, params) -> SuccessfulResult | ErrorResult | None: ... + def search(self, *query) -> ResourceCollection: ... + def submit_for_settlement(self, transaction_id, amount=None, params=None) -> SuccessfulResult | ErrorResult | None: ... + def update_details(self, transaction_id, params=None) -> SuccessfulResult | ErrorResult | None: ... + def submit_for_partial_settlement(self, transaction_id, amount, params=None) -> SuccessfulResult | ErrorResult | None: ... + def package_tracking(self, transaction_id, params=None) -> SuccessfulResult | ErrorResult | None: ... + def void(self, transaction_id, params=None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/transaction_line_item.pyi b/stubs/braintree/braintree/transaction_line_item.pyi index 11cd731f7884..7e9fe4ce9446 100644 --- a/stubs/braintree/braintree/transaction_line_item.pyi +++ b/stubs/braintree/braintree/transaction_line_item.pyi @@ -1,11 +1,12 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource +from typing import Final + +from braintree.attribute_getter import AttributeGetter class TransactionLineItem(AttributeGetter): class Kind: - Credit: str - Debit: str + Credit: Final = "credit" + Debit: Final = "debit" + def __init__(self, attributes) -> None: ... @staticmethod def find_all(transaction_id): ... diff --git a/stubs/braintree/braintree/transaction_line_item_gateway.pyi b/stubs/braintree/braintree/transaction_line_item_gateway.pyi index 8eca1b10cc65..dcf1e5b87505 100644 --- a/stubs/braintree/braintree/transaction_line_item_gateway.pyi +++ b/stubs/braintree/braintree/transaction_line_item_gateway.pyi @@ -1,14 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.exceptions.request_timeout_error import RequestTimeoutError as RequestTimeoutError -from braintree.resource import Resource as Resource -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.transaction_line_item import TransactionLineItem as TransactionLineItem +from braintree.transaction_line_item import TransactionLineItem class TransactionLineItemGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def find_all(self, transaction_id): ... + def find_all(self, transaction_id: str) -> list[TransactionLineItem]: ... diff --git a/stubs/braintree/braintree/transaction_review.pyi b/stubs/braintree/braintree/transaction_review.pyi new file mode 100644 index 000000000000..bfd6545725bc --- /dev/null +++ b/stubs/braintree/braintree/transaction_review.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class TransactionReview(Resource): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/transaction_search.pyi b/stubs/braintree/braintree/transaction_search.pyi index 439cc9f7f29d..647929eaea36 100644 --- a/stubs/braintree/braintree/transaction_search.pyi +++ b/stubs/braintree/braintree/transaction_search.pyi @@ -1,73 +1,74 @@ -from typing import Any - -from braintree.credit_card import CreditCard as CreditCard -from braintree.search import Search as Search -from braintree.transaction import Transaction as Transaction -from braintree.util import Constants as Constants +from braintree.search import Search class TransactionSearch: - billing_first_name: Any - billing_company: Any - billing_country_name: Any - billing_extended_address: Any - billing_last_name: Any - billing_locality: Any - billing_postal_code: Any - billing_region: Any - billing_street_address: Any - credit_card_cardholder_name: Any - currency: Any - customer_company: Any - customer_email: Any - customer_fax: Any - customer_first_name: Any - customer_id: Any - customer_last_name: Any - customer_phone: Any - customer_website: Any - id: Any - order_id: Any - payment_method_token: Any - processor_authorization_code: Any - europe_bank_account_iban: Any - settlement_batch_id: Any - shipping_company: Any - shipping_country_name: Any - shipping_extended_address: Any - shipping_first_name: Any - shipping_last_name: Any - shipping_locality: Any - shipping_postal_code: Any - shipping_region: Any - shipping_street_address: Any - paypal_payer_email: Any - paypal_payment_id: Any - paypal_authorization_id: Any - credit_card_unique_identifier: Any - store_id: Any - credit_card_expiration_date: Any - credit_card_number: Any - user: Any - ids: Any - merchant_account_id: Any - payment_instrument_type: Any - store_ids: Any - created_using: Any - credit_card_card_type: Any - credit_card_customer_location: Any - source: Any - status: Any - type: Any - refund: Any - amount: Any - authorization_expired_at: Any - authorized_at: Any - created_at: Any - disbursement_date: Any - dispute_date: Any - failed_at: Any - gateway_rejected_at: Any - processor_declined_at: Any - settled_at: Any - submitted_for_settlement_at: Any - voided_at: Any + ach_type: Search.MultipleValueNodeBuilder + acquirer_reference_number: Search.TextNodeBuilder + billing_company: Search.TextNodeBuilder + billing_country_name: Search.TextNodeBuilder + billing_extended_address: Search.TextNodeBuilder + billing_first_name: Search.TextNodeBuilder + billing_last_name: Search.TextNodeBuilder + billing_locality: Search.TextNodeBuilder + billing_postal_code: Search.TextNodeBuilder + billing_region: Search.TextNodeBuilder + billing_street_address: Search.TextNodeBuilder + credit_card_cardholder_name: Search.TextNodeBuilder + currency: Search.TextNodeBuilder + customer_company: Search.TextNodeBuilder + customer_email: Search.TextNodeBuilder + customer_fax: Search.TextNodeBuilder + customer_first_name: Search.TextNodeBuilder + customer_id: Search.TextNodeBuilder + customer_last_name: Search.TextNodeBuilder + customer_phone: Search.TextNodeBuilder + customer_website: Search.TextNodeBuilder + id: Search.TextNodeBuilder + order_id: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder + processor_authorization_code: Search.TextNodeBuilder + europe_bank_account_iban: Search.TextNodeBuilder + settlement_batch_id: Search.TextNodeBuilder + shipping_company: Search.TextNodeBuilder + shipping_country_name: Search.TextNodeBuilder + shipping_extended_address: Search.TextNodeBuilder + shipping_first_name: Search.TextNodeBuilder + shipping_last_name: Search.TextNodeBuilder + shipping_locality: Search.TextNodeBuilder + shipping_postal_code: Search.TextNodeBuilder + shipping_region: Search.TextNodeBuilder + shipping_street_address: Search.TextNodeBuilder + paypal_payer_email: Search.TextNodeBuilder + paypal_payment_id: Search.TextNodeBuilder + paypal_authorization_id: Search.TextNodeBuilder + sepa_debit_paypal_v2_order_id: Search.TextNodeBuilder + credit_card_unique_identifier: Search.TextNodeBuilder + store_id: Search.TextNodeBuilder + credit_card_expiration_date: Search.EqualityNodeBuilder + credit_card_number: Search.PartialMatchNodeBuilder + user: Search.MultipleValueNodeBuilder + ids: Search.MultipleValueNodeBuilder + merchant_account_id: Search.MultipleValueNodeBuilder + payment_instrument_type: Search.MultipleValueNodeBuilder + store_ids: Search.MultipleValueNodeBuilder + created_using: Search.MultipleValueNodeBuilder + credit_card_card_type: Search.MultipleValueNodeBuilder + credit_card_customer_location: Search.MultipleValueNodeBuilder + debit_network: Search.MultipleValueNodeBuilder + source: Search.MultipleValueNodeBuilder + status: Search.MultipleValueNodeBuilder + type: Search.MultipleValueNodeBuilder + refund: Search.KeyValueNodeBuilder + amount: Search.RangeNodeBuilder + authorization_expired_at: Search.RangeNodeBuilder + authorized_at: Search.RangeNodeBuilder + created_at: Search.RangeNodeBuilder + disbursement_date: Search.RangeNodeBuilder + dispute_date: Search.RangeNodeBuilder + failed_at: Search.RangeNodeBuilder + gateway_rejected_at: Search.RangeNodeBuilder + processor_declined_at: Search.RangeNodeBuilder + settled_at: Search.RangeNodeBuilder + submitted_for_settlement_at: Search.RangeNodeBuilder + voided_at: Search.RangeNodeBuilder + ach_return_responses_created_at: Search.RangeNodeBuilder + reason_code: Search.MultipleValueNodeBuilder diff --git a/stubs/braintree/braintree/transaction_us_bank_account_request.pyi b/stubs/braintree/braintree/transaction_us_bank_account_request.pyi new file mode 100644 index 000000000000..4f9e2991c728 --- /dev/null +++ b/stubs/braintree/braintree/transaction_us_bank_account_request.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from datetime import datetime +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _ParamsDict(TypedDict, total=False): + ach_mandate_text: str + ach_mandate_accepted_at: str + +class TransactionUsBankAccountRequest: + parent: Incomplete + def __init__(self, parent) -> None: ... + def ach_mandate_text(self, ach_mandate_text: str) -> Self: ... + def ach_mandate_accepted_at(self, ach_mandate_accepted_at: str | datetime) -> Self: ... + def done(self): ... + def to_param_dict(self) -> _ParamsDict: ... diff --git a/stubs/braintree/braintree/transfer.pyi b/stubs/braintree/braintree/transfer.pyi new file mode 100644 index 000000000000..ac730e9345dd --- /dev/null +++ b/stubs/braintree/braintree/transfer.pyi @@ -0,0 +1,8 @@ +from braintree.attribute_getter import AttributeGetter +from braintree.receiver import Receiver +from braintree.sender import Sender + +class Transfer(AttributeGetter): + sender: Sender + receiver: Receiver + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/unknown_payment_method.pyi b/stubs/braintree/braintree/unknown_payment_method.pyi index b683e6ee0186..9551e3225685 100644 --- a/stubs/braintree/braintree/unknown_payment_method.pyi +++ b/stubs/braintree/braintree/unknown_payment_method.pyi @@ -1,4 +1,4 @@ -from braintree.resource import Resource as Resource +from braintree.resource import Resource class UnknownPaymentMethod(Resource): - def image_url(self): ... + def image_url(self) -> str: ... diff --git a/stubs/braintree/braintree/us_bank_account.pyi b/stubs/braintree/braintree/us_bank_account.pyi index 31d005cd00a9..538a965c739d 100644 --- a/stubs/braintree/braintree/us_bank_account.pyi +++ b/stubs/braintree/braintree/us_bank_account.pyi @@ -1,17 +1,16 @@ -from typing import Any - -from braintree.ach_mandate import AchMandate as AchMandate -from braintree.configuration import Configuration as Configuration -from braintree.resource import Resource as Resource -from braintree.us_bank_account_verification import UsBankAccountVerification as UsBankAccountVerification +from braintree.ach_mandate import AchMandate +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account_verification import UsBankAccountVerification class UsBankAccount(Resource): @staticmethod - def find(token): ... + def find(token: str) -> UsBankAccount | None: ... @staticmethod - def sale(token, transactionRequest): ... + def sale(token: str, transactionRequest) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def signature(): ... - ach_mandate: Any - verifications: Any + def signature() -> list[str]: ... + ach_mandate: AchMandate | None + verifications: list[UsBankAccountVerification] def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/us_bank_account_gateway.pyi b/stubs/braintree/braintree/us_bank_account_gateway.pyi index 665b5714664b..8e3643b7f868 100644 --- a/stubs/braintree/braintree/us_bank_account_gateway.pyi +++ b/stubs/braintree/braintree/us_bank_account_gateway.pyi @@ -1,10 +1,9 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.us_bank_account import UsBankAccount as UsBankAccount +from braintree.us_bank_account import UsBankAccount class UsBankAccountGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def find(self, us_bank_account_token): ... + def find(self, us_bank_account_token: str) -> UsBankAccount | None: ... diff --git a/stubs/braintree/braintree/us_bank_account_verification.pyi b/stubs/braintree/braintree/us_bank_account_verification.pyi index cf4bd42cbb8b..92e90486795c 100644 --- a/stubs/braintree/braintree/us_bank_account_verification.pyi +++ b/stubs/braintree/braintree/us_bank_account_verification.pyi @@ -1,27 +1,36 @@ -from typing import Any +from typing import Final -from braintree.attribute_getter import AttributeGetter as AttributeGetter -from braintree.configuration import Configuration as Configuration +from braintree.attribute_getter import AttributeGetter +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account import UsBankAccount class UsBankAccountVerification(AttributeGetter): class Status: - Failed: str - GatewayRejected: str - ProcessorDeclined: str - Unrecognized: str - Verified: str - Pending: str + Failed: Final = "failed" + GatewayRejected: Final = "gateway_rejected" + ProcessorDeclined: Final = "processor_declined" + Unrecognized: Final = "unrecognized" + Verified: Final = "verified" + Pending: Final = "pending" + class VerificationMethod: - NetworkCheck: str - IndependentCheck: str - TokenizedCheck: str - MicroTransfers: str - us_bank_account: Any + NetworkCheck: Final = "network_check" + IndependentCheck: Final = "independent_check" + InstantVerificationAccountValidation: Final = "instant_verification_account_validation" + TokenizedCheck: Final = "tokenized_check" + MicroTransfers: Final = "micro_transfers" + + class VerificationAddOns: + CustomerVerification: Final = "customer_verification" + + us_bank_account: UsBankAccount | None def __init__(self, gateway, attributes) -> None: ... @staticmethod - def confirm_micro_transfer_amounts(verification_id, amounts): ... + def confirm_micro_transfer_amounts(verification_id: str, amounts) -> SuccessfulResult | ErrorResult | None: ... @staticmethod - def find(verification_id): ... + def find(verification_id: str) -> UsBankAccountVerification: ... @staticmethod - def search(*query): ... - def __eq__(self, other): ... + def search(*query) -> ResourceCollection: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi b/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi index 1f420f984fef..5522b67d2f3a 100644 --- a/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi +++ b/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi @@ -1,16 +1,14 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.error_result import ErrorResult as ErrorResult -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.resource_collection import ResourceCollection as ResourceCollection -from braintree.successful_result import SuccessfulResult as SuccessfulResult -from braintree.us_bank_account_verification import UsBankAccountVerification as UsBankAccountVerification -from braintree.us_bank_account_verification_search import UsBankAccountVerificationSearch as UsBankAccountVerificationSearch +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account_verification import UsBankAccountVerification class UsBankAccountVerificationGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def confirm_micro_transfer_amounts(self, verification_id, amounts): ... - def find(self, verification_id): ... - def search(self, *query): ... + def confirm_micro_transfer_amounts(self, verification_id: str, amounts) -> SuccessfulResult | ErrorResult | None: ... + def find(self, verification_id: str) -> UsBankAccountVerification: ... + def search(self, *query) -> ResourceCollection: ... diff --git a/stubs/braintree/braintree/us_bank_account_verification_search.pyi b/stubs/braintree/braintree/us_bank_account_verification_search.pyi index 3b937177d22c..2f8e58831d6c 100644 --- a/stubs/braintree/braintree/us_bank_account_verification_search.pyi +++ b/stubs/braintree/braintree/us_bank_account_verification_search.pyi @@ -1,20 +1,15 @@ -from typing import Any - -from braintree.search import Search as Search -from braintree.us_bank_account import UsBankAccount as UsBankAccount -from braintree.us_bank_account_verification import UsBankAccountVerification as UsBankAccountVerification -from braintree.util import Constants as Constants +from braintree.search import Search class UsBankAccountVerificationSearch: - account_holder_name: Any - customer_email: Any - customer_id: Any - id: Any - payment_method_token: Any - routing_number: Any - ids: Any - status: Any - verification_method: Any - created_at: Any - account_type: Any - account_number: Any + account_holder_name: Search.TextNodeBuilder + customer_email: Search.TextNodeBuilder + customer_id: Search.TextNodeBuilder + id: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder + routing_number: Search.TextNodeBuilder + ids: Search.MultipleValueNodeBuilder + status: Search.MultipleValueNodeBuilder + verification_method: Search.MultipleValueNodeBuilder + created_at: Search.RangeNodeBuilder + account_type: Search.EqualityNodeBuilder + account_number: Search.EndsWithNodeBuilder diff --git a/stubs/braintree/braintree/util/__init__.pyi b/stubs/braintree/braintree/util/__init__.pyi index 974d71418ec0..62115e01e518 100644 --- a/stubs/braintree/braintree/util/__init__.pyi +++ b/stubs/braintree/braintree/util/__init__.pyi @@ -1,5 +1,6 @@ from braintree.util.constants import Constants as Constants from braintree.util.crypto import Crypto as Crypto +from braintree.util.experimental import Experimental as Experimental from braintree.util.generator import Generator as Generator from braintree.util.graphql_client import GraphQLClient as GraphQLClient from braintree.util.http import Http as Http diff --git a/stubs/braintree/braintree/util/constants.pyi b/stubs/braintree/braintree/util/constants.pyi index f46d366a20d1..17cdc02f6ba8 100644 --- a/stubs/braintree/braintree/util/constants.pyi +++ b/stubs/braintree/braintree/util/constants.pyi @@ -1,3 +1,7 @@ +from _typeshed import Incomplete +from typing import Any + class Constants: @staticmethod - def get_all_constant_values_from_class(klass): ... + def get_all_constant_values_from_class(klass: object) -> list[Any]: ... # Any taken from klass.__dict__ + def get_all_enum_values(enum_class) -> list[Incomplete]: ... diff --git a/stubs/braintree/braintree/util/crypto.pyi b/stubs/braintree/braintree/util/crypto.pyi index 6ea4a83dc232..6d0666648f62 100644 --- a/stubs/braintree/braintree/util/crypto.pyi +++ b/stubs/braintree/braintree/util/crypto.pyi @@ -1,9 +1,24 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Literal, overload + text_type = str class Crypto: @staticmethod - def sha1_hmac_hash(secret_key, content): ... + def sha1_hmac_hash(secret_key: str | ReadableBuffer, content: str | ReadableBuffer | None) -> str: ... + @staticmethod + def sha256_hmac_hash(secret_key: str | ReadableBuffer, content: str | ReadableBuffer | None) -> str: ... + + @overload + @staticmethod + def secure_compare(left: None, right: Iterable[str | bytes | bytearray]) -> Literal[False]: ... + @overload + @staticmethod + def secure_compare(left: Iterable[str | bytes | bytearray], right: None) -> Literal[False]: ... + @overload @staticmethod - def sha256_hmac_hash(secret_key, content): ... + def secure_compare(left: None, right: None) -> Literal[False]: ... + @overload @staticmethod - def secure_compare(left, right): ... + def secure_compare(left: Iterable[str | bytes | bytearray], right: Iterable[str | bytes | bytearray]) -> bool: ... diff --git a/stubs/braintree/braintree/util/datetime_parser.pyi b/stubs/braintree/braintree/util/datetime_parser.pyi index eb12ffa4057c..c2341864097a 100644 --- a/stubs/braintree/braintree/util/datetime_parser.pyi +++ b/stubs/braintree/braintree/util/datetime_parser.pyi @@ -1 +1,3 @@ -def parse_datetime(timestamp): ... +from datetime import datetime + +def parse_datetime(timestamp: str) -> datetime: ... diff --git a/stubs/braintree/braintree/util/experimental.pyi b/stubs/braintree/braintree/util/experimental.pyi new file mode 100644 index 000000000000..4b1c1b906de6 --- /dev/null +++ b/stubs/braintree/braintree/util/experimental.pyi @@ -0,0 +1,5 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +def Experimental(cls: _T) -> _T: ... diff --git a/stubs/braintree/braintree/util/generator.pyi b/stubs/braintree/braintree/util/generator.pyi index 5768acfcab7a..03e10a43fede 100644 --- a/stubs/braintree/braintree/util/generator.pyi +++ b/stubs/braintree/braintree/util/generator.pyi @@ -1,10 +1,27 @@ -from typing import Any +import datetime +import decimal +from collections.abc import Iterable, Mapping +from typing import TypeAlias integer_types = int text_type = str binary_type = bytes +_XMLValue: TypeAlias = ( + str + | bytes + | int + | bool + | decimal.Decimal + | Iterable[_XMLValue] + | Mapping[str, _XMLValue] + | datetime.datetime + | datetime.date + | None +) +_XML: TypeAlias = Mapping[str, _XMLValue] + class Generator: - dict: Any - def __init__(self, dict) -> None: ... - def generate(self): ... + dict: _XML + def __init__(self, dict: _XML) -> None: ... + def generate(self) -> str: ... diff --git a/stubs/braintree/braintree/util/graphql_client.pyi b/stubs/braintree/braintree/util/graphql_client.pyi index 16ac5e47dab9..60792398addd 100644 --- a/stubs/braintree/braintree/util/graphql_client.pyi +++ b/stubs/braintree/braintree/util/graphql_client.pyi @@ -1,18 +1,38 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import TypedDict, type_check_only -from braintree.exceptions.authentication_error import AuthenticationError as AuthenticationError -from braintree.exceptions.authorization_error import AuthorizationError as AuthorizationError -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.exceptions.server_error import ServerError as ServerError -from braintree.exceptions.service_unavailable_error import ServiceUnavailableError as ServiceUnavailableError -from braintree.exceptions.too_many_requests_error import TooManyRequestsError as TooManyRequestsError -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError -from braintree.exceptions.upgrade_required_error import UpgradeRequiredError as UpgradeRequiredError -from braintree.util.http import Http as Http +from braintree.configuration import Configuration +from braintree.environment import Environment +from braintree.util.http import Http + +@type_check_only +class _Extension(TypedDict): + errorClass: Incomplete + legacyCode: int | None + +@type_check_only +class _Error(TypedDict): + attribute: str | None + code: int | None + message: str | None + extensions: _Extension | None + +@type_check_only +class _ValidationErrors(TypedDict): + errors: Iterable[_Error] + +@type_check_only +class _Response(TypedDict): + errors: Iterable[_Error] | None class GraphQLClient(Http): @staticmethod - def raise_exception_for_graphql_error(response) -> None: ... - graphql_headers: Any - def __init__(self, config: Any | None = ..., environment: Any | None = ...) -> None: ... - def query(self, definition, variables: Any | None = ..., operation_name: Any | None = ...): ... + def raise_exception_for_graphql_error(response: _Response) -> None: ... + graphql_headers: dict[str, str] + def __init__(self, config: Configuration | None = None, environment: Environment | None = None) -> None: ... + def query(self, definition, variables=None, operation_name=None): ... + @staticmethod + def get_validation_errors(response) -> _ValidationErrors | None: ... + @staticmethod + def get_validation_error_code(error: _Error) -> int | None: ... diff --git a/stubs/braintree/braintree/util/http.pyi b/stubs/braintree/braintree/util/http.pyi index f5e7a1ad67e3..e2bda12df16c 100644 --- a/stubs/braintree/braintree/util/http.pyi +++ b/stubs/braintree/braintree/util/http.pyi @@ -1,42 +1,29 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Final -from braintree import version as version -from braintree.environment import Environment as Environment -from braintree.exceptions.authentication_error import AuthenticationError as AuthenticationError -from braintree.exceptions.authorization_error import AuthorizationError as AuthorizationError -from braintree.exceptions.gateway_timeout_error import GatewayTimeoutError as GatewayTimeoutError -from braintree.exceptions.http.connection_error import ConnectionError as ConnectionError -from braintree.exceptions.http.invalid_response_error import InvalidResponseError as InvalidResponseError -from braintree.exceptions.http.timeout_error import ( - ConnectTimeoutError as ConnectTimeoutError, - ReadTimeoutError as ReadTimeoutError, - TimeoutError as TimeoutError, -) -from braintree.exceptions.not_found_error import NotFoundError as NotFoundError -from braintree.exceptions.request_timeout_error import RequestTimeoutError as RequestTimeoutError -from braintree.exceptions.server_error import ServerError as ServerError -from braintree.exceptions.service_unavailable_error import ServiceUnavailableError as ServiceUnavailableError -from braintree.exceptions.too_many_requests_error import TooManyRequestsError as TooManyRequestsError -from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError -from braintree.exceptions.upgrade_required_error import UpgradeRequiredError as UpgradeRequiredError -from braintree.util.xml_util import XmlUtil as XmlUtil +from braintree.configuration import Configuration +from braintree.environment import Environment class Http: class ContentType: - Xml: str - Multipart: str - Json: str + Xml: Final = "application/xml" + Multipart: Final = "multipart/form-data" + Json: Final = "application/json" + @staticmethod - def is_error_status(status): ... + def is_error_status(status: int) -> bool: ... @staticmethod - def raise_exception_from_status(status, message: Any | None = ...) -> None: ... - config: Any - environment: Any - def __init__(self, config, environment: Any | None = ...) -> None: ... - def post(self, path, params: Any | None = ...): ... - def delete(self, path): ... - def get(self, path): ... - def put(self, path, params: Any | None = ...): ... - def post_multipart(self, path, files, params: Any | None = ...): ... - def http_do(self, http_verb, path, headers, request_body): ... - def handle_exception(self, exception) -> None: ... + def raise_exception_from_status(status: int, message: str | None = None) -> None: ... + config: Configuration + environment: Environment + def __init__(self, config: Configuration, environment: Environment | None = None) -> None: ... + def close(self) -> None: ... + def post(self, path: str, params: dict[str, Incomplete] | None = None): ... + def delete(self, path: str): ... + def get(self, path: str): ... + def put(self, path: str, params: dict[str, Incomplete] | None = None): ... + def post_multipart(self, path: str, files, params: dict[str, Incomplete] | None = None): ... + def http_do( + self, http_verb: str, path: str, headers: dict[str, Incomplete], request_body: str | tuple[str, Incomplete] | None + ) -> list[int | str]: ... + def handle_exception(self, exception: IOError) -> None: ... diff --git a/stubs/braintree/braintree/util/parser.pyi b/stubs/braintree/braintree/util/parser.pyi index 04f71d120645..3798ec84dd65 100644 --- a/stubs/braintree/braintree/util/parser.pyi +++ b/stubs/braintree/braintree/util/parser.pyi @@ -1,10 +1,10 @@ -from typing import Any +from xml.dom.minidom import Document -from braintree.util.datetime_parser import parse_datetime as parse_datetime +from .generator import _XML binary_type = bytes class Parser: - doc: Any - def __init__(self, xml) -> None: ... - def parse(self): ... + doc: Document + def __init__(self, xml: str | bytes) -> None: ... + def parse(self) -> _XML: ... diff --git a/stubs/braintree/braintree/util/validation.pyi b/stubs/braintree/braintree/util/validation.pyi new file mode 100644 index 000000000000..1fe26fac43d4 --- /dev/null +++ b/stubs/braintree/braintree/util/validation.pyi @@ -0,0 +1,6 @@ +import re +from typing import Final + +VALID_PATH_SEGMENT_REGEX: Final[re.Pattern[str]] + +def is_invalid_path_segment(value: object) -> bool: ... diff --git a/stubs/braintree/braintree/util/xml_util.pyi b/stubs/braintree/braintree/util/xml_util.pyi index d288665ac9fd..eb340ea8c570 100644 --- a/stubs/braintree/braintree/util/xml_util.pyi +++ b/stubs/braintree/braintree/util/xml_util.pyi @@ -1,8 +1,7 @@ -from braintree.util.generator import Generator as Generator -from braintree.util.parser import Parser as Parser +from .generator import _XML class XmlUtil: @staticmethod - def xml_from_dict(dict): ... + def xml_from_dict(dict: _XML) -> str: ... @staticmethod - def dict_from_xml(xml): ... + def dict_from_xml(xml: str | bytes) -> _XML: ... diff --git a/stubs/braintree/braintree/validation_error.pyi b/stubs/braintree/braintree/validation_error.pyi index 04254c7212a6..19b726ae1c8f 100644 --- a/stubs/braintree/braintree/validation_error.pyi +++ b/stubs/braintree/braintree/validation_error.pyi @@ -1,3 +1,3 @@ -from braintree.attribute_getter import AttributeGetter as AttributeGetter +from braintree.attribute_getter import AttributeGetter class ValidationError(AttributeGetter): ... diff --git a/stubs/braintree/braintree/validation_error_collection.pyi b/stubs/braintree/braintree/validation_error_collection.pyi index 546dfcf7cd98..d0d677c5c3f8 100644 --- a/stubs/braintree/braintree/validation_error_collection.pyi +++ b/stubs/braintree/braintree/validation_error_collection.pyi @@ -1,20 +1,21 @@ -from typing import Any +from _typeshed import Incomplete +from typing_extensions import Self -from braintree.validation_error import ValidationError as ValidationError +from braintree.validation_error import ValidationError class ValidationErrorCollection: - data: Any - def __init__(self, data: Any | None = ...) -> None: ... + data: dict[str, Incomplete] + def __init__(self, data: dict[str, Incomplete] | None = None) -> None: ... @property - def deep_errors(self): ... - def for_index(self, index): ... - def for_object(self, nested_key): ... - def on(self, attribute): ... + def deep_errors(self) -> list[ValidationError]: ... + def for_index(self, index: int | str) -> Self: ... + def for_object(self, nested_key: str) -> Self: ... + def on(self, attribute: str) -> list[ValidationError]: ... @property - def deep_size(self): ... + def deep_size(self) -> int: ... @property - def errors(self): ... + def errors(self) -> list[ValidationError]: ... @property - def size(self): ... - def __getitem__(self, index): ... - def __len__(self): ... + def size(self) -> int: ... + def __getitem__(self, index: int) -> ValidationError: ... + def __len__(self) -> int: ... diff --git a/stubs/braintree/braintree/venmo_account.pyi b/stubs/braintree/braintree/venmo_account.pyi index 8d4fe93d9304..71e2a37dc612 100644 --- a/stubs/braintree/braintree/venmo_account.pyi +++ b/stubs/braintree/braintree/venmo_account.pyi @@ -1,7 +1,6 @@ -from typing import Any - -from braintree.resource import Resource as Resource +from braintree.resource import Resource +from braintree.subscription import Subscription class VenmoAccount(Resource): - subscriptions: Any + subscriptions: list[Subscription] def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/venmo_profile_data.pyi b/stubs/braintree/braintree/venmo_profile_data.pyi new file mode 100644 index 000000000000..fd6dd4d8fca0 --- /dev/null +++ b/stubs/braintree/braintree/venmo_profile_data.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class VenmoProfileData(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/version.pyi b/stubs/braintree/braintree/version.pyi index 935fb36a8bf5..5fac495d89ce 100644 --- a/stubs/braintree/braintree/version.pyi +++ b/stubs/braintree/braintree/version.pyi @@ -1 +1,3 @@ -Version: str +from typing import Final + +Version: Final[str] diff --git a/stubs/braintree/braintree/visa_checkout_card.pyi b/stubs/braintree/braintree/visa_checkout_card.pyi index 6e8f37d5cd19..9909b514e95e 100644 --- a/stubs/braintree/braintree/visa_checkout_card.pyi +++ b/stubs/braintree/braintree/visa_checkout_card.pyi @@ -1,15 +1,17 @@ -from typing import Any +from typing_extensions import deprecated -from braintree.address import Address as Address -from braintree.credit_card_verification import CreditCardVerification as CreditCardVerification -from braintree.resource import Resource as Resource +from braintree.address import Address +from braintree.credit_card_verification import CreditCardVerification +from braintree.resource import Resource +from braintree.subscription import Subscription +@deprecated("Visa Checkout is no longer supported for creating new transactions.") class VisaCheckoutCard(Resource): - billing_address: Any - subscriptions: Any - verification: Any + billing_address: Address | None + subscriptions: list[Subscription] + verification: CreditCardVerification def __init__(self, gateway, attributes): ... @property - def expiration_date(self): ... + def expiration_date(self) -> str: ... @property - def masked_number(self): ... + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/webhook_notification.pyi b/stubs/braintree/braintree/webhook_notification.pyi index 34de0f7710aa..06e38fef592a 100644 --- a/stubs/braintree/braintree/webhook_notification.pyi +++ b/stubs/braintree/braintree/webhook_notification.pyi @@ -1,83 +1,94 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Final -from braintree.account_updater_daily_report import AccountUpdaterDailyReport as AccountUpdaterDailyReport -from braintree.configuration import Configuration as Configuration -from braintree.connected_merchant_paypal_status_changed import ( - ConnectedMerchantPayPalStatusChanged as ConnectedMerchantPayPalStatusChanged, -) -from braintree.connected_merchant_status_transitioned import ( - ConnectedMerchantStatusTransitioned as ConnectedMerchantStatusTransitioned, -) -from braintree.disbursement import Disbursement as Disbursement -from braintree.dispute import Dispute as Dispute -from braintree.error_result import ErrorResult as ErrorResult -from braintree.granted_payment_instrument_update import GrantedPaymentInstrumentUpdate as GrantedPaymentInstrumentUpdate -from braintree.local_payment_completed import LocalPaymentCompleted as LocalPaymentCompleted -from braintree.local_payment_reversed import LocalPaymentReversed as LocalPaymentReversed -from braintree.merchant_account import MerchantAccount as MerchantAccount -from braintree.oauth_access_revocation import OAuthAccessRevocation as OAuthAccessRevocation -from braintree.partner_merchant import PartnerMerchant as PartnerMerchant -from braintree.resource import Resource as Resource -from braintree.revoked_payment_method_metadata import RevokedPaymentMethodMetadata as RevokedPaymentMethodMetadata -from braintree.subscription import Subscription as Subscription -from braintree.transaction import Transaction as Transaction -from braintree.validation_error_collection import ValidationErrorCollection as ValidationErrorCollection +from braintree.account_updater_daily_report import AccountUpdaterDailyReport +from braintree.connected_merchant_paypal_status_changed import ConnectedMerchantPayPalStatusChanged +from braintree.connected_merchant_status_transitioned import ConnectedMerchantStatusTransitioned +from braintree.disbursement import Disbursement +from braintree.dispute import Dispute +from braintree.granted_payment_instrument_update import GrantedPaymentInstrumentUpdate +from braintree.local_payment_completed import LocalPaymentCompleted +from braintree.local_payment_expired import LocalPaymentExpired +from braintree.local_payment_funded import LocalPaymentFunded +from braintree.local_payment_reversed import LocalPaymentReversed +from braintree.merchant_account import MerchantAccount +from braintree.oauth_access_revocation import OAuthAccessRevocation +from braintree.partner_merchant import PartnerMerchant +from braintree.payment_method_customer_data_updated_metadata import PaymentMethodCustomerDataUpdatedMetadata +from braintree.resource import Resource +from braintree.revoked_payment_method_metadata import RevokedPaymentMethodMetadata +from braintree.subscription import Subscription +from braintree.transaction import Transaction +from braintree.transaction_review import TransactionReview +from braintree.validation_error_collection import ValidationErrorCollection class WebhookNotification(Resource): class Kind: - AccountUpdaterDailyReport: str - Check: str - ConnectedMerchantPayPalStatusChanged: str - ConnectedMerchantStatusTransitioned: str - Disbursement: str - DisbursementException: str - DisputeAccepted: str - DisputeDisputed: str - DisputeExpired: str - DisputeLost: str - DisputeOpened: str - DisputeWon: str - GrantedPaymentMethodRevoked: str - GrantorUpdatedGrantedPaymentMethod: str - LocalPaymentCompleted: str - LocalPaymentReversed: str - OAuthAccessRevoked: str - PartnerMerchantConnected: str - PartnerMerchantDeclined: str - PartnerMerchantDisconnected: str - PaymentMethodRevokedByCustomer: str - RecipientUpdatedGrantedPaymentMethod: str - SubMerchantAccountApproved: str - SubMerchantAccountDeclined: str - SubscriptionCanceled: str - SubscriptionChargedSuccessfully: str - SubscriptionChargedUnsuccessfully: str - SubscriptionExpired: str - SubscriptionTrialEnded: str - SubscriptionWentActive: str - SubscriptionWentPastDue: str - TransactionDisbursed: str - TransactionSettled: str - TransactionSettlementDeclined: str + AccountUpdaterDailyReport: Final = "account_updater_daily_report" + Check: Final = "check" + ConnectedMerchantPayPalStatusChanged: Final = "connected_merchant_paypal_status_changed" + ConnectedMerchantStatusTransitioned: Final = "connected_merchant_status_transitioned" + Disbursement: Final = "disbursement" + DisbursementException: Final = "disbursement_exception" + DisputeAccepted: Final = "dispute_accepted" + DisputeAutoAccepted: Final = "dispute_auto_accepted" + DisputeDisputed: Final = "dispute_disputed" + DisputeExpired: Final = "dispute_expired" + DisputeLost: Final = "dispute_lost" + DisputeOpened: Final = "dispute_opened" + DisputeUnderReview: Final = "dispute_under_review" + DisputeWon: Final = "dispute_won" + GrantedPaymentMethodRevoked: Final = "granted_payment_method_revoked" + GrantorUpdatedGrantedPaymentMethod: Final = "grantor_updated_granted_payment_method" + LocalPaymentCompleted: Final = "local_payment_completed" + LocalPaymentExpired: Final = "local_payment_expired" + LocalPaymentFunded: Final = "local_payment_funded" + LocalPaymentReversed: Final = "local_payment_reversed" + OAuthAccessRevoked: Final = "oauth_access_revoked" + PartnerMerchantConnected: Final = "partner_merchant_connected" + PartnerMerchantDeclined: Final = "partner_merchant_declined" + PartnerMerchantDisconnected: Final = "partner_merchant_disconnected" + PaymentMethodCustomerDataUpdated: Final = "payment_method_customer_data_updated" + PaymentMethodRevokedByCustomer: Final = "payment_method_revoked_by_customer" + RecipientUpdatedGrantedPaymentMethod: Final = "recipient_updated_granted_payment_method" + RefundFailed: Final = "refund_failed" + SubscriptionBillingSkipped: Final = "subscription_billing_skipped" + SubscriptionCanceled: Final = "subscription_canceled" + SubscriptionChargedSuccessfully: Final = "subscription_charged_successfully" + SubscriptionChargedUnsuccessfully: Final = "subscription_charged_unsuccessfully" + SubscriptionExpired: Final = "subscription_expired" + SubscriptionTrialEnded: Final = "subscription_trial_ended" + SubscriptionWentActive: Final = "subscription_went_active" + SubscriptionWentPastDue: Final = "subscription_went_past_due" + TransactionDisbursed: Final = "transaction_disbursed" + TransactionRetried: Final = "transaction_retried" + TransactionReviewed: Final = "transaction_reviewed" + TransactionSettled: Final = "transaction_settled" + TransactionSettlementDeclined: Final = "transaction_settlement_declined" + @staticmethod - def parse(signature, payload): ... + def parse(signature: str, payload: str) -> WebhookNotification: ... @staticmethod - def verify(challenge): ... - source_merchant_id: Any - subscription: Any - merchant_account: Any - transaction: Any - connected_merchant_status_transitioned: Any - connected_merchant_paypal_status_changed: Any - partner_merchant: Any - oauth_access_revocation: Any - disbursement: Any - dispute: Any - account_updater_daily_report: Any - granted_payment_instrument_update: Any - revoked_payment_method_metadata: Any - local_payment_completed: Any - local_payment_reversed: Any - errors: Any - message: Any + def verify(challenge: str) -> str: ... + source_merchant_id: Incomplete + subscription: Subscription + merchant_account: MerchantAccount + transaction: Transaction + transaction_review: TransactionReview + connected_merchant_status_transitioned: ConnectedMerchantStatusTransitioned + connected_merchant_paypal_status_changed: ConnectedMerchantPayPalStatusChanged + partner_merchant: PartnerMerchant + oauth_access_revocation: OAuthAccessRevocation + disbursement: Disbursement + dispute: Dispute + account_updater_daily_report: AccountUpdaterDailyReport + granted_payment_instrument_update: GrantedPaymentInstrumentUpdate + revoked_payment_method_metadata: RevokedPaymentMethodMetadata + local_payment_completed: LocalPaymentCompleted + local_payment_expired: LocalPaymentExpired + local_payment_funded: LocalPaymentFunded + local_payment_reversed: LocalPaymentReversed + payment_method_customer_data_updated_metadata: PaymentMethodCustomerDataUpdatedMetadata + errors: ValidationErrorCollection + message: Incomplete def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/webhook_notification_gateway.pyi b/stubs/braintree/braintree/webhook_notification_gateway.pyi index 9f26304aa798..671fde3deab9 100644 --- a/stubs/braintree/braintree/webhook_notification_gateway.pyi +++ b/stubs/braintree/braintree/webhook_notification_gateway.pyi @@ -1,16 +1,12 @@ -from typing import Any +from _typeshed import Incomplete -from braintree.exceptions.invalid_challenge_error import InvalidChallengeError as InvalidChallengeError -from braintree.exceptions.invalid_signature_error import InvalidSignatureError as InvalidSignatureError -from braintree.util.crypto import Crypto as Crypto -from braintree.util.xml_util import XmlUtil as XmlUtil -from braintree.webhook_notification import WebhookNotification as WebhookNotification +from braintree.webhook_notification import WebhookNotification text_type = str class WebhookNotificationGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def parse(self, signature, payload): ... - def verify(self, challenge): ... + def parse(self, signature: str, payload: str) -> WebhookNotification: ... + def verify(self, challenge: str) -> str: ... diff --git a/stubs/braintree/braintree/webhook_testing.pyi b/stubs/braintree/braintree/webhook_testing.pyi index 6e12f0cd1300..d47691caa553 100644 --- a/stubs/braintree/braintree/webhook_testing.pyi +++ b/stubs/braintree/braintree/webhook_testing.pyi @@ -1,7 +1,3 @@ -from typing import Any - -from braintree.configuration import Configuration as Configuration - class WebhookTesting: @staticmethod - def sample_notification(kind, id, source_merchant_id: Any | None = ...): ... + def sample_notification(kind: str, id: str, source_merchant_id: str | None = None) -> dict[str, str | bytes]: ... diff --git a/stubs/braintree/braintree/webhook_testing_gateway.pyi b/stubs/braintree/braintree/webhook_testing_gateway.pyi index b11569d054f8..8bb417416bd8 100644 --- a/stubs/braintree/braintree/webhook_testing_gateway.pyi +++ b/stubs/braintree/braintree/webhook_testing_gateway.pyi @@ -1,10 +1,7 @@ -from typing import Any - -from braintree.util.crypto import Crypto as Crypto -from braintree.webhook_notification import WebhookNotification as WebhookNotification +from _typeshed import Incomplete class WebhookTestingGateway: - gateway: Any - config: Any + gateway: Incomplete + config: Incomplete def __init__(self, gateway) -> None: ... - def sample_notification(self, kind, id, source_merchant_id: Any | None = ...): ... + def sample_notification(self, kind: str, id: str, source_merchant_id: str | None = None) -> dict[str, str | bytes]: ... diff --git a/stubs/cachetools/@tests/stubtest_allowlist.txt b/stubs/cachetools/@tests/stubtest_allowlist.txt index 878cbadf2488..a0bcfbfe73bc 100644 --- a/stubs/cachetools/@tests/stubtest_allowlist.txt +++ b/stubs/cachetools/@tests/stubtest_allowlist.txt @@ -1,2 +1,21 @@ cachetools.Cache.get -cachetools.cache.Cache.get + +# stubs omit defaulted arguments that are meant to be optimizations, not provided by user +cachetools.FIFOCache.__delitem__ +cachetools.FIFOCache.__setitem__ +cachetools.LFUCache.__delitem__ +cachetools.LFUCache.__getitem__ +cachetools.LFUCache.__setitem__ +cachetools.LRUCache.__delitem__ +cachetools.LRUCache.__getitem__ +cachetools.LRUCache.__setitem__ +cachetools.RRCache.__delitem__ +cachetools.RRCache.__setitem__ +cachetools.TLRUCache.__delitem__ +cachetools.TLRUCache.__getitem__ +cachetools.TLRUCache.__setitem__ +cachetools.TTLCache.__delitem__ +cachetools.TTLCache.__getitem__ +cachetools.TTLCache.__setitem__ +cachetools._TimedCache.__len__ +cachetools._TimedCache.__repr__ diff --git a/stubs/cachetools/@tests/test_cases/check_cachetools.py b/stubs/cachetools/@tests/test_cases/check_cachetools.py new file mode 100644 index 000000000000..cd890c76a209 --- /dev/null +++ b/stubs/cachetools/@tests/test_cases/check_cachetools.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from collections.abc import Hashable +from typing import Any +from typing_extensions import assert_type + +from cachetools import LRUCache, cached, keys as cachekeys +from cachetools.func import fifo_cache, lfu_cache, lru_cache, rr_cache, ttl_cache + +# Tests for cachetools.cached + +# Explicitly parameterize the cache to avoid Unknown types +cache_inst: LRUCache[int, int] = LRUCache(maxsize=128) + + +@cached(cache_inst) +def check_cached(x: int) -> int: + return x * 2 + + +assert_type(check_cached(3), int) +# Methods cache_info/cache_clear are only present when info=True; do not access them here. + + +@cached(cache_inst, info=True) +def check_cached_with_info(x: int) -> int: + return x + 1 + + +assert_type(check_cached_with_info(4), int) +assert_type(check_cached_with_info.cache_info().misses, int) +check_cached_with_info.cache_clear() + + +# Tests for cachetools.func decorators + + +@lru_cache +def lru_noparens(x: int) -> int: + return x * 2 + + +@lru_cache(maxsize=32) +def lru_with_maxsize(x: int) -> int: + return x * 3 + + +assert_type(lru_noparens(3), int) +assert_type(lru_with_maxsize(3), int) +assert_type(lru_noparens.cache_info().hits, int) +assert_type(lru_with_maxsize.cache_info().misses, int) +assert_type(lru_with_maxsize.cache_parameters(), dict[str, Any]) +lru_with_maxsize.cache_clear() + + +@fifo_cache +def fifo_func(x: int) -> int: + return x + + +@lfu_cache +def lfu_func(x: int) -> int: + return x + + +@rr_cache +def rr_func(x: int) -> int: + return x + + +@ttl_cache +def ttl_func(x: int) -> int: + return x + + +assert_type(fifo_func(1), int) +assert_type(lfu_func(1), int) +assert_type(rr_func(1), int) +assert_type(ttl_func(1), int) +assert_type(fifo_func.cache_info().currsize, float) +assert_type(lfu_func.cache_parameters(), dict[str, Any]) + + +# Tests for cachetools.keys + +k1 = cachekeys.hashkey(1, "a") +assert_type(k1, tuple[Hashable, ...]) + + +class C: + def method(self, a: int) -> int: + return a + + +inst = C() + +k2 = cachekeys.methodkey(inst, 5) +assert_type(k2, tuple[Hashable, ...]) + +k3 = cachekeys.typedkey(1, "x") +assert_type(k3, tuple[Hashable, ...]) + +k4 = cachekeys.typedmethodkey(inst, 2) +assert_type(k4, tuple[Hashable, ...]) diff --git a/stubs/cachetools/METADATA.toml b/stubs/cachetools/METADATA.toml index cb7498d03056..1099004a4a54 100644 --- a/stubs/cachetools/METADATA.toml +++ b/stubs/cachetools/METADATA.toml @@ -1 +1,3 @@ -version = "4.2.*" +version = "7.0.*" +upstream-repository = "https://github.com/tkem/cachetools" +obsolete-since = {version = "7.1.0", date = "2026-05-01"} diff --git a/stubs/cachetools/cachetools/__init__.pyi b/stubs/cachetools/cachetools/__init__.pyi index 06088cadd40a..add55e47a10d 100644 --- a/stubs/cachetools/cachetools/__init__.pyi +++ b/stubs/cachetools/cachetools/__init__.pyi @@ -1,24 +1,34 @@ -from _typeshed import IdentityFunction -from collections.abc import Iterator, Sequence +import random +from collections.abc import Callable, Iterator, MutableMapping, Sequence from contextlib import AbstractContextManager -from typing import Any, Callable, Generic, MutableMapping, TypeVar, overload +from typing import Any, Final, Generic, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only + +__all__: Final = ("Cache", "FIFOCache", "LFUCache", "LRUCache", "RRCache", "TLRUCache", "TTLCache", "cached", "cachedmethod") +__version__: str _KT = TypeVar("_KT") _VT = TypeVar("_VT") +_TT = TypeVar("_TT", default=float) _T = TypeVar("_T") +_R = TypeVar("_R") +_KT2 = TypeVar("_KT2") +_VT2 = TypeVar("_VT2") -class Cache(MutableMapping[_KT, _VT], Generic[_KT, _VT]): - def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = ...) -> None: ... +class Cache(MutableMapping[_KT, _VT]): + def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = None) -> None: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, value: _VT) -> None: ... def __delitem__(self, key: _KT) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... - @overload # type: ignore[override] + + @overload def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T) -> _VT | _T: ... - def setdefault(self, key: _KT, default: _VT | None = ...) -> _VT: ... + + def setdefault(self, key: _KT, default: _VT | None = None) -> _VT: ... @property def maxsize(self) -> float: ... @property @@ -26,42 +36,148 @@ class Cache(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @staticmethod def getsizeof(value: _VT) -> float: ... -class FIFOCache(Cache[_KT, _VT]): - def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = ...) -> None: ... - -class LFUCache(Cache[_KT, _VT]): - def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = ...) -> None: ... - -class LRUCache(Cache[_KT, _VT]): - def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = ...) -> None: ... - -class MRUCache(Cache[_KT, _VT]): - def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = ...) -> None: ... +class FIFOCache(Cache[_KT, _VT]): ... +class LFUCache(Cache[_KT, _VT]): ... +class LRUCache(Cache[_KT, _VT]): ... class RRCache(Cache[_KT, _VT]): def __init__( - self, maxsize: float, choice: Callable[[Sequence[_KT]], _KT] | None = ..., getsizeof: Callable[[_VT], float] | None = ... + self, + maxsize: float, + choice: Callable[[Sequence[_KT]], _KT] = random.choice, + getsizeof: Callable[[_VT], float] | None = None, ) -> None: ... @property def choice(self) -> Callable[[Sequence[_KT]], _KT]: ... -class TTLCache(Cache[_KT, _VT]): +class _TimedCache(Cache[_KT, _VT], Generic[_KT, _VT, _TT]): + def __init__(self, maxsize: float, timer: Callable[[], _TT], getsizeof: Callable[[_VT], float] | None = None) -> None: ... + + class _Timer(AbstractContextManager[_T]): + def __init__(self, timer: Callable[[], _T]) -> None: ... + def __call__(self) -> _T: ... + def __enter__(self) -> _T: ... + def __exit__(self, *exc: object) -> None: ... + def __getattr__(self, name: str) -> Any: ... + + @property + def timer(self) -> _Timer[_TT]: ... + +class TTLCache(_TimedCache[_KT, _VT, _TT]): + @overload def __init__( - self, maxsize: float, ttl: float, timer: Callable[[], float] = ..., getsizeof: Callable[[_VT], float] | None = ... + self: TTLCache[_KT2, _VT2, float], maxsize: float, ttl: float, *, getsizeof: Callable[[_VT2], float] | None = None ) -> None: ... + @overload + def __init__( + self, + maxsize: float, + ttl: Any, # FIXME: must be "addable" to _TT + timer: Callable[[], _TT], + getsizeof: Callable[[_VT], float] | None = None, + ) -> None: ... + @property - def currsize(self) -> float: ... - @property - def timer(self) -> Callable[[], float]: ... + def ttl(self) -> Any: ... + def expire(self, time: _TT | None = None) -> list[tuple[_KT, _VT]]: ... + +class TLRUCache(_TimedCache[_KT, _VT, _TT]): + @overload + def __init__( + self: TLRUCache[_KT2, _VT2, float], + maxsize: float, + ttu: Callable[[_KT2, _VT2, float], float], + *, + getsizeof: Callable[[_VT2], float] | None = None, + ) -> None: ... + @overload + def __init__( + self, + maxsize: float, + ttu: Callable[[_KT, _VT, _TT], _TT], + timer: Callable[[], _TT], + getsizeof: Callable[[_VT], float] | None = None, + ) -> None: ... + @property - def ttl(self) -> float: ... - def expire(self, time: float | None = ...) -> None: ... + def ttu(self) -> Callable[[_KT, _VT, _TT], _TT]: ... + def expire(self, time: _TT | None = None) -> list[tuple[_KT, _VT]]: ... + +class _CacheInfo(NamedTuple): + hits: int + misses: int + maxsize: float | None + currsize: float + +@type_check_only +class _AbstractCondition(AbstractContextManager[Any], Protocol): + def wait(self, timeout: float | None = None) -> bool: ... + def wait_for(self, predicate: Callable[[], _T], timeout: float | None = None) -> _T: ... + def notify(self, n: int = 1) -> None: ... + def notify_all(self) -> None: ... + +@type_check_only +class _cached_wrapper(Generic[_R]): + __wrapped__: Callable[..., _R] + __name__: str + __doc__: str | None + cache: MutableMapping[Any, Any] | None + cache_key: Callable[..., Any] = ... + cache_lock: AbstractContextManager[Any] | None = None + cache_condition: _AbstractCondition | None = None + def __call__(self, /, *args: Any, **kwargs: Any) -> _R: ... + def cache_clear(self) -> None: ... +@type_check_only +class _cached_wrapper_info(_cached_wrapper[_R]): + def cache_info(self) -> _CacheInfo: ... + +@overload +def cached( + cache: MutableMapping[_KT, Any] | None, + key: Callable[..., _KT] = ..., + lock: AbstractContextManager[Any] | None = None, + condition: _AbstractCondition | None = None, + info: Literal[True] = ..., +) -> Callable[[Callable[..., _R]], _cached_wrapper_info[_R]]: ... +@overload def cached( - cache: MutableMapping[_KT, Any] | None, key: Callable[..., _KT] = ..., lock: AbstractContextManager[Any] | None = ... -) -> IdentityFunction: ... + cache: MutableMapping[_KT, Any] | None, + key: Callable[..., _KT] = ..., + lock: AbstractContextManager[Any] | None = None, + condition: _AbstractCondition | None = None, + info: Literal[False] = ..., +) -> Callable[[Callable[..., _R]], _cached_wrapper[_R]]: ... + +@type_check_only +class _cachedmethod_wrapper(Generic[_R]): + __wrapped__: Callable[..., _R] + __name__: str + __doc__: str | None + cache: MutableMapping[Any, Any] | None + cache_key: Callable[..., Any] = ... + cache_lock: AbstractContextManager[Any] | None = None + cache_condition: _AbstractCondition | None = None + def __call__(self, /, *args: Any, **kwargs: Any) -> _R: ... + def cache_clear(self) -> None: ... + +@type_check_only +class _cachedmethod_wrapper_info(_cachedmethod_wrapper[_R]): + def cache_info(self) -> _CacheInfo: ... + +@overload +def cachedmethod( + cache: Callable[[Any], MutableMapping[_KT, Any]], + key: Callable[..., _KT] = ..., + lock: Callable[[Any], AbstractContextManager[Any]] | None = None, + condition: Callable[[Any], _AbstractCondition] | None = None, + info: Literal[True] = ..., +) -> Callable[[Callable[..., _R]], _cachedmethod_wrapper_info[_R]]: ... +@overload def cachedmethod( - cache: Callable[[Any], MutableMapping[_KT, Any] | None], + cache: Callable[[Any], MutableMapping[_KT, Any]], key: Callable[..., _KT] = ..., - lock: Callable[[Any], AbstractContextManager[Any]] | None = ..., -) -> IdentityFunction: ... + lock: Callable[[Any], AbstractContextManager[Any]] | None = None, + condition: Callable[[Any], _AbstractCondition] | None = None, + info: Literal[False] = ..., +) -> Callable[[Callable[..., _R]], _cachedmethod_wrapper[_R]]: ... diff --git a/stubs/cachetools/cachetools/cache.pyi b/stubs/cachetools/cachetools/cache.pyi deleted file mode 100644 index a9bd3f70f626..000000000000 --- a/stubs/cachetools/cachetools/cache.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import Cache as Cache diff --git a/stubs/cachetools/cachetools/fifo.pyi b/stubs/cachetools/cachetools/fifo.pyi deleted file mode 100644 index c6b386ad455a..000000000000 --- a/stubs/cachetools/cachetools/fifo.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import FIFOCache as FIFOCache diff --git a/stubs/cachetools/cachetools/func.pyi b/stubs/cachetools/cachetools/func.pyi index d081d5166316..974dde3da37d 100644 --- a/stubs/cachetools/cachetools/func.pyi +++ b/stubs/cachetools/cachetools/func.pyi @@ -1,13 +1,54 @@ -from _typeshed import IdentityFunction -from typing import Callable, Sequence, TypeVar +from collections.abc import Callable, Sequence +from typing import Any, Final, Generic, TypeVar, overload, type_check_only + +from . import _CacheInfo + +__all__: Final = ("fifo_cache", "lfu_cache", "lru_cache", "rr_cache", "ttl_cache") _T = TypeVar("_T") +_R = TypeVar("_R") + +@type_check_only +class _cachetools_cache_wrapper(Generic[_R]): + __wrapped__: Callable[..., _R] + __name__: str + __doc__: str | None + def __call__(self, /, *args: Any, **kwargs: Any) -> _R: ... + def cache_info(self) -> _CacheInfo: ... + def cache_clear(self) -> None: ... + def cache_parameters(self) -> dict[str, Any]: ... + +@overload +def fifo_cache( + maxsize: int | None = 128, typed: bool = False +) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def fifo_cache(maxsize: Callable[..., _R], typed: bool = False) -> _cachetools_cache_wrapper[_R]: ... -def fifo_cache(maxsize: float = ..., typed: bool = ...) -> IdentityFunction: ... -def lfu_cache(maxsize: float = ..., typed: bool = ...) -> IdentityFunction: ... -def lru_cache(maxsize: float = ..., typed: bool = ...) -> IdentityFunction: ... -def mru_cache(maxsize: float = ..., typed: bool = ...) -> IdentityFunction: ... -def rr_cache(maxsize: float = ..., choice: Callable[[Sequence[_T]], _T] | None = ..., typed: bool = ...) -> IdentityFunction: ... +@overload +def lfu_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def lfu_cache(maxsize: Callable[..., _R], typed: bool = False) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def lru_cache(maxsize: Callable[..., _R], typed: bool = False) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def rr_cache( + maxsize: int | None = 128, choice: Callable[[Sequence[_T]], _T] = ..., typed: bool = False +) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def rr_cache( + maxsize: Callable[..., _R], choice: Callable[[Sequence[_T]], _T] = ..., typed: bool = False +) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def ttl_cache( + maxsize: int | None = 128, ttl: Any = 600, timer: Callable[[], _T] = ..., typed: bool = False +) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload def ttl_cache( - maxsize: float = ..., ttl: float = ..., timer: Callable[[], float] = ..., typed: bool = ... -) -> IdentityFunction: ... + maxsize: Callable[..., _R], ttl: Any = 600, timer: Callable[[], _T] = ..., typed: bool = False +) -> _cachetools_cache_wrapper[_R]: ... diff --git a/stubs/cachetools/cachetools/keys.pyi b/stubs/cachetools/cachetools/keys.pyi index 9effbe6e171f..feccf6f9bcea 100644 --- a/stubs/cachetools/cachetools/keys.pyi +++ b/stubs/cachetools/cachetools/keys.pyi @@ -1,4 +1,10 @@ -from typing import Hashable, Tuple +from _typeshed import Unused +from collections.abc import Hashable +from typing import Final -def hashkey(*args: Hashable, **kwargs: Hashable) -> Tuple[Hashable, ...]: ... -def typedkey(*args: Hashable, **kwargs: Hashable) -> Tuple[Hashable, ...]: ... +__all__: Final = ("hashkey", "methodkey", "typedkey", "typedmethodkey") + +def hashkey(*args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... +def methodkey(self: Unused, /, *args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... +def typedkey(*args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... +def typedmethodkey(self: Unused, /, *args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... diff --git a/stubs/cachetools/cachetools/lfu.pyi b/stubs/cachetools/cachetools/lfu.pyi deleted file mode 100644 index 9951e65e2841..000000000000 --- a/stubs/cachetools/cachetools/lfu.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import LFUCache as LFUCache diff --git a/stubs/cachetools/cachetools/lru.pyi b/stubs/cachetools/cachetools/lru.pyi deleted file mode 100644 index 4ea2d6413ca6..000000000000 --- a/stubs/cachetools/cachetools/lru.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import LRUCache as LRUCache diff --git a/stubs/cachetools/cachetools/mru.pyi b/stubs/cachetools/cachetools/mru.pyi deleted file mode 100644 index b345f5262b04..000000000000 --- a/stubs/cachetools/cachetools/mru.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import MRUCache as MRUCache diff --git a/stubs/cachetools/cachetools/rr.pyi b/stubs/cachetools/cachetools/rr.pyi deleted file mode 100644 index 18e2098ceb66..000000000000 --- a/stubs/cachetools/cachetools/rr.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import RRCache as RRCache diff --git a/stubs/cachetools/cachetools/ttl.pyi b/stubs/cachetools/cachetools/ttl.pyi deleted file mode 100644 index aee05857648a..000000000000 --- a/stubs/cachetools/cachetools/ttl.pyi +++ /dev/null @@ -1,2 +0,0 @@ -# this module is deprecated -from . import TTLCache as TTLCache diff --git a/stubs/caldav/@tests/stubtest_allowlist.txt b/stubs/caldav/@tests/stubtest_allowlist.txt deleted file mode 100644 index 293f7da8b10a..000000000000 --- a/stubs/caldav/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,13 +0,0 @@ -# **kwargs replaced with actual arguments in stubs -caldav.DAVClient.calendar -caldav.DAVClient.principal -caldav.davclient.DAVClient.calendar -caldav.davclient.DAVClient.principal - -# Initialized in class, but immediately overwritten in __init__ -caldav.DAVClient.url -caldav.davclient.DAVClient.url -caldav.davclient.DAVResponse.headers -caldav.elements.base.BaseElement.children - -.*.findprop diff --git a/stubs/caldav/METADATA.toml b/stubs/caldav/METADATA.toml deleted file mode 100644 index a8d20041e01c..000000000000 --- a/stubs/caldav/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -version = "0.8.*" -# also types-lxml and types-icalendar when those stubs are added -requires = ["types-requests", "types-vobject"] diff --git a/stubs/caldav/caldav/__init__.pyi b/stubs/caldav/caldav/__init__.pyi deleted file mode 100644 index 721495fa93d4..000000000000 --- a/stubs/caldav/caldav/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from .davclient import DAVClient as DAVClient -from .objects import * diff --git a/stubs/caldav/caldav/davclient.pyi b/stubs/caldav/caldav/davclient.pyi deleted file mode 100644 index 6689f23e3995..000000000000 --- a/stubs/caldav/caldav/davclient.pyi +++ /dev/null @@ -1,70 +0,0 @@ -from collections.abc import Iterable, Mapping -from typing import Any -from urllib.parse import ParseResult, SplitResult - -from requests.auth import AuthBase -from requests.models import Response -from requests.structures import CaseInsensitiveDict - -from .lib.url import URL -from .objects import Calendar, DAVObject, Principal - -_Element = Any # actually lxml.etree._Element - -class DAVResponse: - reason: str - tree: _Element | None - status: int - headers: CaseInsensitiveDict[str] - objects: dict[str, dict[str, str]] # only defined after call to find_objects_and_props() - def __init__(self, response: Response) -> None: ... - @property - def raw(self) -> str: ... - def validate_status(self, status: str) -> None: ... - def find_objects_and_props(self) -> None: ... - def expand_simple_props( - self, props: Iterable[Any] = ..., multi_value_props: Iterable[Any] = ..., xpath: str | None = ... - ) -> dict[str, dict[str, str]]: ... - -class DAVClient: - proxy: str | None - url: URL - headers: dict[str, str] - username: str | None - password: str | None - auth: AuthBase | None - ssl_verify_cert: bool | str - ssl_cert: str | tuple[str, str] | None - def __init__( - self, - url: str, - proxy: str | None = ..., - username: str | None = ..., - password: str | None = ..., - auth: AuthBase | None = ..., - ssl_verify_cert: bool | str = ..., - ssl_cert: str | tuple[str, str] | None = ..., - ) -> None: ... - def principal(self, *, url: str | ParseResult | SplitResult | URL | None = ...) -> Principal: ... - def calendar( - self, - url: str | ParseResult | SplitResult | URL | None = ..., - parent: DAVObject | None = ..., - name: str | None = ..., - id: str | None = ..., - props: Mapping[Any, Any] = ..., - **extra: Any, - ) -> Calendar: ... - def check_dav_support(self) -> str | None: ... - def check_cdav_support(self) -> bool: ... - def check_scheduling_support(self) -> bool: ... - def propfind(self, url: str | None = ..., props: str = ..., depth: int = ...) -> DAVResponse: ... - def proppatch(self, url: str, body: str, dummy: None = ...) -> DAVResponse: ... - def report(self, url: str, query: str = ..., depth: int = ...) -> DAVResponse: ... - def mkcol(self, url: str, body: str, dummy: None = ...) -> DAVResponse: ... - def mkcalendar(self, url: str, body: str = ..., dummy: None = ...) -> DAVResponse: ... - def put(self, url: str, body: str, headers: Mapping[str, str] = ...) -> DAVResponse: ... - def post(self, url: str, body: str, headers: Mapping[str, str] = ...) -> DAVResponse: ... - def delete(self, url: str) -> DAVResponse: ... - def options(self, url: str) -> DAVResponse: ... - def request(self, url: str, method: str = ..., body: str = ..., headers: Mapping[str, str] = ...) -> DAVResponse: ... diff --git a/stubs/caldav/caldav/elements/base.pyi b/stubs/caldav/caldav/elements/base.pyi deleted file mode 100644 index c418e0cde41a..000000000000 --- a/stubs/caldav/caldav/elements/base.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from _typeshed import Self -from collections.abc import Iterable -from typing import Any, ClassVar - -_Element = Any # actually lxml.etree._Element - -class BaseElement: - tag: ClassVar[str | None] - children: list[BaseElement] - value: str | None - attributes: Any | None - caldav_class: Any | None - def __init__(self, name: str | None = ..., value: str | bytes | None = ...) -> None: ... - def __add__(self: Self, other: BaseElement) -> Self: ... - def xmlelement(self) -> _Element: ... - def xmlchildren(self, root: _Element) -> None: ... - def append(self: Self, element: BaseElement | Iterable[BaseElement]) -> Self: ... - -class NamedBaseElement(BaseElement): - def __init__(self, name: str | None = ...) -> None: ... - -class ValuedBaseElement(BaseElement): - def __init__(self, value: str | bytes | None = ...) -> None: ... diff --git a/stubs/caldav/caldav/elements/cdav.pyi b/stubs/caldav/caldav/elements/cdav.pyi deleted file mode 100644 index 632894a24460..000000000000 --- a/stubs/caldav/caldav/elements/cdav.pyi +++ /dev/null @@ -1,100 +0,0 @@ -import datetime -from typing import ClassVar - -from .base import BaseElement, NamedBaseElement, ValuedBaseElement - -class CalendarQuery(BaseElement): - tag: ClassVar[str] - -class FreeBusyQuery(BaseElement): - tag: ClassVar[str] - -class Mkcalendar(BaseElement): - tag: ClassVar[str] - -class CalendarMultiGet(BaseElement): - tag: ClassVar[str] - -class ScheduleInboxURL(BaseElement): - tag: ClassVar[str] - -class ScheduleOutboxURL(BaseElement): - tag: ClassVar[str] - -class Filter(BaseElement): - tag: ClassVar[str] - -class CompFilter(NamedBaseElement): - tag: ClassVar[str] - -class PropFilter(NamedBaseElement): - tag: ClassVar[str] - -class ParamFilter(NamedBaseElement): - tag: ClassVar[str] - -class TextMatch(ValuedBaseElement): - tag: ClassVar[str] - def __init__(self, value, collation: str = ..., negate: bool = ...) -> None: ... - -class TimeRange(BaseElement): - tag: ClassVar[str] - def __init__(self, start: datetime.datetime | None = ..., end: datetime.datetime | None = ...) -> None: ... - -class NotDefined(BaseElement): - tag: ClassVar[str] - -class CalendarData(BaseElement): - tag: ClassVar[str] - -class Expand(BaseElement): - tag: ClassVar[str] - def __init__(self, start: datetime.datetime | None, end: datetime.datetime | None = ...) -> None: ... - -class Comp(NamedBaseElement): - tag: ClassVar[str] - -class CalendarUserAddressSet(BaseElement): - tag: ClassVar[str] - -class CalendarUserType(BaseElement): - tag: ClassVar[str] - -class CalendarHomeSet(BaseElement): - tag: ClassVar[str] - -class Calendar(BaseElement): - tag: ClassVar[str] - -class CalendarDescription(ValuedBaseElement): - tag: ClassVar[str] - -class CalendarTimeZone(ValuedBaseElement): - tag: ClassVar[str] - -class SupportedCalendarComponentSet(ValuedBaseElement): - tag: ClassVar[str] - -class SupportedCalendarData(ValuedBaseElement): - tag: ClassVar[str] - -class MaxResourceSize(ValuedBaseElement): - tag: ClassVar[str] - -class MinDateTime(ValuedBaseElement): - tag: ClassVar[str] - -class MaxDateTime(ValuedBaseElement): - tag: ClassVar[str] - -class MaxInstances(ValuedBaseElement): - tag: ClassVar[str] - -class MaxAttendeesPerInstance(ValuedBaseElement): - tag: ClassVar[str] - -class Allprop(BaseElement): - tag: ClassVar[str] - -class ScheduleTag(BaseElement): - tag: ClassVar[str] diff --git a/stubs/caldav/caldav/elements/dav.pyi b/stubs/caldav/caldav/elements/dav.pyi deleted file mode 100644 index 4f3577e2f51e..000000000000 --- a/stubs/caldav/caldav/elements/dav.pyi +++ /dev/null @@ -1,63 +0,0 @@ -from typing import ClassVar - -from .base import BaseElement, ValuedBaseElement - -class Propfind(BaseElement): - tag: ClassVar[str] - -class PropertyUpdate(BaseElement): - tag: ClassVar[str] - -class Mkcol(BaseElement): - tag: ClassVar[str] - -class SyncCollection(BaseElement): - tag: ClassVar[str] - -class SyncToken(BaseElement): - tag: ClassVar[str] - -class SyncLevel(BaseElement): - tag: ClassVar[str] - -class Prop(BaseElement): - tag: ClassVar[str] - -class Collection(BaseElement): - tag: ClassVar[str] - -class Set(BaseElement): - tag: ClassVar[str] - -class ResourceType(BaseElement): - tag: ClassVar[str] - -class DisplayName(ValuedBaseElement): - tag: ClassVar[str] - -class GetEtag(ValuedBaseElement): - tag: ClassVar[str] - -class Href(BaseElement): - tag: ClassVar[str] - -class Response(BaseElement): - tag: ClassVar[str] - -class Status(BaseElement): - tag: ClassVar[str] - -class PropStat(BaseElement): - tag: ClassVar[str] - -class MultiStatus(BaseElement): - tag: ClassVar[str] - -class CurrentUserPrincipal(BaseElement): - tag: ClassVar[str] - -class PrincipalCollectionSet(BaseElement): - tag: ClassVar[str] - -class Allprop(BaseElement): - tag: ClassVar[str] diff --git a/stubs/caldav/caldav/elements/ical.pyi b/stubs/caldav/caldav/elements/ical.pyi deleted file mode 100644 index 762d6ae1ec93..000000000000 --- a/stubs/caldav/caldav/elements/ical.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import ClassVar - -from .base import ValuedBaseElement - -class CalendarColor(ValuedBaseElement): - tag: ClassVar[str] - -class CalendarOrder(ValuedBaseElement): - tag: ClassVar[str] diff --git a/stubs/caldav/caldav/lib/error.pyi b/stubs/caldav/caldav/lib/error.pyi deleted file mode 100644 index b088bb8f2623..000000000000 --- a/stubs/caldav/caldav/lib/error.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Type - -def assert_(condition: object) -> None: ... - -ERR_FRAGMENT: str - -class DAVError(Exception): - url: str | None - reason: str - def __init__(self, url: str | None = ..., reason: str | None = ...) -> None: ... - -class AuthorizationError(DAVError): ... -class PropsetError(DAVError): ... -class ProppatchError(DAVError): ... -class PropfindError(DAVError): ... -class ReportError(DAVError): ... -class MkcolError(DAVError): ... -class MkcalendarError(DAVError): ... -class PutError(DAVError): ... -class DeleteError(DAVError): ... -class NotFoundError(DAVError): ... -class ConsistencyError(DAVError): ... -class ResponseError(DAVError): ... - -exception_by_method: dict[str, Type[DAVError]] diff --git a/stubs/caldav/caldav/lib/namespace.pyi b/stubs/caldav/caldav/lib/namespace.pyi deleted file mode 100644 index a3ad5724ee79..000000000000 --- a/stubs/caldav/caldav/lib/namespace.pyi +++ /dev/null @@ -1,4 +0,0 @@ -nsmap: dict[str, str] -nsmap2: dict[str, str] - -def ns(prefix: str, tag: str | None = ...) -> str: ... diff --git a/stubs/caldav/caldav/lib/url.pyi b/stubs/caldav/caldav/lib/url.pyi deleted file mode 100644 index a47a19578b6a..000000000000 --- a/stubs/caldav/caldav/lib/url.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import overload -from urllib.parse import ParseResult, SplitResult - -class URL: - def __init__(self, url: str | ParseResult | SplitResult) -> None: ... - def __bool__(self) -> bool: ... - def __ne__(self, other: object) -> bool: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - @overload - @classmethod - def objectify(cls, url: None) -> None: ... - @overload - @classmethod - def objectify(cls, url: URL | str | ParseResult | SplitResult) -> URL: ... - def __getattr__(self, attr: str): ... - def __unicode__(self) -> str: ... - def strip_trailing_slash(self) -> URL: ... - def is_auth(self) -> bool: ... - def unauth(self) -> URL: ... - def canonical(self) -> URL: ... - def join(self, path: object) -> URL: ... - -@overload -def make(url: None) -> None: ... -@overload -def make(url: URL | str | ParseResult | SplitResult) -> URL: ... diff --git a/stubs/caldav/caldav/lib/vcal.pyi b/stubs/caldav/caldav/lib/vcal.pyi deleted file mode 100644 index 7b567428c447..000000000000 --- a/stubs/caldav/caldav/lib/vcal.pyi +++ /dev/null @@ -1 +0,0 @@ -def fix(event): ... diff --git a/stubs/caldav/caldav/objects.pyi b/stubs/caldav/caldav/objects.pyi deleted file mode 100644 index 6f2f94ff1dc1..000000000000 --- a/stubs/caldav/caldav/objects.pyi +++ /dev/null @@ -1,175 +0,0 @@ -import datetime -from _typeshed import Self -from collections.abc import Iterable, Iterator, Mapping -from typing import Any, Type, TypeVar, overload -from typing_extensions import Literal -from urllib.parse import ParseResult, SplitResult - -from vobject.base import VBase - -from .davclient import DAVClient -from .elements.cdav import CompFilter, ScheduleInboxURL, ScheduleOutboxURL -from .lib.url import URL - -_CC = TypeVar("_CC", bound=CalendarObjectResource) - -_vCalAddress = Any # actually icalendar.vCalAddress - -class DAVObject: - id: str | None - url: URL | None - client: DAVClient | None - parent: DAVObject | None - name: str | None - props: Mapping[Any, Any] - extra_init_options: dict[str, Any] - def __init__( - self, - client: DAVClient | None = ..., - url: str | ParseResult | SplitResult | URL | None = ..., - parent: DAVObject | None = ..., - name: str | None = ..., - id: str | None = ..., - props: Mapping[Any, Any] | None = ..., - **extra: Any, - ) -> None: ... - @property - def canonical_url(self) -> str: ... - def children(self, type: str | None = ...) -> list[tuple[URL, Any, Any]]: ... - def get_property(self, prop, use_cached: bool = ..., **passthrough) -> Any | None: ... - def get_properties( - self, props: Any | None = ..., depth: int = ..., parse_response_xml: bool = ..., parse_props: bool = ... - ): ... - def set_properties(self: Self, props: Any | None = ...) -> Self: ... - def save(self: Self) -> Self: ... - def delete(self) -> None: ... - -class CalendarSet(DAVObject): - def calendars(self) -> list[Calendar]: ... - def make_calendar( - self, name: str | None = ..., cal_id: str | None = ..., supported_calendar_component_set: Any | None = ... - ) -> Calendar: ... - def calendar(self, name: str | None = ..., cal_id: str | None = ...) -> Calendar: ... - -class Principal(DAVObject): - def __init__(self, client: DAVClient | None = ..., url: str | ParseResult | SplitResult | URL | None = ...) -> None: ... - def calendars(self) -> list[Calendar]: ... - def make_calendar( - self, name: str | None = ..., cal_id: str | None = ..., supported_calendar_component_set: Any | None = ... - ) -> Calendar: ... - def calendar(self, name: str | None = ..., cal_id: str | None = ...) -> Calendar: ... - def get_vcal_address(self) -> _vCalAddress: ... - calendar_home_set: CalendarSet # can also be set to anything URL.objectify() accepts - def freebusy_request(self, dtstart, dtend, attendees): ... - def calendar_user_address_set(self) -> list[str]: ... - def schedule_inbox(self) -> ScheduleInbox: ... - def schedule_outbox(self) -> ScheduleOutbox: ... - -class Calendar(DAVObject): - def get_supported_components(self) -> list[Any]: ... - def save_with_invites(self, ical: str, attendees, **attendeeoptions) -> None: ... - def save_event(self, ical: str, no_overwrite: bool = ..., no_create: bool = ...) -> Event: ... - def save_todo(self, ical: str, no_overwrite: bool = ..., no_create: bool = ...) -> Todo: ... - def save_journal(self, ical: str, no_overwrite: bool = ..., no_create: bool = ...) -> Journal: ... - add_event = save_event - add_todo = save_todo - add_journal = save_journal - def calendar_multiget(self, event_urls: Iterable[URL]) -> list[Event]: ... - def build_date_search_query( - self, - start, - end: datetime.datetime | None = ..., - compfilter: Literal["VEVENT"] | None = ..., - expand: bool | Literal["maybe"] = ..., - ): ... - @overload - def date_search( - self, - start: datetime.datetime, - end: datetime.datetime | None = ..., - compfilter: Literal["VEVENT"] = ..., - expand: bool | Literal["maybe"] = ..., - ) -> list[Event]: ... - @overload - def date_search( - self, start: datetime.datetime, *, compfilter: None, expand: bool | Literal["maybe"] = ... - ) -> list[CalendarObjectResource]: ... - @overload - def date_search( - self, start: datetime.datetime, end: datetime.datetime | None, compfilter: None, expand: bool | Literal["maybe"] = ... - ) -> list[CalendarObjectResource]: ... - @overload - def search(self, xml, comp_class: None = ...) -> list[CalendarObjectResource]: ... - @overload - def search(self, xml, comp_class: Type[_CC]) -> list[_CC]: ... - def freebusy_request(self, start: datetime.datetime, end: datetime.datetime) -> FreeBusy: ... - def todos(self, sort_keys: Iterable[str] = ..., include_completed: bool = ..., sort_key: str | None = ...) -> list[Todo]: ... - def event_by_url(self, href, data: Any | None = ...) -> Event: ... - def object_by_uid(self, uid: str, comp_filter: CompFilter | None = ...) -> Event: ... - def todo_by_uid(self, uid: str) -> CalendarObjectResource: ... - def event_by_uid(self, uid: str) -> CalendarObjectResource: ... - def journal_by_uid(self, uid: str) -> CalendarObjectResource: ... - event = event_by_uid - def events(self) -> list[Event]: ... - def objects_by_sync_token( - self, sync_token: Any | None = ..., load_objects: bool = ... - ) -> SynchronizableCalendarObjectCollection: ... - objects = objects_by_sync_token - def journals(self) -> list[Journal]: ... - -class ScheduleMailbox(Calendar): - def __init__( - self, - client: DAVClient | None = ..., - principal: Principal | None = ..., - url: str | ParseResult | SplitResult | URL | None = ..., - ) -> None: ... - def get_items(self): ... - -class ScheduleInbox(ScheduleMailbox): - findprop = ScheduleInboxURL - -class ScheduleOutbox(ScheduleMailbox): - findprop = ScheduleOutboxURL - -class SynchronizableCalendarObjectCollection: - def __init__(self, calendar, objects, sync_token) -> None: ... - def __iter__(self) -> Iterator[Any]: ... - def objects_by_url(self): ... - def sync(self) -> tuple[Any, Any]: ... - -class CalendarObjectResource(DAVObject): - def __init__( - self, - client: DAVClient | None = ..., - url: str | ParseResult | SplitResult | URL | None = ..., - data: Any | None = ..., - parent: Any | None = ..., - id: Any | None = ..., - props: Any | None = ..., - ) -> None: ... - def add_organizer(self) -> None: ... - def add_attendee(self, attendee, no_default_parameters: bool = ..., **parameters) -> None: ... - def is_invite_request(self) -> bool: ... - def accept_invite(self, calendar: Any | None = ...) -> None: ... - def decline_invite(self, calendar: Any | None = ...) -> None: ... - def tentatively_accept_invite(self, calendar: Any | None = ...) -> None: ... - def copy(self: Self, keep_uid: bool = ..., new_parent: Any | None = ...) -> Self: ... - def load(self: Self) -> Self: ... - def change_attendee_status(self, attendee: Any | None = ..., **kwargs) -> None: ... - def save( - self: Self, no_overwrite: bool = ..., no_create: bool = ..., obj_type: Any | None = ..., if_schedule_tag_match: bool = ... - ) -> Self: ... - data: Any - vobject_instance: VBase - icalendar_instance: Any - instance: VBase - -class Event(CalendarObjectResource): ... -class Journal(CalendarObjectResource): ... - -class FreeBusy(CalendarObjectResource): - def __init__(self, parent, data, url: str | ParseResult | SplitResult | URL | None = ..., id: Any | None = ...) -> None: ... - -class Todo(CalendarObjectResource): - def complete(self, completion_timestamp: datetime.datetime | None = ...) -> None: ... diff --git a/stubs/capturer/@tests/stubtest_allowlist.txt b/stubs/capturer/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..6f3cc357f2f6 --- /dev/null +++ b/stubs/capturer/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Tests should not be part of the stubs +capturer.tests.* diff --git a/stubs/capturer/METADATA.toml b/stubs/capturer/METADATA.toml new file mode 100644 index 000000000000..a64fd3f58135 --- /dev/null +++ b/stubs/capturer/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.0.*" +upstream-repository = "https://github.com/xolox/python-capturer" diff --git a/stubs/capturer/capturer.pyi b/stubs/capturer/capturer.pyi new file mode 100644 index 000000000000..0bd324a760ea --- /dev/null +++ b/stubs/capturer/capturer.pyi @@ -0,0 +1,122 @@ +from _typeshed import FileDescriptorOrPath, SupportsWrite +from collections.abc import Callable +from io import BufferedReader +from multiprocessing import Process +from multiprocessing.queues import Queue +from multiprocessing.synchronize import Event +from signal import Signals +from types import FrameType, TracebackType +from typing import IO, Any +from typing_extensions import Never, Self + +__version__: str +aliases: dict[str, Any] +DEFAULT_TEXT_ENCODING: str +GRACEFUL_SHUTDOWN_SIGNAL: Signals +TERMINATION_DELAY: float +PARTIAL_DEFAULT: bool +STDOUT_FD: int +STDERR_FD: int + +def enable_old_api() -> None: ... +def create_proxy_method(name: str) -> Callable[..., Any]: ... + +class MultiProcessHelper: + processes: list[Process] + def __init__(self) -> None: ... + def start_child(self, target: Callable[[Event], Any]) -> None: ... + def stop_children(self) -> None: ... + def wait_for_children(self) -> None: ... + def enable_graceful_shutdown(self) -> None: ... + def raise_shutdown_request(self, signum: int, frame: FrameType | None) -> Never: ... + +class CaptureOutput(MultiProcessHelper): + chunk_size: int + encoding: str + merged: bool + relay: bool + termination_delay: float + pseudo_terminals: list[PseudoTerminal] + streams: list[tuple[int, Stream]] + stdout_stream: Stream + stderr_stream: Stream + output: PseudoTerminal + output_queue: Queue[tuple[Any, bytes]] + stdout: PseudoTerminal + stderr: PseudoTerminal + def __init__( + self, merged: bool = True, encoding: str = ..., termination_delay: float = ..., chunk_size: int = 1024, relay: bool = True + ) -> None: ... + def initialize_stream(self, file_obj: IO[str], expected_fd: int) -> Stream: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> bool | None: ... + @property + def is_capturing(self) -> bool: ... + def start_capture(self) -> None: ... + def finish_capture(self) -> None: ... + def allocate_pty( + self, relay_fd: int | None = None, output_queue: Queue[tuple[Any, bytes]] | None = None, queue_token: Any | None = None + ) -> PseudoTerminal: ... + def merge_loop(self, started_event: Event) -> None: ... + def get_handle(self, partial: bool = ...) -> BufferedReader: ... + def get_bytes(self, partial: bool = ...) -> bytes: ... + def get_lines(self, interpreted: bool = True, partial: bool = ...) -> list[str]: ... + def get_text(self, interpreted: bool = ..., partial: bool = ...) -> str: ... + def save_to_handle(self, handle: SupportsWrite[bytes], partial: bool = ...) -> None: ... + def save_to_path(self, filename: FileDescriptorOrPath, partial: bool = ...) -> None: ... + +class OutputBuffer: + fd: int + buffer: bytes + def __init__(self, fd: int) -> None: ... + def add(self, output: bytes) -> None: ... + def flush(self) -> None: ... + +class PseudoTerminal(MultiProcessHelper): + encoding: str + termination_delay: float + chunk_size: int + relay_fd: int | None + output_queue: Queue[tuple[Any, bytes]] | None + queue_token: Any | None + streams: list[Stream] + master_fd: int + slave_fd: int + output_fd: int + output_handle: BufferedReader + def __init__( + self, + encoding: str, + termination_delay: float, + chunk_size: int, + relay_fd: int | None, + output_queue: Queue[tuple[int, bytes]] | None, + queue_token: Any | None, + ) -> None: ... + def attach(self, stream: Stream) -> None: ... + def start_capture(self) -> None: ... + def finish_capture(self) -> None: ... + def close_pseudo_terminal(self) -> None: ... + def restore_streams(self) -> None: ... + def get_handle(self, partial: bool = ...) -> BufferedReader: ... + def get_bytes(self, partial: bool = ...) -> bytes: ... + def get_lines(self, interpreted: bool = True, partial: bool = ...) -> list[str]: ... + def get_text(self, interpreted: bool = ..., partial: bool = ...) -> str: ... + def save_to_handle(self, handle: SupportsWrite[bytes], partial: bool = ...) -> None: ... + def save_to_path(self, filename: FileDescriptorOrPath, partial: bool = ...) -> None: ... + def capture_loop(self, started_event: Event) -> None: ... + +class Stream: + fd: int + original_fd: int + is_redirected: bool + def __init__(self, fd: int) -> None: ... + def redirect(self, target_fd: int) -> None: ... + def restore(self) -> None: ... + +class ShutdownRequested(Exception): ... diff --git a/stubs/certifi/METADATA.toml b/stubs/certifi/METADATA.toml deleted file mode 100644 index a75d69563a04..000000000000 --- a/stubs/certifi/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "2021.10.8" -python2 = true diff --git a/stubs/certifi/certifi.pyi b/stubs/certifi/certifi.pyi deleted file mode 100644 index 315f7c822eee..000000000000 --- a/stubs/certifi/certifi.pyi +++ /dev/null @@ -1,2 +0,0 @@ -def where() -> str: ... -def contents() -> str: ... diff --git a/stubs/cffi/@tests/stubtest_allowlist.txt b/stubs/cffi/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..908583146f5f --- /dev/null +++ b/stubs/cffi/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# added dynamically and not detected by stubtest +cffi.(api.)?FFI.CData +cffi.(api.)?FFI.CType +cffi.(api.)?FFI.buffer diff --git a/stubs/cffi/@tests/stubtest_allowlist_darwin.txt b/stubs/cffi/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..55d4b889aca9 --- /dev/null +++ b/stubs/cffi/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# Technically exists on all OSs, but crashes on all but Windows. So we hide it in stubs +cffi.(api.)?FFI.getwinerror diff --git a/stubs/cffi/@tests/stubtest_allowlist_linux.txt b/stubs/cffi/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..55d4b889aca9 --- /dev/null +++ b/stubs/cffi/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# Technically exists on all OSs, but crashes on all but Windows. So we hide it in stubs +cffi.(api.)?FFI.getwinerror diff --git a/stubs/cffi/METADATA.toml b/stubs/cffi/METADATA.toml new file mode 100644 index 000000000000..443f8d492847 --- /dev/null +++ b/stubs/cffi/METADATA.toml @@ -0,0 +1,7 @@ +version = "2.1.*" +upstream-repository = "https://github.com/python-cffi/cffi/" +dependencies = ["types-setuptools"] + +[tool.stubtest] +# linux and darwin are mostly equivalent, except for a single `RTLD_DEEPBIND` variable +ci-platforms = ["linux", "win32"] diff --git a/stubs/cffi/_cffi_backend.pyi b/stubs/cffi/_cffi_backend.pyi new file mode 100644 index 000000000000..27c2f4d6cf00 --- /dev/null +++ b/stubs/cffi/_cffi_backend.pyi @@ -0,0 +1,286 @@ +import sys +import types +from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer +from collections.abc import Callable, Hashable +from typing import Any, ClassVar, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_T = TypeVar("_T") + +@type_check_only +class _Allocator(Protocol): + def __call__(self, cdecl: str | CType, init: Any = ...) -> _CDataBase: ... + +__version__: str + +FFI_CDECL: int +FFI_DEFAULT_ABI: int +RTLD_GLOBAL: int +RTLD_LAZY: int +RTLD_LOCAL: int +RTLD_NOW: int +if sys.platform == "linux": + RTLD_DEEPBIND: int +if sys.platform != "win32": + RTLD_NODELETE: int + RTLD_NOLOAD: int + +@final +class CField: + bitshift: Incomplete + bitsize: Incomplete + flags: Incomplete + offset: Incomplete + type: Incomplete + +@final +class CLibrary: + def close_lib(self) -> None: ... + def load_function(self, *args, **kwargs): ... + def read_variable(self, *args, **kwargs): ... + def write_variable(self, *args, **kwargs): ... + +@final +class CType: + abi: Incomplete + args: Incomplete + cname: Incomplete + elements: Incomplete + ellipsis: Incomplete + fields: Incomplete + item: Incomplete + kind: Incomplete + length: Incomplete + relements: Incomplete + result: Incomplete + def __dir__(self): ... + +@final +class Lib: + def __dir__(self): ... + +@final +class _CDataBase: + __name__: ClassVar[str] + def __add__(self, other, /): ... + def __bool__(self) -> bool: ... + def __call__(self, *args, **kwargs): ... + def __complex__(self) -> complex: ... + def __delitem__(self, other, /) -> None: ... + def __dir__(self): ... + def __enter__(self) -> Self: ... + def __eq__(self, other, /): ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None, / + ): ... + def __float__(self) -> float: ... + def __ge__(self, other, /): ... + def __getitem__(self, index: SupportsIndex | slice, /): ... + def __gt__(self, other, /): ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def __iter__(self): ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + def __radd__(self, other, /): ... + def __rsub__(self, other, /): ... + def __setitem__(self, index: SupportsIndex | slice, object, /) -> None: ... + def __sub__(self, other, /): ... + +@final +class buffer: + __hash__: ClassVar[None] # type: ignore[assignment] + def __new__(cls, *args, **kwargs) -> Self: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __delitem__(self, other, /) -> None: ... + def __eq__(self, other, /): ... + def __ge__(self, other, /): ... + def __getitem__(self, index, /): ... + def __gt__(self, other, /): ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + def __setitem__(self, index, object, /) -> None: ... + +# These aliases are to work around pyright complaints. +# Pyright doesn't like it when a class object is defined as an alias +# of a global object with the same name. +_tmp_CType = CType +_tmp_buffer = buffer + +@disjoint_base +class FFI: + CData: TypeAlias = _CDataBase + CType: TypeAlias = _tmp_CType + buffer: TypeAlias = _tmp_buffer # noqa: Y042 + + class error(Exception): ... + NULL: ClassVar[CData] + RTLD_GLOBAL: ClassVar[int] + RTLD_LAZY: ClassVar[int] + RTLD_LOCAL: ClassVar[int] + RTLD_NOW: ClassVar[int] + if sys.platform != "win32": + RTLD_DEEPBIND: ClassVar[int] + RTLD_NODELETE: ClassVar[int] + RTLD_NOLOAD: ClassVar[int] + + errno: int + + def __init__( + self, + module_name: str = ..., + _version: int = ..., + _types: bytes = ..., + _globals: tuple[bytes | int, ...] = ..., + _struct_unions: tuple[tuple[bytes, ...], ...] = ..., + _enums: tuple[bytes, ...] = ..., + _typenames: tuple[bytes, ...] = ..., + _includes: tuple[FFI, ...] = ..., + ) -> None: ... + + @overload + def addressof(self, cdata: CData, /, *field_or_index: str | int) -> CData: ... + @overload + def addressof(self, library: Lib, name: str, /) -> CData: ... + + def alignof(self, cdecl: str | CType | CData, /) -> int: ... + + @overload + def callback( + self, + cdecl: str | CType, + python_callable: None = ..., + error: Any = ..., + onerror: Callable[[Exception, Any, Any], None] | None = ..., + ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def callback( + self, + cdecl: str | CType, + python_callable: Callable[..., _T], + error: Any = ..., + onerror: Callable[[Exception, Any, Any], None] | None = ..., + ) -> Callable[..., _T]: ... + + def cast(self, cdecl: str | CType, value: CData | int) -> CData: ... + def def_extern( + self, name: str = ..., error: Any = ..., onerror: Callable[[Exception, Any, types.TracebackType], Any] = ... + ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def dlclose(self, lib: Lib, /) -> None: ... + if sys.platform == "win32": + def dlopen(self, libpath: str | CData, flags: int = ..., /) -> Lib: ... + else: + def dlopen(self, libpath: str | CData | None = ..., flags: int = ..., /) -> Lib: ... + + @overload + def from_buffer(self, cdecl: ReadableBuffer, require_writable: Literal[False] = ...) -> CData: ... + @overload + def from_buffer(self, cdecl: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + @overload + def from_buffer(self, cdecl: str | CType, python_buffer: ReadableBuffer, require_writable: Literal[False] = ...) -> CData: ... + @overload + def from_buffer(self, cdecl: str | CType, python_buffer: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + + def from_handle(self, x: CData, /) -> Any: ... + + @overload + def gc(self, cdata: CData, destructor: Callable[[CData], Any], size: int = ...) -> CData: ... + @overload + def gc(self, cdata: CData, destructor: None, size: int = ...) -> None: ... + + def getctype(self, cdecl: str | CType, replace_with: str = ...) -> str: ... + if sys.platform == "win32": + def getwinerror(self, code: int = ...) -> tuple[int, str]: ... + + def init_once(self, func: Callable[[], Any], tag: Hashable) -> Any: ... + def integer_const(self, name: str) -> int: ... + def list_types(self) -> tuple[list[str], list[str], list[str]]: ... + def memmove(self, dest: CData | WriteableBuffer, src: CData | ReadableBuffer, n: int) -> None: ... + def new(self, cdecl: str | CType, init: Any = ...) -> CData: ... + + @overload + def new_allocator(self, alloc: None = ..., free: None = ..., should_clear_after_alloc: bool = ...) -> _Allocator: ... + @overload + def new_allocator( + self, alloc: Callable[[int], CData], free: None = ..., should_clear_after_alloc: bool = ... + ) -> _Allocator: ... + @overload + def new_allocator( + self, alloc: Callable[[int], CData], free: Callable[[CData], Any], should_clear_after_alloc: bool = ... + ) -> _Allocator: ... + + def new_handle(self, x: Any, /) -> CData: ... + def offsetof(self, cdecl: str | CType, field_or_index: str | int, /, *__fields_or_indexes: str | int) -> int: ... + def release(self, cdata: CData, /) -> None: ... + def sizeof(self, cdecl: str | CType | CData, /) -> int: ... + def string(self, cdata: CData, maxlen: int = -1) -> bytes | str: ... + def typeof(self, cdecl: str | CData, /) -> CType: ... + def unpack(self, cdata: CData, length: int) -> bytes | str | list[Any]: ... + +def alignof(cdecl: CType, /) -> int: ... +def callback( + cdecl: CType, + python_callable: Callable[..., _T], + error: Any = ..., + onerror: Callable[[Exception, Any, Any], None] | None = ..., + /, +) -> Callable[..., _T]: ... +def cast(cdecl: CType, value: _CDataBase, /) -> _CDataBase: ... +def complete_struct_or_union( + cdecl: CType, + fields: list[tuple[str, CType, int, int]], + ignored: Any, + total_size: int, + total_alignment: int, + sflags: int, + pack: int, + /, +) -> None: ... + +@overload +def from_buffer(cdecl: CType, python_buffer: ReadableBuffer, /, require_writable: Literal[False] = ...) -> _CDataBase: ... +@overload +def from_buffer(cdecl: CType, python_buffer: WriteableBuffer, /, require_writable: Literal[True]) -> _CDataBase: ... + +def from_handle(x: _CDataBase, /) -> Any: ... + +@overload +def gcp(cdata: _CDataBase, destructor: Callable[[_CDataBase], Any], size: int = ...) -> _CDataBase: ... +@overload +def gcp(cdata: _CDataBase, destructor: None, size: int = ...) -> None: ... + +def get_errno() -> int: ... +def getcname(cdecl: CType, replace_with: str, /) -> str: ... + +if sys.platform == "win32": + def getwinerror(code: int = ...) -> tuple[int, str]: ... + +if sys.platform == "win32": + def load_library(libpath: str | _CDataBase, flags: int = ..., /) -> CLibrary: ... + +else: + def load_library(libpath: str | _CDataBase | None = ..., flags: int = ..., /) -> CLibrary: ... + +def memmove(dest: _CDataBase | WriteableBuffer, src: _CDataBase | ReadableBuffer, n: int) -> None: ... +def new_array_type(cdecl: CType, length: int | None, /) -> CType: ... +def new_enum_type(name: str, enumerators: tuple[str, ...], enumvalues: tuple[Any, ...], basetype: CType, /) -> CType: ... +def new_function_type(args: tuple[CType, ...], result: CType, ellipsis: int, abi: int, /) -> CType: ... +def new_pointer_type(cdecl: CType, /) -> CType: ... +def new_primitive_type(name: str, /) -> CType: ... +def new_struct_type(name: str, /) -> CType: ... +def new_union_type(name: str, /) -> CType: ... +def new_void_type() -> CType: ... +def newp(cdecl: CType, init: Any = ..., /) -> _CDataBase: ... +def newp_handle(cdecl: CType, x: Any, /) -> _CDataBase: ... +def rawaddressof(cdecl: CType, cdata: _CDataBase, offset: int, /) -> _CDataBase: ... +def release(cdata: _CDataBase, /) -> None: ... +def set_errno(errno: int, /) -> None: ... +def sizeof(cdecl: CType | _CDataBase, /) -> int: ... +def string(cdata: _CDataBase, maxlen: int) -> bytes | str: ... +def typeof(cdata: _CDataBase, /) -> CType: ... +def typeoffsetof(cdecl: CType, fieldname: str | int, following: bool = ..., /) -> tuple[CType, int]: ... +def unpack(cdata: _CDataBase, length: int) -> bytes | str | list[Any]: ... diff --git a/stubs/cffi/cffi/__init__.pyi b/stubs/cffi/cffi/__init__.pyi new file mode 100644 index 000000000000..b549eb5b1ea9 --- /dev/null +++ b/stubs/cffi/cffi/__init__.pyi @@ -0,0 +1,15 @@ +from typing import Final + +from .api import FFI as FFI +from .error import ( + CDefError as CDefError, + FFIError as FFIError, + PkgConfigError as PkgConfigError, + VerificationError as VerificationError, + VerificationMissing as VerificationMissing, +) + +__all__ = ["FFI", "VerificationError", "VerificationMissing", "CDefError", "FFIError"] +__version__: Final[str] +__version_info__: Final[tuple[int, int, int]] +__version_verifier_modules__: Final[str] diff --git a/stubs/cffi/cffi/api.pyi b/stubs/cffi/cffi/api.pyi new file mode 100644 index 000000000000..05ea2daecbfc --- /dev/null +++ b/stubs/cffi/cffi/api.pyi @@ -0,0 +1,111 @@ +import sys +import types +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable, Hashable +from typing import Any, Literal, TypeAlias, TypeVar, overload + +import _cffi_backend +from setuptools._distutils.extension import Extension + +_T = TypeVar("_T") + +basestring: TypeAlias = str # noqa: Y042 + +class FFI: + CData: TypeAlias = _cffi_backend._CDataBase + CType: TypeAlias = _cffi_backend.CType + buffer: TypeAlias = _cffi_backend.buffer # noqa: Y042 + + BVoidP: CType + BCharA: CType + NULL: CData + errno: int + + def __init__(self, backend: types.ModuleType | None = None) -> None: ... + def cdef(self, csource: str, override: bool = False, packed: bool = False, pack: int | None = None) -> None: ... + def embedding_api(self, csource: str, packed: bool = False, pack: bool | int | None = None) -> None: ... + + if sys.platform == "win32": + def dlopen(self, name: str, flags: int = ...) -> _cffi_backend.Lib: ... + else: + def dlopen(self, name: str | None, flags: int = 0) -> _cffi_backend.Lib: ... + + def dlclose(self, lib: _cffi_backend.Lib) -> None: ... + def typeof(self, cdecl: str | CData | types.BuiltinFunctionType | types.FunctionType) -> CType: ... + def sizeof(self, cdecl: str | CData) -> int: ... + def alignof(self, cdecl: str | CData) -> int: ... + def offsetof(self, cdecl: str | CData, *fields_or_indexes: str | int) -> int: ... + + # The acceptable types of `init` depend on the value of `cdecl` only known at runtime, and + # therefore unknown to the type checker. + def new(self, cdecl: str | CType, init: Any = None) -> CData: ... + def new_allocator( + self, + alloc: Callable[[int], CData] | None = None, + free: Callable[[CData], Any] | None = None, + should_clear_after_alloc: bool = True, + ) -> _cffi_backend._Allocator: ... + def cast(self, cdecl: str | CType, source: CData | float) -> CData: ... + def string(self, cdata: CData, maxlen: int = -1) -> bytes | str: ... + def unpack(self, cdata: CData, length: int) -> bytes | str | list[Any]: ... + + @overload + def from_buffer(self, cdecl: ReadableBuffer, require_writable: Literal[False] = False) -> CData: ... + @overload + def from_buffer(self, cdecl: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + @overload + def from_buffer( + self, cdecl: str | CType, python_buffer: ReadableBuffer, require_writable: Literal[False] = False + ) -> CData: ... + @overload + def from_buffer(self, cdecl: str | CType, python_buffer: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + + def memmove(self, dest: CData | WriteableBuffer, src: CData | ReadableBuffer, n: int) -> None: ... + + @overload + def callback( + self, + cdecl: str | CType, + python_callable: None = None, + error: Any = None, + onerror: Callable[[Exception, Any, Any], None] | None = None, + ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def callback( + self, + cdecl: str | CType, + python_callable: Callable[..., _T], + error: Any = None, + onerror: Callable[[Exception, Any, Any], None] | None = None, + ) -> Callable[..., _T]: ... + + def getctype(self, cdecl: str | CType, replace_with: str = "") -> str: ... + + @overload + def gc(self, cdata: CData, destructor: Callable[[CData], Any], size: int = 0) -> CData: ... + @overload + def gc(self, cdata: CData, destructor: None, size: int = 0) -> None: ... + + def verify(self, source: str = "", tmpdir: str | None = None, **kwargs: Any) -> _cffi_backend.Lib: ... + # Technically exists on all OSs, but crashes on all but Windows. So we hide it in stubs + if sys.platform == "win32": + def getwinerror(self, code: int = -1) -> tuple[int, str] | None: ... + + def addressof(self, cdata: CData, *fields_or_indexes: str | int) -> CData: ... + def include(self, ffi_to_include: FFI) -> None: ... + def new_handle(self, x: Any) -> CData: ... + def from_handle(self, x: CData) -> Any: ... + def release(self, x: CData) -> None: ... + def set_unicode(self, enabled_flag: bool) -> None: ... + def set_source(self, module_name: str, source: str | None, source_extension: str = ".c", **kwds: Any) -> None: ... + def set_source_pkgconfig( + self, module_name: str, pkgconfig_libs: list[str], source: str, source_extension: str = ".c", **kwds: Any + ) -> None: ... + def distutils_extension(self, tmpdir: str = "build", verbose: bool = True) -> Extension: ... + def emit_c_code(self, filename: str) -> None: ... + def emit_python_code(self, filename: str) -> None: ... + def compile(self, tmpdir: str = ".", verbose: int = 0, target: str | None = None, debug: bool | None = None) -> str: ... + def init_once(self, func: Callable[[], Any], tag: Hashable) -> Any: ... + def embedding_init_code(self, pysource: str) -> None: ... + def def_extern(self, *args: Any, **kwds: Any) -> None: ... + def list_types(self) -> tuple[list[str], list[str], list[str]]: ... diff --git a/stubs/cffi/cffi/backend_ctypes.pyi b/stubs/cffi/cffi/backend_ctypes.pyi new file mode 100644 index 000000000000..04c0e8a8ffbe --- /dev/null +++ b/stubs/cffi/cffi/backend_ctypes.pyi @@ -0,0 +1,85 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +unicode = str +long = int +xrange = range +bytechr: Callable[[float], bytes] + +class CTypesType(type): ... + +class CTypesData: + __slots__ = ["__weakref__"] + __metaclass__: Incomplete + __name__: str + def __init__(self, *args) -> None: ... + def __iter__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self) -> int: ... + def __repr__(self, c_name: str | None = None): ... + +class CTypesGenericPrimitive(CTypesData): + __slots__: list[str] = [] + def __hash__(self) -> int: ... + +class CTypesGenericArray(CTypesData): + __slots__: list[str] = [] + def __iter__(self): ... + +class CTypesGenericPtr(CTypesData): + __slots__ = ["_address", "_as_ctype_ptr"] + kind: str + def __nonzero__(self) -> bool: ... + def __bool__(self) -> bool: ... + +class CTypesBaseStructOrUnion(CTypesData): + __slots__ = ["_blob"] + +class CTypesBackend: + PRIMITIVE_TYPES: Incomplete + RTLD_LAZY: int + RTLD_NOW: int + RTLD_GLOBAL: Incomplete + RTLD_LOCAL: Incomplete + def __init__(self) -> None: ... + ffi: Incomplete + def set_ffi(self, ffi) -> None: ... + def load_library(self, path, flags: int = 0): ... + def new_void_type(self): ... + def new_primitive_type(self, name): ... + def new_pointer_type(self, BItem): ... + def new_array_type(self, CTypesPtr, length): ... + def new_struct_type(self, name): ... + def new_union_type(self, name): ... + def complete_struct_or_union( + self, CTypesStructOrUnion, fields, tp, totalsize: int = -1, totalalignment: int = -1, sflags: int = 0, pack: int = 0 + ): ... + def new_function_type(self, BArgs, BResult, has_varargs): ... + def new_enum_type(self, name, enumerators, enumvalues, CTypesInt): ... + def get_errno(self): ... + def set_errno(self, value) -> None: ... + def string(self, b, maxlen: int = -1): ... + def buffer(self, bptr, size: int = -1) -> None: ... + def sizeof(self, cdata_or_BType) -> int: ... + def alignof(self, BType) -> int: ... + def newp(self, BType, source): ... + def cast(self, BType, source): ... + def callback(self, BType, source, error, onerror): ... + def gcp(self, cdata, destructor, size: int = 0): ... + typeof: Incomplete + def getcname(self, BType, replace_with): ... + def typeoffsetof(self, BType, fieldname, num: int = 0): ... + def rawaddressof(self, BTypePtr, cdata, offset=None): ... + +class CTypesLibrary: + backend: Incomplete + cdll: Incomplete + def __init__(self, backend, cdll) -> None: ... + def load_function(self, BType, name): ... + def read_variable(self, BType, name): ... + def write_variable(self, BType, name, value) -> None: ... diff --git a/stubs/cffi/cffi/cffi_opcode.pyi b/stubs/cffi/cffi/cffi_opcode.pyi new file mode 100644 index 000000000000..a992eb339797 --- /dev/null +++ b/stubs/cffi/cffi/cffi_opcode.pyi @@ -0,0 +1,92 @@ +from typing import Final + +class CffiOp: + op: int | None + arg: str | None + def __init__(self, op: int | None, arg: str | None) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_bytes(self) -> str: ... + +def format_four_bytes(num: int) -> str: ... + +OP_PRIMITIVE: Final = 1 +OP_POINTER: Final = 3 +OP_ARRAY: Final = 5 +OP_OPEN_ARRAY: Final = 7 +OP_STRUCT_UNION: Final = 9 +OP_ENUM: Final = 11 +OP_FUNCTION: Final = 13 +OP_FUNCTION_END: Final = 15 +OP_NOOP: Final = 17 +OP_BITFIELD: Final = 19 +OP_TYPENAME: Final = 21 +OP_CPYTHON_BLTN_V: Final = 23 +OP_CPYTHON_BLTN_N: Final = 25 +OP_CPYTHON_BLTN_O: Final = 27 +OP_CONSTANT: Final = 29 +OP_CONSTANT_INT: Final = 31 +OP_GLOBAL_VAR: Final = 33 +OP_DLOPEN_FUNC: Final = 35 +OP_DLOPEN_CONST: Final = 37 +OP_GLOBAL_VAR_F: Final = 39 +OP_EXTERN_PYTHON: Final = 41 +PRIM_VOID: Final = 0 +PRIM_BOOL: Final = 1 +PRIM_CHAR: Final = 2 +PRIM_SCHAR: Final = 3 +PRIM_UCHAR: Final = 4 +PRIM_SHORT: Final = 5 +PRIM_USHORT: Final = 6 +PRIM_INT: Final = 7 +PRIM_UINT: Final = 8 +PRIM_LONG: Final = 9 +PRIM_ULONG: Final = 10 +PRIM_LONGLONG: Final = 11 +PRIM_ULONGLONG: Final = 12 +PRIM_FLOAT: Final = 13 +PRIM_DOUBLE: Final = 14 +PRIM_LONGDOUBLE: Final = 15 +PRIM_WCHAR: Final = 16 +PRIM_INT8: Final = 17 +PRIM_UINT8: Final = 18 +PRIM_INT16: Final = 19 +PRIM_UINT16: Final = 20 +PRIM_INT32: Final = 21 +PRIM_UINT32: Final = 22 +PRIM_INT64: Final = 23 +PRIM_UINT64: Final = 24 +PRIM_INTPTR: Final = 25 +PRIM_UINTPTR: Final = 26 +PRIM_PTRDIFF: Final = 27 +PRIM_SIZE: Final = 28 +PRIM_SSIZE: Final = 29 +PRIM_INT_LEAST8: Final = 30 +PRIM_UINT_LEAST8: Final = 31 +PRIM_INT_LEAST16: Final = 32 +PRIM_UINT_LEAST16: Final = 33 +PRIM_INT_LEAST32: Final = 34 +PRIM_UINT_LEAST32: Final = 35 +PRIM_INT_LEAST64: Final = 36 +PRIM_UINT_LEAST64: Final = 37 +PRIM_INT_FAST8: Final = 38 +PRIM_UINT_FAST8: Final = 39 +PRIM_INT_FAST16: Final = 40 +PRIM_UINT_FAST16: Final = 41 +PRIM_INT_FAST32: Final = 42 +PRIM_UINT_FAST32: Final = 43 +PRIM_INT_FAST64: Final = 44 +PRIM_UINT_FAST64: Final = 45 +PRIM_INTMAX: Final = 46 +PRIM_UINTMAX: Final = 47 +PRIM_FLOATCOMPLEX: Final = 48 +PRIM_DOUBLECOMPLEX: Final = 49 +PRIM_CHAR16: Final = 50 +PRIM_CHAR32: Final = 51 +PRIMITIVE_TO_INDEX: Final[dict[str, int]] +F_UNION: Final = 1 +F_CHECK_FIELDS: Final = 2 +F_PACKED: Final = 4 +F_EXTERNAL: Final = 8 +F_OPAQUE: Final = 16 +G_FLAGS: Final[dict[bytes, bytes]] +CLASS_NAME: Final[dict[int, str]] diff --git a/stubs/cffi/cffi/commontypes.pyi b/stubs/cffi/cffi/commontypes.pyi new file mode 100644 index 000000000000..fe9e35ee52b6 --- /dev/null +++ b/stubs/cffi/cffi/commontypes.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +COMMON_TYPES: Incomplete + +def resolve_common_type(parser, commontype): ... +def win_common_types(): ... diff --git a/stubs/cffi/cffi/cparser.pyi b/stubs/cffi/cffi/cparser.pyi new file mode 100644 index 000000000000..a42b2ddc0406 --- /dev/null +++ b/stubs/cffi/cffi/cparser.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +lock: Incomplete +CDEF_SOURCE_STRING: str + +class Parser: + def __init__(self) -> None: ... + def convert_pycparser_error(self, e, csource) -> None: ... + def parse(self, csource, override: bool = False, packed: bool = False, pack=None, dllexport: bool = False) -> None: ... + def parse_type(self, cdecl): ... + def parse_type_and_quals(self, cdecl): ... + def include(self, other) -> None: ... diff --git a/stubs/cffi/cffi/error.pyi b/stubs/cffi/cffi/error.pyi new file mode 100644 index 000000000000..a71f17e5d049 --- /dev/null +++ b/stubs/cffi/cffi/error.pyi @@ -0,0 +1,14 @@ +class FFIError(Exception): + __module__: str + +class CDefError(Exception): + __module__: str + +class VerificationError(Exception): + __module__: str + +class VerificationMissing(Exception): + __module__: str + +class PkgConfigError(Exception): + __module__: str diff --git a/stubs/cffi/cffi/ffiplatform.pyi b/stubs/cffi/cffi/ffiplatform.pyi new file mode 100644 index 000000000000..f7fe46729b32 --- /dev/null +++ b/stubs/cffi/cffi/ffiplatform.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrOrBytesPath +from typing import Any, Final + +LIST_OF_FILE_NAMES: Final[list[str]] + +def get_extension(srcfilename, modname, sources=(), **kwds): ... +def compile(tmpdir, ext, compiler_verbose: int = 0, debug=None): ... +def maybe_relative_path(path: StrOrBytesPath) -> StrOrBytesPath | str: ... + +int_or_long = int + +def flatten(x: int | str | list[Any] | tuple[Any] | dict[Any, Any]) -> str: ... diff --git a/stubs/cffi/cffi/gen_src.pyi b/stubs/cffi/cffi/gen_src.pyi new file mode 100644 index 000000000000..bac2cd9f246d --- /dev/null +++ b/stubs/cffi/cffi/gen_src.pyi @@ -0,0 +1 @@ +# Entry point for `python -m cffi.gen_src`; the implementation lives in the private module `cffi._cffi_gen_src` diff --git a/stubs/cffi/cffi/lock.pyi b/stubs/cffi/cffi/lock.pyi new file mode 100644 index 000000000000..fc8393af7412 --- /dev/null +++ b/stubs/cffi/cffi/lock.pyi @@ -0,0 +1 @@ +from _thread import allocate_lock as allocate_lock diff --git a/stubs/cffi/cffi/model.pyi b/stubs/cffi/cffi/model.pyi new file mode 100644 index 000000000000..48a03c2dcea9 --- /dev/null +++ b/stubs/cffi/cffi/model.pyi @@ -0,0 +1,164 @@ +from _thread import LockType +from _typeshed import Incomplete +from collections.abc import Generator +from typing import Final + +from .error import CDefError as CDefError, VerificationError as VerificationError, VerificationMissing as VerificationMissing +from .lock import allocate_lock as allocate_lock + +Q_CONST: Final = 1 +Q_RESTRICT: Final = 2 +Q_VOLATILE: Final = 4 + +def qualify(quals: int, replace_with: str) -> str: ... + +class BaseTypeByIdentity: + is_array_type: bool + is_raw_function: bool + def get_c_name(self, replace_with: str = "", context: str = "a C file", quals: int = 0) -> str: ... + def has_c_name(self) -> bool: ... + def is_integer_type(self) -> bool: ... + def get_cached_btype(self, ffi, finishlist, can_delay: bool = False): ... + +class BaseType(BaseTypeByIdentity): + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class VoidType(BaseType): + c_name_with_marker: str + def __init__(self) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + +void_type: VoidType + +class BasePrimitiveType(BaseType): + def is_complex_type(self) -> bool: ... + +class PrimitiveType(BasePrimitiveType): + ALL_PRIMITIVE_TYPES: dict[str, str] + name: str + c_name_with_marker: str + def __init__(self, name: str) -> None: ... + def is_char_type(self) -> bool: ... + def is_integer_type(self) -> bool: ... + def is_float_type(self) -> bool: ... + def is_complex_type(self) -> bool: ... + def build_backend_type(self, ffi, finishlist): ... + +class UnknownIntegerType(BasePrimitiveType): + name: str + c_name_with_marker: str + def __init__(self, name: str) -> None: ... + def is_integer_type(self) -> bool: ... + def build_backend_type(self, ffi, finishlist) -> None: ... + +class UnknownFloatType(BasePrimitiveType): + name: str + c_name_with_marker: str + def __init__(self, name: str) -> None: ... + def build_backend_type(self, ffi, finishlist) -> None: ... + +class BaseFunctionType(BaseType): + args: Incomplete + result: Incomplete + ellipsis: Incomplete + abi: Incomplete + c_name_with_marker: str + def __init__(self, args, result, ellipsis, abi=None) -> None: ... + +class RawFunctionType(BaseFunctionType): + is_raw_function: bool + def build_backend_type(self, ffi, finishlist) -> None: ... + def as_function_pointer(self) -> FunctionPtrType: ... + +class FunctionPtrType(BaseFunctionType): + def build_backend_type(self, ffi, finishlist): ... + def as_raw_function(self) -> RawFunctionType: ... + +class PointerType(BaseType): + totype: BaseTypeByIdentity + quals: int + c_name_with_marker: str + def __init__(self, totype: BaseTypeByIdentity, quals: int = 0) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + +voidp_type: PointerType + +def ConstPointerType(totype: BaseTypeByIdentity) -> PointerType: ... + +const_voidp_type: PointerType + +class NamedPointerType(PointerType): + name: str + c_name_with_marker: str + def __init__(self, totype: BaseTypeByIdentity, name: str, quals: int = 0) -> None: ... + +class ArrayType(BaseType): + is_array_type: bool + item: Incomplete + length: str | None + c_name_with_marker: str + def __init__(self, item, length: str | None) -> None: ... + def length_is_unknown(self) -> bool: ... + def resolve_length(self, newlength: str | None) -> ArrayType: ... + def build_backend_type(self, ffi, finishlist): ... + +char_array_type: ArrayType + +class StructOrUnionOrEnum(BaseTypeByIdentity): + forcename: str | None + c_name_with_marker: str + def build_c_name_with_marker(self) -> None: ... + def force_the_name(self, forcename: str | None) -> None: ... + def get_official_name(self) -> str: ... + +class StructOrUnion(StructOrUnionOrEnum): + fixedlayout: Incomplete + completed: int + partial: bool + packed: int + name: Incomplete + fldnames: Incomplete + fldtypes: Incomplete + fldbitsize: Incomplete + fldquals: Incomplete + def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None) -> None: ... + def anonymous_struct_fields(self) -> Generator[StructOrUnion]: ... + def enumfields(self, expand_anonymous_struct_union: bool = True) -> Generator[Incomplete]: ... + def force_flatten(self) -> None: ... + def get_cached_btype(self, ffi, finishlist, can_delay: bool = False): ... + def finish_backend_type(self, ffi, finishlist) -> None: ... + def check_not_partial(self) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + +class StructType(StructOrUnion): + kind: str + +class UnionType(StructOrUnion): + kind: str + +class EnumType(StructOrUnionOrEnum): + kind: str + partial: bool + partial_resolved: bool + name: Incomplete + enumerators: Incomplete + enumvalues: Incomplete + baseinttype: Incomplete + def __init__(self, name, enumerators, enumvalues, baseinttype=None) -> None: ... + forcename: str | None + def force_the_name(self, forcename: str | None) -> None: ... + def check_not_partial(self) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + def build_baseinttype(self, ffi, finishlist): ... + +def unknown_type(name: str, structname: str | None = None) -> StructType: ... +def unknown_ptr_type(name: str, structname: str | None = None) -> NamedPointerType: ... + +global_lock: LockType + +def get_typecache(backend): ... +def global_cache(srctype, ffi, funcname, *args, **kwds): ... +def pointer_cache(ffi, BType): ... +def attach_exception_info(e, name: str) -> None: ... diff --git a/stubs/cffi/cffi/pkgconfig.pyi b/stubs/cffi/cffi/pkgconfig.pyi new file mode 100644 index 000000000000..510961c2b349 --- /dev/null +++ b/stubs/cffi/cffi/pkgconfig.pyi @@ -0,0 +1,5 @@ +from collections.abc import Sequence + +def merge_flags(cfg1: dict[str, list[str]], cfg2: dict[str, list[str]]) -> dict[str, list[str]]: ... +def call(libname: str, flag: str, encoding: str = "utf-8") -> str: ... +def flags_from_pkgconfig(libs: Sequence[str]) -> dict[str, list[str]]: ... diff --git a/stubs/cffi/cffi/recompiler.pyi b/stubs/cffi/cffi/recompiler.pyi new file mode 100644 index 000000000000..bb73ccf88479 --- /dev/null +++ b/stubs/cffi/cffi/recompiler.pyi @@ -0,0 +1,97 @@ +import io +from _typeshed import Incomplete, StrPath +from typing import Final, TypeAlias + +from .cffi_opcode import * +from .error import VerificationError as VerificationError + +VERSION_BASE: Final = 9729 +VERSION_EMBEDDED: Final = 9985 +VERSION_CHAR16CHAR32: Final = 10241 +FREE_THREADED_BUILD: Final[int | None] +USE_LIMITED_API: Final[bool] + +class GlobalExpr: + name: Incomplete + address: Incomplete + type_op: Incomplete + size: Incomplete + check_value: Incomplete + def __init__(self, name, address, type_op, size: int = 0, check_value: int = 0) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class FieldExpr: + name: Incomplete + field_offset: Incomplete + field_size: Incomplete + fbitsize: Incomplete + field_type_op: Incomplete + def __init__(self, name, field_offset, field_size, fbitsize, field_type_op) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> None: ... + def as_field_python_expr(self) -> str: ... + +class StructUnionExpr: + name: Incomplete + type_index: Incomplete + flags: Incomplete + size: Incomplete + alignment: Incomplete + comment: Incomplete + first_field_index: Incomplete + c_fields: Incomplete + def __init__(self, name, type_index, flags, size, alignment, comment, first_field_index, c_fields) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class EnumExpr: + name: Incomplete + type_index: Incomplete + size: Incomplete + signed: Incomplete + allenums: Incomplete + def __init__(self, name, type_index, size, signed, allenums) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class TypenameExpr: + name: Incomplete + type_index: Incomplete + def __init__(self, name, type_index) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class Recompiler: + ffi: Incomplete + module_name: str + target_is_python: bool + def __init__(self, ffi, module_name: str, target_is_python: bool = False) -> None: ... + def needs_version(self, ver: int) -> None: ... + cffi_types: list[Incomplete] + def collect_type_table(self) -> None: ... + ALL_STEPS: list[str] + def collect_step_tables(self) -> None: ... + def write_source_to_f(self, f, preamble: str) -> None: ... + def write_c_source_to_f(self, f, preamble: str) -> None: ... + def write_py_source_to_f(self, f) -> None: ... + +NativeIO: TypeAlias = io.StringIO + +def make_c_source(ffi, module_name: str, preamble: str, target_c_file, verbose: bool = False): ... +def make_py_source(ffi, module_name: str, target_py_file, verbose: bool = False): ... +def recompile( + ffi, + module_name: str | bytes, + preamble: str | None, + tmpdir: str = ".", + call_c_compiler: bool = True, + c_file=None, + source_extension: str = ".c", + extradir: StrPath | None = None, + compiler_verbose: int = 1, + target: str | None = None, + debug: int | None = None, + uses_ffiplatform: bool = True, + **kwds, +): ... diff --git a/stubs/cffi/cffi/setuptools_ext.pyi b/stubs/cffi/cffi/setuptools_ext.pyi new file mode 100644 index 000000000000..beb58858964d --- /dev/null +++ b/stubs/cffi/cffi/setuptools_ext.pyi @@ -0,0 +1,6 @@ +basestring = str + +def error(msg) -> None: ... +def execfile(filename, glob) -> None: ... +def add_cffi_module(dist, mod_spec) -> None: ... +def cffi_modules(dist, attr, value) -> None: ... diff --git a/stubs/cffi/cffi/vengine_cpy.pyi b/stubs/cffi/cffi/vengine_cpy.pyi new file mode 100644 index 000000000000..e9cd0afa70c0 --- /dev/null +++ b/stubs/cffi/cffi/vengine_cpy.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class VCPythonEngine: + verifier: Incomplete + ffi: Incomplete + def __init__(self, verifier) -> None: ... + def patch_extension_kwds(self, kwds) -> None: ... + def find_module(self, module_name, path, so_suffixes): ... + def collect_types(self) -> None: ... + def write_source_to_f(self) -> None: ... + def load_library(self, flags=None): ... + +cffimod_header: str diff --git a/stubs/cffi/cffi/vengine_gen.pyi b/stubs/cffi/cffi/vengine_gen.pyi new file mode 100644 index 000000000000..f77bf20fc0f9 --- /dev/null +++ b/stubs/cffi/cffi/vengine_gen.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class VGenericEngine: + verifier: Incomplete + ffi: Incomplete + export_symbols: Incomplete + def __init__(self, verifier) -> None: ... + def patch_extension_kwds(self, kwds) -> None: ... + def find_module(self, module_name, path, so_suffixes): ... + def collect_types(self) -> None: ... + def write_source_to_f(self) -> None: ... + def load_library(self, flags: int = 0): ... + +cffimod_header: str diff --git a/stubs/cffi/cffi/verifier.pyi b/stubs/cffi/cffi/verifier.pyi new file mode 100644 index 000000000000..5c8b8d733fbc --- /dev/null +++ b/stubs/cffi/cffi/verifier.pyi @@ -0,0 +1,42 @@ +import io +import os +from _typeshed import Incomplete, StrPath +from typing import AnyStr, TypeAlias + +NativeIO: TypeAlias = io.StringIO + +class Verifier: + ffi: Incomplete + preamble: Incomplete + flags: int | None + kwds: dict[str, list[str] | tuple[str]] + tmpdir: StrPath + sourcefilename: str + modulefilename: str + ext_package: str | None + def __init__( + self, + ffi, + preamble, + tmpdir: StrPath | None = None, + modulename: str | None = None, + ext_package: str | None = None, + tag: str = "", + force_generic_engine: bool = False, + source_extension: str = ".c", + flags: int | None = None, + relative_to: os.PathLike[AnyStr] | None = None, + **kwds: list[str] | tuple[str], + ) -> None: ... + def write_source(self, file=None) -> None: ... + def compile_module(self) -> None: ... + def load_library(self): ... + def get_module_name(self) -> str: ... + def get_extension(self): ... + def generates_python_module(self) -> bool: ... + def make_relative_to( + self, kwds: dict[str, list[str] | tuple[str]], relative_to: os.PathLike[AnyStr] | None + ) -> dict[str, list[str] | tuple[str]]: ... + +def set_tmpdir(dirname: StrPath) -> None: ... +def cleanup_tmpdir(tmpdir: StrPath | None = None, keep_so: bool = False) -> None: ... diff --git a/stubs/channels/@tests/django_settings.py b/stubs/channels/@tests/django_settings.py new file mode 100644 index 000000000000..2be16834be19 --- /dev/null +++ b/stubs/channels/@tests/django_settings.py @@ -0,0 +1,12 @@ +SECRET_KEY = "1" + +INSTALLED_APPS = ( + "django.contrib.contenttypes", + "django.contrib.sites", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.admin.apps.SimpleAdminConfig", + "django.contrib.staticfiles", + "django.contrib.auth", + "channels", +) diff --git a/stubs/channels/@tests/stubtest_allowlist.txt b/stubs/channels/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..91fccf79e4ce --- /dev/null +++ b/stubs/channels/@tests/stubtest_allowlist.txt @@ -0,0 +1,20 @@ +# channels.auth.UserLazyObject metaclass is mismatch +channels.auth.UserLazyObject + +# these one need to be exclude due to mypy error: * is not present at runtime +channels.auth.UserLazyObject.DoesNotExist +channels.auth.UserLazyObject.MultipleObjectsReturned +channels.auth.UserLazyObject.NotUpdated +channels.auth.UserLazyObject@AnnotatedWith + +# "is not a function", because it's wrapped in database_sync_to_async, +# which makes it a class instance. +channels.consumer.SyncConsumer.dispatch + +# database_sync_to_async is implemented as a class instance but stubbed as a function +# for better type inference when used as decorator/function +channels.db.database_sync_to_async + +# Set to None on class, but initialized to non-None value in __init__ +channels.generic.websocket.WebsocketConsumer.groups +channels.generic.websocket.AsyncWebsocketConsumer.groups diff --git a/stubs/channels/METADATA.toml b/stubs/channels/METADATA.toml new file mode 100644 index 000000000000..1eed45be8e4d --- /dev/null +++ b/stubs/channels/METADATA.toml @@ -0,0 +1,8 @@ +version = "4.3.*" +upstream-repository = "https://github.com/django/channels" +dependencies = ["django-stubs>=6.0.3", "asgiref"] + +[tool.stubtest] +mypy-plugins = ['mypy_django_plugin.main'] +mypy-plugins-config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}} +stubtest-dependencies = ["daphne"] diff --git a/stubs/channels/channels/__init__.pyi b/stubs/channels/channels/__init__.pyi new file mode 100644 index 000000000000..561199954632 --- /dev/null +++ b/stubs/channels/channels/__init__.pyi @@ -0,0 +1,4 @@ +from typing import Final + +__version__: Final[str] +DEFAULT_CHANNEL_LAYER: Final[str] diff --git a/stubs/channels/channels/apps.pyi b/stubs/channels/channels/apps.pyi new file mode 100644 index 000000000000..ad15a21b6961 --- /dev/null +++ b/stubs/channels/channels/apps.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from django.apps import AppConfig + +class ChannelsConfig(AppConfig): + name: Final = "channels" + verbose_name: str = "Channels" diff --git a/stubs/channels/channels/auth.pyi b/stubs/channels/channels/auth.pyi new file mode 100644 index 000000000000..8c2361d3bbdd --- /dev/null +++ b/stubs/channels/channels/auth.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable +from channels.middleware import BaseMiddleware +from django.contrib.auth.backends import BaseBackend +from django.contrib.auth.base_user import AbstractBaseUser +from django.contrib.auth.models import AnonymousUser +from django.utils.functional import LazyObject + +from .consumer import _ChannelScope +from .utils import _ChannelApplication + +async def get_user(scope: _ChannelScope) -> AbstractBaseUser | AnonymousUser: ... +async def login(scope: _ChannelScope, user: AbstractBaseUser, backend: BaseBackend | None = None) -> None: ... +async def logout(scope: _ChannelScope) -> None: ... + +# Inherits AbstractBaseUser to improve autocomplete and show this is a lazy proxy for a user. +# At runtime, it's just a LazyObject that wraps the actual user instance. +class UserLazyObject(AbstractBaseUser, LazyObject[Incomplete]): ... + +class AuthMiddleware(BaseMiddleware): + def populate_scope(self, scope: _ChannelScope) -> None: ... + async def resolve_scope(self, scope: _ChannelScope) -> None: ... + async def __call__( + self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable + ) -> _ChannelApplication: ... + +def AuthMiddlewareStack(inner: _ChannelApplication) -> _ChannelApplication: ... diff --git a/stubs/channels/channels/consumer.pyi b/stubs/channels/channels/consumer.pyi new file mode 100644 index 000000000000..9f6f4725c00a --- /dev/null +++ b/stubs/channels/channels/consumer.pyi @@ -0,0 +1,75 @@ +from _typeshed import Incomplete +from collections.abc import Awaitable +from typing import Any, ClassVar, Protocol, TypedDict, type_check_only + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable, Scope, WebSocketScope +from channels.auth import UserLazyObject +from channels.layers import BaseChannelLayer +from django.contrib.sessions.backends.base import SessionBase +from django.utils.functional import LazyObject + +# _LazySession is a LazyObject that wraps a SessionBase instance. +# We subclass both for type checking purposes to expose SessionBase attributes, +# and suppress mypy's "misc" error with `# type: ignore[misc]`. +@type_check_only +class _LazySession(SessionBase, LazyObject[Incomplete]): # type: ignore[misc] + _wrapped: SessionBase + +@type_check_only +class _URLRoute(TypedDict): + # Values extracted from Django's URLPattern matching, + # passed through ASGI scope routing. + # `args` and `kwargs` are the result of pattern matching against the URL path. + args: tuple[Any, ...] + kwargs: dict[str, Any] + +# Channel Scope definition +@type_check_only +class _ChannelScope(WebSocketScope, total=False): + # Channels specific + channel: str + url_route: _URLRoute + path_remaining: str + + # Auth specific + cookies: dict[str, str] + session: _LazySession + user: UserLazyObject | None + +# Accepts any ASGI message dict with a required "type" key (str), +# but allows additional arbitrary keys for flexibility. +def get_handler_name(message: dict[str, Any]) -> str: ... + +@type_check_only +class _ASGIApplicationProtocol(Protocol): + consumer_class: AsyncConsumer + + # Accepts any initialization kwargs passed to the consumer class. + # Typed as `Any` to allow flexibility in subclass-specific arguments. + consumer_initkwargs: Any + + def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> Awaitable[None]: ... + +class AsyncConsumer: + channel_layer_alias: ClassVar[str] + + scope: _ChannelScope + channel_layer: BaseChannelLayer + channel_name: str + channel_receive: ASGIReceiveCallable + base_send: ASGISendCallable + + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... + async def dispatch(self, message: dict[str, Any]) -> None: ... + async def send(self, message: dict[str, Any]) -> None: ... + + # initkwargs will be used to instantiate the consumer instance. + @classmethod + def as_asgi(cls, **initkwargs: Any) -> _ASGIApplicationProtocol: ... + +class SyncConsumer(AsyncConsumer): + + # Since we're overriding asynchronous methods with synchronous ones, + # we need to use `# type: ignore[override]` to suppress mypy errors. + async def dispatch(self, message: dict[str, Any]) -> None: ... # type: ignore[override] + def send(self, message: dict[str, Any]) -> None: ... # type: ignore[override] diff --git a/stubs/channels/channels/db.pyi b/stubs/channels/channels/db.pyi new file mode 100644 index 000000000000..913b89ca24ea --- /dev/null +++ b/stubs/channels/channels/db.pyi @@ -0,0 +1,31 @@ +import asyncio +from _typeshed import OptExcInfo +from asyncio import BaseEventLoop +from collections.abc import Callable, Coroutine +from concurrent.futures import ThreadPoolExecutor +from typing import Any, ParamSpec, TypeVar + +from asgiref.sync import SyncToAsync + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +class DatabaseSyncToAsync(SyncToAsync[_P, _R]): + def thread_handler( + self, + loop: BaseEventLoop, + exc_info: OptExcInfo, + task_context: list[asyncio.Task[Any]] | None, + func: Callable[_P, _R], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _R: ... + +# We define `database_sync_to_async` as a function instead of assigning +# `DatabaseSyncToAsync(...)` directly, to preserve both decorator and +# higher-order function behavior with correct type hints. +# A direct assignment would result in incorrect type inference for the wrapped function. +def database_sync_to_async( + func: Callable[_P, _R], thread_sensitive: bool = True, executor: ThreadPoolExecutor | None = None +) -> Callable[_P, Coroutine[Any, Any, _R]]: ... +async def aclose_old_connections() -> None: ... diff --git a/stubs/channels/channels/exceptions.pyi b/stubs/channels/channels/exceptions.pyi new file mode 100644 index 000000000000..eaba1dfaee14 --- /dev/null +++ b/stubs/channels/channels/exceptions.pyi @@ -0,0 +1,8 @@ +class RequestAborted(Exception): ... +class RequestTimeout(RequestAborted): ... +class InvalidChannelLayerError(ValueError): ... +class AcceptConnection(Exception): ... +class DenyConnection(Exception): ... +class ChannelFull(Exception): ... +class MessageTooLarge(Exception): ... +class StopConsumer(Exception): ... diff --git a/stubs/requests/requests/packages/urllib3/contrib/__init__.pyi b/stubs/channels/channels/generic/__init__.pyi similarity index 100% rename from stubs/requests/requests/packages/urllib3/contrib/__init__.pyi rename to stubs/channels/channels/generic/__init__.pyi diff --git a/stubs/channels/channels/generic/http.pyi b/stubs/channels/channels/generic/http.pyi new file mode 100644 index 000000000000..84e3b1dbff84 --- /dev/null +++ b/stubs/channels/channels/generic/http.pyi @@ -0,0 +1,19 @@ +from _typeshed import Unused +from collections.abc import Iterable +from typing import Any + +from asgiref.typing import HTTPDisconnectEvent, HTTPRequestEvent, HTTPScope +from channels.consumer import AsyncConsumer + +class AsyncHttpConsumer(AsyncConsumer): + body: list[bytes] + scope: HTTPScope # type: ignore[assignment] + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + async def send_headers(self, *, status: int = 200, headers: Iterable[tuple[bytes, bytes]] | None = None) -> None: ... + async def send_body(self, body: bytes, *, more_body: bool = False) -> None: ... + async def send_response(self, status: int, body: bytes, **kwargs: Any) -> None: ... + async def handle(self, body: bytes) -> None: ... + async def disconnect(self) -> None: ... + async def http_request(self, message: HTTPRequestEvent) -> None: ... + async def http_disconnect(self, message: HTTPDisconnectEvent) -> None: ... diff --git a/stubs/channels/channels/generic/websocket.pyi b/stubs/channels/channels/generic/websocket.pyi new file mode 100644 index 000000000000..f19d406e1e5d --- /dev/null +++ b/stubs/channels/channels/generic/websocket.pyi @@ -0,0 +1,61 @@ +from _typeshed import Unused +from typing import Any + +from asgiref.typing import WebSocketConnectEvent, WebSocketDisconnectEvent, WebSocketReceiveEvent +from channels.consumer import AsyncConsumer, SyncConsumer + +class WebsocketConsumer(SyncConsumer): + groups: list[str] + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + def websocket_connect(self, message: WebSocketConnectEvent) -> None: ... + def connect(self) -> None: ... + def accept(self, subprotocol: str | None = None, headers: list[tuple[str, str]] | None = None) -> None: ... + def websocket_receive(self, message: WebSocketReceiveEvent) -> None: ... + def receive(self, text_data: str | None = None, bytes_data: bytes | None = None) -> None: ... + def send( # type: ignore[override] + self, text_data: str | None = None, bytes_data: bytes | None = None, close: bool = False + ) -> None: ... + def close(self, code: int | bool | None = None, reason: str | None = None) -> None: ... + def websocket_disconnect(self, message: WebSocketDisconnectEvent) -> None: ... + def disconnect(self, code: int) -> None: ... + +class JsonWebsocketConsumer(WebsocketConsumer): + def receive(self, text_data: str | None = None, bytes_data: bytes | None = None, **kwargs: Any) -> None: ... + # content is typed as Any to match json.loads() return type - JSON can represent + # various Python types (dict, list, str, int, float, bool, None) + def receive_json(self, content: Any, **kwargs: Any) -> None: ... + # content is typed as Any to match json.dumps() input type - accepts any JSON-serializable object + def send_json(self, content: Any, close: bool = False) -> None: ... + @classmethod + def decode_json(cls, text_data: str) -> Any: ... # Returns Any like json.loads() + @classmethod + def encode_json(cls, content: Any) -> str: ... # Accepts Any like json.dumps() + +class AsyncWebsocketConsumer(AsyncConsumer): + groups: list[str] + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + async def websocket_connect(self, message: WebSocketConnectEvent) -> None: ... + async def connect(self) -> None: ... + async def accept(self, subprotocol: str | None = None, headers: list[tuple[str, str]] | None = None) -> None: ... + async def websocket_receive(self, message: WebSocketReceiveEvent) -> None: ... + async def receive(self, text_data: str | None = None, bytes_data: bytes | None = None) -> None: ... + async def send( # type: ignore[override] + self, text_data: str | None = None, bytes_data: bytes | None = None, close: bool = False + ) -> None: ... + async def close(self, code: int | bool | None = None, reason: str | None = None) -> None: ... + async def websocket_disconnect(self, message: WebSocketDisconnectEvent) -> None: ... + async def disconnect(self, code: int) -> None: ... + +class AsyncJsonWebsocketConsumer(AsyncWebsocketConsumer): + async def receive(self, text_data: str | None = None, bytes_data: bytes | None = None, **kwargs: Any) -> None: ... + # content is typed as Any to match json.loads() return type - JSON can represent + # various Python types (dict, list, str, int, float, bool, None) + async def receive_json(self, content: Any, **kwargs: Any) -> None: ... + # content is typed as Any to match json.dumps() input type - accepts any JSON-serializable object + async def send_json(self, content: Any, close: bool = False) -> None: ... + @classmethod + async def decode_json(cls, text_data: str) -> Any: ... # Returns Any like json.loads() + @classmethod + async def encode_json(cls, content: Any) -> str: ... # Accepts Any like json.dumps() diff --git a/stubs/channels/channels/layers.pyi b/stubs/channels/channels/layers.pyi new file mode 100644 index 000000000000..a527e5873b7e --- /dev/null +++ b/stubs/channels/channels/layers.pyi @@ -0,0 +1,96 @@ +import asyncio +from re import Pattern +from typing import Any, ClassVar, TypeAlias, overload +from typing_extensions import deprecated + +class ChannelLayerManager: + backends: dict[str, BaseChannelLayer] + + def __init__(self) -> None: ... + @property + def configs(self) -> dict[str, Any]: ... + def make_backend(self, name: str) -> BaseChannelLayer: ... + def make_test_backend(self, name: str) -> Any: ... + def __getitem__(self, key: str) -> BaseChannelLayer: ... + def __contains__(self, key: str) -> bool: ... + def set(self, key: str, layer: BaseChannelLayer) -> BaseChannelLayer | None: ... + +_ChannelCapacityPattern: TypeAlias = Pattern[str] | str +_ChannelCapacityDict: TypeAlias = dict[_ChannelCapacityPattern, int] +_CompiledChannelCapacity: TypeAlias = list[tuple[Pattern[str], int]] + +class BaseChannelLayer: + MAX_NAME_LENGTH: ClassVar[int] = 100 + expiry: int + capacity: int + channel_capacity: _ChannelCapacityDict + channel_name_regex: Pattern[str] + group_name_regex: Pattern[str] + invalid_name_error: str + + def __init__(self, expiry: int = 60, capacity: int = 100, channel_capacity: _ChannelCapacityDict | None = None) -> None: ... + def compile_capacities(self, channel_capacity: _ChannelCapacityDict) -> _CompiledChannelCapacity: ... + def get_capacity(self, channel: str) -> int: ... + + @overload + def match_type_and_length(self, name: str) -> bool: ... + @overload + def match_type_and_length(self, name: object) -> bool: ... + + @overload + def require_valid_channel_name(self, name: str, receive: bool = False) -> bool: ... + @overload + def require_valid_channel_name(self, name: object, receive: bool = False) -> bool: ... + + @overload + def require_valid_group_name(self, name: str) -> bool: ... + @overload + def require_valid_group_name(self, name: object) -> bool: ... + + @overload + def valid_channel_names(self, names: list[str], receive: bool = False) -> bool: ... + @overload + def valid_channel_names(self, names: list[Any], receive: bool = False) -> bool: ... + + def non_local_name(self, name: str) -> str: ... + async def send(self, channel: str, message: dict[str, Any]) -> None: ... + async def receive(self, channel: str) -> dict[str, Any]: ... + async def new_channel(self) -> str: ... + async def flush(self) -> None: ... + async def group_add(self, group: str, channel: str) -> None: ... + async def group_discard(self, group: str, channel: str) -> None: ... + async def group_send(self, group: str, message: dict[str, Any]) -> None: ... + @deprecated("Use require_valid_channel_name instead.") + def valid_channel_name(self, channel_name: str, receive: bool = False) -> bool: ... + @deprecated("Use require_valid_group_name instead.") + def valid_group_name(self, group_name: str) -> bool: ... + +_InMemoryQueueData: TypeAlias = tuple[float, dict[str, Any]] + +class InMemoryChannelLayer(BaseChannelLayer): + channels: dict[str, asyncio.Queue[_InMemoryQueueData]] + groups: dict[str, dict[str, float]] + group_expiry: int + + def __init__( + self, + expiry: int = 60, + group_expiry: int = 86400, + capacity: int = 100, + channel_capacity: _ChannelCapacityDict | None = None, + ) -> None: ... + + extensions: list[str] + + async def send(self, channel: str, message: dict[str, Any]) -> None: ... + async def receive(self, channel: str) -> dict[str, Any]: ... + async def new_channel(self, prefix: str = "specific.") -> str: ... + async def flush(self) -> None: ... + async def close(self) -> None: ... + async def group_add(self, group: str, channel: str) -> None: ... + async def group_discard(self, group: str, channel: str) -> None: ... + async def group_send(self, group: str, message: dict[str, Any]) -> None: ... + +def get_channel_layer(alias: str = "default") -> BaseChannelLayer | None: ... + +channel_layers: ChannelLayerManager diff --git a/stubs/requests/requests/packages/urllib3/packages/__init__.pyi b/stubs/channels/channels/management/__init__.pyi similarity index 100% rename from stubs/requests/requests/packages/urllib3/packages/__init__.pyi rename to stubs/channels/channels/management/__init__.pyi diff --git a/stubs/selenium/selenium/__init__.pyi b/stubs/channels/channels/management/commands/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/__init__.pyi rename to stubs/channels/channels/management/commands/__init__.pyi diff --git a/stubs/channels/channels/management/commands/runworker.pyi b/stubs/channels/channels/management/commands/runworker.pyi new file mode 100644 index 000000000000..533b94cea88d --- /dev/null +++ b/stubs/channels/channels/management/commands/runworker.pyi @@ -0,0 +1,25 @@ +import logging +from _typeshed import Unused +from argparse import ArgumentParser +from typing import TypedDict, type_check_only + +from channels.layers import BaseChannelLayer +from channels.worker import Worker +from django.core.management.base import BaseCommand + +logger: logging.Logger + +@type_check_only +class _RunWorkerCommandOption(TypedDict): + verbosity: int | None + layer: str + channels: list[str] + +class Command(BaseCommand): + leave_locale_alone: bool = True + worker_class: type[Worker] = ... + verbosity: int + channel_layer: BaseChannelLayer + + def add_arguments(self, parser: ArgumentParser) -> None: ... + def handle(self, *args: Unused, **options: _RunWorkerCommandOption) -> None: ... diff --git a/stubs/channels/channels/middleware.pyi b/stubs/channels/channels/middleware.pyi new file mode 100644 index 000000000000..339ae9218244 --- /dev/null +++ b/stubs/channels/channels/middleware.pyi @@ -0,0 +1,12 @@ +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable + +from .consumer import _ChannelScope +from .utils import _ChannelApplication + +class BaseMiddleware: + inner: _ChannelApplication + + def __init__(self, inner: _ChannelApplication) -> None: ... + async def __call__( + self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable + ) -> _ChannelApplication: ... diff --git a/stubs/channels/channels/routing.pyi b/stubs/channels/channels/routing.pyi new file mode 100644 index 000000000000..d2a0655d43ce --- /dev/null +++ b/stubs/channels/channels/routing.pyi @@ -0,0 +1,31 @@ +from typing import Any, type_check_only + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable, Scope +from django.urls.resolvers import URLPattern + +from .consumer import _ASGIApplicationProtocol, _ChannelScope +from .utils import _ChannelApplication + +def get_default_application() -> ProtocolTypeRouter: ... + +class ProtocolTypeRouter: + application_mapping: dict[str, _ChannelApplication] + + def __init__(self, application_mapping: dict[str, Any]) -> None: ... + async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... + +@type_check_only +class _ExtendedURLPattern(URLPattern): + callback: _ASGIApplicationProtocol | URLRouter + +class URLRouter: + routes: list[_ExtendedURLPattern | URLRouter] + + def __init__(self, routes: list[_ExtendedURLPattern | URLRouter]) -> None: ... + async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... + +class ChannelNameRouter: + application_mapping: dict[str, _ChannelApplication] + + def __init__(self, application_mapping: dict[str, _ChannelApplication]) -> None: ... + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/android/__init__.pyi b/stubs/channels/channels/security/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/android/__init__.pyi rename to stubs/channels/channels/security/__init__.pyi diff --git a/stubs/channels/channels/security/websocket.pyi b/stubs/channels/channels/security/websocket.pyi new file mode 100644 index 000000000000..aa76a1b4012e --- /dev/null +++ b/stubs/channels/channels/security/websocket.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Any +from urllib.parse import ParseResult + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable +from channels.consumer import _ChannelScope +from channels.generic.websocket import AsyncWebsocketConsumer +from channels.utils import _ChannelApplication + +class OriginValidator: + application: _ChannelApplication + allowed_origins: Iterable[str | Pattern[str]] + + def __init__(self, application: _ChannelApplication, allowed_origins: Iterable[str | Pattern[str]]) -> None: ... + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> Any: ... + def valid_origin(self, parsed_origin: ParseResult | None) -> bool: ... + def validate_origin(self, parsed_origin: ParseResult | None) -> bool: ... + def match_allowed_origin(self, parsed_origin: ParseResult | None, pattern: str | Pattern[str]) -> bool: ... + def get_origin_port(self, origin: ParseResult | None) -> int | None: ... + +def AllowedHostsOriginValidator(application: _ChannelApplication) -> OriginValidator: ... + +class WebsocketDenier(AsyncWebsocketConsumer): + async def connect(self) -> None: ... diff --git a/stubs/channels/channels/sessions.pyi b/stubs/channels/channels/sessions.pyi new file mode 100644 index 000000000000..04a4eb729535 --- /dev/null +++ b/stubs/channels/channels/sessions.pyi @@ -0,0 +1,56 @@ +import datetime +from collections.abc import Awaitable +from typing import Any + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable +from channels.consumer import _ChannelScope +from channels.utils import _ChannelApplication +from django.contrib.sessions.backends.base import SessionBase + +class CookieMiddleware: + inner: _ChannelApplication + + def __init__(self, inner: _ChannelApplication) -> None: ... + + # Returns the same type as the provided _ChannelApplication. + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> Any: ... + @classmethod + def set_cookie( + cls, + message: dict[str, Any], + key: str, + value: str = "", + max_age: int | None = None, + expires: str | datetime.datetime | None = None, + path: str = "/", + domain: str | None = None, + secure: bool = False, + httponly: bool = False, + samesite: str = "lax", + ) -> None: ... + @classmethod + def delete_cookie(cls, message: dict[str, Any], key: str, path: str = "/", domain: str | None = None) -> None: ... + +class InstanceSessionWrapper: + save_message_types: list[str] + cookie_response_message_types: list[str] + cookie_name: str + session_store: SessionBase + scope: _ChannelScope + activated: bool + real_send: ASGISendCallable + + def __init__(self, scope: _ChannelScope, send: ASGISendCallable) -> None: ... + async def resolve_session(self) -> None: ... + async def send(self, message: dict[str, Any]) -> Awaitable[None]: ... + async def save_session(self) -> None: ... + +class SessionMiddleware: + inner: _ChannelApplication + + def __init__(self, inner: _ChannelApplication) -> None: ... + async def __call__( + self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable + ) -> _ChannelApplication: ... + +def SessionMiddlewareStack(inner: _ChannelApplication) -> _ChannelApplication: ... diff --git a/stubs/channels/channels/testing/__init__.pyi b/stubs/channels/channels/testing/__init__.pyi new file mode 100644 index 000000000000..1cb75a0bf6dd --- /dev/null +++ b/stubs/channels/channels/testing/__init__.pyi @@ -0,0 +1,6 @@ +from .application import ApplicationCommunicator +from .http import HttpCommunicator +from .live import ChannelsLiveServerTestCase +from .websocket import WebsocketCommunicator + +__all__ = ["ApplicationCommunicator", "HttpCommunicator", "ChannelsLiveServerTestCase", "WebsocketCommunicator"] diff --git a/stubs/channels/channels/testing/application.pyi b/stubs/channels/channels/testing/application.pyi new file mode 100644 index 000000000000..db3f567c1d61 --- /dev/null +++ b/stubs/channels/channels/testing/application.pyi @@ -0,0 +1,21 @@ +from typing import Any + +from asgiref.testing import ApplicationCommunicator as BaseApplicationCommunicator + +def no_op() -> None: ... + +class ApplicationCommunicator(BaseApplicationCommunicator): + # ASGI messages are dictionaries with a "type" key and protocol-specific fields. + # Dictionary values can be strings, bytes, lists, or other types depending on the protocol: + # - HTTP: {"type": "http.request", "body": b"request data", "headers": [...], ...} + # - WebSocket: {"type": "websocket.receive", "bytes": b"binary data"} or {"text": "string"} + # - Custom protocols: Application-specific message dictionaries + async def send_input(self, message: dict[str, Any]) -> None: ... + async def receive_output(self, timeout: float = 1) -> dict[str, Any]: ... + + # The following methods are not present in the original source code, + # but are commonly used in practice. Since the base package doesn't + # provide type hints for them, they are added here to improve type correctness. + async def receive_nothing(self, timeout: float = 0.1, interval: float = 0.01) -> bool: ... + async def wait(self, timeout: float = 1) -> None: ... + def stop(self, exceptions: bool = True) -> None: ... diff --git a/stubs/channels/channels/testing/http.pyi b/stubs/channels/channels/testing/http.pyi new file mode 100644 index 000000000000..6eb6650036c8 --- /dev/null +++ b/stubs/channels/channels/testing/http.pyi @@ -0,0 +1,41 @@ +from collections.abc import Iterable +from typing import Literal, TypedDict, type_check_only + +from channels.testing.application import ApplicationCommunicator +from channels.utils import _ChannelApplication + +# HTTP test-specific response type +@type_check_only +class _HTTPTestResponse(TypedDict, total=False): + status: int + headers: Iterable[tuple[bytes, bytes]] + body: bytes + +@type_check_only +class _HTTPTestScope(TypedDict, total=False): + type: Literal["http"] + http_version: str + method: str + scheme: str + path: str + raw_path: bytes + query_string: bytes + root_path: str + headers: Iterable[tuple[bytes, bytes]] | None + client: tuple[str, int] | None + server: tuple[str, int | None] | None + +class HttpCommunicator(ApplicationCommunicator): + scope: _HTTPTestScope + body: bytes + sent_request: bool + + def __init__( + self, + application: _ChannelApplication, + method: str, + path: str, + body: bytes = b"", + headers: Iterable[tuple[bytes, bytes]] | None = None, + ) -> None: ... + async def get_response(self, timeout: float = 1) -> _HTTPTestResponse: ... diff --git a/stubs/channels/channels/testing/live.pyi b/stubs/channels/channels/testing/live.pyi new file mode 100644 index 000000000000..e9f52d6e5e22 --- /dev/null +++ b/stubs/channels/channels/testing/live.pyi @@ -0,0 +1,25 @@ +from collections.abc import Callable +from typing import Any, ClassVar, TypeAlias + +from channels.routing import ProtocolTypeRouter +from channels.utils import _ChannelApplication +from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler +from django.test.testcases import TransactionTestCase + +DaphneProcess: TypeAlias = Any # TODO: temporary hack for daphne.testing.DaphneProcess; remove once daphne provides types + +_StaticWrapper: TypeAlias = Callable[[ProtocolTypeRouter], _ChannelApplication] + +def make_application(*, static_wrapper: _StaticWrapper | None) -> Any: ... +def set_database_connection() -> None: ... + +class ChannelsLiveServerTestCase(TransactionTestCase): + host: ClassVar[str] = "localhost" + ProtocolServerProcess: ClassVar[type[DaphneProcess]] = ... + static_wrapper: ClassVar[type[ASGIStaticFilesHandler]] = ... + serve_static: ClassVar[bool] = True + + @property + def live_server_url(self) -> str: ... + @property + def live_server_ws_url(self) -> str: ... diff --git a/stubs/channels/channels/testing/websocket.pyi b/stubs/channels/channels/testing/websocket.pyi new file mode 100644 index 000000000000..9b79d7dc10eb --- /dev/null +++ b/stubs/channels/channels/testing/websocket.pyi @@ -0,0 +1,55 @@ +from collections.abc import Iterable +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import NotRequired + +from asgiref.typing import ASGIVersions +from channels.testing.application import ApplicationCommunicator +from channels.utils import _ChannelApplication + +@type_check_only +class _WebsocketTestScope(TypedDict, total=False): + spec_version: int + type: Literal["websocket"] + asgi: ASGIVersions + http_version: str + scheme: str + path: str + raw_path: bytes + query_string: bytes + root_path: str + headers: Iterable[tuple[bytes, bytes]] | None + client: tuple[str, int] | None + server: tuple[str, int | None] | None + subprotocols: Iterable[str] | None + state: NotRequired[dict[str, Any]] + extensions: dict[str, dict[object, object]] | None + +_Connected: TypeAlias = bool +_CloseCodeOrAcceptSubProtocol: TypeAlias = int | str | None +_WebsocketConnectResponse: TypeAlias = tuple[_Connected, _CloseCodeOrAcceptSubProtocol] + +class WebsocketCommunicator(ApplicationCommunicator): + scope: _WebsocketTestScope + response_headers: list[tuple[bytes, bytes]] | None + + def __init__( + self, + application: _ChannelApplication, + path: str, + headers: Iterable[tuple[bytes, bytes]] | None = None, + subprotocols: Iterable[str] | None = None, + spec_version: int | None = None, + ) -> None: ... + async def connect(self, timeout: float = 1) -> _WebsocketConnectResponse: ... + async def send_to(self, text_data: str | None = None, bytes_data: bytes | None = None) -> None: ... + async def receive_from(self, timeout: float = 1) -> str | bytes: ... + + # These overloads reflect common usage, where users typically send and receive `dict[str, Any]`. + # The base case allows `Any` to support broader `json.dumps` / `json.loads` compatibility. + @overload + async def send_json_to(self, data: dict[str, Any]) -> None: ... + @overload + async def send_json_to(self, data: Any) -> None: ... + + async def receive_json_from(self, timeout: float = 1) -> Any: ... + async def disconnect(self, code: int = 1000, timeout: float = 1) -> None: ... diff --git a/stubs/channels/channels/utils.pyi b/stubs/channels/channels/utils.pyi new file mode 100644 index 000000000000..80b4dff1a902 --- /dev/null +++ b/stubs/channels/channels/utils.pyi @@ -0,0 +1,19 @@ +from collections.abc import Awaitable, Callable +from typing import Any, Protocol, TypeAlias, type_check_only + +from asgiref.typing import ASGIApplication, ASGIReceiveCallable + +def name_that_thing(thing: object) -> str: ... +async def await_many_dispatch( + consumer_callables: list[Callable[[], Awaitable[ASGIReceiveCallable]]], dispatch: Callable[[dict[str, Any]], Awaitable[None]] +) -> None: ... + +# Defines a generic ASGI middleware protocol. +# All arguments are typed as `Any` to maximize compatibility with third-party ASGI middleware +# that may not strictly follow type conventions or use more specific signatures. +@type_check_only +class _MiddlewareProtocol(Protocol): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def __call__(self, scope: Any, receive: Any, send: Any) -> Any: ... + +_ChannelApplication: TypeAlias = _MiddlewareProtocol | ASGIApplication # noqa: Y047 diff --git a/stubs/channels/channels/worker.pyi b/stubs/channels/channels/worker.pyi new file mode 100644 index 000000000000..a20b5feec275 --- /dev/null +++ b/stubs/channels/channels/worker.pyi @@ -0,0 +1,13 @@ +from asgiref.server import StatelessServer +from channels.layers import BaseChannelLayer +from channels.utils import _ChannelApplication + +class Worker(StatelessServer): + channels: list[str] + channel_layer: BaseChannelLayer + + def __init__( + self, application: _ChannelApplication, channels: list[str], channel_layer: BaseChannelLayer, max_applications: int = 1000 + ) -> None: ... + async def handle(self) -> None: ... + async def listener(self, channel: str) -> None: ... diff --git a/stubs/characteristic/METADATA.toml b/stubs/characteristic/METADATA.toml deleted file mode 100644 index 199895dd573d..000000000000 --- a/stubs/characteristic/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "14.3.*" -python2 = true diff --git a/stubs/characteristic/characteristic/__init__.pyi b/stubs/characteristic/characteristic/__init__.pyi deleted file mode 100644 index 08056c3e6c07..000000000000 --- a/stubs/characteristic/characteristic/__init__.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any, AnyStr, Callable, Sequence, Type, TypeVar - -def with_repr(attrs: Sequence[AnyStr | Attribute]) -> Callable[..., Any]: ... -def with_cmp(attrs: Sequence[AnyStr | Attribute]) -> Callable[..., Any]: ... -def with_init(attrs: Sequence[AnyStr | Attribute]) -> Callable[..., Any]: ... -def immutable(attrs: Sequence[AnyStr | Attribute]) -> Callable[..., Any]: ... -def strip_leading_underscores(attribute_name: AnyStr) -> AnyStr: ... - -NOTHING = Any - -_T = TypeVar("_T") - -def attributes( - attrs: Sequence[AnyStr | Attribute], - apply_with_cmp: bool = ..., - apply_with_init: bool = ..., - apply_with_repr: bool = ..., - apply_immutable: bool = ..., - store_attributes: Callable[[type, Attribute], Any] | None = ..., - **kw: dict[Any, Any] | None, -) -> Callable[[Type[_T]], Type[_T]]: ... - -class Attribute: - def __init__( - self, - name: AnyStr, - exclude_from_cmp: bool = ..., - exclude_from_init: bool = ..., - exclude_from_repr: bool = ..., - exclude_from_immutable: bool = ..., - default_value: Any = ..., - default_factory: Callable[[None], Any] | None = ..., - instance_of: Any | None = ..., - init_aliaser: Callable[[AnyStr], AnyStr] | None = ..., - ) -> None: ... diff --git a/stubs/chardet/@tests/stubtest_allowlist.txt b/stubs/chardet/@tests/stubtest_allowlist.txt deleted file mode 100644 index d3e6aac28349..000000000000 --- a/stubs/chardet/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,25 +0,0 @@ -chardet.langbulgarianmodel.BulgarianLangModel -chardet.langbulgarianmodel.Latin5BulgarianModel -chardet.langbulgarianmodel.Latin5_BulgarianCharToOrderMap -chardet.langbulgarianmodel.Win1251BulgarianModel -chardet.langbulgarianmodel.win1251BulgarianCharToOrderMap -chardet.langcyrillicmodel -chardet.langgreekmodel.GreekLangModel -chardet.langgreekmodel.Latin7GreekModel -chardet.langgreekmodel.Latin7_char_to_order_map -chardet.langgreekmodel.Win1253GreekModel -chardet.langgreekmodel.win1253_char_to_order_map -chardet.langhebrewmodel.HEBREW_LANG_MODEL -chardet.langhebrewmodel.WIN1255_CHAR_TO_ORDER_MAP -chardet.langhebrewmodel.Win1255HebrewModel -chardet.langhungarianmodel.HungarianLangModel -chardet.langhungarianmodel.Latin2HungarianModel -chardet.langhungarianmodel.Latin2_HungarianCharToOrderMap -chardet.langhungarianmodel.Win1250HungarianModel -chardet.langhungarianmodel.win1250HungarianCharToOrderMap -chardet.langthaimodel.TIS620CharToOrderMap -chardet.langthaimodel.TIS620ThaiModel -chardet.langthaimodel.ThaiLangModel -chardet.langturkishmodel.Latin5TurkishModel -chardet.langturkishmodel.Latin5_TurkishCharToOrderMap -chardet.langturkishmodel.TurkishLangModel diff --git a/stubs/chardet/METADATA.toml b/stubs/chardet/METADATA.toml deleted file mode 100644 index 5df22726ce72..000000000000 --- a/stubs/chardet/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -version = "4.0.*" -python2 = true -requires = [] diff --git a/stubs/chardet/chardet/__init__.pyi b/stubs/chardet/chardet/__init__.pyi deleted file mode 100644 index 54e48f5c7233..000000000000 --- a/stubs/chardet/chardet/__init__.pyi +++ /dev/null @@ -1,26 +0,0 @@ -import sys -from typing import Any, Tuple - -from .universaldetector import UniversalDetector as UniversalDetector - -def __getattr__(name: str) -> Any: ... # incomplete - -if sys.version_info >= (3, 8): - from typing import TypedDict -else: - from typing_extensions import TypedDict - -class _LangModelType(TypedDict): - char_to_order_map: Tuple[int, ...] - precedence_matrix: Tuple[int, ...] - typical_positive_ratio: float - keep_english_letter: bool - charset_name: str - language: str - -class _SMModelType(TypedDict): - class_table: Tuple[int, ...] - class_factor: int - state_table: Tuple[int, ...] - char_len_table: Tuple[int, ...] - name: str diff --git a/stubs/chardet/chardet/enums.pyi b/stubs/chardet/chardet/enums.pyi deleted file mode 100644 index 08116f112432..000000000000 --- a/stubs/chardet/chardet/enums.pyi +++ /dev/null @@ -1,39 +0,0 @@ -class InputState(object): - PURE_ASCII: int - ESC_ASCII: int - HIGH_BYTE: int - -class LanguageFilter(object): - CHINESE_SIMPLIFIED: int - CHINESE_TRADITIONAL: int - JAPANESE: int - KOREAN: int - NON_CJK: int - ALL: int - CHINESE: int - CJK: int - -class ProbingState(object): - DETECTING: int - FOUND_IT: int - NOT_ME: int - -class MachineState(object): - START: int - ERROR: int - ITS_ME: int - -class SequenceLikelihood(object): - NEGATIVE: int - UNLIKELY: int - LIKELY: int - POSITIVE: int - @classmethod - def get_num_categories(cls) -> int: ... - -class CharacterCategory(object): - UNDEFINED: int - LINE_BREAK: int - SYMBOL: int - DIGIT: int - CONTROL: int diff --git a/stubs/chardet/chardet/langbulgarianmodel.pyi b/stubs/chardet/chardet/langbulgarianmodel.pyi deleted file mode 100644 index de07cfa7b1b4..000000000000 --- a/stubs/chardet/chardet/langbulgarianmodel.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -Latin5_BulgarianCharToOrderMap: Tuple[int, ...] -win1251BulgarianCharToOrderMap: Tuple[int, ...] -BulgarianLangModel: Tuple[int, ...] -Latin5BulgarianModel: _LangModelType -Win1251BulgarianModel: _LangModelType diff --git a/stubs/chardet/chardet/langcyrillicmodel.pyi b/stubs/chardet/chardet/langcyrillicmodel.pyi deleted file mode 100644 index 40a7044b1398..000000000000 --- a/stubs/chardet/chardet/langcyrillicmodel.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -KOI8R_char_to_order_map: Tuple[int, ...] -win1251_char_to_order_map: Tuple[int, ...] -latin5_char_to_order_map: Tuple[int, ...] -macCyrillic_char_to_order_map: Tuple[int, ...] -IBM855_char_to_order_map: Tuple[int, ...] -IBM866_char_to_order_map: Tuple[int, ...] -RussianLangModel: Tuple[int, ...] -Koi8rModel: _LangModelType -Win1251CyrillicModel: _LangModelType -Latin5CyrillicModel: _LangModelType -MacCyrillicModel: _LangModelType -Ibm866Model: _LangModelType -Ibm855Model: _LangModelType diff --git a/stubs/chardet/chardet/langgreekmodel.pyi b/stubs/chardet/chardet/langgreekmodel.pyi deleted file mode 100644 index f0fa3e8c21d3..000000000000 --- a/stubs/chardet/chardet/langgreekmodel.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -Latin7_char_to_order_map: Tuple[int, ...] -win1253_char_to_order_map: Tuple[int, ...] -GreekLangModel: Tuple[int, ...] -Latin7GreekModel: _LangModelType -Win1253GreekModel: _LangModelType diff --git a/stubs/chardet/chardet/langhebrewmodel.pyi b/stubs/chardet/chardet/langhebrewmodel.pyi deleted file mode 100644 index 08bfbc91bf26..000000000000 --- a/stubs/chardet/chardet/langhebrewmodel.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -WIN1255_CHAR_TO_ORDER_MAP: Tuple[int, ...] -HEBREW_LANG_MODEL: Tuple[int, ...] -Win1255HebrewModel: _LangModelType diff --git a/stubs/chardet/chardet/langhungarianmodel.pyi b/stubs/chardet/chardet/langhungarianmodel.pyi deleted file mode 100644 index 01e4a44380c2..000000000000 --- a/stubs/chardet/chardet/langhungarianmodel.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -Latin2_HungarianCharToOrderMap: Tuple[int, ...] -win1250HungarianCharToOrderMap: Tuple[int, ...] -HungarianLangModel: Tuple[int, ...] -Latin2HungarianModel: _LangModelType -Win1250HungarianModel: _LangModelType diff --git a/stubs/chardet/chardet/langthaimodel.pyi b/stubs/chardet/chardet/langthaimodel.pyi deleted file mode 100644 index 93149e72b16c..000000000000 --- a/stubs/chardet/chardet/langthaimodel.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -TIS620CharToOrderMap: Tuple[int, ...] -ThaiLangModel: Tuple[int, ...] -TIS620ThaiModel: _LangModelType diff --git a/stubs/chardet/chardet/langturkishmodel.pyi b/stubs/chardet/chardet/langturkishmodel.pyi deleted file mode 100644 index 65b1bdcbbe2d..000000000000 --- a/stubs/chardet/chardet/langturkishmodel.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Tuple - -from . import _LangModelType - -Latin5_TurkishCharToOrderMap: Tuple[int, ...] -TurkishLangModel: Tuple[int, ...] -Latin5TurkishModel: _LangModelType diff --git a/stubs/chardet/chardet/universaldetector.pyi b/stubs/chardet/chardet/universaldetector.pyi deleted file mode 100644 index 372a4fefa5e6..000000000000 --- a/stubs/chardet/chardet/universaldetector.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from logging import Logger -from typing import Pattern -from typing_extensions import TypedDict - -class _FinalResultType(TypedDict): - encoding: str - confidence: float - language: str - -class _IntermediateResultType(TypedDict): - encoding: str | None - confidence: float - language: str | None - -class UniversalDetector(object): - MINIMUM_THRESHOLD: float - HIGH_BYTE_DETECTOR: Pattern[bytes] - ESC_DETECTOR: Pattern[bytes] - WIN_BYTE_DETECTOR: Pattern[bytes] - ISO_WIN_MAP: dict[str, str] - - result: _IntermediateResultType - done: bool - lang_filter: int - logger: Logger - def __init__(self, lang_filter: int = ...) -> None: ... - def reset(self) -> None: ... - def feed(self, byte_str: bytes) -> None: ... - def close(self) -> _FinalResultType: ... diff --git a/stubs/chardet/chardet/version.pyi b/stubs/chardet/chardet/version.pyi deleted file mode 100644 index 966073bd25a6..000000000000 --- a/stubs/chardet/chardet/version.pyi +++ /dev/null @@ -1,2 +0,0 @@ -__version__: str -VERSION: list[str] diff --git a/stubs/chevron/METADATA.toml b/stubs/chevron/METADATA.toml new file mode 100755 index 000000000000..83c82dbd7688 --- /dev/null +++ b/stubs/chevron/METADATA.toml @@ -0,0 +1,4 @@ +version = "0.14.*" +upstream-repository = "https://github.com/noahmorrison/chevron" + +[tool.stubtest] diff --git a/stubs/chevron/chevron/__init__.pyi b/stubs/chevron/chevron/__init__.pyi new file mode 100644 index 000000000000..472809791640 --- /dev/null +++ b/stubs/chevron/chevron/__init__.pyi @@ -0,0 +1,5 @@ +from .main import cli_main as cli_main, main as main +from .renderer import render as render +from .tokenizer import ChevronError as ChevronError + +__all__ = ["main", "render", "cli_main", "ChevronError"] diff --git a/stubs/chevron/chevron/main.pyi b/stubs/chevron/chevron/main.pyi new file mode 100644 index 000000000000..c12595aaeed5 --- /dev/null +++ b/stubs/chevron/chevron/main.pyi @@ -0,0 +1,5 @@ +from _typeshed import FileDescriptorOrPath +from typing import Any + +def main(template: FileDescriptorOrPath, data: FileDescriptorOrPath | None = None, **kwargs: Any) -> str: ... +def cli_main() -> None: ... diff --git a/stubs/chevron/chevron/metadata.pyi b/stubs/chevron/chevron/metadata.pyi new file mode 100644 index 000000000000..c2ee2cab489b --- /dev/null +++ b/stubs/chevron/chevron/metadata.pyi @@ -0,0 +1 @@ +version: str diff --git a/stubs/chevron/chevron/renderer.pyi b/stubs/chevron/chevron/renderer.pyi new file mode 100644 index 000000000000..274a4719f602 --- /dev/null +++ b/stubs/chevron/chevron/renderer.pyi @@ -0,0 +1,22 @@ +from _typeshed import StrPath, SupportsRead +from collections.abc import MutableSequence, Sequence +from typing import Any, Literal + +g_token_cache: dict[str, list[tuple[str, str]]] # undocumented +python3: Literal[True] +string_type = str +unicode_type = str + +def unicode(x: str, y: str) -> str: ... +def render( + template: SupportsRead[str] | str | Sequence[tuple[str, str]] = "", + data: dict[str, Any] = {}, + partials_path: StrPath | None = ".", + partials_ext: str = "mustache", + partials_dict: dict[str, str] = {}, + padding: str = "", + def_ldel: str | None = "{{", + def_rdel: str | None = "}}", + scopes: MutableSequence[int] | None = None, + warn: bool = False, +) -> str: ... diff --git a/stubs/chevron/chevron/tokenizer.pyi b/stubs/chevron/chevron/tokenizer.pyi new file mode 100644 index 000000000000..1103c68c2d35 --- /dev/null +++ b/stubs/chevron/chevron/tokenizer.pyi @@ -0,0 +1,11 @@ +from collections.abc import Iterator + +class ChevronError(SyntaxError): ... + +def grab_literal(template: str, l_del: str | None) -> tuple[str, str]: ... # undocumented +def l_sa_check(template: str, literal: str, is_standalone: bool) -> bool | None: ... # undocumented +def r_sa_check(template: str, tag_type: str, is_standalone: bool) -> bool: ... # undocumented +def parse_tag(template: str, l_del: str | None, r_del: str | None) -> tuple[tuple[str, str], str]: ... # undocumented +def tokenize( + template: str, def_ldel: str | None = "{{", def_rdel: str | None = "}}" +) -> Iterator[tuple[str, str]]: ... # undocumented diff --git a/stubs/click-default-group/METADATA.toml b/stubs/click-default-group/METADATA.toml new file mode 100644 index 000000000000..d59ab76ab915 --- /dev/null +++ b/stubs/click-default-group/METADATA.toml @@ -0,0 +1,4 @@ +version = "1.2.*" +upstream-repository = "https://github.com/click-contrib/click-default-group" +# requires a version of click with a py.typed +dependencies = ["click>=8.0.0"] diff --git a/stubs/click-default-group/click_default_group.pyi b/stubs/click-default-group/click_default_group.pyi new file mode 100644 index 000000000000..28a6ebedce2d --- /dev/null +++ b/stubs/click-default-group/click_default_group.pyi @@ -0,0 +1,84 @@ +from collections.abc import Callable, MutableMapping, Sequence +from typing import Any, Final, Literal, overload +from typing_extensions import deprecated + +import click + +__all__ = ["DefaultGroup"] +__version__: Final[str] + +class DefaultGroup(click.Group): + ignore_unknown_options: bool + default_cmd_name: str | None + default_if_no_args: bool + # type hints were taken from click lib + def __init__( + self, + name: str | None = None, + commands: MutableMapping[str, click.Command] | Sequence[click.Command] | None = None, + *, + ignore_unknown_options: Literal[True] | None = True, + default: str | None = None, + default_if_no_args: bool = False, + invoke_without_command: bool = False, + no_args_is_help: bool | None = None, + subcommand_metavar: str | None = None, + chain: bool = False, + result_callback: Callable[..., Any] | None = None, # Any is specified in click lib + context_settings: MutableMapping[str, Any] | None = None, # Any is specified in click lib + callback: Callable[..., Any] | None = None, # Any is specified in click lib + params: list[click.Parameter] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str | None = "[OPTIONS]", + add_help_option: bool = True, + hidden: bool = False, + deprecated: bool = False, + ) -> None: ... + def set_default_command(self, command: click.Command) -> None: ... + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: ... + def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None: ... + def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple[str | None, click.Command | None, list[str]]: ... + def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: ... + + @overload + def command( + self, + __func: Callable[..., Any], + /, + *, + name: str | None = ..., + cls: type[click.Command] | None = ..., + default: Literal[False] = False, + ) -> click.Command: ... + @overload + @deprecated("Use default param of `DefaultGroup` or `set_default_command()` instead") + def command( + self, + __func: Callable[..., Any], + /, + *, + name: str | None = ..., + cls: type[click.Command] | None = ..., + default: Literal[True], + ) -> click.Command: ... + @overload + def command( + self, *, name: str | None = ..., cls: type[click.Command] | None = ..., default: Literal[False] = False + ) -> Callable[[Callable[..., Any]], click.Command]: ... + @overload + @deprecated("Use default param of `DefaultGroup` or `set_default_command()` instead") + def command( + self, *, name: str | None = ..., cls: type[click.Command] | None = ..., default: Literal[True] + ) -> Callable[[Callable[..., Any]], click.Command]: ... + @overload + def command(self, *args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], click.Command] | click.Command: ... + +class DefaultCommandFormatter: + group: click.Group + formatter: click.HelpFormatter + mark: str + def __init__(self, group: click.Group, formatter: click.HelpFormatter, mark: str = "*") -> None: ... + def write_dl(self, rows: Sequence[tuple[str, str]], col_max: int = 30, col_spacing: int = -2) -> None: ... + def __getattr__(self, attr: str) -> Any: ... # attribute access is forwarded to click.HelpFormatter diff --git a/stubs/click-log/METADATA.toml b/stubs/click-log/METADATA.toml new file mode 100644 index 000000000000..af9b07a4091b --- /dev/null +++ b/stubs/click-log/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.4.*" +upstream-repository = "https://github.com/click-contrib/click-log" +dependencies = ["click>=8.0.0"] diff --git a/stubs/click-log/click_log/__init__.pyi b/stubs/click-log/click_log/__init__.pyi new file mode 100644 index 000000000000..b3d38f6720c0 --- /dev/null +++ b/stubs/click-log/click_log/__init__.pyi @@ -0,0 +1,4 @@ +from .core import ClickHandler as ClickHandler, ColorFormatter as ColorFormatter, basic_config as basic_config +from .options import simple_verbosity_option as simple_verbosity_option + +__version__: str diff --git a/stubs/click-log/click_log/core.pyi b/stubs/click-log/click_log/core.pyi new file mode 100644 index 000000000000..8ee5d99e3596 --- /dev/null +++ b/stubs/click-log/click_log/core.pyi @@ -0,0 +1,15 @@ +import logging + +LOGGER_KEY: str +DEFAULT_LEVEL: int +PY2: bool +text_type: type + +class ColorFormatter(logging.Formatter): + colors: dict[str, dict[str, str]] + def format(self, record: logging.LogRecord) -> str: ... + +class ClickHandler(logging.Handler): + def emit(self, record: logging.LogRecord) -> None: ... + +def basic_config(logger: logging.Logger | str | None = None) -> None: ... diff --git a/stubs/click-log/click_log/options.pyi b/stubs/click-log/click_log/options.pyi new file mode 100644 index 000000000000..cea9e5edd8ea --- /dev/null +++ b/stubs/click-log/click_log/options.pyi @@ -0,0 +1,10 @@ +import logging +from collections.abc import Callable +from typing import Any, TypeAlias, TypeVar + +import click + +_AnyCallable: TypeAlias = Callable[..., Any] +_FC = TypeVar("_FC", bound=_AnyCallable | click.Command) + +def simple_verbosity_option(logger: logging.Logger | str | None = None, *names: str, **kwargs: Any) -> Callable[[_FC], _FC]: ... diff --git a/stubs/click-shell/METADATA.toml b/stubs/click-shell/METADATA.toml new file mode 100644 index 000000000000..6d8aa15caf14 --- /dev/null +++ b/stubs/click-shell/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.1" +upstream-repository = "https://github.com/clarkperkins/click-shell" +dependencies = ["click>=8.0.0"] diff --git a/stubs/click-shell/click_shell/__init__.pyi b/stubs/click-shell/click_shell/__init__.pyi new file mode 100644 index 000000000000..38ef48feb91b --- /dev/null +++ b/stubs/click-shell/click_shell/__init__.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from .core import Shell as Shell, make_click_shell as make_click_shell +from .decorators import shell as shell + +__all__ = ["make_click_shell", "shell", "Shell", "__version__"] +__version__: Final[str] diff --git a/stubs/click-shell/click_shell/_cmd.pyi b/stubs/click-shell/click_shell/_cmd.pyi new file mode 100644 index 000000000000..c6848e48928e --- /dev/null +++ b/stubs/click-shell/click_shell/_cmd.pyi @@ -0,0 +1,28 @@ +from cmd import Cmd +from collections.abc import Callable +from typing import Any, ClassVar, TextIO + +import click + +class ClickCmd(Cmd): + nocommand: ClassVar[str] + def __init__( + self, + ctx: click.Context | None = None, + on_finished: Callable[[click.Context], None] | None = None, + hist_file: str | None = None, + completekey: str = "tab", + stdin: TextIO | None = None, + stdout: TextIO | None = None, + ) -> None: ... + def preloop(self) -> None: ... + def postloop(self) -> None: ... + def cmdloop(self, intro: str | None = None) -> None: ... + def get_prompt(self) -> str | None: ... + def emptyline(self) -> bool: ... + def default(self, line: str) -> None: ... + def get_names(self) -> list[str]: ... + def do_help(self, arg: str) -> None: ... + def do_quit(self, arg: str) -> bool: ... + def do_exit(self, arg: str) -> bool: ... + def print_topics(self, header: Any, cmds: list[str] | None, cmdlen: int, maxcol: int) -> None: ... diff --git a/stubs/click-shell/click_shell/_compat.pyi b/stubs/click-shell/click_shell/_compat.pyi new file mode 100644 index 000000000000..c383de4ff97c --- /dev/null +++ b/stubs/click-shell/click_shell/_compat.pyi @@ -0,0 +1,10 @@ +import types +from collections.abc import Callable +from typing import Any, Final + +import click + +PY2: Final = False + +def get_method_type(func: Callable[..., Any], obj: object) -> types.MethodType: ... +def get_choices(cli: click.Command, prog_name: str, args: list[str], incomplete: str) -> list[str]: ... diff --git a/stubs/click-shell/click_shell/core.pyi b/stubs/click-shell/click_shell/core.pyi new file mode 100644 index 000000000000..673c0c69464d --- /dev/null +++ b/stubs/click-shell/click_shell/core.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from logging import Logger +from typing import Any + +import click + +from ._cmd import ClickCmd + +logger: Logger + +def get_invoke(command: click.Command) -> Callable[[ClickCmd, str], bool]: ... +def get_help(command: click.Command) -> Callable[[ClickCmd], None]: ... +def get_complete(command: click.Command) -> Callable[[ClickCmd, str, str, int, int], list[str]]: ... + +class ClickShell(ClickCmd): + def add_command(self, cmd: click.Command, name: str) -> None: ... + +def make_click_shell( + ctx: click.Context, + prompt: str | Callable[[], str] | Callable[[click.Context, str], str] | None = None, + intro: str | None = None, + hist_file: str | None = None, +) -> ClickShell: ... + +class Shell(click.Group): + def __init__( + self, + prompt: str | Callable[[], str] | Callable[[click.Context, str], str] | None = None, + intro: str | None = None, + hist_file: str | None = None, + on_finished: Callable[[click.Context], None] | None = None, + **attrs: Any, + ) -> None: ... + def add_command(self, cmd: click.Command, name: str | None = None) -> None: ... + def invoke(self, ctx: click.Context) -> Any: ... diff --git a/stubs/click-shell/click_shell/decorators.pyi b/stubs/click-shell/click_shell/decorators.pyi new file mode 100644 index 000000000000..ce72f74fbd6e --- /dev/null +++ b/stubs/click-shell/click_shell/decorators.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from typing import Any + +from click.decorators import _AnyCallable + +from .core import Shell + +def shell(name: str | None = None, **attrs: Any) -> Callable[[_AnyCallable], Shell]: ... diff --git a/stubs/click-spinner/@tests/stubtest_allowlist.txt b/stubs/click-spinner/@tests/stubtest_allowlist.txt deleted file mode 100644 index dc1463c3c44c..000000000000 --- a/stubs/click-spinner/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,2 +0,0 @@ -click_spinner.Spinner.__init__ -click_spinner.spinner diff --git a/stubs/click-spinner/METADATA.toml b/stubs/click-spinner/METADATA.toml index f511d7da692f..57e844258422 100644 --- a/stubs/click-spinner/METADATA.toml +++ b/stubs/click-spinner/METADATA.toml @@ -1,3 +1,3 @@ -version = "0.1.*" -python2 = true -requires = [] +version = "0.1.11" +upstream-repository = "https://github.com/click-contrib/click-spinner" +obsolete-since = { version = "0.2.0", date = "2026-06-23" } diff --git a/stubs/click-spinner/click_spinner/__init__.pyi b/stubs/click-spinner/click_spinner/__init__.pyi index 6ddb0e8f42fd..6b576256729a 100644 --- a/stubs/click-spinner/click_spinner/__init__.pyi +++ b/stubs/click-spinner/click_spinner/__init__.pyi @@ -1,16 +1,18 @@ import threading +from collections.abc import Iterator from types import TracebackType -from typing import Iterator, Protocol, Type -from typing_extensions import Literal +from typing import Final, Literal, Protocol, type_check_only +from typing_extensions import Self -__version__: str +__version__: Final[str] +@type_check_only class _Stream(Protocol): def isatty(self) -> bool: ... def flush(self) -> None: ... - def write(self, s: str) -> int: ... + def write(self, s: str, /) -> int: ... -class Spinner(object): +class Spinner: spinner_cycle: Iterator[str] disable: bool beep: bool @@ -18,13 +20,13 @@ class Spinner(object): stream: _Stream stop_running: threading.Event | None spin_thread: threading.Thread | None - def __init__(self, beep: bool, disable: bool, force: bool, stream: _Stream) -> None: ... + def __init__(self, beep: bool = False, disable: bool = False, force: bool = False, stream: _Stream = ...) -> None: ... def start(self) -> None: ... def stop(self) -> None: ... def init_spin(self) -> None: ... - def __enter__(self) -> Spinner: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> Literal[False]: ... -def spinner(beep: bool, disable: bool, force: bool, stream: _Stream) -> Spinner: ... +def spinner(beep: bool = False, disable: bool = False, force: bool = False, stream: _Stream = ...) -> Spinner: ... diff --git a/stubs/click-web/METADATA.toml b/stubs/click-web/METADATA.toml new file mode 100644 index 000000000000..b155c1e542e9 --- /dev/null +++ b/stubs/click-web/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.8.*" +upstream-repository = "https://github.com/fredrik-corneliusson/click-web" +dependencies = ["click>=8.0.0", "Flask>=2.3.2"] diff --git a/stubs/click-web/click_web/__init__.pyi b/stubs/click-web/click_web/__init__.pyi new file mode 100644 index 000000000000..3f97be32e833 --- /dev/null +++ b/stubs/click-web/click_web/__init__.pyi @@ -0,0 +1,16 @@ +import logging +import types +from _typeshed import Incomplete + +import click +import flask + +# This should be jinja2.Environment, but it does not have stubs and forbidden for requires in METADATA.toml +jinja_env: Incomplete +script_file: str | None +click_root_cmd: str | None +OUTPUT_FOLDER: str +_flask_app: flask.Flask | None +logger: logging.Logger | None + +def create_click_web_app(module: types.ModuleType, command: click.Command, root: str = "/") -> flask.Flask: ... diff --git a/stubs/click-web/click_web/exceptions.pyi b/stubs/click-web/click_web/exceptions.pyi new file mode 100644 index 000000000000..172a2026a871 --- /dev/null +++ b/stubs/click-web/click_web/exceptions.pyi @@ -0,0 +1,2 @@ +class ClickWebException(Exception): ... +class CommandNotFound(ClickWebException): ... diff --git a/stubs/selenium/selenium/webdriver/blackberry/__init__.pyi b/stubs/click-web/click_web/resources/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/blackberry/__init__.pyi rename to stubs/click-web/click_web/resources/__init__.pyi diff --git a/stubs/click-web/click_web/resources/cmd_exec.pyi b/stubs/click-web/click_web/resources/cmd_exec.pyi new file mode 100644 index 000000000000..b1121b450b8d --- /dev/null +++ b/stubs/click-web/click_web/resources/cmd_exec.pyi @@ -0,0 +1,93 @@ +import logging +from collections.abc import Generator +from typing import ClassVar, Final + +from flask import Response + +from .input_fields import FieldId + +logger: logging.Logger | None + +HTML_HEAD: Final[str] +HTML_TAIL: Final[str] + +class Executor: + RAW_CMD_PATH: ClassVar[str] + returncode: int | None + + def __init__(self) -> None: ... + def exec(self, command_path: str) -> Response: ... + def _exec_raw(self, command: list[str]) -> Response: ... # undocumented + def _exec_html(self, command_path: str) -> Response: ... # undocumented + def _run_script_and_generate_stream(self) -> Generator[str]: ... # undocumented + def _create_cmd_header(self, commands: list[CmdPart]) -> str: ... # undocumented + def _create_result_footer(self) -> Generator[str]: ... # undocumented + +def _get_download_link(field_info: FieldFileInfo) -> str: ... # undocumented + +class CommandLineRaw: + def __init__(self, script_file_path: str, command: str) -> None: ... + def append(self, part: str, secret: bool = False) -> None: ... + def get_commandline(self, obfuscate: bool = False) -> list[str]: ... + def get_download_field_infos(self) -> list[FieldInfo]: ... + def after_script_executed(self) -> None: ... + +class CommandLineForm: + command_line_bulder: FormToCommandLineBuilder + def __init__(self, script_file_path: str, commands: list[str]) -> None: ... + def append(self, part: str, secret: bool = False) -> None: ... + def get_commandline(self, obfuscate: bool = False) -> list[str]: ... + def get_download_field_infos(self) -> list[FieldInfo]: ... + def after_script_executed(self) -> None: ... + +def _get_python_interpreter() -> str: ... + +class CmdPart: + def __init__(self, part: str, secret: bool = False) -> None: ... + +class FormToCommandLineBuilder: + def __init__(self, command_line: CommandLineForm) -> None: ... + def add_command_args(self, command_index: int) -> None: ... + @staticmethod + def _is_option(cmd_option: str) -> bool: ... + def _process_option(self, field_info: FieldInfo) -> None: ... + +class FieldInfo: + param: FieldId + key: str + is_file: bool + cmd_opt: str + generate_download_link: bool + @staticmethod + def factory(key: str) -> FieldInfo: ... + def __init__(self, param: FieldId) -> None: ... + def before_script_execute(self) -> None: ... + def after_script_executed(self) -> None: ... + def __lt__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + +class FieldFileInfo(FieldInfo): + mode: str + generate_download_link: bool + link_name: str + file_path: str + def __init__(self, fimeta: FieldId) -> None: ... + def before_script_execute(self) -> None: ... + @classmethod + def temp_dir(cls) -> str: ... + def save(self) -> None: ... + +class FieldOutFileInfo(FieldFileInfo): + file_suffix: str + def __init__(self, fimeta: FieldId) -> None: ... + def save(self) -> None: ... + +class FieldPathInfo(FieldFileInfo): + def save(self) -> None: ... + def after_script_executed(self) -> None: ... + +class FieldPathOutInfo(FieldOutFileInfo): + def save(self) -> None: ... + def after_script_executed(self) -> None: ... + +def zip_folder(folder_path: str, out_folder: str, out_prefix: str) -> str: ... diff --git a/stubs/click-web/click_web/resources/cmd_form.pyi b/stubs/click-web/click_web/resources/cmd_form.pyi new file mode 100644 index 000000000000..d3f3ed573489 --- /dev/null +++ b/stubs/click-web/click_web/resources/cmd_form.pyi @@ -0,0 +1,13 @@ +from typing import Any, TypedDict, type_check_only + +import click + +@type_check_only +class _FormData(TypedDict): + command: click.Command + fields: list[dict[str, Any]] # each item is result of resources.input_fields.get_input_field() function + +def get_form_for(command_path: str) -> str: ... +def _get_commands_by_path(command_path: str) -> list[tuple[click.Context, click.Command]]: ... +def _generate_form_data(ctx_and_commands: list[tuple[click.Context, click.Command]]) -> list[_FormData]: ... +def _process_help(help_text: bool) -> str: ... diff --git a/stubs/click-web/click_web/resources/index.pyi b/stubs/click-web/click_web/resources/index.pyi new file mode 100644 index 000000000000..c0f3aebbbdf8 --- /dev/null +++ b/stubs/click-web/click_web/resources/index.pyi @@ -0,0 +1,9 @@ +from collections import OrderedDict +from typing import Any + +import click + +def index() -> str: ... +def _click_to_tree( + ctx: click.Context, node: click.Command, ancestors: list[click.Command] | None = None +) -> OrderedDict[str, Any]: ... diff --git a/stubs/click-web/click_web/resources/input_fields.pyi b/stubs/click-web/click_web/resources/input_fields.pyi new file mode 100644 index 000000000000..a1465ff56b70 --- /dev/null +++ b/stubs/click-web/click_web/resources/input_fields.pyi @@ -0,0 +1,81 @@ +from typing import Any, ClassVar, Final + +import click +from click_web.web_click_types import EmailParamType, PasswordParamType, TextAreaParamType + +class FieldId: + SEPARATOR: ClassVar[str] + command_index: int + param_index: int + param_type: str + click_type: str + nargs: int + form_type: str + name: str + key: str + + def __init__( + self, + command_index: int, + param_index: int, + param_type: str, + click_type: str, + nargs: int, + form_type: str, + name: str, + key: str | None = None, + ) -> None: ... + @classmethod + def from_string(cls, field_info_as_string: str) -> FieldId: ... + +class NotSupported(ValueError): ... + +class BaseInput: + param_type_cls: type[click.types.ParamType[Any]] | None + ctx: click.Context + param: click.Parameter + command_index: int + param_index: int + def __init__(self, ctx: click.Context, param: click.Parameter, command_index: int, param_index: int) -> None: ... + def is_supported(self) -> bool: ... + @property + def fields(self) -> dict[str, Any]: ... + @property + def type_attrs(self) -> dict[str, Any]: ... + def _to_cmd_line_name(self, name: str) -> str: ... + def _build_name(self, name: str) -> str: ... + +class ChoiceInput(BaseInput): + param_type_cls: type[click.Choice[Any]] + +class FlagInput(BaseInput): + param_type_cls: None + +class IntInput(BaseInput): + param_type_cls: type[click.types.IntParamType] + +class FloatInput(BaseInput): + param_type_cls: type[click.types.FloatParamType] + +class FolderInput(BaseInput): + param_type_cls: None + +class FileInput(BaseInput): + param_type_cls: None + +class EmailInput(BaseInput): + param_type_cls: type[EmailParamType] + +class PasswordInput(BaseInput): + param_type_cls: type[PasswordParamType] + +class TextAreaInput(BaseInput): + param_type_cls: type[TextAreaParamType] + +class DefaultInput(BaseInput): + param_type_cls: type[click.ParamType[Any]] + +INPUT_TYPES: Final[list[type[BaseInput]]] +_DEFAULT_INPUT: Final[list[type[DefaultInput]]] + +def get_input_field(ctx: click.Context, param: click.Parameter, command_index: int, param_index: int) -> dict[str, Any]: ... diff --git a/stubs/click-web/click_web/web_click_types.pyi b/stubs/click-web/click_web/web_click_types.pyi new file mode 100644 index 000000000000..db072f3cbc3a --- /dev/null +++ b/stubs/click-web/click_web/web_click_types.pyi @@ -0,0 +1,20 @@ +import re +from typing import Any, ClassVar, TypeVar + +import click + +_T = TypeVar("_T") + +class EmailParamType(click.ParamType[str]): + EMAIL_REGEX: ClassVar[re.Pattern[str]] + def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str: ... + +class PasswordParamType(click.ParamType[Any]): + def convert(self, value: _T, param: click.Parameter | None, ctx: click.Context | None) -> _T: ... + +class TextAreaParamType(click.ParamType[Any]): + def convert(self, value: _T, param: click.Parameter | None, ctx: click.Context | None) -> _T: ... + +EMAIL_TYPE: EmailParamType +PASSWORD_TYPE: PasswordParamType +TEXTAREA_TYPE: TextAreaParamType diff --git a/stubs/colorama/@tests/stubtest_allowlist.txt b/stubs/colorama/@tests/stubtest_allowlist.txt index e78dac9d627b..cee2f1962bb5 100644 --- a/stubs/colorama/@tests/stubtest_allowlist.txt +++ b/stubs/colorama/@tests/stubtest_allowlist.txt @@ -1,3 +1,4 @@ +# These are defined as ints, but later are converted to strings via magic: colorama.ansi.AnsiBack.BLACK colorama.ansi.AnsiBack.BLUE colorama.ansi.AnsiBack.CYAN @@ -36,5 +37,10 @@ colorama.ansi.AnsiStyle.BRIGHT colorama.ansi.AnsiStyle.DIM colorama.ansi.AnsiStyle.NORMAL colorama.ansi.AnsiStyle.RESET_ALL + +# These are defined as None, but on initialization are set to correct values: colorama.initialise.wrapped_stderr colorama.initialise.wrapped_stdout + +# Not planning on writing stubs for tests: +colorama.tests.* diff --git a/stubs/colorama/@tests/stubtest_allowlist_linux.txt b/stubs/colorama/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..8bd292ef088e --- /dev/null +++ b/stubs/colorama/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,4 @@ +# These are only available on Windows: +colorama.winterm.WinColor +colorama.winterm.WinStyle +colorama.winterm.WinTerm diff --git a/stubs/colorama/METADATA.toml b/stubs/colorama/METADATA.toml index cea6c7b21c6f..42172a31b734 100644 --- a/stubs/colorama/METADATA.toml +++ b/stubs/colorama/METADATA.toml @@ -1,2 +1,5 @@ version = "0.4.*" -python2 = true \ No newline at end of file +upstream-repository = "https://github.com/tartley/colorama" + +[tool.stubtest] +ci-platforms = ["linux", "win32"] diff --git a/stubs/colorama/colorama/__init__.pyi b/stubs/colorama/colorama/__init__.pyi index 1fc778d8a8ea..e6d15ec71ddb 100644 --- a/stubs/colorama/colorama/__init__.pyi +++ b/stubs/colorama/colorama/__init__.pyi @@ -1,3 +1,9 @@ from .ansi import Back as Back, Cursor as Cursor, Fore as Fore, Style as Style from .ansitowin32 import AnsiToWin32 as AnsiToWin32 -from .initialise import colorama_text as colorama_text, deinit as deinit, init as init, reinit as reinit +from .initialise import ( + colorama_text as colorama_text, + deinit as deinit, + init as init, + just_fix_windows_console as just_fix_windows_console, + reinit as reinit, +) diff --git a/stubs/colorama/colorama/ansi.pyi b/stubs/colorama/colorama/ansi.pyi index 7224a7a81c72..3b857496e6d3 100644 --- a/stubs/colorama/colorama/ansi.pyi +++ b/stubs/colorama/colorama/ansi.pyi @@ -4,64 +4,64 @@ BEL: str def code_to_chars(code: int) -> str: ... def set_title(title: str) -> str: ... -def clear_screen(mode: int = ...) -> str: ... -def clear_line(mode: int = ...) -> str: ... +def clear_screen(mode: int = 2) -> str: ... +def clear_line(mode: int = 2) -> str: ... class AnsiCodes: def __init__(self) -> None: ... class AnsiCursor: - def UP(self, n: int = ...) -> str: ... - def DOWN(self, n: int = ...) -> str: ... - def FORWARD(self, n: int = ...) -> str: ... - def BACK(self, n: int = ...) -> str: ... - def POS(self, x: int = ..., y: int = ...) -> str: ... + def UP(self, n: int = 1) -> str: ... + def DOWN(self, n: int = 1) -> str: ... + def FORWARD(self, n: int = 1) -> str: ... + def BACK(self, n: int = 1) -> str: ... + def POS(self, x: int = 1, y: int = 1) -> str: ... # All attributes in the following classes are string in instances and int in the class. # We use str since that is the common case for users. class AnsiFore(AnsiCodes): - BLACK: str = ... - RED: str = ... - GREEN: str = ... - YELLOW: str = ... - BLUE: str = ... - MAGENTA: str = ... - CYAN: str = ... - WHITE: str = ... - RESET: str = ... - LIGHTBLACK_EX: str = ... - LIGHTRED_EX: str = ... - LIGHTGREEN_EX: str = ... - LIGHTYELLOW_EX: str = ... - LIGHTBLUE_EX: str = ... - LIGHTMAGENTA_EX: str = ... - LIGHTCYAN_EX: str = ... - LIGHTWHITE_EX: str = ... + BLACK: str + RED: str + GREEN: str + YELLOW: str + BLUE: str + MAGENTA: str + CYAN: str + WHITE: str + RESET: str + LIGHTBLACK_EX: str + LIGHTRED_EX: str + LIGHTGREEN_EX: str + LIGHTYELLOW_EX: str + LIGHTBLUE_EX: str + LIGHTMAGENTA_EX: str + LIGHTCYAN_EX: str + LIGHTWHITE_EX: str class AnsiBack(AnsiCodes): - BLACK: str = ... - RED: str = ... - GREEN: str = ... - YELLOW: str = ... - BLUE: str = ... - MAGENTA: str = ... - CYAN: str = ... - WHITE: str = ... - RESET: str = ... - LIGHTBLACK_EX: str = ... - LIGHTRED_EX: str = ... - LIGHTGREEN_EX: str = ... - LIGHTYELLOW_EX: str = ... - LIGHTBLUE_EX: str = ... - LIGHTMAGENTA_EX: str = ... - LIGHTCYAN_EX: str = ... - LIGHTWHITE_EX: str = ... + BLACK: str + RED: str + GREEN: str + YELLOW: str + BLUE: str + MAGENTA: str + CYAN: str + WHITE: str + RESET: str + LIGHTBLACK_EX: str + LIGHTRED_EX: str + LIGHTGREEN_EX: str + LIGHTYELLOW_EX: str + LIGHTBLUE_EX: str + LIGHTMAGENTA_EX: str + LIGHTCYAN_EX: str + LIGHTWHITE_EX: str class AnsiStyle(AnsiCodes): - BRIGHT: str = ... - DIM: str = ... - NORMAL: str = ... - RESET_ALL: str = ... + BRIGHT: str + DIM: str + NORMAL: str + RESET_ALL: str Fore: AnsiFore Back: AnsiBack diff --git a/stubs/colorama/colorama/ansitowin32.pyi b/stubs/colorama/colorama/ansitowin32.pyi index 117fe8f6265c..e32fec9d33c3 100644 --- a/stubs/colorama/colorama/ansitowin32.pyi +++ b/stubs/colorama/colorama/ansitowin32.pyi @@ -1,6 +1,9 @@ import sys from _typeshed import SupportsWrite -from typing import Any, Callable, Dict, Optional, Pattern, Sequence, TextIO, Tuple, Union +from collections.abc import Callable, Sequence +from re import Pattern +from types import TracebackType +from typing import Any, ClassVar, TextIO, TypeAlias if sys.platform == "win32": from .winterm import WinTerm @@ -13,26 +16,30 @@ class StreamWrapper: def __init__(self, wrapped: TextIO, converter: SupportsWrite[str]) -> None: ... def __getattr__(self, name: str) -> Any: ... def __enter__(self, *args: object, **kwargs: object) -> TextIO: ... - def __exit__(self, *args: Any, **kwargs: Any) -> None: ... + def __exit__( + self, t: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, /, **kwargs: Any + ) -> None: ... def write(self, text: str) -> None: ... def isatty(self) -> bool: ... @property def closed(self) -> bool: ... -_WinTermCall = Callable[[Optional[int], bool, bool], None] -_WinTermCallDict = Dict[int, Union[Tuple[_WinTermCall], Tuple[_WinTermCall, int], Tuple[_WinTermCall, int, bool]]] +_WinTermCall: TypeAlias = Callable[[int | None, bool, bool], None] +_WinTermCallDict: TypeAlias = dict[int, tuple[_WinTermCall] | tuple[_WinTermCall, int] | tuple[_WinTermCall, int, bool]] class AnsiToWin32: - ANSI_CSI_RE: Pattern[str] = ... - ANSI_OSC_RE: Pattern[str] = ... - wrapped: TextIO = ... - autoreset: bool = ... - stream: StreamWrapper = ... - strip: bool = ... - convert: bool = ... - win32_calls: _WinTermCallDict = ... - on_stderr: bool = ... - def __init__(self, wrapped: TextIO, convert: bool | None = ..., strip: bool | None = ..., autoreset: bool = ...) -> None: ... + ANSI_CSI_RE: ClassVar[Pattern[str]] + ANSI_OSC_RE: ClassVar[Pattern[str]] + wrapped: TextIO + autoreset: bool + stream: StreamWrapper + strip: bool + convert: bool + win32_calls: _WinTermCallDict + on_stderr: bool + def __init__( + self, wrapped: TextIO, convert: bool | None = None, strip: bool | None = None, autoreset: bool = False + ) -> None: ... def should_wrap(self) -> bool: ... def get_win32_calls(self) -> _WinTermCallDict: ... def write(self, text: str) -> None: ... @@ -40,6 +47,7 @@ class AnsiToWin32: def write_and_convert(self, text: str) -> None: ... def write_plain_text(self, text: str, start: int, end: int) -> None: ... def convert_ansi(self, paramstring: str, command: str) -> None: ... - def extract_params(self, command: str, paramstring: str) -> Tuple[int, ...]: ... + def extract_params(self, command: str, paramstring: str) -> tuple[int, ...]: ... def call_win32(self, command: str, params: Sequence[int]) -> None: ... def convert_osc(self, text: str) -> str: ... + def flush(self) -> None: ... diff --git a/stubs/colorama/colorama/initialise.pyi b/stubs/colorama/colorama/initialise.pyi index f76f826e0925..028b981307c8 100644 --- a/stubs/colorama/colorama/initialise.pyi +++ b/stubs/colorama/colorama/initialise.pyi @@ -1,18 +1,23 @@ -from typing import Any, ContextManager, TextIO +from contextlib import AbstractContextManager +from typing import Any, TextIO, TypeVar from .ansitowin32 import StreamWrapper +_TextIOT = TypeVar("_TextIOT", bound=TextIO) + orig_stdout: TextIO | None orig_stderr: TextIO | None wrapped_stdout: TextIO | StreamWrapper wrapped_stderr: TextIO | StreamWrapper atexit_done: bool +fixed_windows_console: bool def reset_all() -> None: ... -def init(autoreset: bool = ..., convert: bool | None = ..., strip: bool | None = ..., wrap: bool = ...) -> None: ... +def init(autoreset: bool = False, convert: bool | None = None, strip: bool | None = None, wrap: bool = True) -> None: ... def deinit() -> None: ... -def colorama_text(*args: Any, **kwargs: Any) -> ContextManager[None]: ... +def colorama_text(*args: Any, **kwargs: Any) -> AbstractContextManager[None]: ... def reinit() -> None: ... def wrap_stream( - stream: TextIO, convert: bool | None, strip: bool | None, autoreset: bool, wrap: bool -) -> TextIO | StreamWrapper: ... + stream: _TextIOT, convert: bool | None, strip: bool | None, autoreset: bool, wrap: bool +) -> _TextIOT | StreamWrapper: ... +def just_fix_windows_console() -> None: ... diff --git a/stubs/colorama/colorama/win32.pyi b/stubs/colorama/colorama/win32.pyi index 37e6a0b99f9d..f1bcefe7063a 100644 --- a/stubs/colorama/colorama/win32.pyi +++ b/stubs/colorama/colorama/win32.pyi @@ -1,29 +1,33 @@ import sys -from typing import Callable -from typing_extensions import Literal +from collections.abc import Callable +from typing import Literal STDOUT: Literal[-11] STDERR: Literal[-12] +ENABLE_VIRTUAL_TERMINAL_PROCESSING: int if sys.platform == "win32": from ctypes import LibraryLoader, Structure, WinDLL, wintypes windll: LibraryLoader[WinDLL] COORD = wintypes._COORD + class CONSOLE_SCREEN_BUFFER_INFO(Structure): dwSize: COORD dwCursorPosition: COORD wAttributes: wintypes.WORD srWindow: wintypes.SMALL_RECT dwMaximumWindowSize: COORD - def __str__(self) -> str: ... + def winapi_test() -> bool: ... - def GetConsoleScreenBufferInfo(stream_id: int = ...) -> CONSOLE_SCREEN_BUFFER_INFO: ... + def GetConsoleScreenBufferInfo(stream_id: int = -11) -> CONSOLE_SCREEN_BUFFER_INFO: ... def SetConsoleTextAttribute(stream_id: int, attrs: wintypes.WORD) -> wintypes.BOOL: ... - def SetConsoleCursorPosition(stream_id: int, position: COORD, adjust: bool = ...) -> wintypes.BOOL: ... + def SetConsoleCursorPosition(stream_id: int, position: COORD, adjust: bool = True) -> wintypes.BOOL: ... def FillConsoleOutputCharacter(stream_id: int, char: str, length: int, start: COORD) -> int: ... def FillConsoleOutputAttribute(stream_id: int, attr: int, length: int, start: COORD) -> wintypes.BOOL: ... def SetConsoleTitle(title: str) -> wintypes.BOOL: ... + def GetConsoleMode(handle: int) -> int: ... + def SetConsoleMode(handle: int, mode: int) -> None: ... else: windll: None diff --git a/stubs/colorama/colorama/winterm.pyi b/stubs/colorama/colorama/winterm.pyi index a827463c000c..7762e0236262 100644 --- a/stubs/colorama/colorama/winterm.pyi +++ b/stubs/colorama/colorama/winterm.pyi @@ -1,33 +1,38 @@ import sys +from typing import Final if sys.platform == "win32": - from . import win32 + class WinColor: - BLACK: int = ... - BLUE: int = ... - GREEN: int = ... - CYAN: int = ... - RED: int = ... - MAGENTA: int = ... - YELLOW: int = ... - GREY: int = ... + BLACK: Final = 0 + BLUE: Final = 1 + GREEN: Final = 2 + CYAN: Final = 3 + RED: Final = 4 + MAGENTA: Final = 5 + YELLOW: Final = 6 + GREY: Final = 7 + class WinStyle: - NORMAL: int = ... - BRIGHT: int = ... - BRIGHT_BACKGROUND: int = ... + NORMAL: Final = 0x00 + BRIGHT: Final = 0x08 + BRIGHT_BACKGROUND: Final = 0x80 + class WinTerm: def __init__(self) -> None: ... def get_attrs(self) -> int: ... def set_attrs(self, value: int) -> None: ... - def reset_all(self, on_stderr: bool | None = ...) -> None: ... - def fore(self, fore: int | None = ..., light: bool = ..., on_stderr: bool = ...) -> None: ... - def back(self, back: int | None = ..., light: bool = ..., on_stderr: bool = ...) -> None: ... - def style(self, style: int | None = ..., on_stderr: bool = ...) -> None: ... - def set_console(self, attrs: int | None = ..., on_stderr: bool = ...) -> None: ... + def reset_all(self, on_stderr: bool | None = None) -> None: ... + def fore(self, fore: int | None = None, light: bool = False, on_stderr: bool = False) -> None: ... + def back(self, back: int | None = None, light: bool = False, on_stderr: bool = False) -> None: ... + def style(self, style: int | None = None, on_stderr: bool = False) -> None: ... + def set_console(self, attrs: int | None = None, on_stderr: bool = False) -> None: ... def get_position(self, handle: int) -> win32.COORD: ... - def set_cursor_position(self, position: win32.COORD | None = ..., on_stderr: bool = ...) -> None: ... - def cursor_adjust(self, x: int, y: int, on_stderr: bool = ...) -> None: ... - def erase_screen(self, mode: int = ..., on_stderr: bool = ...) -> None: ... - def erase_line(self, mode: int = ..., on_stderr: bool = ...) -> None: ... + def set_cursor_position(self, position: win32.COORD | None = None, on_stderr: bool = False) -> None: ... + def cursor_adjust(self, x: int, y: int, on_stderr: bool = False) -> None: ... + def erase_screen(self, mode: int = 0, on_stderr: bool = False) -> None: ... + def erase_line(self, mode: int = 0, on_stderr: bool = False) -> None: ... def set_title(self, title: str) -> None: ... + +def enable_vt_processing(fd: int) -> bool: ... diff --git a/stubs/colorful/METADATA.toml b/stubs/colorful/METADATA.toml new file mode 100644 index 000000000000..51d16a937052 --- /dev/null +++ b/stubs/colorful/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.5.*" +upstream-repository = "https://github.com/timofurrer/colorful" diff --git a/stubs/selenium/selenium/webdriver/chrome/__init__.pyi b/stubs/colorful/colorful/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/chrome/__init__.pyi rename to stubs/colorful/colorful/__init__.pyi diff --git a/stubs/colorful/colorful/ansi.pyi b/stubs/colorful/colorful/ansi.pyi new file mode 100644 index 000000000000..ed25609c6766 --- /dev/null +++ b/stubs/colorful/colorful/ansi.pyi @@ -0,0 +1,14 @@ +from typing import Final + +MODIFIERS: Final[dict[str, tuple[int, int]]] +MODIFIER_RESET_OFFSET: Final[int] +FOREGROUND_COLOR_OFFSET: Final[int] +BACKGROUND_COLOR_OFFSET: Final[int] +COLOR_CLOSE_OFFSET: Final[int] +CSI: Final[str] +ANSI_ESCAPE_CODE: Final[str] +NEST_PLACEHOLDER: Final[str] + +def round(value: float) -> int: ... +def rgb_to_ansi256(r: int, g: int, b: int) -> int: ... +def rgb_to_ansi16(r: int, g: int, b: int, use_bright: bool = False) -> int: ... diff --git a/stubs/colorful/colorful/colors.pyi b/stubs/colorful/colorful/colors.pyi new file mode 100644 index 000000000000..8865b2357284 --- /dev/null +++ b/stubs/colorful/colorful/colors.pyi @@ -0,0 +1,6 @@ +from _typeshed import SupportsItems + +def parse_colors(path: str) -> SupportsItems[str, str | tuple[int, int, int]]: ... +def parse_rgb_txt_file(path: str) -> SupportsItems[str, str | tuple[int, int, int]]: ... +def parse_json_color_file(path: str) -> dict[str, str]: ... +def sanitize_color_palette(colorpalette: SupportsItems[str, str | tuple[int, int, int]]) -> dict[str, tuple[int, int, int]]: ... diff --git a/stubs/colorful/colorful/core.pyi b/stubs/colorful/colorful/core.pyi new file mode 100644 index 000000000000..8fe0a797f7f6 --- /dev/null +++ b/stubs/colorful/colorful/core.pyi @@ -0,0 +1,104 @@ +from _typeshed import SupportsGetItem, SupportsItems, SupportsWrite + +# This module defines a function "str()", which is why "str" can't be used +# as a type annotation or type alias. +from builtins import str as _str +from collections.abc import Iterator +from typing import Any, Final, Literal, TypeAlias +from typing_extensions import LiteralString, Self + +# Custom type helpers +_ColorModeType: TypeAlias = Literal[0, 8, 16, 256, 16777215] +_PaletteType: TypeAlias = dict[_str, _str] | dict[_str, tuple[int, int, int]] | dict[_str, _str | tuple[int, int, int]] +_StyleType: TypeAlias = tuple[_str, _str] + +DEFAULT_RGB_TXT_PATH: Final[_str] +COLOR_PALETTE: Final[dict[_str, _str]] +COLORNAMES_COLORS_PATH: Final[_str] + +class ColorfulError(Exception): ... +class ColorfulAttributeError(AttributeError, ColorfulError): ... + +def translate_rgb_to_ansi_code(red: int, green: int, blue: int, offset: int, colormode: _ColorModeType) -> _str: ... +def translate_colorname_to_ansi_code( + colorname: _str, offset: int, colormode: _ColorModeType, colorpalette: SupportsGetItem[_str, _str | tuple[int, int, int]] +) -> _str: ... +def resolve_modifier_to_ansi_code(modifiername: _str, colormode: _ColorModeType) -> _str: ... +def translate_style( + style: _str, colormode: _ColorModeType, colorpalette: SupportsGetItem[_str, _str | tuple[int, int, int]] +) -> _str: ... +def style_string(string: _str, ansi_style: _StyleType, colormode: _ColorModeType, nested: bool = False) -> _str: ... + +class ColorfulString: + orig_string: _str + styled_string: _str + colorful_ctx: Colorful + def __init__(self, orig_string: _str, styled_string: _str, colorful_ctx: Colorful) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_str]: ... + def __add__(self, other: _str | ColorfulString) -> Self: ... + def __iadd__(self, other: _str | ColorfulString) -> Self: ... + def __radd__(self, other: _str | ColorfulString) -> Self: ... + def __mul__(self, other: _str) -> Self: ... + def __format__(self, format_spec: _str) -> _str: ... + # Forwards item access to styled_string (a str). + def __getattr__(self, name: _str) -> Any: ... + +class Colorful: + NO_COLORS: Final[int] + ANSI_8_COLORS: Final[int] + ANSI_16_COLORS: Final[int] + ANSI_256_COLORS: Final[int] + TRUE_COLORS: Final[int] + COLORNAMES_COLORS = COLORNAMES_COLORS_PATH + close_fg_color: Final[_str] + close_bg_color: Final[_str] + no_bold: Final[_str] + no_dimmed: Final[_str] + no_italic: Final[_str] + no_underlined: Final[_str] + no_blinkslow: Final[_str] + no_blinkrapid: Final[_str] + no_inversed: Final[_str] + no_concealed: Final[_str] + no_struckthrough: Final[_str] + colormode: _ColorModeType + def __init__(self, colormode: _ColorModeType | None = None, colorpalette: _str | _PaletteType | None = None) -> None: ... + + @property + def colorpalette(self) -> SupportsItems[_str, _str | tuple[int, int, int]] | None: ... + @colorpalette.setter + def colorpalette(self, colorpalette: _str | _PaletteType) -> None: ... + + def setup( + self, + colormode: _ColorModeType | None = None, + colorpalette: _str | _PaletteType | None = None, + extend_colors: bool = False, + ) -> None: ... + def disable(self) -> None: ... + def use_8_ansi_colors(self) -> None: ... + def use_16_ansi_colors(self) -> None: ... + def use_256_ansi_colors(self) -> None: ... + def use_true_colors(self) -> None: ... + def use_palette(self, colorpalette: _str | _PaletteType) -> None: ... + def update_palette(self, colorpalette: _str | _PaletteType) -> None: ... + def use_style(self, style_name: _str) -> None: ... + def format(self, string: _str, *args: LiteralString, **kwargs: LiteralString) -> _str: ... + def str(self, string: _str) -> ColorfulString: ... + def print( + self, *objects: object, sep: _str = " ", end: _str = "\n", file: SupportsWrite[_str] | None = None, flush: bool = False + ) -> None: ... + + class ColorfulStyle: + colormode: _ColorModeType + colorful_ctx: Colorful + def __init__(self, style: _StyleType, colormode: _ColorModeType, colorful_ctx: Colorful) -> None: ... + def evaluate(self, string: _str, nested: bool = False) -> ColorfulString: ... + def __and__(self, other: Self) -> Self: ... + def __call__(self, string: _str, nested: bool = False) -> ColorfulString: ... + def __or__(self, other) -> ColorfulString: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + + def __getattr__(self, name: _str) -> ColorfulStyle: ... diff --git a/stubs/colorful/colorful/styles.pyi b/stubs/colorful/colorful/styles.pyi new file mode 100644 index 000000000000..8a0fcbe01789 --- /dev/null +++ b/stubs/colorful/colorful/styles.pyi @@ -0,0 +1,4 @@ +from typing import Final + +SOLARIZED: Final[dict[str, str]] +MONOKAI: Final[dict[str, str]] diff --git a/stubs/colorful/colorful/terminal.pyi b/stubs/colorful/colorful/terminal.pyi new file mode 100644 index 000000000000..3445996c485b --- /dev/null +++ b/stubs/colorful/colorful/terminal.pyi @@ -0,0 +1,16 @@ +from typing import Final, Protocol, overload, type_check_only + +@type_check_only +class _SupportsGet(Protocol): + @overload + def get(self, name: str, /) -> str | None: ... + @overload + def get(self, name: str, default: str, /) -> str: ... + +NO_COLORS: Final[int] +ANSI_8_COLORS: Final[int] +ANSI_16_COLORS: Final[int] +ANSI_256_COLORS: Final[int] +TRUE_COLORS: Final[int] + +def detect_color_support(env: _SupportsGet) -> int: ... diff --git a/stubs/colorful/colorful/utils.pyi b/stubs/colorful/colorful/utils.pyi new file mode 100644 index 000000000000..a4156beb64f9 --- /dev/null +++ b/stubs/colorful/colorful/utils.pyi @@ -0,0 +1,2 @@ +def hex_to_rgb(value: str) -> tuple[int, int, int]: ... +def check_hex(value: str) -> None: ... diff --git a/stubs/commonmark/METADATA.toml b/stubs/commonmark/METADATA.toml deleted file mode 100644 index 51e869b47983..000000000000 --- a/stubs/commonmark/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "0.9.*" diff --git a/stubs/commonmark/commonmark/__init__.pyi b/stubs/commonmark/commonmark/__init__.pyi deleted file mode 100644 index 9d6feae3d8d4..000000000000 --- a/stubs/commonmark/commonmark/__init__.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from commonmark.blocks import Parser as Parser -from commonmark.dump import dumpAST as dumpAST, dumpJSON as dumpJSON -from commonmark.main import commonmark as commonmark -from commonmark.render.html import HtmlRenderer as HtmlRenderer -from commonmark.render.rst import ReStructuredTextRenderer as ReStructuredTextRenderer diff --git a/stubs/commonmark/commonmark/blocks.pyi b/stubs/commonmark/commonmark/blocks.pyi deleted file mode 100644 index 25504c4b9eae..000000000000 --- a/stubs/commonmark/commonmark/blocks.pyi +++ /dev/null @@ -1,166 +0,0 @@ -from typing import Any - -CODE_INDENT: int -reHtmlBlockOpen: Any -reHtmlBlockClose: Any -reThematicBreak: Any -reMaybeSpecial: Any -reNonSpace: Any -reBulletListMarker: Any -reOrderedListMarker: Any -reATXHeadingMarker: Any -reCodeFence: Any -reClosingCodeFence: Any -reSetextHeadingLine: Any -reLineEnding: Any - -def is_blank(s): ... -def is_space_or_tab(s): ... -def peek(ln, pos): ... -def ends_with_blank_line(block): ... -def parse_list_marker(parser, container): ... -def lists_match(list_data, item_data): ... - -class Block: - accepts_lines: Any - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...) -> None: ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t) -> None: ... - -class Document(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class List(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class BlockQuote(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class Item(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class Heading(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class ThematicBreak(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class CodeBlock(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class HtmlBlock(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class Paragraph(Block): - accepts_lines: bool - @staticmethod - def continue_(parser: Any | None = ..., container: Any | None = ...): ... - @staticmethod - def finalize(parser: Any | None = ..., block: Any | None = ...) -> None: ... - @staticmethod - def can_contain(t): ... - -class BlockStarts: - METHODS: Any - @staticmethod - def block_quote(parser, container: Any | None = ...): ... - @staticmethod - def atx_heading(parser, container: Any | None = ...): ... - @staticmethod - def fenced_code_block(parser, container: Any | None = ...): ... - @staticmethod - def html_block(parser, container: Any | None = ...): ... - @staticmethod - def setext_heading(parser, container: Any | None = ...): ... - @staticmethod - def thematic_break(parser, container: Any | None = ...): ... - @staticmethod - def list_item(parser, container: Any | None = ...): ... - @staticmethod - def indented_code_block(parser, container: Any | None = ...): ... - -class Parser: - doc: Any - block_starts: Any - tip: Any - oldtip: Any - current_line: str - line_number: int - offset: int - column: int - next_nonspace: int - next_nonspace_column: int - indent: int - indented: bool - blank: bool - partially_consumed_tab: bool - all_closed: bool - last_matched_container: Any - refmap: Any - last_line_length: int - inline_parser: Any - options: Any - def __init__(self, options=...) -> None: ... - def add_line(self) -> None: ... - def add_child(self, tag, offset): ... - def close_unmatched_blocks(self) -> None: ... - def find_next_nonspace(self) -> None: ... - def advance_next_nonspace(self) -> None: ... - def advance_offset(self, count, columns) -> None: ... - def incorporate_line(self, ln) -> None: ... - def finalize(self, block, line_number) -> None: ... - def process_inlines(self, block) -> None: ... - def parse(self, my_input): ... - -CAMEL_RE: Any diff --git a/stubs/commonmark/commonmark/cmark.pyi b/stubs/commonmark/commonmark/cmark.pyi deleted file mode 100644 index 7e7363e797f3..000000000000 --- a/stubs/commonmark/commonmark/cmark.pyi +++ /dev/null @@ -1 +0,0 @@ -def main() -> None: ... diff --git a/stubs/commonmark/commonmark/common.pyi b/stubs/commonmark/commonmark/common.pyi deleted file mode 100644 index c55a67969ad1..000000000000 --- a/stubs/commonmark/commonmark/common.pyi +++ /dev/null @@ -1,35 +0,0 @@ -import html -from typing import Any - -HTMLunescape = html.unescape -ENTITY: str -TAGNAME: str -ATTRIBUTENAME: str -UNQUOTEDVALUE: str -SINGLEQUOTEDVALUE: str -DOUBLEQUOTEDVALUE: str -ATTRIBUTEVALUE: Any -ATTRIBUTEVALUESPEC: Any -ATTRIBUTE: Any -OPENTAG: Any -CLOSETAG: Any -HTMLCOMMENT: str -PROCESSINGINSTRUCTION: str -DECLARATION: Any -CDATA: str -HTMLTAG: Any -reHtmlTag: Any -reBackslashOrAmp: Any -ESCAPABLE: str -reEntityOrEscapedChar: Any -XMLSPECIAL: str -reXmlSpecial: Any - -def unescape_char(s): ... -def unescape_string(s): ... -def normalize_uri(uri): ... - -UNSAFE_MAP: Any - -def replace_unsafe_char(s): ... -def escape_xml(s): ... diff --git a/stubs/commonmark/commonmark/dump.pyi b/stubs/commonmark/commonmark/dump.pyi deleted file mode 100644 index 821fb95b7f5d..000000000000 --- a/stubs/commonmark/commonmark/dump.pyi +++ /dev/null @@ -1,3 +0,0 @@ -def prepare(obj, topnode: bool = ...): ... -def dumpJSON(obj): ... -def dumpAST(obj, ind: int = ..., topnode: bool = ...) -> None: ... diff --git a/stubs/commonmark/commonmark/entitytrans.pyi b/stubs/commonmark/commonmark/entitytrans.pyi deleted file mode 100644 index b8b0efae5fc8..000000000000 --- a/stubs/commonmark/commonmark/entitytrans.pyi +++ /dev/null @@ -1 +0,0 @@ -def _unescape(s: str) -> str: ... diff --git a/stubs/commonmark/commonmark/inlines.pyi b/stubs/commonmark/commonmark/inlines.pyi deleted file mode 100644 index e53f22a10cf8..000000000000 --- a/stubs/commonmark/commonmark/inlines.pyi +++ /dev/null @@ -1,65 +0,0 @@ -import html -from typing import Any - -HTMLunescape = html.unescape -ESCAPED_CHAR: Any -rePunctuation: Any -reLinkTitle: Any -reLinkDestinationBraces: Any -reEscapable: Any -reEntityHere: Any -reTicks: Any -reTicksHere: Any -reEllipses: Any -reDash: Any -reEmailAutolink: Any -reAutolink: Any -reSpnl: Any -reWhitespaceChar: Any -reWhitespace: Any -reUnicodeWhitespaceChar: Any -reFinalSpace: Any -reInitialSpace: Any -reSpaceAtEndOfLine: Any -reLinkLabel: Any -reMain: Any - -def text(s): ... -def smart_dashes(chars): ... - -class InlineParser: - subject: str - brackets: Any - pos: int - refmap: Any - options: Any - def __init__(self, options=...) -> None: ... - def match(self, regexString): ... - def peek(self): ... - def spnl(self): ... - def parseBackticks(self, block): ... - def parseBackslash(self, block): ... - def parseAutolink(self, block): ... - def parseHtmlTag(self, block): ... - def scanDelims(self, c): ... - delimiters: Any - def handleDelim(self, cc, block): ... - def removeDelimiter(self, delim) -> None: ... - @staticmethod - def removeDelimitersBetween(bottom, top) -> None: ... - def processEmphasis(self, stack_bottom) -> None: ... - def parseLinkTitle(self): ... - def parseLinkDestination(self): ... - def parseLinkLabel(self): ... - def parseOpenBracket(self, block): ... - def parseBang(self, block): ... - def parseCloseBracket(self, block): ... - def addBracket(self, node, index, image) -> None: ... - def removeBracket(self) -> None: ... - def parseEntity(self, block): ... - def parseString(self, block): ... - def parseNewline(self, block): ... - def parseReference(self, s, refmap): ... - def parseInline(self, block): ... - def parseInlines(self, block) -> None: ... - parse: Any diff --git a/stubs/commonmark/commonmark/main.pyi b/stubs/commonmark/commonmark/main.pyi deleted file mode 100644 index c7c6b4219ea0..000000000000 --- a/stubs/commonmark/commonmark/main.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing_extensions import Literal - -def commonmark(text: str, format: Literal["html", "json", "ast", "rst"] = ...) -> str: ... diff --git a/stubs/commonmark/commonmark/node.pyi b/stubs/commonmark/commonmark/node.pyi deleted file mode 100644 index 8760df613cd1..000000000000 --- a/stubs/commonmark/commonmark/node.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any - -reContainer: Any - -def is_container(node): ... - -class NodeWalker: - current: Any - root: Any - entering: bool - def __init__(self, root) -> None: ... - def __next__(self): ... - next: Any - def __iter__(self): ... - def nxt(self): ... - def resume_at(self, node, entering) -> None: ... - -class Node: - t: Any - parent: Any - first_child: Any - last_child: Any - prv: Any - nxt: Any - sourcepos: Any - last_line_blank: bool - last_line_checked: bool - is_open: bool - string_content: str - literal: Any - list_data: Any - info: Any - destination: Any - title: Any - is_fenced: bool - fence_char: Any - fence_length: int - fence_offset: Any - level: Any - on_enter: Any - on_exit: Any - def __init__(self, node_type, sourcepos) -> None: ... - def pretty(self) -> None: ... - def normalize(self) -> None: ... - def is_container(self): ... - def append_child(self, child) -> None: ... - def prepend_child(self, child) -> None: ... - def unlink(self) -> None: ... - def insert_after(self, sibling) -> None: ... - def insert_before(self, sibling) -> None: ... - def walker(self): ... diff --git a/stubs/commonmark/commonmark/normalize_reference.pyi b/stubs/commonmark/commonmark/normalize_reference.pyi deleted file mode 100644 index 96a3414d109b..000000000000 --- a/stubs/commonmark/commonmark/normalize_reference.pyi +++ /dev/null @@ -1 +0,0 @@ -def normalize_reference(string): ... diff --git a/stubs/commonmark/commonmark/render/html.pyi b/stubs/commonmark/commonmark/render/html.pyi deleted file mode 100644 index b98864128d11..000000000000 --- a/stubs/commonmark/commonmark/render/html.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Any - -from commonmark.render.renderer import Renderer - -reUnsafeProtocol: Any -reSafeDataProtocol: Any - -def potentially_unsafe(url): ... - -class HtmlRenderer(Renderer): - disable_tags: int - last_out: str - options: Any - def __init__(self, options=...) -> None: ... - def escape(self, text): ... - def tag(self, name, attrs: Any | None = ..., selfclosing: Any | None = ...) -> None: ... - def text(self, node, entering: Any | None = ...) -> None: ... - def softbreak(self, node: Any | None = ..., entering: Any | None = ...) -> None: ... - def linebreak(self, node: Any | None = ..., entering: Any | None = ...) -> None: ... - def link(self, node, entering) -> None: ... - def image(self, node, entering) -> None: ... - def emph(self, node, entering) -> None: ... - def strong(self, node, entering) -> None: ... - def paragraph(self, node, entering) -> None: ... - def heading(self, node, entering) -> None: ... - def code(self, node, entering) -> None: ... - def code_block(self, node, entering) -> None: ... - def thematic_break(self, node, entering) -> None: ... - def block_quote(self, node, entering) -> None: ... - def list(self, node, entering) -> None: ... - def item(self, node, entering) -> None: ... - def html_inline(self, node, entering) -> None: ... - def html_block(self, node, entering) -> None: ... - def custom_inline(self, node, entering) -> None: ... - def custom_block(self, node, entering) -> None: ... - def out(self, s) -> None: ... - def attrs(self, node): ... diff --git a/stubs/commonmark/commonmark/render/renderer.pyi b/stubs/commonmark/commonmark/render/renderer.pyi deleted file mode 100644 index b8e2e46f0969..000000000000 --- a/stubs/commonmark/commonmark/render/renderer.pyi +++ /dev/null @@ -1,7 +0,0 @@ -class Renderer: - buf: str - last_out: str - def render(self, ast): ... - def lit(self, s) -> None: ... - def cr(self) -> None: ... - def out(self, s) -> None: ... diff --git a/stubs/commonmark/commonmark/render/rst.pyi b/stubs/commonmark/commonmark/render/rst.pyi deleted file mode 100644 index 9357bfd9fc37..000000000000 --- a/stubs/commonmark/commonmark/render/rst.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any - -from commonmark.render.renderer import Renderer - -class ReStructuredTextRenderer(Renderer): - indent_char: Any - indent_length: int - def __init__(self, indent_char: str = ...) -> None: ... - def lit(self, s): ... - def cr(self) -> None: ... - def indent_lines(self, literal, indent_length: int = ...): ... - def document(self, node, entering) -> None: ... - def softbreak(self, node, entering) -> None: ... - def linebreak(self, node, entering) -> None: ... - def text(self, node, entering) -> None: ... - def emph(self, node, entering) -> None: ... - def strong(self, node, entering) -> None: ... - def paragraph(self, node, entering) -> None: ... - def link(self, node, entering) -> None: ... - def image(self, node, entering) -> None: ... - def code(self, node, entering) -> None: ... - def code_block(self, node, entering) -> None: ... - def list(self, node, entering) -> None: ... - def item(self, node, entering) -> None: ... - def block_quote(self, node, entering) -> None: ... - def heading(self, node, entering) -> None: ... diff --git a/stubs/console-menu/METADATA.toml b/stubs/console-menu/METADATA.toml new file mode 100644 index 000000000000..dbaaa6fd0ec8 --- /dev/null +++ b/stubs/console-menu/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.8.*" +upstream-repository = "https://github.com/aegirhall/console-menu" diff --git a/stubs/console-menu/consolemenu/__init__.pyi b/stubs/console-menu/consolemenu/__init__.pyi new file mode 100644 index 000000000000..e597f474c010 --- /dev/null +++ b/stubs/console-menu/consolemenu/__init__.pyi @@ -0,0 +1,17 @@ +from . import items as items +from .console_menu import ConsoleMenu as ConsoleMenu, Screen as Screen, clear_terminal as clear_terminal +from .menu_formatter import MenuFormatBuilder as MenuFormatBuilder +from .multiselect_menu import MultiSelectMenu as MultiSelectMenu +from .prompt_utils import PromptUtils as PromptUtils +from .selection_menu import SelectionMenu as SelectionMenu + +__all__ = [ + "ConsoleMenu", + "SelectionMenu", + "MultiSelectMenu", + "MenuFormatBuilder", + "PromptUtils", + "Screen", + "items", + "clear_terminal", +] diff --git a/stubs/console-menu/consolemenu/console_menu.pyi b/stubs/console-menu/consolemenu/console_menu.pyi new file mode 100644 index 000000000000..49bbdd7cbe4e --- /dev/null +++ b/stubs/console-menu/consolemenu/console_menu.pyi @@ -0,0 +1,97 @@ +from collections.abc import Callable + +from consolemenu.menu_formatter import MenuFormatBuilder as MenuFormatBuilder +from consolemenu.screen import Screen as Screen + +class ConsoleMenu: + currently_active_menu: ConsoleMenu | None + screen: Screen + clear_screen_before_render: bool + formatter: MenuFormatBuilder + title: str | Callable[[], str] | None + subtitle: str | Callable[[], str] | None + prologue_text: str | Callable[[], str] | None + epilogue_text: str | Callable[[], str] | None + highlight: None + normal: None + show_exit_option: bool + items: list[MenuItem] + parent: ConsoleMenu | None + exit_item: ExitItem + current_option: int + selected_option: int + returned_value: object + should_exit: bool + previous_active_menu: ConsoleMenu | None + def __init__( + self, + title: str | Callable[[], str] | None = None, + subtitle: str | Callable[[], str] | None = None, + screen: Screen | None = None, + formatter: MenuFormatBuilder | None = None, + prologue_text: str | Callable[[], str] | None = None, + epilogue_text: str | Callable[[], str] | None = None, + clear_screen: bool = True, + show_exit_option: bool = True, + exit_option_text: str = "Exit", + exit_menu_char: str | None = None, + ) -> None: ... + @property + def current_item(self) -> MenuItem | None: ... + @property + def selected_item(self) -> MenuItem | None: ... + def append_item(self, item: MenuItem) -> None: ... + def remove_item(self, item: MenuItem) -> bool: ... + def add_exit(self) -> bool: ... + def remove_exit(self) -> bool: ... + def is_selected_item_exit(self) -> bool: ... + def start(self, show_exit_option: bool | None = None) -> None: ... + def show(self, show_exit_option: bool | None = None) -> None: ... + def draw(self) -> None: ... + def is_running(self) -> bool: ... + def wait_for_start(self, timeout: float | None = None) -> bool: ... + def is_alive(self) -> bool: ... + def pause(self) -> None: ... + def resume(self) -> None: ... + def join(self, timeout: float | None = None) -> None: ... + def get_input(self) -> int: ... + def process_user_input(self) -> int | None: ... + def go_to(self, option: int) -> None: ... + def go_down(self) -> None: ... + def go_up(self) -> None: ... + def select(self) -> None: ... + def exit(self) -> None: ... + def clear_screen(self) -> None: ... + def get_title(self) -> str: ... + def get_subtitle(self) -> str: ... + def get_prologue_text(self) -> str: ... + def get_epilogue_text(self) -> str: ... + +class MenuItem: + text: str + menu: ConsoleMenu | None + should_exit: bool + index_item_separator: str + menu_char: str | None + def __init__( + self, + text: str | Callable[[], str], + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + def show(self, index: int) -> str: ... + def set_up(self) -> None: ... + def action(self) -> None: ... + def clean_up(self) -> None: ... + def get_return(self) -> object: ... + def __eq__(self, o: MenuItem) -> bool: ... # type: ignore[override] + def get_text(self) -> str: ... + +class ExitItem(MenuItem): + def __init__( + self, text: str | Callable[[], str] = "Exit", menu: ConsoleMenu | None = None, menu_char: str | None = None + ) -> None: ... + def show(self, index: int, available_width: None = None) -> str: ... + +def clear_terminal() -> None: ... diff --git a/stubs/console-menu/consolemenu/format/__init__.pyi b/stubs/console-menu/consolemenu/format/__init__.pyi new file mode 100644 index 000000000000..cc963da051c8 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/__init__.pyi @@ -0,0 +1,29 @@ +from .menu_borders import ( + AsciiBorderStyle as AsciiBorderStyle, + DoubleLineBorderStyle as DoubleLineBorderStyle, + DoubleLineOuterLightInnerBorderStyle as DoubleLineOuterLightInnerBorderStyle, + HeavyBorderStyle as HeavyBorderStyle, + HeavyOuterLightInnerBorderStyle as HeavyOuterLightInnerBorderStyle, + LightBorderStyle as LightBorderStyle, + MenuBorderStyle as MenuBorderStyle, + MenuBorderStyleFactory as MenuBorderStyleFactory, + MenuBorderStyleType as MenuBorderStyleType, +) +from .menu_margins import MenuMargins as MenuMargins +from .menu_padding import MenuPadding as MenuPadding +from .menu_style import MenuStyle as MenuStyle + +__all__ = [ + "MenuBorderStyle", + "MenuBorderStyleType", + "MenuBorderStyleFactory", + "MenuMargins", + "MenuPadding", + "MenuStyle", + "AsciiBorderStyle", + "LightBorderStyle", + "HeavyBorderStyle", + "DoubleLineBorderStyle", + "DoubleLineOuterLightInnerBorderStyle", + "HeavyOuterLightInnerBorderStyle", +] diff --git a/stubs/console-menu/consolemenu/format/menu_borders.pyi b/stubs/console-menu/consolemenu/format/menu_borders.pyi new file mode 100644 index 000000000000..9710b4abe2be --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_borders.pyi @@ -0,0 +1,194 @@ +import logging + +class MenuBorderStyle: + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class AsciiBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class LightBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class HeavyBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class HeavyOuterLightInnerBorderStyle(HeavyBorderStyle): + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + +class DoubleLineBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class DoubleLineOuterLightInnerBorderStyle(DoubleLineBorderStyle): + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + +class MenuBorderStyleType: + ASCII_BORDER: int + LIGHT_BORDER: int + HEAVY_BORDER: int + DOUBLE_LINE_BORDER: int + HEAVY_OUTER_LIGHT_INNER_BORDER: int + DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER: int + +class MenuBorderStyleFactory: + logger: logging.Logger + def __init__(self) -> None: ... + def create_border(self, border_style_type: MenuBorderStyleType) -> MenuBorderStyle: ... + def create_ascii_border(self) -> AsciiBorderStyle: ... + def create_light_border(self) -> LightBorderStyle: ... + def create_heavy_border(self) -> HeavyBorderStyle: ... + def create_heavy_outer_light_inner_border(self) -> HeavyOuterLightInnerBorderStyle: ... + def create_doubleline_border(self) -> DoubleLineBorderStyle: ... + def create_doubleline_outer_light_inner_border(self) -> DoubleLineOuterLightInnerBorderStyle: ... + @staticmethod + def is_win_python35_or_earlier() -> bool: ... diff --git a/stubs/console-menu/consolemenu/format/menu_margins.pyi b/stubs/console-menu/consolemenu/format/menu_margins.pyi new file mode 100644 index 000000000000..92505a4999e9 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_margins.pyi @@ -0,0 +1,22 @@ +class MenuMargins: + def __init__(self, top: int = 1, left: int = 2, bottom: int = 0, right: int = 2) -> None: ... + + @property + def left(self) -> int: ... + @left.setter + def left(self, left: int) -> None: ... + + @property + def right(self) -> int: ... + @right.setter + def right(self, right: int) -> None: ... + + @property + def top(self) -> int: ... + @top.setter + def top(self, top: int) -> None: ... + + @property + def bottom(self) -> int: ... + @bottom.setter + def bottom(self, bottom: int) -> None: ... diff --git a/stubs/console-menu/consolemenu/format/menu_padding.pyi b/stubs/console-menu/consolemenu/format/menu_padding.pyi new file mode 100644 index 000000000000..41791c1efed0 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_padding.pyi @@ -0,0 +1,22 @@ +class MenuPadding: + def __init__(self, top: int = 1, left: int = 2, bottom: int = 1, right: int = 2) -> None: ... + + @property + def left(self) -> int: ... + @left.setter + def left(self, left: int) -> None: ... + + @property + def right(self) -> int: ... + @right.setter + def right(self, right: int) -> None: ... + + @property + def top(self) -> int: ... + @top.setter + def top(self, top: int) -> None: ... + + @property + def bottom(self) -> int: ... + @bottom.setter + def bottom(self, bottom: int) -> None: ... diff --git a/stubs/console-menu/consolemenu/format/menu_style.pyi b/stubs/console-menu/consolemenu/format/menu_style.pyi new file mode 100644 index 000000000000..a0bfc1c42259 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_style.pyi @@ -0,0 +1,33 @@ +from consolemenu.format.menu_borders import MenuBorderStyle as MenuBorderStyle, MenuBorderStyleFactory as MenuBorderStyleFactory +from consolemenu.format.menu_margins import MenuMargins as MenuMargins +from consolemenu.format.menu_padding import MenuPadding as MenuPadding + +class MenuStyle: + def __init__( + self, + margins: MenuMargins | None = None, + padding: MenuPadding | None = None, + border_style: MenuBorderStyle | None = None, + border_style_type: int | None = None, + border_style_factory: MenuBorderStyleFactory | None = None, + ) -> None: ... + + @property + def margins(self) -> MenuMargins: ... + @margins.setter + def margins(self, margins: MenuMargins) -> None: ... + + @property + def padding(self) -> MenuPadding: ... + @padding.setter + def padding(self, padding: MenuPadding) -> None: ... + + @property + def border_style(self) -> MenuBorderStyle: ... + @border_style.setter + def border_style(self, border_style: MenuBorderStyle) -> None: ... + + @property + def border_style_factory(self) -> MenuBorderStyleFactory: ... + @border_style_factory.setter + def border_style_factory(self, border_style_factory: MenuBorderStyleFactory) -> None: ... diff --git a/stubs/console-menu/consolemenu/items/__init__.pyi b/stubs/console-menu/consolemenu/items/__init__.pyi new file mode 100644 index 000000000000..29943004afbf --- /dev/null +++ b/stubs/console-menu/consolemenu/items/__init__.pyi @@ -0,0 +1,8 @@ +from ..console_menu import ExitItem as ExitItem, MenuItem as MenuItem +from .command_item import CommandItem as CommandItem +from .external_item import ExternalItem as ExternalItem +from .function_item import FunctionItem as FunctionItem +from .selection_item import SelectionItem as SelectionItem +from .submenu_item import SubmenuItem as SubmenuItem + +__all__ = ["CommandItem", "ExitItem", "ExternalItem", "FunctionItem", "MenuItem", "SelectionItem", "SubmenuItem"] diff --git a/stubs/console-menu/consolemenu/items/command_item.pyi b/stubs/console-menu/consolemenu/items/command_item.pyi new file mode 100644 index 000000000000..1df604797124 --- /dev/null +++ b/stubs/console-menu/consolemenu/items/command_item.pyi @@ -0,0 +1,18 @@ +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import ExternalItem as ExternalItem + +class CommandItem(ExternalItem): + command: str + arguments: list[str] + exit_status: int | None + def __init__( + self, + text: str, + command: str, + arguments: list[str] | None = None, + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + def action(self) -> None: ... + def get_return(self) -> int: ... diff --git a/stubs/console-menu/consolemenu/items/external_item.pyi b/stubs/console-menu/consolemenu/items/external_item.pyi new file mode 100644 index 000000000000..33cf83a8eb0c --- /dev/null +++ b/stubs/console-menu/consolemenu/items/external_item.pyi @@ -0,0 +1,5 @@ +from consolemenu.items import MenuItem as MenuItem + +class ExternalItem(MenuItem): + def set_up(self) -> None: ... + def clean_up(self) -> None: ... diff --git a/stubs/console-menu/consolemenu/items/function_item.pyi b/stubs/console-menu/consolemenu/items/function_item.pyi new file mode 100644 index 000000000000..3322c4a3042d --- /dev/null +++ b/stubs/console-menu/consolemenu/items/function_item.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping, Sequence +from typing import Any + +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import ExternalItem as ExternalItem + +class FunctionItem(ExternalItem): + function: Callable[..., Any] + args: Sequence[Any] + kwargs: Mapping[str, Any] + return_value: Incomplete | None + def __init__( + self, + text: str, + function: Callable[..., Any], + args: Sequence[Any] | None = None, + kwargs: Mapping[str, Any] | None = None, + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + def action(self) -> None: ... + def clean_up(self) -> None: ... + def get_return(self) -> Any | None: ... diff --git a/stubs/console-menu/consolemenu/items/selection_item.pyi b/stubs/console-menu/consolemenu/items/selection_item.pyi new file mode 100644 index 000000000000..ce37a82bba7f --- /dev/null +++ b/stubs/console-menu/consolemenu/items/selection_item.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable + +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import MenuItem as MenuItem + +class SelectionItem(MenuItem): + index: int + def __init__( + self, text: str | Callable[[], str], index: int, menu: ConsoleMenu | None = None, menu_char: str | None = None + ) -> None: ... + def get_return(self) -> int: ... diff --git a/stubs/console-menu/consolemenu/items/submenu_item.pyi b/stubs/console-menu/consolemenu/items/submenu_item.pyi new file mode 100644 index 000000000000..9cda42875cb8 --- /dev/null +++ b/stubs/console-menu/consolemenu/items/submenu_item.pyi @@ -0,0 +1,22 @@ +from collections.abc import Callable + +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import MenuItem as MenuItem + +class SubmenuItem(MenuItem): + submenu: ConsoleMenu + def __init__( + self, + text: str | Callable[[], str], + submenu: ConsoleMenu, + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + menu: ConsoleMenu + def set_menu(self, menu: ConsoleMenu) -> None: ... + def set_up(self) -> None: ... + def action(self) -> None: ... + def clean_up(self) -> None: ... + def get_return(self) -> object: ... + def get_submenu(self) -> ConsoleMenu: ... diff --git a/stubs/console-menu/consolemenu/menu_component.pyi b/stubs/console-menu/consolemenu/menu_component.pyi new file mode 100644 index 000000000000..12cc5c53aae2 --- /dev/null +++ b/stubs/console-menu/consolemenu/menu_component.pyi @@ -0,0 +1,103 @@ +from collections.abc import Generator + +from consolemenu.console_menu import MenuItem +from consolemenu.format import MenuBorderStyle, MenuMargins, MenuPadding, MenuStyle as MenuStyle + +def ansilen(s: str) -> int: ... + +class Dimension: + width: int + height: int + def __init__(self, width: int = 0, height: int = 0, dimension: Dimension | None = None) -> None: ... + +class MenuComponent: + def __init__(self, menu_style: MenuStyle, max_dimension: Dimension | None = None) -> None: ... + @property + def max_dimension(self) -> Dimension: ... + @property + def style(self) -> MenuStyle: ... + @property + def margins(self) -> MenuMargins: ... + @property + def padding(self) -> MenuPadding: ... + @property + def border_style(self) -> MenuBorderStyle: ... + def calculate_border_width(self) -> int: ... + def calculate_content_width(self) -> int: ... + def generate(self) -> Generator[str]: ... + def inner_horizontals(self) -> str: ... + def inner_horizontal_border(self) -> str: ... + def outer_horizontals(self) -> str: ... + def outer_horizontal_border_bottom(self) -> str: ... + def outer_horizontal_border_top(self) -> str: ... + def row(self, content: str = "", align: str = "left", indent_len: int = 0) -> str: ... + +class MenuHeader(MenuComponent): + title: str + title_align: str + subtitle: str + subtitle_align: str + show_bottom_border: bool + def __init__( + self, + menu_style: MenuStyle, + max_dimension: Dimension | None = None, + title: str | None = None, + title_align: str = "left", + subtitle: str | None = None, + subtitle_align: str = "left", + show_bottom_border: bool = False, + ) -> None: ... + def generate(self) -> Generator[str]: ... + +class MenuTextSection(MenuComponent): + text: str + text_align: str + show_top_border: bool + show_bottom_border: bool + def __init__( + self, + menu_style: MenuStyle, + max_dimension: Dimension | None = None, + text: str | None = None, + text_align: str = "left", + show_top_border: bool = False, + show_bottom_border: bool = False, + ) -> None: ... + def generate(self) -> Generator[str]: ... + +class MenuItemsSection(MenuComponent): + items_align: str + def __init__( + self, + menu_style: MenuStyle, + max_dimension: Dimension | None = None, + items: list[MenuItem] | None = None, + items_align: str = "left", + ) -> None: ... + + @property + def items(self) -> list[MenuItem]: ... + @items.setter + def items(self, items: list[MenuItem]) -> None: ... + + @property + def items_with_bottom_border(self) -> list[str]: ... + @property + def items_with_top_border(self) -> list[str]: ... + def show_item_bottom_border(self, item_text: str, flag: bool) -> None: ... + def show_item_top_border(self, item_text: str, flag: bool) -> None: ... + def generate(self) -> Generator[str]: ... + +class MenuFooter(MenuComponent): + def generate(self) -> Generator[str]: ... + +class MenuPrompt(MenuComponent): + def __init__(self, menu_style: MenuStyle, max_dimension: Dimension | None = None, prompt_string: str = ">>") -> None: ... + + @property + def prompt(self) -> str: ... + @prompt.setter + def prompt(self, prompt: str) -> None: ... + + def generate(self) -> Generator[str]: ... diff --git a/stubs/console-menu/consolemenu/menu_formatter.pyi b/stubs/console-menu/consolemenu/menu_formatter.pyi new file mode 100644 index 000000000000..1144678da276 --- /dev/null +++ b/stubs/console-menu/consolemenu/menu_formatter.pyi @@ -0,0 +1,55 @@ +from consolemenu.console_menu import MenuItem +from consolemenu.format import MenuBorderStyleType +from consolemenu.format.menu_borders import MenuBorderStyle as MenuBorderStyle, MenuBorderStyleFactory as MenuBorderStyleFactory +from consolemenu.format.menu_style import MenuStyle as MenuStyle +from consolemenu.menu_component import ( + Dimension as Dimension, + MenuFooter as MenuFooter, + MenuHeader as MenuHeader, + MenuItemsSection as MenuItemsSection, + MenuPrompt as MenuPrompt, + MenuTextSection as MenuTextSection, +) + +class MenuFormatBuilder: + def __init__(self, max_dimension: Dimension | None = None) -> None: ... + def set_border_style(self, border_style: MenuBorderStyle) -> MenuFormatBuilder: ... + def set_border_style_type(self, border_style_type: MenuBorderStyleType) -> MenuFormatBuilder: ... + def set_border_style_factory(self, border_style_factory: MenuBorderStyleFactory) -> MenuFormatBuilder: ... + def set_bottom_margin(self, bottom_margin: int) -> MenuFormatBuilder: ... + def set_left_margin(self, left_margin: int) -> MenuFormatBuilder: ... + def set_right_margin(self, right_margin: int) -> MenuFormatBuilder: ... + def set_top_margin(self, top_margin: int) -> MenuFormatBuilder: ... + def set_title_align(self, align: str = "left") -> MenuFormatBuilder: ... + def set_subtitle_align(self, align: str = "left") -> MenuFormatBuilder: ... + def set_header_left_padding(self, x: int) -> MenuFormatBuilder: ... + def set_header_right_padding(self, x: int) -> MenuFormatBuilder: ... + def set_header_bottom_padding(self, x: int) -> MenuFormatBuilder: ... + def set_header_top_padding(self, x: int) -> MenuFormatBuilder: ... + def show_header_bottom_border(self, flag: bool) -> MenuFormatBuilder: ... + def set_footer_left_padding(self, x: int) -> MenuFormatBuilder: ... + def set_footer_right_padding(self, x: int) -> MenuFormatBuilder: ... + def set_footer_bottom_padding(self, x: int) -> MenuFormatBuilder: ... + def set_footer_top_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_left_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_right_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_bottom_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_top_padding(self, x: int) -> MenuFormatBuilder: ... + def show_item_bottom_border(self, item_text: str, flag: bool) -> MenuFormatBuilder: ... + def show_item_top_border(self, item_text: str, flag: bool) -> MenuFormatBuilder: ... + def set_prologue_text_align(self, align: str = "left") -> MenuFormatBuilder: ... + def show_prologue_top_border(self, flag: bool) -> MenuFormatBuilder: ... + def show_prologue_bottom_border(self, flag: bool) -> MenuFormatBuilder: ... + def set_epilogue_text_align(self, align: str = "left") -> MenuFormatBuilder: ... + def show_epilogue_top_border(self, flag: bool) -> MenuFormatBuilder: ... + def show_epilogue_bottom_border(self, flag: bool) -> MenuFormatBuilder: ... + def set_prompt(self, prompt: MenuPrompt) -> MenuFormatBuilder: ... + def clear_data(self) -> None: ... + def format( + self, + title: str | None = None, + subtitle: str | None = None, + prologue_text: str | None = None, + epilogue_text: str | None = None, + items: list[MenuItem] | None = None, + ) -> str: ... diff --git a/stubs/console-menu/consolemenu/multiselect_menu.pyi b/stubs/console-menu/consolemenu/multiselect_menu.pyi new file mode 100644 index 000000000000..4fe1a6260546 --- /dev/null +++ b/stubs/console-menu/consolemenu/multiselect_menu.pyi @@ -0,0 +1,22 @@ +from consolemenu import ConsoleMenu as ConsoleMenu +from consolemenu.console_menu import MenuItem +from consolemenu.items import SubmenuItem as SubmenuItem +from consolemenu.menu_formatter import MenuFormatBuilder + +class MultiSelectMenu(ConsoleMenu): + ack_item_completion: bool + def __init__( + self, + title: str | None = None, + subtitle: str | None = None, + formatter: MenuFormatBuilder | None = None, + prologue_text: str | None = None, + epilogue_text: str | None = None, + ack_item_completion: bool = True, + show_exit_option: bool = True, + exit_option_text: str = "Exit", + clear_screen: bool = True, + ) -> None: ... + def append_item(self, item: MenuItem) -> None: ... + current_option: int + def process_user_input(self) -> None: ... diff --git a/stubs/console-menu/consolemenu/prompt_utils.pyi b/stubs/console-menu/consolemenu/prompt_utils.pyi new file mode 100644 index 000000000000..d40dda7d98de --- /dev/null +++ b/stubs/console-menu/consolemenu/prompt_utils.pyi @@ -0,0 +1,47 @@ +from collections.abc import Iterable, Sequence +from typing import Any, NamedTuple + +from consolemenu.screen import Screen +from consolemenu.validators.base import BaseValidator + +class InputResult(NamedTuple): + input_string: str + validation_result: bool + +class PromptFormatter: + @staticmethod + def format_prompt( + prompt: str | None = None, + default: str | None = None, + enable_quit: bool = False, + quit_string: str = "q", + quit_message: str = "(enter q to Quit)", + ) -> str: ... + +class PromptUtils: + def __init__(self, screen: Screen, prompt_formatter: PromptFormatter | None = None) -> None: ... + @property + def screen(self) -> Screen: ... + def clear(self) -> None: ... + def confirm_answer(self, answer: str, message: str | None = None) -> bool: ... + def enter_to_continue(self, message: str | None = None) -> None: ... + def input( + self, + prompt: str | None = None, + default: str | None = None, + validators: Iterable[BaseValidator] | None = None, + enable_quit: bool = False, + quit_string: str = "q", + quit_message: str = "(enter q to Quit)", + ) -> InputResult: ... + def input_password(self, message: str | None = None) -> str: ... + def printf(self, *args: Any) -> None: ... + def println(self, *args: Any) -> None: ... + def prompt_and_confirm_password(self, message: str) -> str: ... + def prompt_for_bilateral_choice(self, prompt: str, option1: str, option2: str) -> str: ... + def prompt_for_trilateral_choice(self, prompt: str, option1: str, option2: str, option3: str) -> str: ... + def prompt_for_yes_or_no(self, prompt: str) -> bool: ... + def prompt_for_numbered_choice(self, choices: Sequence[str], title: str | None = None, prompt: str = ">") -> int: ... + def validate_input(self, input_string: str, validators: BaseValidator) -> bool: ... + +class UserQuit(Exception): ... diff --git a/stubs/console-menu/consolemenu/screen.pyi b/stubs/console-menu/consolemenu/screen.pyi new file mode 100644 index 000000000000..63d5734327f3 --- /dev/null +++ b/stubs/console-menu/consolemenu/screen.pyi @@ -0,0 +1,17 @@ +from typing import Any + +class Screen: + def __init__(self) -> None: ... + @property + def screen_height(self) -> int: ... + @property + def screen_width(self) -> int: ... + @staticmethod + def clear() -> None: ... + @staticmethod + def flush() -> None: ... + def input(self, prompt: str = "") -> str: ... + @staticmethod + def printf(*args: Any) -> None: ... + @staticmethod + def println(*args: Any) -> None: ... diff --git a/stubs/console-menu/consolemenu/selection_menu.pyi b/stubs/console-menu/consolemenu/selection_menu.pyi new file mode 100644 index 000000000000..9760461e9542 --- /dev/null +++ b/stubs/console-menu/consolemenu/selection_menu.pyi @@ -0,0 +1,31 @@ +from collections.abc import Iterable + +from consolemenu import ConsoleMenu as ConsoleMenu +from consolemenu.items import SelectionItem as SelectionItem +from consolemenu.menu_formatter import MenuFormatBuilder +from consolemenu.screen import Screen + +class SelectionMenu(ConsoleMenu): + def __init__( + self, + strings: Iterable[str], + title: str | None = None, + subtitle: str | None = None, + screen: Screen | None = None, + formatter: MenuFormatBuilder | None = None, + prologue_text: str | None = None, + epilogue_text: str | None = None, + show_exit_option: bool = True, + exit_option_text: str = "Exit", + clear_screen: bool = True, + ) -> None: ... + @classmethod + def get_selection( + cls, + strings: Iterable[str], + title: str = "Select an option", + subtitle: str | None = None, + show_exit_option: bool = True, + _menu: ConsoleMenu | None = None, + ) -> int: ... + def append_string(self, string: str) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/__init__.pyi b/stubs/console-menu/consolemenu/validators/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/common/__init__.pyi rename to stubs/console-menu/consolemenu/validators/__init__.pyi diff --git a/stubs/console-menu/consolemenu/validators/base.pyi b/stubs/console-menu/consolemenu/validators/base.pyi new file mode 100644 index 000000000000..eaea5c87caec --- /dev/null +++ b/stubs/console-menu/consolemenu/validators/base.pyi @@ -0,0 +1,11 @@ +import abc +from abc import abstractmethod +from logging import Logger + +class InvalidValidator(Exception): ... + +class BaseValidator(metaclass=abc.ABCMeta): + log: Logger + def __init__(self) -> None: ... + @abstractmethod + def validate(self, input_string: str) -> bool: ... diff --git a/stubs/console-menu/consolemenu/validators/regex.pyi b/stubs/console-menu/consolemenu/validators/regex.pyi new file mode 100644 index 000000000000..fdadc44f6720 --- /dev/null +++ b/stubs/console-menu/consolemenu/validators/regex.pyi @@ -0,0 +1,7 @@ +from consolemenu.validators.base import BaseValidator as BaseValidator + +class RegexValidator(BaseValidator): + def __init__(self, pattern: str) -> None: ... + @property + def pattern(self) -> str: ... + def validate(self, input_string: str) -> bool: ... diff --git a/stubs/console-menu/consolemenu/validators/url.pyi b/stubs/console-menu/consolemenu/validators/url.pyi new file mode 100644 index 000000000000..d9e92bb636cc --- /dev/null +++ b/stubs/console-menu/consolemenu/validators/url.pyi @@ -0,0 +1,5 @@ +from consolemenu.validators.base import BaseValidator as BaseValidator + +class UrlValidator(BaseValidator): + def __init__(self) -> None: ... + def validate(self, input_string: str) -> bool: ... diff --git a/stdlib/@python2/distutils/command/bdist.pyi b/stubs/console-menu/consolemenu/version.pyi similarity index 100% rename from stdlib/@python2/distutils/command/bdist.pyi rename to stubs/console-menu/consolemenu/version.pyi diff --git a/stubs/contextvars/@tests/stubtest_allowlist.txt b/stubs/contextvars/@tests/stubtest_allowlist.txt deleted file mode 100644 index 64f8aa01ac09..000000000000 --- a/stubs/contextvars/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,4 +0,0 @@ -contextvars.Context.__init__ -contextvars.Context.get -contextvars.ContextVar.reset -contextvars.ContextVar.set diff --git a/stubs/contextvars/METADATA.toml b/stubs/contextvars/METADATA.toml deleted file mode 100644 index ea07e8d318f6..000000000000 --- a/stubs/contextvars/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "2.4" diff --git a/stubs/contextvars/contextvars.pyi b/stubs/contextvars/contextvars.pyi deleted file mode 100644 index 429d2037afb2..000000000000 --- a/stubs/contextvars/contextvars.pyi +++ /dev/null @@ -1,38 +0,0 @@ -import sys -from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar - -if sys.version_info >= (3, 9): - from types import GenericAlias - -_T = TypeVar("_T") - -class ContextVar(Generic[_T]): - def __init__(self, name: str, *, default: _T = ...) -> None: ... - @property - def name(self) -> str: ... - def get(self, default: _T = ...) -> _T: ... - def set(self, value: _T) -> Token[_T]: ... - def reset(self, token: Token[_T]) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class Token(Generic[_T]): - @property - def var(self) -> ContextVar[_T]: ... - @property - def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express - MISSING: ClassVar[object] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -def copy_context() -> Context: ... - -# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have -# a different value. -class Context(Mapping[ContextVar[Any], Any]): - def __init__(self) -> None: ... - def run(self, callable: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... - def copy(self) -> Context: ... - def __getitem__(self, key: ContextVar[Any]) -> Any: ... - def __iter__(self) -> Iterator[ContextVar[Any]]: ... - def __len__(self) -> int: ... diff --git a/stubs/convertdate/METADATA.toml b/stubs/convertdate/METADATA.toml new file mode 100644 index 000000000000..d54ebc5903a5 --- /dev/null +++ b/stubs/convertdate/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.5.1" +upstream-repository = "https://github.com/fitnr/convertdate" diff --git a/stubs/convertdate/convertdate/__init__.pyi b/stubs/convertdate/convertdate/__init__.pyi new file mode 100644 index 000000000000..b33581cac340 --- /dev/null +++ b/stubs/convertdate/convertdate/__init__.pyi @@ -0,0 +1,47 @@ +from typing import Final + +from . import ( + armenian as armenian, + bahai as bahai, + coptic as coptic, + daycount as daycount, + dublin as dublin, + french_republican as french_republican, + gregorian as gregorian, + hebrew as hebrew, + holidays as holidays, + indian_civil as indian_civil, + islamic as islamic, + iso as iso, + julian as julian, + julianday as julianday, + mayan as mayan, + ordinal as ordinal, + persian as persian, + positivist as positivist, + utils as utils, +) + +__version__: Final[str] + +__all__ = [ + "armenian", + "bahai", + "coptic", + "daycount", + "dublin", + "french_republican", + "gregorian", + "hebrew", + "holidays", + "indian_civil", + "islamic", + "iso", + "julian", + "julianday", + "mayan", + "ordinal", + "persian", + "positivist", + "utils", +] diff --git a/stubs/convertdate/convertdate/armenian.pyi b/stubs/convertdate/convertdate/armenian.pyi new file mode 100644 index 000000000000..3ff93da6847c --- /dev/null +++ b/stubs/convertdate/convertdate/armenian.pyi @@ -0,0 +1,24 @@ +from typing import Final, Literal + +EPOCH: Final = 1922501.5 +EPOCH_SARKAWAG: Final = 2117210.5 +MONTHS: Final[list[str]] +MONTHS_ARM: Final[list[str]] + +def leap(year: int) -> bool: ... +def to_jd(year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None) -> float: ... +def from_jd(jd: float, method: Literal["sarkawag", "moveable"] | None = None) -> tuple[int, int, int]: ... +def to_julian(year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None) -> tuple[int, int, int]: ... +def from_julian( + year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None +) -> tuple[int, int, int]: ... +def to_gregorian( + year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None +) -> tuple[int, int, int]: ... +def from_gregorian( + year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None +) -> tuple[int, int, int]: ... +def month_length(year: int, month: int, method: Literal["sarkawag", "moveable"] | None = None) -> Literal[5, 6, 30]: ... +def monthcalendar(year: int, month: int, method: Literal["sarkawag", "moveable"] | None = None) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, lang: str | None = None) -> str: ... +def tostring(year: int, month: int, day: int, lang: str | None = None) -> str: ... diff --git a/stubs/convertdate/convertdate/bahai.pyi b/stubs/convertdate/convertdate/bahai.pyi new file mode 100644 index 000000000000..53a426b839e3 --- /dev/null +++ b/stubs/convertdate/convertdate/bahai.pyi @@ -0,0 +1,37 @@ +from typing import Final + +EPOCH: Final = 2394646.5 +EPOCH_GREGORIAN_YEAR: Final = 1844 +TEHRAN: Final = 51.4215, 35.6944 +WEEKDAYS: Final = ("Jamál", "Kamál", "Fidál", "Idál", "Istijlál", "Istiqlál", "Jalál") +MONTHS: Final[tuple[str, ...]] +ENGLISH_MONTHS: Final[tuple[str, ...]] +BAHA: Final = 1 +JALAL: Final = 2 +JAMAL: Final = 3 +AZAMAT: Final = 4 +NUR: Final = 5 +RAHMAT: Final = 6 +KALIMAT: Final = 7 +KAMAL: Final = 8 +ASMA: Final = 9 +IZZAT: Final = 10 +MASHIYYAT: Final = 11 +ILM: Final = 12 +QUDRAT: Final = 13 +QAWL: Final = 14 +MASAIL: Final = 15 +SHARAF: Final = 16 +SULTAN: Final = 17 +MULK: Final = 18 +AYYAMIHA: Final = 19 +ALA: Final = 20 + +def gregorian_nawruz(year: int) -> tuple[int, int]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> int: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, lang: str | None = None) -> str: ... diff --git a/stubs/convertdate/convertdate/coptic.pyi b/stubs/convertdate/convertdate/coptic.pyi new file mode 100644 index 000000000000..dca579cabf68 --- /dev/null +++ b/stubs/convertdate/convertdate/coptic.pyi @@ -0,0 +1,14 @@ +from typing import Final, Literal + +EPOCH: Final = 1825029.5 +MONTHS: Final[list[str]] +WEEKDAYS: Final = ["Tkyriaka", "Pesnau", "Pshoment", "Peftoou", "Ptiou", "Psoou", "Psabbaton"] + +def is_leap(year: int) -> bool: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jdc: float) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[5, 6, 30]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/__init__.pyi b/stubs/convertdate/convertdate/data/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/common/actions/__init__.pyi rename to stubs/convertdate/convertdate/data/__init__.pyi diff --git a/stubs/convertdate/convertdate/data/french_republican_days.pyi b/stubs/convertdate/convertdate/data/french_republican_days.pyi new file mode 100644 index 000000000000..9a37dc5f97b4 --- /dev/null +++ b/stubs/convertdate/convertdate/data/french_republican_days.pyi @@ -0,0 +1,3 @@ +from typing import Final + +french_republican_days: Final[dict[int, list[str]]] diff --git a/stubs/convertdate/convertdate/data/positivist.pyi b/stubs/convertdate/convertdate/data/positivist.pyi new file mode 100644 index 000000000000..a1529785d031 --- /dev/null +++ b/stubs/convertdate/convertdate/data/positivist.pyi @@ -0,0 +1,6 @@ +from typing import Final + +DAY_NAMES: Final[tuple[str, ...]] +leap_day_replacements: Final[dict[int, str]] +DAY_NAMES_LEAP: Final[list[str]] +FESTIVALS: Final[dict[tuple[int, int], str]] diff --git a/stubs/convertdate/convertdate/daycount.pyi b/stubs/convertdate/convertdate/daycount.pyi new file mode 100644 index 000000000000..e2029ede976e --- /dev/null +++ b/stubs/convertdate/convertdate/daycount.pyi @@ -0,0 +1,13 @@ +import datetime + +class DayCount: + epoch: float + def __init__(self, epoch: float) -> None: ... + def to_gregorian(self, dc: int) -> tuple[int, int, int]: ... + def from_gregorian(self, year: int, month: int, day: int) -> float: ... + def to_jd(self, dc: int) -> float: ... + def from_jd(self, jdc: float) -> float: ... + def from_julian(self, year: int, month: int, day: int) -> float: ... + def to_julian(self, dc: int) -> tuple[int, int, int]: ... + def to_datetime(self, dc: int) -> datetime.datetime: ... + def from_datetime(self, date: datetime.datetime) -> float: ... diff --git a/stubs/convertdate/convertdate/dublin.pyi b/stubs/convertdate/convertdate/dublin.pyi new file mode 100644 index 000000000000..5c28661a945c --- /dev/null +++ b/stubs/convertdate/convertdate/dublin.pyi @@ -0,0 +1,13 @@ +import datetime +from typing import Final + +EPOCH: Final = 2415020 + +def to_gregorian(dc: int) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> float: ... +def to_jd(dc: int) -> float: ... +def from_jd(jdc: float) -> float: ... +def from_julian(year: int, month: int, day: int) -> float: ... +def to_julian(dc: int) -> tuple[int, int, int]: ... +def to_datetime(dc: int) -> datetime.datetime: ... +def from_datetime(date: datetime.datetime) -> float: ... diff --git a/stubs/convertdate/convertdate/french_republican.pyi b/stubs/convertdate/convertdate/french_republican.pyi new file mode 100644 index 000000000000..d8c0c029a7ba --- /dev/null +++ b/stubs/convertdate/convertdate/french_republican.pyi @@ -0,0 +1,27 @@ +from typing import Final, Literal + +EPOCH: Final = 2375839.5 +YEAR_EPOCH: Final = 1791.0 +DAYS_IN_YEAR: Final = 365.0 +MOIS: Final[list[str]] +MONTHS: Final[list[str]] +LEAP_CYCLE_DAYS: Final = 1461.0 +LEAP_CYCLE_YEARS: Final = 4.0 + +def leap(year: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None) -> bool: ... +def premier_da_la_annee(jd: float) -> float: ... +def to_jd( + year: int, month: int, day: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> float: ... +def from_jd( + jd: float, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> tuple[int, int, int]: ... +def decade(jour: float) -> int: ... +def day_name(month: int, day: int) -> str: ... +def from_gregorian( + year: int, month: int, day: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> tuple[int, int, int]: ... +def to_gregorian( + an: int, mois: int, jour: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> tuple[int, int, int]: ... +def format(an: int, mois: int, jour: int) -> str: ... diff --git a/stubs/convertdate/convertdate/gregorian.pyi b/stubs/convertdate/convertdate/gregorian.pyi new file mode 100644 index 000000000000..8d9c2df9044a --- /dev/null +++ b/stubs/convertdate/convertdate/gregorian.pyi @@ -0,0 +1,20 @@ +from typing import Final, Literal + +EPOCH: Final = 1721425.5 +INTERCALATION_CYCLE_YEARS: Final = 400 +INTERCALATION_CYCLE_DAYS: Final = 146097 +LEAP_SUPPRESSION_YEARS: Final = 100 +LEAP_SUPPRESSION_DAYS: Final = 36524 +LEAP_CYCLE_YEARS: Final = 4 +LEAP_CYCLE_DAYS: Final = 1461 +YEAR_DAYS: Final = 365 +HAVE_30_DAYS: Final = (4, 6, 9, 11) +HAVE_31_DAYS: Final = (1, 3, 5, 7, 8, 10, 12) + +def legal_date(year: int, month: int, day: int) -> Literal[True]: ... +def to_jd2(year: int, month: int, day: int) -> float: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> int: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, format_string: str = "%-d %B %y") -> str: ... diff --git a/stubs/convertdate/convertdate/hebrew.pyi b/stubs/convertdate/convertdate/hebrew.pyi new file mode 100644 index 000000000000..dfe5544d185d --- /dev/null +++ b/stubs/convertdate/convertdate/hebrew.pyi @@ -0,0 +1,37 @@ +from typing import Final, Literal +from typing_extensions import deprecated + +EPOCH: Final = 347995.5 +HEBREW_YEAR_OFFSET: Final = 3760 +NISAN: Final = 1 +IYYAR: Final = 2 +SIVAN: Final = 3 +TAMMUZ: Final = 4 +AV: Final = 5 +ELUL: Final = 6 +TISHRI: Final = 7 +HESHVAN: Final = 8 +KISLEV: Final = 9 +TEVETH: Final = 10 +SHEVAT: Final = 11 +ADAR: Final = 12 +VEADAR: Final = 13 +MONTHS: Final[list[str]] +MONTHS_HEB: Final[list[str]] + +def leap(year: int) -> bool: ... +def year_months(year: int) -> Literal[12, 13]: ... +def delay_1(year: int) -> int: ... +def delay_2(year: int) -> Literal[0, 1, 2]: ... +def year_days(year: int) -> float: ... +def month_length(year: int, month: int) -> Literal[29, 30]: ... +@deprecated("The `month_days` function is deprecated. Use `month_length` instead.") +def month_days(year: int, month: int) -> Literal[29, 30]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def to_civil(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_jd_gregorianyear(gregorianyear: int, hebrew_month: int, hebrew_day: int) -> float: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, lang: str | None = None) -> str: ... diff --git a/stubs/convertdate/convertdate/holidays.pyi b/stubs/convertdate/convertdate/holidays.pyi new file mode 100644 index 000000000000..02f709274187 --- /dev/null +++ b/stubs/convertdate/convertdate/holidays.pyi @@ -0,0 +1,161 @@ +from typing import Final, Literal +from typing_extensions import deprecated + +MON: Final = 0 +TUE: Final = 1 +WED: Final = 2 +THU: Final = 3 +FRI: Final = 4 +SAT: Final = 5 +SUN: Final = 6 +JAN: Final = 1 +FEB: Final = 2 +MAR: Final = 3 +APR: Final = 4 +MAY: Final = 5 +JUN: Final = 6 +JUL: Final = 7 +AUG: Final = 8 +SEP: Final = 9 +OCT: Final = 10 +NOV: Final = 11 +DEC: Final = 12 + +def new_years(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def martin_luther_king_day(year: int) -> tuple[int, int, int]: ... +def lincolns_birthday(year: int) -> tuple[int, int, int]: ... +def valentines_day(year: int) -> tuple[int, int, int]: ... +def washingtons_birthday(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def presidents_day(year: int) -> tuple[int, int, int]: ... +def pulaski_day(year: int) -> tuple[int, int, int]: ... +def easter(year: int, church: Literal["western", "orthodox", "eastern"] | None = None) -> tuple[int, int, int]: ... +def may_day(year: int) -> tuple[int, int, int]: ... +def mothers_day(year: int) -> tuple[int, int, int]: ... +def memorial_day(year: int) -> tuple[int, int, int]: ... +def fathers_day(year: int) -> tuple[int, int, int]: ... +def juneteenth(year: int) -> tuple[int, int, int]: ... +def flag_day(year: int) -> tuple[int, int, int]: ... +def independence_day(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def labor_day(year: int) -> tuple[int, int, int]: ... +def indigenous_peoples_day(year: int, country: str = "usa") -> tuple[int, int, int]: ... +@deprecated("The `columbus_day` function will be removed in a future release. Use `indigenous_peoples_day` instead.") +def columbus_day(year: int, country: str = "usa") -> tuple[int, int, int]: ... +def halloween(year: int) -> tuple[int, int, int]: ... +def election_day(year: int) -> tuple[int, int, int]: ... +def veterans_day(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def rememberance_day(year: int) -> tuple[int, int, int]: ... +def armistice_day(year: int) -> tuple[int, int, int]: ... +def thanksgiving(year: int, country: Literal["usa", "canada"] = "usa") -> tuple[int, int, int]: ... +def christmas_eve(year: int) -> tuple[int, int, int]: ... +def christmas(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def new_years_eve(year: int) -> tuple[int, int, int]: ... +def hanukkah(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def purim(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def rosh_hashanah(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def yom_kippur(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def passover(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def shavuot(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def sukkot(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def shemini_azeret(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def lag_baomer(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def tu_beshvat(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def tisha_bav(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def dia_constitucion(year: int, observed: bool | None = True) -> tuple[int, int, int]: ... +def natalicio_benito_juarez(year: int, observed: bool | None = True) -> tuple[int, int, int]: ... +def dia_independencia(year: int) -> tuple[int, int, int]: ... +def dia_revolucion(year: int) -> tuple[int, int, int]: ... +def ramadan(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def ashura(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def eid_alfitr(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def eid_aladha(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... + +class Holidays: + year: int + def __init__(self, year: int | None = None) -> None: ... + def set_year(self, year: int) -> None: ... + @property + def christmas(self) -> tuple[int, int, int]: ... + @property + def christmas_eve(self) -> tuple[int, int, int]: ... + @property + def thanksgiving(self) -> tuple[int, int, int]: ... + @property + def new_years(self) -> tuple[int, int, int]: ... + @property + def new_years_eve(self) -> tuple[int, int, int]: ... + @property + def independence_day(self) -> tuple[int, int, int]: ... + @property + def flag_day(self) -> tuple[int, int, int]: ... + @property + def election_day(self) -> tuple[int, int, int]: ... + @property + def presidents_day(self) -> tuple[int, int, int]: ... + @property + def washingtons_birthday(self) -> tuple[int, int, int]: ... + @property + def lincolns_birthday(self) -> tuple[int, int, int]: ... + @property + def memorial_day(self) -> tuple[int, int, int]: ... + @property + def juneteenth(self) -> tuple[int, int, int]: ... + @property + def labor_day(self) -> tuple[int, int, int]: ... + @property + def indigenous_peoples_day(self) -> tuple[int, int, int]: ... + @property + def columbus_day(self) -> tuple[int, int, int]: ... + @property + def veterans_day(self) -> tuple[int, int, int]: ... + @property + def valentines_day(self) -> tuple[int, int, int]: ... + @property + def halloween(self) -> tuple[int, int, int]: ... + @property + def mothers_day(self) -> tuple[int, int, int]: ... + @property + def fathers_day(self) -> tuple[int, int, int]: ... + @property + def pulaski_day(self) -> tuple[int, int, int]: ... + @property + def easter(self) -> tuple[int, int, int]: ... + @property + def martin_luther_king_day(self) -> tuple[int, int, int]: ... + @property + def hanukkah(self) -> tuple[int, int, int]: ... + @property + def purim(self) -> tuple[int, int, int]: ... + @property + def rosh_hashanah(self) -> tuple[int, int, int]: ... + @property + def yom_kippur(self) -> tuple[int, int, int]: ... + @property + def passover(self) -> tuple[int, int, int]: ... + @property + def shavuot(self) -> tuple[int, int, int]: ... + @property + def sukkot(self) -> tuple[int, int, int]: ... + @property + def tu_beshvat(self) -> tuple[int, int, int]: ... + @property + def shemini_azeret(self) -> tuple[int, int, int]: ... + @property + def lag_baomer(self) -> tuple[int, int, int]: ... + @property + def tisha_bav(self) -> tuple[int, int, int]: ... + @property + def dia_constitucion(self) -> tuple[int, int, int]: ... + @property + def natalicio_benito_juarez(self) -> tuple[int, int, int]: ... + @property + def dia_independencia(self) -> tuple[int, int, int]: ... + @property + def dia_revolucion(self) -> tuple[int, int, int]: ... + @property + def ramadan(self) -> tuple[int, int, int]: ... + @property + def ashura(self) -> tuple[int, int, int]: ... + @property + def eid_alfitr(self) -> tuple[int, int, int]: ... + @property + def eid_aladha(self) -> tuple[int, int, int]: ... diff --git a/stubs/convertdate/convertdate/indian_civil.pyi b/stubs/convertdate/convertdate/indian_civil.pyi new file mode 100644 index 000000000000..d3121e0f3bba --- /dev/null +++ b/stubs/convertdate/convertdate/indian_civil.pyi @@ -0,0 +1,15 @@ +from typing import Final, Literal + +WEEKDAYS: Final = ("Ravivāra", "Somavāra", "Maṅgalavāra", "Budhavāra", "Guruvāra", "Śukravāra", "Śanivāra") +MONTHS: Final[tuple[str, ...]] +HAVE_31_DAYS: Final = (2, 3, 4, 5, 6) +HAVE_30_DAYS: Final = (7, 8, 9, 10, 11, 12) +SAKA_EPOCH: Final = 78 + +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[30, 31]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/islamic.pyi b/stubs/convertdate/convertdate/islamic.pyi new file mode 100644 index 000000000000..a1b29ee695c9 --- /dev/null +++ b/stubs/convertdate/convertdate/islamic.pyi @@ -0,0 +1,17 @@ +from typing import Final, Literal + +EPOCH: Final = 1948439.5 +WEEKDAYS: Final = ("al-'ahad", "al-'ithnayn", "ath-thalatha'", "al-'arb`a'", "al-khamis", "al-jum`a", "as-sabt") +MONTHS: Final[list[str]] +HAS_29_DAYS: Final = (2, 4, 6, 8, 10) +HAS_30_DAYS: Final = (1, 3, 5, 7, 9, 11) + +def leap(year: int) -> bool: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def to_jd_gregorianyear(gregorianyear: int, islamic_month: int, islamic_day: int) -> float: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[29, 30]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/iso.pyi b/stubs/convertdate/convertdate/iso.pyi new file mode 100644 index 000000000000..f8f6021cf11a --- /dev/null +++ b/stubs/convertdate/convertdate/iso.pyi @@ -0,0 +1,17 @@ +import datetime +from typing import Final, Literal + +MON: Final = 0 +TUE: Final = 1 +WED: Final = 2 +THU: Final = 3 +FRI: Final = 4 +SAT: Final = 5 +SUN: Final = 6 + +def to_jd(year: int, week: int, day: int) -> float: ... +def from_jd(jd: float) -> datetime._IsoCalendarDate: ... +def weeks_per_year(year: int) -> Literal[52, 53]: ... +def from_gregorian(year: int, month: int, day: int) -> datetime._IsoCalendarDate: ... +def to_gregorian(year: int, week: int, day: int) -> tuple[int, int, int]: ... +def format(year: int, week: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/julian.pyi b/stubs/convertdate/convertdate/julian.pyi new file mode 100644 index 000000000000..4ef363bb981c --- /dev/null +++ b/stubs/convertdate/convertdate/julian.pyi @@ -0,0 +1,20 @@ +from typing import Final, Literal + +J0000: Final = 1721424.5 +J1970: Final = 2440587.5 +JMJD: Final = 2400000.5 +JULIAN_EPOCH: Final = 1721423.5 +J2000: Final = 2451545.0 +JULIANCENTURY: Final = 36525.0 +HAVE_30_DAYS: Final = (4, 6, 9, 11) +HAVE_31_DAYS: Final = (1, 3, 5, 7, 8, 10, 12) + +def leap(year: int) -> bool: ... +def month_length(year: int, month: int) -> Literal[28, 29, 30, 31]: ... +def legal_date(year: int, month: int, day: int) -> Literal[True]: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, format_string: str = "%-d %B %y") -> str: ... diff --git a/stubs/convertdate/convertdate/julianday.pyi b/stubs/convertdate/convertdate/julianday.pyi new file mode 100644 index 000000000000..cedad663b7ab --- /dev/null +++ b/stubs/convertdate/convertdate/julianday.pyi @@ -0,0 +1,8 @@ +import datetime + +def to_datetime(jdc: float) -> datetime.datetime: ... +def from_datetime(dt: datetime.datetime) -> float: ... +def to_gregorian(jdc: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> float: ... +def to_julian(jdc: float) -> tuple[int, int, int]: ... +def from_julian(year: int, month: int, day: int) -> float: ... diff --git a/stubs/convertdate/convertdate/mayan.pyi b/stubs/convertdate/convertdate/mayan.pyi new file mode 100644 index 000000000000..310f04093135 --- /dev/null +++ b/stubs/convertdate/convertdate/mayan.pyi @@ -0,0 +1,43 @@ +from _typeshed import Unused +from collections.abc import Generator +from typing import Final, Literal, overload +from typing_extensions import Never + +EPOCH: Final = 584282.5 +HAAB: Final[list[str]] +HAAB_TRANSLATIONS: Final[list[str]] +TZOLKIN: Final[list[str]] +TZOLKIN_TRANSLATIONS: Final[list[str]] + +def to_jd(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int, int, int]: ... +def to_gregorian(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int, int, int]: ... +def to_haab(jd: float) -> tuple[int, str]: ... +def to_tzolkin(jd: float) -> tuple[int, str]: ... +def lc_to_haab(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> tuple[int, str]: ... +def lc_to_tzolkin(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> tuple[int, str]: ... +def lc_to_haab_tzolkin(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> str: ... +def translate_haab(h: str) -> str | None: ... +def translate_tzolkin(tz: str) -> str | None: ... +def tzolkin_generator(number: int | None = None, name: str | None = None) -> Generator[tuple[int, str]]: ... +def longcount_generator( + baktun: int, katun: int, tun: int, uinal: int, kin: int +) -> Generator[tuple[int, int, int, int, int], None, Never]: ... +def next_haab(month: str, jd: float) -> float: ... +def next_tzolkin(tzolkin: tuple[int, str], jd: float) -> float: ... +def next_tzolkin_haab(tzolkin: tuple[int, str], haab: tuple[int, str], jd: float) -> float: ... +def month_length(month: str) -> Literal[5, 20]: ... + +@overload +def haab_monthcalendar( + baktun: int, katun: int, tun: int, uinal: int, kin: int, jdc: None = None +) -> list[list[tuple[int | None, tuple[int, str] | None, tuple[int, int, int, int, int] | None]]]: ... +@overload +def haab_monthcalendar( + baktun: Unused = None, katun: Unused = None, tun: Unused = None, uinal: Unused = None, kin: Unused = None, jdc: float = ... +) -> list[list[tuple[int | None, tuple[int, str] | None, tuple[int, int, int, int, int] | None]]]: ... + +def haab_monthcalendar_prospective( + haabmonth: str, jdc: float +) -> list[list[tuple[int | None, tuple[int, str] | None, tuple[int, int, int, int, int] | None]]]: ... diff --git a/stubs/convertdate/convertdate/ordinal.pyi b/stubs/convertdate/convertdate/ordinal.pyi new file mode 100644 index 000000000000..893fc7abb1be --- /dev/null +++ b/stubs/convertdate/convertdate/ordinal.pyi @@ -0,0 +1,4 @@ +def to_jd(year: int, dayofyear: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int]: ... +def to_gregorian(year: int, dayofyear: int) -> tuple[int, int, int]: ... diff --git a/stubs/convertdate/convertdate/persian.pyi b/stubs/convertdate/convertdate/persian.pyi new file mode 100644 index 000000000000..35746af8adc7 --- /dev/null +++ b/stubs/convertdate/convertdate/persian.pyi @@ -0,0 +1,19 @@ +from typing import Final, Literal + +EPOCH: Final = 1948320.5 +WEEKDAYS: Final[tuple[str, ...]] +MONTHS: Final[list[str]] +HAS_31_DAYS: Final = (1, 2, 3, 4, 5, 6) +HAS_30_DAYS: Final = (7, 8, 9, 10, 11) + +def leap(year: int) -> bool: ... +def equinox_jd(gyear: int) -> int: ... +def last_equinox_jd(jd: float) -> int: ... +def jd_to_pyear(jd: float) -> tuple[int, int]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[29, 30, 31]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/positivist.pyi b/stubs/convertdate/convertdate/positivist.pyi new file mode 100644 index 000000000000..51dcfd398dc4 --- /dev/null +++ b/stubs/convertdate/convertdate/positivist.pyi @@ -0,0 +1,15 @@ +from typing import Final, Literal + +EPOCH: Final = 2374479.5 +YEAR_EPOCH: Final = 1789 +DAYS_IN_YEAR: Final = 365 +MONTHS: Final[tuple[str, ...]] + +def legal_date(year: int, month: int, day: int) -> Literal[True]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def dayname(year: int, month: int, day: int) -> tuple[str, str]: ... +def weekday(day: int) -> int: ... +def festival(month: int, day: int) -> str | None: ... diff --git a/stubs/convertdate/convertdate/utils.pyi b/stubs/convertdate/convertdate/utils.pyi new file mode 100644 index 000000000000..3e6f89a2e981 --- /dev/null +++ b/stubs/convertdate/convertdate/utils.pyi @@ -0,0 +1,53 @@ +from typing import Final, Literal, overload + +TROPICALYEAR: Final[float] + +@overload +def amod(a: float, b: int) -> int: ... +@overload +def amod(a: float, b: float) -> float: ... + +def jwday(j: float) -> int: ... + +@overload +def weekday_before(weekday: int, jd: int) -> int: ... +@overload +def weekday_before(weekday: int, jd: float) -> float: ... + +@overload +def search_weekday(weekday: int, jd: int, direction: Literal[-1, 1], offset: int) -> int: ... +@overload +def search_weekday(weekday: int, jd: float, direction: Literal[-1, 1], offset: int) -> float: ... + +@overload +def nearest_weekday(weekday: int, jd: int) -> int: ... +@overload +def nearest_weekday(weekday: int, jd: float) -> float: ... + +@overload +def next_weekday(weekday: int, jd: int) -> int: ... +@overload +def next_weekday(weekday: int, jd: float) -> float: ... + +@overload +def next_or_current_weekday(weekday: int, jd: int) -> int: ... +@overload +def next_or_current_weekday(weekday: int, jd: float) -> float: ... + +@overload +def previous_weekday(weekday: int, jd: int) -> int: ... +@overload +def previous_weekday(weekday: int, jd: float) -> float: ... + +@overload +def previous_or_current_weekday(weekday: int, jd: int) -> int: ... +@overload +def previous_or_current_weekday(weekday: int, jd: float) -> float: ... + +@overload +def n_weeks(weekday: int, jd: int, nthweek: int) -> int: ... +@overload +def n_weeks(weekday: int, jd: float, nthweek: int) -> float: ... + +def monthcalendarhelper(start_weekday: int, month_length: int) -> list[list[int | None]]: ... +def nth_day_of_month(n: int, weekday: int, month: int, year: int) -> tuple[int, int, int]: ... diff --git a/stubs/croniter/@tests/stubtest_allowlist.txt b/stubs/croniter/@tests/stubtest_allowlist.txt index 5eb01ecab6ff..a5206909ac76 100644 --- a/stubs/croniter/@tests/stubtest_allowlist.txt +++ b/stubs/croniter/@tests/stubtest_allowlist.txt @@ -1,3 +1 @@ -croniter.CroniterError -croniter.croniter.__next__ -croniter.croniter.next +croniter.tests.* diff --git a/stubs/croniter/METADATA.toml b/stubs/croniter/METADATA.toml index e29f8e7f8ef1..0470bcfbbb5a 100644 --- a/stubs/croniter/METADATA.toml +++ b/stubs/croniter/METADATA.toml @@ -1,2 +1,2 @@ -version = "1.0.*" -python2 = true +version = "6.2.4" +upstream-repository = "https://github.com/pallets-eco/croniter" diff --git a/stubs/croniter/croniter.pyi b/stubs/croniter/croniter.pyi deleted file mode 100644 index 820e0ee50a42..000000000000 --- a/stubs/croniter/croniter.pyi +++ /dev/null @@ -1,78 +0,0 @@ -import datetime -from typing import Any, Iterator, Text, Tuple, Type, TypeVar, Union -from typing_extensions import Literal - -_RetType = Union[Type[float], Type[datetime.datetime]] -_SelfT = TypeVar("_SelfT", bound=croniter) - -class CroniterError(ValueError): ... -class CroniterBadCronError(CroniterError): ... -class CroniterBadDateError(CroniterError): ... -class CroniterNotAlphaError(CroniterError): ... - -class croniter(Iterator[Any]): - MONTHS_IN_YEAR: Literal[12] - RANGES: Tuple[tuple[int, int], ...] - DAYS: tuple[ - Literal[31], - Literal[28], - Literal[31], - Literal[30], - Literal[31], - Literal[30], - Literal[31], - Literal[31], - Literal[30], - Literal[31], - Literal[30], - Literal[31], - ] - ALPHACONV: Tuple[dict[str, Any], ...] - LOWMAP: Tuple[dict[int, Any], ...] - LEN_MEANS_ALL: Tuple[int, ...] - bad_length: str - tzinfo: datetime.tzinfo | None - cur: float - expanded: list[list[str]] - start_time: float - dst_start_time: float - nth_weekday_of_month: dict[str, Any] - def __init__( - self, - expr_format: Text, - start_time: float | datetime.datetime | None = ..., - ret_type: _RetType | None = ..., - day_or: bool = ..., - max_years_between_matches: int | None = ..., - is_prev: bool = ..., - hash_id: str | bytes | None = ..., # unicode not accepted on python 2 - ) -> None: ... - # Most return value depend on ret_type, which can be passed in both as a method argument and as - # a constructor argument. - def get_next(self, ret_type: _RetType | None = ..., start_time: float | datetime.datetime | None = ...) -> Any: ... - def get_prev(self, ret_type: _RetType | None = ...) -> Any: ... - def get_current(self, ret_type: _RetType | None = ...) -> Any: ... - def set_current(self, start_time: float | datetime.datetime) -> float: ... - def __iter__(self: _SelfT) -> _SelfT: ... - def __next__(self, ret_type: _RetType | None = ...) -> Any: ... - def next(self, ret_type: _RetType | None = ...) -> Any: ... - def all_next(self, ret_type: _RetType | None = ...) -> Iterator[Any]: ... - def all_prev(self, ret_type: _RetType | None = ...) -> Iterator[Any]: ... - def iter(self, ret_type: _RetType | None = ...) -> Iterator[Any]: ... - def is_leap(self, year: int) -> bool: ... - @classmethod - def expand(cls, expr_format: Text, hash_id: str | bytes | None = ...) -> tuple[list[list[str]], dict[str, Any]]: ... - @classmethod - def is_valid(cls, expression: Text, hash_id: str | bytes | None = ...) -> bool: ... - @classmethod - def match(cls, cron_expression: Text, testdate: float | datetime.datetime | None, day_or: bool = ...) -> bool: ... - -def croniter_range( - start: float | datetime.datetime, - stop: float | datetime.datetime, - expr_format: Text, - ret_type: _RetType | None = ..., - day_or: bool = ..., - exclude_ends: bool = ..., - _croniter: Type[croniter] | None = ..., -) -> Iterator[Any]: ... diff --git a/stubs/croniter/croniter/__init__.pyi b/stubs/croniter/croniter/__init__.pyi new file mode 100644 index 000000000000..164f8b701f56 --- /dev/null +++ b/stubs/croniter/croniter/__init__.pyi @@ -0,0 +1,43 @@ +from . import croniter as croniter_m +from .croniter import ( + DAY_FIELD as DAY_FIELD, + HOUR_FIELD as HOUR_FIELD, + MINUTE_FIELD as MINUTE_FIELD, + MONTH_FIELD as MONTH_FIELD, + OVERFLOW32B_MODE as OVERFLOW32B_MODE, + SECOND_FIELD as SECOND_FIELD, + UTC_DT as UTC_DT, + YEAR_FIELD as YEAR_FIELD, + CroniterBadCronError as CroniterBadCronError, + CroniterBadDateError as CroniterBadDateError, + CroniterBadTypeRangeError as CroniterBadTypeRangeError, + CroniterError as CroniterError, + CroniterNotAlphaError as CroniterNotAlphaError, + CroniterUnsupportedSyntaxError as CroniterUnsupportedSyntaxError, + croniter as croniter, + croniter_range as croniter_range, + datetime_to_timestamp as datetime_to_timestamp, +) + +cron_m = croniter_m + +__all__ = [ + "DAY_FIELD", + "HOUR_FIELD", + "MINUTE_FIELD", + "MONTH_FIELD", + "OVERFLOW32B_MODE", + "SECOND_FIELD", + "UTC_DT", + "YEAR_FIELD", + "CroniterBadCronError", + "CroniterBadDateError", + "CroniterBadTypeRangeError", + "CroniterError", + "CroniterNotAlphaError", + "CroniterUnsupportedSyntaxError", + "cron_m", + "croniter", + "croniter_range", + "datetime_to_timestamp", +] diff --git a/stubs/croniter/croniter/croniter.pyi b/stubs/croniter/croniter/croniter.pyi new file mode 100644 index 000000000000..ce5ecf5a59cf --- /dev/null +++ b/stubs/croniter/croniter/croniter.pyi @@ -0,0 +1,359 @@ +import datetime +from _typeshed import Unused +from collections.abc import Generator, Iterable +from re import Match, Pattern +from typing import Any, Final, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self + +_R_co = TypeVar("_R_co", float, datetime.datetime, default=float, covariant=True) +_R2_co = TypeVar("_R2_co", float, datetime.datetime, covariant=True) +_Expressions: TypeAlias = list[str] # fixed-length list of 5 or 6 strings +ExpandedExpression: TypeAlias = list[int | Literal["*", "l"]] + +@type_check_only +class _AllIter(Protocol[_R_co]): + @overload + def __call__( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R2_co]: ... + @overload + def __call__( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R_co]: ... + +def is_32bit() -> bool: ... + +OVERFLOW32B_MODE: Final[bool] + +UTC_DT: Final[datetime.timezone] +EPOCH: Final[datetime.datetime] +M_ALPHAS: Final[dict[str, int]] +DOW_ALPHAS: Final[dict[str, int]] + +MINUTE_FIELD: Final = 0 +HOUR_FIELD: Final = 1 +DAY_FIELD: Final = 2 +MONTH_FIELD: Final = 3 +DOW_FIELD: Final = 4 +SECOND_FIELD: Final = 5 +YEAR_FIELD: Final = 6 + +UNIX_FIELDS: Final[tuple[int, int, int, int, int]] +SECOND_FIELDS: Final[tuple[int, int, int, int, int, int]] +YEAR_FIELDS: Final[tuple[int, int, int, int, int, int, int]] + +step_search_re: Final[Pattern[str]] +only_int_re: Final[Pattern[str]] + +DAYS: Final[tuple[int, int, int, int, int, int, int, int, int, int, int, int]] +WEEKDAYS: Final[str] +MONTHS: Final[str] +star_or_int_re: Final[Pattern[str]] +special_dow_re: Final[Pattern[str]] +nearest_weekday_re: Final[Pattern[str]] +re_star: Final[Pattern[str]] +hash_expression_re: Final[Pattern[str]] + +CRON_FIELDS: Final[dict[str | int, tuple[int, ...]]] +UNIX_CRON_LEN: Final = 5 +SECOND_CRON_LEN: Final = 6 +YEAR_CRON_LEN: Final = 7 +VALID_LEN_EXPRESSION: Final[set[int]] +MARKER: object + +def datetime_to_timestamp(d: datetime.datetime) -> float: ... + +class CroniterError(ValueError): ... +class CroniterBadTypeRangeError(TypeError): ... +class CroniterBadCronError(CroniterError): ... +class CroniterUnsupportedSyntaxError(CroniterBadCronError): ... +class CroniterBadDateError(CroniterError): ... +class CroniterNotAlphaError(CroniterError): ... + +class croniter(Generic[_R_co]): + MONTHS_IN_YEAR: Final = 12 + RANGES: Final[ + tuple[ + tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int] + ] + ] + ALPHACONV: Final[ + tuple[ + dict[Never, Never], + dict[Never, Never], + dict[str, str], + dict[str, int], + dict[str, int], + dict[Never, Never], + dict[Never, Never], + ] + ] + LOWMAP: Final[ + tuple[ + dict[Never, Never], + dict[Never, Never], + dict[int, int], + dict[int, int], + dict[int, int], + dict[Never, Never], + dict[Never, Never], + ] + ] + LEN_MEANS_ALL: Final[tuple[int, int, int, int, int, int, int]] + + second_at_beginning: bool + tzinfo: datetime.tzinfo | None + + start_time: float + dst_start_time: float + cur: float + + expanded: list[list[str]] + nth_weekday_of_month: dict[str, set[int]] + expressions: _Expressions + nearest_weekday: set[int] + fields: tuple[int, ...] + + @overload + def __new__( + cls, + expr_format: str, + start_time: float | datetime.datetime | None = None, + ret_type: type[float] = ..., + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> croniter[float]: ... + @overload + def __new__( + cls, + expr_format: str, + start_time: float | datetime.datetime | None, + ret_type: type[datetime.datetime], + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> croniter[datetime.datetime]: ... + @overload + def __new__( + cls, + expr_format: str, + *, + ret_type: type[datetime.datetime], + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> croniter[datetime.datetime]: ... + + def __init__( + self, + expr_format: str, + start_time: float | datetime.datetime | None = None, + ret_type: type[_R_co] = ..., + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> None: ... + + @overload + def get_next( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R2_co: ... + @overload + def get_next( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R_co: ... + + @overload + def get_prev( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R2_co: ... + @overload + def get_prev( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R_co: ... + + @overload + def get_current(self, ret_type: type[_R2_co]) -> _R2_co: ... + @overload + def get_current(self, ret_type: None = None) -> _R_co: ... + + def set_current(self, start_time: float | datetime.datetime | None, force: bool = True) -> float: ... + @staticmethod + def datetime_to_timestamp(d: datetime.datetime) -> float: ... + def timestamp_to_datetime(self, timestamp: float, tzinfo: datetime.tzinfo | None = ...) -> datetime.datetime: ... + + @overload + def all_next( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R2_co]: ... + @overload + def all_next( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R_co]: ... + + @overload + def all_prev( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R2_co]: ... + @overload + def all_prev( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R_co]: ... + + def iter(self, *args: Unused, **kwargs: Unused) -> _AllIter[_R_co]: ... + def __iter__(self) -> Self: ... + + @overload + def next( + self, + ret_type: type[_R2_co], + start_time: float | datetime.datetime | None = None, + is_prev: bool | None = None, + update_current: bool | None = None, + ) -> _R2_co: ... + @overload + def next( + self, + ret_type: None = None, + start_time: float | datetime.datetime | None = None, + is_prev: bool | None = None, + update_current: bool | None = None, + ) -> _R_co: ... + + __next__ = next + @classmethod + def value_alias( + cls, + val: int, + field_index: Literal[0, 1, 2, 3, 4, 5, 6], + len_expressions: int | list[Any] | dict[Any, Any] | tuple[Any, ...] | set[Any] = 5, + ) -> int: ... + DAYS_IN_MONTH: Final[dict[int, int]] + @classmethod + def expand( + cls, + expr_format: str, + hash_id: bytes | None = None, + second_at_beginning: bool = False, + from_timestamp: float | None = None, + strict: bool = False, + strict_year: int | Iterable[int] | None = None, + ) -> tuple[list[ExpandedExpression], dict[str, set[int]]]: ... + @classmethod + def is_valid( + cls, + expression: str, + hash_id: bytes | None = None, + encoding: str = "UTF-8", + second_at_beginning: bool = False, + strict: bool = False, + strict_year: int | Iterable[int] | None = None, + ) -> bool: ... + @classmethod + def match( + cls, + cron_expression: str, + testdate: float | datetime.datetime | None, + day_or: bool = True, + second_at_beginning: bool = False, + precision_in_seconds: int | None = None, + ) -> bool: ... + @classmethod + def match_range( + cls, + cron_expression: str, + from_datetime: datetime.datetime, + to_datetime: datetime.datetime, + day_or: bool = True, + second_at_beginning: bool = False, + precision_in_seconds: int | None = None, + ) -> bool: ... + +@overload +def croniter_range( + start: float | datetime.datetime, + stop: float | datetime.datetime, + expr_format: str, + ret_type: type[_R2_co], + day_or: bool = True, + exclude_ends: bool = False, + _croniter: type[croniter] | None = None, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, +) -> Generator[_R2_co]: ... +@overload +def croniter_range( + start: float, + stop: float | datetime.datetime, + expr_format: str, + ret_type: None = None, + day_or: bool = True, + exclude_ends: bool = False, + _croniter: type[croniter] | None = None, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, +) -> Generator[float]: ... +@overload +def croniter_range( + start: datetime.datetime, + stop: float | datetime.datetime, + expr_format: str, + ret_type: None = None, + day_or: bool = True, + exclude_ends: bool = False, + _croniter: type[croniter] | None = None, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, +) -> Generator[datetime.datetime]: ... + +class HashExpander: + cron: croniter + def __init__(self, cronit: croniter) -> None: ... + + @overload + def do( + self, + idx: int, + hash_type: Literal["r"], + hash_id: None = None, + range_end: int | None = None, + range_begin: int | None = None, + ) -> int: ... + @overload + def do( + self, idx: int, hash_type: str, hash_id: bytes, range_end: int | None = None, range_begin: int | None = None + ) -> int: ... + @overload + def do( + self, idx: int, hash_type: str = "h", *, hash_id: bytes, range_end: int | None = None, range_begin: int | None = None + ) -> int: ... + + def match(self, efl: Unused, idx: Unused, expr: str, hash_id: bytes | None = None, **kw: Unused) -> Match[str] | None: ... + def expand( + self, + efl: object, + idx: int, + expr: str, + hash_id: bytes | None = None, + match: Match[str] | Literal[""] | None = "", + **kw: object, + ) -> str: ... + +EXPANDERS: dict[str, type[HashExpander]] diff --git a/stubs/cryptography/@tests/stubtest_allowlist.txt b/stubs/cryptography/@tests/stubtest_allowlist.txt deleted file mode 100644 index bf470c14d9a7..000000000000 --- a/stubs/cryptography/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,38 +0,0 @@ -cryptography.exceptions.UnsupportedAlgorithm.__init__ -cryptography.fernet.Fernet.__init__ -cryptography.fernet.MultiFernet.decrypt -cryptography.fernet.MultiFernet.decrypt_at_time -cryptography.fernet.MultiFernet.encrypt -cryptography.fernet.MultiFernet.encrypt_at_time -cryptography.hazmat.backends.interfaces.DHBackend.dh_parameters_supported -cryptography.hazmat.backends.interfaces.HMACBackend.cmac_algorithm_supported -cryptography.hazmat.bindings.openssl.binding.Binding.init_static_locks -cryptography.hazmat.primitives.asymmetric.dh.DHParameterNumbers.__init__ -cryptography.hazmat.primitives.ciphers.aead.AESCCM.__init__ -cryptography.hazmat.primitives.cmac.CMAC.__init__ -cryptography.hazmat.primitives.hashes.BLAKE2b.__init__ -cryptography.hazmat.primitives.hashes.BLAKE2s.__init__ -cryptography.hazmat.primitives.hashes.Hash.__init__ -cryptography.hazmat.primitives.hmac.HMAC.__init__ -cryptography.hazmat.primitives.hmac.HMAC.update -cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates -cryptography.hazmat.primitives.serialization.pkcs7.PKCS7SignatureBuilder.__init__ -cryptography.x509.CertificateBuilder.public_key -cryptography.x509.CertificateBuilder.serial_number -cryptography.x509.CertificateRevocationListBuilder.__init__ -cryptography.x509.CertificateRevocationListBuilder.issuer_name -cryptography.x509.CertificateRevocationListBuilder.last_update -cryptography.x509.CertificateRevocationListBuilder.next_update -cryptography.x509.CertificateSigningRequestBuilder.__init__ -cryptography.x509.Extension.__init__ -cryptography.x509.Extensions.__init__ -cryptography.x509.NameAttribute.__init__ -cryptography.x509.OCSPExtensionOID -cryptography.x509.RevokedCertificateBuilder.__init__ -cryptography.x509.RevokedCertificateBuilder.serial_number -cryptography.x509.extensions.AccessDescription.__init__ -cryptography.x509.extensions.AuthorityInformationAccess.__init__ -cryptography.x509.extensions.CRLDistributionPoints.__init__ -cryptography.x509.extensions.DistributionPoint.__init__ -cryptography.x509.extensions.Extension.__init__ -cryptography.x509.extensions.GeneralNames.__init__ diff --git a/stubs/cryptography/METADATA.toml b/stubs/cryptography/METADATA.toml deleted file mode 100644 index 67fb5034d2cd..000000000000 --- a/stubs/cryptography/METADATA.toml +++ /dev/null @@ -1,4 +0,0 @@ -version = "3.3.*" -python2 = true -requires = ["types-enum34", "types-ipaddress"] -obsolete_since = "3.4.4" diff --git a/stubs/cryptography/cryptography/exceptions.pyi b/stubs/cryptography/cryptography/exceptions.pyi deleted file mode 100644 index 48041a805cea..000000000000 --- a/stubs/cryptography/cryptography/exceptions.pyi +++ /dev/null @@ -1,7 +0,0 @@ -class AlreadyFinalized(Exception): ... -class AlreadyUpdated(Exception): ... -class InvalidKey(Exception): ... -class InvalidSignature(Exception): ... -class InvalidTag(Exception): ... -class NotYetFinalized(Exception): ... -class UnsupportedAlgorithm(Exception): ... diff --git a/stubs/cryptography/cryptography/fernet.pyi b/stubs/cryptography/cryptography/fernet.pyi deleted file mode 100644 index 2eb1e189bbe0..000000000000 --- a/stubs/cryptography/cryptography/fernet.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Text - -class InvalidToken(Exception): ... - -class Fernet(object): - def __init__(self, key: bytes | Text) -> None: ... - def decrypt(self, token: bytes, ttl: int | None = ...) -> bytes: ... - # decrypt_at_time accepts None ttl at runtime but it's an implementtion detail and it doesn't really - # make sense for the client code to use it like that, so the parameter is typed as int as opposed to - # int | None. - def decrypt_at_time(self, token: bytes, ttl: int, current_time: int) -> bytes: ... - def encrypt(self, data: bytes) -> bytes: ... - def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: ... - def extract_timestamp(self, token: bytes) -> int: ... - @classmethod - def generate_key(cls) -> bytes: ... - -class MultiFernet(object): - def __init__(self, fernets: list[Fernet]) -> None: ... - def decrypt(self, token: bytes, ttl: int | None = ...) -> bytes: ... - # See a note above on the typing of the ttl parameter. - def decrypt_at_time(self, token: bytes, ttl: int, current_time: int) -> bytes: ... - def encrypt(self, data: bytes) -> bytes: ... - def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: ... - def rotate(self, msg: bytes) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/__init__.pyi b/stubs/cryptography/cryptography/hazmat/__init__.pyi deleted file mode 100644 index e27843e53382..000000000000 --- a/stubs/cryptography/cryptography/hazmat/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... diff --git a/stubs/cryptography/cryptography/hazmat/backends/__init__.pyi b/stubs/cryptography/cryptography/hazmat/backends/__init__.pyi deleted file mode 100644 index d452202eee99..000000000000 --- a/stubs/cryptography/cryptography/hazmat/backends/__init__.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -def default_backend() -> Any: ... - -# TODO: add some backends -def __getattr__(name: str) -> Any: ... diff --git a/stubs/cryptography/cryptography/hazmat/backends/interfaces.pyi b/stubs/cryptography/cryptography/hazmat/backends/interfaces.pyi deleted file mode 100644 index 9dbbecfbe3f7..000000000000 --- a/stubs/cryptography/cryptography/hazmat/backends/interfaces.pyi +++ /dev/null @@ -1,196 +0,0 @@ -from abc import ABCMeta, abstractmethod -from typing import Any - -from cryptography.hazmat.primitives.asymmetric.dh import ( - DHParameterNumbers, - DHParameters, - DHPrivateKey, - DHPrivateNumbers, - DHPublicKey, - DHPublicNumbers, -) -from cryptography.hazmat.primitives.asymmetric.dsa import ( - DSAParameterNumbers, - DSAParameters, - DSAPrivateKey, - DSAPrivateNumbers, - DSAPublicKey, - DSAPublicNumbers, -) -from cryptography.hazmat.primitives.asymmetric.ec import ( - EllipticCurve, - EllipticCurvePrivateKey, - EllipticCurvePrivateNumbers, - EllipticCurvePublicKey, - EllipticCurvePublicNumbers, - EllipticCurveSignatureAlgorithm, -) -from cryptography.hazmat.primitives.asymmetric.padding import AsymmetricPadding -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPrivateNumbers, RSAPublicKey, RSAPublicNumbers -from cryptography.hazmat.primitives.ciphers import BlockCipherAlgorithm, CipherAlgorithm, CipherContext -from cryptography.hazmat.primitives.ciphers.modes import Mode -from cryptography.hazmat.primitives.hashes import HashAlgorithm, HashContext -from cryptography.x509 import ( - Certificate, - CertificateBuilder, - CertificateRevocationList, - CertificateRevocationListBuilder, - CertificateSigningRequest, - CertificateSigningRequestBuilder, - Name, - RevokedCertificate, - RevokedCertificateBuilder, -) - -class CipherBackend(metaclass=ABCMeta): - @abstractmethod - def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool: ... - @abstractmethod - def create_symmetric_encryption_ctx(self, cipher: CipherAlgorithm, mode: Mode) -> CipherContext: ... - @abstractmethod - def create_symmetric_decryption_ctx(self, cipher: CipherAlgorithm, mode: Mode) -> CipherContext: ... - -class CMACBackend(metaclass=ABCMeta): - @abstractmethod - def cmac_algorithm_supported(self, algorithm: BlockCipherAlgorithm) -> bool: ... - @abstractmethod - def create_cmac_ctx(self, algorithm: BlockCipherAlgorithm) -> Any: ... - -class DERSerializationBackend(metaclass=ABCMeta): - @abstractmethod - def load_der_parameters(self, data: bytes) -> Any: ... - @abstractmethod - def load_der_private_key(self, data: bytes, password: bytes | None) -> Any: ... - @abstractmethod - def load_der_public_key(self, data: bytes) -> Any: ... - -class DHBackend(metaclass=ABCMeta): - @abstractmethod - def dh_parameters_supported(self, p: int, g: int, q: int | None) -> bool: ... - @abstractmethod - def dh_x942_serialization_supported(self) -> bool: ... - @abstractmethod - def generate_dh_parameters(self, generator: int, key_size: int) -> DHParameters: ... - @abstractmethod - def generate_dh_private_key(self, parameters: DHParameters) -> DHPrivateKey: ... - @abstractmethod - def generate_dh_private_key_and_parameters(self, generator: int, key_size: int) -> DHPrivateKey: ... - @abstractmethod - def load_dh_parameter_numbers(self, numbers: DHParameterNumbers) -> DHParameters: ... - @abstractmethod - def load_dh_private_numbers(self, numbers: DHPrivateNumbers) -> DHPrivateKey: ... - @abstractmethod - def load_dh_public_numbers(self, numbers: DHPublicNumbers) -> DHPublicKey: ... - -class DSABackend(metaclass=ABCMeta): - @abstractmethod - def dsa_hash_supported(self, algorithm: HashAlgorithm) -> bool: ... - @abstractmethod - def dsa_parameters_supported(self, p: int, q: int, g: int) -> bool: ... - @abstractmethod - def generate_dsa_parameters(self, key_size: int) -> DSAParameters: ... - @abstractmethod - def generate_dsa_private_key(self, parameters: DSAParameters) -> DSAPrivateKey: ... - @abstractmethod - def generate_dsa_private_key_and_parameters(self, key_size: int) -> DSAPrivateKey: ... - @abstractmethod - def load_dsa_parameter_numbers(self, numbers: DSAParameterNumbers) -> DSAParameters: ... - @abstractmethod - def load_dsa_private_numbers(self, numbers: DSAPrivateNumbers) -> DSAPrivateKey: ... - @abstractmethod - def load_dsa_public_numbers(self, numbers: DSAPublicNumbers) -> DSAPublicKey: ... - -class EllipticCurveBackend(metaclass=ABCMeta): - @abstractmethod - def derive_elliptic_curve_private_key(self, private_value: int, curve: EllipticCurve) -> EllipticCurvePrivateKey: ... - @abstractmethod - def elliptic_curve_signature_algorithm_supported( - self, signature_algorithm: EllipticCurveSignatureAlgorithm, curve: EllipticCurve - ) -> bool: ... - @abstractmethod - def elliptic_curve_supported(self, curve: EllipticCurve) -> bool: ... - @abstractmethod - def generate_elliptic_curve_private_key(self, curve: EllipticCurve) -> EllipticCurvePrivateKey: ... - @abstractmethod - def load_elliptic_curve_private_numbers(self, numbers: EllipticCurvePrivateNumbers) -> EllipticCurvePrivateKey: ... - @abstractmethod - def load_elliptic_curve_public_numbers(self, numbers: EllipticCurvePublicNumbers) -> EllipticCurvePublicKey: ... - -class HMACBackend(metaclass=ABCMeta): - @abstractmethod - def create_hmac_ctx(self, key: bytes, algorithm: HashAlgorithm) -> HashContext: ... - @abstractmethod - def cmac_algorithm_supported(self, algorithm: HashAlgorithm) -> bool: ... - -class HashBackend(metaclass=ABCMeta): - @abstractmethod - def create_hash_ctx(self, algorithm: HashAlgorithm) -> HashContext: ... - @abstractmethod - def hash_supported(self, algorithm: HashAlgorithm) -> bool: ... - -class PBKDF2HMACBackend(metaclass=ABCMeta): - @abstractmethod - def derive_pbkdf2_hmac( - self, algorithm: HashAlgorithm, length: int, salt: bytes, iterations: int, key_material: bytes - ) -> bytes: ... - @abstractmethod - def pbkdf2_hmac_supported(self, algorithm: HashAlgorithm) -> bool: ... - -class PEMSerializationBackend(metaclass=ABCMeta): - @abstractmethod - def load_pem_parameters(self, data: bytes) -> Any: ... - @abstractmethod - def load_pem_private_key(self, data: bytes, password: bytes | None) -> Any: ... - @abstractmethod - def load_pem_public_key(self, data: bytes) -> Any: ... - -class RSABackend(metaclass=ABCMeta): - @abstractmethod - def generate_rsa_parameters_supported(self, public_exponent: int, key_size: int) -> bool: ... - @abstractmethod - def generate_rsa_private_key(self, public_exponent: int, key_size: int) -> RSAPrivateKey: ... - @abstractmethod - def load_rsa_public_numbers(self, numbers: RSAPublicNumbers) -> RSAPublicKey: ... - @abstractmethod - def load_rsa_private_numbers(self, numbers: RSAPrivateNumbers) -> RSAPrivateKey: ... - @abstractmethod - def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool: ... - -class ScryptBackend(metaclass=ABCMeta): - @abstractmethod - def derive_scrypt(self, key_material: bytes, salt: bytes, length: int, n: int, r: int, p: int) -> bytes: ... - -class X509Backend(metaclass=ABCMeta): - @abstractmethod - def create_x509_certificate( - self, - builder: CertificateBuilder, - private_key: DSAPrivateKey | EllipticCurvePrivateKey | RSAPrivateKey, - algorithm: HashAlgorithm, - ) -> Certificate: ... - @abstractmethod - def create_x509_crl( - self, - builder: CertificateRevocationListBuilder, - private_key: DSAPrivateKey | EllipticCurvePrivateKey | RSAPrivateKey, - algorithm: HashAlgorithm, - ) -> CertificateRevocationList: ... - @abstractmethod - def create_x509_csr( - self, - builder: CertificateSigningRequestBuilder, - private_key: DSAPrivateKey | EllipticCurvePrivateKey | RSAPrivateKey, - algorithm: HashAlgorithm, - ) -> CertificateSigningRequest: ... - @abstractmethod - def create_x509_revoked_certificate(self, builder: RevokedCertificateBuilder) -> RevokedCertificate: ... - @abstractmethod - def load_der_x509_certificate(self, data: bytes) -> Certificate: ... - @abstractmethod - def load_der_x509_csr(self, data: bytes) -> CertificateSigningRequest: ... - @abstractmethod - def load_pem_x509_certificate(self, data: bytes) -> Certificate: ... - @abstractmethod - def load_pem_x509_csr(self, data: bytes) -> CertificateSigningRequest: ... - @abstractmethod - def x509_name_bytes(self, name: Name) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/bindings/openssl/binding.pyi b/stubs/cryptography/cryptography/hazmat/bindings/openssl/binding.pyi deleted file mode 100644 index 51c967bee642..000000000000 --- a/stubs/cryptography/cryptography/hazmat/bindings/openssl/binding.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -class Binding(object): - ffi: Any | None - lib: Any | None - def init_static_locks(self) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/__init__.pyi b/stubs/cryptography/cryptography/hazmat/primitives/__init__.pyi deleted file mode 100644 index e27843e53382..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/__init__.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/__init__.pyi deleted file mode 100644 index e27843e53382..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/dh.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/dh.pyi deleted file mode 100644 index 7846f75b055c..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/dh.pyi +++ /dev/null @@ -1,78 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.backends.interfaces import DHBackend -from cryptography.hazmat.primitives.serialization import ( - Encoding, - KeySerializationEncryption, - ParameterFormat, - PrivateFormat, - PublicFormat, -) - -class DHParameters(metaclass=ABCMeta): - @abstractmethod - def generate_private_key(self) -> DHPrivateKey: ... - @abstractmethod - def parameter_bytes(self, encoding: Encoding, format: ParameterFormat) -> bytes: ... - @abstractmethod - def parameter_numbers(self) -> DHParameterNumbers: ... - -DHParametersWithSerialization = DHParameters - -class DHParameterNumbers(object): - @property - def p(self) -> int: ... - @property - def g(self) -> int: ... - @property - def q(self) -> int: ... - def __init__(self, p: int, g: int, q: int | None) -> None: ... - def parameters(self, backend: DHBackend | None = ...) -> DHParameters: ... - -class DHPrivateKey(metaclass=ABCMeta): - key_size: int - @abstractmethod - def exchange(self, peer_public_key: DHPublicKey) -> bytes: ... - @abstractmethod - def parameters(self) -> DHParameters: ... - @abstractmethod - def public_key(self) -> DHPublicKey: ... - -class DHPrivateKeyWithSerialization(DHPrivateKey): - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def private_numbers(self) -> DHPrivateNumbers: ... - -class DHPrivateNumbers(object): - @property - def public_numbers(self) -> DHPublicNumbers: ... - @property - def x(self) -> int: ... - def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ... - def private_key(self, backend: DHBackend | None = ...) -> DHPrivateKey: ... - -class DHPublicKey(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @abstractmethod - def parameters(self) -> DHParameters: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... - @abstractmethod - def public_numbers(self) -> DHPublicNumbers: ... - -DHPublicKeyWithSerialization = DHPublicKey - -class DHPublicNumbers(object): - @property - def parameter_numbers(self) -> DHParameterNumbers: ... - @property - def y(self) -> int: ... - def __init__(self, y: int, parameter_numbers: DHParameterNumbers) -> None: ... - def public_key(self, backend: DHBackend | None = ...) -> DHPublicKey: ... - -def generate_parameters(generator: int, key_size: int, backend: DHBackend | None = ...) -> DHParameters: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/dsa.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/dsa.pyi deleted file mode 100644 index db9f191536de..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/dsa.pyi +++ /dev/null @@ -1,76 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.backends.interfaces import DSABackend -from cryptography.hazmat.primitives.asymmetric import AsymmetricVerificationContext -from cryptography.hazmat.primitives.asymmetric.utils import Prehashed -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat - -class DSAParameters(metaclass=ABCMeta): - @abstractmethod - def generate_private_key(self) -> DSAPrivateKey: ... - -class DSAParametersWithNumbers(DSAParameters): - @abstractmethod - def parameter_numbers(self) -> DSAParameterNumbers: ... - -class DSAParameterNumbers(object): - @property - def p(self) -> int: ... - @property - def q(self) -> int: ... - @property - def g(self) -> int: ... - def __init__(self, p: int, q: int, g: int) -> None: ... - def parameters(self, backend: DSABackend | None = ...) -> DSAParameters: ... - -class DSAPrivateKey(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @abstractmethod - def parameters(self) -> DSAParameters: ... - @abstractmethod - def public_key(self) -> DSAPublicKey: ... - @abstractmethod - def sign(self, data: bytes, algorithm: HashAlgorithm | Prehashed) -> bytes: ... - -class DSAPrivateKeyWithSerialization(DSAPrivateKey): - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def private_numbers(self) -> DSAPrivateNumbers: ... - -class DSAPrivateNumbers(object): - @property - def x(self) -> int: ... - @property - def public_numbers(self) -> DSAPublicNumbers: ... - def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ... - -class DSAPublicKey(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... - @abstractmethod - def public_numbers(self) -> DSAPublicNumbers: ... - @abstractmethod - def verifier(self, signature: bytes, signature_algorithm: HashAlgorithm | Prehashed) -> AsymmetricVerificationContext: ... - @abstractmethod - def verify(self, signature: bytes, data: bytes, algorithm: HashAlgorithm | Prehashed) -> None: ... - -DSAPublicKeyWithSerialization = DSAPublicKey - -class DSAPublicNumbers(object): - @property - def y(self) -> int: ... - @property - def parameter_numbers(self) -> DSAParameterNumbers: ... - def __init__(self, y: int, parameter_numbers: DSAParameterNumbers) -> None: ... - -def generate_parameters(key_size: int, backend: DSABackend | None = ...) -> DSAParameters: ... -def generate_private_key(key_size: int, backend: DSABackend | None = ...) -> DSAPrivateKey: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ec.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ec.pyi deleted file mode 100644 index 33fb4cb9a931..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ec.pyi +++ /dev/null @@ -1,196 +0,0 @@ -from abc import ABCMeta, abstractmethod -from typing import ClassVar - -from cryptography.hazmat.backends.interfaces import EllipticCurveBackend -from cryptography.hazmat.primitives.asymmetric import AsymmetricVerificationContext -from cryptography.hazmat.primitives.asymmetric.utils import Prehashed -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat -from cryptography.x509 import ObjectIdentifier - -class EllipticCurve(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @property - @abstractmethod - def name(self) -> str: ... - -class BrainpoolP256R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class BrainpoolP384R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class BrainpoolP512R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECP192R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECP224R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECP256K1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECP256R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECP384R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECP521R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT163K1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT163R2(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT233K1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT233R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT283K1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT283R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT409K1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT409R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT571K1(EllipticCurve): - key_size: int = ... - name: str = ... - -class SECT571R1(EllipticCurve): - key_size: int = ... - name: str = ... - -class EllipticCurveOID(object): - SECP192R1: ClassVar[ObjectIdentifier] - SECP224R1: ClassVar[ObjectIdentifier] - SECP256K1: ClassVar[ObjectIdentifier] - SECP256R1: ClassVar[ObjectIdentifier] - SECP384R1: ClassVar[ObjectIdentifier] - SECP521R1: ClassVar[ObjectIdentifier] - BRAINPOOLP256R1: ClassVar[ObjectIdentifier] - BRAINPOOLP384R1: ClassVar[ObjectIdentifier] - BRAINPOOLP512R1: ClassVar[ObjectIdentifier] - SECT163K1: ClassVar[ObjectIdentifier] - SECT163R2: ClassVar[ObjectIdentifier] - SECT233K1: ClassVar[ObjectIdentifier] - SECT233R1: ClassVar[ObjectIdentifier] - SECT283K1: ClassVar[ObjectIdentifier] - SECT283R1: ClassVar[ObjectIdentifier] - SECT409K1: ClassVar[ObjectIdentifier] - SECT409R1: ClassVar[ObjectIdentifier] - SECT571K1: ClassVar[ObjectIdentifier] - SECT571R1: ClassVar[ObjectIdentifier] - -class EllipticCurvePrivateKey(metaclass=ABCMeta): - @property - @abstractmethod - def curve(self) -> EllipticCurve: ... - @property - @abstractmethod - def key_size(self) -> int: ... - @abstractmethod - def exchange(self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey) -> bytes: ... - @abstractmethod - def public_key(self) -> EllipticCurvePublicKey: ... - @abstractmethod - def sign(self, data: bytes, signature_algorithm: EllipticCurveSignatureAlgorithm) -> bytes: ... - -class EllipticCurvePrivateKeyWithSerialization(EllipticCurvePrivateKey): - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def private_numbers(self) -> EllipticCurvePrivateNumbers: ... - -class EllipticCurvePrivateNumbers(object): - @property - def private_value(self) -> int: ... - @property - def public_numbers(self) -> EllipticCurvePublicNumbers: ... - def __init__(self, private_value: int, public_numbers: EllipticCurvePublicNumbers) -> None: ... - def private_key(self, backend: EllipticCurveBackend | None = ...) -> EllipticCurvePrivateKey: ... - -class EllipticCurvePublicKey(metaclass=ABCMeta): - @property - @abstractmethod - def curve(self) -> EllipticCurve: ... - @property - @abstractmethod - def key_size(self) -> int: ... - @classmethod - def from_encoded_point(cls, curve: EllipticCurve, data: bytes) -> EllipticCurvePublicKey: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... - @abstractmethod - def public_numbers(self) -> EllipticCurvePublicNumbers: ... - @abstractmethod - def verifier( - self, signature: bytes, signature_algorithm: EllipticCurveSignatureAlgorithm - ) -> AsymmetricVerificationContext: ... - @abstractmethod - def verify(self, signature: bytes, data: bytes, signature_algorithm: EllipticCurveSignatureAlgorithm) -> None: ... - -EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey - -class EllipticCurvePublicNumbers(object): - @property - def curve(self) -> EllipticCurve: ... - @property - def x(self) -> int: ... - @property - def y(self) -> int: ... - def __init__(self, x: int, y: int, curve: EllipticCurve) -> None: ... - @classmethod - def from_encoded_point(cls, curve: EllipticCurve, data: bytes) -> EllipticCurvePublicNumbers: ... - def public_key(self, backend: EllipticCurveBackend | None = ...) -> EllipticCurvePublicKey: ... - -class EllipticCurveSignatureAlgorithm(metaclass=ABCMeta): - @property - @abstractmethod - def algorithm(self) -> HashAlgorithm | Prehashed: ... - -class ECDH(object): ... - -class ECDSA(EllipticCurveSignatureAlgorithm): - def __init__(self, algorithm: HashAlgorithm | Prehashed): ... - @property - def algorithm(self) -> HashAlgorithm | Prehashed: ... - -def derive_private_key( - private_value: int, curve: EllipticCurve, backend: EllipticCurveBackend | None = ... -) -> EllipticCurvePrivateKey: ... -def generate_private_key(curve: EllipticCurve, backend: EllipticCurveBackend | None = ...) -> EllipticCurvePrivateKey: ... -def get_curve_for_oid(oid: ObjectIdentifier) -> EllipticCurve: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ed25519.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ed25519.pyi deleted file mode 100644 index 518d2d6b9ea5..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ed25519.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat - -class Ed25519PrivateKey(metaclass=ABCMeta): - @classmethod - def generate(cls) -> Ed25519PrivateKey: ... - @classmethod - def from_private_bytes(cls, data: bytes) -> Ed25519PrivateKey: ... - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def public_key(self) -> Ed25519PublicKey: ... - @abstractmethod - def sign(self, data: bytes) -> bytes: ... - -class Ed25519PublicKey(metaclass=ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... - @abstractmethod - def verify(self, signature: bytes, data: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ed448.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ed448.pyi deleted file mode 100644 index fa43fc1bc122..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/ed448.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat - -class Ed448PrivateKey(metaclass=ABCMeta): - @classmethod - def generate(cls) -> Ed448PrivateKey: ... - @classmethod - def from_private_bytes(cls, data: bytes) -> Ed448PrivateKey: ... - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def public_key(self) -> Ed448PublicKey: ... - @abstractmethod - def sign(self, data: bytes) -> bytes: ... - -class Ed448PublicKey(metaclass=ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> Ed448PublicKey: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... - @abstractmethod - def verify(self, signature: bytes, data: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/padding.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/padding.pyi deleted file mode 100644 index bb1781c132ef..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/padding.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from abc import ABCMeta, abstractmethod -from typing import ClassVar - -from cryptography.hazmat.primitives.hashes import HashAlgorithm - -class AsymmetricPadding(metaclass=ABCMeta): - @property - @abstractmethod - def name(self) -> str: ... - -class MGF1(object): - def __init__(self, algorithm: HashAlgorithm) -> None: ... - -class OAEP(AsymmetricPadding): - def __init__(self, mgf: MGF1, algorithm: HashAlgorithm, label: bytes | None) -> None: ... - @property - def name(self) -> str: ... - -class PKCS1v15(AsymmetricPadding): - @property - def name(self) -> str: ... - -class PSS(AsymmetricPadding): - MAX_LENGTH: ClassVar[object] - def __init__(self, mgf: MGF1, salt_length: int | object) -> None: ... - @property - def name(self) -> str: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/rsa.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/rsa.pyi deleted file mode 100644 index 958fc71f808c..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/rsa.pyi +++ /dev/null @@ -1,80 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.backends.interfaces import RSABackend -from cryptography.hazmat.primitives.asymmetric import AsymmetricVerificationContext -from cryptography.hazmat.primitives.asymmetric.padding import AsymmetricPadding -from cryptography.hazmat.primitives.asymmetric.utils import Prehashed -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat - -class RSAPrivateKey(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @abstractmethod - def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes: ... - @abstractmethod - def public_key(self) -> RSAPublicKey: ... - @abstractmethod - def sign(self, data: bytes, padding: AsymmetricPadding, algorithm: HashAlgorithm | Prehashed) -> bytes: ... - -class RSAPrivateKeyWithSerialization(RSAPrivateKey): - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def private_numbers(self) -> RSAPrivateNumbers: ... - -class RSAPublicKey(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @abstractmethod - def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... - @abstractmethod - def public_numbers(self) -> RSAPublicNumbers: ... - @abstractmethod - def verifier( - self, signature: bytes, padding: AsymmetricPadding, algorithm: HashAlgorithm | Prehashed - ) -> AsymmetricVerificationContext: ... - @abstractmethod - def verify(self, signature: bytes, data: bytes, padding: AsymmetricPadding, algorithm: HashAlgorithm | Prehashed) -> None: ... - -RSAPublicKeyWithSerialization = RSAPublicKey - -def generate_private_key( - public_exponent: int, key_size: int, backend: RSABackend | None = ... -) -> RSAPrivateKeyWithSerialization: ... -def rsa_crt_iqmp(p: int, q: int) -> int: ... -def rsa_crt_dmp1(private_exponent: int, p: int) -> int: ... -def rsa_crt_dmq1(private_exponent: int, q: int) -> int: ... -def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]: ... - -class RSAPrivateNumbers(object): - def __init__(self, p: int, q: int, d: int, dmp1: int, dmq1: int, iqmp: int, public_numbers: RSAPublicNumbers) -> None: ... - @property - def p(self) -> int: ... - @property - def q(self) -> int: ... - @property - def d(self) -> int: ... - @property - def dmp1(self) -> int: ... - @property - def dmq1(self) -> int: ... - @property - def iqmp(self) -> int: ... - @property - def public_numbers(self) -> RSAPublicNumbers: ... - def private_key(self, backend: RSABackend | None = ...) -> RSAPrivateKey: ... - -class RSAPublicNumbers(object): - def __init__(self, e: int, n: int) -> None: ... - @property - def e(self) -> int: ... - @property - def n(self) -> int: ... - def public_key(self, backend: RSABackend | None = ...) -> RSAPublicKey: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/utils.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/utils.pyi deleted file mode 100644 index 199bfc8ea4bb..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/utils.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from cryptography.hazmat.primitives.hashes import HashAlgorithm - -def decode_dss_signature(signature: bytes) -> tuple[int, int]: ... -def encode_dss_signature(r: int, s: int) -> bytes: ... - -class Prehashed(object): - _algorithm: HashAlgorithm # undocumented - _digest_size: int # undocumented - def __init__(self, algorithm: HashAlgorithm) -> None: ... - digest_size: int diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/x25519.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/x25519.pyi deleted file mode 100644 index 245878df7e54..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/x25519.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat - -class X25519PrivateKey(metaclass=ABCMeta): - @classmethod - def from_private_bytes(cls, data: bytes) -> X25519PrivateKey: ... - @classmethod - def generate(cls) -> X25519PrivateKey: ... - @abstractmethod - def exchange(self, peer_public_key: X25519PublicKey) -> bytes: ... - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def public_key(self) -> X25519PublicKey: ... - -class X25519PublicKey(metaclass=ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> X25519PublicKey: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/x448.pyi b/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/x448.pyi deleted file mode 100644 index a4620e510f60..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/asymmetric/x448.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat - -class X448PrivateKey(metaclass=ABCMeta): - @classmethod - def from_private_bytes(cls, data: bytes) -> X448PrivateKey: ... - @classmethod - def generate(cls) -> X448PrivateKey: ... - @abstractmethod - def exchange(self, peer_public_key: X448PublicKey) -> bytes: ... - @abstractmethod - def private_bytes( - self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption - ) -> bytes: ... - @abstractmethod - def public_key(self) -> X448PublicKey: ... - -class X448PublicKey(metaclass=ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> X448PublicKey: ... - @abstractmethod - def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/__init__.pyi b/stubs/cryptography/cryptography/hazmat/primitives/ciphers/__init__.pyi deleted file mode 100644 index f75a32cc50d9..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/__init__.pyi +++ /dev/null @@ -1,43 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.backends.interfaces import CipherBackend -from cryptography.hazmat.primitives.ciphers.modes import Mode - -class AEADCipherContext(metaclass=ABCMeta): - @abstractmethod - def authenticate_additional_data(self, data: bytes) -> None: ... - -class AEADDecryptionContext(metaclass=ABCMeta): - @abstractmethod - def finalize_with_tag(self, tag: bytes) -> bytes: ... - -class AEADEncryptionContext(metaclass=ABCMeta): - @property - @abstractmethod - def tag(self) -> bytes: ... - -class BlockCipherAlgorithm(metaclass=ABCMeta): - @property - @abstractmethod - def block_size(self) -> int: ... - -class Cipher(object): - def __init__(self, algorithm: CipherAlgorithm, mode: Mode | None, backend: CipherBackend | None = ...) -> None: ... - def decryptor(self) -> CipherContext: ... - def encryptor(self) -> CipherContext: ... - -class CipherAlgorithm(metaclass=ABCMeta): - @property - @abstractmethod - def key_size(self) -> int: ... - @property - @abstractmethod - def name(self) -> str: ... - -class CipherContext(metaclass=ABCMeta): - @abstractmethod - def finalize(self) -> bytes: ... - @abstractmethod - def update(self, data: bytes) -> bytes: ... - @abstractmethod - def update_into(self, data: bytes, buf: bytearray) -> int: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/aead.pyi b/stubs/cryptography/cryptography/hazmat/primitives/ciphers/aead.pyi deleted file mode 100644 index c6552a22813c..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/aead.pyi +++ /dev/null @@ -1,20 +0,0 @@ -class AESCCM(object): - def __init__(self, key: bytes, tag_length: int | None) -> None: ... - def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes | None) -> bytes: ... - def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes | None) -> bytes: ... - @classmethod - def generate_key(cls, bit_length: int) -> bytes: ... - -class AESGCM(object): - def __init__(self, key: bytes) -> None: ... - def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes | None) -> bytes: ... - def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes | None) -> bytes: ... - @classmethod - def generate_key(cls, bit_length: int) -> bytes: ... - -class ChaCha20Poly1305(object): - def __init__(self, key: bytes) -> None: ... - def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes | None) -> bytes: ... - def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes | None) -> bytes: ... - @classmethod - def generate_key(cls) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/algorithms.pyi b/stubs/cryptography/cryptography/hazmat/primitives/ciphers/algorithms.pyi deleted file mode 100644 index 466c70b055b5..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/algorithms.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from cryptography.hazmat.primitives.ciphers import BlockCipherAlgorithm, CipherAlgorithm -from cryptography.hazmat.primitives.ciphers.modes import ModeWithNonce - -class AES(BlockCipherAlgorithm, CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... - @property - def key_size(self) -> int: ... - -class ARC4(CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - name: str = ... - key_sizes: frozenset[int] = ... - -class Blowfish(BlockCipherAlgorithm, CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... - -class Camellia(BlockCipherAlgorithm, CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... - -class CAST5(BlockCipherAlgorithm, CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... - -class ChaCha20(CipherAlgorithm, ModeWithNonce): - def __init__(self, key: bytes, nonce: bytes) -> None: ... - @property - def key_size(self) -> int: ... - name: str = ... - key_sizes: frozenset[int] = ... - @property - def nonce(self) -> bytes: ... - -class IDEA(CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... - -class SEED(BlockCipherAlgorithm, CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... - -class TripleDES(BlockCipherAlgorithm, CipherAlgorithm): - def __init__(self, key: bytes) -> None: ... - @property - def key_size(self) -> int: ... - block_size: int = ... - name: str = ... - key_sizes: frozenset[int] = ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/modes.pyi b/stubs/cryptography/cryptography/hazmat/primitives/ciphers/modes.pyi deleted file mode 100644 index b99d7a89fc92..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/ciphers/modes.pyi +++ /dev/null @@ -1,93 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.primitives.ciphers import CipherAlgorithm - -class Mode(metaclass=ABCMeta): - @property - @abstractmethod - def name(self) -> str: ... - @abstractmethod - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class ModeWithAuthenticationTag(metaclass=ABCMeta): - @property - @abstractmethod - def tag(self) -> bytes: ... - -class ModeWithInitializationVector(metaclass=ABCMeta): - @property - @abstractmethod - def initialization_vector(self) -> bytes: ... - -class ModeWithNonce(metaclass=ABCMeta): - @property - @abstractmethod - def nonce(self) -> bytes: ... - -class ModeWithTweak(metaclass=ABCMeta): - @property - @abstractmethod - def tweak(self) -> bytes: ... - -class CBC(Mode, ModeWithInitializationVector): - def __init__(self, initialization_vector: bytes) -> None: ... - @property - def initialization_vector(self) -> bytes: ... - @property - def name(self) -> str: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class CTR(Mode, ModeWithNonce): - def __init__(self, nonce: bytes) -> None: ... - @property - def name(self) -> str: ... - @property - def nonce(self) -> bytes: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class CFB(Mode, ModeWithInitializationVector): - def __init__(self, initialization_vector: bytes) -> None: ... - @property - def initialization_vector(self) -> bytes: ... - @property - def name(self) -> str: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class CFB8(Mode, ModeWithInitializationVector): - def __init__(self, initialization_vector: bytes) -> None: ... - @property - def initialization_vector(self) -> bytes: ... - @property - def name(self) -> str: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class ECB(Mode): - @property - def name(self) -> str: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class GCM(Mode, ModeWithInitializationVector, ModeWithAuthenticationTag): - def __init__(self, initialization_vector: bytes, tag: bytes | None = ..., min_tag_length: int | None = ...) -> None: ... - @property - def initialization_vector(self) -> bytes: ... - @property - def name(self) -> str: ... - @property - def tag(self) -> bytes: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class OFB(Mode, ModeWithInitializationVector): - def __init__(self, initialization_vector: bytes) -> None: ... - @property - def initialization_vector(self) -> bytes: ... - @property - def name(self) -> str: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... - -class XTS(Mode, ModeWithTweak): - def __init__(self, tweak: bytes) -> None: ... - @property - def name(self) -> str: ... - @property - def tweak(self) -> bytes: ... - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/cmac.pyi b/stubs/cryptography/cryptography/hazmat/primitives/cmac.pyi deleted file mode 100644 index ae05822a9016..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/cmac.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from cryptography.hazmat.backends.interfaces import CMACBackend -from cryptography.hazmat.primitives.ciphers import BlockCipherAlgorithm - -class CMAC(object): - def __init__(self, algorithm: BlockCipherAlgorithm, backend: CMACBackend | None = ...) -> None: ... - def copy(self) -> CMAC: ... - def finalize(self) -> bytes: ... - def update(self, data: bytes) -> None: ... - def verify(self, signature: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/constant_time.pyi b/stubs/cryptography/cryptography/hazmat/primitives/constant_time.pyi deleted file mode 100644 index 9a0733e6ef09..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/constant_time.pyi +++ /dev/null @@ -1 +0,0 @@ -def bytes_eq(a: bytes, b: bytes) -> bool: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/hashes.pyi b/stubs/cryptography/cryptography/hazmat/primitives/hashes.pyi deleted file mode 100644 index 6e4828a48b21..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/hashes.pyi +++ /dev/null @@ -1,43 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from cryptography.hazmat.backends.interfaces import HashBackend - -class HashAlgorithm(metaclass=ABCMeta): - digest_size: int - name: str - -class HashContext(metaclass=ABCMeta): - algorithm: HashAlgorithm - @abstractmethod - def copy(self) -> HashContext: ... - @abstractmethod - def finalize(self) -> bytes: ... - @abstractmethod - def update(self, data: bytes) -> None: ... - -class BLAKE2b(HashAlgorithm): ... -class BLAKE2s(HashAlgorithm): ... -class MD5(HashAlgorithm): ... -class SHA1(HashAlgorithm): ... -class SHA224(HashAlgorithm): ... -class SHA256(HashAlgorithm): ... -class SHA384(HashAlgorithm): ... -class SHA3_224(HashAlgorithm): ... -class SHA3_256(HashAlgorithm): ... -class SHA3_384(HashAlgorithm): ... -class SHA3_512(HashAlgorithm): ... -class SHA512(HashAlgorithm): ... -class SHA512_224(HashAlgorithm): ... -class SHA512_256(HashAlgorithm): ... - -class SHAKE128(HashAlgorithm): - def __init__(self, digest_size: int) -> None: ... - -class SHAKE256(HashAlgorithm): - def __init__(self, digest_size: int) -> None: ... - -class Hash(HashContext): - def __init__(self, algorithm: HashAlgorithm, backend: HashBackend | None = ...): ... - def copy(self) -> Hash: ... - def finalize(self) -> bytes: ... - def update(self, data: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/hmac.pyi b/stubs/cryptography/cryptography/hazmat/primitives/hmac.pyi deleted file mode 100644 index 102ec390c655..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/hmac.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from cryptography.hazmat.backends.interfaces import HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm - -class HMAC(object): - def __init__(self, key: bytes, algorithm: HashAlgorithm, backend: HMACBackend | None = ...) -> None: ... - def copy(self) -> HMAC: ... - def finalize(self) -> bytes: ... - def update(self, msg: bytes) -> None: ... - def verify(self, signature: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/__init__.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/__init__.pyi deleted file mode 100644 index 549ca9120486..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/__init__.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from abc import ABCMeta, abstractmethod - -class KeyDerivationFunction(metaclass=ABCMeta): - @abstractmethod - def derive(self, key_material: bytes) -> bytes: ... - @abstractmethod - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/concatkdf.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/concatkdf.pyi deleted file mode 100644 index 157609c30568..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/concatkdf.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from cryptography.hazmat.backends.interfaces import HashBackend, HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -class ConcatKDFHash(KeyDerivationFunction): - def __init__(self, algorithm: HashAlgorithm, length: int, otherinfo: bytes | None, backend: HashBackend | None = ...): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class ConcatKDFHMAC(KeyDerivationFunction): - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - salt: bytes | None, - otherinfo: bytes | None, - backend: HMACBackend | None = ..., - ): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/hkdf.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/hkdf.pyi deleted file mode 100644 index 95cae782c006..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/hkdf.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from cryptography.hazmat.backends.interfaces import HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -class HKDF(KeyDerivationFunction): - def __init__( - self, algorithm: HashAlgorithm, length: int, salt: bytes | None, info: bytes | None, backend: HMACBackend | None = ... - ): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class HKDFExpand(KeyDerivationFunction): - def __init__(self, algorithm: HashAlgorithm, length: int, info: bytes | None, backend: HMACBackend | None = ...): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/kbkdf.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/kbkdf.pyi deleted file mode 100644 index 375ef66a885d..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/kbkdf.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from enum import Enum - -from cryptography.hazmat.backends.interfaces import HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -class Mode(Enum): - CounterMode: str - -class CounterLocation(Enum): - BeforeFixed: str - AfterFixed: str - -class KBKDFHMAC(KeyDerivationFunction): - def __init__( - self, - algorithm: HashAlgorithm, - mode: Mode, - length: int, - rlen: int, - llen: int, - location: CounterLocation, - label: bytes | None, - context: bytes | None, - fixed: bytes | None, - backend: HMACBackend | None = ..., - ): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/pbkdf2.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/pbkdf2.pyi deleted file mode 100644 index 805450a1c594..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/pbkdf2.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from cryptography.hazmat.backends.interfaces import PBKDF2HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -class PBKDF2HMAC(KeyDerivationFunction): - def __init__( - self, algorithm: HashAlgorithm, length: int, salt: bytes, iterations: int, backend: PBKDF2HMACBackend | None = ... - ): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/scrypt.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/scrypt.pyi deleted file mode 100644 index cd426b0e28d2..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/scrypt.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from cryptography.hazmat.backends.interfaces import ScryptBackend -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -class Scrypt(KeyDerivationFunction): - def __init__(self, salt: bytes, length: int, n: int, r: int, p: int, backend: ScryptBackend | None = ...): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/kdf/x963kdf.pyi b/stubs/cryptography/cryptography/hazmat/primitives/kdf/x963kdf.pyi deleted file mode 100644 index af74f2c07643..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/kdf/x963kdf.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from cryptography.hazmat.backends.interfaces import HashBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -class X963KDF(KeyDerivationFunction): - def __init__(self, algorithm: HashAlgorithm, length: int, sharedinfo: bytes | None, backend: HashBackend | None = ...): ... - def derive(self, key_material: bytes) -> bytes: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/keywrap.pyi b/stubs/cryptography/cryptography/hazmat/primitives/keywrap.pyi deleted file mode 100644 index 33ca77d79ef1..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/keywrap.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from cryptography.hazmat.backends.interfaces import CipherBackend - -def aes_key_wrap(wrapping_key: bytes, key_to_wrap: bytes, backend: CipherBackend | None = ...) -> bytes: ... -def aes_key_wrap_with_padding(wrapping_key: bytes, key_to_wrap: bytes, backend: CipherBackend | None = ...) -> bytes: ... -def aes_key_unwrap(wrapping_key: bytes, wrapped_key: bytes, backend: CipherBackend | None = ...) -> bytes: ... -def aes_key_unwrap_with_padding(wrapping_key: bytes, wrapped_key: bytes, backend: CipherBackend | None = ...) -> bytes: ... - -class InvalidUnwrap(Exception): ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/padding.pyi b/stubs/cryptography/cryptography/hazmat/primitives/padding.pyi deleted file mode 100644 index 7a9d5a8e2f37..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/padding.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from abc import ABCMeta, abstractmethod - -class PaddingContext(metaclass=ABCMeta): - @abstractmethod - def finalize(self) -> bytes: ... - @abstractmethod - def update(self, data: bytes) -> bytes: ... - -class ANSIX923(object): - def __init__(self, block_size: int) -> None: ... - def padder(self) -> PaddingContext: ... - def unpadder(self) -> PaddingContext: ... - -class PKCS7(object): - def __init__(self, block_size: int) -> None: ... - def padder(self) -> PaddingContext: ... - def unpadder(self) -> PaddingContext: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/poly1305.pyi b/stubs/cryptography/cryptography/hazmat/primitives/poly1305.pyi deleted file mode 100644 index 886f67027681..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/poly1305.pyi +++ /dev/null @@ -1,9 +0,0 @@ -class Poly1305(object): - def __init__(self, key: bytes) -> None: ... - def finalize(self) -> bytes: ... - @classmethod - def generate_tag(cls, key: bytes, data: bytes) -> bytes: ... - def update(self, data: bytes) -> None: ... - def verify(self, tag: bytes) -> None: ... - @classmethod - def verify_tag(cls, key: bytes, data: bytes, tag: bytes) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/serialization/__init__.pyi b/stubs/cryptography/cryptography/hazmat/primitives/serialization/__init__.pyi deleted file mode 100644 index e899766b7d0a..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/serialization/__init__.pyi +++ /dev/null @@ -1,60 +0,0 @@ -from abc import ABCMeta -from enum import Enum -from typing import Any - -from cryptography.hazmat.backends.interfaces import ( - DERSerializationBackend, - DSABackend, - EllipticCurveBackend, - PEMSerializationBackend, - RSABackend, -) - -def load_pem_private_key( - data: bytes, password: bytes | None, backend: PEMSerializationBackend | None = ... -) -> Any: ... # actually RSAPrivateKey | DSAPrivateKey | DHPrivateKey | EllipticCurvePrivateKey -def load_pem_public_key( - data: bytes, backend: PEMSerializationBackend | None = ... -) -> Any: ... # actually RSAPublicKey | DSAPublicKey | DHPublicKey | EllipticCurvePublicKey -def load_der_private_key( - data: bytes, password: bytes | None, backend: DERSerializationBackend | None = ... -) -> Any: ... # actually RSAPrivateKey | DSAPrivateKey | DHPrivateKey | EllipticCurvePrivateKey -def load_der_public_key( - data: bytes, backend: DERSerializationBackend | None = ... -) -> Any: ... # actually RSAPublicKey | DSAPublicKey | DHPublicKey | EllipticCurvePublicKey -def load_ssh_public_key( - data: bytes, backend: RSABackend | DSABackend | EllipticCurveBackend | None = ... -) -> Any: ... # actually RSAPublicKey | DSAPublicKey | DHPublicKey | EllipticCurvePublicKey | Ed25519PublicKey - -class Encoding(Enum): - PEM: str - DER: str - OpenSSH: str - Raw: str - X962: str - SMIME: str - -class PrivateFormat(Enum): - PKCS8: str - TraditionalOpenSSL: str - Raw: str - OpenSSH: str - -class PublicFormat(Enum): - SubjectPublicKeyInfo: str - PKCS1: str - OpenSSH: str - Raw: str - CompressedPoint: str - UncompressedPoint: str - -class ParameterFormat(Enum): - PKCS3: str - -class KeySerializationEncryption(metaclass=ABCMeta): ... - -class BestAvailableEncryption(KeySerializationEncryption): - password: bytes - def __init__(self, password: bytes) -> None: ... - -class NoEncryption(KeySerializationEncryption): ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/serialization/pkcs12.pyi b/stubs/cryptography/cryptography/hazmat/primitives/serialization/pkcs12.pyi deleted file mode 100644 index 72c91f7a69ca..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/serialization/pkcs12.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any - -from cryptography.hazmat.primitives.asymmetric.dsa import DSAPrivateKeyWithSerialization -from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKeyWithSerialization -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKeyWithSerialization -from cryptography.hazmat.primitives.serialization import KeySerializationEncryption -from cryptography.x509 import Certificate - -def load_key_and_certificates( - data: bytes, password: bytes | None, backend: Any | None = ... -) -> tuple[Any | None, Certificate | None, list[Certificate]]: ... -def serialize_key_and_certificates( - name: bytes, - key: RSAPrivateKeyWithSerialization | EllipticCurvePrivateKeyWithSerialization | DSAPrivateKeyWithSerialization, - cert: Certificate | None, - cas: list[Certificate] | None, - enc: KeySerializationEncryption, -) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/serialization/pkcs7.pyi b/stubs/cryptography/cryptography/hazmat/primitives/serialization/pkcs7.pyi deleted file mode 100644 index c403282f3df2..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/serialization/pkcs7.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from enum import Enum -from typing import Any, Iterable - -from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey -from cryptography.hazmat.primitives.hashes import SHA1, SHA224, SHA256, SHA384, SHA512 -from cryptography.hazmat.primitives.serialization import Encoding -from cryptography.x509 import Certificate - -def load_pem_pkcs7_certificates(data: bytes) -> list[Certificate]: ... -def load_der_pkcs7_certificates(data: bytes) -> list[Certificate]: ... - -class PKCS7Options(Enum): - Text: str - Binary: str - DetachedSignature: str - NoCapabilities: str - NoAttributes: str - NoCerts: str - -class PKCS7SignatureBuilder: - def set_data(self, data: bytes) -> PKCS7SignatureBuilder: ... - def add_signer( - self, - certificate: Certificate, - private_key: RSAPrivateKey | EllipticCurvePrivateKey, - hash_algorithm: SHA1 | SHA224 | SHA256 | SHA384 | SHA512, - ) -> PKCS7SignatureBuilder: ... - def add_certificate(self, certificate: Certificate) -> PKCS7SignatureBuilder: ... - def sign(self, encoding: Encoding, options: Iterable[PKCS7Options], backend: Any | None = ...) -> bytes: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/twofactor/__init__.pyi b/stubs/cryptography/cryptography/hazmat/primitives/twofactor/__init__.pyi deleted file mode 100644 index eff812f2a418..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/twofactor/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -class InvalidToken(Exception): ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/twofactor/hotp.pyi b/stubs/cryptography/cryptography/hazmat/primitives/twofactor/hotp.pyi deleted file mode 100644 index 2cb453061748..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/twofactor/hotp.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from cryptography.hazmat.backends.interfaces import HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm - -class HOTP(object): - def __init__( - self, key: bytes, length: int, algorithm: HashAlgorithm, backend: HMACBackend | None = ..., enforce_key_length: bool = ... - ): ... - def generate(self, counter: int) -> bytes: ... - def get_provisioning_uri(self, account_name: str, counter: int, issuer: str | None) -> str: ... - def verify(self, hotp: bytes, counter: int) -> None: ... diff --git a/stubs/cryptography/cryptography/hazmat/primitives/twofactor/totp.pyi b/stubs/cryptography/cryptography/hazmat/primitives/twofactor/totp.pyi deleted file mode 100644 index f6ba23e46276..000000000000 --- a/stubs/cryptography/cryptography/hazmat/primitives/twofactor/totp.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from cryptography.hazmat.backends.interfaces import HMACBackend -from cryptography.hazmat.primitives.hashes import HashAlgorithm - -class TOTP(object): - def __init__( - self, - key: bytes, - length: int, - algorithm: HashAlgorithm, - time_step: int, - backend: HMACBackend | None = ..., - enforce_key_length: bool = ..., - ): ... - def generate(self, time: int) -> bytes: ... - def get_provisioning_uri(self, account_name: str, issuer: str | None) -> str: ... - def verify(self, totp: bytes, time: int) -> None: ... diff --git a/stubs/cryptography/cryptography/x509/__init__.pyi b/stubs/cryptography/cryptography/x509/__init__.pyi deleted file mode 100644 index be3b7bdabd3f..000000000000 --- a/stubs/cryptography/cryptography/x509/__init__.pyi +++ /dev/null @@ -1,417 +0,0 @@ -import datetime -from abc import ABCMeta, abstractmethod -from enum import Enum -from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network -from typing import Any, ClassVar, Generator, Generic, Iterable, Sequence, Text, Type, TypeVar - -from cryptography.hazmat.backends.interfaces import X509Backend -from cryptography.hazmat.primitives.asymmetric.dsa import DSAPrivateKey, DSAPublicKey -from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey -from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey, Ed448PublicKey -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.serialization import Encoding - -class ObjectIdentifier(object): - dotted_string: str - def __init__(self, dotted_string: str) -> None: ... - -class CRLEntryExtensionOID(object): - CERTIFICATE_ISSUER: ClassVar[ObjectIdentifier] - CRL_REASON: ClassVar[ObjectIdentifier] - INVALIDITY_DATE: ClassVar[ObjectIdentifier] - -class ExtensionOID(object): - AUTHORITY_INFORMATION_ACCESS: ClassVar[ObjectIdentifier] - AUTHORITY_KEY_IDENTIFIER: ClassVar[ObjectIdentifier] - BASIC_CONSTRAINTS: ClassVar[ObjectIdentifier] - CERTIFICATE_POLICIES: ClassVar[ObjectIdentifier] - CRL_DISTRIBUTION_POINTS: ClassVar[ObjectIdentifier] - CRL_NUMBER: ClassVar[ObjectIdentifier] - DELTA_CRL_INDICATOR: ClassVar[ObjectIdentifier] - EXTENDED_KEY_USAGE: ClassVar[ObjectIdentifier] - FRESHEST_CRL: ClassVar[ObjectIdentifier] - INHIBIT_ANY_POLICY: ClassVar[ObjectIdentifier] - ISSUER_ALTERNATIVE_NAME: ClassVar[ObjectIdentifier] - ISSUING_DISTRIBUTION_POINT: ClassVar[ObjectIdentifier] - KEY_USAGE: ClassVar[ObjectIdentifier] - NAME_CONSTRAINTS: ClassVar[ObjectIdentifier] - OCSP_NO_CHECK: ClassVar[ObjectIdentifier] - POLICY_CONSTRAINTS: ClassVar[ObjectIdentifier] - POLICY_MAPPINGS: ClassVar[ObjectIdentifier] - PRECERT_POISON: ClassVar[ObjectIdentifier] - PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ClassVar[ObjectIdentifier] - SUBJECT_ALTERNATIVE_NAME: ClassVar[ObjectIdentifier] - SUBJECT_DIRECTORY_ATTRIBUTES: ClassVar[ObjectIdentifier] - SUBJECT_INFORMATION_ACCESS: ClassVar[ObjectIdentifier] - SUBJECT_KEY_IDENTIFIER: ClassVar[ObjectIdentifier] - TLS_FEATURE: ClassVar[ObjectIdentifier] - -class NameOID(object): - BUSINESS_CATEGORY: ClassVar[ObjectIdentifier] - COMMON_NAME: ClassVar[ObjectIdentifier] - COUNTRY_NAME: ClassVar[ObjectIdentifier] - DN_QUALIFIER: ClassVar[ObjectIdentifier] - DOMAIN_COMPONENT: ClassVar[ObjectIdentifier] - EMAIL_ADDRESS: ClassVar[ObjectIdentifier] - GENERATION_QUALIFIER: ClassVar[ObjectIdentifier] - GIVEN_NAME: ClassVar[ObjectIdentifier] - JURISDICTION_COUNTRY_NAME: ClassVar[ObjectIdentifier] - JURISDICTION_LOCALITY_NAME: ClassVar[ObjectIdentifier] - JURISDICTION_STATE_OR_PROVINCE_NAME: ClassVar[ObjectIdentifier] - LOCALITY_NAME: ClassVar[ObjectIdentifier] - ORGANIZATIONAL_UNIT_NAME: ClassVar[ObjectIdentifier] - ORGANIZATION_NAME: ClassVar[ObjectIdentifier] - POSTAL_ADDRESS: ClassVar[ObjectIdentifier] - POSTAL_CODE: ClassVar[ObjectIdentifier] - PSEUDONYM: ClassVar[ObjectIdentifier] - SERIAL_NUMBER: ClassVar[ObjectIdentifier] - STATE_OR_PROVINCE_NAME: ClassVar[ObjectIdentifier] - STREET_ADDRESS: ClassVar[ObjectIdentifier] - SURNAME: ClassVar[ObjectIdentifier] - TITLE: ClassVar[ObjectIdentifier] - USER_ID: ClassVar[ObjectIdentifier] - X500_UNIQUE_IDENTIFIER: ClassVar[ObjectIdentifier] - -class OCSPExtensionOID(object): - NONCE: ClassVar[ObjectIdentifier] - -class SignatureAlgorithmOID(object): - DSA_WITH_SHA1: ClassVar[ObjectIdentifier] - DSA_WITH_SHA224: ClassVar[ObjectIdentifier] - DSA_WITH_SHA256: ClassVar[ObjectIdentifier] - ECDSA_WITH_SHA1: ClassVar[ObjectIdentifier] - ECDSA_WITH_SHA224: ClassVar[ObjectIdentifier] - ECDSA_WITH_SHA256: ClassVar[ObjectIdentifier] - ECDSA_WITH_SHA384: ClassVar[ObjectIdentifier] - ECDSA_WITH_SHA512: ClassVar[ObjectIdentifier] - ED25519: ClassVar[ObjectIdentifier] - ED448: ClassVar[ObjectIdentifier] - RSASSA_PSS: ClassVar[ObjectIdentifier] - RSA_WITH_MD5: ClassVar[ObjectIdentifier] - RSA_WITH_SHA1: ClassVar[ObjectIdentifier] - RSA_WITH_SHA224: ClassVar[ObjectIdentifier] - RSA_WITH_SHA256: ClassVar[ObjectIdentifier] - RSA_WITH_SHA384: ClassVar[ObjectIdentifier] - RSA_WITH_SHA512: ClassVar[ObjectIdentifier] - -class ExtendedKeyUsageOID(object): - SERVER_AUTH: ClassVar[ObjectIdentifier] - CLIENT_AUTH: ClassVar[ObjectIdentifier] - CODE_SIGNING: ClassVar[ObjectIdentifier] - EMAIL_PROTECTION: ClassVar[ObjectIdentifier] - TIME_STAMPING: ClassVar[ObjectIdentifier] - OCSP_SIGNING: ClassVar[ObjectIdentifier] - ANY_EXTENDED_KEY_USAGE: ClassVar[ObjectIdentifier] - -class NameAttribute(object): - oid: ObjectIdentifier - value: Text - def __init__(self, oid: ObjectIdentifier, value: Text) -> None: ... - def rfc4514_string(self) -> str: ... - -class RelativeDistinguishedName(object): - def __init__(self, attributes: list[NameAttribute]) -> None: ... - def __iter__(self) -> Generator[NameAttribute, None, None]: ... - def get_attributes_for_oid(self, oid: ObjectIdentifier) -> list[NameAttribute]: ... - def rfc4514_string(self) -> str: ... - -class Name(object): - rdns: list[RelativeDistinguishedName] - def __init__(self, attributes: Sequence[NameAttribute | RelativeDistinguishedName]) -> None: ... - def __iter__(self) -> Generator[NameAttribute, None, None]: ... - def __len__(self) -> int: ... - def get_attributes_for_oid(self, oid: ObjectIdentifier) -> list[NameAttribute]: ... - def public_bytes(self, backend: X509Backend | None = ...) -> bytes: ... - def rfc4514_string(self) -> str: ... - -class Version(Enum): - v1: int - v3: int - -class Certificate(metaclass=ABCMeta): - extensions: Extensions - issuer: Name - not_valid_after: datetime.datetime - not_valid_before: datetime.datetime - serial_number: int - signature: bytes - signature_algorithm_oid: ObjectIdentifier - signature_hash_algorithm: HashAlgorithm - tbs_certificate_bytes: bytes - subject: Name - version: Version - @abstractmethod - def fingerprint(self, algorithm: HashAlgorithm) -> bytes: ... - @abstractmethod - def public_bytes(self, encoding: Encoding) -> bytes: ... - @abstractmethod - def public_key(self) -> DSAPublicKey | Ed25519PublicKey | Ed448PublicKey | EllipticCurvePublicKey | RSAPublicKey: ... - -class CertificateBuilder(object): - def __init__( - self, - issuer_name: Name | None = ..., - subject_name: Name | None = ..., - public_key: DSAPublicKey | Ed25519PublicKey | Ed448PublicKey | EllipticCurvePublicKey | RSAPublicKey | None = ..., - serial_number: int | None = ..., - not_valid_before: datetime.datetime | None = ..., - not_valid_after: datetime.datetime | None = ..., - extensions: Iterable[ExtensionType] | None = ..., - ) -> None: ... - def add_extension(self, extension: ExtensionType, critical: bool) -> CertificateBuilder: ... - def issuer_name(self, name: Name) -> CertificateBuilder: ... - def not_valid_after(self, time: datetime.datetime) -> CertificateBuilder: ... - def not_valid_before(self, time: datetime.datetime) -> CertificateBuilder: ... - def public_key( - self, public_key: DSAPublicKey | Ed25519PublicKey | Ed448PublicKey | EllipticCurvePublicKey | RSAPublicKey - ) -> CertificateBuilder: ... - def serial_number(self, serial_number: int) -> CertificateBuilder: ... - def sign( - self, - private_key: DSAPrivateKey | Ed25519PrivateKey | Ed448PrivateKey | EllipticCurvePrivateKey | RSAPrivateKey, - algorithm: HashAlgorithm | None, - backend: X509Backend | None = ..., - ) -> Certificate: ... - def subject_name(self, name: Name) -> CertificateBuilder: ... - -class CertificateRevocationList(metaclass=ABCMeta): - extensions: Extensions - issuer: Name - last_update: datetime.datetime - next_update: datetime.datetime - signature: bytes - signature_algorithm_oid: ObjectIdentifier - signature_hash_algorithm: HashAlgorithm - tbs_certlist_bytes: bytes - @abstractmethod - def fingerprint(self, algorithm: HashAlgorithm) -> bytes: ... - @abstractmethod - def get_revoked_certificate_by_serial_number(self, serial_number: int) -> RevokedCertificate: ... - @abstractmethod - def is_signature_valid( - self, public_key: DSAPublicKey | Ed25519PublicKey | Ed448PublicKey | EllipticCurvePublicKey | RSAPublicKey - ) -> bool: ... - @abstractmethod - def public_bytes(self, encoding: Encoding) -> bytes: ... - -class CertificateRevocationListBuilder(object): - def add_extension(self, extension: ExtensionType, critical: bool) -> CertificateRevocationListBuilder: ... - def add_revoked_certificate(self, revoked_certificate: RevokedCertificate) -> CertificateRevocationListBuilder: ... - def issuer_name(self, name: Name) -> CertificateRevocationListBuilder: ... - def last_update(self, time: datetime.datetime) -> CertificateRevocationListBuilder: ... - def next_update(self, time: datetime.datetime) -> CertificateRevocationListBuilder: ... - def sign( - self, - private_key: DSAPrivateKey | Ed25519PrivateKey | Ed448PrivateKey | EllipticCurvePrivateKey | RSAPrivateKey, - algorithm: HashAlgorithm | None, - backend: X509Backend | None = ..., - ) -> CertificateRevocationList: ... - -class CertificateSigningRequest(metaclass=ABCMeta): - extensions: Extensions - is_signature_valid: bool - signature: bytes - signature_algorithm_oid: ObjectIdentifier - signature_hash_algorithm: HashAlgorithm - subject: Name - tbs_certrequest_bytes: bytes - @abstractmethod - def public_bytes(self, encoding: Encoding) -> bytes: ... - @abstractmethod - def public_key(self) -> DSAPublicKey | Ed25519PublicKey | Ed448PublicKey | EllipticCurvePublicKey | RSAPublicKey: ... - -class CertificateSigningRequestBuilder(object): - def add_extension(self, extension: ExtensionType, critical: bool) -> CertificateSigningRequestBuilder: ... - def subject_name(self, name: Name) -> CertificateSigningRequestBuilder: ... - def sign( - self, - private_key: DSAPrivateKey | Ed25519PrivateKey | Ed448PrivateKey | EllipticCurvePrivateKey | RSAPrivateKey, - algorithm: HashAlgorithm | None, - backend: X509Backend | None = ..., - ) -> CertificateSigningRequest: ... - -class RevokedCertificate(metaclass=ABCMeta): - extensions: Extensions - revocation_date: datetime.datetime - serial_number: int - -class RevokedCertificateBuilder(object): - def add_extension(self, extension: ExtensionType, critical: bool) -> RevokedCertificateBuilder: ... - def build(self, backend: X509Backend | None = ...) -> RevokedCertificate: ... - def revocation_date(self, time: datetime.datetime) -> RevokedCertificateBuilder: ... - def serial_number(self, serial_number: int) -> RevokedCertificateBuilder: ... - -# General Name Classes - -class GeneralName(metaclass=ABCMeta): - value: Any - -class DirectoryName(GeneralName): - value: Name - def __init__(self, value: Name) -> None: ... - -class DNSName(GeneralName): - value: Text - def __init__(self, value: Text) -> None: ... - -class IPAddress(GeneralName): - value: IPv4Address | IPv6Address | IPv4Network | IPv6Network - def __init__(self, value: IPv4Address | IPv6Address | IPv4Network | IPv6Network) -> None: ... - -class OtherName(GeneralName): - type_id: ObjectIdentifier - value: bytes - def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None: ... - -class RegisteredID(GeneralName): - value: ObjectIdentifier - def __init__(self, value: ObjectIdentifier) -> None: ... - -class RFC822Name(GeneralName): - value: Text - def __init__(self, value: Text) -> None: ... - -class UniformResourceIdentifier(GeneralName): - value: Text - def __init__(self, value: Text) -> None: ... - -# X.509 Extensions - -class ExtensionType(metaclass=ABCMeta): - oid: ObjectIdentifier - -_T = TypeVar("_T", bound="ExtensionType") - -class Extension(Generic[_T]): - critical: bool - oid: ObjectIdentifier - value: _T - -class Extensions(object): - def __init__(self, general_names: list[Extension[Any]]) -> None: ... - def __iter__(self) -> Generator[Extension[Any], None, None]: ... - def get_extension_for_oid(self, oid: ObjectIdentifier) -> Extension[Any]: ... - def get_extension_for_class(self, extclass: Type[_T]) -> Extension[_T]: ... - -class DuplicateExtension(Exception): - oid: ObjectIdentifier - def __init__(self, msg: str, oid: ObjectIdentifier) -> None: ... - -class ExtensionNotFound(Exception): - oid: ObjectIdentifier - def __init__(self, msg: str, oid: ObjectIdentifier) -> None: ... - -class IssuerAlternativeName(ExtensionType): - def __init__(self, general_names: list[GeneralName]) -> None: ... - def __iter__(self) -> Generator[GeneralName, None, None]: ... - def get_values_for_type(self, type: Type[GeneralName]) -> list[Any]: ... - -class SubjectAlternativeName(ExtensionType): - def __init__(self, general_names: list[GeneralName]) -> None: ... - def __iter__(self) -> Generator[GeneralName, None, None]: ... - def get_values_for_type(self, type: Type[GeneralName]) -> list[Any]: ... - -class AuthorityKeyIdentifier(ExtensionType): - @property - def key_identifier(self) -> bytes: ... - @property - def authority_cert_issuer(self) -> list[GeneralName] | None: ... - @property - def authority_cert_serial_number(self) -> int | None: ... - def __init__( - self, key_identifier: bytes, authority_cert_issuer: Iterable[GeneralName] | None, authority_cert_serial_number: int | None - ) -> None: ... - @classmethod - def from_issuer_public_key( - cls, public_key: RSAPublicKey | DSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey - ) -> AuthorityKeyIdentifier: ... - @classmethod - def from_issuer_subject_key_identifier(cls, ski: SubjectKeyIdentifier) -> AuthorityKeyIdentifier: ... - -class SubjectKeyIdentifier(ExtensionType): - @property - def digest(self) -> bytes: ... - def __init__(self, digest: bytes) -> None: ... - @classmethod - def from_public_key( - cls, public_key: RSAPublicKey | DSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey - ) -> SubjectKeyIdentifier: ... - -class AccessDescription: - @property - def access_method(self) -> ObjectIdentifier: ... - @property - def access_location(self) -> GeneralName: ... - def __init__(self, access_method: ObjectIdentifier, access_location: GeneralName) -> None: ... - -class AuthorityInformationAccess(ExtensionType): - def __init__(self, descriptions: Iterable[AccessDescription]) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Generator[AccessDescription, None, None]: ... - def __getitem__(self, item: int) -> AccessDescription: ... - -class SubjectInformationAccess(ExtensionType): - def __init__(self, descriptions: Iterable[AccessDescription]) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Generator[AccessDescription, None, None]: ... - def __getitem__(self, item: int) -> AccessDescription: ... - -class BasicConstraints(ExtensionType): - @property - def ca(self) -> bool: ... - @property - def path_length(self) -> int | None: ... - def __init__(self, ca: bool, path_length: int | None) -> None: ... - -class KeyUsage(ExtensionType): - @property - def digital_signature(self) -> bool: ... - @property - def content_commitment(self) -> bool: ... - @property - def key_encipherment(self) -> bool: ... - @property - def data_encipherment(self) -> bool: ... - @property - def key_agreement(self) -> bool: ... - @property - def key_cert_sign(self) -> bool: ... - @property - def crl_sign(self) -> bool: ... - @property - def encipher_only(self) -> bool: ... - @property - def decipher_only(self) -> bool: ... - def __init__( - self, - digital_signature: bool, - content_commitment: bool, - key_encipherment: bool, - data_encipherment: bool, - key_agreement: bool, - key_cert_sign: bool, - crl_sign: bool, - encipher_only: bool, - decipher_only: bool, - ) -> None: ... - -class ExtendedKeyUsage(ExtensionType): - def __init__(self, usages: Iterable[ObjectIdentifier]) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Generator[ObjectIdentifier, None, None]: ... - def __getitem__(self, item: int) -> ObjectIdentifier: ... - -class UnrecognizedExtension(ExtensionType): - @property - def value(self) -> bytes: ... - def __init__(self, oid: ObjectIdentifier, value: bytes) -> None: ... - -def load_der_x509_certificate(data: bytes, backend: X509Backend | None = ...) -> Certificate: ... -def load_pem_x509_certificate(data: bytes, backend: X509Backend | None = ...) -> Certificate: ... -def load_der_x509_crl(data: bytes, backend: X509Backend | None = ...) -> CertificateRevocationList: ... -def load_pem_x509_crl(data: bytes, backend: X509Backend | None = ...) -> CertificateRevocationList: ... -def load_der_x509_csr(data: bytes, backend: X509Backend | None = ...) -> CertificateSigningRequest: ... -def load_pem_x509_csr(data: bytes, backend: X509Backend | None = ...) -> CertificateSigningRequest: ... -def __getattr__(name: str) -> Any: ... # incomplete diff --git a/stubs/cryptography/cryptography/x509/extensions.pyi b/stubs/cryptography/cryptography/x509/extensions.pyi deleted file mode 100644 index a9b2ad08b530..000000000000 --- a/stubs/cryptography/cryptography/x509/extensions.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any, Iterator - -from cryptography.x509 import GeneralName, ObjectIdentifier - -class Extension: - value: Any = ... - -class GeneralNames: - def __iter__(self) -> Iterator[GeneralName]: ... - -class DistributionPoint: - full_name: GeneralNames = ... - -class CRLDistributionPoints: - def __iter__(self) -> Iterator[DistributionPoint]: ... - -class AccessDescription: - access_method: ObjectIdentifier = ... - access_location: GeneralName = ... - -class AuthorityInformationAccess: - def __iter__(self) -> Iterator[AccessDescription]: ... diff --git a/stubs/cryptography/cryptography/x509/oid.pyi b/stubs/cryptography/cryptography/x509/oid.pyi deleted file mode 100644 index 2ca14b95ff64..000000000000 --- a/stubs/cryptography/cryptography/x509/oid.pyi +++ /dev/null @@ -1,104 +0,0 @@ -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.x509 import ObjectIdentifier - -class ExtensionOID: - SUBJECT_DIRECTORY_ATTRIBUTES: ObjectIdentifier = ... - SUBJECT_KEY_IDENTIFIER: ObjectIdentifier = ... - KEY_USAGE: ObjectIdentifier = ... - SUBJECT_ALTERNATIVE_NAME: ObjectIdentifier = ... - ISSUER_ALTERNATIVE_NAME: ObjectIdentifier = ... - BASIC_CONSTRAINTS: ObjectIdentifier = ... - NAME_CONSTRAINTS: ObjectIdentifier = ... - CRL_DISTRIBUTION_POINTS: ObjectIdentifier = ... - CERTIFICATE_POLICIES: ObjectIdentifier = ... - POLICY_MAPPINGS: ObjectIdentifier = ... - AUTHORITY_KEY_IDENTIFIER: ObjectIdentifier = ... - POLICY_CONSTRAINTS: ObjectIdentifier = ... - EXTENDED_KEY_USAGE: ObjectIdentifier = ... - FRESHEST_CRL: ObjectIdentifier = ... - INHIBIT_ANY_POLICY: ObjectIdentifier = ... - ISSUING_DISTRIBUTION_POINT: ObjectIdentifier = ... - AUTHORITY_INFORMATION_ACCESS: ObjectIdentifier = ... - SUBJECT_INFORMATION_ACCESS: ObjectIdentifier = ... - OCSP_NO_CHECK: ObjectIdentifier = ... - TLS_FEATURE: ObjectIdentifier = ... - CRL_NUMBER: ObjectIdentifier = ... - DELTA_CRL_INDICATOR: ObjectIdentifier = ... - PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ObjectIdentifier = ... - PRECERT_POISON: ObjectIdentifier = ... - -class OCSPExtensionOID: - NONCE: ObjectIdentifier = ... - -class CRLEntryExtensionOID: - CERTIFICATE_ISSUER: ObjectIdentifier = ... - CRL_REASON: ObjectIdentifier = ... - INVALIDITY_DATE: ObjectIdentifier = ... - -class NameOID: - COMMON_NAME: ObjectIdentifier = ... - COUNTRY_NAME: ObjectIdentifier = ... - LOCALITY_NAME: ObjectIdentifier = ... - STATE_OR_PROVINCE_NAME: ObjectIdentifier = ... - STREET_ADDRESS: ObjectIdentifier = ... - ORGANIZATION_NAME: ObjectIdentifier = ... - ORGANIZATIONAL_UNIT_NAME: ObjectIdentifier = ... - SERIAL_NUMBER: ObjectIdentifier = ... - SURNAME: ObjectIdentifier = ... - GIVEN_NAME: ObjectIdentifier = ... - TITLE: ObjectIdentifier = ... - GENERATION_QUALIFIER: ObjectIdentifier = ... - X500_UNIQUE_IDENTIFIER: ObjectIdentifier = ... - DN_QUALIFIER: ObjectIdentifier = ... - PSEUDONYM: ObjectIdentifier = ... - USER_ID: ObjectIdentifier = ... - DOMAIN_COMPONENT: ObjectIdentifier = ... - EMAIL_ADDRESS: ObjectIdentifier = ... - JURISDICTION_COUNTRY_NAME: ObjectIdentifier = ... - JURISDICTION_LOCALITY_NAME: ObjectIdentifier = ... - JURISDICTION_STATE_OR_PROVINCE_NAME: ObjectIdentifier = ... - BUSINESS_CATEGORY: ObjectIdentifier = ... - POSTAL_ADDRESS: ObjectIdentifier = ... - POSTAL_CODE: ObjectIdentifier = ... - -class SignatureAlgorithmOID: - RSA_WITH_MD5: ObjectIdentifier = ... - RSA_WITH_SHA1: ObjectIdentifier = ... - _RSA_WITH_SHA1: ObjectIdentifier = ... - RSA_WITH_SHA224: ObjectIdentifier = ... - RSA_WITH_SHA256: ObjectIdentifier = ... - RSA_WITH_SHA384: ObjectIdentifier = ... - RSA_WITH_SHA512: ObjectIdentifier = ... - RSASSA_PSS: ObjectIdentifier = ... - ECDSA_WITH_SHA1: ObjectIdentifier = ... - ECDSA_WITH_SHA224: ObjectIdentifier = ... - ECDSA_WITH_SHA256: ObjectIdentifier = ... - ECDSA_WITH_SHA384: ObjectIdentifier = ... - ECDSA_WITH_SHA512: ObjectIdentifier = ... - DSA_WITH_SHA1: ObjectIdentifier = ... - DSA_WITH_SHA224: ObjectIdentifier = ... - DSA_WITH_SHA256: ObjectIdentifier = ... - ED25519: ObjectIdentifier = ... - ED448: ObjectIdentifier = ... - -class ExtendedKeyUsageOID: - SERVER_AUTH: ObjectIdentifier = ... - CLIENT_AUTH: ObjectIdentifier = ... - CODE_SIGNING: ObjectIdentifier = ... - EMAIL_PROTECTION: ObjectIdentifier = ... - TIME_STAMPING: ObjectIdentifier = ... - OCSP_SIGNING: ObjectIdentifier = ... - ANY_EXTENDED_KEY_USAGE: ObjectIdentifier = ... - -class AuthorityInformationAccessOID: - CA_ISSUERS: ObjectIdentifier = ... - OCSP: ObjectIdentifier = ... - -class CertificatePoliciesOID: - CPS_QUALIFIER: ObjectIdentifier = ... - CPS_USER_NOTICE: ObjectIdentifier = ... - ANY_POLICY: ObjectIdentifier = ... - -_OID_NAMES: dict[ObjectIdentifier, str] = ... - -_SIG_OIDS_TO_HASH: dict[ObjectIdentifier, HashAlgorithm | None] = ... diff --git a/stubs/dataclasses/@tests/stubtest_allowlist.txt b/stubs/dataclasses/@tests/stubtest_allowlist.txt deleted file mode 100644 index 40267589899e..000000000000 --- a/stubs/dataclasses/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,5 +0,0 @@ -dataclasses.Field.__init__ -dataclasses.InitVar.__init__ -dataclasses.dataclass -dataclasses.field -dataclasses.replace diff --git a/stubs/dataclasses/METADATA.toml b/stubs/dataclasses/METADATA.toml deleted file mode 100644 index 22cbe4eb9ca3..000000000000 --- a/stubs/dataclasses/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "0.6" diff --git a/stubs/dataclasses/dataclasses.pyi b/stubs/dataclasses/dataclasses.pyi deleted file mode 100644 index a76db82bd6ac..000000000000 --- a/stubs/dataclasses/dataclasses.pyi +++ /dev/null @@ -1,91 +0,0 @@ -import sys -from typing import Any, Callable, Generic, Iterable, Mapping, Tuple, Type, TypeVar, overload - -if sys.version_info >= (3, 9): - from types import GenericAlias - -_T = TypeVar("_T") - -class _MISSING_TYPE: ... - -MISSING: _MISSING_TYPE - -@overload -def asdict(obj: Any) -> dict[str, Any]: ... -@overload -def asdict(obj: Any, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... -@overload -def astuple(obj: Any) -> Tuple[Any, ...]: ... -@overload -def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... -@overload -def dataclass(_cls: Type[_T]) -> Type[_T]: ... -@overload -def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... -@overload -def dataclass( - *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... -) -> Callable[[Type[_T]], Type[_T]]: ... - -class Field(Generic[_T]): - name: str - type: Type[_T] - default: _T - default_factory: Callable[[], _T] - repr: bool - hash: bool | None - init: bool - compare: bool - metadata: Mapping[str, Any] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -# NOTE: Actual return type is 'Field[_T]', but we want to help type checkers -# to understand the magic that happens at runtime. -@overload # `default` and `default_factory` are optional and mutually exclusive. -def field( - *, - default: _T, - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[str, Any] | None = ..., -) -> _T: ... -@overload -def field( - *, - default_factory: Callable[[], _T], - init: bool = ..., - repr: bool = ..., - hash: bool | None = ..., - compare: bool = ..., - metadata: Mapping[str, Any] | None = ..., -) -> _T: ... -@overload -def field( - *, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ... -) -> Any: ... -def fields(class_or_instance: Any) -> Tuple[Field[Any], ...]: ... -def is_dataclass(obj: Any) -> bool: ... - -class FrozenInstanceError(AttributeError): ... - -class InitVar(Generic[_T]): - if sys.version_info >= (3, 9): - def __class_getitem__(cls, type: Any) -> GenericAlias: ... - -def make_dataclass( - cls_name: str, - fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], - *, - bases: Tuple[type, ...] = ..., - namespace: dict[str, Any] | None = ..., - init: bool = ..., - repr: bool = ..., - eq: bool = ..., - order: bool = ..., - unsafe_hash: bool = ..., - frozen: bool = ..., -) -> type: ... -def replace(obj: _T, **changes: Any) -> _T: ... diff --git a/stubs/datauri/METADATA.toml b/stubs/datauri/METADATA.toml new file mode 100644 index 000000000000..1c6aeddc2a16 --- /dev/null +++ b/stubs/datauri/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1.*" +upstream-repository = "https://github.com/eclecticiq/python-data-uri" diff --git a/stubs/datauri/datauri/__init__.pyi b/stubs/datauri/datauri/__init__.pyi new file mode 100644 index 000000000000..491565ffefb8 --- /dev/null +++ b/stubs/datauri/datauri/__init__.pyi @@ -0,0 +1 @@ +from .datauri import DataURIError as DataURIError, discover as discover, parse as parse diff --git a/stubs/datauri/datauri/datauri.pyi b/stubs/datauri/datauri/datauri.pyi new file mode 100644 index 000000000000..d9223caca30f --- /dev/null +++ b/stubs/datauri/datauri/datauri.pyi @@ -0,0 +1,19 @@ +from collections.abc import Generator +from re import Pattern +from typing import Final + +RE_DATA_URI: Final[Pattern[str]] # undocumented + +class DataURIError(ValueError): ... + +class ParsedDataURI: + media_type: str | None + data: bytes + uri: str + + def __init__(self, media_type: str | None, data: bytes, uri: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +def parse(uri: str) -> ParsedDataURI: ... +def discover(s: str) -> Generator[ParsedDataURI]: ... diff --git a/stubs/dateparser/@tests/stubtest_allowlist.txt b/stubs/dateparser/@tests/stubtest_allowlist.txt index 287d3a8b4bd4..40724a190bca 100644 --- a/stubs/dateparser/@tests/stubtest_allowlist.txt +++ b/stubs/dateparser/@tests/stubtest_allowlist.txt @@ -3,3 +3,6 @@ dateparser.calendars.hijri_parser dateparser.calendars.jalali dateparser.calendars.jalali_parser dateparser.search.detection.BaseLanguageDetector.iterate_applicable_languages + +# Timezone and other internal data: +dateparser.data.date_translation_data.* diff --git a/stubs/dateparser/METADATA.toml b/stubs/dateparser/METADATA.toml index f3e83f9c456b..cc9a77d9559d 100644 --- a/stubs/dateparser/METADATA.toml +++ b/stubs/dateparser/METADATA.toml @@ -1 +1,5 @@ -version = "1.0.*" +version = "1.4.3" +upstream-repository = "https://github.com/scrapinghub/dateparser" + +[tool.stubtest] +extras = ["fasttext", "langdetect"] diff --git a/stubs/dateparser/dateparser/__init__.pyi b/stubs/dateparser/dateparser/__init__.pyi index fcee04715e90..2f772d4714cb 100644 --- a/stubs/dateparser/dateparser/__init__.pyi +++ b/stubs/dateparser/dateparser/__init__.pyi @@ -1,41 +1,45 @@ import datetime -import sys +from typing import Any, Final, Literal, TypedDict, type_check_only -from dateparser.date import DateDataParser +from dateparser.conf import Settings -if sys.version_info >= (3, 8): - from typing import Literal, TypedDict -else: - from typing_extensions import Literal, TypedDict +from .date import DateDataParser, _DetectLanguagesFunction -__version__: str +__version__: Final[str] _default_parser: DateDataParser -_Part = Literal["day", "month", "year"] -_ParserKind = Literal["timestamp", "relative-time", "custom-formats", "absolute-time", "no-spaces-time"] - -class _Settings(TypedDict, total=False): - DATE_ORDER: str +@type_check_only +class _Settings(TypedDict, total=False): # noqa: Y049 + DATE_ORDER: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] PREFER_LOCALE_DATE_ORDER: bool TIMEZONE: str TO_TIMEZONE: str RETURN_AS_TIMEZONE_AWARE: bool + PREFER_MONTH_OF_YEAR: Literal["current", "first", "last"] PREFER_DAY_OF_MONTH: Literal["current", "first", "last"] PREFER_DATES_FROM: Literal["current_period", "future", "past"] RELATIVE_BASE: datetime.datetime STRICT_PARSING: bool - REQUIRE_PARTS: list[_Part] + REQUIRE_PARTS: list[Literal["day", "month", "year"]] + IGNORE_SURROUNDING_TEXT: bool SKIP_TOKENS: list[str] NORMALIZE: bool RETURN_TIME_AS_PERIOD: bool - PARSERS: list[_ParserKind] + RETURN_TIME_SPAN: bool + DEFAULT_START_OF_WEEK: Literal["monday", "sunday"] + DEFAULT_DAYS_IN_MONTH: int + PARSERS: list[Literal["timestamp", "relative-time", "custom-formats", "absolute-time", "no-spaces-time"]] + DEFAULT_LANGUAGES: list[str] + LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD: float + CACHE_SIZE_LIMIT: int def parse( date_string: str, - date_formats: list[str] | tuple[str] | set[str] | None = ..., - languages: list[str] | tuple[str] | set[str] | None = ..., - locales: list[str] | tuple[str] | set[str] | None = ..., - region: str | None = ..., - settings: _Settings | None = ..., + date_formats: list[str] | tuple[str, ...] | set[str] | None = None, + languages: list[str] | tuple[str, ...] | set[str] | None = None, + locales: list[str] | tuple[str, ...] | set[str] | None = None, + region: str | None = None, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, ) -> datetime.datetime | None: ... diff --git a/stubs/dateparser/dateparser/calendars/__init__.pyi b/stubs/dateparser/dateparser/calendars/__init__.pyi index 1f7227a35352..82f7f5df75b6 100644 --- a/stubs/dateparser/dateparser/calendars/__init__.pyi +++ b/stubs/dateparser/dateparser/calendars/__init__.pyi @@ -1,20 +1,47 @@ -from typing import Any +from abc import abstractmethod +from datetime import datetime +from typing import ClassVar, Protocol, type_check_only +from dateparser.conf import Settings +from dateparser.date import DateData from dateparser.parser import _parser +# Examples: `hijri_parser.hijri` class or `convertdate.persian` module +@type_check_only +class _CalendarConverter(Protocol): + @classmethod + def to_gregorian(cls, year: int, month: int, day: int) -> tuple[int, int, int]: ... + @classmethod + def from_gregorian( + cls, year: int | None = None, month: int | None = None, day: int | None = None + ) -> tuple[int, int, int]: ... + @classmethod + def month_length(cls, year: int, month: int) -> int: ... + +# Examples: `hijri_parser.HijriDate` or `jalali_parser.PersianDate` +@type_check_only +class _NonGregorianDate(Protocol): + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int) -> None: ... + def weekday(self) -> int | None: ... + class CalendarBase: - parser: Any - source: Any - def __init__(self, source) -> None: ... - def get_date(self): ... + parser: type[_parser] + source: str + def __init__(self, source: str) -> None: ... + def get_date(self) -> DateData | None: ... class non_gregorian_parser(_parser): - calendar_converter: Any - default_year: Any - default_month: Any - default_day: Any - non_gregorian_date_cls: Any + calendar_converter: ClassVar[type[_CalendarConverter]] + default_year: ClassVar[int] + default_month: ClassVar[int] + default_day: ClassVar[int] + non_gregorian_date_cls: ClassVar[type[_NonGregorianDate]] @classmethod - def to_latin(cls, source): ... + def to_latin(cls, source: str) -> str: ... + @abstractmethod + def handle_two_digit_year(self, year: int) -> int: ... @classmethod - def parse(cls, datestring, settings): ... + def parse(cls, datestring: str, settings: Settings) -> tuple[datetime, str | None]: ... # type: ignore[override] diff --git a/stubs/dateparser/dateparser/calendars/hijri.pyi b/stubs/dateparser/dateparser/calendars/hijri.pyi index ef8381576622..3a134a5b0b69 100644 --- a/stubs/dateparser/dateparser/calendars/hijri.pyi +++ b/stubs/dateparser/dateparser/calendars/hijri.pyi @@ -1,6 +1,5 @@ -from typing import Any - from dateparser.calendars import CalendarBase +from dateparser.calendars.hijri_parser import hijri_parser class HijriCalendar(CalendarBase): - parser: Any + parser: type[hijri_parser] diff --git a/stubs/dateparser/dateparser/calendars/hijri_parser.pyi b/stubs/dateparser/dateparser/calendars/hijri_parser.pyi index c78ae2bbaeeb..13551dba93dc 100644 --- a/stubs/dateparser/dateparser/calendars/hijri_parser.pyi +++ b/stubs/dateparser/dateparser/calendars/hijri_parser.pyi @@ -1,25 +1,28 @@ -from typing import Any +from typing import ClassVar from dateparser.calendars import non_gregorian_parser class hijri: @classmethod - def to_gregorian(cls, year: Any | None = ..., month: Any | None = ..., day: Any | None = ...): ... + def to_gregorian(cls, year: int | None = None, month: int | None = None, day: int | None = None) -> tuple[int, int, int]: ... @classmethod - def from_gregorian(cls, year: Any | None = ..., month: Any | None = ..., day: Any | None = ...): ... + def from_gregorian( + cls, year: int | None = None, month: int | None = None, day: int | None = None + ) -> tuple[int, int, int]: ... @classmethod - def month_length(cls, year, month): ... + def month_length(cls, year: int | None, month: int | None) -> int: ... class HijriDate: - year: Any - month: Any - day: Any - def __init__(self, year, month, day) -> None: ... - def weekday(self): ... + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int) -> None: ... + def weekday(self) -> int | None: ... class hijri_parser(non_gregorian_parser): - calendar_converter: Any - default_year: int - default_month: int - default_day: int - non_gregorian_date_cls: Any + calendar_converter: ClassVar[type[hijri]] + default_year: ClassVar[int] + default_month: ClassVar[int] + default_day: ClassVar[int] + non_gregorian_date_cls: ClassVar[type[HijriDate]] + def handle_two_digit_year(self, year: int) -> int: ... diff --git a/stubs/dateparser/dateparser/calendars/jalali.pyi b/stubs/dateparser/dateparser/calendars/jalali.pyi index 355120027b94..8df2dce7228a 100644 --- a/stubs/dateparser/dateparser/calendars/jalali.pyi +++ b/stubs/dateparser/dateparser/calendars/jalali.pyi @@ -1,6 +1,6 @@ -from typing import Any +from dateparser.calendars.jalali_parser import jalali_parser from . import CalendarBase class JalaliCalendar(CalendarBase): - parser: Any + parser: type[jalali_parser] diff --git a/stubs/dateparser/dateparser/calendars/jalali_parser.pyi b/stubs/dateparser/dateparser/calendars/jalali_parser.pyi index e642ba251923..9c8064135b31 100644 --- a/stubs/dateparser/dateparser/calendars/jalali_parser.pyi +++ b/stubs/dateparser/dateparser/calendars/jalali_parser.pyi @@ -1,17 +1,18 @@ -from typing import Any +from typing import ClassVar from dateparser.calendars import non_gregorian_parser class PersianDate: - year: Any - month: Any - day: Any - def __init__(self, year, month, day) -> None: ... - def weekday(self): ... + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int) -> None: ... + def weekday(self) -> int | None: ... class jalali_parser(non_gregorian_parser): - calendar_converter: Any - default_year: int - default_month: int - default_day: int - non_gregorian_date_cls: Any + # `calendar_converter` is `convertdate.persian` module + default_year: ClassVar[int] + default_month: ClassVar[int] + default_day: ClassVar[int] + non_gregorian_date_cls: ClassVar[type[PersianDate]] + def handle_two_digit_year(self, year: int) -> int: ... diff --git a/stubs/dateparser/dateparser/conf.pyi b/stubs/dateparser/dateparser/conf.pyi index 30d86dcff9c8..ad80b028637e 100644 --- a/stubs/dateparser/dateparser/conf.pyi +++ b/stubs/dateparser/dateparser/conf.pyi @@ -1,16 +1,47 @@ -from typing import Any +import datetime +from collections.abc import Callable +from typing import Any, Literal, ParamSpec, TypeVar +from typing_extensions import Self + +_P = ParamSpec("_P") +_R = TypeVar("_R") class Settings: - def __new__(cls, *args, **kw) -> Settings: ... - def __init__(self, settings: Any | None = ...) -> None: ... + # Next attributes are optional and may be missing. + # Please keep in sync with _Settings TypedDict + DATE_ORDER: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] + PREFER_LOCALE_DATE_ORDER: bool + TIMEZONE: str + TO_TIMEZONE: str + RETURN_AS_TIMEZONE_AWARE: bool + PREFER_MONTH_OF_YEAR: Literal["current", "first", "last"] + PREFER_DAY_OF_MONTH: Literal["current", "first", "last"] + PREFER_DATES_FROM: Literal["current_period", "future", "past"] + RELATIVE_BASE: datetime.datetime + STRICT_PARSING: bool + REQUIRE_PARTS: list[Literal["day", "month", "year"]] + IGNORE_SURROUNDING_TEXT: bool + SKIP_TOKENS: list[str] + NORMALIZE: bool + RETURN_TIME_AS_PERIOD: bool + RETURN_TIME_SPAN: bool + DEFAULT_START_OF_WEEK: Literal["monday", "sunday"] + DEFAULT_DAYS_IN_MONTH: int + PARSERS: list[Literal["timestamp", "relative-time", "custom-formats", "absolute-time", "no-spaces-time"]] + DEFAULT_LANGUAGES: list[str] + LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD: float + CACHE_SIZE_LIMIT: int + + def __new__(cls, *args, **kwargs) -> Self: ... + def __init__(self, settings: dict[str, Any] | None = None) -> None: ... @classmethod - def get_key(cls, settings: Any | None = ...): ... - def replace(self, mod_settings: Any | None = ..., **kwds): ... + def get_key(cls, settings: dict[str, Any] | None = None) -> str: ... + def replace(self, mod_settings: dict[str, Any] | None = None, **kwds) -> Self: ... -settings: Any +settings: Settings -def apply_settings(f): ... +def apply_settings(f: Callable[_P, _R]) -> Callable[_P, _R]: ... class SettingValidationError(ValueError): ... -def check_settings(settings) -> None: ... +def check_settings(settings: Settings) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/html5/__init__.pyi b/stubs/dateparser/dateparser/custom_language_detection/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/common/html5/__init__.pyi rename to stubs/dateparser/dateparser/custom_language_detection/__init__.pyi diff --git a/stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi b/stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi new file mode 100644 index 000000000000..e7440af40333 --- /dev/null +++ b/stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi @@ -0,0 +1 @@ +def detect_languages(text: str, confidence_threshold: float) -> list[str]: ... diff --git a/stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi b/stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi new file mode 100644 index 000000000000..e7440af40333 --- /dev/null +++ b/stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi @@ -0,0 +1 @@ +def detect_languages(text: str, confidence_threshold: float) -> list[str]: ... diff --git a/stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi b/stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi new file mode 100644 index 000000000000..0f5de55de936 --- /dev/null +++ b/stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi @@ -0,0 +1 @@ +def map_languages(language_codes: list[str]) -> list[str]: ... diff --git a/stubs/dateparser/dateparser/data/__init__.pyi b/stubs/dateparser/dateparser/data/__init__.pyi index e69de29bb2d1..91633ea6b715 100644 --- a/stubs/dateparser/dateparser/data/__init__.pyi +++ b/stubs/dateparser/dateparser/data/__init__.pyi @@ -0,0 +1 @@ +from .languages_info import language_locale_dict as language_locale_dict, language_order as language_order diff --git a/stubs/dateparser/dateparser/data/languages_info.pyi b/stubs/dateparser/dateparser/data/languages_info.pyi index 799fa8b92f9c..5ac61c380052 100644 --- a/stubs/dateparser/dateparser/data/languages_info.pyi +++ b/stubs/dateparser/dateparser/data/languages_info.pyi @@ -1,4 +1,5 @@ -from typing import Any +from typing import Final -language_order: Any -language_locale_dict: Any +language_order: Final[list[str]] +language_map: Final[dict[str, list[str]]] +language_locale_dict: Final[dict[str, list[str]]] diff --git a/stubs/dateparser/dateparser/date.pyi b/stubs/dateparser/dateparser/date.pyi index cc5118dcedb9..465e738b3806 100644 --- a/stubs/dateparser/dateparser/date.pyi +++ b/stubs/dateparser/dateparser/date.pyi @@ -1,66 +1,96 @@ -import collections -import sys -from _typeshed import Self as Self -from datetime import datetime -from typing import ClassVar, Iterable, Iterator, Type, overload +import re +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Callable, Iterable, Iterator, Set as AbstractSet +from datetime import date, datetime, tzinfo +from typing import Any, ClassVar, Final, Literal, NamedTuple, TypeAlias, TypeVar, overload, type_check_only -from dateparser import _Settings from dateparser.conf import Settings from dateparser.languages.loader import LocaleDataLoader from dateparser.languages.locale import Locale -if sys.version_info >= (3, 8): - from re import Pattern - from typing import Literal -else: - from typing import Pattern - from typing_extensions import Literal +_DateT = TypeVar("_DateT", bound=date) -_Period = Literal["time", "day", "week", "month", "year"] -APOSTROPHE_LOOK_ALIKE_CHARS: list[str] -RE_NBSP: Pattern[str] -RE_SPACES: Pattern[str] -RE_TRIM_SPACES: Pattern[str] -RE_TRIM_COLONS: Pattern[str] -RE_SANITIZE_SKIP: Pattern[str] -RE_SANITIZE_RUSSIAN: Pattern[str] -RE_SANITIZE_PERIOD: Pattern[str] -RE_SANITIZE_ON: Pattern[str] -RE_SANITIZE_APOSTROPHE: Pattern[str] -RE_SEARCH_TIMESTAMP: Pattern[str] +_DetectLanguagesFunction: TypeAlias = Callable[[str, float], list[str]] +_Period: TypeAlias = Literal["time", "day", "week", "month", "year"] +# Work around attribute and type having the same name. +_Weekday: TypeAlias = Incomplete # Actually it's dateutil._common.weekday class + +@type_check_only +class _DateData(NamedTuple): + date_obj: datetime | None + locale: str | None + period: _Period | None + +APOSTROPHE_LOOK_ALIKE_CHARS: Final[list[str]] +RE_NBSP: Final[re.Pattern[str]] +RE_SPACES: Final[re.Pattern[str]] +RE_TRIM_SPACES: Final[re.Pattern[str]] +RE_TRIM_COLONS: Final[re.Pattern[str]] +RE_SANITIZE_SKIP: Final[re.Pattern[str]] +RE_SANITIZE_RUSSIAN: Final[re.Pattern[str]] +RE_SANITIZE_PERIOD: Final[re.Pattern[str]] +RE_SANITIZE_ON: Final[re.Pattern[str]] +RE_SANITIZE_APOSTROPHE: Final[re.Pattern[str]] +RE_SEARCH_TIMESTAMP: Final[re.Pattern[str]] +RE_SANITIZE_CROATIAN: Final[re.Pattern[str]] +RE_SEARCH_NEGATIVE_TIMESTAMP: Final[re.Pattern[str]] def sanitize_spaces(date_string: str) -> str: ... -def date_range(begin, end, **kwargs) -> None: ... -def get_intersecting_periods(low, high, period: str = ...) -> None: ... +def date_range( + begin: _DateT, + end: _DateT, + *, + dt1: date | None = None, + dt2: date | None = None, + years: int = 0, + months: int = 0, + days: int = 0, + leapdays: int = 0, + weeks: int = 0, + hours: int = 0, + minutes: int = 0, + seconds: int = 0, + microseconds: int = 0, + weekday: int | _Weekday | None = None, + yearday: int | None = None, + nlyearday: int | None = None, + microsecond: int | None = None, +) -> Iterator[_DateT]: ... +def get_intersecting_periods( + low: _DateT, high: _DateT, period: Literal["year", "month", "week", "day", "hour", "minute", "second", "microsecond"] = "day" +) -> Iterator[_DateT]: ... def sanitize_date(date_string: str) -> str: ... -def get_date_from_timestamp(date_string: str, settings: Settings) -> datetime | None: ... +def get_date_from_timestamp(date_string: str, settings: Settings, negative: bool | None = False) -> datetime | None: ... def parse_with_formats(date_string: str, date_formats: Iterable[str], settings: Settings) -> DateData: ... class _DateLocaleParser: locale: Locale date_string: str - date_formats: list[str] | tuple[str] | set[str] | None + date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None def __init__( self, locale: Locale, date_string: str, - date_formats: list[str] | tuple[str] | set[str] | None, - settings: Settings | None = ..., + date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None, + settings: Settings | None = None, + ignore_surrounding_text: bool = False, ) -> None: ... @classmethod def parse( cls, locale: Locale, date_string: str, - date_formats: list[str] | tuple[str] | set[str] | None = ..., - settings: Settings | None = ..., + date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + settings: Settings | None = None, + ignore_surrounding_text: bool = False, ) -> DateData: ... def _parse(self) -> DateData | None: ... def _try_timestamp(self) -> DateData: ... def _try_freshness_parser(self) -> DateData | None: ... def _try_absolute_parser(self) -> DateData | None: ... def _try_nospaces_parser(self) -> DateData | None: ... - def _try_parser(self, parse_method) -> DateData | None: ... + def _try_parser(self, parse_method: Callable[[str, Settings, tzinfo | None], tuple[datetime, str]]) -> DateData | None: ... def _try_given_formats(self) -> DateData | None: ... def _get_translated_date(self) -> str: ... def _get_translated_date_with_formatting(self) -> str: ... @@ -70,13 +100,15 @@ class DateData: date_obj: datetime | None locale: str | None period: _Period | None - def __init__(self, *, date_obj: datetime | None = ..., period: _Period | None = ..., locale: str | None = ...) -> None: ... + def __init__(self, *, date_obj: datetime | None = None, period: _Period | None = None, locale: str | None = None) -> None: ... + @overload def __getitem__(self, k: Literal["date_obj"]) -> datetime | None: ... @overload def __getitem__(self, k: Literal["locale"]) -> str | None: ... @overload def __getitem__(self, k: Literal["period"]) -> _Period | None: ... + @overload def __setitem__(self, k: Literal["date_obj"], v: datetime) -> None: ... @overload @@ -90,21 +122,27 @@ class DateDataParser: try_previous_locales: bool use_given_order: bool languages: list[str] | None - locales: list[str] | tuple[str] | set[str] | None + locales: list[str] | tuple[str, ...] | AbstractSet[str] | None region: str - previous_locales: collections.OrderedDict[Locale, None] + detect_languages_function: _DetectLanguagesFunction | None + previous_locales: OrderedDict[Locale, None] def __init__( self, - languages: list[str] | tuple[str] | set[str] | None = ..., - locales: list[str] | tuple[str] | set[str] | None = ..., - region: str | None = ..., - try_previous_locales: bool = ..., - use_given_order: bool = ..., - settings: _Settings | None = ..., + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + locales: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + region: str | None = None, + try_previous_locales: bool = False, + use_given_order: bool = False, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, ) -> None: ... - def get_date_data(self, date_string: str, date_formats: list[str] | tuple[str] | set[str] | None = ...) -> DateData: ... - def get_date_tuple(self, date_string: str, date_formats: list[str] | tuple[str] | set[str] | None = ...): ... - def _get_applicable_locales(self, date_string: str) -> Iterator[Locale]: ... - def _is_applicable_locale(self, locale: Locale, date_string: str) -> bool: ... + def get_date_data( + self, date_string: str, date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None = None + ) -> DateData: ... + def get_date_tuple( + self, date_string: str, date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None = None + ) -> _DateData: ... + def _get_applicable_locales(self, date_string: str, ignore_surrounding_text: bool = False) -> Iterator[Locale]: ... + def _is_applicable_locale(self, locale: Locale, date_string: str, ignore_surrounding_text: bool = False) -> bool: ... @classmethod - def _get_locale_loader(cls: Type[DateDataParser]) -> LocaleDataLoader: ... + def _get_locale_loader(cls: type[DateDataParser]) -> LocaleDataLoader: ... diff --git a/stubs/dateparser/dateparser/date_parser.pyi b/stubs/dateparser/dateparser/date_parser.pyi index 65abc3b34e60..0c9a24d02f62 100644 --- a/stubs/dateparser/dateparser/date_parser.pyi +++ b/stubs/dateparser/dateparser/date_parser.pyi @@ -1,6 +1,18 @@ -from typing import Any +from collections.abc import Callable +from datetime import datetime, tzinfo +from typing import Literal + +from dateparser.conf import Settings class DateParser: - def parse(self, date_string, parse_method, settings: Any | None = ...): ... + def parse( + self, + date_string: str, + parse_method: Callable[ + [str, Settings, tzinfo | None, Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] | None], tuple[datetime, str] + ], + settings: Settings | None = None, + date_order: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] | None = None, + ) -> tuple[datetime, str]: ... -date_parser: Any +date_parser: DateParser diff --git a/stubs/dateparser/dateparser/freshness_date_parser.pyi b/stubs/dateparser/dateparser/freshness_date_parser.pyi index 41f717efa7ed..e05a0318a175 100644 --- a/stubs/dateparser/dateparser/freshness_date_parser.pyi +++ b/stubs/dateparser/dateparser/freshness_date_parser.pyi @@ -1,11 +1,20 @@ -from typing import Any +import re +from _typeshed import Incomplete +from datetime import datetime +from typing import Final +from zoneinfo import ZoneInfo -PATTERN: Any +from dateparser.conf import Settings +from dateparser.date import DateData + +PATTERN: Final[re.Pattern[str]] class FreshnessDateDataParser: - def get_local_tz(self): ... - def parse(self, date_string, settings): ... - def get_kwargs(self, date_string): ... - def get_date_data(self, date_string, settings: Any | None = ...): ... + def get_local_tz(self) -> ZoneInfo: ... + def parse(self, date_string: str, settings: Settings) -> tuple[datetime | None, str | None]: ... + def get_kwargs( + self, date_string: str + ) -> tuple[dict[str, float], dict[str, Incomplete]] | dict[None, None]: ... # return empty dict if pattern not found + def get_date_data(self, date_string: str, settings: Settings | None = None) -> DateData: ... -freshness_date_parser: Any +freshness_date_parser: FreshnessDateDataParser diff --git a/stubs/dateparser/dateparser/languages/__init__.pyi b/stubs/dateparser/dateparser/languages/__init__.pyi index e69de29bb2d1..2f14a878d997 100644 --- a/stubs/dateparser/dateparser/languages/__init__.pyi +++ b/stubs/dateparser/dateparser/languages/__init__.pyi @@ -0,0 +1,2 @@ +from .loader import default_loader as default_loader +from .locale import Locale as Locale diff --git a/stubs/dateparser/dateparser/languages/dictionary.pyi b/stubs/dateparser/dateparser/languages/dictionary.pyi index 76a2fd2a4478..a207c8ed5e7d 100644 --- a/stubs/dateparser/dateparser/languages/dictionary.pyi +++ b/stubs/dateparser/dateparser/languages/dictionary.pyi @@ -1,23 +1,32 @@ -from typing import Any +import re +from _typeshed import Incomplete +from itertools import chain +from typing import Final, overload -PARSER_HARDCODED_TOKENS: Any -PARSER_KNOWN_TOKENS: Any -ALWAYS_KEEP_TOKENS: Any -KNOWN_WORD_TOKENS: Any -PARENTHESES_PATTERN: Any -NUMERAL_PATTERN: Any -KEEP_TOKEN_PATTERN: Any +from dateparser.conf import Settings + +PARSER_HARDCODED_TOKENS: Final[list[str]] +PARSER_KNOWN_TOKENS: Final[list[str]] +ALWAYS_KEEP_TOKENS: Final[list[str]] +KNOWN_WORD_TOKENS: Final[list[str]] +PARENTHESES_PATTERN: Final[re.Pattern[str]] +NUMERAL_PATTERN: Final[re.Pattern[str]] +KEEP_TOKEN_PATTERN: Final[re.Pattern[str]] class UnknownTokenError(Exception): ... class Dictionary: - info: Any - def __init__(self, locale_info, settings: Any | None = ...) -> None: ... - def __contains__(self, key): ... - def __getitem__(self, key): ... - def __iter__(self) -> Any: ... - def are_tokens_valid(self, tokens): ... - def split(self, string, keep_formatting: bool = ...): ... + info: dict[str, Incomplete] + def __init__(self, locale_info: dict[str, Incomplete], settings: Settings | None = None) -> None: ... + def __contains__(self, key: str) -> bool: ... + def __getitem__(self, key: str): ... + def __iter__(self) -> chain[str]: ... + def are_tokens_valid(self, tokens: list[str]) -> bool: ... + + @overload + def split(self, string: None, keep_formatting: bool = False) -> None: ... + @overload + def split(self, string: str, keep_formatting: bool = False) -> list[str]: ... class NormalizedDictionary(Dictionary): - def __init__(self, locale_info, settings: Any | None = ...) -> None: ... + def __init__(self, locale_info: dict[str, Incomplete], settings: Settings | None = None) -> None: ... diff --git a/stubs/dateparser/dateparser/languages/loader.pyi b/stubs/dateparser/dateparser/languages/loader.pyi index 8eaa38c77b08..80f89c211053 100644 --- a/stubs/dateparser/dateparser/languages/loader.pyi +++ b/stubs/dateparser/dateparser/languages/loader.pyi @@ -1,27 +1,29 @@ +import re from collections import OrderedDict -from typing import Any, Iterator +from collections.abc import Iterator +from typing import Final from .locale import Locale -LOCALE_SPLIT_PATTERN: Any +LOCALE_SPLIT_PATTERN: Final[re.Pattern[str]] class LocaleDataLoader: def get_locale_map( self, - languages: list[str] | None = ..., - locales: list[str] | None = ..., - region: str | None = ..., - use_given_order: bool = ..., - allow_conflicting_locales: bool = ..., - ) -> OrderedDict[str, list[Any] | str | int]: ... + languages: list[str] | None = None, + locales: list[str] | None = None, + region: str | None = None, + use_given_order: bool = False, + allow_conflicting_locales: bool = False, + ) -> OrderedDict[str, Locale]: ... def get_locales( self, - languages: list[str] | None = ..., - locales: list[str] | None = ..., - region: str | None = ..., - use_given_order: bool = ..., - allow_conflicting_locales: bool = ..., + languages: list[str] | None = None, + locales: list[str] | None = None, + region: str | None = None, + use_given_order: bool = False, + allow_conflicting_locales: bool = False, ) -> Iterator[Locale]: ... def get_locale(self, shortname: str) -> Locale: ... -default_loader: Any +default_loader: LocaleDataLoader diff --git a/stubs/dateparser/dateparser/languages/locale.pyi b/stubs/dateparser/dateparser/languages/locale.pyi index 1c91e2659929..587414f06bfe 100644 --- a/stubs/dateparser/dateparser/languages/locale.pyi +++ b/stubs/dateparser/dateparser/languages/locale.pyi @@ -1,23 +1,37 @@ -import sys +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Mapping, Sized +from re import Pattern +from typing import Final, TypeVar from dateparser.conf import Settings -if sys.version_info >= (3, 8): - from re import Pattern -else: - from typing import Pattern +_K = TypeVar("_K", bound=Sized) +_V = TypeVar("_V") -DIGIT_GROUP_PATTERN: Pattern[str] -NUMERAL_PATTERN: Pattern[str] +NUMERAL_PATTERN: Final[Pattern[str]] class Locale: shortname: str - def __init__(self, shortname: str, language_info) -> None: ... - def is_applicable(self, date_string: str, strip_timezone: bool = ..., settings: Settings | None = ...) -> bool: ... - def count_applicability(self, text: str, strip_timezone: bool = ..., settings: Settings | None = ...): ... + info: OrderedDict[str, Incomplete] + def __init__(self, shortname: str, language_info: Mapping[Incomplete, Incomplete]) -> None: ... + def is_applicable( + self, + date_string: str, + strip_timezone: bool = False, + settings: Settings | None = None, + ignore_surrounding_text: bool = False, + ) -> bool: ... + def count_applicability(self, text: str, strip_timezone: bool = False, settings: Settings | None = None) -> list[int]: ... @staticmethod - def clean_dictionary(dictionary, threshold: int = ...): ... - def translate(self, date_string: str, keep_formatting: bool = ..., settings: Settings | None = ...) -> str: ... - def translate_search(self, search_string, settings: Settings | None = ...): ... - def get_wordchars_for_detection(self, settings): ... - def to_parserinfo(self, base_cls=...): ... + def clean_dictionary(dictionary: Mapping[_K, _V], threshold: int = 2) -> Mapping[_K, _V]: ... + def translate( + self, + date_string: str, + keep_formatting: bool = False, + settings: Settings | None = None, + ignore_surrounding_text: bool = False, + ) -> str: ... + def translate_search(self, search_string: str, settings: Settings | None = None) -> tuple[list[str], list[str]]: ... + def get_wordchars_for_detection(self, settings: Settings) -> set[str]: ... + def to_parserinfo(self, base_cls: type = ...): ... diff --git a/stubs/dateparser/dateparser/languages/validation.pyi b/stubs/dateparser/dateparser/languages/validation.pyi index 790faa6af36a..b98ed3d6e90c 100644 --- a/stubs/dateparser/dateparser/languages/validation.pyi +++ b/stubs/dateparser/dateparser/languages/validation.pyi @@ -1,9 +1,11 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger +from typing import ClassVar class LanguageValidator: - logger: Any - VALID_KEYS: Any + VALID_KEYS: ClassVar[list[str]] + logger: Logger | None @classmethod - def get_logger(cls): ... + def get_logger(cls) -> Logger: ... @classmethod - def validate_info(cls, language_id, info): ... + def validate_info(cls, language_id, info: dict[str, Incomplete]) -> bool: ... diff --git a/stubs/dateparser/dateparser/parser.pyi b/stubs/dateparser/dateparser/parser.pyi index de87e8e9fa72..eef0dd768f85 100644 --- a/stubs/dateparser/dateparser/parser.pyi +++ b/stubs/dateparser/dateparser/parser.pyi @@ -1,51 +1,79 @@ -from typing import Any +import datetime +import re +from collections import OrderedDict +from collections.abc import Callable, Iterable, Iterator +from io import StringIO +from typing import ClassVar, Final, Literal, TypeAlias, overload -NSP_COMPATIBLE: Any -MERIDIAN: Any -MICROSECOND: Any -EIGHT_DIGIT: Any -HOUR_MINUTE_REGEX: Any +from dateparser.conf import Settings -def no_space_parser_eligibile(datestring): ... -def get_unresolved_attrs(parser_object): ... +_TokenType: TypeAlias = Literal[0, 1, 2] +_Component: TypeAlias = Literal["year", "month", "day"] -date_order_chart: Any +NSP_COMPATIBLE: Final[re.Pattern[str]] +MERIDIAN: Final[re.Pattern[str]] +MICROSECOND: Final[re.Pattern[str]] +EIGHT_DIGIT: Final[re.Pattern[str]] +HOUR_MINUTE_REGEX: Final[re.Pattern[str]] -def resolve_date_order(order, lst: Any | None = ...): ... +def no_space_parser_eligibile(datestring: str) -> bool: ... +def get_unresolved_attrs(parser_object: object) -> tuple[list[_Component], list[_Component]]: ... + +date_order_chart: Final[dict[Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"], str]] + +@overload +def resolve_date_order(order: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"], lst: Literal[True]) -> list[_Component]: ... +@overload +def resolve_date_order(order: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"], lst: Literal[False] | None = None) -> str: ... class _time_parser: - time_directives: Any - def __call__(self, timestring): ... + time_directives: list[str] + def __call__(self, timestring: str) -> datetime.time: ... -time_parser: Any +time_parser: _time_parser class _no_spaces_parser: - period: Any - date_formats: Any - def __init__(self, *args, **kwargs): ... + period: dict[str, list[str]] + date_formats: dict[str, list[str]] + def __init__(self, *args, **kwargs) -> None: ... @classmethod - def parse(cls, datestring, settings): ... + def parse( + cls, datestring: str, settings: Settings, date_order: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] | None = None + ) -> tuple[datetime.datetime, str]: ... class _parser: - alpha_directives: Any - num_directives: Any - settings: Any - tokens: Any - filtered_tokens: Any - unset_tokens: Any - day: Any - month: Any - year: Any - time: Any - auto_order: Any - ordered_num_directives: Any - def __init__(self, tokens, settings): ... + alpha_directives: ClassVar[dict[str, list[str]]] + num_directives: ClassVar[dict[str, list[str]]] + + settings: Settings + tokens: list[tuple[str, _TokenType]] + filtered_tokens: list[tuple[str, _TokenType, int]] + unset_tokens: list[tuple[str, _TokenType, _Component]] + day: int | None + month: int | None + year: int | None + time: Callable[[], datetime.time] | None + auto_order: list[str] + ordered_num_directives: OrderedDict[str, list[str]] + + def __init__( + self, + tokens: Iterable[tuple[str, _TokenType]], + settings: Settings, + date_order: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] | None = None, + ) -> None: ... @classmethod - def parse(cls, datestring, settings): ... + def parse( + cls, + datestring: str, + settings: Settings, + tz: datetime.tzinfo | None = None, + date_order: Literal["DMY", "DYM", "MDY", "MYD", "YDM", "YMD"] | None = None, + ) -> tuple[datetime.datetime, str | None]: ... class tokenizer: - digits: str - letters: str - instream: Any - def __init__(self, ds) -> None: ... - def tokenize(self) -> None: ... + digits: Literal["0123456789:"] + letters: Literal["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] + instream: StringIO + def __init__(self, ds: str) -> None: ... + def tokenize(self) -> Iterator[tuple[str, _TokenType]]: ... diff --git a/stubs/dateparser/dateparser/search/__init__.pyi b/stubs/dateparser/dateparser/search/__init__.pyi index e14bcc05f634..4c5d5c6c467d 100644 --- a/stubs/dateparser/dateparser/search/__init__.pyi +++ b/stubs/dateparser/dateparser/search/__init__.pyi @@ -1,24 +1,26 @@ -import sys -from collections.abc import Mapping, Set +from collections.abc import Set as AbstractSet from datetime import datetime -from typing import Any, Tuple, overload +from typing import Any, Literal, overload -if sys.version_info >= (3, 8): - from typing import Literal -else: - from typing_extensions import Literal +from dateparser.conf import Settings + +from ..date import _DetectLanguagesFunction @overload def search_dates( text: str, - languages: list[str] | Tuple[str, ...] | Set[str] | None, - settings: Mapping[Any, Any] | None, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None, + settings: Settings | dict[str, Any] | None, add_detected_language: Literal[True], -) -> list[tuple[str, datetime, str]]: ... + detect_languages_function: _DetectLanguagesFunction | None = None, + strategy: Literal["split", "ngram"] = "split", +) -> list[tuple[str, datetime, str]] | None: ... @overload def search_dates( text: str, - languages: list[str] | Tuple[str, ...] | Set[str] | None = ..., - settings: Mapping[Any, Any] | None = ..., - add_detected_language: Literal[False] = ..., -) -> list[tuple[str, datetime]]: ... + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + settings: Settings | dict[str, Any] | None = None, + add_detected_language: Literal[False] = False, + detect_languages_function: _DetectLanguagesFunction | None = None, + strategy: Literal["split", "ngram"] = "split", +) -> list[tuple[str, datetime]] | None: ... diff --git a/stubs/dateparser/dateparser/search/detection.pyi b/stubs/dateparser/dateparser/search/detection.pyi index 69767c2e6922..1466b18175cc 100644 --- a/stubs/dateparser/dateparser/search/detection.pyi +++ b/stubs/dateparser/dateparser/search/detection.pyi @@ -1,17 +1,25 @@ -from typing import Any +from collections.abc import Iterator + +from dateparser.conf import Settings +from dateparser.languages.locale import Locale class BaseLanguageDetector: - languages: Any - def __init__(self, languages) -> None: ... - def iterate_applicable_languages(self, date_string, modify: bool = ..., settings: Any | None = ...) -> None: ... + languages: list[Locale] + def __init__(self, languages: list[Locale]) -> None: ... + def iterate_applicable_languages( + self, date_string: str, modify: bool = False, settings: Settings | None = None + ) -> Iterator[Locale]: ... class AutoDetectLanguage(BaseLanguageDetector): - language_pool: Any - allow_redetection: Any - def __init__(self, languages, allow_redetection: bool = ...) -> None: ... - languages: Any - def iterate_applicable_languages(self, date_string, modify: bool = ..., settings: Any | None = ...) -> None: ... + language_pool: list[Locale] + allow_redetection: bool + def __init__(self, languages: list[Locale], allow_redetection: bool = False) -> None: ... + def iterate_applicable_languages( + self, date_string: str, modify: bool = False, settings: Settings | None = None + ) -> Iterator[Locale]: ... class ExactLanguages(BaseLanguageDetector): - def __init__(self, languages) -> None: ... - def iterate_applicable_languages(self, date_string, modify: bool = ..., settings: Any | None = ...) -> None: ... + def __init__(self, languages: list[Locale]) -> None: ... + def iterate_applicable_languages( + self, date_string: str, modify: bool = False, settings: Settings | None = None + ) -> Iterator[Locale]: ... diff --git a/stubs/dateparser/dateparser/search/ngram_search.pyi b/stubs/dateparser/dateparser/search/ngram_search.pyi new file mode 100644 index 000000000000..9a22a1c57174 --- /dev/null +++ b/stubs/dateparser/dateparser/search/ngram_search.pyi @@ -0,0 +1,18 @@ +import datetime +from _typeshed import Incomplete +from collections.abc import Set as AbstractSet +from logging import Logger + +from dateparser.conf import Settings + +logger: Logger + +class _NgramDateSearch: + max_tokens: int + def __init__(self, max_tokens: int = 7) -> None: ... + def search_parse( + self, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None, + text: str, + settings: Settings | dict[str, Incomplete] | None, + ) -> list[tuple[str, datetime.datetime]]: ... diff --git a/stubs/dateparser/dateparser/search/search.pyi b/stubs/dateparser/dateparser/search/search.pyi index 67e6e9582492..c7919a0aae4b 100644 --- a/stubs/dateparser/dateparser/search/search.pyi +++ b/stubs/dateparser/dateparser/search/search.pyi @@ -1,29 +1,76 @@ -from typing import Any +import datetime +import re +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Iterable, Sequence, Set as AbstractSet +from typing import Any, Final, Literal, TypedDict, type_check_only -RELATIVE_REG: Any +from dateparser.conf import Settings +from dateparser.date import DateData, DateDataParser, _DetectLanguagesFunction +from dateparser.languages.loader import LocaleDataLoader +from dateparser.languages.locale import Locale +from dateparser.search.ngram_search import _NgramDateSearch -def date_is_relative(translation): ... +@type_check_only +class _SearchDates(TypedDict): + Language: str | None + Dates: list[tuple[str, datetime.datetime]] | None + +RELATIVE_REG: Final[re.Pattern[str]] + +def date_is_relative(translation: str) -> bool: ... class _ExactLanguageSearch: - loader: Any - language: Any - def __init__(self, loader) -> None: ... - def get_current_language(self, shortname) -> None: ... - def search(self, shortname, text, settings): ... + loader: LocaleDataLoader + def __init__(self, loader: LocaleDataLoader) -> None: ... + def get_current_language(self, shortname: str) -> Locale: ... + def search(self, shortname: str, text: str, settings: Settings | None) -> tuple[list[str], list[str]]: ... @staticmethod - def set_relative_base(substring, already_parsed): ... - def choose_best_split(self, possible_parsed_splits, possible_substrings_splits): ... - def split_by(self, item, original, splitter): ... - def split_if_not_parsed(self, item, original): ... - def parse_item(self, parser, item, translated_item, parsed, need_relative_base): ... - def parse_found_objects(self, parser, to_parse, original, translated, settings): ... - def search_parse(self, shortname, text, settings): ... + def set_relative_base( + substring: str, already_parsed: list[tuple[DateData, bool]] + ) -> tuple[str, datetime.datetime | None]: ... + def choose_best_split( + self, possible_parsed_splits: list[Incomplete], possible_substrings_splits: list[Incomplete] + ) -> tuple[Incomplete, Incomplete]: ... + def split_by(self, item: str, original: str, splitter: str) -> list[list[list[str]]]: ... + def split_if_not_parsed(self, item: str, original: str) -> list[list[list[str]]]: ... + def parse_item( + self, + parser: DateDataParser, + item: str, + translated_item: str, + parsed: list[tuple[DateData, bool]], + need_relative_base: bool | None, + ) -> tuple[DateData, bool]: ... + def parse_found_objects( + self, + parser: DateDataParser, + to_parse: Iterable[str], + original: Sequence[str], + translated: Sequence[str], + settings: Settings, + ) -> tuple[list[tuple[DateData, bool]], list[str]]: ... + def search_parse(self, shortname: str, text: str, settings: Settings) -> list[tuple[str, datetime.datetime]]: ... class DateSearchWithDetection: - loader: Any - available_language_map: Any - search: Any + loader: LocaleDataLoader + available_language_map: OrderedDict[str, Locale] + search: _ExactLanguageSearch + ngram_search: _NgramDateSearch def __init__(self) -> None: ... - language_detector: Any - def detect_language(self, text, languages): ... - def search_dates(self, text, languages: Any | None = ..., settings: Any | None = ...): ... + def detect_language( + self, + text: str, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, + ) -> str | None: ... + def search_dates( + self, + text: str, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, + strategy: Literal["split", "ngram"] = "split", + ) -> _SearchDates: ... + def preprocess_text(self, text: str, languages: Iterable[str] | None) -> str: ... diff --git a/stubs/dateparser/dateparser/search/text_detection.pyi b/stubs/dateparser/dateparser/search/text_detection.pyi index ee6d30ecb5e4..fdbe298e2c0d 100644 --- a/stubs/dateparser/dateparser/search/text_detection.pyi +++ b/stubs/dateparser/dateparser/search/text_detection.pyi @@ -1,11 +1,10 @@ -from typing import Any - +from dateparser.conf import Settings +from dateparser.languages.locale import Locale from dateparser.search.detection import BaseLanguageDetector class FullTextLanguageDetector(BaseLanguageDetector): - languages: Any - language_unique_chars: Any - language_chars: Any - def __init__(self, languages) -> None: ... - def get_unique_characters(self, settings) -> None: ... - def character_check(self, date_string, settings) -> None: ... + language_unique_chars: list[set[str]] + language_chars: list[set[str]] + def __init__(self, languages: list[Locale]) -> None: ... + def get_unique_characters(self, settings: Settings) -> None: ... + def character_check(self, date_string: str, settings: Settings) -> None: ... diff --git a/stubs/dateparser/dateparser/timezone_parser.pyi b/stubs/dateparser/dateparser/timezone_parser.pyi index dc7dccd68157..e8be25d29462 100644 --- a/stubs/dateparser/dateparser/timezone_parser.pyi +++ b/stubs/dateparser/dateparser/timezone_parser.pyi @@ -1,18 +1,23 @@ -from datetime import tzinfo -from typing import Any +import re +from collections.abc import Generator +from datetime import datetime, timedelta, tzinfo +from typing import TypeVar + +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) class StaticTzInfo(tzinfo): - def __init__(self, name, offset) -> None: ... - def tzname(self, dt): ... - def utcoffset(self, dt): ... - def dst(self, dt): ... - def localize(self, dt, is_dst: bool = ...): ... - def __getinitargs__(self): ... + def __init__(self, name: str, offset: timedelta) -> None: ... + def tzname(self, dt: datetime | None) -> str: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def dst(self, dt: datetime | None) -> timedelta: ... + def localize(self, dt: _DateTimeT, is_dst: bool = False) -> _DateTimeT: ... + def __getinitargs__(self) -> tuple[str, timedelta]: ... -def pop_tz_offset_from_string(date_string, as_offset: bool = ...): ... -def word_is_tz(word): ... -def convert_to_local_tz(datetime_obj, datetime_tz_offset): ... -def build_tz_offsets(search_regex_parts): ... -def get_local_tz_offset(): ... +def pop_tz_offset_from_string(date_string: str, as_offset: bool = True) -> tuple[str, StaticTzInfo | str | None]: ... +def word_is_tz(word: str) -> bool: ... +def is_timezone_token(token: str) -> bool: ... +def convert_to_local_tz(datetime_obj: _DateTimeT, datetime_tz_offset: timedelta) -> _DateTimeT: ... +def build_tz_offsets(search_regex_parts: list[str]) -> Generator[tuple[str, dict[str, re.Pattern[str] | timedelta]]]: ... +def get_local_tz_offset() -> timedelta: ... -local_tz_offset: Any +local_tz_offset: timedelta diff --git a/stubs/dateparser/dateparser/timezones.pyi b/stubs/dateparser/dateparser/timezones.pyi index f521c45ad27c..c767c52dd861 100644 --- a/stubs/dateparser/dateparser/timezones.pyi +++ b/stubs/dateparser/dateparser/timezones.pyi @@ -1,3 +1,3 @@ -from typing import Any +from typing import Final -timezone_info_list: Any +timezone_info_list: Final[list[dict[str, list[str | tuple[str, str | int]]]]] diff --git a/stubs/dateparser/dateparser/utils/__init__.pyi b/stubs/dateparser/dateparser/utils/__init__.pyi index 1dd81898563c..695d51a09400 100644 --- a/stubs/dateparser/dateparser/utils/__init__.pyi +++ b/stubs/dateparser/dateparser/utils/__init__.pyi @@ -1,21 +1,34 @@ +import datetime +from _typeshed import MaybeNone from collections import OrderedDict -from typing import Any, Mapping +from collections.abc import Mapping +from logging import Logger +from typing import Any, TypeVar + +from dateparser.conf import Settings + +_DateT = TypeVar("_DateT", bound=datetime.date) +_DateTimeT = TypeVar("_DateTimeT", bound=datetime.datetime) def strip_braces(date_string: str) -> str: ... -def normalize_unicode(string: str, form: str = ...) -> str: ... +def normalize_unicode(string: str, form: str = "NFKD") -> str: ... def combine_dicts( primary_dict: Mapping[Any, Any], supplementary_dict: Mapping[Any, Any] ) -> OrderedDict[str, str | list[Any]]: ... -def find_date_separator(format) -> Any: ... -def localize_timezone(date_time, tz_string): ... -def apply_tzdatabase_timezone(date_time, pytz_string): ... -def apply_dateparser_timezone(utc_datetime, offset_or_timezone_abb): ... -def apply_timezone(date_time, tz_string): ... -def apply_timezone_from_settings(date_obj, settings): ... -def get_last_day_of_month(year, month): ... -def get_previous_leap_year(year): ... -def get_next_leap_year(year): ... -def set_correct_day_from_settings(date_obj, settings, current_day: Any | None = ...): ... +def find_date_separator(format: str) -> str | MaybeNone | None: ... +def localize_timezone(date_time: _DateTimeT, tz_string: str) -> _DateTimeT: ... +def apply_tzdatabase_timezone(date_time: _DateTimeT, pytz_string: str) -> _DateTimeT: ... +def apply_dateparser_timezone(utc_datetime: _DateTimeT, offset_or_timezone_abb) -> _DateTimeT | None: ... +def apply_timezone(date_time: _DateTimeT, tz_string: str) -> _DateTimeT: ... +def apply_timezone_from_settings(date_obj: _DateTimeT, settings: Settings | None) -> _DateTimeT: ... +def get_last_day_of_month(year: int, month: int) -> int: ... +def get_previous_leap_year(year: int) -> int: ... +def get_next_leap_year(year: int) -> int: ... +def set_correct_day_from_settings(date_obj: _DateT, settings: Settings, current_day: int | None = None) -> _DateT: ... +def set_correct_month_from_settings(date_obj: _DateT, settings: Settings, current_month: int | None = None) -> _DateT: ... def registry(cls): ... -def get_logger() -> Any: ... +def get_logger() -> Logger: ... def setup_logging() -> None: ... + +# TODO: this needs `types-pytz` and a type-alias +def get_timezone_from_tz_string(tz_string: str): ... diff --git a/stubs/dateparser/dateparser/utils/strptime.pyi b/stubs/dateparser/dateparser/utils/strptime.pyi index 5fceb4c1a3fe..69d630a709d0 100644 --- a/stubs/dateparser/dateparser/utils/strptime.pyi +++ b/stubs/dateparser/dateparser/utils/strptime.pyi @@ -1,8 +1,14 @@ +import re from datetime import datetime -from typing import Any +from time import struct_time +from typing import Final, Protocol, type_check_only -TIME_MATCHER: Any -MS_SEARCHER: Any +TIME_MATCHER: Final[re.Pattern[str]] +MS_SEARCHER: Final[re.Pattern[str]] -def patch_strptime() -> Any: ... -def strptime(date_string, format) -> datetime: ... +@type_check_only +class _strptime_time(Protocol): + def __call__(self, data_string: str, format: str = "%a %b %d %H:%M:%S %Y") -> struct_time: ... + +def patch_strptime() -> _strptime_time: ... +def strptime(date_string: str, format: str) -> datetime: ... diff --git a/stubs/dateparser/dateparser/utils/time_spans.pyi b/stubs/dateparser/dateparser/utils/time_spans.pyi new file mode 100644 index 000000000000..61726ba82839 --- /dev/null +++ b/stubs/dateparser/dateparser/utils/time_spans.pyi @@ -0,0 +1,23 @@ +import datetime +from typing import TypedDict, TypeVar, type_check_only +from typing_extensions import NotRequired + +from dateparser.conf import Settings + +_DateT = TypeVar("_DateT", bound=datetime.date) + +@type_check_only +class _SpanInformation(TypedDict): + type: str + direction: str + matched_text: str + start_pos: int + end_pos: int + number: NotRequired[int] + +def get_week_start(date: _DateT, start_of_week: str = "monday") -> _DateT: ... +def get_week_end(date: _DateT, start_of_week: str = "monday") -> _DateT: ... +def detect_time_span(text: str) -> _SpanInformation | None: ... +def generate_time_span( + span_info: _SpanInformation, base_date: _DateT | None = None, settings: Settings | None = None +) -> tuple[_DateT, _DateT]: ... diff --git a/stubs/dateparser/dateparser_data/settings.pyi b/stubs/dateparser/dateparser_data/settings.pyi index 2de84e3de707..42d65ec2bca0 100644 --- a/stubs/dateparser/dateparser_data/settings.pyi +++ b/stubs/dateparser/dateparser_data/settings.pyi @@ -1,4 +1,6 @@ -from typing import Any +from typing import Final -default_parsers: Any -settings: Any +from dateparser import _Settings + +default_parsers: Final[list[str]] +settings: Final[_Settings] diff --git a/stubs/decorator/@tests/stubtest_allowlist.txt b/stubs/decorator/@tests/stubtest_allowlist.txt index c256a8ca4053..3dd621676f14 100644 --- a/stubs/decorator/@tests/stubtest_allowlist.txt +++ b/stubs/decorator/@tests/stubtest_allowlist.txt @@ -1,9 +1,5 @@ -decorator.ContextManager.__init__ decorator.FunctionMaker.args decorator.FunctionMaker.kwonlyargs decorator.FunctionMaker.kwonlydefaults decorator.FunctionMaker.varargs decorator.FunctionMaker.varkw -decorator.decorate -decorator.decorator -decorator.get_init diff --git a/stubs/decorator/METADATA.toml b/stubs/decorator/METADATA.toml index 2c151642b36f..ec35837c7fa9 100644 --- a/stubs/decorator/METADATA.toml +++ b/stubs/decorator/METADATA.toml @@ -1 +1,3 @@ -version = "5.1.*" +version = "5.2.*" +upstream-repository = "https://github.com/micheles/decorator" +obsolete-since = { version = "5.3.0", date = "2026-05-17" } diff --git a/stubs/decorator/decorator.pyi b/stubs/decorator/decorator.pyi index 0d50a5412a1d..092f5c781823 100644 --- a/stubs/decorator/decorator.pyi +++ b/stubs/decorator/decorator.pyi @@ -1,83 +1,72 @@ -import sys -from typing import Any, Callable, Iterator, NamedTuple, Pattern, Text, Tuple, TypeVar +import inspect +from builtins import dict as _dict # alias to avoid conflicts with attribute name +from collections.abc import Callable, Generator, Iterator +from contextlib import _GeneratorContextManager +from inspect import Signature, getfullargspec as getfullargspec, iscoroutinefunction as iscoroutinefunction +from re import Pattern +from typing import Any, Final, Literal, ParamSpec, TypeVar _C = TypeVar("_C", bound=Callable[..., Any]) _Func = TypeVar("_Func", bound=Callable[..., Any]) _T = TypeVar("_T") +_P = ParamSpec("_P") -def get_init(cls: type) -> None: ... +DEF: Final[Pattern[str]] +POS: Final[Literal[inspect._ParameterKind.POSITIONAL_OR_KEYWORD]] +EMPTY: Final[type[inspect._empty]] -if sys.version_info >= (3,): - from inspect import getfullargspec as getfullargspec, iscoroutinefunction as iscoroutinefunction -else: - class FullArgSpec(NamedTuple): - args: list[str] - varargs: str | None - varkw: str | None - defaults: Tuple[Any, ...] - kwonlyargs: list[str] - kwonlydefaults: dict[str, Any] - annotations: dict[str, Any] - def iscoroutinefunction(f: Callable[..., Any]) -> bool: ... - def getfullargspec(func: Any) -> FullArgSpec: ... - -if sys.version_info >= (3, 2): - from contextlib import _GeneratorContextManager -else: - from contextlib import GeneratorContextManager as _GeneratorContextManager - -DEF: Pattern[str] - -_dict = dict # conflicts with attribute name - -class FunctionMaker(object): - args: list[Text] - varargs: Text | None - varkw: Text | None - defaults: Tuple[Any, ...] - kwonlyargs: list[Text] - kwonlydefaults: Text | None - shortsignature: Text | None - name: Text - doc: Text | None - module: Text | None - annotations: _dict[Text, Any] - signature: Text - dict: _dict[Text, Any] +class FunctionMaker: + args: list[str] + varargs: str | None + varkw: str | None + defaults: tuple[Any, ...] | None + kwonlyargs: list[str] + kwonlydefaults: _dict[str, Any] | None + shortsignature: str | None + name: str + doc: str | None + module: str | None + annotations: _dict[str, Any] + signature: str + dict: _dict[str, Any] def __init__( self, func: Callable[..., Any] | None = ..., - name: Text | None = ..., - signature: Text | None = ..., - defaults: Tuple[Any, ...] | None = ..., - doc: Text | None = ..., - module: Text | None = ..., - funcdict: _dict[Text, Any] | None = ..., + name: str | None = ..., + signature: str | None = ..., + defaults: tuple[Any, ...] | None = ..., + doc: str | None = ..., + module: str | None = ..., + funcdict: _dict[str, Any] | None = ..., ) -> None: ... def update(self, func: Any, **kw: Any) -> None: ... def make( - self, src_templ: Text, evaldict: _dict[Text, Any] | None = ..., addsource: bool = ..., **attrs: Any + self, src_templ: str, evaldict: _dict[str, Any] | None = ..., addsource: bool = ..., **attrs: Any ) -> Callable[..., Any]: ... @classmethod def create( cls, obj: Any, - body: Text, - evaldict: _dict[Text, Any], - defaults: Tuple[Any, ...] | None = ..., - doc: Text | None = ..., - module: Text | None = ..., + body: str, + evaldict: _dict[str, Any], + defaults: tuple[Any, ...] | None = ..., + doc: str | None = ..., + module: str | None = ..., addsource: bool = ..., **attrs: Any, ) -> Callable[..., Any]: ... -def decorate(func: _Func, caller: Callable[..., Any], extras: Any = ...) -> _Func: ... +def fix(args: tuple[Any, ...], kwargs: dict[str, Any], sig: Signature) -> tuple[tuple[Any, ...], dict[str, Any]]: ... +def decorate(func: _Func, caller: Callable[..., Any], extras: tuple[Any, ...] = ..., kwsyntax: bool = False) -> _Func: ... +def decoratorx(caller: Callable[..., Any]) -> Callable[..., Any]: ... def decorator( - caller: Callable[..., Any], _func: Callable[..., Any] | None = ... + caller: Callable[..., Any], _func: Callable[..., Any] | None = None, kwsyntax: bool = False ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ... class ContextManager(_GeneratorContextManager[_T]): + def __init__(self, g: Callable[..., Generator[_T]], *a: Any, **k: Any) -> None: ... def __call__(self, func: _C) -> _C: ... -def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... +def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, ContextManager[_T]]: ... +def append(a: type, vancestors: list[type]) -> None: ... def dispatch_on(*dispatch_args: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ... diff --git a/stubs/defusedxml/METADATA.toml b/stubs/defusedxml/METADATA.toml new file mode 100644 index 000000000000..96a6481f670b --- /dev/null +++ b/stubs/defusedxml/METADATA.toml @@ -0,0 +1,5 @@ +version = "0.7.*" +upstream-repository = "https://github.com/tiran/defusedxml" + +[tool.stubtest] +stubtest-dependencies = ["lxml"] diff --git a/stubs/defusedxml/defusedxml/ElementTree.pyi b/stubs/defusedxml/defusedxml/ElementTree.pyi new file mode 100644 index 000000000000..638db7e47a16 --- /dev/null +++ b/stubs/defusedxml/defusedxml/ElementTree.pyi @@ -0,0 +1,78 @@ +from _typeshed import ReadableBuffer +from collections.abc import Sequence +from typing import Any, Final +from xml.etree.ElementTree import ( + Element, + ElementTree, + ParseError as ParseError, + XMLParser as _XMLParser, + _FileRead, + _IterParseIterator, + _Target, + tostring as tostring, +) + +__origin__: Final = "xml.etree.ElementTree" + +class DefusedXMLParser(_XMLParser): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, + html: object = ..., # argument is deprecated, if bool(html) is True you will get TypeError + target: _Target | None = None, + encoding: str | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + +XMLTreeBuilder = DefusedXMLParser +XMLParse = DefusedXMLParser +XMLParser = DefusedXMLParser + +# Wrapper to xml.etree.ElementTree.parse +def parse( + source: _FileRead, + parser: XMLParser | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> ElementTree: ... + +# Wrapper to xml.etree.ElementTree.iterparse +# +# See there for possible return types. +def iterparse( + source: _FileRead, + events: Sequence[str] | None = None, + parser: XMLParser | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> _IterParseIterator[Any]: ... +def fromstring( + text: str | ReadableBuffer, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True +) -> Element: ... + +XML = fromstring + +__all__ = ["ParseError", "XML", "XMLParse", "XMLParser", "XMLTreeBuilder", "fromstring", "iterparse", "parse", "tostring"] diff --git a/stubs/defusedxml/defusedxml/__init__.pyi b/stubs/defusedxml/defusedxml/__init__.pyi new file mode 100644 index 000000000000..396800468af8 --- /dev/null +++ b/stubs/defusedxml/defusedxml/__init__.pyi @@ -0,0 +1,9 @@ +from .common import ( + DefusedXmlException as DefusedXmlException, + DTDForbidden as DTDForbidden, + EntitiesForbidden as EntitiesForbidden, + ExternalReferenceForbidden as ExternalReferenceForbidden, + NotSupportedError as NotSupportedError, +) + +__all__ = ["DefusedXmlException", "DTDForbidden", "EntitiesForbidden", "ExternalReferenceForbidden", "NotSupportedError"] diff --git a/stubs/defusedxml/defusedxml/cElementTree.pyi b/stubs/defusedxml/defusedxml/cElementTree.pyi new file mode 100644 index 000000000000..5d096d4f14d7 --- /dev/null +++ b/stubs/defusedxml/defusedxml/cElementTree.pyi @@ -0,0 +1,16 @@ +from typing import Final + +from .ElementTree import ( + XML as XML, + ParseError as ParseError, + XMLParse as XMLParse, + XMLParser as XMLParser, + XMLTreeBuilder as XMLTreeBuilder, + fromstring as fromstring, + iterparse as iterparse, + parse as parse, + tostring as tostring, +) + +__origin__: Final = "xml.etree.cElementTree" +__all__ = ["ParseError", "XML", "XMLParse", "XMLParser", "XMLTreeBuilder", "fromstring", "iterparse", "parse", "tostring"] diff --git a/stubs/defusedxml/defusedxml/common.pyi b/stubs/defusedxml/defusedxml/common.pyi new file mode 100644 index 000000000000..15eb3f181444 --- /dev/null +++ b/stubs/defusedxml/defusedxml/common.pyi @@ -0,0 +1,31 @@ +from typing import Final + +PY3: Final[bool] + +class DefusedXmlException(ValueError): ... + +class DTDForbidden(DefusedXmlException): + name: str + sysid: str | None + pubid: str | None + def __init__(self, name: str, sysid: str | None, pubid: str | None) -> None: ... + +class EntitiesForbidden(DefusedXmlException): + name: str + value: str | None + base: str | None + sysid: str | None + pubid: str | None + notation_name: str | None + def __init__( + self, name: str, value: str | None, base: str | None, sysid: str | None, pubid: str | None, notation_name: str | None + ) -> None: ... + +class ExternalReferenceForbidden(DefusedXmlException): + context: str + base: str | None + sysid: str | None + pubid: str | None + def __init__(self, context: str, base: str | None, sysid: str | None, pubid: str | None) -> None: ... + +class NotSupportedError(DefusedXmlException): ... diff --git a/stubs/defusedxml/defusedxml/expatbuilder.pyi b/stubs/defusedxml/defusedxml/expatbuilder.pyi new file mode 100644 index 000000000000..8905cab7c8d8 --- /dev/null +++ b/stubs/defusedxml/defusedxml/expatbuilder.pyi @@ -0,0 +1,49 @@ +from _typeshed import SupportsRead +from typing import Final +from xml.dom.expatbuilder import ExpatBuilder as _ExpatBuilder, Namespaces as _Namespaces +from xml.dom.minidom import Document +from xml.dom.xmlbuilder import Options +from xml.parsers.expat import XMLParserType + +__origin__: Final = "xml.dom.expatbuilder" + +class DefusedExpatBuilder(_ExpatBuilder): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, options: Options | None = None, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + def install(self, parser: XMLParserType) -> None: ... + +class DefusedExpatBuilderNS(_Namespaces, DefusedExpatBuilder): + def install(self, parser: XMLParserType) -> None: ... + def reset(self) -> None: ... + +def parse( + file: str | SupportsRead[bytes | str], + namespaces: bool = True, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Document: ... +def parseString( + string: str, namespaces: bool = True, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True +) -> Document: ... diff --git a/stubs/defusedxml/defusedxml/expatreader.pyi b/stubs/defusedxml/defusedxml/expatreader.pyi new file mode 100644 index 000000000000..89155fba5e71 --- /dev/null +++ b/stubs/defusedxml/defusedxml/expatreader.pyi @@ -0,0 +1,43 @@ +from typing import Final +from xml.sax.expatreader import ExpatParser as _ExpatParser, _BoolType + +__origin__: Final = "xml.sax.expatreader" + +class DefusedExpatParser(_ExpatParser): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, + namespaceHandling: _BoolType = 0, + bufsize: int = 65516, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + def reset(self) -> None: ... + +def create_parser( + namespaceHandling: _BoolType = 0, + bufsize: int = 65516, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> DefusedExpatParser: ... diff --git a/stubs/defusedxml/defusedxml/lxml.pyi b/stubs/defusedxml/defusedxml/lxml.pyi new file mode 100644 index 000000000000..0ff53d95ca3b --- /dev/null +++ b/stubs/defusedxml/defusedxml/lxml.pyi @@ -0,0 +1,55 @@ +import threading +from _typeshed import Incomplete +from typing import Final, Literal, type_check_only + +# Not bothering with types here as lxml support is supposed to be dropped in a future version of defusedxml + +LXML3: bool +__origin__: Final = "lxml.etree" + +def tostring( + element_or_tree, + *, + encoding: str | None = None, + method: Literal["xml", "html", "text", "c14n", "c14n2"] = "xml", + xml_declaration: bool | None = None, + pretty_print: bool = False, + with_tail: bool = True, + standalone: bool | None = None, + doctype=None, + exclusive: bool = False, + inclusive_ns_prefixes=None, + with_comments: bool = True, + strip_text: bool = False, +): ... + +# Should be imported from lxml.etree.ElementBase, but lxml lacks types +@type_check_only +class _ElementBase: ... + +class RestrictedElement(_ElementBase): + __slots__ = () + blacklist: Incomplete + def __iter__(self): ... + def iterchildren(self, tag=None, reversed: bool = False): ... + def iter(self, tag=None, *tags): ... + def iterdescendants(self, tag=None, *tags): ... + def itersiblings(self, tag=None, preceding: bool = False): ... + def getchildren(self): ... + def getiterator(self, tag=None): ... + +class GlobalParserTLS(threading.local): + parser_config: Incomplete + element_class: Incomplete + def createDefaultParser(self): ... + def setDefaultParser(self, parser) -> None: ... + def getDefaultParser(self): ... + +def getDefaultParser(): ... +def check_docinfo(elementtree, forbid_dtd: bool = False, forbid_entities: bool = True) -> None: ... +def parse(source, parser=None, base_url=None, forbid_dtd: bool = False, forbid_entities: bool = True): ... +def fromstring(text, parser=None, base_url=None, forbid_dtd: bool = False, forbid_entities: bool = True): ... + +XML = fromstring + +def iterparse(*args, **kwargs) -> None: ... diff --git a/stubs/defusedxml/defusedxml/minidom.pyi b/stubs/defusedxml/defusedxml/minidom.pyi new file mode 100644 index 000000000000..0097ebd5d5b8 --- /dev/null +++ b/stubs/defusedxml/defusedxml/minidom.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsRead +from typing import Final +from xml.dom.minidom import Document +from xml.sax.xmlreader import XMLReader + +__origin__: Final = "xml.dom.minidom" + +def parse( + file: str | SupportsRead[bytes | str], + parser: XMLReader | None = None, + bufsize: int | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Document: ... +def parseString( + string: str, + parser: XMLReader | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Document: ... diff --git a/stubs/defusedxml/defusedxml/pulldom.pyi b/stubs/defusedxml/defusedxml/pulldom.pyi new file mode 100644 index 000000000000..706b2b876c06 --- /dev/null +++ b/stubs/defusedxml/defusedxml/pulldom.pyi @@ -0,0 +1,22 @@ +from typing import Final +from xml.dom.pulldom import DOMEventStream +from xml.sax import _SupportsReadClose +from xml.sax.xmlreader import XMLReader + +__origin__: Final = "xml.dom.pulldom" + +def parse( + stream_or_string: str | _SupportsReadClose[str] | _SupportsReadClose[bytes], + parser: XMLReader | None = None, + bufsize: int | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> DOMEventStream: ... +def parseString( + string: str, + parser: XMLReader | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> DOMEventStream: ... diff --git a/stubs/defusedxml/defusedxml/sax.pyi b/stubs/defusedxml/defusedxml/sax.pyi new file mode 100644 index 000000000000..9ecd454218bf --- /dev/null +++ b/stubs/defusedxml/defusedxml/sax.pyi @@ -0,0 +1,26 @@ +from _typeshed import ReadableBuffer, Unused +from typing import Final +from xml.sax import ErrorHandler as _ErrorHandler, _Source, xmlreader +from xml.sax.handler import _ContentHandlerProtocol + +from .expatreader import DefusedExpatParser + +__origin__: Final = "xml.sax" + +def parse( + source: xmlreader.InputSource | _Source, + handler: _ContentHandlerProtocol, + errorHandler: _ErrorHandler = ..., + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> None: ... +def parseString( + string: ReadableBuffer, + handler: _ContentHandlerProtocol, + errorHandler: _ErrorHandler = ..., + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> None: ... +def make_parser(parser_list: Unused = []) -> DefusedExpatParser: ... diff --git a/stubs/defusedxml/defusedxml/xmlrpc.pyi b/stubs/defusedxml/defusedxml/xmlrpc.pyi new file mode 100644 index 000000000000..da38c6870004 --- /dev/null +++ b/stubs/defusedxml/defusedxml/xmlrpc.pyi @@ -0,0 +1,48 @@ +import gzip +from _typeshed import ReadableBuffer +from typing import Final, Protocol, type_check_only +from xmlrpc.client import ExpatParser, Unmarshaller + +@type_check_only +class _Readable(Protocol): + def read(self, size: int | None = -1) -> bytes: ... + +__origin__: Final = "xmlrpc.client" +MAX_DATA: Final = 31457280 + +def defused_gzip_decode(data: ReadableBuffer, limit: int | None = None) -> bytes: ... + +class DefusedGzipDecodedResponse(gzip.GzipFile): + limit: int + readlength: int | None + def __init__(self, response: _Readable, limit: int | None = None) -> None: ... + def read(self, n: int) -> bytes: ... # type: ignore[override] + def close(self) -> None: ... + +class DefusedExpatParser(ExpatParser): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, target: Unmarshaller, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + +def monkey_patch() -> None: ... +def unmonkey_patch() -> None: ... diff --git a/stubs/dirhash/METADATA.toml b/stubs/dirhash/METADATA.toml new file mode 100644 index 000000000000..a49924a2eb8a --- /dev/null +++ b/stubs/dirhash/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.5.*" +upstream-repository = "https://github.com/andhus/dirhash-python" diff --git a/stubs/dirhash/dirhash/__init__.pyi b/stubs/dirhash/dirhash/__init__.pyi new file mode 100644 index 000000000000..380aa3f9cbf4 --- /dev/null +++ b/stubs/dirhash/dirhash/__init__.pyi @@ -0,0 +1,92 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from os import PathLike +from typing import TypeAlias, TypeVar + +_DirNode: TypeAlias = Incomplete # scantree.DirNode +_RecursionPath: TypeAlias = Incomplete # scantree.RecursionPath +_RP = TypeVar("_RP", bound=_RecursionPath) + +__all__ = [ + "__version__", + "algorithms_guaranteed", + "algorithms_available", + "dirhash", + "dirhash_impl", + "included_paths", + "Filter", + "get_match_patterns", + "Protocol", +] + +__version__: str +algorithms_guaranteed: set[str] +algorithms_available: set[str] + +def dirhash( + directory: str | PathLike[str], + algorithm: str, + match: Iterable[str] = ("*",), + ignore: Iterable[str] | None = None, + linked_dirs: bool = True, + linked_files: bool = True, + empty_dirs: bool = False, + entry_properties: Iterable[str] = ("name", "data"), + allow_cyclic_links: bool = False, + chunk_size: int = 1048576, + jobs: int = 1, +) -> str: ... +def dirhash_impl( + directory: str | PathLike[str], + algorithm: str, + filter_: Filter | None = None, + protocol: Protocol | None = None, + chunk_size: int = 1048576, + jobs: int = 1, +) -> str: ... +def included_paths( + directory: str | PathLike[str], + match: Iterable[str] = ("*",), + ignore: Iterable[str] | None = None, + linked_dirs: bool = True, + linked_files: bool = True, + empty_dirs: bool = False, + allow_cyclic_links: bool = False, +) -> list[str]: ... + +class Filter: + linked_dirs: bool + linked_files: bool + empty_dirs: bool + + def __init__( + self, + match_patterns: Iterable[str] | None = None, + linked_dirs: bool = True, + linked_files: bool = True, + empty_dirs: bool = False, + ) -> None: ... + @property + def match_patterns(self) -> tuple[str, ...]: ... + def include(self, recursion_path: _RecursionPath) -> bool: ... + def match_file(self, filepath: str | PathLike[str]) -> bool: ... + def __call__(self, paths: Iterable[_RP]) -> Generator[_RP]: ... + +def get_match_patterns( + match: Iterable[str] | None = None, + ignore: Iterable[str] | None = None, + ignore_extensions: Iterable[str] | None = None, + ignore_hidden: bool = False, +) -> list[str]: ... + +class Protocol: + class EntryProperties: + NAME: str + DATA: str + IS_LINK: str + options: set[str] + + entry_properties: Iterable[str] + allow_cyclic_links: bool + def __init__(self, entry_properties: Iterable[str] = ("name", "data"), allow_cyclic_links: bool = False) -> None: ... + def get_descriptor(self, dir_node: _DirNode) -> str: ... diff --git a/stubs/dirhash/dirhash/cli.pyi b/stubs/dirhash/dirhash/cli.pyi new file mode 100644 index 000000000000..b8229142d858 --- /dev/null +++ b/stubs/dirhash/dirhash/cli.pyi @@ -0,0 +1,5 @@ +from collections.abc import Sequence +from typing import Any + +def main() -> None: ... +def get_kwargs(args: Sequence[str]) -> dict[str, Any]: ... # value depends on the key diff --git a/stubs/django-filter/@tests/django_settings.py b/stubs/django-filter/@tests/django_settings.py new file mode 100644 index 000000000000..f44d14e04e15 --- /dev/null +++ b/stubs/django-filter/@tests/django_settings.py @@ -0,0 +1,12 @@ +SECRET_KEY = "1" + +INSTALLED_APPS = ( + "django.contrib.contenttypes", + "django.contrib.sites", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.admin.apps.SimpleAdminConfig", + "django.contrib.staticfiles", + "django.contrib.auth", + "django_filters", +) diff --git a/stubs/django-filter/@tests/stubtest_allowlist.txt b/stubs/django-filter/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d52e9f9f922f --- /dev/null +++ b/stubs/django-filter/@tests/stubtest_allowlist.txt @@ -0,0 +1,19 @@ +# Lookup NamedTuple: Parameter name mismatch between inferred stub and runtime +django_filters.fields.Lookup.__new__ +django_filters.fields.Lookup.__doc__ + +# ChoiceIteratorMixin.choices: Cannot define choices property due to incompatibility with base class ChoiceField +django_filters.fields.ChoiceIteratorMixin.choices + +# Our __init__ signatures are more precise -- ignore "stub does not have *args argument" +django_filters.fields.BaseCSVField.__init__ +django_filters.fields.ChoiceField.__init__ +django_filters.fields.ChoiceIteratorMixin.__init__ +django_filters.fields.LookupChoiceField.__init__ +django_filters.fields.MultipleChoiceField.__init__ +django_filters.fields.RangeField.__init__ +django_filters.filters.QuerySetRequestMixin.__init__ +django_filters.widgets.CSVWidget.__init__ + +# BaseCSVFilter constructs a custom class dynamically, which stubtest can't handle. +django_filters(\.\w+)*\.OrderingFilter.field_class diff --git a/stubs/django-filter/METADATA.toml b/stubs/django-filter/METADATA.toml new file mode 100644 index 000000000000..ac437a8b53cc --- /dev/null +++ b/stubs/django-filter/METADATA.toml @@ -0,0 +1,7 @@ +version = "26.2.*" +upstream-repository = "https://github.com/carltongibson/django-filter/" +dependencies = ["django-stubs>=6.0.8"] + +[tool.stubtest] +mypy-plugins = ["mypy_django_plugin.main"] +mypy-plugins-config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}} diff --git a/stubs/django-filter/django_filters/__init__.pyi b/stubs/django-filter/django_filters/__init__.pyi new file mode 100644 index 000000000000..1ed733b2476a --- /dev/null +++ b/stubs/django-filter/django_filters/__init__.pyi @@ -0,0 +1,10 @@ +from typing import Final + +from .filters import * +from .filterset import FilterSet as FilterSet, UnknownFieldBehavior as UnknownFieldBehavior + +__version__: Final[str] + +def parse_version(version: str) -> tuple[str | int]: ... + +VERSION: tuple[str | int, ...] diff --git a/stubs/django-filter/django_filters/compat.pyi b/stubs/django-filter/django_filters/compat.pyi new file mode 100644 index 000000000000..87785dfab536 --- /dev/null +++ b/stubs/django-filter/django_filters/compat.pyi @@ -0,0 +1 @@ +def is_crispy() -> bool: ... diff --git a/stubs/django-filter/django_filters/conf.pyi b/stubs/django-filter/django_filters/conf.pyi new file mode 100644 index 000000000000..b519d1da8b5d --- /dev/null +++ b/stubs/django-filter/django_filters/conf.pyi @@ -0,0 +1,17 @@ +from _typeshed import Unused +from typing import Any + +DEFAULTS: dict[str, Any] # Configuration values can be strings, booleans, callables, etc. +DEPRECATED_SETTINGS: list[str] + +def is_callable(value: Any) -> bool: ... # Accepts any value to test if it's callable + +class Settings: + # Setting values can be of any type, so getter and setter methods return/accept Any + def __getattr__(self, name: str) -> Any: ... # Returns setting values of various types + def get_setting(self, setting: str) -> Any: ... # Setting values vary by configuration option + def change_setting( + self, setting: str, value: Any, enter: bool, **kwargs: Unused + ) -> None: ... # Accepts any setting value type + +settings: Settings diff --git a/stubs/django-filter/django_filters/constants.pyi b/stubs/django-filter/django_filters/constants.pyi new file mode 100644 index 000000000000..1a88634ea477 --- /dev/null +++ b/stubs/django-filter/django_filters/constants.pyi @@ -0,0 +1,6 @@ +from typing import Any, Final + +# String constant used to indicate all model fields should be included +ALL_FIELDS: Final[str] = "__all__" +# Collection of values considered empty by Django filters - tuple type allows various empty containers +EMPTY_VALUES: Final[Any] = ... diff --git a/stubs/django-filter/django_filters/exceptions.pyi b/stubs/django-filter/django_filters/exceptions.pyi new file mode 100644 index 000000000000..725c08b5cada --- /dev/null +++ b/stubs/django-filter/django_filters/exceptions.pyi @@ -0,0 +1,8 @@ +from typing import Any + +from django.core.exceptions import FieldError +from django.db import models + +class FieldLookupError(FieldError): + # Field type params are runtime-determined + def __init__(self, model_field: models.Field[Any, Any], lookup_expr: str) -> None: ... diff --git a/stubs/django-filter/django_filters/fields.pyi b/stubs/django-filter/django_filters/fields.pyi new file mode 100644 index 000000000000..9a2b5293d4ee --- /dev/null +++ b/stubs/django-filter/django_filters/fields.pyi @@ -0,0 +1,159 @@ +from _typeshed import Unused +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, NamedTuple, TypeAlias, TypeVar + +from django import forms +from django.db.models import Choices +from django.db.models.base import Model +from django.forms import Widget +from django_stubs_ext import StrOrPromise + +DJANGO_50: bool + +# Ref: django-stubs/forms/fields.pyi +# Problem: attribute `widget` is always of type `Widget` after field instantiation. +# However, on class level it can be set to `Type[Widget]` too. +# If we annotate it as `Union[Widget, Type[Widget]]`, every code that uses field +# instances will not typecheck. +# If we annotate it as `Widget`, any widget subclasses that do e.g. +# `widget = Select` will not typecheck. +# `Any` gives too much freedom, but does not create false positives. +_ClassLevelWidget: TypeAlias = Any +# Validator parameter type depends on type of the form field used. +_ValidatorCallable: TypeAlias = Callable[[Any], None] +# Based on django-stubs utils/choices.pyi +_Choice: TypeAlias = tuple[Any, Any] +_ChoiceNamedGroup: TypeAlias = tuple[str, Iterable[_Choice]] +_Choices: TypeAlias = Iterable[_Choice | _ChoiceNamedGroup] +_ChoicesMapping: TypeAlias = Mapping[Any, Any] +_ChoicesInput: TypeAlias = _Choices | _ChoicesMapping | type[Choices] | Callable[[], _Choices | _ChoicesMapping] + +_M = TypeVar("_M", bound=Model) + +class RangeField(forms.MultiValueField): + widget: _ClassLevelWidget = ... + def __init__( + self, + fields: tuple[forms.Field, forms.Field] | None = None, + *, + # Inherited from Django MultiValueField + require_all_fields: bool = True, + required: bool = ..., + widget: Widget | type[Widget] | None = ..., + label: StrOrPromise | None = ..., + initial: Any | None = ..., # Type depends on the form field used. + help_text: StrOrPromise = ..., + error_messages: Mapping[str, StrOrPromise] | None = ..., + show_hidden_initial: bool = ..., + validators: Sequence[_ValidatorCallable] = ..., + localize: bool = ..., + disabled: bool = ..., + label_suffix: str | None = ..., + ) -> None: ... # Args/kwargs can be any field params, passes to parent + def compress(self, data_list: list[Any] | None) -> slice | None: ... # Data list elements can be any field value type + +class DateRangeField(RangeField): + widget: _ClassLevelWidget = ... + def compress(self, data_list: list[Any] | None) -> slice | None: ... # Date values in list can be any date type + +class DateTimeRangeField(RangeField): + widget: _ClassLevelWidget = ... + +class IsoDateTimeRangeField(RangeField): + widget: _ClassLevelWidget = ... + +class TimeRangeField(RangeField): + widget: _ClassLevelWidget = ... + +class Lookup(NamedTuple): + value: Any # Lookup values can be any filterable type + lookup_expr: str + +class LookupChoiceField(forms.MultiValueField): + def __init__( + self, + field: forms.Field, + lookup_choices: Sequence[tuple[str, str]], + *, + empty_label: StrOrPromise = ..., + widget: Unused = ..., + help_text: Unused = ..., + # Inherited from Django MultiValueField + require_all_fields: bool = True, + required: bool = ..., + label: StrOrPromise | None = ..., + initial: Any | None = ..., # Type depends on the form field used. + error_messages: Mapping[str, StrOrPromise] | None = ..., + show_hidden_initial: bool = ..., + validators: Sequence[_ValidatorCallable] = ..., + localize: bool = ..., + disabled: bool = ..., + label_suffix: str | None = ..., + ) -> None: ... # Args/kwargs can be any field params, uses kwargs for empty_label + def compress(self, data_list: list[Any] | None) -> Lookup | None: ... # Data list can contain any lookup components + +class IsoDateTimeField(forms.DateTimeField): + ISO_8601: str + input_formats: list[str] + def strptime(self, value: str, format: str) -> Any: ... # Returns datetime objects or parsing results + +class BaseCSVField(forms.Field): + base_widget_class: _ClassLevelWidget = ... + def clean(self, value: Any) -> Any: ... # Cleaned values can be any valid field type + +class BaseRangeField(BaseCSVField): + widget: _ClassLevelWidget = ... + def clean(self, value: Any) -> Any: ... # Input and output values can be any range type + +class ChoiceIterator: + field: ChoiceField + choices: Sequence[tuple[Any, str]] # Choice values can be any type (int, str, Model, etc.) + def __init__( + self, field: ChoiceField, choices: Sequence[tuple[Any, str]] + ) -> None: ... # Choice values can be any selectable type + def __iter__(self) -> Any: ... # Iterator yields choice tuples with any value types + def __len__(self) -> int: ... + +class ModelChoiceIterator(forms.models.ModelChoiceIterator[_M]): + def __iter__(self) -> Any: ... # Iterator yields choice tuples with any value types + def __len__(self) -> int: ... + +class ChoiceIteratorMixin: + null_label: StrOrPromise | None + null_value: Any # Null choice values can be any type (None, empty string, etc.) + def __init__(self, *, null_label: StrOrPromise | None, null_value: Any) -> None: ... + +class ChoiceField(ChoiceIteratorMixin, forms.ChoiceField): + iterator = ChoiceIterator + empty_label: StrOrPromise + def __init__( + self, + *, + empty_label: StrOrPromise = ..., + # Inherited from Django ChoiceField + choices: _ChoicesInput = (), + required: bool = ..., + widget: Widget | type[Widget] | None = ..., + label: StrOrPromise | None = ..., + initial: Any | None = ..., # Type depends on the form field used. + help_text: StrOrPromise = ..., + error_messages: Mapping[str, StrOrPromise] | None = ..., + show_hidden_initial: bool = ..., + validators: Sequence[_ValidatorCallable] = ..., + localize: bool = ..., + disabled: bool = ..., + label_suffix: str | None = ..., + null_label: StrOrPromise | None, + null_value: Any, # Type depends on the form field used. + ) -> None: ... + +class MultipleChoiceField(ChoiceIteratorMixin, forms.MultipleChoiceField): + iterator = ChoiceIterator + empty_label: StrOrPromise | None + +class ModelChoiceField(ChoiceIteratorMixin, forms.ModelChoiceField[Any]): + iterator = ModelChoiceIterator + def to_python(self, value: Any) -> Any: ... # Converts any input to Python model objects or values + +class ModelMultipleChoiceField(ChoiceIteratorMixin, forms.ModelMultipleChoiceField[Any]): + iterator = ModelChoiceIterator diff --git a/stubs/django-filter/django_filters/filters.pyi b/stubs/django-filter/django_filters/filters.pyi new file mode 100644 index 000000000000..ed728843981f --- /dev/null +++ b/stubs/django-filter/django_filters/filters.pyi @@ -0,0 +1,329 @@ +from collections import OrderedDict +from collections.abc import Callable, Iterable +from typing import Any + +from django import forms +from django.db.models import QuerySet +from django.forms import Field +from django_stubs_ext import StrOrPromise + +from .fields import ( + BaseCSVField, + BaseRangeField, + DateRangeField, + DateTimeRangeField, + IsoDateTimeField, + IsoDateTimeRangeField, + Lookup, + LookupChoiceField, + ModelChoiceField, + ModelMultipleChoiceField, + RangeField, + TimeRangeField, +) + +__all__ = [ + "AllValuesFilter", + "AllValuesMultipleFilter", + "BaseCSVFilter", + "BaseInFilter", + "BaseRangeFilter", + "BooleanFilter", + "CharFilter", + "ChoiceFilter", + "DateFilter", + "DateFromToRangeFilter", + "DateRangeFilter", + "DateTimeFilter", + "DateTimeFromToRangeFilter", + "DurationFilter", + "Filter", + "IsoDateTimeFilter", + "IsoDateTimeFromToRangeFilter", + "LookupChoiceFilter", + "ModelChoiceFilter", + "ModelMultipleChoiceFilter", + "MultipleChoiceFilter", + "NumberFilter", + "NumericRangeFilter", + "OrderingFilter", + "RangeFilter", + "TimeFilter", + "TimeRangeFilter", + "TypedChoiceFilter", + "TypedMultipleChoiceFilter", + "UUIDFilter", +] + +class Filter: + creation_counter: int + field_class: type[Any] # Subclasses specify more specific field types + field_name: str | None + lookup_expr: str + distinct: bool + exclude: bool + extra: dict[str, Any] # Field kwargs can include various types of parameters + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def get_method(self, qs: QuerySet[Any]) -> Callable[..., QuerySet[Any]]: ... # Returns QuerySet filtering methods + method: Callable[..., Any] | str | None # Custom filter methods return various types + label: StrOrPromise | None # Filter label for display + @property + def field(self) -> Field: ... + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... # Filter value can be any user input type + +class CharFilter(Filter): + field_class: type[forms.CharField] + +class BooleanFilter(Filter): + field_class: type[forms.NullBooleanField] + +class ChoiceFilter(Filter): + field_class: type[Any] # Base class for choice-based filters + null_value: Any # Null value can be any type (None, empty string, etc.) + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class TypedChoiceFilter(Filter): + field_class: type[forms.TypedChoiceField] + +class UUIDFilter(Filter): + field_class: type[forms.UUIDField] + +class MultipleChoiceFilter(Filter): + field_class: type[Any] # Base class for multiple choice filters + always_filter: bool + conjoined: bool + null_value: Any # Multiple choice null values vary by implementation + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + distinct: bool = True, # Overrides distinct default + conjoined: bool = False, + null_value: Any = ..., # Multiple choice null values vary by implementation + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def is_noop(self, qs: QuerySet[Any], value: Any) -> bool: ... # Value can be any filter input + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + def get_filter_predicate(self, v: Any) -> dict[str, Any]: ... # Predicate value can be any filter input type + +class TypedMultipleChoiceFilter(MultipleChoiceFilter): + field_class: type[forms.TypedMultipleChoiceField] # More specific than parent MultipleChoiceField + +class DateFilter(Filter): + field_class: type[forms.DateField] + +class DateTimeFilter(Filter): + field_class: type[forms.DateTimeField] + +class IsoDateTimeFilter(DateTimeFilter): + field_class: type[IsoDateTimeField] + +class TimeFilter(Filter): + field_class: type[forms.TimeField] + +class DurationFilter(Filter): + field_class: type[forms.DurationField] + +class QuerySetRequestMixin: + queryset: QuerySet[Any] | None + def __init__(self, *, queryset: QuerySet[Any] | None) -> None: ... + def get_request(self) -> Any: ... # Request can be HttpRequest or other request types + def get_queryset(self, request: Any) -> QuerySet[Any]: ... # Request parameter accepts various request types + @property + def field(self) -> Field: ... + +class ModelChoiceFilter(QuerySetRequestMixin, ChoiceFilter): + field_class: type[ModelChoiceField] # More specific than parent ChoiceField + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + # Inherited from QuerySetRequestMixin + queryset: QuerySet[Any] | None = None, + # Inherited from ChoiceFilter + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + +class ModelMultipleChoiceFilter(QuerySetRequestMixin, MultipleChoiceFilter): + field_class: type[ModelMultipleChoiceField] # More specific than parent MultipleChoiceField + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + # Inherited from QuerySetRequestMixin + queryset: QuerySet[Any] | None = None, + # Inherited from MultipleChoiceFilter + distinct: bool = True, # Overrides distinct default + conjoined: bool = False, + null_value: Any = ..., # Multiple choice null values vary by implementation + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + +class NumberFilter(Filter): + field_class: type[forms.DecimalField] + def get_max_validator(self) -> Any: ... # Validator can be various Django validator types + @property + def field(self) -> Field: ... + +class NumericRangeFilter(Filter): + field_class: type[RangeField] + lookup_expr: str + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class RangeFilter(Filter): + field_class: type[RangeField] + lookup_expr: str + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class DateRangeFilter(ChoiceFilter): + choices: list[tuple[str, str]] | None + filters: dict[str, Filter] | None + def __init__( + self, + choices: list[tuple[str, str]] | None = None, + filters: dict[str, Filter] | None = None, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + # Inherited from ChoiceFilter + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... # Uses args/kwargs for choice and filter configuration + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class DateFromToRangeFilter(RangeFilter): + field_class: type[DateRangeField] + +class DateTimeFromToRangeFilter(RangeFilter): + field_class: type[DateTimeRangeField] + +class IsoDateTimeFromToRangeFilter(RangeFilter): + field_class: type[IsoDateTimeRangeField] + +class TimeRangeFilter(RangeFilter): + field_class: type[TimeRangeField] + +class AllValuesFilter(ChoiceFilter): + @property + def field(self) -> Field: ... + +class AllValuesMultipleFilter(MultipleChoiceFilter): + @property + def field(self) -> Field: ... + +class BaseCSVFilter(Filter): + base_field_class: type[BaseCSVField] = ... + field_class: type[Any] # Base class for CSV-based filters + +class BaseInFilter(BaseCSVFilter): ... + +class BaseRangeFilter(BaseCSVFilter): + base_field_class: type[BaseRangeField] = ... + +class LookupChoiceFilter(Filter): + field_class: type[forms.CharField] + outer_class: type[LookupChoiceField] = ... + empty_label: StrOrPromise | None + lookup_choices: list[tuple[str, StrOrPromise]] | None + def __init__( + self, + field_name: str | None = None, + lookup_choices: list[tuple[str, StrOrPromise]] | None = None, + field_class: type[Field] | None = None, + *, + empty_label: StrOrPromise = ..., + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + @classmethod + def normalize_lookup(cls, lookup: str | tuple[str, StrOrPromise]) -> tuple[str, StrOrPromise]: ... + def get_lookup_choices(self) -> list[tuple[str, StrOrPromise]]: ... + @property + def field(self) -> Field: ... + lookup_expr: str + def filter(self, qs: QuerySet[Any], lookup: Lookup) -> QuerySet[Any]: ... + +class OrderingFilter(BaseCSVFilter, ChoiceFilter): + # Inherits CSV field behavior for comma-separated ordering. + # BaseCSVFilter constructs a custom ConcreteCSVField class that derives + # from BaseCSVField. + field_class: type[BaseCSVField] + descending_fmt: str + param_map: dict[str, str] | None + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + fields: dict[str, str] | Iterable[str | tuple[str, str]] = ..., + field_labels: dict[str, StrOrPromise] = ..., + # Inherited from ChoiceFilter + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def get_ordering_value(self, param: str) -> str: ... + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + @classmethod + def normalize_fields(cls, fields: dict[str, str] | Iterable[str | tuple[str, str]]) -> OrderedDict[str, str]: ... + def build_choices(self, fields: Any, labels: dict[str, StrOrPromise] | None) -> list[tuple[str, str]]: ... + +class FilterMethod: + f: Filter + def __init__(self, filter_instance: Filter) -> None: ... + def __call__(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + @property + def method(self) -> Callable[..., Any]: ... diff --git a/stubs/django-filter/django_filters/filterset.pyi b/stubs/django-filter/django_filters/filterset.pyi new file mode 100644 index 000000000000..72cdeab7b5aa --- /dev/null +++ b/stubs/django-filter/django_filters/filterset.pyi @@ -0,0 +1,88 @@ +from collections import OrderedDict +from collections.abc import Sequence +from enum import Enum +from typing import Any, ClassVar + +from django.db import models +from django.db.models import Model, QuerySet +from django.forms import Form +from django.http import HttpRequest, QueryDict + +from .filters import Filter + +def remote_queryset(field: models.Field[Any, Any]) -> QuerySet[Any]: ... # Field type params vary by model definition + +class UnknownFieldBehavior(Enum): + RAISE = "raise" + WARN = "warn" + IGNORE = "ignore" + +class FilterSetOptions: + model: type[Model] | None + fields: Sequence[str] | dict[str, Sequence[str]] | str | None + exclude: Sequence[str] | None + filter_overrides: dict[type[models.Field[Any, Any]], dict[str, Any]] # Field override mapping + form: type[Form] + unknown_field_behavior: UnknownFieldBehavior + def __init__(self, options: Any | None = None) -> None: ... # Meta options can be various configuration types + +class FilterSetMetaclass(type): + # Class attrs vary by definition + def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> FilterSetMetaclass: ... + + # Class attrs vary by definition + @classmethod + def get_declared_filters(cls, bases: tuple[type, ...], attrs: dict[str, Any]) -> OrderedDict[str, Filter]: ... + +# Django field types vary widely - Any allows mapping all field types to their filters +FILTER_FOR_DBFIELD_DEFAULTS: dict[type[models.Field[Any, Any]], dict[str, Any]] + +class BaseFilterSet: + FILTER_DEFAULTS: ClassVar[dict[type[models.Field[Any, Any]], dict[str, Any]]] = ... # Field type mapping + is_bound: bool + base_filters: OrderedDict[str, Filter] + declared_filters: OrderedDict[str, Filter] + data: QueryDict | dict[str, Any] | None # Filter input data values vary + queryset: QuerySet[Any] | None # Base queryset for any model type + request: HttpRequest | None + form_prefix: str | None + filters: OrderedDict[str, Filter] + def __init__( + self, + data: QueryDict | dict[str, Any] | None = None, # Filter data values vary + queryset: QuerySet[Any] | None = None, # Base queryset for any model + *, + request: HttpRequest | None = None, + prefix: str | None = None, + ) -> None: ... + def is_valid(self) -> bool: ... + @property + def errors(self) -> dict[str, list[str]]: ... + def filter_queryset(self, queryset: QuerySet[Any]) -> QuerySet[Any]: ... # Works with any model type + @property + def qs(self) -> QuerySet[Any]: ... # Filtered queryset of any model + def get_form_class(self) -> type[Form]: ... + @property + def form(self) -> Form: ... + @classmethod + def get_fields(cls) -> dict[str, models.Field[Any, Any]]: ... # Model fields have varying type params + @classmethod + def get_filter_name(cls, field_name: str, lookup_expr: str) -> str: ... + @classmethod + def get_filters(cls) -> OrderedDict[str, Filter]: ... + @classmethod + def handle_unrecognized_field(cls, field_name: str, message: str) -> None: ... + @classmethod + def filter_for_field( + cls, field: models.Field[Any, Any], field_name: str, lookup_expr: str | None = None + ) -> Filter: ... # Accepts any Django field type + @classmethod + def filter_for_lookup( + cls, field: models.Field[Any, Any], lookup_type: str # Field type varies by model + ) -> tuple[type[Filter], dict[str, Any]]: ... + +class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass): ... + +def filterset_factory( + model: type[Model], filterset: FilterSetMetaclass = ..., fields: Sequence[str] | dict[str, Sequence[str]] | str | None = None +) -> type[FilterSet]: ... diff --git a/stubs/django-filter/django_filters/rest_framework/__init__.pyi b/stubs/django-filter/django_filters/rest_framework/__init__.pyi new file mode 100644 index 000000000000..560557bc8d9b --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/__init__.pyi @@ -0,0 +1,34 @@ +from .backends import DjangoFilterBackend as DjangoFilterBackend +from .filters import ( + AllValuesFilter as AllValuesFilter, + AllValuesMultipleFilter as AllValuesMultipleFilter, + BaseCSVFilter as BaseCSVFilter, + BaseInFilter as BaseInFilter, + BaseRangeFilter as BaseRangeFilter, + BooleanFilter as BooleanFilter, + CharFilter as CharFilter, + ChoiceFilter as ChoiceFilter, + DateFilter as DateFilter, + DateFromToRangeFilter as DateFromToRangeFilter, + DateRangeFilter as DateRangeFilter, + DateTimeFilter as DateTimeFilter, + DateTimeFromToRangeFilter as DateTimeFromToRangeFilter, + DurationFilter as DurationFilter, + Filter as Filter, + IsoDateTimeFilter as IsoDateTimeFilter, + IsoDateTimeFromToRangeFilter as IsoDateTimeFromToRangeFilter, + LookupChoiceFilter as LookupChoiceFilter, + ModelChoiceFilter as ModelChoiceFilter, + ModelMultipleChoiceFilter as ModelMultipleChoiceFilter, + MultipleChoiceFilter as MultipleChoiceFilter, + NumberFilter as NumberFilter, + NumericRangeFilter as NumericRangeFilter, + OrderingFilter as OrderingFilter, + RangeFilter as RangeFilter, + TimeFilter as TimeFilter, + TimeRangeFilter as TimeRangeFilter, + TypedChoiceFilter as TypedChoiceFilter, + TypedMultipleChoiceFilter as TypedMultipleChoiceFilter, + UUIDFilter as UUIDFilter, +) +from .filterset import FilterSet as FilterSet diff --git a/stubs/django-filter/django_filters/rest_framework/backends.pyi b/stubs/django-filter/django_filters/rest_framework/backends.pyi new file mode 100644 index 000000000000..c58bf4c98260 --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/backends.pyi @@ -0,0 +1,29 @@ +from typing import Any, TypeAlias + +from django.db.models import QuerySet +from django.http import HttpRequest +from django_filters.filterset import FilterSetMetaclass + +from . import filterset + +# APIView placeholder - djangorestframework is optional, so we use Any for compatibility +_APIView: TypeAlias = Any + +class DjangoFilterBackend: + filterset_base: FilterSetMetaclass = ... + raise_exception: bool + @property + def template(self) -> str: ... + + # Works with any model type + def get_filterset(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> filterset.FilterSet | None: ... + + # Any model queryset + def get_filterset_class(self, view: _APIView, queryset: QuerySet[Any] | None = None) -> type[filterset.FilterSet] | None: ... + + # Kwargs vary by filterset + def get_filterset_kwargs(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> dict[str, Any]: ... + + # Filters any model type + def filter_queryset(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> QuerySet[Any]: ... + def to_html(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> str: ... # Renders form for any model diff --git a/stubs/django-filter/django_filters/rest_framework/filters.pyi b/stubs/django-filter/django_filters/rest_framework/filters.pyi new file mode 100644 index 000000000000..9dec2084d15f --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/filters.pyi @@ -0,0 +1,68 @@ +from ..filters import ( + AllValuesFilter, + AllValuesMultipleFilter, + BaseCSVFilter, + BaseInFilter, + BaseRangeFilter, + BooleanFilter as _BaseBooleanFilter, + CharFilter, + ChoiceFilter, + DateFilter, + DateFromToRangeFilter, + DateRangeFilter, + DateTimeFilter, + DateTimeFromToRangeFilter, + DurationFilter, + Filter, + IsoDateTimeFilter, + IsoDateTimeFromToRangeFilter, + LookupChoiceFilter, + ModelChoiceFilter, + ModelMultipleChoiceFilter, + MultipleChoiceFilter, + NumberFilter, + NumericRangeFilter, + OrderingFilter, + RangeFilter, + TimeFilter, + TimeRangeFilter, + TypedChoiceFilter, + TypedMultipleChoiceFilter, + UUIDFilter, +) + +__all__ = [ + "AllValuesFilter", + "AllValuesMultipleFilter", + "BaseCSVFilter", + "BaseInFilter", + "BaseRangeFilter", + "BooleanFilter", + "CharFilter", + "ChoiceFilter", + "DateFilter", + "DateFromToRangeFilter", + "DateRangeFilter", + "DateTimeFilter", + "DateTimeFromToRangeFilter", + "DurationFilter", + "Filter", + "IsoDateTimeFilter", + "IsoDateTimeFromToRangeFilter", + "LookupChoiceFilter", + "ModelChoiceFilter", + "ModelMultipleChoiceFilter", + "MultipleChoiceFilter", + "NumberFilter", + "NumericRangeFilter", + "OrderingFilter", + "RangeFilter", + "TimeFilter", + "TimeRangeFilter", + "TypedChoiceFilter", + "TypedMultipleChoiceFilter", + "UUIDFilter", +] + +# REST framework specific BooleanFilter that uses BooleanWidget by default +class BooleanFilter(_BaseBooleanFilter): ... diff --git a/stubs/django-filter/django_filters/rest_framework/filterset.pyi b/stubs/django-filter/django_filters/rest_framework/filterset.pyi new file mode 100644 index 000000000000..cd7eb9ab5813 --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/filterset.pyi @@ -0,0 +1,17 @@ +from collections import OrderedDict +from typing import Any, ClassVar + +from django.db import models +from django.forms import Form +from django_filters import filterset +from django_filters.filters import Filter + +# REST framework field mappings support all Django field types +FILTER_FOR_DBFIELD_DEFAULTS: dict[type[models.Field[Any, Any]], dict[str, Any]] + +class FilterSet(filterset.FilterSet): + FILTER_DEFAULTS: ClassVar[dict[type[models.Field[Any, Any]], dict[str, Any]]] = ... # DRF field mappings + base_filters: OrderedDict[str, Filter] + declared_filters: OrderedDict[str, Filter] + @property + def form(self) -> Form: ... diff --git a/stubs/django-filter/django_filters/utils.pyi b/stubs/django-filter/django_filters/utils.pyi new file mode 100644 index 000000000000..247108ee84ec --- /dev/null +++ b/stubs/django-filter/django_filters/utils.pyi @@ -0,0 +1,36 @@ +from collections.abc import Callable +from datetime import datetime +from typing import Any + +from django.db import models +from django.db.models import Model + +def deprecate(msg: str, level_modifier: int = 0) -> None: ... + +class MigrationNotice(DeprecationWarning): + url: str + def __init__(self, message: str) -> None: ... + +class RenameAttributesBase(type): + renamed_attributes: tuple[tuple[str, str, DeprecationWarning], ...] = () + + # Class attrs vary by definition + def __new__(metacls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> RenameAttributesBase: ... + def get_name(metacls, name: str) -> str: ... + def __getattr__(metacls, name: str) -> Any: ... # Attribute values vary by name and class + def __setattr__(metacls, name: str, value: Any) -> None: ... # Attribute values can be any type + +def try_dbfield( + fn: Callable[[models.Field[Any, Any]], Any], field_class: type[models.Field[Any, Any]] +) -> Any: ... # Generic field operation +def get_all_model_fields(model: type[Model]) -> dict[str, models.Field[Any, Any]]: ... # Fields vary by model definition +def get_model_field(model: type[Model], field_name: str) -> models.Field[Any, Any]: ... # Field type unknown at static time +def get_field_parts(model: type[Model], field_name: str) -> list[models.Field[Any, Any]]: ... # Relationship fields vary +def resolve_field( + model_field: models.Field[Any, Any], lookup_expr: str +) -> tuple[models.Field[Any, Any], str]: ... # Generic field resolution +def handle_timezone(value: datetime, is_dst: bool | None = None) -> datetime: ... +def verbose_field_name(model: type[Model], field_name: str) -> str: ... +def verbose_lookup_expr(lookup_expr: str) -> str: ... +def label_for_filter(model: type[Model], field_name: str, lookup_expr: str, exclude: bool = False) -> str: ... +def translate_validation(error_dict: dict[str, list[str]]) -> dict[str, list[str]]: ... diff --git a/stubs/django-filter/django_filters/views.pyi b/stubs/django-filter/django_filters/views.pyi new file mode 100644 index 000000000000..0af9f1f21256 --- /dev/null +++ b/stubs/django-filter/django_filters/views.pyi @@ -0,0 +1,38 @@ +from _typeshed import Unused +from typing import Any + +from django.db.models import Model, QuerySet +from django.http import HttpRequest, HttpResponse +from django.views.generic import View +from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin + +from .constants import ALL_FIELDS +from .filterset import FilterSet + +class FilterMixin: + filterset_class: type[FilterSet] | None + filterset_fields = ALL_FIELDS + strict: bool + def get_filterset_class(self) -> type[FilterSet] | None: ... + def get_filterset(self, filterset_class: type[FilterSet]) -> FilterSet: ... + def get_filterset_kwargs(self, filterset_class: type[FilterSet]) -> dict[str, Any]: ... # Filterset init params vary + def get_strict(self) -> bool: ... + +class BaseFilterView(FilterMixin, MultipleObjectMixin[Any], View): # Generic model type + filterset: FilterSet + object_list: QuerySet[Any] # Filtered objects of any model type + + def get(self, request: HttpRequest, *args: Unused, **kwargs: Unused) -> HttpResponse: ... + +class FilterView(MultipleObjectTemplateResponseMixin, BaseFilterView): + template_name_suffix: str + +def object_filter( + request: HttpRequest, + model: type[Model] | None = None, + queryset: QuerySet[Any] | None = None, # Base queryset for any model + template_name: str | None = None, + extra_context: dict[str, Any] | None = None, # Template context values vary + context_processors: list[Any] | None = None, # Context processors vary by implementation + filter_class: type[FilterSet] | None = None, +) -> HttpResponse: ... diff --git a/stubs/django-filter/django_filters/widgets.pyi b/stubs/django-filter/django_filters/widgets.pyi new file mode 100644 index 000000000000..8707dc0fdbfb --- /dev/null +++ b/stubs/django-filter/django_filters/widgets.pyi @@ -0,0 +1,81 @@ +from collections.abc import Mapping, Sequence +from typing import Any + +from django import forms +from django.http import QueryDict +from django.utils.safestring import SafeString + +class LinkWidget(forms.Widget): + # Choice values can be any type (int, str, Model, etc.) + choices: Sequence[tuple[Any, str]] + # Choice values can be any selectable type + def __init__(self, attrs: dict[str, Any] | None = None, choices: Sequence[tuple[Any, str]] = ()) -> None: ... + data: QueryDict | dict[str, Any] + # Return value depends on widget data type + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> Any: ... + # Widget value and renderer can be any type, choices parameter combines with class choices + def render( # type: ignore[override] + self, + name: str, + value: Any, + attrs: dict[str, Any] | None = None, + choices: Sequence[tuple[Any, str]] = (), + renderer: Any | None = None, + ) -> SafeString: ... + # Choice values and selections can be any type + def render_options(self, choices: Sequence[tuple[Any, str]], selected_choices: list[Any], name: str) -> str: ... + # Selected choices and option values can be any type + def render_option(self, name: str, selected_choices: list[Any], option_value: Any, option_label: str) -> str: ... + def option_string(self) -> str: ... + +class SuffixedMultiWidget(forms.MultiWidget): + suffixes: list[str] + def suffixed(self, name: str, suffix: str) -> str: ... + # Widget value and context can contain any data types + def get_context(self, name: str, value: Any, attrs: dict[str, Any] | None) -> dict[str, Any]: ... + # Returns list of any value types from widget data + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> list[Any]: ... + # Widget data can contain any types + def value_omitted_from_data(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> bool: ... + def replace_name(self, output: str, index: int) -> str: ... + # Decompresses any widget value into list of components + def decompress(self, value: Any) -> list[Any] | None: ... + +class RangeWidget(SuffixedMultiWidget): + template_name: str + suffixes: list[str] + # Accepts any widget attribute types + def __init__(self, attrs: dict[str, Any] | None = None) -> None: ... + # Decompresses any range value into list components + def decompress(self, value: Any) -> list[Any] | None: ... + +class DateRangeWidget(RangeWidget): + suffixes: list[str] + +class LookupChoiceWidget(SuffixedMultiWidget): + suffixes: list[str] + # Decompresses any lookup choice value into components + def decompress(self, value: Any) -> list[Any] | None: ... + +class BooleanWidget(forms.Select): + # Accepts any widget attribute types + def __init__(self, attrs: dict[str, Any] | None = None) -> None: ... + # Widget value and renderer can be any type + def render(self, name: str, value: Any, attrs: dict[str, Any] | None = None, renderer: Any | None = None) -> SafeString: ... + # Return value type depends on widget data + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> Any: ... + +class BaseCSVWidget(forms.Widget): + # Can be widget class or instance - __init__ converts to instance via instantiation or deepcopy + surrogate: type[Any] = ... + + # CSV widget data can contain any types + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> list[str]: ... + # Widget value and renderer can be any type + def render(self, name: str, value: Any, attrs: dict[str, Any] | None = None, renderer: Any | None = None) -> SafeString: ... + +class CSVWidget(BaseCSVWidget, forms.TextInput): ... + +class QueryArrayWidget(BaseCSVWidget, forms.TextInput): + # Query array widget data can contain any types + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> list[str]: ... diff --git a/stubs/django-import-export/METADATA.toml b/stubs/django-import-export/METADATA.toml new file mode 100644 index 000000000000..9452959702c8 --- /dev/null +++ b/stubs/django-import-export/METADATA.toml @@ -0,0 +1,6 @@ +version = "4.4.*" +upstream-repository = "https://github.com/django-import-export/django-import-export" +dependencies = ["django-stubs"] # Add tablib when typed, and update _Incomplete aliases in stubs + +[tool.stubtest] +skip = true # Django requires configured settings at runtime diff --git a/stubs/Pillow/PIL/_version.pyi b/stubs/django-import-export/import_export/__init__.pyi similarity index 100% rename from stubs/Pillow/PIL/_version.pyi rename to stubs/django-import-export/import_export/__init__.pyi diff --git a/stubs/django-import-export/import_export/admin.pyi b/stubs/django-import-export/import_export/admin.pyi new file mode 100644 index 000000000000..8480deb8ff67 --- /dev/null +++ b/stubs/django-import-export/import_export/admin.pyi @@ -0,0 +1,109 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Any, Literal, TypeAlias, TypeVar +from typing_extensions import deprecated + +from django.contrib import admin +from django.contrib.admin.helpers import ActionForm +from django.core.files import File +from django.db.models import Model, QuerySet +from django.forms import Form +from django.http.request import HttpRequest +from django.http.response import HttpResponse +from django.template.response import TemplateResponse +from django.urls import URLPattern + +from .formats.base_formats import Format +from .mixins import BaseExportMixin, BaseImportMixin +from .results import Result +from .tmp_storages import BaseStorage + +Dataset: TypeAlias = Incomplete # tablib.Dataset +logger: Logger + +_ModelT = TypeVar("_ModelT", bound=Model) + +class ImportExportMixinBase: + base_change_list_template: str + change_list_template: str + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def init_change_list_template(self) -> None: ... + def get_model_info(self) -> tuple[str, str]: ... + def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse: ... + +class ImportMixin(BaseImportMixin[_ModelT], ImportExportMixinBase): + import_export_change_list_template: str + import_template_name: str + import_form_class: type[Form] = ... + confirm_form_class: type[Form] = ... + from_encoding: str + import_error_display: Sequence[Literal["message", "row", "traceback"]] + skip_admin_log: bool | None + tmp_storage_class: str | type[BaseStorage] + def get_skip_admin_log(self) -> bool: ... + def get_tmp_storage_class(self) -> type[BaseStorage]: ... + def get_tmp_storage_class_kwargs(self) -> dict[str, Any]: ... + def has_import_permission(self, request: HttpRequest) -> bool: ... + def get_urls(self) -> list[URLPattern]: ... + def process_import(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: ... + def process_dataset(self, dataset: Dataset, form: Form, request: HttpRequest, **kwargs: Any) -> Result: ... + def process_result(self, result: Result, request: HttpRequest) -> HttpResponse: ... + def generate_log_entries(self, result: Result, request: HttpRequest) -> None: ... + def add_success_message(self, result: Result, request: HttpRequest) -> None: ... + def get_import_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def create_import_form(self, request: HttpRequest) -> Form: ... + def get_import_form_class(self, request: HttpRequest) -> type[Form]: ... + def get_import_form_kwargs(self, request: HttpRequest) -> dict[str, Any]: ... + def get_import_form_initial(self, request: HttpRequest) -> dict[str, Any]: ... + def create_confirm_form(self, request: HttpRequest, import_form: Form | None = None) -> Form: ... + def get_confirm_form_class(self, request: HttpRequest) -> type[Form]: ... + def get_confirm_form_kwargs(self, request: HttpRequest, import_form: Form | None = None) -> dict[str, Any]: ... + def get_confirm_form_initial(self, request: HttpRequest, import_form: Form | None) -> dict[str, Any]: ... + def get_import_data_kwargs(self, **kwargs: Any) -> dict[str, Any]: ... + def write_to_tmp_storage(self, import_file: File[bytes], input_format: Format) -> BaseStorage: ... + def add_data_read_fail_error_to_form(self, form: Form, e: Exception) -> None: ... + def import_action(self, request: HttpRequest, **kwargs: Any) -> TemplateResponse: ... + def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse: ... + +class ExportMixin(BaseExportMixin[_ModelT], ImportExportMixinBase): + import_export_change_list_template: str + export_template_name: str + to_encoding: str | None + export_form_class: type[Form] = ... + def get_urls(self) -> list[URLPattern]: ... + def has_export_permission(self, request: HttpRequest) -> bool: ... + def get_export_queryset(self, request: HttpRequest) -> QuerySet[_ModelT]: ... + def get_export_data( + self, file_format: Format, request: HttpRequest, queryset: QuerySet[_ModelT], **kwargs: Any + ) -> str | bytes: ... + def get_export_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_export_form_class(self) -> type[Form]: ... + def export_action(self, request: HttpRequest) -> TemplateResponse: ... + @deprecated( + "The 'get_valid_export_item_pks()' method is deprecated and will be removed in a future release. " + "Overwrite 'get_queryset()' or 'get_export_queryset()' instead." + ) + def get_valid_export_item_pks(self, request: HttpRequest) -> list[str]: ... + def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse: ... + def get_export_filename(self, request: HttpRequest, queryset: QuerySet[_ModelT], file_format: Format) -> str: ... # type: ignore[override] + def init_request_context_data(self, request: HttpRequest, form: Form) -> dict[str, Any]: ... + +class ImportExportMixin(ImportMixin[_ModelT], ExportMixin[_ModelT]): ... +class ImportExportModelAdmin(ImportExportMixin[_ModelT], admin.ModelAdmin[_ModelT]): ... # type: ignore[misc] + +class ExportActionMixin(ExportMixin[_ModelT]): + change_form_template: str + show_change_form_export: bool + action_form: type[ActionForm] + def change_view( + self, request: HttpRequest, object_id: str, form_url: str = "", extra_context: dict[str, Any] | None = None + ) -> HttpResponse: ... + def response_change(self, request: HttpRequest, obj: _ModelT) -> HttpResponse: ... + def export_admin_action(self, request: HttpRequest, queryset: QuerySet[_ModelT]) -> HttpResponse: ... + def get_actions(self, request: HttpRequest) -> dict[str, tuple[Callable[..., str], str, str] | None]: ... + +class ExportActionModelAdmin(ExportActionMixin[_ModelT], admin.ModelAdmin[_ModelT]): ... # type: ignore[misc] # pyrefly: ignore[inconsistent-inheritance] +class ImportExportActionModelAdmin(ImportMixin[_ModelT], ExportActionModelAdmin[_ModelT]): ... # type: ignore[misc] diff --git a/stubs/django-import-export/import_export/command_utils.pyi b/stubs/django-import-export/import_export/command_utils.pyi new file mode 100644 index 000000000000..a3c1fb5e4236 --- /dev/null +++ b/stubs/django-import-export/import_export/command_utils.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrPath +from typing import Any + +from .formats.base_formats import Format +from .resources import ModelResource + +def get_resource_class(model_or_resource_class: str) -> ModelResource[Any]: ... + +MIME_TYPE_FORMAT_MAPPING: dict[str, type[Format]] + +def get_format_class(format_name: str, file_name: StrPath, encoding: str | None = None) -> Format: ... +def get_default_format_names() -> str: ... diff --git a/stubs/django-import-export/import_export/declarative.pyi b/stubs/django-import-export/import_export/declarative.pyi new file mode 100644 index 000000000000..e0c723239488 --- /dev/null +++ b/stubs/django-import-export/import_export/declarative.pyi @@ -0,0 +1,11 @@ +import _typeshed +from logging import Logger +from typing import Any + +logger: Logger + +class DeclarativeMetaclass(type): + def __new__(cls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], attrs: dict[str, Any]) -> _typeshed.Self: ... + +class ModelDeclarativeMetaclass(DeclarativeMetaclass): + def __new__(cls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], attrs: dict[str, Any]) -> _typeshed.Self: ... diff --git a/stubs/django-import-export/import_export/exceptions.pyi b/stubs/django-import-export/import_export/exceptions.pyi new file mode 100644 index 000000000000..3f6b99db52d9 --- /dev/null +++ b/stubs/django-import-export/import_export/exceptions.pyi @@ -0,0 +1,11 @@ +from typing import Any + +class ImportExportError(Exception): ... +class FieldError(ImportExportError): ... +class WidgetError(ImportExportError): ... + +class ImportError(ImportExportError): + error: Exception + number: int | None + row: dict[str, Any] | None + def __init__(self, error: Exception, number: int | None = None, row: dict[str, Any] | None = None) -> None: ... diff --git a/stubs/django-import-export/import_export/fields.pyi b/stubs/django-import-export/import_export/fields.pyi new file mode 100644 index 000000000000..d17fb1d7e2eb --- /dev/null +++ b/stubs/django-import-export/import_export/fields.pyi @@ -0,0 +1,34 @@ +from collections.abc import Callable, Mapping +from typing import Any, ClassVar + +from django.db.models import Model +from django.db.models.fields import NOT_PROVIDED + +from .widgets import Widget + +class Field: + empty_values: ClassVar[list[str | None]] + attribute: str | None + default: type[NOT_PROVIDED] | Callable[[], Any] | Any + column_name: str | None + widget: Widget + readonly: bool + saves_null_values: bool + dehydrate_method: str + m2m_add: bool + def __init__( + self, + attribute: str | None = None, + column_name: str | None = None, + widget: Widget | None = None, + default: type[NOT_PROVIDED] | Callable[[], Any] | Any = ..., + readonly: bool = False, + saves_null_values: bool = True, + dehydrate_method: str | None = None, + m2m_add: bool = False, + ) -> None: ... + def clean(self, row: Mapping[str, Any], **kwargs: Any) -> Any: ... + def get_value(self, instance: Model) -> Any: ... + def save(self, instance: Model, row: Mapping[str, Any], is_m2m: bool = False, **kwargs: Any) -> None: ... + def export(self, instance: Model, **kwargs: Any) -> str: ... + def get_dehydrate_method(self, field_name: str | None = None) -> str: ... diff --git a/stubs/selenium/selenium/webdriver/edge/__init__.pyi b/stubs/django-import-export/import_export/formats/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/edge/__init__.pyi rename to stubs/django-import-export/import_export/formats/__init__.pyi diff --git a/stubs/django-import-export/import_export/formats/base_formats.pyi b/stubs/django-import-export/import_export/formats/base_formats.pyi new file mode 100644 index 000000000000..17c7f4a60ad4 --- /dev/null +++ b/stubs/django-import-export/import_export/formats/base_formats.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete, ReadableBuffer +from logging import Logger +from typing import IO, Any, ClassVar, TypeAlias +from typing_extensions import Self + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +logger: Logger + +class Format: + def get_title(self) -> type[Self]: ... + def create_dataset(self, in_stream: str | bytes | IO[Any]) -> Dataset: ... + def export_data(self, dataset: Dataset, **kwargs: Any) -> Any: ... + def is_binary(self) -> bool: ... + def get_read_mode(self) -> str: ... + def get_extension(self) -> str: ... + def get_content_type(self) -> str: ... + @classmethod + def is_available(cls) -> bool: ... + def can_import(self) -> bool: ... + def can_export(self) -> bool: ... + +class TablibFormat(Format): + TABLIB_MODULE: ClassVar[str] + CONTENT_TYPE: ClassVar[str] + encoding: str | None + def __init__(self, encoding: str | None = None) -> None: ... + def get_format(self) -> type[Any]: ... + def get_title(self) -> str: ... # type: ignore[override] + def create_dataset(self, in_stream: str | bytes | IO[Any], **kwargs: Any) -> Dataset: ... # type: ignore[override] + +class TextFormat(TablibFormat): ... + +class CSV(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class JSON(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class YAML(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class TSV(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class ODS(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> bytes: ... + +class HTML(TextFormat): ... + +class XLS(TablibFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> bytes: ... + def create_dataset(self, in_stream: bytes) -> Dataset: ... # type: ignore[override] + +class XLSX(TablibFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> bytes: ... + def create_dataset(self, in_stream: ReadableBuffer) -> Dataset: ... # type: ignore[override] + +DEFAULT_FORMATS: list[type[Format]] +BINARY_FORMATS: list[type[Format]] diff --git a/stubs/django-import-export/import_export/forms.pyi b/stubs/django-import-export/import_export/forms.pyi new file mode 100644 index 000000000000..910554c49bbb --- /dev/null +++ b/stubs/django-import-export/import_export/forms.pyi @@ -0,0 +1,38 @@ +from collections.abc import Iterable, Sequence +from typing import Any + +from django import forms + +from .formats.base_formats import Format +from .resources import ModelResource, Resource + +class ImportExportFormBase(forms.Form): + resource: forms.ChoiceField + format: forms.ChoiceField + def __init__( + self, formats: list[type[Format]], resources: list[type[Resource[Any]]] | None = None, **kwargs: Any + ) -> None: ... + +class ImportForm(ImportExportFormBase): + import_file: forms.FileField + field_order: Sequence[str] + @property + def media(self) -> forms.Media: ... + +class ConfirmImportForm(forms.Form): + import_file_name: forms.CharField + original_file_name: forms.CharField + resource: forms.CharField + def clean_import_file_name(self) -> str: ... + +class ExportForm(ImportExportFormBase): + export_items: forms.MultipleChoiceField + +class SelectableFieldsExportForm(ExportForm): + resources: Iterable[ModelResource[Any]] + is_selectable_fields_form: bool + resource_fields: dict[str, list[str]] + @staticmethod + def create_boolean_field_name(resource: ModelResource[Any], field_name: str) -> str: ... + def get_selected_resource(self) -> ModelResource[Any]: ... + def get_selected_resource_export_fields(self) -> list[str]: ... diff --git a/stubs/django-import-export/import_export/instance_loaders.pyi b/stubs/django-import-export/import_export/instance_loaders.pyi new file mode 100644 index 000000000000..e2840f83aba9 --- /dev/null +++ b/stubs/django-import-export/import_export/instance_loaders.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Any, TypeAlias + +from django.db.models import Model, QuerySet + +from .fields import Field +from .resources import Resource + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +class BaseInstanceLoader: + resource: Resource[Any] + dataset: Dataset | None + def __init__(self, resource: Resource[Any], dataset: Dataset | None = None) -> None: ... + def get_instance(self, row: dict[str, Any]) -> Model | None: ... + +class ModelInstanceLoader(BaseInstanceLoader): + def get_queryset(self) -> QuerySet[Any]: ... + +class CachedInstanceLoader(ModelInstanceLoader): + pk_field: Field + all_instances: dict[Any, Model] diff --git a/stubs/django-import-export/import_export/mixins.pyi b/stubs/django-import-export/import_export/mixins.pyi new file mode 100644 index 000000000000..7c5bd003e4f5 --- /dev/null +++ b/stubs/django-import-export/import_export/mixins.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete, SupportsGetItem +from logging import Logger +from typing import Any, Generic, TypeAlias, TypeVar +from typing_extensions import deprecated + +from django.db.models import Model, QuerySet +from django.forms import BaseForm, Form +from django.http.request import HttpRequest +from django.http.response import HttpResponse +from django.views.generic.edit import FormView + +from .formats.base_formats import Format +from .resources import Resource + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +logger: Logger + +_ModelT = TypeVar("_ModelT", bound=Model) + +class BaseImportExportMixin(Generic[_ModelT]): + resource_classes: SupportsGetItem[int, type[Resource[_ModelT]]] + @property + def formats(self) -> list[type[Format]]: ... + @property + def export_formats(self) -> list[type[Format]]: ... + @property + def import_formats(self) -> list[type[Format]]: ... + def check_resource_classes(self, resource_classes: SupportsGetItem[int, type[Resource[_ModelT]]]) -> None: ... + def get_resource_classes(self, request: HttpRequest) -> list[type[Resource[_ModelT]]]: ... + def get_resource_kwargs(self, request: HttpRequest, *args: Any, **kwargs: Any) -> dict[str, Any]: ... + def get_resource_index(self, form: Form) -> int: ... + +class BaseImportMixin(BaseImportExportMixin[_ModelT]): + skip_import_confirm: bool + def get_import_resource_classes(self, request: HttpRequest) -> list[type[Resource[_ModelT]]]: ... + def get_import_formats(self) -> list[Format]: ... + def get_import_resource_kwargs(self, request: HttpRequest, **kwargs: Any) -> dict[str, Any]: ... + def choose_import_resource_class(self, form: Form, request: HttpRequest) -> type[Resource[_ModelT]]: ... + def is_skip_import_confirm_enabled(self) -> bool: ... + +class BaseExportMixin(BaseImportExportMixin[_ModelT]): + model: Model + skip_export_form: bool + skip_export_form_from_action: bool + def get_export_formats(self) -> list[Format]: ... + def get_export_resource_classes(self, request: HttpRequest) -> list[Resource[_ModelT]]: ... + def choose_export_resource_class(self, form: Form, request: HttpRequest) -> Resource[_ModelT]: ... + def get_export_resource_kwargs(self, request: HttpRequest, **kwargs: Any) -> dict[str, Any]: ... + def get_data_for_export(self, request: HttpRequest, queryset: QuerySet[_ModelT], **kwargs: Any) -> Dataset: ... + def get_export_filename(self, file_format: Format) -> str: ... + def is_skip_export_form_enabled(self) -> bool: ... + def is_skip_export_form_from_action_enabled(self) -> bool: ... + +class ExportViewMixin(BaseExportMixin[_ModelT]): + form_class: type[BaseForm] = ... + def get_export_data(self, file_format: Format, queryset: QuerySet[_ModelT], **kwargs: Any) -> str | bytes: ... + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_form_kwargs(self) -> dict[str, Any]: ... + +_FormT = TypeVar("_FormT", bound=BaseForm) + +@deprecated("ExportViewFormMixin is deprecated and will be removed in a future release.") +class ExportViewFormMixin(ExportViewMixin[_ModelT], FormView[_FormT]): # type: ignore[misc] + def form_valid(self, form: _FormT) -> HttpResponse: ... diff --git a/stubs/django-import-export/import_export/options.pyi b/stubs/django-import-export/import_export/options.pyi new file mode 100644 index 000000000000..6ddc523acc85 --- /dev/null +++ b/stubs/django-import-export/import_export/options.pyi @@ -0,0 +1,32 @@ +from collections.abc import Sequence +from typing import Any, Generic, TypeVar + +from django.db.models import Model + +from .instance_loaders import BaseInstanceLoader + +_ModelT = TypeVar("_ModelT", bound=Model) + +class ResourceOptions(Generic[_ModelT]): + model: _ModelT | str + fields: Sequence[str] | None + exclude: Sequence[str] | None + instance_loader_class: type[BaseInstanceLoader] | None + import_id_fields: Sequence[str] + export_order: Sequence[str] | None + import_order: Sequence[str] | None + widgets: dict[str, Any] | None + use_transactions: bool | None + skip_unchanged: bool + report_skipped: bool + clean_model_instances: bool + chunk_size: int | None + skip_diff: bool + skip_html_diff: bool + use_bulk: bool + batch_size: int + force_init_instance: bool + using_db: str | None + store_row_values: bool + store_instance: bool + use_natural_foreign_keys: bool diff --git a/stubs/django-import-export/import_export/resources.pyi b/stubs/django-import-export/import_export/resources.pyi new file mode 100644 index 000000000000..4f1c75dac782 --- /dev/null +++ b/stubs/django-import-export/import_export/resources.pyi @@ -0,0 +1,170 @@ +import _typeshed +from collections import OrderedDict +from collections.abc import Iterator, Sequence +from functools import partial +from logging import Logger +from typing import Any, ClassVar, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Never, deprecated + +from django.db.models import Field as DjangoField, Model, QuerySet +from django.utils.safestring import SafeString + +from .declarative import DeclarativeMetaclass, ModelDeclarativeMetaclass +from .fields import Field +from .instance_loaders import BaseInstanceLoader +from .options import ResourceOptions +from .results import Error, Result, RowResult +from .widgets import ForeignKeyWidget, ManyToManyWidget, Widget + +Dataset: TypeAlias = _typeshed.Incomplete # tablib.Dataset +logger: Logger + +def has_natural_foreign_key(model: Model) -> bool: ... + +class Diff: + left: list[str] + right: list[str] + new: bool + def __init__(self, resource: Resource[_ModelT], instance: _ModelT, new: bool) -> None: ... + def compare_with(self, resource: Resource[_ModelT], instance: _ModelT, dry_run: bool = False) -> None: ... + def as_html(self) -> list[SafeString]: ... + +_ModelT = TypeVar("_ModelT", bound=Model) + +class Resource(Generic[_ModelT], metaclass=DeclarativeMetaclass): + _meta: ResourceOptions[_ModelT] + fields: OrderedDict[str, Field] + create_instances: list[_ModelT] + update_instances: list[_ModelT] + delete_instances: list[_ModelT] + def __init__(self, **kwargs: Any) -> None: ... + @classmethod + def get_result_class(self) -> type[Result]: ... + @classmethod + def get_row_result_class(self) -> type[RowResult]: ... + @classmethod + def get_error_result_class(self) -> type[Error]: ... + @classmethod + def get_diff_class(self) -> type[Diff]: ... + @classmethod + def get_db_connection_name(self) -> str: ... + def get_use_transactions(self) -> bool: ... + def get_chunk_size(self) -> int: ... + @deprecated("The 'get_fields()' method is deprecated and will be removed in a future release.") + def get_fields(self, **kwargs: Any) -> list[Field]: ... + def get_field_name(self, field: Field) -> str: ... + def init_instance(self, row: dict[str, Any] | None = None) -> _ModelT: ... + def get_instance(self, instance_loader: BaseInstanceLoader, row: dict[str, Any]) -> _ModelT | None: ... + def get_or_init_instance(self, instance_loader: BaseInstanceLoader, row: dict[str, Any]) -> tuple[_ModelT | None, bool]: ... + def get_import_id_fields(self) -> Sequence[str]: ... + def get_bulk_update_fields(self) -> list[str]: ... + def bulk_create( + self, + using_transactions: bool, + dry_run: bool, + raise_errors: bool, + batch_size: int | None = None, + result: Result | None = None, + ) -> None: ... + def bulk_update( + self, + using_transactions: bool, + dry_run: bool, + raise_errors: bool, + batch_size: int | None = None, + result: Result | None = None, + ) -> None: ... + def bulk_delete(self, using_transactions: bool, dry_run: bool, raise_errors: bool, result: Result | None = None) -> None: ... + def validate_instance( + self, instance: _ModelT, import_validation_errors: dict[str, Any] | None = None, validate_unique: bool = True + ) -> None: ... + # For all the definitions below (from `save_instance()` to `import_row()`), `**kwargs` should contain: + # dry_run: bool, use_transactions: bool, row_number: int, retain_instance_in_row_result: bool. + # Users are free to pass extra arguments in `import_data()`so PEP 728 can probably be leveraged here. + def save_instance(self, instance: _ModelT, is_create: bool, row: dict[str, Any], **kwargs: Any) -> None: ... + def do_instance_save(self, instance: _ModelT) -> None: ... + def before_save_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def after_save_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def delete_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def before_delete_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def after_delete_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def import_field(self, field: Field, instance: _ModelT, row: dict[str, Any], is_m2m: bool = False, **kwargs: Any) -> None: ... + def get_import_fields(self) -> list[Field]: ... + def import_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def save_m2m(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def for_delete(self, row: dict[str, Any], instance: _ModelT) -> bool: ... + def skip_row( + self, instance: _ModelT, original: _ModelT, row: dict[str, Any], import_validation_errors: dict[str, Any] | None = None + ) -> bool: ... + def get_diff_headers(self) -> list[str]: ... + def before_import(self, dataset: Dataset, **kwargs: Any) -> None: ... + def after_import(self, dataset: Dataset, result: Result, **kwargs: Any) -> None: ... + def before_import_row(self, row: dict[str, Any], **kwargs: Any) -> None: ... + def after_import_row(self, row: dict[str, Any], row_result: RowResult, **kwargs: Any) -> None: ... + def after_init_instance(self, instance: _ModelT, new: bool, row: dict[str, Any], **kwargs: Any) -> None: ... + + @overload + def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[True]) -> Never: ... + @overload + def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[False] = False) -> None: ... + + def import_row(self, row: dict[str, Any], instance_loader: BaseInstanceLoader, **kwargs: Any) -> RowResult: ... + def import_data( + self, + dataset: Dataset, + dry_run: bool = False, + raise_errors: bool = False, + use_transactions: bool | None = None, + collect_failed_rows: bool = False, + rollback_on_validation_errors: bool = False, + **kwargs: Any, + ) -> Result: ... + def import_data_inner( + self, + dataset: Dataset, + dry_run: bool, + raise_errors: bool, + using_transactions: bool, + collect_failed_rows: bool, + **kwargs: Any, + ) -> Result: ... + def get_import_order(self) -> tuple[str, ...]: ... + def get_export_order(self) -> tuple[str, ...]: ... + def before_export(self, queryset: QuerySet[_ModelT], **kwargs: Any) -> None: ... + def after_export(self, queryset: QuerySet[_ModelT], dataset: Dataset, **kwargs: Any) -> None: ... + def filter_export(self, queryset: QuerySet[_ModelT], **kwargs: Any) -> QuerySet[_ModelT]: ... + def export_field(self, field: Field, instance: _ModelT, **kwargs: Any) -> str: ... + def get_export_fields(self, selected_fields: Sequence[str] | None = None) -> list[Field]: ... + def export_resource(self, instance: _ModelT, selected_fields: Sequence[str] | None = None, **kwargs: Any) -> list[str]: ... + def get_export_headers(self, selected_fields: Sequence[str] | None = None) -> list[str]: ... + def get_user_visible_headers(self) -> list[str]: ... + def get_user_visible_fields(self) -> list[str]: ... + def iter_queryset(self, queryset: QuerySet[_ModelT]) -> Iterator[_ModelT]: ... + def export(self, queryset: QuerySet[_ModelT] | None = None, **kwargs: Any) -> Dataset: ... + +class ModelResource(Resource[_ModelT], metaclass=ModelDeclarativeMetaclass): + DEFAULT_RESOURCE_FIELD: ClassVar[type[Field]] = ... + WIDGETS_MAP: ClassVar[dict[str, type[Widget]]] + @classmethod + def get_m2m_widget(cls, field: DjangoField[Any, Any]) -> partial[ManyToManyWidget[Any]]: ... + @classmethod + def get_fk_widget(cls, field: DjangoField[Any, Any]) -> partial[ForeignKeyWidget[Any]]: ... + @classmethod + def widget_from_django_field(cls, f: DjangoField[Any, Any], default: type[Widget] = ...) -> type[Widget]: ... + @classmethod + def widget_kwargs_for_field(cls, field_name: str, django_field: DjangoField[Any, Any]) -> dict[str, Any]: ... + @classmethod + def field_from_django_field(cls, field_name: str, django_field: DjangoField[Any, Any], readonly: bool) -> Field: ... + def get_queryset(self) -> QuerySet[_ModelT]: ... + def init_instance(self, row: dict[str, Any] | None = None) -> _ModelT: ... + def after_import(self, dataset: Dataset, result: Result, **kwargs: Any) -> None: ... + @classmethod + def get_display_name(cls) -> str: ... + +_ResourceT = TypeVar("_ResourceT", bound=Resource[Any]) + +# HK Type Vars could help type the first overload: +@overload +def modelresource_factory(model: Model, resource_class: type[_ResourceT]) -> _ResourceT: ... +@overload +def modelresource_factory(model: _ModelT) -> ModelResource[_ModelT]: ... diff --git a/stubs/django-import-export/import_export/results.pyi b/stubs/django-import-export/import_export/results.pyi new file mode 100644 index 000000000000..5d108fbf6d4e --- /dev/null +++ b/stubs/django-import-export/import_export/results.pyi @@ -0,0 +1,88 @@ +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Iterator +from functools import cached_property +from typing import Any, ClassVar, Literal, TypeAlias + +from django.core.exceptions import ValidationError +from django.db.models import Model + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +class Error: + error: Exception + row: dict[str, Any] + number: int | None + def __init__(self, error: Exception, row: dict[str, Any] | None = None, number: int | None = None) -> None: ... + @cached_property + def traceback(self) -> str: ... + +_ImportType: TypeAlias = Literal["update", "new", "delete", "skip", "error", "invalid"] + +class RowResult: + IMPORT_TYPE_UPDATE: ClassVar[Literal["update"]] + IMPORT_TYPE_NEW: ClassVar[Literal["new"]] + IMPORT_TYPE_DELETE: ClassVar[Literal["delete"]] + IMPORT_TYPE_SKIP: ClassVar[Literal["skip"]] + IMPORT_TYPE_ERROR: ClassVar[Literal["error"]] + IMPORT_TYPE_INVALID: ClassVar[Literal["invalid"]] + valid_import_types: frozenset[_ImportType] + errors: list[Error] + validation_error: ValidationError | None + diff: list[str] | None + import_type: _ImportType + row_values: dict[str, Any] + object_id: Any | None + object_repr: str | None + instance: Model + original: Model + def __init__(self) -> None: ... + def add_instance_info(self, instance: Model) -> None: ... + def is_update(self) -> bool: ... + def is_new(self) -> bool: ... + def is_delete(self) -> bool: ... + def is_skip(self) -> bool: ... + def is_error(self) -> bool: ... + def is_invalid(self) -> bool: ... + def is_valid(self) -> bool: ... + +class ErrorRow: + number: int + errors: list[Error] + def __init__(self, number: int, errors: list[Error]) -> None: ... + +class InvalidRow: + number: int + error: ValidationError + values: tuple[Any, ...] + error_dict: dict[str, list[str]] + def __init__(self, number: int, validation_error: ValidationError, values: tuple[Any, ...]) -> None: ... + @property + def field_specific_errors(self) -> dict[str, list[str]]: ... + @property + def non_field_specific_errors(self) -> list[str]: ... + @property + def error_count(self) -> int: ... + +class Result: + base_errors: list[Error] + diff_headers: list[str] + rows: list[RowResult] + invalid_rows: list[InvalidRow] + error_rows: list[ErrorRow] + failed_dataset: Dataset + totals: OrderedDict[_ImportType, int] + total_rows: int + def __init__(self) -> None: ... + def valid_rows(self) -> list[RowResult]: ... + def append_row_result(self, row_result: RowResult) -> None: ... + def append_base_error(self, error: Error) -> None: ... + def add_dataset_headers(self, headers: list[str] | None) -> None: ... + def append_failed_row(self, row: dict[str, Any], error: Exception) -> None: ... + def append_invalid_row(self, number: int, row: dict[str, Any], validation_error: ValidationError) -> None: ... + def append_error_row(self, number: int, row: dict[str, Any], errors: list[Error]) -> None: ... + def increment_row_result_total(self, row_result: RowResult) -> None: ... + def row_errors(self) -> list[tuple[int, Any]]: ... + def has_errors(self) -> bool: ... + def has_validation_errors(self) -> bool: ... + def __iter__(self) -> Iterator[RowResult]: ... diff --git a/stubs/django-import-export/import_export/signals.pyi b/stubs/django-import-export/import_export/signals.pyi new file mode 100644 index 000000000000..7d32df82f840 --- /dev/null +++ b/stubs/django-import-export/import_export/signals.pyi @@ -0,0 +1,4 @@ +from django.dispatch import Signal + +post_export: Signal +post_import: Signal diff --git a/stubs/selenium/selenium/webdriver/firefox/__init__.pyi b/stubs/django-import-export/import_export/templatetags/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/firefox/__init__.pyi rename to stubs/django-import-export/import_export/templatetags/__init__.pyi diff --git a/stubs/django-import-export/import_export/templatetags/import_export_tags.pyi b/stubs/django-import-export/import_export/templatetags/import_export_tags.pyi new file mode 100644 index 000000000000..9d6c0e4d7f68 --- /dev/null +++ b/stubs/django-import-export/import_export/templatetags/import_export_tags.pyi @@ -0,0 +1,8 @@ +from typing_extensions import LiteralString + +from django.template import Library + +register: Library + +@register.simple_tag +def compare_values(value1: str, value2: str) -> LiteralString: ... diff --git a/stubs/django-import-export/import_export/tmp_storages.pyi b/stubs/django-import-export/import_export/tmp_storages.pyi new file mode 100644 index 000000000000..eda138ffda97 --- /dev/null +++ b/stubs/django-import-export/import_export/tmp_storages.pyi @@ -0,0 +1,34 @@ +from abc import abstractmethod +from typing import IO, Any, ClassVar + +class BaseStorage: + name: str | None + read_mode: str + encoding: str | None + def __init__(self, *, name: str | None = None, read_mode: str = "", encoding: str | None = None) -> None: ... + @abstractmethod + def save(self, data: Any) -> None: ... + @abstractmethod + def read(self) -> Any: ... # `Any` because `read` returns things from `save` + @abstractmethod + def remove(self) -> None: ... + +class TempFolderStorage(BaseStorage): + def save(self, data: Any) -> None: ... + def read(self) -> Any: ... + def remove(self) -> None: ... + def get_full_path(self) -> str: ... + +class CacheStorage(BaseStorage): + CACHE_LIFETIME: int + CACHE_PREFIX: str + def save(self, data: Any) -> None: ... + def read(self) -> Any: ... + def remove(self) -> None: ... + +class MediaStorage(BaseStorage): + MEDIA_FOLDER: ClassVar[str] + def save(self, data: IO[Any]) -> None: ... + def read(self) -> Any: ... + def remove(self) -> None: ... + def get_full_path(self) -> str: ... diff --git a/stubs/django-import-export/import_export/utils.pyi b/stubs/django-import-export/import_export/utils.pyi new file mode 100644 index 000000000000..d4b968a3f3f7 --- /dev/null +++ b/stubs/django-import-export/import_export/utils.pyi @@ -0,0 +1,19 @@ +from types import TracebackType +from typing import Any, overload + +from django.db.models import Field as DjangoField, ForeignObjectRel, Model +from django.db.transaction import Atomic + +class atomic_if_using_transaction: + using_transactions: bool + context_manager: Atomic + def __init__(self, using_transactions: bool, using: str | None) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +@overload +def get_related_model(field: ForeignObjectRel) -> Model: ... +@overload +def get_related_model(field: DjangoField[Any, Any]) -> Model | None: ... diff --git a/stubs/django-import-export/import_export/widgets.pyi b/stubs/django-import-export/import_export/widgets.pyi new file mode 100644 index 000000000000..1939cad05f1f --- /dev/null +++ b/stubs/django-import-export/import_export/widgets.pyi @@ -0,0 +1,91 @@ +from collections.abc import Mapping +from datetime import datetime +from typing import Any, ClassVar, Generic, TypeVar, overload +from typing_extensions import deprecated + +from django.db.models import Model, QuerySet + +def format_datetime(value: datetime, datetime_format: str) -> str: ... + +class Widget: + coerce_to_string: bool + def __init__(self, coerce_to_string: bool = True) -> None: ... + def clean(self, value: Any, row: Mapping[str, Any] | None = None, **kwargs: Any) -> Any: ... + + @overload + @deprecated("The 'obj' parameter is deprecated and will be removed in a future release.") + def render(self, value: Any, obj: Model, **kwargs: Any) -> Any: ... + @overload + def render(self, value: Any, obj: None = None, **kwargs: Any) -> Any: ... + +class NumberWidget(Widget): + def is_empty(self, value: Any) -> bool: ... + +class FloatWidget(NumberWidget): ... +class IntegerWidget(NumberWidget): ... +class DecimalWidget(NumberWidget): ... + +class CharWidget(Widget): + allow_blank: bool + def __init__(self, coerce_to_string: bool = True, allow_blank: bool = True) -> None: ... + +class BooleanWidget(Widget): + TRUE_VALUES: ClassVar[list[str | int | bool]] + FALSE_VALUES: ClassVar[list[str | int | bool]] + NULL_VALUES: ClassVar[list[str | None]] + def __init__(self, coerce_to_string: bool = True) -> None: ... + +class DateWidget(Widget): + formats: tuple[str, ...] + def __init__(self, format: str | None = None, coerce_to_string: bool = True) -> None: ... + +class DateTimeWidget(Widget): + formats: tuple[str, ...] + def __init__(self, format: str | None = None, coerce_to_string: bool = True) -> None: ... + +class TimeWidget(Widget): + formats: tuple[str, ...] + def __init__(self, format: str | None = None, coerce_to_string: bool = True) -> None: ... + +class DurationWidget(Widget): ... + +class SimpleArrayWidget(Widget): + separator: str + def __init__(self, separator: str | None = None, coerce_to_string: bool = True) -> None: ... + +class JSONWidget(Widget): ... + +_ModelT = TypeVar("_ModelT", bound=Model) + +class ForeignKeyWidget(Widget, Generic[_ModelT]): + model: type[_ModelT] + field: str + key_is_id: bool + use_natural_foreign_keys: bool + def __init__( + self, + model: type[_ModelT], + field: str = "pk", + use_natural_foreign_keys: bool = False, + key_is_id: bool = False, + **kwargs: Any, + ) -> None: ... + def get_queryset(self, value: Any, row: Mapping[str, Any], *args: Any, **kwargs: Any) -> QuerySet[_ModelT]: ... + def get_instance_by_natural_key(self, value: str | bytes | bytearray) -> _ModelT: ... + def get_instance_by_lookup_fields(self, value: Any, row: Mapping[str, Any], **kwargs: Any) -> _ModelT: ... + def get_lookup_kwargs(self, value: Any, row: Mapping[str, Any] | None = None, **kwargs: Any) -> dict[str, Any]: ... + +class _CachedQuerySetWrapper(Generic[_ModelT]): + queryset: QuerySet[_ModelT] + model: type[_ModelT] + def __init__(self, queryset: QuerySet[_ModelT]) -> None: ... + def get(self, **lookup_fields: Any) -> _ModelT: ... # instance can have different fields + +class CachedForeignKeyWidget(ForeignKeyWidget[_ModelT]): + def get_instance_by_lookup_fields(self, value: Any, row: Mapping[str, Any], **kwargs: Any) -> _ModelT: ... + +class ManyToManyWidget(Widget, Generic[_ModelT]): + model: _ModelT + separator: str + field: str + def __init__(self, model: _ModelT, separator: str | None = None, field: str | None = None, **kwargs: Any) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/ie/__init__.pyi b/stubs/django-import-export/management/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/ie/__init__.pyi rename to stubs/django-import-export/management/__init__.pyi diff --git a/stubs/selenium/selenium/webdriver/opera/__init__.pyi b/stubs/django-import-export/management/commands/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/opera/__init__.pyi rename to stubs/django-import-export/management/commands/__init__.pyi diff --git a/stubs/django-import-export/management/commands/export.pyi b/stubs/django-import-export/management/commands/export.pyi new file mode 100644 index 000000000000..8d75fb4d613f --- /dev/null +++ b/stubs/django-import-export/management/commands/export.pyi @@ -0,0 +1,3 @@ +from django.core.management.base import BaseCommand + +class Command(BaseCommand): ... diff --git a/stubs/django-import-export/management/commands/import.pyi b/stubs/django-import-export/management/commands/import.pyi new file mode 100644 index 000000000000..8d75fb4d613f --- /dev/null +++ b/stubs/django-import-export/management/commands/import.pyi @@ -0,0 +1,3 @@ +from django.core.management.base import BaseCommand + +class Command(BaseCommand): ... diff --git a/stubs/docker/@tests/stubtest_allowlist.txt b/stubs/docker/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ff14ff488c4d --- /dev/null +++ b/stubs/docker/@tests/stubtest_allowlist.txt @@ -0,0 +1,13 @@ +# requires paramiko, which is only installed with the ssh extra +docker.transport.sshconn + +# model is always set by child classes +docker.models.resource.Collection.model + +# implementation has *args and **kwargs params that can't be used +docker.api.container.ContainerApiMixin.start +docker.client.DockerClient.info +docker.client.DockerClient.ping + +# Internal-use module for types shared by multiple modules. +docker._types diff --git a/stubs/docker/@tests/stubtest_allowlist_darwin.txt b/stubs/docker/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..9f467ef3adc7 --- /dev/null +++ b/stubs/docker/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +# the named pipe transport requires pywin32, which is only installed on Windows +docker.transport.npipeconn +docker.transport.npipesocket diff --git a/stubs/docker/@tests/stubtest_allowlist_linux.txt b/stubs/docker/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..9f467ef3adc7 --- /dev/null +++ b/stubs/docker/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +# the named pipe transport requires pywin32, which is only installed on Windows +docker.transport.npipeconn +docker.transport.npipesocket diff --git a/stubs/docker/@tests/test_cases/check_attach.py b/stubs/docker/@tests/test_cases/check_attach.py new file mode 100644 index 000000000000..802099b9e2c2 --- /dev/null +++ b/stubs/docker/@tests/test_cases/check_attach.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from docker.models.containers import Container + + +def check_attach(c: Container) -> None: + assert_type(c.attach(), bytes) + assert_type(c.attach(stream=False), bytes) + for line in c.attach(stream=True): + assert_type(line, bytes) diff --git a/stubs/docker/METADATA.toml b/stubs/docker/METADATA.toml new file mode 100644 index 000000000000..68e0966475ac --- /dev/null +++ b/stubs/docker/METADATA.toml @@ -0,0 +1,7 @@ +version = "7.2.*" +upstream-repository = "https://github.com/docker/docker-py" +dependencies = ["types-requests", "urllib3>=2"] +optional-dependencies = ["types-paramiko"] + +[tool.stubtest] +ci-platforms = ["linux", "win32"] diff --git a/stubs/docker/docker/__init__.pyi b/stubs/docker/docker/__init__.pyi new file mode 100644 index 000000000000..52a7b3243202 --- /dev/null +++ b/stubs/docker/docker/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Final + +from .api import APIClient as APIClient +from .client import DockerClient as DockerClient, from_context as from_context, from_env as from_env +from .context import Context as Context, ContextAPI as ContextAPI +from .tls import TLSConfig as TLSConfig +from .version import __version__ as __version__ + +__title__: Final[str] diff --git a/stubs/docker/docker/_types.pyi b/stubs/docker/docker/_types.pyi new file mode 100644 index 000000000000..5500470c6fa5 --- /dev/null +++ b/stubs/docker/docker/_types.pyi @@ -0,0 +1,25 @@ +# Internal-use module for types shared by multiple modules. +# This does not match a module in docker-py. + +from pathlib import Path +from typing import TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +# Type alias for JSON, explained at: +# https://github.com/python/typing/issues/182#issuecomment-1320974824. +JSON: TypeAlias = dict[str, JSON] | list[JSON] | str | int | float | bool | None + +@type_check_only +class ContainerWeightDevice(TypedDict): + Path: Path + Weight: int + +# See https://docs.docker.com/engine/api/v1.42/#tag/Container/operation/ContainerWait +@type_check_only +class _WaitErrorDetails(TypedDict): + Message: str + +@type_check_only +class WaitContainerResponse(TypedDict): + StatusCode: int + Error: NotRequired[_WaitErrorDetails] diff --git a/stubs/docker/docker/api/__init__.pyi b/stubs/docker/docker/api/__init__.pyi new file mode 100644 index 000000000000..0b38db71747d --- /dev/null +++ b/stubs/docker/docker/api/__init__.pyi @@ -0,0 +1 @@ +from .client import APIClient as APIClient diff --git a/stubs/docker/docker/api/build.pyi b/stubs/docker/docker/api/build.pyi new file mode 100644 index 000000000000..73d69c033557 --- /dev/null +++ b/stubs/docker/docker/api/build.pyi @@ -0,0 +1,55 @@ +from collections.abc import Generator +from io import StringIO +from logging import Logger +from typing import IO, Any, TypedDict, type_check_only + +log: Logger + +@type_check_only +class _ContainerLimits(TypedDict, total=False): + memory: int + memswap: int + cpushares: int + cpusetcpus: str + +@type_check_only +class _Filers(TypedDict, total=False): + dangling: bool + until: str + +class BuildApiMixin: + def build( + self, + path: str | None = None, + tag: str | None = None, + quiet: bool = False, + fileobj: StringIO | IO[bytes] | None = None, + nocache: bool = False, + rm: bool = False, + timeout: int | None = None, + custom_context: bool = False, + encoding: str | None = None, + pull: bool = False, + forcerm: bool = False, + dockerfile: str | None = None, + container_limits: _ContainerLimits | None = None, + decode: bool = False, + buildargs: dict[str, Any] | None = None, + gzip: bool = False, + shmsize: int | None = None, + labels: dict[str, Any] | None = None, + # need to use list, because the type must be json serializable + cache_from: list[str] | None = None, + target: str | None = None, + network_mode: str | None = None, + squash: bool | None = None, + extra_hosts: list[str] | dict[str, str] | None = None, + platform: str | None = None, + isolation: str | None = None, + use_config_proxy: bool = True, + ) -> Generator[Any]: ... + def prune_builds( + self, filters: _Filers | None = None, keep_storage: int | None = None, all: bool | None = None + ) -> dict[str, Any]: ... + +def process_dockerfile(dockerfile: str | None, path: str) -> tuple[str | None, str | None]: ... diff --git a/stubs/docker/docker/api/client.pyi b/stubs/docker/docker/api/client.pyi new file mode 100644 index 000000000000..d3dd50eeb7c7 --- /dev/null +++ b/stubs/docker/docker/api/client.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence + +import requests +from docker.tls import TLSConfig +from requests.adapters import BaseAdapter + +from .build import BuildApiMixin +from .config import ConfigApiMixin +from .container import ContainerApiMixin +from .daemon import DaemonApiMixin +from .exec_api import ExecApiMixin +from .image import ImageApiMixin +from .network import NetworkApiMixin +from .plugin import PluginApiMixin +from .secret import SecretApiMixin +from .service import ServiceApiMixin +from .swarm import SwarmApiMixin +from .volume import VolumeApiMixin + +class APIClient( + requests.Session, + BuildApiMixin, + ConfigApiMixin, + ContainerApiMixin, + DaemonApiMixin, + ExecApiMixin, + ImageApiMixin, + NetworkApiMixin, + PluginApiMixin, + SecretApiMixin, + ServiceApiMixin, + SwarmApiMixin, + VolumeApiMixin, +): + __attrs__: Sequence[str] + base_url: str + timeout: int + credstore_env: Mapping[Incomplete, Incomplete] | None + def __init__( + self, + base_url: str | None = None, + version: str | None = None, + timeout: int = 60, + tls: bool | TLSConfig = False, + user_agent: str = ..., + num_pools: int | None = None, + credstore_env: Mapping[Incomplete, Incomplete] | None = None, + use_ssh_client: bool = False, + max_pool_size: int = 10, + ) -> None: ... + def get_adapter(self, url: str) -> BaseAdapter: ... + @property + def api_version(self) -> str: ... + def reload_config(self, dockercfg_path: str | None = None) -> None: ... diff --git a/stubs/docker/docker/api/config.pyi b/stubs/docker/docker/api/config.pyi new file mode 100644 index 000000000000..df2a281ee813 --- /dev/null +++ b/stubs/docker/docker/api/config.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class ConfigApiMixin: + def create_config( + self, + name: str, + data: bytes, + labels: dict[Incomplete, Incomplete] | None = None, + templating: dict[Incomplete, Incomplete] | None = None, + ): ... + def inspect_config(self, id): ... + def remove_config(self, id): ... + def configs(self, filters=None): ... diff --git a/stubs/docker/docker/api/container.pyi b/stubs/docker/docker/api/container.pyi new file mode 100644 index 000000000000..09322cad2948 --- /dev/null +++ b/stubs/docker/docker/api/container.pyi @@ -0,0 +1,326 @@ +import datetime +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import NotRequired + +from docker._types import ContainerWeightDevice, WaitContainerResponse +from docker.types.containers import DeviceRequest, LogConfig, Ulimit +from docker.types.daemon import CancellableStream +from docker.types.healthcheck import Healthcheck +from docker.types.services import Mount + +from ..types import ContainerConfig, EndpointConfig, HostConfig, NetworkingConfig + +@type_check_only +class _RestartPolicy(TypedDict): + MaximumRetryCount: NotRequired[int] + Name: NotRequired[Literal["always", "on-failure"]] + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +@type_check_only +class _TopResult(TypedDict): + Titles: list[str] + Processes: list[list[str]] + +_Container: TypeAlias = _HasId | _HasID | str + +class ContainerApiMixin: + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + demux: Literal[False] = False, + ) -> bytes: ... + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + *, + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + *, + stream: Literal[True], + logs: bool = False, + demux: Literal[False] = False, + ) -> CancellableStream[bytes]: ... + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + *, + stream: Literal[True], + logs: bool = False, + demux: Literal[True], + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + + def attach_socket(self, container: _Container, params=None, ws: bool = False): ... + def commit( + self, + container: _Container, + repository: str | None = None, + tag: str | None = None, + message=None, + author=None, + pause: bool = True, + changes=None, + conf=None, + ): ... + def containers( + self, + quiet: bool = False, + all: bool = False, + trunc: bool = False, + latest: bool = False, + since: str | None = None, + before: str | None = None, + limit: int = -1, + size: bool = False, + filters=None, + ): ... + def create_container( + self, + image, + command: str | list[str] | None = None, + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[Incomplete, Incomplete]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + name: str | None = None, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config=None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config=None, + healthcheck=None, + stop_timeout: int | None = None, + runtime: str | None = None, + use_config_proxy: bool = True, + platform: str | None = None, + ): ... + # Please keep in sync with docker.types.ContainerConfig + def create_container_config( + self, + image: str, + command: str | list[str], + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[str, str]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config: HostConfig | None = None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config: NetworkingConfig | None = None, + healthcheck: Healthcheck | None = None, + stop_timeout: int | None = None, + runtime: str | None = None, + ) -> ContainerConfig: ... + def create_container_from_config(self, config, name=None, platform=None): ... + # Please keep in sync with docker.types.HostConfig + def create_host_config( + self, + binds: dict[str, Mapping[str, str]] | list[str] | None = None, + port_bindings: Mapping[int | str, Any] | None = None, # Any: int, str, tuple, dict, or list + lxc_conf: dict[str, str] | list[dict[str, str]] | None = None, + publish_all_ports: bool = False, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + privileged: bool = False, + dns: list[str] | None = None, + dns_search: list[str] | None = None, + volumes_from: list[str] | None = None, + network_mode: str | None = None, + restart_policy: Mapping[str, str | int] | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + devices: list[str] | None = None, + extra_hosts: dict[str, str] | list[str] | None = None, + read_only: bool | None = None, + pid_mode: str | None = None, + ipc_mode: str | None = None, + security_opt: list[str] | None = None, + ulimits: list[Ulimit] | None = None, + log_config: LogConfig | None = None, + mem_limit: str | int | None = None, + memswap_limit: str | int | None = None, + mem_reservation: str | int | None = None, + kernel_memory: str | int | None = None, + mem_swappiness: int | None = None, + cgroup_parent: str | None = None, + group_add: Iterable[str | int] | None = None, + cpu_quota: int | None = None, + cpu_period: int | None = None, + blkio_weight: int | None = None, + blkio_weight_device: list[ContainerWeightDevice] | None = None, + device_read_bps: list[Mapping[str, str | int]] | None = None, + device_write_bps: list[Mapping[str, str | int]] | None = None, + device_read_iops: list[Mapping[str, str | int]] | None = None, + device_write_iops: list[Mapping[str, str | int]] | None = None, + oom_kill_disable: bool = False, + shm_size: str | int | None = None, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + oom_score_adj: int | None = None, + dns_opt: list[str] | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + pids_limit: int | None = None, + isolation: str | None = None, + auto_remove: bool = False, + storage_opt: dict[str, str] | None = None, + init: bool | None = None, + init_path: str | None = None, + volume_driver: str | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + nano_cpus: int | None = None, + cpuset_mems: str | None = None, + runtime: str | None = None, + mounts: list[Mount] | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + device_cgroup_rules: list[str] | None = None, + device_requests: list[DeviceRequest] | None = None, + cgroupns: Literal["private", "host"] | None = None, + ) -> HostConfig: ... + # Please keep in sync with docker.types.NetworkingConfig + def create_networking_config(self, endpoints_config: EndpointConfig | None = None) -> NetworkingConfig: ... + # Please keep in sync with docker.types.EndpointConfig + def create_endpoint_config( + self, + aliases: list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + ipv4_address: str | None = None, + ipv6_address: str | None = None, + link_local_ips: list[str] | None = None, + driver_opt: dict[str, str] | None = None, + mac_address: str | None = None, + ) -> EndpointConfig: ... + def diff(self, container: _Container) -> list[dict[Incomplete, Incomplete]]: ... + def export(self, container: _Container, chunk_size: int | None = 2097152): ... + def get_archive( + self, container: _Container, path, chunk_size: int | None = 2097152, encode_stream: bool = False + ) -> tuple[Incomplete, Incomplete]: ... + def inspect_container(self, container: _Container): ... + def kill(self, container: _Container, signal: str | int | None = None) -> None: ... + + @overload + def logs( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + *, + stream: Literal[True], + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> CancellableStream[bytes]: ... + @overload + def logs( + self, + container: _Container, + stdout: bool, + stderr: bool, + stream: Literal[True], + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> CancellableStream[bytes]: ... + @overload + def logs( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> bytes: ... + + def pause(self, container: _Container) -> None: ... + def port(self, container: _Container, private_port: int): ... + def put_archive(self, container: _Container, path: str, data) -> bool: ... + def prune_containers(self, filters=None): ... + def remove_container(self, container: _Container, v: bool = False, link: bool = False, force: bool = False) -> None: ... + def rename(self, container: _Container, name: str) -> None: ... + def resize(self, container: _Container, height: int, width: int) -> None: ... + def restart(self, container: _Container, timeout: int = 10) -> None: ... + def start(self, container: _Container) -> None: ... + def stats(self, container: _Container, decode: bool | None = None, stream: bool = True, one_shot: bool | None = None): ... + def stop(self, container: _Container, timeout: int | None = None) -> None: ... + def top(self, container: _Container, ps_args: str | None = None) -> _TopResult: ... + def unpause(self, container: _Container) -> None: ... + def update_container( + self, + container: _Container, + blkio_weight: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + mem_limit: float | str | None = None, + mem_reservation: float | str | None = None, + memswap_limit: int | str | None = None, + kernel_memory: int | str | None = None, + restart_policy: _RestartPolicy | None = None, + ): ... + def wait( + self, + container: _Container, + timeout: int | None = None, + condition: Literal["not-running", "next-exit", "removed"] | None = None, + ) -> WaitContainerResponse: ... diff --git a/stubs/docker/docker/api/daemon.pyi b/stubs/docker/docker/api/daemon.pyi new file mode 100644 index 000000000000..d1fccfe7b3c4 --- /dev/null +++ b/stubs/docker/docker/api/daemon.pyi @@ -0,0 +1,37 @@ +from datetime import datetime +from typing import Any, Literal, overload + +from docker.types.daemon import CancellableStream + +class DaemonApiMixin: + def df(self) -> dict[str, Any]: ... + + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[False] | None = None, + ) -> CancellableStream[str]: ... + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[True] = ..., + ) -> CancellableStream[dict[str, Any]]: ... + + def info(self) -> dict[str, Any]: ... + def login( + self, + username: str, + password: str | None = None, + email: str | None = None, + registry: str | None = None, + reauth: bool = False, + dockercfg_path: str | None = None, + ) -> dict[str, Any]: ... + def ping(self) -> bool: ... + def version(self, api_version: bool = True) -> dict[str, Any]: ... diff --git a/stubs/docker/docker/api/exec_api.pyi b/stubs/docker/docker/api/exec_api.pyi new file mode 100644 index 000000000000..4b5c1ca02cd0 --- /dev/null +++ b/stubs/docker/docker/api/exec_api.pyi @@ -0,0 +1,137 @@ +from _io import _BufferedReaderStream +from _typeshed import Incomplete +from socket import SocketIO +from typing import Literal, overload + +from docker.transport.sshconn import SSHSocket +from docker.types.daemon import CancellableStream + +class ExecApiMixin: + def exec_create( + self, + container, + cmd, + stdout: bool = True, + stderr: bool = True, + stdin: bool = False, + tty: bool = False, + privileged: bool = False, + user: str = "", + environment: dict[str, str] | list[str] | None = None, + workdir: str | None = None, + detach_keys: str | None = None, + ) -> dict[str, Incomplete]: ... + def exec_inspect(self, exec_id: str) -> dict[str, Incomplete]: ... + def exec_resize(self, exec_id: str, height: int | None = None, width: int | None = None) -> None: ... + + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[True], + tty: bool = False, + stream: bool = False, + socket: bool = False, + demux: bool = False, + ) -> bytes: ... + @overload + def exec_start( + self, exec_id: str, detach: Literal[False], tty: bool, stream: bool, socket: Literal[True], demux: bool = False + ) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + stream: bool = False, + *, + socket: Literal[True], + demux: bool = False, + ) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + @overload + def exec_start( + self, exec_id: str, detach: Literal[False], tty: bool, stream: Literal[True], socket: Literal[False], demux: Literal[True] + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + socket: Literal[False] = False, + *, + stream: Literal[True], + demux: Literal[True], + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False], + tty: bool, + stream: Literal[True], + socket: Literal[False], + demux: Literal[False], + ) -> CancellableStream[bytes]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + *, + stream: Literal[True], + socket: Literal[False] = False, + demux: Literal[False] = False, + ) -> CancellableStream[bytes]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False], + tty: bool, + stream: Literal[False], + socket: Literal[False], + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + stream: Literal[False] = False, + socket: Literal[False] = False, + *, + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + stream: Literal[False] = False, + socket: Literal[False] = False, + demux: Literal[False] = False, + ) -> bytes: ... + @overload + def exec_start( + self, + exec_id: str, + detach: bool = False, + tty: bool = False, + stream: bool = False, + socket: bool = False, + demux: bool = False, + ) -> ( + str + | SocketIO + | _BufferedReaderStream + | SSHSocket + | CancellableStream[bytes] + | CancellableStream[tuple[bytes | None, bytes | None]] + | tuple[bytes | None, bytes | None] + | bytes + ): ... diff --git a/stubs/docker/docker/api/image.pyi b/stubs/docker/docker/api/image.pyi new file mode 100644 index 000000000000..565ed904d273 --- /dev/null +++ b/stubs/docker/docker/api/image.pyi @@ -0,0 +1,43 @@ +import logging +from typing import Any + +log: logging.Logger + +class ImageApiMixin: + def get_image(self, image: str, chunk_size: int | None = 2097152): ... + def history(self, image): ... + def images(self, name: str | None = None, quiet: bool = False, all: bool = False, filters=None): ... + def import_image( + self, + src=None, + repository: str | None = None, + tag: str | None = None, + image: str | None = None, + changes=None, + stream_src: bool = False, + ): ... + def import_image_from_data(self, data, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_file(self, filename: str, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_stream(self, stream, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_url(self, url, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_image(self, image, repository: str | None = None, tag: str | None = None, changes=None): ... + def inspect_image(self, image): ... + def inspect_distribution(self, image, auth_config=None): ... + def load_image(self, data, quiet=None): ... + def prune_images(self, filters=None): ... + def pull( + self, + repository: str, + tag: str | None = None, + stream: bool = False, + auth_config: dict[str, Any] | None = None, + decode: bool = False, + platform: str | None = None, + all_tags: bool = False, + ): ... + def push(self, repository: str, tag: str | None = None, stream: bool = False, auth_config=None, decode: bool = False): ... + def remove_image(self, image: str, force: bool = False, noprune: bool = False): ... + def search(self, term: str, limit: int | None = None): ... + def tag(self, image, repository, tag: str | None = None, force: bool = False) -> bool: ... + +def is_file(src: str) -> bool: ... diff --git a/stubs/docker/docker/api/network.pyi b/stubs/docker/docker/api/network.pyi new file mode 100644 index 000000000000..c6a8cf6b434e --- /dev/null +++ b/stubs/docker/docker/api/network.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Any, Literal, TypeAlias, TypedDict, type_check_only + +from docker.types import IPAMConfig + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +_Network: TypeAlias = _HasId | _HasID | str +_Container: TypeAlias = _HasId | _HasID | str + +class NetworkApiMixin: + def networks(self, names: list[Incomplete] | None = None, ids: list[Incomplete] | None = None, filters=None): ... + def create_network( + self, + name: str, + driver: str | None = None, + options: dict[str, Any] | None = None, + ipam: IPAMConfig | None = None, + check_duplicate: bool | None = None, + internal: bool = False, + labels: dict[str, Any] | None = None, + enable_ipv6: bool = False, + attachable: bool | None = None, + scope: Literal["local", "global", "swarm"] | None = None, + ingress: bool | None = None, + ) -> dict[str, str]: ... + def prune_networks(self, filters=None): ... + def remove_network(self, net_id: _Network) -> None: ... + def inspect_network( + self, net_id: _Network, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None + ): ... + def connect_container_to_network( + self, + container: _Container, + net_id: str, + ipv4_address=None, + ipv6_address=None, + aliases=None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + link_local_ips=None, + driver_opt=None, + mac_address=None, + ) -> None: ... + def disconnect_container_from_network(self, container: _Container, net_id: str, force: bool = False) -> None: ... diff --git a/stubs/docker/docker/api/plugin.pyi b/stubs/docker/docker/api/plugin.pyi new file mode 100644 index 000000000000..2b8e21968b88 --- /dev/null +++ b/stubs/docker/docker/api/plugin.pyi @@ -0,0 +1,12 @@ +class PluginApiMixin: + def configure_plugin(self, name, options): ... + def create_plugin(self, name, plugin_data_dir, gzip: bool = False): ... + def disable_plugin(self, name, force: bool = False): ... + def enable_plugin(self, name, timeout: int = 0): ... + def inspect_plugin(self, name): ... + def pull_plugin(self, remote, privileges, name=None): ... + def plugins(self): ... + def plugin_privileges(self, name): ... + def push_plugin(self, name): ... + def remove_plugin(self, name, force: bool = False): ... + def upgrade_plugin(self, name, remote, privileges): ... diff --git a/stubs/docker/docker/api/secret.pyi b/stubs/docker/docker/api/secret.pyi new file mode 100644 index 000000000000..18e6acde3774 --- /dev/null +++ b/stubs/docker/docker/api/secret.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from typing import Any + +from docker.types import DriverConfig + +class SecretApiMixin: + def create_secret( + self, name: str, data: bytes, labels: dict[str, Any] | None = None, driver: DriverConfig | None = None + ) -> dict[str, Any]: ... + def inspect_secret(self, id: str) -> dict[str, Any]: ... + def remove_secret(self, id: str) -> bool: ... + def secrets(self, filters: dict[str, Any] | None = None) -> Iterable[dict[str, Any]]: ... diff --git a/stubs/docker/docker/api/service.pyi b/stubs/docker/docker/api/service.pyi new file mode 100644 index 000000000000..cf86afc7ba6f --- /dev/null +++ b/stubs/docker/docker/api/service.pyi @@ -0,0 +1,45 @@ +class ServiceApiMixin: + def create_service( + self, + task_template, + name=None, + labels=None, + mode=None, + update_config=None, + networks=None, + endpoint_config=None, + endpoint_spec=None, + rollback_config=None, + ): ... + def inspect_service(self, service, insert_defaults=None): ... + def inspect_task(self, task): ... + def remove_service(self, service): ... + def services(self, filters=None, status=None): ... + def service_logs( + self, + service, + details: bool = False, + follow: bool = False, + stdout: bool = False, + stderr: bool = False, + since: int = 0, + timestamps: bool = False, + tail: str = "all", + is_tty=None, + ): ... + def tasks(self, filters=None): ... + def update_service( + self, + service, + version, + task_template=None, + name=None, + labels=None, + mode=None, + update_config=None, + networks=None, + endpoint_config=None, + endpoint_spec=None, + fetch_current_spec: bool = False, + rollback_config=None, + ): ... diff --git a/stubs/docker/docker/api/swarm.pyi b/stubs/docker/docker/api/swarm.pyi new file mode 100644 index 000000000000..428375570858 --- /dev/null +++ b/stubs/docker/docker/api/swarm.pyi @@ -0,0 +1,85 @@ +import logging +from typing import Any, Literal, TypeAlias, TypedDict, type_check_only + +from docker.types.services import DriverConfig +from docker.types.swarm import SwarmExternalCA, SwarmSpec + +log: logging.Logger + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +_Node: TypeAlias = _HasId | _HasID | str + +@type_check_only +class _NodeSpec(TypedDict, total=False): + Name: str + Labels: dict[str, str] + Role: Literal["worker", "manager"] + Availability: Literal["active", "pause", "drain"] + +@type_check_only +class _UnlockKeyResponse(TypedDict): + UnlockKey: str + +class SwarmApiMixin: + def create_swarm_spec( + self, + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> SwarmSpec: ... + def get_unlock_key(self) -> _UnlockKeyResponse: ... + def init_swarm( + self, + advertise_addr: str | None = None, + listen_addr: str = "0.0.0.0:2377", + force_new_cluster: bool = False, + swarm_spec: dict[str, Any] | None = None, # Any: arbitrary SwarmSpec configuration body + default_addr_pool: list[str] | None = None, + subnet_size: int | None = None, + data_path_addr: str | None = None, + data_path_port: int | None = None, + ) -> str: ... + def inspect_swarm(self) -> dict[str, Any]: ... # Any: deeply nested ClusterInfo + JoinTokens + def inspect_node(self, node_id: _Node) -> dict[str, Any]: ... # Any: deeply nested Node object + def join_swarm( + self, + remote_addrs: list[str], + join_token: str, + listen_addr: str = "0.0.0.0:2377", + advertise_addr: str | None = None, + data_path_addr: str | None = None, + ) -> Literal[True]: ... + def leave_swarm(self, force: bool = False) -> Literal[True]: ... + def nodes(self, filters: dict[str, Any] | None = None) -> list[dict[str, Any]]: ... # Any: filter values + Node response + def remove_node(self, node_id: _Node, force: bool = False) -> Literal[True]: ... + def unlock_swarm(self, key: str | _UnlockKeyResponse) -> Literal[True]: ... + def update_node(self, node_id: _Node, version: int, node_spec: _NodeSpec | None = None) -> Literal[True]: ... + def update_swarm( + self, + version: int, + swarm_spec: dict[str, Any] | None = None, # Any: arbitrary SwarmSpec configuration body + rotate_worker_token: bool = False, + rotate_manager_token: bool = False, + rotate_manager_unlock_key: bool = False, + ) -> Literal[True]: ... diff --git a/stubs/docker/docker/api/volume.pyi b/stubs/docker/docker/api/volume.pyi new file mode 100644 index 000000000000..b798f9f79782 --- /dev/null +++ b/stubs/docker/docker/api/volume.pyi @@ -0,0 +1,14 @@ +from typing import Any + +class VolumeApiMixin: + def volumes(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + def create_volume( + self, + name: str | None = None, + driver: str | None = None, + driver_opts: dict[str, Any] | None = None, + labels: dict[str, Any] | None = None, + ) -> dict[str, Any]: ... + def inspect_volume(self, name: str) -> dict[str, Any]: ... + def prune_volumes(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + def remove_volume(self, name, force: bool = False) -> None: ... diff --git a/stubs/docker/docker/auth.pyi b/stubs/docker/docker/auth.pyi new file mode 100644 index 000000000000..48d3c5c2cbd6 --- /dev/null +++ b/stubs/docker/docker/auth.pyi @@ -0,0 +1,48 @@ +from _typeshed import FileDescriptorOrPath, Incomplete, ReadableBuffer +from collections.abc import Mapping, MutableMapping +from logging import Logger +from typing import Final +from typing_extensions import Self + +INDEX_NAME: Final[str] +INDEX_URL: Final[str] +TOKEN_USERNAME: Final[str] +log: Logger + +def resolve_repository_name(repo_name: str) -> tuple[str, str]: ... +def resolve_index_name(index_name: str) -> str: ... +def get_config_header(client, registry) -> bytes | None: ... +def split_repo_name(repo_name: str) -> tuple[str, str]: ... +def get_credential_store(authconfig: AuthConfig | MutableMapping[str, Incomplete], registry: str | None): ... + +class AuthConfig(dict[str, Incomplete]): + def __init__(self, dct: MutableMapping[str, Incomplete], credstore_env=None) -> None: ... + @classmethod + def parse_auth( + cls, entries: Mapping[str, dict[Incomplete, Incomplete]], raise_on_error: bool = False + ) -> dict[str, Incomplete]: ... + @classmethod + def load_config( + cls, config_path: FileDescriptorOrPath | None, config_dict: dict[str, Incomplete] | None, credstore_env=None + ) -> Self: ... + @property + def auths(self) -> dict[str, Incomplete]: ... + @property + def creds_store(self): ... + @property + def cred_helpers(self): ... + @property + def is_empty(self) -> bool: ... + def resolve_authconfig(self, registry: str | None = None): ... + def get_credential_store(self, registry: str | None): ... + def get_all_credentials(self): ... + def add_auth(self, reg: str, data) -> None: ... + +def resolve_authconfig(authconfig, registry: str | None = None, credstore_env=None): ... +def convert_to_hostname(url: str) -> str: ... +def decode_auth(auth: str | ReadableBuffer) -> tuple[str, str]: ... +def encode_header(auth) -> bytes: ... +def parse_auth(entries: Mapping[str, dict[Incomplete, Incomplete]], raise_on_error: bool = False): ... +def load_config( + config_path: FileDescriptorOrPath | None = None, config_dict: dict[str, Incomplete] | None = None, credstore_env=None +) -> AuthConfig: ... diff --git a/stubs/docker/docker/client.pyi b/stubs/docker/docker/client.pyi new file mode 100644 index 000000000000..eef6be705974 --- /dev/null +++ b/stubs/docker/docker/client.pyi @@ -0,0 +1,127 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from datetime import datetime +from typing import Any, Literal, Protocol, overload, type_check_only +from typing_extensions import Never + +from docker import APIClient +from docker.models.configs import ConfigCollection +from docker.models.containers import ContainerCollection +from docker.models.images import ImageCollection +from docker.models.networks import NetworkCollection +from docker.models.nodes import NodeCollection +from docker.models.plugins import PluginCollection +from docker.models.secrets import SecretCollection +from docker.models.services import ServiceCollection +from docker.models.swarm import Swarm +from docker.models.volumes import VolumeCollection +from docker.tls import TLSConfig +from docker.types import CancellableStream + +@type_check_only +class _Environ(Protocol): + def __getitem__(self, k: str, /) -> str: ... + def keys(self) -> Iterable[str]: ... + +class DockerClient: + api: APIClient + # Please keep in sync with docker.APIClient + def __init__( + self, + base_url: str | None = None, + version: str | None = None, + timeout: int = 60, + tls: bool | TLSConfig = False, + user_agent: str = ..., + num_pools: int | None = None, + credstore_env: Mapping[Incomplete, Incomplete] | None = None, + use_ssh_client: bool = False, + max_pool_size: int = 10, + ) -> None: ... + @classmethod + def from_env( + cls, + *, + version: str | None = None, + timeout: int = 60, + max_pool_size: int = 10, + environment: _Environ | None = None, + use_ssh_client: bool = False, + use_context: bool = True, + ) -> DockerClient: ... + @classmethod + def from_context( + cls, + name=None, + *, + version: str | None = None, + timeout: int = 60, + max_pool_size: int = 10, + use_ssh_client: bool = False, + base_url: str | None = None, + tls: bool | TLSConfig = False, + user_agent: str = ..., + num_pools: int | None = None, + credstore_env: Mapping[Incomplete, Incomplete] | None = None, + ): ... + @property + def configs(self) -> ConfigCollection: ... + @property + def containers(self) -> ContainerCollection: ... + @property + def images(self) -> ImageCollection: ... + @property + def networks(self) -> NetworkCollection: ... + @property + def nodes(self) -> NodeCollection: ... + @property + def plugins(self) -> PluginCollection: ... + @property + def secrets(self) -> SecretCollection: ... + @property + def services(self) -> ServiceCollection: ... + @property + def swarm(self) -> Swarm: ... + @property + def volumes(self) -> VolumeCollection: ... + + # Please keep in sync with docker.api.daemon.DaemonApiMixin.events + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[False] | None = None, + ) -> CancellableStream[str]: ... + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[True] = ..., + ) -> CancellableStream[dict[str, Any]]: ... + + def df(self) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.info + def info(self) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.login + def login( + self, + username: str, + password: str | None = None, + email: str | None = None, + registry: str | None = None, + reauth: bool = False, + dockercfg_path: str | None = None, + ) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.ping + def ping(self) -> bool: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.version + def version(self, api_version: bool = True) -> dict[str, Any]: ... + def close(self) -> None: ... + def __getattr__(self, name: str) -> Never: ... + +from_env = DockerClient.from_env +from_context = DockerClient.from_context diff --git a/stubs/docker/docker/constants.pyi b/stubs/docker/docker/constants.pyi new file mode 100644 index 000000000000..c9692144d083 --- /dev/null +++ b/stubs/docker/docker/constants.pyi @@ -0,0 +1,22 @@ +from collections.abc import Mapping, Sequence +from typing import Final + +DEFAULT_DOCKER_API_VERSION: Final[str] +MINIMUM_DOCKER_API_VERSION: Final[str] +DEFAULT_TIMEOUT_SECONDS: Final[int] +STREAM_HEADER_SIZE_BYTES: Final[int] +CONTAINER_LIMITS_KEYS: Final[Sequence[str]] +DEFAULT_HTTP_HOST: Final[str] +DEFAULT_UNIX_SOCKET: Final[str] +DEFAULT_NPIPE: Final[str] +BYTE_UNITS: Final[Mapping[str, int]] +INSECURE_REGISTRY_DEPRECATION_WARNING: Final[str] +IS_WINDOWS_PLATFORM: Final[bool] +WINDOWS_LONGPATH_PREFIX: Final[str] +DEFAULT_USER_AGENT: Final[str] +DEFAULT_NUM_POOLS: Final[int] +DEFAULT_NUM_POOLS_SSH: Final[int] +DEFAULT_MAX_POOL_SIZE: Final[int] +DEFAULT_DATA_CHUNK_SIZE: Final[int] +DEFAULT_SWARM_ADDR_POOL: Final[Sequence[str]] +DEFAULT_SWARM_SUBNET_SIZE: Final[int] diff --git a/stubs/docker/docker/context/__init__.pyi b/stubs/docker/docker/context/__init__.pyi new file mode 100644 index 000000000000..c9f9395972a2 --- /dev/null +++ b/stubs/docker/docker/context/__init__.pyi @@ -0,0 +1,2 @@ +from .api import ContextAPI as ContextAPI +from .context import Context as Context diff --git a/stubs/docker/docker/context/api.pyi b/stubs/docker/docker/context/api.pyi new file mode 100644 index 000000000000..bf3e591243ca --- /dev/null +++ b/stubs/docker/docker/context/api.pyi @@ -0,0 +1,39 @@ +from collections.abc import Mapping, Sequence +from typing import TypedDict, type_check_only + +from docker.context.context import Context +from docker.tls import TLSConfig + +@type_check_only +class _ContextKwargs(TypedDict, total=False): + base_url: str + tls: TLSConfig + +class ContextAPI: + DEFAULT_CONTEXT: Context + @classmethod + def create_context( + cls, + name: str, + orchestrator: str | None = None, + host: str | None = None, + tls_cfg: TLSConfig | None = None, + default_namespace: str | None = None, + skip_tls_verify: bool = False, + ) -> Context: ... + @classmethod + def get_context(cls, name: str | None = None) -> Context: ... + @classmethod + def contexts(cls) -> Sequence[Context]: ... + @classmethod + def get_current_context(cls) -> Context: ... + @classmethod + def kwargs_from_context( + cls, name: str | None = None, environment: Mapping[str, str | None] | None = None # TODO: Use SupportsGet + ) -> _ContextKwargs: ... + @classmethod + def set_current_context(cls, name: str = "default") -> None: ... + @classmethod + def remove_context(cls, name: str) -> None: ... + @classmethod + def inspect_context(cls, name: str = "default") -> Context: ... diff --git a/stubs/docker/docker/context/config.pyi b/stubs/docker/docker/context/config.pyi new file mode 100644 index 000000000000..a24b8e0f5cd2 --- /dev/null +++ b/stubs/docker/docker/context/config.pyi @@ -0,0 +1,10 @@ +METAFILE: str + +def get_current_context_name() -> str: ... +def write_context_name_to_docker_config(name: str | None = None) -> Exception | None: ... +def get_context_id(name: str) -> str: ... +def get_context_dir() -> str: ... +def get_meta_dir(name: str | None = None) -> str: ... +def get_meta_file(name: str) -> str: ... +def get_tls_dir(name: str | None = None, endpoint: str = "") -> str: ... +def get_context_host(path: str | None = None, tls: bool = False) -> str: ... diff --git a/stubs/docker/docker/context/context.pyi b/stubs/docker/docker/context/context.pyi new file mode 100644 index 000000000000..cffd95233e08 --- /dev/null +++ b/stubs/docker/docker/context/context.pyi @@ -0,0 +1,81 @@ +from typing import TypedDict, type_check_only + +from docker.tls import TLSConfig as _TLSConfig + +@type_check_only +class _StorageData(TypedDict): + MetadataPath: str + TLSPath: str + +@type_check_only +class _Storage(TypedDict): + Storage: _StorageData + +@type_check_only +class _Endpoint(TypedDict, total=False): + Host: str + SkipTLSVerify: bool + DefaultNamespace: str + +@type_check_only +class _TLSMaterial(TypedDict): + TLSMaterial: dict[str, list[str]] + +@type_check_only +class _MetaMetaData(TypedDict, total=False): + StackOrchestrator: str + +@type_check_only +class _Metadata(TypedDict): + Name: str + Metadata: _MetaMetaData + Endpoints: dict[str, _Endpoint] + +@type_check_only +class _Context(_Metadata, _TLSMaterial, _Storage): ... + +class Context: + name: str + context_type: str | None + orchestrator: str | None + endpoints: dict[str, _Endpoint] + tls_cfg: dict[str, _TLSConfig] + meta_path: str + tls_path: str + def __init__( + self, + name: str, + orchestrator: str | None = None, + host: str | None = None, + endpoints: dict[str, _Endpoint] | None = None, + tls: bool = False, + ) -> None: ... + def set_endpoint( + self, + name: str = "docker", + host: str | None = None, + tls_cfg: _TLSConfig | None = None, + skip_tls_verify: bool = False, + def_namespace: str | None = None, + ) -> None: ... + def inspect(self) -> _Context: ... + @classmethod + def load_context(cls, name: str) -> Context | None: ... + def save(self) -> None: ... + def remove(self) -> None: ... + def __call__(self) -> _Context: ... + def is_docker_host(self) -> bool: ... + @property + def Name(self) -> str: ... + @property + def Host(self) -> str | None: ... + @property + def Orchestrator(self) -> str: ... + @property + def Metadata(self) -> _Metadata: ... + @property + def TLSConfig(self) -> _TLSConfig: ... + @property + def TLSMaterial(self) -> _TLSMaterial: ... + @property + def Storage(self) -> _Storage: ... diff --git a/stubs/docker/docker/credentials/__init__.pyi b/stubs/docker/docker/credentials/__init__.pyi new file mode 100644 index 000000000000..d0b5f26cc128 --- /dev/null +++ b/stubs/docker/docker/credentials/__init__.pyi @@ -0,0 +1,8 @@ +from .constants import ( + DEFAULT_LINUX_STORE as DEFAULT_LINUX_STORE, + DEFAULT_OSX_STORE as DEFAULT_OSX_STORE, + DEFAULT_WIN32_STORE as DEFAULT_WIN32_STORE, + PROGRAM_PREFIX as PROGRAM_PREFIX, +) +from .errors import CredentialsNotFound as CredentialsNotFound, StoreError as StoreError +from .store import Store as Store diff --git a/stubs/docker/docker/credentials/constants.pyi b/stubs/docker/docker/credentials/constants.pyi new file mode 100644 index 000000000000..50bc76200277 --- /dev/null +++ b/stubs/docker/docker/credentials/constants.pyi @@ -0,0 +1,4 @@ +PROGRAM_PREFIX: str +DEFAULT_LINUX_STORE: str +DEFAULT_OSX_STORE: str +DEFAULT_WIN32_STORE: str diff --git a/stubs/docker/docker/credentials/errors.pyi b/stubs/docker/docker/credentials/errors.pyi new file mode 100644 index 000000000000..faff8f40e574 --- /dev/null +++ b/stubs/docker/docker/credentials/errors.pyi @@ -0,0 +1,7 @@ +from subprocess import CalledProcessError + +class StoreError(RuntimeError): ... +class CredentialsNotFound(StoreError): ... +class InitializationError(StoreError): ... + +def process_store_error(cpe: CalledProcessError, program: str) -> Exception: ... diff --git a/stubs/docker/docker/credentials/store.pyi b/stubs/docker/docker/credentials/store.pyi new file mode 100644 index 000000000000..42d05f34338e --- /dev/null +++ b/stubs/docker/docker/credentials/store.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +class Store: + program: str + exe: str | None + environment: Incomplete + def __init__(self, program: str, environment=None) -> None: ... + def get(self, server): ... + def store(self, server, username, secret): ... + def erase(self, server) -> None: ... + def list(self): ... diff --git a/stubs/docker/docker/credentials/utils.pyi b/stubs/docker/docker/credentials/utils.pyi new file mode 100644 index 000000000000..1e87e491697b --- /dev/null +++ b/stubs/docker/docker/credentials/utils.pyi @@ -0,0 +1 @@ +def create_environment_dict(overrides): ... diff --git a/stubs/docker/docker/errors.pyi b/stubs/docker/docker/errors.pyi new file mode 100644 index 000000000000..407f1afb13f9 --- /dev/null +++ b/stubs/docker/docker/errors.pyi @@ -0,0 +1,74 @@ +from collections.abc import Iterator, Mapping +from typing import Any +from typing_extensions import Never + +from docker.models.containers import Container +from docker.models.images import Image +from requests import HTTPError, Response + +class DockerException(Exception): ... + +def create_api_error_from_http_exception(e: HTTPError) -> Never: ... + +class APIError(HTTPError, DockerException): + response: Response | None + explanation: str | None + def __init__(self, message: str, response: Response | None = None, explanation: str | None = None) -> None: ... + @property + def status_code(self) -> int | None: ... + def is_error(self) -> bool: ... + def is_client_error(self) -> bool: ... + def is_server_error(self) -> bool: ... + +class NotFound(APIError): ... +class ImageNotFound(NotFound): ... +class InvalidVersion(DockerException): ... +class InvalidRepository(DockerException): ... +class InvalidConfigFile(DockerException): ... +class InvalidArgument(DockerException): ... +class DeprecatedMethod(DockerException): ... + +class TLSParameterError(DockerException): + msg: str + def __init__(self, msg: str) -> None: ... + +class NullResource(DockerException, ValueError): ... + +class ContainerError(DockerException): + container: Container + exit_status: int + command: str | list[str] | None + image: str | Image + stderr: str | None + def __init__( + self, container: Container, exit_status: int, command: str | list[str] | None, image: str | Image, stderr: str | None + ) -> None: ... + +class StreamParseError(RuntimeError): + msg: str + def __init__(self, reason: str) -> None: ... + +class BuildError(DockerException): + msg: str + build_log: Iterator[dict[str, str]] + def __init__(self, reason: str, build_log: Iterator[dict[str, str]]) -> None: ... + +class ImageLoadError(DockerException): ... + +def create_unexpected_kwargs_error(name, kwargs: Mapping[str, Any]) -> Never: ... + +class MissingContextParameter(DockerException): + param: str + def __init__(self, param: str) -> None: ... + +class ContextAlreadyExists(DockerException): + name: str + def __init__(self, name: str) -> None: ... + +class ContextException(DockerException): + msg: str + def __init__(self, msg: str) -> None: ... + +class ContextNotFound(DockerException): + name: str + def __init__(self, name: str) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/phantomjs/__init__.pyi b/stubs/docker/docker/models/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/phantomjs/__init__.pyi rename to stubs/docker/docker/models/__init__.pyi diff --git a/stubs/docker/docker/models/configs.pyi b/stubs/docker/docker/models/configs.pyi new file mode 100644 index 000000000000..08a8fe4e6baa --- /dev/null +++ b/stubs/docker/docker/models/configs.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from .resource import Collection, Model + +class Config(Model): + id_attribute: str + @property + def name(self) -> str: ... + def remove(self) -> bool: ... + +class ConfigCollection(Collection[Config]): + model: type[Config] + # Please keep in sync with docker.api.config.ConfigApiMixin.create_config + def create( # type: ignore[override] + self, + *, + name: str, + data: bytes, + labels: dict[Incomplete, Incomplete] | None = None, + templating: dict[Incomplete, Incomplete] | None = None, + ) -> Config: ... + def get(self, config_id: str) -> Config: ... + # Please keep in sync with docker.api.config.ConfigApiMixin.configs + def list(self, *, filters=None) -> _list[Config]: ... diff --git a/stubs/docker/docker/models/containers.pyi b/stubs/docker/docker/models/containers.pyi new file mode 100644 index 000000000000..f6cb0353801d --- /dev/null +++ b/stubs/docker/docker/models/containers.pyi @@ -0,0 +1,477 @@ +import datetime +from _io import _BufferedReaderStream +from builtins import list as _list +from collections.abc import Iterable, Iterator, Mapping +from socket import SocketIO +from typing import Any, Literal, NamedTuple, overload + +from docker._types import ContainerWeightDevice, WaitContainerResponse +from docker.api.container import _RestartPolicy, _TopResult +from docker.transport.sshconn import SSHSocket +from docker.types import EndpointConfig +from docker.types.containers import DeviceRequest, LogConfig, Ulimit +from docker.types.daemon import CancellableStream +from docker.types.services import Mount + +from .images import Image +from .resource import Collection, Model + +class Container(Model): + @property + def name(self) -> str | None: ... + @property + def image(self) -> Image | None: ... + @property + def labels(self) -> dict[str, str]: ... + @property + def status(self) -> str: ... + @property + def health(self) -> str: ... + @property + def ports(self) -> dict[str, list[dict[str, str]] | None]: ... + + # Please keep in sync with docker.api.container.ContainerApiMixin.attach + @overload + def attach( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + demux: Literal[False] = False, + ) -> bytes: ... + @overload + def attach( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def attach( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[True], + logs: bool = False, + demux: Literal[False] = False, + ) -> CancellableStream[bytes]: ... + @overload + def attach( + self, *, stdout: bool = True, stderr: bool = True, stream: Literal[True], logs: bool = False, demux: Literal[True] + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + + # Please keep in sync with docker.api.container.ContainerApiMixin.attach_socket + def attach_socket(self, *, params=None, ws: bool = False) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.commit + def commit( + self, + repository: str | None = None, + tag: str | None = None, + *, + message=None, + author=None, + pause: bool = True, + changes=None, + conf=None, + ) -> Image: ... + def diff(self) -> list[dict[str, int | str]]: ... + def exec_run( + self, + cmd: str | list[str], + stdout: bool = True, + stderr: bool = True, + stdin: bool = False, + tty: bool = False, + privileged: bool = False, + user: str = "", + detach: bool = False, + stream: bool = False, + socket: bool = False, + environment: dict[str, str] | list[str] | None = None, + workdir: str | None = None, + demux: bool = False, + ) -> ExecResult: ... + def export(self, chunk_size: int | None = 2097152) -> str: ... + def get_archive( + self, path: str, chunk_size: int | None = 2097152, encode_stream: bool = False + ) -> tuple[Iterator[bytes], dict[str, Any] | None]: ... + def kill(self, signal: str | int | None = None) -> None: ... + + # Please keep in sync with docker.api.container.ContainerApiMixin.logs + @overload + def logs( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[True], + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> CancellableStream[bytes]: ... + @overload + def logs( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> bytes: ... + + def pause(self) -> None: ... + def put_archive(self, path: str, data) -> bool: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.remove_container + def remove(self, *, v: bool = False, link: bool = False, force: bool = False) -> None: ... + def rename(self, name: str) -> None: ... + def resize(self, height: int, width: int) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.restart + def restart(self, *, timeout: float | None = 10) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.start + def start(self) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.stats + def stats( + self, *, decode: bool | None = None, stream: bool = True, one_shot: bool | None = None + ) -> Iterator[dict[str, Any]] | dict[str, Any]: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.stop + def stop(self, *, timeout: float | None = None) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.top + def top(self, *, ps_args: str | None = None) -> _TopResult: ... + def unpause(self) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.update_container + def update( + self, + *, + blkio_weight: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + mem_limit: float | str | None = None, + mem_reservation: float | str | None = None, + memswap_limit: int | str | None = None, + kernel_memory: int | str | None = None, + restart_policy: _RestartPolicy | None = None, + ): ... + # Please keep in sync with docker.api.container.ContainerApiMixin.wait + def wait( + self, *, timeout: float | None = None, condition: Literal["not-running", "next-exit", "removed"] | None = None + ) -> WaitContainerResponse: ... + +class ContainerCollection(Collection[Container]): + model: type[Container] + + @overload + def run( + self, + image: str | Image, + command: str | _list[str] | None = None, + stdout: bool = True, + stderr: bool = False, + remove: bool = False, + *, + auto_remove: bool = False, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, + blkio_weight: int | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, + cgroup_parent: str | None = None, + cgroupns: Literal["private", "host"] | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + detach: Literal[False] = False, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, + extra_hosts: dict[str, str] | None = None, + group_add: Iterable[str | int] | None = None, + healthcheck: dict[str, Any] | None = None, + hostname: str | None = None, + init: bool | None = None, + init_path: str | None = None, + ipc_mode: str | None = None, + isolation: str | None = None, + kernel_memory: str | int | None = None, + labels: dict[str, str] | _list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + log_config: LogConfig | None = None, + lxc_conf: dict[str, str] | None = None, + mac_address: str | None = None, + mem_limit: str | int | None = None, + mem_reservation: str | int | None = None, + mem_swappiness: int | None = None, + memswap_limit: str | int | None = None, + mounts: _list[Mount] | None = None, + name: str | None = None, + nano_cpus: int | None = None, + network: str | None = None, + network_disabled: bool = False, + network_mode: str | None = None, + networking_config: dict[str, EndpointConfig] | None = None, + oom_kill_disable: bool = False, + oom_score_adj: int | None = None, + pid_mode: str | None = None, + pids_limit: int | None = None, + platform: str | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, + privileged: bool = False, + publish_all_ports: bool = False, + read_only: bool | None = None, + restart_policy: _RestartPolicy | None = None, + runtime: str | None = None, + security_opt: _list[str] | None = None, + shm_size: str | int | None = None, + stdin_open: bool = False, + stop_signal: str | None = None, + storage_opt: dict[str, str] | None = None, + stream: bool = False, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + tty: bool = False, + ulimits: _list[Ulimit] | None = None, + use_config_proxy: bool | None = None, + user: str | int | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + version: str | None = None, + volume_driver: str | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, + working_dir: str | None = None, + ) -> bytes: ... # TODO: This should return a stream, if `stream` is True + @overload + def run( + self, + image: str | Image, + command: str | _list[str] | None = None, + stdout: bool = True, + stderr: bool = False, + remove: bool = False, + *, + auto_remove: bool = False, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, + blkio_weight: int | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, + cgroup_parent: str | None = None, + cgroupns: Literal["private", "host"] | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + detach: Literal[True], + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, + extra_hosts: dict[str, str] | None = None, + group_add: Iterable[str | int] | None = None, + healthcheck: dict[str, Any] | None = None, + hostname: str | None = None, + init: bool | None = None, + init_path: str | None = None, + ipc_mode: str | None = None, + isolation: str | None = None, + kernel_memory: str | int | None = None, + labels: dict[str, str] | _list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + log_config: LogConfig | None = None, + lxc_conf: dict[str, str] | None = None, + mac_address: str | None = None, + mem_limit: str | int | None = None, + mem_reservation: str | int | None = None, + mem_swappiness: int | None = None, + memswap_limit: str | int | None = None, + mounts: _list[Mount] | None = None, + name: str | None = None, + nano_cpus: int | None = None, + network: str | None = None, + network_disabled: bool = False, + network_mode: str | None = None, + networking_config: dict[str, EndpointConfig] | None = None, + oom_kill_disable: bool = False, + oom_score_adj: int | None = None, + pid_mode: str | None = None, + pids_limit: int | None = None, + platform: str | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, + privileged: bool = False, + publish_all_ports: bool = False, + read_only: bool | None = None, + restart_policy: _RestartPolicy | None = None, + runtime: str | None = None, + security_opt: _list[str] | None = None, + shm_size: str | int | None = None, + stdin_open: bool = False, + stop_signal: str | None = None, + storage_opt: dict[str, str] | None = None, + stream: bool = False, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + tty: bool = False, + ulimits: _list[Ulimit] | None = None, + use_config_proxy: bool | None = None, + user: str | int | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + version: str | None = None, + volume_driver: str | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, + working_dir: str | None = None, + ) -> Container: ... + + def create( # type: ignore[override] + self, + image: str | Image, + command: str | _list[str] | None = None, + *, + auto_remove: bool = False, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, + blkio_weight: int | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, + cgroup_parent: str | None = None, + cgroupns: Literal["private", "host"] | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + detach: bool = False, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, + extra_hosts: dict[str, str] | None = None, + group_add: Iterable[str | int] | None = None, + healthcheck: dict[str, Any] | None = None, + hostname: str | None = None, + init: bool | None = None, + init_path: str | None = None, + ipc_mode: str | None = None, + isolation: str | None = None, + kernel_memory: str | int | None = None, + labels: dict[str, str] | _list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + log_config: LogConfig | None = None, + lxc_conf: dict[str, str] | None = None, + mac_address: str | None = None, + mem_limit: str | int | None = None, + mem_reservation: str | int | None = None, + mem_swappiness: int | None = None, + memswap_limit: str | int | None = None, + mounts: _list[Mount] | None = None, + name: str | None = None, + nano_cpus: int | None = None, + network: str | None = None, + network_disabled: bool = False, + network_mode: str | None = None, + networking_config: dict[str, EndpointConfig] | None = None, + oom_kill_disable: bool = False, + oom_score_adj: int | None = None, + pid_mode: str | None = None, + pids_limit: int | None = None, + platform: str | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, + privileged: bool = False, + publish_all_ports: bool = False, + read_only: bool | None = None, + restart_policy: _RestartPolicy | None = None, + runtime: str | None = None, + security_opt: _list[str] | None = None, + shm_size: str | int | None = None, + stdin_open: bool = False, + stop_signal: str | None = None, + storage_opt: dict[str, str] | None = None, + stream: bool = False, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + tty: bool = False, + ulimits: _list[Ulimit] | None = None, + use_config_proxy: bool | None = None, + user: str | int | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + version: str | None = None, + volume_driver: str | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, + working_dir: str | None = None, + ) -> Container: ... + def get(self, container_id: str) -> Container: ... + def list( + self, + all: bool = False, + before: str | None = None, + filters: dict[str, str | _list[str] | bool] | None = None, + limit: int = -1, + since: str | None = None, + sparse: bool = False, + ignore_removed: bool = False, + ) -> _list[Container]: ... + def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + +RUN_CREATE_KWARGS: list[str] +RUN_HOST_CONFIG_KWARGS: list[str] + +class ExecResult(NamedTuple): + exit_code: int | None + output: bytes | Iterator[bytes] diff --git a/stubs/docker/docker/models/images.pyi b/stubs/docker/docker/models/images.pyi new file mode 100644 index 000000000000..db5b7954ca3e --- /dev/null +++ b/stubs/docker/docker/models/images.pyi @@ -0,0 +1,127 @@ +from _typeshed import Incomplete, SupportsRead +from builtins import list as _list +from collections.abc import Iterator +from io import StringIO +from typing import IO, Any, Literal, TypedDict, overload, type_check_only + +from docker._types import JSON +from docker.api.build import _Filers + +from .resource import Collection, Model + +@type_check_only +class _ContainerLimits(TypedDict, total=False): + memory: int + memswap: int + cpushares: int + cpusetcpus: str + +class Image(Model): + @property + def labels(self) -> dict[str, Any]: ... + @property + def short_id(self) -> str: ... + @property + def tags(self) -> list[str]: ... + def history(self) -> list[Any]: ... + def remove(self, force: bool = False, noprune: bool = False) -> dict[str, Any]: ... + def save(self, chunk_size: int = 2097152, named: str | bool = False) -> Iterator[Any]: ... + # Please keep in sync with docker.api.image.ImageApiMixin.tag + def tag(self, repository: str, tag: str | None = None, *, force: bool = False) -> bool: ... + +class RegistryData(Model): + image_name: str + # Please keep in sync with docker.models.resource.Model.__init__ + def __init__(self, image_name: str, attrs=None, client=None, collection=None) -> None: ... + @property + def id(self) -> str: ... + @property + def short_id(self) -> str: ... + def pull(self, platform: str | None = None) -> Image: ... + def has_platform(self, platform): ... + def reload(self) -> None: ... + +class ImageCollection(Collection[Image]): + model: type[Image] + # Please keep in sync with docker.api.build.BuildApiMixin.build + def build( + self, + *, + path: str | None = None, + tag: str | None = None, + quiet: bool = False, + fileobj: StringIO | IO[bytes] | None = None, + nocache: bool = False, + rm: bool = False, + timeout: int | None = None, + custom_context: bool = False, + encoding: str | None = None, + pull: bool = False, + forcerm: bool = False, + dockerfile: str | None = None, + container_limits: _ContainerLimits | None = None, + decode: bool = False, + buildargs: dict[str, Any] | None = None, + gzip: bool = False, + shmsize: int | None = None, + labels: dict[str, Any] | None = None, + # need to use list, because the type must be json serializable + cache_from: _list[str] | None = None, + target: str | None = None, + network_mode: str | None = None, + squash: bool | None = None, + extra_hosts: _list[str] | dict[str, str] | None = None, + platform: str | None = None, + isolation: str | None = None, + use_config_proxy: bool = True, + ) -> tuple[Image, Iterator[JSON]]: ... + def get(self, name: str) -> Image: ... + def get_registry_data(self, name, auth_config: dict[str, Any] | None = None) -> RegistryData: ... + def list(self, name: str | None = None, all: bool = False, filters: dict[str, Any] | None = None) -> _list[Image]: ... + def load(self, data: bytes | SupportsRead[bytes]) -> _list[Image]: ... + + # Please keep in sync with docker.api.image.ImageApiMixin.pull + @overload + def pull( + self, + repository: str, + tag: str | None = None, + all_tags: Literal[False] = False, + *, + platform: str | None = None, + auth_config: dict[str, Any] | None = None, + ) -> Image: ... + @overload + def pull( + self, + repository: str, + tag: str | None = None, + *, + all_tags: Literal[True], + auth_config: dict[str, Any] | None = None, + platform: str | None = None, + ) -> _list[Image]: ... + @overload + def pull( + self, + repository: str, + tag: str | None, + all_tags: Literal[True], + *, + auth_config: dict[str, Any] | None = None, + platform: str | None = None, + ) -> _list[Image]: ... + + # Please keep in sync with docker.api.image.ImageApiMixin.push + def push(self, repository: str, tag: str | None = None, *, stream: bool = False, auth_config=None, decode: bool = False): ... + # Please keep in sync with docker.api.image.ImageApiMixin.remove_image + def remove(self, image: str, force: bool = False, noprune: bool = False) -> None: ... + # Please keep in sync with docker.api.image.ImageApiMixin.search + def search(self, term: str, limit: int | None = None): ... + def prune(self, filters: dict[str, Any] | None = None): ... + # Please keep in sync with docker.api.build.BuildApiMixin.prune_builds + def prune_builds( + self, filters: _Filers | None = None, keep_storage: int | None = None, all: bool | None = None + ) -> dict[str, Incomplete]: ... + +def normalize_platform(platform, engine_info): ... diff --git a/stubs/docker/docker/models/networks.pyi b/stubs/docker/docker/models/networks.pyi new file mode 100644 index 000000000000..d1679aa9f397 --- /dev/null +++ b/stubs/docker/docker/models/networks.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete +from builtins import list as _list +from collections.abc import Iterable +from typing import Any, Literal + +from docker.types import IPAMConfig + +from .containers import Container +from .resource import Collection, Model + +class Network(Model): + @property + def name(self) -> str | None: ... + @property + def containers(self) -> list[Container]: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.connect_container_to_network + def connect( + self, + container: str | Container, + ipv4_address=None, + ipv6_address=None, + aliases=None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + link_local_ips=None, + driver_opt=None, + mac_address=None, + ) -> None: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.disconnect_container_from_network + def disconnect(self, container: str | Container, force: bool = False) -> None: ... + def remove(self) -> None: ... + +class NetworkCollection(Collection[Network]): + model: type[Network] + # Please keep in sync with docker.api.network.NetworkApiMixin.create_network + def create( # type: ignore[override] + self, + name: str, + driver: str | None = None, + options: dict[str, Any] | None = None, + ipam: IPAMConfig | None = None, + check_duplicate: bool | None = None, + internal: bool = False, + labels: dict[str, Any] | None = None, + enable_ipv6: bool = False, + attachable: bool | None = None, + scope: Literal["local", "global", "swarm"] | None = None, + ingress: bool | None = None, + ) -> Network: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.inspect_network + def get( # type: ignore[override] + self, network_id: str, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None + ) -> Network: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.networks + def list( + self, names: _list[Incomplete] | None = None, ids: _list[Incomplete] | None = None, filters=None, *, greedy: bool = False + ) -> _list[Network]: ... + def prune(self, filters: dict[str, Incomplete] | None = None) -> dict[str, Any]: ... diff --git a/stubs/docker/docker/models/nodes.pyi b/stubs/docker/docker/models/nodes.pyi new file mode 100644 index 000000000000..ecf780c29378 --- /dev/null +++ b/stubs/docker/docker/models/nodes.pyi @@ -0,0 +1,17 @@ +from builtins import list as _list +from typing import Any, Literal + +from .resource import Collection, Model + +class Node(Model): + id_attribute: str + @property + def version(self) -> int: ... + def update(self, node_spec) -> Literal[True]: ... + def remove(self, force: bool = False) -> Literal[True]: ... + +class NodeCollection(Collection[Node]): + model: type[Node] + def get(self, node_id) -> Node: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.nodes + def list(self, filters: dict[str, Any] | None = None) -> _list[Node]: ... # Any: filter values + Node response diff --git a/stubs/docker/docker/models/plugins.pyi b/stubs/docker/docker/models/plugins.pyi new file mode 100644 index 000000000000..68c672edd038 --- /dev/null +++ b/stubs/docker/docker/models/plugins.pyi @@ -0,0 +1,26 @@ +from builtins import list as _list +from collections.abc import Generator +from typing import Any + +from .resource import Collection, Model + +class Plugin(Model): + @property + def name(self) -> str | None: ... + @property + def enabled(self) -> bool | None: ... + @property + def settings(self) -> dict[str, Any] | None: ... + def configure(self, options: dict[str, Any]) -> None: ... + def disable(self, force: bool = False) -> None: ... + def enable(self, timeout: int = 0) -> None: ... + def push(self) -> Generator[dict[str, Any]]: ... + def remove(self, force: bool = False) -> bool: ... + def upgrade(self, remote: str | None = None) -> Generator[dict[str, Any]]: ... + +class PluginCollection(Collection[Plugin]): + model: type[Plugin] + def create(self, name, plugin_data_dir, gzip: bool = False): ... # type: ignore[override] + def get(self, name): ... + def install(self, remote_name, local_name=None): ... + def list(self) -> _list[Plugin]: ... diff --git a/stubs/docker/docker/models/resource.pyi b/stubs/docker/docker/models/resource.pyi new file mode 100644 index 000000000000..4e22b67516ff --- /dev/null +++ b/stubs/docker/docker/models/resource.pyi @@ -0,0 +1,33 @@ +from builtins import list as _list +from typing import Any, Generic, TypeVar +from typing_extensions import Never, Self + +from docker import DockerClient + +_T = TypeVar("_T", bound=Model) + +class Model: + id_attribute: str + client: DockerClient | None + collection: Collection[Self] | None + attrs: dict[str, Any] + def __init__( + self, attrs: dict[str, Any] | None = None, client: DockerClient | None = None, collection: Collection[Self] | None = None + ) -> None: ... + def __eq__(self, other) -> bool: ... + def __hash__(self) -> int: ... + @property + def id(self) -> str | None: ... + @property + def short_id(self) -> str: ... + def reload(self) -> None: ... + +class Collection(Generic[_T]): + model: type[_T] + client: DockerClient + def __init__(self, client: DockerClient | None = None) -> None: ... + def __call__(self, *args, **kwargs) -> Never: ... + def list(self) -> _list[_T]: ... + def get(self, key: str) -> _T: ... + def create(self, attrs: Any | None = None) -> _T: ... + def prepare_model(self, attrs: Model | dict[str, Any]) -> _T: ... diff --git a/stubs/docker/docker/models/secrets.pyi b/stubs/docker/docker/models/secrets.pyi new file mode 100644 index 000000000000..0e5137542eb1 --- /dev/null +++ b/stubs/docker/docker/models/secrets.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from docker.types import DriverConfig + +from .resource import Collection, Model + +class Secret(Model): + id_attribute: str + @property + def name(self) -> str: ... + def remove(self) -> bool: ... + +class SecretCollection(Collection[Secret]): + model: type[Secret] + # Please keep in sync with docker.api.secret.SecretApiMixin.create_secret + def create( # type: ignore[override] + self, *, name: str, data: bytes, labels: dict[str, Incomplete] | None = None, driver: DriverConfig | None = None + ) -> Secret: ... + def get(self, secret_id: str) -> Secret: ... + # Please keep in sync with docker.api.secret.SecretApiMixin.secrets + def list(self, *, filters: dict[str, Incomplete] | None = None) -> _list[Secret]: ... diff --git a/stubs/docker/docker/models/services.pyi b/stubs/docker/docker/models/services.pyi new file mode 100644 index 000000000000..1dc00693427e --- /dev/null +++ b/stubs/docker/docker/models/services.pyi @@ -0,0 +1,39 @@ +from builtins import list as _list + +from .resource import Collection, Model + +class Service(Model): + id_attribute: str + @property + def name(self): ... + @property + def version(self): ... + def remove(self): ... + def tasks(self, filters=None): ... + def update(self, **kwargs): ... + # Please keep in sync with docker.api.service.ServiceApiMixin.service_logs + def logs( + self, + *, + details: bool = False, + follow: bool = False, + stdout: bool = False, + stderr: bool = False, + since: int = 0, + timestamps: bool = False, + tail: str = "all", + ): ... + def scale(self, replicas: int | None): ... + def force_update(self): ... + +class ServiceCollection(Collection[Service]): + model: type[Service] + def create(self, image, command=None, **kwargs): ... # type: ignore[override] + def get(self, service_id, insert_defaults=None): ... + # Please keep in sync with docker.api.service.ServiceApiMixin.services + def list(self, *, filters=None, status=None) -> _list[Service]: ... + +CONTAINER_SPEC_KWARGS: list[str] +TASK_TEMPLATE_KWARGS: list[str] +CREATE_SERVICE_KWARGS: list[str] +PLACEMENT_KWARGS: list[str] diff --git a/stubs/docker/docker/models/swarm.pyi b/stubs/docker/docker/models/swarm.pyi new file mode 100644 index 000000000000..f8a5dd9f9934 --- /dev/null +++ b/stubs/docker/docker/models/swarm.pyi @@ -0,0 +1,78 @@ +from collections.abc import Iterable +from typing import Any + +from docker.types.services import DriverConfig +from docker.types.swarm import SwarmExternalCA + +from .resource import Model + +class Swarm(Model): + id_attribute: str + @property + def version(self) -> str | None: ... + def get_unlock_key(self) -> dict[str, Any]: ... + def init( + self, + advertise_addr: str | None = None, + listen_addr: str = "0.0.0.0:2377", + force_new_cluster: bool = False, + default_addr_pool: Iterable[str] | None = None, + subnet_size: int | None = None, + data_path_addr: str | None = None, + data_path_port: int | None = None, + *, # Please keep in sync with docker.api.swarm.SwarmApiMixin.create_swarm_spec + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> str: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.join_swarm + def join( + self, + remote_addrs: list[str], + join_token: str, + listen_addr: str = "0.0.0.0:2377", + advertise_addr: str | None = None, + data_path_addr: str | None = None, + ) -> bool: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.leave_swarm + def leave(self, force: bool = False) -> bool: ... + def reload(self) -> None: ... + def unlock(self, key: str) -> bool: ... + def update( + self, + rotate_worker_token: bool = False, + rotate_manager_token: bool = False, + rotate_manager_unlock_key: bool = False, + *, # Please keep in sync with docker.api.swarm.SwarmApiMixin.create_swarm_spec + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> bool: ... diff --git a/stubs/docker/docker/models/volumes.pyi b/stubs/docker/docker/models/volumes.pyi new file mode 100644 index 000000000000..b33cfb30557c --- /dev/null +++ b/stubs/docker/docker/models/volumes.pyi @@ -0,0 +1,26 @@ +from builtins import list as _list +from typing import Any + +from .resource import Collection, Model + +class Volume(Model): + id_attribute: str + @property + def name(self) -> str: ... + def remove(self, force: bool = False) -> None: ... + +class VolumeCollection(Collection[Volume]): + model: type[Volume] + # Please keep in sync with docker.api.volume.VolumeApiMixin.create_volume + def create( # type: ignore[override] + self, + name: str | None = None, + *, + driver: str | None = None, + driver_opts: dict[str, Any] | None = None, + labels: dict[str, Any] | None = None, + ) -> Volume: ... + def get(self, volume_id: str) -> Volume: ... + # Please keep in sync with docker.api.volume.VolumeApiMixin.create_volume + def list(self, *, filters: dict[str, Any] | None = None) -> _list[Volume]: ... + def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... diff --git a/stubs/docker/docker/tls.pyi b/stubs/docker/docker/tls.pyi new file mode 100644 index 000000000000..e7d4a0cbe938 --- /dev/null +++ b/stubs/docker/docker/tls.pyi @@ -0,0 +1,10 @@ +from docker import APIClient + +class TLSConfig: + cert: tuple[str, str] | None + ca_cert: str | None + verify: bool | str | None + def __init__( + self, client_cert: tuple[str, str] | None = None, ca_cert: str | None = None, verify: bool | str | None = None + ) -> None: ... + def configure_client(self, client: APIClient) -> None: ... diff --git a/stubs/docker/docker/transport/__init__.pyi b/stubs/docker/docker/transport/__init__.pyi new file mode 100644 index 000000000000..69637bbd0ef8 --- /dev/null +++ b/stubs/docker/docker/transport/__init__.pyi @@ -0,0 +1,4 @@ +from .npipeconn import NpipeHTTPAdapter as NpipeHTTPAdapter +from .npipesocket import NpipeSocket as NpipeSocket +from .sshconn import SSHHTTPAdapter as SSHHTTPAdapter +from .unixconn import UnixHTTPAdapter as UnixHTTPAdapter diff --git a/stubs/docker/docker/transport/basehttpadapter.pyi b/stubs/docker/docker/transport/basehttpadapter.pyi new file mode 100644 index 000000000000..efa32eef4f7d --- /dev/null +++ b/stubs/docker/docker/transport/basehttpadapter.pyi @@ -0,0 +1,14 @@ +from collections.abc import Mapping + +import requests.adapters +from urllib3.connectionpool import ConnectionPool + +class BaseHTTPAdapter(requests.adapters.HTTPAdapter): + def close(self) -> None: ... + def get_connection_with_tls_context( + self, + request: requests.PreparedRequest, + verify: bool | str | None, + proxies: Mapping[str, str] | None = None, + cert: tuple[str, str] | str | None = None, + ) -> ConnectionPool: ... diff --git a/stubs/docker/docker/transport/npipeconn.pyi b/stubs/docker/docker/transport/npipeconn.pyi new file mode 100644 index 000000000000..c4d5e1c3787c --- /dev/null +++ b/stubs/docker/docker/transport/npipeconn.pyi @@ -0,0 +1,29 @@ +import urllib3 +import urllib3.connection +from docker.transport.basehttpadapter import BaseHTTPAdapter +from docker.transport.npipesocket import NpipeSocket +from urllib3._collections import RecentlyUsedContainer as urllib3_RecentlyUsedContainer + +RecentlyUsedContainer = urllib3_RecentlyUsedContainer + +class NpipeHTTPConnection(urllib3.connection.HTTPConnection): + npipe_path: str + timeout: int + def __init__(self, npipe_path: str, timeout: int = 60) -> None: ... + sock: NpipeSocket | None + def connect(self) -> None: ... + +class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + npipe_path: str + timeout: urllib3.Timeout + def __init__(self, npipe_path: str, timeout: int = 60, maxsize: int = 10) -> None: ... + +class NpipeHTTPAdapter(BaseHTTPAdapter): + __attrs__: list[str] + npipe_path: str + timeout: int + max_pool_size: int + pools: RecentlyUsedContainer + def __init__(self, base_url: str, timeout: int = 60, pool_connections: int = 25, max_pool_size: int = 10) -> None: ... + def get_connection(self, url, proxies=None): ... + def request_url(self, request, proxies): ... diff --git a/stubs/docker/docker/transport/npipesocket.pyi b/stubs/docker/docker/transport/npipesocket.pyi new file mode 100644 index 000000000000..f68d4785b082 --- /dev/null +++ b/stubs/docker/docker/transport/npipesocket.pyi @@ -0,0 +1,57 @@ +import io +from _typeshed import ReadableBuffer +from typing import Any, Literal, TypeAlias +from typing_extensions import Never + +cERROR_PIPE_BUSY: int +cSECURITY_SQOS_PRESENT: int +cSECURITY_ANONYMOUS: int +MAXIMUM_RETRY_COUNT: int + +def check_closed(f): ... + +_PyHANDLE: TypeAlias = Any # pywin32._win32typing.PyHANDLE + +class NpipeSocket: + def __init__(self, handle: _PyHANDLE | None = None) -> None: ... + def accept(self) -> None: ... + def bind(self, address) -> None: ... + def close(self) -> None: ... + flags: int + def connect(self, address: str, retry_count: int = 0) -> None: ... + def connect_ex(self, address: str) -> None: ... + def detach(self) -> _PyHANDLE | None: ... + def dup(self) -> NpipeSocket: ... + def getpeername(self) -> str: ... + def getsockname(self) -> str: ... + # NotImplementedError + def getsockopt(self, level, optname, buflen=None) -> Never: ... + # NotImplementedError + def ioctl(self, control, option) -> Never: ... + # NotImplementedError + def listen(self, backlog) -> Never: ... + def makefile(self, mode: str | None = None, bufsize: int | None = None) -> io.BufferedReader: ... + def recv(self, bufsize: int, flags: int = 0) -> str: ... + def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[str, str]: ... + def recvfrom_into(self, buf: memoryview | ReadableBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, str]: ... + def recv_into(self, buf: memoryview | ReadableBuffer, nbytes: int = 0) -> int: ... + def send(self, string: str, flags: int = 0) -> int: ... + def sendall(self, string: str, flags: int = 0) -> int: ... + def sendto(self, string: str, address: str) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def settimeout(self, value: float | None) -> None: ... + def gettimeout(self) -> int | None: ... + # NotImplementedError + def setsockopt(self, level, optname, value) -> Never: ... + def shutdown(self, how) -> None: ... + +class NpipeFileIOBase(io.RawIOBase): + sock: NpipeSocket + def __init__(self, npipe_socket: NpipeSocket) -> None: ... + def close(self) -> None: ... + def fileno(self): ... + def isatty(self) -> Literal[False]: ... + def readable(self) -> Literal[True]: ... + def readinto(self, buf: memoryview | ReadableBuffer) -> int: ... + def seekable(self) -> Literal[False]: ... + def writable(self) -> Literal[False]: ... diff --git a/stubs/docker/docker/transport/sshconn.pyi b/stubs/docker/docker/transport/sshconn.pyi new file mode 100644 index 000000000000..c184ecb5d3e6 --- /dev/null +++ b/stubs/docker/docker/transport/sshconn.pyi @@ -0,0 +1,53 @@ +import socket +import subprocess + +import urllib3 +import urllib3.connection +from docker.transport.basehttpadapter import BaseHTTPAdapter +from paramiko import SSHClient, Transport +from urllib3._collections import RecentlyUsedContainer as urllib3_RecentlyUsedContainer + +RecentlyUsedContainer = urllib3_RecentlyUsedContainer + +class SSHSocket(socket.socket): + host: str + port: str | None + user: str | None + proc: subprocess.Popen[bytes] | None + def __init__(self, host: str) -> None: ... + def connect(self, **kwargs) -> None: ... # type: ignore[override] + def sendall(self, data) -> None: ... # type: ignore[override] + def send(self, data): ... # type: ignore[override] + def recv(self, n): ... # type: ignore[override] + def makefile(self, mode): ... # type: ignore[override] + def close(self) -> None: ... + +class SSHConnection(urllib3.connection.HTTPConnection): + ssh_transport: Transport | None + timeout: int + ssh_host: str | None + def __init__(self, ssh_transport: Transport | None = None, timeout: int = 60, host: str | None = None) -> None: ... + sock: SSHSocket | None + def connect(self) -> None: ... + +class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + scheme: str + ssh_transport: Transport | None + timeout: urllib3.Timeout + ssh_host: str | None + def __init__( + self, ssh_client: SSHClient | None = None, timeout: int = 60, maxsize: int = 10, host: str | None = None + ) -> None: ... + +class SSHHTTPAdapter(BaseHTTPAdapter): + __attrs__: list[str] + ssh_client: SSHClient | None + ssh_host: str + timeout: int + max_pool_size: int + pools: int + def __init__( + self, base_url: str, timeout: int = 60, pool_connections: int = 25, max_pool_size: int = 10, shell_out: bool = False + ) -> None: ... + def get_connection(self, url: str | bytes, proxies=None) -> SSHConnectionPool: ... + def close(self) -> None: ... diff --git a/stubs/docker/docker/transport/unixconn.pyi b/stubs/docker/docker/transport/unixconn.pyi new file mode 100644 index 000000000000..b2124a79fb90 --- /dev/null +++ b/stubs/docker/docker/transport/unixconn.pyi @@ -0,0 +1,34 @@ +import socket + +import urllib3 +import urllib3.connection +from docker.transport.basehttpadapter import BaseHTTPAdapter +from requests import PreparedRequest +from urllib3._collections import RecentlyUsedContainer as urllib3_RecentlyUsedContainer + +RecentlyUsedContainer = urllib3_RecentlyUsedContainer + +class UnixHTTPConnection(urllib3.connection.HTTPConnection): + base_url: str + unix_socket: str + timeout: int + def __init__(self, base_url: str, unix_socket: str, timeout: int = 60) -> None: ... + sock: socket.socket | None + def connect(self) -> None: ... + +class UnixHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + base_url: str + socket_path: str + timeout: urllib3.Timeout + def __init__(self, base_url: str, socket_path: str, timeout: int = 60, maxsize: int = 10) -> None: ... + +class UnixHTTPAdapter(BaseHTTPAdapter): + __attrs__: list[str] + socket_path: str + timeout: int + max_pool_size: int + pools: RecentlyUsedContainer + def __init__(self, socket_url: str, timeout: int = 60, pool_connections: int = 25, max_pool_size: int = 10) -> None: ... + def get_connection(self, url: bytes | str, proxies=None) -> UnixHTTPConnectionPool: ... + # proxies is unused + def request_url(self, request: PreparedRequest, proxies) -> str: ... diff --git a/stubs/docker/docker/types/__init__.pyi b/stubs/docker/docker/types/__init__.pyi new file mode 100644 index 000000000000..9404c047fe2b --- /dev/null +++ b/stubs/docker/docker/types/__init__.pyi @@ -0,0 +1,35 @@ +from .containers import ( + ContainerConfig as ContainerConfig, + DeviceRequest as DeviceRequest, + HostConfig as HostConfig, + LogConfig as LogConfig, + Ulimit as Ulimit, +) +from .daemon import CancellableStream as CancellableStream +from .healthcheck import Healthcheck as Healthcheck +from .networks import ( + EndpointConfig as EndpointConfig, + IPAMConfig as IPAMConfig, + IPAMPool as IPAMPool, + NetworkingConfig as NetworkingConfig, +) +from .services import ( + ConfigReference as ConfigReference, + ContainerSpec as ContainerSpec, + DNSConfig as DNSConfig, + DriverConfig as DriverConfig, + EndpointSpec as EndpointSpec, + Mount as Mount, + NetworkAttachmentConfig as NetworkAttachmentConfig, + Placement as Placement, + PlacementPreference as PlacementPreference, + Privileges as Privileges, + Resources as Resources, + RestartPolicy as RestartPolicy, + RollbackConfig as RollbackConfig, + SecretReference as SecretReference, + ServiceMode as ServiceMode, + TaskTemplate as TaskTemplate, + UpdateConfig as UpdateConfig, +) +from .swarm import SwarmExternalCA as SwarmExternalCA, SwarmSpec as SwarmSpec diff --git a/stubs/docker/docker/types/base.pyi b/stubs/docker/docker/types/base.pyi new file mode 100644 index 000000000000..913e6261d85c --- /dev/null +++ b/stubs/docker/docker/types/base.pyi @@ -0,0 +1,7 @@ +from collections.abc import Mapping +from typing import TypeVar + +_VT = TypeVar("_VT") + +class DictType(dict[str, _VT]): + def __init__(self, init: Mapping[str, _VT]) -> None: ... diff --git a/stubs/docker/docker/types/containers.pyi b/stubs/docker/docker/types/containers.pyi new file mode 100644 index 000000000000..98b38ffc069e --- /dev/null +++ b/stubs/docker/docker/types/containers.pyi @@ -0,0 +1,199 @@ +import builtins +from collections.abc import Iterable, Mapping +from typing import Any, Final, Literal + +from docker._types import ContainerWeightDevice + +from .. import errors +from .base import DictType +from .healthcheck import Healthcheck +from .networks import NetworkingConfig +from .services import Mount + +class LogConfigTypesEnum: + JSON: Final = "json-file" + SYSLOG: Final = "syslog" + JOURNALD: Final = "journald" + GELF: Final = "gelf" + FLUENTD: Final = "fluentd" + NONE: Final = "none" + +class LogConfig(DictType[Any]): + types: builtins.type[LogConfigTypesEnum] + def __init__(self, *, type: str = ..., Type: str = ..., config: dict[str, str] = {}, Config: dict[str, str] = {}) -> None: ... + + @property + def type(self) -> str: ... + @type.setter + def type(self, value: str) -> None: ... + + @property + def config(self) -> dict[str, str]: ... + def set_config_value(self, key: str, value: str) -> None: ... + def unset_config(self, key: str) -> None: ... + +class Ulimit(DictType[Any]): + def __init__( + self, *, name: str = ..., Name: str = ..., soft: int = ..., Soft: int = ..., hard: int = ..., Hard: int = ... + ) -> None: ... + + @property + def name(self) -> str: ... + @name.setter + def name(self, value: str) -> None: ... + + @property + def soft(self) -> int | None: ... + @soft.setter + def soft(self, value: int | None) -> None: ... + + @property + def hard(self) -> int | None: ... + @hard.setter + def hard(self, value: int | None) -> None: ... + +class DeviceRequest(DictType[Any]): + def __init__( + self, + *, + driver: str = ..., + Driver: str = ..., + count: int = ..., + Count: int = ..., + device_ids: list[str] = ..., + DeviceIDs: list[str] = ..., + capabilities: list[list[str]] = ..., + Capabilities: list[list[str]] = ..., + options: dict[str, str] = ..., + Options: dict[str, str] = ..., + ) -> None: ... + + @property + def driver(self) -> str: ... + @driver.setter + def driver(self, value: str) -> None: ... + + @property + def count(self) -> int: ... + @count.setter + def count(self, value: int) -> None: ... + + @property + def device_ids(self) -> list[str]: ... + @device_ids.setter + def device_ids(self, value: list[str]) -> None: ... + + @property + def capabilities(self) -> list[list[str]]: ... + @capabilities.setter + def capabilities(self, value: list[list[str]]) -> None: ... + + @property + def options(self) -> dict[str, str]: ... + @options.setter + def options(self, value: dict[str, str]) -> None: ... + +class HostConfig(dict[str, Any]): + def __init__( + self, + version: str, + binds: dict[str, Mapping[str, str]] | list[str] | None = None, + port_bindings: Mapping[int | str, Any] | None = None, # Any: int, str, tuple, dict, or list + lxc_conf: dict[str, str] | list[dict[str, str]] | None = None, + publish_all_ports: bool = False, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + privileged: bool = False, + dns: list[str] | None = None, + dns_search: list[str] | None = None, + volumes_from: list[str] | None = None, + network_mode: str | None = None, + restart_policy: Mapping[str, str | int] | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + devices: list[str] | None = None, + extra_hosts: dict[str, str] | list[str] | None = None, + read_only: bool | None = None, + pid_mode: str | None = None, + ipc_mode: str | None = None, + security_opt: list[str] | None = None, + ulimits: list[Ulimit] | None = None, + log_config: LogConfig | None = None, + mem_limit: str | int | None = None, + memswap_limit: str | int | None = None, + mem_reservation: str | int | None = None, + kernel_memory: str | int | None = None, + mem_swappiness: int | None = None, + cgroup_parent: str | None = None, + group_add: Iterable[str | int] | None = None, + cpu_quota: int | None = None, + cpu_period: int | None = None, + blkio_weight: int | None = None, + blkio_weight_device: list[ContainerWeightDevice] | None = None, + device_read_bps: list[Mapping[str, str | int]] | None = None, + device_write_bps: list[Mapping[str, str | int]] | None = None, + device_read_iops: list[Mapping[str, str | int]] | None = None, + device_write_iops: list[Mapping[str, str | int]] | None = None, + oom_kill_disable: bool = False, + shm_size: str | int | None = None, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + oom_score_adj: int | None = None, + dns_opt: list[str] | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + pids_limit: int | None = None, + isolation: str | None = None, + auto_remove: bool = False, + storage_opt: dict[str, str] | None = None, + init: bool | None = None, + init_path: str | None = None, + volume_driver: str | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + nano_cpus: int | None = None, + cpuset_mems: str | None = None, + runtime: str | None = None, + mounts: list[Mount] | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + device_cgroup_rules: list[str] | None = None, + device_requests: list[DeviceRequest] | None = None, + cgroupns: Literal["private", "host"] | None = None, + ) -> None: ... + +def host_config_type_error(param: str, param_value: object, expected: str) -> TypeError: ... +def host_config_version_error(param: str, version: str, less_than: bool = True) -> errors.InvalidVersion: ... +def host_config_value_error(param: str, param_value: object) -> ValueError: ... +def host_config_incompatible_error(param: str, param_value: str, incompatible_param: str) -> errors.InvalidArgument: ... + +class ContainerConfig(dict[str, Any]): + def __init__( + self, + version: str, + image: str, + command: str | list[str], + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[str, str]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config: HostConfig | None = None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config: NetworkingConfig | None = None, + healthcheck: Healthcheck | None = None, + stop_timeout: int | None = None, + runtime: str | None = None, + ) -> None: ... diff --git a/stubs/docker/docker/types/daemon.pyi b/stubs/docker/docker/types/daemon.pyi new file mode 100644 index 000000000000..6561a772fc7a --- /dev/null +++ b/stubs/docker/docker/types/daemon.pyi @@ -0,0 +1,14 @@ +from collections.abc import Iterator +from typing import Generic, TypeVar +from typing_extensions import Self + +from requests import Response + +_T_co = TypeVar("_T_co", covariant=True) + +class CancellableStream(Generic[_T_co]): + def __init__(self, stream: Iterator[_T_co], response: Response) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + next = __next__ + def close(self) -> None: ... diff --git a/stubs/docker/docker/types/healthcheck.pyi b/stubs/docker/docker/types/healthcheck.pyi new file mode 100644 index 000000000000..c113c3fb2b28 --- /dev/null +++ b/stubs/docker/docker/types/healthcheck.pyi @@ -0,0 +1,44 @@ +from typing import Any + +from .base import DictType + +class Healthcheck(DictType[Any]): + def __init__( + self, + *, + test: str | list[str] | None = None, + Test: str | list[str] | None = None, + interval: int | None = None, + Interval: int | None = None, + timeout: int | None = None, + Timeout: int | None = None, + retries: int | None = None, + Retries: int | None = None, + start_period: int | None = None, + StartPeriod: int | None = None, + ) -> None: ... + + @property + def test(self) -> list[str] | None: ... + @test.setter + def test(self, value: str | list[str] | None) -> None: ... + + @property + def interval(self) -> int | None: ... + @interval.setter + def interval(self, value: int | None) -> None: ... + + @property + def timeout(self) -> int | None: ... + @timeout.setter + def timeout(self, value: int | None) -> None: ... + + @property + def retries(self) -> int | None: ... + @retries.setter + def retries(self, value: int | None) -> None: ... + + @property + def start_period(self) -> int | None: ... + @start_period.setter + def start_period(self, value: int | None) -> None: ... diff --git a/stubs/docker/docker/types/networks.pyi b/stubs/docker/docker/types/networks.pyi new file mode 100644 index 000000000000..bf9e5d027714 --- /dev/null +++ b/stubs/docker/docker/types/networks.pyi @@ -0,0 +1,32 @@ +from collections.abc import Iterable +from typing import Any + +class EndpointConfig(dict[str, Any]): + def __init__( + self, + version: str, + aliases: list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + ipv4_address: str | None = None, + ipv6_address: str | None = None, + link_local_ips: list[str] | None = None, + driver_opt: dict[str, str] | None = None, + mac_address: str | None = None, + ) -> None: ... + +class NetworkingConfig(dict[str, Any]): + def __init__(self, endpoints_config: EndpointConfig | None = None) -> None: ... + +class IPAMConfig(dict[str, Any]): + def __init__( + self, driver: str = "default", pool_configs: list[IPAMPool] | None = None, options: dict[str, str] | None = None + ) -> None: ... + +class IPAMPool(dict[str, Any]): + def __init__( + self, + subnet: str | None = None, + iprange: str | None = None, + gateway: str | None = None, + aux_addresses: dict[str, str] | None = None, + ) -> None: ... diff --git a/stubs/docker/docker/types/services.pyi b/stubs/docker/docker/types/services.pyi new file mode 100644 index 000000000000..b82487a83824 --- /dev/null +++ b/stubs/docker/docker/types/services.pyi @@ -0,0 +1,195 @@ +from collections.abc import Iterable, Mapping +from typing import Any, Final, Literal, TypedDict, TypeVar, overload, type_check_only + +from .healthcheck import Healthcheck + +_T = TypeVar("_T") + +class TaskTemplate(dict[str, Any]): + def __init__( + self, + container_spec: ContainerSpec, + resources: Resources | None = None, + restart_policy: RestartPolicy | None = None, + placement: Placement | list[str] | None = None, + log_driver: DriverConfig | None = None, + networks: Iterable[str | NetworkAttachmentConfig] | None = None, + force_update: int | None = None, + ) -> None: ... + @property + def container_spec(self) -> ContainerSpec: ... + @property + def resources(self) -> Resources: ... + @property + def restart_policy(self) -> RestartPolicy: ... + @property + def placement(self) -> Placement: ... + +class ContainerSpec(dict[str, Any]): + def __init__( + self, + image: str, + command: str | list[str] | None = None, + args: list[str] | None = None, + hostname: str | None = None, + env: dict[str, str | bytes | None] | list[str] | None = None, + workdir: str | None = None, + user: str | None = None, + labels: dict[str, str] | None = None, + mounts: Iterable[str | Mount] | None = None, + stop_grace_period: int | None = None, + secrets: list[SecretReference] | None = None, + tty: bool | None = None, + groups: list[str] | None = None, + open_stdin: bool | None = None, + read_only: bool | None = None, + stop_signal: str | None = None, + healthcheck: Healthcheck | None = None, + hosts: Mapping[str, str] | None = None, + dns_config: DNSConfig | None = None, + configs: list[ConfigReference] | None = None, + privileges: Privileges | None = None, + isolation: str | None = None, + init: bool | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + sysctls: dict[str, str] | None = None, + ) -> None: ... + +class Mount(dict[str, Any]): + def __init__( + self, + target: str, + source: str | None, + type: Literal["bind", "volume", "tmpfs", "npipe"] = "volume", + read_only: bool = False, + consistency: Literal["default", "consistent", "cached", "delegated"] | None = None, + propagation: str | None = None, + no_copy: bool = False, + labels: dict[str, str] | None = None, + driver_config: DriverConfig | None = None, + tmpfs_size: int | str | None = None, + tmpfs_mode: int | None = None, + subpath: str | None = None, + ) -> None: ... + @classmethod + def parse_mount_string(cls, string: str) -> Mount: ... + +@type_check_only +class _ResourceDict(TypedDict): + Kind: str + Value: int + +class Resources(dict[str, Any]): + def __init__( + self, + cpu_limit: int | None = None, + mem_limit: int | None = None, + cpu_reservation: int | None = None, + mem_reservation: int | None = None, + generic_resources: ( + dict[str, int | str] | list[dict[Literal["DiscreteResourceSpec", "NamedResourceSpec"], _ResourceDict]] | None + ) = None, + ) -> None: ... + +class UpdateConfig(dict[str, Any]): + def __init__( + self, + parallelism: int = 0, + delay: int | None = None, + failure_action: Literal["pause", "continue", "rollback"] = "continue", + monitor: int | None = None, + max_failure_ratio: float | None = None, + order: Literal["start-first", "stop-first"] | None = None, + ) -> None: ... + +class RollbackConfig(UpdateConfig): ... + +class RestartConditionTypesEnum: + NONE: Final = "none" + ON_FAILURE: Final = "on-failure" + ANY: Final = "any" + +class RestartPolicy(dict[str, Any]): + condition_types: type[RestartConditionTypesEnum] + def __init__( + self, condition: Literal["none", "on-failure", "any"] = "none", delay: int = 0, max_attempts: int = 0, window: int = 0 + ) -> None: ... + +class DriverConfig(dict[str, Any]): + def __init__(self, name: str, options: dict[str, str] | None = None) -> None: ... + +class EndpointSpec(dict[str, Any]): + def __init__( + self, mode: str | None = None, ports: Mapping[str, str | tuple[str | None, ...]] | list[dict[str, str]] | None = None + ) -> None: ... + +@overload +def convert_service_ports(ports: list[_T]) -> list[_T]: ... +@overload +def convert_service_ports(ports: Mapping[str, str | tuple[str | None, ...]]) -> list[dict[str, str]]: ... + +class ServiceMode(dict[str, Any]): + mode: Literal["replicated", "global", "ReplicatedJob", "GlobalJob"] + def __init__( + self, + mode: Literal["replicated", "global", "replicated-job", "global-job"], + replicas: int | None = None, + concurrency: int | None = None, + ) -> None: ... + @property + def replicas(self) -> int | None: ... + +class SecretReference(dict[str, Any]): + def __init__( + self, + secret_id: str, + secret_name: str, + filename: str | None = None, + uid: str | None = None, + gid: str | None = None, + mode: int = 292, + ) -> None: ... + +class ConfigReference(dict[str, Any]): + def __init__( + self, + config_id: str, + config_name: str, + filename: str | None = None, + uid: str | None = None, + gid: str | None = None, + mode: int = 292, + ) -> None: ... + +class Placement(dict[str, Any]): + def __init__( + self, + constraints: list[str] | None = None, + preferences: Iterable[tuple[str, str] | PlacementPreference] | None = None, + platforms: Iterable[tuple[str, str]] | None = None, + maxreplicas: int | None = None, + ) -> None: ... + +class PlacementPreference(dict[str, Any]): + def __init__(self, strategy: Literal["spread"], descriptor: str) -> None: ... + +class DNSConfig(dict[str, Any]): + def __init__( + self, nameservers: list[str] | None = None, search: list[str] | None = None, options: list[str] | None = None + ) -> None: ... + +class Privileges(dict[str, Any]): + def __init__( + self, + credentialspec_file: str | None = None, + credentialspec_registry: str | None = None, + selinux_disable: bool | None = None, + selinux_user: str | None = None, + selinux_role: str | None = None, + selinux_type: str | None = None, + selinux_level: str | None = None, + ) -> None: ... + +class NetworkAttachmentConfig(dict[str, Any]): + def __init__(self, target: str, aliases: list[str] | None = None, options: dict[str, str] | None = None) -> None: ... diff --git a/stubs/docker/docker/types/swarm.pyi b/stubs/docker/docker/types/swarm.pyi new file mode 100644 index 000000000000..b7d81fe5cfea --- /dev/null +++ b/stubs/docker/docker/types/swarm.pyi @@ -0,0 +1,30 @@ +from typing import Any + +from .services import DriverConfig + +class SwarmSpec(dict[str, Any]): + def __init__( + self, + version: str, + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> None: ... + +class SwarmExternalCA(dict[str, Any]): + def __init__( + self, url: str, protocol: str | None = None, options: dict[str, str] | None = None, ca_cert: str | None = None + ) -> None: ... diff --git a/stubs/docker/docker/utils/__init__.pyi b/stubs/docker/docker/utils/__init__.pyi new file mode 100644 index 000000000000..608f91d1cf65 --- /dev/null +++ b/stubs/docker/docker/utils/__init__.pyi @@ -0,0 +1,32 @@ +from .build import ( + create_archive as create_archive, + exclude_paths as exclude_paths, + match_tag as match_tag, + mkbuildcontext as mkbuildcontext, + tar as tar, +) +from .decorators import check_resource as check_resource, minimum_version as minimum_version, update_headers as update_headers +from .utils import ( + compare_version as compare_version, + convert_filters as convert_filters, + convert_port_bindings as convert_port_bindings, + convert_service_networks as convert_service_networks, + convert_volume_binds as convert_volume_binds, + create_host_config as create_host_config, + create_ipam_config as create_ipam_config, + create_ipam_pool as create_ipam_pool, + datetime_to_timestamp as datetime_to_timestamp, + decode_json_header as decode_json_header, + format_environment as format_environment, + format_extra_hosts as format_extra_hosts, + kwargs_from_env as kwargs_from_env, + normalize_links as normalize_links, + parse_bytes as parse_bytes, + parse_devices as parse_devices, + parse_env_file as parse_env_file, + parse_host as parse_host, + parse_repository_tag as parse_repository_tag, + split_command as split_command, + version_gte as version_gte, + version_lt as version_lt, +) diff --git a/stubs/docker/docker/utils/build.pyi b/stubs/docker/docker/utils/build.pyi new file mode 100644 index 000000000000..ec168530da14 --- /dev/null +++ b/stubs/docker/docker/utils/build.pyi @@ -0,0 +1,39 @@ +import io +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Generator, Iterable, MutableSequence +from os import PathLike +from tarfile import _Fileobj +from tempfile import _TemporaryFileWrapper + +def match_tag(tag: str) -> bool: ... +def tar( + path: PathLike[str], + exclude: list[str] | None = None, + dockerfile: tuple[str | None, str | None] | None = None, + fileobj: _Fileobj | None = None, + gzip: bool = False, +) -> _TemporaryFileWrapper[bytes] | _Fileobj: ... +def exclude_paths(root: StrPath, patterns: MutableSequence[str], dockerfile: str | None = None) -> set[str]: ... +def build_file_list(root: str) -> list[str]: ... +def create_archive( + root: str, files: Iterable[str] | None = None, fileobj: _Fileobj | None = None, gzip: bool = False, extra_files=None +) -> _TemporaryFileWrapper[bytes] | _Fileobj: ... +def mkbuildcontext(dockerfile: io.IOBase | StrOrBytesPath) -> _TemporaryFileWrapper[bytes]: ... +def split_path(p: str) -> list[str]: ... +def normalize_slashes(p: str) -> str: ... +def walk(root: StrPath, patterns: Iterable[str], default: bool = True) -> Generator[str]: ... + +class PatternMatcher: + patterns: list[Pattern] + def __init__(self, patterns: Iterable[str]) -> None: ... + def matches(self, filepath: PathLike[str]) -> bool: ... + def walk(self, root: StrPath) -> Generator[str]: ... + +class Pattern: + exclusion: bool + dirs: list[str] + cleaned_pattern: str + def __init__(self, pattern_str: str) -> None: ... + @classmethod + def normalize(cls, p: str) -> list[str]: ... + def match(self, filepath: str) -> bool: ... diff --git a/stubs/docker/docker/utils/config.pyi b/stubs/docker/docker/utils/config.pyi new file mode 100644 index 000000000000..50941696e163 --- /dev/null +++ b/stubs/docker/docker/utils/config.pyi @@ -0,0 +1,12 @@ +from _typeshed import FileDescriptorOrPath +from logging import Logger +from typing import Final + +DOCKER_CONFIG_FILENAME: Final[str] +LEGACY_DOCKER_CONFIG_FILENAME: Final[str] +log: Logger + +def find_config_file(config_path: FileDescriptorOrPath | None = None) -> FileDescriptorOrPath | None: ... +def config_path_from_environment() -> str | None: ... +def home_dir() -> str: ... +def load_general_config(config_path: FileDescriptorOrPath | None = None): ... diff --git a/stubs/docker/docker/utils/decorators.pyi b/stubs/docker/docker/utils/decorators.pyi new file mode 100644 index 000000000000..2a8a68524cd5 --- /dev/null +++ b/stubs/docker/docker/utils/decorators.pyi @@ -0,0 +1,9 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +def check_resource(resource_name: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def minimum_version(version: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def update_headers(f: Callable[_P, _R]) -> Callable[_P, _R]: ... diff --git a/stubs/docker/docker/utils/fnmatch.pyi b/stubs/docker/docker/utils/fnmatch.pyi new file mode 100644 index 000000000000..631a71ee5c0a --- /dev/null +++ b/stubs/docker/docker/utils/fnmatch.pyi @@ -0,0 +1,5 @@ +__all__ = ["fnmatch", "fnmatchcase", "translate"] + +def fnmatch(name: str, pat: str) -> bool: ... +def fnmatchcase(name: str, pat: str) -> bool: ... +def translate(pat: str) -> str: ... diff --git a/stubs/docker/docker/utils/json_stream.pyi b/stubs/docker/docker/utils/json_stream.pyi new file mode 100644 index 000000000000..4805785eb27b --- /dev/null +++ b/stubs/docker/docker/utils/json_stream.pyi @@ -0,0 +1,15 @@ +import json +from collections.abc import Callable, Generator, Iterator +from typing import Any + +from docker._types import JSON + +json_decoder: json.JSONDecoder + +def stream_as_text(stream: Iterator[str | bytes]) -> Generator[str]: ... +def json_splitter(buffer: str) -> tuple[JSON, str] | None: ... +def json_stream(stream: Iterator[str]) -> Generator[JSON]: ... +def line_splitter(buffer: str, separator: str = "\n") -> tuple[str, str] | None: ... +def split_buffer( + stream: Iterator[str | bytes], splitter: Callable[[str], tuple[str, str]] | None = None, decoder: Callable[[str], Any] = ... +) -> Generator[Any]: ... diff --git a/stubs/docker/docker/utils/ports.pyi b/stubs/docker/docker/utils/ports.pyi new file mode 100644 index 000000000000..ffc6615f36b4 --- /dev/null +++ b/stubs/docker/docker/utils/ports.pyi @@ -0,0 +1,11 @@ +import re +from _typeshed import Incomplete +from typing import Final + +PORT_SPEC: Final[re.Pattern[str]] + +def add_port_mapping(port_bindings, internal_port, external) -> None: ... +def add_port(port_bindings, internal_port_range, external_range) -> None: ... +def build_port_bindings(ports) -> dict[Incomplete, Incomplete]: ... +def port_range(start, end, proto, randomly_available_port: bool = False): ... +def split_port(port: object) -> tuple[Incomplete, Incomplete]: ... diff --git a/stubs/docker/docker/utils/proxy.pyi b/stubs/docker/docker/utils/proxy.pyi new file mode 100644 index 000000000000..c0c5a038e45b --- /dev/null +++ b/stubs/docker/docker/utils/proxy.pyi @@ -0,0 +1,35 @@ +from collections.abc import Sequence +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +@type_check_only +class _ProxyConfigDict(TypedDict): + http: NotRequired[str] + https: NotRequired[str] + ftpProxy: NotRequired[str] + noProxy: NotRequired[str] + +@type_check_only +class _Environment(TypedDict): + http_proxy: NotRequired[str] + HTTP_PROXY: NotRequired[str] + https_proxy: NotRequired[str] + HTTPS_PROXY: NotRequired[str] + ftp_proxy: NotRequired[str] + FTP_PROXY: NotRequired[str] + no_proxy: NotRequired[str] + NO_PROXY: NotRequired[str] + +class ProxyConfig(dict[str, str]): + @property + def http(self) -> str | None: ... + @property + def https(self) -> str | None: ... + @property + def ftp(self) -> str | None: ... + @property + def no_proxy(self) -> str | None: ... + @staticmethod + def from_dict(config: _ProxyConfigDict) -> ProxyConfig: ... + def get_environment(self) -> _Environment: ... + def inject_proxy_environment(self, environment: Sequence[str] | None) -> Sequence[str] | None: ... diff --git a/stubs/docker/docker/utils/socket.pyi b/stubs/docker/docker/utils/socket.pyi new file mode 100644 index 000000000000..67e4caab2beb --- /dev/null +++ b/stubs/docker/docker/utils/socket.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Generator, Iterable +from typing import Final, Literal, TypeVar, overload + +_T = TypeVar("_T") + +STDOUT: Final = 1 +STDERR: Final = 2 + +class SocketError(Exception): ... + +NPIPE_ENDED: Final = 109 + +def read(socket, n: int = 4096): ... +def read_exactly(socket, n: int) -> bytes: ... +def next_frame_header(socket) -> tuple[Incomplete, int]: ... +def frames_iter(socket, tty): ... +def frames_iter_no_tty(socket) -> Generator[tuple[str | Incomplete, str | bytes | Incomplete]]: ... +def frames_iter_tty(socket) -> Generator[Incomplete]: ... + +@overload +def consume_socket_output( + frames: Iterable[tuple[Incomplete, Incomplete]], demux: Literal[True] +) -> tuple[Incomplete, Incomplete]: ... +@overload +def consume_socket_output(frames: Iterable[ReadableBuffer], demux: Literal[False] = False) -> bytes: ... + +@overload +def demux_adaptor(stream_id: Literal[1], data: _T) -> tuple[_T, None]: ... +@overload +def demux_adaptor(stream_id: Literal[2], data: _T) -> tuple[None, _T]: ... diff --git a/stubs/docker/docker/utils/utils.pyi b/stubs/docker/docker/utils/utils.pyi new file mode 100644 index 000000000000..7b248df23535 --- /dev/null +++ b/stubs/docker/docker/utils/utils.pyi @@ -0,0 +1,78 @@ +import datetime +from _typeshed import FileDescriptorOrPath, ReadableBuffer, Unused +from collections.abc import Iterable, Mapping +from shlex import _ShlexInstream +from typing import Literal, NamedTuple, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated + +from ..tls import TLSConfig + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +@type_check_only +class _EnvKWArgs(TypedDict, total=False): + base_url: str + tls: TLSConfig + +class URLComponents(NamedTuple): + scheme: str | None + netloc: str | None + url: str + params: str | None + query: str | None + fragment: str | None + +@deprecated("utils.create_ipam_pool has been removed. Please use a docker.types.IPAMPool object instead.") +def create_ipam_pool(*args: Unused, **kwargs: Unused) -> Never: ... +@deprecated("utils.create_ipam_config has been removed. Please use a docker.types.IPAMConfig object instead.") +def create_ipam_config(*args: Unused, **kwargs: Unused) -> Never: ... +def decode_json_header(header: str | ReadableBuffer): ... +def compare_version(v1: str, v2: str) -> Literal[0, -1, 1]: ... +def version_lt(v1: str, v2: str) -> bool: ... +def version_gte(v1: str, v2: str) -> bool: ... +def convert_port_bindings( + port_bindings: Mapping[str, int | list[int] | tuple[str, int] | None], +) -> dict[str, list[dict[str, str]]]: ... + +@overload +def convert_volume_binds(binds: list[_T]) -> list[_T]: ... +@overload +def convert_volume_binds(binds: Mapping[str | bytes, bytes | str | dict[str, bytes | str]]) -> list[str]: ... + +@overload +def convert_tmpfs_mounts(tmpfs: dict[_K, _V]) -> dict[_K, _V]: ... +@overload +def convert_tmpfs_mounts(tmpfs: list[str]) -> dict[str, str]: ... + +@overload +def convert_service_networks(networks: None) -> None: ... +@overload +def convert_service_networks(networks: list[str] | list[dict[str, str]] | list[str | dict[str, str]]) -> list[dict[str, str]]: ... + +def parse_repository_tag(repo_name: str) -> tuple[str, str | None]: ... + +@overload +def parse_host(addr: None, is_win32: Literal[True], tls: bool = False) -> Literal["npipe:////./pipe/docker_engine"]: ... +@overload +def parse_host( + addr: None, is_win32: Literal[False] = False, tls: bool = False +) -> Literal["http+unix:///var/run/docker.sock"]: ... +@overload +def parse_host(addr: str | None, is_win32: bool = False, tls: bool = False) -> str | bytes: ... + +def parse_devices(devices: Iterable[str | dict[str, str]]) -> list[dict[str, str]]: ... +def kwargs_from_env(environment: Mapping[str, str] | None = None) -> _EnvKWArgs: ... +def convert_filters(filters) -> str: ... +def datetime_to_timestamp(dt: datetime.datetime) -> int: ... +def parse_bytes(s: float | str) -> float: ... +def normalize_links(links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]]): ... +def parse_env_file(env_file: FileDescriptorOrPath) -> dict[str, str]: ... +def split_command(command: str | _ShlexInstream) -> list[str]: ... +def format_environment(environment: Mapping[str, object | None]) -> list[str]: ... +def format_extra_hosts( + extra_hosts: Mapping[object, object], task: bool = False # keys and values are converted to str +) -> list[str]: ... +@deprecated("utils.create_host_config has been removed. Please use a docker.types.HostConfig object instead.") +def create_host_config(self, *args: Unused, **kwargs: Unused) -> Never: ... diff --git a/stubs/docker/docker/version.pyi b/stubs/docker/docker/version.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/docker/docker/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/dockerfile-parse/METADATA.toml b/stubs/dockerfile-parse/METADATA.toml new file mode 100644 index 000000000000..8f5cd433f5de --- /dev/null +++ b/stubs/dockerfile-parse/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.*" +upstream-repository = "https://github.com/containerbuildsystem/dockerfile-parse" diff --git a/stubs/dockerfile-parse/dockerfile_parse/__init__.pyi b/stubs/dockerfile-parse/dockerfile_parse/__init__.pyi new file mode 100644 index 000000000000..53ccc597c4dc --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/__init__.pyi @@ -0,0 +1,5 @@ +from typing import Final + +from .parser import DockerfileParser as DockerfileParser + +__version__: Final[str] diff --git a/stubs/dockerfile-parse/dockerfile_parse/constants.pyi b/stubs/dockerfile-parse/dockerfile_parse/constants.pyi new file mode 100644 index 000000000000..9453a8eff553 --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/constants.pyi @@ -0,0 +1,4 @@ +from typing import Final + +DOCKERFILE_FILENAME: Final = "Dockerfile" +COMMENT_INSTRUCTION: Final = "COMMENT" diff --git a/stubs/dockerfile-parse/dockerfile_parse/parser.pyi b/stubs/dockerfile-parse/dockerfile_parse/parser.pyi new file mode 100644 index 000000000000..fbaa98096332 --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/parser.pyi @@ -0,0 +1,70 @@ +import logging +from collections.abc import Mapping, Sequence +from typing import IO, ClassVar, TypedDict, type_check_only + +from .util import Context + +logger: logging.Logger + +class KeyValues(dict[str, str]): + parser_attr: ClassVar[str | None] + parser: DockerfileParser + def __init__(self, key_values: Mapping[str, str], parser: DockerfileParser) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... # type: ignore[override] + +class Labels(KeyValues): ... +class Envs(KeyValues): ... +class Args(KeyValues): ... + +@type_check_only +class _InstructionDict(TypedDict): + instruction: str + startline: int + endline: int + content: str + value: str + +class DockerfileParser: + fileobj: IO[str] + dockerfile_path: str + cache_content: bool + cached_content: str + env_replace: bool + parent_env: dict[str, str] + build_args: dict[str, str] + def __init__( + self, + path: str | None = None, + cache_content: bool = False, + env_replace: bool = True, + parent_env: dict[str, str] | None = None, + fileobj: IO[str] | None = None, + build_args: dict[str, str] | None = None, + ) -> None: ... + lines: list[str] + content: str + @property + def structure(self) -> list[_InstructionDict]: ... + @property + def json(self) -> str: ... + parent_images: Sequence[str] + @property + def is_multistage(self) -> bool: ... + baseimage: str + cmd: str + labels: Mapping[str, str] + envs: Mapping[str, str] + args: Mapping[str, str] + def add_lines( + self, *lines: str, all_stages: bool | None = ..., at_start: bool | None = ..., skip_scratch: bool | None = ... + ) -> None: ... + def add_lines_at( + self, anchor: str | int | dict[str, int], *lines: str, replace: bool | None = ..., after: bool | None = ... + ) -> None: ... + @property + def context_structure(self) -> list[Context]: ... + +def image_from(from_value: str) -> tuple[str | None, str | None]: ... diff --git a/stubs/dockerfile-parse/dockerfile_parse/util.pyi b/stubs/dockerfile-parse/dockerfile_parse/util.pyi new file mode 100644 index 000000000000..ca1f4086b290 --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/util.pyi @@ -0,0 +1,51 @@ +from collections.abc import Generator, Mapping, MutableMapping +from io import StringIO +from typing import ClassVar, Literal, TypeAlias + +def b2u(string: bytes | str) -> str: ... +def u2b(string: str | bytes) -> bytes: ... + +_Quotes: TypeAlias = Literal["'", '"'] +_ContextType: TypeAlias = Literal["ARG", "ENV", "LABEL"] + +class WordSplitter: + SQUOTE: ClassVar[_Quotes] + DQUOTE: ClassVar[_Quotes] + stream: StringIO + args: Mapping[str, str] | None + envs: Mapping[str, str] | None + quotes: _Quotes | None + escaped: bool + def __init__(self, s: str, args: Mapping[str, str] | None = None, envs: Mapping[str, str] | None = None) -> None: ... + def dequote(self) -> str: ... + def split(self, maxsplit: int | None = None, dequote: bool = True) -> Generator[str | None]: ... + +def extract_key_values( + env_replace: bool, args: Mapping[str, str], envs: Mapping[str, str], instruction_value: str +) -> list[tuple[str, str]]: ... +def get_key_val_dictionary( + instruction_value: str, + env_replace: bool = False, + args: Mapping[str, str] | None = None, + envs: Mapping[str, str] | None = None, +) -> dict[str, str]: ... + +class Context: + args: MutableMapping[str, str] + envs: MutableMapping[str, str] + labels: MutableMapping[str, str] + line_args: Mapping[str, str] + line_envs: Mapping[str, str] + line_labels: Mapping[str, str] + def __init__( + self, + args: MutableMapping[str, str] | None = None, + envs: MutableMapping[str, str] | None = None, + labels: MutableMapping[str, str] | None = None, + line_args: Mapping[str, str] | None = None, + line_envs: Mapping[str, str] | None = None, + line_labels: Mapping[str, str] | None = None, + ) -> None: ... + def set_line_value(self, context_type: _ContextType, value: Mapping[str, str]) -> None: ... + def get_line_value(self, context_type: _ContextType) -> Mapping[str, str]: ... + def get_values(self, context_type: _ContextType) -> Mapping[str, str]: ... diff --git a/stubs/docopt/METADATA.toml b/stubs/docopt/METADATA.toml deleted file mode 100644 index ce19e8f4b3b6..000000000000 --- a/stubs/docopt/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -# Prior to v0.6, docopt() had only 3 optional args -version = "0.6.*" -python2 = true \ No newline at end of file diff --git a/stubs/docopt/docopt.pyi b/stubs/docopt/docopt.pyi deleted file mode 100644 index 7f7bba6a7e69..000000000000 --- a/stubs/docopt/docopt.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any, Iterable, Union - -__version__: str - -_Argv = Union[Iterable[str], str] - -def docopt( - doc: str, argv: _Argv | None = ..., help: bool = ..., version: Any | None = ..., options_first: bool = ... -) -> dict[str, Any]: ... # Really should be dict[str, str | bool] diff --git a/stubs/docutils/@tests/stubtest_allowlist.txt b/stubs/docutils/@tests/stubtest_allowlist.txt index a6aa9c57efa9..e210c1e10470 100644 --- a/stubs/docutils/@tests/stubtest_allowlist.txt +++ b/stubs/docutils/@tests/stubtest_allowlist.txt @@ -1,10 +1,25 @@ +docutils.nodes.Element.__iter__ # doesn't exist at runtime, but the class is iterable due to __getitem__ +docutils.nodes.Element.tagname # class variable is overridden in __init__ method +docutils.nodes.NodeVisitor.depart_\w+ # Methods are discovered dynamically on commonly-used subclasses +docutils.nodes.NodeVisitor.visit_\w+ # Methods are discovered dynamically on commonly-used subclasses +docutils.nodes.NodeVisitor.__init__ # Argument "document" should be positional-only, but subclasses are not + +# these methods take a rawsource parameter that has been deprecated and is completely ignored, so we omit it from the stub +docutils.nodes.Text.__new__ +docutils.parsers.rst.directives.admonitions.BaseAdmonition.node_class # must be overridden by base classes (pseudo-abstract) +docutils.statemachine.State.nested_sm # is initialised in __init__ +docutils.statemachine.State.nested_sm_kwargs # is initialised in __init__ +docutils.statemachine.ViewList.__iter__ # doesn't exist at runtime, but the class is iterable due to __getitem__ +docutils.transforms.Transform.apply # method apply is not implemented +docutils.transforms.Transform.__getattr__ docutils.TransformSpec.unknown_reference_resolvers -docutils.frontend.ConfigParser.__getattr__ -docutils.frontend.ConfigParser.read -docutils.frontend.OptionParser.__getattr__ -docutils.io.FileOutput.__getattr__ -docutils.io.FileOutput.__init__ -docutils.io.Input.__getattr__ -docutils.io.Input.__init__ -docutils.parsers.rst.Directive.__getattr__ -docutils.parsers.rst.nodes +docutils.writers.latex2e.PreambleCmds... contents +docutils.writers.latex2e.PreambleCmds.inline role \w+ # attribute names with spaces, set with setattr() from docutils.sty + +# Files that don't exist at runtime of stubtests, raises ImportError: +docutils.parsers.commonmark_wrapper +docutils.parsers.recommonmark_wrapper +docutils.writers.odf_odt.pygmentsformatter # import `pygments` third-party library + +# `TYPE_CHECKING` variable is for internal use: +docutils.*\.TYPE_CHECKING diff --git a/stubs/docutils/METADATA.toml b/stubs/docutils/METADATA.toml index 17d320a94b90..f48cf6eedcb7 100644 --- a/stubs/docutils/METADATA.toml +++ b/stubs/docutils/METADATA.toml @@ -1 +1,2 @@ -version = "0.17.*" +version = "0.23" +upstream-repository = "https://sourceforge.net/p/docutils/code" diff --git a/stubs/docutils/docutils/__init__.pyi b/stubs/docutils/docutils/__init__.pyi index d4477b9624b0..9845ec945daa 100644 --- a/stubs/docutils/docutils/__init__.pyi +++ b/stubs/docutils/docutils/__init__.pyi @@ -1,8 +1,12 @@ -from typing import Any, ClassVar, NamedTuple, Tuple +from typing import Any, ClassVar, Final, NamedTuple, type_check_only +from typing_extensions import Self -__docformat__: str -__version__: str +from docutils.transforms import Transform +__docformat__: Final = "reStructuredText" +__version__: Final[str] + +@type_check_only class _VersionInfo(NamedTuple): major: int minor: int @@ -12,30 +16,31 @@ class _VersionInfo(NamedTuple): release: bool class VersionInfo(_VersionInfo): + __slots__ = () def __new__( - cls, major: int = ..., minor: int = ..., micro: int = ..., releaselevel: str = ..., serial: int = ..., release: bool = ... - ) -> VersionInfo: ... + cls, major: int = 0, minor: int = 0, micro: int = 0, releaselevel: str = "final", serial: int = 0, release: bool = True + ) -> Self: ... -__version_info__: VersionInfo -__version_details__: str +__version_info__: Final[VersionInfo] +__version_details__: Final[str] class ApplicationError(Exception): ... class DataError(ApplicationError): ... class SettingsSpec: - settings_spec: ClassVar[Tuple[Any, ...]] + settings_spec: ClassVar[tuple[Any, ...]] # Mixed tuple structure; uses Any for flexibility in nested option definitions settings_defaults: ClassVar[dict[Any, Any] | None] settings_default_overrides: ClassVar[dict[Any, Any] | None] - relative_path_settings: ClassVar[Tuple[Any, ...]] + relative_path_settings: ClassVar[tuple[Any, ...]] config_section: ClassVar[str | None] - config_section_dependencies: ClassVar[Tuple[str, ...] | None] + config_section_dependencies: ClassVar[tuple[str, ...] | None] class TransformSpec: - def get_transforms(self) -> list[Any]: ... - default_transforms: ClassVar[Tuple[Any, ...]] + def get_transforms(self) -> list[type[Transform]]: ... + default_transforms: ClassVar[tuple[Any, ...]] unknown_reference_resolvers: ClassVar[list[Any]] class Component(SettingsSpec, TransformSpec): component_type: ClassVar[str | None] - supported: ClassVar[Tuple[str, ...]] + supported: ClassVar[tuple[str, ...]] def supports(self, format: str) -> bool: ... diff --git a/stubs/docutils/docutils/__main__.pyi b/stubs/docutils/docutils/__main__.pyi new file mode 100644 index 000000000000..819b94bd9593 --- /dev/null +++ b/stubs/docutils/docutils/__main__.pyi @@ -0,0 +1,11 @@ +from typing import ClassVar, Final + +import docutils + +__docformat__: Final = "reStructuredText" + +class CliSettingsSpec(docutils.SettingsSpec): + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + +def main() -> None: ... diff --git a/stubs/docutils/docutils/core.pyi b/stubs/docutils/docutils/core.pyi index 964e6fa3f426..00e9b290ca0b 100644 --- a/stubs/docutils/docutils/core.pyi +++ b/stubs/docutils/docutils/core.pyi @@ -1,3 +1,220 @@ -from typing import Any +from _typeshed import Incomplete, StrPath +from typing import IO, Final +from typing_extensions import deprecated -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import SettingsSpec, nodes +from docutils.frontend import Values +from docutils.io import Input, Output +from docutils.parsers import Parser +from docutils.readers import Reader +from docutils.utils import SystemMessage +from docutils.writers import Writer, _WriterParts + +__docformat__: Final = "reStructuredText" + +class Publisher: + document: nodes.document | None + reader: Reader[Incomplete] + parser: Parser + writer: Writer[Incomplete] + source: Input[Incomplete] + source_class: type[Input[Incomplete]] + destination: Output | None + destination_class: type[Output] + settings: dict[str, Incomplete] + def __init__( + self, + reader: Reader[Incomplete] | None = None, + parser: Parser | None = None, + writer: Writer[Incomplete] | None = None, + source: Input[Incomplete] | None = None, + source_class: type[Input[Incomplete]] = ..., + destination: Output | None = None, + destination_class: type[Output] = ..., + settings: dict[str, Incomplete] | None = None, + ) -> None: ... + def set_reader(self, reader: str, parser: Parser | None = None, parser_name: str | None = None) -> None: ... + def set_writer(self, writer_name: str) -> None: ... + @deprecated("The `Publisher.set_components()` will be removed in Docutils 2.0.") + def set_components(self, reader_name: str, parser_name: str, writer_name: str) -> None: ... + def get_settings( + self, + usage: str | None = None, + description: str | None = None, + settings_spec: SettingsSpec | None = None, + config_section: str | None = None, + **defaults, + ): ... + def process_programmatic_settings(self, settings_spec, settings_overrides, config_section) -> None: ... + def process_command_line( + self, + argv: list[str] | None = None, + usage=None, + description: str | None = None, + settings_spec=None, + config_section=None, + **defaults, + ) -> None: ... + def set_io(self, source_path: StrPath | None = None, destination_path: StrPath | None = None) -> None: ... + def set_source(self, source: str | None = None, source_path: StrPath | None = None) -> None: ... + def set_destination(self, destination=None, destination_path: StrPath | None = None) -> None: ... + def apply_transforms(self) -> None: ... + def publish( + self, + argv: list[str] | None = None, + usage: str | None = None, + description: str | None = None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, + ): ... + def debugging_dumps(self) -> None: ... + def prompt(self) -> None: ... + def report_Exception(self, error: BaseException) -> None: ... + def report_SystemMessage(self, error: SystemMessage) -> None: ... + def report_UnicodeError(self, error: UnicodeEncodeError) -> None: ... + +default_usage: Final[str] +default_description: Final[str] + +def publish_cmdline( + reader: Reader[Incomplete] | None = None, + reader_name: str | None = None, + parser: Parser | None = None, + parser_name: str | None = None, + writer: Writer[Incomplete] | None = None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = True, + argv: list[str] | None = None, + usage: str = "%prog [options] [ []]", + description: str = ..., +): ... +def publish_file( + source=None, + source_path: StrPath | None = None, + destination=None, + destination_path: StrPath | None = None, + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +def publish_string( + source, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +def publish_parts( + source, + source_path: StrPath | None = None, + source_class: type[Input[Incomplete]] = ..., + destination_path: StrPath | None = None, + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides: dict[str, Incomplete] | None = None, + config_section: str | None = None, + enable_exit_status: bool = False, +) -> _WriterParts: ... +def publish_doctree( + source: str | bytes | IO[str] | IO[bytes] | None, + source_path: StrPath | None = None, + source_class: type[Input[Incomplete]] = ..., + reader: Reader[Incomplete] | str | None = None, + reader_name: str | None = None, + parser: Parser | str | None = None, + parser_name: str | None = None, + settings: Values | None = None, + settings_spec: SettingsSpec | type[SettingsSpec] | None = None, + settings_overrides: dict[str, Incomplete] | None = None, + config_section: str | None = None, + enable_exit_status: bool = False, +) -> nodes.document: ... +def publish_from_doctree( + document, + destination_path: StrPath | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +@deprecated("The `publish_cmdline_to_binary()` is deprecated by `publish_cmdline()` and will be removed in Docutils 0.24.") +def publish_cmdline_to_binary( + reader=None, + reader_name: str = "standalone", + parser=None, + parser_name: str = "restructuredtext", + writer=None, + writer_name: str = "pseudoxml", + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = True, + argv: list[str] | None = None, + usage: str = "%prog [options] [ []]", + description: str = ..., + destination=None, + destination_class: type[Output] = ..., +): ... +def publish_programmatically( + source_class: type[Input[Incomplete]], + source, + source_path: StrPath | None, + destination_class: type[Output], + destination, + destination_path: StrPath | None, + reader, + reader_name: str, + parser, + parser_name: str, + writer, + writer_name: str, + settings, + settings_spec, + settings_overrides, + config_section: str, + enable_exit_status: bool, +) -> tuple[str | bytes | None, Publisher]: ... +def rst2something(writer: str, documenttype: str, doc_path: str = "") -> None: ... +def rst2html() -> None: ... +def rst2html4() -> None: ... +def rst2html5() -> None: ... +def rst2latex() -> None: ... +def rst2man() -> None: ... +def rst2odt() -> None: ... +def rst2pseudoxml() -> None: ... +def rst2s5() -> None: ... +def rst2xetex() -> None: ... +def rst2xml() -> None: ... diff --git a/stubs/docutils/docutils/examples.pyi b/stubs/docutils/docutils/examples.pyi index 964e6fa3f426..3973316b9666 100644 --- a/stubs/docutils/docutils/examples.pyi +++ b/stubs/docutils/docutils/examples.pyi @@ -1,3 +1,45 @@ -from typing import Any +from _typeshed import Incomplete, StrPath +from typing import Literal, TypeAlias, overload -def __getattr__(name: str) -> Any: ... # incomplete +from docutils.core import Publisher +from docutils.nodes import document +from docutils.writers import _WriterParts + +_HTMLHeaderLevel: TypeAlias = Literal[1, 2, 3, 4, 5, 6] + +def html_parts( + input_string: str | bytes, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + input_encoding: str = "unicode", + doctitle: bool = True, + initial_header_level: _HTMLHeaderLevel = 1, +) -> _WriterParts: ... + +@overload +def html_body( + input_string: str | bytes, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + input_encoding: str = "unicode", + output_encoding: Literal["unicode"] = "unicode", + doctitle: bool = True, + initial_header_level: _HTMLHeaderLevel = 1, +) -> str: ... +@overload +def html_body( + input_string: str | bytes, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + input_encoding: str = "unicode", + output_encoding: str = "unicode", + doctitle: bool = True, + initial_header_level: _HTMLHeaderLevel = 1, +) -> str | bytes: ... + +def internals( + source: str, + source_path: StrPath | None = None, + input_encoding: str = "unicode", + settings_overrides: dict[str, Incomplete] | None = None, +) -> tuple[document | None, Publisher]: ... diff --git a/stubs/docutils/docutils/frontend.pyi b/stubs/docutils/docutils/frontend.pyi index c32dc44ffb5e..88aabf86b2e6 100644 --- a/stubs/docutils/docutils/frontend.pyi +++ b/stubs/docutils/docutils/frontend.pyi @@ -1,78 +1,202 @@ import optparse -from collections.abc import Iterable, Mapping +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Mapping, Sequence from configparser import RawConfigParser -from typing import Any, ClassVar, Tuple, Type +from typing import Any, ClassVar, Final, Literal, Protocol, overload, type_check_only +from typing_extensions import deprecated from docutils import SettingsSpec -from docutils.parsers import Parser from docutils.utils import DependencyList -__docformat__: str +__docformat__: Final = "reStructuredText" -def store_multiple(option, opt, value, parser, *args, **kwargs) -> None: ... -def read_config_file(option, opt, value, parser) -> None: ... -def validate_encoding(setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ...): ... +@type_check_only +class _OptionValidator(Protocol): + def __call__( + self, + setting: str, + value: str | None, + option_parser: OptionParser, + /, + config_parser: ConfigParser | None = None, + config_section: str | None = None, + ) -> Any: ... + +@deprecated("Deprecated and will be removed with the switch to from optparse to argparse.") +def store_multiple(option: optparse.Option, opt: str, value, parser: OptionParser, *args: str, **kwargs) -> None: ... +@deprecated("Deprecated and will be removed with the switch to from optparse to argparse.") +def read_config_file(option: optparse.Option, opt: str, value, parser: OptionParser) -> None: ... +def validate_encoding( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... def validate_encoding_error_handler( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... -): ... + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... def validate_encoding_and_error_handler( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... -): ... + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... def validate_boolean( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str | bool, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> bool: ... +def validate_ternary( + setting: str | bool, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str | bool | None: ... def validate_nonnegative_int( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str | int, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> int: ... def validate_threshold( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str | int, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> int: ... def validate_colon_separated_string_list( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str | list[str], + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> list[str]: ... def validate_comma_separated_list( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str | list[str], + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> list[str]: ... +def validate_math_output( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> tuple[()] | tuple[str, str]: ... def validate_url_trailing_slash( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> str: ... def validate_dependency_file( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... + setting: str | None, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, ) -> DependencyList: ... -def validate_strip_class(setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ...): ... +def validate_strip_class( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> list[str]: ... def validate_smartquotes_locales( - setting, value, option_parser, config_parser: Any | None = ..., config_section: Any | None = ... -) -> list[tuple[str, str]]: ... -def make_paths_absolute(pathdict, keys, base_path: Any | None = ...) -> None: ... -def make_one_path_absolute(base_path, path) -> str: ... -def filter_settings_spec(settings_spec, *exclude, **replace) -> Tuple[Any, ...]: ... + setting: str | list[str | tuple[str, str]], + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> list[tuple[str, Sequence[str]]]: ... +def make_paths_absolute( + pathdict: dict[str, list[StrPath] | StrPath], keys: tuple[str], base_path: StrPath | None = None +) -> None: ... +@deprecated("The `frontend.make_one_path_absolute` will be removed in Docutils 2.0 or later.") +def make_one_path_absolute(base_path: StrPath, path: StrPath) -> str: ... +def filter_settings_spec(settings_spec, *exclude, **replace) -> tuple[Any, ...]: ... +@deprecated("The `frontend.Values` class will be removed in Docutils 2.0 or later.") class Values(optparse.Values): - def update(self, other_dict, option_parser) -> None: ... + record_dependencies: DependencyList + def __init__(self, defaults: dict[str, Any] | None = None) -> None: ... + def update(self, other_dict: Values | Mapping[str, Incomplete], option_parser: OptionParser) -> None: ... def copy(self) -> Values: ... + def setdefault(self, name: str, default): ... -class Option(optparse.Option): ... +@deprecated("The `frontend.Option` class will be removed in Docutils 2.0 or later.") +class Option(optparse.Option): + ATTRS: list[str] + validator: _OptionValidator + overrides: str | None + def __init__(self, *args: str | None, **kwargs) -> None: ... +@deprecated( + "The `frontend.OptionParser` class will be replaced by a subclass of `argparse.ArgumentParser` in Docutils 2.0 or later." +) class OptionParser(optparse.OptionParser, SettingsSpec): standard_config_files: ClassVar[list[str]] - threshold_choices: ClassVar[list[str]] + threshold_choices: ClassVar[tuple[str, ...]] thresholds: ClassVar[dict[str, int]] booleans: ClassVar[dict[str, bool]] default_error_encoding: ClassVar[str] default_error_encoding_error_handler: ClassVar[str] config_section: ClassVar[str] version_template: ClassVar[str] + details: str + lists: dict[str, Literal[True]] + config_files: list[str] + relative_path_settings: ClassVar[tuple[str, ...]] + version: str + components: tuple[SettingsSpec, ...] def __init__( self, - components: Iterable[Type[Parser]] = ..., - defaults: Mapping[str, Any] | None = ..., - read_config_files: bool | None = ..., + components: Iterable[SettingsSpec | type[SettingsSpec]] = (), + defaults: Mapping[str, Any] | None = None, + read_config_files: bool | None = False, *args, **kwargs, ) -> None: ... - def __getattr__(self, name: str) -> Any: ... # incomplete + def populate_from_components(self, components: Iterable[SettingsSpec]) -> None: ... + @classmethod + def get_standard_config_files(cls) -> Sequence[StrPath]: ... + def get_standard_config_settings(self) -> Values: ... + def get_config_file_settings(self, config_file: str) -> dict[str, Incomplete]: ... + def check_values(self, values: Values, args: list[str]) -> Values: ... # type: ignore[override] + def check_args(self, args: list[str]) -> tuple[str | None, str | None]: ... + def get_default_values(self) -> Values: ... + def get_option_by_dest(self, dest: str) -> Option: ... class ConfigParser(RawConfigParser): - def __getattr__(self, name: str) -> Any: ... # incomplete + old_settings: ClassVar[dict[str, tuple[str, str]]] + old_warning: ClassVar[str] + not_utf8_error: ClassVar[str] + + @overload # type: ignore[override] + def read(self, filenames: str | Sequence[str]) -> list[str]: ... + @overload + @deprecated("The `option_parser` parameter is deprecated and will be removed in Docutils 0.24.") + def read(self, filenames: str | Sequence[str], option_parser: OptionParser | None) -> list[str]: ... + + def handle_old_config(self, filename: str) -> None: ... + def validate_settings(self, filename: str, option_parser: OptionParser) -> None: ... + def optionxform(self, optionstr: str) -> str: ... + +class ConfigDeprecationWarning(FutureWarning): ... -class ConfigDeprecationWarning(DeprecationWarning): ... +def get_default_settings(*components: SettingsSpec | type[SettingsSpec]) -> Values: ... diff --git a/stubs/docutils/docutils/io.pyi b/stubs/docutils/docutils/io.pyi index b8d4751e8fc5..41cec25e1fd4 100644 --- a/stubs/docutils/docutils/io.pyi +++ b/stubs/docutils/docutils/io.pyi @@ -1,67 +1,139 @@ -from _typeshed import OpenBinaryModeReading, OpenBinaryModeWriting, OpenTextModeReading, OpenTextModeWriting -from typing import Any, ClassVar +from _typeshed import ( + Incomplete, + OpenBinaryModeReading, + OpenBinaryModeWriting, + OpenTextModeReading, + OpenTextModeWriting, + StrPath, + SupportsWrite, + Unused, +) +from re import Pattern +from typing import IO, Any, ClassVar, Final, Generic, Literal, TextIO, TypeVar +from typing_extensions import deprecated -from docutils import TransformSpec +from docutils import TransformSpec, nodes -__docformat__: str +__docformat__: Final = "reStructuredText" -class InputError(IOError): ... -class OutputError(IOError): ... +class InputError(OSError): ... +class OutputError(OSError): ... -def check_encoding(stream: Any, encoding: str) -> bool | None: ... +def check_encoding(stream: TextIO, encoding: str) -> bool | None: ... +def error_string(err: BaseException) -> str: ... -class Input(TransformSpec): +_S = TypeVar("_S") + +class Input(TransformSpec, Generic[_S]): component_type: ClassVar[str] default_source_path: ClassVar[str | None] - def read(self) -> Any: ... - def __getattr__(self, name: str) -> Any: ... # incomplete + encoding: str | None + error_handler: str + source: _S | None + source_path: str | None + successful_encoding: str | None = None + def __init__( + self, + source: _S | None = None, + source_path: str | None = None, + encoding: str | None = "utf-8", + error_handler: str = "strict", + ) -> None: ... + def read(self) -> str: ... + def decode(self, data: str | bytes | bytearray) -> str: ... + coding_slug: ClassVar[Pattern[bytes]] + byte_order_marks: ClassVar[tuple[tuple[bytes, str], ...]] + @deprecated("Deprecated and will be removed in Docutils 1.0.") + def determine_encoding_from_data(self, data: str | bytes | bytearray) -> str | None: ... + def isatty(self) -> bool: ... class Output(TransformSpec): component_type: ClassVar[str] default_destination_path: ClassVar[str | None] + encoding: str | None + error_handler: str + destination: Incomplete + destination_path: StrPath | None def __init__( self, - destination: Any | None = ..., - destination_path: Any | None = ..., - encoding: str | None = ..., - error_handler: str = ..., + destination=None, + destination_path: StrPath | None = None, + encoding: str | None = None, + error_handler: str | None = "strict", ) -> None: ... def write(self, data: str) -> Any: ... # returns bytes or str def encode(self, data: str) -> Any: ... # returns bytes or str -class FileInput(Input): +class ErrorOutput: + destination: SupportsWrite[str] | SupportsWrite[bytes] | Literal[False] + encoding: str + encoding_errors: str + decoding_errors: str def __init__( self, - source: Any | None = ..., - source_path: Any | None = ..., - encoding: str | None = ..., - error_handler: str = ..., - autoclose: bool = ..., - mode: OpenTextModeReading | OpenBinaryModeReading = ..., + destination: str | SupportsWrite[str] | SupportsWrite[bytes] | Literal[False] | None = None, + encoding: str | None = None, + encoding_errors: str = "backslashreplace", + decoding_errors: str = "replace", ) -> None: ... + def write(self, data: str | bytes | Exception) -> None: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + +class FileInput(Input[IO[str]]): + autoclose: bool + def __init__( + self, + source=None, + source_path: StrPath | None = None, + encoding: str | None = "utf-8", + error_handler: str | None = "strict", + autoclose: bool = True, + mode: OpenTextModeReading | OpenBinaryModeReading = "r", + ) -> None: ... + def read(self) -> str: ... def readlines(self) -> list[str]: ... def close(self) -> None: ... class FileOutput(Output): + default_destination_path: ClassVar[str] mode: ClassVar[OpenTextModeWriting | OpenBinaryModeWriting] - def __getattr__(self, name: str) -> Any: ... # incomplete + opened: bool + autoclose: bool + def __init__( + self, + destination=None, + destination_path: StrPath | None = None, + encoding: str | None = None, + error_handler: str | None = "strict", + autoclose: bool = True, + handle_io_errors: None = None, + mode: OpenTextModeWriting | OpenBinaryModeWriting | None = None, + ) -> None: ... + def open(self) -> None: ... + def write(self, data: str | bytes) -> str | bytes: ... + def close(self) -> None: ... +@deprecated("The `BinaryFileOutput` is deprecated by `FileOutput` and will be removed in Docutils 0.24.") class BinaryFileOutput(FileOutput): ... -class StringInput(Input): +class StringInput(Input[str]): default_source_path: ClassVar[str] + def read(self) -> str: ... class StringOutput(Output): default_destination_path: ClassVar[str] destination: str | bytes # only defined after call to write() + def write(self, data: str | bytes) -> str | bytes: ... -class NullInput(Input): +class NullInput(Input[Any]): default_source_path: ClassVar[str] def read(self) -> str: ... class NullOutput(Output): default_destination_path: ClassVar[str] - def write(self, data: object) -> None: ... + def write(self, data: Unused) -> None: ... -class DocTreeInput(Input): +class DocTreeInput(Input[nodes.document]): default_source_path: ClassVar[str] + def read(self): ... diff --git a/stubs/docutils/docutils/languages/__init__.pyi b/stubs/docutils/docutils/languages/__init__.pyi index 964e6fa3f426..415e42286a17 100644 --- a/stubs/docutils/docutils/languages/__init__.pyi +++ b/stubs/docutils/docutils/languages/__init__.pyi @@ -1,3 +1,25 @@ -from typing import Any +from typing import ClassVar, Final, Protocol, type_check_only +from typing_extensions import Self -def __getattr__(name: str) -> Any: ... # incomplete +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +@type_check_only +class _LanguageModule(Protocol): + labels: dict[str, str] + author_separators: list[str] + bibliographic_fields: list[str] + +class LanguageImporter: + packages: ClassVar[tuple[str, ...]] + warn_msg: ClassVar[str] + fallback: ClassVar[str] + cache: dict[str, _LanguageModule] + def __init__(self) -> None: ... + def import_from_packages(self, name: str, reporter: Reporter | None = None) -> _LanguageModule: ... + def check_content(self, module: _LanguageModule) -> None: ... + def __call__(self, language_code: str, reporter: Reporter | None = None) -> _LanguageModule: ... + def __class_getitem__(cls, name) -> type[Self]: ... + +get_language: LanguageImporter diff --git a/stubs/docutils/docutils/languages/af.pyi b/stubs/docutils/docutils/languages/af.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/af.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ar.pyi b/stubs/docutils/docutils/languages/ar.pyi new file mode 100644 index 000000000000..ea6236c81970 --- /dev/null +++ b/stubs/docutils/docutils/languages/ar.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal["؛", "،"]] diff --git a/stubs/docutils/docutils/languages/ca.pyi b/stubs/docutils/docutils/languages/ca.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ca.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/cs.pyi b/stubs/docutils/docutils/languages/cs.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/cs.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/da.pyi b/stubs/docutils/docutils/languages/da.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/da.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/de.pyi b/stubs/docutils/docutils/languages/de.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/de.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/en.pyi b/stubs/docutils/docutils/languages/en.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/en.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/eo.pyi b/stubs/docutils/docutils/languages/eo.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/eo.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/es.pyi b/stubs/docutils/docutils/languages/es.pyi new file mode 100644 index 000000000000..67f306e26583 --- /dev/null +++ b/stubs/docutils/docutils/languages/es.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +__docformat__: str +labels: Incomplete +bibliographic_fields: Incomplete +author_separators: Incomplete diff --git a/stubs/docutils/docutils/languages/fa.pyi b/stubs/docutils/docutils/languages/fa.pyi new file mode 100644 index 000000000000..ea6236c81970 --- /dev/null +++ b/stubs/docutils/docutils/languages/fa.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal["؛", "،"]] diff --git a/stubs/docutils/docutils/languages/fi.pyi b/stubs/docutils/docutils/languages/fi.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/fi.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/fr.pyi b/stubs/docutils/docutils/languages/fr.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/fr.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/gl.pyi b/stubs/docutils/docutils/languages/gl.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/gl.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/he.pyi b/stubs/docutils/docutils/languages/he.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/he.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/it.pyi b/stubs/docutils/docutils/languages/it.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/it.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ja.pyi b/stubs/docutils/docutils/languages/ja.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ja.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ka.pyi b/stubs/docutils/docutils/languages/ka.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ka.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ko.pyi b/stubs/docutils/docutils/languages/ko.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ko.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/lt.pyi b/stubs/docutils/docutils/languages/lt.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/lt.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/lv.pyi b/stubs/docutils/docutils/languages/lv.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/lv.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/nl.pyi b/stubs/docutils/docutils/languages/nl.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/nl.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/pl.pyi b/stubs/docutils/docutils/languages/pl.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/pl.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/pt_br.pyi b/stubs/docutils/docutils/languages/pt_br.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/pt_br.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ru.pyi b/stubs/docutils/docutils/languages/ru.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ru.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/sk.pyi b/stubs/docutils/docutils/languages/sk.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/sk.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/sv.pyi b/stubs/docutils/docutils/languages/sv.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/sv.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/uk.pyi b/stubs/docutils/docutils/languages/uk.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/uk.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/zh_cn.pyi b/stubs/docutils/docutils/languages/zh_cn.pyi new file mode 100644 index 000000000000..251a17cfe865 --- /dev/null +++ b/stubs/docutils/docutils/languages/zh_cn.pyi @@ -0,0 +1,6 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[str] diff --git a/stubs/docutils/docutils/languages/zh_tw.pyi b/stubs/docutils/docutils/languages/zh_tw.pyi new file mode 100644 index 000000000000..251a17cfe865 --- /dev/null +++ b/stubs/docutils/docutils/languages/zh_tw.pyi @@ -0,0 +1,6 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[str] diff --git a/stubs/docutils/docutils/nodes.pyi b/stubs/docutils/docutils/nodes.pyi index 964e6fa3f426..56b49e584f2b 100644 --- a/stubs/docutils/docutils/nodes.pyi +++ b/stubs/docutils/docutils/nodes.pyi @@ -1,3 +1,781 @@ -from typing import Any +import sys +import xml.dom.minidom +from _typeshed import Incomplete, StrPath +from abc import abstractmethod +from collections import Counter +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence +from typing import Any, ClassVar, Final, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated -def __getattr__(name: str) -> Any: ... # incomplete +from docutils.frontend import Values +from docutils.transforms import Transform, Transformer +from docutils.utils import Reporter + +_N = TypeVar("_N", bound=Node) +_ElementLikeType: TypeAlias = type[Element | Text | Body | Bibliographic | Inline] +_ContentModelCategory: TypeAlias = _ElementLikeType | tuple[_ElementLikeType, ...] +_ContentModelQuantifier: TypeAlias = Literal[".", "?", "+", "*"] +_ContentModelItem: TypeAlias = tuple[_ContentModelCategory, _ContentModelQuantifier] +_ContentModelTuple: TypeAlias = tuple[_ContentModelItem, ...] + +@type_check_only +class _DomModule(Protocol): + Document: type[xml.dom.minidom.Document] + +__docformat__: Final = "reStructuredText" + +# Functional Node Base Classes + +class Node: + # children is initialized by the subclasses + children: Sequence[Node] + # TODO: `parent` is actually `Element | None``, but `None`` only happens rarely, + # i.e. for synthetic nodes (or `document`, where it is overridden). + # See https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#the-any-trick + parent: Element | Any + source: str | None + line: int | None + + @property + def document(self) -> _Document | None: ... + @document.setter + def document(self, value: _Document) -> None: ... + + def __bool__(self) -> Literal[True]: ... + def asdom( + self, dom: _DomModule | None = None + ) -> xml.dom.minidom.Document | xml.dom.minidom.Element | xml.dom.minidom.Text: ... + # While docutils documents the Node class to be abstract it does not + # actually use the ABCMeta metaclass. We still set @abstractmethod here + # (although it's not used in the docutils implementation) because it + # makes Mypy reject Node() with "Cannot instantiate abstract class". + @abstractmethod + def copy(self) -> Self: ... + @abstractmethod + def deepcopy(self) -> Self: ... + @abstractmethod + def pformat(self, indent: str = " ", level: int = 0) -> str: ... + @abstractmethod + def astext(self) -> str: ... + def setup_child(self, child: Node) -> None: ... + def walk(self, visitor: NodeVisitor) -> bool: ... + def walkabout(self, visitor: NodeVisitor) -> bool: ... + + @overload + def findall( + self, + condition: type[_N] | tuple[type[_N], ...], + include_self: bool = True, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> Generator[_N]: ... + @overload + def findall( + self, + condition: Callable[[Node], bool] | None = None, + include_self: bool = True, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> Generator[Node]: ... + + @overload + @deprecated("The `nodes.Node.traverse()` is deprecated. Use `Node.findall()` instead.") + def traverse( + self, + condition: type[_N] | tuple[type[_N], ...], + include_self: bool = True, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> list[_N]: ... + @overload + @deprecated("The `nodes.Node.traverse()` is deprecated. Use `Node.findall()` instead.") + def traverse( + self, + condition: Callable[[Node], bool] | None = None, + include_self: bool = True, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> list[Node]: ... + + @overload + def next_node( + self, + condition: type[_N] | tuple[type[_N], ...], + include_self: bool = False, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> _N | None: ... + @overload + def next_node( + self, + condition: Callable[[Node], bool] | None = None, + include_self: bool = False, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> Node | None: ... + + def validate(self, recursive: bool = True) -> None: ... + def validate_position(self) -> None: ... + +# Left out +# - def ensure_str (deprecated) +# - def unescape (canonical import from docutils.utils) +def unescape(text: str, restore_backslashes: bool = False, respect_whitespace: bool = False) -> str: ... + +class Text(Node, str): + tagname: ClassVar[str] + children: tuple[()] + + # we omit the rawsource parameter because it has been deprecated and is ignored + def __new__(cls, data: str) -> Self: ... + def shortrepr(self, maxlen: int = 18) -> str: ... + def copy(self) -> Self: ... + def deepcopy(self) -> Self: ... + def pformat(self, indent: str = " ", level: int = 0) -> str: ... + def astext(self) -> str: ... + def rstrip(self, chars: str | None = None) -> str: ... + def lstrip(self, chars: str | None = None) -> str: ... + +_T = TypeVar("_T") + +class Element(Node): + local_attributes: ClassVar[Sequence[str]] + valid_attributes: ClassVar[Sequence[str]] + common_attributes: ClassVar[Sequence[str]] + basic_attributes: ClassVar[Sequence[str]] + list_attributes: ClassVar[Sequence[str]] + known_attributes: ClassVar[Sequence[str]] + content_model: ClassVar[_ContentModelTuple] + tagname: str + child_text_separator: ClassVar[str] + attributes: dict[str, Any] + children: list[Node] + rawsource: str + def __init__(self, rawsource: str = "", *children: Node, **attributes: Any) -> None: ... + def shortrepr(self) -> str: ... + def starttag(self, quoteattr: Callable[[str], str] | None = None) -> str: ... + def endtag(self) -> str: ... + def emptytag(self) -> str: ... + def __len__(self) -> int: ... + def __contains__(self, key: str | Node) -> bool: ... + + @overload + def __getitem__(self, key: str) -> Any: ... + @overload + def __getitem__(self, key: int) -> Node: ... + @overload + def __getitem__(self, key: slice) -> list[Node]: ... + + @overload + def __setitem__(self, key: str, item: Any) -> None: ... + @overload + def __setitem__(self, key: int, item: Node) -> None: ... + @overload + def __setitem__(self, key: slice, item: Iterable[Node]) -> None: ... + + def __delitem__(self, key: str | int | slice) -> None: ... + def __add__(self, other: list[Node]) -> list[Node]: ... + def __radd__(self, other: list[Node]) -> list[Node]: ... + def __iadd__(self, other: Node | Iterable[Node]) -> Self: ... + def astext(self) -> str: ... + def non_default_attributes(self) -> dict[str, Any]: ... + def attlist(self) -> list[tuple[str, Any]]: ... + + @overload + def get(self, key: str) -> Any: ... + @overload + def get(self, key: str, failobj: _T) -> _T: ... + + def hasattr(self, attr: str) -> bool: ... + def delattr(self, attr: str) -> None: ... + + @overload + def setdefault(self, key: str) -> Any: ... + @overload + def setdefault(self, key: str, failobj: _T) -> Any | _T: ... + + has_key = hasattr + def get_language_code(self, fallback: str = "") -> str: ... + def append(self, item: Node) -> None: ... + def extend(self, item: Iterable[Node]) -> None: ... + def insert(self, index: SupportsIndex, item: Node | Iterable[Node] | None) -> None: ... + def pop(self, i: int = -1) -> Node: ... + def remove(self, item: Node) -> None: ... + def index(self, item: Node, start: int = 0, stop: int = sys.maxsize) -> int: ... + def previous_sibling(self) -> Node | None: ... + def section_hierarchy(self) -> list[section]: ... + def is_not_default(self, key: str) -> bool: ... + def update_basic_atts(self, dict_: Mapping[str, Any] | Node) -> None: ... + def append_attr_list(self, attr: str, values: Iterable[Any]) -> None: ... + def coerce_append_attr_list(self, attr: str, value) -> None: ... + def replace_attr(self, attr: str, value: Any, force: bool = True) -> None: ... + def copy_attr_convert(self, attr: str, value: Any, replace: bool = True) -> None: ... + def copy_attr_coerce(self, attr: str, value: Any, replace: bool) -> None: ... + def copy_attr_concatenate(self, attr: str, value: Any, replace: bool) -> None: ... + def copy_attr_consistent(self, attr: str, value: Any, replace: bool) -> None: ... + def update_all_atts( + self, + dict_: Mapping[str, Any] | Node, + update_fun: Callable[[Element, str, Any, bool], object] = ..., + replace: bool = True, + and_source: bool = False, + ) -> None: ... + def update_all_atts_consistantly( + self, dict_: Mapping[str, Any] | Node, replace: bool = True, and_source: bool = False + ) -> None: ... + def update_all_atts_concatenating( + self, dict_: dict[str, Any] | Node, replace: bool = True, and_source: bool = False + ) -> None: ... + def update_all_atts_coercion( + self, dict_: Mapping[str, Any] | Node, replace: bool = True, and_source: bool = False + ) -> None: ... + def update_all_atts_convert(self, dict_: Mapping[str, Any] | Node, and_source: bool = False) -> None: ... + def clear(self) -> None: ... + def replace(self, old: Node, new: Node | Sequence[Node]) -> None: ... + def replace_self(self, new: Node | Sequence[Node]) -> None: ... + def first_child_matching_class( + self, childclass: type[Node] | tuple[type[Node], ...], start: int = 0, end: int = sys.maxsize + ) -> int | None: ... + def first_child_not_matching_class( + self, childclass: type[Node] | tuple[type[Node], ...], start: int = 0, end: int = sys.maxsize + ) -> int | None: ... + def pformat(self, indent: str = " ", level: int = 0) -> str: ... + def copy(self) -> Self: ... + def deepcopy(self) -> Self: ... + def note_referenced_by(self, name: str | None = None, id: str | None = None) -> None: ... + @classmethod + def is_not_list_attribute(cls, attr: str) -> bool: ... + @classmethod + def is_not_known_attribute(cls, attr: str) -> bool: ... + def validate_attributes(self) -> None: ... + def validate_content( + self, model: _ContentModelTuple | None = None, elements: Sequence[Incomplete] | None = None + ) -> list[Incomplete]: ... + + # '__iter__' is added as workaround, since mypy doesn't support classes that are iterable via '__getitem__' + # see https://github.com/python/typeshed/pull/10099#issuecomment-1528789395 + def __iter__(self) -> Iterator[Node]: ... + +class TextElement(Element): + def __init__(self, rawsource: str = "", text: str = "", *children: Node, **attributes) -> None: ... + +class FixedTextElement(TextElement): ... +class PureTextElement(TextElement): ... + +# Mixins + +class Resolvable: + resolved: int + +class BackLinkable: + list_attributes: ClassVar[Sequence[str]] + valid_attributes: ClassVar[Sequence[str]] + def add_backref(self, refid: str) -> None: ... + +# Element Categories + +class Root: ... +class Titular: ... +class PreBibliographic: ... +class Bibliographic: ... + +class Decorative(PreBibliographic): + content_model: ClassVar[_ContentModelTuple] + +class Structural: ... +class SubStructural: ... +class Body: ... +class General(Body): ... +class Sequential(Body): ... + +class Admonition(Body): + content_model: ClassVar[_ContentModelTuple] + +class Special(Body): ... +class Invisible(PreBibliographic): ... +class Part: ... +class Inline: ... +class Referential(Resolvable): ... + +class Targetable(Resolvable): + referenced: int + indirect_reference_name: str | None + +class Labeled: ... + +# Root Element + +_Document: TypeAlias = document +_Decoration: TypeAlias = decoration + +class document(Root, Structural, Element): + current_source: str | None + current_line: int | None + settings: Values + reporter: Reporter + indirect_targets: list[target] + substitution_defs: dict[str, substitution_definition] + substitution_names: dict[str, str] + refnames: dict[str, list[Element]] + refids: dict[str, list[Element]] + names: dict[str, Element | None] + nameids: dict[str, str] + nametypes: dict[str, bool] + ids: dict[str, Element] + footnote_refs: dict[str, list[footnote_reference]] + citation_refs: dict[str, list[citation_reference]] + autofootnotes: list[footnote] + autofootnote_refs: list[footnote_reference] + symbol_footnotes: list[footnote] + symbol_footnote_refs: list[footnote_reference] + footnotes: list[footnote] + citations: list[citation] + autofootnote_start: int + symbol_footnote_start: int + id_counter: Counter[str] + parse_messages: list[system_message] + transform_messages: list[system_message] + transformer: Transformer + include_log: list[tuple[StrPath, tuple[Incomplete, ...]]] + decoration: decoration | None + document: Self + def __init__(self, settings: Values, reporter: Reporter, *args: Node, **kwargs: Any) -> None: ... + def asdom(self, dom: Any | None = None) -> Any: ... + def set_id(self, node: Element, msgnode: Element | None = None, suggested_prefix: str = "") -> str: ... + def create_id(self, node: Element, suggested_prefix: str = "") -> str: ... + @deprecated("`nodes.document.set_name_id_map()` will be removed in Docutils 1.0.") + def set_name_id_map(self, node: Element, id: str, msgnode: Element | None = None, explicit: bool = False) -> None: ... + def set_duplicate_name(self, node: Element, name: str, msgnode: Element, explicit: bool) -> None: ... + def note_names(self, node: Element, msgnode: Element | None = None, explicit: bool = False) -> None: ... + def has_name(self, name: str) -> bool: ... + def note_implicit_target(self, target: Element, msgnode: Element | None = None) -> None: ... + def note_explicit_target(self, target: Element, msgnode: Element | None = None) -> None: ... + def note_refname(self, node: Element) -> None: ... + def note_refid(self, node: Element) -> None: ... + def note_indirect_target(self, target: target) -> None: ... + def note_anonymous_target(self, target: target) -> None: ... + def note_autofootnote(self, footnote: footnote) -> None: ... + def note_autofootnote_ref(self, ref: footnote_reference) -> None: ... + def note_symbol_footnote(self, footnote: footnote) -> None: ... + def note_symbol_footnote_ref(self, ref: footnote_reference) -> None: ... + def note_footnote(self, footnote: footnote) -> None: ... + def note_footnote_ref(self, ref: footnote_reference) -> None: ... + def note_citation(self, citation: citation) -> None: ... + def note_citation_ref(self, ref: citation_reference) -> None: ... + def note_substitution_def(self, subdef: substitution_definition, def_name: str, msgnode: Element | None = None) -> None: ... + def note_substitution_ref(self, subref: substitution_reference, refname: str) -> None: ... + def note_pending(self, pending: pending, priority: int | None = None) -> None: ... + def note_parse_message(self, message: system_message) -> None: ... + def note_transform_message(self, message: system_message) -> None: ... + def note_source(self, source: str, offset: int) -> None: ... + def copy(self) -> Self: ... + def get_decoration(self) -> _Decoration: ... + +# Title Elements + +class title(Titular, PreBibliographic, TextElement): ... +class subtitle(Titular, PreBibliographic, TextElement): ... +class rubric(Titular, TextElement): ... + +# Meta-Data Element + +class meta(PreBibliographic, Element): ... + +# Bibliographic Elements + +class docinfo(Bibliographic, Element): ... +class author(Bibliographic, TextElement): ... +class authors(Bibliographic, Element): ... +class organization(Bibliographic, TextElement): ... +class address(Bibliographic, FixedTextElement): ... +class contact(Bibliographic, TextElement): ... +class version(Bibliographic, TextElement): ... +class revision(Bibliographic, TextElement): ... +class status(Bibliographic, TextElement): ... +class date(Bibliographic, TextElement): ... +class copyright(Bibliographic, TextElement): ... + +# Decorative Elements + +class decoration(Decorative, Element): + def get_header(self) -> header: ... + def get_footer(self) -> footer: ... + +class header(Decorative, Element): ... +class footer(Decorative, Element): ... + +# Structural Elements + +class section(Structural, Element): ... +class topic(Structural, Element): ... +class sidebar(Structural, Element): ... + +class transition(Structural, Element): + ignored_siblings: ClassVar[tuple[type[Element], ...]] + +# Body Elements +# =============== + +class paragraph(General, TextElement): ... +class compound(General, Element): ... +class container(General, Element): ... +class bullet_list(Sequential, Element): ... +class enumerated_list(Sequential, Element): ... +class list_item(Part, Element): ... +class definition_list(Sequential, Element): ... +class definition_list_item(Part, Element): ... +class term(Part, TextElement): ... +class classifier(Part, TextElement): ... +class definition(Part, Element): ... +class field_list(Sequential, Element): ... +class field(Part, Element): ... +class field_name(Part, TextElement): ... +class field_body(Part, Element): ... +class option(Part, Element): ... +class option_argument(Part, TextElement): ... +class option_group(Part, Element): ... +class option_list(Sequential, Element): ... +class option_list_item(Part, Element): ... +class option_string(Part, TextElement): ... +class description(Part, Element): ... +class literal_block(General, FixedTextElement): ... +class doctest_block(General, FixedTextElement): ... +class math_block(General, FixedTextElement): ... +class line_block(General, Element): ... + +class line(Part, TextElement): + indent: str | None + +class block_quote(General, Element): ... +class attribution(Part, TextElement): ... +class attention(Admonition, Element): ... +class caution(Admonition, Element): ... +class danger(Admonition, Element): ... +class error(Admonition, Element): ... +class important(Admonition, Element): ... +class note(Admonition, Element): ... +class tip(Admonition, Element): ... +class hint(Admonition, Element): ... +class warning(Admonition, Element): ... +class admonition(Admonition, Element): ... +class comment(Special, Invisible, FixedTextElement): ... +class substitution_definition(Special, Invisible, TextElement): ... +class target(Special, Invisible, Inline, TextElement, Targetable): ... +class footnote(General, BackLinkable, Element, Labeled, Targetable): ... +class citation(General, BackLinkable, Element, Labeled, Targetable): ... +class label(Part, TextElement): ... +class figure(General, Element): ... +class caption(Part, TextElement): ... +class legend(Part, Element): ... +class table(General, Element): ... +class tgroup(Part, Element): ... + +class colspec(Part, Element): + def propwidth(self) -> float: ... + +class thead(Part, Element): ... +class tbody(Part, Element): ... +class row(Part, Element): ... +class entry(Part, Element): ... + +class system_message(Special, BackLinkable, PreBibliographic, Element): + def __init__(self, message: str | None = None, *children: Node, **attributes) -> None: ... + def astext(self) -> str: ... + +class pending(Special, Invisible, Element): + transform: type[Transform] + details: Mapping[str, Any] + def __init__( + self, + transform: type[Transform], + details: Mapping[str, Any] | None = None, + rawsource: str = "", + *children: Node, + **attributes, + ) -> None: ... + +class raw(Special, Inline, PreBibliographic, FixedTextElement): ... + +# Inline Elements + +class emphasis(Inline, TextElement): ... +class strong(Inline, TextElement): ... +class literal(Inline, TextElement): ... +class reference(General, Inline, Referential, TextElement): ... +class footnote_reference(Inline, Referential, TextElement): ... +class citation_reference(Inline, Referential, TextElement): ... +class substitution_reference(Inline, TextElement): ... +class title_reference(Inline, TextElement): ... +class abbreviation(Inline, TextElement): ... +class acronym(Inline, TextElement): ... +class superscript(Inline, TextElement): ... +class subscript(Inline, TextElement): ... +class math(Inline, TextElement): ... +class image(General, Inline, Element): ... +class inline(Inline, TextElement): ... +class problematic(Inline, TextElement): ... +class generated(Inline, TextElement): ... + +# Auxiliary Classes, Functions, and Data + +node_class_names: list[str] + +class NodeVisitor: + optional: ClassVar[tuple[str, ...]] + document: _Document + def __init__(self, document: _Document) -> None: ... + def dispatch_visit(self, node: Node) -> Any: ... + def dispatch_departure(self, node: Node) -> Any: ... + def unknown_visit(self, node: Node) -> Any: ... + def unknown_departure(self, node: Node) -> Any: ... + + # These methods only exist on the subclasses `GenericNodeVisitor` and `SparseNodeVisitor` at runtime. + # If subclassing `NodeVisitor` directly, `visit_*` methods must be implemented for nodes and children that will be called + # with `Node.walk()` and `Node.walkabout()`. + # `depart_*` methods must also be implemented for nodes and children that will be called with `Node.walkabout()`. + def visit_Text(self, node: Text) -> Any: ... + def visit_abbreviation(self, node: abbreviation) -> Any: ... + def visit_acronym(self, node: acronym) -> Any: ... + def visit_address(self, node: address) -> Any: ... + def visit_admonition(self, node: admonition) -> Any: ... + def visit_attention(self, node: attention) -> Any: ... + def visit_attribution(self, node: attribution) -> Any: ... + def visit_author(self, node: author) -> Any: ... + def visit_authors(self, node: authors) -> Any: ... + def visit_block_quote(self, node: block_quote) -> Any: ... + def visit_bullet_list(self, node: bullet_list) -> Any: ... + def visit_caption(self, node: caption) -> Any: ... + def visit_caution(self, node: caution) -> Any: ... + def visit_citation(self, node: citation) -> Any: ... + def visit_citation_reference(self, node: citation_reference) -> Any: ... + def visit_classifier(self, node: classifier) -> Any: ... + def visit_colspec(self, node: colspec) -> Any: ... + def visit_comment(self, node: comment) -> Any: ... + def visit_compound(self, node: compound) -> Any: ... + def visit_contact(self, node: contact) -> Any: ... + def visit_container(self, node: container) -> Any: ... + def visit_copyright(self, node: copyright) -> Any: ... + def visit_danger(self, node: danger) -> Any: ... + def visit_date(self, node: date) -> Any: ... + def visit_decoration(self, node: decoration) -> Any: ... + def visit_definition(self, node: definition) -> Any: ... + def visit_definition_list(self, node: definition_list) -> Any: ... + def visit_definition_list_item(self, node: definition_list_item) -> Any: ... + def visit_description(self, node: description) -> Any: ... + def visit_docinfo(self, node: docinfo) -> Any: ... + def visit_doctest_block(self, node: doctest_block) -> Any: ... + def visit_document(self, node: _Document) -> Any: ... + def visit_emphasis(self, node: emphasis) -> Any: ... + def visit_entry(self, node: entry) -> Any: ... + def visit_enumerated_list(self, node: enumerated_list) -> Any: ... + def visit_error(self, node: error) -> Any: ... + def visit_field(self, node: field) -> Any: ... + def visit_field_body(self, node: field_body) -> Any: ... + def visit_field_list(self, node: field_list) -> Any: ... + def visit_field_name(self, node: field_name) -> Any: ... + def visit_figure(self, node: figure) -> Any: ... + def visit_footer(self, node: footer) -> Any: ... + def visit_footnote(self, node: footnote) -> Any: ... + def visit_footnote_reference(self, node: footnote_reference) -> Any: ... + def visit_generated(self, node: generated) -> Any: ... + def visit_header(self, node: header) -> Any: ... + def visit_hint(self, node: hint) -> Any: ... + def visit_image(self, node: image) -> Any: ... + def visit_important(self, node: important) -> Any: ... + def visit_inline(self, node: inline) -> Any: ... + def visit_label(self, node: label) -> Any: ... + def visit_legend(self, node: legend) -> Any: ... + def visit_line(self, node: line) -> Any: ... + def visit_line_block(self, node: line_block) -> Any: ... + def visit_list_item(self, node: list_item) -> Any: ... + def visit_literal(self, node: literal) -> Any: ... + def visit_literal_block(self, node: literal_block) -> Any: ... + def visit_math(self, node: math) -> Any: ... + def visit_math_block(self, node: math_block) -> Any: ... + def visit_meta(self, node: meta) -> Any: ... + def visit_note(self, node: note) -> Any: ... + def visit_option(self, node: option) -> Any: ... + def visit_option_argument(self, node: option_argument) -> Any: ... + def visit_option_group(self, node: option_group) -> Any: ... + def visit_option_list(self, node: option_list) -> Any: ... + def visit_option_list_item(self, node: option_list_item) -> Any: ... + def visit_option_string(self, node: option_string) -> Any: ... + def visit_organization(self, node: organization) -> Any: ... + def visit_paragraph(self, node: paragraph) -> Any: ... + def visit_pending(self, node: pending) -> Any: ... + def visit_problematic(self, node: problematic) -> Any: ... + def visit_raw(self, node: raw) -> Any: ... + def visit_reference(self, node: reference) -> Any: ... + def visit_revision(self, node: revision) -> Any: ... + def visit_row(self, node: row) -> Any: ... + def visit_rubric(self, node: rubric) -> Any: ... + def visit_section(self, node: section) -> Any: ... + def visit_sidebar(self, node: sidebar) -> Any: ... + def visit_status(self, node: status) -> Any: ... + def visit_strong(self, node: strong) -> Any: ... + def visit_subscript(self, node: subscript) -> Any: ... + def visit_substitution_definition(self, node: substitution_definition) -> Any: ... + def visit_substitution_reference(self, node: substitution_reference) -> Any: ... + def visit_subtitle(self, node: subtitle) -> Any: ... + def visit_superscript(self, node: superscript) -> Any: ... + def visit_system_message(self, node: system_message) -> Any: ... + def visit_table(self, node: table) -> Any: ... + def visit_target(self, node: target) -> Any: ... + def visit_tbody(self, node: tbody) -> Any: ... + def visit_term(self, node: term) -> Any: ... + def visit_tgroup(self, node: tgroup) -> Any: ... + def visit_thead(self, node: thead) -> Any: ... + def visit_tip(self, node: tip) -> Any: ... + def visit_title(self, node: title) -> Any: ... + def visit_title_reference(self, node: title_reference) -> Any: ... + def visit_topic(self, node: topic) -> Any: ... + def visit_transition(self, node: transition) -> Any: ... + def visit_version(self, node: version) -> Any: ... + def visit_warning(self, node: warning) -> Any: ... + def depart_Text(self, node: Text) -> Any: ... + def depart_abbreviation(self, node: abbreviation) -> Any: ... + def depart_acronym(self, node: acronym) -> Any: ... + def depart_address(self, node: address) -> Any: ... + def depart_admonition(self, node: admonition) -> Any: ... + def depart_attention(self, node: attention) -> Any: ... + def depart_attribution(self, node: attribution) -> Any: ... + def depart_author(self, node: author) -> Any: ... + def depart_authors(self, node: authors) -> Any: ... + def depart_block_quote(self, node: block_quote) -> Any: ... + def depart_bullet_list(self, node: bullet_list) -> Any: ... + def depart_caption(self, node: caption) -> Any: ... + def depart_caution(self, node: caution) -> Any: ... + def depart_citation(self, node: citation) -> Any: ... + def depart_citation_reference(self, node: citation_reference) -> Any: ... + def depart_classifier(self, node: classifier) -> Any: ... + def depart_colspec(self, node: colspec) -> Any: ... + def depart_comment(self, node: comment) -> Any: ... + def depart_compound(self, node: compound) -> Any: ... + def depart_contact(self, node: contact) -> Any: ... + def depart_container(self, node: container) -> Any: ... + def depart_copyright(self, node: copyright) -> Any: ... + def depart_danger(self, node: danger) -> Any: ... + def depart_date(self, node: date) -> Any: ... + def depart_decoration(self, node: decoration) -> Any: ... + def depart_definition(self, node: definition) -> Any: ... + def depart_definition_list(self, node: definition_list) -> Any: ... + def depart_definition_list_item(self, node: definition_list_item) -> Any: ... + def depart_description(self, node: description) -> Any: ... + def depart_docinfo(self, node: docinfo) -> Any: ... + def depart_doctest_block(self, node: doctest_block) -> Any: ... + def depart_document(self, node: _Document) -> Any: ... + def depart_emphasis(self, node: emphasis) -> Any: ... + def depart_entry(self, node: entry) -> Any: ... + def depart_enumerated_list(self, node: enumerated_list) -> Any: ... + def depart_error(self, node: error) -> Any: ... + def depart_field(self, node: field) -> Any: ... + def depart_field_body(self, node: field_body) -> Any: ... + def depart_field_list(self, node: field_list) -> Any: ... + def depart_field_name(self, node: field_name) -> Any: ... + def depart_figure(self, node: figure) -> Any: ... + def depart_footer(self, node: footer) -> Any: ... + def depart_footnote(self, node: footnote) -> Any: ... + def depart_footnote_reference(self, node: footnote_reference) -> Any: ... + def depart_generated(self, node: generated) -> Any: ... + def depart_header(self, node: header) -> Any: ... + def depart_hint(self, node: hint) -> Any: ... + def depart_image(self, node: image) -> Any: ... + def depart_important(self, node: important) -> Any: ... + def depart_inline(self, node: inline) -> Any: ... + def depart_label(self, node: label) -> Any: ... + def depart_legend(self, node: legend) -> Any: ... + def depart_line(self, node: line) -> Any: ... + def depart_line_block(self, node: line_block) -> Any: ... + def depart_list_item(self, node: list_item) -> Any: ... + def depart_literal(self, node: literal) -> Any: ... + def depart_literal_block(self, node: literal_block) -> Any: ... + def depart_math(self, node: math) -> Any: ... + def depart_math_block(self, node: math_block) -> Any: ... + def depart_meta(self, node: meta) -> Any: ... + def depart_note(self, node: note) -> Any: ... + def depart_option(self, node: option) -> Any: ... + def depart_option_argument(self, node: option_argument) -> Any: ... + def depart_option_group(self, node: option_group) -> Any: ... + def depart_option_list(self, node: option_list) -> Any: ... + def depart_option_list_item(self, node: option_list_item) -> Any: ... + def depart_option_string(self, node: option_string) -> Any: ... + def depart_organization(self, node: organization) -> Any: ... + def depart_paragraph(self, node: paragraph) -> Any: ... + def depart_pending(self, node: pending) -> Any: ... + def depart_problematic(self, node: problematic) -> Any: ... + def depart_raw(self, node: raw) -> Any: ... + def depart_reference(self, node: reference) -> Any: ... + def depart_revision(self, node: revision) -> Any: ... + def depart_row(self, node: row) -> Any: ... + def depart_rubric(self, node: rubric) -> Any: ... + def depart_section(self, node: section) -> Any: ... + def depart_sidebar(self, node: sidebar) -> Any: ... + def depart_status(self, node: status) -> Any: ... + def depart_strong(self, node: strong) -> Any: ... + def depart_subscript(self, node: subscript) -> Any: ... + def depart_substitution_definition(self, node: substitution_definition) -> Any: ... + def depart_substitution_reference(self, node: substitution_reference) -> Any: ... + def depart_subtitle(self, node: subtitle) -> Any: ... + def depart_superscript(self, node: superscript) -> Any: ... + def depart_system_message(self, node: system_message) -> Any: ... + def depart_table(self, node: table) -> Any: ... + def depart_target(self, node: target) -> Any: ... + def depart_tbody(self, node: tbody) -> Any: ... + def depart_term(self, node: term) -> Any: ... + def depart_tgroup(self, node: tgroup) -> Any: ... + def depart_thead(self, node: thead) -> Any: ... + def depart_tip(self, node: tip) -> Any: ... + def depart_title(self, node: title) -> Any: ... + def depart_title_reference(self, node: title_reference) -> Any: ... + def depart_topic(self, node: topic) -> Any: ... + def depart_transition(self, node: transition) -> Any: ... + def depart_version(self, node: version) -> Any: ... + def depart_warning(self, node: warning) -> Any: ... + +class SparseNodeVisitor(NodeVisitor): ... + +class GenericNodeVisitor(NodeVisitor): + def default_visit(self, node: Node) -> None: ... + def default_departure(self, node: Node) -> None: ... + +class TreeCopyVisitor(GenericNodeVisitor): + parent_stack: list[Node] + parent: list[Node] + def get_tree_copy(self) -> Node: ... + +class ValidationError(ValueError): + def __init__(self, msg: str, problematic_element: Element | None = None) -> None: ... + +class TreePruningException(Exception): ... +class SkipChildren(TreePruningException): ... +class SkipSiblings(TreePruningException): ... +class SkipNode(TreePruningException): ... +class SkipDeparture(TreePruningException): ... +class NodeFound(TreePruningException): ... +class StopTraversal(TreePruningException): ... + +def make_id(string: str) -> str: ... +def dupname(node: Node, name: str) -> None: ... +def fully_normalize_name(name: str) -> str: ... +def whitespace_normalize_name(name: str) -> str: ... +def serial_escape(value: str) -> str: ... +def split_name_list(s: str) -> list[str]: ... +def pseudo_quoteattr(value: str) -> str: ... +def parse_measure(measure: str, unit_pattern: str = "[a-zA-Zµ]*|%?") -> tuple[float, str]: ... +def create_keyword_validator(*keywords: str) -> Callable[[str], str]: ... +def validate_identifier(value: str) -> str: ... +def validate_identifier_list(value: str | list[str]) -> list[str]: ... +def validate_measure(measure: str) -> str: ... +def validate_colwidth(measure: str | float) -> float: ... +def validate_NMTOKEN(value: str) -> str: ... +def validate_NMTOKENS(value: str | list[str]) -> list[str]: ... +def validate_refname_list(value: str | list[str]) -> list[str]: ... +def validate_yesorno(value: str | int | bool) -> bool: ... + +ATTRIBUTE_VALIDATORS: dict[str, Callable[[str], Any]] diff --git a/stubs/docutils/docutils/parsers/__init__.pyi b/stubs/docutils/docutils/parsers/__init__.pyi index a77c183734e0..d15966c81088 100644 --- a/stubs/docutils/docutils/parsers/__init__.pyi +++ b/stubs/docutils/docutils/parsers/__init__.pyi @@ -1,16 +1,19 @@ -from typing import Any, ClassVar, Type +from typing import ClassVar, Final from docutils import Component +from docutils.nodes import _Document + +__docformat__: Final = "reStructuredText" class Parser(Component): component_type: ClassVar[str] config_section: ClassVar[str] - inputstring: Any # defined after call to setup_parse() - document: Any # defined after call to setup_parse() - def parse(self, inputstring: str, document) -> None: ... - def setup_parse(self, inputstring: str, document) -> None: ... + inputstring: str # defined after call to setup_parse() + document: _Document # defined after call to setup_parse() + def parse(self, inputstring: str, document: _Document) -> None: ... + def setup_parse(self, inputstring: str, document: _Document) -> None: ... def finish_parse(self) -> None: ... -_parser_aliases: dict[str, str] +PARSER_ALIASES: Final[dict[str, str]] -def get_parser_class(parser_name: str) -> Type[Parser]: ... +def get_parser_class(parser_name: str) -> type[Parser]: ... diff --git a/stubs/docutils/docutils/parsers/commonmark_wrapper.pyi b/stubs/docutils/docutils/parsers/commonmark_wrapper.pyi new file mode 100644 index 000000000000..a9b7a2c2956e --- /dev/null +++ b/stubs/docutils/docutils/parsers/commonmark_wrapper.pyi @@ -0,0 +1,9 @@ +from typing import Literal, TypeAlias + +from docutils import parsers + +_ParserName: TypeAlias = Literal["pycmark", "myst", "recommonmark"] + +commonmark_parser_names: tuple[_ParserName, ...] +Parser: type[parsers.Parser] # if Parser is None or parser_name is empty string, user cannot import current module +parser_name: _ParserName diff --git a/stubs/docutils/docutils/parsers/docutils_xml.pyi b/stubs/docutils/docutils/parsers/docutils_xml.pyi new file mode 100644 index 000000000000..d8351b0c7ea8 --- /dev/null +++ b/stubs/docutils/docutils/parsers/docutils_xml.pyi @@ -0,0 +1,16 @@ +import xml.etree.ElementTree as ET +from typing import ClassVar, Final + +from docutils import nodes, parsers + +__docformat__: Final = "reStructuredText" + +class Parser(parsers.Parser): + config_section_dependencies: ClassVar[tuple[str, ...]] + settings_default_overrides: ClassVar[dict[str, bool]] + +class Unknown(nodes.Special, nodes.Inline, nodes.Element): ... + +def parse_element(inputstring: str, document: nodes.document | None = None) -> nodes.Element: ... +def element2node(element: ET.Element | None, document: nodes.document | None = None, unindent: bool = True) -> nodes.Element: ... +def append_text(node: nodes.Element, text: str | None, unindent: bool | None) -> None: ... diff --git a/stubs/docutils/docutils/parsers/null.pyi b/stubs/docutils/docutils/parsers/null.pyi index 1d3629109243..ff81ca28c7fd 100644 --- a/stubs/docutils/docutils/parsers/null.pyi +++ b/stubs/docutils/docutils/parsers/null.pyi @@ -1,6 +1,9 @@ -from typing import ClassVar, Tuple +from typing import ClassVar, Final from docutils import parsers +__docformat__: Final = "reStructuredText" + class Parser(parsers.Parser): - config_section_dependencies: ClassVar[Tuple[str, ...]] + supported: ClassVar[tuple[str, ...]] + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi b/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi index 964e6fa3f426..3f12ce9e59f7 100644 --- a/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi +++ b/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi @@ -1,3 +1,55 @@ -from typing import Any +from types import ModuleType +from typing import ClassVar +from typing_extensions import deprecated -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import nodes +from docutils.transforms import Transform + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +class pending_xref(nodes.Inline, nodes.Element): ... + +sphinx: ModuleType + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +def is_literal(node: nodes.Node) -> bool: ... + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +class _CommonMarkParser: + default_config: ClassVar[dict[str, None]] + def __init__(self) -> None: ... + def convert_ast(self, ast): ... + def default_visit(self, mdnode): ... + def default_depart(self, mdnode): ... + def visit_heading(self, mdnode): ... + def depart_heading(self, _): ... + def visit_text(self, mdnode): ... + def visit_softbreak(self, _): ... + def visit_linebreak(self, _): ... + def visit_paragraph(self, mdnode): ... + def visit_emph(self, _): ... + def visit_strong(self, _): ... + def visit_code(self, mdnode): ... + def visit_link(self, mdnode): ... + def depart_link(self, mdnode): ... + def visit_image(self, mdnode): ... + def visit_list(self, mdnode): ... + def visit_item(self, mdnode): ... + def visit_code_block(self, mdnode): ... + def visit_block_quote(self, mdnode): ... + def visit_html(self, mdnode): ... + def visit_html_inline(self, mdnode): ... + def visit_html_block(self, mdnode): ... + def visit_thematic_break(self, _): ... + def setup_sections(self): ... + def add_section(self, section, level): ... + def is_section_level(self, level, section): ... + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +class Parser(_CommonMarkParser): + supported: ClassVar[tuple[str, ...]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + def get_transforms(self) -> list[type[Transform]]: ... + def parse(self, inputstring: str, document: nodes.document) -> None: ... + def visit_document(self, node) -> None: ... + def visit_text(self, mdnode) -> None: ... diff --git a/stubs/docutils/docutils/parsers/rst/__init__.pyi b/stubs/docutils/docutils/parsers/rst/__init__.pyi index f605176c4173..2ec7af62d1e1 100644 --- a/stubs/docutils/docutils/parsers/rst/__init__.pyi +++ b/stubs/docutils/docutils/parsers/rst/__init__.pyi @@ -1,34 +1,70 @@ -from typing import Any, ClassVar, Tuple -from typing_extensions import Literal +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import Any, ClassVar, Final, Literal, TypeAlias -from docutils import parsers -from docutils.parsers.rst import states +from docutils import nodes, parsers +from docutils.parsers.rst.states import Inliner, RSTState, RSTStateMachine +from docutils.statemachine import StringList +from docutils.transforms import Transform +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" class Parser(parsers.Parser): - config_section_dependencies: ClassVar[Tuple[str, ...]] + config_section_dependencies: ClassVar[tuple[str, ...]] initial_state: Literal["Body", "RFC2822Body"] - state_classes: Any - inliner: Any - def __init__(self, rfc2822: bool = ..., inliner: Any | None = ...) -> None: ... + state_classes: Sequence[type[RSTState]] + inliner: Inliner | None + statemachine: RSTStateMachine + def __init__(self, rfc2822: bool = False, inliner: Inliner | None = None) -> None: ... + def get_transforms(self) -> list[type[Transform]]: ... + def parse(self, inputstring: str, document: nodes.document) -> None: ... class DirectiveError(Exception): - level: Any + level: int msg: str - def __init__(self, level: Any, message: str) -> None: ... + def __init__(self, level: int, message: str) -> None: ... class Directive: + required_arguments: ClassVar[int] + optional_arguments: ClassVar[int] + final_argument_whitespace: ClassVar[bool] + option_spec: ClassVar[dict[str, Callable[[str], Incomplete]] | None] + has_content: ClassVar[bool] + name: str + arguments: list[str] + options: dict[str, Incomplete] + content: StringList + lineno: int + content_offset: int + block_text: str + state: RSTState + state_machine: RSTStateMachine = ... + reporter: Reporter def __init__( self, name: str, - arguments: list[Any], - options: dict[str, Any], - content: list[str], + arguments: list[str], + options: dict[str, Incomplete], + content: StringList, lineno: int, content_offset: int, block_text: str, - state: states.RSTState, - state_machine: states.RSTStateMachine, + state: RSTState, + state_machine: RSTStateMachine, ) -> None: ... - def __getattr__(self, name: str) -> Any: ... # incomplete + def run(self) -> Sequence[nodes.Node]: ... + def directive_error(self, level: int, message: str) -> DirectiveError: ... + def debug(self, message: str) -> DirectiveError: ... + def info(self, message: str) -> DirectiveError: ... + def warning(self, message: str) -> DirectiveError: ... + def error(self, message: str) -> DirectiveError: ... + def severe(self, message: str) -> DirectiveError: ... + def assert_has_content(self) -> None: ... + def add_name(self, node: nodes.Node) -> None: ... + +_DirectiveFn: TypeAlias = Callable[ + [str, list[str], dict[str, Any], StringList, int, int, str, RSTState, RSTStateMachine], Directive +] -def convert_directive_function(directive_fn): ... +def convert_directive_function(directive_fn: _DirectiveFn) -> type[Directive]: ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/__init__.pyi b/stubs/docutils/docutils/parsers/rst/directives/__init__.pyi new file mode 100644 index 000000000000..501bb87ddaf9 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/__init__.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable, Container, Iterable, Sequence +from re import Pattern +from typing import Final, Literal + +from docutils.languages import _LanguageModule +from docutils.nodes import document, system_message +from docutils.parsers import Parser +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +def register_directive(name: str, directive: type[Directive]) -> None: ... +def directive( + directive_name: str, language_module: _LanguageModule, document: document +) -> tuple[type[Directive] | None, list[system_message]]: ... +def flag(argument: str | None) -> None: ... +def unchanged_required(argument: str) -> str: ... +def unchanged(argument: str | None) -> str: ... +def path(argument: str) -> str: ... +def uri(argument: str) -> str: ... +def nonnegative_int(argument: str) -> int: ... +def percentage(argument: str) -> int: ... + +CSS3_LENGTH_UNITS: Final[tuple[str, ...]] +length_units: Final[list[str]] + +def get_measure(argument: str, units: Iterable[str]) -> str: ... +def length_or_unitless(argument: str) -> str: ... +def length_or_percentage_or_unitless(argument: str, default: str = "") -> str: ... +def class_option(argument: str) -> list[str]: ... + +unicode_pattern: Final[Pattern[str]] + +def unicode_code(code: str) -> str: ... +def single_char_or_unicode(argument: str) -> str: ... +def single_char_or_whitespace_or_unicode(argument: str | Literal["tab", "space"]) -> str: ... # noqa: Y051 +def positive_int(argument: str) -> int: ... +def positive_int_list(argument: str) -> list[int]: ... +def encoding(argument: str) -> str: ... +def choice(argument: str, values: Sequence[str]) -> str: ... +def format_values(values: Sequence[object]) -> str: ... +def value_or(values: Container[str], other: Callable[[str], str]) -> Callable[[str], str]: ... +def parser_name(argument: str | None) -> type[Parser] | None: ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi b/stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi new file mode 100644 index 000000000000..58c4e5debc63 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi @@ -0,0 +1,39 @@ +from typing import Final + +from docutils import nodes +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class BaseAdmonition(Directive): + node_class: type[nodes.Admonition] # Subclasses must set this to the appropriate admonition node class. + +class Admonition(BaseAdmonition): + node_class: type[nodes.admonition] + +class Attention(BaseAdmonition): + node_class: type[nodes.attention] + +class Caution(BaseAdmonition): + node_class: type[nodes.caution] + +class Danger(BaseAdmonition): + node_class: type[nodes.danger] + +class Error(BaseAdmonition): + node_class: type[nodes.error] + +class Hint(BaseAdmonition): + node_class: type[nodes.hint] + +class Important(BaseAdmonition): + node_class: type[nodes.important] + +class Note(BaseAdmonition): + node_class: type[nodes.note] + +class Tip(BaseAdmonition): + node_class: type[nodes.tip] + +class Warning(BaseAdmonition): + node_class: type[nodes.warning] diff --git a/stubs/docutils/docutils/parsers/rst/directives/body.pyi b/stubs/docutils/docutils/parsers/rst/directives/body.pyi new file mode 100644 index 000000000000..345309e71599 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/body.pyi @@ -0,0 +1,73 @@ +from collections.abc import Callable +from typing import ClassVar, Final, TypeAlias + +from docutils import nodes +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +_DirectiveFn: TypeAlias = Callable[[str], str | list[str]] + +class BasePseudoSection(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + node_class: ClassVar[type[nodes.Node] | None] + invalid_parents: ClassVar[ + tuple[ + type[nodes.SubStructural], + type[nodes.Bibliographic], + type[nodes.Decorative], + type[nodes.Body], + type[nodes.Part], + type[nodes.topic], + ] + ] + def run(self): ... + +class Topic(BasePseudoSection): + node_class: ClassVar[type[nodes.Node]] + +class Sidebar(BasePseudoSection): + node_class: ClassVar[type[nodes.Node]] + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class LineBlock(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class ParsedLiteral(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class CodeBlock(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class MathBlock(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class Rubric(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class BlockQuote(Directive): + classes: ClassVar[list[str]] + def run(self): ... + +class Epigraph(BlockQuote): + classes: ClassVar[list[str]] + +class Highlights(BlockQuote): + classes: ClassVar[list[str]] + +class PullQuote(BlockQuote): + classes: ClassVar[list[str]] + +class Compound(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class Container(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/html.pyi b/stubs/docutils/docutils/parsers/rst/directives/html.pyi new file mode 100644 index 000000000000..d4dc9ba85ed5 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/html.pyi @@ -0,0 +1,5 @@ +from typing import Final + +from docutils.parsers.rst.directives.misc import Meta as Meta, MetaBody as MetaBody + +__docformat__: Final = "reStructuredText" diff --git a/stubs/docutils/docutils/parsers/rst/directives/images.pyi b/stubs/docutils/docutils/parsers/rst/directives/images.pyi new file mode 100644 index 000000000000..cd9654c65b4c --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/images.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from typing import Final + +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class Image(Directive): + align_h_values: Incomplete + align_v_values: Incomplete + align_values: Incomplete + loading_values: Incomplete + def align(argument): ... + def loading(argument): ... + +class Figure(Image): + def align(argument): ... + def figwidth_value(argument): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/misc.pyi b/stubs/docutils/docutils/parsers/rst/directives/misc.pyi new file mode 100644 index 000000000000..46b89b555d45 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/misc.pyi @@ -0,0 +1,46 @@ +from _typeshed import StrPath +from pathlib import Path +from re import Match, Pattern +from typing import ClassVar, Final + +from docutils import nodes +from docutils.parsers.rst import Directive +from docutils.parsers.rst.states import SpecializedBody + +__docformat__: Final = "reStructuredText" + +def adapt_path(path: str, source: StrPath = "", root_prefix: StrPath = "") -> str: ... + +class Include(Directive): + standard_include_path: Path + def read_file(self, path: StrPath) -> str: ... + def as_literal_block(self, text: str) -> list[nodes.literal_block]: ... + def as_code_block(self, text: str) -> list[nodes.literal_block]: ... + def custom_parse(self, text: str) -> list[nodes.Node]: ... + def insert_into_input_lines(self, text: str) -> None: ... + +class Raw(Directive): ... +class Replace(Directive): ... + +class Unicode(Directive): + comment_pattern: Pattern[str] + +class Class(Directive): ... + +class Role(Directive): + argument_pattern: Pattern[str] + +class DefaultRole(Directive): ... +class Title(Directive): ... + +class MetaBody(SpecializedBody): + def field_marker( # type: ignore[override] + self, match: Match[str], context: list[str], next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def parsemeta(self, match: Match[str]): ... + +class Meta(Directive): + SMkwargs: ClassVar[dict[str, tuple[MetaBody]]] + +class Date(Directive): ... +class TestDirective(Directive): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/parts.pyi b/stubs/docutils/docutils/parsers/rst/directives/parts.pyi new file mode 100644 index 000000000000..c69296038b5b --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/parts.pyi @@ -0,0 +1,14 @@ +from collections.abc import Sequence +from typing import Final + +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class Contents(Directive): + backlinks_values: Sequence[str] + def backlinks(arg): ... + +class Sectnum(Directive): ... +class Header(Directive): ... +class Footer(Directive): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/references.pyi b/stubs/docutils/docutils/parsers/rst/directives/references.pyi new file mode 100644 index 000000000000..412af33927d8 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/references.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class TargetNotes(Directive): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/tables.pyi b/stubs/docutils/docutils/parsers/rst/directives/tables.pyi new file mode 100644 index 000000000000..3bc3e4d3b430 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/tables.pyi @@ -0,0 +1,59 @@ +import csv +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import ClassVar, Final +from typing_extensions import deprecated + +from docutils import nodes +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +def align(argument): ... + +class Table(Directive): + option_spec: ClassVar[dict[str, Callable[[str], str | list[str]]]] + def make_title(self): ... + def check_table_dimensions(self, rows, header_rows, stub_columns) -> None: ... + def set_table_width(self, table_node) -> None: ... + @property + def widths(self): ... + def get_column_widths(self, n_cols): ... + def extend_short_rows_with_empty_cells(self, columns, parts) -> None: ... + +class RSTTable(Table): + def run(self) -> Sequence[nodes.table | nodes.system_message]: ... + +class CSVTable(Table): + class DocutilsDialect(csv.Dialect): + delimiter: str + quotechar: str + doublequote: bool + skipinitialspace: bool + strict: bool + lineterminator: str + quoting: Incomplete + escapechar: Incomplete + def __init__(self, options) -> None: ... + + @deprecated("Deprecated and will be removed in Docutils 1.0.") + class HeaderDialect(csv.Dialect): + delimiter: str + quotechar: str + escapechar: str + doublequote: bool + skipinitialspace: bool + strict: bool + lineterminator: str + quoting: Incomplete + def __init__(self) -> None: ... + + def process_header_option(self): ... + def run(self) -> Sequence[nodes.table | nodes.system_message]: ... + def get_csv_data(self): ... + def parse_csv_data_into_rows(self, csv_data, dialect, source): ... + +class ListTable(Table): + def run(self) -> Sequence[nodes.table | nodes.system_message]: ... + def check_list_content(self, node): ... + def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns) -> nodes.table: ... diff --git a/stubs/docutils/docutils/parsers/rst/languages/__init__.pyi b/stubs/docutils/docutils/parsers/rst/languages/__init__.pyi new file mode 100644 index 000000000000..e38d495da4b6 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/__init__.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar, Final, Protocol, type_check_only + +from docutils.languages import LanguageImporter +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +@type_check_only +class _RstLanguageModule(Protocol): + directives: dict[str, str] + roles: dict[str, str] + +class RstLanguageImporter(LanguageImporter): + cache: dict[str, _RstLanguageModule] # type: ignore[assignment] + fallback: ClassVar[None] # type: ignore[assignment] + def import_from_packages(self, name: str, reporter: Reporter | None = None) -> _RstLanguageModule: ... # type: ignore[override] + def check_content(self, module: _RstLanguageModule) -> None: ... # type: ignore[override] + def __call__(self, language_code: str, reporter: Reporter | None = None) -> _RstLanguageModule: ... # type: ignore[override] + +get_language: RstLanguageImporter diff --git a/stubs/docutils/docutils/parsers/rst/languages/af.pyi b/stubs/docutils/docutils/parsers/rst/languages/af.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/af.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ar.pyi b/stubs/docutils/docutils/parsers/rst/languages/ar.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ar.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ca.pyi b/stubs/docutils/docutils/parsers/rst/languages/ca.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ca.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/cs.pyi b/stubs/docutils/docutils/parsers/rst/languages/cs.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/cs.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/da.pyi b/stubs/docutils/docutils/parsers/rst/languages/da.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/da.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/de.pyi b/stubs/docutils/docutils/parsers/rst/languages/de.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/de.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/en.pyi b/stubs/docutils/docutils/parsers/rst/languages/en.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/en.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/eo.pyi b/stubs/docutils/docutils/parsers/rst/languages/eo.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/eo.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/es.pyi b/stubs/docutils/docutils/parsers/rst/languages/es.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/es.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/fa.pyi b/stubs/docutils/docutils/parsers/rst/languages/fa.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/fa.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/fi.pyi b/stubs/docutils/docutils/parsers/rst/languages/fi.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/fi.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/fr.pyi b/stubs/docutils/docutils/parsers/rst/languages/fr.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/fr.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/gl.pyi b/stubs/docutils/docutils/parsers/rst/languages/gl.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/gl.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/he.pyi b/stubs/docutils/docutils/parsers/rst/languages/he.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/he.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/it.pyi b/stubs/docutils/docutils/parsers/rst/languages/it.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/it.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ja.pyi b/stubs/docutils/docutils/parsers/rst/languages/ja.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ja.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ka.pyi b/stubs/docutils/docutils/parsers/rst/languages/ka.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ka.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ko.pyi b/stubs/docutils/docutils/parsers/rst/languages/ko.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ko.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/lt.pyi b/stubs/docutils/docutils/parsers/rst/languages/lt.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/lt.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/lv.pyi b/stubs/docutils/docutils/parsers/rst/languages/lv.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/lv.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/nl.pyi b/stubs/docutils/docutils/parsers/rst/languages/nl.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/nl.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/pl.pyi b/stubs/docutils/docutils/parsers/rst/languages/pl.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/pl.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi b/stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ru.pyi b/stubs/docutils/docutils/parsers/rst/languages/ru.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ru.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/sk.pyi b/stubs/docutils/docutils/parsers/rst/languages/sk.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/sk.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/sv.pyi b/stubs/docutils/docutils/parsers/rst/languages/sv.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/sv.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/uk.pyi b/stubs/docutils/docutils/parsers/rst/languages/uk.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/uk.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi b/stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi b/stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/nodes.pyi b/stubs/docutils/docutils/parsers/rst/nodes.pyi deleted file mode 100644 index 964e6fa3f426..000000000000 --- a/stubs/docutils/docutils/parsers/rst/nodes.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete diff --git a/stubs/docutils/docutils/parsers/rst/roles.pyi b/stubs/docutils/docutils/parsers/rst/roles.pyi index 2c3d65b68c94..8c91bff07b63 100644 --- a/stubs/docutils/docutils/parsers/rst/roles.pyi +++ b/stubs/docutils/docutils/parsers/rst/roles.pyi @@ -1,12 +1,135 @@ -from typing import Any, Callable, Dict, List, Tuple +from collections.abc import Callable, Mapping, Sequence +from typing import Any, Final, TypeAlias +from typing_extensions import deprecated -import docutils.nodes import docutils.parsers.rst.states +from docutils import nodes +from docutils.languages import _LanguageModule +from docutils.nodes import Node, system_message +from docutils.parsers.rst.states import Inliner +from docutils.utils import Reporter -_RoleFn = Callable[ - [str, str, str, int, docutils.parsers.rst.states.Inliner, Dict[str, Any], List[str]], - Tuple[List[docutils.nodes.reference], List[docutils.nodes.reference]], +__docformat__: Final = "reStructuredText" +DEFAULT_INTERPRETED_ROLE: Final = "title-reference" + +_RoleFn: TypeAlias = Callable[ + [str, str, str, int, docutils.parsers.rst.states.Inliner, Mapping[str, Any], Sequence[str]], + tuple[Sequence[nodes.reference], Sequence[nodes.reference]], ] +def register_canonical_role(name: str, role_fn: _RoleFn) -> None: ... def register_local_role(name: str, role_fn: _RoleFn) -> None: ... -def __getattr__(name: str) -> Any: ... # incomplete +def role( + role_name: str, language_module: _LanguageModule, lineno: int, reporter: Reporter +) -> tuple[_RoleFn | None, list[system_message]]: ... +def set_implicit_options(role_fn: _RoleFn) -> None: ... +def register_generic_role(canonical_name: str, node_class: type[Node]) -> None: ... + +class GenericRole: + name: str + node_class: type[Node] + def __init__(self, role_name: str, node_class: type[Node]) -> None: ... + def __call__( + self, + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, + ) -> tuple[list[Node], list[system_message]]: ... + +class CustomRole: + name: str + base_role: _RoleFn | CustomRole + options: Mapping[str, Any] + content: Sequence[str] + supplied_options: Mapping[str, Any] + supplied_content: Sequence[str] + def __init__( + self, + role_name: str, + base_role: _RoleFn | CustomRole, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, + ) -> None: ... + def __call__( + self, + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, + ) -> tuple[list[Node], list[system_message]]: ... + +def generic_custom_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def pep_reference_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def rfc_reference_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def raw_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def code_role( + role_name: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def math_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def unimplemented_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +@deprecated("Deprecated and will be removed in Docutils 2.0, Use `roles.normalize_options()` instead.") +def set_classes(options: dict[str, str]) -> None: ... +@deprecated("Deprecated and will be removed in Docutils 2.0, Use `roles.normalize_options()` instead.") +def normalized_role_options(options: Mapping[str, Any] | None) -> dict[str, Any]: ... +def normalize_options(options: Mapping[str, Any] | None) -> dict[str, Any]: ... diff --git a/stubs/docutils/docutils/parsers/rst/states.pyi b/stubs/docutils/docutils/parsers/rst/states.pyi index a7f106948a78..d148d2521222 100644 --- a/stubs/docutils/docutils/parsers/rst/states.pyi +++ b/stubs/docutils/docutils/parsers/rst/states.pyi @@ -1,6 +1,390 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence +from re import Match, Pattern +from types import ModuleType, SimpleNamespace as Struct +from typing import Any, ClassVar, Final, TypeAlias +from typing_extensions import Never + +from docutils import ApplicationError, DataError, nodes +from docutils.nodes import Node, system_message +from docutils.parsers.rst.languages import _RstLanguageModule +from docutils.statemachine import StateMachine, StateMachineWS, StateWS, StringList +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +class MarkupError(DataError): ... +class UnknownInterpretedRoleError(DataError): ... +class InterpretedRoleNotImplementedError(DataError): ... +class ParserError(ApplicationError): ... +class MarkupMismatch(Exception): ... + +class RSTStateMachine(StateMachineWS[list[str]]): + language: _RstLanguageModule + match_titles: bool + memo: Struct | None + document: nodes.document + reporter: Reporter + node: nodes.document | None + section_level_offset: int + def run( # type: ignore[override] + self, + input_lines: Sequence[str] | StringList, + document: nodes.document, + input_offset: int = 0, + match_titles: bool = True, + inliner: Inliner | None = None, + ) -> None: ... + +class NestedStateMachine(RSTStateMachine): + parent_state_machine: Incomplete | None + def __init__(self, state_classes, initial_state, debug: bool = False, parent_state_machine=None) -> None: ... + def run( # type: ignore[override] + self, input_lines: Sequence[str] | StringList, input_offset: int, memo, node, match_titles: bool = True + ) -> list[str]: ... + +class RSTState(StateWS[list[str]]): + nested_sm: type[NestedStateMachine] + nested_sm_cache: list[StateMachine[Incomplete]] + def __init__(self, state_machine, debug: bool = False) -> None: ... + memo: Incomplete + reporter: Reporter + inliner: Inliner + document: nodes.document + parent: Incomplete + def runtime_init(self) -> None: ... + def goto_line(self, abs_line_offset: int) -> None: ... + def no_match(self, context: list[str], transitions): ... + def bof(self, context: list[str]): ... + def nested_parse( + self, + block: StringList, + input_offset: int, + node: nodes.Element | None = None, + match_titles: bool = False, + state_machine_class: StateMachineWS[Incomplete] | None = None, + state_machine_kwargs: dict[Incomplete, Incomplete] | None = None, + ) -> int: ... + def nested_list_parse( + self, + block, + input_offset: int, + node, + initial_state, + blank_finish, + blank_finish_state=None, + extra_settings={}, + match_titles: bool = False, + state_machine_class=None, + state_machine_kwargs=None, + ): ... + def section(self, title: str, source, style, lineno: int, messages) -> None: ... + def check_subsection(self, source, style, lineno: int): ... + def title_inconsistent(self, sourcetext: str, lineno: int): ... + def new_subsection(self, title: str, lineno: int, messages) -> None: ... + def paragraph(self, lines: Iterable[str], lineno: int): ... + def inline_text(self, text: str, lineno: int) -> tuple[list[Node], list[system_message]]: ... + def unindent_warning(self, node_name: str): ... + +def build_regexp(definition, compile_patterns: bool | None = True): ... + +_BasicDefinition: TypeAlias = tuple[str, str, str, list[Pattern[str]]] +_DefinitionParts: TypeAlias = tuple[str, str, str, list[Pattern[str] | _BasicDefinition]] +_DefinitionType: TypeAlias = tuple[str, str, str, list[Pattern[str] | _DefinitionParts]] class Inliner: + implicit_dispatch: list[tuple[Pattern[str], Callable[[Match[str], int], Sequence[nodes.Node]]]] def __init__(self) -> None: ... + start_string_prefix: str + end_string_suffix: str + parts: _DefinitionType + patterns: Struct + def init_customizations(self, settings: Any) -> None: ... + reporter: Reporter + document: nodes.document + language: ModuleType + parent: nodes.Element + def parse( + self, text: str, lineno: int, memo: Struct, parent: nodes.Element + ) -> tuple[list[nodes.Node], list[nodes.system_message]]: ... + non_whitespace_before: str + non_whitespace_escape_before: str + non_unescaped_whitespace_escape_before: str + non_whitespace_after: str + simplename: str + uric: str + uri_end_delim: str + urilast: str + uri_end: str + emailc: str + email_pattern: str + def quoted_start(self, match: Match[str]) -> bool: ... + def inline_obj( + self, + match: Match[str], + lineno: int, + end_pattern: Pattern[str], + nodeclass: nodes.TextElement, + restore_backslashes: bool = False, + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message], str]: ... + def problematic(self, text: str, rawsource: str, message: nodes.system_message) -> nodes.problematic: ... + def emphasis( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def strong(self, match: Match[str], lineno: int) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def interpreted_or_phrase_ref( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def phrase_ref( + self, before: str, after: str, rawsource: str, escaped: str, text: str | None = None + ) -> tuple[str, list[nodes.Node], str, list[nodes.Node]]: ... + def adjust_uri(self, uri: str) -> str: ... + def interpreted( + self, rawsource: str, text: str, role: str, lineno: int + ) -> tuple[list[nodes.Node], list[nodes.system_message]]: ... + def literal(self, match: Match[str], lineno: int) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def inline_internal_target( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def substitution_reference( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def footnote_reference( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def reference( + self, match: Match[str], lineno: int, anonymous: bool = False + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def anonymous_reference( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def standalone_uri( + self, match: Match[str], lineno: int + ) -> list[tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]: ... + def pep_reference( + self, match: Match[str], lineno: int + ) -> list[tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]: ... + rfc_url: str = ... + def rfc_reference( + self, match: Match[str], lineno: int + ) -> list[tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]: ... + def implicit_inline(self, text: str, lineno: int) -> list[nodes.Text]: ... + dispatch: dict[str, Callable[[Match[str], int], tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]] = ... + +class Body(RSTState): + double_width_pad_char: Incomplete + enum: Incomplete + grid_table_top_pat: Incomplete + simple_table_top_pat: Incomplete + simple_table_border_pat: Incomplete + pats: Incomplete + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[tuple[str, ...]] + sequence: str + format: str + def indent(self, match, context, next_state): ... + def block_quote(self, indented, line_offset): ... + attribution_pattern: Incomplete + def split_attribution(self, indented, line_offset): ... + def check_attribution(self, indented, attribution_start): ... + def parse_attribution(self, indented, line_offset): ... + def bullet(self, match, context, next_state): ... + def list_item(self, indent): ... + def enumerator(self, match, context, next_state): ... + def parse_enumerator(self, match, expected_sequence=None): ... + def is_enumerated_list_item(self, ordinal, sequence, format): ... + def make_enumerator(self, ordinal, sequence, format): ... + def field_marker(self, match, context, next_state): ... + def field(self, match): ... + def parse_field_marker(self, match): ... + def parse_field_body(self, indented, offset, node) -> None: ... + def option_marker(self, match, context, next_state): ... + def option_list_item(self, match): ... + def parse_option_marker(self, match): ... + def doctest(self, match, context, next_state): ... + def line_block(self, match, context, next_state): ... + def line_block_line(self, match, lineno): ... + def nest_line_block_lines(self, block) -> None: ... + def nest_line_block_segment(self, block) -> None: ... + def grid_table_top(self, match, context, next_state): ... + def simple_table_top(self, match, context, next_state): ... + def table_top(self, match, context, next_state, isolate_function, parser_class): ... + def table(self, isolate_function, parser_class): ... + def isolate_grid_table(self): ... + def isolate_simple_table(self): ... + def malformed_table(self, block, detail: str = "", offset: int = 0): ... + def build_table(self, tabledata, tableline, stub_columns: int = 0, widths=None) -> nodes.table: ... + def build_table_row(self, rowdata, tableline): ... + explicit: Incomplete + def footnote(self, match): ... + def citation(self, match): ... + def hyperlink_target(self, match): ... + def make_target(self, block, block_text, lineno, target_name): ... + def parse_target(self, block, block_text, lineno): ... + def is_reference(self, reference): ... + def add_target(self, targetname, refuri, target, lineno) -> None: ... + def substitution_def(self, match): ... + def disallowed_inside_substitution_definitions(self, node): ... + def directive(self, match, **option_presets): ... + def run_directive(self, directive, match, type_name, option_presets): ... + def parse_directive_block(self, indented, line_offset, directive, option_presets): ... + def parse_directive_options(self, option_presets, option_spec, arg_block): ... + def parse_directive_arguments(self, directive, arg_block): ... + def parse_extension_options(self, option_spec, datalines): ... + def unknown_directive(self, type_name): ... + def comment(self, match): ... + def explicit_markup(self, match, context, next_state): ... + def explicit_construct(self, match): ... + def explicit_list(self, blank_finish) -> None: ... + def anonymous(self, match: Match[str], context: list[str] | None, next_state: str): ... + def anonymous_target(self, match): ... + def line(self, match, context, next_state): ... + def text(self, match, context, next_state): ... + +class RFC2822Body(Body): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[tuple[str | tuple[str, str], str]]] # type: ignore[assignment] + def rfc2822(self, match, context, next_state): ... + def rfc2822_field(self, match): ... + +class SpecializedBody(Body): + def invalid_input( + self, match: Match[str] | None = None, context: list[str] | None = None, next_state: str | None = None + ) -> Never: ... + indent = invalid_input # type: ignore[assignment] + bullet = invalid_input + enumerator = invalid_input + field_marker = invalid_input + option_marker = invalid_input + doctest = invalid_input + line_block = invalid_input + grid_table_top = invalid_input + simple_table_top = invalid_input + explicit_markup = invalid_input + anonymous = invalid_input # type: ignore[assignment] + line = invalid_input + text = invalid_input + +class BulletList(SpecializedBody): + blank_finish: Incomplete + def bullet( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class DefinitionList(SpecializedBody): + def text(self, match: Match[str], context: list[str] | None, next_state: str | None) -> tuple[list[str], str, list[str]]: ... # type: ignore[override] + +class EnumeratedList(SpecializedBody): + auto: int + blank_finish: Incomplete + lastordinal: Incomplete + def enumerator( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class FieldList(SpecializedBody): + blank_finish: Incomplete + def field_marker( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class OptionList(SpecializedBody): + blank_finish: Incomplete + def option_marker( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class RFC2822List(SpecializedBody, RFC2822Body): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[tuple[str | tuple[str, str], str]]] # type: ignore[assignment] + blank_finish: Incomplete + def rfc2822(self, match, context, next_state): ... + blank: Incomplete + +class ExtensionOptions(FieldList): + def parse_field_body(self, indented, offset, node) -> None: ... + +class LineBlock(SpecializedBody): + blank: Incomplete + blank_finish: Incomplete + def line_block( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class Explicit(SpecializedBody): + blank_finish: Incomplete + blank: Incomplete + def explicit_markup( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def anonymous( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class SubstitutionDef(Body): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[str]] # type: ignore[assignment] + blank_finish: Incomplete + def embedded_directive(self, match, context, next_state) -> None: ... + def text(self, match, context, next_state) -> None: ... + +class Text(RSTState): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[tuple[str, str]]] + def blank(self, match, context, next_state): ... + def eof(self, context): ... + def indent(self, match, context, next_state): ... + def underline(self, match, context, next_state): ... + def text(self, match, context, next_state): ... + def literal_block(self): ... + def quoted_literal_block(self): ... + def definition_list_item(self, termline): ... + classifier_delimiter: Incomplete + def term(self, lines, lineno): ... + +class SpecializedText(Text): + def eof(self, context): ... + def invalid_input( + self, match: Match[str] | None = None, context: list[str] | None = None, next_state: str | None = None + ) -> Never: ... + blank = invalid_input + indent = invalid_input + underline = invalid_input + text = invalid_input + +class Definition(SpecializedText): + def eof(self, context): ... + blank_finish: Incomplete + def indent( # type: ignore[override] + self, match: Match[str] | None, context: list[str], next_state: str | None + ) -> tuple[list[str], str, list[str]]: ... + +class Line(SpecializedText): + eofcheck: int + def eof(self, context: list[str]): ... + def blank(self, match: Match[str] | None, context: list[str], next_state: str | None) -> tuple[list[str], str, list[str]]: ... # type: ignore[override] + def text(self, match: Match[str], context: list[str], next_state: str | None) -> tuple[list[str], str, list[str]]: ... # type: ignore[override] + indent = text # type: ignore[assignment] + def underline( # type: ignore[override] + self, match: Match[str] | None, context: list[str], next_state: str | None + ) -> tuple[list[str], str, list[str]]: ... + def short_overline(self, context, blocktext, lineno, lines: int = 1) -> None: ... + def state_correction(self, context, lines: int = 1) -> None: ... + +class QuotedLiteralBlock(RSTState): + patterns: ClassVar[dict[str, str | Pattern[str]]] + messages: Incomplete + initial_lineno: Incomplete + def __init__(self, state_machine, debug: bool = False) -> None: ... + def blank(self, match, context, next_state): ... + def eof(self, context): ... + def indent(self, match: Match[str] | None, context: list[str], next_state: str | None) -> Never: ... + def initial_quoted( + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def quoted( + self, match: Match[str], context: list[str], next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def text(self, match: Match[str] | None, context: list[str] | None, next_state: str | None) -> None: ... -def __getattr__(name: str) -> Any: ... # incomplete +state_classes: tuple[type[RSTState], ...] diff --git a/stubs/docutils/docutils/parsers/rst/tableparser.pyi b/stubs/docutils/docutils/parsers/rst/tableparser.pyi new file mode 100644 index 000000000000..ad805b9ccd52 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/tableparser.pyi @@ -0,0 +1,64 @@ +from re import Pattern +from typing import ClassVar, Final, TypeAlias + +from docutils import DataError +from docutils.statemachine import StringList + +_Cell: TypeAlias = tuple[int, int, int, list[str]] +_Row: TypeAlias = list[_Cell | None] +_Colspecs: TypeAlias = list[int] + +__docformat__: Final = "reStructuredText" + +class TableMarkupError(DataError): + offset: int + def __init__(self, *args, **kwargs) -> None: ... + +class TableParser: + head_body_separator_pat: ClassVar[Pattern[str] | None] + double_width_pad_char: ClassVar[str] + head_body_sep: int + def parse(self, block: StringList) -> tuple[_Colspecs, list[_Row], list[_Row]]: ... + def find_head_body_sep(self) -> None: ... + +class GridTableParser(TableParser): + head_body_separator_pat: ClassVar[Pattern[str]] + block: StringList + bottom: int + right: int + head_body_sep: int + done: list[int] + cells: list[_Cell] + rowseps: dict[int, list[int]] + colseps: dict[int, list[int]] + def setup(self, block: StringList) -> None: ... + def parse_table(self) -> None: ... + def mark_done(self, top: int, left: int, bottom: int, right: int) -> None: ... + def check_parse_complete(self) -> bool: ... + def scan_cell(self, top: int, left: int) -> tuple[int, int, dict[int, list[int]], dict[int, list[int]]]: ... + def scan_right(self, top: int, left: int) -> tuple[int, int, dict[int, list[int]], dict[int, list[int]]]: ... + def scan_down(self, top: int, left: int, right: int) -> tuple[int, dict[int, list[int]], dict[int, list[int]]]: ... + def scan_left(self, top: int, left: int, bottom: int, right: int) -> tuple[dict[int, list[int]], dict[int, list[int]]]: ... + def scan_up(self, top: int, left: int, bottom: int, right: int) -> dict[int, list[int]]: ... + def structure_from_cells(self) -> tuple[_Colspecs, list[_Row], list[_Row]]: ... + +class SimpleTableParser(TableParser): + head_body_separator_pat: ClassVar[Pattern[str]] + span_pat: ClassVar[Pattern[str]] + block: StringList + head_body_sep: int + columns: list[tuple[int, int]] + border_end: int + table: tuple[list[int], list[_Row], list[_Row]] + done: list[int] + rowseps: dict[int, tuple[int]] + colseps: dict[int, tuple[int]] + def setup(self, block: StringList) -> None: ... + def parse_table(self) -> None: ... + def parse_columns(self, line: str, offset: int) -> list[tuple[int, int]]: ... + def init_row(self, colspec: list[tuple[int, int]], offset: int) -> list[_Cell]: ... + def parse_row(self, lines: list[str], start: int, spanline: tuple[str, int] | None = None) -> None: ... + def check_columns(self, lines: list[str], first_line: int, columns: list[tuple[int, int]]) -> None: ... + def structure_from_cells(self) -> tuple[_Colspecs, list[_Row], list[_Row]]: ... + +def update_dict_of_lists(master: dict[int, list[int]], newdata: dict[int, list[int]]) -> None: ... diff --git a/stubs/docutils/docutils/readers/__init__.pyi b/stubs/docutils/docutils/readers/__init__.pyi index 964e6fa3f426..d29e4aa717d3 100644 --- a/stubs/docutils/docutils/readers/__init__.pyi +++ b/stubs/docutils/docutils/readers/__init__.pyi @@ -1,3 +1,31 @@ -from typing import Any +from typing import Any, ClassVar, Final, Generic, TypeVar -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import Component, nodes +from docutils.frontend import Values +from docutils.io import Input +from docutils.parsers import Parser +from docutils.transforms import Transform + +_S = TypeVar("_S") + +__docformat__: Final = "reStructuredText" + +class Reader(Component, Generic[_S]): + component_type: ClassVar[str] + config_section: ClassVar[str] + def get_transforms(self) -> list[type[Transform]]: ... + def __init__(self, parser: Parser | None = None, parser_name: str | None = None) -> None: ... + parser: Parser | None + source: Input[_S] | None + input: str | None + def set_parser(self, parser_name: str) -> None: ... + settings: Values + def read(self, source: Input[_S], parser: Parser, settings: Values) -> nodes.document: ... + document: nodes.document + def parse(self) -> None: ... + def new_document(self) -> nodes.document: ... + +class ReReader(Reader[_S]): + def get_transforms(self) -> list[type[Transform]]: ... + +def get_reader_class(reader_name: str) -> type[Reader[Any]]: ... diff --git a/stubs/docutils/docutils/readers/doctree.pyi b/stubs/docutils/docutils/readers/doctree.pyi index 964e6fa3f426..27be5d0e1f0e 100644 --- a/stubs/docutils/docutils/readers/doctree.pyi +++ b/stubs/docutils/docutils/readers/doctree.pyi @@ -1,3 +1,10 @@ -from typing import Any +from typing import ClassVar, Final, TypeVar -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import readers + +_S = TypeVar("_S", bound=str | bytes) + +__docformat__: Final = "reStructuredText" + +class Reader(readers.ReReader[_S]): + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/readers/pep.pyi b/stubs/docutils/docutils/readers/pep.pyi index 964e6fa3f426..ef0247369aad 100644 --- a/stubs/docutils/docutils/readers/pep.pyi +++ b/stubs/docutils/docutils/readers/pep.pyi @@ -1,3 +1,12 @@ -from typing import Any +from typing import ClassVar, Final, TypeVar -def __getattr__(name: str) -> Any: ... # incomplete +from docutils.parsers.rst import states +from docutils.readers import standalone + +__docformat__: Final = "reStructuredText" + +_S = TypeVar("_S", bound=str | bytes) + +class Reader(standalone.Reader[_S]): + settings_default_overrides: ClassVar[dict[str, int]] + inliner_class: ClassVar[type[states.Inliner]] diff --git a/stubs/docutils/docutils/readers/standalone.pyi b/stubs/docutils/docutils/readers/standalone.pyi index 964e6fa3f426..6e7319e2c5d1 100644 --- a/stubs/docutils/docutils/readers/standalone.pyi +++ b/stubs/docutils/docutils/readers/standalone.pyi @@ -1,3 +1,11 @@ -from typing import Any +from typing import ClassVar, Final, TypeVar -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import nodes, readers + +__docformat__: Final = "reStructuredText" + +_S = TypeVar("_S", bound=str | bytes) + +class Reader(readers.Reader[_S]): + document: nodes.document | None # type: ignore[assignment] + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/statemachine.pyi b/stubs/docutils/docutils/statemachine.pyi index 964e6fa3f426..96b5f38a7461 100644 --- a/stubs/docutils/docutils/statemachine.pyi +++ b/stubs/docutils/docutils/statemachine.pyi @@ -1,3 +1,205 @@ -from typing import Any +import sys +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from re import Match, Pattern +from typing import Any, ClassVar, Final, Generic, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self -def __getattr__(name: str) -> Any: ... # incomplete +_T = TypeVar("_T") +_Context = TypeVar("_Context") +_TransitionResult: TypeAlias = tuple[_Context, str | None, list[str]] +_TransitionMethod: TypeAlias = Callable[[Match[str], _Context, str], _TransitionResult[_Context]] +_Observer: TypeAlias = Callable[[StateMachine[_Context]], None] + +__docformat__: Final = "restructuredtext" + +class StateMachine(Generic[_Context]): + input_lines: StringList | None + input_offset: int + line: str | None + line_offset: int + debug: bool + initial_state: str + current_state: str + states: dict[str, State[_Context]] + observers: list[_Observer[_Context]] + def __init__(self, state_classes: Iterable[type[State[_Context]]], initial_state: str, debug: bool = False) -> None: ... + def unlink(self) -> None: ... + def run( + self, + input_lines: Sequence[str] | StringList, + input_offset: int = 0, + context: _Context | None = None, + input_source: str | None = None, + initial_state: str | None = None, + ) -> list[str]: ... + def get_state(self, next_state: str | None = None) -> State[_Context]: ... + def next_line(self, n: int = 1) -> str: ... + def is_next_line_blank(self) -> bool: ... + def at_eof(self) -> bool: ... + def at_bof(self) -> bool: ... + def previous_line(self, n: int = 1) -> str | None: ... + def goto_line(self, line_offset: int) -> str | None: ... + def get_source(self, line_offset: int) -> str: ... + def abs_line_offset(self) -> int: ... + def abs_line_number(self) -> int: ... + def get_source_and_line(self, lineno: int | None = None) -> tuple[str, int] | tuple[None, None]: ... + def insert_input(self, input_lines: list[str] | StringList, source: str) -> None: ... + def get_text_block(self, flush_left: bool = False) -> StringList: ... + def check_line( + self, context: _Context, state: State[_Context], transitions: list[str] | None = None + ) -> _TransitionResult[_Context]: ... + def add_state(self, state_class: type[State[_Context]]) -> None: ... + def add_states(self, state_classes: Iterable[type[State[_Context]]]) -> None: ... + def runtime_init(self) -> None: ... + def error(self) -> None: ... + def attach_observer(self, observer: _Observer[_Context]) -> None: ... + def detach_observer(self, observer: _Observer[_Context]) -> None: ... + def notify_observers(self) -> None: ... + +class State(Generic[_Context]): + patterns: ClassVar[dict[str, str | Pattern[str]] | None] + initial_transitions: ClassVar[Sequence[str] | Sequence[tuple[str, str]] | None] + nested_sm: type[StateMachine[_Context]] + nested_sm_kwargs: dict[str, Any] + transition_order: list[str] + transitions: dict[str, tuple[Pattern[str], Callable[[], None], str]] + state_machine: StateMachine[_Context] + debug: bool + def __init__(self, state_machine: StateMachine[_Context], debug: bool = False) -> None: ... + def runtime_init(self) -> None: ... + def unlink(self) -> None: ... + def add_initial_transitions(self) -> None: ... + def add_transitions(self, names: Iterable[str], transitions) -> None: ... + def add_transition(self, name: str, transition: tuple[Pattern[str], str, str]) -> None: ... + def remove_transition(self, name: str) -> None: ... + def make_transition( + self, name: str, next_state: str | None = None + ) -> tuple[Pattern[str], _TransitionMethod[_Context], str]: ... + def make_transitions( + self, name_list: list[str | tuple[str] | tuple[str, str]] + ) -> tuple[list[str], dict[str, tuple[Pattern[str], _TransitionMethod[_Context], str]]]: ... + def no_match( + self, context: _Context, transitions: tuple[list[str], dict[str, tuple[Pattern[str], _TransitionMethod[_Context], str]]] + ) -> _TransitionResult[_Context]: ... + def bof(self, context: _Context) -> tuple[list[str], list[str]]: ... + def eof(self, context: _Context) -> list[str]: ... + def nop(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + +class StateMachineWS(StateMachine[_Context]): + def get_indented(self, until_blank: bool = False, strip_indent: bool = True) -> tuple[StringList, int, int, bool]: ... + def get_known_indented( + self, indent: int, until_blank: bool = False, strip_indent: bool = True + ) -> tuple[list[str], int, bool]: ... + def get_first_known_indented( + self, indent: int, until_blank: bool = False, strip_indent: bool = True, strip_top: bool = True + ) -> tuple[list[str], int, int, bool]: ... + +class StateWS(State[_Context]): + indent_sm: type[StateMachine[_Context]] | None + indent_sm_kwargs: dict[str, Any] | None + known_indent_sm: type[StateMachine[_Context]] | None + known_indent_sm_kwargs: dict[str, Any] | None + ws_patterns: dict[str, Pattern[str]] + ws_initial_transitions: Sequence[str] + def __init__(self, state_machine: StateMachine[_Context], debug: bool = False) -> None: ... + def add_initial_transitions(self) -> None: ... + def blank(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + def indent(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + def known_indent(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + def first_known_indent(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + +class _SearchOverride: + def match(self, pattern: Pattern[str]) -> Match[str]: ... + +class SearchStateMachine(_SearchOverride, StateMachine[_Context]): ... +class SearchStateMachineWS(_SearchOverride, StateMachineWS[_Context]): ... + +class ViewList(Generic[_T]): + data: list[_T] + items: list[tuple[str, int]] + parent: Self + parent_offset: int + def __init__( + self, + initlist: Self | Sequence[_T] | None = None, + source: str | None = None, + items: list[tuple[str, int]] | None = None, + parent: Self | None = None, + parent_offset: int | None = None, + ) -> None: ... + def __lt__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... + def __contains__(self, item: _T) -> bool: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, i: slice) -> Self: ... + @overload + def __getitem__(self, i: SupportsIndex) -> _T: ... + + @overload + def __setitem__(self, i: slice, item: Self) -> None: ... + @overload + def __setitem__(self, i: SupportsIndex, item: _T) -> None: ... + + def __delitem__(self, i: SupportsIndex) -> None: ... + def __add__(self, other: Self) -> Self: ... + def __radd__(self, other: Self) -> Self: ... + def __iadd__(self, other: Self) -> Self: ... + def __mul__(self, n: int) -> Self: ... + __rmul__ = __mul__ + def __imul__(self, n: int) -> Self: ... + def extend(self, other: Self) -> None: ... + def append(self, item: _T, source: str | None = None, offset: int = 0) -> None: ... + def insert(self, i: int, item: _T, source: str | None = None, offset: int = 0) -> None: ... + def pop(self, i: int = -1) -> _T: ... + def trim_start(self, n: int = 1) -> None: ... + def trim_end(self, n: int = 1) -> None: ... + def remove(self, item: _T) -> None: ... + def count(self, item: _T) -> int: ... + def index(self, item: _T) -> int: ... + def reverse(self) -> None: ... + def sort(self, *args: tuple[_T, tuple[str, int]]) -> None: ... + def info(self, i: int) -> tuple[str, int | None]: ... + def source(self, i: int) -> str: ... + def offset(self, i: int) -> int: ... + def disconnect(self) -> None: ... + def xitems(self) -> Generator[tuple[str, int, str]]: ... + def pprint(self) -> None: ... + + # dummy atribute to indicate to mypy that ViewList is Iterable[str] + def __iter__(self) -> Iterator[str]: ... + +class StringList(ViewList[str]): + def trim_left(self, length: int, start: int = 0, end: int = sys.maxsize) -> None: ... + def get_text_block(self, start: int, flush_left: bool = False) -> StringList: ... + def get_indented( + self, + start: int = 0, + until_blank: bool = False, + strip_indent: bool = True, + block_indent: int | None = None, + first_indent: int | None = None, + ) -> tuple[StringList, int, bool]: ... + def get_2D_block(self, top: int, left: int, bottom: int, right: int, strip_indent: bool = True) -> StringList: ... + def pad_double_width(self, pad_char: str) -> None: ... + def replace(self, old: str, new: str) -> None: ... + +class StateMachineError(Exception): ... +class UnknownStateError(StateMachineError): ... +class DuplicateStateError(StateMachineError): ... +class UnknownTransitionError(StateMachineError): ... +class DuplicateTransitionError(StateMachineError): ... +class TransitionPatternNotFound(StateMachineError): ... +class TransitionMethodNotFound(StateMachineError): ... +class UnexpectedIndentationError(StateMachineError): ... +class TransitionCorrection(Exception): ... +class StateCorrection(Exception): ... + +def string2lines( + astring: str, tab_width: int = 8, convert_whitespace: bool = False, whitespace: Pattern[str] = ... +) -> list[str]: ... diff --git a/stubs/docutils/docutils/transforms/__init__.pyi b/stubs/docutils/docutils/transforms/__init__.pyi index 964e6fa3f426..a848d0768f9f 100644 --- a/stubs/docutils/docutils/transforms/__init__.pyi +++ b/stubs/docutils/docutils/transforms/__init__.pyi @@ -1,3 +1,35 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import Any, ClassVar, Final, TypeAlias -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import ApplicationError, TransformSpec, nodes +from docutils.languages import LanguageImporter + +_TransformTuple: TypeAlias = tuple[str, type[Transform], nodes.Node | None, dict[str, Any]] + +__docformat__: Final = "reStructuredText" + +class TransformError(ApplicationError): ... + +class Transform: + default_priority: ClassVar[int | None] + document: nodes.document + startnode: nodes.Node | None + language: LanguageImporter + def __init__(self, document: nodes.document, startnode: nodes.Node | None = None) -> None: ... + def __getattr__(self, name: str, /) -> Incomplete: ... # method apply is not implemented + +class Transformer(TransformSpec): + transforms: list[_TransformTuple] + document: nodes.document + applied: list[_TransformTuple] + sorted: bool + components: Mapping[str, TransformSpec] + serialno: int + def __init__(self, document: nodes.document): ... + def add_transform(self, transform_class: type[Transform], priority: int | None = None, **kwargs) -> None: ... + def add_transforms(self, transform_list: Iterable[type[Transform]]) -> None: ... + def add_pending(self, pending: nodes.pending, priority: int | None = None) -> None: ... + def get_priority_string(self, priority: int) -> str: ... + def populate_from_components(self, components: Iterable[TransformSpec]) -> None: ... + def apply_transforms(self) -> None: ... diff --git a/stubs/docutils/docutils/transforms/components.pyi b/stubs/docutils/docutils/transforms/components.pyi new file mode 100644 index 000000000000..1c079281007a --- /dev/null +++ b/stubs/docutils/docutils/transforms/components.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Filter(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... diff --git a/stubs/docutils/docutils/transforms/frontmatter.pyi b/stubs/docutils/docutils/transforms/frontmatter.pyi new file mode 100644 index 000000000000..bb0a86afb869 --- /dev/null +++ b/stubs/docutils/docutils/transforms/frontmatter.pyi @@ -0,0 +1,34 @@ +import re +from typing import ClassVar, Final + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class TitlePromoter(Transform): + def promote_title(self, node: nodes.Element) -> bool: ... + def promote_subtitle(self, node: nodes.Element) -> bool: ... + def candidate_index(self, node: nodes.Element) -> tuple[nodes.Node, int] | tuple[None, None]: ... + +class DocTitle(TitlePromoter): + default_priority: ClassVar[int] + def set_metadata(self) -> None: ... + def apply(self) -> None: ... + +class SectionSubTitle(TitlePromoter): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class DocInfo(Transform): + default_priority: ClassVar[int] + biblio_nodes: ClassVar[dict[str, type[nodes.Element]]] + rcs_keyword_substitutions: ClassVar[list[tuple[re.Pattern[str], str]]] + def apply(self) -> None: ... + def extract_bibliographic(self, field_list): ... + def check_empty_biblio_field(self, field, name) -> bool: ... + def check_compound_biblio_field(self, field, name) -> bool: ... + def extract_authors(self, field, name, docinfo) -> None: ... + def authors_from_one_paragraph(self, field) -> list[list[nodes.Text]]: ... + def authors_from_bullet_list(self, field): ... + def authors_from_paragraphs(self, field): ... diff --git a/stubs/docutils/docutils/transforms/misc.pyi b/stubs/docutils/docutils/transforms/misc.pyi new file mode 100644 index 000000000000..5fddcda15047 --- /dev/null +++ b/stubs/docutils/docutils/transforms/misc.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar, Final + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class CallBack(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class ClassAttribute(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class Transitions(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def warn(self, msg: str, node: nodes.Node) -> None: ... diff --git a/stubs/docutils/docutils/transforms/parts.pyi b/stubs/docutils/docutils/transforms/parts.pyi new file mode 100644 index 000000000000..39aa9e2aa8df --- /dev/null +++ b/stubs/docutils/docutils/transforms/parts.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterable, Sequence +from typing import ClassVar, Final +from typing_extensions import Never + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class SectNum(Transform): + default_priority: ClassVar[int] + maxdepth: int + startvalue: int + prefix: str + suffix: str + def apply(self) -> None: ... + def update_section_numbers(self, node: nodes.Element, prefix: Iterable[str] = (), depth: int = 0) -> None: ... + +class Contents(Transform): + default_priority: ClassVar[int] + toc_id: Incomplete + backlinks: Incomplete + def apply(self) -> None: ... + def build_contents( + self, node: nodes.Element, level: int = 0 + ) -> nodes.bullet_list | list[None]: ... # return empty list if entries is empty + def copy_and_filter(self, node: nodes.Node) -> Sequence[nodes.Node]: ... + +class ContentsFilter(nodes.TreeCopyVisitor): + def get_entry_text(self) -> Sequence[nodes.Node]: ... + def ignore_node_but_process_children(self, node: Unused) -> Never: ... + visit_problematic = ignore_node_but_process_children + visit_reference = ignore_node_but_process_children + visit_target = ignore_node_but_process_children diff --git a/stubs/docutils/docutils/transforms/peps.pyi b/stubs/docutils/docutils/transforms/peps.pyi new file mode 100644 index 000000000000..6b309245d35c --- /dev/null +++ b/stubs/docutils/docutils/transforms/peps.pyi @@ -0,0 +1,43 @@ +import re +from typing import ClassVar, Final + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Headers(Transform): + default_priority: ClassVar[int] + pep_url: ClassVar[str] + pep_cvs_url: ClassVar[str] + rcs_keyword_substitutions: ClassVar[tuple[tuple[re.Pattern[str], str], ...]] + def apply(self) -> None: ... + +class Contents(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class TargetNotes(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def cleanup_callback(self, pending: nodes.pending) -> None: ... + +class PEPZero(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class PEPZeroSpecial(nodes.SparseNodeVisitor): + pep_url: ClassVar[str] + def unknown_visit(self, node: nodes.Node) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + pep_table: bool + entry: int + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + +non_masked_addresses: tuple[str, ...] + +def mask_email(ref: nodes.reference, pepno: int | None = None) -> nodes.Node: ... diff --git a/stubs/docutils/docutils/transforms/references.pyi b/stubs/docutils/docutils/transforms/references.pyi new file mode 100644 index 000000000000..6bb14effc834 --- /dev/null +++ b/stubs/docutils/docutils/transforms/references.pyi @@ -0,0 +1,84 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, overload + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class SectionIDs(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class PropagateTargets(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class AnonymousHyperlinks(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class IndirectHyperlinks(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def resolve_indirect_target(self, target: nodes.Element) -> None: ... + def nonexistent_indirect_target(self, target: nodes.Element) -> None: ... + def circular_indirect_reference(self, target: nodes.Element) -> None: ... + def indirect_target_error(self, target: nodes.Element, explanation) -> None: ... + def resolve_indirect_references(self, target: nodes.Element) -> None: ... + +class ExternalTargets(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class InternalTargets(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def resolve_reference_ids(self, target: nodes.Element) -> None: ... + +class Footnotes(Transform): + default_priority: ClassVar[int] + autofootnote_labels: list[str] | None + symbols: ClassVar[list[str]] + def apply(self) -> None: ... + def number_footnotes(self, startnum: int) -> int: ... + def number_footnote_references(self, startnum: int) -> None: ... + def symbolize_footnotes(self) -> None: ... + def resolve_footnotes_and_citations(self) -> None: ... + + @overload + def resolve_references(self, note: nodes.footnote, reflist: Iterable[nodes.footnote_reference]) -> None: ... + @overload + def resolve_references(self, note: nodes.citation, reflist: Iterable[nodes.citation_reference]) -> None: ... + @overload + def resolve_references(self, note: nodes.title, reflist: Iterable[nodes.title_reference]) -> None: ... + +class CircularSubstitutionDefinitionError(Exception): ... + +class Substitutions(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class TargetNotes(Transform): + default_priority: ClassVar[int] + classes: Incomplete + def __init__(self, document: nodes.document, startnode: nodes.Node) -> None: ... + def apply(self) -> None: ... + def make_target_footnote(self, refuri: str, refs: list[Incomplete], notes: dict[Incomplete, Incomplete]): ... + +class CitationReferences(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class DanglingReferences(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class DanglingReferencesVisitor(nodes.SparseNodeVisitor): + document: nodes.document + def __init__(self, document: nodes.document, unknown_reference_resolvers) -> None: ... + def unknown_visit(self, node: nodes.Node) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... diff --git a/stubs/docutils/docutils/transforms/universal.pyi b/stubs/docutils/docutils/transforms/universal.pyi new file mode 100644 index 000000000000..5d54735bbca8 --- /dev/null +++ b/stubs/docutils/docutils/transforms/universal.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import ClassVar, Final, Literal + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Decorations(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def generate_header(self) -> None: ... + def generate_footer(self) -> list[nodes.paragraph] | None: ... + +class ExposeInternals(Transform): + default_priority: ClassVar[int] + def not_Text(self, node: object) -> bool: ... # node passing to isinstance() method + def apply(self) -> None: ... + +class Messages(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class FilterMessages(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class TestMessages(Transform): + __test__: bool + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class StripComments(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class StripClassesAndElements(Transform): + default_priority: ClassVar[int] + strip_elements: set[Incomplete] + def apply(self) -> None: ... + def check_classes(self, node: object) -> bool: ... + +class SmartQuotes(Transform): + default_priority: ClassVar[int] + nodes_to_skip: ClassVar[tuple[type[nodes.Node | nodes.Special], ...]] + literal_nodes: ClassVar[tuple[type[nodes.Node | nodes.Body], ...]] + smartquotes_action: ClassVar[str] + unsupported_languages: set[str] + def __init__(self, document: nodes.document, startnode: nodes.Node | None) -> None: ... + def get_tokens(self, txtnodes: Iterable[nodes.Node]) -> Generator[tuple[Literal["literal", "plain"], str]]: ... + def apply(self) -> None: ... + +class Validate(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... diff --git a/stubs/docutils/docutils/transforms/writer_aux.pyi b/stubs/docutils/docutils/transforms/writer_aux.pyi new file mode 100644 index 000000000000..38523f07319e --- /dev/null +++ b/stubs/docutils/docutils/transforms/writer_aux.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Admonitions(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... diff --git a/stubs/docutils/docutils/utils/__init__.pyi b/stubs/docutils/docutils/utils/__init__.pyi index 189352a6770c..f076c0f2e8d8 100644 --- a/stubs/docutils/docutils/utils/__init__.pyi +++ b/stubs/docutils/docutils/utils/__init__.pyi @@ -1,16 +1,131 @@ -from collections.abc import Iterable -from typing import Any +import optparse +from _typeshed import StrPath, SupportsWrite +from collections.abc import Callable, Iterable, Mapping, Sequence +from re import Pattern +from typing import Any, Final, Literal, TypeAlias, TypeVar +from typing_extensions import deprecated -from docutils.io import FileOutput +from docutils import ApplicationError, DataError, nodes +from docutils.frontend import Values +from docutils.io import ErrorOutput, FileOutput +from docutils.nodes import document, unescape as unescape -_list = list +_T = TypeVar("_T") +_Observer: TypeAlias = Callable[[nodes.system_message], object] +_SystemMessageLevel: TypeAlias = Literal[0, 1, 2, 3, 4] + +__docformat__: Final = "reStructuredText" class DependencyList: - list: _list[str] + list: list[str] file: FileOutput | None - def __init__(self, output_file: str | None = ..., dependencies: Iterable[str] = ...) -> None: ... + def __init__(self, output_file: str | None = None, dependencies: Iterable[str] = ()) -> None: ... def set_output(self, output_file: str | None) -> None: ... - def add(self, *filenames: str) -> None: ... + def add(self, *paths: str) -> None: ... def close(self) -> None: ... -def __getattr__(name: str) -> Any: ... # incomplete +class SystemMessagePropagation(ApplicationError): ... + +class Reporter: + get_source_and_line: Callable[[int | None], tuple[StrPath | None, int | None]] + levels: Final[Sequence[str]] + + DEBUG_LEVEL: Final = 0 + INFO_LEVEL: Final = 1 + WARNING_LEVEL: Final = 2 + ERROR_LEVEL: Final = 3 + SEVERE_LEVEL: Final = 4 + + stream: ErrorOutput + encoding: str + observers: list[_Observer] + max_level: int + def __init__( + self, + source: str, + report_level: int, + halt_level: int, + stream: SupportsWrite[str] | SupportsWrite[bytes] | str | bool | None = None, + debug: bool = False, + encoding: str | None = None, + error_handler: str = "backslashreplace", + ) -> None: ... + + source: str + error_handler: str + debug_flag: bool + report_level: _SystemMessageLevel + halt_level: int + def attach_observer(self, observer: _Observer) -> None: ... + def detach_observer(self, observer: _Observer) -> None: ... + def notify_observers(self, message: nodes.system_message) -> None: ... + def system_message( + self, + level: int, + message: str | Exception, + *children: nodes.Node, + base_node: nodes.Node = ..., + source: str = ..., + **kwargs, + ) -> nodes.system_message: ... + def debug( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def info( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def warning( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def error( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def severe( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + +class SystemMessage(ApplicationError): + level: _SystemMessageLevel + def __init__(self, system_message: object, level: _SystemMessageLevel): ... + +def new_reporter(source_path: str, settings: optparse.Values) -> Reporter: ... +def new_document(source_path: str, settings: optparse.Values | None = None) -> document: ... + +class ExtensionOptionError(DataError): ... +class BadOptionError(ExtensionOptionError): ... +class BadOptionDataError(ExtensionOptionError): ... +class DuplicateOptionError(ExtensionOptionError): ... + +def extract_extension_options( + field_list: nodes.field_list, options_spec: Mapping[str, Callable[[str], Any]] +) -> dict[str, Any]: ... +def extract_options(field_list: nodes.field_list) -> list[tuple[str, str]]: ... +def assemble_option_dict( + option_list: Iterable[tuple[str, str]], options_spec: Mapping[str, Callable[[str], Any]] +) -> dict[str, Any]: ... + +class NameValueError(DataError): ... + +@deprecated("Deprecated and will be removed in Docutils 1.0.") +def decode_path(path: str) -> str: ... +def extract_name_value(line: str) -> list[tuple[str, str]]: ... +def clean_rcs_keywords(paragraph: nodes.paragraph, keyword_substitutions: Iterable[tuple[Pattern[str], str]]) -> None: ... +def relative_path(source: StrPath | None, target: StrPath) -> str: ... +@deprecated("Deprecated and will be removed in Docutils 1.0. Use `get_stylesheet_list()` instead.") +def get_stylesheet_reference(settings: Values, relative_to: StrPath | None = None) -> str: ... +def get_stylesheet_list(settings: Values) -> list[str]: ... +def find_file_in_dirs(path: StrPath, dirs: Iterable[StrPath]) -> str: ... +def get_trim_footnote_ref_space(settings: Values) -> bool: ... +def get_source_line(node: nodes.Node) -> tuple[str, int]: ... +def escape2null(text: str) -> str: ... +def split_escaped_whitespace(text: str) -> list[str]: ... +def strip_combining_chars(text: str) -> str: ... +def find_combining_chars(text: str) -> list[int]: ... +def column_indices(text: str) -> list[int]: ... + +east_asian_widths: dict[str, int] + +def column_width(text: str) -> int: ... +def uniq(L: list[_T]) -> list[_T]: ... +def normalize_language_tag(tag: str) -> list[str]: ... +def xml_declaration(encoding: str | None = None) -> str: ... diff --git a/stubs/docutils/docutils/utils/_roman_numerals.pyi b/stubs/docutils/docutils/utils/_roman_numerals.pyi new file mode 100644 index 000000000000..0d7b27baff83 --- /dev/null +++ b/stubs/docutils/docutils/utils/_roman_numerals.pyi @@ -0,0 +1,30 @@ +from typing import Final, final +from typing_extensions import Self + +__all__ = ("MAX", "MIN", "InvalidRomanNumeralError", "OutOfRangeError", "RomanNumeral") + +MIN: Final = 1 +MAX: Final = 4_999 + +@final +class OutOfRangeError(TypeError): ... + +@final +class InvalidRomanNumeralError(ValueError): + def __init__(self, value: str, *args: object) -> None: ... + +@final +class RomanNumeral: + __slots__ = ("_value",) + def __init__(self, value: int, /) -> None: ... + def __int__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __setattr__(self, key: str, value: object) -> None: ... + def to_uppercase(self) -> str: ... + def to_lowercase(self) -> str: ... + @classmethod + def from_string(cls, string: str, /) -> Self: ... + +_ROMAN_NUMERAL_PREFIXES: Final[list[tuple[int, str, str]]] diff --git a/stubs/docutils/docutils/utils/code_analyzer.pyi b/stubs/docutils/docutils/utils/code_analyzer.pyi new file mode 100644 index 000000000000..e778c7db6afd --- /dev/null +++ b/stubs/docutils/docutils/utils/code_analyzer.pyi @@ -0,0 +1,28 @@ +from collections.abc import Generator, Iterable +from typing import Final, Literal, TypeAlias + +from docutils import ApplicationError + +_TokenNames: TypeAlias = Literal["long", "short", "none"] + +__docformat__: Final = "reStructuredText" +with_pygments: bool +unstyled_tokens: list[str] + +class LexerError(ApplicationError): ... + +class Lexer: + code: str + language: str + tokennames: _TokenNames + lexer: Lexer | None + def __init__(self, code: str, language: str, tokennames: _TokenNames = "short") -> None: ... + def merge(self, tokens: Iterable[tuple[_TokenNames, str]]) -> Generator[tuple[_TokenNames, str]]: ... + def __iter__(self) -> Generator[tuple[list[str], str]]: ... + +class NumberLines: + tokens: Iterable[tuple[list[str], str]] + startline: int + fmt_str: str + def __init__(self, tokens: Iterable[tuple[list[str], str]], startline: int, endline: int) -> None: ... + def __iter__(self) -> Generator[tuple[list[str], str]]: ... diff --git a/stubs/docutils/docutils/utils/math/__init__.pyi b/stubs/docutils/docutils/utils/math/__init__.pyi new file mode 100644 index 000000000000..cfe920e0bbc7 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/__init__.pyi @@ -0,0 +1,13 @@ +from typing import Final, Literal + +from docutils.nodes import Node + +__docformat__: Final = "reStructuredText" + +class MathError(ValueError): + details: list[Node] + def __init__(self, msg: object, details: list[Node] = []) -> None: ... + +def toplevel_code(code: str) -> str: ... +def pick_math_environment(code: str, numbered: bool = False) -> Literal["align*", "equation*", "align", "equation"]: ... +def wrap_math_code(code: str, as_block: bool | None) -> str: ... diff --git a/stubs/docutils/docutils/utils/math/latex2mathml.pyi b/stubs/docutils/docutils/utils/math/latex2mathml.pyi new file mode 100644 index 000000000000..8adda7596f3a --- /dev/null +++ b/stubs/docutils/docutils/utils/math/latex2mathml.pyi @@ -0,0 +1,44 @@ +from collections.abc import Iterable + +from docutils.utils.math.mathml_elements import MathElement, mover, msub, msubsup, msup, mtd, munder, munderover + +letters: dict[str, str] +ordinary: dict[str, str] +greek_capitals: dict[str, str] +functions: dict[str, str | None] +modulo_functions: dict[str, tuple[bool, bool, bool, str]] +math_alphabets: dict[str, str] +stretchables: dict[str, str] +operators: dict[str, str] +thick_operators: dict[str, str] +small_operators: dict[str, str] +movablelimits: tuple[str, ...] +spaces: dict[str, str] +accents: dict[str, str] +over: dict[str, tuple[str, float]] +under: dict[str, tuple[str, float]] +anomalous_chars: dict[str, str] +mathbb: dict[str, str] +matrices: dict[str, tuple[str, str]] +layout_styles: dict[str, dict[str, bool | int]] +fractions: dict[str, dict[str, bool | int | str] | dict[str, bool | int] | dict[str, int]] +delimiter_sizes: list[str] +bigdelimiters: dict[str, int] + +def tex_cmdname(string: str) -> tuple[str, str]: ... +def tex_number(string: str) -> tuple[str, str]: ... +def tex_token(string: str) -> tuple[str, str]: ... +def tex_group(string: str) -> tuple[str, str]: ... +def tex_token_or_group(string: str) -> tuple[str, str]: ... +def tex_optarg(string: str) -> tuple[str, str]: ... +def parse_latex_math(root: MathElement, source: str) -> MathElement: ... +def handle_cmd(name: str, node: MathElement, string: str) -> tuple[MathElement, str]: ... +def handle_math_alphabet(name: str, node: MathElement, string: str) -> tuple[MathElement, str]: ... +def handle_script_or_limit( + node: MathElement, c: str, limits: str = "" +) -> munderover | msubsup | munder | msub | mover | msup: ... +def begin_environment(node: MathElement, string: str) -> tuple[mtd, str]: ... +def end_environment(node: MathElement, string: str) -> tuple[MathElement, str]: ... +def tex_equation_columns(rows: Iterable[str]) -> int: ... +def align_attributes(rows: Iterable[str]) -> dict[str, str | bool]: ... +def tex2mathml(tex_math: str, as_block: bool = False) -> str: ... diff --git a/stubs/docutils/docutils/utils/math/math2html.pyi b/stubs/docutils/docutils/utils/math/math2html.pyi new file mode 100644 index 000000000000..0972842a9ad0 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/math2html.pyi @@ -0,0 +1,638 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import ClassVar, Final, TextIO, TypeVar + +_T = TypeVar("_T") + +__docformat__: Final = "reStructuredText" +__version__: Final[str] + +class Trace: + debugmode: ClassVar[bool] + quietmode: ClassVar[bool] + showlinesmode: ClassVar[bool] + prefix: ClassVar[str | None] + @classmethod + def debug(cls, message: str) -> None: ... + @classmethod + def message(cls, message: str) -> None: ... + @classmethod + def error(cls, message: str) -> None: ... + @classmethod + def show(cls, message: str, channel: TextIO) -> None: ... + +class ContainerConfig: + extracttext: ClassVar[dict[str, list[str]]] + +class EscapeConfig: + chars: ClassVar[dict[str, str]] + entities: ClassVar[dict[str, str]] + +class FormulaConfig: + alphacommands: ClassVar[dict[str, str]] + array: ClassVar[dict[str, str]] + bigbrackets: ClassVar[dict[str, list[str]]] + bracketcommands: ClassVar[dict[str, str]] + combiningfunctions: ClassVar[dict[str, str]] + commands: ClassVar[dict[str, str]] + cmddict: ClassVar[dict[str, str]] + oversetfunctions: ClassVar[dict[str, str]] + undersetfunctions: ClassVar[dict[str, str]] + endings: ClassVar[dict[str, str]] + environments: ClassVar[dict[str, list[str]]] + fontfunctions: ClassVar[dict[str, str]] + hybridfunctions: ClassVar[dict[str, list[str]]] + hybridsizes: ClassVar[dict[str, str]] + labelfunctions: ClassVar[dict[str, str]] + limitcommands: ClassVar[dict[str, str]] + modified: ClassVar[dict[str, str]] + onefunctions: ClassVar[dict[str, str]] + spacedcommands: ClassVar[dict[str, str]] + starts: ClassVar[dict[str, str]] + symbolfunctions: ClassVar[dict[str, str]] + textfunctions: ClassVar[dict[str, str]] + unmodified: ClassVar[dict[str, list[str]]] + key: str + value: str + +class CommandLineParser: + options: Incomplete + def __init__(self, options) -> None: ... + def parseoptions(self, args): ... + def readoption(self, args): ... + def readquoted(self, args, initial): ... + def readequalskey(self, arg, args): ... + +class Options: + location: Incomplete + debug: bool + quiet: bool + version: bool + help: bool + simplemath: bool + showlines: bool + branches: Incomplete + def parseoptions(self, args) -> None: ... + def processoptions(self) -> None: ... + def usage(self) -> None: ... + def showoptions(self) -> None: ... + def showversion(self) -> None: ... + +class Cloner: + @classmethod + def clone(cls, original: _T) -> _T: ... + @classmethod + def create(cls, type: type[_T]) -> _T: ... + +class ContainerExtractor: + allowed: Incomplete + extracted: Incomplete + def __init__(self, config) -> None: ... + def extract(self, container): ... + def process(self, container, lst) -> None: ... + def safeclone(self, container): ... + +class Parser: + begin: int + parameters: Incomplete + def __init__(self) -> None: ... + def parseheader(self, reader): ... + def parseparameter(self, reader) -> None: ... + def parseending(self, reader, process) -> None: ... + def parsecontainer(self, reader, contents) -> None: ... + +class LoneCommand(Parser): + def parse(self, reader): ... + +class TextParser(Parser): + stack: Incomplete + ending: Incomplete + endings: Incomplete + def __init__(self, container) -> None: ... + def parse(self, reader): ... + def isending(self, reader): ... + +class ExcludingParser(Parser): + def parse(self, reader): ... + +class BoundedParser(ExcludingParser): + def parse(self, reader): ... + +class BoundedDummy(Parser): + def parse(self, reader): ... + +class StringParser(Parser): + begin: Incomplete + def parseheader(self, reader): ... + def parse(self, reader): ... + +class ContainerOutput: + def gethtml(self, container) -> None: ... + def isempty(self): ... + +class EmptyOutput(ContainerOutput): + def gethtml(self, container): ... + def isempty(self): ... + +class FixedOutput(ContainerOutput): + def gethtml(self, container): ... + +class ContentsOutput(ContainerOutput): + def gethtml(self, container): ... + +class TaggedOutput(ContentsOutput): + tag: Incomplete + breaklines: bool + empty: bool + def settag(self, tag, breaklines: bool = False, empty: bool = False): ... + def setbreaklines(self, breaklines): ... + def gethtml(self, container): ... + def open(self, container): ... + def close(self, container): ... + def selfclosing(self, container): ... + def checktag(self, container): ... + +class FilteredOutput(ContentsOutput): + filters: Incomplete + def __init__(self) -> None: ... + def addfilter(self, original, replacement) -> None: ... + def gethtml(self, container): ... + def filter(self, line): ... + +class StringOutput(ContainerOutput): + def gethtml(self, container): ... + +class Globable: + leavepending: bool + endinglist: Incomplete + def __init__(self) -> None: ... + def checkbytemark(self) -> None: ... + def isout(self): ... + def current(self): ... + def checkfor(self, string): ... + def finished(self): ... + def skipcurrent(self): ... + def glob(self, currentcheck): ... + def globalpha(self): ... + def globnumber(self): ... + def isidentifier(self): ... + def globidentifier(self): ... + def isvalue(self): ... + def globvalue(self): ... + def skipspace(self): ... + def globincluding(self, magicchar): ... + def globexcluding(self, excluded): ... + def pushending(self, ending, optional: bool = False) -> None: ... + def popending(self, expected=None): ... + def nextending(self): ... + +class EndingList: + endings: Incomplete + def __init__(self) -> None: ... + def add(self, ending, optional: bool = False) -> None: ... + def pickpending(self, pos) -> None: ... + def checkin(self, pos): ... + def pop(self, pos): ... + def findending(self, pos): ... + def checkpending(self) -> None: ... + +class PositionEnding: + ending: Incomplete + optional: Incomplete + def __init__(self, ending, optional) -> None: ... + def checkin(self, pos): ... + +class Position(Globable): + def __init__(self) -> None: ... + def skip(self, string) -> None: ... + def identifier(self): ... + def extract(self, length) -> None: ... + def checkfor(self, string): ... + def checkforlower(self, string): ... + def skipcurrent(self): ... + def __next__(self): ... + def checkskip(self, string): ... + def error(self, message) -> None: ... + +class TextPosition(Position): + pos: int + text: Incomplete + def __init__(self, text) -> None: ... + def skip(self, string) -> None: ... + def identifier(self): ... + def isout(self): ... + def current(self): ... + def extract(self, length): ... + +class Container: + partkey: Incomplete + parent: Incomplete + begin: Incomplete + contents: Incomplete + def __init__(self) -> None: ... + def process(self) -> None: ... + def gethtml(self): ... + def escape(self, line, replacements={"&": "&", "<": "<", ">": ">"}): ... + def escapeentities(self, line): ... + def searchall(self, type): ... + def searchremove(self, type): ... + def searchprocess(self, type, process): ... + def locateprocess(self, locate, process) -> None: ... + def recursivesearch(self, locate, recursive, process) -> None: ... + def extracttext(self): ... + def group(self, index, group, isingroup) -> None: ... + def remove(self, index) -> None: ... + def tree(self, level: int = 0) -> None: ... + def getparameter(self, name): ... + def getparameterlist(self, name): ... + def hasemptyoutput(self): ... + +class BlackBox(Container): + parser: Incomplete + output: Incomplete + contents: Incomplete + def __init__(self) -> None: ... + +class StringContainer(Container): + parsed: Incomplete + parser: Incomplete + output: Incomplete + string: str + def __init__(self) -> None: ... + def process(self) -> None: ... + def replacespecial(self, line): ... + def changeline(self, line): ... + def extracttext(self): ... + +class Constant(StringContainer): + contents: Incomplete + string: Incomplete + output: Incomplete + def __init__(self, text) -> None: ... + +class DocumentParameters: + displaymode: bool + +class FormulaParser(Parser): + begin: Incomplete + def parseheader(self, reader): ... + def parsetype(self, reader): ... + def parse(self, reader): ... + def parseformula(self, reader): ... + def parsesingleliner(self, reader, start, ending): ... + def parsemultiliner(self, reader, start, ending): ... + +class FormulaBit(Container): + type: str | None + size: int + original: str + contents: Incomplete + output: Incomplete + def __init__(self) -> None: ... + factory: Incomplete + def setfactory(self, factory): ... + def add(self, bit) -> None: ... + def skiporiginal(self, string, pos) -> None: ... + def computesize(self): ... + def clone(self): ... + +class TaggedBit(FormulaBit): + output: Incomplete + def constant(self, constant, tag): ... + contents: Incomplete + def complete(self, contents, tag, breaklines: bool = False): ... + def selfcomplete(self, tag): ... + +class FormulaConstant(Constant): + original: Incomplete + size: int + type: str | None + def __init__(self, string) -> None: ... + def computesize(self): ... + def clone(self): ... + +class RawText(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class FormulaSymbol(FormulaBit): + modified: Incomplete + unmodified: Incomplete + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + def addsymbol(self, symbol, pos) -> None: ... + +class FormulaNumber(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos): ... + +class Comment(FormulaBit): + start: Incomplete + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class WhiteSpace(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class Bracket(FormulaBit): + start: Incomplete + ending: Incomplete + inner: Incomplete + def __init__(self) -> None: ... + def detect(self, pos): ... + def parsebit(self, pos): ... + def parsetext(self, pos): ... + def parseliteral(self, pos): ... + def parsecomplete(self, pos, innerparser) -> None: ... + def innerformula(self, pos) -> None: ... + def innertext(self, pos) -> None: ... + literal: str + def innerliteral(self, pos) -> None: ... + +class SquareBracket(Bracket): + start: Incomplete + ending: Incomplete + def clone(self): ... + +class MathsProcessor: + def process(self, contents, index) -> None: ... + +class FormulaProcessor: + processors: Incomplete + def process(self, bit) -> None: ... + def processcontents(self, bit) -> None: ... + def processinsides(self, bit) -> None: ... + def traversewhole(self, formula) -> None: ... + def traverse(self, bit) -> Generator[Incomplete, Incomplete]: ... + def italicize(self, bit, contents) -> None: ... + +class Formula(Container): + parser: Incomplete + output: Incomplete + def __init__(self) -> None: ... + def process(self) -> None: ... + contents: Incomplete + def classic(self) -> None: ... + def parse(self, pos): ... + header: Incomplete + def parsedollarinline(self, pos) -> None: ... + def parsedollarblock(self, pos) -> None: ... + parsed: Incomplete + def parsedollar(self, pos) -> None: ... + def parseinlineto(self, pos, limit) -> None: ... + def parseblockto(self, pos, limit) -> None: ... + def parseupto(self, pos, limit): ... + +class WholeFormula(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class FormulaFactory: + types: Incomplete + skippedtypes: Incomplete + defining: bool + instances: Incomplete + def __init__(self) -> None: ... + def detecttype(self, type, pos): ... + def instance(self, type): ... + def create(self, type): ... + def clearskipped(self, pos) -> None: ... + def skipany(self, pos): ... + def parseany(self, pos): ... + def parsetype(self, type, pos): ... + def parseformula(self, formula): ... + +class FormulaCommand(FormulaBit): + types: Incomplete + start: Incomplete + commandmap: ClassVar[dict[str, str] | dict[str, list[str]] | None] + def detect(self, pos): ... + output: Incomplete + def parsebit(self, pos): ... + def parsewithcommand(self, command, pos): ... + def parsecommandtype(self, command, type, pos): ... + def extractcommand(self, pos): ... + def emptycommand(self, pos): ... + def parseupgreek(self, command, pos): ... + +class CommandBit(FormulaCommand): + command: Incomplete + translated: Incomplete + def setcommand(self, command) -> None: ... + def parseparameter(self, pos): ... + def parsesquare(self, pos): ... + def parseliteral(self, pos): ... + def parsesquareliteral(self, pos): ... + def parsetext(self, pos): ... + +class EmptyCommand(CommandBit): + commandmap: ClassVar[dict[str, str]] + contents: Incomplete + def parsebit(self, pos) -> None: ... + +class SpacedCommand(CommandBit): + commandmap: ClassVar[dict[str, str]] + contents: Incomplete + def parsebit(self, pos) -> None: ... + +class AlphaCommand(EmptyCommand): + commandmap: ClassVar[dict[str, str]] + greek_capitals: Incomplete + def parsebit(self, pos) -> None: ... + +class OneParamFunction(CommandBit): + commandmap: ClassVar[dict[str, str]] + simplified: bool + output: Incomplete + def parsebit(self, pos) -> None: ... + html: Incomplete + def simplifyifpossible(self) -> None: ... + +class SymbolFunction(CommandBit): + commandmap: ClassVar[dict[str, str]] + def detect(self, pos): ... + output: Incomplete + def parsebit(self, pos) -> None: ... + +class TextFunction(CommandBit): + commandmap: ClassVar[dict[str, str]] + output: Incomplete + def parsebit(self, pos) -> None: ... + def process(self) -> None: ... + +class FontFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + def process(self) -> None: ... + +class BigBracket: + size: Incomplete + original: Incomplete + alignment: Incomplete + pieces: Incomplete + def __init__(self, size, bracket, alignment: str = "l") -> None: ... + def getpiece(self, index): ... + def getpiece1(self, index): ... + def getpiece3(self, index): ... + def getpiece4(self, index): ... + def getcell(self, index): ... + def getcontents(self): ... + def getsinglebracket(self): ... + +class FormulaEquation(CommandBit): + piece: str + output: Incomplete + def parsebit(self, pos) -> None: ... + +class FormulaCell(FormulaCommand): + alignment: Incomplete + output: Incomplete + def setalignment(self, alignment): ... + def parsebit(self, pos) -> None: ... + +class FormulaRow(FormulaCommand): + cellseparator: Incomplete + alignments: Incomplete + output: Incomplete + def setalignments(self, alignments): ... + def parsebit(self, pos) -> None: ... + def createcell(self, index): ... + +class MultiRowFormula(CommandBit): + rows: Incomplete + size: Incomplete + def parserows(self, pos) -> None: ... + def iteraterows(self, pos) -> Generator[Incomplete]: ... + def addempty(self) -> None: ... + def addrow(self, row) -> None: ... + +class FormulaArray(MultiRowFormula): + piece: str + output: Incomplete + def parsebit(self, pos) -> None: ... + valign: str + alignments: Incomplete + def parsealignments(self, pos) -> None: ... + +class FormulaMatrix(MultiRowFormula): + piece: str + output: Incomplete + valign: str + alignments: Incomplete + def parsebit(self, pos) -> None: ... + +class FormulaCases(MultiRowFormula): + piece: str + output: Incomplete + alignments: Incomplete + contents: Incomplete + def parsebit(self, pos) -> None: ... + +class EquationEnvironment(MultiRowFormula): + output: Incomplete + alignments: Incomplete + def parsebit(self, pos) -> None: ... + +class BeginCommand(CommandBit): + commandmap: ClassVar[dict[str, str]] + types: Incomplete + size: Incomplete + def parsebit(self, pos) -> None: ... + def findbit(self, piece): ... + +class CombiningFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + def parsebit(self, pos) -> None: ... + def parsesingleparameter(self, pos): ... + +class OversetFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + symbol: Incomplete + parameter: Incomplete + output: Incomplete + def parsebit(self, pos) -> None: ... + +class UndersetFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + symbol: Incomplete + parameter: Incomplete + output: Incomplete + def parsebit(self, pos) -> None: ... + +class LimitCommand(EmptyCommand): + commandmap: ClassVar[dict[str, str]] + output: Incomplete + def parsebit(self, pos) -> None: ... + +class LimitPreviousCommand(LimitCommand): + commandmap: ClassVar[None] # type: ignore[assignment] + output: Incomplete + def parsebit(self, pos) -> None: ... + +class LimitsProcessor(MathsProcessor): + def process(self, contents, index) -> None: ... + def checklimits(self, contents, index): ... + def limitsahead(self, contents, index) -> None: ... + def modifylimits(self, contents, index) -> None: ... + def getlimit(self, contents, index): ... + def modifyscripts(self, contents, index) -> None: ... + def checkscript(self, contents, index): ... + def checkcommand(self, contents, index, type): ... + def getscript(self, contents, index): ... + +class BracketCommand(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + def parsebit(self, pos) -> None: ... + original: Incomplete + command: Incomplete + contents: Incomplete + def create(self, direction, character): ... + +class BracketProcessor(MathsProcessor): + def process(self, contents, index): ... + def processleft(self, contents, index) -> None: ... + def checkleft(self, contents, index): ... + def checkright(self, contents, index): ... + def checkdirection(self, bit, command): ... + def findright(self, contents, index): ... + def findmax(self, contents, leftindex, rightindex): ... + def resize(self, command, size) -> None: ... + +class ParameterDefinition: + parambrackets: ClassVar[list[tuple[str, str]]] + name: str + literal: bool + optional: bool + value: Incomplete + literalvalue: Incomplete + def __init__(self) -> None: ... + def parse(self, pos): ... + def read(self, pos, function) -> None: ... + +class ParameterFunction(CommandBit): + params: Incomplete + def readparams(self, readtemplate, pos) -> None: ... + def paramdefs(self, readtemplate) -> Generator[Incomplete]: ... + def getparam(self, name): ... + def getvalue(self, name): ... + def getliteralvalue(self, name): ... + +class HybridFunction(ParameterFunction): + commandmap: ClassVar[dict[str, list[str]]] + contents: Incomplete + def parsebit(self, pos) -> None: ... + def writeparams(self, writetemplate): ... + def writepos(self, pos): ... + def writeparam(self, pos): ... + def writefunction(self, pos): ... + def readtag(self, pos): ... + def writebracket(self, direction, character): ... + size: Incomplete + def computehybridsize(self) -> None: ... + +class HybridSize: + configsizes: ClassVar[dict[str, str]] + def getsize(self, function): ... + +def math2html(formula): ... +def main() -> None: ... diff --git a/stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi b/stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi new file mode 100644 index 000000000000..15aa3be4ed02 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi @@ -0,0 +1,13 @@ +from typing import Final + +mathbb: Final[dict[str, str]] +mathbf: Final[dict[str, str]] +mathbfit: Final[dict[str, str]] +mathcal: Final[dict[str, str]] +mathfrak: Final[dict[str, str]] +mathit: Final[dict[str, str]] +mathsf: Final[dict[str, str]] +mathsfbf: Final[dict[str, str]] +mathsfbfit: Final[dict[str, str]] +mathsfit: Final[dict[str, str]] +mathtt: Final[dict[str, str]] diff --git a/stubs/docutils/docutils/utils/math/mathml_elements.pyi b/stubs/docutils/docutils/utils/math/mathml_elements.pyi new file mode 100644 index 000000000000..d55220a93166 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/mathml_elements.pyi @@ -0,0 +1,85 @@ +import numbers +import xml.etree.ElementTree as ET +from collections.abc import Iterable +from typing import ClassVar, Final, SupportsIndex, overload +from typing_extensions import Self + +__docformat__: Final = "reStructuredText" +GLOBAL_ATTRIBUTES: Final[tuple[str, ...]] + +class MathElement(ET.Element): + nchildren: ClassVar[int | None] + parent: MathElement | None + def __init__(self, *children, **attributes: object) -> None: ... # attributes is passed to self.a_str method + @staticmethod + def a_str(v: object) -> str: ... + def set(self, key: str, value: object) -> None: ... # value is passed to self.a_str method + + @overload # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: MathElement) -> None: ... + @overload # type: ignore[override] + def __setitem__(self, key: slice, value: Iterable[MathElement]) -> None: ... + + def is_full(self) -> bool: ... + def close(self) -> MathElement | None: ... + def append(self, element: MathElement) -> Self: ... # type: ignore[override] + def extend(self, elements: Iterable[MathElement]) -> Self: ... # type: ignore[override] + def pop(self, index: int = -1): ... + def in_block(self) -> bool: ... + def indent_xml(self, space: str = " ", level: int = 0) -> None: ... + def unindent_xml(self) -> None: ... + def toxml(self, encoding: str | None = None) -> str: ... + +class MathRow(MathElement): ... + +class MathSchema(MathElement): + nchildren: ClassVar[int] + switch: bool + def __init__(self, *children, switch: bool = False, **kwargs) -> None: ... + +class MathToken(MathElement): + nchildren: ClassVar[int] + text: str + def __init__(self, text: str | numbers.Number, **attributes: object) -> None: ... + +class math(MathRow): ... +class mtext(MathToken): ... +class mi(MathToken): ... +class mn(MathToken): ... +class mo(MathToken): ... + +class mspace(MathElement): + nchildren: ClassVar[int] + +class mrow(MathRow): + def transfer_attributes(self, other) -> None: ... + +class mfrac(MathSchema): ... + +class msqrt(MathRow): + nchildren: ClassVar[int] + +class mroot(MathSchema): ... +class mstyle(MathRow): ... +class merror(MathRow): ... + +class menclose(MathRow): + nchildren: ClassVar[int] + +class mpadded(MathRow): ... + +class mphantom(MathRow): + nchildren: ClassVar[int] + +class msub(MathSchema): ... +class msup(MathSchema): ... + +class msubsup(MathSchema): + nchildren: ClassVar[int] + +class munder(msub): ... +class mover(msup): ... +class munderover(msubsup): ... +class mtable(MathElement): ... +class mtr(MathRow): ... +class mtd(MathRow): ... diff --git a/stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi b/stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi new file mode 100644 index 000000000000..c15fde2125f9 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi @@ -0,0 +1,9 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +document_template: Final[str] + +def blahtexml(math_code: str, as_block: bool = False) -> str: ... +def latexml(math_code: str, as_block: bool = False) -> str: ... +def pandoc(math_code: str, as_block: bool = False) -> str: ... +def ttm(math_code: str, as_block: bool = False) -> str: ... diff --git a/stubs/docutils/docutils/utils/math/tex2unichar.pyi b/stubs/docutils/docutils/utils/math/tex2unichar.pyi new file mode 100644 index 000000000000..3cbd0cfbcb54 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/tex2unichar.pyi @@ -0,0 +1,14 @@ +mathaccent: dict[str, str] +mathalpha: dict[str, str] +mathbin: dict[str, str] +mathclose: dict[str, str] +mathfence: dict[str, str] +mathop: dict[str, str] +mathopen: dict[str, str] +mathord: dict[str, str] +mathover: dict[str, str] +mathpunct: dict[str, str] +mathradical: dict[str, str] +mathrel: dict[str, str] +mathunder: dict[str, str] +space: dict[str, str] diff --git a/stubs/docutils/docutils/utils/math/unichar2tex.pyi b/stubs/docutils/docutils/utils/math/unichar2tex.pyi new file mode 100644 index 000000000000..3ef39b9d9bf0 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/unichar2tex.pyi @@ -0,0 +1 @@ +uni2tex_table: dict[int, str] diff --git a/stubs/docutils/docutils/utils/punctuation_chars.pyi b/stubs/docutils/docutils/utils/punctuation_chars.pyi new file mode 100644 index 000000000000..9d593c137519 --- /dev/null +++ b/stubs/docutils/docutils/utils/punctuation_chars.pyi @@ -0,0 +1,9 @@ +from typing import Final + +openers: Final[str] +closers: Final[str] +delimiters: Final[str] +closing_delimiters: Final[str] +quote_pairs: dict[str, str] + +def match_chars(c1: str, c2: str) -> bool: ... diff --git a/stubs/docutils/docutils/utils/smartquotes.pyi b/stubs/docutils/docutils/utils/smartquotes.pyi new file mode 100644 index 000000000000..1d68592d288c --- /dev/null +++ b/stubs/docutils/docutils/utils/smartquotes.pyi @@ -0,0 +1,44 @@ +from collections.abc import Generator, Iterable +from re import Pattern +from typing import ClassVar, Final, Literal + +options: Final[str] + +class smartchars: + endash: ClassVar[str] + emdash: ClassVar[str] + ellipsis: ClassVar[str] + apostrophe: ClassVar[str] + quotes: ClassVar[dict[str, str | tuple[str, str, str, str]]] + language: str + def __init__(self, language: str = "en") -> None: ... + +class RegularExpressions: + START_SINGLE: ClassVar[Pattern[str]] + START_DOUBLE: ClassVar[Pattern[str]] + ADJACENT_1: ClassVar[Pattern[str]] + ADJACENT_2: ClassVar[Pattern[str]] + OPEN_SINGLE: ClassVar[Pattern[str]] + OPEN_DOUBLE: ClassVar[Pattern[str]] + DECADE: ClassVar[Pattern[str]] + APOSTROPHE: ClassVar[Pattern[str]] + OPENING_SECONDARY: ClassVar[Pattern[str]] + CLOSING_SECONDARY: ClassVar[Pattern[str]] + OPENING_PRIMARY: ClassVar[Pattern[str]] + CLOSING_PRIMARY: ClassVar[Pattern[str]] + +regexes: RegularExpressions +default_smartypants_attr: Final = "1" + +def smartyPants(text: str, attr="1", language: str = "en") -> str: ... +def educate_tokens(text_tokens: Iterable[tuple[str, str]], attr="1", language: str = "en") -> Generator[str]: ... +def educateQuotes(text: str, language: str = "en") -> str: ... +def educateBackticks(text: str, language: str = "en") -> str: ... +def educateSingleBackticks(text: str, language: str = "en") -> str: ... +def educateDashes(text: str) -> str: ... +def educateDashesOldSchool(text: str) -> str: ... +def educateDashesOldSchoolInverted(text: str) -> str: ... +def educateEllipses(text: str) -> str: ... +def stupefyEntities(text: str, language: str = "en") -> str: ... +def processEscapes(text: str, restore: bool = False) -> str: ... +def tokenize(text: str) -> Generator[tuple[Literal["tag", "text"], str]]: ... diff --git a/stubs/docutils/docutils/utils/urischemes.pyi b/stubs/docutils/docutils/utils/urischemes.pyi new file mode 100644 index 000000000000..5e6f8a70a45d --- /dev/null +++ b/stubs/docutils/docutils/utils/urischemes.pyi @@ -0,0 +1 @@ +schemes: dict[str, str] diff --git a/stubs/docutils/docutils/writers/__init__.pyi b/stubs/docutils/docutils/writers/__init__.pyi index 964e6fa3f426..3fa0f555d1ae 100644 --- a/stubs/docutils/docutils/writers/__init__.pyi +++ b/stubs/docutils/docutils/writers/__init__.pyi @@ -1,3 +1,92 @@ -from typing import Any +from _typeshed import StrPath +from pathlib import Path +from typing import Any, Final, Generic, TypedDict, TypeVar, type_check_only +from typing_extensions import Required -def __getattr__(name: str) -> Any: ... # incomplete +from docutils import Component, nodes +from docutils.frontend import Values +from docutils.io import Output +from docutils.languages import LanguageImporter + +_S = TypeVar("_S") + +__docformat__: Final = "reStructuredText" + +# It would probably be better to specialize writers for subclasses, +# but this gives us all possible Writer items w/o instance checks +@type_check_only +class _WriterParts(TypedDict, total=False): + # Parts Provided by All Writers https://docutils.sourceforge.io/docs/api/publisher.html#parts-provided-by-all-writers + + # See Writer.assemble_parts + whole: Required[str | bytes] + encoding: Required[str] + errors: Required[str] + version: Required[str] + + # Parts Provided by the HTML Writers https://docutils.sourceforge.io/docs/api/publisher.html#parts-provided-by-the-html-writers + + # HTML4 Writer https://docutils.sourceforge.io/docs/api/publisher.html#html4-writer + # + HTML5 Writer https://docutils.sourceforge.io/docs/api/publisher.html#html5-writer + body: str + body_prefix: str + body_pre_docinfo: str + body_suffix: str + docinfo: str + footer: str + fragment: str + head: str + head_prefix: str + header: str + html_body: str + html_head: str + html_prolog: str + html_subtitle: str + html_title: str + meta: str + stylesheet: str + subtitle: str + title: str + # PEP/HTML Writer https://docutils.sourceforge.io/docs/api/publisher.html#pep-html-writer + # + S5/HTML Writer https://docutils.sourceforge.io/docs/api/publisher.html#s5-html-writer + pepnum: str + + # Parts Provided by the (Xe)LaTeX Writers https://docutils.sourceforge.io/docs/api/publisher.html#parts-provided-by-the-xe-latex-writers + + # (commenting out those already included) + abstract: str + # body: str + # body_pre_docinfo: str + dedication: str + # docinfo: str + fallbacks: str + # head_prefix: str + latex_preamble: str + pdfsetup: str + requirements: str + # stylesheet: str + # subtitle: str + # title: str + titledata: str + +class Writer(Component, Generic[_S]): + parts: _WriterParts + language: LanguageImporter | None = None + document: nodes.document | None = None + destination: Output | None = None + output: _S | None = None + def __init__(self) -> None: ... + def write(self, document: nodes.document, destination: Output) -> str | bytes | None: ... + def translate(self) -> None: ... + def assemble_parts(self) -> None: ... + +class UnfilteredWriter(Writer[_S]): ... + +class DoctreeTranslator(nodes.NodeVisitor): + settings: Values + def __init__(self, document: nodes.document) -> None: ... + def uri2path(self, uri: str, output_path: StrPath | None = None) -> Path: ... + +WRITER_ALIASES: Final[dict[str, str]] + +def get_writer_class(writer_name: str) -> type[Writer[Any]]: ... diff --git a/stubs/docutils/docutils/writers/_html_base.pyi b/stubs/docutils/docutils/writers/_html_base.pyi new file mode 100644 index 000000000000..dccf180e85ce --- /dev/null +++ b/stubs/docutils/docutils/writers/_html_base.pyi @@ -0,0 +1,305 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Callable +from re import Pattern +from typing import ClassVar, Final +from typing_extensions import Never + +from docutils import nodes, writers +from docutils.frontend import Values +from docutils.languages import _LanguageModule + +__docformat__: Final = "reStructuredText" + +class Writer(writers.Writer[str]): + settings_defaults: ClassVar[dict[str, str]] + relative_path_settings: ClassVar[tuple[str, ...]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + visitor_attributes: ClassVar[tuple[str, ...]] + visitor: nodes.NodeVisitor + def translate(self) -> None: ... + def apply_template(self) -> str: ... + def interpolation_dict(self) -> dict[str, str]: ... + def assemble_parts(self) -> None: ... + +class HTMLTranslator(nodes.NodeVisitor): + doctype: ClassVar[str] + doctype_mathml: ClassVar[str] + head_prefix_template: ClassVar[str] + content_type: ClassVar[str] + generator: ClassVar[str] + documenttag_args: ClassVar[dict[str, str]] + mathjax_script: ClassVar[str] + mathjax_url: ClassVar[str] + stylesheet_link: ClassVar[str] + embedded_stylesheet: ClassVar[str] + words_and_spaces: ClassVar[Pattern[str]] + in_word_wrap_point: ClassVar[Pattern[str]] + lang_attribute: ClassVar[str] + special_characters: ClassVar[dict[int, str]] + videotypes: ClassVar[tuple[str, ...]] + attribution_formats: ClassVar[dict[str, tuple[str, str]]] + settings: Values + language: _LanguageModule + initial_header_level: int + image_loading: str + body: list[str] + body_prefix: list[str] + body_pre_docinfo: list[Incomplete] + body_suffix: list[str] + docinfo: list[str] + footer: list[str] + fragment: list[Incomplete] + head: list[Incomplete] + head_prefix: list[Incomplete] + header: list[Incomplete] + html_body: list[Incomplete] + html_head: list[Incomplete] + html_prolog: list[Incomplete] + html_subtitle: list[Incomplete] + html_title: list[Incomplete] + meta: list[Incomplete] + stylesheet: list[Incomplete] + title: list[Incomplete] + subtitle: list[Incomplete] + context: list[Incomplete] + section_level: int + colspecs: list[Incomplete] + compact_p: bool + compact_simple: bool + compact_field_list: bool + in_docinfo: bool + in_sidebar: bool + in_document_title: int + in_mailto: bool + author_in_authors: bool + math_header: list[str] + messages: list[Incomplete] + def __init__(self, document: nodes.document) -> None: ... + def astext(self) -> str: ... + def attval(self, text: str, whitespace: Pattern[str] = ...) -> str: ... + def cloak_email(self, addr: str) -> str: ... + def cloak_mailto(self, uri: str) -> str: ... + def encode(self, text: object) -> str: ... + def image_size(self, node: nodes.image) -> str: ... + def read_size_with_PIL(self, node) -> tuple[int, int] | None: ... + def prepare_svg(self, code: str | bytes, node: nodes.Element, atts: dict[str, Incomplete]) -> str: ... + def stylesheet_call(self, path: StrPath, adjust_path: bool | None = None) -> str: ... + def starttag(self, node: nodes.Element, tagname: str, suffix: str = "\n", empty: bool = False, **attributes) -> str: ... + def emptytag(self, node: nodes.Element, tagname: str, suffix: str = "\n", **attributes) -> str: ... + def report_messages(self, node: nodes.Node) -> None: ... + def set_class_on_child(self, node, class_, index: int = 0) -> None: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_abbreviation(self, node: nodes.abbreviation) -> None: ... + def depart_abbreviation(self, node: nodes.abbreviation) -> None: ... + def visit_acronym(self, node: nodes.acronym) -> None: ... + def depart_acronym(self, node: nodes.acronym) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition | None = None) -> None: ... + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def check_simple_list(self, node: nodes.Node) -> bool: ... + def is_compactable(self, node: nodes.Element) -> bool: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def visit_comment(self, node: nodes.comment, sub: Callable[[str, str], str] = ...) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def depart_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def depart_date(self, node: nodes.date) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_docinfo_item(self, node, name: str, meta: bool = True) -> None: ... + def depart_docinfo_item(self) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + math_tags: dict[str, tuple[str, str, list[str]]] + math_output: str | Incomplete + def visit_math(self, node: nodes.math) -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_meta(self, node: nodes.meta) -> None: ... + def depart_meta(self, node: nodes.meta) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def depart_reference(self, node: nodes.reference) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_substitution_reference(self, node: nodes.substitution_reference) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def depart_target(self, node: nodes.target) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def section_title_tags(self, node: nodes.Element) -> tuple[str, str]: ... + def visit_title(self, node: nodes.title) -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def depart_version(self, node: nodes.version) -> None: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... + +class SimpleListChecker(nodes.GenericNodeVisitor): + def visit_list_item(self, node: nodes.list_item) -> None: ... + def pass_node(self, node: nodes.Node) -> None: ... + def ignore_node(self, node: nodes.Node) -> None: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def visit_comment(self, node: nodes.comment) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def visit_pending(self, node: nodes.pending) -> None: ... diff --git a/stubs/docutils/docutils/writers/docutils_xml.pyi b/stubs/docutils/docutils/writers/docutils_xml.pyi new file mode 100644 index 000000000000..dfd4096071d4 --- /dev/null +++ b/stubs/docutils/docutils/writers/docutils_xml.pyi @@ -0,0 +1,45 @@ +from collections.abc import Callable +from typing import ClassVar, Final +from xml.sax.handler import ContentHandler +from xml.sax.xmlreader import Locator, XMLReader + +import docutils +from docutils import nodes, writers +from docutils.frontend import Values + +__docformat__: Final = "reStructuredText" + +class RawXmlError(docutils.ApplicationError): ... + +class Writer(writers.Writer[str]): + settings_defaults: ClassVar[dict[str, str]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[XMLTranslator] + visitor: XMLTranslator + +class XMLTranslator(nodes.GenericNodeVisitor): + doctype: ClassVar[str] + generator: ClassVar[str] + xmlparser: ClassVar[XMLReader] + warn: Callable[..., nodes.system_message] + error: Callable[..., nodes.system_message] + settings: Values + indent: str + newline: str + level: int + in_simple: int + fixed_text: int + output: list[str] + the_handle: TestXml + def __init__(self, document: nodes.document) -> None: ... + simple_nodes: ClassVar[tuple[type[nodes.Element], ...]] + def default_visit(self, node: nodes.Element) -> None: ... # type: ignore[override] + def default_departure(self, node: nodes.Element) -> None: ... # type: ignore[override] + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + +class TestXml(ContentHandler): + locator: Locator + def setDocumentLocator(self, locator: Locator) -> None: ... diff --git a/stubs/docutils/docutils/writers/html4css1/__init__.pyi b/stubs/docutils/docutils/writers/html4css1/__init__.pyi new file mode 100644 index 000000000000..76da0b68d282 --- /dev/null +++ b/stubs/docutils/docutils/writers/html4css1/__init__.pyi @@ -0,0 +1,125 @@ +from _typeshed import Incomplete +from typing import ClassVar, Final + +from docutils import nodes +from docutils.writers import _html_base + +__docformat__: Final = "reStructuredText" + +class Writer(_html_base.Writer): + default_stylesheets: ClassVar[list[str]] + default_stylesheet_dirs: ClassVar[list[str]] + default_template: ClassVar[str] + config_section: ClassVar[str] + translator_class: type[HTMLTranslator] + +class HTMLTranslator(_html_base.HTMLTranslator): + content_type: ClassVar[str] + content_type_mathml: ClassVar[str] + object_image_types: ClassVar[dict[str, str]] + def set_first_last(self, node) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition | None = None) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + author_in_authors: bool + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def is_compactable(self, node: nodes.Element) -> bool: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + in_docinfo: bool + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + docinfo: Incomplete + body: Incomplete + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_docinfo_item(self, node, name, meta: bool = True) -> None: ... + def depart_docinfo_item(self) -> None: ... + def visit_doctest_block(self, node) -> None: ... + def depart_doctest_block(self, node) -> None: ... + def visit_entry(self, node) -> None: ... + def depart_entry(self, node) -> None: ... + compact_p: Incomplete + compact_simple: Incomplete + def visit_enumerated_list(self, node) -> None: ... + def depart_enumerated_list(self, node) -> None: ... + def visit_field(self, node) -> None: ... + def depart_field(self, node) -> None: ... + def visit_field_body(self, node) -> None: ... + def depart_field_body(self, node) -> None: ... + compact_field_list: bool + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def footnote_backrefs(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def should_be_compact_paragraph(self, node: nodes.Element) -> bool: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + in_sidebar: bool + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + in_document_title: int + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + subtitle: list[Incomplete] + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def section_title_tags(self, node: nodes.Element) -> tuple[str, str]: ... + +class SimpleListChecker(_html_base.SimpleListChecker): + def visit_list_item(self, node: nodes.list_item) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... diff --git a/stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi b/stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi new file mode 100644 index 000000000000..dd59417aa099 --- /dev/null +++ b/stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi @@ -0,0 +1,16 @@ +from pathlib import Path +from typing import ClassVar, Final + +from docutils.writers import _html_base + +__docformat__: Final = "reStructuredText" + +class Writer(_html_base.Writer): + default_stylesheets: ClassVar[list[str]] + default_stylesheet_dirs: ClassVar[list[str]] + default_template: ClassVar[Path] + translator_class: type[HTMLTranslator] + +class HTMLTranslator(_html_base.HTMLTranslator): + supported_block_tags: set[str] + supported_inline_tags: set[str] diff --git a/stubs/docutils/docutils/writers/latex2e/__init__.pyi b/stubs/docutils/docutils/writers/latex2e/__init__.pyi new file mode 100644 index 000000000000..359019018439 --- /dev/null +++ b/stubs/docutils/docutils/writers/latex2e/__init__.pyi @@ -0,0 +1,424 @@ +import re +from _typeshed import Incomplete, StrPath +from collections.abc import Callable, Iterable +from io import TextIOWrapper +from pathlib import Path +from typing import ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Never, deprecated + +from docutils import nodes +from docutils.frontend import Values +from docutils.languages import _LanguageModule +from docutils.utils import Reporter +from docutils.writers import Writer as _Writer + +_K = TypeVar("_K") +_V = TypeVar("_V") + +__docformat__: Final = "reStructuredText" + +LATEX_WRITER_DIR: Final[Path] + +class Writer(_Writer[str]): + default_template: ClassVar[str] + default_template_path: ClassVar[Path] + default_preamble: ClassVar[str] + table_style_values: ClassVar[list[str]] + relative_path_settings: ClassVar[tuple[str, ...]] + settings_defaults: ClassVar[dict[str, int]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + head_parts: ClassVar[tuple[str, ...]] + visitor_attributes: ClassVar[tuple[str, ...]] + translator_class: type[LaTeXTranslator] + +class Babel: + language_codes: ClassVar[dict[str, str]] + warn_msg: ClassVar[str] + active_chars: ClassVar[dict[str, str]] + + reporter: Reporter | None + language: str + otherlanguages: dict[str, str | bool] + setup: list[str] + + def __init__(self, language_code: str, reporter: Reporter | None = None) -> None: ... + def __call__(self) -> str: ... + def language_name(self, language_code: str) -> str: ... + def get_language(self) -> str: ... + +@deprecated("Deprecated and will be removed in Docutils 0.24.") +class SortableDict(dict[_K, _V]): + def sortedkeys(self) -> list[_K]: ... + def sortedvalues(self) -> list[_V]: ... + +class PreambleCmds: + ch: ClassVar[str] + color: ClassVar[str] + float: ClassVar[str] + linking: ClassVar[str] + minitoc: ClassVar[str] + table: ClassVar[str] + table_columnwidth: ClassVar[str] + textcomp: ClassVar[str] + abstract_legacy: ClassVar[str] + admonition_legacy: ClassVar[str] + error_legacy: ClassVar[str] + title_legacy: ClassVar[str] + toc_list: ClassVar[str] + ttem: ClassVar[str] + duclass: ClassVar[str] + providelength: ClassVar[str] + abstract: ClassVar[str] + dedication: ClassVar[str] + docinfo: ClassVar[str] + error: ClassVar[str] + highlight_rules: ClassVar[str] + admonition: ClassVar[str] + fieldlist: ClassVar[str] + footnotes: ClassVar[str] + bracket_footnoterefs: ClassVar[str] + inline: ClassVar[str] + legend: ClassVar[str] + lineblock: ClassVar[str] + optionlist: ClassVar[str] + rubric: ClassVar[str] + sidebar: ClassVar[str] + title: ClassVar[str] + subtitle: ClassVar[str] + documentsubtitle: ClassVar[str] + titlereference: ClassVar[str] + transition: ClassVar[str] + secnumdepth: ClassVar[str] + rem: ClassVar[str] + vmin: ClassVar[str] + vmax: ClassVar[str] + +fp: TextIOWrapper +line: str +block_name: str +definitions: str + +class CharMaps: + alltt: ClassVar[dict[int, str]] + special: ClassVar[dict[int, str]] + unsupported_unicode: ClassVar[dict[int, str]] + utf8_supported_unicode: ClassVar[dict[int, str]] + textcomp: ClassVar[dict[int, str]] + pifont: ClassVar[dict[int, str]] + +class DocumentClass: + document_class: str + sections: list[str] + def __init__(self, document_class: str, with_part: bool = False) -> None: ... + def section(self, level: int) -> str: ... + def latex_section_depth(self, depth: int) -> int: ... + +class Table: + legacy_column_widths: bool + caption: list[str] + stubs: list[Incomplete] + colwidths_auto: bool + borders: str + def __init__(self, translator: LaTeXTranslator, latex_type: str) -> None: ... + def open(self) -> None: ... + def close(self) -> None: ... + def is_open(self) -> bool: ... + def set_table_style(self, node, settings) -> None: ... + def get_latex_type(self) -> str: ... + def set(self, attr, value) -> None: ... + def get(self, attr): ... + def get_vertical_bar(self) -> Literal["|", ""]: ... + def get_opening(self, width: str = r"\linewidth") -> str: ... + def get_closing(self) -> str: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def get_colspecs(self, node: nodes.Element) -> str: ... + def get_column_width(self) -> str: ... + def get_multicolumn_width(self, start: int, len_: int) -> str: ... + def need_recurse(self) -> bool | Literal[0]: ... + def visit_thead(self) -> list[str]: ... + def depart_thead(self) -> list[str]: ... + def visit_row(self) -> None: ... + def depart_row(self) -> list[str]: ... + def set_rowspan(self, cell, value) -> None: ... + def get_rowspan(self, cell): ... + def get_entry_number(self) -> int: ... + def visit_entry(self) -> None: ... + def is_stub_column(self): ... + +class LaTeXTranslator(nodes.NodeVisitor): + is_xetex: ClassVar[bool] + compound_enumerators: ClassVar[bool] + section_prefix_for_enumerators: ClassVar[bool] + section_enumerator_separator: ClassVar[str] + has_latex_toc: ClassVar[bool] + section_level: ClassVar[int] + inside_citation_reference_label: ClassVar[bool] + verbatim: ClassVar[bool] + insert_non_breaking_blanks: ClassVar[bool] + insert_newline: ClassVar[bool] + literal: ClassVar[bool] + alltt: ClassVar[bool] + TITLEDATA_NODES: ClassVar[tuple[type[nodes.Element], ...]] + + warn: Callable[..., nodes.system_message] + error: Callable[..., nodes.system_message] + settings: Values + latex_encoding: str + use_latex_toc: Incomplete + use_latex_docinfo: Incomplete + use_latex_citations: Incomplete + reference_label: Incomplete + hyperlink_color: Incomplete + font_encoding: str + literal_block_env: str + literal_block_options: str + bibtex: Incomplete + language_module: _LanguageModule + babel: Babel + author_separator: str + documentoptions: str + d_class: DocumentClass + graphicx_package: str + docutils_footnotes: Incomplete + head_prefix: list[str] + requirements: SortableDict[str, str] | list[str] + latex_preamble: list[Incomplete] + fallbacks: SortableDict[str, str] | list[str] + pdfsetup: list[str] + title: list[Incomplete] + subtitle: list[Incomplete] + titledata: list[Incomplete] + body_pre_docinfo: list[Incomplete] + docinfo: list[Incomplete] + dedication: list[Incomplete] + abstract: list[Incomplete] + body: list[Incomplete] + context: list[Incomplete] + title_labels: list[Incomplete] + subtitle_labels: list[Incomplete] + author_stack: list[Incomplete] + date: list[Incomplete] + pdfauthor: list[Incomplete] + pdfinfo: list[Incomplete] + table_stack: list[Incomplete] + active_table: Table + out: list[Incomplete] + out_stack: list[Incomplete] + fallback_stylesheet: bool + stylesheet: list[str] + hyperref_options: str + + def __init__(self, document: nodes.document, babel_class: type = ...) -> None: ... + def stylesheet_call(self, path: StrPath) -> str: ... + def to_latex_encoding(self, docutils_encoding: str) -> str: ... + def language_label(self, docutil_label: str) -> str: ... + def encode(self, text: str) -> str: ... + def attval(self, text: str, whitespace: re.Pattern[str] = ...) -> str: ... + def is_inline(self, node: nodes.Node) -> bool: ... + def ids_to_labels( + self, node: nodes.Element, set_anchor: bool = True, protect: bool = False, newline: bool = False, pre_nl: bool = False + ) -> list[str]: ... + def append_hypertargets(self, node: nodes.Element) -> None: ... + def set_align_from_classes(self, node) -> None: ... + def insert_align_declaration(self, node: nodes.Element, default: str | None = None) -> None: ... + def provide_fallback(self, feature: str, key: str | None = None) -> None: ... + def duclass_open(self, node) -> None: ... + def duclass_close(self, node) -> None: ... + def push_output_collector(self, new_out) -> None: ... + def pop_output_collector(self) -> None: ... + def term_postfix(self, node: nodes.Element) -> str: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_abbreviation(self, node: nodes.abbreviation) -> None: ... + def depart_abbreviation(self, node: nodes.abbreviation) -> None: ... + def visit_acronym(self, node: nodes.acronym) -> None: ... + def depart_acronym(self, node: nodes.acronym) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def visit_comment(self, node: nodes.comment) -> None: ... + def depart_comment(self, node: nodes.comment) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def depart_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def depart_date(self, node: nodes.date) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + + @overload + def visit_docinfo_item(self, node) -> None: ... + @overload + @deprecated("The `name` parameter is deprecated and will be removed in Docutils 0.24.") + def visit_docinfo_item(self, node, name: str | None) -> None: ... + + def depart_docinfo_item(self, node) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def make_title(self) -> None: ... + def append_bibliogaphy(self) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def insert_additional_table_colum_delimiters(self) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def label_delim(self, node, bracket, superscript) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def to_latex_length(self, length_str: str, node: nodes.Node | None = None) -> str: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def is_plaintext(self, node) -> bool: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_meta(self, node: nodes.meta) -> None: ... + def depart_meta(self, node: nodes.meta) -> None: ... + def visit_math(self, node: nodes.math, math_env: str = "$") -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def depart_raw(self, node: nodes.raw) -> None: ... + def has_unbalanced_braces(self, string: Iterable[str]) -> bool: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def depart_reference(self, node: nodes.reference) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + attribution_formats: dict[str, tuple[str, str]] + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_substitution_reference(self, node: nodes.substitution_reference) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def depart_target(self, node: nodes.target) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def thead_depth(self) -> int: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def visit_title(self, node: nodes.title) -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_contents(self, node) -> None: ... + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def depart_version(self, node: nodes.version) -> None: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... diff --git a/stubs/docutils/docutils/writers/manpage.pyi b/stubs/docutils/docutils/writers/manpage.pyi new file mode 100644 index 000000000000..9b9606008bb3 --- /dev/null +++ b/stubs/docutils/docutils/writers/manpage.pyi @@ -0,0 +1,253 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from typing import ClassVar, Final, Protocol, type_check_only +from typing_extensions import Never + +from docutils import nodes, writers +from docutils.frontend import Values +from docutils.languages import _LanguageModule + +@type_check_only +class _RegexPatternSub(Protocol): + # Matches the signature of the bound instance method `re.Pattern[str].sub` exactly + def __call__(self, /, repl: str | Callable[[re.Match[str]], str], string: str, count: int = 0) -> str: ... + +__docformat__: Final = "reStructuredText" +FIELD_LIST_INDENT: Final[int] +DEFINITION_LIST_INDENT: Final[int] +OPTION_LIST_INDENT: Final[int] +BLOCKQOUTE_INDENT: Final[float] +LITERAL_BLOCK_INDENT: Final[float] +MACRO_DEF: Final[str] +NONPRINTING_BREAKPOINT: Final[str] +NONBREAKING_INSERT_RE: Final[re.Pattern[str]] +NONBREAKING_INSERT_RE2: Final[re.Pattern[str]] + +def insert_URI_breakpoints(s: str) -> str: ... + +class Writer(writers.Writer[str]): + translator_class: type[Translator] + +class Table: + def __init__(self) -> None: ... + def new_row(self) -> None: ... + def append_separator(self, separator) -> None: ... + def append_cell(self, cell_lines: list[str]) -> None: ... + def as_list(self) -> list[str]: ... + +class Translator(nodes.NodeVisitor): + words_and_spaces: ClassVar[re.Pattern[str]] + possibly_a_roff_command: ClassVar[re.Pattern[str]] + document_start: ClassVar[str] + settings: Values + language: _LanguageModule + head: list[str] + body: list[str] + foot: list[str] + section_level: int + context: list[str | int] + topic_class: str + colspecs: list[nodes.colspec] + compact_p: int + compact_simple: Incomplete + header_written: int + authors: list[Incomplete] + defs: dict[str, tuple[str, ...]] + def comment_begin(self, text: str) -> str: ... + def comment(self, text: str) -> str: ... + def ensure_eol(self) -> None: ... + def ensure_c_eol(self) -> None: ... + def astext(self) -> str: ... + def deunicode(self, text: str) -> str: ... + def encode_special_chars(self, text: str) -> str: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def list_start(self, node) -> None: ... + def list_end(self) -> None: ... + def header(self) -> str: ... + def append_header(self) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition, name: str | None = None) -> None: ... + def depart_admonition(self, node: nodes.admonition) -> None: ... + def visit_attention(self, node: nodes.attention) -> None: ... + def depart_attention(self, node: nodes.attention) -> None: ... + def visit_docinfo_item(self, node: nodes.docinfo, name: str) -> None: ... + def depart_docinfo_item(self, node: nodes.docinfo) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_caution(self, node: nodes.caution) -> None: ... + def depart_caution(self, node: nodes.caution) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def write_colspecs(self) -> None: ... + def visit_comment(self, node: nodes.comment, sub: _RegexPatternSub = ...) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def visit_danger(self, node: nodes.danger) -> None: ... + def depart_danger(self, node: nodes.danger) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_error(self, node: nodes.error) -> None: ... + def depart_error(self, node: nodes.error) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def footnote_backrefs(self, node) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_hint(self, node: nodes.hint) -> None: ... + def depart_hint(self, node: nodes.hint) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_image(self, node: nodes.image) -> None: ... + def visit_important(self, node: nodes.important) -> None: ... + def depart_important(self, node: nodes.important) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_math(self, node: nodes.math) -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_note(self, node: nodes.note) -> None: ... + def depart_note(self, node: nodes.note) -> None: ... + def indent(self, by: float = 0.5) -> None: ... + def dedent(self) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def first_child(self, node): ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_substitution_reference(self, node: nodes.substitution_reference) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def visit_tip(self, node: nodes.tip) -> None: ... + def depart_tip(self, node: nodes.tip) -> None: ... + def visit_title(self, node: nodes.title) -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def visit_warning(self, node: nodes.warning) -> None: ... + def depart_warning(self, node: nodes.warning) -> None: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... diff --git a/stubs/docutils/docutils/writers/null.pyi b/stubs/docutils/docutils/writers/null.pyi new file mode 100644 index 000000000000..f20c030b833c --- /dev/null +++ b/stubs/docutils/docutils/writers/null.pyi @@ -0,0 +1,11 @@ +from typing import ClassVar, Final + +from docutils import writers + +__docformat__: Final = "reStructuredText" + +class Writer(writers.UnfilteredWriter[str]): + supported: ClassVar[tuple[str, ...]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str]] + def translate(self) -> None: ... diff --git a/stubs/docutils/docutils/writers/odf_odt/__init__.pyi b/stubs/docutils/docutils/writers/odf_odt/__init__.pyi new file mode 100644 index 000000000000..d9a6795a9438 --- /dev/null +++ b/stubs/docutils/docutils/writers/odf_odt/__init__.pyi @@ -0,0 +1,426 @@ +import itertools +import re +import zipfile +from _typeshed import FileDescriptorOrPath, Incomplete, ReadableBuffer, SizedBuffer, Unused +from collections.abc import Generator +from typing import ClassVar, Final, Literal +from xml.etree import ElementTree + +from docutils import nodes, writers +from docutils.frontend import Values +from docutils.languages import _LanguageModule +from docutils.readers import standalone + +__docformat__: Final = "reStructuredText" +VERSION: Final[str] +IMAGE_NAME_COUNTER: Final[itertools.count[int]] + +class _ElementInterfaceWrapper(ElementTree.Element): + def __init__(self, tag: str, attrib: dict[str, str] | None = None) -> None: ... + def setparent(self, parent) -> None: ... + def getparent(self): ... + +SPACES_PATTERN: Final[re.Pattern[str]] +TABS_PATTERN: Final[re.Pattern[str]] +FILL_PAT1: Final[re.Pattern[str]] +FILL_PAT2: Final[re.Pattern[str]] +TABLESTYLEPREFIX: Final[str] +TABLENAMEDEFAULT: Final[str] +TABLEPROPERTYNAMES: Final[tuple[str, ...]] +GENERATOR_DESC: Final[str] +NAME_SPACE_1: Final[str] +CONTENT_NAMESPACE_DICT: Final[dict[str, str]] +CNSD: Final[dict[str, str]] +STYLES_NAMESPACE_DICT: Final[dict[str, str]] +SNSD: Final[dict[str, str]] +MANIFEST_NAMESPACE_DICT: Final[dict[str, str]] +MANNSD: Final[dict[str, str]] +META_NAMESPACE_DICT: Final[dict[str, str]] +METNSD: Final[dict[str, str]] +CONTENT_NAMESPACE_ATTRIB: Final[dict[str, str]] +STYLES_NAMESPACE_ATTRIB: Final[dict[str, str]] +MANIFEST_NAMESPACE_ATTRIB: Final[dict[str, str]] +META_NAMESPACE_ATTRIB: Final[dict[str, str]] + +def Element( + tag: str, attrib: dict[str, str] | None = None, nsmap: Unused = None, nsdict: Unused = ... +) -> _ElementInterfaceWrapper: ... +def SubElement( + parent: _ElementInterfaceWrapper, tag: str, attrib: dict[str, str] | None = None, nsmap: Unused = None, nsdict: Unused = ... +) -> _ElementInterfaceWrapper: ... +def fix_ns(tag: str, attrib: dict[str, str], nsdict: Unused) -> tuple[str, dict[str, str]]: ... +def add_ns(tag: str, nsdict: Unused = ...) -> str: ... +def ToString(et: ElementTree.ElementTree) -> str: ... +def escape_cdata(text: str) -> str: ... + +class TableStyle: + border: str | None + backgroundcolor: str | None + def __init__(self, border: str | None = None, backgroundcolor: str | None = None) -> None: ... + def get_border_(self): ... + def set_border_(self, border) -> None: ... + border_: Incomplete + def get_backgroundcolor_(self): ... + def set_backgroundcolor_(self, backgroundcolor) -> None: ... + backgroundcolor_: Incomplete + +BUILTIN_DEFAULT_TABLE_STYLE: TableStyle + +class ListLevel: + level: int + sibling_level: bool + nested_level: bool + def __init__(self, level: int, sibling_level: bool = True, nested_level: bool = True) -> None: ... + def get_sibling(self) -> bool: ... + def set_sibling(self, sibling_level: bool) -> None: ... + def get_nested(self) -> bool: ... + def set_nested(self, nested_level: bool) -> None: ... + def get_level(self) -> int: ... + def set_level(self, level: int) -> None: ... + +class Writer(writers.Writer[bytes]): + MIME_TYPE: ClassVar[str] + EXTENSION: ClassVar[str] + default_stylesheet: ClassVar[str] + default_stylesheet_path: ClassVar[str] + default_template: ClassVar[str] + default_template_path: ClassVar[str] + translator_class: type[ODFTranslator] + settings: Values + visitor: ODFTranslator + def assemble_my_parts(self) -> None: ... + def update_stylesheet(self, stylesheet_root, language_code: str | None, region_code: str | None): ... + def write_zip_str( + self, zfile: zipfile.ZipFile, name: str, bytes_: str | SizedBuffer, compress_type: int = zipfile.ZIP_DEFLATED + ) -> None: ... + def store_embedded_files(self, zfile: zipfile.ZipFile) -> None: ... + def get_settings(self) -> bytes: ... + def get_stylesheet(self) -> bytes: ... + def copy_from_stylesheet(self, outzipfile: zipfile.ZipFile) -> None: ... + def assemble_parts(self) -> None: ... + def create_manifest(self) -> str: ... + def create_meta(self) -> str: ... + +class ODFTranslator(nodes.GenericNodeVisitor): + used_styles: ClassVar[tuple[str, ...]] + settings: Values + language_code: str + language: _LanguageModule + format_map: dict[str, str] + section_level: int + section_count: int + content_tree: ElementTree.ElementTree + current_element: _ElementInterfaceWrapper + automatic_styles: _ElementInterfaceWrapper + body_text_element: _ElementInterfaceWrapper + paragraph_style_stack: list[str] + list_style_stack: list[str] + table_count: int + column_count: int + trace_level: int + optiontablestyles_generated: bool + field_name: Incomplete + field_element: Incomplete + title: str | None + image_count: int + image_style_count: int + image_dict: dict[str, tuple[str, str]] + embedded_file_list: list[Incomplete] + syntaxhighlighting: int + syntaxhighlight_lexer: str + header_content: list[Incomplete] + footer_content: list[Incomplete] + in_header: bool + in_footer: bool + blockstyle: str + in_table_of_contents: bool + table_of_content_index_body: _ElementInterfaceWrapper | None + list_level: int + def_list_level: int + footnote_ref_dict: dict[Incomplete, _ElementInterfaceWrapper] + footnote_list: list[tuple[Incomplete, Incomplete]] + footnote_chars_idx: int + footnote_level: int + pending_ids: Incomplete + in_paragraph: bool + found_doc_title: bool + bumped_list_level_stack: list[ListLevel] + meta_dict: dict[Incomplete, Incomplete] + line_block_level: int + line_indent_level: int + citation_id: Incomplete + style_index: int + str_stylesheet: str | bytes + str_stylesheetcontent: str | bytes | None + dom_stylesheet: ElementTree.Element | None + table_styles: dict[str, TableStyle] | None + in_citation: bool + inline_style_count_stack: list[int] + def get_str_stylesheet(self) -> str | bytes: ... + dom_stylesheetcontent: ElementTree.Element + def retrieve_styles(self, extension: str) -> None: ... + def extract_table_styles(self, styles_str: str | ReadableBuffer) -> dict[str, TableStyle]: ... + def get_property(self, stylenode: ElementTree.Element) -> str | None: ... + def add_doc_title(self) -> None: ... + def find_first_text_p(self, el: _ElementInterfaceWrapper) -> _ElementInterfaceWrapper | None: ... + def attach_page_style(self, el: _ElementInterfaceWrapper) -> None: ... + def rststyle(self, name: str, parameters: tuple[object, ...] = ()) -> str: ... + def generate_content_element(self, root: _ElementInterfaceWrapper) -> _ElementInterfaceWrapper: ... + def setup_page(self): ... + def get_dom_stylesheet(self) -> ElementTree.Element | None: ... + def setup_paper(self, root_el) -> None: ... + def add_header_footer(self, root_el) -> None: ... + code_none: int + code_field: int + code_text: int + field_pat: re.Pattern[str] + def create_custom_headfoot(self, parent: _ElementInterfaceWrapper, text: str, style_name, automatic_styles) -> None: ... + def make_field_element( + self, parent: _ElementInterfaceWrapper, text: str, style_name, automatic_styles + ) -> _ElementInterfaceWrapper | None: ... + def split_field_specifiers_iter(self, text: str) -> Generator[tuple[int, str]]: ... + def astext(self) -> str: ... + def content_astext(self) -> str: ... + def set_title(self, title: str) -> None: ... + def get_title(self) -> str | None: ... + def set_embedded_file_list(self, embedded_file_list) -> None: ... + def get_embedded_file_list(self): ... + def get_meta_dict(self): ... + def process_footnotes(self) -> None: ... + def append_child( + self, tag: str, attrib: dict[str, str] | None = None, parent: _ElementInterfaceWrapper | None = None + ) -> _ElementInterfaceWrapper: ... + def append_p(self, style: str, text: str | None = None) -> _ElementInterfaceWrapper: ... + def append_pending_ids(self, el: _ElementInterfaceWrapper) -> None: ... + def set_current_element(self, el: _ElementInterfaceWrapper) -> None: ... + def set_to_parent(self) -> None: ... + def generate_labeled_block(self, node: nodes.Node, label: str) -> _ElementInterfaceWrapper: ... + def generate_labeled_line(self, node: nodes.Node, label: str) -> _ElementInterfaceWrapper: ... + def encode(self, text: str) -> str: ... + def dispatch_visit(self, node: nodes.Element) -> None: ... # type: ignore[override] + def handle_basic_atts(self, node: nodes.Element) -> None: ... + def default_visit(self, node: nodes.Element) -> None: ... # type: ignore[override] + def default_departure(self, node: nodes.Element) -> None: ... # type: ignore[override] + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def depart_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def depart_date(self, node: nodes.date) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def depart_version(self, node: nodes.version) -> None: ... + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_comment(self, node: nodes.comment) -> None: ... + def depart_comment(self, node: nodes.comment) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + save_footnote_current: _ElementInterfaceWrapper + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + footnote_chars: list[str] + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def check_file_exists(self, path: FileDescriptorOrPath) -> Literal[1, 0]: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def get_image_width_height(self, node: nodes.image, attr: str) -> tuple[float | None, Literal["%", "cm"] | None]: ... + def convert_to_cm(self, size: str) -> tuple[float, Literal["cm"]]: ... + def get_image_scale(self, node: nodes.image) -> float: ... + def get_image_scaled_width_height(self, node: nodes.image, source) -> tuple[Incomplete, Incomplete]: ... + def get_page_width(self) -> float: ... + def generate_figure(self, node: nodes.image, source, destination, current_element): ... + def generate_image( + self, node: nodes.image, source, destination, current_element, frame_attrs: dict[str, str] | None = None + ): ... + def is_in_table(self, node: nodes.Node) -> bool: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def fill_line(self, line: str) -> str: ... + def fill_func1(self, matchobj: re.Match[str]) -> str: ... + def fill_func2(self, matchobj: re.Match[str]) -> str: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_math(self, node: nodes.math) -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_meta(self, node: nodes.meta) -> None: ... + def depart_meta(self, node: nodes.meta) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def depart_raw(self, node: nodes.raw) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def depart_reference(self, node: nodes.reference) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_section(self, node: nodes.section, move_ids: int = 1) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def depart_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def get_table_style(self, node) -> TableStyle: ... + current_table_style: _ElementInterfaceWrapper + table_width: float + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + in_thead: bool + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def depart_target(self, node: nodes.target) -> None: ... + def visit_title(self, node: nodes.title, move_ids: int = 1, title_type: str = "title") -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_subtitle(self, node: nodes.subtitle, move_ids: int = 1) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def generate_table_of_content_entry_template(self, el1) -> None: ... + def find_title_label(self, node, class_type, label_key): ... + save_current_element: Incomplete + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def update_toc_page_numbers(self, el) -> None: ... + def update_toc_collect(self, el, level, collection) -> None: ... + def update_toc_add_numbers(self, collection) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_warning(self, node: nodes.warning) -> None: ... + def depart_warning(self, node: nodes.warning) -> None: ... + def visit_attention(self, node: nodes.attention) -> None: ... + def depart_attention(self, node: nodes.attention) -> None: ... + def visit_caution(self, node: nodes.caution) -> None: ... + def depart_caution(self, node: nodes.caution) -> None: ... + def visit_danger(self, node: nodes.danger) -> None: ... + def depart_danger(self, node: nodes.danger) -> None: ... + def visit_error(self, node: nodes.error) -> None: ... + def depart_error(self, node: nodes.error) -> None: ... + def visit_hint(self, node: nodes.hint) -> None: ... + def depart_hint(self, node: nodes.hint) -> None: ... + def visit_important(self, node: nodes.important) -> None: ... + def depart_important(self, node: nodes.important) -> None: ... + def visit_note(self, node: nodes.note) -> None: ... + def depart_note(self, node: nodes.note) -> None: ... + def visit_tip(self, node: nodes.tip) -> None: ... + def depart_tip(self, node: nodes.tip) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition) -> None: ... + def generate_admonition(self, node: nodes.Node, label: str, title: str | None = None) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_abbreviation(self, node: nodes.abbreviation) -> None: ... + def depart_abbreviation(self, node: nodes.abbreviation) -> None: ... + def visit_acronym(self, node: nodes.acronym) -> None: ... + def depart_acronym(self, node: nodes.acronym) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + +class Reader(standalone.Reader[str | bytes]): ... diff --git a/stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi b/stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi new file mode 100644 index 000000000000..d0fbc5009ca5 --- /dev/null +++ b/stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi @@ -0,0 +1,7 @@ +from _typeshed import StrPath +from typing import IO + +NAMESPACES: dict[str, str] + +def prepstyle(filename: StrPath | IO[bytes]) -> None: ... +def main() -> None: ... diff --git a/stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi b/stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi new file mode 100644 index 000000000000..10293d3fb075 --- /dev/null +++ b/stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from typing import Any + +# Formatter[str] from types-pygments +class _Formatter: + name: Any + aliases: Any + filenames: Any + unicodeoutput: bool + style: Any + full: Any + title: Any + encoding: Any + options: Any + def __init__(self, *, encoding: None = None, outencoding: None = None, **options) -> None: ... + def get_style_defs(self, arg: str = ""): ... + def format(self, tokensource, outfile): ... + +class OdtPygmentsFormatter(_Formatter): + rststyle_function: Incomplete + escape_function: Incomplete + def __init__(self, rststyle_function, escape_function) -> None: ... + def rststyle(self, name, parameters=()): ... + def get_style_defs(self, arg: str = ""): ... + def format(self, tokensource, outfile): ... + +class OdtPygmentsProgFormatter(OdtPygmentsFormatter): + def format(self, tokensource, outfile) -> None: ... + +class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter): + def format(self, tokensource, outfile) -> None: ... diff --git a/stubs/docutils/docutils/writers/pep_html/__init__.pyi b/stubs/docutils/docutils/writers/pep_html/__init__.pyi new file mode 100644 index 000000000000..bdefd546ad4e --- /dev/null +++ b/stubs/docutils/docutils/writers/pep_html/__init__.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar, Final + +from docutils.writers import html4css1 + +__docformat__: Final = "reStructuredText" + +class Writer(html4css1.Writer): + default_stylesheet: ClassVar[str] + default_stylesheet_path: ClassVar[str] + default_template_path: ClassVar[str] + settings_default_overrides: ClassVar[dict[str, str]] + relative_path_settings: ClassVar[tuple[str, ...]] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[HTMLTranslator] + pepnum: str + title: str + def interpolation_dict(self) -> dict[str, str | int]: ... # type: ignore[override] + +class HTMLTranslator(html4css1.HTMLTranslator): + def depart_field_list(self, node) -> None: ... diff --git a/stubs/docutils/docutils/writers/pseudoxml.pyi b/stubs/docutils/docutils/writers/pseudoxml.pyi new file mode 100644 index 000000000000..2372ffc0b509 --- /dev/null +++ b/stubs/docutils/docutils/writers/pseudoxml.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils import writers + +__docformat__: Final = "reStructuredText" + +class Writer(writers.Writer[str]): + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/writers/s5_html/__init__.pyi b/stubs/docutils/docutils/writers/s5_html/__init__.pyi new file mode 100644 index 000000000000..fe0f36f15b47 --- /dev/null +++ b/stubs/docutils/docutils/writers/s5_html/__init__.pyi @@ -0,0 +1,42 @@ +import re +from _typeshed import StrPath +from typing import ClassVar, Final + +from docutils import nodes +from docutils.writers import html4css1 + +__docformat__: Final = "reStructuredText" +themes_dir_path: Final[str] + +def find_theme(name: StrPath) -> str: ... + +class Writer(html4css1.Writer): + settings_default_overrides: ClassVar[dict[str, int]] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[S5HTMLTranslator] + +class S5HTMLTranslator(html4css1.HTMLTranslator): + s5_stylesheet_template: ClassVar[str] + disable_current_slide: ClassVar[str] + layout_template: ClassVar[str] + default_theme: ClassVar[str] + base_theme_file: ClassVar[str] + direct_theme_files: ClassVar[tuple[str, ...]] + indirect_theme_files: ClassVar[tuple[str, ...]] + required_theme_files: ClassVar[tuple[str, ...]] + theme_file_path: str | None + s5_footer: list[str] + s5_header: list[str] + section_count: int + theme_files_copied: dict[str, bool] + def __init__(self, document: nodes.document, /) -> None: ... + def setup_theme(self) -> None: ... + def copy_theme(self) -> None: ... + files_to_skip_pattern: re.Pattern[str] + def copy_file(self, name, source_dir, dest_dir): ... + def depart_document(self, node: nodes.document) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_title(self, node: nodes.title) -> None: ... diff --git a/stubs/docutils/docutils/writers/xetex/__init__.pyi b/stubs/docutils/docutils/writers/xetex/__init__.pyi new file mode 100644 index 000000000000..a8528b3670b2 --- /dev/null +++ b/stubs/docutils/docutils/writers/xetex/__init__.pyi @@ -0,0 +1,30 @@ +from typing import ClassVar, Final + +from docutils import nodes +from docutils.utils import Reporter +from docutils.writers import latex2e + +__docformat__: Final = "reStructuredText" + +class Writer(latex2e.Writer): + default_template: ClassVar[str] + default_preamble: ClassVar[str] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[XeLaTeXTranslator] + +class Babel(latex2e.Babel): + language_code: str + reporter: Reporter + language: str + warn_msg: str # type: ignore[misc] + quote_index: int + quotes: tuple[str, ...] + literal_double_quote: str + key: str + def __init__(self, language_code: str, reporter: Reporter) -> None: ... + +class XeLaTeXTranslator(latex2e.LaTeXTranslator): + is_xetex: bool # type: ignore[misc] + def __init__(self, document: nodes.document) -> None: ... + def to_latex_length(self, length_str: str, node: nodes.Node | None = None) -> str: ... diff --git a/stubs/editdistance/@tests/stubtest_allowlist.txt b/stubs/editdistance/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ef46eff1a3b5 --- /dev/null +++ b/stubs/editdistance/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Not public API -- the submodule is an implementation detail due to it being a cythonized package +editdistance.bycython diff --git a/stubs/editdistance/METADATA.toml b/stubs/editdistance/METADATA.toml index 1883b870198a..2c5ced48093a 100644 --- a/stubs/editdistance/METADATA.toml +++ b/stubs/editdistance/METADATA.toml @@ -1 +1,2 @@ -version = "0.5.*" +version = "0.8.*" +upstream-repository = "https://github.com/roy-ht/editdistance" diff --git a/stubs/editdistance/editdistance.pyi b/stubs/editdistance/editdistance.pyi deleted file mode 100644 index 082b0acc0f3b..000000000000 --- a/stubs/editdistance/editdistance.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Hashable, Iterable - -def eval(a: Iterable[Hashable], b: Iterable[Hashable]) -> int: ... -def distance(a: Iterable[Hashable], b: Iterable[Hashable]) -> int: ... diff --git a/stubs/editdistance/editdistance/__init__.pyi b/stubs/editdistance/editdistance/__init__.pyi new file mode 100644 index 000000000000..8d31bd35aa1b --- /dev/null +++ b/stubs/editdistance/editdistance/__init__.pyi @@ -0,0 +1,8 @@ +from collections.abc import Hashable, Iterable + +def eval(a: Iterable[Hashable], b: Iterable[Hashable]) -> int: ... +def distance(a: Iterable[Hashable], b: Iterable[Hashable]) -> int: ... +def eval_criterion(a: Iterable[Hashable], b: Iterable[Hashable], thr: int) -> bool: ... +def distance_le_than(a: Iterable[Hashable], b: Iterable[Hashable], thr: int) -> bool: ... + +__all__ = ("eval", "distance", "eval_criterion", "distance_le_than") diff --git a/stubs/emoji/METADATA.toml b/stubs/emoji/METADATA.toml deleted file mode 100644 index 56eef46c616f..000000000000 --- a/stubs/emoji/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "1.2.*" -python2 = true diff --git a/stubs/emoji/emoji/__init__.pyi b/stubs/emoji/emoji/__init__.pyi deleted file mode 100644 index 0fe8cbc71897..000000000000 --- a/stubs/emoji/emoji/__init__.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from .core import ( - demojize as demojize, - emoji_count as emoji_count, - emoji_lis as emoji_lis, - emojize as emojize, - get_emoji_regexp as get_emoji_regexp, -) -from .unicode_codes import ( - EMOJI_ALIAS_UNICODE_ENGLISH as EMOJI_ALIAS_UNICODE_ENGLISH, - EMOJI_UNICODE_ENGLISH as EMOJI_UNICODE_ENGLISH, - EMOJI_UNICODE_ITALIAN as EMOJI_UNICODE_ITALIAN, - EMOJI_UNICODE_PORTUGUESE as EMOJI_UNICODE_PORTUGUESE, - EMOJI_UNICODE_SPANISH as EMOJI_UNICODE_SPANISH, - UNICODE_EMOJI_ALIAS_ENGLISH as UNICODE_EMOJI_ALIAS_ENGLISH, - UNICODE_EMOJI_ENGLISH as UNICODE_EMOJI_ENGLISH, - UNICODE_EMOJI_ITALIAN as UNICODE_EMOJI_ITALIAN, - UNICODE_EMOJI_PORTUGUESE as UNICODE_EMOJI_PORTUGUESE, - UNICODE_EMOJI_SPANISH as UNICODE_EMOJI_SPANISH, -) diff --git a/stubs/emoji/emoji/core.pyi b/stubs/emoji/emoji/core.pyi deleted file mode 100644 index de134feab0bc..000000000000 --- a/stubs/emoji/emoji/core.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Pattern, Text -from typing_extensions import Literal - -_DEFAULT_DELIMITER: str - -def emojize( - string: str, - use_aliases: bool = ..., - delimiters: tuple[str, str] = ..., - variant: Literal["text_type", "emoji_type", None] = ..., - language: str = ..., -) -> str: ... -def demojize(string: str, use_aliases: bool = ..., delimiters: tuple[str, str] = ..., language: str = ...) -> str: ... -def get_emoji_regexp(language: str = ...) -> Pattern[Text]: ... -def emoji_lis(string: str, language: str = ...) -> list[dict[str, int | str]]: ... -def distinct_emoji_lis(string: str) -> list[str]: ... -def emoji_count(string: str) -> int: ... diff --git a/stubs/emoji/emoji/unicode_codes/__init__.pyi b/stubs/emoji/emoji/unicode_codes/__init__.pyi deleted file mode 100644 index 3dcd4dda06b6..000000000000 --- a/stubs/emoji/emoji/unicode_codes/__init__.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Text - -from .en import ( - EMOJI_ALIAS_UNICODE_ENGLISH as EMOJI_ALIAS_UNICODE_ENGLISH, - EMOJI_UNICODE_ENGLISH as EMOJI_UNICODE_ENGLISH, - UNICODE_EMOJI_ALIAS_ENGLISH as UNICODE_EMOJI_ALIAS_ENGLISH, - UNICODE_EMOJI_ENGLISH as UNICODE_EMOJI_ENGLISH, -) -from .es import EMOJI_UNICODE_SPANISH as EMOJI_UNICODE_SPANISH, UNICODE_EMOJI_SPANISH as UNICODE_EMOJI_SPANISH -from .it import EMOJI_UNICODE_ITALIAN as EMOJI_UNICODE_ITALIAN, UNICODE_EMOJI_ITALIAN as UNICODE_EMOJI_ITALIAN -from .pt import EMOJI_UNICODE_PORTUGUESE as EMOJI_UNICODE_PORTUGUESE, UNICODE_EMOJI_PORTUGUESE as UNICODE_EMOJI_PORTUGUESE - -EMOJI_UNICODE: dict[str, dict[Text, Text]] -UNICODE_EMOJI: dict[str, dict[Text, Text]] diff --git a/stubs/emoji/emoji/unicode_codes/en.pyi b/stubs/emoji/emoji/unicode_codes/en.pyi deleted file mode 100644 index c9f5842f4375..000000000000 --- a/stubs/emoji/emoji/unicode_codes/en.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Text - -EMOJI_ALIAS_UNICODE_ENGLISH: dict[Text, Text] -EMOJI_UNICODE_ENGLISH: dict[Text, Text] -UNICODE_EMOJI_ENGLISH: dict[Text, Text] -UNICODE_EMOJI_ALIAS_ENGLISH: dict[Text, Text] diff --git a/stubs/emoji/emoji/unicode_codes/es.pyi b/stubs/emoji/emoji/unicode_codes/es.pyi deleted file mode 100644 index f16505b47cb7..000000000000 --- a/stubs/emoji/emoji/unicode_codes/es.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Text - -EMOJI_UNICODE_SPANISH: dict[Text, Text] -UNICODE_EMOJI_SPANISH: dict[Text, Text] diff --git a/stubs/emoji/emoji/unicode_codes/it.pyi b/stubs/emoji/emoji/unicode_codes/it.pyi deleted file mode 100644 index 1edefd24077a..000000000000 --- a/stubs/emoji/emoji/unicode_codes/it.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Text - -EMOJI_UNICODE_ITALIAN: dict[Text, Text] -UNICODE_EMOJI_ITALIAN: dict[Text, Text] diff --git a/stubs/emoji/emoji/unicode_codes/pt.pyi b/stubs/emoji/emoji/unicode_codes/pt.pyi deleted file mode 100644 index ef94454f2dbb..000000000000 --- a/stubs/emoji/emoji/unicode_codes/pt.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Text - -EMOJI_UNICODE_PORTUGUESE: dict[Text, Text] -UNICODE_EMOJI_PORTUGUESE: dict[Text, Text] diff --git a/stubs/entrypoints/@tests/stubtest_allowlist.txt b/stubs/entrypoints/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7bfaa84f2a47 --- /dev/null +++ b/stubs/entrypoints/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# staticmethod weirdness: +entrypoints.CaseSensitiveConfigParser.optionxform diff --git a/stubs/entrypoints/METADATA.toml b/stubs/entrypoints/METADATA.toml index 7730a01469a9..cd6b4631d954 100644 --- a/stubs/entrypoints/METADATA.toml +++ b/stubs/entrypoints/METADATA.toml @@ -1,2 +1,2 @@ -version = "0.3.*" -python2 = true +version = "0.4.*" +upstream-repository = "https://github.com/takluyver/entrypoints" diff --git a/stubs/entrypoints/entrypoints.pyi b/stubs/entrypoints/entrypoints.pyi index 8b64db4c78cc..c519f64f4cc9 100644 --- a/stubs/entrypoints/entrypoints.pyi +++ b/stubs/entrypoints/entrypoints.pyi @@ -1,57 +1,48 @@ -import sys -from _typeshed import Self -from typing import Any, Iterator, Sequence, Text, Type +from collections.abc import Iterator, Sequence +from configparser import ConfigParser +from re import Pattern +from typing import Any +from typing_extensions import Self -if sys.version_info >= (3, 0): - from configparser import ConfigParser -else: - from ConfigParser import ConfigParser - -if sys.version_info >= (3, 8): - from re import Pattern -else: - from typing import Pattern - -entry_point_pattern: Pattern[Text] -file_in_zip_pattern: Pattern[Text] +entry_point_pattern: Pattern[str] +file_in_zip_pattern: Pattern[str] class BadEntryPoint(Exception): - epstr: Text - def __init__(self, epstr: Text) -> None: ... + epstr: str + def __init__(self, epstr: str) -> None: ... @staticmethod def err_to_warnings() -> Iterator[None]: ... class NoSuchEntryPoint(Exception): - group: Text - name: Text - def __init__(self, group: Text, name: Text) -> None: ... + group: str + name: str + def __init__(self, group: str, name: str) -> None: ... + +class CaseSensitiveConfigParser(ConfigParser): ... class EntryPoint: - name: Text - module_name: Text - object_name: Text - extras: Sequence[Text] | None + name: str + module_name: str + object_name: str + extras: Sequence[str] | None distro: Distribution | None def __init__( - self, - name: Text, - module_name: Text, - object_name: Text, - extras: Sequence[Text] | None = ..., - distro: Distribution | None = ..., + self, name: str, module_name: str, object_name: str, extras: Sequence[str] | None = ..., distro: Distribution | None = ... ) -> None: ... def load(self) -> Any: ... @classmethod - def from_string(cls: Type[Self], epstr: Text, name: Text, distro: Distribution | None = ...) -> Self: ... + def from_string(cls, epstr: str, name: str, distro: Distribution | None = ...) -> Self: ... class Distribution: - name: Text - version: Text - def __init__(self, name: Text, version: Text) -> None: ... + name: str + version: str + def __init__(self, name: str, version: str) -> None: ... + @classmethod + def from_name_version(cls, name: str) -> Self: ... def iter_files_distros( - path: Sequence[Text] | None = ..., repeated_distro: Text = ... + path: Sequence[str] | None = ..., repeated_distro: str = ... ) -> Iterator[tuple[ConfigParser, Distribution | None]]: ... -def get_single(group: Text, name: Text, path: Sequence[Text] | None = ...) -> EntryPoint: ... -def get_group_named(group: Text, path: Sequence[Text] | None = ...) -> dict[str, EntryPoint]: ... -def get_group_all(group: Text, path: Sequence[Text] | None = ...) -> list[EntryPoint]: ... +def get_single(group: str, name: str, path: Sequence[str] | None = ...) -> EntryPoint: ... +def get_group_named(group: str, path: Sequence[str] | None = ...) -> dict[str, EntryPoint]: ... +def get_group_all(group: str, path: Sequence[str] | None = ...) -> list[EntryPoint]: ... diff --git a/stubs/enum34/@python2/enum.pyi b/stubs/enum34/@python2/enum.pyi deleted file mode 100644 index 4bc061d1c440..000000000000 --- a/stubs/enum34/@python2/enum.pyi +++ /dev/null @@ -1,73 +0,0 @@ -import sys -from abc import ABCMeta -from typing import Any, Dict, Iterator, List, Mapping, Type, TypeVar, Union - -_T = TypeVar("_T") -_S = TypeVar("_S", bound=Type[Enum]) - -# Note: EnumMeta actually subclasses type directly, not ABCMeta. -# This is a temporary workaround to allow multiple creation of enums with builtins -# such as str as mixins, which due to the handling of ABCs of builtin types, cause -# spurious inconsistent metaclass structure. See #1595. -# Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself -class EnumMeta(ABCMeta): - def __iter__(self: Type[_T]) -> Iterator[_T]: ... - def __reversed__(self: Type[_T]) -> Iterator[_T]: ... - def __contains__(self, member: object) -> bool: ... - def __getitem__(self: Type[_T], name: str) -> _T: ... - @property - def __members__(self: Type[_T]) -> Mapping[str, _T]: ... - def __len__(self) -> int: ... - -class Enum(metaclass=EnumMeta): - name: str - value: Any - _name_: str - _value_: Any - _member_names_: List[str] # undocumented - _member_map_: Dict[str, Enum] # undocumented - _value2member_map_: Dict[int, Enum] # undocumented - if sys.version_info >= (3, 7): - _ignore_: Union[str, List[str]] - _order_: str - __order__: str - @classmethod - def _missing_(cls, value: object) -> Any: ... - @staticmethod - def _generate_next_value_(name: str, start: int, count: int, last_values: List[Any]) -> Any: ... - def __new__(cls: Type[_T], value: object) -> _T: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - def __dir__(self) -> List[str]: ... - def __format__(self, format_spec: str) -> str: ... - def __hash__(self) -> Any: ... - def __reduce_ex__(self, proto: object) -> Any: ... - -class IntEnum(int, Enum): - value: int - -def unique(enumeration: _S) -> _S: ... - -_auto_null: Any - -# subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() -class auto(IntFlag): - value: Any - -class Flag(Enum): - def __contains__(self: _T, other: _T) -> bool: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - def __bool__(self) -> bool: ... - def __or__(self: _T, other: _T) -> _T: ... - def __and__(self: _T, other: _T) -> _T: ... - def __xor__(self: _T, other: _T) -> _T: ... - def __invert__(self: _T) -> _T: ... - -class IntFlag(int, Flag): - def __or__(self: _T, other: Union[int, _T]) -> _T: ... - def __and__(self: _T, other: Union[int, _T]) -> _T: ... - def __xor__(self: _T, other: Union[int, _T]) -> _T: ... - __ror__ = __or__ - __rand__ = __and__ - __rxor__ = __xor__ diff --git a/stubs/enum34/METADATA.toml b/stubs/enum34/METADATA.toml deleted file mode 100644 index c0a0050d4a68..000000000000 --- a/stubs/enum34/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "1.1.*" -python2 = true diff --git a/stubs/ephem/@tests/stubtest_allowlist.txt b/stubs/ephem/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..78c3d158f1a7 --- /dev/null +++ b/stubs/ephem/@tests/stubtest_allowlist.txt @@ -0,0 +1,11 @@ +# Tests +ephem.tests.* + +# Leaked loop variables +ephem.stars.k +ephem.stars.v + +# Runtime signature has *args/**kwargs that raise TypeError; stub signature is correct +ephem._libastro.Observer.__init__ +ephem.FixedBody.__init__ +ephem._libastro.FixedBody.__init__ diff --git a/stubs/ephem/METADATA.toml b/stubs/ephem/METADATA.toml new file mode 100644 index 000000000000..1f1f7d6bc0e3 --- /dev/null +++ b/stubs/ephem/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.2.*" +upstream-repository = "https://github.com/brandon-rhodes/pyephem" diff --git a/stubs/ephem/ephem/__init__.pyi b/stubs/ephem/ephem/__init__.pyi new file mode 100644 index 000000000000..477799ef2be7 --- /dev/null +++ b/stubs/ephem/ephem/__init__.pyi @@ -0,0 +1,289 @@ +from collections.abc import Callable +from datetime import datetime as _datetime, timedelta as _timedelta, tzinfo as _tzinfo +from typing import Final, overload +from typing_extensions import Never, Self + +from . import _libastro + +__version__: Final[str] + +# Mathematical constants +tau: Final[float] +twopi: Final[float] +halfpi: Final[float] +quarterpi: Final[float] +eighthpi: Final[float] +degree: Final[float] +arcminute: Final[float] +arcsecond: Final[float] +half_arcsecond: Final[float] +tiny: Final[float] + +# Physical constants +c: Final[float] +meters_per_au: Final[float] +earth_radius: Final[float] +moon_radius: Final[float] +sun_radius: Final[float] + +# Epoch constants +B1900: Final[float] +B1950: Final[float] +J2000: Final[float] + +# Type imports from _libastro +Angle = _libastro.Angle +degrees = _libastro.degrees +hours = _libastro.hours +Date = _libastro.Date + +# Time constants +hour: Final[float] +minute: Final[float] +second: Final[float] + +# Precision constants +default_newton_precision: Final[float] +rise_set_iterations: Final[tuple[int, int, int, int, int, int, int]] + +# Function imports from _libastro +delta_t = _libastro.delta_t +julian_date = _libastro.julian_date + +# Body type imports from _libastro +Body = _libastro.Body +Planet = _libastro.Planet +PlanetMoon = _libastro.PlanetMoon +FixedBody = _libastro.FixedBody +EllipticalBody = _libastro.EllipticalBody +ParabolicBody = _libastro.ParabolicBody +HyperbolicBody = _libastro.HyperbolicBody +EarthSatellite = _libastro.EarthSatellite + +# Database and coordinate functions from _libastro +readdb = _libastro.readdb +readtle = _libastro.readtle +constellation = _libastro.constellation +separation = _libastro.separation +unrefract = _libastro.unrefract +now = _libastro.now + +# Star atlas functions from _libastro +millennium_atlas = _libastro.millennium_atlas +uranometria = _libastro.uranometria +uranometria2000 = _libastro.uranometria2000 + +# Special planet classes from _libastro +Jupiter = _libastro.Jupiter +Saturn = _libastro.Saturn +Moon = _libastro.Moon + +# Dynamically created planet classes +class Mercury(Planet): + __planet__: Final = 0 + +class Venus(Planet): + __planet__: Final = 1 + +class Mars(Planet): + __planet__: Final = 2 + +class Uranus(Planet): + __planet__: Final = 5 + +class Neptune(Planet): + __planet__: Final = 6 + +class Pluto(Planet): + __planet__: Final = 7 + +class Sun(Planet): + __planet__: Final = 8 + +# Planet moon classes +class Phobos(PlanetMoon): + __planet__: Final = 10 + +class Deimos(PlanetMoon): + __planet__: Final = 11 + +class Io(PlanetMoon): + __planet__: Final = 12 + +class Europa(PlanetMoon): + __planet__: Final = 13 + +class Ganymede(PlanetMoon): + __planet__: Final = 14 + +class Callisto(PlanetMoon): + __planet__: Final = 15 + +class Mimas(PlanetMoon): + __planet__: Final = 16 + +class Enceladus(PlanetMoon): + __planet__: Final = 17 + +class Tethys(PlanetMoon): + __planet__: Final = 18 + +class Dione(PlanetMoon): + __planet__: Final = 19 + +class Rhea(PlanetMoon): + __planet__: Final = 20 + +class Titan(PlanetMoon): + __planet__: Final = 21 + +class Hyperion(PlanetMoon): + __planet__: Final = 22 + +class Iapetus(PlanetMoon): + __planet__: Final = 23 + +class Ariel(PlanetMoon): + __planet__: Final = 24 + +class Umbriel(PlanetMoon): + __planet__: Final = 25 + +class Titania(PlanetMoon): + __planet__: Final = 26 + +class Oberon(PlanetMoon): + __planet__: Final = 27 + +class Miranda(PlanetMoon): + __planet__: Final = 28 + +# Newton's method +def newton(f: Callable[[float], float], x0: float, x1: float, precision: float = ...) -> float: ... + +# Equinox and solstice functions +def holiday(d0: _libastro._DateInitType, motion: float, offset: float) -> Date: ... +def previous_vernal_equinox(date: _libastro._DateInitType) -> Date: ... +def next_vernal_equinox(date: _libastro._DateInitType) -> Date: ... +def previous_summer_solstice(date: _libastro._DateInitType) -> Date: ... +def next_summer_solstice(date: _libastro._DateInitType) -> Date: ... +def previous_autumnal_equinox(date: _libastro._DateInitType) -> Date: ... +def next_autumnal_equinox(date: _libastro._DateInitType) -> Date: ... +def previous_winter_solstice(date: _libastro._DateInitType) -> Date: ... +def next_winter_solstice(date: _libastro._DateInitType) -> Date: ... + +# Synonyms +next_spring_equinox = next_vernal_equinox +previous_spring_equinox = previous_vernal_equinox +next_fall_equinox = next_autumnal_equinox +next_autumn_equinox = next_autumnal_equinox +previous_fall_equinox = previous_autumnal_equinox +previous_autumn_equinox = previous_autumnal_equinox + +# More general equinox/solstice functions +def previous_equinox(date: _libastro._DateInitType) -> Date: ... +def next_equinox(date: _libastro._DateInitType) -> Date: ... +def previous_solstice(date: _libastro._DateInitType) -> Date: ... +def next_solstice(date: _libastro._DateInitType) -> Date: ... +def previous_new_moon(date: _libastro._DateInitType) -> Date: ... +def next_new_moon(date: _libastro._DateInitType) -> Date: ... +def previous_first_quarter_moon(date: _libastro._DateInitType) -> Date: ... +def next_first_quarter_moon(date: _libastro._DateInitType) -> Date: ... +def previous_full_moon(date: _libastro._DateInitType) -> Date: ... +def next_full_moon(date: _libastro._DateInitType) -> Date: ... +def previous_last_quarter_moon(date: _libastro._DateInitType) -> Date: ... +def next_last_quarter_moon(date: _libastro._DateInitType) -> Date: ... + +# Exceptions +class CircumpolarError(ValueError): ... +class NeverUpError(CircumpolarError): ... +class AlwaysUpError(CircumpolarError): ... + +# Observer class +class Observer(_libastro.Observer): + __slots__: list[str] = ["name"] + + name: object + + def copy(self) -> Self: ... + __copy__ = copy + def compute_pressure(self) -> None: ... + def previous_transit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def next_transit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def previous_antitransit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def next_antitransit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def disallow_circumpolar(self, declination: float) -> None: ... + def previous_rising(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def previous_setting(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def next_rising(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def next_setting(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def next_pass( + self, body: EarthSatellite, singlepass: bool = True + ) -> tuple[Date | None, Date | None, Date | None, Date | None, Date | None, Date | None]: ... + +# Time conversion functions +def localtime(date: Date | float) -> _datetime: ... + +class _UTC(_tzinfo): + ZERO: _timedelta + def tzname(self, dt: _datetime | None, /) -> Never: ... + def utcoffset(self, dt: _datetime | None) -> _timedelta: ... + def dst(self, dt: _datetime | None) -> _timedelta: ... + +UTC: _UTC + +def to_timezone(date: Date | float, tzinfo: _tzinfo) -> _datetime: ... + +# Coordinate classes +class Coordinate: + epoch: Date + + @overload + def __init__(self, body: Body, *, epoch: _libastro._DateInitType | None = None) -> None: ... + @overload + def __init__(self, coord1: float | str, coord2: float | str, *, epoch: _libastro._DateInitType | None = None) -> None: ... + @overload + def __init__(self, coord: Coordinate, *, epoch: _libastro._DateInitType | None = None) -> None: ... + +class Equatorial(Coordinate): + ra: Angle + dec: Angle + + def get(self) -> tuple[Angle, Angle]: ... + def set(self, ra: float | str, dec: float | str) -> None: ... + + to_radec = get + from_radec = set + +class LonLatCoordinate(Coordinate): + lon: Angle + lat: Angle + + def set(self, lon: float | str, lat: float | str) -> None: ... + def get(self) -> tuple[Angle, Angle]: ... + + @property + def long(self) -> Angle: ... + @long.setter + def long(self, value: Angle) -> None: ... + +class Ecliptic(LonLatCoordinate): + def to_radec(self) -> tuple[Angle, Angle]: ... + def from_radec(self, ra: float | str, dec: float | str) -> None: ... + +class Galactic(LonLatCoordinate): + def to_radec(self) -> tuple[Angle, Angle]: ... + def from_radec(self, ra: float | str, dec: float | str) -> None: ... + +# Backwards compatibility aliases +date = Date +angle = Angle +LongLatCoordinate = LonLatCoordinate + +# Catalog functions +@overload +def star(name: str, observer: Observer, /) -> FixedBody: ... +@overload +def star(name: str, when: _libastro._DateInitType, epoch: _libastro._DateInitType) -> FixedBody: ... + +def city(name: str) -> Observer: ... diff --git a/stubs/ephem/ephem/_libastro.pyi b/stubs/ephem/ephem/_libastro.pyi new file mode 100644 index 000000000000..1d21f7e04c70 --- /dev/null +++ b/stubs/ephem/ephem/_libastro.pyi @@ -0,0 +1,394 @@ +import builtins +from _typeshed import Unused +from datetime import datetime as _datetime +from typing import Final, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Never, Self, deprecated, disjoint_base + +_DateInitType: TypeAlias = ( + Date + | float + | str + | tuple[int] + | tuple[int, int] + | tuple[int, int, float] + | tuple[int, int, float, float] + | tuple[int, int, float, float, float] + | tuple[int, int, float, float, float, float] + | _datetime +) + +@type_check_only +class _DateDescriptor: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Date: ... + + def __set__(self, obj: object, value: _DateInitType) -> None: ... + +@type_check_only +class _AngleDescriptorRadiansHours: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Angle: ... + + def __set__(self, obj: object, value: float | str) -> None: ... + +@type_check_only +class _AngleDescriptorRadiansDegrees: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Angle: ... + + def __set__(self, obj: object, value: float | str) -> None: ... + +@type_check_only +class _AngleDescriptorDegreesRadians: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Angle: ... + + @overload + @deprecated("Do not pass Angle objects! The radian value will be incorrectly interpreted as degrees.") + def __set__(self, obj: object, value: Angle) -> None: ... + @overload + def __set__(self, obj: object, value: float | str) -> None: ... + +J2000: Final[float] +MJD0: Final[float] +earth_radius: Final[float] +meters_per_au: Final[float] +moon_radius: Final[float] +sun_radius: Final[float] + +@disjoint_base +class Angle(float): # type: ignore[type-var] + def __new__(cls, *args: Unused, **kwargs: Unused) -> Never: ... + @property + def norm(self) -> Angle: ... + @property + def znorm(self) -> Angle: ... + +class Date(float): + @overload + def __new__(cls) -> Date: ... + @overload + def __new__(cls, date: _DateInitType, /) -> Date: ... + + def triple(self) -> builtins.tuple[int, int, float]: ... + def tuple(self) -> builtins.tuple[int, int, int, int, int, float]: ... + def datetime(self) -> _datetime: ... + +@disjoint_base +class Observer: + lat: _AngleDescriptorRadiansDegrees + lon: _AngleDescriptorRadiansDegrees + long: _AngleDescriptorRadiansDegrees + elevation: float + elev: float + temp: float + temperature: float + pressure: float + horizon: _AngleDescriptorRadiansDegrees + epoch: _DateDescriptor + date: _DateDescriptor + + def __init__(self) -> None: ... + def sidereal_time(self) -> Angle: ... + def radec_of(self, az: float | str, alt: float | str) -> tuple[Angle, Angle]: ... + +@disjoint_base +class Body: + @property + def name(self) -> str | None: ... + @property + def a_ra(self) -> Angle: ... + @property + def a_dec(self) -> Angle: ... + @property + def a_epoch(self) -> Date: ... + @property + def ra(self) -> Angle: ... + @property + def dec(self) -> Angle: ... + @property + def g_ra(self) -> Angle: ... + @property + def g_dec(self) -> Angle: ... + @property + def elong(self) -> Angle: ... + @property + def mag(self) -> float: ... + @property + def size(self) -> float: ... + @property + def radius(self) -> Angle: ... + @property + def alt(self) -> Angle: ... + @property + def az(self) -> Angle: ... + @property + def ha(self) -> Angle: ... + @property + def rise_time(self) -> Date | None: ... + @property + def rise_az(self) -> Angle | None: ... + @property + def transit_time(self) -> Date | None: ... + @property + def transit_alt(self) -> Angle | None: ... + @property + def set_time(self) -> Date | None: ... + @property + def set_az(self) -> Angle | None: ... + @property + def circumpolar(self) -> bool: ... + @property + def neverup(self) -> bool: ... + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + def __copy__(self) -> Self: ... + + @overload + def compute(self, observer: Observer, /) -> None: ... + @overload + def compute(self, when: _DateInitType = ..., epoch: _DateInitType = ...) -> None: ... + + def copy(self) -> Self: ... + def writedb(self) -> str: ... + def parallactic_angle(self) -> Angle: ... + +class Planet(Body): + @property + def hlon(self) -> Angle: ... + @property + def hlat(self) -> Angle: ... + @property + def sun_distance(self) -> float: ... + @property + def earth_distance(self) -> float: ... + @property + def phase(self) -> float: ... + @property + def hlong(self) -> Angle: ... + + @overload + def __init__(self, observer: Observer, /) -> None: ... + @overload + def __init__(self, when: _DateInitType, /, epoch: _DateInitType = ...) -> None: ... + @overload + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +@disjoint_base +class Moon(Planet): + @property + def libration_lat(self) -> Angle: ... + @property + def libration_long(self) -> Angle: ... + @property + def colong(self) -> Angle: ... + @property + def moon_phase(self) -> float: ... + @property + def subsolar_lat(self) -> Angle: ... + +@disjoint_base +class Jupiter(Planet): + @property + def cmlI(self) -> Angle: ... + @property + def cmlII(self) -> Angle: ... + +@disjoint_base +class Saturn(Planet): + @property + def earth_tilt(self) -> Angle: ... + @property + def sun_tilt(self) -> Angle: ... + +@disjoint_base +class PlanetMoon: + @property + def name(self) -> str: ... + @property + def a_ra(self) -> Angle: ... + @property + def a_dec(self) -> Angle: ... + @property + def ra(self) -> Angle: ... + @property + def dec(self) -> Angle: ... + @property + def g_ra(self) -> Angle: ... + @property + def g_dec(self) -> Angle: ... + @property + def alt(self) -> Angle: ... + @property + def az(self) -> Angle: ... + @property + def x(self) -> float: ... + @property + def y(self) -> float: ... + @property + def z(self) -> float: ... + @property + def earth_visible(self) -> float: ... + @property + def sun_visible(self) -> float: ... + + @overload + def __init__(self, observer: Observer, /) -> None: ... + @overload + def __init__(self, when: _DateInitType, /, epoch: _DateInitType = ...) -> None: ... + @overload + def __init__(self, **kwargs: Unused) -> None: ... + + def __copy__(self) -> Self: ... + + @overload + def compute(self, observer: Observer, /) -> None: ... + @overload + def compute(self, when: _DateInitType = ..., epoch: _DateInitType = ...) -> None: ... + + def copy(self) -> Self: ... + def writedb(self) -> str: ... + def parallactic_angle(self) -> Angle: ... + +class FixedBody(Body): + name: str | None + mag: float + _spect: str + _ratio: float + _pa: _AngleDescriptorRadiansDegrees + _epoch: _DateDescriptor + _ra: _AngleDescriptorRadiansHours + _dec: _AngleDescriptorRadiansDegrees + _pmra: float + _pmdec: float + _class: str + + def __init__(self) -> None: ... + +class EllipticalBody(Planet): + name: str | None + _inc: _AngleDescriptorDegreesRadians + _Om: _AngleDescriptorDegreesRadians + _om: _AngleDescriptorDegreesRadians + _M: _AngleDescriptorDegreesRadians + _epoch_M: _DateDescriptor + _epoch: _DateDescriptor + _H: float + _G: float + _g: float + _k: float + _a: float + _size: float + _e: float + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +class ParabolicBody(Planet): + name: str | None + _epoch: _DateDescriptor + _epoch_p: _DateDescriptor + _inc: _AngleDescriptorDegreesRadians + _om: _AngleDescriptorDegreesRadians + _Om: _AngleDescriptorDegreesRadians + _q: float + _g: float + _k: float + _size: float + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +class HyperbolicBody(Planet): + name: str | None + _epoch: _DateDescriptor + _epoch_p: _DateDescriptor + _inc: _AngleDescriptorDegreesRadians + _Om: _AngleDescriptorDegreesRadians + _om: _AngleDescriptorDegreesRadians + _e: float + _q: float + _g: float + _k: float + _size: float + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +@disjoint_base +class EarthSatellite(Body): + name: str | None + epoch: _DateDescriptor + _epoch: _DateDescriptor + _inc: _AngleDescriptorDegreesRadians + _raan: _AngleDescriptorDegreesRadians + _ap: _AngleDescriptorDegreesRadians + _M: _AngleDescriptorDegreesRadians + n: float + inc: float + raan: float + e: float + ap: float + M: float + decay: float + drag: float + orbit: float + _n: float + _e: float + _decay: float + _drag: float + _orbit: int + catalog_number: str | None + + @property + def sublat(self) -> Angle: ... + @property + def sublong(self) -> Angle: ... + @property + def elevation(self) -> float: ... + @property + def range(self) -> float: ... + @property + def range_velocity(self) -> float: ... + @property + def eclipsed(self) -> bool: ... + +@type_check_only +class _MoonPhases(TypedDict): + new: Date + full: Date + +def builtin_planets() -> list[tuple[int, str, str]]: ... +def degrees(angle: float | str, /) -> Angle: ... +def hours(angle: float | str, /) -> Angle: ... +def now() -> Date: ... +def separation( + obj1: tuple[float | str, float | str] | Body | Observer, obj2: tuple[float | str, float | str] | Body | Observer, / +) -> Angle: ... +def readdb(db_line: str, /) -> Body: ... +def readtle(name: str, line1: str, line2: str, /) -> EarthSatellite: ... +def unrefract(pressure: float, temperature: float, apparent_alt: float, /) -> Angle: ... +def uranometria(ra: float | str, dec: float | str, /) -> int: ... +def uranometria2000(ra: float | str, dec: float | str, /) -> int: ... +def millennium_atlas(ra: float | str, dec: float | str, /) -> int: ... + +@overload +def constellation(position: Body) -> tuple[str, str]: ... +@overload +def constellation(position: tuple[Angle | float, Angle | float], epoch: Date | float = ...) -> tuple[str, str]: ... + +def julian_date(date: _DateInitType | Observer = ..., /) -> float: ... +def delta_t(date: _DateInitType | Observer = ..., /) -> float: ... +def moon_phases(date: _DateInitType | Observer = ...) -> _MoonPhases: ... +def eq_ecl(epoch: Date | float, ra: Angle | float, dec: Angle | float, /) -> tuple[Angle, Angle]: ... +def ecl_eq(epoch: Date | float, lon: Angle | float, lat: Angle | float, /) -> tuple[Angle, Angle]: ... +def eq_gal(epoch: Date | float, ra: Angle | float, dec: Angle | float, /) -> tuple[Angle, Angle]: ... +def gal_eq(epoch: Date | float, glon: Angle | float, glat: Angle | float, /) -> tuple[Angle, Angle]: ... +def precess(epoch1: Date | float, epoch2: Date | float, ra: Angle | float, dec: Angle | float, /) -> tuple[Angle, Angle]: ... +def _next_pass( + observer: Observer, body: Body, / +) -> tuple[Date | None, Angle | None, Date | None, Angle | None, Date | None, Angle | None]: ... diff --git a/stubs/ephem/ephem/cities.pyi b/stubs/ephem/ephem/cities.pyi new file mode 100644 index 000000000000..fa6959106a6a --- /dev/null +++ b/stubs/ephem/ephem/cities.pyi @@ -0,0 +1,5 @@ +from . import Observer + +def city(name: str) -> Observer: ... +def lookup(address: str) -> None: ... +def lookup_with_geonames(q: str, username: str) -> Observer: ... diff --git a/stubs/ephem/ephem/stars.pyi b/stubs/ephem/ephem/stars.pyi new file mode 100644 index 000000000000..0806c1be73e0 --- /dev/null +++ b/stubs/ephem/ephem/stars.pyi @@ -0,0 +1,15 @@ +from typing import Final, overload + +from . import FixedBody, Observer +from ._libastro import _DateInitType + +db: Final[str] +stars: dict[str, FixedBody] + +@overload +def star(name: str, observer: Observer, /) -> FixedBody: ... +@overload +def star(name: str, when: _DateInitType = ..., epoch: _DateInitType = ...) -> FixedBody: ... + +STAR_NUMBER_NAME: Final[dict[int, str]] +STAR_NAME_NUMBER: Final[dict[str, int]] diff --git a/stubs/et_xmlfile/METADATA.toml b/stubs/et_xmlfile/METADATA.toml new file mode 100644 index 000000000000..db02b864055f --- /dev/null +++ b/stubs/et_xmlfile/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.*" +upstream-repository = "https://foss.heptapod.net/openpyxl/et_xmlfile" diff --git a/stubs/et_xmlfile/et_xmlfile/__init__.pyi b/stubs/et_xmlfile/et_xmlfile/__init__.pyi new file mode 100644 index 000000000000..ddf9bb3b811f --- /dev/null +++ b/stubs/et_xmlfile/et_xmlfile/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Final + +from .xmlfile import xmlfile as xmlfile + +__version__: Final[str] +__author__: Final[str] +__license__: Final[str] +__author_email__: Final[str] +__url__: Final[str] diff --git a/stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi b/stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi new file mode 100644 index 000000000000..217728dbee3b --- /dev/null +++ b/stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi @@ -0,0 +1,173 @@ +import xml.etree.ElementTree as ET +from _typeshed import Unused +from collections.abc import Callable +from typing import Any, Literal, overload + +def current_global_nsmap() -> dict[str, str]: ... + +class IncrementalTree(ET.ElementTree): + def write( # type: ignore[override] + self, + file_or_filename: ET._FileWrite, + encoding: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + method: Literal["xml", "html", "text"] | None = None, # does not accept 'c14n', unlike parent method + *, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + ) -> None: ... + +def process_attribs( + elem: ET.Element[Any], + is_nsmap_scope_changed: bool | None, + default_ns_attr_prefix: str | None, + nsmap_scope: dict[str, str], + global_nsmap: dict[str, str], + new_namespace_prefixes: set[str], + uri_to_prefix: dict[str, str], +) -> tuple[list[tuple[str, str]], str | None, dict[str, str]]: ... +def write_elem_start( + write: Callable[..., None], + elem: ET.Element[Any], + nsmap_scope: dict[str, str], + global_nsmap: dict[str, str], + short_empty_elements: bool | None, + is_html: bool | None, + is_root: bool = False, + uri_to_prefix: dict[str, str] | None = None, + default_ns_attr_prefix: str | None = None, + new_nsmap: dict[str, str] | None = None, + **kwargs: Unused, +) -> tuple[str | None, dict[str, str], str | None, dict[str, str] | None, bool]: ... + +@overload +def tostring( + element: ET.Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> bytes: ... +@overload +def tostring( + element: ET.Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> str: ... +@overload +def tostring( + element: ET.Element[Any], + encoding: str, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> Any: ... + +@overload +def tostringlist( + element: ET.Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> list[bytes]: ... +@overload +def tostringlist( + element: ET.Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> list[str]: ... +@overload +def tostringlist( + element: ET.Element[Any], + encoding: str, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> list[Any]: ... + +@overload +def compat_tostring( + element: ET.Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = True, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> bytes: ... +@overload +def compat_tostring( + element: ET.Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = True, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> str: ... +@overload +def compat_tostring( + element: ET.Element[Any], + encoding: str, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = True, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> Any: ... diff --git a/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi b/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi new file mode 100644 index 000000000000..ffa96d78670c --- /dev/null +++ b/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi @@ -0,0 +1,36 @@ +import types +import xml.etree.ElementTree as ET +from collections.abc import Callable, Generator +from contextlib import _GeneratorContextManager, contextmanager +from typing import Any + +class LxmlSyntaxError(Exception): ... + +class _IncrementalFileWriter: + global_nsmap: dict[str, str] + is_html: bool + def __init__(self, output_file: Callable[[str], object]) -> None: ... + @contextmanager + def element( + self, + tag: str | ET._ElementCallable, + attrib: dict[str, str] | None = None, + nsmap: dict[str, str] | None = None, + **_extra: str, + ) -> Generator[None]: ... + def write(self, arg: str | ET.Element[Any]) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None + ) -> None: ... + +class xmlfile: + encoding: str + writer_cm: _GeneratorContextManager[tuple[Callable[[str], object], str]] | None + def __init__( + self, output_file: ET._FileWrite, buffered: bool = False, encoding: str = "utf-8", close: bool = False + ) -> None: ... + def __enter__(self) -> _IncrementalFileWriter: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None + ) -> None: ... diff --git a/stubs/fanstatic/@tests/stubtest_allowlist.txt b/stubs/fanstatic/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e51f685c4d08 --- /dev/null +++ b/stubs/fanstatic/@tests/stubtest_allowlist.txt @@ -0,0 +1,69 @@ +# Error: is not present in stub +# ============================= +# These are methods and attributes that really should have been +# prefixed with a `_`, since they should only really be used +# internally +fanstatic.core.Asset.init_dependency_nr +fanstatic.core.Library.init_library_nr + +# In order to catch errors where DummyNeededResources would be called +# with clear/library_url/resources these methods were dropped from the +# stub. We would prefer to use @type_error() once that is an option +fanstatic.core.DummyNeededResources.clear +fanstatic.core.DummyNeededResources.library_url +fanstatic.core.DummyNeededResources.resources + +fanstatic.compiler.mtime + +# Error: is inconsistent +# ====================== +# The core API for Dependable is a bit annoying, since the base class +# should really be abstract and instead defines some attributes as +# None, even though all subclasses populate them, so these have been +# made abstract to make defining correct subclasses more easy +fanstatic.core.Asset.depends +fanstatic.core.Asset.resources +fanstatic.core.Asset.supports +fanstatic.core.Dependable.depends +fanstatic.core.Dependable.resources +fanstatic.core.Dependable.supports +fanstatic.core.Group.depends +fanstatic.core.Group.resources +fanstatic.core.Group.supports + +# The API for Compiler has very much the same problem, so these are +# some more attributes/methods that have been made abstract for the +# purposes of type checking +fanstatic.compiler.CommandlineBase.command +fanstatic.compiler.Compiler.name +fanstatic.compiler.Compiler.source_extension +fanstatic.compiler.Minifier.name +fanstatic.compiler.Minifier.source_extension +fanstatic.compiler.Minifier.target_extension +fanstatic.compiler.NullCompiler.name +fanstatic.registry.Registry.ENTRY_POINT + +# This is only inconsistent because the library authors set this +# attribute to `None` on the class, so they could assign a docstring +# to it. `__init__` will always populate this attribute with a `str` +fanstatic.core.Library.path + +# Error: variable differs from runtime type +# ====================== +# These are some sentinel objects which use the NewType pattern to create a +# distinct type +fanstatic.compiler.SOURCE +fanstatic.compiler.TARGET +fanstatic.core.NOTHING +fanstatic.core.REQUIRED_DEFAULT_MARKER + +# Error: is not present at runtime +# ================================ +# See above, defining correct subclasses is more easy with abstract +# properties on the superclass +fanstatic.injector.InjectorPlugin.name + +# Error: failed to find stubs +# =========================== +# Tests should not be part of the stubs +fanstatic.tests.* diff --git a/stubs/fanstatic/METADATA.toml b/stubs/fanstatic/METADATA.toml new file mode 100644 index 000000000000..a7eea5dca12e --- /dev/null +++ b/stubs/fanstatic/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.7.*" +upstream-repository = "https://github.com/zopefoundation/fanstatic" +dependencies = ["types-setuptools", "types-WebOb"] diff --git a/stubs/fanstatic/fanstatic/__init__.pyi b/stubs/fanstatic/fanstatic/__init__.pyi new file mode 100644 index 000000000000..9527cb5fb528 --- /dev/null +++ b/stubs/fanstatic/fanstatic/__init__.pyi @@ -0,0 +1,43 @@ +from fanstatic.compiler import Compiler as Compiler, Minifier as Minifier, sdist_compile as sdist_compile +from fanstatic.core import ( + BUNDLE_PREFIX as BUNDLE_PREFIX, + DEBUG as DEBUG, + DEFAULT_SIGNATURE as DEFAULT_SIGNATURE, + MINIFIED as MINIFIED, + NEEDED as NEEDED, + VERSION_PREFIX as VERSION_PREFIX, + ConfigurationError as ConfigurationError, + Group as Group, + GroupResource as GroupResource, + Library as Library, + LibraryDependencyCycleError as LibraryDependencyCycleError, + NeededResources as NeededResources, + Resource as Resource, + Slot as Slot, + SlotError as SlotError, + UnknownResourceError as UnknownResourceError, + UnknownResourceExtension as UnknownResourceExtension, + UnknownResourceExtensionError as UnknownResourceExtensionError, + clear_needed as clear_needed, + del_needed as del_needed, + get_needed as get_needed, + init_needed as init_needed, + register_inclusion_renderer as register_inclusion_renderer, + set_auto_register_library as set_auto_register_library, + set_resource_file_existence_checking as set_resource_file_existence_checking, +) +from fanstatic.inclusion import Inclusion as Inclusion, bundle_resources as bundle_resources, sort_resources as sort_resources +from fanstatic.injector import Injector as Injector, make_injector as make_injector +from fanstatic.publisher import ( + Delegator as Delegator, + LibraryPublisher as LibraryPublisher, + Publisher as Publisher, + make_publisher as make_publisher, +) +from fanstatic.registry import ( + CompilerRegistry as CompilerRegistry, + LibraryRegistry as LibraryRegistry, + MinifierRegistry as MinifierRegistry, + get_library_registry as get_library_registry, +) +from fanstatic.wsgi import Fanstatic as Fanstatic, Serf as Serf, make_fanstatic as make_fanstatic, make_serf as make_serf diff --git a/stubs/fanstatic/fanstatic/checksum.pyi b/stubs/fanstatic/fanstatic/checksum.pyi new file mode 100644 index 000000000000..316137739b11 --- /dev/null +++ b/stubs/fanstatic/fanstatic/checksum.pyi @@ -0,0 +1,10 @@ +from _typeshed import GenericPath, StrOrBytesPath, StrPath +from collections.abc import Iterator +from typing import AnyStr + +VCS_NAMES: list[str] +IGNORED_EXTENSIONS: list[str] + +def list_directory(path: GenericPath[AnyStr], include_directories: bool = True) -> Iterator[AnyStr]: ... +def mtime(path: StrOrBytesPath) -> str: ... +def md5(path: StrPath) -> str: ... diff --git a/stubs/fanstatic/fanstatic/compiler.pyi b/stubs/fanstatic/fanstatic/compiler.pyi new file mode 100644 index 000000000000..3ac5c78d6dd4 --- /dev/null +++ b/stubs/fanstatic/fanstatic/compiler.pyi @@ -0,0 +1,124 @@ +from _typeshed import StrOrBytesPath +from abc import abstractmethod +from logging import Logger +from subprocess import Popen +from typing import Any, ClassVar, Literal, NewType + +import setuptools.command.sdist +from fanstatic.core import Resource + +logger: Logger + +class CompilerError(Exception): ... + +class Compiler: + @property + @abstractmethod + def name(self) -> str: ... + @property + @abstractmethod + def source_extension(self) -> str: ... + def __call__(self, resource: Resource, force: bool = False) -> None: ... + def process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> Any: ... + def should_process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> bool: ... + @property + @abstractmethod + def available(self) -> bool: ... + def source_path(self, resource: Resource) -> str | None: ... + def target_path(self, resource: Resource) -> str | None: ... + +class Minifier(Compiler): + @property + @abstractmethod + def name(self) -> str: ... + @property + @abstractmethod + def source_extension(self) -> str: ... + @property + @abstractmethod + def target_extension(self) -> str: ... + def source_to_target(self, resource: Resource) -> str: ... + +def compile_resources(argv: list[str] = ...) -> None: ... + +class sdist_compile(setuptools.command.sdist.sdist): ... + +class NullCompiler(Compiler): + name: ClassVar[Literal[""]] + source_extension = NotImplemented + def source_path(self, resource: Resource) -> None: ... + def target_path(self, resource: Resource) -> None: ... + def should_process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> Literal[False]: ... + @property + def available(self) -> Literal[False]: ... + +_SourceType = NewType("_SourceType", object) +_TargetType = NewType("_TargetType", object) +SOURCE: _SourceType +TARGET: _TargetType + +class CommandlineBase: + @property + @abstractmethod + def command(self) -> str: ... + arguments: ClassVar[list[str]] + @property + def available(self) -> bool: ... + def process(self, source: StrOrBytesPath | _SourceType, target: StrOrBytesPath | _TargetType) -> Popen[str]: ... + +class CoffeeScript(CommandlineBase, Compiler): + name: ClassVar[Literal["coffee"]] + command: ClassVar[Literal["coffee"]] + source_extension = NotImplemented + def process( # type: ignore[override] + self, source: StrOrBytesPath | _SourceType, target: StrOrBytesPath | _TargetType + ) -> None: ... + +COFFEE_COMPILER: CoffeeScript + +class LESS(CommandlineBase, Compiler): + name: ClassVar[Literal["less"]] + command: ClassVar[Literal["lessc"]] + source_extension = NotImplemented + +LESS_COMPILER: LESS + +class SASS(CommandlineBase, Compiler): + name: ClassVar[Literal["sass"]] + command: ClassVar[Literal["sass"]] + source_extension: ClassVar[Literal[".scss"]] + +SASS_COMPILER: SASS + +class PythonPackageBase: + @property + @abstractmethod + def package(self) -> str: ... + @property + def available(self) -> bool: ... + +class CSSMin(PythonPackageBase, Minifier): + name: ClassVar[Literal["cssmin"]] + package: ClassVar[Literal["cssmin"]] + source_extension = NotImplemented + target_extension: ClassVar[Literal[".min.css"]] + +CSSMIN_MINIFIER: CSSMin + +class JSMin(PythonPackageBase, Minifier): + name: ClassVar[Literal["jsmin"]] + package: ClassVar[Literal["jsmin"]] + source_extension = NotImplemented + target_extension: ClassVar[Literal[".min.js"]] + +JSMIN_MINIFIER: JSMin + +class Closure(PythonPackageBase, Minifier): + name: ClassVar[Literal["closure"]] + package: ClassVar[Literal["closure"]] + source_extension = NotImplemented + target_extension: Literal[".min.js"] + arguments: ClassVar[list[str]] + def process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> Popen[str]: ... + +CLOSURE_MINIFIER: Closure diff --git a/stubs/fanstatic/fanstatic/config.pyi b/stubs/fanstatic/fanstatic/config.pyi new file mode 100644 index 000000000000..551600e14faf --- /dev/null +++ b/stubs/fanstatic/fanstatic/config.pyi @@ -0,0 +1,10 @@ +from _typeshed import SupportsItems +from typing import TypeVar + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +BOOL_CONFIG: set[str] + +def asbool(obj: object) -> bool: ... +def convert_config(config: SupportsItems[_KT, _VT]) -> dict[_KT, _VT | bool]: ... diff --git a/stubs/fanstatic/fanstatic/core.pyi b/stubs/fanstatic/fanstatic/core.pyi new file mode 100644 index 000000000000..9197bdd323c2 --- /dev/null +++ b/stubs/fanstatic/fanstatic/core.pyi @@ -0,0 +1,236 @@ +from abc import abstractmethod +from collections.abc import Callable, Iterable +from threading import local +from types import ModuleType +from typing import Literal, NewType, TypeAlias + +from fanstatic.compiler import Compiler, Minifier + +_Renderer: TypeAlias = Callable[[str], str] + +DEFAULT_SIGNATURE: str +VERSION_PREFIX: str +BUNDLE_PREFIX: str +NEEDED: str +DEBUG: str +MINIFIED: str + +def set_resource_file_existence_checking(v: bool) -> None: ... +def set_auto_register_library(v: bool) -> None: ... + +class UnknownResourceExtensionError(Exception): ... +class ModeResourceDependencyError(Exception): ... + +UnknownResourceExtension = UnknownResourceExtensionError + +class UnknownResourceError(Exception): ... +class ConfigurationError(Exception): ... +class LibraryDependencyCycleError(Exception): ... +class SlotError(Exception): ... + +class Library: + path: str + name: str + rootpath: str + ignores: list[str] + version: str | None + known_resources: dict[str, Resource] + known_assets: dict[str, Asset] + module: ModuleType + compilers: dict[str, Compiler] + minifiers: dict[str, Minifier] + def __init__( + self, + name: str, + rootpath: str, + ignores: list[str] | None = None, + version: str | None = None, + compilers: dict[str, Compiler] | None = None, + minifiers: dict[str, Minifier] | None = None, + ) -> None: ... + def check_dependency_cycle(self, resource: Resource) -> None: ... + def register(self, resource: Resource) -> None: ... + def signature(self, recompute_hashes: bool = False, version_method: Callable[[str], str] | None = None) -> str: ... + +def caller_dir() -> str: ... + +class InclusionRenderers(dict[str, tuple[int, _Renderer]]): + def register(self, extension: str, renderer: _Renderer, order: int | None = None) -> None: ... + +inclusion_renderers: InclusionRenderers + +def register_inclusion_renderer(extension: str, renderer: _Renderer, order: int | None = None) -> None: ... +def render_ico(url: str) -> str: ... +def render_css(url: str) -> str: ... +def render_js(url: str) -> str: ... +def render_print_css(url: str) -> str: ... +def render_screen_css(url: str) -> str: ... + +class Renderable: + @abstractmethod + def render(self, library_url: str) -> str: ... + +class Dependable: + @property + @abstractmethod + def resources(self) -> set[Dependable]: ... + @property + @abstractmethod + def depends(self) -> set[Dependable]: ... + @property + @abstractmethod + def supports(self) -> set[Dependable]: ... + def add_dependency(self, dependency: Dependable) -> None: ... + @abstractmethod + def set_dependencies(self, dependencies: Iterable[Dependable] | None) -> None: ... + @abstractmethod + def list_assets(self) -> set[Asset]: ... + def list_supporting(self) -> set[Dependable]: ... + +class Asset(Dependable): + resources: set[Dependable] + depends: set[Dependable] + supports: set[Dependable] + library: Library + def __init__(self, library: Library, depends: Iterable[Dependable] | None = None) -> None: ... + def set_dependencies(self, depends: Iterable[Dependable] | None) -> None: ... + def list_assets(self) -> set[Asset]: ... + +_NothingType = NewType("_NothingType", object) +NOTHING: _NothingType + +class Resource(Renderable, Asset): + relpath: str + ext: str + mode_parent: str | None + compiler: Compiler + source: str | None + minifier: Minifier + minified: Resource | None + bottom: bool + dont_bundle: bool + renderer: _Renderer + modes: dict[str, Resource] + supersedes: list[Resource] + rollups: list[Resource] + def __init__( + self, + library: Library, + relpath: str, + depends: Iterable[Dependable] | None = None, + supersedes: list[Resource] | None = None, + bottom: bool = False, + renderer: _Renderer | None = None, + debug: str | Resource | None = None, + dont_bundle: bool = False, + minified: str | Resource | None = None, + minifier: Minifier | _NothingType = ..., + compiler: Compiler | _NothingType = ..., + source: str | None = None, + mode_parent: str | None = None, + ) -> None: ... + def fullpath(self, path: str | None = None) -> str: ... + def compile(self, force: bool = False) -> None: ... + def render(self, library_url: str) -> str: ... + def mode(self, mode: str | None) -> Resource: ... + def need(self, slots: dict[Slot, Resource] | None = None) -> None: ... + +_RequiredDefaultMarkerType = NewType("_RequiredDefaultMarkerType", object) +REQUIRED_DEFAULT_MARKER: _RequiredDefaultMarkerType + +class Slot(Asset): + default: Resource | None + ext: str + required: bool + def __init__( + self, + library: Library, + extension: str, + depends: Iterable[Dependable] | None = None, + required: bool | _RequiredDefaultMarkerType = ..., + default: Resource | None = None, + ) -> None: ... + +class FilledSlot(Renderable): + filledby: Resource + library: Library + relpath: str + bottom: bool + rollups: list[Resource] + dont_bundle: bool + ext: str + order: int + renderer: _Renderer + dependency_nr: int + modes: dict[str, FilledSlot] + def __init__(self, slot: Slot, resource: Resource) -> None: ... + def render(self, library_url: str) -> str: ... + def compile(self, force: bool = False) -> None: ... + def mode(self, mode: str | None) -> FilledSlot: ... + +class Group(Dependable): + resources: set[Dependable] + depends: set[Dependable] + supports: set[Dependable] + def __init__(self, depends: Iterable[Dependable]) -> None: ... + def set_dependencies(self, depends: Iterable[Dependable]) -> None: ... # type: ignore[override] + def list_assets(self) -> set[Asset]: ... + def need(self, slots: dict[Slot, Resource] | None = None) -> None: ... + +GroupResource = Group + +class NeededResources: + def __init__( + self, + versioning: bool = False, + versioning_use_md5: bool = False, + recompute_hashes: bool = True, + base_url: str | None = None, + script_name: str | None = None, + publisher_signature: str = "fanstatic", + resources: Iterable[Dependable] | None = None, + ) -> None: ... + def has_resources(self) -> bool: ... + def has_base_url(self) -> bool: ... + def set_base_url(self, url: str) -> None: ... + def need(self, resource: Resource | Group, slots: dict[Slot, Resource] | None = None) -> None: ... + def resources(self) -> set[Resource]: ... + def clear(self) -> None: ... + def library_url(self, library: Library) -> str: ... + +class DummyNeededResources: + def need(self, resource: Resource | Group, slots: dict[Slot, Resource] | None = None) -> None: ... + def has_resources(self) -> Literal[False]: ... + +thread_local_needed_data: local + +def init_needed( + versioning: bool = False, + versioning_use_md5: bool = False, + recompute_hashes: bool = True, + base_url: str | None = None, + script_name: str | None = None, + publisher_signature: str = ..., + resources: Iterable[Dependable] | None = None, +) -> NeededResources: ... +def del_needed() -> None: ... +def get_needed() -> NeededResources | DummyNeededResources: ... +def clear_needed() -> None: ... + +class Bundle(Renderable): + def __init__(self) -> None: ... + @property + def dirname(self) -> str: ... + @property + def library(self) -> Library: ... + @property + def renderer(self) -> _Renderer: ... + @property + def ext(self) -> str: ... + @property + def relpath(self) -> str: ... + def resources(self) -> list[Resource]: ... + def render(self, library_url: str) -> str: ... + def fits(self, resource: Resource) -> bool: ... + def append(self, resource: Resource) -> None: ... + def add_to_list(self, result: list[Renderable]) -> None: ... diff --git a/stubs/fanstatic/fanstatic/inclusion.pyi b/stubs/fanstatic/fanstatic/inclusion.pyi new file mode 100644 index 000000000000..53b0076396ef --- /dev/null +++ b/stubs/fanstatic/fanstatic/inclusion.pyi @@ -0,0 +1,22 @@ +from collections.abc import Iterable + +from fanstatic.core import Bundle, NeededResources, Resource + +def bundle_resources(resources: Iterable[Resource]) -> list[Resource | Bundle]: ... +def rollup_resources(resources: Iterable[Resource]) -> set[Resource]: ... +def sort_resources(resources: Iterable[Resource]) -> list[Resource]: ... + +class Inclusion: + needed: NeededResources + resources: list[Resource | Bundle] + def __init__( + self, + needed: NeededResources, + resources: Iterable[Resource] | None = None, + compile: bool = False, + bundle: bool = False, + mode: str | None = None, + rollup: bool = False, + ) -> None: ... + def __len__(self) -> int: ... + def render(self) -> str: ... diff --git a/stubs/fanstatic/fanstatic/injector.pyi b/stubs/fanstatic/fanstatic/injector.pyi new file mode 100644 index 000000000000..5d387b99d65a --- /dev/null +++ b/stubs/fanstatic/fanstatic/injector.pyi @@ -0,0 +1,60 @@ +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from abc import abstractmethod +from collections.abc import Iterable +from typing import Any, Literal, TypedDict, type_check_only +from typing_extensions import Unpack + +from fanstatic.core import Dependable, NeededResources, Resource +from fanstatic.inclusion import Inclusion +from webob import Request, Response + +@type_check_only +class _NeededResourcesConfig(TypedDict, total=False): + versioning: bool + versioning_use_md5: bool + recompute_hashes: bool + base_url: str | None + script_name: str | None + publisher_signature: str + resources: Iterable[Dependable] | None + +@type_check_only +class _InjectorPluginOptions(TypedDict, total=False): + compile: bool + bundle: bool + rollup: bool + debug: bool + minified: bool + +@type_check_only +class _TopBottomInjectorPluginOptions(_InjectorPluginOptions, total=False): + bottom: bool + force_bottom: bool + +CONTENT_TYPES: list[str] + +class Injector: + app: WSGIApplication + config: _NeededResourcesConfig + injector: InjectorPlugin + def __init__( + self, app: WSGIApplication, injector: InjectorPlugin | None = None, **config: Unpack[_NeededResourcesConfig] + ) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +class InjectorPlugin: + @property + @abstractmethod + def name(self) -> str: ... + def __init__(self, options: _InjectorPluginOptions) -> None: ... + def make_inclusion(self, needed: NeededResources, resources: set[Resource] | None = None) -> Inclusion: ... + def __call__( + self, html: bytes, needed: NeededResources, request: Request | None = None, response: Response | None = None + ) -> None: ... + +class TopBottomInjector(InjectorPlugin): + name: Literal["topbottom"] + def __init__(self, options: _TopBottomInjectorPluginOptions) -> None: ... + def group(self, needed: NeededResources) -> tuple[Inclusion, Inclusion]: ... + +def make_injector(app: WSGIApplication, global_config: Any, **local_config: Any) -> Injector: ... diff --git a/stubs/fanstatic/fanstatic/publisher.pyi b/stubs/fanstatic/fanstatic/publisher.pyi new file mode 100644 index 000000000000..ba239c5c7e47 --- /dev/null +++ b/stubs/fanstatic/fanstatic/publisher.pyi @@ -0,0 +1,48 @@ +from _typeshed import StrOrBytesPath +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from typing import IO, Any, Literal + +from fanstatic.core import Library +from fanstatic.registry import LibraryRegistry +from webob import Request, Response +from webob.dec import wsgify +from webob.static import DirectoryApp, FileApp + +MINUTE_IN_SECONDS: Literal[60] +HOUR_IN_SECONDS: Literal[3600] +DAY_IN_SECONDS: Literal[86400] +YEAR_IN_SECONDS: int +FOREVER: int + +class BundleApp(FileApp): + filenames: list[str] + def __init__(self, rootpath: str, bundle: IO[bytes], filenames: Iterable[StrOrBytesPath]) -> None: ... + @wsgify + def __call__(self, req: Request) -> Response: ... + +class LibraryPublisher(DirectoryApp): + ignores: list[str] + library: Library + cached_apps: dict[str, FileApp] + def __init__(self, library: Library) -> None: ... + @wsgify + def __call__(self, req: Request) -> Response: ... + +class Publisher: + registry: LibraryRegistry + directory_publishers: dict[str, LibraryPublisher] + def __init__(self, registry: LibraryRegistry) -> None: ... + @wsgify + def __call__(self, request: Request) -> Response: ... + +class Delegator: + app: WSGIApplication + publisher: Publisher + publisher_signature: str + trigger: str + def __init__(self, app: WSGIApplication, publisher: Publisher, publisher_signature: str = "fanstatic") -> None: ... + def is_resource(self, request: Request) -> bool: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +def make_publisher(global_config: Any) -> Publisher: ... diff --git a/stubs/fanstatic/fanstatic/registry.pyi b/stubs/fanstatic/fanstatic/registry.pyi new file mode 100644 index 000000000000..c0a78589feea --- /dev/null +++ b/stubs/fanstatic/fanstatic/registry.pyi @@ -0,0 +1,50 @@ +from abc import abstractmethod +from collections.abc import Iterable +from threading import Lock +from typing import Any, ClassVar, Literal, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from fanstatic.compiler import Compiler, Minifier +from fanstatic.core import Library +from fanstatic.injector import InjectorPlugin + +# Used to be pkg_resources.EntryPoint, but any EntryPoint-like class with a `load` method works +@type_check_only +class _EntryPoint(Protocol): + def load(self) -> Any: ... # Can be any attribute in the module + +@type_check_only +class _HasName(Protocol): + @property + def name(self) -> str: ... + +_NamedT = TypeVar("_NamedT", bound=_HasName) + +prepare_lock: Lock + +class Registry(dict[str, _NamedT]): + @property + @abstractmethod + def ENTRY_POINT(self) -> str: ... + def __init__(self, items: Iterable[_NamedT] = ()) -> None: ... + def add(self, item: _NamedT) -> None: ... + def load_items_from_entry_points(self) -> None: ... + def make_item_from_entry_point(self, entry_point: _EntryPoint) -> Any: ... + @classmethod + def instance(cls) -> Self: ... + +class LibraryRegistry(Registry[Library]): + ENTRY_POINT: ClassVar[Literal["fanstatic.libraries"]] + prepared: bool + def prepare(self) -> None: ... + +get_library_registry = LibraryRegistry.instance + +class CompilerRegistry(Registry[Compiler]): + ENTRY_POINT: ClassVar[Literal["fanstatic.compilers"]] + +class MinifierRegistry(Registry[Minifier]): + ENTRY_POINT: ClassVar[Literal["fanstatic.minifiers"]] + +class InjectorRegistry(Registry[InjectorPlugin]): + ENTRY_POINT: ClassVar[Literal["fanstatic.injectors"]] diff --git a/stubs/fanstatic/fanstatic/wsgi.pyi b/stubs/fanstatic/fanstatic/wsgi.pyi new file mode 100644 index 000000000000..bd0859b091d3 --- /dev/null +++ b/stubs/fanstatic/fanstatic/wsgi.pyi @@ -0,0 +1,22 @@ +from _typeshed.wsgi import WSGIApplication +from typing import Any + +from fanstatic.core import Resource +from fanstatic.injector import InjectorPlugin +from fanstatic.publisher import Delegator +from webob import Request, Response +from webob.dec import wsgify + +def Fanstatic( + app: WSGIApplication, publisher_signature: str = "fanstatic", injector: InjectorPlugin | None = None, **config: Any +) -> Delegator: ... +def make_fanstatic(app: WSGIApplication, global_config: Any, **local_config: Any) -> Delegator: ... + +class Serf: + resource: Resource + def __init__(self, resource: Resource) -> None: ... + @wsgify + def __call__(self, request: Request) -> Response: ... + +def make_serf(global_config: Any, **local_config: Any) -> Serf: ... +def resolve(name: str, module: str | None = None) -> Any: ... diff --git a/stubs/filelock/METADATA.toml b/stubs/filelock/METADATA.toml deleted file mode 100644 index 38c94680a9a8..000000000000 --- a/stubs/filelock/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "3.2.*" diff --git a/stubs/filelock/filelock/__init__.pyi b/stubs/filelock/filelock/__init__.pyi deleted file mode 100644 index e10860f893ee..000000000000 --- a/stubs/filelock/filelock/__init__.pyi +++ /dev/null @@ -1,51 +0,0 @@ -import sys -from types import TracebackType -from typing import Type - -class Timeout(TimeoutError): - def __init__(self, lock_file: str) -> None: ... - def __str__(self) -> str: ... - -class _Acquire_ReturnProxy: - def __init__(self, lock: str) -> None: ... - def __enter__(self) -> str: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, traceback: TracebackType | None - ) -> None: ... - -class BaseFileLock: - def __init__(self, lock_file: str, timeout: float | int | str = ...) -> None: ... - @property - def lock_file(self) -> str: ... - @property - def timeout(self) -> float: ... - @timeout.setter - def timeout(self, value: int | str | float) -> None: ... # type: ignore - @property - def is_locked(self) -> bool: ... - def acquire(self, timeout: float | None = ..., poll_intervall: float = ...) -> _Acquire_ReturnProxy: ... - def release(self, force: bool = ...) -> None: ... - def __enter__(self) -> BaseFileLock: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, traceback: TracebackType | None - ) -> None: ... - def __del__(self) -> None: ... - -class WindowsFileLock(BaseFileLock): - def _acquire(self) -> None: ... - def _release(self) -> None: ... - -class UnixFileLock(BaseFileLock): - def _acquire(self) -> None: ... - def _release(self) -> None: ... - -class SoftFileLock(BaseFileLock): - def _acquire(self) -> None: ... - def _release(self) -> None: ... - -if sys.platform == "win32": - FileLock = WindowsFileLock -elif sys.platform == "linux" or sys.platform == "darwin": - FileLock = UnixFileLock -else: - FileLock = SoftFileLock diff --git a/stubs/first/METADATA.toml b/stubs/first/METADATA.toml index 72294377102c..3fe3d66bda4d 100644 --- a/stubs/first/METADATA.toml +++ b/stubs/first/METADATA.toml @@ -1,2 +1,2 @@ version = "2.0.*" -python2 = true +upstream-repository = "https://github.com/hynek/first" diff --git a/stubs/first/first.pyi b/stubs/first/first.pyi index 2306d521be3c..17fe072b2fe0 100644 --- a/stubs/first/first.pyi +++ b/stubs/first/first.pyi @@ -1,8 +1,12 @@ -from typing import Any, Callable, Iterable, TypeVar, overload +from collections.abc import Callable, Iterable +from typing import Any, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") +__license__: str +__title__: str + @overload def first(iterable: Iterable[_T]) -> _T | None: ... @overload @@ -10,4 +14,6 @@ def first(iterable: Iterable[_T], default: _S) -> _T | _S: ... @overload def first(iterable: Iterable[_T], default: _S, key: Callable[[_T], Any] | None) -> _T | _S: ... @overload +def first(iterable: Iterable[_T], default: None, key: Callable[[_T], Any] | None) -> _T | None: ... +@overload def first(iterable: Iterable[_T], *, key: Callable[[_T], Any] | None) -> _T | None: ... diff --git a/stubs/flake8-2020/METADATA.toml b/stubs/flake8-2020/METADATA.toml deleted file mode 100644 index 6cf9fae44d92..000000000000 --- a/stubs/flake8-2020/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "1.6.*" diff --git a/stubs/flake8-2020/flake8_2020.pyi b/stubs/flake8-2020/flake8_2020.pyi deleted file mode 100644 index 3577b66a6d12..000000000000 --- a/stubs/flake8-2020/flake8_2020.pyi +++ /dev/null @@ -1,14 +0,0 @@ -# flake8-2020 has type annotations, but PEP 561 states: -# This PEP does not support distributing typing information as part of module-only distributions or single-file modules within namespace packages. -# Therefore typeshed is the best place. - -import ast -from typing import Any, ClassVar, Generator, Type - -class Plugin: - name: ClassVar[str] - version: ClassVar[str] - def __init__(self, tree: ast.AST) -> None: ... - def run(self) -> Generator[tuple[int, int, str, Type[Any]], None, None]: ... - -def __getattr__(name: str) -> Any: ... # incomplete (other attributes are normally not accessed) diff --git a/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt b/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt index 82f069091409..206909ae98a0 100644 --- a/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt +++ b/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt @@ -1 +1,39 @@ -bugbear.BugBearChecker.__getattr__ +# Autogenerated methods using @attr.* decorators +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_props__ +bugbear.B040CaughtException.__match_args__ +bugbear.B041VariableKeyType.__match_args__ +bugbear.BugBearChecker.__ge__ +bugbear.BugBearChecker.__gt__ +bugbear.BugBearChecker.__le__ +bugbear.BugBearChecker.__lt__ +bugbear.BugBearChecker.__match_args__ +bugbear.BugBearVisitor.__ge__ +bugbear.BugBearVisitor.__gt__ +bugbear.BugBearVisitor.__le__ +bugbear.BugBearVisitor.__lt__ +bugbear.BugBearVisitor.__match_args__ +bugbear.NameFinder.__ge__ +bugbear.NameFinder.__gt__ +bugbear.NameFinder.__le__ +bugbear.NameFinder.__lt__ +bugbear.NameFinder.__match_args__ +bugbear.NamedExprFinder.__ge__ +bugbear.NamedExprFinder.__gt__ +bugbear.NamedExprFinder.__le__ +bugbear.NamedExprFinder.__lt__ +bugbear.NamedExprFinder.__match_args__ +bugbear.B020AttributeFinder.__ge__ +bugbear.B020AttributeFinder.__gt__ +bugbear.B020AttributeFinder.__le__ +bugbear.B020AttributeFinder.__lt__ +bugbear.B020AttributeFinder.__match_args__ +# == Python 3.13 +bugbear.B040CaughtException.__replace__ +bugbear.B041VariableKeyType.__replace__ +bugbear.BugBearChecker.__replace__ +bugbear.BugBearVisitor.__replace__ +bugbear.NameFinder.__replace__ +bugbear.NamedExprFinder.__replace__ +bugbear.B020AttributeFinder.__replace__ diff --git a/stubs/flake8-bugbear/METADATA.toml b/stubs/flake8-bugbear/METADATA.toml index 4965db3af595..24784d426395 100644 --- a/stubs/flake8-bugbear/METADATA.toml +++ b/stubs/flake8-bugbear/METADATA.toml @@ -1 +1,2 @@ -version = "21.11.29" +version = "26.9.9" +upstream-repository = "https://github.com/PyCQA/flake8-bugbear" diff --git a/stubs/flake8-bugbear/bugbear.pyi b/stubs/flake8-bugbear/bugbear.pyi index b435e5bcecda..e10209b6d987 100644 --- a/stubs/flake8-bugbear/bugbear.pyi +++ b/stubs/flake8-bugbear/bugbear.pyi @@ -1,17 +1,37 @@ import argparse import ast -from typing import Any, Sequence +import sys +from collections.abc import Generator, Iterable, Sequence +from logging import Logger +from typing import Any, ClassVar, Final, Literal, NamedTuple, Protocol, overload + +__version__: Final[str] +LOG: Logger +CONTEXTFUL_NODES: Final[tuple[type[ast.AST], ...]] +FUNCTION_NODES: Final[tuple[type[ast.AST], ...]] +FUNCTIONS_WITHOUT_SIDE_EFFECTS: Final[tuple[str, ...]] +B908_pytest_functions: Final[set[str]] +B908_unittest_methods: Final[set[str]] +B902_default_decorators: Final[set[str]] + +class Context(NamedTuple): + node: ast.AST + stack: list[ast.AST] class BugBearChecker: - name: str - version: str + name: ClassVar[str] + version: ClassVar[str] tree: ast.AST | None filename: str lines: Sequence[str] | None max_line_length: int visitor: ast.NodeVisitor options: argparse.Namespace | None - def run(self) -> None: ... + def run(self) -> Iterable[tuple[int, int, str, type[BugBearChecker]]]: ... + def gen_line_based_checks(self) -> Generator[error]: ... + @classmethod + def adapt_error(cls, e: error) -> tuple[int, int, str, type[BugBearChecker]]: ... + def load_file(self) -> None: ... @staticmethod def add_options(optmanager: Any) -> None: ... def __init__( @@ -22,6 +42,245 @@ class BugBearChecker: max_line_length: int = ..., options: argparse.Namespace | None = ..., ) -> None: ... - def __getattr__(self, name: str) -> Any: ... # incomplete (other attributes are normally not accessed) + def should_warn(self, code: str) -> bool: ... + +def names_from_assignments(assign_target: ast.expr) -> Generator[str]: ... +def children_in_scope(node: ast.AST) -> Generator[ast.AST]: ... + +class ExceptBaseExceptionVisitor(ast.NodeVisitor): + root: ast.ExceptHandler + def __init__(self, except_node: ast.ExceptHandler) -> None: ... + def re_raised(self) -> bool: ... + def visit_Raise(self, node: ast.Raise) -> None: ... + def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: ... + +class B040CaughtException: + name: str + has_note: bool + def __init__(self, name: str, has_note: bool) -> None: ... + +class B041UnhandledKeyType: ... + +class B041VariableKeyType: + name: str + def __init__(self, name: str) -> None: ... + +class AstPositionNode(Protocol): + lineno: int + col_offset: int + +class BugBearVisitor(ast.NodeVisitor): + filename: str + lines: Sequence[str] | None + b008_b039_extend_immutable_calls: set[str] + b902_classmethod_decorators: set[str] + node_window: list[ast.AST] + errors: list[error] + contexts: list[Context] + b040_caught_exception: B040CaughtException | None + NODE_WINDOW_SIZE: ClassVar[int] = 4 + in_trystar: str + def __init__( + self, + filename: str, + lines: Sequence[str] | None, + b008_b039_extend_immutable_calls: set[str] = ..., + b902_classmethod_decorators: set[str] = ..., + node_window: list[ast.AST] = ..., + errors: list[error] = ..., + contexts: list[Context] = ..., + b040_caught_exception: B040CaughtException | None = None, + in_trystar: str = "", + ) -> None: ... + def add_error(self, code: str, node: AstPositionNode, *vars: object) -> None: ... + @property + def node_stack(self) -> list[ast.AST]: ... + def in_class_init(self) -> bool: ... + def visit_Return(self, node: ast.Return) -> None: ... + def visit_Yield(self, node: ast.Yield) -> None: ... + def visit_YieldFrom(self, node: ast.YieldFrom) -> None: ... + def visit(self, node: ast.AST) -> None: ... + def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: ... + def visit_UAdd(self, node: ast.UAdd) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_Module(self, node: ast.Module) -> None: ... + def visit_Assign(self, node: ast.Assign) -> None: ... + def visit_For(self, node: ast.For) -> None: ... + def visit_AsyncFor(self, node: ast.AsyncFor) -> None: ... + def visit_While(self, node: ast.While) -> None: ... + def visit_ListComp(self, node: ast.ListComp) -> None: ... + def visit_SetComp(self, node: ast.SetComp) -> None: ... + def visit_DictComp(self, node: ast.DictComp) -> None: ... + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: ... + def visit_Assert(self, node: ast.Assert) -> None: ... + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: ... + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: ... + def visit_ClassDef(self, node: ast.ClassDef) -> None: ... + if sys.version_info >= (3, 11): + def visit_Try(self, node: ast.Try | ast.TryStar) -> None: ... + def visit_TryStar(self, node: ast.TryStar) -> None: ... + else: + def visit_Try(self, node: ast.Try) -> None: ... + def visit_TryStar(self, node: ast.Try) -> None: ... + + def visit_Compare(self, node: ast.Compare) -> None: ... + def visit_Raise(self, node: ast.Raise) -> None: ... + def visit_With(self, node: ast.With) -> None: ... + def visit_JoinedStr(self, node: ast.JoinedStr) -> None: ... + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: ... + def visit_Import(self, node: ast.Import) -> None: ... + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: ... + def visit_Set(self, node: ast.Set) -> None: ... + def visit_Dict(self, node: ast.Dict) -> None: ... + def check_for_b041(self, node: ast.Dict) -> None: ... + def check_for_b005(self, node: ast.Import | ast.ImportFrom | ast.Call) -> None: ... + def check_for_b006_and_b008(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + def check_for_b039(self, node: ast.Call) -> None: ... + def check_for_b007(self, node: ast.For | ast.AsyncFor) -> None: ... + def check_for_b011(self, node: ast.Assert) -> None: ... + if sys.version_info >= (3, 11): + def check_for_b012(self, node: ast.Try | ast.TryStar) -> None: ... + else: + def check_for_b012(self, node: ast.Try) -> None: ... + + def check_for_b013_b014_b029_b030(self, node: ast.ExceptHandler) -> list[str]: ... + def check_for_b015(self, node: ast.Compare) -> None: ... + def check_for_b016(self, node: ast.Raise) -> None: ... + def check_for_b017(self, node: ast.With | ast.AsyncWith) -> None: ... + def check_for_b019(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + def check_for_b020(self, node: ast.For | ast.AsyncFor | ast.comprehension) -> None: ... + def check_for_b023( + self, loop_node: ast.For | ast.AsyncFor | ast.While | ast.GeneratorExp | ast.SetComp | ast.ListComp | ast.DictComp + ) -> None: ... + def check_for_b024_and_b027(self, node: ast.ClassDef) -> None: ... + def check_for_b026(self, call: ast.Call) -> None: ... + def check_for_b031(self, loop_node: ast.For | ast.AsyncFor) -> None: ... + def check_for_b035(self, node: ast.DictComp) -> None: ... + def check_for_b040_add_note(self, node: ast.Attribute) -> bool: ... + def check_for_b040_usage(self, node: ast.expr | list[ast.expr] | list[ast.keyword] | None) -> None: ... + def check_for_b904(self, node: ast.Raise) -> None: ... + def walk_function_body( + self, node: ast.FunctionDef | ast.AsyncFunctionDef + ) -> Generator[tuple[ast.FunctionDef | ast.AsyncFunctionDef, ast.stmt]]: ... + def check_for_b901(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + + @overload + @classmethod + def find_decorator_name(cls, d: ast.Name | ast.Attribute | ast.Call) -> str: ... + @overload + @classmethod + def find_decorator_name(cls, d: ast.AST) -> str | None: ... + + def check_for_b902(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + def check_for_b903(self, node: ast.ClassDef) -> None: ... + def check_for_b018(self, node: ast.AST) -> None: ... + def check_for_b021(self, node: ast.AsyncFunctionDef | ast.FunctionDef | ast.ClassDef | ast.Module) -> None: ... + def check_for_b022(self, node: ast.With | ast.AsyncWith) -> None: ... + def check_for_b908(self, node: ast.With) -> None: ... + if sys.version_info >= (3, 11): + def check_for_b025(self, node: ast.Try | ast.TryStar) -> None: ... + else: + def check_for_b025(self, node: ast.Try) -> None: ... + + def check_for_b905(self, node: ast.Call) -> None: ... + def check_for_b912(self, node: ast.Call) -> None: ... + def check_for_b913(self, node: ast.For) -> None: ... + def check_for_b906(self, node: ast.FunctionDef) -> None: ... + def check_for_b907(self, node: ast.JoinedStr) -> None: ... + def check_for_b028(self, node: ast.Call) -> None: ... + def check_for_b032(self, node: ast.AnnAssign) -> None: ... + def check_for_b033(self, node: ast.Set) -> None: ... + def check_for_b034(self, node: ast.Call) -> None: ... + def check_for_b042(self, node: ast.ClassDef) -> None: ... + def check_for_b044(self, node: ast.Assert) -> None: ... + def check_for_b909(self, node: ast.For) -> None: ... + def check_for_b910(self, node: ast.Call) -> None: ... + def check_for_b911(self, node: ast.Call) -> None: ... + +def compose_call_path(node: ast.expr) -> Generator[str]: ... +def is_name(node: ast.expr, name: str) -> bool: ... + +class B909Checker(ast.NodeVisitor): + MUTATING_FUNCTIONS: ClassVar[tuple[str, ...]] + name: str + key: str + mutations: dict[int, list[ast.Assign | ast.AugAssign | ast.Delete | ast.Call]] + def __init__(self, name: str, key: str) -> None: ... + def visit_Assign(self, node: ast.Assign) -> None: ... + def visit_AugAssign(self, node: ast.AugAssign) -> None: ... + def visit_Delete(self, node: ast.Delete) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_If(self, node: ast.If) -> None: ... + def visit(self, node: ast.AST | list[ast.stmt]) -> Any: ... + +class NameFinder(ast.NodeVisitor): + names: dict[str, list[ast.Name]] + def __init__(self, names: dict[str, list[ast.Name]] = ...) -> None: ... + def visit_Name(self, node: ast.Name) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> Any: ... + +class B913UsageFinder(NameFinder): + def visit_Name(self, node: ast.Name) -> None: ... + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: ... + def visit_ListComp(self, node: ast.ListComp) -> None: ... + def visit_SetComp(self, node: ast.SetComp) -> None: ... + def visit_DictComp(self, node: ast.DictComp) -> None: ... + def visit_AugAssign(self, node: ast.AugAssign) -> None: ... + +class NamedExprFinder(ast.NodeVisitor): + names: dict[str, list[ast.Name]] + def __init__(self, names: dict[str, list[ast.Name]] = ...) -> None: ... + def visit_NamedExpr(self, node: ast.NamedExpr) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> Any: ... + +class FunctionDefDefaultsVisitor(ast.NodeVisitor): + def __init__( + self, error_code_calls: Error, error_code_literals: Error, b008_b039_extend_immutable_calls: set[str] | None = None + ) -> None: ... + def visit_mutable_literal_or_comprehension( + self, node: ast.List | ast.Dict | ast.Set | ast.ListComp | ast.DictComp | ast.SetComp + ) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_Lambda(self, node: ast.Lambda) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> None: ... + +class B020NameFinder(NameFinder): + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: ... + def visit_ListComp(self, node: ast.ListComp) -> None: ... + def visit_DictComp(self, node: ast.DictComp) -> None: ... + def visit_comprehension(self, node: ast.comprehension) -> None: ... + def visit_Lambda(self, node: ast.Lambda) -> None: ... + +class B020AttributeFinder(B020NameFinder): + paths: set[str] + def __init__(self, names: dict[str, list[ast.Name]] = ..., paths: set[str] = ...) -> None: ... + def visit_Attribute(self, node: ast.Attribute) -> None: ... + def visit_Lambda(self, node: ast.Lambda) -> None: ... + +B005_METHODS: Final[set[str]] +B006_MUTABLE_LITERALS: Final[tuple[Literal["Dict"], Literal["List"], Literal["Set"]]] +B006_MUTABLE_COMPREHENSIONS: Final[tuple[Literal["ListComp"], Literal["DictComp"], Literal["SetComp"]]] +B006_MUTABLE_CALLS: Final[set[str]] +B008_IMMUTABLE_CALLS: Final[set[str]] +B014_REDUNDANT_EXCEPTIONS: Final[dict[Literal["OSError", "ValueError"], set[str]]] +B019_CACHES: Final[set[str]] +B902_IMPLICIT_CLASSMETHODS: Final[set[str]] +B902_SELF: Final[list[str]] +B902_CLS: Final[list[str]] +B902_METACLS: Final[list[str]] + +class error(NamedTuple): + lineno: int + col: int + message: str + type: type[BugBearChecker] + # Arguments for formatting the message, i.e. message.format(*vars). + vars: tuple[object, ...] + +class Error: + message: str + def __init__(self, message: str) -> None: ... + def __call__(self, lineno: int, col: int, vars: tuple[object, ...] = ()) -> error: ... -def __getattr__(name: str) -> Any: ... # incomplete (other attributes are normally not accessed) +error_codes: Final[dict[str, Error]] +disabled_by_default: Final[list[str]] diff --git a/stubs/flake8-builtins/METADATA.toml b/stubs/flake8-builtins/METADATA.toml index 97ceca8aa9f5..5f4f23a38df6 100644 --- a/stubs/flake8-builtins/METADATA.toml +++ b/stubs/flake8-builtins/METADATA.toml @@ -1 +1,3 @@ -version = "1.5.*" +version = "3.1.*" +upstream-repository = "https://github.com/gforcada/flake8-builtins" +dependencies = ["types-flake8"] diff --git a/stubs/flake8-builtins/flake8_builtins.pyi b/stubs/flake8-builtins/flake8_builtins.pyi index e5a3d89c5f11..9e80c36dc14a 100644 --- a/stubs/flake8-builtins/flake8_builtins.pyi +++ b/stubs/flake8-builtins/flake8_builtins.pyi @@ -1,10 +1,45 @@ import ast -from typing import Any, ClassVar, Generator, Type +from argparse import Namespace +from collections.abc import Iterator +from typing import ClassVar, TypeAlias + +from flake8.options.manager import OptionManager + +_Error: TypeAlias = tuple[int, int, str, type[BuiltinsChecker]] class BuiltinsChecker: name: ClassVar[str] version: ClassVar[str] - def __init__(self, tree: ast.AST, filename: str) -> None: ... - def run(self) -> Generator[tuple[int, int, str, Type[Any]], None, None]: ... + assign_msg: ClassVar[str] + argument_msg: ClassVar[str] + class_attribute_msg: ClassVar[str] + import_msg: ClassVar[str] + module_name_msg: ClassVar[str] + lambda_argument_msg: ClassVar[str] -def __getattr__(name: str) -> Any: ... # incomplete (other attributes are normally not accessed) + default_line_number: ClassVar[int] + default_column_offset: ClassVar[int] + + names: ClassVar[list[str]] + ignore_list: ClassVar[set[str]] + ignored_module_names: ClassVar[set[str]] + + def __init__(self, tree: ast.AST, filename: str) -> None: ... + @classmethod + def add_options(cls, option_manager: OptionManager) -> None: ... + @classmethod + def parse_options(cls, options: Namespace) -> None: ... + def run(self) -> Iterator[_Error]: ... + def check_assignment(self, statement: ast.Assign | ast.AnnAssign | ast.NamedExpr) -> Iterator[_Error]: ... + def check_function_definition(self, statement: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[_Error]: ... + def check_lambda_definition(self, statement: ast.Lambda) -> Iterator[_Error]: ... + def check_for_loop(self, statement: ast.For | ast.AsyncFor) -> Iterator[_Error]: ... + def check_with(self, statement: ast.With | ast.AsyncWith) -> Iterator[_Error]: ... + def check_exception(self, statement: ast.excepthandler) -> Iterator[_Error]: ... + def check_comprehension( + self, statement: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp + ) -> Iterator[_Error]: ... + def check_import(self, statement: ast.Import | ast.ImportFrom) -> Iterator[_Error]: ... + def check_class(self, statement: ast.ClassDef) -> Iterator[_Error]: ... + def error(self, statement: ast.AST | None = None, variable: str | None = None, message: str | None = None) -> _Error: ... + def check_module_name(self, filename: str) -> Iterator[_Error]: ... diff --git a/stubs/flake8-docstrings/METADATA.toml b/stubs/flake8-docstrings/METADATA.toml index 6cf9fae44d92..201a2cb77311 100644 --- a/stubs/flake8-docstrings/METADATA.toml +++ b/stubs/flake8-docstrings/METADATA.toml @@ -1 +1,3 @@ -version = "1.6.*" +version = "1.7.*" +upstream-repository = "https://github.com/pycqa/flake8-docstrings" +dependencies = ["types-flake8"] diff --git a/stubs/flake8-docstrings/flake8_docstrings.pyi b/stubs/flake8-docstrings/flake8_docstrings.pyi index bd8621cfec95..0c9f9344a561 100644 --- a/stubs/flake8-docstrings/flake8_docstrings.pyi +++ b/stubs/flake8-docstrings/flake8_docstrings.pyi @@ -1,19 +1,24 @@ import argparse import ast -from typing import Any, ClassVar, Generator, Iterable, Type +from collections.abc import Generator, Iterable +from typing import Any, ClassVar, Final, Literal +from typing_extensions import Self + +from flake8.options.manager import OptionManager + +__version__: Final[str] +__all__ = ("pep257Checker",) class pep257Checker: name: ClassVar[str] version: ClassVar[str] tree: ast.AST filename: str - checker: Any + checker: Any # actual type: pep257.ConventionChecker source: str def __init__(self, tree: ast.AST, filename: str, lines: Iterable[str]) -> None: ... @classmethod - def add_options(cls, parser: Any) -> None: ... + def add_options(cls, parser: OptionManager) -> None: ... @classmethod def parse_options(cls, options: argparse.Namespace) -> None: ... - def run(self) -> Generator[tuple[int, int, str, Type[Any]], None, None]: ... - -def __getattr__(name: str) -> Any: ... # incomplete + def run(self) -> Generator[tuple[int, Literal[0], str, type[Self]]]: ... diff --git a/stubs/flake8-plugin-utils/@tests/stubtest_allowlist.txt b/stubs/flake8-plugin-utils/@tests/stubtest_allowlist.txt deleted file mode 100644 index c458a54104da..000000000000 --- a/stubs/flake8-plugin-utils/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,6 +0,0 @@ -flake8_plugin_utils -flake8_plugin_utils.plugin -flake8_plugin_utils.utils -flake8_plugin_utils.utils.assertions -flake8_plugin_utils.utils.constants -flake8_plugin_utils.utils.equiv_nodes diff --git a/stubs/flake8-plugin-utils/METADATA.toml b/stubs/flake8-plugin-utils/METADATA.toml deleted file mode 100644 index 3ea18392d7df..000000000000 --- a/stubs/flake8-plugin-utils/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "1.3.*" diff --git a/stubs/flake8-plugin-utils/flake8_plugin_utils/__init__.pyi b/stubs/flake8-plugin-utils/flake8_plugin_utils/__init__.pyi deleted file mode 100644 index 0c3f4bced581..000000000000 --- a/stubs/flake8-plugin-utils/flake8_plugin_utils/__init__.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from .plugin import Error as Error, Plugin as Plugin, Visitor as Visitor -from .utils import ( - assert_error as assert_error, - assert_not_error as assert_not_error, - check_equivalent_nodes as check_equivalent_nodes, - is_false as is_false, - is_none as is_none, - is_true as is_true, -) diff --git a/stubs/flake8-plugin-utils/flake8_plugin_utils/plugin.pyi b/stubs/flake8-plugin-utils/flake8_plugin_utils/plugin.pyi deleted file mode 100644 index 066a43e538c5..000000000000 --- a/stubs/flake8-plugin-utils/flake8_plugin_utils/plugin.pyi +++ /dev/null @@ -1,36 +0,0 @@ -import argparse -import ast -from typing import Any, Generic, Iterable, Iterator, Tuple, Type, TypeVar - -FLAKE8_ERROR = Tuple[int, int, str, Type[Any]] -TConfig = TypeVar("TConfig") # noqa: Y001 - -class Error: - code: str - message: str - lineno: int - col_offset: int - def __init__(self, lineno: int, col_offset: int, **kwargs: Any) -> None: ... - @classmethod - def formatted_message(cls, **kwargs: Any) -> str: ... - -class Visitor(ast.NodeVisitor, Generic[TConfig]): - errors: list[Error] - def __init__(self, config: TConfig | None = ...) -> None: ... - @property - def config(self) -> TConfig: ... - def error_from_node(self, error: Type[Error], node: ast.AST, **kwargs: Any) -> None: ... - -class Plugin(Generic[TConfig]): - name: str - version: str - visitors: list[Type[Visitor[TConfig]]] - config: TConfig - def __init__(self, tree: ast.AST) -> None: ... - def run(self) -> Iterable[FLAKE8_ERROR]: ... - @classmethod - def parse_options(cls, option_manager: Any, options: argparse.Namespace, args: list[str]) -> None: ... - @classmethod - def parse_options_to_config(cls, option_manager: Any, options: argparse.Namespace, args: list[str]) -> TConfig | None: ... - @classmethod - def test_config(cls, config: TConfig) -> Iterator[None]: ... diff --git a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/__init__.pyi b/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/__init__.pyi deleted file mode 100644 index 095dbe4c7283..000000000000 --- a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from .assertions import assert_error as assert_error, assert_not_error as assert_not_error -from .constants import is_false as is_false, is_none as is_none, is_true as is_true -from .equiv_nodes import check_equivalent_nodes as check_equivalent_nodes diff --git a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/assertions.pyi b/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/assertions.pyi deleted file mode 100644 index 2bd61dd8409c..000000000000 --- a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/assertions.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any, Type - -from ..plugin import Error as Error, TConfig as TConfig, Visitor as Visitor - -def assert_error( - visitor_cls: Type[Visitor[TConfig]], src: str, expected: Type[Error], config: TConfig | None = ..., **kwargs: Any -) -> None: ... -def assert_not_error(visitor_cls: Type[Visitor[TConfig]], src: str, config: TConfig | None = ...) -> None: ... diff --git a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/constants.pyi b/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/constants.pyi deleted file mode 100644 index 8503693c6f3e..000000000000 --- a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/constants.pyi +++ /dev/null @@ -1,5 +0,0 @@ -import ast - -def is_none(node: ast.AST) -> bool: ... -def is_false(node: ast.AST) -> bool: ... -def is_true(node: ast.AST) -> bool: ... diff --git a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/equiv_nodes.pyi b/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/equiv_nodes.pyi deleted file mode 100644 index 641945b106b9..000000000000 --- a/stubs/flake8-plugin-utils/flake8_plugin_utils/utils/equiv_nodes.pyi +++ /dev/null @@ -1,3 +0,0 @@ -import ast - -def check_equivalent_nodes(node1: ast.AST, node2: ast.AST) -> bool: ... diff --git a/stubs/flake8-rst-docstrings/METADATA.toml b/stubs/flake8-rst-docstrings/METADATA.toml new file mode 100644 index 000000000000..f8912d7c9e35 --- /dev/null +++ b/stubs/flake8-rst-docstrings/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.4.*" +upstream-repository = "https://github.com/peterjc/flake8-rst-docstrings" diff --git a/stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi b/stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi new file mode 100644 index 000000000000..b04ae53ef63b --- /dev/null +++ b/stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi @@ -0,0 +1,34 @@ +import ast +from argparse import Namespace +from collections.abc import Container, Generator +from typing import Any + +rst_prefix: str +rst_fail_load: int +rst_fail_lint: int +code_mapping_info: dict[str, int] +code_mapping_warning: dict[str, int] +code_mapping_error: dict[str, int] +code_mapping_severe: dict[str, int] +code_mappings_by_level: dict[int, dict[str, int]] + +def code_mapping( + level: int, + msg: str, + extra_directives: Container[str], + extra_roles: Container[str], + extra_substitutions: Container[str], + default: int = ..., +) -> int: ... + +class reStructuredTextChecker: + name: str + version: str + tree: ast.AST + filename: str + def __init__(self, tree: ast.AST, filename: str = ...) -> None: ... + @classmethod + def add_options(cls, parser: Any) -> None: ... + @classmethod + def parse_options(cls, options: Namespace) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[reStructuredTextChecker]]]: ... diff --git a/stubs/flake8-simplify/METADATA.toml b/stubs/flake8-simplify/METADATA.toml index c562b663336b..5ef28e476ab3 100644 --- a/stubs/flake8-simplify/METADATA.toml +++ b/stubs/flake8-simplify/METADATA.toml @@ -1 +1,2 @@ -version = "0.14.*" +version = "0.30.*" +upstream-repository = "https://github.com/MartinThoma/flake8-simplify" diff --git a/stubs/flake8-simplify/flake8_simplify.pyi b/stubs/flake8-simplify/flake8_simplify.pyi deleted file mode 100644 index 0d5e35b60672..000000000000 --- a/stubs/flake8-simplify/flake8_simplify.pyi +++ /dev/null @@ -1,8 +0,0 @@ -import ast -from typing import Any, ClassVar, Generator, Type - -class Plugin: - name: ClassVar[str] - version: ClassVar[str] - def __init__(self, tree: ast.AST) -> None: ... - def run(self) -> Generator[tuple[int, int, str, Type[Any]], None, None]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/__init__.pyi b/stubs/flake8-simplify/flake8_simplify/__init__.pyi new file mode 100644 index 000000000000..161c2bf90499 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/__init__.pyi @@ -0,0 +1,31 @@ +import ast +import logging +from collections.abc import Generator +from typing import Any, ClassVar + +logger: logging.Logger + +class Visitor(ast.NodeVisitor): + errors: list[tuple[int, int, str]] + def __init__(self) -> None: ... + def visit_Assign(self, node: ast.Assign) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_With(self, node: ast.With) -> None: ... + def visit_Expr(self, node: ast.Expr) -> None: ... + def visit_BoolOp(self, node: ast.BoolOp) -> None: ... + def visit_If(self, node: ast.If) -> None: ... + def visit_For(self, node: ast.For) -> None: ... + def visit_Subscript(self, node: ast.Subscript) -> None: ... + def visit_Try(self, node: ast.Try) -> None: ... + def visit_UnaryOp(self, node_v: ast.UnaryOp) -> None: ... + def visit_IfExp(self, node: ast.IfExp) -> None: ... + def visit_Compare(self, node: ast.Compare) -> None: ... + def visit_ClassDef(self, node: ast.ClassDef) -> None: ... + +class Plugin: + name: ClassVar[str] + version: ClassVar[str] + def __init__(self, tree: ast.AST) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[Any]]]: ... + +def add_meta(root: ast.AST, level: int = 0) -> None: ... diff --git a/stubs/flake8-simplify/flake8_simplify/constants.pyi b/stubs/flake8-simplify/flake8_simplify/constants.pyi new file mode 100644 index 000000000000..58254db7068f --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/constants.pyi @@ -0,0 +1,6 @@ +import ast +from typing import Final + +BOOL_CONST_TYPES: Final[tuple[type[ast.Constant]]] +AST_CONST_TYPES: Final[tuple[type[ast.Constant]]] +STR_TYPES: Final[tuple[type[ast.Constant]]] diff --git a/stubs/selenium/selenium/webdriver/remote/__init__.pyi b/stubs/flake8-simplify/flake8_simplify/rules/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/remote/__init__.pyi rename to stubs/flake8-simplify/flake8_simplify/rules/__init__.pyi diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi new file mode 100644 index 000000000000..019ac9f499a7 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi @@ -0,0 +1,6 @@ +import ast + +from flake8_simplify.utils import Assign + +def get_sim904(node: ast.Assign) -> list[tuple[int, int, str]]: ... +def get_sim909(node: Assign) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi new file mode 100644 index 000000000000..d130dceae322 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi @@ -0,0 +1,8 @@ +import ast + +def get_sim101(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim109(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim220(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim221(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim222(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim223(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi new file mode 100644 index 000000000000..d8b62cfa427d --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi @@ -0,0 +1,13 @@ +import ast +import logging + +from flake8_simplify.utils import Call + +logger: logging.Logger + +def get_sim115(node: Call) -> list[tuple[int, int, str]]: ... +def get_sim901(node: ast.Call) -> list[tuple[int, int, str]]: ... +def get_sim905(node: ast.Call) -> list[tuple[int, int, str]]: ... +def get_sim906(node: ast.Call) -> list[tuple[int, int, str]]: ... +def get_sim910(node: Call) -> list[tuple[int, int, str]]: ... +def get_sim911(node: ast.AST) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi new file mode 100644 index 000000000000..09dc22b3595f --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim120(node: ast.ClassDef) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi new file mode 100644 index 000000000000..0a7b816a5e3c --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi @@ -0,0 +1,4 @@ +import ast + +def get_sim118(node: ast.Compare) -> list[tuple[int, int, str]]: ... +def get_sim300(node: ast.Compare) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi new file mode 100644 index 000000000000..af53ac0309d8 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim112(node: ast.Expr) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi new file mode 100644 index 000000000000..235c7fd2b287 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi @@ -0,0 +1,7 @@ +import ast + +from flake8_simplify.utils import For + +def get_sim104(node: ast.For) -> list[tuple[int, int, str]]: ... +def get_sim110_sim111(node: ast.For) -> list[tuple[int, int, str]]: ... +def get_sim113(node: For) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi new file mode 100644 index 000000000000..65121cfcef51 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi @@ -0,0 +1,11 @@ +import ast + +from flake8_simplify.utils import If + +def get_sim102(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim103(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim108(node: If) -> list[tuple[int, int, str]]: ... +def get_sim114(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim116(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim908(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim401(node: ast.If) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi new file mode 100644 index 000000000000..8a37a0c6a5ab --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi @@ -0,0 +1,5 @@ +import ast + +def get_sim210(node: ast.IfExp) -> list[tuple[int, int, str]]: ... +def get_sim211(node: ast.IfExp) -> list[tuple[int, int, str]]: ... +def get_sim212(node: ast.IfExp) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi new file mode 100644 index 000000000000..eb2fa207b32b --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim907(node: ast.Subscript) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi new file mode 100644 index 000000000000..9156100ebbe1 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi @@ -0,0 +1,4 @@ +import ast + +def get_sim105(node: ast.Try) -> list[tuple[int, int, str]]: ... +def get_sim107(node: ast.Try) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi new file mode 100644 index 000000000000..93603e0576f1 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi @@ -0,0 +1,8 @@ +import ast + +from flake8_simplify.utils import UnaryOp + +def get_sim201(node: UnaryOp) -> list[tuple[int, int, str]]: ... +def get_sim202(node: UnaryOp) -> list[tuple[int, int, str]]: ... +def get_sim203(node: UnaryOp) -> list[tuple[int, int, str]]: ... +def get_sim208(node: ast.UnaryOp) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi new file mode 100644 index 000000000000..310080e7ec0d --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim117(node: ast.With) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/utils.pyi b/stubs/flake8-simplify/flake8_simplify/utils.pyi new file mode 100644 index 000000000000..06104640204a --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/utils.pyi @@ -0,0 +1,36 @@ +import ast +from _typeshed import Incomplete + +class UnaryOp(ast.UnaryOp): + parent: ast.Expr + def __init__(self, orig: ast.UnaryOp) -> None: ... + +class Call(ast.Call): + parent: ast.Expr + def __init__(self, orig: ast.Call) -> None: ... + +class If(ast.If): + parent: ast.Expr + def __init__(self, orig: ast.If) -> None: ... + +class For(ast.For): + parent: ast.AST + previous_sibling: Incomplete + def __init__(self, orig: ast.For) -> None: ... + +class Assign(ast.Assign): + parent: ast.AST + previous_sibling: Incomplete + def __init__(self, orig: ast.Assign) -> None: ... + +def to_source(node: ast.expr | ast.Expr | ast.withitem | ast.slice | ast.Assign | None) -> str: ... +def strip_triple_quotes(string: str) -> str: ... +def use_double_quotes(string: str) -> str: ... +def is_body_same(body1: list[ast.stmt], body2: list[ast.stmt]) -> bool: ... +def is_stmt_equal(a: ast.stmt, b: ast.stmt) -> bool: ... +def get_if_body_pairs(node: ast.If) -> list[tuple[ast.expr, list[ast.stmt]]]: ... +def is_constant_increase(expr: ast.AugAssign) -> bool: ... +def is_exception_check(node: ast.If) -> bool: ... +def is_same_expression(a: ast.expr, b: ast.expr) -> bool: ... +def expression_uses_variable(expr: ast.expr, var: str) -> bool: ... +def body_contains_continue(stmts: list[ast.stmt]) -> bool: ... diff --git a/stubs/flake8-typing-imports/METADATA.toml b/stubs/flake8-typing-imports/METADATA.toml index 88c1356c9e65..77ede4ca1037 100644 --- a/stubs/flake8-typing-imports/METADATA.toml +++ b/stubs/flake8-typing-imports/METADATA.toml @@ -1 +1,2 @@ -version = "1.11.*" +version = "1.17.*" +upstream-repository = "https://github.com/asottile/flake8-typing-imports" diff --git a/stubs/flake8-typing-imports/flake8_typing_imports.pyi b/stubs/flake8-typing-imports/flake8_typing_imports.pyi index 04585966849f..f2dd55ee9f12 100644 --- a/stubs/flake8-typing-imports/flake8_typing_imports.pyi +++ b/stubs/flake8-typing-imports/flake8_typing_imports.pyi @@ -1,15 +1,40 @@ import argparse import ast -from typing import Any, ClassVar, Generator, Type +from collections.abc import Generator +from typing import Any, Final, NamedTuple +from typing_extensions import Self + +class Version(NamedTuple): + major: int = 0 + minor: int = 0 + patch: int = 0 + @classmethod + def parse(cls, s: str) -> Self: ... + +SYMBOLS: Final[list[tuple[Version, frozenset[str]]]] +VERSIONS: Final[frozenset[Version]] + +class Visitor(ast.NodeVisitor): + imports: dict[str, list[tuple[int, int]]] + attributes: dict[str, list[tuple[int, int]]] + defined_overload: bool + unions_pattern_or_match: list[tuple[int, int]] + from_imported_names: set[str] + namedtuple_methods: list[tuple[int, int]] + namedtuple_defaults: list[tuple[int, int]] + def __init__(self) -> None: ... + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: ... + def visit_Attribute(self, node: ast.Attribute) -> None: ... + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: ... + def visit_Subscript(self, node: ast.Subscript) -> None: ... + def visit_ClassDef(self, node: ast.ClassDef) -> None: ... + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: ... + def generic_visit(self, node: ast.AST) -> None: ... class Plugin: - name: ClassVar[str] - version: ClassVar[str] @staticmethod def add_options(option_manager: Any) -> None: ... @classmethod def parse_options(cls, options: argparse.Namespace) -> None: ... def __init__(self, tree: ast.AST) -> None: ... - def run(self) -> Generator[tuple[int, int, str, Type[Any]], None, None]: ... - -def __getattr__(name: str) -> Any: ... # incomplete (other attributes are normally not accessed) + def run(self) -> Generator[tuple[int, int, str, type[Any]]]: ... diff --git a/stubs/flake8/@tests/stubtest_allowlist.txt b/stubs/flake8/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e33caad65504 --- /dev/null +++ b/stubs/flake8/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +flake8.__main__ diff --git a/stubs/flake8/METADATA.toml b/stubs/flake8/METADATA.toml new file mode 100644 index 000000000000..0918bdd4ab2f --- /dev/null +++ b/stubs/flake8/METADATA.toml @@ -0,0 +1,3 @@ +version = "7.4.*" +upstream-repository = "https://github.com/pycqa/flake8" +dependencies = ["types-pyflakes"] diff --git a/stubs/flake8/flake8/__init__.pyi b/stubs/flake8/flake8/__init__.pyi new file mode 100644 index 000000000000..56cd4da6b6cd --- /dev/null +++ b/stubs/flake8/flake8/__init__.pyi @@ -0,0 +1,8 @@ +from logging import Logger + +LOG: Logger +__version__: str +__version_info__: tuple[int, int, int] +LOG_FORMAT: str + +def configure_logging(verbosity: int, filename: str | None = None, logformat: str = ...) -> None: ... diff --git a/stubs/flake8/flake8/_compat.pyi b/stubs/flake8/flake8/_compat.pyi new file mode 100644 index 000000000000..7fbc26e88fc1 --- /dev/null +++ b/stubs/flake8/flake8/_compat.pyi @@ -0,0 +1,9 @@ +from typing import Final + +FSTRING_START: Final[int] +FSTRING_MIDDLE: Final[int] +FSTRING_END: Final[int] + +TSTRING_START: Final[int] +TSTRING_MIDDLE: Final[int] +TSTRING_END: Final[int] diff --git a/stubs/selenium/selenium/webdriver/safari/__init__.pyi b/stubs/flake8/flake8/api/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/safari/__init__.pyi rename to stubs/flake8/flake8/api/__init__.pyi diff --git a/stubs/flake8/flake8/api/legacy.pyi b/stubs/flake8/flake8/api/legacy.pyi new file mode 100644 index 000000000000..7f8ad95d25cc --- /dev/null +++ b/stubs/flake8/flake8/api/legacy.pyi @@ -0,0 +1,27 @@ +import argparse +from _typeshed import Unused +from typing import Any + +from ..formatting import base as formatter +from ..main import application as app + +__all__ = ("get_style_guide",) + +class Report: + def __init__(self, application: app.Application) -> None: ... + @property + def total_errors(self) -> int: ... + def get_statistics(self, violation: str) -> list[str]: ... + +class StyleGuide: + def __init__(self, application: app.Application) -> None: ... + @property + def options(self) -> argparse.Namespace: ... + @property + def paths(self) -> list[str]: ... + def check_files(self, paths: list[str] | None = None) -> Report: ... + def excluded(self, filename: str, parent: str | None = None) -> bool: ... + def init_report(self, reporter: type[formatter.BaseFormatter] | None = None) -> None: ... + def input_file(self, filename: str, lines: Unused = None, expected: Unused = None, line_offset: Unused = 0) -> Report: ... + +def get_style_guide(**kwargs: Any) -> StyleGuide: ... diff --git a/stubs/flake8/flake8/checker.pyi b/stubs/flake8/flake8/checker.pyi new file mode 100644 index 000000000000..d370840cc1b7 --- /dev/null +++ b/stubs/flake8/flake8/checker.pyi @@ -0,0 +1,55 @@ +import argparse +import tokenize +from _typeshed import Incomplete +from collections.abc import Sequence +from logging import Logger +from typing import Any, TypeAlias + +from .plugins.finder import Checkers, LoadedPlugin +from .processor import _LogicalMapping +from .style_guide import StyleGuideManager + +Results: TypeAlias = list[tuple[str, int, int, str, str | None]] + +LOG: Logger +SERIAL_RETRY_ERRNOS: Incomplete + +class Manager: + style_guide: Incomplete + options: Incomplete + plugins: Incomplete + jobs: Incomplete + statistics: Incomplete + exclude: Incomplete + argv: Incomplete + results: Incomplete + def __init__(self, style_guide: StyleGuideManager, plugins: Checkers, argv: Sequence[str]) -> None: ... + def report(self) -> tuple[int, int]: ... + def run_parallel(self) -> None: ... + def run_serial(self) -> None: ... + def run(self) -> None: ... + filenames: Incomplete + def start(self) -> None: ... + def stop(self) -> None: ... + +class FileChecker: + options: Incomplete + filename: Incomplete + plugins: Incomplete + results: Incomplete + statistics: Incomplete + processor: Incomplete + display_name: Incomplete + should_process: bool + def __init__(self, *, filename: str, plugins: Checkers, options: argparse.Namespace) -> None: ... + def report(self, error_code: str | None, line_number: int, column: int, text: str) -> str: ... + def run_check(self, plugin: LoadedPlugin, **arguments: Any) -> Any: ... + def run_ast_checks(self) -> None: ... + def run_logical_checks(self) -> None: ... + def run_physical_checks(self, physical_line: str) -> None: ... + def process_tokens(self) -> None: ... + def run_checks(self) -> tuple[str, Results, dict[str, int]]: ... + def handle_newline(self, token_type: int) -> None: ... + def check_physical_eol(self, token: tokenize.TokenInfo, prev_physical: str) -> None: ... + +def find_offset(offset: int, mapping: _LogicalMapping) -> tuple[int, int]: ... diff --git a/stubs/flake8/flake8/defaults.pyi b/stubs/flake8/flake8/defaults.pyi new file mode 100644 index 000000000000..1a9459d17410 --- /dev/null +++ b/stubs/flake8/flake8/defaults.pyi @@ -0,0 +1,12 @@ +from re import Pattern +from typing import Final + +EXCLUDE: Final[tuple[str, ...]] +IGNORE: Final[tuple[str, ...]] +MAX_LINE_LENGTH: Final = 79 +INDENT_SIZE: Final = 4 +WHITESPACE: Final[frozenset[str]] +STATISTIC_NAMES: Final[tuple[str, ...]] +NOQA_INLINE_REGEXP: Final[Pattern[str]] +NOQA_FILE: Final[Pattern[str]] +VALID_CODE_PREFIX: Final[Pattern[str]] diff --git a/stubs/flake8/flake8/discover_files.pyi b/stubs/flake8/flake8/discover_files.pyi new file mode 100644 index 000000000000..aca433fa617c --- /dev/null +++ b/stubs/flake8/flake8/discover_files.pyi @@ -0,0 +1,8 @@ +from collections.abc import Generator, Sequence +from logging import Logger + +LOG: Logger + +def expand_paths( + *, paths: Sequence[str], stdin_display_name: str, filename_patterns: Sequence[str], exclude: Sequence[str] +) -> Generator[str]: ... diff --git a/stubs/flake8/flake8/exceptions.pyi b/stubs/flake8/flake8/exceptions.pyi new file mode 100644 index 000000000000..7c6e3fc70629 --- /dev/null +++ b/stubs/flake8/flake8/exceptions.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +class Flake8Exception(Exception): ... +class EarlyQuit(Flake8Exception): ... +class ExecutionError(Flake8Exception): ... + +class FailedToLoadPlugin(Flake8Exception): + FORMAT: str + plugin_name: Incomplete + original_exception: Incomplete + def __init__(self, plugin_name: str, exception: Exception) -> None: ... + +class PluginRequestedUnknownParameters(Flake8Exception): + FORMAT: str + plugin_name: Incomplete + original_exception: Incomplete + def __init__(self, plugin_name: str, exception: Exception) -> None: ... + +class PluginExecutionFailed(Flake8Exception): + FORMAT: str + filename: Incomplete + plugin_name: Incomplete + original_exception: Incomplete + def __init__(self, filename: str, plugin_name: str, exception: Exception) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/support/__init__.pyi b/stubs/flake8/flake8/formatting/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/support/__init__.pyi rename to stubs/flake8/flake8/formatting/__init__.pyi diff --git a/stubs/flake8/flake8/formatting/_windows_color.pyi b/stubs/flake8/flake8/formatting/_windows_color.pyi new file mode 100644 index 000000000000..f8af8baa7fce --- /dev/null +++ b/stubs/flake8/flake8/formatting/_windows_color.pyi @@ -0,0 +1 @@ +terminal_supports_color: bool diff --git a/stubs/flake8/flake8/formatting/base.pyi b/stubs/flake8/flake8/formatting/base.pyi new file mode 100644 index 000000000000..8401cdf00ce1 --- /dev/null +++ b/stubs/flake8/flake8/formatting/base.pyi @@ -0,0 +1,25 @@ +import argparse +from _typeshed import Incomplete + +from ..statistics import Statistics +from ..violation import Violation as Violation + +class BaseFormatter: + options: Incomplete + filename: Incomplete + output_fd: Incomplete + newline: str + color: Incomplete + def __init__(self, options: argparse.Namespace) -> None: ... + def after_init(self) -> None: ... + def beginning(self, filename: str) -> None: ... + def finished(self, filename: str) -> None: ... + def start(self) -> None: ... + def handle(self, error: Violation) -> None: ... + def format(self, error: Violation) -> str | None: ... + def show_statistics(self, statistics: Statistics) -> None: ... + def show_benchmarks(self, benchmarks: list[tuple[str, float]]) -> None: ... + def show_source(self, error: Violation) -> str | None: ... + def write(self, line: str | None, source: str | None) -> None: ... + def _write(self, output: str) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/flake8/flake8/formatting/default.pyi b/stubs/flake8/flake8/formatting/default.pyi new file mode 100644 index 000000000000..a2cdebdd3456 --- /dev/null +++ b/stubs/flake8/flake8/formatting/default.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete + +from ..violation import Violation +from .base import BaseFormatter + +COLORS: dict[str, str] +COLORS_OFF: dict[str, str] + +class SimpleFormatter(BaseFormatter): + error_format: str + def format(self, error: Violation) -> str | None: ... + +class Default(SimpleFormatter): + error_format: str + def after_init(self) -> None: ... + +class Pylint(SimpleFormatter): + error_format: str + +class FilenameOnly(SimpleFormatter): + error_format: str + filenames_already_printed: Incomplete + def after_init(self) -> None: ... + def show_source(self, error: Violation) -> str | None: ... + def format(self, error: Violation) -> str | None: ... + +class Nothing(BaseFormatter): + def format(self, error: Violation) -> str | None: ... + def show_source(self, error: Violation) -> str | None: ... diff --git a/stubs/selenium/selenium/webdriver/webkitgtk/__init__.pyi b/stubs/flake8/flake8/main/__init__.pyi similarity index 100% rename from stubs/selenium/selenium/webdriver/webkitgtk/__init__.pyi rename to stubs/flake8/flake8/main/__init__.pyi diff --git a/stubs/flake8/flake8/main/application.pyi b/stubs/flake8/flake8/main/application.pyi new file mode 100644 index 000000000000..b41ba83c8b06 --- /dev/null +++ b/stubs/flake8/flake8/main/application.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from logging import Logger + +LOG: Logger + +class Application: + start_time: Incomplete + end_time: Incomplete + plugins: Incomplete + formatter: Incomplete + guide: Incomplete + file_checker_manager: Incomplete + options: Incomplete + result_count: int + total_result_count: int + catastrophic_failure: bool + def __init__(self) -> None: ... + def exit_code(self) -> int: ... + def make_formatter(self) -> None: ... + def make_guide(self) -> None: ... + def make_file_checker_manager(self, argv: Sequence[str]) -> None: ... + def run_checks(self) -> None: ... + def report_benchmarks(self) -> None: ... + def report_errors(self) -> None: ... + def report_statistics(self) -> None: ... + def initialize(self, argv: Sequence[str]) -> None: ... + def report(self) -> None: ... + def run(self, argv: Sequence[str]) -> None: ... diff --git a/stubs/flake8/flake8/main/cli.pyi b/stubs/flake8/flake8/main/cli.pyi new file mode 100644 index 000000000000..2d91d1aa373c --- /dev/null +++ b/stubs/flake8/flake8/main/cli.pyi @@ -0,0 +1,3 @@ +from collections.abc import Sequence + +def main(argv: Sequence[str] | None = None) -> int: ... diff --git a/stubs/flake8/flake8/main/debug.pyi b/stubs/flake8/flake8/main/debug.pyi new file mode 100644 index 000000000000..2f1ef97cfeb0 --- /dev/null +++ b/stubs/flake8/flake8/main/debug.pyi @@ -0,0 +1,5 @@ +from typing import Any + +from ..plugins.finder import Plugins + +def information(version: str, plugins: Plugins) -> dict[str, Any]: ... diff --git a/stubs/flake8/flake8/main/options.pyi b/stubs/flake8/flake8/main/options.pyi new file mode 100644 index 000000000000..1f9bf70a5d7f --- /dev/null +++ b/stubs/flake8/flake8/main/options.pyi @@ -0,0 +1,12 @@ +from argparse import ArgumentParser + +from ..options.manager import OptionManager + +def stage1_arg_parser() -> ArgumentParser: ... + +class JobsArgument: + is_auto: bool + n_jobs: int + def __init__(self, arg: str) -> None: ... + +def register_default_options(option_manager: OptionManager) -> None: ... diff --git a/stubs/typed-ast/typed_ast/__init__.pyi b/stubs/flake8/flake8/options/__init__.pyi similarity index 100% rename from stubs/typed-ast/typed_ast/__init__.pyi rename to stubs/flake8/flake8/options/__init__.pyi diff --git a/stubs/flake8/flake8/options/aggregator.pyi b/stubs/flake8/flake8/options/aggregator.pyi new file mode 100644 index 000000000000..a6bb859a8c3b --- /dev/null +++ b/stubs/flake8/flake8/options/aggregator.pyi @@ -0,0 +1,12 @@ +import argparse +import configparser +from collections.abc import Sequence +from logging import Logger + +from .manager import OptionManager + +LOG: Logger + +def aggregate_options( + manager: OptionManager, cfg: configparser.RawConfigParser, cfg_dir: str, argv: Sequence[str] | None +) -> argparse.Namespace: ... diff --git a/stubs/flake8/flake8/options/config.pyi b/stubs/flake8/flake8/options/config.pyi new file mode 100644 index 000000000000..a443261b15a2 --- /dev/null +++ b/stubs/flake8/flake8/options/config.pyi @@ -0,0 +1,10 @@ +import configparser +from logging import Logger +from typing import Any + +from .manager import OptionManager + +LOG: Logger + +def load_config(config: str | None, extra: list[str], *, isolated: bool = False) -> tuple[configparser.RawConfigParser, str]: ... +def parse_config(option_manager: OptionManager, cfg: configparser.RawConfigParser, cfg_dir: str) -> dict[str, Any]: ... diff --git a/stubs/flake8/flake8/options/manager.pyi b/stubs/flake8/flake8/options/manager.pyi new file mode 100644 index 000000000000..5bb2519d8e34 --- /dev/null +++ b/stubs/flake8/flake8/options/manager.pyi @@ -0,0 +1,71 @@ +import argparse +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from enum import Enum +from logging import Logger +from typing import Any + +from ..plugins.finder import Plugins + +LOG: Logger + +class _ARG(Enum): + NO = 1 + +class Option: + short_option_name: Incomplete + long_option_name: Incomplete + option_args: Incomplete + action: Incomplete + default: Incomplete + type: Incomplete + dest: Incomplete + nargs: Incomplete + const: Incomplete + choices: Incomplete + help: Incomplete + metavar: Incomplete + required: Incomplete + option_kwargs: Incomplete + parse_from_config: Incomplete + comma_separated_list: Incomplete + normalize_paths: Incomplete + config_name: Incomplete + def __init__( + self, + short_option_name: str | _ARG = ..., + long_option_name: str | _ARG = ..., + action: str | type[argparse.Action] | _ARG = ..., + default: Any | _ARG = ..., + type: Callable[..., Any] | _ARG = ..., + dest: str | _ARG = ..., + nargs: int | str | _ARG = ..., + const: Any | _ARG = ..., + choices: Sequence[Any] | _ARG = ..., + help: str | _ARG = ..., + metavar: str | _ARG = ..., + required: bool | _ARG = ..., + parse_from_config: bool = False, + comma_separated_list: bool = False, + normalize_paths: bool = False, + ) -> None: ... + @property + def filtered_option_kwargs(self) -> dict[str, Any]: ... + def normalize(self, value: Any, *normalize_args: str) -> Any: ... + def to_argparse(self) -> tuple[list[str], dict[str, Any]]: ... + +class OptionManager: + formatter_names: Incomplete + parser: Incomplete + config_options_dict: Incomplete + options: Incomplete + extended_default_ignore: Incomplete + extended_default_select: Incomplete + def __init__( + self, *, version: str, plugin_versions: str, parents: list[argparse.ArgumentParser], formatter_names: list[str] + ) -> None: ... + def register_plugins(self, plugins: Plugins) -> None: ... + def add_option(self, *args: Any, **kwargs: Any) -> None: ... + def extend_default_ignore(self, error_codes: Sequence[str]) -> None: ... + def extend_default_select(self, error_codes: Sequence[str]) -> None: ... + def parse_args(self, args: Sequence[str] | None = None, values: argparse.Namespace | None = None) -> argparse.Namespace: ... diff --git a/stubs/flake8/flake8/options/parse_args.pyi b/stubs/flake8/flake8/options/parse_args.pyi new file mode 100644 index 000000000000..2818b87ce814 --- /dev/null +++ b/stubs/flake8/flake8/options/parse_args.pyi @@ -0,0 +1,6 @@ +import argparse +from collections.abc import Sequence + +from ..plugins import finder + +def parse_args(argv: Sequence[str]) -> tuple[finder.Plugins, argparse.Namespace]: ... diff --git a/stdlib/@python2/distutils/command/bdist_dumb.pyi b/stubs/flake8/flake8/plugins/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/bdist_dumb.pyi rename to stubs/flake8/flake8/plugins/__init__.pyi diff --git a/stubs/flake8/flake8/plugins/finder.pyi b/stubs/flake8/flake8/plugins/finder.pyi new file mode 100644 index 000000000000..8a8a7d49a099 --- /dev/null +++ b/stubs/flake8/flake8/plugins/finder.pyi @@ -0,0 +1,48 @@ +import configparser +import importlib.metadata +from collections.abc import Generator +from logging import Logger +from typing import Any, Final, NamedTuple + +LOG: Logger +FLAKE8_GROUPS: Final[frozenset[str]] +BANNED_PLUGINS: dict[str, str] + +class Plugin(NamedTuple): + package: str + version: str + entry_point: importlib.metadata.EntryPoint + +class LoadedPlugin(NamedTuple): + plugin: Plugin + obj: Any + parameters: dict[str, bool] + @property + def entry_name(self) -> str: ... + @property + def display_name(self) -> str: ... + +class Checkers(NamedTuple): + tree: list[LoadedPlugin] + logical_line: list[LoadedPlugin] + physical_line: list[LoadedPlugin] + +class Plugins(NamedTuple): + checkers: Checkers + reporters: dict[str, LoadedPlugin] + disabled: list[LoadedPlugin] + def all_plugins(self) -> Generator[LoadedPlugin]: ... + def versions_str(self) -> str: ... + +class PluginOptions(NamedTuple): + local_plugin_paths: tuple[str, ...] + enable_extensions: frozenset[str] + require_plugins: frozenset[str] + @classmethod + def blank(cls) -> PluginOptions: ... + +def parse_plugin_options( + cfg: configparser.RawConfigParser, cfg_dir: str, *, enable_extensions: str | None, require_plugins: str | None +) -> PluginOptions: ... +def find_plugins(cfg: configparser.RawConfigParser, opts: PluginOptions) -> list[Plugin]: ... +def load_plugins(plugins: list[Plugin], opts: PluginOptions) -> Plugins: ... diff --git a/stubs/flake8/flake8/plugins/pycodestyle.pyi b/stubs/flake8/flake8/plugins/pycodestyle.pyi new file mode 100644 index 000000000000..108770a0ae93 --- /dev/null +++ b/stubs/flake8/flake8/plugins/pycodestyle.pyi @@ -0,0 +1,32 @@ +from collections.abc import Generator +from typing import Any + +def pycodestyle_logical( + blank_before: Any, + blank_lines: Any, + checker_state: Any, + hang_closing: Any, + indent_char: Any, + indent_level: Any, + indent_size: Any, + line_number: Any, + lines: Any, + logical_line: Any, + max_doc_length: Any, + noqa: Any, + previous_indent_level: Any, + previous_logical: Any, + previous_unindented_logical_line: Any, + tokens: Any, + verbose: Any, +) -> Generator[tuple[int, str]]: ... +def pycodestyle_physical( + indent_char: Any, + line_number: Any, + lines: Any, + max_line_length: Any, + multiline: Any, + noqa: Any, + physical_line: Any, + total_lines: Any, +) -> Generator[tuple[int, str]]: ... diff --git a/stubs/flake8/flake8/plugins/pyflakes.pyi b/stubs/flake8/flake8/plugins/pyflakes.pyi new file mode 100644 index 000000000000..6453e63d8385 --- /dev/null +++ b/stubs/flake8/flake8/plugins/pyflakes.pyi @@ -0,0 +1,21 @@ +from argparse import Namespace +from ast import AST +from collections.abc import Generator +from logging import Logger +from typing import Any + +from pyflakes.checker import Checker + +from ..options.manager import OptionManager + +LOG: Logger +FLAKE8_PYFLAKES_CODES: dict[str, str] + +class FlakesChecker(Checker): + with_doctest: bool + def __init__(self, tree: AST, filename: str) -> None: ... + @classmethod + def add_options(cls, parser: OptionManager) -> None: ... + @classmethod + def parse_options(cls, options: Namespace) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[Any]]]: ... diff --git a/stubs/flake8/flake8/plugins/reporter.pyi b/stubs/flake8/flake8/plugins/reporter.pyi new file mode 100644 index 000000000000..ee3e72711d6e --- /dev/null +++ b/stubs/flake8/flake8/plugins/reporter.pyi @@ -0,0 +1,9 @@ +import argparse +from logging import Logger + +from ..formatting.base import BaseFormatter +from .finder import LoadedPlugin + +LOG: Logger + +def make(reporters: dict[str, LoadedPlugin], options: argparse.Namespace) -> BaseFormatter: ... diff --git a/stubs/flake8/flake8/processor.pyi b/stubs/flake8/flake8/processor.pyi new file mode 100644 index 000000000000..a00e0b1e2359 --- /dev/null +++ b/stubs/flake8/flake8/processor.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from argparse import Namespace +from ast import AST +from collections.abc import Generator +from logging import Logger +from tokenize import TokenInfo +from typing import Any, Final, TypeAlias + +from .plugins.finder import LoadedPlugin + +LOG: Logger +NEWLINE: Final[frozenset[int]] +SKIP_TOKENS: Final[frozenset[int]] + +_LogicalMapping: TypeAlias = list[tuple[int, tuple[int, int]]] +_Logical: TypeAlias = tuple[list[str], list[str], _LogicalMapping] + +class FileProcessor: + noqa: bool + options: Incomplete + filename: Incomplete + lines: Incomplete + blank_before: int + blank_lines: int + checker_state: Incomplete + hang_closing: Incomplete + indent_char: Incomplete + indent_level: int + indent_size: Incomplete + line_number: int + logical_line: str + max_line_length: Incomplete + max_doc_length: Incomplete + multiline: bool + previous_indent_level: int + previous_logical: str + previous_unindented_logical_line: str + tokens: Incomplete + total_lines: Incomplete + verbose: Incomplete + statistics: Incomplete + def __init__(self, filename: str, options: Namespace, lines: list[str] | None = None) -> None: ... + @property + def file_tokens(self) -> list[TokenInfo]: ... + def tstring_start(self, lineno: int) -> None: ... + def fstring_start(self, lineno: int) -> None: ... + def multiline_string(self, token: TokenInfo) -> Generator[str]: ... + def reset_blank_before(self) -> None: ... + def delete_first_token(self) -> None: ... + def visited_new_blank_line(self) -> None: ... + def update_state(self, mapping: _LogicalMapping) -> None: ... + def update_checker_state_for(self, plugin: LoadedPlugin) -> None: ... + def next_logical_line(self) -> None: ... + def build_logical_line_tokens(self) -> _Logical: ... + def build_ast(self) -> AST: ... + def build_logical_line(self) -> tuple[str, str, _LogicalMapping]: ... + def keyword_arguments_for(self, parameters: dict[str, bool], arguments: dict[str, Any]) -> dict[str, Any]: ... + def generate_tokens(self) -> Generator[TokenInfo]: ... + def noqa_line_for(self, line_number: int) -> str | None: ... + def next_line(self) -> str: ... + def read_lines(self) -> list[str]: ... + def read_lines_from_filename(self) -> list[str]: ... + def read_lines_from_stdin(self) -> list[str]: ... + def should_ignore_file(self) -> bool: ... + def strip_utf_bom(self) -> None: ... + +def is_eol_token(token: TokenInfo) -> bool: ... +def is_multiline_string(token: TokenInfo) -> bool: ... +def token_is_newline(token: TokenInfo) -> bool: ... +def count_parentheses(current_parentheses_count: int, token_text: str) -> int: ... +def expand_indent(line: str) -> int: ... +def mutate_string(text: str) -> str: ... diff --git a/stubs/flake8/flake8/statistics.pyi b/stubs/flake8/flake8/statistics.pyi new file mode 100644 index 000000000000..5b7d1f551e44 --- /dev/null +++ b/stubs/flake8/flake8/statistics.pyi @@ -0,0 +1,27 @@ +from collections.abc import Generator +from typing import NamedTuple + +from .violation import Violation + +class Statistics: + def __init__(self) -> None: ... + def error_codes(self) -> list[str]: ... + def record(self, error: Violation) -> None: ... + def statistics_for(self, prefix: str, filename: str | None = None) -> Generator[Statistic]: ... + +class Key(NamedTuple): + filename: str + code: str + @classmethod + def create_from(cls, error: Violation) -> Key: ... + def matches(self, prefix: str, filename: str | None) -> bool: ... + +class Statistic: + error_code: str + filename: str + message: str + count: int + def __init__(self, error_code: str, filename: str, message: str, count: int) -> None: ... + @classmethod + def create_from(cls, error: Violation) -> Statistic: ... + def increment(self) -> None: ... diff --git a/stubs/flake8/flake8/style_guide.pyi b/stubs/flake8/flake8/style_guide.pyi new file mode 100644 index 000000000000..bc27ec55b820 --- /dev/null +++ b/stubs/flake8/flake8/style_guide.pyi @@ -0,0 +1,70 @@ +import argparse +import enum +from _typeshed import Incomplete +from collections.abc import Generator, Sequence + +from .formatting.base import BaseFormatter +from .statistics import Statistics + +__all__ = ("StyleGuide",) + +class Selected(enum.Enum): + Explicitly = "explicitly selected" + Implicitly = "implicitly selected" + +class Ignored(enum.Enum): + Explicitly = "explicitly ignored" + Implicitly = "implicitly ignored" + +class Decision(enum.Enum): + Ignored = "ignored error" + Selected = "selected error" + +class DecisionEngine: + cache: Incomplete + selected_explicitly: Incomplete + ignored_explicitly: Incomplete + selected: Incomplete + ignored: Incomplete + def __init__(self, options: argparse.Namespace) -> None: ... + def was_selected(self, code: str) -> Selected | Ignored: ... + def was_ignored(self, code: str) -> Selected | Ignored: ... + def make_decision(self, code: str) -> Decision: ... + def decision_for(self, code: str) -> Decision: ... + +class StyleGuideManager: + options: Incomplete + formatter: Incomplete + stats: Incomplete + decider: Incomplete + style_guides: Incomplete + default_style_guide: Incomplete + style_guide_for: Incomplete + def __init__(self, options: argparse.Namespace, formatter: BaseFormatter, decider: DecisionEngine | None = None) -> None: ... + def populate_style_guides_with(self, options: argparse.Namespace) -> Generator[StyleGuide]: ... + def processing_file(self, filename: str) -> Generator[StyleGuide]: ... + def handle_error( + self, code: str, filename: str, line_number: int, column_number: int, text: str, physical_line: str | None = None + ) -> int: ... + +class StyleGuide: + options: Incomplete + formatter: Incomplete + stats: Incomplete + decider: Incomplete + filename: Incomplete + def __init__( + self, + options: argparse.Namespace, + formatter: BaseFormatter, + stats: Statistics, + filename: str | None = None, + decider: DecisionEngine | None = None, + ) -> None: ... + def copy(self, filename: str | None = None, extend_ignore_with: Sequence[str] | None = None) -> StyleGuide: ... + def processing_file(self, filename: str) -> Generator[StyleGuide]: ... + def applies_to(self, filename: str) -> bool: ... + def should_report_error(self, code: str) -> Decision: ... + def handle_error( + self, code: str, filename: str, line_number: int, column_number: int, text: str, physical_line: str | None = None + ) -> int: ... diff --git a/stubs/flake8/flake8/utils.pyi b/stubs/flake8/flake8/utils.pyi new file mode 100644 index 000000000000..b12329404e01 --- /dev/null +++ b/stubs/flake8/flake8/utils.pyi @@ -0,0 +1,25 @@ +import logging +from collections.abc import Sequence +from re import Pattern +from typing import Final, NamedTuple + +COMMA_SEPARATED_LIST_RE: Final[Pattern[str]] +LOCAL_PLUGIN_LIST_RE: Final[Pattern[str]] +NORMALIZE_PACKAGE_NAME_RE: Final[Pattern[str]] + +def parse_comma_separated_list(value: str, regexp: Pattern[str] = ...) -> list[str]: ... + +class _Token(NamedTuple): + tp: str + src: str + +def parse_files_to_codes_mapping(value_: Sequence[str] | str) -> list[tuple[str, list[str]]]: ... +def normalize_paths(paths: Sequence[str], parent: str = ".") -> list[str]: ... +def normalize_path(path: str, parent: str = ".") -> str: ... +def stdin_get_value() -> str: ... +def stdin_get_lines() -> list[str]: ... +def is_using_stdin(paths: list[str]) -> bool: ... +def fnmatch(filename: str, patterns: Sequence[str]) -> bool: ... +def matches_filename(path: str, patterns: Sequence[str], log_message: str, logger: logging.Logger) -> bool: ... +def get_python_version() -> str: ... +def normalize_pypi_name(s: str) -> str: ... diff --git a/stubs/flake8/flake8/violation.pyi b/stubs/flake8/flake8/violation.pyi new file mode 100644 index 000000000000..7526471ebb71 --- /dev/null +++ b/stubs/flake8/flake8/violation.pyi @@ -0,0 +1,13 @@ +from logging import Logger +from typing import NamedTuple + +LOG: Logger + +class Violation(NamedTuple): + code: str + filename: str + line_number: int + column_number: int + text: str + physical_line: str | None + def is_inline_ignored(self, disable_noqa: bool) -> bool: ... diff --git a/stubs/fpdf2/@tests/stubtest_allowlist.txt b/stubs/fpdf2/@tests/stubtest_allowlist.txt deleted file mode 100644 index 212b6ef1d5ad..000000000000 --- a/stubs/fpdf2/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,3 +0,0 @@ -# The "dest" argument is unused and will be removed. -fpdf.FPDF.output -fpdf.fpdf.FPDF.output diff --git a/stubs/fpdf2/METADATA.toml b/stubs/fpdf2/METADATA.toml deleted file mode 100644 index 4b1457dea513..000000000000 --- a/stubs/fpdf2/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "2.4.*" -requires = ["types-Pillow"] diff --git a/stubs/fpdf2/fpdf/__init__.pyi b/stubs/fpdf2/fpdf/__init__.pyi deleted file mode 100644 index 2ee9dd6704d3..000000000000 --- a/stubs/fpdf2/fpdf/__init__.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from pathlib import Path - -from .fpdf import FPDF as FPDF, TitleStyle as TitleStyle -from .html import HTML2FPDF as HTML2FPDF, HTMLMixin as HTMLMixin -from .template import Template as Template - -__license__: str -__version__: str -FPDF_VERSION: str -FPDF_FONT_DIR: Path diff --git a/stubs/fpdf2/fpdf/actions.pyi b/stubs/fpdf2/fpdf/actions.pyi deleted file mode 100644 index 69feb0a2bf21..000000000000 --- a/stubs/fpdf2/fpdf/actions.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from abc import ABC -from typing import Any - -class Action(ABC): - def dict_as_string(self) -> None: ... - -class NamedAction(Action): - action_name: Any - def __init__(self, action_name) -> None: ... - def dict_as_string(self): ... - -class GoToAction(Action): - dest: Any - def __init__(self, dest) -> None: ... - def dict_as_string(self): ... - -class GoToRemoteAction(Action): - file: Any - dest: Any - def __init__(self, file, dest) -> None: ... - def dict_as_string(self): ... - -class LaunchAction(Action): - file: Any - def __init__(self, file) -> None: ... - def dict_as_string(self): ... diff --git a/stubs/fpdf2/fpdf/deprecation.pyi b/stubs/fpdf2/fpdf/deprecation.pyi deleted file mode 100644 index 044aa1cf795d..000000000000 --- a/stubs/fpdf2/fpdf/deprecation.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from types import ModuleType - -class WarnOnDeprecatedModuleAttributes(ModuleType): - def __getattr__(self, name): ... - def __setattr__(self, name, value) -> None: ... diff --git a/stubs/fpdf2/fpdf/errors.pyi b/stubs/fpdf2/fpdf/errors.pyi deleted file mode 100644 index 637a55e25159..000000000000 --- a/stubs/fpdf2/fpdf/errors.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -class FPDFException(Exception): ... - -class FPDFPageFormatException(FPDFException): - argument: Any - unknown: Any - one: Any - def __init__(self, argument, unknown: bool = ..., one: bool = ...) -> None: ... diff --git a/stubs/fpdf2/fpdf/fonts.pyi b/stubs/fpdf2/fpdf/fonts.pyi deleted file mode 100644 index 5a894fff6278..000000000000 --- a/stubs/fpdf2/fpdf/fonts.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Any - -courier: Any -fpdf_charwidths: Any diff --git a/stubs/fpdf2/fpdf/fpdf.pyi b/stubs/fpdf2/fpdf/fpdf.pyi deleted file mode 100644 index b8eaa3fcdba5..000000000000 --- a/stubs/fpdf2/fpdf/fpdf.pyi +++ /dev/null @@ -1,284 +0,0 @@ -import datetime -from _typeshed import StrPath -from collections import defaultdict -from collections.abc import Callable, Generator -from enum import IntEnum -from io import BytesIO -from pathlib import Path -from typing import Any, NamedTuple, overload -from typing_extensions import Literal - -from PIL import Image - -from .actions import Action -from .syntax import DestinationXYZ -from .util import _Unit - -_Orientation = Literal["", "portrait", "p", "P", "landscape", "l", "L"] -_Format = Literal["", "a3", "A3", "a4", "A4", "a5", "A5", "letter", "Letter", "legal", "Legal"] -_FontStyle = Literal["", "B", "I"] -_FontStyles = Literal["", "B", "I", "U", "BU", "UB", "BI", "IB", "IU", "UI", "BIU", "BUI", "IBU", "IUB", "UBI", "UIB"] -PAGE_FORMATS: dict[_Format, tuple[float, float]] - -class DocumentState(IntEnum): - UNINITIALIZED: int - READY: int - GENERATING_PAGE: int - CLOSED: int - -class Annotation(NamedTuple): - type: str - x: int - y: int - width: int - height: int - contents: str | None = ... - link: str | int | None = ... - alt_text: str | None = ... - action: Action | None = ... - -class TitleStyle(NamedTuple): - font_family: str | None = ... - font_style: str | None = ... - font_size_pt: int | None = ... - color: int | tuple[int, int, int] | None = ... - underline: bool = ... - t_margin: int | None = ... - l_margin: int | None = ... - b_margin: int | None = ... - -class ToCPlaceholder(NamedTuple): - render_function: Callable[[FPDF, Any], object] - start_page: int - y: int - pages: int = ... - -class SubsetMap: - def __init__(self, identities: list[int]) -> None: ... - def pick(self, unicode: int): ... - def dict(self): ... - -def get_page_format(format: _Format | tuple[float, float], k: float | None = ...) -> tuple[float, float]: ... -def load_cache(filename: Path): ... - -# TODO: TypedDicts -_Page = dict[str, Any] -_Font = dict[str, Any] -_FontFile = dict[str, Any] -_Image = dict[str, Any] - -class FPDF: - MARKDOWN_BOLD_MARKER: str - MARKDOWN_ITALICS_MARKER: str - MARKDOWN_UNDERLINE_MARKER: str - offsets: dict[int, int] - page: int - n: int - buffer: bytearray - pages: dict[int, _Page] - state: DocumentState - fonts: dict[str, _Font] - font_files: dict[str, _FontFile] - diffs: dict[int, int] - images: dict[str, _Image] - annots: defaultdict[int, list[Annotation]] - links: dict[int, DestinationXYZ] - in_footer: int - lasth: int - current_font: _Font - font_family: str - font_style: str - font_size_pt: int - font_stretching: int - str_alias_nb_pages: str - underline: int - draw_color: str - fill_color: str - text_color: str - ws: int - angle: int - font_cache_dir: Any - xmp_metadata: Any - image_filter: str - page_duration: int - page_transition: Any - struct_builder: Any - section_title_styles: Any - core_fonts: Any - core_fonts_encoding: str - font_aliases: Any - k: float - def_orientation: Any - font_size: Any - c_margin: Any - line_width: float - dw_pt: float - dh_pt: float - compress: bool - pdf_version: str - - x: float - y: float - t_margin: float - r_margin: float - l_margin: float - - # Set during call to _set_orientation(), called from __init__(). - cur_orientation: Literal["P", "L"] - w_pt: float - h_pt: float - w: float - h: float - def __init__( - self, - orientation: _Orientation = ..., - unit: _Unit | float = ..., - format: _Format | tuple[float, float] = ..., - font_cache_dir: bool = ..., - ) -> None: ... - @property - def unifontsubset(self): ... - @property - def epw(self): ... - @property - def eph(self): ... - def set_margin(self, margin: float) -> None: ... - def set_margins(self, left: float, top: float, right: float = ...) -> None: ... - def set_left_margin(self, margin: float) -> None: ... - def set_top_margin(self, margin: float) -> None: ... - def set_right_margin(self, margin: float) -> None: ... - auto_page_break: Any - b_margin: Any - page_break_trigger: Any - def set_auto_page_break(self, auto: bool, margin: float = ...) -> None: ... - zoom_mode: Any - layout_mode: Any - def set_display_mode(self, zoom, layout: str = ...) -> None: ... - def set_compression(self, compress) -> None: ... - title: Any - def set_title(self, title: str) -> None: ... - lang: Any - def set_lang(self, lang: str) -> None: ... - subject: Any - def set_subject(self, subject: str) -> None: ... - author: Any - def set_author(self, author: str) -> None: ... - keywords: Any - def set_keywords(self, keywords: str) -> None: ... - creator: Any - def set_creator(self, creator: str) -> None: ... - producer: Any - def set_producer(self, producer: str) -> None: ... - creation_date: Any - def set_creation_date(self, date: datetime.datetime | None = ...) -> None: ... - def set_xmp_metadata(self, xmp_metadata) -> None: ... - def set_doc_option(self, opt, value) -> None: ... - def set_image_filter(self, image_filter) -> None: ... - def alias_nb_pages(self, alias: str = ...) -> None: ... - def open(self) -> None: ... - def close(self) -> None: ... - def add_page( - self, - orientation: _Orientation = ..., - format: _Format | tuple[float, float] = ..., - same: bool = ..., - duration: int = ..., - transition: Any | None = ..., - ) -> None: ... - def header(self) -> None: ... - def footer(self) -> None: ... - def page_no(self) -> int: ... - def set_draw_color(self, r, g: int = ..., b: int = ...) -> None: ... - def set_fill_color(self, r, g: int = ..., b: int = ...) -> None: ... - def set_text_color(self, r, g: int = ..., b: int = ...) -> None: ... - def get_string_width(self, s, normalized: bool = ..., markdown: bool = ...): ... - def set_line_width(self, width: float) -> None: ... - def line(self, x1: float, y1: float, x2: float, y2: float) -> None: ... - def polyline(self, point_list, fill: bool = ..., polygon: bool = ...) -> None: ... - def polygon(self, point_list, fill: bool = ...) -> None: ... - def dashed_line(self, x1, y1, x2, y2, dash_length: int = ..., space_length: int = ...) -> None: ... - def rect(self, x, y, w, h, style: Any | None = ...) -> None: ... - def ellipse(self, x, y, w, h, style: Any | None = ...) -> None: ... - def circle(self, x, y, r, style: Any | None = ...) -> None: ... - def add_font(self, family: str, style: _FontStyle = ..., fname: str | None = ..., uni: bool = ...) -> None: ... - def set_font(self, family: str | None = ..., style: _FontStyles = ..., size: int = ...) -> None: ... - def set_font_size(self, size: int) -> None: ... - def set_stretching(self, stretching) -> None: ... - def add_link(self): ... - def set_link(self, link, y: int = ..., x: int = ..., page: int = ..., zoom: str = ...) -> None: ... - def link(self, x, y, w, h, link, alt_text: Any | None = ...) -> None: ... - def text_annotation(self, x, y, text) -> None: ... - def add_action(self, action, x, y, w, h) -> None: ... - def text(self, x, y, txt: str = ...) -> None: ... - def rotate(self, angle, x: Any | None = ..., y: Any | None = ...) -> None: ... - def rotation(self, angle, x: Any | None = ..., y: Any | None = ...) -> Generator[None, None, None]: ... - @property - def accept_page_break(self): ... - def cell( - self, - w: float | None = ..., - h: float | None = ..., - txt: str = ..., - border: bool | Literal[0, 1] | str = ..., - ln: int = ..., - align: str = ..., - fill: bool = ..., - link: str = ..., - center: bool = ..., - markdown: bool = ..., - ): ... - def will_page_break(self, height): ... - def multi_cell( - self, - w: float, - h: float | None = ..., - txt: str = ..., - border: bool | Literal[0, 1] | str = ..., - align: str = ..., - fill: bool = ..., - split_only: bool = ..., - link: str = ..., - ln: int = ..., - max_line_height: Any | None = ..., - markdown: bool = ..., - ): ... - def write(self, h: Any | None = ..., txt: str = ..., link: str = ...) -> None: ... - def image( - self, - name: str | Image.Image | BytesIO | StrPath, - x: float | None = ..., - y: float | None = ..., - w: float = ..., - h: float = ..., - type: str = ..., - link: str = ..., - title: str | None = ..., - alt_text: str | None = ..., - ) -> _Image: ... - def ln(self, h: Any | None = ...) -> None: ... - def get_x(self) -> float: ... - def set_x(self, x: float) -> None: ... - def get_y(self) -> float: ... - def set_y(self, y: float) -> None: ... - def set_xy(self, x: float, y: float) -> None: ... - @overload - def output(self, name: Literal[""] = ...) -> bytearray: ... # type: ignore[misc] - @overload - def output(self, name: str) -> None: ... - def normalize_text(self, txt): ... - def interleaved2of5(self, txt, x, y, w: int = ..., h: int = ...) -> None: ... - def code39(self, txt, x, y, w: float = ..., h: int = ...) -> None: ... - def rect_clip(self, x, y, w, h) -> Generator[None, None, None]: ... - def unbreakable(self) -> Generator[Any, None, None]: ... - def insert_toc_placeholder(self, render_toc_function, pages: int = ...) -> None: ... - def set_section_title_styles( - self, - level0, - level1: Any | None = ..., - level2: Any | None = ..., - level3: Any | None = ..., - level4: Any | None = ..., - level5: Any | None = ..., - level6: Any | None = ..., - ) -> None: ... - def start_section(self, name, level: int = ...) -> None: ... diff --git a/stubs/fpdf2/fpdf/html.pyi b/stubs/fpdf2/fpdf/html.pyi deleted file mode 100644 index c2e9a3a59066..000000000000 --- a/stubs/fpdf2/fpdf/html.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from html.parser import HTMLParser -from typing import Any - -LOGGER: Any -BULLET_WIN1252: str -DEFAULT_HEADING_SIZES: Any -COLOR_DICT: Any - -def px2mm(px): ... -def color_as_decimal(color: str = ...): ... - -class HTML2FPDF(HTMLParser): - pdf: Any - image_map: Any - li_tag_indent: Any - table_line_separators: Any - ul_bullet_char: Any - style: Any - href: str - align: str - page_links: Any - font_stack: Any - indent: int - bullet: Any - font_size: Any - font_color: Any - table: Any - table_col_width: Any - table_col_index: Any - td: Any - th: Any - tr: Any - thead: Any - tfoot: Any - tr_index: Any - theader: Any - tfooter: Any - theader_out: bool - table_row_height: int - heading_level: Any - heading_sizes: Any - def __init__( - self, - pdf, - image_map: Any | None = ..., - li_tag_indent: int = ..., - table_line_separators: bool = ..., - ul_bullet_char=..., - heading_sizes: Any | None = ..., - **_, - ): ... - def width2unit(self, length): ... - def handle_data(self, data) -> None: ... - def box_shadow(self, w, h, bgcolor) -> None: ... - def output_table_header(self) -> None: ... - tfooter_out: bool - def output_table_footer(self) -> None: ... - def output_table_sep(self) -> None: ... - font_face: Any - table_offset: Any - def handle_starttag(self, tag, attrs) -> None: ... - tbody: Any - def handle_endtag(self, tag) -> None: ... - h: Any - def set_font(self, face: Any | None = ..., size: Any | None = ...) -> None: ... - def set_style(self, tag: Any | None = ..., enable: bool = ...) -> None: ... - def set_text_color(self, r: Any | None = ..., g: int = ..., b: int = ...) -> None: ... - def put_link(self, txt) -> None: ... - def render_toc(self, pdf, outline) -> None: ... - def error(self, message: str) -> None: ... - -class HTMLMixin: - HTML2FPDF_CLASS: Any - def write_html(self, text, *args, **kwargs) -> None: ... diff --git a/stubs/fpdf2/fpdf/image_parsing.pyi b/stubs/fpdf2/fpdf/image_parsing.pyi deleted file mode 100644 index 6355b3adf3c2..000000000000 --- a/stubs/fpdf2/fpdf/image_parsing.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any, Tuple -from typing_extensions import Literal - -_ImageFilter = Literal["AUTO", "FlateDecode", "DCTDecode", "JPXDecode"] - -SUPPORTED_IMAGE_FILTERS: Tuple[_ImageFilter, ...] - -def load_image(filename): ... - -# Returned dict could be typed as a TypedDict. -def get_img_info(img, image_filter: _ImageFilter = ..., dims: Any | None = ...) -> dict[str, Any]: ... diff --git a/stubs/fpdf2/fpdf/outline.pyi b/stubs/fpdf2/fpdf/outline.pyi deleted file mode 100644 index 0df21fb1a58b..000000000000 --- a/stubs/fpdf2/fpdf/outline.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any, NamedTuple - -from .structure_tree import StructElem -from .syntax import Destination, PDFObject - -class OutlineSection(NamedTuple): - name: str - level: str - page_number: int - dest: Destination - struct_elem: StructElem | None = ... - -class OutlineItemDictionary(PDFObject): - title: str - parent: Any | None - prev: Any | None - next: Any | None - first: Any | None - last: Any | None - count: int - dest: str | None - struct_elem: StructElem | None - def __init__(self, title: str, dest: str | None = ..., struct_elem: StructElem | None = ..., **kwargs) -> None: ... - -class OutlineDictionary(PDFObject): - type: str - first: Any | None - last: Any | None - count: int - def __init__(self, **kwargs) -> None: ... - -def serialize_outline(sections, first_object_id: int = ..., fpdf: Any | None = ...): ... diff --git a/stubs/fpdf2/fpdf/recorder.pyi b/stubs/fpdf2/fpdf/recorder.pyi deleted file mode 100644 index 6401da5362ed..000000000000 --- a/stubs/fpdf2/fpdf/recorder.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -class FPDFRecorder: - pdf: Any - accept_page_break: bool - def __init__(self, pdf, accept_page_break: bool = ...) -> None: ... - def __getattr__(self, name): ... - def rewind(self) -> None: ... - def replay(self) -> None: ... - -class CallRecorder: - def __init__(self, func, calls) -> None: ... - def __call__(self, *args, **kwargs): ... diff --git a/stubs/fpdf2/fpdf/structure_tree.pyi b/stubs/fpdf2/fpdf/structure_tree.pyi deleted file mode 100644 index b8bc849b3d19..000000000000 --- a/stubs/fpdf2/fpdf/structure_tree.pyi +++ /dev/null @@ -1,52 +0,0 @@ -from typing import Any, NamedTuple - -from .syntax import PDFObject - -class MarkedContent(NamedTuple): - page_object_id: int - struct_parents_id: int - struct_type: str - mcid: int | None = ... - title: str | None = ... - alt_text: str | None = ... - -class NumberTree(PDFObject): - nums: Any - def __init__(self, **kwargs) -> None: ... - def serialize(self, fpdf: Any | None = ..., obj_dict: Any | None = ...): ... - -class StructTreeRoot(PDFObject): - type: str - parent_tree: Any - k: Any - def __init__(self, **kwargs) -> None: ... - -class StructElem(PDFObject): - type: str - s: Any - p: Any - k: Any - pg: Any - t: Any - alt: Any - def __init__( - self, - struct_type: str, - parent: PDFObject, - kids: list[int] | list[StructElem], - page: PDFObject | None = ..., - title: str | None = ..., - alt: str | None = ..., - **kwargs, - ) -> None: ... - -class StructureTreeBuilder: - struct_tree_root: Any - doc_struct_elem: Any - struct_elem_per_mc: Any - def __init__(self) -> None: ... - def add_marked_content(self, marked_content) -> None: ... - def next_mcid_for_page(self, page_object_id): ... - def empty(self): ... - def serialize(self, first_object_id: int = ..., fpdf: Any | None = ...): ... - def assign_ids(self, n): ... diff --git a/stubs/fpdf2/fpdf/syntax.pyi b/stubs/fpdf2/fpdf/syntax.pyi deleted file mode 100644 index 54788032540a..000000000000 --- a/stubs/fpdf2/fpdf/syntax.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from abc import ABC -from typing import Any, List - -def clear_empty_fields(d): ... -def create_dictionary_string( - dict_, - open_dict: str = ..., - close_dict: str = ..., - field_join: str = ..., - key_value_join: str = ..., - has_empty_fields: bool = ..., -): ... -def create_list_string(list_): ... -def iobj_ref(n): ... -def create_stream(stream): ... - -class PDFObject: - def __init__(self, id: Any | None = ...) -> None: ... - @property - def id(self): ... - @id.setter - def id(self, n) -> None: ... - @property - def ref(self): ... - def serialize(self, fpdf: Any | None = ..., obj_dict: Any | None = ...): ... - -def camel_case(property_name): ... - -class PDFString(str): - def serialize(self): ... - -class PDFArray(List[Any]): - def serialize(self): ... - -class Destination(ABC): - def as_str(self, pdf: Any | None = ...) -> None: ... - -class DestinationXYZ(Destination): - page: Any - x: Any - y: Any - zoom: Any - page_as_obj_id: Any - def __init__(self, page, x: int = ..., y: int = ..., zoom: str = ..., page_as_obj_id: bool = ...) -> None: ... - def as_str(self, pdf: Any | None = ...): ... diff --git a/stubs/fpdf2/fpdf/template.pyi b/stubs/fpdf2/fpdf/template.pyi deleted file mode 100644 index 8ab4d6cb970c..000000000000 --- a/stubs/fpdf2/fpdf/template.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Any - -class FlexTemplate: - pdf: Any - splitting_pdf: Any - handlers: Any - texts: Any - def __init__(self, pdf, elements: Any | None = ...) -> None: ... - elements: Any - keys: Any - def load_elements(self, elements) -> None: ... - def parse_csv(self, infile, delimiter: str = ..., decimal_sep: str = ..., encoding: Any | None = ...): ... - def __setitem__(self, name, value) -> None: ... - set: Any - def __contains__(self, name): ... - def __getitem__(self, name): ... - def split_multicell(self, text, element_name): ... - def render(self, offsetx: float = ..., offsety: float = ..., rotate: float = ..., scale: float = ...): ... - -class Template(FlexTemplate): - def __init__( - self, - infile: Any | None = ..., - elements: Any | None = ..., - format: str = ..., - orientation: str = ..., - unit: str = ..., - title: str = ..., - author: str = ..., - subject: str = ..., - creator: str = ..., - keywords: str = ..., - ) -> None: ... - def add_page(self) -> None: ... - def render(self, outfile: Any | None = ..., dest: Any | None = ...) -> None: ... # type: ignore[override] diff --git a/stubs/fpdf2/fpdf/transitions.pyi b/stubs/fpdf2/fpdf/transitions.pyi deleted file mode 100644 index c1d692275e78..000000000000 --- a/stubs/fpdf2/fpdf/transitions.pyi +++ /dev/null @@ -1,58 +0,0 @@ -from abc import ABC -from typing import Any - -class Transition(ABC): - def dict_as_string(self) -> None: ... - -class SplitTransition(Transition): - dimension: Any - direction: Any - def __init__(self, dimension, direction) -> None: ... - def dict_as_string(self): ... - -class BlindsTransition(Transition): - dimension: Any - def __init__(self, dimension) -> None: ... - def dict_as_string(self): ... - -class BoxTransition(Transition): - direction: Any - def __init__(self, direction) -> None: ... - def dict_as_string(self): ... - -class WipeTransition(Transition): - direction: Any - def __init__(self, direction) -> None: ... - def dict_as_string(self): ... - -class DissolveTransition(Transition): - def dict_as_string(self): ... - -class GlitterTransition(Transition): - direction: Any - def __init__(self, direction) -> None: ... - def dict_as_string(self): ... - -class FlyTransition(Transition): - dimension: Any - direction: Any - def __init__(self, dimension, direction: Any | None = ...) -> None: ... - def dict_as_string(self): ... - -class PushTransition(Transition): - direction: Any - def __init__(self, direction) -> None: ... - def dict_as_string(self): ... - -class CoverTransition(Transition): - direction: Any - def __init__(self, direction) -> None: ... - def dict_as_string(self): ... - -class UncoverTransition(Transition): - direction: Any - def __init__(self, direction) -> None: ... - def dict_as_string(self): ... - -class FadeTransition(Transition): - def dict_as_string(self): ... diff --git a/stubs/fpdf2/fpdf/ttfonts.pyi b/stubs/fpdf2/fpdf/ttfonts.pyi deleted file mode 100644 index 84990f260693..000000000000 --- a/stubs/fpdf2/fpdf/ttfonts.pyi +++ /dev/null @@ -1,72 +0,0 @@ -from typing import Any - -GF_WORDS: Any -GF_SCALE: Any -GF_MORE: Any -GF_XYSCALE: Any -GF_TWOBYTWO: Any - -def sub32(x, y): ... -def calcChecksum(data): ... - -class TTFontFile: - maxStrLenRead: int - def __init__(self) -> None: ... - filename: Any - charWidths: Any - glyphPos: Any - charToGlyph: Any - tables: Any - otables: Any - ascent: int - descent: int - version: Any - def getMetrics(self, file) -> None: ... - numTables: Any - searchRange: Any - entrySelector: Any - rangeShift: Any - def readTableDirectory(self) -> None: ... - def get_table_pos(self, tag): ... - def seek(self, pos) -> None: ... - def skip(self, delta) -> None: ... - def seek_table(self, tag, offset_in_table: int = ...): ... - def read_tag(self): ... - def read_short(self): ... - def read_ushort(self): ... - def read_ulong(self): ... - def get_ushort(self, pos): ... - @staticmethod - def splice(stream, offset, value): ... - def get_chunk(self, pos, length): ... - def get_table(self, tag): ... - def add(self, tag, data) -> None: ... - sFamilyClass: int - sFamilySubClass: int - name: Any - familyName: Any - styleName: Any - fullName: Any - uniqueFontID: Any - unitsPerEm: Any - bbox: Any - capHeight: Any - stemV: Any - italicAngle: Any - underlinePosition: Any - underlineThickness: Any - flags: int - def extractInfo(self) -> None: ... - maxUni: int - codeToGlyph: Any - glyphdata: Any - def makeSubset(self, file, subset): ... - def getGlyphs(self, originalGlyphIdx, nonlocals) -> None: ... - defaultWidth: Any - def getHMTX(self, numberOfHMetrics, numGlyphs, glyphToChar, scale) -> None: ... - def getHMetric(self, numberOfHMetrics, gid): ... - def getLOCA(self, indexToLocFormat, numGlyphs) -> None: ... - maxUniChar: int - def getCMAP4(self, unicode_cmap_offset, glyphToChar, charToGlyph) -> None: ... - def getCMAP12(self, unicode_cmap_offset, glyphToChar, charToGlyph) -> None: ... - def endTTFile(self, stm): ... diff --git a/stubs/fpdf2/fpdf/util.pyi b/stubs/fpdf2/fpdf/util.pyi deleted file mode 100644 index 0455c3f2a6b8..000000000000 --- a/stubs/fpdf2/fpdf/util.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from collections.abc import Iterable -from typing import Any, Tuple -from typing_extensions import Literal - -_Unit = Literal["pt", "mm", "cm", "in"] - -def substr(s, start, length: int = ...): ... -def enclose_in_parens(s): ... -def escape_parens(s): ... -def b(s): ... -def get_scale_factor(unit: _Unit | float) -> float: ... -def convert_unit( - # to_convert has a recursive type - to_convert: float | Iterable[float | Iterable[Any]], - old_unit: str | float, - new_unit: str | float, -) -> float | Tuple[float, ...]: ... -def dochecks() -> None: ... diff --git a/stubs/freezegun/METADATA.toml b/stubs/freezegun/METADATA.toml deleted file mode 100644 index c9f594bd7bbd..000000000000 --- a/stubs/freezegun/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "1.1.*" diff --git a/stubs/freezegun/freezegun/__init__.pyi b/stubs/freezegun/freezegun/__init__.pyi deleted file mode 100644 index 1de0916f79df..000000000000 --- a/stubs/freezegun/freezegun/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from .api import freeze_time as freeze_time diff --git a/stubs/freezegun/freezegun/api.pyi b/stubs/freezegun/freezegun/api.pyi deleted file mode 100644 index d2aaaf4a19ea..000000000000 --- a/stubs/freezegun/freezegun/api.pyi +++ /dev/null @@ -1,59 +0,0 @@ -from collections.abc import Awaitable, Callable, Iterator, Sequence -from datetime import date, datetime, timedelta -from numbers import Real -from typing import Any, Type, TypeVar, Union, overload - -_T = TypeVar("_T") -_Freezable = Union[str, datetime, date, timedelta] - -class TickingDateTimeFactory(object): - def __init__(self, time_to_freeze: datetime, start: datetime) -> None: ... - def __call__(self) -> datetime: ... - -class FrozenDateTimeFactory(object): - def __init__(self, time_to_freeze: datetime) -> None: ... - def __call__(self) -> datetime: ... - def tick(self, delta: float | Real | timedelta = ...) -> None: ... - def move_to(self, target_datetime: _Freezable | None) -> None: ... - -class StepTickTimeFactory(object): - def __init__(self, time_to_freeze: datetime, step_width: float) -> None: ... - def __call__(self) -> datetime: ... - def tick(self, delta: timedelta | None = ...) -> None: ... - def update_step_width(self, step_width: float) -> None: ... - def move_to(self, target_datetime: _Freezable | None) -> None: ... - -class _freeze_time: - def __init__( - self, - time_to_freeze_str: _Freezable | None, - tz_offset: float, - ignore: Sequence[str], - tick: bool, - as_arg: bool, - as_kwarg: str, - auto_tick_seconds: float, - ) -> None: ... - @overload - def __call__(self, func: Type[_T]) -> Type[_T]: ... - @overload - def __call__(self, func: Callable[..., Awaitable[_T]]) -> Callable[..., Awaitable[_T]]: ... - @overload - def __call__(self, func: Callable[..., _T]) -> Callable[..., _T]: ... - def __enter__(self) -> FrozenDateTimeFactory | StepTickTimeFactory: ... - def __exit__(self, *args: Any) -> None: ... - def start(self) -> Any: ... - def stop(self) -> None: ... - def decorate_class(self, klass: Type[_T]) -> _T: ... - def decorate_coroutine(self, coroutine: _T) -> _T: ... - def decorate_callable(self, func: Callable[..., _T]) -> Callable[..., _T]: ... - -def freeze_time( - time_to_freeze: _Freezable | Callable[..., _Freezable] | Iterator[_Freezable] | None = ..., - tz_offset: float | None = ..., - ignore: Sequence[str] | None = ..., - tick: bool | None = ..., - as_arg: bool | None = ..., - as_kwarg: str | None = ..., - auto_tick_seconds: float | None = ..., -) -> _freeze_time: ... diff --git a/stubs/frozendict/@tests/stubtest_allowlist.txt b/stubs/frozendict/@tests/stubtest_allowlist.txt deleted file mode 100644 index 8941c269fbee..000000000000 --- a/stubs/frozendict/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,5 +0,0 @@ -frozendict.FrozenOrderedDict -frozendict.frozendict.__hash__ -frozendict.frozendict.__new__ -frozendict.frozendict.__repr__ -frozendict.frozendict.copy diff --git a/stubs/frozendict/METADATA.toml b/stubs/frozendict/METADATA.toml deleted file mode 100644 index 58bc38349459..000000000000 --- a/stubs/frozendict/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "2.0.*" diff --git a/stubs/frozendict/frozendict.pyi b/stubs/frozendict/frozendict.pyi deleted file mode 100644 index 10c78c8e646d..000000000000 --- a/stubs/frozendict/frozendict.pyi +++ /dev/null @@ -1,27 +0,0 @@ -import collections -from typing import Any, Generic, Iterable, Iterator, Mapping, Type, TypeVar, overload - -_S = TypeVar("_S") -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - -class frozendict(Mapping[_KT, _VT], Generic[_KT, _VT]): - - dict_cls: Type[dict[Any, Any]] = ... - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, mapping: Mapping[_KT, _VT]) -> None: ... - @overload - def __init__(self, iterable: Iterable[tuple[_KT, _VT]]) -> None: ... - def __getitem__(self, key: _KT) -> _VT: ... - def __contains__(self, key: object) -> bool: ... - def copy(self: _S, **add_or_replace: _VT) -> _S: ... - def __iter__(self) -> Iterator[_KT]: ... - def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __hash__(self) -> int: ... - -class FrozenOrderedDict(frozendict[_KT, _VT]): - - dict_cls: Type[collections.OrderedDict[Any, Any]] = ... diff --git a/stubs/futures/@python2/concurrent/futures/__init__.pyi b/stubs/futures/@python2/concurrent/futures/__init__.pyi deleted file mode 100644 index 1f93f021f4e8..000000000000 --- a/stubs/futures/@python2/concurrent/futures/__init__.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from ._base import ( - ALL_COMPLETED as ALL_COMPLETED, - FIRST_COMPLETED as FIRST_COMPLETED, - FIRST_EXCEPTION as FIRST_EXCEPTION, - CancelledError as CancelledError, - Executor as Executor, - Future as Future, - TimeoutError as TimeoutError, - as_completed as as_completed, - wait as wait, -) -from .process import ProcessPoolExecutor as ProcessPoolExecutor -from .thread import ThreadPoolExecutor as ThreadPoolExecutor diff --git a/stubs/futures/@python2/concurrent/futures/_base.pyi b/stubs/futures/@python2/concurrent/futures/_base.pyi deleted file mode 100644 index 40a986279f04..000000000000 --- a/stubs/futures/@python2/concurrent/futures/_base.pyi +++ /dev/null @@ -1,92 +0,0 @@ -import threading -from abc import abstractmethod -from logging import Logger -from types import TracebackType -from typing import Any, Callable, Container, Generic, Iterable, Iterator, List, Optional, Protocol, Set, Tuple, TypeVar - -FIRST_COMPLETED: str -FIRST_EXCEPTION: str -ALL_COMPLETED: str -PENDING: str -RUNNING: str -CANCELLED: str -CANCELLED_AND_NOTIFIED: str -FINISHED: str -LOGGER: Logger - -class Error(Exception): ... -class CancelledError(Error): ... -class TimeoutError(Error): ... - -_T = TypeVar("_T") - -_T_co = TypeVar("_T_co", covariant=True) - -# Copied over Collection implementation as it does not exist in Python 2 and <3.6. -# Also to solve pytype issues with _Collection. -class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - -class Future(Generic[_T]): - def __init__(self) -> None: ... - def cancel(self) -> bool: ... - def cancelled(self) -> bool: ... - def running(self) -> bool: ... - def done(self) -> bool: ... - def add_done_callback(self, fn: Callable[[Future[_T]], Any]) -> None: ... - def result(self, timeout: Optional[float] = ...) -> _T: ... - def set_running_or_notify_cancel(self) -> bool: ... - def set_result(self, result: _T) -> None: ... - def exception(self, timeout: Optional[float] = ...) -> Any: ... - def exception_info(self, timeout: Optional[float] = ...) -> Tuple[Any, Optional[TracebackType]]: ... - def set_exception(self, exception: Any) -> None: ... - def set_exception_info(self, exception: Any, traceback: Optional[TracebackType]) -> None: ... - -class Executor: - def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... - def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ...) -> Iterator[_T]: ... - def shutdown(self, wait: bool = ...) -> None: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Optional[bool]: ... - -def as_completed(fs: Iterable[Future[_T]], timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... -def wait( - fs: _Collection[Future[_T]], timeout: Optional[float] = ..., return_when: str = ... -) -> Tuple[Set[Future[_T]], Set[Future[_T]]]: ... - -class _Waiter: - event: threading.Event - finished_futures: List[Future[Any]] - def __init__(self) -> None: ... - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... - -class _AsCompletedWaiter(_Waiter): - lock: threading.Lock - def __init__(self) -> None: ... - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... - -class _FirstCompletedWaiter(_Waiter): - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... - -class _AllCompletedWaiter(_Waiter): - num_pending_calls: int - stop_on_exception: bool - lock: threading.Lock - def __init__(self, num_pending_calls: int, stop_on_exception: bool) -> None: ... - def add_result(self, future: Future[Any]) -> None: ... - def add_exception(self, future: Future[Any]) -> None: ... - def add_cancelled(self, future: Future[Any]) -> None: ... - -class _AcquireFutures: - futures: Iterable[Future[Any]] - def __init__(self, futures: Iterable[Future[Any]]) -> None: ... - def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... diff --git a/stubs/futures/@python2/concurrent/futures/process.pyi b/stubs/futures/@python2/concurrent/futures/process.pyi deleted file mode 100644 index d56902c48a17..000000000000 --- a/stubs/futures/@python2/concurrent/futures/process.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any, Optional - -from ._base import Executor - -EXTRA_QUEUED_CALLS: Any - -class ProcessPoolExecutor(Executor): - def __init__(self, max_workers: Optional[int] = ...) -> None: ... diff --git a/stubs/futures/@python2/concurrent/futures/thread.pyi b/stubs/futures/@python2/concurrent/futures/thread.pyi deleted file mode 100644 index 6e272f38dde9..000000000000 --- a/stubs/futures/@python2/concurrent/futures/thread.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any, Callable, Generic, Iterable, Mapping, Optional, TypeVar - -from ._base import Executor, Future - -_S = TypeVar("_S") - -class ThreadPoolExecutor(Executor): - def __init__(self, max_workers: Optional[int] = ..., thread_name_prefix: str = ...) -> None: ... - -class _WorkItem(Generic[_S]): - future: Future[_S] - fn: Callable[..., _S] - args: Iterable[Any] - kwargs: Mapping[str, Any] - def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... - def run(self) -> None: ... diff --git a/stubs/futures/METADATA.toml b/stubs/futures/METADATA.toml deleted file mode 100644 index 103ece479fa8..000000000000 --- a/stubs/futures/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "3.3.*" -python2 = true diff --git a/stubs/gdb/@tests/stubtest_allowlist.txt b/stubs/gdb/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0defd3d50977 --- /dev/null +++ b/stubs/gdb/@tests/stubtest_allowlist.txt @@ -0,0 +1,83 @@ +# Internal list of packages to auto-load +gdb.packages +gdb.GdbSetPythonDirectory + +# optional method, only called when present +gdb.Command.complete +gdb.FinishBreakpoint.out_of_scope +gdb.Parameter.get_set_string +gdb.Parameter.get_show_string + +# TODO: abstract/optional methods to be implemented by subclasses +# gdb.FinishBreakpoint.out_of_scope +gdb.Breakpoint.stop +gdb.Command.invoke +gdb.Function.invoke +gdb.MICommand.invoke + +# TODO: investigate why they are not present at runtime +gdb.Instruction +gdb.LazyString +gdb.Membuf +gdb.Record +gdb.RecordFunctionSegment +gdb.RecordGap +gdb.RecordInstruction +gdb.TuiWindow + +# python implementation of built-in commands +gdb.command +gdb.command.explore +gdb.command.frame_filters +gdb.command.missing_debug +gdb.command.pretty_printers +gdb.command.prompt +gdb.command.type_printers +gdb.command.unwinders +gdb.command.xmethods + +# implementing internal convenience functions +gdb.function +gdb.function.as_string +gdb.function.caller_is +gdb.function.strfns + +# internal workers for frame filters +gdb.frames +gdb.FrameDecorator.FrameVars + +# function is only called when it's present +gdb.prompt_hook + +# internal methods used in the public gdb.prompt.substitute_prompt +gdb.prompt.prompt_help +gdb.prompt.prompt_substitutions + +# internal module to register a printer for mpx_bound128 type +gdb.printer +gdb.printer.bound_registers + +gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter +gdb.printing.add_builtin_pretty_printer + +# internal methods for colorful commandline output +gdb.styling + +# internal worker for SimpleXMethodMatcher +gdb.xmethod.SimpleXMethodMatcher.SimpleXMethodWorker + +# list of registered xmethods to be added by xmethod.register_xmethod_matcher() +gdb.xmethods +gdb.Objfile.xmethods +gdb.Progspace.xmethods + +# stubtest thinks this can't be sub-classed at runtime, but it is +gdb.disassembler.DisassemblerPart + +gdb.TuiEnabledEvent +gdb.events.tui_enabled + +gdb.Progspace.missing_debug_handlers +gdb.missing_debug_handlers +gdb.missing_files +gdb.missing_objfile diff --git a/stubs/gdb/METADATA.toml b/stubs/gdb/METADATA.toml new file mode 100644 index 000000000000..5fcf687ea80b --- /dev/null +++ b/stubs/gdb/METADATA.toml @@ -0,0 +1,16 @@ +version = "16.3.*" +# This is the official web portal for the GDB Git repo, +# see https://sourceware.org/gdb/current/ for other ways of obtaining the source code. +upstream-repository = "https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=tree" +extra-description = """\ + Type hints for GDB's \ + [Python API](https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html). \ + Note that this API is available only when running Python scripts under GDB: \ + it is not possible to install the `gdb` package separately, for instance \ + using `pip`.\ +""" + +[tool.stubtest] +skip = true # https://github.com/python/typeshed/issues/15236 +ci-platforms = ["linux"] +apt-dependencies = ["gdb"] diff --git a/stubs/gdb/gdb/FrameDecorator.pyi b/stubs/gdb/gdb/FrameDecorator.pyi new file mode 100644 index 000000000000..5ec95901e46a --- /dev/null +++ b/stubs/gdb/gdb/FrameDecorator.pyi @@ -0,0 +1,24 @@ +from collections.abc import Iterator +from typing import Protocol + +import gdb + +class SymValueWrapper(Protocol): + def symbol(self) -> gdb.Symbol | str: ... + def value(self) -> gdb._ValueOrNative | None: ... + +class _FrameDecoratorBase: + def __init__(self, base: gdb.Frame | FrameDecorator) -> None: ... + def elided(self) -> Iterator[gdb.Frame] | None: ... + def function(self) -> str | None: ... + def address(self) -> int | None: ... + def line(self) -> int | None: ... + def frame_args(self) -> Iterator[SymValueWrapper] | None: ... + def frame_locals(self) -> Iterator[SymValueWrapper] | None: ... + def inferior_frame(self) -> gdb.Frame: ... + +class FrameDecorator(_FrameDecoratorBase): + def filename(self) -> str | None: ... + +class DAPFrameDecorator(_FrameDecoratorBase): + def filename(self) -> str | None: ... diff --git a/stubs/gdb/gdb/FrameIterator.pyi b/stubs/gdb/gdb/FrameIterator.pyi new file mode 100644 index 000000000000..26e1dd436012 --- /dev/null +++ b/stubs/gdb/gdb/FrameIterator.pyi @@ -0,0 +1,8 @@ +import gdb + +class FrameIterator: + frame: gdb.Frame + + def __init__(self, frame_obj: gdb.Frame) -> None: ... + def __iter__(self) -> FrameIterator: ... + def __next__(self) -> gdb.Frame: ... diff --git a/stubs/gdb/gdb/__init__.pyi b/stubs/gdb/gdb/__init__.pyi new file mode 100644 index 000000000000..5911d37ab914 --- /dev/null +++ b/stubs/gdb/gdb/__init__.pyi @@ -0,0 +1,1051 @@ +# The GDB Python API is implemented in C, so the type hints below were made +# reading the documentation +# (https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html). + +import _typeshed +import threading +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager +from typing import Any, Final, Generic, Literal, Protocol, TypeAlias, TypedDict, TypeVar, final, overload, type_check_only +from typing_extensions import deprecated, disjoint_base + +import gdb.FrameDecorator +import gdb.types +from gdb.missing_debug import MissingDebugHandler +from gdb.missing_files import MissingFileHandler + +# The following submodules are automatically imported +from . import events as events, printing as printing, prompt as prompt, types as types + +# Basic + +VERSION: str +HOST_CONFIG: str +TARGET_CONFIG: str + +PYTHONDIR: str + +STDOUT: int +STDERR: int +STDLOG: int + +@overload +def execute(command: str, from_tty: bool = False, to_string: Literal[False] = False) -> None: ... +@overload +def execute(command: str, *, to_string: Literal[True]) -> str: ... +@overload +def execute(command: str, from_tty: bool, to_string: Literal[True]) -> str: ... +@overload +def execute(command: str, from_tty: bool = False, to_string: bool = False) -> str | None: ... + +def breakpoints() -> Sequence[Breakpoint]: ... +def rbreak(regex: str, minsyms: bool = ..., throttle: int = ..., symtabs: Iterator[Symtab] = ...) -> list[Breakpoint]: ... +def parameter(parameter: str, /) -> bool | int | str | None: ... +def set_parameter(name: str, value: bool | int | str | None) -> None: ... +def with_parameter(name: str, value: bool | int | str | None) -> AbstractContextManager[None]: ... +def history(number: int, /) -> Value: ... +def add_history(value: Value, /) -> int: ... +def history_count() -> int: ... +def convenience_variable(name: str, /) -> Value | None: ... +def set_convenience_variable(name: str, value: _ValueOrNative | None, /) -> None: ... +def parse_and_eval(expression: str, global_context: bool = False) -> Value: ... +def format_address(address: int, progspace: Progspace = ..., architecture: Architecture = ...): ... +def find_pc_line(pc: int | Value) -> Symtab_and_line: ... +def post_event(event: Callable[[], object], /) -> None: ... +def write(string: str, stream: int = ...) -> None: ... +def flush(stream: int = ...) -> None: ... +def target_charset() -> str: ... +def target_wide_charset() -> str: ... +def host_charset() -> str: ... +def solib_name(addr: int) -> str | None: ... +def decode_line(expression: str = ..., /) -> tuple[str | None, tuple[Symtab_and_line, ...] | None]: ... +def architecture_names() -> list[str]: ... +def connections() -> list[TargetConnection]: ... + +prompt_hook: Callable[[str], str | None] + +# Exceptions + +class error(RuntimeError): ... +class MemoryError(error): ... +class GdbError(Exception): ... + +# Values + +_ValueOrNative: TypeAlias = bool | int | float | str | Value | LazyString +_ValueOrInt: TypeAlias = Value | int + +@disjoint_base +class Value: + address: Value | None + is_optimized_out: bool + type: Type + dynamic_type: Type + is_lazy: bool + bytes: bytes + + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __add__(self, other: _ValueOrNative, /) -> Value: ... + def __radd__(self, other: _ValueOrNative, /) -> Value: ... + def __sub__(self, other: _ValueOrNative, /) -> Value: ... + def __rsub__(self, other: _ValueOrNative, /) -> Value: ... + def __mul__(self, other: _ValueOrNative, /) -> Value: ... + def __rmul__(self, other: _ValueOrNative, /) -> Value: ... + def __truediv__(self, other: _ValueOrNative, /) -> Value: ... + def __rtruediv__(self, other: _ValueOrNative, /) -> Value: ... + def __mod__(self, other: _ValueOrNative, /) -> Value: ... + def __rmod__(self, other: _ValueOrNative, /) -> Value: ... + def __pow__(self, other: _ValueOrNative, mod: None = None, /) -> Value: ... + def __and__(self, other: _ValueOrNative, /) -> Value: ... + def __or__(self, other: _ValueOrNative, /) -> Value: ... + def __xor__(self, other: _ValueOrNative, /) -> Value: ... + def __lshift__(self, other: _ValueOrNative, /) -> Value: ... + def __rshift__(self, other: _ValueOrNative, /) -> Value: ... + def __eq__(self, other: _ValueOrNative, /) -> bool: ... # type: ignore[override] + def __ne__(self, other: _ValueOrNative, /) -> bool: ... # type: ignore[override] + def __lt__(self, other: _ValueOrNative, /) -> bool: ... + def __le__(self, other: _ValueOrNative, /) -> bool: ... + def __gt__(self, other: _ValueOrNative, /) -> bool: ... + def __ge__(self, other: _ValueOrNative, /) -> bool: ... + def __getitem__(self, key: int | str | Field, /) -> Value: ... + def __call__(self, *args: _ValueOrNative) -> Value: ... + + @overload + def __init__(self, val: _ValueOrNative, type: None = None) -> None: ... + @overload + def __init__(self, val: _BufferType, type: Type) -> None: ... + + def cast(self, type: Type) -> Value: ... + def dereference(self) -> Value: ... + def referenced_value(self) -> Value: ... + def reference_value(self) -> Value: ... + def rvalue_reference_value(self) -> Value: ... + def const_value(self) -> Value: ... + def dynamic_cast(self, type: Type) -> Value: ... + def reinterpret_cast(self, type: Type) -> Value: ... + def format_string( + self, + raw: bool = ..., + pretty_arrays: bool = ..., + pretty_structs: bool = ..., + array_indexes: bool = ..., + symbols: bool = ..., + unions: bool = ..., + address: bool = ..., + styling: bool = ..., + nibbles: bool = ..., + deref_refs: bool = ..., + actual_objects: bool = ..., + static_members: bool = ..., + max_characters: int = ..., + max_elements: int = ..., + max_depth: int = ..., + repeat_threshold: int = ..., + format: str = ..., + ) -> str: ... + def string(self, encoding: str = ..., errors: str = ..., length: int = ...) -> str: ... + def lazy_string(self, encoding: str = ..., length: int = ...) -> LazyString: ... + def fetch_lazy(self) -> None: ... + def assign(self, val): ... + def to_array(self): ... + +# Types + +def lookup_type(name: str, block: Block = ...) -> Type: ... + +@final +class Type(Mapping[str, Field]): + alignof: int + code: int + dynamic: bool + name: str + sizeof: int + tag: str | None + objfile: Objfile | None + is_scalar: bool + is_signed: bool + is_array_like: bool + is_string_like: bool + + def fields(self) -> list[Field]: ... + def array(self, n1: int | Value, n2: int | Value = ...) -> Type: ... + def vector(self, n1: int, n2: int = ...) -> Type: ... + def iteritems(self) -> TypeIterator[tuple[str, Field]]: ... + def iterkeys(self) -> TypeIterator[str]: ... + def itervalues(self) -> TypeIterator[Field]: ... + def const(self) -> Type: ... + def volatile(self) -> Type: ... + def unqualified(self) -> Type: ... + def range(self) -> tuple[int, int]: ... + def reference(self) -> Type: ... + def pointer(self) -> Type: ... + def strip_typedefs(self) -> Type: ... + def target(self) -> Type: ... + def template_argument(self, n: int, block: Block = ...) -> Type: ... + def optimized_out(self) -> Value: ... + def get(self, key: str, default: Any = ...) -> Field | Any: ... + def has_key(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def __getitem__(self, key: str, /) -> Field: ... + def __iter__(self) -> TypeIterator[str]: ... + +_T = TypeVar("_T") + +@final +class TypeIterator(Iterator[_T]): + def __next__(self) -> _T: ... + +@final +class Field: + bitpos: int | None + enumval: int + name: str | None + artificial: bool + is_base_class: bool + bitsize: int + type: Type | None + parent_type: Type + +TYPE_CODE_BITSTRING: Final = -1 +TYPE_CODE_PTR: Final = 1 +TYPE_CODE_ARRAY: Final = 2 +TYPE_CODE_STRUCT: Final = 3 +TYPE_CODE_UNION: Final = 4 +TYPE_CODE_ENUM: Final = 5 +TYPE_CODE_FLAGS: Final = 6 +TYPE_CODE_FUNC: Final = 7 +TYPE_CODE_INT: Final = 8 +TYPE_CODE_FLT: Final = 9 +TYPE_CODE_VOID: Final = 10 +TYPE_CODE_SET: Final = 11 +TYPE_CODE_RANGE: Final = 12 +TYPE_CODE_STRING: Final = 13 +TYPE_CODE_ERROR: Final = 14 +TYPE_CODE_METHOD: Final = 15 +TYPE_CODE_METHODPTR: Final = 16 +TYPE_CODE_MEMBERPTR: Final = 17 +TYPE_CODE_REF: Final = 18 +TYPE_CODE_RVALUE_REF: Final = 19 +TYPE_CODE_CHAR: Final = 20 +TYPE_CODE_BOOL: Final = 21 +TYPE_CODE_COMPLEX: Final = 22 +TYPE_CODE_TYPEDEF: Final = 23 +TYPE_CODE_NAMESPACE: Final = 24 +TYPE_CODE_DECFLOAT: Final = 25 +TYPE_CODE_MODULE: Final = 26 +TYPE_CODE_INTERNAL_FUNCTION: Final = 27 +TYPE_CODE_XMETHOD: Final = 28 +TYPE_CODE_FIXED_POINT: Final = 29 +TYPE_CODE_NAMELIST: Final = 30 + +SEARCH_UNDEF_DOMAIN: Final[int] +SEARCH_VAR_DOMAIN: Final[int] +SEARCH_STRUCT_DOMAIN: Final[int] +SEARCH_MODULE_DOMAIN: Final[int] +SEARCH_LABEL_DOMAIN: Final[int] +SEARCH_COMMON_BLOCK_DOMAIN: Final[int] +SEARCH_TYPE_DOMAIN: Final[int] +SEARCH_FUNCTION_DOMAIN: Final[int] + +# Pretty Printing + +@type_check_only +class _PrettyPrinter(Protocol): + # TODO: The "children" and "display_hint" methods are optional for + # pretty-printers. Unfortunately, there is no such thing as an optional + # method in the type system at the moment. + # + # def children(self) -> Iterator[tuple[str, _ValueOrNative]]: ... + # def display_hint(self) -> str | None: ... + def to_string(self) -> str | LazyString: ... + +_PrettyPrinterLookupFunction: TypeAlias = Callable[[Value], _PrettyPrinter | None] + +def default_visualizer(value: Value, /) -> _PrettyPrinter | None: ... + +# Selecting Pretty-Printers + +pretty_printers: list[_PrettyPrinterLookupFunction] +type_printers: list[gdb.types._TypePrinter] + +# Filtering Frames + +@type_check_only +class _FrameFilter(Protocol): + name: str + enabled: bool + priority: int + + def filter( + self, iterator: Iterator[gdb.FrameDecorator.FrameDecorator | gdb.FrameDecorator.DAPFrameDecorator] + ) -> Iterator[gdb.FrameDecorator.FrameDecorator | gdb.FrameDecorator.DAPFrameDecorator]: ... + +frame_filters: dict[str, _FrameFilter] + +# Unwinding Frames + +@final +class PendingFrame: + def read_register(self, register: str | RegisterDescriptor | int) -> Value: ... + def create_unwind_info(self, frame_id: object, /) -> UnwindInfo: ... + def architecture(self) -> Architecture: ... + def language(self): ... + def level(self) -> int: ... + def name(self) -> str: ... + def pc(self) -> int: ... + def block(self) -> Block: ... + def find_sal(self) -> Symtab_and_line: ... + def function(self) -> Symbol: ... + def is_valid(self) -> bool: ... + +@final +class UnwindInfo: + def add_saved_register(self, register: str | RegisterDescriptor | int, value: Value) -> None: ... + +@type_check_only +class _Unwinder(Protocol): + @property + def name(self) -> str: ... + enabled: bool + + def __call__(self, pending_frame: PendingFrame) -> UnwindInfo | None: ... + +frame_unwinders: list[_Unwinder] + +# Inferiors + +def inferiors() -> tuple[Inferior, ...]: ... +def selected_inferior() -> Inferior: ... + +_BufferType: TypeAlias = _typeshed.ReadableBuffer + +@final +class Inferior: + num: int + connection: TargetConnection | None + connection_num: int | None + pid: int + was_attached: bool + progspace: Progspace + main_name: str | None + + @property + def arguments(self) -> str | None: ... + @arguments.setter + def arguments(self, args: str | Sequence[str]) -> None: ... + + def is_valid(self) -> bool: ... + def threads(self) -> tuple[InferiorThread, ...]: ... + def architecture(self) -> Architecture: ... + def read_memory(self, address: _ValueOrInt, length: int) -> memoryview: ... + def write_memory(self, address: _ValueOrInt, buffer: _BufferType, length: int = ...) -> None: ... + def search_memory(self, address: _ValueOrInt, length: int, pattern: _BufferType) -> int | None: ... + def thread_from_handle(self, handle: Value) -> InferiorThread: ... + @deprecated("Use gdb.thread_from_handle() instead.") + def thread_from_thread_handle(self, handle: Value) -> InferiorThread: ... + def set_env(self, name: str, value: str) -> None: ... + def unset_env(self, name: str) -> None: ... + def clear_env(self) -> None: ... + +# Threads + +class Thread(threading.Thread): ... + +def selected_thread() -> InferiorThread: ... + +@final +class InferiorThread: + name: str | None + details: str | None + num: int + global_num: int + ptid: tuple[int, int, int] + ptid_string: str + inferior: Inferior + + def is_valid(self) -> bool: ... + def switch(self) -> None: ... + def is_stopped(self) -> bool: ... + def is_running(self) -> bool: ... + def is_exited(self) -> bool: ... + def handle(self) -> bytes: ... + +# Recordings + +def start_recording(method: str = ..., format: str = ..., /) -> Record: ... +def current_recording() -> Record | None: ... +def stop_recording() -> None: ... + +class Record: + method: str + format: str | None + begin: Instruction + end: Instruction + replay_position: Instruction | None + instruction_history: list[Instruction] + function_call_history: list[RecordFunctionSegment] + + def goto(self, instruction: Instruction, /) -> None: ... + def clear(self) -> None: ... + +class Instruction: + pc: int + data: memoryview + decoded: str + size: int + +class RecordInstruction(Instruction): + number: int + sal: Symtab_and_line | None + is_speculative: bool + +class RecordGap(Instruction): + number: int + error_code: int + error_string: str + +class RecordFunctionSegment: + number: int + symbol: Symbol | None + level: int | None + instructions: list[RecordInstruction | RecordGap] + up: RecordFunctionSegment | None + prev: RecordFunctionSegment | None + next: RecordFunctionSegment | None + +# CLI Commands + +@disjoint_base +class Command: + def __init__(self, name: str, command_class: int, completer_class: int = ..., prefix: bool = ...) -> None: ... + def dont_repeat(self) -> None: ... + def invoke(self, argument: str, from_tty: bool) -> None: ... + def complete(self, text: str, word: str) -> object: ... + +def string_to_argv(argv: str, /) -> list[str]: ... + +COMMAND_NONE: int +COMMAND_RUNNING: int +COMMAND_DATA: int +COMMAND_STACK: int +COMMAND_FILES: int +COMMAND_SUPPORT: int +COMMAND_STATUS: int +COMMAND_BREAKPOINTS: int +COMMAND_TRACEPOINTS: int +COMMAND_TUI: int +COMMAND_USER: int +COMMAND_OBSCURE: int +COMMAND_MAINTENANCE: int + +COMPLETE_NONE: int +COMPLETE_FILENAME: int +COMPLETE_LOCATION: int +COMPLETE_COMMAND: int +COMPLETE_SYMBOL: int +COMPLETE_EXPRESSION: int + +# GDB/MI Commands + +@disjoint_base +class MICommand: + name: str + installed: bool + + def __init__(self, name: str) -> None: ... + def invoke(self, arguments: list[str]) -> dict[str, object] | None: ... + +# Parameters + +@disjoint_base +class Parameter: + set_doc: str + show_doc: str + value: object + + def __init__(self, name: str, command_class: int, parameter_class: int, enum_sequence: Sequence[str] = ...) -> None: ... + def get_set_string(self) -> str: ... + def get_show_string(self, svalue: str) -> str: ... + +PARAM_BOOLEAN: int +PARAM_AUTO_BOOLEAN: int +PARAM_UINTEGER: int +PARAM_INTEGER: int +PARAM_STRING: int +PARAM_STRING_NOESCAPE: int +PARAM_OPTIONAL_FILENAME: int +PARAM_FILENAME: int +PARAM_ZINTEGER: int +PARAM_ZUINTEGER: int +PARAM_ZUINTEGER_UNLIMITED: int +PARAM_ENUM: int + +# Convenience functions + +class Function: + def __init__(self, name: str) -> None: ... + def invoke(self, *args: Value) -> _ValueOrNative: ... + +# Progspaces + +def current_progspace() -> Progspace | None: ... +def progspaces() -> Sequence[Progspace]: ... + +@final +class Progspace: + executable_filename: str | None + filename: str | None + symbol_file: Objfile | None + pretty_printers: list[_PrettyPrinterLookupFunction] + type_printers: list[gdb.types._TypePrinter] + frame_filters: dict[str, _FrameFilter] + frame_unwinders: list[_Unwinder] + missing_file_handlers: Sequence[tuple[Literal["debug"], MissingDebugHandler] | tuple[Literal["file"], MissingFileHandler]] + + def block_for_pc(self, pc: int, /) -> Block | None: ... + def find_pc_line(self, pc: int, /) -> Symtab_and_line: ... + def is_valid(self) -> bool: ... + def objfile_for_address(self, address: int, /) -> Objfile | None: ... + def objfiles(self) -> Sequence[Objfile]: ... + def solib_name(self, address: int, /) -> str | None: ... + +# Objfiles + +def current_objfile() -> Objfile | None: ... +def objfiles() -> list[Objfile]: ... +def lookup_objfile(name: str, by_build_id: bool = ...) -> Objfile | None: ... + +@final +class Objfile: + filename: str | None + username: str | None + owner: Objfile | None + build_id: str | None + progspace: Progspace | None + pretty_printers: list[_PrettyPrinterLookupFunction] + type_printers: list[gdb.types._TypePrinter] + frame_filters: dict[str, _FrameFilter] + frame_unwinders: list[_Unwinder] + is_file: bool + + def is_valid(self) -> bool: ... + def add_separate_debug_file(self, file: str) -> None: ... + def lookup_global_symbol(self, name: str, domain: int = ...) -> Symbol | None: ... + def lookup_static_symbol(self, name: str, domain: int = ...) -> Symbol | None: ... + +# Frames + +def selected_frame() -> Frame: ... +def newest_frame() -> Frame: ... +def frame_stop_reason_string(code: int, /) -> str: ... +def invalidate_cached_frames() -> None: ... + +NORMAL_FRAME: int +DUMMY_FRAME: int +INLINE_FRAME: int +TAILCALL_FRAME: int +SIGTRAMP_FRAME: int +ARCH_FRAME: int +SENTINEL_FRAME: int + +FRAME_UNWIND_NO_REASON: int +FRAME_UNWIND_NULL_ID: int +FRAME_UNWIND_OUTERMOST: int +FRAME_UNWIND_UNAVAILABLE: int +FRAME_UNWIND_INNER_ID: int +FRAME_UNWIND_SAME_ID: int +FRAME_UNWIND_NO_SAVED_PC: int +FRAME_UNWIND_MEMORY_ERROR: int + +@final +class Frame: + def is_valid(self) -> bool: ... + def name(self) -> str | None: ... + def architecture(self) -> Architecture: ... + def type(self) -> int: ... + def unwind_stop_reason(self) -> int: ... + def pc(self) -> int: ... + def block(self) -> Block: ... + def function(self) -> Symbol: ... + def older(self) -> Frame | None: ... + def newer(self) -> Frame | None: ... + def find_sal(self) -> Symtab_and_line: ... + def read_register(self, register: str | RegisterDescriptor | int) -> Value: ... + def read_var(self, variable: str | Symbol, block: Block | None = ...) -> Value: ... + def select(self) -> None: ... + def level(self) -> int: ... + def static_link(self) -> Frame | None: ... + def language(self): ... + +# Blocks + +def block_for_pc(pc: int) -> Block | None: ... + +@final +class Block: + start: int + end: int + function: Symbol | None + superblock: Block | None + global_block: Block + static_block: Block | None + is_global: bool + is_static: bool + + def is_valid(self) -> bool: ... + def __iter__(self) -> BlockIterator: ... + +@final +class BlockIterator: + def is_valid(self) -> bool: ... + def __iter__(self: _typeshed.Self) -> _typeshed.Self: ... + def __next__(self) -> Symbol: ... + +# Symbols + +def lookup_symbol(name: str, block: Block | None = ..., domain: int = ...) -> tuple[Symbol | None, bool]: ... +def lookup_global_symbol(name: str, domain: int = ...) -> Symbol | None: ... +def lookup_static_symbol(name: str, domain: int = ...) -> Symbol | None: ... +def lookup_static_symbols(name: str, domain: int = ...) -> list[Symbol]: ... + +@final +class Symbol: + type: Type | None + symtab: Symtab + line: int + name: str + linkage_name: str + print_name: str + addr_class: int + needs_frame: bool + is_argument: bool + is_constant: bool + is_function: bool + is_variable: bool + is_artificial: bool + + def is_valid(self) -> bool: ... + def value(self, frame: Frame = ..., /) -> Value: ... + +SYMBOL_UNDEF_DOMAIN: Final = 0 +SYMBOL_VAR_DOMAIN: Final = 1 +SYMBOL_STRUCT_DOMAIN: Final = 2 +SYMBOL_MODULE_DOMAIN: Final = 3 +SYMBOL_LABEL_DOMAIN: Final = 4 +SYMBOL_COMMON_BLOCK_DOMAIN: Final = 5 +SYMBOL_TYPE_DOMAIN: Final = 6 +SYMBOL_FUNCTION_DOMAIN: Final = 7 + +SYMBOL_LOC_UNDEF: Final = 0 +SYMBOL_LOC_CONST: Final = 1 +SYMBOL_LOC_STATIC: Final = 2 +SYMBOL_LOC_REGISTER: Final = 3 +SYMBOL_LOC_ARG: Final = 4 +SYMBOL_LOC_REF_ARG: Final = 5 +SYMBOL_LOC_REGPARM_ADDR: Final = 6 +SYMBOL_LOC_LOCAL: Final = 7 +SYMBOL_LOC_TYPEDEF: Final = 8 +SYMBOL_LOC_LABEL: Final = 9 +SYMBOL_LOC_BLOCK: Final = 10 +SYMBOL_LOC_CONST_BYTES: Final = 11 +SYMBOL_LOC_UNRESOLVED: Final = 12 +SYMBOL_LOC_OPTIMIZED_OUT: Final = 13 +SYMBOL_LOC_COMPUTED: Final = 14 +SYMBOL_LOC_COMMON_BLOCK: Final = 15 + +# Symbol tables + +@final +class Symtab_and_line: + symtab: Symtab + pc: int + last: int + line: int + + def is_valid(self) -> bool: ... + +@final +class Symtab: + filename: str + objfile: Objfile + producer: str + + def is_valid(self) -> bool: ... + def fullname(self) -> str: ... + def global_block(self) -> Block: ... + def static_block(self) -> Block: ... + def linetable(self) -> LineTable: ... + +# Line Tables + +@final +class LineTableEntry: + line: int + pc: int + +@final +class LineTableIterator(Iterator[LineTableEntry]): + def __next__(self) -> LineTableEntry: ... + def is_valid(self) -> bool: ... + +@final +class LineTable: + def __iter__(self) -> LineTableIterator: ... + def line(self, line: int, /) -> tuple[LineTableEntry, ...]: ... + def has_line(self, line: int, /) -> bool: ... + def source_lines(self) -> list[int]: ... + def is_valid(self) -> bool: ... + +# Breakpoints + +@disjoint_base +class Breakpoint: + # The where="spec" form of __init__(). See py-breakpoints.c:bppy_init():keywords for the positional order. + @overload + def __init__( + self, + # where + spec: str = ..., + # options + type: int = ..., + wp_class: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + + # The where="location" form of __init__(). A watchpoint (`type=BP_WATCHPOINT`) cannot be created with this form. + # + # We exclude the `wp_class` (watchpoint class) option here, even though py-breakpoints.c accepts it. It doesn't make sense + # unless type==BP_WATCHPOINT, and is silently ignored in those cases; allowing it in those cases is likely an oversight, not + # an intentional allowance. + # + # We repeat this 7 times because the type system doesn't have simple a way for us to say "at least one of `function`, `label`, + # or `line`", so we must repeat it for each combination of the 3. + # + # The len=3 combination. + @overload + def __init__( + self, + *, + # where + source: str = ..., + function: str, + label: str, + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + # The 3 len=2 combinations. + @overload + def __init__( + self, + *, + source: str = ..., + # where + label: str, + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + function: str, + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + function: str, + label: str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + # The 3 len=1 combinations. + @overload + def __init__( + self, + *, + source: str = ..., + # where + function: str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + label: str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + + # Methods. + def stop(self) -> bool: ... + def is_valid(self) -> bool: ... + def delete(self) -> None: ... + + enabled: bool + silent: bool + pending: bool + thread: int | None + task: str | None + ignore_count: int + number: int + type: int + visible: bool + temporary: bool + hit_count: int + location: str | None + locations: Sequence[BreakpointLocation] + inferior: int | None + expression: str | None + condition: str | None + commands: str | None + +@final +class BreakpointLocation: + address: int + enabled: bool + fullname: str + function: str | None + owner: Breakpoint + source: tuple[str, int] + thread_groups: Sequence[int] + +BP_NONE: int +BP_BREAKPOINT: int +BP_HARDWARE_BREAKPOINT: int +BP_WATCHPOINT: int +BP_HARDWARE_WATCHPOINT: int +BP_READ_WATCHPOINT: int +BP_ACCESS_WATCHPOINT: int +BP_CATCHPOINT: int + +WP_READ: int +WP_WRITE: int +WP_ACCESS: int + +# Finish Breakpoints + +@disjoint_base +class FinishBreakpoint(Breakpoint): + return_value: Value | None + + def __init__(self, frame: Frame = ..., internal: bool = ...) -> None: ... + def out_of_scope(self) -> None: ... + +# Lazy strings + +class LazyString: + def value(self) -> Value: ... + + address: Value + length: int + encoding: str + type: Type + +# Architectures + +@type_check_only +class _Instruction(TypedDict): + addr: int + asm: str + length: int + +@final +class Architecture: + def name(self) -> str: ... + def disassemble(self, start_pc: int, end_pc: int = ..., count: int = ...) -> list[_Instruction]: ... + def integer_type(self, size: int, signed: bool = ...) -> Type: ... + def registers(self, reggroup: str = ...) -> RegisterDescriptorIterator: ... + def register_groups(self) -> RegisterGroupsIterator: ... + +# Registers + +@final +class RegisterDescriptor: + name: str + +@final +class RegisterDescriptorIterator(Iterator[RegisterDescriptor]): + def __next__(self) -> RegisterDescriptor: ... + def find(self, name: str) -> RegisterDescriptor | None: ... + +@final +class RegisterGroup: + name: str + +@final +class RegisterGroupsIterator(Iterator[RegisterGroup]): + def __next__(self) -> RegisterGroup: ... + +# Connections + +@disjoint_base +class TargetConnection: + def is_valid(self) -> bool: ... + + num: int + type: str + description: str + details: str | None + +@final +class RemoteTargetConnection(TargetConnection): + def send_packet(self, packet: str | bytes) -> bytes: ... + +# TUI Windows + +def register_window_type(name: str, factory: Callable[[TuiWindow], _Window]) -> None: ... + +class TuiWindow: + width: int + height: int + title: str + + def is_valid(self) -> bool: ... + def erase(self) -> None: ... + def write(self, string: str, full_window: bool = ...) -> None: ... + +@type_check_only +class _Window(Protocol): + def close(self) -> None: ... + def render(self) -> None: ... + def hscroll(self, num: int) -> None: ... + def vscroll(self, num: int) -> None: ... + def click(self, x: int, y: int, button: int) -> None: ... + +# Events +@disjoint_base +class Event: ... + +class ThreadEvent(Event): + inferior_thread: InferiorThread + +class ContinueEvent(ThreadEvent): ... + +class ExitedEvent(Event): + exit_code: int + inferior: Inferior + +class ThreadExitedEvent(ThreadEvent): ... + +class StopEvent(ThreadEvent): + details: dict[str, object] + +class BreakpointEvent(StopEvent): + breakpoints: Sequence[Breakpoint] + breakpoint: Breakpoint + +class NewObjFileEvent(Event): + new_objfile: Objfile + +class FreeObjFileEvent(Event): + objfile: Objfile + +class ClearObjFilesEvent(Event): + progspace: Progspace + +class NewProgspaceEvent(Event): ... +class FreeProgspaceEvent(Event): ... + +class SignalEvent(StopEvent): + stop_signal: str + +@type_check_only +class _InferiorCallEvent(Event): ... + +class InferiorCallPreEvent(_InferiorCallEvent): + ptid: InferiorThread + address: Value + +class InferiorCallPostEvent(_InferiorCallEvent): + ptid: InferiorThread + address: Value + +class MemoryChangedEvent(Event): + address: Value + length: int + +class RegisterChangedEvent(Event): + frame: Frame + regnum: str + +class NewInferiorEvent(Event): + inferior: Inferior + +class InferiorDeletedEvent(Event): + inferior: Inferior + +class NewThreadEvent(ThreadEvent): ... + +class GdbExitingEvent(Event): + exit_code: int + +class ConnectionEvent(Event): + connection: TargetConnection + +class ExecutableChangedEvent(Event): ... + +class TuiEnabledEvent(Event): + enabled: bool + +_ET = TypeVar("_ET", bound=Event | Breakpoint | None) + +@final +class EventRegistry(Generic[_ET]): + def connect(self, object: Callable[[_ET], object], /) -> None: ... + def disconnect(self, object: Callable[[_ET], object], /) -> None: ... + +class ValuePrinter: ... + +def blocked_signals(): ... +def notify_mi(name: str, data: dict[str, object] | None = None): ... +def interrupt(): ... +def execute_mi(command: str, *args: str) -> dict[str, object]: ... diff --git a/stubs/gdb/gdb/dap/__init__.pyi b/stubs/gdb/gdb/dap/__init__.pyi new file mode 100644 index 000000000000..9c9c1931ee7e --- /dev/null +++ b/stubs/gdb/gdb/dap/__init__.pyi @@ -0,0 +1,21 @@ +from . import ( + breakpoint as breakpoint, + bt as bt, + evaluate as evaluate, + launch as launch, + locations as locations, + memory as memory, + modules as modules, + next as next, + pause as pause, + scopes as scopes, + sources as sources, + startup as startup, + threads as threads, +) +from .server import Server as Server + +def pre_command_loop() -> None: ... +def run() -> None: ... + +session_started: bool diff --git a/stubs/gdb/gdb/dap/breakpoint.pyi b/stubs/gdb/gdb/dap/breakpoint.pyi new file mode 100644 index 000000000000..6e96978e2f43 --- /dev/null +++ b/stubs/gdb/gdb/dap/breakpoint.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Sequence +from contextlib import AbstractContextManager +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +from .sources import Source + +@type_check_only +class _SourceBreakpoint(TypedDict): + source: str + line: int + condition: NotRequired[str | None] + hitCondition: NotRequired[str | None] + logMessage: NotRequired[str | None] + +@type_check_only +class _ExceptionFilterOptions(TypedDict): + filderId: str + condition: NotRequired[str | None] + +@type_check_only +class _BreakpointDescriptor(TypedDict): + id: int + verified: bool + reason: NotRequired[str] # only present when verified is False. Possibly only literal "pending" or "failed" + message: NotRequired[str] # only present when reason == "failed" + source: NotRequired[Source] + line: NotRequired[int] + instructionReference: NotRequired[str] + +@type_check_only +class _SetBreakpointResult(TypedDict): + breakpoints: list[_BreakpointDescriptor] + +# frozenset entries are tuples from _SourceBreakpoint.items() or _ExceptionFilterOptions.items() +breakpoint_map: dict[str, dict[frozenset[Incomplete], gdb.Breakpoint]] + +def suppress_new_breakpoint_event() -> AbstractContextManager[None]: ... +def set_breakpoint(*, source: Source, breakpoints: Sequence[_SourceBreakpoint] = (), **args: Unused) -> _SetBreakpointResult: ... +def set_fn_breakpoint(*, breakpoints: Sequence[_SourceBreakpoint], **args: Unused) -> _SetBreakpointResult: ... +def set_insn_breakpoints( + *, breakpoints: Sequence[_SourceBreakpoint], offset: int | None = None, **args: Unused +) -> _SetBreakpointResult: ... +def set_exception_breakpoints( + *, filters: Sequence[str], filterOptions: Sequence[_ExceptionFilterOptions] = (), **args: Unused +) -> _SetBreakpointResult: ... diff --git a/stubs/gdb/gdb/dap/bt.pyi b/stubs/gdb/gdb/dap/bt.pyi new file mode 100644 index 000000000000..0127cfbbaa0a --- /dev/null +++ b/stubs/gdb/gdb/dap/bt.pyi @@ -0,0 +1,49 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +from .sources import Source +from .varref import _ValueFormat + +@type_check_only +class _StackFrameFormat(_ValueFormat, total=False): + parameters: bool + parameterTypes: bool + parameterNames: bool + parameterValues: bool + line: bool + module: bool + includeAll: bool + +@type_check_only +class _StackFrame(TypedDict): + id: int + name: str + line: int + column: int + instructionPointerReference: str + moduleId: NotRequired[str | None] + source: NotRequired[Source] + +@type_check_only +class _StackTraceResult(TypedDict): + stackFrames: list[_StackFrame] + +def check_stack_frame( + *, + # From source: + # Note that StackFrameFormat extends ValueFormat, which is why + # "hex" appears here. + hex: bool = False, + parameters: bool = False, + parameterTypes: bool = False, + parameterNames: bool = False, + parameterValues: bool = False, + line: bool = False, + module: bool = False, + includeAll: bool = False, + **rest: Unused, +) -> _StackFrameFormat: ... +def stacktrace( + *, levels: int = 0, startFrame: int = 0, threadId: int, format: _StackFrameFormat | None = None, **extra: Unused +) -> _StackTraceResult: ... diff --git a/stubs/gdb/gdb/dap/disassemble.pyi b/stubs/gdb/gdb/dap/disassemble.pyi new file mode 100644 index 000000000000..387dbaf4b9bc --- /dev/null +++ b/stubs/gdb/gdb/dap/disassemble.pyi @@ -0,0 +1,22 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +from .sources import Source + +@type_check_only +class _Instruction(TypedDict): + address: str + instruction: str + instructionBytes: str + symbol: NotRequired[str] # only set if there's a corresponding label + line: NotRequired[int] # only set if source is available + location: NotRequired[Source] # only set if source is available + +@type_check_only +class _DisassembleResult(TypedDict): + instructions: list[_Instruction] + +def disassemble( + *, memoryReference: str, offset: int = 0, instructionOffset: int = 0, instructionCount: int, **extra: Unused +) -> _DisassembleResult: ... diff --git a/stubs/gdb/gdb/dap/evaluate.pyi b/stubs/gdb/gdb/dap/evaluate.pyi new file mode 100644 index 000000000000..04cd64085758 --- /dev/null +++ b/stubs/gdb/gdb/dap/evaluate.pyi @@ -0,0 +1,31 @@ +from _typeshed import Unused +from typing import Literal, TypedDict, type_check_only + +import gdb + +from .varref import VariableReference, _ValueFormat, _VariableReferenceDescriptor + +class EvaluateResult(VariableReference): + def __init__(self, value: gdb.Value) -> None: ... + +@type_check_only +class _VariablesResult(TypedDict): + variables: list[_VariableReferenceDescriptor] + +def eval_request( + *, + expression: str, + frameId: int | None = None, + context: Literal["watch", "variables", "hover", "repl"] = "variables", + format: _ValueFormat | None = None, + **args: Unused, +) -> _VariableReferenceDescriptor: ... +def variables( + *, variablesReference: int, start: int = 0, count: int = 0, format: _ValueFormat | None = None, **args: Unused +) -> _VariablesResult: ... +def set_expression( + *, expression: str, value: str, frameId: int | None = None, format: _ValueFormat | None = None, **args: Unused +) -> _VariableReferenceDescriptor: ... +def set_variable( + *, variablesReference: int, name: str, value: str, format: _ValueFormat | None = None, **args: Unused +) -> _VariableReferenceDescriptor: ... diff --git a/stubs/gdb/gdb/dap/events.pyi b/stubs/gdb/gdb/dap/events.pyi new file mode 100644 index 000000000000..7cd269266eff --- /dev/null +++ b/stubs/gdb/gdb/dap/events.pyi @@ -0,0 +1,12 @@ +import gdb + +inferior_running: bool + +def send_process_event_once() -> None: ... +def expect_process(reason: str) -> None: ... +def thread_event(event: gdb.ThreadEvent, reason: str) -> None: ... +def expect_stop(reason: str) -> None: ... +def exec_and_expect_stop(cmd: str, expected_pause: bool = False) -> None: ... + +# Map from gdb stop reasons to DAP stop reasons. +stop_reason_map: dict[str, str] diff --git a/stubs/gdb/gdb/dap/frames.pyi b/stubs/gdb/gdb/dap/frames.pyi new file mode 100644 index 000000000000..3c7d516e36c6 --- /dev/null +++ b/stubs/gdb/gdb/dap/frames.pyi @@ -0,0 +1,7 @@ +from collections.abc import Generator + +import gdb + +def frame_for_id(id: int) -> gdb.Frame: ... +def select_frame(id: int) -> None: ... +def dap_frame_generator(frame_low: int, levels: int, include_all: bool) -> Generator[tuple[int, gdb.Frame]]: ... diff --git a/stubs/gdb/gdb/dap/io.pyi b/stubs/gdb/gdb/dap/io.pyi new file mode 100644 index 000000000000..2cf4f182f395 --- /dev/null +++ b/stubs/gdb/gdb/dap/io.pyi @@ -0,0 +1,16 @@ +from _typeshed import SupportsFlush, SupportsRead, SupportsReadline, SupportsWrite +from typing import Any, type_check_only + +import gdb + +from .server import _JSONValue +from .startup import DAPQueue + +@type_check_only +class _SupportsReadAndReadlineBytes(SupportsRead[bytes], SupportsReadline[bytes]): ... + +@type_check_only +class _SupportsWriteAndFlushBytes(SupportsWrite[bytes], SupportsFlush): ... + +def read_json(stream: _SupportsReadAndReadlineBytes) -> Any: ... # returns result of json.loads +def start_json_writer(stream: _SupportsWriteAndFlushBytes, queue: DAPQueue[_JSONValue]) -> gdb.Thread: ... diff --git a/stubs/gdb/gdb/dap/launch.pyi b/stubs/gdb/gdb/dap/launch.pyi new file mode 100644 index 000000000000..5d573114df88 --- /dev/null +++ b/stubs/gdb/gdb/dap/launch.pyi @@ -0,0 +1,14 @@ +from _typeshed import Unused +from collections.abc import Mapping, Sequence + +def launch( + *, + program: str | None = None, + cwd: str | None = None, + args: Sequence[str] = (), + env: Mapping[str, str] | None = None, + stopAtBeginningOfMainSubprogram: bool = False, + **extra: Unused, +): ... +def attach(*, program: str | None = None, pid: int | None = None, target: str | None = None, **args: Unused) -> None: ... +def config_done(**args: Unused) -> None: ... diff --git a/stubs/gdb/gdb/dap/locations.pyi b/stubs/gdb/gdb/dap/locations.pyi new file mode 100644 index 000000000000..da63e65c83ea --- /dev/null +++ b/stubs/gdb/gdb/dap/locations.pyi @@ -0,0 +1,16 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only + +from .sources import Source + +@type_check_only +class _Line(TypedDict): + line: int + +@type_check_only +class _BreakpointLocationsResult(TypedDict): + breakpoints: list[_Line] + +def breakpoint_locations( + *, source: Source, line: int, endLine: int | None = None, **extra: Unused +) -> _BreakpointLocationsResult: ... diff --git a/stubs/gdb/gdb/dap/memory.pyi b/stubs/gdb/gdb/dap/memory.pyi new file mode 100644 index 000000000000..b6a33a3d1262 --- /dev/null +++ b/stubs/gdb/gdb/dap/memory.pyi @@ -0,0 +1,10 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only + +@type_check_only +class _ReadMemoryResult(TypedDict): + address: str + data: str + +def read_memory(*, memoryReference: str, offset: int = 0, count: int, **extra: Unused) -> _ReadMemoryResult: ... +def write_memory(*, memoryReference: str, offset: int = 0, data: str, **extra: Unused): ... diff --git a/stubs/gdb/gdb/dap/modules.pyi b/stubs/gdb/gdb/dap/modules.pyi new file mode 100644 index 000000000000..eae61cfb47da --- /dev/null +++ b/stubs/gdb/gdb/dap/modules.pyi @@ -0,0 +1,21 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +@type_check_only +class _Module(TypedDict): + id: str | None + name: str | None + path: NotRequired[str | None] + +@type_check_only +class _ModulesResult(TypedDict): + modules: list[_Module] + totalModules: int + +def module_id(objfile: gdb.Objfile) -> str | None: ... +def is_module(objfile: gdb.Objfile) -> bool: ... +def make_module(objf: gdb.Objfile) -> _Module: ... +def modules(*, startModule: int = 0, moduleCount: int = 0, **args: Unused) -> _ModulesResult: ... diff --git a/stubs/gdb/gdb/dap/next.pyi b/stubs/gdb/gdb/dap/next.pyi new file mode 100644 index 000000000000..1418de48f8da --- /dev/null +++ b/stubs/gdb/gdb/dap/next.pyi @@ -0,0 +1,13 @@ +from _typeshed import Unused +from typing import Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _ContinueRequestResult(TypedDict): + allThreadsContinued: bool + +_Granularity: TypeAlias = Literal["statement", "instruction"] + +def next(*, threadId: int, singleThread: bool = False, granularity: _Granularity = "statement", **args: Unused) -> None: ... +def step_in(*, threadId: int, singleThread: bool = False, granularity: _Granularity = "statement", **args: Unused) -> None: ... +def step_out(*, threadId: int, singleThread: bool = False, **args: Unused): ... +def continue_request(*, threadId: int, singleThread: bool = False, **args: Unused) -> _ContinueRequestResult: ... diff --git a/stubs/gdb/gdb/dap/pause.pyi b/stubs/gdb/gdb/dap/pause.pyi new file mode 100644 index 000000000000..6343b7b03156 --- /dev/null +++ b/stubs/gdb/gdb/dap/pause.pyi @@ -0,0 +1,3 @@ +from _typeshed import Unused + +def pause(**args: Unused) -> None: ... diff --git a/stubs/gdb/gdb/dap/scopes.pyi b/stubs/gdb/gdb/dap/scopes.pyi new file mode 100644 index 000000000000..c5421b6f747f --- /dev/null +++ b/stubs/gdb/gdb/dap/scopes.pyi @@ -0,0 +1,47 @@ +from _typeshed import Unused +from collections.abc import Iterable +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +from ..FrameDecorator import FrameDecorator, SymValueWrapper +from .varref import BaseReference, _ReferenceDescriptor + +frame_to_scope: dict[int, _ScopeReference] + +@type_check_only +class _ScopeReferenceDescriptor(_ReferenceDescriptor): + presentationHint: str + expensive: bool + namedVariables: int + line: NotRequired[int] + +@type_check_only +class _ScopesResult(TypedDict): + scopes: list[_ScopeReferenceDescriptor] + +def clear_scopes(event: Unused) -> None: ... +def set_finish_value(val: gdb.Value) -> None: ... +def symbol_value(sym: SymValueWrapper, frame: FrameDecorator) -> tuple[str, gdb.Value]: ... + +class _ScopeReference(BaseReference): + hint: str + frame: FrameDecorator + inf_frame: gdb.Frame + function: str | None + line: int | None + var_list: tuple[SymValueWrapper, ...] + def __init__(self, name: str, hint: str, frame: FrameDecorator, var_list: Iterable[SymValueWrapper]) -> None: ... + def to_object(self) -> _ScopeReferenceDescriptor: ... + def has_children(self) -> bool: ... + def child_count(self) -> int: ... + # note: parameter named changed from 'index' to 'idx' + def fetch_one_child(self, idx: int) -> tuple[str, gdb.Value]: ... + +class _FinishScopeReference(_ScopeReference): ... + +class _RegisterReference(_ScopeReference): + def __init__(self, name: str, frame: FrameDecorator) -> None: ... + +def scopes(*, frameId: int, **extra: Unused) -> _ScopesResult: ... diff --git a/stubs/gdb/gdb/dap/server.pyi b/stubs/gdb/gdb/dap/server.pyi new file mode 100644 index 000000000000..8d9f49c16193 --- /dev/null +++ b/stubs/gdb/gdb/dap/server.pyi @@ -0,0 +1,77 @@ +import threading +from _typeshed import Incomplete, SupportsReadline, Unused +from collections.abc import Callable +from contextlib import AbstractContextManager +from typing import Any, Generic, TypeAlias, TypeVar, type_check_only + +from .io import _SupportsReadAndReadlineBytes, _SupportsWriteAndFlushBytes +from .startup import DAPQueue + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) + +_RequestID: TypeAlias = int +_EventBody: TypeAlias = Any # arbitrary object, implicitly constrained by the event being sent +_JSONValue: TypeAlias = Any # any object that can be handled by json.dumps/json.loads + +class NotStoppedException(Exception): ... + +class CancellationHandler: + lock: threading.Lock + reqs: list[_RequestID] + in_flight_dap_thread: _RequestID | None + in_flight_gdb_thread: _RequestID | None + def starting(self, req: _RequestID) -> None: ... + def done(self, req: _RequestID) -> None: ... # req argument is not used + def cancel(self, req: _RequestID) -> None: ... + def interruptable_region(self, req: _RequestID | None) -> AbstractContextManager[None]: ... + +class Server: + in_stream: _SupportsReadAndReadlineBytes + out_stream: _SupportsWriteAndFlushBytes + child_stream: SupportsReadline[str] + delay_events: list[tuple[str, _EventBody]] + write_queue: DAPQueue[_JSONValue | None] + read_queue: DAPQueue[_JSONValue | None] + done: bool + canceller: CancellationHandler + config: dict[str, Incomplete] + def __init__( + self, + in_stream: _SupportsReadAndReadlineBytes, + out_stream: _SupportsWriteAndFlushBytes, + child_stream: SupportsReadline[str], + ) -> None: ... + def main_loop(self) -> None: ... + def send_event(self, event: str, body: _EventBody | None = None) -> None: ... + def send_event_later(self, event: str, body: _EventBody | None = None) -> None: ... + def shutdown(self) -> None: ... + +def send_event(event: str, body: _EventBody | None = None) -> None: ... + +@type_check_only +class _Wrapper: + def __call__(self, func: _F) -> _F: ... + +def request(name: str, *, response: bool = True, on_dap_thread: bool = False, expect_stopped: bool = True) -> _Wrapper: ... +def capability(name: str, value: bool = True) -> _Wrapper: ... +def client_bool_capability(name: str) -> bool: ... +def initialize(**args) -> dict[str, bool]: ... # args is arbitrary values for Server.config +def terminate(**args: Unused) -> None: ... +def disconnect(*, terminateDebuggee: bool = False, **args: Unused): ... +def cancel(**args: Unused) -> None: ... + +class Invoker: + cmd: str + def __init__(self, cmd: str) -> None: ... + def __call__(self) -> None: ... + +class Cancellable(Generic[_T]): + fn: Callable[[], _T] + result_q: DAPQueue[_T] | None + req: _RequestID + def __init__(self, fn: Callable[[], _T], result_q: DAPQueue[_T] | None = None) -> None: ... + def __call__(self) -> None: ... + +def send_gdb(cmd: str | Callable[[], object]) -> None: ... +def send_gdb_with_response(fn: str | Callable[[], _T]) -> _T: ... diff --git a/stubs/gdb/gdb/dap/sources.pyi b/stubs/gdb/gdb/dap/sources.pyi new file mode 100644 index 000000000000..7adee35f2c9b --- /dev/null +++ b/stubs/gdb/gdb/dap/sources.pyi @@ -0,0 +1,23 @@ +from _typeshed import Unused +from typing import TypeAlias, TypedDict, type_check_only + +_SourceReferenceID: TypeAlias = int + +@type_check_only +class Source(TypedDict, total=False): + name: str + path: str + sourceReference: _SourceReferenceID + +@type_check_only +class _LoadSourcesResult(TypedDict): + sources: list[Source] + +@type_check_only +class _SourceResult(TypedDict): + content: str + +def make_source(fullname: str, filename: str | None) -> Source: ... +def decode_source(source: Source) -> _SourceReferenceID: ... +def loaded_sources(**extra: Unused) -> _LoadSourcesResult: ... +def source(*, source: Source | None = None, sourceReference: _SourceReferenceID, **extra: Unused) -> _SourceResult: ... diff --git a/stubs/gdb/gdb/dap/startup.pyi b/stubs/gdb/gdb/dap/startup.pyi new file mode 100644 index 000000000000..107a408901d1 --- /dev/null +++ b/stubs/gdb/gdb/dap/startup.pyi @@ -0,0 +1,43 @@ +import enum +import io +import queue +import threading +from collections.abc import Callable, Iterable +from typing import Any, ClassVar, TypeAlias, TypeVar + +import gdb + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) + +DAPQueue: TypeAlias = queue.SimpleQueue[_T] + +class DAPException(Exception): ... + +def parse_and_eval(expression: str, global_context: bool = False) -> gdb.Value: ... + +# target and args are passed to gdb.Thread +def start_thread(name: str, target: Callable[..., object], args: Iterable[Any] = ()) -> gdb.Thread: ... +def start_dap(target: Callable[..., object]) -> None: ... +def in_gdb_thread(func: _F) -> _F: ... +def in_dap_thread(func: _F) -> _F: ... + +class LogLevel(enum.IntEnum): + DEFAULT = 1 + FULL = 2 + +class LogLevelParam(gdb.Parameter): + def __init__(self) -> None: ... + +class LoggingParam(gdb.Parameter): + lock: ClassVar[threading.Lock] + log_file: io.TextIOWrapper | None + def __init__(self) -> None: ... + def get_set_string(self) -> str: ... + +dap_log: LoggingParam + +def log(something: object, level: LogLevel = LogLevel.DEFAULT) -> None: ... +def thread_log(something: object, level: LogLevel = LogLevel.DEFAULT) -> None: ... +def log_stack(level: LogLevel = LogLevel.DEFAULT) -> None: ... +def exec_and_log(cmd: str) -> None: ... diff --git a/stubs/gdb/gdb/dap/state.pyi b/stubs/gdb/gdb/dap/state.pyi new file mode 100644 index 000000000000..1d80080e1531 --- /dev/null +++ b/stubs/gdb/gdb/dap/state.pyi @@ -0,0 +1 @@ +def set_thread(thread_id: int) -> None: ... diff --git a/stubs/gdb/gdb/dap/threads.pyi b/stubs/gdb/gdb/dap/threads.pyi new file mode 100644 index 000000000000..3de0ccff3b13 --- /dev/null +++ b/stubs/gdb/gdb/dap/threads.pyi @@ -0,0 +1,14 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +@type_check_only +class _Thread(TypedDict): + id: int + name: NotRequired[str] + +@type_check_only +class _ThreadsResult(TypedDict): + threads: list[_Thread] + +def threads(**args: Unused) -> _ThreadsResult: ... diff --git a/stubs/gdb/gdb/dap/typecheck.pyi b/stubs/gdb/gdb/dap/typecheck.pyi new file mode 100644 index 000000000000..37993cca7a34 --- /dev/null +++ b/stubs/gdb/gdb/dap/typecheck.pyi @@ -0,0 +1,6 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def type_check(func: _F) -> _F: ... diff --git a/stubs/gdb/gdb/dap/varref.pyi b/stubs/gdb/gdb/dap/varref.pyi new file mode 100644 index 000000000000..83d700607585 --- /dev/null +++ b/stubs/gdb/gdb/dap/varref.pyi @@ -0,0 +1,70 @@ +import abc +from _typeshed import Unused +from collections import defaultdict +from collections.abc import Generator +from contextlib import AbstractContextManager +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +@type_check_only +class _ValueFormat(TypedDict, total=False): + hex: bool + +@type_check_only +class _ReferenceDescriptor(TypedDict): + # Result of BaseReference.to_object() + variableReference: int + name: NotRequired[str] + +@type_check_only +class _VariableReferenceDescriptor(_ReferenceDescriptor): + # Result of VariableReference.to_object() + indexedVariables: NotRequired[int] + namedVariables: NotRequired[int] + memoryReference: NotRequired[str] + type: NotRequired[str] + # Below key name set by VariableReference.result_name + # Could be modelled with extra_items=str if PEP 728 is accepted. + value: NotRequired[str] + +all_variables: list[BaseReference] + +def clear_vars(event: Unused) -> None: ... +def apply_format(value_format: _ValueFormat | None) -> AbstractContextManager[None]: ... + +class BaseReference(abc.ABC): + ref: int + name: str + children: list[VariableReference | None] | None + by_name: dict[str, VariableReference] + name_counts: defaultdict[str, int] + def __init__(self, name: str) -> None: ... + def to_object(self) -> _ReferenceDescriptor: ... + @abc.abstractmethod + def has_children(self) -> bool: ... + def reset_children(self): ... + @abc.abstractmethod + def fetch_one_child(self, index: int) -> tuple[str, gdb.Value]: ... + @abc.abstractmethod + def child_count(self) -> int: ... + def fetch_children(self, start: int, count: int) -> Generator[VariableReference]: ... + def find_child_by_name(self, name: str) -> VariableReference: ... + +class VariableReference(BaseReference): + result_name: str + value: gdb.Value + child_cache: list[tuple[int | str, gdb.Value]] | None + count: int | None + printer: gdb._PrettyPrinter + def __init__(self, name: str, value: gdb.Value, result_name: str = "value") -> None: ... + def assign(self, value: gdb.Value) -> None: ... + def has_children(self) -> bool: ... + def cache_children(self) -> list[tuple[int | str, gdb.Value]]: ... + def child_count(self) -> int: ... + def to_object(self) -> _VariableReferenceDescriptor: ... + # note: parameter named changed from 'index' to 'idx' + def fetch_one_child(self, idx: int) -> tuple[str, gdb.Value]: ... + +def find_variable(ref: int) -> BaseReference: ... diff --git a/stubs/gdb/gdb/disassembler.pyi b/stubs/gdb/gdb/disassembler.pyi new file mode 100644 index 000000000000..e878264cfef5 --- /dev/null +++ b/stubs/gdb/gdb/disassembler.pyi @@ -0,0 +1,60 @@ +from collections.abc import Sequence +from typing import Final, final +from typing_extensions import disjoint_base + +import gdb +from gdb import Architecture, Progspace + +class Disassembler: + def __init__(self, name: str) -> None: ... + def __call__(self, info): ... + +@disjoint_base +class DisassembleInfo: + address: int + architecture: Architecture + progspace: Progspace + def __init__(self, info: DisassembleInfo) -> None: ... + def address_part(self, address: int) -> DisassemblerAddressPart: ... + def is_valid(self) -> bool: ... + def read_memory(self, len: int, offset: int = 0): ... + def text_part(self, style: int, string: str) -> DisassemblerTextPart: ... + +class DisassemblerPart: + def __init__(self, /, *args, **kwargs) -> None: ... + +@final +class DisassemblerAddressPart(DisassemblerPart): + address: int + string: str + +@final +class DisassemblerTextPart(DisassemblerPart): + string: str + style: int + +@final +class DisassemblerResult: + def __init__(self, length: int, string: str | None = None, parts: Sequence[DisassemblerPart] | None = None) -> None: ... + length: int + parts: Sequence[DisassemblerPart] + string: str + +STYLE_TEXT: Final = 0 +STYLE_MNEMONIC: Final = 1 +STYLE_SUB_MNEMONIC: Final = 2 +STYLE_ASSEMBLER_DIRECTIVE: Final = 3 +STYLE_REGISTER: Final = 4 +STYLE_IMMEDIATE: Final = 5 +STYLE_ADDRESS: Final = 6 +STYLE_ADDRESS_OFFSET: Final = 7 +STYLE_SYMBOL: Final = 8 +STYLE_COMMENT_START: Final = 9 + +def builtin_disassemble(info: DisassembleInfo) -> None: ... + +class maint_info_py_disassemblers_cmd(gdb.Command): + def __init__(self) -> None: ... + def invoke(self, args, from_tty): ... + +def register_disassembler(disassembler: type[Disassembler], architecture: str | None = None): ... diff --git a/stubs/gdb/gdb/events.pyi b/stubs/gdb/gdb/events.pyi new file mode 100644 index 000000000000..6160804bf485 --- /dev/null +++ b/stubs/gdb/gdb/events.pyi @@ -0,0 +1,25 @@ +import gdb + +cont: gdb.EventRegistry[gdb.ContinueEvent] +exited: gdb.EventRegistry[gdb.ExitedEvent] +thread_exited: gdb.EventRegistry[gdb.ThreadExitedEvent] +stop: gdb.EventRegistry[gdb.StopEvent] +new_objfile: gdb.EventRegistry[gdb.NewObjFileEvent] +free_objfile: gdb.EventRegistry[gdb.FreeObjFileEvent] +clear_objfiles: gdb.EventRegistry[gdb.ClearObjFilesEvent] +new_progspace: gdb.EventRegistry[gdb.NewProgspaceEvent] +free_progspace: gdb.EventRegistry[gdb.FreeProgspaceEvent] +inferior_call: gdb.EventRegistry[gdb._InferiorCallEvent] +memory_changed: gdb.EventRegistry[gdb.MemoryChangedEvent] +register_changed: gdb.EventRegistry[gdb.RegisterChangedEvent] +breakpoint_created: gdb.EventRegistry[gdb.Breakpoint] +breakpoint_modified: gdb.EventRegistry[gdb.Breakpoint] +breakpoint_deleted: gdb.EventRegistry[gdb.Breakpoint] +before_prompt: gdb.EventRegistry[None] +new_inferior: gdb.EventRegistry[gdb.NewInferiorEvent] +inferior_deleted: gdb.EventRegistry[gdb.InferiorDeletedEvent] +new_thread: gdb.EventRegistry[gdb.NewThreadEvent] +gdb_exiting: gdb.EventRegistry[gdb.GdbExitingEvent] +connection_removed: gdb.EventRegistry[gdb.ConnectionEvent] +executable_changed: gdb.EventRegistry[gdb.ExecutableChangedEvent] +tui_enabled: gdb.EventRegistry[gdb.TuiEnabledEvent] diff --git a/stubs/gdb/gdb/missing_debug.pyi b/stubs/gdb/gdb/missing_debug.pyi new file mode 100644 index 000000000000..1b9d5988f954 --- /dev/null +++ b/stubs/gdb/gdb/missing_debug.pyi @@ -0,0 +1,8 @@ +import gdb +from gdb import Progspace +from gdb.missing_files import MissingFileHandler + +class MissingDebugHandler(MissingFileHandler): + def __call__(self, objfile: gdb.Objfile) -> bool | str | None: ... + +def register_handler(locus: Progspace | None, handler: MissingDebugHandler, replace: bool = False) -> None: ... diff --git a/stubs/gdb/gdb/missing_files.pyi b/stubs/gdb/gdb/missing_files.pyi new file mode 100644 index 000000000000..fbc6f113167d --- /dev/null +++ b/stubs/gdb/gdb/missing_files.pyi @@ -0,0 +1,13 @@ +from typing import Literal + +from gdb import Progspace + +class MissingFileHandler: + @property + def name(self) -> str: ... + enabled: bool + def __init__(self, name: str) -> None: ... + +def register_handler( + handler_type: Literal["debug", "objfile"], locus: Progspace | None, handler: MissingFileHandler, replace: bool = False +) -> None: ... diff --git a/stubs/gdb/gdb/missing_objfile.pyi b/stubs/gdb/gdb/missing_objfile.pyi new file mode 100644 index 000000000000..8e50b1c1baa5 --- /dev/null +++ b/stubs/gdb/gdb/missing_objfile.pyi @@ -0,0 +1,7 @@ +from gdb import Progspace +from gdb.missing_files import MissingFileHandler + +class MissingObjfileHandler(MissingFileHandler): + def __call__(self, buildid: str, filename: str) -> bool | str | None: ... + +def register_handler(locus: Progspace | None, handler: MissingObjfileHandler, replace: bool = False) -> None: ... diff --git a/stubs/gdb/gdb/printing.pyi b/stubs/gdb/gdb/printing.pyi new file mode 100644 index 000000000000..f3348f1569ae --- /dev/null +++ b/stubs/gdb/gdb/printing.pyi @@ -0,0 +1,56 @@ +from collections.abc import Callable, Iterable + +import gdb +from gdb import _PrettyPrinterLookupFunction + +class PrettyPrinter: + name: str + subprinters: list[SubPrettyPrinter] | None + enabled: bool + + def __init__(self, name: str, subprinters: Iterable[SubPrettyPrinter] | None = ...) -> None: ... + def __call__(self, val: gdb.Value) -> gdb._PrettyPrinter | None: ... + +class SubPrettyPrinter: + name: str + enabled: bool + + def __init__(self, name: str) -> None: ... + +class RegexpCollectionPrettyPrinter(PrettyPrinter): + def __init__(self, name: str) -> None: ... + def add_printer(self, name: str, regexp: str, gen_printer: _PrettyPrinterLookupFunction) -> None: ... + +class FlagEnumerationPrinter(PrettyPrinter): + def __init__(self, enum_type: str) -> None: ... + +class NoOpArrayPrinter(gdb.ValuePrinter): + def __init__(self, ty, value) -> None: ... + def child(self, i): ... + def children(self): ... + def display_hint(self): ... + def num_children(self): ... + def to_string(self) -> str: ... + +class NoOpPointerReferencePrinter(gdb.ValuePrinter): + def __init__(self, value) -> None: ... + def child(self, i): ... + def children(self): ... + def num_children(self): ... + def to_string(self) -> str: ... + +class NoOpScalarPrinter(gdb.ValuePrinter): + def __init__(self, value) -> None: ... + def to_string(self) -> str: ... + +class NoOpStructPrinter(gdb.ValuePrinter): + def __init__(self, ty, value) -> None: ... + def children(self): ... + def to_string(self) -> str: ... + +def register_pretty_printer( + obj: gdb.Objfile | gdb.Progspace | None, + printer: PrettyPrinter | Callable[[gdb.Value], gdb._PrettyPrinter | None], + replace: bool = ..., +) -> None: ... +def make_visualizer(value: gdb.Value): ... diff --git a/stubs/gdb/gdb/prompt.pyi b/stubs/gdb/gdb/prompt.pyi new file mode 100644 index 000000000000..5690907e81e6 --- /dev/null +++ b/stubs/gdb/gdb/prompt.pyi @@ -0,0 +1 @@ +def substitute_prompt(prompt: str) -> str: ... diff --git a/stubs/gdb/gdb/types.pyi b/stubs/gdb/gdb/types.pyi new file mode 100644 index 000000000000..ec34ea3e606e --- /dev/null +++ b/stubs/gdb/gdb/types.pyi @@ -0,0 +1,30 @@ +from collections.abc import Iterator +from typing import Protocol, type_check_only + +import gdb + +def get_basic_type(type_: gdb.Type) -> gdb.Type: ... +def has_field(type_: gdb.Type, field: str) -> bool: ... +def make_enum_dict(enum_type: gdb.Type) -> dict[str, int]: ... +def deep_items(type_: gdb.Type) -> Iterator[tuple[str, gdb.Field]]: ... +def get_type_recognizers() -> list[_TypeRecognizer]: ... +def apply_type_recognizers(recognizers: list[_TypeRecognizer], type_obj: gdb.Type) -> str | None: ... +def register_type_printer(locus: gdb.Objfile | gdb.Progspace | None, printer: _TypePrinter) -> None: ... + +@type_check_only +class _TypePrinter(Protocol): + enabled: bool + name: str + + def instantiate(self) -> _TypeRecognizer | None: ... + +@type_check_only +class _TypeRecognizer(Protocol): + def recognize(self, type: gdb.Type, /) -> str | None: ... + +class TypePrinter: + enabled: bool + name: str + + def __init__(self, name: str) -> None: ... + def instantiate(self) -> _TypeRecognizer | None: ... diff --git a/stubs/gdb/gdb/unwinder.pyi b/stubs/gdb/gdb/unwinder.pyi new file mode 100644 index 000000000000..60a5f84d6dec --- /dev/null +++ b/stubs/gdb/gdb/unwinder.pyi @@ -0,0 +1,20 @@ +import gdb + +class FrameId: + def __init__(self, sp: gdb.Value | int, pc: gdb.Value | int, special: gdb.Value | int | None = None) -> None: ... + @property + def pc(self) -> gdb.Value | int: ... + @property + def sp(self) -> gdb.Value | int: ... + @property + def special(self) -> gdb.Value | int | None: ... + +class Unwinder: + @property + def name(self) -> str: ... + enabled: bool + + def __init__(self, name: str) -> None: ... + def __call__(self, pending_frame: gdb.PendingFrame) -> gdb.UnwindInfo | None: ... + +def register_unwinder(locus: gdb.Objfile | gdb.Progspace | None, unwinder: gdb._Unwinder, replace: bool = ...) -> None: ... diff --git a/stubs/gdb/gdb/xmethod.pyi b/stubs/gdb/gdb/xmethod.pyi new file mode 100644 index 000000000000..31ff16523322 --- /dev/null +++ b/stubs/gdb/gdb/xmethod.pyi @@ -0,0 +1,47 @@ +from collections.abc import Sequence +from re import Pattern +from typing import Protocol, type_check_only + +import gdb + +def register_xmethod_matcher( + locus: gdb.Objfile | gdb.Progspace | None, matcher: XMethodMatcher, replace: bool = False +) -> None: ... + +@type_check_only +class _XMethod(Protocol): + name: str + enabled: bool + +class XMethod: + name: str + enabled: bool + + def __init__(self, name: str) -> None: ... + +class XMethodWorker: + def get_arg_types(self) -> Sequence[gdb.Type] | gdb.Type | None: ... + def get_result_type(self, *args: gdb.Value) -> gdb.Type: ... + def __call__(self, *args: gdb.Value) -> object: ... + +class XMethodMatcher: + name: str + enabled: bool + methods: list[_XMethod] | None + + def __init__(self, name: str) -> None: ... + def match(self, class_type: gdb.Type, method_name: str) -> XMethodWorker | Sequence[XMethodWorker]: ... + +@type_check_only +class _SimpleWorkerMethod(Protocol): + def __call__(self, *args: gdb.Value) -> object: ... + +class SimpleXMethodMatcher(XMethodMatcher): + def __init__( + self, + name: str, + class_matcher: str | Pattern[str], + method_matcher: str | Pattern[str], + method_function: _SimpleWorkerMethod, + *arg_types: Sequence[gdb.Type] | gdb.Type | None, + ) -> None: ... diff --git a/stubs/geojson/@tests/stubtest_allowlist.txt b/stubs/geojson/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d3376f747930 --- /dev/null +++ b/stubs/geojson/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# Stub missing OK, not part of public API +geojson.factory +geojson.examples diff --git a/stubs/geojson/METADATA.toml b/stubs/geojson/METADATA.toml new file mode 100644 index 000000000000..2e98409a8944 --- /dev/null +++ b/stubs/geojson/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.3.0" +upstream-repository = "https://github.com/jazzband/geojson" diff --git a/stubs/geojson/geojson/__init__.pyi b/stubs/geojson/geojson/__init__.pyi new file mode 100644 index 000000000000..a022f4f97930 --- /dev/null +++ b/stubs/geojson/geojson/__init__.pyi @@ -0,0 +1,28 @@ +from geojson._version import __version__, __version_info__ +from geojson.base import GeoJSON +from geojson.codec import GeoJSONEncoder, dump, dumps, load, loads +from geojson.feature import Feature, FeatureCollection +from geojson.geometry import GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from geojson.utils import coords, map_coords + +__all__ = [ + "dump", + "dumps", + "load", + "loads", + "GeoJSONEncoder", + "coords", + "map_coords", + "Point", + "LineString", + "Polygon", + "MultiLineString", + "MultiPoint", + "MultiPolygon", + "GeometryCollection", + "Feature", + "FeatureCollection", + "GeoJSON", + "__version__", + "__version_info__", +] diff --git a/stubs/geojson/geojson/_version.pyi b/stubs/geojson/geojson/_version.pyi new file mode 100644 index 000000000000..fd947dd9c0e2 --- /dev/null +++ b/stubs/geojson/geojson/_version.pyi @@ -0,0 +1,2 @@ +__version__: str +__version_info__: tuple[int, ...] diff --git a/stubs/geojson/geojson/base.pyi b/stubs/geojson/geojson/base.pyi new file mode 100644 index 000000000000..c75f2d4c7989 --- /dev/null +++ b/stubs/geojson/geojson/base.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Any + +class GeoJSON(dict[str, Any]): + def __init__(self, iterable: Iterable[tuple[str, Any]] = (), **extra) -> None: ... + def __getattr__(self, name: str | int) -> Incomplete: ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + @property + def __geo_interface__(self) -> GeoJSON | None: ... + @classmethod + def to_instance(cls, ob, default=None, strict: bool = False) -> GeoJSON: ... + @property + def is_valid(self) -> bool: ... + def check_list_errors(self, checkFunc, lst) -> list[str] | None: ... + def errors(self) -> list[str] | None: ... diff --git a/stubs/geojson/geojson/codec.pyi b/stubs/geojson/geojson/codec.pyi new file mode 100644 index 000000000000..7b9d82f0944e --- /dev/null +++ b/stubs/geojson/geojson/codec.pyi @@ -0,0 +1,33 @@ +import json +from _typeshed import SupportsRead, SupportsWrite +from collections.abc import Callable +from typing import Any +from typing_extensions import Never + +from geojson.base import GeoJSON + +class GeoJSONEncoder(json.JSONEncoder): + def default(self, obj) -> GeoJSON: ... + +def dump( + obj, fp: SupportsWrite[str], cls: type[json.JSONEncoder] | None = json.JSONEncoder, allow_nan: bool = False, **kwargs +) -> None: ... +def dumps( + obj, cls: type[json.JSONEncoder] | None = json.JSONEncoder, allow_nan: bool = False, ensure_ascii: bool = False, **kwargs +) -> str: ... +def load( + fp: SupportsRead[str], + cls: type[json.JSONDecoder] = json.JSONDecoder, + parse_constant: Callable[..., Never] = ..., + object_hook: Callable[[dict[str, Any]], GeoJSON] = GeoJSON.to_instance, + **kwargs, +) -> GeoJSON: ... +def loads( + s: str, + cls: type[json.JSONDecoder] = json.JSONDecoder, + parse_constant: Callable[..., Never] = ..., + object_hook: Callable[[dict[str, Any]], GeoJSON] = GeoJSON.to_instance, + **kwargs, +) -> GeoJSON: ... + +PyGFPEncoder = GeoJSONEncoder diff --git a/stubs/geojson/geojson/feature.pyi b/stubs/geojson/geojson/feature.pyi new file mode 100644 index 000000000000..e2834fa45dd0 --- /dev/null +++ b/stubs/geojson/geojson/feature.pyi @@ -0,0 +1,15 @@ +from typing import Any + +from geojson.base import GeoJSON +from geojson.geometry import Geometry + +class Feature(GeoJSON): + def __init__( + self, id: str | int | None = None, geometry: Geometry | None = None, properties: dict[str, Any] | None = None, **extra + ) -> None: ... + def errors(self) -> list[str] | None: ... + +class FeatureCollection(GeoJSON): + def __init__(self, features: list[Feature | Geometry], **extra) -> None: ... + def errors(self) -> list[str] | None: ... + def __getitem__(self, key: int | str) -> Feature: ... diff --git a/stubs/geojson/geojson/geometry.pyi b/stubs/geojson/geojson/geometry.pyi new file mode 100644 index 000000000000..57e2f1918e5c --- /dev/null +++ b/stubs/geojson/geojson/geometry.pyi @@ -0,0 +1,52 @@ +from collections.abc import Sequence +from decimal import Decimal +from typing import TypeAlias + +from geojson.base import GeoJSON + +_InputCoord: TypeAlias = float | Decimal | Geometry | Sequence[_InputCoord] +_CleanCoord: TypeAlias = float | Decimal | list[_CleanCoord] + +DEFAULT_PRECISION: int + +class Geometry(GeoJSON): + def __init__( + self, + coordinates: Sequence[_InputCoord] | Geometry | None = None, + validate: bool = False, + precision: int | None = None, + **extra, + ) -> None: ... + @classmethod + def clean_coordinates(cls, coords: Sequence[_InputCoord] | Geometry, precision: int) -> list[_CleanCoord]: ... + +class GeometryCollection(GeoJSON): + def __init__(self, geometries: Sequence[Geometry] | None = None, **extra) -> None: ... + def errors(self) -> list[str] | None: ... + def __getitem__(self, key) -> Geometry | tuple[()] | None: ... + +def check_point(coord) -> str | None: ... + +class Point(Geometry): + def errors(self) -> list[str] | None: ... + +class MultiPoint(Geometry): + def errors(self) -> list[str] | None: ... + +def check_line_string(coord) -> str | None: ... + +class LineString(Geometry): + def errors(self) -> list[str] | None: ... + +class MultiLineString(MultiPoint): + def errors(self) -> list[str] | None: ... + +def check_polygon(coord) -> str | None: ... + +class Polygon(Geometry): + def errors(self) -> list[str] | None: ... + +class MultiPolygon(Geometry): + def errors(self) -> list[str] | None: ... + +class Default: ... diff --git a/stubs/geojson/geojson/mapping.pyi b/stubs/geojson/geojson/mapping.pyi new file mode 100644 index 000000000000..d9b0e4900ebb --- /dev/null +++ b/stubs/geojson/geojson/mapping.pyi @@ -0,0 +1,6 @@ +from typing import Any, Literal + +GEO_INTERFACE_MARKER: Literal["__geo_interface__"] + +def is_mapping(obj) -> bool: ... +def to_mapping(obj) -> dict[str, Any]: ... diff --git a/stubs/geojson/geojson/utils.pyi b/stubs/geojson/geojson/utils.pyi new file mode 100644 index 000000000000..9e35c35bfc81 --- /dev/null +++ b/stubs/geojson/geojson/utils.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator +from typing import Any, Literal + +from geojson.base import GeoJSON +from geojson.geometry import Geometry, LineString, Point, Polygon + +def coords(obj: GeoJSON | dict[str, Any]) -> Generator[tuple[float]]: ... +def map_coords(func: Callable[[Incomplete], float | Geometry], obj: GeoJSON | dict[str, Any]) -> dict[str, Any]: ... +def map_tuples(func: Callable[[Incomplete], float | Geometry], obj: GeoJSON | dict[str, Any]) -> dict[str, Any]: ... +def map_geometries(func: Callable[[Incomplete], float | Geometry], obj: GeoJSON | dict[str, Any]) -> dict[str, Any]: ... +def generate_random( + featureType: Literal["Point", "LineString", "Polygon"], + numberVertices: int = 3, + boundingBox: list[float] = [-180.0, -90.0, 180.0, 90.0], +) -> Point | LineString | Polygon: ... diff --git a/stubs/geopandas/@tests/stubtest_allowlist.txt b/stubs/geopandas/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2251765af4e4 --- /dev/null +++ b/stubs/geopandas/@tests/stubtest_allowlist.txt @@ -0,0 +1,25 @@ +# Stub missing OK +geopandas\.conftest +geopandas\.(.*\.)?tests.* +geopandas\.array\.(type_mapping|geometry_type_ids|geometry_type_values) +geopandas\.io\.file\.(FIONA|PYOGRIO)_GE_.* +geopandas\.io\.file\.(fiona|pyogrio)(_env|_import_error)? +geopandas\.io\.util +geopandas\.datasets\.* + +# Inconsistent OK +geopandas\.(geodataframe\.)?GeoDataFrame\.plot + +# Failed to import OK (require extra dependencies) +geopandas\.io\._geoarrow +geopandas\._exports + +# stub parameter differs from runtime parameter "self" +geopandas.geodataframe.GeoDataFrame.explore +geopandas.geoseries.GeoSeries.explore +geopandas.geoseries.GeoSeries.plot + +# Inconsistent (TODO) +geopandas\.(geoseries\.)?GeoSeries\.apply +geopandas\.(geoseries\.)?GeoSeries\.fillna +geopandas\.(geoseries\.)?GeoSeries\.sort_index diff --git a/stubs/geopandas/METADATA.toml b/stubs/geopandas/METADATA.toml new file mode 100644 index 000000000000..653120efd9b8 --- /dev/null +++ b/stubs/geopandas/METADATA.toml @@ -0,0 +1,9 @@ +version = "1.1.4" +upstream-repository = "https://github.com/geopandas/geopandas" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20", "pandas-stubs", "types-shapely", "pyproj"] + +[tool.stubtest] +# libproj-dev and proj-bin are required to build pyproj if wheels for the +# target Python version are not available. +apt-dependencies = ["libproj-dev", "proj-bin"] diff --git a/stubs/geopandas/geopandas/__init__.pyi b/stubs/geopandas/geopandas/__init__.pyi new file mode 100644 index 000000000000..d2a3b1899ed1 --- /dev/null +++ b/stubs/geopandas/geopandas/__init__.pyi @@ -0,0 +1,20 @@ +from typing import Final + +from ._config import options as options +from ._exports import ( + gpd as gpd, + list_layers as list_layers, + np as np, + pd as pd, + read_feather as read_feather, + read_file as read_file, + read_parquet as read_parquet, + read_postgis as read_postgis, +) +from .array import points_from_xy as points_from_xy +from .geodataframe import GeoDataFrame as GeoDataFrame +from .geoseries import GeoSeries as GeoSeries +from .tools import clip as clip, overlay as overlay, sjoin as sjoin, sjoin_nearest as sjoin_nearest +from .tools._show_versions import show_versions as show_versions + +__version__: Final[str] diff --git a/stubs/geopandas/geopandas/_config.pyi b/stubs/geopandas/geopandas/_config.pyi new file mode 100644 index 000000000000..c60381fdc8ec --- /dev/null +++ b/stubs/geopandas/geopandas/_config.pyi @@ -0,0 +1,21 @@ +from _typeshed import SupportsItems, Unused +from collections.abc import Callable +from typing import Any, NamedTuple + +class Option(NamedTuple): + key: str + default_value: Any # Can be "any" type + doc: str + validator: Callable[[object], Unused] + callback: Callable[[str, object], Unused] | None + +class Options: + def __init__(self, options: SupportsItems[str, Option]) -> None: ... + # Accept and return arbitrary values + def __setattr__(self, key: str, value: Any) -> None: ... + def __getattr__(self, key: str) -> Any: ... + +display_precision: Option +use_pygeos: Option +io_engine: Option +options: Options diff --git a/stubs/geopandas/geopandas/_decorator.pyi b/stubs/geopandas/geopandas/_decorator.pyi new file mode 100644 index 000000000000..6d82bcec9198 --- /dev/null +++ b/stubs/geopandas/geopandas/_decorator.pyi @@ -0,0 +1,20 @@ +from collections.abc import Callable +from typing import TypeAlias, TypeVar, overload + +_AnyCallable: TypeAlias = Callable[..., object] +_Func = TypeVar("_Func", bound=_AnyCallable) + +# We (ab)use this decorator to also copy the signature of the source function (overload 1) +# The advantages are: +# - avoid copying all parameters and types manually while conserving type safety +# - signature properly handeled in IDEs (at least with Pylance) +# - docstring from the original function properly displayed (at least with Pylance) +# Using the other overloads returns the signature of the decorated function instead +@overload +def doc(func: _Func, /, **params: object) -> Callable[[_AnyCallable], _Func]: ... +@overload +def doc(docstring: str, /, *docstrings: str | _AnyCallable, **params: object) -> Callable[[_Func], _Func]: ... +@overload +def doc( + docstring1: str | _AnyCallable, docstring2: str | _AnyCallable, /, *docstrings: str | _AnyCallable, **params: object +) -> Callable[[_Func], _Func]: ... diff --git a/stubs/geopandas/geopandas/_exports.pyi b/stubs/geopandas/geopandas/_exports.pyi new file mode 100644 index 000000000000..cfea4e64c3e9 --- /dev/null +++ b/stubs/geopandas/geopandas/_exports.pyi @@ -0,0 +1,21 @@ +# Type checking-only module to export public symbols with a different name in __init__.pyi + +import geopandas as gpd +import numpy as np +import pandas as pd +from geopandas.io.arrow import _read_feather as read_feather, _read_parquet as read_parquet +from geopandas.io.file import _list_layers as list_layers, _read_file as read_file +from geopandas.io.sql import _read_postgis as read_postgis + +__all__ = [ + # IO functions + "read_file", + "read_feather", + "read_parquet", + "read_postgis", + "list_layers", + # Modules for interactive use + "np", + "pd", + "gpd", +] diff --git a/stubs/geopandas/geopandas/accessors.pyi b/stubs/geopandas/geopandas/accessors.pyi new file mode 100644 index 000000000000..d69a67fe594b --- /dev/null +++ b/stubs/geopandas/geopandas/accessors.pyi @@ -0,0 +1,7 @@ +from typing import Any + +import pandas as pd + +class GeoSeriesAccessor: + def __init__(self, series: pd.Series[Any]) -> None: ... # Cannot use pd.Series[BaseGeometry] + def __getattr__(self, name: str) -> Any: ... # Delegate all attributes to the GeoSeries diff --git a/stubs/geopandas/geopandas/array.pyi b/stubs/geopandas/geopandas/array.pyi new file mode 100644 index 000000000000..0d0d745aefc6 --- /dev/null +++ b/stubs/geopandas/geopandas/array.pyi @@ -0,0 +1,259 @@ +import builtins +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Collection +from typing import Any, ClassVar, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Never, Self, deprecated + +import numpy as np +import pandas as pd +from numpy.typing import ArrayLike, DTypeLike, NDArray +from pandas._typing import ScalarIndexer, SequenceIndexer, TakeIndexer +from pandas.api.extensions import ExtensionArray, ExtensionDtype +from pyproj import CRS, Transformer +from shapely import Geometry +from shapely.geometry.base import BaseGeometry + +from .base import _AffinityOrigin, _ConvertibleToCRS +from .sindex import SpatialIndex + +_ScalarType = TypeVar("_ScalarType", bound=np.generic) +_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarType]] +_Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_ScalarType]] +_ArrayOrGeom: TypeAlias = GeometryArray | ArrayLike | Geometry + +TransformerFromCRS = Transformer.from_crs +POLYGON_GEOM_TYPES: Final[set[str]] +LINE_GEOM_TYPES: Final[set[str]] +POINT_GEOM_TYPES: Final[set[str]] + +class GeometryDtype(ExtensionDtype): + type: ClassVar[type[BaseGeometry]] + name: ClassVar[str] + na_value: None + @classmethod + def construct_from_string(cls, string: str) -> Self: ... + @classmethod + def construct_array_type(cls) -> builtins.type[GeometryArray]: ... + +def isna(value: object) -> bool: ... +def from_shapely(data, crs: _ConvertibleToCRS | None = None) -> GeometryArray: ... +def to_shapely(geoms: GeometryArray) -> _Array1D[np.object_]: ... +def from_wkb( + data, crs: _ConvertibleToCRS | None = None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise" +) -> GeometryArray: ... + +@overload +def to_wkb(geoms: GeometryArray, hex: Literal[False] = False, **kwargs) -> _Array1D[np.bytes_]: ... +@overload +def to_wkb(geoms: GeometryArray, hex: Literal[True], **kwargs) -> _Array1D[np.str_]: ... + +def from_wkt( + data, crs: _ConvertibleToCRS | None = None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise" +) -> GeometryArray: ... +def to_wkt(geoms: GeometryArray, **kwargs) -> _Array1D[np.str_]: ... +def points_from_xy( + x: ArrayLike, y: ArrayLike, z: ArrayLike | None = None, crs: _ConvertibleToCRS | None = None +) -> GeometryArray: ... + +class GeometryArray(ExtensionArray): + def __init__(self, data: GeometryArray | NDArray[np.object_], crs: _ConvertibleToCRS | None = None) -> None: ... + @property + def sindex(self) -> SpatialIndex: ... + @property + def has_sindex(self) -> bool: ... + + @property + def crs(self) -> CRS | None: ... + @crs.setter + def crs(self, value: _ConvertibleToCRS | None) -> None: ... + + def check_geographic_crs(self, stacklevel: int) -> None: ... + @property + def dtype(self) -> GeometryDtype: ... + def __len__(self) -> int: ... + + # np.integer[Any] because precision is not important + @overload + def __getitem__(self, idx: ScalarIndexer) -> BaseGeometry: ... # Always 1-D, doesn't accept tuple + @overload + def __getitem__(self, idx: SequenceIndexer) -> GeometryArray: ... + + def __setitem__( + self, key, value: _ArrayOrGeom | pd.DataFrame | pd.Series[Any] # Cannot use pd.Series[BaseGeometry] + ) -> None: ... + @property + def is_valid(self) -> _Array1D[np.bool_]: ... + def is_valid_reason(self) -> _Array1D[np.object_]: ... + def is_valid_coverage(self, gap_width: float = 0.0) -> bool: ... + def invalid_coverage_edges(self, gap_width: float = 0.0) -> _Array1D[np.object_]: ... + @property + def is_empty(self) -> _Array1D[np.bool_]: ... + @property + def is_simple(self) -> _Array1D[np.bool_]: ... + @property + def is_ring(self) -> _Array1D[np.bool_]: ... + @property + def is_closed(self) -> _Array1D[np.bool_]: ... + @property + def is_ccw(self) -> _Array1D[np.bool_]: ... + @property + def has_z(self) -> _Array1D[np.bool_]: ... + @property + def has_m(self) -> _Array1D[np.bool_]: ... + @property + def geom_type(self) -> _Array1D[np.str_]: ... + @property + def area(self) -> _Array1D[np.float64]: ... + @property + def length(self) -> _Array1D[np.float64]: ... + def count_coordinates(self) -> _Array1D[np.int32]: ... + def count_geometries(self) -> _Array1D[np.int32]: ... + def count_interior_rings(self) -> _Array1D[np.int32]: ... + def get_precision(self) -> _Array1D[np.float64]: ... + def get_geometry(self, index: SupportsIndex | ArrayLike) -> _Array1D[np.object_]: ... + @property + def boundary(self) -> GeometryArray: ... + @property + def centroid(self) -> GeometryArray: ... + def concave_hull(self, ratio: float, allow_holes: bool) -> _Array1D[np.object_]: ... + def constrained_delaunay_triangles(self) -> GeometryArray: ... + @property + def convex_hull(self) -> GeometryArray: ... + @property + def envelope(self) -> GeometryArray: ... + def minimum_rotated_rectangle(self) -> GeometryArray: ... + @property + def exterior(self) -> GeometryArray: ... + def extract_unique_points(self) -> GeometryArray: ... + def offset_curve( + self, + distance: float | ArrayLike, + quad_segs: int = 8, + join_style: Literal["round", "bevel", "mitre"] = "round", + mitre_limit: float = 5.0, + ) -> GeometryArray: ... + @property + def interiors(self) -> _Array1D[np.object_]: ... + def remove_repeated_points(self, tolerance: float | ArrayLike = 0.0) -> GeometryArray: ... + def representative_point(self) -> GeometryArray: ... + def minimum_bounding_circle(self) -> GeometryArray: ... + def maximum_inscribed_circle(self, tolerance: float | ArrayLike) -> GeometryArray: ... + def minimum_bounding_radius(self) -> _Array1D[np.float64]: ... + def minimum_clearance(self) -> _Array1D[np.float64]: ... + def minimum_clearance_line(self) -> GeometryArray: ... + def normalize(self) -> GeometryArray: ... + def orient_polygons(self, exterior_cw: bool = False) -> GeometryArray: ... + def make_valid(self, method: Literal["linework", "structure"] = "linework", keep_collapsed: bool = True) -> GeometryArray: ... + def reverse(self) -> GeometryArray: ... + def segmentize(self, max_segment_length: float | ArrayLike) -> GeometryArray: ... + def force_2d(self) -> GeometryArray: ... + def force_3d(self, z: float | ArrayLike = 0) -> GeometryArray: ... + def transform( + self, transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], include_z: bool = False + ) -> GeometryArray: ... + def line_merge(self, directed: bool = False) -> GeometryArray: ... + def set_precision( + self, grid_size: float, mode: Literal["valid_output", "pointwise", "keep_collapsed", 0, 1, 2] = "valid_output" + ) -> GeometryArray: ... + def covers(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def covered_by(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def contains(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def contains_properly(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def crosses(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def disjoint(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def geom_equals(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def intersects(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def overlaps(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def touches(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def within(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def dwithin(self, other: _ArrayOrGeom, distance: float) -> _Array1D[np.bool_]: ... + def geom_equals_exact(self, other: _ArrayOrGeom, tolerance: float | ArrayLike) -> _Array1D[np.bool_]: ... + def geom_equals_identical(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def clip_by_rect(self, xmin: float, ymin: float, xmax: float, ymax: float) -> GeometryArray: ... + def difference(self, other: _ArrayOrGeom) -> GeometryArray: ... + def intersection(self, other: _ArrayOrGeom) -> GeometryArray: ... + def symmetric_difference(self, other: _ArrayOrGeom) -> GeometryArray: ... + def union(self, other: _ArrayOrGeom) -> GeometryArray: ... + def shortest_line(self, other: _ArrayOrGeom) -> GeometryArray: ... + def snap(self, other: _ArrayOrGeom, tolerance: float | ArrayLike) -> GeometryArray: ... + def shared_paths(self, other: _ArrayOrGeom) -> GeometryArray: ... + def distance(self, other: _ArrayOrGeom) -> _Array1D[np.float64]: ... + def hausdorff_distance(self, other: _ArrayOrGeom, **kwargs) -> _Array1D[np.float64]: ... + def frechet_distance(self, other: _ArrayOrGeom, **kwargs) -> _Array1D[np.float64]: ... + def buffer(self, distance: float | ArrayLike, resolution: int = 16, **kwargs) -> GeometryArray: ... + def interpolate(self, distance: float | ArrayLike, normalized: bool = False) -> GeometryArray: ... # type: ignore[override] + def simplify(self, tolerance: float | ArrayLike, preserve_topology: bool = True) -> GeometryArray: ... + def simplify_coverage(self, tolerance: float | ArrayLike, simplify_boundary: bool = True) -> GeometryArray: ... + def project(self, other: _ArrayOrGeom, normalized: bool = False) -> _Array1D[np.float64]: ... + def relate(self, other: _ArrayOrGeom) -> _Array1D[np.str_]: ... + def relate_pattern(self, other: _ArrayOrGeom, pattern: str) -> _Array1D[np.bool_]: ... + @deprecated("Use method `union_all` instead.") + def unary_union(self) -> BaseGeometry: ... + def union_all( + self, method: Literal["coverage", "unary", "disjoint_subset"] = "unary", grid_size: float | None = None + ) -> BaseGeometry: ... + def intersection_all(self) -> BaseGeometry: ... + def affine_transform(self, matrix: Collection[float]) -> GeometryArray: ... + def translate(self, xoff: float = 0.0, yoff: float = 0.0, zoff: float = 0.0) -> GeometryArray: ... + def rotate(self, angle: float, origin: _AffinityOrigin = "center", use_radians: bool = False) -> GeometryArray: ... + def scale( + self, xfact: float = 1.0, yfact: float = 1.0, zfact: float = 1.0, origin: _AffinityOrigin = "center" + ) -> GeometryArray: ... + def skew( + self, xs: float = 0.0, ys: float = 0.0, origin: _AffinityOrigin = "center", use_radians: bool = False + ) -> GeometryArray: ... + def to_crs(self, crs: _ConvertibleToCRS | None = None, epsg: int | None = None) -> GeometryArray: ... + def estimate_utm_crs(self, datum_name: str = "WGS 84") -> CRS: ... + @property + def x(self) -> _Array1D[np.float64]: ... + @property + def y(self) -> _Array1D[np.float64]: ... + @property + def z(self) -> _Array1D[np.float64]: ... + @property + def m(self) -> _Array1D[np.float64]: ... + @property + def bounds(self) -> _Array2D[np.float64]: ... + @property + def total_bounds(self) -> _Array1D[np.float64]: ... + @property + def size(self) -> int: ... + @property + def shape(self) -> tuple[int]: ... # Always 1-D, this is not mistaken for tuple[int, ...] + @property + def ndim(self) -> Literal[1]: ... + def copy(self, *args: Unused, **kwargs: Unused) -> GeometryArray: ... + def take(self, indices: TakeIndexer, allow_fill: bool = False, fill_value: Geometry | None = None) -> GeometryArray: ... + def fillna( # type: ignore[override] + self, + value: Geometry | GeometryArray | None = None, + method: Literal["backfill", "bfill", "pad", "ffill"] | None = None, + limit: int | None = None, + copy: bool = True, + ) -> GeometryArray: ... + + @overload # type: ignore[override] + def astype(self, dtype: GeometryDtype, copy: bool = True) -> GeometryArray: ... + @overload + def astype(self, dtype: ExtensionDtype | Literal["string"], copy: bool = True) -> ExtensionArray: ... # type: ignore[overload-overlap] + @overload + def astype(self, dtype: DTypeLike, copy: bool = True) -> _Array1D[Incomplete]: ... + + def isna(self) -> _Array1D[np.bool_]: ... + def value_counts(self, dropna: bool = True) -> pd.Series[int]: ... + def unique(self) -> GeometryArray: ... + @property + def nbytes(self) -> int: ... + def shift(self, periods: int = 1, fill_value: Geometry | None = None) -> GeometryArray: ... # type: ignore[override] + def argmin(self, skipna: bool = True) -> Never: ... + def argmax(self, skipna: bool = True) -> Never: ... + def __array__(self, dtype: DTypeLike | None = None, copy: bool | None = None) -> _Array1D[np.object_]: ... + def __eq__(self, other: object) -> _Array1D[np.bool_]: ... # type: ignore[override] + def __ne__(self, other: object) -> _Array1D[np.bool_]: ... # type: ignore[override] + def __contains__(self, item: object) -> np.bool_: ... + +# TODO: Improve `func` type with a callable protocol (with overloads for 2D and 3D geometries) +def transform( + data: NDArray[np.object_] | GeometryArray | pd.Series[Any], # Cannot use pd.Series[BaseGeometry] + func: Callable[..., NDArray[np.float64]], +) -> NDArray[np.object_]: ... diff --git a/stubs/geopandas/geopandas/base.pyi b/stubs/geopandas/geopandas/base.pyi new file mode 100644 index 000000000000..1cb2dc1c8420 --- /dev/null +++ b/stubs/geopandas/geopandas/base.pyi @@ -0,0 +1,246 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable, Collection, Hashable, Iterable, Mapping, Sequence +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated + +import numpy as np +import pandas as pd +from numpy.random import BitGenerator, Generator as RandomGenerator, SeedSequence +from numpy.typing import ArrayLike, NDArray +from pandas._typing import ListLikeU +from pandas.core.base import IndexOpsMixin +from pyproj import CRS +from shapely import Geometry, MultiPolygon, Point, Polygon +from shapely.geometry.base import BaseGeometry + +from .array import GeometryArray, _Array1D +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries +from .sindex import SpatialIndex + +@type_check_only +class _SupportsToWkt(Protocol): + def to_wkt(self) -> str: ... + +@type_check_only +class _SupportsGeoInterface(Protocol): # noqa: Y046 + @property + def __geo_interface__(self) -> dict[str, Any]: ... # values are arbitrary + +_ConvertibleToCRS: TypeAlias = str | int | tuple[str, str] | list[str] | dict[str, Incomplete] | _SupportsToWkt +_AffinityOrigin: TypeAlias = Literal["center", "centroid"] | Point | tuple[float, float] | tuple[float, float, float] +_ClipMask: TypeAlias = GeoDataFrame | GeoSeries | Polygon | MultiPolygon | tuple[float, float, float, float] # noqa: Y047 +# np.floating[Any] because precision is not important +_BboxLike: TypeAlias = Sequence[float] | NDArray[np.floating[Any]] | Geometry | GeoDataFrame | GeoSeries # noqa: Y047 +_MaskLike: TypeAlias = dict[str, Incomplete] | Geometry | GeoDataFrame | GeoSeries # noqa: Y047 + +# Cannot use IndexOpsMixin[Geometry] because of IndexOpsMixin type variable bounds +_GeoListLike: TypeAlias = ArrayLike | Sequence[Geometry] | IndexOpsMixin[Any] +_ConvertibleToGeoSeries: TypeAlias = Geometry | Mapping[int, Geometry] | Mapping[str, Geometry] | _GeoListLike # noqa: Y047 + +# Cannot use pd.Series[Geometry] because of pd.Series type variable bounds +_GeomSeq: TypeAlias = Sequence[Geometry] | NDArray[np.object_] | pd.Series[Any] | GeometryArray | GeoSeries +_GeomCol: TypeAlias = Hashable | _GeomSeq # name of column or column values # noqa: Y047 +# dict[Any, Any] because of variance issues +_ConvertibleToDataFrame: TypeAlias = ( # noqa: Y047 + ListLikeU | pd.DataFrame | dict[Any, Any] | Iterable[ListLikeU | tuple[Hashable, ListLikeU] | dict[Any, Any]] +) + +def is_geometry_type(data: object) -> bool: ... + +class GeoPandasBase: + @property + def area(self) -> pd.Series[float]: ... + + @property + def crs(self) -> CRS | None: ... + @crs.setter + def crs(self, value: _ConvertibleToCRS | None) -> None: ... + + @property + def geom_type(self) -> pd.Series[str]: ... + @property + def type(self) -> pd.Series[str]: ... + @property + def length(self) -> pd.Series[float]: ... + @property + def is_valid(self) -> pd.Series[bool]: ... + def is_valid_reason(self) -> pd.Series[str]: ... + def is_valid_coverage(self, *, gap_width: float = 0.0) -> bool: ... + def invalid_coverage_edges(self, *, gap_width: float = 0.0) -> GeoSeries: ... + @property + def is_empty(self) -> pd.Series[bool]: ... + def count_coordinates(self) -> pd.Series[int]: ... + def count_geometries(self) -> pd.Series[int]: ... + def count_interior_rings(self) -> pd.Series[int]: ... + @property + def is_simple(self) -> pd.Series[bool]: ... + @property + def is_ring(self) -> pd.Series[bool]: ... + @property + def is_ccw(self) -> pd.Series[bool]: ... + @property + def is_closed(self) -> pd.Series[bool]: ... + @property + def has_z(self) -> pd.Series[bool]: ... + @property + def has_m(self) -> pd.Series[bool]: ... + def get_precision(self) -> pd.Series[float]: ... + def get_geometry(self, index: SupportsIndex | ArrayLike) -> GeoSeries: ... + @property + def boundary(self) -> GeoSeries: ... + @property + def centroid(self) -> GeoSeries: ... + def concave_hull(self, ratio: float = 0.0, allow_holes: bool = False) -> GeoSeries: ... + def constrained_delaunay_triangles(self) -> GeoSeries: ... + @property + def convex_hull(self) -> GeoSeries: ... + def delaunay_triangles(self, tolerance: float | ArrayLike = 0.0, only_edges: bool | ArrayLike = False) -> GeoSeries: ... + def voronoi_polygons( + self, tolerance: float | ArrayLike = 0.0, extend_to: Geometry | None = None, only_edges: bool = False + ) -> GeoSeries: ... + @property + def envelope(self) -> GeoSeries: ... + def minimum_rotated_rectangle(self) -> GeoSeries: ... + @property + def exterior(self) -> GeoSeries: ... + def extract_unique_points(self) -> GeoSeries: ... + def offset_curve( + self, + distance: float | ArrayLike, + quad_segs: int = 8, + join_style: Literal["round", "bevel", "mitre"] = "round", + mitre_limit: float = 5.0, + ) -> GeoSeries: ... + @property + def interiors(self) -> pd.Series[Any]: ... # Cannot use pd.Series[BaseGeometry] + def remove_repeated_points(self, tolerance: float = 0.0) -> GeoSeries: ... + def set_precision( + self, grid_size: float, mode: Literal["valid_output", "pointwise", "keep_collapsed"] = "valid_output" + ) -> GeoSeries: ... + def representative_point(self) -> GeoSeries: ... + def minimum_bounding_circle(self) -> GeoSeries: ... + def maximum_inscribed_circle(self, *, tolerance: float | ArrayLike | None = None) -> GeoSeries: ... + def minimum_bounding_radius(self) -> pd.Series[float]: ... + def minimum_clearance(self) -> pd.Series[float]: ... + def minimum_clearance_line(self) -> GeoSeries: ... + def normalize(self) -> GeoSeries: ... + def orient_polygons(self, *, exterior_cw: bool = False) -> GeoSeries: ... + def make_valid(self, *, method: Literal["linework", "structure"] = "linework", keep_collapsed: bool = True) -> GeoSeries: ... + def reverse(self) -> GeoSeries: ... + def segmentize(self, max_segment_length: float | ArrayLike) -> GeoSeries: ... + def transform( + self, transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], include_z: bool = False + ) -> GeoSeries: ... + def force_2d(self) -> GeoSeries: ... + def force_3d(self, z: float | ArrayLike = 0) -> GeoSeries: ... + def line_merge(self, directed: bool = False) -> GeoSeries: ... + @property + @deprecated("Use method `union_all` instead.") + def unary_union(self) -> BaseGeometry: ... + def union_all( + self, method: Literal["coverage", "unary", "disjoint_subset"] = "unary", *, grid_size: float | None = None + ) -> BaseGeometry: ... + def intersection_all(self) -> BaseGeometry: ... + def contains(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def contains_properly(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def dwithin(self, other: GeoSeries | Geometry, distance: float | ArrayLike, align: bool | None = None) -> pd.Series[bool]: ... + def geom_equals(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def geom_equals_exact( + self, other: GeoSeries | Geometry, tolerance: float | ArrayLike, align: bool | None = None + ) -> pd.Series[bool]: ... + def geom_equals_identical(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def crosses(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def disjoint(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def intersects(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def overlaps(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def touches(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def within(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def covers(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def covered_by(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def distance(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[float]: ... + def hausdorff_distance( + self, other: GeoSeries | Geometry, align: bool | None = None, densify: float | ArrayLike | None = None + ) -> pd.Series[float]: ... + def frechet_distance( + self, other: GeoSeries | Geometry, align: bool | None = None, densify: float | ArrayLike | None = None + ) -> pd.Series[float]: ... + def difference(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def symmetric_difference(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def union(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def intersection(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def clip_by_rect(self, xmin: float, ymin: float, xmax: float, ymax: float) -> GeoSeries: ... + def shortest_line(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def snap(self, other: GeoSeries | Geometry, tolerance: float | ArrayLike, align: bool | None = None) -> GeoSeries: ... + def shared_paths(self, other: GeoSeries | Geometry, align: bool | None = None): ... + @property + def bounds(self) -> pd.DataFrame: ... + @property + def total_bounds(self) -> _Array1D[np.float64]: ... + @property + def sindex(self) -> SpatialIndex: ... + @property + def has_sindex(self) -> bool: ... + def buffer( + self, + distance: float | ArrayLike, + resolution: int = 16, + cap_style: Literal["round", "square", "flat"] = "round", + join_style: Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs, + ) -> GeoSeries: ... + def simplify(self, tolerance: float | ArrayLike, preserve_topology: bool = True) -> GeoSeries: ... + def simplify_coverage(self, tolerance: float | ArrayLike, *, simplify_boundary: bool = True) -> GeoSeries: ... + def relate(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[str]: ... + def relate_pattern(self, other: GeoSeries | Geometry, pattern: str, align: bool | None = None) -> pd.Series[bool]: ... + def project(self, other: GeoSeries | Geometry, normalized: bool = False, align: bool | None = None) -> pd.Series[float]: ... + def interpolate(self, distance: float | ArrayLike, normalized: bool = False) -> GeoSeries: ... + def affine_transform(self, matrix: Collection[float]) -> GeoSeries: ... + def translate(self, xoff: float = 0.0, yoff: float = 0.0, zoff: float = 0.0) -> GeoSeries: ... + def rotate(self, angle: float, origin: _AffinityOrigin = "center", use_radians: bool = False) -> GeoSeries: ... + def scale( + self, xfact: float = 1.0, yfact: float = 1.0, zfact: float = 1.0, origin: _AffinityOrigin = "center" + ) -> GeoSeries: ... + def skew( + self, xs: float = 0.0, ys: float = 0.0, origin: _AffinityOrigin = "center", use_radians: bool = False + ) -> GeoSeries: ... + @property + def cx(self) -> SupportsGetItem[tuple[SupportsIndex | slice, SupportsIndex | slice], Self]: ... + def get_coordinates( + self, include_z: bool = False, ignore_index: bool = False, index_parts: bool = False, *, include_m: bool = False + ) -> pd.DataFrame: ... + def hilbert_distance( + self, total_bounds: tuple[float, float, float, float] | Iterable[float] | None = None, level: int = 16 + ) -> pd.Series[int]: ... + + @overload + def sample_points( + self, + size: int | ArrayLike, + method: str = "uniform", + seed: None = None, + rng: int | ArrayLike | SeedSequence | BitGenerator | RandomGenerator | None = None, + **kwargs, + ) -> GeoSeries: ... + @overload + @deprecated("Parameter `seed` is deprecated. Use `rng` instead.") + def sample_points( + self, + size: int | ArrayLike, + method: str = "uniform", + *, + seed: int | ArrayLike | SeedSequence | BitGenerator | RandomGenerator, + rng: int | ArrayLike | SeedSequence | BitGenerator | RandomGenerator | None = None, + **kwargs, + ) -> GeoSeries: ... + + def build_area(self, node: bool = True) -> GeoSeries: ... + + @overload + def polygonize(self, node: bool = True, full: Literal[False] = False) -> GeoSeries: ... + @overload + def polygonize(self, node: bool = True, *, full: Literal[True]) -> tuple[GeoSeries, GeoSeries, GeoSeries, GeoSeries]: ... + @overload + def polygonize(self, node: bool, full: Literal[True]) -> tuple[GeoSeries, GeoSeries, GeoSeries, GeoSeries]: ... diff --git a/stubs/geopandas/geopandas/explore.pyi b/stubs/geopandas/geopandas/explore.pyi new file mode 100644 index 000000000000..1ecd3a1cb1cb --- /dev/null +++ b/stubs/geopandas/geopandas/explore.pyi @@ -0,0 +1,65 @@ +from collections.abc import Callable, Hashable, MutableMapping, Sequence +from typing import Any + +import branca # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +import folium # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +import pandas as pd +import xyzservices # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from matplotlib.colors import Colormap # type: ignore[import-not-found] +from numpy.typing import ArrayLike, NDArray + +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries + +def _explore( + df: GeoDataFrame, + column: Hashable | NDArray[Any] | pd.Series[Any] | None = None, # Accepts "any" array or series + cmap: str | Colormap | branca.colormap.ColorMap | Sequence[str] | Callable[[Any], str] | None = None, # accepts "any" object + color: str | ArrayLike | None = None, + m: folium.Map | None = None, + tiles: str | folium.TileLayer | xyzservices.TileProvider | None = "OpenStreetMap", + attr: str | None = None, + tooltip: bool = True, + popup: bool = False, + highlight: bool = True, + categorical: bool = False, + legend: bool = True, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + width: float | str = "100%", + height: float | str = "100%", + categories: Sequence[Any] | NDArray[Any] | pd.Series[Any] | pd.Index[Any] | None = None, # categories can have "any" type + classification_kwds: MutableMapping[str, Any] | None = None, + control_scale: bool = True, + marker_type: str | folium.Marker | None = None, + # The following kwds will never be typed more precisely than "Any" + marker_kwds: MutableMapping[str, Any] = {}, + style_kwds: MutableMapping[str, Any] = {}, + highlight_kwds: MutableMapping[str, Any] = {}, + missing_kwds: MutableMapping[str, Any] = {}, + tooltip_kwds: MutableMapping[str, Any] = {}, + popup_kwds: MutableMapping[str, Any] = {}, + legend_kwds: MutableMapping[str, Any] = {}, + map_kwds: MutableMapping[str, Any] = {}, + **kwargs, +) -> folium.Map: ... +def _explore_geoseries( + s: GeoSeries, + color: str | ArrayLike | None = None, + m: folium.Map | None = None, + tiles: str | folium.TileLayer | xyzservices.TileProvider | None = "OpenStreetMap", + attr: str | None = None, + highlight: bool = True, + width: float | str = "100%", + height: float | str = "100%", + control_scale: bool = True, + marker_type: str | folium.Marker | None = None, + # The following kwds will never be typed more precisely than "Any" + marker_kwds: MutableMapping[str, Any] = {}, + style_kwds: MutableMapping[str, Any] = {}, + highlight_kwds: MutableMapping[str, Any] = {}, + map_kwds: MutableMapping[str, Any] = {}, + **kwargs, +) -> folium.Map: ... diff --git a/stubs/geopandas/geopandas/geodataframe.pyi b/stubs/geopandas/geopandas/geodataframe.pyi new file mode 100644 index 000000000000..f51ba3119945 --- /dev/null +++ b/stubs/geopandas/geopandas/geodataframe.pyi @@ -0,0 +1,370 @@ +import io +import os +from _typeshed import Incomplete, SupportsGetItem, SupportsLenAndGetItem, SupportsRead, SupportsWrite +from collections.abc import Callable, Container, Hashable, Iterable, Iterator, Mapping, Sequence +from json import JSONEncoder +from typing import Any, Literal, overload +from typing_extensions import Self + +import pandas as pd +from numpy.typing import ArrayLike +from pandas._typing import AggFuncTypeFrame, Axes, Axis, Dtype, GroupByObject, IndexLabel, Scalar +from pyproj import CRS + +from ._decorator import doc +from .base import ( + GeoPandasBase, + _BboxLike, + _ClipMask, + _ConvertibleToCRS, + _ConvertibleToDataFrame, + _GeomCol, + _GeomSeq, + _MaskLike, + _SupportsGeoInterface, +) +from .explore import _explore +from .geoseries import GeoSeries +from .io._geoarrow import ArrowTable, _GeomEncoding +from .io.sql import _SQLConnection +from .plotting import GeoplotAccessor + +crs_mismatch_error: str + +class GeoDataFrame(GeoPandasBase, pd.DataFrame): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + # Override the weird annotation of DataFrame.__new__ in pandas-stubs + @overload + def __new__( + cls, + data: _ConvertibleToDataFrame | None = None, + index: Axes | None = None, + columns: Axes | None = None, + dtype: Dtype | None = None, + copy: bool | None = None, + *, + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + ) -> Self: ... + @overload + def __new__( + cls, + data: Scalar, + index: Axes, + columns: Axes, + dtype: Dtype | None = None, + copy: bool | None = None, + *, + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + ) -> Self: ... + + def __init__( + self, + data: _ConvertibleToDataFrame | None = None, + index: Axes | None = None, + columns: Axes | None = None, + dtype: Dtype | None = None, + copy: bool | None = None, + *, + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + ) -> None: ... + def __setattr__(self, attr: str, val: Any) -> None: ... # type: ignore[misc] # Can set arbitrary objects + + @property + def geometry(self) -> GeoSeries: ... + @geometry.setter + def geometry(self, col: _GeomSeq) -> None: ... + + @overload + def set_geometry( + self, col: _GeomCol, drop: bool | None = None, inplace: Literal[False] = False, crs: _ConvertibleToCRS | None = None + ) -> Self: ... + @overload + def set_geometry( + self, col: _GeomCol, drop: bool | None = None, *, inplace: Literal[True], crs: _ConvertibleToCRS | None = None + ) -> None: ... + @overload + def set_geometry( + self, col: _GeomCol, drop: bool | None, inplace: Literal[True], crs: _ConvertibleToCRS | None = None + ) -> None: ... + + @overload + def rename_geometry(self, col: Hashable, inplace: Literal[False] = False) -> Self: ... + @overload + def rename_geometry(self, col: Hashable, inplace: Literal[True]) -> None: ... + + @property + def active_geometry_name(self) -> str | None: ... + + @property + def crs(self) -> CRS | None: ... + @crs.setter + def crs(self, value: _ConvertibleToCRS | None) -> None: ... + + @classmethod + def from_dict( # type: ignore[override] + # Mapping[Any, Any] because of invariance keys and arbitrary values + cls, + data: Mapping[Any, Any], + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + **kwargs, + ) -> Self: ... + # Keep inline with GeoSeries.from_file and geopandas.io.file._read_file + @classmethod + def from_file( + cls, + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + *, + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + ignore_geometry: Literal[False] = False, + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # engine dependent + ) -> Self: ... + @classmethod + def from_features( + cls, + features: ( + _SupportsGeoInterface + | Mapping[str, _SupportsGeoInterface | SupportsGetItem[str, Incomplete]] + | Iterable[_SupportsGeoInterface | SupportsGetItem[str, Incomplete]] + ), + crs: _ConvertibleToCRS | None = None, + columns: Axes | None = None, + ) -> Self: ... + + @overload + @classmethod + def from_postgis( + cls, + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | list[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + *, + chunksize: int, + ) -> Iterator[GeoDataFrame]: ... + @overload + @classmethod + def from_postgis( + cls, + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | list[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + chunksize: None = None, + ) -> GeoDataFrame: ... + + @classmethod + def from_arrow( + cls, table, geometry: str | None = None, to_pandas_kwargs: Mapping[str, Incomplete] | None = None + ) -> GeoDataFrame: ... # TODO: `table: pyarrow.Table | table-like` + def to_json( # type: ignore[override] + self, + na: str = "null", + show_bbox: bool = False, + drop_id: bool = False, + to_wgs84: bool = False, + *, + # json.dumps kwargs + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[JSONEncoder] | None = None, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[..., Any] | None = None, # as typed in the json stdlib module + sort_keys: bool = False, + **kwargs, + ) -> str: ... + @property + def __geo_interface__(self) -> dict[str, Any]: ... # values are arbitrary + def iterfeatures( + self, na: str = "null", show_bbox: bool = False, drop_id: bool = False + ) -> Iterator[dict[str, Incomplete]]: ... + def to_geo_dict(self, na: str = "null", show_bbox: bool = False, drop_id: bool = False) -> dict[str, Incomplete]: ... + def to_wkb( + self, + hex: bool = False, + *, + # shapely kwargs + output_dimension: int = ..., + byte_order: int = ..., + include_srid: bool = ..., + flavor: Literal["iso", "extended"] = ..., + **kwargs, + ) -> pd.DataFrame: ... + def to_wkt( + self, + *, + # shapely kwargs + rounding_precision: int = ..., + trim: bool = ..., + output_dimension: int = ..., + old_3d: bool = ..., + **kwargs, + ) -> pd.DataFrame: ... + def to_arrow( + self, + *, + index: bool | None = None, + geometry_encoding: _GeomEncoding = "WKB", + interleaved: bool = True, + include_z: bool | None = None, + ) -> ArrowTable: ... + def to_parquet( # type: ignore[override] + self, + path: str | os.PathLike[str] | SupportsWrite[Incomplete], + index: bool | None = None, + compression: Literal["snappy", "gzip", "brotli", "lz4", "zstd"] | None = "snappy", + geometry_encoding: _GeomEncoding = "WKB", + write_covering_bbox: bool = False, + schema_version: str | None = None, + *, + engine: Literal["auto", "pyarrow"] = "auto", # Only these engines are supported, unlike pandas + **kwargs, + ) -> None: ... + def to_feather( + self, + path: str | os.PathLike[str] | SupportsWrite[Incomplete], + index: bool | None = None, + compression: Literal["zstd", "lz4", "uncompressed"] | None = None, + schema_version: str | None = None, + **kwargs, + ) -> None: ... + # Keep method to_file roughly in line with GeoSeries.to_file + def to_file( + self, + filename: str | os.PathLike[str] | io.BytesIO, + driver: str | None = None, + schema: dict[str, Incomplete] | None = None, + index: bool | None = None, + *, + # kwargs from `_to_file` function + mode: Literal["w", "a"] = "w", + crs: _ConvertibleToCRS | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + metadata: dict[str, str] | None = None, + # kwargs extracted from engines + layer: int | str | None = None, + encoding: str | None = None, + overwrite: bool | None = ..., + **kwargs, # engine and driver dependent + ) -> None: ... + + @overload + def set_crs( + self, crs: _ConvertibleToCRS, epsg: int | None = None, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs( + self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: bool = False, allow_override: bool = False) -> Self: ... + + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None = None, inplace: Literal[False] = False) -> Self: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: Literal[False] = False) -> Self: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: Literal[False] = False) -> Self: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None = None, *, inplace: Literal[True]) -> None: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None, inplace: Literal[True]) -> None: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: Literal[True]) -> None: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: Literal[True]) -> None: ... + + def estimate_utm_crs(self, datum_name: str = "WGS 84") -> CRS: ... + # def __getitem__(self, key): ... + def __delitem__(self, key) -> None: ... # type: ignore[misc] + # def __setitem__(self, key, value) -> None: ... + def copy(self, deep: bool = True) -> Self: ... # type: ignore[misc] + # def merge(self, *args, **kwargs) -> GeoDataFrame | pd.DataFrame: ... + def apply( # type: ignore[override] + self, + func: Callable[..., Incomplete], + axis: Axis = 0, + raw: bool = False, + result_type: Literal["expand", "reduce", "broadcast"] | None = None, + args: tuple[Any, ...] = (), # type inexpressible in the typing system + *, + by_row: Literal[False, "compat"] = "compat", + engine: Literal["python", "numba"] = "python", + engine_kwargs: dict[str, bool] | None = None, + **kwargs, + ) -> pd.DataFrame | pd.Series[Incomplete]: ... + def __finalize__(self, other, method: str | None = None, **kwargs) -> Self: ... # type: ignore[misc] + def dissolve( + self, + by: GroupByObject | None = None, + aggfunc: AggFuncTypeFrame = "first", + as_index: bool = True, + level: IndexLabel | None = None, + sort: bool = True, + observed: bool = False, + dropna: bool = True, + method: Literal["coverage", "unary", "disjoint_subset"] = "unary", + grid_size: float | None = None, + **kwargs, + ) -> GeoDataFrame: ... + def explode(self, column: IndexLabel | None = None, ignore_index: bool = False, index_parts: bool = False) -> Self: ... + def to_postgis( + self, + name: str, + con: _SQLConnection, + schema: str | None = None, + if_exists: Literal["fail", "replace", "append"] = "fail", + index: bool = False, + index_label: IndexLabel | None = None, + chunksize: int | None = None, + dtype: dict[Any, Incomplete] | None = None, # columns can be of "any" type + ) -> None: ... + @property + def plot(self) -> GeoplotAccessor: ... + @doc(_explore) # pyright: ignore[reportUnknownArgumentType] + def explore(self, *args, **kwargs): ... # signature of `_explore` copied in `@doc` + def sjoin( + self, + df: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + predicate: str = "intersects", + lsuffix: str = "left", + rsuffix: str = "right", + *, + # **kwargs passed to geopandas.sjoin + distance: float | ArrayLike | None = None, + on_attribute: str | Sequence[str] | None = None, + **kwargs, + ) -> GeoDataFrame: ... + def sjoin_nearest( + self, + right: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + max_distance: float | None = None, + lsuffix: str = "left", + rsuffix: str = "right", + distance_col: str | None = None, + exclusive: bool = False, + ) -> GeoDataFrame: ... + def clip(self, mask: _ClipMask, keep_geom_type: bool = False, sort: bool = False) -> GeoDataFrame: ... # type: ignore[override] + def overlay( + self, right: GeoDataFrame, how: str = "intersection", keep_geom_type: bool | None = None, make_valid: bool = True + ) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/geoseries.pyi b/stubs/geopandas/geopandas/geoseries.pyi new file mode 100644 index 000000000000..cf5c5ca81337 --- /dev/null +++ b/stubs/geopandas/geopandas/geoseries.pyi @@ -0,0 +1,218 @@ +import io +import json +import os +from _typeshed import Incomplete, SupportsRead +from collections.abc import Callable, Hashable +from typing import Any, Literal, final, overload +from typing_extensions import Self + +import pandas as pd +from numpy.typing import ArrayLike +from pandas._typing import Axes, Dtype +from pyproj import CRS +from shapely.geometry.base import BaseGeometry + +from ._decorator import doc +from .array import GeometryArray +from .base import GeoPandasBase, _BboxLike, _ClipMask, _ConvertibleToCRS, _ConvertibleToGeoSeries, _MaskLike +from .explore import _explore_geoseries +from .io._geoarrow import GeoArrowArray +from .plotting import plot_series + +class GeoSeries(GeoPandasBase, pd.Series[BaseGeometry]): # type: ignore[type-var,misc] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-type-arguments] # pyrefly: ignore [bad-specialization, inconsistent-inheritance] + # Override the weird annotation of Series.__new__ in pandas-stubs + def __new__( + self, + data: _ConvertibleToGeoSeries | None = None, + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + def __init__( + self, + data: _ConvertibleToGeoSeries | None = None, + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> None: ... + @final # type: ignore[misc] + def copy(self, deep: bool = True) -> Self: ... + @property + def values(self) -> GeometryArray: ... + @property + def geometry(self) -> Self: ... + @property + def x(self) -> pd.Series[float]: ... + @property + def y(self) -> pd.Series[float]: ... + @property + def z(self) -> pd.Series[float]: ... + @property + def m(self) -> pd.Series[float]: ... + # Keep inline with GeoDataFrame.from_file and geopandas.io.file._read_file + @classmethod + def from_file( + cls, + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + *, + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + ignore_geometry: Literal[False] = False, + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # engine dependent + ) -> GeoSeries: ... + @classmethod + def from_wkb( + cls, + data: ArrayLike, # array-like of bytes handled by shapely.from_wkb(data) + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @classmethod + def from_wkt( + cls, + data: ArrayLike, # array-like of str handled by shapely.from_wkt(data) + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @classmethod + def from_xy( + cls, + # x, y, z: array-like of floats handled by np.asarray(..., dtype="float64") + x: ArrayLike, + y: ArrayLike, + z: ArrayLike | None = None, + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @classmethod + def from_arrow( + cls, + arr, + *, + # GeoSeries constructor kwargs + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @property + def __geo_interface__(self) -> dict[str, Any]: ... # values are arbitrary + # Keep method to_file roughly in line with GeoDataFrame.to_file + def to_file( + self, + filename: str | os.PathLike[str] | io.BytesIO, + driver: str | None = None, + index: bool | None = None, + *, + # kwargs from `_to_file` function + schema: dict[str, Incomplete] | None = None, + mode: Literal["w", "a"] = "w", + crs: _ConvertibleToCRS | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + metadata: dict[str, str] | None = None, + # kwargs extracted from engines + layer: int | str | None = None, + encoding: str | None = None, + overwrite: bool | None = ..., + **kwargs, # engine and driver dependent + ) -> None: ... + # *** `__getitem__`, `sort_index` and `take` are annotated with `-> Self` in pandas-stubs; no need to override them *** + # *** `apply` annotation in pandas-stubs is compatible except for deprecated `convert_dtype` argument *** + # def apply(self, func, convert_dtype: bool | None = None, args=(), **kwargs): ... + def isna(self) -> pd.Series[bool]: ... + def isnull(self) -> pd.Series[bool]: ... + def notna(self) -> pd.Series[bool]: ... + def notnull(self) -> pd.Series[bool]: ... + # *** TODO: `fillna` annotation in pandas-stubs is NOT compatible; must `-> Self` *** + # def fillna(self, value=None, method: FillnaOptions | None = None, inplace: bool = False, **kwargs): ... + def __contains__(self, other: object) -> bool: ... # type: ignore[misc] + @doc(plot_series) + def plot(self, *args, **kwargs): ... # type: ignore[override] # signature of `plot_series` copied in `@doc` + @doc(_explore_geoseries) # pyright: ignore[reportUnknownArgumentType] + def explore(self, *args, **kwargs): ... # signature of `_explore_geoseries` copied in `@doc` + def explode(self, ignore_index: bool = False, index_parts: bool = False) -> GeoSeries: ... + + @overload + def set_crs( + self, crs: _ConvertibleToCRS, epsg: int | None = None, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs( + self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: bool = False, allow_override: bool = False) -> Self: ... + + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None = None) -> GeoSeries: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None = None, *, epsg: int) -> GeoSeries: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None, epsg: int) -> GeoSeries: ... + + def estimate_utm_crs(self, datum_name: str = "WGS 84") -> CRS: ... + def to_json( # type: ignore[override] + self, + show_bbox: bool = True, + drop_id: bool = False, + to_wgs84: bool = False, + *, + # Keywords from json.dumps + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[json.JSONEncoder] | None = None, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[..., Any] | None = None, # as typed in the json stdlib module + sort_keys: bool = False, + **kwds, + ) -> str: ... + + @overload + def to_wkb(self, hex: Literal[False] = False, **kwargs) -> pd.Series[bytes]: ... + @overload + def to_wkb(self, hex: Literal[True], **kwargs) -> pd.Series[str]: ... + @overload + def to_wkb(self, hex: bool = False, **kwargs) -> pd.Series[str] | pd.Series[bytes]: ... + + def to_wkt(self, **kwargs) -> pd.Series[str]: ... + def to_arrow( + self, + geometry_encoding: Literal["WKB", "geoarrow", "wkb", "GeoArrow"] = "WKB", + interleaved: bool | None = True, + include_z: bool | None = None, + ) -> GeoArrowArray: ... + def clip(self, mask: _ClipMask, keep_geom_type: bool = False, sort: bool = False) -> GeoSeries: ... # type: ignore[override] diff --git a/stubs/geopandas/geopandas/io/__init__.pyi b/stubs/geopandas/geopandas/io/__init__.pyi new file mode 100644 index 000000000000..43612d29b8bc --- /dev/null +++ b/stubs/geopandas/geopandas/io/__init__.pyi @@ -0,0 +1 @@ +from . import arrow as arrow, file as file, sql as sql diff --git a/stubs/geopandas/geopandas/io/_geoarrow.pyi b/stubs/geopandas/geopandas/io/_geoarrow.pyi new file mode 100644 index 000000000000..720cd25f9358 --- /dev/null +++ b/stubs/geopandas/geopandas/io/_geoarrow.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import ( + # pyarrow types returned as Any to avoid depending on pyarrow (40 MB) in stubs + Any as _PAArray, + Any as _PAField, + Any as _PATable, + Literal, + Protocol, + TypeAlias, + type_check_only, +) +from typing_extensions import CapsuleType + +import numpy as np +from numpy.typing import NDArray + +from ..array import GeometryArray +from ..geodataframe import GeoDataFrame + +# Literal for language server completions and str because runtime normalizes to lowercase +_GeomEncoding: TypeAlias = Literal["WKB", "geoarrow"] | str # noqa: Y051 + +@type_check_only +class _PyarrowTableLike(Protocol): + def __arrow_c_stream__(self, requested_schema=None) -> CapsuleType: ... + +@type_check_only +class _PyarrowFieldLike(Protocol): + def __arrow_c_schema__(self) -> CapsuleType: ... + +@type_check_only +class _PyarrowArrayLike(Protocol): + def __arrow_c_array__(self) -> tuple[CapsuleType, CapsuleType]: ... + +GEOARROW_ENCODINGS: list[str] + +class ArrowTable: + def __init__(self, pa_table: _PyarrowTableLike) -> None: ... + def __arrow_c_stream__(self, requested_schema=None) -> CapsuleType: ... + +class GeoArrowArray: + def __init__(self, pa_field: _PyarrowFieldLike, pa_array: _PyarrowArrayLike) -> None: ... + def __arrow_c_array__(self, requested_schema=None) -> tuple[CapsuleType, CapsuleType]: ... + +def geopandas_to_arrow( + df: GeoDataFrame, + index: bool | None = None, + geometry_encoding: _GeomEncoding = "WKB", + interleaved: bool = True, + include_z: bool | None = None, +) -> tuple[_PATable, dict[str, str]]: ... +def construct_wkb_array( + shapely_arr: NDArray[np.object_], *, field_name: str = "geometry", crs: str | None = None +) -> tuple[_PAField, _PAArray]: ... +def construct_geometry_array( + shapely_arr: NDArray[np.object_], + include_z: bool | None = None, + *, + field_name: str = "geometry", + crs: str | None = None, + interleaved: bool = True, +) -> tuple[_PAField, _PAArray]: ... +def arrow_to_geopandas( + table, geometry: str | None = None, to_pandas_kwargs: Mapping[str, Incomplete] | None = None +) -> GeoDataFrame: ... +def arrow_to_geometry_array(arr) -> GeometryArray: ... +def construct_shapely_array(arr: _PAArray, extension_name: str) -> NDArray[np.object_]: ... diff --git a/stubs/geopandas/geopandas/io/arrow.pyi b/stubs/geopandas/geopandas/io/arrow.pyi new file mode 100644 index 000000000000..88e2419b8d1e --- /dev/null +++ b/stubs/geopandas/geopandas/io/arrow.pyi @@ -0,0 +1,28 @@ +import os +from _typeshed import Incomplete, SupportsGetItem, SupportsKeysAndGetItem +from collections.abc import Iterable, Mapping +from typing import Any, Final + +from ..geodataframe import GeoDataFrame + +METADATA_VERSION: Final[str] +SUPPORTED_VERSIONS_LITERAL = Incomplete +SUPPORTED_VERSIONS: Final[list[str]] +GEOARROW_ENCODINGS: Final[list[str]] +SUPPORTED_ENCODINGS: Final[list[str]] +PARQUET_GEOMETRY_ENCODINGS = Incomplete + +def _read_parquet( + path: str | os.PathLike[str], + columns: Iterable[str] | None = None, + storage_options: SupportsKeysAndGetItem[str, Any] | None = None, # type depend on the connection + bbox: SupportsGetItem[int, float] | None = None, + to_pandas_kwargs: Mapping[str, Incomplete] | None = None, + **kwargs, # kwargs passed to pyarrow.parquet.read_table +) -> GeoDataFrame: ... +def _read_feather( + path: str | os.PathLike[str], + columns: Iterable[str] | None = None, + to_pandas_kwargs: Mapping[str, Incomplete] | None = None, + **kwargs, # kwargs passed to pyarrow.feather.read_table +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/io/file.pyi b/stubs/geopandas/geopandas/io/file.pyi new file mode 100644 index 000000000000..ec2b63b9e198 --- /dev/null +++ b/stubs/geopandas/geopandas/io/file.pyi @@ -0,0 +1,48 @@ +import os +from _typeshed import Incomplete, SupportsRead +from collections import OrderedDict +from typing import Literal, TypedDict, overload, type_check_only + +import pandas as pd +from pandas._typing import Axes + +from ..base import _BboxLike, _MaskLike +from ..geodataframe import GeoDataFrame + +# Keep inline with GeoDataFrame.from_file and GeoSeries.from_file +@overload +def _read_file( + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + columns: Axes | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + *, + ignore_geometry: Literal[False] = False, + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # depend on engine +) -> GeoDataFrame: ... +@overload +def _read_file( + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + columns: Axes | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + *, + ignore_geometry: Literal[True], + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # depend on engine +) -> pd.DataFrame: ... + +@type_check_only +class _Schema(TypedDict): + geometry: str | list[str] + properties: OrderedDict[str, str] + +def infer_schema(df: GeoDataFrame) -> _Schema: ... +def _list_layers(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | SupportsRead[Incomplete]) -> pd.DataFrame: ... diff --git a/stubs/geopandas/geopandas/io/sql.pyi b/stubs/geopandas/geopandas/io/sql.pyi new file mode 100644 index 000000000000..a68afccb51ed --- /dev/null +++ b/stubs/geopandas/geopandas/io/sql.pyi @@ -0,0 +1,117 @@ +import sqlite3 +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Container, Iterator, Mapping +from contextlib import AbstractContextManager +from typing import Any, Protocol, TypeAlias, overload, type_check_only + +from pandas._typing import Scalar + +from ..base import _ConvertibleToCRS +from ..geodataframe import GeoDataFrame + +# Start SQLAlchemy hack +# --------------------- +# The code actually explicitly checks for SQLAlchemy's `Connection` and `Engine` with +# isinstance checks. However to avoid a dependency on SQLAlchemy, we use "good-enough" +# protocols that match as much as possible the SQLAlchemy implementation. This makes it +# very hard for someone to pass in the wrong object. +@type_check_only +class _SqlalchemyTransactionLike(Protocol): + # is_active: bool + # connection: _SqlalchemyConnectionLike + # def __init__(self, connection: _SqlalchemyConnectionLike): ... + # @property + # def is_valid(self) -> bool: ... + def close(self) -> None: ... + def rollback(self) -> None: ... + def commit(self) -> None: ... + +# `Any` is used in places where it would require to copy a lot of types from sqlalchemy +@type_check_only +class _SqlAlchemyEventTarget(Protocol): + dispatch: Any + +@type_check_only +class _SqlalchemyConnectionLike(_SqlAlchemyEventTarget, Protocol): + engine: Any + @property + def closed(self) -> bool: ... + @property + def invalidated(self) -> bool: ... + def __enter__(self) -> _SqlalchemyConnectionLike: ... # noqa: Y034 + def __exit__(self, type_, value, traceback, /) -> None: ... + @property + def info(self) -> dict[Any, Any]: ... + def invalidate(self, exception: BaseException | None = None) -> None: ... + def detach(self) -> None: ... + def begin(self) -> _SqlalchemyTransactionLike: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def recover_twophase(self) -> list[Any]: ... + def rollback_prepared(self, xid: Any, recover: bool = ...) -> None: ... + def commit_prepared(self, xid: Any, recover: bool = ...) -> None: ... + def in_transaction(self) -> bool: ... + def in_nested_transaction(self) -> bool: ... + def close(self) -> None: ... + +@type_check_only +class _SqlalchemyEngineLike(_SqlAlchemyEventTarget, Protocol): + dialect: Any + pool: Any + url: Any + hide_parameters: bool + @property + def engine(self) -> _SqlalchemyEngineLike: ... + def clear_compiled_cache(self) -> None: ... + def update_execution_options(self, **opt: Any) -> None: ... + @property + def name(self) -> str: ... + @property + def driver(self) -> str: ... + def dispose(self, close: bool = True) -> None: ... + def begin(self) -> AbstractContextManager[Any]: ... + def connect(self) -> Any: ... + +_SqlalchemyConnectableLike: TypeAlias = _SqlalchemyConnectionLike | _SqlalchemyEngineLike +# --------------------- +# End SQLAlchemy hack + +_SQLConnection: TypeAlias = str | _SqlalchemyConnectableLike | sqlite3.Connection # coppied from pandas.io.sql + +@overload +def _read_postgis( + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | Container[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + *, + chunksize: int, +) -> Iterator[GeoDataFrame]: ... +@overload +def _read_postgis( + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | Container[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + chunksize: None = None, +) -> GeoDataFrame: ... +@overload +def _read_postgis( + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | Container[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + chunksize: int | None = None, +) -> GeoDataFrame | Iterator[GeoDataFrame]: ... diff --git a/stubs/geopandas/geopandas/plotting.pyi b/stubs/geopandas/geopandas/plotting.pyi new file mode 100644 index 000000000000..4d08e752d64c --- /dev/null +++ b/stubs/geopandas/geopandas/plotting.pyi @@ -0,0 +1,259 @@ +from _typeshed import Incomplete +from collections.abc import Collection, Hashable, Iterable, Mapping, Sequence +from typing import Literal, TypeAlias, overload + +import numpy as np +import pandas as pd +from matplotlib.axes import Axes # type: ignore[import-not-found] +from matplotlib.colors import Colormap, Normalize # type: ignore[import-not-found] +from matplotlib.typing import ColorType # type: ignore[import-not-found] +from numpy.typing import ArrayLike, NDArray +from pandas.plotting import PlotAccessor + +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries + +_ColorOrColors: TypeAlias = ColorType | Sequence[ColorType] | ArrayLike + +def plot_series( + s: GeoSeries, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + figsize: tuple[float, float] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + autolim: bool = True, + *, + # Extracted from `**style_kwds` + vmin: float = ..., + vmax: float = ..., + facecolor: _ColorOrColors | None = None, + norm: Normalize | None = None, + **style_kwds, +) -> Axes: ... + +# IMPORTANT: keep roughly in sync with `GeoplotAccessor` methods below +def plot_dataframe( + df: GeoDataFrame, + column: Hashable | None = None, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + cax: Axes | None = None, + categorical: bool = False, + legend: bool = False, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + markersize: str | float | Iterable[float] | ArrayLike | None = None, + figsize: tuple[float, float] | None = None, + legend_kwds: dict[str, Incomplete] | None = None, + categories: Iterable[Hashable] | None = None, + classification_kwds: dict[str, Incomplete] | None = None, + missing_kwds: dict[str, Incomplete] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + autolim: bool = True, + *, + # Extracted from `**style_kwds` + norm: Normalize | None = None, + alpha: float = 1, + facecolor: _ColorOrColors | None = None, + edgecolor: _ColorOrColors | None = None, + linewidth: float = ..., + label: str = "NaN", + **style_kwds, +) -> Axes: ... + +# IMPORTANT: keep roughly in sync with `plot_dataframe` +class GeoplotAccessor(PlotAccessor): + # The first 3 overloads of calls are from pandas, the last overload is geopandas specific + @overload # type: ignore[override] + def __call__( + self, + x: Hashable = ..., + y: Hashable | Sequence[Hashable] = ..., + *, + kind: Literal["line", "bar", "barh", "hist", "box", "kde", "density", "area", "pie", "scatter", "hexbin"], + ax: Axes | None = None, + subplots: Literal[False] = False, + sharex: bool | None = None, + sharey: bool | None = None, + layout: tuple[int, int] | None = None, + figsize: tuple[float, float] | None = None, + use_index: bool = True, + title: str | None = None, + grid: bool | None = None, + legend: bool | Literal["reverse"] = True, + style: str | Sequence[str] | Mapping[Incomplete, str] | None = None, + logx: bool | Literal["sym"] = False, + logy: bool | Literal["sym"] = False, + loglog: bool | Literal["sym"] = False, + xticks: Sequence[float] | None = None, + yticks: Sequence[float] | None = None, + xlim: tuple[float, float] | list[float] | None = None, + ylim: tuple[float, float] | list[float] | None = None, + xlabel: str | None = None, + ylabel: str | None = None, + rot: float | None = None, + fontsize: float | None = None, + cmap: str | Colormap | None = None, # also accepts `colormap` but plot_dataframe uses `cmap` + colorbar: bool | None = None, + position: float = 0.5, + table: bool | pd.Series[Incomplete] | pd.DataFrame = False, + yerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + xerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + stacked: bool = ..., # default value depends on kind + secondary_y: bool | Sequence[Hashable] = False, + mark_right: bool = True, + include_bool: bool = False, + backend: str | None = None, + **kwargs, + ) -> Axes: ... + @overload + def __call__( + self, + x: Hashable = ..., + y: Hashable | Sequence[Hashable] = ..., + *, + kind: Literal["line", "bar", "barh", "hist", "kde", "density", "area", "pie", "scatter", "hexbin"], + ax: Sequence[Axes] | None = None, + subplots: Literal[True] | Iterable[Iterable[Hashable]], + sharex: bool | None = None, + sharey: bool | None = None, + layout: tuple[int, int] | None = None, + figsize: tuple[float, float] | None = None, + use_index: bool = True, + title: str | Collection[str] | None = None, + grid: bool | None = None, + legend: bool | Literal["reverse"] = True, + style: str | Sequence[str] | Mapping[Incomplete, str] | None = None, + logx: bool | Literal["sym"] = False, + logy: bool | Literal["sym"] = False, + loglog: bool | Literal["sym"] = False, + xticks: Sequence[float] | None = None, + yticks: Sequence[float] | None = None, + xlim: tuple[float, float] | list[float] | None = None, + ylim: tuple[float, float] | list[float] | None = None, + xlabel: str | None = None, + ylabel: str | None = None, + rot: float | None = None, + fontsize: float | None = None, + cmap: str | Colormap | None = None, # also accepts `colormap` but plot_dataframe uses `cmap` + colorbar: bool | None = None, + position: float = 0.5, + table: bool | pd.Series[Incomplete] | pd.DataFrame = False, + yerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + xerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + stacked: bool = ..., # default value depends on kind + secondary_y: bool | Sequence[Hashable] = False, + mark_right: bool = True, + include_bool: bool = False, + backend: str | None = None, + **kwargs, + ) -> NDArray[np.object_]: ... # should be NDArray[Axes] but it is not supported + @overload + def __call__( + self, + x: Hashable = ..., + y: Hashable | Sequence[Hashable] = ..., + *, + kind: Literal["box"], + ax: Sequence[Axes] | None = None, + subplots: Literal[True] | Iterable[Iterable[Hashable]], + sharex: bool | None = None, + sharey: bool | None = None, + layout: tuple[int, int] | None = None, + figsize: tuple[float, float] | None = None, + use_index: bool = True, + title: str | Collection[str] | None = None, + grid: bool | None = None, + legend: bool | Literal["reverse"] = True, + style: str | Sequence[str] | Mapping[Incomplete, str] | None = None, + logx: bool | Literal["sym"] = False, + logy: bool | Literal["sym"] = False, + loglog: bool | Literal["sym"] = False, + xticks: Sequence[float] | None = None, + yticks: Sequence[float] | None = None, + xlim: tuple[float, float] | list[float] | None = None, + ylim: tuple[float, float] | list[float] | None = None, + xlabel: str | None = None, + ylabel: str | None = None, + rot: float | None = None, + fontsize: float | None = None, + cmap: str | Colormap | None = None, # also accepts `colormap` but plot_dataframe uses `cmap` + colorbar: bool | None = None, + position: float = 0.5, + table: bool | pd.Series[Incomplete] | pd.DataFrame = False, + yerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + xerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + stacked: bool = ..., # default value depends on kind + secondary_y: bool | Sequence[Hashable] = False, + mark_right: bool = True, + include_bool: bool = False, + backend: str | None = None, + **kwargs, + ) -> pd.Series[Axes]: ... # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-type-arguments] # pyrefly: ignore [bad-specialization] + @overload + def __call__( + self, + column: Hashable | pd.Series | pd.Index | NDArray | None = None, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + cax: Axes | None = None, + categorical: bool = False, + legend: bool = False, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + markersize: str | float | Iterable[float] | ArrayLike | None = None, + figsize: tuple[float, float] | None = None, + legend_kwds: dict[str, Incomplete] | None = None, + categories: Iterable[Hashable] | None = None, + classification_kwds: dict[str, Incomplete] | None = None, + missing_kwds: dict[str, Incomplete] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + *, + kind: Literal["geo"] = "geo", + # Extracted from `**style_kwds` + norm: Normalize | None = None, + alpha: float = 1, + facecolor: _ColorOrColors | None = None, + edgecolor: _ColorOrColors | None = None, + linewidth: float = ..., + label: str = "NaN", + **style_kwds, + ) -> Axes: ... + + def geo( + self, + column: Hashable | pd.Series | pd.Index | NDArray | None = None, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + cax: Axes | None = None, + categorical: bool = False, + legend: bool = False, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + markersize: str | float | Iterable[float] | ArrayLike | None = None, + figsize: tuple[float, float] | None = None, + legend_kwds: dict[str, Incomplete] | None = None, + categories: Iterable[Hashable] | None = None, + classification_kwds: dict[str, Incomplete] | None = None, + missing_kwds: dict[str, Incomplete] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + *, + # Extracted from `**style_kwds` + norm: Normalize | None = None, + alpha: float = 1, + facecolor: _ColorOrColors | None = None, + edgecolor: _ColorOrColors | None = None, + linewidth: float = ..., + label: str = "NaN", + **style_kwds, + ) -> Axes: ... diff --git a/stubs/geopandas/geopandas/sindex.pyi b/stubs/geopandas/geopandas/sindex.pyi new file mode 100644 index 000000000000..1ef9bcb01ad9 --- /dev/null +++ b/stubs/geopandas/geopandas/sindex.pyi @@ -0,0 +1,82 @@ +from collections.abc import Iterable +from typing import Any, Final, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from shapely import Geometry + +from .array import _Array1D, _Array2D + +PREDICATES: Final[set[str | None]] + +class SpatialIndex: + geometries: NDArray[np.object_] + def __init__(self, geometry: NDArray[np.object_]) -> None: ... + @property + def valid_query_predicates(self) -> set[str | None]: ... + + @overload + def query( + self, + geometry: Geometry | ArrayLike, + predicate: str | None = None, + sort: bool = False, + distance: float | ArrayLike | None = None, + output_format: Literal["indices"] = "indices", + ) -> NDArray[np.int64]: ... + @overload + def query( + self, + geometry: Geometry | ArrayLike, + predicate: str | None = None, + sort: bool = False, + distance: float | ArrayLike | None = None, + *, + output_format: Literal["dense"], + ) -> NDArray[np.bool_]: ... + @overload + def query( + self, + geometry: Geometry | ArrayLike, + predicate: str | None = None, + sort: bool = False, + distance: float | ArrayLike | None = None, + *, + output_format: Literal["sparse"], + ) -> Any: ... # returns scipy coo_array but we don't depend on scipy + + @overload + def nearest( + self, + geometry, + return_all: bool = True, + max_distance: float | None = None, + return_distance: Literal[False] = False, + exclusive: bool = False, + ) -> _Array2D[np.int64]: ... + @overload + def nearest( + self, + geometry, + return_all: bool = True, + max_distance: float | None = None, + *, + return_distance: Literal[True], + exclusive: bool = False, + ) -> tuple[_Array2D[np.int64], _Array1D[np.float64]]: ... + @overload + def nearest( + self, + geometry, + return_all: bool = True, + max_distance: float | None = None, + return_distance: bool = False, + exclusive: bool = False, + ) -> _Array2D[np.int64] | tuple[_Array2D[np.int64], _Array1D[np.float64]]: ... + + def intersection(self, coordinates: Iterable[float]) -> _Array1D[np.int64]: ... + @property + def size(self) -> int: ... + @property + def is_empty(self) -> bool: ... + def __len__(self) -> int: ... diff --git a/stubs/geopandas/geopandas/testing.pyi b/stubs/geopandas/geopandas/testing.pyi new file mode 100644 index 000000000000..5293b09b40fc --- /dev/null +++ b/stubs/geopandas/geopandas/testing.pyi @@ -0,0 +1,33 @@ +from typing import Literal + +from .array import GeometryArray +from .base import GeoPandasBase +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries + +def geom_equals(this: GeoPandasBase | GeometryArray, that: GeoPandasBase | GeometryArray) -> bool: ... +def geom_almost_equals(this: GeoPandasBase | GeometryArray, that: GeoPandasBase | GeometryArray) -> bool: ... +def assert_geoseries_equal( + left: GeoSeries, + right: GeoSeries, + check_dtype: bool = True, + check_index_type: bool = False, + check_series_type: bool = True, + check_less_precise: bool = False, + check_geom_type: bool = False, + check_crs: bool = True, + normalize: bool = False, +) -> None: ... +def assert_geodataframe_equal( + left: GeoDataFrame, + right: GeoDataFrame, + check_dtype: bool = True, + check_index_type: bool | Literal["equiv"] = "equiv", + check_column_type: bool | Literal["equiv"] = "equiv", + check_frame_type: bool = True, + check_like: bool = False, + check_less_precise: bool = False, + check_geom_type: bool = False, + check_crs: bool = True, + normalize: bool = False, +) -> None: ... diff --git a/stubs/geopandas/geopandas/tools/__init__.pyi b/stubs/geopandas/geopandas/tools/__init__.pyi new file mode 100644 index 000000000000..a194399c228c --- /dev/null +++ b/stubs/geopandas/geopandas/tools/__init__.pyi @@ -0,0 +1,7 @@ +from .clip import clip as clip +from .geocoding import geocode as geocode, reverse_geocode as reverse_geocode +from .overlay import overlay as overlay +from .sjoin import sjoin as sjoin, sjoin_nearest as sjoin_nearest +from .util import collect as collect + +__all__ = ["collect", "geocode", "overlay", "reverse_geocode", "sjoin", "sjoin_nearest", "clip"] diff --git a/stubs/geopandas/geopandas/tools/_show_versions.pyi b/stubs/geopandas/geopandas/tools/_show_versions.pyi new file mode 100644 index 000000000000..1eeec0747405 --- /dev/null +++ b/stubs/geopandas/geopandas/tools/_show_versions.pyi @@ -0,0 +1 @@ +def show_versions() -> None: ... diff --git a/stubs/geopandas/geopandas/tools/clip.pyi b/stubs/geopandas/geopandas/tools/clip.pyi new file mode 100644 index 000000000000..bf91bbce3bbb --- /dev/null +++ b/stubs/geopandas/geopandas/tools/clip.pyi @@ -0,0 +1,9 @@ +from typing import TypeVar + +from ..base import _ClipMask +from ..geodataframe import GeoDataFrame +from ..geoseries import GeoSeries + +_G = TypeVar("_G", GeoDataFrame, GeoSeries) + +def clip(gdf: _G, mask: _ClipMask, keep_geom_type: bool = False, sort: bool = False) -> _G: ... diff --git a/stubs/geopandas/geopandas/tools/geocoding.pyi b/stubs/geopandas/geopandas/tools/geocoding.pyi new file mode 100644 index 000000000000..3748d7945de1 --- /dev/null +++ b/stubs/geopandas/geopandas/tools/geocoding.pyi @@ -0,0 +1,18 @@ +from collections.abc import Callable, Iterable +from typing import Protocol, type_check_only + +from ..base import _ConvertibleToGeoSeries +from ..geodataframe import GeoDataFrame + +@type_check_only +class _GeoCoder(Protocol): + # Represents a geopy.geocoders.base.GeoCoder subclass without actually depending on geopy + def geocode(self, query: str, /): ... + def reverse(self, coords, /, exactly_one: bool = ...): ... + +# TODO: Use something like `provider: Callable[P, _GeoCoder], **kwargs: P.kwargs` in the functions +# below if this ever becomes a thing +def geocode(strings: Iterable[str], provider: str | Callable[..., _GeoCoder] | None = None, **kwargs) -> GeoDataFrame: ... +def reverse_geocode( + points: _ConvertibleToGeoSeries, provider: str | Callable[..., _GeoCoder] | None = None, **kwargs +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/tools/hilbert_curve.pyi b/stubs/geopandas/geopandas/tools/hilbert_curve.pyi new file mode 100644 index 000000000000..9e9993ad673a --- /dev/null +++ b/stubs/geopandas/geopandas/tools/hilbert_curve.pyi @@ -0,0 +1 @@ +MAX_LEVEL: int diff --git a/stubs/geopandas/geopandas/tools/overlay.pyi b/stubs/geopandas/geopandas/tools/overlay.pyi new file mode 100644 index 000000000000..082d0ac5b15c --- /dev/null +++ b/stubs/geopandas/geopandas/tools/overlay.pyi @@ -0,0 +1,11 @@ +from typing import Literal + +from ..geodataframe import GeoDataFrame + +def overlay( + df1: GeoDataFrame, + df2: GeoDataFrame, + how: Literal["intersection", "union", "identity", "symmetric_difference", "difference"] = "intersection", + keep_geom_type: bool | None = None, + make_valid: bool = True, +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/tools/sjoin.pyi b/stubs/geopandas/geopandas/tools/sjoin.pyi new file mode 100644 index 000000000000..a902f71d3e05 --- /dev/null +++ b/stubs/geopandas/geopandas/tools/sjoin.pyi @@ -0,0 +1,26 @@ +from typing import Literal + +from numpy.typing import ArrayLike + +from ..geodataframe import GeoDataFrame + +def sjoin( + left_df: GeoDataFrame, + right_df: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + predicate: str = "intersects", + lsuffix: str = "left", + rsuffix: str = "right", + distance: float | ArrayLike | None = None, + on_attribute: str | tuple[str, ...] | list[str] | None = None, +) -> GeoDataFrame: ... +def sjoin_nearest( + left_df: GeoDataFrame, + right_df: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + max_distance: float | None = None, + lsuffix: str = "left", + rsuffix: str = "right", + distance_col: str | None = None, + exclusive: bool = False, +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/tools/util.pyi b/stubs/geopandas/geopandas/tools/util.pyi new file mode 100644 index 000000000000..ea80edd4c6aa --- /dev/null +++ b/stubs/geopandas/geopandas/tools/util.pyi @@ -0,0 +1,12 @@ +from collections.abc import Collection +from typing import Any + +import pandas as pd +from shapely import Geometry +from shapely.geometry.base import BaseGeometry + +from ..geoseries import GeoSeries + +def collect( + x: Collection[Geometry] | GeoSeries | pd.Series[Any] | Geometry, multi: bool = False # Cannot use pd.Series[BaseGeometry] +) -> BaseGeometry: ... diff --git a/stubs/gevent/@tests/stubtest_allowlist.txt b/stubs/gevent/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ed67e0945e91 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist.txt @@ -0,0 +1,164 @@ +# TODO: missing from stub +gevent.os.__all__ +gevent.socket.__all__ +gevent.ssl.__all__ +gevent.subprocess.__all__ + +# Error: failed to find stubs +# ============================= +# testing modules are not included in type stubs +gevent.testing +gevent.testing.* +gevent.tests +gevent.tests.* + +# these are only present for monkey patching and should not be used directly +gevent.thread +gevent.threading + +# deprecated module which should not be used anymore +gevent.builtins +gevent.contextvars +gevent.core + +# part of internal API which is not needed for public type stubs +gevent._ffi.callback + +# Error: is not present in stub +# ============================= +# internal API stuff we dropped because it wasn't necessary +gevent._config.Config.subclass +gevent._ffi.CRITICAL +gevent._ffi.DEBUG +gevent._ffi.ERROR +gevent._ffi.GEVENT_DEBUG_LEVEL +gevent._ffi.TRACE +gevent._ffi.loop.AbstractLoop.async +gevent._fileobjectcommon.UniversalNewlineBytesWrapper +gevent._waiter.Waiter.switch_args + +# loop local that wasn't deleted +gevent.resolver.blocking.Resolver.method + +# isn't actually implemented for libuv, it just raises an exception +gevent.libuv.watcher.watcher.feed + +# unnecessary python 2 compatibility stuff +gevent._config.Config.trace_malloc +gevent._imap.IMapUnordered.next +gevent.pywsgi.Environ.iteritems + +# weird method that doesn't work with this being generic, so we removed it +# it's not necessary for public API +gevent.hub.Waiter.switch_args + +# zope.interface related attributes we can ignore +gevent.[\w\.]+\.__implemented__ +gevent.[\w\.]+\.__providedBy__ +gevent.[\w\.]+\.__provides__ + +# these shouldn't be in __all__ they end up there, due to how gevent imports +# the globals from the stdlib ssl module, For ssl/subprocess we ignore all symbols +# that start with an underscore (i.e. internal symbols) +gevent\.ssl\._[A-Za-z0-9]\w* +gevent.ssl.base64 +gevent.ssl.create_connection +gevent.ssl.errno +gevent.ssl.os +gevent.ssl.warnings +gevent\.subprocess\._[A-Za-z0-9]\w* + +# Error: differs from runtime type +# ====================== +# these are None in the base class, but all settings are a subclass +# so it makes sense to annotate this as not None +gevent._config.Setting.default +gevent._config.Setting.environment_key +gevent._config.Setting.name +gevent._config.Setting.value + +# it is set to None on the class but always initialized in __init__ +gevent.hub.Hub.thread_ident +gevent.pywsgi.WSGIServer.error_log +gevent.pywsgi.WSGIServer.log + +# Error: is inconsistent +# ====================== +# minor config validation implementation difference that don't matter for +# the actual subclasses, which are proper settings. +gevent._config.SettingType.__new__ +gevent._config._PositiveValueMixin.validate + +# internal API implementation detail we don't care about +gevent._ffi.watcher.AbstractWatcherType.__new__ + +# we don't care about write/writeall allowing a named parameter +gevent._fileobjectcommon.FlushingBufferedWriter.write +gevent._fileobjectcommon.WriteIsWriteallMixin.write +gevent._fileobjectcommon.WriteallMixin.writeall + +# these are different because of Cython, without Cython these don't have +# any arguments, so it should be annotated that way +gevent._ident.IdentRegistry.__init__ +gevent.event.AsyncResult.__init__ +gevent.event.Event.__init__ + +# positional only arguments due to Cython? +gevent._abstract_linkable.AbstractLinkable.rawlink +gevent._abstract_linkable.AbstractLinkable.unlink + +# removed undocumented arguments for internal use +gevent.greenlet.Greenlet.link +gevent.greenlet.Greenlet.link_exception +gevent.greenlet.Greenlet.link_value +gevent._threading.Queue.qsize + +# removed deprecated argument +gevent._hub_primitives.wait_readwrite +gevent._hub_primitives.wait_write +gevent.pywsgi.WSGIHandler.__init__ + +# we have punted on socket, the gevent version of these functions sometimes use +# named parameters, while the base implementation only allows positional arguments +# we're fine with holding the geven implemenation to the same restrictions +# additionally there's some functions with additional optional arguments, that +# we are fine with ignoring for now as well +gevent.socket.cancel_wait + +# gevent overwrites with a named parameter for fd, but we're fine with only +# supporting the API of the superclass +gevent.threadpool.ThreadPoolExecutor.submit + +# Error: is not a type/function +# ===================== +# zope.interface related errors, these shouldn't matter +gevent._monitor.implementer +gevent.events.implementer +gevent.events.IEventLoopBlocked +gevent.events.IGeventDidPatchAllEvent +gevent.events.IGeventDidPatchBuiltinModulesEvent +gevent.events.IGeventDidPatchEvent +gevent.events.IGeventDidPatchModuleEvent +gevent.events.IGeventPatchEvent +gevent.events.IGeventWillPatchAllEvent +gevent.events.IGeventWillPatchEvent +gevent.events.IGeventWillPatchModuleEvent +gevent.events.IMemoryUsageThresholdExceeded +gevent.events.IMemoryUsageUnderThreshold +gevent.events.IPeriodicMonitorThread +gevent.events.IPeriodicMonitorThreadStartedEvent + +# Error: failed to import +# ====================== +# internal use module for some complex protocols used across different modules +# so there wasn't really a great place for them +gevent._types + +# The first parameter is technically positional-or-keyword but there's no +# useful way to use it as a keyword argument; we mark it positional-only. +gevent.pool.GroupMappingMixin.imap +gevent.pool.GroupMappingMixin.imap_unordered + +# Importing gevent.monkey.__main__ leads to issues in stubtest, since gevent will +# try to monkeypatch stubtest +gevent.monkey.__main__ diff --git a/stubs/gevent/@tests/stubtest_allowlist_darwin.txt b/stubs/gevent/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..9ef60bc83f94 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,14 @@ +# Error: is not present in stub +# ============================= +# internal API stuff we dropped because it wasn't necessary +gevent.libev.corecext.loop.async + +# Error: is inconsistent +# ====================== +# these are inconsistent due to the ParamSpec hack for positional only callables +gevent.libev.corecext.loop.run_callback +gevent.libev.corecext.loop.run_callback_threadsafe +gevent.libev.watcher.watcher.feed + +# undocumented argument for internal use only +gevent.libev.watcher.watcher.__init__ diff --git a/stubs/gevent/@tests/stubtest_allowlist_linux.txt b/stubs/gevent/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..9ef60bc83f94 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,14 @@ +# Error: is not present in stub +# ============================= +# internal API stuff we dropped because it wasn't necessary +gevent.libev.corecext.loop.async + +# Error: is inconsistent +# ====================== +# these are inconsistent due to the ParamSpec hack for positional only callables +gevent.libev.corecext.loop.run_callback +gevent.libev.corecext.loop.run_callback_threadsafe +gevent.libev.watcher.watcher.feed + +# undocumented argument for internal use only +gevent.libev.watcher.watcher.__init__ diff --git a/stubs/gevent/@tests/stubtest_allowlist_win32.txt b/stubs/gevent/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..f64157a5bae8 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,19 @@ +# Error: is not present in stub +# ============================= +# these get exported but don't actually work on win32 so we ignore them +gevent.signal.__all__ +gevent.signal.getsignal +gevent.signal.signal +gevent.signal.set_wakeup_fd + +# the docs say this doesn't work on windows, so it has been removed +gevent._ffi.loop.AbstractLoop.fork + +# for some reason this extension exists even though it is not supported on windows +gevent.libev.corecext.* + +# Error: failed to import +# ============================= +# these won't work until we find out if we can install libev somehow with choco +gevent.libev.corecffi +gevent.libev.watcher diff --git a/stubs/gevent/METADATA.toml b/stubs/gevent/METADATA.toml new file mode 100644 index 000000000000..9680c6db9497 --- /dev/null +++ b/stubs/gevent/METADATA.toml @@ -0,0 +1,12 @@ +version = "26.9.*" +upstream-repository = "https://github.com/gevent/gevent" +dependencies = ["types-greenlet", "types-psutil>=7.2.0"] + +[tool.stubtest] +# Run stubtest on all platforms, since there is some platform specific stuff +# especially in the stdlib module replacement +ci-platforms = ["linux", "darwin", "win32"] +# for testing the ffi loop implementations on all platforms +stubtest-dependencies = ["cffi", "dnspython"] +apt-dependencies = ["libev4", "libev-dev", "libuv1", "libuv1-dev"] +brew-dependencies = ["libev", "libuv"] diff --git a/stubs/gevent/gevent/__init__.pyi b/stubs/gevent/gevent/__init__.pyi new file mode 100644 index 000000000000..0a7c6aff3799 --- /dev/null +++ b/stubs/gevent/gevent/__init__.pyi @@ -0,0 +1,76 @@ +import sys + +from gevent._config import config as config +from gevent._hub_local import get_hub as get_hub +from gevent._hub_primitives import iwait_on_objects as iwait, wait_on_objects as wait +from gevent.greenlet import Greenlet as Greenlet, joinall as joinall, killall as killall +from gevent.hub import ( + GreenletExit as GreenletExit, + getcurrent as getcurrent, + idle as idle, + kill as kill, + reinit as reinit, + signal as signal_handler, + sleep as sleep, + spawn_raw as spawn_raw, +) +from gevent.timeout import Timeout as Timeout, with_timeout as with_timeout + +if sys.platform != "win32": + from gevent.os import fork + + __all__ = [ + "Greenlet", + "GreenletExit", + "Timeout", + "config", + "fork", + "get_hub", + "getcurrent", + "getswitchinterval", + "idle", + "iwait", + "joinall", + "kill", + "killall", + "reinit", + "setswitchinterval", + "signal_handler", + "sleep", + "spawn", + "spawn_later", + "spawn_raw", + "wait", + "with_timeout", + ] +else: + __all__ = [ + "Greenlet", + "GreenletExit", + "Timeout", + "config", + "get_hub", + "getcurrent", + "getswitchinterval", + "idle", + "iwait", + "joinall", + "kill", + "killall", + "reinit", + "setswitchinterval", + "signal_handler", + "sleep", + "spawn", + "spawn_later", + "spawn_raw", + "wait", + "with_timeout", + ] + +__version__: str + +getswitchinterval = sys.getswitchinterval +setswitchinterval = sys.setswitchinterval +spawn = Greenlet.spawn +spawn_later = Greenlet.spawn_later diff --git a/stubs/gevent/gevent/_abstract_linkable.pyi b/stubs/gevent/gevent/_abstract_linkable.pyi new file mode 100644 index 000000000000..5c312a96c763 --- /dev/null +++ b/stubs/gevent/gevent/_abstract_linkable.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable +from typing_extensions import Self + +from gevent.hub import Hub + +class AbstractLinkable: + __slots__ = ("hub", "_links", "_notifier", "_notify_all", "__weakref__") + @property + def hub(self) -> Hub | None: ... + def __init__(self, hub: Hub | None = None) -> None: ... + def linkcount(self) -> int: ... + def rawlink(self, callback: Callable[[Self], object], /) -> None: ... + def ready(self) -> bool: ... + def unlink(self, callback: Callable[[Self], object], /) -> None: ... + +__all__ = ["AbstractLinkable"] diff --git a/stubs/gevent/gevent/_config.pyi b/stubs/gevent/gevent/_config.pyi new file mode 100644 index 000000000000..7015d9f4252f --- /dev/null +++ b/stubs/gevent/gevent/_config.pyi @@ -0,0 +1,204 @@ +from collections.abc import Callable, Sequence +from typing import Any, Generic, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Never + +from gevent._types import _Loop, _Resolver +from gevent.fileobject import _FileObjectType +from gevent.threadpool import ThreadPool + +__all__ = ["config"] + +_T = TypeVar("_T") + +@type_check_only +class _SettingDescriptor(Protocol[_T]): + @overload + def __get__(self, obj: None, owner: type[Config]) -> property: ... + @overload + def __get__(self, obj: Config, owner: type[Config]) -> _T: ... + + def __set__(self, obj: Config, value: str | _T) -> None: ... + +class SettingType(type): + def fmt_desc(cls, desc: str) -> str: ... + +def validate_invalid(value: object) -> Never: ... +def validate_bool(value: str | bool) -> bool: ... +def validate_anything(value: _T) -> _T: ... + +convert_str_value_as_is = validate_anything + +class Setting(Generic[_T], metaclass=SettingType): + order: int # all subclasses have this + name: str + environment_key: str + value: _T + default: _T + document: bool + desc: str + validate: Callable[[Any], _T] + def get(self) -> _T: ... + def set(self, val: str | _T) -> None: ... + +class Config: + settings: dict[str, Setting[Any]] + def __init__(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: object) -> None: ... + def set(self, name: str, value: object) -> None: ... + def __dir__(self) -> list[str]: ... + def print_help(self) -> None: ... + + # we manually add properties for all the settings in this module + # SettingType inserts a property into Config for every subclass of Setting + resolver: _SettingDescriptor[type[_Resolver]] + threadpool: _SettingDescriptor[type[Threadpool]] + threadpool_idle_task_timeout: _SettingDescriptor[float] + loop: _SettingDescriptor[type[_Loop]] + format_context: _SettingDescriptor[Callable[[Any], str]] + libev_backend: _SettingDescriptor[str | None] + fileobject: _SettingDescriptor[_FileObjectType] + disable_watch_children: _SettingDescriptor[bool] + track_greenlet_tree: _SettingDescriptor[bool] + monitor_thread: _SettingDescriptor[bool] + max_blocking_time: _SettingDescriptor[float] + memory_monitor_period: _SettingDescriptor[float] + max_memory_usage: _SettingDescriptor[int | None] + resolver_nameservers: _SettingDescriptor[Sequence[str] | str | None] + resolver_timeout: _SettingDescriptor[float | None] + # these get parsed by gevent.resolver.cares.channel so the Setting does not + # perform any conversion, but we know at least what types can be valid + ares_flags: _SettingDescriptor[str | int | None] + ares_timeout: _SettingDescriptor[str | float | None] + ares_tries: _SettingDescriptor[str | int | None] + ares_ndots: _SettingDescriptor[str | int | None] + ares_udp_port: _SettingDescriptor[str | int | None] + ares_tcp_port: _SettingDescriptor[str | int | None] + ares_servers: _SettingDescriptor[Sequence[str] | str | None] + print_blocking_reports: _SettingDescriptor[bool] + +class ImportableSetting(Generic[_T]): + default: str | Sequence[str] + shortname_map: dict[str, str] + def validate(self, value: str | _T) -> _T: ... + def get_options(self) -> dict[str, _T]: ... + +class BoolSettingMixin: + @staticmethod + def validate(value: str | bool) -> bool: ... + +class IntSettingMixin: + @staticmethod + def validate(value: int) -> int: ... + +class _PositiveValueMixin(Generic[_T]): + @staticmethod + def validate(value: _T) -> _T: ... + +class FloatSettingMixin(_PositiveValueMixin[float]): ... +class ByteCountSettingMixin(_PositiveValueMixin[int]): ... + +class Resolver(ImportableSetting[type[_Resolver]], Setting[type[_Resolver]]): + desc: str + default: list[str] # type: ignore[assignment] + shortname_map: dict[str, str] + +class Threadpool(ImportableSetting[type[ThreadPool]], Setting[type[ThreadPool]]): + desc: str + default: str # type: ignore[assignment] + +class ThreadpoolIdleTaskTimeout(FloatSettingMixin, Setting[float]): + document: bool + desc: str + default: float + +class Loop(ImportableSetting[type[_Loop]], Setting[type[_Loop]]): + desc: str + default: list[str] # type: ignore[assignment] + shortname_map: dict[str, str] + +class FormatContext(ImportableSetting[Callable[[Any], str]], Setting[Callable[[Any], str]]): + default: str # type: ignore[assignment] + +class LibevBackend(Setting[str | None]): + desc: str + default: None + +class FileObject(ImportableSetting[_FileObjectType], Setting[_FileObjectType]): + desc: str + default: list[str] # type: ignore[assignment] + shortname_map: dict[str, str] + +class WatchChildren(BoolSettingMixin, Setting[bool]): + desc: str + default: bool + +class TrackGreenletTree(BoolSettingMixin, Setting[bool]): + default: bool + desc: str + +class MonitorThread(BoolSettingMixin, Setting[bool]): + default: bool + desc: str + +class MaxBlockingTime(FloatSettingMixin, Setting[float]): + default: float + desc: str + +class PrintBlockingReports(BoolSettingMixin, Setting[bool]): + default: bool + desc: str + +class MonitorMemoryPeriod(FloatSettingMixin, Setting[float]): + default: int + desc: str + +class MonitorMemoryMaxUsage(ByteCountSettingMixin, Setting[int | None]): + default: None + desc: str + +class AresSettingMixin: + document: bool + @property + def kwarg_name(self) -> str: ... + validate: Any # we just want this to mixin without errors + +class AresFlags(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresTimeout(AresSettingMixin, Setting[str | float | None]): + document: bool + default: None + desc: str + +class AresTries(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresNdots(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresUDPPort(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresTCPPort(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresServers(AresSettingMixin, Setting[Sequence[str] | str | None]): + document: bool + default: None + desc: str + +class ResolverNameservers(AresSettingMixin, Setting[Sequence[str] | str | None]): + document: bool + default: None + desc: str + @property + def kwarg_name(self) -> str: ... + +class ResolverTimeout(FloatSettingMixin, AresSettingMixin, Setting[float | None]): + document: bool + desc: str + @property + def kwarg_name(self) -> str: ... + +config: Config = ... diff --git a/stdlib/@python2/distutils/command/bdist_packager.pyi b/stubs/gevent/gevent/_ffi/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/bdist_packager.pyi rename to stubs/gevent/gevent/_ffi/__init__.pyi diff --git a/stubs/gevent/gevent/_ffi/loop.pyi b/stubs/gevent/gevent/_ffi/loop.pyi new file mode 100644 index 000000000000..38222a945d36 --- /dev/null +++ b/stubs/gevent/gevent/_ffi/loop.pyi @@ -0,0 +1,87 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Callable, Sequence +from types import TracebackType +from typing import Protocol, TypeAlias, type_check_only +from typing_extensions import TypeVarTuple, Unpack + +from gevent._types import _AsyncWatcher, _Callback, _ChildWatcher, _IoWatcher, _StatWatcher, _TimerWatcher, _Watcher + +_Ts = TypeVarTuple("_Ts") +_ErrorHandlerFunc: TypeAlias = Callable[ + [object | None, type[BaseException] | None, BaseException | None, TracebackType | None], object +] + +@type_check_only +class _SupportsHandleError(Protocol): + handle_error: _ErrorHandlerFunc + +_ErrorHandler: TypeAlias = _ErrorHandlerFunc | _SupportsHandleError + +def assign_standard_callbacks( + ffi: object, lib: object, callbacks_class: Callable[[object], object], extras: Sequence[tuple[object, object]] = () +) -> object: ... + +class AbstractLoop: + CALLBACK_CHECK_COUNT: int + error_handler: _ErrorHandler | None + starting_timer_may_update_loop_time: bool + # internal API, this __init__ will only be called from subclasses + def __init__( + self, ffi: object, lib: object, watchers: object, flags: int | None = None, default: bool | None = None + ) -> None: ... + def destroy(self) -> bool | None: ... + @property + def ptr(self) -> int: ... + @property + def WatcherType(self) -> type[_Watcher]: ... + @property + def MAXPRI(self) -> int: ... + @property + def MINPRI(self) -> int: ... + def handle_error( + self, context: object | None, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def run(self, nowait: bool = False, once: bool = False) -> None: ... + def reinit(self) -> None: ... + def ref(self) -> None: ... + def unref(self) -> None: ... + def break_(self, how: int | None = ...) -> None: ... + def verify(self) -> None: ... + def now(self) -> float: ... + def update_now(self) -> None: ... + update = update_now # deprecated + @property + def default(self) -> bool: ... + @property + def iteration(self) -> int: ... + @property + def depth(self) -> int: ... + @property + def backend_int(self) -> int: ... + @property + def backend(self) -> str | int: ... + @property + def pendingcnt(self) -> int: ... + @property + def activecnt(self) -> int: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> _IoWatcher: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> _TimerWatcher: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def idle(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def check(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> _ChildWatcher: ... + def install_sigchld(self) -> None: ... + + def async_(self, ref: bool = True, priority: int | None = None) -> _AsyncWatcher: ... + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = None) -> _StatWatcher: ... + def run_callback(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> _Callback: ... + def run_callback_threadsafe(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> _Callback: ... + def callback(self, priority: float | None = None) -> _Callback: ... + def fileno(self) -> FileDescriptor | None: ... + +__all__ = ["AbstractLoop", "assign_standard_callbacks"] diff --git a/stubs/gevent/gevent/_ffi/watcher.pyi b/stubs/gevent/gevent/_ffi/watcher.pyi new file mode 100644 index 000000000000..9c5c3b181cf9 --- /dev/null +++ b/stubs/gevent/gevent/_ffi/watcher.pyi @@ -0,0 +1,98 @@ +from _typeshed import FileDescriptor, StrOrBytesPath +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, overload +from typing_extensions import Self, TypeVarTuple, Unpack + +from gevent._types import _Loop, _StatResult + +_Ts = TypeVarTuple("_Ts") + +class AbstractWatcherType(type): + def new_handle(cls, obj: object) -> int: ... + def new(cls, kind: object) -> Any: ... + +class watcher(metaclass=AbstractWatcherType): + loop: _Loop + def __init__(self, _loop: _Loop, ref: bool = True, priority: int | None = None, args: tuple[object, ...] = ()) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + @property + def ref(self) -> bool: ... + callback: Callable[..., Any] + args: tuple[Any, ...] + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def stop(self) -> None: ... + + @property + def priority(self) -> int | None: ... + @priority.setter + def priority(self, value: int | None) -> None: ... + + @property + def active(self) -> bool: ... + @property + def pending(self) -> bool: ... + +class IoMixin: + EVENT_MASK: int + def __init__(self, loop: _Loop, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> None: ... + + @overload + def start(self, callback: Callable[[int, Unpack[_Ts]], Any], *args: Unpack[_Ts], pass_events: Literal[True]) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + +class TimerMixin: + def __init__( + self, loop: _Loop, after: float = 0.0, repeat: float = 0.0, ref: bool = True, priority: int | None = None + ) -> None: ... + + @overload + def start(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + + @overload + def again(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def again(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + +class SignalMixin: + def __init__(self, loop: _Loop, signalnum: int, ref: bool = True, priority: int | None = None) -> None: ... + +class IdleMixin: ... +class PrepareMixin: ... +class CheckMixin: ... +class ForkMixin: ... + +class AsyncMixin: + def send(self) -> None: ... + def send_ignoring_arg(self, _ignored: object) -> None: ... + @property + def pending(self) -> bool: ... + +class ChildMixin: + def __init__(self, loop: _Loop, pid: int, trace: int = 0, ref: bool = True) -> None: ... + @property + def pid(self) -> int: ... + @property + def rpid(self) -> int | None: ... + @property + def rstatus(self) -> int: ... + +class StatMixin: + def __init__( + self, _loop: _Loop, path: StrOrBytesPath, interval: float = 0.0, ref: bool = True, priority: float | None = None + ) -> None: ... + @property + def path(self) -> StrOrBytesPath: ... + @property + def attr(self) -> _StatResult | None: ... + @property + def prev(self) -> _StatResult | None: ... + @property + def interval(self) -> float: ... + +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/_fileobjectcommon.pyi b/stubs/gevent/gevent/_fileobjectcommon.pyi new file mode 100644 index 000000000000..3aba7454d1ca --- /dev/null +++ b/stubs/gevent/gevent/_fileobjectcommon.pyi @@ -0,0 +1,371 @@ +import io +from _typeshed import ( + FileDescriptorOrPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, +) +from types import TracebackType +from typing import IO, Any, AnyStr, ClassVar, Generic, Literal, TypeVar, overload +from typing_extensions import Self + +from gevent.lock import DummySemaphore, Semaphore +from gevent.threadpool import ThreadPool + +_IOT = TypeVar("_IOT", bound=IO[Any]) + +class cancel_wait_ex(IOError): + def __init__(self) -> None: ... + +class FileObjectClosed(IOError): + def __init__(self) -> None: ... + +class FlushingBufferedWriter(io.BufferedWriter): ... + +class WriteallMixin: + def writeall(self, b: ReadableBuffer, /) -> int: ... + +class FileIO(io.FileIO): + __slots__ = () + +class WriteIsWriteallMixin(WriteallMixin): + def write(self, b: ReadableBuffer, /) -> int: ... + +class WriteallFileIO(WriteIsWriteallMixin, io.FileIO): ... # type: ignore[misc] + +class OpenDescriptor(Generic[_IOT]): + default_buffer_size: ClassVar[int] + fileio_mode: str + mode: str + creating: bool + reading: bool + writing: bool + appending: bool + updating: bool + text: bool + binary: bool + can_write: bool + can_read: bool + native: bool + universal: bool + buffering: int + encoding: str | None + errors: str | None + newline: bool + closefd: bool + atomic_write: bool + # we could add all the necessary overloads here too, but since this is internal API + # I don't think it makes sense to do that + def __init__( + self, + fobj: FileDescriptorOrPath, + mode: str = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + def is_fd(self) -> bool: ... + def opened(self) -> _IOT: ... + def opened_raw(self) -> FileIO: ... + @staticmethod + def is_buffered(stream: object) -> bool: ... + @classmethod + def buffer_size_for_stream(cls, stream: object) -> int: ... + +class FileObjectBase(Generic[_IOT, AnyStr]): + def __init__( + self: FileObjectBase[_IOT, AnyStr], descriptor: OpenDescriptor[_IOT] # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... + io: _IOT + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, /) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> AnyStr: ... + def __bool__(self) -> bool: ... + next = __next__ + +class FileObjectBlock(FileObjectBase[_IOT, AnyStr]): + # Text mode: always binds a TextIOWrapper + @overload + def __init__( + self: FileObjectBlock[io.TextIOWrapper, str], + fobj: FileDescriptorOrPath, + mode: OpenTextMode = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Unbuffered binary mode: binds a FileIO + @overload + def __init__( + self: FileObjectBlock[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0], + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[0] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectBlock[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + *, + buffering: Literal[0], + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def __init__( + self: FileObjectBlock[io.BufferedRandom, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectBlock[io.BufferedWriter, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectBlock[io.BufferedReader, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def __init__( + self: FileObjectBlock[IO[bytes], bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Fallback if mode is not specified + @overload + def __init__( + self: FileObjectBlock[IO[Any], Any], + fobj: FileDescriptorOrPath, + mode: str, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + +class FileObjectThread(FileObjectBase[_IOT, AnyStr]): + threadpool: ThreadPool + lock: Semaphore | DummySemaphore + + # Text mode: always binds a TextIOWrapper + @overload + def __init__( + self: FileObjectThread[io.TextIOWrapper, str], + fobj: FileDescriptorOrPath, + mode: OpenTextMode = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Unbuffered binary mode: binds a FileIO + @overload + def __init__( + self: FileObjectThread[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0], + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[0] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + @overload + def __init__( + self: FileObjectThread[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + *, + buffering: Literal[0], + closefd: bool | None = None, + atomic_write: bool = False, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def __init__( + self: FileObjectThread[io.BufferedRandom, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + @overload + def __init__( + self: FileObjectThread[io.BufferedWriter, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + @overload + def __init__( + self: FileObjectThread[io.BufferedReader, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def __init__( + self: FileObjectThread[IO[bytes], bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Fallback if mode is not specified + @overload + def __init__( + self: FileObjectThread[IO[Any], Any], + fobj: FileDescriptorOrPath, + mode: str, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... diff --git a/stubs/gevent/gevent/_greenlet_primitives.pyi b/stubs/gevent/gevent/_greenlet_primitives.pyi new file mode 100644 index 000000000000..60356ed148d6 --- /dev/null +++ b/stubs/gevent/gevent/_greenlet_primitives.pyi @@ -0,0 +1,21 @@ +from abc import abstractmethod +from typing import Any +from typing_extensions import Never, disjoint_base + +from gevent._types import _Loop +from greenlet import greenlet + +class TrackedRawGreenlet(greenlet): ... + +@disjoint_base +class SwitchOutGreenletWithLoop(TrackedRawGreenlet): + @property + @abstractmethod + def loop(self) -> _Loop: ... + @loop.setter + def loop(self, value: _Loop) -> None: ... + + def switch(self) -> Any: ... + def switch_out(self) -> Never: ... + +__all__ = ["TrackedRawGreenlet", "SwitchOutGreenletWithLoop"] diff --git a/stubs/gevent/gevent/_hub_local.pyi b/stubs/gevent/gevent/_hub_local.pyi new file mode 100644 index 000000000000..783ef5bc7b0d --- /dev/null +++ b/stubs/gevent/gevent/_hub_local.pyi @@ -0,0 +1,15 @@ +from gevent._types import _Loop +from gevent.hub import Hub as _Hub + +__all__ = ["get_hub", "get_hub_noargs", "get_hub_if_exists"] + +Hub: type[_Hub] | None + +def get_hub_class() -> type[_Hub] | None: ... +def set_default_hub_class(hubtype: type[_Hub]) -> None: ... +def get_hub() -> _Hub: ... +def get_hub_noargs() -> _Hub: ... +def get_hub_if_exists() -> _Hub | None: ... +def set_hub(hub: _Hub) -> None: ... +def get_loop() -> _Loop: ... +def set_loop(loop: _Loop) -> None: ... diff --git a/stubs/gevent/gevent/_hub_primitives.pyi b/stubs/gevent/gevent/_hub_primitives.pyi new file mode 100644 index 000000000000..8be21a4d546b --- /dev/null +++ b/stubs/gevent/gevent/_hub_primitives.pyi @@ -0,0 +1,74 @@ +from _typeshed import FileDescriptor +from collections.abc import Callable, Collection, Iterable +from types import TracebackType +from typing import Any, Generic, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack, disjoint_base + +from gevent._greenlet_primitives import SwitchOutGreenletWithLoop +from gevent._types import _Loop, _Watcher +from gevent.hub import Hub +from gevent.socket import socket + +__all__ = ["WaitOperationsGreenlet", "iwait_on_objects", "wait_on_objects", "wait_read", "wait_write", "wait_readwrite"] + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts") +_WaitableT = TypeVar("_WaitableT", bound=_Waitable) + +@type_check_only +class _Waitable(Protocol): + def rawlink(self, callback: Callable[[Any], object], /) -> object: ... + def unlink(self, callback: Callable[[Any], object], /) -> object: ... + +class WaitOperationsGreenlet(SwitchOutGreenletWithLoop): + loop: _Loop + def wait(self, watcher: _Watcher) -> None: ... + def cancel_waits_close_and_then( + self, + watchers: Iterable[_Watcher], + exc_kind: type[BaseException] | BaseException, + then: Callable[[Unpack[_Ts]], object], + *then_args: Unpack[_Ts], + ) -> None: ... + def cancel_wait(self, watcher: _Watcher, error: type[BaseException] | BaseException, close_watcher: bool = False) -> None: ... + +@disjoint_base +class _WaitIterator(Generic[_T]): + def __init__(self, objects: Collection[_T], hub: Hub, timeout: float, count: int | None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + next = __next__ + +@overload +def iwait_on_objects(objects: None, timeout: float | None = None, count: int | None = None) -> list[bool]: ... +@overload +def iwait_on_objects( + objects: Collection[_WaitableT], timeout: float | None = None, count: int | None = None +) -> _WaitIterator[_WaitableT]: ... + +@overload +def wait_on_objects(objects: None = None, timeout: float | None = None, count: int | None = None) -> bool: ... +@overload +def wait_on_objects( + objects: Collection[_WaitableT], timeout: float | None = None, count: int | None = None +) -> list[_WaitableT]: ... + +def set_default_timeout_error(e: type[BaseException]) -> None: ... +def wait_on_socket(socket: socket, watcher: _Watcher, timeout_exc: type[BaseException] | BaseException | None = None) -> None: ... +def wait_on_watcher( + watcher: _Watcher, + timeout: float | None = None, + timeout_exc: type[BaseException] | BaseException = ..., + hub: Hub | None = None, +) -> None: ... +def wait_read( + fileno: FileDescriptor, timeout: float | None = None, timeout_exc: type[BaseException] | BaseException = ... +) -> None: ... +def wait_write( + fileno: FileDescriptor, timeout: float | None = None, timeout_exc: type[BaseException] | BaseException = ... +) -> None: ... +def wait_readwrite( + fileno: FileDescriptor, timeout: float | None = None, timeout_exc: type[BaseException] | BaseException = ... +) -> None: ... diff --git a/stubs/gevent/gevent/_ident.pyi b/stubs/gevent/gevent/_ident.pyi new file mode 100644 index 000000000000..e59d21de18cf --- /dev/null +++ b/stubs/gevent/gevent/_ident.pyi @@ -0,0 +1,15 @@ +from typing import Any, final +from weakref import ref + +@final +class ValuedWeakRef(ref): + __slots__ = ("value",) + value: Any + +@final +class IdentRegistry: + def __init__(self) -> None: ... + def get_ident(self, obj: object) -> int: ... + def __len__(self) -> int: ... + +__all__ = ["IdentRegistry"] diff --git a/stubs/gevent/gevent/_imap.pyi b/stubs/gevent/gevent/_imap.pyi new file mode 100644 index 000000000000..2a515665cf6b --- /dev/null +++ b/stubs/gevent/gevent/_imap.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable, Iterable +from typing import Any, ParamSpec, TypeVar +from typing_extensions import Self, disjoint_base + +from gevent.greenlet import Greenlet +from gevent.queue import UnboundQueue + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# this matches builtins.map to some degree, but since it is an non-public API type that just gets +# returned by some public API functions, we don't bother adding a whole bunch of overloads to handle +# the case of 1-n Iterables being passed in and just go for the fully unsafe signature +# we do the crazy overloads instead in the functions that create these objects +@disjoint_base +class IMapUnordered(Greenlet[_P, _T]): + finished: bool + # it may contain an undocumented Failure object + queue: UnboundQueue[_T | object] + def __init__(self, func: Callable[_P, _T], iterable: Iterable[Any], spawn: Callable[_P, Greenlet[_P, _T]]) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class IMap(IMapUnordered[_P, _T]): + index: int + +__all__ = ["IMapUnordered", "IMap"] diff --git a/stubs/gevent/gevent/_monitor.pyi b/stubs/gevent/gevent/_monitor.pyi new file mode 100644 index 000000000000..3647e0f33f0d --- /dev/null +++ b/stubs/gevent/gevent/_monitor.pyi @@ -0,0 +1,51 @@ +from collections.abc import Callable, Sequence +from typing import Any, TypeVar + +from gevent.events import IPeriodicMonitorThread, MemoryUsageThresholdExceeded, MemoryUsageUnderThreshold +from gevent.hub import Hub +from greenlet import greenlet + +__all__ = ["PeriodicMonitoringThread"] + +_T = TypeVar("_T") + +# FIXME: While it would be nice to import Interface from zope.interface here so the +# mypy plugin will work correctly for the people that use it, it causes all +# sorts of issues to reference a module that is not stubbed in typeshed, so +# for now we punt and just define an alias for Interface and implementer we +# can get rid of later +def implementer(interface: Any, /) -> Callable[[_T], _T]: ... + +class MonitorWarning(RuntimeWarning): ... + +class _MonitorEntry: + __slots__ = ("function", "period", "last_run_time") + function: Callable[[Hub], object] + period: float + last_run_time: float + def __init__(self, function: Callable[[Hub], object], period: float) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +@implementer(IPeriodicMonitorThread) +class PeriodicMonitoringThread: + inactive_sleep_time: float + min_sleep_time: float + min_memory_monitor_period: float + should_run: bool + monitor_thread_ident: int + pid: int + def __init__(self, hub: Hub) -> None: ... + @property + def hub(self) -> Hub | None: ... + def monitoring_functions(self) -> list[_MonitorEntry]: ... + def add_monitoring_function(self, function: Callable[[Hub], object], period: float) -> None: ... + def calculate_sleep_time(self) -> float: ... + def kill(self) -> None: ... + def __call__(self) -> None: ... + def monitor_blocking(self, hub: Hub) -> tuple[greenlet, Sequence[str]]: ... + def ignore_current_greenlet_blocking(self) -> None: ... + def monitor_current_greenlet_blocking(self) -> None: ... + def can_monitor_memory_usage(self) -> bool: ... + def install_monitor_memory_usage(self) -> None: ... + def monitor_memory_usage(self, _hub: Hub) -> MemoryUsageThresholdExceeded | MemoryUsageUnderThreshold | None: ... diff --git a/stubs/gevent/gevent/_threading.pyi b/stubs/gevent/gevent/_threading.pyi new file mode 100644 index 000000000000..1c671bdec7f9 --- /dev/null +++ b/stubs/gevent/gevent/_threading.pyi @@ -0,0 +1,22 @@ +from _thread import LockType, allocate_lock as Lock +from typing import Generic, NewType, TypeVar + +__all__ = ["Lock", "Queue", "EmptyTimeout"] + +_T = TypeVar("_T") +_Cookie = NewType("_Cookie", LockType) + +class EmptyTimeout(Exception): ... + +class Queue(Generic[_T]): + __slots__ = ("_queue", "_mutex", "_not_empty", "unfinished_tasks") + unfinished_tasks: int + def __init__(self) -> None: ... + def task_done(self) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put(self, item: _T) -> None: ... + def get(self, cookie: _Cookie, timeout: int = -1) -> _T: ... + def allocate_cookie(self) -> _Cookie: ... + def kill(self) -> None: ... diff --git a/stubs/gevent/gevent/_types.pyi b/stubs/gevent/gevent/_types.pyi new file mode 100644 index 000000000000..a5718fb32d7e --- /dev/null +++ b/stubs/gevent/gevent/_types.pyi @@ -0,0 +1,160 @@ +import sys +from _typeshed import FileDescriptor, StrOrBytesPath +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import TypeVarTuple, Unpack + +_Ts = TypeVarTuple("_Ts") + +# gevent uses zope.interface interanlly which does not work well with type checkers +# partially due to the odd call signatures without self and partially due to them +# behaving essentially like a Protocol, so a mypy plugin is necessary to type check +# them correctly, and then you still have to give up on some valuable features due +# to the missing self/cls argument. +# To ensure maximum compatibility with other type checkers and so we don't depend +# on mypy-zope we define an equivalent Protocol for each interface, which we will +# use on arguments in place of the interface +# it also looks like ILoop is possibly too strict, since there are additional +# properties and methods that are available on all event loops, so these have +# been added as well, instead of completely mirroring the internal interface + +@type_check_only +class _Loop(Protocol): # noqa: Y046 + @property + def approx_timer_resolution(self) -> float: ... + @property + def default(self) -> bool: ... + @property + def iteration(self) -> int: ... + @property + def depth(self) -> int: ... + @property + def backend_int(self) -> int: ... + @property + def backend(self) -> str | int: ... + @property + def pendingcnt(self) -> int: ... + @property + def activecnt(self) -> int: ... + def handle_error( + self, context: object | None, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def run(self, nowait: bool = False, once: bool = False) -> None: ... + def reinit(self) -> None: ... + def ref(self) -> None: ... + def unref(self) -> None: ... + def break_(self, how: int | None = ...) -> None: ... + def verify(self) -> None: ... + def now(self) -> float: ... + def update_now(self) -> None: ... + def destroy(self) -> None: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> _IoWatcher: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> _TimerWatcher: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def idle(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def check(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> _ChildWatcher: ... + def install_sigchld(self) -> None: ... + + def async_(self, ref: bool = True, priority: int | None = None) -> _AsyncWatcher: ... + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = ...) -> _StatWatcher: ... + def run_callback(self, func: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> _Callback: ... + def run_callback_threadsafe(self, func: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> _Callback: ... + def fileno(self) -> FileDescriptor | None: ... + +@type_check_only +class _Watcher(Protocol): + # while IWatcher allows for kwargs the actual implementation does not... + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def stop(self) -> None: ... + def close(self) -> None: ... + +# this matches Intersection[_Watcher, TimerMixin] +@type_check_only +class _TimerWatcher(_Watcher, Protocol): + # this has one specific allowed keyword argument, if it is given we don't try to check + # the passed in arguments, but if it isn't passed in, then we do. + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + + @overload + def again(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def again(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + +# this matches Intersection[_Watcher, IoMixin] +@type_check_only +class _IoWatcher(_Watcher, Protocol): + EVENT_MASK: int + + # pass_events means the first argument of the callback needs to be an integer, but we can't + # type check the other passed in args in this case + @overload + def start(self, callback: Callable[[int, Unpack[_Ts]], Any], *args: Unpack[_Ts], pass_events: Literal[True]) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + +# this matches Intersection[_Watcher, ChildMixin] +@type_check_only +class _ChildWatcher(_Watcher, Protocol): + @property + def pid(self) -> int: ... + @property + def rpid(self) -> int | None: ... + @property + def rstatus(self) -> int: ... + +# this matches Intersection[_Watcher, AsyncMixin] +@type_check_only +class _AsyncWatcher(_Watcher, Protocol): + def send(self) -> None: ... + def send_ignoring_arg(self, ignored: object, /) -> None: ... + @property + def pending(self) -> bool: ... + +# all implementations return something of this shape +@type_check_only +class _StatResult(Protocol): + @property + def st_nlink(self) -> int: ... + +# this matches Intersection[_Watcher, StatMixin] +@type_check_only +class _StatWatcher(_Watcher, Protocol): + @property + def path(self) -> StrOrBytesPath: ... + @property + def attr(self) -> _StatResult | None: ... + @property + def prev(self) -> _StatResult | None: ... + @property + def interval(self) -> float: ... + +@type_check_only +class _Callback(Protocol): + pending: bool + def stop(self) -> None: ... + def close(self) -> None: ... + +_FullSockAddr: TypeAlias = tuple[str, int, int, int] # host, port, flowinfo, scopeid +_SockAddr: TypeAlias = _FullSockAddr | tuple[str, int] +_AddrinfoResult: TypeAlias = list[tuple[int, int, int, str, _SockAddr]] # family, type, protocol, cname, sockaddr +_NameinfoResult: TypeAlias = tuple[str, str] + +@type_check_only +class _Resolver(Protocol): # noqa: Y046 + def close(self) -> None: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... diff --git a/stubs/gevent/gevent/_util.pyi b/stubs/gevent/gevent/_util.pyi new file mode 100644 index 000000000000..d0f6df62d749 --- /dev/null +++ b/stubs/gevent/gevent/_util.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable, Iterable, MutableMapping, Sequence +from types import ModuleType +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +_T = TypeVar("_T") + +WRAPPER_ASSIGNMENTS: tuple[str, ...] +WRAPPER_UPDATES: tuple[str, ...] + +def update_wrapper( + wrapper: _T, + wrapped: object, + assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), + updated: Sequence[str] = ("__dict__",), +) -> _T: ... +def copy_globals( + source: ModuleType, + globs: MutableMapping[str, Any], + only_names: Iterable[str] | None = None, + ignore_missing_names: bool = False, + names_to_ignore: Sequence[str] = (), + dunder_names_to_keep: Sequence[str] = ("__implements__", "__all__", "__imports__"), + cleanup_globs: bool = True, +) -> list[str]: ... +def import_c_accel(globs: MutableMapping[str, Any], cname: str) -> None: ... + +class Lazy(Generic[_T]): + data: _T + def __init__(self, func: Callable[[Any], _T]) -> None: ... + + @overload + def __get__(self, inst: None, class_: type[object]) -> Self: ... + @overload + def __get__(self, inst: object, class_: type[object]) -> _T: ... + +class readproperty(Generic[_T]): + func: Callable[[Any], _T] + def __init__( + self: readproperty[_T], func: Callable[[Any], _T] # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... + + @overload + def __get__(self, inst: None, class_: type[object]) -> Self: ... + @overload + def __get__(self, inst: object, class_: type[object]) -> _T: ... + +class LazyOnClass(Generic[_T]): + @classmethod + def lazy(cls, cls_dict: MutableMapping[str, Any], func: Callable[[Any], _T]) -> None: ... + name: str + func: Callable[[Any], _T] + def __init__(self, func: Callable[[Any], _T], name: str | None = None) -> None: ... + + @overload + def __get__(self, inst: None, class_: type[object]) -> Self: ... + @overload + def __get__(self, inst: object, class_: type[object]) -> _T: ... + +def gmctime() -> str: ... +def prereleaser_middle(data: MutableMapping[str, Any]) -> None: ... +def postreleaser_before(data: MutableMapping[str, Any]) -> None: ... diff --git a/stubs/gevent/gevent/_waiter.pyi b/stubs/gevent/gevent/_waiter.pyi new file mode 100644 index 000000000000..bd1125d84f1e --- /dev/null +++ b/stubs/gevent/gevent/_waiter.pyi @@ -0,0 +1,48 @@ +from types import TracebackType +from typing import Generic, TypeAlias, TypeVar, final, overload + +from gevent.event import _ValueSource +from gevent.hub import Hub +from greenlet import greenlet as greenlet_t + +__all__ = ["Waiter"] + +_T = TypeVar("_T") +# this is annoying, it's due to them using *throw args, rather than just storing them in standardized form +_ThrowArgs: TypeAlias = ( + tuple[()] + | tuple[BaseException] + | tuple[BaseException, None] + | tuple[BaseException, None, TracebackType | None] + | tuple[type[BaseException]] + | tuple[type[BaseException], BaseException | object] + | tuple[type[BaseException], BaseException | object, TracebackType | None] +) + +class Waiter(Generic[_T]): + __slots__ = ["hub", "greenlet", "value", "_exception"] + @property + def hub(self) -> Hub: ... # readonly in Cython + @property + def greenlet(self) -> greenlet_t | None: ... # readonly in Cython + @property + def value(self) -> _T | None: ... # readonly in Cython + def __init__(self, hub: Hub | None = None) -> None: ... + def clear(self) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + @property + def exc_info(self) -> _ThrowArgs | None: ... + def switch(self, value: _T) -> None: ... + + @overload + def throw(self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /) -> None: ... + @overload + def throw(self, typ: BaseException = ..., val: None = None, tb: TracebackType | None = None, /) -> None: ... + + def get(self) -> _T: ... + def __call__(self, source: _ValueSource[_T]) -> None: ... + +@final +class MultipleWaiter(Waiter[_T]): + __slots__ = ["_values"] diff --git a/stubs/gevent/gevent/ares.pyi b/stubs/gevent/gevent/ares.pyi new file mode 100644 index 000000000000..6104efb65acc --- /dev/null +++ b/stubs/gevent/gevent/ares.pyi @@ -0,0 +1,3 @@ +from gevent.resolver.cares import * + +__all__ = ["channel"] diff --git a/stubs/gevent/gevent/backdoor.pyi b/stubs/gevent/gevent/backdoor.pyi new file mode 100644 index 000000000000..d88cd66710f9 --- /dev/null +++ b/stubs/gevent/gevent/backdoor.pyi @@ -0,0 +1,49 @@ +from _typeshed import StrOrBytesPath +from typing import Any, overload + +from gevent.baseserver import _Spawner +from gevent.server import StreamServer, _Address +from gevent.socket import socket as _GeventSocket +from gevent.ssl import SSLContext + +class BackdoorServer(StreamServer): + locals: dict[str, Any] + banner: str | None + + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + locals: dict[str, Any] | None = None, + banner: str | None = None, + *, + backlog: int | None = None, + spawn: _Spawner = "default", + ssl_context: SSLContext, + server_side: bool = True, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ) -> None: ... + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + locals: dict[str, Any] | None = None, + banner: str | None = None, + *, + backlog: int | None = None, + spawn: _Spawner = "default", + keyfile: StrOrBytesPath = ..., + certfile: StrOrBytesPath = ..., + server_side: bool = True, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str = ..., + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str = ..., + ) -> None: ... + + def handle(self, conn: _GeventSocket, _address: _Address) -> None: ... + +__all__ = ["BackdoorServer"] diff --git a/stubs/gevent/gevent/baseserver.pyi b/stubs/gevent/gevent/baseserver.pyi new file mode 100644 index 000000000000..453f974eefec --- /dev/null +++ b/stubs/gevent/gevent/baseserver.pyi @@ -0,0 +1,65 @@ +from collections.abc import Callable, Container +from types import TracebackType +from typing import Generic, Literal, ParamSpec, Protocol, TypeAlias, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack + +from gevent._types import _Loop +from gevent.pool import Pool +from gevent.socket import socket as _GeventSocket +from greenlet import greenlet + +_Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") + +@type_check_only +class _SpawnFunc(Protocol): + def __call__(self, func: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> greenlet: ... + +_Spawner: TypeAlias = Pool | _SpawnFunc | int | Literal["default"] | None + +class BaseServer(Generic[Unpack[_Ts]]): + min_delay: float + max_delay: float + max_accept: int + stop_timeout: float + fatal_errors: Container[int] + pool: Pool | None + delay: float + loop: _Loop + family: int + address: str | tuple[str, int] + socket: _GeventSocket + handle: Callable[[Unpack[_Ts]], object] + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[Unpack[_Ts]], object] | None = None, + spawn: _Spawner = "default", + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, /) -> None: ... + def set_listener(self, listener: _GeventSocket | tuple[str, int] | str) -> None: ... + def set_spawn(self, spawn: _Spawner) -> None: ... + def set_handle(self, handle: Callable[[Unpack[_Ts]], object]) -> None: ... + def start_accepting(self) -> None: ... + def stop_accepting(self) -> None: ... + def do_handle(self, *args: Unpack[_Ts]) -> None: ... + def do_close(self, *args: Unpack[_Ts]) -> None: ... + def do_read(self) -> tuple[Unpack[_Ts]] | None: ... + def full(self) -> bool: ... + @property + def server_host(self) -> str | None: ... + @property + def server_port(self) -> int | None: ... + def init_socket(self) -> None: ... + @property + def started(self) -> bool: ... + def start(self) -> None: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def stop(self, timeout: float | None = None) -> None: ... + def serve_forever(self, stop_timeout: float | None = None) -> None: ... + def is_fatal_error(self, ex: BaseException) -> bool: ... + +__all__ = ["BaseServer"] diff --git a/stubs/gevent/gevent/event.pyi b/stubs/gevent/gevent/event.pyi new file mode 100644 index 000000000000..4652810532d2 --- /dev/null +++ b/stubs/gevent/gevent/event.pyi @@ -0,0 +1,70 @@ +from types import TracebackType +from typing import Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from gevent._abstract_linkable import AbstractLinkable + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +# gevent generally allows the tracebock to be omitted, it can also fail to serialize +# in which case it will be None as well. +_ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] +_OptExcInfo: TypeAlias = _ExcInfo | tuple[None, None, None] + +@type_check_only +class _ValueSource(Protocol[_T_co]): + def successful(self) -> bool: ... + @property + def value(self) -> _T_co | None: ... + @property + def exception(self) -> BaseException | None: ... + +class Event(AbstractLinkable): + __slots__ = ("_flag",) + def __init__(self) -> None: ... + def is_set(self) -> bool: ... + def isSet(self) -> bool: ... + def ready(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + + @overload + def wait(self, timeout: None = None) -> Literal[True]: ... + @overload + def wait(self, timeout: float) -> bool: ... + +class AsyncResult(AbstractLinkable, Generic[_T]): + __slots__ = ("_value", "_exc_info", "_imap_task_index") + def __init__(self) -> None: ... + @property + def value(self) -> _T | None: ... + @property + def exc_info(self) -> _OptExcInfo | tuple[None, None, None] | tuple[()]: ... + @property + def exception(self) -> BaseException | None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + def set(self, value: _T | None = None) -> None: ... + + @overload + def set_exception(self, exception: BaseException, exc_info: None = None) -> None: ... + @overload + def set_exception(self, exception: BaseException | None, exc_info: _OptExcInfo) -> None: ... + + # technically get/get_nowait/result should just return _T, but the API is designed in + # such a way that it is perfectly legal for a ValueSource to have neither its value nor + # its exception set, while still being marked successful, at which point None would be + # stored into value, it's also legal to call set without arguments, which has the same + # effect, this is a little annoying, since it will introduce some additional None checks + # that may not be necessary, but it's impossible to annotate this situation, so for now + # we just deal with the possibly redundant None checks... + def get(self, block: bool = True, timeout: float | None = None) -> _T | None: ... + def get_nowait(self) -> _T | None: ... + def wait(self, timeout: float | None = None) -> _T | None: ... + def __call__(self, source: _ValueSource[_T]) -> None: ... + def result(self, timeout: float | None = None) -> _T | None: ... + set_result = set + def done(self) -> bool: ... + def cancel(self) -> Literal[False]: ... + def cancelled(self) -> Literal[False]: ... + +__all__ = ["Event", "AsyncResult"] diff --git a/stubs/gevent/gevent/events.pyi b/stubs/gevent/gevent/events.pyi new file mode 100644 index 000000000000..ff6fc39f082a --- /dev/null +++ b/stubs/gevent/gevent/events.pyi @@ -0,0 +1,186 @@ +from collections.abc import Callable, Mapping, Sequence +from types import ModuleType +from typing import Any, Protocol, TypeAlias, TypeVar, type_check_only + +from gevent.hub import Hub +from greenlet import greenlet as greenlet_t +from psutil._ntuples import pmem + +_T = TypeVar("_T") +# FIXME: While it would be nice to import Interface from zope.interface here so the +# mypy plugin will work correctly for the people that use it, it causes all +# sorts of issues to reference a module that is not stubbed in typeshed, so +# for now we punt and just define an alias for Interface and implementer we +# can get rid of later +Interface: TypeAlias = Any + +def implementer(interface: Interface, /) -> Callable[[_T], _T]: ... + +subscribers: list[Callable[[Any], object]] + +@type_check_only +class _PeriodicMonitorThread(Protocol): + def add_monitoring_function(self, function: Callable[[Hub], object], period: float | None) -> object: ... + +class IPeriodicMonitorThread(Interface): + def add_monitoring_function(function: Callable[[Hub], object], period: float | None) -> object: ... + +class IPeriodicMonitorThreadStartedEvent(Interface): + monitor: IPeriodicMonitorThread + +@implementer(IPeriodicMonitorThread) +class PeriodicMonitorThreadStartedEvent: + ENTRY_POINT_NAME: str + monitor: _PeriodicMonitorThread + def __init__(self, monitor: _PeriodicMonitorThread) -> None: ... + +class IEventLoopBlocked(Interface): + greenlet: greenlet_t + blocking_time: float + info: Sequence[str] + hub: Hub | None + +@implementer(IEventLoopBlocked) +class EventLoopBlocked: + greenlet: greenlet_t + blocking_time: float + info: Sequence[str] + hub: Hub | None + def __init__(self, greenlet: greenlet_t, blocking_time: float, info: Sequence[str], *, hub: Hub | None = None) -> None: ... + +class IMemoryUsageThresholdExceeded(Interface): + mem_usage: int + max_allowed: int + memory_info: pmem + +class _AbstractMemoryEvent: + mem_usage: int + max_allowed: int + memory_info: pmem + def __init__(self, mem_usage: int, max_allowed: int, memory_info: pmem) -> None: ... + +@implementer(IMemoryUsageThresholdExceeded) +class MemoryUsageThresholdExceeded(_AbstractMemoryEvent): ... + +class IMemoryUsageUnderThreshold(Interface): + mem_usage: int + max_allowed: int + max_memory_usage: int + memory_info: pmem + +@implementer(IMemoryUsageUnderThreshold) +class MemoryUsageUnderThreshold(_AbstractMemoryEvent): + max_memory_usage: int + def __init__(self, mem_usage: int, max_allowed: int, memory_info: pmem, max_usage: int) -> None: ... + +class IGeventPatchEvent(Interface): + source: object + target: object + +@implementer(IGeventPatchEvent) +class GeventPatchEvent: + source: object + target: object + def __init__(self, source: object, target: object) -> None: ... + +class IGeventWillPatchEvent(IGeventPatchEvent): ... +class DoNotPatch(BaseException): ... + +@implementer(IGeventWillPatchEvent) +class GeventWillPatchEvent(GeventPatchEvent): ... + +class IGeventDidPatchEvent(IGeventPatchEvent): ... + +@implementer(IGeventWillPatchEvent) +class GeventDidPatchEvent(GeventPatchEvent): ... + +class IGeventWillPatchModuleEvent(IGeventWillPatchEvent): + source: ModuleType + target: ModuleType + module_name: str + target_item_names: list[str] + +@implementer(IGeventWillPatchModuleEvent) +class GeventWillPatchModuleEvent(GeventWillPatchEvent): + ENTRY_POINT_NAME: str + source: ModuleType + target: ModuleType + module_name: str + target_item_names: list[str] + def __init__(self, module_name: str, source: ModuleType, target: ModuleType, items: list[str]) -> None: ... + +class IGeventDidPatchModuleEvent(IGeventDidPatchEvent): + source: ModuleType + target: ModuleType + module_name: str + +@implementer(IGeventDidPatchModuleEvent) +class GeventDidPatchModuleEvent(GeventDidPatchEvent): + ENTRY_POINT_NAME: str + source: ModuleType + target: ModuleType + module_name: str + def __init__(self, module_name: str, source: ModuleType, target: ModuleType) -> None: ... + +class IGeventWillPatchAllEvent(IGeventWillPatchEvent): + patch_all_arguments: Mapping[str, Any] + patch_all_kwargs: Mapping[str, Any] + def will_patch_module(module_name: str) -> bool: ... # pyrefly: ignore [invalid-annotation] + +class _PatchAllMixin: + def __init__(self, patch_all_arguments: Mapping[str, Any], patch_all_kwargs: Mapping[str, Any]) -> None: ... + @property + def patch_all_arguments(self) -> dict[str, Any]: ... # safe to mutate, it's a copy + @property + def patch_all_kwargs(self) -> dict[str, Any]: ... # safe to mutate, it's a copy + +@implementer(IGeventWillPatchAllEvent) +class GeventWillPatchAllEvent(_PatchAllMixin, GeventWillPatchEvent): + ENTRY_POINT_NAME: str + def will_patch_module(self, module_name: str) -> bool: ... + +class IGeventDidPatchBuiltinModulesEvent(IGeventDidPatchEvent): + patch_all_arguments: Mapping[str, Any] + patch_all_kwargs: Mapping[str, Any] + +@implementer(IGeventDidPatchBuiltinModulesEvent) +class GeventDidPatchBuiltinModulesEvent(_PatchAllMixin, GeventDidPatchEvent): + ENTRY_POINT_NAME: str + +class IGeventDidPatchAllEvent(IGeventDidPatchEvent): ... + +@implementer(IGeventDidPatchAllEvent) +class GeventDidPatchAllEvent(_PatchAllMixin, GeventDidPatchEvent): + ENTRY_POINT_NAME: str + +__all__ = [ + "subscribers", + # monitor thread + "IEventLoopBlocked", + "EventLoopBlocked", + "IMemoryUsageThresholdExceeded", + "MemoryUsageThresholdExceeded", + "IMemoryUsageUnderThreshold", + "MemoryUsageUnderThreshold", + # Hub + "IPeriodicMonitorThread", + "IPeriodicMonitorThreadStartedEvent", + "PeriodicMonitorThreadStartedEvent", + # monkey + "IGeventPatchEvent", + "GeventPatchEvent", + "IGeventWillPatchEvent", + "DoNotPatch", + "GeventWillPatchEvent", + "IGeventDidPatchEvent", + "IGeventWillPatchModuleEvent", + "GeventWillPatchModuleEvent", + "IGeventDidPatchModuleEvent", + "GeventDidPatchModuleEvent", + "IGeventWillPatchAllEvent", + "GeventWillPatchAllEvent", + "IGeventDidPatchBuiltinModulesEvent", + "GeventDidPatchBuiltinModulesEvent", + "IGeventDidPatchAllEvent", + "GeventDidPatchAllEvent", +] diff --git a/stubs/gevent/gevent/exceptions.pyi b/stubs/gevent/gevent/exceptions.pyi new file mode 100644 index 000000000000..26cacfa4fc7d --- /dev/null +++ b/stubs/gevent/gevent/exceptions.pyi @@ -0,0 +1,17 @@ +from gevent.hub import Hub +from greenlet import GreenletExit + +class LoopExit(Exception): + @property + def hub(self) -> Hub | None: ... + +class BlockingSwitchOutError(AssertionError): ... +class InvalidSwitchError(AssertionError): ... +class ConcurrentObjectUseError(AssertionError): ... +class InvalidThreadUseError(RuntimeError): ... + +class HubDestroyed(GreenletExit): + destroy_loop: bool + def __init__(self, destroy_loop: bool) -> None: ... + +__all__ = ["LoopExit"] diff --git a/stubs/gevent/gevent/fileobject.pyi b/stubs/gevent/gevent/fileobject.pyi new file mode 100644 index 000000000000..d832e066b7ef --- /dev/null +++ b/stubs/gevent/gevent/fileobject.pyi @@ -0,0 +1,157 @@ +import sys +from typing import Any, TypeAlias + +from gevent._fileobjectcommon import FileObjectBlock as FileObjectBlock, FileObjectThread as FileObjectThread + +if sys.platform != "win32": + import io + from _typeshed import ( + FileDescriptorOrPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ) + from typing import IO, AnyStr, Literal, overload + + from gevent._fileobjectcommon import _IOT, FileObjectBase + + # this is implemented in _fileobjectposix and technically uses an undocumented subclass + # of RawIOBase, but the interface is the same, so it doesn't seem worth it to add + # annotations for it. _fileobjectcommon was barely worth it due to the common base class + # of all three FileObject types + class FileObjectPosix(FileObjectBase[_IOT, AnyStr]): + default_bufsize = io.DEFAULT_BUFFER_SIZE + fileio: io.RawIOBase + + # Text mode: always binds a TextIOWrapper + @overload + def __init__( + self: FileObjectPosix[io.TextIOWrapper, str], + fobj: FileDescriptorOrPath, + mode: OpenTextMode = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Unbuffered binary mode: binds a FileIO + @overload + def __init__( + self: FileObjectPosix[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0], + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[0] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectPosix[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + *, + buffering: Literal[0], + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def __init__( + self: FileObjectPosix[io.BufferedRandom, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectPosix[io.BufferedWriter, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectPosix[io.BufferedReader, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def __init__( + self: FileObjectPosix[IO[bytes], bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Fallback if mode is not specified + @overload + def __init__( + self: FileObjectPosix[IO[Any], Any], + fobj: FileDescriptorOrPath, + mode: str, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + _FileObjectType: TypeAlias = type[FileObjectPosix[Any, Any] | FileObjectBlock[Any, Any] | FileObjectThread[Any, Any]] + __all__ = ["FileObjectPosix", "FileObjectThread", "FileObjectBlock", "FileObject"] +else: + _FileObjectType: TypeAlias = type[FileObjectBlock[Any, Any] | FileObjectThread[Any, Any]] + __all__ = ["FileObjectThread", "FileObjectBlock", "FileObject"] + +FileObject: _FileObjectType diff --git a/stubs/gevent/gevent/greenlet.pyi b/stubs/gevent/gevent/greenlet.pyi new file mode 100644 index 000000000000..e6551f06f9de --- /dev/null +++ b/stubs/gevent/gevent/greenlet.pyi @@ -0,0 +1,106 @@ +import weakref +from collections.abc import Callable, Iterable, Sequence +from types import FrameType, TracebackType +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, overload +from typing_extensions import Self, disjoint_base + +import greenlet +from gevent._types import _Loop +from gevent._util import readproperty + +_T = TypeVar("_T") +_G = TypeVar("_G", bound=greenlet.greenlet) +_P = ParamSpec("_P") + +@disjoint_base +class Greenlet(greenlet.greenlet, Generic[_P, _T]): + # we can't use _P.args/_P.kwargs here because pyright will complain + # mypy doesn't seem to mind though + args: tuple[Any, ...] + kwargs: dict[str, Any] + value: _T | None + + @overload + def __init__( + self: Greenlet[_P, _T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + run: Callable[_P, _T], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> None: ... + @overload + def __init__(self: Greenlet[[], None]) -> None: ... + + @readproperty + def name(self) -> str: ... + @property + def minimal_ident(self) -> int: ... + @property + def loop(self) -> _Loop: ... + @property + def dead(self) -> bool: ... + @property + def started(self) -> bool: ... + @property + def exception(self) -> BaseException | None: ... + @property + def exc_info(self) -> tuple[type[BaseException], BaseException, TracebackType | None] | None: ... + @staticmethod + def add_spawn_callback(callback: Callable[[Greenlet[..., Any]], object]) -> None: ... + @staticmethod + def remove_spawn_callback(callback: Callable[[Greenlet[..., Any]], object]) -> None: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def has_links(self) -> bool: ... + def join(self, timeout: float | None = None) -> None: ... + def kill( + self, exception: type[BaseException] | BaseException = ..., block: bool = True, timeout: float | None = None + ) -> None: ... + def link(self, callback: Callable[[Self], object]) -> None: ... + def link_exception(self, callback: Callable[[Self], object]) -> None: ... + def link_value(self, callback: Callable[[Self], object]) -> None: ... + def rawlink(self, callback: Callable[[Self], object]) -> None: ... + def unlink(self, callback: Callable[[Self], Any]) -> None: ... + def unlink_all(self) -> None: ... + def ready(self) -> bool: ... + def run(self) -> Any: ... + + @overload + @classmethod + def spawn(cls, run: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Self: ... + @overload + @classmethod + def spawn(cls) -> Greenlet[[], None]: ... + + @overload + @classmethod + def spawn_later(cls, seconds: float, run: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Self: ... + @overload + @classmethod + def spawn_later(cls, seconds: float) -> Greenlet[[], None]: ... + + def start(self) -> None: ... + def start_later(self, seconds: float) -> None: ... + def successful(self) -> bool: ... + def __bool__(self) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + + # since these are for instrumentation which is disabled by default, we could + # consider just not annotating them... + spawning_stack_limit: ClassVar[int] + spawn_tree_locals: dict[str, Any] | None + spawning_greenlet: weakref.ref[greenlet.greenlet] | None + # not quite accurate, since it may be an internal dummy type instead + # but since it has all the same fields as FrameType we shouldn't care + spawning_stack: FrameType | None + +def joinall( + greenlets: Sequence[_G], timeout: float | None = None, raise_error: bool = False, count: int | None = None +) -> list[_G]: ... +def killall( + greenlets: Iterable[greenlet.greenlet], + exception: type[BaseException] | BaseException = ..., + block: bool = True, + timeout: float | None = None, +) -> None: ... + +__all__ = ["Greenlet", "joinall", "killall"] diff --git a/stubs/gevent/gevent/hub.pyi b/stubs/gevent/gevent/hub.pyi new file mode 100644 index 000000000000..0daf83413755 --- /dev/null +++ b/stubs/gevent/gevent/hub.pyi @@ -0,0 +1,118 @@ +from collections.abc import Callable +from types import TracebackType +from typing import Any, Generic, ParamSpec, Protocol, TextIO, TypeVar, overload, type_check_only + +import gevent._hub_local +import gevent._waiter +import greenlet +from gevent._hub_primitives import WaitOperationsGreenlet +from gevent._ident import IdentRegistry +from gevent._monitor import PeriodicMonitoringThread +from gevent._types import _Loop, _Watcher +from gevent._util import Lazy, readproperty +from gevent.greenlet import Greenlet +from gevent.resolver import AbstractResolver +from gevent.threadpool import ThreadPool + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +GreenletExit = greenlet.GreenletExit +getcurrent = greenlet.getcurrent +get_hub = gevent._hub_local.get_hub +Waiter = gevent._waiter.Waiter + +@type_check_only +class _DefaultReturnProperty(Protocol[_T]): + @overload + def __get__(self, obj: None, owner: type[object] | None = None) -> property: ... + @overload + def __get__(self, obj: object, owner: type[object] | None = None) -> _T: ... + + def __set__(self, obj: object, value: _T | None) -> None: ... + def __del__(self) -> None: ... + +def spawn_raw(function: Callable[..., object], *args: object, **kwargs: object) -> greenlet.greenlet: ... +def sleep(seconds: float = 0, ref: bool = True) -> None: ... +def idle(priority: int = 0) -> None: ... +def kill(greenlet: greenlet.greenlet, exception: type[BaseException] | BaseException = ...) -> None: ... + +class signal(Generic[_P]): + greenlet_class: type[Greenlet[..., Any]] | None + hub: Hub + watcher: _Watcher + handler: Callable[_P, object] + # we can't use _P.args/_P.kwargs here because pyright will complain + # mypy doesn't seem to mind though + args: tuple[Any, ...] + kwargs: dict[str, Any] + def __init__(self, signalnum: int, handler: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + + @property + def ref(self) -> bool: ... + @ref.setter + def ref(self, value: bool) -> None: ... + + def cancel(self) -> None: ... + def handle(self) -> None: ... + +def reinit(hub: Hub | None = None) -> None: ... + +class Hub(WaitOperationsGreenlet): + SYSTEM_ERROR: tuple[type[BaseException], ...] + NOT_ERROR: tuple[type[BaseException], ...] + threadpool_size: int + periodic_monitoring_thread: PeriodicMonitoringThread | None + thread_ident: int + name: str + loop: _Loop + format_context: Callable[[object], str] + minimal_ident: int + + @overload + def __init__(self, loop: _Loop, default: None = None) -> None: ... + @overload + def __init__(self, loop: None = None, default: bool | None = None) -> None: ... + + @Lazy + def ident_registry(self) -> IdentRegistry: ... + @property + def loop_class(self) -> type[_Loop]: ... + @property + def backend(self) -> int | str: ... + @property + def main_hub(self) -> bool: ... + def handle_error( + self, + context: object | None, + type: type[BaseException] | None, + value: BaseException | str | None, + tb: TracebackType | None, + ) -> None: ... + def handle_system_error( + self, type: type[BaseException], value: BaseException | None, tb: TracebackType | None = None + ) -> None: ... + @readproperty + def exception_stream(self) -> TextIO | None: ... + def print_exception( + self, context: object | None, t: type[BaseException] | None, v: BaseException | str | None, tb: TracebackType | None + ) -> None: ... + def run(self) -> None: ... + def start_periodic_monitoring_thread(self) -> PeriodicMonitoringThread: ... + def join(self, timeout: float | None = None) -> bool: ... + def destroy(self, destroy_loop: bool | None = None) -> None: ... + @property + def resolver_class(self) -> type[AbstractResolver]: ... + resolver: _DefaultReturnProperty[AbstractResolver] + @property + def threadpool_class(self) -> type[ThreadPool]: ... + threadpool: _DefaultReturnProperty[ThreadPool] + +class linkproxy: + __slots__ = ["callback", "obj"] + callback: Callable[[object], object] + obj: object + def __init__(self, callback: Callable[[_T], object], obj: _T) -> None: ... + def __call__(self, *args: object) -> None: ... + +__all__ = ["getcurrent", "GreenletExit", "spawn_raw", "sleep", "kill", "signal", "reinit", "get_hub", "Hub", "Waiter"] diff --git a/stubs/gevent/gevent/libev/__init__.pyi b/stubs/gevent/gevent/libev/__init__.pyi new file mode 100644 index 000000000000..c9c2ef67bd9d --- /dev/null +++ b/stubs/gevent/gevent/libev/__init__.pyi @@ -0,0 +1 @@ +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/libev/corecext.pyi b/stubs/gevent/gevent/libev/corecext.pyi new file mode 100644 index 000000000000..fd2f8d80f4dd --- /dev/null +++ b/stubs/gevent/gevent/libev/corecext.pyi @@ -0,0 +1,103 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Callable, Sequence +from types import TracebackType +from typing import Any, ParamSpec +from typing_extensions import disjoint_base + +from gevent._ffi.loop import _ErrorHandler +from gevent._types import _Callback +from gevent.libev import watcher + +# this c extension is only available on posix +if sys.platform != "win32": + _P = ParamSpec("_P") + + def get_version() -> str: ... + def get_header_version() -> str: ... + # the final item in the list could be an integer if one of the backends did not have a string mapping + def embeddable_backends() -> list[str | int]: ... + def recommended_backends() -> list[str | int]: ... + def supported_backends() -> list[str | int]: ... + def time() -> float: ... + + @disjoint_base + class loop: + starting_timer_may_update_loop_time: bool + error_handler: _ErrorHandler + @property + def approx_timer_resolution(self) -> float: ... # readonly in Cython + def __init__(self, flags: Sequence[str] | str | int | None = None, default: bool | None = None, ptr: int = 0) -> None: ... + def destroy(self) -> None: ... + @property + def ptr(self) -> int: ... + @property + def WatcherType(self) -> type[watcher.watcher]: ... + @property + def MAXPRI(self) -> int: ... + @property + def MINPRI(self) -> int: ... + def handle_error( + self, context: object | None, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def run(self, nowait: bool = False, once: bool = False) -> None: ... + def reinit(self) -> None: ... + def ref(self) -> None: ... + def unref(self) -> None: ... + def break_(self, how: int = 1) -> None: ... + def verify(self) -> None: ... + def now(self) -> float: ... + def update_now(self) -> None: ... + update = update_now # deprecated + @property + def default(self) -> bool: ... + @property + def iteration(self) -> int: ... + @property + def depth(self) -> int: ... + @property + def backend_int(self) -> int: ... + @property + def backend(self) -> str | int: ... + @property + def pendingcnt(self) -> int: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> watcher.io: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> watcher.timer: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> watcher.signal: ... + def idle(self, ref: bool = True, priority: int | None = None) -> watcher.idle: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> watcher.prepare: ... + def check(self, ref: bool = True, priority: int | None = None) -> watcher.check: ... + def fork(self, ref: bool = True, priority: int | None = None) -> watcher.fork: ... + def async_(self, ref: bool = True, priority: int | None = None) -> watcher.async_: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> watcher.child: ... + def install_sigchld(self) -> None: ... + def reset_sigchld(self) -> None: ... + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = None) -> watcher.stat: ... + # These technically don't allow the functions arguments to be passed in as kwargs + # but there's no way to express that yet with ParamSpec, however, we would still like + # to verify that the arguments match + def run_callback(self, func: Callable[_P, Any], *args: _P.args, **_: _P.kwargs) -> _Callback: ... + def run_callback_threadsafe(self, func: Callable[_P, Any], *args: _P.args, **_: _P.kwargs) -> _Callback: ... + def fileno(self) -> FileDescriptor | None: ... + @property + def activecnt(self) -> int: ... + @property + def sig_pending(self) -> int: ... + # the final item in the list could be a integer if some of the flags don't a string mapping + @property + def origflags(self) -> list[str | int]: ... + @property + def origflags_int(self) -> int: ... + @property + def sigfd(self) -> FileDescriptor: ... + + __all__ = [ + "get_version", + "get_header_version", + "supported_backends", + "recommended_backends", + "embeddable_backends", + "time", + "loop", + ] diff --git a/stubs/gevent/gevent/libev/corecffi.pyi b/stubs/gevent/gevent/libev/corecffi.pyi new file mode 100644 index 000000000000..3f7821a82524 --- /dev/null +++ b/stubs/gevent/gevent/libev/corecffi.pyi @@ -0,0 +1,46 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Sequence + +from gevent._ffi.loop import AbstractLoop +from gevent.libev import watcher + +def get_version() -> str: ... +def get_header_version() -> str: ... +def supported_backends() -> list[str | int]: ... +def recommended_backends() -> list[str | int]: ... +def embeddable_backends() -> list[str | int]: ... +def time() -> float: ... + +class loop(AbstractLoop): + approx_timer_resolution: float + error_handler: None + @property + def MAXPRI(self) -> int: ... + @property + def MINPRI(self) -> int: ... + def __init__(self, flags: Sequence[str] | str | int | None = None, default: bool | None = None) -> None: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> watcher.io: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> watcher.timer: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> watcher.signal: ... + def idle(self, ref: bool = True, priority: int | None = None) -> watcher.idle: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> watcher.prepare: ... + def check(self, ref: bool = True, priority: int | None = None) -> watcher.check: ... + def async_(self, ref: bool = True, priority: int | None = None) -> watcher.async_: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> watcher.fork: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> watcher.child: ... + def reset_sigchld(self) -> None: ... + + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = None) -> watcher.stat: ... + +__all__ = [ + "get_version", + "get_header_version", + "supported_backends", + "recommended_backends", + "embeddable_backends", + "time", + "loop", +] diff --git a/stubs/gevent/gevent/libev/watcher.pyi b/stubs/gevent/gevent/libev/watcher.pyi new file mode 100644 index 000000000000..776056872c35 --- /dev/null +++ b/stubs/gevent/gevent/libev/watcher.pyi @@ -0,0 +1,71 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Callable +from typing import ParamSpec, TypeAlias + +from gevent._ffi import watcher as _base +from gevent.libev.corecffi import loop as cffi_loop + +__all__: list[str] = [] + +if sys.platform != "win32": + from gevent.libev.corecext import loop as cext_loop + + _Loop: TypeAlias = cffi_loop | cext_loop +else: + _Loop: TypeAlias = cffi_loop + +_P = ParamSpec("_P") + +class watcher(_base.watcher): + def __init__(self, _loop: _Loop, ref: bool = True, priority: int | None = None) -> None: ... + + @property + def ref(self) -> bool: ... + @ref.setter + def ref(self, value: bool) -> None: ... + + # does not accept keyword arguments + def feed(self, revents: int, callback: Callable[_P, object], *args: _P.args, **_: _P.kwargs) -> None: ... + +class io(_base.IoMixin, watcher): + EVENT_MASK: int + + @property + def fd(self) -> FileDescriptor: ... + @fd.setter + def fd(self, value: FileDescriptor) -> None: ... + + @property + def events(self) -> int: ... + @events.setter + def events(self, events: int) -> None: ... + + @property + def events_str(self) -> str: ... + +class timer(_base.TimerMixin, watcher): + @property + def at(self) -> float: ... + +class signal(_base.SignalMixin, watcher): ... +class idle(_base.IdleMixin, watcher): ... +class prepare(_base.PrepareMixin, watcher): ... +class check(_base.CheckMixin, watcher): ... +class fork(_base.ForkMixin, watcher): ... +class async_(_base.AsyncMixin, watcher): ... + +class child(_base.ChildMixin, watcher): + @property + def rpid(self) -> int: ... + @rpid.setter + def rpid(self, value: int) -> None: ... + + @property + def rstatus(self) -> int: ... + @rstatus.setter + def rstatus(self, value: int) -> None: ... + +class stat(_base.StatMixin, watcher): + @property + def interval(self) -> float: ... diff --git a/stubs/gevent/gevent/libuv/__init__.pyi b/stubs/gevent/gevent/libuv/__init__.pyi new file mode 100644 index 000000000000..c9c2ef67bd9d --- /dev/null +++ b/stubs/gevent/gevent/libuv/__init__.pyi @@ -0,0 +1 @@ +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/libuv/loop.pyi b/stubs/gevent/gevent/libuv/loop.pyi new file mode 100644 index 000000000000..cd4ccd5287ef --- /dev/null +++ b/stubs/gevent/gevent/libuv/loop.pyi @@ -0,0 +1,44 @@ +import sys +from _typeshed import FileDescriptor +from typing import NamedTuple + +from gevent._ffi.loop import AbstractLoop +from gevent._types import _IoWatcher +from gevent.libuv import watcher + +def get_version() -> str: ... +def get_header_version() -> str: ... +def supported_backends() -> list[str]: ... + +class loop(AbstractLoop): + CALLBACK_CHECK_COUNT: int + SIGNAL_CHECK_INTERVAL_MS: int + approx_timer_resolution: float + error_handler: None + def __init__(self, flags: int | None = None, default: bool | None = None) -> None: ... + + class _HandleState(NamedTuple): + handle: int + type: str + watcher: watcher.watcher + ref: bool + active: bool + closing: bool + + def debug(self) -> list[_HandleState]: ... + def install_sigchld(self) -> None: ... + def reset_sigchld(self) -> None: ... + # this returns a class private to gevent.libuv.watcher.io, which satisifies the protocol + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> _IoWatcher: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> watcher.timer: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> watcher.signal: ... + def idle(self, ref: bool = True, priority: int | None = None) -> watcher.idle: ... + def check(self, ref: bool = True, priority: int | None = None) -> watcher.check: ... + def async_(self, ref: bool = True, priority: int | None = None) -> watcher.async_: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> watcher.fork: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> watcher.child: ... + # prepare is not supported on libuv yet, but we need type_error to annotate that + +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/libuv/watcher.pyi b/stubs/gevent/gevent/libuv/watcher.pyi new file mode 100644 index 000000000000..84c9fe212baf --- /dev/null +++ b/stubs/gevent/gevent/libuv/watcher.pyi @@ -0,0 +1,37 @@ +from gevent._ffi import watcher as _base +from gevent._types import _IoWatcher + +class watcher(_base.watcher): + @property + def ref(self) -> bool: ... + @ref.setter + def ref(self, value: bool) -> None: ... + +class io(_base.IoMixin, watcher): + EVENT_MASK: int + + @property + def events(self) -> int: ... + @events.setter + def events(self, value: int) -> None: ... + + def multiplex(self, events: int) -> _IoWatcher: ... + def close_all(self) -> None: ... + +class fork(_base.ForkMixin, watcher): ... +class child(_base.ChildMixin, watcher): ... + +# for some reason pending on this has been overwritten with None, but we don't +# necessarily want to change our Protocol to reflect that, so for now we ignore it +class async_(_base.AsyncMixin, watcher): ... +class timer(_base.TimerMixin, watcher): ... + +class stat(_base.StatMixin, watcher): + MIN_STAT_INTERVAL: float + +class signal(_base.SignalMixin, watcher): ... +class idle(_base.IdleMixin, watcher): ... +class check(_base.CheckMixin, watcher): ... +class prepare(_base.PrepareMixin, watcher): ... + +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/local.pyi b/stubs/gevent/gevent/local.pyi new file mode 100644 index 000000000000..ac2642fbe6a9 --- /dev/null +++ b/stubs/gevent/gevent/local.pyi @@ -0,0 +1,20 @@ +from typing import Any +from typing_extensions import Self + +class local: + __slots__ = ( + "_local__impl", + "_local_type_set_descriptors", + "_local_type_get_descriptors", + "_local_type_vars", + "_local_type_del_descriptors", + "_local_type", + "_local_type_set_or_del_descriptors", + ) + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + def __copy__(self) -> Self: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __delattr__(self, name: str, /) -> None: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +__all__ = ["local"] diff --git a/stubs/gevent/gevent/lock.pyi b/stubs/gevent/gevent/lock.pyi new file mode 100644 index 000000000000..80cb2342f661 --- /dev/null +++ b/stubs/gevent/gevent/lock.pyi @@ -0,0 +1,44 @@ +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal + +from gevent._abstract_linkable import AbstractLinkable +from gevent.hub import Hub + +__all__ = ["Semaphore", "BoundedSemaphore", "DummySemaphore", "RLock"] + +class Semaphore(AbstractLinkable): + __slots__ = ("counter", "_multithreaded") + counter: int + def __init__(self, value: int = 1, hub: Hub | None = None) -> None: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def locked(self) -> bool: ... + def ready(self) -> bool: ... + def release(self) -> int: ... + def wait(self, timeout: float | None = None) -> int: ... + def __enter__(self) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +class BoundedSemaphore(Semaphore): + __slots__ = ("_initial_value",) + +class DummySemaphore: + def __init__(self, value: int | None = None) -> None: ... + def locked(self) -> Literal[False]: ... + def ready(self) -> Literal[True]: ... + def release(self) -> None: ... + def rawlink(self, callback: Callable[[Any], object]) -> None: ... + def unlink(self, callback: Callable[[Any], object]) -> None: ... + def wait(self, timeout: float | None = None) -> Literal[1]: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> Literal[True]: ... + def __enter__(self) -> None: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + +class RLock: + __slots__ = ("_block", "_owner", "_count", "__weakref__") + def __init__(self, hub: Hub | None = None) -> None: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def __enter__(self) -> bool: ... + def release(self) -> None: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + def locked(self) -> bool: ... diff --git a/stubs/gevent/gevent/monkey/__init__.pyi b/stubs/gevent/gevent/monkey/__init__.pyi new file mode 100644 index 000000000000..da6da0c3f35f --- /dev/null +++ b/stubs/gevent/gevent/monkey/__init__.pyi @@ -0,0 +1,68 @@ +from typing import Any + +from gevent.monkey.api import get_original as get_original, patch_module as patch_module + +class MonkeyPatchWarning(RuntimeWarning): ... + +def is_module_patched(mod_name: str) -> bool: ... +def is_object_patched(mod_name: str, item_name: str) -> bool: ... +def patch_os() -> None: ... +def patch_queue() -> None: ... +def patch_time() -> None: ... +def patch_thread( + threading: bool = True, _threading_local: bool = True, Event: bool = True, logging: bool = True, existing_locks: bool = True +) -> None: ... +def patch_socket(dns: bool = True, aggressive: bool = True) -> None: ... +def patch_builtins() -> None: ... +def patch_dns() -> None: ... +def patch_ssl() -> None: ... +def patch_select(aggressive: bool = True) -> None: ... +def patch_selectors(aggressive: bool = True) -> None: ... +def patch_subprocess() -> None: ... +def patch_sys(stdin: bool = True, stdout: bool = True, stderr: bool = True) -> None: ... +def patch_signal() -> None: ... +def patch_all( + socket: bool = True, + dns: bool = True, + time: bool = True, + select: bool = True, + thread: bool = True, + os: bool = True, + ssl: bool = True, + subprocess: bool = True, + sys: bool = False, + aggressive: bool = True, + Event: bool = True, + builtins: bool = True, # does nothing on Python 3 + signal: bool = True, + queue: bool = True, + contextvars: bool = True, # does nothing on Python 3.7+ + **kwargs: object, +) -> bool | None: ... +def main() -> dict[str, Any]: ... + +__all__ = [ + "patch_all", + "patch_builtins", + "patch_dns", + "patch_os", + "patch_queue", + "patch_select", + "patch_signal", + "patch_socket", + "patch_ssl", + "patch_subprocess", + "patch_sys", + "patch_thread", + "patch_time", + # query functions + "get_original", + "is_module_patched", + "is_object_patched", + # plugin API + "patch_module", + # module functions + "main", + # Errors and warnings + "MonkeyPatchWarning", +] diff --git a/stubs/gevent/gevent/monkey/api.pyi b/stubs/gevent/gevent/monkey/api.pyi new file mode 100644 index 000000000000..130687dec5c0 --- /dev/null +++ b/stubs/gevent/gevent/monkey/api.pyi @@ -0,0 +1,7 @@ +from types import ModuleType +from typing import Any + +def get_original(mod_name: str, item_name: str) -> Any: ... +def patch_item(module: ModuleType, attr: str, newitem: object) -> None: ... +def remove_item(module: ModuleType, attr: str) -> None: ... +def patch_module(target_module: ModuleType, source_module: ModuleType, items: list[str] | None = None) -> bool: ... diff --git a/stubs/gevent/gevent/os.pyi b/stubs/gevent/gevent/os.pyi new file mode 100644 index 000000000000..ac7d0cf0b976 --- /dev/null +++ b/stubs/gevent/gevent/os.pyi @@ -0,0 +1,36 @@ +import os +import sys +from _typeshed import FileDescriptor, ReadableBuffer +from collections.abc import Callable +from typing import Literal + +from gevent._types import _ChildWatcher, _Loop + +def tp_read(fd: FileDescriptor, n: int) -> bytes: ... +def tp_write(fd: FileDescriptor, buf: ReadableBuffer) -> int: ... + +if sys.platform != "win32": + def close(fd: FileDescriptor) -> None: ... + def make_nonblocking(fd: FileDescriptor) -> Literal[True] | None: ... + def nb_read(fd: FileDescriptor, n: int) -> bytes: ... + def nb_write(fd: FileDescriptor, buf: ReadableBuffer) -> int: ... + fork = os.fork + forkpty = os.forkpty + def fork_gevent() -> int: ... + def forkpty_gevent() -> tuple[int, int]: ... + waitpid = os.waitpid + def fork_and_watch( + callback: Callable[[_ChildWatcher], object] | None = None, + loop: _Loop | None = None, + ref: bool = False, + fork: Callable[[], int] = ..., + ) -> int: ... + def forkpty_and_watch( + callback: Callable[[_ChildWatcher], object] | None = None, + loop: _Loop | None = None, + ref: bool = False, + forkpty: Callable[[], tuple[int, int]] = ..., + ) -> tuple[int, int]: ... + + posix_spawn = os.posix_spawn + posix_spawnp = os.posix_spawnp diff --git a/stubs/gevent/gevent/pool.pyi b/stubs/gevent/gevent/pool.pyi new file mode 100644 index 000000000000..74345130b9ed --- /dev/null +++ b/stubs/gevent/gevent/pool.pyi @@ -0,0 +1,209 @@ +from collections.abc import Callable, Collection, Iterable, Iterator +from typing import Any, ParamSpec, TypeVar, overload + +from gevent._imap import IMap, IMapUnordered +from gevent.greenlet import Greenlet +from gevent.queue import Full as QueueFull + +__all__ = ["Group", "Pool", "PoolFull"] + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_S = TypeVar("_S") +_P = ParamSpec("_P") + +class GroupMappingMixin: + __slots__ = () + def spawn(self, func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Greenlet[_P, _T]: ... + # we would like to use ParamSpec for these, but since args and kwds are passed in as is + # pyright will complain if we use _P.args/_P.kwargs, it appears to work on mypy though + # we can probably get away with Sequence and Mapping instead of tuple and dict, but for + # now we will be strict, just to be safe + def apply_cb( + self, + func: Callable[..., _T], + args: tuple[Any, ...] | None = None, + kwds: dict[str, Any] | None = None, + callback: Callable[[_T], object] | None = None, + ) -> _T: ... + # The ParamSpec of the spawned greenlet can differ from the one being passed in, but the return type will match + def apply_async( + self, + func: Callable[..., _T], + args: tuple[Any, ...] | None = None, + kwds: dict[str, Any] | None = None, + callback: Callable[[_T], object] | None = None, + ) -> Greenlet[..., _T]: ... + def apply(self, func: Callable[..., _T], args: tuple[Any, ...] | None = None, kwds: dict[str, Any] | None = None) -> _T: ... + def map(self, func: Callable[[_T], _S], iterable: Iterable[_T]) -> list[_S]: ... + def map_cb( + self, func: Callable[[_T], _S], iterable: Iterable[_T], callback: Callable[[list[_S]], object] | None = None + ) -> list[_S]: ... + def map_async( + self, func: Callable[[_T], _S], iterable: Iterable[_T], callback: Callable[[list[_S]], object] | None = None + ) -> Greenlet[..., list[_S]]: ... + + @overload + def imap(self, func: Callable[[_T1], _S], iter1: Iterable[_T1], /, *, maxsize: int | None = None) -> IMap[[_T1], _S]: ... + @overload + def imap( + self, func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, maxsize: int | None = None + ) -> IMap[[_T1, _T2], _S]: ... + @overload + def imap( + self, + func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + /, + *, + maxsize: int | None = None, + ) -> IMap[[_T1, _T2, _T3], _S]: ... + @overload + def imap( + self, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + *, + maxsize: int | None = None, + ) -> IMap[[_T1, _T2, _T3, _T4], _S]: ... + @overload + def imap( + self, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + maxsize: int | None = None, + ) -> IMap[[_T1, _T2, _T3, _T4, _T5], _S]: ... + @overload + def imap( + self, + func: Callable[_P, _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + maxsize: int | None = None, + ) -> IMap[_P, _S]: ... + + @overload + def imap_unordered( + self, func: Callable[[_T1], _S], iter1: Iterable[_T1], /, *, maxsize: int | None = None + ) -> IMapUnordered[[_T1], _S]: ... + @overload + def imap_unordered( + self, func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, maxsize: int | None = None + ) -> IMapUnordered[[_T1, _T2], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + /, + *, + maxsize: int | None = None, + ) -> IMapUnordered[[_T1, _T2, _T3], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + *, + maxsize: int | None = None, + ) -> IMapUnordered[[_T1, _T2, _T3, _T4], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + maxsize: int | None = None, + ) -> IMapUnordered[[_T1, _T2, _T3, _T4, _T5], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[_P, _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + maxsize: int | None = None, + ) -> IMapUnordered[_P, _S]: ... + +# TODO: Consider making these generic in Greenlet. The drawback would be, that it +# wouldn't be possible to mix Greenlets with different return values/ParamSpecs +# unless you bind Grenlet[..., object], but in that case all the spawn/apply/map +# methods become less helpful, because the return types cannot be as specific... +# We would need higher-kinded TypeVars if we wanted to give up neither +class Group(GroupMappingMixin): + greenlet_class: type[Greenlet[..., Any]] + greenlets: set[Greenlet[..., Any]] + dying: set[Greenlet[..., Any]] + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, grenlets: Collection[Greenlet[..., object]], /) -> None: ... + + def __len__(self) -> int: ... + def __contains__(self, item: Greenlet[..., object]) -> bool: ... + def __iter__(self) -> Iterator[Greenlet[..., object]]: ... + def add(self, greenlet: Greenlet[..., object]) -> None: ... + def discard(self, greenlet: Greenlet[..., object]) -> None: ... + def start(self, greenlet: Greenlet[..., object]) -> None: ... + def join(self, timeout: float | None = None, raise_error: bool = False) -> bool: ... + def kill( + self, exception: type[BaseException] | BaseException = ..., block: bool = True, timeout: float | None = None + ) -> None: ... + def killone( + self, + greenlet: Greenlet[..., object], + exception: type[BaseException] | BaseException = ..., + block: bool = True, + timeout: float | None = None, + ) -> None: ... + def full(self) -> bool: ... + def wait_available(self, timeout: float | None = None) -> int | None: ... + +class PoolFull(QueueFull): ... + +class Pool(Group): + size: int | None + def __init__(self, size: int | None = None, greenlet_class: type[Greenlet[..., object]] | None = None) -> None: ... + def wait_available(self, timeout: float | None = None) -> int: ... + def free_count(self) -> int: ... + def start(self, greenlet: Greenlet[..., object], blocking: bool = True, timeout: float | None = None) -> None: ... + def add(self, greenlet: Greenlet[..., object], blocking: bool = True, timeout: float | None = None) -> None: ... diff --git a/stubs/gevent/gevent/pywsgi.pyi b/stubs/gevent/gevent/pywsgi.pyi new file mode 100644 index 000000000000..cda7fd112a38 --- /dev/null +++ b/stubs/gevent/gevent/pywsgi.pyi @@ -0,0 +1,197 @@ +from _typeshed import OptExcInfo, StrOrBytesPath, SupportsWrite +from _typeshed.wsgi import WSGIApplication, WSGIEnvironment +from collections.abc import Callable, Container, Iterable, Iterator +from http.client import HTTPMessage +from io import BufferedIOBase, BufferedReader +from logging import Logger +from types import TracebackType +from typing import Any, ClassVar, Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self + +from gevent.baseserver import _Spawner +from gevent.server import StreamServer +from gevent.socket import socket as _GeventSocket +from gevent.ssl import SSLContext + +__all__ = ["WSGIServer", "WSGIHandler", "LoggingLogAdapter", "Environ", "SecureEnviron", "WSGISecureEnviron"] + +_T = TypeVar("_T") + +@type_check_only +class _LogOutputStream(SupportsWrite[str], Protocol): + def writelines(self, lines: Iterable[str], /) -> None: ... + def flush(self) -> None: ... + +class Input: + __slots__ = ( + "rfile", + "content_length", + "socket", + "position", + "chunked_input", + "chunk_length", + "_chunked_input_error", + "send_100_continue_enabled", + ) + rfile: BufferedReader + content_length: int | None + socket: _GeventSocket | None + position: int + chunked_input: bool + chunk_length: int + send_100_continue_enabled: bool + def __init__( + self, rfile: BufferedReader, content_length: int | None, socket: _GeventSocket | None = None, chunked_input: bool = False + ) -> None: ... + def read(self, length: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, hint: object | None = None) -> list[bytes]: ... + def __iter__(self) -> Self: ... + def next(self) -> bytes: ... + __next__ = next + +class OldMessage(HTTPMessage): + status: str + def __init__(self) -> None: ... + + @overload + def getheader(self, name: str, default: None = None) -> str | None: ... + @overload + def getheader(self, name: str, default: _T) -> str | _T: ... + + @property + def headers(self) -> Iterator[str]: ... + @property + def typeheader(self) -> str | None: ... + +class WSGIHandler: + protocol_version: str + def MessageClass(self, fp: BufferedIOBase) -> OldMessage: ... + status: str | None + response_headers: list[tuple[str, str]] | None + code: int | None + provided_date: str | None + provided_content_length: str | None + close_connection: bool + time_start: float + time_finish: float + headers_sent: bool + response_use_chunked: bool + connection_upgraded: bool + environ: WSGIEnvironment | None + application: WSGIApplication | None + requestline: str | None + response_length: int + result: Iterable[bytes] | None + wsgi_input: Input | None + content_length: int + headers: OldMessage + request_version: str | None + command: str | None + path: str | None + socket: _GeventSocket + client_address: str + server: WSGIServer + rfile: BufferedReader + def __init__(self, sock: _GeventSocket, address: str, server: WSGIServer) -> None: ... + def handle(self) -> None: ... + def read_request(self, raw_requestline: str) -> OldMessage: ... + def log_error(self, msg: str, *args: object) -> None: ... + def read_requestline(self) -> str: ... + def handle_one_request(self) -> tuple[str, bytes] | Literal[True] | None: ... + def finalize_headers(self) -> None: ... + ApplicationError: type[AssertionError] + def write(self, data: bytes) -> None: ... + def start_response( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None + ) -> Callable[[bytes], None]: ... + def log_request(self) -> None: ... + def format_request(self) -> str: ... + def process_result(self) -> None: ... + def run_application(self) -> None: ... + ignored_socket_errors: tuple[int, ...] + def handle_one_response(self) -> None: ... + def handle_error(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def get_environ(self) -> WSGIEnvironment: ... + +class LoggingLogAdapter: + __slots__ = ("_logger", "_level") + def __init__(self, logger: Logger, level: int = 20) -> None: ... + def write(self, msg: str) -> None: ... + def flush(self) -> None: ... + def writelines(self, lines: Iterable[str]) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: object) -> None: ... + def __delattr__(self, name: str) -> None: ... + +class Environ(WSGIEnvironment): + __slots__ = () + +class SecureEnviron(Environ): + __slots__ = ("secure_repr", "whitelist_keys", "print_masked_keys") + default_secure_repr: ClassVar[bool] + default_whitelist_keys: ClassVar[Container[str]] + default_print_masked_keys: ClassVar[bool] + secure_repr: bool + whitelist_keys: Container[str] + print_masked_keys: bool + +class WSGISecureEnviron(SecureEnviron): ... + +class WSGIServer(StreamServer): + handler_class: type[WSGIHandler] + log: _LogOutputStream + error_log: _LogOutputStream + environ_class: type[WSGIEnvironment] + secure_environ_class: type[SecureEnviron] + base_env: WSGIEnvironment + application: WSGIApplication + + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + application: WSGIApplication | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + log: str | Logger | _LogOutputStream | None = "default", + error_log: str | Logger | _LogOutputStream | None = "default", + handler_class: type[WSGIHandler] | None = None, + environ: WSGIEnvironment | None = None, + *, + ssl_context: SSLContext, + server_side: bool = True, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ) -> None: ... + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + application: WSGIApplication | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + log: str | Logger | _LogOutputStream | None = "default", + error_log: str | Logger | _LogOutputStream | None = "default", + handler_class: type[WSGIHandler] | None = None, + environ: WSGIEnvironment | None = None, + *, + keyfile: StrOrBytesPath = ..., + certfile: StrOrBytesPath = ..., + server_side: bool = True, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str = ..., + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str = ..., + ) -> None: ... + + environ: WSGIEnvironment + def set_environ(self, environ: WSGIEnvironment | None = None) -> None: ... + max_accept: int + def set_max_accept(self) -> None: ... + def get_environ(self) -> WSGIEnvironment: ... + def init_socket(self) -> None: ... + def update_environ(self) -> None: ... + def handle(self, sock: _GeventSocket, address: str) -> None: ... diff --git a/stubs/gevent/gevent/queue.pyi b/stubs/gevent/gevent/queue.pyi new file mode 100644 index 000000000000..afe1ce226dc0 --- /dev/null +++ b/stubs/gevent/gevent/queue.pyi @@ -0,0 +1,115 @@ +import sys +import types +from collections import deque +from collections.abc import Iterable + +# technically it is using _PySimpleQueue, which has the same interface as SimpleQueue +from queue import Empty as Empty, Full as Full +from typing import Any, Generic, Literal, TypeVar, final, overload +from typing_extensions import Self + +from gevent._waiter import Waiter +from gevent.hub import Hub + +__all__ = ["Queue", "PriorityQueue", "LifoQueue", "SimpleQueue", "JoinableQueue", "Channel", "Empty", "Full", "ShutDown"] + +if sys.version_info >= (3, 13): + from queue import ShutDown as ShutDown +else: + class ShutDown(Exception): ... + +_T = TypeVar("_T") + +class SimpleQueue(Generic[_T]): + __slots__ = ("_maxsize", "getters", "putters", "hub", "_event_unlock", "queue", "__weakref__", "is_shutdown") + @property + def hub(self) -> Hub: ... # readonly in Cython + @property + def queue(self) -> deque[_T]: ... # readonly in Cython + maxsize: int | None + is_shutdown: bool + + @classmethod + def __class_getitem__(cls, item: Any, /) -> types.GenericAlias: ... + + @overload + def __init__(self, maxsize: int | None = None) -> None: ... + @overload + def __init__(self, maxsize: int | None, items: Iterable[_T]) -> None: ... + @overload + def __init__(self, maxsize: int | None = None, *, items: Iterable[_T]) -> None: ... + + def copy(self) -> Self: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + def peek(self, block: bool = True, timeout: float | None = None) -> _T: ... + def peek_nowait(self) -> _T: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def qsize(self) -> int: ... + def __bool__(self) -> bool: ... + def __iter__(self) -> Self: ... + def __len__(self) -> int: ... + def __next__(self) -> _T: ... + next = __next__ + +class Queue(SimpleQueue[_T]): + __slots__ = ("_cond", "unfinished_tasks") + @property + def unfinished_tasks(self) -> int: ... # readonly in Cython + + @overload + def __init__(self, maxsize: int | None = None, *, unfinished_tasks: int | None = None) -> None: ... + @overload + def __init__(self, maxsize: int | None, items: Iterable[_T], unfinished_tasks: int | None = None) -> None: ... + @overload + def __init__(self, maxsize: int | None = None, *, items: Iterable[_T], unfinished_tasks: int | None = None) -> None: ... + + def join(self, timeout: float | None = None) -> bool: ... + def task_done(self) -> None: ... + def shutdown(self, immediate: bool = False) -> None: ... + +JoinableQueue = Queue + +@final +class UnboundQueue(Queue[_T]): + __slots__ = () + + @overload + def __init__(self, maxsize: None = None) -> None: ... + @overload + def __init__(self, maxsize: None, items: Iterable[_T]) -> None: ... + @overload + def __init__(self, maxsize: None = None, *, items: Iterable[_T]) -> None: ... + +class PriorityQueue(Queue[_T]): + __slots__ = () + +class LifoQueue(Queue[_T]): + __slots__ = () + +class Channel(Generic[_T]): + __slots__ = ("getters", "putters", "hub", "_event_unlock", "__weakref__") + @property + def getters(self) -> deque[Waiter[Any]]: ... # readonly in Cython + @property + def putters(self) -> deque[tuple[_T, Waiter[Any]]]: ... # readonly in Cython + @property + def hub(self) -> Hub: ... # readonly in Cython + def __init__(self, maxsize: Literal[1] = 1) -> None: ... + @classmethod + def __class_getitem__(cls, item: Any, /) -> types.GenericAlias: ... + @property + def balance(self) -> int: ... + def qsize(self) -> Literal[0]: ... + def empty(self) -> Literal[True]: ... + def full(self) -> Literal[True]: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + next = __next__ diff --git a/stubs/gevent/gevent/resolver/__init__.pyi b/stubs/gevent/gevent/resolver/__init__.pyi new file mode 100644 index 000000000000..72609bc06442 --- /dev/null +++ b/stubs/gevent/gevent/resolver/__init__.pyi @@ -0,0 +1,23 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +from gevent._types import _AddrinfoResult, _NameinfoResult, _SockAddr + +_F = TypeVar("_F", bound=Callable[..., Any]) + +class AbstractResolver: + HOSTNAME_ENCODING: str + EAI_NONAME_MSG: str + EAI_FAMILY_MSG: str + def close(self) -> None: ... + @staticmethod + def fixup_gaierror(func: _F) -> _F: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... + +__all__ = () diff --git a/stubs/gevent/gevent/resolver/ares.pyi b/stubs/gevent/gevent/resolver/ares.pyi new file mode 100644 index 000000000000..ca16b3cf1dc1 --- /dev/null +++ b/stubs/gevent/gevent/resolver/ares.pyi @@ -0,0 +1,41 @@ +from collections.abc import Sequence +from typing import TypedDict, type_check_only + +from gevent._types import _Watcher +from gevent.hub import Hub +from gevent.resolver import AbstractResolver +from gevent.resolver.cares import channel + +@type_check_only +class _ChannelArgs(TypedDict): + flags: str | int | None + timeout: str | float | None + tries: str | int | None + ndots: str | int | None + udp_port: str | int | None + tcp_port: str | int | None + servers: Sequence[str] | str | None + +class Resolver(AbstractResolver): + cares_class: type[channel] + hub: Hub + cares: channel + pid: int + params: _ChannelArgs + fork_watcher: _Watcher + def __init__( + self, + hub: Hub | None = None, + use_environ: bool = True, + *, + flags: str | int | None = None, + timeout: str | float | None = None, + tries: str | int | None = None, + ndots: str | int | None = None, + udp_port: str | int | None = None, + tcp_port: str | int | None = None, + servers: Sequence[str] | str | None = None, + ) -> None: ... + def __del__(self) -> None: ... + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver/blocking.pyi b/stubs/gevent/gevent/resolver/blocking.pyi new file mode 100644 index 000000000000..54ee37b7ce31 --- /dev/null +++ b/stubs/gevent/gevent/resolver/blocking.pyi @@ -0,0 +1,15 @@ +from gevent._types import _AddrinfoResult, _NameinfoResult, _SockAddr +from gevent.hub import Hub + +class Resolver: + def __init__(self, hub: Hub | None = None) -> None: ... + def close(self) -> None: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver/cares.pyi b/stubs/gevent/gevent/resolver/cares.pyi new file mode 100644 index 000000000000..01dbe77d2e2c --- /dev/null +++ b/stubs/gevent/gevent/resolver/cares.pyi @@ -0,0 +1,52 @@ +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Generic, TypeVar +from typing_extensions import Self, disjoint_base + +from gevent._types import _AddrinfoResult, _Loop, _NameinfoResult, _SockAddr + +_T = TypeVar("_T") + +class ares_host_result(tuple[str, list[str], list[str]]): + family: int + def __new__(cls, family: int, iterable: Iterable[Any]) -> Self: ... + +@disjoint_base +class Result(Generic[_T]): + exception: BaseException | None + value: _T | None + def __init__(self, value: _T | None = None, exception: BaseException | None = None) -> None: ... + def get(self) -> Any | None: ... + def successful(self) -> bool: ... + +@disjoint_base +class channel: + @property + def loop(self) -> _Loop: ... + def __init__( + self, + loop: _Loop, + flags: str | int | None = None, + timeout: str | float | None = None, + tries: str | int | None = None, + ndots: str | int | None = None, + udp_port: str | int | None = None, + tcp_port: str | int | None = None, + servers: Sequence[str] | str | None = None, + ) -> None: ... + def destroy(self) -> None: ... + def getaddrinfo( + self, + callback: Callable[[Result[_AddrinfoResult]], object], + name: str, + service: str | None, + family: int = 0, + type: int = 0, + proto: int = 0, + flags: int = 0, + ) -> None: ... + def gethostbyaddr(self, callback: Callable[[Result[ares_host_result]], object], addr: str) -> Any: ... + def gethostbyname(self, callback: Callable[[Result[ares_host_result]], object], name: str, family: int = 2) -> None: ... + def getnameinfo(self, callback: Callable[[Result[_NameinfoResult]], object], sockaddr: _SockAddr, flags: int) -> None: ... + def set_servers(self, servers: Sequence[str] | str | None = None) -> None: ... + +__all__ = ["channel"] diff --git a/stubs/gevent/gevent/resolver/dnspython.pyi b/stubs/gevent/gevent/resolver/dnspython.pyi new file mode 100644 index 000000000000..cf965d10a2c9 --- /dev/null +++ b/stubs/gevent/gevent/resolver/dnspython.pyi @@ -0,0 +1,11 @@ +from typing import Any + +from gevent.hub import Hub +from gevent.resolver import AbstractResolver + +class Resolver(AbstractResolver): + def __init__(self, hub: Hub | None = ...) -> None: ... + @property + def resolver(self) -> Any: ... # this is a custom dnspython Resolver + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver/thread.pyi b/stubs/gevent/gevent/resolver/thread.pyi new file mode 100644 index 000000000000..3a265ed172c3 --- /dev/null +++ b/stubs/gevent/gevent/resolver/thread.pyi @@ -0,0 +1,17 @@ +from gevent._types import _AddrinfoResult, _NameinfoResult, _SockAddr +from gevent.hub import Hub +from gevent.threadpool import ThreadPool + +class Resolver: + pool: ThreadPool + def __init__(self, hub: Hub | None = None) -> None: ... + def close(self) -> None: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver_ares.pyi b/stubs/gevent/gevent/resolver_ares.pyi new file mode 100644 index 000000000000..4d1fbbaae20e --- /dev/null +++ b/stubs/gevent/gevent/resolver_ares.pyi @@ -0,0 +1,3 @@ +from gevent.resolver.ares import * + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver_thread.pyi b/stubs/gevent/gevent/resolver_thread.pyi new file mode 100644 index 000000000000..f960eab26073 --- /dev/null +++ b/stubs/gevent/gevent/resolver_thread.pyi @@ -0,0 +1,2 @@ +from gevent.resolver.thread import * +from gevent.resolver.thread import __all__ as __all__ diff --git a/stubs/gevent/gevent/select.pyi b/stubs/gevent/gevent/select.pyi new file mode 100644 index 000000000000..b1313ceda1b7 --- /dev/null +++ b/stubs/gevent/gevent/select.pyi @@ -0,0 +1,20 @@ +import sys +from _typeshed import FileDescriptorLike +from collections.abc import Iterable +from select import error as error +from typing import Any + +def select( + rlist: Iterable[Any], wlist: Iterable[Any], xlist: Iterable[Any], timeout: float | None = None +) -> tuple[list[Any], list[Any], list[Any]]: ... + +if sys.platform != "win32": + __all__ = ["error", "poll", "select"] +else: + __all__ = ["error", "select"] + +class poll: + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... + def poll(self, timeout: float | None = None) -> list[tuple[int, int]]: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... diff --git a/stubs/gevent/gevent/selectors.pyi b/stubs/gevent/gevent/selectors.pyi new file mode 100644 index 000000000000..12614ef1e6ff --- /dev/null +++ b/stubs/gevent/gevent/selectors.pyi @@ -0,0 +1,24 @@ +from _typeshed import FileDescriptorLike +from collections.abc import Mapping +from selectors import BaseSelector, SelectorKey +from typing import Any + +from gevent._util import Lazy +from gevent.hub import Hub + +__all__ = ["DefaultSelector", "GeventSelector"] + +# technically this derives from _BaseSelectorImpl, which does not have type annotations +# but in terms of type checking the only difference is, that we need to add get_map since +# GeventSelector does not override it +class GeventSelector(BaseSelector): + def __init__(self, hub: Hub | None = None) -> None: ... + @Lazy + def hub(self) -> Hub: ... + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + def close(self) -> None: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +DefaultSelector = GeventSelector diff --git a/stubs/gevent/gevent/server.pyi b/stubs/gevent/gevent/server.pyi new file mode 100644 index 000000000000..8f8306684052 --- /dev/null +++ b/stubs/gevent/gevent/server.pyi @@ -0,0 +1,89 @@ +from _socket import _Address as _StrictAddress +from _typeshed import ReadableBuffer, StrOrBytesPath +from collections.abc import Callable +from typing import Any, ClassVar, TypeAlias, TypedDict, overload, type_check_only + +from gevent.baseserver import BaseServer, _Spawner +from gevent.socket import socket as _GeventSocket +from gevent.ssl import SSLContext, wrap_socket as ssl_wrap_socket + +# For simplicity we treat _Address as Any, we could be more strict and use the definition +# from the stdlib _socket.pyi. But that would exclude some potentially valid handlers. +_Address: TypeAlias = Any + +@type_check_only +class _SSLArguments(TypedDict, total=False): + keyfile: StrOrBytesPath + certfile: StrOrBytesPath + server_side: bool + cert_reqs: int + ssl_version: int + ca_certs: str + suppress_ragged_eofs: bool + do_handshake_on_connect: bool + ciphers: str + +class StreamServer(BaseServer[_GeventSocket, _Address]): + backlog: int + reuse_addr: ClassVar[int | None] + wrap_socket = ssl_wrap_socket + ssl_args: _SSLArguments | None + + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[_GeventSocket, _Address], object] | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + *, + ssl_context: SSLContext, + server_side: bool = True, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ) -> None: ... + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[_GeventSocket, _Address], object] | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + *, + keyfile: StrOrBytesPath = ..., + certfile: StrOrBytesPath = ..., + server_side: bool = True, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str = ..., + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str = ..., + ) -> None: ... + + @property + def ssl_enabled(self) -> bool: ... + @classmethod + def get_listener(cls, address: _StrictAddress, backlog: int | None = None, family: int | None = None) -> _GeventSocket: ... + def do_read(self) -> tuple[_GeventSocket, _Address]: ... + def do_close(self, sock: _GeventSocket, address: _Address) -> None: ... + def wrap_socket_and_handle(self, client_socket: _GeventSocket, address: _StrictAddress) -> Any: ... + +class DatagramServer(BaseServer[_GeventSocket, _Address]): + reuse_addr: ClassVar[int | None] + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[_GeventSocket, _Address], object] | None = None, + spawn: _Spawner = "default", + ) -> None: ... + @classmethod + def get_listener(cls, address: _StrictAddress, family: int | None = None) -> _GeventSocket: ... + def do_read(self) -> tuple[_GeventSocket, _Address]: ... + + @overload + def sendto(self, data: ReadableBuffer, address: _StrictAddress, /) -> int: ... + @overload + def sendto(self, data: ReadableBuffer, flags: int, address: _StrictAddress, /) -> int: ... + +__all__ = ["StreamServer", "DatagramServer"] diff --git a/stubs/gevent/gevent/signal.pyi b/stubs/gevent/gevent/signal.pyi new file mode 100644 index 000000000000..66d277ac680a --- /dev/null +++ b/stubs/gevent/gevent/signal.pyi @@ -0,0 +1,13 @@ +import sys +from signal import _HANDLER, _SIGNUM + +# technically the implementations will always be around, but since they always +# throw an exception on windows, due to the missing SIGCHLD, we might as well +# pretent they don't exist, but what is different, is that the parameters are +# named even pre 3.10, so we don't just import the symbol from stdlib signal +if sys.platform != "win32": + def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... + def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... + def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = True) -> int: ... + + __all__ = ["signal", "getsignal", "set_wakeup_fd"] diff --git a/stubs/gevent/gevent/socket.pyi b/stubs/gevent/gevent/socket.pyi new file mode 100644 index 000000000000..ccfc9a4c6f2c --- /dev/null +++ b/stubs/gevent/gevent/socket.pyi @@ -0,0 +1,23 @@ +from socket import * + +from gevent._hub_primitives import ( + wait_on_watcher, + wait_read as wait_read, + wait_readwrite as wait_readwrite, + wait_write as wait_write, +) +from gevent._types import _Watcher + +# This matches the stdlib socket module almost exactly, but contains a couple of extensions +# as a result we just pretend we import everything from socket, which is not entirely correct +# but it gets us most of the way there without having to write a really long list of imports +# with the same platform and version checks, just so we can properly distinguish this module's +# socket class from the native socket class (which could cause issues anyways, since functions +# that accept a socket should still accept the gevent implementation...) +# we can put in the work and do it properly once we have a use-case for it. +# the majority of the gevent implementation can be found in _socket3 and _socketcommon +# which also just imports a lot of symbols from the stdlib socket/_socket module + +wait = wait_on_watcher + +def cancel_wait(watcher: _Watcher, error: type[BaseException] | BaseException) -> None: ... diff --git a/stubs/gevent/gevent/ssl.pyi b/stubs/gevent/gevent/ssl.pyi new file mode 100644 index 000000000000..a8acf2abdaf5 --- /dev/null +++ b/stubs/gevent/gevent/ssl.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import StrOrBytesPath +from ssl import * + +import gevent.socket + +# for simplicity we trust that gevent's implementation matches the stdlib version exactly +# for the most part they just copy all the symbols anyways and re-implment the few that +# need to work differently. The only potentially problematic symbol is SSLSocket, since +# it derives from gevent's socket, rather than the stdlib one. SSLContext derives from +# the stdlib SSLContext. Since we already punted on socket, we don't need to change +# anything here either, until we decide that we can't punt on socket. + +if sys.version_info >= (3, 12): + # FIXME: wrap_socket has been removed in 3.12, gevent implements its own, so it + # will probably still be there in 3.12, but until we stub out gevent.ssl + # properly we will have to just pretend it still exists + def wrap_socket( + sock: gevent.socket.socket, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + server_side: bool = False, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str | None = None, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str | None = None, + ) -> SSLSocket: ... diff --git a/stubs/gevent/gevent/subprocess.pyi b/stubs/gevent/gevent/subprocess.pyi new file mode 100644 index 000000000000..8f4c048ba1e0 --- /dev/null +++ b/stubs/gevent/gevent/subprocess.pyi @@ -0,0 +1,4 @@ +from subprocess import * + +# this is another module we decide to just punt on and trust that gevent's implementation +# at the very least satisfies the stdlib interface. diff --git a/stubs/gevent/gevent/threadpool.pyi b/stubs/gevent/gevent/threadpool.pyi new file mode 100644 index 000000000000..22f71e18256b --- /dev/null +++ b/stubs/gevent/gevent/threadpool.pyi @@ -0,0 +1,71 @@ +import concurrent.futures +from collections.abc import Callable +from typing import Any, Generic, ParamSpec, TypeAlias, TypeVar + +from gevent._threading import Queue +from gevent._types import _AsyncWatcher, _Watcher +from gevent.event import AsyncResult, _OptExcInfo, _ValueSource +from gevent.greenlet import Greenlet +from gevent.hub import Hub +from gevent.pool import GroupMappingMixin + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_TaskItem: TypeAlias = tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any], ThreadResult[Any]] +_Receiver: TypeAlias = Callable[[_ValueSource[_T]], object] + +class ThreadPool(GroupMappingMixin): + __slots__ = ( + "hub", + "_maxsize", + "manager", + "pid", + "fork_watcher", + "_available_worker_threads_greenlet_sem", + "_worker_greenlets", + "task_queue", + "_idle_task_timeout", + ) + hub: Hub + pid: int + manager: Greenlet[..., Any] | None + task_queue: Queue[_TaskItem] + fork_watcher: _Watcher + def __init__(self, maxsize: int, hub: Hub | None = None, idle_task_timeout: int = -1) -> None: ... + + @property + def maxsize(self) -> int: ... + @maxsize.setter + def maxsize(self, value: int) -> None: ... + + @property + def size(self) -> int: ... + @size.setter + def size(self, value: int) -> None: ... + + def __len__(self) -> int: ... + def join(self) -> None: ... + def kill(self) -> None: ... + def adjust(self) -> None: ... + def spawn(self, func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> AsyncResult[_T]: ... # type: ignore[override] + +class ThreadResult(Generic[_T]): + __slots__ = ("exc_info", "async_watcher", "_call_when_ready", "value", "context", "hub", "receiver") + receiver: _Receiver[_T] + hub: Hub + context: object | None + value: _T | None + exc_info: _OptExcInfo | tuple[()] + async_watcher: _AsyncWatcher + def __init__(self, receiver: _Receiver[_T], hub: Hub, call_when_ready: Callable[[], object]) -> None: ... + @property + def exception(self) -> BaseException | None: ... + def destroy_in_main_thread(self) -> None: ... + def set(self, value: _T) -> None: ... + def handle_error(self, context: object, exc_info: _OptExcInfo) -> None: ... + def successful(self) -> bool: ... + +class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor): + kill = concurrent.futures.ThreadPoolExecutor.shutdown + +__all__ = ["ThreadPool", "ThreadResult", "ThreadPoolExecutor"] diff --git a/stubs/gevent/gevent/time.pyi b/stubs/gevent/gevent/time.pyi new file mode 100644 index 000000000000..7bd856892efd --- /dev/null +++ b/stubs/gevent/gevent/time.pyi @@ -0,0 +1,3 @@ +from gevent.hub import sleep as sleep + +__all__ = ["sleep"] diff --git a/stubs/gevent/gevent/timeout.pyi b/stubs/gevent/gevent/timeout.pyi new file mode 100644 index 000000000000..413d605350ce --- /dev/null +++ b/stubs/gevent/gevent/timeout.pyi @@ -0,0 +1,60 @@ +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, ParamSpec, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self + +from gevent._types import _TimerWatcher + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_TimeoutT = TypeVar("_TimeoutT", bound=Timeout) +_P = ParamSpec("_P") + +@type_check_only +class _HasSeconds(Protocol): + @property + def seconds(self) -> float | int: ... + +class Timeout(BaseException): + seconds: float | None + exception: type[BaseException] | BaseException | None + timer: _TimerWatcher + def __init__( + self, + seconds: float | None = None, + exception: type[BaseException] | BaseException | None = None, + ref: bool = True, + priority: int = -1, + ) -> None: ... + def start(self) -> None: ... + + @overload + @classmethod + def start_new( + cls, timeout: float | None = None, exception: type[BaseException] | BaseException | None = None, ref: bool = True + ) -> Self: ... + @overload + @classmethod + def start_new(cls, timeout: _TimeoutT) -> _TimeoutT: ... + + @property + def pending(self) -> bool: ... + def cancel(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> Literal[True] | None: ... + def __lt__(self, other: _HasSeconds | float) -> bool: ... + +# when timeout_value is provided we unfortunately get no type checking on *args, **kwargs, because +# ParamSpec does not allow mixing in additional keyword arguments +@overload +def with_timeout( + seconds: float | None, function: Callable[..., _T1], *args: Any, timeout_value: _T2, **kwds: Any +) -> _T1 | _T2: ... +@overload +def with_timeout(seconds: float | None, function: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T: ... + +__all__ = ["Timeout", "with_timeout"] diff --git a/stubs/gevent/gevent/util.pyi b/stubs/gevent/gevent/util.pyi new file mode 100644 index 000000000000..d0fce9863178 --- /dev/null +++ b/stubs/gevent/gevent/util.pyi @@ -0,0 +1,51 @@ +from _typeshed import SupportsWrite +from collections.abc import Callable +from types import TracebackType +from typing import Any, Generic, ParamSpec, TypeVar +from typing_extensions import Self + +from gevent.hub import Hub +from greenlet import greenlet as greenlet_t + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +class wrap_errors(Generic[_P, _T]): + def __init__(self, errors: tuple[type[BaseException], ...], func: Callable[_P, _T]) -> None: ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: ... + def __getattr__(self, name: str) -> Any: ... + +def print_run_info( + thread_stacks: bool = True, greenlet_stacks: bool = True, limit: int | None = ..., file: SupportsWrite[str] | None = None +) -> None: ... +def format_run_info( + thread_stacks: bool = True, greenlet_stacks: bool = True, limit: int | None = ..., current_thread_ident: int | None = None +) -> None: ... + +class GreenletTree: + greenlet: greenlet_t | None + is_current_tree: bool + child_trees: list[GreenletTree] + DEFAULT_DETAILS: dict[str, Any] + def __init__(self, greenlet: greenlet_t | None) -> None: ... + def add_child(self, tree: GreenletTree) -> None: ... + @property + def root(self) -> bool: ... + def __getattr__(self, name: str) -> Any: ... + def format_lines(self, details: bool | dict[str, Any] = True) -> str: ... + def format(self, details: bool | dict[str, Any] = True) -> str: ... + @classmethod + def forest(cls) -> list[GreenletTree]: ... + @classmethod + def current_tree(cls) -> GreenletTree: ... + +class assert_switches: + hub: Hub | None + tracer: object | None + max_blocking_time: float | None + hub_only: bool + def __init__(self, max_blocking_time: float | None = None, hub_only: bool = False) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +__all__ = ["format_run_info", "print_run_info", "GreenletTree", "wrap_errors", "assert_switches"] diff --git a/stubs/gevent/gevent/win32util.pyi b/stubs/gevent/gevent/win32util.pyi new file mode 100644 index 000000000000..e6fc566ee52c --- /dev/null +++ b/stubs/gevent/gevent/win32util.pyi @@ -0,0 +1,5 @@ +from collections.abc import Callable + +formatError: Callable[[object], str] + +__all__ = ["formatError"] diff --git a/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt b/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt index a67cb1a30510..cdb920843ba3 100644 --- a/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt +++ b/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt @@ -1,4 +1,3 @@ # inconsistency of signatures between stub and implementation (cls vs self) -google.cloud.ndb.ModelAdapter.__new__ google.cloud.ndb.metadata.EntityGroup.__new__ google.cloud.ndb.model.ModelAdapter.__new__ diff --git a/stubs/google-cloud-ndb/METADATA.toml b/stubs/google-cloud-ndb/METADATA.toml index 971cc4a0f9b2..fb13602f4b47 100644 --- a/stubs/google-cloud-ndb/METADATA.toml +++ b/stubs/google-cloud-ndb/METADATA.toml @@ -1,2 +1,6 @@ -version = "1.9.*" -requires = ["types-six"] +version = "2.4.*" +upstream-repository = "https://github.com/googleapis/python-ndb" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi index 3fb429e6e962..39c67d5ae96d 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi @@ -107,3 +107,112 @@ from google.cloud.ndb.tasklets import ( wait_all as wait_all, wait_any as wait_any, ) +from google.cloud.ndb.version import __version__ as __version__ + +__all__ = [ + "__version__", + "AutoBatcher", + "Client", + "Context", + "ContextOptions", + "EVENTUAL", + "EVENTUAL_CONSISTENCY", + "STRONG", + "TransactionOptions", + "Key", + "BlobKey", + "BlobKeyProperty", + "BlobProperty", + "BooleanProperty", + "ComputedProperty", + "ComputedPropertyError", + "DateProperty", + "DateTimeProperty", + "delete_multi", + "delete_multi_async", + "Expando", + "FloatProperty", + "GenericProperty", + "GeoPt", + "GeoPtProperty", + "get_indexes", + "get_indexes_async", + "get_multi", + "get_multi_async", + "GlobalCache", + "in_transaction", + "Index", + "IndexProperty", + "IndexState", + "IntegerProperty", + "InvalidPropertyError", + "BadProjectionError", + "JsonProperty", + "KeyProperty", + "KindError", + "LocalStructuredProperty", + "make_connection", + "MemcacheCache", + "MetaModel", + "Model", + "ModelAdapter", + "ModelAttribute", + "ModelKey", + "non_transactional", + "PickleProperty", + "PolyModel", + "Property", + "put_multi", + "put_multi_async", + "ReadonlyPropertyError", + "RedisCache", + "Rollback", + "StringProperty", + "StructuredProperty", + "TextProperty", + "TimeProperty", + "transaction", + "transaction_async", + "transactional", + "transactional_async", + "transactional_tasklet", + "UnprojectedPropertyError", + "User", + "UserNotFoundError", + "UserProperty", + "ConjunctionNode", + "AND", + "Cursor", + "DisjunctionNode", + "OR", + "FalseNode", + "FilterNode", + "gql", + "Node", + "Parameter", + "ParameterizedFunction", + "ParameterizedThing", + "ParameterNode", + "PostFilterNode", + "Query", + "QueryIterator", + "QueryOptions", + "RepeatedStructuredPropertyPredicate", + "add_flow_exception", + "Future", + "get_context", + "get_toplevel_context", + "make_context", + "make_default_context", + "QueueFuture", + "ReducingFuture", + "Return", + "SerialQueueFuture", + "set_context", + "sleep", + "synctasklet", + "tasklet", + "toplevel", + "wait_all", + "wait_any", +] diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi index 0f50383e9b04..79e0c3ded8dd 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi @@ -1,3 +1 @@ -from typing import Any - -def get_batch(batch_cls, options: Any | None = ...): ... +def get_batch(batch_cls, options=None): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi index dd86c584e048..cf28a3450640 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete from google.cloud.ndb import tasklets as tasklets @@ -12,49 +12,49 @@ class _GlobalCacheBatch: def make_call(self) -> None: ... def future_info(self, key) -> None: ... -global_get: Any +global_get: Incomplete class _GlobalCacheGetBatch(_GlobalCacheBatch): - todo: Any - keys: Any + todo: Incomplete + keys: Incomplete def __init__(self, ignore_options) -> None: ... def add(self, key): ... def done_callback(self, cache_call) -> None: ... def make_call(self): ... def future_info(self, key): ... -def global_set(key, value, expires: Any | None = ..., read: bool = ...): ... +def global_set(key, value, expires=None, read: bool = False): ... class _GlobalCacheSetBatch(_GlobalCacheBatch): - expires: Any + expires: Incomplete todo: object futures: object def __init__(self, options) -> None: ... def done_callback(self, cache_call) -> None: ... def add(self, key, value): ... def make_call(self): ... - def future_info(self, key, value): ... + def future_info(self, key, value): ... # type: ignore[override] class _GlobalCacheSetIfNotExistsBatch(_GlobalCacheSetBatch): def add(self, key, value): ... def make_call(self): ... - def future_info(self, key, value): ... + def future_info(self, key, value): ... # type: ignore[override] -global_delete: Any +global_delete: Incomplete class _GlobalCacheDeleteBatch(_GlobalCacheBatch): - keys: Any - futures: Any + keys: Incomplete + futures: Incomplete def __init__(self, ignore_options) -> None: ... def add(self, key): ... def make_call(self): ... def future_info(self, key): ... -global_watch: Any +global_watch: Incomplete class _GlobalCacheWatchBatch(_GlobalCacheDeleteBatch): def make_call(self): ... - def future_info(self, key): ... + def future_info(self, key, value): ... # type: ignore[override] def global_unwatch(key): ... @@ -62,11 +62,11 @@ class _GlobalCacheUnwatchBatch(_GlobalCacheDeleteBatch): def make_call(self): ... def future_info(self, key): ... -global_compare_and_swap: Any +global_compare_and_swap: Incomplete class _GlobalCacheCompareAndSwapBatch(_GlobalCacheSetBatch): def make_call(self): ... - def future_info(self, key, value): ... + def future_info(self, key, value): ... # type: ignore[override] def is_locked_value(value): ... def global_cache_key(key): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi index 67b9641d6080..e1dda8111460 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi @@ -1,4 +1,4 @@ -from typing_extensions import Literal +from typing import Literal EVENTUAL: Literal[2] EVENTUAL_CONSISTENCY: Literal[2] diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi index c199db49696d..95574c737ea1 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete class QueryIterator: def __iter__(self): ... @@ -13,10 +13,10 @@ class QueryIterator: class Cursor: @classmethod def from_websafe_string(cls, urlsafe): ... - cursor: Any - def __init__(self, cursor: Any | None = ..., urlsafe: Any | None = ...) -> None: ... + cursor: Incomplete + def __init__(self, cursor=None, urlsafe=None) -> None: ... def to_websafe_string(self): ... def urlsafe(self): ... def __eq__(self, other): ... def __ne__(self, other): ... - def __hash__(self): ... + def __hash__(self) -> int: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi index 2c80cd3751c1..47091d2d3915 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi @@ -1,18 +1,19 @@ -from typing import Any, NamedTuple +from _typeshed import Incomplete +from typing import NamedTuple class _Event(NamedTuple): - when: Any - callback: Any - args: Any - kwargs: Any + when: Incomplete + callback: Incomplete + args: Incomplete + kwargs: Incomplete class EventLoop: - current: Any - idlers: Any + current: Incomplete + idlers: Incomplete inactive: int - queue: Any - rpcs: Any - rpc_results: Any + queue: Incomplete + rpcs: Incomplete + rpc_results: Incomplete def __init__(self) -> None: ... def clear(self) -> None: ... def insort_event_right(self, event) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi index 153e041a5889..768eb779c961 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi @@ -1,15 +1,28 @@ -from typing import Any - class Options: + __slots__ = ( + "retries", + "timeout", + "use_cache", + "use_global_cache", + "global_cache_timeout", + "use_datastore", + "force_writes", + "max_memcache_items", + "propagation", + "deadline", + "use_memcache", + "memcache_timeout", + ) @classmethod - def options(cls, wrapped): ... + def options(cls, wrapped, _disambiguate_from_model_properties: bool = False): ... @classmethod def slots(cls): ... - def __init__(self, config: Any | None = ..., **kwargs) -> None: ... + def __init__(self, config=None, **kwargs) -> None: ... def __eq__(self, other): ... def __ne__(self, other): ... def copy(self, **kwargs): ... def items(self) -> None: ... class ReadOptions(Options): - def __init__(self, config: Any | None = ..., **kwargs) -> None: ... + __slots__ = ("read_consistency", "read_policy", "transaction") + def __init__(self, config=None, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi index c3dc5a4738d2..c25cb8779bc3 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi @@ -1,18 +1,8 @@ -from typing import Any - def in_transaction(): ... -def transaction( - callback, retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Any | None = ... -): ... -def transaction_async( - callback, retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Any | None = ... -): ... -def transaction_async_( - callback, retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Any | None = ... -): ... -def transactional(retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Any | None = ...): ... -def transactional_async(retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Any | None = ...): ... -def transactional_tasklet( - retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Any | None = ... -): ... -def non_transactional(allow_existing: bool = ...): ... +def transaction(callback, retries=..., read_only: bool = False, join: bool = False, xg: bool = True, propagation=None): ... +def transaction_async(callback, retries=..., read_only: bool = False, join: bool = False, xg: bool = True, propagation=None): ... +def transaction_async_(callback, retries=..., read_only: bool = False, join: bool = False, xg: bool = True, propagation=None): ... +def transactional(retries=..., read_only: bool = False, join: bool = True, xg: bool = True, propagation=None): ... +def transactional_async(retries=..., read_only: bool = False, join: bool = True, xg: bool = True, propagation=None): ... +def transactional_tasklet(retries=..., read_only: bool = False, join: bool = True, xg: bool = True, propagation=None): ... +def non_transactional(allow_existing: bool = True): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi index acb002aadcec..8db54d2a1908 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi @@ -1,8 +1,8 @@ -from typing import Any +from _typeshed import Incomplete from google.cloud.ndb import model -BlobKey: Any +BlobKey: Incomplete BLOB_INFO_KIND: str BLOB_MIGRATION_KIND: str BLOB_KEY_HEADER: str @@ -51,10 +51,10 @@ class Error: def fetch_data(*args, **kwargs) -> None: ... def fetch_data_async(*args, **kwargs) -> None: ... -get: Any -get_async: Any -get_multi: Any -get_multi_async: Any +get: Incomplete +get_async: Incomplete +get_multi: Incomplete +get_multi_async: Incomplete class InternalError: def __init__(self, *args, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi index 207673ea13a2..d9b28a4e571b 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi @@ -1,21 +1,35 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable, Generator +from contextlib import contextmanager +from typing import ClassVar -DATASTORE_API_HOST: Any +from google.cloud.ndb import context as context_module, key + +DATASTORE_API_HOST: str class Client: - SCOPE: Any - namespace: Any - host: Any - client_info: Any - secure: Any - stub: Any - def __init__(self, project: Any | None = ..., namespace: Any | None = ..., credentials: Any | None = ...) -> None: ... + SCOPE: ClassVar[tuple[str, ...]] + namespace: str | None + host: str + client_info: Incomplete + secure: bool + stub: Incomplete + database: str | None + def __init__( + self, + project: str | None = None, + namespace: str | None = None, + credentials=None, + client_options=None, + database: str | None = None, + ) -> None: ... + @contextmanager def context( self, namespace=..., - cache_policy: Any | None = ..., - global_cache: Any | None = ..., - global_cache_policy: Any | None = ..., - global_cache_timeout_policy: Any | None = ..., - legacy_data: bool = ..., - ) -> None: ... + cache_policy: Callable[[key.Key], bool] | None = None, + global_cache=None, + global_cache_policy: Callable[[key.Key], bool] | None = None, + global_cache_timeout_policy: Callable[[key.Key], int] | None = None, + legacy_data: bool = True, + ) -> Generator[context_module.Context]: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi index bb3538fab21c..6889e9304bb9 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi @@ -1,54 +1,61 @@ -from typing import Any, Callable, NamedTuple +from _typeshed import Incomplete +from collections.abc import Callable +from typing import NamedTuple from google.cloud.ndb import Key, exceptions as exceptions class _LocalState: def __init__(self) -> None: ... + @property def context(self): ... @context.setter def context(self, value) -> None: ... + @property def toplevel_context(self): ... @toplevel_context.setter def toplevel_context(self, value) -> None: ... -def get_context(raise_context_error: bool = ...): ... -def get_toplevel_context(raise_context_error: bool = ...): ... +def get_context(raise_context_error: bool = True): ... +def get_toplevel_context(raise_context_error: bool = True): ... class _ContextTuple(NamedTuple): - client: Any - namespace: Any - eventloop: Any - batches: Any - commit_batches: Any - transaction: Any - cache: Any - global_cache: Any - on_commit_callbacks: Any - legacy_data: Any + id: Incomplete + client: Incomplete + namespace: Incomplete + eventloop: Incomplete + batches: Incomplete + commit_batches: Incomplete + transaction: Incomplete + cache: Incomplete + global_cache: Incomplete + on_commit_callbacks: Incomplete + transaction_complete_callbacks: Incomplete + legacy_data: Incomplete class _Context(_ContextTuple): def __new__( cls, client, + id=None, namespace=..., - eventloop: Any | None = ..., - batches: Any | None = ..., - commit_batches: Any | None = ..., - transaction: Any | None = ..., - cache: Any | None = ..., - cache_policy: Any | None = ..., - global_cache: Any | None = ..., - global_cache_flush_keys: object | None = ..., - global_cache_policy: Callable[[Key], bool] | None = ..., - global_cache_timeout_policy: Any | None = ..., - datastore_policy: Any | None = ..., - on_commit_callbacks: Any | None = ..., - legacy_data: bool = ..., - retry: Any | None = ..., - rpc_time: Any | None = ..., - wait_time: Any | None = ..., + eventloop=None, + batches=None, + commit_batches=None, + transaction=None, + cache=None, + cache_policy=None, + global_cache=None, + global_cache_policy: Callable[[Key], bool] | None = None, + global_cache_timeout_policy=None, + datastore_policy=None, + on_commit_callbacks=None, + transaction_complete_callbacks=None, + legacy_data: bool = True, + retry=None, + rpc_time=None, + wait_time=None, ): ... def new(self, **kwargs): ... rpc_time: int @@ -62,19 +69,19 @@ class Context(_Context): def get_cache_policy(self): ... def get_datastore_policy(self) -> None: ... def get_global_cache_policy(self): ... - get_memcache_policy: Any + get_memcache_policy: Incomplete def get_global_cache_timeout_policy(self): ... - get_memcache_timeout_policy: Any - cache_policy: Any + get_memcache_timeout_policy: Incomplete + cache_policy: Incomplete def set_cache_policy(self, policy): ... - datastore_policy: Any + datastore_policy: Incomplete def set_datastore_policy(self, policy): ... - global_cache_policy: Any + global_cache_policy: Incomplete def set_global_cache_policy(self, policy): ... - set_memcache_policy: Any - global_cache_timeout_policy: Any + set_memcache_policy: Incomplete + global_cache_timeout_policy: Incomplete def set_global_cache_timeout_policy(self, policy): ... - set_memcache_timeout_policy: Any + set_memcache_timeout_policy: Incomplete def get_retry_state(self): ... def set_retry_state(self, state) -> None: ... def clear_retry_state(self) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi index ab5a3a0ae0b2..c575423699d3 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete class Error(Exception): ... @@ -12,7 +12,7 @@ class Rollback(Error): ... class BadQueryError(Error): ... class BadFilterError(Error): - filter: Any + filter: Incomplete def __init__(self, filter) -> None: ... class NoLongerImplementedError(NotImplementedError): diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi index bcc4aa155703..976003bf9711 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi @@ -1,75 +1,77 @@ import abc -from typing import Any +from _typeshed import Incomplete +from typing_extensions import Self -ConnectionError: Any +ConnectionError: Incomplete class GlobalCache(metaclass=abc.ABCMeta): - __metaclass__: Any - transient_errors: Any + __metaclass__: Incomplete + transient_errors: Incomplete strict_read: bool strict_write: bool @abc.abstractmethod def get(self, keys): ... @abc.abstractmethod - def set(self, items, expires: Any | None = ...): ... + def set(self, items, expires=None): ... @abc.abstractmethod def delete(self, keys): ... @abc.abstractmethod - def watch(self, keys): ... + def watch(self, items): ... @abc.abstractmethod def unwatch(self, keys): ... @abc.abstractmethod - def compare_and_swap(self, items, expires: Any | None = ...): ... + def compare_and_swap(self, items, expires=None): ... @abc.abstractmethod def clear(self): ... class _InProcessGlobalCache(GlobalCache): - cache: Any + cache: Incomplete def __init__(self) -> None: ... def get(self, keys): ... - def set(self, items, expires: Any | None = ...) -> None: ... + def set(self, items, expires=None) -> None: ... def delete(self, keys) -> None: ... - def watch(self, keys) -> None: ... + def watch(self, items) -> None: ... def unwatch(self, keys) -> None: ... - def compare_and_swap(self, items, expires: Any | None = ...): ... + def compare_and_swap(self, items, expires=None): ... def clear(self) -> None: ... class RedisCache(GlobalCache): - transient_errors: Any + transient_errors: Incomplete @classmethod - def from_environment(cls, strict_read: bool = ..., strict_write: bool = ...): ... - redis: Any - strict_read: Any - strict_write: Any - def __init__(self, redis, strict_read: bool = ..., strict_write: bool = ...) -> None: ... + def from_environment(cls, strict_read: bool = False, strict_write: bool = True) -> Self: ... + redis: Incomplete + strict_read: Incomplete + strict_write: Incomplete + def __init__(self, redis, strict_read: bool = False, strict_write: bool = True) -> None: ... @property def pipes(self): ... def get(self, keys): ... - def set(self, items, expires: Any | None = ...) -> None: ... + def set(self, items, expires=None) -> None: ... def delete(self, keys) -> None: ... - def watch(self, keys) -> None: ... + def watch(self, items) -> None: ... def unwatch(self, keys) -> None: ... - def compare_and_swap(self, items, expires: Any | None = ...): ... + def compare_and_swap(self, items, expires=None): ... def clear(self) -> None: ... class MemcacheCache(GlobalCache): class KeyNotSet(Exception): - key: Any + key: Incomplete def __init__(self, key) -> None: ... def __eq__(self, other): ... - transient_errors: Any + + transient_errors: Incomplete @classmethod - def from_environment(cls, max_pool_size: int = ..., strict_read: bool = ..., strict_write: bool = ...): ... - client: Any - strict_read: Any - strict_write: Any - def __init__(self, client, strict_read: bool = ..., strict_write: bool = ...) -> None: ... + def from_environment(cls, max_pool_size: int = 4, strict_read: bool = False, strict_write: bool = True) -> Self: ... + client: Incomplete + strict_read: Incomplete + strict_write: Incomplete + def __init__(self, client, strict_read: bool = False, strict_write: bool = True) -> None: ... @property def caskeys(self): ... def get(self, keys): ... - def set(self, items, expires: Any | None = ...): ... + def set(self, items, expires=None): ... def delete(self, keys) -> None: ... - def watch(self, keys) -> None: ... + def watch(self, items) -> None: ... def unwatch(self, keys) -> None: ... - def compare_and_swap(self, items, expires: Any | None = ...): ... + def compare_and_swap(self, items, expires=None): ... def clear(self) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi index 6a9896e3d032..07abf9236341 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi @@ -1,10 +1,10 @@ -from typing import Any +from _typeshed import Incomplete -UNDEFINED: Any +UNDEFINED: Incomplete class Key: def __new__(cls, *path_args, **kwargs): ... - def __hash__(self): ... + def __hash__(self) -> int: ... def __eq__(self, other): ... def __ne__(self, other): ... def __lt__(self, other): ... @@ -16,7 +16,8 @@ class Key: def root(self): ... def namespace(self): ... def project(self): ... - app: Any + app: Incomplete + def database(self) -> str | None: ... def id(self): ... def string_id(self): ... def integer_id(self): ... @@ -29,69 +30,69 @@ class Key: def to_legacy_urlsafe(self, location_prefix): ... def get( self, - read_consistency: Any | None = ..., - read_policy: Any | None = ..., - transaction: Any | None = ..., - retries: Any | None = ..., - timeout: Any | None = ..., - deadline: Any | None = ..., - use_cache: Any | None = ..., - use_global_cache: Any | None = ..., - use_datastore: Any | None = ..., - global_cache_timeout: Any | None = ..., - use_memcache: Any | None = ..., - memcache_timeout: Any | None = ..., - max_memcache_items: Any | None = ..., - force_writes: Any | None = ..., - _options: Any | None = ..., + read_consistency=None, + read_policy=None, + transaction=None, + retries=None, + timeout=None, + deadline=None, + use_cache=None, + use_global_cache=None, + use_datastore=None, + global_cache_timeout=None, + use_memcache=None, + memcache_timeout=None, + max_memcache_items=None, + force_writes=None, + _options=None, ): ... def get_async( self, - read_consistency: Any | None = ..., - read_policy: Any | None = ..., - transaction: Any | None = ..., - retries: Any | None = ..., - timeout: Any | None = ..., - deadline: Any | None = ..., - use_cache: Any | None = ..., - use_global_cache: Any | None = ..., - use_datastore: Any | None = ..., - global_cache_timeout: Any | None = ..., - use_memcache: Any | None = ..., - memcache_timeout: Any | None = ..., - max_memcache_items: Any | None = ..., - force_writes: Any | None = ..., - _options: Any | None = ..., + read_consistency=None, + read_policy=None, + transaction=None, + retries=None, + timeout=None, + deadline=None, + use_cache=None, + use_global_cache=None, + use_datastore=None, + global_cache_timeout=None, + use_memcache=None, + memcache_timeout=None, + max_memcache_items=None, + force_writes=None, + _options=None, ): ... def delete( self, - retries: Any | None = ..., - timeout: Any | None = ..., - deadline: Any | None = ..., - use_cache: Any | None = ..., - use_global_cache: Any | None = ..., - use_datastore: Any | None = ..., - global_cache_timeout: Any | None = ..., - use_memcache: Any | None = ..., - memcache_timeout: Any | None = ..., - max_memcache_items: Any | None = ..., - force_writes: Any | None = ..., - _options: Any | None = ..., + retries=None, + timeout=None, + deadline=None, + use_cache=None, + use_global_cache=None, + use_datastore=None, + global_cache_timeout=None, + use_memcache=None, + memcache_timeout=None, + max_memcache_items=None, + force_writes=None, + _options=None, ): ... def delete_async( self, - retries: Any | None = ..., - timeout: Any | None = ..., - deadline: Any | None = ..., - use_cache: Any | None = ..., - use_global_cache: Any | None = ..., - use_datastore: Any | None = ..., - global_cache_timeout: Any | None = ..., - use_memcache: Any | None = ..., - memcache_timeout: Any | None = ..., - max_memcache_items: Any | None = ..., - force_writes: Any | None = ..., - _options: Any | None = ..., + retries=None, + timeout=None, + deadline=None, + use_cache=None, + use_global_cache=None, + use_datastore=None, + global_cache_timeout=None, + use_memcache=None, + memcache_timeout=None, + max_memcache_items=None, + force_writes=None, + _options=None, ): ... @classmethod def from_old_key(cls, old_key) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi index 6c8d3392476f..564a4d6f04b7 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete from google.cloud.ndb import model @@ -31,7 +31,7 @@ class Property(_BaseMetadata): def property_name(self): ... @property def kind_name(self): ... - property_representation: Any + property_representation: Incomplete @classmethod def key_for_kind(cls, kind): ... @classmethod @@ -45,7 +45,7 @@ class EntityGroup: def __new__(cls, *args, **kwargs): ... def get_entity_group_version(*args, **kwargs) -> None: ... -def get_kinds(start: Any | None = ..., end: Any | None = ...): ... -def get_namespaces(start: Any | None = ..., end: Any | None = ...): ... -def get_properties_of_kind(kind, start: Any | None = ..., end: Any | None = ...): ... -def get_representations_of_kind(kind, start: Any | None = ..., end: Any | None = ...): ... +def get_kinds(start=None, end=None): ... +def get_namespaces(start=None, end=None): ... +def get_properties_of_kind(kind, start=None, end=None): ... +def get_representations_of_kind(kind, start=None, end=None): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi index 08d663f96e97..277330ce17a8 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi @@ -1,7 +1,8 @@ import datetime -from collections.abc import Iterable, Sequence -from typing import Callable, NoReturn, Type -from typing_extensions import Literal +from _typeshed import Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Literal, TypeAlias +from typing_extensions import Never, Self from google.cloud.ndb import exceptions, key as key_module, query as query_module, tasklets as tasklets_module @@ -23,19 +24,19 @@ class UserNotFoundError(exceptions.Error): ... class _NotEqualMixin: def __ne__(self, other: object) -> bool: ... -DirectionT = Literal["asc", "desc"] +_Direction: TypeAlias = Literal["asc", "desc"] class IndexProperty(_NotEqualMixin): - def __new__(cls, name: str, direction: DirectionT) -> IndexProperty: ... + def __new__(cls, name: str, direction: _Direction) -> Self: ... @property def name(self) -> str: ... @property - def direction(self) -> DirectionT: ... + def direction(self) -> _Direction: ... def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... class Index(_NotEqualMixin): - def __new__(cls, kind: str, properties: list[IndexProperty], ancestor: bool) -> Index: ... + def __new__(cls, kind: str, properties: list[IndexProperty], ancestor: bool) -> Self: ... @property def kind(self) -> str: ... @property @@ -57,14 +58,15 @@ class IndexState(_NotEqualMixin): def __hash__(self) -> int: ... class ModelAdapter: - def __new__(cls, *args, **kwargs) -> ModelAdapter: ... + # This actually returns Never, but mypy can't handle that + def __new__(cls, *args, **kwargs) -> Self: ... -def make_connection(*args, **kwargs) -> NoReturn: ... +def make_connection(*args, **kwargs) -> Never: ... class ModelAttribute: ... class _BaseValue(_NotEqualMixin): - b_val: object = ... + b_val: object def __init__(self, b_val) -> None: ... def __eq__(self, other) -> bool: ... def __hash__(self) -> int: ... @@ -72,15 +74,15 @@ class _BaseValue(_NotEqualMixin): class Property(ModelAttribute): def __init__( self, - name: str | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - required: bool | None = ..., - default: object | None = ..., - choices: Iterable[object] | None = ..., - validator: Callable[[Property], object] | None = ..., - verbose_name: str | None = ..., - write_empty_list: bool | None = ..., + name: str | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + required: bool | None = None, + default: object = None, + choices: Iterable[object] | None = None, + validator: Callable[[Property, Any], object] | None = None, + verbose_name: str | None = None, + write_empty_list: bool | None = None, ) -> None: ... def __eq__(self, value: object) -> query_module.FilterNode: ... # type: ignore[override] def __ne__(self, value: object) -> query_module.FilterNode: ... # type: ignore[override] @@ -88,7 +90,12 @@ class Property(ModelAttribute): def __le__(self, value: object) -> query_module.FilterNode: ... def __gt__(self, value: object) -> query_module.FilterNode: ... def __ge__(self, value: object) -> query_module.FilterNode: ... - def IN(self, value: Iterable[object]) -> query_module.DisjunctionNode | query_module.FilterNode | query_module.FalseNode: ... + def IN( + self, value: Iterable[object], server_op: bool = False + ) -> query_module.DisjunctionNode | query_module.FilterNode | query_module.FalseNode: ... + def NOT_IN( + self, value: Iterable[object], server_op: bool = False + ) -> query_module.DisjunctionNode | query_module.FilterNode | query_module.FalseNode: ... def __neg__(self) -> query_module.PropertyOrder: ... def __pos__(self) -> query_module.PropertyOrder: ... def __set__(self, entity: Model, value: object) -> None: ... @@ -96,46 +103,47 @@ class Property(ModelAttribute): class ModelKey(Property): def __init__(self) -> None: ... - def __get__(self, entity: Model, unused_cls: Type[Model] | None = ...) -> key_module.Key | list[key_module.Key] | None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = None) -> key_module.Key | list[key_module.Key] | None: ... class BooleanProperty(Property): - def __get__(self, entity: Model, unused_cls: Type[Model] | None = ...) -> bool | list[bool] | None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = None) -> bool | list[bool] | None: ... class IntegerProperty(Property): - def __get__(self, entity: Model, unused_cls: Type[Model] | None = ...) -> int | list[int] | None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = None) -> int | list[int] | None: ... class FloatProperty(Property): - def __get__(self, entity: Model, unused_cls: Type[Model] | None = ...) -> float | list[float] | None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = None) -> float | list[float] | None: ... class _CompressedValue(bytes): - z_val: bytes = ... + z_val: bytes def __init__(self, z_val: bytes) -> None: ... def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> NoReturn: ... + def __hash__(self) -> Never: ... class BlobProperty(Property): def __init__( self, - name: str | None = ..., - compressed: bool | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - required: bool | None = ..., - default: bytes | None = ..., - choices: Iterable[bytes] | None = ..., - validator: Callable[[Property], object] | None = ..., - verbose_name: str | None = ..., - write_empty_list: bool | None = ..., + name: str | None = None, + compressed: bool | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + required: bool | None = None, + default: bytes | None = None, + choices: Iterable[bytes] | None = None, + validator: Callable[[Property, Any], object] | None = None, + verbose_name: str | None = None, + write_empty_list: bool | None = None, ) -> None: ... - def __get__(self, entity: Model, unused_cls: Type[Model] | None = ...) -> bytes | list[bytes] | None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = None) -> bytes | list[bytes] | None: ... class CompressedTextProperty(BlobProperty): + __slots__ = () def __init__(self, *args, **kwargs) -> None: ... class TextProperty(Property): def __new__(cls, *args, **kwargs): ... def __init__(self, *args, **kwargs) -> None: ... - def __get__(self, entity: Model, unused_cls: Type[Model] | None = ...) -> str | list[str] | None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = None) -> str | list[str] | None: ... class StringProperty(TextProperty): def __init__(self, *args, **kwargs) -> None: ... @@ -146,21 +154,21 @@ class PickleProperty(BlobProperty): ... class JsonProperty(BlobProperty): def __init__( self, - name: str | None = ..., - compressed: bool | None = ..., - json_type: type | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - required: bool | None = ..., - default: object | None = ..., - choices: Iterable[object] | None = ..., - validator: Callable[[Property], object] | None = ..., - verbose_name: str | None = ..., - write_empty_list: bool | None = ..., + name: str | None = None, + compressed: bool | None = None, + json_type: type | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + required: bool | None = None, + default: object = None, + choices: Iterable[object] | None = None, + validator: Callable[[Property, Any], object] | None = None, + verbose_name: str | None = None, + write_empty_list: bool | None = None, ) -> None: ... class User: - def __init__(self, email: str | None = ..., _auth_domain: str | None = ..., _user_id: str | None = ...) -> None: ... + def __init__(self, email: str | None = None, _auth_domain: str | None = None, _user_id: str | None = None) -> None: ... def nickname(self) -> str: ... def email(self): ... def user_id(self) -> str | None: ... @@ -172,32 +180,32 @@ class User: class UserProperty(Property): def __init__( self, - name: str | None = ..., - auto_current_user: bool | None = ..., - auto_current_user_add: bool | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - required: bool | None = ..., - default: bytes | None = ..., - choices: Iterable[bytes] | None = ..., - validator: Callable[[Property], object] | None = ..., - verbose_name: str | None = ..., - write_empty_list: bool | None = ..., + name: str | None = None, + auto_current_user: bool | None = None, + auto_current_user_add: bool | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + required: bool | None = None, + default: bytes | None = None, + choices: Iterable[bytes] | None = None, + validator: Callable[[Property, Any], object] | None = None, + verbose_name: str | None = None, + write_empty_list: bool | None = None, ) -> None: ... class KeyProperty(Property): def __init__( self, - name: str | None = ..., - kind: Type[Model] | str | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - required: bool | None = ..., - default: key_module.Key | None = ..., - choices: Iterable[key_module.Key] | None = ..., - validator: Callable[[Property, key_module.Key], bool] | None = ..., - verbose_name: str | None = ..., - write_empty_list: bool | None = ..., + name: str | None = None, + kind: type[Model] | str | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + required: bool | None = None, + default: key_module.Key | None = None, + choices: Iterable[key_module.Key] | None = None, + validator: Callable[[Property, key_module.Key], key_module.Key] | None = None, + verbose_name: str | None = None, + write_empty_list: bool | None = None, ) -> None: ... class BlobKeyProperty(Property): ... @@ -205,200 +213,202 @@ class BlobKeyProperty(Property): ... class DateTimeProperty(Property): def __init__( self, - name: str | None = ..., - auto_now: bool | None = ..., - auto_now_add: bool | None = ..., - tzinfo: datetime.tzinfo | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - required: bool | None = ..., - default: datetime.datetime | None = ..., - choices: Iterable[datetime.datetime] | None = ..., - validator: Callable[[Property, object], bool] | None = ..., - verbose_name: str | None = ..., - write_empty_list: bool | None = ..., + name: str | None = None, + auto_now: bool | None = None, + auto_now_add: bool | None = None, + tzinfo: datetime.tzinfo | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + required: bool | None = None, + default: datetime.datetime | None = None, + choices: Iterable[datetime.datetime] | None = None, + validator: Callable[[Property, Any], object] | None = None, + verbose_name: str | None = None, + write_empty_list: bool | None = None, ) -> None: ... class DateProperty(DateTimeProperty): ... class TimeProperty(DateTimeProperty): ... class StructuredProperty(Property): - def __init__(self, model_class: type, name: str | None = ..., **kwargs) -> None: ... - def __getattr__(self, attrname): ... - def IN(self, value: Iterable[object]) -> query_module.DisjunctionNode | query_module.FalseNode: ... + def __init__(self, model_class: type, name: str | None = None, **kwargs) -> None: ... + def __getattr__(self, attrname: str): ... + def IN(self, value: Iterable[object]) -> query_module.DisjunctionNode | query_module.FalseNode: ... # type: ignore[override] class LocalStructuredProperty(BlobProperty): - def __init__(self, model_class: Type[Model], **kwargs) -> None: ... + def __init__(self, model_class: type[Model], **kwargs) -> None: ... class GenericProperty(Property): - def __init__(self, name: str | None = ..., compressed: bool = ..., **kwargs) -> None: ... + def __init__(self, name: str | None = None, compressed: bool = False, **kwargs) -> None: ... class ComputedProperty(GenericProperty): def __init__( self, func: Callable[[Model], object], - name: str | None = ..., - indexed: bool | None = ..., - repeated: bool | None = ..., - verbose_name: str | None = ..., + name: str | None = None, + indexed: bool | None = None, + repeated: bool | None = None, + verbose_name: str | None = None, ) -> None: ... class MetaModel(type): def __init__(cls, name: str, bases, classdict) -> None: ... class Model(_NotEqualMixin, metaclass=MetaModel): - key: ModelKey = ... + key: ModelKey def __init__(_self, **kwargs) -> None: ... - def __hash__(self) -> NoReturn: ... + def __hash__(self) -> Never: ... def __eq__(self, other: object) -> bool: ... @classmethod - def gql(cls: Type[Model], query_string: str, *args, **kwargs) -> query_module.Query: ... + def gql(cls: type[Model], query_string: str, *args, **kwargs) -> query_module.Query: ... def put(self, **kwargs): ... def put_async(self, **kwargs) -> tasklets_module.Future: ... @classmethod - def query(cls: Type[Model], *args, **kwargs) -> query_module.Query: ... + def query(cls: type[Model], *args, **kwargs) -> query_module.Query: ... @classmethod def allocate_ids( - cls: Type[Model], - size: int | None = ..., - max: int | None = ..., - parent: key_module.Key | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options=..., + cls: type[Model], + size: int | None = None, + max: int | None = None, + parent: key_module.Key | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options=None, ) -> tuple[key_module.Key, key_module.Key]: ... @classmethod def allocate_ids_async( - cls: Type[Model], - size: int | None = ..., - max: int | None = ..., - parent: key_module.Key | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options=..., + cls: type[Model], + size: int | None = None, + max: int | None = None, + parent: key_module.Key | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options=None, ) -> tasklets_module.Future: ... @classmethod def get_by_id( - cls: Type[Model], + cls, id: int | str | None, - parent: key_module.Key | None = ..., - namespace: str | None = ..., - project: str | None = ..., - app: str | None = ..., - read_consistency: Literal["EVENTUAL"] | None = ..., - read_policy: Literal["EVENTUAL"] | None = ..., - transaction: bytes | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options=..., - ) -> tasklets_module.Future: ... + parent: key_module.Key | None = None, + namespace: str | None = None, + project: str | None = None, + app: str | None = None, + read_consistency: Literal["EVENTUAL"] | None = None, + read_policy: Literal["EVENTUAL"] | None = None, + transaction: bytes | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options=None, + database: str | None = None, + ) -> Self | None: ... @classmethod def get_by_id_async( - cls: Type[Model], + cls: type[Model], id: int | str, - parent: key_module.Key | None = ..., - namespace: str | None = ..., - project: str | None = ..., - app: str | None = ..., - read_consistency: Literal["EVENTUAL"] | None = ..., - read_policy: Literal["EVENTUAL"] | None = ..., - transaction: bytes | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options=..., - ) -> Model | None: ... + parent: key_module.Key | None = None, + namespace: str | None = None, + project: str | None = None, + app: str | None = None, + read_consistency: Literal["EVENTUAL"] | None = None, + read_policy: Literal["EVENTUAL"] | None = None, + transaction: bytes | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options=None, + database: str | None = None, + ) -> tasklets_module.Future: ... @classmethod def get_or_insert( - cls: Type[Model], - name: str, - parent: key_module.Key | None = ..., - namespace: str | None = ..., - project: str | None = ..., - app: str | None = ..., - read_consistency: Literal["EVENTUAL"] | None = ..., - read_policy: Literal["EVENTUAL"] | None = ..., - transaction: bytes | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options=..., + cls, + _name: str, + parent: key_module.Key | None = None, + namespace: str | None = None, + project: str | None = None, + app: str | None = None, + read_consistency: Literal["EVENTUAL"] | None = None, + read_policy: Literal["EVENTUAL"] | None = None, + transaction: bytes | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options=None, **kw_model_args, - ) -> Model: ... + ) -> Self: ... @classmethod def get_or_insert_async( - cls: Type[Model], - name: str, - parent: key_module.Key | None = ..., - namespace: str | None = ..., - project: str | None = ..., - app: str | None = ..., - read_consistency: Literal["EVENTUAL"] | None = ..., - read_policy: Literal["EVENTUAL"] | None = ..., - transaction: bytes | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options=..., + cls: type[Model], + _name: str, + parent: key_module.Key | None = None, + namespace: str | None = None, + project: str | None = None, + app: str | None = None, + read_consistency: Literal["EVENTUAL"] | None = None, + read_policy: Literal["EVENTUAL"] | None = None, + transaction: bytes | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options=None, **kw_model_args, ) -> tasklets_module.Future: ... def populate(self, **kwargs) -> None: ... def has_complete_key(self) -> bool: ... def to_dict( self, - include: list[object] | tuple[object, object] | set[object] | None = ..., - exclude: list[object] | tuple[object, object] | set[object] | None = ..., + include: list[object] | tuple[object, object] | set[object] | None = None, + exclude: list[object] | tuple[object, object] | set[object] | None = None, ): ... class Expando(Model): @@ -407,100 +417,100 @@ class Expando(Model): def __delattr__(self, name: str) -> None: ... def get_multi_async( - keys: Sequence[Type[key_module.Key]], - read_consistency: Literal["EVENTUAL"] | None = ..., - read_policy: Literal["EVENTUAL"] | None = ..., - transaction: bytes | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options: object | None = ..., -) -> list[Type[tasklets_module.Future]]: ... + keys: Sequence[key_module.Key], + read_consistency: Literal["EVENTUAL"] | None = None, + read_policy: Literal["EVENTUAL"] | None = None, + transaction: bytes | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options: object = None, +) -> list[tasklets_module.Future]: ... def get_multi( - keys: Sequence[Type[key_module.Key]], - read_consistency: Literal["EVENTUAL"] | None = ..., - read_policy: Literal["EVENTUAL"] | None = ..., - transaction: bytes | None = ..., - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options: object | None = ..., -) -> list[Type[Model] | None]: ... + keys: Sequence[key_module.Key], + read_consistency: Literal["EVENTUAL"] | None = None, + read_policy: Literal["EVENTUAL"] | None = None, + transaction: bytes | None = None, + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options: object = None, +) -> list[Model | None]: ... def put_multi_async( - entities: list[Type[Model]], - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options: object | None = ..., + entities: list[Model], + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options: object = None, ) -> list[tasklets_module.Future]: ... def put_multi( entities: list[Model], - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options: object | None = ..., + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options: object = None, ) -> list[key_module.Key]: ... def delete_multi_async( - keys: list[key_module.Key], - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options: object | None = ..., + keys: Sequence[key_module.Key], + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options: object = None, ) -> list[tasklets_module.Future]: ... def delete_multi( keys: Sequence[key_module.Key], - retries: int | None = ..., - timeout: float | None = ..., - deadline: float | None = ..., - use_cache: bool | None = ..., - use_global_cache: bool | None = ..., - global_cache_timeout: int | None = ..., - use_datastore: bool | None = ..., - use_memcache: bool | None = ..., - memcache_timeout: int | None = ..., - max_memcache_items: int | None = ..., - force_writes: bool | None = ..., - _options: object | None = ..., + retries: int | None = None, + timeout: float | None = None, + deadline: float | None = None, + use_cache: bool | None = None, + use_global_cache: bool | None = None, + global_cache_timeout: int | None = None, + use_datastore: bool | None = None, + use_memcache: bool | None = None, + memcache_timeout: int | None = None, + max_memcache_items: int | None = None, + force_writes: bool | None = None, + _options: object = None, ) -> list[None]: ... -def get_indexes_async(**options: object) -> NoReturn: ... -def get_indexes(**options: object) -> NoReturn: ... +def get_indexes_async(**options: Unused) -> Never: ... +def get_indexes(**options: Unused) -> Never: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi index 43cabd288871..3730e8669ba8 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi @@ -1,9 +1,9 @@ -from typing import Any +from _typeshed import Incomplete from google.cloud.ndb import model class _ClassKeyProperty(model.StringProperty): - def __init__(self, name=..., indexed: bool = ...) -> None: ... + def __init__(self, name="class", indexed: bool = True) -> None: ... class PolyModel(model.Model): - class_: Any + class_: Incomplete diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi index 6ca3d6f33976..2c067bb8f368 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi @@ -1,17 +1,17 @@ -from typing import Any +from _typeshed import Incomplete from google.cloud.ndb import _options class PropertyOrder: - name: Any - reverse: Any - def __init__(self, name, reverse: bool = ...) -> None: ... + name: Incomplete + reverse: Incomplete + def __init__(self, name, reverse: bool = False) -> None: ... def __neg__(self): ... class RepeatedStructuredPropertyPredicate: - name: Any - match_keys: Any - match_values: Any + name: Incomplete + match_keys: Incomplete + match_values: Incomplete def __init__(self, name, match_keys, entity_pb) -> None: ... def __call__(self, entity_pb): ... @@ -27,8 +27,8 @@ class Parameter(ParameterizedThing): def resolve(self, bindings, used): ... class ParameterizedFunction(ParameterizedThing): - func: Any - values: Any + func: Incomplete + values: Incomplete def __init__(self, func, values) -> None: ... def __eq__(self, other): ... def is_parameterized(self): ... @@ -54,7 +54,7 @@ class ParameterNode(Node): def resolve(self, bindings, used): ... class FilterNode(Node): - def __new__(cls, name, opsymbol, value): ... + def __new__(cls, name, opsymbol, value, server_op: bool = False): ... def __getnewargs__(self): ... def __eq__(self, other): ... @@ -64,9 +64,9 @@ class PostFilterNode(Node): def __eq__(self, other): ... class _BooleanClauses: - name: Any - combine_or: Any - or_parts: Any + name: Incomplete + combine_or: Incomplete + or_parts: Incomplete def __init__(self, name, combine_or) -> None: ... def add_node(self, node) -> None: ... @@ -88,40 +88,61 @@ AND = ConjunctionNode OR = DisjunctionNode class QueryOptions(_options.ReadOptions): - project: Any - namespace: Any - def __init__(self, config: Any | None = ..., context: Any | None = ..., **kwargs) -> None: ... + __slots__ = ( + "kind", + "ancestor", + "filters", + "order_by", + "orders", + "distinct_on", + "group_by", + "namespace", + "project", + "database", + "keys_only", + "limit", + "offset", + "start_cursor", + "end_cursor", + "projection", + "callback", + ) + project: Incomplete + namespace: Incomplete + database: str | None + def __init__(self, config=None, context=None, **kwargs) -> None: ... class Query: - default_options: Any - kind: Any - ancestor: Any - filters: Any - order_by: Any - project: Any - namespace: Any - limit: Any - offset: Any - keys_only: Any - projection: Any - distinct_on: Any + default_options: Incomplete + kind: Incomplete + ancestor: Incomplete + filters: Incomplete + order_by: Incomplete + project: Incomplete + namespace: Incomplete + limit: Incomplete + offset: Incomplete + keys_only: Incomplete + projection: Incomplete + distinct_on: Incomplete + database: str | None def __init__( self, - kind: Any | None = ..., - filters: Any | None = ..., - ancestor: Any | None = ..., - order_by: Any | None = ..., - orders: Any | None = ..., - project: Any | None = ..., - app: Any | None = ..., - namespace: Any | None = ..., - projection: Any | None = ..., - distinct_on: Any | None = ..., - group_by: Any | None = ..., - limit: Any | None = ..., - offset: Any | None = ..., - keys_only: Any | None = ..., - default_options: Any | None = ..., + kind=None, + filters=None, + ancestor=None, + order_by=None, + orders=None, + project=None, + app=None, + namespace=None, + projection=None, + distinct_on=None, + group_by=None, + limit=None, + offset=None, + keys_only=None, + default_options=None, ) -> None: ... @property def is_distinct(self): ... @@ -129,18 +150,18 @@ class Query: def order(self, *props): ... def analyze(self): ... def bind(self, *positional, **keyword): ... - def fetch(self, limit: Any | None = ..., **kwargs): ... - def fetch_async(self, limit: Any | None = ..., **kwargs): ... - def run_to_queue(self, queue, conn, options: Any | None = ..., dsquery: Any | None = ...) -> None: ... + def fetch(self, limit=None, **kwargs): ... + def fetch_async(self, limit=None, **kwargs): ... + def run_to_queue(self, queue, conn, options=None, dsquery=None) -> None: ... def iter(self, **kwargs): ... - __iter__: Any + __iter__: Incomplete def map(self, callback, **kwargs): ... def map_async(self, callback, **kwargs) -> None: ... def get(self, **kwargs): ... def get_async(self, **kwargs) -> None: ... - def count(self, limit: Any | None = ..., **kwargs): ... - def count_async(self, limit: Any | None = ..., **kwargs): ... + def count(self, limit=None, **kwargs): ... + def count_async(self, limit=None, **kwargs): ... def fetch_page(self, page_size, **kwargs): ... def fetch_page_async(self, page_size, **kwargs) -> None: ... -def gql(query_string: str, *args: Any, **kwds: Any) -> Query: ... +def gql(query_string: str, *args, **kwds) -> Query: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi index 1ffa02ff04de..7dfaaa5c7042 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi @@ -1,41 +1,41 @@ -from typing import Any +from _typeshed import Incomplete from google.cloud.ndb import model class BaseStatistic(model.Model): STORED_KIND_NAME: str - bytes: Any - count: Any - timestamp: Any + bytes: Incomplete + count: Incomplete + timestamp: Incomplete class BaseKindStatistic(BaseStatistic): STORED_KIND_NAME: str - kind_name: Any - entity_bytes: Any + kind_name: Incomplete + entity_bytes: Incomplete class GlobalStat(BaseStatistic): STORED_KIND_NAME: str - entity_bytes: Any - builtin_index_bytes: Any - builtin_index_count: Any - composite_index_bytes: Any - composite_index_count: Any + entity_bytes: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + composite_index_bytes: Incomplete + composite_index_count: Incomplete class NamespaceStat(BaseStatistic): STORED_KIND_NAME: str - subject_namespace: Any - entity_bytes: Any - builtin_index_bytes: Any - builtin_index_count: Any - composite_index_bytes: Any - composite_index_count: Any + subject_namespace: Incomplete + entity_bytes: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + composite_index_bytes: Incomplete + composite_index_count: Incomplete class KindStat(BaseKindStatistic): STORED_KIND_NAME: str - builtin_index_bytes: Any - builtin_index_count: Any - composite_index_bytes: Any - composite_index_count: Any + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + composite_index_bytes: Incomplete + composite_index_count: Incomplete class KindRootEntityStat(BaseKindStatistic): STORED_KIND_NAME: str @@ -45,34 +45,34 @@ class KindNonRootEntityStat(BaseKindStatistic): class PropertyTypeStat(BaseStatistic): STORED_KIND_NAME: str - property_type: Any - entity_bytes: Any - builtin_index_bytes: Any - builtin_index_count: Any + property_type: Incomplete + entity_bytes: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete class KindPropertyTypeStat(BaseKindStatistic): STORED_KIND_NAME: str - property_type: Any - builtin_index_bytes: Any - builtin_index_count: Any + property_type: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete class KindPropertyNameStat(BaseKindStatistic): STORED_KIND_NAME: str - property_name: Any - builtin_index_bytes: Any - builtin_index_count: Any + property_name: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete class KindPropertyNamePropertyTypeStat(BaseKindStatistic): STORED_KIND_NAME: str - property_type: Any - property_name: Any - builtin_index_bytes: Any - builtin_index_count: Any + property_type: Incomplete + property_name: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete class KindCompositeIndexStat(BaseStatistic): STORED_KIND_NAME: str - index_id: Any - kind_name: Any + index_id: Incomplete + kind_name: Incomplete class NamespaceGlobalStat(GlobalStat): STORED_KIND_NAME: str diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi index 4d9f34d69784..81966706c1e3 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi @@ -1,8 +1,8 @@ -from typing import Any +from _typeshed import Incomplete class Future: - info: Any - def __init__(self, info: str = ...) -> None: ... + info: Incomplete + def __init__(self, info: str = "Unknown") -> None: ... def done(self): ... def running(self): ... def wait(self) -> None: ... @@ -10,9 +10,9 @@ class Future: def set_result(self, result) -> None: ... def set_exception(self, exception) -> None: ... def result(self): ... - get_result: Any + get_result: Incomplete def exception(self): ... - get_exception: Any + get_exception: Incomplete def get_traceback(self): ... def add_done_callback(self, callback) -> None: ... def cancel(self) -> None: ... @@ -23,10 +23,10 @@ class Future: def wait_all(futures): ... class _TaskletFuture(Future): - generator: Any - context: Any - waiting_on: Any - def __init__(self, generator, context, info: str = ...) -> None: ... + generator: Incomplete + context: Incomplete + waiting_on: Incomplete + def __init__(self, generator, context, info: str = "Unknown") -> None: ... def cancel(self) -> None: ... class _MultiFuture(Future): diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi index 3ddb96071d22..ccc5ca208d88 100644 --- a/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi +++ b/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi @@ -1,11 +1,11 @@ import threading -from typing import Any +from _typeshed import Incomplete -TRUTHY_STRINGS: Any +TRUTHY_STRINGS: Incomplete def asbool(value): ... -DEBUG: Any +DEBUG: Incomplete def code_info(*args, **kwargs) -> None: ... def decorator(*args, **kwargs) -> None: ... @@ -16,7 +16,7 @@ def get_stack(*args, **kwargs) -> None: ... def logging_debug(log, message, *args, **kwargs) -> None: ... class keyword_only: - defaults: Any + defaults: Incomplete def __init__(self, **kwargs) -> None: ... def __call__(self, wrapped): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/version.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/version.pyi new file mode 100644 index 000000000000..bda5b5a7f4cc --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/version.pyi @@ -0,0 +1 @@ +__version__: str diff --git a/stubs/greenlet/@tests/stubtest_allowlist.txt b/stubs/greenlet/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..38d2d056903f --- /dev/null +++ b/stubs/greenlet/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Error: is not present in stub +# ============================= +# this module only contains C code and exports no Python code, so it's better +# if we pretend it doesn't exist +greenlet.platform +# the tests should not be part of the modules +greenlet.tests diff --git a/stubs/greenlet/@tests/test_cases/check_greenlet.py b/stubs/greenlet/@tests/test_cases/check_greenlet.py new file mode 100644 index 000000000000..976772d1775c --- /dev/null +++ b/stubs/greenlet/@tests/test_cases/check_greenlet.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from typing import Optional +from typing_extensions import assert_type + +import greenlet + +g = greenlet.greenlet() +h = greenlet.greenlet() +assert_type(g.parent, Optional[greenlet.greenlet]) +g.parent = h + +# Although "parent" sometimes can be None at runtime, +# it's always illegal for it to be set to None +g.parent = None # type: ignore diff --git a/stubs/greenlet/METADATA.toml b/stubs/greenlet/METADATA.toml new file mode 100644 index 000000000000..5677f8261f6b --- /dev/null +++ b/stubs/greenlet/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.5.*" +upstream-repository = "https://github.com/python-greenlet/greenlet" diff --git a/stubs/greenlet/greenlet/__init__.pyi b/stubs/greenlet/greenlet/__init__.pyi new file mode 100644 index 000000000000..903fc6f31c70 --- /dev/null +++ b/stubs/greenlet/greenlet/__init__.pyi @@ -0,0 +1,14 @@ +from typing import Final + +from ._greenlet import ( + _C_API as _C_API, + GreenletExit as GreenletExit, + error as error, + getcurrent as getcurrent, + gettrace as gettrace, + greenlet as greenlet, + settrace as settrace, +) + +__version__: Final[str] +__all__ = ["__version__", "_C_API", "GreenletExit", "error", "getcurrent", "greenlet", "gettrace", "settrace"] diff --git a/stubs/greenlet/greenlet/_greenlet.pyi b/stubs/greenlet/greenlet/_greenlet.pyi new file mode 100644 index 000000000000..09c4cb22ec8f --- /dev/null +++ b/stubs/greenlet/greenlet/_greenlet.pyi @@ -0,0 +1,90 @@ +import sys +from collections.abc import Callable +from contextvars import Context +from types import FrameType, TracebackType +from typing import Any, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import disjoint_base + +_TraceEvent: TypeAlias = Literal["switch", "throw"] +_TraceCallback: TypeAlias = Callable[[_TraceEvent, tuple[greenlet, greenlet]], object] + +CLOCKS_PER_SEC: int +GREENLET_USE_CONTEXT_VARS: bool +GREENLET_USE_GC: bool +GREENLET_USE_STANDARD_THREADING: bool +GREENLET_USE_TRACING: bool +# this is a PyCapsule, it may be used to pass the gevent C-API to another C-extension +# there isn't a runtime type for this, since it's only an opaque wrapper around void* +# but it's probably still better than pretending it doesn't exist, so people that need +# to pass this around, can still pass it around without having to ignore type errors... +_C_API: object + +@type_check_only +class _ParentDescriptor(Protocol): + def __get__(self, obj: greenlet, owner: type[greenlet] | None = None) -> greenlet | None: ... + def __set__(self, obj: greenlet, value: greenlet) -> None: ... + +class GreenletExit(BaseException): ... +class error(Exception): ... + +@disjoint_base +class greenlet: + @property + def dead(self) -> bool: ... + + @property + def gr_context(self) -> Context | None: ... + @gr_context.setter + def gr_context(self, value: Context | None) -> None: ... + + @property + def gr_frame(self) -> FrameType | None: ... + # the parent attribute is a bit special, since it can't be set to `None` manually, but + # it can be `None` for the master greenlet which will always be around, regardless of + # how many greenlets have been spawned explicitly. Since there can only be one such + # greenlet per thread, there is no way to create another one manually. + parent: _ParentDescriptor + + @property + def run(self) -> Callable[..., Any]: ... + @run.setter + def run(self, value: Callable[..., Any]) -> None: ... + + def __init__(self, run: Callable[..., Any] | None = None, parent: greenlet | None = None) -> None: ... + def switch(self, *args: Any, **kwargs: Any) -> Any: ... + + @overload + def throw( + self, typ: type[BaseException] = ..., val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> Any: ... + @overload + def throw(self, typ: BaseException = ..., val: None = None, tb: TracebackType | None = None, /) -> Any: ... + + def __bool__(self) -> bool: ... + + # aliases for some module attributes/methods + GreenletExit: type[GreenletExit] + error: type[error] + @staticmethod + def getcurrent() -> greenlet: ... + @staticmethod + def gettrace() -> _TraceCallback | None: ... + @staticmethod + def settrace(callback: _TraceCallback | None, /) -> _TraceCallback | None: ... + +class UnswitchableGreenlet(greenlet): # undocumented + force_switch_error: bool + force_slp_switch_error: bool + +def enable_optional_cleanup(enabled: bool, /) -> None: ... +def get_clocks_used_doing_optional_cleanup() -> int: ... +def get_pending_cleanup_count() -> int: ... +def get_total_main_greenlets() -> int: ... + +if sys.version_info < (3, 13): + def get_tstate_trash_delete_nesting() -> int: ... + +def getcurrent() -> greenlet: ... +def gettrace() -> _TraceCallback | None: ... +def set_thread_local(key: object, value: object, /) -> None: ... +def settrace(callback: _TraceCallback | None, /) -> _TraceCallback | None: ... diff --git a/stubs/grpcio-channelz/METADATA.toml b/stubs/grpcio-channelz/METADATA.toml new file mode 100644 index 000000000000..b12e58c39175 --- /dev/null +++ b/stubs/grpcio-channelz/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio", "types-protobuf"] diff --git a/stdlib/@python2/distutils/command/bdist_rpm.pyi b/stubs/grpcio-channelz/grpc_channelz/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/bdist_rpm.pyi rename to stubs/grpcio-channelz/grpc_channelz/__init__.pyi diff --git a/stdlib/@python2/distutils/command/bdist_wininst.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/bdist_wininst.pyi rename to stubs/grpcio-channelz/grpc_channelz/v1/__init__.pyi diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi new file mode 100644 index 000000000000..87aa2bf125d1 --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi @@ -0,0 +1,19 @@ +from grpc_channelz.v1 import channelz_pb2, channelz_pb2_grpc + +class ChannelzServicer(channelz_pb2_grpc.ChannelzServicer): + @staticmethod + async def GetTopChannels(request: channelz_pb2.GetTopChannelsRequest, context) -> channelz_pb2.GetTopChannelsResponse: ... + @staticmethod + async def GetServers(request: channelz_pb2.GetServersRequest, context) -> channelz_pb2.GetServersResponse: ... + @staticmethod + async def GetServer(request: channelz_pb2.GetServerRequest, context) -> channelz_pb2.GetServerResponse: ... + @staticmethod + async def GetServerSockets( + request: channelz_pb2.GetServerSocketsRequest, context + ) -> channelz_pb2.GetServerSocketsResponse: ... + @staticmethod + async def GetChannel(request: channelz_pb2.GetChannelRequest, context) -> channelz_pb2.GetChannelResponse: ... + @staticmethod + async def GetSubchannel(request: channelz_pb2.GetSubchannelRequest, context) -> channelz_pb2.GetSubchannelResponse: ... + @staticmethod + async def GetSocket(request: channelz_pb2.GetSocketRequest, context) -> channelz_pb2.GetSocketResponse: ... diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi new file mode 100644 index 000000000000..f8b7ba089b47 --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi @@ -0,0 +1,25 @@ +import grpc_channelz.v1.channelz_pb2 as _channelz_pb2 +import grpc_channelz.v1.channelz_pb2_grpc as _channelz_pb2_grpc +from grpc import ServicerContext + +class ChannelzServicer(_channelz_pb2_grpc.ChannelzServicer): + @staticmethod + def GetTopChannels( + request: _channelz_pb2.GetTopChannelsRequest, context: ServicerContext + ) -> _channelz_pb2.GetTopChannelsResponse: ... + @staticmethod + def GetServers(request: _channelz_pb2.GetServersRequest, context: ServicerContext) -> _channelz_pb2.GetServersResponse: ... + @staticmethod + def GetServer(request: _channelz_pb2.GetServerRequest, context: ServicerContext) -> _channelz_pb2.GetServerResponse: ... + @staticmethod + def GetServerSockets( + request: _channelz_pb2.GetServerSocketsRequest, context: ServicerContext + ) -> _channelz_pb2.GetServerSocketsResponse: ... + @staticmethod + def GetChannel(request: _channelz_pb2.GetChannelRequest, context: ServicerContext) -> _channelz_pb2.GetChannelResponse: ... + @staticmethod + def GetSubchannel( + request: _channelz_pb2.GetSubchannelRequest, context: ServicerContext + ) -> _channelz_pb2.GetSubchannelResponse: ... + @staticmethod + def GetSocket(request: _channelz_pb2.GetSocketRequest, context: ServicerContext) -> _channelz_pb2.GetSocketResponse: ... diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi new file mode 100644 index 000000000000..2ed61fd4fa3a --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi @@ -0,0 +1,6 @@ +from grpc_channelz.v1 import _async as aio +from grpc_channelz.v1._servicer import ChannelzServicer + +def add_channelz_servicer(server) -> None: ... + +__all__ = ["aio", "add_channelz_servicer", "ChannelzServicer"] diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi new file mode 100644 index 000000000000..262fa0f3f89c --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi @@ -0,0 +1,604 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import ClassVar, final + +from google._upb._message import Descriptor, FileDescriptor, MessageMeta +from google.protobuf import any_pb2, duration_pb2, message, timestamp_pb2, wrappers_pb2 +from google.protobuf.internal import containers + +DESCRIPTOR: FileDescriptor + +@final +class Channel(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + CHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SUBCHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SOCKET_REF_FIELD_NUMBER: ClassVar[int] + ref: ChannelRef + data: ChannelData + channel_ref: containers.RepeatedCompositeFieldContainer[ChannelRef] + subchannel_ref: containers.RepeatedCompositeFieldContainer[SubchannelRef] + socket_ref: containers.RepeatedCompositeFieldContainer[SocketRef] + def __init__( + self, + ref: ChannelRef | Mapping[Incomplete, Incomplete] | None = ..., + data: ChannelData | Mapping[Incomplete, Incomplete] | None = ..., + channel_ref: Iterable[ChannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + subchannel_ref: Iterable[SubchannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + socket_ref: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Subchannel(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + CHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SUBCHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SOCKET_REF_FIELD_NUMBER: ClassVar[int] + ref: SubchannelRef + data: ChannelData + channel_ref: containers.RepeatedCompositeFieldContainer[ChannelRef] + subchannel_ref: containers.RepeatedCompositeFieldContainer[SubchannelRef] + socket_ref: containers.RepeatedCompositeFieldContainer[SocketRef] + def __init__( + self, + ref: SubchannelRef | Mapping[Incomplete, Incomplete] | None = ..., + data: ChannelData | Mapping[Incomplete, Incomplete] | None = ..., + channel_ref: Iterable[ChannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + subchannel_ref: Iterable[SubchannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + socket_ref: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelConnectivityState(message.Message, metaclass=MessageMeta): + State: Incomplete + UNKNOWN: Incomplete + IDLE: Incomplete + CONNECTING: Incomplete + READY: Incomplete + TRANSIENT_FAILURE: Incomplete + SHUTDOWN: Incomplete + STATE_FIELD_NUMBER: ClassVar[int] + state: Incomplete + def __init__(self, state: Incomplete | str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelData(message.Message, metaclass=MessageMeta): + STATE_FIELD_NUMBER: ClassVar[int] + TARGET_FIELD_NUMBER: ClassVar[int] + TRACE_FIELD_NUMBER: ClassVar[int] + CALLS_STARTED_FIELD_NUMBER: ClassVar[int] + CALLS_SUCCEEDED_FIELD_NUMBER: ClassVar[int] + CALLS_FAILED_FIELD_NUMBER: ClassVar[int] + LAST_CALL_STARTED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + state: ChannelConnectivityState + target: str + trace: ChannelTrace + calls_started: int + calls_succeeded: int + calls_failed: int + last_call_started_timestamp: timestamp_pb2.Timestamp + def __init__( + self, + state: ChannelConnectivityState | Mapping[Incomplete, Incomplete] | None = ..., + target: str | None = ..., + trace: ChannelTrace | Mapping[Incomplete, Incomplete] | None = ..., + calls_started: int | None = ..., + calls_succeeded: int | None = ..., + calls_failed: int | None = ..., + last_call_started_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelTraceEvent(message.Message, metaclass=MessageMeta): + Severity: Incomplete + CT_UNKNOWN: Incomplete + CT_INFO: Incomplete + CT_WARNING: Incomplete + CT_ERROR: Incomplete + DESCRIPTION_FIELD_NUMBER: ClassVar[int] + SEVERITY_FIELD_NUMBER: ClassVar[int] + TIMESTAMP_FIELD_NUMBER: ClassVar[int] + CHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SUBCHANNEL_REF_FIELD_NUMBER: ClassVar[int] + description: str + severity: Incomplete + timestamp: timestamp_pb2.Timestamp + channel_ref: ChannelRef + subchannel_ref: SubchannelRef + def __init__( + self, + description: str | None = ..., + severity: Incomplete | str | None = ..., + timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + channel_ref: ChannelRef | Mapping[Incomplete, Incomplete] | None = ..., + subchannel_ref: SubchannelRef | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelTrace(message.Message, metaclass=MessageMeta): + NUM_EVENTS_LOGGED_FIELD_NUMBER: ClassVar[int] + CREATION_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + EVENTS_FIELD_NUMBER: ClassVar[int] + num_events_logged: int + creation_timestamp: timestamp_pb2.Timestamp + events: containers.RepeatedCompositeFieldContainer[ChannelTraceEvent] + def __init__( + self, + num_events_logged: int | None = ..., + creation_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + events: Iterable[ChannelTraceEvent | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelRef(message.Message, metaclass=MessageMeta): + CHANNEL_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + channel_id: int + name: str + def __init__(self, channel_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SubchannelRef(message.Message, metaclass=MessageMeta): + SUBCHANNEL_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + subchannel_id: int + name: str + def __init__(self, subchannel_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketRef(message.Message, metaclass=MessageMeta): + SOCKET_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + socket_id: int + name: str + def __init__(self, socket_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServerRef(message.Message, metaclass=MessageMeta): + SERVER_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + server_id: int + name: str + def __init__(self, server_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Server(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + LISTEN_SOCKET_FIELD_NUMBER: ClassVar[int] + ref: ServerRef + data: ServerData + listen_socket: containers.RepeatedCompositeFieldContainer[SocketRef] + def __init__( + self, + ref: ServerRef | Mapping[Incomplete, Incomplete] | None = ..., + data: ServerData | Mapping[Incomplete, Incomplete] | None = ..., + listen_socket: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServerData(message.Message, metaclass=MessageMeta): + TRACE_FIELD_NUMBER: ClassVar[int] + CALLS_STARTED_FIELD_NUMBER: ClassVar[int] + CALLS_SUCCEEDED_FIELD_NUMBER: ClassVar[int] + CALLS_FAILED_FIELD_NUMBER: ClassVar[int] + LAST_CALL_STARTED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + trace: ChannelTrace + calls_started: int + calls_succeeded: int + calls_failed: int + last_call_started_timestamp: timestamp_pb2.Timestamp + def __init__( + self, + trace: ChannelTrace | Mapping[Incomplete, Incomplete] | None = ..., + calls_started: int | None = ..., + calls_succeeded: int | None = ..., + calls_failed: int | None = ..., + last_call_started_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Socket(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + LOCAL_FIELD_NUMBER: ClassVar[int] + REMOTE_FIELD_NUMBER: ClassVar[int] + SECURITY_FIELD_NUMBER: ClassVar[int] + REMOTE_NAME_FIELD_NUMBER: ClassVar[int] + ref: SocketRef + data: SocketData + local: Address + remote: Address + security: Security + remote_name: str + def __init__( + self, + ref: SocketRef | Mapping[Incomplete, Incomplete] | None = ..., + data: SocketData | Mapping[Incomplete, Incomplete] | None = ..., + local: Address | Mapping[Incomplete, Incomplete] | None = ..., + remote: Address | Mapping[Incomplete, Incomplete] | None = ..., + security: Security | Mapping[Incomplete, Incomplete] | None = ..., + remote_name: str | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketData(message.Message, metaclass=MessageMeta): + STREAMS_STARTED_FIELD_NUMBER: ClassVar[int] + STREAMS_SUCCEEDED_FIELD_NUMBER: ClassVar[int] + STREAMS_FAILED_FIELD_NUMBER: ClassVar[int] + MESSAGES_SENT_FIELD_NUMBER: ClassVar[int] + MESSAGES_RECEIVED_FIELD_NUMBER: ClassVar[int] + KEEP_ALIVES_SENT_FIELD_NUMBER: ClassVar[int] + LAST_LOCAL_STREAM_CREATED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LAST_REMOTE_STREAM_CREATED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LAST_MESSAGE_SENT_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LAST_MESSAGE_RECEIVED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LOCAL_FLOW_CONTROL_WINDOW_FIELD_NUMBER: ClassVar[int] + REMOTE_FLOW_CONTROL_WINDOW_FIELD_NUMBER: ClassVar[int] + OPTION_FIELD_NUMBER: ClassVar[int] + streams_started: int + streams_succeeded: int + streams_failed: int + messages_sent: int + messages_received: int + keep_alives_sent: int + last_local_stream_created_timestamp: timestamp_pb2.Timestamp + last_remote_stream_created_timestamp: timestamp_pb2.Timestamp + last_message_sent_timestamp: timestamp_pb2.Timestamp + last_message_received_timestamp: timestamp_pb2.Timestamp + local_flow_control_window: wrappers_pb2.Int64Value + remote_flow_control_window: wrappers_pb2.Int64Value + option: containers.RepeatedCompositeFieldContainer[SocketOption] + def __init__( + self, + streams_started: int | None = ..., + streams_succeeded: int | None = ..., + streams_failed: int | None = ..., + messages_sent: int | None = ..., + messages_received: int | None = ..., + keep_alives_sent: int | None = ..., + last_local_stream_created_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + last_remote_stream_created_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + last_message_sent_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + last_message_received_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + local_flow_control_window: wrappers_pb2.Int64Value | Mapping[Incomplete, Incomplete] | None = ..., + remote_flow_control_window: wrappers_pb2.Int64Value | Mapping[Incomplete, Incomplete] | None = ..., + option: Iterable[SocketOption | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Address(message.Message, metaclass=MessageMeta): + @final + class TcpIpAddress(message.Message, metaclass=MessageMeta): + IP_ADDRESS_FIELD_NUMBER: ClassVar[int] + PORT_FIELD_NUMBER: ClassVar[int] + ip_address: bytes + port: int + def __init__(self, ip_address: bytes | None = ..., port: int | None = ...) -> None: ... + + @final + class UdsAddress(message.Message, metaclass=MessageMeta): + FILENAME_FIELD_NUMBER: ClassVar[int] + filename: str + def __init__(self, filename: str | None = ...) -> None: ... + + @final + class OtherAddress(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + VALUE_FIELD_NUMBER: ClassVar[int] + name: str + value: any_pb2.Any + def __init__(self, name: str | None = ..., value: any_pb2.Any | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + + TCPIP_ADDRESS_FIELD_NUMBER: ClassVar[int] + UDS_ADDRESS_FIELD_NUMBER: ClassVar[int] + OTHER_ADDRESS_FIELD_NUMBER: ClassVar[int] + tcpip_address: Address.TcpIpAddress + uds_address: Address.UdsAddress + other_address: Address.OtherAddress + def __init__( + self, + tcpip_address: Address.TcpIpAddress | Mapping[Incomplete, Incomplete] | None = ..., + uds_address: Address.UdsAddress | Mapping[Incomplete, Incomplete] | None = ..., + other_address: Address.OtherAddress | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Security(message.Message, metaclass=MessageMeta): + @final + class Tls(message.Message, metaclass=MessageMeta): + STANDARD_NAME_FIELD_NUMBER: ClassVar[int] + OTHER_NAME_FIELD_NUMBER: ClassVar[int] + LOCAL_CERTIFICATE_FIELD_NUMBER: ClassVar[int] + REMOTE_CERTIFICATE_FIELD_NUMBER: ClassVar[int] + standard_name: str + other_name: str + local_certificate: bytes + remote_certificate: bytes + def __init__( + self, + standard_name: str | None = ..., + other_name: str | None = ..., + local_certificate: bytes | None = ..., + remote_certificate: bytes | None = ..., + ) -> None: ... + + @final + class OtherSecurity(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + VALUE_FIELD_NUMBER: ClassVar[int] + name: str + value: any_pb2.Any + def __init__(self, name: str | None = ..., value: any_pb2.Any | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + + TLS_FIELD_NUMBER: ClassVar[int] + OTHER_FIELD_NUMBER: ClassVar[int] + tls: Security.Tls + other: Security.OtherSecurity + def __init__( + self, + tls: Security.Tls | Mapping[Incomplete, Incomplete] | None = ..., + other: Security.OtherSecurity | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOption(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + VALUE_FIELD_NUMBER: ClassVar[int] + ADDITIONAL_FIELD_NUMBER: ClassVar[int] + name: str + value: str + additional: any_pb2.Any + def __init__( + self, + name: str | None = ..., + value: str | None = ..., + additional: any_pb2.Any | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOptionTimeout(message.Message, metaclass=MessageMeta): + DURATION_FIELD_NUMBER: ClassVar[int] + duration: duration_pb2.Duration + def __init__(self, duration: duration_pb2.Duration | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOptionLinger(message.Message, metaclass=MessageMeta): + ACTIVE_FIELD_NUMBER: ClassVar[int] + DURATION_FIELD_NUMBER: ClassVar[int] + active: bool + duration: duration_pb2.Duration + def __init__( + self, active: bool = ..., duration: duration_pb2.Duration | Mapping[Incomplete, Incomplete] | None = ... + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOptionTcpInfo(message.Message, metaclass=MessageMeta): + TCPI_STATE_FIELD_NUMBER: ClassVar[int] + TCPI_CA_STATE_FIELD_NUMBER: ClassVar[int] + TCPI_RETRANSMITS_FIELD_NUMBER: ClassVar[int] + TCPI_PROBES_FIELD_NUMBER: ClassVar[int] + TCPI_BACKOFF_FIELD_NUMBER: ClassVar[int] + TCPI_OPTIONS_FIELD_NUMBER: ClassVar[int] + TCPI_SND_WSCALE_FIELD_NUMBER: ClassVar[int] + TCPI_RCV_WSCALE_FIELD_NUMBER: ClassVar[int] + TCPI_RTO_FIELD_NUMBER: ClassVar[int] + TCPI_ATO_FIELD_NUMBER: ClassVar[int] + TCPI_SND_MSS_FIELD_NUMBER: ClassVar[int] + TCPI_RCV_MSS_FIELD_NUMBER: ClassVar[int] + TCPI_UNACKED_FIELD_NUMBER: ClassVar[int] + TCPI_SACKED_FIELD_NUMBER: ClassVar[int] + TCPI_LOST_FIELD_NUMBER: ClassVar[int] + TCPI_RETRANS_FIELD_NUMBER: ClassVar[int] + TCPI_FACKETS_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_DATA_SENT_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_ACK_SENT_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_DATA_RECV_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_ACK_RECV_FIELD_NUMBER: ClassVar[int] + TCPI_PMTU_FIELD_NUMBER: ClassVar[int] + TCPI_RCV_SSTHRESH_FIELD_NUMBER: ClassVar[int] + TCPI_RTT_FIELD_NUMBER: ClassVar[int] + TCPI_RTTVAR_FIELD_NUMBER: ClassVar[int] + TCPI_SND_SSTHRESH_FIELD_NUMBER: ClassVar[int] + TCPI_SND_CWND_FIELD_NUMBER: ClassVar[int] + TCPI_ADVMSS_FIELD_NUMBER: ClassVar[int] + TCPI_REORDERING_FIELD_NUMBER: ClassVar[int] + tcpi_state: int + tcpi_ca_state: int + tcpi_retransmits: int + tcpi_probes: int + tcpi_backoff: int + tcpi_options: int + tcpi_snd_wscale: int + tcpi_rcv_wscale: int + tcpi_rto: int + tcpi_ato: int + tcpi_snd_mss: int + tcpi_rcv_mss: int + tcpi_unacked: int + tcpi_sacked: int + tcpi_lost: int + tcpi_retrans: int + tcpi_fackets: int + tcpi_last_data_sent: int + tcpi_last_ack_sent: int + tcpi_last_data_recv: int + tcpi_last_ack_recv: int + tcpi_pmtu: int + tcpi_rcv_ssthresh: int + tcpi_rtt: int + tcpi_rttvar: int + tcpi_snd_ssthresh: int + tcpi_snd_cwnd: int + tcpi_advmss: int + tcpi_reordering: int + def __init__( + self, + tcpi_state: int | None = ..., + tcpi_ca_state: int | None = ..., + tcpi_retransmits: int | None = ..., + tcpi_probes: int | None = ..., + tcpi_backoff: int | None = ..., + tcpi_options: int | None = ..., + tcpi_snd_wscale: int | None = ..., + tcpi_rcv_wscale: int | None = ..., + tcpi_rto: int | None = ..., + tcpi_ato: int | None = ..., + tcpi_snd_mss: int | None = ..., + tcpi_rcv_mss: int | None = ..., + tcpi_unacked: int | None = ..., + tcpi_sacked: int | None = ..., + tcpi_lost: int | None = ..., + tcpi_retrans: int | None = ..., + tcpi_fackets: int | None = ..., + tcpi_last_data_sent: int | None = ..., + tcpi_last_ack_sent: int | None = ..., + tcpi_last_data_recv: int | None = ..., + tcpi_last_ack_recv: int | None = ..., + tcpi_pmtu: int | None = ..., + tcpi_rcv_ssthresh: int | None = ..., + tcpi_rtt: int | None = ..., + tcpi_rttvar: int | None = ..., + tcpi_snd_ssthresh: int | None = ..., + tcpi_snd_cwnd: int | None = ..., + tcpi_advmss: int | None = ..., + tcpi_reordering: int | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetTopChannelsRequest(message.Message, metaclass=MessageMeta): + START_CHANNEL_ID_FIELD_NUMBER: ClassVar[int] + MAX_RESULTS_FIELD_NUMBER: ClassVar[int] + start_channel_id: int + max_results: int + def __init__(self, start_channel_id: int | None = ..., max_results: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetTopChannelsResponse(message.Message, metaclass=MessageMeta): + CHANNEL_FIELD_NUMBER: ClassVar[int] + END_FIELD_NUMBER: ClassVar[int] + channel: containers.RepeatedCompositeFieldContainer[Channel] + end: bool + def __init__(self, channel: Iterable[Channel | Mapping[Incomplete, Incomplete]] | None = ..., end: bool = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServersRequest(message.Message, metaclass=MessageMeta): + START_SERVER_ID_FIELD_NUMBER: ClassVar[int] + MAX_RESULTS_FIELD_NUMBER: ClassVar[int] + start_server_id: int + max_results: int + def __init__(self, start_server_id: int | None = ..., max_results: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServersResponse(message.Message, metaclass=MessageMeta): + SERVER_FIELD_NUMBER: ClassVar[int] + END_FIELD_NUMBER: ClassVar[int] + server: containers.RepeatedCompositeFieldContainer[Server] + end: bool + def __init__(self, server: Iterable[Server | Mapping[Incomplete, Incomplete]] | None = ..., end: bool = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerRequest(message.Message, metaclass=MessageMeta): + SERVER_ID_FIELD_NUMBER: ClassVar[int] + server_id: int + def __init__(self, server_id: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerResponse(message.Message, metaclass=MessageMeta): + SERVER_FIELD_NUMBER: ClassVar[int] + server: Server + def __init__(self, server: Server | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerSocketsRequest(message.Message, metaclass=MessageMeta): + SERVER_ID_FIELD_NUMBER: ClassVar[int] + START_SOCKET_ID_FIELD_NUMBER: ClassVar[int] + MAX_RESULTS_FIELD_NUMBER: ClassVar[int] + server_id: int + start_socket_id: int + max_results: int + def __init__(self, server_id: int | None = ..., start_socket_id: int | None = ..., max_results: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerSocketsResponse(message.Message, metaclass=MessageMeta): + SOCKET_REF_FIELD_NUMBER: ClassVar[int] + END_FIELD_NUMBER: ClassVar[int] + socket_ref: containers.RepeatedCompositeFieldContainer[SocketRef] + end: bool + def __init__( + self, socket_ref: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., end: bool = ... + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetChannelRequest(message.Message, metaclass=MessageMeta): + CHANNEL_ID_FIELD_NUMBER: ClassVar[int] + channel_id: int + def __init__(self, channel_id: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetChannelResponse(message.Message, metaclass=MessageMeta): + CHANNEL_FIELD_NUMBER: ClassVar[int] + channel: Channel + def __init__(self, channel: Channel | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSubchannelRequest(message.Message, metaclass=MessageMeta): + SUBCHANNEL_ID_FIELD_NUMBER: ClassVar[int] + subchannel_id: int + def __init__(self, subchannel_id: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSubchannelResponse(message.Message, metaclass=MessageMeta): + SUBCHANNEL_FIELD_NUMBER: ClassVar[int] + subchannel: Subchannel + def __init__(self, subchannel: Subchannel | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSocketRequest(message.Message, metaclass=MessageMeta): + SOCKET_ID_FIELD_NUMBER: ClassVar[int] + SUMMARY_FIELD_NUMBER: ClassVar[int] + socket_id: int + summary: bool + def __init__(self, socket_id: int | None = ..., summary: bool = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSocketResponse(message.Message, metaclass=MessageMeta): + SOCKET_FIELD_NUMBER: ClassVar[int] + socket: Socket + def __init__(self, socket: Socket | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi new file mode 100644 index 000000000000..bd6f78fecf4d --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi @@ -0,0 +1,121 @@ +from _typeshed import Incomplete +from typing import Final + +import grpc + +GRPC_GENERATED_VERSION: Final[str] +GRPC_VERSION: Final[str] + +class ChannelzStub: + GetTopChannels: Incomplete + GetServers: Incomplete + GetServer: Incomplete + GetServerSockets: Incomplete + GetChannel: Incomplete + GetSubchannel: Incomplete + GetSocket: Incomplete + def __init__(self, channel: grpc.Channel): ... + +class ChannelzServicer: + def GetTopChannels(self, request, context): ... + def GetServers(self, request, context): ... + def GetServer(self, request, context): ... + def GetServerSockets(self, request, context): ... + def GetChannel(self, request, context): ... + def GetSubchannel(self, request, context): ... + def GetSocket(self, request, context): ... + +def add_ChannelzServicer_to_server(servicer, server) -> None: ... + +class Channelz: + @staticmethod + def GetTopChannels( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetServers( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetServer( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetServerSockets( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetChannel( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetSubchannel( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetSocket( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... diff --git a/stubs/grpcio-health-checking/METADATA.toml b/stubs/grpcio-health-checking/METADATA.toml new file mode 100644 index 000000000000..b12e58c39175 --- /dev/null +++ b/stubs/grpcio-health-checking/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio", "types-protobuf"] diff --git a/stdlib/@python2/distutils/command/build.pyi b/stubs/grpcio-health-checking/grpc_health/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/build.pyi rename to stubs/grpcio-health-checking/grpc_health/__init__.pyi diff --git a/stdlib/@python2/distutils/command/build_clib.pyi b/stubs/grpcio-health-checking/grpc_health/v1/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/build_clib.pyi rename to stubs/grpcio-health-checking/grpc_health/v1/__init__.pyi diff --git a/stubs/grpcio-health-checking/grpc_health/v1/health.pyi b/stubs/grpcio-health-checking/grpc_health/v1/health.pyi new file mode 100644 index 000000000000..e98ffdbcd980 --- /dev/null +++ b/stubs/grpcio-health-checking/grpc_health/v1/health.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from concurrent import futures +from typing import Final, overload +from typing_extensions import Self + +from grpc import ServicerContext +from grpc_health.v1 import health_pb2, health_pb2_grpc + +SERVICE_NAME: Final[str] +OVERALL_HEALTH: Final[str] + +class _Watcher: + def __init__(self) -> None: ... + def __iter__(self) -> Self: ... + def next(self) -> health_pb2.HealthCheckResponse: ... + def __next__(self) -> health_pb2.HealthCheckResponse: ... + def add(self, response: health_pb2.HealthCheckResponse) -> None: ... + def close(self) -> None: ... + +class HealthServicer(health_pb2_grpc.HealthServicer): + def __init__( + self, experimental_non_blocking: bool = True, experimental_thread_pool: futures.ThreadPoolExecutor | None = None + ) -> None: ... + def Check(self, request: health_pb2.HealthCheckRequest, context: ServicerContext) -> health_pb2.HealthCheckResponse: ... + + @overload + def Watch( + self, request: health_pb2.HealthCheckRequest, context: ServicerContext, send_response_callback: None = None + ) -> _Watcher: ... + @overload + def Watch( + self, request: health_pb2.HealthCheckRequest, context: ServicerContext, send_response_callback: Callable[..., Incomplete] + ) -> None: ... + + def set(self, service: str, status: health_pb2.HealthCheckResponse.ServingStatus) -> None: ... + def enter_graceful_shutdown(self) -> None: ... diff --git a/stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi new file mode 100644 index 000000000000..82191f79b659 --- /dev/null +++ b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from typing import ClassVar, final + +from google._upb._message import Descriptor, FileDescriptor, MessageMeta +from google.protobuf import message + +DESCRIPTOR: FileDescriptor + +@final +class HealthCheckRequest(message.Message, metaclass=MessageMeta): + SERVICE_FIELD_NUMBER: ClassVar[int] + service: str + def __init__(self, service: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class HealthCheckResponse(message.Message, metaclass=MessageMeta): + ServingStatus: Incomplete + UNKNOWN: Incomplete + SERVING: Incomplete + NOT_SERVING: Incomplete + SERVICE_UNKNOWN: Incomplete + STATUS_FIELD_NUMBER: ClassVar[int] + status: Incomplete + def __init__(self, status: Incomplete | str | None = ...) -> None: ... + DESCRIPTOR: Descriptor diff --git a/stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi new file mode 100644 index 000000000000..8170664f0cb1 --- /dev/null +++ b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi @@ -0,0 +1,41 @@ +from typing import Final + +GRPC_GENERATED_VERSION: Final[str] +GRPC_VERSION: Final[str] + +class HealthStub: + def __init__(self, channel) -> None: ... + +class HealthServicer: + def Check(self, request, context): ... + def Watch(self, request, context): ... + +def add_HealthServicer_to_server(servicer, server) -> None: ... + +class Health: + @staticmethod + def Check( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def Watch( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... diff --git a/stubs/grpcio-reflection/@tests/test_cases/check_reflection.py b/stubs/grpcio-reflection/@tests/test_cases/check_reflection.py new file mode 100644 index 000000000000..5287283960a8 --- /dev/null +++ b/stubs/grpcio-reflection/@tests/test_cases/check_reflection.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from typing import cast + +import grpc +from grpc_reflection.v1alpha.reflection import enable_server_reflection + +server = cast(grpc.Server, None) +enable_server_reflection(["foo"], server, None) diff --git a/stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py b/stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py new file mode 100644 index 000000000000..80d4054cc123 --- /dev/null +++ b/stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from typing import cast + +import grpc.aio +from grpc_reflection.v1alpha.reflection import enable_server_reflection + +server = cast(grpc.aio.Server, None) +enable_server_reflection(["foo"], server, None) diff --git a/stubs/grpcio-reflection/METADATA.toml b/stubs/grpcio-reflection/METADATA.toml new file mode 100644 index 000000000000..b12e58c39175 --- /dev/null +++ b/stubs/grpcio-reflection/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio", "types-protobuf"] diff --git a/stdlib/@python2/distutils/command/build_ext.pyi b/stubs/grpcio-reflection/grpc_reflection/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/build_ext.pyi rename to stubs/grpcio-reflection/grpc_reflection/__init__.pyi diff --git a/stdlib/@python2/distutils/command/build_scripts.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/build_scripts.pyi rename to stubs/grpcio-reflection/grpc_reflection/v1alpha/__init__.pyi diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi new file mode 100644 index 000000000000..39fa94fe1d91 --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi @@ -0,0 +1,11 @@ +from collections.abc import AsyncIterable + +from grpc_reflection.v1alpha import reflection_pb2 +from grpc_reflection.v1alpha._base import BaseReflectionServicer + +class ReflectionServicer(BaseReflectionServicer): + async def ServerReflectionInfo( + self, request_iterator: AsyncIterable[reflection_pb2.ServerReflectionRequest], unused_context + ) -> AsyncIterable[reflection_pb2.ServerReflectionResponse]: ... + +__all__ = ["ReflectionServicer"] diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi new file mode 100644 index 000000000000..e808f4a9147a --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi @@ -0,0 +1,6 @@ +from grpc_reflection.v1alpha import reflection_pb2_grpc + +class BaseReflectionServicer(reflection_pb2_grpc.ServerReflectionServicer): + def __init__(self, service_names, pool=None) -> None: ... + +__all__ = ["BaseReflectionServicer"] diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi new file mode 100644 index 000000000000..e41b1edb0bab --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi @@ -0,0 +1,11 @@ +import grpc +from google.protobuf.descriptor_database import DescriptorDatabase +from google.protobuf.descriptor_pb2 import FileDescriptorProto + +class ProtoReflectionDescriptorDatabase(DescriptorDatabase): + def __init__(self, channel: grpc.Channel) -> None: ... + def get_services(self) -> list[str]: ... + def FindFileByName(self, name: str) -> FileDescriptorProto: ... + def FindFileContainingSymbol(self, symbol: str) -> FileDescriptorProto: ... + def FindAllExtensionNumbers(self, extendee_name: str) -> list[int]: ... + def FindFileContainingExtension(self, extendee_name: str, extension_number: int) -> FileDescriptorProto: ... diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi new file mode 100644 index 000000000000..0c00500de3a7 --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Final, TypeAlias + +import grpc +import grpc.aio +from google.protobuf import descriptor_pool +from grpc_reflection.v1alpha import reflection_pb2 as _reflection_pb2 +from grpc_reflection.v1alpha._base import BaseReflectionServicer + +from . import _async as aio + +SERVICE_NAME: Final[str] + +_AnyServer: TypeAlias = grpc.Server | grpc.aio.Server +_AnyServicerContext: TypeAlias = grpc.ServicerContext | grpc.aio.ServicerContext[Incomplete, Incomplete] + +class ReflectionServicer(BaseReflectionServicer): + def ServerReflectionInfo( + self, request_iterator: Iterable[_reflection_pb2.ServerReflectionRequest], context: _AnyServicerContext + ): ... + +def enable_server_reflection( + service_names: Iterable[str], server: _AnyServer, pool: descriptor_pool.DescriptorPool | None = None +) -> None: ... + +__all__ = ["SERVICE_NAME", "ReflectionServicer", "enable_server_reflection", "aio"] diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi new file mode 100644 index 000000000000..94f335771385 --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import ClassVar, final + +from google._upb._message import Descriptor, FileDescriptor, MessageMeta +from google.protobuf import message +from google.protobuf.internal import containers + +DESCRIPTOR: FileDescriptor + +@final +class ServerReflectionRequest(message.Message, metaclass=MessageMeta): + HOST_FIELD_NUMBER: ClassVar[int] + FILE_BY_FILENAME_FIELD_NUMBER: ClassVar[int] + FILE_CONTAINING_SYMBOL_FIELD_NUMBER: ClassVar[int] + FILE_CONTAINING_EXTENSION_FIELD_NUMBER: ClassVar[int] + ALL_EXTENSION_NUMBERS_OF_TYPE_FIELD_NUMBER: ClassVar[int] + LIST_SERVICES_FIELD_NUMBER: ClassVar[int] + host: str + file_by_filename: str + file_containing_symbol: str + file_containing_extension: ExtensionRequest + all_extension_numbers_of_type: str + list_services: str + def __init__( + self, + host: str | None = ..., + file_by_filename: str | None = ..., + file_containing_symbol: str | None = ..., + file_containing_extension: ExtensionRequest | Mapping[Incomplete, Incomplete] | None = ..., + all_extension_numbers_of_type: str | None = ..., + list_services: str | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ExtensionRequest(message.Message, metaclass=MessageMeta): + CONTAINING_TYPE_FIELD_NUMBER: ClassVar[int] + EXTENSION_NUMBER_FIELD_NUMBER: ClassVar[int] + containing_type: str + extension_number: int + def __init__(self, containing_type: str | None = ..., extension_number: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServerReflectionResponse(message.Message, metaclass=MessageMeta): + VALID_HOST_FIELD_NUMBER: ClassVar[int] + ORIGINAL_REQUEST_FIELD_NUMBER: ClassVar[int] + FILE_DESCRIPTOR_RESPONSE_FIELD_NUMBER: ClassVar[int] + ALL_EXTENSION_NUMBERS_RESPONSE_FIELD_NUMBER: ClassVar[int] + LIST_SERVICES_RESPONSE_FIELD_NUMBER: ClassVar[int] + ERROR_RESPONSE_FIELD_NUMBER: ClassVar[int] + valid_host: str + original_request: ServerReflectionRequest + file_descriptor_response: FileDescriptorResponse + all_extension_numbers_response: ExtensionNumberResponse + list_services_response: ListServiceResponse + error_response: ErrorResponse + def __init__( + self, + valid_host: str | None = ..., + original_request: ServerReflectionRequest | Mapping[Incomplete, Incomplete] | None = ..., + file_descriptor_response: FileDescriptorResponse | Mapping[Incomplete, Incomplete] | None = ..., + all_extension_numbers_response: ExtensionNumberResponse | Mapping[Incomplete, Incomplete] | None = ..., + list_services_response: ListServiceResponse | Mapping[Incomplete, Incomplete] | None = ..., + error_response: ErrorResponse | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class FileDescriptorResponse(message.Message, metaclass=MessageMeta): + FILE_DESCRIPTOR_PROTO_FIELD_NUMBER: ClassVar[int] + file_descriptor_proto: containers.RepeatedScalarFieldContainer[bytes] + def __init__(self, file_descriptor_proto: Iterable[bytes] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ExtensionNumberResponse(message.Message, metaclass=MessageMeta): + BASE_TYPE_NAME_FIELD_NUMBER: ClassVar[int] + EXTENSION_NUMBER_FIELD_NUMBER: ClassVar[int] + base_type_name: str + extension_number: containers.RepeatedScalarFieldContainer[int] + def __init__(self, base_type_name: str | None = ..., extension_number: Iterable[int] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ListServiceResponse(message.Message, metaclass=MessageMeta): + SERVICE_FIELD_NUMBER: ClassVar[int] + service: containers.RepeatedCompositeFieldContainer[ServiceResponse] + def __init__(self, service: Iterable[ServiceResponse | Mapping[Incomplete, Incomplete]] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServiceResponse(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + name: str + def __init__(self, name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ErrorResponse(message.Message, metaclass=MessageMeta): + ERROR_CODE_FIELD_NUMBER: ClassVar[int] + ERROR_MESSAGE_FIELD_NUMBER: ClassVar[int] + error_code: int + error_message: str + def __init__(self, error_code: int | None = ..., error_message: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi new file mode 100644 index 000000000000..31b983b4f82c --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi @@ -0,0 +1,31 @@ +from binascii import Incomplete +from typing import Final + +import grpc + +GRPC_GENERATED_VERSION: Final[str] +GRPC_VERSION: Final[str] + +class ServerReflectionStub: + ServerReflectionInfo: Incomplete + def __init__(self, channel: grpc.Channel) -> None: ... + +class ServerReflectionServicer: + def ServerReflectionInfo(self, request_iterator, context): ... + +def add_ServerReflectionServicer_to_server(servicer, server): ... + +class ServerReflection: + @staticmethod + def ServerReflectionInfo( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... diff --git a/stubs/grpcio-status/METADATA.toml b/stubs/grpcio-status/METADATA.toml new file mode 100644 index 000000000000..3591441645d2 --- /dev/null +++ b/stubs/grpcio-status/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio"] diff --git a/stdlib/@python2/distutils/command/check.pyi b/stubs/grpcio-status/grpc_status/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/check.pyi rename to stubs/grpcio-status/grpc_status/__init__.pyi diff --git a/stubs/grpcio-status/grpc_status/_async.pyi b/stubs/grpcio-status/grpc_status/_async.pyi new file mode 100644 index 000000000000..a636b3f59f20 --- /dev/null +++ b/stubs/grpcio-status/grpc_status/_async.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +async def from_call(call) -> Incomplete | None: ... + +__all__ = ["from_call"] diff --git a/stubs/grpcio-status/grpc_status/rpc_status.pyi b/stubs/grpcio-status/grpc_status/rpc_status.pyi new file mode 100644 index 000000000000..e2e0204167f5 --- /dev/null +++ b/stubs/grpcio-status/grpc_status/rpc_status.pyi @@ -0,0 +1,11 @@ +import grpc + +from . import _async as aio + +# Returns a google.rpc.status.Status message corresponding to a given grpc.Call. +def from_call(call: grpc.Call): ... + +# Convert a google.rpc.status.Status message to grpc.Status. +def to_status(status) -> grpc.Status: ... + +__all__ = ["from_call", "to_status", "aio"] diff --git a/stubs/grpcio/@tests/stubtest_allowlist.txt b/stubs/grpcio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3409137cfdce --- /dev/null +++ b/stubs/grpcio/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Error: is not present at runtime +# ============================= +# Error class attributes that aren't defined. +grpc.RpcError.code +grpc.RpcError.details +grpc.RpcError.trailing_metadata diff --git a/stubs/grpcio/@tests/test_cases/check_aio.py b/stubs/grpcio/@tests/test_cases/check_aio.py new file mode 100644 index 000000000000..f76a34987cb5 --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_aio.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import cast +from typing_extensions import assert_type + +import grpc.aio + +# Interceptor casts +client_interceptors: list[grpc.aio.ClientInterceptor] = [] +grpc.aio.insecure_channel("target", interceptors=client_interceptors) + +server_interceptors: list[grpc.aio.ServerInterceptor] = [] +grpc.aio.server(interceptors=server_interceptors) + + +# Metadata +async def metadata() -> None: + metadata = await cast(grpc.aio.Call, None).initial_metadata() + assert_type(metadata["foo"], grpc.aio._MetadataValue) + # grpc.aio.Metadata is a Collection that iterates as (key, value) tuples, + # not a Mapping that iterates bare keys. + for key, value in metadata: + assert_type(key, str) + assert_type(value, grpc.aio._MetadataValue) diff --git a/stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py b/stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py new file mode 100644 index 000000000000..36fb5870380b --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import Protocol, cast +from typing_extensions import assert_type + +import grpc.aio + + +class DummyRequest: + pass + + +class DummyReply: + pass + + +class DummyServiceStub(Protocol): + UnaryUnary: grpc.aio.UnaryUnaryMultiCallable[DummyRequest, DummyReply] + UnaryStream: grpc.aio.UnaryStreamMultiCallable[DummyRequest, DummyReply] + StreamUnary: grpc.aio.StreamUnaryMultiCallable[DummyRequest, DummyReply] + StreamStream: grpc.aio.StreamStreamMultiCallable[DummyRequest, DummyReply] + + +stub = cast(DummyServiceStub, None) +req = DummyRequest() + + +async def async_context() -> None: + assert_type(await stub.UnaryUnary(req), DummyReply) + + async for resp in stub.UnaryStream(req): + assert_type(resp, DummyReply) + + assert_type(await stub.StreamUnary(iter([req])), DummyReply) + + async for resp in stub.StreamStream(iter([req])): + assert_type(resp, DummyReply) diff --git a/stubs/grpcio/@tests/test_cases/check_grpc.py b/stubs/grpcio/@tests/test_cases/check_grpc.py new file mode 100644 index 000000000000..4ff365685afc --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_grpc.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Optional, cast +from typing_extensions import assert_type + +import grpc + +# Channel options: +assert_type(grpc.insecure_channel("target", ()), grpc.Channel) +assert_type(grpc.insecure_channel("target", (("a", "b"),)), grpc.Channel) +assert_type(grpc.insecure_channel("target", (("a", "b"), ("c", "d"))), grpc.Channel) + +# Local channel credentials: +creds = grpc.local_channel_credentials(grpc.LocalConnectionType.LOCAL_TCP) +assert_type(creds, grpc.ChannelCredentials) + +# Other credential types: +assert_type(grpc.alts_channel_credentials(), grpc.ChannelCredentials) +assert_type(grpc.alts_server_credentials(), grpc.ServerCredentials) +assert_type(grpc.compute_engine_channel_credentials(grpc.CallCredentials("")), grpc.ChannelCredentials) +assert_type(grpc.insecure_server_credentials(), grpc.ServerCredentials) + +# XDS credentials: +assert_type( + grpc.xds_channel_credentials(grpc.local_channel_credentials(grpc.LocalConnectionType.LOCAL_TCP)), grpc.ChannelCredentials +) +assert_type(grpc.xds_server_credentials(grpc.insecure_server_credentials()), grpc.ServerCredentials) + +# Channel ready future +channel = grpc.insecure_channel("target", ()) +assert_type(grpc.channel_ready_future(channel).result(), None) + +# Channel options supports list: +assert_type(grpc.insecure_channel("target", []), grpc.Channel) +assert_type(grpc.insecure_channel("target", [("a", "b")]), grpc.Channel) +assert_type(grpc.insecure_channel("target", [("a", "b"), ("c", "d")]), grpc.Channel) + +# Client call details optionals: +call_details = grpc.ClientCallDetails() +assert_type(call_details.method, str) +assert_type(call_details.timeout, Optional[float]) + +# Call iterator +call_iter = cast(grpc._CallIterator[str], None) +for call in call_iter: + assert_type(call, str) +assert_type(next(call_iter), str) diff --git a/stubs/grpcio/@tests/test_cases/check_handler_inheritance.py b/stubs/grpcio/@tests/test_cases/check_handler_inheritance.py new file mode 100644 index 000000000000..ce74855fa76d --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_handler_inheritance.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import Any, cast +from typing_extensions import assert_type + +import grpc + + +class Request: + pass + + +class Response: + pass + + +def unary_unary_call(rq: Request, ctx: grpc.ServicerContext) -> Response: + assert_type(rq, Request) + return Response() + + +class ServiceHandler(grpc.ServiceRpcHandler): + def service_name(self) -> str: + return "hello" + + def service(self, handler_call_details: grpc.HandlerCallDetails) -> grpc.RpcMethodHandler[Any, Any] | None: + rpc = grpc.RpcMethodHandler[Request, Response]() + rpc.unary_unary = unary_unary_call + return rpc + + +h = ServiceHandler() +hcd = cast(grpc.HandlerCallDetails, None) +ctx = cast(grpc.ServicerContext, None) +svc = h.service(hcd) +if svc is not None and svc.unary_unary is not None: + svc.unary_unary(Request(), ctx) diff --git a/stubs/grpcio/@tests/test_cases/check_multi_callable.py b/stubs/grpcio/@tests/test_cases/check_multi_callable.py new file mode 100644 index 000000000000..254d60b2a228 --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_multi_callable.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import Protocol, cast +from typing_extensions import assert_type + +import grpc + + +class DummyRequest: + pass + + +class DummyReply: + pass + + +class DummyServiceStub(Protocol): + UnaryUnary: grpc.UnaryUnaryMultiCallable[DummyRequest, DummyReply] + UnaryStream: grpc.UnaryStreamMultiCallable[DummyRequest, DummyReply] + StreamUnary: grpc.StreamUnaryMultiCallable[DummyRequest, DummyReply] + StreamStream: grpc.StreamStreamMultiCallable[DummyRequest, DummyReply] + + +stub = cast(DummyServiceStub, None) +req = DummyRequest() + +assert_type(stub.UnaryUnary(req), DummyReply) + +for resp in stub.UnaryStream(req): + assert_type(resp, DummyReply) + +assert_type(stub.StreamUnary(iter([req])), DummyReply) + +for resp in stub.StreamStream(iter([req])): + assert_type(resp, DummyReply) diff --git a/stubs/grpcio/@tests/test_cases/check_register.py b/stubs/grpcio/@tests/test_cases/check_register.py new file mode 100644 index 000000000000..b68daa523e7a --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_register.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from typing import Any + +import grpc + + +@grpc.Call.register +class CallProxy: + def __init__(self, target: grpc.Call) -> None: + self._target = target + + def __getattr__(self, name: str) -> Any: + return getattr(self._target, name) diff --git a/stubs/grpcio/@tests/test_cases/check_server_interceptor.py b/stubs/grpcio/@tests/test_cases/check_server_interceptor.py new file mode 100644 index 000000000000..893ff591fb52 --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_server_interceptor.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from collections.abc import Callable +from concurrent.futures.thread import ThreadPoolExecutor +from typing import Awaitable, TypeVar + +import grpc +import grpc.aio + +RequestT = TypeVar("RequestT") +ResponseT = TypeVar("ResponseT") + + +class NoopInterceptor(grpc.ServerInterceptor): + def intercept_service( + self, + continuation: Callable[[grpc.HandlerCallDetails], grpc.RpcMethodHandler[RequestT, ResponseT] | None], + handler_call_details: grpc.HandlerCallDetails, + ) -> grpc.RpcMethodHandler[RequestT, ResponseT] | None: + return continuation(handler_call_details) + + +grpc.server(interceptors=[NoopInterceptor()], thread_pool=ThreadPoolExecutor()) + + +class NoopAioInterceptor(grpc.aio.ServerInterceptor): + async def intercept_service( + self, + continuation: Callable[[grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler[RequestT, ResponseT] | None]], + handler_call_details: grpc.HandlerCallDetails, + ) -> grpc.RpcMethodHandler[RequestT, ResponseT] | None: + return await continuation(handler_call_details) + + +grpc.aio.server(interceptors=[NoopAioInterceptor()]) diff --git a/stubs/grpcio/METADATA.toml b/stubs/grpcio/METADATA.toml new file mode 100644 index 000000000000..cd3f42a9af3b --- /dev/null +++ b/stubs/grpcio/METADATA.toml @@ -0,0 +1,6 @@ +version = "~=1.84.0" +upstream-repository = "https://github.com/grpc/grpc" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/grpcio/grpc/__init__.pyi b/stubs/grpcio/grpc/__init__.pyi new file mode 100644 index 000000000000..bd0210796ec4 --- /dev/null +++ b/stubs/grpcio/grpc/__init__.pyi @@ -0,0 +1,611 @@ +import abc +import enum +import threading +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from concurrent import futures +from types import ModuleType, TracebackType +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, runtime_checkable, type_check_only +from typing_extensions import Never, Self + +from . import aio as aio + +__version__: str + +_T = TypeVar("_T") + +# XXX: Early attempts to tame this used literals for all the keys (gRPC is +# a bit segfaulty and doesn't adequately validate the option keys), but that +# didn't quite work out. Maybe it's something we can come back to +_OptionKeyValue: TypeAlias = tuple[str, Any] +_Options: TypeAlias = Sequence[_OptionKeyValue] + +class Compression(enum.IntEnum): + NoCompression = 0 + Deflate = 1 + Gzip = 2 + +@enum.unique +class LocalConnectionType(enum.Enum): + UDS = 0 + LOCAL_TCP = 1 + +# XXX: not documented, needs more investigation. +# Some evidence: +# - https://github.com/grpc/grpc/blob/0e1984effd7e977ef18f1ad7fde7d10a2a153e1d/src/python/grpcio_tests/tests/unit/_metadata_test.py#L71 +# - https://github.com/grpc/grpc/blob/0e1984effd7e977ef18f1ad7fde7d10a2a153e1d/src/python/grpcio_tests/tests/unit/_metadata_test.py#L58 +# - https://github.com/grpc/grpc/blob/0e1984effd7e977ef18f1ad7fde7d10a2a153e1d/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py#L66 +_Metadata: TypeAlias = tuple[tuple[str, str | bytes], ...] + +_TRequest = TypeVar("_TRequest") +_TResponse = TypeVar("_TResponse") +_Serializer: TypeAlias = Callable[[_T], bytes] +_Deserializer: TypeAlias = Callable[[bytes], _T] + +# Future Interfaces: + +class FutureTimeoutError(Exception): ... +class FutureCancelledError(Exception): ... + +_TFutureValue = TypeVar("_TFutureValue") + +class Future(abc.ABC, Generic[_TFutureValue]): + @abc.abstractmethod + def add_done_callback(self, fn: Callable[[Future[_TFutureValue]], None]) -> None: ... + @abc.abstractmethod + def cancel(self) -> bool: ... + @abc.abstractmethod + def cancelled(self) -> bool: ... + @abc.abstractmethod + def done(self) -> bool: ... + @abc.abstractmethod + def exception(self, timeout: float | None = None) -> Exception | None: ... + @abc.abstractmethod + def result(self, timeout: float | None = None) -> _TFutureValue: ... + @abc.abstractmethod + def running(self) -> bool: ... + + # FIXME: unsure of the exact return type here. Is it a traceback.StackSummary? + @abc.abstractmethod + def traceback(self, timeout: float | None = None): ... + +# Create Client: + +def insecure_channel(target: str, options: _Options | None = None, compression: Compression | None = None) -> Channel: ... +def secure_channel( + target: str, credentials: ChannelCredentials, options: _Options | None = None, compression: Compression | None = None +) -> Channel: ... + +_Interceptor: TypeAlias = ( + UnaryUnaryClientInterceptor | UnaryStreamClientInterceptor | StreamUnaryClientInterceptor | StreamStreamClientInterceptor +) + +def intercept_channel(channel: Channel, *interceptors: _Interceptor) -> Channel: ... + +# Create Client Credentials: + +def ssl_channel_credentials( + root_certificates: bytes | None = None, private_key: bytes | None = None, certificate_chain: bytes | None = None +) -> ChannelCredentials: ... +def local_channel_credentials(local_connect_type: LocalConnectionType = ...) -> ChannelCredentials: ... +def metadata_call_credentials(metadata_plugin: AuthMetadataPlugin, name: str | None = None) -> CallCredentials: ... +def access_token_call_credentials(access_token: str) -> CallCredentials: ... +def alts_channel_credentials(service_accounts: Sequence[str] | None = None) -> ChannelCredentials: ... +def compute_engine_channel_credentials(call_credentials: CallCredentials) -> ChannelCredentials: ... +def xds_channel_credentials(fallback_credentials: ChannelCredentials | None = None) -> ChannelCredentials: ... + +# GRPC docs say there should be at least two: +def composite_call_credentials(creds1: CallCredentials, creds2: CallCredentials, *rest: CallCredentials) -> CallCredentials: ... + +# Compose a ChannelCredentials and one or more CallCredentials objects. +def composite_channel_credentials( + channel_credentials: ChannelCredentials, call_credentials: CallCredentials, *rest: CallCredentials +) -> ChannelCredentials: ... + +# Create Server: + +def server( + thread_pool: futures.ThreadPoolExecutor, + handlers: list[GenericRpcHandler] | None = None, + interceptors: list[ServerInterceptor] | None = None, + options: _Options | None = None, + maximum_concurrent_rpcs: int | None = None, + compression: Compression | None = None, + xds: bool = False, +) -> Server: ... + +# Create Server Credentials: + +_CertificateChainPair: TypeAlias = tuple[bytes, bytes] + +def ssl_server_credentials( + private_key_certificate_chain_pairs: list[_CertificateChainPair], + root_certificates: bytes | None = None, + require_client_auth: bool = False, +) -> ServerCredentials: ... +def local_server_credentials(local_connect_type: LocalConnectionType = ...) -> ServerCredentials: ... +def ssl_server_certificate_configuration( + private_key_certificate_chain_pairs: list[_CertificateChainPair], root_certificates: bytes | None = None +) -> ServerCertificateConfiguration: ... +def dynamic_ssl_server_credentials( + initial_certificate_configuration: ServerCertificateConfiguration, + certificate_configuration_fetcher: Callable[[], ServerCertificateConfiguration], + require_client_authentication: bool = False, +) -> ServerCredentials: ... +def alts_server_credentials() -> ServerCredentials: ... +def insecure_server_credentials() -> ServerCredentials: ... +def xds_server_credentials(fallback_credentials: ServerCredentials) -> ServerCredentials: ... + +# RPC Method Handlers: + +# XXX: This is probably what appears in the add_FooServicer_to_server function +# in the _pb2_grpc files that get generated, which points to the FooServicer +# handler functions that get generated, which look like this: +# +# def FloobDoob(self, request, context): +# return response +# +@type_check_only +class _Behaviour(Protocol): + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +def unary_unary_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def unary_stream_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def stream_unary_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def stream_stream_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def method_handlers_generic_handler( + service: str, method_handlers: dict[str, RpcMethodHandler[Any, Any]] +) -> GenericRpcHandler: ... + +# Channel Ready Future: + +def channel_ready_future(channel: Channel) -> Future[None]: ... + +# Channel Connectivity: + +class ChannelConnectivity(enum.Enum): + IDLE = (0, "idle") + CONNECTING = (1, "connecting") + READY = (2, "ready") + TRANSIENT_FAILURE = (3, "transient failure") + SHUTDOWN = (4, "shutdown") + +# gRPC Status Code: + +class Status(abc.ABC): + code: StatusCode + + # XXX: misnamed property, does not align with status.proto, where it is called 'message': + details: str + + trailing_metadata: _Metadata + +# https://grpc.github.io/grpc/core/md_doc_statuscodes.html +class StatusCode(enum.Enum): + OK = (0, "ok") + CANCELLED = (1, "cancelled") + UNKNOWN = (2, "unknown") + INVALID_ARGUMENT = (3, "invalid argument") + DEADLINE_EXCEEDED = (4, "deadline exceeded") + NOT_FOUND = (5, "not found") + ALREADY_EXISTS = (6, "already exists") + PERMISSION_DENIED = (7, "permission denied") + RESOURCE_EXHAUSTED = (8, "resource exhausted") + FAILED_PRECONDITION = (9, "failed precondition") + ABORTED = (10, "aborted") + OUT_OF_RANGE = (11, "out of range") + UNIMPLEMENTED = (12, "unimplemented") + INTERNAL = (13, "internal") + UNAVAILABLE = (14, "unavailable") + DATA_LOSS = (15, "data loss") + UNAUTHENTICATED = (16, "unauthenticated") + +# Channel Object: + +class Channel(abc.ABC): + @abc.abstractmethod + def close(self) -> None: ... + @abc.abstractmethod + def stream_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def stream_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def subscribe(self, callback: Callable[[ChannelConnectivity], None], try_to_connect: bool = False) -> None: ... + @abc.abstractmethod + def unary_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unary_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unsubscribe(self, callback: Callable[[ChannelConnectivity], None]) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + +# Server Object: + +class Server(abc.ABC): + @abc.abstractmethod + def add_generic_rpc_handlers(self, generic_rpc_handlers: Iterable[GenericRpcHandler]) -> None: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_insecure_port(self, address: str) -> int: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_secure_port(self, address: str, server_credentials: ServerCredentials) -> int: ... + @abc.abstractmethod + def start(self) -> None: ... + + # Grace period is in seconds. + @abc.abstractmethod + def stop(self, grace: float | None) -> threading.Event: ... + + # Block current thread until the server stops. Returns a bool + # indicates if the operation times out. Timeout is in seconds. + def wait_for_termination(self, timeout: float | None = None) -> bool: ... + +# Authentication & Authorization Objects: + +# This class has no supported interface +class ChannelCredentials: + def __init__(self, credentials) -> None: ... + +# This class has no supported interface +class CallCredentials: + def __init__(self, credentials) -> None: ... + +class AuthMetadataContext(abc.ABC): + service_url: str + method_name: str + +class AuthMetadataPluginCallback(abc.ABC): + def __call__(self, metadata: _Metadata, error: Exception | None) -> None: ... + +class AuthMetadataPlugin(abc.ABC): + def __call__(self, context: AuthMetadataContext, callback: AuthMetadataPluginCallback) -> None: ... + +# This class has no supported interface +class ServerCredentials: + def __init__(self, credentials) -> None: ... + +# This class has no supported interface +class ServerCertificateConfiguration: + def __init__(self, certificate_configuration) -> None: ... + +# gRPC Exceptions: + +@type_check_only +class _Metadatum: + key: str + value: bytes + +# FIXME: There is scant documentation about what is actually available in this type. +# The properties here are the properties observed in the wild, and may be inaccurate. +# A better source to confirm their presence needs to be found at some point. +class RpcError(Exception): + def code(self) -> StatusCode: ... + + # misnamed property, does not align with status.proto, where it is called 'message': + def details(self) -> str | None: ... + + # XXX: This has a slightly different return type to all the other metadata: + def trailing_metadata(self) -> tuple[_Metadatum, ...]: ... + +# Shared Context: + +class RpcContext(abc.ABC): + @abc.abstractmethod + def add_callback(self, callback: Callable[[], None]) -> bool: ... + @abc.abstractmethod + def cancel(self) -> bool: ... + @abc.abstractmethod + def is_active(self) -> bool: ... + @abc.abstractmethod + def time_remaining(self) -> float: ... + +# Client-Side Context: + +class Call(RpcContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def code(self) -> StatusCode: ... + + # misnamed property, does not align with status.proto, where it is called 'message': + @abc.abstractmethod + def details(self) -> str: ... + @abc.abstractmethod + def initial_metadata(self) -> _Metadata: ... + @abc.abstractmethod + def trailing_metadata(self) -> _Metadata: ... + +# Client-Side Interceptor: + +class ClientCallDetails(abc.ABC): + method: str + timeout: float | None + metadata: _Metadata | None + credentials: CallCredentials | None + + # "This is an EXPERIMENTAL argument. An optional flag t enable wait for ready mechanism." + wait_for_ready: bool | None + + compression: Compression | None + +# An object that is both a Call for the RPC and a Future. In the event of +# RPC completion, the return Call-Future's result value will be the +# response message of the RPC. Should the event terminate with non-OK +# status, the returned Call-Future's exception value will be an RpcError. +# +@type_check_only +class _CallFuture(Call, Future[_TResponse], metaclass=abc.ABCMeta): ... + +class UnaryUnaryClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request)`. + @abc.abstractmethod + def intercept_unary_unary( + self, + continuation: Callable[[ClientCallDetails, _TRequest], _CallFuture[_TResponse]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> _CallFuture[_TResponse]: ... + +@type_check_only +class _CallIterator(Call, Generic[_TResponse], metaclass=abc.ABCMeta): + def __iter__(self) -> Iterator[_TResponse]: ... + def __next__(self) -> _TResponse: ... + +class UnaryStreamClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request)`. + @abc.abstractmethod + def intercept_unary_stream( + self, + continuation: Callable[[ClientCallDetails, _TRequest], _CallIterator[_TResponse]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> _CallIterator[_TResponse]: ... + +class StreamUnaryClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + def intercept_stream_unary( + self, + continuation: Callable[[ClientCallDetails, Iterator[_TRequest]], _CallFuture[_TResponse]], + client_call_details: ClientCallDetails, + request_iterator: Iterator[_TRequest], + ) -> _CallFuture[_TResponse]: ... + +class StreamStreamClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + def intercept_stream_stream( + self, + continuation: Callable[[ClientCallDetails, Iterator[_TRequest]], _CallIterator[_TResponse]], + client_call_details: ClientCallDetails, + request_iterator: Iterator[_TRequest], + ) -> _CallIterator[_TResponse]: ... + +# Service-Side Context: + +class ServicerContext(RpcContext, metaclass=abc.ABCMeta): + # misnamed parameter 'details', does not align with status.proto, where it is called 'message': + @abc.abstractmethod + def abort(self, code: StatusCode, details: str) -> Never: ... + @abc.abstractmethod + def abort_with_status(self, status: Status) -> Never: ... + + # FIXME: The docs say "A map of strings to an iterable of bytes for each auth property". + # Does that mean 'bytes' (which is iterable), or 'Iterable[bytes]'? + @abc.abstractmethod + def auth_context(self) -> Mapping[str, bytes]: ... + def disable_next_message_compression(self) -> None: ... + @abc.abstractmethod + def invocation_metadata(self) -> _Metadata: ... + @abc.abstractmethod + def peer(self) -> str: ... + @abc.abstractmethod + def peer_identities(self) -> Iterable[bytes] | None: ... + @abc.abstractmethod + def peer_identity_key(self) -> str | None: ... + @abc.abstractmethod + def send_initial_metadata(self, initial_metadata: _Metadata) -> None: ... + @abc.abstractmethod + def set_code(self, code: StatusCode) -> None: ... + def set_compression(self, compression: Compression) -> None: ... + @abc.abstractmethod + def set_trailing_metadata(self, trailing_metadata: _Metadata) -> None: ... + + # misnamed function 'details', does not align with status.proto, where it is called 'message': + @abc.abstractmethod + def set_details(self, details: str) -> None: ... + def trailing_metadata(self) -> _Metadata: ... + +# Service-Side Handler: + +class RpcMethodHandler(abc.ABC, Generic[_TRequest, _TResponse]): + request_streaming: bool + response_streaming: bool + + # XXX: not clear from docs whether this is optional or not + request_deserializer: _Deserializer[_TRequest] | None + + # XXX: not clear from docs whether this is optional or not + response_serializer: _Serializer[_TResponse] | None + + unary_unary: Callable[[_TRequest, ServicerContext], _TResponse] | None + + unary_stream: Callable[[_TRequest, ServicerContext], Iterator[_TResponse]] | None + + stream_unary: Callable[[Iterator[_TRequest], ServicerContext], _TResponse] | None + + stream_stream: Callable[[Iterator[_TRequest], ServicerContext], Iterator[_TResponse]] | None + +@runtime_checkable +class HandlerCallDetails(Protocol): + method: str + invocation_metadata: _Metadata + +class GenericRpcHandler(abc.ABC): + # The return type depends on the handler call details. + @abc.abstractmethod + def service(self, handler_call_details: HandlerCallDetails) -> RpcMethodHandler[Any, Any] | None: ... + +class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta): + @abc.abstractmethod + def service_name(self) -> str: ... + +# Service-Side Interceptor: + +class ServerInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(handler_call_details)`. + @abc.abstractmethod + def intercept_service( + self, + continuation: Callable[[HandlerCallDetails], RpcMethodHandler[_TRequest, _TResponse] | None], + handler_call_details: HandlerCallDetails, + ) -> RpcMethodHandler[_TRequest, _TResponse] | None: ... + +# Multi-Callable Interfaces: + +class UnaryUnaryMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _TResponse: ... + @abc.abstractmethod + def future( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallFuture[_TResponse]: ... + @abc.abstractmethod + def with_call( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + # FIXME: Return value is documented as "The response value for the RPC and a Call value for the RPC"; + # this is slightly unclear so this return type is a best-effort guess. + ) -> tuple[_TResponse, Call]: ... + +class UnaryStreamMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallIterator[_TResponse]: ... + +class StreamUnaryMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _TResponse: ... + @abc.abstractmethod + def future( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallFuture[_TResponse]: ... + @abc.abstractmethod + def with_call( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + # FIXME: Return value is documented as "The response value for the RPC and a Call value for the RPC"; + # this is slightly unclear so this return type is a best-effort guess. + ) -> tuple[_TResponse, Call]: ... + +class StreamStreamMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallIterator[_TResponse]: ... + +# Runtime Protobuf Parsing: + +def protos(protobuf_path: str) -> ModuleType: ... +def services(protobuf_path: str) -> ModuleType: ... +def protos_and_services(protobuf_path: str) -> tuple[ModuleType, ModuleType]: ... diff --git a/stubs/grpcio/grpc/aio/__init__.pyi b/stubs/grpcio/grpc/aio/__init__.pyi new file mode 100644 index 000000000000..d71a3ba2be1b --- /dev/null +++ b/stubs/grpcio/grpc/aio/__init__.pyi @@ -0,0 +1,537 @@ +import abc +import asyncio +from _typeshed import Incomplete, MaybeNone +from collections.abc import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Collection, + Generator, + Iterable, + Iterator, + Mapping, + Sequence, +) +from concurrent import futures +from types import TracebackType +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self + +from grpc import ( + CallCredentials, + ChannelConnectivity, + ChannelCredentials, + Compression, + GenericRpcHandler, + HandlerCallDetails, + RpcError, + RpcMethodHandler, + ServerCredentials, + Status, + StatusCode, + _Options, +) + +__all__ = ( + "EOF", + "AbortError", + "AioRpcError", + "BaseError", + "Call", + "Channel", + "ClientCallDetails", + "ClientInterceptor", + "InterceptedUnaryUnaryCall", + "InternalError", + "Metadata", + "RpcContext", + "Server", + "ServerInterceptor", + "ServicerContext", + "StreamStreamCall", + "StreamStreamClientInterceptor", + "StreamStreamMultiCallable", + "StreamUnaryCall", + "StreamUnaryClientInterceptor", + "StreamUnaryMultiCallable", + "UnaryStreamCall", + "UnaryStreamClientInterceptor", + "UnaryStreamMultiCallable", + "UnaryUnaryCall", + "UnaryUnaryClientInterceptor", + "UnaryUnaryMultiCallable", + "UsageError", + "init_grpc_aio", + "insecure_channel", + "secure_channel", + "server", + "shutdown_grpc_aio", +) + +_TRequest = TypeVar("_TRequest") +_TResponse = TypeVar("_TResponse") + +@type_check_only +class _EOF: + def __bool__(self) -> Literal[False]: ... + def __len__(self) -> Literal[0]: ... + +EOF: Final[_EOF] + +def init_grpc_aio() -> None: ... +def shutdown_grpc_aio() -> None: ... + +# Exceptions: + +class BaseError(Exception): ... +class UsageError(BaseError): ... +class AbortError(BaseError): ... +class InternalError(BaseError): ... + +class AioRpcError(RpcError): + def __init__( + self, + code: StatusCode, + initial_metadata: Metadata | None = None, + trailing_metadata: Metadata | None = None, + details: str | None = None, + debug_error_string: str | None = None, + ) -> None: ... + def code(self) -> StatusCode: ... + def details(self) -> str | None: ... + def initial_metadata(self) -> Metadata | MaybeNone: ... + # AioRpcError returns the async Metadata, overriding the synchronous + # grpc.RpcError.trailing_metadata() -> tuple[_Metadatum, ...]. + def trailing_metadata(self) -> Metadata | MaybeNone: ... # type: ignore[override] + def debug_error_string(self) -> str | None: ... + +# Create Client: + +def insecure_channel( + target: str, + options: _Options | None = None, + compression: Compression | None = None, + interceptors: Sequence[ClientInterceptor] | None = None, +) -> Channel: ... +def secure_channel( + target: str, + credentials: ChannelCredentials, + options: _Options | None = None, + compression: Compression | None = None, + interceptors: Sequence[ClientInterceptor] | None = None, +) -> Channel: ... + +# Create Server: + +def server( + migration_thread_pool: futures.Executor | None = None, + handlers: Sequence[GenericRpcHandler] | None = None, + interceptors: Sequence[ServerInterceptor] | None = None, + options: _Options | None = None, + maximum_concurrent_rpcs: int | None = None, + compression: Compression | None = None, +) -> Server: ... + +# Channel Object: + +_Serializer: TypeAlias = Callable[[_T], bytes] +_Deserializer: TypeAlias = Callable[[bytes], _T] + +class Channel(abc.ABC): + @abc.abstractmethod + async def close(self, grace: float | None = None) -> None: ... + @abc.abstractmethod + def get_state(self, try_to_connect: bool = False) -> ChannelConnectivity: ... + @abc.abstractmethod + async def wait_for_state_change(self, last_observed_state: ChannelConnectivity) -> None: ... + @abc.abstractmethod + def stream_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def stream_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unary_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unary_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + async def __aenter__(self) -> Self: ... + @abc.abstractmethod + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + @abc.abstractmethod + async def channel_ready(self) -> None: ... + +# Server Object: + +class Server(metaclass=abc.ABCMeta): + @abc.abstractmethod + def add_generic_rpc_handlers(self, generic_rpc_handlers: Iterable[GenericRpcHandler]) -> None: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_insecure_port(self, address: str) -> int: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_secure_port(self, address: str, server_credentials: ServerCredentials) -> int: ... + @abc.abstractmethod + async def start(self) -> None: ... + + # Grace period is in seconds. + @abc.abstractmethod + async def stop(self, grace: float | None) -> None: ... + + # Returns a bool indicates if the operation times out. Timeout is in seconds. + @abc.abstractmethod + async def wait_for_termination(self, timeout: float | None = None) -> bool: ... + +# Client-Side Context: + +_DoneCallbackType: TypeAlias = Callable[[Any], None] +_EOFType: TypeAlias = object + +class RpcContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def cancelled(self) -> bool: ... + @abc.abstractmethod + def done(self) -> bool: ... + @abc.abstractmethod + def time_remaining(self) -> float | None: ... + @abc.abstractmethod + def cancel(self) -> bool: ... + @abc.abstractmethod + def add_done_callback(self, callback: _DoneCallbackType) -> None: ... + +class Call(RpcContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + async def initial_metadata(self) -> Metadata: ... + @abc.abstractmethod + async def trailing_metadata(self) -> Metadata: ... + @abc.abstractmethod + async def code(self) -> StatusCode: ... + @abc.abstractmethod + async def details(self) -> str: ... + @abc.abstractmethod + async def wait_for_connection(self) -> None: ... + +class UnaryUnaryCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __await__(self) -> Generator[None, None, _TResponse]: ... + +class UnaryStreamCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __aiter__(self) -> AsyncIterator[_TResponse]: ... + @abc.abstractmethod + async def read(self) -> _EOFType | _TResponse: ... + +class StreamUnaryCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + async def write(self, request: _TRequest) -> None: ... + @abc.abstractmethod + async def done_writing(self) -> None: ... + @abc.abstractmethod + def __await__(self) -> Generator[None, None, _TResponse]: ... + +class StreamStreamCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __aiter__(self) -> AsyncIterator[_TResponse]: ... + @abc.abstractmethod + async def read(self) -> _EOFType | _TResponse: ... + @abc.abstractmethod + async def write(self, request: _TRequest) -> None: ... + @abc.abstractmethod + async def done_writing(self) -> None: ... + +# Service-Side Context: + +@type_check_only +class _DoneCallback(Generic[_TRequest, _TResponse]): + def __call__(self, ctx: ServicerContext[_TRequest, _TResponse]) -> None: ... + +class ServicerContext(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + async def abort(self, code: StatusCode, details: str = "", trailing_metadata: _MetadataType = ()) -> Never: ... + @abc.abstractmethod + async def read(self) -> _TRequest: ... + @abc.abstractmethod + async def write(self, message: _TResponse) -> None: ... + @abc.abstractmethod + async def send_initial_metadata(self, initial_metadata: _MetadataType) -> None: ... + def add_done_callback(self, callback: _DoneCallback[_TRequest, _TResponse]) -> None: ... + @abc.abstractmethod + async def abort_with_status(self, status: Status) -> Never: ... + @abc.abstractmethod + def set_trailing_metadata(self, trailing_metadata: _MetadataType) -> None: ... + @abc.abstractmethod + def invocation_metadata(self) -> Metadata | None: ... + @abc.abstractmethod + def set_code(self, code: StatusCode) -> None: ... + @abc.abstractmethod + def set_details(self, details: str) -> None: ... + @abc.abstractmethod + def set_compression(self, compression: Compression) -> None: ... + @abc.abstractmethod + def disable_next_message_compression(self) -> None: ... + @abc.abstractmethod + def peer(self) -> str: ... + @abc.abstractmethod + def peer_identities(self) -> Iterable[bytes] | None: ... + @abc.abstractmethod + def peer_identity_key(self) -> str | None: ... + @abc.abstractmethod + def auth_context(self) -> Mapping[str, Iterable[bytes]]: ... + def time_remaining(self) -> float: ... + def trailing_metadata(self) -> Metadata: ... + def code(self) -> StatusCode: ... + def details(self) -> str: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + +# Client-Side Interceptor: + +class ClientCallDetails(abc.ABC): + def __new__( + _cls, + method: str, + timeout: float | None, + metadata: Metadata | None, + credentials: CallCredentials | None, + wait_for_ready: bool | None, + ) -> Self: ... + + method: str + timeout: float | None + metadata: Metadata | None + credentials: CallCredentials | None + + # "This is an EXPERIMENTAL argument. An optional flag t enable wait for ready mechanism." + wait_for_ready: bool | None + + # As at 1.53.0, this is not supported in aio: + # compression: Compression | None + +@type_check_only +class _InterceptedCall(Generic[_TRequest, _TResponse]): + def __init__(self, interceptors_task: asyncio.Task[Any]) -> None: ... + def __del__(self) -> None: ... + def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + def add_done_callback(self, callback: _DoneCallback[_TRequest, _TResponse]) -> None: ... + def time_remaining(self) -> float | None: ... + async def initial_metadata(self) -> Metadata | None: ... + async def trailing_metadata(self) -> Metadata | None: ... + async def code(self) -> StatusCode: ... + async def details(self) -> str: ... + async def debug_error_string(self) -> str | None: ... + async def wait_for_connection(self) -> None: ... + +class InterceptedUnaryUnaryCall(_InterceptedCall[_TRequest, _TResponse], metaclass=abc.ABCMeta): + def __await__(self) -> Generator[Incomplete, None, _TResponse]: ... + def __init__( + self, + interceptors: Sequence[UnaryUnaryClientInterceptor], + request: _TRequest, + timeout: float | None, + metadata: Metadata, + credentials: CallCredentials | None, + wait_for_ready: bool | None, + channel: Channel, + method: bytes, + request_serializer: _Serializer[_TRequest], + response_deserializer: _Deserializer[_TResponse], + loop: asyncio.AbstractEventLoop, + registered_call_handle: int = 0, + ) -> None: ... + + # pylint: disable=too-many-arguments + async def _invoke( + self, + interceptors: Sequence[UnaryUnaryClientInterceptor], + method: bytes, + timeout: float | None, + metadata: Metadata | None, + credentials: CallCredentials | None, + wait_for_ready: bool | None, + request: _TRequest, + request_serializer: _Serializer[_TRequest], + response_deserializer: _Deserializer[_TResponse], + ) -> UnaryUnaryCall[_TRequest, _TResponse]: ... + def time_remaining(self) -> float | None: ... + +class ClientInterceptor(metaclass=abc.ABCMeta): ... + +class UnaryUnaryClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request)`. + @abc.abstractmethod + async def intercept_unary_unary( + self, + continuation: Callable[[ClientCallDetails, _TRequest], Awaitable[UnaryUnaryCall[_TRequest, _TResponse]]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> _TResponse | UnaryUnaryCall[_TRequest, _TResponse]: ... + +class UnaryStreamClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request)`. + @abc.abstractmethod + async def intercept_unary_stream( + self, + continuation: Callable[[ClientCallDetails, _TRequest], Awaitable[UnaryStreamCall[_TRequest, _TResponse]]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> AsyncIterator[_TResponse] | UnaryStreamCall[_TRequest, _TResponse]: ... + +class StreamUnaryClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + async def intercept_stream_unary( + self, + continuation: Callable[ + [ClientCallDetails, AsyncIterable[_TRequest] | Iterable[_TRequest]], Awaitable[StreamUnaryCall[_TRequest, _TResponse]] + ], + client_call_details: ClientCallDetails, + request_iterator: AsyncIterable[_TRequest] | Iterable[_TRequest], + ) -> _TResponse | StreamUnaryCall[_TRequest, _TResponse]: ... + +class StreamStreamClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + async def intercept_stream_stream( + self, + continuation: Callable[ + [ClientCallDetails, AsyncIterable[_TRequest] | Iterable[_TRequest]], + Awaitable[StreamStreamCall[_TRequest, _TResponse]], + ], + client_call_details: ClientCallDetails, + request_iterator: AsyncIterable[_TRequest] | Iterable[_TRequest], + ) -> AsyncIterator[_TResponse] | StreamStreamCall[_TRequest, _TResponse]: ... + +# Server-Side Interceptor: + +class ServerInterceptor(metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(handler_call_details)`. + # The return is Optional: per the runtime docstring, an interceptor + # may return None to signal that the RPC is not serviced, and the + # continuation propagates that None down the chain. + @abc.abstractmethod + async def intercept_service( + self, + continuation: Callable[[HandlerCallDetails], Awaitable[RpcMethodHandler[_TRequest, _TResponse] | None]], + handler_call_details: HandlerCallDetails, + ) -> RpcMethodHandler[_TRequest, _TResponse] | None: ... + +# Multi-Callable Interfaces: + +class UnaryUnaryMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + *, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> UnaryUnaryCall[_TRequest, _TResponse]: ... + +class UnaryStreamMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + *, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> UnaryStreamCall[_TRequest, _TResponse]: ... + +class StreamUnaryMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request_iterator: AsyncIterator[_TRequest] | Iterator[_TRequest] | None = None, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> StreamUnaryCall[_TRequest, _TResponse]: ... + +class StreamStreamMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request_iterator: AsyncIterator[_TRequest] | Iterator[_TRequest] | None = None, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> StreamStreamCall[_TRequest, _TResponse]: ... + +# Metadata: + +_MetadataKey: TypeAlias = str +_MetadataValue: TypeAlias = str | bytes +_MetadatumType: TypeAlias = tuple[_MetadataKey, _MetadataValue] +_MetadataType: TypeAlias = Metadata | Sequence[_MetadatumType] +_T = TypeVar("_T") + +class Metadata(Collection[_MetadatumType]): + def __init__(self, *args: tuple[_MetadataKey, _MetadataValue]) -> None: ... + @classmethod + def from_tuple(cls, raw_metadata: Iterable[_MetadatumType]) -> Self: ... + def add(self, key: _MetadataKey, value: _MetadataValue) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _MetadataKey) -> _MetadataValue: ... + def __setitem__(self, key: _MetadataKey, value: _MetadataValue) -> None: ... + def __delitem__(self, key: _MetadataKey) -> None: ... + def delete_all(self, key: _MetadataKey) -> None: ... + def __iter__(self) -> Iterator[_MetadatumType]: ... + + @overload + def get(self, key: _MetadataKey, default: None = None) -> _MetadataValue | None: ... + @overload + def get(self, key: _MetadataKey, default: _MetadataValue) -> _MetadataValue: ... + @overload + def get(self, key: _MetadataKey, default: _T) -> _MetadataValue | _T: ... + + def get_all(self, key: _MetadataKey) -> list[_MetadataValue]: ... + def set_all(self, key: _MetadataKey, values: list[_MetadataValue]) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __add__(self, other: Any) -> Metadata: ... diff --git a/stubs/grpcio/grpc/experimental/gevent.pyi b/stubs/grpcio/grpc/experimental/gevent.pyi new file mode 100644 index 000000000000..71163b4763c9 --- /dev/null +++ b/stubs/grpcio/grpc/experimental/gevent.pyi @@ -0,0 +1 @@ +def init_gevent() -> None: ... diff --git a/stubs/gunicorn/@tests/stubtest_allowlist.txt b/stubs/gunicorn/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..771d1891e68d --- /dev/null +++ b/stubs/gunicorn/@tests/stubtest_allowlist.txt @@ -0,0 +1,14 @@ +# Is not present in runtime. For more details, see the file itself. +gunicorn._types + +# .pyi file doesn't exist +gunicorn.__main__ + +# Internal API stuff: +gunicorn.config.Config.forwarded_allow_networks +gunicorn.config.Config.proxy_allow_networks + +# Set to None on class, but initialized to non-None value in __init__ +gunicorn.http.message.Message.scheme +gunicorn.http2.request.HTTP2Request.scheme +gunicorn.http2.request.HTTP2Request.version diff --git a/stubs/gunicorn/METADATA.toml b/stubs/gunicorn/METADATA.toml new file mode 100644 index 000000000000..60913393ea88 --- /dev/null +++ b/stubs/gunicorn/METADATA.toml @@ -0,0 +1,14 @@ +version = "26.2.0" +upstream-repository = "https://github.com/benoitc/gunicorn" +optional-dependencies = ["types-gevent"] + +[tool.stubtest] +supported-platforms = ["linux", "darwin"] +ci-platforms = ["linux", "darwin"] +stubtest-dependencies = [ + "gevent>=1.4.0", + "tornado>=0.2", + "setproctitle", + "PasteDeploy", + "inotify", +] diff --git a/stubs/gunicorn/gunicorn/__init__.pyi b/stubs/gunicorn/gunicorn/__init__.pyi new file mode 100644 index 000000000000..ddd769a92a3e --- /dev/null +++ b/stubs/gunicorn/gunicorn/__init__.pyi @@ -0,0 +1,6 @@ +from typing import Final + +version_info: Final[tuple[int, int, int]] +__version__: Final[str] +SERVER: Final[str] +SERVER_SOFTWARE: Final[str] diff --git a/stubs/gunicorn/gunicorn/_types.pyi b/stubs/gunicorn/gunicorn/_types.pyi new file mode 100644 index 000000000000..14e8f740a8be --- /dev/null +++ b/stubs/gunicorn/gunicorn/_types.pyi @@ -0,0 +1,25 @@ +############################################################################################################ +# This .pyi file is a helper for centralized storage types that are reused across different runtime modules. +############################################################################################################ +from _typeshed import FileDescriptor +from collections.abc import Awaitable, Callable, Iterable, MutableMapping +from typing import Any, TypeAlias +from typing_extensions import LiteralString + +_StatusType: TypeAlias = str +_HeadersType: TypeAlias = Iterable[tuple[str, str]] + +_EnvironType: TypeAlias = MutableMapping[str, Any] # See https://peps.python.org/pep-0333/ +_StartResponseType: TypeAlias = Callable[[_StatusType, _HeadersType], None] +_ResponseBodyType: TypeAlias = Iterable[bytes] +_WSGIAppType: TypeAlias = Callable[[_EnvironType, _StartResponseType], _ResponseBodyType] # noqa: Y047 + +_ScopeType: TypeAlias = MutableMapping[str, Any] +_MessageType: TypeAlias = MutableMapping[str, Any] +_ReceiveType: TypeAlias = Callable[[], Awaitable[_MessageType]] +_SendType: TypeAlias = Callable[[_MessageType], Awaitable[None]] +_ASGIAppType: TypeAlias = Callable[[_ScopeType, _ReceiveType, _SendType], Awaitable[None]] # noqa: Y047 + +_UnixSocketPathType: TypeAlias = str +_TcpAddressType: TypeAlias = tuple[LiteralString, int] # noqa: Y047 +_AddressType: TypeAlias = _UnixSocketPathType | FileDescriptor | _TcpAddressType # noqa: Y047 diff --git a/stdlib/@python2/distutils/command/clean.pyi b/stubs/gunicorn/gunicorn/app/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/clean.pyi rename to stubs/gunicorn/gunicorn/app/__init__.pyi diff --git a/stubs/gunicorn/gunicorn/app/base.pyi b/stubs/gunicorn/gunicorn/app/base.pyi new file mode 100644 index 000000000000..6e06417eca5d --- /dev/null +++ b/stubs/gunicorn/gunicorn/app/base.pyi @@ -0,0 +1,33 @@ +from argparse import ArgumentParser, Namespace +from typing import Any + +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger + +from .._types import _ASGIAppType, _WSGIAppType + +class BaseApplication: + usage: str | None + cfg: Config + callable: _WSGIAppType | _ASGIAppType | None + prog: str | None + logger: GLogger + + def __init__(self, usage: str | None = None, prog: str | None = None) -> None: ... + def do_load_config(self) -> None: ... + def load_default_config(self) -> None: ... + def init(self, parser: ArgumentParser, opts: Namespace, args: list[str]) -> dict[str, Any] | None: ... + def load(self) -> _WSGIAppType | _ASGIAppType: ... + def load_config(self) -> None: ... + def reload(self) -> None: ... + def wsgi(self) -> _WSGIAppType | _ASGIAppType: ... + def run(self) -> None: ... + +class Application(BaseApplication): + def chdir(self) -> None: ... + def get_config_from_filename(self, filename: str) -> dict[str, Any]: ... + def get_config_from_module_name(self, module_name: str) -> dict[str, Any]: ... + def load_config_from_module_name_or_filename(self, location: str) -> dict[str, Any]: ... + def load_config_from_file(self, filename: str) -> dict[str, Any]: ... + def load_config(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/app/pasterapp.pyi b/stubs/gunicorn/gunicorn/app/pasterapp.pyi new file mode 100644 index 000000000000..ab94b4872f49 --- /dev/null +++ b/stubs/gunicorn/gunicorn/app/pasterapp.pyi @@ -0,0 +1,7 @@ +from typing import Any + +from .._types import _WSGIAppType + +def get_wsgi_app(config_uri: str, name: str | None = None, defaults: dict[str, Any] | None = None) -> _WSGIAppType: ... +def has_logging_config(config_file: str) -> bool: ... +def serve(app: _WSGIAppType, global_conf: dict[str, Any], **local_conf: Any) -> None: ... diff --git a/stubs/gunicorn/gunicorn/app/wsgiapp.pyi b/stubs/gunicorn/gunicorn/app/wsgiapp.pyi new file mode 100644 index 000000000000..36e0cedc410f --- /dev/null +++ b/stubs/gunicorn/gunicorn/app/wsgiapp.pyi @@ -0,0 +1,16 @@ +from argparse import ArgumentParser, Namespace + +from gunicorn.app.base import Application + +from .._types import _WSGIAppType + +class WSGIApplication(Application): + app_uri: str | None + + def init(self, parser: ArgumentParser, opts: Namespace, args: list[str]) -> None: ... + def load_config(self) -> None: ... + def load_wsgiapp(self) -> _WSGIAppType: ... + def load_pasteapp(self) -> _WSGIAppType: ... + def load(self) -> _WSGIAppType: ... + +def run(prog: str | None = None) -> None: ... diff --git a/stubs/gunicorn/gunicorn/arbiter.pyi b/stubs/gunicorn/gunicorn/arbiter.pyi new file mode 100644 index 000000000000..422a711477c6 --- /dev/null +++ b/stubs/gunicorn/gunicorn/arbiter.pyi @@ -0,0 +1,80 @@ +from queue import SimpleQueue +from types import FrameType +from typing import ClassVar + +from gunicorn.app.base import BaseApplication +from gunicorn.config import Config +from gunicorn.dirty import DirtyArbiter +from gunicorn.glogging import Logger as GLogger +from gunicorn.sock import BaseSocket +from gunicorn.workers.base import Worker + +from ._types import _AddressType +from .pidfile import Pidfile + +class Arbiter: + WORKER_BOOT_ERROR: ClassVar[int] + APP_LOAD_ERROR: ClassVar[int] + START_CTX: ClassVar[dict[int | str, str | list[str]]] + LISTENERS: ClassVar[list[BaseSocket]] + WORKERS: ClassVar[dict[int, Worker]] + WAKEUP_REQUEST: ClassVar[int] + SIGNALS: ClassVar[list[int]] + SIG_NAMES: ClassVar[dict[int, str]] + log: GLogger | None + SIG_QUEUE: SimpleQueue[int] + pidfile: Pidfile | None + systemd: bool + worker_age: int + reexec_pid: int + master_pid: int + master_name: str + dirty_arbiter_pid: int + dirty_arbiter: DirtyArbiter | None + dirty_pidfile: str | None + pid: int + app: BaseApplication + cfg: Config + worker_class: type[Worker] + address: list[_AddressType] + timeout: int + proc_name: str + num_workers: int + + def __init__(self, app: BaseApplication) -> None: ... + def setup(self, app: BaseApplication) -> None: ... + def start(self) -> None: ... + def init_signals(self) -> None: ... + def signal(self, sig: int, frame: FrameType | None) -> None: ... + def run(self) -> None: ... + def signal_chld(self, sig: int, frame: FrameType | None) -> None: ... + def handle_chld(self) -> None: ... + handle_cld = handle_chld + def handle_hup(self) -> None: ... + def handle_term(self) -> None: ... + def handle_int(self) -> None: ... + def handle_quit(self) -> None: ... + def handle_ttin(self) -> None: ... + def handle_ttou(self) -> None: ... + def handle_usr1(self) -> None: ... + def handle_usr2(self) -> None: ... + def handle_winch(self) -> None: ... + def maybe_promote_master(self) -> None: ... + def wakeup(self) -> None: ... + def halt(self, reason: str | None = None, exit_status: int = 0) -> None: ... + def wait_for_signals(self, timeout: float | None = 1.0) -> list[int]: ... + def stop(self, graceful: bool = True) -> None: ... + def reexec(self) -> None: ... + def reload(self) -> None: ... + def murder_workers(self) -> None: ... + def reap_workers(self) -> None: ... + def manage_workers(self) -> None: ... + def spawn_worker(self) -> int: ... + def spawn_workers(self) -> None: ... + def kill_workers(self, sig: int) -> None: ... + def kill_worker(self, pid: int, sig: int) -> None: ... + def spawn_dirty_arbiter(self) -> int | None: ... + def kill_dirty_arbiter(self, sig: int) -> None: ... + def handle_dirty_arbiter_exit(self, wpid: int, status: int) -> None: ... + def reap_dirty_arbiter(self) -> None: ... + def manage_dirty_arbiter(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/__init__.pyi b/stubs/gunicorn/gunicorn/asgi/__init__.pyi new file mode 100644 index 000000000000..0e635cb1217d --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/__init__.pyi @@ -0,0 +1,4 @@ +from gunicorn.asgi.lifespan import LifespanManager as LifespanManager +from gunicorn.asgi.unreader import AsyncUnreader as AsyncUnreader + +__all__ = ["AsyncUnreader", "LifespanManager"] diff --git a/stubs/gunicorn/gunicorn/asgi/lifespan.pyi b/stubs/gunicorn/gunicorn/asgi/lifespan.pyi new file mode 100644 index 000000000000..a55dca666674 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/lifespan.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from gunicorn.glogging import Logger as GLogger + +from .._types import _ASGIAppType + +class LifespanManager: + app: _ASGIAppType + logger: GLogger + state: dict[Incomplete, Incomplete] + + def __init__(self, app: _ASGIAppType, logger: GLogger, state: dict[Incomplete, Incomplete] | None = None) -> None: ... + async def startup(self) -> None: ... + async def shutdown(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/parser.pyi b/stubs/gunicorn/gunicorn/asgi/parser.pyi new file mode 100644 index 000000000000..294d7681f0e0 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/parser.pyi @@ -0,0 +1,163 @@ +from collections.abc import Callable, Iterable +from enum import IntEnum +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self + +_H1CProtocol: TypeAlias = Any # gunicorn_h1c H1CProtocol class + +class ParseError(Exception): ... +class InvalidProxyLine(ParseError): ... +class InvalidProxyHeader(ParseError): ... + +@type_check_only +class _ProxyProtocolInfo(TypedDict): + proxy_protocol: Literal["TCP4", "TCP6", "UDP4", "UDP6"] + client_addr: str + client_port: int + proxy_addr: str + proxy_port: int + +@type_check_only +class _ProxyProtocolInfoUnknown(TypedDict): + proxy_protocol: Literal["UNKNOWN", "LOCAL", "UNSPEC"] + client_addr: None + client_port: None + proxy_addr: None + proxy_port: None + +PP_V2_SIGNATURE: Final[bytes] +RFC9110_6_5_1_FORBIDDEN_TRAILER: Final[frozenset[bytes]] + +class PPCommand(IntEnum): + LOCAL = 0x0 + PROXY = 0x1 + +class PPFamily(IntEnum): + UNSPEC = 0x0 + INET = 0x1 + INET6 = 0x2 + UNIX = 0x3 + +class PPProtocol(IntEnum): + UNSPEC = 0x0 + STREAM = 0x1 + DGRAM = 0x2 + +class LimitRequestLine(ParseError): ... +class InvalidRequestLine(ParseError): ... +class LimitRequestHeaders(ParseError): ... +class InvalidRequestMethod(ParseError): ... +class InvalidHTTPVersion(ParseError): ... +class InvalidHeaderName(ParseError): ... +class InvalidHeader(ParseError): ... +class UnsupportedTransferCoding(ParseError): ... +class InvalidChunkSize(ParseError): ... +class InvalidChunkExtension(ParseError): ... + +RFC9110_5_3_SINGLETON_FIELDS: Final[frozenset[bytes]] + +class PythonProtocol: + __slots__ = ( + "_on_message_begin", + "_on_url", + "_on_header", + "_on_headers_complete", + "_on_body", + "_on_message_complete", + "_state", + "_buffer", + "_headers_list", + "method", + "path", + "http_version", + "headers", + "content_length", + "is_chunked", + "should_keep_alive", + "is_complete", + "_body_remaining", + "_skip_body", + "_chunk_state", + "_chunk_size", + "_chunk_remaining", + "_limit_request_line", + "_limit_request_fields", + "_limit_request_field_size", + "_permit_unconventional_http_method", + "_permit_unconventional_http_version", + "_header_count", + "_proxy_protocol", + "_proxy_protocol_info", + "_proxy_protocol_done", + ) + method: bytes | None + path: bytes | None + http_version: tuple[int, int] | None + headers: list[tuple[bytes, bytes]] + content_length: int | None + is_chunked: bool + should_keep_alive: bool + is_complete: bool + + def __init__( + self, + on_message_begin: Callable[[], object] | None = None, + on_url: Callable[[bytes], object] | None = None, + on_header: Callable[[bytes, bytes], object] | None = None, + on_headers_complete: Callable[[], bool] | None = None, + on_body: Callable[[bytes], object] | None = None, + on_message_complete: Callable[[], object] | None = None, + limit_request_line: int = 8190, + limit_request_fields: int = 100, + limit_request_field_size: int = 8190, + permit_unconventional_http_method: bool = False, + permit_unconventional_http_version: bool = False, + proxy_protocol: Literal["off", "v1", "v2", "auto"] = "off", + ) -> None: ... + def feed(self, data: Iterable[SupportsIndex]) -> None: ... + def remaining(self) -> bytes: ... + @property + def remaining_truncated(self) -> Literal[False]: ... + @property + def proxy_protocol_info(self) -> _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None: ... + def reset(self) -> None: ... + def finish(self) -> None: ... + +class CallbackRequest: + __slots__ = ( + "method", + "uri", + "path", + "query", + "fragment", + "version", + "headers", + "headers_bytes", + "scheme", + "raw_path", + "content_length", + "chunked", + "must_close", + "proxy_protocol_info", + "_expect_100_continue", + ) + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + version: tuple[int, int] | None + headers: list[tuple[str, str]] + headers_bytes: list[tuple[bytes, bytes]] + scheme: Literal["https", "http"] + raw_path: bytes + content_length: int + chunked: bool + must_close: bool + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + + def __init__(self) -> None: ... + @classmethod + def from_parser(cls, parser: _H1CProtocol | PythonProtocol, is_ssl: bool = False) -> Self: ... + def should_close(self) -> bool: ... + def get_header(self, name: str) -> str | None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/protocol.pyi b/stubs/gunicorn/gunicorn/asgi/protocol.pyi new file mode 100644 index 000000000000..376851ee89ab --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/protocol.pyi @@ -0,0 +1,61 @@ +import asyncio +from collections.abc import Iterable +from typing import Final, Literal, TypedDict, type_check_only +from typing_extensions import NotRequired + +from gunicorn.asgi.parser import CallbackRequest +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.workers.gasgi import ASGIWorker + +from .._types import _ASGIAppType + +HIGH_WATER_LIMIT: Final = 65536 + +class FlowControl: + __slots__ = ("_transport", "read_paused", "write_paused", "_is_writable_event") + read_paused: bool + write_paused: bool + + def __init__(self, transport: asyncio.BaseTransport) -> None: ... + async def drain(self) -> None: ... + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + +class ASGIResponseInfo: + status: str | int + sent: int + headers: list[tuple[str, str]] + + def __init__(self, status: str | int, headers: Iterable[tuple[str | bytes, str | bytes]], sent: int) -> None: ... + +@type_check_only +class _BodyReceieverReceiveReturnType(TypedDict): + type: Literal["http.disconnect", "http.request"] + body: NotRequired[bytes] + more_body: NotRequired[bool] + +class BodyReceiver: + __slots__ = ("_chunks", "_complete", "_body_finished", "_closed", "_body_wait_expired", "_waiter", "request", "protocol") + request: CallbackRequest + protocol: ASGIProtocol + + def __init__(self, request: CallbackRequest, protocol: ASGIProtocol) -> None: ... + def feed(self, chunk: bytes) -> None: ... + def set_complete(self) -> None: ... + def signal_disconnect(self) -> None: ... + async def receive(self) -> _BodyReceieverReceiveReturnType: ... + +class ASGIProtocol(asyncio.Protocol): + worker: ASGIWorker + cfg: Config + log: GLogger + app: _ASGIAppType + transport: asyncio.BaseTransport | None + reader: asyncio.StreamReader | None + writer: asyncio.BaseTransport | None + req_count: int + + def __init__(self, worker: ASGIWorker) -> None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/unreader.pyi b/stubs/gunicorn/gunicorn/asgi/unreader.pyi new file mode 100644 index 000000000000..8bb53ea2f396 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/unreader.pyi @@ -0,0 +1,13 @@ +import asyncio +import io +from _typeshed import ReadableBuffer + +class AsyncUnreader: + reader: asyncio.StreamReader + buf: io.BytesIO + max_chunk: int + + def __init__(self, reader: asyncio.StreamReader, max_chunk: int = 8192) -> None: ... + async def read(self, size: int | None = None) -> bytes: ... + def unread(self, data: ReadableBuffer) -> None: ... + def has_buffered_data(self) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi b/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi new file mode 100644 index 000000000000..c76678bf8199 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi @@ -0,0 +1,39 @@ +from typing import Literal +from typing_extensions import Self + +from gunicorn.asgi.unreader import AsyncUnreader +from gunicorn.config import Config +from gunicorn.uwsgi.message import UWSGIRequest + +from .._types import _AddressType +from .parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +class AsyncUWSGIRequest(UWSGIRequest): + cfg: Config + unreader: AsyncUnreader # type: ignore[assignment] + peer_addr: _AddressType + remote_addr: _AddressType + req_number: int + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + version: tuple[int, int] + headers: list[tuple[str, str]] + trailers: list[tuple[str, str]] + scheme: Literal["https", "http"] + must_close: bool + uwsgi_vars: dict[str, str] + modifier1: int + modifier2: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + content_length: int + chunked: bool + + def __init__(self, cfg: Config, unreader: AsyncUnreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... + @classmethod + async def parse(cls, cfg: Config, unreader: AsyncUnreader, peer_addr: _AddressType, req_number: int = 1) -> Self: ... # type: ignore[override] + async def read_body(self, size: int = 8192) -> bytes: ... + async def drain_body(self) -> None: ... + def get_header(self, name: str) -> str | None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/websocket.pyi b/stubs/gunicorn/gunicorn/asgi/websocket.pyi new file mode 100644 index 000000000000..457d53f0f637 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/websocket.pyi @@ -0,0 +1,40 @@ +import asyncio +from typing import Final + +from gunicorn.glogging import Logger as GLogger + +from .._types import _ASGIAppType, _ScopeType + +OPCODE_CONTINUATION: Final = 0x0 +OPCODE_TEXT: Final = 0x1 +OPCODE_BINARY: Final = 0x2 +OPCODE_CLOSE: Final = 0x8 +OPCODE_PING: Final = 0x9 +OPCODE_PONG: Final = 0xA +CLOSE_NORMAL: Final = 1000 +CLOSE_GOING_AWAY: Final = 1001 +CLOSE_PROTOCOL_ERROR: Final = 1002 +CLOSE_UNSUPPORTED: Final = 1003 +CLOSE_NO_STATUS: Final = 1005 +CLOSE_ABNORMAL: Final = 1006 +CLOSE_INVALID_DATA: Final = 1007 +CLOSE_POLICY_VIOLATION: Final = 1008 +CLOSE_MESSAGE_TOO_BIG: Final = 1009 +CLOSE_MANDATORY_EXT: Final = 1010 +CLOSE_INTERNAL_ERROR: Final = 1011 +WS_GUID: Final = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +class WebSocketProtocol: + transport: asyncio.Transport + scope: _ScopeType + app: _ASGIAppType + log: GLogger + accepted: bool + closed: bool + close_code: int | None + close_reason: str | None + + def __init__(self, transport: asyncio.Transport, scope: _ScopeType, app: _ASGIAppType, log: GLogger) -> None: ... + def feed_data(self, data: bytes) -> None: ... + def feed_eof(self) -> None: ... + async def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/config.pyi b/stubs/gunicorn/gunicorn/config.pyi new file mode 100644 index 000000000000..390a6d591365 --- /dev/null +++ b/stubs/gunicorn/gunicorn/config.pyi @@ -0,0 +1,1348 @@ +import argparse +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Container +from ssl import SSLContext, _SSLMethod +from typing import Annotated, Any, ClassVar, Final, TypeAlias, overload + +from gunicorn.arbiter import Arbiter +from gunicorn.glogging import Logger as GLogger +from gunicorn.http import Request +from gunicorn.http.wsgi import Response +from gunicorn.workers.base import Worker + +from ._types import _AddressType, _EnvironType + +_ConfigValueType: TypeAlias = Any +# Any: Value type depends on the setting's validator (e.g., validate_bool, validate_pos_int). +# Maybe types: bool, int, str, list[str], dict[str, Any], Callable[..., object], type[object], ssl.PROTOCOL_*. +# Validator ensures type correctness at runtime. + +_OnStartingHookType: TypeAlias = Callable[[Arbiter], object] +_OnReloadHookType: TypeAlias = Callable[[Arbiter], object] +_WhenReadyHookType: TypeAlias = Callable[[Arbiter], object] +_PreForkHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_PostForkHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_PostWorkerInitHookType: TypeAlias = Callable[[Worker], object] +_WorkerIntHookType: TypeAlias = Callable[[Worker], object] +_WorkerAbortHookType: TypeAlias = Callable[[Worker], object] +_PreExecHookType: TypeAlias = Callable[[Arbiter], object] +_PreRequestHookType: TypeAlias = Callable[[Worker, Request], object] +_PostRequestHookType: TypeAlias = Callable[[Worker, Request, _EnvironType, Response], object] +_ChildExitHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_WorkerExitHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_NumWorkersChangedHookType: TypeAlias = Callable[[Arbiter, int, int | None], object] +_OnExitHookType: TypeAlias = Callable[[Arbiter], object] +_SSLContextHookType: TypeAlias = Callable[[Config, Callable[[], SSLContext]], SSLContext] +_OnDirtyStartingHookType: TypeAlias = Callable[[Arbiter], object] +_DirtyPostForkHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_DirtyWorkerInitHookType: TypeAlias = Callable[[Worker], object] +_DirtyWorkerExitHookType: TypeAlias = Callable[[Arbiter, Worker], object] + +_HookType: TypeAlias = ( + _OnStartingHookType + | _OnReloadHookType + | _WhenReadyHookType + | _PreForkHookType + | _PostForkHookType + | _PostWorkerInitHookType + | _WorkerIntHookType + | _WorkerAbortHookType + | _PreExecHookType + | _PreRequestHookType + | _PostRequestHookType + | _ChildExitHookType + | _WorkerExitHookType + | _NumWorkersChangedHookType + | _OnExitHookType + | _SSLContextHookType + | _OnDirtyStartingHookType + | _DirtyPostForkHookType + | _DirtyWorkerInitHookType + | _DirtyWorkerExitHookType +) +# Validators +_BoolValidatorType: TypeAlias = Callable[[bool | str | None], bool | None] +_StringValidatorType: TypeAlias = Callable[[str | None], str | None] +_ListStringValidatorType: TypeAlias = Callable[[str | list[str] | None], list[str]] +_IntValidatorType: TypeAlias = Callable[[ConvertibleToInt], int] +_DictValidatorType: TypeAlias = Callable[[dict[str, Any]], dict[str, Any]] +_ClassValidatorType: TypeAlias = Callable[[object | str | None], type[Any] | None] +_UserGroupValidatorType: TypeAlias = Callable[[str | int | None], int] +_AddressValidatorType: TypeAlias = Callable[[str | None], _AddressType | None] +_CallableValidatorType: TypeAlias = Callable[[str | _HookType], _HookType] +_ProxyProtocolValidatorType: TypeAlias = Callable[[str | bool | None], str] +_ASGILoopValidatorType: TypeAlias = Callable[[str | None], str] +_ASGILifespanValidatorType: TypeAlias = Callable[[str | None], str] +_HTTP2FrameSizeValidatorType: TypeAlias = Callable[[ConvertibleToInt], int] +_HTTPProtocolsValidatorType: TypeAlias = Callable[[str | None], list[str]] +_HttpParserValidatorType: TypeAlias = Callable[[str | None], str] +_HTTP2CleartextValidatorType: TypeAlias = Callable[[str | bool | None], str] + +_ValidatorType: TypeAlias = ( # noqa: Y047 + _BoolValidatorType + | _StringValidatorType + | _ListStringValidatorType + | _IntValidatorType + | _DictValidatorType + | _ClassValidatorType + | _UserGroupValidatorType + | _AddressValidatorType + | _CallableValidatorType + | _ProxyProtocolValidatorType + | _ASGILoopValidatorType + | _ASGILifespanValidatorType + | _HTTP2FrameSizeValidatorType + | _HTTPProtocolsValidatorType + | _HttpParserValidatorType + | _HTTP2CleartextValidatorType +) + +KNOWN_SETTINGS: list[Setting] +PLATFORM: str + +def make_settings(ignore: Container[Setting] | None = None) -> dict[str, Setting]: ... +def auto_int(_: Any, x: str) -> int: ... + +class Config: + settings: dict[str, Setting] + usage: str | None + prog: str | None + env_orig: dict[str, str] + + def __init__(self, usage: str | None = None, prog: str | None = None) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def set(self, name: str, value: _ConfigValueType) -> None: ... + def get_cmd_args_from_env(self) -> list[str]: ... + def parser(self) -> argparse.ArgumentParser: ... + @property + def worker_class_str(self) -> str: ... + @property + def worker_class(self) -> type[Worker]: ... + @property + def address(self) -> list[_AddressType]: ... + @property + def uid(self) -> int: ... + @property + def gid(self) -> int: ... + @property + def proc_name(self) -> str | None: ... + @property + def logger_class(self) -> type[GLogger]: ... + @property + def is_ssl(self) -> bool: ... + @property + def ssl_options(self) -> dict[str, Any]: ... + @property + def env(self) -> dict[str, str]: ... + @property + def sendfile(self) -> bool: ... + @property + def reuse_port(self) -> bool: ... + @property + def paste_global_conf(self) -> dict[str, str] | None: ... + +class SettingMeta(type): + def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> SettingMeta: ... + def fmt_desc(cls, desc: str) -> None: ... + +class Setting(metaclass=SettingMeta): + name: ClassVar[str | None] + value: _ConfigValueType + section: ClassVar[str | None] + cli: ClassVar[list[str] | None] + validator: ClassVar[Callable[..., Any] | None] # See `_ValidatorType` + type: ClassVar[argparse._ActionType | None] + meta: ClassVar[str | None] + action: ClassVar[str | None] + default: ClassVar[Any] + short: ClassVar[str | None] + desc: ClassVar[str | None] + nargs: ClassVar[int | str | None] + const: ClassVar[bool | str | None] + order: ClassVar[int] + + def __init__(self) -> None: ... + def add_option(self, parser: argparse.ArgumentParser) -> None: ... + def copy(self) -> Setting: ... + def get(self) -> _ConfigValueType: ... + def set(self, val: _ConfigValueType) -> None: ... + def __lt__(self, other: Setting) -> bool: ... + + __cmp__ = __lt__ + +def validate_http2_cleartext(val: str | bool | None) -> str: ... + +@overload +def validate_bool(val: bool) -> bool: ... +@overload +def validate_bool(val: None) -> None: ... +@overload +def validate_bool(val: Annotated[str, "Case-insensitive boolean string ('true'/'false' in any case)"]) -> bool: ... + +def validate_dict(val: dict[str, Any]) -> dict[str, Any]: ... +def validate_pos_int(val: ConvertibleToInt) -> int: ... +def validate_http2_frame_size(val: ConvertibleToInt) -> int: ... +def validate_ssl_version(val: _SSLMethod) -> _SSLMethod: ... + +@overload +def validate_string(val: str) -> str: ... +@overload +def validate_string(val: None) -> None: ... + +@overload +def validate_file_exists(val: str) -> str: ... +@overload +def validate_file_exists(val: None) -> None: ... + +def validate_list_string(val: str | list[str] | None) -> list[str]: ... +def validate_list_of_files_or_patterns(val: str | list[str] | None) -> list[str]: ... +def validate_string_to_addr_list(val: str | None) -> list[str]: ... +def validate_string_to_list(val: str | None) -> list[str]: ... + +@overload +def validate_class(val: str) -> str: ... +@overload +def validate_class(val: None) -> None: ... +@overload +def validate_class(val: object) -> object: ... + +def validate_callable(arity: int) -> _CallableValidatorType: ... +def validate_user(val: int | str | None) -> int: ... +def validate_group(val: int | str | None) -> int: ... +def validate_post_request(val: str | _HookType) -> _PostRequestHookType: ... +def validate_chdir(val: str) -> str: ... + +@overload +def validate_statsd_address(val: str) -> _AddressType: ... +@overload +def validate_statsd_address(val: None) -> None: ... + +def validate_reload_engine(val: str) -> str: ... + +@overload +def validate_header_map_behaviour(val: str) -> str: ... +@overload +def validate_header_map_behaviour(val: None) -> None: ... + +def get_default_config_file() -> str | None: ... + +class ConfigFile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class WSGIApp(Setting): + name: ClassVar[str] + section: ClassVar[str] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class Bind(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class Backlog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Workers(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class WorkerClass(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ClassValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class WorkerThreads(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class WorkerConnections(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class MaxRequests(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class MaxRequestsJitter(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Timeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class GracefulTimeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Keepalive(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class LimitRequestLine(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class LimitRequestFields(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class LimitRequestFieldSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Reload(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class ReloadEngine(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[Callable[[str], str]] + default: ClassVar[str] + desc: ClassVar[str] + +class ReloadExtraFiles(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class Spew(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class ConfigCheck(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PrintConfig(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PreloadApp(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Sendfile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + const: ClassVar[bool] + desc: ClassVar[str] + +class ReusePort(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Chdir(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[Callable[[str], str]] + default: ClassVar[str] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class Daemon(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Env(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class Pidfile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class WorkerTmpDir(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class User(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_UserGroupValidatorType] + default: ClassVar[int] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class Group(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_UserGroupValidatorType] + default: ClassVar[int] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class Umask(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[Callable[[Any, str], int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Initgroups(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class TmpUploadDir(Setting): + name: ClassVar[str] + section: ClassVar[str] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SecureSchemeHeader(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_DictValidatorType] + default: ClassVar[dict[str, str]] + desc: ClassVar[str] + +class ForwardedAllowIPS(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class AccessLog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class DisableRedirectAccessToSyslog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class AccessLogFormat(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class ErrorLog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class Loglevel(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class CaptureOutput(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class LoggerClass(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ClassValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class LogConfig(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class LogConfigDict(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_DictValidatorType] + default: ClassVar[dict[str, Any]] + desc: ClassVar[str] + +class LogConfigJson(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SyslogTo(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + default_doc: ClassVar[str] + +class Syslog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class SyslogPrefix(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SyslogFacility(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class EnableStdioInheritance(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + default: ClassVar[bool] + action: ClassVar[str] + desc: ClassVar[str] + +class StatsdHost(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + default: ClassVar[None] + validator: ClassVar[_AddressValidatorType] + desc: ClassVar[str] + +class DogstatsdTags(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + default: ClassVar[str] + validator: ClassVar[_StringValidatorType] + desc: ClassVar[str] + +class StatsdPrefix(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + default: ClassVar[str] + validator: ClassVar[_StringValidatorType] + desc: ClassVar[str] + +class BacklogMetric(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + default: ClassVar[bool] + action: ClassVar[str] + desc: ClassVar[str] + +class Procname(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class DefaultProcName(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class PythonPath(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class Paste(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class OnStarting(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_OnStartingHookType] + desc: ClassVar[str] + + def on_starting(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class OnReload(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_OnReloadHookType] + desc: ClassVar[str] + + def on_reload(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WhenReady(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WhenReadyHookType] + desc: ClassVar[str] + + def when_ready(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class Prefork(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PreForkHookType] + desc: ClassVar[str] + + def pre_fork(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class Postfork(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PostForkHookType] + desc: ClassVar[str] + + def post_fork(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PostWorkerInit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PostWorkerInitHookType] + desc: ClassVar[str] + + def post_worker_init(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WorkerInt(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WorkerIntHookType] + desc: ClassVar[str] + + def worker_int(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WorkerAbort(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WorkerAbortHookType] + desc: ClassVar[str] + + def worker_abort(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PreExec(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PreExecHookType] + desc: ClassVar[str] + + def pre_exec(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PreRequest(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PreRequestHookType] + desc: ClassVar[str] + + def pre_request(worker: Worker, req: Request) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PostRequest(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PostRequestHookType] + desc: ClassVar[str] + + def post_request(worker: Worker, req: Request, environ: _EnvironType, resp: Response) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class ChildExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_ChildExitHookType] + desc: ClassVar[str] + + def child_exit(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WorkerExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WorkerExitHookType] + desc: ClassVar[str] + + def worker_exit(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class NumWorkersChanged(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_NumWorkersChangedHookType] + desc: ClassVar[str] + + def nworkers_changed(server: Arbiter, new_value: int, old_value: int | None) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class OnExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + default: ClassVar[_OnExitHookType] + desc: ClassVar[str] + + def on_exit(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class NewSSLContext(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_SSLContextHookType] + desc: ClassVar[str] + + def ssl_context(config: Config, default_ssl_context_factory: Callable[[], SSLContext]) -> SSLContext: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +def validate_proxy_protocol(val: str | bool | None) -> str: ... + +class ProxyProtocol(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ProxyProtocolValidatorType] + default: ClassVar[str] + nargs: ClassVar[str] + const: ClassVar[str] + desc: ClassVar[str] + +class ProxyAllowFrom(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class Protocol(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class UWSGIAllowFrom(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class KeyFile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class CertFile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SSLVersion(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[Callable[[_SSLMethod], _SSLMethod]] + default: ClassVar[_SSLMethod] + desc: ClassVar[str] + +class CertReqs(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_IntValidatorType] + default: ClassVar[int] + desc: ClassVar[str] + +class CACerts(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SuppressRaggedEOFs(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + action: ClassVar[str] + default: ClassVar[bool] + validator: ClassVar[_BoolValidatorType] + desc: ClassVar[str] + +class DoHandshakeOnConnect(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Ciphers(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +VALID_HTTP_PROTOCOLS: Final[frozenset[str]] +ALPN_PROTOCOL_MAP: Final[dict[str, str]] + +def validate_http_protocols(val: str | None) -> list[str]: ... + +class HTTPProtocols(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HTTPProtocolsValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class HTTP2Cleartext(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HTTP2CleartextValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class HTTP2MaxConcurrentStreams(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HTTP2InitialWindowSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HTTP2MaxFrameSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HTTP2FrameSizeValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HTTP2MaxHeaderListSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class PasteGlobalConf(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class PermitObsoleteFolding(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class StripHeaderSpaces(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PermitUnconventionalHTTPMethod(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PermitUnconventionalHTTPVersion(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class CasefoldHTTPMethod(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class ForwarderHeaders(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class HeaderMap(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +def validate_asgi_loop(val: str | None) -> str: ... +def validate_asgi_lifespan(val: str | None) -> str: ... +def validate_http_parser(val: str | None) -> str: ... + +class ASGILoop(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ASGILoopValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class ASGILifespan(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ASGILifespanValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class ASGIDisconnectGracePeriod(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HttpParser(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HttpParserValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class RootPath(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class DirtyApps(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + action: ClassVar[str] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class DirtyWorkers(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class DirtyTimeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class DirtyThreads(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class DirtyGracefulTimeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class OnDirtyStarting(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_OnDirtyStartingHookType] + desc: ClassVar[str] + + def on_dirty_starting(arbiter: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class DirtyPostFork(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_DirtyPostForkHookType] + desc: ClassVar[str] + + def dirty_post_fork(arbiter: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class DirtyWorkerInit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_DirtyWorkerInitHookType] + desc: ClassVar[str] + + def dirty_worker_init(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class DirtyWorkerExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_DirtyWorkerExitHookType] + desc: ClassVar[str] + + def dirty_worker_exit(arbiter: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class ControlSocket(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class ControlSocketMode(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[Callable[[Any, str], int]] + default: ClassVar[int] + desc: ClassVar[str] + +class ControlSocketDisable(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] diff --git a/stubs/gunicorn/gunicorn/ctl/__init__.pyi b/stubs/gunicorn/gunicorn/ctl/__init__.pyi new file mode 100644 index 000000000000..03f497fa809f --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/__init__.pyi @@ -0,0 +1,5 @@ +from gunicorn.ctl.client import ControlClient as ControlClient +from gunicorn.ctl.protocol import ControlProtocol as ControlProtocol +from gunicorn.ctl.server import ControlSocketServer as ControlSocketServer + +__all__ = ["ControlSocketServer", "ControlClient", "ControlProtocol"] diff --git a/stubs/gunicorn/gunicorn/ctl/cli.pyi b/stubs/gunicorn/gunicorn/ctl/cli.pyi new file mode 100644 index 000000000000..e0e4775c6910 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/cli.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +def format_workers(data: dict[str, Incomplete]) -> str: ... +def format_dirty(data: dict[str, Incomplete]) -> str: ... +def format_stats(data: dict[str, Incomplete]) -> str: ... +def format_listeners(data: dict[str, Incomplete]) -> str: ... +def format_config(data: dict[str, Incomplete]) -> str: ... +def format_help(data: dict[str, Incomplete]) -> str: ... +def format_all(data: dict[str, Incomplete]) -> str: ... +def format_response(command: str, data: dict[str, Incomplete]) -> str: ... +def run_command(socket_path: str, command: str, json_output: bool = False) -> int: ... +def run_interactive(socket_path: str, json_output: bool = False) -> int: ... +def main() -> int: ... diff --git a/stubs/gunicorn/gunicorn/ctl/client.pyi b/stubs/gunicorn/gunicorn/ctl/client.pyi new file mode 100644 index 000000000000..7cc5912eed33 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/client.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete, Unused +from typing_extensions import Self + +class ControlClientError(Exception): ... + +class ControlClient: + socket_path: str + timeout: float + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def send_command(self, command: str, args: list[str] | None = None) -> dict[Incomplete, Incomplete]: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + +def parse_command(line: str) -> tuple[str, list[str]]: ... diff --git a/stubs/gunicorn/gunicorn/ctl/handlers.pyi b/stubs/gunicorn/gunicorn/ctl/handlers.pyi new file mode 100644 index 000000000000..7814cef1cb3c --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/handlers.pyi @@ -0,0 +1,113 @@ +from _typeshed import Incomplete +from typing import Literal, TypedDict, type_check_only +from typing_extensions import NotRequired + +from gunicorn.arbiter import Arbiter + +@type_check_only +class _Worker(TypedDict): + pid: int + age: int + booted: bool + last_heartbeat: float + aborted: NotRequired[bool] + apps: NotRequired[list[str]] + +@type_check_only +class _ShowWorkersReturnType(TypedDict): + workers: list[_Worker] + count: int + +@type_check_only +class _App(TypedDict): + import_path: str + worker_count: int | None + current_workers: int + worker_pids: list[int] + +@type_check_only +class _ShowDirtyReturnType(TypedDict): + enabled: bool + pid: int | None + workers: list[_Worker] + apps: list[_App] + +@type_check_only +class _ShowStatsReturnType(TypedDict): + uptime: float | None + pid: int + workers_current: int + workers_target: int + workers_spawned: int + workers_killed: int + reloads: int + dirty_arbiter_pid: int | None + +@type_check_only +class _ListenerInfo(TypedDict): + address: str + fd: int + type: Literal["unix", "tcp", "tcp6", "unknown"] + +@type_check_only +class _ShowListenersReturnType(TypedDict): + listeners: list[_ListenerInfo] + count: int + +@type_check_only +class _WorkerAddReturnType(TypedDict): + added: int + previous: int + total: int + +@type_check_only +class _WorkerRemovedReturnType(TypedDict): + removed: int + previous: int + total: int + +@type_check_only +class _WorkerKillSucessReturnType(TypedDict): + success: Literal[True] + killed: int + +@type_check_only +class _WorkerKillFailedReturnType(TypedDict): + success: Literal[False] + error: str + +@type_check_only +class _ReloadReturnType(TypedDict): + status: Literal["reloading"] + +@type_check_only +class _ReopenReturnType(TypedDict): + status: Literal["reopening"] + +@type_check_only +class _ShutdownReturnType(TypedDict): + status: Literal["shutting_down"] + mode: str + +@type_check_only +class _HelpReturnType(TypedDict): + commands: dict[str, str] + +class CommandHandlers: + arbiter: Arbiter + def __init__(self, arbiter: Arbiter) -> None: ... + def show_workers(self) -> _ShowWorkersReturnType: ... + def show_dirty(self) -> _ShowDirtyReturnType: ... + def show_config(self) -> dict[str, Incomplete]: ... + def show_stats(self) -> _ShowStatsReturnType: ... + def show_listeners(self) -> _ShowListenersReturnType: ... + def worker_add(self, count: int = 1) -> _WorkerAddReturnType: ... + def worker_remove(self, count: int = 1) -> _WorkerRemovedReturnType: ... + def worker_kill(self, pid: int) -> _WorkerKillSucessReturnType | _WorkerKillFailedReturnType: ... + def dirty_add(self, count: int = 1) -> dict[str, Incomplete]: ... + def dirty_remove(self, count: int = 1) -> dict[str, Incomplete]: ... + def reload(self) -> _ReloadReturnType: ... + def reopen(self) -> _ReopenReturnType: ... + def shutdown(self, mode: str = "graceful") -> _ShutdownReturnType: ... + def show_all(self) -> dict[str, Incomplete]: ... + def help(self) -> _HelpReturnType: ... diff --git a/stubs/gunicorn/gunicorn/ctl/protocol.pyi b/stubs/gunicorn/gunicorn/ctl/protocol.pyi new file mode 100644 index 000000000000..c4a8a62cee27 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/protocol.pyi @@ -0,0 +1,45 @@ +from asyncio import StreamReader, StreamWriter +from socket import socket +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _CtlRequest(TypedDict): + id: int + command: str + args: list[str] + +@type_check_only +class _CtlSuccessResponse(TypedDict): + id: int + status: Literal["ok"] + data: dict[str, Any] + +@type_check_only +class _CtlErrorResponse(TypedDict): + id: int + status: Literal["error"] + error: str + +_CtlResponse: TypeAlias = _CtlSuccessResponse | _CtlErrorResponse +_CtlMessage: TypeAlias = _CtlRequest | _CtlResponse + +class ProtocolError(Exception): ... + +class ControlProtocol: + MAX_MESSAGE_SIZE: ClassVar[int] + @staticmethod + def encode_message(data: _CtlMessage) -> bytes: ... + @staticmethod + def decode_message(data: bytes) -> _CtlMessage: ... + @staticmethod + def read_message(sock: socket) -> _CtlMessage: ... + @staticmethod + def write_message(sock: socket, data: _CtlMessage) -> None: ... + @staticmethod + async def read_message_async(reader: StreamReader) -> _CtlMessage: ... + @staticmethod + async def write_message_async(writer: StreamWriter, data: _CtlMessage) -> None: ... + +def make_request(request_id: int, command: str, args: list[str] | None = None) -> _CtlRequest: ... +def make_response(request_id: int, data: dict[str, Any] | None = None) -> _CtlSuccessResponse: ... +def make_error_response(request_id: int, error: str) -> _CtlErrorResponse: ... diff --git a/stubs/gunicorn/gunicorn/ctl/server.pyi b/stubs/gunicorn/gunicorn/ctl/server.pyi new file mode 100644 index 000000000000..0ab97c7a2df9 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/server.pyi @@ -0,0 +1,11 @@ +from gunicorn.arbiter import Arbiter +from gunicorn.ctl.handlers import CommandHandlers + +class ControlSocketServer: + arbiter: Arbiter + socket_path: str + socket_mode: int + handlers: CommandHandlers + def __init__(self, arbiter: Arbiter, socket_path: str, socket_mode: int = 0o600) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/debug.pyi b/stubs/gunicorn/gunicorn/debug.pyi new file mode 100644 index 000000000000..8769f873c587 --- /dev/null +++ b/stubs/gunicorn/gunicorn/debug.pyi @@ -0,0 +1,18 @@ +__all__ = ["spew", "unspew"] + +from collections.abc import Container +from types import FrameType +from typing import Any +from typing_extensions import Self + +class Spew: + trace_names: Container[str] | None = None + show_values: bool + + def __init__(self, trace_names: Container[str] | None = None, show_values: bool = True) -> None: ... + def __call__( + self, frame: FrameType, event: str, arg: Any # `arg` is not used inside the function, stub is set Any + ) -> Self: ... + +def spew(trace_names: Container[str] | None = None, show_values: bool = False) -> None: ... +def unspew() -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/__init__.pyi b/stubs/gunicorn/gunicorn/dirty/__init__.pyi new file mode 100644 index 000000000000..9d0294631e6f --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/__init__.pyi @@ -0,0 +1,51 @@ +from . import stash as stash +from .app import DirtyApp as DirtyApp +from .arbiter import DirtyArbiter as DirtyArbiter +from .client import ( + DirtyClient as DirtyClient, + close_dirty_client as close_dirty_client, + close_dirty_client_async as close_dirty_client_async, + get_dirty_client as get_dirty_client, + get_dirty_client_async as get_dirty_client_async, + set_dirty_socket_path as set_dirty_socket_path, +) +from .errors import ( + DirtyAppError as DirtyAppError, + DirtyAppNotFoundError as DirtyAppNotFoundError, + DirtyConnectionError as DirtyConnectionError, + DirtyError as DirtyError, + DirtyProtocolError as DirtyProtocolError, + DirtyTimeoutError as DirtyTimeoutError, + DirtyWorkerError as DirtyWorkerError, +) +from .stash import ( + StashClient as StashClient, + StashError as StashError, + StashKeyNotFoundError as StashKeyNotFoundError, + StashTable as StashTable, + StashTableNotFoundError as StashTableNotFoundError, +) + +__all__ = [ + "DirtyError", + "DirtyTimeoutError", + "DirtyConnectionError", + "DirtyWorkerError", + "DirtyAppError", + "DirtyAppNotFoundError", + "DirtyProtocolError", + "DirtyApp", + "DirtyClient", + "get_dirty_client", + "get_dirty_client_async", + "close_dirty_client", + "close_dirty_client_async", + "stash", + "StashClient", + "StashTable", + "StashError", + "StashTableNotFoundError", + "StashKeyNotFoundError", + "DirtyArbiter", + "set_dirty_socket_path", +] diff --git a/stubs/gunicorn/gunicorn/dirty/app.pyi b/stubs/gunicorn/gunicorn/dirty/app.pyi new file mode 100644 index 000000000000..c2355e8c438c --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/app.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Any + +class DirtyApp: + workers: Incomplete | None + + def init(self) -> None: ... + def __call__( + self, action: str, *args: Any, **kwargs: Any + ) -> Any: ... # Arguments and result depend on method name passed to action + def close(self) -> None: ... + +def parse_dirty_app_spec(spec: str) -> tuple[str, int | None]: ... +def load_dirty_app(import_path: str): ... +def load_dirty_apps(import_paths: Iterable[str]) -> dict[str, Incomplete]: ... +def get_app_workers_attribute(import_path: str) -> int | None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/arbiter.pyi b/stubs/gunicorn/gunicorn/dirty/arbiter.pyi new file mode 100644 index 000000000000..c1e9114c29a3 --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/arbiter.pyi @@ -0,0 +1,48 @@ +import asyncio +from _typeshed import Incomplete +from asyncio import StreamReader, StreamWriter +from signal import Signals +from typing import ClassVar + +from gunicorn.config import Config +from gunicorn.dirty.worker import DirtyWorker +from gunicorn.glogging import Logger as GLogger + +class DirtyArbiter: + SIGNALS: ClassVar[list[Signals]] + WORKER_BOOT_ERROR: ClassVar[int] + cfg: Config + log: GLogger + pid: int | None + ppid: int + pidfile: str | None + tmpdir: str + socket_path: str + workers: dict[int, DirtyWorker] + worker_sockets: dict[int, str] + worker_connections: dict[int, tuple[Incomplete, Incomplete]] + worker_queues: dict[int, asyncio.Queue[Incomplete]] + worker_consumers: dict[int, asyncio.Task[None]] + worker_age: int + alive: bool + num_workers: int + app_specs: dict[str, dict[Incomplete, Incomplete]] + app_worker_map: dict[str, set[Incomplete]] + worker_app_map: dict[int, list[Incomplete]] + stash_tables: dict[str, dict[Incomplete, Incomplete]] + + def __init__(self, cfg: Config, log: GLogger, socket_path: str | None = None, pidfile: str | None = None) -> None: ... + def run(self) -> None: ... + def init_signals(self) -> None: ... + async def handle_client(self, reader: StreamReader, writer: StreamWriter) -> None: ... + async def route_request(self, request: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def handle_status_request(self, message: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def handle_manage_request(self, message: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def handle_stash_request(self, message: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def manage_workers(self) -> None: ... + def spawn_worker(self, force_all_apps: bool = False) -> int | None: ... + def kill_worker(self, pid: int, sig: int) -> None: ... + async def murder_workers(self) -> None: ... + def reap_workers(self) -> None: ... + async def reload(self) -> None: ... + async def stop(self, graceful: bool = True) -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/client.pyi b/stubs/gunicorn/gunicorn/dirty/client.pyi new file mode 100644 index 000000000000..3d77eb9a31df --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/client.pyi @@ -0,0 +1,74 @@ +from _typeshed import Incomplete +from types import TracebackType +from typing import Any, ClassVar +from typing_extensions import Self + +class DirtyClient: + socket_path: str + timeout: float + + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: ... + def connect(self) -> None: ... + # Arguments and result depend on app path and method name passed to action + def execute(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> Any: ... + def stream(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> DirtyStreamIterator: ... + def close(self) -> None: ... + async def connect_async(self) -> None: ... + async def execute_async(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> Any: ... + def stream_async(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> DirtyAsyncStreamIterator: ... + async def close_async(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class DirtyStreamIterator: + DEFAULT_IDLE_TIMEOUT: ClassVar[float] + client: DirtyClient + app_path: str + action: str + args: tuple[Incomplete, ...] + kwargs: dict[str, Incomplete] + + def __init__( + self, + client: DirtyClient, + app_path: str, + action: str, + args: tuple[Incomplete, ...], + kwargs: dict[str, Incomplete], + idle_timeout: float | None = None, + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> Incomplete | None: ... + +class DirtyAsyncStreamIterator: + DEFAULT_IDLE_TIMEOUT: ClassVar[float] + client: DirtyClient + app_path: str + action: str + args: tuple[Incomplete, ...] + kwargs: dict[str, Incomplete] + + def __init__( + self, + client: DirtyClient, + app_path: str, + action: str, + args: tuple[Incomplete, ...], + kwargs: dict[str, Incomplete], + idle_timeout: float | None = None, + ) -> None: ... + def __aiter__(self) -> Self: ... + async def __anext__(self) -> Incomplete | None: ... + +def set_dirty_socket_path(path: str) -> None: ... +def get_dirty_socket_path() -> str: ... +def get_dirty_client(timeout: float = 30.0) -> DirtyClient: ... +async def get_dirty_client_async(timeout: float = 30.0) -> DirtyClient: ... +def close_dirty_client() -> None: ... +async def close_dirty_client_async() -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/errors.pyi b/stubs/gunicorn/gunicorn/dirty/errors.pyi new file mode 100644 index 000000000000..0bfd9ed341ab --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/errors.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +@type_check_only +class _DirtyErrorDict(TypedDict): + error_type: str + message: str + details: dict[str, Incomplete] + +class DirtyError(Exception): + message: str + details: dict[str, Incomplete] + + def __init__(self, message: str, details: dict[str, Incomplete] | None = None) -> None: ... + def to_dict(self) -> _DirtyErrorDict: ... + @classmethod + def from_dict(cls, data: dict[str, Incomplete]) -> DirtyError: ... + +class DirtyTimeoutError(DirtyError): + timeout: float | None + + def __init__(self, message: str = "Operation timed out", timeout: float | None = None) -> None: ... + +class DirtyConnectionError(DirtyError): + socket_path: str | None + + def __init__(self, message: str = "Connection failed", socket_path: str | None = None) -> None: ... + +class DirtyWorkerError(DirtyError): + worker_id: int | None + traceback: str | None + + def __init__(self, message: str, worker_id: int | None = None, traceback: str | None = None) -> None: ... + +class DirtyAppError(DirtyError): + app_path: str | None + action: str | None + traceback: str | None + + def __init__( + self, message: str, app_path: str | None = None, action: str | None = None, traceback: str | None = None + ) -> None: ... + +class DirtyAppNotFoundError(DirtyAppError): + app_path: str + + def __init__(self, app_path: str) -> None: ... + +class DirtyNoWorkersAvailableError(DirtyError): + app_path: str + + def __init__(self, app_path: str, message: str | None = None) -> None: ... + +class DirtyProtocolError(DirtyError): + def __init__(self, message: str = "Protocol error", raw_data: str | bytes | None = None) -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/protocol.pyi b/stubs/gunicorn/gunicorn/dirty/protocol.pyi new file mode 100644 index 000000000000..66135ae193bf --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/protocol.pyi @@ -0,0 +1,171 @@ +import asyncio +import socket +from _typeshed import Incomplete +from typing import ClassVar, Final, Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +from .errors import _DirtyErrorDict + +MAGIC: Final = b"GD" +VERSION: Final = 0x01 +MSG_TYPE_REQUEST: Final = 0x01 +MSG_TYPE_RESPONSE: Final = 0x02 +MSG_TYPE_ERROR: Final = 0x03 +MSG_TYPE_CHUNK: Final = 0x04 +MSG_TYPE_END: Final = 0x05 +MSG_TYPE_STASH: Final = 0x10 +MSG_TYPE_STATUS: Final = 0x11 +MSG_TYPE_MANAGE: Final = 0x12 +MSG_TYPE_REQUEST_STR: Final = "request" +MSG_TYPE_RESPONSE_STR: Final = "response" +MSG_TYPE_ERROR_STR: Final = "error" +MSG_TYPE_CHUNK_STR: Final = "chunk" +MSG_TYPE_END_STR: Final = "end" +MSG_TYPE_STASH_STR: Final = "stash" +MSG_TYPE_STATUS_STR: Final = "status" +MSG_TYPE_MANAGE_STR: Final = "manage" +MSG_TYPE_TO_STR: Final[dict[int, str]] +MSG_TYPE_FROM_STR: Final[dict[str, int]] +STASH_OP_PUT: Final = 1 +STASH_OP_GET: Final = 2 +STASH_OP_DELETE: Final = 3 +STASH_OP_KEYS: Final = 4 +STASH_OP_CLEAR: Final = 5 +STASH_OP_INFO: Final = 6 +STASH_OP_ENSURE: Final = 7 +STASH_OP_DELETE_TABLE: Final = 8 +STASH_OP_TABLES: Final = 9 +STASH_OP_EXISTS: Final = 10 +MANAGE_OP_ADD: Final = 1 +MANAGE_OP_REMOVE: Final = 2 +HEADER_FORMAT: Final = ">2sBBIQ" +HEADER_SIZE: Final[int] +MAX_MESSAGE_SIZE: Final = 67108864 + +@type_check_only +class _DirtyRequest(TypedDict): + type: Literal["request"] + id: int | str + app_path: str + action: str + args: list[Incomplete] + kwargs: dict[str, Incomplete] + +@type_check_only +class _DirtyResponse(TypedDict): + type: Literal["response"] + id: int | str + result: Incomplete + +@type_check_only +class _DirtyErrorResponse(TypedDict): + type: Literal["error"] + id: int | str + error: _DirtyErrorDict | dict[str, Incomplete] + +@type_check_only +class _DirtyChunkMessage(TypedDict): + type: Literal["chunk"] + id: int | str + data: Incomplete + +@type_check_only +class _DirtyEndMessage(TypedDict): + type: Literal["end"] + id: int | str + +@type_check_only +class _DirtyStashMessage(TypedDict): + type: Literal["stash"] + id: int | str + op: int + table: str + key: NotRequired[Incomplete] + value: NotRequired[Incomplete] + pattern: NotRequired[Incomplete] + +@type_check_only +class _DirtyManageMessage(TypedDict): + type: Literal["manage"] + id: int | str + op: int + count: int + +_DirtyMessage: TypeAlias = ( + _DirtyRequest + | _DirtyResponse + | _DirtyErrorResponse + | _DirtyChunkMessage + | _DirtyEndMessage + | _DirtyStashMessage + | _DirtyManageMessage +) + +class BinaryProtocol: + HEADER_SIZE: ClassVar[int] + MAX_MESSAGE_SIZE: ClassVar[int] + MSG_TYPE_REQUEST: ClassVar[str] + MSG_TYPE_RESPONSE: ClassVar[str] + MSG_TYPE_ERROR: ClassVar[str] + MSG_TYPE_CHUNK: ClassVar[str] + MSG_TYPE_END: ClassVar[str] + MSG_TYPE_STASH: ClassVar[str] + MSG_TYPE_STATUS: ClassVar[str] + MSG_TYPE_MANAGE: ClassVar[str] + + @staticmethod + def encode_header(msg_type: int, request_id: int, payload_length: int) -> bytes: ... + @staticmethod + def decode_header(data: bytes) -> tuple[int, int, int]: ... + @staticmethod + def encode_request( + request_id: int, + app_path: str, + action: str, + args: tuple[Incomplete, ...] | None = None, + kwargs: dict[str, Incomplete] | None = None, + ) -> bytes: ... + @staticmethod + def encode_response(request_id: int, result) -> bytes: ... + @staticmethod + def encode_error(request_id: int, error: BaseException | dict[str, Incomplete]) -> bytes: ... + @staticmethod + def encode_chunk(request_id: int, data) -> bytes: ... + @staticmethod + def encode_end(request_id: int) -> bytes: ... + @staticmethod + def encode_status(request_id: int) -> bytes: ... + @staticmethod + def encode_manage(request_id: int, op: int, count: int = 1) -> bytes: ... + @staticmethod + def encode_stash(request_id: int, op: int, table: str, key=None, value=None, pattern=None) -> bytes: ... + @staticmethod + def decode_message(data: bytes) -> tuple[str, int, Incomplete]: ... + @staticmethod + async def read_message_async(reader: asyncio.StreamReader) -> _DirtyMessage: ... + @staticmethod + async def write_message_async(writer: asyncio.StreamWriter, message: _DirtyMessage) -> None: ... + @staticmethod + def _recv_exactly(sock: socket.socket, n: int) -> bytes: ... + @staticmethod + def read_message(sock: socket.socket) -> _DirtyMessage: ... + @staticmethod + def write_message(sock: socket.socket, message: _DirtyMessage) -> None: ... + @staticmethod + def _encode_from_dict(message: _DirtyMessage) -> bytes: ... + +DirtyProtocol = BinaryProtocol + +def make_request( + request_id: int | str, + app_path: str, + action: str, + args: tuple[Incomplete, ...] | None = None, + kwargs: dict[str, Incomplete] | None = None, +) -> _DirtyRequest: ... +def make_response(request_id: int | str, result) -> _DirtyResponse: ... +def make_error_response(request_id: int | str, error) -> _DirtyErrorResponse: ... +def make_chunk_message(request_id: int | str, data) -> _DirtyChunkMessage: ... +def make_end_message(request_id: int | str) -> _DirtyEndMessage: ... +def make_stash_message(request_id: int | str, op: int, table: str, key=None, value=None, pattern=None) -> _DirtyStashMessage: ... +def make_manage_message(request_id: int | str, op: int, count: int = 1) -> _DirtyManageMessage: ... diff --git a/stubs/gunicorn/gunicorn/dirty/stash.pyi b/stubs/gunicorn/gunicorn/dirty/stash.pyi new file mode 100644 index 000000000000..113180170b71 --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/stash.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from types import TracebackType +from typing_extensions import Self + +from .errors import DirtyError + +class StashError(DirtyError): ... + +class StashTableNotFoundError(StashError): + table_name: str + + def __init__(self, table_name: str) -> None: ... + +class StashKeyNotFoundError(StashError): + table_name: str + key: str + + def __init__(self, table_name: str, key: str) -> None: ... + +class StashClient: + socket_path: str + timeout: float + + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: ... + def put(self, table: str, key: str, value) -> None: ... + def get(self, table: str, key: str, default=None): ... + def delete(self, table: str, key: str) -> bool: ... + def keys(self, table: str, pattern: str | None = None) -> list[str]: ... + def clear(self, table: str) -> None: ... + def info(self, table: str) -> dict[str, Incomplete]: ... + def ensure(self, table: str) -> None: ... + def exists(self, table: str, key=None) -> bool: ... + def delete_table(self, table: str) -> None: ... + def tables(self) -> list[str]: ... + def table(self, name: str) -> StashTable: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class StashTable: + def __init__(self, client: StashClient, name: str) -> None: ... + @property + def name(self) -> str: ... + def __getitem__(self, key: str): ... + def __setitem__(self, key: str, value) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def get(self, key: str, default=None): ... + def keys(self, pattern: str | None = None) -> list[str]: ... + def clear(self) -> None: ... + def items(self) -> Iterator[tuple[Incomplete, Incomplete]]: ... + def values(self) -> Iterator[Incomplete]: ... + +def set_stash_socket_path(path: str) -> None: ... +def get_stash_socket_path() -> str: ... +def put(table: str, key: str, value) -> None: ... +def get(table: str, key: str, default=None): ... +def delete(table: str, key: str) -> bool: ... +def keys(table: str, pattern: str | None = None) -> list[str]: ... +def clear(table: str) -> None: ... +def info(table: str) -> dict[str, Incomplete]: ... +def ensure(table: str) -> None: ... +def exists(table: str, key: str | None = None) -> bool: ... +def delete_table(table: str) -> None: ... +def tables() -> list[str]: ... +def table(name: str) -> StashTable: ... diff --git a/stubs/gunicorn/gunicorn/dirty/tlv.pyi b/stubs/gunicorn/gunicorn/dirty/tlv.pyi new file mode 100644 index 000000000000..abc9f1432a34 --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/tlv.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from typing import Final + +TYPE_NONE: Final = 0x00 +TYPE_BOOL: Final = 0x01 +TYPE_INT64: Final = 0x05 +TYPE_FLOAT64: Final = 0x06 +TYPE_BYTES: Final = 0x10 +TYPE_STRING: Final = 0x11 +TYPE_LIST: Final = 0x20 +TYPE_DICT: Final = 0x21 +MAX_STRING_SIZE: Final = 67108864 +MAX_BYTES_SIZE: Final = 67108864 +MAX_LIST_SIZE: Final = 1048576 +MAX_DICT_SIZE: Final = 1048576 + +class TLVEncoder: + @staticmethod + def encode( + value: bool | float | str | bytes | list[Incomplete] | tuple[Incomplete, ...] | dict[object, Incomplete] | None, + ) -> bytes: ... # dict key passed to `str()` function + @staticmethod + def decode(data: bytes, offset: int = 0) -> tuple[Incomplete, int]: ... + @staticmethod + def decode_full(data: bytes): ... diff --git a/stubs/gunicorn/gunicorn/dirty/worker.pyi b/stubs/gunicorn/gunicorn/dirty/worker.pyi new file mode 100644 index 000000000000..2d6d93817d4c --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/worker.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from asyncio import StreamReader, StreamWriter +from collections.abc import Iterable, Mapping +from signal import Signals +from typing import Any, ClassVar, Literal + +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.workers.workertmp import WorkerTmp + +class DirtyWorker: + SIGNALS: ClassVar[list[Signals]] + age: int + pid: int | Literal["[booting]"] + ppid: int + app_paths: list[str] + cfg: Config + log: GLogger + socket_path: str + booted: bool + aborted: bool + alive: bool + tmp: WorkerTmp + apps: dict[str, Incomplete] + + def __init__(self, age: int, ppid: int, app_paths: list[str], cfg: Config, log: GLogger, socket_path: str) -> None: ... + def notify(self) -> None: ... + def init_process(self) -> None: ... + def init_signals(self) -> None: ... + def load_apps(self) -> None: ... + def run(self) -> None: ... + async def handle_connection(self, reader: StreamReader, writer: StreamWriter) -> None: ... + async def handle_request(self, message: dict[str, Incomplete], writer: StreamWriter) -> None: ... + async def execute( + self, app_path: str, action: str, args: Iterable[Any], kwargs: Mapping[str, Any] + ) -> Any: ... # Arguments and result depend on method name passed to action diff --git a/stubs/gunicorn/gunicorn/errors.pyi b/stubs/gunicorn/gunicorn/errors.pyi new file mode 100644 index 000000000000..f25818c3ff07 --- /dev/null +++ b/stubs/gunicorn/gunicorn/errors.pyi @@ -0,0 +1,8 @@ +class HaltServer(BaseException): + reason: str + exit_status: int + + def __init__(self, reason: str, exit_status: int = 1) -> None: ... + +class ConfigError(Exception): ... +class AppImportError(Exception): ... diff --git a/stubs/gunicorn/gunicorn/glogging.pyi b/stubs/gunicorn/gunicorn/glogging.pyi new file mode 100644 index 000000000000..964c528bd95b --- /dev/null +++ b/stubs/gunicorn/gunicorn/glogging.pyi @@ -0,0 +1,159 @@ +import logging +import threading +from collections.abc import Mapping +from datetime import timedelta +from logging.config import _DictConfigArgs +from socket import SocketKind +from typing import Annotated, Any, ClassVar, Literal, TypeAlias, TypedDict, type_check_only + +from gunicorn.http import Request +from gunicorn.http.wsgi import Response + +from ._types import _EnvironType +from .config import Config + +SYSLOG_FACILITIES: dict[str, int] + +@type_check_only +class _AtomsDict(TypedDict, total=False): + h: str + l: str + u: str + t: str + r: str + s: str + m: str | None + U: str | None + q: str | None + H: str | None + b: str + B: int | None + f: str + a: str + T: int + D: int + M: int + L: str + p: str + +_CriticalIntType: TypeAlias = Annotated[int, "50"] +_ErrorIntType: TypeAlias = Annotated[int, "40"] +_WarningIntType: TypeAlias = Annotated[int, "30"] +_InfoIntType: TypeAlias = Annotated[int, "20"] +_DebugIntType: TypeAlias = Annotated[int, "10"] +_LogLevelIntType: TypeAlias = _CriticalIntType | _ErrorIntType | _WarningIntType | _InfoIntType | _DebugIntType +_LogLevelStrType: TypeAlias = Literal["critical", "error", "warning", "info", "debug"] +_LogLevelType: TypeAlias = _LogLevelIntType | _LogLevelStrType + +CONFIG_DEFAULTS: _DictConfigArgs + +def loggers() -> list[logging.Logger]: ... + +class SafeAtoms(dict[str, Any]): + def __init__(self, atoms: dict[str, Any]) -> None: ... + def __getitem__(self, k: str) -> str: ... + +_SyslogAddressType: TypeAlias = ( + tuple[Literal[SocketKind.SOCK_DGRAM] | None, str] # Unix Socket + | tuple[Literal[SocketKind.SOCK_DGRAM, SocketKind.SOCK_STREAM], tuple[str, int]] # TCP/UDP Socket +) + +def parse_syslog_address(addr: str) -> _SyslogAddressType: ... + +@type_check_only +class _LogLevels(TypedDict): + critical: _CriticalIntType + error: _ErrorIntType + warning: _WarningIntType + info: _InfoIntType + debug: _DebugIntType + +class Logger: + LOG_LEVELS: ClassVar[_LogLevels] + loglevel: ClassVar[_LogLevelIntType] + error_fmt: ClassVar[str] + datefmt: ClassVar[str] + access_fmt: ClassVar[str] + syslog_fmt: ClassVar[str] + atoms_wrapper_class: ClassVar[type[SafeAtoms]] + error_log: logging.Logger + access_log: logging.Logger + error_handlers: list[logging.Handler] + access_handlers: list[logging.Handler] + logfile: Any | None + lock: threading.Lock + cfg: Config + + def __init__(self, cfg: Config) -> None: ... + def setup(self, cfg: Config) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def debug( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + lvl: _LogLevelType, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def atoms(self, resp: Response, req: Request, environ: _EnvironType, request_time: timedelta) -> _AtomsDict: ... + @property + def access_log_enabled(self) -> bool: ... + def access(self, resp: Response, req: Request, environ: _EnvironType, request_time: timedelta) -> None: ... + def now(self) -> str: ... + def reopen_files(self) -> None: ... + def close_on_exec(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http/__init__.pyi b/stubs/gunicorn/gunicorn/http/__init__.pyi new file mode 100644 index 000000000000..8265485b044a --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/__init__.pyi @@ -0,0 +1,25 @@ +import socket +from collections.abc import Iterable +from typing import Literal, overload + +from gunicorn.config import Config +from gunicorn.http.message import Message as Message, Request as Request +from gunicorn.http.parser import RequestParser as RequestParser +from gunicorn.http2.connection import HTTP2ServerConnection +from gunicorn.uwsgi.parser import UWSGIParser + +from .._types import _AddressType + +@overload +def get_parser( + cfg: Config, + source: socket.socket | Iterable[bytes], + source_addr: _AddressType, + http2_connection: Literal[False] | None = False, +) -> UWSGIParser | RequestParser: ... +@overload +def get_parser( + cfg: Config, source: socket.socket | Iterable[bytes], source_addr: _AddressType, http2_connection: Literal[True] = ... +) -> HTTP2ServerConnection: ... + +__all__ = ["Message", "Request", "RequestParser", "get_parser"] diff --git a/stubs/gunicorn/gunicorn/http/body.pyi b/stubs/gunicorn/gunicorn/http/body.pyi new file mode 100644 index 000000000000..a8ac9a698588 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/body.pyi @@ -0,0 +1,48 @@ +import io +from collections.abc import Callable, Generator, Iterator +from typing import TypeAlias + +from gunicorn.http.message import Request +from gunicorn.http.unreader import Unreader + +class ChunkedReader: + req: Request + parser: Generator[bytes] | None + buf: io.BytesIO + + def __init__(self, req: Request, unreader: Unreader) -> None: ... + def read(self, size: int) -> bytes: ... + def parse_trailers(self, unreader: Unreader, data: bytes) -> None: ... + def parse_chunked(self, unreader: Unreader) -> Generator[bytes]: ... + def parse_chunk_size(self, unreader: Unreader, data: bytes | None = None) -> tuple[int, bytes | None]: ... + def get_data(self, unreader: Unreader, buf: io.BytesIO) -> None: ... + +class LengthReader: + unreader: Unreader + length: int + + def __init__(self, unreader: Unreader, length: int) -> None: ... + def read(self, size: int) -> bytes: ... + +class EOFReader: + unreader: Unreader + buf: io.BytesIO + finished: bool + + def __init__(self, unreader: Unreader) -> None: ... + def read(self, size: int) -> bytes: ... + +_ReaderType: TypeAlias = ChunkedReader | LengthReader | EOFReader + +class Body: + reader: _ReaderType + buf: io.BytesIO + + def __init__(self, reader: _ReaderType) -> None: ... + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + next: Callable[[Body], bytes] + def getsize(self, size: int | None) -> int: ... + def read(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, size: int | None = None) -> list[bytes]: ... diff --git a/stubs/gunicorn/gunicorn/http/errors.pyi b/stubs/gunicorn/gunicorn/http/errors.pyi new file mode 100644 index 000000000000..0e775b72a6f4 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/errors.pyi @@ -0,0 +1,108 @@ +from typing_extensions import Buffer + +from gunicorn.http import Message + +class ParseException(Exception): ... + +class NoMoreData(IOError): + buf: Buffer + + def __init__(self, buf: Buffer | None = None) -> None: ... + +class ConfigurationProblem(ParseException): + info: str + code: int + + def __init__(self, info: str) -> None: ... + +class InvalidRequestLine(ParseException): + req: str + code: int + + def __init__(self, req: str) -> None: ... + +class InvalidRequestMethod(ParseException): + method: str + + def __init__(self, method: str) -> None: ... + +class ExpectationFailed(ParseException): + expect: str + + def __init__(self, expect: str) -> None: ... + +class InvalidHTTPVersion(ParseException): + version: str | tuple[int, int] + + def __init__(self, version: str | tuple[int, int]) -> None: ... + +class InvalidHeader(ParseException): + hdr: str + req: Message | None + + def __init__(self, hdr: str, req: Message | None = None) -> None: ... + +class ObsoleteFolding(ParseException): + hdr: str + + def __init__(self, hdr: str) -> None: ... + +class InvalidHeaderName(ParseException): + hdr: str + + def __init__(self, hdr: str) -> None: ... + +class UnsupportedTransferCoding(ParseException): + hdr: str + code: int + + def __init__(self, hdr: str) -> None: ... + +class InvalidChunkSize(IOError): + data: bytes + + def __init__(self, data: bytes) -> None: ... + +class ChunkMissingTerminator(IOError): + term: bytes + + def __init__(self, term: bytes) -> None: ... + +class InvalidChunkExtension(IOError): + reason: str + def __init__(self, reason: str) -> None: ... + +class LimitRequestLine(ParseException): + size: int + max_size: int | None + + def __init__(self, size: int, max_size: int | None = None) -> None: ... + +class LimitRequestHeaders(ParseException): + msg: str + + def __init__(self, msg: str) -> None: ... + +class InvalidProxyLine(ParseException): + line: str + code: int + + def __init__(self, line: str) -> None: ... + +class InvalidProxyHeader(ParseException): + msg: str + code: int + + def __init__(self, msg: str) -> None: ... + +class ForbiddenProxyRequest(ParseException): + host: str + code: int + + def __init__(self, host: str) -> None: ... + +class InvalidSchemeHeaders(ParseException): ... + +class InvalidH2CPreface(ParseException): + data: bytes + def __init__(self, data: bytes) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http/message.pyi b/stubs/gunicorn/gunicorn/http/message.pyi new file mode 100644 index 000000000000..c7b7da7d5e12 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/message.pyi @@ -0,0 +1,85 @@ +import io +import re +from enum import IntEnum +from typing import Final, Literal + +from gunicorn.config import Config +from gunicorn.http.body import Body +from gunicorn.http.unreader import Unreader + +from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +PP_V2_SIGNATURE: Final = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" + +class PPCommand(IntEnum): + LOCAL = 0x0 + PROXY = 0x1 + +class PPFamily(IntEnum): + UNSPEC = 0x0 + INET = 0x1 + INET6 = 0x2 + UNIX = 0x3 + +class PPProtocol(IntEnum): + UNSPEC = 0x0 + STREAM = 0x1 + DGRAM = 0x2 + +MAX_REQUEST_LINE: Final = 8190 +MAX_HEADERS: Final = 32768 +DEFAULT_MAX_HEADERFIELD_SIZE: Final = 8190 +RFC9110_5_6_2_TOKEN_SPECIALS: Final = r"!#$%&'*+-.^_`|~" +TOKEN_RE: Final[re.Pattern[str]] +METHOD_BADCHAR_RE: Final[re.Pattern[str]] +VERSION_RE: Final[re.Pattern[str]] +RFC9110_5_5_INVALID_AND_DANGEROUS: Final[re.Pattern[str]] +RFC9110_6_5_1_FORBIDDEN_TRAILER: Final[frozenset[str]] +RFC9110_5_3_SINGLETON_FIELDS: Final[frozenset[str]] + +class HeaderPolicy: + scheme: str | None + version: tuple[int, int] | None + +class Message(HeaderPolicy): + cfg: Config + unreader: Unreader + peer_addr: _AddressType + remote_addr: _AddressType + version: tuple[int, int] | None + headers: list[tuple[str, str]] + trailers: list[tuple[str, str]] + body: Body | None + scheme: Literal["https", "http"] + must_close: bool + limit_request_fields: int + limit_request_field_size: int + max_buffer_headers: int + + def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType) -> None: ... + def force_close(self) -> None: ... + def parse(self, unreader: Unreader) -> bytes: ... + def parse_headers(self, data: bytes, from_trailer: bool = False) -> list[tuple[str, str]]: ... + def set_body_reader(self) -> None: ... + def should_close(self) -> bool: ... + +class Request(Message): + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + limit_request_line: int + req_number: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + + def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... + def get_data(self, unreader: Unreader, buf: io.BytesIO, stop: bool = False) -> None: ... + def parse(self, unreader: Unreader) -> bytes: ... + def read_into(self, unreader: Unreader, buf: bytearray, stop: bool | None = False) -> None: ... + def read_line(self, unreader: Unreader, buf: bytearray, limit: int = 0) -> tuple[bytes, bytearray]: ... + def read_bytes(self, unreader: Unreader, buf: bytearray, count: int) -> tuple[bytes, bytearray]: ... + def proxy_protocol_access_check(self) -> None: ... + def parse_request_line(self, line_bytes: bytes) -> None: ... + def set_body_reader(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http/parser.pyi b/stubs/gunicorn/gunicorn/http/parser.pyi new file mode 100644 index 000000000000..5da5625d7d67 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/parser.pyi @@ -0,0 +1,28 @@ +import socket +from collections.abc import Callable, Iterable, Iterator +from typing import ClassVar + +from gunicorn.config import Config +from gunicorn.http.message import Request +from gunicorn.http.unreader import Unreader + +from .._types import _AddressType + +class Parser: + # TODO: Use Protocol instead of Request class + mesg_class: ClassVar[type[Request] | None] + cfg: Config + unreader: Unreader + mesg: Request | None + source_addr: _AddressType + req_count: int + + def __init__(self, cfg: Config, source: socket.socket | Iterable[bytes], source_addr: _AddressType) -> None: ... + def __iter__(self) -> Iterator[Request]: ... + def finish_body(self, deadline: float | None = None, max_bytes: int | None = None) -> None: ... + def __next__(self) -> Request: ... + + next: Callable[[Parser], Request] + +class RequestParser(Parser): + mesg_class: ClassVar[type[Request]] diff --git a/stubs/gunicorn/gunicorn/http/unreader.pyi b/stubs/gunicorn/gunicorn/http/unreader.pyi new file mode 100644 index 000000000000..bfc9992b9506 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/unreader.pyi @@ -0,0 +1,26 @@ +import io +import socket +from _typeshed import ReadableBuffer +from collections.abc import Iterable, Iterator + +class Unreader: + buf: io.BytesIO + + def __init__(self) -> None: ... + def chunk(self) -> bytes: ... + def take_buffered(self) -> bytes: ... + def read(self, size: int | None = None) -> bytes: ... + def unread(self, data: ReadableBuffer) -> None: ... + +class SocketUnreader(Unreader): + sock: socket.socket + mxchunk: int + + def __init__(self, sock: socket.socket, max_chunk: int = 8192) -> None: ... + def chunk(self) -> bytes: ... + +class IterUnreader(Unreader): + iter: Iterator[bytes] | None + + def __init__(self, iterable: Iterable[bytes]) -> None: ... + def chunk(self) -> bytes: ... diff --git a/stubs/gunicorn/gunicorn/http/wsgi.pyi b/stubs/gunicorn/gunicorn/http/wsgi.pyi new file mode 100644 index 000000000000..cbf843149c9d --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/wsgi.pyi @@ -0,0 +1,98 @@ +import io +import logging +import re +import socket +from _typeshed import Incomplete, ReadableBuffer, Unused +from collections.abc import Callable +from typing import Any, Final, Protocol, overload, type_check_only +from typing_extensions import Self + +from gunicorn.config import Config +from gunicorn.http import Request + +from .._types import _AddressType, _EnvironType, _HeadersType, _StatusType + +BLKSIZE: Final = 0x3FFFFFFF +HEADER_VALUE_RE: Final[re.Pattern[str]] +log: logging.Logger + +@type_check_only +class _FileLikeProtocol(Protocol): + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> object: ... + + # optional fields: + # def close(self) -> None: ... + # def fileno(self) -> int: ... + +class FileWrapper: + filelike: io.IOBase + blksize: int + close: Callable[[], None] | None + + def __init__(self, filelike: _FileLikeProtocol, blksize: int = 8192) -> None: ... + def __getitem__(self, key: Unused) -> bytes: ... + def __iter__(self) -> Self: ... + def __next__(self) -> bytes: ... + +class WSGIErrorsWrapper(io.RawIOBase): + streams: list[io.TextIOBase] + + def __init__(self, cfg: Config) -> None: ... + def write(self, data: ReadableBuffer) -> None: ... + +def base_environ(cfg: Config) -> _EnvironType: ... +def default_environ(req: Request, sock: socket.socket, cfg: Config) -> _EnvironType: ... +def proxy_environ(req: Request) -> _EnvironType: ... + +@overload +def create( + req: Request, + sock: socket.socket, + client: _AddressType, + server: _AddressType, + cfg: Config, + response_class: type[Response] | None = None, + response_args: tuple[Incomplete, ...] = (), +) -> tuple[Response, _EnvironType]: ... +@overload +def create( + req: Request, + sock: socket.socket, + client: _AddressType, + server: _AddressType, + cfg: Config, + response_class: type[Incomplete], + response_args: tuple[Incomplete, ...] = (), +) -> tuple[Incomplete, _EnvironType]: ... + +class Response: + req: Request + sock: socket.socket + version: str + status: str | None + chunked: bool + must_close: bool + headers: _HeadersType + headers_sent: bool + response_length: int | None + sent: int + upgrade: bool + cfg: Config + status_code: int | None + + def __init__(self, req: Request, sock: socket.socket, cfg: Config) -> None: ... + def force_close(self) -> None: ... + def should_close(self) -> bool: ... + def start_response( + self, status: _StatusType, headers: _HeadersType, exc_info: tuple[type, BaseException, Any] | None = None + ) -> Callable[[bytes], None]: ... + def process_headers(self, headers: _HeadersType) -> None: ... + def is_chunked(self) -> bool: ... + def default_headers(self) -> list[str]: ... + def send_headers(self) -> None: ... + def write(self, arg: bytes) -> None: ... + def can_sendfile(self) -> bool: ... + def sendfile(self, respiter: FileWrapper) -> bool: ... + def write_file(self, respiter: FileWrapper) -> None: ... + def close(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http2/__init__.pyi b/stubs/gunicorn/gunicorn/http2/__init__.pyi new file mode 100644 index 000000000000..3ad38b85146f --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/__init__.pyi @@ -0,0 +1,19 @@ +from typing import Final + +from .async_connection import AsyncHTTP2Connection +from .connection import HTTP2ServerConnection + +H2_MIN_VERSION: Final[tuple[int, int, int]] + +def is_http2_available() -> bool: ... +def get_h2_version() -> tuple[int, int, int]: ... +def get_http2_connection_class() -> type[HTTP2ServerConnection]: ... +def get_async_http2_connection_class() -> type[AsyncHTTP2Connection]: ... + +__all__ = [ + "is_http2_available", + "get_h2_version", + "get_http2_connection_class", + "get_async_http2_connection_class", + "H2_MIN_VERSION", +] diff --git a/stubs/gunicorn/gunicorn/http2/async_connection.pyi b/stubs/gunicorn/gunicorn/http2/async_connection.pyi new file mode 100644 index 000000000000..1cc1d687ea03 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/async_connection.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete +from asyncio import StreamReader, StreamWriter +from collections.abc import Iterable +from typing import ClassVar + +from gunicorn.config import Config +from gunicorn.http.message import Request +from gunicorn.http2.connection import _H2Connection +from gunicorn.http2.request import HTTP2Request +from gunicorn.http2.stream import HTTP2Stream + +from .._types import _AddressType + +class AsyncHTTP2Connection: + READ_BUFFER_SIZE: ClassVar[int] + cfg: Config + reader: StreamReader + writer: StreamWriter + client_addr: _AddressType + streams: dict[int, HTTP2Stream] + initial_window_size: int + max_concurrent_streams: int + max_frame_size: int + max_header_list_size: int + h2_conn: _H2Connection + + def __init__(self, cfg: Config, reader: StreamReader, writer: StreamWriter, client_addr: _AddressType) -> None: ... + async def initiate_connection(self) -> None: ... + async def initiate_upgrade( + self, settings_header: bytes | None, http1_req: Request, body: bytes | None = b"" + ) -> HTTP2Request: ... + async def receive_data(self, timeout: float | None = None) -> list[HTTP2Request]: ... + async def send_informational(self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]]) -> None: ... + async def send_response( + self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]], body: bytes | None = None + ) -> bool: ... + async def send_data(self, stream_id: int, data: bytes, end_stream: bool = False) -> bool: ... + async def send_trailers(self, stream_id: int, trailers: Iterable[tuple[str, Incomplete]]) -> bool: ... + async def send_error(self, stream_id: int, status_code: int, message: str | None = None) -> None: ... + async def reset_stream(self, stream_id: int, error_code: int = 0x8) -> None: ... + async def close(self, error_code: int = 0x0, last_stream_id: int | None = None) -> None: ... + @property + def is_closed(self) -> bool: ... + def cleanup_stream(self, stream_id: int) -> None: ... + +__all__ = ["AsyncHTTP2Connection"] diff --git a/stubs/gunicorn/gunicorn/http2/connection.pyi b/stubs/gunicorn/gunicorn/http2/connection.pyi new file mode 100644 index 000000000000..d4425d160b6d --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/connection.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from ssl import SSLSocket +from typing import Any, ClassVar, TypeAlias + +from gunicorn.config import Config +from gunicorn.http.message import Request +from gunicorn.http2.request import HTTP2Request +from gunicorn.http2.stream import HTTP2Stream + +from .._types import _AddressType + +_H2Connection: TypeAlias = Any # h2.connection.H2Connection class + +class HTTP2ServerConnection: + READ_BUFFER_SIZE: ClassVar[int] + cfg: Config + sock: SSLSocket + client_addr: _AddressType + streams: dict[int, HTTP2Stream] + initial_window_size: int + max_concurrent_streams: int + max_frame_size: int + max_header_list_size: int + h2_conn: _H2Connection + + def __init__(self, cfg: Config, sock: SSLSocket, client_addr: _AddressType) -> None: ... + def initiate_connection(self) -> None: ... + def initiate_upgrade(self, settings_header: bytes | None, http1_req: Request, body: bytes | None = None) -> HTTP2Request: ... + def receive_data(self, data: bytes | None = None) -> list[HTTP2Request]: ... + def send_informational(self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]]) -> None: ... + def send_response_headers( + self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]], end_stream: bool = False + ) -> bool: ... + def end_stream(self, stream_id: int, trailers: Iterable[tuple[str, Incomplete]] | None = None) -> bool: ... + def send_response( + self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]], body: bytes | None = None + ) -> bool: ... + def send_data(self, stream_id: int, data: bytes, end_stream: bool = False) -> bool: ... + def send_trailers(self, stream_id: int, trailers: Iterable[tuple[str, Incomplete]]) -> bool: ... + def send_error(self, stream_id: int, status_code: int, message: str | None = None) -> None: ... + def reset_stream(self, stream_id: int, error_code: int = 0x8) -> None: ... + def close(self, error_code: int = 0x0, last_stream_id: int | None = None) -> None: ... + @property + def is_closed(self) -> bool: ... + def cleanup_stream(self, stream_id: int) -> None: ... + +__all__ = ["HTTP2ServerConnection"] diff --git a/stubs/gunicorn/gunicorn/http2/errors.pyi b/stubs/gunicorn/gunicorn/http2/errors.pyi new file mode 100644 index 000000000000..7e033d23f7a1 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/errors.pyi @@ -0,0 +1,70 @@ +from typing import Final + +class HTTP2ErrorCode: + NO_ERROR: Final = 0x0 + PROTOCOL_ERROR: Final = 0x1 + INTERNAL_ERROR: Final = 0x2 + FLOW_CONTROL_ERROR: Final = 0x3 + SETTINGS_TIMEOUT: Final = 0x4 + STREAM_CLOSED: Final = 0x5 + FRAME_SIZE_ERROR: Final = 0x6 + REFUSED_STREAM: Final = 0x7 + CANCEL: Final = 0x8 + COMPRESSION_ERROR: Final = 0x9 + CONNECT_ERROR: Final = 0xA + ENHANCE_YOUR_CALM: Final = 0xB + INADEQUATE_SECURITY: Final = 0xC + HTTP_1_1_REQUIRED: Final = 0xD + +class HTTP2Error(Exception): + message: str + error_code: int + + def __init__(self, message: str | None = None, error_code: int | None = None) -> None: ... + +class HTTP2ProtocolError(HTTP2Error): ... +class HTTP2InternalError(HTTP2Error): ... +class HTTP2FlowControlError(HTTP2Error): ... +class HTTP2SettingsTimeout(HTTP2Error): ... +class HTTP2StreamClosed(HTTP2Error): ... +class HTTP2FrameSizeError(HTTP2Error): ... +class HTTP2RefusedStream(HTTP2Error): ... +class HTTP2Cancel(HTTP2Error): ... +class HTTP2CompressionError(HTTP2Error): ... +class HTTP2ConnectError(HTTP2Error): ... +class HTTP2EnhanceYourCalm(HTTP2Error): ... +class HTTP2InadequateSecurity(HTTP2Error): ... +class HTTP2RequiresHTTP11(HTTP2Error): ... + +class HTTP2StreamError(HTTP2Error): + stream_id: int + + def __init__(self, stream_id: int, message: str | None = None, error_code: int | None = None) -> None: ... + +class HTTP2ConnectionError(HTTP2Error): ... +class HTTP2ConfigurationError(HTTP2Error): ... + +class HTTP2NotAvailable(HTTP2Error): + def __init__(self, message: str | None = None) -> None: ... + +__all__ = [ + "HTTP2ErrorCode", + "HTTP2Error", + "HTTP2ProtocolError", + "HTTP2InternalError", + "HTTP2FlowControlError", + "HTTP2SettingsTimeout", + "HTTP2StreamClosed", + "HTTP2FrameSizeError", + "HTTP2RefusedStream", + "HTTP2Cancel", + "HTTP2CompressionError", + "HTTP2ConnectError", + "HTTP2EnhanceYourCalm", + "HTTP2InadequateSecurity", + "HTTP2RequiresHTTP11", + "HTTP2StreamError", + "HTTP2ConnectionError", + "HTTP2ConfigurationError", + "HTTP2NotAvailable", +] diff --git a/stubs/gunicorn/gunicorn/http2/negotiation.pyi b/stubs/gunicorn/gunicorn/http2/negotiation.pyi new file mode 100644 index 000000000000..f6e8bef46fdc --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/negotiation.pyi @@ -0,0 +1,27 @@ +import socket +from typing import Final, Literal, Protocol, type_check_only + +from gunicorn.config import Config + +from .._types import _AddressType + +@type_check_only +class _HasHeaders(Protocol): + headers: list[tuple[str, str]] + +H2C_PREFACE: Final = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" +H2C_PREFACE_TIMEOUT: Final = 1.0 +MATCH: Final = "match" +PARTIAL: Final = "partial" +MISMATCH: Final = "mismatch" + +def preface_match(buf: bytes) -> Literal["match", "mismatch", "partial"]: ... +def peer_trusted_for_h2c(cfg: Config, peer_addr: _AddressType) -> bool: ... +def prior_knowledge_allowed(cfg: Config, peer_addr: _AddressType) -> bool: ... +def mismatch_is_error(cfg: Config) -> bool: ... +def upgrade_allowed(cfg: Config, peer_addr: _AddressType) -> bool: ... +def read_preface_blocking(sock: socket.socket, timeout: float | None = None) -> tuple[bool, bytes]: ... + +UPGRADE_101: Final[bytes] + +def upgrade_settings(req: _HasHeaders) -> bytes | None: ... diff --git a/stubs/gunicorn/gunicorn/http2/request.pyi b/stubs/gunicorn/gunicorn/http2/request.pyi new file mode 100644 index 000000000000..ae156235adce --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/request.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterator +from typing import Literal + +from gunicorn.config import Config +from gunicorn.http.message import HeaderPolicy +from gunicorn.http2.stream import HTTP2Stream + +from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +class HTTP2Body: + def __init__(self, data: ReadableBuffer) -> None: ... + def read(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, hint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... + def __len__(self) -> int: ... + def close(self) -> None: ... + +class HTTP2Request(HeaderPolicy): + stream: HTTP2Stream + cfg: Config + peer_addr: _AddressType + remote_addr: _AddressType + version: tuple[int, int] + method: str + scheme: Literal["https", "http"] + uri: str + path: str + query: str + fragment: str + headers: list[tuple[str, str]] + trailers: list[tuple[str, Incomplete]] + body: HTTP2Body + must_close: bool + req_number: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + priority_weight: int + priority_depends_on: int + + def __init__(self, stream: HTTP2Stream, cfg: Config, peer_addr: _AddressType) -> None: ... + def force_close(self) -> None: ... + def should_close(self) -> bool: ... + def get_header(self, name: str) -> str | None: ... + @property + def content_length(self) -> int | None: ... + @property + def content_type(self) -> str | None: ... + +__all__ = ["HTTP2Request", "HTTP2Body"] diff --git a/stubs/gunicorn/gunicorn/http2/response.pyi b/stubs/gunicorn/gunicorn/http2/response.pyi new file mode 100644 index 000000000000..660fdf8b336c --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/response.pyi @@ -0,0 +1,17 @@ +import socket + +from gunicorn.config import Config +from gunicorn.http import Request +from gunicorn.http.wsgi import Response +from gunicorn.http2.connection import HTTP2ServerConnection + +class HTTP2Response(Response): + h2_conn: HTTP2ServerConnection + stream_id: int + def __init__( + self, req: Request, sock: socket.socket, cfg: Config, h2_conn: HTTP2ServerConnection, stream_id: int + ) -> None: ... + def is_chunked(self) -> bool: ... + def can_sendfile(self) -> bool: ... + def send_headers(self) -> None: ... + def close(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http2/stream.pyi b/stubs/gunicorn/gunicorn/http2/stream.pyi new file mode 100644 index 000000000000..5e7eecb15c19 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/stream.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from enum import Enum +from io import BytesIO + +from gunicorn.http2.connection import HTTP2ServerConnection + +class StreamState(Enum): + IDLE = 1 + RESERVED_LOCAL = 2 + RESERVED_REMOTE = 3 + OPEN = 4 + HALF_CLOSED_LOCAL = 5 + HALF_CLOSED_REMOTE = 6 + CLOSED = 7 + +class HTTP2Stream: + stream_id: int + connection: HTTP2ServerConnection + state: StreamState + request_headers: list[tuple[str, Incomplete]] + request_body: BytesIO + request_complete: bool + response_started: bool + response_headers_sent: bool + response_complete: bool + window_size: int + trailers: list[tuple[str, Incomplete]] | None + response_trailers: list[tuple[str, Incomplete]] | None + priority_weight: int + priority_depends_on: int + priority_exclusive: bool + + def __init__(self, stream_id: int, connection: HTTP2ServerConnection) -> None: ... + @property + def is_client_stream(self) -> bool: ... + @property + def is_server_stream(self) -> bool: ... + @property + def can_receive(self) -> bool: ... + @property + def can_send(self) -> bool: ... + def receive_headers(self, headers: Iterable[tuple[str, Incomplete]], end_stream: bool | None = False) -> None: ... + def receive_data(self, data: ReadableBuffer, end_stream: bool | None = False) -> None: ... + def receive_trailers(self, trailers: list[tuple[str, Incomplete]]) -> None: ... + def send_headers(self, headers: Iterable[tuple[str, Incomplete]], end_stream: bool | None = False) -> None: ... + def send_data(self, data: ReadableBuffer, end_stream: bool | None = False) -> None: ... + def send_trailers(self, trailers: list[tuple[str, Incomplete]]) -> None: ... + def reset(self, error_code: int = 0x8) -> None: ... + def close(self) -> None: ... + def update_priority( + self, weight: int | None = None, depends_on: int | None = None, exclusive: bool | None = None + ) -> None: ... + def get_request_body(self) -> bytes: ... + async def read_body_chunk(self) -> bytes | None: ... + def get_pseudo_headers(self) -> dict[str, Incomplete]: ... + def get_regular_headers(self) -> list[tuple[str, Incomplete]]: ... + +__all__ = ["HTTP2Stream", "StreamState"] diff --git a/stdlib/@python2/distutils/command/install_data.pyi b/stubs/gunicorn/gunicorn/instrument/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/install_data.pyi rename to stubs/gunicorn/gunicorn/instrument/__init__.pyi diff --git a/stubs/gunicorn/gunicorn/instrument/statsd.pyi b/stubs/gunicorn/gunicorn/instrument/statsd.pyi new file mode 100644 index 000000000000..d08e86de095d --- /dev/null +++ b/stubs/gunicorn/gunicorn/instrument/statsd.pyi @@ -0,0 +1,99 @@ +import logging +import socket +from collections.abc import Mapping +from datetime import timedelta +from typing import Final + +from gunicorn.config import Config +from gunicorn.glogging import Logger +from gunicorn.http import Request +from gunicorn.http.wsgi import Response + +from .._types import _EnvironType +from ..glogging import _LogLevelType + +METRIC_VAR: Final = "metric" +VALUE_VAR: Final = "value" +MTYPE_VAR: Final = "mtype" +GAUGE_TYPE: Final = "gauge" +COUNTER_TYPE: Final = "counter" +HISTOGRAM_TYPE: Final = "histogram" +TIMER_TYPE: Final = "timer" + +class Statsd(Logger): + prefix: str + sock: socket.socket | None + dogstatsd_tags: str | None + cfg: Config + + def __init__(self, cfg: Config) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def debug( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + lvl: _LogLevelType, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def access(self, resp: Response, req: Request, environ: _EnvironType, request_time: timedelta) -> None: ... + def gauge(self, name: str, value: float) -> None: ... + def increment(self, name: str, value: int, sampling_rate: float = 1.0) -> None: ... + def decrement(self, name: str, value: int, sampling_rate: float = 1.0) -> None: ... + def timer(self, name: str, value: float) -> None: ... + def histogram(self, name: str, value: float) -> None: ... diff --git a/stubs/gunicorn/gunicorn/pidfile.pyi b/stubs/gunicorn/gunicorn/pidfile.pyi new file mode 100644 index 000000000000..9ff0d9dd91d0 --- /dev/null +++ b/stubs/gunicorn/gunicorn/pidfile.pyi @@ -0,0 +1,11 @@ +from _typeshed import StrOrBytesPath + +class Pidfile: + fname: StrOrBytesPath + pid: int | None + + def __init__(self, fname: StrOrBytesPath) -> None: ... + def create(self, pid: int) -> None: ... + def rename(self, path: StrOrBytesPath) -> None: ... + def unlink(self) -> None: ... + def validate(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/reloader.pyi b/stubs/gunicorn/gunicorn/reloader.pyi new file mode 100644 index 000000000000..62371ed476e0 --- /dev/null +++ b/stubs/gunicorn/gunicorn/reloader.pyi @@ -0,0 +1,49 @@ +import sys +import threading +from collections.abc import Callable, Iterable +from re import Pattern +from typing import Final, TypeAlias, TypedDict, type_check_only +from typing_extensions import Never + +COMPILED_EXT_RE: Final[Pattern[str]] + +class ReloaderBase(threading.Thread): + daemon: bool + + def __init__( + self, extra_files: Iterable[str] | None = None, interval: int = 1, callback: Callable[[str], None] | None = None + ) -> None: ... + def add_extra_file(self, filename: str) -> None: ... + def get_files(self) -> list[str]: ... + +class Reloader(ReloaderBase): + def run(self) -> None: ... + +has_inotify: bool + +if sys.platform == "linux": + class InotifyReloader(ReloaderBase): + event_mask: int + daemon: bool + + def __init__(self, extra_files: Iterable[str] | None = None, callback: Callable[[str], None] | None = None) -> None: ... + def add_extra_file(self, filename: str) -> None: ... + def get_dirs(self) -> set[str]: ... + def refresh_dirs(self) -> None: ... + def run(self) -> None: ... + +else: + class InotifyReloader: + def __init__(self, extra_files: Iterable[str] | None = None, callback: Callable[[str], None] | None = None) -> Never: ... + +_PreferredReloaderType: TypeAlias = type[InotifyReloader | Reloader] +_ReloaderType: TypeAlias = InotifyReloader | Reloader # noqa: Y047 + +@type_check_only +class _ReloadedEngines(TypedDict): + auto: _PreferredReloaderType + pool: type[Reloader] + inotify: type[InotifyReloader] + +preferred_reloader: _PreferredReloaderType +reloader_engines: _ReloadedEngines diff --git a/stubs/gunicorn/gunicorn/sock.pyi b/stubs/gunicorn/gunicorn/sock.pyi new file mode 100644 index 000000000000..0fd5963d0777 --- /dev/null +++ b/stubs/gunicorn/gunicorn/sock.pyi @@ -0,0 +1,46 @@ +import socket +import sys +from collections.abc import Iterable +from ssl import SSLContext, SSLSocket +from typing import Any, ClassVar, Final, Literal, SupportsIndex + +from gunicorn.glogging import Logger as GLogger + +from .config import Config + +PLATFORM: Final[str] + +class BaseSocket: + sock: socket.socket + + def __init__(self, address: str, conf: Config, log: GLogger, fd: SupportsIndex | None = None) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def set_options(self, sock: socket.socket, bound: bool = False) -> socket.socket: ... + def bind(self, sock: socket.socket) -> None: ... + def close(self) -> None: ... + def get_backlog(self) -> int: ... + +class TCPSocket(BaseSocket): + FAMILY: ClassVar[Literal[socket.AddressFamily.AF_INET, socket.AddressFamily.AF_INET6]] + + def set_options(self, sock: socket.socket, bound: bool = False) -> socket.socket: ... + def get_backlog(self) -> int: ... + +class TCP6Socket(TCPSocket): + FAMILY: ClassVar[Literal[socket.AddressFamily.AF_INET6]] + +class UnixSocket(BaseSocket): + if sys.platform != "win32": + FAMILY: ClassVar[Literal[socket.AddressFamily.AF_UNIX]] + else: + FAMILY: ClassVar[Literal[0]] # Stub for windows + + def __init__(self, addr: str, conf: Config, log: GLogger, fd: SupportsIndex | None = None) -> None: ... + def bind(self, sock: socket.socket) -> None: ... + +def create_sockets(conf: Config, log: GLogger, fds: Iterable[SupportsIndex] | None = None) -> list[BaseSocket]: ... +def close_sockets(listeners: Iterable[socket.socket], unlink: bool = True) -> None: ... +def ssl_context(conf: Config) -> SSLContext: ... +def ssl_wrap_socket(sock: socket.socket, conf: Config) -> SSLSocket: ... +def get_negotiated_protocol(ssl_socket: SSLSocket) -> str | None: ... +def is_http2_negotiated(ssl_socket: SSLSocket) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/systemd.pyi b/stubs/gunicorn/gunicorn/systemd.pyi new file mode 100644 index 000000000000..a7facceeec92 --- /dev/null +++ b/stubs/gunicorn/gunicorn/systemd.pyi @@ -0,0 +1,8 @@ +from typing import Final + +from gunicorn.glogging import Logger as GLogger + +SD_LISTEN_FDS_START: Final[int] + +def listen_fds(unset_environment: bool = True) -> int: ... +def sd_notify(state: str, logger: GLogger, unset_environment: bool = False) -> None: ... diff --git a/stubs/gunicorn/gunicorn/util.pyi b/stubs/gunicorn/gunicorn/util.pyi new file mode 100644 index 000000000000..f635cef2e69b --- /dev/null +++ b/stubs/gunicorn/gunicorn/util.pyi @@ -0,0 +1,53 @@ +import types +from _typeshed import FileDescriptorLike, FileDescriptorOrPath, StrOrBytesPath +from inspect import _IntrospectableCallable, _ParameterKind +from re import Pattern +from socket import socket +from typing import Any, Final, Literal +from typing_extensions import Never +from urllib.parse import SplitResult + +from ._types import _AddressType, _WSGIAppType + +REDIRECT_TO: Final[str] +GLOB_MAGIC_RE: Final[Pattern[str]] +hop_headers: set[str] + +def is_glob_pattern(value: str) -> bool: ... +def load_entry_point(distribution: str, group: str, name: str) -> type[object]: ... +def load_class( + uri: str | object, default: str = "gunicorn.workers.sync.SyncWorker", section: str = "gunicorn.workers" +) -> type[Any]: ... + +positionals: tuple[Literal[_ParameterKind.POSITIONAL_ONLY], Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] + +def get_arity(f: _IntrospectableCallable) -> int: ... +def get_username(uid: int) -> str: ... +def set_owner_process(uid: int, gid: int, initgroups: bool = False) -> None: ... +def chown(path: FileDescriptorOrPath, uid: int, gid: int) -> None: ... +def unlink(filename: StrOrBytesPath) -> None: ... +def is_ipv6(addr: str) -> bool: ... +def parse_address(netloc: str, default_port: str = "8000") -> _AddressType: ... +def close_on_exec(fd: FileDescriptorLike) -> None: ... +def set_non_blocking(fd: FileDescriptorLike) -> None: ... +def close(sock: socket) -> None: ... +def close_graceful(sock: socket, timeout: float = 2.0, max_drain: int = 65536) -> None: ... +def write_chunk(sock: socket, data: bytes) -> None: ... +def write(sock: socket, data: bytes, chunked: bool = False) -> None: ... +def write_nonblock(sock: socket, data: bytes, chunked: bool = False) -> None: ... +def write_error(sock: socket, status_int: int, reason: str, mesg: str) -> None: ... +def import_app(module: str) -> _WSGIAppType: ... +def getcwd() -> str: ... +def http_date(timestamp: float | None = None) -> str: ... +def is_hoppish(header: str) -> bool: ... +def daemonize(enable_stdio_inheritance: bool = False) -> None: ... +def seed() -> None: ... +def check_is_writable(path: FileDescriptorOrPath) -> None: ... +def to_bytestring(value: str | bytes, encoding: str = "utf8") -> bytes: ... +def has_fileno(obj: object) -> bool: ... +def warn(msg: str) -> None: ... +def make_fail_app(msg: str) -> _WSGIAppType: ... +def split_request_uri(uri: str) -> SplitResult: ... +def reraise(tp: type[BaseException], value: BaseException | None, tb: types.TracebackType | None = None) -> Never: ... +def bytes_to_str(b: bytes) -> str: ... +def unquote_to_wsgi_str(string: str) -> str: ... diff --git a/stubs/gunicorn/gunicorn/uwsgi/__init__.pyi b/stubs/gunicorn/gunicorn/uwsgi/__init__.pyi new file mode 100644 index 000000000000..47193b1757e6 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/__init__.pyi @@ -0,0 +1,17 @@ +from gunicorn.uwsgi.errors import ( + ForbiddenUWSGIRequest as ForbiddenUWSGIRequest, + InvalidUWSGIHeader as InvalidUWSGIHeader, + UnsupportedModifier as UnsupportedModifier, + UWSGIParseException as UWSGIParseException, +) +from gunicorn.uwsgi.message import UWSGIRequest as UWSGIRequest +from gunicorn.uwsgi.parser import UWSGIParser as UWSGIParser + +__all__ = [ + "UWSGIRequest", + "UWSGIParser", + "UWSGIParseException", + "InvalidUWSGIHeader", + "UnsupportedModifier", + "ForbiddenUWSGIRequest", +] diff --git a/stubs/gunicorn/gunicorn/uwsgi/errors.pyi b/stubs/gunicorn/gunicorn/uwsgi/errors.pyi new file mode 100644 index 000000000000..265536815654 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/errors.pyi @@ -0,0 +1,19 @@ +class UWSGIParseException(Exception): ... + +class InvalidUWSGIHeader(UWSGIParseException): + msg: str + code: int + + def __init__(self, msg: str = "") -> None: ... + +class UnsupportedModifier(UWSGIParseException): + modifier: int + code: int + + def __init__(self, modifier: int) -> None: ... + +class ForbiddenUWSGIRequest(UWSGIParseException): + host: str + code: int + + def __init__(self, host: str) -> None: ... diff --git a/stubs/gunicorn/gunicorn/uwsgi/message.pyi b/stubs/gunicorn/gunicorn/uwsgi/message.pyi new file mode 100644 index 000000000000..b89c893ad508 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/message.pyi @@ -0,0 +1,38 @@ +from typing import Final, Literal + +from gunicorn.config import Config +from gunicorn.http.body import Body +from gunicorn.http.unreader import Unreader + +from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +MAX_UWSGI_VARS: Final = 1000 + +class UWSGIRequest: + cfg: Config + unreader: Unreader + peer_addr: _AddressType + remote_addr: _AddressType + req_number: int + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + version: tuple[int, int] + headers: list[tuple[str, str]] + trailers: list[tuple[str, str]] + body: Body | None + scheme: Literal["https", "http"] + must_close: bool + uwsgi_vars: dict[str, str] + modifier1: int + modifier2: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + + def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... + def force_close(self) -> None: ... + def parse(self, unreader: Unreader) -> bytes: ... + def set_body_reader(self) -> None: ... + def should_close(self) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/uwsgi/parser.pyi b/stubs/gunicorn/gunicorn/uwsgi/parser.pyi new file mode 100644 index 000000000000..488b318b2299 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/parser.pyi @@ -0,0 +1,7 @@ +from typing import ClassVar + +from gunicorn.http.parser import Parser +from gunicorn.uwsgi.message import UWSGIRequest + +class UWSGIParser(Parser): + mesg_class: ClassVar[type[UWSGIRequest]] # type: ignore[assignment] diff --git a/stubs/gunicorn/gunicorn/workers/__init__.pyi b/stubs/gunicorn/gunicorn/workers/__init__.pyi new file mode 100644 index 000000000000..d687a67ab557 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/__init__.pyi @@ -0,0 +1,13 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _SupportedWorkers(TypedDict): + sync: str + gevent: str + gevent_wsgi: str + gevent_pywsgi: str + tornado: str + gthread: str + asgi: str + +SUPPORTED_WORKERS: _SupportedWorkers diff --git a/stubs/gunicorn/gunicorn/workers/base.pyi b/stubs/gunicorn/gunicorn/workers/base.pyi new file mode 100644 index 000000000000..aa0d5fc3a76a --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/base.pyi @@ -0,0 +1,48 @@ +import socket +from types import FrameType +from typing import ClassVar + +from gunicorn.app.base import BaseApplication +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.http import Request +from gunicorn.workers.workertmp import WorkerTmp + +from .._types import _AddressType, _WSGIAppType +from ..reloader import _ReloaderType + +class Worker: + SIGNALS: ClassVar[list[int]] + PIPE: ClassVar[list[int]] + age: int + pid: str + ppid: int + sockets: list[socket.socket] + app: BaseApplication + timeout: int + cfg: Config + booted: bool + aborted: bool + reloader: _ReloaderType | None + nr: int + max_requests: int + alive: bool + log: GLogger + tmp: WorkerTmp + wait_fds: list[socket.socket | int] + wsgi: _WSGIAppType + + def __init__( + self, age: int, ppid: int, sockets: list[socket.socket], app: BaseApplication, timeout: int, cfg: Config, log: GLogger + ) -> None: ... + def notify(self) -> None: ... + def run(self) -> None: ... + def init_process(self) -> None: ... + def load_wsgi(self) -> None: ... + def init_signals(self) -> None: ... + def handle_usr1(self, sig: int, frame: FrameType | None) -> None: ... + def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_quit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_abort(self, sig: int, frame: FrameType | None) -> None: ... + def handle_error(self, req: Request | None, client: socket.socket, addr: _AddressType, exc: BaseException) -> None: ... + def handle_winch(self, sig: int, fname: str | None) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/base_async.pyi b/stubs/gunicorn/gunicorn/workers/base_async.pyi new file mode 100644 index 000000000000..9fc7ea06c383 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/base_async.pyi @@ -0,0 +1,29 @@ +import socket + +from gunicorn.http import Request +from gunicorn.http2.connection import HTTP2ServerConnection +from gunicorn.workers import base + +from .._types import _AddressType + +ALREADY_HANDLED: object + +class AsyncWorker(base.Worker): + worker_connections: int + alive: bool + + def timeout_ctx(self) -> None: ... + def is_already_handled(self, respiter: object) -> bool: ... + def handle(self, listener: socket.socket, client: socket.socket, addr: _AddressType) -> None: ... + def handle_http2( + self, + listener: socket.socket, + client: socket.socket, + addr: _AddressType, + preface: bytes | None = b"", + upgrade: tuple[bytes | None, Request, bytes | None] | None = None, + ) -> None: ... + def handle_http2_request( + self, listener_name: _AddressType, req: Request, sock: socket.socket, addr: _AddressType, h2_conn: HTTP2ServerConnection + ) -> None: ... + def handle_request(self, listener_name: _AddressType, req: Request, sock: socket.socket, addr: _AddressType) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/workers/gasgi.pyi b/stubs/gunicorn/gunicorn/workers/gasgi.pyi new file mode 100644 index 000000000000..564d6d375a9d --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/gasgi.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from asyncio.base_events import Server +from asyncio.events import AbstractEventLoop +from typing_extensions import Never + +from gunicorn.asgi.lifespan import LifespanManager +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.workers import base + +from .._types import _ASGIAppType + +class ASGIWorker(base.Worker): + worker_connections: int + loop: AbstractEventLoop | None + servers: list[Server] + nr_conns: int + lifespan: LifespanManager | None + state: dict[Incomplete, Incomplete] + asgi: _ASGIAppType + + @classmethod + def check_config(cls, cfg: Config, log: GLogger) -> None: ... + def init_process(self) -> None: ... + def load_wsgi(self) -> None: ... + def init_signals(self) -> None: ... + def handle_quit_signal(self) -> None: ... + def handle_exit_signal(self) -> None: ... + def handle_usr1_signal(self) -> None: ... + def handle_winch_signal(self) -> None: ... + def handle_abort_signal(self) -> Never: ... + def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/ggevent.pyi b/stubs/gunicorn/gunicorn/workers/ggevent.pyi new file mode 100644 index 000000000000..6e2aa6da142d --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/ggevent.pyi @@ -0,0 +1,45 @@ +from types import FrameType +from typing import Any, ClassVar, Final + +from gevent import pywsgi +from gevent.pywsgi import WSGIHandler +from gevent.server import StreamServer +from gevent.socket import socket as GeventSocket +from gunicorn.http import Request +from gunicorn.workers.base_async import AsyncWorker + +from .._types import _AddressType + +VERSION: Final[str] + +class GeventWorker(AsyncWorker): + server_class: ClassVar[type[StreamServer] | None] + wsgi_handler: ClassVar[type[WSGIHandler] | None] + sockets: list[GeventSocket] + + def patch(self) -> None: ... + def notify(self) -> None: ... + def timeout_ctx(self) -> None: ... + def run(self) -> None: ... + def handle(self, listener: GeventSocket, client: GeventSocket, addr: _AddressType) -> None: ... + def handle_request(self, listener_name: _AddressType, req: Request, sock: GeventSocket, addr: _AddressType) -> bool: ... + def handle_quit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_usr1(self, sig: int, frame: FrameType | None) -> None: ... + def init_process(self) -> None: ... + +class GeventResponse: + status: ClassVar[str | None] + headers: ClassVar[dict[str, str] | None] + sent: ClassVar[int | None] + + def __init__(self, status: str, headers: dict[str, str], clength: int | None) -> None: ... + +class PyWSGIHandler(pywsgi.WSGIHandler): + def log_request(self) -> None: ... + def get_environ(self) -> dict[str, Any]: ... + +class PyWSGIServer(pywsgi.WSGIServer): ... + +class GeventPyWSGIWorker(GeventWorker): + server_class: ClassVar[type[PyWSGIServer] | None] + wsgi_handler: ClassVar[type[PyWSGIHandler] | None] diff --git a/stubs/gunicorn/gunicorn/workers/gthread.pyi b/stubs/gunicorn/gunicorn/workers/gthread.pyi new file mode 100644 index 000000000000..65e5058f9e2e --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/gthread.pyi @@ -0,0 +1,81 @@ +import socket +from _typeshed import Unused +from collections import deque +from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor +from selectors import DefaultSelector +from types import FrameType +from typing import Final + +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.http import Request, RequestParser +from gunicorn.http2.connection import HTTP2ServerConnection +from gunicorn.uwsgi.parser import UWSGIParser + +from .._types import _AddressType +from . import base + +DEFAULT_WORKER_DATA_TIMEOUT: Final = 5.0 + +class TConn: + cfg: Config + sock: socket.socket + client: _AddressType + server: _AddressType + timeout: float | None + parser: HTTP2ServerConnection | UWSGIParser | RequestParser | None + initialized: bool + is_http2: bool + data_ready: bool + + def __init__(self, cfg: Config, sock: socket.socket, client: _AddressType, server: _AddressType) -> None: ... + def init(self) -> None: ... + def set_timeout(self) -> None: ... + def wait_for_data(self, timeout: float | None) -> bool: ... + def close(self, graceful: bool = False) -> None: ... + +class PollableMethodQueue: + def __init__(self) -> None: ... + def init(self) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int | None: ... + # Actually, `*args` are expected to match the parameter types of `callback`. + # Ideally this would be typed using ParamSpec as: + # def defer(self, callback: Callable[_P, object], *args: _P.args) -> None + def defer(self, callback: Callable[..., object], *args: object) -> None: ... + def run_callbacks(self, _fileobj: Unused, max_callbacks: int = 50) -> None: ... + +class ThreadWorker(base.Worker): + worker_connections: int + max_keepalived: int + tpool: ThreadPoolExecutor + poller: DefaultSelector + method_queue: PollableMethodQueue + keepalived_conns: deque[TConn] + pending_conns: deque[TConn] + nr_conns: int + alive: bool + + @classmethod + def check_config(cls, cfg: Config, log: GLogger) -> None: ... + def init_process(self) -> None: ... + def get_thread_pool(self) -> ThreadPoolExecutor: ... + def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_quit(self, sig: int, frame: FrameType | None) -> None: ... + def set_accept_enabled(self, enabled: bool | None) -> None: ... + def enqueue_req(self, conn: TConn) -> None: ... + def accept(self, listener: socket.socket) -> None: ... + def on_client_socket_readable(self, conn: TConn, client: socket.socket) -> None: ... + def on_pending_socket_readable(self, conn: TConn, client: socket.socket) -> None: ... + def murder_keepalived(self) -> None: ... + def murder_pending(self) -> None: ... + def is_parent_alive(self) -> bool: ... + def wait_for_and_dispatch_events(self, timeout: float | None) -> None: ... + def run(self) -> None: ... + def finish_request(self, conn: TConn, fs: Future[bool]) -> None: ... + def handle(self, conn: TConn) -> bool: ... + def handle_h2c_upgrade(self, conn: TConn, req: Request, settings: bytes | None) -> bool: ... + def handle_http2(self, conn: TConn) -> bool: ... + def handle_http2_request(self, req: Request, conn: TConn, h2_conn: HTTP2ServerConnection) -> None: ... + def handle_request(self, req: Request, conn: TConn) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/workers/gtornado.pyi b/stubs/gunicorn/gunicorn/workers/gtornado.pyi new file mode 100644 index 000000000000..25267d4d46bb --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/gtornado.pyi @@ -0,0 +1,24 @@ +from types import FrameType +from typing import Any, TypeAlias + +from gunicorn.workers.base import Worker + +IOLoop: TypeAlias = Any # tornado IOLoop class +PeriodicCallback: TypeAlias = Any # tornado PeriodicCallback class +_HTTPServer: TypeAlias = Any # tornado httpserver.HTTPServer class + +class TornadoWorker(Worker): + alive: bool + server_alive: bool + ioloop: IOLoop + callbacks: list[PeriodicCallback] + server: _HTTPServer + + @classmethod + def setup(cls) -> None: ... + def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_request(self) -> None: ... + def watchdog(self) -> None: ... + def heartbeat(self) -> None: ... + def init_process(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/sync.pyi b/stubs/gunicorn/gunicorn/workers/sync.pyi new file mode 100644 index 000000000000..cf461d5e785c --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/sync.pyi @@ -0,0 +1,19 @@ +import socket + +from gunicorn.http import Request +from gunicorn.workers.base import Worker + +from .._types import _AddressType + +class StopWaiting(Exception): ... + +class SyncWorker(Worker): + def accept(self, listener: socket.socket) -> None: ... + def wait(self, timeout: int) -> list[socket.socket | int] | None: ... + def is_parent_alive(self) -> bool: ... + def run_for_one(self, timeout: int) -> None: ... + def run_for_multiple(self, timeout: int) -> None: ... + def run(self) -> None: ... + def handle(self, listener: socket.socket, client: socket.socket, addr: _AddressType) -> None: ... + def handle_request(self, listener: socket.socket, req: Request, client: socket.socket, addr: tuple[str, int]) -> bool: ... + def handle_error(self, req: Request | None, client: socket.socket, addr: _AddressType, exc: BaseException) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/workertmp.pyi b/stubs/gunicorn/gunicorn/workers/workertmp.pyi new file mode 100644 index 000000000000..4bfc3c6182f9 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/workertmp.pyi @@ -0,0 +1,13 @@ +from typing import Final + +from gunicorn.config import Config + +PLATFORM: Final[str] +IS_CYGWIN: Final[bool] + +class WorkerTmp: + def __init__(self, cfg: Config) -> None: ... + def notify(self) -> None: ... + def last_update(self) -> float: ... + def fileno(self) -> int: ... + def close(self) -> None: ... diff --git a/stubs/hdbcli/@tests/stubtest_allowlist.txt b/stubs/hdbcli/@tests/stubtest_allowlist.txt index 283ddd3b2062..0a8477f582f6 100644 --- a/stubs/hdbcli/@tests/stubtest_allowlist.txt +++ b/stubs/hdbcli/@tests/stubtest_allowlist.txt @@ -1,8 +1,23 @@ +# Are set to `None` by default, initialized later: hdbcli.dbapi.Error.errorcode hdbcli.dbapi.Error.errortext hdbcli.dbapi.Warning.errorcode hdbcli.dbapi.Warning.errortext -# Similar issues to builtins.memoryview -hdbcli.dbapi.BINARY.__iter__ -hdbcli.dbapi.BINARY.cast -hdbcli.dbapi.BINARY.__contains__ +hdbcli.dbapi.ExecuteManyErrorEntry.rownumber + +hdbcli.dbapi.buffer +hdbcli.dbapi.long +hdbcli.dbapi.unicode + +# async_connect is an alias for AsyncConnection, but at runtime its a function +hdbcli.dbapi.async_connect + +# *args/**kwargs are not added by purpose but are part of the python wrapper +hdbcli.dbapi.AsyncLob.close +hdbcli.dbapi.AsyncCursor.nextset +hdbcli.dbapi.AsyncCursor.fetchall +hdbcli.dbapi.AsyncCursor.close +hdbcli.dbapi.AsyncConnection.rollback +hdbcli.dbapi.AsyncConnection.commit +hdbcli.dbapi.AsyncConnection.close +hdbcli.dbapi.AsyncConnection.cancel diff --git a/stubs/hdbcli/METADATA.toml b/stubs/hdbcli/METADATA.toml index 4e51482b6fc4..6a7db568934b 100644 --- a/stubs/hdbcli/METADATA.toml +++ b/stubs/hdbcli/METADATA.toml @@ -1 +1,2 @@ -version = "2.10.*" +# upstream-repository = closed-source +version = "2.30.*" diff --git a/stubs/hdbcli/hdbcli/__init__.pyi b/stubs/hdbcli/hdbcli/__init__.pyi index bda5b5a7f4cc..bbf8a8962414 100644 --- a/stubs/hdbcli/hdbcli/__init__.pyi +++ b/stubs/hdbcli/hdbcli/__init__.pyi @@ -1 +1,7 @@ -__version__: str +from typing import Final + +from . import dbapi as dbapi + +__version__: Final[str] + +__all__ = ["dbapi"] diff --git a/stubs/hdbcli/hdbcli/dbapi.pyi b/stubs/hdbcli/hdbcli/dbapi.pyi index 7ab8c8be9f23..4acfa34cdcfd 100644 --- a/stubs/hdbcli/hdbcli/dbapi.pyi +++ b/stubs/hdbcli/hdbcli/dbapi.pyi @@ -1,25 +1,27 @@ import decimal -from _typeshed import ReadableBuffer +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Callable, Sequence from datetime import date, datetime, time -from typing import Any, Sequence, Tuple, Type, overload -from typing_extensions import Literal +from types import TracebackType +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import Self, disjoint_base from .resultrow import ResultRow -apilevel: str -threadsafety: int -paramstyle: Tuple[str, ...] -connect = Connection +apilevel: Final[str] +threadsafety: Final[int] +paramstyle: Final[tuple[str, ...]] # hdbcli defines it as a tuple which does not follow PEP 249 +@disjoint_base class Connection: def __init__( self, - address: str, - port: int, - username: str, - password: str, - autocommit: bool = ..., - packetsize: int | None = ..., + address: str = "", + port: int = 0, + user: str = "", + password: str = "", + autocommit: bool = True, + packetsize: int | None = None, userkey: str | None = ..., *, sessionvariables: dict[str, str] | None = ..., @@ -32,11 +34,17 @@ class Connection: def getaddress(self) -> str: ... def getautocommit(self) -> bool: ... def getclientinfo(self, key: str = ...) -> str | dict[str, str]: ... + def getproperty(self, *args, **kwargs): ... def isconnected(self) -> bool: ... def rollback(self) -> None: ... def setautocommit(self, auto: bool = ...) -> None: ... def setclientinfo(self, key: str, value: str | None = ...) -> None: ... + def ontrace(self, callback: Callable[[str], Any], options: str = ...) -> None: ... + def ping(self) -> bool: ... + +connect = Connection +@disjoint_base class LOB: def __init__(self, *args: Any, **kwargs: Any) -> None: ... def close(self) -> bool: ... @@ -44,42 +52,59 @@ class LOB: def read(self, size: int = ..., position: int = ...) -> str | bytes: ... def write(self, object: str | bytes) -> int: ... -_Parameters = Sequence[Tuple[Any, ...]] +_Parameters: TypeAlias = Sequence[tuple[Any, ...]] | None +_Holdability: TypeAlias = Literal[0, 1, 2, 3] +@disjoint_base class Cursor: - description: Tuple[Tuple[Any, ...], ...] + description: tuple[tuple[Any, ...], ...] rowcount: int statementhash: str | None connection: Connection arraysize: int + refreshts: int | None + maxage: int def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def callproc(self, procname: str, parameters: Tuple[Any, ...] = ..., overview: bool = ...) -> Tuple[Any, ...]: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + def callproc(self, procname: str, parameters: tuple[Any, ...] = ..., overview: bool = ...) -> tuple[Any, ...]: ... def close(self) -> None: ... - def description_ext(self) -> Sequence[Tuple[Any, ...]]: ... - def execute(self, operation: str, parameters: Tuple[Any, ...]) -> bool: ... - def executemany(self, operation: str, parameters: _Parameters) -> Any: ... - def executemanyprepared(self, parameters: _Parameters) -> Any: ... + def description_ext(self) -> Sequence[tuple[Any, ...]]: ... + def execute(self, operation: str, parameters: tuple[Any, ...] | None = ...) -> bool: ... + def executemany(self, operation: str, parameters: _Parameters = ..., batcherrors: bool = False) -> Any: ... + def executemanyprepared(self, parameters: _Parameters = ...) -> Any: ... def executeprepared(self, parameters: _Parameters = ...) -> Any: ... def fetchone(self, uselob: bool = ...) -> ResultRow | None: ... def fetchall(self) -> list[ResultRow]: ... def fetchmany(self, size: int | None = ...) -> list[ResultRow]: ... - def get_resultset_holdability(self) -> int: ... + def getrowsaffectedcounts(self) -> tuple[Any, ...]: ... + def getpacketsize(self) -> int: ... + def get_resultset_holdability(self) -> _Holdability: ... def getwarning(self) -> Warning | None: ... def haswarning(self) -> bool: ... + def clearwarning(self) -> None: ... + def has_result_set(self) -> bool: ... def nextset(self) -> None: ... - def parameter_description(self) -> Tuple[str, ...]: ... + def parameter_description(self) -> tuple[str, ...]: ... + @overload def prepare(self, operation: str, newcursor: Literal[True]) -> Cursor: ... @overload def prepare(self, operation: str, newcursor: Literal[False]) -> Any: ... - def scroll(self, value: int, mode: Literal["absolute"] | Literal["relative"] = ...) -> None: ... + + def print_message(self): ... + def parsenamedquery(self, *args, **kwargs): ... + def scroll(self, value: int, mode: Literal["absolute", "relative"] = ...) -> None: ... def server_cpu_time(self) -> int: ... def server_memory_usage(self) -> int: ... def server_processing_time(self) -> int: ... def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... def setfetchsize(self, value: int) -> None: ... - def set_resultset_holdability(self, holdability: int) -> None: ... + def setquerytimeout(self, value: int) -> None: ... + def setpacketsize(self, value: int) -> None: ... + def set_resultset_holdability(self, holdability: _Holdability) -> None: ... def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... + def setcommandinfo(self, command_info: str, line_number: int) -> None: ... class Warning(Exception): errorcode: int @@ -98,9 +123,15 @@ class InternalError(DatabaseError): ... class DataError(DatabaseError): ... class NotSupportedError(DatabaseError): ... +class ExecuteManyError(Error): + errors: Incomplete + +class ExecuteManyErrorEntry(Error): + rownumber: int + def Date(year: int, month: int, day: int) -> date: ... -def Time(hour: int, minute: int, second: int, millisecond: int = ...) -> time: ... -def Timestamp(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int = ...) -> datetime: ... +def Time(hour: int, minute: int, second: int, millisecond: int = 0) -> time: ... +def Timestamp(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int = 0) -> datetime: ... def DateFromTicks(ticks: float) -> date: ... def TimeFromTicks(ticks: float) -> time: ... def TimestampFromTicks(ticks: float) -> datetime: ... @@ -108,8 +139,55 @@ def Binary(data: ReadableBuffer) -> memoryview: ... Decimal = decimal.Decimal -NUMBER: Type[int] | Type[float] | Type[complex] -DATETIME: Type[date] | Type[time] | Type[datetime] +NUMBER: type[int | float | complex] +DATETIME: type[date | time | datetime] STRING = str BINARY = memoryview ROWID = int + +class AsyncConnection(Connection): + @classmethod + async def create( + cls, + address: str = "", + port: int = 0, + user: str = "", + password: str = "", + autocommit: bool = True, + packetsize: int | None = None, + userkey: str | None = ..., + *, + sessionvariables: dict[str, str] | None = ..., + forcebulkfetch: bool | None = ..., + ) -> Self: ... + async def cancel(self) -> bool: ... # type: ignore[override] + async def close(self) -> None: ... # type: ignore[override] + async def commit(self) -> None: ... # type: ignore[override] + async def cursor(self) -> AsyncCursor: ... # type: ignore[override] + async def rollback(self) -> None: ... # type: ignore[override] + +class AsyncCursor(Cursor): + async def callproc(self, procname: str, parameters: tuple[Any, ...] = ..., overview: bool = ...) -> tuple[Any, ...]: ... # type: ignore[override] + async def close(self) -> None: ... # type: ignore[override] + async def execute(self, operation: str, parameters: tuple[Any, ...] | None = ...) -> bool: ... # type: ignore[override] + async def executemany(self, operation: str, parameters: _Parameters = ..., batcherrors: bool = False) -> Any: ... + async def executemanyprepared(self, parameters: _Parameters = ...) -> Any: ... + async def executeprepared(self, parameters: _Parameters = ...) -> Any: ... + async def fetchone(self, uselob: bool = ...) -> ResultRow | None: ... # type: ignore[override] + async def fetchall(self) -> list[ResultRow]: ... # type: ignore[override] + async def fetchmany(self, size: int | None = ...) -> list[ResultRow]: ... # type: ignore[override] + async def nextset(self) -> None: ... # type: ignore[override] + async def prepare(self, operation: str, newcursor: bool = ...) -> Any: ... # type: ignore[override] + async def scroll(self, value: int, mode: Literal["absolute", "relative"] = ...) -> None: ... # type: ignore[override] + async def __aenter__(self) -> Self: ... + async def __aexit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + +class AsyncLob(LOB): + async def close(self) -> None: ... # type: ignore[override] + async def find(self, object: str, length: int, position: int = ...) -> int: ... # type: ignore[override] + async def read(self, size: int = ..., position: int = ...) -> str | bytes: ... # type: ignore[override] + async def write(self, object: str | bytes) -> int: ... # type: ignore[override] + +async_connect = AsyncConnection + +def set_async_mode(enabled: bool = True) -> None: ... diff --git a/stubs/hdbcli/hdbcli/resultrow.pyi b/stubs/hdbcli/hdbcli/resultrow.pyi index 02a02eca91d4..d3e9454dbfe1 100644 --- a/stubs/hdbcli/hdbcli/resultrow.pyi +++ b/stubs/hdbcli/hdbcli/resultrow.pyi @@ -1,6 +1,19 @@ -from typing import Any, Tuple +from collections.abc import Iterator, Sequence +from typing import Any, overload +from typing_extensions import disjoint_base +@disjoint_base class ResultRow: def __init__(self, *args: Any, **kwargs: Any) -> None: ... - column_names: Tuple[str, ...] - column_values: Tuple[Any, ...] + column_names: tuple[str, ...] + column_values: tuple[Any, ...] + + def __len__(self) -> int: ... + + @overload + def __getitem__(self, index: int, /) -> Any: ... + @overload + def __getitem__(self, index: slice, /) -> Sequence[Any]: ... + + def __iter__(self) -> Iterator[Any]: ... + # __next__, __delitem__, __setitem__ are technically defined but lead always to an error diff --git a/stubs/hnswlib/@tests/stubtest_allowlist.txt b/stubs/hnswlib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c8b95d1e576d --- /dev/null +++ b/stubs/hnswlib/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# The metaclass of Index is pybind11_builtins.pybind11_type. Since pybind11 is not a +# runtime dependency of hnswlib, we exclude Index from stubtest checks. +hnswlib.Index diff --git a/stubs/hnswlib/METADATA.toml b/stubs/hnswlib/METADATA.toml new file mode 100644 index 000000000000..5fc25ee47d79 --- /dev/null +++ b/stubs/hnswlib/METADATA.toml @@ -0,0 +1,11 @@ +version = "0.8.*" +upstream-repository = "https://github.com/nmslib/hnswlib" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.21"] + +[tool.stubtest] +# hnswlib is source-only and compiles with -march=native by default. CI +# restores pip's wheel cache across runners with different CPUs, so a wheel +# built on one machine can SIGILL on the next. See +# https://github.com/python/typeshed/issues/16100 +install-environment = { HNSWLIB_NO_NATIVE = "1" } diff --git a/stubs/hnswlib/hnswlib.pyi b/stubs/hnswlib/hnswlib.pyi new file mode 100644 index 000000000000..4a84d55d99f8 --- /dev/null +++ b/stubs/hnswlib/hnswlib.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +BFIndex: Incomplete + +class Index: + ef: int + num_threads: int + + @overload + def __init__(self, params: dict[str, Any]) -> None: ... + @overload + def __init__(self, index: Index) -> None: ... + @overload + def __init__(self, space: Literal["l2", "ip", "cosine"], dim: int) -> None: ... + + def add_items( + self, data: ArrayLike, ids: ArrayLike | None = None, num_threads: int = -1, replace_deleted: bool = False + ) -> None: ... + def get_current_count(self) -> int: ... + def get_ids_list(self) -> list[int]: ... + + @overload + def get_items(self, ids: ArrayLike | None = ..., return_type: Literal["list"] = ...) -> list[float]: ... + @overload + def get_items(self, ids: ArrayLike | None = ..., return_type: Literal["numpy"] = ...) -> NDArray[np.float32]: ... + @overload + def get_items( + self, ids: ArrayLike | None = None, return_type: Literal["numpy", "list"] = "numpy" + ) -> NDArray[np.float32] | list[float]: ... + + def get_max_elements(self) -> int: ... + def index_file_size(self) -> int: ... + def init_index( + self, + max_elements: int, + M: int = 16, + ef_construction: int = 200, + random_seed: int = 100, + allow_replace_deleted: bool = False, + ) -> None: ... + def knn_query( + self, data: ArrayLike, k: int = 1, num_threads: int = -1, filter: Callable[[int], bool] | None = None + ) -> tuple[NDArray[np.uint64], NDArray[np.float32]]: ... + def load_index(self, path_to_index: str, max_elements: int = 0, allow_replace_deleted: bool = False) -> None: ... + def mark_deleted(self, label: int) -> None: ... + def resize_index(self, new_size: int) -> None: ... + def save_index(self, path_to_index: str) -> None: ... + def set_ef(self, ef: int) -> None: ... + def set_num_threads(self, num_threads: int) -> None: ... + def unmark_deleted(self, label: int) -> None: ... + @property + def M(self) -> int: ... + @property + def dim(self) -> int: ... + @property + def ef_construction(self) -> int: ... + @property + def element_count(self) -> int: ... + @property + def max_elements(self) -> int: ... + @property + def space(self) -> str: ... diff --git a/stubs/html5lib/@tests/requirements-stubtest.txt b/stubs/html5lib/@tests/requirements-stubtest.txt deleted file mode 100644 index 0bf46c1ccd09..000000000000 --- a/stubs/html5lib/@tests/requirements-stubtest.txt +++ /dev/null @@ -1,2 +0,0 @@ -genshi -lxml diff --git a/stubs/html5lib/@tests/stubtest_allowlist.txt b/stubs/html5lib/@tests/stubtest_allowlist.txt index 82dbdb726b09..7d9f867632d2 100644 --- a/stubs/html5lib/@tests/stubtest_allowlist.txt +++ b/stubs/html5lib/@tests/stubtest_allowlist.txt @@ -1,3 +1,6 @@ -# Misnamed first argument in implementation -html5lib._inputstream.EncodingBytes.__new__ -html5lib._tokenizer.attributeMap.get +# Side effects from module initialization: +html5lib.serializer.k +html5lib.serializer.v +html5lib.treeadapters.sax.prefix +html5lib.treeadapters.sax.localName +html5lib.treeadapters.sax.namespace diff --git a/stubs/html5lib/METADATA.toml b/stubs/html5lib/METADATA.toml index c9f594bd7bbd..7049e9bd2e85 100644 --- a/stubs/html5lib/METADATA.toml +++ b/stubs/html5lib/METADATA.toml @@ -1 +1,6 @@ version = "1.1.*" +upstream-repository = "https://github.com/html5lib/html5lib-python" +dependencies = ["types-webencodings"] + +[tool.stubtest] +extras = ["all"] diff --git a/stubs/html5lib/html5lib/__init__.pyi b/stubs/html5lib/html5lib/__init__.pyi index 709bc661394a..3a24c70e9f41 100644 --- a/stubs/html5lib/html5lib/__init__.pyi +++ b/stubs/html5lib/html5lib/__init__.pyi @@ -1,6 +1,10 @@ +from typing import Final + from .html5parser import HTMLParser as HTMLParser, parse as parse, parseFragment as parseFragment from .serializer import serialize as serialize from .treebuilders import getTreeBuilder as getTreeBuilder from .treewalkers import getTreeWalker as getTreeWalker -__version__: str +__all__ = ["HTMLParser", "parse", "parseFragment", "getTreeBuilder", "getTreeWalker", "serialize"] + +__version__: Final[str] diff --git a/stubs/html5lib/html5lib/_ihatexml.pyi b/stubs/html5lib/html5lib/_ihatexml.pyi index dff7e852ec09..4f0844635aa3 100644 --- a/stubs/html5lib/html5lib/_ihatexml.pyi +++ b/stubs/html5lib/html5lib/_ihatexml.pyi @@ -1,55 +1,55 @@ -from typing import Any +import re baseChar: str ideographic: str combiningCharacter: str digit: str extender: str -letter: Any -name: Any -nameFirst: Any -reChar: Any -reCharRange: Any +letter: str +name: str +nameFirst: str +reChar: re.Pattern[str] +reCharRange: re.Pattern[str] -def charStringToList(chars): ... -def normaliseCharList(charList): ... +def charStringToList(chars: str) -> list[list[int]]: ... +def normaliseCharList(charList: list[list[int]]) -> list[list[int]]: ... -max_unicode: Any +max_unicode: int -def missingRanges(charList): ... -def listToRegexpStr(charList): ... -def hexToInt(hex_str): ... -def escapeRegexp(string): ... +def missingRanges(charList: list[list[int]]) -> list[list[int]]: ... +def listToRegexpStr(charList: list[list[int]]) -> str: ... +def hexToInt(hex_str: str | bytes | bytearray) -> int: ... +def escapeRegexp(string: str) -> str: ... -nonXmlNameBMPRegexp: Any -nonXmlNameFirstBMPRegexp: Any -nonPubidCharRegexp: Any +nonXmlNameBMPRegexp: re.Pattern[str] +nonXmlNameFirstBMPRegexp: re.Pattern[str] +nonPubidCharRegexp: re.Pattern[str] class InfosetFilter: - replacementRegexp: Any - dropXmlnsLocalName: Any - dropXmlnsAttrNs: Any - preventDoubleDashComments: Any - preventDashAtCommentEnd: Any - replaceFormFeedCharacters: Any - preventSingleQuotePubid: Any - replaceCache: Any + replacementRegexp: re.Pattern[str] + dropXmlnsLocalName: bool + dropXmlnsAttrNs: bool + preventDoubleDashComments: bool + preventDashAtCommentEnd: bool + replaceFormFeedCharacters: bool + preventSingleQuotePubid: bool + replaceCache: dict[str, str] def __init__( self, - dropXmlnsLocalName: bool = ..., - dropXmlnsAttrNs: bool = ..., - preventDoubleDashComments: bool = ..., - preventDashAtCommentEnd: bool = ..., - replaceFormFeedCharacters: bool = ..., - preventSingleQuotePubid: bool = ..., + dropXmlnsLocalName: bool = False, + dropXmlnsAttrNs: bool = False, + preventDoubleDashComments: bool = False, + preventDashAtCommentEnd: bool = False, + replaceFormFeedCharacters: bool = True, + preventSingleQuotePubid: bool = False, ) -> None: ... - def coerceAttribute(self, name, namespace: Any | None = ...): ... - def coerceElement(self, name): ... - def coerceComment(self, data): ... - def coerceCharacters(self, data): ... - def coercePubid(self, data): ... - def toXmlName(self, name): ... - def getReplacementCharacter(self, char): ... - def fromXmlName(self, name): ... - def escapeChar(self, char): ... - def unescapeChar(self, charcode): ... + def coerceAttribute(self, name: str, namespace: str | None = None) -> str | None: ... + def coerceElement(self, name: str) -> str: ... + def coerceComment(self, data: str) -> str: ... + def coerceCharacters(self, data: str) -> str: ... + def coercePubid(self, data: str) -> str: ... + def toXmlName(self, name: str) -> str: ... + def getReplacementCharacter(self, char: str) -> str: ... + def fromXmlName(self, name: str) -> str: ... + def escapeChar(self, char: str) -> str: ... + def unescapeChar(self, charcode: str | bytes | bytearray) -> str: ... diff --git a/stubs/html5lib/html5lib/_inputstream.pyi b/stubs/html5lib/html5lib/_inputstream.pyi index ad08d358740b..1a011ee46eb8 100644 --- a/stubs/html5lib/html5lib/_inputstream.pyi +++ b/stubs/html5lib/html5lib/_inputstream.pyi @@ -1,109 +1,150 @@ -from typing import Any +import re +from _io import BytesIO, StringIO +from _typeshed import Incomplete, ReadableBuffer, SupportsRead +from collections.abc import Callable, Iterable +from typing import Any, AnyStr, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self -spaceCharactersBytes: Any -asciiLettersBytes: Any -asciiUppercaseBytes: Any -spacesAngleBrackets: Any +from webencodings import Encoding + +_UnicodeInputStream: TypeAlias = str | SupportsRead[str] +_BinaryInputStream: TypeAlias = bytes | SupportsRead[bytes] +_InputStream: TypeAlias = _UnicodeInputStream | _BinaryInputStream # noqa: Y047 # used in other files +_SupportsReadT = TypeVar("_SupportsReadT", bound=SupportsRead[Any]) +_SupportsReadBytesT = TypeVar("_SupportsReadBytesT", bound=SupportsRead[bytes]) + +spaceCharactersBytes: frozenset[bytes] +asciiLettersBytes: frozenset[bytes] +asciiUppercaseBytes: frozenset[bytes] +spacesAngleBrackets: frozenset[bytes] invalid_unicode_no_surrogate: str -invalid_unicode_re: Any -non_bmp_invalid_codepoints: Any -ascii_punctuation_re: Any -charsUntilRegEx: Any - -class BufferedStream: - stream: Any - buffer: Any - position: Any - def __init__(self, stream) -> None: ... - def tell(self): ... - def seek(self, pos) -> None: ... - def read(self, bytes): ... - -def HTMLInputStream(source, **kwargs): ... +invalid_unicode_re: re.Pattern[str] +non_bmp_invalid_codepoints: set[int] +ascii_punctuation_re: re.Pattern[str] +charsUntilRegEx: dict[tuple[Iterable[str | bytes | bytearray], bool], re.Pattern[str]] + +class BufferedStream(Generic[AnyStr]): + stream: SupportsRead[AnyStr] + buffer: list[AnyStr] + position: list[int] + def __init__(self, stream: SupportsRead[AnyStr]) -> None: ... + def tell(self) -> int: ... + def seek(self, pos: int) -> None: ... + def read(self, bytes: int) -> AnyStr: ... + +@overload +def HTMLInputStream(source: _UnicodeInputStream) -> HTMLUnicodeInputStream: ... +@overload +def HTMLInputStream( + source: _BinaryInputStream, + *, + override_encoding: str | bytes | None = None, + transport_encoding: str | bytes | None = None, + same_origin_parent_encoding: str | bytes | None = None, + likely_encoding: str | bytes | None = None, + default_encoding: str = "windows-1252", + useChardet: bool = True, +) -> HTMLBinaryInputStream: ... class HTMLUnicodeInputStream: - reportCharacterErrors: Any - newLines: Any - charEncoding: Any - dataStream: Any - def __init__(self, source) -> None: ... + reportCharacterErrors: Callable[[str], None] + newLines: list[int] + charEncoding: tuple[Encoding, str] + dataStream: Incomplete + def __init__(self, source: _UnicodeInputStream) -> None: ... chunk: str chunkSize: int chunkOffset: int - errors: Any + errors: list[str] prevNumLines: int prevNumCols: int def reset(self) -> None: ... - def openStream(self, source): ... - def position(self): ... - def char(self): ... - def readChunk(self, chunkSize: Any | None = ...): ... - def characterErrorsUCS4(self, data) -> None: ... - def characterErrorsUCS2(self, data) -> None: ... - def charsUntil(self, characters, opposite: bool = ...): ... - def unget(self, char) -> None: ... + + @overload + def openStream(self, source: _SupportsReadT) -> _SupportsReadT: ... + @overload + def openStream(self, source: str | None) -> StringIO: ... + + def position(self) -> tuple[int, int]: ... + def char(self) -> str | None: ... + def readChunk(self, chunkSize: int | None = None) -> bool: ... + def characterErrorsUCS4(self, data: str) -> None: ... + def characterErrorsUCS2(self, data: str) -> None: ... + def charsUntil(self, characters: Iterable[str | bytes | bytearray], opposite: bool = False) -> str: ... + def unget(self, char: str | None) -> None: ... class HTMLBinaryInputStream(HTMLUnicodeInputStream): - rawStream: Any + rawStream: Incomplete numBytesMeta: int numBytesChardet: int - override_encoding: Any - transport_encoding: Any - same_origin_parent_encoding: Any - likely_encoding: Any - default_encoding: Any - charEncoding: Any + override_encoding: Incomplete + transport_encoding: Incomplete + same_origin_parent_encoding: Incomplete + likely_encoding: Incomplete + default_encoding: str + charEncoding: tuple[Encoding, str] def __init__( self, - source, - override_encoding: Any | None = ..., - transport_encoding: Any | None = ..., - same_origin_parent_encoding: Any | None = ..., - likely_encoding: Any | None = ..., - default_encoding: str = ..., - useChardet: bool = ..., + source: _BinaryInputStream, + override_encoding: str | bytes | None = None, + transport_encoding: str | bytes | None = None, + same_origin_parent_encoding: str | bytes | None = None, + likely_encoding: str | bytes | None = None, + default_encoding: str = "windows-1252", + useChardet: bool = True, ) -> None: ... - dataStream: Any + dataStream: Incomplete def reset(self) -> None: ... - def openStream(self, source): ... - def determineEncoding(self, chardet: bool = ...): ... - def changeEncoding(self, newEncoding) -> None: ... - def detectBOM(self): ... - def detectEncodingMeta(self): ... + + @overload # type: ignore[override] + def openStream(self, source: _SupportsReadBytesT) -> _SupportsReadBytesT: ... + @overload # type: ignore[override] + def openStream(self, source: ReadableBuffer) -> BytesIO: ... + + def determineEncoding(self, chardet: bool = True): ... + def changeEncoding(self, newEncoding: str | bytes | None) -> None: ... + def detectBOM(self) -> Encoding | None: ... + def detectEncodingMeta(self) -> Encoding | None: ... class EncodingBytes(bytes): - def __new__(cls, value): ... - def __init__(self, value) -> None: ... - def __iter__(self): ... - def __next__(self): ... - def next(self): ... - def previous(self): ... - def setPosition(self, position) -> None: ... - def getPosition(self): ... - position: Any - def getCurrentByte(self): ... - currentByte: Any - def skip(self, chars=...): ... - def skipUntil(self, chars): ... - def matchBytes(self, bytes): ... - def jumpTo(self, bytes): ... + def __new__(self, value: bytes) -> Self: ... + def __init__(self, value: bytes) -> None: ... + def __iter__(self) -> Self: ... # type: ignore[override] + def __next__(self) -> bytes: ... + def next(self) -> bytes: ... + def previous(self) -> bytes: ... + def setPosition(self, position: int) -> None: ... + def getPosition(self) -> int | None: ... + + @property + def position(self) -> int | None: ... + @position.setter + def position(self, position: int) -> None: ... + + def getCurrentByte(self) -> bytes: ... + @property + def currentByte(self) -> bytes: ... + def skip(self, chars: bytes | bytearray | Iterable[bytes] = ...) -> bytes | None: ... + def skipUntil(self, chars: bytes | bytearray | Iterable[bytes]) -> bytes | None: ... + def matchBytes(self, bytes: bytes | bytearray) -> bool: ... + def jumpTo(self, bytes: bytes | bytearray) -> Literal[True]: ... class EncodingParser: - data: Any - encoding: Any - def __init__(self, data) -> None: ... - def getEncoding(self): ... - def handleComment(self): ... - def handleMeta(self): ... - def handlePossibleStartTag(self): ... - def handlePossibleEndTag(self): ... - def handlePossibleTag(self, endTag): ... - def handleOther(self): ... - def getAttribute(self): ... + data: EncodingBytes + encoding: Encoding | None + def __init__(self, data: bytes) -> None: ... + def getEncoding(self) -> Encoding | None: ... + def handleComment(self) -> bool: ... + def handleMeta(self) -> bool: ... + def handlePossibleStartTag(self) -> bool: ... + def handlePossibleEndTag(self) -> bool: ... + def handlePossibleTag(self, endTag: bool | None) -> bool: ... + def handleOther(self) -> bool: ... + def getAttribute(self) -> tuple[bytes, bytes] | None: ... class ContentAttrParser: - data: Any - def __init__(self, data) -> None: ... - def parse(self): ... + data: EncodingBytes + def __init__(self, data: EncodingBytes) -> None: ... + def parse(self) -> bytes | None: ... -def lookupEncoding(encoding): ... +def lookupEncoding(encoding: str | bytes | None) -> Encoding | None: ... diff --git a/stubs/html5lib/html5lib/_tokenizer.pyi b/stubs/html5lib/html5lib/_tokenizer.pyi index cf62e2ca65d9..d2c148b5e21d 100644 --- a/stubs/html5lib/html5lib/_tokenizer.pyi +++ b/stubs/html5lib/html5lib/_tokenizer.pyi @@ -1,93 +1,128 @@ -import sys -from collections import OrderedDict -from typing import Any, Dict +from _typeshed import Incomplete +from collections import deque +from collections.abc import Callable, Iterator +from typing import TypedDict, overload, type_check_only -entitiesTrie: Any -if sys.version_info >= (3, 7): - attributeMap = Dict[Any, Any] -else: - attributeMap = OrderedDict[Any, Any] +from ._inputstream import HTMLBinaryInputStream, HTMLUnicodeInputStream, _BinaryInputStream, _UnicodeInputStream +from ._trie import Trie + +@type_check_only +class _DataVars(TypedDict, total=False): + data: str | None + charAsInt: int + +@type_check_only +class _Token(TypedDict, total=False): + type: int + data: str | list[str] + datavars: _DataVars + name: str + selfClosing: bool + selfClosingAcknowledged: bool + publicId: str | None + systemId: str | None + correct: bool + +entitiesTrie: Trie +attributeMap = dict class HTMLTokenizer: - stream: Any - parser: Any + # TODO: Use Protocol to allow subclasses to set `stream` that do not inherit from HTMLUnicodeInputStream + stream: HTMLUnicodeInputStream | HTMLBinaryInputStream + parser: Incomplete escapeFlag: bool - lastFourChars: Any - state: Any + lastFourChars: list[Incomplete] + state: Callable[[], bool] escape: bool - currentToken: Any - def __init__(self, stream, parser: Any | None = ..., **kwargs) -> None: ... - tokenQueue: Any - def __iter__(self): ... - def consumeNumberEntity(self, isHex): ... - def consumeEntity(self, allowedChar: Any | None = ..., fromAttribute: bool = ...) -> None: ... - def processEntityInAttribute(self, allowedChar) -> None: ... + currentToken: _Token | None + + @overload + def __init__(self, stream: _UnicodeInputStream, parser=None) -> None: ... + @overload + def __init__( + self, + stream: _BinaryInputStream, + parser=None, + *, + override_encoding: str | bytes | None = None, + transport_encoding: str | bytes | None = None, + same_origin_parent_encoding: str | bytes | None = None, + likely_encoding: str | bytes | None = None, + default_encoding: str = "windows-1252", + useChardet: bool = True, + ) -> None: ... + + tokenQueue: deque[_Token] + def __iter__(self) -> Iterator[_Token]: ... + def consumeNumberEntity(self, isHex: bool | None) -> str: ... + def consumeEntity(self, allowedChar: str | None = None, fromAttribute: bool = False) -> None: ... + def processEntityInAttribute(self, allowedChar: str | None) -> None: ... def emitCurrentToken(self) -> None: ... - def dataState(self): ... - def entityDataState(self): ... - def rcdataState(self): ... - def characterReferenceInRcdata(self): ... - def rawtextState(self): ... - def scriptDataState(self): ... - def plaintextState(self): ... - def tagOpenState(self): ... - def closeTagOpenState(self): ... - def tagNameState(self): ... + def dataState(self) -> bool: ... + def entityDataState(self) -> bool: ... + def rcdataState(self) -> bool: ... + def characterReferenceInRcdata(self) -> bool: ... + def rawtextState(self) -> bool: ... + def scriptDataState(self) -> bool: ... + def plaintextState(self) -> bool: ... + def tagOpenState(self) -> bool: ... + def closeTagOpenState(self) -> bool: ... + def tagNameState(self) -> bool: ... temporaryBuffer: str - def rcdataLessThanSignState(self): ... - def rcdataEndTagOpenState(self): ... - def rcdataEndTagNameState(self): ... - def rawtextLessThanSignState(self): ... - def rawtextEndTagOpenState(self): ... - def rawtextEndTagNameState(self): ... - def scriptDataLessThanSignState(self): ... - def scriptDataEndTagOpenState(self): ... - def scriptDataEndTagNameState(self): ... - def scriptDataEscapeStartState(self): ... - def scriptDataEscapeStartDashState(self): ... - def scriptDataEscapedState(self): ... - def scriptDataEscapedDashState(self): ... - def scriptDataEscapedDashDashState(self): ... - def scriptDataEscapedLessThanSignState(self): ... - def scriptDataEscapedEndTagOpenState(self): ... - def scriptDataEscapedEndTagNameState(self): ... - def scriptDataDoubleEscapeStartState(self): ... - def scriptDataDoubleEscapedState(self): ... - def scriptDataDoubleEscapedDashState(self): ... - def scriptDataDoubleEscapedDashDashState(self): ... - def scriptDataDoubleEscapedLessThanSignState(self): ... - def scriptDataDoubleEscapeEndState(self): ... - def beforeAttributeNameState(self): ... - def attributeNameState(self): ... - def afterAttributeNameState(self): ... - def beforeAttributeValueState(self): ... - def attributeValueDoubleQuotedState(self): ... - def attributeValueSingleQuotedState(self): ... - def attributeValueUnQuotedState(self): ... - def afterAttributeValueState(self): ... - def selfClosingStartTagState(self): ... - def bogusCommentState(self): ... - def markupDeclarationOpenState(self): ... - def commentStartState(self): ... - def commentStartDashState(self): ... - def commentState(self): ... - def commentEndDashState(self): ... - def commentEndState(self): ... - def commentEndBangState(self): ... - def doctypeState(self): ... - def beforeDoctypeNameState(self): ... - def doctypeNameState(self): ... - def afterDoctypeNameState(self): ... - def afterDoctypePublicKeywordState(self): ... - def beforeDoctypePublicIdentifierState(self): ... - def doctypePublicIdentifierDoubleQuotedState(self): ... - def doctypePublicIdentifierSingleQuotedState(self): ... - def afterDoctypePublicIdentifierState(self): ... - def betweenDoctypePublicAndSystemIdentifiersState(self): ... - def afterDoctypeSystemKeywordState(self): ... - def beforeDoctypeSystemIdentifierState(self): ... - def doctypeSystemIdentifierDoubleQuotedState(self): ... - def doctypeSystemIdentifierSingleQuotedState(self): ... - def afterDoctypeSystemIdentifierState(self): ... - def bogusDoctypeState(self): ... - def cdataSectionState(self): ... + def rcdataLessThanSignState(self) -> bool: ... + def rcdataEndTagOpenState(self) -> bool: ... + def rcdataEndTagNameState(self) -> bool: ... + def rawtextLessThanSignState(self) -> bool: ... + def rawtextEndTagOpenState(self) -> bool: ... + def rawtextEndTagNameState(self) -> bool: ... + def scriptDataLessThanSignState(self) -> bool: ... + def scriptDataEndTagOpenState(self) -> bool: ... + def scriptDataEndTagNameState(self) -> bool: ... + def scriptDataEscapeStartState(self) -> bool: ... + def scriptDataEscapeStartDashState(self) -> bool: ... + def scriptDataEscapedState(self) -> bool: ... + def scriptDataEscapedDashState(self) -> bool: ... + def scriptDataEscapedDashDashState(self) -> bool: ... + def scriptDataEscapedLessThanSignState(self) -> bool: ... + def scriptDataEscapedEndTagOpenState(self) -> bool: ... + def scriptDataEscapedEndTagNameState(self) -> bool: ... + def scriptDataDoubleEscapeStartState(self) -> bool: ... + def scriptDataDoubleEscapedState(self) -> bool: ... + def scriptDataDoubleEscapedDashState(self) -> bool: ... + def scriptDataDoubleEscapedDashDashState(self) -> bool: ... + def scriptDataDoubleEscapedLessThanSignState(self) -> bool: ... + def scriptDataDoubleEscapeEndState(self) -> bool: ... + def beforeAttributeNameState(self) -> bool: ... + def attributeNameState(self) -> bool: ... + def afterAttributeNameState(self) -> bool: ... + def beforeAttributeValueState(self) -> bool: ... + def attributeValueDoubleQuotedState(self) -> bool: ... + def attributeValueSingleQuotedState(self) -> bool: ... + def attributeValueUnQuotedState(self) -> bool: ... + def afterAttributeValueState(self) -> bool: ... + def selfClosingStartTagState(self) -> bool: ... + def bogusCommentState(self) -> bool: ... + def markupDeclarationOpenState(self) -> bool: ... + def commentStartState(self) -> bool: ... + def commentStartDashState(self) -> bool: ... + def commentState(self) -> bool: ... + def commentEndDashState(self) -> bool: ... + def commentEndState(self) -> bool: ... + def commentEndBangState(self) -> bool: ... + def doctypeState(self) -> bool: ... + def beforeDoctypeNameState(self) -> bool: ... + def doctypeNameState(self) -> bool: ... + def afterDoctypeNameState(self) -> bool: ... + def afterDoctypePublicKeywordState(self) -> bool: ... + def beforeDoctypePublicIdentifierState(self) -> bool: ... + def doctypePublicIdentifierDoubleQuotedState(self) -> bool: ... + def doctypePublicIdentifierSingleQuotedState(self) -> bool: ... + def afterDoctypePublicIdentifierState(self) -> bool: ... + def betweenDoctypePublicAndSystemIdentifiersState(self) -> bool: ... + def afterDoctypeSystemKeywordState(self) -> bool: ... + def beforeDoctypeSystemIdentifierState(self) -> bool: ... + def doctypeSystemIdentifierDoubleQuotedState(self) -> bool: ... + def doctypeSystemIdentifierSingleQuotedState(self) -> bool: ... + def afterDoctypeSystemIdentifierState(self) -> bool: ... + def bogusDoctypeState(self) -> bool: ... + def cdataSectionState(self) -> bool: ... diff --git a/stubs/html5lib/html5lib/_trie/__init__.pyi b/stubs/html5lib/html5lib/_trie/__init__.pyi index 7095d84cbea4..3b0ea9a093bf 100644 --- a/stubs/html5lib/html5lib/_trie/__init__.pyi +++ b/stubs/html5lib/html5lib/_trie/__init__.pyi @@ -1 +1,3 @@ from .py import Trie as Trie + +__all__ = ["Trie"] diff --git a/stubs/html5lib/html5lib/_trie/_base.pyi b/stubs/html5lib/html5lib/_trie/_base.pyi index 138c91ccd1ba..45725be511b6 100644 --- a/stubs/html5lib/html5lib/_trie/_base.pyi +++ b/stubs/html5lib/html5lib/_trie/_base.pyi @@ -1,9 +1,9 @@ +from _typeshed import Incomplete from abc import ABCMeta from collections.abc import Mapping -from typing import Any -class Trie(Mapping[Any, Any], metaclass=ABCMeta): - def keys(self, prefix: Any | None = ...): ... +class Trie(Mapping[Incomplete, Incomplete], metaclass=ABCMeta): + def keys(self, prefix=None): ... def has_keys_with_prefix(self, prefix): ... def longest_prefix(self, prefix): ... def longest_prefix_item(self, prefix): ... diff --git a/stubs/html5lib/html5lib/_trie/py.pyi b/stubs/html5lib/html5lib/_trie/py.pyi index cd3e66dd49e8..4d3f7c7bb069 100644 --- a/stubs/html5lib/html5lib/_trie/py.pyi +++ b/stubs/html5lib/html5lib/_trie/py.pyi @@ -1,12 +1,10 @@ -from typing import Any - from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data) -> None: ... def __contains__(self, key): ... - def __len__(self): ... + def __len__(self) -> int: ... def __iter__(self): ... def __getitem__(self, key): ... - def keys(self, prefix: Any | None = ...): ... + def keys(self, prefix=None): ... def has_keys_with_prefix(self, prefix): ... diff --git a/stubs/html5lib/html5lib/_utils.pyi b/stubs/html5lib/html5lib/_utils.pyi index c6f85f5a622f..3197ccb548e0 100644 --- a/stubs/html5lib/html5lib/_utils.pyi +++ b/stubs/html5lib/html5lib/_utils.pyi @@ -1,24 +1,43 @@ -from collections.abc import Mapping -from typing import Any, Dict +import xml.etree.ElementTree as default_etree +from _typeshed import Incomplete, Unused +from collections.abc import Iterable, Mapping, Sequence +from typing import Final, TypeVar, overload -supports_lone_surrogates: bool +__all__ = [ + "default_etree", + "MethodDispatcher", + "isSurrogatePair", + "surrogatePairToCodepoint", + "moduleFactoryFactory", + "supports_lone_surrogates", +] -class MethodDispatcher(Dict[Any, Any]): - default: Any - def __init__(self, items=...) -> None: ... - def __getitem__(self, key): ... - def __get__(self, instance, owner: Any | None = ...): ... +supports_lone_surrogates: Final[bool] + +_K = TypeVar("_K") +_V = TypeVar("_V") + +class MethodDispatcher(dict[_K, _V]): + default: _V | None + + @overload # to solve `reportInvalidTypeVarUse` + def __init__(self) -> None: ... + @overload + def __init__(self, items: Iterable[tuple[_K | Iterable[_K], _V]]) -> None: ... + + def __getitem__(self, key: _K) -> _V | None: ... # type: ignore[override] + def __get__(self, instance, owner: Unused = None) -> BoundMethodDispatcher: ... -class BoundMethodDispatcher(Mapping[Any, Any]): - instance: Any - dispatcher: Any +class BoundMethodDispatcher(Mapping[Incomplete, Incomplete]): + instance: Incomplete + dispatcher: Incomplete def __init__(self, instance, dispatcher) -> None: ... def __getitem__(self, key): ... - def get(self, key, default): ... + def get(self, key, default): ... # type: ignore[override] def __iter__(self): ... - def __len__(self): ... - def __contains__(self, key): ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... -def isSurrogatePair(data): ... -def surrogatePairToCodepoint(data): ... +def isSurrogatePair(data: Sequence[str | bytes | bytearray]) -> bool: ... +def surrogatePairToCodepoint(data: Sequence[str | bytes | bytearray]) -> int: ... def moduleFactoryFactory(factory): ... diff --git a/stubs/html5lib/html5lib/constants.pyi b/stubs/html5lib/html5lib/constants.pyi index b8a3ac8f1cdd..a5c4c5289afd 100644 --- a/stubs/html5lib/html5lib/constants.pyi +++ b/stubs/html5lib/html5lib/constants.pyi @@ -1,37 +1,35 @@ -from typing import Any - -EOF: Any -E: Any -namespaces: Any -scopingElements: Any -formattingElements: Any -specialElements: Any -htmlIntegrationPointElements: Any -mathmlTextIntegrationPointElements: Any -adjustSVGAttributes: Any -adjustMathMLAttributes: Any -adjustForeignAttributes: Any -unadjustForeignAttributes: Any -spaceCharacters: Any -tableInsertModeElements: Any -asciiLowercase: Any -asciiUppercase: Any -asciiLetters: Any -digits: Any -hexDigits: Any -asciiUpper2Lower: Any -headingElements: Any -voidElements: Any -cdataElements: Any -rcdataElements: Any -booleanAttributes: Any -entitiesWindows1252: Any -xmlEntities: Any -entities: Any -replacementCharacters: Any -tokenTypes: Any -tagTokenTypes: Any -prefixes: Any +EOF: None +E: dict[str, str] +namespaces: dict[str, str] +scopingElements: frozenset[tuple[str, str]] +formattingElements: frozenset[tuple[str, str]] +specialElements: frozenset[tuple[str, str]] +htmlIntegrationPointElements: frozenset[tuple[str, str]] +mathmlTextIntegrationPointElements: frozenset[tuple[str, str]] +adjustSVGAttributes: dict[str, str] +adjustMathMLAttributes: dict[str, str] +adjustForeignAttributes: dict[str, tuple[str, str, str] | tuple[None, str, str]] +unadjustForeignAttributes: dict[tuple[str, str], str] +spaceCharacters: frozenset[str] +tableInsertModeElements: frozenset[str] +asciiLowercase: frozenset[str] +asciiUppercase: frozenset[str] +asciiLetters: frozenset[str] +digits: frozenset[str] +hexDigits: frozenset[str] +asciiUpper2Lower: dict[int, int] +headingElements: tuple[str, ...] +voidElements: frozenset[str] +cdataElements: frozenset[str] +rcdataElements: frozenset[str] +booleanAttributes: dict[str, frozenset[str]] +entitiesWindows1252: tuple[int, ...] +xmlEntities: frozenset[str] +entities: dict[str, str] +replacementCharacters: dict[int, str] +tokenTypes: dict[str, int] +tagTokenTypes: frozenset[int] +prefixes: dict[str, str] class DataLossWarning(UserWarning): ... class _ReparseException(Exception): ... diff --git a/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi b/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi index 20b694d65edf..955bae07d8ba 100644 --- a/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi +++ b/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi @@ -1,4 +1,5 @@ +from _typeshed import Incomplete + from . import base -class Filter(base.Filter): - def __iter__(self): ... +class Filter(base.Filter[dict[str, Incomplete]]): ... diff --git a/stubs/html5lib/html5lib/filters/base.pyi b/stubs/html5lib/html5lib/filters/base.pyi index 16d3726e0a85..ddbaf78f74ab 100644 --- a/stubs/html5lib/html5lib/filters/base.pyi +++ b/stubs/html5lib/html5lib/filters/base.pyi @@ -1,7 +1,10 @@ -from typing import Any +from collections.abc import Iterable, Iterator +from typing import Any, Generic, TypeVar -class Filter: - source: Any - def __init__(self, source) -> None: ... - def __iter__(self): ... - def __getattr__(self, name): ... +_T = TypeVar("_T", default=Any) + +class Filter(Generic[_T]): + source: Iterable[_T] + def __init__(self, source: Iterable[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __getattr__(self, name: str) -> Any: ... # Depends on `source` diff --git a/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi b/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi index 9cde8fde35bc..d8bb75bfcf99 100644 --- a/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi +++ b/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi @@ -1,8 +1,8 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterable from . import base -class Filter(base.Filter): - encoding: Any - def __init__(self, source, encoding) -> None: ... - def __iter__(self): ... +class Filter(base.Filter[dict[str, Incomplete]]): + encoding: str | None + def __init__(self, source: Iterable[dict[str, Incomplete]], encoding: str | None) -> None: ... diff --git a/stubs/html5lib/html5lib/filters/lint.pyi b/stubs/html5lib/html5lib/filters/lint.pyi index 5803963a11a0..37da9926b41a 100644 --- a/stubs/html5lib/html5lib/filters/lint.pyi +++ b/stubs/html5lib/html5lib/filters/lint.pyi @@ -1,8 +1,10 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterable from . import base -class Filter(base.Filter): - require_matching_tags: Any - def __init__(self, source, require_matching_tags: bool = ...) -> None: ... - def __iter__(self): ... +spaceCharacters: str + +class Filter(base.Filter[dict[str, Incomplete]]): + require_matching_tags: bool + def __init__(self, source: Iterable[dict[str, Incomplete]], require_matching_tags: bool = True) -> None: ... diff --git a/stubs/html5lib/html5lib/filters/optionaltags.pyi b/stubs/html5lib/html5lib/filters/optionaltags.pyi index 5d53a467e4a5..9050d864e756 100644 --- a/stubs/html5lib/html5lib/filters/optionaltags.pyi +++ b/stubs/html5lib/html5lib/filters/optionaltags.pyi @@ -1,7 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Generator + from . import base -class Filter(base.Filter): - def slider(self) -> None: ... - def __iter__(self): ... - def is_optional_start(self, tagname, previous, next): ... - def is_optional_end(self, tagname, next): ... +class Filter(base.Filter[dict[str, Incomplete]]): + def slider(self) -> Generator[tuple[Incomplete, Incomplete, Incomplete]]: ... + def is_optional_start(self, tagname: str, previous, next) -> bool: ... + def is_optional_end(self, tagname: str, next) -> bool: ... diff --git a/stubs/html5lib/html5lib/filters/sanitizer.pyi b/stubs/html5lib/html5lib/filters/sanitizer.pyi index 176e81a01796..3308d7fd60cd 100644 --- a/stubs/html5lib/html5lib/filters/sanitizer.pyi +++ b/stubs/html5lib/html5lib/filters/sanitizer.pyi @@ -1,34 +1,51 @@ -from typing import Any +import re +from _typeshed import Incomplete +from collections.abc import Iterable +from typing_extensions import deprecated from . import base -class Filter(base.Filter): - allowed_elements: Any - allowed_attributes: Any - allowed_css_properties: Any - allowed_css_keywords: Any - allowed_svg_properties: Any - allowed_protocols: Any - allowed_content_types: Any - attr_val_is_uri: Any - svg_attr_val_allows_ref: Any - svg_allow_local_href: Any +__all__ = ["Filter"] + +allowed_elements: frozenset[tuple[str, str]] +allowed_attributes: frozenset[tuple[None, str] | tuple[str, str]] +attr_val_is_uri: frozenset[tuple[None, str] | tuple[str, str]] +svg_attr_val_allows_ref: frozenset[tuple[None, str]] +svg_allow_local_href: frozenset[tuple[None, str]] +allowed_css_properties: frozenset[str] +allowed_css_keywords: frozenset[str] +allowed_svg_properties: frozenset[str] +allowed_protocols: frozenset[str] +allowed_content_types: frozenset[str] +data_content_type: re.Pattern[str] + +@deprecated("html5lib's sanitizer is deprecated; see https://github.com/html5lib/html5lib-python/issues/443") +class Filter(base.Filter[dict[str, Incomplete]]): + allowed_elements: Iterable[tuple[str | None, str]] + allowed_attributes: Iterable[tuple[str | None, str]] + allowed_css_properties: Iterable[str] + allowed_css_keywords: Iterable[str] + allowed_svg_properties: Iterable[str] + allowed_protocols: Iterable[str] + allowed_content_types: Iterable[str] + attr_val_is_uri: Iterable[tuple[str | None, str]] + svg_attr_val_allows_ref: Iterable[tuple[str | None, str]] + svg_allow_local_href: Iterable[tuple[str | None, str]] def __init__( self, - source, - allowed_elements=..., - allowed_attributes=..., - allowed_css_properties=..., - allowed_css_keywords=..., - allowed_svg_properties=..., - allowed_protocols=..., - allowed_content_types=..., - attr_val_is_uri=..., - svg_attr_val_allows_ref=..., - svg_allow_local_href=..., + source: Iterable[dict[str, Incomplete]], + allowed_elements: Iterable[tuple[str | None, str]] = ..., + allowed_attributes: Iterable[tuple[str | None, str]] = ..., + allowed_css_properties: Iterable[str] = ..., + allowed_css_keywords: Iterable[str] = ..., + allowed_svg_properties: Iterable[str] = ..., + allowed_protocols: Iterable[str] = ..., + allowed_content_types: Iterable[str] = ..., + attr_val_is_uri: Iterable[tuple[str | None, str]] = ..., + svg_attr_val_allows_ref: Iterable[tuple[str | None, str]] = ..., + svg_allow_local_href: Iterable[tuple[str | None, str]] = ..., ) -> None: ... - def __iter__(self): ... - def sanitize_token(self, token): ... - def allowed_token(self, token): ... - def disallowed_token(self, token): ... - def sanitize_css(self, style): ... + def sanitize_token(self, token: dict[str, Incomplete]) -> dict[str, Incomplete] | None: ... + def allowed_token(self, token: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def disallowed_token(self, token: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def sanitize_css(self, style: str) -> str: ... diff --git a/stubs/html5lib/html5lib/filters/whitespace.pyi b/stubs/html5lib/html5lib/filters/whitespace.pyi index 117aaf6411a0..89334b070913 100644 --- a/stubs/html5lib/html5lib/filters/whitespace.pyi +++ b/stubs/html5lib/html5lib/filters/whitespace.pyi @@ -1,11 +1,12 @@ -from typing import Any +import re +from _typeshed import Incomplete from . import base -SPACES_REGEX: Any +spaceCharacters: str +SPACES_REGEX: re.Pattern[str] -class Filter(base.Filter): - spacePreserveElements: Any - def __iter__(self): ... +class Filter(base.Filter[dict[str, Incomplete]]): + spacePreserveElements: frozenset[str] -def collapse_spaces(text): ... +def collapse_spaces(text: str) -> str: ... diff --git a/stubs/html5lib/html5lib/html5parser.pyi b/stubs/html5lib/html5lib/html5parser.pyi index d7a873dde8dd..5f78cf43a2ba 100644 --- a/stubs/html5lib/html5lib/html5parser.pyi +++ b/stubs/html5lib/html5lib/html5parser.pyi @@ -1,57 +1,66 @@ -from _typeshed import SupportsRead -from typing import Any, overload -from typing_extensions import Literal +from _typeshed import Incomplete +from typing import Any, Literal, overload from xml.etree.ElementTree import Element +from ._inputstream import _InputStream +from ._tokenizer import HTMLTokenizer +from .treebuilders.base import TreeBuilder + @overload def parse( - doc: str | bytes | SupportsRead[str] | SupportsRead[bytes], - treebuilder: Literal["etree"] = ..., - namespaceHTMLElements: bool = ..., - **kwargs, + doc: _InputStream, treebuilder: Literal["etree"] = "etree", namespaceHTMLElements: bool = True, **kwargs ) -> Element: ... @overload -def parse( - doc: str | bytes | SupportsRead[str] | SupportsRead[bytes], treebuilder: str, namespaceHTMLElements: bool = ..., **kwargs +def parse(doc: _InputStream, treebuilder: str, namespaceHTMLElements: bool = True, **kwargs): ... + +def parseFragment( + doc: _InputStream, container: str = "div", treebuilder: str = "etree", namespaceHTMLElements: bool = True, **kwargs ): ... -def parseFragment(doc, container: str = ..., treebuilder: str = ..., namespaceHTMLElements: bool = ..., **kwargs): ... def method_decorator_metaclass(function): ... class HTMLParser: - strict: Any - tree: Any - errors: Any - phases: Any + strict: bool + tree: Incomplete + errors: list[Incomplete] + phases: Incomplete def __init__( - self, tree: Any | None = ..., strict: bool = ..., namespaceHTMLElements: bool = ..., debug: bool = ... + self, + tree: str | type[TreeBuilder] | None = None, + strict: bool = False, + namespaceHTMLElements: bool = True, + debug: bool = False, ) -> None: ... firstStartTag: bool - log: Any + log: Incomplete compatMode: str - innerHTML: Any - phase: Any - lastPhase: Any - beforeRCDataPhase: Any + container: str + innerHTML: Incomplete + phase: Incomplete + lastPhase: Incomplete + beforeRCDataPhase: Incomplete framesetOK: bool + tokenizer: HTMLTokenizer def reset(self) -> None: ... @property def documentEncoding(self) -> str | None: ... - def isHTMLIntegrationPoint(self, element) -> bool: ... - def isMathMLTextIntegrationPoint(self, element) -> bool: ... + def isHTMLIntegrationPoint(self, element: Element) -> bool: ... + def isMathMLTextIntegrationPoint(self, element: Element) -> bool: ... def mainLoop(self) -> None: ... - def parse(self, stream, scripting: bool = ..., **kwargs): ... - def parseFragment(self, stream, *args, **kwargs): ... - def parseError(self, errorcode: str = ..., datavars: Any | None = ...) -> None: ... - def adjustMathMLAttributes(self, token) -> None: ... - def adjustSVGAttributes(self, token) -> None: ... - def adjustForeignAttributes(self, token) -> None: ... - def reparseTokenNormal(self, token) -> None: ... + def parse(self, stream: _InputStream, scripting: bool = ..., **kwargs): ... + def parseFragment(self, stream: _InputStream, *args, **kwargs): ... + def parseError(self, errorcode: str = "XXX-undefined-error", datavars=None) -> None: ... + def adjustMathMLAttributes(self, token: dict[str, Any]) -> None: ... + def adjustSVGAttributes(self, token: dict[str, Any]) -> None: ... + def adjustForeignAttributes(self, token: dict[str, Any]) -> None: ... + def reparseTokenNormal(self, token: dict[str, Any]) -> None: ... def resetInsertionMode(self) -> None: ... - originalPhase: Any - def parseRCDataRawtext(self, token, contentType) -> None: ... + originalPhase: Incomplete + def parseRCDataRawtext(self, token, contentType: Literal["RAWTEXT", "RCDATA"]) -> None: ... -def getPhases(debug): ... -def adjust_attributes(token, replacements) -> None: ... -def impliedTagToken(name, type: str = ..., attributes: Any | None = ..., selfClosing: bool = ...): ... +def getPhases(debug: bool | None) -> dict[str, type]: ... +def adjust_attributes(token: dict[str, Any], replacements: dict[str, Any]) -> None: ... +def impliedTagToken( + name: str, type: str = "EndTag", attributes: dict[str, Any] | None = None, selfClosing: bool = False +) -> dict[str, Any]: ... class ParseError(Exception): ... diff --git a/stubs/html5lib/html5lib/serializer.pyi b/stubs/html5lib/html5lib/serializer.pyi index 210c725cc2d0..a4e990c78803 100644 --- a/stubs/html5lib/html5lib/serializer.pyi +++ b/stubs/html5lib/html5lib/serializer.pyi @@ -1,15 +1,54 @@ -from typing import Any, overload +from _typeshed import Incomplete +from collections.abc import Generator +from typing import Literal, overload + +def htmlentityreplace_errors(exc: UnicodeError) -> tuple[str | bytes, int]: ... -def htmlentityreplace_errors(exc: Exception) -> tuple[str | bytes, int]: ... -@overload -def serialize(input, tree: str = ..., encoding: None = ..., **serializer_opts) -> str: ... @overload -def serialize(input, tree: str, encoding: str, **serializer_opts) -> bytes: ... +def serialize( + input, + tree: Literal["dom", "genshi", "lxml", "etree"] = "etree", + encoding: Literal[""] | None = None, + *, + quote_attr_values: Literal["legacy", "spec", "always"] = "legacy", + quote_char: str = '"', + use_best_quote_char: bool = ..., # default value depends on whether quote_char was passed + omit_optional_tags: bool = True, + minimize_boolean_attributes: bool = True, + use_trailing_solidus: bool = False, + space_before_trailing_solidus: bool = True, + escape_lt_in_attrs: bool = False, + escape_rcdata: bool = False, + resolve_entities: bool = True, + alphabetical_attributes: bool = False, + inject_meta_charset: bool = True, + strip_whitespace: bool = False, + sanitize: bool = False, +) -> str: ... @overload -def serialize(input, *, encoding: str, **serializer_opts) -> bytes: ... +def serialize( + input, + tree: Literal["dom", "genshi", "lxml", "etree"] = "etree", + encoding: str = ..., + *, + quote_attr_values: Literal["legacy", "spec", "always"] = "legacy", + quote_char: str = '"', + use_best_quote_char: bool = ..., # default value depends on whether quote_char was passed + omit_optional_tags: bool = True, + minimize_boolean_attributes: bool = True, + use_trailing_solidus: bool = False, + space_before_trailing_solidus: bool = True, + escape_lt_in_attrs: bool = False, + escape_rcdata: bool = False, + resolve_entities: bool = True, + alphabetical_attributes: bool = False, + inject_meta_charset: bool = True, + strip_whitespace: bool = False, + sanitize: bool = False, +) -> bytes: ... class HTMLSerializer: - quote_attr_values: str + quote_attr_values: Literal["legacy", "spec", "always"] quote_char: str use_best_quote_char: bool omit_optional_tags: bool @@ -23,15 +62,41 @@ class HTMLSerializer: inject_meta_charset: bool strip_whitespace: bool sanitize: bool - options: Any - errors: Any + options: tuple[str, ...] + errors: list[Incomplete] strict: bool - def __init__(self, **kwargs) -> None: ... - def encode(self, string): ... - def encodeStrict(self, string): ... - encoding: Any - def serialize(self, treewalker, encoding: Any | None = ...) -> None: ... - def render(self, treewalker, encoding: Any | None = ...): ... - def serializeError(self, data: str = ...) -> None: ... + def __init__( + self, + *, + quote_attr_values: Literal["legacy", "spec", "always"] = "legacy", + quote_char: str = '"', + use_best_quote_char: bool = ..., # default value depends on whether quote_char was passed + omit_optional_tags: bool = True, + minimize_boolean_attributes: bool = True, + use_trailing_solidus: bool = False, + space_before_trailing_solidus: bool = True, + escape_lt_in_attrs: bool = False, + escape_rcdata: bool = False, + resolve_entities: bool = True, + alphabetical_attributes: bool = False, + inject_meta_charset: bool = True, + strip_whitespace: bool = False, + sanitize: bool = False, + ) -> None: ... + def encode(self, string: str) -> str | bytes: ... # result depends on self.encoding + def encodeStrict(self, string: str) -> str | bytes: ... # result depends on self.encoding + encoding: str | None + + @overload + def serialize(self, treewalker, encoding: Literal[""] | None = None) -> Generator[str]: ... + @overload + def serialize(self, treewalker, encoding: str = ...) -> Generator[bytes]: ... + + @overload + def render(self, treewalker, encoding: Literal[""] | None = None) -> str: ... + @overload + def render(self, treewalker, encoding: str = ...) -> bytes: ... + + def serializeError(self, data="XXX ERROR MESSAGE NEEDED") -> None: ... class SerializeError(Exception): ... diff --git a/stubs/html5lib/html5lib/treeadapters/__init__.pyi b/stubs/html5lib/html5lib/treeadapters/__init__.pyi index bf1267485d4b..49b1ebb296a2 100644 --- a/stubs/html5lib/html5lib/treeadapters/__init__.pyi +++ b/stubs/html5lib/html5lib/treeadapters/__init__.pyi @@ -1 +1,3 @@ from . import genshi as genshi, sax as sax + +__all__ = ["sax", "genshi"] diff --git a/stubs/html5lib/html5lib/treeadapters/sax.pyi b/stubs/html5lib/html5lib/treeadapters/sax.pyi index 87ebcb1cb930..22c93013ce67 100644 --- a/stubs/html5lib/html5lib/treeadapters/sax.pyi +++ b/stubs/html5lib/html5lib/treeadapters/sax.pyi @@ -1,5 +1,3 @@ -from typing import Any - -prefix_mapping: Any +prefix_mapping: dict[str, str] def to_sax(walker, handler) -> None: ... diff --git a/stubs/html5lib/html5lib/treebuilders/__init__.pyi b/stubs/html5lib/html5lib/treebuilders/__init__.pyi index a9cd20041283..7fc1af410d92 100644 --- a/stubs/html5lib/html5lib/treebuilders/__init__.pyi +++ b/stubs/html5lib/html5lib/treebuilders/__init__.pyi @@ -1,5 +1,5 @@ -from typing import Any +from typing import Literal -treeBuilderCache: Any +treeBuilderCache: dict[str, type] -def getTreeBuilder(treeType, implementation: Any | None = ..., **kwargs): ... +def getTreeBuilder(treeType: Literal["dom", "etree", "lxml"], implementation=None, **kwargs): ... diff --git a/stubs/html5lib/html5lib/treebuilders/base.pyi b/stubs/html5lib/html5lib/treebuilders/base.pyi index 12e89bb296d4..59137fe3239f 100644 --- a/stubs/html5lib/html5lib/treebuilders/base.pyi +++ b/stubs/html5lib/html5lib/treebuilders/base.pyi @@ -1,55 +1,55 @@ -from typing import Any, List +from _typeshed import Incomplete -Marker: Any -listElementsMap: Any +Marker: Incomplete +listElementsMap: dict[str | None, tuple[frozenset[tuple[str, str]], bool]] class Node: - name: Any - parent: Any - value: Any - attributes: Any - childNodes: Any - def __init__(self, name) -> None: ... + name: str + parent: Incomplete + value: Incomplete + attributes: Incomplete + childNodes: Incomplete + def __init__(self, name: str) -> None: ... def appendChild(self, node) -> None: ... - def insertText(self, data, insertBefore: Any | None = ...) -> None: ... + def insertText(self, data, insertBefore=None) -> None: ... def insertBefore(self, node, refNode) -> None: ... def removeChild(self, node) -> None: ... def reparentChildren(self, newParent) -> None: ... def cloneNode(self) -> None: ... def hasContent(self) -> None: ... -class ActiveFormattingElements(List[Any]): +class ActiveFormattingElements(list[Incomplete]): def append(self, node) -> None: ... - def nodesEqual(self, node1, node2): ... + def nodesEqual(self, node1, node2) -> bool: ... class TreeBuilder: - documentClass: Any - elementClass: Any - commentClass: Any - doctypeClass: Any - fragmentClass: Any - defaultNamespace: str - def __init__(self, namespaceHTMLElements) -> None: ... - openElements: Any - activeFormattingElements: Any - headPointer: Any - formPointer: Any + documentClass: Incomplete + elementClass: Incomplete + commentClass: Incomplete + doctypeClass: Incomplete + fragmentClass: Incomplete + defaultNamespace: str | None + def __init__(self, namespaceHTMLElements: bool | None) -> None: ... + openElements: Incomplete + activeFormattingElements: Incomplete + headPointer: Incomplete + formPointer: Incomplete insertFromTable: bool - document: Any + document: Incomplete def reset(self) -> None: ... - def elementInScope(self, target, variant: Any | None = ...): ... + def elementInScope(self, target, variant=None): ... def reconstructActiveFormattingElements(self) -> None: ... def clearActiveFormattingElements(self) -> None: ... def elementInActiveFormattingElements(self, name): ... def insertRoot(self, token) -> None: ... def insertDoctype(self, token) -> None: ... - def insertComment(self, token, parent: Any | None = ...) -> None: ... + def insertComment(self, token, parent=None) -> None: ... def createElement(self, token): ... def insertElementNormal(self, token): ... def insertElementTable(self, token): ... - def insertText(self, data, parent: Any | None = ...) -> None: ... + def insertText(self, data, parent=None) -> None: ... def getTableMisnestedNodePosition(self): ... - def generateImpliedEndTags(self, exclude: Any | None = ...) -> None: ... + def generateImpliedEndTags(self, exclude=None) -> None: ... def getDocument(self): ... def getFragment(self): ... - def testSerializer(self, node) -> None: ... + def testSerializer(self, node): ... diff --git a/stubs/html5lib/html5lib/treebuilders/dom.pyi b/stubs/html5lib/html5lib/treebuilders/dom.pyi index 12de3344d248..d8049c383cf1 100644 --- a/stubs/html5lib/html5lib/treebuilders/dom.pyi +++ b/stubs/html5lib/html5lib/treebuilders/dom.pyi @@ -1,5 +1,7 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable +from types import ModuleType -def getDomBuilder(DomImplementation): ... +def getDomBuilder(DomImplementation) -> dict[str, Incomplete]: ... -getDomModule: Any +getDomModule: Callable[..., ModuleType] diff --git a/stubs/html5lib/html5lib/treebuilders/etree.pyi b/stubs/html5lib/html5lib/treebuilders/etree.pyi index f4b8e54b5c6c..b9dfabb88835 100644 --- a/stubs/html5lib/html5lib/treebuilders/etree.pyi +++ b/stubs/html5lib/html5lib/treebuilders/etree.pyi @@ -1,7 +1,10 @@ -from typing import Any +import re +from _typeshed import Incomplete +from collections.abc import Callable +from types import ModuleType -tag_regexp: Any +tag_regexp: re.Pattern[str] -def getETreeBuilder(ElementTreeImplementation, fullTree: bool = ...): ... +def getETreeBuilder(ElementTreeImplementation, fullTree: bool = False) -> dict[str, Incomplete]: ... -getETreeModule: Any +getETreeModule: Callable[..., ModuleType] diff --git a/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi b/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi index 1016b90919eb..665eb117d358 100644 --- a/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi +++ b/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi @@ -1,43 +1,45 @@ -from typing import Any +import re +from _typeshed import Incomplete from . import base fullTree: bool -tag_regexp: Any -comment_type: Any +tag_regexp: re.Pattern[str] +comment_type: Incomplete class DocumentType: - name: Any - publicId: Any - systemId: Any + name: Incomplete + publicId: Incomplete + systemId: Incomplete def __init__(self, name, publicId, systemId) -> None: ... class Document: def __init__(self) -> None: ... def appendChild(self, element) -> None: ... - childNodes: Any + @property + def childNodes(self): ... -def testSerializer(element): ... -def tostring(element): ... +def testSerializer(element) -> str: ... +def tostring(element) -> str: ... class TreeBuilder(base.TreeBuilder): - documentClass: Any - doctypeClass: Any - elementClass: Any - commentClass: Any - fragmentClass: Any - implementation: Any - namespaceHTMLElements: Any - def __init__(self, namespaceHTMLElements, fullTree: bool = ...): ... - insertComment: Any - initial_comments: Any - doctype: Any + documentClass: Incomplete + doctypeClass: Incomplete + elementClass: Incomplete + commentClass: Incomplete + fragmentClass: Incomplete + implementation: Incomplete + namespaceHTMLElements: Incomplete + def __init__(self, namespaceHTMLElements, fullTree: bool = False): ... + insertComment: Incomplete + initial_comments: Incomplete + doctype: Incomplete def reset(self) -> None: ... def testSerializer(self, element): ... def getDocument(self): ... def getFragment(self): ... def insertDoctype(self, token) -> None: ... - def insertCommentInitial(self, data, parent: Any | None = ...) -> None: ... - def insertCommentMain(self, data, parent: Any | None = ...) -> None: ... - document: Any + def insertCommentInitial(self, data, parent=None) -> None: ... + def insertCommentMain(self, data, parent=None) -> None: ... + document: Incomplete def insertRoot(self, token) -> None: ... diff --git a/stubs/html5lib/html5lib/treewalkers/__init__.pyi b/stubs/html5lib/html5lib/treewalkers/__init__.pyi index eb1e26e94254..247912e69830 100644 --- a/stubs/html5lib/html5lib/treewalkers/__init__.pyi +++ b/stubs/html5lib/html5lib/treewalkers/__init__.pyi @@ -1,4 +1,7 @@ -from typing import Any +from types import ModuleType -def getTreeWalker(treeType, implementation: Any | None = ..., **kwargs): ... -def pprint(walker): ... +__all__ = ["getTreeWalker", "pprint"] + +def getTreeWalker(treeType: str, implementation: ModuleType | None = None, **kwargs): ... +def concatenateCharacterTokens(tokens): ... +def pprint(walker) -> str: ... diff --git a/stubs/html5lib/html5lib/treewalkers/base.pyi b/stubs/html5lib/html5lib/treewalkers/base.pyi index 34eee4b3e789..2ef37965b6d2 100644 --- a/stubs/html5lib/html5lib/treewalkers/base.pyi +++ b/stubs/html5lib/html5lib/treewalkers/base.pyi @@ -1,24 +1,27 @@ -from typing import Any +from _typeshed import Incomplete -DOCUMENT: Any -DOCTYPE: Any -TEXT: Any -ELEMENT: Any -COMMENT: Any -ENTITY: Any +__all__ = ["DOCUMENT", "DOCTYPE", "TEXT", "ELEMENT", "COMMENT", "ENTITY", "UNKNOWN", "TreeWalker", "NonRecursiveTreeWalker"] + +DOCUMENT: int +DOCTYPE: int +TEXT: int +ELEMENT: int +COMMENT: int +ENTITY: int UNKNOWN: str +spaceCharacters: str class TreeWalker: - tree: Any + tree: Incomplete def __init__(self, tree) -> None: ... def __iter__(self): ... def error(self, msg): ... - def emptyTag(self, namespace, name, attrs, hasChildren: bool = ...) -> None: ... + def emptyTag(self, namespace, name, attrs, hasChildren: bool = False) -> None: ... def startTag(self, namespace, name, attrs): ... def endTag(self, namespace, name): ... def text(self, data) -> None: ... def comment(self, data): ... - def doctype(self, name, publicId: Any | None = ..., systemId: Any | None = ...): ... + def doctype(self, name, publicId=None, systemId=None): ... def entity(self, name): ... def unknown(self, nodeType): ... diff --git a/stubs/html5lib/html5lib/treewalkers/etree.pyi b/stubs/html5lib/html5lib/treewalkers/etree.pyi index 33f6d800214f..94878061a818 100644 --- a/stubs/html5lib/html5lib/treewalkers/etree.pyi +++ b/stubs/html5lib/html5lib/treewalkers/etree.pyi @@ -1,7 +1,9 @@ -from typing import Any +import re +from collections.abc import Callable +from types import ModuleType -tag_regexp: Any +tag_regexp: re.Pattern[str] def getETreeBuilder(ElementTreeImplementation): ... -getETreeModule: Any +getETreeModule: Callable[..., ModuleType] diff --git a/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi b/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi index c9fb06cee9bc..4071bb068650 100644 --- a/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi +++ b/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi @@ -1,52 +1,56 @@ -from typing import Any +from _typeshed import Incomplete +from typing import SupportsIndex, overload from .base import NonRecursiveTreeWalker -def ensure_str(s): ... +@overload +def ensure_str(s: None) -> None: ... +@overload +def ensure_str(s: str | bytes | bytearray) -> str: ... class Root: - elementtree: Any - children: Any - text: Any - tail: Any + elementtree: Incomplete + children: list[Incomplete] + text: str | None + tail: str | None def __init__(self, et) -> None: ... - def __getitem__(self, key): ... + def __getitem__(self, key: SupportsIndex): ... def getnext(self) -> None: ... - def __len__(self): ... + def __len__(self) -> int: ... class Doctype: - root_node: Any - name: Any - public_id: Any - system_id: Any - text: Any - tail: Any + root_node: Incomplete + name: Incomplete + public_id: Incomplete + system_id: Incomplete + text: Incomplete + tail: Incomplete def __init__(self, root_node, name, public_id, system_id) -> None: ... def getnext(self): ... class FragmentRoot(Root): - children: Any - text: Any + children: Incomplete + text: Incomplete def __init__(self, children) -> None: ... def getnext(self) -> None: ... class FragmentWrapper: - root_node: Any - obj: Any - text: Any - tail: Any + root_node: Incomplete + obj: Incomplete + text: Incomplete + tail: Incomplete def __init__(self, fragment_root, obj) -> None: ... - def __getattr__(self, name): ... + def __getattr__(self, name: str): ... def getnext(self): ... def __getitem__(self, key): ... - def __bool__(self): ... + def __bool__(self) -> bool: ... def getparent(self) -> None: ... - def __unicode__(self): ... - def __len__(self): ... + def __unicode__(self) -> str: ... + def __len__(self) -> int: ... class TreeWalker(NonRecursiveTreeWalker): - fragmentChildren: Any - filter: Any + fragmentChildren: Incomplete + filter: Incomplete def __init__(self, tree) -> None: ... def getNodeDetails(self, node): ... def getFirstChild(self, node): ... diff --git a/stubs/httplib2/METADATA.toml b/stubs/httplib2/METADATA.toml index ae1fb69ffa18..69b14a50a93a 100644 --- a/stubs/httplib2/METADATA.toml +++ b/stubs/httplib2/METADATA.toml @@ -1 +1,2 @@ -version = "0.20.*" +version = "0.32.0" +upstream-repository = "https://github.com/httplib2/httplib2" diff --git a/stubs/httplib2/httplib2/__init__.pyi b/stubs/httplib2/httplib2/__init__.pyi index 14bf1dba7af8..7be7c15e3ea0 100644 --- a/stubs/httplib2/httplib2/__init__.pyi +++ b/stubs/httplib2/httplib2/__init__.pyi @@ -1,58 +1,100 @@ +import builtins +import email.message import http.client +import re +from _ssl import _PasswordType +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, MaybeNone, StrOrBytesPath from collections.abc import Generator -from typing import Any, Dict, TypeVar +from ssl import _SSLMethod +from typing import Any, ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Self from .error import * -# Should use _typeshed.Self when google/pytype#952 is fixed. -Self = TypeVar("Self") # noqa Y001 - -__author__: str -__copyright__: str -__contributors__: list[str] -__license__: str -__version__: str - -debuglevel: int -RETRIES: int +_T = TypeVar("_T", default=str) +_R = TypeVar("_R") +_D = TypeVar("_D") + +__author__: Final[str] +__copyright__: Final[str] +__contributors__: Final[list[str]] +__license__: Final[str] +__version__: Final[str] +__all__ = [ + "debuglevel", + "FailedToDecompressContent", + "Http", + "HttpLib2Error", + "ProxyInfo", + "RedirectLimit", + "RedirectMissingLocation", + "Response", + "RETRIES", + "UnimplementedDigestAuthOptionError", + "UnimplementedHmacDigestAuthOptionError", +] + +def has_timeout(timeout: float | None) -> bool: ... + +debuglevel: Final[int] +RETRIES: Final[int] +DEFAULT_MAX_REDIRECTS: Final[int] +HOP_BY_HOP: Final[list[str]] +SAFE_METHODS: Final[tuple[str, ...]] +REDIRECT_CODES: Final[frozenset[int]] +CA_CERTS: Final[str] +DEFAULT_TLS_VERSION: Final[_SSLMethod] +URI: Final[re.Pattern[str]] + +def parse_uri(uri: str) -> tuple[str | MaybeNone, str | MaybeNone, str | MaybeNone, str | MaybeNone, str | MaybeNone]: ... +def urlnorm(uri: str) -> tuple[str | MaybeNone, str | MaybeNone, str | MaybeNone, str | MaybeNone]: ... + +re_url_scheme: Final[re.Pattern[str]] +re_unsafe: Final[re.Pattern[str]] + +def safename(filename: str | bytes) -> str: ... + +NORMALIZE_SPACE: Final[re.Pattern[str]] +USE_WWW_AUTH_STRICT_PARSING: Final[int] class Authentication: - path: Any - host: Any - credentials: Any - http: Any - def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... - def depth(self, request_uri): ... - def inscope(self, host, request_uri): ... + path: Incomplete + host: Incomplete + credentials: Incomplete + http: Incomplete + def __init__(self, credentials, host, request_uri: str, headers, response, content, http) -> None: ... + def depth(self, request_uri: str) -> int: ... + def inscope(self, host: str, request_uri: str) -> bool: ... def request(self, method, request_uri, headers, content) -> None: ... - def response(self, response, content): ... - def __eq__(self, auth): ... - def __ne__(self, auth): ... - def __lt__(self, auth): ... - def __gt__(self, auth): ... - def __le__(self, auth): ... - def __ge__(self, auth): ... - def __bool__(self): ... + def response(self, response, content) -> bool: ... + def __eq__(self, auth: object) -> bool: ... + def __ne__(self, auth: object) -> bool: ... + def __lt__(self, auth: object) -> bool: ... + def __gt__(self, auth: object) -> bool: ... + def __le__(self, auth: object) -> bool: ... + def __ge__(self, auth: object) -> bool: ... + def __bool__(self) -> bool: ... class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... def request(self, method, request_uri, headers, content) -> None: ... class DigestAuthentication(Authentication): - challenge: Any - A1: Any + challenge: Incomplete + A1: Incomplete def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... - def request(self, method, request_uri, headers, content, cnonce: Any | None = ...): ... - def response(self, response, content): ... + def request(self, method, request_uri, headers, content, cnonce=None): ... + def response(self, response, content) -> bool: ... class HmacDigestAuthentication(Authentication): - challenge: Any - hashmod: Any - pwhashmod: Any - key: Any + challenge: Incomplete + hashmod: Incomplete + pwhashmod: Incomplete + key: Incomplete + __author__: ClassVar[str] def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... def request(self, method, request_uri, headers, content) -> None: ... - def response(self, response, content): ... + def response(self, response, content) -> bool: ... class WsseAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... @@ -64,123 +106,127 @@ class GoogleLoginAuthentication(Authentication): def request(self, method, request_uri, headers, content) -> None: ... class FileCache: - cache: Any - safe: Any + cache: Incomplete + safe: Incomplete def __init__(self, cache, safe=...) -> None: ... def get(self, key): ... def set(self, key, value) -> None: ... def delete(self, key) -> None: ... class Credentials: - credentials: Any + credentials: Incomplete def __init__(self) -> None: ... - def add(self, name, password, domain: str = ...) -> None: ... + def add(self, name, password, domain: str = "") -> None: ... def clear(self) -> None: ... - def iter(self, domain) -> Generator[tuple[str, str], None, None]: ... + def iter(self, domain) -> Generator[tuple[str, str]]: ... class KeyCerts(Credentials): def add(self, key, cert, domain, password) -> None: ... # type: ignore[override] - def iter(self, domain) -> Generator[tuple[str, str, str], None, None]: ... # type: ignore[override] + def iter(self, domain) -> Generator[tuple[str, str, str]]: ... # type: ignore[override] class AllHosts: ... class ProxyInfo: - bypass_hosts: Any + bypass_hosts: Incomplete def __init__( - self, - proxy_type, - proxy_host, - proxy_port, - proxy_rdns: bool = ..., - proxy_user: Any | None = ..., - proxy_pass: Any | None = ..., - proxy_headers: Any | None = ..., + self, proxy_type, proxy_host, proxy_port, proxy_rdns: bool = True, proxy_user=None, proxy_pass=None, proxy_headers=None ) -> None: ... def astuple(self): ... def isgood(self): ... def applies_to(self, hostname): ... def bypass_host(self, hostname): ... +def proxy_info_from_environment(method: Literal["http", "https"] = "http") -> ProxyInfo | None: ... +def proxy_info_from_url(url: str, method: Literal["http", "https"] = "http", noproxy: str | None = None) -> ProxyInfo: ... + class HTTPConnectionWithTimeout(http.client.HTTPConnection): - proxy_info: Any - def __init__(self, host, port: Any | None = ..., timeout: Any | None = ..., proxy_info: Any | None = ...) -> None: ... - sock: Any + proxy_info: Incomplete + def __init__(self, host, port=None, timeout=None, proxy_info=None) -> None: ... + sock: Incomplete def connect(self) -> None: ... class HTTPSConnectionWithTimeout(http.client.HTTPSConnection): - disable_ssl_certificate_validation: Any - ca_certs: Any - proxy_info: Any - key_file: Any - cert_file: Any - key_password: Any + disable_ssl_certificate_validation: bool + ca_certs: StrOrBytesPath | None + proxy_info: Incomplete + key_file: StrOrBytesPath | None + cert_file: StrOrBytesPath | None + key_password: _PasswordType | None def __init__( self, - host, - port: Any | None = ..., - key_file: Any | None = ..., - cert_file: Any | None = ..., - timeout: Any | None = ..., - proxy_info: Any | None = ..., - ca_certs: Any | None = ..., - disable_ssl_certificate_validation: bool = ..., - tls_maximum_version: Any | None = ..., - tls_minimum_version: Any | None = ..., - key_password: Any | None = ..., + host: str, + port: int | None = None, + key_file: StrOrBytesPath | None = None, + cert_file: StrOrBytesPath | None = None, + timeout: float | None = None, + proxy_info=None, + ca_certs: StrOrBytesPath | None = None, + disable_ssl_certificate_validation: bool = False, + tls_maximum_version=None, + tls_minimum_version=None, + key_password: _PasswordType | None = None, ) -> None: ... - sock: Any + sock: Incomplete def connect(self) -> None: ... +SCHEME_TO_CONNECTION: Final[dict[Literal["http", "https"], type[http.client.HTTPConnection]]] + class Http: - proxy_info: Any - ca_certs: Any - disable_ssl_certificate_validation: Any - tls_maximum_version: Any - tls_minimum_version: Any - connections: Any - cache: Any - credentials: Any - certificates: Any - authorizations: Any + proxy_info: Incomplete + ca_certs: Incomplete + disable_ssl_certificate_validation: bool + tls_maximum_version: Incomplete + tls_minimum_version: Incomplete + connections: Incomplete + cache: FileCache + credentials: Credentials + certificates: KeyCerts + authorizations: list[Authentication] follow_redirects: bool - redirect_codes: Any - optimistic_concurrency_methods: Any - safe_methods: Any + redirect_codes: frozenset[int] + optimistic_concurrency_methods: list[str] + safe_methods: list[str] follow_all_redirects: bool ignore_etag: bool force_exception_to_status_code: bool - timeout: Any + timeout: float | None forward_authorization_headers: bool + limit_kwargs: dict[str, float] def __init__( self, - cache: Any | None = ..., - timeout: Any | None = ..., + cache: str | FileCache | None = None, + timeout: float | None = None, proxy_info=..., - ca_certs: Any | None = ..., - disable_ssl_certificate_validation: bool = ..., - tls_maximum_version: Any | None = ..., - tls_minimum_version: Any | None = ..., + ca_certs=None, + disable_ssl_certificate_validation: bool = False, + tls_maximum_version=None, + tls_minimum_version=None, + decode_limit_hard: ConvertibleToInt | None = None, + decode_limit_safe: ConvertibleToInt | None = None, + decode_limit_ratio: ConvertibleToFloat | None = None, + decode_limit_chunk: ConvertibleToInt | None = None, ) -> None: ... def close(self) -> None: ... - def add_credentials(self, name, password, domain: str = ...) -> None: ... - def add_certificate(self, key, cert, domain, password: Any | None = ...) -> None: ... + def add_credentials(self, name, password, domain: str = "") -> None: ... + def add_certificate(self, key, cert, domain, password=None) -> None: ... def clear_credentials(self) -> None: ... - def request( - self, - uri, - method: str = ..., - body: Any | None = ..., - headers: Any | None = ..., - redirections=..., - connection_type: Any | None = ..., - ): ... - -class Response(Dict[str, Any]): + def request(self, uri, method: str = "GET", body=None, headers=None, redirections=5, connection_type=None): ... + +class Response(dict[str, str | _T]): fromcache: bool version: int status: int reason: str - previous: Any - def __init__(self, info) -> None: ... + previous: Response[_T] | None + def __init__(self, info: http.client.HTTPResponse | email.message.Message | builtins.dict[str, _T]) -> None: ... @property - def dict(self: Self) -> Self: ... + def dict(self) -> Self: ... + +@overload +def try_value_or_env( + to: type[_R], value: Any, env_key: str, default: None = None # `value` type depends on what `to()` can convert +) -> _R | None: ... +@overload +def try_value_or_env( + to: type[_R], value: Any, env_key: str, default: _D = ... # `value` type depends on what `to()` can convert +) -> _R | _D: ... diff --git a/stubs/httplib2/httplib2/auth.pyi b/stubs/httplib2/httplib2/auth.pyi index d7168f153cc3..8e4faf3b08fc 100644 --- a/stubs/httplib2/httplib2/auth.pyi +++ b/stubs/httplib2/httplib2/auth.pyi @@ -1,15 +1,18 @@ -from typing import Any +import re +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Final -UNQUOTE_PAIRS: Any -unquote: Any -tchar: Any -token: Any -token68: Any -quoted_string: Any -auth_param_name: Any -auth_param: Any -params: Any -scheme: Any -challenge: Any -authentication_info: Any -www_authenticate: Any +UNQUOTE_PAIRS: Final[re.Pattern[str]] +unquote: Callable[..., str] +tchar: Final[str] +token: Incomplete # types from pyparsing library +token68: Incomplete +quoted_string: Incomplete +auth_param_name: Incomplete +auth_param: Incomplete +params: Incomplete +scheme: Incomplete +challenge: Incomplete +authentication_info: Incomplete +www_authenticate: Incomplete diff --git a/stubs/httplib2/httplib2/certs.pyi b/stubs/httplib2/httplib2/certs.pyi index c0a5ce2b9bce..197e1ced1d60 100644 --- a/stubs/httplib2/httplib2/certs.pyi +++ b/stubs/httplib2/httplib2/certs.pyi @@ -1,9 +1,10 @@ -from typing import Any +from collections.abc import Callable +from typing import Final certifi_available: bool -certifi_where: Any +certifi_where: Callable[[], str] | None custom_ca_locater_available: bool -custom_ca_locater_where: Any -BUILTIN_CA_CERTS: Any +custom_ca_locater_where: Callable[..., str] | None +BUILTIN_CA_CERTS: Final[str] -def where(): ... +def where() -> str: ... diff --git a/stubs/httplib2/httplib2/decode.pyi b/stubs/httplib2/httplib2/decode.pyi new file mode 100644 index 000000000000..9c9e14ca1601 --- /dev/null +++ b/stubs/httplib2/httplib2/decode.pyi @@ -0,0 +1,52 @@ +from typing import Final, Protocol + +class DecodeRatioError(Exception): ... +class DecodeLimitError(Exception): ... + +class DecoderProtocol(Protocol): + @property + def needs_input(self) -> bool: ... + def decode(self, b: bytes) -> bytes: ... + def flush(self) -> bytes: ... + def consume_bytes(self, data: bytes, chunk_size: int = 65536) -> bytes: ... + +class ZlibDecoder(DecoderProtocol): + __slots__ = ("_decoder",) + WBITS_DEFLATE: Final = -15 + WBITS_ZLIB: Final = 15 + WBITS_GZIP: Final = 31 + WBITS_AUTO_GZIP_ZLIB: Final = 47 + + def __init__(self, wbits: int = 47): ... + @property + def needs_input(self) -> bool: ... + def decode(self, b: bytes) -> bytes: ... + def flush(self) -> bytes: ... + +def DeflateDecoder() -> ZlibDecoder: ... + +class LimitDecoder(DecoderProtocol): + __slots__ = ( + "_decoder", + "_ratio", + "_chunk_size", + "_safe_limit", + "_hard_limit", + "_consumed_length", + "_output_length", + "_input_buffer", + "_flushed", + ) + + def __init__( + self, + decoder: DecoderProtocol, + ratio: float = 100, + chunk_size: int = 65536, + safe_limit: int = 10485760, + hard_limit: int = ..., + ) -> None: ... + @property + def needs_input(self) -> bool: ... + def decode(self, b: bytes) -> bytes: ... + def flush(self) -> bytes: ... diff --git a/stubs/httplib2/httplib2/error.pyi b/stubs/httplib2/httplib2/error.pyi index 1287702e2196..fa94b45ba8c0 100644 --- a/stubs/httplib2/httplib2/error.pyi +++ b/stubs/httplib2/httplib2/error.pyi @@ -1,11 +1,15 @@ -from typing import Any +from _typeshed import Incomplete + +from httplib2 import Response class HttpLib2Error(Exception): ... class HttpLib2ErrorWithResponse(HttpLib2Error): - response: Any - content: Any - def __init__(self, desc, response, content) -> None: ... + response: Response | dict[str, Incomplete] | None + content: str | bytes | None + def __init__( + self, desc: str | None, response: Response | dict[str, Incomplete] | None, content: str | bytes | None + ) -> None: ... class RedirectMissingLocation(HttpLib2ErrorWithResponse): ... class RedirectLimit(HttpLib2ErrorWithResponse): ... diff --git a/stubs/httplib2/httplib2/iri2uri.pyi b/stubs/httplib2/httplib2/iri2uri.pyi index 7365d894ee2e..d935ed36f15e 100644 --- a/stubs/httplib2/httplib2/iri2uri.pyi +++ b/stubs/httplib2/httplib2/iri2uri.pyi @@ -1,12 +1,14 @@ -from typing import Any +from typing import Final, TypeVar -__author__: str -__copyright__: str -__contributors__: list[str] -__version__: str -__license__: str +_T = TypeVar("_T") -escape_range: Any +__author__: Final[str] +__copyright__: Final[str] +__contributors__: Final[list[str]] +__version__: Final[str] +__license__: Final[str] -def encode(c): ... -def iri2uri(uri): ... +escape_range: list[tuple[int, int]] + +def encode(c: str) -> str: ... +def iri2uri(uri: _T) -> _T: ... diff --git a/stubs/httplib2/httplib2/socks.pyi b/stubs/httplib2/httplib2/socks.pyi deleted file mode 100644 index c65363dee819..000000000000 --- a/stubs/httplib2/httplib2/socks.pyi +++ /dev/null @@ -1,42 +0,0 @@ -import socket -from typing import Any - -PROXY_TYPE_SOCKS4: int -PROXY_TYPE_SOCKS5: int -PROXY_TYPE_HTTP: int -PROXY_TYPE_HTTP_NO_TUNNEL: int - -class ProxyError(Exception): ... -class GeneralProxyError(ProxyError): ... -class Socks5AuthError(ProxyError): ... -class Socks5Error(ProxyError): ... -class Socks4Error(ProxyError): ... -class HTTPError(ProxyError): ... - -def setdefaultproxy( - proxytype: Any | None = ..., - addr: Any | None = ..., - port: Any | None = ..., - rdns: bool = ..., - username: Any | None = ..., - password: Any | None = ..., -) -> None: ... -def wrapmodule(module) -> None: ... - -class socksocket(socket.socket): - def __init__(self, family=..., type=..., proto: int = ..., _sock: Any | None = ...) -> None: ... - def sendall(self, content, *args): ... - def setproxy( - self, - proxytype: Any | None = ..., - addr: Any | None = ..., - port: Any | None = ..., - rdns: bool = ..., - username: Any | None = ..., - password: Any | None = ..., - headers: Any | None = ..., - ) -> None: ... - def getproxysockname(self): ... - def getproxypeername(self): ... - def getpeername(self): ... - def connect(self, destpair) -> None: ... diff --git a/stubs/httpretty/METADATA.toml b/stubs/httpretty/METADATA.toml new file mode 100644 index 000000000000..84ef9a4c2452 --- /dev/null +++ b/stubs/httpretty/METADATA.toml @@ -0,0 +1,6 @@ +version = "1.1.4" +upstream-repository = "https://github.com/gabrielfalcao/HTTPretty" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/httpretty/httpretty/__init__.pyi b/stubs/httpretty/httpretty/__init__.pyi new file mode 100644 index 000000000000..22b0f3a9b48d --- /dev/null +++ b/stubs/httpretty/httpretty/__init__.pyi @@ -0,0 +1,39 @@ +from typing import Final + +from .core import ( + EmptyRequestHeaders as EmptyRequestHeaders, + Entry as Entry, + HTTPrettyRequest as HTTPrettyRequest, + HTTPrettyRequestEmpty as HTTPrettyRequestEmpty, + URIInfo as URIInfo, + URIMatcher as URIMatcher, + get_default_thread_timeout as get_default_thread_timeout, + httprettified as httprettified, + httprettized as httprettized, + httpretty as httpretty, + set_default_thread_timeout as set_default_thread_timeout, +) +from .errors import HTTPrettyError as HTTPrettyError, UnmockedError as UnmockedError + +__version__: Final[str] +HTTPretty = httpretty +activate = httprettified +enabled = httprettized +enable = httpretty.enable +register_uri = httpretty.register_uri +disable = httpretty.disable +is_enabled = httpretty.is_enabled +reset = httpretty.reset +Response = httpretty.Response +GET: Final = "GET" +PUT: Final = "PUT" +POST: Final = "POST" +DELETE: Final = "DELETE" +HEAD: Final = "HEAD" +PATCH: Final = "PATCH" +OPTIONS: Final = "OPTIONS" +CONNECT: Final = "CONNECT" + +def last_request() -> HTTPrettyRequest | HTTPrettyRequestEmpty: ... +def latest_requests() -> list[HTTPrettyRequest]: ... +def has_request() -> bool: ... diff --git a/stubs/httpretty/httpretty/compat.pyi b/stubs/httpretty/httpretty/compat.pyi new file mode 100644 index 000000000000..aa9ef01dc4b4 --- /dev/null +++ b/stubs/httpretty/httpretty/compat.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +class BaseClass: ... + +def encode_obj(in_obj: _T) -> _T: ... diff --git a/stubs/httpretty/httpretty/core.pyi b/stubs/httpretty/httpretty/core.pyi new file mode 100644 index 000000000000..d858deefecdb --- /dev/null +++ b/stubs/httpretty/httpretty/core.pyi @@ -0,0 +1,202 @@ +import re +from collections.abc import Callable, Iterable, Mapping +from contextlib import AbstractContextManager +from http.client import HTTPMessage +from types import TracebackType +from typing import Any, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import ParamSpec, TypeVar + +from .http import HttpBaseClass, _HTTPMethod + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +@type_check_only +class _WritableFileobj(Protocol): + def write(self, b: bytes, /) -> object: ... + def seek(self, offset: int, /) -> object: ... + +_URI: TypeAlias = str | re.Pattern[str] +_HeaderValue: TypeAlias = str | int | bool | None +_Headers: TypeAlias = Mapping[str, _HeaderValue] +_Body: TypeAlias = str | bytes +_ResponseBody: TypeAlias = _Body | Callable[[HTTPrettyRequest, str, _Headers], tuple[int, _Headers, _Body]] + +def set_default_thread_timeout(timeout: float) -> None: ... +def get_default_thread_timeout() -> float: ... + +class HTTPrettyRequest(HttpBaseClass): + headers: HTTPMessage + raw_headers: str + path: str + querystring: dict[str, list[str]] + parsed_body: Any # It can be any object after parsing raw (str) body + created_at: float + def __init__( + self, headers: str | bytes, body: _Body = "", sock: object | None = None, path_encoding: str = "iso-8859-1" + ) -> None: ... + @property + def method(self) -> str: ... + @property + def protocol(self) -> str: ... + + @property + def body(self) -> str: ... + @body.setter + def body(self, value: _Body) -> None: ... + + @property + def url(self) -> str: ... + @property + def host(self) -> str: ... + def parse_querystring(self, qs: str) -> dict[str, list[str]]: ... + def parse_request_body(self, body: str) -> Any: ... # Any object can be returned if deserialization is successful + +class EmptyRequestHeaders(dict[str, str]): ... + +class HTTPrettyRequestEmpty: + method: str | None + url: str | None + body: str + headers: EmptyRequestHeaders + +class Entry(HttpBaseClass): + method: _HTTPMethod + uri: str + request: HTTPrettyRequest + body: _Body + status: int + streaming: bool + adding_headers: dict[str, str] + forcing_headers: dict[str, str] + def __init__( + self, + method: str, + uri: str, + body: _ResponseBody, + adding_headers: _Headers | None = None, + forcing_headers: _Headers | None = None, + status: int = 200, + streaming: bool = False, + **headers: str, + ) -> None: ... + def validate(self) -> None: ... + def normalize_headers(self, headers: _Headers) -> dict[str, str]: ... + def fill_filekind(self, fk: _WritableFileobj) -> None: ... + +class URIInfo(HttpBaseClass): + default_str_attrs: tuple[str, ...] + username: str + password: str + hostname: str + port: int + path: str + query: str + scheme: str + fragment: str + last_request: HTTPrettyRequest | None + def __init__( + self, + username: str = "", + password: str = "", + hostname: str = "", + port: int = 80, + path: str = "/", + query: str = "", + fragment: str = "", + scheme: str = "", + last_request: HTTPrettyRequest | None = None, + ) -> None: ... + def to_str(self, attrs: Iterable[str]) -> str: ... + def str_with_query(self) -> str: ... + def full_url(self, use_querystring: bool = True) -> str: ... + def get_full_domain(self) -> str: ... + @classmethod + def from_uri(cls, uri: str, entry: Entry) -> URIInfo: ... + +class URIMatcher: + regex: re.Pattern[str] | None + info: URIInfo | None + entries: list[Entry] + priority: int + uri: _URI + def __init__(self, uri: _URI, entries: Iterable[Entry], match_querystring: bool = False, priority: int = 0) -> None: ... + def matches(self, info: URIInfo) -> bool: ... + def get_next_entry(self, method: _HTTPMethod, info: URIInfo, request: HTTPrettyRequest) -> Entry: ... + +class httpretty(HttpBaseClass): + METHODS: tuple[_HTTPMethod, ...] + latest_requests: list[HTTPrettyRequest] + last_request: HTTPrettyRequest | HTTPrettyRequestEmpty + allow_net_connect: bool + @classmethod + def match_uriinfo(cls, info: URIInfo) -> tuple[Entry | None, list[str]]: ... + @classmethod + def match_https_hostname(cls, hostname: str) -> bool: ... + @classmethod + def match_http_address(cls, hostname: str, port: int) -> bool: ... + @classmethod + def record( + cls, + filename: str, + indentation: int = 4, + encoding: str = "utf-8", + verbose: bool = False, + allow_net_connect: bool = True, + # Passed to urllib3.PoolManager as kwargs, and connection pool's parameters have various types + pool_manager_params: Mapping[str, Any] | None = None, + ) -> AbstractContextManager[None]: ... + @classmethod + def playback(cls, filename: str, allow_net_connect: bool = True, verbose: bool = False) -> AbstractContextManager[None]: ... + @classmethod + def reset(cls) -> None: ... + @classmethod + def historify_request(cls, headers: str | bytes, body: _Body = "", sock: object | None = None) -> HTTPrettyRequest: ... + @classmethod + def register_uri( + cls, + method: str, + uri: _URI, + body: _ResponseBody = '{"message": "HTTPretty :)"}', + adding_headers: _Headers | None = None, + forcing_headers: _Headers | None = None, + status: int = 200, + responses: Iterable[Entry] | None = None, + match_querystring: bool = False, + priority: int = 0, + **headers: str, + ) -> None: ... + @classmethod + def Response( + cls, + body: _ResponseBody, + method: _HTTPMethod | None = None, + uri: str | None = None, + adding_headers: _Headers | None = None, + forcing_headers: _Headers | None = None, + status: int = 200, + streaming: bool = False, + **headers: str, + ) -> Entry: ... + @classmethod + def disable(cls) -> None: ... + @classmethod + def is_enabled(cls) -> bool: ... + @classmethod + def enable(cls, allow_net_connect: bool = True, verbose: bool = False) -> None: ... + +class httprettized: + allow_net_connect: bool + verbose: bool + def __init__(self, allow_net_connect: bool = True, verbose: bool = False) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +@overload +def httprettified(test: Callable[_P, _R]) -> Callable[_P, _R]: ... +@overload +def httprettified( + test: None = None, allow_net_connect: bool = True, verbose: bool = False +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... diff --git a/stubs/httpretty/httpretty/errors.pyi b/stubs/httpretty/httpretty/errors.pyi new file mode 100644 index 000000000000..4fb6e583a119 --- /dev/null +++ b/stubs/httpretty/httpretty/errors.pyi @@ -0,0 +1,4 @@ +class HTTPrettyError(Exception): ... + +class UnmockedError(HTTPrettyError): + def __init__(self, message: str = ..., request: object | None = None, address: object | None = None) -> None: ... diff --git a/stubs/httpretty/httpretty/http.pyi b/stubs/httpretty/httpretty/http.pyi new file mode 100644 index 000000000000..a3d2612cb381 --- /dev/null +++ b/stubs/httpretty/httpretty/http.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsLenAndGetItem +from typing import Final, Literal, TypeAlias +from typing_extensions import TypeVar + +_T = TypeVar("_T", str, bytes) +_HTTPMethod: TypeAlias = Literal["GET", "PUT", "POST", "DELETE", "HEAD", "PATCH", "OPTIONS", "CONNECT"] + +STATUSES: dict[int, str] + +class HttpBaseClass: + GET: Final = "GET" + PUT: Final = "PUT" + POST: Final = "POST" + DELETE: Final = "DELETE" + HEAD: Final = "HEAD" + PATCH: Final = "PATCH" + OPTIONS: Final = "OPTIONS" + CONNECT: Final = "CONNECT" + METHODS: tuple[_HTTPMethod, ...] + +def parse_requestline(s: str) -> tuple[str, str, str]: ... +def last_requestline(sent_data: SupportsLenAndGetItem[_T]) -> _T | None: ... diff --git a/stubs/httpretty/httpretty/utils.pyi b/stubs/httpretty/httpretty/utils.pyi new file mode 100644 index 000000000000..b38062b2ea81 --- /dev/null +++ b/stubs/httpretty/httpretty/utils.pyi @@ -0,0 +1,2 @@ +def utf8(s: str | bytes) -> bytes: ... +def decode_utf8(s: str | bytes) -> str: ... diff --git a/stubs/httpretty/httpretty/version.pyi b/stubs/httpretty/httpretty/version.pyi new file mode 100644 index 000000000000..669513528d4a --- /dev/null +++ b/stubs/httpretty/httpretty/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +version: Final[str] diff --git a/stubs/humanfriendly/@tests/requirements-stubtest.txt b/stubs/humanfriendly/@tests/requirements-stubtest.txt deleted file mode 100644 index 2d34645ab27d..000000000000 --- a/stubs/humanfriendly/@tests/requirements-stubtest.txt +++ /dev/null @@ -1,2 +0,0 @@ -docutils -mock \ No newline at end of file diff --git a/stubs/humanfriendly/@tests/stubtest_allowlist.txt b/stubs/humanfriendly/@tests/stubtest_allowlist.txt deleted file mode 100644 index deebbcb2c7cb..000000000000 --- a/stubs/humanfriendly/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,2 +0,0 @@ -humanfriendly.compat.StringIO.seek -humanfriendly.compat.StringIO.truncate diff --git a/stubs/humanfriendly/METADATA.toml b/stubs/humanfriendly/METADATA.toml deleted file mode 100644 index a6930073a3ac..000000000000 --- a/stubs/humanfriendly/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "9.2.*" diff --git a/stubs/humanfriendly/humanfriendly/__init__.pyi b/stubs/humanfriendly/humanfriendly/__init__.pyi deleted file mode 100644 index 6630b1a4ad84..000000000000 --- a/stubs/humanfriendly/humanfriendly/__init__.pyi +++ /dev/null @@ -1,49 +0,0 @@ -import datetime -from typing import Any, NamedTuple, Pattern - -class SizeUnit(NamedTuple): - divider: int - symbol: str - name: str - -class CombinedUnit(NamedTuple): - decimal: SizeUnit - binary: SizeUnit - -disk_size_units: Any -length_size_units: Any -time_units: Any - -def coerce_boolean(value: object) -> bool: ... -def coerce_pattern(value: str | Pattern[str], flags: int = ...) -> Pattern[str]: ... -def coerce_seconds(value: float | datetime.timedelta) -> float: ... -def format_size(num_bytes: float, keep_width: bool = ..., binary: bool = ...) -> str: ... -def parse_size(size: str, binary: bool = ...) -> int: ... -def format_length(num_metres: float, keep_width: bool = ...) -> str: ... -def parse_length(length: str) -> float: ... -def format_number(number: float, num_decimals: int = ...) -> str: ... -def round_number(count: float, keep_width: bool = ...) -> str: ... -def format_timespan(num_seconds: float | datetime.timedelta, detailed: bool = ..., max_units: int = ...) -> str: ... -def parse_timespan(timespan: str) -> float: ... -def parse_date(datestring: str) -> tuple[int, int, int, int, int, int]: ... -def format_path(pathname: str) -> str: ... -def parse_path(pathname: str) -> str: ... - -class Timer: - monotonic: bool - resumable: bool - start_time: float - total_time: float - def __init__(self, start_time: Any | None = ..., resumable: bool = ...) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - def sleep(self, seconds: float) -> None: ... - @property - def elapsed_time(self): ... - @property - def rounded(self): ... - -class InvalidDate(Exception): ... -class InvalidSize(Exception): ... -class InvalidLength(Exception): ... -class InvalidTimespan(Exception): ... diff --git a/stubs/humanfriendly/humanfriendly/case.pyi b/stubs/humanfriendly/humanfriendly/case.pyi deleted file mode 100644 index 2dc151869845..000000000000 --- a/stubs/humanfriendly/humanfriendly/case.pyi +++ /dev/null @@ -1,23 +0,0 @@ -import collections -from typing import Any - -from humanfriendly.compat import unicode - -class CaseInsensitiveDict(collections.OrderedDict): - def __init__(self, other: Any | None = ..., **kw) -> None: ... - def coerce_key(self, key): ... - @classmethod - def fromkeys(cls, iterable, value: Any | None = ...): ... - def get(self, key, default: Any | None = ...): ... - def pop(self, key, default: Any | None = ...): ... - def setdefault(self, key, default: Any | None = ...): ... - def update(self, other: Any | None = ..., **kw) -> None: ... # type: ignore[override] - def __contains__(self, key): ... - def __delitem__(self, key): ... - def __getitem__(self, key): ... - def __setitem__(self, key, value): ... - -class CaseInsensitiveKey(unicode): - def __new__(cls, value): ... - def __hash__(self): ... - def __eq__(self, other): ... diff --git a/stubs/humanfriendly/humanfriendly/cli.pyi b/stubs/humanfriendly/humanfriendly/cli.pyi deleted file mode 100644 index 200009fc324d..000000000000 --- a/stubs/humanfriendly/humanfriendly/cli.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -def main() -> None: ... -def run_command(command_line) -> None: ... -def print_formatted_length(value) -> None: ... -def print_formatted_number(value) -> None: ... -def print_formatted_size(value, binary) -> None: ... -def print_formatted_table(delimiter) -> None: ... -def print_formatted_timespan(value) -> None: ... -def print_parsed_length(value) -> None: ... -def print_parsed_size(value) -> None: ... -def demonstrate_ansi_formatting() -> None: ... -def demonstrate_256_colors(i, j, group: Any | None = ...) -> None: ... diff --git a/stubs/humanfriendly/humanfriendly/compat.pyi b/stubs/humanfriendly/humanfriendly/compat.pyi deleted file mode 100644 index 431dc344708c..000000000000 --- a/stubs/humanfriendly/humanfriendly/compat.pyi +++ /dev/null @@ -1,23 +0,0 @@ -import sys - -if sys.version_info >= (3, 0): - unicode = str - unichr = chr - basestring = str - interactive_prompt = input - from html.parser import HTMLParser as HTMLParser - from io import StringIO as StringIO -else: - unicode = unicode - unichr = unichr - basestring = basestring - interactive_prompt = raw_input - from StringIO import StringIO as StringIO - - from HTMLParser import HTMLParser as HTMLParser - -def coerce_string(value): ... -def is_string(value): ... -def is_unicode(value): ... -def on_macos(): ... -def on_windows(): ... diff --git a/stubs/humanfriendly/humanfriendly/decorators.pyi b/stubs/humanfriendly/humanfriendly/decorators.pyi deleted file mode 100644 index e961fd398726..000000000000 --- a/stubs/humanfriendly/humanfriendly/decorators.pyi +++ /dev/null @@ -1,3 +0,0 @@ -RESULTS_ATTRIBUTE: str - -def cached(function): ... diff --git a/stubs/humanfriendly/humanfriendly/deprecation.pyi b/stubs/humanfriendly/humanfriendly/deprecation.pyi deleted file mode 100644 index f384fa8aa6b9..000000000000 --- a/stubs/humanfriendly/humanfriendly/deprecation.pyi +++ /dev/null @@ -1,14 +0,0 @@ -import types -from typing import Any - -def define_aliases(module_name, **aliases) -> None: ... -def get_aliases(module_name): ... -def deprecated_args(*names): ... -def is_method(function): ... - -class DeprecationProxy(types.ModuleType): - module: Any - aliases: Any - def __init__(self, module, aliases) -> None: ... - def __getattr__(self, name): ... - def resolve(self, target): ... diff --git a/stubs/humanfriendly/humanfriendly/prompts.pyi b/stubs/humanfriendly/humanfriendly/prompts.pyi deleted file mode 100644 index 9bc7a4fb4a99..000000000000 --- a/stubs/humanfriendly/humanfriendly/prompts.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -MAX_ATTEMPTS: int -logger: Any - -def prompt_for_confirmation(question, default: Any | None = ..., padding: bool = ...): ... -def prompt_for_choice(choices, default: Any | None = ..., padding: bool = ...): ... -def prompt_for_input(question, default: Any | None = ..., padding: bool = ..., strip: bool = ...): ... -def prepare_prompt_text(prompt_text, **options): ... -def prepare_friendly_prompts() -> None: ... -def retry_limit(limit=...) -> None: ... - -class TooManyInvalidReplies(Exception): ... diff --git a/stubs/humanfriendly/humanfriendly/sphinx.pyi b/stubs/humanfriendly/humanfriendly/sphinx.pyi deleted file mode 100644 index eb6a6354362b..000000000000 --- a/stubs/humanfriendly/humanfriendly/sphinx.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -logger: Any - -def deprecation_note_callback(app, what, name, obj, options, lines) -> None: ... -def enable_deprecation_notes(app) -> None: ... -def enable_man_role(app) -> None: ... -def enable_pypi_role(app) -> None: ... -def enable_special_methods(app) -> None: ... -def enable_usage_formatting(app) -> None: ... -def man_role(role, rawtext, text, lineno, inliner, options=..., content=...): ... -def pypi_role(role, rawtext, text, lineno, inliner, options=..., content=...): ... -def setup(app): ... -def special_methods_callback(app, what, name, obj, skip, options): ... -def usage_message_callback(app, what, name, obj, options, lines) -> None: ... diff --git a/stubs/humanfriendly/humanfriendly/tables.pyi b/stubs/humanfriendly/humanfriendly/tables.pyi deleted file mode 100644 index 0b324b1f3233..000000000000 --- a/stubs/humanfriendly/humanfriendly/tables.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -def format_smart_table(data, column_names): ... -def format_pretty_table(data, column_names: Any | None = ..., horizontal_bar: str = ..., vertical_bar: str = ...): ... -def format_robust_table(data, column_names): ... -def format_rst_table(data, column_names: Any | None = ...): ... diff --git a/stubs/humanfriendly/humanfriendly/terminal/__init__.pyi b/stubs/humanfriendly/humanfriendly/terminal/__init__.pyi deleted file mode 100644 index 8c94e18c07f9..000000000000 --- a/stubs/humanfriendly/humanfriendly/terminal/__init__.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Any - -ANSI_CSI: str -ANSI_SGR: str -ANSI_ERASE_LINE: Any -ANSI_RESET: Any -ANSI_HIDE_CURSOR: Any -ANSI_SHOW_CURSOR: Any -ANSI_COLOR_CODES: Any -ANSI_TEXT_STYLES: Any -CLEAN_OUTPUT_PATTERN: Any -DEFAULT_LINES: int -DEFAULT_COLUMNS: int -DEFAULT_ENCODING: str -HIGHLIGHT_COLOR: Any - -def ansi_strip(text, readline_hints: bool = ...): ... -def ansi_style(**kw): ... -def ansi_width(text): ... -def ansi_wrap(text, **kw): ... -def auto_encode(stream, text, *args, **kw) -> None: ... -def clean_terminal_output(text): ... -def connected_to_terminal(stream: Any | None = ...): ... -def enable_ansi_support(): ... -def find_terminal_size(): ... -def find_terminal_size_using_ioctl(stream): ... -def find_terminal_size_using_stty(): ... -def get_pager_command(text: Any | None = ...): ... -def have_windows_native_ansi_support(): ... -def message(text, *args, **kw) -> None: ... -def output(text, *args, **kw) -> None: ... -def readline_strip(expr): ... -def readline_wrap(expr): ... -def show_pager(formatted_text, encoding=...) -> None: ... -def terminal_supports_colors(stream: Any | None = ...): ... -def usage(usage_text) -> None: ... -def warning(text, *args, **kw) -> None: ... diff --git a/stubs/humanfriendly/humanfriendly/terminal/html.pyi b/stubs/humanfriendly/humanfriendly/terminal/html.pyi deleted file mode 100644 index ad1907b1e605..000000000000 --- a/stubs/humanfriendly/humanfriendly/terminal/html.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any - -from humanfriendly.compat import HTMLParser - -def html_to_ansi(data, callback: Any | None = ...): ... - -class HTMLConverter(HTMLParser): - BLOCK_TAGS: Any - callback: Any - output: Any - def __init__(self, *args, **kw) -> None: ... - def __call__(self, data): ... - @property - def current_style(self): ... - stack: Any - def close(self) -> None: ... - def emit_style(self, style: Any | None = ...) -> None: ... - def handle_charref(self, value) -> None: ... - link_text: Any - def handle_data(self, data) -> None: ... - def handle_endtag(self, tag) -> None: ... - def handle_entityref(self, name) -> None: ... - link_url: Any - def handle_starttag(self, tag, attrs) -> None: ... - def normalize_url(self, url): ... - def parse_color(self, value): ... - def push_styles(self, **changes) -> None: ... - def render_url(self, url): ... - preformatted_text_level: int - def reset(self) -> None: ... - def urls_match(self, a, b): ... diff --git a/stubs/humanfriendly/humanfriendly/terminal/spinners.pyi b/stubs/humanfriendly/humanfriendly/terminal/spinners.pyi deleted file mode 100644 index 091ac7c27893..000000000000 --- a/stubs/humanfriendly/humanfriendly/terminal/spinners.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Any - -GLYPHS: Any -MINIMUM_INTERVAL: float - -class Spinner: - interactive: Any - interval: Any - label: Any - states: Any - stream: Any - timer: Any - total: Any - counter: int - last_update: int - def __init__(self, **options) -> None: ... - def step(self, progress: int = ..., label: Any | None = ...) -> None: ... - def sleep(self) -> None: ... - def clear(self) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - -class AutomaticSpinner: - label: Any - show_time: Any - shutdown_event: Any - subprocess: Any - def __init__(self, label, show_time: bool = ...) -> None: ... - def __enter__(self) -> None: ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... diff --git a/stubs/humanfriendly/humanfriendly/testing.pyi b/stubs/humanfriendly/humanfriendly/testing.pyi deleted file mode 100644 index 8da7c31787e0..000000000000 --- a/stubs/humanfriendly/humanfriendly/testing.pyi +++ /dev/null @@ -1,86 +0,0 @@ -import unittest -from typing import Any - -from humanfriendly.compat import StringIO - -def configure_logging(log_level=...) -> None: ... -def make_dirs(pathname) -> None: ... -def retry(func, timeout: int = ..., exc_type=...): ... -def run_cli(entry_point, *arguments, **options): ... -def skip_on_raise(*exc_types): ... -def touch(filename) -> None: ... - -class CallableTimedOut(Exception): ... - -class ContextManager: - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - -class PatchedAttribute(ContextManager): - object_to_patch: Any - attribute_to_patch: Any - patched_value: Any - original_value: Any - def __init__(self, obj, name, value) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - -class PatchedItem(ContextManager): - object_to_patch: Any - item_to_patch: Any - patched_value: Any - original_value: Any - def __init__(self, obj, item, value) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - -class TemporaryDirectory(ContextManager): - mkdtemp_options: Any - temporary_directory: Any - def __init__(self, **options) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - -class MockedHomeDirectory(PatchedItem, TemporaryDirectory): - def __init__(self) -> None: ... - patched_value: Any - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - -class CustomSearchPath(PatchedItem, TemporaryDirectory): - isolated_search_path: Any - def __init__(self, isolated: bool = ...) -> None: ... - patched_value: Any - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - @property - def current_search_path(self): ... - -class MockedProgram(CustomSearchPath): - program_name: Any - program_returncode: Any - program_script: Any - program_signal_file: Any - def __init__(self, name, returncode: int = ..., script: Any | None = ...) -> None: ... - def __enter__(self): ... - def __exit__(self, *args, **kw): ... - -class CaptureOutput(ContextManager): - stdin: Any - stdout: Any - stderr: Any - patched_attributes: Any - def __init__(self, merged: bool = ..., input: str = ..., enabled: bool = ...) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type: Any | None = ..., exc_value: Any | None = ..., traceback: Any | None = ...) -> None: ... - def get_lines(self): ... - def get_text(self): ... - def getvalue(self): ... - -class CaptureBuffer(StringIO): - def get_lines(self): ... - def get_text(self): ... - -class TestCase(unittest.TestCase): - def __init__(self, *args, **kw) -> None: ... - def setUp(self, log_level=...) -> None: ... diff --git a/stubs/humanfriendly/humanfriendly/text.pyi b/stubs/humanfriendly/humanfriendly/text.pyi deleted file mode 100644 index 9c58cff1401d..000000000000 --- a/stubs/humanfriendly/humanfriendly/text.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -def compact(text, *args, **kw): ... -def compact_empty_lines(text): ... -def concatenate(items, conjunction: str = ..., serial_comma: bool = ...): ... -def dedent(text, *args, **kw): ... -def format(text, *args, **kw): ... -def generate_slug(text, delimiter: str = ...): ... -def is_empty_line(text): ... -def join_lines(text): ... -def pluralize(count, singular, plural: Any | None = ...): ... -def pluralize_raw(count, singular, plural: Any | None = ...): ... -def random_string(length=..., characters=...): ... -def split(text, delimiter: str = ...): ... -def split_paragraphs(text): ... -def tokenize(text): ... -def trim_empty_lines(text): ... diff --git a/stubs/humanfriendly/humanfriendly/usage.pyi b/stubs/humanfriendly/humanfriendly/usage.pyi deleted file mode 100644 index 9ebfb108f70a..000000000000 --- a/stubs/humanfriendly/humanfriendly/usage.pyi +++ /dev/null @@ -1,7 +0,0 @@ -USAGE_MARKER: str - -def format_usage(usage_text): ... -def find_meta_variables(usage_text): ... -def parse_usage(text): ... -def render_usage(text): ... -def inject_usage(module_name) -> None: ... diff --git a/stubs/hvac/METADATA.toml b/stubs/hvac/METADATA.toml new file mode 100644 index 000000000000..fe7a9ba835b4 --- /dev/null +++ b/stubs/hvac/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.4.*" +upstream-repository = "https://github.com/hvac/hvac" +dependencies = ["requests>=2.34.0"] diff --git a/stubs/hvac/hvac/__init__.pyi b/stubs/hvac/hvac/__init__.pyi new file mode 100644 index 000000000000..cc4d88cd6958 --- /dev/null +++ b/stubs/hvac/hvac/__init__.pyi @@ -0,0 +1,3 @@ +from hvac.v1 import Client as Client + +__all__ = ("Client",) diff --git a/stubs/hvac/hvac/adapters.pyi b/stubs/hvac/hvac/adapters.pyi new file mode 100644 index 000000000000..3bd1b3e0d981 --- /dev/null +++ b/stubs/hvac/hvac/adapters.pyi @@ -0,0 +1,66 @@ +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from typing import Any, Generic, TypeVar, type_check_only +from typing_extensions import Self + +from requests import Response, Session + +_R = TypeVar("_R") + +class Adapter(Generic[_R], metaclass=ABCMeta): + @classmethod + def from_adapter(cls, adapter: Adapter[_R]) -> Self: ... + base_uri: str + token: str | None + namespace: str | None + session: Session + allow_redirects: bool + ignore_exceptions: bool + strict_http: bool + request_header: bool + def __init__( + self, + base_uri: str = "http://localhost:8200", + token: str | None = None, + cert: tuple[str, str] | None = None, + verify: bool = True, + timeout: int = 30, + proxies: Mapping[str, str] | None = None, + allow_redirects: bool = True, + session: Session | None = None, + namespace: str | None = None, + ignore_exceptions: bool = False, + strict_http: bool = False, + request_header: bool = True, + ) -> None: ... + @staticmethod + def urljoin(*args: object) -> str: ... + def close(self) -> None: ... + def get(self, url: str, **kwargs: Any) -> _R: ... + def post(self, url: str, **kwargs: Any) -> _R: ... + def put(self, url: str, **kwargs: Any) -> _R: ... + def delete(self, url: str, **kwargs: Any) -> _R: ... + def list(self, url: str, **kwargs: Any) -> _R: ... + def head(self, url: str, **kwargs: Any) -> _R: ... + def login(self, url: str, use_token: bool = True, **kwargs: Any) -> Response: ... + @abstractmethod + def get_login_token(self, response: _R) -> str: ... + @abstractmethod + def request( + self, method, url: str, headers: Mapping[str, str] | None = None, raise_exception: bool = True, **kwargs: Any + ) -> _R: ... + +@type_check_only +class _GenericRawAdapter(Adapter[_R]): + def get_login_token(self, response: _R) -> str: ... + def request( + self, method: str, url: str, headers: Mapping[str, str] | None = None, raise_exception: bool = True, **kwargs: Any + ) -> _R: ... + +class RawAdapter(_GenericRawAdapter[Response]): ... + +class JSONAdapter(_GenericRawAdapter[Response | dict[Any, Any]]): + def get_login_token(self, response: Response | dict[Any, Any]) -> str: ... + def request(self, *args: Any, **kwargs: Any) -> Response | dict[Any, Any]: ... + +Request = RawAdapter diff --git a/stubs/hvac/hvac/api/__init__.pyi b/stubs/hvac/hvac/api/__init__.pyi new file mode 100644 index 000000000000..f794e4d52c59 --- /dev/null +++ b/stubs/hvac/hvac/api/__init__.pyi @@ -0,0 +1,7 @@ +from hvac.api.auth_methods import AuthMethods as AuthMethods +from hvac.api.secrets_engines import SecretsEngines as SecretsEngines +from hvac.api.system_backend import SystemBackend as SystemBackend +from hvac.api.vault_api_base import VaultApiBase as VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory as VaultApiCategory + +__all__ = ("AuthMethods", "SecretsEngines", "SystemBackend", "VaultApiBase", "VaultApiCategory") diff --git a/stubs/hvac/hvac/api/auth_methods/__init__.pyi b/stubs/hvac/hvac/api/auth_methods/__init__.pyi new file mode 100644 index 000000000000..7d3e80ff560b --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/__init__.pyi @@ -0,0 +1,40 @@ +from hvac.api.auth_methods.approle import AppRole as AppRole +from hvac.api.auth_methods.aws import Aws as Aws +from hvac.api.auth_methods.azure import Azure as Azure +from hvac.api.auth_methods.cert import Cert as Cert +from hvac.api.auth_methods.gcp import Gcp as Gcp +from hvac.api.auth_methods.github import Github as Github +from hvac.api.auth_methods.jwt import JWT as JWT +from hvac.api.auth_methods.kubernetes import Kubernetes as Kubernetes +from hvac.api.auth_methods.ldap import Ldap as Ldap +from hvac.api.auth_methods.legacy_mfa import LegacyMfa as LegacyMfa +from hvac.api.auth_methods.oidc import OIDC as OIDC +from hvac.api.auth_methods.okta import Okta as Okta +from hvac.api.auth_methods.radius import Radius as Radius +from hvac.api.auth_methods.token import Token as Token +from hvac.api.auth_methods.userpass import Userpass as Userpass +from hvac.api.vault_api_base import VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory + +__all__ = ( + "AuthMethods", + "AppRole", + "Azure", + "Gcp", + "Github", + "JWT", + "Kubernetes", + "Ldap", + "Userpass", + "LegacyMfa", + "OIDC", + "Okta", + "Radius", + "Token", + "Aws", + "Cert", +) + +class AuthMethods(VaultApiCategory): + implemented_classes: list[type[VaultApiBase]] + unimplemented_classes: list[str] diff --git a/stubs/hvac/hvac/api/auth_methods/approle.pyi b/stubs/hvac/hvac/api/auth_methods/approle.pyi new file mode 100644 index 000000000000..530e11f8bf0e --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/approle.pyi @@ -0,0 +1,39 @@ +from hvac.api.vault_api_base import VaultApiBase + +class AppRole(VaultApiBase): + def create_or_update_approle( + self, + role_name, + bind_secret_id=None, + secret_id_bound_cidrs=None, + secret_id_num_uses=None, + secret_id_ttl=None, + enable_local_secret_ids=None, + token_ttl=None, + token_max_ttl=None, + token_policies=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_type=None, + mount_point="approle", + ): ... + def list_roles(self, mount_point="approle"): ... + def read_role(self, role_name, mount_point="approle"): ... + def delete_role(self, role_name, mount_point="approle"): ... + def read_role_id(self, role_name, mount_point="approle"): ... + def update_role_id(self, role_name, role_id, mount_point="approle"): ... + def generate_secret_id( + self, role_name, metadata=None, cidr_list=None, token_bound_cidrs=None, mount_point="approle", wrap_ttl=None + ): ... + def create_custom_secret_id( + self, role_name, secret_id, metadata=None, cidr_list=None, token_bound_cidrs=None, mount_point="approle", wrap_ttl=None + ): ... + def read_secret_id(self, role_name, secret_id, mount_point="approle"): ... + def destroy_secret_id(self, role_name, secret_id, mount_point="approle"): ... + def list_secret_id_accessors(self, role_name, mount_point="approle"): ... + def read_secret_id_accessor(self, role_name, secret_id_accessor, mount_point="approle"): ... + def destroy_secret_id_accessor(self, role_name, secret_id_accessor, mount_point="approle"): ... + def login(self, role_id, secret_id=None, use_token: bool = True, mount_point="approle"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/aws.pyi b/stubs/hvac/hvac/api/auth_methods/aws.pyi new file mode 100644 index 000000000000..7298a79a1cc9 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/aws.pyi @@ -0,0 +1,103 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class Aws(VaultApiBase): + def configure( + self, + max_retries=None, + access_key=None, + secret_key=None, + endpoint=None, + iam_endpoint=None, + sts_endpoint=None, + iam_server_id_header_value=None, + mount_point: str = "aws", + sts_region: str | None = None, + ): ... + def read_config(self, mount_point: str = "aws"): ... + def delete_config(self, mount_point: str = "aws"): ... + def configure_identity_integration( + self, + iam_alias=None, + ec2_alias=None, + mount_point: str = "aws", + iam_metadata: str | list[str] | None = None, + ec2_metadata: str | list[str] | None = None, + ): ... + def read_identity_integration(self, mount_point: str = "aws"): ... + def create_certificate_configuration(self, cert_name, aws_public_cert, document_type=None, mount_point: str = "aws"): ... + def read_certificate_configuration(self, cert_name, mount_point: str = "aws"): ... + def delete_certificate_configuration(self, cert_name, mount_point: str = "aws"): ... + def list_certificate_configurations(self, mount_point: str = "aws"): ... + def create_sts_role(self, account_id, sts_role, mount_point: str = "aws"): ... + def read_sts_role(self, account_id, mount_point: str = "aws"): ... + def list_sts_roles(self, mount_point: str = "aws"): ... + def delete_sts_role(self, account_id, mount_point: str = "aws"): ... + def configure_identity_whitelist_tidy(self, safety_buffer=None, disable_periodic_tidy=None, mount_point: str = "aws"): ... + def read_identity_whitelist_tidy(self, mount_point: str = "aws"): ... + def delete_identity_whitelist_tidy(self, mount_point: str = "aws"): ... + def configure_role_tag_blacklist_tidy(self, safety_buffer=None, disable_periodic_tidy=None, mount_point: str = "aws"): ... + def read_role_tag_blacklist_tidy(self, mount_point: str = "aws"): ... + def delete_role_tag_blacklist_tidy(self, mount_point: str = "aws"): ... + def create_role( + self, + role, + auth_type=None, + bound_ami_id=None, + bound_account_id=None, + bound_region=None, + bound_vpc_id=None, + bound_subnet_id=None, + bound_iam_role_arn=None, + bound_iam_instance_profile_arn=None, + bound_ec2_instance_id=None, + role_tag=None, + bound_iam_principal_arn=None, + inferred_entity_type=None, + inferred_aws_region=None, + resolve_aws_unique_ids=None, + ttl=None, + max_ttl=None, + period=None, + policies=None, + allow_instance_migration=None, + disallow_reauthentication=None, + mount_point: str = "aws", + ): ... + def read_role(self, role, mount_point: str = "aws"): ... + def list_roles(self, mount_point: str = "aws"): ... + def delete_role(self, role, mount_point: str = "aws"): ... + def create_role_tags( + self, + role, + policies=None, + max_ttl=None, + instance_id=None, + allow_instance_migration=None, + disallow_reauthentication=None, + mount_point: str = "aws", + ): ... + def iam_login( + self, + access_key, + secret_key, + session_token=None, + header_value=None, + role=None, + use_token: bool = True, + region: str = "us-east-1", + mount_point: str = "aws", + ): ... + def ec2_login(self, pkcs7, nonce=None, role=None, use_token: bool = True, mount_point: str = "aws"): ... + def place_role_tags_in_blacklist(self, role_tag, mount_point: str = "aws"): ... + def read_role_tag_blacklist(self, role_tag, mount_point: str = "aws"): ... + def list_blacklist_tags(self, mount_point: str = "aws"): ... + def delete_blacklist_tags(self, role_tag, mount_point: str = "aws"): ... + def tidy_blacklist_tags(self, safety_buffer: str = "72h", mount_point: str = "aws"): ... + def read_identity_whitelist(self, instance_id, mount_point: str = "aws"): ... + def list_identity_whitelist(self, mount_point: str = "aws"): ... + def delete_identity_whitelist_entries(self, instance_id, mount_point: str = "aws"): ... + def tidy_identity_whitelist_entries(self, safety_buffer: str = "72h", mount_point: str = "aws"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/azure.pyi b/stubs/hvac/hvac/api/auth_methods/azure.pyi new file mode 100644 index 000000000000..ffa918c02e17 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/azure.pyi @@ -0,0 +1,42 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +logger: logging.Logger + +class Azure(VaultApiBase): + def configure(self, tenant_id, resource, environment=None, client_id=None, client_secret=None, mount_point="azure"): ... + def read_config(self, mount_point="azure"): ... + def delete_config(self, mount_point="azure"): ... + def create_role( + self, + name, + policies=None, + ttl=None, + max_ttl=None, + period=None, + bound_service_principal_ids=None, + bound_group_ids=None, + bound_locations=None, + bound_subscription_ids=None, + bound_resource_groups=None, + bound_scale_sets=None, + num_uses=None, + mount_point="azure", + ): ... + def read_role(self, name, mount_point="azure"): ... + def list_roles(self, mount_point="azure"): ... + def delete_role(self, name, mount_point="azure"): ... + def login( + self, + role, + jwt, + subscription_id=None, + resource_group_name=None, + vm_name=None, + vmss_name=None, + use_token: bool = True, + mount_point="azure", + ): ... diff --git a/stubs/hvac/hvac/api/auth_methods/cert.pyi b/stubs/hvac/hvac/api/auth_methods/cert.pyi new file mode 100644 index 000000000000..9fdfc8701a7d --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/cert.pyi @@ -0,0 +1,41 @@ +from hvac.api.vault_api_base import VaultApiBase + +class Cert(VaultApiBase): + def create_ca_certificate_role( + self, + name, + certificate: str = "", + certificate_file: str = "", + allowed_common_names: str = "", + allowed_dns_sans: str = "", + allowed_email_sans: str = "", + allowed_uri_sans: str = "", + allowed_organizational_units: str = "", + required_extensions: str = "", + display_name: str = "", + token_ttl: int = 0, + token_max_ttl: int = 0, + token_policies=[], + token_bound_cidrs=[], + token_explicit_max_ttl: int = 0, + token_no_default_policy: bool = False, + token_num_uses: int = 0, + token_period: int = 0, + token_type: str = "", + mount_point: str = "cert", + ): ... + def read_ca_certificate_role(self, name, mount_point: str = "cert"): ... + def list_certificate_roles(self, mount_point: str = "cert"): ... + def delete_certificate_role(self, name, mount_point: str = "cert"): ... + def configure_tls_certificate(self, mount_point: str = "cert", disable_binding: bool = False): ... + def login( + self, + name: str = "", + cacert: bool = False, + cert_pem: str = "", + key_pem: str = "", + mount_point: str = "cert", + use_token: bool = True, + ): ... + + class CertificateAuthError(Exception): ... diff --git a/stubs/hvac/hvac/api/auth_methods/gcp.pyi b/stubs/hvac/hvac/api/auth_methods/gcp.pyi new file mode 100644 index 000000000000..8ebb0e03faf4 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/gcp.pyi @@ -0,0 +1,38 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +logger: logging.Logger + +class Gcp(VaultApiBase): + def configure( + self, credentials=None, google_certs_endpoint="https://www.googleapis.com/oauth2/v3/certs", mount_point="gcp" + ): ... + def read_config(self, mount_point="gcp"): ... + def delete_config(self, mount_point="gcp"): ... + def create_role( + self, + name, + role_type, + project_id, + ttl=None, + max_ttl=None, + period=None, + policies=None, + bound_service_accounts=None, + max_jwt_exp=None, + allow_gce_inference=None, + bound_zones=None, + bound_regions=None, + bound_instance_groups=None, + bound_labels=None, + mount_point="gcp", + ): ... + def edit_service_accounts_on_iam_role(self, name, add=None, remove=None, mount_point="gcp"): ... + def edit_labels_on_gce_role(self, name, add=None, remove=None, mount_point="gcp"): ... + def read_role(self, name, mount_point="gcp"): ... + def list_roles(self, mount_point="gcp"): ... + def delete_role(self, role, mount_point="gcp"): ... + def login(self, role, jwt, use_token: bool = True, mount_point="gcp"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/github.pyi b/stubs/hvac/hvac/api/auth_methods/github.pyi new file mode 100644 index 000000000000..3005c03d599a --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/github.pyi @@ -0,0 +1,12 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Github(VaultApiBase): + def configure(self, organization, base_url=None, ttl=None, max_ttl=None, mount_point="github"): ... + def read_configuration(self, mount_point="github"): ... + def map_team(self, team_name, policies=None, mount_point="github"): ... + def read_team_mapping(self, team_name, mount_point="github"): ... + def map_user(self, user_name, policies=None, mount_point="github"): ... + def read_user_mapping(self, user_name, mount_point="github"): ... + def login(self, token, use_token: bool = True, mount_point="github"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/jwt.pyi b/stubs/hvac/hvac/api/auth_methods/jwt.pyi new file mode 100644 index 000000000000..9db9396fe388 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/jwt.pyi @@ -0,0 +1,59 @@ +from hvac.api.vault_api_base import VaultApiBase + +class JWT(VaultApiBase): + DEFAULT_PATH: str + def resolve_path(self, path): ... + def configure( + self, + oidc_discovery_url=None, + oidc_discovery_ca_pem=None, + oidc_client_id=None, + oidc_client_secret=None, + oidc_response_mode=None, + oidc_response_types=None, + jwks_url=None, + jwks_ca_pem=None, + jwt_validation_pubkeys=None, + bound_issuer=None, + jwt_supported_algs=None, + default_role=None, + provider_config=None, + path: str | None = None, + namespace_in_state: bool | None = None, + ): ... + def read_config(self, path=None): ... + def create_role( + self, + name, + user_claim, + allowed_redirect_uris, + role_type: str = "jwt", + bound_audiences=None, + clock_skew_leeway=None, + expiration_leeway=None, + not_before_leeway=None, + bound_subject=None, + bound_claims=None, + groups_claim=None, + claim_mappings=None, + oidc_scopes=None, + bound_claims_type: str = "string", + verbose_oidc_logging: bool = False, + token_ttl=None, + token_max_ttl=None, + token_policies=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_type=None, + path=None, + user_claim_json_pointer=None, + ): ... + def read_role(self, name, path=None): ... + def list_roles(self, path=None): ... + def delete_role(self, name, path=None): ... + def oidc_authorization_url_request(self, role, redirect_uri, path=None): ... + def oidc_callback(self, state, nonce, code, path=None): ... + def jwt_login(self, role, jwt, use_token: bool = True, path=None): ... diff --git a/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi b/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi new file mode 100644 index 000000000000..15d674291da8 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi @@ -0,0 +1,34 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Kubernetes(VaultApiBase): + def configure( + self, + kubernetes_host: str, + kubernetes_ca_cert: str | None = None, + token_reviewer_jwt: str | None = None, + pem_keys: list[str] | None = None, + issuer: str | None = None, + mount_point: str = "kubernetes", + disable_local_ca_jwt: bool = False, + ): ... + def read_config(self, mount_point: str = "kubernetes"): ... + def create_role( + self, + name: str, + bound_service_account_names: list[str] | str, + bound_service_account_namespaces: list[str] | str, + ttl: str | None = None, + max_ttl: str | None = None, + period: str | None = None, + policies: list[str] | str | None = None, + token_type: str = "", + mount_point: str = "kubernetes", + alias_name_source: str | None = None, + audience: str | None = None, + ): ... + def read_role(self, name: str, mount_point: str = "kubernetes"): ... + def list_roles(self, mount_point: str = "kubernetes"): ... + def delete_role(self, name: str, mount_point: str = "kubernetes"): ... + def login(self, role: str, jwt: str, use_token: bool = True, mount_point: str = "kubernetes"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/ldap.pyi b/stubs/hvac/hvac/api/auth_methods/ldap.pyi new file mode 100644 index 000000000000..f2d19fc58cb6 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/ldap.pyi @@ -0,0 +1,56 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Ldap(VaultApiBase): + def configure( + self, + userdn=None, + groupdn=None, + url=None, + case_sensitive_names=None, + starttls=None, + tls_min_version=None, + tls_max_version=None, + insecure_tls=None, + certificate=None, + binddn=None, + bindpass=None, + userattr=None, + discoverdn=None, + deny_null_bind: bool = True, + upndomain=None, + groupfilter=None, + groupattr=None, + use_token_groups=None, + token_ttl=None, + token_max_ttl=None, + mount_point="ldap", + *, + anonymous_group_search=None, + client_tls_cert=None, + client_tls_key=None, + connection_timeout=None, + dereference_aliases=None, + max_page_size=None, + request_timeout=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_policies=None, + token_type=None, + userfilter=None, + username_as_alias=None, + ): ... + def read_configuration(self, mount_point="ldap"): ... + def create_or_update_group(self, name, policies=None, mount_point="ldap"): ... + def list_groups(self, mount_point="ldap"): ... + def read_group(self, name, mount_point="ldap"): ... + def delete_group(self, name, mount_point="ldap"): ... + def create_or_update_user(self, username, policies=None, groups=None, mount_point="ldap"): ... + def list_users(self, mount_point="ldap"): ... + def read_user(self, username, mount_point="ldap"): ... + def delete_user(self, username, mount_point="ldap"): ... + def login(self, username, password, use_token: bool = True, mount_point="ldap"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi b/stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi new file mode 100644 index 000000000000..68f56a952845 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi @@ -0,0 +1,11 @@ +from hvac.api.vault_api_base import VaultApiBase + +SUPPORTED_MFA_TYPES: list[str] +SUPPORTED_AUTH_METHODS: list[str] + +class LegacyMfa(VaultApiBase): + def configure(self, mount_point, mfa_type: str = "duo", force: bool = False): ... + def read_configuration(self, mount_point): ... + def configure_duo_access(self, mount_point, host, integration_key, secret_key): ... + def configure_duo_behavior(self, mount_point, push_info=None, user_agent=None, username_format: str = "%s"): ... + def read_duo_behavior_configuration(self, mount_point): ... diff --git a/stubs/hvac/hvac/api/auth_methods/oidc.pyi b/stubs/hvac/hvac/api/auth_methods/oidc.pyi new file mode 100644 index 000000000000..c53113665a6e --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/oidc.pyi @@ -0,0 +1,33 @@ +from hvac.api.auth_methods.jwt import JWT + +class OIDC(JWT): + DEFAULT_PATH: str + def create_role( + self, + name, + user_claim, + allowed_redirect_uris, + role_type: str = "oidc", + bound_audiences=None, + clock_skew_leeway=None, + expiration_leeway=None, + not_before_leeway=None, + bound_subject=None, + bound_claims=None, + groups_claim=None, + claim_mappings=None, + oidc_scopes=None, + bound_claims_type: str = "string", + verbose_oidc_logging: bool = False, + token_ttl=None, + token_max_ttl=None, + token_policies=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_type=None, + path=None, + user_claim_json_pointer=None, + ) -> None: ... diff --git a/stubs/hvac/hvac/api/auth_methods/okta.pyi b/stubs/hvac/hvac/api/auth_methods/okta.pyi new file mode 100644 index 000000000000..d48dfbf6de1f --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/okta.pyi @@ -0,0 +1,18 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Okta(VaultApiBase): + def configure( + self, org_name, api_token=None, base_url=None, ttl=None, max_ttl=None, bypass_okta_mfa=None, mount_point="okta" + ): ... + def read_config(self, mount_point="okta"): ... + def list_users(self, mount_point="okta"): ... + def register_user(self, username, groups=None, policies=None, mount_point="okta"): ... + def read_user(self, username, mount_point="okta"): ... + def delete_user(self, username, mount_point="okta"): ... + def list_groups(self, mount_point="okta"): ... + def register_group(self, name, policies=None, mount_point="okta"): ... + def read_group(self, name, mount_point="okta"): ... + def delete_group(self, name, mount_point="okta"): ... + def login(self, username, password, use_token: bool = True, mount_point="okta"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/radius.pyi b/stubs/hvac/hvac/api/auth_methods/radius.pyi new file mode 100644 index 000000000000..1db73c5bef9f --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/radius.pyi @@ -0,0 +1,14 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Radius(VaultApiBase): + def configure( + self, host, secret, port=None, unregistered_user_policies=None, dial_timeout=None, nas_port=None, mount_point="radius" + ): ... + def read_configuration(self, mount_point="radius"): ... + def register_user(self, username, policies=None, mount_point="radius"): ... + def list_users(self, mount_point="radius"): ... + def read_user(self, username, mount_point="radius"): ... + def delete_user(self, username, mount_point="radius"): ... + def login(self, username, password, use_token: bool = True, mount_point="radius"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/token.pyi b/stubs/hvac/hvac/api/auth_methods/token.pyi new file mode 100644 index 000000000000..5500be2fcab1 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/token.pyi @@ -0,0 +1,70 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Token(VaultApiBase): + def create( + self, + id=None, + role_name=None, + policies=None, + meta=None, + no_parent: bool = False, + no_default_policy: bool = False, + renewable: bool = True, + ttl=None, + type=None, + explicit_max_ttl=None, + display_name: str = "token", + num_uses: int = 0, + period=None, + entity_alias=None, + wrap_ttl=None, + mount_point="token", + ): ... + def create_orphan( + self, + id=None, + role_name=None, + policies=None, + meta=None, + no_default_policy: bool = False, + renewable: bool = True, + ttl=None, + type=None, + explicit_max_ttl=None, + display_name: str = "token", + num_uses: int = 0, + period=None, + entity_alias=None, + wrap_ttl=None, + mount_point="token", + ): ... + def list_accessors(self, mount_point="token"): ... + def lookup(self, token, mount_point="token"): ... + def lookup_self(self, mount_point="token"): ... + def lookup_accessor(self, accessor, mount_point="token"): ... + def renew(self, token, increment=None, wrap_ttl=None, mount_point="token"): ... + def renew_self(self, increment=None, wrap_ttl=None, mount_point="token"): ... + def renew_accessor(self, accessor, increment=None, wrap_ttl=None, mount_point="token"): ... + def revoke(self, token, mount_point="token"): ... + def revoke_self(self, mount_point="token"): ... + def revoke_accessor(self, accessor, mount_point="token"): ... + def revoke_and_orphan_children(self, token, mount_point="token"): ... + def read_role(self, role_name, mount_point="token"): ... + def list_roles(self, mount_point="token"): ... + def create_or_update_role( + self, + role_name, + allowed_policies=None, + disallowed_policies=None, + orphan: bool = False, + renewable: bool = True, + path_suffix=None, + allowed_entity_aliases=None, + mount_point="token", + token_period=None, + token_explicit_max_ttl=None, + ): ... + def delete_role(self, role_name, mount_point="token"): ... + def tidy(self, mount_point="token"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/userpass.pyi b/stubs/hvac/hvac/api/auth_methods/userpass.pyi new file mode 100644 index 000000000000..d8991c0b9f2f --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/userpass.pyi @@ -0,0 +1,11 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Userpass(VaultApiBase): + def create_or_update_user(self, username, password=None, policies=None, mount_point="userpass", **kwargs): ... + def list_user(self, mount_point="userpass"): ... + def read_user(self, username, mount_point="userpass"): ... + def delete_user(self, username, mount_point="userpass"): ... + def update_password_on_user(self, username, password, mount_point="userpass"): ... + def login(self, username, password, use_token: bool = True, mount_point="userpass"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/__init__.pyi b/stubs/hvac/hvac/api/secrets_engines/__init__.pyi new file mode 100644 index 000000000000..00e078835556 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/__init__.pyi @@ -0,0 +1,59 @@ +from hvac.api.secrets_engines.active_directory import ActiveDirectory as ActiveDirectory +from hvac.api.secrets_engines.aws import Aws as Aws +from hvac.api.secrets_engines.azure import Azure as Azure +from hvac.api.secrets_engines.consul import Consul as Consul +from hvac.api.secrets_engines.database import Database as Database +from hvac.api.secrets_engines.gcp import Gcp as Gcp +from hvac.api.secrets_engines.identity import Identity as Identity +from hvac.api.secrets_engines.kv import Kv as Kv +from hvac.api.secrets_engines.kv_v1 import KvV1 as KvV1 +from hvac.api.secrets_engines.kv_v2 import KvV2 as KvV2 +from hvac.api.secrets_engines.ldap import Ldap as Ldap +from hvac.api.secrets_engines.pki import Pki as Pki +from hvac.api.secrets_engines.rabbitmq import RabbitMQ as RabbitMQ +from hvac.api.secrets_engines.ssh import Ssh as Ssh +from hvac.api.secrets_engines.transform import Transform as Transform +from hvac.api.secrets_engines.transit import Transit as Transit +from hvac.api.vault_api_base import VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory + +__all__ = ( + "Aws", + "Azure", + "Gcp", + "ActiveDirectory", + "Identity", + "Kv", + "KvV1", + "KvV2", + "Ldap", + "Pki", + "Transform", + "Transit", + "SecretsEngines", + "Database", + "RabbitMQ", + "Ssh", +) + +class SecretsEngines(VaultApiCategory): + implemented_classes: list[type[VaultApiBase]] + unimplemented_classes: list[str] + + # The following attributes are dynamically created at runtime by + # VaultApiCategory based on implemented_classes. + # These explicit assignments make them visible for static type checkers. + aws: Aws + azure: Azure + gcp: Gcp + activedirectory: ActiveDirectory + identity: Identity + kv: Kv + ldap: Ldap + pki: Pki + transform: Transform + transit: Transit + database: Database + consul: Consul + rabbitmq: RabbitMQ + ssh: Ssh diff --git a/stubs/hvac/hvac/api/secrets_engines/active_directory.pyi b/stubs/hvac/hvac/api/secrets_engines/active_directory.pyi new file mode 100644 index 000000000000..f7d527c75232 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/active_directory.pyi @@ -0,0 +1,24 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class ActiveDirectory(VaultApiBase): + def configure( + self, + binddn=None, + bindpass=None, + url=None, + userdn=None, + upndomain=None, + ttl=None, + max_ttl=None, + mount_point="ad", + *args, + **kwargs, + ): ... + def read_config(self, mount_point="ad"): ... + def create_or_update_role(self, name, service_account_name=None, ttl=None, mount_point="ad"): ... + def read_role(self, name, mount_point="ad"): ... + def list_roles(self, mount_point="ad"): ... + def delete_role(self, name, mount_point="ad"): ... + def generate_credentials(self, name, mount_point="ad"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/aws.pyi b/stubs/hvac/hvac/api/secrets_engines/aws.pyi new file mode 100644 index 000000000000..373d55a4e0e5 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/aws.pyi @@ -0,0 +1,28 @@ +from hvac.api.vault_api_base import VaultApiBase + +class Aws(VaultApiBase): + def configure_root_iam_credentials( + self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None, max_retries=None, mount_point="aws" + ): ... + def rotate_root_iam_credentials(self, mount_point="aws"): ... + def configure_lease(self, lease, lease_max, mount_point="aws"): ... + def read_lease_config(self, mount_point="aws"): ... + def create_or_update_role( + self, + name, + credential_type, + policy_document=None, + default_sts_ttl=None, + max_sts_ttl=None, + role_arns=None, + policy_arns=None, + legacy_params: bool = False, + iam_tags=None, + mount_point="aws", + ): ... + def read_role(self, name, mount_point="aws"): ... + def list_roles(self, mount_point="aws"): ... + def delete_role(self, name, mount_point="aws"): ... + def generate_credentials( + self, name, role_arn=None, ttl=None, endpoint: str = "creds", mount_point="aws", role_session_name=None + ): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/azure.pyi b/stubs/hvac/hvac/api/secrets_engines/azure.pyi new file mode 100644 index 000000000000..5ba4e4eac2dd --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/azure.pyi @@ -0,0 +1,13 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Azure(VaultApiBase): + def configure( + self, subscription_id, tenant_id, client_id=None, client_secret=None, environment=None, mount_point="azure" + ): ... + def read_config(self, mount_point="azure"): ... + def delete_config(self, mount_point="azure"): ... + def create_or_update_role(self, name, azure_roles, ttl=None, max_ttl=None, mount_point="azure"): ... + def list_roles(self, mount_point="azure"): ... + def generate_credentials(self, name, mount_point="azure"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/consul.pyi b/stubs/hvac/hvac/api/secrets_engines/consul.pyi new file mode 100644 index 000000000000..0a27a6da6b70 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/consul.pyi @@ -0,0 +1,13 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Consul(VaultApiBase): + def configure_access(self, address, token, scheme=None, mount_point="consul"): ... + def create_or_update_role( + self, name, policy=None, policies=None, token_type=None, local=None, ttl=None, max_ttl=None, mount_point="consul" + ): ... + def read_role(self, name, mount_point="consul"): ... + def list_roles(self, mount_point="consul"): ... + def delete_role(self, name, mount_point="consul"): ... + def generate_credentials(self, name, mount_point="consul"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/database.pyi b/stubs/hvac/hvac/api/secrets_engines/database.pyi new file mode 100644 index 000000000000..ff88fe47d9e6 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/database.pyi @@ -0,0 +1,45 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Database(VaultApiBase): + def configure( + self, + name, + plugin_name, + verify_connection=None, + allowed_roles=None, + root_rotation_statements=None, + mount_point="database", + *args, + **kwargs, + ): ... + def rotate_root_credentials(self, name, mount_point="database"): ... + def read_connection(self, name, mount_point="database"): ... + def list_connections(self, mount_point="database"): ... + def delete_connection(self, name, mount_point="database"): ... + def reset_connection(self, name, mount_point="database"): ... + def create_role( + self, + name, + db_name, + creation_statements, + default_ttl=None, + max_ttl=None, + revocation_statements=None, + rollback_statements=None, + renew_statements=None, + mount_point="database", + ): ... + def create_static_role( + self, name, db_name, username, rotation_statements, rotation_period: int = 86400, mount_point="database" + ): ... + def read_role(self, name, mount_point="database"): ... + def read_static_role(self, name, mount_point="database"): ... + def list_roles(self, mount_point="database"): ... + def list_static_roles(self, mount_point="database"): ... + def delete_role(self, name, mount_point="database"): ... + def delete_static_role(self, name, mount_point="database"): ... + def generate_credentials(self, name, mount_point="database"): ... + def get_static_credentials(self, name, mount_point="database"): ... + def rotate_static_role_credentials(self, name, mount_point="database"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/gcp.pyi b/stubs/hvac/hvac/api/secrets_engines/gcp.pyi new file mode 100644 index 000000000000..8ccc89bbf6e3 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/gcp.pyi @@ -0,0 +1,46 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Gcp(VaultApiBase): + def configure(self, credentials=None, ttl=None, max_ttl=None, mount_point="gcp"): ... + def rotate_root_credentials(self, mount_point="gcp"): ... + def read_config(self, mount_point="gcp"): ... + def create_or_update_roleset(self, name, project, bindings, secret_type=None, token_scopes=None, mount_point="gcp"): ... + def rotate_roleset_account(self, name, mount_point="gcp"): ... + def rotate_roleset_account_key(self, name, mount_point="gcp"): ... + def read_roleset(self, name, mount_point="gcp"): ... + def list_rolesets(self, mount_point="gcp"): ... + def delete_roleset(self, name, mount_point="gcp"): ... + def generate_oauth2_access_token(self, roleset, mount_point="gcp"): ... + def generate_service_account_key( + self, + roleset, + key_algorithm: str = "KEY_ALG_RSA_2048", + key_type: str = "TYPE_GOOGLE_CREDENTIALS_FILE", + method: str = "POST", + mount_point="gcp", + ): ... + def create_or_update_static_account( + self, name, service_account_email, bindings=None, secret_type=None, token_scopes=None, mount_point="gcp" + ): ... + def rotate_static_account_key(self, name, mount_point="gcp"): ... + def read_static_account(self, name, mount_point="gcp"): ... + def list_static_accounts(self, mount_point="gcp"): ... + def delete_static_account(self, name, mount_point="gcp"): ... + def generate_static_account_oauth2_access_token(self, name, mount_point="gcp"): ... + def generate_static_account_service_account_key( + self, + name, + key_algorithm: str = "KEY_ALG_RSA_2048", + key_type: str = "TYPE_GOOGLE_CREDENTIALS_FILE", + method: str = "POST", + mount_point="gcp", + ): ... + def create_or_update_impersonated_account( + self, name, service_account_email, token_scopes=None, ttl=None, mount_point="gcp" + ): ... + def read_impersonated_account(self, name, mount_point="gcp"): ... + def list_impersonated_accounts(self, mount_point="gcp"): ... + def delete_impersonated_account(self, name, mount_point="gcp"): ... + def generate_impersonated_account_oauth2_access_token(self, name, mount_point="gcp"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/identity.pyi b/stubs/hvac/hvac/api/secrets_engines/identity.pyi new file mode 100644 index 000000000000..7adc58901956 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/identity.pyi @@ -0,0 +1,106 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class Identity(VaultApiBase): + def create_or_update_entity( + self, name, entity_id=None, metadata=None, policies=None, disabled=None, mount_point: str = "identity" + ): ... + def create_or_update_entity_by_name( + self, name, metadata=None, policies=None, disabled=None, mount_point: str = "identity" + ): ... + def read_entity(self, entity_id, mount_point: str = "identity"): ... + def read_entity_by_name(self, name, mount_point: str = "identity"): ... + def update_entity(self, entity_id, name=None, metadata=None, policies=None, disabled=None, mount_point: str = "identity"): ... + def delete_entity(self, entity_id, mount_point: str = "identity"): ... + def delete_entity_by_name(self, name, mount_point: str = "identity"): ... + def list_entities(self, method: str = "LIST", mount_point: str = "identity"): ... + def list_entities_by_name(self, method: str = "LIST", mount_point: str = "identity"): ... + def merge_entities( + self, from_entity_ids, to_entity_id, force=None, mount_point: str = "identity", conflicting_alias_ids_to_keep=None + ): ... + def create_or_update_entity_alias(self, name, canonical_id, mount_accessor, alias_id=None, mount_point: str = "identity"): ... + def read_entity_alias(self, alias_id, mount_point: str = "identity"): ... + def update_entity_alias(self, alias_id, name, canonical_id, mount_accessor, mount_point: str = "identity"): ... + def list_entity_aliases(self, method: str = "LIST", mount_point: str = "identity"): ... + def delete_entity_alias(self, alias_id, mount_point: str = "identity"): ... + @staticmethod + def validate_member_id_params_for_group_type(group_type, params, member_group_ids, member_entity_ids): ... + def create_or_update_group( + self, + name, + group_id=None, + group_type: str = "internal", + metadata=None, + policies=None, + member_group_ids=None, + member_entity_ids=None, + mount_point: str = "identity", + ): ... + def read_group(self, group_id, mount_point: str = "identity"): ... + def update_group( + self, + group_id, + name, + group_type: str = "internal", + metadata=None, + policies=None, + member_group_ids=None, + member_entity_ids=None, + mount_point: str = "identity", + ): ... + def delete_group(self, group_id, mount_point: str = "identity"): ... + def list_groups(self, method: str = "LIST", mount_point: str = "identity"): ... + def list_groups_by_name(self, method: str = "LIST", mount_point: str = "identity"): ... + def create_or_update_group_by_name( + self, + name, + group_type: str = "internal", + metadata=None, + policies=None, + member_group_ids=None, + member_entity_ids=None, + mount_point: str = "identity", + ): ... + def read_group_by_name(self, name, mount_point: str = "identity"): ... + def delete_group_by_name(self, name, mount_point: str = "identity"): ... + def create_or_update_group_alias( + self, name, alias_id=None, mount_accessor=None, canonical_id=None, mount_point: str = "identity" + ): ... + def update_group_alias(self, entity_id, name, mount_accessor=None, canonical_id=None, mount_point="identity"): ... + def read_group_alias(self, alias_id, mount_point: str = "identity"): ... + def delete_group_alias(self, entity_id, mount_point: str = "identity"): ... + def list_group_aliases(self, method: str = "LIST", mount_point: str = "identity"): ... + def lookup_entity( + self, name=None, entity_id=None, alias_id=None, alias_name=None, alias_mount_accessor=None, mount_point: str = "identity" + ): ... + def lookup_group( + self, name=None, group_id=None, alias_id=None, alias_name=None, alias_mount_accessor=None, mount_point: str = "identity" + ): ... + def configure_tokens_backend(self, issuer=None, mount_point: str = "identity"): ... + def read_tokens_backend_configuration(self, mount_point: str = "identity"): ... + def create_named_key( + self, + name, + rotation_period: str = "24h", + verification_ttl: str = "24h", + allowed_client_ids=None, + algorithm: str = "RS256", + mount_point: str = "identity", + ): ... + def read_named_key(self, name, mount_point: str = "identity"): ... + def delete_named_key(self, name, mount_point: str = "identity"): ... + def list_named_keys(self, mount_point: str = "identity"): ... + def rotate_named_key(self, name, verification_ttl, mount_point: str = "identity"): ... + def create_or_update_role( + self, name, key, template=None, client_id=None, ttl: str = "24h", mount_point: str = "identity" + ): ... + def read_role(self, name, mount_point: str = "identity"): ... + def delete_role(self, name, mount_point: str = "identity"): ... + def list_roles(self, mount_point: str = "identity"): ... + def generate_signed_id_token(self, name, mount_point: str = "identity"): ... + def introspect_signed_id_token(self, token, client_id=None, mount_point: str = "identity"): ... + def read_well_known_configurations(self, mount_point: str = "identity"): ... + def read_active_public_keys(self, mount_point: str = "identity"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/kv.pyi b/stubs/hvac/hvac/api/secrets_engines/kv.pyi new file mode 100644 index 000000000000..5c0ec3a0c7ca --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/kv.pyi @@ -0,0 +1,23 @@ +import logging +from typing import Any + +from hvac.adapters import Adapter +from hvac.api.secrets_engines import KvV1, KvV2 +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class Kv(VaultApiBase): + allowed_kv_versions: list[str] + def __init__(self, adapter: Adapter[Any], default_kv_version: str = "2") -> None: ... + @property + def v1(self) -> KvV1: ... + @property + def v2(self) -> KvV2: ... + + @property + def default_kv_version(self) -> str: ... + @default_kv_version.setter + def default_kv_version(self, default_kv_version: str) -> None: ... + + def __getattr__(self, item: str): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi b/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi new file mode 100644 index 000000000000..68117f2bdddb --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi @@ -0,0 +1,13 @@ +from typing import Any + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class KvV1(VaultApiBase): + def read_secret(self, path: str, mount_point: str = "secret"): ... + def list_secrets(self, path: str, mount_point: str = "secret"): ... + def create_or_update_secret( + self, path: str, secret: dict[str, Any], method: str | None = None, mount_point: str = "secret" + ): ... + def delete_secret(self, path: str, mount_point: str = "secret"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi b/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi new file mode 100644 index 000000000000..6e838ffd152f --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi @@ -0,0 +1,37 @@ +from typing import Any + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class KvV2(VaultApiBase): + def configure( + self, + max_versions: int = 10, + cas_required: bool | None = None, + delete_version_after: str = "0s", + mount_point: str = "secret", + ): ... + def read_configuration(self, mount_point: str = "secret"): ... + def read_secret(self, path: str, mount_point: str = "secret", raise_on_deleted_version: bool | None = None): ... + def read_secret_version( + self, path: str, version: int | None = None, mount_point: str = "secret", raise_on_deleted_version: bool | None = None + ): ... + def create_or_update_secret(self, path: str, secret: dict[str, Any], cas: int | None = None, mount_point: str = "secret"): ... + def patch(self, path: str, secret: dict[str, str], mount_point: str = "secret"): ... + def delete_latest_version_of_secret(self, path: str, mount_point: str = "secret"): ... + def delete_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def undelete_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def destroy_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def list_secrets(self, path: str, mount_point: str = "secret"): ... + def read_secret_metadata(self, path: str, mount_point: str = "secret"): ... + def update_metadata( + self, + path: str, + max_versions: int | None = None, + cas_required: bool | None = None, + delete_version_after: str = "0s", + mount_point: str = "secret", + custom_metadata: dict[str, str] | None = None, + ): ... + def delete_metadata_and_all_versions(self, path: str, mount_point: str = "secret"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/ldap.pyi b/stubs/hvac/hvac/api/secrets_engines/ldap.pyi new file mode 100644 index 000000000000..7a17162bf8c1 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/ldap.pyi @@ -0,0 +1,41 @@ +from typing import Final + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: Final = "ldap" + +class Ldap(VaultApiBase): + def configure( + self, + binddn: str | None = None, + bindpass: str | None = None, + url: str | None = None, + password_policy: str | None = None, + schema: str | None = None, + userdn: str | None = None, + userattr: str | None = None, + upndomain: str | None = None, + connection_timeout: int | str | None = None, + request_timeout: int | str | None = None, + starttls: bool | None = None, + insecure_tls: bool | None = None, + certificate: str | None = None, + client_tls_cert: str | None = None, + client_tls_key: str | None = None, + mount_point: str = "ldap", + ): ... + def read_config(self, mount_point: str = "ldap"): ... + def rotate_root(self, mount_point: str = "ldap"): ... + def create_or_update_static_role( + self, + name: str, + username: str | None = None, + dn: str | None = None, + rotation_period: str | None = None, + mount_point: str = "ldap", + ): ... + def read_static_role(self, name: str, mount_point: str = "ldap"): ... + def list_static_roles(self, mount_point: str = "ldap"): ... + def delete_static_role(self, name: str, mount_point: str = "ldap"): ... + def generate_static_credentials(self, name: str, mount_point: str = "ldap"): ... + def rotate_static_credentials(self, name: str, mount_point: str = "ldap"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/pki.pyi b/stubs/hvac/hvac/api/secrets_engines/pki.pyi new file mode 100644 index 000000000000..f8ea43398709 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/pki.pyi @@ -0,0 +1,36 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Pki(VaultApiBase): + def read_ca_certificate(self, mount_point="pki"): ... + def read_ca_certificate_chain(self, mount_point="pki"): ... + def read_certificate(self, serial, mount_point="pki"): ... + def list_certificates(self, mount_point="pki"): ... + def submit_ca_information(self, pem_bundle, mount_point="pki"): ... + def read_crl_configuration(self, mount_point="pki"): ... + def set_crl_configuration(self, expiry=None, disable=None, extra_params=None, mount_point="pki"): ... + def read_urls(self, mount_point="pki"): ... + def set_urls(self, params, mount_point="pki"): ... + def read_crl(self, mount_point="pki"): ... + def rotate_crl(self, mount_point="pki"): ... + def generate_intermediate(self, type, common_name, extra_params=None, mount_point="pki", wrap_ttl=None): ... + def set_signed_intermediate(self, certificate, mount_point="pki"): ... + def generate_certificate(self, name, common_name, extra_params=None, mount_point="pki", wrap_ttl=None): ... + def revoke_certificate(self, serial_number, mount_point="pki"): ... + def create_or_update_role(self, name, extra_params=None, mount_point="pki"): ... + def read_role(self, name, mount_point="pki"): ... + def list_roles(self, mount_point="pki"): ... + def delete_role(self, name, mount_point="pki"): ... + def generate_root(self, type, common_name, extra_params=None, mount_point="pki", wrap_ttl=None): ... + def delete_root(self, mount_point="pki"): ... + def sign_intermediate(self, csr, common_name, extra_params=None, mount_point="pki"): ... + def sign_self_issued(self, certificate, mount_point="pki"): ... + def sign_certificate(self, name, csr, common_name, extra_params=None, mount_point="pki"): ... + def sign_verbatim(self, csr, name: bool = False, extra_params=None, mount_point="pki"): ... + def tidy(self, extra_params=None, mount_point="pki"): ... + def read_issuer(self, issuer_ref, mount_point="pki"): ... + def list_issuers(self, mount_point="pki"): ... + def update_issuer(self, issuer_ref, extra_params=None, mount_point="pki"): ... + def revoke_issuer(self, issuer_ref, mount_point="pki"): ... + def delete_issuer(self, issuer_ref, mount_point="pki"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi b/stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi new file mode 100644 index 000000000000..6c77c2ed6590 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi @@ -0,0 +1,18 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class RabbitMQ(VaultApiBase): + def configure( + self, + connection_uri: str = "", + username: str = "", + password: str = "", + verify_connection: bool = True, + mount_point="rabbitmq", + ): ... + def configure_lease(self, ttl, max_ttl, mount_point="rabbitmq"): ... + def create_role(self, name, tags: str = "", vhosts: str = "", vhost_topics: str = "", mount_point: str = "rabbitmq"): ... + def read_role(self, name, mount_point="rabbitmq"): ... + def delete_role(self, name, mount_point="rabbitmq"): ... + def generate_credentials(self, name, mount_point="rabbitmq"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/ssh.pyi b/stubs/hvac/hvac/api/secrets_engines/ssh.pyi new file mode 100644 index 000000000000..b7b7f3d3305d --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/ssh.pyi @@ -0,0 +1,71 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Ssh(VaultApiBase): + def create_or_update_key(self, name: str = "", key: str = "", mount_point: str = "ssh"): ... + def delete_key(self, name: str = "", mount_point: str = "ssh"): ... + def create_role( + self, + name: str = "", + key: str = "", + admin_user: str = "", + default_user: str = "", + cidr_list: str = "", + exclude_cidr_list: str = "", + port: int = 22, + key_type: str = "", + key_bits: int = 1024, + install_script: str = "", + allowed_users: str = "", + allowed_users_template: str = "", + allowed_domains: str = "", + key_option_specs: str = "", + ttl: str = "", + max_ttl: str = "", + allowed_critical_options: str = "", + allowed_extensions: str = "", + default_critical_options=None, + default_extensions=None, + allow_user_certificates: str = "", + allow_host_certificates: bool = False, + allow_bare_domains: bool = False, + allow_subdomains: bool = False, + allow_user_key_ids: bool = False, + key_id_format: str = "", + allowed_user_key_lengths=None, + algorithm_signer: str = "", + mount_point="ssh", + ): ... + def read_role(self, name: str = "", mount_point: str = "ssh"): ... + def list_roles(self, mount_point: str = "ssh"): ... + def delete_role(self, name: str = "", mount_point: str = "ssh"): ... + def list_zeroaddress_roles(self, mount_point: str = "ssh"): ... + def configure_zeroaddress_roles(self, roles: str = "", mount_point: str = "ssh"): ... + def delete_zeroaddress_role(self, mount_point: str = "ssh"): ... + def generate_ssh_credentials(self, name: str = "", username: str = "", ip: str = "", mount_point: str = "ssh"): ... + def list_roles_by_ip(self, ip: str = "", mount_point: str = "ssh"): ... + def verify_ssh_otp(self, otp, mount_point="ssh"): ... + def submit_ca_information( + self, + private_key: str = "", + public_key: str = "", + generate_signing_key: bool = True, + key_type: str = "ssh-rsa", + key_bits: int = 0, + mount_point: str = "ssh", + ): ... + def delete_ca_information(self, mount_point: str = "ssh"): ... + def read_public_key(self, mount_point: str = "ssh"): ... + def sign_ssh_key( + self, + name: str = "", + public_key: str = "", + ttl: str = "", + valid_principals: str = "", + cert_type: str = "user", + key_id: str = "", + critical_options=None, + extensions=None, + mount_point: str = "ssh", + ): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/transform.pyi b/stubs/hvac/hvac/api/secrets_engines/transform.pyi new file mode 100644 index 000000000000..39aff82b3f50 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/transform.pyi @@ -0,0 +1,79 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Transform(VaultApiBase): + def create_or_update_role(self, name, transformations, mount_point: str = "transform"): ... + def read_role(self, name, mount_point: str = "transform"): ... + def list_roles(self, mount_point: str = "transform"): ... + def delete_role(self, name, mount_point: str = "transform"): ... + def create_or_update_transformation( + self, + name, + transform_type, + template, + tweak_source: str = "supplied", + masking_character: str = "*", + allowed_roles=None, + mount_point: str = "transform", + ): ... + def create_or_update_fpe_transformation( + self, name, template, tweak_source: str = "supplied", allowed_roles=None, mount_point: str = "transform" + ): ... + def create_or_update_masking_transformation( + self, name, template, masking_character: str = "*", allowed_roles=None, mount_point: str = "transform" + ): ... + def create_or_update_tokenization_transformation( + self, + name, + max_ttl: int = 0, + mapping_mode: str = "default", + allowed_roles=None, + stores=None, + mount_point: str = "transform", + ): ... + def read_transformation(self, name, mount_point: str = "transform"): ... + def list_transformations(self, mount_point: str = "transform"): ... + def delete_transformation(self, name, mount_point: str = "transform"): ... + def create_or_update_template(self, name, template_type, pattern, alphabet, mount_point: str = "transform"): ... + def read_template(self, name, mount_point: str = "transform"): ... + def list_templates(self, mount_point: str = "transform"): ... + def delete_template(self, name, mount_point: str = "transform"): ... + def create_or_update_alphabet(self, name, alphabet, mount_point: str = "transform"): ... + def read_alphabet(self, name, mount_point: str = "transform"): ... + def list_alphabets(self, mount_point: str = "transform"): ... + def delete_alphabet(self, name, mount_point: str = "transform"): ... + def create_or_update_tokenization_store( + self, + name, + driver, + connection_string, + username=None, + password=None, + type: str = "sql", + supported_transformations=None, + schema: str = "public", + max_open_connections: int = 4, + max_idle_connections: int = 4, + max_connection_lifetime: int = 0, + mount_point: str = "transform", + ): ... + def encode( + self, role_name, value=None, transformation=None, tweak=None, batch_input=None, mount_point: str = "transform" + ): ... + def decode( + self, role_name, value=None, transformation=None, tweak=None, batch_input=None, mount_point: str = "transform" + ): ... + def validate_token(self, role_name, value, transformation, batch_input=None, mount_point: str = "transform"): ... + def check_tokenization(self, role_name, value, transformation, batch_input=None, mount_point: str = "transform"): ... + def retrieve_token_metadata(self, role_name, value, transformation, batch_input=None, mount_point: str = "transform"): ... + def snapshot_tokenization_state(self, name, limit: int = 1000, continuation: str = "", mount_point: str = "transform"): ... + def restore_tokenization_state(self, name, values, mount_point: str = "transform"): ... + def export_decoded_tokenization_state( + self, name, limit: int = 1000, continuation: str = "", mount_point: str = "transform" + ): ... + def rotate_tokenization_key(self, transform_name, mount_point: str = "transform"): ... + def update_tokenization_key_config(self, transform_name, min_decryption_version, mount_point: str = "transform"): ... + def list_tokenization_key_configuration(self, mount_point: str = "transform"): ... + def read_tokenization_key_configuration(self, transform_name, mount_point: str = "transform"): ... + def trim_tokenization_key_version(self, transform_name, min_available_version, mount_point: str = "transform"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/transit.pyi b/stubs/hvac/hvac/api/secrets_engines/transit.pyi new file mode 100644 index 000000000000..86a2335ec4d6 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/transit.pyi @@ -0,0 +1,93 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Transit(VaultApiBase): + def create_key( + self, + name, + convergent_encryption=None, + derived=None, + exportable=None, + allow_plaintext_backup=None, + key_type=None, + mount_point="transit", + auto_rotate_period=None, + ): ... + def read_key(self, name, mount_point="transit"): ... + def list_keys(self, mount_point="transit"): ... + def delete_key(self, name, mount_point="transit"): ... + def update_key_configuration( + self, + name, + min_decryption_version=None, + min_encryption_version=None, + deletion_allowed=None, + exportable=None, + allow_plaintext_backup=None, + mount_point="transit", + auto_rotate_period=None, + ): ... + def rotate_key(self, name, mount_point="transit"): ... + def export_key(self, name, key_type, version=None, mount_point="transit"): ... + def encrypt_data( + self, + name, + plaintext=None, + context=None, + key_version=None, + nonce=None, + batch_input=None, + type=None, + convergent_encryption=None, + mount_point: str = "transit", + associated_data: str | None = None, + ): ... + def decrypt_data( + self, + name, + ciphertext=None, + context=None, + nonce=None, + batch_input=None, + mount_point: str = "transit", + associated_data: str | None = None, + ): ... + def rewrap_data( + self, name, ciphertext, context=None, key_version=None, nonce=None, batch_input=None, mount_point="transit" + ): ... + def generate_data_key(self, name, key_type, context=None, nonce=None, bits=None, mount_point="transit"): ... + def generate_random_bytes(self, n_bytes=None, output_format=None, mount_point="transit"): ... + def hash_data(self, hash_input, algorithm=None, output_format=None, mount_point="transit"): ... + def generate_hmac(self, name, hash_input, key_version=None, algorithm=None, mount_point="transit"): ... + def sign_data( + self, + name, + hash_input=None, + key_version=None, + hash_algorithm=None, + context=None, + prehashed=None, + signature_algorithm=None, + marshaling_algorithm=None, + salt_length=None, + mount_point="transit", + batch_input=None, + ): ... + def verify_signed_data( + self, + name, + hash_input, + signature=None, + hmac=None, + hash_algorithm=None, + context=None, + prehashed=None, + signature_algorithm=None, + salt_length=None, + marshaling_algorithm=None, + mount_point="transit", + ): ... + def backup_key(self, name, mount_point="transit"): ... + def restore_key(self, backup, name=None, force=None, mount_point="transit"): ... + def trim_key(self, name, min_version, mount_point="transit"): ... diff --git a/stubs/hvac/hvac/api/system_backend/__init__.pyi b/stubs/hvac/hvac/api/system_backend/__init__.pyi new file mode 100644 index 000000000000..c4066c28c71b --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/__init__.pyi @@ -0,0 +1,62 @@ +from hvac.api.system_backend.audit import Audit as Audit +from hvac.api.system_backend.auth import Auth as Auth +from hvac.api.system_backend.capabilities import Capabilities as Capabilities +from hvac.api.system_backend.health import Health as Health +from hvac.api.system_backend.init import Init as Init +from hvac.api.system_backend.key import Key as Key +from hvac.api.system_backend.leader import Leader as Leader +from hvac.api.system_backend.lease import Lease as Lease +from hvac.api.system_backend.mount import Mount as Mount +from hvac.api.system_backend.namespace import Namespace as Namespace +from hvac.api.system_backend.policies import Policies as Policies +from hvac.api.system_backend.policy import Policy as Policy +from hvac.api.system_backend.quota import Quota as Quota +from hvac.api.system_backend.raft import Raft as Raft +from hvac.api.system_backend.seal import Seal as Seal +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin as SystemBackendMixin +from hvac.api.system_backend.wrapping import Wrapping as Wrapping +from hvac.api.vault_api_base import VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory + +__all__ = ( + "Audit", + "Auth", + "Capabilities", + "Health", + "Init", + "Key", + "Leader", + "Lease", + "Mount", + "Namespace", + "Policies", + "Policy", + "Quota", + "Raft", + "Seal", + "SystemBackend", + "SystemBackendMixin", + "Wrapping", +) + +class SystemBackend( + VaultApiCategory, + Audit, + Auth, + Capabilities, + Health, + Init, + Key, + Leader, + Lease, + Mount, + Namespace, + Policies, + Policy, + Quota, + Raft, + Seal, + Wrapping, +): + implemented_classes: list[type[VaultApiBase]] + unimplemented_classes: list[str] diff --git a/stubs/hvac/hvac/api/system_backend/audit.pyi b/stubs/hvac/hvac/api/system_backend/audit.pyi new file mode 100644 index 000000000000..99dea810178f --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/audit.pyi @@ -0,0 +1,7 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Audit(SystemBackendMixin): + def list_enabled_audit_devices(self): ... + def enable_audit_device(self, device_type, description=None, options=None, path=None, local=None): ... + def disable_audit_device(self, path): ... + def calculate_hash(self, path, input_to_hash): ... diff --git a/stubs/hvac/hvac/api/system_backend/auth.pyi b/stubs/hvac/hvac/api/system_backend/auth.pyi new file mode 100644 index 000000000000..1534a1c71499 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/auth.pyi @@ -0,0 +1,21 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Auth(SystemBackendMixin): + def list_auth_methods(self): ... + def enable_auth_method( + self, method_type, description=None, config=None, plugin_name=None, local: bool = False, path=None, **kwargs + ): ... + def disable_auth_method(self, path): ... + def read_auth_method_tuning(self, path): ... + def tune_auth_method( + self, + path, + default_lease_ttl=None, + max_lease_ttl=None, + description=None, + audit_non_hmac_request_keys=None, + audit_non_hmac_response_keys=None, + listing_visibility=None, + passthrough_request_headers=None, + **kwargs, + ): ... diff --git a/stubs/hvac/hvac/api/system_backend/capabilities.pyi b/stubs/hvac/hvac/api/system_backend/capabilities.pyi new file mode 100644 index 000000000000..398f822a5870 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/capabilities.pyi @@ -0,0 +1,4 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Capabilities(SystemBackendMixin): + def get_capabilities(self, paths, token=None, accessor=None): ... diff --git a/stubs/hvac/hvac/api/system_backend/health.pyi b/stubs/hvac/hvac/api/system_backend/health.pyi new file mode 100644 index 000000000000..9e252742786e --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/health.pyi @@ -0,0 +1,14 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Health(SystemBackendMixin): + def read_health_status( + self, + standby_ok=None, + active_code=None, + standby_code=None, + dr_secondary_code=None, + performance_standby_code=None, + sealed_code=None, + uninit_code=None, + method: str = "HEAD", + ): ... diff --git a/stubs/hvac/hvac/api/system_backend/init.pyi b/stubs/hvac/hvac/api/system_backend/init.pyi new file mode 100644 index 000000000000..bd96164557d3 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/init.pyi @@ -0,0 +1,16 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Init(SystemBackendMixin): + def read_init_status(self): ... + def is_initialized(self): ... + def initialize( + self, + secret_shares=None, + secret_threshold=None, + pgp_keys=None, + root_token_pgp_key=None, + stored_shares=None, + recovery_shares=None, + recovery_threshold=None, + recovery_pgp_keys=None, + ): ... diff --git a/stubs/hvac/hvac/api/system_backend/key.pyi b/stubs/hvac/hvac/api/system_backend/key.pyi new file mode 100644 index 000000000000..ada0db2177f4 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/key.pyi @@ -0,0 +1,27 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Key(SystemBackendMixin): + def read_root_generation_progress(self): ... + def start_root_token_generation(self, otp=None, pgp_key=None): ... + def generate_root(self, key, nonce): ... + def cancel_root_generation(self): ... + def get_encryption_key_status(self): ... + def rotate_encryption_key(self): ... + def read_rekey_progress(self, recovery_key: bool = False): ... + def start_rekey( + self, + secret_shares: int = 5, + secret_threshold: int = 3, + pgp_keys=None, + backup: bool = False, + require_verification: bool = False, + recovery_key: bool = False, + ): ... + def cancel_rekey(self, recovery_key: bool = False): ... + def rekey(self, key, nonce=None, recovery_key: bool = False): ... + def rekey_multi(self, keys, nonce=None, recovery_key: bool = False): ... + def read_backup_keys(self, recovery_key: bool = False): ... + def cancel_rekey_verify(self): ... + def rekey_verify(self, key, nonce): ... + def rekey_verify_multi(self, keys, nonce): ... + def read_rekey_verify_progress(self): ... diff --git a/stubs/hvac/hvac/api/system_backend/leader.pyi b/stubs/hvac/hvac/api/system_backend/leader.pyi new file mode 100644 index 000000000000..c46711c1b204 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/leader.pyi @@ -0,0 +1,5 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Leader(SystemBackendMixin): + def read_leader_status(self): ... + def step_down(self): ... diff --git a/stubs/hvac/hvac/api/system_backend/lease.pyi b/stubs/hvac/hvac/api/system_backend/lease.pyi new file mode 100644 index 000000000000..9fd68b3f5f9d --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/lease.pyi @@ -0,0 +1,9 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Lease(SystemBackendMixin): + def read_lease(self, lease_id): ... + def list_leases(self, prefix): ... + def renew_lease(self, lease_id, increment=None): ... + def revoke_lease(self, lease_id): ... + def revoke_prefix(self, prefix): ... + def revoke_force(self, prefix): ... diff --git a/stubs/hvac/hvac/api/system_backend/mount.pyi b/stubs/hvac/hvac/api/system_backend/mount.pyi new file mode 100644 index 000000000000..54e83c1af5d7 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/mount.pyi @@ -0,0 +1,34 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Mount(SystemBackendMixin): + def list_mounted_secrets_engines(self): ... + def retrieve_mount_option(self, mount_point, option_name, default_value=None): ... + def enable_secrets_engine( + self, + backend_type, + path=None, + description=None, + config=None, + plugin_name=None, + options=None, + local: bool = False, + seal_wrap: bool = False, + **kwargs, + ): ... + def disable_secrets_engine(self, path): ... + def read_mount_configuration(self, path): ... + def tune_mount_configuration( + self, + path, + default_lease_ttl=None, + max_lease_ttl=None, + description=None, + audit_non_hmac_request_keys=None, + audit_non_hmac_response_keys=None, + listing_visibility=None, + passthrough_request_headers=None, + options=None, + force_no_cache=None, + **kwargs, + ): ... + def move_backend(self, from_path, to_path): ... diff --git a/stubs/hvac/hvac/api/system_backend/namespace.pyi b/stubs/hvac/hvac/api/system_backend/namespace.pyi new file mode 100644 index 000000000000..68e86561c8c5 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/namespace.pyi @@ -0,0 +1,6 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Namespace(SystemBackendMixin): + def create_namespace(self, path): ... + def list_namespaces(self): ... + def delete_namespace(self, path): ... diff --git a/stubs/hvac/hvac/api/system_backend/policies.pyi b/stubs/hvac/hvac/api/system_backend/policies.pyi new file mode 100644 index 000000000000..324b0e4da8aa --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/policies.pyi @@ -0,0 +1,15 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Policies(SystemBackendMixin): + def list_acl_policies(self): ... + def read_acl_policy(self, name): ... + def create_or_update_acl_policy(self, name, policy, pretty_print: bool = True): ... + def delete_acl_policy(self, name): ... + def list_rgp_policies(self): ... + def read_rgp_policy(self, name): ... + def create_or_update_rgp_policy(self, name, policy, enforcement_level): ... + def delete_rgp_policy(self, name): ... + def list_egp_policies(self): ... + def read_egp_policy(self, name): ... + def create_or_update_egp_policy(self, name, policy, enforcement_level, paths): ... + def delete_egp_policy(self, name): ... diff --git a/stubs/hvac/hvac/api/system_backend/policy.pyi b/stubs/hvac/hvac/api/system_backend/policy.pyi new file mode 100644 index 000000000000..51de631b3a26 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/policy.pyi @@ -0,0 +1,7 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Policy(SystemBackendMixin): + def list_policies(self): ... + def read_policy(self, name): ... + def create_or_update_policy(self, name, policy, pretty_print: bool = True): ... + def delete_policy(self, name): ... diff --git a/stubs/hvac/hvac/api/system_backend/quota.pyi b/stubs/hvac/hvac/api/system_backend/quota.pyi new file mode 100644 index 000000000000..15385d68a492 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/quota.pyi @@ -0,0 +1,9 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Quota(SystemBackendMixin): + def read_quota(self, name): ... + def list_quotas(self): ... + def create_or_update_quota( + self, name, rate, path=None, interval=None, block_interval=None, role=None, rate_limit_type=None, inheritable=None + ): ... + def delete_quota(self, name): ... diff --git a/stubs/hvac/hvac/api/system_backend/raft.pyi b/stubs/hvac/hvac/api/system_backend/raft.pyi new file mode 100644 index 000000000000..94b531a53953 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/raft.pyi @@ -0,0 +1,21 @@ +from typing import Any + +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin +from requests import Response + +class Raft(SystemBackendMixin): + def join_raft_cluster( + self, leader_api_addr, retry: bool = False, leader_ca_cert=None, leader_client_cert=None, leader_client_key=None + ): ... + def read_raft_config(self): ... + def remove_raft_node(self, server_id): ... + def take_raft_snapshot(self): ... + def restore_raft_snapshot(self, snapshot): ... + def force_restore_raft_snapshot(self, snapshot): ... + def read_raft_auto_snapshot_status(self, name: str) -> Response: ... + def read_raft_auto_snapshot_config(self, name: str) -> Response: ... + def list_raft_auto_snapshot_configs(self) -> Response: ... + def create_or_update_raft_auto_snapshot_config( + self, name: str, interval: str, storage_type: str, retain: int = 1, **kwargs: Any + ) -> Response: ... + def delete_raft_auto_snapshot_config(self, name: str) -> Response: ... diff --git a/stubs/hvac/hvac/api/system_backend/seal.pyi b/stubs/hvac/hvac/api/system_backend/seal.pyi new file mode 100644 index 000000000000..9590f989df20 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/seal.pyi @@ -0,0 +1,8 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Seal(SystemBackendMixin): + def is_sealed(self): ... + def read_seal_status(self): ... + def seal(self): ... + def submit_unseal_key(self, key=None, reset: bool = False, migrate: bool = False): ... + def submit_unseal_keys(self, keys, migrate: bool = False): ... diff --git a/stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi b/stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi new file mode 100644 index 000000000000..5aab4a8129e5 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi @@ -0,0 +1,8 @@ +import logging +from abc import ABCMeta + +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class SystemBackendMixin(VaultApiBase, metaclass=ABCMeta): ... diff --git a/stubs/hvac/hvac/api/system_backend/wrapping.pyi b/stubs/hvac/hvac/api/system_backend/wrapping.pyi new file mode 100644 index 000000000000..abed47c18ea1 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/wrapping.pyi @@ -0,0 +1,6 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin +from requests._types import JsonType + +class Wrapping(SystemBackendMixin): + def unwrap(self, token=None): ... + def wrap(self, payload: JsonType = None, ttl: int = 60): ... diff --git a/stubs/hvac/hvac/api/vault_api_base.pyi b/stubs/hvac/hvac/api/vault_api_base.pyi new file mode 100644 index 000000000000..063f55d8fcf7 --- /dev/null +++ b/stubs/hvac/hvac/api/vault_api_base.pyi @@ -0,0 +1,10 @@ +from abc import ABCMeta +from logging import Logger +from typing import Any + +from hvac.adapters import Adapter + +logger: Logger + +class VaultApiBase(metaclass=ABCMeta): + def __init__(self, adapter: Adapter[Any]) -> None: ... diff --git a/stubs/hvac/hvac/api/vault_api_category.pyi b/stubs/hvac/hvac/api/vault_api_category.pyi new file mode 100644 index 000000000000..9d0e8be845bd --- /dev/null +++ b/stubs/hvac/hvac/api/vault_api_category.pyi @@ -0,0 +1,26 @@ +from abc import ABCMeta, abstractmethod +from logging import Logger +from typing import Any + +from hvac.adapters import Adapter +from hvac.api.vault_api_base import VaultApiBase + +logger: Logger + +class VaultApiCategory(VaultApiBase, metaclass=ABCMeta): + implemented_class_names: list[str] + def __init__(self, adapter: Adapter[Any]) -> None: ... + def __getattr__(self, item: str): ... + + @property + def adapter(self) -> Adapter[Any]: ... + @adapter.setter + def adapter(self, adapter: Adapter[Any]) -> None: ... + + @property + @abstractmethod + def implemented_classes(self) -> list[type[VaultApiBase]]: ... + @property + def unimplemented_classes(self) -> list[str]: ... + @staticmethod + def get_private_attr_name(class_name: str) -> str: ... diff --git a/stubs/hvac/hvac/aws_utils.pyi b/stubs/hvac/hvac/aws_utils.pyi new file mode 100644 index 000000000000..a63a1b022c81 --- /dev/null +++ b/stubs/hvac/hvac/aws_utils.pyi @@ -0,0 +1,11 @@ +import requests + +class SigV4Auth: + access_key: str + secret_key: str + session_token: str | None + region: str + def __init__(self, access_key: str, secret_key: str, session_token: str | None = None, region: str = "us-east-1") -> None: ... + def add_auth(self, request: requests.PreparedRequest) -> None: ... + +def generate_sigv4_auth_request(header_value: str | None = None): ... diff --git a/stdlib/@python2/distutils/command/install_headers.pyi b/stubs/hvac/hvac/constants/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/install_headers.pyi rename to stubs/hvac/hvac/constants/__init__.pyi diff --git a/stubs/hvac/hvac/constants/approle.pyi b/stubs/hvac/hvac/constants/approle.pyi new file mode 100644 index 000000000000..1eb6dc9a051b --- /dev/null +++ b/stubs/hvac/hvac/constants/approle.pyi @@ -0,0 +1,4 @@ +from collections.abc import Iterable + +DEFAULT_MOUNT_POINT: str +ALLOWED_TOKEN_TYPES: Iterable[str] diff --git a/stubs/hvac/hvac/constants/aws.pyi b/stubs/hvac/hvac/constants/aws.pyi new file mode 100644 index 000000000000..7fed919b49f6 --- /dev/null +++ b/stubs/hvac/hvac/constants/aws.pyi @@ -0,0 +1,7 @@ +from collections.abc import Iterable + +DEFAULT_MOUNT_POINT: str +ALLOWED_CREDS_ENDPOINTS: Iterable[str] +ALLOWED_CREDS_TYPES: Iterable[str] +ALLOWED_IAM_ALIAS_TYPES: Iterable[str] +ALLOWED_EC2_ALIAS_TYPES: Iterable[str] diff --git a/stubs/hvac/hvac/constants/azure.pyi b/stubs/hvac/hvac/constants/azure.pyi new file mode 100644 index 000000000000..c857aa27d47d --- /dev/null +++ b/stubs/hvac/hvac/constants/azure.pyi @@ -0,0 +1,3 @@ +from collections.abc import Iterable + +VALID_ENVIRONMENTS: Iterable[str] diff --git a/stubs/hvac/hvac/constants/client.pyi b/stubs/hvac/hvac/constants/client.pyi new file mode 100644 index 000000000000..81d22815bd8a --- /dev/null +++ b/stubs/hvac/hvac/constants/client.pyi @@ -0,0 +1,8 @@ +from hvac.utils import _DeprecateProperty + +DEPRECATED_PROPERTIES: dict[str, _DeprecateProperty] +DEFAULT_URL: str +VAULT_CACERT: str | None +VAULT_CAPATH: str | None +VAULT_CLIENT_CERT: str | None +VAULT_CLIENT_KEY: str | None diff --git a/stubs/hvac/hvac/constants/gcp.pyi b/stubs/hvac/hvac/constants/gcp.pyi new file mode 100644 index 000000000000..1c0bd678663c --- /dev/null +++ b/stubs/hvac/hvac/constants/gcp.pyi @@ -0,0 +1,8 @@ +from collections.abc import Iterable + +DEFAULT_MOUNT_POINT: str +ALLOWED_ROLE_TYPES: Iterable[str] +ALLOWED_SECRETS_TYPES: Iterable[str] +SERVICE_ACCOUNT_KEY_ALGORITHMS: Iterable[str] +SERVICE_ACCOUNT_KEY_TYPES: Iterable[str] +GCP_CERTS_ENDPOINT: str diff --git a/stubs/hvac/hvac/constants/identity.pyi b/stubs/hvac/hvac/constants/identity.pyi new file mode 100644 index 000000000000..c9041bf3e3b2 --- /dev/null +++ b/stubs/hvac/hvac/constants/identity.pyi @@ -0,0 +1,5 @@ +from collections.abc import Iterable +from typing import Final + +ALLOWED_GROUP_TYPES: Iterable[str] +DEFAULT_MOUNT_POINT: Final = "identity" diff --git a/stubs/hvac/hvac/constants/transit.pyi b/stubs/hvac/hvac/constants/transit.pyi new file mode 100644 index 000000000000..af633211ff13 --- /dev/null +++ b/stubs/hvac/hvac/constants/transit.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from re import Pattern + +ALLOWED_KEY_TYPES: Iterable[str] +ALLOWED_EXPORT_KEY_TYPES: Iterable[str] +ALLOWED_DATA_KEY_TYPES: Iterable[str] +ALLOWED_DATA_KEY_BITS: Iterable[int] +ALLOWED_HASH_DATA_ALGORITHMS: Iterable[str] +ALLOWED_HASH_DATA_FORMATS: Iterable[str] +ALLOWED_SIGNATURE_ALGORITHMS: Iterable[str] +ALLOWED_MARSHALING_ALGORITHMS: Iterable[str] +ALLOWED_SALT_LENGTHS: Pattern[str] diff --git a/stubs/hvac/hvac/exceptions.pyi b/stubs/hvac/hvac/exceptions.pyi new file mode 100644 index 000000000000..67c2ed53b81a --- /dev/null +++ b/stubs/hvac/hvac/exceptions.pyi @@ -0,0 +1,43 @@ +from collections.abc import Iterable +from typing_extensions import Self + +class VaultError(Exception): + errors: Iterable[str] | str | None + method: str | None + url: str | None + text: str | None + json: object + def __init__( + self, + message: str | None = None, + errors: Iterable[str] | str | None = None, + method: str | None = None, + url: str | None = None, + text: str | None = None, + json: object | None = None, + ) -> None: ... + @classmethod + def from_status( + cls, + status_code: int, + message: str | None = ..., + errors: Iterable[str] | str | None = ..., + method: str | None = ..., + url: str | None = ..., + text: str | None = ..., + json: object | None = ..., + ) -> Self: ... + +class InvalidRequest(VaultError): ... +class Unauthorized(VaultError): ... +class Forbidden(VaultError): ... +class InvalidPath(VaultError): ... +class UnsupportedOperation(VaultError): ... +class PreconditionFailed(VaultError): ... +class RateLimitExceeded(VaultError): ... +class InternalServerError(VaultError): ... +class VaultNotInitialized(VaultError): ... +class VaultDown(VaultError): ... +class UnexpectedError(VaultError): ... +class BadGateway(VaultError): ... +class ParamValidationError(VaultError): ... diff --git a/stubs/hvac/hvac/utils.pyi b/stubs/hvac/hvac/utils.pyi new file mode 100644 index 000000000000..ba48033a43d4 --- /dev/null +++ b/stubs/hvac/hvac/utils.pyi @@ -0,0 +1,48 @@ +from collections.abc import Callable, Iterable, Mapping +from typing import Any, TypedDict, TypeVar, type_check_only +from typing_extensions import Never, NotRequired + +@type_check_only +class _DeprecateProperty(TypedDict): + to_be_removed_in_version: str + client_property: str + new_property: NotRequired[str] + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +def raise_for_error( + method: str, + url: str, + status_code: int, + message: str | None = None, + errors: Iterable[str] | str | None = None, + text: str | None = None, + json: object | None = None, +) -> Never: ... +def aliased_parameter( + name: str, *aliases: str, removed_in_version: str | None, position: int | None = None, raise_on_multiple: bool = True +) -> Callable[..., Any]: ... +def generate_parameter_deprecation_message( + to_be_removed_in_version: str, old_parameter_name: str, new_parameter_name: str | None = None, extra_notes: str | None = None +) -> str: ... +def generate_method_deprecation_message( + to_be_removed_in_version: str, old_method_name: str, method_name: str | None = None, module_name: str | None = None +) -> str: ... +def generate_property_deprecation_message( + to_be_removed_in_version: str, old_name: str, new_name: str, new_attribute: str, module_name: str = "Client" +) -> str: ... +def getattr_with_deprecated_properties(obj: object, item: str, deprecated_properties: dict[str, _DeprecateProperty]) -> Any: ... +def deprecated_method(to_be_removed_in_version: str, new_method: Callable[..., Any] | None = None) -> Callable[..., Any]: ... +def validate_list_of_strings_param(param_name: str, param_argument: Iterable[Any] | str) -> None: ... +def list_to_comma_delimited(list_param: Iterable[str] | None) -> str: ... +def get_token_from_env() -> str | None: ... +def comma_delimited_to_list(list_param: Iterable[_T]) -> Iterable[_T]: ... + +# the docstring states that this function returns a bool, but the code does not return anything +def validate_pem_format(param_name: str, param_argument: str) -> None: ... +def remove_nones(params: Mapping[_K, _V | None]) -> Mapping[_K, _V]: ... +def format_url( + format_str: str, *args: object, **kwargs: object +) -> str: ... # values are passed to builtins.str, which takes an object type diff --git a/stubs/hvac/hvac/v1/__init__.pyi b/stubs/hvac/hvac/v1/__init__.pyi new file mode 100644 index 000000000000..e368210f0a1c --- /dev/null +++ b/stubs/hvac/hvac/v1/__init__.pyi @@ -0,0 +1,92 @@ +from typing import Any, Literal, overload + +from hvac.adapters import Adapter +from hvac.api import AuthMethods, SystemBackend +from hvac.api.secrets_engines import SecretsEngines +from requests import Session +from requests.models import Response + +has_hcl_parser: bool + +class Client: + def __init__( + self, + url: str | None = None, + token: str | None = None, + cert: tuple[str, str] | None = None, + verify: bool | str | None = None, + timeout: int = 30, + proxies: dict[str, str] | None = None, + allow_redirects: bool = True, + session: Session | None = None, + adapter: type[Adapter[Any]] = ..., + namespace: str | None = None, + **kwargs: Any, + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + + @property + def adapter(self) -> Adapter[Any]: ... + @adapter.setter + def adapter(self, adapter: Adapter[Any]) -> None: ... + + @property + def url(self) -> str: ... + @url.setter + def url(self, url: str) -> None: ... + + @property + def token(self) -> str: ... + @token.setter + def token(self, token: str) -> None: ... + + @property + def session(self) -> Session: ... + @session.setter + def session(self, session: Session) -> None: ... + + @property + def allow_redirects(self) -> bool: ... + @allow_redirects.setter + def allow_redirects(self, allow_redirects: bool) -> None: ... + + @property + def auth(self) -> AuthMethods: ... + @property + def secrets(self) -> SecretsEngines: ... + @property + def sys(self) -> SystemBackend: ... + @property + def generate_root_status(self) -> dict[str, Any] | Response: ... + @property + def key_status(self) -> dict[str, Any] | Response: ... + @property + def rekey_status(self) -> dict[str, Any] | Response: ... + @property + def ha_status(self) -> dict[str, Any] | Response: ... + @property + def seal_status(self) -> dict[str, Any] | Response: ... + def read(self, path: str, wrap_ttl: int | str | None = None) -> dict[str, Any] | Response | None: ... + def list(self, path: str) -> dict[str, Any] | Response | None: ... + def write(self, path: str, wrap_ttl: int | str | None, **kwargs: Any) -> dict[str, Any] | Response: ... + def write_data( + self, path: str, *, data: dict[str, Any] | None = None, wrap_ttl: int | str | None = None + ) -> dict[str, Any] | Response: ... + def delete(self, path: str) -> None: ... + + @overload + def get_policy(self, name: str, parse: Literal[False] = False) -> str | None: ... + @overload + def get_policy(self, name: str, parse: Literal[True]) -> dict[str, Any] | None: ... + + def lookup_token( + self, token: str | None = None, accessor: bool = False, wrap_ttl: int | str | None = None + ) -> dict[str, Any] | Response: ... + def revoke_token(self, token: str, orphan: bool = False, accessor: bool = False) -> None: ... + def renew_token( + self, token: str, increment: bool | None = None, wrap_ttl: int | str | None = None + ) -> dict[str, Any] | Response: ... + def logout(self, revoke_token: bool = False) -> None: ... + def is_authenticated(self) -> bool: ... + def auth_cubbyhole(self, token: str) -> Response: ... + def login(self, url: str, use_token: bool = True, **kwargs: Any) -> Response: ... diff --git a/stubs/ibm-db/METADATA.toml b/stubs/ibm-db/METADATA.toml new file mode 100644 index 000000000000..a39a4ef3eacb --- /dev/null +++ b/stubs/ibm-db/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.3.0" +upstream-repository = "https://github.com/ibmdb/python-ibmdb" diff --git a/stubs/ibm-db/ibm_db.pyi b/stubs/ibm-db/ibm_db.pyi new file mode 100644 index 000000000000..a7e9456b7515 --- /dev/null +++ b/stubs/ibm-db/ibm_db.pyi @@ -0,0 +1,371 @@ +from typing import Any, Final, final, overload +from typing_extensions import Self + +__version__: Final[str] +ATTR_CASE: Final = 3271982 +CASE_LOWER: Final = 1 +CASE_NATURAL: Final = 0 +CASE_UPPER: Final = 2 +PARAM_FILE: Final = 11 +QUOTED_LITERAL_REPLACEMENT_OFF: Final = 0 +QUOTED_LITERAL_REPLACEMENT_ON: Final = 1 +SQL_API_SQLROWCOUNT: Final[int] +SQL_ATTR_AUTOCOMMIT: Final[int] +SQL_ATTR_CALL_RETURN: Final[int] +SQL_ATTR_CURRENT_SCHEMA: Final[int] +SQL_ATTR_CURSOR_TYPE: Final[int] +SQL_ATTR_INFO_ACCTSTR: Final[int] +SQL_ATTR_INFO_APPLNAME: Final[int] +SQL_ATTR_INFO_PROGRAMNAME: Final[int] +SQL_ATTR_INFO_USERID: Final[int] +SQL_ATTR_INFO_WRKSTNNAME: Final[int] +SQL_ATTR_PARAMSET_SIZE: Final[int] +SQL_ATTR_PARAM_BIND_TYPE: Final[int] +SQL_ATTR_QUERY_TIMEOUT: Final[int] +SQL_ATTR_ROWCOUNT_PREFETCH: Final[int] +SQL_ATTR_TRUSTED_CONTEXT_PASSWORD: Final[int] +SQL_ATTR_TRUSTED_CONTEXT_USERID: Final[int] +SQL_ATTR_TXN_ISOLATION: Final[int] +SQL_ATTR_USE_TRUSTED_CONTEXT: Final[int] +SQL_ATTR_XML_DECLARATION: Final[int] +SQL_AUTOCOMMIT_OFF: Final[int] +SQL_AUTOCOMMIT_ON: Final[int] +SQL_BIGINT: Final[int] +SQL_BINARY: Final[int] +SQL_BIT: Final[int] +SQL_BLOB: Final[int] +SQL_BLOB_LOCATOR: Final[int] +SQL_BOOLEAN: Final[int] +SQL_CHAR: Final[int] +SQL_CLOB: Final[int] +SQL_CLOB_LOCATOR: Final[int] +SQL_CONCURRENT_TRANS: Final[int] +SQL_COORDINATED_TRANS: Final[int] +SQL_CURSOR_DYNAMIC: Final[int] +SQL_CURSOR_FORWARD_ONLY: Final[int] +SQL_CURSOR_KEYSET_DRIVEN: Final[int] +SQL_CURSOR_STATIC: Final[int] +SQL_DBCLOB: Final[int] +SQL_DBCLOB_LOCATOR: Final[int] +SQL_DBMS_NAME: Final[int] +SQL_DBMS_VER: Final[int] +SQL_DECFLOAT: Final[int] +SQL_DECIMAL: Final[int] +SQL_DOUBLE: Final[int] +SQL_FALSE: Final[int] +SQL_FLOAT: Final[int] +SQL_GRAPHIC: Final[int] +SQL_INDEX_CLUSTERED: Final[int] +SQL_INDEX_OTHER: Final[int] +SQL_INTEGER: Final[int] +SQL_LONGVARBINARY: Final[int] +SQL_LONGVARCHAR: Final[int] +SQL_LONGVARGRAPHIC: Final[int] +SQL_NUMERIC: Final[int] +SQL_PARAM_BIND_BY_COLUMN: Final[int] +SQL_PARAM_INPUT: Final[int] +SQL_PARAM_INPUT_OUTPUT: Final[int] +SQL_PARAM_OUTPUT: Final[int] +SQL_REAL: Final[int] +SQL_ROWCOUNT_PREFETCH_OFF: Final[int] +SQL_ROWCOUNT_PREFETCH_ON: Final[int] +SQL_SMALLINT: Final[int] +SQL_TABLE_STAT: Final[int] +SQL_TINYINT: Final[int] +SQL_TRUE: Final[int] +SQL_TXN_NO_COMMIT: Final[int] +SQL_TXN_READ_COMMITTED: Final[int] +SQL_TXN_READ_UNCOMMITTED: Final[int] +SQL_TXN_REPEATABLE_READ: Final[int] +SQL_TXN_SERIALIZABLE: Final[int] +SQL_TYPE_DATE: Final[int] +SQL_TYPE_TIME: Final[int] +SQL_TYPE_TIMESTAMP: Final[int] +SQL_VARBINARY: Final[int] +SQL_VARCHAR: Final[int] +SQL_VARGRAPHIC: Final[int] +SQL_WCHAR: Final[int] +SQL_WLONGVARCHAR: Final[int] +SQL_WVARCHAR: Final[int] +SQL_XML: Final[int] +USE_WCHAR: Final = 100 +WCHAR_NO: Final = 0 +WCHAR_YES: Final = 1 + +SQL_ATTR_ACCESS_MODE: Final[int] +SQL_ATTR_ALLOW_INTERLEAVED_GETDATA: Final[int] +SQL_ATTR_ANSI_APP: Final[int] +SQL_ATTR_APPEND_FOR_FETCH_ONLY: Final[int] +SQL_ATTR_APP_USES_LOB_LOCATOR: Final[int] +SQL_ATTR_ASYNC_ENABLE: Final[int] +SQL_ATTR_AUTO_IPD: Final[int] +SQL_ATTR_CACHE_USRLIBL: Final[int] +SQL_ATTR_CLIENT_APPLCOMPAT: Final[int] +SQL_ATTR_CLIENT_CODEPAGE: Final[int] +SQL_ATTR_COLUMNWISE_MRI: Final[int] +SQL_ATTR_COMMITONEOF: Final[int] +SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION: Final[int] +SQL_ATTR_CONFIG_KEYWORDS_ARRAY_SIZE: Final[int] +SQL_ATTR_CONFIG_KEYWORDS_MAXLEN: Final[int] +SQL_ATTR_CONNECTION_DEAD: Final[int] +SQL_ATTR_CONNECTTYPE: Final[int] +SQL_ATTR_CONNECT_NODE: Final[int] +SQL_ATTR_CONNECT_PASSIVE: Final[int] +SQL_ATTR_CONN_CONTEXT: Final[int] +SQL_ATTR_CURRENT_CATALOG: Final[int] +SQL_ATTR_CURRENT_IMPLICIT_XMLPARSE_OPTION: Final[int] +SQL_ATTR_CURRENT_PACKAGE_PATH: Final[int] +SQL_ATTR_CURRENT_PACKAGE_SET: Final[int] +SQL_ATTR_DATE_FMT: Final[int] +SQL_ATTR_DATE_SEP: Final[int] +SQL_ATTR_DB2EXPLAIN: Final[int] +SQL_ATTR_DB2_APPLICATION_HANDLE: Final[int] +SQL_ATTR_DB2_APPLICATION_ID: Final[int] +SQL_ATTR_DB2_SQLERRP: Final[int] +SQL_ATTR_DECFLOAT_ROUNDING_MODE: Final[int] +SQL_ATTR_DECIMAL_SEP: Final[int] +SQL_ATTR_DESCRIBE_CALL: Final[int] +SQL_ATTR_DESCRIBE_OUTPUT_LEVEL: Final[int] +SQL_ATTR_DETECT_READ_ONLY_TXN: Final[int] +SQL_ATTR_DEFERRED_PREPARE: Final[int] +SQL_ATTR_ENLIST_IN_DTC: Final[int] +SQL_ATTR_EXTENDED_INDICATORS: Final[int] +SQL_ATTR_FET_BUF_SIZE: Final[int] +SQL_ATTR_FORCE_ROLLBACK: Final[int] +SQL_ATTR_FREE_LOCATORS_ON_FETCH: Final[int] +SQL_ATTR_GET_LATEST_MEMBER: Final[int] +SQL_ATTR_GET_LATEST_MEMBER_NAME: Final[int] +SQL_ATTR_IGNORE_SERVER_LIST: Final[int] +SQL_ATTR_INFO_CRRTKN: Final[int] +SQL_ATTR_INFO_PROGRAMID: Final[int] +SQL_ATTR_KEEP_DYNAMIC: Final[int] +SQL_ATTR_LOB_CACHE_SIZE: Final[int] +SQL_ATTR_LOB_FILE_THRESHOLD: Final[int] +SQL_ATTR_LOGIN_TIMEOUT: Final[int] +SQL_ATTR_LONGDATA_COMPAT: Final[int] +SQL_ATTR_MAPCHAR: Final[int] +SQL_ATTR_MAXBLKEXT: Final[int] +SQL_ATTR_MAX_LOB_BLOCK_SIZE: Final[int] +SQL_ATTR_NETWORK_STATISTICS: Final[int] +SQL_ATTR_OVERRIDE_CHARACTER_CODEPAGE: Final[int] +SQL_ATTR_OVERRIDE_CODEPAGE: Final[int] +SQL_ATTR_OVERRIDE_PRIMARY_AFFINITY: Final[int] +SQL_ATTR_PARC_BATCH: Final[int] +SQL_ATTR_PING_DB: Final[int] +SQL_ATTR_PING_NTIMES: Final[int] +SQL_ATTR_PING_REQUEST_PACKET_SIZE: Final[int] +SQL_ATTR_QUERY_PREFETCH: Final[int] +SQL_ATTR_QUIET_MODE: Final[int] +SQL_ATTR_READ_ONLY_CONNECTION: Final[int] +SQL_ATTR_RECEIVE_TIMEOUT: Final[int] +SQL_ATTR_REOPT: Final[int] +SQL_ATTR_REPORT_ISLONG_FOR_LONGTYPES_OLEDB: Final[int] +SQL_ATTR_REPORT_SEAMLESSFAILOVER_WARNING: Final[int] +SQL_ATTR_REPORT_TIMESTAMP_TRUNC_AS_WARN: Final[int] +SQL_ATTR_RETRYONERROR: Final[int] +SQL_ATTR_RETRY_ON_MERGE: Final[int] +SQL_ATTR_ROW_ARRAY_SIZE: Final[int] +SQL_ATTR_SERVER_MSGTXT_MASK: Final[int] +SQL_ATTR_SERVER_MSGTXT_SP: Final[int] +SQL_ATTR_SESSION_GLOBAL_VAR: Final[int] +SQL_ATTR_SESSION_TIME_ZONE: Final[int] +SQL_ATTR_SPECIAL_REGISTER: Final[int] +SQL_ATTR_SQLCOLUMNS_SORT_BY_ORDINAL_OLEDB: Final[int] +SQL_ATTR_STMT_CONCENTRATOR: Final[int] +SQL_ATTR_STREAM_GETDATA: Final[int] +SQL_ATTR_STREAM_OUTPUTLOB_ON_CALL: Final[int] +SQL_ATTR_TIME_FMT: Final[int] +SQL_ATTR_TIME_SEP: Final[int] +SQL_ATTR_TRUSTED_CONTEXT_ACCESSTOKEN: Final[int] +SQL_ATTR_USER_REGISTRY_NAME: Final[int] +SQL_ATTR_WCHARTYPE: Final[int] + +@final +class IBM_DBClientInfo: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + APPL_CODEPAGE: int + CONN_CODEPAGE: int + DATA_SOURCE_NAME: str + DRIVER_NAME: str + DRIVER_ODBC_VER: str + DRIVER_VER: str + ODBC_SQL_CONFORMANCE: str + ODBC_VER: str + +@final +class IBM_DBConnection: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + +@final +class IBM_DBEnvHandle: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + +@final +class IBM_DBServerInfo: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + DBMS_NAME: str + DBMS_VER: str + DB_CODEPAGE: int + DB_NAME: str + DFT_ISOLATION: str + IDENTIFIER_QUOTE_CHAR: str + INST_NAME: str + ISOLATION_OPTION: tuple[str, str, str, str, str] + KEYWORDS: str + LIKE_ESCAPE_CLAUSE: bool + MAX_COL_NAME_LEN: int + MAX_IDENTIFIER_LEN: int + MAX_INDEX_SIZE: int + MAX_PROC_NAME_LEN: int + MAX_ROW_SIZE: int + MAX_SCHEMA_NAME_LEN: int + MAX_STATEMENT_LEN: int + MAX_TABLE_NAME_LEN: int + NON_NULLABLE_COLUMNS: bool + PROCEDURES: bool + SPECIAL_CHARS: str + SQL_CONFORMANCE: str + +@final +class IBM_DBStatement: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + +def active(connection: IBM_DBConnection | None, /) -> bool: ... +def alloc_env_handle() -> IBM_DBEnvHandle: ... +def autocommit(connection: IBM_DBConnection, value: int = ..., /) -> int | bool: ... +def bind_param( + stmt: IBM_DBStatement, + parameter_number: int, + variable: str, + parameter_type: int | None = ..., + data_type: int | None = ..., + precision: int | None = ..., + scale: int | None = ..., + size: int | None = ..., + /, +) -> bool: ... + +@overload +def callproc(connection: IBM_DBConnection, procname: str, /) -> IBM_DBStatement | None: ... +@overload +def callproc(connection: IBM_DBConnection, procname: str, parameters: tuple[object, ...], /) -> tuple[object, ...] | None: ... + +def check_function_support(connection: IBM_DBConnection, function_id: int, /) -> bool: ... +def client_info(connection: IBM_DBConnection, /) -> IBM_DBClientInfo | bool: ... +def close(connection: IBM_DBConnection, /) -> bool: ... +def column_privileges( + connection: IBM_DBConnection, + qualifier: str | None = ..., + schema: str | None = ..., + table_name: str | None = ..., + column_name: str | None = ..., + /, +) -> IBM_DBStatement: ... +def columns( + connection: IBM_DBConnection, + qualifier: str | None = ..., + schema: str | None = ..., + table_name: str | None = ..., + column_name: str | None = ..., + /, +) -> IBM_DBStatement: ... +def commit(connection: IBM_DBConnection, /) -> bool: ... +def commit_two_phase(env_handle: IBM_DBEnvHandle, /) -> bool: ... +def conn_error(connection: IBM_DBConnection | None = ..., /) -> str: ... +def conn_errormsg(connection: IBM_DBConnection | None = ..., /) -> str: ... +def conn_warn(connection: IBM_DBConnection | None = ..., /) -> str: ... +def connect( + database: str, user: str, password: str, options: dict[int, int | str] | None = ..., replace_quoted_literal: int = ..., / +) -> IBM_DBConnection | None: ... +def connect_coordinated(env_handle: IBM_DBEnvHandle, database: str, user: str, password: str, /) -> IBM_DBConnection: ... +def createdb(connection: IBM_DBConnection, dbName: str, codeSet: str = ..., mode: str = ..., /) -> bool: ... +def createdbNX(connection: IBM_DBConnection, dbName: str, codeSet: str = ..., mode: str = ..., /) -> bool: ... +def cursor_type(stmt: IBM_DBStatement, /) -> int: ... +def debug(option: str | bool) -> None: ... +def dropdb(connection: IBM_DBConnection, dbName: str, /) -> bool: ... +def exec_immediate( + connection: IBM_DBConnection, statement: str | None, options: dict[int, int] = ..., / +) -> IBM_DBStatement | bool: ... +def execute(stmt: IBM_DBStatement, parameters: tuple[object, ...] | None = ..., /) -> bool: ... +def execute_many( + stmt: IBM_DBStatement, seq_of_parameters: tuple[object, ...], options: dict[int, int] = ..., / +) -> int | None: ... +def fetchall(stmt: IBM_DBStatement, /) -> list[tuple[object, ...]]: ... +def fetchmany(stmt: IBM_DBStatement, numberOfRows: int, /) -> list[tuple[object, ...]]: ... +def fetchone(stmt: IBM_DBStatement, /) -> tuple[object, ...]: ... +def fetch_assoc(stmt: IBM_DBStatement, row_number: int = ..., /) -> dict[str, object] | bool: ... +def fetch_both(stmt: IBM_DBStatement, row_number: int = ..., /) -> dict[int | str, object] | bool: ... +def fetch_row(stmt: IBM_DBStatement, row_number: int = ..., /) -> bool: ... +def fetch_tuple(stmt: IBM_DBStatement, row_number: int = ..., /) -> tuple[object, ...]: ... +def fetch_callproc(stmt: IBM_DBStatement, /) -> tuple[object, ...]: ... +def field_display_size(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_name(stmt: IBM_DBStatement, column: int | str, /) -> str | bool: ... +def field_nullable(stmt: IBM_DBStatement, column: int | str, /) -> bool: ... +def field_num(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_precision(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_scale(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_type(stmt: IBM_DBStatement, column: int | str, /) -> str | bool: ... +def field_width(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def foreign_keys( + connection: IBM_DBConnection, + pk_qualifier: str | None, + pk_schema: str | None, + pk_table_name: str | None, + fk_qualifier: str | None = ..., + fk_schema: str | None = ..., + fk_table_name: str | None = ..., + /, +) -> IBM_DBStatement: ... +def free_env_handle(env_handle: IBM_DBEnvHandle, /) -> bool: ... +def free_result(stmt: IBM_DBStatement, /) -> bool: ... +def free_stmt(stmt: IBM_DBStatement, /) -> bool: ... +def get_db_info(connection: IBM_DBConnection, option: int, /) -> str | bool: ... +def get_last_serial_value(stmt: IBM_DBStatement, /) -> str | bool: ... +def get_num_result(stmt: IBM_DBStatement, /) -> int | bool: ... +def get_option(resc: IBM_DBConnection | IBM_DBStatement, options: int, type: int, /) -> Any: ... +def get_sqlcode(connection_or_stmt: IBM_DBConnection | IBM_DBStatement | None = None, /) -> str: ... +def next_result(stmt: IBM_DBStatement, /) -> IBM_DBStatement | bool: ... +def num_fields(stmt: IBM_DBStatement, /) -> int | bool: ... +def num_rows(stmt: IBM_DBStatement, /) -> int: ... +def pconnect( + database: str, username: str, password: str, options: dict[int, int | str] | None = ..., / +) -> IBM_DBConnection | None: ... +def prepare( + connection: IBM_DBConnection, statement: str, options: dict[int, int | str] | None = ..., / +) -> IBM_DBStatement | bool: ... +def primary_keys( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, table_name: str | None, / +) -> IBM_DBStatement: ... +def procedure_columns( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, procedure: str | None, parameter: str | None, / +) -> IBM_DBStatement | bool: ... +def procedures( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, procedure: str | None, / +) -> IBM_DBStatement | bool: ... +def recreatedb(connection: IBM_DBConnection, dbName: str, codeSet: str | None = ..., mode: str | None = ..., /) -> bool: ... +def result(stmt: IBM_DBStatement, column: int | str, /) -> Any: ... +def rollback(connection: IBM_DBConnection, /) -> bool: ... +def rollback_two_phase(env_handle: IBM_DBEnvHandle, /) -> bool: ... +def server_info(connection: IBM_DBConnection, /) -> IBM_DBServerInfo | bool: ... +def set_env_attr(env_handle: IBM_DBEnvHandle, attribute: int, value: int, /) -> bool: ... +def set_option(resc: IBM_DBConnection | IBM_DBStatement, options: dict[int, int | str], type: int, /) -> bool: ... +def special_columns( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, table_name: str | None, scope: int, / +) -> IBM_DBStatement: ... +def statistics( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, table_name: str | None, unique: bool | None, / +) -> IBM_DBStatement: ... +def stmt_error(stmt: IBM_DBStatement = ..., /) -> str: ... +def stmt_errormsg(stmt: IBM_DBStatement = ..., /) -> str: ... +def stmt_warn(connection: IBM_DBConnection = ..., /) -> IBM_DBStatement: ... +def table_privileges( + connection: IBM_DBConnection, qualifier: str | None = ..., schema: str | None = ..., table_name: str | None = ..., / +) -> IBM_DBStatement | bool: ... +def tables( + connection: IBM_DBConnection, + qualifier: str | None = ..., + schema: str | None = ..., + table_name: str | None = ..., + table_type: str | None = ..., + /, +) -> IBM_DBStatement | bool: ... diff --git a/stubs/ibm-db/ibm_db_ctx.pyi b/stubs/ibm-db/ibm_db_ctx.pyi new file mode 100644 index 000000000000..32620f29cf4f --- /dev/null +++ b/stubs/ibm-db/ibm_db_ctx.pyi @@ -0,0 +1,8 @@ +from types import TracebackType + +import ibm_db + +class Db2connect: + def __init__(self, dsn: str, username: str, password: str) -> None: ... + def __enter__(self) -> ibm_db.IBM_DBConnection: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... diff --git a/stubs/inifile/@tests/stubtest_allowlist.txt b/stubs/inifile/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f94f1cf123df --- /dev/null +++ b/stubs/inifile/@tests/stubtest_allowlist.txt @@ -0,0 +1,24 @@ +# These are internal use and python 2 compatibility variables and functions +inifile.PY2 +inifile.WIN +inifile.integer_types +inifile.iter_from_file +inifile.iteritems +inifile.reraise +inifile.string_types +inifile.text_type + +# Attributes that should be treated as read-only and thus are annotated +# with @property +inifile.Dialect.ns_sep +inifile.Dialect.kv_sep +inifile.Dialect.quotes +inifile.Dialect.true +inifile.Dialect.false +inifile.Dialect.comments +inifile.Dialect.allow_escaping +inifile.Dialect.linesep +inifile.IniData.dialect +inifile.IniFile.filename +inifile.IniFile.encoding +inifile.IniFile.is_new diff --git a/stubs/inifile/METADATA.toml b/stubs/inifile/METADATA.toml new file mode 100644 index 000000000000..5532296509e6 --- /dev/null +++ b/stubs/inifile/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.4.*" +upstream-repository = "https://github.com/mitsuhiko/python-inifile" diff --git a/stubs/inifile/inifile.pyi b/stubs/inifile/inifile.pyi new file mode 100644 index 000000000000..db23bc4e06ce --- /dev/null +++ b/stubs/inifile/inifile.pyi @@ -0,0 +1,138 @@ +from _typeshed import StrPath, SupportsKeysAndGetItem +from collections.abc import Container, Iterable, Iterator, Mapping, MutableMapping, Sequence +from typing import Literal, TypeAlias, TypeVar, overload +from uuid import UUID + +_T = TypeVar("_T") + +_Token: TypeAlias = ( + tuple[Literal["EMPTY"], str, None] + | tuple[Literal["COMMENT"], str, None] + | tuple[Literal["SECTION"], str, tuple[str, ...]] + | tuple[Literal["KV"], str, tuple[str, str, str]] +) + +def get_app_dir(app_name: str, roaming: bool = ..., force_posix: bool = ...) -> str: ... + +class Dialect: + def __init__( + self, + ns_sep: str = ..., + kv_sep: str = ..., + quotes: Sequence[str] = ..., + true: Sequence[str] = ..., + false: Sequence[str] = ..., + comments: Container[str] = ..., + allow_escaping: bool = ..., + linesep: str | None = ..., + ) -> None: ... + @property + def ns_sep(self) -> str: ... + @property + def kv_sep(self) -> str: ... + @property + def quotes(self) -> Sequence[str]: ... + @property + def true(self) -> Sequence[str]: ... + @property + def false(self) -> Sequence[str]: ... + @property + def comments(self) -> Container[str]: ... + @property + def allow_escaping(self) -> bool: ... + @property + def linesep(self) -> str | None: ... + def get_actual_linesep(self) -> str: ... + def get_strippable_lineseps(self) -> str: ... + def kv_serialize(self, key: str, val: str | None) -> str | None: ... + def escape(self, value: str, quote: str | None = ...) -> str: ... + def unescape(self, value: str) -> str: ... + def to_string(self, value: bool | float | str) -> str: ... + def dict_from_iterable(self, iterable: Iterable[str]) -> MutableMapping[str, str]: ... + def tokenize(self, iterable: Iterable[str]) -> Iterator[_Token]: ... + def update_tokens( + self, old_tokens: Iterable[_Token], changes: SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]] + ) -> list[_Token]: ... + +default_dialect: Dialect + +class IniData(MutableMapping[str, str]): + def __init__(self, mapping: Mapping[str, str] | None = ..., dialect: Dialect | None = ...) -> None: ... + @property + def dialect(self) -> Dialect: ... + @property + def is_dirty(self) -> bool: ... + def get_updated_lines(self, line_iter: Iterable[_Token] | None = ...) -> list[_Token]: ... + def discard(self) -> None: ... + def rollover(self) -> None: ... + def to_dict(self) -> dict[str, str]: ... + def __len__(self) -> int: ... + + @overload + def get(self, name: str, default: None = None) -> str | None: ... + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: _T) -> str | _T: ... + + @overload + def get_ascii(self, name: str) -> str | None: ... + @overload + def get_ascii(self, name: str, default: _T) -> str | _T: ... + + @overload + def get_bool(self, name: str) -> bool: ... + @overload + def get_bool(self, name: str, default: _T) -> bool | _T: ... + + @overload + def get_int(self, name: str) -> int | None: ... + @overload + def get_int(self, name: str, default: _T = ...) -> int | _T: ... + + @overload + def get_float(self, name: str) -> float | None: ... + @overload + def get_float(self, name: str, default: _T) -> float | _T: ... + + @overload + def get_uuid(self, name: str) -> UUID | None: ... + @overload + def get_uuid(self, name: str, default: _T) -> UUID | _T: ... + + def itersections(self) -> Iterator[str]: ... + def sections(self) -> Iterator[str]: ... + def iteritems(self) -> Iterator[tuple[str, str]]: ... + def iterkeys(self) -> Iterator[str]: ... + def itervalues(self) -> Iterator[str]: ... + # NB: keys, items, values currently return a generator, which is + # incompatible with the views returned by Mappings + def items(self) -> Iterator[tuple[str, str]]: ... # type: ignore[override] + def keys(self) -> Iterator[str]: ... # type: ignore[override] + def __iter__(self) -> Iterator[str]: ... + def values(self) -> Iterator[str]: ... # type: ignore[override] + def section_as_dict(self, section: str) -> dict[str, str]: ... + def __getitem__(self, name: str) -> str: ... + def __setitem__(self, name: str, value: str) -> None: ... + def __delitem__(self, name: str) -> None: ... + +class IniFile(IniData): + def __init__(self, filename: StrPath, encoding: str | None = ..., dialect: Dialect | None = ...) -> None: ... + @property + def filename(self) -> str: ... + @property + def encoding(self) -> str | None: ... + @property + def is_new(self) -> bool: ... + def save(self, create_folder: bool = ...) -> None: ... + +class AppIniFile(IniFile): + def __init__( + self, + app_name: str, + filename: StrPath, + roaming: bool = ..., + force_posix: bool = ..., + encoding: str | None = ..., + dialect: Dialect | None = ..., + ) -> None: ... diff --git a/stubs/ipaddress/@python2/ipaddress.pyi b/stubs/ipaddress/@python2/ipaddress.pyi deleted file mode 100644 index 5d0c7dd6456e..000000000000 --- a/stubs/ipaddress/@python2/ipaddress.pyi +++ /dev/null @@ -1,148 +0,0 @@ -from typing import Any, Container, Generic, Iterable, Iterator, Optional, SupportsInt, Text, Tuple, TypeVar, overload - -# Undocumented length constants -IPV4LENGTH: int -IPV6LENGTH: int - -_A = TypeVar("_A", IPv4Address, IPv6Address) -_N = TypeVar("_N", IPv4Network, IPv6Network) -_T = TypeVar("_T") - -def ip_address(address: object) -> Any: ... # morally Union[IPv4Address, IPv6Address] -def ip_network(address: object, strict: bool = ...) -> Any: ... # morally Union[IPv4Network, IPv6Network] -def ip_interface(address: object) -> Any: ... # morally Union[IPv4Interface, IPv6Interface] - -class _IPAddressBase: - def __eq__(self, other: Any) -> bool: ... - def __ge__(self: _T, other: _T) -> bool: ... - def __gt__(self: _T, other: _T) -> bool: ... - def __le__(self: _T, other: _T) -> bool: ... - def __lt__(self: _T, other: _T) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - @property - def compressed(self) -> Text: ... - @property - def exploded(self) -> Text: ... - @property - def reverse_pointer(self) -> Text: ... - @property - def version(self) -> int: ... - -class _BaseAddress(_IPAddressBase, SupportsInt): - def __init__(self, address: object) -> None: ... - def __add__(self: _T, other: int) -> _T: ... - def __hash__(self) -> int: ... - def __int__(self) -> int: ... - def __sub__(self: _T, other: int) -> _T: ... - @property - def is_global(self) -> bool: ... - @property - def is_link_local(self) -> bool: ... - @property - def is_loopback(self) -> bool: ... - @property - def is_multicast(self) -> bool: ... - @property - def is_private(self) -> bool: ... - @property - def is_reserved(self) -> bool: ... - @property - def is_unspecified(self) -> bool: ... - @property - def max_prefixlen(self) -> int: ... - @property - def packed(self) -> bytes: ... - -class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): - network_address: _A - netmask: _A - def __init__(self, address: object, strict: bool = ...) -> None: ... - def __contains__(self, other: Any) -> bool: ... - def __getitem__(self, n: int) -> _A: ... - def __iter__(self) -> Iterator[_A]: ... - def address_exclude(self: _T, other: _T) -> Iterator[_T]: ... - @property - def broadcast_address(self) -> _A: ... - def compare_networks(self: _T, other: _T) -> int: ... - def hosts(self) -> Iterator[_A]: ... - @property - def is_global(self) -> bool: ... - @property - def is_link_local(self) -> bool: ... - @property - def is_loopback(self) -> bool: ... - @property - def is_multicast(self) -> bool: ... - @property - def is_private(self) -> bool: ... - @property - def is_reserved(self) -> bool: ... - @property - def is_unspecified(self) -> bool: ... - @property - def max_prefixlen(self) -> int: ... - @property - def num_addresses(self) -> int: ... - def overlaps(self, other: _BaseNetwork[_A]) -> bool: ... - @property - def prefixlen(self) -> int: ... - def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> Iterator[_T]: ... - def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> _T: ... - @property - def with_hostmask(self) -> Text: ... - @property - def with_netmask(self) -> Text: ... - @property - def with_prefixlen(self) -> Text: ... - @property - def hostmask(self) -> _A: ... - -class _BaseInterface(_BaseAddress, Generic[_A, _N]): - hostmask: _A - netmask: _A - network: _N - @property - def ip(self) -> _A: ... - @property - def with_hostmask(self) -> Text: ... - @property - def with_netmask(self) -> Text: ... - @property - def with_prefixlen(self) -> Text: ... - -class IPv4Address(_BaseAddress): ... -class IPv4Network(_BaseNetwork[IPv4Address]): ... -class IPv4Interface(IPv4Address, _BaseInterface[IPv4Address, IPv4Network]): ... - -class IPv6Address(_BaseAddress): - @property - def ipv4_mapped(self) -> Optional[IPv4Address]: ... - @property - def is_site_local(self) -> bool: ... - @property - def sixtofour(self) -> Optional[IPv4Address]: ... - @property - def teredo(self) -> Optional[Tuple[IPv4Address, IPv4Address]]: ... - -class IPv6Network(_BaseNetwork[IPv6Address]): - @property - def is_site_local(self) -> bool: ... - -class IPv6Interface(IPv6Address, _BaseInterface[IPv6Address, IPv6Network]): ... - -def v4_int_to_packed(address: int) -> bytes: ... -def v6_int_to_packed(address: int) -> bytes: ... -@overload -def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ... -@overload -def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ... -def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... -@overload -def get_mixed_type_key(obj: _A) -> Tuple[int, _A]: ... -@overload -def get_mixed_type_key(obj: IPv4Network) -> Tuple[int, IPv4Address, IPv4Address]: ... -@overload -def get_mixed_type_key(obj: IPv6Network) -> Tuple[int, IPv6Address, IPv6Address]: ... - -class AddressValueError(ValueError): ... -class NetmaskValueError(ValueError): ... diff --git a/stubs/ipaddress/METADATA.toml b/stubs/ipaddress/METADATA.toml deleted file mode 100644 index e29f8e7f8ef1..000000000000 --- a/stubs/ipaddress/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "1.0.*" -python2 = true diff --git a/stubs/jmespath/METADATA.toml b/stubs/jmespath/METADATA.toml index 5c7ed21e8ad5..856988fbacb3 100644 --- a/stubs/jmespath/METADATA.toml +++ b/stubs/jmespath/METADATA.toml @@ -1 +1,2 @@ -version = "0.10.*" +version = "1.1.*" +upstream-repository = "https://github.com/jmespath/jmespath.py" diff --git a/stubs/jmespath/jmespath/__init__.pyi b/stubs/jmespath/jmespath/__init__.pyi index 4f40ec73e3f1..f653d3f499a9 100644 --- a/stubs/jmespath/jmespath/__init__.pyi +++ b/stubs/jmespath/jmespath/__init__.pyi @@ -1,7 +1,9 @@ -from typing import Any +from typing import Any, Final from jmespath import parser as parser from jmespath.visitor import Options as Options -def compile(expression): ... -def search(expression, data, options: Any | None = ...): ... +__version__: Final[str] + +def compile(expression: str) -> parser.ParsedResult: ... +def search(expression: str, data: Any, options: Options | None = None) -> Any: ... diff --git a/stubs/jmespath/jmespath/ast.pyi b/stubs/jmespath/jmespath/ast.pyi index 77cc988f9265..53d718e084a0 100644 --- a/stubs/jmespath/jmespath/ast.pyi +++ b/stubs/jmespath/jmespath/ast.pyi @@ -1,22 +1,56 @@ -def comparator(name, first, second): ... -def current_node(): ... -def expref(expression): ... -def function_expression(name, args): ... -def field(name): ... -def filter_projection(left, right, comparator): ... -def flatten(node): ... -def identity(): ... -def index(index): ... -def index_expression(children): ... -def key_val_pair(key_name, node): ... -def literal(literal_value): ... -def multi_select_dict(nodes): ... -def multi_select_list(nodes): ... -def or_expression(left, right): ... -def and_expression(left, right): ... -def not_expression(expr): ... -def pipe(left, right): ... -def projection(left, right): ... -def subexpression(children): ... -def slice(start, end, step): ... -def value_projection(left, right): ... +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +_NodeType: TypeAlias = Literal[ + "comparator", + "current", + "expref", + "function_expression", + "field", + "filter_projection", + "flatten", + "identity", + "index", + "index_expression", + "key_val_pair", + "literal", + "multi_select_dict", + "multi_select_list", + "or_expression", + "and_expression", + "not_expression", + "pipe", + "projection", + "subexpression", + "slice", + "value_projection", +] + +@type_check_only +class _ASTNode(TypedDict): + type: _NodeType + children: list[_ASTNode] + value: NotRequired[str] + +def comparator(name: str, first: _ASTNode, second: _ASTNode) -> _ASTNode: ... +def current_node() -> _ASTNode: ... +def expref(expression: _ASTNode) -> _ASTNode: ... +def function_expression(name: str, args: list[_ASTNode]) -> _ASTNode: ... +def field(name: str) -> _ASTNode: ... +def filter_projection(left: _ASTNode, right: _ASTNode, comparator: _ASTNode) -> _ASTNode: ... +def flatten(node: _ASTNode) -> _ASTNode: ... +def identity() -> _ASTNode: ... +def index(index: str) -> _ASTNode: ... +def index_expression(children: list[_ASTNode]) -> _ASTNode: ... +def key_val_pair(key_name: str, node: _ASTNode) -> _ASTNode: ... +def literal(literal_value: str) -> _ASTNode: ... +def multi_select_dict(nodes: list[_ASTNode]) -> _ASTNode: ... +def multi_select_list(nodes: list[_ASTNode]) -> _ASTNode: ... +def or_expression(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def and_expression(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def not_expression(expr: _ASTNode) -> _ASTNode: ... +def pipe(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def projection(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def subexpression(children: list[_ASTNode]) -> _ASTNode: ... +def slice(start: _ASTNode, end: _ASTNode, step: _ASTNode) -> _ASTNode: ... +def value_projection(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... diff --git a/stubs/jmespath/jmespath/compat.pyi b/stubs/jmespath/jmespath/compat.pyi new file mode 100644 index 000000000000..771f0e5c3e50 --- /dev/null +++ b/stubs/jmespath/jmespath/compat.pyi @@ -0,0 +1,13 @@ +from collections.abc import Generator +from itertools import zip_longest as zip_longest +from types import FunctionType +from typing import TypeVar + +_T = TypeVar("_T") + +text_type = str +string_type = str + +def with_str_method(cls: _T) -> _T: ... +def with_repr_method(cls: _T) -> _T: ... +def get_methods(cls: object) -> Generator[tuple[str, FunctionType]]: ... diff --git a/stubs/jmespath/jmespath/exceptions.pyi b/stubs/jmespath/jmespath/exceptions.pyi index 8bbb095c24ec..45a6c4ec514e 100644 --- a/stubs/jmespath/jmespath/exceptions.pyi +++ b/stubs/jmespath/jmespath/exceptions.pyi @@ -1,44 +1,45 @@ +from collections.abc import Sequence from typing import Any class JMESPathError(ValueError): ... class ParseError(JMESPathError): - lex_position: Any - token_value: Any - token_type: Any - msg: Any - expression: Any - def __init__(self, lex_position, token_value, token_type, msg=...) -> None: ... + lex_position: int + token_value: str + token_type: str + msg: str + expression: str | None + def __init__( + self, lex_position: int, token_value: str, token_type: str, msg: str = "Invalid jmespath expression" + ) -> None: ... class IncompleteExpressionError(ParseError): - expression: Any - lex_position: Any - token_type: Any - token_value: Any - def set_expression(self, expression) -> None: ... + # When ParseError is used directly, the token always have a non-null value and type + token_value: str | None # type: ignore[assignment] + token_type: str | None # type: ignore[assignment] + expression: str + def set_expression(self, expression: str) -> None: ... class LexerError(ParseError): - lexer_position: Any - lexer_value: Any - message: Any - expression: Any - def __init__(self, lexer_position, lexer_value, message, expression: Any | None = ...) -> None: ... + lexer_position: int + lexer_value: str + message: str + def __init__(self, lexer_position: int, lexer_value: str, message: str, expression: str | None = None) -> None: ... class ArityError(ParseError): - expected_arity: Any - actual_arity: Any - function_name: Any - expression: Any - def __init__(self, expected, actual, name) -> None: ... + expected_arity: int + actual_arity: int + function_name: str + def __init__(self, expected: int, actual: int, name: str) -> None: ... class VariadictArityError(ArityError): ... class JMESPathTypeError(JMESPathError): - function_name: Any + function_name: str current_value: Any - actual_type: Any - expected_types: Any - def __init__(self, function_name, current_value, actual_type, expected_types) -> None: ... + actual_type: str + expected_types: Sequence[str] + def __init__(self, function_name: str, current_value: Any, actual_type: str, expected_types: Sequence[str]) -> None: ... class EmptyExpressionError(JMESPathError): def __init__(self) -> None: ... diff --git a/stubs/jmespath/jmespath/functions.pyi b/stubs/jmespath/jmespath/functions.pyi index b64e9ec2891e..4d657f4c49ea 100644 --- a/stubs/jmespath/jmespath/functions.pyi +++ b/stubs/jmespath/jmespath/functions.pyi @@ -1,13 +1,23 @@ -from typing import Any +from collections.abc import Callable, Iterable +from typing import Any, TypedDict, TypeVar, type_check_only +from typing_extensions import NotRequired -TYPES_MAP: Any -REVERSE_TYPES_MAP: Any +TYPES_MAP: dict[str, str] +REVERSE_TYPES_MAP: dict[str, tuple[str, ...]] -def signature(*arguments): ... +@type_check_only +class _Signature(TypedDict): + types: list[str] + variadic: NotRequired[bool] + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def signature(*arguments: _Signature) -> Callable[[_F], _F]: ... class FunctionRegistry(type): - def __init__(cls, name, bases, attrs) -> None: ... + def __init__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> None: ... -class Functions: +class Functions(metaclass=FunctionRegistry): FUNCTION_TABLE: Any - def call_function(self, function_name, resolved_args): ... + # resolved_args and return value are the *args and return of a function called by name + def call_function(self, function_name: str, resolved_args: Iterable[Any]) -> Any: ... diff --git a/stubs/jmespath/jmespath/lexer.pyi b/stubs/jmespath/jmespath/lexer.pyi index 70696ca8c679..0e26ebc18888 100644 --- a/stubs/jmespath/jmespath/lexer.pyi +++ b/stubs/jmespath/jmespath/lexer.pyi @@ -1,11 +1,19 @@ -from typing import Any +from collections.abc import Iterator +from typing import ClassVar, TypedDict, type_check_only from jmespath.exceptions import EmptyExpressionError as EmptyExpressionError, LexerError as LexerError +@type_check_only +class _LexerTokenizeResult(TypedDict): + type: str + value: str + start: int + end: int + class Lexer: - START_IDENTIFIER: Any - VALID_IDENTIFIER: Any - VALID_NUMBER: Any - WHITESPACE: Any - SIMPLE_TOKENS: Any - def tokenize(self, expression) -> None: ... + START_IDENTIFIER: ClassVar[set[str]] + VALID_IDENTIFIER: ClassVar[set[str]] + VALID_NUMBER: ClassVar[set[str]] + WHITESPACE: ClassVar[set[str]] + SIMPLE_TOKENS: ClassVar[dict[str, str]] + def tokenize(self, expression: str) -> Iterator[_LexerTokenizeResult]: ... diff --git a/stubs/jmespath/jmespath/parser.pyi b/stubs/jmespath/jmespath/parser.pyi index 4e5499e6760e..fc3c7aa9d2be 100644 --- a/stubs/jmespath/jmespath/parser.pyi +++ b/stubs/jmespath/jmespath/parser.pyi @@ -1,15 +1,19 @@ -from typing import Any +from collections.abc import Iterator +from typing import Any, ClassVar + +from jmespath.lexer import _LexerTokenizeResult +from jmespath.visitor import Options, _TreeNode class Parser: - BINDING_POWER: Any - tokenizer: Any - def __init__(self, lookahead: int = ...) -> None: ... - def parse(self, expression): ... + BINDING_POWER: ClassVar[dict[str, int]] + tokenizer: Iterator[_LexerTokenizeResult] | None + def __init__(self, lookahead: int = 2) -> None: ... + def parse(self, expression: str) -> ParsedResult: ... @classmethod def purge(cls) -> None: ... class ParsedResult: - expression: Any - parsed: Any - def __init__(self, expression, parsed) -> None: ... - def search(self, value, options: Any | None = ...): ... + expression: str + parsed: _TreeNode + def __init__(self, expression: str, parsed: _TreeNode) -> None: ... + def search(self, value: Any, options: Options | None = None) -> Any: ... diff --git a/stubs/jmespath/jmespath/visitor.pyi b/stubs/jmespath/jmespath/visitor.pyi index 99e86bc907de..9c5da94684d5 100644 --- a/stubs/jmespath/jmespath/visitor.pyi +++ b/stubs/jmespath/jmespath/visitor.pyi @@ -1,49 +1,67 @@ -from typing import Any +from _typeshed import Unused +from collections.abc import Callable, MutableMapping +from typing import Any, ClassVar, TypedDict, TypeVar, type_check_only +from typing_extensions import Never + +from jmespath.functions import Functions + +_T = TypeVar("_T") class Options: - dict_cls: Any - custom_functions: Any - def __init__(self, dict_cls: Any | None = ..., custom_functions: Any | None = ...) -> None: ... + dict_cls: Callable[[], MutableMapping[Any, Any]] | None + custom_functions: Functions | None + def __init__( + self, dict_cls: Callable[[], MutableMapping[Any, Any]] | None = None, custom_functions: Functions | None = None + ) -> None: ... class _Expression: - expression: Any - interpreter: Any - def __init__(self, expression, interpreter) -> None: ... - def visit(self, node, *args, **kwargs): ... + expression: str + interpreter: Visitor + def __init__(self, expression: str, interpreter: Visitor) -> None: ... + # `args` and `kwargs` are passed to the appropriate `visit_*` method. + def visit(self, node: _TreeNode, *args: Any, **kwargs: Any) -> Any: ... class Visitor: def __init__(self) -> None: ... - def visit(self, node, *args, **kwargs): ... - def default_visit(self, node, *args, **kwargs) -> None: ... + # `args` and `kwargs` are passed to the appropriate `visit_*` method. + # Its return value is returned from visit. + def visit(self, node: _TreeNode, *args: Any, **kwargs: Any) -> Any: ... + def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> Never: ... + +@type_check_only +class _TreeNode(TypedDict): + type: str + value: Any + children: list[_TreeNode] class TreeInterpreter(Visitor): - COMPARATOR_FUNC: Any - MAP_TYPE: Any - def __init__(self, options: Any | None = ...) -> None: ... - def default_visit(self, node, *args, **kwargs) -> None: ... - def visit_subexpression(self, node, value): ... - def visit_field(self, node, value): ... - def visit_comparator(self, node, value): ... - def visit_current(self, node, value): ... - def visit_expref(self, node, value): ... - def visit_function_expression(self, node, value): ... - def visit_filter_projection(self, node, value): ... - def visit_flatten(self, node, value): ... - def visit_identity(self, node, value): ... - def visit_index(self, node, value): ... - def visit_index_expression(self, node, value): ... - def visit_slice(self, node, value): ... - def visit_key_val_pair(self, node, value): ... - def visit_literal(self, node, value): ... - def visit_multi_select_dict(self, node, value): ... - def visit_multi_select_list(self, node, value): ... - def visit_or_expression(self, node, value): ... - def visit_and_expression(self, node, value): ... - def visit_not_expression(self, node, value): ... - def visit_pipe(self, node, value): ... - def visit_projection(self, node, value): ... - def visit_value_projection(self, node, value): ... + COMPARATOR_FUNC: ClassVar[dict[str, Callable[[Any, Any], Any]]] + MAP_TYPE: ClassVar[Callable[[], MutableMapping[Any, Any]]] + def __init__(self, options: Options | None = None) -> None: ... + def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> Never: ... + def visit_subexpression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_field(self, node: _TreeNode, value: Any) -> Any: ... + def visit_comparator(self, node: _TreeNode, value: Any) -> Any: ... + def visit_current(self, node: _TreeNode, value: _T) -> _T: ... + def visit_expref(self, node: _TreeNode, value: Any) -> _Expression: ... + def visit_function_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_filter_projection(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + def visit_flatten(self, node: _TreeNode, value: Any) -> Any: ... + def visit_identity(self, node: _TreeNode, value: _T) -> _T: ... + def visit_index(self, node: _TreeNode, value: Any) -> Any: ... + def visit_index_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_slice(self, node: _TreeNode, value: Any) -> Any: ... + def visit_key_val_pair(self, node: _TreeNode, value: Any) -> Any: ... + def visit_literal(self, node: _TreeNode, value: Any) -> Any: ... + def visit_multi_select_dict(self, node: _TreeNode, value: Any) -> Any: ... + def visit_multi_select_list(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + def visit_or_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_and_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_not_expression(self, node: _TreeNode, value: Any) -> bool: ... + def visit_pipe(self, node: _TreeNode, value: Any) -> Any: ... + def visit_projection(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + def visit_value_projection(self, node: _TreeNode, value: Any) -> list[Any] | None: ... class GraphvizVisitor(Visitor): def __init__(self) -> None: ... - def visit(self, node, *args, **kwargs): ... + def visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> str: ... diff --git a/stubs/jsonnet/METADATA.toml b/stubs/jsonnet/METADATA.toml new file mode 100644 index 000000000000..60c7cdd7f4e4 --- /dev/null +++ b/stubs/jsonnet/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.22.*" +upstream-repository = "https://github.com/google/jsonnet" diff --git a/stubs/jsonnet/_jsonnet.pyi b/stubs/jsonnet/_jsonnet.pyi new file mode 100644 index 000000000000..cad86c28b9d1 --- /dev/null +++ b/stubs/jsonnet/_jsonnet.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from typing import Final + +# Gleaned from https://github.com/google/jsonnet/blob/master/python/_jsonnet.c +version: Final[str] + +def evaluate_file( + filename: str, + jpathdir: str | list[str] | None = ..., + max_stack: int = 500, + gc_min_objects: int = 1000, + gc_growth_trigger: float = 2, + ext_vars: dict[str, str] | None = ..., + ext_codes: dict[str, str] | None = ..., + tla_vars: dict[str, str] | None = ..., + tla_codes: dict[str, str] | None = ..., + max_trace: int = 20, + import_callback: Callable[[str, str], tuple[str, object | None]] = ..., + native_callbacks: dict[str, tuple[tuple[str, ...], Callable[..., object]]] | None = ..., +) -> str: ... +def evaluate_snippet( + filename: str, + src: str, + jpathdir: str | list[str] | None = ..., + max_stack: int = 500, + gc_min_objects: int = 1000, + gc_growth_trigger: float = 2, + ext_vars: dict[str, str] | None = ..., + ext_codes: dict[str, str] | None = ..., + tla_vars: dict[str, str] | None = ..., + tla_codes: dict[str, str] | None = ..., + max_trace: int = 20, + import_callback: Callable[[str, str], tuple[str, object | None]] = ..., + native_callbacks: dict[str, tuple[tuple[str, ...], Callable[..., object]]] | None = ..., +) -> str: ... diff --git a/stubs/jsonschema/@tests/stubtest_allowlist.txt b/stubs/jsonschema/@tests/stubtest_allowlist.txt index 48d08e94735c..0df25c11cc77 100644 --- a/stubs/jsonschema/@tests/stubtest_allowlist.txt +++ b/stubs/jsonschema/@tests/stubtest_allowlist.txt @@ -1,14 +1,35 @@ -jsonschema._format.is_css21_color -jsonschema._format.is_css_color_code -jsonschema._format.is_datetime -jsonschema._format.is_duration -jsonschema._format.is_host_name -jsonschema._format.is_idn_host_name -jsonschema._format.is_iri -jsonschema._format.is_iri_reference -jsonschema._format.is_json_pointer -jsonschema._format.is_relative_json_pointer -jsonschema._format.is_time -jsonschema._format.is_uri -jsonschema._format.is_uri_reference -jsonschema._format.is_uri_template +# Testing modules are not included in type stubs: +jsonschema.tests.* +jsonschema.benchmarks.* + +# When importing this module, SystemExit: 2 is thrown: +jsonschema.__main__ + +# Autogenerated methods using @attr.* decorators: +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_post_init__ +.*\.__attrs_props__ +jsonschema._types.TypeChecker.__match_args__ +jsonschema.cli._Outputter.__match_args__ +jsonschema.cli._PlainFormatter.__match_args__ +jsonschema.cli._PrettyFormatter.__match_args__ +jsonschema.exceptions.RefResolutionError.__match_args__ +jsonschema.validators.Draft201909Validator.__match_args__ +jsonschema.validators.Draft202012Validator.__match_args__ +jsonschema.validators.Draft3Validator.__match_args__ +jsonschema.validators.Draft4Validator.__match_args__ +jsonschema.validators.Draft6Validator.__match_args__ +jsonschema.validators.Draft7Validator.__match_args__ +# >= Python 3.13 +jsonschema._types.TypeChecker.__replace__ +jsonschema.cli._Outputter.__replace__ +jsonschema.cli._PlainFormatter.__replace__ +jsonschema.cli._PrettyFormatter.__replace__ +jsonschema.exceptions.RefResolutionError.__replace__ +jsonschema.validators.Draft201909Validator.__replace__ +jsonschema.validators.Draft202012Validator.__replace__ +jsonschema.validators.Draft3Validator.__replace__ +jsonschema.validators.Draft4Validator.__replace__ +jsonschema.validators.Draft6Validator.__replace__ +jsonschema.validators.Draft7Validator.__replace__ diff --git a/stubs/jsonschema/METADATA.toml b/stubs/jsonschema/METADATA.toml index a51d6edb1ccd..a9b3778d2826 100644 --- a/stubs/jsonschema/METADATA.toml +++ b/stubs/jsonschema/METADATA.toml @@ -1 +1,6 @@ -version = "4.3.*" +version = "~=4.26.0" +upstream-repository = "https://github.com/python-jsonschema/jsonschema" +dependencies = ["referencing"] + +[tool.stubtest] +extras = ["format"] diff --git a/stubs/jsonschema/jsonschema/__init__.pyi b/stubs/jsonschema/jsonschema/__init__.pyi index dcb925bc6032..61cf92fd5d18 100644 --- a/stubs/jsonschema/jsonschema/__init__.pyi +++ b/stubs/jsonschema/jsonschema/__init__.pyi @@ -26,3 +26,17 @@ from jsonschema.validators import ( RefResolver as RefResolver, validate as validate, ) + +__all__ = [ + "Draft3Validator", + "Draft4Validator", + "Draft6Validator", + "Draft7Validator", + "Draft201909Validator", + "Draft202012Validator", + "FormatChecker", + "SchemaError", + "TypeChecker", + "ValidationError", + "validate", +] diff --git a/stubs/jsonschema/jsonschema/_format.pyi b/stubs/jsonschema/jsonschema/_format.pyi index 492800ab5190..9204059bee6d 100644 --- a/stubs/jsonschema/jsonschema/_format.pyi +++ b/stubs/jsonschema/jsonschema/_format.pyi @@ -1,12 +1,19 @@ -from typing import Any, Iterable +from collections.abc import Callable, Iterable +from typing import TypeAlias, TypeVar + +_FormatCheckCallable: TypeAlias = Callable[[object], bool] +_F = TypeVar("_F", bound=_FormatCheckCallable) +_RaisesType: TypeAlias = type[Exception] | tuple[type[Exception], ...] class FormatChecker: - checkers: Any - def __init__(self, formats: Iterable[str] | None = ...) -> None: ... - def checks(self, format, raises=...): ... - cls_checks: Any - def check(self, instance, format) -> None: ... - def conforms(self, instance, format) -> bool: ... + checkers: dict[str, tuple[_FormatCheckCallable, _RaisesType]] + + def __init__(self, formats: Iterable[str] | None = None) -> None: ... + def checks(self, format: str, raises: _RaisesType = ()) -> Callable[[_F], _F]: ... + @classmethod + def cls_checks(cls, format: str, raises: _RaisesType = ()) -> Callable[[_F], _F]: ... + def check(self, instance: object, format: str) -> None: ... + def conforms(self, instance: object, format: str) -> bool: ... draft3_format_checker: FormatChecker draft4_format_checker: FormatChecker @@ -15,28 +22,27 @@ draft7_format_checker: FormatChecker draft201909_format_checker: FormatChecker draft202012_format_checker: FormatChecker -def is_email(instance) -> bool: ... -def is_ipv4(instance) -> bool: ... -def is_ipv6(instance) -> bool: ... +def is_email(instance: object) -> bool: ... +def is_ipv4(instance: object) -> bool: ... +def is_ipv6(instance: object) -> bool: ... # is_host_name is only defined if fqdn is installed. -def is_host_name(instance) -> bool: ... -def is_idn_host_name(instance) -> bool: ... -def is_uri(instance) -> bool: ... -def is_uri_reference(instance) -> bool: ... -def is_iri(instance) -> bool: ... -def is_iri_reference(instance) -> bool: ... -def is_datetime(instance) -> bool: ... -def is_time(instance) -> bool: ... -def is_regex(instance) -> bool: ... -def is_date(instance) -> bool: ... -def is_draft3_time(instance) -> bool: ... -def is_css_color_code(instance) -> bool: ... -def is_css21_color(instance) -> bool: ... -def is_json_pointer(instance) -> bool: ... -def is_relative_json_pointer(instance) -> bool: ... -def is_uri_template(instance) -> bool: ... +def is_host_name(instance: object) -> bool: ... +def is_idn_host_name(instance: object) -> bool: ... +def is_uri(instance: object) -> bool: ... +def is_uri_reference(instance: object) -> bool: ... +def is_iri(instance: object) -> bool: ... +def is_iri_reference(instance: object) -> bool: ... +def is_datetime(instance: object) -> bool: ... +def is_time(instance: object) -> bool: ... +def is_regex(instance: object) -> bool: ... +def is_date(instance: object) -> bool: ... +def is_draft3_time(instance: object) -> bool: ... +def is_css21_color(instance: object) -> bool: ... +def is_json_pointer(instance: object) -> bool: ... +def is_relative_json_pointer(instance: object) -> bool: ... +def is_uri_template(instance: object) -> bool: ... # is_duration is only defined if isoduration is installed. -def is_duration(instance) -> bool: ... -def is_uuid(instance) -> bool: ... +def is_duration(instance: object) -> bool: ... +def is_uuid(instance: object) -> bool: ... diff --git a/stubs/jsonschema/jsonschema/_keywords.pyi b/stubs/jsonschema/jsonschema/_keywords.pyi new file mode 100644 index 000000000000..3d050a93933a --- /dev/null +++ b/stubs/jsonschema/jsonschema/_keywords.pyi @@ -0,0 +1,36 @@ +def patternProperties(validator, patternProperties, instance, schema) -> None: ... +def propertyNames(validator, propertyNames, instance, schema) -> None: ... +def additionalProperties(validator, aP, instance, schema) -> None: ... +def items(validator, items, instance, schema) -> None: ... +def const(validator, const, instance, schema) -> None: ... +def contains(validator, contains, instance, schema) -> None: ... +def exclusiveMinimum(validator, minimum, instance, schema) -> None: ... +def exclusiveMaximum(validator, maximum, instance, schema) -> None: ... +def minimum(validator, minimum, instance, schema) -> None: ... +def maximum(validator, maximum, instance, schema) -> None: ... +def multipleOf(validator, dB, instance, schema) -> None: ... +def minItems(validator, mI, instance, schema) -> None: ... +def maxItems(validator, mI, instance, schema) -> None: ... +def uniqueItems(validator, uI, instance, schema) -> None: ... +def pattern(validator, patrn, instance, schema) -> None: ... +def format(validator, format, instance, schema) -> None: ... +def minLength(validator, mL, instance, schema) -> None: ... +def maxLength(validator, mL, instance, schema) -> None: ... +def dependentRequired(validator, dependentRequired, instance, schema) -> None: ... +def dependentSchemas(validator, dependentSchemas, instance, schema) -> None: ... +def enum(validator, enums, instance, schema) -> None: ... +def ref(validator, ref, instance, schema) -> None: ... +def dynamicRef(validator, dynamicRef, instance, schema) -> None: ... +def type(validator, types, instance, schema) -> None: ... +def properties(validator, properties, instance, schema) -> None: ... +def required(validator, required, instance, schema) -> None: ... +def minProperties(validator, mP, instance, schema) -> None: ... +def maxProperties(validator, mP, instance, schema) -> None: ... +def allOf(validator, allOf, instance, schema) -> None: ... +def anyOf(validator, anyOf, instance, schema) -> None: ... +def oneOf(validator, oneOf, instance, schema) -> None: ... +def not_(validator, not_schema, instance, schema) -> None: ... +def if_(validator, if_schema, instance, schema) -> None: ... +def unevaluatedItems(validator, unevaluatedItems, instance, schema) -> None: ... +def unevaluatedProperties(validator, unevaluatedProperties, instance, schema) -> None: ... +def prefixItems(validator, prefixItems, instance, schema) -> None: ... diff --git a/stubs/jsonschema/jsonschema/_legacy_keywords.pyi b/stubs/jsonschema/jsonschema/_legacy_keywords.pyi new file mode 100644 index 000000000000..e2898f8ed015 --- /dev/null +++ b/stubs/jsonschema/jsonschema/_legacy_keywords.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from collections.abc import ItemsView, Iterator + +from .exceptions import ValidationError + +def ignore_ref_siblings(schema) -> list[tuple[str, Incomplete]] | ItemsView[str, Incomplete]: ... +def dependencies_draft3(validator, dependencies, instance, schema) -> None: ... +def dependencies_draft4_draft6_draft7(validator, dependencies, instance, schema) -> None: ... +def disallow_draft3(validator, disallow, instance, schema) -> None: ... +def extends_draft3(validator, extends, instance, schema) -> None: ... +def items_draft3_draft4(validator, items, instance, schema) -> None: ... +def additionalItems(validator, aI, instance, schema) -> None: ... +def items_draft6_draft7_draft201909(validator, items, instance, schema) -> None: ... +def minimum_draft3_draft4(validator, minimum, instance, schema) -> None: ... +def maximum_draft3_draft4(validator, maximum, instance, schema) -> None: ... +def properties_draft3(validator, properties, instance, schema) -> None: ... +def type_draft3(validator, types, instance, schema) -> None: ... +def contains_draft6_draft7(validator, contains, instance, schema) -> None: ... +def recursiveRef(validator, recursiveRef, instance, schema) -> None: ... +def find_evaluated_item_indexes_by_schema(validator, instance, schema) -> list[int]: ... +def unevaluatedItems_draft2019(validator, unevaluatedItems, instance, schema) -> Iterator[ValidationError]: ... +def find_evaluated_property_keys_by_schema(validator, instance, schema) -> list[Incomplete]: ... +def unevaluatedProperties_draft2019(validator, uP, instance, schema) -> Iterator[ValidationError]: ... diff --git a/stubs/jsonschema/jsonschema/_legacy_validators.pyi b/stubs/jsonschema/jsonschema/_legacy_validators.pyi deleted file mode 100644 index 08a7dd5394ea..000000000000 --- a/stubs/jsonschema/jsonschema/_legacy_validators.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any, ItemsView - -def ignore_ref_siblings(schema) -> list[tuple[str, Any]] | ItemsView[str, Any]: ... -def dependencies_draft3(validator, dependencies, instance, schema) -> None: ... -def dependencies_draft4_draft6_draft7(validator, dependencies, instance, schema) -> None: ... -def disallow_draft3(validator, disallow, instance, schema) -> None: ... -def extends_draft3(validator, extends, instance, schema) -> None: ... -def items_draft3_draft4(validator, items, instance, schema) -> None: ... -def items_draft6_draft7_draft201909(validator, items, instance, schema) -> None: ... -def minimum_draft3_draft4(validator, minimum, instance, schema) -> None: ... -def maximum_draft3_draft4(validator, maximum, instance, schema) -> None: ... -def properties_draft3(validator, properties, instance, schema) -> None: ... -def type_draft3(validator, types, instance, schema) -> None: ... -def contains_draft6_draft7(validator, contains, instance, schema) -> None: ... -def recursiveRef(validator, recursiveRef, instance, schema) -> None: ... diff --git a/stubs/jsonschema/jsonschema/_reflect.pyi b/stubs/jsonschema/jsonschema/_reflect.pyi deleted file mode 100644 index a19c6f9d8bf2..000000000000 --- a/stubs/jsonschema/jsonschema/_reflect.pyi +++ /dev/null @@ -1,7 +0,0 @@ -class _NoModuleFound(Exception): ... -class InvalidName(ValueError): ... -class ModuleNotFound(InvalidName): ... -class ObjectNotFound(InvalidName): ... - -def reraise(exception, traceback) -> None: ... -def namedAny(name): ... diff --git a/stubs/jsonschema/jsonschema/_types.pyi b/stubs/jsonschema/jsonschema/_types.pyi index 5c97055445e0..a4fa843f195c 100644 --- a/stubs/jsonschema/jsonschema/_types.pyi +++ b/stubs/jsonschema/jsonschema/_types.pyi @@ -1,19 +1,22 @@ -from typing import Callable, Iterable, Mapping +from _typeshed import Unused +from collections.abc import Callable, Iterable, Mapping +from typing import Literal -def is_array(checker, instance) -> bool: ... -def is_bool(checker, instance) -> bool: ... -def is_integer(checker, instance) -> bool: ... -def is_null(checker, instance) -> bool: ... -def is_number(checker, instance) -> bool: ... -def is_object(checker, instance) -> bool: ... -def is_string(checker, instance) -> bool: ... -def is_any(checker, instance) -> bool: ... +def is_array(checker: Unused, instance: object) -> bool: ... +def is_bool(checker: Unused, instance: object) -> bool: ... +def is_integer(checker: Unused, instance: object) -> bool: ... +def is_null(checker: Unused, instance: object) -> bool: ... +def is_number(checker: Unused, instance: object) -> bool: ... +def is_object(checker: Unused, instance: object) -> bool: ... +def is_string(checker: Unused, instance: object) -> bool: ... +def is_any(checker: Unused, instance: Unused) -> Literal[True]: ... class TypeChecker: + __slots__ = ("_type_checkers", "__weakref__") def __init__(self, type_checkers: Mapping[str, Callable[[object], bool]] = ...) -> None: ... def is_type(self, instance, type: str) -> bool: ... def redefine(self, type: str, fn: Callable[..., bool]) -> TypeChecker: ... - def redefine_many(self, definitions=...) -> TypeChecker: ... + def redefine_many(self, definitions=()) -> TypeChecker: ... def remove(self, *types: Iterable[str]) -> TypeChecker: ... draft3_type_checker: TypeChecker diff --git a/stubs/jsonschema/jsonschema/_typing.pyi b/stubs/jsonschema/jsonschema/_typing.pyi new file mode 100644 index 000000000000..78e946676d79 --- /dev/null +++ b/stubs/jsonschema/jsonschema/_typing.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable, Iterable +from typing import Any, Protocol, TypeAlias + +from jsonschema.protocols import Validator +from referencing.jsonschema import Schema + +class SchemaKeywordValidator(Protocol): + def __call__(self, validator: Validator, value: Any, instance: Any, schema: Schema) -> None: ... + +id_of: TypeAlias = Callable[[Schema], str | None] # noqa: Y042 + +ApplicableValidators: TypeAlias = Callable[[Schema], Iterable[tuple[str, Any]]] diff --git a/stubs/jsonschema/jsonschema/_utils.pyi b/stubs/jsonschema/jsonschema/_utils.pyi index 448be7e91cfa..cc0a4f062227 100644 --- a/stubs/jsonschema/jsonschema/_utils.pyi +++ b/stubs/jsonschema/jsonschema/_utils.pyi @@ -1,24 +1,38 @@ -from typing import Any, Generator, Iterable, Mapping, MutableMapping, Sized +from _typeshed import Incomplete, SupportsNext, SupportsRichComparison +from collections.abc import Generator, Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Literal, TypeVar, overload -class URIDict(MutableMapping[Any, Any]): +_T = TypeVar("_T") + +class URIDict(MutableMapping[str, MutableMapping[str, Any]]): def normalize(self, uri: str) -> str: ... - store: dict[Any, Any] - def __init__(self, *args, **kwargs) -> None: ... - def __getitem__(self, uri): ... - def __setitem__(self, uri, value) -> None: ... - def __delitem__(self, uri) -> None: ... - def __iter__(self): ... - def __len__(self): ... + store: dict[str, MutableMapping[str, Any]] + def __init__( + self, + m: Mapping[str, MutableMapping[str, Any]] | Iterable[tuple[str, MutableMapping[str, Any]]], + /, + **kwargs: MutableMapping[str, Any], + ) -> None: ... + def __getitem__(self, uri: str) -> MutableMapping[str, Any]: ... + def __setitem__(self, uri: str, value: MutableMapping[str, Any]) -> None: ... + def __delitem__(self, uri: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... class Unset: ... -def load_schema(name): ... -def format_as_index(container: str, indices) -> str: ... -def find_additional_properties(instance: Iterable[Any], schema: Mapping[Any, Any]) -> Generator[Any, None, None]: ... -def extras_msg(extras: Iterable[Any] | Sized) -> str: ... -def ensure_list(thing) -> list[Any]: ... +def format_as_index(container: str, indices: Iterable[Incomplete] | None) -> str: ... +def find_additional_properties(instance: Iterable[str], schema: Mapping[str, Iterable[str]]) -> Generator[str]: ... +def extras_msg(extras: Iterable[object]) -> tuple[str, Literal["was", "were"]]: ... # elements are passed to the repr() function + +@overload +def ensure_list(thing: str) -> list[str]: ... +@overload +def ensure_list(thing: _T) -> _T: ... + def equal(one, two) -> bool: ... def unbool(element, true=..., false=...): ... -def uniq(container) -> bool: ... -def find_evaluated_item_indexes_by_schema(validator, instance, schema) -> list[Any]: ... -def find_evaluated_property_keys_by_schema(validator, instance, schema) -> list[Any]: ... +def uniq(container: Iterable[SupportsRichComparison]) -> bool: ... +def find_evaluated_item_indexes_by_schema(validator, instance, schema) -> list[Incomplete]: ... +def find_evaluated_property_keys_by_schema(validator, instance, schema) -> list[Incomplete]: ... +def is_valid(errs_it: SupportsNext[object]) -> bool: ... diff --git a/stubs/jsonschema/jsonschema/_validators.pyi b/stubs/jsonschema/jsonschema/_validators.pyi deleted file mode 100644 index f6daf12685ea..000000000000 --- a/stubs/jsonschema/jsonschema/_validators.pyi +++ /dev/null @@ -1,37 +0,0 @@ -def patternProperties(validator, patternProperties, instance, schema) -> None: ... -def propertyNames(validator, propertyNames, instance, schema) -> None: ... -def additionalProperties(validator, aP, instance, schema) -> None: ... -def items(validator, items, instance, schema) -> None: ... -def additionalItems(validator, aI, instance, schema) -> None: ... -def const(validator, const, instance, schema) -> None: ... -def contains(validator, contains, instance, schema) -> None: ... -def exclusiveMinimum(validator, minimum, instance, schema) -> None: ... -def exclusiveMaximum(validator, maximum, instance, schema) -> None: ... -def minimum(validator, minimum, instance, schema) -> None: ... -def maximum(validator, maximum, instance, schema) -> None: ... -def multipleOf(validator, dB, instance, schema) -> None: ... -def minItems(validator, mI, instance, schema) -> None: ... -def maxItems(validator, mI, instance, schema) -> None: ... -def uniqueItems(validator, uI, instance, schema) -> None: ... -def pattern(validator, patrn, instance, schema) -> None: ... -def format(validator, format, instance, schema) -> None: ... -def minLength(validator, mL, instance, schema) -> None: ... -def maxLength(validator, mL, instance, schema) -> None: ... -def dependentRequired(validator, dependentRequired, instance, schema) -> None: ... -def dependentSchemas(validator, dependentSchemas, instance, schema) -> None: ... -def enum(validator, enums, instance, schema) -> None: ... -def ref(validator, ref, instance, schema) -> None: ... -def dynamicRef(validator, dynamicRef, instance, schema) -> None: ... -def type(validator, types, instance, schema) -> None: ... -def properties(validator, properties, instance, schema) -> None: ... -def required(validator, required, instance, schema) -> None: ... -def minProperties(validator, mP, instance, schema) -> None: ... -def maxProperties(validator, mP, instance, schema) -> None: ... -def allOf(validator, allOf, instance, schema) -> None: ... -def anyOf(validator, anyOf, instance, schema) -> None: ... -def oneOf(validator, oneOf, instance, schema) -> None: ... -def not_(validator, not_schema, instance, schema) -> None: ... -def if_(validator, if_schema, instance, schema) -> None: ... -def unevaluatedItems(validator, unevaluatedItems, instance, schema) -> None: ... -def unevaluatedProperties(validator, unevaluatedProperties, instance, schema) -> None: ... -def prefixItems(validator, prefixItems, instance, schema) -> None: ... diff --git a/stubs/jsonschema/jsonschema/cli.pyi b/stubs/jsonschema/jsonschema/cli.pyi index 85c3bd71d0a2..3d640e236fb6 100644 --- a/stubs/jsonschema/jsonschema/cli.pyi +++ b/stubs/jsonschema/jsonschema/cli.pyi @@ -1,32 +1,65 @@ +import argparse +from _typeshed import ExcInfo, FileDescriptorOrPath, Incomplete, OptExcInfo, SupportsWrite +from collections.abc import Mapping, Sequence from typing import Any +from typing_extensions import Self, deprecated +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") class _CannotLoadFile(Exception): ... +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") class _Outputter: - def __init__(self, formatter, stdout, stderr): ... + __slots__ = ("_formatter", "_stdout", "_stderr", "__weakref__") + _formatter: _PlainFormatter | _PrettyFormatter + _stdout: SupportsWrite[str] + _stderr: SupportsWrite[str] + + def __init__( + self, formatter: _PlainFormatter | _PrettyFormatter, stdout: SupportsWrite[str], stderr: SupportsWrite[str] + ) -> None: ... @classmethod - def from_arguments(cls, arguments, stdout, stderr): ... - def load(self, path): ... - def filenotfound_error(self, **kwargs) -> None: ... - def parsing_error(self, **kwargs) -> None: ... - def validation_error(self, **kwargs) -> None: ... - def validation_success(self, **kwargs) -> None: ... + def from_arguments( + cls, arguments: Mapping[str, Incomplete], stdout: SupportsWrite[str], stderr: SupportsWrite[str] + ) -> Self: ... + def load(self, path: FileDescriptorOrPath) -> Any: ... # result of json.load() + def filenotfound_error(self, *, path: FileDescriptorOrPath, exc_info: OptExcInfo) -> None: ... + def parsing_error(self, *, path: FileDescriptorOrPath, exc_info: ExcInfo) -> None: ... + def validation_error(self, *, instance_path: FileDescriptorOrPath, error: BaseException) -> None: ... + def validation_success(self, *, instance_path: FileDescriptorOrPath) -> None: ... +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") class _PrettyFormatter: - def filenotfound_error(self, path, exc_info): ... - def parsing_error(self, path, exc_info): ... - def validation_error(self, instance_path, error): ... - def validation_success(self, instance_path): ... + __slots__ = ("__weakref__",) + _ERROR_MSG: str + _SUCCESS_MSG: str + + def __init__(self) -> None: ... + def filenotfound_error(self, path: FileDescriptorOrPath, exc_info: OptExcInfo) -> str: ... + def parsing_error(self, path: FileDescriptorOrPath, exc_info: ExcInfo) -> str: ... + def validation_error(self, instance_path: FileDescriptorOrPath, error: BaseException) -> str: ... + def validation_success(self, instance_path: FileDescriptorOrPath) -> str: ... +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") class _PlainFormatter: - def __init__(self, error_format): ... - def filenotfound_error(self, path, exc_info): ... - def parsing_error(self, path, exc_info): ... - def validation_error(self, instance_path, error): ... - def validation_success(self, instance_path): ... + __slots__ = ("_error_format", "__weakref__") + _error_format: str + + def __init__(self, error_format: str) -> None: ... + def filenotfound_error(self, path: FileDescriptorOrPath, exc_info: OptExcInfo) -> str: ... + def parsing_error(self, path: FileDescriptorOrPath, exc_info: ExcInfo) -> str: ... + def validation_error(self, instance_path: FileDescriptorOrPath, error: BaseException) -> str: ... + def validation_success(self, instance_path: FileDescriptorOrPath) -> str: ... -parser: Any +parser: argparse.ArgumentParser -def parse_args(args): ... -def main(args=...) -> None: ... -def run(arguments, stdout=..., stderr=..., stdin=...): ... +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +def parse_args(args: Sequence[str] | None) -> dict[str, Any]: ... # result of vars(argparse.Namespace()) +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +def main(args: Sequence[str] = ...) -> None: ... +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +def run( + arguments: Mapping[str, Incomplete], + stdout: SupportsWrite[str] = ..., + stderr: SupportsWrite[str] = ..., + stdin: SupportsWrite[str] = ..., +) -> int: ... diff --git a/stubs/jsonschema/jsonschema/exceptions.pyi b/stubs/jsonschema/jsonschema/exceptions.pyi index 466264dbbf0c..937a03e2587a 100644 --- a/stubs/jsonschema/jsonschema/exceptions.pyi +++ b/stubs/jsonschema/jsonschema/exceptions.pyi @@ -1,40 +1,55 @@ -from typing import Any +from _typeshed import Incomplete, SupportsRichComparison, sentinel +from collections import deque +from collections.abc import Callable, Container, Iterable, Iterator, Mapping, MutableMapping, Sequence +from typing import Any, TypeAlias +from typing_extensions import Self, deprecated -WEAK_MATCHES: Any -STRONG_MATCHES: Any +from ._types import TypeChecker +from ._utils import Unset + +_RelevanceFuncType: TypeAlias = Callable[[ValidationError], SupportsRichComparison] + +WEAK_MATCHES: frozenset[str] +STRONG_MATCHES: frozenset[str] class _Error(Exception): - message: Any - path: Any - schema_path: Any - context: Any - cause: Any - validator: Any - validator_value: Any - instance: Any - schema: Any - parent: Any + message: str + path: deque[str | int] + relative_path: deque[str | int] + schema_path: deque[str | int] + relative_schema_path: deque[str | int] + context: list[ValidationError] + cause: Exception | None + validator: str | Unset + validator_value: Any | Unset + instance: Any | Unset + schema: Mapping[str, Any] | bool | Unset + parent: _Error | None def __init__( self, - message, - validator=..., - path=..., - cause: Any | None = ..., - context=..., - validator_value=..., - instance=..., - schema=..., - schema_path=..., - parent: Any | None = ..., + message: str, + validator: str | Unset = sentinel, + path: Iterable[str | int] = (), + cause: Exception | None = None, + context: Sequence[ValidationError] = (), + validator_value: Any | Unset = sentinel, + instance: Any | Unset = sentinel, + schema: Mapping[str, Any] | bool | Unset = sentinel, + schema_path: Iterable[str | int] = (), + parent: _Error | None = None, + type_checker: TypeChecker | Unset = sentinel, ) -> None: ... @classmethod - def create_from(cls, other): ... + def create_from(cls, other: _Error) -> Self: ... @property - def absolute_path(self): ... + def absolute_path(self) -> Sequence[str | int]: ... @property - def absolute_schema_path(self): ... + def absolute_schema_path(self) -> Sequence[str | int]: ... @property - def json_path(self): ... + def json_path(self) -> str: ... + # TODO: this type could be made more precise using TypedDict to + # enumerate the types of the members + def _contents(self) -> dict[str, Incomplete]: ... class ValidationError(_Error): ... class SchemaError(_Error): ... @@ -43,33 +58,34 @@ class RefResolutionError(Exception): def __init__(self, cause: str) -> None: ... class UndefinedTypeCheck(Exception): - type: Any + type: Incomplete def __init__(self, type) -> None: ... class UnknownType(Exception): - type: Any - instance: Any - schema: Any + type: Incomplete + instance: Incomplete + schema: Incomplete def __init__(self, type, instance, schema) -> None: ... class FormatError(Exception): - message: Any - cause: Any - def __init__(self, message, cause: Any | None = ...) -> None: ... + message: Incomplete + cause: Incomplete + def __init__(self, message, cause=None) -> None: ... class ErrorTree: - errors: Any - def __init__(self, errors=...) -> None: ... - def __contains__(self, index): ... + errors: MutableMapping[str, ValidationError] + def __init__(self, errors: Iterable[ValidationError] = ()) -> None: ... + def __contains__(self, index: object) -> bool: ... def __getitem__(self, index): ... - def __setitem__(self, index, value) -> None: ... - def __iter__(self): ... - def __len__(self): ... + @deprecated("ErrorTree.__setitem__ is deprecated without replacement.") + def __setitem__(self, index: str | int, value: ErrorTree) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... @property def total_errors(self): ... -def by_relevance(weak=..., strong=...): ... +def by_relevance(weak: Container[str] = ..., strong: Container[str] = ...) -> _RelevanceFuncType: ... -relevance: Any +relevance: _RelevanceFuncType -def best_match(errors, key=...): ... +def best_match(errors: Iterable[ValidationError], key: _RelevanceFuncType = ...): ... diff --git a/stubs/jsonschema/jsonschema/protocols.pyi b/stubs/jsonschema/jsonschema/protocols.pyi index 451e4ec67976..237a32f35066 100644 --- a/stubs/jsonschema/jsonschema/protocols.pyi +++ b/stubs/jsonschema/jsonschema/protocols.pyi @@ -1,22 +1,32 @@ -from typing import Any, ClassVar, Iterator, Protocol +from _typeshed import Incomplete +from collections.abc import Iterator, Mapping, Sequence +from typing import Any, ClassVar, Protocol, TypeAlias +import referencing.jsonschema from jsonschema._format import FormatChecker from jsonschema._types import TypeChecker from jsonschema.exceptions import ValidationError -from jsonschema.validators import RefResolver + +_JsonParameter: TypeAlias = str | int | float | bool | Mapping[str, _JsonParameter] | Sequence[_JsonParameter] | None class Validator(Protocol): - META_SCHEMA: ClassVar[dict[Any, Any]] - VALIDATORS: ClassVar[dict[Any, Any]] + META_SCHEMA: ClassVar[dict[Incomplete, Incomplete]] + VALIDATORS: ClassVar[dict[Incomplete, Incomplete]] TYPE_CHECKER: ClassVar[TypeChecker] - schema: dict[Any, Any] | bool + FORMAT_CHECKER: ClassVar[FormatChecker] + schema: referencing.jsonschema.Schema def __init__( - self, schema: dict[Any, Any] | bool, resolver: RefResolver | None = ..., format_checker: FormatChecker | None = ... + self, + schema: Mapping[Incomplete, Incomplete] | bool, + resolver: Any = None, # deprecated + format_checker: FormatChecker | None = None, + *, + registry: referencing.jsonschema.SchemaRegistry = ..., ) -> None: ... @classmethod - def check_schema(cls, schema: dict[Any, Any]) -> None: ... - def is_type(self, instance: Any, type: str) -> bool: ... - def is_valid(self, instance: dict[Any, Any]) -> bool: ... - def iter_errors(self, instance: dict[Any, Any]) -> Iterator[ValidationError]: ... - def validate(self, instance: dict[Any, Any]) -> None: ... - def evolve(self, **kwargs) -> "Validator": ... + def check_schema(cls, schema: dict[Incomplete, Incomplete]) -> None: ... + def is_type(self, instance: _JsonParameter, type: str) -> bool: ... + def is_valid(self, instance: _JsonParameter) -> bool: ... + def iter_errors(self, instance: _JsonParameter) -> Iterator[ValidationError]: ... + def validate(self, instance: _JsonParameter) -> None: ... + def evolve(self, **kwargs) -> Validator: ... diff --git a/stubs/jsonschema/jsonschema/validators.pyi b/stubs/jsonschema/jsonschema/validators.pyi index 7829021784ac..5d5ab49c6333 100644 --- a/stubs/jsonschema/jsonschema/validators.pyi +++ b/stubs/jsonschema/jsonschema/validators.pyi @@ -1,45 +1,144 @@ -from typing import Any, Callable +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping +from contextlib import contextmanager +from typing import Any, ClassVar, TypeAlias, overload, type_check_only +from typing_extensions import deprecated -def validates(version: str) -> Callable[..., Any]: ... -def create(meta_schema, validators=..., version: Any | None = ..., type_checker=..., id_of=..., applicable_validators=...): ... -def extend(validator, validators=..., version: Any | None = ..., type_checker: Any | None = ...): ... +from referencing.jsonschema import Schema, SchemaRegistry +from referencing.typing import URI -Draft3Validator: Any -Draft4Validator: Any -Draft6Validator: Any -Draft7Validator: Any -Draft201909Validator: Any -Draft202012Validator: Any +from ._format import FormatChecker +from ._types import TypeChecker +from ._utils import Unset, URIDict +from .exceptions import ValidationError +from .protocols import Validator +# these type aliases do not exist at runtime, they're only defined here in the stub +_JsonObject: TypeAlias = Mapping[str, Any] +_JsonValue: TypeAlias = _JsonObject | list[Any] | str | int | float | bool | None +_ValidatorCallback: TypeAlias = Callable[[Any, Any, _JsonValue, _JsonObject], Iterator[ValidationError]] + +# This class does not exist at runtime. Compatible classes are created at +# runtime by create(). +@type_check_only +class _Validator(Validator): + VALIDATORS: ClassVar[dict[Incomplete, Incomplete]] + META_SCHEMA: ClassVar[dict[Incomplete, Incomplete]] + TYPE_CHECKER: ClassVar[Incomplete] + FORMAT_CHECKER: ClassVar[Incomplete] + @staticmethod + def ID_OF(contents: Schema) -> URI | None: ... + schema: Schema + format_checker: FormatChecker | None + def __init__( + self, + schema: Mapping[Incomplete, Incomplete] | bool, + resolver: Any = None, # deprecated + format_checker: FormatChecker | None = None, + *, + registry: SchemaRegistry = ..., + ) -> None: ... + @classmethod + def check_schema(cls, schema: Schema, format_checker: FormatChecker | Unset = ...) -> None: ... + @property + @deprecated( + "Accessing resolver() is deprecated as of v4.18.0, " + "in favor of the https://github.com/python-jsonschema/referencing library." + ) + def resolver(self): ... + def evolve(self, **changes) -> _Validator: ... + + @overload + def iter_errors(self, instance) -> Generator[Incomplete]: ... + @overload + @deprecated("Passing a schema to Validator.iter_errors is deprecated and will be removed in a future release.") + def iter_errors(self, instance, _schema: Schema | None) -> Generator[Incomplete]: ... + + def descend( + self, instance, schema: Schema, path: Incomplete | None = ..., schema_path: Incomplete | None = ..., resolver=None + ) -> Generator[Incomplete]: ... + def validate(self, *args, **kwargs) -> None: ... + def is_type(self, instance, type) -> bool: ... + + @overload + def is_valid(self, instance) -> bool: ... + @overload + @deprecated("Passing a schema to Validator.is_valid is deprecated and will be removed in a future release.") + def is_valid(self, instance, _schema: Schema | None) -> bool: ... + +def validates(version: str) -> Callable[[_Validator], _Validator]: ... +def create( + meta_schema: Schema, + validators: Mapping[str, _ValidatorCallback] | tuple[()] = (), + version=None, + type_checker: TypeChecker = ..., + format_checker: FormatChecker = ..., + id_of: Callable[[Schema], str] = ..., + applicable_validators: Callable[[Schema], Iterable[tuple[str, _ValidatorCallback]]] = ..., +) -> type[_Validator]: ... +def extend(validator, validators=(), version=None, type_checker=None, format_checker=None): ... + +# At runtime these are fields that are assigned the return values of create() calls. +class Draft3Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft4Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft6Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft7Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft201909Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft202012Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +_Handler: TypeAlias = Callable[[str], Incomplete] + +@deprecated( + "jsonschema.RefResolver is deprecated as of v4.18.0, in favor of the " + "https://github.com/python-jsonschema/referencing library, which " + "provides more compliant referencing behavior as well as more " + "flexible APIs for customization. A future release will remove " + "RefResolver. Please file a feature request (on referencing) if you " + "are missing an API for the kind of customization you need." +) class RefResolver: - referrer: Any - cache_remote: Any - handlers: Any - store: Any + referrer: dict[str, Incomplete] + cache_remote: Incomplete + handlers: dict[str, _Handler] + store: URIDict def __init__( self, - base_uri, - referrer, - store=..., - cache_remote: bool = ..., - handlers=..., - urljoin_cache: Any | None = ..., - remote_cache: Any | None = ..., + base_uri: str, + referrer: dict[str, Incomplete], + store: Mapping[str, Mapping[str, Any]] | Iterable[tuple[str, Mapping[str, Any]]] = ..., + cache_remote: bool = True, + handlers: SupportsKeysAndGetItem[str, _Handler] | Iterable[tuple[str, _Handler]] = (), + urljoin_cache=None, + remote_cache=None, ) -> None: ... @classmethod - def from_schema(cls, schema, id_of=..., *args, **kwargs): ... + def from_schema(cls, schema: Schema, id_of=..., *args, **kwargs): ... def push_scope(self, scope) -> None: ... def pop_scope(self) -> None: ... @property def resolution_scope(self): ... @property - def base_uri(self): ... - def in_scope(self, scope) -> None: ... - def resolving(self, ref) -> None: ... - def resolve(self, ref): ... - def resolve_from_url(self, url): ... - def resolve_fragment(self, document, fragment): ... - def resolve_remote(self, uri): ... - -def validate(instance, schema, cls: Any | None = ..., *args, **kwargs) -> None: ... -def validator_for(schema, default=...): ... + def base_uri(self) -> str: ... + @contextmanager + @deprecated("jsonschema.RefResolver.in_scope is deprecated and will be removed in a future release.") + def in_scope(self, scope) -> Generator[None]: ... + @contextmanager + def resolving(self, ref: str) -> Generator[Incomplete]: ... + def resolve(self, ref: str) -> tuple[str, Incomplete]: ... + def resolve_from_url(self, url: str): ... + def resolve_fragment(self, document, fragment: str): ... + def resolve_remote(self, uri: str): ... + +def validate(instance: object, schema: Schema, cls: type[_Validator] | None = None, *args: Any, **kwargs: Any) -> None: ... +def validator_for(schema: Schema | bool, default: type[Validator] | Unset = ...) -> type[Validator]: ... diff --git a/stubs/jwcrypto/@tests/stubtest_allowlist.txt b/stubs/jwcrypto/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..253d414f8eab --- /dev/null +++ b/stubs/jwcrypto/@tests/stubtest_allowlist.txt @@ -0,0 +1,10 @@ +# test code does not need type hints +jwcrypto.tests +jwcrypto.tests-cookbook +jwcrypto.tests_mldsa + +# even if the deprecated decorator is applied, the attribute is not present +jwcrypto.jwt.JWTMissingKeyID.__deprecated__ + +# https://github.com/python/mypy/issues/20160 +(jwcrypto.jwt.JWTMissingKeyID.__init_subclass__)? diff --git a/stubs/jwcrypto/METADATA.toml b/stubs/jwcrypto/METADATA.toml new file mode 100644 index 000000000000..9d270191a056 --- /dev/null +++ b/stubs/jwcrypto/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.6.1" +upstream-repository = "https://github.com/latchset/jwcrypto" +dependencies = ["cryptography"] diff --git a/stdlib/@python2/distutils/command/install_lib.pyi b/stubs/jwcrypto/jwcrypto/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/install_lib.pyi rename to stubs/jwcrypto/jwcrypto/__init__.pyi diff --git a/stubs/jwcrypto/jwcrypto/common.pyi b/stubs/jwcrypto/jwcrypto/common.pyi new file mode 100644 index 000000000000..1deafd70a886 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/common.pyi @@ -0,0 +1,53 @@ +from collections.abc import Callable, Iterator, MutableMapping +from typing import Any, NamedTuple + +from jwcrypto.jwe import JWE +from jwcrypto.jws import JWS + +def base64url_encode(payload: str | bytes) -> str: ... +def base64url_decode(payload: str) -> bytes: ... +def json_encode(string: str | bytes) -> str: ... + +# The function returns json.loads which returns Any +def json_decode(string: str | bytes) -> Any: ... + +class JWException(Exception): ... + +class InvalidJWAAlgorithm(JWException): + def __init__(self, message: str | None = None) -> None: ... + +class InvalidCEKeyLength(JWException): + def __init__(self, expected: int, obtained: int) -> None: ... + +class InvalidJWEData(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWEOperation(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWEKeyType(JWException): + def __init__(self, expected: int, obtained: int) -> None: ... + +class InvalidJWEKeyLength(JWException): + def __init__(self, expected: int, obtained: int) -> None: ... + +class InvalidJWSERegOperation(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWKeyNotFound(JWException): + def __init__(self, message: str | None = None) -> None: ... + +class JWSEHeaderParameter(NamedTuple): + description: str + mustprotect: bool + supported: bool + check_fn: Callable[[JWS | JWE], bool] | None + +class JWSEHeaderRegistry(MutableMapping[str, JWSEHeaderParameter]): + def __init__(self, init_registry: dict[str, JWSEHeaderParameter] | None = None) -> None: ... + def check_header(self, h: str, value: JWS | JWE) -> bool: ... + def __getitem__(self, key: str) -> JWSEHeaderParameter: ... + def __iter__(self) -> Iterator[str]: ... + def __delitem__(self, key: str) -> None: ... + def __setitem__(self, h: str, jwse_header_param: JWSEHeaderParameter) -> None: ... + def __len__(self) -> int: ... diff --git a/stubs/jwcrypto/jwcrypto/jwa.pyi b/stubs/jwcrypto/jwcrypto/jwa.pyi new file mode 100644 index 000000000000..50fdc6d1158d --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwa.pyi @@ -0,0 +1,39 @@ +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from typing import ClassVar, Literal + +default_max_pbkdf2_iterations: int +default_warn_deprecated_algorithms: bool +default_enforce_hmac_key_length: bool + +class JWAAlgorithm(metaclass=ABCMeta): + @property + @abstractmethod + def name(self) -> str: ... + @property + @abstractmethod + def description(self) -> str: ... + @property + @abstractmethod + def keysize(self) -> int: ... + @property + @abstractmethod + def algorithm_usage_location(self) -> str: ... + @property + @abstractmethod + def algorithm_use(self) -> str: ... + status: Literal["active", "deprecated", "prohibited"] + deprecated_by: str | None + @property + def input_keysize(self) -> int: ... + +class JWA: + algorithms_registry: ClassVar[Mapping[str, JWAAlgorithm]] + @classmethod + def instantiate_alg(cls, name: str, use: str | None = None) -> JWAAlgorithm: ... + @classmethod + def signing_alg(cls, name: str) -> JWAAlgorithm: ... + @classmethod + def keymgmt_alg(cls, name: str) -> JWAAlgorithm: ... + @classmethod + def encryption_alg(cls, name: str) -> JWAAlgorithm: ... diff --git a/stubs/jwcrypto/jwcrypto/jwe.pyi b/stubs/jwcrypto/jwcrypto/jwe.pyi new file mode 100644 index 000000000000..6c8ba45c94e6 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwe.pyi @@ -0,0 +1,62 @@ +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Iterable +from typing import Any +from typing_extensions import LiteralString, Self + +from jwcrypto import common +from jwcrypto.common import JWSEHeaderParameter, JWSEHeaderRegistry +from jwcrypto.jwk import JWK, JWKSet + +default_max_compressed_size: int +default_max_plaintext_size: int + +JWEHeaderRegistry: dict[LiteralString, JWSEHeaderParameter] + +default_allowed_algs: list[LiteralString] + +InvalidCEKeyLength = common.InvalidCEKeyLength +InvalidJWEData = common.InvalidJWEData +InvalidJWEKeyLength = common.InvalidJWEKeyLength +InvalidJWEKeyType = common.InvalidJWEKeyType +InvalidJWEOperation = common.InvalidJWEOperation + +class JWE: + objects: dict[str, Any] + plaintext: bytes | None + header_registry: JWSEHeaderRegistry + flattened: bool + cek: Incomplete + decryptlog: list[str] | None + def __init__( + self, + plaintext: str | bytes | None = None, + protected: str | None = None, + unprotected: str | None = None, + aad: bytes | None = None, + algs: list[LiteralString] | None = None, + recipient: str | None = None, + header: str | None = None, + header_registry: ( + SupportsKeysAndGetItem[LiteralString, JWSEHeaderParameter] + | Iterable[tuple[LiteralString, JWSEHeaderParameter]] + | None + ) = None, + flattened: bool = True, + ) -> None: ... + + @property + def allowed_algs(self) -> list[LiteralString]: ... + @allowed_algs.setter + def allowed_algs(self, algs: list[LiteralString]) -> None: ... + + def add_recipient(self, key: JWK, header: dict[str, Any] | str | None = None) -> None: ... + def serialize(self, compact: bool = False) -> str: ... + def decrypt(self, key: JWK | JWKSet, max_plaintext: int = 0) -> None: ... + def deserialize(self, raw_jwe: str | bytes, key: JWK | JWKSet | None = None) -> None: ... + @property + def payload(self) -> bytes: ... + @property + def jose_header(self) -> dict[Incomplete, Incomplete]: ... + @classmethod + def from_jose_token(cls, token: str | bytes) -> Self: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/jwcrypto/jwcrypto/jwk.pyi b/stubs/jwcrypto/jwcrypto/jwk.pyi new file mode 100644 index 000000000000..0ca1ae923cb9 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwk.pyi @@ -0,0 +1,301 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from enum import Enum +from typing import Any, Literal, NamedTuple, TypeAlias, TypeVar, overload +from typing_extensions import LiteralString, Self, deprecated + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, rsa +from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey as Ed448PrivateKey, Ed448PublicKey as Ed448PublicKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey as Ed25519PrivateKey, + Ed25519PublicKey as Ed25519PublicKey, +) +from cryptography.hazmat.primitives.asymmetric.mldsa import ( + MLDSA44PrivateKey as MLDSA44PrivateKey, + MLDSA44PublicKey as MLDSA44PublicKey, + MLDSA65PrivateKey as MLDSA65PrivateKey, + MLDSA65PublicKey as MLDSA65PublicKey, + MLDSA87PrivateKey as MLDSA87PrivateKey, + MLDSA87PublicKey as MLDSA87PublicKey, +) +from cryptography.hazmat.primitives.asymmetric.x448 import X448PrivateKey as X448PrivateKey, X448PublicKey as X448PublicKey +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PrivateKey as X25519PrivateKey, + X25519PublicKey as X25519PublicKey, +) +from jwcrypto.common import JWException + +_T = TypeVar("_T") + +class UnimplementedOKPCurveKey: + @classmethod + def generate(cls): ... + @classmethod + def from_public_bytes(cls, *args): ... + @classmethod + def from_private_bytes(cls, *args): ... + +ImplementedOkpCurves: Sequence[str] +priv_bytes: Callable[[bytes], X25519PrivateKey] | None + +class _Ed25519_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class _Ed448_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class _X25519_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class _X448_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class UnimplementedAKPAlgorithm: + @classmethod + def generate(cls): ... + @classmethod + def from_public_bytes(cls, *args): ... + @classmethod + def from_seed_bytes(cls, *args): ... + +ImplementedAKPAlgorithms: Sequence[str] + +class _AKPAlg(NamedTuple): + pubkey: UnimplementedAKPAlgorithm + privkey: UnimplementedAKPAlgorithm + +_JWKKeyTypeSupported: TypeAlias = Literal["oct", "RSA", "EC", "OKP"] +JWKTypesRegistry: dict[_JWKKeyTypeSupported, str] + +class ParmType(Enum): + name = "A string with a name" # pyright: ignore[reportAssignmentType] + b64 = "Base64url Encoded" + b64u = "Base64urlUint Encoded" + unsupported = "Unsupported Parameter" + +class JWKParameter(NamedTuple): + description: str + public: bool + required: bool | None + type: ParmType | None + +JWKValuesRegistry: dict[LiteralString, dict[LiteralString, JWKParameter]] +JWKParamsRegistry: dict[LiteralString, JWKParameter] +JWKEllipticCurveRegistry: dict[LiteralString, str] +_JWKUseSupported: TypeAlias = Literal["sig", "enc"] +JWKUseRegistry: dict[_JWKUseSupported, str] +_JWKOperationSupported: TypeAlias = Literal[ + "sign", "verify", "encrypt", "decrypt", "wrapKey", "unwrapKey", "deriveKey", "deriveBits" +] +JWKOperationsRegistry: dict[_JWKOperationSupported, str] +JWKOpAndUsePairs: dict[_JWKOperationSupported, _JWKUseSupported] +JWKpycaCurveMap: dict[LiteralString, LiteralString] +IANANamedInformationHashAlgorithmRegistry: dict[ + LiteralString, + hashes.SHA256 + | hashes.SHA384 + | hashes.SHA512 + | hashes.SHA3_224 + | hashes.SHA3_256 + | hashes.SHA3_384 + | hashes.SHA3_512 + | hashes.BLAKE2s + | hashes.BLAKE2b + | None, +] + +class InvalidJWKType(JWException): + value: str | None + def __init__(self, value: str | None = None) -> None: ... + +class InvalidJWKUsage(JWException): + value: str + use: str + def __init__(self, use: str, value: str) -> None: ... + +class InvalidJWKOperation(JWException): + op: str + values: Sequence[str] + def __init__(self, operation: str, values: Sequence[str]) -> None: ... + +class InvalidJWKValue(JWException): ... + +class JWK(dict[str, Any]): + unsafe_skip_rsa_key_validation: bool + + @overload + def __init__( + self, + *, + generate: Literal["RSA"], + public_exponent: int | None = None, + size: int | None = None, + kid: str | None = None, + alg: str | None = None, + use: _JWKUseSupported | None = None, + key_ops: list[_JWKOperationSupported] | None = None, + ) -> None: ... + @overload + def __init__(self, *, generate: Literal["oct", "EC", "OKP"], **kwargs) -> None: ... + @overload + def __init__(self, **kwargs) -> None: ... + + # TODO: __init__ may not be typed adequately because keyword arguments depend on the value of generate + @classmethod + @overload + def generate( + cls, + *, + kty: Literal["RSA"], + public_exponent: int | None = None, + size: int | None = None, + kid: str | None = None, + alg: str | None = None, + use: _JWKUseSupported | None = None, + key_ops: list[_JWKOperationSupported] | None = None, + ) -> Self: ... + @classmethod + @overload + def generate(cls, *, kty: _JWKKeyTypeSupported, **kwargs) -> Self: ... + + def generate_key(self, *, kty: _JWKKeyTypeSupported, **kwargs) -> None: ... + def import_key(self, **kwargs) -> None: ... + @classmethod + def from_json(cls, key) -> Self: ... + + @overload + def export(self, private_key: bool = True, as_dict: Literal[False] = False) -> str: ... + @overload + def export(self, private_key: bool, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export(self, *, as_dict: Literal[True]) -> dict[str, Any]: ... + + @overload + def export_public(self, as_dict: Literal[False] = False) -> str: ... + @overload + def export_public(self, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export_public(self, as_dict: bool = False) -> str | dict[str, Any]: ... + + @overload + def export_private(self, as_dict: Literal[False] = False) -> str: ... + @overload + def export_private(self, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export_private(self, as_dict: bool = False) -> str | dict[str, Any]: ... + + @overload + def export_symmetric(self, as_dict: Literal[False] = False) -> str: ... + @overload + def export_symmetric(self, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export_symmetric(self, as_dict: bool = False) -> str | dict[str, Any]: ... + + def public(self) -> Self: ... + @property + def has_public(self) -> bool: ... + @property + def has_private(self) -> bool: ... + @property + def is_symmetric(self) -> bool: ... + @property + @deprecated("") + def key_type(self) -> str | None: ... + @property + @deprecated("") + def key_id(self) -> str | None: ... + @property + @deprecated("") + def key_curve(self) -> str | None: ... + @deprecated("") + def get_curve( + self, arg: str + ) -> ( + ec.SECP256R1 + | ec.SECP384R1 + | ec.SECP521R1 + | ec.SECP256K1 + | ec.BrainpoolP256R1 + | ec.BrainpoolP384R1 + | ec.BrainpoolP512R1 + | _Ed25519_CURVE + | _Ed448_CURVE + | _X25519_CURVE + | _X448_CURVE + ): ... + def get_op_key( + self, operation: str | None = None, arg: str | None = None + ) -> str | rsa.RSAPrivateKey | rsa.RSAPublicKey | ec.EllipticCurvePrivateKey | ec.EllipticCurvePublicKey | None: ... + def import_from_pyca( + self, + key: ( + rsa.RSAPrivateKey + | rsa.RSAPublicKey + | ec.EllipticCurvePrivateKey + | ec.EllipticCurvePublicKey + | Ed25519PrivateKey + | Ed448PrivateKey + | X25519PrivateKey + | Ed25519PublicKey + | Ed448PublicKey + | X25519PublicKey + ), + ) -> None: ... + def import_from_pem(self, data: bytes, password: bytes | None = None, kid: str | None = None) -> None: ... + + @overload + def export_to_pem(self, private_key: Literal[False] = False, password: Unused = False) -> bytes: ... + @overload + def export_to_pem(self, private_key: Literal[True], password: bytes | None) -> bytes: ... + + @classmethod + def from_pyca( + cls, + key: ( + rsa.RSAPrivateKey + | rsa.RSAPublicKey + | ec.EllipticCurvePrivateKey + | ec.EllipticCurvePublicKey + | Ed25519PrivateKey + | Ed448PrivateKey + | X25519PrivateKey + | Ed25519PublicKey + | Ed448PublicKey + | X25519PublicKey + ), + ) -> Self: ... + @classmethod + def from_pem(cls, data: bytes, password: bytes | None = None) -> Self: ... + def thumbprint(self, hashalg: hashes.HashAlgorithm = ...) -> str: ... + def thumbprint_uri(self, hname: str = "sha-256") -> str: ... + @classmethod + def from_password(cls, password: str) -> Self: ... + def setdefault(self, key: str, default: _T | None = None) -> _T: ... + def __hash__(self) -> int: ... # type: ignore[override] + +class JWKSet(dict[Literal["keys"], set[JWK]]): + @overload + def __setitem__(self, key: Literal["keys"], val: JWK) -> None: ... + @overload + def __setitem__(self, key: str, val: Any) -> None: ... + + def add(self, elem: JWK) -> None: ... + + @overload + def export(self, private_keys: bool = True, as_dict: Literal[False] = False) -> str: ... + @overload + def export(self, private_keys: bool, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export(self, *, as_dict: Literal[True]) -> dict[str, Any]: ... + + def import_keyset(self, keyset: str | bytes) -> None: ... + @classmethod + def from_json(cls, keyset: str | bytes) -> Self: ... + def get_key(self, kid: str) -> JWK | None: ... + def get_keys(self, kid: str) -> set[JWK]: ... + def setdefault(self, key: str, default: _T | None = None) -> _T: ... diff --git a/stubs/jwcrypto/jwcrypto/jws.pyi b/stubs/jwcrypto/jwcrypto/jws.pyi new file mode 100644 index 000000000000..b73d3f1fd227 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jws.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete +from typing import Any, Literal +from typing_extensions import LiteralString, Self + +from jwcrypto.common import JWException, JWSEHeaderParameter +from jwcrypto.jwa import JWAAlgorithm +from jwcrypto.jwk import JWK, JWKSet + +JWSHeaderRegistry: dict[LiteralString, JWSEHeaderParameter] +default_allowed_algs: list[LiteralString] + +class InvalidJWSSignature(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWSObject(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWSOperation(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWSCore: + alg: str + engine: JWAAlgorithm + key: JWK | JWKSet + header: dict[str, Any] + protected: str + payload: bytes + def __init__( + self, + alg: str, + key: JWK | JWKSet, + header: dict[str, Any] | str | None, + payload: str | bytes, + algs: list[str] | None = None, + ) -> None: ... + def sign(self) -> dict[str, str | bytes]: ... + def verify(self, signature: bytes) -> Literal[True]: ... + +class JWS: + objects: dict[str, Incomplete] + verifylog: list[str] | None + header_registry: Incomplete + def __init__(self, payload=None, header_registry=None) -> None: ... + + @property + def allowed_algs(self): ... + @allowed_algs.setter + def allowed_algs(self, algs) -> None: ... + + @property + def is_valid(self): ... + def verify(self, key, alg=None, detached_payload=None) -> None: ... + def deserialize(self, raw_jws, key=None, alg=None) -> None: ... + def add_signature(self, key, alg=None, protected=None, header=None) -> None: ... + def serialize(self, compact: bool = False) -> str: ... + @property + def payload(self): ... + def detach_payload(self) -> None: ... + @property + def jose_header(self): ... + @classmethod + def from_jose_token(cls, token: str | bytes) -> Self: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/jwcrypto/jwcrypto/jwt.pyi b/stubs/jwcrypto/jwcrypto/jwt.pyi new file mode 100644 index 000000000000..f5fa84c6dc41 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwt.pyi @@ -0,0 +1,85 @@ +from typing import Any, SupportsInt +from typing_extensions import LiteralString, deprecated + +from jwcrypto.common import JWException, JWKeyNotFound +from jwcrypto.jwk import JWK, JWKSet + +JWTClaimsRegistry: dict[LiteralString, str] +JWT_expect_type: bool + +class JWTExpired(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTNotYetValid(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTMissingClaim(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTInvalidClaimValue(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTInvalidClaimFormat(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +@deprecated("") +class JWTMissingKeyID(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTMissingKey(JWKeyNotFound): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWT: + deserializelog: list[str] | None + def __init__( + self, + header: dict[str, Any] | str | None = None, + claims: dict[str, Any] | str | None = None, + jwt=None, + key: JWK | JWKSet | None = None, + algs=None, + default_claims=None, + check_claims=None, + expected_type=None, + strict_serialization: bool = False, + ) -> None: ... + + @property + def header(self) -> str: ... + @header.setter + def header(self, h: dict[str, Any] | str) -> None: ... + + @property + def claims(self) -> str: ... + @claims.setter + def claims(self, data: str) -> None: ... + + @property + def token(self): ... + @token.setter + def token(self, t) -> None: ... + + @property + def leeway(self) -> int: ... + @leeway.setter + def leeway(self, lwy: SupportsInt) -> None: ... + + @property + def validity(self) -> int: ... + @validity.setter + def validity(self, v: SupportsInt) -> None: ... + + @property + def expected_type(self): ... + @expected_type.setter + def expected_type(self, v) -> None: ... + + def norm_typ(self, val): ... + def make_signed_token(self, key: JWK) -> None: ... + def make_encrypted_token(self, key: JWK) -> None: ... + def validate(self, key: JWK | JWKSet) -> None: ... + def deserialize(self, jwt, key=None) -> None: ... + def serialize(self, compact: bool = True) -> str: ... + @classmethod + def from_jose_token(cls, token): ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/jwcrypto/jwcrypto/version.pyi b/stubs/jwcrypto/jwcrypto/version.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/kafka-python/@tests/stubtest_allowlist.txt b/stubs/kafka-python/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d58243279e96 --- /dev/null +++ b/stubs/kafka-python/@tests/stubtest_allowlist.txt @@ -0,0 +1,31 @@ +# Command-line entry points are not a useful typed API surface. +kafka.__main__ +kafka.admin.__main__ +kafka.consumer.__main__ +kafka.producer.__main__ + +# Benchmark modules are not included in type stubs. +kafka.benchmarks.* + +# Vendored compatibility modules are implementation details. +kafka.vendor + +# Undocumented and clearly not meant to be exposed. +kafka.coordinator.base.heartbeat_log +kafka.net.selector.log_trace +kafka.*\.log +kafka.*\.logger +kafka.*\.__license__ + +# The max_version param expects an int, even though it has as default value of float('inf'). +kafka.protocol.broker_version_data.BrokerVersionData.api_version + +# TODO: This has more attributes. +kafka.protocol.api_header.RequestHeader.client_id +kafka.protocol.api_header.RequestHeader.correlation_id +kafka.protocol.api_header.RequestHeader.request_api_key +kafka.protocol.api_header.RequestHeader.request_api_version +kafka.protocol.api_header.ResponseHeader.correlation_id +kafka.coordinator.assignors.sticky.user_data.StickyAssignorUserData.TopicPartition +kafka.coordinator.assignors.sticky.user_data.StickyAssignorUserData.generation +kafka.coordinator.assignors.sticky.user_data.StickyAssignorUserData.previous_assignment diff --git a/stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt b/stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..0f5c5020fb76 --- /dev/null +++ b/stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# The bytes subclass object layout differs by platform/Python build. +kafka.protocol.message.PartialMessage diff --git a/stubs/kafka-python/METADATA.toml b/stubs/kafka-python/METADATA.toml new file mode 100644 index 000000000000..26c881cc7b5e --- /dev/null +++ b/stubs/kafka-python/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.0.11" +upstream-repository = "https://github.com/dpkp/kafka-python" diff --git a/stubs/kafka-python/kafka/__init__.pyi b/stubs/kafka-python/kafka/__init__.pyi new file mode 100644 index 000000000000..b4df0bc6fad8 --- /dev/null +++ b/stubs/kafka-python/kafka/__init__.pyi @@ -0,0 +1,38 @@ +from kafka.admin import KafkaAdminClient as KafkaAdminClient +from kafka.consumer import KafkaConsumer as KafkaConsumer +from kafka.consumer.subscription_state import ( + AsyncConsumerRebalanceListener as AsyncConsumerRebalanceListener, + ConsumerRebalanceListener as ConsumerRebalanceListener, +) +from kafka.producer import KafkaProducer as KafkaProducer +from kafka.protocol.consumer import IsolationLevel as IsolationLevel, OffsetSpec as OffsetSpec +from kafka.serializer import ( + DefaultSerializer as DefaultSerializer, + Deserializer as Deserializer, + JsonSerializer as JsonSerializer, + Serializer as Serializer, +) +from kafka.structs import ( + ConsumerGroupMetadata as ConsumerGroupMetadata, + OffsetAndMetadata as OffsetAndMetadata, + TopicPartition as TopicPartition, + TopicPartitionReplica as TopicPartitionReplica, +) + +__all__ = [ + "KafkaAdminClient", + "KafkaConsumer", + "KafkaProducer", + "AsyncConsumerRebalanceListener", + "ConsumerRebalanceListener", + "DefaultSerializer", + "JsonSerializer", + "Serializer", + "Deserializer", + "ConsumerGroupMetadata", + "OffsetAndMetadata", + "TopicPartition", + "TopicPartitionReplica", + "IsolationLevel", + "OffsetSpec", +] diff --git a/stubs/kafka-python/kafka/admin/__init__.pyi b/stubs/kafka-python/kafka/admin/__init__.pyi new file mode 100644 index 000000000000..8db21243ba72 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/__init__.pyi @@ -0,0 +1,68 @@ +from kafka.admin._acls import ( + ACL as ACL, + ACLFilter as ACLFilter, + ACLOperation as ACLOperation, + ACLPermissionType as ACLPermissionType, + ACLResourcePatternType as ACLResourcePatternType, + ResourcePattern as ResourcePattern, + ResourcePatternFilter as ResourcePatternFilter, + ResourceType as ResourceType, +) +from kafka.admin._cluster import UpdateFeatureType as UpdateFeatureType +from kafka.admin._configs import ( + AlterConfigOp as AlterConfigOp, + ConfigFilterType as ConfigFilterType, + ConfigResource as ConfigResource, + ConfigResourceType as ConfigResourceType, + ConfigSourceType as ConfigSourceType, + ConfigType as ConfigType, +) +from kafka.admin._groups import GroupState as GroupState, GroupType as GroupType, MemberToRemove as MemberToRemove +from kafka.admin._partitions import NewPartitions as NewPartitions, OffsetSpec as OffsetSpec, OffsetTimestamp as OffsetTimestamp +from kafka.admin._topics import NewTopic as NewTopic +from kafka.admin._transactions import ( + AbortTransactionSpec as AbortTransactionSpec, + PartitionProducerState as PartitionProducerState, + ProducerState as ProducerState, + TransactionDescription as TransactionDescription, + TransactionListing as TransactionListing, + TransactionState as TransactionState, +) +from kafka.admin._users import ( + ScramMechanism as ScramMechanism, + UserScramCredentialDeletion as UserScramCredentialDeletion, + UserScramCredentialUpsertion as UserScramCredentialUpsertion, +) +from kafka.admin.client import KafkaAdminClient as KafkaAdminClient + +__all__ = [ + "KafkaAdminClient", + "ACL", + "ACLFilter", + "ACLOperation", + "ACLPermissionType", + "ACLResourcePatternType", + "ResourceType", + "ResourcePattern", + "ResourcePatternFilter", + "AlterConfigOp", + "ConfigResource", + "ConfigResourceType", + "ConfigType", + "ConfigSourceType", + "UpdateFeatureType", + "GroupState", + "GroupType", + "MemberToRemove", + "OffsetSpec", + "OffsetTimestamp", + "AbortTransactionSpec", + "PartitionProducerState", + "ProducerState", + "TransactionDescription", + "TransactionListing", + "TransactionState", + "ScramMechanism", + "UserScramCredentialDeletion", + "UserScramCredentialUpsertion", +] diff --git a/stubs/kafka-python/kafka/admin/_acls.pyi b/stubs/kafka-python/kafka/admin/_acls.pyi new file mode 100644 index 000000000000..cb348d886743 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_acls.pyi @@ -0,0 +1,108 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from enum import IntEnum +from typing import TypedDict, type_check_only + +from kafka.errors import KafkaError + +@type_check_only +class _CreateAclsResult(TypedDict): + succeeded: list[ACL] + failed: list[type[KafkaError]] + +class ACLAdminMixin: + config: dict[Incomplete, Incomplete] + def describe_acls(self, acl_filter: ACLFilter) -> tuple[list[ACL], type[KafkaError]]: ... + def create_acls(self, acls: Sequence[ACL]) -> _CreateAclsResult: ... + def delete_acls(self, acl_filters: Sequence[ACLFilter]) -> list[tuple[ACLFilter, list[ACL], type[KafkaError]]]: ... + +class ResourceType(IntEnum): + UNKNOWN = 0 + ANY = 1 + TOPIC = 2 + GROUP = 3 + CLUSTER = 4 + TRANSACTIONAL_ID = 5 + DELEGATION_TOKEN = 6 + USER = 7 + +class ACLOperation(IntEnum): + UNKNOWN = 0 + ANY = 1 + ALL = 2 + READ = 3 + WRITE = 4 + CREATE = 5 + DELETE = 6 + ALTER = 7 + DESCRIBE = 8 + CLUSTER_ACTION = 9 + DESCRIBE_CONFIGS = 10 + ALTER_CONFIGS = 11 + IDEMPOTENT_WRITE = 12 + CREATE_TOKENS = 13 + DESCRIBE_TOKENS = 14 + +class ACLPermissionType(IntEnum): + UNKNOWN = 0 + ANY = 1 + DENY = 2 + ALLOW = 3 + +class ACLResourcePatternType(IntEnum): + UNKNOWN = 0 + ANY = 1 + MATCH = 2 + LITERAL = 3 + PREFIXED = 4 + +class ResourcePatternFilter: + resource_type: ResourceType + resource_name: str | None + pattern_type: ACLResourcePatternType + def __init__(self, resource_type: ResourceType, resource_name: str | None, pattern_type: ACLResourcePatternType) -> None: ... + def validate(self) -> None: ... + def __eq__(self, other: ResourcePatternFilter) -> bool: ... # type: ignore[override] + def __hash__(self) -> int: ... + +class ResourcePattern(ResourcePatternFilter): + resource_name: str + def __init__( + self, + resource_type: ResourceType, + resource_name: str, + pattern_type: ACLResourcePatternType = ACLResourcePatternType.LITERAL, + ) -> None: ... + def validate(self) -> None: ... + +class ACLFilter: + principal: str | None + host: str | None + operation: ACLOperation + permission_type: ACLPermissionType + resource_pattern: ResourcePatternFilter + def __init__( + self, + principal: str | None, + host: str | None, + operation: ACLOperation, + permission_type: ACLPermissionType, + resource_pattern: ResourcePatternFilter, + ) -> None: ... + def validate(self) -> None: ... + def __eq__(self, other: ACLFilter) -> bool: ... # type: ignore[override] + def __hash__(self) -> int: ... + +class ACL(ACLFilter): + resource_pattern: ResourcePattern + def __init__( + self, + principal: str, + host: str, + operation: ACLOperation, + permission_type: ACLPermissionType, + resource_pattern: ResourcePattern, + ) -> None: ... + def validate(self) -> None: ... + +def valid_acl_operations(int_vals) -> set[ACLOperation]: ... diff --git a/stubs/kafka-python/kafka/admin/_cluster.pyi b/stubs/kafka-python/kafka/admin/_cluster.pyi new file mode 100644 index 000000000000..4faa7f80c99c --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_cluster.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.protocol.api_key import ApiKey +from kafka.util import EnumHelper + +class ClusterAdminMixin: + def describe_cluster(self) -> dict[str, Incomplete]: ... + def describe_log_dirs( + self, + topic_partitions: dict[Incomplete, Incomplete] | list[Incomplete] | None = None, + brokers: list[Incomplete] | None = None, + ) -> list[dict[str, Incomplete]]: ... + def alter_replica_log_dirs(self, replica_assignments): ... + def describe_metadata_quorum(self): ... + def get_broker_version_data(self, broker_id): ... + def api_versions(self) -> dict[ApiKey, tuple[int, int] | Incomplete]: ... + def describe_features(self, send_request_to_controller: bool = False) -> dict[str, Incomplete]: ... + def update_features( + self, feature_updates: dict[Incomplete, Incomplete], validate_only: bool = False, timeout_ms: int = 60000 + ) -> dict[Incomplete, Incomplete]: ... + +class UpdateFeatureType(EnumHelper, IntEnum): + UNKNOWN = 0 + UPGRADE = 1 + SAFE_DOWNGRADE = 2 + UNSAFE_DOWNGRADE = 3 diff --git a/stubs/kafka-python/kafka/admin/_configs.pyi b/stubs/kafka-python/kafka/admin/_configs.pyi new file mode 100644 index 000000000000..8842b8c4a17b --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_configs.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from enum import IntEnum + +from kafka.util import EnumHelper + +class ConfigAdminMixin: + config: dict[Incomplete, Incomplete] + def describe_configs( + self, + config_resources: Sequence[ConfigResource], + include_synonyms: bool = False, + config_filter: ConfigFilterType | str = "modified", + ): ... + def list_config_resources(self, resource_types: Sequence[ConfigResourceType | str] | None = None): ... + def alter_configs( + self, + config_resources: Sequence[ConfigResource], + validate_only: bool = False, + raise_on_unknown: bool = True, + incremental: bool | None = None, + ): ... + def reset_configs( + self, + config_resources: Sequence[ConfigResource], + validate_only: bool = False, + raise_on_unknown: bool = True, + incremental: bool | None = None, + ): ... + +class AlterConfigOp(EnumHelper, IntEnum): + SET = 0 + DELETE = 1 + APPEND = 2 + SUBTRACT = 3 + +class ConfigFilterType(EnumHelper, IntEnum): + ALL = 0 + DYNAMIC = 1 + MODIFIED = 2 + DEFAULT = 3 + STATIC = 4 + def should_skip(self, config_source: ConfigSourceType) -> bool: ... + +class ConfigResourceType(EnumHelper, IntEnum): + UNKNOWN = 0 + TOPIC = 2 + BROKER = 4 + BROKER_LOGGER = 8 + CLIENT_METRICS = 16 + GROUP = 32 + +class ConfigResource: + resource_type: ConfigResourceType + name: str + configs: Mapping[str, str] | None + def __init__(self, resource_type: ConfigResourceType | str, name: str, configs: Mapping[str, str] | None = None) -> None: ... + +class ConfigType(EnumHelper, IntEnum): + UNKNOWN = 0 + BOOLEAN = 1 + STRING = 2 + INT = 3 + SHORT = 4 + LONG = 5 + DOUBLE = 6 + LIST = 7 + CLASS = 8 + PASSWORD = 9 + +class ConfigSourceType(EnumHelper, IntEnum): + UNKNOWN = 0 + DYNAMIC_TOPIC_CONFIG = 1 + DYNAMIC_BROKER_CONFIG = 2 + DYNAMIC_DEFAULT_BROKER_CONFIG = 3 + STATIC_BROKER_CONFIG = 4 + DEFAULT_CONFIG = 5 + DYNAMIC_BROKER_LOGGER_CONFIG = 6 + DYNAMIC_CLIENT_METRICS_CONFIG = 7 + DYNAMIC_GROUP_CONFIG = 8 + def is_modified(self) -> bool: ... + @classmethod + def dynamic_for_resource_type(cls, resource_type: ConfigResourceType) -> ConfigSourceType: ... diff --git a/stubs/kafka-python/kafka/admin/_groups.pyi b/stubs/kafka-python/kafka/admin/_groups.pyi new file mode 100644 index 000000000000..abe2d632c507 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_groups.pyi @@ -0,0 +1,64 @@ +import sys +from _typeshed import Incomplete + +from kafka.util import EnumHelper + +class GroupAdminMixin: + config: dict[Incomplete, Incomplete] + def describe_groups( + self, group_ids, group_coordinator_id: int | None = None, include_authorized_operations: bool = False + ): ... + def list_groups(self, broker_ids=None, states_filter=None, types_filter=None): ... + def list_group_offsets(self, group_specs): ... + def delete_groups(self, group_ids, group_coordinator_id: int | None = None): ... + def alter_group_offsets(self, group_id: str, offsets, group_coordinator_id: int | None = None): ... + def reset_group_offsets(self, group_id: str, offset_specs, group_coordinator_id: int | None = None): ... + def delete_group_offsets(self, group_id: str, partitions, group_coordinator_id: int | None = None): ... + def remove_group_members(self, group_id: str, members, group_coordinator_id: int | None = None): ... + +class MemberToRemove: + __slots__ = ("member_id", "group_instance_id", "reason") + member_id: str | None + group_instance_id: str | None + reason: str | None + def __init__(self, member_id: str | None = None, group_instance_id: str | None = None, reason: str | None = None) -> None: ... + def __eq__(self, other: MemberToRemove) -> bool: ... # type: ignore[override] + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 11): + from enum import StrEnum + + class GroupState(EnumHelper, StrEnum): + UNKNOWN = "Unknown" + PREPARING_REBALANCE = "PreparingRebalance" + COMPLETING_REBALANCE = "CompletingRebalance" + STABLE = "Stable" + DEAD = "Dead" + EMPTY = "Empty" + ASSIGNING = "Assigning" + RECONCILING = "Reconciling" + + class GroupType(EnumHelper, StrEnum): + UNKNOWN = "Unknown" + CLASSIC = "classic" + CONSUMER = "consumer" + SHARE = "share" + +else: + from enum import Enum + + class GroupState(EnumHelper, str, Enum): + UNKNOWN = "Unknown" + PREPARING_REBALANCE = "PreparingRebalance" + COMPLETING_REBALANCE = "CompletingRebalance" + STABLE = "Stable" + DEAD = "Dead" + EMPTY = "Empty" + ASSIGNING = "Assigning" + RECONCILING = "Reconciling" + + class GroupType(EnumHelper, str, Enum): + UNKNOWN = "Unknown" + CLASSIC = "classic" + CONSUMER = "consumer" + SHARE = "share" diff --git a/stubs/kafka-python/kafka/admin/_partitions.pyi b/stubs/kafka-python/kafka/admin/_partitions.pyi new file mode 100644 index 000000000000..fde83e35b19f --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_partitions.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from typing_extensions import deprecated + +from kafka.protocol.consumer import IsolationLevel, OffsetSpec as OffsetSpec, OffsetTimestamp as OffsetTimestamp +from kafka.structs import TopicPartition + +class PartitionAdminMixin: + config: dict[Incomplete, Incomplete] + def create_partitions( + self, + topic_partitions: Mapping[str, int | dict[Incomplete, Incomplete] | NewPartitions], + timeout_ms: int | None = None, + validate_only: bool = False, + raise_errors: bool = True, + ): ... + def delete_records( + self, records_to_delete: Mapping[TopicPartition, int], timeout_ms: float | None = None, partition_leader_id=None + ) -> dict[TopicPartition, Incomplete]: ... + def elect_leaders(self, election_type, topic_partitions=None, timeout_ms=None, raise_errors: bool = True): ... + def alter_partition_reassignments(self, reassignments, timeout_ms=None): ... + def list_partition_reassignments(self, topic_partitions=None, timeout_ms=None): ... + def describe_topic_partitions(self, topics, response_partition_limit: int = 2000, cursor=None): ... + def list_partition_offsets( + self, topic_partition_specs, isolation_level: IsolationLevel = IsolationLevel.READ_UNCOMMITTED, timeout_ms=None + ): ... + +@deprecated("Deprecated since v3.0.0. Use simple `dict` instead.") +class NewPartitions: + total_count: int + new_assignments: Sequence[Sequence[int]] | None + def __init__(self, total_count: int, new_assignments: Sequence[Sequence[int]] | None = None) -> None: ... diff --git a/stubs/kafka-python/kafka/admin/_topics.pyi b/stubs/kafka-python/kafka/admin/_topics.pyi new file mode 100644 index 000000000000..ccdb7cc6c93c --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_topics.pyi @@ -0,0 +1,35 @@ +import uuid +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from typing_extensions import deprecated + +class TopicAdminMixin: + config: dict[Incomplete, Incomplete] + def list_topics(self) -> list[str]: ... + def describe_topics(self, topics: Sequence[str | uuid.UUID] | None = None) -> list[dict[str, Incomplete]]: ... + def create_topics( + self, + new_topics: dict[str, dict[Incomplete, Incomplete]] | Sequence[NewTopic], + timeout_ms: float | None = None, + validate_only: bool = False, + raise_errors: bool = True, + wait_for_metadata: bool = False, + ): ... + def wait_for_topics(self, topic_names, timeout_ms: float | None = 10000): ... + def delete_topics(self, topics: Sequence[str | uuid.UUID], timeout_ms: float | None = None, raise_errors: bool = True): ... + +@deprecated("Deprecated since v3.0.0. Use simple `dict` instead.") +class NewTopic: + name: str + num_partitions: int + replication_factor: int + replica_assignments: Mapping[int, Sequence[int]] | None + topic_configs: Mapping[str, str] | None + def __init__( + self, + name: str, + num_partitions: int = -1, + replication_factor: int = -1, + replica_assignments: Mapping[int, Sequence[int]] | None = None, + topic_configs: Mapping[str, str] | None = None, + ) -> None: ... diff --git a/stubs/kafka-python/kafka/admin/_transactions.pyi b/stubs/kafka-python/kafka/admin/_transactions.pyi new file mode 100644 index 000000000000..fb381a30b34f --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_transactions.pyi @@ -0,0 +1,80 @@ +import sys +from _typeshed import Incomplete +from typing import NamedTuple + +from kafka.structs import TopicPartition +from kafka.util import EnumHelper + +if sys.version_info >= (3, 11): + from enum import StrEnum + + class TransactionState(EnumHelper, StrEnum): + EMPTY = "Empty" + ONGOING = "Ongoing" + PREPARE_COMMIT = "PrepareCommit" + PREPARE_ABORT = "PrepareAbort" + COMPLETE_COMMIT = "CompleteCommit" + COMPLETE_ABORT = "CompleteAbort" + DEAD = "Dead" + PREPARE_EPOCH_FENCE = "PrepareEpochFence" + UNKNOWN = "Unknown" + +else: + from enum import Enum + + class TransactionState(EnumHelper, str, Enum): + EMPTY = "Empty" + ONGOING = "Ongoing" + PREPARE_COMMIT = "PrepareCommit" + PREPARE_ABORT = "PrepareAbort" + COMPLETE_COMMIT = "CompleteCommit" + COMPLETE_ABORT = "CompleteAbort" + DEAD = "Dead" + PREPARE_EPOCH_FENCE = "PrepareEpochFence" + UNKNOWN = "Unknown" + +class TransactionListing(NamedTuple): + transactional_id: str + producer_id: int + state: TransactionState + +class TransactionDescription(NamedTuple): + coordinator_id: int + state: TransactionState + producer_id: int + producer_epoch: int + transaction_timeout_ms: int + transaction_start_time_ms: int + topic_partitions: set[TopicPartition] + +class ProducerState(NamedTuple): + producer_id: int + producer_epoch: int + last_sequence: int + last_timestamp: int + coordinator_epoch: int + current_transaction_start_offset: int + +class PartitionProducerState(NamedTuple): + active_producers: list[ProducerState] + +class AbortTransactionSpec(NamedTuple): + topic_partition: TopicPartition + producer_id: int + producer_epoch: int + coordinator_epoch: int = -1 + +class TransactionsAdminMixin: + config: dict[Incomplete, Incomplete] + def list_transactions( + self, + broker_ids=None, + producer_id_filters=None, + state_filters=None, + duration_filter_ms: float | None = None, + transactional_id_pattern: str | None = None, + ): ... + def describe_transactions(self, transactional_ids): ... + def describe_producers(self, partitions, broker_id: int | None = None): ... + def abort_transaction(self, spec): ... + def find_hanging_transactions(self, broker_ids=None, max_transaction_timeout_ms: float = 900000): ... diff --git a/stubs/kafka-python/kafka/admin/_users.pyi b/stubs/kafka-python/kafka/admin/_users.pyi new file mode 100644 index 000000000000..9937bc64f07d --- /dev/null +++ b/stubs/kafka-python/kafka/admin/_users.pyi @@ -0,0 +1,36 @@ +from _typeshed import ReadableBuffer +from collections.abc import Sequence +from enum import IntEnum +from typing import Final + +class UserAdminMixin: + def alter_user_scram_credentials(self, alterations: Sequence[UserScramCredentialDeletion | UserScramCredentialUpsertion]): ... + def describe_user_scram_credentials(self, users: Sequence[str] | None = None): ... + +class ScramMechanism(IntEnum): + UNKNOWN = 0 + SCRAM_SHA_256 = 1 + SCRAM_SHA_512 = 2 + @property + def hash_name(self) -> str: ... + +class UserScramCredentialDeletion: + user: str + mechanism: ScramMechanism + def __init__(self, user: str, mechanism: ScramMechanism | int | str) -> None: ... + +class UserScramCredentialUpsertion: + DEFAULT_ITERATIONS: Final = 4096 + user: str + mechanism: ScramMechanism + iterations: int + salt: ReadableBuffer + salted_password: bytes + def __init__( + self, + user: str, + mechanism: ScramMechanism | int | str, + password: str | ReadableBuffer, + iterations: int | None = None, + salt: ReadableBuffer | None = None, + ) -> None: ... diff --git a/stubs/kafka-python/kafka/admin/client.pyi b/stubs/kafka-python/kafka/admin/client.pyi new file mode 100644 index 000000000000..f83c11bd361f --- /dev/null +++ b/stubs/kafka-python/kafka/admin/client.pyi @@ -0,0 +1,77 @@ +import selectors +import ssl +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from types import TracebackType +from typing import Literal +from typing_extensions import Self + +from kafka.admin._acls import ACLAdminMixin +from kafka.admin._cluster import ClusterAdminMixin +from kafka.admin._configs import ConfigAdminMixin +from kafka.admin._groups import GroupAdminMixin +from kafka.admin._partitions import PartitionAdminMixin +from kafka.admin._topics import TopicAdminMixin +from kafka.admin._transactions import TransactionsAdminMixin +from kafka.admin._users import UserAdminMixin +from kafka.net.sasl.oauth import AbstractTokenProvider + +class KafkaAdminClient( + ACLAdminMixin, + ClusterAdminMixin, + ConfigAdminMixin, + GroupAdminMixin, + PartitionAdminMixin, + TopicAdminMixin, + TransactionsAdminMixin, + UserAdminMixin, +): + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + def __init__( + self, + *, + bootstrap_servers: str | Sequence[str] = "localhost", + client_id: str = ..., + request_timeout_ms: int = 30_000, + connections_max_idle_ms: int = 540_000, + reconnect_backoff_ms: int = 50, + reconnect_backoff_max_ms: int = 30_000, + max_in_flight_requests_per_connection: int = 5, + receive_message_max_bytes: int = 100_000_000, + receive_buffer_bytes: int | None = None, + send_buffer_bytes: int | None = None, + socket_options: Sequence[tuple[int, int, int]] = ..., + retry_backoff_ms: int = 100, + metadata_max_age_ms: int = 300_000, + client_dns_lookup: str = "use_all_dns_ips", + security_protocol: Literal["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"] = "PLAINTEXT", + ssl_context: ssl.SSLContext | None = None, + ssl_check_hostname: bool = True, + ssl_cafile: str | None = None, + ssl_certfile: str | None = None, + ssl_keyfile: str | None = None, + ssl_password: str | None = None, + ssl_crlfile: str | None = None, + api_version: tuple[int, ...] | None = None, + bootstrap_timeout_ms: int = 30_000, + selector: type[selectors.BaseSelector] = selectors.DefaultSelector, + sasl_mechanism: Literal["PLAIN", "GSSAPI", "OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-512"] | None = None, + sasl_plain_username: str | None = None, + sasl_plain_password: str | None = None, + sasl_kerberos_name: object | None = None, + sasl_kerberos_service_name: str = "kafka", + sasl_kerberos_domain_name: str | None = None, + sasl_oauth_token_provider: AbstractTokenProvider | None = None, + proxy_url: str | None = None, + socks5_proxy: str | None = None, + metric_reporters: Sequence[type[object]] = [], + metrics_num_samples: int = 2, + metrics_sample_window_ms: int = 30_000, + kafka_client: Callable[..., object] = ..., + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/cli/__init__.pyi b/stubs/kafka-python/kafka/cli/__init__.pyi new file mode 100644 index 000000000000..0ff9583c55d3 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/__init__.pyi @@ -0,0 +1,6 @@ +from collections.abc import Sequence +from typing import Final + +USAGE: Final[str] + +def run_cli(args: Sequence[str] | None = None): ... diff --git a/stubs/kafka-python/kafka/cli/admin/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/__init__.pyi new file mode 100644 index 000000000000..858a47e2a4f4 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/__init__.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from argparse import ArgumentParser +from collections.abc import Iterable, Sequence +from typing import Final, Literal + +DEFAULT_COMMAND_GROUPS: Final[tuple[type[Incomplete], ...]] + +def main_parser(prog: str | None = None) -> ArgumentParser: ... +def build_parser(groups: Iterable[Incomplete] = (), prog: str | None = None) -> ArgumentParser: ... +def run_cli(args: Sequence[str] | None = None, prog: str | None = None) -> Literal[0, 1]: ... diff --git a/stubs/kafka-python/kafka/cli/admin/acls/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/acls/__init__.pyi new file mode 100644 index 000000000000..e912ffc496f7 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/acls/__init__.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar + +from .create import CreateACLs as CreateACLs +from .delete import DeleteACLs as DeleteACLs +from .describe import DescribeACLs as DescribeACLs + +class ACLsCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[list[type[CreateACLs | DeleteACLs | DescribeACLs]]] diff --git a/stubs/kafka-python/kafka/cli/admin/acls/common.pyi b/stubs/kafka-python/kafka/cli/admin/acls/common.pyi new file mode 100644 index 000000000000..e8240e52f66b --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/acls/common.pyi @@ -0,0 +1,8 @@ +from argparse import ArgumentParser, Namespace + +from kafka.admin._acls import ACL, ACLFilter + +def add_acl_filter_args(parser: ArgumentParser) -> None: ... +def add_acl_args(parser: ArgumentParser, required: bool = False) -> None: ... +def acl_filter_from_args(args: Namespace) -> ACLFilter: ... +def acl_from_args(args: Namespace) -> ACL: ... diff --git a/stubs/kafka-python/kafka/cli/admin/acls/create.pyi b/stubs/kafka-python/kafka/cli/admin/acls/create.pyi new file mode 100644 index 000000000000..ec0cb1769a1f --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/acls/create.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class CreateACLs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace) -> dict[str, list[str]]: ... diff --git a/stubs/kafka-python/kafka/cli/admin/acls/delete.pyi b/stubs/kafka-python/kafka/cli/admin/acls/delete.pyi new file mode 100644 index 000000000000..2d01a119b10b --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/acls/delete.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DeleteACLs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace) -> list[dict[str, str | list[str]]]: ... diff --git a/stubs/kafka-python/kafka/cli/admin/acls/describe.pyi b/stubs/kafka-python/kafka/cli/admin/acls/describe.pyi new file mode 100644 index 000000000000..efec8643f6c7 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/acls/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeACLs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace) -> list[str]: ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi new file mode 100644 index 000000000000..3648c304df63 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi @@ -0,0 +1,25 @@ +from typing import ClassVar + +from .describe import DescribeCluster as DescribeCluster +from .describe_quorum import DescribeQuorum as DescribeQuorum +from .features import DescribeFeatures as DescribeFeatures, UpdateFeatures as UpdateFeatures +from .log_dirs import AlterLogDirs as AlterLogDirs, DescribeLogDirs as DescribeLogDirs +from .versions import GetApiVersions as GetApiVersions, GetBrokerVersion as GetBrokerVersion + +class ClusterCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[ + list[ + type[ + DescribeCluster + | DescribeQuorum + | GetApiVersions + | GetBrokerVersion + | DescribeFeatures + | UpdateFeatures + | DescribeLogDirs + | AlterLogDirs + ] + ] + ] diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi new file mode 100644 index 000000000000..61da926f0817 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeCluster: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/describe_quorum.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/describe_quorum.pyi new file mode 100644 index 000000000000..cb62c6776c4a --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/describe_quorum.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeQuorum: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/features.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/features.pyi new file mode 100644 index 000000000000..ddaaac6c8093 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/features.pyi @@ -0,0 +1,18 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeFeatures: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... + +class UpdateFeatures: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/log_dirs.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/log_dirs.pyi new file mode 100644 index 000000000000..8c93a9394494 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/log_dirs.pyi @@ -0,0 +1,18 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeLogDirs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... + +class AlterLogDirs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/versions.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/versions.pyi new file mode 100644 index 000000000000..c586e68ea2b2 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/versions.pyi @@ -0,0 +1,18 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class GetApiVersions: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... + +class GetBrokerVersion: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi new file mode 100644 index 000000000000..eb707fc5f581 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi @@ -0,0 +1,12 @@ +from builtins import list as _list +from typing import ClassVar + +from .alter import AlterConfigs as AlterConfigs +from .describe import DescribeConfigs as DescribeConfigs +from .list import ListConfigResources as ListConfigResources +from .reset import ResetConfigs as ResetConfigs + +class ConfigsCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[_list[type[DescribeConfigs | AlterConfigs | ListConfigResources | ResetConfigs]]] diff --git a/stubs/kafka-python/kafka/cli/admin/configs/alter.pyi b/stubs/kafka-python/kafka/cli/admin/configs/alter.pyi new file mode 100644 index 000000000000..352545904c6e --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/alter.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class AlterConfigs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/common.pyi b/stubs/kafka-python/kafka/cli/admin/configs/common.pyi new file mode 100644 index 000000000000..1cb0927ffb12 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/common.pyi @@ -0,0 +1,7 @@ +from argparse import ArgumentParser, Namespace +from collections.abc import Mapping + +from kafka.admin import ConfigResource + +def add_resource_arguments(parser: ArgumentParser) -> None: ... +def parse_resources(args: Namespace, configs: Mapping[str, str] | None = None) -> list[ConfigResource]: ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/describe.pyi b/stubs/kafka-python/kafka/cli/admin/configs/describe.pyi new file mode 100644 index 000000000000..00911c79ea40 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeConfigs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/list.pyi b/stubs/kafka-python/kafka/cli/admin/configs/list.pyi new file mode 100644 index 000000000000..1b25e66036ba --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/list.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListConfigResources: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/reset.pyi b/stubs/kafka-python/kafka/cli/admin/configs/reset.pyi new file mode 100644 index 000000000000..2d64756dbce7 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/reset.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ResetConfigs: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/groups/__init__.pyi new file mode 100644 index 000000000000..9c172a682635 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/__init__.pyi @@ -0,0 +1,29 @@ +from builtins import list as _list +from typing import ClassVar + +from .alter_offsets import AlterGroupOffsets as AlterGroupOffsets +from .delete import DeleteGroups as DeleteGroups +from .delete_offsets import DeleteGroupOffsets as DeleteGroupOffsets +from .describe import DescribeGroups as DescribeGroups +from .list import ListGroups as ListGroups +from .list_offsets import ListGroupOffsets as ListGroupOffsets +from .remove_members import RemoveGroupMembers as RemoveGroupMembers +from .reset_offsets import ResetGroupOffsets as ResetGroupOffsets + +class GroupsCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[ + _list[ + type[ + ListGroups + | DescribeGroups + | DeleteGroups + | ListGroupOffsets + | AlterGroupOffsets + | ResetGroupOffsets + | DeleteGroupOffsets + | RemoveGroupMembers + ] + ] + ] diff --git a/stubs/kafka-python/kafka/cli/admin/groups/alter_offsets.pyi b/stubs/kafka-python/kafka/cli/admin/groups/alter_offsets.pyi new file mode 100644 index 000000000000..ff1638fbfca2 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/alter_offsets.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class AlterGroupOffsets: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/delete.pyi b/stubs/kafka-python/kafka/cli/admin/groups/delete.pyi new file mode 100644 index 000000000000..0709db861eb4 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/delete.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DeleteGroups: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/delete_offsets.pyi b/stubs/kafka-python/kafka/cli/admin/groups/delete_offsets.pyi new file mode 100644 index 000000000000..043b8de719c9 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/delete_offsets.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DeleteGroupOffsets: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/describe.pyi b/stubs/kafka-python/kafka/cli/admin/groups/describe.pyi new file mode 100644 index 000000000000..cd072ca86a4d --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeGroups: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/list.pyi b/stubs/kafka-python/kafka/cli/admin/groups/list.pyi new file mode 100644 index 000000000000..8b3d45ceae35 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/list.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListGroups: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/list_offsets.pyi b/stubs/kafka-python/kafka/cli/admin/groups/list_offsets.pyi new file mode 100644 index 000000000000..50cbd4de698f --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/list_offsets.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListGroupOffsets: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/remove_members.pyi b/stubs/kafka-python/kafka/cli/admin/groups/remove_members.pyi new file mode 100644 index 000000000000..0eca80d14f68 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/remove_members.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class RemoveGroupMembers: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/groups/reset_offsets.pyi b/stubs/kafka-python/kafka/cli/admin/groups/reset_offsets.pyi new file mode 100644 index 000000000000..c8ca4b195239 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/groups/reset_offsets.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ResetGroupOffsets: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/__init__.pyi new file mode 100644 index 000000000000..86830132391c --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/__init__.pyi @@ -0,0 +1,26 @@ +from typing import ClassVar + +from .alter_reassignments import AlterPartitionReassignments as AlterPartitionReassignments +from .create import CreatePartitions as CreatePartitions +from .delete_records import DeleteRecords as DeleteRecords +from .describe import DescribeTopicPartitions as DescribeTopicPartitions +from .elect_leaders import ElectLeaders as ElectLeaders +from .list_offsets import ListPartitionOffsets as ListPartitionOffsets +from .list_reassignments import ListPartitionReassignments as ListPartitionReassignments + +class PartitionsCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[ + list[ + type[ + CreatePartitions + | DescribeTopicPartitions + | ListPartitionOffsets + | ListPartitionReassignments + | AlterPartitionReassignments + | DeleteRecords + | ElectLeaders + ] + ] + ] diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/alter_reassignments.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/alter_reassignments.pyi new file mode 100644 index 000000000000..97ad131b2043 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/alter_reassignments.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class AlterPartitionReassignments: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/create.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/create.pyi new file mode 100644 index 000000000000..1fa2cff1d847 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/create.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class CreatePartitions: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/delete_records.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/delete_records.pyi new file mode 100644 index 000000000000..ab09f0b76a36 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/delete_records.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DeleteRecords: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/describe.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/describe.pyi new file mode 100644 index 000000000000..0b8e09da01ae --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeTopicPartitions: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/elect_leaders.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/elect_leaders.pyi new file mode 100644 index 000000000000..fb32599c1e4e --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/elect_leaders.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ElectLeaders: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/list_offsets.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/list_offsets.pyi new file mode 100644 index 000000000000..0a9bbae86dd7 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/list_offsets.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListPartitionOffsets: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/partitions/list_reassignments.pyi b/stubs/kafka-python/kafka/cli/admin/partitions/list_reassignments.pyi new file mode 100644 index 000000000000..cbd232b083a8 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/partitions/list_reassignments.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListPartitionReassignments: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi new file mode 100644 index 000000000000..8bd2b923b143 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi @@ -0,0 +1,12 @@ +from builtins import list as _list +from typing import ClassVar + +from .create import CreateTopic as CreateTopic +from .delete import DeleteTopic as DeleteTopic +from .describe import DescribeTopics as DescribeTopics +from .list import ListTopics as ListTopics + +class TopicsCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[_list[type[ListTopics | DescribeTopics | CreateTopic | DeleteTopic]]] diff --git a/stubs/kafka-python/kafka/cli/admin/topics/create.pyi b/stubs/kafka-python/kafka/cli/admin/topics/create.pyi new file mode 100644 index 000000000000..2b93872c070e --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/create.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class CreateTopic: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/delete.pyi b/stubs/kafka-python/kafka/cli/admin/topics/delete.pyi new file mode 100644 index 000000000000..c233c135783b --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/delete.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DeleteTopic: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/describe.pyi b/stubs/kafka-python/kafka/cli/admin/topics/describe.pyi new file mode 100644 index 000000000000..400eb72ba029 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeTopics: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/list.pyi b/stubs/kafka-python/kafka/cli/admin/topics/list.pyi new file mode 100644 index 000000000000..9ce08a5b60a3 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/list.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListTopics: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/transactions/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/transactions/__init__.pyi new file mode 100644 index 000000000000..9aaf5f38b1dc --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/transactions/__init__.pyi @@ -0,0 +1,15 @@ +from builtins import list as _list +from typing import ClassVar + +from .abort import AbortTransaction as AbortTransaction +from .describe import DescribeTransactions as DescribeTransactions +from .describe_producers import DescribeProducers as DescribeProducers +from .find_hanging import FindHangingTransactions as FindHangingTransactions +from .list import ListTransactions as ListTransactions + +class TransactionsCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[ + _list[type[ListTransactions | DescribeTransactions | DescribeProducers | FindHangingTransactions | AbortTransaction]] + ] diff --git a/stubs/kafka-python/kafka/cli/admin/transactions/abort.pyi b/stubs/kafka-python/kafka/cli/admin/transactions/abort.pyi new file mode 100644 index 000000000000..ab041e45d67a --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/transactions/abort.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class AbortTransaction: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/transactions/describe.pyi b/stubs/kafka-python/kafka/cli/admin/transactions/describe.pyi new file mode 100644 index 000000000000..a7c24dbe1af1 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/transactions/describe.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeTransactions: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/transactions/describe_producers.pyi b/stubs/kafka-python/kafka/cli/admin/transactions/describe_producers.pyi new file mode 100644 index 000000000000..00dc69493027 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/transactions/describe_producers.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeProducers: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/transactions/find_hanging.pyi b/stubs/kafka-python/kafka/cli/admin/transactions/find_hanging.pyi new file mode 100644 index 000000000000..225137449936 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/transactions/find_hanging.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class FindHangingTransactions: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/transactions/list.pyi b/stubs/kafka-python/kafka/cli/admin/transactions/list.pyi new file mode 100644 index 000000000000..917f0a7254a6 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/transactions/list.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class ListTransactions: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/users/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/users/__init__.pyi new file mode 100644 index 000000000000..79ef7b8e2222 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/users/__init__.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar + +from .alter_user_scram_credentials import AlterUserScramCredentials as AlterUserScramCredentials +from .describe_user_scram_credentials import DescribeUserScramCredentials as DescribeUserScramCredentials + +class UsersCommandGroup: + GROUP: ClassVar[str] + HELP: ClassVar[str] + COMMANDS: ClassVar[list[type[DescribeUserScramCredentials | AlterUserScramCredentials]]] diff --git a/stubs/kafka-python/kafka/cli/admin/users/alter_user_scram_credentials.pyi b/stubs/kafka-python/kafka/cli/admin/users/alter_user_scram_credentials.pyi new file mode 100644 index 000000000000..0351c7c5a8e7 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/users/alter_user_scram_credentials.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class AlterUserScramCredentials: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/admin/users/describe_user_scram_credentials.pyi b/stubs/kafka-python/kafka/cli/admin/users/describe_user_scram_credentials.pyi new file mode 100644 index 000000000000..b597cc3defd1 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/users/describe_user_scram_credentials.pyi @@ -0,0 +1,10 @@ +from argparse import ArgumentParser, Namespace +from typing import ClassVar + +class DescribeUserScramCredentials: + COMMAND: ClassVar[str] + HELP: ClassVar[str] + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + @classmethod + def command(cls, client, args: Namespace): ... diff --git a/stubs/kafka-python/kafka/cli/common.pyi b/stubs/kafka-python/kafka/cli/common.pyi new file mode 100644 index 000000000000..6ec3dec8e395 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/common.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from argparse import ArgumentParser +from collections.abc import Iterable + +def add_connect_cli_args(parser: ArgumentParser, bootstrap_required: bool = True) -> None: ... +def build_kwargs(props: Iterable[str]) -> dict[str, Incomplete]: ... +def build_connect_kwargs(config) -> dict[str, Incomplete]: ... +def add_logging_cli_args(parser: ArgumentParser) -> None: ... +def add_extended_cli_args(parser: ArgumentParser) -> None: ... +def configure_logging(config) -> None: ... +def add_common_cli_args(parser: ArgumentParser, bootstrap_required: bool = True) -> None: ... diff --git a/stubs/kafka-python/kafka/cli/consumer/__init__.pyi b/stubs/kafka-python/kafka/cli/consumer/__init__.pyi new file mode 100644 index 000000000000..47c52debb8e8 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/consumer/__init__.pyi @@ -0,0 +1,6 @@ +from argparse import ArgumentParser +from collections.abc import Iterable +from typing import Literal + +def main_parser(prog: str | None = None) -> ArgumentParser: ... +def run_cli(args: Iterable[str] | None = None, prog: str | None = None) -> Literal[0, 1] | None: ... diff --git a/stubs/kafka-python/kafka/cli/producer/__init__.pyi b/stubs/kafka-python/kafka/cli/producer/__init__.pyi new file mode 100644 index 000000000000..7fdb378ee5f8 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/producer/__init__.pyi @@ -0,0 +1,6 @@ +from argparse import ArgumentParser +from collections.abc import Iterable +from typing import Literal + +def main_parser(prog: str | None = None) -> ArgumentParser: ... +def run_cli(args: Iterable[str] | None = None, prog: str | None = None) -> Literal[0, 1]: ... diff --git a/stubs/kafka-python/kafka/cluster.pyi b/stubs/kafka-python/kafka/cluster.pyi new file mode 100644 index 000000000000..7c0107194ce1 --- /dev/null +++ b/stubs/kafka-python/kafka/cluster.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete +from socket import AddressFamily +from typing import Final + +from kafka.future import Future +from kafka.protocol.metadata import CoordinatorType, MetadataRequest + +class ClusterMetadata: + DEFAULT_CONFIG: dict[str, Incomplete] + need_all_topic_metadata: bool + unauthorized_topics: Incomplete + internal_topics: Incomplete + controller: Incomplete + cluster_id: Incomplete + config: dict[str, Incomplete] + closed: bool + def __init__(self, **configs) -> None: ... + @property + def metadata_refresh_in_progress(self) -> bool: ... + def attach(self, manager) -> None: ... + def close(self) -> None: ... + def start_refresh_loop(self) -> None: ... + async def refresh_metadata(self, node_id=None) -> None: ... + def is_bootstrap(self, node_id) -> bool: ... + def set_topics(self, topics) -> Future: ... + def add_topic(self, topic: str) -> Future: ... + def brokers(self) -> list[Incomplete]: ... + def bootstrap_brokers(self) -> list[Incomplete]: ... + def broker_metadata(self, broker_id): ... + def partitions_for_topic(self, topic): ... + def available_partitions_for_topic(self, topic): ... + def leader_for_partition(self, partition): ... + def is_replica_node(self, partition, node_id): ... + def leader_epoch_for_partition(self, partition): ... + def update_partition_leader(self, partition, leader_id: int, leader_epoch: int) -> bool: ... + def partitions_for_broker(self, broker_id): ... + def get_coordinator(self, key: str, key_type: CoordinatorType = CoordinatorType.GROUP): ... + def ttl(self): ... + def refresh_backoff(self): ... + def request_update(self) -> Future: ... + @property + def need_update(self) -> bool: ... + def topics(self, exclude_internal_topics: bool = True): ... + def metadata_request(self) -> MetadataRequest: ... + def topic_id(self, topic_name): ... + def topic_name_for_id(self, topic_id): ... + def failed_update(self, exception) -> None: ... + def update_metadata(self, metadata): ... + def add_listener(self, listener) -> None: ... + def remove_listener(self, listener) -> None: ... + def add_coordinator(self, response, key_type: CoordinatorType, key: str, synthesize_node_id: bool = True): ... + +def collect_hosts(hosts, randomize: bool = True) -> list[Incomplete]: ... +def expand_to_canonical_bootstrap_hosts(hosts) -> list[Incomplete]: ... + +DEFAULT_KAFKA_PORT: Final = 9092 + +def get_ip_port_afi(host_and_port_str: str) -> tuple[str, int, AddressFamily]: ... diff --git a/stubs/kafka-python/kafka/codec.pyi b/stubs/kafka-python/kafka/codec.pyi new file mode 100644 index 000000000000..fcd6af14d29d --- /dev/null +++ b/stubs/kafka-python/kafka/codec.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +ZSTD_MAX_OUTPUT_SIZE: Incomplete +PYPY: Incomplete + +def has_gzip(): ... +def has_snappy(): ... +def has_zstd(): ... +def has_lz4(): ... +def gzip_encode(payload, compresslevel=None): ... +def gzip_decode(payload): ... +def snappy_encode(payload, xerial_compatible: bool = True, xerial_blocksize=32768): ... +def snappy_decode(payload): ... + +lz4_encode: Incomplete + +def lz4f_decode(payload): ... + +lz4_decode: Incomplete +lz4_decode = lz4f_decode + +def lz4_encode_old_kafka(payload): ... +def lz4_decode_old_kafka(payload): ... +def zstd_encode(payload): ... +def zstd_decode(payload): ... diff --git a/stubs/kafka-python/kafka/consumer/__init__.pyi b/stubs/kafka-python/kafka/consumer/__init__.pyi new file mode 100644 index 000000000000..6830e557ab8b --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.consumer.group import KafkaConsumer as KafkaConsumer + +__all__ = ["KafkaConsumer"] diff --git a/stubs/kafka-python/kafka/consumer/fetcher.pyi b/stubs/kafka-python/kafka/consumer/fetcher.pyi new file mode 100644 index 000000000000..5807c0a18b9e --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/fetcher.pyi @@ -0,0 +1,149 @@ +from _typeshed import Incomplete +from typing import ClassVar, NamedTuple + +import kafka.errors as Errors + +class ConsumerRecord(NamedTuple): + topic: str + partition: int + leader_epoch: int | None + offset: int + timestamp: int + timestamp_type: int + key: Incomplete + value: Incomplete + headers: list[tuple[str, bytes]] + checksum: int | None + serialized_key_size: int + serialized_value_size: int + serialized_header_size: int + +class CompletedFetch(NamedTuple): + topic_partition: Incomplete + fetched_offset: Incomplete + response_version: Incomplete + partition_data: Incomplete + metric_aggregator: Incomplete + +class ExceptionMetadata(NamedTuple): + partition: Incomplete + fetched_offset: Incomplete + exception: Incomplete + +class RecordTooLargeError(Errors.KafkaError): ... + +class Fetcher: + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + def __init__(self, client, subscriptions, **configs) -> None: ... + def fetch_records(self, max_records: int | None = None, update_offsets: bool = True, timeout_ms=None): ... + def send_fetches(self): ... + def in_flight_fetches(self) -> bool: ... + def reset_offsets_if_needed(self, timeout_ms=None): ... + def offsets_by_times(self, timestamps, timeout_ms=None): ... + def beginning_offsets(self, partitions, timeout_ms=None): ... + def end_offsets(self, partitions, timeout_ms=None): ... + def beginning_or_end_offset(self, partitions, timestamp, timeout_ms=None): ... + def fetched_records(self, max_records: int | None = None, update_offsets: bool = True): ... + def maybe_validate_positions(self) -> None: ... + def validate_offsets_if_needed(self, timeout_ms=None): ... + def close(self) -> None: ... + + class PartitionRecords: + fetch_offset: Incomplete + topic_partition: Incomplete + leader_epoch: int + next_fetch_offset: Incomplete + bytes_read: int + records_read: int + isolation_level: Incomplete + aborted_producer_ids: Incomplete + aborted_transactions: Incomplete + metric_aggregator: Incomplete + check_crcs: Incomplete + record_iterator: Incomplete + on_drain: Incomplete + def __init__( + self, + fetch_offset, + tp, + records, + key_deserializer=None, + value_deserializer=None, + check_crcs: bool = True, + isolation_level=..., + aborted_transactions=None, + metric_aggregator=None, + on_drain=..., + ) -> None: ... + def __bool__(self) -> bool: ... + def drain(self) -> None: ... + def take(self, n=None) -> list[Incomplete]: ... + +class FetchSessionHandler: + node_id: Incomplete + next_metadata: Incomplete + session_partitions: Incomplete + def __init__(self, node_id) -> None: ... + def build_next(self, next_partitions): ... + def handle_response(self, response): ... + def handle_error(self, _exception) -> None: ... + +class FetchMetadata: + __slots__ = ("session_id", "epoch") + MAX_EPOCH: int + INVALID_SESSION_ID: int + THROTTLED_SESSION_ID: int + INITIAL_EPOCH: int + FINAL_EPOCH: int + INITIAL: ClassVar[FetchMetadata] + LEGACY: ClassVar[FetchMetadata] + session_id: Incomplete + epoch: Incomplete + def __init__(self, session_id, epoch) -> None: ... + @property + def is_full(self): ... + @classmethod + def next_epoch(cls, prev_epoch): ... + def next_close_existing(self): ... + @classmethod + def new_incremental(cls, session_id): ... + def next_incremental(self): ... + +class FetchRequestData: + __slots__ = ("_to_send", "_to_forget", "_metadata") + def __init__(self, to_send, to_forget, metadata) -> None: ... + @property + def metadata(self): ... + @property + def id(self): ... + @property + def epoch(self): ... + @property + def to_send(self): ... + @property + def to_forget(self): ... + +class FetchMetrics: + __slots__ = ("total_bytes", "total_records") + total_bytes: int + total_records: int + def __init__(self) -> None: ... + +class FetchResponseMetricAggregator: + sensors: Incomplete + unrecorded_partitions: Incomplete + fetch_metrics: Incomplete + topic_fetch_metrics: Incomplete + def __init__(self, sensors, partitions) -> None: ... + def record(self, partition, num_bytes, num_records) -> None: ... + +class FetchManagerMetrics: + metrics: Incomplete + group_name: Incomplete + bytes_fetched: Incomplete + records_fetched: Incomplete + fetch_latency: Incomplete + records_fetch_lag: Incomplete + def __init__(self, metrics, prefix) -> None: ... + def record_topic_fetch_metrics(self, topic, num_bytes, num_records) -> None: ... diff --git a/stubs/kafka-python/kafka/consumer/group.pyi b/stubs/kafka-python/kafka/consumer/group.pyi new file mode 100644 index 000000000000..e92809f99202 --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/group.pyi @@ -0,0 +1,148 @@ +import selectors +import ssl +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from types import TracebackType +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Self + +from kafka.consumer.fetcher import ConsumerRecord +from kafka.consumer.subscription_state import ConsumerRebalanceListener +from kafka.future import Future +from kafka.serializer.abstract import Deserializer +from kafka.structs import OffsetAndMetadata, OffsetAndTimestamp, TopicPartition + +_CommitCallback: TypeAlias = Callable[[Mapping[TopicPartition, OffsetAndMetadata], object], object] +_ConsumerDeserializer: TypeAlias = Deserializer | Callable[[bytes | None], object] + +class KafkaConsumer(Iterator[ConsumerRecord]): + DEFAULT_CONFIG: dict[str, Incomplete] + DEFAULT_SESSION_TIMEOUT_MS_PRE_KIP_735: Final = 30000 + config: dict[str, Incomplete] + def __init__( + self, + *topics: str, + bootstrap_servers: str | Sequence[str] = "localhost", + client_id: str = ..., + client_rack: str = "", + group_id: str | None = None, + group_instance_id: str | None = None, + key_deserializer: _ConsumerDeserializer | None = None, + value_deserializer: _ConsumerDeserializer | None = None, + enable_incremental_fetch_sessions: bool = True, + fetch_max_wait_ms: int = 500, + fetch_min_bytes: int = 1, + fetch_max_bytes: int = 52_428_800, + max_partition_fetch_bytes: int = 1_048_576, + request_timeout_ms: int = 30_000, + retry_backoff_ms: int = 100, + reconnect_backoff_ms: int = 50, + reconnect_backoff_max_ms: int = 30000, + max_in_flight_requests_per_connection: int = 5, + auto_offset_reset: Literal["earliest", "latest", "smallest", "largest"] = "latest", + enable_auto_commit: bool = True, + auto_commit_interval_ms: int = 5000, + default_offset_commit_callback: _CommitCallback = ..., + check_crcs: bool = True, + isolation_level: Literal["read_uncommitted", "read_committed"] = "read_uncommitted", + allow_auto_create_topics: bool = True, + metadata_max_age_ms: int = 300000, + client_dns_lookup: str = "use_all_dns_ips", + partition_assignment_strategy: Sequence[type[object]] = ..., + max_poll_records: int = 500, + max_poll_interval_ms: int = 300000, + session_timeout_ms: int = 45000, + heartbeat_interval_ms: int = 3000, + receive_buffer_bytes: int | None = None, + send_buffer_bytes: int | None = None, + receive_message_max_bytes: int = 100_000_000, + socket_options: Sequence[tuple[int, int, int]] = ..., + consumer_timeout_ms: int | float = ..., + security_protocol: Literal["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"] = "PLAINTEXT", + ssl_context: ssl.SSLContext | None = None, + ssl_check_hostname: bool = True, + ssl_cafile: str | None = None, + ssl_certfile: str | None = None, + ssl_keyfile: str | None = None, + ssl_crlfile: str | None = None, + ssl_password: str | None = None, + ssl_ciphers: str | None = None, + api_version: tuple[int, ...] | None = None, + bootstrap_timeout_ms: int = 30000, + connections_max_idle_ms: int = 540000, + metric_reporters: Sequence[type[object]] = [], + metrics_enabled: bool = True, + metrics_num_samples: int = 2, + metrics_sample_window_ms: int = 30000, + metric_group_prefix: str = "consumer", + selector: type[selectors.BaseSelector] = selectors.DefaultSelector, + exclude_internal_topics: bool = True, + sasl_mechanism: Literal["PLAIN", "GSSAPI", "OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-512"] | None = None, + sasl_plain_username: str | None = None, + sasl_plain_password: str | None = None, + sasl_kerberos_name: object | None = None, + sasl_kerberos_service_name: str = "kafka", + sasl_kerberos_domain_name: str | None = None, + sasl_oauth_token_provider: object | None = None, + proxy_url: str | None = None, + socks5_proxy: str | None = None, + kafka_client: Callable[..., object] = ..., + ) -> None: ... + def bootstrap_connected(self): ... + def bootstrap(self, timeout_ms: float | None = None, refresh: bool = False) -> None: ... + def assign(self, partitions: Iterable[TopicPartition]) -> None: ... + def assignment(self) -> set[TopicPartition]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self, autocommit: bool = True, timeout_ms: float | None = None) -> None: ... + def commit_async( + self, offsets: Mapping[TopicPartition, OffsetAndMetadata] | None = None, callback: _CommitCallback | None = None + ) -> Future: ... + def commit( + self, offsets: Mapping[TopicPartition, OffsetAndMetadata] | None = None, timeout_ms: float | None = None + ) -> None: ... + def group_metadata(self): ... + + @overload + def committed( + self, partition: TopicPartition, metadata: Literal[False] = False, timeout_ms: float | None = None + ) -> int | None: ... + @overload + def committed( + self, partition: TopicPartition, metadata: Literal[True], timeout_ms: float | None = None + ) -> OffsetAndMetadata | None: ... + @overload + def committed( + self, partition: TopicPartition, metadata: bool, timeout_ms: float | None = None + ) -> int | OffsetAndMetadata | None: ... + + def topics(self) -> set[str]: ... + def partitions_for_topic(self, topic: str) -> set[int]: ... + def poll( + self, timeout_ms: float = 0, max_records: int | None = None, update_offsets: bool = True + ) -> dict[TopicPartition, list[ConsumerRecord]]: ... + def position(self, partition: TopicPartition, timeout_ms: float | None = None) -> int | None: ... + def highwater(self, partition: TopicPartition) -> int | None: ... + def pause(self, *partitions: TopicPartition) -> None: ... + def paused(self) -> set[TopicPartition]: ... + def resume(self, *partitions: TopicPartition) -> None: ... + def seek(self, partition: TopicPartition, offset: int) -> None: ... + def seek_to_beginning(self, *partitions: TopicPartition) -> None: ... + def seek_to_end(self, *partitions: TopicPartition) -> None: ... + def subscribe( + self, topics: Iterable[str] = (), pattern: str | None = None, listener: ConsumerRebalanceListener | None = None + ) -> None: ... + def subscription(self) -> set[str]: ... + def unsubscribe(self) -> None: ... + def metrics(self, raw: bool = False) -> dict[str, dict[str, object]] | dict[object, object] | None: ... + def offsets_for_times( + self, timestamps: Mapping[TopicPartition, int], timeout_ms: float | None = None + ) -> dict[TopicPartition, OffsetAndTimestamp | None]: ... + def beginning_offsets( + self, partitions: Iterable[TopicPartition], timeout_ms: float | None = None + ) -> dict[TopicPartition, int]: ... + def end_offsets(self, partitions: Iterable[TopicPartition], timeout_ms: float | None = None) -> dict[TopicPartition, int]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> ConsumerRecord: ... diff --git a/stubs/kafka-python/kafka/consumer/subscription_state.pyi b/stubs/kafka-python/kafka/consumer/subscription_state.pyi new file mode 100644 index 000000000000..c72410406b58 --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/subscription_state.pyi @@ -0,0 +1,156 @@ +import abc +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.structs import OffsetAndMetadata +from kafka.util import synchronized + +class SubscriptionType(IntEnum): + NONE = 0 + AUTO_TOPICS = 1 + AUTO_PATTERN = 2 + USER_ASSIGNED = 3 + +class SubscriptionState: + subscription: Incomplete + subscription_type: Incomplete + subscribed_pattern: Incomplete + assignment: Incomplete + rebalance_listener: Incomplete + listeners: Incomplete + def __init__(self, offset_reset_strategy: str = "earliest") -> None: ... + @synchronized + def subscribe(self, topics=(), pattern=None, listener=None) -> None: ... + @synchronized + def change_subscription(self, topics) -> None: ... + @synchronized + def group_subscribe(self, topics) -> None: ... + @synchronized + def reset_group_subscription(self) -> None: ... + @synchronized + def assign_from_user(self, partitions) -> None: ... + @synchronized + def assign_from_subscribed(self, assignments) -> None: ... + @synchronized + def unsubscribe(self) -> None: ... + @synchronized + def group_subscription(self): ... + @synchronized + def seek(self, partition, offset) -> None: ... + @synchronized + def assigned_partitions(self): ... + @synchronized + def paused_partitions(self): ... + @synchronized + def fetchable_partitions(self): ... + @synchronized + def partitions_auto_assigned(self): ... + @synchronized + def all_consumed_offsets(self): ... + @synchronized + def request_offset_reset(self, partition, offset_reset_strategy=None) -> None: ... + @synchronized + def set_reset_pending(self, partitions, next_allowed_reset_time) -> None: ... + @synchronized + def has_default_offset_reset_policy(self): ... + @synchronized + def is_offset_reset_needed(self, partition): ... + @synchronized + def has_all_fetch_positions(self): ... + @synchronized + def missing_fetch_positions(self): ... + @synchronized + def has_valid_position(self, partition): ... + @synchronized + def reset_missing_positions(self) -> None: ... + @synchronized + def partitions_needing_reset(self): ... + @synchronized + def next_offset_reset_retry_time(self): ... + @synchronized + def maybe_validate_position_for_current_leader(self, partition, current_leader_epoch) -> bool: ... + @synchronized + def request_position_validation(self, partition) -> bool: ... + @synchronized + def partitions_needing_validation(self) -> set[Incomplete]: ... + @synchronized + def next_offset_validation_retry_time(self): ... + @synchronized + def set_validation_pending(self, partitions, next_allowed_retry_time) -> None: ... + @synchronized + def validation_failed(self, partitions, next_allowed_retry_time) -> None: ... + @synchronized + def complete_validation(self, partition, validated_position=None) -> None: ... + @synchronized + def is_offset_validation_needed(self, partition) -> bool: ... + @synchronized + def is_assigned(self, partition) -> bool: ... + @synchronized + def is_paused(self, partition): ... + @synchronized + def is_fetchable(self, partition) -> bool: ... + @synchronized + def pause(self, partition) -> None: ... + @synchronized + def resume(self, partition) -> None: ... + @synchronized + def mark_pending_revocation(self, partitions) -> None: ... + @synchronized + def reset_failed(self, partitions, next_retry_time) -> None: ... + @synchronized + def move_partition_to_end(self, partition) -> None: ... + @synchronized + def position(self, partition): ... + +class TopicPartitionState: + paused: bool + reset_strategy: Incomplete + highwater: Incomplete + drop_pending_record_batch: bool + next_allowed_retry_time: Incomplete + def __init__(self) -> None: ... + + @property + def position(self) -> OffsetAndMetadata | None: ... + @position.setter + def position(self, offset: OffsetAndMetadata) -> None: ... + + def reset(self, strategy) -> None: ... + def is_reset_allowed(self) -> bool: ... + @property + def awaiting_reset(self) -> bool: ... + def set_reset_pending(self, next_allowed_retry_time) -> None: ... + def reset_failed(self, next_allowed_retry_time) -> None: ... + @property + def has_valid_position(self) -> bool: ... + def is_missing_position(self) -> bool: ... + def seek(self, offset) -> None: ... + def pause(self) -> None: ... + def resume(self) -> None: ... + def mark_pending_revocation(self, val: bool = True) -> None: ... + def is_fetchable(self) -> bool: ... + def preferred_read_replica(self): ... + def update_preferred_read_replica(self, node_id, expiration_time) -> bool: ... + def clear_preferred_read_replica(self): ... + @property + def awaiting_validation(self) -> bool: ... + def maybe_validate_position(self, current_leader_epoch) -> bool: ... + def request_position_validation(self) -> bool: ... + def is_validation_allowed(self) -> bool: ... + def set_validation_pending(self, next_allowed_retry_time) -> None: ... + def validation_failed(self, next_allowed_retry_time) -> None: ... + def complete_validation(self, validated_position=None) -> None: ... + +class ConsumerRebalanceListener(metaclass=abc.ABCMeta): + @abc.abstractmethod + def on_partitions_revoked(self, revoked): ... + @abc.abstractmethod + def on_partitions_assigned(self, assigned): ... + def on_partitions_lost(self, lost): ... + +class AsyncConsumerRebalanceListener(metaclass=abc.ABCMeta): + @abc.abstractmethod + async def on_partitions_revoked(self, revoked): ... + @abc.abstractmethod + async def on_partitions_assigned(self, assigned): ... + async def on_partitions_lost(self, lost): ... diff --git a/stdlib/@python2/distutils/command/install_scripts.pyi b/stubs/kafka-python/kafka/coordinator/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/install_scripts.pyi rename to stubs/kafka-python/kafka/coordinator/__init__.pyi diff --git a/stdlib/@python2/distutils/command/register.pyi b/stubs/kafka-python/kafka/coordinator/assignors/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/register.pyi rename to stubs/kafka-python/kafka/coordinator/assignors/__init__.pyi diff --git a/stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi b/stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi new file mode 100644 index 000000000000..c7240602d27f --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi @@ -0,0 +1,18 @@ +import abc +from enum import IntEnum + +class RebalanceProtocol(IntEnum): + EAGER = 0 + COOPERATIVE = 1 + +class AbstractPartitionAssignor(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self): ... + def supported_protocols(self) -> list[RebalanceProtocol]: ... + @abc.abstractmethod + def assign(self, cluster, members): ... + @abc.abstractmethod + def metadata(self, topics): ... + @abc.abstractmethod + def on_assignment(self, assignment, generation): ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/cooperative_sticky.pyi b/stubs/kafka-python/kafka/coordinator/assignors/cooperative_sticky.pyi new file mode 100644 index 000000000000..90a108a19604 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/cooperative_sticky.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from kafka.coordinator.assignors.abstract import RebalanceProtocol +from kafka.coordinator.assignors.sticky.sticky_assignor import StickyAssignorMemberMetadataV1, StickyPartitionAssignor +from kafka.protocol.consumer.metadata import ConsumerProtocolAssignment, ConsumerProtocolSubscription + +class CooperativeStickyAssignor(StickyPartitionAssignor): + name: str + version: int + def supported_protocols(self) -> list[RebalanceProtocol]: ... + def metadata(self, topics) -> ConsumerProtocolSubscription: ... + @classmethod + def parse_member_metadata(cls, metadata) -> StickyAssignorMemberMetadataV1: ... + def assign(self, cluster, members) -> dict[Incomplete, ConsumerProtocolAssignment]: ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/range.pyi b/stubs/kafka-python/kafka/coordinator/assignors/range.pyi new file mode 100644 index 000000000000..aad327525b18 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/range.pyi @@ -0,0 +1,12 @@ +from kafka.coordinator.assignors.abstract import AbstractPartitionAssignor +from kafka.protocol.consumer.metadata import ConsumerProtocolSubscription + +class RangePartitionAssignor(AbstractPartitionAssignor): + name: str + version: int + @classmethod + def assign(cls, cluster, members): ... + @classmethod + def metadata(cls, topics) -> ConsumerProtocolSubscription: ... + @classmethod + def on_assignment(cls, assignment, generation) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi b/stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi new file mode 100644 index 000000000000..f09cc9f47677 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi @@ -0,0 +1,12 @@ +from kafka.coordinator.assignors.abstract import AbstractPartitionAssignor +from kafka.protocol.consumer.metadata import ConsumerProtocolSubscription + +class RoundRobinPartitionAssignor(AbstractPartitionAssignor): + name: str + version: int + @classmethod + def assign(cls, cluster, members): ... + @classmethod + def metadata(cls, topics) -> ConsumerProtocolSubscription: ... + @classmethod + def on_assignment(cls, assignment, generation) -> None: ... diff --git a/stdlib/@python2/distutils/command/sdist.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/__init__.pyi similarity index 100% rename from stdlib/@python2/distutils/command/sdist.pyi rename to stubs/kafka-python/kafka/coordinator/assignors/sticky/__init__.pyi diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi new file mode 100644 index 000000000000..ff8e506ab9a0 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +class ConsumerPair(NamedTuple): + src_member_id: Incomplete + dst_member_id: Incomplete + +def is_sublist(source, target): ... + +class PartitionMovements: + partition_movements_by_topic: Incomplete + partition_movements: Incomplete + def __init__(self) -> None: ... + def move_partition(self, partition, old_consumer, new_consumer) -> None: ... + def get_partition_to_be_moved(self, partition, old_consumer, new_consumer): ... + def are_sticky(self): ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi new file mode 100644 index 000000000000..670cfe6b9c0b --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class SortedSet: + def __init__(self, iterable=None, key=None) -> None: ... + def first(self): ... + def last(self): ... + def pop_last(self): ... + def add(self, value): ... + def remove(self, value): ... + def __contains__(self, value) -> bool: ... + def __iter__(self): ... + __nonzero__: Incomplete + __bool__: Incomplete diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi new file mode 100644 index 000000000000..225f3a05d47f --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from typing import Final, NamedTuple + +from kafka.coordinator.assignors.abstract import AbstractPartitionAssignor +from kafka.protocol.consumer.metadata import ConsumerProtocolAssignment, ConsumerProtocolSubscription + +class ConsumerGenerationPair(NamedTuple): + consumer: Incomplete + generation: Incomplete + +def has_identical_list_elements(list_): ... +def subscriptions_comparator_key(element): ... +def partitions_comparator_key(element): ... +def remove_if_present(collection, element) -> None: ... + +class StickyAssignorMemberMetadataV1(NamedTuple): + subscription: Incomplete + partitions: Incomplete + generation: Incomplete + +class StickyAssignmentExecutor: + members: Incomplete + current_assignment: Incomplete + previous_assignment: Incomplete + current_partition_consumer: Incomplete + is_fresh_assignment: bool + partition_to_all_potential_consumers: Incomplete + consumer_to_all_potential_partitions: Incomplete + sorted_current_subscriptions: Incomplete + sorted_partitions: Incomplete + unassigned_partitions: Incomplete + revocation_required: bool + partition_movements: Incomplete + def __init__(self, cluster, members) -> None: ... + def perform_initial_assignment(self) -> None: ... + def balance(self) -> None: ... + def get_final_assignment(self, member_id): ... + +class StickyPartitionAssignor(AbstractPartitionAssignor): + DEFAULT_GENERATION_ID: Final = -1 + name: str + version: int + member_assignment: Incomplete | None + generation: int + def __init__(self) -> None: ... + def assign(self, cluster, members) -> dict[Incomplete, ConsumerProtocolAssignment]: ... + @classmethod + def parse_member_metadata(cls, metadata) -> StickyAssignorMemberMetadataV1: ... + def metadata(self, topics) -> ConsumerProtocolSubscription: ... + def on_assignment(self, assignment, generation) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/user_data.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/user_data.pyi new file mode 100644 index 000000000000..041f58055293 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/user_data.pyi @@ -0,0 +1,6 @@ +from kafka.protocol.api_data import ApiData + +class StickyAssignorUserData(ApiData): + def __init__(self, *args, **kw) -> None: ... + # TODO: Reflect TopicPartition, generation, previous_assignment attributes + def __getattr__(self, name: str): ... # incomplete class diff --git a/stubs/kafka-python/kafka/coordinator/base.pyi b/stubs/kafka-python/kafka/coordinator/base.pyi new file mode 100644 index 000000000000..7290b0084190 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/base.pyi @@ -0,0 +1,71 @@ +import abc +from _typeshed import Incomplete +from typing import ClassVar, Final +from typing_extensions import deprecated + +from kafka import errors as Errors +from kafka.structs import ConsumerGroupMetadata + +class Generation: + NO_GENERATION: ClassVar[Generation] + generation_id: Incomplete + member_id: Incomplete + protocol: Incomplete + def __init__(self, generation_id, member_id, protocol) -> None: ... + def has_member_id(self) -> bool: ... + def is_lost(self) -> bool: ... + def __eq__(self, other) -> bool: ... + +class UnjoinedGroupException(Errors.KafkaError): ... + +class BaseCoordinator(metaclass=abc.ABCMeta): + DEFAULT_CONFIG: Incomplete + config: Incomplete + heartbeat: Incomplete + rejoin_needed: bool + rejoining: bool + state: Incomplete + coordinator_id: Incomplete + DEFAULT_SESSION_TIMEOUT_MS_PRE_KIP_735: Final = 30000 + def __init__(self, client, **configs) -> None: ... + @property + def group_id(self): ... + @property + def group_instance_id(self): ... + @abc.abstractmethod + def protocol_type(self): ... + @abc.abstractmethod + def group_protocols(self): ... + def coordinator_unknown(self): ... + def coordinator(self): ... + def stable(self) -> bool: ... + def ensure_coordinator_ready(self, timeout_ms=None) -> bool: ... + async def ensure_coordinator_ready_async(self, timeout_ms=None) -> bool: ... + def lookup_coordinator(self): ... + def need_rejoin(self): ... + def poll_heartbeat(self) -> None: ... + def time_to_next_heartbeat(self): ... + def ensure_active_group(self, timeout_ms=None) -> bool: ... + async def ensure_active_group_async(self, timeout_ms=None) -> bool: ... + async def join_group_async(self, timeout_ms=None) -> bool: ... + def coordinator_dead(self, error) -> None: ... + def generation_if_stable(self): ... + def group_metadata(self) -> ConsumerGroupMetadata: ... + @deprecated("Deprecated. Use `coordinator.generation_if_stable()` instead.") + def generation(self): ... + def rebalance_in_progress(self): ... + def reset_generation(self, member_id="") -> None: ... + def request_rejoin(self) -> None: ... + def close(self, timeout_ms=None) -> None: ... + def is_dynamic_member(self): ... + def maybe_leave_group(self, reason=None, timeout_ms=None) -> None: ... + async def maybe_leave_group_async(self, reason=None, timeout_ms=None) -> None: ... + +class GroupCoordinatorMetrics: + heartbeat: Incomplete + metrics: Incomplete + metric_group_name: Incomplete + heartbeat_latency: Incomplete + join_latency: Incomplete + sync_latency: Incomplete + def __init__(self, heartbeat, metrics, prefix, tags=None) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/consumer.pyi b/stubs/kafka-python/kafka/coordinator/consumer.pyi new file mode 100644 index 000000000000..afb7537724b3 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/consumer.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from kafka.coordinator.base import BaseCoordinator + +class ConsumerCoordinator(BaseCoordinator): + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + auto_commit_interval: Incomplete + next_auto_commit_deadline: Incomplete + completed_offset_commits: Incomplete + def __init__(self, client, subscription, **configs) -> None: ... + def protocol_type(self) -> str: ... + def group_protocols(self) -> list[tuple[Incomplete, Incomplete]]: ... + def poll(self, timeout_ms=None) -> bool: ... + def time_to_next_poll(self): ... + def need_rejoin(self) -> bool: ... + def refresh_committed_offsets_if_needed(self, timeout_ms=None): ... + async def refresh_committed_offsets_if_needed_async(self, timeout_ms=None) -> bool: ... + def fetch_committed_offsets(self, partitions, timeout_ms=None): ... + async def fetch_committed_offsets_async(self, partitions, timeout_ms=None): ... + def close(self, autocommit: bool = True, timeout_ms=None) -> None: ... # type: ignore[override] + def commit_offsets_async(self, offsets, callback=None): ... + def commit_offsets_sync(self, offsets, timeout_ms=None): ... + def maybe_auto_commit_offsets_now(self) -> None: ... + +class ConsumerCoordinatorMetrics: + metrics: Incomplete + metric_group_name: Incomplete + commit_latency: Incomplete + def __init__(self, metrics, metric_group_prefix, subscription) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/heartbeat.pyi b/stubs/kafka-python/kafka/coordinator/heartbeat.pyi new file mode 100644 index 000000000000..87bb2db6ff5d --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/heartbeat.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +class Heartbeat: + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + last_send: float + last_receive: float + last_poll: float + last_reset: float + heartbeat_failed: bool | None + def __init__(self, **configs) -> None: ... + def poll(self) -> None: ... + def sent_heartbeat(self) -> None: ... + def fail_heartbeat(self) -> None: ... + def received_heartbeat(self) -> None: ... + def time_to_next_heartbeat(self): ... + def should_heartbeat(self): ... + def session_timeout_expired(self): ... + def reset_timeouts(self) -> None: ... + def poll_timeout_expired(self): ... diff --git a/stubs/kafka-python/kafka/coordinator/subscription.pyi b/stubs/kafka-python/kafka/coordinator/subscription.pyi new file mode 100644 index 000000000000..8fc9b3fdb31d --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/subscription.pyi @@ -0,0 +1,14 @@ +class Subscription: + __slots__ = ("_metadata", "_group_instance_id") + def __init__(self, metadata, group_instance_id) -> None: ... + @property + def version(self): ... + @property + def user_data(self): ... + @property + def topics(self): ... + subscription = topics + @property + def group_instance_id(self): ... + def encode(self): ... + def __eq__(self, other): ... diff --git a/stubs/kafka-python/kafka/errors.pyi b/stubs/kafka-python/kafka/errors.pyi new file mode 100644 index 000000000000..9d5f0604eda8 --- /dev/null +++ b/stubs/kafka-python/kafka/errors.pyi @@ -0,0 +1,702 @@ +from _typeshed import Incomplete + +class KafkaError(Exception): + retriable: bool + invalid_metadata: bool + def __eq__(self, other): ... + +class RetriableError(KafkaError): + retriable: bool + +class InvalidMetadataError(RetriableError): + invalid_metadata: bool + +class Cancelled(RetriableError): ... + +class CommitFailedError(KafkaError): + def __init__(self, *args) -> None: ... + +class IllegalArgumentError(KafkaError): ... +class IllegalStateError(KafkaError): ... +class KafkaConfigurationError(KafkaError): ... +class KafkaConnectionError(InvalidMetadataError): ... +class KafkaProtocolError(KafkaError): ... +class CorrelationIdError(RetriableError, KafkaProtocolError): ... +class InvalidReceiveError(KafkaProtocolError): ... +class KafkaTimeoutError(KafkaError): ... +class MetadataEmptyBrokerList(KafkaError): ... +class NoOffsetForPartitionError(KafkaError): ... + +class LogTruncationError(KafkaError): + divergent_offsets: Incomplete + def __init__(self, divergent_offsets, *args): ... + +class NodeNotReadyError(RetriableError): ... +class UnknownBrokerIdError(KafkaError): ... +class QuotaViolationError(KafkaError): ... +class StaleMetadata(InvalidMetadataError): ... +class TooManyInFlightRequests(RetriableError): ... +class UnrecognizedBrokerVersion(KafkaError): ... +class UnsupportedCodecError(KafkaError): ... + +class TransactionAbortedError(KafkaError): + message: str + +class BrokerResponseError(KafkaError): + errno: Incomplete + message: Incomplete + description: Incomplete + +class AuthorizationError(BrokerResponseError): ... + +class NoError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownError(BrokerResponseError): + errno: int + message: str + description: str + +class OffsetOutOfRangeError(BrokerResponseError): + errno: int + message: str + description: str + +class CorruptRecordError(BrokerResponseError): + errno: int + message: str + description: str + +CorruptRecordException = CorruptRecordError + +class UnknownTopicOrPartitionError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class InvalidFetchRequestError(BrokerResponseError): + errno: int + message: str + description: str + +class LeaderNotAvailableError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class NotLeaderForPartitionError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class RequestTimedOutError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class BrokerNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + +class ReplicaNotAvailableError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class MessageSizeTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class StaleControllerEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class OffsetMetadataTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class NetworkExceptionError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + +class CoordinatorLoadInProgressError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class CoordinatorNotAvailableError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class NotCoordinatorError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class InvalidTopicError(BrokerResponseError): + errno: int + message: str + description: str + +class RecordListTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class NotEnoughReplicasError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class NotEnoughReplicasAfterAppendError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class InvalidRequiredAcksError(BrokerResponseError): + errno: int + message: str + description: str + +class IllegalGenerationError(BrokerResponseError): + errno: int + message: str + description: str + +class InconsistentGroupProtocolError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidGroupIdError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownMemberIdError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidSessionTimeoutError(BrokerResponseError): + errno: int + message: str + description: str + +class RebalanceInProgressError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidCommitOffsetSizeError(BrokerResponseError): + errno: int + message: str + description: str + +class TopicAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class GroupAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class ClusterAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class InvalidTimestampError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedSaslMechanismError(BrokerResponseError): + errno: int + message: str + description: str + +class IllegalSaslStateError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedVersionError(BrokerResponseError): + errno: int + message: str + description: str + +class IncompatibleBrokerVersion(UnsupportedVersionError): ... + +class TopicAlreadyExistsError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidPartitionsError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidReplicationFactorError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidReplicationAssignmentError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidConfigurationError(BrokerResponseError): + errno: int + message: str + description: str + +class NotControllerError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class InvalidRequestError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedForMessageFormatError(BrokerResponseError): + errno: int + message: str + description: str + +class PolicyViolationError(BrokerResponseError): + errno: int + message: str + description: str + +class OutOfOrderSequenceNumberError(BrokerResponseError): + errno: int + message: str + description: str + +class DuplicateSequenceNumberError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidProducerEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidTxnStateError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidProducerIdMappingError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidTransactionTimeoutError(BrokerResponseError): + errno: int + message: str + description: str + +class ConcurrentTransactionsError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class TransactionCoordinatorFencedError(BrokerResponseError): + errno: int + message: str + description: str + +class TransactionalIdAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class SecurityDisabledError(BrokerResponseError): + errno: int + message: str + description: str + +class OperationNotAttemptedError(BrokerResponseError): + errno: int + message: str + description: str + +class KafkaStorageError(BrokerResponseError): + errno: int + message: str + description: str + +class LogDirNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +class SaslAuthenticationFailedError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownProducerIdError(BrokerResponseError): + errno: int + message: str + description: str + +class ReassignmentInProgressError(BrokerResponseError): + errno: int + message: str + description: str + +class DelegationTokenAuthDisabledError(BrokerResponseError): + errno: int + message: str + description: str + +class DelegationTokenNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +class DelegationTokenOwnerMismatchError(BrokerResponseError): + errno: int + message: str + description: str + +class DelegationTokenRequestNotAllowedError(BrokerResponseError): + errno: int + message: str + description: str + +class DelegationTokenAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class DelegationTokenExpiredError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidPrincipalTypeError(BrokerResponseError): + errno: int + message: str + description: str + +class NonEmptyGroupError(BrokerResponseError): + errno: int + message: str + description: str + +class GroupIdNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +class FetchSessionIdNotFoundError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class InvalidFetchSessionEpochError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class ListenerNotFoundError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class TopicDeletionDisabledError(BrokerResponseError): + errno: int + message: str + description: str + +class FencedLeaderEpochError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class UnknownLeaderEpochError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedCompressionTypeError(BrokerResponseError): + errno: int + message: str + description: str + +class StaleBrokerEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class OffsetNotAvailableError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class MemberIdRequiredError(BrokerResponseError): + errno: int + message: str + description: str + +class PreferredLeaderNotAvailableError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class GroupMaxSizeReachedError(BrokerResponseError): + errno: int + message: str + description: str + +class FencedInstanceIdError(BrokerResponseError): + errno: int + message: str + description: str + +class EligibleLeadersNotAvailableError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class ElectionNotNeededError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class NoReassignmentInProgressError(BrokerResponseError): + errno: int + message: str + description: str + +class GroupSubscribedToTopicError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidRecordError(BrokerResponseError): + errno: int + message: str + description: str + +class UnstableOffsetCommitError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class ThrottlingQuotaExceededError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class ProducerFencedError(BrokerResponseError): + errno: int + message: str + description: str + +class ResourceNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +class DuplicateResourceError(BrokerResponseError): + errno: int + message: str + description: str + +class UnacceptableCredentialError(BrokerResponseError): + errno: int + message: str + description: str + +class InconsistentVoterSetError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidUpdateVersionError(BrokerResponseError): + errno: int + message: str + description: str + +class FeatureUpdateFailedError(BrokerResponseError): + errno: int + message: str + description: str + +class PrincipalDeserializationFailureError(BrokerResponseError): + errno: int + message: str + description: str + +class SnapshotNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +class PositionOutOfRangeError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownTopicIdError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class DuplicateBrokerRegistrationError(BrokerResponseError): + errno: int + message: str + description: str + +class BrokerIdNotRegisteredError(BrokerResponseError): + errno: int + message: str + description: str + +class InconsistentTopicIdError(InvalidMetadataError, BrokerResponseError): + errno: int + message: str + description: str + +class InconsistentClusterIdError(BrokerResponseError): + errno: int + message: str + description: str + +class TransactionalIdNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +class FetchSessionTopicIdError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class IneligibleReplicaError(BrokerResponseError): + errno: int + message: str + description: str + +class NewLeaderElectedError(BrokerResponseError): + errno: int + message: str + description: str + +class OffsetMovedToTieredStorageError(BrokerResponseError): + errno: int + message: str + description: str + +class FencedMemberEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class UnreleasedInstanceIdError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedAssignorError(BrokerResponseError): + errno: int + message: str + description: str + +class StaleMemberEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class MismatchedEndpointTypeError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedEndpointTypeError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownControllerIdError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownSubscriptionIdError(BrokerResponseError): + errno: int + message: str + description: str + +class TelemetryTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidRegistrationError(BrokerResponseError): + errno: int + message: str + description: str + +class TransactionAbortableError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidRecordStateError(BrokerResponseError): + errno: int + message: str + description: str + +class ShareSessionNotFoundError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class InvalidShareSessionEpochError(RetriableError, BrokerResponseError): + errno: int + message: str + description: str + +class FencedStateEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidVoterKeyError(BrokerResponseError): + errno: int + message: str + description: str + +class DuplicateVoterError(BrokerResponseError): + errno: int + message: str + description: str + +class VoterNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + +kafka_errors: Incomplete + +def for_code(error_code): ... diff --git a/stubs/kafka-python/kafka/future.pyi b/stubs/kafka-python/kafka/future.pyi new file mode 100644 index 000000000000..42ea198f2582 --- /dev/null +++ b/stubs/kafka-python/kafka/future.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing_extensions import Self + +class Future: + __slots__ = ("is_done", "value", "exception", "_callbacks", "_errbacks", "_lock") + error_on_callbacks: bool + is_done: bool + value: Incomplete + exception: Incomplete + def __init__(self) -> None: ... + def succeeded(self) -> bool: ... + def failed(self) -> bool: ... + def retriable(self) -> bool: ... + def success(self, value) -> Self: ... + def failure(self, e) -> Self: ... + def add_callback(self, f, *args, **kwargs) -> Self: ... + def add_errback(self, f, *args, **kwargs) -> Self: ... + def add_both(self, f, *args, **kwargs) -> Self: ... + def chain(self, future) -> Self: ... + def __await__(self) -> Generator[Self]: ... diff --git a/stubs/kafka-python/kafka/metrics/__init__.pyi b/stubs/kafka-python/kafka/metrics/__init__.pyi new file mode 100644 index 000000000000..9e6b062abd21 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/__init__.pyi @@ -0,0 +1,10 @@ +from kafka.metrics.compound_stat import NamedMeasurable as NamedMeasurable +from kafka.metrics.dict_reporter import DictReporter as DictReporter +from kafka.metrics.kafka_metric import KafkaMetric as KafkaMetric +from kafka.metrics.measurable import AnonMeasurable as AnonMeasurable +from kafka.metrics.metric_config import MetricConfig as MetricConfig +from kafka.metrics.metric_name import MetricName as MetricName +from kafka.metrics.metrics import Metrics as Metrics +from kafka.metrics.quota import Quota as Quota + +__all__ = ["AnonMeasurable", "DictReporter", "KafkaMetric", "MetricConfig", "MetricName", "Metrics", "NamedMeasurable", "Quota"] diff --git a/stubs/kafka-python/kafka/metrics/compound_stat.pyi b/stubs/kafka-python/kafka/metrics/compound_stat.pyi new file mode 100644 index 000000000000..66ad951e5bb2 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/compound_stat.pyi @@ -0,0 +1,15 @@ +import abc + +from kafka.metrics.stat import AbstractStat + +class AbstractCompoundStat(AbstractStat, metaclass=abc.ABCMeta): + @abc.abstractmethod + def stats(self): ... + +class NamedMeasurable: + __slots__ = ("_name", "_stat") + def __init__(self, metric_name, measurable_stat) -> None: ... + @property + def name(self): ... + @property + def stat(self): ... diff --git a/stubs/kafka-python/kafka/metrics/dict_reporter.pyi b/stubs/kafka-python/kafka/metrics/dict_reporter.pyi new file mode 100644 index 000000000000..45ca2b302d44 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/dict_reporter.pyi @@ -0,0 +1,11 @@ +from kafka.metrics.metrics_reporter import AbstractMetricsReporter + +class DictReporter(AbstractMetricsReporter): + def __init__(self, prefix: str = "") -> None: ... + def snapshot(self): ... + def init(self, metrics) -> None: ... + def metric_change(self, metric) -> None: ... + def metric_removal(self, metric): ... + def get_category(self, metric) -> str: ... + def configure(self, configs) -> None: ... + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/kafka_metric.pyi b/stubs/kafka-python/kafka/metrics/kafka_metric.pyi new file mode 100644 index 000000000000..471e2b36721a --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/kafka_metric.pyi @@ -0,0 +1,14 @@ +class KafkaMetric: + __slots__ = ("_metric_name", "_measurable", "_config") + def __init__(self, metric_name, measurable, config) -> None: ... + @property + def metric_name(self): ... + @property + def measurable(self): ... + + @property + def config(self): ... + @config.setter + def config(self, config) -> None: ... + + def value(self, time_ms=None): ... diff --git a/stubs/kafka-python/kafka/metrics/measurable.pyi b/stubs/kafka-python/kafka/metrics/measurable.pyi new file mode 100644 index 000000000000..2753796bc8cd --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/measurable.pyi @@ -0,0 +1,9 @@ +import abc + +class AbstractMeasurable(metaclass=abc.ABCMeta): + @abc.abstractmethod + def measure(self, config, now): ... + +class AnonMeasurable(AbstractMeasurable): + def __init__(self, measure_fn) -> None: ... + def measure(self, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/measurable_stat.pyi b/stubs/kafka-python/kafka/metrics/measurable_stat.pyi new file mode 100644 index 000000000000..31569f41942a --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/measurable_stat.pyi @@ -0,0 +1,6 @@ +import abc + +from kafka.metrics.measurable import AbstractMeasurable +from kafka.metrics.stat import AbstractStat + +class AbstractMeasurableStat(AbstractStat, AbstractMeasurable, metaclass=abc.ABCMeta): ... diff --git a/stubs/kafka-python/kafka/metrics/metric_config.pyi b/stubs/kafka-python/kafka/metrics/metric_config.pyi new file mode 100644 index 000000000000..da5d6f475216 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metric_config.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class MetricConfig: + __slots__ = ("quota", "_samples", "event_window", "time_window_ms", "tags") + quota: Incomplete + event_window: Incomplete + time_window_ms: Incomplete + tags: Incomplete + def __init__(self, quota=None, samples: int = 2, event_window=..., time_window_ms=30000, tags=None) -> None: ... + + @property + def samples(self): ... + @samples.setter + def samples(self, value) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/metric_name.pyi b/stubs/kafka-python/kafka/metrics/metric_name.pyi new file mode 100644 index 000000000000..61d2b007278b --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metric_name.pyi @@ -0,0 +1,14 @@ +class MetricName: + __slots__ = ("_name", "_group", "_description", "_tags", "_hash") + def __init__(self, name, group, description=None, tags=None) -> None: ... + @property + def name(self): ... + @property + def group(self): ... + @property + def description(self): ... + @property + def tags(self): ... + def __hash__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... diff --git a/stubs/kafka-python/kafka/metrics/metrics.pyi b/stubs/kafka-python/kafka/metrics/metrics.pyi new file mode 100644 index 000000000000..90361cd1d02c --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metrics.pyi @@ -0,0 +1,20 @@ +class Metrics: + def __init__(self, default_config=None, reporters=None, enable_expiration: bool = False) -> None: ... + @property + def config(self): ... + @property + def metrics(self): ... + def metric_name(self, name, group, description: str = "", tags=None): ... + def get_sensor(self, name): ... + def sensor(self, name, config=None, inactive_sensor_expiration_time_seconds=..., parents=None): ... + def remove_sensor(self, name) -> None: ... + def add_metric(self, metric_name, measurable, config=None) -> None: ... + def remove_metric(self, metric_name): ... + def add_reporter(self, reporter) -> None: ... + def register_metric(self, metric) -> None: ... + + class ExpireSensorTask: + @staticmethod + def run(metrics) -> None: ... + + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/metrics_reporter.pyi b/stubs/kafka-python/kafka/metrics/metrics_reporter.pyi new file mode 100644 index 000000000000..e8022ff431d2 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metrics_reporter.pyi @@ -0,0 +1,13 @@ +import abc + +class AbstractMetricsReporter(metaclass=abc.ABCMeta): + @abc.abstractmethod + def init(self, metrics): ... + @abc.abstractmethod + def metric_change(self, metric): ... + @abc.abstractmethod + def metric_removal(self, metric): ... + @abc.abstractmethod + def configure(self, configs): ... + @abc.abstractmethod + def close(self): ... diff --git a/stubs/kafka-python/kafka/metrics/quota.pyi b/stubs/kafka-python/kafka/metrics/quota.pyi new file mode 100644 index 000000000000..a812b66fd6f5 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/quota.pyi @@ -0,0 +1,14 @@ +class Quota: + __slots__ = ("_bound", "_upper") + def __init__(self, bound, is_upper) -> None: ... + @staticmethod + def upper_bound(upper_bound): ... + @staticmethod + def lower_bound(lower_bound): ... + def is_upper_bound(self): ... + @property + def bound(self): ... + def is_acceptable(self, value): ... + def __hash__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... diff --git a/stubs/kafka-python/kafka/metrics/stat.pyi b/stubs/kafka-python/kafka/metrics/stat.pyi new file mode 100644 index 000000000000..d9b5f9473988 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stat.pyi @@ -0,0 +1,5 @@ +import abc + +class AbstractStat(metaclass=abc.ABCMeta): + @abc.abstractmethod + def record(self, config, value, time_ms): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/__init__.pyi b/stubs/kafka-python/kafka/metrics/stats/__init__.pyi new file mode 100644 index 000000000000..bc86bfd66544 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/__init__.pyi @@ -0,0 +1,12 @@ +from kafka.metrics.stats.avg import Avg as Avg +from kafka.metrics.stats.count import Count as Count +from kafka.metrics.stats.histogram import Histogram as Histogram +from kafka.metrics.stats.max_stat import Max as Max +from kafka.metrics.stats.min_stat import Min as Min +from kafka.metrics.stats.percentile import Percentile as Percentile +from kafka.metrics.stats.percentiles import Percentiles as Percentiles +from kafka.metrics.stats.rate import Rate as Rate +from kafka.metrics.stats.sensor import Sensor as Sensor +from kafka.metrics.stats.total import Total as Total + +__all__ = ["Avg", "Count", "Histogram", "Max", "Min", "Percentile", "Percentiles", "Rate", "Sensor", "Total"] diff --git a/stubs/kafka-python/kafka/metrics/stats/avg.pyi b/stubs/kafka-python/kafka/metrics/stats/avg.pyi new file mode 100644 index 000000000000..e500971a4601 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/avg.pyi @@ -0,0 +1,7 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Avg(AbstractSampledStat): + __slots__ = ("_initial_value", "_samples", "_current") + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/count.pyi b/stubs/kafka-python/kafka/metrics/stats/count.pyi new file mode 100644 index 000000000000..9f305e3a81e0 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/count.pyi @@ -0,0 +1,7 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Count(AbstractSampledStat): + __slots__ = ("_initial_value", "_samples", "_current") + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/histogram.pyi b/stubs/kafka-python/kafka/metrics/stats/histogram.pyi new file mode 100644 index 000000000000..b5b013fa8c8e --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/histogram.pyi @@ -0,0 +1,24 @@ +class Histogram: + __slots__ = ("_hist", "_count", "_bin_scheme") + def __init__(self, bin_scheme) -> None: ... + def record(self, value) -> None: ... + def value(self, quantile): ... + @property + def counts(self): ... + def clear(self) -> None: ... + + class ConstantBinScheme: + __slots__ = ("_min", "_max", "_bins", "_bucket_width") + def __init__(self, bins, min_val, max_val) -> None: ... + @property + def bins(self): ... + def from_bin(self, b): ... + def to_bin(self, x): ... + + class LinearBinScheme: + __slots__ = ("_bins", "_max", "_scale") + def __init__(self, num_bins, max_val) -> None: ... + @property + def bins(self): ... + def from_bin(self, b): ... + def to_bin(self, x): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/max_stat.pyi b/stubs/kafka-python/kafka/metrics/stats/max_stat.pyi new file mode 100644 index 000000000000..72f018c796f3 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/max_stat.pyi @@ -0,0 +1,7 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Max(AbstractSampledStat): + __slots__ = ("_initial_value", "_samples", "_current") + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/min_stat.pyi b/stubs/kafka-python/kafka/metrics/stats/min_stat.pyi new file mode 100644 index 000000000000..d3d895e3bbc6 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/min_stat.pyi @@ -0,0 +1,7 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Min(AbstractSampledStat): + __slots__ = ("_initial_value", "_samples", "_current") + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/percentile.pyi b/stubs/kafka-python/kafka/metrics/stats/percentile.pyi new file mode 100644 index 000000000000..bec615ced91f --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/percentile.pyi @@ -0,0 +1,7 @@ +class Percentile: + __slots__ = ("_metric_name", "_percentile") + def __init__(self, metric_name, percentile) -> None: ... + @property + def name(self): ... + @property + def percentile(self): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/percentiles.pyi b/stubs/kafka-python/kafka/metrics/stats/percentiles.pyi new file mode 100644 index 000000000000..5f40f4193eb3 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/percentiles.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from kafka.metrics.compound_stat import AbstractCompoundStat +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class BucketSizing: + CONSTANT: int + LINEAR: int + +class Percentiles(AbstractSampledStat, AbstractCompoundStat): + __slots__ = ("_initial_value", "_samples", "_current", "_percentiles", "_buckets", "_bin_scheme") + def __init__(self, size_in_bytes, bucketing, max_val, min_val: float = 0.0, percentiles=None) -> None: ... + def stats(self): ... + def value(self, config, now, quantile): ... + def combine(self, samples, config, now): ... + def new_sample(self, time_ms): ... + def update(self, sample, config, value, time_ms) -> None: ... + + class HistogramSample(AbstractSampledStat.Sample): + histogram: Incomplete + def __init__(self, scheme, now) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/stats/rate.pyi b/stubs/kafka-python/kafka/metrics/stats/rate.pyi new file mode 100644 index 000000000000..22c4c09cd0ef --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/rate.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from kafka.metrics.measurable_stat import AbstractMeasurableStat +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class TimeUnit: + NANOSECONDS: Incomplete + MICROSECONDS: Incomplete + MILLISECONDS: Incomplete + SECONDS: Incomplete + MINUTES: Incomplete + HOURS: Incomplete + DAYS: Incomplete + @staticmethod + def get_name(time_unit): ... + +class Rate(AbstractMeasurableStat): + __slots__ = ("_stat", "_unit") + def __init__(self, time_unit=3, sampled_stat=None) -> None: ... + def unit_name(self): ... + def record(self, config, value, time_ms) -> None: ... + def measure(self, config, now): ... + def window_size(self, config, now): ... + def convert(self, time_ms): ... + +class SampledTotal(AbstractSampledStat): + __slots__ = ("_initial_value", "_samples", "_current") + def __init__(self, initial_value=None) -> None: ... + def update(self, sample, config, value, time_ms) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi b/stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi new file mode 100644 index 000000000000..f063cc9cff09 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi @@ -0,0 +1,27 @@ +import abc +from _typeshed import Incomplete + +from kafka.metrics.measurable_stat import AbstractMeasurableStat + +class AbstractSampledStat(AbstractMeasurableStat, metaclass=abc.ABCMeta): + __slots__ = ("_initial_value", "_samples", "_current") + def __init__(self, initial_value) -> None: ... + @abc.abstractmethod + def update(self, sample, config, value, time_ms): ... + @abc.abstractmethod + def combine(self, samples, config, now): ... + def record(self, config, value, time_ms) -> None: ... + def new_sample(self, time_ms): ... + def measure(self, config, now): ... + def current(self, time_ms): ... + def oldest(self, now): ... + def purge_obsolete_samples(self, config, now) -> None: ... + + class Sample: + initial_value: Incomplete + event_count: int + last_window_ms: Incomplete + value: Incomplete + def __init__(self, initial_value, now) -> None: ... + def reset(self, now) -> None: ... + def is_complete(self, time_ms, config): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/sensor.pyi b/stubs/kafka-python/kafka/metrics/stats/sensor.pyi new file mode 100644 index 000000000000..af3baa05db05 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/sensor.pyi @@ -0,0 +1,21 @@ +class Sensor: + __slots__ = ( + "_lock", + "_registry", + "_name", + "_parents", + "_metrics", + "_stats", + "_config", + "_inactive_sensor_expiration_time_ms", + "_last_record_time", + ) + def __init__(self, registry, name, parents, config, inactive_sensor_expiration_time_seconds) -> None: ... + @property + def name(self): ... + @property + def metrics(self): ... + def record(self, value: float = 1.0, time_ms=None) -> None: ... + def add_compound(self, compound_stat, config=None) -> None: ... + def add(self, metric_name, stat, config=None) -> None: ... + def has_expired(self): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/total.pyi b/stubs/kafka-python/kafka/metrics/stats/total.pyi new file mode 100644 index 000000000000..bd52102f6cfb --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/total.pyi @@ -0,0 +1,7 @@ +from kafka.metrics.measurable_stat import AbstractMeasurableStat + +class Total(AbstractMeasurableStat): + __slots__ = ("_total",) + def __init__(self, value: float = 0.0) -> None: ... + def record(self, config, value, now) -> None: ... + def measure(self, config, now): ... diff --git a/stubs/kafka-python/kafka/net/__init__.pyi b/stubs/kafka-python/kafka/net/__init__.pyi new file mode 100644 index 000000000000..1a7f3a813291 --- /dev/null +++ b/stubs/kafka-python/kafka/net/__init__.pyi @@ -0,0 +1,26 @@ +from .compat import KafkaNetClient as KafkaNetClient +from .connection import KafkaConnection as KafkaConnection +from .http_connect import HttpConnectProxy as HttpConnectProxy +from .inet import KafkaNetSocket as KafkaNetSocket, create_connection as create_connection +from .manager import KafkaConnectionManager as KafkaConnectionManager +from .metrics import KafkaConnectionMetrics as KafkaConnectionMetrics, KafkaManagerMetrics as KafkaManagerMetrics +from .selector import NetworkSelector as NetworkSelector +from .socks5 import Socks5Proxy as Socks5Proxy +from .transport import KafkaSSLTransport as KafkaSSLTransport, KafkaTCPTransport as KafkaTCPTransport +from .wakeup_notifier import WakeupNotifier as WakeupNotifier + +__all__ = [ + "KafkaConnection", + "create_connection", + "KafkaNetSocket", + "KafkaConnectionManager", + "KafkaConnectionMetrics", + "KafkaManagerMetrics", + "NetworkSelector", + "HttpConnectProxy", + "Socks5Proxy", + "KafkaTCPTransport", + "KafkaSSLTransport", + "WakeupNotifier", + "KafkaNetClient", +] diff --git a/stubs/kafka-python/kafka/net/compat.pyi b/stubs/kafka-python/kafka/net/compat.pyi new file mode 100644 index 000000000000..4998b20c5eb4 --- /dev/null +++ b/stubs/kafka-python/kafka/net/compat.pyi @@ -0,0 +1,24 @@ +class KafkaNetClient: + def __init__(self, net=None, manager=None, **configs) -> None: ... + @property + def cluster(self): ... + def connected(self, node_id) -> bool: ... + def is_disconnected(self, node_id) -> bool: ... + def is_ready(self, node_id) -> bool: ... + def ready(self, node_id, **kwargs) -> bool: ... + def maybe_connect(self, node_id, **kwargs) -> None: ... + def await_ready(self, node_id, timeout_ms=30000): ... + def in_flight_request_count(self, node_id=None) -> int: ... + def throttle_delay(self, node_id) -> int: ... + def bootstrap_connected(self) -> bool: ... + def get_broker_version(self, timeout_ms=None): ... + def check_version(self, node_id=None, timeout_ms=10000): ... + def send(self, node_id, request, **kwargs): ... + def send_and_receive(self, node_id, request, timeout_ms=30000): ... + def poll(self, timeout_ms=None, future=None): ... + def close(self, node_id=None) -> None: ... + def least_loaded_node(self, bootstrap_fallback: bool = False): ... + def least_loaded_node_refresh_ms(self, bootstrap_fallback: bool = False): ... + def connection_delay(self, node_id): ... + def wakeup(self) -> None: ... + def api_version(self, operation, max_version=None): ... diff --git a/stubs/kafka-python/kafka/net/connection.pyi b/stubs/kafka-python/kafka/net/connection.pyi new file mode 100644 index 000000000000..0112c13275ed --- /dev/null +++ b/stubs/kafka-python/kafka/net/connection.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete +from collections import deque +from collections.abc import Generator +from typing_extensions import Self + +from kafka.future import Future + +class KafkaConnection: + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + node_id: Incomplete + net: Incomplete + transport: Incomplete | None + parser: Incomplete | None + paused: set[Incomplete] + connected: bool + initializing: bool + in_flight_requests: deque[tuple[Incomplete, ...]] + broker_version_data: Incomplete + def __init__(self, net, node_id=None, broker_version_data=None, **configs) -> None: ... + @property + def broker_version(self): ... + @property + def closed(self) -> bool: ... + @property + def init_future(self) -> Future: ... + def __await__(self) -> Generator[Future, Incomplete, Self]: ... + @property + def close_future(self) -> Future: ... + def send_request(self, request, request_timeout_ms=None) -> Future: ... + def send_buffered(self) -> None: ... + def data_received(self, data) -> None: ... + def eof_received(self): ... + def connection_lost(self, exc) -> None: ... + def fail_in_flight_requests(self, error) -> None: ... + def connection_made(self, transport) -> None: ... + def pause(self, v) -> None: ... + def unpause(self, v) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + def close(self, error=None) -> None: ... + async def initialize(self, timeout_at: float | None = None) -> None: ... + @property + def sasl_enabled(self) -> bool: ... + +class SaslReauthenticator: + session_lifetime_ms: Incomplete + authenticated_at: float | None + def __init__(self, conn) -> None: ... + @property + def is_reauthenticating(self) -> bool: ... + @property + def task(self): ... + def session_updated(self, session_lifetime_ms) -> None: ... + def schedule(self) -> None: ... + def cancel(self) -> None: ... + def on_response_processed(self) -> None: ... diff --git a/stubs/kafka-python/kafka/net/http_connect.pyi b/stubs/kafka-python/kafka/net/http_connect.pyi new file mode 100644 index 000000000000..976db341ffcd --- /dev/null +++ b/stubs/kafka-python/kafka/net/http_connect.pyi @@ -0,0 +1,10 @@ +import socket as _socket + +from kafka.net.inet import KafkaNetSocket + +class HttpConnectProxy(KafkaNetSocket): + SCHEMES: tuple[str, ...] + def __init__(self, proxy_url) -> None: ... # pyright: ignore[reportInconsistentConstructor] + def dns_lookup(self, host, port, proxy: bool = False): ... + def socket(self, family=..., sock_type=..., proto=...) -> _socket.socket: ... + def connect_ex(self, sock, addr) -> int: ... diff --git a/stubs/kafka-python/kafka/net/inet.pyi b/stubs/kafka-python/kafka/net/inet.pyi new file mode 100644 index 000000000000..2241554661a2 --- /dev/null +++ b/stubs/kafka-python/kafka/net/inet.pyi @@ -0,0 +1,16 @@ +import socket as _socket +from typing_extensions import Self + +async def create_connection(net, host, port, socket_options=(), proxy_url=None, timeout_at=None): ... + +class KafkaNetSocket: + @classmethod + def register_class(cls, klass) -> None: ... + def __init_subclass__(cls, **kw) -> None: ... + def __new__(cls, proxy_url=None) -> Self: ... + def __init__(self, proxy_url=None) -> None: ... + def dns_lookup(self, host, port, raise_error: bool = False): ... + def socket(self, family=..., sock_type=..., proto=...) -> _socket.socket: ... + async def connect(self, net, addrinfo, socket_options=(), timeout_at=None): ... + async def sock_connect(self, net, sock, sockaddr, timeout_at=None): ... + def connect_ex(self, sock, sockaddr): ... diff --git a/stubs/kafka-python/kafka/net/manager.pyi b/stubs/kafka-python/kafka/net/manager.pyi new file mode 100644 index 000000000000..e72d0e139f44 --- /dev/null +++ b/stubs/kafka-python/kafka/net/manager.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from kafka.cluster import ClusterMetadata +from kafka.future import Future +from kafka.protocol.broker_version_data import BrokerVersionData + +class KafkaConnectionManager: + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + cluster: ClusterMetadata + broker_version_data: BrokerVersionData | None + closed: bool + def __init__(self, net, **configs) -> None: ... + @property + def broker_version(self): ... + def least_used_connections(self) -> list[Incomplete]: ... + def bootstrap_async(self, timeout_ms=None, refresh: bool = True): ... + def bootstrap(self, timeout_ms=None, refresh: bool = True) -> None: ... + @property + def bootstrapped(self) -> bool: ... + def close_idle_connections(self) -> None: ... + @property + def ssl_enabled(self) -> bool: ... + def get_connection( + self, + node_id, + timeout_ms=None, + pop_on_close: bool = True, + refresh_metadata_on_err: bool = True, + reset_backoff_on_connect: bool = True, + ): ... + def send(self, request, node_id=None, request_timeout_ms=None): ... + def least_loaded_node(self): ... + def reset_backoff(self, node_id) -> None: ... + def jitter_pct(self) -> float: ... + def update_backoff(self, node_id): ... + def connection_delay(self, node_id) -> int: ... + def socket_connection_setup_timeout_ms(self, node_id): ... + def auth_failure(self, node_id): ... + def maybe_raise_auth_failure(self, node_id) -> None: ... + def close(self, node_id=None, timeout_ms=None) -> None: ... + async def wait_for(self, future, timeout_ms): ... + def call_soon(self, coro, *args) -> Future: ... + def run(self, coro, *args): ... diff --git a/stubs/kafka-python/kafka/net/metrics.pyi b/stubs/kafka-python/kafka/net/metrics.pyi new file mode 100644 index 000000000000..a314a9f2c0e8 --- /dev/null +++ b/stubs/kafka-python/kafka/net/metrics.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +class KafkaManagerMetrics: + metrics: Incomplete + connection_closed: Incomplete + connection_created: Incomplete + def __init__(self, metrics, metric_group_prefix: str, conns) -> None: ... + +class KafkaConnectionMetrics: + metrics: Incomplete + bytes_sent: Incomplete + bytes_received: Incomplete + request_time: Incomplete + throttle_time: Incomplete + def __init__(self, metrics, metric_group_prefix: str, node_id) -> None: ... diff --git a/stubs/kafka-python/kafka/net/sasl/__init__.pyi b/stubs/kafka-python/kafka/net/sasl/__init__.pyi new file mode 100644 index 000000000000..93fcedc0ab97 --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/__init__.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +SASL_MECHANISMS: Incomplete + +def register_sasl_mechanism(name, klass, overwrite: bool = False) -> None: ... +def get_sasl_mechanism(name): ... diff --git a/stubs/kafka-python/kafka/net/sasl/abc.pyi b/stubs/kafka-python/kafka/net/sasl/abc.pyi new file mode 100644 index 000000000000..52d76c08a27c --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/abc.pyi @@ -0,0 +1,14 @@ +import abc + +class SaslMechanism(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __init__(self, **config): ... + @abc.abstractmethod + def auth_bytes(self): ... + @abc.abstractmethod + def receive(self, auth_bytes): ... + @abc.abstractmethod + def is_done(self): ... + @abc.abstractmethod + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/net/sasl/gssapi.pyi b/stubs/kafka-python/kafka/net/sasl/gssapi.pyi new file mode 100644 index 000000000000..cb3140c760b9 --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/gssapi.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from .abc import SaslMechanism + +class SaslMechanismGSSAPI(SaslMechanism): + SASL_QOP_AUTH: int + SASL_QOP_AUTH_INT: int + SASL_QOP_AUTH_CONF: int + gssapi_name: Incomplete + auth_id: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/net/sasl/msk.pyi b/stubs/kafka-python/kafka/net/sasl/msk.pyi new file mode 100644 index 000000000000..272d60726c2b --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/msk.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from .abc import SaslMechanism + +class SaslMechanismAwsMskIam(SaslMechanism): + host: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... + +class AwsMskIamClient: + UNRESERVED_CHARS: Incomplete + algorithm: str + expires: str + hashfunc: Incomplete + headers: Incomplete + version: str + service: str + action: Incomplete + datestamp: Incomplete + timestamp: Incomplete + host: Incomplete + access_key: Incomplete + secret_key: Incomplete + region: Incomplete + token: Incomplete + def __init__(self, host, access_key, secret_key, region, token=None) -> None: ... + def first_message(self): ... diff --git a/stubs/kafka-python/kafka/net/sasl/oauth.pyi b/stubs/kafka-python/kafka/net/sasl/oauth.pyi new file mode 100644 index 000000000000..47876d066958 --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/oauth.pyi @@ -0,0 +1,19 @@ +import abc +from _typeshed import Incomplete + +from .abc import SaslMechanism + +class SaslMechanismOAuth(SaslMechanism): + token_provider: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... + +class AbstractTokenProvider(abc.ABC, metaclass=abc.ABCMeta): + def __init__(self, **config) -> None: ... + @abc.abstractmethod + def token(self): ... + def extensions(self): ... diff --git a/stubs/kafka-python/kafka/net/sasl/plain.pyi b/stubs/kafka-python/kafka/net/sasl/plain.pyi new file mode 100644 index 000000000000..ef14330ae527 --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/plain.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from .abc import SaslMechanism + +class SaslMechanismPlain(SaslMechanism): + username: Incomplete + password: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/net/sasl/scram.pyi b/stubs/kafka-python/kafka/net/sasl/scram.pyi new file mode 100644 index 000000000000..6803c6c15b63 --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/scram.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from .abc import SaslMechanism + +def xor_bytes(left, right) -> bytes: ... + +class SaslMechanismScram(SaslMechanism): + username: Incomplete + mechanism: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes): ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... + +class ScramClient: + MECHANISMS: Incomplete + nonce: Incomplete + auth_message: bytes + salted_password: Incomplete + user: Incomplete + password: Incomplete + hashfunc: Incomplete + hashname: Incomplete + stored_key: Incomplete + client_key: Incomplete + client_signature: Incomplete + client_proof: Incomplete + server_key: Incomplete + server_signature: Incomplete + def __init__(self, user, password, mechanism) -> None: ... + def first_message(self): ... + def process_server_first_message(self, server_first_message) -> None: ... + def hmac(self, key, msg): ... + def create_salted_password(self, salt, iterations) -> None: ... + def final_message(self): ... + def process_server_final_message(self, server_final_message) -> None: ... diff --git a/stubs/kafka-python/kafka/net/sasl/sspi.pyi b/stubs/kafka-python/kafka/net/sasl/sspi.pyi new file mode 100644 index 000000000000..7e7f456f39e5 --- /dev/null +++ b/stubs/kafka-python/kafka/net/sasl/sspi.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from .abc import SaslMechanism + +class SaslMechanismSSPI(SaslMechanism): + SASL_QOP_AUTH: int + SASL_QOP_AUTH_INT: int + SASL_QOP_AUTH_CONF: int + auth_id: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/net/selector.pyi b/stubs/kafka-python/kafka/net/selector.pyi new file mode 100644 index 000000000000..6342c2ecebf2 --- /dev/null +++ b/stubs/kafka-python/kafka/net/selector.pyi @@ -0,0 +1,73 @@ +import enum +from _typeshed import Incomplete +from collections.abc import Generator +from typing import Final +from typing_extensions import Self + +from kafka.future import Future + +MAX_TIMEOUT: Final = 2147483 + +def yield_callback(callback): ... + +class KernelEvent: + method: str + args: tuple[Incomplete, ...] + def __init__(self, method: str, *args) -> None: ... + def __await__(self) -> Generator[Self]: ... + +class TaskState(enum.Enum): + CREATED = "created" + SCHEDULED = "scheduled" + UNSCHEDULED = "unscheduled" + READY = "ready" + RUNNING = "running" + WAIT_IO = "wait_io" + WAIT_FUTURE = "wait_future" + DONE = "done" + CANCELLED = "cancelled" + +class Task: + scheduled_at: Incomplete | None + state: Incomplete + def __init__(self, coro) -> None: ... + def __lt__(self, other) -> bool: ... + def __call__(self, arg=None): ... + def push_stack(self, coro) -> None: ... + def inject_exc(self, exc) -> None: ... + def close(self) -> None: ... + @property + def is_done(self) -> bool: ... + @property + def result(self): ... + @property + def exception(self): ... + +class NetworkSelector: + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + def __init__(self, **configs) -> None: ... + def run_forever(self) -> None: ... + def start(self) -> None: ... + def stop(self, timeout_ms=None) -> None: ... + def run(self, coro, *args): ... + def drain(self, scheduled: bool = False) -> None: ... + def call_at(self, when, task) -> Task: ... + def call_later(self, delay, task) -> Task: ... + def call_soon(self, task) -> Task: ... + def call_soon_threadsafe(self, callback) -> Task: ... + def call_soon_with_future(self, coro, *args) -> Future: ... + def cancel(self, task) -> None: ... + def reschedule(self, when, task): ... + def sleep(self, delay) -> KernelEvent: ... + def wait_write(self, fileobj, timeout_at=None) -> KernelEvent: ... + def wait_read(self, fileobj, timeout_at=None) -> KernelEvent: ... + def register_event(self, fileobj, event, task) -> None: ... + def unregister_event(self, fileobj, event) -> None: ... + def add_reader(self, fileobj, task) -> None: ... + def remove_reader(self, fileobj) -> None: ... + def add_writer(self, fileobj, task) -> None: ... + def remove_writer(self, fileobj) -> None: ... + def poll(self, timeout_ms=None, future=None) -> None: ... + def wakeup(self) -> None: ... + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/net/socks5.pyi b/stubs/kafka-python/kafka/net/socks5.pyi new file mode 100644 index 000000000000..52c11a38ba3c --- /dev/null +++ b/stubs/kafka-python/kafka/net/socks5.pyi @@ -0,0 +1,22 @@ +import socket as _socket +from typing import Final + +from kafka.net.inet import KafkaNetSocket + +class ProxyConnectionStates: + DISCONNECTED: Final = "" + CONNECTING: Final = "" + NEGOTIATE_PROPOSE: Final = "" + NEGOTIATING: Final = "" + AUTHENTICATING: Final = "" + REQUEST_SUBMIT: Final = "" + REQUESTING: Final = "" + READ_ADDRESS: Final = "" + COMPLETE: Final = "" + +class Socks5Proxy(KafkaNetSocket): + SCHEMES: tuple[str, ...] + def __init__(self, proxy_url: str) -> None: ... # pyright: ignore[reportInconsistentConstructor] + def dns_lookup(self, host, port, proxy: bool = False): ... + def socket(self, family=..., sock_type=..., proto=...) -> _socket.socket: ... + def connect_ex(self, sock, addr) -> int: ... diff --git a/stubs/kafka-python/kafka/net/transport.pyi b/stubs/kafka-python/kafka/net/transport.pyi new file mode 100644 index 000000000000..acfb577e6fa4 --- /dev/null +++ b/stubs/kafka-python/kafka/net/transport.pyi @@ -0,0 +1,43 @@ +import socket +from _typeshed import Incomplete + +class KafkaTCPTransport: + host: Incomplete | None + last_write: float + last_read: float + def __init__(self, net, sock, host=None) -> None: ... + @property + def last_activity(self) -> float: ... + def is_closing(self) -> bool: ... + def close(self) -> None: ... + def set_protocol(self, protocol) -> None: ... + def get_protocol(self): ... + def is_reading(self) -> bool: ... + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + def set_write_buffer_limits(self, high=None, low=None): ... + def get_write_buffer_size(self): ... + def get_write_buffer_limits(self): ... + def write(self, data) -> None: ... + def writelines(self, list_of_data) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self): ... + def abort(self, error=None) -> None: ... + def abortConnection(self) -> None: ... + def getHost(self) -> socket._RetAddress: ... + def getPeer(self) -> socket._RetAddress: ... + def getTcpKeepAlive(self) -> int: ... + def getTcpNoDelay(self) -> int: ... + def loseWriteConnection(self) -> None: ... + def setTcpKeepAlive(self, enabled) -> None: ... + def setTcpNoDelay(self, enabled) -> None: ... + def loseConnection(self) -> None: ... + def writeSequence(self, data) -> None: ... + async def handshake(self) -> None: ... + def host_port(self) -> str: ... + +class KafkaSSLTransport(KafkaTCPTransport): + DEFAULT_CONFIG: dict[str, Incomplete] + ssl_config: dict[str, Incomplete] + def __init__(self, net, sock, host=None, **configs) -> None: ... + async def handshake(self) -> None: ... diff --git a/stubs/kafka-python/kafka/net/wakeup_notifier.pyi b/stubs/kafka-python/kafka/net/wakeup_notifier.pyi new file mode 100644 index 000000000000..92177c18484f --- /dev/null +++ b/stubs/kafka-python/kafka/net/wakeup_notifier.pyi @@ -0,0 +1,4 @@ +class WakeupNotifier: + def __init__(self, net) -> None: ... + async def __call__(self, timeout_secs=None) -> None: ... + def notify(self) -> None: ... diff --git a/stubs/kafka-python/kafka/partitioner/__init__.pyi b/stubs/kafka-python/kafka/partitioner/__init__.pyi new file mode 100644 index 000000000000..841530ee0fa1 --- /dev/null +++ b/stubs/kafka-python/kafka/partitioner/__init__.pyi @@ -0,0 +1,5 @@ +from .abc import Partitioner as Partitioner +from .default import DefaultPartitioner as DefaultPartitioner, murmur2 as murmur2 +from .sticky import StickyPartitioner as StickyPartitioner + +__all__ = ["Partitioner", "DefaultPartitioner", "StickyPartitioner", "murmur2"] diff --git a/stubs/kafka-python/kafka/partitioner/abc.pyi b/stubs/kafka-python/kafka/partitioner/abc.pyi new file mode 100644 index 000000000000..28ff08312585 --- /dev/null +++ b/stubs/kafka-python/kafka/partitioner/abc.pyi @@ -0,0 +1,9 @@ +import abc + +from kafka.cluster import ClusterMetadata + +class Partitioner(abc.ABC): + @abc.abstractmethod + def partition( + self, topic: str, key, serialized_key: bytes, value, serialized_value: bytes, cluster: ClusterMetadata + ) -> int: ... diff --git a/stubs/kafka-python/kafka/partitioner/default.pyi b/stubs/kafka-python/kafka/partitioner/default.pyi new file mode 100644 index 000000000000..e7e1bac1cdb9 --- /dev/null +++ b/stubs/kafka-python/kafka/partitioner/default.pyi @@ -0,0 +1,6 @@ +from .abc import Partitioner + +class DefaultPartitioner(Partitioner): + def partition(self, topic, key, serialized_key, value, serialized_value, cluster) -> int: ... + +def murmur2(data: bytes) -> int: ... diff --git a/stubs/kafka-python/kafka/partitioner/sticky.pyi b/stubs/kafka-python/kafka/partitioner/sticky.pyi new file mode 100644 index 000000000000..3658eeb8b6f9 --- /dev/null +++ b/stubs/kafka-python/kafka/partitioner/sticky.pyi @@ -0,0 +1,6 @@ +from .default import DefaultPartitioner + +class StickyPartitioner(DefaultPartitioner): + def __init__(self) -> None: ... + def partition(self, topic, key, serialized_key, value, serialized_value, cluster): ... + def on_new_batch(self, topic, cluster, prev_partition) -> None: ... diff --git a/stubs/kafka-python/kafka/producer/__init__.pyi b/stubs/kafka-python/kafka/producer/__init__.pyi new file mode 100644 index 000000000000..35360a27f231 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.producer.kafka import KafkaProducer as KafkaProducer + +__all__ = ["KafkaProducer"] diff --git a/stubs/kafka-python/kafka/producer/future.pyi b/stubs/kafka-python/kafka/producer/future.pyi new file mode 100644 index 000000000000..70c40099b453 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/future.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +from kafka.future import Future +from kafka.structs import TopicPartition + +class FutureProduceResult(Future): + __slots__ = ("topic_partition", "_latch") + topic_partition: TopicPartition + def __init__(self, topic_partition: TopicPartition) -> None: ... + def success(self, value): ... + def failure(self, error): ... + def wait(self, timeout=None): ... + +class FutureRecordMetadata(Future): + __slots__ = ("_produce_future", "args") + args: Incomplete + def __init__( + self, + produce_future, + batch_index, + timestamp_ms, + checksum, + serialized_key_size, + serialized_value_size, + serialized_header_size, + ) -> None: ... + def rebind(self, new_produce_future, new_batch_index) -> None: ... + def get(self, timeout=None): ... + +class RecordMetadata(NamedTuple): + topic: str + partition: int + topic_partition: TopicPartition + offset: int + timestamp: int + checksum: int | None # Deprecated field + serialized_key_size: int + serialized_value_size: int + serialized_header_size: int diff --git a/stubs/kafka-python/kafka/producer/kafka.pyi b/stubs/kafka-python/kafka/producer/kafka.pyi new file mode 100644 index 000000000000..1084cd1f926e --- /dev/null +++ b/stubs/kafka-python/kafka/producer/kafka.pyi @@ -0,0 +1,109 @@ +import selectors +import ssl +from _typeshed import Incomplete +from collections.abc import Callable, Mapping, Sequence +from types import TracebackType +from typing import Literal, TypeAlias +from typing_extensions import Self + +from kafka.producer.future import FutureRecordMetadata +from kafka.producer.record_accumulator import AtomicInteger +from kafka.serializer.abstract import Serializer +from kafka.structs import ConsumerGroupMetadata, OffsetAndMetadata, TopicPartition + +_Partitioner: TypeAlias = Callable[[bytes | None, Sequence[int], Sequence[int]], int] +_ProducerSerializer: TypeAlias = Serializer | Callable[[object], bytes] + +PRODUCER_CLIENT_ID_SEQUENCE: AtomicInteger + +class KafkaProducer: + DEFAULT_CONFIG: dict[str, Incomplete] + DEPRECATED_CONFIGS: tuple[str, ...] + config: dict[str, Incomplete] + def __init__( + self, + *, + bootstrap_servers: str | Sequence[str] = "localhost", + client_id: str | None = None, + key_serializer: _ProducerSerializer | None = None, + value_serializer: _ProducerSerializer | None = None, + enable_idempotence: bool = True, + transactional_id: str | None = None, + transaction_timeout_ms: int = 60000, + delivery_timeout_ms: float = 120000, + acks: int | Literal["all"] = -1, + compression_type: Literal["gzip", "snappy", "lz4", "zstd"] | None = None, + retries: int | float = ..., + batch_size: int = 16384, + linger_ms: int = 0, + partitioner: _Partitioner = ..., + connections_max_idle_ms: int = 540000, + max_block_ms: int = 60000, + max_request_size: int = 1048576, + allow_auto_create_topics: bool = True, + metadata_max_age_ms: int = 300000, + client_dns_lookup: str = "use_all_dns_ips", + retry_backoff_ms: int = 100, + request_timeout_ms: int = 30000, + receive_message_max_bytes: int = 100_000_000, + receive_buffer_bytes: int | None = None, + send_buffer_bytes: int | None = None, + socket_options: Sequence[tuple[int, int, int]] = ..., + reconnect_backoff_ms: int = 50, + reconnect_backoff_max_ms: int = 30000, + max_in_flight_requests_per_connection: int = 5, + security_protocol: Literal["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"] = "PLAINTEXT", + ssl_context: ssl.SSLContext | None = None, + ssl_check_hostname: bool = True, + ssl_cafile: str | None = None, + ssl_certfile: str | None = None, + ssl_keyfile: str | None = None, + ssl_crlfile: str | None = None, + ssl_password: str | None = None, + ssl_ciphers: str | None = None, + api_version: tuple[int, ...] | None = None, + bootstrap_timeout_ms: int = 30000, + metric_reporters: Sequence[type[object]] = [], + metrics_enabled: bool = True, + metrics_num_samples: int = 2, + metrics_sample_window_ms: int = 30000, + selector: type[selectors.BaseSelector] = selectors.DefaultSelector, + sasl_mechanism: Literal["PLAIN", "GSSAPI", "OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-512"] | None = None, + sasl_plain_username: str | None = None, + sasl_plain_password: str | None = None, + sasl_kerberos_name: object | None = None, + sasl_kerberos_service_name: str = "kafka", + sasl_kerberos_domain_name: str | None = None, + sasl_oauth_token_provider: object | None = None, + proxy_url: str | None = None, + socks5_proxy: str | None = None, + kafka_client: Callable[..., object] = ..., + ) -> None: ... + def bootstrap_connected(self) -> bool: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self, timeout: float | None = None, null_logger: bool = False) -> None: ... + def partitions_for(self, topic: str) -> set[int]: ... + @classmethod + def max_usable_produce_magic(cls, api_version): ... + def init_transactions(self) -> None: ... + def begin_transaction(self) -> None: ... + def send_offsets_to_transaction( + self, offsets: Mapping[TopicPartition, OffsetAndMetadata], group_metadata: str | ConsumerGroupMetadata + ) -> None: ... + def commit_transaction(self) -> None: ... + def abort_transaction(self) -> None: ... + def send( + self, + topic: str, + value: object = None, + key: object = None, + headers: Sequence[tuple[str, bytes]] | None = None, + partition: int | None = None, + timestamp_ms: int | None = None, + ) -> FutureRecordMetadata: ... + def flush(self, timeout: float | None = None) -> None: ... + def metrics(self, raw: bool = False) -> dict[str, dict[str, object]] | dict[object, object] | None: ... diff --git a/stubs/kafka-python/kafka/producer/producer_batch.pyi b/stubs/kafka-python/kafka/producer/producer_batch.pyi new file mode 100644 index 000000000000..dc6d522e3028 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/producer_batch.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.producer.future import FutureProduceResult + +class FinalState(IntEnum): + ABORTED = 0 + FAILED = 1 + SUCCEEDED = 2 + +class ProducerBatch: + max_record_size: int + created: float + drained: Incomplete | None + attempts: int + last_attempt: float + last_append: float + records: Incomplete + topic_partition: Incomplete + produce_future: FutureProduceResult + def __init__(self, tp, records, now: float | None = None) -> None: ... + @property + def final_state(self): ... + @property + def record_count(self): ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + @property + def base_sequence(self): ... + @property + def has_sequence(self) -> bool: ... + def try_append(self, timestamp_ms, key, value, headers, now=None): ... + def abort(self, exception) -> None: ... + def complete(self, base_offset, log_append_time) -> bool: ... + def complete_exceptionally(self, top_level_exception, record_exceptions_fn) -> bool: ... + def done(self, base_offset=None, timestamp_ms=None, top_level_exception=None, record_exceptions_fn=None) -> bool: ... + def has_reached_delivery_timeout(self, delivery_timeout_ms, now=None) -> bool: ... + def in_retry(self) -> bool: ... + def retry(self, now=None) -> None: ... + @property + def is_done(self) -> bool: ... + def __lt__(self, other) -> bool: ... diff --git a/stubs/kafka-python/kafka/producer/record_accumulator.pyi b/stubs/kafka-python/kafka/producer/record_accumulator.pyi new file mode 100644 index 000000000000..23b060c00a16 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/record_accumulator.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete + +class AtomicInteger: + def __init__(self, val: int = 0) -> None: ... + def increment(self): ... + def decrement(self): ... + def get(self): ... + +class RecordAccumulator: + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + muted: set[Incomplete] + def __init__(self, **configs) -> None: ... + @property + def delivery_timeout_ms(self): ... + @property + def next_expiry_time_ms(self) -> float: ... + def append(self, tp, timestamp_ms, key, value, headers, now: float | None = None, abort_on_new_batch: bool = False): ... + def reset_next_batch_expiry_time(self) -> None: ... + def maybe_update_next_batch_expiry_time(self, batch) -> None: ... + def expired_batches(self, now=None) -> list[Incomplete]: ... + def split_and_reenqueue(self, batch, now: float | None = None) -> int: ... + def reenqueue(self, batch, now=None) -> None: ... + def ready(self, cluster, now: float | None = None): ... + def has_undrained(self) -> bool: ... + def drain_batches_for_one_node(self, cluster, node_id, max_size, now: float | None = None) -> list[Incomplete]: ... + def drain(self, cluster, nodes, max_size, now: float | None = None): ... + def deallocate(self, batch) -> None: ... + def flush_in_progress(self) -> bool: ... + def begin_flush(self) -> None: ... + def await_flush_completion(self, timeout=None) -> None: ... + @property + def has_incomplete(self) -> bool: ... + def abort_incomplete_batches(self) -> None: ... + def abort_batches(self, error) -> None: ... + def abort_undrained_batches(self, error) -> None: ... + def close(self) -> None: ... + +class IncompleteProducerBatches: + def __init__(self) -> None: ... + def add(self, batch) -> None: ... + def remove(self, batch) -> None: ... + def all(self) -> list[Incomplete]: ... + def __bool__(self) -> bool: ... + __nonzero__ = __bool__ diff --git a/stubs/kafka-python/kafka/producer/sender.pyi b/stubs/kafka-python/kafka/producer/sender.pyi new file mode 100644 index 000000000000..b50b36d34b16 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/sender.pyi @@ -0,0 +1,34 @@ +import threading +from _typeshed import Incomplete + +class Sender(threading.Thread): + DEFAULT_CONFIG: dict[str, Incomplete] + config: dict[str, Incomplete] + name: Incomplete + def __init__(self, client, metadata, accumulator, **configs) -> None: ... + def run(self) -> None: ... + def run_once(self) -> None: ... + def initiate_close(self) -> None: ... + def force_close(self) -> None: ... + def add_topic(self, topic) -> None: ... + def wakeup(self) -> None: ... + def bootstrap_connected(self): ... + +class SenderMetrics: + metrics: Incomplete + batch_size_sensor: Incomplete + compression_rate_sensor: Incomplete + queue_time_sensor: Incomplete + records_per_request_sensor: Incomplete + byte_rate_sensor: Incomplete + retry_sensor: Incomplete + error_sensor: Incomplete + max_record_size_sensor: Incomplete + def __init__(self, metrics, client, metadata) -> None: ... + def add_metric( + self, metric_name, measurable, group_name: str = "producer-metrics", description=None, tags=None, sensor_name=None + ) -> None: ... + def maybe_register_topic_metrics(self, topic) -> None: ... + def update_produce_request_metrics(self, batches_map) -> None: ... + def record_retries(self, topic, count) -> None: ... + def record_errors(self, topic, count) -> None: ... diff --git a/stubs/kafka-python/kafka/producer/transaction_manager.pyi b/stubs/kafka-python/kafka/producer/transaction_manager.pyi new file mode 100644 index 000000000000..5a478e3ad144 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/transaction_manager.pyi @@ -0,0 +1,210 @@ +import abc +from _typeshed import Incomplete +from enum import IntEnum +from typing import Final, Literal + +from kafka.protocol.producer import InitProducerIdRequest +from kafka.structs import ConsumerGroupMetadata + +NO_PRODUCER_ID: Final = -1 +NO_PRODUCER_EPOCH: Final = -1 +NO_SEQUENCE: Final = -1 + +class ProducerIdAndEpoch: + __slots__ = ("producer_id", "epoch") + producer_id: Incomplete + epoch: Incomplete + def __init__(self, producer_id, epoch) -> None: ... + @property + def is_valid(self): ... + def match(self, batch): ... + def __eq__(self, other): ... + +class TransactionState(IntEnum): + UNINITIALIZED = 0 + INITIALIZING = 1 + READY = 2 + IN_TRANSACTION = 3 + COMMITTING_TRANSACTION = 4 + ABORTING_TRANSACTION = 5 + ABORTABLE_ERROR = 6 + FATAL_ERROR = 7 + BUMPING_PRODUCER_EPOCH = 8 + @classmethod + def is_transition_valid(cls, source, target): ... + +class Priority(IntEnum): + FIND_COORDINATOR = 0 + INIT_PRODUCER_ID = 1 + ADD_PARTITIONS_OR_OFFSETS = 2 + END_TXN = 3 + +class TransactionManager: + NO_INFLIGHT_REQUEST_CORRELATION_ID: int + ADD_PARTITIONS_RETRY_BACKOFF_MS: int + transactional_id: Incomplete + transaction_timeout_ms: Incomplete + producer_id_and_epoch: Incomplete + retry_backoff_ms: Incomplete + def __init__( + self, + transactional_id=None, + transaction_timeout_ms: int = 0, + retry_backoff_ms: int = 100, + api_version=(0, 11), + metadata=None, + ) -> None: ... + def initialize_transactions(self): ... + def init_producer_id(self) -> None: ... + def begin_transaction(self) -> None: ... + def begin_commit(self): ... + def begin_abort(self): ... + def send_offsets_to_transaction(self, offsets, group_metadata: str | ConsumerGroupMetadata): ... + def maybe_add_partition_to_transaction(self, topic_partition) -> None: ... + def is_send_to_partition_allowed(self, tp): ... + def has_producer_id(self, producer_id=None) -> bool: ... + def is_transactional(self) -> bool: ... + def has_partitions_to_add(self) -> bool: ... + def is_completing(self) -> bool: ... + @property + def last_error(self): ... + def has_error(self) -> bool: ... + def is_bumping_epoch(self) -> bool: ... + ERROR_CLASS_RETRIABLE: Final = "RETRIABLE" + ERROR_CLASS_ABORTABLE: Final = "ABORTABLE" + ERROR_CLASS_FATAL: Final = "FATAL" + ERROR_CLASS_NEEDS_EPOCH_BUMP: Final = "NEEDS_EPOCH_BUMP" + ERROR_CLASS_NEEDS_PRODUCER_ID_RESET: Final = "NEEDS_PRODUCER_ID_RESET" + def classify_batch_error( + self, error, batch, log_start_offset=-1 + ) -> Literal["FATAL", "RETRIABLE", "NEEDS_EPOCH_BUMP", "NEEDS_PRODUCER_ID_RESET", "ABORTABLE"]: ... + def is_aborting(self) -> bool: ... + def transition_to_abortable_error(self, exc) -> None: ... + def transition_to_fatal_error(self, exc) -> None: ... + def is_partition_added(self, partition) -> bool: ... + def is_partition_pending_add(self, partition) -> bool: ... + def has_producer_id_and_epoch(self, producer_id, producer_epoch) -> bool: ... + def set_producer_id_and_epoch(self, producer_id_and_epoch) -> None: ... + def reset_producer_id(self) -> None: ... + def bump_producer_id_and_epoch(self) -> None: ... + def sequence_number(self, tp): ... + def increment_sequence_number(self, tp, increment) -> None: ... + def set_sequence_number(self, tp, sequence) -> None: ... + def reset_sequence_for_partition(self, tp) -> None: ... + def update_last_acked_offset(self, tp, base_offset, record_count) -> None: ... + def last_acked_offset(self, tp): ... + def next_request_handler(self, has_incomplete_batches): ... + def retry(self, request) -> None: ... + def authentication_failed(self, exc) -> None: ... + def coordinator(self, coord_type): ... + def lookup_coordinator_for_request(self, request) -> None: ... + def next_in_flight_request_correlation_id(self): ... + def clear_in_flight_transactional_request_correlation_id(self) -> None: ... + def has_in_flight_transactional_request(self): ... + def has_fatal_error(self): ... + def has_abortable_error(self): ... + +class TransactionalRequestResult: + def __init__(self) -> None: ... + def done(self, error=None) -> None: ... + def wait(self, timeout_ms=None): ... + @property + def is_done(self): ... + @property + def succeeded(self): ... + @property + def failed(self): ... + @property + def exception(self): ... + +class TxnRequestHandler(metaclass=abc.ABCMeta): + transaction_manager: Incomplete + retry_backoff_ms: Incomplete + request: Incomplete + def __init__(self, transaction_manager, result=None) -> None: ... + @property + def transactional_id(self): ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + def fatal_error(self, exc) -> None: ... + def abortable_error(self, exc) -> None: ... + def fail(self, exc) -> None: ... + def reenqueue(self) -> None: ... + def on_complete(self, correlation_id, response_or_exc) -> None: ... + def needs_coordinator(self): ... + @property + def result(self): ... + @property + def coordinator_type(self): ... + @property + def coordinator_key(self): ... + def set_retry(self) -> None: ... + @property + def is_retry(self): ... + @abc.abstractmethod + def handle_response(self, response): ... + @property + @abc.abstractmethod + def priority(self): ... + +class InitProducerIdHandler(TxnRequestHandler): + request: InitProducerIdRequest + def __init__(self, transaction_manager, transaction_timeout_ms, is_epoch_bump: bool = False) -> None: ... + @property + def priority(self): ... + @property + def coordinator_type(self): ... + def handle_response(self, response) -> None: ... + +class AddPartitionsToTxnHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, topic_partitions) -> None: ... + @property + def priority(self): ... + retry_backoff_ms: Incomplete + def handle_response(self, response) -> None: ... + def maybe_override_retry_backoff_ms(self) -> None: ... + +class FindCoordinatorHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, coord_type, coord_key) -> None: ... + @property + def priority(self): ... + @property + def coordinator_type(self) -> None: ... + @property + def coordinator_key(self) -> None: ... + def handle_response(self, response) -> None: ... + +class EndTxnHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, committed) -> None: ... + @property + def priority(self): ... + def handle_response(self, response) -> None: ... + +class AddOffsetsToTxnHandler(TxnRequestHandler): + group_metadata: Incomplete + consumer_group_id: Incomplete + offsets: Incomplete + request: Incomplete + def __init__(self, transaction_manager, group_metadata, offsets) -> None: ... + @property + def priority(self): ... + def handle_response(self, response) -> None: ... + +class TxnOffsetCommitHandler(TxnRequestHandler): + group_metadata: Incomplete + consumer_group_id: Incomplete + offsets: Incomplete + request: Incomplete + def __init__(self, transaction_manager, group_metadata, offsets, result) -> None: ... + @property + def priority(self): ... + @property + def coordinator_type(self): ... + @property + def coordinator_key(self): ... + def handle_response(self, response) -> None: ... diff --git a/stdlib/distutils/command/bdist_wininst.pyi b/stubs/kafka-python/kafka/protocol/__init__.pyi similarity index 100% rename from stdlib/distutils/command/bdist_wininst.pyi rename to stubs/kafka-python/kafka/protocol/__init__.pyi diff --git a/stubs/kafka-python/kafka/protocol/admin/__init__.pyi b/stubs/kafka-python/kafka/protocol/admin/__init__.pyi new file mode 100644 index 000000000000..9e292518cbbc --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/__init__.pyi @@ -0,0 +1,76 @@ +from .acl import * +from .client_quotas import * +from .cluster import * +from .configs import * +from .groups import * +from .topics import * +from .transactions import * +from .users import * + +__all__ = [ + "CreateAclsRequest", + "CreateAclsResponse", + "DeleteAclsRequest", + "DeleteAclsResponse", + "DescribeAclsRequest", + "DescribeAclsResponse", + "ACLResourceType", + "ACLOperation", + "ACLPermissionType", + "ACLResourcePatternType", + "AlterClientQuotasRequest", + "AlterClientQuotasResponse", + "DescribeClientQuotasRequest", + "DescribeClientQuotasResponse", + "DescribeClusterRequest", + "DescribeClusterResponse", + "DescribeLogDirsRequest", + "DescribeLogDirsResponse", + "AlterReplicaLogDirsRequest", + "AlterReplicaLogDirsResponse", + "DescribeQuorumRequest", + "DescribeQuorumResponse", + "UpdateFeaturesRequest", + "UpdateFeaturesResponse", + "AlterConfigsRequest", + "AlterConfigsResponse", + "DescribeConfigsRequest", + "DescribeConfigsResponse", + "IncrementalAlterConfigsRequest", + "IncrementalAlterConfigsResponse", + "ListConfigResourcesRequest", + "ListConfigResourcesResponse", + "DescribeGroupsRequest", + "DescribeGroupsResponse", + "ListGroupsRequest", + "ListGroupsResponse", + "DeleteGroupsRequest", + "DeleteGroupsResponse", + "CreateTopicsRequest", + "CreateTopicsResponse", + "DeleteTopicsRequest", + "DeleteTopicsResponse", + "CreatePartitionsRequest", + "CreatePartitionsResponse", + "AlterPartitionReassignmentsRequest", + "AlterPartitionReassignmentsResponse", + "ListPartitionReassignmentsRequest", + "ListPartitionReassignmentsResponse", + "DescribeTopicPartitionsRequest", + "DescribeTopicPartitionsResponse", + "DeleteRecordsRequest", + "DeleteRecordsResponse", + "ElectLeadersRequest", + "ElectLeadersResponse", + "ElectionType", + "ListTransactionsRequest", + "ListTransactionsResponse", + "DescribeTransactionsRequest", + "DescribeTransactionsResponse", + "DescribeProducersRequest", + "DescribeProducersResponse", + "AlterUserScramCredentialsRequest", + "AlterUserScramCredentialsResponse", + "DescribeUserScramCredentialsRequest", + "DescribeUserScramCredentialsResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/acl.pyi b/stubs/kafka-python/kafka/protocol/admin/acl.pyi new file mode 100644 index 000000000000..a29c2ea590e9 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/acl.pyi @@ -0,0 +1,362 @@ +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class CreateAclsRequest(ApiMessage): + class AclCreation(DataContainer): + resource_type: int + resource_name: str + resource_pattern_type: int + principal: str + host: str + operation: int + permission_type: int + def __init__( + self, + *args, + resource_type: int = ..., + resource_name: str = ..., + resource_pattern_type: int = ..., + principal: str = ..., + host: str = ..., + operation: int = ..., + permission_type: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + creations: list[AclCreation] + def __init__(self, *args, creations: list[AclCreation] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class CreateAclsResponse(ApiMessage): + class AclCreationResult(DataContainer): + error_code: int + error_message: str | None + def __init__( + self, *args, error_code: int = ..., error_message: str | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + results: list[AclCreationResult] + def __init__( + self, *args, throttle_time_ms: int = ..., results: list[AclCreationResult] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteAclsRequest(ApiMessage): + class DeleteAclsFilter(DataContainer): + resource_type_filter: int + resource_name_filter: str | None + pattern_type_filter: int + principal_filter: str | None + host_filter: str | None + operation: int + permission_type: int + def __init__( + self, + *args, + resource_type_filter: int = ..., + resource_name_filter: str | None = ..., + pattern_type_filter: int = ..., + principal_filter: str | None = ..., + host_filter: str | None = ..., + operation: int = ..., + permission_type: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + filters: list[DeleteAclsFilter] + def __init__(self, *args, filters: list[DeleteAclsFilter] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteAclsResponse(ApiMessage): + class DeleteAclsFilterResult(DataContainer): + class DeleteAclsMatchingAcl(DataContainer): + error_code: int + error_message: str | None + resource_type: int + resource_name: str + pattern_type: int + principal: str + host: str + operation: int + permission_type: int + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + resource_type: int = ..., + resource_name: str = ..., + pattern_type: int = ..., + principal: str = ..., + host: str = ..., + operation: int = ..., + permission_type: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + error_message: str | None + matching_acls: list[DeleteAclsMatchingAcl] + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + matching_acls: list[DeleteAclsMatchingAcl] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + filter_results: list[DeleteAclsFilterResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + filter_results: list[DeleteAclsFilterResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeAclsRequest(ApiMessage): + resource_type_filter: int + resource_name_filter: str | None + pattern_type_filter: int + principal_filter: str | None + host_filter: str | None + operation: int + permission_type: int + def __init__( + self, + *args, + resource_type_filter: int = ..., + resource_name_filter: str | None = ..., + pattern_type_filter: int = ..., + principal_filter: str | None = ..., + host_filter: str | None = ..., + operation: int = ..., + permission_type: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeAclsResponse(ApiMessage): + class DescribeAclsResource(DataContainer): + class AclDescription(DataContainer): + principal: str + host: str + operation: int + permission_type: int + def __init__( + self, + *args, + principal: str = ..., + host: str = ..., + operation: int = ..., + permission_type: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + resource_type: int + resource_name: str + pattern_type: int + acls: list[AclDescription] + def __init__( + self, + *args, + resource_type: int = ..., + resource_name: str = ..., + pattern_type: int = ..., + acls: list[AclDescription] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + resources: list[DescribeAclsResource] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + resources: list[DescribeAclsResource] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ACLResourceType(IntEnum): + UNKNOWN = 0 + ANY = 1 + TOPIC = 2 + GROUP = 3 + CLUSTER = 4 + TRANSACTIONAL_ID = 5 + DELEGATION_TOKEN = 6 + +class ACLOperation(IntEnum): + UNKNOWN = 0 + ANY = 1 + ALL = 2 + READ = 3 + WRITE = 4 + CREATE = 5 + DELETE = 6 + ALTER = 7 + DESCRIBE = 8 + CLUSTER_ACTION = 9 + DESCRIBE_CONFIGS = 10 + ALTER_CONFIGS = 11 + IDEMPOTENT_WRITE = 12 + CREATE_TOKENS = 13 + DESCRIBE_TOKENS = 14 + +class ACLPermissionType(IntEnum): + UNKNOWN = 0 + ANY = 1 + DENY = 2 + ALLOW = 3 + +class ACLResourcePatternType(IntEnum): + UNKNOWN = 0 + ANY = 1 + MATCH = 2 + LITERAL = 3 + PREFIXED = 4 + +__all__ = [ + "CreateAclsRequest", + "CreateAclsResponse", + "DeleteAclsRequest", + "DeleteAclsResponse", + "DescribeAclsRequest", + "DescribeAclsResponse", + "ACLResourceType", + "ACLOperation", + "ACLPermissionType", + "ACLResourcePatternType", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/client_quotas.pyi b/stubs/kafka-python/kafka/protocol/admin/client_quotas.pyi new file mode 100644 index 000000000000..1580153547ee --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/client_quotas.pyi @@ -0,0 +1,210 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class AlterClientQuotasRequest(ApiMessage): + class EntryData(DataContainer): + class EntityData(DataContainer): + entity_type: str + entity_name: str | None + def __init__( + self, *args, entity_type: str = ..., entity_name: str | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class OpData(DataContainer): + key: str + value: float + remove: bool + def __init__( + self, *args, key: str = ..., value: float = ..., remove: bool = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + entity: list[EntityData] + ops: list[OpData] + def __init__( + self, *args, entity: list[EntityData] = ..., ops: list[OpData] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + entries: list[EntryData] + validate_only: bool + def __init__( + self, *args, entries: list[EntryData] = ..., validate_only: bool = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterClientQuotasResponse(ApiMessage): + class EntryData(DataContainer): + class EntityData(DataContainer): + entity_type: str + entity_name: str | None + def __init__( + self, *args, entity_type: str = ..., entity_name: str | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + error_message: str | None + entity: list[EntityData] + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + entity: list[EntityData] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + entries: list[EntryData] + def __init__( + self, *args, throttle_time_ms: int = ..., entries: list[EntryData] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeClientQuotasRequest(ApiMessage): + class ComponentData(DataContainer): + entity_type: str + match_type: int + match: str | None + def __init__( + self, + *args, + entity_type: str = ..., + match_type: int = ..., + match: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + components: list[ComponentData] + strict: bool + def __init__( + self, *args, components: list[ComponentData] = ..., strict: bool = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeClientQuotasResponse(ApiMessage): + class EntryData(DataContainer): + class EntityData(DataContainer): + entity_type: str + entity_name: str | None + def __init__( + self, *args, entity_type: str = ..., entity_name: str | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class ValueData(DataContainer): + key: str + value: float + def __init__(self, *args, key: str = ..., value: float = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + entity: list[EntityData] + values: list[ValueData] + def __init__( + self, *args, entity: list[EntityData] = ..., values: list[ValueData] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + entries: list[EntryData] | None + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + entries: list[EntryData] | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = ["AlterClientQuotasRequest", "AlterClientQuotasResponse", "DescribeClientQuotasRequest", "DescribeClientQuotasResponse"] diff --git a/stubs/kafka-python/kafka/protocol/admin/cluster.pyi b/stubs/kafka-python/kafka/protocol/admin/cluster.pyi new file mode 100644 index 000000000000..af25aae69210 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/cluster.pyi @@ -0,0 +1,569 @@ +import uuid +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class DescribeClusterRequest(ApiMessage): + include_cluster_authorized_operations: bool + endpoint_type: int + include_fenced_brokers: bool + def __init__( + self, + *args, + include_cluster_authorized_operations: bool = ..., + endpoint_type: int = ..., + include_fenced_brokers: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeClusterResponse(ApiMessage): + class DescribeClusterBroker(DataContainer): + broker_id: int + host: str + port: int + rack: str | None + is_fenced: bool + def __init__( + self, + *args, + broker_id: int = ..., + host: str = ..., + port: int = ..., + rack: str | None = ..., + is_fenced: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + endpoint_type: int + cluster_id: str + controller_id: int + brokers: list[DescribeClusterBroker] + authorized_operations: set[int] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + endpoint_type: int = ..., + cluster_id: str = ..., + controller_id: int = ..., + brokers: list[DescribeClusterBroker] = ..., + authorized_operations: set[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def json_patch(cls, json): ... + +class DescribeLogDirsRequest(ApiMessage): + class DescribableLogDirTopic(DataContainer): + topic: str + partitions: list[int] + def __init__( + self, *args, topic: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[DescribableLogDirTopic] | None + def __init__( + self, *args, topics: list[DescribableLogDirTopic] | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeLogDirsResponse(ApiMessage): + class DescribeLogDirsResult(DataContainer): + class DescribeLogDirsTopic(DataContainer): + class DescribeLogDirsPartition(DataContainer): + partition_index: int + partition_size: int + offset_lag: int + is_future_key: bool + def __init__( + self, + *args, + partition_index: int = ..., + partition_size: int = ..., + offset_lag: int = ..., + is_future_key: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[DescribeLogDirsPartition] + def __init__( + self, + *args, + name: str = ..., + partitions: list[DescribeLogDirsPartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + log_dir: str + topics: list[DescribeLogDirsTopic] + total_bytes: int + usable_bytes: int + is_cordoned: bool + def __init__( + self, + *args, + error_code: int = ..., + log_dir: str = ..., + topics: list[DescribeLogDirsTopic] = ..., + total_bytes: int = ..., + usable_bytes: int = ..., + is_cordoned: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + results: list[DescribeLogDirsResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + results: list[DescribeLogDirsResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterReplicaLogDirsRequest(ApiMessage): + class AlterReplicaLogDir(DataContainer): + class AlterReplicaLogDirTopic(DataContainer): + name: str + partitions: list[int] + def __init__( + self, *args, name: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + path: str + topics: list[AlterReplicaLogDirTopic] + def __init__( + self, *args, path: str = ..., topics: list[AlterReplicaLogDirTopic] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + dirs: list[AlterReplicaLogDir] + def __init__(self, *args, dirs: list[AlterReplicaLogDir] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterReplicaLogDirsResponse(ApiMessage): + class AlterReplicaLogDirTopicResult(DataContainer): + class AlterReplicaLogDirPartitionResult(DataContainer): + partition_index: int + error_code: int + def __init__( + self, *args, partition_index: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic_name: str + partitions: list[AlterReplicaLogDirPartitionResult] + def __init__( + self, + *args, + topic_name: str = ..., + partitions: list[AlterReplicaLogDirPartitionResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + results: list[AlterReplicaLogDirTopicResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + results: list[AlterReplicaLogDirTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeQuorumRequest(ApiMessage): + class TopicData(DataContainer): + class PartitionData(DataContainer): + partition_index: int + def __init__(self, *args, partition_index: int = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic_name: str + partitions: list[PartitionData] + def __init__( + self, *args, topic_name: str = ..., partitions: list[PartitionData] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[TopicData] + def __init__(self, *args, topics: list[TopicData] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeQuorumResponse(ApiMessage): + class TopicData(DataContainer): + class PartitionData(DataContainer): + class ReplicaState(DataContainer): + replica_id: int + replica_directory_id: uuid.UUID + log_end_offset: int + last_fetch_timestamp: int + last_caught_up_timestamp: int + def __init__( + self, + *args, + replica_id: int = ..., + replica_directory_id: uuid.UUID = ..., + log_end_offset: int = ..., + last_fetch_timestamp: int = ..., + last_caught_up_timestamp: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + partition_index: int + error_code: int + error_message: str | None + leader_id: int + leader_epoch: int + high_watermark: int + current_voters: list[ReplicaState] + observers: list[ReplicaState] + def __init__( + self, + *args, + partition_index: int = ..., + error_code: int = ..., + error_message: str | None = ..., + leader_id: int = ..., + leader_epoch: int = ..., + high_watermark: int = ..., + current_voters: list[ReplicaState] = ..., + observers: list[ReplicaState] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic_name: str + partitions: list[PartitionData] + def __init__( + self, *args, topic_name: str = ..., partitions: list[PartitionData] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class Node(DataContainer): + class Listener(DataContainer): + name: str + host: str + port: int + def __init__( + self, *args, name: str = ..., host: str = ..., port: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + node_id: int + listeners: list[Listener] + def __init__( + self, *args, node_id: int = ..., listeners: list[Listener] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + error_message: str | None + topics: list[TopicData] + nodes: list[Node] + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + topics: list[TopicData] = ..., + nodes: list[Node] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class UpdateFeaturesRequest(ApiMessage): + class FeatureUpdateKey(DataContainer): + feature: str + max_version_level: int + allow_downgrade: bool + upgrade_type: int + def __init__( + self, + *args, + feature: str = ..., + max_version_level: int = ..., + allow_downgrade: bool = ..., + upgrade_type: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + timeout_ms: int + feature_updates: list[FeatureUpdateKey] + validate_only: bool + def __init__( + self, + *args, + timeout_ms: int = ..., + feature_updates: list[FeatureUpdateKey] = ..., + validate_only: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class UpdateFeaturesResponse(ApiMessage): + class UpdatableFeatureResult(DataContainer): + feature: str + error_code: int + error_message: str | None + def __init__( + self, + *args, + feature: str = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + results: list[UpdatableFeatureResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + results: list[UpdatableFeatureResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "DescribeClusterRequest", + "DescribeClusterResponse", + "DescribeLogDirsRequest", + "DescribeLogDirsResponse", + "AlterReplicaLogDirsRequest", + "AlterReplicaLogDirsResponse", + "DescribeQuorumRequest", + "DescribeQuorumResponse", + "UpdateFeaturesRequest", + "UpdateFeaturesResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/configs.pyi b/stubs/kafka-python/kafka/protocol/admin/configs.pyi new file mode 100644 index 000000000000..fe32bcb42d39 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/configs.pyi @@ -0,0 +1,405 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class AlterConfigsRequest(ApiMessage): + class AlterConfigsResource(DataContainer): + class AlterableConfig(DataContainer): + name: str + value: str | None + def __init__(self, *args, name: str = ..., value: str | None = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + resource_type: int + resource_name: str + configs: list[AlterableConfig] + def __init__( + self, + *args, + resource_type: int = ..., + resource_name: str = ..., + configs: list[AlterableConfig] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + resources: list[AlterConfigsResource] + validate_only: bool + def __init__( + self, *args, resources: list[AlterConfigsResource] = ..., validate_only: bool = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterConfigsResponse(ApiMessage): + class AlterConfigsResourceResponse(DataContainer): + error_code: int + error_message: str | None + resource_type: int + resource_name: str + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + resource_type: int = ..., + resource_name: str = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + responses: list[AlterConfigsResourceResponse] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + responses: list[AlterConfigsResourceResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeConfigsRequest(ApiMessage): + class DescribeConfigsResource(DataContainer): + resource_type: int + resource_name: str + configuration_keys: list[str] | None + def __init__( + self, + *args, + resource_type: int = ..., + resource_name: str = ..., + configuration_keys: list[str] | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + resources: list[DescribeConfigsResource] + include_synonyms: bool + include_documentation: bool + def __init__( + self, + *args, + resources: list[DescribeConfigsResource] = ..., + include_synonyms: bool = ..., + include_documentation: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeConfigsResponse(ApiMessage): + class DescribeConfigsResult(DataContainer): + class DescribeConfigsResourceResult(DataContainer): + class DescribeConfigsSynonym(DataContainer): + name: str + value: str | None + source: int + def __init__( + self, *args, name: str = ..., value: str | None = ..., source: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + value: str | None + read_only: bool + config_source: int + is_default: bool + is_sensitive: bool + synonyms: list[DescribeConfigsSynonym] + config_type: int + documentation: str | None + def __init__( + self, + *args, + name: str = ..., + value: str | None = ..., + read_only: bool = ..., + config_source: int = ..., + is_default: bool = ..., + is_sensitive: bool = ..., + synonyms: list[DescribeConfigsSynonym] = ..., + config_type: int = ..., + documentation: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + error_message: str | None + resource_type: int + resource_name: str + configs: list[DescribeConfigsResourceResult] + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + resource_type: int = ..., + resource_name: str = ..., + configs: list[DescribeConfigsResourceResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + results: list[DescribeConfigsResult] + def __init__( + self, *args, throttle_time_ms: int = ..., results: list[DescribeConfigsResult] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class IncrementalAlterConfigsRequest(ApiMessage): + class AlterConfigsResource(DataContainer): + class AlterableConfig(DataContainer): + name: str + config_operation: int + value: str | None + def __init__( + self, + *args, + name: str = ..., + config_operation: int = ..., + value: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + resource_type: int + resource_name: str + configs: list[AlterableConfig] + def __init__( + self, + *args, + resource_type: int = ..., + resource_name: str = ..., + configs: list[AlterableConfig] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + resources: list[AlterConfigsResource] + validate_only: bool + def __init__( + self, *args, resources: list[AlterConfigsResource] = ..., validate_only: bool = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class IncrementalAlterConfigsResponse(ApiMessage): + class AlterConfigsResourceResponse(DataContainer): + error_code: int + error_message: str | None + resource_type: int + resource_name: str + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + resource_type: int = ..., + resource_name: str = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + responses: list[AlterConfigsResourceResponse] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + responses: list[AlterConfigsResourceResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ListConfigResourcesRequest(ApiMessage): + resource_types: list[int] + def __init__(self, *args, resource_types: list[int] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ListConfigResourcesResponse(ApiMessage): + class ConfigResource(DataContainer): + resource_name: str + resource_type: int + def __init__( + self, *args, resource_name: str = ..., resource_type: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + config_resources: list[ConfigResource] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + config_resources: list[ConfigResource] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "AlterConfigsRequest", + "AlterConfigsResponse", + "DescribeConfigsRequest", + "DescribeConfigsResponse", + "IncrementalAlterConfigsRequest", + "IncrementalAlterConfigsResponse", + "ListConfigResourcesRequest", + "ListConfigResourcesResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/groups.pyi b/stubs/kafka-python/kafka/protocol/admin/groups.pyi new file mode 100644 index 000000000000..7445f01664b3 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/groups.pyi @@ -0,0 +1,235 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_data import ApiData +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class DescribeGroupsRequest(ApiMessage): + groups: list[str] + include_authorized_operations: bool + def __init__( + self, *args, groups: list[str] = ..., include_authorized_operations: bool = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeGroupsResponse(ApiMessage): + class DescribedGroup(DataContainer): + class DescribedGroupMember(DataContainer): + member_id: str + group_instance_id: str | None + client_id: str + client_host: str + member_metadata: bytes | ApiData + member_assignment: bytes | ApiData + def __init__( + self, + *args, + member_id: str = ..., + group_instance_id: str | None = ..., + client_id: str = ..., + client_host: str = ..., + member_metadata: bytes | ApiData = ..., + member_assignment: bytes | ApiData = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + error_message: str | None + group_id: str + group_state: str + protocol_type: str + protocol_data: str + members: list[DescribedGroupMember] + authorized_operations: set[int] + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + group_id: str = ..., + group_state: str = ..., + protocol_type: str = ..., + protocol_data: str = ..., + members: list[DescribedGroupMember] = ..., + authorized_operations: set[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + groups: list[DescribedGroup] + def __init__( + self, *args, throttle_time_ms: int = ..., groups: list[DescribedGroup] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def json_patch(cls, json): ... + +class ListGroupsRequest(ApiMessage): + states_filter: list[str] + types_filter: list[str] + def __init__( + self, *args, states_filter: list[str] = ..., types_filter: list[str] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ListGroupsResponse(ApiMessage): + class ListedGroup(DataContainer): + group_id: str + protocol_type: str + group_state: str + group_type: str + def __init__( + self, + *args, + group_id: str = ..., + protocol_type: str = ..., + group_state: str = ..., + group_type: str = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + groups: list[ListedGroup] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + groups: list[ListedGroup] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteGroupsRequest(ApiMessage): + groups_names: list[str] + def __init__(self, *args, groups_names: list[str] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteGroupsResponse(ApiMessage): + class DeletableGroupResult(DataContainer): + group_id: str + error_code: int + def __init__(self, *args, group_id: str = ..., error_code: int = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + results: list[DeletableGroupResult] + def __init__( + self, *args, throttle_time_ms: int = ..., results: list[DeletableGroupResult] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "DescribeGroupsRequest", + "DescribeGroupsResponse", + "ListGroupsRequest", + "ListGroupsResponse", + "DeleteGroupsRequest", + "DeleteGroupsResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/topics.pyi b/stubs/kafka-python/kafka/protocol/admin/topics.pyi new file mode 100644 index 000000000000..45e7d6b7ff79 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/topics.pyi @@ -0,0 +1,918 @@ +import uuid +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class CreateTopicsRequest(ApiMessage): + class CreatableTopic(DataContainer): + class CreatableReplicaAssignment(DataContainer): + partition_index: int + broker_ids: list[int] + def __init__( + self, *args, partition_index: int = ..., broker_ids: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class CreatableTopicConfig(DataContainer): + name: str + value: str | None + def __init__(self, *args, name: str = ..., value: str | None = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + num_partitions: int + replication_factor: int + assignments: list[CreatableReplicaAssignment] + configs: list[CreatableTopicConfig] + def __init__( + self, + *args, + name: str = ..., + num_partitions: int = ..., + replication_factor: int = ..., + assignments: list[CreatableReplicaAssignment] = ..., + configs: list[CreatableTopicConfig] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[CreatableTopic] + timeout_ms: int + validate_only: bool + def __init__( + self, + *args, + topics: list[CreatableTopic] = ..., + timeout_ms: int = ..., + validate_only: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class CreateTopicsResponse(ApiMessage): + class CreatableTopicResult(DataContainer): + class CreatableTopicConfigs(DataContainer): + name: str + value: str | None + read_only: bool + config_source: int + is_sensitive: bool + def __init__( + self, + *args, + name: str = ..., + value: str | None = ..., + read_only: bool = ..., + config_source: int = ..., + is_sensitive: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + topic_id: uuid.UUID + error_code: int + error_message: str | None + topic_config_error_code: int + num_partitions: int + replication_factor: int + configs: list[CreatableTopicConfigs] | None + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + error_code: int = ..., + error_message: str | None = ..., + topic_config_error_code: int = ..., + num_partitions: int = ..., + replication_factor: int = ..., + configs: list[CreatableTopicConfigs] | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[CreatableTopicResult] + def __init__( + self, *args, throttle_time_ms: int = ..., topics: list[CreatableTopicResult] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteTopicsRequest(ApiMessage): + class DeleteTopicState(DataContainer): + name: str | None + topic_id: uuid.UUID + def __init__( + self, *args, name: str | None = ..., topic_id: uuid.UUID = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[DeleteTopicState] + topic_names: list[str] + timeout_ms: int + def __init__( + self, + *args, + topics: list[DeleteTopicState] = ..., + topic_names: list[str] = ..., + timeout_ms: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + def encode(self, version=None, header=False, framed=False): ... + +class DeleteTopicsResponse(ApiMessage): + class DeletableTopicResult(DataContainer): + name: str | None + topic_id: uuid.UUID + error_code: int + error_message: str | None + def __init__( + self, + *args, + name: str | None = ..., + topic_id: uuid.UUID = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + responses: list[DeletableTopicResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + responses: list[DeletableTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class CreatePartitionsRequest(ApiMessage): + class CreatePartitionsTopic(DataContainer): + class CreatePartitionsAssignment(DataContainer): + broker_ids: list[int] + def __init__(self, *args, broker_ids: list[int] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + count: int + assignments: list[CreatePartitionsAssignment] | None + def __init__( + self, + *args, + name: str = ..., + count: int = ..., + assignments: list[CreatePartitionsAssignment] | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[CreatePartitionsTopic] + timeout_ms: int + validate_only: bool + def __init__( + self, + *args, + topics: list[CreatePartitionsTopic] = ..., + timeout_ms: int = ..., + validate_only: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def json_patch(cls, json): ... + +class CreatePartitionsResponse(ApiMessage): + class CreatePartitionsTopicResult(DataContainer): + name: str + error_code: int + error_message: str | None + def __init__( + self, + *args, + name: str = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + results: list[CreatePartitionsTopicResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + results: list[CreatePartitionsTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterPartitionReassignmentsRequest(ApiMessage): + class ReassignableTopic(DataContainer): + class ReassignablePartition(DataContainer): + partition_index: int + replicas: list[int] | None + def __init__( + self, *args, partition_index: int = ..., replicas: list[int] | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[ReassignablePartition] + def __init__( + self, *args, name: str = ..., partitions: list[ReassignablePartition] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + timeout_ms: int + allow_replication_factor_change: bool + topics: list[ReassignableTopic] + def __init__( + self, + *args, + timeout_ms: int = ..., + allow_replication_factor_change: bool = ..., + topics: list[ReassignableTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterPartitionReassignmentsResponse(ApiMessage): + class ReassignableTopicResponse(DataContainer): + class ReassignablePartitionResponse(DataContainer): + partition_index: int + error_code: int + error_message: str | None + def __init__( + self, + *args, + partition_index: int = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[ReassignablePartitionResponse] + def __init__( + self, + *args, + name: str = ..., + partitions: list[ReassignablePartitionResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + allow_replication_factor_change: bool + error_code: int + error_message: str | None + responses: list[ReassignableTopicResponse] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + allow_replication_factor_change: bool = ..., + error_code: int = ..., + error_message: str | None = ..., + responses: list[ReassignableTopicResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ListPartitionReassignmentsRequest(ApiMessage): + class ListPartitionReassignmentsTopics(DataContainer): + name: str + partition_indexes: list[int] + def __init__( + self, *args, name: str = ..., partition_indexes: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + timeout_ms: int + topics: list[ListPartitionReassignmentsTopics] | None + def __init__( + self, + *args, + timeout_ms: int = ..., + topics: list[ListPartitionReassignmentsTopics] | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ListPartitionReassignmentsResponse(ApiMessage): + class OngoingTopicReassignment(DataContainer): + class OngoingPartitionReassignment(DataContainer): + partition_index: int + replicas: list[int] + adding_replicas: list[int] + removing_replicas: list[int] + def __init__( + self, + *args, + partition_index: int = ..., + replicas: list[int] = ..., + adding_replicas: list[int] = ..., + removing_replicas: list[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[OngoingPartitionReassignment] + def __init__( + self, + *args, + name: str = ..., + partitions: list[OngoingPartitionReassignment] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + topics: list[OngoingTopicReassignment] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + topics: list[OngoingTopicReassignment] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeTopicPartitionsRequest(ApiMessage): + class TopicRequest(DataContainer): + name: str + def __init__(self, *args, name: str = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class Cursor(DataContainer): + topic_name: str + partition_index: int + def __init__( + self, *args, topic_name: str = ..., partition_index: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[TopicRequest] + response_partition_limit: int + cursor: Cursor | None + def __init__( + self, + *args, + topics: list[TopicRequest] = ..., + response_partition_limit: int = ..., + cursor: Cursor | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeTopicPartitionsResponse(ApiMessage): + class DescribeTopicPartitionsResponseTopic(DataContainer): + class DescribeTopicPartitionsResponsePartition(DataContainer): + error_code: int + partition_index: int + leader_id: int + leader_epoch: int + replica_nodes: list[int] + isr_nodes: list[int] + eligible_leader_replicas: list[int] | None + last_known_elr: list[int] | None + offline_replicas: list[int] + def __init__( + self, + *args, + error_code: int = ..., + partition_index: int = ..., + leader_id: int = ..., + leader_epoch: int = ..., + replica_nodes: list[int] = ..., + isr_nodes: list[int] = ..., + eligible_leader_replicas: list[int] | None = ..., + last_known_elr: list[int] | None = ..., + offline_replicas: list[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + name: str | None + topic_id: uuid.UUID + is_internal: bool + partitions: list[DescribeTopicPartitionsResponsePartition] + topic_authorized_operations: int + def __init__( + self, + *args, + error_code: int = ..., + name: str | None = ..., + topic_id: uuid.UUID = ..., + is_internal: bool = ..., + partitions: list[DescribeTopicPartitionsResponsePartition] = ..., + topic_authorized_operations: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class Cursor(DataContainer): + topic_name: str + partition_index: int + def __init__( + self, *args, topic_name: str = ..., partition_index: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[DescribeTopicPartitionsResponseTopic] + next_cursor: Cursor | None + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[DescribeTopicPartitionsResponseTopic] = ..., + next_cursor: Cursor | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteRecordsRequest(ApiMessage): + class DeleteRecordsTopic(DataContainer): + class DeleteRecordsPartition(DataContainer): + partition_index: int + offset: int + def __init__( + self, *args, partition_index: int = ..., offset: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[DeleteRecordsPartition] + def __init__( + self, *args, name: str = ..., partitions: list[DeleteRecordsPartition] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[DeleteRecordsTopic] + timeout_ms: int + def __init__( + self, *args, topics: list[DeleteRecordsTopic] = ..., timeout_ms: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DeleteRecordsResponse(ApiMessage): + class DeleteRecordsTopicResult(DataContainer): + class DeleteRecordsPartitionResult(DataContainer): + partition_index: int + low_watermark: int + error_code: int + def __init__( + self, + *args, + partition_index: int = ..., + low_watermark: int = ..., + error_code: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[DeleteRecordsPartitionResult] + def __init__( + self, + *args, + name: str = ..., + partitions: list[DeleteRecordsPartitionResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[DeleteRecordsTopicResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[DeleteRecordsTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ElectLeadersRequest(ApiMessage): + class TopicPartitions(DataContainer): + topic: str + partitions: list[int] + def __init__( + self, *args, topic: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + election_type: int + topic_partitions: list[TopicPartitions] | None + timeout_ms: int + def __init__( + self, + *args, + election_type: int = ..., + topic_partitions: list[TopicPartitions] | None = ..., + timeout_ms: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ElectLeadersResponse(ApiMessage): + class ReplicaElectionResult(DataContainer): + class PartitionResult(DataContainer): + partition_id: int + error_code: int + error_message: str | None + def __init__( + self, + *args, + partition_id: int = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic: str + partition_result: list[PartitionResult] + def __init__( + self, *args, topic: str = ..., partition_result: list[PartitionResult] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + replica_election_results: list[ReplicaElectionResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + replica_election_results: list[ReplicaElectionResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ElectionType(IntEnum): + PREFERRED = 0 + UNCLEAN = 1 + +__all__ = [ + "CreateTopicsRequest", + "CreateTopicsResponse", + "DeleteTopicsRequest", + "DeleteTopicsResponse", + "CreatePartitionsRequest", + "CreatePartitionsResponse", + "AlterPartitionReassignmentsRequest", + "AlterPartitionReassignmentsResponse", + "ListPartitionReassignmentsRequest", + "ListPartitionReassignmentsResponse", + "DescribeTopicPartitionsRequest", + "DescribeTopicPartitionsResponse", + "DeleteRecordsRequest", + "DeleteRecordsResponse", + "ElectLeadersRequest", + "ElectLeadersResponse", + "ElectionType", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/transactions.pyi b/stubs/kafka-python/kafka/protocol/admin/transactions.pyi new file mode 100644 index 000000000000..719151c07180 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/transactions.pyi @@ -0,0 +1,284 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class ListTransactionsRequest(ApiMessage): + state_filters: list[str] + producer_id_filters: list[int] + duration_filter: int + transactional_id_pattern: str | None + def __init__( + self, + *args, + state_filters: list[str] = ..., + producer_id_filters: list[int] = ..., + duration_filter: int = ..., + transactional_id_pattern: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ListTransactionsResponse(ApiMessage): + class TransactionState(DataContainer): + transactional_id: str + producer_id: int + transaction_state: str + def __init__( + self, + *args, + transactional_id: str = ..., + producer_id: int = ..., + transaction_state: str = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + unknown_state_filters: list[str] + transaction_states: list[TransactionState] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + unknown_state_filters: list[str] = ..., + transaction_states: list[TransactionState] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeTransactionsRequest(ApiMessage): + transactional_ids: list[str] + def __init__(self, *args, transactional_ids: list[str] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeTransactionsResponse(ApiMessage): + class TransactionState(DataContainer): + class TopicData(DataContainer): + topic: str + partitions: list[int] + def __init__( + self, *args, topic: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + transactional_id: str + transaction_state: str + transaction_timeout_ms: int + transaction_start_time_ms: int + producer_id: int + producer_epoch: int + topics: list[TopicData] + def __init__( + self, + *args, + error_code: int = ..., + transactional_id: str = ..., + transaction_state: str = ..., + transaction_timeout_ms: int = ..., + transaction_start_time_ms: int = ..., + producer_id: int = ..., + producer_epoch: int = ..., + topics: list[TopicData] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + transaction_states: list[TransactionState] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + transaction_states: list[TransactionState] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeProducersRequest(ApiMessage): + class TopicRequest(DataContainer): + name: str + partition_indexes: list[int] + def __init__( + self, *args, name: str = ..., partition_indexes: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[TopicRequest] + def __init__(self, *args, topics: list[TopicRequest] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeProducersResponse(ApiMessage): + class TopicResponse(DataContainer): + class PartitionResponse(DataContainer): + class ProducerState(DataContainer): + producer_id: int + producer_epoch: int + last_sequence: int + last_timestamp: int + coordinator_epoch: int + current_txn_start_offset: int + def __init__( + self, + *args, + producer_id: int = ..., + producer_epoch: int = ..., + last_sequence: int = ..., + last_timestamp: int = ..., + coordinator_epoch: int = ..., + current_txn_start_offset: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + partition_index: int + error_code: int + error_message: str | None + active_producers: list[ProducerState] + def __init__( + self, + *args, + partition_index: int = ..., + error_code: int = ..., + error_message: str | None = ..., + active_producers: list[ProducerState] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[PartitionResponse] + def __init__( + self, *args, name: str = ..., partitions: list[PartitionResponse] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[TopicResponse] + def __init__( + self, *args, throttle_time_ms: int = ..., topics: list[TopicResponse] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "ListTransactionsRequest", + "ListTransactionsResponse", + "DescribeTransactionsRequest", + "DescribeTransactionsResponse", + "DescribeProducersRequest", + "DescribeProducersResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/admin/users.pyi b/stubs/kafka-python/kafka/protocol/admin/users.pyi new file mode 100644 index 000000000000..63309692837e --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin/users.pyi @@ -0,0 +1,202 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_data import ApiData +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class AlterUserScramCredentialsRequest(ApiMessage): + class ScramCredentialDeletion(DataContainer): + name: str + mechanism: int + def __init__(self, *args, name: str = ..., mechanism: int = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class ScramCredentialUpsertion(DataContainer): + name: str + mechanism: int + iterations: int + salt: bytes | ApiData + salted_password: bytes | ApiData + def __init__( + self, + *args, + name: str = ..., + mechanism: int = ..., + iterations: int = ..., + salt: bytes | ApiData = ..., + salted_password: bytes | ApiData = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + deletions: list[ScramCredentialDeletion] + upsertions: list[ScramCredentialUpsertion] + def __init__( + self, + *args, + deletions: list[ScramCredentialDeletion] = ..., + upsertions: list[ScramCredentialUpsertion] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AlterUserScramCredentialsResponse(ApiMessage): + class AlterUserScramCredentialsResult(DataContainer): + user: str + error_code: int + error_message: str | None + def __init__( + self, + *args, + user: str = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + results: list[AlterUserScramCredentialsResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + results: list[AlterUserScramCredentialsResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeUserScramCredentialsRequest(ApiMessage): + class UserName(DataContainer): + name: str + def __init__(self, *args, name: str = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + users: list[UserName] | None + def __init__(self, *args, users: list[UserName] | None = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class DescribeUserScramCredentialsResponse(ApiMessage): + class DescribeUserScramCredentialsResult(DataContainer): + class CredentialInfo(DataContainer): + mechanism: int + iterations: int + def __init__( + self, *args, mechanism: int = ..., iterations: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + user: str + error_code: int + error_message: str | None + credential_infos: list[CredentialInfo] + def __init__( + self, + *args, + user: str = ..., + error_code: int = ..., + error_message: str | None = ..., + credential_infos: list[CredentialInfo] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + results: list[DescribeUserScramCredentialsResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + results: list[DescribeUserScramCredentialsResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "AlterUserScramCredentialsRequest", + "AlterUserScramCredentialsResponse", + "DescribeUserScramCredentialsRequest", + "DescribeUserScramCredentialsResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/api_data.pyi b/stubs/kafka-python/kafka/protocol/api_data.pyi new file mode 100644 index 000000000000..b3606d6573cf --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/api_data.pyi @@ -0,0 +1,33 @@ +from kafka.util import classproperty + +from .data_container import DataContainer, SlotsBuilder + +class JsonSchemaData(SlotsBuilder): + def __new__(metacls, name, bases, attrs, **kw): ... + def __init__(cls, name, bases, attrs, **kw) -> None: ... + +class ApiData(DataContainer, metaclass=JsonSchemaData): + def __init_subclass__(cls, **kw) -> None: ... + def __init__(self, *args, **kwargs) -> None: ... + @classproperty + def name(cls): ... + @classproperty + def type(cls): ... + @classproperty + def json(cls): ... + @classproperty + def valid_versions(cls): ... + @classproperty + def min_version(cls): ... + @classproperty + def max_version(cls): ... + @classmethod + def flexible_version_q(cls, version): ... + @classproperty + def header_class(cls): ... + def encode_header(self, flexible: bool = False): ... + @classmethod + def parse_header(cls, data): ... + def encode(self, version=None, header: bool = True, framed: bool = False) -> bytes: ... + @classmethod + def decode(cls, data, version=None, header: bool = True, framed: bool = False): ... # type: ignore[override] diff --git a/stubs/kafka-python/kafka/protocol/api_header.pyi b/stubs/kafka-python/kafka/protocol/api_header.pyi new file mode 100644 index 000000000000..43156854fdbc --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/api_header.pyi @@ -0,0 +1,25 @@ +from .api_data import JsonSchemaData +from .data_container import DataContainer + +class ApiHeader(DataContainer, metaclass=JsonSchemaData): + __slots__ = () + def __init_subclass__(cls, **kw) -> None: ... + def encode(self, flexible: bool = False): ... + def encode_into(self, out, flexible: bool = False) -> None: ... + @classmethod + def decode(cls, data, flexible: bool = False): ... # type: ignore[override] + +class ResponseClassRegistry: + @classmethod + def register_response_class(cls, response_class) -> None: ... + @classmethod + def get_response_class(cls, request_header): ... + +class RequestHeader(ApiHeader): + def get_response_class(self): ... + # TODO: Reflect client_id, correlation_id, request_api_key, request_api_version attributes + def __getattr__(self, name: str): ... # incomplete class + +class ResponseHeader(ApiHeader): + # TODO: Reflect correlation_id attribute + def __getattr__(self, name: str): ... # incomplete class diff --git a/stubs/kafka-python/kafka/protocol/api_key.pyi b/stubs/kafka-python/kafka/protocol/api_key.pyi new file mode 100644 index 000000000000..fa8d789777ce --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/api_key.pyi @@ -0,0 +1,96 @@ +from enum import IntEnum + +class ApiKey(IntEnum): + Produce = 0 + Fetch = 1 + ListOffsets = 2 + Metadata = 3 + LeaderAndIsr = 4 + StopReplica = 5 + UpdateMetadata = 6 + ControlledShutdown = 7 + OffsetCommit = 8 + OffsetFetch = 9 + FindCoordinator = 10 + JoinGroup = 11 + Heartbeat = 12 + LeaveGroup = 13 + SyncGroup = 14 + DescribeGroups = 15 + ListGroups = 16 + SaslHandshake = 17 + ApiVersions = 18 + CreateTopics = 19 + DeleteTopics = 20 + DeleteRecords = 21 + InitProducerId = 22 + OffsetForLeaderEpoch = 23 + AddPartitionsToTxn = 24 + AddOffsetsToTxn = 25 + EndTxn = 26 + WriteTxnMarkers = 27 + TxnOffsetCommit = 28 + DescribeAcls = 29 + CreateAcls = 30 + DeleteAcls = 31 + DescribeConfigs = 32 + AlterConfigs = 33 + AlterReplicaLogDirs = 34 + DescribeLogDirs = 35 + SaslAuthenticate = 36 + CreatePartitions = 37 + CreateDelegationToken = 38 + RenewDelegationToken = 39 + ExpireDelegationToken = 40 + DescribeDelegationToken = 41 + DeleteGroups = 42 + ElectLeaders = 43 + IncrementalAlterConfigs = 44 + AlterPartitionReassignments = 45 + ListPartitionReassignments = 46 + OffsetDelete = 47 + DescribeClientQuotas = 48 + AlterClientQuotas = 49 + DescribeUserScramCredentials = 50 + AlterUserScramCredentials = 51 + Vote = 52 + BeginQuorumEpoch = 53 + EndQuorumEpoch = 54 + DescribeQuorum = 55 + AlterPartition = 56 + UpdateFeatures = 57 + Envelope = 58 + FetchSnapshot = 59 + DescribeCluster = 60 + DescribeProducers = 61 + BrokerRegistration = 62 + BrokerHeartbeat = 63 + UnregisterBroker = 64 + DescribeTransactions = 65 + ListTransactions = 66 + AllocateProducerIds = 67 + ConsumerGroupHeartbeat = 68 + ConsumerGroupDescribe = 69 + ControllerRegistration = 70 + GetTelemetrySubscriptions = 71 + PushTelemetry = 72 + AssignReplicasToDirs = 73 + ListConfigResources = 74 + DescribeTopicPartitions = 75 + ShareGroupHeartbeat = 76 + ShareGroupDescribe = 77 + ShareFetch = 78 + ShareAcknowledge = 79 + AddRaftVoter = 80 + RemoveRaftVoter = 81 + UpdateRaftVoter = 82 + InitializeShareGroupState = 83 + ReadShareGroupState = 84 + WriteShareGroupState = 85 + DeleteShareGroupState = 86 + ReadShareGroupStateSummary = 87 + StreamsGroupHeartbeat = 88 + StreamsGroupDescribe = 89 + DescribeShareGroupOffsets = 90 + AlterShareGroupOffsets = 91 + DeleteShareGroupOffsets = 92 diff --git a/stubs/kafka-python/kafka/protocol/api_message.pyi b/stubs/kafka-python/kafka/protocol/api_message.pyi new file mode 100644 index 000000000000..d5752eaccb31 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/api_message.pyi @@ -0,0 +1,60 @@ +from typing_extensions import Self + +from kafka.util import classproperty + +from .api_data import JsonSchemaData +from .data_container import DataContainer + +class VersionSubscriptable(type): + def __init__(cls, name, bases, attrs, **kw) -> None: ... + def __getitem__(cls, version): ... + def __len__(cls): ... + +class ApiMessageData(VersionSubscriptable, JsonSchemaData): + def __init__(cls, name, bases, attrs, **kw) -> None: ... + +class ApiMessage(DataContainer, metaclass=ApiMessageData): + __slots__ = ("_header", "_min_version", "_max_version") + def __init_subclass__(cls, **kw) -> None: ... + def __new__(cls, *args, **kwargs) -> Self: ... + def __init__(self, *args, **kwargs) -> None: ... + @classproperty + def name(cls): ... + @classproperty + def type(cls): ... + @classproperty + def API_KEY(cls): ... + @classproperty + def json(cls): ... + @classproperty + def valid_versions(cls): ... + @classproperty + def min_version(cls): ... + @classproperty + def max_version(cls): ... + @classmethod + def flexible_version_q(cls, version) -> bool: ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self): ... + + @property + def API_VERSION(self): ... + @API_VERSION.setter + def API_VERSION(self, version): ... + + @property + def header(self): ... + @classproperty + def header_class(cls): ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + def encode_header(self, flexible: bool = False): ... + def encode_header_into(self, out, flexible: bool = False) -> None: ... + @classmethod + def parse_header(cls, data, version=None): ... + @classmethod + def encode_into__optimized_context(cls, version=None): ... + def encode(self, version=None, header: bool = False, framed: bool = False): ... + @classmethod + def decode(cls, data, version=None, header: bool = False, framed: bool = False): ... # type: ignore[override] + def __eq__(self, other) -> bool: ... diff --git a/stubs/kafka-python/kafka/protocol/broker_version_data.pyi b/stubs/kafka-python/kafka/protocol/broker_version_data.pyi new file mode 100644 index 000000000000..4bb36e298cec --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/broker_version_data.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +class BrokerVersionData: + __slots__ = ("broker_version", "api_versions") + broker_version: Incomplete + api_versions: Incomplete + def __init__(self, broker_version=None, api_versions=None) -> None: ... + def api_version(self, operation, min_version: int = 0, max_version: int = ...) -> int: ... + @property + def broker_version_str(self) -> str: ... + def __eq__(self, other) -> bool: ... + def __lt__(self, other) -> bool: ... + def __le__(self, other) -> bool: ... + def __gt__(self, other) -> bool: ... + def __ge__(self, other) -> bool: ... + +def infer_broker_version_from_api_versions(api_versions): ... + +VERSION_CHECKS: tuple[tuple[tuple[int, ...], Incomplete], ...] +BROKER_API_VERSIONS: dict[tuple[int, ...], dict[int, tuple[int, ...]]] diff --git a/stubs/kafka-python/kafka/protocol/consumer/__init__.pyi b/stubs/kafka-python/kafka/protocol/consumer/__init__.pyi new file mode 100644 index 000000000000..cb63f963b18c --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/consumer/__init__.pyi @@ -0,0 +1,37 @@ +from .fetch import * +from .group import * +from .metadata import * +from .offsets import * + +__all__ = [ + "FetchRequest", + "FetchResponse", + "DEFAULT_GENERATION_ID", + "UNKNOWN_MEMBER_ID", + "JoinGroupRequest", + "JoinGroupResponse", + "SyncGroupRequest", + "SyncGroupResponse", + "LeaveGroupRequest", + "LeaveGroupResponse", + "HeartbeatRequest", + "HeartbeatResponse", + "OffsetFetchRequest", + "OffsetFetchResponse", + "OffsetCommitRequest", + "OffsetCommitResponse", + "OffsetDeleteRequest", + "OffsetDeleteResponse", + "ConsumerProtocolSubscription", + "ConsumerProtocolAssignment", + "ConsumerProtocolType", + "UNKNOWN_OFFSET", + "OffsetResetStrategy", + "IsolationLevel", + "OffsetSpec", + "OffsetTimestamp", + "ListOffsetsRequest", + "ListOffsetsResponse", + "OffsetForLeaderEpochRequest", + "OffsetForLeaderEpochResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/consumer/fetch.pyi b/stubs/kafka-python/kafka/protocol/consumer/fetch.pyi new file mode 100644 index 000000000000..888cbcb47355 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/consumer/fetch.pyi @@ -0,0 +1,272 @@ +import uuid +from _typeshed import Incomplete + +from kafka.protocol.api_data import ApiData +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class FetchRequest(ApiMessage): + class ReplicaState(DataContainer): + replica_id: int + replica_epoch: int + def __init__( + self, *args, replica_id: int = ..., replica_epoch: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class FetchTopic(DataContainer): + class FetchPartition(DataContainer): + partition: int + current_leader_epoch: int + fetch_offset: int + last_fetched_epoch: int + log_start_offset: int + partition_max_bytes: int + replica_directory_id: uuid.UUID + high_watermark: int + def __init__( + self, + *args, + partition: int = ..., + current_leader_epoch: int = ..., + fetch_offset: int = ..., + last_fetched_epoch: int = ..., + log_start_offset: int = ..., + partition_max_bytes: int = ..., + replica_directory_id: uuid.UUID = ..., + high_watermark: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic: str + topic_id: uuid.UUID + partitions: list[FetchPartition] + def __init__( + self, + *args, + topic: str = ..., + topic_id: uuid.UUID = ..., + partitions: list[FetchPartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class ForgottenTopic(DataContainer): + topic: str + topic_id: uuid.UUID + partitions: list[int] + def __init__( + self, + *args, + topic: str = ..., + topic_id: uuid.UUID = ..., + partitions: list[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + cluster_id: str | None + replica_id: int + replica_state: ReplicaState + max_wait_ms: int + min_bytes: int + max_bytes: int + isolation_level: int + session_id: int + session_epoch: int + topics: list[FetchTopic] + forgotten_topics_data: list[ForgottenTopic] + rack_id: str + def __init__( + self, + *args, + cluster_id: str | None = ..., + replica_id: int = ..., + replica_state: ReplicaState = ..., + max_wait_ms: int = ..., + min_bytes: int = ..., + max_bytes: int = ..., + isolation_level: int = ..., + session_id: int = ..., + session_epoch: int = ..., + topics: list[FetchTopic] = ..., + forgotten_topics_data: list[ForgottenTopic] = ..., + rack_id: str = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def min_version_for_isolation_level(cls, il): ... + +class FetchResponse(ApiMessage): + class FetchableTopicResponse(DataContainer): + class PartitionData(DataContainer): + class EpochEndOffset(DataContainer): + epoch: int + end_offset: int + def __init__( + self, *args, epoch: int = ..., end_offset: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class LeaderIdAndEpoch(DataContainer): + leader_id: int + leader_epoch: int + def __init__( + self, *args, leader_id: int = ..., leader_epoch: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class SnapshotId(DataContainer): + end_offset: int + epoch: int + def __init__( + self, *args, end_offset: int = ..., epoch: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class AbortedTransaction(DataContainer): + producer_id: int + first_offset: int + def __init__( + self, *args, producer_id: int = ..., first_offset: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + partition_index: int + error_code: int + high_watermark: int + last_stable_offset: int + log_start_offset: int + diverging_epoch: EpochEndOffset + current_leader: LeaderIdAndEpoch + snapshot_id: SnapshotId + aborted_transactions: list[AbortedTransaction] | None + preferred_read_replica: int + records: bytes | ApiData | None + def __init__( + self, + *args, + partition_index: int = ..., + error_code: int = ..., + high_watermark: int = ..., + last_stable_offset: int = ..., + log_start_offset: int = ..., + diverging_epoch: EpochEndOffset = ..., + current_leader: LeaderIdAndEpoch = ..., + snapshot_id: SnapshotId = ..., + aborted_transactions: list[AbortedTransaction] | None = ..., + preferred_read_replica: int = ..., + records: bytes | ApiData | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic: str + topic_id: uuid.UUID + partitions: list[PartitionData] + def __init__( + self, + *args, + topic: str = ..., + topic_id: uuid.UUID = ..., + partitions: list[PartitionData] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class NodeEndpoint(DataContainer): + node_id: int + host: str + port: int + rack: str | None + def __init__( + self, + *args, + node_id: int = ..., + host: str = ..., + port: int = ..., + rack: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + session_id: int + responses: list[FetchableTopicResponse] + node_endpoints: list[NodeEndpoint] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + session_id: int = ..., + responses: list[FetchableTopicResponse] = ..., + node_endpoints: list[NodeEndpoint] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = ["FetchRequest", "FetchResponse"] diff --git a/stubs/kafka-python/kafka/protocol/consumer/group.pyi b/stubs/kafka-python/kafka/protocol/consumer/group.pyi new file mode 100644 index 000000000000..afba3210444c --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/consumer/group.pyi @@ -0,0 +1,799 @@ +import uuid +from _typeshed import Incomplete +from typing import Final + +from kafka.protocol.api_data import ApiData +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +DEFAULT_GENERATION_ID: Final = -1 +UNKNOWN_MEMBER_ID: Final = "" + +class JoinGroupRequest(ApiMessage): + class JoinGroupRequestProtocol(DataContainer): + name: str + metadata: bytes | ApiData + def __init__( + self, *args, name: str = ..., metadata: bytes | ApiData = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + session_timeout_ms: int + rebalance_timeout_ms: int + member_id: str + group_instance_id: str | None + protocol_type: str + protocols: list[JoinGroupRequestProtocol] + reason: str | None + def __init__( + self, + *args, + group_id: str = ..., + session_timeout_ms: int = ..., + rebalance_timeout_ms: int = ..., + member_id: str = ..., + group_instance_id: str | None = ..., + protocol_type: str = ..., + protocols: list[JoinGroupRequestProtocol] = ..., + reason: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class JoinGroupResponse(ApiMessage): + class JoinGroupResponseMember(DataContainer): + member_id: str + group_instance_id: str | None + metadata: bytes | ApiData + def __init__( + self, + *args, + member_id: str = ..., + group_instance_id: str | None = ..., + metadata: bytes | ApiData = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + generation_id: int + protocol_type: str | None + protocol_name: str | None + leader: str + skip_assignment: bool + member_id: str + members: list[JoinGroupResponseMember] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + generation_id: int = ..., + protocol_type: str | None = ..., + protocol_name: str | None = ..., + leader: str = ..., + skip_assignment: bool = ..., + member_id: str = ..., + members: list[JoinGroupResponseMember] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class SyncGroupRequest(ApiMessage): + class SyncGroupRequestAssignment(DataContainer): + member_id: str + assignment: bytes | ApiData + def __init__( + self, *args, member_id: str = ..., assignment: bytes | ApiData = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + generation_id: int + member_id: str + group_instance_id: str | None + protocol_type: str | None + protocol_name: str | None + assignments: list[SyncGroupRequestAssignment] + def __init__( + self, + *args, + group_id: str = ..., + generation_id: int = ..., + member_id: str = ..., + group_instance_id: str | None = ..., + protocol_type: str | None = ..., + protocol_name: str | None = ..., + assignments: list[SyncGroupRequestAssignment] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class SyncGroupResponse(ApiMessage): + throttle_time_ms: int + error_code: int + protocol_type: str | None + protocol_name: str | None + assignment: bytes | ApiData + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + protocol_type: str | None = ..., + protocol_name: str | None = ..., + assignment: bytes | ApiData = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class LeaveGroupRequest(ApiMessage): + class MemberIdentity(DataContainer): + member_id: str + group_instance_id: str | None + reason: str | None + def __init__( + self, + *args, + member_id: str = ..., + group_instance_id: str | None = ..., + reason: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + member_id: str + members: list[MemberIdentity] + def __init__( + self, + *args, + group_id: str = ..., + member_id: str = ..., + members: list[MemberIdentity] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class LeaveGroupResponse(ApiMessage): + class MemberResponse(DataContainer): + member_id: str + group_instance_id: str | None + error_code: int + def __init__( + self, + *args, + member_id: str = ..., + group_instance_id: str | None = ..., + error_code: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + members: list[MemberResponse] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + members: list[MemberResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class HeartbeatRequest(ApiMessage): + group_id: str + generation_id: int + member_id: str + group_instance_id: str | None + def __init__( + self, + *args, + group_id: str = ..., + generation_id: int = ..., + member_id: str = ..., + group_instance_id: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class HeartbeatResponse(ApiMessage): + throttle_time_ms: int + error_code: int + def __init__( + self, *args, throttle_time_ms: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetFetchRequest(ApiMessage): + class OffsetFetchRequestTopic(DataContainer): + name: str + partition_indexes: list[int] + def __init__( + self, *args, name: str = ..., partition_indexes: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class OffsetFetchRequestGroup(DataContainer): + class OffsetFetchRequestTopics(DataContainer): + name: str + topic_id: uuid.UUID + partition_indexes: list[int] + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + partition_indexes: list[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + member_id: str | None + member_epoch: int + topics: list[OffsetFetchRequestTopics] | None + def __init__( + self, + *args, + group_id: str = ..., + member_id: str | None = ..., + member_epoch: int = ..., + topics: list[OffsetFetchRequestTopics] | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + topics: list[OffsetFetchRequestTopic] | None + groups: list[OffsetFetchRequestGroup] + require_stable: bool + def __init__( + self, + *args, + group_id: str = ..., + topics: list[OffsetFetchRequestTopic] | None = ..., + groups: list[OffsetFetchRequestGroup] = ..., + require_stable: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetFetchResponse(ApiMessage): + class OffsetFetchResponseTopic(DataContainer): + class OffsetFetchResponsePartition(DataContainer): + partition_index: int + committed_offset: int + committed_leader_epoch: int + metadata: str | None + error_code: int + def __init__( + self, + *args, + partition_index: int = ..., + committed_offset: int = ..., + committed_leader_epoch: int = ..., + metadata: str | None = ..., + error_code: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[OffsetFetchResponsePartition] + def __init__( + self, + *args, + name: str = ..., + partitions: list[OffsetFetchResponsePartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class OffsetFetchResponseGroup(DataContainer): + class OffsetFetchResponseTopics(DataContainer): + class OffsetFetchResponsePartitions(DataContainer): + partition_index: int + committed_offset: int + committed_leader_epoch: int + metadata: str | None + error_code: int + def __init__( + self, + *args, + partition_index: int = ..., + committed_offset: int = ..., + committed_leader_epoch: int = ..., + metadata: str | None = ..., + error_code: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + topic_id: uuid.UUID + partitions: list[OffsetFetchResponsePartitions] + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + partitions: list[OffsetFetchResponsePartitions] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + topics: list[OffsetFetchResponseTopics] + error_code: int + def __init__( + self, + *args, + group_id: str = ..., + topics: list[OffsetFetchResponseTopics] = ..., + error_code: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[OffsetFetchResponseTopic] + error_code: int + groups: list[OffsetFetchResponseGroup] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[OffsetFetchResponseTopic] = ..., + error_code: int = ..., + groups: list[OffsetFetchResponseGroup] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetCommitRequest(ApiMessage): + class OffsetCommitRequestTopic(DataContainer): + class OffsetCommitRequestPartition(DataContainer): + partition_index: int + committed_offset: int + committed_leader_epoch: int + commit_timestamp: int + committed_metadata: str | None + def __init__( + self, + *args, + partition_index: int = ..., + committed_offset: int = ..., + committed_leader_epoch: int = ..., + commit_timestamp: int = ..., + committed_metadata: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + topic_id: uuid.UUID + partitions: list[OffsetCommitRequestPartition] + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + partitions: list[OffsetCommitRequestPartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + generation_id_or_member_epoch: int + member_id: str + group_instance_id: str | None + retention_time_ms: int + topics: list[OffsetCommitRequestTopic] + def __init__( + self, + *args, + group_id: str = ..., + generation_id_or_member_epoch: int = ..., + member_id: str = ..., + group_instance_id: str | None = ..., + retention_time_ms: int = ..., + topics: list[OffsetCommitRequestTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetCommitResponse(ApiMessage): + class OffsetCommitResponseTopic(DataContainer): + class OffsetCommitResponsePartition(DataContainer): + partition_index: int + error_code: int + def __init__( + self, *args, partition_index: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + topic_id: uuid.UUID + partitions: list[OffsetCommitResponsePartition] + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + partitions: list[OffsetCommitResponsePartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[OffsetCommitResponseTopic] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[OffsetCommitResponseTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetDeleteRequest(ApiMessage): + class OffsetDeleteRequestTopic(DataContainer): + class OffsetDeleteRequestPartition(DataContainer): + partition_index: int + def __init__(self, *args, partition_index: int = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[OffsetDeleteRequestPartition] + def __init__( + self, + *args, + name: str = ..., + partitions: list[OffsetDeleteRequestPartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + group_id: str + topics: list[OffsetDeleteRequestTopic] + def __init__( + self, *args, group_id: str = ..., topics: list[OffsetDeleteRequestTopic] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetDeleteResponse(ApiMessage): + class OffsetDeleteResponseTopic(DataContainer): + class OffsetDeleteResponsePartition(DataContainer): + partition_index: int + error_code: int + def __init__( + self, *args, partition_index: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[OffsetDeleteResponsePartition] + def __init__( + self, + *args, + name: str = ..., + partitions: list[OffsetDeleteResponsePartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + throttle_time_ms: int + topics: list[OffsetDeleteResponseTopic] + def __init__( + self, + *args, + error_code: int = ..., + throttle_time_ms: int = ..., + topics: list[OffsetDeleteResponseTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "DEFAULT_GENERATION_ID", + "UNKNOWN_MEMBER_ID", + "JoinGroupRequest", + "JoinGroupResponse", + "SyncGroupRequest", + "SyncGroupResponse", + "LeaveGroupRequest", + "LeaveGroupResponse", + "HeartbeatRequest", + "HeartbeatResponse", + "OffsetFetchRequest", + "OffsetFetchResponse", + "OffsetCommitRequest", + "OffsetCommitResponse", + "OffsetDeleteRequest", + "OffsetDeleteResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/consumer/metadata.pyi b/stubs/kafka-python/kafka/protocol/consumer/metadata.pyi new file mode 100644 index 000000000000..15d899effc4b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/consumer/metadata.pyi @@ -0,0 +1,82 @@ +from _typeshed import Incomplete +from typing import Final + +from kafka.protocol.api_data import ApiData +from kafka.protocol.data_container import DataContainer + +ConsumerProtocolType: Final = "consumer" + +class ConsumerProtocolSubscription(ApiData): + class TopicPartition(DataContainer): + topic: str + partitions: list[int] + def __init__( + self, *args, topic: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[str] + user_data: bytes | ApiData | None + owned_partitions: list[TopicPartition] + generation_id: int + rack_id: str | None + def __init__( + self, + *args, + topics: list[str] = ..., + user_data: bytes | ApiData | None = ..., + owned_partitions: list[TopicPartition] = ..., + generation_id: int = ..., + rack_id: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + valid_versions: tuple[int, int] + min_version: int + max_version: int + +class ConsumerProtocolAssignment(ApiData): + class TopicPartition(DataContainer): + topic: str + partitions: list[int] + def __init__( + self, *args, topic: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + assigned_partitions: list[TopicPartition] + user_data: bytes | ApiData | None + def __init__( + self, + *args, + assigned_partitions: list[TopicPartition] = ..., + user_data: bytes | ApiData | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + valid_versions: tuple[int, int] + min_version: int + max_version: int + + @property + def assignment(self) -> list[TopicPartition]: ... + @assignment.setter + def assignment(self, value: list[TopicPartition]) -> None: ... + + def partitions(self) -> list[TopicPartition]: ... + +__all__ = ["ConsumerProtocolSubscription", "ConsumerProtocolAssignment", "ConsumerProtocolType"] diff --git a/stubs/kafka-python/kafka/protocol/consumer/offsets.pyi b/stubs/kafka-python/kafka/protocol/consumer/offsets.pyi new file mode 100644 index 000000000000..472c68ce8414 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/consumer/offsets.pyi @@ -0,0 +1,278 @@ +from _typeshed import Incomplete +from enum import IntEnum +from typing import Final + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer +from kafka.util import EnumHelper + +UNKNOWN_OFFSET: Final = -1 + +class OffsetResetStrategy: + LATEST: Final = -1 + EARLIEST: Final = -2 + NONE: Final = 0 + +class IsolationLevel(EnumHelper, IntEnum): + READ_UNCOMMITTED = 0 + READ_COMMITTED = 1 + +class OffsetSpec(EnumHelper, IntEnum): + LATEST = -1 + EARLIEST = -2 + MAX_TIMESTAMP = -3 + EARLIEST_LOCAL = -4 + LATEST_TIERED = -5 + +class OffsetTimestamp(int): + __slots__ = () + +class ListOffsetsRequest(ApiMessage): + class ListOffsetsTopic(DataContainer): + class ListOffsetsPartition(DataContainer): + partition_index: int + current_leader_epoch: int + timestamp: int + max_num_offsets: int + def __init__( + self, + *args, + partition_index: int = ..., + current_leader_epoch: int = ..., + timestamp: int = ..., + max_num_offsets: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[ListOffsetsPartition] + def __init__( + self, *args, name: str = ..., partitions: list[ListOffsetsPartition] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + replica_id: int + isolation_level: int + topics: list[ListOffsetsTopic] + timeout_ms: int + def __init__( + self, + *args, + replica_id: int = ..., + isolation_level: int = ..., + topics: list[ListOffsetsTopic] = ..., + timeout_ms: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def min_version_for_timestamp(cls, ts): ... + @classmethod + def min_version_for_isolation_level(cls, il): ... + +class ListOffsetsResponse(ApiMessage): + class ListOffsetsTopicResponse(DataContainer): + class ListOffsetsPartitionResponse(DataContainer): + partition_index: int + error_code: int + old_style_offsets: list[int] + timestamp: int + offset: int + leader_epoch: int + def __init__( + self, + *args, + partition_index: int = ..., + error_code: int = ..., + old_style_offsets: list[int] = ..., + timestamp: int = ..., + offset: int = ..., + leader_epoch: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[ListOffsetsPartitionResponse] + def __init__( + self, + *args, + name: str = ..., + partitions: list[ListOffsetsPartitionResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[ListOffsetsTopicResponse] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[ListOffsetsTopicResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetForLeaderEpochRequest(ApiMessage): + class OffsetForLeaderTopic(DataContainer): + class OffsetForLeaderPartition(DataContainer): + partition: int + current_leader_epoch: int + leader_epoch: int + def __init__( + self, + *args, + partition: int = ..., + current_leader_epoch: int = ..., + leader_epoch: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic: str + partitions: list[OffsetForLeaderPartition] + def __init__( + self, *args, topic: str = ..., partitions: list[OffsetForLeaderPartition] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + replica_id: int + topics: list[OffsetForLeaderTopic] + def __init__( + self, *args, replica_id: int = ..., topics: list[OffsetForLeaderTopic] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class OffsetForLeaderEpochResponse(ApiMessage): + class OffsetForLeaderTopicResult(DataContainer): + class EpochEndOffset(DataContainer): + error_code: int + partition: int + leader_epoch: int + end_offset: int + def __init__( + self, + *args, + error_code: int = ..., + partition: int = ..., + leader_epoch: int = ..., + end_offset: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topic: str + partitions: list[EpochEndOffset] + def __init__( + self, *args, topic: str = ..., partitions: list[EpochEndOffset] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[OffsetForLeaderTopicResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[OffsetForLeaderTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "UNKNOWN_OFFSET", + "OffsetResetStrategy", + "IsolationLevel", + "OffsetSpec", + "OffsetTimestamp", + "ListOffsetsRequest", + "ListOffsetsResponse", + "OffsetForLeaderEpochRequest", + "OffsetForLeaderEpochResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/data_container.pyi b/stubs/kafka-python/kafka/protocol/data_container.pyi new file mode 100644 index 000000000000..0abd4d7706d8 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/data_container.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +from kafka.util import classproperty + +class SlotsBuilder(type): + def __new__(metacls, name, bases, attrs, **kw): ... + +class DataContainer(metaclass=SlotsBuilder): + __slots__ = ("tags", "unknown_tags", "_version") + def __init_subclass__(cls, **kwargs) -> None: ... + tags: set[Incomplete] | None + unknown_tags: dict[str, Incomplete] | None + def __init__(self, *args, version=None, **field_vals) -> None: ... + def __getattr__(self, name): ... + @property + def version(self): ... + def encode(self, *args, **kwargs): ... + def encode_into(self, out, *args, **kwargs) -> None: ... + @classmethod + def decode(cls, data, **kwargs): ... + @classproperty + def fields(cls): ... + def __eq__(self, other) -> bool: ... + def __iter__(self) -> Iterator[Incomplete]: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + def __getitem__(self, key: int | slice): ... diff --git a/stubs/kafka-python/kafka/protocol/frame.pyi b/stubs/kafka-python/kafka/protocol/frame.pyi new file mode 100644 index 000000000000..b3c8b9647588 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/frame.pyi @@ -0,0 +1,6 @@ +class KafkaBytes(bytearray): + def __init__(self, size) -> None: ... + def read(self, nbytes=None): ... + def write(self, data) -> None: ... + def seek(self, idx) -> None: ... + def tell(self): ... diff --git a/stubs/kafka-python/kafka/protocol/generate_stubs.pyi b/stubs/kafka-python/kafka/protocol/generate_stubs.pyi new file mode 100644 index 000000000000..367f85525b68 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/generate_stubs.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from types import ModuleType +from typing import Final + +SIMPLE_TYPE_MAP: Final[dict[str, str]] +MESSAGE_MODULES: Final[list[str]] + +def resolve_type(field: object) -> str: ... +def emit_class(cls: type, indent: int = 0, base_name: str | None = None) -> list[str]: ... +def discover_modules() -> dict[str, tuple[ModuleType, list[tuple[str, Incomplete]]]]: ... +def generate_module(mod, exports) -> str: ... +def generate_all(dry_run: bool = False, check: bool = False) -> bool: ... diff --git a/stubs/kafka-python/kafka/protocol/metadata/__init__.pyi b/stubs/kafka-python/kafka/protocol/metadata/__init__.pyi new file mode 100644 index 000000000000..7a07a803c212 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/metadata/__init__.pyi @@ -0,0 +1,13 @@ +from .api_versions import * +from .find_coordinator import * +from .metadata import * + +__all__ = [ + "ApiVersionsRequest", + "ApiVersionsResponse", + "CoordinatorType", + "FindCoordinatorRequest", + "FindCoordinatorResponse", + "MetadataRequest", + "MetadataResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/metadata/api_versions.pyi b/stubs/kafka-python/kafka/protocol/metadata/api_versions.pyi new file mode 100644 index 000000000000..febcbb43cbd5 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/metadata/api_versions.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class ApiVersionsRequest(ApiMessage): + client_software_name: str + client_software_version: str + def __init__( + self, *args, client_software_name: str = ..., client_software_version: str = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class ApiVersionsResponse(ApiMessage): + class ApiVersion(DataContainer): + api_key: int + min_version: int + max_version: int + def __init__( + self, *args, api_key: int = ..., min_version: int = ..., max_version: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class SupportedFeatureKey(DataContainer): + name: str + min_version: int + max_version: int + def __init__( + self, *args, name: str = ..., min_version: int = ..., max_version: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class FinalizedFeatureKey(DataContainer): + name: str + max_version_level: int + min_version_level: int + def __init__( + self, + *args, + name: str = ..., + max_version_level: int = ..., + min_version_level: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + api_keys: list[ApiVersion] + throttle_time_ms: int + supported_features: list[SupportedFeatureKey] + finalized_features_epoch: int + finalized_features: list[FinalizedFeatureKey] + zk_migration_ready: bool + def __init__( + self, + *args, + error_code: int = ..., + api_keys: list[ApiVersion] = ..., + throttle_time_ms: int = ..., + supported_features: list[SupportedFeatureKey] = ..., + finalized_features_epoch: int = ..., + finalized_features: list[FinalizedFeatureKey] = ..., + zk_migration_ready: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def parse_header(cls, data, version=None): ... + def encode_header(self, flexible: bool = False): ... + @classmethod + def decode(cls, data, version=None, header: bool = False, framed: bool = False): ... # type: ignore[override] + +__all__ = ["ApiVersionsRequest", "ApiVersionsResponse"] diff --git a/stubs/kafka-python/kafka/protocol/metadata/find_coordinator.pyi b/stubs/kafka-python/kafka/protocol/metadata/find_coordinator.pyi new file mode 100644 index 000000000000..d1c9be13e5dc --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/metadata/find_coordinator.pyi @@ -0,0 +1,98 @@ +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer +from kafka.util import EnumHelper + +class CoordinatorType(EnumHelper, IntEnum): + GROUP = 0 + TRANSACTION = 1 + SHARE = 2 + +class FindCoordinatorRequest(ApiMessage): + key: str + key_type: int + coordinator_keys: list[str] + def __init__( + self, *args, key: str = ..., key_type: int = ..., coordinator_keys: list[str] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class FindCoordinatorResponse(ApiMessage): + class Coordinator(DataContainer): + key: str + node_id: int + host: str + port: int + error_code: int + error_message: str | None + def __init__( + self, + *args, + key: str = ..., + node_id: int = ..., + host: str = ..., + port: int = ..., + error_code: int = ..., + error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + error_message: str | None + node_id: int + host: str + port: int + coordinators: list[Coordinator] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + error_message: str | None = ..., + node_id: int = ..., + host: str = ..., + port: int = ..., + coordinators: list[Coordinator] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = ["CoordinatorType", "FindCoordinatorRequest", "FindCoordinatorResponse"] diff --git a/stubs/kafka-python/kafka/protocol/metadata/metadata.pyi b/stubs/kafka-python/kafka/protocol/metadata/metadata.pyi new file mode 100644 index 000000000000..372a7394f9b0 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/metadata/metadata.pyi @@ -0,0 +1,160 @@ +import uuid +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class MetadataRequest(ApiMessage): + ALL_TOPICS: Incomplete | None + NO_TOPICS: list[Incomplete] + + class MetadataRequestTopic(DataContainer): + topic_id: uuid.UUID + name: str | None + def __init__( + self, *args, topic_id: uuid.UUID = ..., name: str | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + topics: list[MetadataRequestTopic] | None + allow_auto_topic_creation: bool + include_cluster_authorized_operations: bool + include_topic_authorized_operations: bool + def __init__( + self, + *args, + topics: list[MetadataRequestTopic] | None = ..., + allow_auto_topic_creation: bool = ..., + include_cluster_authorized_operations: bool = ..., + include_topic_authorized_operations: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + def encode(self, version=None, header=False, framed=False): ... + +class MetadataResponse(ApiMessage): + class MetadataResponseBroker(DataContainer): + node_id: int + host: str + port: int + rack: str | None + def __init__( + self, + *args, + node_id: int = ..., + host: str = ..., + port: int = ..., + rack: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class MetadataResponseTopic(DataContainer): + class MetadataResponsePartition(DataContainer): + error_code: int + partition_index: int + leader_id: int + leader_epoch: int + replica_nodes: list[int] + isr_nodes: list[int] + offline_replicas: list[int] + def __init__( + self, + *args, + error_code: int = ..., + partition_index: int = ..., + leader_id: int = ..., + leader_epoch: int = ..., + replica_nodes: list[int] = ..., + isr_nodes: list[int] = ..., + offline_replicas: list[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + error_code: int + name: str | None + topic_id: uuid.UUID + is_internal: bool + partitions: list[MetadataResponsePartition] + authorized_operations: set[int] + def __init__( + self, + *args, + error_code: int = ..., + name: str | None = ..., + topic_id: uuid.UUID = ..., + is_internal: bool = ..., + partitions: list[MetadataResponsePartition] = ..., + authorized_operations: set[int] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + brokers: list[MetadataResponseBroker] + cluster_id: str | None + controller_id: int + topics: list[MetadataResponseTopic] + authorized_operations: set[int] + error_code: int + def __init__( + self, + *args, + throttle_time_ms: int = ..., + brokers: list[MetadataResponseBroker] = ..., + cluster_id: str | None = ..., + controller_id: int = ..., + topics: list[MetadataResponseTopic] = ..., + authorized_operations: set[int] = ..., + error_code: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + @classmethod + def json_patch(cls, json): ... + +__all__ = ["MetadataRequest", "MetadataResponse"] diff --git a/stubs/Pillow/PIL/PdfImagePlugin.pyi b/stubs/kafka-python/kafka/protocol/old/__init__.pyi similarity index 100% rename from stubs/Pillow/PIL/PdfImagePlugin.pyi rename to stubs/kafka-python/kafka/protocol/old/__init__.pyi diff --git a/stubs/kafka-python/kafka/protocol/old/abstract.pyi b/stubs/kafka-python/kafka/protocol/old/abstract.pyi new file mode 100644 index 000000000000..c3a45c08d62c --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/abstract.pyi @@ -0,0 +1,11 @@ +import abc +from _typeshed import Incomplete + +class AbstractType(metaclass=abc.ABCMeta): + @classmethod + @abc.abstractmethod + def encode(cls, value): ... + @classmethod + @abc.abstractmethod + def decode(cls, data): ... + repr: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/add_offsets_to_txn.pyi b/stubs/kafka-python/kafka/protocol/old/add_offsets_to_txn.pyi new file mode 100644 index 000000000000..8f2c24de09a3 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/add_offsets_to_txn.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class AddOffsetsToTxnResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +AddOffsetsToTxnRequest: Incomplete +AddOffsetsToTxnResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/add_partitions_to_txn.pyi b/stubs/kafka-python/kafka/protocol/old/add_partitions_to_txn.pyi new file mode 100644 index 000000000000..455e50c13472 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/add_partitions_to_txn.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class AddPartitionsToTxnResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AddPartitionsToTxnResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AddPartitionsToTxnResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AddPartitionsToTxnRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddPartitionsToTxnResponse_v0 + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AddPartitionsToTxnRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddPartitionsToTxnResponse_v1 + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AddPartitionsToTxnRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddPartitionsToTxnResponse_v2 + SCHEMA: Incomplete + ALIASES: dict[str, str] + +AddPartitionsToTxnRequest: list[type[Incomplete]] +AddPartitionsToTxnResponse: list[type[Incomplete]] diff --git a/stubs/kafka-python/kafka/protocol/old/admin.pyi b/stubs/kafka-python/kafka/protocol/old/admin.pyi new file mode 100644 index 000000000000..d83f6efd6a50 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/admin.pyi @@ -0,0 +1,479 @@ +from _typeshed import Incomplete +from enum import IntEnum + +from .api import Request, Response + +class CreateTopicsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateTopicsRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +CreateTopicsRequest: Incomplete +CreateTopicsResponse: Incomplete + +class DeleteTopicsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteTopicsRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +DeleteTopicsRequest: Incomplete +DeleteTopicsResponse: Incomplete + +class DeleteRecordsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteRecordsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DeleteRecordsResponse: Incomplete +DeleteRecordsRequest: Incomplete + +class ListGroupsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +ListGroupsRequest: Incomplete +ListGroupsResponse: Incomplete + +class DescribeGroupsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DescribeGroupsRequest: Incomplete +DescribeGroupsResponse: Incomplete + +class DescribeAclsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeAclsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeAclsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeAclsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DescribeAclsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DescribeAclsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DescribeAclsRequest: Incomplete +DescribeAclsResponse: Incomplete + +class CreateAclsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateAclsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreateAclsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateAclsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +CreateAclsRequest: Incomplete +CreateAclsResponse: Incomplete + +class DeleteAclsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteAclsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DeleteAclsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteAclsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DeleteAclsRequest: Incomplete +DeleteAclsResponse: Incomplete + +class AlterConfigsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AlterConfigsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class AlterConfigsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AlterConfigsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +AlterConfigsRequest: Incomplete +AlterConfigsResponse: Incomplete + +class DescribeConfigsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DescribeConfigsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DescribeConfigsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DescribeConfigsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeConfigsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeConfigsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DescribeConfigsRequest: Incomplete +DescribeConfigsResponse: Incomplete + +class DescribeLogDirsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class DescribeLogDirsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DescribeLogDirsResponse: Incomplete +DescribeLogDirsRequest: Incomplete + +class CreatePartitionsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreatePartitionsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreatePartitionsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class CreatePartitionsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +CreatePartitionsRequest: Incomplete +CreatePartitionsResponse: Incomplete + +class DeleteGroupsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteGroupsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteGroupsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteGroupsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DeleteGroupsRequest: Incomplete +DeleteGroupsResponse: Incomplete + +class DescribeClientQuotasResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeClientQuotasRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +DescribeClientQuotasRequest: Incomplete +DescribeClientQuotasResponse: Incomplete + +class AlterPartitionReassignmentsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +class AlterPartitionReassignmentsRequest_v0(Request): + FLEXIBLE_VERSION: bool + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +AlterPartitionReassignmentsRequest: Incomplete +AlterPartitionReassignmentsResponse: Incomplete + +class ListPartitionReassignmentsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +class ListPartitionReassignmentsRequest_v0(Request): + FLEXIBLE_VERSION: bool + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +ListPartitionReassignmentsRequest: Incomplete +ListPartitionReassignmentsResponse: Incomplete + +class ElectLeadersResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ElectLeadersRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ElectLeadersResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ElectLeadersRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ElectionType(IntEnum): + PREFERRED = 0 + UNCLEAN = 1 + +ElectLeadersRequest: Incomplete +ElectLeadersResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/api.pyi b/stubs/kafka-python/kafka/protocol/old/api.pyi new file mode 100644 index 000000000000..c8732d81be39 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/api.pyi @@ -0,0 +1,66 @@ +import abc +from typing_extensions import Self + +from .struct import Struct +from .types import Schema + +class ResponseClassRegistry: + @classmethod + def register_response_class(cls, response_class) -> None: ... + @classmethod + def get_response_class(cls, header): ... + +class RequestHeader(ResponseClassRegistry, Struct): + SCHEMA: Schema + def get_response_class(self): ... # type: ignore[override] + +class RequestHeaderV2(ResponseClassRegistry, Struct): + SCHEMA: Schema + def get_response_class(self): ... # type: ignore[override] + +class ResponseHeader(Struct): + SCHEMA: Schema + +class ResponseHeaderV2(Struct): + SCHEMA: Schema + +class RequestResponse(Struct, metaclass=abc.ABCMeta): + def __init__(self, *args, **kwargs) -> None: ... + @property + @abc.abstractmethod + def API_KEY(self): ... + @property + @abc.abstractmethod + def API_VERSION(self): ... + def to_object(self): ... + @classmethod + @abc.abstractmethod + def is_request(cls): ... + @property + def header(self): ... + def with_header(self, correlation_id: int = 0, client_id="kafka-python") -> None: ... + def encode(self, header: bool = False, framed: bool = False) -> bytes: ... + @classmethod + @abc.abstractmethod + def header_class(cls): ... + @classmethod + def parse_header(cls, read_buffer): ... + @classmethod + def decode(cls, data, header: bool = False, framed: bool = False) -> Self: ... + def __eq__(self, other) -> bool: ... + +class Request(RequestResponse, metaclass=abc.ABCMeta): + FLEXIBLE_VERSION: bool + @classmethod + def is_request(cls): ... + def expect_response(self): ... + @classmethod + def header_class(cls): ... + +class Response(RequestResponse, metaclass=abc.ABCMeta): + FLEXIBLE_VERSION: bool + def __init_subclass__(cls, **kwargs) -> None: ... + @classmethod + def is_request(cls): ... + @classmethod + def header_class(cls): ... diff --git a/stubs/kafka-python/kafka/protocol/old/api_versions.pyi b/stubs/kafka-python/kafka/protocol/old/api_versions.pyi new file mode 100644 index 000000000000..d71419ac2134 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/api_versions.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class BaseApiVersionsResponse(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + @classmethod + def decode(cls, data, header: bool = False, framed: bool = False): ... + +class ApiVersionsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ApiVersionsResponse_v1(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v2(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v3(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v4(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +class ApiVersionsRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +ApiVersionsRequest: Incomplete +ApiVersionsResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/commit.pyi b/stubs/kafka-python/kafka/protocol/old/commit.pyi new file mode 100644 index 000000000000..f3bf34359f36 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/commit.pyi @@ -0,0 +1,166 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class OffsetCommitResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetCommitRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetCommitRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULT_RETENTION_TIME: int + ALIASES: dict[str, str] + +class OffsetCommitRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULT_RETENTION_TIME: int + ALIASES: dict[str, str] + +class OffsetCommitRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULT_RETENTION_TIME: int + ALIASES: dict[str, str] + +class OffsetCommitRequest_v5(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetCommitRequest_v6(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetCommitRequest_v7(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +OffsetCommitRequest: Incomplete +OffsetCommitResponse: Incomplete + +class OffsetFetchResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetFetchRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetFetchRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetFetchRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetFetchRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class OffsetFetchRequest_v5(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +OffsetFetchRequest: Incomplete +OffsetFetchResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/consumer_protocol.pyi b/stubs/kafka-python/kafka/protocol/old/consumer_protocol.pyi new file mode 100644 index 000000000000..f5b6721a0d45 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/consumer_protocol.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from .struct import Struct + +class ConsumerProtocolMemberMetadata_v0(Struct): + SCHEMA: Incomplete + +class ConsumerProtocolMemberAssignment_v0(Struct): + SCHEMA: Incomplete + def partitions(self): ... + +class ConsumerProtocol_v0: + PROTOCOL_TYPE: str + METADATA = ConsumerProtocolMemberMetadata_v0 + ASSIGNMENT = ConsumerProtocolMemberAssignment_v0 + +ConsumerProtocol: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/end_txn.pyi b/stubs/kafka-python/kafka/protocol/old/end_txn.pyi new file mode 100644 index 000000000000..541f89bfb43e --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/end_txn.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class EndTxnResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +EndTxnRequest: Incomplete +EndTxnResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/fetch.pyi b/stubs/kafka-python/kafka/protocol/old/fetch.pyi new file mode 100644 index 000000000000..f5eed746b22d --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/fetch.pyi @@ -0,0 +1,155 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +from .api import Request, Response + +class AbortedTransaction(NamedTuple): + producer_id: Incomplete + first_offset: Incomplete + +class FetchResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v8(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v9(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v10(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchResponse_v11(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v5(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v6(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v7(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v8(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v9(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v10(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FetchRequest_v11(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +FetchRequest: Incomplete +FetchResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/find_coordinator.pyi b/stubs/kafka-python/kafka/protocol/old/find_coordinator.pyi new file mode 100644 index 000000000000..8e46974cc93a --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/find_coordinator.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class FindCoordinatorResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FindCoordinatorResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FindCoordinatorResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FindCoordinatorRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FindCoordinatorRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class FindCoordinatorRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +FindCoordinatorRequest: Incomplete +FindCoordinatorResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/group.pyi b/stubs/kafka-python/kafka/protocol/old/group.pyi new file mode 100644 index 000000000000..010931be6a9b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/group.pyi @@ -0,0 +1,239 @@ +from _typeshed import Incomplete +from typing import Final, NamedTuple + +from .api import Request, Response +from .struct import Struct + +DEFAULT_GENERATION_ID: Final = -1 +UNKNOWN_MEMBER_ID: Final = "" + +class GroupMember(NamedTuple): + member_id: Incomplete = ... + group_instance_id: Incomplete = ... + metadata: Incomplete = ... + +class JoinGroupResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class JoinGroupRequest_v5(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +JoinGroupRequest: Incomplete +JoinGroupResponse: Incomplete + +class ProtocolMetadata(Struct): + SCHEMA: Incomplete + +class SyncGroupResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SyncGroupRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +SyncGroupRequest: Incomplete +SyncGroupResponse: Incomplete + +class MemberAssignment(Struct): + SCHEMA: Incomplete + +class HeartbeatResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class HeartbeatRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class HeartbeatRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class HeartbeatRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +HeartbeatRequest: Incomplete +HeartbeatResponse: Incomplete + +class LeaveGroupResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class LeaveGroupRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class LeaveGroupRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class LeaveGroupRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +LeaveGroupRequest: Incomplete +LeaveGroupResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/init_producer_id.pyi b/stubs/kafka-python/kafka/protocol/old/init_producer_id.pyi new file mode 100644 index 000000000000..39108d004f3a --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/init_producer_id.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class InitProducerIdResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class InitProducerIdResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class InitProducerIdRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class InitProducerIdRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +InitProducerIdRequest: Incomplete +InitProducerIdResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/list_offsets.pyi b/stubs/kafka-python/kafka/protocol/old/list_offsets.pyi new file mode 100644 index 000000000000..78b6568bd9a8 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/list_offsets.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete +from typing import Final + +from .api import Request, Response + +UNKNOWN_OFFSET: Final = -1 + +class OffsetResetStrategy: + LATEST: int + EARLIEST: int + NONE: int + +class ListOffsetsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v5(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + DEFAULTS: Incomplete + +ListOffsetsRequest: Incomplete +ListOffsetsResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/metadata.pyi b/stubs/kafka-python/kafka/protocol/old/metadata.pyi new file mode 100644 index 000000000000..81d377e60348 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/metadata.pyi @@ -0,0 +1,114 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class MetadataResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v8(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v5(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v6(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v7(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v8(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +MetadataRequest: Incomplete +MetadataResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/offset_for_leader_epoch.pyi b/stubs/kafka-python/kafka/protocol/old/offset_for_leader_epoch.pyi new file mode 100644 index 000000000000..410081d1edb1 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/offset_for_leader_epoch.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class OffsetForLeaderEpochResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v3(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v4(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +OffsetForLeaderEpochRequest: Incomplete +OffsetForLeaderEpochResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/produce.pyi b/stubs/kafka-python/kafka/protocol/old/produce.pyi new file mode 100644 index 000000000000..351682500a67 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/produce.pyi @@ -0,0 +1,112 @@ +import abc +from _typeshed import Incomplete +from typing import type_check_only + +from .api import Request, Response + +class ProduceResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceResponse_v8(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +@type_check_only +class _ProduceRequest(Request, metaclass=abc.ABCMeta): + API_KEY: int + def expect_response(self): ... + +class ProduceRequest_v0(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v1(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v2(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v3(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v4(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v5(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v6(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v7(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class ProduceRequest_v8(_ProduceRequest): + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +ProduceRequest: list[type[_ProduceRequest]] +ProduceResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/sasl_authenticate.pyi b/stubs/kafka-python/kafka/protocol/old/sasl_authenticate.pyi new file mode 100644 index 000000000000..e49adbc9d788 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/sasl_authenticate.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class SaslAuthenticateResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +SaslAuthenticateRequest: Incomplete +SaslAuthenticateResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/sasl_handshake.pyi b/stubs/kafka-python/kafka/protocol/old/sasl_handshake.pyi new file mode 100644 index 000000000000..04281eb3b053 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/sasl_handshake.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class SaslHandshakeResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SaslHandshakeResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + ALIASES: dict[str, str] + +class SaslHandshakeRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslHandshakeRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +SaslHandshakeRequest: Incomplete +SaslHandshakeResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/struct.pyi b/stubs/kafka-python/kafka/protocol/old/struct.pyi new file mode 100644 index 000000000000..aa8c11dee6e7 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/struct.pyi @@ -0,0 +1,15 @@ +import abc +from typing_extensions import Self + +class Struct(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def SCHEMA(self): ... + ALIASES: dict[str, str] + def __init__(self, *args, **kwargs) -> None: ... + def encode(self): ... + @classmethod + def decode(cls, data) -> Self: ... + def get_item(self, name): ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> bool: ... diff --git a/stubs/kafka-python/kafka/protocol/old/txn_offset_commit.pyi b/stubs/kafka-python/kafka/protocol/old/txn_offset_commit.pyi new file mode 100644 index 000000000000..faa3f73980fe --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/txn_offset_commit.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +from .api import Request, Response + +class TxnOffsetCommitResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitRequest_v0(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitRequest_v2(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +TxnOffsetCommitRequest: Incomplete +TxnOffsetCommitResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/old/types.pyi b/stubs/kafka-python/kafka/protocol/old/types.pyi new file mode 100644 index 000000000000..4fa526218d1f --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/old/types.pyi @@ -0,0 +1,125 @@ +import uuid +from _typeshed import Incomplete +from typing import Final + +from .abstract import AbstractType as AbstractType + +class Int8(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Int16(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Int32(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Int64(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Float64(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class UUID(AbstractType): + ZERO_UUID: Final[uuid.UUID] + @classmethod + def encode(cls, value) -> bytes: ... + @classmethod + def decode(cls, data) -> uuid.UUID: ... + +class String(AbstractType): + encoding: Incomplete + def __init__(self, encoding: str = "utf-8") -> None: ... + def encode(self, value): ... # type: ignore[override] + def decode(self, data): ... # type: ignore[override] + +class Bytes(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + @classmethod + def repr(cls, value): ... + +class Boolean(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Schema(AbstractType): + def __init__(self, *fields) -> None: ... + def has_tagged_fields(self): ... + def encode(self, item): ... # type: ignore[override] + def decode(self, data): ... # type: ignore[override] + def __len__(self) -> int: ... + def repr(self, value): ... + +class Array(AbstractType): + array_of: Incomplete + def __init__(self, *array_of) -> None: ... + def encode(self, items): ... # type: ignore[override] + def decode(self, data): ... # type: ignore[override] + def repr(self, list_of_items): ... + +class UnsignedVarInt32(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class VarInt32(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class VarInt64(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class CompactString(String): + def decode(self, data): ... # type: ignore[override] + def encode(self, value): ... # type: ignore[override] + +class TaggedFields(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class CompactBytes(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class CompactArray(Array): + def encode(self, items): ... # type: ignore[override] + def decode(self, data): ... # type: ignore[override] + +class BitField(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, vals): ... + @classmethod + def to_32_bit_field(cls, vals): ... + @classmethod + def from_32_bit_field(cls, value): ... diff --git a/stubs/kafka-python/kafka/protocol/parser.pyi b/stubs/kafka-python/kafka/protocol/parser.pyi new file mode 100644 index 000000000000..b67f05b9cac9 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/parser.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections import deque + +class KafkaProtocol: + in_flight_requests: deque[tuple[int, Incomplete]] + bytes_to_send: list[bytes] + def __init__(self, *, client_id: str = ..., ident: str = "", receive_message_max_bytes: int = 100000000) -> None: ... + def send_request(self, request, correlation_id: int | None = None) -> int: ... + def send_bytes(self) -> bytes: ... + def receive_bytes(self, data: bytes) -> list[tuple[Incomplete, Incomplete]]: ... diff --git a/stubs/kafka-python/kafka/protocol/producer/__init__.pyi b/stubs/kafka-python/kafka/protocol/producer/__init__.pyi new file mode 100644 index 000000000000..1661cb819399 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/producer/__init__.pyi @@ -0,0 +1,19 @@ +from .produce import * +from .transaction import * + +__all__ = [ + "ProduceRequest", + "ProduceResponse", + "InitProducerIdRequest", + "InitProducerIdResponse", + "AddPartitionsToTxnRequest", + "AddPartitionsToTxnResponse", + "AddOffsetsToTxnRequest", + "AddOffsetsToTxnResponse", + "EndTxnRequest", + "EndTxnResponse", + "TxnOffsetCommitRequest", + "TxnOffsetCommitResponse", + "WriteTxnMarkersRequest", + "WriteTxnMarkersResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/producer/produce.pyi b/stubs/kafka-python/kafka/protocol/producer/produce.pyi new file mode 100644 index 000000000000..bf73051392c3 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/producer/produce.pyi @@ -0,0 +1,185 @@ +import uuid +from _typeshed import Incomplete + +from kafka.protocol.api_data import ApiData +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class ProduceRequest(ApiMessage): + class TopicProduceData(DataContainer): + class PartitionProduceData(DataContainer): + index: int + records: bytes | ApiData | None + def __init__( + self, *args, index: int = ..., records: bytes | ApiData | None = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + topic_id: uuid.UUID + partition_data: list[PartitionProduceData] + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + partition_data: list[PartitionProduceData] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + transactional_id: str | None + acks: int + timeout_ms: int + topic_data: list[TopicProduceData] + def __init__( + self, + *args, + transactional_id: str | None = ..., + acks: int = ..., + timeout_ms: int = ..., + topic_data: list[TopicProduceData] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + def expect_response(self) -> bool: ... + +class ProduceResponse(ApiMessage): + class TopicProduceResponse(DataContainer): + class PartitionProduceResponse(DataContainer): + class BatchIndexAndErrorMessage(DataContainer): + batch_index: int + batch_index_error_message: str | None + def __init__( + self, + *args, + batch_index: int = ..., + batch_index_error_message: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class LeaderIdAndEpoch(DataContainer): + leader_id: int + leader_epoch: int + def __init__( + self, *args, leader_id: int = ..., leader_epoch: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + index: int + error_code: int + base_offset: int + log_append_time_ms: int + log_start_offset: int + record_errors: list[BatchIndexAndErrorMessage] + error_message: str | None + current_leader: LeaderIdAndEpoch + def __init__( + self, + *args, + index: int = ..., + error_code: int = ..., + base_offset: int = ..., + log_append_time_ms: int = ..., + log_start_offset: int = ..., + record_errors: list[BatchIndexAndErrorMessage] = ..., + error_message: str | None = ..., + current_leader: LeaderIdAndEpoch = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + topic_id: uuid.UUID + partition_responses: list[PartitionProduceResponse] + def __init__( + self, + *args, + name: str = ..., + topic_id: uuid.UUID = ..., + partition_responses: list[PartitionProduceResponse] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class NodeEndpoint(DataContainer): + node_id: int + host: str + port: int + rack: str | None + def __init__( + self, + *args, + node_id: int = ..., + host: str = ..., + port: int = ..., + rack: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + responses: list[TopicProduceResponse] + throttle_time_ms: int + node_endpoints: list[NodeEndpoint] + def __init__( + self, + *args, + responses: list[TopicProduceResponse] = ..., + throttle_time_ms: int = ..., + node_endpoints: list[NodeEndpoint] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = ["ProduceRequest", "ProduceResponse"] diff --git a/stubs/kafka-python/kafka/protocol/producer/transaction.pyi b/stubs/kafka-python/kafka/protocol/producer/transaction.pyi new file mode 100644 index 000000000000..ccb56a9aa031 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/producer/transaction.pyi @@ -0,0 +1,620 @@ +from _typeshed import Incomplete + +from kafka.protocol.api_message import ApiMessage +from kafka.protocol.data_container import DataContainer + +class InitProducerIdRequest(ApiMessage): + transactional_id: str | None + transaction_timeout_ms: int + producer_id: int + producer_epoch: int + enable2_pc: bool + keep_prepared_txn: bool + def __init__( + self, + *args, + transactional_id: str | None = ..., + transaction_timeout_ms: int = ..., + producer_id: int = ..., + producer_epoch: int = ..., + enable2_pc: bool = ..., + keep_prepared_txn: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class InitProducerIdResponse(ApiMessage): + throttle_time_ms: int + error_code: int + producer_id: int + producer_epoch: int + ongoing_txn_producer_id: int + ongoing_txn_producer_epoch: int + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + producer_id: int = ..., + producer_epoch: int = ..., + ongoing_txn_producer_id: int = ..., + ongoing_txn_producer_epoch: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AddPartitionsToTxnRequest(ApiMessage): + class AddPartitionsToTxnTransaction(DataContainer): + class AddPartitionsToTxnTopic(DataContainer): + name: str + partitions: list[int] + def __init__( + self, *args, name: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + transactional_id: str + producer_id: int + producer_epoch: int + verify_only: bool + topics: list[AddPartitionsToTxnTopic] + def __init__( + self, + *args, + transactional_id: str = ..., + producer_id: int = ..., + producer_epoch: int = ..., + verify_only: bool = ..., + topics: list[AddPartitionsToTxnTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class AddPartitionsToTxnTopic(DataContainer): + name: str + partitions: list[int] + def __init__(self, *args, name: str = ..., partitions: list[int] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + transactions: list[AddPartitionsToTxnTransaction] + v3_and_below_transactional_id: str + v3_and_below_producer_id: int + v3_and_below_producer_epoch: int + v3_and_below_topics: list[AddPartitionsToTxnTopic] + def __init__( + self, + *args, + transactions: list[AddPartitionsToTxnTransaction] = ..., + v3_and_below_transactional_id: str = ..., + v3_and_below_producer_id: int = ..., + v3_and_below_producer_epoch: int = ..., + v3_and_below_topics: list[AddPartitionsToTxnTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AddPartitionsToTxnResponse(ApiMessage): + class AddPartitionsToTxnResult(DataContainer): + class AddPartitionsToTxnTopicResult(DataContainer): + class AddPartitionsToTxnPartitionResult(DataContainer): + partition_index: int + partition_error_code: int + def __init__( + self, *args, partition_index: int = ..., partition_error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + results_by_partition: list[AddPartitionsToTxnPartitionResult] + def __init__( + self, + *args, + name: str = ..., + results_by_partition: list[AddPartitionsToTxnPartitionResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + transactional_id: str + topic_results: list[AddPartitionsToTxnTopicResult] + def __init__( + self, + *args, + transactional_id: str = ..., + topic_results: list[AddPartitionsToTxnTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + class AddPartitionsToTxnTopicResult(DataContainer): + class AddPartitionsToTxnPartitionResult(DataContainer): + partition_index: int + partition_error_code: int + def __init__( + self, *args, partition_index: int = ..., partition_error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + results_by_partition: list[AddPartitionsToTxnPartitionResult] + def __init__( + self, + *args, + name: str = ..., + results_by_partition: list[AddPartitionsToTxnPartitionResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + error_code: int + results_by_transaction: list[AddPartitionsToTxnResult] + results_by_topic_v3_and_below: list[AddPartitionsToTxnTopicResult] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + results_by_transaction: list[AddPartitionsToTxnResult] = ..., + results_by_topic_v3_and_below: list[AddPartitionsToTxnTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AddOffsetsToTxnRequest(ApiMessage): + transactional_id: str + producer_id: int + producer_epoch: int + group_id: str + def __init__( + self, + *args, + transactional_id: str = ..., + producer_id: int = ..., + producer_epoch: int = ..., + group_id: str = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class AddOffsetsToTxnResponse(ApiMessage): + throttle_time_ms: int + error_code: int + def __init__( + self, *args, throttle_time_ms: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class EndTxnRequest(ApiMessage): + transactional_id: str + producer_id: int + producer_epoch: int + committed: bool + def __init__( + self, + *args, + transactional_id: str = ..., + producer_id: int = ..., + producer_epoch: int = ..., + committed: bool = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class EndTxnResponse(ApiMessage): + throttle_time_ms: int + error_code: int + producer_id: int + producer_epoch: int + def __init__( + self, + *args, + throttle_time_ms: int = ..., + error_code: int = ..., + producer_id: int = ..., + producer_epoch: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class TxnOffsetCommitRequest(ApiMessage): + class TxnOffsetCommitRequestTopic(DataContainer): + class TxnOffsetCommitRequestPartition(DataContainer): + partition_index: int + committed_offset: int + committed_leader_epoch: int + committed_metadata: str | None + def __init__( + self, + *args, + partition_index: int = ..., + committed_offset: int = ..., + committed_leader_epoch: int = ..., + committed_metadata: str | None = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[TxnOffsetCommitRequestPartition] + def __init__( + self, + *args, + name: str = ..., + partitions: list[TxnOffsetCommitRequestPartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + transactional_id: str + group_id: str + producer_id: int + producer_epoch: int + generation_id: int + member_id: str + group_instance_id: str | None + topics: list[TxnOffsetCommitRequestTopic] + def __init__( + self, + *args, + transactional_id: str = ..., + group_id: str = ..., + producer_id: int = ..., + producer_epoch: int = ..., + generation_id: int = ..., + member_id: str = ..., + group_instance_id: str | None = ..., + topics: list[TxnOffsetCommitRequestTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class TxnOffsetCommitResponse(ApiMessage): + class TxnOffsetCommitResponseTopic(DataContainer): + class TxnOffsetCommitResponsePartition(DataContainer): + partition_index: int + error_code: int + def __init__( + self, *args, partition_index: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[TxnOffsetCommitResponsePartition] + def __init__( + self, + *args, + name: str = ..., + partitions: list[TxnOffsetCommitResponsePartition] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + throttle_time_ms: int + topics: list[TxnOffsetCommitResponseTopic] + def __init__( + self, + *args, + throttle_time_ms: int = ..., + topics: list[TxnOffsetCommitResponseTopic] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class WriteTxnMarkersRequest(ApiMessage): + class WritableTxnMarker(DataContainer): + class WritableTxnMarkerTopic(DataContainer): + name: str + partition_indexes: list[int] + def __init__( + self, *args, name: str = ..., partition_indexes: list[int] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + producer_id: int + producer_epoch: int + transaction_result: bool + topics: list[WritableTxnMarkerTopic] + coordinator_epoch: int + transaction_version: int + def __init__( + self, + *args, + producer_id: int = ..., + producer_epoch: int = ..., + transaction_result: bool = ..., + topics: list[WritableTxnMarkerTopic] = ..., + coordinator_epoch: int = ..., + transaction_version: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + markers: list[WritableTxnMarker] + def __init__(self, *args, markers: list[WritableTxnMarker] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class WriteTxnMarkersResponse(ApiMessage): + class WritableTxnMarkerResult(DataContainer): + class WritableTxnMarkerTopicResult(DataContainer): + class WritableTxnMarkerPartitionResult(DataContainer): + partition_index: int + error_code: int + def __init__( + self, *args, partition_index: int = ..., error_code: int = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + name: str + partitions: list[WritableTxnMarkerPartitionResult] + def __init__( + self, + *args, + name: str = ..., + partitions: list[WritableTxnMarkerPartitionResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + producer_id: int + topics: list[WritableTxnMarkerTopicResult] + def __init__( + self, + *args, + producer_id: int = ..., + topics: list[WritableTxnMarkerTopicResult] = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + + markers: list[WritableTxnMarkerResult] + def __init__(self, *args, markers: list[WritableTxnMarkerResult] = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +__all__ = [ + "InitProducerIdRequest", + "InitProducerIdResponse", + "AddPartitionsToTxnRequest", + "AddPartitionsToTxnResponse", + "AddOffsetsToTxnRequest", + "AddOffsetsToTxnResponse", + "EndTxnRequest", + "EndTxnResponse", + "TxnOffsetCommitRequest", + "TxnOffsetCommitResponse", + "WriteTxnMarkersRequest", + "WriteTxnMarkersResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/sasl.pyi b/stubs/kafka-python/kafka/protocol/sasl.pyi new file mode 100644 index 000000000000..30095d81e622 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/sasl.pyi @@ -0,0 +1,126 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +from kafka.protocol.api_data import ApiData +from kafka.protocol.api_message import ApiMessage + +class SaslHandshakeRequest(ApiMessage): + mechanism: str + def __init__(self, *args, mechanism: str = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class SaslHandshakeResponse(ApiMessage): + error_code: int + mechanisms: list[str] + def __init__( + self, *args, error_code: int = ..., mechanisms: list[str] = ..., version: int | None = None, **kwargs + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class SaslAuthenticateRequest(ApiMessage): + auth_bytes: bytes | ApiData + def __init__(self, *args, auth_bytes: bytes | ApiData = ..., version: int | None = None, **kwargs) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class SaslAuthenticateResponse(ApiMessage): + error_code: int + error_message: str | None + auth_bytes: bytes | ApiData + session_lifetime_ms: int + def __init__( + self, + *args, + error_code: int = ..., + error_message: str | None = ..., + auth_bytes: bytes | ApiData = ..., + session_lifetime_ms: int = ..., + version: int | None = None, + **kwargs, + ) -> None: ... + @property + def version(self) -> int | None: ... + def to_dict(self, meta: bool = False, json: bool = True) -> dict[Incomplete, Incomplete]: ... + name: str + type: str + API_KEY: int + API_VERSION: int + valid_versions: tuple[int, int] + min_version: int + max_version: int + @property + def header(self): ... + @classmethod + def is_request(cls) -> bool: ... + def expect_response(self) -> bool: ... + def with_header(self, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class SaslBytesRequest: + API_VERSION: int + header: SaslBytesResponse | None + def __init__(self, data) -> None: ... + def with_header(self, correlation_id=None, **kwargs) -> None: ... + def encode(self, framed: bool = True, header: bool = True) -> bytes: ... + def expect_response(self): ... + +class SaslBytesResponse: + correlation_id: Incomplete + error_code: int + def __init__(self, correlation_id) -> None: ... + def parse_header(self, read_buffer) -> Self: ... + auth_bytes: Incomplete + def decode(self, read_buffer) -> Self: ... + def get_response_class(self) -> Self: ... + +__all__ = [ + "SaslHandshakeRequest", + "SaslHandshakeResponse", + "SaslAuthenticateRequest", + "SaslAuthenticateResponse", + "SaslBytesRequest", + "SaslBytesResponse", +] diff --git a/stubs/kafka-python/kafka/protocol/schemas/__init__.pyi b/stubs/kafka-python/kafka/protocol/schemas/__init__.pyi new file mode 100644 index 000000000000..46c73ea289e5 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/__init__.pyi @@ -0,0 +1,4 @@ +from .fields import * +from .load_json import load_json as load_json + +__all__ = ["BaseField", "SimpleField", "StructField", "ArrayField", "StructArrayField", "load_json"] diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/__init__.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/__init__.pyi new file mode 100644 index 000000000000..95100c188f63 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/__init__.pyi @@ -0,0 +1,7 @@ +from .array import ArrayField as ArrayField +from .base import BaseField as BaseField +from .simple import SimpleField as SimpleField +from .struct import StructField as StructField +from .struct_array import StructArrayField as StructArrayField + +__all__ = ["BaseField", "SimpleField", "StructField", "ArrayField", "StructArrayField"] diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/array.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/array.pyi new file mode 100644 index 000000000000..fe53ab246093 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/array.pyi @@ -0,0 +1,21 @@ +from typing_extensions import Self + +from .base import BaseField +from .simple import SimpleField + +class ArrayField(BaseField): + @classmethod + def parse_inner_type(cls, json) -> SimpleField | None: ... + @classmethod + def parse_array_type(cls, json) -> str | None: ... + @classmethod + def parse_json(cls, json) -> Self | None: ... + array_of: SimpleField + def __init__(self, json, array_of: SimpleField | None = None) -> None: ... + def is_array(self) -> bool: ... + def encode(self, items, version=None, compact: bool = False, tagged: bool = False) -> bytes: ... + def encode_into(self, items, out, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def emit_encode_into(self, ctx, val_expr, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def emit_decode_from(self, ctx, var_name, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def decode(self, data, version=None, compact: bool = False, tagged: bool = False): ... + def to_json(self, val): ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/base.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/base.pyi new file mode 100644 index 000000000000..972c93c6c3fc --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/base.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +class BaseField: + FIELD_TYPES: list[type[Incomplete]] + def __init_subclass__(cls, **kw) -> None: ... + @classmethod + def parse_json_fields(cls, json): ... + @classmethod + def parse_json(cls, json): ... + @classmethod + def underscore_name(cls, name: str) -> str: ... + @classmethod + def parse_versions(cls, versions: str) -> tuple[int, ...] | None: ... + name: str + def __init__(self, json) -> None: ... + @property + def type_str(self): ... + @property + def tag(self): ... + def is_array(self) -> bool: ... + def is_struct(self) -> bool: ... + def is_struct_array(self) -> bool: ... + def is_batchable(self) -> bool: ... + def has_data_class(self) -> bool: ... + def __call__(self, *args, **kwargs): ... + @property + def fields(self): ... + @property + def min_version(self): ... + @property + def max_version(self): ... + def for_version_q(self, version) -> bool: ... + def nullable_for_version_q(self, version) -> bool: ... + def tagged_field_q(self, version) -> bool: ... + @property + def default(self): ... + def encode(self, value, version=None, compact: bool = False, tagged: bool = False): ... + def decode(self, data, version=None, compact: bool = False, tagged: bool = False): ... + def __eq__(self, other) -> bool: ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/__init__.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/__init__.pyi new file mode 100644 index 000000000000..2597c4205dde --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/__init__.pyi @@ -0,0 +1,33 @@ +from .encode_buffer import EncodeBuffer as EncodeBuffer, EncodeBufferPool as EncodeBufferPool +from .tagged_fields import TaggedFields as TaggedFields +from .types import ( + UUID as UUID, + BitField as BitField, + Boolean as Boolean, + Bytes as Bytes, + Float64 as Float64, + Int8 as Int8, + Int16 as Int16, + Int32 as Int32, + Int64 as Int64, + String as String, + UnsignedInt16 as UnsignedInt16, + UnsignedVarInt32 as UnsignedVarInt32, +) + +__all__ = [ + "BitField", + "Boolean", + "UUID", + "Bytes", + "String", + "Int8", + "Int16", + "Int32", + "Int64", + "UnsignedInt16", + "UnsignedVarInt32", + "Float64", + "TaggedFields", + "EncodeBuffer", +] diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/encode_buffer.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/encode_buffer.pyi new file mode 100644 index 000000000000..17f9016f618b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/encode_buffer.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete, ReadableBuffer, Unused +from collections.abc import Iterable +from typing import SupportsIndex + +class EncodeBuffer: + __slots__ = ("buf", "pos") + buf: bytearray + pos: int + def __init__(self, size: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer = 65536) -> None: ... + def reset(self) -> None: ... + def ensure(self, needed: int) -> None: ... + def result(self) -> bytearray: ... + +class EncodeBufferPool: + @classmethod + def acquire(cls) -> _PooledBuffer: ... + +class _PooledBuffer: + __slots__ = ("_pool", "_buf") + def __init__(self, pool: EncodeBufferPool) -> None: ... + def __enter__(self) -> EncodeBuffer | Incomplete: ... + def __exit__(self, *exc: Unused): ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/tagged_fields.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/tagged_fields.pyi new file mode 100644 index 000000000000..0c3d23a8699b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/tagged_fields.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +class TaggedFields: + def __init__(self, fields) -> None: ... + def encode(self, item, version=None) -> bytes: ... + def encode_into(self, item, out, version=None) -> None: ... + def decode(self, data, version=None) -> dict[str, Incomplete]: ... + @classmethod + def decode_empty(cls, data) -> None: ... + @classmethod + def encode_empty(cls) -> bytes: ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/types.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/types.pyi new file mode 100644 index 000000000000..5302860eef6c --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/codecs/types.pyi @@ -0,0 +1,138 @@ +import uuid +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, Literal + +class FixedCodec: + fmt: ClassVar[str | None] + size: ClassVar[int | None] + batchable: ClassVar[bool] + def __init_subclass__(cls, **kw) -> None: ... + @classmethod + def encode(cls, value, compact: bool = False) -> bytes: ... + @classmethod + def encode_into(cls, out, value, compact: bool = False) -> None: ... + @classmethod + def decode(cls, data, compact: bool = False): ... + @classmethod + def decode_from(cls, data, pos) -> tuple[Incomplete, Incomplete]: ... + @classmethod + def emit_encode_into(cls, ctx, val_expr, indent, compact: bool = False) -> None: ... + @classmethod + def emit_decode_from(cls, ctx, var_name, indent, compact: bool = False) -> None: ... + +class Int8(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class Int16(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class UnsignedInt16(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class Int32(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class Int64(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class Float64(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class UUID: + fmt: ClassVar[str] + size: ClassVar[int] + ZERO_UUID: Final[uuid.UUID] + @classmethod + def encode(cls, value, compact: bool = False) -> bytes: ... + @classmethod + def encode_into(cls, out, value, compact: bool = False) -> None: ... + @classmethod + def emit_encode_into(cls, ctx, val_expr, indent, compact: bool = False) -> None: ... + @classmethod + def emit_decode_from(cls, ctx, var_name, indent, compact: bool = False) -> None: ... + @classmethod + def decode(cls, data, compact: bool = False) -> uuid.UUID | None: ... + +class String: + fmt: ClassVar[str | None] + size: ClassVar[Literal["variable"]] + encoding: str + def __init__(self, encoding: str = "utf-8") -> None: ... + def encode(self, value, compact: bool = False) -> bytes: ... + def encode_into(self, out, value, compact: bool = False) -> None: ... + def emit_encode_into(self, ctx, val_expr, indent, compact: bool = False) -> None: ... + def emit_decode_from(self, ctx, var_name, indent, compact: bool = False) -> None: ... + def decode(self, data, compact: bool = False): ... + +class Bytes: + fmt: ClassVar[str] + size: ClassVar[Literal["variable"]] + @classmethod + def encode(cls, value, compact: bool = False) -> bytes: ... + @classmethod + def encode_into(cls, out, value, compact: bool = False) -> None: ... + @classmethod + def emit_encode_into(cls, ctx, val_expr, indent, compact: bool = False) -> None: ... + @classmethod + def emit_decode_from(cls, ctx, var_name, indent, compact: bool = False) -> None: ... + @classmethod + def decode(cls, data, compact: bool = False): ... + +class Boolean(FixedCodec): + fmt: ClassVar[str] + size: ClassVar[int] + +class UnsignedVarInt32: + fmt: ClassVar[str] + size: ClassVar[Literal["variable"]] + @classmethod + def decode(cls, data, compact: bool = False): ... + @classmethod + def encode(cls, value, compact: bool = False) -> bytes: ... + @classmethod + def encode_into(cls, out, value) -> None: ... + @classmethod + def emit_encode_into(cls, ctx, val_expr, indent, compact: bool = False) -> None: ... + @classmethod + def emit_decode_from(cls, ctx, var_name, indent) -> None: ... + +class VarInt32: + fmt: ClassVar[str] + size: ClassVar[Literal["variable"]] + @classmethod + def decode(cls, data, compact: bool = False): ... + @classmethod + def encode(cls, value, compact: bool = False) -> bytes: ... + +class VarInt64: + fmt: ClassVar[str] + size: ClassVar[Literal["variable"]] + @classmethod + def decode(cls, data, compact: bool = False): ... + @classmethod + def encode(cls, value, compact: bool = False) -> bytes: ... + +class BitField: + fmt: ClassVar[str] + size: ClassVar[int] + @classmethod + def decode(cls, data, compact: bool = False) -> set[Incomplete] | None: ... + @classmethod + def encode(cls, vals, compact: bool = False) -> bytes: ... + @classmethod + def encode_into(cls, out, vals, compact: bool = False) -> None: ... + @classmethod + def emit_encode_into(cls, ctx, val_expr, indent, compact: bool = False) -> None: ... + @classmethod + def emit_decode_from(cls, ctx, var_name, indent, compact: bool = False) -> None: ... + @classmethod + def to_32_bit_field(cls, vals: Iterable[int]) -> int: ... + @classmethod + def from_32_bit_field(cls, value: int) -> set[int]: ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/codegen.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/codegen.pyi new file mode 100644 index 000000000000..7cb3f2afa5be --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/codegen.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +class CodegenContext: + lines: list[str] + globs: dict[str, Incomplete] + def __init__(self) -> None: ... + def next_var(self, prefix: str = "v") -> str: ... + def emit(self, indent, line) -> None: ... + def emit_reserve(self, indent, nbytes) -> None: ... + def source(self) -> None: ... + def print(self) -> None: ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/simple.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/simple.pyi new file mode 100644 index 000000000000..d2d151cbc74b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/simple.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +from .base import BaseField + +class SimpleField(BaseField): + TYPES: dict[str, type[Incomplete]] + @classmethod + def parse_json(cls, json) -> Self | None: ... + def __init__(self, json) -> None: ... + def is_batchable(self) -> bool: ... + def encode(self, value, version=None, compact: bool = False, tagged: bool = False) -> bytes: ... + def encode_into(self, value, out, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def emit_encode_into(self, ctx, val_expr, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def emit_decode_from(self, ctx, var_name, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def decode(self, data, version=None, compact: bool = False, tagged: bool = False): ... + def to_json(self, val): ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/struct.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/struct.pyi new file mode 100644 index 000000000000..74b97fd2a255 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/struct.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +from .base import BaseField +from .codegen import CodegenContext + +class StructField(BaseField): + @classmethod + def parse_json(cls, json) -> Self | None: ... + def __init__(self, json) -> None: ... + @property + def fields(self) -> dict[Incomplete, Incomplete]: ... + def is_struct(self): ... + def has_data_class(self) -> bool: ... + def set_data_class(self, data_class) -> None: ... + @property + def data_class(self): ... + def __call__(self, *args, **kw): ... + def tagged_fields(self, version): ... + def untagged_fields(self, version): ... + def encode(self, item, version=None, compact: bool = False, tagged: bool = False) -> bytes: ... + def emit_encode_into( + self, ctx, item_expr, indent, version=None, compact: bool = False, tagged: bool = False, tuple_access: bool = False + ) -> None: ... + def encode_into(self, item, out, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def encode_into__optimized_context(self, version, compact: bool = False, tagged: bool = False) -> CodegenContext: ... + def compiled_encode_into(self, version, compact: bool = False, tagged: bool = False): ... + def emit_decode_from(self, ctx, var_name, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def compiled_decode_from(self, version, compact: bool = False, tagged: bool = False, data_class=None): ... + def decode(self, data, version=None, compact: bool = False, tagged: bool = False, data_class=None): ... + def __len__(self) -> int: ... + def __eq__(self, other) -> bool: ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/fields/struct_array.pyi b/stubs/kafka-python/kafka/protocol/schemas/fields/struct_array.pyi new file mode 100644 index 000000000000..6227dc43647b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/fields/struct_array.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +from .array import ArrayField +from .struct import StructField + +class StructArrayField(ArrayField): + @classmethod + def parse_inner_type(cls, json) -> StructField | None: ... # type: ignore[override] + @classmethod + def parse_json(cls, json) -> Self | None: ... + map_key: Incomplete | None + def __init__(self, json, array_of=None) -> None: ... + @property + def type_str(self): ... + def is_struct_array(self): ... + @property + def fields(self): ... + def tagged_fields(self, version): ... + def untagged_fields(self, version): ... + def has_data_class(self): ... + def set_data_class(self, data_class): ... + @property + def data_class(self): ... + def __call__(self, *args, **kw): ... + def emit_decode_from(self, ctx, var_name, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... + def emit_encode_into(self, ctx, val_expr, indent, version=None, compact: bool = False, tagged: bool = False) -> None: ... diff --git a/stubs/kafka-python/kafka/protocol/schemas/load_json.pyi b/stubs/kafka-python/kafka/protocol/schemas/load_json.pyi new file mode 100644 index 000000000000..12140ce7a283 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/schemas/load_json.pyi @@ -0,0 +1,3 @@ +from types import ModuleType + +def load_json(msg_type: str, package: str | ModuleType | None = None): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mssql/provision.pyi b/stubs/kafka-python/kafka/protocol/schemas/resources/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/dialects/mssql/provision.pyi rename to stubs/kafka-python/kafka/protocol/schemas/resources/__init__.pyi diff --git a/stubs/kafka-python/kafka/record/__init__.pyi b/stubs/kafka-python/kafka/record/__init__.pyi new file mode 100644 index 000000000000..7ac09dc7e0d8 --- /dev/null +++ b/stubs/kafka-python/kafka/record/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.record.memory_records import MemoryRecords as MemoryRecords, MemoryRecordsBuilder as MemoryRecordsBuilder + +__all__ = ["MemoryRecords", "MemoryRecordsBuilder"] diff --git a/stubs/kafka-python/kafka/record/_crc32c.pyi b/stubs/kafka-python/kafka/record/_crc32c.pyi new file mode 100644 index 000000000000..3337132fe642 --- /dev/null +++ b/stubs/kafka-python/kafka/record/_crc32c.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +CRC_TABLE: Incomplete +CRC_INIT: int + +def crc_update(crc, data): ... +def crc_finalize(crc): ... +def crc(data): ... diff --git a/stubs/kafka-python/kafka/record/abc.pyi b/stubs/kafka-python/kafka/record/abc.pyi new file mode 100644 index 000000000000..ce0922d9bfd5 --- /dev/null +++ b/stubs/kafka-python/kafka/record/abc.pyi @@ -0,0 +1,64 @@ +import abc + +class ABCRecord(metaclass=abc.ABCMeta): + __slots__ = () + @property + @abc.abstractmethod + def size_in_bytes(self): ... + @property + @abc.abstractmethod + def offset(self): ... + @property + @abc.abstractmethod + def timestamp(self): ... + @property + @abc.abstractmethod + def timestamp_type(self): ... + @property + @abc.abstractmethod + def key(self): ... + @property + @abc.abstractmethod + def value(self): ... + @property + @abc.abstractmethod + def checksum(self): ... + @abc.abstractmethod + def validate_crc(self): ... + @property + @abc.abstractmethod + def headers(self): ... + +class ABCRecordBatchBuilder(metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def append(self, offset, timestamp, key, value, headers=None): ... + @abc.abstractmethod + def size_in_bytes(self, offset, timestamp, key, value, headers): ... + @abc.abstractmethod + def build(self): ... + +class ABCRecordBatch(metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __iter__(self): ... + @property + @abc.abstractmethod + def base_offset(self): ... + @property + @abc.abstractmethod + def size_in_bytes(self): ... + @property + @abc.abstractmethod + def magic(self): ... + +class ABCRecords(metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __init__(self, buffer): ... + @abc.abstractmethod + def size_in_bytes(self): ... + @abc.abstractmethod + def next_batch(self): ... + @abc.abstractmethod + def has_next(self): ... diff --git a/stubs/kafka-python/kafka/record/default_records.pyi b/stubs/kafka-python/kafka/record/default_records.pyi new file mode 100644 index 000000000000..a9347abc4ca5 --- /dev/null +++ b/stubs/kafka-python/kafka/record/default_records.pyi @@ -0,0 +1,176 @@ +from _typeshed import Incomplete + +from kafka.record.abc import ABCRecord, ABCRecordBatch, ABCRecordBatchBuilder + +class DefaultRecordBase: + __slots__ = () + HEADER_STRUCT: Incomplete + ATTRIBUTES_OFFSET: Incomplete + CRC_OFFSET: Incomplete + AFTER_LEN_OFFSET: Incomplete + CODEC_MASK: int + CODEC_NONE: int + CODEC_GZIP: int + CODEC_SNAPPY: int + CODEC_LZ4: int + CODEC_ZSTD: int + TIMESTAMP_TYPE_MASK: int + TRANSACTIONAL_MASK: int + CONTROL_MASK: int + LOG_APPEND_TIME: int + CREATE_TIME: int + NO_PRODUCER_ID: int + NO_SEQUENCE: int + MAX_INT: int + +class DefaultRecordBatch(DefaultRecordBase, ABCRecordBatch): + __slots__ = ("_buffer", "_header_data", "_pos", "_num_records", "_next_record_index", "_decompressed") + def __init__(self, buffer) -> None: ... + @property + def base_offset(self): ... + @property + def size_in_bytes(self): ... + @property + def leader_epoch(self): ... + @property + def magic(self): ... + @property + def crc(self): ... + @property + def attributes(self): ... + @property + def last_offset_delta(self): ... + @property + def last_offset(self): ... + @property + def next_offset(self): ... + @property + def compression_type(self): ... + @property + def timestamp_type(self): ... + @property + def is_transactional(self): ... + @property + def is_control_batch(self): ... + @property + def first_timestamp(self): ... + @property + def max_timestamp(self): ... + @property + def producer_id(self): ... + def has_producer_id(self): ... + @property + def producer_epoch(self): ... + @property + def base_sequence(self): ... + @property + def has_sequence(self): ... + @property + def last_sequence(self): ... + @property + def records_count(self): ... + def __iter__(self): ... + def __next__(self): ... + next = __next__ + def validate_crc(self): ... + +class DefaultRecord(ABCRecord): + __slots__ = ("_size_in_bytes", "_offset", "_timestamp", "_timestamp_type", "_key", "_value", "_headers") + def __init__(self, size_in_bytes, offset, timestamp, timestamp_type, key, value, headers) -> None: ... + @property + def size_in_bytes(self): ... + @property + def offset(self): ... + @property + def timestamp(self): ... + @property + def timestamp_type(self): ... + @property + def key(self): ... + @property + def value(self): ... + @property + def headers(self): ... + @property + def checksum(self) -> None: ... + def validate_crc(self): ... + +class ControlRecord(DefaultRecord): + __slots__ = ("_size_in_bytes", "_offset", "_timestamp", "_timestamp_type", "_key", "_value", "_headers", "_version", "_type") + KEY_STRUCT: Incomplete + def __init__(self, size_in_bytes, offset, timestamp, timestamp_type, key, value, headers) -> None: ... + @property + def version(self): ... + @property + def type(self): ... + @property + def abort(self): ... + @property + def commit(self): ... + +class DefaultRecordBatchBuilder(DefaultRecordBase, ABCRecordBatchBuilder): + __slots__ = ( + "_magic", + "_compression_type", + "_batch_size", + "_is_transactional", + "_producer_id", + "_producer_epoch", + "_base_sequence", + "_first_timestamp", + "_max_timestamp", + "_last_offset", + "_num_records", + "_buffer", + ) + MAX_RECORD_OVERHEAD: int + def __init__( + self, magic, compression_type, is_transactional, producer_id, producer_epoch, base_sequence, batch_size + ) -> None: ... + def set_producer_state(self, producer_id, producer_epoch, base_sequence, is_transactional) -> None: ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + @property + def base_sequence(self): ... + def append( # type: ignore[override] + self, + offset, + timestamp, + key, + value, + headers, + encode_varint=..., + size_of_varint=..., + get_type=..., + type_int=..., + time_time=..., + byte_like=..., + bytearray_type=..., + len_func=..., + zero_len_varint: int = 1, + ): ... + def write_header(self, use_compression_type: bool = True) -> None: ... + def build(self): ... + def size(self): ... + @classmethod + def header_size_in_bytes(cls): ... + @classmethod + def size_in_bytes(cls, offset_delta, timestamp_delta, key, value, headers): ... + @classmethod + def size_of(cls, key, value, headers): ... + @classmethod + def estimate_size_in_bytes(cls, key, value, headers): ... + +class DefaultRecordMetadata: + __slots__ = ("_size", "_timestamp", "_offset") + def __init__(self, offset, size, timestamp) -> None: ... + @property + def offset(self): ... + @property + def crc(self) -> None: ... + @property + def size(self): ... + @property + def timestamp(self): ... diff --git a/stubs/kafka-python/kafka/record/legacy_records.pyi b/stubs/kafka-python/kafka/record/legacy_records.pyi new file mode 100644 index 000000000000..cd4f5495120f --- /dev/null +++ b/stubs/kafka-python/kafka/record/legacy_records.pyi @@ -0,0 +1,91 @@ +from _typeshed import Incomplete + +from kafka.record.abc import ABCRecord, ABCRecordBatch, ABCRecordBatchBuilder + +class LegacyRecordBase: + __slots__ = () + HEADER_STRUCT_V0: Incomplete + HEADER_STRUCT_V1: Incomplete + LOG_OVERHEAD: Incomplete + CRC_OFFSET: Incomplete + MAGIC_OFFSET: Incomplete + RECORD_OVERHEAD_V0: Incomplete + RECORD_OVERHEAD_V1: Incomplete + KEY_OFFSET_V0: Incomplete + KEY_OFFSET_V1: Incomplete + KEY_LENGTH: Incomplete + VALUE_LENGTH: Incomplete + CODEC_MASK: int + CODEC_NONE: int + CODEC_GZIP: int + CODEC_SNAPPY: int + CODEC_LZ4: int + TIMESTAMP_TYPE_MASK: int + LOG_APPEND_TIME: int + CREATE_TIME: int + NO_TIMESTAMP: int + +class LegacyRecordBatch(ABCRecordBatch, LegacyRecordBase): + __slots__ = ("_buffer", "_magic", "_offset", "_length", "_crc", "_timestamp", "_attributes", "_decompressed") + def __init__(self, buffer, magic) -> None: ... + @property + def base_offset(self): ... + @property + def size_in_bytes(self): ... + @property + def timestamp_type(self): ... + @property + def compression_type(self): ... + @property + def magic(self): ... + def validate_crc(self): ... + def __iter__(self): ... + +class LegacyRecord(ABCRecord): + __slots__ = ("_magic", "_offset", "_timestamp", "_timestamp_type", "_key", "_value", "_crc", "_crc_bytes") + def __init__(self, magic, offset, timestamp, timestamp_type, key, value, crc, crc_bytes) -> None: ... + @property + def magic(self): ... + @property + def offset(self): ... + @property + def timestamp(self): ... + @property + def timestamp_type(self): ... + @property + def key(self): ... + @property + def value(self): ... + @property + def headers(self): ... + @property + def checksum(self): ... + def validate_crc(self): ... + @property + def size_in_bytes(self): ... + +class LegacyRecordBatchBuilder(ABCRecordBatchBuilder, LegacyRecordBase): + __slots__ = ("_magic", "_compression_type", "_batch_size", "_buffer") + def __init__(self, magic, compression_type, batch_size) -> None: ... + def append(self, offset, timestamp, key, value, headers=None): ... + def build(self): ... + def size(self): ... + def size_in_bytes(self, offset, timestamp, key, value, headers=None): ... + @classmethod + def record_size(cls, magic, key, value): ... + @classmethod + def record_overhead(cls, magic): ... + @classmethod + def estimate_size_in_bytes(cls, magic, compression_type, key, value): ... + +class LegacyRecordMetadata: + __slots__ = ("_crc", "_size", "_timestamp", "_offset") + def __init__(self, offset, crc, size, timestamp) -> None: ... + @property + def offset(self): ... + @property + def crc(self): ... + @property + def size(self): ... + @property + def timestamp(self): ... diff --git a/stubs/kafka-python/kafka/record/memory_records.pyi b/stubs/kafka-python/kafka/record/memory_records.pyi new file mode 100644 index 000000000000..d2be8259fa71 --- /dev/null +++ b/stubs/kafka-python/kafka/record/memory_records.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete + +from kafka.record.abc import ABCRecords + +class MemoryRecords(ABCRecords): + __slots__ = ("_buffer", "_pos", "_next_slice", "_remaining_bytes") + LENGTH_OFFSET: Incomplete + LOG_OVERHEAD: Incomplete + MAGIC_OFFSET: Incomplete + MIN_SLICE: Incomplete + def __init__(self, bytes_data) -> None: ... + def size_in_bytes(self): ... + def valid_bytes(self): ... + def has_next(self): ... + def next_batch(self, _min_slice=26, _magic_offset=16): ... + def __iter__(self): ... + def __next__(self): ... + next = __next__ + +class MemoryRecordsBuilder: + __slots__ = ( + "_builder", + "_batch_size", + "_buffer", + "_next_offset", + "_closed", + "_magic", + "_bytes_written", + "_producer_id", + "_producer_epoch", + "_base_sequence", + ) + def __init__( + self, + magic, + compression_type, + batch_size, + offset: int = 0, + transactional: bool = False, + producer_id: int = -1, + producer_epoch: int = -1, + base_sequence: int = -1, + ) -> None: ... + def skip(self, offsets_to_skip) -> None: ... + def append(self, timestamp, key, value, headers=None): ... + def set_producer_state(self, producer_id, producer_epoch, base_sequence, is_transactional) -> None: ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + @property + def base_sequence(self): ... + def records(self): ... + def close(self) -> None: ... + def size_in_bytes(self): ... + def compression_rate(self): ... + def is_full(self): ... + def next_offset(self): ... + def buffer(self): ... diff --git a/stubs/kafka-python/kafka/record/util.pyi b/stubs/kafka-python/kafka/record/util.pyi new file mode 100644 index 000000000000..fa94937bc8f8 --- /dev/null +++ b/stubs/kafka-python/kafka/record/util.pyi @@ -0,0 +1,5 @@ +def encode_varint(value, write): ... +def size_of_varint(value): ... +def decode_varint(buffer, pos: int = 0): ... +def calc_crc32c(memview, _crc32c=...): ... +def calc_crc32(memview): ... diff --git a/stubs/kafka-python/kafka/serializer/__init__.pyi b/stubs/kafka-python/kafka/serializer/__init__.pyi new file mode 100644 index 000000000000..fe3588013b49 --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/__init__.pyi @@ -0,0 +1,4 @@ +from .abstract import Deserializer as Deserializer, Serializer as Serializer +from .default import DefaultSerializer as DefaultSerializer +from .json import JsonSerializer as JsonSerializer +from .wrapper import DeserializeWrapper as DeserializeWrapper, SerializeWrapper as SerializeWrapper diff --git a/stubs/kafka-python/kafka/serializer/abstract.pyi b/stubs/kafka-python/kafka/serializer/abstract.pyi new file mode 100644 index 000000000000..d8b45d1f4886 --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/abstract.pyi @@ -0,0 +1,11 @@ +import abc + +class Serializer(metaclass=abc.ABCMeta): + @abc.abstractmethod + def serialize(self, topic: str, headers: list[tuple[str, bytes]], data): ... + def close(self) -> None: ... + +class Deserializer(metaclass=abc.ABCMeta): + @abc.abstractmethod + def deserialize(self, topic: str, headers: list[tuple[str, bytes]], data: bytes | None): ... + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/serializer/default.pyi b/stubs/kafka-python/kafka/serializer/default.pyi new file mode 100644 index 000000000000..104f9957e278 --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/default.pyi @@ -0,0 +1,7 @@ +from .abstract import Deserializer, Serializer + +class DefaultSerializer(Serializer, Deserializer): + encoding: str + def __init__(self, encoding: str = "utf-8") -> None: ... + def serialize(self, topic: str, headers: list[tuple[str, bytes]], data: str | bytes | bytearray | memoryview | None): ... + def deserialize(self, topic: str, headers: list[tuple[str, bytes]], data: bytes | None) -> str | None: ... diff --git a/stubs/kafka-python/kafka/serializer/json.pyi b/stubs/kafka-python/kafka/serializer/json.pyi new file mode 100644 index 000000000000..f542de83c560 --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/json.pyi @@ -0,0 +1,5 @@ +from .default import DefaultSerializer + +class JsonSerializer(DefaultSerializer): + def serialize(self, topic: str, headers: list[tuple[str, bytes]], data): ... + def deserialize(self, topic: str, headers: list[tuple[str, bytes]], data): ... diff --git a/stubs/kafka-python/kafka/serializer/wrapper.pyi b/stubs/kafka-python/kafka/serializer/wrapper.pyi new file mode 100644 index 000000000000..705f605a5b70 --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/wrapper.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from .abstract import Deserializer, Serializer + +class DeserializeWrapper(Deserializer): + fn: Incomplete + def __init__(self, fn) -> None: ... + def deserialize(self, topic: str, headers: list[tuple[str, bytes]], data): ... + +class SerializeWrapper(Serializer): + fn: Incomplete + def __init__(self, fn) -> None: ... + def serialize(self, topic: str, headers: list[tuple[str, bytes]], data): ... diff --git a/stubs/kafka-python/kafka/structs.pyi b/stubs/kafka-python/kafka/structs.pyi new file mode 100644 index 000000000000..00e8a2dae59a --- /dev/null +++ b/stubs/kafka-python/kafka/structs.pyi @@ -0,0 +1,32 @@ +from typing import Final, Literal, NamedTuple + +class TopicPartition(NamedTuple): + topic: str + partition: int + +class TopicPartitionReplica(NamedTuple): + topic: str + partition: int + broker_id: int + +class OffsetAndMetadata(NamedTuple): + offset: int | None = None + metadata: str = "" + leader_epoch: int = -1 + +class OffsetAndTimestamp(NamedTuple): + offset: int + timestamp: int + leader_epoch: int + +class MemberState: + UNJOINED: Final = "" + REBALANCING: Final = "" + STABLE: Final = "" + +class ConsumerGroupMetadata(NamedTuple): + group_id: str | None = None + generation_id: int = -1 + member_id: str = "" + group_instance_id: str | None = None + state: Literal["", "", ""] = ... # Please, keep in sync with MemberState diff --git a/stubs/kafka-python/kafka/util.pyi b/stubs/kafka-python/kafka/util.pyi new file mode 100644 index 000000000000..83880d3b228e --- /dev/null +++ b/stubs/kafka-python/kafka/util.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +class Timer: + __slots__ = ("_start_at", "_expire_at", "_timeout_ms", "_error_message") + def __init__(self, timeout_ms, error_message=None, start_at=None) -> None: ... + @property + def expired(self): ... + @property + def timeout_ms(self): ... + @property + def timeout_secs(self) -> float | None: ... + @property + def elapsed_ms(self): ... + def maybe_raise(self) -> None: ... + +TOPIC_MAX_LENGTH: int +TOPIC_LEGAL_CHARS: Incomplete + +def ensure_valid_topic_name(topic) -> None: ... + +class WeakMethod: + target: Incomplete + method: Incomplete + def __init__(self, object_dot_method) -> None: ... + def __call__(self, *args, **kwargs): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class Dict(dict[Incomplete, Incomplete]): ... + +def synchronized(func: Callable[_P, _T]) -> Callable[_P, _T]: ... + +class classproperty: + f: Incomplete + def __init__(self, f): ... + def __get__(self, obj, owner): ... + +class EnumHelper: + @classmethod + def build_from(cls, val): ... + @classmethod + def value_for(cls, val): ... diff --git a/stubs/kafka-python/kafka/version.pyi b/stubs/kafka-python/kafka/version.pyi new file mode 100644 index 000000000000..bda5b5a7f4cc --- /dev/null +++ b/stubs/kafka-python/kafka/version.pyi @@ -0,0 +1 @@ +__version__: str diff --git a/stubs/keyboard/@tests/stubtest_allowlist.txt b/stubs/keyboard/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c508422424b0 --- /dev/null +++ b/stubs/keyboard/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# scan_code *should* never be None in real use. This is also according to docs. +keyboard._keyboard_event.KeyboardEvent.scan_code +# TODO: Should this be allowlisted? +keyboard.__main__ + +keyboard._canonical_names.basestring +keyboard._keyboard_event.basestring diff --git a/stubs/keyboard/@tests/stubtest_allowlist_darwin.txt b/stubs/keyboard/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..cdf3ec0e6861 --- /dev/null +++ b/stubs/keyboard/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +# Defaults don't align with possible values +keyboard.mouse.on_button +keyboard.mouse.wait diff --git a/stubs/keyboard/@tests/stubtest_allowlist_linux.txt b/stubs/keyboard/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..cdf3ec0e6861 --- /dev/null +++ b/stubs/keyboard/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +# Defaults don't align with possible values +keyboard.mouse.on_button +keyboard.mouse.wait diff --git a/stubs/keyboard/METADATA.toml b/stubs/keyboard/METADATA.toml new file mode 100644 index 000000000000..cda767908896 --- /dev/null +++ b/stubs/keyboard/METADATA.toml @@ -0,0 +1,9 @@ +version = "0.13.*" +upstream-repository = "https://github.com/boppreh/keyboard" + +# [tool.stubtest] +# While the stubs slightly differ on Windows vs Linux. +# It's only by possible mouse buttons and event literal types. +# As well as returning a tuple of int/long from keyboard.mouse.get_position +# The "mouse" module is obsoleted by the "mouse" package. +# ci-platforms = ["linux"] diff --git a/stubs/keyboard/keyboard/__init__.pyi b/stubs/keyboard/keyboard/__init__.pyi new file mode 100644 index 000000000000..a858acfa7658 --- /dev/null +++ b/stubs/keyboard/keyboard/__init__.pyi @@ -0,0 +1,113 @@ +from collections.abc import Callable, Generator, Iterable, Sequence +from queue import Queue +from threading import Event as _UninterruptibleEvent +from typing import TypeAlias + +from ._canonical_names import all_modifiers as all_modifiers, sided_modifiers as sided_modifiers +from ._keyboard_event import KEY_DOWN as KEY_DOWN, KEY_UP as KEY_UP, KeyboardEvent as KeyboardEvent + +_Key: TypeAlias = int | str +_ScanCodeList: TypeAlias = list[int] | tuple[int, ...] +_ParseableHotkey: TypeAlias = _Key | list[int | _ScanCodeList] | tuple[int | _ScanCodeList, ...] +_Callback: TypeAlias = Callable[[KeyboardEvent], bool | None] | Callable[[], bool | None] +# mypy doesn't support PEP 646's TypeVarTuple yet: https://github.com/python/mypy/issues/12280 +# _Ts = TypeVarTuple("_Ts") +_Ts: TypeAlias = tuple[object, ...] + +version: str + +class _Event(_UninterruptibleEvent): + def wait(self) -> None: ... # type: ignore[override] # Actual implementation + +def is_modifier(key: _Key | None) -> bool: ... +def key_to_scan_codes(key: _ParseableHotkey, error_if_missing: bool = True) -> tuple[int, ...]: ... +def parse_hotkey(hotkey: _ParseableHotkey) -> tuple[tuple[tuple[int, ...], ...], ...]: ... +def send(hotkey: _ParseableHotkey, do_press: bool = True, do_release: bool = True) -> None: ... + +press_and_release = send + +def press(hotkey: _ParseableHotkey) -> None: ... +def release(hotkey: _ParseableHotkey) -> None: ... + +# is_pressed cannot check multi-step hotkeys, so not using _ParseableHotkey + +def is_pressed(hotkey: _Key | _ScanCodeList) -> bool: ... +def call_later(fn: Callable[..., None], args: _Ts = (), delay: float = 0.001) -> None: ... +def hook(callback: _Callback, suppress: bool = False, on_remove: Callable[[], None] = ...) -> Callable[[], None]: ... +def on_press(callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def on_release(callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def hook_key(key: _ParseableHotkey, callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def on_press_key(key: _ParseableHotkey, callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def on_release_key(key: _ParseableHotkey, callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def unhook(remove: _Callback) -> None: ... + +unhook_key = unhook + +def unhook_all() -> None: ... +def block_key(key: _ParseableHotkey) -> Callable[[], None]: ... + +unblock_key = unhook_key + +def remap_key(src: _ParseableHotkey, dst: _ParseableHotkey) -> Callable[[], None]: ... + +unremap_key = unhook_key + +def parse_hotkey_combinations(hotkey: _ParseableHotkey) -> tuple[tuple[tuple[int, ...], ...], ...]: ... +def add_hotkey( + hotkey: _ParseableHotkey, + callback: Callable[..., bool | None], + args: _Ts = (), + suppress: bool = False, + timeout: float = 1, + trigger_on_release: bool = False, +) -> Callable[[], None]: ... + +register_hotkey = add_hotkey + +def remove_hotkey(hotkey_or_callback: _ParseableHotkey | _Callback) -> None: ... + +unregister_hotkey = remove_hotkey +clear_hotkey = remove_hotkey + +def unhook_all_hotkeys() -> None: ... + +unregister_all_hotkeys = unhook_all_hotkeys +remove_all_hotkeys = unhook_all_hotkeys +clear_all_hotkeys = unhook_all_hotkeys + +def remap_hotkey( + src: _ParseableHotkey, dst: _ParseableHotkey, suppress: bool = True, trigger_on_release: bool = False +) -> Callable[[], None]: ... + +unremap_hotkey = remove_hotkey + +def stash_state() -> list[int]: ... +def restore_state(scan_codes: Iterable[int]) -> None: ... +def restore_modifiers(scan_codes: Iterable[int]) -> None: ... +def write(text: str, delay: float = 0, restore_state_after: bool = True, exact: bool | None = None) -> None: ... +def wait(hotkey: _ParseableHotkey | None = None, suppress: bool = False, trigger_on_release: bool = False) -> None: ... +def get_hotkey_name(names: Iterable[str] | None = None) -> str: ... +def read_event(suppress: bool = False) -> KeyboardEvent: ... +def read_key(suppress: bool = False) -> _Key: ... +def read_hotkey(suppress: bool = True) -> str: ... +def get_typed_strings(events: Iterable[KeyboardEvent], allow_backspace: bool = True) -> Generator[str]: ... +def start_recording( + recorded_events_queue: Queue[KeyboardEvent] | None = None, +) -> tuple[Queue[KeyboardEvent], Callable[[], None]]: ... +def stop_recording() -> list[KeyboardEvent]: ... +def record(until: str = "escape", suppress: bool = False, trigger_on_release: bool = False) -> list[KeyboardEvent]: ... +def play(events: Iterable[KeyboardEvent], speed_factor: float = 1.0) -> None: ... + +replay = play + +def add_word_listener( + word: str, callback: _Callback, triggers: Sequence[str] = ["space"], match_suffix: bool = False, timeout: float = 2 +) -> Callable[[], None]: ... +def remove_word_listener(word_or_handler: str | _Callback) -> None: ... +def add_abbreviation( + source_text: str, replacement_text: str, match_suffix: bool = False, timeout: float = 2 +) -> Callable[[], None]: ... + +register_word_listener = add_word_listener +register_abbreviation = add_abbreviation +remove_abbreviation = remove_word_listener diff --git a/stubs/keyboard/keyboard/_canonical_names.pyi b/stubs/keyboard/keyboard/_canonical_names.pyi new file mode 100644 index 000000000000..8a0c3a007643 --- /dev/null +++ b/stubs/keyboard/keyboard/_canonical_names.pyi @@ -0,0 +1,5 @@ +canonical_names: dict[str, str] +sided_modifiers: set[str] +all_modifiers: set[str] + +def normalize_name(name: str) -> str: ... diff --git a/stubs/keyboard/keyboard/_generic.pyi b/stubs/keyboard/keyboard/_generic.pyi new file mode 100644 index 000000000000..a1784b3d89a8 --- /dev/null +++ b/stubs/keyboard/keyboard/_generic.pyi @@ -0,0 +1,23 @@ +from collections.abc import Callable +from queue import Queue +from threading import Lock, Thread +from typing import ClassVar, Literal, TypeAlias + +from ._keyboard_event import KeyboardEvent +from ._mouse_event import _MouseEvent + +_Event: TypeAlias = KeyboardEvent | _MouseEvent + +class GenericListener: + lock: ClassVar[Lock] + handlers: list[Callable[[_Event], bool | None]] + listening: bool + queue: Queue[_Event] + listening_thread: Thread | None + processing_thread: Thread | None + def invoke_handlers(self, event: _Event) -> Literal[1] | None: ... + def start_if_necessary(self) -> None: ... + def pre_process_event(self, event: _Event) -> None: ... + def process(self) -> None: ... + def add_handler(self, handler: Callable[[_Event], bool | None]) -> None: ... + def remove_handler(self, handler: Callable[[_Event], bool | None]) -> None: ... diff --git a/stubs/keyboard/keyboard/_keyboard_event.pyi b/stubs/keyboard/keyboard/_keyboard_event.pyi new file mode 100644 index 000000000000..94746c56abba --- /dev/null +++ b/stubs/keyboard/keyboard/_keyboard_event.pyi @@ -0,0 +1,28 @@ +from typing import Literal + +from ._canonical_names import canonical_names as canonical_names, normalize_name as normalize_name + +KEY_DOWN: Literal["down"] +KEY_UP: Literal["up"] + +class KeyboardEvent: + event_type: Literal["down", "up"] | None + scan_code: int + name: str | None + time: float | None + device: str | None + modifiers: tuple[str, ...] | None + is_keypad: bool | None + + def __init__( + self, + event_type: Literal["down", "up"] | None, + scan_code: int, + name: str | None = None, + time: float | None = None, + device: str | None = None, + modifiers: tuple[str, ...] | None = None, + is_keypad: bool | None = None, + ) -> None: ... + def to_json(self, ensure_ascii: bool = False) -> str: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/keyboard/keyboard/_mouse_event.pyi b/stubs/keyboard/keyboard/_mouse_event.pyi new file mode 100644 index 000000000000..e9e95b80e112 --- /dev/null +++ b/stubs/keyboard/keyboard/_mouse_event.pyi @@ -0,0 +1,42 @@ +import sys +from typing import Literal, NamedTuple, TypeAlias + +_MouseEvent: TypeAlias = ButtonEvent | WheelEvent | MoveEvent # noqa: Y047 # Used outside + +LEFT: Literal["left"] +RIGHT: Literal["right"] +MIDDLE: Literal["middle"] +X: Literal["x"] +X2: Literal["x2"] + +UP: Literal["up"] +DOWN: Literal["down"] +DOUBLE: Literal["double"] +WHEEL: Literal["wheel"] + +VERTICAL: Literal["vertical"] +HORIZONTAL: Literal["horizontal"] + +if sys.platform == "linux" or sys.platform == "win32": + _MouseButton: TypeAlias = Literal["left", "right", "middle", "x", "x2"] +else: + _MouseButton: TypeAlias = Literal["left", "right", "middle"] + +if sys.platform == "win32": + _MouseEventType: TypeAlias = Literal["up", "down", "double", "wheel"] +else: + _MouseEventType: TypeAlias = Literal["up", "down"] + +class ButtonEvent(NamedTuple): + event_type: _MouseEventType + button: _MouseButton + time: float + +class WheelEvent(NamedTuple): + delta: int + time: float + +class MoveEvent(NamedTuple): + x: int + y: int + time: float diff --git a/stubs/keyboard/keyboard/mouse.pyi b/stubs/keyboard/keyboard/mouse.pyi new file mode 100644 index 000000000000..6105f85d59a9 --- /dev/null +++ b/stubs/keyboard/keyboard/mouse.pyi @@ -0,0 +1,83 @@ +import sys +from collections.abc import Callable, Iterable +from ctypes import c_long +from typing import Literal, SupportsInt, TypeAlias, TypeVar + +from ._generic import GenericListener as _GenericListener +from ._mouse_event import ( + DOUBLE as DOUBLE, + DOWN as DOWN, + LEFT as LEFT, + MIDDLE as MIDDLE, + RIGHT as RIGHT, + UP as UP, + X2 as X2, + ButtonEvent as ButtonEvent, + MoveEvent as MoveEvent, + WheelEvent as WheelEvent, + X as X, + _MouseButton, + _MouseEvent, + _MouseEventType, +) + +# mypy doesn't support PEP 646's TypeVarTuple yet: https://github.com/python/mypy/issues/12280 +# _Ts = TypeVarTuple("_Ts") +_Ts: TypeAlias = tuple[object, ...] +_Callback: TypeAlias = Callable[[_MouseEvent], bool | None] +_C = TypeVar("_C", bound=_Callback) + +class _MouseListener(_GenericListener): + def init(self) -> None: ... + def pre_process_event( # type: ignore[override] # Mouse specific events and return + self, event: _MouseEvent + ) -> Literal[True]: ... + def listen(self) -> None: ... + +def is_pressed(button: _MouseButton = "left") -> bool: ... +def press(button: _MouseButton = "left") -> None: ... +def release(button: _MouseButton = "left") -> None: ... +def click(button: _MouseButton = "left") -> None: ... +def double_click(button: _MouseButton = "left") -> None: ... +def right_click() -> None: ... +def wheel(delta: int = 1) -> None: ... +def move(x: SupportsInt, y: SupportsInt, absolute: bool = True, duration: float = 0) -> None: ... +def drag(start_x: int, start_y: int, end_x: int, end_y: int, absolute: bool = True, duration: float = 0) -> None: ... +def on_button( + callback: Callable[..., None], + args: _Ts = (), + # Omitting default: Darwin has no x and x2 + buttons: list[_MouseButton] | tuple[_MouseButton, ...] | _MouseButton = ..., + # Omitting default: Darwin and Linux don't have "double", yet the defaults includes it + types: list[_MouseEventType] | tuple[_MouseEventType, ...] | _MouseEventType = ..., +) -> _Callback: ... +def on_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def on_double_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def on_right_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def on_middle_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def wait( + button: _MouseButton = "left", + # Omitting default: Darwin and Linux don't have "double", yet the defaults includes it + target_types: tuple[_MouseEventType, ...] = ..., +) -> None: ... + +if sys.platform == "win32": + def get_position() -> tuple[c_long, c_long]: ... + +else: + def get_position() -> tuple[int, int]: ... + +def hook(callback: _C) -> _C: ... +def unhook(callback: _Callback) -> None: ... +def unhook_all() -> None: ... +def record(button: _MouseButton = "right", target_types: tuple[_MouseEventType] = ("down",)) -> _MouseEvent: ... +def play( + events: Iterable[_MouseEvent], + speed_factor: float = 1.0, + include_clicks: bool = True, + include_moves: bool = True, + include_wheel: bool = True, +) -> None: ... + +replay = play +hold = press diff --git a/stubs/ldap3/@tests/stubtest_allowlist.txt b/stubs/ldap3/@tests/stubtest_allowlist.txt index 71eb99da0822..c1fe27b112fb 100644 --- a/stubs/ldap3/@tests/stubtest_allowlist.txt +++ b/stubs/ldap3/@tests/stubtest_allowlist.txt @@ -1 +1 @@ -ldap3.protocol.sasl.kerberos # requires gssapi package to import +ldap3.utils.ordDict # file is available only in Python 2.6 diff --git a/stubs/ldap3/METADATA.toml b/stubs/ldap3/METADATA.toml index 77ff5706c1d9..d50ccbe8478f 100644 --- a/stubs/ldap3/METADATA.toml +++ b/stubs/ldap3/METADATA.toml @@ -1,2 +1,10 @@ version = "2.9.*" -requires = [] # requires types-pyasn1 (not available yet) +upstream-repository = "https://github.com/cannatag/ldap3" +dependencies = ["types-pyasn1"] + +[tool.stubtest] +apt-dependencies = ["libkrb5-dev"] +# No need to install on the CI. Leaving here as information for MacOs/Windows contributors. +# brew-dependencies = ["krb5"] +# choco-dependencies = ["mitkerberos"] +stubtest-dependencies = ["gssapi"] diff --git a/stubs/ldap3/ldap3/__init__.pyi b/stubs/ldap3/ldap3/__init__.pyi index 4f72194fa2bd..7cb7544c04fa 100644 --- a/stubs/ldap3/ldap3/__init__.pyi +++ b/stubs/ldap3/ldap3/__init__.pyi @@ -1,5 +1,4 @@ -from typing import Any, Tuple, Type -from typing_extensions import Literal +from typing import Literal from .abstract.attrDef import AttrDef as AttrDef from .abstract.attribute import ( @@ -98,7 +97,7 @@ HASHED_SALTED_SHA384: Literal["SALTED_SHA384"] HASHED_SALTED_SHA512: Literal["SALTED_SHA512"] HASHED_SALTED_MD5: Literal["SALTED_MD5"] -NUMERIC_TYPES: Tuple[Type[Any], ...] -INTEGER_TYPES: Tuple[Type[Any], ...] -STRING_TYPES: Tuple[Type[Any], ...] -SEQUENCE_TYPES: Tuple[Type[Any], ...] +NUMERIC_TYPES: tuple[type, ...] +INTEGER_TYPES: tuple[type, ...] +STRING_TYPES: tuple[type, ...] +SEQUENCE_TYPES: tuple[type, ...] diff --git a/stubs/ldap3/ldap3/abstract/__init__.pyi b/stubs/ldap3/ldap3/abstract/__init__.pyi index 5c2b1bd77518..2e5fe21aca1c 100644 --- a/stubs/ldap3/ldap3/abstract/__init__.pyi +++ b/stubs/ldap3/ldap3/abstract/__init__.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete STATUS_INIT: str STATUS_VIRTUAL: str @@ -11,5 +11,5 @@ STATUS_READY_FOR_DELETION: str STATUS_READY_FOR_MOVING: str STATUS_READY_FOR_RENAMING: str STATUS_DELETED: str -STATUSES: Any -INITIAL_STATUSES: Any +STATUSES: Incomplete +INITIAL_STATUSES: Incomplete diff --git a/stubs/ldap3/ldap3/abstract/attrDef.pyi b/stubs/ldap3/ldap3/abstract/attrDef.pyi index 980262393e08..b59e04f5df98 100644 --- a/stubs/ldap3/ldap3/abstract/attrDef.pyi +++ b/stubs/ldap3/ldap3/abstract/attrDef.pyi @@ -1,33 +1,33 @@ -from typing import Any +from _typeshed import Incomplete class AttrDef: - name: Any - key: Any - validate: Any - pre_query: Any - post_query: Any - default: Any - dereference_dn: Any - description: Any - mandatory: Any - single_value: Any - oid_info: Any - other_names: Any + name: Incomplete + key: Incomplete + validate: Incomplete + pre_query: Incomplete + post_query: Incomplete + default: Incomplete + dereference_dn: Incomplete + description: Incomplete + mandatory: Incomplete + single_value: Incomplete + oid_info: Incomplete + other_names: Incomplete def __init__( self, name, - key: Any | None = ..., - validate: Any | None = ..., - pre_query: Any | None = ..., - post_query: Any | None = ..., + key=None, + validate=None, + pre_query=None, + post_query=None, default=..., - dereference_dn: Any | None = ..., - description: Any | None = ..., - mandatory: bool = ..., - single_value: Any | None = ..., - alias: Any | None = ..., + dereference_dn=None, + description=None, + mandatory: bool = False, + single_value=None, + alias=None, ) -> None: ... def __eq__(self, other): ... def __lt__(self, other): ... - def __hash__(self): ... - def __setattr__(self, key, value) -> None: ... + def __hash__(self) -> int: ... + def __setattr__(self, key: str, value) -> None: ... diff --git a/stubs/ldap3/ldap3/abstract/attribute.pyi b/stubs/ldap3/ldap3/abstract/attribute.pyi index d5ed793dbf77..8040ae647a15 100644 --- a/stubs/ldap3/ldap3/abstract/attribute.pyi +++ b/stubs/ldap3/ldap3/abstract/attribute.pyi @@ -1,16 +1,16 @@ -from typing import Any +from _typeshed import Incomplete class Attribute: - key: Any - definition: Any - values: Any - raw_values: Any - response: Any - entry: Any - cursor: Any - other_names: Any + key: Incomplete + definition: Incomplete + values: Incomplete + raw_values: Incomplete + response: Incomplete + entry: Incomplete + cursor: Incomplete + other_names: Incomplete def __init__(self, attr_def, entry, cursor) -> None: ... - def __len__(self): ... + def __len__(self) -> int: ... def __iter__(self): ... def __getitem__(self, item): ... def __eq__(self, other): ... diff --git a/stubs/ldap3/ldap3/abstract/cursor.pyi b/stubs/ldap3/ldap3/abstract/cursor.pyi index ee27126afca7..9a22b44ac9e2 100644 --- a/stubs/ldap3/ldap3/abstract/cursor.pyi +++ b/stubs/ldap3/ldap3/abstract/cursor.pyi @@ -1,32 +1,33 @@ -from typing import Any, NamedTuple +from _typeshed import Incomplete +from typing import NamedTuple class Operation(NamedTuple): - request: Any - result: Any - response: Any + request: Incomplete + result: Incomplete + response: Incomplete class Cursor: - connection: Any - get_operational_attributes: Any - definition: Any - attributes: Any - controls: Any - execution_time: Any - entries: Any - schema: Any + connection: Incomplete + get_operational_attributes: Incomplete + definition: Incomplete + attributes: Incomplete + controls: Incomplete + execution_time: Incomplete + entries: Incomplete + schema: Incomplete def __init__( self, connection, object_def, - get_operational_attributes: bool = ..., - attributes: Any | None = ..., - controls: Any | None = ..., - auxiliary_class: Any | None = ..., + get_operational_attributes: bool = False, + attributes=None, + controls=None, + auxiliary_class=None, ) -> None: ... def __iter__(self): ... def __getitem__(self, item): ... - def __len__(self): ... - def __bool__(self): ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... def match_dn(self, dn): ... def match(self, attributes, value): ... def remove(self, entry) -> None: ... @@ -38,65 +39,68 @@ class Cursor: def failed(self): ... class Reader(Cursor): - entry_class: Any - attribute_class: Any - entry_initial_status: Any - sub_tree: Any - base: Any - dereference_aliases: Any - validated_query: Any - query_filter: Any + entry_class: Incomplete + attribute_class: Incomplete + entry_initial_status: Incomplete + sub_tree: Incomplete + base: Incomplete + dereference_aliases: Incomplete + validated_query: Incomplete + query_filter: Incomplete def __init__( self, connection, object_def, base, - query: str = ..., - components_in_and: bool = ..., - sub_tree: bool = ..., - get_operational_attributes: bool = ..., - attributes: Any | None = ..., - controls: Any | None = ..., - auxiliary_class: Any | None = ..., + query: str = "", + components_in_and: bool = True, + sub_tree: bool = True, + get_operational_attributes: bool = False, + attributes=None, + controls=None, + auxiliary_class=None, ) -> None: ... + @property def query(self): ... @query.setter def query(self, value) -> None: ... + @property def components_in_and(self): ... @components_in_and.setter def components_in_and(self, value) -> None: ... + def clear(self) -> None: ... - execution_time: Any - entries: Any + execution_time: Incomplete + entries: Incomplete def reset(self) -> None: ... - def search(self, attributes: Any | None = ...): ... - def search_object(self, entry_dn: Any | None = ..., attributes: Any | None = ...): ... - def search_level(self, attributes: Any | None = ...): ... - def search_subtree(self, attributes: Any | None = ...): ... - def search_paged(self, paged_size, paged_criticality: bool = ..., generator: bool = ..., attributes: Any | None = ...): ... + def search(self, attributes=None): ... + def search_object(self, entry_dn=None, attributes=None): ... + def search_level(self, attributes=None): ... + def search_subtree(self, attributes=None): ... + def search_paged(self, paged_size, paged_criticality: bool = True, generator: bool = True, attributes=None): ... class Writer(Cursor): - entry_class: Any - attribute_class: Any - entry_initial_status: Any + entry_class: Incomplete + attribute_class: Incomplete + entry_initial_status: Incomplete @staticmethod - def from_cursor(cursor, connection: Any | None = ..., object_def: Any | None = ..., custom_validator: Any | None = ...): ... + def from_cursor(cursor, connection=None, object_def=None, custom_validator=None): ... @staticmethod - def from_response(connection, object_def, response: Any | None = ...): ... - dereference_aliases: Any + def from_response(connection, object_def, response=None): ... + dereference_aliases: Incomplete def __init__( self, connection, object_def, - get_operational_attributes: bool = ..., - attributes: Any | None = ..., - controls: Any | None = ..., - auxiliary_class: Any | None = ..., + get_operational_attributes: bool = False, + attributes=None, + controls=None, + auxiliary_class=None, ) -> None: ... - execution_time: Any - def commit(self, refresh: bool = ...): ... + execution_time: Incomplete + def commit(self, refresh: bool = True): ... def discard(self) -> None: ... def new(self, dn): ... - def refresh_entry(self, entry, tries: int = ..., seconds: int = ...): ... + def refresh_entry(self, entry, tries: int = 4, seconds: int = 2): ... diff --git a/stubs/ldap3/ldap3/abstract/entry.pyi b/stubs/ldap3/ldap3/abstract/entry.pyi index b7392e22cd6d..1b2df740d130 100644 --- a/stubs/ldap3/ldap3/abstract/entry.pyi +++ b/stubs/ldap3/ldap3/abstract/entry.pyi @@ -1,16 +1,16 @@ -from typing import Any +from _typeshed import Incomplete class EntryState: - dn: Any - status: Any - attributes: Any - raw_attributes: Any - response: Any - cursor: Any - origin: Any - read_time: Any - changes: Any - definition: Any + dn: Incomplete + status: Incomplete + attributes: Incomplete + raw_attributes: Incomplete + response: Incomplete + cursor: Incomplete + origin: Incomplete + read_time: Incomplete + changes: Incomplete + definition: Incomplete def __init__(self, dn, cursor) -> None: ... def set_status(self, status) -> None: ... @property @@ -20,8 +20,8 @@ class EntryBase: def __init__(self, dn, cursor) -> None: ... def __iter__(self): ... def __contains__(self, item): ... - def __getattr__(self, item): ... - def __setattr__(self, item, value) -> None: ... + def __getattr__(self, item: str): ... + def __setattr__(self, item: str, value) -> None: ... def __getitem__(self, item): ... def __eq__(self, other): ... def __lt__(self, other): ... @@ -46,37 +46,30 @@ class EntryBase: def entry_read_time(self): ... def entry_to_json( self, - raw: bool = ..., - indent: int = ..., - sort: bool = ..., - stream: Any | None = ..., - checked_attributes: bool = ..., - include_empty: bool = ..., - ): ... - def entry_to_ldif( - self, all_base64: bool = ..., line_separator: Any | None = ..., sort_order: Any | None = ..., stream: Any | None = ... + raw: bool = False, + indent: int = 4, + sort: bool = True, + stream=None, + checked_attributes: bool = True, + include_empty: bool = True, ): ... + def entry_to_ldif(self, all_base64: bool = False, line_separator=None, sort_order=None, stream=None): ... class Entry(EntryBase): def entry_writable( - self, - object_def: Any | None = ..., - writer_cursor: Any | None = ..., - attributes: Any | None = ..., - custom_validator: Any | None = ..., - auxiliary_class: Any | None = ..., + self, object_def=None, writer_cursor=None, attributes=None, custom_validator=None, auxiliary_class=None ): ... class WritableEntry(EntryBase): def __setitem__(self, key, value) -> None: ... - def __setattr__(self, item, value) -> None: ... - def __getattr__(self, item): ... + def __setattr__(self, item: str, value) -> None: ... + def __getattr__(self, item: str): ... @property def entry_virtual_attributes(self): ... - def entry_commit_changes(self, refresh: bool = ..., controls: Any | None = ..., clear_history: bool = ...): ... + def entry_commit_changes(self, refresh: bool = True, controls=None, clear_history: bool = True): ... def entry_discard_changes(self) -> None: ... def entry_delete(self) -> None: ... - def entry_refresh(self, tries: int = ..., seconds: int = ...): ... + def entry_refresh(self, tries: int = 4, seconds: int = 2): ... def entry_move(self, destination_dn) -> None: ... def entry_rename(self, new_name) -> None: ... @property diff --git a/stubs/ldap3/ldap3/abstract/objectDef.pyi b/stubs/ldap3/ldap3/abstract/objectDef.pyi index 31931796f27c..4aaefa21448b 100644 --- a/stubs/ldap3/ldap3/abstract/objectDef.pyi +++ b/stubs/ldap3/ldap3/abstract/objectDef.pyi @@ -1,23 +1,15 @@ -from typing import Any - class ObjectDef: - def __init__( - self, - object_class: Any | None = ..., - schema: Any | None = ..., - custom_validator: Any | None = ..., - auxiliary_class: Any | None = ..., - ) -> None: ... + def __init__(self, object_class=None, schema=None, custom_validator=None, auxiliary_class=None) -> None: ... def __getitem__(self, item): ... - def __getattr__(self, item): ... - def __setattr__(self, key, value) -> None: ... + def __getattr__(self, item: str): ... + def __setattr__(self, key: str, value) -> None: ... def __iadd__(self, other): ... def __isub__(self, other): ... def __iter__(self): ... - def __len__(self): ... - def __bool__(self): ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... def __contains__(self, item): ... - def add_from_schema(self, attribute_name, mandatory: bool = ...) -> None: ... - def add_attribute(self, definition: Any | None = ...) -> None: ... + def add_from_schema(self, attribute_name, mandatory: bool = False) -> None: ... + def add_attribute(self, definition=None) -> None: ... def remove_attribute(self, item) -> None: ... def clear_attributes(self) -> None: ... diff --git a/stubs/ldap3/ldap3/core/connection.pyi b/stubs/ldap3/ldap3/core/connection.pyi index 2b21d779b85f..d348f2fbe1d4 100644 --- a/stubs/ldap3/ldap3/core/connection.pyi +++ b/stubs/ldap3/ldap3/core/connection.pyi @@ -1,170 +1,191 @@ -from _typeshed import Self +from _collections_abc import Generator, dict_keys +from _typeshed import Incomplete, ReadableBuffer from types import TracebackType -from typing import Any, Type -from typing_extensions import Literal +from typing import Literal, TypeAlias +from typing_extensions import Self +from pyasn1.type.base import Asn1Item + +from ..protocol.convert import _ControlSequence +from .pooling import ServerPool from .server import Server -SASL_AVAILABLE_MECHANISMS: Any -CLIENT_STRATEGIES: Any +SASL_AVAILABLE_MECHANISMS: Incomplete +CLIENT_STRATEGIES: Incomplete + +_ServerSequence: TypeAlias = ( + set[Server] | list[Server] | tuple[Server, ...] | Generator[Server, None, None] | dict_keys[Server, Incomplete] +) +# TODO: Construct full request and response types. This is non-trivial because there are many different request/response types and +# the libary was written async (not thread-safe) design. +_Request: TypeAlias = Incomplete +_Response: TypeAlias = Incomplete +_Result: TypeAlias = Incomplete class Connection: - connection_lock: Any + connection_lock: Incomplete last_error: str - strategy_type: Any - user: Any - password: Any - authentication: Any - version: Any - auto_referrals: Any - request: Any - response: Any | None - result: Any + strategy_type: Incomplete + user: Incomplete + password: Incomplete + authentication: Incomplete + version: Incomplete + auto_referrals: Incomplete + request: _Request + response: _Response | None + result: _Result bound: bool listening: bool closed: bool - auto_bind: Any - sasl_mechanism: Any - sasl_credentials: Any - socket: Any + auto_bind: Incomplete + sasl_mechanism: Incomplete + sasl_credentials: Incomplete + socket: Incomplete tls_started: bool sasl_in_progress: bool - read_only: Any - lazy: Any - pool_name: Any + read_only: Incomplete + lazy: Incomplete + pool_name: Incomplete pool_size: int | None - cred_store: Any - pool_lifetime: Any - pool_keepalive: Any + cred_store: Incomplete + pool_lifetime: Incomplete + pool_keepalive: Incomplete starting_tls: bool - check_names: Any - raise_exceptions: Any - auto_range: Any - extend: Any - fast_decoder: Any - receive_timeout: Any - empty_attributes: Any - use_referral_cache: Any - auto_escape: Any - auto_encode: Any - source_address: Any - source_port_list: Any - server_pool: Any | None - server: Any - strategy: Any - send: Any - open: Any - get_response: Any - post_send_single_response: Any - post_send_search: Any + check_names: Incomplete + raise_exceptions: Incomplete + auto_range: Incomplete + extend: Incomplete + fast_decoder: Incomplete + receive_timeout: Incomplete + empty_attributes: Incomplete + use_referral_cache: Incomplete + auto_escape: Incomplete + auto_encode: Incomplete + source_address: Incomplete + source_port_list: Incomplete + server_pool: Incomplete | None + server: Incomplete + strategy: Incomplete + send: Incomplete + open: Incomplete + get_response: Incomplete + post_send_single_response: Incomplete + post_send_search: Incomplete def __init__( self, - server: Server | str, - user: str | None = ..., - password: str | None = ..., - auto_bind: Literal["DEFAULT", "NONE", "NO_TLS", "TLS_BEFORE_BIND", "TLS_AFTER_BIND"] = ..., - version: int = ..., - authentication: Literal["ANONYMOUS", "SIMPLE", "SASL", "NTLM"] | None = ..., + server: Server | str | _ServerSequence | ServerPool, + user: str | None = None, + password: str | None = None, + auto_bind: Literal["DEFAULT", "NONE", "NO_TLS", "TLS_BEFORE_BIND", "TLS_AFTER_BIND"] | bool = "DEFAULT", + version: int = 3, + authentication: Literal["ANONYMOUS", "SIMPLE", "SASL", "NTLM"] | None = None, client_strategy: Literal[ - "SYNC", "SAFE_SYNC", "ASYNC", "LDIF", "RESTARTABLE", "REUSABLE", "MOCK_SYNC", "MOCK_ASYNC", "ASYNC_STREAM" - ] = ..., - auto_referrals: bool = ..., - auto_range: bool = ..., - sasl_mechanism: str | None = ..., - sasl_credentials: Any | None = ..., - check_names: bool = ..., - collect_usage: bool = ..., - read_only: bool = ..., - lazy: bool = ..., - raise_exceptions: bool = ..., - pool_name: str | None = ..., - pool_size: int | None = ..., - pool_lifetime: int | None = ..., - cred_store: Any | None = ..., - fast_decoder: bool = ..., - receive_timeout: Any | None = ..., - return_empty_attributes: bool = ..., - use_referral_cache: bool = ..., - auto_escape: bool = ..., - auto_encode: bool = ..., - pool_keepalive: Any | None = ..., - source_address: str | None = ..., - source_port: int | None = ..., - source_port_list: Any | None = ..., + "SYNC", + "SAFE_RESTARTABLE", + "SAFE_SYNC", + "ASYNC", + "LDIF", + "RESTARTABLE", + "REUSABLE", + "MOCK_SYNC", + "MOCK_ASYNC", + "ASYNC_STREAM", + ] = "SYNC", + auto_referrals: bool = True, + auto_range: bool = True, + sasl_mechanism: str | None = None, + sasl_credentials=None, + check_names: bool = True, + collect_usage: bool = False, + read_only: bool = False, + lazy: bool = False, + raise_exceptions: bool = False, + pool_name: str | None = None, + pool_size: int | None = None, + pool_lifetime: int | None = None, + cred_store=None, + fast_decoder: bool = True, + receive_timeout=None, + return_empty_attributes: bool = True, + use_referral_cache: bool = False, + auto_escape: bool = True, + auto_encode: bool = True, + pool_keepalive=None, + source_address: str | None = None, + source_port: int | None = None, + source_port_list=None, ) -> None: ... def repr_with_sensitive_data_stripped(self): ... + @property def stream(self): ... @stream.setter def stream(self, value) -> None: ... + @property def usage(self): ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> Literal[False] | None: ... - def bind(self, read_server_info: bool = ..., controls: Any | None = ...): ... + def bind(self, read_server_info: bool = True, controls=None): ... def rebind( self, - user: Any | None = ..., - password: Any | None = ..., - authentication: Any | None = ..., - sasl_mechanism: Any | None = ..., - sasl_credentials: Any | None = ..., - read_server_info: bool = ..., - controls: Any | None = ..., + user=None, + password=None, + authentication=None, + sasl_mechanism=None, + sasl_credentials=None, + read_server_info: bool = True, + controls=None, ): ... - def unbind(self, controls: Any | None = ...): ... + # Thread safe strategies return a (status, result, response, request) tuple instead of a bare status + def unbind( + self, controls: _ControlSequence | None = None + ) -> Literal[True] | tuple[Literal[True], _Result, _Response, _Request]: ... def search( self, search_base: str, search_filter: str, - search_scope: Literal["BASE", "LEVEL", "SUBTREE"] = ..., - dereference_aliases: Literal["NEVER", "SEARCH", "FINDING_BASE", "ALWAYS"] = ..., - attributes: Any | None = ..., - size_limit: int = ..., - time_limit: int = ..., - types_only: bool = ..., - get_operational_attributes: bool = ..., - controls: Any | None = ..., - paged_size: int | None = ..., - paged_criticality: bool = ..., - paged_cookie: str | bytes | None = ..., - auto_escape: bool | None = ..., - ): ... - def compare(self, dn, attribute, value, controls: Any | None = ...): ... - def add(self, dn, object_class: Any | None = ..., attributes: Any | None = ..., controls: Any | None = ...): ... - def delete(self, dn, controls: Any | None = ...): ... - def modify(self, dn, changes, controls: Any | None = ...): ... - def modify_dn( - self, dn, relative_dn, delete_old_dn: bool = ..., new_superior: Any | None = ..., controls: Any | None = ... + search_scope: Literal["BASE", "LEVEL", "SUBTREE"] = "SUBTREE", + dereference_aliases: Literal["NEVER", "SEARCH", "FINDING_BASE", "ALWAYS"] = "ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int | None = None, + paged_criticality: bool = False, + paged_cookie: str | bytes | None = None, + auto_escape: bool | None = None, ): ... - def abandon(self, message_id, controls: Any | None = ...): ... + def compare(self, dn, attribute, value, controls=None): ... + def add(self, dn, object_class=None, attributes=None, controls=None): ... + def delete(self, dn, controls=None): ... + def modify(self, dn, changes, controls=None): ... + def modify_dn(self, dn, relative_dn, delete_old_dn: bool = True, new_superior=None, controls=None): ... + def abandon(self, message_id, controls=None): ... def extended( - self, request_name, request_value: Any | None = ..., controls: Any | None = ..., no_encode: Any | None = ... + self, request_name, request_value: Asn1Item | ReadableBuffer | None = None, controls=None, no_encode: bool | None = None ): ... - def start_tls(self, read_server_info: bool = ...): ... + def start_tls(self, read_server_info: bool = True): ... def do_sasl_bind(self, controls): ... def do_ntlm_bind(self, controls): ... def refresh_server_info(self) -> None: ... def response_to_ldif( - self, - search_result: Any | None = ..., - all_base64: bool = ..., - line_separator: Any | None = ..., - sort_order: Any | None = ..., - stream: Any | None = ..., + self, search_result=None, all_base64: bool = False, line_separator=None, sort_order=None, stream=None ): ... def response_to_json( self, - raw: bool = ..., - search_result: Any | None = ..., - indent: int = ..., - sort: bool = ..., - stream: Any | None = ..., - checked_attributes: bool = ..., - include_empty: bool = ..., + raw: bool = False, + search_result=None, + indent: int = 4, + sort: bool = True, + stream=None, + checked_attributes: bool = True, + include_empty: bool = True, ): ... - def response_to_file(self, target, raw: bool = ..., indent: int = ..., sort: bool = ...) -> None: ... + def response_to_file(self, target, raw: bool = False, indent: int = 4, sort: bool = True) -> None: ... @property def entries(self): ... diff --git a/stubs/ldap3/ldap3/core/exceptions.pyi b/stubs/ldap3/ldap3/core/exceptions.pyi index 9e1cc81383cf..f0ce91bf5ba8 100644 --- a/stubs/ldap3/ldap3/core/exceptions.pyi +++ b/stubs/ldap3/ldap3/core/exceptions.pyi @@ -1,35 +1,18 @@ import socket -from typing import Any, Type, TypeVar - -_T = TypeVar("_T") +from _typeshed import Incomplete +from typing_extensions import Self class LDAPException(Exception): ... class LDAPOperationResult(LDAPException): - def __new__( - cls: Type[_T], - result: Any | None = ..., - description: Any | None = ..., - dn: Any | None = ..., - message: Any | None = ..., - response_type: Any | None = ..., - response: Any | None = ..., - ) -> _T: ... - result: Any - description: Any - dn: Any - message: Any - type: Any - response: Any - def __init__( - self, - result: Any | None = ..., - description: Any | None = ..., - dn: Any | None = ..., - message: Any | None = ..., - response_type: Any | None = ..., - response: Any | None = ..., - ) -> None: ... + def __new__(cls, result=None, description=None, dn=None, message=None, response_type=None, response=None) -> Self: ... + result: Incomplete + description: Incomplete + dn: Incomplete + message: Incomplete + type: Incomplete + response: Incomplete + def __init__(self, result=None, description=None, dn=None, message=None, response_type=None, response=None) -> None: ... class LDAPOperationsErrorResult(LDAPOperationResult): ... class LDAPProtocolErrorResult(LDAPOperationResult): ... @@ -80,7 +63,7 @@ class LDAPAssertionFailedResult(LDAPOperationResult): ... class LDAPAuthorizationDeniedResult(LDAPOperationResult): ... class LDAPESyncRefreshRequiredResult(LDAPOperationResult): ... -exception_table: Any +exception_table: Incomplete class LDAPExceptionError(LDAPException): ... class LDAPConfigurationError(LDAPExceptionError): ... diff --git a/stubs/ldap3/ldap3/core/pooling.pyi b/stubs/ldap3/ldap3/core/pooling.pyi index 088c73e1fb22..861a4d06af53 100644 --- a/stubs/ldap3/ldap3/core/pooling.pyi +++ b/stubs/ldap3/ldap3/core/pooling.pyi @@ -1,38 +1,38 @@ -from typing import Any +from _typeshed import Incomplete -POOLING_STRATEGIES: Any +POOLING_STRATEGIES: Incomplete class ServerState: - server: Any - last_checked_time: Any - available: Any + server: Incomplete + last_checked_time: Incomplete + available: Incomplete def __init__(self, server, last_checked_time, available) -> None: ... class ServerPoolState: - server_states: Any - strategy: Any - server_pool: Any + server_states: Incomplete + strategy: Incomplete + server_pool: Incomplete last_used_server: int - initialize_time: Any + initialize_time: Incomplete def __init__(self, server_pool) -> None: ... def refresh(self) -> None: ... def get_current_server(self): ... def get_server(self): ... def find_active_random_server(self): ... def find_active_server(self, starting): ... - def __len__(self): ... + def __len__(self) -> int: ... class ServerPool: - servers: Any - pool_states: Any - active: Any - exhaust: Any - single: Any - strategy: Any + servers: Incomplete + pool_states: Incomplete + active: Incomplete + exhaust: Incomplete + single: Incomplete + strategy: Incomplete def __init__( - self, servers: Any | None = ..., pool_strategy=..., active: bool = ..., exhaust: bool = ..., single_state: bool = ... + self, servers=None, pool_strategy="ROUND_ROBIN", active: bool = True, exhaust: bool = False, single_state: bool = True ) -> None: ... - def __len__(self): ... + def __len__(self) -> int: ... def __getitem__(self, item): ... def __iter__(self): ... def add(self, servers) -> None: ... diff --git a/stubs/ldap3/ldap3/core/rdns.pyi b/stubs/ldap3/ldap3/core/rdns.pyi index e712f803bcce..41205368d2d7 100644 --- a/stubs/ldap3/ldap3/core/rdns.pyi +++ b/stubs/ldap3/ldap3/core/rdns.pyi @@ -1,12 +1,12 @@ -from typing import Any +from _typeshed import Incomplete class ReverseDnsSetting: - OFF: Any - REQUIRE_RESOLVE_ALL_ADDRESSES: Any - REQUIRE_RESOLVE_IP_ADDRESSES_ONLY: Any - OPTIONAL_RESOLVE_ALL_ADDRESSES: Any - OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY: Any - SUPPORTED_VALUES: Any + OFF: Incomplete + REQUIRE_RESOLVE_ALL_ADDRESSES: Incomplete + REQUIRE_RESOLVE_IP_ADDRESSES_ONLY: Incomplete + OPTIONAL_RESOLVE_ALL_ADDRESSES: Incomplete + OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY: Incomplete + SUPPORTED_VALUES: Incomplete -def get_hostname_by_addr(addr, success_required: bool = ...): ... +def get_hostname_by_addr(addr, success_required: bool = True): ... def is_ip_addr(addr): ... diff --git a/stubs/ldap3/ldap3/core/results.pyi b/stubs/ldap3/ldap3/core/results.pyi index a2772bd148fe..67e1e0dcb549 100644 --- a/stubs/ldap3/ldap3/core/results.pyi +++ b/stubs/ldap3/ldap3/core/results.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete RESULT_SUCCESS: int RESULT_OPERATIONS_ERROR: int @@ -52,5 +52,5 @@ RESULT_CANNOT_CANCEL: int RESULT_ASSERTION_FAILED: int RESULT_AUTHORIZATION_DENIED: int RESULT_E_SYNC_REFRESH_REQUIRED: int -RESULT_CODES: Any -DO_NOT_RAISE_EXCEPTIONS: Any +RESULT_CODES: Incomplete +DO_NOT_RAISE_EXCEPTIONS: Incomplete diff --git a/stubs/ldap3/ldap3/core/server.pyi b/stubs/ldap3/ldap3/core/server.pyi index 65890428ec7a..d31ad382f694 100644 --- a/stubs/ldap3/ldap3/core/server.pyi +++ b/stubs/ldap3/ldap3/core/server.pyi @@ -1,63 +1,52 @@ -from socket import AF_UNIX as AF_UNIX -from typing import Any -from typing_extensions import Literal +from _typeshed import Incomplete +from typing import Literal unix_socket_available: bool class Server: ipc: bool - host: Any - port: Any - allowed_referral_hosts: Any - ssl: Any - tls: Any - name: Any - get_info: Any - dit_lock: Any - custom_formatter: Any - custom_validator: Any - current_address: Any - connect_timeout: Any - mode: Any + host: Incomplete + port: Incomplete + allowed_referral_hosts: Incomplete + ssl: Incomplete + tls: Incomplete + name: Incomplete + get_info: Incomplete + dit_lock: Incomplete + custom_formatter: Incomplete + custom_validator: Incomplete + current_address: Incomplete + connect_timeout: Incomplete + mode: Incomplete def __init__( self, host: str, - port: int | None = ..., - use_ssl: bool = ..., - allowed_referral_hosts: Any | None = ..., - get_info: Literal["NO_INFO", "DSA", "SCHEMA", "ALL"] = ..., - tls: Any | None = ..., - formatter: Any | None = ..., - connect_timeout: Any | None = ..., - mode: Literal["IP_SYSTEM_DEFAULT", "IP_V4_ONLY", "IP_V6_ONLY", "IP_V4_PREFERRED", "IP_V6_PREFERRED"] = ..., - validator: Any | None = ..., + port: int | None = None, + use_ssl: bool = False, + allowed_referral_hosts=None, + get_info: Literal["NO_INFO", "DSA", "SCHEMA", "ALL"] = "SCHEMA", + tls=None, + formatter=None, + connect_timeout=None, + mode: Literal["IP_SYSTEM_DEFAULT", "IP_V4_ONLY", "IP_V6_ONLY", "IP_V4_PREFERRED", "IP_V6_PREFERRED"] = "IP_V6_PREFERRED", + validator=None, ) -> None: ... @property def address_info(self): ... def update_availability(self, address, available) -> None: ... def reset_availability(self) -> None: ... - def check_availability( - self, source_address: Any | None = ..., source_port: Any | None = ..., source_port_list: Any | None = ... - ): ... + def check_availability(self, source_address=None, source_port=None, source_port_list=None): ... @staticmethod def next_message_id(): ... def get_info_from_server(self, connection) -> None: ... - def attach_dsa_info(self, dsa_info: Any | None = ...) -> None: ... - def attach_schema_info(self, dsa_schema: Any | None = ...) -> None: ... + def attach_dsa_info(self, dsa_info=None) -> None: ... + def attach_schema_info(self, dsa_schema=None) -> None: ... @property def info(self): ... @property def schema(self): ... @staticmethod - def from_definition( - host, - dsa_info, - dsa_schema, - port: Any | None = ..., - use_ssl: bool = ..., - formatter: Any | None = ..., - validator: Any | None = ..., - ): ... + def from_definition(host, dsa_info, dsa_schema, port=None, use_ssl: bool = False, formatter=None, validator=None): ... def candidate_addresses(self): ... def has_control(self, control): ... def has_extension(self, extension): ... diff --git a/stubs/ldap3/ldap3/core/timezone.pyi b/stubs/ldap3/ldap3/core/timezone.pyi index c6c52b37c0ae..f56ab0d9f4d3 100644 --- a/stubs/ldap3/ldap3/core/timezone.pyi +++ b/stubs/ldap3/ldap3/core/timezone.pyi @@ -1,9 +1,9 @@ +from _typeshed import Incomplete from datetime import tzinfo -from typing import Any class OffsetTzInfo(tzinfo): - offset: Any - name: Any + offset: Incomplete + name: Incomplete def __init__(self, offset, name) -> None: ... def utcoffset(self, dt): ... def tzname(self, dt): ... diff --git a/stubs/ldap3/ldap3/core/tls.pyi b/stubs/ldap3/ldap3/core/tls.pyi index c776f7f88ad5..3636fa700ed1 100644 --- a/stubs/ldap3/ldap3/core/tls.pyi +++ b/stubs/ldap3/ldap3/core/tls.pyi @@ -1,36 +1,36 @@ -from typing import Any +from _typeshed import Incomplete use_ssl_context: bool class Tls: - ssl_options: Any - validate: Any - ca_certs_file: Any - ca_certs_path: Any - ca_certs_data: Any - private_key_password: Any - version: Any - private_key_file: Any - certificate_file: Any - valid_names: Any - ciphers: Any - sni: Any + ssl_options: Incomplete + validate: Incomplete + ca_certs_file: Incomplete + ca_certs_path: Incomplete + ca_certs_data: Incomplete + private_key_password: Incomplete + version: Incomplete + private_key_file: Incomplete + certificate_file: Incomplete + valid_names: Incomplete + ciphers: Incomplete + sni: Incomplete def __init__( self, - local_private_key_file: Any | None = ..., - local_certificate_file: Any | None = ..., + local_private_key_file=None, + local_certificate_file=None, validate=..., - version: Any | None = ..., - ssl_options: Any | None = ..., - ca_certs_file: Any | None = ..., - valid_names: Any | None = ..., - ca_certs_path: Any | None = ..., - ca_certs_data: Any | None = ..., - local_private_key_password: Any | None = ..., - ciphers: Any | None = ..., - sni: Any | None = ..., + version=None, + ssl_options=None, + ca_certs_file=None, + valid_names=None, + ca_certs_path=None, + ca_certs_data=None, + local_private_key_password=None, + ciphers=None, + sni=None, ) -> None: ... - def wrap_socket(self, connection, do_handshake: bool = ...) -> None: ... + def wrap_socket(self, connection, do_handshake: bool = False) -> None: ... def start_tls(self, connection): ... def check_hostname(sock, server_name, additional_names) -> None: ... diff --git a/stubs/ldap3/ldap3/core/usage.pyi b/stubs/ldap3/ldap3/core/usage.pyi index ccb805bbde76..19bcd126af4e 100644 --- a/stubs/ldap3/ldap3/core/usage.pyi +++ b/stubs/ldap3/ldap3/core/usage.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete class ConnectionUsage: open_sockets: int @@ -26,16 +26,16 @@ class ConnectionUsage: restartable_successes: int servers_from_pool: int def reset(self) -> None: ... - initial_connection_start_time: Any - open_socket_start_time: Any - connection_stop_time: Any - last_transmitted_time: Any - last_received_time: Any + initial_connection_start_time: Incomplete + open_socket_start_time: Incomplete + connection_stop_time: Incomplete + last_transmitted_time: Incomplete + last_received_time: Incomplete def __init__(self) -> None: ... def __iadd__(self, other): ... def update_transmitted_message(self, message, length) -> None: ... def update_received_message(self, length) -> None: ... - def start(self, reset: bool = ...) -> None: ... + def start(self, reset: bool = True) -> None: ... def stop(self) -> None: ... @property def elapsed_time(self): ... diff --git a/stubs/ldap3/ldap3/extend/__init__.pyi b/stubs/ldap3/ldap3/extend/__init__.pyi index 61ca6f486b45..db6afd88f452 100644 --- a/stubs/ldap3/ldap3/extend/__init__.pyi +++ b/stubs/ldap3/ldap3/extend/__init__.pyi @@ -1,105 +1,97 @@ -from typing import Any +from _typeshed import Incomplete class ExtendedOperationContainer: def __init__(self, connection) -> None: ... class StandardExtendedOperations(ExtendedOperationContainer): - def who_am_i(self, controls: Any | None = ...): ... - def modify_password( - self, - user: Any | None = ..., - old_password: Any | None = ..., - new_password: Any | None = ..., - hash_algorithm: Any | None = ..., - salt: Any | None = ..., - controls: Any | None = ..., - ): ... + def who_am_i(self, controls=None): ... + def modify_password(self, user=None, old_password=None, new_password=None, hash_algorithm=None, salt=None, controls=None): ... def paged_search( self, search_base, search_filter, - search_scope=..., - dereference_aliases=..., - attributes: Any | None = ..., - size_limit: int = ..., - time_limit: int = ..., - types_only: bool = ..., - get_operational_attributes: bool = ..., - controls: Any | None = ..., - paged_size: int = ..., - paged_criticality: bool = ..., - generator: bool = ..., + search_scope="SUBTREE", + dereference_aliases="ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int = 100, + paged_criticality: bool = False, + generator: bool = True, ): ... def persistent_search( self, - search_base: str = ..., - search_filter: str = ..., - search_scope=..., - dereference_aliases=..., - attributes=..., - size_limit: int = ..., - time_limit: int = ..., - controls: Any | None = ..., - changes_only: bool = ..., - show_additions: bool = ..., - show_deletions: bool = ..., - show_modifications: bool = ..., - show_dn_modifications: bool = ..., - notifications: bool = ..., - streaming: bool = ..., - callback: Any | None = ..., + search_base: str = "", + search_filter: str = "(objectclass=*)", + search_scope="SUBTREE", + dereference_aliases="NEVER", + attributes="*", + size_limit: int = 0, + time_limit: int = 0, + controls=None, + changes_only: bool = True, + show_additions: bool = True, + show_deletions: bool = True, + show_modifications: bool = True, + show_dn_modifications: bool = True, + notifications: bool = True, + streaming: bool = True, + callback=None, ): ... def funnel_search( self, - search_base: str = ..., - search_filter: str = ..., - search_scope=..., - dereference_aliases=..., - attributes=..., - size_limit: int = ..., - time_limit: int = ..., - controls: Any | None = ..., - streaming: bool = ..., - callback: Any | None = ..., + search_base: str = "", + search_filter: str = "", + search_scope="SUBTREE", + dereference_aliases="NEVER", + attributes="*", + size_limit: int = 0, + time_limit: int = 0, + controls=None, + streaming: bool = False, + callback=None, ): ... class NovellExtendedOperations(ExtendedOperationContainer): - def get_bind_dn(self, controls: Any | None = ...): ... - def get_universal_password(self, user, controls: Any | None = ...): ... - def set_universal_password(self, user, new_password: Any | None = ..., controls: Any | None = ...): ... - def list_replicas(self, server_dn, controls: Any | None = ...): ... - def partition_entry_count(self, partition_dn, controls: Any | None = ...): ... - def replica_info(self, server_dn, partition_dn, controls: Any | None = ...): ... - def start_transaction(self, controls: Any | None = ...): ... - def end_transaction(self, commit: bool = ..., controls: Any | None = ...): ... - def add_members_to_groups(self, members, groups, fix: bool = ..., transaction: bool = ...): ... - def remove_members_from_groups(self, members, groups, fix: bool = ..., transaction: bool = ...): ... - def check_groups_memberships(self, members, groups, fix: bool = ..., transaction: bool = ...): ... + def get_bind_dn(self, controls=None): ... + def get_universal_password(self, user, controls=None): ... + def set_universal_password(self, user, new_password=None, controls=None): ... + def list_replicas(self, server_dn, controls=None): ... + def partition_entry_count(self, partition_dn, controls=None): ... + def replica_info(self, server_dn, partition_dn, controls=None): ... + def start_transaction(self, controls=None): ... + def end_transaction(self, commit: bool = True, controls=None): ... + def add_members_to_groups(self, members, groups, fix: bool = True, transaction: bool = True): ... + def remove_members_from_groups(self, members, groups, fix: bool = True, transaction: bool = True): ... + def check_groups_memberships(self, members, groups, fix: bool = False, transaction: bool = True): ... class MicrosoftExtendedOperations(ExtendedOperationContainer): def dir_sync( self, sync_base, - sync_filter: str = ..., - attributes=..., - cookie: Any | None = ..., - object_security: bool = ..., - ancestors_first: bool = ..., - public_data_only: bool = ..., - incremental_values: bool = ..., - max_length: int = ..., - hex_guid: bool = ..., + sync_filter: str = "(objectclass=*)", + attributes="*", + cookie=None, + object_security: bool = False, + ancestors_first: bool = True, + public_data_only: bool = False, + incremental_values: bool = True, + max_length: int = 2147483647, + hex_guid: bool = False, ): ... - def modify_password(self, user, new_password, old_password: Any | None = ..., controls: Any | None = ...): ... + def modify_password(self, user, new_password, old_password=None, controls=None): ... def unlock_account(self, user): ... - def add_members_to_groups(self, members, groups, fix: bool = ...): ... - def remove_members_from_groups(self, members, groups, fix: bool = ...): ... + def add_members_to_groups(self, members, groups, fix: bool = True): ... + def remove_members_from_groups(self, members, groups, fix: bool = True): ... def persistent_search( - self, search_base: str = ..., search_scope=..., attributes=..., streaming: bool = ..., callback: Any | None = ... + self, search_base: str = "", search_scope="SUBTREE", attributes="*", streaming: bool = True, callback=None ): ... class ExtendedOperationsRoot(ExtendedOperationContainer): - standard: Any - novell: Any - microsoft: Any + standard: Incomplete + novell: Incomplete + microsoft: Incomplete def __init__(self, connection) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi b/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi index 486d084f95ec..39195431a854 100644 --- a/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi +++ b/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi @@ -1 +1 @@ -def ad_add_members_to_groups(connection, members_dn, groups_dn, fix: bool = ..., raise_error: bool = ...): ... +def ad_add_members_to_groups(connection, members_dn, groups_dn, fix: bool = True, raise_error: bool = False): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi b/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi index 68acbfc5d21e..80f947e9589f 100644 --- a/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi +++ b/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi @@ -1,17 +1,17 @@ -from typing import Any +from _typeshed import Incomplete class DirSync: - connection: Any - base: Any - filter: Any - attributes: Any - cookie: Any - object_security: Any - ancestors_first: Any - public_data_only: Any - incremental_values: Any - max_length: Any - hex_guid: Any + connection: Incomplete + base: Incomplete + filter: Incomplete + attributes: Incomplete + cookie: Incomplete + object_security: Incomplete + ancestors_first: Incomplete + public_data_only: Incomplete + incremental_values: Incomplete + max_length: Incomplete + hex_guid: Incomplete more_results: bool def __init__( self, diff --git a/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi b/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi index 5b3d27a0f751..6ee9b965f9d2 100644 --- a/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi +++ b/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi @@ -1,3 +1 @@ -from typing import Any - -def ad_modify_password(connection, user_dn, new_password, old_password, controls: Any | None = ...): ... +def ad_modify_password(connection, user_dn, new_password, old_password, controls=None): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi b/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi index 95fca82fce4b..5c39dfc8b0b8 100644 --- a/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi +++ b/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi @@ -1,15 +1,15 @@ -from typing import Any +from _typeshed import Incomplete class ADPersistentSearch: - connection: Any - message_id: Any - base: Any - scope: Any - attributes: Any - controls: Any + connection: Incomplete + message_id: Incomplete + base: Incomplete + scope: Incomplete + attributes: Incomplete + controls: Incomplete filter: str def __init__(self, connection, search_base, search_scope, attributes, streaming, callback) -> None: ... def start(self) -> None: ... - def stop(self, unbind: bool = ...) -> None: ... - def next(self, block: bool = ..., timeout: Any | None = ...): ... - def funnel(self, block: bool = ..., timeout: Any | None = ...) -> None: ... + def stop(self, unbind: bool = True) -> None: ... + def next(self, block: bool = False, timeout=None): ... + def funnel(self, block: bool = False, timeout=None) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi b/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi index 915fb9dbb562..33fce56a80c1 100644 --- a/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi +++ b/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi @@ -1 +1 @@ -def ad_remove_members_from_groups(connection, members_dn, groups_dn, fix, raise_error: bool = ...): ... +def ad_remove_members_from_groups(connection, members_dn, groups_dn, fix, raise_error: bool = False): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi b/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi index 842378089f63..dd96df4b40a5 100644 --- a/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi +++ b/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi @@ -1,3 +1 @@ -from typing import Any - -def ad_unlock_account(connection, user_dn, controls: Any | None = ...): ... +def ad_unlock_account(connection, user_dn, controls=None): ... diff --git a/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi b/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi index f0e8c5896949..d771f87e9fc1 100644 --- a/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi +++ b/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi @@ -1,14 +1,15 @@ -from typing import Any +from _typeshed import Incomplete from ...extend.operation import ExtendedOperation +from ...protocol.novell import EndGroupTypeRequestValue, EndGroupTypeResponseValue class EndTransaction(ExtendedOperation): request_name: str response_name: str - request_value: Any - asn1_spec: Any + request_value: EndGroupTypeRequestValue + asn1_spec: EndGroupTypeResponseValue def config(self) -> None: ... - def __init__(self, connection, commit: bool = ..., controls: Any | None = ...) -> None: ... + def __init__(self, connection, commit: bool = True, controls=None) -> None: ... def populate_result(self) -> None: ... - response_value: Any + response_value: Incomplete def set_response(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi b/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi index 4c194ce82909..3e9e9c40b490 100644 --- a/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi +++ b/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi @@ -1,11 +1,10 @@ -from typing import Any - from ...extend.operation import ExtendedOperation +from ...protocol.novell import Identity class GetBindDn(ExtendedOperation): request_name: str response_name: str response_attribute: str - asn1_spec: Any + asn1_spec: Identity def config(self) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi b/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi index 0c7b6e7a80af..414761713115 100644 --- a/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi +++ b/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi @@ -1,13 +1,13 @@ -from typing import Any - from ...extend.operation import ExtendedOperation +from ...protocol.novell import ReplicaList +from ...protocol.rfc4511 import LDAPDN class ListReplicas(ExtendedOperation): request_name: str response_name: str - request_value: Any - asn1_spec: Any + request_value: LDAPDN + asn1_spec: ReplicaList response_attribute: str def config(self) -> None: ... - def __init__(self, connection, server_dn, controls: Any | None = ...) -> None: ... + def __init__(self, connection, server_dn, controls=None) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi b/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi index 59d0f1ca37ac..f18b0ab3ac64 100644 --- a/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi +++ b/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi @@ -1,13 +1,12 @@ -from typing import Any - from ...extend.operation import ExtendedOperation +from ...protocol.novell import NmasGetUniversalPasswordRequestValue, NmasGetUniversalPasswordResponseValue class NmasGetUniversalPassword(ExtendedOperation): request_name: str response_name: str - request_value: Any - asn1_spec: Any + request_value: NmasGetUniversalPasswordRequestValue + asn1_spec: NmasGetUniversalPasswordResponseValue response_attribute: str def config(self) -> None: ... - def __init__(self, connection, user, controls: Any | None = ...) -> None: ... + def __init__(self, connection, user, controls=None) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi b/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi index a35b984ba8f2..762b20e7e2b5 100644 --- a/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi +++ b/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi @@ -1,13 +1,12 @@ -from typing import Any - from ...extend.operation import ExtendedOperation +from ...protocol.novell import NmasSetUniversalPasswordRequestValue, NmasSetUniversalPasswordResponseValue class NmasSetUniversalPassword(ExtendedOperation): request_name: str response_name: str - request_value: Any - asn1_spec: Any + request_value: NmasSetUniversalPasswordRequestValue + asn1_spec: NmasSetUniversalPasswordResponseValue response_attribute: str def config(self) -> None: ... - def __init__(self, connection, user, new_password, controls: Any | None = ...) -> None: ... + def __init__(self, connection, user, new_password, controls=None) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi b/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi index a9127983afcf..3231221f71ab 100644 --- a/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi +++ b/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi @@ -1,12 +1,11 @@ -from typing import Any - +from ...protocol.rfc4511 import LDAPDN from ..operation import ExtendedOperation class PartitionEntryCount(ExtendedOperation): request_name: str response_name: str - request_value: Any + request_value: LDAPDN response_attribute: str def config(self) -> None: ... - def __init__(self, connection, partition_dn, controls: Any | None = ...) -> None: ... + def __init__(self, connection, partition_dn, controls=None) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi b/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi index 6a4358053f43..5bc47e022a2a 100644 --- a/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi +++ b/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi @@ -1,12 +1,11 @@ -from typing import Any - +from ...protocol.novell import ReplicaInfoRequestValue from ..operation import ExtendedOperation class ReplicaInfo(ExtendedOperation): request_name: str response_name: str - request_value: Any + request_value: ReplicaInfoRequestValue response_attribute: str def config(self) -> None: ... - def __init__(self, connection, server_dn, partition_dn, controls: Any | None = ...) -> None: ... + def __init__(self, connection, server_dn, partition_dn, controls=None) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi b/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi index 74dd78c5cf06..f5225664e7c3 100644 --- a/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi +++ b/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi @@ -1,14 +1,15 @@ -from typing import Any +from _typeshed import Incomplete from ...extend.operation import ExtendedOperation +from ...protocol.novell import CreateGroupTypeRequestValue, CreateGroupTypeResponseValue class StartTransaction(ExtendedOperation): request_name: str response_name: str - request_value: Any - asn1_spec: Any + request_value: CreateGroupTypeRequestValue + asn1_spec: CreateGroupTypeResponseValue def config(self) -> None: ... - def __init__(self, connection, controls: Any | None = ...) -> None: ... + def __init__(self, connection, controls=None) -> None: ... def populate_result(self) -> None: ... - response_value: Any + response_value: Incomplete def set_response(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/operation.pyi b/stubs/ldap3/ldap3/extend/operation.pyi index 4b14b4b5333d..614f5c9842c7 100644 --- a/stubs/ldap3/ldap3/extend/operation.pyi +++ b/stubs/ldap3/ldap3/extend/operation.pyi @@ -1,19 +1,21 @@ -from typing import Any +from _typeshed import Incomplete + +from pyasn1.type.base import Asn1Type class ExtendedOperation: - connection: Any - decoded_response: Any - result: Any - asn1_spec: Any - request_name: Any - response_name: Any - request_value: Any - response_value: Any - response_attribute: Any - controls: Any - def __init__(self, connection, controls: Any | None = ...) -> None: ... + connection: Incomplete + decoded_response: Incomplete | None + result: Incomplete | None + asn1_spec: Asn1Type | None + request_name: Incomplete | None + response_name: Incomplete | None + request_value: Asn1Type | None + response_value: Incomplete | None + response_attribute: Incomplete | None + controls: Incomplete + def __init__(self, connection, controls=None) -> None: ... def send(self): ... def populate_result(self) -> None: ... - def decode_response(self, response: Any | None = ...) -> None: ... + def decode_response(self, response=None) -> None: ... def set_response(self) -> None: ... def config(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi b/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi index 741f7c5b96c5..d651eff6afda 100644 --- a/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi +++ b/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi @@ -1,32 +1,30 @@ -from typing import Any - def paged_search_generator( connection, search_base, search_filter, - search_scope=..., - dereference_aliases=..., - attributes: Any | None = ..., - size_limit: int = ..., - time_limit: int = ..., - types_only: bool = ..., - get_operational_attributes: bool = ..., - controls: Any | None = ..., - paged_size: int = ..., - paged_criticality: bool = ..., + search_scope="SUBTREE", + dereference_aliases="ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int = 100, + paged_criticality: bool = False, ) -> None: ... def paged_search_accumulator( connection, search_base, search_filter, - search_scope=..., - dereference_aliases=..., - attributes: Any | None = ..., - size_limit: int = ..., - time_limit: int = ..., - types_only: bool = ..., - get_operational_attributes: bool = ..., - controls: Any | None = ..., - paged_size: int = ..., - paged_criticality: bool = ..., + search_scope="SUBTREE", + dereference_aliases="ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int = 100, + paged_criticality: bool = False, ): ... diff --git a/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi b/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi index 3af402ec3654..8b059d36c29e 100644 --- a/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi +++ b/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi @@ -1,18 +1,18 @@ -from typing import Any +from _typeshed import Incomplete class PersistentSearch: - connection: Any - changes_only: Any - notifications: Any - message_id: Any - base: Any - filter: Any - scope: Any - dereference_aliases: Any - attributes: Any - size_limit: Any - time_limit: Any - controls: Any + connection: Incomplete + changes_only: Incomplete + notifications: Incomplete + message_id: Incomplete + base: Incomplete + filter: Incomplete + scope: Incomplete + dereference_aliases: Incomplete + attributes: Incomplete + size_limit: Incomplete + time_limit: Incomplete + controls: Incomplete def __init__( self, connection, @@ -31,6 +31,6 @@ class PersistentSearch: callback, ) -> None: ... def start(self) -> None: ... - def stop(self, unbind: bool = ...) -> None: ... - def next(self, block: bool = ..., timeout: Any | None = ...): ... - def funnel(self, block: bool = ..., timeout: Any | None = ...) -> None: ... + def stop(self, unbind: bool = True) -> None: ... + def next(self, block: bool = False, timeout=None): ... + def funnel(self, block: bool = False, timeout=None) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi b/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi index 5df4b6d1ecbd..1cd8156be3e8 100644 --- a/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi +++ b/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi @@ -1,21 +1,13 @@ -from typing import Any - from ...extend.operation import ExtendedOperation +from ...protocol.rfc3062 import PasswdModifyRequestValue, PasswdModifyResponseValue class ModifyPassword(ExtendedOperation): request_name: str - request_value: Any - asn1_spec: Any + request_value: PasswdModifyRequestValue + asn1_spec: PasswdModifyResponseValue response_attribute: str def config(self) -> None: ... def __init__( - self, - connection, - user: Any | None = ..., - old_password: Any | None = ..., - new_password: Any | None = ..., - hash_algorithm: Any | None = ..., - salt: Any | None = ..., - controls: Any | None = ..., + self, connection, user=None, old_password=None, new_password=None, hash_algorithm=None, salt=None, controls=None ) -> None: ... def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/operation/add.pyi b/stubs/ldap3/ldap3/operation/add.pyi index 59d87bae8a03..777b0e3c2f5f 100644 --- a/stubs/ldap3/ldap3/operation/add.pyi +++ b/stubs/ldap3/ldap3/operation/add.pyi @@ -1,7 +1,3 @@ -from typing import Any - -def add_operation( - dn, attributes, auto_encode, schema: Any | None = ..., validator: Any | None = ..., check_names: bool = ... -): ... +def add_operation(dn, attributes, auto_encode, schema=None, validator=None, check_names: bool = False): ... def add_request_to_dict(request): ... def add_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/bind.pyi b/stubs/ldap3/ldap3/operation/bind.pyi index 5079a87da77d..9d8f99c13ecd 100644 --- a/stubs/ldap3/ldap3/operation/bind.pyi +++ b/stubs/ldap3/ldap3/operation/bind.pyi @@ -1,21 +1,9 @@ -from typing import Any - def bind_operation( - version, - authentication, - name: str = ..., - password: Any | None = ..., - sasl_mechanism: Any | None = ..., - sasl_credentials: Any | None = ..., - auto_encode: bool = ..., + version, authentication, name: str = "", password=None, sasl_mechanism=None, sasl_credentials=None, auto_encode: bool = False ): ... def bind_request_to_dict(request): ... def bind_response_operation( - result_code, - matched_dn: str = ..., - diagnostic_message: str = ..., - referral: Any | None = ..., - server_sasl_credentials: Any | None = ..., + result_code, matched_dn: str = "", diagnostic_message: str = "", referral=None, server_sasl_credentials=None ): ... def bind_response_to_dict(response): ... def sicily_bind_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/compare.pyi b/stubs/ldap3/ldap3/operation/compare.pyi index 4b12d354700d..911781143cc4 100644 --- a/stubs/ldap3/ldap3/operation/compare.pyi +++ b/stubs/ldap3/ldap3/operation/compare.pyi @@ -1,7 +1,3 @@ -from typing import Any - -def compare_operation( - dn, attribute, value, auto_encode, schema: Any | None = ..., validator: Any | None = ..., check_names: bool = ... -): ... +def compare_operation(dn, attribute, value, auto_encode, schema=None, validator=None, check_names: bool = False): ... def compare_request_to_dict(request): ... def compare_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/extended.pyi b/stubs/ldap3/ldap3/operation/extended.pyi index 2cc46be69181..e519cf999503 100644 --- a/stubs/ldap3/ldap3/operation/extended.pyi +++ b/stubs/ldap3/ldap3/operation/extended.pyi @@ -1,6 +1,12 @@ -from typing import Any +from _typeshed import ReadableBuffer -def extended_operation(request_name, request_value: Any | None = ..., no_encode: Any | None = ...): ... +from pyasn1.type.base import Asn1Item + +from ..protocol.rfc4511 import ExtendedRequest + +def extended_operation( + request_name, request_value: Asn1Item | ReadableBuffer | None = None, no_encode: bool | None = None +) -> ExtendedRequest: ... def extended_request_to_dict(request): ... def extended_response_to_dict(response): ... def intermediate_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/modify.pyi b/stubs/ldap3/ldap3/operation/modify.pyi index 8700499b9e94..f21725f4b7f1 100644 --- a/stubs/ldap3/ldap3/operation/modify.pyi +++ b/stubs/ldap3/ldap3/operation/modify.pyi @@ -1,9 +1,7 @@ -from typing import Any +from _typeshed import Incomplete -change_table: Any +change_table: Incomplete -def modify_operation( - dn, changes, auto_encode, schema: Any | None = ..., validator: Any | None = ..., check_names: bool = ... -): ... +def modify_operation(dn, changes, auto_encode, schema=None, validator=None, check_names: bool = False): ... def modify_request_to_dict(request): ... def modify_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/modifyDn.pyi b/stubs/ldap3/ldap3/operation/modifyDn.pyi index db754b8fa4ca..b69d03458aae 100644 --- a/stubs/ldap3/ldap3/operation/modifyDn.pyi +++ b/stubs/ldap3/ldap3/operation/modifyDn.pyi @@ -1,5 +1,3 @@ -from typing import Any - -def modify_dn_operation(dn, new_relative_dn, delete_old_rdn: bool = ..., new_superior: Any | None = ...): ... +def modify_dn_operation(dn, new_relative_dn, delete_old_rdn: bool = True, new_superior=None): ... def modify_dn_request_to_dict(request): ... def modify_dn_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/search.pyi b/stubs/ldap3/ldap3/operation/search.pyi index 78a728ed439e..34f7b29c925a 100644 --- a/stubs/ldap3/ldap3/operation/search.pyi +++ b/stubs/ldap3/ldap3/operation/search.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete ROOT: int AND: int @@ -17,11 +17,13 @@ SEARCH_MATCH_OR_CLOSE: int SEARCH_MATCH_OR_CONTROL: int class FilterNode: - tag: Any - parent: Any - assertion: Any - elements: Any - def __init__(self, tag: Any | None = ..., assertion: Any | None = ...) -> None: ... + tag: Incomplete + parent: Incomplete + assertion: Incomplete + elements: Incomplete + def __init__(self, tag=None, assertion=None) -> None: ... + def __str__(self, pos: int = 0) -> str: ... + def __repr__(self, pos: int = 0) -> str: ... def append(self, filter_node): ... def evaluate_match(match, schema, auto_escape, auto_encode, validator, check_names): ... @@ -39,9 +41,9 @@ def search_operation( types_only, auto_escape, auto_encode, - schema: Any | None = ..., - validator: Any | None = ..., - check_names: bool = ..., + schema=None, + validator=None, + check_names: bool = False, ): ... def decode_vals(vals): ... def decode_vals_fast(vals): ... @@ -51,8 +53,8 @@ def decode_raw_vals(vals): ... def decode_raw_vals_fast(vals): ... def raw_attributes_to_dict(attribute_list): ... def raw_attributes_to_dict_fast(attribute_list): ... -def checked_attributes_to_dict(attribute_list, schema: Any | None = ..., custom_formatter: Any | None = ...): ... -def checked_attributes_to_dict_fast(attribute_list, schema: Any | None = ..., custom_formatter: Any | None = ...): ... +def checked_attributes_to_dict(attribute_list, schema=None, custom_formatter=None): ... +def checked_attributes_to_dict_fast(attribute_list, schema=None, custom_formatter=None): ... def matching_rule_assertion_to_string(matching_rule_assertion): ... def filter_to_string(filter_object): ... def search_request_to_dict(request): ... diff --git a/stubs/ldap3/ldap3/protocol/controls.pyi b/stubs/ldap3/ldap3/protocol/controls.pyi index 7c67b9f3c104..589001327862 100644 --- a/stubs/ldap3/ldap3/protocol/controls.pyi +++ b/stubs/ldap3/ldap3/protocol/controls.pyi @@ -1 +1 @@ -def build_control(oid, criticality, value, encode_control_value: bool = ...): ... +def build_control(oid, criticality, value, encode_control_value: bool = True): ... diff --git a/stubs/ldap3/ldap3/protocol/convert.pyi b/stubs/ldap3/ldap3/protocol/convert.pyi index 4bf4baf99b3b..8909df7c028c 100644 --- a/stubs/ldap3/ldap3/protocol/convert.pyi +++ b/stubs/ldap3/ldap3/protocol/convert.pyi @@ -1,4 +1,14 @@ -from typing import Any +from _collections_abc import Generator, dict_keys +from _typeshed import Incomplete +from typing import TypeAlias + +from .rfc4511 import Control, Controls + +# A control is either a Control object or a (controlType, criticality, controlValue) triple +_Control: TypeAlias = Control | tuple[str, bool, str | bytes | None] +_ControlSequence: TypeAlias = ( + set[_Control] | list[_Control] | tuple[_Control, ...] | Generator[_Control, None, None] | dict_keys[_Control, Incomplete] +) def to_str_or_normalized_unicode(val): ... def attribute_to_dict(attribute): ... @@ -15,8 +25,8 @@ def attributes_to_list(attributes): ... def ava_to_dict(ava): ... def substring_to_dict(substring): ... def prepare_changes_for_request(changes): ... -def build_controls_list(controls): ... +def build_controls_list(controls: _ControlSequence | None) -> Controls | None: ... def validate_assertion_value(schema, name, value, auto_escape, auto_encode, validator, check_names): ... -def validate_attribute_value(schema, name, value, auto_encode, validator: Any | None = ..., check_names: bool = ...): ... +def validate_attribute_value(schema, name, value, auto_encode, validator=None, check_names: bool = False): ... def prepare_filter_for_sending(raw_string): ... def prepare_for_sending(raw_string): ... diff --git a/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi b/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi index 69c4e1aea172..62eb577c68af 100644 --- a/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi +++ b/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete def format_unicode(raw_value): ... def format_integer(raw_value): ... @@ -8,7 +8,7 @@ def format_uuid_le(raw_value): ... def format_boolean(raw_value): ... def format_ad_timestamp(raw_value): ... -time_format: Any +time_format: Incomplete def format_time(raw_value): ... def format_ad_timedelta(raw_value): ... diff --git a/stubs/ldap3/ldap3/protocol/formatters/standard.pyi b/stubs/ldap3/ldap3/protocol/formatters/standard.pyi index f85dd6485adf..7fa4eb927472 100644 --- a/stubs/ldap3/ldap3/protocol/formatters/standard.pyi +++ b/stubs/ldap3/ldap3/protocol/formatters/standard.pyi @@ -1,6 +1,6 @@ -from typing import Any +from _typeshed import Incomplete -standard_formatter: Any +standard_formatter: Incomplete def find_attribute_helpers(attr_type, name, custom_formatter): ... def format_attribute_values(schema, name, values, custom_formatter): ... diff --git a/stubs/ldap3/ldap3/protocol/microsoft.pyi b/stubs/ldap3/ldap3/protocol/microsoft.pyi index 204a718e333d..ac18a70ff620 100644 --- a/stubs/ldap3/ldap3/protocol/microsoft.pyi +++ b/stubs/ldap3/ldap3/protocol/microsoft.pyi @@ -1,27 +1,25 @@ -from typing import Any - -# Enable when pyasn1 gets stubs: -# from pyasn1.type.univ import Sequence -Sequence = Any +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import Sequence class SicilyBindResponse(Sequence): - tagSet: Any - componentType: Any + tagSet: TagSet + componentType: NamedTypes class DirSyncControlRequestValue(Sequence): - componentType: Any + componentType: NamedTypes class DirSyncControlResponseValue(Sequence): - componentType: Any + componentType: NamedTypes class SdFlags(Sequence): - componentType: Any + componentType: NamedTypes class ExtendedDN(Sequence): - componentType: Any + componentType: NamedTypes def dir_sync_control(criticality, object_security, ancestors_first, public_data_only, incremental_values, max_length, cookie): ... -def extended_dn_control(criticality: bool = ..., hex_format: bool = ...): ... -def show_deleted_control(criticality: bool = ...): ... -def security_descriptor_control(criticality: bool = ..., sdflags: int = ...): ... -def persistent_search_control(criticality: bool = ...): ... +def extended_dn_control(criticality: bool = False, hex_format: bool = False): ... +def show_deleted_control(criticality: bool = False): ... +def security_descriptor_control(criticality: bool = False, sdflags: int = 15): ... +def persistent_search_control(criticality: bool = False): ... diff --git a/stubs/ldap3/ldap3/protocol/novell.pyi b/stubs/ldap3/ldap3/protocol/novell.pyi index 8ced7089e996..d3e9c48ef807 100644 --- a/stubs/ldap3/ldap3/protocol/novell.pyi +++ b/stubs/ldap3/ldap3/protocol/novell.pyi @@ -1,11 +1,6 @@ -from typing import Any - -# Enable when pyasn1 gets stubs: -# from pyasn1.type.univ import Integer, OctetString, Sequence, SequenceOf -Integer = Any -OctetString = Any -Sequence = Any -SequenceOf = Any +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import Integer, OctetString, Sequence, SequenceOf NMAS_LDAP_EXT_VERSION: int @@ -13,60 +8,60 @@ class Identity(OctetString): encoding: str class LDAPDN(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class Password(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class LDAPOID(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class GroupCookie(Integer): - tagSet: Any + tagSet: TagSet class NmasVer(Integer): - tagSet: Any + tagSet: TagSet class Error(Integer): - tagSet: Any + tagSet: TagSet class NmasGetUniversalPasswordRequestValue(Sequence): - componentType: Any + componentType: NamedTypes class NmasGetUniversalPasswordResponseValue(Sequence): - componentType: Any + componentType: NamedTypes class NmasSetUniversalPasswordRequestValue(Sequence): - componentType: Any + componentType: NamedTypes class NmasSetUniversalPasswordResponseValue(Sequence): - componentType: Any + componentType: NamedTypes class ReplicaList(SequenceOf): - componentType: Any + componentType: OctetString class ReplicaInfoRequestValue(Sequence): - tagSet: Any - componentType: Any + tagSet: TagSet + componentType: NamedTypes class ReplicaInfoResponseValue(Sequence): - tagSet: Any - componentType: Any + tagSet: TagSet + componentType: NamedTypes class CreateGroupTypeRequestValue(Sequence): - componentType: Any + componentType: NamedTypes class CreateGroupTypeResponseValue(Sequence): - componentType: Any + componentType: NamedTypes class EndGroupTypeRequestValue(Sequence): - componentType: Any + componentType: NamedTypes class EndGroupTypeResponseValue(Sequence): - componentType: Any + componentType: NamedTypes class GroupingControlValue(Sequence): - componentType: Any + componentType: NamedTypes diff --git a/stubs/ldap3/ldap3/protocol/oid.pyi b/stubs/ldap3/ldap3/protocol/oid.pyi index 77efddad270f..83886b0b5654 100644 --- a/stubs/ldap3/ldap3/protocol/oid.pyi +++ b/stubs/ldap3/ldap3/protocol/oid.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete OID_CONTROL: str OID_EXTENSION: str @@ -26,4 +26,4 @@ def decode_oids(sequence): ... def decode_syntax(syntax): ... def oid_to_string(oid): ... -Oids: Any +Oids: Incomplete diff --git a/stubs/ldap3/ldap3/protocol/persistentSearch.pyi b/stubs/ldap3/ldap3/protocol/persistentSearch.pyi index 933ae390b28c..199e6c4c750c 100644 --- a/stubs/ldap3/ldap3/protocol/persistentSearch.pyi +++ b/stubs/ldap3/ldap3/protocol/persistentSearch.pyi @@ -1,17 +1,14 @@ -from typing import Any - -# Enable when pyasn1 gets stubs: -# from pyasn1.type.univ import Enumerated, Sequence -Enumerated = Any -Sequence = Any +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.namedval import NamedValues +from pyasn1.type.univ import Enumerated, Sequence class PersistentSearchControl(Sequence): - componentType: Any + componentType: NamedTypes class ChangeType(Enumerated): - namedValues: Any + namedValues: NamedValues class EntryChangeNotificationControl(Sequence): - componentType: Any + componentType: NamedTypes -def persistent_search_control(change_types, changes_only: bool = ..., return_ecs: bool = ..., criticality: bool = ...): ... +def persistent_search_control(change_types, changes_only: bool = True, return_ecs: bool = True, criticality: bool = False): ... diff --git a/stubs/ldap3/ldap3/protocol/rfc2696.pyi b/stubs/ldap3/ldap3/protocol/rfc2696.pyi index 8cb346f0304b..4df6aa5aed3e 100644 --- a/stubs/ldap3/ldap3/protocol/rfc2696.pyi +++ b/stubs/ldap3/ldap3/protocol/rfc2696.pyi @@ -1,21 +1,19 @@ -from typing import Any +from typing import Final -# Enable when pyasn1 gets stubs: -# from pyasn1.type.univ import Integer, OctetString, Sequence -Integer = Any -OctetString = Any -Sequence = Any +from pyasn1.type.constraint import ConstraintsIntersection, ValueRangeConstraint +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.univ import Integer, OctetString, Sequence -MAXINT: Any -rangeInt0ToMaxConstraint: Any +MAXINT: Final[Integer] +rangeInt0ToMaxConstraint: ValueRangeConstraint class Integer0ToMax(Integer): - subtypeSpec: Any + subtypeSpec: ConstraintsIntersection class Size(Integer0ToMax): ... class Cookie(OctetString): ... class RealSearchControlValue(Sequence): - componentType: Any + componentType: NamedTypes -def paged_search_control(criticality: bool = ..., size: int = ..., cookie: Any | None = ...): ... +def paged_search_control(criticality: bool = False, size: int = 10, cookie=None): ... diff --git a/stubs/ldap3/ldap3/protocol/rfc2849.pyi b/stubs/ldap3/ldap3/protocol/rfc2849.pyi index b589bc57ce65..62420dde63d3 100644 --- a/stubs/ldap3/ldap3/protocol/rfc2849.pyi +++ b/stubs/ldap3/ldap3/protocol/rfc2849.pyi @@ -1,17 +1,17 @@ -from typing import Any +from _typeshed import Incomplete -conf_ldif_line_length: Any +conf_ldif_line_length: Incomplete def safe_ldif_string(bytes_value): ... def add_controls(controls, all_base64): ... def add_attributes(attributes, all_base64): ... def sort_ldif_lines(lines, sort_order): ... -def search_response_to_ldif(entries, all_base64, sort_order: Any | None = ...): ... -def add_request_to_ldif(entry, all_base64, sort_order: Any | None = ...): ... -def delete_request_to_ldif(entry, all_base64, sort_order: Any | None = ...): ... -def modify_request_to_ldif(entry, all_base64, sort_order: Any | None = ...): ... -def modify_dn_request_to_ldif(entry, all_base64, sort_order: Any | None = ...): ... -def operation_to_ldif(operation_type, entries, all_base64: bool = ..., sort_order: Any | None = ...): ... +def search_response_to_ldif(entries, all_base64, sort_order=None): ... +def add_request_to_ldif(entry, all_base64, sort_order=None): ... +def delete_request_to_ldif(entry, all_base64, sort_order=None): ... +def modify_request_to_ldif(entry, all_base64, sort_order=None): ... +def modify_dn_request_to_ldif(entry, all_base64, sort_order=None): ... +def operation_to_ldif(operation_type, entries, all_base64: bool = False, sort_order=None): ... def add_ldif_header(ldif_lines): ... def ldif_sort(line, sort_order): ... def decode_persistent_search_control(change): ... diff --git a/stubs/ldap3/ldap3/protocol/rfc3062.pyi b/stubs/ldap3/ldap3/protocol/rfc3062.pyi index c508ccbbfb10..4a97a374a37f 100644 --- a/stubs/ldap3/ldap3/protocol/rfc3062.pyi +++ b/stubs/ldap3/ldap3/protocol/rfc3062.pyi @@ -1,28 +1,25 @@ -from typing import Any - -# Enable when pyasn1 gets stubs: -# from pyasn1.type.univ import OctetString, Sequence -OctetString = Any -Sequence = Any +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import OctetString, Sequence class UserIdentity(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class OldPasswd(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class NewPasswd(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class GenPasswd(OctetString): - tagSet: Any + tagSet: TagSet encoding: str class PasswdModifyRequestValue(Sequence): - componentType: Any + componentType: NamedTypes class PasswdModifyResponseValue(Sequence): - componentType: Any + componentType: NamedTypes diff --git a/stubs/ldap3/ldap3/protocol/rfc4511.pyi b/stubs/ldap3/ldap3/protocol/rfc4511.pyi index 070910ae3868..83b9c2b71b44 100644 --- a/stubs/ldap3/ldap3/protocol/rfc4511.pyi +++ b/stubs/ldap3/ldap3/protocol/rfc4511.pyi @@ -1,32 +1,28 @@ -from typing import Any as _Any - -# Enable when pyasn1 gets stubs: -# from pyasn1.type.univ import Boolean, Choice, Enumerated, Integer, Null, OctetString, Sequence, SequenceOf, SetOf -Boolean = _Any -Choice = _Any -Enumerated = _Any -Integer = _Any -Null = _Any -OctetString = _Any -Sequence = _Any -SequenceOf = _Any -SetOf = _Any - -LDAP_MAX_INT: int -MAXINT: _Any -rangeInt0ToMaxConstraint: _Any -rangeInt1To127Constraint: _Any -size1ToMaxConstraint: _Any -responseValueConstraint: _Any -numericOIDConstraint: _Any -distinguishedNameConstraint: _Any -nameComponentConstraint: _Any -attributeDescriptionConstraint: _Any -uriConstraint: _Any -attributeSelectorConstraint: _Any +# Alias the import to avoid name clash with a class called "Final" +from typing import Final as _Final + +from pyasn1.type.constraint import ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.namedval import NamedValues +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import Boolean, Choice, Enumerated, Integer, Null, OctetString, Sequence, SequenceOf, SetOf + +LDAP_MAX_INT: _Final[int] +MAXINT: _Final[Integer] +rangeInt0ToMaxConstraint: ValueRangeConstraint +rangeInt1To127Constraint: ValueRangeConstraint +size1ToMaxConstraint: ValueSizeConstraint +responseValueConstraint: SingleValueConstraint +# Custom constraints. They have yet to be implemented so ldap3 keeps them as None. +numericOIDConstraint: None +distinguishedNameConstraint: None +nameComponentConstraint: None +attributeDescriptionConstraint: None +uriConstraint: None +attributeSelectorConstraint: None class Integer0ToMax(Integer): - subtypeSpec: _Any + subtypeSpec: ConstraintsIntersection class LDAPString(OctetString): encoding: str @@ -44,71 +40,71 @@ class AssertionValue(OctetString): encoding: str class AttributeValueAssertion(Sequence): - componentType: _Any + componentType: NamedTypes class MatchingRuleId(LDAPString): ... class Vals(SetOf): - componentType: _Any + componentType: AttributeValue class ValsAtLeast1(SetOf): - componentType: _Any - subtypeSpec: _Any + componentType: AttributeValue + subtypeSpec: ConstraintsIntersection class PartialAttribute(Sequence): - componentType: _Any + componentType: NamedTypes class Attribute(Sequence): - componentType: _Any + componentType: NamedTypes class AttributeList(SequenceOf): - componentType: _Any + componentType: Attribute class Simple(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class Credentials(OctetString): encoding: str class SaslCredentials(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class SicilyPackageDiscovery(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class SicilyNegotiate(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class SicilyResponse(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class AuthenticationChoice(Choice): - componentType: _Any + componentType: NamedTypes class Version(Integer): - subtypeSpec: _Any + subtypeSpec: ConstraintsIntersection class ResultCode(Enumerated): - namedValues: _Any - subTypeSpec: _Any + namedValues: NamedValues + subTypeSpec: ConstraintsIntersection class URI(LDAPString): ... class Referral(SequenceOf): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: URI class ServerSaslCreds(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class LDAPResult(Sequence): - componentType: _Any + componentType: NamedTypes class Criticality(Boolean): defaultValue: bool @@ -117,207 +113,209 @@ class ControlValue(OctetString): encoding: str class Control(Sequence): - componentType: _Any + componentType: NamedTypes class Controls(SequenceOf): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: Control class Scope(Enumerated): - namedValues: _Any + namedValues: NamedValues class DerefAliases(Enumerated): - namedValues: _Any + namedValues: NamedValues class TypesOnly(Boolean): ... class Selector(LDAPString): ... class AttributeSelection(SequenceOf): - componentType: _Any + componentType: Selector class MatchingRule(MatchingRuleId): - tagSet: _Any + tagSet: TagSet class Type(AttributeDescription): - tagSet: _Any + tagSet: TagSet class MatchValue(AssertionValue): - tagSet: _Any + tagSet: TagSet class DnAttributes(Boolean): - tagSet: _Any - defaultValue: _Any + tagSet: TagSet + defaultValue: Boolean class MatchingRuleAssertion(Sequence): - componentType: _Any + componentType: NamedTypes class Initial(AssertionValue): - tagSet: _Any + tagSet: TagSet class Any(AssertionValue): - tagSet: _Any + tagSet: TagSet class Final(AssertionValue): - tagSet: _Any + tagSet: TagSet class Substring(Choice): - componentType: _Any + componentType: NamedTypes class Substrings(SequenceOf): - subtypeSpec: _Any - componentType: _Any + subtypeSpec: ConstraintsIntersection + componentType: Substring class SubstringFilter(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class And(SetOf): - tagSet: _Any - subtypeSpec: _Any + tagSet: TagSet + subtypeSpec: ConstraintsIntersection + componentType: Filter class Or(SetOf): - tagSet: _Any - subtypeSpec: _Any + tagSet: TagSet + subtypeSpec: ConstraintsIntersection + componentType: Filter class Not(Choice): ... class EqualityMatch(AttributeValueAssertion): - tagSet: _Any + tagSet: TagSet class GreaterOrEqual(AttributeValueAssertion): - tagSet: _Any + tagSet: TagSet class LessOrEqual(AttributeValueAssertion): - tagSet: _Any + tagSet: TagSet class Present(AttributeDescription): - tagSet: _Any + tagSet: TagSet class ApproxMatch(AttributeValueAssertion): - tagSet: _Any + tagSet: TagSet class ExtensibleMatch(MatchingRuleAssertion): - tagSet: _Any + tagSet: TagSet class Filter(Choice): - componentType: _Any + componentType: NamedTypes class PartialAttributeList(SequenceOf): - componentType: _Any + componentType: PartialAttribute class Operation(Enumerated): - namedValues: _Any + namedValues: NamedValues class Change(Sequence): - componentType: _Any + componentType: NamedTypes class Changes(SequenceOf): - componentType: _Any + componentType: Change class DeleteOldRDN(Boolean): ... class NewSuperior(LDAPDN): - tagSet: _Any + tagSet: TagSet class RequestName(LDAPOID): - tagSet: _Any + tagSet: TagSet class RequestValue(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class ResponseName(LDAPOID): - tagSet: _Any + tagSet: TagSet class ResponseValue(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class IntermediateResponseName(LDAPOID): - tagSet: _Any + tagSet: TagSet class IntermediateResponseValue(OctetString): - tagSet: _Any + tagSet: TagSet encoding: str class BindRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class BindResponse(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class UnbindRequest(Null): - tagSet: _Any + tagSet: TagSet class SearchRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class SearchResultReference(SequenceOf): - tagSet: _Any - subtypeSpec: _Any - componentType: _Any + tagSet: TagSet + subtypeSpec: ConstraintsIntersection + componentType: URI class SearchResultEntry(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class SearchResultDone(LDAPResult): - tagSet: _Any + tagSet: TagSet class ModifyRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class ModifyResponse(LDAPResult): - tagSet: _Any + tagSet: TagSet class AddRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class AddResponse(LDAPResult): - tagSet: _Any + tagSet: TagSet class DelRequest(LDAPDN): - tagSet: _Any + tagSet: TagSet class DelResponse(LDAPResult): - tagSet: _Any + tagSet: TagSet class ModifyDNRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class ModifyDNResponse(LDAPResult): - tagSet: _Any + tagSet: TagSet class CompareRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class CompareResponse(LDAPResult): - tagSet: _Any + tagSet: TagSet class AbandonRequest(MessageID): - tagSet: _Any + tagSet: TagSet class ExtendedRequest(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class ExtendedResponse(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class IntermediateResponse(Sequence): - tagSet: _Any - componentType: _Any + tagSet: TagSet + componentType: NamedTypes class ProtocolOp(Choice): - componentType: _Any + componentType: NamedTypes class LDAPMessage(Sequence): - componentType: _Any + componentType: NamedTypes diff --git a/stubs/ldap3/ldap3/protocol/rfc4512.pyi b/stubs/ldap3/ldap3/protocol/rfc4512.pyi index 816dfeb2d0a6..8334585e4075 100644 --- a/stubs/ldap3/ldap3/protocol/rfc4512.pyi +++ b/stubs/ldap3/ldap3/protocol/rfc4512.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete def constant_to_class_kind(value): ... def constant_to_attribute_usage(value): ... @@ -9,62 +9,55 @@ def extension_to_tuple(extension_string): ... def list_to_string(list_object): ... class BaseServerInfo: - raw: Any + raw: Incomplete def __init__(self, raw_attributes) -> None: ... @classmethod - def from_json(cls, json_definition, schema: Any | None = ..., custom_formatter: Any | None = ...): ... + def from_json(cls, json_definition, schema=None, custom_formatter=None): ... @classmethod - def from_file(cls, target, schema: Any | None = ..., custom_formatter: Any | None = ...): ... - def to_file(self, target, indent: int = ..., sort: bool = ...) -> None: ... - def to_json(self, indent: int = ..., sort: bool = ...): ... + def from_file(cls, target, schema=None, custom_formatter=None): ... + def to_file(self, target, indent: int = 4, sort: bool = True) -> None: ... + def to_json(self, indent: int = 4, sort: bool = True): ... class DsaInfo(BaseServerInfo): - alt_servers: Any - naming_contexts: Any - supported_controls: Any - supported_extensions: Any - supported_features: Any - supported_ldap_versions: Any - supported_sasl_mechanisms: Any - vendor_name: Any - vendor_version: Any - schema_entry: Any - other: Any + alt_servers: Incomplete + naming_contexts: Incomplete + supported_controls: Incomplete + supported_extensions: Incomplete + supported_features: Incomplete + supported_ldap_versions: Incomplete + supported_sasl_mechanisms: Incomplete + vendor_name: Incomplete + vendor_version: Incomplete + schema_entry: Incomplete + other: Incomplete def __init__(self, attributes, raw_attributes) -> None: ... class SchemaInfo(BaseServerInfo): - schema_entry: Any - create_time_stamp: Any - modify_time_stamp: Any - attribute_types: Any - object_classes: Any - matching_rules: Any - matching_rule_uses: Any - dit_content_rules: Any - dit_structure_rules: Any - name_forms: Any - ldap_syntaxes: Any - other: Any + schema_entry: Incomplete + create_time_stamp: Incomplete + modify_time_stamp: Incomplete + attribute_types: Incomplete + object_classes: Incomplete + matching_rules: Incomplete + matching_rule_uses: Incomplete + dit_content_rules: Incomplete + dit_structure_rules: Incomplete + name_forms: Incomplete + ldap_syntaxes: Incomplete + other: Incomplete def __init__(self, schema_entry, attributes, raw_attributes) -> None: ... def is_valid(self): ... class BaseObjectInfo: - oid: Any - name: Any - description: Any - obsolete: Any - extensions: Any - experimental: Any - raw_definition: Any + oid: Incomplete + name: Incomplete + description: Incomplete + obsolete: Incomplete + extensions: Incomplete + experimental: Incomplete + raw_definition: Incomplete def __init__( - self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + self, oid=None, name=None, description=None, obsolete: bool = False, extensions=None, experimental=None, definition=None ) -> None: ... @property def oid_info(self): ... @@ -72,147 +65,140 @@ class BaseObjectInfo: def from_definition(cls, definitions): ... class MatchingRuleInfo(BaseObjectInfo): - syntax: Any + syntax: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - syntax: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + syntax=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... class MatchingRuleUseInfo(BaseObjectInfo): - apply_to: Any + apply_to: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - apply_to: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + apply_to=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... class ObjectClassInfo(BaseObjectInfo): - superior: Any - kind: Any - must_contain: Any - may_contain: Any + superior: Incomplete + kind: Incomplete + must_contain: Incomplete + may_contain: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - superior: Any | None = ..., - kind: Any | None = ..., - must_contain: Any | None = ..., - may_contain: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + superior=None, + kind=None, + must_contain=None, + may_contain=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... class AttributeTypeInfo(BaseObjectInfo): - superior: Any - equality: Any - ordering: Any - substring: Any - syntax: Any - min_length: Any - single_value: Any - collective: Any - no_user_modification: Any - usage: Any - mandatory_in: Any - optional_in: Any + superior: Incomplete + equality: Incomplete + ordering: Incomplete + substring: Incomplete + syntax: Incomplete + min_length: Incomplete + single_value: Incomplete + collective: Incomplete + no_user_modification: Incomplete + usage: Incomplete + mandatory_in: Incomplete + optional_in: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - superior: Any | None = ..., - equality: Any | None = ..., - ordering: Any | None = ..., - substring: Any | None = ..., - syntax: Any | None = ..., - min_length: Any | None = ..., - single_value: bool = ..., - collective: bool = ..., - no_user_modification: bool = ..., - usage: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + superior=None, + equality=None, + ordering=None, + substring=None, + syntax=None, + min_length=None, + single_value: bool = False, + collective: bool = False, + no_user_modification: bool = False, + usage=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... class LdapSyntaxInfo(BaseObjectInfo): - def __init__( - self, - oid: Any | None = ..., - description: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., - ) -> None: ... + def __init__(self, oid=None, description=None, extensions=None, experimental=None, definition=None) -> None: ... class DitContentRuleInfo(BaseObjectInfo): - auxiliary_classes: Any - must_contain: Any - may_contain: Any - not_contains: Any + auxiliary_classes: Incomplete + must_contain: Incomplete + may_contain: Incomplete + not_contains: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - auxiliary_classes: Any | None = ..., - must_contain: Any | None = ..., - may_contain: Any | None = ..., - not_contains: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + auxiliary_classes=None, + must_contain=None, + may_contain=None, + not_contains=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... class DitStructureRuleInfo(BaseObjectInfo): - superior: Any - name_form: Any + superior: Incomplete + name_form: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - name_form: Any | None = ..., - superior: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + name_form=None, + superior=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... class NameFormInfo(BaseObjectInfo): - object_class: Any - must_contain: Any - may_contain: Any + object_class: Incomplete + must_contain: Incomplete + may_contain: Incomplete def __init__( self, - oid: Any | None = ..., - name: Any | None = ..., - description: Any | None = ..., - obsolete: bool = ..., - object_class: Any | None = ..., - must_contain: Any | None = ..., - may_contain: Any | None = ..., - extensions: Any | None = ..., - experimental: Any | None = ..., - definition: Any | None = ..., + oid=None, + name=None, + description=None, + obsolete: bool = False, + object_class=None, + must_contain=None, + may_contain=None, + extensions=None, + experimental=None, + definition=None, ) -> None: ... diff --git a/stubs/ldap3/ldap3/protocol/rfc4527.pyi b/stubs/ldap3/ldap3/protocol/rfc4527.pyi index eacc393c49c1..bcacd48140af 100644 --- a/stubs/ldap3/ldap3/protocol/rfc4527.pyi +++ b/stubs/ldap3/ldap3/protocol/rfc4527.pyi @@ -1,2 +1,2 @@ -def pre_read_control(attributes, criticality: bool = ...): ... -def post_read_control(attributes, criticality: bool = ...): ... +def pre_read_control(attributes, criticality: bool = False): ... +def post_read_control(attributes, criticality: bool = False): ... diff --git a/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi b/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi index 564c26ab5dc7..32c30e0f7a45 100644 --- a/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi +++ b/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi @@ -1,5 +1,5 @@ def sasl_prep(data): ... -def validate_simple_password(password, accept_empty: bool = ...): ... +def validate_simple_password(password, accept_empty: bool = False): ... def abort_sasl_negotiation(connection, controls): ... def send_sasl_negotiation(connection, controls, payload): ... def random_hex_string(size): ... diff --git a/stubs/ldap3/ldap3/strategy/asyncStream.pyi b/stubs/ldap3/ldap3/strategy/asyncStream.pyi index b0ed1b4fd07e..ece52ea4d10e 100644 --- a/stubs/ldap3/ldap3/strategy/asyncStream.pyi +++ b/stubs/ldap3/ldap3/strategy/asyncStream.pyi @@ -1,17 +1,17 @@ -from typing import Any +from _typeshed import Incomplete from ..strategy.asynchronous import AsyncStrategy class AsyncStreamStrategy(AsyncStrategy): can_stream: bool - line_separator: Any + line_separator: Incomplete all_base64: bool - stream: Any - order: Any - persistent_search_message_id: Any + stream: Incomplete + order: Incomplete + persistent_search_message_id: Incomplete streaming: bool - callback: Any - events: Any + callback: Incomplete + events: Incomplete def __init__(self, ldap_connection) -> None: ... def accumulate_stream(self, message_id, change) -> None: ... def get_stream(self): ... diff --git a/stubs/ldap3/ldap3/strategy/asynchronous.pyi b/stubs/ldap3/ldap3/strategy/asynchronous.pyi index ecc746f863f3..5e8be4de852d 100644 --- a/stubs/ldap3/ldap3/strategy/asynchronous.pyi +++ b/stubs/ldap3/ldap3/strategy/asynchronous.pyi @@ -1,23 +1,24 @@ +from _typeshed import Incomplete from threading import Thread -from typing import Any from ..strategy.base import BaseStrategy class AsyncStrategy(BaseStrategy): class ReceiverSocketThread(Thread): - connection: Any - socket_size: Any + connection: Incomplete + socket_size: Incomplete def __init__(self, ldap_connection) -> None: ... def run(self) -> None: ... + sync: bool no_real_dsa: bool pooled: bool can_stream: bool - receiver: Any - async_lock: Any - event_lock: Any + receiver: Incomplete + async_lock: Incomplete + event_lock: Incomplete def __init__(self, ldap_connection) -> None: ... - def open(self, reset_usage: bool = ..., read_server_info: bool = ...) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... def close(self) -> None: ... def set_event_for_message(self, message_id) -> None: ... def post_send_search(self, message_id): ... diff --git a/stubs/ldap3/ldap3/strategy/base.pyi b/stubs/ldap3/ldap3/strategy/base.pyi index 4c7a07a1a415..bf28ee9f9548 100644 --- a/stubs/ldap3/ldap3/strategy/base.pyi +++ b/stubs/ldap3/ldap3/strategy/base.pyi @@ -1,4 +1,6 @@ -from typing import Any +from _typeshed import Incomplete + +from ..protocol.convert import _ControlSequence unix_socket_available: bool SESSION_TERMINATED_BY_SERVER: str @@ -6,18 +8,18 @@ TRANSACTION_ERROR: str RESPONSE_COMPLETE: str class BaseStrategy: - connection: Any - sync: Any - no_real_dsa: Any - pooled: Any - can_stream: Any - referral_cache: Any + connection: Incomplete + sync: Incomplete + no_real_dsa: Incomplete + pooled: Incomplete + can_stream: Incomplete + referral_cache: Incomplete thread_safe: bool def __init__(self, ldap_connection) -> None: ... - def open(self, reset_usage: bool = ..., read_server_info: bool = ...) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... def close(self) -> None: ... - def send(self, message_type, request, controls: Any | None = ...): ... - def get_response(self, message_id, timeout: Any | None = ..., get_request: bool = ...): ... + def send(self, message_type, request, controls: _ControlSequence | None = None): ... + def get_response(self, message_id, timeout=None, get_request: bool = False): ... @staticmethod def compute_ldap_message_size(data): ... def decode_response(self, ldap_message): ... @@ -25,9 +27,9 @@ class BaseStrategy: @staticmethod def decode_control(control): ... @staticmethod - def decode_control_fast(control, from_server: bool = ...): ... + def decode_control_fast(control, from_server: bool = True): ... @staticmethod - def decode_request(message_type, component, controls: Any | None = ...): ... + def decode_request(message_type, component, controls=None): ... def valid_referral_list(self, referrals): ... def do_next_range_search(self, request, response, attr_name): ... def do_search_on_auto_range(self, request, response): ... diff --git a/stubs/ldap3/ldap3/strategy/ldifProducer.pyi b/stubs/ldap3/ldap3/strategy/ldifProducer.pyi index 7ac55a30b077..36268051577c 100644 --- a/stubs/ldap3/ldap3/strategy/ldifProducer.pyi +++ b/stubs/ldap3/ldap3/strategy/ldifProducer.pyi @@ -1,5 +1,6 @@ -from typing import Any +from _typeshed import Incomplete +from ..protocol.convert import _ControlSequence from .base import BaseStrategy class LdifProducerStrategy(BaseStrategy): @@ -7,13 +8,13 @@ class LdifProducerStrategy(BaseStrategy): no_real_dsa: bool pooled: bool can_stream: bool - line_separator: Any + line_separator: Incomplete all_base64: bool - stream: Any - order: Any + stream: Incomplete + order: Incomplete def __init__(self, ldap_connection) -> None: ... def receiving(self) -> None: ... - def send(self, message_type, request, controls: Any | None = ...): ... + def send(self, message_type, request, controls: _ControlSequence | None = None): ... def post_send_single_response(self, message_id): ... def post_send_search(self, message_id) -> None: ... def accumulate_stream(self, fragment) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/mockAsync.pyi b/stubs/ldap3/ldap3/strategy/mockAsync.pyi index 2acd74751413..9ff38e9dd117 100644 --- a/stubs/ldap3/ldap3/strategy/mockAsync.pyi +++ b/stubs/ldap3/ldap3/strategy/mockAsync.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete from .asynchronous import AsyncStrategy from .mockBase import MockBaseStrategy @@ -6,6 +6,6 @@ from .mockBase import MockBaseStrategy class MockAsyncStrategy(MockBaseStrategy, AsyncStrategy): def __init__(self, ldap_connection) -> None: ... def post_send_search(self, payload): ... - bound: Any + bound: Incomplete def post_send_single_response(self, payload): ... - def get_response(self, message_id, timeout: Any | None = ..., get_request: bool = ...): ... + def get_response(self, message_id, timeout=None, get_request: bool = False): ... diff --git a/stubs/ldap3/ldap3/strategy/mockBase.pyi b/stubs/ldap3/ldap3/strategy/mockBase.pyi index c4b0c3483047..36042b449036 100644 --- a/stubs/ldap3/ldap3/strategy/mockBase.pyi +++ b/stubs/ldap3/ldap3/strategy/mockBase.pyi @@ -1,27 +1,29 @@ -from typing import Any +from _typeshed import Incomplete -SEARCH_CONTROLS: Any +from ..protocol.convert import _ControlSequence + +SEARCH_CONTROLS: Incomplete SERVER_ENCODING: str def random_cookie(): ... class PagedSearchSet: - size: Any - response: Any - cookie: Any + size: Incomplete + response: Incomplete + cookie: Incomplete sent: int done: bool def __init__(self, response, size, criticality) -> None: ... - def next(self, size: Any | None = ...): ... + def next(self, size=None): ... class MockBaseStrategy: - entries: Any + entries: Incomplete no_real_dsa: bool - bound: Any - custom_validators: Any - operational_attributes: Any + bound: Incomplete + custom_validators: Incomplete + operational_attributes: Incomplete def __init__(self) -> None: ... - def add_entry(self, dn, attributes, validate: bool = ...): ... + def add_entry(self, dn, attributes, validate: bool = True): ... def remove_entry(self, dn): ... def entries_from_json(self, json_entry_file) -> None: ... def mock_bind(self, request_message, controls): ... @@ -34,4 +36,4 @@ class MockBaseStrategy: def mock_extended(self, request_message, controls): ... def evaluate_filter_node(self, node, candidates): ... def equal(self, dn, attribute_type, value_to_check): ... - def send(self, message_type, request, controls: Any | None = ...): ... + def send(self, message_type, request, controls: _ControlSequence | None = None): ... diff --git a/stubs/ldap3/ldap3/strategy/mockSync.pyi b/stubs/ldap3/ldap3/strategy/mockSync.pyi index dcfd12d8958b..7d8b07ec7c3a 100644 --- a/stubs/ldap3/ldap3/strategy/mockSync.pyi +++ b/stubs/ldap3/ldap3/strategy/mockSync.pyi @@ -1,4 +1,4 @@ -from typing import Any +from _typeshed import Incomplete from .mockBase import MockBaseStrategy from .sync import SyncStrategy @@ -6,5 +6,5 @@ from .sync import SyncStrategy class MockSyncStrategy(MockBaseStrategy, SyncStrategy): def __init__(self, ldap_connection) -> None: ... def post_send_search(self, payload): ... - bound: Any + bound: Incomplete def post_send_single_response(self, payload): ... diff --git a/stubs/ldap3/ldap3/strategy/restartable.pyi b/stubs/ldap3/ldap3/strategy/restartable.pyi index d38804ee0f85..4ac56e980728 100644 --- a/stubs/ldap3/ldap3/strategy/restartable.pyi +++ b/stubs/ldap3/ldap3/strategy/restartable.pyi @@ -1,5 +1,6 @@ -from typing import Any +from _typeshed import Incomplete +from ..protocol.convert import _ControlSequence from .sync import SyncStrategy class RestartableStrategy(SyncStrategy): @@ -7,12 +8,12 @@ class RestartableStrategy(SyncStrategy): no_real_dsa: bool pooled: bool can_stream: bool - restartable_sleep_time: Any - restartable_tries: Any - exception_history: Any + restartable_sleep_time: Incomplete + restartable_tries: Incomplete + exception_history: Incomplete def __init__(self, ldap_connection) -> None: ... - def open(self, reset_usage: bool = ..., read_server_info: bool = ...) -> None: ... - def send(self, message_type, request, controls: Any | None = ...): ... + def open(self, reset_usage: bool = False, read_server_info: bool = True) -> None: ... + def send(self, message_type, request, controls: _ControlSequence | None = None): ... def post_send_single_response(self, message_id): ... def post_send_search(self, message_id): ... def get_stream(self) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/reusable.pyi b/stubs/ldap3/ldap3/strategy/reusable.pyi index cc5bfad4101c..7b5159b57224 100644 --- a/stubs/ldap3/ldap3/strategy/reusable.pyi +++ b/stubs/ldap3/ldap3/strategy/reusable.pyi @@ -1,6 +1,7 @@ +from _typeshed import Incomplete from threading import Thread -from typing import Any +from ..protocol.convert import _ControlSequence from .base import BaseStrategy TERMINATE_REUSABLE: str @@ -10,26 +11,27 @@ BOGUS_EXTENDED: int BOGUS_ABANDON: int class ReusableStrategy(BaseStrategy): - pools: Any + pools: Incomplete def receiving(self) -> None: ... def get_stream(self) -> None: ... def set_stream(self, value) -> None: ... + class ConnectionPool: def __new__(cls, connection): ... - name: Any - master_connection: Any - workers: Any - pool_size: Any - lifetime: Any - keepalive: Any - request_queue: Any + name: Incomplete + master_connection: Incomplete + workers: Incomplete + pool_size: Incomplete + lifetime: Incomplete + keepalive: Incomplete + request_queue: Incomplete open_pool: bool bind_pool: bool tls_pool: bool counter: int - terminated_usage: Any + terminated_usage: Incomplete terminated: bool - pool_lock: Any + pool_lock: Incomplete started: bool def __init__(self, connection) -> None: ... def get_info_from_server(self) -> None: ... @@ -37,35 +39,38 @@ class ReusableStrategy(BaseStrategy): def start_pool(self): ... def create_pool(self) -> None: ... def terminate_pool(self) -> None: ... + class PooledConnectionThread(Thread): daemon: bool - worker: Any - master_connection: Any + worker: Incomplete + master_connection: Incomplete def __init__(self, worker, master_connection) -> None: ... def run(self) -> None: ... + class PooledConnectionWorker: - master_connection: Any - request_queue: Any + master_connection: Incomplete + request_queue: Incomplete running: bool busy: bool get_info_from_server: bool - connection: Any - creation_time: Any + connection: Incomplete + creation_time: Incomplete task_counter: int - thread: Any - worker_lock: Any + thread: Incomplete + worker_lock: Incomplete def __init__(self, connection, request_queue) -> None: ... def new_connection(self) -> None: ... + sync: bool no_real_dsa: bool pooled: bool can_stream: bool - pool: Any + pool: Incomplete def __init__(self, ldap_connection) -> None: ... - def open(self, reset_usage: bool = ..., read_server_info: bool = ...) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... def terminate(self) -> None: ... - def send(self, message_type, request, controls: Any | None = ...): ... + def send(self, message_type, request, controls: _ControlSequence | None = None): ... def validate_bind(self, controls): ... - def get_response(self, counter, timeout: Any | None = ..., get_request: bool = ...): ... + def get_response(self, counter, timeout=None, get_request: bool = False): ... def post_send_single_response(self, counter): ... def post_send_search(self, counter): ... diff --git a/stubs/ldap3/ldap3/strategy/sync.pyi b/stubs/ldap3/ldap3/strategy/sync.pyi index a1a8460902e2..c270ecb6dfc5 100644 --- a/stubs/ldap3/ldap3/strategy/sync.pyi +++ b/stubs/ldap3/ldap3/strategy/sync.pyi @@ -1,17 +1,17 @@ -from typing import Any +from _typeshed import Incomplete from ..strategy.base import BaseStrategy -LDAP_MESSAGE_TEMPLATE: Any +LDAP_MESSAGE_TEMPLATE: Incomplete class SyncStrategy(BaseStrategy): sync: bool no_real_dsa: bool pooled: bool can_stream: bool - socket_size: Any + socket_size: Incomplete def __init__(self, ldap_connection) -> None: ... - def open(self, reset_usage: bool = ..., read_server_info: bool = ...) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... def receiving(self): ... def post_send_single_response(self, message_id): ... def post_send_search(self, message_id): ... diff --git a/stubs/ldap3/ldap3/utils/asn1.pyi b/stubs/ldap3/ldap3/utils/asn1.pyi index 859a9b958630..11d682cb54e6 100644 --- a/stubs/ldap3/ldap3/utils/asn1.pyi +++ b/stubs/ldap3/ldap3/utils/asn1.pyi @@ -1,37 +1,52 @@ -from typing import Any +from _typeshed import Incomplete, IndexableBuffer, SliceableBuffer, Unused +from collections.abc import Callable, Mapping +from typing import Any, Final, TypeAlias, TypeVar, overload -# Enable when pyasn1 gets stubs: -# from pyasn1.codec.ber.encoder import AbstractItemEncoder, BooleanEncoder -AbstractItemEncoder = Any -BooleanEncoder = Any +from pyasn1.codec.ber.encoder import AbstractItemEncoder +from pyasn1.type.tag import TagSet -CLASSES: Any +# Use _typeshed._SupportsGetItemBuffer after PEP 688 +_SupportsGetItemBuffer: TypeAlias = SliceableBuffer | IndexableBuffer +_R = TypeVar("_R") +_B = TypeVar("_B", bound=_SupportsGetItemBuffer) +# The possible return type is a union of all other decode methods, ie: AnyOf[Incomplete | bool] +_AllDecodersReturnType: TypeAlias = Any + +CLASSES: Final[dict[tuple[bool, bool], int]] class LDAPBooleanEncoder(AbstractItemEncoder): supportIndefLenMode: bool # Requires pyasn1 > 0.3.7 - def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + def encodeValue(self, value: bool | int, asn1Spec: Unused, encodeFun: Unused, **options: Unused): ... -customTagMap: Any -customTypeMap: Any +customTagMap: dict[TagSet, AbstractItemEncoder] +customTypeMap: dict[int, AbstractItemEncoder] def compute_ber_size(data): ... def decode_message_fast(message): ... -def decode_sequence(message, start, stop, context_decoders: Any | None = ...): ... -def decode_integer(message, start, stop, context_decoders: Any | None = ...): ... -def decode_octet_string(message, start, stop, context_decoders: Any | None = ...): ... -def decode_boolean(message, start, stop, context_decoders: Any | None = ...): ... -def decode_bind_response(message, start, stop, context_decoders: Any | None = ...): ... -def decode_extended_response(message, start, stop, context_decoders: Any | None = ...): ... -def decode_intermediate_response(message, start, stop, context_decoders: Any | None = ...): ... -def decode_controls(message, start, stop, context_decoders: Any | None = ...): ... + +@overload +def decode_sequence(message: _B, start: int, stop: int, context_decoders: Mapping[int, Callable[[_B, int, int], _R]]) -> _R: ... +@overload +def decode_sequence( + message: _SupportsGetItemBuffer, start: int, stop: int, context_decoders: None = None +) -> _AllDecodersReturnType: ... + +def decode_integer(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_octet_string(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_boolean(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_bind_response(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_extended_response(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_intermediate_response(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_controls(message, start: int, stop: int, context_decoders: Unused = None): ... def ldap_result_to_dict_fast(response): ... def get_byte(x): ... def get_bytes(x): ... -DECODERS: Any -BIND_RESPONSE_CONTEXT: Any -EXTENDED_RESPONSE_CONTEXT: Any -INTERMEDIATE_RESPONSE_CONTEXT: Any -LDAP_MESSAGE_CONTEXT: Any -CONTROLS_CONTEXT: Any +# The possible return type is a union of all other decode methods, ie: AnyOf[Incomplete | bool] +DECODERS: dict[tuple[int, int], Callable[..., _AllDecodersReturnType]] +BIND_RESPONSE_CONTEXT: dict[int, Callable[..., Incomplete]] +EXTENDED_RESPONSE_CONTEXT: dict[int, Callable[..., Incomplete]] +INTERMEDIATE_RESPONSE_CONTEXT: dict[int, Callable[..., Incomplete]] +LDAP_MESSAGE_CONTEXT: dict[int, Callable[..., Incomplete]] +CONTROLS_CONTEXT: dict[int, Callable[..., Incomplete]] diff --git a/stubs/ldap3/ldap3/utils/ciDict.pyi b/stubs/ldap3/ldap3/utils/ciDict.pyi index 2564fc656c57..ff9abffa557e 100644 --- a/stubs/ldap3/ldap3/utils/ciDict.pyi +++ b/stubs/ldap3/ldap3/utils/ciDict.pyi @@ -1,29 +1,29 @@ from collections.abc import MutableMapping -from typing import Any, Generic, TypeVar +from typing import TypeVar _KT = TypeVar("_KT") _VT = TypeVar("_VT") -class CaseInsensitiveDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): - def __init__(self, other: Any | None = ..., **kwargs) -> None: ... +class CaseInsensitiveDict(MutableMapping[_KT, _VT]): + def __init__(self, other=None, **kwargs) -> None: ... def __contains__(self, item): ... def __delitem__(self, key) -> None: ... def __setitem__(self, key, item) -> None: ... def __getitem__(self, key): ... def __iter__(self): ... - def __len__(self): ... + def __len__(self) -> int: ... def keys(self): ... def values(self): ... def items(self): ... def __eq__(self, other): ... def copy(self): ... -class CaseInsensitiveWithAliasDict(CaseInsensitiveDict[_KT, _VT], Generic[_KT, _VT]): - def __init__(self, other: Any | None = ..., **kwargs) -> None: ... +class CaseInsensitiveWithAliasDict(CaseInsensitiveDict[_KT, _VT]): + def __init__(self, other=None, **kwargs) -> None: ... def aliases(self): ... def __setitem__(self, key, value) -> None: ... def __delitem__(self, key) -> None: ... - def set_alias(self, key, alias, ignore_duplicates: bool = ...) -> None: ... + def set_alias(self, key, alias, ignore_duplicates: bool = False) -> None: ... def remove_alias(self, alias) -> None: ... def __getitem__(self, key): ... def copy(self): ... diff --git a/stubs/ldap3/ldap3/utils/config.pyi b/stubs/ldap3/ldap3/utils/config.pyi index 80971d5fc15c..e16df54889f5 100644 --- a/stubs/ldap3/ldap3/utils/config.pyi +++ b/stubs/ldap3/ldap3/utils/config.pyi @@ -1,6 +1,6 @@ -from typing import Any +from _typeshed import Incomplete -PARAMETERS: Any +PARAMETERS: Incomplete def get_config_parameter(parameter): ... def set_config_parameter(parameter, value) -> None: ... diff --git a/stubs/ldap3/ldap3/utils/conv.pyi b/stubs/ldap3/ldap3/utils/conv.pyi index 280e2085cfec..a31439c08e46 100644 --- a/stubs/ldap3/ldap3/utils/conv.pyi +++ b/stubs/ldap3/ldap3/utils/conv.pyi @@ -1,14 +1,12 @@ -from typing import Any - -def to_unicode(obj: float | bytes | str, encoding: str | None = ..., from_server: bool = ...) -> str: ... -def to_raw(obj, encoding: str = ...): ... -def escape_filter_chars(text: float | bytes | str, encoding: str | None = ...) -> str: ... -def unescape_filter_chars(text, encoding: Any | None = ...): ... +def to_unicode(obj: float | bytes | str, encoding: str | None = None, from_server: bool = False) -> str: ... +def to_raw(obj, encoding: str = "utf-8"): ... +def escape_filter_chars(text: float | bytes | str, encoding: str | None = None) -> str: ... +def unescape_filter_chars(text, encoding=None): ... def escape_bytes(bytes_value: str | bytes) -> str: ... def prepare_for_stream(value): ... def json_encode_b64(obj): ... def check_json_dict(json_dict) -> None: ... def json_hook(obj): ... -def format_json(obj, iso_format: bool = ...): ... +def format_json(obj, iso_format: bool = False): ... def is_filter_escaped(text): ... def ldap_escape_to_bytes(text): ... diff --git a/stubs/ldap3/ldap3/utils/dn.pyi b/stubs/ldap3/ldap3/utils/dn.pyi index dab0cdffd451..0b5c559c604f 100644 --- a/stubs/ldap3/ldap3/utils/dn.pyi +++ b/stubs/ldap3/ldap3/utils/dn.pyi @@ -3,9 +3,9 @@ STATE_ESCAPE: int STATE_ESCAPE_HEX: int def to_dn( - iterator, decompose: bool = ..., remove_space: bool = ..., space_around_equal: bool = ..., separate_rdn: bool = ... + iterator, decompose: bool = False, remove_space: bool = False, space_around_equal: bool = False, separate_rdn: bool = False ): ... -def parse_dn(dn, escape: bool = ..., strip: bool = ...): ... -def safe_dn(dn, decompose: bool = ..., reverse: bool = ...): ... -def safe_rdn(dn, decompose: bool = ...): ... +def parse_dn(dn, escape: bool = False, strip: bool = False): ... +def safe_dn(dn, decompose: bool = False, reverse: bool = False): ... +def safe_rdn(dn, decompose: bool = False): ... def escape_rdn(rdn: str) -> str: ... diff --git a/stubs/ldap3/ldap3/utils/hashed.pyi b/stubs/ldap3/ldap3/utils/hashed.pyi index 74734cc6339e..86c0f721e2d6 100644 --- a/stubs/ldap3/ldap3/utils/hashed.pyi +++ b/stubs/ldap3/ldap3/utils/hashed.pyi @@ -1,6 +1,6 @@ -from typing import Any +from _typeshed import Incomplete -algorithms_table: Any -salted_table: Any +algorithms_table: Incomplete +salted_table: Incomplete -def hashed(algorithm, value, salt: Any | None = ..., raw: bool = ..., encoding: str = ...): ... +def hashed(algorithm, value, salt=None, raw: bool = False, encoding: str = "utf-8"): ... diff --git a/stubs/ldap3/ldap3/utils/log.pyi b/stubs/ldap3/ldap3/utils/log.pyi index a5c47f7bdf4f..9ab59fda4045 100644 --- a/stubs/ldap3/ldap3/utils/log.pyi +++ b/stubs/ldap3/ldap3/utils/log.pyi @@ -1,5 +1,5 @@ +from _typeshed import Incomplete from logging import NullHandler as NullHandler -from typing import Any OFF: int ERROR: int @@ -7,12 +7,12 @@ BASIC: int PROTOCOL: int NETWORK: int EXTENDED: int -DETAIL_LEVELS: Any +DETAIL_LEVELS: Incomplete def get_detail_level_name(level_name): ... def log(detail, message, *args) -> None: ... def log_enabled(detail): ... -def set_library_log_hide_sensitive_data(hide: bool = ...) -> None: ... +def set_library_log_hide_sensitive_data(hide: bool = True) -> None: ... def get_library_log_hide_sensitive_data(): ... def set_library_log_activation_level(logging_level) -> None: ... def get_library_log_activation_lavel(): ... @@ -22,4 +22,4 @@ def set_library_log_detail_level(detail) -> None: ... def get_library_log_detail_level(): ... def format_ldap_message(message, prefix): ... -logger: Any +logger: Incomplete diff --git a/stubs/ldap3/ldap3/utils/ntlm.pyi b/stubs/ldap3/ldap3/utils/ntlm.pyi index 6e122f3a778d..37045dcbb0d8 100644 --- a/stubs/ldap3/ldap3/utils/ntlm.pyi +++ b/stubs/ldap3/ldap3/utils/ntlm.pyi @@ -1,6 +1,6 @@ -from typing import Any +from _typeshed import Incomplete -oem_encoding: Any +oem_encoding: Incomplete NTLM_SIGNATURE: bytes NTLM_MESSAGE_TYPE_NTLM_NEGOTIATE: int NTLM_MESSAGE_TYPE_NTLM_CHALLENGE: int @@ -27,7 +27,7 @@ FLAG_NEGOTIATE_SIGN: int FLAG_REQUEST_TARGET: int FLAG_NEGOTIATE_OEM: int FLAG_NEGOTIATE_UNICODE: int -FLAG_TYPES: Any +FLAG_TYPES: Incomplete AV_END_OF_LIST: int AV_NETBIOS_COMPUTER_NAME: int AV_NETBIOS_DOMAIN_NAME: int @@ -39,60 +39,60 @@ AV_TIMESTAMP: int AV_SINGLE_HOST_DATA: int AV_TARGET_NAME: int AV_CHANNEL_BINDINGS: int -AV_TYPES: Any +AV_TYPES: Incomplete AV_FLAG_CONSTRAINED: int AV_FLAG_INTEGRITY: int AV_FLAG_TARGET_SPN_UNTRUSTED: int -AV_FLAG_TYPES: Any +AV_FLAG_TYPES: Incomplete -def pack_windows_version(debug: bool = ...): ... +def pack_windows_version(debug: bool = False): ... def unpack_windows_version(version_message): ... class NtlmClient: client_config_flags: int - exported_session_key: Any - negotiated_flags: Any - user_name: Any - user_domain: Any - no_lm_response_ntlm_v1: Any + exported_session_key: Incomplete + negotiated_flags: Incomplete + user_name: Incomplete + user_domain: Incomplete + no_lm_response_ntlm_v1: Incomplete client_blocked: bool - client_block_exceptions: Any - client_require_128_bit_encryption: Any - max_life_time: Any - client_signing_key: Any - client_sealing_key: Any - sequence_number: Any - server_sealing_key: Any - server_signing_key: Any + client_block_exceptions: Incomplete + client_require_128_bit_encryption: Incomplete + max_life_time: Incomplete + client_signing_key: Incomplete + client_sealing_key: Incomplete + sequence_number: Incomplete + server_sealing_key: Incomplete + server_signing_key: Incomplete integrity: bool replay_detect: bool sequence_detect: bool confidentiality: bool datagram: bool identity: bool - client_supplied_target_name: Any - client_channel_binding_unhashed: Any - unverified_target_name: Any - server_challenge: Any - server_target_name: Any - server_target_info: Any - server_version: Any - server_av_netbios_computer_name: Any - server_av_netbios_domain_name: Any - server_av_dns_computer_name: Any - server_av_dns_domain_name: Any - server_av_dns_forest_name: Any - server_av_target_name: Any - server_av_flags: Any - server_av_timestamp: Any - server_av_single_host_data: Any - server_av_channel_bindings: Any - server_av_flag_constrained: Any - server_av_flag_integrity: Any - server_av_flag_target_spn_untrusted: Any - current_encoding: Any - client_challenge: Any - server_target_info_raw: Any + client_supplied_target_name: Incomplete + client_channel_binding_unhashed: Incomplete + unverified_target_name: Incomplete + server_challenge: Incomplete + server_target_name: Incomplete + server_target_info: Incomplete + server_version: Incomplete + server_av_netbios_computer_name: Incomplete + server_av_netbios_domain_name: Incomplete + server_av_dns_computer_name: Incomplete + server_av_dns_domain_name: Incomplete + server_av_dns_forest_name: Incomplete + server_av_target_name: Incomplete + server_av_flags: Incomplete + server_av_timestamp: Incomplete + server_av_single_host_data: Incomplete + server_av_channel_bindings: Incomplete + server_av_flag_constrained: Incomplete + server_av_flag_integrity: Incomplete + server_av_flag_target_spn_untrusted: Incomplete + current_encoding: Incomplete + client_challenge: Incomplete + server_target_info_raw: Incomplete def __init__(self, domain, user_name, password) -> None: ... def get_client_flag(self, flag): ... def get_negotiated_flag(self, flag): ... diff --git a/stubs/ldap3/ldap3/utils/repr.pyi b/stubs/ldap3/ldap3/utils/repr.pyi index f2c58e20ed4d..41c269d19898 100644 --- a/stubs/ldap3/ldap3/utils/repr.pyi +++ b/stubs/ldap3/ldap3/utils/repr.pyi @@ -1,5 +1,5 @@ -from typing import Any +from _typeshed import Incomplete -repr_encoding: Any +repr_encoding: Incomplete def to_stdout_encoding(value): ... diff --git a/stubs/ldap3/ldap3/version.pyi b/stubs/ldap3/ldap3/version.pyi index 50be840c1d09..5939bd051b4b 100644 --- a/stubs/ldap3/ldap3/version.pyi +++ b/stubs/ldap3/ldap3/version.pyi @@ -1,3 +1,9 @@ -__url__: str -__description__: str -__status__: str +from typing import Final + +__version__: Final[str] +__author__: Final[str] +__email__: Final[str] +__url__: Final[str] +__description__: Final[str] +__status__: Final[str] +__license__: Final[str] diff --git a/stubs/lunardate/METADATA.toml b/stubs/lunardate/METADATA.toml new file mode 100644 index 000000000000..87e20fe9932b --- /dev/null +++ b/stubs/lunardate/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.3.*" +upstream-repository = "https://github.com/lidaobing/python-lunardate" diff --git a/stubs/lunardate/lunardate.pyi b/stubs/lunardate/lunardate.pyi new file mode 100644 index 000000000000..2cb4e87ea2ec --- /dev/null +++ b/stubs/lunardate/lunardate.pyi @@ -0,0 +1,53 @@ +import datetime +from typing import Final, SupportsIndex, overload +from typing_extensions import deprecated + +__version__: Final[str] +__all__ = ["LunarDate"] + +class LunarDate: + year: int + month: int + day: int + is_leap_month: bool + def __init__(self, year: int, month: int, day: int, is_leap_month: bool | None = False) -> None: ... + @property + @deprecated("The `isLeapMonth` is deprecated since v0.3.0. Use `is_leap_month` instead.") + def isLeapMonth(self) -> bool: ... + @staticmethod + @deprecated("The `leapMonthForYear` is deprecated since v0.3.0. Use `leap_month_for_year` instead.") + def leapMonthForYear(year: int) -> int | None: ... + @staticmethod + def leap_month_for_year(year: int) -> int | None: ... + @staticmethod + @deprecated("The `fromSolarDate` is deprecated since v0.3.0. Use `from_solar_date` instead.") + def fromSolarDate(year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> LunarDate: ... + @staticmethod + def from_solar_date(year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> LunarDate: ... + @deprecated("The `toSolarDate` is deprecated since v0.3.0. Use `to_solar_date` instead.") + def toSolarDate(self) -> datetime.date: ... + def to_solar_date(self) -> datetime.date: ... + + @overload + def __sub__(self, other: LunarDate | datetime.date) -> datetime.timedelta: ... + @overload + def __sub__(self, other: datetime.timedelta) -> LunarDate: ... + + def __rsub__(self, other: datetime.date) -> datetime.timedelta: ... + def __add__(self, other: datetime.timedelta) -> LunarDate: ... + def __radd__(self, other: datetime.timedelta) -> LunarDate: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: LunarDate | datetime.date) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __ge__(self, other: LunarDate | datetime.date) -> bool: ... + @classmethod + def today(cls) -> LunarDate: ... + +YEAR_INFOS: Final[list[int]] + +def year_info_to_year_day(year_info: int) -> int: ... + +YEAR_DAYS: Final[list[int]] + +def day_to_lunar_date(offset: int) -> None: ... diff --git a/stubs/lupa/METADATA.toml b/stubs/lupa/METADATA.toml new file mode 100644 index 000000000000..9ab84dd92ab1 --- /dev/null +++ b/stubs/lupa/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.8.*" +upstream-repository = "https://github.com/scoder/lupa" diff --git a/stubs/lupa/lupa/__init__.pyi b/stubs/lupa/lupa/__init__.pyi new file mode 100644 index 000000000000..6eb98c022432 --- /dev/null +++ b/stubs/lupa/lupa/__init__.pyi @@ -0,0 +1,17 @@ +from .lua55 import * + +__all__ = [ + # from lua55 (newest lib) + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] diff --git a/stubs/lupa/lupa/lua51.pyi b/stubs/lupa/lupa/lua51.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua51.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua52.pyi b/stubs/lupa/lupa/lua52.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua52.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua53.pyi b/stubs/lupa/lupa/lua53.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua53.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua54.pyi b/stubs/lupa/lupa/lua54.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua54.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua55.pyi b/stubs/lupa/lupa/lua55.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua55.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/luajit20.pyi b/stubs/lupa/lupa/luajit20.pyi new file mode 100644 index 000000000000..fdf3fe3d448e --- /dev/null +++ b/stubs/lupa/lupa/luajit20.pyi @@ -0,0 +1,96 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterator +from typing import Any, Final, Generic, TypeVar, type_check_only +from typing_extensions import disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaIter: + def __iter__(self) -> Iterator[object]: ... + +@type_check_only +class _LuaTable: + def keys(self) -> _LuaIter: ... + def values(self) -> _LuaIter: ... + def items(self) -> _LuaIter: ... + +@type_check_only +class _LuaNoGC: ... + +@type_check_only +class _LuaObject: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + # @classmethod + # def __cinit__(cls, unpack_return_tuples: bool) -> None: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = ...) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/luajit21.pyi b/stubs/lupa/lupa/luajit21.pyi new file mode 100644 index 000000000000..fdf3fe3d448e --- /dev/null +++ b/stubs/lupa/lupa/luajit21.pyi @@ -0,0 +1,96 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterator +from typing import Any, Final, Generic, TypeVar, type_check_only +from typing_extensions import disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaIter: + def __iter__(self) -> Iterator[object]: ... + +@type_check_only +class _LuaTable: + def keys(self) -> _LuaIter: ... + def values(self) -> _LuaIter: ... + def items(self) -> _LuaIter: ... + +@type_check_only +class _LuaNoGC: ... + +@type_check_only +class _LuaObject: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + # @classmethod + # def __cinit__(cls, unpack_return_tuples: bool) -> None: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = ...) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/version.pyi b/stubs/lupa/lupa/version.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/lupa/lupa/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/lzstring/@tests/stubtest_allowlist.txt b/stubs/lzstring/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3f24b90e86d4 --- /dev/null +++ b/stubs/lzstring/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Internal implementation details that are intentionally missing from stub +lzstring.keyStrBase64 +lzstring.keyStrUriSafe +lzstring.baseReverseDic +lzstring.Object +lzstring.getBaseValue diff --git a/stubs/lzstring/METADATA.toml b/stubs/lzstring/METADATA.toml new file mode 100644 index 000000000000..22e4f392e123 --- /dev/null +++ b/stubs/lzstring/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.0.*" +upstream-repository = "https://github.com/gkovacs/lz-string-python" diff --git a/stubs/lzstring/lzstring/__init__.pyi b/stubs/lzstring/lzstring/__init__.pyi new file mode 100644 index 000000000000..8d66d865bd76 --- /dev/null +++ b/stubs/lzstring/lzstring/__init__.pyi @@ -0,0 +1,17 @@ +class LZString: + @staticmethod + def compress(uncompressed: str | None) -> str: ... + @staticmethod + def compressToUTF16(uncompressed: str | None) -> str: ... + @staticmethod + def compressToBase64(uncompressed: str | None) -> str: ... + @staticmethod + def compressToEncodedURIComponent(uncompressed: str | None) -> str: ... + @staticmethod + def decompress(compressed: str | None) -> str | None: ... + @staticmethod + def decompressFromUTF16(compressed: str | None) -> str | None: ... + @staticmethod + def decompressFromBase64(compressed: str | None) -> str | None: ... + @staticmethod + def decompressFromEncodedURIComponent(compressed: str | None) -> str | None: ... diff --git a/stubs/m3u8/@tests/stubtest_allowlist.txt b/stubs/m3u8/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7842199c24e4 --- /dev/null +++ b/stubs/m3u8/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +# type check only +m3u8.httpclient.HTTPSHandler.__new__ +# internal functions and attributes +m3u8.parser.get_segment_custom_value +m3u8.parser.save_segment_custom_value diff --git a/stubs/m3u8/METADATA.toml b/stubs/m3u8/METADATA.toml new file mode 100644 index 000000000000..eb4c10a4f5cc --- /dev/null +++ b/stubs/m3u8/METADATA.toml @@ -0,0 +1,2 @@ +version = "6.0.*" +upstream-repository = "https://github.com/globocom/m3u8" diff --git a/stubs/m3u8/m3u8/__init__.pyi b/stubs/m3u8/m3u8/__init__.pyi new file mode 100644 index 000000000000..6fe32d5edeee --- /dev/null +++ b/stubs/m3u8/m3u8/__init__.pyi @@ -0,0 +1,72 @@ +from collections.abc import Callable, Mapping +from typing import Any, TypeAlias + +from m3u8.httpclient import _HTTPClientProtocol +from m3u8.model import ( + M3U8, + ContentSteering, + DateRange, + DateRangeList, + IFramePlaylist, + ImagePlaylist, + Key, + Media, + MediaList, + PartialSegment, + PartialSegmentList, + PartInformation, + Playlist, + PlaylistList, + PreloadHint, + RenditionReport, + RenditionReportList, + Segment, + SegmentList, + ServerControl, + Skip, + Start, + Tiles, +) +from m3u8.parser import ParseError, parse + +__all__ = ( + "M3U8", + "Segment", + "SegmentList", + "PartialSegment", + "PartialSegmentList", + "Key", + "Playlist", + "IFramePlaylist", + "Media", + "MediaList", + "PlaylistList", + "Start", + "RenditionReport", + "RenditionReportList", + "ServerControl", + "Skip", + "PartInformation", + "PreloadHint", + "DateRange", + "DateRangeList", + "ContentSteering", + "ImagePlaylist", + "Tiles", + "loads", + "load", + "parse", + "ParseError", +) + +_CustomTagsParser: TypeAlias = Callable[[str, int, dict[str, Any], dict[str, Any]], object] + +def loads(content: str, uri: str | None = None, custom_tags_parser: _CustomTagsParser | None = None) -> M3U8: ... +def load( + uri: str, + timeout: float | None = None, + headers: Mapping[str, Any] = {}, + custom_tags_parser: _CustomTagsParser | None = None, + http_client: _HTTPClientProtocol = ..., + verify_ssl: bool = True, +) -> M3U8: ... diff --git a/stubs/m3u8/m3u8/httpclient.pyi b/stubs/m3u8/m3u8/httpclient.pyi new file mode 100644 index 000000000000..96569e96e167 --- /dev/null +++ b/stubs/m3u8/m3u8/httpclient.pyi @@ -0,0 +1,19 @@ +import urllib.request +from typing import Any, Protocol, type_check_only + +@type_check_only +class _HTTPClientProtocol(Protocol): # noqa: Y046 + def download( + self, uri: str, timeout: float | None = None, headers: dict[str, Any] = {}, verify_ssl: bool = True + ) -> tuple[str, str]: ... + +class DefaultHTTPClient: + proxies: dict[str, str] | None + + def __init__(self, proxies: dict[str, str] | None = None) -> None: ... + def download( + self, uri: str, timeout: float | None = None, headers: dict[str, Any] = {}, verify_ssl: bool = True + ) -> tuple[str, str]: ... + +class HTTPSHandler: + def __new__(cls, verify_ssl: bool = True) -> urllib.request.HTTPSHandler: ... # type: ignore[misc] diff --git a/stubs/m3u8/m3u8/mixins.pyi b/stubs/m3u8/m3u8/mixins.pyi new file mode 100644 index 000000000000..9e5d89db5772 --- /dev/null +++ b/stubs/m3u8/m3u8/mixins.pyi @@ -0,0 +1,28 @@ +from abc import ABCMeta +from collections.abc import Iterable +from typing import TypeVar + +_T = TypeVar("_T") + +class BasePathMixin: + uri: str | None + @property + def absolute_uri(self) -> str: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + def get_path_from_uri(self) -> str: ... + +class GroupedBasePathMixin(Iterable[_T], metaclass=ABCMeta): + @property + def base_uri(self) -> str: ... + @base_uri.setter + def base_uri(self, __new_url: str, /) -> None: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, __new_url: str, /) -> None: ... diff --git a/stubs/m3u8/m3u8/model.pyi b/stubs/m3u8/m3u8/model.pyi new file mode 100644 index 000000000000..f532280b71b2 --- /dev/null +++ b/stubs/m3u8/m3u8/model.pyi @@ -0,0 +1,454 @@ +import datetime as dt +from _typeshed import Incomplete, StrOrBytesPath, Unused +from collections.abc import Callable, Iterable, Mapping +from decimal import Decimal +from typing import Any, ClassVar, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from m3u8.mixins import BasePathMixin, GroupedBasePathMixin +from m3u8.protocol import ext_x_map, ext_x_session_key + +_T = TypeVar("_T") +_CustomTagsParser: TypeAlias = Callable[[str, int, dict[str, Incomplete], dict[str, Incomplete]], object] + +@type_check_only +class _PlaylistProtocol(Protocol): + base_uri: str | None + uri: str | None + @property + def absolute_uri(self) -> str: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + def get_path_from_uri(self) -> str: ... + +_PlaylistAnyT = TypeVar("_PlaylistAnyT", bound=_PlaylistProtocol) + +class MalformedPlaylistError(Exception): ... + +class M3U8: + simple_attributes: tuple[tuple[str, str], ...] + data: dict[str, Incomplete] + keys: list[Key] + segment_map: list[InitializationSection] + segments: SegmentList + files: list[str | None] + media: MediaList + playlists: PlaylistList[Playlist] + iframe_playlists: PlaylistList[IFramePlaylist] + image_playlists: PlaylistList[ImagePlaylist] + start: Start + server_control: ServerControl + part_inf: PartInformation + skip: Skip + rendition_reports: RenditionReportList + session_data: SessionDataList + session_keys: list[SessionKey | None] + preload_hint: PreloadHint + content_steering: ContentSteering + + # inserted via setattr() + + is_variant: bool | None + is_endlist: bool | None + is_i_frames_only: bool | None + target_duration: float | None + media_sequence: int | None + program_date_time: dt.datetime | None + is_independent_segments: bool | None + version: str | None + allow_cache: str | None + playlist_type: str | None + discontinuity_sequence: Incomplete | None # undocmented + is_images_only: bool | None + + def __init__( + self, + content: str | None = None, + base_path: str | None = None, + base_uri: str | None = None, + strict: bool = False, + custom_tags_parser: _CustomTagsParser | None = None, + ) -> None: ... + + @property + def base_uri(self) -> str | None: ... + @base_uri.setter + def base_uri(self, new_base_uri: str) -> None: ... + + @property + def base_path(self) -> str | None: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + def add_playlist(self, playlist: Playlist) -> None: ... + def add_iframe_playlist(self, iframe_playlist: IFramePlaylist) -> None: ... + def add_image_playlist(self, image_playlist: ImagePlaylist) -> None: ... + def add_media(self, media: Media) -> None: ... + def add_segment(self, segment: Segment) -> None: ... + def add_rendition_report(self, report: RenditionReport) -> None: ... + def dumps(self, timespec: str = "milliseconds", infspec: str = "auto") -> str: ... + def dump(self, filename: StrOrBytesPath) -> None: ... + def __unicode__(self) -> str: ... + +class Segment(BasePathMixin): + media_sequence: int | None + uri: str | None + duration: float | None + title: str + bitrate: int | None + byterange: str | None + program_date_time: dt.datetime | None + current_program_date_time: dt.datetime | None + discontinuity: bool + cue_out_start: bool + cue_out_explicitly_duration: bool + cue_out: bool + cue_in: bool + scte35: str | None + oatcls_scte35: str | None + scte35_duration: float | None + scte35_elapsedtime: Incomplete | None + asset_metadata: dict[str, Incomplete] | None + key: Key | None + parts: PartialSegmentList + init_section: InitializationSection | None + dateranges: DateRangeList + gap_tag: Incomplete | None + custom_parser_values: dict[str, Incomplete] + def __init__( + self, + uri: str | None = None, + base_uri: str | None = None, + program_date_time: dt.datetime | None = None, + current_program_date_time: dt.datetime | None = None, + duration: float | None = None, + title: str | None = None, + bitrate: int | None = None, + byterange: str | None = None, + cue_out: bool = False, + cue_out_start: bool = False, + cue_out_explicitly_duration: bool = False, + cue_in: bool = False, + discontinuity: bool = False, + key: Unused = None, + scte35: str | None = None, + oatcls_scte35: str | None = None, + scte35_duration: float | None = None, + scte35_elapsedtime=None, + asset_metadata: Mapping[str, str] | None = None, + keyobject: Key | None = None, + parts: Iterable[Mapping[str, Incomplete]] | None = None, + init_section: Mapping[str, Incomplete] | None = None, + dateranges: Iterable[Mapping[str, Incomplete]] | None = None, + gap_tag: list[Mapping[str, Incomplete]] | None = None, + media_sequence: int | None = None, + custom_parser_values: dict[str, Incomplete] | None = None, + ) -> None: ... + def add_part(self, part: PartialSegment) -> None: ... + def dumps(self, last_segment: PartialSegment | None, timespec: str = "milliseconds", infspec: str = "auto") -> str: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + @property + def base_uri(self) -> str: ... + @base_uri.setter + def base_uri(self, newbase_uri: str) -> None: ... + +class SegmentList(list[Segment], GroupedBasePathMixin[Segment]): + def dumps(self, timespec: str = "milliseconds", infspec: str = "auto") -> str: ... + @property + def uri(self) -> list[str | None]: ... + def by_key(self, key: Key) -> list[Segment]: ... + +class PartialSegment(BasePathMixin): + base_uri: str + uri: str | None + duration: float | None + program_date_time: dt.datetime | None + current_program_date_time: dt.datetime | None + byterange: str | None + independent: bool + gap: str | None + dateranges: DateRangeList + gap_tag: str | None + + def __init__( + self, + base_uri: str, + uri: str | None, + duration: float | None, + program_date_time: dt.datetime | None = None, + current_program_date_time: dt.datetime | None = None, + byterange: str | None = None, + independent=None, + gap=None, + dateranges: Iterable[Mapping[str, Incomplete]] | None = None, + gap_tag=None, + ) -> None: ... + def dumps(self, last_segment) -> str: ... + +class PartialSegmentList(list[PartialSegment], GroupedBasePathMixin[PartialSegment]): ... + +class Key(BasePathMixin): + tag: ClassVar[str] = ... + method: str + base_uri: str + uri: str | None + iv: str | None + keyformat: str | None + keyformatversions: str | None + + def __init__( + self, + method: str, + base_uri: str, + uri: str | None = None, + iv: str | None = None, + keyformat: str | None = None, + keyformatversions: str | None = None, + **kwargs, + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class InitializationSection(BasePathMixin): + tag = ext_x_map + base_uri: str + uri: str | None + byterange: str | None + def __init__(self, base_uri: str, uri: str | None, byterange: str | None = None) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class SessionKey(Key): + tag = ext_x_session_key + +class Playlist(_PlaylistProtocol): + base_uri: str | None + uri: str | None + stream_info: StreamInfo + media: MediaList + def __init__(self, uri: str | None, stream_info: Mapping[str, Incomplete], media: MediaList, base_uri: str) -> None: ... + +class IFramePlaylist(_PlaylistProtocol): + uri: str | None + base_uri: str | None + iframe_stream_info: StreamInfo + def __init__(self, base_uri: str, uri: str | None, iframe_stream_info: Mapping[str, Incomplete]) -> None: ... + +class StreamInfo: + bandwidth: int | None + closed_captions: Incomplete | None + average_bandwidth: int | None + program_id: int | None + resolution: tuple[int, int] | None + codecs: str | None + audio: str | None + video: str | None + subtitles: str | None + frame_rate: float | None + video_range: str | None + hdcp_level: str | None + pathway_id: str | None + stable_variant_id: str | None + req_video_layout: str | None + def __init__( + self, + *, + bandwidth: int | None = None, + closed_captions=None, + average_bandwidth: int | None = None, + program_id: int | None = None, + resolution: tuple[int, int] | None = None, + codecs: str | None = None, + audio: str | None = None, + video: str | None = None, + subtitles: str | None = None, + frame_rate: float | None = None, + video_range: str | None = None, + hdcp_level: str | None = None, + pathway_id: str | None = None, + stable_variant_id: str | None = None, + req_video_layout: str | None = None, + ) -> None: ... + +class Media(BasePathMixin): + base_uri: str | None + uri: str | None + type: str | None + group_id: str | None + language: str | None + name: str | None + default: str | None + autoselect: str | None + forced: str | None + assoc_language: str | None + instream_id: str | None + characteristics: str | None + channels: str | None + stable_rendition_id: str | None + extras: dict[str, Incomplete] + + def __init__( + self, + uri: str | None = None, + type: str | None = None, + group_id: str | None = None, + language: str | None = None, + name: str | None = None, + default: str | None = None, + autoselect: str | None = None, + forced: str | None = None, + characteristics: str | None = None, + channels: str | None = None, + stable_rendition_id: str | None = None, + assoc_language: str | None = None, + instream_id: str | None = None, + base_uri: str | None = None, + **extras, + ) -> None: ... + def dumps(self) -> str: ... + +class TagList(list[_T]): ... + +class MediaList(TagList[Media], list[Media], GroupedBasePathMixin[Media]): + @property + def uri(self) -> list[str | None]: ... + +class PlaylistList(TagList[_PlaylistAnyT], list[_PlaylistAnyT], GroupedBasePathMixin[_PlaylistAnyT]): ... +class SessionDataList(TagList[SessionData], list[SessionData]): ... + +class Start: + time_offset: float + precise: Literal["YES", "NO"] + def __init__(self, time_offset: float, precise: Literal["YES", "NO"] | None = None) -> None: ... + +class RenditionReport(BasePathMixin): + base_uri: str | None + uri: str | None + last_msn: int + last_part: int | None + def __init__(self, base_uri: str | None, uri: str | None, last_msn: int, last_part: int | None = None) -> None: ... + def dumps(self) -> str: ... + +class RenditionReportList(list[RenditionReport], GroupedBasePathMixin[RenditionReport]): ... + +class ServerControl: + can_skip_until: float | None + can_block_reload: str | None + hold_back: float | None + part_hold_back: float | None + can_skip_dateranges: str | None + def __init__( + self, + can_skip_until: float | None = None, + can_block_reload: str | None = None, + hold_back: float | None = None, + part_hold_back: float | None = None, + can_skip_dateranges: str | None = None, + ) -> None: ... + def __getitem__(self, item: str) -> str | float | None: ... + def dumps(self) -> str: ... + +class Skip: + skipped_segments: int | None + recently_removed_dateranges: str | None + def __init__(self, skipped_segments: int, recently_removed_dateranges: str | None = None) -> None: ... + def dumps(self) -> str: ... + +class PartInformation: + part_target: float | None + def __init__(self, part_target: float | None = None) -> None: ... + def dumps(self) -> str: ... + +class PreloadHint(BasePathMixin): + hint_type: str | None + base_uri: str | None + uri: str | None + byterange_start: int | None + byterange_length: int | None + def __init__( + self, + type: str | None, + base_uri: str | None, + uri: str | None, + byterange_start: int | None = None, + byterange_length: int | None = None, + ) -> None: ... + def __getitem__(self, item: str) -> str | int | None: ... + def dumps(self) -> str: ... + +class SessionData: + data_id: str + value: str | None + uri: str | None + language: str | None + def __init__(self, data_id: str, value: str | None = None, uri: str | None = None, language: str | None = None) -> None: ... + def dumps(self) -> str: ... + +class DateRangeList(TagList[DateRange]): ... + +class DateRange: + id: str + start_date: str | None + class_: str | None + end_date: str | None + duration: float | None + planned_duration: float | None + scte35_cmd: str | None + scte35_out: str | None + scte35_in: str | None + end_on_next: Incomplete + x_client_attrs: list[tuple[str, str]] + def __init__( + self, + *, + id: str, + start_date: str | None = None, + class_: str | None = None, # actually passing as `class` argument + end_date: str | None = None, + duration: float | None = None, + planned_duration: float | None = None, + scte35_cmd: str | None = None, + scte35_out: str | None = None, + scte35_in: str | None = None, + end_on_next=None, + **kwargs: str, # for arguments with `x_` prefix + ) -> None: ... + def dumps(self) -> str: ... + +class ContentSteering(BasePathMixin): + base_uri: str | None + uri: str | None + pathway_id: str | None + def __init__(self, base_uri: str | None, server_uri: str | None, pathway_id: str | None = None) -> None: ... + def dumps(self) -> str: ... + +class ImagePlaylist(_PlaylistProtocol): + uri: str | None + base_uri: str | None + image_stream_info: StreamInfo + def __init__(self, base_uri: str | None, uri: str | None, image_stream_info: Mapping[str, Incomplete]) -> None: ... + +class Tiles(BasePathMixin): # this is unused in runtime, so this is (temporary) has incomplete + uri: str | None + resolution: Incomplete + layout: Incomplete + duration: Incomplete + def __init__(self, resolution, layout, duration) -> None: ... + def dumps(self) -> str: ... + +@overload +def find_key(keydata: None, keylist: Iterable[Key | None]) -> None: ... +@overload +def find_key(keydata: Mapping[str, Any], keylist: Iterable[Key | None]) -> Key: ... # keydata can contain any values + +def denormalize_attribute(attribute: str) -> str: ... +def quoted(string: str | None) -> str: ... +def number_to_string(number: str | float | Decimal) -> str: ... diff --git a/stubs/m3u8/m3u8/parser.pyi b/stubs/m3u8/m3u8/parser.pyi new file mode 100644 index 000000000000..5970547659bd --- /dev/null +++ b/stubs/m3u8/m3u8/parser.pyi @@ -0,0 +1,29 @@ +from collections.abc import Callable +from datetime import date, datetime, time +from itertools import repeat +from re import Pattern +from typing import Any, TypeAlias, overload + +_CustomTagsParser: TypeAlias = Callable[[str, int, dict[str, Any], dict[str, Any]], object] + +ATTRIBUTELISTPATTERN: Pattern[str] + +def cast_date_time(value: str) -> datetime: ... + +@overload +def format_date_time(value: time, *, timespec: str = ...) -> str: ... +@overload +def format_date_time(value: datetime, *, sep: str = ..., timespec: str = ...) -> str: ... +@overload +def format_date_time(value: date) -> str: ... + +class ParseError(Exception): + lineno: int + line: str + def __init__(self, lineno: int, line: str) -> None: ... + +def parse(content: str, strict: bool = False, custom_tags_parser: _CustomTagsParser | None = None) -> dict[str, Any]: ... +def string_to_lines(string: str) -> list[str]: ... +def remove_quotes_parser(*attrs: repeat[Callable[[str], str]]) -> dict[repeat[Callable[[str], str]], Callable[[str], str]]: ... +def remove_quotes(string: str) -> str: ... +def normalize_attribute(attribute: str) -> str: ... diff --git a/stubs/m3u8/m3u8/protocol.pyi b/stubs/m3u8/m3u8/protocol.pyi new file mode 100644 index 000000000000..06bb58b5a20c --- /dev/null +++ b/stubs/m3u8/m3u8/protocol.pyi @@ -0,0 +1,41 @@ +ext_m3u: str +ext_x_targetduration: str +ext_x_media_sequence: str +ext_x_discontinuity_sequence: str +ext_x_program_date_time: str +ext_x_media: str +ext_x_playlist_type: str +ext_x_key: str +ext_x_stream_inf: str +ext_x_version: str +ext_x_allow_cache: str +ext_x_endlist: str +extinf: str +ext_i_frames_only: str +ext_x_asset: str +ext_x_bitrate: str +ext_x_byterange: str +ext_x_i_frame_stream_inf: str +ext_x_discontinuity: str +ext_x_cue_out: str +ext_x_cue_out_cont: str +ext_x_cue_in: str +ext_x_cue_span: str +ext_oatcls_scte35: str +ext_is_independent_segments: str +ext_x_map: str +ext_x_start: str +ext_x_server_control: str +ext_x_part_inf: str +ext_x_part: str +ext_x_rendition_report: str +ext_x_skip: str +ext_x_session_data: str +ext_x_session_key: str +ext_x_preload_hint: str +ext_x_daterange: str +ext_x_gap: str +ext_x_content_steering: str +ext_x_image_stream_inf: str +ext_x_images_only: str +ext_x_tiles: str diff --git a/stubs/m3u8/m3u8/version_matching.pyi b/stubs/m3u8/m3u8/version_matching.pyi new file mode 100644 index 000000000000..6f4265b2ebfc --- /dev/null +++ b/stubs/m3u8/m3u8/version_matching.pyi @@ -0,0 +1,5 @@ +from m3u8.version_matching_rules import VersionMatchingError + +def get_version(file_lines: list[str]) -> float | None: ... +def valid_in_all_rules(line_number: int, line: str, version: float) -> list[VersionMatchingError]: ... +def validate(file_lines: list[str]) -> list[VersionMatchingError]: ... diff --git a/stubs/m3u8/m3u8/version_matching_rules.pyi b/stubs/m3u8/m3u8/version_matching_rules.pyi new file mode 100644 index 000000000000..2fb0bde7212f --- /dev/null +++ b/stubs/m3u8/m3u8/version_matching_rules.pyi @@ -0,0 +1,24 @@ +from dataclasses import dataclass + +@dataclass +class VersionMatchingError(Exception): + line_number: int + line: str + how_to_fix: str = ... + description: str = ... + +class VersionMatchRuleBase: + description: str + how_to_fix: str + version: float + line_number: int + line: str + def __init__(self, version: float, line_number: int, line: str) -> None: ... + def validate(self) -> bool: ... + def get_error(self) -> VersionMatchingError: ... + +class ValidIVInEXTXKEY(VersionMatchRuleBase): ... +class ValidFloatingPointEXTINF(VersionMatchRuleBase): ... +class ValidEXTXBYTERANGEOrEXTXIFRAMESONLY(VersionMatchRuleBase): ... + +available_rules: list[type[VersionMatchRuleBase]] diff --git a/stubs/mock/@tests/stubtest_allowlist.txt b/stubs/mock/@tests/stubtest_allowlist.txt index fea9da93591e..636393741865 100644 --- a/stubs/mock/@tests/stubtest_allowlist.txt +++ b/stubs/mock/@tests/stubtest_allowlist.txt @@ -1,13 +1,3 @@ -mock.NonCallableMock.__new__ -mock.patch -mock.mock.NonCallableMock.__new__ -mock.mock.patch - -# Methods with a first argument that's not called "self" -mock.mock.AsyncMockMixin.assert_any_await -mock.mock.AsyncMockMixin.assert_awaited -mock.mock.AsyncMockMixin.assert_awaited_once -mock.mock.AsyncMockMixin.assert_awaited_once_with -mock.mock.AsyncMockMixin.assert_awaited_with -mock.mock.AsyncMockMixin.assert_has_awaits -mock.mock.AsyncMockMixin.assert_not_awaited +# Uses `_timeout_unset` sentinel: +mock.mock.ThreadingMixin.__init__ +mock.mock.ThreadingMixin.wait_until_called diff --git a/stubs/mock/METADATA.toml b/stubs/mock/METADATA.toml index 3188e8fc281e..1436f5662373 100644 --- a/stubs/mock/METADATA.toml +++ b/stubs/mock/METADATA.toml @@ -1 +1,2 @@ -version = "4.0.*" +version = "5.2.*" +upstream-repository = "https://github.com/testing-cabal/mock" diff --git a/stubs/mock/mock/__init__.pyi b/stubs/mock/mock/__init__.pyi index 9b47e2207bef..4fc3625d63a7 100644 --- a/stubs/mock/mock/__init__.pyi +++ b/stubs/mock/mock/__init__.pyi @@ -1,3 +1,24 @@ from .mock import * +__all__ = ( + "__version__", + "version_info", + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "ThreadingMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", +) +__version__: str version_info: tuple[int, int, int] diff --git a/stubs/mock/mock/backports.pyi b/stubs/mock/mock/backports.pyi new file mode 100644 index 000000000000..9cb45af2cd60 --- /dev/null +++ b/stubs/mock/mock/backports.pyi @@ -0,0 +1,2 @@ +from inspect import iscoroutinefunction as iscoroutinefunction +from unittest import IsolatedAsyncioTestCase as IsolatedAsyncioTestCase diff --git a/stubs/mock/mock/mock.pyi b/stubs/mock/mock/mock.pyi index e61862bf876d..8ec149dd76a4 100644 --- a/stubs/mock/mock/mock.pyi +++ b/stubs/mock/mock/mock.pyi @@ -1,10 +1,16 @@ -from collections.abc import Callable, Mapping, Sequence -from typing import Any, Generic, Type, TypeVar, overload +from _typeshed import Incomplete +from collections.abc import Callable, Coroutine, Iterable, Mapping, Sequence +from contextlib import AbstractContextManager +from types import TracebackType +from typing import Any, ClassVar, Generic, Literal, ParamSpec, TypeVar, overload, type_check_only +from typing_extensions import Self _F = TypeVar("_F", bound=Callable[..., Any]) +_AF = TypeVar("_AF", bound=Callable[..., Coroutine[Any, Any, Any]]) _T = TypeVar("_T") -_TT = TypeVar("_TT", bound=Type[Any]) +_TT = TypeVar("_TT", bound=type[Any]) _R = TypeVar("_R") +_P = ParamSpec("_P") __all__ = ( "Mock", @@ -16,6 +22,7 @@ __all__ = ( "call", "create_autospec", "AsyncMock", + "ThreadingMock", "FILTER_DIR", "NonCallableMock", "NonCallableMagicMock", @@ -23,31 +30,37 @@ __all__ = ( "PropertyMock", "seal", ) -__version__: str -FILTER_DIR: Any +class InvalidSpecError(Exception): ... -sentinel: Any -DEFAULT: Any +FILTER_DIR: bool + +class _SentinelObject: + def __init__(self, name: str) -> None: ... + name: str + +class _Sentinel: + def __getattr__(self, name: str) -> _SentinelObject: ... + +sentinel: _Sentinel +DEFAULT: _SentinelObject class _Call(tuple[Any, ...]): def __new__( - cls, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... - ) -> Any: ... + cls, value: Any = (), name: Incomplete | None = "", parent=None, two: bool = False, from_kall: bool = True + ) -> Self: ... name: Any parent: Any from_kall: Any - def __init__( - self, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... - ) -> None: ... - def __eq__(self, other: Any) -> bool: ... - __ne__: Any + def __init__(self, value: Any = (), name=None, parent=None, two: bool = False, from_kall: bool = True) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... def __getattr__(self, attr: str) -> Any: ... @property - def args(self): ... + def args(self) -> tuple[Any, ...]: ... @property - def kwargs(self): ... + def kwargs(self) -> dict[str, Any]: ... def call_list(self) -> _CallList: ... call: _Call @@ -58,37 +71,53 @@ class _CallList(list[_Call]): class Base: def __init__(self, *args: Any, **kwargs: Any) -> None: ... +# We subclass with "Any" because mocks are explicitly designed to stand in for other types, +# something that can't be expressed with our static type system. class NonCallableMock(Base, Any): - def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... + def __new__( + cls, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state=None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> Self: ... def __init__( self, - spec: list[str] | object | Type[object] | None = ..., - wraps: Any | None = ..., - name: str | None = ..., - spec_set: list[str] | object | Type[object] | None = ..., - parent: NonCallableMock | None = ..., - _spec_state: Any | None = ..., - _new_name: str = ..., - _new_parent: NonCallableMock | None = ..., - _spec_as_instance: bool = ..., - _eat_self: bool | None = ..., - unsafe: bool = ..., + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state=None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, **kwargs: Any, ) -> None: ... def __getattr__(self, name: str) -> Any: ... - def _calls_repr(self, prefix: str = ...) -> str: ... + def _calls_repr(self) -> str: ... def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... def assert_not_called(_mock_self) -> None: ... def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... - def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = ...) -> str: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... def assert_called(_mock_self) -> None: ... def assert_called_once(_mock_self) -> None: ... - def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... def _extract_mock_name(self) -> str: ... def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... - def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ... - def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... - def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = False) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = False, _eat_self: bool = False) -> None: ... def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... def configure_mock(self, **kwargs: Any) -> None: ... return_value: Any @@ -106,16 +135,16 @@ class CallableMixin(Base): side_effect: Any def __init__( self, - spec: Any | None = ..., - side_effect: Any | None = ..., + spec=None, + side_effect=None, return_value: Any = ..., - wraps: Any | None = ..., - name: Any | None = ..., - spec_set: Any | None = ..., - parent: Any | None = ..., - _spec_state: Any | None = ..., - _new_name: Any = ..., - _new_parent: Any | None = ..., + wraps=None, + name=None, + spec_set=None, + parent=None, + _spec_state=None, + _new_name: Any = "", + _new_parent=None, **kwargs: Any, ) -> None: ... def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... @@ -136,27 +165,35 @@ class _patch(Generic[_T]): kwargs: Mapping[str, Any] additional_patchers: Any def __init__( - self: _patch[_T], + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 getter: Callable[[], Any], attribute: str, new: _T, - spec: Any | None, + spec: Incomplete | None, create: bool, - spec_set: Any | None, - autospec: Any | None, - new_callable: Any | None, + spec_set: Incomplete | None, + autospec: Incomplete | None, + new_callable: Incomplete | None, kwargs: Mapping[str, Any], + *, + unsafe: bool = False, ) -> None: ... def copy(self) -> _patch[_T]: ... - def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ... def decorate_class(self, klass: _TT) -> _TT: ... def decorate_callable(self, func: _F) -> _F: ... + def decorate_async_callable(self, func: _AF) -> _AF: ... + def decoration_helper( + self, patched: Any, args: tuple[Any, ...], keywargs: dict[str, Any] + ) -> AbstractContextManager[tuple[tuple[Any, ...], dict[str, Any]]]: ... def get_original(self) -> tuple[Any, bool]: ... target: Any temp_original: Any is_local: bool def __enter__(self) -> _T: ... - def __exit__(self, *exc_info: Any) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... def start(self) -> _T: ... def stop(self) -> None: ... @@ -164,27 +201,32 @@ class _patch_dict: in_dict: Any values: Any clear: Any - def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ... + def __init__(self, in_dict: Any, values: Any = (), clear: Any = False, **kwargs: Any) -> None: ... def __call__(self, f: Any) -> Any: ... + def decorate_callable(self, f: _F) -> _F: ... + def decorate_async_callable(self, f: _AF) -> _AF: ... def decorate_class(self, klass: Any) -> Any: ... def __enter__(self) -> Any: ... - def __exit__(self, *args: Any) -> Any: ... + def __exit__(self, *args: object) -> Any: ... start: Any stop: Any +@type_check_only class _patcher: TEST_PREFIX: str - dict: Type[_patch_dict] + dict: type[_patch_dict] + @overload - def __call__( # type: ignore[misc] + def __call__( self, target: Any, *, - spec: Any | None = ..., + spec: Incomplete | None = ..., create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + unsafe: bool = ..., **kwargs: Any, ) -> _patch[MagicMock | AsyncMock]: ... # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. @@ -195,24 +237,28 @@ class _patcher: self, target: Any, new: _T, - spec: Any | None = ..., + spec: Incomplete | None = ..., create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + *, + unsafe: bool = ..., **kwargs: Any, ) -> _patch[_T]: ... + @overload - def object( # type: ignore[misc] + def object( self, target: Any, attribute: str, *, - spec: Any | None = ..., + spec: Incomplete | None = ..., create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + unsafe: bool = ..., **kwargs: Any, ) -> _patch[MagicMock | AsyncMock]: ... @overload @@ -220,22 +266,27 @@ class _patcher: self, target: Any, attribute: str, - new: _T = ..., - spec: Any | None = ..., + new: _T, + spec: Incomplete | None = ..., create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + *, + unsafe: bool = ..., **kwargs: Any, ) -> _patch[_T]: ... + def multiple( self, target: Any, - spec: Any | None = ..., + spec: Incomplete | None = ..., create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + *, + unsafe: bool = ..., **kwargs: _T, ) -> _patch[_T]: ... def stopall(self) -> None: ... @@ -246,45 +297,52 @@ class MagicMixin: def __init__(self, *args: Any, **kw: Any) -> None: ... class NonCallableMagicMock(MagicMixin, NonCallableMock): - def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... class MagicMock(MagicMixin, Mock): - def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... class AsyncMockMixin(Base): def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def assert_awaited(self) -> None: ... - def assert_awaited_once(self) -> None: ... - def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... - def assert_has_awaits(self, calls: _CallList, any_order: bool = ...) -> None: ... - def assert_not_awaited(self) -> None: ... + def assert_awaited(_mock_self) -> None: ... + def assert_awaited_once(_mock_self) -> None: ... + def assert_awaited_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(_mock_self, calls: Iterable[_Call], any_order: bool = False) -> None: ... + def assert_not_awaited(_mock_self) -> None: ... def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... await_count: int await_args: _Call | None await_args_list: _CallList + __name__: str + __defaults__: tuple[Any, ...] + __kwdefaults__: dict[str, Any] + __annotations__: dict[str, Any] | None # type: ignore[assignment] -class AsyncMagicMixin(MagicMixin): - def __init__(self, *args: Any, **kw: Any) -> None: ... +class AsyncMagicMixin(MagicMixin): ... -class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... +class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... class MagicProxy(Base): name: str parent: Any - def __init__(self, name: str, parent) -> None: ... + def __init__(self, name: str, parent: Any) -> None: ... def create_mock(self) -> Any: ... - def __get__(self, obj: Any, _type: Any | None = ...) -> Any: ... + def __get__(self, obj: Any, _type=None) -> Any: ... -class _ANY: - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... +class _ANY(Any): + def __eq__(self, other: object) -> Literal[True]: ... + def __ne__(self, other: object) -> Literal[False]: ... -ANY: Any +ANY: _ANY def create_autospec( - spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Any | None = ..., _name: Any | None = ..., **kwargs: Any + spec: Any, spec_set: Any = False, instance: Any = False, _parent=None, _name=None, *, unsafe: bool = False, **kwargs: Any ) -> Any: ... class _SpecState: @@ -294,18 +352,26 @@ class _SpecState: parent: Any instance: Any name: Any - def __init__( - self, - spec: Any, - spec_set: Any = ..., - parent: Any | None = ..., - name: Any | None = ..., - ids: Any | None = ..., - instance: Any = ..., - ) -> None: ... + def __init__(self, spec: Any, spec_set: Any = False, parent=None, name=None, ids=None, instance: Any = False) -> None: ... -def mock_open(mock: Any | None = ..., read_data: Any = ...) -> Any: ... +def mock_open(mock=None, read_data: Any = "") -> Any: ... -PropertyMock = Any +class PropertyMock(Mock): + def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ... + def __set__(self, obj: Any, value: Any) -> None: ... def seal(mock: Any) -> None: ... + +class ThreadingMixin(Base): + DEFAULT_TIMEOUT: ClassVar[float | None] + + def __init__(self, *args: Any, timeout: float | None = ..., **kwargs: Any) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + def wait_until_called(self, *, timeout: float | None = ...) -> None: ... + def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: ... + +class ThreadingMock(ThreadingMixin, MagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `ThreadingMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... diff --git a/stubs/mypy-extensions/@tests/stubtest_allowlist.txt b/stubs/mypy-extensions/@tests/stubtest_allowlist.txt index bffaebc697dc..4f48c1c4bbe4 100644 --- a/stubs/mypy-extensions/@tests/stubtest_allowlist.txt +++ b/stubs/mypy-extensions/@tests/stubtest_allowlist.txt @@ -1,2 +1,6 @@ mypy_extensions.FlexibleAlias mypy_extensions.TypedDict +mypy_extensions.i64.* +mypy_extensions.i32.* +mypy_extensions.i16.* +mypy_extensions.u8.* diff --git a/stubs/mypy-extensions/METADATA.toml b/stubs/mypy-extensions/METADATA.toml index 79b51931ee0b..33583f5d725b 100644 --- a/stubs/mypy-extensions/METADATA.toml +++ b/stubs/mypy-extensions/METADATA.toml @@ -1,2 +1,2 @@ -version = "0.4.*" -python2 = true +version = "1.1.*" +upstream-repository = "https://github.com/python/mypy_extensions" diff --git a/stubs/mypy-extensions/mypy_extensions.pyi b/stubs/mypy-extensions/mypy_extensions.pyi index dd182c485177..f4f7fa6faf76 100644 --- a/stubs/mypy-extensions/mypy_extensions.pyi +++ b/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,45 +1,95 @@ import abc -import sys -from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, Type, TypeVar, ValuesView +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import IdentityFunction, Unused +from collections.abc import Mapping +from typing import Any, ClassVar, Generic, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, deprecated _T = TypeVar("_T") _U = TypeVar("_U") # Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing(_extensions)._TypedDict +@type_check_only +@deprecated("Use typing._TypedDict instead") class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): - def copy(self: _T) -> _T: ... - # Using NoReturn so that only calls using mypy plugin hook that specialize the signature + __total__: ClassVar[bool] + # Unlike typing(_extensions).TypedDict, + # subclasses of mypy_extensions.TypedDict do NOT have the __required_keys__ and __optional_keys__ ClassVars + def copy(self) -> Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature # can go through. - def setdefault(self, k: NoReturn, default: object) -> object: ... + def setdefault(self, k: Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. - def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... - if sys.version_info >= (3, 0): - def items(self) -> ItemsView[str, object]: ... - def keys(self) -> KeysView[str]: ... - def values(self) -> ValuesView[object]: ... - else: - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... - def __delitem__(self, k: NoReturn) -> None: ... - -def TypedDict(typename: str, fields: dict[str, Type[Any]], total: bool = ...) -> Type[dict[str, Any]]: ... -def Arg(type: _T = ..., name: str | None = ...) -> _T: ... -def DefaultArg(type: _T = ..., name: str | None = ...) -> _T: ... -def NamedArg(type: _T = ..., name: str | None = ...) -> _T: ... -def DefaultNamedArg(type: _T = ..., name: str | None = ...) -> _T: ... -def VarArg(type: _T = ...) -> _T: ... -def KwArg(type: _T = ...) -> _T: ... + def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: Self, /) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + def __delitem__(self, k: Never) -> None: ... + + @overload + def __or__(self, value: Self, /) -> Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: Self, /) -> Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of `__or__` and `__ior__`: + def __ior__(self, value: Self, /) -> Self: ... # type: ignore[misc] + +@deprecated("Use typing.TypedDict or typing_extensions.TypedDict instead") +def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... + +@overload +def Arg(type: _T, name: str | None = ...) -> _T: ... +@overload +def Arg(*, name: str | None = ...) -> Any: ... + +@overload +def DefaultArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def DefaultArg(*, name: str | None = ...) -> Any: ... + +@overload +def NamedArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def NamedArg(*, name: str | None = ...) -> Any: ... + +@overload +def DefaultNamedArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def DefaultNamedArg(*, name: str | None = ...) -> Any: ... + +@overload +def VarArg(type: _T) -> _T: ... +@overload +def VarArg() -> Any: ... + +@overload +def KwArg(type: _T) -> _T: ... +@overload +def KwArg() -> Any: ... # Return type that indicates a function does not return. -# Deprecated: Use typing.NoReturn instead. +@deprecated("Use typing.Never instead") class NoReturn: ... -# This is intended as a class decorator, but mypy rejects abstract classes -# when a Type[_T] is expected, so we can't give it the type we want -def trait(cls: Any) -> Any: ... -def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ... +# This is consistent with implementation. Usage intends for this as +# a class decorator, but mypy does not support type[_T] for abstract +# classes until this issue is resolved, https://github.com/python/mypy/issues/4717. +def trait(cls: _T) -> _T: ... +def mypyc_attr(*attrs: str, **kwattrs: Unused) -> IdentityFunction: ... class FlexibleAlias(Generic[_T, _U]): ... + +# Mypy and mypyc treat these native int types as different from 'int', but this is +# a non-standard extension. For other tools, aliasing these to 'int' allows them +# to mostly do the right thing with these types. +i64 = int +i32 = int +i16 = int +u8 = int diff --git a/stubs/mysqlclient/@tests/stubtest_allowlist.txt b/stubs/mysqlclient/@tests/stubtest_allowlist.txt index fbc91acd69fa..c22d30fb9a56 100644 --- a/stubs/mysqlclient/@tests/stubtest_allowlist.txt +++ b/stubs/mysqlclient/@tests/stubtest_allowlist.txt @@ -1 +1,12 @@ -MySQLdb.Connection +# Deprecated reexports that are added via __getattr__(). +MySQLdb.cursors.BaseCursor.DataError +MySQLdb.cursors.BaseCursor.DatabaseError +MySQLdb.cursors.BaseCursor.Error +MySQLdb.cursors.BaseCursor.IntegrityError +MySQLdb.cursors.BaseCursor.InterfaceError +MySQLdb.cursors.BaseCursor.InternalError +MySQLdb.cursors.BaseCursor.MySQLError +MySQLdb.cursors.BaseCursor.NotSupportedError +MySQLdb.cursors.BaseCursor.OperationalError +MySQLdb.cursors.BaseCursor.ProgrammingError +MySQLdb.cursors.BaseCursor.Warning diff --git a/stubs/mysqlclient/METADATA.toml b/stubs/mysqlclient/METADATA.toml index 159b06b06fd2..b242844fd810 100644 --- a/stubs/mysqlclient/METADATA.toml +++ b/stubs/mysqlclient/METADATA.toml @@ -1 +1,5 @@ -version = "2.0.*" \ No newline at end of file +version = "2.3.*" +upstream-repository = "https://github.com/PyMySQL/mysqlclient" + +[tool.stubtest] +apt-dependencies = ["libmariadb-dev"] diff --git a/stubs/mysqlclient/MySQLdb/__init__.pyi b/stubs/mysqlclient/MySQLdb/__init__.pyi index 88d6eb25bd2c..740ff8fe5f04 100644 --- a/stubs/mysqlclient/MySQLdb/__init__.pyi +++ b/stubs/mysqlclient/MySQLdb/__init__.pyi @@ -1,4 +1,4 @@ -from typing import Any, FrozenSet +from _typeshed import Incomplete from MySQLdb import connections as connections, constants as constants, converters as converters, cursors as cursors from MySQLdb._mysql import ( @@ -14,8 +14,6 @@ from MySQLdb._mysql import ( ProgrammingError as ProgrammingError, Warning as Warning, debug as debug, - escape as escape, - escape_string as escape_string, get_client_info as get_client_info, string_literal as string_literal, ) @@ -35,19 +33,63 @@ threadsafety: int apilevel: str paramstyle: str -class DBAPISet(FrozenSet[Any]): +class DBAPISet(frozenset[Incomplete]): def __eq__(self, other): ... -STRING: Any -BINARY: Any -NUMBER: Any -DATE: Any -TIME: Any -TIMESTAMP: Any -DATETIME: Any -ROWID: Any +STRING: Incomplete +BINARY: Incomplete +NUMBER: Incomplete +DATE: Incomplete +TIME: Incomplete +TIMESTAMP: Incomplete +DATETIME: Incomplete +ROWID: Incomplete def Binary(x): ... -def Connect(*args, **kwargs): ... +def Connect(*args, **kwargs) -> Connection: ... connect = Connect + +__all__ = [ + "BINARY", + "Binary", + "Connect", + "Connection", + "DATE", + "Date", + "Time", + "Timestamp", + "DateFromTicks", + "TimeFromTicks", + "TimestampFromTicks", + "DataError", + "DatabaseError", + "Error", + "FIELD_TYPE", + "IntegrityError", + "InterfaceError", + "InternalError", + "MySQLError", + "NUMBER", + "NotSupportedError", + "DBAPISet", + "OperationalError", + "ProgrammingError", + "ROWID", + "STRING", + "TIME", + "TIMESTAMP", + "Warning", + "apilevel", + "connect", + "connections", + "constants", + "converters", + "cursors", + "debug", + "get_client_info", + "paramstyle", + "string_literal", + "threadsafety", + "version_info", +] diff --git a/stubs/mysqlclient/MySQLdb/_mysql.pyi b/stubs/mysqlclient/MySQLdb/_mysql.pyi index 690e3469893f..1de55ce47508 100644 --- a/stubs/mysqlclient/MySQLdb/_mysql.pyi +++ b/stubs/mysqlclient/MySQLdb/_mysql.pyi @@ -1,9 +1,11 @@ import builtins -from typing import Any, Tuple +from _typeshed import Incomplete +from typing import overload +from typing_extensions import deprecated, disjoint_base import MySQLdb._exceptions -version_info: Tuple[Any, ...] +version_info: tuple[Incomplete, ...] class DataError(MySQLdb._exceptions.DatabaseError): ... class DatabaseError(MySQLdb._exceptions.Error): ... @@ -17,71 +19,82 @@ class OperationalError(MySQLdb._exceptions.DatabaseError): ... class ProgrammingError(MySQLdb._exceptions.DatabaseError): ... class Warning(builtins.Warning, MySQLdb._exceptions.MySQLError): ... +@disjoint_base class connection: - client_flag: Any - converter: Any - open: Any - port: Any - server_capabilities: Any + client_flag: Incomplete + converter: Incomplete + open: Incomplete + port: Incomplete + server_capabilities: Incomplete def __init__(self, *args, **kwargs) -> None: ... - def _get_native_connection(self, *args, **kwargs) -> Any: ... - def affected_rows(self, *args, **kwargs) -> Any: ... - def autocommit(self, on) -> Any: ... - def change_user(self, *args, **kwargs) -> Any: ... - def character_set_name(self, *args, **kwargs) -> Any: ... - def close(self, *args, **kwargs) -> Any: ... - def commit(self, *args, **kwargs) -> Any: ... - def dump_debug_info(self, *args, **kwargs) -> Any: ... - def errno(self, *args, **kwargs) -> Any: ... - def error(self, *args, **kwargs) -> Any: ... - def escape(self, obj, dict) -> Any: ... - def escape_string(self, s) -> Any: ... - def field_count(self, *args, **kwargs) -> Any: ... - def fileno(self, *args, **kwargs) -> Any: ... - def get_autocommit(self, *args, **kwargs) -> Any: ... - def get_character_set_info(self, *args, **kwargs) -> Any: ... - def get_host_info(self, *args, **kwargs) -> Any: ... - def get_proto_info(self, *args, **kwargs) -> Any: ... - def get_server_info(self, *args, **kwargs) -> Any: ... - def info(self, *args, **kwargs) -> Any: ... - def insert_id(self, *args, **kwargs) -> Any: ... - def kill(self, *args, **kwargs) -> Any: ... - def next_result(self) -> Any: ... - def ping(self) -> Any: ... - def query(self, query) -> Any: ... - def read_query_result(self, *args, **kwargs) -> Any: ... - def rollback(self, *args, **kwargs) -> Any: ... - def select_db(self, *args, **kwargs) -> Any: ... - def send_query(self, *args, **kwargs) -> Any: ... - def set_character_set(self, charset) -> Any: ... - def set_server_option(self, option) -> Any: ... - def shutdown(self, *args, **kwargs) -> Any: ... - def sqlstate(self, *args, **kwargs) -> Any: ... - def stat(self, *args, **kwargs) -> Any: ... - def store_result(self, *args, **kwargs) -> Any: ... - def string_literal(self, obj) -> Any: ... - def thread_id(self, *args, **kwargs) -> Any: ... - def use_result(self, *args, **kwargs) -> Any: ... - def warning_count(self, *args, **kwargs) -> Any: ... - def __delattr__(self, name) -> Any: ... - def __setattr__(self, name, value) -> Any: ... + def _get_native_connection(self): ... + def affected_rows(self): ... + def autocommit(self, on): ... + def change_user(self, *args, **kwargs): ... + def character_set_name(self): ... + def close(self): ... + def commit(self): ... + def dump_debug_info(self): ... + def errno(self): ... + def error(self): ... + def escape(self, obj, dict): ... + def escape_string(self, s): ... + def field_count(self): ... + def fileno(self): ... + def get_autocommit(self): ... + def get_character_set_info(self): ... + def get_host_info(self): ... + def get_proto_info(self): ... + def get_server_info(self): ... + def info(self): ... + def insert_id(self): ... + def kill(self, *args, **kwargs): ... + def more_results(self) -> bool: ... + def next_result(self): ... + @overload + @deprecated("The reconnect parameter of ping() is deprecated.") + def ping(self, reconnect: bool) -> None: ... + @overload + def ping(self) -> None: ... + + def query(self, query): ... + def read_query_result(self): ... + def rollback(self): ... + def select_db(self, *args, **kwargs): ... + def send_query(self, *args, **kwargs): ... + def set_character_set(self, charset: str) -> None: ... + def set_server_option(self, option): ... + def shutdown(self): ... + def sqlstate(self): ... + def stat(self): ... + def store_result(self): ... + def string_literal(self, obj, /) -> str: ... + def thread_id(self): ... + def use_result(self): ... + def discard_result(self) -> None: ... + def warning_count(self): ... + def __delattr__(self, name: str, /) -> None: ... + def __setattr__(self, name: str, value, /) -> None: ... + +@disjoint_base class result: - converter: Any - has_next: Any + converter: Incomplete + has_next: Incomplete def __init__(self, *args, **kwargs) -> None: ... - def data_seek(self, n) -> Any: ... - def describe(self, *args, **kwargs) -> Any: ... - def fetch_row(self, *args, **kwargs) -> Any: ... - def field_flags(self, *args, **kwargs) -> Any: ... - def num_fields(self, *args, **kwargs) -> Any: ... - def num_rows(self, *args, **kwargs) -> Any: ... - def __delattr__(self, name) -> Any: ... - def __setattr__(self, name, value) -> Any: ... + def data_seek(self, n): ... + def describe(self): ... + def fetch_row(self, *args, **kwargs): ... + def discard(self) -> None: ... + def field_flags(self): ... + def num_fields(self): ... + def num_rows(self): ... + def __delattr__(self, name: str, /) -> None: ... + def __setattr__(self, name: str, value, /) -> None: ... -def connect(*args, **kwargs) -> Any: ... -def debug(*args, **kwargs) -> Any: ... -def escape(obj, dict) -> Any: ... -def escape_string(s) -> Any: ... -def get_client_info() -> Any: ... -def string_literal(obj) -> Any: ... +def connect(*args, **kwargs): ... +def debug(*args, **kwargs): ... +def escape(obj, dict): ... +def escape_string(s): ... +def get_client_info(): ... +def string_literal(obj, /) -> str: ... diff --git a/stubs/mysqlclient/MySQLdb/connections.pyi b/stubs/mysqlclient/MySQLdb/connections.pyi index 93bc84a1d58b..565b6df12f91 100644 --- a/stubs/mysqlclient/MySQLdb/connections.pyi +++ b/stubs/mysqlclient/MySQLdb/connections.pyi @@ -1,6 +1,10 @@ -from typing import Any +from _typeshed import Incomplete +from re import Pattern +from types import TracebackType +from typing import Any, Literal, TypeAlias +from typing_extensions import LiteralString, Self -from . import _mysql, cursors as cursors +from . import _mysql, cursors from ._exceptions import ( DatabaseError as DatabaseError, DataError as DataError, @@ -14,35 +18,43 @@ from ._exceptions import ( Warning as Warning, ) -re_numeric_part: Any +# Any kind of object that can be passed to Connection.literal(). +# The allowed types depend on the defined encoders, but the following +# types are always allowed. +_Literal: TypeAlias = str | bytearray | bytes | tuple[_Literal, ...] | list[_Literal] | Any + +re_numeric_part: Pattern[str] def numeric_part(s): ... class Connection(_mysql.connection): - default_cursor: Any - cursorclass: Any - encoders: Any + default_cursor: type[cursors.Cursor] + executemany_fallback: Literal["loop", "multi"] + cursorclass: type[cursors.BaseCursor] + encoders: Incomplete encoding: str - messages: Any - def __init__(self, *args, **kwargs): ... - def __enter__(self): ... - def __exit__(self, exc_type, exc_value, traceback) -> None: ... - def autocommit(self, on) -> None: ... - def cursor(self, cursorclass: Any | None = ...): ... + messages: Incomplete + def __init__(self, *args, executemany_fallback: Literal["loop", "multi"] = ..., **kwargs) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def autocommit(self, on: bool) -> None: ... + def cursor(self, cursorclass: type[cursors.BaseCursor] | None = None): ... def query(self, query) -> None: ... - def literal(self, o): ... + def literal(self, o: _Literal) -> bytes: ... def begin(self) -> None: ... def warning_count(self): ... - def set_character_set(self, charset) -> None: ... + def set_character_set(self, charset: LiteralString, collation: LiteralString | None = None) -> None: ... def set_sql_mode(self, sql_mode) -> None: ... def show_warnings(self): ... - Warning: Any - Error: Any - InterfaceError: Any - DatabaseError: Any - DataError: Any - OperationalError: Any - IntegrityError: Any - InternalError: Any - ProgrammingError: Any - NotSupportedError: Any + Warning: type[BaseException] + Error: type[BaseException] + InterfaceError: type[BaseException] + DatabaseError: type[BaseException] + DataError: type[BaseException] + OperationalError: type[BaseException] + IntegrityError: type[BaseException] + InternalError: type[BaseException] + ProgrammingError: type[BaseException] + NotSupportedError: type[BaseException] diff --git a/stubs/mysqlclient/MySQLdb/constants/__init__.pyi b/stubs/mysqlclient/MySQLdb/constants/__init__.pyi index 3eaad111bed7..df9363bc4207 100644 --- a/stubs/mysqlclient/MySQLdb/constants/__init__.pyi +++ b/stubs/mysqlclient/MySQLdb/constants/__init__.pyi @@ -1 +1,3 @@ from . import CLIENT as CLIENT, CR as CR, ER as ER, FIELD_TYPE as FIELD_TYPE, FLAG as FLAG + +__all__ = ["CR", "FIELD_TYPE", "CLIENT", "ER", "FLAG"] diff --git a/stubs/mysqlclient/MySQLdb/converters.pyi b/stubs/mysqlclient/MySQLdb/converters.pyi index d350ee383f26..510e795cf23a 100644 --- a/stubs/mysqlclient/MySQLdb/converters.pyi +++ b/stubs/mysqlclient/MySQLdb/converters.pyi @@ -1,5 +1,5 @@ import array -from typing import Any +from _typeshed import Incomplete from MySQLdb._exceptions import ProgrammingError as ProgrammingError from MySQLdb._mysql import string_literal as string_literal @@ -15,7 +15,7 @@ from MySQLdb.times import ( TimeDelta_or_None as TimeDelta_or_None, ) -NoneType: Any +NoneType: Incomplete ArrayType = array.array def Bool2Str(s, d): ... @@ -27,4 +27,4 @@ def Thing2Literal(o, d): ... def Decimal2Literal(o, d): ... def array2Str(o, d): ... -conversions: Any +conversions: Incomplete diff --git a/stubs/mysqlclient/MySQLdb/cursors.pyi b/stubs/mysqlclient/MySQLdb/cursors.pyi index 3362a3daeef8..64f01642bc37 100644 --- a/stubs/mysqlclient/MySQLdb/cursors.pyi +++ b/stubs/mysqlclient/MySQLdb/cursors.pyi @@ -1,8 +1,45 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterable +from re import Pattern +from typing import Literal, TypeAlias +from typing_extensions import LiteralString, Self -RE_INSERT_VALUES: Any +from .connections import _Literal + +_Arguments: TypeAlias = dict[str, _Literal] | dict[bytes, _Literal] | Iterable[_Literal] + +RE_INSERT_VALUES: Pattern[str] class BaseCursor: + max_stmt_length: int + max_multi_stmt_length: int + max_multi_stmt_count: int + executemany_fallback: Literal["loop", "multi"] | None + connection: Incomplete + + warning_count: int + description: Incomplete | None + description_flags: Incomplete | None + rowcount: int + arraysize: int + lastrowid: Incomplete | None + rownumber: Incomplete | None + + def __init__(self, connection) -> None: ... + def close(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + def nextset(self): ... + def setinputsizes(self, *args) -> None: ... + def setoutputsizes(self, *args) -> None: ... + def execute(self, query, args=None): ... + def mogrify(self, query: str | bytes, args: _Arguments | None = None) -> str: ... + def executemany(self, query: LiteralString, args: Iterable[_Arguments]) -> int | None: ... + def callproc(self, procname, args=()): ... + def __iter__(self) -> Self: ... + def __next__(self): ... + + # These are all deprecated. from ._exceptions import ( DatabaseError as DatabaseError, DataError as DataError, @@ -17,42 +54,18 @@ class BaseCursor: Warning as Warning, ) - max_stmt_length: Any - connection: Any - description: Any - description_flags: Any - rowcount: int - arraysize: int - lastrowid: Any - rownumber: Any - def __init__(self, connection) -> None: ... - def close(self) -> None: ... - def __enter__(self): ... - def __exit__(self, *exc_info) -> None: ... - def nextset(self): ... - def setinputsizes(self, *args) -> None: ... - def setoutputsizes(self, *args) -> None: ... - def execute(self, query, args: Any | None = ...): ... - def executemany(self, query: str, args: list[Any]) -> int: ... - def callproc(self, procname, args=...): ... - def __iter__(self): ... - class CursorStoreResultMixIn: - rownumber: Any + rownumber: Incomplete def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... + def fetchmany(self, size=None): ... def fetchall(self): ... - def scroll(self, value, mode: str = ...) -> None: ... - def __iter__(self): ... + def scroll(self, value, mode: str = "relative") -> None: ... class CursorUseResultMixIn: - rownumber: Any + rownumber: Incomplete def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... + def fetchmany(self, size=None): ... def fetchall(self): ... - def __iter__(self): ... - def next(self): ... - __next__: Any class CursorTupleRowsMixIn: ... class CursorDictRowsMixIn: ... diff --git a/stubs/mysqlclient/MySQLdb/release.pyi b/stubs/mysqlclient/MySQLdb/release.pyi index 99069a2e3f12..a78eb9f6a30d 100644 --- a/stubs/mysqlclient/MySQLdb/release.pyi +++ b/stubs/mysqlclient/MySQLdb/release.pyi @@ -1,3 +1 @@ -from typing import Any - -version_info: Any +version_info: tuple[int, int, int, str, int] diff --git a/stubs/mysqlclient/MySQLdb/times.pyi b/stubs/mysqlclient/MySQLdb/times.pyi index 339617fde1b2..21a14cfc8551 100644 --- a/stubs/mysqlclient/MySQLdb/times.pyi +++ b/stubs/mysqlclient/MySQLdb/times.pyi @@ -1,3 +1,4 @@ +from _typeshed import Unused from datetime import date, datetime, time, timedelta from MySQLdb._mysql import string_literal as string_literal @@ -9,18 +10,18 @@ Timestamp = datetime DateTimeDeltaType = timedelta DateTimeType = datetime -def DateFromTicks(ticks): ... -def TimeFromTicks(ticks): ... -def TimestampFromTicks(ticks): ... +def DateFromTicks(ticks: float | None) -> date: ... +def TimeFromTicks(ticks: float | None) -> time: ... +def TimestampFromTicks(ticks: float | None) -> datetime: ... format_TIME = str format_DATE = str -def format_TIMEDELTA(v): ... -def format_TIMESTAMP(d): ... -def DateTime_or_None(s): ... -def TimeDelta_or_None(s): ... -def Time_or_None(s): ... -def Date_or_None(s): ... -def DateTime2literal(d, c): ... -def DateTimeDelta2literal(d, c): ... +def format_TIMEDELTA(v: timedelta) -> str: ... +def format_TIMESTAMP(d: datetime) -> str: ... +def DateTime_or_None(s: str) -> datetime | None: ... +def TimeDelta_or_None(s: str) -> timedelta | None: ... +def Time_or_None(s: str) -> time | None: ... +def Date_or_None(s: str) -> date | None: ... +def DateTime2literal(d: datetime, c: Unused) -> str: ... +def DateTimeDelta2literal(d: datetime, c: Unused) -> str: ... diff --git a/stubs/nanoid/METADATA.toml b/stubs/nanoid/METADATA.toml new file mode 100644 index 000000000000..d2d220486c31 --- /dev/null +++ b/stubs/nanoid/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.0" +upstream-repository = "https://github.com/puyuan/py-nanoid" diff --git a/stubs/nanoid/nanoid/__init__.pyi b/stubs/nanoid/nanoid/__init__.pyi new file mode 100644 index 000000000000..37e83e31a712 --- /dev/null +++ b/stubs/nanoid/nanoid/__init__.pyi @@ -0,0 +1,4 @@ +from nanoid.generate import generate +from nanoid.non_secure_generate import non_secure_generate + +__all__ = ["generate", "non_secure_generate"] diff --git a/stubs/nanoid/nanoid/algorithm.pyi b/stubs/nanoid/nanoid/algorithm.pyi new file mode 100644 index 000000000000..e5d49982f64c --- /dev/null +++ b/stubs/nanoid/nanoid/algorithm.pyi @@ -0,0 +1 @@ +def algorithm_generate(random_bytes: int) -> bytearray: ... diff --git a/stubs/nanoid/nanoid/generate.pyi b/stubs/nanoid/nanoid/generate.pyi new file mode 100644 index 000000000000..8c3e6771b179 --- /dev/null +++ b/stubs/nanoid/nanoid/generate.pyi @@ -0,0 +1,3 @@ +def generate( + alphabet: str = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", size: int = 21 # noqa: Y053 +) -> str: ... diff --git a/stubs/nanoid/nanoid/method.pyi b/stubs/nanoid/nanoid/method.pyi new file mode 100644 index 000000000000..0e79a8e09215 --- /dev/null +++ b/stubs/nanoid/nanoid/method.pyi @@ -0,0 +1,6 @@ +from collections.abc import Callable, Sequence +from typing import TypeAlias + +_Algorithm: TypeAlias = Callable[[int], Sequence[int]] + +def method(algorithm: _Algorithm, alphabet: str, size: int) -> str: ... diff --git a/stubs/nanoid/nanoid/non_secure_generate.pyi b/stubs/nanoid/nanoid/non_secure_generate.pyi new file mode 100644 index 000000000000..d37459182d95 --- /dev/null +++ b/stubs/nanoid/nanoid/non_secure_generate.pyi @@ -0,0 +1,3 @@ +def non_secure_generate( + alphabet: str = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", size: int = 21 # noqa: Y053 +) -> str: ... diff --git a/stubs/nanoid/nanoid/resources.pyi b/stubs/nanoid/nanoid/resources.pyi new file mode 100644 index 000000000000..a0bd3b8f78ff --- /dev/null +++ b/stubs/nanoid/nanoid/resources.pyi @@ -0,0 +1,2 @@ +alphabet: str +size: int diff --git a/stubs/nanoleafapi/@tests/stubtest_allowlist.txt b/stubs/nanoleafapi/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..dcdd0cfdbb8f --- /dev/null +++ b/stubs/nanoleafapi/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +nanoleafapi.test_nanoleaf diff --git a/stubs/nanoleafapi/METADATA.toml b/stubs/nanoleafapi/METADATA.toml new file mode 100644 index 000000000000..4f4332fcd18c --- /dev/null +++ b/stubs/nanoleafapi/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.1.*" +upstream-repository = "https://github.com/MylesMor/nanoleafapi" diff --git a/stubs/nanoleafapi/nanoleafapi/__init__.pyi b/stubs/nanoleafapi/nanoleafapi/__init__.pyi new file mode 100644 index 000000000000..78cdd18a19f5 --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/__init__.pyi @@ -0,0 +1,16 @@ +from nanoleafapi.digital_twin import NanoleafDigitalTwin as NanoleafDigitalTwin +from nanoleafapi.nanoleaf import ( + BLUE as BLUE, + GREEN as GREEN, + LIGHT_BLUE as LIGHT_BLUE, + ORANGE as ORANGE, + PINK as PINK, + PURPLE as PURPLE, + RED as RED, + WHITE as WHITE, + YELLOW as YELLOW, + Nanoleaf as Nanoleaf, + NanoleafConnectionError as NanoleafConnectionError, + NanoleafEffectCreationError as NanoleafEffectCreationError, + NanoleafRegistrationError as NanoleafRegistrationError, +) diff --git a/stubs/nanoleafapi/nanoleafapi/digital_twin.pyi b/stubs/nanoleafapi/nanoleafapi/digital_twin.pyi new file mode 100644 index 000000000000..5da49f6bedef --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/digital_twin.pyi @@ -0,0 +1,12 @@ +from nanoleafapi.nanoleaf import Nanoleaf + +class NanoleafDigitalTwin: + nanoleaf: Nanoleaf + tile_dict: dict[str, dict[str, int]] + def __init__(self, nl: Nanoleaf) -> None: ... + def set_color(self, panel_id: int, rgb: tuple[int, int, int]) -> None: ... + def set_all_colors(self, rgb: tuple[int, int, int]) -> None: ... + def get_ids(self) -> list[int]: ... + def get_color(self, panel_id: int) -> tuple[int, int, int]: ... + def get_all_colors(self) -> dict[int, tuple[int, int, int]]: ... + def sync(self) -> bool: ... diff --git a/stubs/nanoleafapi/nanoleafapi/discovery.pyi b/stubs/nanoleafapi/nanoleafapi/discovery.pyi new file mode 100644 index 000000000000..233eb0cd2553 --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/discovery.pyi @@ -0,0 +1 @@ +def discover_devices(timeout: int = 30, debug: bool = False) -> dict[str | None, str]: ... diff --git a/stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi b/stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi new file mode 100644 index 000000000000..d83625ad5285 --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any + +RED: tuple[int, int, int] +ORANGE: tuple[int, int, int] +YELLOW: tuple[int, int, int] +GREEN: tuple[int, int, int] +LIGHT_BLUE: tuple[int, int, int] +BLUE: tuple[int, int, int] +PINK: tuple[int, int, int] +PURPLE: tuple[int, int, int] +WHITE: tuple[int, int, int] + +class Nanoleaf: + ip: str + print_errors: bool + url: str + auth_token: str + already_registered: bool + def __init__(self, ip: str, auth_token: str | None = None, print_errors: bool = False) -> None: ... + def create_auth_token(self) -> str | None: ... + def delete_auth_token(self, auth_token: str) -> bool: ... + def check_connection(self) -> None: ... + def get_info(self) -> dict[str, Incomplete]: ... + def get_name(self) -> str: ... + def get_auth_token(self) -> str | None: ... + def get_ids(self) -> list[int]: ... + @staticmethod + def get_custom_base_effect(anim_type: str = "custom", loop: bool = True) -> dict[str, Incomplete]: ... + def power_off(self) -> bool: ... + def power_on(self) -> bool: ... + def get_power(self) -> bool: ... + def toggle_power(self) -> bool: ... + def set_color(self, rgb: tuple[int, int, int]) -> bool: ... + def set_brightness(self, brightness: int, duration: int = 0) -> bool: ... + def increment_brightness(self, brightness: int) -> bool: ... + def get_brightness(self) -> int: ... + def identify(self) -> bool: ... + def set_hue(self, value: int) -> bool: ... + def increment_hue(self, value: int) -> bool: ... + def get_hue(self) -> int: ... + def set_saturation(self, value: int) -> bool: ... + def increment_saturation(self, value: int) -> bool: ... + def get_saturation(self) -> int: ... + def set_color_temp(self, value: int) -> bool: ... + def increment_color_temp(self, value: int) -> bool: ... + def get_color_temp(self) -> int: ... + def get_color_mode(self) -> str: ... + def get_current_effect(self) -> str: ... + def set_effect(self, effect_name: str) -> bool: ... + def list_effects(self) -> list[str]: ... + def write_effect(self, effect_dict: dict[str, Incomplete]) -> bool: ... + def effect_exists(self, effect_name: str) -> bool: ... + def pulsate(self, rgb: tuple[int, int, int], speed: float = 1) -> bool: ... + def flow(self, rgb_list: list[tuple[int, int, int]], speed: float = 1) -> bool: ... + def spectrum(self, speed: float = 1) -> bool: ... + def enable_extcontrol(self) -> bool: ... + def get_layout(self) -> dict[str, Incomplete]: ... + def register_event(self, func: Callable[[dict[str, Incomplete]], Any], event_types: list[int]) -> None: ... + +class NanoleafRegistrationError(Exception): + def __init__(self) -> None: ... + +class NanoleafConnectionError(Exception): + def __init__(self) -> None: ... + +class NanoleafEffectCreationError(Exception): ... diff --git a/stubs/netaddr/@tests/stubtest_allowlist.txt b/stubs/netaddr/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b493ad84230b --- /dev/null +++ b/stubs/netaddr/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +netaddr.tests.* + +# __getattr__ is not present at runtime but __init__ has `self.__dict__.update(kwargs)` +netaddr.ip.iana.XMLRecordParser.__getattr__ diff --git a/stubs/netaddr/METADATA.toml b/stubs/netaddr/METADATA.toml new file mode 100644 index 000000000000..fbb5fc4b2ac0 --- /dev/null +++ b/stubs/netaddr/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.3.*" +upstream-repository = "https://github.com/netaddr/netaddr" diff --git a/stubs/netaddr/netaddr/__init__.pyi b/stubs/netaddr/netaddr/__init__.pyi new file mode 100644 index 000000000000..efc922f6964e --- /dev/null +++ b/stubs/netaddr/netaddr/__init__.pyi @@ -0,0 +1,124 @@ +from netaddr.contrib.subnet_splitter import SubnetSplitter as SubnetSplitter +from netaddr.core import ( + INET_ATON as INET_ATON, + INET_PTON as INET_PTON, + NOHOST as NOHOST, + ZEROFILL as ZEROFILL, + AddrConversionError as AddrConversionError, + AddrFormatError as AddrFormatError, + NotRegisteredError as NotRegisteredError, +) +from netaddr.eui import EUI as EUI, IAB as IAB, OUI as OUI +from netaddr.ip import ( + IPAddress as IPAddress, + IPNetwork as IPNetwork, + IPRange as IPRange, + all_matching_cidrs as all_matching_cidrs, + cidr_abbrev_to_verbose as cidr_abbrev_to_verbose, + cidr_exclude as cidr_exclude, + cidr_merge as cidr_merge, + iprange_to_cidrs as iprange_to_cidrs, + iter_iprange as iter_iprange, + iter_unique_ips as iter_unique_ips, + largest_matching_cidr as largest_matching_cidr, + smallest_matching_cidr as smallest_matching_cidr, + spanning_cidr as spanning_cidr, +) +from netaddr.ip.glob import ( + IPGlob as IPGlob, + cidr_to_glob as cidr_to_glob, + glob_to_cidrs as glob_to_cidrs, + glob_to_iprange as glob_to_iprange, + glob_to_iptuple as glob_to_iptuple, + iprange_to_globs as iprange_to_globs, + valid_glob as valid_glob, +) +from netaddr.ip.nmap import iter_nmap_range as iter_nmap_range, valid_nmap_range as valid_nmap_range +from netaddr.ip.rfc1924 import base85_to_ipv6 as base85_to_ipv6, ipv6_to_base85 as ipv6_to_base85 +from netaddr.ip.sets import IPSet as IPSet +from netaddr.strategy.eui48 import ( + mac_bare as mac_bare, + mac_cisco as mac_cisco, + mac_eui48 as mac_eui48, + mac_pgsql as mac_pgsql, + mac_unix as mac_unix, + mac_unix_expanded as mac_unix_expanded, + valid_str as valid_mac, +) +from netaddr.strategy.eui64 import ( + eui64_bare as eui64_bare, + eui64_base as eui64_base, + eui64_cisco as eui64_cisco, + eui64_unix as eui64_unix, + eui64_unix_expanded as eui64_unix_expanded, + valid_str as valid_eui64, +) +from netaddr.strategy.ipv4 import expand_partial_address as expand_partial_ipv4_address, valid_str as valid_ipv4 +from netaddr.strategy.ipv6 import ( + ipv6_compact as ipv6_compact, + ipv6_full as ipv6_full, + ipv6_verbose as ipv6_verbose, + valid_str as valid_ipv6, +) + +__all__ = [ + "AddrConversionError", + "AddrFormatError", + "NotRegisteredError", + "ZEROFILL", + "INET_ATON", + "INET_PTON", + "NOHOST", + "IPAddress", + "IPNetwork", + "IPRange", + "all_matching_cidrs", + "cidr_abbrev_to_verbose", + "cidr_exclude", + "cidr_merge", + "iprange_to_cidrs", + "iter_iprange", + "iter_unique_ips", + "largest_matching_cidr", + "smallest_matching_cidr", + "spanning_cidr", + "IPSet", + "IPGlob", + "cidr_to_glob", + "glob_to_cidrs", + "glob_to_iprange", + "glob_to_iptuple", + "iprange_to_globs", + "valid_glob", + "valid_nmap_range", + "iter_nmap_range", + "base85_to_ipv6", + "ipv6_to_base85", + "EUI", + "IAB", + "OUI", + "valid_ipv4", + "valid_ipv6", + "ipv6_compact", + "ipv6_full", + "ipv6_verbose", + "mac_eui48", + "mac_unix", + "mac_unix_expanded", + "mac_cisco", + "mac_bare", + "mac_pgsql", + "valid_mac", + "eui64_base", + "eui64_unix", + "eui64_unix_expanded", + "eui64_cisco", + "eui64_bare", + "valid_eui64", + "SubnetSplitter", + "expand_partial_ipv4_address", +] + +__version__: str +VERSION: tuple[int, ...] +STATUS: str diff --git a/stubs/netaddr/netaddr/cli.pyi b/stubs/netaddr/netaddr/cli.pyi new file mode 100644 index 000000000000..c19fa74b5960 --- /dev/null +++ b/stubs/netaddr/netaddr/cli.pyi @@ -0,0 +1,8 @@ +from typing import Any + +SHELL_NAMESPACE: dict[str, Any] +ASCII_ART_LOGO: str + +def main() -> None: ... +def shell() -> None: ... +def info(network_input: str) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/mysql/provision.pyi b/stubs/netaddr/netaddr/compat.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/dialects/mysql/provision.pyi rename to stubs/netaddr/netaddr/compat.pyi diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/oracle/provision.pyi b/stubs/netaddr/netaddr/contrib/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/dialects/oracle/provision.pyi rename to stubs/netaddr/netaddr/contrib/__init__.pyi diff --git a/stubs/netaddr/netaddr/contrib/subnet_splitter.pyi b/stubs/netaddr/netaddr/contrib/subnet_splitter.pyi new file mode 100644 index 000000000000..55edd7f096bb --- /dev/null +++ b/stubs/netaddr/netaddr/contrib/subnet_splitter.pyi @@ -0,0 +1,7 @@ +from netaddr.ip import IPNetwork, _IPAddressAddr + +class SubnetSplitter: + def __init__(self, base_cidr: _IPAddressAddr) -> None: ... + def extract_subnet(self, prefix: int, count: int | None = None) -> list[IPNetwork]: ... + def available_subnets(self) -> list[IPNetwork]: ... + def remove_subnet(self, ip_network: IPNetwork) -> None: ... diff --git a/stubs/netaddr/netaddr/core.pyi b/stubs/netaddr/netaddr/core.pyi new file mode 100644 index 000000000000..03460aa3eb71 --- /dev/null +++ b/stubs/netaddr/netaddr/core.pyi @@ -0,0 +1,34 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterator, Mapping +from typing import Final + +BIG_ENDIAN_PLATFORM: bool +INET_PTON: Final = 1 +ZEROFILL: Final = 2 +NOHOST: Final = 4 +INET_ATON: Final = 8 + +class AddrFormatError(Exception): ... +class AddrConversionError(Exception): ... +class NotRegisteredError(Exception): ... + +class Subscriber: + def update(self, data) -> None: ... + +class PrettyPrinter(Subscriber): + fh: SupportsWrite[str] + write_eol: bool + def __init__(self, fh: SupportsWrite[str] = ..., write_eol: bool = True) -> None: ... + def update(self, data: object) -> None: ... + +class Publisher: + subscribers: list[Subscriber] + def __init__(self) -> None: ... + def attach(self, subscriber: Subscriber) -> None: ... + def detach(self, subscriber: Subscriber) -> None: ... + def notify(self, data: object) -> None: ... + +class DictDotLookup: + def __init__(self, d: Mapping[str, object]) -> None: ... + def __getitem__(self, name: str) -> object: ... + def __iter__(self) -> Iterator[str]: ... diff --git a/stubs/netaddr/netaddr/eui/__init__.pyi b/stubs/netaddr/netaddr/eui/__init__.pyi new file mode 100644 index 000000000000..4ff92b883f43 --- /dev/null +++ b/stubs/netaddr/netaddr/eui/__init__.pyi @@ -0,0 +1,91 @@ +from _typeshed import ConvertibleToInt +from typing import ClassVar, Literal, overload +from typing_extensions import Self + +from netaddr.core import DictDotLookup +from netaddr.ip import IPAddress +from netaddr.strategy.eui48 import mac_eui48 +from netaddr.strategy.eui64 import eui64_base + +class BaseIdentifier: + __slots__ = ("_value", "__weakref__") + def __init__(self) -> None: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + +class OUI(BaseIdentifier): + __slots__ = ("records",) + records: list[dict[str, object]] + def __init__(self, oui: str | int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + @property + def reg_count(self) -> int: ... + def registration(self, index: int = 0) -> DictDotLookup: ... + +class IAB(BaseIdentifier): + __slots__ = ("record",) + IAB_EUI_VALUES: ClassVar[tuple[int, int]] + @classmethod + def split_iab_mac(cls, eui_int: int, strict: bool = False) -> tuple[int, int]: ... + record: dict[str, object] + def __init__(self, iab: str | int, strict: bool = False) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def registration(self) -> DictDotLookup: ... + +class EUI(BaseIdentifier): + __slots__ = ("_module", "_dialect") + def __init__( + self, addr: EUI | int | str, version: int | None = None, dialect: type[mac_eui48 | eui64_base] | None = None + ) -> None: ... + + @property + def value(self) -> int: ... + @value.setter + def value(self, value: ConvertibleToInt) -> None: ... + + @property + def dialect(self) -> type[mac_eui48 | eui64_base]: ... + @dialect.setter + def dialect(self, value: type[mac_eui48 | eui64_base] | None) -> None: ... + + @property + def oui(self) -> OUI: ... + @property + def ei(self) -> str: ... + def is_iab(self) -> bool: ... + @property + def iab(self) -> IAB | None: ... + @property + def version(self) -> Literal[48, 64]: ... + + @overload + def __getitem__(self, idx: int) -> int: ... + @overload + def __getitem__(self, idx: slice) -> list[int]: ... + @overload + def __getitem__(self, idx: int | slice) -> int | list[int]: ... + + def __setitem__(self, idx: int, value: int) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: EUI | int | str) -> bool: ... + def __le__(self, other: EUI | int | str) -> bool: ... + def __gt__(self, other: EUI | int | str) -> bool: ... + def __ge__(self, other: EUI | int | str) -> bool: ... + def bits(self, word_sep: str | None = None) -> str: ... + @property + def packed(self) -> bytes: ... + @property + def words(self) -> tuple[int, ...]: ... + @property + def bin(self) -> str: ... + def eui64(self) -> Self: ... + def modified_eui64(self) -> Self: ... + def ipv6(self, prefix: ConvertibleToInt) -> IPAddress: ... + def ipv6_link_local(self) -> IPAddress: ... + @property + def info(self) -> DictDotLookup: ... + def format(self, dialect: type[mac_eui48 | eui64_base] | None = None) -> str: ... diff --git a/stubs/netaddr/netaddr/eui/ieee.pyi b/stubs/netaddr/netaddr/eui/ieee.pyi new file mode 100644 index 000000000000..a0bcd560d645 --- /dev/null +++ b/stubs/netaddr/netaddr/eui/ieee.pyi @@ -0,0 +1,32 @@ +import _csv +from _typeshed import FileDescriptorOrPath, StrOrBytesPath +from collections.abc import Iterable +from typing import Any, BinaryIO, TextIO, TypeAlias + +from netaddr.core import Publisher, Subscriber + +_INDEX: TypeAlias = dict[int, list[tuple[int, int]]] +OUI_INDEX: _INDEX +IAB_INDEX: _INDEX + +class FileIndexer(Subscriber): + writer: _csv.Writer + def __init__(self, index_file: TextIO | FileDescriptorOrPath) -> None: ... + def update(self, data: Iterable[Any]) -> None: ... + +class OUIIndexParser(Publisher): + fh: BinaryIO + def __init__(self, ieee_file: BinaryIO | FileDescriptorOrPath) -> None: ... + def parse(self) -> None: ... + +class IABIndexParser(Publisher): + fh: BinaryIO + def __init__(self, ieee_file: BinaryIO | FileDescriptorOrPath) -> None: ... + def parse(self) -> None: ... + +def create_index_from_registry( + registry_fh: BinaryIO | FileDescriptorOrPath, index_path: StrOrBytesPath, parser: type[OUIIndexParser | IABIndexParser] +) -> None: ... +def create_indices() -> None: ... +def load_index(index: _INDEX, fp: Iterable[bytes]) -> None: ... +def load_indices() -> None: ... diff --git a/stubs/netaddr/netaddr/fbsocket.pyi b/stubs/netaddr/netaddr/fbsocket.pyi new file mode 100644 index 000000000000..f33989b5b19d --- /dev/null +++ b/stubs/netaddr/netaddr/fbsocket.pyi @@ -0,0 +1,8 @@ +from typing import Literal + +AF_INET: Literal[2] +AF_INET6: Literal[10] + +def inet_ntoa(packed_ip: bytes) -> str: ... +def inet_ntop(af: int, packed_ip: bytes) -> str: ... +def inet_pton(af: int, ip_string: str) -> str: ... diff --git a/stubs/netaddr/netaddr/ip/__init__.pyi b/stubs/netaddr/netaddr/ip/__init__.pyi new file mode 100644 index 000000000000..0f748120ca95 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/__init__.pyi @@ -0,0 +1,192 @@ +from _typeshed import ConvertibleToInt, Unused +from abc import abstractmethod +from collections.abc import Iterable, Iterator +from types import ModuleType +from typing import Literal, SupportsIndex, SupportsInt, TypeAlias, overload +from typing_extensions import Self + +from netaddr.core import DictDotLookup +from netaddr.strategy.ipv6 import ipv6_verbose + +class BaseIP: + __slots__ = ("_value", "_module", "__weakref__") + def __init__(self) -> None: ... + + @property + def value(self) -> int | None: ... + @value.setter + def value(self, value: int) -> None: ... + + @abstractmethod + def key(self) -> tuple[int, ...]: ... + @abstractmethod + def sort_key(self) -> tuple[int, ...]: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: BaseIP) -> bool: ... + def __le__(self, other: BaseIP) -> bool: ... + def __gt__(self, other: BaseIP) -> bool: ... + def __ge__(self, other: BaseIP) -> bool: ... + def is_unicast(self) -> bool: ... + def is_multicast(self) -> bool: ... + def is_loopback(self) -> bool: ... + def is_link_local(self) -> bool: ... + def is_reserved(self) -> bool: ... + def is_ipv4_mapped(self) -> bool: ... + def is_ipv4_compat(self) -> bool: ... + @property + def info(self) -> DictDotLookup: ... + @property + def version(self) -> Literal[4, 6]: ... + +_IPAddressAddr: TypeAlias = BaseIP | int | str +_IPNetworkAddr: TypeAlias = IPNetwork | IPAddress | tuple[int, int] | str + +class IPAddress(BaseIP): + __slots__ = () + def __init__(self, addr: _IPAddressAddr, version: Literal[4, 6] | None = None, flags: int = 0) -> None: ... + def netmask_bits(self) -> int: ... + def is_hostmask(self) -> bool: ... + def is_netmask(self) -> bool: ... + def __iadd__(self, num: int) -> Self: ... + def __isub__(self, num: int) -> Self: ... + def __add__(self, num: int) -> Self: ... + __radd__ = __add__ + def __sub__(self, num: int) -> Self: ... + def __rsub__(self, num: int) -> Self: ... + def key(self) -> tuple[int, ...]: ... + def sort_key(self) -> tuple[int, ...]: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + def __bytes__(self) -> bytes: ... + def bits(self, word_sep: str | None = None) -> str: ... + @property + def packed(self) -> bytes: ... + @property + def words(self) -> tuple[int, ...]: ... + @property + def bin(self) -> str: ... + @property + def reverse_dns(self) -> str: ... + def ipv4(self) -> Self: ... + def ipv6(self, ipv4_compatible: bool = False) -> Self: ... + def format(self, dialect: type[ipv6_verbose] | None = None) -> str: ... + def __or__(self, other: SupportsInt | SupportsIndex) -> Self: ... + def __and__(self, other: SupportsInt | SupportsIndex) -> Self: ... + def __xor__(self, other: SupportsInt | SupportsIndex) -> Self: ... + def __lshift__(self, numbits: int) -> Self: ... + def __rshift__(self, numbits: int) -> Self: ... + def __bool__(self) -> bool: ... + def to_canonical(self) -> Self: ... + def is_global(self) -> bool: ... + def is_ipv4_private_use(self) -> bool: ... + def is_ipv6_unique_local(self) -> bool: ... + +class IPListMixin: + __slots__ = () + def __iter__(self) -> Iterator[IPAddress]: ... + @property + def size(self) -> int: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, index: SupportsIndex) -> IPAddress: ... + @overload + def __getitem__(self, index: slice) -> Iterator[IPAddress]: ... + @overload + def __getitem__(self, index: SupportsIndex | slice) -> IPAddress | Iterator[IPAddress]: ... + + def __contains__(self, other: BaseIP | _IPAddressAddr) -> bool: ... + def __bool__(self) -> Literal[True]: ... + +def parse_ip_network( + module: ModuleType, addr: tuple[int, int] | str, flags: int = 0, *, expand_partial: bool = False +) -> tuple[int, int]: ... + +class IPNetwork(BaseIP, IPListMixin): + __slots__ = ("_prefixlen",) + def __init__( + self, addr: _IPNetworkAddr, version: Literal[4, 6] | None = None, flags: int = 0, *, expand_partial: bool = False + ) -> None: ... + + @property + def prefixlen(self) -> int: ... + @prefixlen.setter + def prefixlen(self, value: int) -> None: ... + + @property + def ip(self) -> IPAddress: ... + @property + def network(self) -> IPAddress: ... + @property + def broadcast(self) -> IPAddress | None: ... + @property + def first(self) -> int: ... + @property + def last(self) -> int: ... + + @property + def netmask(self) -> IPAddress: ... + @netmask.setter + def netmask(self, value: _IPAddressAddr) -> None: ... + + @property + def hostmask(self) -> IPAddress: ... + @property + def cidr(self) -> IPNetwork: ... + def __iadd__(self, num: int) -> Self: ... + def __isub__(self, num: int) -> Self: ... + # runtime overrides __contains__ with incompatible type for "other" + def __contains__(self, other: BaseIP | _IPNetworkAddr) -> bool: ... # type: ignore[override] + def key(self) -> tuple[int, ...]: ... + def sort_key(self) -> tuple[int, ...]: ... + def ipv4(self) -> Self: ... + def ipv6(self, ipv4_compatible: bool = False) -> Self: ... + def previous(self, step: int = 1) -> Self: ... + def next(self, step: int = 1) -> Self: ... + def supernet(self, prefixlen: int = 0) -> list[IPNetwork]: ... + def subnet(self, prefixlen: int, count: int | None = None, fmt: Unused = None) -> Iterator[Self]: ... + def iter_hosts(self) -> Iterator[IPAddress]: ... + +class IPRange(BaseIP, IPListMixin): + __slots__ = ("_start", "_end") + def __init__(self, start: _IPAddressAddr, end: _IPAddressAddr, flags: int = 0) -> None: ... + def __contains__(self, other: BaseIP | _IPAddressAddr) -> bool: ... + @property + def first(self) -> int: ... + @property + def last(self) -> int: ... + def key(self) -> tuple[int, ...]: ... + def sort_key(self) -> tuple[int, ...]: ... + def cidrs(self) -> list[IPNetwork]: ... + +def iter_unique_ips(*args: IPRange | _IPNetworkAddr) -> Iterator[IPAddress]: ... +def cidr_abbrev_to_verbose(abbrev_cidr: ConvertibleToInt) -> str: ... +def cidr_merge(ip_addrs: Iterable[IPRange | _IPNetworkAddr]) -> list[IPNetwork]: ... +def cidr_exclude(target: _IPNetworkAddr, exclude: _IPNetworkAddr) -> list[IPNetwork]: ... +def cidr_partition( + target: _IPNetworkAddr, exclude: _IPNetworkAddr +) -> tuple[list[IPNetwork], list[IPNetwork], list[IPNetwork]]: ... +def spanning_cidr(ip_addrs: Iterable[_IPNetworkAddr]) -> IPNetwork: ... +def iter_iprange(start: _IPAddressAddr, end: _IPAddressAddr, step: SupportsInt | SupportsIndex = 1) -> Iterator[IPAddress]: ... +def iprange_to_cidrs(start: _IPNetworkAddr, end: _IPNetworkAddr) -> list[IPNetwork]: ... +def smallest_matching_cidr(ip: _IPAddressAddr, cidrs: Iterable[_IPNetworkAddr]) -> IPNetwork | None: ... +def largest_matching_cidr(ip: _IPAddressAddr, cidrs: Iterable[_IPNetworkAddr]) -> IPNetwork | None: ... +def all_matching_cidrs(ip: _IPAddressAddr, cidrs: Iterable[_IPNetworkAddr]) -> list[IPNetwork]: ... + +IPV4_LOOPBACK: IPNetwork +IPV4_PRIVATE_USE: list[IPNetwork] +IPV4_LINK_LOCAL: IPNetwork +IPV4_MULTICAST: IPNetwork +IPV4_6TO4: IPNetwork +IPV4_RESERVED: tuple[IPNetwork | IPRange, ...] +IPV4_NOT_GLOBALLY_REACHABLE: list[IPNetwork] +IPV4_NOT_GLOBALLY_REACHABLE_EXCEPTIONS: list[IPNetwork] +IPV6_LOOPBACK: IPNetwork +IPV6_UNIQUE_LOCAL: IPNetwork +IPV6_LINK_LOCAL: IPNetwork +IPV6_MULTICAST: IPNetwork +IPV6_RESERVED: tuple[IPNetwork, ...] +IPV6_NOT_GLOBALLY_REACHABLE: list[IPNetwork] +IPV6_NOT_GLOBALLY_REACHABLE_EXCEPTIONS: list[IPNetwork] diff --git a/stubs/netaddr/netaddr/ip/glob.pyi b/stubs/netaddr/netaddr/ip/glob.pyi new file mode 100644 index 000000000000..c2865d085e7b --- /dev/null +++ b/stubs/netaddr/netaddr/ip/glob.pyi @@ -0,0 +1,19 @@ +from typing import TypeGuard + +from netaddr.ip import IPAddress, IPNetwork, IPRange, _IPAddressAddr, _IPNetworkAddr + +def valid_glob(ipglob: object) -> TypeGuard[str]: ... +def glob_to_iptuple(ipglob: str) -> tuple[IPAddress, IPAddress]: ... +def glob_to_iprange(ipglob: str) -> IPRange: ... +def iprange_to_globs(start: _IPAddressAddr, end: _IPAddressAddr) -> list[str]: ... +def glob_to_cidrs(ipglob: str) -> list[IPNetwork]: ... +def cidr_to_glob(cidr: _IPNetworkAddr) -> str: ... + +class IPGlob(IPRange): + __slots__ = ("_glob",) + def __init__(self, ipglob: str) -> None: ... + + @property + def glob(self) -> str: ... + @glob.setter + def glob(self, value: str) -> None: ... diff --git a/stubs/netaddr/netaddr/ip/iana.pyi b/stubs/netaddr/netaddr/ip/iana.pyi new file mode 100644 index 000000000000..1d205a275d25 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/iana.pyi @@ -0,0 +1,51 @@ +from _typeshed import SupportsWrite +from collections.abc import Callable, Mapping, MutableMapping +from typing import Any, TypeAlias +from xml.sax import _Source, handler +from xml.sax.xmlreader import AttributesImpl, InputSource, XMLReader + +from netaddr.core import Publisher, Subscriber +from netaddr.ip import IPAddress, IPNetwork, IPRange + +_IanaInfoKey: TypeAlias = IPAddress | IPNetwork | IPRange + +IANA_INFO: dict[str, dict[_IanaInfoKey, dict[str, str]]] + +class SaxRecordParser(handler.ContentHandler): + def __init__(self, callback: Callable[[Mapping[str, object] | None], object] | None = None) -> None: ... + def startElement(self, name: str, attrs: AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def characters(self, content: str) -> None: ... + +class XMLRecordParser(Publisher): + xmlparser: XMLReader + fh: InputSource | _Source + def __init__(self, fh: InputSource | _Source, **kwargs: object) -> None: ... + def process_record(self, rec: Mapping[str, object]) -> dict[str, str] | None: ... + def consume_record(self, rec: object) -> None: ... + def parse(self) -> None: ... + # Arbitrary attributes are set in __init__ with `self.__dict__.update(kwargs)` + def __getattr__(self, name: str, /) -> Any: ... + +class IPv4Parser(XMLRecordParser): + def process_record(self, rec: Mapping[str, object]) -> dict[str, str]: ... + +class IPv6Parser(XMLRecordParser): + def process_record(self, rec: Mapping[str, object]) -> dict[str, str]: ... + +class IPv6UnicastParser(XMLRecordParser): + def process_record(self, rec: Mapping[str, object]) -> dict[str, str]: ... + +class MulticastParser(XMLRecordParser): + def normalise_addr(self, addr: str) -> str: ... + +class DictUpdater(Subscriber): + dct: MutableMapping[_IanaInfoKey, dict[str, Any]] + topic: str + unique_key: str + def __init__(self, dct: MutableMapping[_IanaInfoKey, dict[str, Any]], topic: str, unique_key: str) -> None: ... + def update(self, data: dict[str, Any]) -> None: ... + +def load_info() -> None: ... +def pprint_info(fh: SupportsWrite[str] | None = None) -> None: ... +def query(ip_addr: IPAddress) -> dict[str, list[dict[str, str]]]: ... diff --git a/stubs/netaddr/netaddr/ip/nmap.pyi b/stubs/netaddr/netaddr/ip/nmap.pyi new file mode 100644 index 000000000000..b63826b5ec95 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/nmap.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterator + +from netaddr.ip import IPAddress + +def valid_nmap_range(target_spec: str) -> bool: ... +def iter_nmap_range(*nmap_target_spec: str) -> Iterator[IPAddress]: ... diff --git a/stubs/netaddr/netaddr/ip/rfc1924.pyi b/stubs/netaddr/netaddr/ip/rfc1924.pyi new file mode 100644 index 000000000000..6a4199bf0bae --- /dev/null +++ b/stubs/netaddr/netaddr/ip/rfc1924.pyi @@ -0,0 +1,9 @@ +from netaddr.ip import _IPAddressAddr + +def chr_range(low: str, high: str) -> list[str]: ... + +BASE_85: list[str] +BASE_85_DICT: dict[str, int] + +def ipv6_to_base85(addr: _IPAddressAddr) -> str: ... +def base85_to_ipv6(addr: str) -> str: ... diff --git a/stubs/netaddr/netaddr/ip/sets.pyi b/stubs/netaddr/netaddr/ip/sets.pyi new file mode 100644 index 000000000000..d8656f69b548 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/sets.pyi @@ -0,0 +1,46 @@ +from collections.abc import Iterable, Iterator +from typing import TypeAlias +from typing_extensions import Never, Self + +from netaddr.ip import IPAddress, IPNetwork, IPRange, _IPNetworkAddr + +_IPIterable: TypeAlias = IPNetwork | IPRange | IPSet | Iterable[_IPNetworkAddr | IPRange | int] + +class IPSet: + __slots__ = ("_cidrs", "__weakref__") + def __init__(self, iterable: _IPIterable | None = None, flags: int = 0) -> None: ... + def compact(self) -> None: ... + def __hash__(self) -> Never: ... + def __contains__(self, ip: _IPNetworkAddr) -> bool: ... + def __bool__(self) -> bool: ... + def __iter__(self) -> Iterator[IPAddress]: ... + def iter_cidrs(self) -> list[IPNetwork]: ... + def add(self, addr: IPRange | _IPNetworkAddr | int, flags: int = 0) -> None: ... + def remove(self, addr: IPRange | _IPNetworkAddr | int, flags: int = 0) -> None: ... + def pop(self) -> IPNetwork: ... + def isdisjoint(self, other: IPSet) -> bool: ... + def copy(self) -> Self: ... + def update(self, iterable: _IPIterable, flags: int = 0) -> None: ... + def clear(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: IPSet) -> bool: ... + def issubset(self, other: IPSet) -> bool: ... + __le__ = issubset + def __gt__(self, other: IPSet) -> bool: ... + def issuperset(self, other: IPSet) -> bool: ... + __ge__ = issuperset + def union(self, other: IPSet) -> Self: ... + __or__ = union + def intersection(self, other: IPSet) -> IPSet: ... + __and__ = intersection + def symmetric_difference(self, other: IPSet) -> IPSet: ... + __xor__ = symmetric_difference + def difference(self, other: IPSet) -> IPSet: ... + __sub__ = difference + def __len__(self) -> int: ... + @property + def size(self) -> int: ... + def iscontiguous(self) -> bool: ... + def iprange(self) -> IPRange | None: ... + def iter_ipranges(self) -> Iterator[IPRange]: ... diff --git a/stubs/netaddr/netaddr/strategy/__init__.pyi b/stubs/netaddr/netaddr/strategy/__init__.pyi new file mode 100644 index 000000000000..0e93ac08c1b2 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/__init__.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable, Sequence + +def bytes_to_bits() -> list[str]: ... + +BYTES_TO_BITS: list[str] + +def valid_words(words: Iterable[int], word_size: int, num_words: int) -> bool: ... +def int_to_words(int_val: int, word_size: int, num_words: int) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int], word_size: int, num_words: int) -> int: ... +def valid_bits(bits: str, width: int, word_sep: str = "") -> bool: ... +def bits_to_int(bits: str, width: int, word_sep: str = "") -> int: ... +def int_to_bits(int_val: int, word_size: int, num_words: int, word_sep: str = "") -> str: ... +def valid_bin(bin_val: str, width: int) -> bool: ... +def int_to_bin(int_val: int, width: int) -> str: ... +def bin_to_int(bin_val: str, width: int) -> int: ... diff --git a/stubs/netaddr/netaddr/strategy/eui48.pyi b/stubs/netaddr/netaddr/strategy/eui48.pyi new file mode 100644 index 000000000000..cd5f73b2f362 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/eui48.pyi @@ -0,0 +1,39 @@ +from collections.abc import Iterable, Sequence +from re import Pattern +from typing import ClassVar, Literal + +width: Literal[48] +version: Literal[48] +max_int: int + +class mac_eui48: + word_size: ClassVar[int] + num_words: ClassVar[int] + max_word: ClassVar[int] + word_sep: ClassVar[str] + word_fmt: ClassVar[str] + word_base: ClassVar[int] + +class mac_unix(mac_eui48): ... +class mac_unix_expanded(mac_unix): ... +class mac_cisco(mac_eui48): ... +class mac_bare(mac_eui48): ... +class mac_pgsql(mac_eui48): ... + +DEFAULT_DIALECT: type[mac_eui48] +RE_MAC_FORMATS: list[Pattern[str]] + +def valid_str(addr: str) -> bool: ... +def str_to_int(addr: str) -> int: ... +def int_to_str(int_val: int, dialect: type[mac_eui48] | None = None) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int], dialect: type[mac_eui48] | None = None) -> bool: ... +def int_to_words(int_val: int, dialect: type[mac_eui48] | None = None) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int], dialect: type[mac_eui48] | None = None) -> int: ... +def valid_bits(bits: str, dialect: type[mac_eui48] | None = None) -> bool: ... +def bits_to_int(bits: str, dialect: type[mac_eui48] | None = None) -> int: ... +def int_to_bits(int_val: int, dialect: type[mac_eui48] | None = None) -> str: ... +def valid_bin(bin_val: str, dialect: type[mac_eui48] | None = None) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... diff --git a/stubs/netaddr/netaddr/strategy/eui64.pyi b/stubs/netaddr/netaddr/strategy/eui64.pyi new file mode 100644 index 000000000000..19d02f085e80 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/eui64.pyi @@ -0,0 +1,38 @@ +from collections.abc import Iterable, Sequence +from re import Pattern +from typing import ClassVar, Literal + +width: Literal[64] +version: Literal[64] +max_int: int + +class eui64_base: + word_size: ClassVar[int] + num_words: ClassVar[int] + max_word: ClassVar[int] + word_sep: ClassVar[str] + word_fmt: ClassVar[str] + word_base: ClassVar[int] + +class eui64_unix(eui64_base): ... +class eui64_unix_expanded(eui64_unix): ... +class eui64_cisco(eui64_base): ... +class eui64_bare(eui64_base): ... + +DEFAULT_EUI64_DIALECT: type[eui64_base] +RE_EUI64_FORMATS: list[Pattern[str]] + +def valid_str(addr: str) -> bool: ... +def str_to_int(addr: str) -> int: ... +def int_to_str(int_val: int, dialect: type[eui64_base] | None = None) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int], dialect: type[eui64_base] | None = None) -> bool: ... +def int_to_words(int_val: int, dialect: type[eui64_base] | None = None) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int], dialect: type[eui64_base] | None = None) -> int: ... +def valid_bits(bits: str, dialect: type[eui64_base] | None = None) -> bool: ... +def bits_to_int(bits: str, dialect: type[eui64_base] | None = None) -> int: ... +def int_to_bits(int_val: int, dialect: type[eui64_base] | None = None) -> str: ... +def valid_bin(bin_val: str, dialect: type[eui64_base] | None = None) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... diff --git a/stubs/netaddr/netaddr/strategy/ipv4.pyi b/stubs/netaddr/netaddr/strategy/ipv4.pyi new file mode 100644 index 000000000000..b9510c4ed763 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/ipv4.pyi @@ -0,0 +1,39 @@ +from _typeshed import Unused +from collections.abc import Iterable, Sequence +from socket import AddressFamily +from typing import Literal + +from netaddr.core import INET_PTON as INET_PTON, ZEROFILL as ZEROFILL + +width: Literal[32] +word_size: Literal[8] +word_fmt: Literal["%d"] +word_sep: Literal["."] +family: Literal[AddressFamily.AF_INET] +family_name: Literal["IPv4"] +version: Literal[4] +word_base: Literal[10] +max_int: int +num_words: Literal[4] +max_word: int +prefix_to_netmask: dict[int, int] +netmask_to_prefix: dict[int, int] +prefix_to_hostmask: dict[int, int] +hostmask_to_prefix: dict[int, int] + +def valid_str(addr: str, flags: int = 0) -> bool: ... +def str_to_int(addr: str, flags: int = 0) -> int: ... +def int_to_str(int_val: int, dialect: Unused = None) -> str: ... +def int_to_arpa(int_val: int) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int]) -> bool: ... +def int_to_words(int_val: int) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int]) -> int: ... +def valid_bits(bits: str) -> bool: ... +def bits_to_int(bits: str) -> int: ... +def int_to_bits(int_val: int, word_sep: str | None = None) -> str: ... +def valid_bin(bin_val: str) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... +def expand_partial_address(addr: str) -> str: ... diff --git a/stubs/netaddr/netaddr/strategy/ipv6.pyi b/stubs/netaddr/netaddr/strategy/ipv6.pyi new file mode 100644 index 000000000000..a2988ffb8837 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/ipv6.pyi @@ -0,0 +1,43 @@ +from collections.abc import Iterable, Sequence +from typing import ClassVar, Final, Literal + +from netaddr.fbsocket import AF_INET6 + +OPT_IMPORTS: bool +width: Literal[128] +word_size: Literal[16] +word_sep: Literal[":"] +family: Final = AF_INET6 +family_name: Literal["IPv6"] +version: Literal[6] +word_base: Literal[16] +max_int: int +num_words: Literal[8] +max_word: int +prefix_to_netmask: dict[int, int] +netmask_to_prefix: dict[int, int] +prefix_to_hostmask: dict[int, int] +hostmask_to_prefix: dict[int, int] + +class ipv6_compact: + word_fmt: ClassVar[str] + compact: ClassVar[bool] + +class ipv6_full(ipv6_compact): ... +class ipv6_verbose(ipv6_compact): ... + +def valid_str(addr: str, flags: int = 0) -> bool: ... +def str_to_int(addr: str, flags: int = 0) -> int: ... +def int_to_str(int_val: int, dialect: type[ipv6_compact] | None = None) -> str: ... +def int_to_arpa(int_val: int) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int]) -> bool: ... +def int_to_words(int_val: int, num_words: int | None = None, word_size: int | None = None) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int]) -> int: ... +def valid_bits(bits: str) -> bool: ... +def bits_to_int(bits: str) -> int: ... +def int_to_bits(int_val: int, word_sep: str | None = None) -> str: ... +def valid_bin(bin_val: str) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... diff --git a/stubs/netifaces/@tests/stubtest_allowlist.txt b/stubs/netifaces/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..553280bdb8d9 --- /dev/null +++ b/stubs/netifaces/@tests/stubtest_allowlist.txt @@ -0,0 +1,34 @@ +# Values that may not always exist at runtime, as they are system-specific. +netifaces.AF_12844 +netifaces.AF_ATM +netifaces.AF_BAN +netifaces.AF_CCITT +netifaces.AF_CHAOS +netifaces.AF_CLUSTER +netifaces.AF_CNT +netifaces.AF_COIP +netifaces.AF_DATAKIT +netifaces.AF_DLI +netifaces.AF_ECMA +netifaces.AF_FIREFOX +netifaces.AF_HYLINK +netifaces.AF_IMPLINK +netifaces.AF_ISO +netifaces.AF_LAT +netifaces.AF_NATM +netifaces.AF_NDRV +netifaces.AF_NETBIOS +netifaces.AF_NETDES +netifaces.AF_NETGRAPH +netifaces.AF_NS +netifaces.AF_PPP +netifaces.AF_PUP +netifaces.AF_SIP +netifaces.AF_SYSTEM +netifaces.AF_UNKNOWN1 +netifaces.AF_VOICEVIEW +netifaces.IN6_IFF_AUTOCONF +netifaces.IN6_IFF_DYNAMIC +netifaces.IN6_IFF_OPTIMISTIC +netifaces.IN6_IFF_SECURED +netifaces.IN6_IFF_TEMPORARY diff --git a/stubs/netifaces/METADATA.toml b/stubs/netifaces/METADATA.toml new file mode 100644 index 000000000000..a6a6a2608f55 --- /dev/null +++ b/stubs/netifaces/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.11.*" +upstream-repository = "https://github.com/al45tair/netifaces" diff --git a/stubs/netifaces/netifaces.pyi b/stubs/netifaces/netifaces.pyi new file mode 100644 index 000000000000..fa146c35761c --- /dev/null +++ b/stubs/netifaces/netifaces.pyi @@ -0,0 +1,72 @@ +from typing import Final, Literal + +AF_12844: Final[int] +AF_APPLETALK: Final[int] +AF_ASH: Final[int] +AF_ATM: Final[int] +AF_ATMPVC: Final[int] +AF_ATMSVC: Final[int] +AF_AX25: Final[int] +AF_BAN: Final[int] +AF_BLUETOOTH: Final[int] +AF_BRIDGE: Final[int] +AF_DATAKIT: Final[int] +AF_DECnet: Final[int] +AF_CCITT: Final[int] +AF_CHAOS: Final[int] +AF_CLUSTER: Final[int] +AF_CNT: Final[int] +AF_COIP: Final[int] +AF_DLI: Final[int] +AF_ECONET: Final[int] +AF_ECMA: Final[int] +AF_FILE: Final[int] +AF_FIREFOX: Final[int] +AF_HYLINK: Final[int] +AF_IMPLINK: Final[int] +AF_INET: Final[int] +AF_INET6: Final[int] +AF_IPX: Final[int] +AF_IRDA: Final[int] +AF_ISDN: Final[int] +AF_ISO: Final[int] +AF_KEY: Final[int] +AF_LAT: Final[int] +AF_LINK: Final[int] +AF_NATM: Final[int] +AF_NETBEUI: Final[int] +AF_NETBIOS: Final[int] +AF_NETDES: Final[int] +AF_NETGRAPH: Final[int] +AF_NETLINK: Final[int] +AF_NETROM: Final[int] +AF_NDRV: Final[int] +AF_NS: Final[int] +AF_PACKET: Final[int] +AF_PPP: Final[int] +AF_PPPOX: Final[int] +AF_PUP: Final[int] +AF_ROSE: Final[int] +AF_ROUTE: Final[int] +AF_SECURITY: Final[int] +AF_SIP: Final[int] +AF_SNA: Final[int] +AF_SYSTEM: Final[int] +AF_UNIX: Final[int] +AF_UNKNOWN1: Final[int] +AF_UNSPEC: Final[int] +AF_VOICEVIEW: Final[int] +AF_WANPIPE: Final[int] +AF_X25: Final[int] +IN6_IFF_AUTOCONF: Final[int] +IN6_IFF_TEMPORARY: Final[int] +IN6_IFF_DYNAMIC: Final[int] +IN6_IFF_OPTIMISTIC: Final[int] +IN6_IFF_SECURED: Final[int] + +address_families: Final[dict[int, str]] +version: Final[str] + +def gateways() -> dict[int | Literal["default"], list[tuple[str, str, bool] | tuple[str, str]] | dict[int, tuple[str, str]]]: ... +def ifaddresses(ifname: str, /) -> dict[int, list[dict[str, str]]]: ... +def interfaces() -> list[str]: ... diff --git a/stubs/networkx/@tests/stubtest_allowlist.txt b/stubs/networkx/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b53baec2a0d1 --- /dev/null +++ b/stubs/networkx/@tests/stubtest_allowlist.txt @@ -0,0 +1,39 @@ +# overloaded class-decorators are not properly supported in type-checkers: +# - mypy: https://github.com/python/mypy/issues/16840 +# - pyright: https://github.com/microsoft/pyright/issues/7167 +networkx\.(algorithms\.)?(boundary\.)?edge_boundary +networkx\.(algorithms\.)?(bridges\.)?local_bridges +networkx\.(algorithms\.)?(clique\.)?node_clique_number +networkx\.(convert_matrix\.)?from_numpy_array +networkx\.(convert_matrix\.)?from_pandas_adjacency +networkx\.(convert_matrix\.)?from_pandas_edgelist +networkx\.(generators\.)?(random_clustered\.)?random_clustered_graph +networkx\.(relabel\.)?relabel_nodes + +# Stubtest doesn't understand aliases of class-decorated functions (possibly https://github.com/python/mypy/issues/6700 ) +networkx\.(algorithms\.)?(centrality\.)?(current_flow_closeness\.)?information_centrality +networkx\.(generators\.)?(random_graphs\.)?binomial_graph +networkx\.(generators\.)?(random_graphs\.)?erdos_renyi_graph +networkx\.(algorithms\.(minors\.(contraction\.)?)?)?identified_nodes +networkx\.algorithms\.flow\.maxflow\.default_flow_func +networkx\.algorithms\.[a-z_\.]+\.default_flow_func +networkx\.(algorithms\.(centrality\.(load\.)?)?)?load_centrality +networkx\.algorithms\.bipartite\.(matching\.)?maximum_matching +networkx\.algorithms\.bipartite\.(cluster\.)?clustering + +# Stubtest says: "runtime argument "backend" has a default value of type None, which is +# incompatible with stub argument type builtins.str. This is often caused by overloads +# failing to account for explicitly passing in the default value." +# Which is true, but would require some way of concatenating `backend` to ParamSpec.kwargs +networkx\.(utils\.)?(backends\.)?_dispatchable\.__call__ + +# Tests are excluded +networkx.conftest +networkx(\..+?)?\.tests(\..+?)? + +# Stub-only module +networkx\._typing + +# "..._DT is not present at runtime" but we don't set it in stubs, I don't understand this one +networkx(\.algorithms)?(\.tree)?(\.mst)?\.SpanningTreeIterator\.Partition\._DT +networkx(\.algorithms)?(\.tree)?(\.branchings)?\.ArborescenceIterator\.Partition\._DT diff --git a/stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py b/stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py new file mode 100644 index 000000000000..c4bb02d2026e --- /dev/null +++ b/stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py @@ -0,0 +1,23 @@ +from typing_extensions import assert_type + +from networkx.utils.backends import _dispatchable + + +@_dispatchable +def some_method(int_p: int, str_p: str) -> float: + return 0.0 + + +# Wrong param / order +some_method("", 0) # type: ignore +# backend is kw-only +some_method(0, "", None) # type: ignore +# No backend means no **backend_kwargs allowed +some_method(0, "", backend_specific_kwarg="") # type: ignore +some_method(0, "", backend=None, backend_specific_kwarg="") # type: ignore + +# Correct usage +assert_type(some_method(0, ""), float) +# type system doesn't allow this yet (see comment in networkx/utils/backends.pyi) +# assert_type(some_method(0, "", backend=None), float) +assert_type(some_method(0, "", backend="custom backend", backend_specific_kwarg=""), float) diff --git a/stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py b/stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py new file mode 100644 index 000000000000..20a38a85a8ad --- /dev/null +++ b/stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py @@ -0,0 +1,25 @@ +from typing_extensions import assert_type + +import networkx as nx +from networkx.classes.reportviews import DegreeView, DiDegreeView + +# Test covariant dict type for `pos` in nx_latex functions +G: "nx.Graph[int]" = nx.Graph([(1, 2), (2, 3), (3, 4)]) +nx.to_latex_raw(G, pos=nx.spring_layout(G, seed=42)) # OK: dict[node, ndarray] +pos1: dict[int, tuple[int, int]] = {1: (1, 2), 2: (3, 4), 3: (5, 6), 4: (7, 8)} +nx.to_latex_raw(G, pos=pos1) # OK: dict[node, 2-tuple] +pos2: dict[int, str] = {1: "(1, 2)", 2: "(3, 4)", 3: "(5, 6)", 4: "(7, 8)"} +nx.to_latex_raw(G, pos=pos2) # OK: dict[node, str] +pos3: dict[int, int] = {1: 1, 2: 3, 3: 5, 4: 7} +nx.to_latex_raw(G, pos=pos3) # type: ignore # dict keys must be str or collection + +# Test that we don't confuse str and Iterable[str] in DiDegreeView.__call__ +G_str = nx.Graph[str]() +di_degree_view = DiDegreeView(G_str) +assert_type(di_degree_view(""), int) +assert_type(di_degree_view([""]), DiDegreeView[str]) +assert_type(di_degree_view({""}), DiDegreeView[str]) +degree_view = DegreeView(G_str) +assert_type(degree_view(""), int) +assert_type(degree_view([""]), DegreeView[str]) +assert_type(degree_view({""}), DegreeView[str]) diff --git a/stubs/networkx/METADATA.toml b/stubs/networkx/METADATA.toml new file mode 100644 index 000000000000..0f83cc29aabf --- /dev/null +++ b/stubs/networkx/METADATA.toml @@ -0,0 +1,8 @@ +version = "3.6.1" +upstream-repository = "https://github.com/networkx/networkx" +# Requires a version of NumPy with `numpy.typing.NDArray`. +optional-dependencies = ["numpy>=1.21"] + +[tool.stubtest] +# stub_uploader won't allow pandas-stubs in the requires field https://github.com/typeshed-internal/stub_uploader/issues/90 +stubtest-dependencies = ["pandas"] diff --git a/stubs/networkx/networkx/__init__.pyi b/stubs/networkx/networkx/__init__.pyi new file mode 100644 index 000000000000..bdd328fb405a --- /dev/null +++ b/stubs/networkx/networkx/__init__.pyi @@ -0,0 +1,30 @@ +from typing import Final + +from networkx.algorithms import * +from networkx.classes import * +from networkx.classes import filters as filters +from networkx.convert import * +from networkx.convert_matrix import * +from networkx.drawing import * +from networkx.exception import * +from networkx.generators import * +from networkx.lazy_imports import _lazy_import as _lazy_import +from networkx.linalg import * +from networkx.readwrite import * +from networkx.relabel import * +from networkx.utils import _clear_cache as _clear_cache, _dispatchable as _dispatchable, config as config + +from . import ( + algorithms as algorithms, + classes as classes, + convert as convert, + convert_matrix as convert_matrix, + drawing as drawing, + generators as generators, + linalg as linalg, + readwrite as readwrite, + relabel as relabel, + utils as utils, +) + +__version__: Final[str] diff --git a/stubs/networkx/networkx/_typing.pyi b/stubs/networkx/networkx/_typing.pyi new file mode 100644 index 000000000000..b82d9673deb0 --- /dev/null +++ b/stubs/networkx/networkx/_typing.pyi @@ -0,0 +1,22 @@ +# Stub-only module, can't be imported at runtime. + +from collections.abc import Collection +from typing import Any, Protocol, TypeAlias, type_check_only +from typing_extensions import TypeVar + +import numpy as np + +_ScalarT = TypeVar("_ScalarT", bound=bool | int | float | complex | str | bytes | np.generic) +_GenericT = TypeVar("_GenericT", bound=np.generic) +_GenericT_co = TypeVar("_GenericT_co", bound=np.generic, covariant=True) +_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], default=Any, covariant=True) + +# numpy aliases +@type_check_only +class SupportsArray(Protocol[_GenericT_co, _ShapeT_co]): + def __array__(self) -> np.ndarray[_ShapeT_co, np.dtype[_GenericT_co]]: ... + +ArrayLike1D: TypeAlias = Collection[_ScalarT] | SupportsArray[_GenericT, tuple[int]] +Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_GenericT]] +Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_GenericT]] +Seed: TypeAlias = int | np.random.Generator | np.random.RandomState diff --git a/stubs/networkx/networkx/algorithms/__init__.pyi b/stubs/networkx/networkx/algorithms/__init__.pyi new file mode 100644 index 000000000000..7dc8465ff47b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/__init__.pyi @@ -0,0 +1,140 @@ +from networkx.algorithms import ( + approximation as approximation, + assortativity as assortativity, + bipartite as bipartite, + centrality as centrality, + chordal as chordal, + clique as clique, + cluster as cluster, + coloring as coloring, + community as community, + components as components, + connectivity as connectivity, + flow as flow, + isomorphism as isomorphism, + link_analysis as link_analysis, + lowest_common_ancestors as lowest_common_ancestors, + node_classification as node_classification, + operators as operators, + shortest_paths as shortest_paths, + tournament as tournament, + traversal as traversal, + tree as tree, +) +from networkx.algorithms.assortativity import * +from networkx.algorithms.asteroidal import * +from networkx.algorithms.bipartite import ( + complete_bipartite_graph as complete_bipartite_graph, + is_bipartite as is_bipartite, + projected_graph as projected_graph, +) +from networkx.algorithms.boundary import * +from networkx.algorithms.bridges import * +from networkx.algorithms.broadcasting import * +from networkx.algorithms.centrality import * +from networkx.algorithms.chains import * +from networkx.algorithms.chordal import * +from networkx.algorithms.clique import * +from networkx.algorithms.cluster import * +from networkx.algorithms.coloring import * +from networkx.algorithms.communicability_alg import * +from networkx.algorithms.components import * +from networkx.algorithms.connectivity import ( + all_node_cuts as all_node_cuts, + all_pairs_node_connectivity as all_pairs_node_connectivity, + average_node_connectivity as average_node_connectivity, + edge_connectivity as edge_connectivity, + edge_disjoint_paths as edge_disjoint_paths, + is_k_edge_connected as is_k_edge_connected, + k_components as k_components, + k_edge_augmentation as k_edge_augmentation, + k_edge_components as k_edge_components, + k_edge_subgraphs as k_edge_subgraphs, + minimum_edge_cut as minimum_edge_cut, + minimum_node_cut as minimum_node_cut, + node_connectivity as node_connectivity, + node_disjoint_paths as node_disjoint_paths, + stoer_wagner as stoer_wagner, +) +from networkx.algorithms.core import * +from networkx.algorithms.covering import * +from networkx.algorithms.cuts import * +from networkx.algorithms.cycles import * +from networkx.algorithms.d_separation import * +from networkx.algorithms.dag import * +from networkx.algorithms.distance_measures import * +from networkx.algorithms.distance_regular import * +from networkx.algorithms.dominance import * +from networkx.algorithms.dominating import * +from networkx.algorithms.efficiency_measures import * +from networkx.algorithms.euler import * +from networkx.algorithms.flow import ( + capacity_scaling as capacity_scaling, + cost_of_flow as cost_of_flow, + gomory_hu_tree as gomory_hu_tree, + max_flow_min_cost as max_flow_min_cost, + maximum_flow as maximum_flow, + maximum_flow_value as maximum_flow_value, + min_cost_flow as min_cost_flow, + min_cost_flow_cost as min_cost_flow_cost, + minimum_cut as minimum_cut, + minimum_cut_value as minimum_cut_value, + network_simplex as network_simplex, +) +from networkx.algorithms.graph_hashing import * +from networkx.algorithms.graphical import * +from networkx.algorithms.hierarchy import * +from networkx.algorithms.hybrid import * +from networkx.algorithms.isolate import * +from networkx.algorithms.isomorphism import ( + could_be_isomorphic as could_be_isomorphic, + fast_could_be_isomorphic as fast_could_be_isomorphic, + faster_could_be_isomorphic as faster_could_be_isomorphic, + is_isomorphic as is_isomorphic, +) +from networkx.algorithms.isomorphism.vf2pp import * +from networkx.algorithms.link_analysis import * +from networkx.algorithms.link_prediction import * +from networkx.algorithms.lowest_common_ancestors import * +from networkx.algorithms.matching import * +from networkx.algorithms.minors import * +from networkx.algorithms.mis import * +from networkx.algorithms.moral import * +from networkx.algorithms.non_randomness import * +from networkx.algorithms.operators import * +from networkx.algorithms.perfect_graph import * +from networkx.algorithms.planar_drawing import * +from networkx.algorithms.planarity import * +from networkx.algorithms.polynomials import * +from networkx.algorithms.reciprocity import * +from networkx.algorithms.regular import * +from networkx.algorithms.richclub import * +from networkx.algorithms.shortest_paths import * +from networkx.algorithms.similarity import * +from networkx.algorithms.simple_paths import * +from networkx.algorithms.smallworld import * +from networkx.algorithms.smetric import * +from networkx.algorithms.sparsifiers import * +from networkx.algorithms.structuralholes import * +from networkx.algorithms.summarization import * +from networkx.algorithms.swap import * +from networkx.algorithms.time_dependent import * +from networkx.algorithms.tournament import is_tournament as is_tournament +from networkx.algorithms.traversal import * +from networkx.algorithms.tree.branchings import ( + ArborescenceIterator as ArborescenceIterator, + maximum_branching as maximum_branching, + maximum_spanning_arborescence as maximum_spanning_arborescence, + minimum_branching as minimum_branching, + minimum_spanning_arborescence as minimum_spanning_arborescence, +) +from networkx.algorithms.tree.coding import * +from networkx.algorithms.tree.decomposition import * +from networkx.algorithms.tree.mst import * +from networkx.algorithms.tree.operations import * +from networkx.algorithms.tree.recognition import * +from networkx.algorithms.triads import * +from networkx.algorithms.vitality import * +from networkx.algorithms.voronoi import * +from networkx.algorithms.walks import * +from networkx.algorithms.wiener import * diff --git a/stubs/networkx/networkx/algorithms/approximation/__init__.pyi b/stubs/networkx/networkx/algorithms/approximation/__init__.pyi new file mode 100644 index 000000000000..c80fffaef227 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/__init__.pyi @@ -0,0 +1,14 @@ +from networkx.algorithms.approximation.clique import * +from networkx.algorithms.approximation.clustering_coefficient import * +from networkx.algorithms.approximation.connectivity import * +from networkx.algorithms.approximation.density import * +from networkx.algorithms.approximation.distance_measures import * +from networkx.algorithms.approximation.dominating_set import * +from networkx.algorithms.approximation.kcomponents import * +from networkx.algorithms.approximation.matching import * +from networkx.algorithms.approximation.maxcut import * +from networkx.algorithms.approximation.ramsey import * +from networkx.algorithms.approximation.steinertree import * +from networkx.algorithms.approximation.traveling_salesman import * +from networkx.algorithms.approximation.treewidth import * +from networkx.algorithms.approximation.vertex_cover import * diff --git a/stubs/networkx/networkx/algorithms/approximation/clique.pyi b/stubs/networkx/networkx/algorithms/approximation/clique.pyi new file mode 100644 index 000000000000..f0d3d435d5c8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/clique.pyi @@ -0,0 +1,13 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["clique_removal", "max_clique", "large_clique_size", "maximum_independent_set"] + +@_dispatchable +def maximum_independent_set(G: Graph[_Node]) -> set[_Node]: ... +@_dispatchable +def max_clique(G: Graph[_Node]) -> set[_Node]: ... +@_dispatchable +def clique_removal(G: Graph[_Node]) -> tuple[set[_Node], list[set[_Node]]]: ... +@_dispatchable +def large_clique_size(G: Graph[_Node]) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi b/stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi new file mode 100644 index 000000000000..cff53629ceb7 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi @@ -0,0 +1,8 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["average_clustering"] + +@_dispatchable +def average_clustering(G: Graph[_Node], trials: int = 1000, seed: int | RandomState | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/connectivity.pyi b/stubs/networkx/networkx/algorithms/approximation/connectivity.pyi new file mode 100644 index 000000000000..6fc71c4130eb --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/connectivity.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["local_node_connectivity", "node_connectivity", "all_pairs_node_connectivity"] + +@_dispatchable +def local_node_connectivity(G: Graph[_Node], source: _Node, target: _Node, cutoff: float | None = None) -> float: ... +@_dispatchable +def node_connectivity(G: Graph[_Node], s: _Node | None = None, t: _Node | None = None) -> float: ... +@_dispatchable +def all_pairs_node_connectivity( + G: Graph[_Node], nbunch: Iterable[_Node] | None = None, cutoff: float | None = None +) -> dict[_Node, dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/density.pyi b/stubs/networkx/networkx/algorithms/approximation/density.pyi new file mode 100644 index 000000000000..8d84f8373b39 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/density.pyi @@ -0,0 +1,14 @@ +from collections.abc import Callable, Hashable +from typing import Literal, TypeAlias + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_Algorithm: TypeAlias = Literal["greedy++", "fista"] + +__all__ = ["densest_subgraph"] + +ALGORITHMS: dict[_Algorithm, Callable[[Graph[Hashable], int], tuple[float, set[int]]]] + +@_dispatchable +def densest_subgraph(G: Graph[_Node], iterations: int = 1, *, method: _Algorithm = "fista") -> tuple[float, set[int]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi b/stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi new file mode 100644 index 000000000000..f52a300f8f66 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi @@ -0,0 +1,8 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["diameter"] + +@_dispatchable +def diameter(G: Graph[_Node], seed: int | RandomState | None = None) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi b/stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi new file mode 100644 index 000000000000..e37d3713ce42 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_weighted_dominating_set", "min_edge_dominating_set"] + +@_dispatchable +def min_weighted_dominating_set(G: Graph[_Node], weight: str | None = None) -> set[Incomplete]: ... +@_dispatchable +def min_edge_dominating_set(G: Graph[_Node]) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi b/stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi new file mode 100644 index 000000000000..e0fe94385cd5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections import defaultdict + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_components"] + +@_dispatchable +def k_components(G: Graph[_Node], min_density: float = 0.95) -> defaultdict[Incomplete, list[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/matching.pyi b/stubs/networkx/networkx/algorithms/approximation/matching.pyi new file mode 100644 index 000000000000..7b5f723d44d0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/matching.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_maximal_matching"] + +@_dispatchable +def min_maximal_matching(G: Graph[_Node]) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/maxcut.pyi b/stubs/networkx/networkx/algorithms/approximation/maxcut.pyi new file mode 100644 index 000000000000..4518df47f2a1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/maxcut.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["randomized_partitioning", "one_exchange"] + +@_dispatchable +def randomized_partitioning( + G: Graph[_Node], seed: int | RandomState | None = None, p: float = 0.5, weight: str | None = None +) -> tuple[float, tuple[set[Incomplete], set[Incomplete]]]: ... +@_dispatchable +def one_exchange( + G: Graph[_Node], initial_cut: set[Incomplete] | None = None, seed: int | RandomState | None = None, weight: str | None = None +) -> tuple[float, tuple[set[Incomplete], set[Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/ramsey.pyi b/stubs/networkx/networkx/algorithms/approximation/ramsey.pyi new file mode 100644 index 000000000000..f1248ef9d101 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/ramsey.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["ramsey_R2"] + +@_dispatchable +def ramsey_R2(G: Graph[_Node]) -> tuple[set[Incomplete], set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/steinertree.pyi b/stubs/networkx/networkx/algorithms/approximation/steinertree.pyi new file mode 100644 index 000000000000..4f761fa97e24 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/steinertree.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing_extensions import deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["metric_closure", "steiner_tree"] + +@_dispatchable +@deprecated( + "`metric_closure` is deprecated and will be removed in NetworkX 3.8. Use `networkx.all_pairs_shortest_path_length` instead." +) +def metric_closure(G: Graph[_Node], weight="weight") -> Graph[Incomplete]: ... +@_dispatchable +def steiner_tree( + G: Graph[_Node], terminal_nodes: Iterable[Incomplete], weight: str = "weight", method: str | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi b/stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi new file mode 100644 index 000000000000..3c388b8d6677 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Literal, TypeVar + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "traveling_salesman_problem", + "christofides", + "asadpour_atsp", + "greedy_tsp", + "simulated_annealing_tsp", + "threshold_accepting_tsp", +] + +_SupportsLenAndGetItemT = TypeVar("_SupportsLenAndGetItemT", bound=SupportsLenAndGetItem[Any]) + +def swap_two_nodes(soln: _SupportsLenAndGetItemT, seed) -> _SupportsLenAndGetItemT: ... +def move_one_node(soln: _SupportsLenAndGetItemT, seed) -> _SupportsLenAndGetItemT: ... +@_dispatchable +def christofides(G: Graph[_Node], weight: str | None = "weight", tree: Graph[_Node] | None = None) -> list[Incomplete]: ... +@_dispatchable +def traveling_salesman_problem( + G: Graph[_Node], + weight: str = "weight", + nodes=None, + cycle: bool = True, + method: Callable[..., Incomplete] | None = None, + **kwargs, +) -> list[Incomplete]: ... +@_dispatchable +def asadpour_atsp( + G: DiGraph[_Node], weight: str | None = "weight", seed: int | RandomState | None = None, source: str | None = None +) -> list[Incomplete]: ... +@_dispatchable +def held_karp_ascent( + G: Graph[_Node], weight: str = "weight" +) -> tuple[float, dict[Incomplete, Incomplete] | Graph[Incomplete]]: ... +@_dispatchable +def spanning_tree_distribution(G: Graph[_Node], z: Mapping[Incomplete, Incomplete]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def greedy_tsp(G: Graph[_Node], weight: str | None = "weight", source=None) -> list[Incomplete]: ... +@_dispatchable +def simulated_annealing_tsp( + G: Graph[_Node], + init_cycle: Literal["greedy"] | Iterable[Incomplete], + weight: str | None = "weight", + source=None, + temp: int | None = 100, + move: Callable[..., Incomplete] | Literal["1-1", "1-0"] = "1-1", + max_iterations: int | None = 10, + N_inner: int | None = 100, + alpha: float = 0.01, + seed: int | RandomState | None = None, +) -> list[Incomplete]: ... +@_dispatchable +def threshold_accepting_tsp( + G: Graph[_Node], + init_cycle: Literal["greedy"] | Iterable[Incomplete], + weight: str | None = "weight", + source=None, + threshold: int | None = 1, + move: Callable[..., Incomplete] | Literal["1-1", "1-0"] = "1-1", + max_iterations: int | None = 10, + N_inner: int | None = 100, + alpha: float = 0.1, + seed: int | RandomState | None = None, +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/treewidth.pyi b/stubs/networkx/networkx/algorithms/approximation/treewidth.pyi new file mode 100644 index 000000000000..6a9f9afe2d39 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/treewidth.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from typing import Generic + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["treewidth_min_degree", "treewidth_min_fill_in"] + +@_dispatchable +def treewidth_min_degree(G: Graph[_Node]) -> tuple[int, Graph[frozenset[_Node]]]: ... +@_dispatchable +def treewidth_min_fill_in(G: Graph[_Node]) -> tuple[int, Graph[frozenset[_Node]]]: ... + +class MinDegreeHeuristic(Generic[_Node]): + count: Incomplete + + def __init__(self, graph: Graph[_Node]) -> None: ... + def best_node(self, graph: Mapping[_Node, set[_Node]]) -> _Node | None: ... + +def min_fill_in_heuristic(graph_dict: Mapping[_Node, set[_Node]]) -> _Node | None: ... +@_dispatchable +def treewidth_decomp( + G: Graph[_Node], heuristic: Callable[[dict[_Node, set[_Node]]], _Node | None] = ... +) -> tuple[int, Graph[frozenset[_Node]]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi b/stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi new file mode 100644 index 000000000000..abec263a7bd0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_weighted_vertex_cover"] + +@_dispatchable +def min_weighted_vertex_cover(G: Graph[_Node], weight: str | None = None) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/__init__.pyi b/stubs/networkx/networkx/algorithms/assortativity/__init__.pyi new file mode 100644 index 000000000000..4d9888609cbc --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/__init__.pyi @@ -0,0 +1,5 @@ +from networkx.algorithms.assortativity.connectivity import * +from networkx.algorithms.assortativity.correlation import * +from networkx.algorithms.assortativity.mixing import * +from networkx.algorithms.assortativity.neighbor_degree import * +from networkx.algorithms.assortativity.pairs import * diff --git a/stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi b/stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi new file mode 100644 index 000000000000..349d6cff8a3c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["average_degree_connectivity"] + +@_dispatchable +def average_degree_connectivity( + G: Graph[_Node], + source: Literal["in+out", "out", "in"] = "in+out", + target: Literal["in+out", "out", "in"] = "in+out", + nodes: Iterable[Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, int | float]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/correlation.pyi b/stubs/networkx/networkx/algorithms/assortativity/correlation.pyi new file mode 100644 index 000000000000..78f36749726d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/correlation.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "degree_pearson_correlation_coefficient", + "degree_assortativity_coefficient", + "attribute_assortativity_coefficient", + "numeric_assortativity_coefficient", +] + +@_dispatchable +def degree_assortativity_coefficient( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes: Iterable[Incomplete] | None = None +) -> float: ... +@_dispatchable +def degree_pearson_correlation_coefficient( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes: Iterable[Incomplete] | None = None +) -> float: ... +@_dispatchable +def attribute_assortativity_coefficient(G: Graph[_Node], attribute: str, nodes: Iterable[Incomplete] | None = None) -> float: ... +@_dispatchable +def numeric_assortativity_coefficient(G: Graph[_Node], attribute: str, nodes: Iterable[Incomplete] | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/mixing.pyi b/stubs/networkx/networkx/algorithms/assortativity/mixing.pyi new file mode 100644 index 000000000000..ef4764e3d59d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/mixing.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["attribute_mixing_matrix", "attribute_mixing_dict", "degree_mixing_matrix", "degree_mixing_dict", "mixing_dict"] + +@_dispatchable +def attribute_mixing_dict( + G: Graph[_Node], attribute: str, nodes: Iterable[Incomplete] | None = None, normalized: bool = False +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def attribute_mixing_matrix( + G: Graph[_Node], + attribute: str, + nodes: Iterable[Incomplete] | None = None, + mapping: Mapping[Incomplete, Incomplete] | None = None, + normalized: bool = True, +) -> np.ndarray[Incomplete, Incomplete]: ... +@_dispatchable +def degree_mixing_dict( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes=None, normalized: bool = False +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def degree_mixing_matrix( + G: Graph[_Node], + x: str = "out", + y: str = "in", + weight: str | None = None, + nodes: Iterable[Incomplete] | None = None, + normalized: bool = True, + mapping: Mapping[Incomplete, Incomplete] | None = None, +) -> np.ndarray[Incomplete, Incomplete]: ... +@_dispatchable +def mixing_dict(xy: Iterable[tuple[Incomplete, Incomplete]], normalized: bool = False) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi b/stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi new file mode 100644 index 000000000000..231c1966d0eb --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["average_neighbor_degree"] + +@_dispatchable +def average_neighbor_degree( + G: Graph[_Node], + source: str | None = "out", + target: str | None = "out", + nodes: Iterable[Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/pairs.pyi b/stubs/networkx/networkx/algorithms/assortativity/pairs.pyi new file mode 100644 index 000000000000..502d5346f0d6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/pairs.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["node_attribute_xy", "node_degree_xy"] + +@_dispatchable +def node_attribute_xy(G: Graph[_Node], attribute, nodes: Iterable[Incomplete] | None = None) -> Generator[Incomplete]: ... +@_dispatchable +def node_degree_xy( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes: Iterable[Incomplete] | None = None +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/asteroidal.pyi b/stubs/networkx/networkx/algorithms/asteroidal.pyi new file mode 100644 index 000000000000..9e4dbd34028f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/asteroidal.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_at_free", "find_asteroidal_triple"] + +@_dispatchable +def find_asteroidal_triple(G: Graph[_Node]) -> list[Incomplete] | None: ... +@_dispatchable +def is_at_free(G: Graph[_Node]) -> bool: ... +@_dispatchable +def create_component_structure(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/__init__.pyi b/stubs/networkx/networkx/algorithms/bipartite/__init__.pyi new file mode 100644 index 000000000000..7b9c7b3c0d3c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/__init__.pyi @@ -0,0 +1,13 @@ +from networkx.algorithms.bipartite.basic import * +from networkx.algorithms.bipartite.centrality import * +from networkx.algorithms.bipartite.cluster import * +from networkx.algorithms.bipartite.covering import * +from networkx.algorithms.bipartite.edgelist import * +from networkx.algorithms.bipartite.extendability import * +from networkx.algorithms.bipartite.generators import * +from networkx.algorithms.bipartite.link_analysis import * +from networkx.algorithms.bipartite.matching import * +from networkx.algorithms.bipartite.matrix import * +from networkx.algorithms.bipartite.projection import * +from networkx.algorithms.bipartite.redundancy import * +from networkx.algorithms.bipartite.spectral import * diff --git a/stubs/networkx/networkx/algorithms/bipartite/basic.pyi b/stubs/networkx/networkx/algorithms/bipartite/basic.pyi new file mode 100644 index 000000000000..8610070f70ce --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/basic.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Collection, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_bipartite", "is_bipartite_node_set", "color", "sets", "density", "degrees"] + +@_dispatchable +def color(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def is_bipartite(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_bipartite_node_set(G: Graph[_Node], nodes: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def sets(G: Graph[_Node], top_nodes: Iterable[Incomplete] | None = None) -> tuple[set[Incomplete], set[Incomplete]]: ... +@_dispatchable +def density(B: Graph[_Node], nodes: Collection[Incomplete]) -> float: ... +@_dispatchable +def degrees(B: Graph[_Node], nodes: Iterable[Incomplete], weight: str | None = None) -> tuple[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/centrality.pyi b/stubs/networkx/networkx/algorithms/bipartite/centrality.pyi new file mode 100644 index 000000000000..90ac03059f80 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/centrality.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"] + +@_dispatchable +def degree_centrality(G: Graph[_Node], nodes: Iterable[Incomplete]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def betweenness_centrality(G: Graph[_Node], nodes: Iterable[Incomplete]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def closeness_centrality( + G: Graph[_Node], nodes: Iterable[Incomplete], normalized: bool | None = True +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/cluster.pyi b/stubs/networkx/networkx/algorithms/bipartite/cluster.pyi new file mode 100644 index 000000000000..1a341ef85e92 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/cluster.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["clustering", "average_clustering", "latapy_clustering", "robins_alexander_clustering"] + +def cc_dot(nu, nv) -> float: ... +def cc_max(nu, nv) -> float: ... +def cc_min(nu, nv) -> float: ... + +modes: dict[str, Callable[[Incomplete, Incomplete], float]] + +@_dispatchable +def latapy_clustering( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, mode: str = "dot" +) -> dict[Incomplete, Incomplete]: ... + +clustering = latapy_clustering + +@_dispatchable +def average_clustering(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, mode: str = "dot") -> float: ... +@_dispatchable +def robins_alexander_clustering(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/covering.pyi b/stubs/networkx/networkx/algorithms/bipartite/covering.pyi new file mode 100644 index 000000000000..ab33bcecf487 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/covering.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_edge_cover"] + +@_dispatchable +def min_edge_cover(G: Graph[_Node], matching_algorithm: Callable[..., Incomplete] | None = None) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi b/stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi new file mode 100644 index 000000000000..de80e3d56b41 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Collection, Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"] + +@_dispatchable +def write_edgelist( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + comments: str = "#", + delimiter: str = " ", + data: bool = True, + encoding: str = "utf-8", +) -> None: ... +@_dispatchable +def generate_edgelist(G: Graph[_Node], delimiter: str = " ", data: bool = True) -> Generator[str]: ... +@_dispatchable +def parse_edgelist( + lines: Iterable[str], + comments: str | None = "#", + delimiter: str | None = None, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + nodetype: type[Incomplete] | None = None, + data: bool | Collection[tuple[str, type[Incomplete]]] = True, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_edgelist( + path: StrPath | SupportsRead[bytes], + comments: str | None = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype=None, + data: bool | Collection[tuple[str, type[Incomplete]]] = True, + edgetype=None, + encoding: str | None = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/extendability.pyi b/stubs/networkx/networkx/algorithms/bipartite/extendability.pyi new file mode 100644 index 000000000000..3269743ce9c2 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/extendability.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["maximal_extendability"] + +@_dispatchable +def maximal_extendability(G: Graph[_Node]) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/generators.pyi b/stubs/networkx/networkx/algorithms/bipartite/generators.pyi new file mode 100644 index 000000000000..cf5b9686cfb9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/generators.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "configuration_model", + "havel_hakimi_graph", + "reverse_havel_hakimi_graph", + "alternating_havel_hakimi_graph", + "preferential_attachment_graph", + "random_graph", + "gnmk_random_graph", + "complete_bipartite_graph", +] + +@_dispatchable +def complete_bipartite_graph(n1, n2, create_using: Graph[_Node] | type[Graph[_Node]] | None = None): ... +@_dispatchable +def configuration_model( + aseq: Iterable[Incomplete], + bseq: Iterable[Incomplete], + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + seed: int | RandomState | None = None, +): ... +@_dispatchable +def havel_hakimi_graph( + aseq: Iterable[Incomplete], bseq: Iterable[Incomplete], create_using: Graph[_Node] | type[Graph[_Node]] | None = None +): ... +@_dispatchable +def reverse_havel_hakimi_graph( + aseq: Iterable[Incomplete], bseq: Iterable[Incomplete], create_using: Graph[_Node] | type[Graph[_Node]] | None = None +): ... +@_dispatchable +def alternating_havel_hakimi_graph( + aseq: Iterable[Incomplete], bseq: Iterable[Incomplete], create_using: Graph[_Node] | type[Graph[_Node]] | None = None +): ... +@_dispatchable +def preferential_attachment_graph( + aseq: Iterable[Incomplete], + p: float, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + seed: int | RandomState | None = None, +): ... +@_dispatchable +def random_graph(n: int, m: int, p: float, seed: int | RandomState | None = None, directed: bool | None = False): ... +@_dispatchable +def gnmk_random_graph(n: int, m: int, k: int, seed: int | RandomState | None = None, directed: bool | None = False): ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi b/stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi new file mode 100644 index 000000000000..75a125908432 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi @@ -0,0 +1,20 @@ +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["birank"] + +@_dispatchable +def birank( + G: Graph[_Node], + nodes: Iterable[_Node], + *, + alpha: float | None = None, + beta: float | None = None, + top_personalization: Mapping[_Node, float] | None = None, + bottom_personalization: Mapping[_Node, float] | None = None, + max_iter: int = 100, + tol: float = 1.0e-6, + weight: str | None = "weight", +) -> dict[_Node, float]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/matching.pyi b/stubs/networkx/networkx/algorithms/bipartite/matching.pyi new file mode 100644 index 000000000000..d0df0b6da990 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/matching.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["maximum_matching", "hopcroft_karp_matching", "eppstein_matching", "to_vertex_cover", "minimum_weight_full_matching"] + +@_dispatchable +def hopcroft_karp_matching(G: Graph[_Node], top_nodes: Iterable[_Node] | None = None) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def eppstein_matching(G: Graph[_Node], top_nodes: Iterable[Incomplete] | None = None) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def to_vertex_cover( + G: Graph[_Node], matching: Mapping[Incomplete, Incomplete], top_nodes: Iterable[Incomplete] | None = None +) -> set[Incomplete]: ... + +maximum_matching = hopcroft_karp_matching + +@_dispatchable +def minimum_weight_full_matching( + G: Graph[_Node], top_nodes: Iterable[Incomplete] | None = None, weight: str | None = "weight" +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/matrix.pyi b/stubs/networkx/networkx/algorithms/bipartite/matrix.pyi new file mode 100644 index 000000000000..18bca470ca7f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/matrix.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["biadjacency_matrix", "from_biadjacency_matrix"] + +@_dispatchable +def biadjacency_matrix( + G: Graph[_Node], + row_order: Iterable[_Node], + column_order: Iterable[Incomplete] | None = None, + dtype: np.dtype[Incomplete] | None = None, + weight: str | None = "weight", + format: str = "csr", +): ... # Return is a complex union of scipy classes depending on the format param +@_dispatchable +def from_biadjacency_matrix( + A, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + edge_attribute: str = "weight", + *, + row_order: Iterable[Incomplete] | None = None, + column_order: Iterable[Incomplete] | None = None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/projection.pyi b/stubs/networkx/networkx/algorithms/bipartite/projection.pyi new file mode 100644 index 000000000000..3d383557dbf5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/projection.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "projected_graph", + "weighted_projected_graph", + "collaboration_weighted_projected_graph", + "overlap_weighted_projected_graph", + "generic_weighted_projected_graph", +] + +@_dispatchable +def projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete], multigraph: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def weighted_projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete], ratio: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def collaboration_weighted_projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def overlap_weighted_projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete], jaccard: bool = True) -> Graph[Incomplete]: ... +@_dispatchable +def generic_weighted_projected_graph( + B: Graph[_Node], nodes: Iterable[Incomplete], weight_function: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi b/stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi new file mode 100644 index 000000000000..539e8012ad11 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["node_redundancy"] + +@_dispatchable +def node_redundancy(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None) -> dict[Incomplete, float]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/spectral.pyi b/stubs/networkx/networkx/algorithms/bipartite/spectral.pyi new file mode 100644 index 000000000000..e7102d54aefe --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/spectral.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["spectral_bipartivity"] + +@_dispatchable +def spectral_bipartivity( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, weight: str = "weight" +) -> float | dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/boundary.pyi b/stubs/networkx/networkx/algorithms/boundary.pyi new file mode 100644 index 000000000000..358ed74eb197 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/boundary.pyi @@ -0,0 +1,112 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import TypeVar, overload + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_U = TypeVar("_U") +__all__ = ["edge_boundary", "node_boundary"] + +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, dict[str, _U]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, dict[str, _U]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, int, dict[str, _U]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, int, dict[str, _U]]]: ... + +@_dispatchable +def node_boundary(G: Graph[_Node], nbunch1: Iterable[Incomplete], nbunch2: Iterable[Incomplete] | None = None) -> set[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/bridges.pyi b/stubs/networkx/networkx/algorithms/bridges.pyi new file mode 100644 index 000000000000..104a682bc24c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bridges.pyi @@ -0,0 +1,17 @@ +from collections.abc import Generator +from typing import overload + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["bridges", "has_bridges", "local_bridges"] + +@_dispatchable +def bridges(G: Graph[_Node], root: _Node | None = None) -> Generator[_Node]: ... +@_dispatchable +def has_bridges(G: Graph[_Node], root: _Node | None = None) -> bool: ... + +@overload +def local_bridges(G: Graph[_Node], with_span: bool = True, weight: str | None = None) -> Generator[tuple[_Node, _Node]]: ... +@overload +def local_bridges(G: Graph[_Node], with_span: bool = True, weight: str | None = None) -> Generator[tuple[_Node, _Node, int]]: ... diff --git a/stubs/networkx/networkx/algorithms/broadcasting.pyi b/stubs/networkx/networkx/algorithms/broadcasting.pyi new file mode 100644 index 000000000000..e61d77b28e7c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/broadcasting.pyi @@ -0,0 +1,9 @@ +import networkx as nx +from networkx.classes.graph import Graph, _Node + +__all__ = ["tree_broadcast_center", "tree_broadcast_time"] + +@nx._dispatchable +def tree_broadcast_center(G: Graph[_Node]) -> tuple[int, set[_Node]]: ... +@nx._dispatchable +def tree_broadcast_time(G: Graph[_Node], node: int | None = None) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/__init__.pyi b/stubs/networkx/networkx/algorithms/centrality/__init__.pyi new file mode 100644 index 000000000000..4a8ceb436a4b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/__init__.pyi @@ -0,0 +1,20 @@ +from .betweenness import * +from .betweenness_subset import * +from .closeness import * +from .current_flow_betweenness import * +from .current_flow_betweenness_subset import * +from .current_flow_closeness import * +from .degree_alg import * +from .dispersion import * +from .eigenvector import * +from .group import * +from .harmonic import * +from .katz import * +from .laplacian import * +from .load import * +from .percolation import * +from .reaching import * +from .second_order import * +from .subgraph_alg import * +from .trophic import * +from .voterank_alg import * diff --git a/stubs/networkx/networkx/algorithms/centrality/betweenness.pyi b/stubs/networkx/networkx/algorithms/centrality/betweenness.pyi new file mode 100644 index 000000000000..ddaf1288a3d4 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/betweenness.pyi @@ -0,0 +1,23 @@ +from networkx.classes.graph import Graph, _Edge, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["betweenness_centrality", "edge_betweenness_centrality"] + +@_dispatchable +def betweenness_centrality( + G: Graph[_Node], + k: int | None = None, + normalized: bool | None = True, + weight: str | None = None, + endpoints: bool | None = False, + seed: int | RandomState | None = None, +) -> dict[_Node, float]: ... +@_dispatchable +def edge_betweenness_centrality( + G: Graph[_Node], + k: int | None = None, + normalized: bool | None = True, + weight: str | None = None, + seed: int | RandomState | None = None, +) -> dict[_Edge[_Node], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi b/stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi new file mode 100644 index 000000000000..8f91e193b844 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi @@ -0,0 +1,23 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Edge, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["betweenness_centrality_subset", "edge_betweenness_centrality_subset"] + +@_dispatchable +def betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = False, + weight: str | None = None, +) -> dict[_Node, float]: ... +@_dispatchable +def edge_betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = False, + weight: str | None = None, +) -> dict[_Edge[_Node], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/closeness.pyi b/stubs/networkx/networkx/algorithms/centrality/closeness.pyi new file mode 100644 index 000000000000..7719ca78e687 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/closeness.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete, SupportsKeysAndGetItem + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["closeness_centrality", "incremental_closeness_centrality"] + +@_dispatchable +def closeness_centrality( + G: Graph[_Node], u: _Node | None = None, distance=None, wf_improved: bool | None = True +) -> dict[_Node, float]: ... +@_dispatchable +def incremental_closeness_centrality( + G: Graph[_Node], + edge: tuple[Incomplete], + prev_cc: SupportsKeysAndGetItem[Incomplete, Incomplete] | None = None, + insertion: bool | None = True, + wf_improved: bool | None = True, +) -> dict[_Node, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi new file mode 100644 index 000000000000..cfee1601ec36 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "current_flow_betweenness_centrality", + "approximate_current_flow_betweenness_centrality", + "edge_current_flow_betweenness_centrality", +] + +@_dispatchable +def approximate_current_flow_betweenness_centrality( + G: Graph[_Node], + normalized: bool | None = True, + weight: str | None = None, + dtype: type = ..., + solver: str = "full", + epsilon: float = 0.5, + kmax: int = 10000, + seed: int | RandomState | None = None, + *, + sample_weight: float = 1, +) -> dict[Incomplete, float]: ... +@_dispatchable +def current_flow_betweenness_centrality( + G: Graph[_Node], normalized: bool | None = True, weight: str | None = None, dtype: type = ..., solver: str = "full" +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def edge_current_flow_betweenness_centrality( + G: Graph[_Node], normalized: bool | None = True, weight: str | None = None, dtype: type = ..., solver: str = "full" +) -> dict[tuple[Incomplete, Incomplete], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi new file mode 100644 index 000000000000..b7f38a4c9b31 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["current_flow_betweenness_centrality_subset", "edge_current_flow_betweenness_centrality_subset"] + +@_dispatchable +def current_flow_betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = True, + weight: str | None = None, + dtype: type = ..., + solver: str = "lu", +) -> dict[Incomplete, float]: ... +@_dispatchable +def edge_current_flow_betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = True, + weight: str | None = None, + dtype: type = ..., + solver: str = "lu", +) -> dict[tuple[Incomplete, Incomplete], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi b/stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi new file mode 100644 index 000000000000..d7b95eeea326 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["current_flow_closeness_centrality", "information_centrality"] + +@_dispatchable +def current_flow_closeness_centrality( + G: Graph[_Node], weight: str | None = None, dtype: type = ..., solver: str = "lu" +) -> dict[Incomplete, float]: ... + +information_centrality = current_flow_closeness_centrality diff --git a/stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi b/stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi new file mode 100644 index 000000000000..a3d4719c8eba --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi @@ -0,0 +1,11 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["degree_centrality", "in_degree_centrality", "out_degree_centrality"] + +@_dispatchable +def degree_centrality(G: Graph[_Node]) -> dict[_Node, float]: ... +@_dispatchable +def in_degree_centrality(G: Graph[_Node]) -> dict[_Node, float]: ... +@_dispatchable +def out_degree_centrality(G: Graph[_Node]) -> dict[_Node, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/dispersion.pyi b/stubs/networkx/networkx/algorithms/centrality/dispersion.pyi new file mode 100644 index 000000000000..4cc9ed0f4de0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/dispersion.pyi @@ -0,0 +1,15 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dispersion"] + +@_dispatchable +def dispersion( + G: Graph[_Node], + u: _Node | None = None, + v: _Node | None = None, + normalized: bool = True, + alpha: float = 1.0, + b: float = 0.0, + c: float = 0.0, +) -> dict[_Node, float] | dict[_Node, dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi b/stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi new file mode 100644 index 000000000000..75ee56abc272 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["eigenvector_centrality", "eigenvector_centrality_numpy"] + +@_dispatchable +def eigenvector_centrality( + G: Graph[_Node], + max_iter: int | None = 100, + tol: float | None = 1e-06, + nstart: Mapping[Incomplete, Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, float]: ... +@_dispatchable +def eigenvector_centrality_numpy( + G: Graph[_Node], weight: str | None = None, max_iter: int | None = 50, tol: float | None = 0 +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi b/stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi new file mode 100644 index 000000000000..6b41a4822a94 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +@_dispatchable +def flow_matrix_row(G: Graph[_Node], weight=None, dtype=..., solver: str = "lu") -> Generator[Incomplete]: ... + +class InverseLaplacian: + dtype: Incomplete + n: Incomplete + w: Incomplete + C: Incomplete + L1: Incomplete + + def __init__(self, L, width=None, dtype=None) -> None: ... + def init_solver(self, L) -> None: ... + def solve(self, r) -> None: ... + def solve_inverse(self, r) -> None: ... + def get_rows(self, r1, r2): ... + def get_row(self, r): ... + def width(self, L): ... + +class FullInverseLaplacian(InverseLaplacian): + IL: Incomplete + + def init_solver(self, L) -> None: ... + def solve(self, rhs): ... + def solve_inverse(self, r): ... + +class SuperLUInverseLaplacian(InverseLaplacian): + lusolve: Incomplete + + def init_solver(self, L) -> None: ... + def solve_inverse(self, r): ... + def solve(self, rhs): ... + +class CGInverseLaplacian(InverseLaplacian): + M: Incomplete + + def init_solver(self, L) -> None: ... + def solve(self, rhs): ... + def solve_inverse(self, r): ... diff --git a/stubs/networkx/networkx/algorithms/centrality/group.pyi b/stubs/networkx/networkx/algorithms/centrality/group.pyi new file mode 100644 index 000000000000..3a5e6b880783 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/group.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Collection, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "group_betweenness_centrality", + "group_closeness_centrality", + "group_degree_centrality", + "group_in_degree_centrality", + "group_out_degree_centrality", + "prominent_group", +] + +@_dispatchable +def group_betweenness_centrality( + G: Graph[_Node], + C: Collection[Incomplete], + normalized: bool | None = True, + weight: str | None = None, + endpoints: bool | None = False, +) -> list[float] | float: ... +@_dispatchable +def prominent_group( + G: Graph[_Node], + k: int, + weight: str | None = None, + C: Iterable[Incomplete] | None = None, + endpoints: bool | None = False, + normalized: bool | None = True, + greedy: bool | None = False, +) -> tuple[float, list[Incomplete]]: ... +@_dispatchable +def group_closeness_centrality(G: Graph[_Node], S: Iterable[Incomplete], weight: str | None = None) -> float: ... +@_dispatchable +def group_degree_centrality(G: Graph[_Node], S: Iterable[Incomplete]) -> float: ... +@_dispatchable +def group_in_degree_centrality(G: Graph[_Node], S: Iterable[Incomplete]) -> float: ... +@_dispatchable +def group_out_degree_centrality(G: Graph[_Node], S: Iterable[Incomplete]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/harmonic.pyi b/stubs/networkx/networkx/algorithms/centrality/harmonic.pyi new file mode 100644 index 000000000000..4b00562653f8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/harmonic.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["harmonic_centrality"] + +@_dispatchable +def harmonic_centrality( + G: Graph[_Node], nbunch: Iterable[Incomplete] | None = None, distance=None, sources: Iterable[Incomplete] | None = None +) -> dict[Incomplete, int]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/katz.pyi b/stubs/networkx/networkx/algorithms/centrality/katz.pyi new file mode 100644 index 000000000000..b8b8cda7b7e5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/katz.pyi @@ -0,0 +1,27 @@ +from _typeshed import ConvertibleToFloat, Incomplete, SupportsItemAccess +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["katz_centrality", "katz_centrality_numpy"] + +@_dispatchable +def katz_centrality( + G: Graph[_Node], + alpha: float | None = 0.1, + beta: ConvertibleToFloat | Iterable[Incomplete] | None = 1.0, + max_iter: int | None = 1000, + tol: float | None = 1e-06, + nstart: SupportsItemAccess[Incomplete, Incomplete] | None = None, + normalized: bool | None = True, + weight: str | None = None, +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def katz_centrality_numpy( + G: Graph[_Node], + alpha: float = 0.1, + beta: float | Mapping[Incomplete, Incomplete] | None = 1.0, + normalized: bool = True, + weight: str | None = None, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/laplacian.pyi b/stubs/networkx/networkx/algorithms/centrality/laplacian.pyi new file mode 100644 index 000000000000..fa270ac3847c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/laplacian.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Collection + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["laplacian_centrality"] + +@_dispatchable +def laplacian_centrality( + G: Graph[_Node], + normalized: bool = True, + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + walk_type: str | None = None, + alpha: float = 0.95, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/load.pyi b/stubs/networkx/networkx/algorithms/centrality/load.pyi new file mode 100644 index 000000000000..30677a841399 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/load.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["load_centrality", "edge_load_centrality"] + +@_dispatchable +def newman_betweenness_centrality( + G: Graph[_Node], v=None, cutoff: bool | None = None, normalized: bool | None = True, weight: str | None = None +) -> float | dict[Incomplete, float]: ... + +load_centrality = newman_betweenness_centrality + +@_dispatchable +def edge_load_centrality(G: Graph[_Node], cutoff: bool | None = False) -> dict[tuple[Incomplete, Incomplete], int]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/percolation.pyi b/stubs/networkx/networkx/algorithms/centrality/percolation.pyi new file mode 100644 index 000000000000..becea462a050 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/percolation.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["percolation_centrality"] + +@_dispatchable +def percolation_centrality( + G: Graph[_Node], + attribute: str | None = "percolation", + states: Mapping[Incomplete, Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/reaching.pyi b/stubs/networkx/networkx/algorithms/centrality/reaching.pyi new file mode 100644 index 000000000000..b491df5addf8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/reaching.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["global_reaching_centrality", "local_reaching_centrality"] + +@_dispatchable +def global_reaching_centrality(G: DiGraph[_Node], weight: str | None = None, normalized: bool | None = True) -> float: ... +@_dispatchable +def local_reaching_centrality( + G: DiGraph[_Node], + v: _Node, + paths: Mapping[Incomplete, Incomplete] | None = None, + weight: str | None = None, + normalized: bool | None = True, +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/second_order.pyi b/stubs/networkx/networkx/algorithms/centrality/second_order.pyi new file mode 100644 index 000000000000..d6f64bcd4bda --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/second_order.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["second_order_centrality"] + +@_dispatchable +def second_order_centrality(G: Graph[_Node], weight: str | None = "weight") -> dict[Incomplete, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi b/stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi new file mode 100644 index 000000000000..c6824639b2d1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["subgraph_centrality_exp", "subgraph_centrality", "communicability_betweenness_centrality", "estrada_index"] + +@_dispatchable +def subgraph_centrality_exp(G: Graph[_Node], *, normalized: bool = False) -> dict[Incomplete, float]: ... +@_dispatchable +def subgraph_centrality(G: Graph[_Node], *, normalized: bool = False) -> dict[Incomplete, float]: ... +@_dispatchable +def communicability_betweenness_centrality(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def estrada_index(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/trophic.pyi b/stubs/networkx/networkx/algorithms/centrality/trophic.pyi new file mode 100644 index 000000000000..4215c89b46d1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/trophic.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["trophic_levels", "trophic_differences", "trophic_incoherence_parameter"] + +@_dispatchable +def trophic_levels(G: DiGraph[_Node], weight="weight") -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def trophic_differences(G: DiGraph[_Node], weight="weight") -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def trophic_incoherence_parameter(G: DiGraph[_Node], weight="weight", cannibalism: bool = False) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi b/stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi new file mode 100644 index 000000000000..4dc2bb55728d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["voterank"] + +@_dispatchable +def voterank(G: Graph[_Node], number_of_nodes: int | None = None) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/chains.pyi b/stubs/networkx/networkx/algorithms/chains.pyi new file mode 100644 index 000000000000..00c7ed63fbfe --- /dev/null +++ b/stubs/networkx/networkx/algorithms/chains.pyi @@ -0,0 +1,9 @@ +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["chain_decomposition"] + +@_dispatchable +def chain_decomposition(G: Graph[_Node], root: _Node | None = None) -> Generator[list[tuple[_Node, _Node]]]: ... diff --git a/stubs/networkx/networkx/algorithms/chordal.pyi b/stubs/networkx/networkx/algorithms/chordal.pyi new file mode 100644 index 000000000000..e7ad7d1d93d0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/chordal.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.exception import NetworkXException +from networkx.utils.backends import _dispatchable + +__all__ = [ + "is_chordal", + "find_induced_nodes", + "chordal_graph_cliques", + "chordal_graph_treewidth", + "NetworkXTreewidthBoundExceeded", + "complete_to_chordal_graph", +] + +class NetworkXTreewidthBoundExceeded(NetworkXException): ... + +@_dispatchable +def is_chordal(G: Graph[_Node]) -> bool: ... +@_dispatchable +def find_induced_nodes(G: Graph[_Node], s: _Node, t: _Node, treewidth_bound: float = sys.maxsize) -> set[_Node]: ... +@_dispatchable +def chordal_graph_cliques(G: Graph[_Node]) -> Generator[frozenset[_Node]]: ... +@_dispatchable +def chordal_graph_treewidth(G: Graph[_Node]) -> int: ... +@_dispatchable +def complete_to_chordal_graph(G: Graph[_Node]) -> tuple[Incomplete, dict[Incomplete, int]]: ... diff --git a/stubs/networkx/networkx/algorithms/clique.pyi b/stubs/networkx/networkx/algorithms/clique.pyi new file mode 100644 index 000000000000..225fc56a64e6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/clique.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Iterator +from typing import overload + +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "find_cliques", + "find_cliques_recursive", + "make_max_clique_graph", + "make_clique_bipartite", + "node_clique_number", + "number_of_cliques", + "enumerate_all_cliques", + "max_weight_clique", +] + +@_dispatchable +def enumerate_all_cliques(G: Graph[_Node]) -> Generator[list[_Node]]: ... +@_dispatchable +def find_cliques(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def find_cliques_recursive(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None) -> Iterator[list[_Node]]: ... +@_dispatchable +def make_max_clique_graph( + G: Graph[_Node], create_using: Graph[_Node, _NodeData, _EdgeData] | type[Graph[_Node, _NodeData, _EdgeData]] | None = None +) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def make_clique_bipartite( + G: Graph[_Node, _NodeData, _EdgeData], + fpos: bool | None = None, + create_using: Graph[_Node, _NodeData, _EdgeData] | type[Graph[_Node, _NodeData, _EdgeData]] | None = None, + name=None, +) -> Graph[_Node]: ... + +@overload +def node_clique_number( + G: Graph[_Node], nodes=None, cliques: Iterable[Incomplete] | None = None, separate_nodes=False +) -> dict[_Node, int]: ... +@overload +def node_clique_number(G: Graph[_Node], nodes=None, cliques: Iterable[Incomplete] | None = None, separate_nodes=False) -> int: ... + +def number_of_cliques( + G: Graph[_Node], nodes: list[_Node] | _Node | None = None, cliques: Iterable[Incomplete] | None = None +) -> int | dict[Incomplete, Incomplete]: ... +@_dispatchable +def max_weight_clique(G: Graph[_Node], weight: str | None = "weight") -> tuple[list[Incomplete], int]: ... + +class MaxWeightClique: + G: Graph[Incomplete] + incumbent_nodes: list[Incomplete] + incumbent_weight: int + node_weights: dict[Incomplete, int] + def __init__(self, G: Graph[_Node], weight): ... + def update_incumbent_if_improved(self, C, C_weight): ... + def greedily_find_independent_set(self, P): ... + def find_branching_nodes(self, P, target): ... + def expand(self, C, C_weight, P): ... + def find_max_weight_clique(self): ... diff --git a/stubs/networkx/networkx/algorithms/cluster.pyi b/stubs/networkx/networkx/algorithms/cluster.pyi new file mode 100644 index 000000000000..ba66252cac44 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/cluster.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from collections import Counter +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _NBunch, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "triangles", + "all_triangles", + "average_clustering", + "clustering", + "transitivity", + "square_clustering", + "generalized_degree", +] + +@_dispatchable +def triangles(G: Graph[_Node], nodes=None) -> int | dict[Incomplete, int]: ... +@_dispatchable +def all_triangles(G: Graph[_Node], nbunch: _NBunch[_Node] = None) -> Generator[tuple[Incomplete, Incomplete, Incomplete]]: ... +@_dispatchable +def average_clustering( + G: Graph[_Node], nodes: Iterable[_Node] | None = None, weight: str | None = None, count_zeros: bool = True +) -> float: ... +@_dispatchable +def clustering(G: Graph[_Node], nodes=None, weight: str | None = None) -> float | int | dict[Incomplete, float | int]: ... +@_dispatchable +def transitivity(G: Graph[_Node]) -> float: ... +@_dispatchable +def square_clustering(G: Graph[_Node], nodes: Iterable[_Node] | None = None) -> float | int | dict[Incomplete, float | int]: ... +@_dispatchable +def generalized_degree( + G: Graph[_Node], nodes: Iterable[_Node] | None = None +) -> Counter[Incomplete] | dict[Incomplete, Counter[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/coloring/__init__.pyi b/stubs/networkx/networkx/algorithms/coloring/__init__.pyi new file mode 100644 index 000000000000..764088306473 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/coloring/__init__.pyi @@ -0,0 +1,4 @@ +from networkx.algorithms.coloring.equitable_coloring import equitable_color as equitable_color +from networkx.algorithms.coloring.greedy_coloring import * + +__all__ = ["greedy_color", "equitable_color"] diff --git a/stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi b/stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi new file mode 100644 index 000000000000..bae8b30ab4f1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Mapping +from typing import SupportsIndex + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["equitable_color"] + +@_dispatchable +def is_coloring(G: Graph[_Node], coloring: SupportsGetItem[Incomplete, Incomplete]) -> bool: ... +@_dispatchable +def is_equitable(G: Graph[_Node], coloring: Mapping[Incomplete, Incomplete], num_colors: SupportsIndex | None = None) -> bool: ... +def make_C_from_F(F): ... +def make_N_from_L_C(L, C): ... +def make_H_from_C_N(C, N): ... +def change_color(u, X, Y, N, H, F, C, L): ... +def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L): ... +@_dispatchable +def pad_graph(G: Graph[_Node], num_colors): ... +def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None): ... +@_dispatchable +def equitable_color(G: Graph[_Node], num_colors: int) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi b/stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi new file mode 100644 index 000000000000..d3287b494edd --- /dev/null +++ b/stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Generator +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "greedy_color", + "strategy_connected_sequential", + "strategy_connected_sequential_bfs", + "strategy_connected_sequential_dfs", + "strategy_independent_set", + "strategy_largest_first", + "strategy_random_sequential", + "strategy_saturation_largest_first", + "strategy_smallest_last", +] + +@_dispatchable +def strategy_largest_first(G: Graph[_Node], colors: Unused): ... +@_dispatchable +def strategy_random_sequential(G: Graph[_Node], colors: Unused, seed=None): ... +@_dispatchable +def strategy_smallest_last(G: Graph[_Node], colors: Unused): ... +@_dispatchable +def strategy_independent_set(G: Graph[_Node], colors: Unused) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def strategy_connected_sequential_bfs(G: Graph[_Node], colors): ... +@_dispatchable +def strategy_connected_sequential_dfs(G: Graph[_Node], colors): ... +@_dispatchable +def strategy_connected_sequential(G: Graph[_Node], colors: Unused, traversal: str = "bfs") -> Generator[Incomplete]: ... +@_dispatchable +def strategy_saturation_largest_first(G: Graph[_Node], colors) -> Generator[Incomplete, None, Incomplete]: ... + +STRATEGIES: Final[dict[str, Callable[..., Incomplete]]] + +@_dispatchable +def greedy_color( + G: Graph[_Node], + strategy: ( + Callable[..., Incomplete] + | Literal[ + "largest_first", + "random_sequential", + "smallest_last", + "independent_set", + "connected_sequential_bfs", + "connected_sequential_dfs", + "connected_sequential", + "saturation_largest_first", + "DSATUR", + ] + ) = "largest_first", + interchange: bool = False, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/communicability_alg.pyi b/stubs/networkx/networkx/algorithms/communicability_alg.pyi new file mode 100644 index 000000000000..b0636d34355f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/communicability_alg.pyi @@ -0,0 +1,9 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["communicability", "communicability_exp"] + +@_dispatchable +def communicability(G: Graph[_Node]) -> dict[_Node, dict[_Node, float]]: ... +@_dispatchable +def communicability_exp(G: Graph[_Node]) -> dict[_Node, dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/__init__.pyi b/stubs/networkx/networkx/algorithms/community/__init__.pyi new file mode 100644 index 000000000000..dc44dd7c344e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/__init__.pyi @@ -0,0 +1,13 @@ +from networkx.algorithms.community.asyn_fluid import * +from networkx.algorithms.community.bipartitions import * +from networkx.algorithms.community.centrality import * +from networkx.algorithms.community.community_utils import * +from networkx.algorithms.community.divisive import * +from networkx.algorithms.community.kclique import * +from networkx.algorithms.community.label_propagation import * +from networkx.algorithms.community.leiden import * +from networkx.algorithms.community.local import * +from networkx.algorithms.community.louvain import * +from networkx.algorithms.community.lukes import * +from networkx.algorithms.community.modularity_max import * +from networkx.algorithms.community.quality import * diff --git a/stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi b/stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi new file mode 100644 index 000000000000..2b3d11cc5a51 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["asyn_fluidc"] + +@_dispatchable +def asyn_fluidc(G: Graph[_Node], k: int, max_iter: int = 100, seed: int | RandomState | None = None) -> Iterator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/bipartitions.pyi b/stubs/networkx/networkx/algorithms/community/bipartitions.pyi new file mode 100644 index 000000000000..991590f7dac1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/bipartitions.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.algorithms.shortest_paths.weighted import _WeightFunc +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["kernighan_lin_bisection", "spectral_modularity_bipartition", "greedy_node_swap_bipartition"] + +@_dispatchable +def kernighan_lin_bisection( + G: Graph[_Node], + partition: tuple[Iterable[Incomplete], Iterable[Incomplete]] | None = None, + max_iter: int = 10, + weight: str | _WeightFunc[_Node] = "weight", + seed: int | RandomState | None = None, +) -> tuple[set[Incomplete], set[Incomplete]]: ... +def spectral_modularity_bipartition(G: Graph[_Node]) -> tuple[set[Incomplete], set[Incomplete]]: ... +def greedy_node_swap_bipartition( + G: Graph[_Node], *, init_split: tuple[set[Incomplete], set[Incomplete]] | None = None, max_iter: int = 10 +) -> tuple[set[Incomplete], set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/centrality.pyi b/stubs/networkx/networkx/algorithms/community/centrality.pyi new file mode 100644 index 000000000000..ec3b07141fe1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/centrality.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["girvan_newman"] + +@_dispatchable +def girvan_newman( + G: Graph[_Node], most_valuable_edge: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete, None, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/community_utils.pyi b/stubs/networkx/networkx/algorithms/community/community_utils.pyi new file mode 100644 index 000000000000..b51294b995dd --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/community_utils.pyi @@ -0,0 +1,9 @@ +from collections.abc import Container, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_partition"] + +@_dispatchable +def is_partition(G: Graph[_Node], communities: Iterable[Container[_Node]]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/community/divisive.pyi b/stubs/networkx/networkx/algorithms/community/divisive.pyi new file mode 100644 index 000000000000..a0c99adae0ef --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/divisive.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_betweenness_partition", "edge_current_flow_betweenness_partition"] + +@_dispatchable +def edge_betweenness_partition(G: Graph[_Node], number_of_sets: int, *, weight: str | None = None) -> list[Incomplete]: ... +@_dispatchable +def edge_current_flow_betweenness_partition( + G: Graph[_Node], number_of_sets: int, *, weight: str | None = None +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/kclique.pyi b/stubs/networkx/networkx/algorithms/community/kclique.pyi new file mode 100644 index 000000000000..f3fecef092a1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/kclique.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_clique_communities"] + +@_dispatchable +def k_clique_communities(G: Graph[_Node], k: int, cliques: Iterable[Incomplete] | None = None) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/label_propagation.pyi b/stubs/networkx/networkx/algorithms/community/label_propagation.pyi new file mode 100644 index 000000000000..8d50d0043835 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/label_propagation.pyi @@ -0,0 +1,18 @@ +from _collections_abc import dict_values +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["label_propagation_communities", "asyn_lpa_communities", "fast_label_propagation_communities"] + +@_dispatchable +def fast_label_propagation_communities(G: Graph[_Node], *, weight=None, seed=None) -> Generator[Incomplete]: ... +@_dispatchable +def asyn_lpa_communities( + G: Graph[_Node], weight: str | None = None, seed: int | RandomState | None = None +) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def label_propagation_communities(G: Graph[_Node]) -> dict_values[Incomplete, set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/leiden.pyi b/stubs/networkx/networkx/algorithms/community/leiden.pyi new file mode 100644 index 000000000000..2cf5052c1229 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/leiden.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["leiden_communities", "leiden_partitions"] + +@_dispatchable +def leiden_communities( + G: Graph[_Node], + weight: str | None = "weight", + resolution: float = 1, + max_level: int | None = None, + seed: int | RandomState | None = None, +) -> list[Incomplete]: ... +@_dispatchable +def leiden_partitions( + G: Graph[_Node], weight: str | None = "weight", resolution: float = 1, seed: int | RandomState | None = None +): ... diff --git a/stubs/networkx/networkx/algorithms/community/local.pyi b/stubs/networkx/networkx/algorithms/community/local.pyi new file mode 100644 index 000000000000..9799724b299b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/local.pyi @@ -0,0 +1,14 @@ +from collections.abc import Callable, Hashable +from typing import Literal, TypeAlias + +from networkx.classes.graph import Graph, _Node + +__all__ = ["greedy_source_expansion"] + +_Algorithm: TypeAlias = Literal["clauset"] + +ALGORITHMS: dict[_Algorithm, Callable[[Graph[Hashable], Hashable, int | None], set[Hashable]]] + +def greedy_source_expansion( + G: Graph[_Node], *, source: _Node, cutoff: int | None = None, method: _Algorithm = "clauset" +) -> set[_Node | None]: ... diff --git a/stubs/networkx/networkx/algorithms/community/louvain.pyi b/stubs/networkx/networkx/algorithms/community/louvain.pyi new file mode 100644 index 000000000000..b4d07e965717 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/louvain.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["louvain_communities", "louvain_partitions"] + +@_dispatchable +def louvain_communities( + G: Graph[_Node], + weight: str | None = "weight", + resolution: float | None = 1, + threshold: float | None = 1e-07, + max_level: int | None = None, + seed: int | RandomState | None = None, +) -> list[set[Incomplete]]: ... +@_dispatchable +def louvain_partitions( + G: Graph[_Node], + weight: str | None = "weight", + resolution: float | None = 1, + threshold: float | None = 1e-07, + seed: int | RandomState | None = None, +) -> Generator[list[set[Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/lukes.pyi b/stubs/networkx/networkx/algorithms/community/lukes.pyi new file mode 100644 index 000000000000..da43a5a29eb8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/lukes.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import Final + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["lukes_partitioning"] + +D_EDGE_W: Final = "weight" +D_EDGE_VALUE: Final[float] +D_NODE_W: Final = "weight" +D_NODE_VALUE: Final = 1 +PKEY: Final = "partitions" +CLUSTER_EVAL_CACHE_SIZE: Final = 2048 + +@_dispatchable +def lukes_partitioning(G: Graph[_Node], max_size: int, node_weight=None, edge_weight=None) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/modularity_max.pyi b/stubs/networkx/networkx/algorithms/community/modularity_max.pyi new file mode 100644 index 000000000000..977fe8b70630 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/modularity_max.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["greedy_modularity_communities", "naive_greedy_modularity_communities"] + +@_dispatchable +def greedy_modularity_communities( + G: Graph[_Node], weight: str | None = None, resolution: float | None = 1, cutoff: int | None = 1, best_n: int | None = None +) -> list[set[Incomplete]] | list[frozenset[Incomplete]]: ... +@_dispatchable +def naive_greedy_modularity_communities( + G: Graph[_Node], resolution: float = 1, weight: str | None = None +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/quality.pyi b/stubs/networkx/networkx/algorithms/community/quality.pyi new file mode 100644 index 000000000000..98aa38954f00 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/quality.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.exception import NetworkXError +from networkx.utils.backends import _dispatchable +from networkx.utils.decorators import argmap + +__all__ = ["modularity", "partition_quality"] + +class NotAPartition(NetworkXError): + def __init__(self, G: Graph[_Node], collection) -> None: ... + +require_partition: argmap + +@_dispatchable +def intra_community_edges(G: Graph[_Node], partition: Iterable[Incomplete]): ... +@_dispatchable +def inter_community_edges(G: Graph[_Node], partition: Iterable[Incomplete]): ... +@_dispatchable +def inter_community_non_edges(G: Graph[_Node], partition: Iterable[Incomplete]): ... +@_dispatchable +def modularity( + G: Graph[_Node], communities: Iterable[set[Incomplete]], weight: str | None = "weight", resolution: float = 1 +) -> float: ... +@_dispatchable +def partition_quality(G: Graph[_Node], partition: Iterable[Incomplete]) -> tuple[float, float]: ... diff --git a/stubs/networkx/networkx/algorithms/components/__init__.pyi b/stubs/networkx/networkx/algorithms/components/__init__.pyi new file mode 100644 index 000000000000..1aee3fd63206 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/__init__.pyi @@ -0,0 +1,6 @@ +from .attracting import * +from .biconnected import * +from .connected import * +from .semiconnected import * +from .strongly_connected import * +from .weakly_connected import * diff --git a/stubs/networkx/networkx/algorithms/components/attracting.pyi b/stubs/networkx/networkx/algorithms/components/attracting.pyi new file mode 100644 index 000000000000..b4599cb049d5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/attracting.pyi @@ -0,0 +1,14 @@ +from collections.abc import Generator + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_attracting_components", "attracting_components", "is_attracting_component"] + +@_dispatchable +def attracting_components(G: DiGraph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def number_attracting_components(G: DiGraph[_Node]) -> int: ... +@_dispatchable +def is_attracting_component(G: DiGraph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/components/biconnected.pyi b/stubs/networkx/networkx/algorithms/components/biconnected.pyi new file mode 100644 index 000000000000..f6b5e78f1401 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/biconnected.pyi @@ -0,0 +1,15 @@ +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["biconnected_components", "biconnected_component_edges", "is_biconnected", "articulation_points"] + +@_dispatchable +def is_biconnected(G: Graph[_Node]) -> bool: ... +@_dispatchable +def biconnected_component_edges(G: Graph[_Node]) -> Generator[list[tuple[_Node, _Node]]]: ... +@_dispatchable +def biconnected_components(G: Graph[_Node]) -> Generator[list[set[_Node]]]: ... +@_dispatchable +def articulation_points(G: Graph[_Node]) -> Generator[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/components/connected.pyi b/stubs/networkx/networkx/algorithms/components/connected.pyi new file mode 100644 index 000000000000..e19f09c06929 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/connected.pyi @@ -0,0 +1,15 @@ +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_connected_components", "connected_components", "is_connected", "node_connected_component"] + +@_dispatchable +def connected_components(G: Graph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def number_connected_components(G: Graph[_Node]) -> int: ... +@_dispatchable +def is_connected(G: Graph[_Node]) -> bool: ... +@_dispatchable +def node_connected_component(G: Graph[_Node], n: _Node) -> set[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/components/semiconnected.pyi b/stubs/networkx/networkx/algorithms/components/semiconnected.pyi new file mode 100644 index 000000000000..f83e432c4075 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/semiconnected.pyi @@ -0,0 +1,8 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_semiconnected"] + +@_dispatchable +def is_semiconnected(G: DiGraph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/components/strongly_connected.pyi b/stubs/networkx/networkx/algorithms/components/strongly_connected.pyi new file mode 100644 index 000000000000..bc0bb03a5970 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/strongly_connected.pyi @@ -0,0 +1,24 @@ +from collections.abc import Generator, Iterable + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "number_strongly_connected_components", + "strongly_connected_components", + "is_strongly_connected", + "kosaraju_strongly_connected_components", + "condensation", +] + +@_dispatchable +def strongly_connected_components(G: DiGraph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def kosaraju_strongly_connected_components(G: DiGraph[_Node], source: _Node | None = None) -> Generator[set[_Node]]: ... +@_dispatchable +def number_strongly_connected_components(G: DiGraph[_Node]) -> int: ... +@_dispatchable +def is_strongly_connected(G: DiGraph[_Node]) -> bool: ... +@_dispatchable +def condensation(G: DiGraph[_Node], scc: Iterable[Iterable[_Node]] | None = None) -> DiGraph[int]: ... diff --git a/stubs/networkx/networkx/algorithms/components/weakly_connected.pyi b/stubs/networkx/networkx/algorithms/components/weakly_connected.pyi new file mode 100644 index 000000000000..ca026575a7e0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/weakly_connected.pyi @@ -0,0 +1,14 @@ +from collections.abc import Generator + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_weakly_connected_components", "weakly_connected_components", "is_weakly_connected"] + +@_dispatchable +def weakly_connected_components(G: DiGraph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def number_weakly_connected_components(G: DiGraph[_Node]) -> int: ... +@_dispatchable +def is_weakly_connected(G: DiGraph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/__init__.pyi b/stubs/networkx/networkx/algorithms/connectivity/__init__.pyi new file mode 100644 index 000000000000..4c3ecc33e72d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/__init__.pyi @@ -0,0 +1,9 @@ +from .connectivity import * +from .cuts import * +from .disjoint_paths import * +from .edge_augmentation import * +from .edge_kcomponents import * +from .kcomponents import * +from .kcutsets import * +from .stoerwagner import * +from .utils import * diff --git a/stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi b/stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi new file mode 100644 index 000000000000..e38e1c82f756 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable, Iterable + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "average_node_connectivity", + "local_node_connectivity", + "node_connectivity", + "local_edge_connectivity", + "edge_connectivity", + "all_pairs_node_connectivity", +] +default_flow_func = edmonds_karp + +@_dispatchable +def local_node_connectivity( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, + cutoff: float | None = None, +) -> float: ... +@_dispatchable +def node_connectivity( + G: Graph[_Node], + s: _Node | None = None, + t: _Node | None = None, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, +) -> float: ... +@_dispatchable +def average_node_connectivity( + G: Graph[_Node], flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None +) -> float: ... +@_dispatchable +def all_pairs_node_connectivity( + G: Graph[_Node], + nbunch: Iterable[tuple[_Node, _Node]] | None = None, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, +) -> dict[_Node, dict[_Node, float]]: ... +@_dispatchable +def local_edge_connectivity( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, + cutoff: float | None = None, +) -> float: ... +@_dispatchable +def edge_connectivity( + G: Graph[_Node], + s: _Node | None = None, + t: _Node | None = None, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, + cutoff: float | None = None, +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/cuts.pyi b/stubs/networkx/networkx/algorithms/connectivity/cuts.pyi new file mode 100644 index 000000000000..4170cc9d37cf --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/cuts.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing_extensions import Never + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["minimum_st_node_cut", "minimum_node_cut", "minimum_st_edge_cut", "minimum_edge_cut"] +default_flow_func = edmonds_karp + +@_dispatchable +def minimum_st_edge_cut( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> set[tuple[Incomplete, Incomplete]]: ... +@_dispatchable +def minimum_st_node_cut( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> dict[Never, Never] | set[Incomplete]: ... +@_dispatchable +def minimum_node_cut( + G: Graph[_Node], s: _Node | None = None, t: _Node | None = None, flow_func: Callable[..., Incomplete] | None = None +) -> dict[Never, Never] | set[Incomplete]: ... +@_dispatchable +def minimum_edge_cut( + G: Graph[_Node], s: _Node | None = None, t: _Node | None = None, flow_func: Callable[..., Incomplete] | None = None +) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi b/stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi new file mode 100644 index 000000000000..1f9ab7fb4ef7 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_disjoint_paths", "node_disjoint_paths"] +default_flow_func = edmonds_karp + +@_dispatchable +def edge_disjoint_paths( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + cutoff: int | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> Generator[Incomplete]: ... +@_dispatchable +def node_disjoint_paths( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + cutoff: int | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi b/stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi new file mode 100644 index 000000000000..b29620946b71 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Collection, Generator, Iterable +from typing import NamedTuple + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_edge_augmentation", "is_k_edge_connected", "is_locally_k_edge_connected"] + +@_dispatchable +def is_k_edge_connected(G: Graph[_Node], k: int) -> bool: ... +@_dispatchable +def is_locally_k_edge_connected(G: Graph[_Node], s: _Node, t: _Node, k: int) -> bool: ... +@_dispatchable +def k_edge_augmentation( + G: Graph[_Node], + k: int, + avail: set[tuple[int, int]] | set[tuple[int, int, float]] | SupportsGetItem[tuple[int, int], float] | None = None, + weight: str | None = None, + partial: bool = False, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def partial_k_edge_augmentation( + G: Graph[_Node], k: int, avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]], weight: str | None = None +): ... +@_dispatchable +def one_edge_augmentation( + G: Graph[_Node], + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]] | None = None, + weight: str | None = None, + partial: bool = False, +): ... +@_dispatchable +def bridge_augmentation( + G: Graph[_Node], + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]] | None = None, + weight: str | None = None, +): ... + +class MetaEdge(NamedTuple): + meta_uv: Incomplete + uv: Incomplete + w: Incomplete + +@_dispatchable +def unconstrained_one_edge_augmentation(G: Graph[_Node]): ... +@_dispatchable +def weighted_one_edge_augmentation( + G: Graph[_Node], + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]], + weight: str | None = None, + partial: bool = False, +): ... +@_dispatchable +def unconstrained_bridge_augmentation(G: Graph[_Node]): ... +@_dispatchable +def weighted_bridge_augmentation( + G: Graph[_Node], avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]], weight: str | None = None +): ... +@_dispatchable +def collapse(G: Graph[_Node], grouped_nodes: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def complement_edges(G: Graph[_Node]): ... +@_dispatchable +def greedy_k_edge_augmentation( + G: Graph[_Node], + k: int, + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]] | None = None, + weight: str | None = None, + seed=None, +): ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi b/stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi new file mode 100644 index 000000000000..f35a458714dd --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_edge_components", "k_edge_subgraphs", "bridge_components", "EdgeComponentAuxGraph"] + +@_dispatchable +def k_edge_components(G: Graph[_Node], k: int) -> Generator[set[Incomplete]]: ... +@_dispatchable +def k_edge_subgraphs(G: Graph[_Node], k: int) -> Generator[Incomplete, Incomplete, Incomplete]: ... +@_dispatchable +def bridge_components(G: Graph[_Node]) -> Generator[Incomplete, Incomplete]: ... + +class EdgeComponentAuxGraph: + A: Incomplete + H: Incomplete + + @classmethod + def construct(cls, G: Graph[_Node]): ... + def k_edge_components(self, k: int) -> Generator[Incomplete, Incomplete]: ... + def k_edge_subgraphs(self, k: int) -> Generator[Incomplete, Incomplete]: ... + +@_dispatchable +def general_k_edge_subgraphs(G: Graph[_Node], k: int): ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi b/stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi new file mode 100644 index 000000000000..6b7c1e1a3b2a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_components"] +default_flow_func = edmonds_karp + +@_dispatchable +def k_components(G: Graph[_Node], flow_func: Callable[..., Incomplete] | None = None) -> dict[Incomplete, Incomplete]: ... +def build_k_number_dict(kcomps) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi b/stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi new file mode 100644 index 000000000000..77b4805cdeda --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["all_node_cuts"] +default_flow_func = edmonds_karp + +@_dispatchable +def all_node_cuts( + G: Graph[_Node], k: int | None = None, flow_func: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi b/stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi new file mode 100644 index 000000000000..e06ceda6d62d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["stoer_wagner"] + +@_dispatchable +def stoer_wagner( + G: Graph[_Node], weight: str = "weight", heap: type = ... +) -> tuple[int | float, tuple[list[Incomplete], list[Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/utils.pyi b/stubs/networkx/networkx/algorithms/connectivity/utils.pyi new file mode 100644 index 000000000000..efc380dd4a29 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/utils.pyi @@ -0,0 +1,9 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["build_auxiliary_node_connectivity", "build_auxiliary_edge_connectivity"] + +@_dispatchable +def build_auxiliary_node_connectivity(G: Graph[_Node]): ... +@_dispatchable +def build_auxiliary_edge_connectivity(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/algorithms/core.pyi b/stubs/networkx/networkx/algorithms/core.pyi new file mode 100644 index 000000000000..f32aade116df --- /dev/null +++ b/stubs/networkx/networkx/algorithms/core.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["core_number", "k_core", "k_shell", "k_crust", "k_corona", "k_truss", "onion_layers"] + +@_dispatchable +def core_number(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def k_core( + G: Graph[_Node], k: int | None = None, core_number: Mapping[Incomplete, Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def k_shell( + G: Graph[_Node], k: int | None = None, core_number: Mapping[Incomplete, Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def k_crust( + G: Graph[_Node], k: int | None = None, core_number: Mapping[Incomplete, Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def k_corona(G: Graph[_Node], k: int | None, core_number: Mapping[Incomplete, Incomplete] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def k_truss(G: Graph[_Node], k: int) -> Graph[Incomplete]: ... +@_dispatchable +def onion_layers(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/covering.pyi b/stubs/networkx/networkx/algorithms/covering.pyi new file mode 100644 index 000000000000..e10e1967bb6f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/covering.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_edge_cover", "is_edge_cover"] + +@_dispatchable +def min_edge_cover(G: Graph[_Node], matching_algorithm: Callable[..., Incomplete] | None = None) -> set[Incomplete]: ... +@_dispatchable +def is_edge_cover(G: Graph[_Node], cover: Iterable[Iterable[Incomplete]]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/cuts.pyi b/stubs/networkx/networkx/algorithms/cuts.pyi new file mode 100644 index 000000000000..4d16d5f516ac --- /dev/null +++ b/stubs/networkx/networkx/algorithms/cuts.pyi @@ -0,0 +1,36 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "boundary_expansion", + "conductance", + "cut_size", + "edge_expansion", + "mixing_expansion", + "node_expansion", + "normalized_cut_size", + "volume", +] + +@_dispatchable +def cut_size(G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None) -> float: ... +@_dispatchable +def volume(G: Graph[_Node], S: Iterable[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def normalized_cut_size( + G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None +) -> float: ... +@_dispatchable +def conductance(G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None) -> float: ... +@_dispatchable +def edge_expansion(G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None) -> float: ... +@_dispatchable +def mixing_expansion( + G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None +) -> float: ... +@_dispatchable +def node_expansion(G: Graph[_Node], S: Iterable[_Node]) -> float: ... +@_dispatchable +def boundary_expansion(G: Graph[_Node], S: Iterable[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/cycles.pyi b/stubs/networkx/networkx/algorithms/cycles.pyi new file mode 100644 index 000000000000..2890429d4516 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/cycles.pyi @@ -0,0 +1,33 @@ +from collections.abc import Generator +from typing import Literal + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _NBunch, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "cycle_basis", + "simple_cycles", + "recursive_simple_cycles", + "find_cycle", + "minimum_cycle_basis", + "chordless_cycles", + "girth", +] + +@_dispatchable +def cycle_basis(G: Graph[_Node], root: _Node | None = None) -> list[list[_Node]]: ... +@_dispatchable +def simple_cycles(G: Graph[_Node], length_bound: int | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def chordless_cycles(G: DiGraph[_Node], length_bound: int | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def recursive_simple_cycles(G: DiGraph[_Node]) -> list[list[_Node]]: ... +@_dispatchable +def find_cycle( + G: Graph[_Node], source: _NBunch[_Node] = None, orientation: Literal["original", "reverse", "ignore"] | None = None +): ... +@_dispatchable +def minimum_cycle_basis(G: Graph[_Node], weight: str | None = None) -> list[list[_Node]]: ... +@_dispatchable +def girth(G: Graph[_Node]) -> float | int: ... # accepts any graph type diff --git a/stubs/networkx/networkx/algorithms/d_separation.pyi b/stubs/networkx/networkx/algorithms/d_separation.pyi new file mode 100644 index 000000000000..7904fb9cd3a9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/d_separation.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_d_separator", "is_minimal_d_separator", "find_minimal_d_separator"] + +@_dispatchable +def is_d_separator(G: DiGraph[_Node], x: _Node | set[_Node], y: _Node | set[_Node], z: _Node | set[_Node]) -> bool: ... +@_dispatchable +def find_minimal_d_separator( + G: DiGraph[_Node], x: set[Incomplete] | Incomplete, y: set[Incomplete] | Incomplete, *, included=None, restricted=None +) -> set[Incomplete] | None: ... +@_dispatchable +def is_minimal_d_separator( + G: DiGraph[_Node], + x: _Node | set[_Node], + y: _Node | set[_Node], + z: _Node | set[_Node], + *, + included: _Node | set[_Node] | None = None, + restricted: _Node | set[_Node] | None = None, +) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/dag.pyi b/stubs/networkx/networkx/algorithms/dag.pyi new file mode 100644 index 000000000000..62b93319e8b1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/dag.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterable + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "descendants", + "ancestors", + "topological_sort", + "lexicographical_topological_sort", + "all_topological_sorts", + "topological_generations", + "is_directed_acyclic_graph", + "is_aperiodic", + "transitive_closure", + "transitive_closure_dag", + "transitive_reduction", + "antichains", + "dag_longest_path", + "dag_longest_path_length", + "dag_to_branching", +] + +@_dispatchable +def descendants(G: Graph[_Node], source) -> set[_Node]: ... +@_dispatchable +def ancestors(G: Graph[_Node], source) -> set[_Node]: ... +@_dispatchable +def is_directed_acyclic_graph(G: Graph[_Node]) -> bool: ... +@_dispatchable +def topological_generations(G: DiGraph[_Node]) -> Generator[list[_Node]]: ... +@_dispatchable +def topological_sort(G: DiGraph[_Node]) -> Generator[_Node]: ... +@_dispatchable +def lexicographical_topological_sort(G: DiGraph[_Node], key: Callable[..., Incomplete] | None = None) -> Generator[_Node]: ... +@_dispatchable +def all_topological_sorts(G: DiGraph[_Node]) -> Generator[list[_Node]]: ... +@_dispatchable +def is_aperiodic(G: DiGraph[_Node]) -> bool: ... +@_dispatchable +def transitive_closure( + G: Graph[_Node, _NodeData, _EdgeData], reflexive: bool | None = False +) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def transitive_closure_dag( + G: DiGraph[_Node, _NodeData, _EdgeData], topo_order: Iterable[Incomplete] | None = None +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def transitive_reduction(G: DiGraph[_Node, _NodeData, _EdgeData]) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def antichains(G: DiGraph[_Node], topo_order: Iterable[Incomplete] | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def dag_longest_path( + G: DiGraph[_Node], + weight: str | None = "weight", + default_weight: int | None = 1, + topo_order: Iterable[Incomplete] | None = None, +) -> list[_Node]: ... +@_dispatchable +def dag_longest_path_length(G: DiGraph[_Node], weight: str | None = "weight", default_weight: int | None = 1) -> int: ... +@_dispatchable +def dag_to_branching(G: DiGraph[_Node, _NodeData, _EdgeData]) -> DiGraph[_Node, _NodeData, _EdgeData]: ... diff --git a/stubs/networkx/networkx/algorithms/distance_measures.pyi b/stubs/networkx/networkx/algorithms/distance_measures.pyi new file mode 100644 index 000000000000..8b109a2b9f5b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/distance_measures.pyi @@ -0,0 +1,63 @@ +from collections.abc import Callable, Mapping +from typing import TypeAlias + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_WeightFunction: TypeAlias = Callable[..., int] + +__all__ = [ + "eccentricity", + "diameter", + "harmonic_diameter", + "radius", + "periphery", + "center", + "barycenter", + "resistance_distance", + "kemeny_constant", + "effective_graph_resistance", +] + +@_dispatchable +def eccentricity( + G: Graph[_Node], + v: _Node | None = None, + sp: Mapping[_Node, Mapping[_Node, int]] | None = None, + weight: str | _WeightFunction | None = None, +) -> int | dict[_Node, int]: ... # TODO: overload on v: dict if v is None else int +@_dispatchable +def diameter( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> int: ... +@_dispatchable +def harmonic_diameter( + G: Graph[_Node], sp: Mapping[_Node, Mapping[_Node, int]] | None = None, *, weight: str | _WeightFunction | None = None +) -> float: ... +@_dispatchable +def periphery( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> list[_Node]: ... +@_dispatchable +def radius( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> int: ... +@_dispatchable +def center( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> list[_Node]: ... +@_dispatchable +def barycenter( + G: Graph[_Node], + weight: str | _WeightFunction | None = None, + attr: str | None = None, + sp: Mapping[_Node, Mapping[_Node, int]] | None = None, +) -> list[_Node]: ... +@_dispatchable +def resistance_distance( + G: Graph[_Node], nodeA: _Node | None = None, nodeB: _Node | None = None, weight: str | None = None, invert_weight: bool = True +) -> float | dict[_Node, float]: ... # TODO: overload on the nodes: float if both are specified else dict +@_dispatchable +def effective_graph_resistance(G: Graph[_Node], weight: str | None = None, invert_weight: bool = True) -> float: ... +@_dispatchable +def kemeny_constant(G: Graph[_Node], *, weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/distance_regular.pyi b/stubs/networkx/networkx/algorithms/distance_regular.pyi new file mode 100644 index 000000000000..0735afbc4ef3 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/distance_regular.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_distance_regular", "is_strongly_regular", "intersection_array", "global_parameters"] + +@_dispatchable +def is_distance_regular(G: Graph[_Node]) -> bool: ... +@_dispatchable +def global_parameters(b: list[Incomplete], c: list[Incomplete]) -> Generator[tuple[Incomplete, Incomplete, Incomplete]]: ... +@_dispatchable +def intersection_array(G: Graph[_Node]) -> tuple[list[Incomplete], list[Incomplete]]: ... +@_dispatchable +def is_strongly_regular(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/dominance.pyi b/stubs/networkx/networkx/algorithms/dominance.pyi new file mode 100644 index 000000000000..acc979d8d9ab --- /dev/null +++ b/stubs/networkx/networkx/algorithms/dominance.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["immediate_dominators", "dominance_frontiers"] + +@_dispatchable +def immediate_dominators(G: Graph[_Node], start: _Node) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def dominance_frontiers(G: Graph[_Node], start: _Node) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/dominating.pyi b/stubs/networkx/networkx/algorithms/dominating.pyi new file mode 100644 index 000000000000..6a3eb9a4fa2e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/dominating.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dominating_set", "is_dominating_set", "connected_dominating_set", "is_connected_dominating_set"] + +@_dispatchable +def dominating_set(G: Graph[_Node], start_with: _Node | None = None) -> set[_Node]: ... +@_dispatchable +def is_dominating_set(G: Graph[_Node], nbunch: Iterable[_Node]) -> bool: ... +@_dispatchable +def connected_dominating_set(G: Graph[_Node]) -> set[_Node]: ... +@_dispatchable +def is_connected_dominating_set(G: Graph[_Node], nbunch: Iterable[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/efficiency_measures.pyi b/stubs/networkx/networkx/algorithms/efficiency_measures.pyi new file mode 100644 index 000000000000..43a2f8d307ca --- /dev/null +++ b/stubs/networkx/networkx/algorithms/efficiency_measures.pyi @@ -0,0 +1,11 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["efficiency", "local_efficiency", "global_efficiency"] + +@_dispatchable +def efficiency(G: Graph[_Node], u: _Node, v: _Node) -> float: ... +@_dispatchable +def global_efficiency(G: Graph[_Node]) -> float: ... +@_dispatchable +def local_efficiency(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/euler.pyi b/stubs/networkx/networkx/algorithms/euler.pyi new file mode 100644 index 000000000000..eaffb70723d6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/euler.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["is_eulerian", "eulerian_circuit", "eulerize", "is_semieulerian", "has_eulerian_path", "eulerian_path"] + +@_dispatchable +def is_eulerian(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_semieulerian(G: Graph[_Node]) -> bool: ... +@_dispatchable +def eulerian_circuit(G: Graph[_Node], source: _Node | None = None, keys: bool = False) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def has_eulerian_path(G: Graph[_Node], source: _Node | None = None) -> bool: ... +@_dispatchable +def eulerian_path(G: Graph[_Node], source=None, keys: bool = False) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def eulerize(G: Graph[_Node]) -> MultiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/__init__.pyi b/stubs/networkx/networkx/algorithms/flow/__init__.pyi new file mode 100644 index 000000000000..a5ac3895e457 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/__init__.pyi @@ -0,0 +1,11 @@ +from .boykovkolmogorov import * +from .capacityscaling import * +from .dinitz_alg import * +from .edmondskarp import * +from .gomory_hu import * +from .maxflow import * +from .mincost import * +from .networksimplex import * +from .preflowpush import * +from .shortestaugmentingpath import * +from .utils import build_flow_dict as build_flow_dict, build_residual_network as build_residual_network diff --git a/stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi b/stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi new file mode 100644 index 000000000000..767af34353d8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["boykov_kolmogorov"] + +@_dispatchable +def boykov_kolmogorov( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi b/stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi new file mode 100644 index 000000000000..08303e681bd2 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["capacity_scaling"] + +@_dispatchable +def capacity_scaling( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight", heap: type = ... +) -> tuple[int, dict[Incomplete, Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi b/stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi new file mode 100644 index 000000000000..9b866da0d367 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dinitz"] + +@_dispatchable +def dinitz( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi b/stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi new file mode 100644 index 000000000000..e43617b2dc61 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edmonds_karp"] + +@_dispatchable +def edmonds_karp( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi b/stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi new file mode 100644 index 000000000000..08c65356dea4 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +from .edmondskarp import edmonds_karp + +__all__ = ["gomory_hu_tree"] +default_flow_func = edmonds_karp + +@_dispatchable +def gomory_hu_tree( + G: Graph[_Node], capacity: str = "capacity", flow_func: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/maxflow.pyi b/stubs/networkx/networkx/algorithms/flow/maxflow.pyi new file mode 100644 index 000000000000..65ec771c6e55 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/maxflow.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +from .preflowpush import preflow_push + +__all__ = ["maximum_flow", "maximum_flow_value", "minimum_cut", "minimum_cut_value"] +default_flow_func = preflow_push + +@_dispatchable +def maximum_flow( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> tuple[int | float, dict[Incomplete, Incomplete]]: ... +@_dispatchable +def maximum_flow_value( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> int | float: ... +@_dispatchable +def minimum_cut( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> tuple[int | float, tuple[set[Incomplete], set[Incomplete]]]: ... +@_dispatchable +def minimum_cut_value( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> int | float: ... diff --git a/stubs/networkx/networkx/algorithms/flow/mincost.pyi b/stubs/networkx/networkx/algorithms/flow/mincost.pyi new file mode 100644 index 000000000000..7ca50162d01a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/mincost.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete, SupportsGetItem + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_cost_flow_cost", "min_cost_flow", "cost_of_flow", "max_flow_min_cost"] + +@_dispatchable +def min_cost_flow_cost( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight" +) -> int | float: ... +@_dispatchable +def min_cost_flow( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight" +) -> dict[Incomplete, dict[Incomplete, Incomplete]]: ... +@_dispatchable +def cost_of_flow(G: Graph[_Node], flowDict: SupportsGetItem[Incomplete, Incomplete], weight: str = "weight") -> int | float: ... +@_dispatchable +def max_flow_min_cost( + G: Graph[_Node], s: str, t: str, capacity: str = "capacity", weight: str = "weight" +) -> dict[Incomplete, dict[Incomplete, Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/networksimplex.pyi b/stubs/networkx/networkx/algorithms/flow/networksimplex.pyi new file mode 100644 index 000000000000..c9a60b87455d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/networksimplex.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["network_simplex"] + +class _DataEssentialsAndFunctions: + node_list: Incomplete + node_indices: Incomplete + node_demands: Incomplete + edge_sources: Incomplete + edge_targets: Incomplete + edge_keys: Incomplete + edge_indices: Incomplete + edge_capacities: Incomplete + edge_weights: Incomplete + edge_count: Incomplete + edge_flow: Incomplete + node_potentials: Incomplete + parent: Incomplete + parent_edge: Incomplete + subtree_size: Incomplete + next_node_dft: Incomplete + prev_node_dft: Incomplete + last_descendent_dft: Incomplete + + def __init__( + self, G: Graph[_Node], multigraph, demand: str = "demand", capacity: str = "capacity", weight: str = "weight" + ) -> None: ... + def initialize_spanning_tree(self, n, faux_inf) -> None: ... + def find_apex(self, p, q): ... + def trace_path(self, p, w): ... + def find_cycle(self, i, p, q): ... + def augment_flow(self, Wn, We, f) -> None: ... + def trace_subtree(self, p) -> Generator[Incomplete]: ... + def remove_edge(self, s, t) -> None: ... + def make_root(self, q) -> None: ... + def add_edge(self, i, p, q) -> None: ... + def update_potentials(self, i, p, q) -> None: ... + def reduced_cost(self, i): ... + def find_entering_edges(self) -> Generator[Incomplete]: ... + def residual_capacity(self, i, p): ... + def find_leaving_edge(self, Wn, We): ... + +@_dispatchable +def network_simplex( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight" +) -> tuple[int | Incomplete, dict[Incomplete, dict[Incomplete, Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/preflowpush.pyi b/stubs/networkx/networkx/algorithms/flow/preflowpush.pyi new file mode 100644 index 000000000000..d31bbb22ac4e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/preflowpush.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["preflow_push"] + +@_dispatchable +def preflow_push( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + global_relabel_freq: float = 1, + value_only: bool = False, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi b/stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi new file mode 100644 index 000000000000..62ec86a862c3 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["shortest_augmenting_path"] + +@_dispatchable +def shortest_augmenting_path( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + two_phase: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/utils.pyi b/stubs/networkx/networkx/algorithms/flow/utils.pyi new file mode 100644 index 000000000000..5bc9995b51c9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/utils.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import overload +from typing_extensions import Never, deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["CurrentEdge", "Level", "GlobalRelabelThreshold", "build_residual_network", "detect_unboundedness", "build_flow_dict"] + +class CurrentEdge: + __slots__ = ("_edges", "_it", "_curr") + def __init__(self, edges) -> None: ... + def get(self): ... + def move_to_next(self) -> None: ... + +class Level: + __slots__ = ("active", "inactive") + active: Incomplete + inactive: Incomplete + + def __init__(self) -> None: ... + +class GlobalRelabelThreshold: + def __init__(self, n, m, freq) -> None: ... + def add_work(self, work) -> None: ... + def is_reached(self) -> bool: ... + def clear_work(self) -> None: ... + +@overload +@deprecated("MultiGraph and MultiDiGraph not supported (yet).") +def build_residual_network(G: MultiGraph[_Node], capacity, *, backend: str | None = None, **backend_kwargs) -> Never: ... +@overload +def build_residual_network(G: Graph[_Node], capacity, *, backend: str | None = None, **backend_kwargs): ... + +@_dispatchable +def detect_unboundedness(R, s, t) -> None: ... +@_dispatchable +def build_flow_dict(G: Graph[_Node], R): ... diff --git a/stubs/networkx/networkx/algorithms/graph_hashing.pyi b/stubs/networkx/networkx/algorithms/graph_hashing.pyi new file mode 100644 index 000000000000..9829cc627f79 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/graph_hashing.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["weisfeiler_lehman_graph_hash", "weisfeiler_lehman_subgraph_hashes"] + +@_dispatchable +def weisfeiler_lehman_graph_hash( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, + iterations: int | None = 3, + digest_size: int | None = 16, +) -> str: ... +@_dispatchable +def weisfeiler_lehman_subgraph_hashes( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, + iterations: int | None = 3, + digest_size: int | None = 16, + include_initial_labels: bool | None = False, +) -> dict[Incomplete, list[str]]: ... diff --git a/stubs/networkx/networkx/algorithms/graphical.pyi b/stubs/networkx/networkx/algorithms/graphical.pyi new file mode 100644 index 000000000000..95054c768cbc --- /dev/null +++ b/stubs/networkx/networkx/algorithms/graphical.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Literal + +from networkx.utils.backends import _dispatchable + +__all__ = [ + "is_graphical", + "is_multigraphical", + "is_pseudographical", + "is_digraphical", + "is_valid_degree_sequence_erdos_gallai", + "is_valid_degree_sequence_havel_hakimi", +] + +@_dispatchable +def is_graphical(sequence: Iterable[Incomplete], method: Literal["eg", "hh"] = "eg") -> bool: ... +@_dispatchable +def is_valid_degree_sequence_havel_hakimi(deg_sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_valid_degree_sequence_erdos_gallai(deg_sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_multigraphical(sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_pseudographical(sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_digraphical(in_sequence: Iterable[Incomplete], out_sequence: Iterable[Incomplete]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/hierarchy.pyi b/stubs/networkx/networkx/algorithms/hierarchy.pyi new file mode 100644 index 000000000000..283d8db11f5d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/hierarchy.pyi @@ -0,0 +1,8 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["flow_hierarchy"] + +@_dispatchable +def flow_hierarchy(G: DiGraph[_Node], weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/hybrid.pyi b/stubs/networkx/networkx/algorithms/hybrid.pyi new file mode 100644 index 000000000000..2e6aff5d823a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/hybrid.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["kl_connected_subgraph", "is_kl_connected"] + +@_dispatchable +def kl_connected_subgraph( + G: Graph[_Node], k: int, l: int, low_memory: bool = False, same_as_graph: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def is_kl_connected(G: Graph[_Node], k: int, l: int, low_memory: bool = False) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/isolate.pyi b/stubs/networkx/networkx/algorithms/isolate.pyi new file mode 100644 index 000000000000..8c0c8bfe0315 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isolate.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_isolate", "isolates", "number_of_isolates"] + +@_dispatchable +def is_isolate(G: Graph[_Node], n: _Node) -> bool: ... +@_dispatchable +def isolates(G: Graph[_Node]) -> Iterator[Incomplete]: ... +@_dispatchable +def number_of_isolates(G: Graph[_Node]) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi b/stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi new file mode 100644 index 000000000000..878c13eed27c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi @@ -0,0 +1,7 @@ +from networkx.algorithms.isomorphism.ismags import * +from networkx.algorithms.isomorphism.isomorph import * +from networkx.algorithms.isomorphism.matchhelpers import * +from networkx.algorithms.isomorphism.temporalisomorphvf2 import * +from networkx.algorithms.isomorphism.tree_isomorphism import * +from networkx.algorithms.isomorphism.vf2pp import * +from networkx.algorithms.isomorphism.vf2userfunc import * diff --git a/stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi b/stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi new file mode 100644 index 000000000000..2f7db7c1ec00 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Hashable, Iterable +from typing import Any + +__all__ = ["ISMAGS"] + +def are_all_equal(iterable: Iterable[Any]) -> bool: ... +def make_partition( + items: Iterable[Hashable], test: Callable[[Hashable, Hashable], bool], check: bool = True +) -> list[set[Incomplete]]: ... +def node_to_part_ID_dict(partition: Iterable[Iterable[Incomplete]]) -> dict[Incomplete, int]: ... +def color_degree_by_node(G, n_colors, e_colors): ... + +class EdgeLookup: + edge_dict: Incomplete + def __init__(self, edge_dict) -> None: ... + def __getitem__(self, edge): ... + def items(self): ... + +class ISMAGS: + graph: Incomplete + subgraph: Incomplete + + def __init__(self, graph, subgraph, node_match=None, edge_match=None, cache=None) -> None: ... + def create_aligned_partitions(self, thing_matcher, sg_things, g_things): ... + def find_isomorphisms(self, symmetry: bool = True) -> Generator[Incomplete, Incomplete, Incomplete]: ... + def largest_common_subgraph(self, symmetry: bool = True) -> Generator[Incomplete, Incomplete]: ... + def analyze_subgraph_symmetry(self) -> dict[Hashable, set[Hashable]]: ... + def is_isomorphic(self, symmetry: bool = False) -> bool: ... + def subgraph_is_isomorphic(self, symmetry: bool = False) -> bool: ... + def isomorphisms_iter(self, symmetry: bool = True) -> Generator[Incomplete, Incomplete]: ... + def subgraph_isomorphisms_iter(self, symmetry: bool = True): ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi b/stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi new file mode 100644 index 000000000000..ebfbdf83d147 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing_extensions import deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["could_be_isomorphic", "fast_could_be_isomorphic", "faster_could_be_isomorphic", "is_isomorphic"] + +@_dispatchable +def could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node], *, properties: str = "dtc") -> bool: ... +@deprecated("`graph_could_be_isomorphic` is a deprecated alias for `could_be_isomorphic`. Use `could_be_isomorphic` instead.") +def graph_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@_dispatchable +def fast_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@deprecated( + "`fast_graph_could_be_isomorphic` is a deprecated alias for `fast_could_be_isomorphic`. " + "Use `fast_could_be_isomorphic` instead." +) +def fast_graph_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@_dispatchable +def faster_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@deprecated( + "`faster_graph_could_be_isomorphic` is a deprecated alias for `faster_could_be_isomorphic`. " + "Use `faster_could_be_isomorphic` instead." +) +def faster_graph_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@_dispatchable +def is_isomorphic( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, +) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi b/stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi new file mode 100644 index 000000000000..734025b38f5e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +__all__ = ["GraphMatcher", "DiGraphMatcher"] + +class GraphMatcher: + G1: Incomplete + G2: Incomplete + G1_nodes: Incomplete + G2_nodes: Incomplete + G2_node_order: Incomplete + old_recursion_limit: Incomplete + test: str + + def __init__(self, G1, G2) -> None: ... + def reset_recursion_limit(self) -> None: ... + def candidate_pairs_iter(self) -> Generator[Incomplete]: ... + core_1: Incomplete + core_2: Incomplete + inout_1: Incomplete + inout_2: Incomplete + state: Incomplete + mapping: Incomplete + + def initialize(self) -> None: ... + def is_isomorphic(self) -> bool: ... + def isomorphisms_iter(self) -> Generator[Incomplete, Incomplete]: ... + def match(self) -> Generator[Incomplete, Incomplete]: ... + def semantic_feasibility(self, G1_node, G2_node): ... + def subgraph_is_isomorphic(self): ... + def subgraph_is_monomorphic(self): ... + def subgraph_isomorphisms_iter(self) -> Generator[Incomplete, Incomplete]: ... + def subgraph_monomorphisms_iter(self) -> Generator[Incomplete, Incomplete]: ... + def syntactic_feasibility(self, G1_node, G2_node): ... + +class DiGraphMatcher(GraphMatcher): + def __init__(self, G1, G2) -> None: ... + def candidate_pairs_iter(self) -> Generator[Incomplete]: ... + core_1: Incomplete + core_2: Incomplete + in_1: Incomplete + in_2: Incomplete + out_1: Incomplete + out_2: Incomplete + state: Incomplete + mapping: Incomplete + + def initialize(self) -> None: ... + def syntactic_feasibility(self, G1_node, G2_node): ... + +class GMState: + GM: Incomplete + G1_node: Incomplete + G2_node: Incomplete + depth: Incomplete + + def __init__(self, GM, G1_node=None, G2_node=None) -> None: ... + def restore(self) -> None: ... + +class DiGMState: + GM: Incomplete + G1_node: Incomplete + G2_node: Incomplete + depth: Incomplete + + def __init__(self, GM, G1_node=None, G2_node=None) -> None: ... + def restore(self) -> None: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi b/stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi new file mode 100644 index 000000000000..382cacbd7ec7 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence +from types import FunctionType + +from networkx.utils.backends import _dispatchable + +__all__ = [ + "categorical_node_match", + "categorical_edge_match", + "categorical_multiedge_match", + "numerical_node_match", + "numerical_edge_match", + "numerical_multiedge_match", + "generic_node_match", + "generic_edge_match", + "generic_multiedge_match", +] + +def copyfunc(f, name=None) -> FunctionType: ... +def allclose(x, y, rtol: float = 1.0000000000000001e-05, atol: float = 1e-08) -> bool: ... +@_dispatchable +def categorical_node_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete] +) -> Callable[..., Incomplete]: ... + +categorical_edge_match: Incomplete + +@_dispatchable +def categorical_multiedge_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete] +) -> Callable[..., Incomplete]: ... +@_dispatchable +def numerical_node_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete], rtol: float = 1e-05, atol: float = 1e-08 +) -> Callable[..., Incomplete]: ... + +numerical_edge_match: Incomplete + +@_dispatchable +def numerical_multiedge_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete], rtol: float = 1e-05, atol: float = 1e-08 +) -> Callable[..., Incomplete]: ... +@_dispatchable +def generic_node_match( + attr: str | Iterable[Incomplete], + default: Incomplete | Iterable[Incomplete], + op: Callable[..., Incomplete] | Sequence[Incomplete], +) -> Callable[..., Incomplete]: ... + +generic_edge_match: Incomplete + +@_dispatchable +def generic_multiedge_match( + attr: str | Iterable[Incomplete], + default: Incomplete | Iterable[Incomplete], + op: Callable[..., Incomplete] | Sequence[Incomplete], +) -> Callable[..., Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi b/stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi new file mode 100644 index 000000000000..7ab32a2abcb9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from .isomorphvf2 import DiGraphMatcher, GraphMatcher + +__all__ = ["TimeRespectingGraphMatcher", "TimeRespectingDiGraphMatcher"] + +class TimeRespectingGraphMatcher(GraphMatcher): + temporal_attribute_name: Incomplete + delta: Incomplete + + def __init__(self, G1, G2, temporal_attribute_name, delta) -> None: ... + def one_hop(self, Gx, Gx_node, neighbors): ... + def two_hop(self, Gx, core_x, Gx_node, neighbors): ... + def semantic_feasibility(self, G1_node, G2_node): ... + +class TimeRespectingDiGraphMatcher(DiGraphMatcher): + temporal_attribute_name: Incomplete + delta: Incomplete + + def __init__(self, G1, G2, temporal_attribute_name, delta) -> None: ... + def get_pred_dates(self, Gx, Gx_node, core_x, pred): ... + def get_succ_dates(self, Gx, Gx_node, core_x, succ): ... + def one_hop(self, Gx, Gx_node, core_x, pred, succ): ... + def two_hop_pred(self, Gx, Gx_node, core_x, pred): ... + def two_hop_succ(self, Gx, Gx_node, core_x, succ): ... + def preds(self, Gx, core_x, v, Gx_node=None): ... + def succs(self, Gx, core_x, v, Gx_node=None): ... + def test_one(self, pred_dates, succ_dates): ... + def test_two(self, pred_dates, succ_dates): ... + def semantic_feasibility(self, G1_node, G2_node): ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi b/stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi new file mode 100644 index 000000000000..1b3d07cd6e14 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["rooted_tree_isomorphism", "tree_isomorphism"] + +@_dispatchable +def root_trees(t1, root1, t2, root2): ... +@_dispatchable +def rooted_tree_isomorphism( + t1: Graph[Incomplete], root1, t2: Graph[Incomplete], root2 +) -> list[tuple[Incomplete, Incomplete]]: ... +@_dispatchable +def tree_isomorphism(t1: Graph[_Node], t2: Graph[_Node]) -> list[tuple[Incomplete, Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi b/stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi new file mode 100644 index 000000000000..f5cbbc1516b2 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import NamedTuple + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["vf2pp_isomorphism", "vf2pp_is_isomorphic", "vf2pp_all_isomorphisms"] + +class _GraphParameters(NamedTuple): + G1: Incomplete + G2: Incomplete + G1_labels: Incomplete + G2_labels: Incomplete + nodes_of_G1Labels: Incomplete + nodes_of_G2Labels: Incomplete + G2_nodes_of_degree: Incomplete + +class _StateParameters(NamedTuple): + mapping: Incomplete + reverse_mapping: Incomplete + T1: Incomplete + T1_in: Incomplete + T1_tilde: Incomplete + T1_tilde_in: Incomplete + T2: Incomplete + T2_in: Incomplete + T2_tilde: Incomplete + T2_tilde_in: Incomplete + +@_dispatchable +def vf2pp_isomorphism( + G1: Graph[_Node], G2: Graph[_Node], node_label: str | None = None, default_label: float | None = None +) -> dict[Incomplete, Incomplete] | None: ... +@_dispatchable +def vf2pp_is_isomorphic( + G1: Graph[_Node], G2: Graph[_Node], node_label: str | None = None, default_label: float | None = None +) -> bool: ... +@_dispatchable +def vf2pp_all_isomorphisms( + G1: Graph[_Node], G2: Graph[_Node], node_label: str | None = None, default_label: float | None = None +) -> Generator[Incomplete, None, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi b/stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi new file mode 100644 index 000000000000..475020aa5b05 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from . import isomorphvf2 as vf2 + +__all__ = ["GraphMatcher", "DiGraphMatcher", "MultiGraphMatcher", "MultiDiGraphMatcher"] + +class GraphMatcher(vf2.GraphMatcher): + node_match: Incomplete + edge_match: Incomplete + G1_adj: Incomplete + G2_adj: Incomplete + + def __init__(self, G1, G2, node_match=None, edge_match=None) -> None: ... + semantic_feasibility: Incomplete + +class DiGraphMatcher(vf2.DiGraphMatcher): + node_match: Incomplete + edge_match: Incomplete + G1_adj: Incomplete + G2_adj: Incomplete + + def __init__(self, G1, G2, node_match=None, edge_match=None) -> None: ... + def semantic_feasibility(self, G1_node, G2_node): ... + +class MultiGraphMatcher(GraphMatcher): ... +class MultiDiGraphMatcher(DiGraphMatcher): ... diff --git a/stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi b/stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi new file mode 100644 index 000000000000..6009f0008147 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi @@ -0,0 +1,2 @@ +from networkx.algorithms.link_analysis.hits_alg import * +from networkx.algorithms.link_analysis.pagerank_alg import * diff --git a/stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi b/stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi new file mode 100644 index 000000000000..f0def237e02f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi @@ -0,0 +1,15 @@ +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["hits"] + +@_dispatchable +def hits( + G: Graph[_Node], + max_iter: int | None = 100, + tol: float | None = 1e-08, + nstart: Mapping[_Node, float] | None = None, + normalized: bool = True, +) -> tuple[dict[_Node, float], dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi b/stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi new file mode 100644 index 000000000000..13fff963097e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi @@ -0,0 +1,29 @@ +from collections.abc import Collection, Mapping + +import numpy as np +from networkx._typing import Array2D +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["pagerank", "google_matrix"] + +@_dispatchable +def pagerank( + G: Graph[_Node], + alpha: float | None = 0.85, + personalization: Mapping[_Node, float] | None = None, + max_iter: int | None = 100, + tol: float | None = 1e-06, + nstart: Mapping[_Node, float] | None = None, + weight: str | None = "weight", + dangling: Mapping[_Node, float] | None = None, +) -> dict[_Node, float]: ... +@_dispatchable +def google_matrix( + G: Graph[_Node], + alpha: float = 0.85, + personalization: Mapping[_Node, float] | None = None, + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + dangling: Mapping[_Node, float] | None = None, +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/algorithms/link_prediction.pyi b/stubs/networkx/networkx/algorithms/link_prediction.pyi new file mode 100644 index 000000000000..1a14f6609bb6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_prediction.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Iterator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "resource_allocation_index", + "jaccard_coefficient", + "adamic_adar_index", + "preferential_attachment", + "cn_soundarajan_hopcroft", + "ra_index_soundarajan_hopcroft", + "within_inter_cluster", + "common_neighbor_centrality", +] + +@_dispatchable +def resource_allocation_index(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def jaccard_coefficient(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def adamic_adar_index(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def common_neighbor_centrality( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, alpha=0.8 +) -> Iterator[Incomplete]: ... +@_dispatchable +def preferential_attachment(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def cn_soundarajan_hopcroft( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, community: str | None = "community" +) -> Iterator[Incomplete]: ... +@_dispatchable +def ra_index_soundarajan_hopcroft( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, community: str | None = "community" +) -> Iterator[Incomplete]: ... +@_dispatchable +def within_inter_cluster( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, delta: float | None = 0.001, community: str | None = "community" +) -> Iterator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi b/stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi new file mode 100644 index 000000000000..ce589b95035d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Iterator + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["all_pairs_lowest_common_ancestor", "tree_all_pairs_lowest_common_ancestor", "lowest_common_ancestor"] + +@_dispatchable +def all_pairs_lowest_common_ancestor(G: DiGraph[_Node], pairs: Iterable[Incomplete] | None = None): ... +@_dispatchable +def lowest_common_ancestor(G: DiGraph[_Node], node1, node2, default=None): ... +@_dispatchable +def tree_all_pairs_lowest_common_ancestor( + G: DiGraph[_Node], root: _Node | None = None, pairs: Iterator[Incomplete] | None = None +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/matching.pyi b/stubs/networkx/networkx/algorithms/matching.pyi new file mode 100644 index 000000000000..e55e966ed3ca --- /dev/null +++ b/stubs/networkx/networkx/algorithms/matching.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "is_matching", + "is_maximal_matching", + "is_perfect_matching", + "max_weight_matching", + "min_weight_matching", + "maximal_matching", +] + +@_dispatchable +def maximal_matching(G: Graph[_Node]) -> set[Incomplete]: ... +def matching_dict_to_set(matching: Mapping[Incomplete, Incomplete]) -> set[Incomplete]: ... +@_dispatchable +def is_matching(G: Graph[_Node], matching: dict[Incomplete, Incomplete] | Iterable[Iterable[Incomplete]]) -> bool: ... +@_dispatchable +def is_maximal_matching(G: Graph[_Node], matching: dict[Incomplete, Incomplete] | Iterable[Iterable[Incomplete]]) -> bool: ... +@_dispatchable +def is_perfect_matching(G: Graph[_Node], matching: dict[Incomplete, Incomplete] | Iterable[Iterable[Incomplete]]) -> bool: ... +@_dispatchable +def min_weight_matching(G: Graph[_Node], weight: str | None = "weight") -> set[Incomplete]: ... +@_dispatchable +def max_weight_matching( + G: Graph[_Node], maxcardinality: bool | None = False, weight: str | None = "weight" +) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/minors/__init__.pyi b/stubs/networkx/networkx/algorithms/minors/__init__.pyi new file mode 100644 index 000000000000..746914c0bcec --- /dev/null +++ b/stubs/networkx/networkx/algorithms/minors/__init__.pyi @@ -0,0 +1,9 @@ +from networkx.algorithms.minors.contraction import ( + contracted_edge as contracted_edge, + contracted_nodes as contracted_nodes, + equivalence_classes as equivalence_classes, + identified_nodes as identified_nodes, + quotient_graph as quotient_graph, +) + +__all__ = ["contracted_edge", "contracted_nodes", "equivalence_classes", "identified_nodes", "quotient_graph"] diff --git a/stubs/networkx/networkx/algorithms/minors/contraction.pyi b/stubs/networkx/networkx/algorithms/minors/contraction.pyi new file mode 100644 index 000000000000..eb6df5761260 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/minors/contraction.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["contracted_edge", "contracted_nodes", "equivalence_classes", "identified_nodes", "quotient_graph"] + +@_dispatchable +def equivalence_classes(iterable: Iterable[_Node], relation: Callable[[_Node, _Node], bool]) -> set[frozenset[_Node]]: ... +@_dispatchable +def quotient_graph( + G: Graph[_Node], + partition: Callable[..., Incomplete] | dict[Incomplete, Incomplete] | list[set[Incomplete]], + edge_relation: Callable[..., Incomplete] | None = None, + node_data: Callable[..., Incomplete] | None = None, + edge_data: Callable[..., Incomplete] | None = None, + weight: str | None = "weight", + relabel: bool = False, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def contracted_nodes( + G: Graph[_Node], u, v, self_loops: bool = True, copy: bool = True, *, store_contraction_as: str | None = "contraction" +) -> Graph[Incomplete]: ... + +identified_nodes = contracted_nodes + +@_dispatchable +def contracted_edge( + G: Graph[_Node], + edge: tuple[Incomplete], + self_loops: bool = True, + copy: bool = True, + *, + store_contraction_as: str | None = "contraction", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/mis.pyi b/stubs/networkx/networkx/algorithms/mis.pyi new file mode 100644 index 000000000000..b0b6a9914384 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/mis.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["maximal_independent_set"] + +@_dispatchable +def maximal_independent_set( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, seed: int | RandomState | None = None +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/moral.pyi b/stubs/networkx/networkx/algorithms/moral.pyi new file mode 100644 index 000000000000..60b07f0e3b4b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/moral.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["moral_graph"] + +@_dispatchable +def moral_graph(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/node_classification.pyi b/stubs/networkx/networkx/algorithms/node_classification.pyi new file mode 100644 index 000000000000..d613a26ded63 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/node_classification.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["harmonic_function", "local_and_global_consistency"] + +@_dispatchable +def harmonic_function(G: Graph[_Node], max_iter: int = 30, label_name: str = "label") -> list[Incomplete]: ... +@_dispatchable +def local_and_global_consistency( + G: Graph[_Node], alpha: float = 0.99, max_iter: int = 30, label_name: str = "label" +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/non_randomness.pyi b/stubs/networkx/networkx/algorithms/non_randomness.pyi new file mode 100644 index 000000000000..45ed928119da --- /dev/null +++ b/stubs/networkx/networkx/algorithms/non_randomness.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["non_randomness"] + +@_dispatchable +def non_randomness(G: Graph[_Node], k: int | None = None, weight: str | None = "weight") -> tuple[float, float]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/__init__.pyi b/stubs/networkx/networkx/algorithms/operators/__init__.pyi new file mode 100644 index 000000000000..0ebc6ab9998d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/__init__.pyi @@ -0,0 +1,4 @@ +from networkx.algorithms.operators.all import * +from networkx.algorithms.operators.binary import * +from networkx.algorithms.operators.product import * +from networkx.algorithms.operators.unary import * diff --git a/stubs/networkx/networkx/algorithms/operators/all.pyi b/stubs/networkx/networkx/algorithms/operators/all.pyi new file mode 100644 index 000000000000..1283c534359c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/all.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["union_all", "compose_all", "disjoint_union_all", "intersection_all"] + +@_dispatchable +def union_all(graphs: Iterable[Incomplete], rename: Iterable[Incomplete] | None = ()) -> Graph[Incomplete]: ... +@_dispatchable +def disjoint_union_all(graphs: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def compose_all(graphs: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def intersection_all(graphs: Iterable[Incomplete]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/binary.pyi b/stubs/networkx/networkx/algorithms/operators/binary.pyi new file mode 100644 index 000000000000..1b02515642a1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/binary.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from collections.abc import Hashable, Iterable +from typing import TypeVar + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["union", "compose", "disjoint_union", "intersection", "difference", "symmetric_difference", "full_join"] + +@_dispatchable +def disjoint_union(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def intersection(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def difference(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def symmetric_difference(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... + +_X_co = TypeVar("_X_co", bound=Hashable, covariant=True) +_Y_co = TypeVar("_Y_co", bound=Hashable, covariant=True) + +@_dispatchable +def compose(G: Graph[_X_co], H: Graph[_Y_co]) -> DiGraph[_X_co | _Y_co]: ... +@_dispatchable +def full_join(G: Graph[_Node], H, rename: tuple[Incomplete, Incomplete] = (None, None)) -> Graph[Incomplete]: ... +@_dispatchable +def union(G: Graph[_X_co], H: Graph[_Y_co], rename: Iterable[Incomplete] | None = ()) -> DiGraph[_X_co | _Y_co]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/product.pyi b/stubs/networkx/networkx/algorithms/operators/product.pyi new file mode 100644 index 000000000000..2fa5b93a77c1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/product.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Hashable +from typing import TypeVar + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_X = TypeVar("_X", bound=Hashable) +_Y = TypeVar("_Y", bound=Hashable) + +__all__ = [ + "tensor_product", + "cartesian_product", + "lexicographic_product", + "strong_product", + "power", + "rooted_product", + "corona_product", + "modular_product", +] + +@_dispatchable +def tensor_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def cartesian_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def lexicographic_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def strong_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def power(G: Graph[_Node], k: int) -> Graph[Incomplete]: ... +@_dispatchable +def rooted_product(G: Graph[_X], H: Graph[_Y], root: _Y) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def corona_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def modular_product(G: Graph[_Node], H) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/unary.pyi b/stubs/networkx/networkx/algorithms/operators/unary.pyi new file mode 100644 index 000000000000..11a8f76ae663 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/unary.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Hashable +from typing import TypeVar + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_G = TypeVar("_G", bound=Graph[Hashable]) + +__all__ = ["complement", "reverse"] + +@_dispatchable +def complement(G: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def reverse(G: _G, copy: bool = True) -> _G: ... diff --git a/stubs/networkx/networkx/algorithms/perfect_graph.pyi b/stubs/networkx/networkx/algorithms/perfect_graph.pyi new file mode 100644 index 000000000000..504389d87e7d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/perfect_graph.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_perfect_graph"] + +@_dispatchable +def is_perfect_graph(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/planar_drawing.pyi b/stubs/networkx/networkx/algorithms/planar_drawing.pyi new file mode 100644 index 000000000000..a40ab8611e12 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/planar_drawing.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Sequence + +from networkx.algorithms.planarity import PlanarEmbedding +from networkx.utils.backends import _dispatchable + +__all__ = ["combinatorial_embedding_to_pos"] + +@_dispatchable +def combinatorial_embedding_to_pos( + embedding: PlanarEmbedding[Incomplete], fully_triangulate: bool = False +) -> dict[Incomplete, Incomplete]: ... +def set_position(parent, tree, remaining_nodes, delta_x, y_coordinate, pos): ... +def get_canonical_ordering(embedding: PlanarEmbedding[Incomplete], outer_face: Sequence[Incomplete]) -> list[Incomplete]: ... +def triangulate_face(embedding: PlanarEmbedding[Incomplete], v1, v2): ... +def triangulate_embedding( + embedding: PlanarEmbedding[Incomplete], fully_triangulate: bool = True +) -> tuple[PlanarEmbedding[Incomplete], list[Incomplete]]: ... +def make_bi_connected( + embedding: PlanarEmbedding[Incomplete], starting_node, outgoing_node, edges_counted: set[tuple[Incomplete, Incomplete]] +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/planarity.pyi b/stubs/networkx/networkx/algorithms/planarity.pyi new file mode 100644 index 000000000000..082bfb94007b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/planarity.pyi @@ -0,0 +1,114 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator, Iterable, Mapping, MutableSet, Reversible +from decimal import Decimal +from typing_extensions import Never + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _EdgePlus, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = ["check_planarity", "is_planar", "PlanarEmbedding"] + +@_dispatchable +def is_planar(G: Graph[_Node]) -> bool: ... +@_dispatchable +def check_planarity(G: Graph[_Node], counterexample: bool = False) -> tuple[bool, Graph[Incomplete]]: ... +@_dispatchable +def get_counterexample(G: Graph[_Node, _NodeData, _EdgeData]) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def get_counterexample_recursive(G: Graph[_Node, _NodeData, _EdgeData]) -> Graph[_Node, _NodeData, _EdgeData]: ... + +class Interval: + low: Incomplete + high: Incomplete + + def __init__(self, low=None, high=None) -> None: ... + def empty(self): ... + def copy(self): ... + def conflicting(self, b, planarity_state): ... + +class ConflictPair: + left: Incomplete + right: Incomplete + + def __init__(self, left=..., right=...) -> None: ... + def swap(self) -> None: ... + def lowest(self, planarity_state): ... + +class LRPlanarity: + __slots__ = [ + "G", + "roots", + "height", + "lowpt", + "lowpt2", + "nesting_depth", + "parent_edge", + "DG", + "adjs", + "ordered_adjs", + "ref", + "side", + "S", + "stack_bottom", + "lowpt_edge", + "left_ref", + "right_ref", + "embedding", + ] + G: Incomplete + roots: Incomplete + height: Incomplete + lowpt: Incomplete + lowpt2: Incomplete + nesting_depth: Incomplete + parent_edge: Incomplete + DG: Incomplete + adjs: Incomplete + ordered_adjs: Incomplete + ref: Incomplete + side: Incomplete + S: Incomplete + stack_bottom: Incomplete + lowpt_edge: Incomplete + left_ref: Incomplete + right_ref: Incomplete + embedding: Incomplete + + def __init__(self, G: Graph[_Node]) -> None: ... + def lr_planarity(self) -> PlanarEmbedding[Incomplete] | None: ... + def lr_planarity_recursive(self): ... + def dfs_orientation(self, v): ... + def dfs_orientation_recursive(self, v) -> None: ... + def dfs_testing(self, v): ... + def dfs_testing_recursive(self, v): ... + def add_constraints(self, ei, e): ... + def remove_back_edges(self, e) -> None: ... + def dfs_embedding(self, v): ... + def dfs_embedding_recursive(self, v) -> None: ... + def sign(self, e): ... + def sign_recursive(self, e): ... + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class PlanarEmbedding(DiGraph[_Node]): + def get_data(self) -> dict[_Node, list[_Node]]: ... + def set_data(self, data: Mapping[_Node, Reversible[_Node]]) -> None: ... + def neighbors_cw_order(self, v: _Node) -> Generator[_Node]: ... + def add_half_edge(self, start_node: _Node, end_node: _Node, *, cw: _Node | None = None, ccw: _Node | None = None): ... + def check_structure(self) -> None: ... + def add_half_edge_ccw(self, start_node: _Node, end_node: _Node, reference_neighbor: _Node) -> None: ... + def add_half_edge_cw(self, start_node: _Node, end_node: _Node, reference_neighbor: _Node) -> None: ... + def connect_components(self, v: _Node, w: _Node) -> None: ... + def add_half_edge_first(self, start_node: _Node, end_node: _Node) -> None: ... + def next_face_half_edge(self, v: _Node, w: _Node) -> tuple[_Node, _Node]: ... + def traverse_face( + self, v: _Node, w: _Node, mark_half_edges: MutableSet[tuple[_Node, _Node]] | None = None + ) -> list[_Node]: ... + # Overriden in __init__ to always raise + def add_edge(self, u_of_edge: _Node, v_of_edge: _Node, **attr: Unused) -> Never: ... + def add_edges_from(self, ebunch_to_add: Iterable[_EdgePlus[_Node]], **attr: Unused) -> Never: ... + def add_weighted_edges_from( + self, ebunch_to_add: Iterable[tuple[_Node, _Node, float | Decimal | None]], weight: str = "weight", **attr: Unused + ) -> Never: ... diff --git a/stubs/networkx/networkx/algorithms/polynomials.pyi b/stubs/networkx/networkx/algorithms/polynomials.pyi new file mode 100644 index 000000000000..9c40146e8d5b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/polynomials.pyi @@ -0,0 +1,9 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["tutte_polynomial", "chromatic_polynomial"] + +@_dispatchable +def tutte_polynomial(G: Graph[_Node]): ... +@_dispatchable +def chromatic_polynomial(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/algorithms/reciprocity.pyi b/stubs/networkx/networkx/algorithms/reciprocity.pyi new file mode 100644 index 000000000000..de7191d31c0e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/reciprocity.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["reciprocity", "overall_reciprocity"] + +@_dispatchable +def reciprocity(G: Graph[_Node], nodes: Iterable[_Node] | None = None) -> float | dict[Incomplete, float | None]: ... +@_dispatchable +def overall_reciprocity(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/algorithms/regular.pyi b/stubs/networkx/networkx/algorithms/regular.pyi new file mode 100644 index 000000000000..063661966c6c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/regular.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_regular", "is_k_regular", "k_factor"] + +@_dispatchable +def is_regular(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_k_regular(G: Graph[_Node], k) -> bool: ... +@_dispatchable +def k_factor(G: Graph[_Node], k: int, matching_weight: str | None = "weight") -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/richclub.pyi b/stubs/networkx/networkx/algorithms/richclub.pyi new file mode 100644 index 000000000000..2f2b25d7b987 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/richclub.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["rich_club_coefficient"] + +@_dispatchable +def rich_club_coefficient( + G: Graph[_Node], normalized: bool = True, Q: float = 100, seed: int | RandomState | None = None +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi new file mode 100644 index 000000000000..b64646da090c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi @@ -0,0 +1,5 @@ +from networkx.algorithms.shortest_paths.astar import * +from networkx.algorithms.shortest_paths.dense import * +from networkx.algorithms.shortest_paths.generic import * +from networkx.algorithms.shortest_paths.unweighted import * +from networkx.algorithms.shortest_paths.weighted import * diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi new file mode 100644 index 000000000000..037db5b93ef9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable + +from networkx.algorithms.shortest_paths.weighted import _WeightFunc +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["astar_path", "astar_path_length"] + +@_dispatchable +def astar_path( + G: Graph[_Node], + source: _Node, + target: _Node, + heuristic: Callable[[_Node, _Node], float] | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", + *, + cutoff: float | None = None, +) -> list[_Node]: ... +@_dispatchable +def astar_path_length( + G: Graph[_Node], + source: _Node, + target: _Node, + heuristic: Callable[[_Node, _Node], float] | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", + *, + cutoff: float | None = None, +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi new file mode 100644 index 000000000000..1290fe33c14c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections import defaultdict +from collections.abc import Collection + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["floyd_warshall", "floyd_warshall_predecessor_and_distance", "reconstruct_path", "floyd_warshall_numpy"] + +@_dispatchable +def floyd_warshall_numpy( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = "weight" +) -> np.ndarray[Incomplete, Incomplete]: ... +@_dispatchable +def floyd_warshall_predecessor_and_distance( + G: Graph[_Node], weight: str | None = "weight" +) -> tuple[dict[Incomplete, dict[Incomplete, Incomplete]], dict[Incomplete, dict[Incomplete, float]]]: ... +@_dispatchable +def reconstruct_path(source: _Node, target: _Node, predecessors: SupportsGetItem[Incomplete, Incomplete]) -> list[Incomplete]: ... +@_dispatchable +def floyd_warshall(G: Graph[_Node], weight: str | None = "weight") -> dict[Incomplete, defaultdict[Incomplete, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi new file mode 100644 index 000000000000..abaf6a0f50f4 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi @@ -0,0 +1,148 @@ +from collections.abc import Generator +from typing import overload + +from networkx.algorithms.shortest_paths.weighted import _WeightFunc +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "shortest_path", + "all_shortest_paths", + "single_source_all_shortest_paths", + "all_pairs_all_shortest_paths", + "shortest_path_length", + "average_shortest_path_length", + "has_path", +] + +@_dispatchable +def has_path(G: Graph[_Node], source: _Node, target: _Node) -> bool: ... + +@overload # both source and target are specified => (s -> t) +def shortest_path( + G: Graph[_Node], + source: _Node, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> list[_Node]: ... +@overload # only source is specified => {t1: (s -> t), t2: (s -> t), ...} +def shortest_path( + G: Graph[_Node], + source: _Node, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, list[_Node]]: ... +@overload # only target is specified (positional) => {s1: (s1 -> t), s2: (s2 -> t), ...} +def shortest_path( + G: Graph[_Node], + source: None, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, list[_Node]]: ... +@overload # only target is specified (keyword) => {s1: (s1 -> t), s2: (s2 -> t), ...} +def shortest_path( + G: Graph[_Node], + source: None = None, + *, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, list[_Node]]: ... +@overload +def shortest_path( # source and target are not specified => generator of (t, {s1: (s1 -> t), s2: (s2 -> t), ...}) + G: Graph[_Node], + source: None = None, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> Generator[tuple[_Node, dict[str, list[_Node]]]]: ... + +@overload # both source and target are specified => len(s -> t) +def shortest_path_length( + G: Graph[_Node], + source: _Node, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> float: ... +@overload # only source is specified => {t1: len(s -> t1), t2: len(s -> t2), ...} +def shortest_path_length( + G: Graph[_Node], + source: _Node, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, float]: ... +@overload # only target is specified (positional) => {s1: len(s1 -> t), s2: len(s2 -> t), ...} +def shortest_path_length( + G: Graph[_Node], + source: None, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, float]: ... +@overload # only target is specified (keyword) => {s1: len(s1 -> t), s2: len(s2 -> t), ...} +def shortest_path_length( + G: Graph[_Node], + source: None = None, + *, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, float]: ... +@overload +def shortest_path_length( # source and target are not specified => generator of (t, {s1: len(s1 -> t), s2: len(s2 -> t), ...}) + G: Graph[_Node], + source: None = None, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> Generator[tuple[_Node, dict[_Node, float]]]: ... + +@_dispatchable +def average_shortest_path_length( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = None, method: str | None = None +) -> float: ... +@_dispatchable +def all_shortest_paths( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = None, method: str | None = "dijkstra" +) -> Generator[list[_Node]]: ... +@_dispatchable +def single_source_all_shortest_paths( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = None, method: str | None = "dijkstra" +) -> Generator[tuple[_Node, list[list[_Node]]]]: ... +@_dispatchable +def all_pairs_all_shortest_paths( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = None, method: str | None = "dijkstra" +) -> Generator[tuple[_Node, dict[_Node, list[list[_Node]]]]]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi new file mode 100644 index 000000000000..636eb613875d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "bidirectional_shortest_path", + "single_source_shortest_path", + "single_source_shortest_path_length", + "single_target_shortest_path", + "single_target_shortest_path_length", + "all_pairs_shortest_path", + "all_pairs_shortest_path_length", + "predecessor", +] + +@_dispatchable +def single_source_shortest_path_length(G: Graph[_Node], source: _Node, cutoff: int | None = None) -> dict[Incomplete, int]: ... +@_dispatchable +def single_target_shortest_path_length( + G: Graph[_Node], target: _Node, cutoff: int | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def all_pairs_shortest_path_length(G: Graph[_Node], cutoff: int | None = None) -> Generator[Incomplete]: ... +@_dispatchable +def bidirectional_shortest_path(G: Graph[_Node], source: _Node, target: _Node) -> list[Incomplete]: ... +@_dispatchable +def single_source_shortest_path( + G: Graph[_Node], source: _Node, cutoff: int | None = None +) -> dict[Incomplete, list[Incomplete]]: ... +@_dispatchable +def single_target_shortest_path( + G: Graph[_Node], target: _Node, cutoff: int | None = None +) -> dict[Incomplete, list[Incomplete]]: ... +@_dispatchable +def all_pairs_shortest_path( + G: Graph[_Node], cutoff: int | None = None +) -> Generator[tuple[Incomplete, dict[Incomplete, list[Incomplete]]]]: ... +@_dispatchable +def predecessor( + G: Graph[_Node], source: _Node, target: _Node | None = None, cutoff: int | None = None, return_seen: bool | None = None +) -> dict[_Node, list[_Node]] | list[_Node] | tuple[dict[_Node, list[_Node]], dict[_Node, int]] | tuple[list[_Node], int]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi new file mode 100644 index 000000000000..bee3ecf7470c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi @@ -0,0 +1,145 @@ +from collections.abc import Callable, Collection, Generator +from typing import Any, TypeAlias + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "dijkstra_path", + "dijkstra_path_length", + "bidirectional_dijkstra", + "single_source_dijkstra", + "single_source_dijkstra_path", + "single_source_dijkstra_path_length", + "multi_source_dijkstra", + "multi_source_dijkstra_path", + "multi_source_dijkstra_path_length", + "all_pairs_dijkstra", + "all_pairs_dijkstra_path", + "all_pairs_dijkstra_path_length", + "dijkstra_predecessor_and_distance", + "bellman_ford_path", + "bellman_ford_path_length", + "single_source_bellman_ford", + "single_source_bellman_ford_path", + "single_source_bellman_ford_path_length", + "all_pairs_bellman_ford_path", + "all_pairs_bellman_ford_path_length", + "bellman_ford_predecessor_and_distance", + "negative_edge_cycle", + "find_negative_cycle", + "goldberg_radzik", + "johnson", +] + +_WeightFunc: TypeAlias = Callable[ + [_Node, _Node, dict[str, Any]], # Any: type of edge data cannot be known statically + float | None, # the weight or None to indicate a hidden edge +] + +@_dispatchable +def dijkstra_path( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> list[_Node]: ... +@_dispatchable +def dijkstra_path_length( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> float: ... +@_dispatchable +def single_source_dijkstra_path( + G: Graph[_Node], source: _Node, cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def single_source_dijkstra_path_length( + G: Graph[_Node], source: _Node, cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, float]: ... +@_dispatchable +def single_source_dijkstra( + G: Graph[_Node], + source: _Node, + target: _Node | None = None, + cutoff: float | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", +) -> tuple[dict[_Node, float], dict[_Node, list[_Node]]] | tuple[float, list[_Node]]: ... # TODO: overload on target +@_dispatchable +def multi_source_dijkstra_path( + G: Graph[_Node], sources: Collection[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def multi_source_dijkstra_path_length( + G: Graph[_Node], sources: Collection[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, float]: ... +@_dispatchable +def multi_source_dijkstra( + G: Graph[_Node], + sources: Collection[_Node], + target: _Node | None = None, + cutoff: float | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", +) -> tuple[dict[_Node, float], dict[_Node, list[_Node]]] | tuple[float, list[_Node]]: ... # TODO: overload on target +@_dispatchable +def dijkstra_predecessor_and_distance( + G: Graph[_Node], source: _Node, cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[dict[_Node, list[_Node]], dict[_Node, float]]: ... +@_dispatchable +def all_pairs_dijkstra( + G: Graph[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, tuple[dict[_Node, float], dict[_Node, list[_Node]]]]]: ... +@_dispatchable +def all_pairs_dijkstra_path_length( + G: Graph[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, float]]]: ... +@_dispatchable +def all_pairs_dijkstra_path( + G: Graph[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, list[_Node]]]]: ... +@_dispatchable +def bellman_ford_predecessor_and_distance( + G: Graph[_Node], + source: _Node, + target: _Node | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", + heuristic: bool = False, +) -> tuple[dict[_Node, list[_Node]], dict[_Node, float]]: ... +@_dispatchable +def bellman_ford_path( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> list[_Node]: ... +@_dispatchable +def bellman_ford_path_length( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> float: ... +@_dispatchable +def single_source_bellman_ford_path( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def single_source_bellman_ford_path_length( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, float]: ... +@_dispatchable +def single_source_bellman_ford( + G: Graph[_Node], source: _Node, target: _Node | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[dict[_Node, float], dict[_Node, list[_Node]]] | tuple[float, list[_Node]]: ... # TODO: overload on target +@_dispatchable +def all_pairs_bellman_ford_path_length( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, float]]]: ... +@_dispatchable +def all_pairs_bellman_ford_path( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, list[_Node]]]]: ... +@_dispatchable +def goldberg_radzik( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[dict[_Node, _Node | None], dict[_Node, float]]: ... +@_dispatchable +def negative_edge_cycle(G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight", heuristic: bool = True) -> bool: ... +@_dispatchable +def find_negative_cycle(G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight") -> list[_Node]: ... +@_dispatchable +def bidirectional_dijkstra( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[float, list[_Node]]: ... +@_dispatchable +def johnson(G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight") -> dict[_Node, dict[_Node, list[_Node]]]: ... diff --git a/stubs/networkx/networkx/algorithms/similarity.pyi b/stubs/networkx/networkx/algorithms/similarity.pyi new file mode 100644 index 000000000000..b0ba3bbe8797 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/similarity.pyi @@ -0,0 +1,125 @@ +from _typeshed import Incomplete, SupportsItemAccess +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "graph_edit_distance", + "optimal_edit_paths", + "optimize_graph_edit_distance", + "optimize_edit_paths", + "simrank_similarity", + "panther_similarity", + "panther_vector_similarity", + "generate_random_paths", +] + +@_dispatchable +def graph_edit_distance( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + roots: tuple[Incomplete, Incomplete] | None = None, + upper_bound: float | None = None, + timeout: float | None = None, +): ... +@_dispatchable +def optimal_edit_paths( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + upper_bound: float | None = None, +) -> tuple[list[tuple[Incomplete, Incomplete]], float]: ... +@_dispatchable +def optimize_graph_edit_distance( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + upper_bound: float | None = None, +) -> Generator[Incomplete]: ... +@_dispatchable +def optimize_edit_paths( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + upper_bound: float | None = None, + strictly_decreasing: bool = True, + roots: tuple[Incomplete, Incomplete] | None = None, + timeout: float | None = None, +) -> Generator[Incomplete, None, Incomplete]: ... +@_dispatchable +def simrank_similarity( + G: Graph[_Node], + source: _Node | None = None, + target: _Node | None = None, + importance_factor: float = 0.9, + max_iterations: int = 1000, + tolerance: float = 0.0001, +) -> float | dict[Incomplete, Incomplete]: ... +@_dispatchable +def panther_similarity( + G: Graph[_Node], + source: _Node, + k: int = 5, + path_length: int = 5, + c: float = 0.5, + delta: float = 0.1, + eps: float | None = None, + weight: str | None = "weight", + seed: int | RandomState | None = None, +) -> dict[bytes, bytes]: ... +@_dispatchable +def panther_vector_similarity( + G: Graph[_Node], + source: _Node, + *, + D: int = 10, + k: int = 5, + path_length: int = 5, + c: float = 0.5, + delta: float = 0.1, + eps: float | None = None, + weight: str | None = "weight", + seed: int | RandomState | None = None, +) -> dict[Incomplete, float]: ... +@_dispatchable +def generate_random_paths( + G: Graph[_Node], + sample_size: int, + path_length: int = 5, + index_map: SupportsItemAccess[Incomplete, Incomplete] | None = None, + weight: str | None = "weight", + seed: int | RandomState | None = None, + *, + source: _Node | None = None, +) -> Generator[list[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/simple_paths.pyi b/stubs/networkx/networkx/algorithms/simple_paths.pyi new file mode 100644 index 000000000000..f32d7d205d2b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/simple_paths.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable, Collection, Generator, Iterable +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["all_simple_paths", "is_simple_path", "shortest_simple_paths", "all_simple_edge_paths"] + +@_dispatchable +def is_simple_path(G: Graph[_Node], nodes: Collection[Incomplete]) -> bool: ... +@_dispatchable +def all_simple_paths( + G: Graph[_Node], source: _Node, target: _Node | Iterable[_Node], cutoff: int | None = None +) -> Generator[list[_Node]]: ... +@_dispatchable +def all_simple_edge_paths( + G: Graph[_Node], source: _Node, target: _Node | Iterable[_Node], cutoff: int | None = None +) -> Generator[list[_Node] | list[tuple[_Node, _Node]], None, list[_Node] | None]: ... +@_dispatchable +def shortest_simple_paths( + G: Graph[_Node], + source: _Node, + target: _Node, + weight: str | Callable[[Any, Any, SupportsGetItem[str, Any]], float | None] | None = None, +) -> Generator[list[_Node]]: ... + +class PathBuffer: + paths: Incomplete + sortedpaths: Incomplete + counter: Incomplete + + def __init__(self) -> None: ... + def __len__(self): ... + def push(self, cost, path) -> None: ... + def pop(self): ... diff --git a/stubs/networkx/networkx/algorithms/smallworld.pyi b/stubs/networkx/networkx/algorithms/smallworld.pyi new file mode 100644 index 000000000000..0b6ae2986819 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/smallworld.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["random_reference", "lattice_reference", "sigma", "omega"] + +@_dispatchable +def random_reference( + G: Graph[_Node], niter: int = 1, connectivity: bool = True, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def lattice_reference( + G: Graph[_Node], + niter: int = 5, + D: np.ndarray[Incomplete, Incomplete] | None = None, + connectivity: bool = True, + seed: int | RandomState | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def sigma(G: Graph[_Node], niter: int = 100, nrand: int = 10, seed: int | RandomState | None = None) -> float: ... +@_dispatchable +def omega(G: Graph[_Node], niter: int = 5, nrand: int = 10, seed: int | RandomState | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/smetric.pyi b/stubs/networkx/networkx/algorithms/smetric.pyi new file mode 100644 index 000000000000..60f6d0ab5d25 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/smetric.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["s_metric"] + +@_dispatchable +def s_metric(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/sparsifiers.pyi b/stubs/networkx/networkx/algorithms/sparsifiers.pyi new file mode 100644 index 000000000000..e94ffe57f37a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/sparsifiers.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["spanner"] + +@_dispatchable +def spanner( + G: Graph[_Node], stretch: float, weight: str | None = None, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/structuralholes.pyi b/stubs/networkx/networkx/algorithms/structuralholes.pyi new file mode 100644 index 000000000000..e869afe75614 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/structuralholes.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["constraint", "local_constraint", "effective_size"] + +@_dispatchable +def mutual_weight(G: Graph[_Node], u, v, weight=None) -> Incomplete | int: ... +@_dispatchable +def normalized_mutual_weight(G: Graph[_Node], u, v, norm=..., weight=None) -> float: ... +@_dispatchable +def effective_size( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, weight: str | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def constraint( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, weight: str | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def local_constraint(G: Graph[_Node], u: _Node, v: _Node, weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/summarization.pyi b/stubs/networkx/networkx/algorithms/summarization.pyi new file mode 100644 index 000000000000..c2ec3253c28f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/summarization.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dedensify", "snap_aggregation"] + +@_dispatchable +def dedensify( + G: Graph[_Node], threshold: int, prefix: str | None = None, copy: bool | None = True +) -> tuple[Graph[Incomplete], set[Incomplete]]: ... +@_dispatchable +def snap_aggregation( + G: Graph[_Node], + node_attributes: Iterable[Incomplete], + edge_attributes: Iterable[Incomplete] | None = (), + prefix: str = "Supernode-", + supernode_attribute: str = "group", + superedge_attribute: str = "types", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/swap.pyi b/stubs/networkx/networkx/algorithms/swap.pyi new file mode 100644 index 000000000000..607e9ae99ee6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/swap.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["double_edge_swap", "connected_double_edge_swap", "directed_edge_swap"] + +@_dispatchable +def directed_edge_swap( + G: DiGraph[_Node], *, nswap: int = 1, max_tries: int = 100, seed: int | RandomState | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def double_edge_swap( + G: Graph[_Node], nswap: int = 1, max_tries: int = 100, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def connected_double_edge_swap( + G: Graph[_Node], nswap: int = 1, _window_threshold: int = 3, seed: int | RandomState | None = None +) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/threshold.pyi b/stubs/networkx/networkx/algorithms/threshold.pyi new file mode 100644 index 000000000000..c66a43788026 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/threshold.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from collections.abc import Sequence + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["is_threshold_graph", "find_threshold_graph"] + +@_dispatchable +def is_threshold_graph(G: Graph[_Node]) -> bool: ... +def is_threshold_sequence(degree_sequence: Sequence[list[int]]) -> bool: ... +def creation_sequence(degree_sequence, with_labels=False, compact=False): ... +def make_compact(creation_sequence): ... +def uncompact(creation_sequence): ... +def creation_sequence_to_weights(creation_sequence): ... +def weights_to_creation_sequence(weights, threshold=1, with_labels=False, compact=False): ... +@_dispatchable +def threshold_graph(creation_sequence, create_using=None): ... +@_dispatchable +def find_alternating_4_cycle(G: Graph[_Node]): ... +@_dispatchable +def find_threshold_graph(G: Graph[_Node], create_using: Graph[_Node] | type[Graph[_Node]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def find_creation_sequence(G: Graph[_Node]): ... +def triangles(creation_sequence): ... +def triangle_sequence(creation_sequence): ... +def cluster_sequence(creation_sequence): ... +def degree_sequence(creation_sequence): ... +def density(creation_sequence): ... +def degree_correlation(creation_sequence): ... +def shortest_path(creation_sequence, u, v): ... +def shortest_path_length(creation_sequence, i): ... +def betweenness_sequence(creation_sequence, normalized=True): ... +def eigenvectors(creation_sequence): ... +def spectral_projection(u, eigenpairs): ... +def eigenvalues(creation_sequence): ... +def random_threshold_sequence(n, p, seed: int | RandomState | None = None): ... +def right_d_threshold_sequence(n: int, m: int) -> list[str]: ... +def left_d_threshold_sequence(n: int, m: int) -> list[str]: ... diff --git a/stubs/networkx/networkx/algorithms/time_dependent.pyi b/stubs/networkx/networkx/algorithms/time_dependent.pyi new file mode 100644 index 000000000000..abdd217acd5c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/time_dependent.pyi @@ -0,0 +1,11 @@ +from datetime import timedelta + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["cd_index"] + +@_dispatchable +def cd_index( + G: Graph[_Node], node: _Node, time_delta: float | timedelta, *, time: str = "time", weight: str | None = None +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/tournament.pyi b/stubs/networkx/networkx/algorithms/tournament.pyi new file mode 100644 index 000000000000..0fff43290acb --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tournament.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "hamiltonian_path", + "is_reachable", + "is_strongly_connected", + "is_tournament", + "random_tournament", + "score_sequence", + "tournament_matrix", +] + +@_dispatchable +def is_tournament(G: Graph[_Node]) -> bool: ... +@_dispatchable +def hamiltonian_path(G: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def random_tournament(n: int, seed: int | RandomState | None = None) -> DiGraph[Incomplete]: ... +@_dispatchable +def tournament_matrix(G: Graph[_Node]): ... +@_dispatchable +def score_sequence(G: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def is_reachable(G: Graph[_Node], s: _Node, t: _Node) -> bool: ... +@_dispatchable +def is_strongly_connected(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/__init__.pyi b/stubs/networkx/networkx/algorithms/traversal/__init__.pyi new file mode 100644 index 000000000000..c97ceceb614a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/__init__.pyi @@ -0,0 +1,5 @@ +from .beamsearch import * +from .breadth_first_search import * +from .depth_first_search import * +from .edgebfs import * +from .edgedfs import * diff --git a/stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi b/stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi new file mode 100644 index 000000000000..9c5c1784d269 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["bfs_beam_edges"] + +@_dispatchable +def bfs_beam_edges( + G: Graph[_Node], source: _Node, value: Callable[[_Node], float], width: int | None = None +) -> Generator[tuple[_Node, _Node]]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi b/stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi new file mode 100644 index 000000000000..60d27065db69 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi @@ -0,0 +1,66 @@ +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import Final, Literal + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "bfs_edges", + "bfs_tree", + "bfs_predecessors", + "bfs_successors", + "descendants_at_distance", + "bfs_layers", + "bfs_labeled_edges", + "generic_bfs_edges", +] + +@_dispatchable +def generic_bfs_edges( + G: Graph[_Node], source: _Node, neighbors: Callable[[_Node], Iterable[_Node]] | None = None, depth_limit: int | None = None +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def bfs_edges( + G: Graph[_Node], + source: _Node, + reverse: bool | None = False, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def bfs_tree( + G: Graph[_Node, _NodeData, _EdgeData], + source: _Node, + reverse: bool | None = False, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def bfs_predecessors( + G: Graph[_Node], + source: _Node, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def bfs_successors( + G: Graph[_Node], + source: _Node, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, list[_Node]]]: ... +@_dispatchable +def bfs_layers(G: Graph[_Node], sources: _Node | Iterable[_Node]) -> Generator[list[_Node]]: ... + +REVERSE_EDGE: Final = "reverse" +TREE_EDGE: Final = "tree" +FORWARD_EDGE: Final = "forward" +LEVEL_EDGE: Final = "level" + +@_dispatchable +def bfs_labeled_edges( + G: Graph[_Node], sources: _Node | Iterable[_Node] +) -> Generator[tuple[_Node, _Node, Literal["tree", "level", "forward", "reverse"]]]: ... +@_dispatchable +def descendants_at_distance(G: Graph[_Node], source: _Node, distance: int) -> set[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi b/stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi new file mode 100644 index 000000000000..083e25e1561d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi @@ -0,0 +1,73 @@ +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import Literal + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "dfs_edges", + "dfs_tree", + "dfs_predecessors", + "dfs_successors", + "dfs_preorder_nodes", + "dfs_postorder_nodes", + "dfs_labeled_edges", +] + +@_dispatchable +def dfs_edges( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def dfs_tree( + G: Graph[_Node, _NodeData, _EdgeData], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def dfs_predecessors( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> dict[_Node, _Node]: ... +@_dispatchable +def dfs_successors( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def dfs_postorder_nodes( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[_Node]: ... +@_dispatchable +def dfs_preorder_nodes( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[_Node]: ... +@_dispatchable +def dfs_labeled_edges( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node, Literal["forward", "nontree", "reverse", "reverse-depth_limit"]]]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi b/stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi new file mode 100644 index 000000000000..f4f3b895c8d3 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_bfs"] + +FORWARD: Final = "forward" +REVERSE: Final = "reverse" + +@_dispatchable +def edge_bfs( + G: Graph[_Node], + source: _Node | Iterable[_Node] | None = None, + orientation: Literal["original", "reverse", "ignore"] | None = None, +) -> Generator[tuple[Incomplete, ...]]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi b/stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi new file mode 100644 index 000000000000..6c5e0bf9a75d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_dfs"] + +FORWARD: Final = "forward" +REVERSE: Final = "reverse" + +@_dispatchable +def edge_dfs( + G: Graph[_Node], + source: _Node | Iterable[_Node] | None = None, + orientation: Literal["original", "reverse", "ignore"] | None = None, +) -> Generator[tuple[Incomplete, ...]]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/__init__.pyi b/stubs/networkx/networkx/algorithms/tree/__init__.pyi new file mode 100644 index 000000000000..1a901de7bdef --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/__init__.pyi @@ -0,0 +1,7 @@ +from .branchings import * +from .coding import * +from .decomposition import * +from .distance_measures import * +from .mst import * +from .operations import * +from .recognition import * diff --git a/stubs/networkx/networkx/algorithms/tree/branchings.pyi b/stubs/networkx/networkx/algorithms/tree/branchings.pyi new file mode 100644 index 000000000000..c9444c109a8d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/branchings.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from dataclasses import dataclass +from typing import Final +from typing_extensions import Self + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "branching_weight", + "greedy_branching", + "maximum_branching", + "minimum_branching", + "minimal_branching", + "maximum_spanning_arborescence", + "minimum_spanning_arborescence", + "ArborescenceIterator", +] + +KINDS: Final[set[str]] +STYLES: Final[dict[str, str]] +INF: Final[float] + +def random_string(L=15, seed=None): ... +@_dispatchable +def branching_weight(G: DiGraph[_Node], attr: str = "weight", default: float = 1) -> int | float: ... +@_dispatchable +def greedy_branching( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, kind: str = "max", seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def maximum_branching( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def minimum_branching( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def minimal_branching( + G: DiGraph[_Node], /, *, attr="weight", default=1, preserve_attrs=False, partition=None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def maximum_spanning_arborescence( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def minimum_spanning_arborescence( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... + +class ArborescenceIterator: + @dataclass(order=True) + class Partition: + mst_weight: float + partition_dict: dict[Incomplete, Incomplete] + def __copy__(self) -> ArborescenceIterator.Partition: ... + + G: Incomplete + weight: Incomplete + minimum: Incomplete + method: Incomplete + partition_key: str + init_partition: Incomplete + + def __init__(self, G: DiGraph[_Node], weight: str = "weight", minimum: bool = True, init_partition=None) -> None: ... + partition_queue: Incomplete + + def __iter__(self) -> Self: ... + def __next__(self): ... diff --git a/stubs/networkx/networkx/algorithms/tree/coding.pyi b/stubs/networkx/networkx/algorithms/tree/coding.pyi new file mode 100644 index 000000000000..7e6013a8526e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/coding.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.exception import NetworkXException +from networkx.utils.backends import _dispatchable + +__all__ = ["from_nested_tuple", "from_prufer_sequence", "NotATree", "to_nested_tuple", "to_prufer_sequence"] + +class NotATree(NetworkXException): ... + +@_dispatchable +def to_nested_tuple(T: Graph[_Node], root: _Node, canonical_form: bool = False) -> tuple[Incomplete, ...]: ... +@_dispatchable +def from_nested_tuple(sequence: tuple[Incomplete, ...], sensible_relabeling: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def to_prufer_sequence(T: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def from_prufer_sequence(sequence: Iterable[Incomplete]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/decomposition.pyi b/stubs/networkx/networkx/algorithms/tree/decomposition.pyi new file mode 100644 index 000000000000..f50ed7b684fc --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/decomposition.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["junction_tree"] + +@_dispatchable +def junction_tree(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/distance_measures.pyi b/stubs/networkx/networkx/algorithms/tree/distance_measures.pyi new file mode 100644 index 000000000000..eb523e2331ac --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/distance_measures.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["center", "centroid"] + +def center(G: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def centroid(G: Graph[_Node]) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/mst.pyi b/stubs/networkx/networkx/algorithms/tree/mst.pyi new file mode 100644 index 000000000000..dc175b1cb1f0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/mst.pyi @@ -0,0 +1,106 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterator +from dataclasses import dataclass +from enum import Enum +from typing import Final, Literal +from typing_extensions import Self + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "minimum_spanning_edges", + "maximum_spanning_edges", + "minimum_spanning_tree", + "maximum_spanning_tree", + "number_of_spanning_trees", + "random_spanning_tree", + "partition_spanning_tree", + "EdgePartition", + "SpanningTreeIterator", +] + +class EdgePartition(Enum): + OPEN = 0 + INCLUDED = 1 + EXCLUDED = 2 + +@_dispatchable +def boruvka_mst_edges( + G: Graph[_Node], minimum: bool = True, weight: str = "weight", keys: bool = False, data: bool = True, ignore_nan: bool = False +): ... +@_dispatchable +def kruskal_mst_edges( + G: Graph[_Node], + minimum: bool, + weight: str = "weight", + keys: bool = True, + data: bool = True, + ignore_nan: bool = False, + partition: str | None = None, +): ... +@_dispatchable +def prim_mst_edges( + G: Graph[_Node], minimum: bool, weight: str = "weight", keys: bool = True, data: bool = True, ignore_nan: bool = False +): ... + +ALGORITHMS: Final[dict[str, Callable[..., Generator[Incomplete, Incomplete, Incomplete]]]] + +@_dispatchable +def minimum_spanning_edges( + G: Graph[_Node], + algorithm: str = "kruskal", + weight: str = "weight", + keys: bool = True, + data: bool | None = True, + ignore_nan: bool = False, +) -> Iterator[Incomplete]: ... +@_dispatchable +def maximum_spanning_edges( + G: Graph[_Node], + algorithm: str = "kruskal", + weight: str = "weight", + keys: bool = True, + data: bool | None = True, + ignore_nan: bool = False, +) -> Iterator[Incomplete]: ... +@_dispatchable +def minimum_spanning_tree( + G: Graph[_Node], weight: str = "weight", algorithm: str = "kruskal", ignore_nan: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def partition_spanning_tree( + G: Graph[_Node], minimum: bool = True, weight: str = "weight", partition: str = "partition", ignore_nan: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def maximum_spanning_tree( + G: Graph[_Node], weight: str = "weight", algorithm: str = "kruskal", ignore_nan: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def random_spanning_tree( + G: Graph[_Node], weight: str | None = None, *, multiplicative=True, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... + +class SpanningTreeIterator: + @dataclass(order=True) + class Partition: + mst_weight: float + partition_dict: dict[Incomplete, Incomplete] + def __copy__(self) -> SpanningTreeIterator.Partition: ... + + G: Incomplete + weight: Incomplete + minimum: Incomplete + ignore_nan: Incomplete + partition_key: str + + def __init__(self, G: DiGraph[_Node], weight: str = "weight", minimum: bool = True, ignore_nan: bool = False) -> None: ... + partition_queue: Incomplete + + def __iter__(self) -> Self: ... + def __next__(self): ... + +@_dispatchable +def number_of_spanning_trees(G: Graph[_Node], *, root=None, weight=None) -> float | Literal[0]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/operations.pyi b/stubs/networkx/networkx/algorithms/tree/operations.pyi new file mode 100644 index 000000000000..b66207c5dfce --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/operations.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["join_trees"] + +@_dispatchable +def join_trees( + rooted_trees: Iterable[Incomplete], *, label_attribute: str | None = None, first_label: int | None = 0 +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/recognition.pyi b/stubs/networkx/networkx/algorithms/tree/recognition.pyi new file mode 100644 index 000000000000..14b1b4ae6147 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/recognition.pyi @@ -0,0 +1,14 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_arborescence", "is_branching", "is_forest", "is_tree"] + +@_dispatchable +def is_arborescence(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_branching(G: DiGraph[_Node]) -> bool: ... +@_dispatchable +def is_forest(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_tree(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/triads.pyi b/stubs/networkx/networkx/algorithms/triads.pyi new file mode 100644 index 000000000000..b4b8fc840daf --- /dev/null +++ b/stubs/networkx/networkx/algorithms/triads.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Collection, Generator +from typing import Final + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["triadic_census", "is_triad", "all_triads", "triads_by_type", "triad_type"] + +TRICODES: Final[tuple[int, ...]] +TRIAD_NAMES: Final[tuple[str, ...]] +TRICODE_TO_NAME: Final[dict[int, str]] + +@_dispatchable +def triadic_census(G: DiGraph[_Node], nodelist: Collection[_Node] | None = None) -> dict[str, int]: ... +@_dispatchable +def is_triad(G: Graph[_Node]) -> bool: ... +@_dispatchable +def all_triads(G: DiGraph[_Node]) -> Generator[Incomplete]: ... +@_dispatchable +def triads_by_type(G: DiGraph[_Node]) -> defaultdict[Incomplete, list[Incomplete]]: ... +@_dispatchable +def triad_type(G: DiGraph[_Node]) -> str | None: ... diff --git a/stubs/networkx/networkx/algorithms/vitality.pyi b/stubs/networkx/networkx/algorithms/vitality.pyi new file mode 100644 index 000000000000..3fd2cfe0e482 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/vitality.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["closeness_vitality"] + +@_dispatchable +def closeness_vitality( + G: Graph[_Node], node=None, weight: str | None = None, wiener_index: float | None = None +) -> float | dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/voronoi.pyi b/stubs/networkx/networkx/algorithms/voronoi.pyi new file mode 100644 index 000000000000..63f890bf2591 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/voronoi.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["voronoi_cells"] + +@_dispatchable +def voronoi_cells( + G: Graph[_Node], + center_nodes: set[Incomplete], + weight: str | Callable[[Any, Any, SupportsGetItem[str, Any]], float | None] | None = "weight", +) -> dict[Incomplete, set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/walks.pyi b/stubs/networkx/networkx/algorithms/walks.pyi new file mode 100644 index 000000000000..44a872420ab5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/walks.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_of_walks"] + +@_dispatchable +def number_of_walks(G: Graph[_Node], walk_length: int) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/wiener.pyi b/stubs/networkx/networkx/algorithms/wiener.pyi new file mode 100644 index 000000000000..6920d3e7176d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/wiener.pyi @@ -0,0 +1,13 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["wiener_index", "schultz_index", "gutman_index", "hyper_wiener_index"] + +@_dispatchable +def wiener_index(G: Graph[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def schultz_index(G: Graph[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def gutman_index(G: Graph[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def hyper_wiener_index(G: Graph[_Node], weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/classes/__init__.pyi b/stubs/networkx/networkx/classes/__init__.pyi new file mode 100644 index 000000000000..e8494acec551 --- /dev/null +++ b/stubs/networkx/networkx/classes/__init__.pyi @@ -0,0 +1,7 @@ +from . import coreviews as coreviews, filters as filters, graphviews as graphviews, reportviews as reportviews +from .digraph import DiGraph as DiGraph +from .function import * +from .graph import Graph as Graph +from .graphviews import reverse_view as reverse_view, subgraph_view as subgraph_view +from .multidigraph import MultiDiGraph as MultiDiGraph +from .multigraph import MultiGraph as MultiGraph diff --git a/stubs/networkx/networkx/classes/coreviews.pyi b/stubs/networkx/networkx/classes/coreviews.pyi new file mode 100644 index 000000000000..ed0114551bfc --- /dev/null +++ b/stubs/networkx/networkx/classes/coreviews.pyi @@ -0,0 +1,79 @@ +from collections.abc import Callable, Iterator, Mapping +from typing import TypeVar +from typing_extensions import Self + +_T = TypeVar("_T") +_U = TypeVar("_U") +_V = TypeVar("_V") + +__all__ = [ + "AtlasView", + "AdjacencyView", + "MultiAdjacencyView", + "UnionAtlas", + "UnionAdjacency", + "UnionMultiInner", + "UnionMultiAdjacency", + "FilterAtlas", + "FilterAdjacency", + "FilterMultiInner", + "FilterMultiAdjacency", +] + +class AtlasView(Mapping[_T, dict[_U, _V]]): + __slots__ = ("_atlas",) + def __getstate__(self) -> dict[str, Mapping[_T, dict[_U, _V]]]: ... + def __setstate__(self, state: dict[str, Mapping[_T, dict[_U, _V]]]) -> None: ... + def __init__(self, d: Mapping[_T, dict[_U, _V]]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> dict[_U, _V]: ... + def copy(self) -> dict[_T, dict[_U, _V]]: ... + +class AdjacencyView(AtlasView[_T, _U, _V]): + __slots__ = () + +class MultiAdjacencyView(AdjacencyView[_T, _U, _V]): + __slots__ = () + +class UnionAtlas(Mapping[_T, dict[_U, _V]]): + __slots__ = ("_succ", "_pred") + def __init__(self, succ: AtlasView[_T, _U, _V], pred: AtlasView[_T, _U, _V]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> dict[_U, _V]: ... + def copy(self) -> Self: ... + +class UnionAdjacency(Mapping[_T, dict[_U, _V]]): + __slots__ = ("_succ", "_pred") + def __init__(self, succ: AdjacencyView[_T, _U, _V], pred: AdjacencyView[_T, _U, _V]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> dict[_U, _V]: ... + def copy(self) -> Self: ... + +class UnionMultiInner(UnionAtlas[_T, _U, _V]): + __slots__ = () + +class UnionMultiAdjacency(UnionAdjacency[_T, _U, _V]): + __slots__ = () + +class FilterAtlas(Mapping[_T, _U]): + NODE_OK: Callable[[_T], bool] + def __init__(self, d: Mapping[_T, _U], NODE_OK: Callable[[_T], bool]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> _U: ... + +class FilterAdjacency(Mapping[_T, Mapping[_U, _V]]): + NODE_OK: Callable[[_T], bool] + EDGE_OK: Callable[[_T, _T], bool] + def __init__( + self, d: Mapping[_T, Mapping[_U, _V]], NODE_OK: Callable[[_T], bool], EDGE_OK: Callable[[_T, _T], bool] + ) -> None: ... + def __len__(self): ... + def __iter__(self): ... + def __getitem__(self, node: _T) -> FilterAtlas[_U, _V]: ... + +class FilterMultiInner(FilterAdjacency[_T, _U, _V]): ... +class FilterMultiAdjacency(FilterAdjacency[_T, _U, _V]): ... diff --git a/stubs/networkx/networkx/classes/digraph.pyi b/stubs/networkx/networkx/classes/digraph.pyi new file mode 100644 index 000000000000..e6a0afb41288 --- /dev/null +++ b/stubs/networkx/networkx/classes/digraph.pyi @@ -0,0 +1,52 @@ +from collections.abc import Iterator +from functools import cached_property +from typing import Any +from typing_extensions import Self + +from networkx.classes.coreviews import AdjacencyView +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.classes.reportviews import ( + DiDegreeView, + InDegreeView, + InEdgeView, + InMultiDegreeView, + InMultiEdgeView, + OutDegreeView, + OutEdgeView, + OutMultiDegreeView, +) + +__all__ = ["DiGraph"] + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class DiGraph(Graph[_Node, _NodeData, _EdgeData]): + @cached_property + def succ(self) -> AdjacencyView[_Node, _Node, dict[str, Any]]: ... + @cached_property + def pred(self) -> AdjacencyView[_Node, _Node, dict[str, Any]]: ... + def has_successor(self, u: _Node, v: _Node) -> bool: ... + def has_predecessor(self, u: _Node, v: _Node) -> bool: ... + def successors(self, n: _Node) -> Iterator[_Node]: ... + + neighbors = successors + + def predecessors(self, n: _Node) -> Iterator[_Node]: ... + @cached_property + def edges(self) -> OutEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def out_edges(self) -> OutEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + # Including subtypes' possible return types for LSP + def in_edges(self) -> InEdgeView[_Node, _NodeData, _EdgeData] | InMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def degree(self) -> DiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + # Including subtypes' possible return types for LSP + def in_degree(self) -> InDegreeView[_Node, _NodeData, _EdgeData] | InMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + # Including subtypes' possible return types for LSP + def out_degree(self) -> OutDegreeView[_Node, _NodeData, _EdgeData] | OutMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, reciprocal: bool = False, as_view: bool = False) -> Graph[_Node, _NodeData, _EdgeData]: ... # type: ignore[override] # Has an additional `reciprocal` keyword argument + def reverse(self, copy: bool = True) -> Self: ... diff --git a/stubs/networkx/networkx/classes/filters.pyi b/stubs/networkx/networkx/classes/filters.pyi new file mode 100644 index 000000000000..c8689991e6f4 --- /dev/null +++ b/stubs/networkx/networkx/classes/filters.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete + +__all__ = [ + "no_filter", + "hide_nodes", + "hide_edges", + "hide_multiedges", + "hide_diedges", + "hide_multidiedges", + "show_nodes", + "show_edges", + "show_multiedges", + "show_diedges", + "show_multidiedges", +] + +def no_filter(*items): ... +def hide_nodes(nodes): ... +def hide_diedges(edges): ... +def hide_edges(edges): ... +def hide_multidiedges(edges): ... +def hide_multiedges(edges): ... + +class show_nodes: + nodes: Incomplete + def __init__(self, nodes) -> None: ... + def __call__(self, node): ... + +def show_diedges(edges): ... +def show_edges(edges): ... +def show_multidiedges(edges): ... +def show_multiedges(edges): ... diff --git a/stubs/networkx/networkx/classes/function.pyi b/stubs/networkx/networkx/classes/function.pyi new file mode 100644 index 000000000000..17d152c96157 --- /dev/null +++ b/stubs/networkx/networkx/classes/function.pyi @@ -0,0 +1,182 @@ +from _typeshed import Incomplete, SupportsItems, SupportsKeysAndGetItem, Unused +from collections.abc import Callable, Collection, Generator, Hashable, Iterable, Iterator +from typing import Literal, TypeVar, overload + +from networkx import _dispatchable +from networkx.algorithms.planarity import PlanarEmbedding +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _NBunch, _Node, _NodeData +from networkx.classes.multigraph import MultiGraph + +__all__ = [ + "nodes", + "edges", + "degree", + "degree_histogram", + "neighbors", + "number_of_nodes", + "number_of_edges", + "density", + "is_directed", + "freeze", + "is_frozen", + "subgraph", + "induced_subgraph", + "edge_subgraph", + "restricted_view", + "to_directed", + "to_undirected", + "add_star", + "add_path", + "add_cycle", + "create_empty_copy", + "set_node_attributes", + "get_node_attributes", + "remove_node_attributes", + "set_edge_attributes", + "get_edge_attributes", + "remove_edge_attributes", + "all_neighbors", + "non_neighbors", + "non_edges", + "common_neighbors", + "is_weighted", + "is_negatively_weighted", + "is_empty", + "selfloop_edges", + "nodes_with_selfloops", + "number_of_selfloops", + "path_weight", + "is_path", + "describe", +] + +_U = TypeVar("_U") + +def nodes(G: Graph[_Node]): ... +def edges(G: Graph[_Node], nbunch=None): ... +def degree(G: Graph[_Node], nbunch=None, weight=None): ... +def neighbors(G: Graph[_Node], n): ... +def number_of_nodes(G: Graph[_Node]): ... +def number_of_edges(G: Graph[_Node]): ... +def density(G: Graph[_Node]): ... +def degree_histogram(G: Graph[_Node]) -> list[int]: ... + +@overload +def is_directed(G: PlanarEmbedding[Hashable]) -> Literal[False]: ... # type: ignore[misc] # Incompatible return types +@overload +def is_directed(G: DiGraph[Hashable]) -> Literal[True]: ... # type: ignore[misc] # Incompatible return types +@overload +def is_directed(G: Graph[Hashable]) -> Literal[False]: ... + +def freeze(G: Graph[_Node]): ... +def is_frozen(G: Graph[Incomplete]) -> bool: ... +def add_star(G_to_add_to: Graph[Incomplete], nodes_for_star: Iterable[Incomplete], **attr) -> None: ... +def add_path(G_to_add_to: Graph[Incomplete], nodes_for_path: Iterable[Incomplete], **attr) -> None: ... +def add_cycle(G_to_add_to: Graph[Incomplete], nodes_for_cycle: Iterable[Incomplete], **attr) -> None: ... +def subgraph(G: Graph[_Node], nbunch: Iterable[Incomplete]): ... +def induced_subgraph(G: Graph[_Node, _NodeData, _EdgeData], nbunch: _NBunch[_Node]) -> Graph[_Node, _NodeData, _EdgeData]: ... +def edge_subgraph(G: Graph[_Node], edges: Iterable[Incomplete]) -> Graph[Incomplete]: ... +def restricted_view(G: Graph[_Node], nodes: Iterable[Incomplete], edges: Iterable[Incomplete]) -> Graph[Incomplete]: ... +def to_directed(graph): ... +def to_undirected(graph): ... +def create_empty_copy(G: Graph[_Node], with_data: bool = True): ... + +# incomplete: Can "Any scalar value" be enforced? +@overload +def set_node_attributes( + G: Graph[Hashable], + values: SupportsItems[_Node, Unused], + name: str, + *, + backend=None, # @_dispatchable adds these arguments, but we can't use this decorator with @overload + **backend_kwargs, +) -> None: ... +@overload +def set_node_attributes( + G: Graph[_Node], + values: SupportsItems[_Node, SupportsKeysAndGetItem[Incomplete, Incomplete] | Iterable[tuple[Incomplete, Incomplete]]], + name: None = None, + *, + backend=None, + **backend_kwargs, +) -> None: ... + +@_dispatchable +def get_node_attributes(G: Graph[_Node], name: str, default=None) -> dict[_Node, Incomplete]: ... +@_dispatchable +def remove_node_attributes(G: Graph[_Node], *attr_names, nbunch=None) -> None: ... + +@overload +def set_edge_attributes( + G: Graph[_Node], + values: SupportsItems[tuple[_Node, _Node], Incomplete], + name: str, + *, + backend: str | None = None, # @_dispatchable adds these arguments, but we can't use this decorator with @overload + **backend_kwargs, +) -> None: ... +@overload +def set_edge_attributes( + G: MultiGraph[_Node], + values: dict[tuple[_Node, _Node, Incomplete], Incomplete], + name: str, + *, + backend: str | None = None, + **backend_kwargs, +) -> None: ... +@overload +def set_edge_attributes( + G: Graph[Hashable], values, name: None = None, *, backend: str | None = None, **backend_kwargs +) -> None: ... + +@_dispatchable +def get_edge_attributes(G: Graph[_Node], name: str, default=None) -> dict[tuple[_Node, _Node], Incomplete]: ... +@_dispatchable +def remove_edge_attributes(G: Graph[_Node], *attr_names, ebunch=None) -> None: ... +def all_neighbors(graph: Graph[_Node], node: _Node) -> Iterator[_Node]: ... +def non_neighbors(graph: Graph[_Node], node: _Node) -> Generator[_Node]: ... +def non_edges(graph: Graph[_Node]) -> Generator[tuple[_Node, _Node]]: ... +def common_neighbors(G: Graph[_Node], u: _Node, v: _Node) -> Generator[_Node]: ... +@_dispatchable +def is_weighted(G: Graph[_Node], edge: tuple[_Node, _Node] | None = None, weight: str = "weight") -> bool: ... +@_dispatchable +def is_negatively_weighted(G: Graph[_Node], edge: tuple[_Node, _Node] | None = None, weight: str = "weight") -> bool: ... +@_dispatchable +def is_empty(G: Graph[Hashable]) -> bool: ... +def nodes_with_selfloops(G: Graph[_Node]) -> Generator[_Node]: ... + +@overload +def selfloop_edges( + G: Graph[_Node], data: Literal[False] = False, keys: Literal[False] = False, default=None +) -> Generator[tuple[_Node, _Node]]: ... +@overload +def selfloop_edges( + G: Graph[_Node, _NodeData, _EdgeData], data: Literal[True], keys: Literal[False] = False, default=None +) -> Generator[tuple[_Node, _Node, _EdgeData]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: str, keys: Literal[False] = False, default: _U | None = None +) -> Generator[tuple[_Node, _Node, _U]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: Literal[False], keys: Literal[True], default=None +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: Literal[False] = False, *, keys: Literal[True], default=None +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def selfloop_edges( + G: Graph[_Node, _NodeData, _EdgeData], data: Literal[True], keys: Literal[True], default=None +) -> Generator[tuple[_Node, _Node, int, _EdgeData]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: str, keys: Literal[True], default: _U | None = None +) -> Generator[tuple[_Node, _Node, int, _U]]: ... + +@_dispatchable +def number_of_selfloops(G: Graph[Hashable]) -> int: ... +def is_path(G: Graph[_Node], path: Iterable[Incomplete]) -> bool: ... +def path_weight(G: Graph[_Node], path: Collection[Incomplete], weight: str) -> int: ... +def describe(G: Graph[_Node], describe_hook: Callable[[Graph[_Node]], dict[str, Incomplete]] | None = None) -> None: ... diff --git a/stubs/networkx/networkx/classes/graph.pyi b/stubs/networkx/networkx/classes/graph.pyi new file mode 100644 index 000000000000..a942816e731b --- /dev/null +++ b/stubs/networkx/networkx/classes/graph.pyi @@ -0,0 +1,128 @@ +from collections.abc import Callable, Collection, Hashable, Iterable, Iterator, Mapping, MutableMapping +from decimal import Decimal +from functools import cached_property +from typing import Any, ClassVar, Generic, TypeAlias, TypeVar, overload +from typing_extensions import Self + +import numpy +from networkx.classes.coreviews import AdjacencyView, AtlasView +from networkx.classes.digraph import DiGraph +from networkx.classes.reportviews import DegreeView, DiDegreeView, EdgeView, NodeView, OutEdgeView + +_DataBound: TypeAlias = Mapping[str, Any] + +_Node = TypeVar("_Node", bound=Hashable) +_NodeData = TypeVar("_NodeData", bound=_DataBound, default=dict[str, Any]) +_EdgeData = TypeVar("_EdgeData", bound=_DataBound, default=dict[str, Any]) + +_NodeWithData: TypeAlias = tuple[_Node, _NodeData] +_NodePlus: TypeAlias = _Node | _NodeWithData[_Node, _NodeData] +_Edge: TypeAlias = tuple[_Node, _Node] +_EdgeWithData: TypeAlias = tuple[_Node, _Node, _EdgeData] +_EdgePlus: TypeAlias = _Edge[_Node] | _EdgeWithData[_Node, _EdgeData] +_MapFactory: TypeAlias = Callable[[], MutableMapping[str, Any]] +_NBunch: TypeAlias = _Node | Iterable[_Node] | None +_Data: TypeAlias = ( + Graph[_Node, _NodeData, _EdgeData] + | dict[_Node, dict[_Node, _NodeData]] + | dict[_Node, Iterable[_Node]] + | Iterable[_EdgePlus[_Node, _EdgeData]] + | numpy.ndarray[Any, Any] + # | scipy.sparse.base.spmatrix +) + +__all__ = ["Graph"] + +class Graph(Collection[_Node], Generic[_Node, _NodeData, _EdgeData]): + __networkx_backend__: ClassVar[str] + node_dict_factory: ClassVar[_MapFactory] + node_attr_dict_factory: ClassVar[_MapFactory] + adjlist_outer_dict_factory: ClassVar[_MapFactory] + adjlist_inner_dict_factory: ClassVar[_MapFactory] + edge_attr_dict_factory: ClassVar[_MapFactory] + graph_attr_dict_factory: ClassVar[_MapFactory] + + graph: dict[str, Any] + __networkx_cache__: dict[str, Any] + + def to_directed_class(self) -> type[DiGraph[_Node, _NodeData, _EdgeData]]: ... + def to_undirected_class(self) -> type[Graph[_Node, _NodeData, _EdgeData]]: ... + # @_dispatchable adds `backend` argument, but this decorated is unsupported constructor type here + # and __init__() ignores this argument + def __new__(cls, *args, backend=None, **kwargs) -> Self: ... + def __init__( + self, incoming_graph_data: _Data[_Node, _NodeData, _EdgeData] | None = None, **attr: Any + ) -> None: ... # attr: key=value pairs + @cached_property + def adj(self) -> AdjacencyView[_Node, _Node, _EdgeData]: ... + + # This object is a read-only dict-like structure + @property + def name(self) -> str: ... + @name.setter + def name(self, s: str) -> None: ... + + def __iter__(self) -> Iterator[_Node]: ... + def __contains__(self, n: object) -> bool: ... + def __len__(self) -> int: ... + def __getitem__(self, n: _Node) -> AtlasView[_Node, str, Any]: ... + def add_node(self, node_for_adding: _Node, **attr: Any) -> None: ... # attr: Set or change node attributes using key=value + def add_nodes_from( + self, nodes_for_adding: Iterable[_NodePlus[_Node, _NodeData]], **attr: Any + ) -> None: ... # attr: key=value pairs + def remove_node(self, n: _Node) -> None: ... + def remove_nodes_from(self, nodes: Iterable[_Node]) -> None: ... + @cached_property + def nodes(self) -> NodeView[_Node, _NodeData, _EdgeData]: ... + def number_of_nodes(self) -> int: ... + def order(self) -> int: ... + def has_node(self, n: _Node) -> bool: ... + # Including subtypes' possible return types for LSP + def add_edge(self, u_of_edge: _Node, v_of_edge: _Node, **attr: Any) -> Hashable | None: ... + # attr: Edge data (or labels or objects) can be assigned using keyword arguments + def add_edges_from(self, ebunch_to_add: Iterable[_EdgePlus[_Node, _EdgeData]], **attr: Any) -> None: ... + # attr: Edge data (or labels or objects) can be assigned using keyword arguments + def add_weighted_edges_from( + self, ebunch_to_add: Iterable[tuple[_Node, _Node, float | Decimal | None]], weight: str = "weight", **attr: Any + ) -> None: ... + # attr: Edge attributes to add/update for all edges. + def remove_edge(self, u: _Node, v: _Node) -> None: ... + def remove_edges_from(self, ebunch: Iterable[_EdgePlus[_Node, _EdgeData]]) -> None: ... + + @overload + def update(self, edges: Graph[_Node, _NodeData, _EdgeData], nodes: None = None) -> None: ... + @overload + def update( + self, + edges: Graph[_Node, _NodeData, _EdgeData] | Iterable[_EdgePlus[_Node, _EdgeData]] | None = None, + nodes: Iterable[_Node] | None = None, + ) -> None: ... + + def has_edge(self, u: _Node, v: _Node) -> bool: ... + def neighbors(self, n: _Node) -> Iterator[_Node]: ... + @cached_property + # Including subtypes' possible return types for LSP + def edges(self) -> EdgeView[_Node, _NodeData, _EdgeData] | OutEdgeView[_Node, _NodeData, _EdgeData]: ... + def get_edge_data(self, u: _Node, v: _Node, default: Any = None) -> _EdgeData: ... + # default: any Python object + def adjacency(self) -> Iterator[tuple[_Node, dict[_Node, _EdgeData]]]: ... + @cached_property + # Including subtypes' possible return types for LSP + def degree(self) -> DegreeView[_Node, _NodeData, _EdgeData] | DiDegreeView[_Node, _NodeData, _EdgeData]: ... + def clear(self) -> None: ... + def clear_edges(self) -> None: ... + def is_multigraph(self) -> bool: ... + def is_directed(self) -> bool: ... + def copy(self, as_view: bool = False) -> Self: ... + def to_directed(self, as_view: bool = False) -> DiGraph[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, as_view: bool = False) -> Graph[_Node, _NodeData, _EdgeData]: ... + def subgraph(self, nodes: _NBunch[_Node]) -> Self: ... + def edge_subgraph(self, edges: Iterable[_Edge[_Node]]) -> Self: ... + + @overload + def size(self, weight: None = None) -> int: ... + @overload + def size(self, weight: str) -> float: ... + + def number_of_edges(self, u: _Node | None = None, v: _Node | None = None) -> int: ... + def nbunch_iter(self, nbunch: _NBunch[_Node] = None) -> Iterator[_Node]: ... diff --git a/stubs/networkx/networkx/classes/graphviews.pyi b/stubs/networkx/networkx/classes/graphviews.pyi new file mode 100644 index 000000000000..29c42a5191af --- /dev/null +++ b/stubs/networkx/networkx/classes/graphviews.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable, Hashable +from typing import TypeVar, overload + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _DataBound, _EdgeData, _Node, _NodeData +from networkx.classes.multidigraph import MultiDiGraph +from networkx.classes.multigraph import MultiGraph + +_G = TypeVar("_G", bound=Graph[Hashable, _DataBound, _DataBound]) +_D = TypeVar("_D", bound=DiGraph[Hashable, _DataBound, _DataBound]) + +__all__ = ["generic_graph_view", "subgraph_view", "reverse_view"] + +@overload +def generic_graph_view(G: _G, create_using: None = None) -> _G: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[MultiDiGraph[_Node, _NodeData, _EdgeData]] +) -> MultiDiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[DiGraph[_Node, _NodeData, _EdgeData]] +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[MultiGraph[_Node, _NodeData, _EdgeData]] +) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[Graph[_Node, _NodeData, _EdgeData]] +) -> Graph[_Node, _NodeData, _EdgeData]: ... + +@overload +def subgraph_view( + G: MultiDiGraph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node, int], bool] = ..., +) -> MultiDiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def subgraph_view( + G: MultiGraph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node, int], bool] = ..., +) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def subgraph_view( + G: DiGraph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node], bool] = ..., +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def subgraph_view( + G: Graph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node], bool] = ..., +) -> Graph[_Node, _NodeData, _EdgeData]: ... + +def reverse_view(G: _D) -> _D: ... diff --git a/stubs/networkx/networkx/classes/multidigraph.pyi b/stubs/networkx/networkx/classes/multidigraph.pyi new file mode 100644 index 000000000000..324f033ac0e6 --- /dev/null +++ b/stubs/networkx/networkx/classes/multidigraph.pyi @@ -0,0 +1,38 @@ +from functools import cached_property +from typing import Any + +from networkx.classes.coreviews import MultiAdjacencyView +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _EdgeData, _Node, _NodeData +from networkx.classes.multigraph import MultiGraph +from networkx.classes.reportviews import ( + DiMultiDegreeView, + InMultiDegreeView, + InMultiEdgeView, + OutMultiDegreeView, + OutMultiEdgeView, +) + +__all__ = ["MultiDiGraph"] + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class MultiDiGraph(MultiGraph[_Node, _NodeData, _EdgeData], DiGraph[_Node, _NodeData, _EdgeData]): + @cached_property + def succ(self) -> MultiAdjacencyView[_Node, _Node, dict[str, Any]]: ... + @cached_property + def pred(self) -> MultiAdjacencyView[_Node, _Node, dict[str, Any]]: ... + @cached_property + def edges(self) -> OutMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def out_edges(self) -> OutMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def in_edges(self) -> InMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def degree(self) -> DiMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def in_degree(self) -> InMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def out_degree(self) -> OutMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, reciprocal: bool = False, as_view: bool = False) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... # type: ignore[override] # Has an additional `reciprocal` keyword argument diff --git a/stubs/networkx/networkx/classes/multigraph.pyi b/stubs/networkx/networkx/classes/multigraph.pyi new file mode 100644 index 000000000000..6d3fcdc56bc3 --- /dev/null +++ b/stubs/networkx/networkx/classes/multigraph.pyi @@ -0,0 +1,62 @@ +from collections.abc import Hashable +from functools import cached_property +from typing import Any, ClassVar, TypeAlias, overload +from typing_extensions import Self, TypeVar + +from networkx.classes.coreviews import MultiAdjacencyView +from networkx.classes.graph import Graph, _EdgeData, _MapFactory, _Node, _NodeData +from networkx.classes.multidigraph import MultiDiGraph +from networkx.classes.reportviews import DiMultiDegreeView, MultiDegreeView, MultiEdgeView, OutMultiEdgeView + +_MultiEdge: TypeAlias = tuple[_Node, _Node, int] # noqa: Y047 + +_DefaultT = TypeVar("_DefaultT") +_KeyT = TypeVar("_KeyT", bound=Hashable) + +__all__ = ["MultiGraph"] + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class MultiGraph(Graph[_Node, _NodeData, _EdgeData]): + edge_key_dict_factory: ClassVar[_MapFactory] + def to_directed_class(self) -> type[MultiDiGraph[_Node, _NodeData, _EdgeData]]: ... + def to_undirected_class(self) -> type[MultiGraph[_Node, _NodeData, _EdgeData]]: ... + # @_dispatchable adds `backend` argument, but this decorated is unsupported constructor type here + # and __init__() ignores this argument + def __new__(cls, *args, backend=None, **kwargs) -> Self: ... + def __init__(self, incoming_graph_data=None, multigraph_input: bool | None = None, **attr: Any) -> None: ... + @cached_property + def adj(self) -> MultiAdjacencyView[_Node, _Node, _EdgeData]: ... # data can be any type + def new_edge_key(self, u: _Node, v: _Node) -> int: ... + + # key : hashable identifier, optional (default=lowest unused integer) + @overload # type: ignore[override] # More complex overload + def add_edge(self, u_for_edge: _Node, v_for_edge: _Node, key: int | None = None, **attr: Any) -> int: ... + @overload + def add_edge(self, u_for_edge: _Node, v_for_edge: _Node, key: _KeyT, **attr: Any) -> _KeyT: ... + + def remove_edge(self, u: _Node, v: _Node, key: Hashable | None = None) -> None: ... + def has_edge(self, u: _Node, v: _Node, key: Hashable | None = None) -> bool: ... + @cached_property + # Including subtypes' possible return types for LSP + def edges(self) -> MultiEdgeView[_Node, _NodeData, _EdgeData] | OutMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + + # key : hashable identifier, optional (default=None). + # default : any Python object (default=None). Value to return if the specific edge (u, v, key) is not found. + # Returns: The edge attribute dictionary. + @overload # type: ignore[override] + def get_edge_data(self, u: _Node, v: _Node, key: Hashable, default: _DefaultT | None = None) -> _EdgeData | _DefaultT: ... + # default : any Python object (default=None). Value to return if there are no edges between u and v and no key is specified. + # Returns: A dictionary mapping edge keys to attribute dictionaries for each of those edges if no specific key is provided. + @overload + def get_edge_data( + self, u: _Node, v: _Node, key: None = None, default: _DefaultT | None = None + ) -> dict[Hashable, _EdgeData | _DefaultT]: ... + + def copy(self, as_view: bool = False) -> Self: ... + @cached_property + # Including subtypes' possible return types for LSP + def degree(self) -> MultiDegreeView[_Node, _NodeData, _EdgeData] | DiMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + def to_directed(self, as_view: bool = False) -> MultiDiGraph[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, as_view: bool = False) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... diff --git a/stubs/networkx/networkx/classes/reportviews.pyi b/stubs/networkx/networkx/classes/reportviews.pyi new file mode 100644 index 000000000000..5bf0396d6108 --- /dev/null +++ b/stubs/networkx/networkx/classes/reportviews.pyi @@ -0,0 +1,427 @@ +from _typeshed import Incomplete, Unused +from abc import ABC +from collections.abc import Iterable, Iterator, Mapping, Set as AbstractSet +from typing import Generic, Literal, TypeVar, overload +from typing_extensions import Self + +from networkx.classes.graph import Graph, _Edge, _EdgeData, _NBunch, _Node, _NodeData + +_D = TypeVar("_D") +_U = TypeVar("_U") + +__all__ = [ + "NodeView", + "NodeDataView", + "EdgeView", + "OutEdgeView", + "InEdgeView", + "EdgeDataView", + "OutEdgeDataView", + "InEdgeDataView", + "MultiEdgeView", + "OutMultiEdgeView", + "InMultiEdgeView", + "MultiEdgeDataView", + "OutMultiEdgeDataView", + "InMultiEdgeDataView", + "DegreeView", + "DiDegreeView", + "InDegreeView", + "OutDegreeView", + "MultiDegreeView", + "DiMultiDegreeView", + "InMultiDegreeView", + "OutMultiDegreeView", +] + +class NodeView(Mapping[_Node, _NodeData], AbstractSet[_Node], Generic[_Node, _NodeData, _EdgeData]): + __slots__ = ("_nodes",) + def __init__(self, graph: Graph[_Node, _NodeData, _EdgeData]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_Node]: ... + def __getitem__(self, n: _Node) -> _NodeData: ... + def __contains__(self, n: object) -> bool: ... + + @overload + def __call__(self, data: Literal[False] = False, default=None) -> Self: ... + @overload + def __call__(self, data: Literal[True] | str, default=None) -> NodeDataView[_Node, _NodeData, _EdgeData]: ... + + @overload + def data(self, data: Literal[False], default=None) -> Self: ... + @overload + def data(self, data: Literal[True] | str = True, default=None) -> NodeDataView[_Node, _NodeData, _EdgeData]: ... + +class NodeDataView(AbstractSet[_Node], Generic[_Node, _NodeData, _EdgeData]): + __slots__ = ("_nodes", "_data", "_default") + def __init__(self, nodedict: _NodeData, data: bool | str = False, default=None) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[tuple[_Node, _NodeData]]: ... # type: ignore[override] + def __contains__(self, n: object) -> bool: ... + def __getitem__(self, n: _Node) -> _NodeData | Incomplete: ... + +class DiDegreeView(Generic[_Node, _NodeData, _EdgeData]): + def __init__( + self, G: Graph[_Node, _NodeData, _EdgeData], nbunch: _NBunch[_Node] = None, weight: bool | str | None = None + ) -> None: ... + + @overload # Use this overload first in case _Node=str, since `str` matches `Iterable[str]` + def __call__(self, nbunch: _Node, weight: bool | str | None = None) -> int: ... # type: ignore[overload-overlap] + @overload + def __call__(self, nbunch: Iterable[_Node] | None = None, weight: bool | str | None = None) -> Self: ... + + def __getitem__(self, n: _Node) -> int: ... + def __iter__(self) -> Iterator[tuple[_Node, int]]: ... + def __len__(self) -> int: ... + +class DegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class OutDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class InDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class MultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class DiMultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class InMultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class OutMultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class EdgeViewABC(ABC): ... + +class OutEdgeDataView(EdgeViewABC, Generic[_Node, _D]): + __slots__ = ("_viewer", "_nbunch", "_data", "_default", "_adjdict", "_nodes_nbrs", "_report") + def __init__(self, viewer, nbunch: _NBunch[_Node] = None, data: bool = False, *, default=None) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_D]: ... + def __contains__(self, e: _Edge[_Node]) -> bool: ... + +class EdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class InEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class OutMultiEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = ("keys",) + keys: bool + def __init__( + self, viewer, nbunch: _NBunch[_Node] = None, data: bool = False, *, default=None, keys: bool = False + ) -> None: ... + +class MultiEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class InMultiEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class OutEdgeView(AbstractSet[Incomplete], Mapping[Incomplete, Incomplete], EdgeViewABC, Generic[_Node, _NodeData, _EdgeData]): + __slots__ = ("_adjdict", "_graph", "_nodes_nbrs") + def __init__(self, G: Graph[_Node, _NodeData, _EdgeData]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[tuple[_Node, _Node]]: ... + def __contains__(self, e: _Edge[_Node]) -> bool: ... # type: ignore[override] + def __getitem__(self, e: _Edge[_Node]) -> _EdgeData: ... + dataview = OutEdgeDataView + + @overload + def __call__(self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None) -> Self: ... # type: ignore[overload-overlap] + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None) -> Self: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + +class EdgeView(OutEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = EdgeDataView + + # Have to override parent's overloads with the proper return type based on dataview + @overload + def __call__(self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None) -> Self: ... # type: ignore[overload-overlap] + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None) -> Self: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + +class InEdgeView(OutEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = InEdgeDataView + + # Have to override parent's overloads with the proper return type based on dataview + @overload + def __call__(self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None) -> Self: ... # type: ignore[overload-overlap] + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None) -> Self: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + +class OutMultiEdgeView(OutEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + def __iter__(self) -> Iterator[tuple[_Node, _Node, Incomplete]]: ... # type: ignore[override] + def __getitem__(self, e: tuple[_Node, _Node, Incomplete]) -> _EdgeData: ... # type: ignore[override] + dataview = OutMultiEdgeDataView + + @overload # type: ignore[override] # Has an additional `keys` keyword argument + def __call__( # type: ignore[overload-overlap] + self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None, keys: Literal[True] + ) -> Self: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, data: Literal[False] = False, *, default: None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload # type: ignore[override] + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None, *, keys: Literal[True]) -> Self: ... + @overload + def data( + self, data: Literal[False], default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + +class MultiEdgeView(OutMultiEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = MultiEdgeDataView # type: ignore[assignment] + + # Have to override parent's overloads with the proper return type based on dataview + @overload # type: ignore[override] # Has an additional `keys` keyword argument + def __call__( # type: ignore[overload-overlap] + self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None, keys: Literal[True] + ) -> Self: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, data: Literal[False] = False, *, default: None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload # type: ignore[override] + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None, *, keys: Literal[True]) -> Self: ... + @overload + def data( + self, data: Literal[False], default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + +class InMultiEdgeView(OutMultiEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = InMultiEdgeDataView # type: ignore[assignment] + + # Have to override parent's overloads with the proper return type based on dataview + @overload # type: ignore[override] + def __call__( # type: ignore[overload-overlap] + self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None, keys: Literal[True] + ) -> Self: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, data: Literal[False] = False, *, default: None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload # type: ignore[override] + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None, *, keys: Literal[True]) -> Self: ... + @overload + def data( + self, data: Literal[False], default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... diff --git a/stubs/networkx/networkx/convert.pyi b/stubs/networkx/networkx/convert.pyi new file mode 100644 index 000000000000..b6bd41f09185 --- /dev/null +++ b/stubs/networkx/networkx/convert.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Collection, Iterable + +from networkx.classes.graph import Graph, _Data, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "to_networkx_graph", + "from_dict_of_dicts", + "to_dict_of_dicts", + "from_dict_of_lists", + "to_dict_of_lists", + "from_edgelist", + "to_edgelist", +] + +def to_networkx_graph( + data: _Data[_Node], + create_using: Graph[_Node, _NodeData, _EdgeData] | Callable[[], Graph[_Node, _NodeData, _EdgeData]] | None = None, + multigraph_input: bool = False, +) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def to_dict_of_lists(G: Graph[_Node], nodelist: Collection[_Node] | None = None) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def from_dict_of_lists( + d: dict[_Node, Iterable[_Node]], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[_Node]: ... +def to_dict_of_dicts( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, edge_data: float | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def from_dict_of_dicts( + d: dict[Incomplete, Incomplete], + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + multigraph_input: bool = False, +) -> Graph[Incomplete]: ... +@_dispatchable +def to_edgelist(G: Graph[_Node], nodelist: Collection[_Node] | None = None): ... +@_dispatchable +def from_edgelist( + edgelist: Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/convert_matrix.pyi b/stubs/networkx/networkx/convert_matrix.pyi new file mode 100644 index 000000000000..98179313bcea --- /dev/null +++ b/stubs/networkx/networkx/convert_matrix.pyi @@ -0,0 +1,119 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Collection, Hashable, Iterable +from typing import Literal, TypeAlias, TypeVar, overload + +import numpy +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +# stub_uploader won't allow pandas-stubs in the requires field https://github.com/typeshed-internal/stub_uploader/issues/90 +# from pandas import DataFrame +_DataFrame: TypeAlias = Incomplete +# from pandas.core.dtypes.base import ExtensionDtype +_ExtensionDtype: TypeAlias = Incomplete +# pandas._typing import Axes +# _Axes: TypeAlias = Index | Series | np.ndarray | list | dict | range | tuple +_Axes: TypeAlias = Collection[_Node] +_G = TypeVar("_G", bound=Graph[Hashable]) + +__all__ = [ + "from_pandas_adjacency", + "to_pandas_adjacency", + "from_pandas_edgelist", + "to_pandas_edgelist", + "from_scipy_sparse_array", + "to_scipy_sparse_array", + "from_numpy_array", + "to_numpy_array", +] + +@_dispatchable +def to_pandas_adjacency( + G: Graph[_Node], + nodelist: _Axes[_Node] | None = None, + dtype: numpy.dtype[Incomplete] | None = None, + order: numpy._OrderCF = None, + multigraph_weight: Callable[[list[float]], float] = ..., + weight: str = "weight", + nonedge: float = 0.0, +) -> _DataFrame: ... + +@overload +def from_pandas_adjacency(df: _DataFrame, create_using: type[_G]) -> _G: ... +@overload +def from_pandas_adjacency(df: _DataFrame, create_using: None = None) -> Graph[Incomplete]: ... + +@_dispatchable +def to_pandas_edgelist( + G: Graph[_Node], + source: str | int = "source", + target: str | int = "target", + nodelist: Iterable[_Node] | None = None, + dtype: _ExtensionDtype | None = None, + edge_key: str | int | None = None, +) -> _DataFrame: ... + +@overload +def from_pandas_edgelist( + df: _DataFrame, + source: str | int, + target: str | int, + edge_attr: str | int | list[str | int] | tuple[str | int] | Literal[True] | None, + create_using: type[_G], + edge_key: str | None = None, +) -> _G: ... +@overload +def from_pandas_edgelist( + df: _DataFrame, + source: str | int = "source", + target: str | int = "target", + edge_attr: str | int | list[str | int] | tuple[str | int] | Literal[True] | None = None, + *, + create_using: type[_G], + edge_key: str | None = None, +) -> _G: ... +@overload +def from_pandas_edgelist( + df: _DataFrame, + source: str | int = "source", + target: str | int = "target", + edge_attr: str | int | list[str | int] | tuple[str | int] | Literal[True] | None = None, + create_using: None = None, + edge_key: str | None = None, +) -> Graph[Incomplete]: ... + +@_dispatchable +def to_scipy_sparse_array( + G: Graph[_Node], + nodelist: Collection[_Node] | None = None, + dtype: np.dtype[Incomplete] | None = None, + weight: str | None = "weight", + format: str = "csr", +): ... +@_dispatchable +def from_scipy_sparse_array( + A, + parallel_edges: bool = False, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + edge_attribute: str = "weight", +): ... +@_dispatchable +def to_numpy_array( + G: Graph[_Node], + nodelist: Collection[_Node] | None = None, + dtype: numpy.dtype[Incomplete] | None = None, + order: numpy._OrderCF = None, + multigraph_weight: Callable[[list[float]], float] = ..., + weight: str = "weight", + nonedge: float = 0.0, +) -> numpy.ndarray[Incomplete, numpy.dtype[Incomplete]]: ... + +@overload +def from_numpy_array( + A: numpy.ndarray[Incomplete, Incomplete], parallel_edges: bool = False, create_using: None = None +) -> Graph[Incomplete]: ... +@overload +def from_numpy_array(A: numpy.ndarray[Incomplete, Incomplete], parallel_edges: bool = False, *, create_using: type[_G]) -> _G: ... +@overload +def from_numpy_array(A: numpy.ndarray[Incomplete, Incomplete], parallel_edges: bool, create_using: type[_G]) -> _G: ... diff --git a/stubs/networkx/networkx/drawing/__init__.pyi b/stubs/networkx/networkx/drawing/__init__.pyi new file mode 100644 index 000000000000..ce16049ef6fa --- /dev/null +++ b/stubs/networkx/networkx/drawing/__init__.pyi @@ -0,0 +1,4 @@ +from . import nx_agraph as nx_agraph, nx_pydot as nx_pydot +from .layout import * +from .nx_latex import * +from .nx_pylab import * diff --git a/stubs/networkx/networkx/drawing/layout.pyi b/stubs/networkx/networkx/drawing/layout.pyi new file mode 100644 index 000000000000..e84a432458be --- /dev/null +++ b/stubs/networkx/networkx/drawing/layout.pyi @@ -0,0 +1,166 @@ +from collections.abc import Collection, Mapping +from typing import Any, Literal, TypeAlias + +import numpy as np +from networkx._typing import Array1D, Array2D, ArrayLike1D, Seed +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable +from numpy.typing import NDArray + +__all__ = [ + "bipartite_layout", + "circular_layout", + "forceatlas2_layout", + "kamada_kawai_layout", + "random_layout", + "rescale_layout", + "rescale_layout_dict", + "shell_layout", + "spring_layout", + "spectral_layout", + "planar_layout", + "fruchterman_reingold_layout", + "spiral_layout", + "multipartite_layout", + "bfs_layout", + "arf_layout", +] + +_FloatArrayLike1D: TypeAlias = ArrayLike1D[float, np.number[Any]] # Any because we don't care about the bit base + +def random_layout( + G: Graph[_Node, _NodeData, _EdgeData], + center: _FloatArrayLike1D | None = None, + dim: int = 2, + seed: Seed | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float32]]: ... +def circular_layout( + G: Graph[_Node, _NodeData, _EdgeData], + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def shell_layout( + G: Graph[_Node, _NodeData, _EdgeData], + nlist: Collection[Collection[_Node]] | None = None, + rotate: float | None = None, + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def bipartite_layout( + G: Graph[_Node, _NodeData, _EdgeData], + nodes: Collection[_Node] | None = None, + align: Literal["vertical", "horizontal"] = "vertical", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + aspect_ratio: float = ..., + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def spring_layout( + G: Graph[_Node, _NodeData, _EdgeData], + k: float | None = None, + pos: Mapping[_Node, Collection[float]] | None = None, + fixed: Collection[_Node] | None = None, + iterations: int = 50, + threshold: float = 0.0001, + weight: str | None = "weight", + scale: float | None = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + seed: Seed | None = None, + store_pos_as: str | None = None, + *, + method: Literal["auto", "force", "energy"] = "auto", + gravity: float = 1.0, +) -> dict[_Node, Array1D[np.float64]]: ... + +fruchterman_reingold_layout = spring_layout + +def kamada_kawai_layout( + G: Graph[_Node, _NodeData, _EdgeData], + dist: Mapping[_Node, Mapping[_Node, float]] | None = None, + pos: Mapping[_Node, Collection[float]] | None = None, + weight: str | None = "weight", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def spectral_layout( + G: Graph[_Node, _NodeData, _EdgeData], + weight: str | None = "weight", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def planar_layout( + G: Graph[_Node, _NodeData, _EdgeData], + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def spiral_layout( + G: Graph[_Node, _NodeData, _EdgeData], + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + resolution: float = 0.35, + equidistant: bool = False, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def multipartite_layout( + G: Graph[_Node, _NodeData, _EdgeData], + subset_key: str | Mapping[Any, Collection[_Node]] = "subset", # layers can be "any" hashable + align: Literal["vertical", "horizontal"] = "vertical", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def arf_layout( + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]] | None = None, + scaling: float = 1, + a: float = 1.1, + etol: float = 1e-06, + dt: float = 0.001, + max_iter: int = 1000, + *, + seed: Seed | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float32]]: ... +@_dispatchable +def forceatlas2_layout( + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]] | None = None, + *, + max_iter: int = 100, + jitter_tolerance: float = 1.0, + scaling_ratio: float = 2.0, + gravity: float = 1.0, + distributed_action: bool = False, + strong_gravity: bool = False, + node_mass: Mapping[_Node, float] | None = None, + node_size: Mapping[_Node, float] | None = None, + weight: str | None = None, + linlog: bool = False, + seed: Seed | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float32]]: ... +def rescale_layout(pos: NDArray[np.number[Any]], scale: float = 1) -> Array2D[np.float64]: ... # ignore the bit base +def rescale_layout_dict(pos: Mapping[_Node, Collection[float]], scale: float = 1) -> dict[_Node, Array1D[np.float64]]: ... +def bfs_layout( + G: Graph[_Node, _NodeData, _EdgeData], + start: _Node, + *, + align: Literal["vertical", "horizontal"] = "vertical", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... diff --git a/stubs/networkx/networkx/drawing/nx_agraph.pyi b/stubs/networkx/networkx/drawing/nx_agraph.pyi new file mode 100644 index 000000000000..86699adf1287 --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_agraph.pyi @@ -0,0 +1,46 @@ +from _typeshed import OpenBinaryModeUpdating, OpenTextModeReading, OpenTextModeWriting, SupportsWrite +from collections.abc import Callable +from typing import IO, Any, Protocol, TypeVar, type_check_only + +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable +from pygraphviz.agraph import AGraph # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + +__all__ = ["from_agraph", "to_agraph", "write_dot", "read_dot", "graphviz_layout", "pygraphviz_layout", "view_pygraphviz"] + +_ModeT_contra = TypeVar("_ModeT_contra", bound=str, contravariant=True) +_FileT_co = TypeVar("_FileT_co", covariant=True) + +@type_check_only +class _SupportsOpen(Protocol[_ModeT_contra, _FileT_co]): + def open(self, *, mode: _ModeT_contra) -> _FileT_co: ... + +@_dispatchable +def from_agraph( + A: AGraph, create_using: Graph[str] | type[Graph[str]] | None = None # TODO: add overloads on `create_using` +) -> Graph[str]: ... +def to_agraph(N: Graph[_Node, _NodeData, _EdgeData]) -> AGraph: ... +def write_dot( + G: Graph[_Node, _NodeData, _EdgeData], + path: str | IO[str] | IO[bytes] | _SupportsOpen[OpenTextModeWriting, IO[str] | IO[bytes]], +) -> None: ... +@_dispatchable +def read_dot(path: str | IO[str] | IO[bytes] | _SupportsOpen[OpenTextModeReading, IO[str] | IO[bytes]]) -> Graph[str]: ... +def graphviz_layout( + G: Graph[_Node, _NodeData, _EdgeData], prog: str = "neato", root: str | None = None, args: str = "" +) -> dict[_Node, tuple[float, float]]: ... +def pygraphviz_layout( + G: Graph[_Node, _NodeData, _EdgeData], prog: str = "neato", root: str | None = None, args: str = "" +) -> dict[_Node, tuple[float, float]]: ... +def view_pygraphviz( + G: Graph[_Node, _NodeData, _EdgeData], + # From implementation looks like Callable could return object since it's always immediately stringified + # But judging by documentation this seems like an extra runtime safety thing and not intended + # Leaving as str unless anyone reports a valid use-case + edgelabel: str | Callable[[dict[str, Any]], str] | None = None, + prog: str = "dot", + args: str = "", + suffix: str = "", + path: str | SupportsWrite[bytes] | _SupportsOpen[OpenBinaryModeUpdating, SupportsWrite[bytes]] | None = None, + show: bool = True, +) -> tuple[str, AGraph]: ... diff --git a/stubs/networkx/networkx/drawing/nx_latex.pyi b/stubs/networkx/networkx/drawing/nx_latex.pyi new file mode 100644 index 000000000000..25bb12bbb67a --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_latex.pyi @@ -0,0 +1,72 @@ +from _typeshed import StrPath, SupportsWrite +from collections.abc import Collection +from typing import Any, TypeAlias, TypeVar + +from networkx.classes.graph import Graph, _Node + +__all__ = ["to_latex_raw", "to_latex", "write_latex"] + +# The node and edge data types are not bound here: `_NodeData` and `_EdgeData` have +# defaults, so they could not precede `_PosT`, which has none, in the type parameter list. +# runtime requires a dict but it doesn't mutate it, we use a bounded typevar as +# a values type to make type checkers treat the dict covariantely +_PosT = TypeVar("_PosT", bound=Collection[float] | str) +_Pos: TypeAlias = str | dict[_Node, _PosT] + +def to_latex_raw( + G: Graph[_Node, Any, Any], + pos: _Pos[_Node, _PosT] = "pos", + tikz_options: str = "", + default_node_options: str = "", + node_options: str | dict[_Node, str] = "node_options", + node_label: str | dict[_Node, str] = "label", + default_edge_options: str = "", + edge_options: str | dict[tuple[_Node, _Node], str] = "edge_options", + edge_label: str | dict[tuple[_Node, _Node], str] = "label", + edge_label_options: str | dict[tuple[_Node, _Node], str] = "edge_label_options", +) -> str: ... +def to_latex( + Gbunch: Graph[_Node, Any, Any] | Collection[Graph[_Node, Any, Any]], + pos: _Pos[_Node, _PosT] | Collection[_Pos[_Node, _PosT]] = "pos", + tikz_options: str = "", + default_node_options: str = "", + node_options: str | dict[_Node, str] = "node_options", + node_label: str | dict[_Node, str] = "node_label", + default_edge_options: str = "", + edge_options: str | dict[tuple[_Node, _Node], str] = "edge_options", + edge_label: str | dict[tuple[_Node, _Node], str] = "edge_label", + edge_label_options: str | dict[tuple[_Node, _Node], str] = "edge_label_options", + caption: str = "", + latex_label: str = "", + sub_captions: Collection[str] | None = None, + sub_labels: Collection[str] | None = None, + n_rows: int = 1, + as_document: bool = True, + document_wrapper: str = ..., + figure_wrapper: str = ..., + subfigure_wrapper: str = ..., +) -> str: ... +def write_latex( + Gbunch: Graph[_Node, Any, Any] | Collection[Graph[_Node, Any, Any]], + path: StrPath | SupportsWrite[str], + *, + # **options passed to `to_latex` + pos: _Pos[_Node, _PosT] | Collection[_Pos[_Node, _PosT]] = "pos", + tikz_options: str = "", + default_node_options: str = "", + node_options: str | dict[_Node, str] = "node_options", + node_label: str | dict[_Node, str] = "node_label", + default_edge_options: str = "", + edge_options: str | dict[tuple[_Node, _Node], str] = "edge_options", + edge_label: str | dict[tuple[_Node, _Node], str] = "edge_label", + edge_label_options: str | dict[tuple[_Node, _Node], str] = "edge_label_options", + caption: str = "", + latex_label: str = "", + sub_captions: Collection[str] | None = None, + sub_labels: Collection[str] | None = None, + n_rows: int = 1, + as_document: bool = True, + document_wrapper: str = ..., + figure_wrapper: str = ..., + subfigure_wrapper: str = ..., +) -> None: ... diff --git a/stubs/networkx/networkx/drawing/nx_pydot.pyi b/stubs/networkx/networkx/drawing/nx_pydot.pyi new file mode 100644 index 000000000000..14b80b77bb2c --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_pydot.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsRead, SupportsWrite +from os import PathLike +from typing import Any + +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable +from pydot import Dot # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + +__all__ = ["write_dot", "read_dot", "graphviz_layout", "pydot_layout", "to_pydot", "from_pydot"] + +def write_dot(G: Graph[_Node, _NodeData, _EdgeData], path: str | PathLike[Any] | SupportsWrite[str]) -> None: ... +@_dispatchable +def read_dot(path: str | PathLike[Any] | SupportsRead[str]) -> Graph[str]: ... +@_dispatchable +def from_pydot(P: Dot) -> Graph[str]: ... +def to_pydot(N: Graph[_Node, _NodeData, _EdgeData]) -> Dot: ... +def graphviz_layout( + G: Graph[_Node, _NodeData, _EdgeData], prog: str = "neato", root: _Node | None = None +) -> dict[_Node, tuple[float, float]]: ... +def pydot_layout( + G: Graph[_Node, _NodeData, _EdgeData], prog: str = "neato", root: _Node | None = None +) -> dict[_Node, tuple[float, float]]: ... diff --git a/stubs/networkx/networkx/drawing/nx_pylab.pyi b/stubs/networkx/networkx/drawing/nx_pylab.pyi new file mode 100644 index 000000000000..5d0102713220 --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_pylab.pyi @@ -0,0 +1,408 @@ +from _typeshed import Incomplete, SupportsItems +from collections.abc import Callable, Collection, Hashable, Iterable, Mapping, Sequence +from typing import Any, Generic, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +import numpy as np +from matplotlib.axes import Axes # type: ignore[import-not-found] +from matplotlib.collections import LineCollection, PathCollection # type: ignore[import-not-found] +from matplotlib.colors import Colormap # type: ignore[import-not-found] +from matplotlib.patches import FancyArrowPatch # type: ignore[import-not-found] +from matplotlib.text import Text # type: ignore[import-not-found] +from matplotlib.typing import ColorType # type: ignore[import-not-found] +from networkx._typing import Array2D +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData + +__all__ = [ + "display", + "apply_matplotlib_colors", + "draw", + "draw_networkx", + "draw_networkx_nodes", + "draw_networkx_edges", + "draw_networkx_labels", + "draw_networkx_edge_labels", + "draw_bipartite", + "draw_circular", + "draw_kamada_kawai", + "draw_random", + "draw_spectral", + "draw_spring", + "draw_planar", + "draw_shell", + "draw_forceatlas2", +] + +_G = TypeVar("_G", bound=Graph[Any, Any, Any]) + +# types from matplotlib +_FontSize: TypeAlias = Literal["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"] | float +_FontWeight: TypeAlias = ( + Literal[ + "ultralight", + "light", + "normal", + "regular", + "book", + "medium", + "roman", + "semibold", + "demibold", + "demi", + "bold", + "heavy", + "extra bold", + "black", + ] + | int +) +_HAlign: TypeAlias = Literal["left", "center", "right"] +_VAlign: TypeAlias = Literal["baseline", "bottom", "center", "center_baseline", "top"] + +@type_check_only +class _DrawNetworkxKwds(TypedDict, Generic[_Node], total=False): + # draw nodes keywords; keep in sync with draw_networkx_nodes + node_color: ColorType | Collection[ColorType] | Collection[float] + cmap: str | Colormap | None + vmin: float | None + vmax: float | None + linewidths: float | Collection[float] | None + edgecolors: Literal["face", "none"] | ColorType | Collection[ColorType] | Collection[float] | None + margins: float | tuple[float, float] | None + # draw edges keywords; keep in sync with draw_networkx_edges + edgelist: Collection[_Node | Hashable] | None # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] + edge_color: ColorType | Collection[ColorType] + style: str | Collection[str] + arrowstyle: str | Collection[str] | None + arrowsize: float | list[int] | list[float] + edge_cmap: Colormap | None + edge_vmin: float | None + edge_vmax: float | None + connectionstyle: str | Iterable[str] + min_source_margin: int | Collection[int] + min_target_margin: int | Collection[int] + # draw labels keywords; keep in sync with draw_networkx_labels + labels: Mapping[_Node, object] | None + font_size: _FontSize | Mapping[_Node, _FontSize] + font_color: ColorType | Mapping[_Node, Colormap] + font_family: str | Mapping[_Node, str] + font_weight: _FontWeight | Mapping[_Node, _FontWeight] + bbox: dict[str, Any] | None + horizontalalignment: _HAlign + verticalalignment: _VAlign + clip_on: bool + # common keywords + nodelist: Sequence[_Node] | None + node_size: float | Collection[float] + node_shape: str + alpha: float | Collection[float] | None + label: str | None + hide_ticks: bool + +def apply_matplotlib_colors( + G: Graph[_Node, _NodeData, _EdgeData], + src_attr: str, + dest_attr: str, + map: str | Colormap, + vmin: float | None = None, + vmax: float | None = None, + nodes: bool = True, +) -> None: ... + +class CurvedArrowTextBase: + arrow: FancyArrowPatch + label_pos: float + labels_horizontal: bool + ax: Axes + x: Incomplete + y: Incomplete + angle: Incomplete + def __init__( + self, + arrow: FancyArrowPatch, + *args, + label_pos: float = 0.5, + labels_horizontal: bool = False, + ax: Axes | None = None, + **kwargs, + ) -> None: ... + def draw(self, renderer) -> None: ... + +def display( + G: _G, + canvas: Axes | None = None, + *, + pos: str | Callable[[_G], Mapping[_Node, Collection[float]]] = ..., + node_visible: str | bool = ..., + node_color: str = ..., + node_size: str | float = ..., + node_label: str | bool = ..., + node_shape: str = ..., + node_alpha: str = ..., + node_border_width: str = ..., + node_border_color: str = ..., + edge_visible: str | bool = ..., + edge_width: str | int = ..., + edge_color: str | ColorType = ..., + edge_label: str = ..., + edge_style: str = ..., + edge_alpha: str | float = ..., + arrowstyle: str = ..., + arrowsize: str | int = ..., + edge_curvature: str = ..., + edge_source_margin: str | int = ..., + edge_target_margin: str | int = ..., + hide_ticks: bool = True, +) -> _G: ... +def draw( + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]] | None = None, + ax: Axes | None = None, + *, + with_labels: bool = ..., # default depends on whether a label argument is passed + **kwds: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_networkx( + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]] | None = None, + arrows: bool | None = None, + with_labels: bool = True, + *, + ax: Axes | None = None, + **kwds: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_networkx_nodes( # keep in sync with _DrawNetworkxKwds above + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + nodelist: Collection[_Node] | None = None, + node_size: float | Collection[float] = 300, + node_color: ColorType | Collection[ColorType] | Collection[float] = "#1f78b4", + node_shape: str = "o", + alpha: float | Collection[float] | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + ax: Axes | None = None, + linewidths: float | Collection[float] | None = None, + edgecolors: Literal["face", "none"] | ColorType | Collection[ColorType] | Collection[float] | None = None, + label: str | None = None, + margins: float | tuple[float, float] | None = None, + hide_ticks: bool = True, +) -> PathCollection: ... + +@overload # arrows=None -> LineCollection if G is undirected, list[FancyArrowPatch] if G is directed +def draw_networkx_edges( # keep in sync with _DrawNetworkxKwds above + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + arrowstyle: str | Collection[str] | None = None, + arrowsize: float | list[int] | list[float] = 10, # documented as int, mpl accepts float + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + arrows: None = None, + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + connectionstyle: str | Iterable[str] = "arc3", + min_source_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + min_target_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + hide_ticks: bool = True, +) -> LineCollection | list[FancyArrowPatch]: ... +@overload # directed graph and arrows=None -> list[FancyArrowPatch] +def draw_networkx_edges( + G: DiGraph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + arrowstyle: str | Collection[str] | None = None, + arrowsize: float | list[int] | list[float] = 10, # documented as int, mpl accepts float + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + arrows: None = None, + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + connectionstyle: str | Iterable[str] = "arc3", + min_source_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + min_target_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + hide_ticks: bool = True, +) -> list[FancyArrowPatch]: ... +@overload # arrows=True -> list[FancyArrowPatch] +def draw_networkx_edges( + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + arrowstyle: str | Collection[str] | None = None, + arrowsize: float | list[int] | list[float] = 10, # documented as int, mpl accepts float + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + *, + arrows: Literal[True], + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + connectionstyle: str | Iterable[str] = "arc3", + min_source_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + min_target_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + hide_ticks: bool = True, +) -> list[FancyArrowPatch]: ... +@overload # arrows=False -> LineCollection +def draw_networkx_edges( + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + *, + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + arrows: Literal[False], + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + hide_ticks: bool = True, +) -> LineCollection: ... + +def draw_networkx_labels( # keep in sync with _DrawNetworkxKwds above + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + labels: Mapping[_Node, object] | None = None, # labels are explicitly converted to str + font_size: _FontSize | Mapping[_Node, _FontSize] = 12, + font_color: ColorType | Mapping[_Node, Colormap] = "k", + font_family: str | Mapping[_Node, str] = "sans-serif", + font_weight: _FontWeight | Mapping[_Node, _FontWeight] = "normal", + alpha: float | Mapping[_Node, float] | None = None, + bbox: dict[str, Any] | None = None, # Any comes from mpl + horizontalalignment: _HAlign = "center", # doc is wrong, doesn't really accept array + verticalalignment: _VAlign = "center", # doc is wrong, doesn't really accept array + ax: Axes | None = None, + clip_on: bool = True, + hide_ticks: bool = True, +) -> dict[_Node, Text]: ... +def draw_networkx_edge_labels( + # TODO: find a way to have a covariant list for params annotated with `something | list[Incomplete]` + G: Graph[_Node, _NodeData, _EdgeData], + pos: Mapping[_Node, Collection[float]], + edge_labels: ( + SupportsItems[ + Collection[_Node | Hashable], # (u, v, k) for multigraphs and (u, v) for simple graphs + object, # labels are explicitly converted to str and nx internally passes non-str + ] + | None + ) = None, + label_pos: float | list[Incomplete] = 0.5, + font_size: _FontSize | list[Incomplete] = 10, + font_color: ColorType | list[Incomplete] = "k", + font_family: str = "sans-serif", + font_weight: _FontWeight | list[Incomplete] = "normal", + alpha: float | list[Incomplete] | None = None, + bbox: dict[str, Any] | None = None, # Any comes from mpl + horizontalalignment: _HAlign | list[Incomplete] = "center", + verticalalignment: _VAlign | list[Incomplete] = "center", + ax: Axes | None = None, + rotate: bool | list[bool] = True, + clip_on: bool = True, + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + connectionstyle: str | Iterable[str] = "arc3", + hide_ticks: bool = True, +) -> dict[tuple[_Node, _Node] | tuple[_Node, _Node, Any], Text]: ... # Any is for multigraph key +def draw_bipartite( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_circular( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_kamada_kawai( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_random( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_spectral( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_spring( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_shell( + G: Graph[_Node, _NodeData, _EdgeData], + nlist: Collection[Collection[_Node]] | None = None, + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_planar( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_forceatlas2( + G: Graph[_Node, _NodeData, _EdgeData], + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def apply_alpha( + colors: ColorType | Collection[ColorType] | Collection[float], + alpha: float | Collection[float], + elem_list: Collection[object], # nx objects (nodes, edges, labels) but its content is not used! + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/exception.pyi b/stubs/networkx/networkx/exception.pyi new file mode 100644 index 000000000000..c1ebc86eee91 --- /dev/null +++ b/stubs/networkx/networkx/exception.pyi @@ -0,0 +1,33 @@ +__all__ = [ + "HasACycle", + "NodeNotFound", + "PowerIterationFailedConvergence", + "ExceededMaxIterations", + "AmbiguousSolution", + "NetworkXAlgorithmError", + "NetworkXException", + "NetworkXError", + "NetworkXNoCycle", + "NetworkXNoPath", + "NetworkXNotImplemented", + "NetworkXPointlessConcept", + "NetworkXUnbounded", + "NetworkXUnfeasible", +] + +class NetworkXException(Exception): ... +class NetworkXError(NetworkXException): ... +class NetworkXPointlessConcept(NetworkXException): ... +class NetworkXAlgorithmError(NetworkXException): ... +class NetworkXUnfeasible(NetworkXAlgorithmError): ... +class NetworkXNoPath(NetworkXUnfeasible): ... +class NetworkXNoCycle(NetworkXUnfeasible): ... +class HasACycle(NetworkXException): ... +class NetworkXUnbounded(NetworkXAlgorithmError): ... +class NetworkXNotImplemented(NetworkXException): ... +class NodeNotFound(NetworkXException): ... +class AmbiguousSolution(NetworkXException): ... +class ExceededMaxIterations(NetworkXException): ... + +class PowerIterationFailedConvergence(ExceededMaxIterations): + def __init__(self, num_iterations, *args, **kw) -> None: ... diff --git a/stubs/networkx/networkx/generators/__init__.pyi b/stubs/networkx/networkx/generators/__init__.pyi new file mode 100644 index 000000000000..878faee7cacc --- /dev/null +++ b/stubs/networkx/networkx/generators/__init__.pyi @@ -0,0 +1,29 @@ +from networkx.generators.atlas import * +from networkx.generators.classic import * +from networkx.generators.cographs import * +from networkx.generators.community import * +from networkx.generators.degree_seq import * +from networkx.generators.directed import * +from networkx.generators.duplication import * +from networkx.generators.ego import * +from networkx.generators.expanders import * +from networkx.generators.geometric import * +from networkx.generators.harary_graph import * +from networkx.generators.internet_as_graphs import * +from networkx.generators.intersection import * +from networkx.generators.interval_graph import * +from networkx.generators.joint_degree_seq import * +from networkx.generators.lattice import * +from networkx.generators.line import * +from networkx.generators.mycielski import * +from networkx.generators.nonisomorphic_trees import * +from networkx.generators.random_clustered import * +from networkx.generators.random_graphs import * +from networkx.generators.small import * +from networkx.generators.social import * +from networkx.generators.spectral_graph_forge import * +from networkx.generators.stochastic import * +from networkx.generators.sudoku import * +from networkx.generators.time_series import * +from networkx.generators.trees import * +from networkx.generators.triads import * diff --git a/stubs/networkx/networkx/generators/atlas.pyi b/stubs/networkx/networkx/generators/atlas.pyi new file mode 100644 index 000000000000..a17a5a5b24d8 --- /dev/null +++ b/stubs/networkx/networkx/generators/atlas.pyi @@ -0,0 +1,22 @@ +import sys +from _typeshed import Incomplete +from typing import Final + +from networkx.utils.backends import _dispatchable + +from ..classes.graph import Graph + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: + from importlib.abc import Traversable + +__all__ = ["graph_atlas", "graph_atlas_g"] + +NUM_GRAPHS: Final = 1253 +ATLAS_FILE: Final[Traversable] + +@_dispatchable +def graph_atlas(i: int) -> Graph[Incomplete]: ... +@_dispatchable +def graph_atlas_g() -> list[Graph[Incomplete]]: ... diff --git a/stubs/networkx/networkx/generators/classic.pyi b/stubs/networkx/networkx/generators/classic.pyi new file mode 100644 index 000000000000..bd070af62575 --- /dev/null +++ b/stubs/networkx/networkx/generators/classic.pyi @@ -0,0 +1,88 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes import Graph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "balanced_tree", + "barbell_graph", + "binomial_tree", + "complete_graph", + "complete_multipartite_graph", + "circular_ladder_graph", + "circulant_graph", + "cycle_graph", + "dorogovtsev_goltsev_mendes_graph", + "empty_graph", + "full_rary_tree", + "kneser_graph", + "ladder_graph", + "lollipop_graph", + "null_graph", + "path_graph", + "star_graph", + "tadpole_graph", + "trivial_graph", + "turan_graph", + "wheel_graph", +] + +@_dispatchable +def full_rary_tree( + r: int, n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def kneser_graph(n: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def balanced_tree( + r: int, h: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def barbell_graph( + m1: int, m2: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def binomial_tree(n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def complete_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def circular_ladder_graph(n, create_using=None): ... +@_dispatchable +def circulant_graph( + n: int, offsets: list[int], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def cycle_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def dorogovtsev_goltsev_mendes_graph( + n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def empty_graph( + n: Incomplete | int = 0, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + default: type[Graph[Incomplete]] = ..., +): ... +@_dispatchable +def ladder_graph(n, create_using=None): ... +@_dispatchable +def lollipop_graph(m, n, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def null_graph(create_using=None): ... +@_dispatchable +def path_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def star_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def tadpole_graph( + m, n, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete] | Incomplete: ... +@_dispatchable +def trivial_graph(create_using=None): ... +@_dispatchable +def turan_graph(n: int, r: int): ... +@_dispatchable +def wheel_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def complete_multipartite_graph(*subset_sizes) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/cographs.pyi b/stubs/networkx/networkx/generators/cographs.pyi new file mode 100644 index 000000000000..53238e9fe20a --- /dev/null +++ b/stubs/networkx/networkx/generators/cographs.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["random_cograph"] + +@_dispatchable +def random_cograph(n: int, seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/community.pyi b/stubs/networkx/networkx/generators/community.pyi new file mode 100644 index 000000000000..e3c9f38ada20 --- /dev/null +++ b/stubs/networkx/networkx/generators/community.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Collection + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "caveman_graph", + "connected_caveman_graph", + "relaxed_caveman_graph", + "random_partition_graph", + "planted_partition_graph", + "gaussian_random_partition_graph", + "ring_of_cliques", + "windmill_graph", + "stochastic_block_model", + "LFR_benchmark_graph", +] + +@_dispatchable +def caveman_graph(l: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def connected_caveman_graph(l: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def relaxed_caveman_graph(l: int, k: int, p: float, seed=None) -> Graph[Incomplete]: ... +@_dispatchable +def random_partition_graph( + sizes: list[int], p_in: float, p_out: float, seed=None, directed: bool = False +) -> DiGraph[Incomplete]: ... +@_dispatchable +def planted_partition_graph( + l: int, k: int, p_in: float, p_out: float, seed=None, directed: bool = False +) -> DiGraph[Incomplete]: ... +@_dispatchable +def gaussian_random_partition_graph( + n: int, s: float, v: float, p_in: float, p_out: float, directed: bool = False, seed=None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def ring_of_cliques(num_cliques: int, clique_size: int) -> Graph[Incomplete]: ... +@_dispatchable +def windmill_graph(n: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def stochastic_block_model( + sizes: list[int], + p: list[list[float]], + nodelist: Collection[Incomplete] | None = None, + seed=None, + directed: bool = False, + selfloops: bool = False, + sparse: bool = True, +) -> DiGraph[Incomplete]: ... +@_dispatchable +def LFR_benchmark_graph( + n: int, + tau1: float, + tau2: float, + mu: float, + average_degree: float | None = None, + min_degree: int | None = None, + max_degree: int | None = None, + min_community: int | None = None, + max_community: int | None = None, + tol: float = 1e-07, + max_iters: int = 500, + seed=None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/degree_seq.pyi b/stubs/networkx/networkx/generators/degree_seq.pyi new file mode 100644 index 000000000000..562806bed693 --- /dev/null +++ b/stubs/networkx/networkx/generators/degree_seq.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete + +from networkx.utils.backends import _dispatchable + +from ..classes.digraph import DiGraph +from ..classes.graph import Graph +from ..classes.multidigraph import MultiDiGraph +from ..classes.multigraph import MultiGraph + +__all__ = [ + "configuration_model", + "directed_configuration_model", + "expected_degree_graph", + "havel_hakimi_graph", + "directed_havel_hakimi_graph", + "degree_sequence_tree", + "random_degree_sequence_graph", +] + +@_dispatchable +def configuration_model( + deg_sequence: list[int], create_using: MultiGraph[Incomplete] | type[MultiGraph[Incomplete]] | None = None, seed=None +) -> MultiGraph[Incomplete]: ... +@_dispatchable +def directed_configuration_model( + in_degree_sequence: list[int], + out_degree_sequence: list[int], + create_using: MultiDiGraph[Incomplete] | type[MultiDiGraph[Incomplete]] | None = None, + seed=None, +) -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def expected_degree_graph(w: list[Incomplete], seed=None, selfloops: bool = True) -> Graph[Incomplete]: ... +@_dispatchable +def havel_hakimi_graph(deg_sequence: list[int], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def directed_havel_hakimi_graph( + in_deg_sequence: list[int], + out_deg_sequence: list[int], + create_using: DiGraph[Incomplete] | type[DiGraph[Incomplete]] | None = None, +) -> DiGraph[Incomplete]: ... +@_dispatchable +def degree_sequence_tree( + deg_sequence, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def random_degree_sequence_graph(sequence: list[int], seed=None, tries: int = 10) -> Graph[Incomplete]: ... + +class DegreeSequenceRandomGraph: + rng: Incomplete + degree: Incomplete + m: Incomplete + dmax: Incomplete + def __init__(self, degree, rng) -> None: ... + remaining_degree: Incomplete + graph: Incomplete + def generate(self): ... + def update_remaining(self, u, v, aux_graph=None) -> None: ... + def p(self, u, v): ... + def q(self, u, v): ... + def suitable_edge(self): ... + def phase1(self) -> None: ... + def phase2(self) -> None: ... + def phase3(self) -> None: ... diff --git a/stubs/networkx/networkx/generators/directed.pyi b/stubs/networkx/networkx/generators/directed.pyi new file mode 100644 index 000000000000..0d32d803d860 --- /dev/null +++ b/stubs/networkx/networkx/generators/directed.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +from ..classes import MultiDiGraph + +__all__ = ["gn_graph", "gnc_graph", "gnr_graph", "random_k_out_graph", "scale_free_graph"] + +@_dispatchable +def gn_graph( + n: int, kernel: Callable[..., Incomplete] | None = None, create_using: DiGraph[Incomplete] | None = None, seed=None +): ... +@_dispatchable +def gnr_graph(n: int, p: float, create_using: DiGraph[Incomplete] | type[DiGraph[Incomplete]] | None = None, seed=None): ... +@_dispatchable +def gnc_graph(n: int, create_using: DiGraph[Incomplete] | type[DiGraph[Incomplete]] | None = None, seed=None): ... +@_dispatchable +def scale_free_graph( + n: int, + alpha: float = 0.41, + beta: float = 0.54, + gamma: float = 0.05, + delta_in: float = 0.2, + delta_out: float = 0, + create_using=None, + seed=None, + initial_graph: MultiDiGraph[Incomplete] | None = None, +) -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def random_uniform_k_out_graph( + n: int, k: int, self_loops: bool = True, with_replacement: bool = True, seed=None +) -> Graph[Incomplete]: ... +@_dispatchable +def random_k_out_graph(n: int, k: int, alpha: float, self_loops: bool = True, seed=None) -> MultiDiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/duplication.pyi b/stubs/networkx/networkx/generators/duplication.pyi new file mode 100644 index 000000000000..0212e9c3b060 --- /dev/null +++ b/stubs/networkx/networkx/generators/duplication.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from networkx.utils.backends import _dispatchable + +from ..classes.graph import Graph + +__all__ = ["partial_duplication_graph", "duplication_divergence_graph"] + +@_dispatchable +def partial_duplication_graph(N: int, n: int, p: float, q: float, seed=None): ... +@_dispatchable +def duplication_divergence_graph(n: int, p: float, seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/ego.pyi b/stubs/networkx/networkx/generators/ego.pyi new file mode 100644 index 000000000000..17a15862aa1a --- /dev/null +++ b/stubs/networkx/networkx/generators/ego.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["ego_graph"] + +@_dispatchable +def ego_graph(G: Graph[_Node], n, radius: float = 1, center: bool = True, undirected: bool = False, distance=None): ... diff --git a/stubs/networkx/networkx/generators/expanders.pyi b/stubs/networkx/networkx/generators/expanders.pyi new file mode 100644 index 000000000000..72d061145a1a --- /dev/null +++ b/stubs/networkx/networkx/generators/expanders.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "margulis_gabber_galil_graph", + "chordal_cycle_graph", + "paley_graph", + "maybe_regular_expander", + "maybe_regular_expander_graph", + "is_regular_expander", + "random_regular_expander_graph", +] + +@_dispatchable +def margulis_gabber_galil_graph( + n: int, create_using: MultiGraph[Incomplete] | type[MultiGraph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def chordal_cycle_graph(p: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def paley_graph(p: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def maybe_regular_expander_graph(n: int, d: int, *, create_using=None, max_tries: int = 100, seed=None) -> Graph[Incomplete]: ... +@deprecated( + "`maybe_regular_expander` is a deprecated alias for `maybe_regular_expander_graph`. " + "Use `maybe_regular_expander_graph` instead." +) +def maybe_regular_expander(n, d, *, create_using=None, max_tries: int = 100, seed=None): ... +@_dispatchable +def is_regular_expander(G: Graph[_Node], *, epsilon: float = 0) -> bool: ... +@_dispatchable +def random_regular_expander_graph(n: int, d: int, *, epsilon=0, create_using=None, max_tries=100, seed=None): ... diff --git a/stubs/networkx/networkx/generators/geometric.pyi b/stubs/networkx/networkx/generators/geometric.pyi new file mode 100644 index 000000000000..1d12fb9c17be --- /dev/null +++ b/stubs/networkx/networkx/generators/geometric.pyi @@ -0,0 +1,78 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "geometric_edges", + "geographical_threshold_graph", + "navigable_small_world_graph", + "random_geometric_graph", + "soft_random_geometric_graph", + "thresholded_random_geometric_graph", + "waxman_graph", + "geometric_soft_configuration_graph", +] + +@_dispatchable +def geometric_edges(G: Graph[_Node], radius: float, p: float = 2) -> list[Incomplete]: ... +@_dispatchable +def random_geometric_graph( + n: int | Iterable[Incomplete], + radius: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + p: float = 2, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def soft_random_geometric_graph( + n: int | Iterable[Incomplete], + radius: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + p: float = 2, + p_dist: Callable[..., Incomplete] | None = None, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def geographical_threshold_graph( + n: int | Iterable[Incomplete], + theta: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + weight: dict[Incomplete, Incomplete] | None = None, + metric: Callable[..., Incomplete] | None = None, + p_dist: Callable[..., Incomplete] | None = None, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def waxman_graph( + n: int | Iterable[Incomplete], + beta: float = 0.4, + alpha: float = 0.1, + L: float | None = None, + domain: tuple[float, float, float, float] = (0, 0, 1, 1), + metric: Callable[..., Incomplete] | None = None, + seed=None, +) -> Graph[Incomplete]: ... + +# docstring marks p as int, but it still works with floats. So I think it's better for consistency +@_dispatchable +def navigable_small_world_graph(n: int, p: float = 1, q: int = 1, r: float = 2, dim: int = 2, seed=None): ... +@_dispatchable +def thresholded_random_geometric_graph( + n: int | Iterable[Incomplete], + radius: float, + theta: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + weight: dict[Incomplete, Incomplete] | None = None, + p: float = 2, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def geometric_soft_configuration_graph( + *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/harary_graph.pyi b/stubs/networkx/networkx/generators/harary_graph.pyi new file mode 100644 index 000000000000..bf2d609225a0 --- /dev/null +++ b/stubs/networkx/networkx/generators/harary_graph.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["hnm_harary_graph", "hkn_harary_graph"] + +@_dispatchable +def hnm_harary_graph( + n: int, m: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def hkn_harary_graph( + k: int, n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/internet_as_graphs.pyi b/stubs/networkx/networkx/generators/internet_as_graphs.pyi new file mode 100644 index 000000000000..eb120b1fd7d5 --- /dev/null +++ b/stubs/networkx/networkx/generators/internet_as_graphs.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["random_internet_as_graph"] + +def uniform_int_from_avg(a, m, seed): ... +def choose_pref_attach(degs: Mapping[Incomplete, Incomplete], seed): ... + +class AS_graph_generator: + seed: Incomplete + n_t: Incomplete + n_m: Incomplete + n_cp: Incomplete + n_c: Incomplete + d_m: Incomplete + d_cp: Incomplete + d_c: Incomplete + p_m_m: Incomplete + p_cp_m: Incomplete + p_cp_cp: Incomplete + t_m: float + t_cp: float + t_c: float + def __init__(self, n, seed) -> None: ... + G: Incomplete + def t_graph(self) -> Graph[Incomplete]: ... + def add_edge(self, i, j, kind) -> None: ... + def choose_peer_pref_attach(self, node_list): ... + def choose_node_pref_attach(self, node_list): ... + def add_customer(self, i, j) -> None: ... + def add_node(self, i, kind: str, reg2prob: float, avg_deg: float, t_edge_prob: float): ... + def add_m_peering_link(self, m, to_kind: str) -> bool: ... + def add_cp_peering_link(self, cp, to_kind: str) -> bool: ... + regions: Incomplete + def graph_regions(self, rn: int) -> None: ... + def add_peering_links(self, from_kind, to_kind) -> None: ... + customers: Incomplete + providers: Incomplete + nodes: Incomplete + def generate(self) -> Graph[Incomplete]: ... + +@_dispatchable +def random_internet_as_graph(n: int, seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/intersection.pyi b/stubs/networkx/networkx/generators/intersection.pyi new file mode 100644 index 000000000000..b631d2b1e31c --- /dev/null +++ b/stubs/networkx/networkx/generators/intersection.pyi @@ -0,0 +1,10 @@ +from networkx.utils.backends import _dispatchable + +__all__ = ["uniform_random_intersection_graph", "k_random_intersection_graph", "general_random_intersection_graph"] + +@_dispatchable +def uniform_random_intersection_graph(n: int, m: int, p: float, seed=None): ... +@_dispatchable +def k_random_intersection_graph(n: int, m: int, k: float, seed=None): ... +@_dispatchable +def general_random_intersection_graph(n: int, m: int, p: list[float], seed=None): ... diff --git a/stubs/networkx/networkx/generators/interval_graph.pyi b/stubs/networkx/networkx/generators/interval_graph.pyi new file mode 100644 index 000000000000..89857e689d47 --- /dev/null +++ b/stubs/networkx/networkx/generators/interval_graph.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["interval_graph"] + +@_dispatchable +def interval_graph(intervals: Iterable[Incomplete]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/joint_degree_seq.pyi b/stubs/networkx/networkx/generators/joint_degree_seq.pyi new file mode 100644 index 000000000000..2814dd544138 --- /dev/null +++ b/stubs/networkx/networkx/generators/joint_degree_seq.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence + +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +from ..classes.graph import Graph + +__all__ = ["is_valid_joint_degree", "is_valid_directed_joint_degree", "joint_degree_graph", "directed_joint_degree_graph"] + +@_dispatchable +def is_valid_joint_degree(joint_degrees: Mapping[int, Mapping[int, int]]) -> bool: ... +@_dispatchable +def joint_degree_graph( + joint_degrees: Mapping[int, Mapping[int, int]], seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def is_valid_directed_joint_degree( + in_degrees: Sequence[int], out_degrees: Sequence[int], nkk: Mapping[int, Mapping[int, int]] +) -> bool: ... +@_dispatchable +def directed_joint_degree_graph( + in_degrees: Sequence[int], + out_degrees: Sequence[int], + nkk: Mapping[int, Mapping[int, int]], + seed: int | RandomState | None = None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/lattice.pyi b/stubs/networkx/networkx/generators/lattice.pyi new file mode 100644 index 000000000000..1b365e7815b3 --- /dev/null +++ b/stubs/networkx/networkx/generators/lattice.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["grid_2d_graph", "grid_graph", "hypercube_graph", "triangular_lattice_graph", "hexagonal_lattice_graph"] + +@_dispatchable +def grid_2d_graph( + m, n, periodic: bool = False, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def grid_graph(dim: list[float] | tuple[float, ...] | Iterable[Incomplete], periodic: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def hypercube_graph(n: int) -> Graph[Incomplete]: ... +@_dispatchable +def triangular_lattice_graph( + m: int, + n: int, + periodic: bool = False, + with_positions: bool = True, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def hexagonal_lattice_graph( + m: int, + n: int, + periodic: bool = False, + with_positions: bool = True, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/line.pyi b/stubs/networkx/networkx/generators/line.pyi new file mode 100644 index 000000000000..a9cd56c23186 --- /dev/null +++ b/stubs/networkx/networkx/generators/line.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["line_graph", "inverse_line_graph"] + +@_dispatchable +def line_graph(G: Graph[_Node], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def inverse_line_graph(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/mycielski.pyi b/stubs/networkx/networkx/generators/mycielski.pyi new file mode 100644 index 000000000000..ba383edc6ed0 --- /dev/null +++ b/stubs/networkx/networkx/generators/mycielski.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["mycielskian", "mycielski_graph"] + +@_dispatchable +def mycielskian(G: Graph[_Node], iterations: int = 1) -> Graph[Incomplete]: ... +@_dispatchable +def mycielski_graph(n: int) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/nonisomorphic_trees.pyi b/stubs/networkx/networkx/generators/nonisomorphic_trees.pyi new file mode 100644 index 000000000000..d8bd5a19ee29 --- /dev/null +++ b/stubs/networkx/networkx/generators/nonisomorphic_trees.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.utils.backends import _dispatchable + +__all__ = ["nonisomorphic_trees", "number_of_nonisomorphic_trees"] + +@_dispatchable +def nonisomorphic_trees(order: int) -> Generator[list[Incomplete]]: ... +@_dispatchable +def number_of_nonisomorphic_trees(order: int) -> int: ... diff --git a/stubs/networkx/networkx/generators/random_clustered.pyi b/stubs/networkx/networkx/generators/random_clustered.pyi new file mode 100644 index 000000000000..3fa7ff59543b --- /dev/null +++ b/stubs/networkx/networkx/generators/random_clustered.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable +from typing import TypeVar, overload + +from networkx import MultiGraph +from networkx.classes.graph import Graph +from networkx.utils.misc import _RandomState + +_G = TypeVar("_G", bound=Graph[int]) +__all__ = ["random_clustered_graph"] + +@overload +def random_clustered_graph( + joint_degree_sequence: Iterable[tuple[int, int]], create_using: None = None, seed: _RandomState = None +) -> MultiGraph[int]: ... +@overload +def random_clustered_graph( + joint_degree_sequence: Iterable[tuple[int, int]], create_using: type[_G], seed: _RandomState = None +) -> _G: ... diff --git a/stubs/networkx/networkx/generators/random_graphs.pyi b/stubs/networkx/networkx/generators/random_graphs.pyi new file mode 100644 index 000000000000..d9e1d6c05571 --- /dev/null +++ b/stubs/networkx/networkx/generators/random_graphs.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing_extensions import deprecated + +from networkx.utils.backends import _dispatchable + +from ..classes.graph import Graph + +__all__ = [ + "fast_gnp_random_graph", + "gnp_random_graph", + "dense_gnm_random_graph", + "gnm_random_graph", + "erdos_renyi_graph", + "binomial_graph", + "newman_watts_strogatz_graph", + "watts_strogatz_graph", + "connected_watts_strogatz_graph", + "random_regular_graph", + "barabasi_albert_graph", + "dual_barabasi_albert_graph", + "extended_barabasi_albert_graph", + "powerlaw_cluster_graph", + "random_lobster", + "random_lobster_graph", + "random_shell_graph", + "random_powerlaw_tree", + "random_powerlaw_tree_sequence", + "random_kernel_graph", +] + +@_dispatchable +def fast_gnp_random_graph(n: int, p: float, seed=None, directed: bool = False, *, create_using=None): ... +@_dispatchable +def gnp_random_graph(n: int, p: float, seed=None, directed: bool = False, *, create_using=None): ... + +binomial_graph = gnp_random_graph +erdos_renyi_graph = gnp_random_graph + +@_dispatchable +def dense_gnm_random_graph(n: int, m: int, seed=None, *, create_using=None): ... +@_dispatchable +def gnm_random_graph(n: int, m: int, seed=None, directed: bool = False, *, create_using=None): ... +@_dispatchable +def newman_watts_strogatz_graph(n: int, k: int, p: float, seed=None, *, create_using=None): ... +@_dispatchable +def watts_strogatz_graph(n: int, k: int, p: float, seed=None, *, create_using=None): ... +@_dispatchable +def connected_watts_strogatz_graph(n: int, k: int, p: float, tries: int = 100, seed=None, *, create_using=None): ... +@_dispatchable +def random_regular_graph(d: int, n: int, seed=None, *, create_using=None): ... +@_dispatchable +def barabasi_albert_graph( + n: int, m: int, seed=None, initial_graph: Graph[Incomplete] | None = None, *, create_using=None +) -> Graph[Incomplete]: ... +@_dispatchable +def dual_barabasi_albert_graph( + n: int, m1: int, m2: int, p: float, seed=None, initial_graph: Graph[Incomplete] | None = None, *, create_using=None +) -> Graph[Incomplete]: ... +@_dispatchable +def extended_barabasi_albert_graph(n: int, m: int, p: float, q: float, seed=None, *, create_using=None) -> Graph[Incomplete]: ... +@_dispatchable +def powerlaw_cluster_graph(n: int, m: int, p: float, seed=None, *, create_using=None): ... +@_dispatchable +def random_lobster_graph(n: int, p1: float, p2: float, seed=None, *, create_using=None): ... +@_dispatchable +@deprecated("`random_lobster` is a deprecated alias for `random_lobster_graph`. Use `random_lobster_graph` instead.") +def random_lobster(n, p1, p2, seed=None, *, create_using=None): ... +@_dispatchable +def random_shell_graph(constructor: Iterable[tuple[int, int, float]], seed=None, *, create_using=None): ... +@_dispatchable +def random_powerlaw_tree(n: int, gamma: float = 3, seed=None, tries: int = 100, *, create_using=None): ... +@_dispatchable +def random_powerlaw_tree_sequence(n: int, gamma: float = 3, seed=None, tries: int = 100): ... +@_dispatchable +def random_kernel_graph( + n: int, + kernel_integral: Callable[..., Incomplete], + kernel_root: Callable[..., Incomplete] | None = None, + seed=None, + *, + create_using=None, +): ... diff --git a/stubs/networkx/networkx/generators/small.pyi b/stubs/networkx/networkx/generators/small.pyi new file mode 100644 index 000000000000..c440b1d46c74 --- /dev/null +++ b/stubs/networkx/networkx/generators/small.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "LCF_graph", + "bull_graph", + "chvatal_graph", + "cubical_graph", + "desargues_graph", + "diamond_graph", + "dodecahedral_graph", + "frucht_graph", + "generalized_petersen_graph", + "heawood_graph", + "hoffman_singleton_graph", + "house_graph", + "house_x_graph", + "icosahedral_graph", + "krackhardt_kite_graph", + "moebius_kantor_graph", + "octahedral_graph", + "pappus_graph", + "petersen_graph", + "sedgewick_maze_graph", + "tetrahedral_graph", + "truncated_cube_graph", + "truncated_tetrahedron_graph", + "tutte_graph", +] + +@_dispatchable +def LCF_graph(n: int, shift_list: list[Incomplete], repeats: int, create_using=None) -> Graph[Incomplete]: ... +@_dispatchable +def bull_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def chvatal_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def cubical_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def desargues_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def diamond_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def dodecahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def frucht_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def heawood_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def hoffman_singleton_graph() -> Graph[Incomplete]: ... +@_dispatchable +def house_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def house_x_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def icosahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def krackhardt_kite_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def moebius_kantor_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def octahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def pappus_graph() -> Graph[Incomplete]: ... +@_dispatchable +def petersen_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def generalized_petersen_graph(n: int, k: int, *, create_using=None) -> Graph[Incomplete]: ... +@_dispatchable +def sedgewick_maze_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def tetrahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def truncated_cube_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def truncated_tetrahedron_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def tutte_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/social.pyi b/stubs/networkx/networkx/generators/social.pyi new file mode 100644 index 000000000000..7a67b31c5c2e --- /dev/null +++ b/stubs/networkx/networkx/generators/social.pyi @@ -0,0 +1,12 @@ +from networkx.utils.backends import _dispatchable + +__all__ = ["karate_club_graph", "davis_southern_women_graph", "florentine_families_graph", "les_miserables_graph"] + +@_dispatchable +def karate_club_graph(): ... +@_dispatchable +def davis_southern_women_graph(): ... +@_dispatchable +def florentine_families_graph(): ... +@_dispatchable +def les_miserables_graph(): ... diff --git a/stubs/networkx/networkx/generators/spectral_graph_forge.pyi b/stubs/networkx/networkx/generators/spectral_graph_forge.pyi new file mode 100644 index 000000000000..2822fc3544a7 --- /dev/null +++ b/stubs/networkx/networkx/generators/spectral_graph_forge.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["spectral_graph_forge"] + +@_dispatchable +def spectral_graph_forge(G: Graph[_Node], alpha: float, transformation: str = "identity", seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/stochastic.pyi b/stubs/networkx/networkx/generators/stochastic.pyi new file mode 100644 index 000000000000..c52c2a9b19e1 --- /dev/null +++ b/stubs/networkx/networkx/generators/stochastic.pyi @@ -0,0 +1,8 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["stochastic_graph"] + +@_dispatchable +def stochastic_graph(G: DiGraph[_Node], copy: bool = True, weight: str = "weight"): ... diff --git a/stubs/networkx/networkx/generators/sudoku.pyi b/stubs/networkx/networkx/generators/sudoku.pyi new file mode 100644 index 000000000000..89a44087d4be --- /dev/null +++ b/stubs/networkx/networkx/generators/sudoku.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["sudoku_graph"] + +@_dispatchable +def sudoku_graph(n: int = 3) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/time_series.pyi b/stubs/networkx/networkx/generators/time_series.pyi new file mode 100644 index 000000000000..aa9a3b755384 --- /dev/null +++ b/stubs/networkx/networkx/generators/time_series.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Sequence + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["visibility_graph"] + +@_dispatchable +def visibility_graph(series: Sequence[float]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/trees.pyi b/stubs/networkx/networkx/generators/trees.pyi new file mode 100644 index 000000000000..eb63cdb49e94 --- /dev/null +++ b/stubs/networkx/networkx/generators/trees.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +from ..classes.digraph import DiGraph + +__all__ = [ + "prefix_tree", + "prefix_tree_recursive", + "random_labeled_tree", + "random_labeled_rooted_tree", + "random_labeled_rooted_forest", + "random_unlabeled_tree", + "random_unlabeled_rooted_tree", + "random_unlabeled_rooted_forest", +] + +@_dispatchable +def prefix_tree(paths: Iterable[Incomplete]) -> DiGraph[Incomplete]: ... +@_dispatchable +def prefix_tree_recursive(paths: Iterable[Incomplete]) -> DiGraph[Incomplete]: ... +@_dispatchable +def random_labeled_tree(n: int, *, seed=None): ... +@_dispatchable +def random_labeled_rooted_tree(n: int, *, seed=None) -> Graph[Incomplete]: ... +@_dispatchable +def random_unlabeled_rooted_tree(n: int, *, number_of_trees=None, seed=None) -> Incomplete | list[Incomplete]: ... +@_dispatchable +def random_labeled_rooted_forest(n: int, *, seed=None) -> Graph[Incomplete]: ... +@_dispatchable +def random_unlabeled_rooted_forest(n: int, *, q=None, number_of_forests=None, seed=None) -> Incomplete | list[Incomplete]: ... +@_dispatchable +def random_unlabeled_tree(n: int, *, number_of_trees=None, seed=None) -> Incomplete | list[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/triads.pyi b/stubs/networkx/networkx/generators/triads.pyi new file mode 100644 index 000000000000..66fb47f93757 --- /dev/null +++ b/stubs/networkx/networkx/generators/triads.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing import Final + +from networkx import DiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["triad_graph"] + +TRIAD_EDGES: Final[dict[str, list[str]]] + +@_dispatchable +def triad_graph(triad_name: str) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/lazy_imports.pyi b/stubs/networkx/networkx/lazy_imports.pyi new file mode 100644 index 000000000000..f806469927aa --- /dev/null +++ b/stubs/networkx/networkx/lazy_imports.pyi @@ -0,0 +1,14 @@ +import types +from _typeshed import Incomplete + +__all__ = ["attach", "_lazy_import"] + +def attach( + module_name: str, submodules: set[Incomplete] | None = None, submod_attrs: dict[Incomplete, Incomplete] | None = None +): ... + +class DelayedImportErrorModule(types.ModuleType): + def __init__(self, frame_data, *args, **kwargs) -> None: ... + def __getattr__(self, x) -> None: ... + +def _lazy_import(fullname: str) -> types.ModuleType | DelayedImportErrorModule: ... diff --git a/stubs/networkx/networkx/linalg/__init__.pyi b/stubs/networkx/networkx/linalg/__init__.pyi new file mode 100644 index 000000000000..af8d23d18616 --- /dev/null +++ b/stubs/networkx/networkx/linalg/__init__.pyi @@ -0,0 +1,15 @@ +from networkx.linalg import ( + attrmatrix as attrmatrix, + bethehessianmatrix as bethehessianmatrix, + graphmatrix as graphmatrix, + laplacianmatrix as laplacianmatrix, + modularitymatrix as modularitymatrix, + spectrum as spectrum, +) +from networkx.linalg.algebraicconnectivity import * +from networkx.linalg.attrmatrix import * +from networkx.linalg.bethehessianmatrix import * +from networkx.linalg.graphmatrix import * +from networkx.linalg.laplacianmatrix import * +from networkx.linalg.modularitymatrix import * +from networkx.linalg.spectrum import * diff --git a/stubs/networkx/networkx/linalg/algebraicconnectivity.pyi b/stubs/networkx/networkx/linalg/algebraicconnectivity.pyi new file mode 100644 index 000000000000..3ff0fd053a4d --- /dev/null +++ b/stubs/networkx/networkx/linalg/algebraicconnectivity.pyi @@ -0,0 +1,45 @@ +from typing import Literal + +import numpy as np +from networkx._typing import Array1D, Seed +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["algebraic_connectivity", "fiedler_vector", "spectral_ordering", "spectral_bisection"] + +@_dispatchable +def algebraic_connectivity( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> float: ... +@_dispatchable +def fiedler_vector( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> Array1D[np.float64]: ... +@_dispatchable +def spectral_ordering( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> list[_Node]: ... +@_dispatchable +def spectral_bisection( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> tuple[set[_Node], set[_Node]]: ... diff --git a/stubs/networkx/networkx/linalg/attrmatrix.pyi b/stubs/networkx/networkx/linalg/attrmatrix.pyi new file mode 100644 index 000000000000..90b19c231e4d --- /dev/null +++ b/stubs/networkx/networkx/linalg/attrmatrix.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Collection +from typing import Any, Literal + +from networkx._typing import Array2D +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.typing import DTypeLike +from scipy.sparse import lil_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = ["attr_matrix", "attr_sparse_matrix"] + +@_dispatchable +def attr_matrix( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, # runtime also accepts `Callable[[_Node], object]`, but it is not documented + normalized: bool = False, # runtime also accepts `Callable[[_Node, _Node], object]`, but it is not documented + rc_order: Collection[_Node] | None = None, + dtype: DTypeLike | None = None, + order: Literal["C", "F"] | None = None, + # TODO: overload on rc_order and node_attr + # (rc_order:[node], node_attr:None) -> 2D-array + # (rc_order:[any], node_attr:str) -> 2D-array + # (rc_order:None, node_attr:None) -> (2D-array, list[node]) + # (rc_order:None, node_attr:str) -> (2D-array, list[any]) +) -> Array2D[Incomplete] | tuple[Array2D[Incomplete], list[_Node] | list[Any]]: ... +@_dispatchable +def attr_sparse_matrix( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, # runtime also accepts `Callable[[_Node], object]`, but it is not documented + normalized: bool = False, # runtime also accepts `Callable[[_Node, _Node], object]`, but it is not documented + rc_order: Collection[_Node] | None = None, + dtype: DTypeLike | None = None, + # TODO: overload on rc_order and node_attr + # (rc_order:[node], node_attr:None) -> lil_array + # (rc_order:[any], node_attr:str) -> lil_array + # (rc_order:None, node_attr:None) -> (lil_array, list[node]) + # (rc_order:None, node_attr:str) -> (lil_array, list[any]) +) -> lil_array | tuple[lil_array, list[_Node] | list[Any]]: ... diff --git a/stubs/networkx/networkx/linalg/bethehessianmatrix.pyi b/stubs/networkx/networkx/linalg/bethehessianmatrix.pyi new file mode 100644 index 000000000000..6cc9100b9870 --- /dev/null +++ b/stubs/networkx/networkx/linalg/bethehessianmatrix.pyi @@ -0,0 +1,10 @@ +from collections.abc import Collection + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from scipy.sparse import csr_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = ["bethe_hessian_matrix"] + +@_dispatchable +def bethe_hessian_matrix(G: Graph[_Node], r: float | None = None, nodelist: Collection[_Node] | None = None) -> csr_array: ... diff --git a/stubs/networkx/networkx/linalg/graphmatrix.pyi b/stubs/networkx/networkx/linalg/graphmatrix.pyi new file mode 100644 index 000000000000..7d08761770d7 --- /dev/null +++ b/stubs/networkx/networkx/linalg/graphmatrix.pyi @@ -0,0 +1,31 @@ +from collections.abc import Collection, Hashable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.typing import DTypeLike +from scipy.sparse import csc_array, csr_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = ["incidence_matrix", "adjacency_matrix"] + +@_dispatchable +def incidence_matrix( + G: Graph[_Node], + nodelist: Collection[_Node] | None = None, + edgelist: ( + Collection[ + # Requiring tuples to represent an edge might be too strict as runtime does not check the type of + # the collection. We can replace the tuples by `Collection[_Node | Hashable]` if people complain. + tuple[_Node, _Node] # for normal graphs, this is (u, v) + | tuple[_Node, _Node, Hashable] # for multigraphs, this is (u, v, key) + ] + | None + ) = None, + oriented: bool = False, + weight: str | None = None, + *, + dtype: DTypeLike | None = None, +) -> csc_array: ... +@_dispatchable +def adjacency_matrix( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, dtype: DTypeLike | None = None, weight: str | None = "weight" +) -> csr_array: ... diff --git a/stubs/networkx/networkx/linalg/laplacianmatrix.pyi b/stubs/networkx/networkx/linalg/laplacianmatrix.pyi new file mode 100644 index 000000000000..089d31900cfb --- /dev/null +++ b/stubs/networkx/networkx/linalg/laplacianmatrix.pyi @@ -0,0 +1,39 @@ +from collections.abc import Collection +from typing import Literal + +import numpy as np +from networkx._typing import Array2D +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from scipy.sparse import csr_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = [ + "laplacian_matrix", + "normalized_laplacian_matrix", + "directed_laplacian_matrix", + "directed_combinatorial_laplacian_matrix", +] + +@_dispatchable +def laplacian_matrix(G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = "weight") -> csr_array: ... +@_dispatchable +def normalized_laplacian_matrix( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = "weight" +) -> csr_array: ... +@_dispatchable +def directed_laplacian_matrix( + G: DiGraph[_Node], + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + walk_type: Literal["random", "lazy", "pagerank"] | None = None, + alpha: float = 0.95, +) -> Array2D[np.float64]: ... +@_dispatchable +def directed_combinatorial_laplacian_matrix( + G: DiGraph[_Node], + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + walk_type: Literal["random", "lazy", "pagerank"] | None = None, + alpha: float = 0.95, +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/linalg/modularitymatrix.pyi b/stubs/networkx/networkx/linalg/modularitymatrix.pyi new file mode 100644 index 000000000000..d7537db42afc --- /dev/null +++ b/stubs/networkx/networkx/linalg/modularitymatrix.pyi @@ -0,0 +1,18 @@ +from collections.abc import Collection + +import numpy as np +from networkx._typing import Array2D +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["modularity_matrix", "directed_modularity_matrix"] + +@_dispatchable +def modularity_matrix( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = None +) -> Array2D[np.float64]: ... +@_dispatchable +def directed_modularity_matrix( + G: DiGraph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = None +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/linalg/spectrum.pyi b/stubs/networkx/networkx/linalg/spectrum.pyi new file mode 100644 index 000000000000..05e4455eb7da --- /dev/null +++ b/stubs/networkx/networkx/linalg/spectrum.pyi @@ -0,0 +1,23 @@ +import numpy as np +from networkx._typing import Array1D +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "laplacian_spectrum", + "adjacency_spectrum", + "modularity_spectrum", + "normalized_laplacian_spectrum", + "bethe_hessian_spectrum", +] + +@_dispatchable +def laplacian_spectrum(G: Graph[_Node], weight: str | None = "weight") -> Array1D[np.float64]: ... +@_dispatchable +def normalized_laplacian_spectrum(G: Graph[_Node], weight: str | None = "weight") -> Array1D[np.float64]: ... +@_dispatchable +def adjacency_spectrum(G: Graph[_Node], weight: str | None = "weight") -> Array1D[np.complex128]: ... +@_dispatchable +def modularity_spectrum(G: Graph[_Node]) -> Array1D[np.complex128]: ... +@_dispatchable +def bethe_hessian_spectrum(G: Graph[_Node], r: float | None = None) -> Array1D[np.float64]: ... diff --git a/stubs/networkx/networkx/readwrite/__init__.pyi b/stubs/networkx/networkx/readwrite/__init__.pyi new file mode 100644 index 000000000000..038e3613e9c3 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/__init__.pyi @@ -0,0 +1,12 @@ +from networkx.readwrite.adjlist import * +from networkx.readwrite.edgelist import * +from networkx.readwrite.gexf import * +from networkx.readwrite.gml import * +from networkx.readwrite.graph6 import * +from networkx.readwrite.graphml import * +from networkx.readwrite.json_graph import * +from networkx.readwrite.leda import * +from networkx.readwrite.multiline_adjlist import * +from networkx.readwrite.pajek import * +from networkx.readwrite.sparse6 import * +from networkx.readwrite.text import * diff --git a/stubs/networkx/networkx/readwrite/adjlist.pyi b/stubs/networkx/networkx/readwrite/adjlist.pyi new file mode 100644 index 000000000000..f416e8f891f4 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/adjlist.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["generate_adjlist", "write_adjlist", "parse_adjlist", "read_adjlist"] + +def generate_adjlist(G: Graph[_Node], delimiter: str = " ") -> Generator[str]: ... +def write_adjlist( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], comments: str = "#", delimiter: str = " ", encoding: str = "utf-8" +) -> None: ... +@_dispatchable +def parse_adjlist( + lines: Iterable[str], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_adjlist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/edgelist.pyi b/stubs/networkx/networkx/readwrite/edgelist.pyi new file mode 100644 index 000000000000..8c2983fc3efc --- /dev/null +++ b/stubs/networkx/networkx/readwrite/edgelist.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "generate_edgelist", + "write_edgelist", + "parse_edgelist", + "read_edgelist", + "read_weighted_edgelist", + "write_weighted_edgelist", +] + +def generate_edgelist(G: Graph[_Node], delimiter: str = " ", data: bool = True) -> Generator[Incomplete]: ... +def write_edgelist( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + comments: str = "#", + delimiter: str = " ", + data: bool = True, + encoding: str = "utf-8", +) -> None: ... +@_dispatchable +def parse_edgelist( + lines: Iterable[str], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + data: bool = True, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_edgelist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype=None, + data: bool = True, + edgetype=None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... +def write_weighted_edgelist( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], comments: str = "#", delimiter: str = " ", encoding: str = "utf-8" +) -> None: ... +@_dispatchable +def read_weighted_edgelist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype=None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/gexf.pyi b/stubs/networkx/networkx/readwrite/gexf.pyi new file mode 100644 index 000000000000..bebb998dfe93 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/gexf.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["write_gexf", "read_gexf", "relabel_gexf_graph", "generate_gexf"] + +def write_gexf( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + encoding: str = "utf-8", + prettyprint: bool = True, + version: str = "1.2draft", +) -> None: ... +def generate_gexf( + G: Graph[_Node], encoding: str = "utf-8", prettyprint: bool = True, version: str = "1.2draft" +) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def read_gexf( + path: StrPath | SupportsRead[bytes], + node_type: type[Incomplete] | None = None, + relabel: bool = False, + version: str = "1.2draft", +) -> Graph[Incomplete]: ... + +class GEXF: + versions: Incomplete + xml_type: Incomplete + python_type: Incomplete + def construct_types(self) -> None: ... + convert_bool: Final[dict[Literal["true", "false", "True", "False", "0", 0, "1", 1], bool]] + NS_GEXF: Incomplete + NS_VIZ: Incomplete + NS_XSI: Incomplete + SCHEMALOCATION: Incomplete + VERSION: Incomplete + version: Incomplete + def set_version(self, version) -> None: ... + +class GEXFWriter(GEXF): + prettyprint: Incomplete + encoding: Incomplete + xml: Incomplete + edge_id: Incomplete + attr_id: Incomplete + all_edge_ids: Incomplete + attr: Incomplete + def __init__(self, graph=None, encoding: str = "utf-8", prettyprint: bool = True, version: str = "1.2draft") -> None: ... + graph_element: Incomplete + def add_graph(self, G: Graph[_Node]) -> None: ... + def add_nodes(self, G: Graph[_Node], graph_element) -> None: ... + def add_edges(self, G: Graph[_Node], graph_element) -> None: ... + def add_attributes(self, node_or_edge, xml_obj, data, default): ... + def get_attr_id(self, title, attr_type, edge_or_node, default, mode): ... + def add_viz(self, element, node_data): ... + def add_parents(self, node_element, node_data): ... + def add_slices(self, node_or_edge_element, node_or_edge_data): ... + def add_spells(self, node_or_edge_element, node_or_edge_data): ... + def alter_graph_mode_timeformat(self, start_or_end) -> None: ... + def write(self, fh) -> None: ... + def indent(self, elem, level: int = 0) -> None: ... + +class GEXFReader(GEXF): + node_type: Incomplete + simple_graph: bool + def __init__(self, node_type=None, version: str = "1.2draft") -> None: ... + xml: Incomplete + def __call__(self, stream): ... + timeformat: Incomplete + def make_graph(self, graph_xml): ... + def add_node(self, G: Graph[_Node], node_xml, node_attr, node_pid=None) -> None: ... + def add_start_end(self, data, xml): ... + def add_viz(self, data, node_xml): ... + def add_parents(self, data, node_xml): ... + def add_slices(self, data, node_or_edge_xml): ... + def add_spells(self, data, node_or_edge_xml): ... + def add_edge(self, G: Graph[_Node], edge_element, edge_attr) -> None: ... + def decode_attr_elements(self, gexf_keys, obj_xml): ... + def find_gexf_attributes(self, attributes_element): ... + +def relabel_gexf_graph(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/gml.pyi b/stubs/networkx/networkx/readwrite/gml.pyi new file mode 100644 index 000000000000..3a9e321d4edf --- /dev/null +++ b/stubs/networkx/networkx/readwrite/gml.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Callable, Generator, Iterable +from enum import Enum +from typing import Final, Generic, NamedTuple, TypeVar + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_T = TypeVar("_T") + +__all__ = ["read_gml", "parse_gml", "generate_gml", "write_gml"] + +def escape(text): ... +def unescape(text): ... +def literal_destringizer(rep: str): ... +@_dispatchable +def read_gml( + path: StrPath | SupportsRead[bytes], label: str = "label", destringizer: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def parse_gml( + lines: str | Iterable[str], label: str = "label", destringizer: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... + +class Pattern(Enum): + KEYS = 0 + REALS = 1 + INTS = 2 + STRINGS = 3 + DICT_START = 4 + DICT_END = 5 + COMMENT_WHITESPACE = 6 + +class Token(NamedTuple, Generic[_T]): + category: Pattern + value: _T + line: int + position: int + +LIST_START_VALUE: Final = "_networkx_list_start" + +def parse_gml_lines(lines, label, destringizer): ... +def literal_stringizer(value) -> str: ... +def generate_gml(G: Graph[_Node], stringizer: Callable[..., Incomplete] | None = None) -> Generator[Incomplete, Incomplete]: ... +def write_gml( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], stringizer: Callable[..., Incomplete] | None = None +) -> None: ... diff --git a/stubs/networkx/networkx/readwrite/graph6.pyi b/stubs/networkx/networkx/readwrite/graph6.pyi new file mode 100644 index 000000000000..17cd91d94b58 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/graph6.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["from_graph6_bytes", "read_graph6", "to_graph6_bytes", "write_graph6"] + +@_dispatchable +def from_graph6_bytes(bytes_in: bytes) -> Graph[Incomplete]: ... +def to_graph6_bytes(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, header: bool = True): ... +@_dispatchable +def read_graph6(path: StrPath | SupportsRead[bytes]) -> Graph[Incomplete]: ... +def write_graph6( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], nodes: Iterable[Incomplete] | None = None, header: bool = True +): ... +def write_graph6_file(G: Graph[_Node], f, nodes: Iterable[Incomplete] | None = None, header: bool = True): ... +def data_to_n(data): ... +def n_to_data(n): ... diff --git a/stubs/networkx/networkx/readwrite/graphml.pyi b/stubs/networkx/networkx/readwrite/graphml.pyi new file mode 100644 index 000000000000..4beb539a4ca7 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/graphml.pyi @@ -0,0 +1,140 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "write_graphml", + "read_graphml", + "generate_graphml", + "write_graphml_xml", + "write_graphml_lxml", + "parse_graphml", + "GraphMLWriter", + "GraphMLReader", +] + +def write_graphml_xml( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute: str | None = None, +) -> None: ... +def write_graphml_lxml( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute: str | None = None, +): ... +def generate_graphml( + G: Graph[_Node], + encoding: str = "utf-8", + prettyprint: bool = True, + named_key_ids: bool = False, + edge_id_from_attribute: str | None = None, +) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def read_graphml( + path: StrPath | SupportsRead[bytes], + node_type: type[Incomplete] = ..., + edge_key_type: type[Incomplete] = ..., + force_multigraph: bool = False, +) -> Graph[Incomplete]: ... +@_dispatchable +def parse_graphml( + graphml_string: str, node_type: type[Incomplete] = ..., edge_key_type: type[Incomplete] = ..., force_multigraph: bool = False +) -> Graph[Incomplete]: ... + +class GraphML: + NS_GRAPHML: Final[str] + NS_XSI: Final[str] + NS_Y: Final[str] + SCHEMALOCATION: Final[str] + xml_type: Incomplete + python_type: Incomplete + def construct_types(self) -> None: ... + convert_bool: Final[dict[Literal["true", "false", "0", 0, "1", 1], bool]] + def get_xml_type(self, key): ... + +class GraphMLWriter(GraphML): + myElement: Incomplete + infer_numeric_types: Incomplete + prettyprint: Incomplete + named_key_ids: Incomplete + edge_id_from_attribute: Incomplete + encoding: Incomplete + xml: Incomplete + keys: Incomplete + attributes: Incomplete + attribute_types: Incomplete + def __init__( + self, + graph=None, + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute=None, + ) -> None: ... + def attr_type(self, name, scope, value): ... + def get_key(self, name, attr_type, scope, default): ... + def add_data(self, name, element_type, value, scope: str = "all", default=None): ... + def add_attributes(self, scope, xml_obj, data, default) -> None: ... + def add_nodes(self, G: Graph[_Node], graph_element) -> None: ... + def add_edges(self, G: Graph[_Node], graph_element) -> None: ... + def add_graph_element(self, G: Graph[_Node]) -> None: ... + def add_graphs(self, graph_list) -> None: ... + def dump(self, stream) -> None: ... + def indent(self, elem, level: int = 0) -> None: ... + +class IncrementalElement: + xml: Incomplete + prettyprint: Incomplete + def __init__(self, xml, prettyprint) -> None: ... + def append(self, element) -> None: ... + +class GraphMLWriterLxml(GraphMLWriter): + myElement: Incomplete + named_key_ids: Incomplete + edge_id_from_attribute: Incomplete + infer_numeric_types: Incomplete + xml: Incomplete + keys: Incomplete + attribute_types: Incomplete + def __init__( + self, + path, + graph=None, + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute=None, + ) -> None: ... + def add_graph_element(self, G: Graph[_Node]) -> None: ... + def add_attributes(self, scope, xml_obj, data, default) -> None: ... + def dump(self, stream=None) -> None: ... + +write_graphml = write_graphml_lxml + +class GraphMLReader(GraphML): + node_type: Incomplete + edge_key_type: Incomplete + multigraph: Incomplete + edge_ids: Incomplete + def __init__(self, node_type=..., edge_key_type=..., force_multigraph: bool = False) -> None: ... + xml: Incomplete + def __call__(self, path=None, string=None) -> Generator[Incomplete]: ... + def make_graph(self, graph_xml, graphml_keys, defaults, G=None): ... + def add_node(self, G: Graph[_Node], node_xml, graphml_keys, defaults) -> None: ... + def add_edge(self, G: Graph[_Node], edge_element, graphml_keys) -> None: ... + def decode_data_elements(self, graphml_keys, obj_xml): ... + def find_graphml_keys(self, graph_element): ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/__init__.pyi b/stubs/networkx/networkx/readwrite/json_graph/__init__.pyi new file mode 100644 index 000000000000..56ff476831de --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/__init__.pyi @@ -0,0 +1,4 @@ +from networkx.readwrite.json_graph.adjacency import * +from networkx.readwrite.json_graph.cytoscape import * +from networkx.readwrite.json_graph.node_link import * +from networkx.readwrite.json_graph.tree import * diff --git a/stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi b/stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi new file mode 100644 index 000000000000..e1728b1cc49f --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["adjacency_data", "adjacency_graph"] + +# Any: Complex type union +def adjacency_data(G: Graph[_Node], attrs: dict[Incomplete, Incomplete] = {"id": "id", "key": "key"}) -> dict[str, Any]: ... +@_dispatchable +def adjacency_graph( + data: dict[Incomplete, Incomplete], + directed: bool = False, + multigraph: bool = True, + attrs: dict[Incomplete, Incomplete] = {"id": "id", "key": "key"}, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi b/stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi new file mode 100644 index 000000000000..959ffb3b2ed5 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["cytoscape_data", "cytoscape_graph"] + +# Any: Complex type union +def cytoscape_data(G: Graph[_Node], name: str = "name", ident: str = "id") -> dict[str, Any]: ... +@_dispatchable +def cytoscape_graph(data: dict[Incomplete, Incomplete], name: str = "name", ident: str = "id") -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/node_link.pyi b/stubs/networkx/networkx/readwrite/json_graph/node_link.pyi new file mode 100644 index 000000000000..15c7da4e2da3 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/node_link.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["node_link_data", "node_link_graph"] + +def node_link_data( + G: Graph[_Node], + *, + source: str = "source", + target: str = "target", + name: str = "id", + key: str = "key", + edges: str = "edges", + nodes: str = "nodes", +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def node_link_graph( + data: dict[Incomplete, Incomplete], + directed: bool = False, + multigraph: bool = True, + attrs=None, + *, + source: str = "source", + target: str = "target", + name: str = "id", + key: str = "key", + edges: str = "edges", + nodes: str = "nodes", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/tree.pyi b/stubs/networkx/networkx/readwrite/json_graph/tree.pyi new file mode 100644 index 000000000000..052e8b5fb2b5 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/tree.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["tree_data", "tree_graph"] + +def tree_data(G: DiGraph[_Node], root, ident: str = "id", children: str = "children") -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def tree_graph(data: dict[Incomplete, Incomplete], ident: str = "id", children: str = "children") -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/leda.pyi b/stubs/networkx/networkx/readwrite/leda.pyi new file mode 100644 index 000000000000..ddec97493fe4 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/leda.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete, StrPath, SupportsRead +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["read_leda", "parse_leda"] + +@_dispatchable +def read_leda(path: StrPath | SupportsRead[bytes], encoding: str = "UTF-8") -> Graph[Incomplete]: ... +@_dispatchable +def parse_leda(lines: str | Iterable[str]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/multiline_adjlist.pyi b/stubs/networkx/networkx/readwrite/multiline_adjlist.pyi new file mode 100644 index 000000000000..ae269ad60fb1 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/multiline_adjlist.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["generate_multiline_adjlist", "write_multiline_adjlist", "parse_multiline_adjlist", "read_multiline_adjlist"] + +def generate_multiline_adjlist(G: Graph[_Node], delimiter: str = " ") -> Generator[str]: ... +def write_multiline_adjlist( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], delimiter: str = " ", comments: str = "#", encoding: str = "utf-8" +) -> None: ... +@_dispatchable +def parse_multiline_adjlist( + lines: Iterable[str], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + edgetype: type[Incomplete] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_multiline_adjlist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + edgetype: type[Incomplete] | None = None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/p2g.pyi b/stubs/networkx/networkx/readwrite/p2g.pyi new file mode 100644 index 000000000000..22d670a68c16 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/p2g.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete, StrPath, SupportsRead + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multidigraph import MultiDiGraph +from networkx.utils.backends import _dispatchable + +def write_p2g(G: Graph[_Node], path, encoding: str = "utf-8") -> None: ... +@_dispatchable +def read_p2g(path: StrPath | SupportsRead[str], encoding: str = "utf-8") -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def parse_p2g(lines) -> MultiDiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/pajek.pyi b/stubs/networkx/networkx/readwrite/pajek.pyi new file mode 100644 index 000000000000..efc593fb2122 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/pajek.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multidigraph import MultiDiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"] + +def generate_pajek(G: Graph[_Node]) -> Generator[Incomplete]: ... +def write_pajek(G: Graph[_Node], path: StrPath | SupportsWrite[bytes], encoding: str = "UTF-8") -> None: ... +@_dispatchable +def read_pajek(path: StrPath | SupportsRead[bytes], encoding: str = "UTF-8") -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def parse_pajek(lines: str | Iterable[str]) -> Graph[Incomplete]: ... +def make_qstr(t): ... diff --git a/stubs/networkx/networkx/readwrite/sparse6.pyi b/stubs/networkx/networkx/readwrite/sparse6.pyi new file mode 100644 index 000000000000..0e65988decab --- /dev/null +++ b/stubs/networkx/networkx/readwrite/sparse6.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["from_sparse6_bytes", "read_sparse6", "to_sparse6_bytes", "write_sparse6"] + +@_dispatchable +def from_sparse6_bytes(string: str) -> Graph[Incomplete]: ... +def to_sparse6_bytes(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, header: bool = True): ... +@_dispatchable +def read_sparse6(path: StrPath | SupportsRead[bytes]) -> MultiGraph[Incomplete]: ... +def write_sparse6( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], nodes: Iterable[Incomplete] | None = None, header: bool = True +) -> None: ... diff --git a/stubs/networkx/networkx/readwrite/text.pyi b/stubs/networkx/networkx/readwrite/text.pyi new file mode 100644 index 000000000000..9a91460b0f54 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/text.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Collection, Generator +from typing import ClassVar + +from networkx.classes.graph import Graph + +__all__ = ["generate_network_text", "write_network_text"] + +class BaseGlyphs: + @classmethod + def as_dict(cls) -> dict[str, str]: ... + +class AsciiBaseGlyphs(BaseGlyphs): + empty: ClassVar[str] + newtree_last: ClassVar[str] + newtree_mid: ClassVar[str] + endof_forest: ClassVar[str] + within_forest: ClassVar[str] + within_tree: ClassVar[str] + +class AsciiDirectedGlyphs(AsciiBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +class AsciiUndirectedGlyphs(AsciiBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +class UtfBaseGlyphs(BaseGlyphs): + empty: ClassVar[str] + newtree_last: ClassVar[str] + newtree_mid: ClassVar[str] + endof_forest: ClassVar[str] + within_forest: ClassVar[str] + within_tree: ClassVar[str] + +class UtfDirectedGlyphs(UtfBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +class UtfUndirectedGlyphs(UtfBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +def generate_network_text( + graph: Graph[Incomplete], + with_labels: bool = True, + sources: Collection[Incomplete] | None = None, + max_depth: int | None = None, + ascii_only: bool = False, + vertical_chains: bool = False, +) -> Generator[Incomplete, None, Incomplete]: ... +def write_network_text( + graph: Graph[Incomplete], + path: Callable[..., Incomplete] | None = None, + with_labels: bool = True, + sources: Collection[Incomplete] | None = None, + max_depth: int | None = None, + ascii_only: bool = False, + end: str = "\n", + vertical_chains: bool = False, +) -> None: ... diff --git a/stubs/networkx/networkx/relabel.pyi b/stubs/networkx/networkx/relabel.pyi new file mode 100644 index 000000000000..d8d2c1b608a6 --- /dev/null +++ b/stubs/networkx/networkx/relabel.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable, Hashable, Mapping +from typing import Literal, TypeVar, overload + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph +from networkx.classes.multidigraph import MultiDiGraph +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +_X = TypeVar("_X", bound=Hashable) +_Y = TypeVar("_Y", bound=Hashable) + +__all__ = ["convert_node_labels_to_integers", "relabel_nodes"] + +@overload +def relabel_nodes( + G: MultiDiGraph[_X], mapping: Mapping[_X, _Y] | Callable[[_X], _Y], copy: bool = True +) -> MultiDiGraph[_X | _Y]: ... +@overload +def relabel_nodes(G: DiGraph[_X], mapping: Mapping[_X, _Y] | Callable[[_X], _Y], copy: bool = True) -> DiGraph[_X | _Y]: ... +@overload +def relabel_nodes(G: MultiGraph[_X], mapping: Mapping[_X, _Y] | Callable[[_X], _Y], copy: bool = True) -> MultiGraph[_X | _Y]: ... +@overload +def relabel_nodes(G: Graph[_X], mapping: Mapping[_X, _Y] | Callable[[_X], _Y], copy: bool = True) -> Graph[_X | _Y]: ... + +@_dispatchable +def convert_node_labels_to_integers( + G: Graph[Hashable], + first_label: int = 0, + ordering: Literal["default", "sorted", "increasing degree", "decreasing degree"] = "default", + label_attribute: str | None = None, +) -> Graph[int]: ... diff --git a/stubs/networkx/networkx/utils/__init__.pyi b/stubs/networkx/networkx/utils/__init__.pyi new file mode 100644 index 000000000000..c615a6e8a8d1 --- /dev/null +++ b/stubs/networkx/networkx/utils/__init__.pyi @@ -0,0 +1,11 @@ +from networkx.utils.backends import * +from networkx.utils.configs import * +from networkx.utils.configs import NetworkXConfig +from networkx.utils.decorators import * +from networkx.utils.heaps import * +from networkx.utils.misc import * +from networkx.utils.random_sequence import * +from networkx.utils.rcm import * +from networkx.utils.union_find import * + +config: NetworkXConfig # Set by networkx/__init__.py diff --git a/stubs/networkx/networkx/utils/backends.pyi b/stubs/networkx/networkx/utils/backends.pyi new file mode 100644 index 000000000000..18bc3359e827 --- /dev/null +++ b/stubs/networkx/networkx/utils/backends.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from typing import Any, Final, Generic, ParamSpec, TypeVar, overload +from typing_extensions import Self + +_P = ParamSpec("_P") +_R = TypeVar("_R") +__all__ = ["_dispatchable"] +FAILED_TO_CONVERT: Final[str] + +class _dispatchable(Generic[_P, _R]): + __defaults__: Incomplete + __kwdefaults__: Incomplete + __module__: Incomplete + __qualname__: Incomplete + __wrapped__: Incomplete + orig_func: Callable[_P, _R] | None + name: str + edge_attrs: dict[str, Any] | None + node_attrs: dict[str, Any] | None + preserve_edge_attrs: bool + preserve_node_attrs: bool + preserve_graph_attrs: bool + mutates_input: bool + optional_graphs: Incomplete + list_graphs: Incomplete + graphs: dict[str, int] + backends: dict[str, Incomplete] + # Incomplete: Ignoring the case where func=None returns a partial, + # we only care about `_dispatchable` used as a static-typing decorator + def __new__( + cls, + func: Callable[_P, _R] | None = None, + *, + name: str | None = None, + graphs: str | Mapping[str, int] | None = "G", + edge_attrs: str | dict[str, Any] | None = None, + node_attrs: str | dict[str, Any] | None = None, + preserve_edge_attrs: bool = False, + preserve_node_attrs: bool = False, + preserve_graph_attrs: bool = False, + preserve_all_attrs: bool = False, + mutates_input: bool = False, + returns_graph: bool = False, + implemented_by_nx: bool = True, + ) -> Self: ... + + @property + def __doc__(self): ... + @__doc__.setter + def __doc__(self, val) -> None: ... + + @property + def __signature__(self): ... + + # Type system limitations doesn't allow us to define this as it truly should. + # But specifying backend with backend_kwargs isn't a common usecase anyway + # and specifying backend as explicitly None is possible but not intended. + # If this ever changes, update stubs/networkx/@tests/test_cases/check_dispatch_decorator.py + @overload + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + @overload + def __call__(self, *args: Any, backend: str, **backend_kwargs: Any) -> _R: ... + + # @overload + # def __call__(self, *args: _P.args, backend: None = None, **kwargs: _P.kwargs) -> _R: ... + # @overload + # def __call__(self, *args: _P.args, backend: str, **kwargs: _P.kwargs, **backend_kwargs: Any) -> _R: ... + def __reduce__(self): ... diff --git a/stubs/networkx/networkx/utils/configs.pyi b/stubs/networkx/networkx/utils/configs.pyi new file mode 100644 index 000000000000..46d843940841 --- /dev/null +++ b/stubs/networkx/networkx/utils/configs.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete +from collections.abc import Callable, ItemsView, Iterable, Iterator, KeysView, ValuesView +from dataclasses import dataclass +from types import TracebackType +from typing_extensions import Self + +__all__ = ["Config"] + +@dataclass(init=False, eq=False, slots=True, kw_only=True, match_args=False) +class Config: + def __init_subclass__(cls, strict: bool = True) -> None: ... + def __new__(cls, **kwargs) -> Self: ... + def __dir__(self) -> Iterable[str]: ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __reversed__(self) -> Iterator[str]: ... + def __getitem__(self, key: str): ... + def __setitem__(self, key: str, value) -> None: ... + def __delitem__(self, key: str) -> None: ... + def get(self, key: str, default=None): ... + def items(self) -> ItemsView[str, Incomplete]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[Incomplete]: ... + def __reduce__(self) -> tuple[Callable[..., Self], tuple[type[Self], dict[Incomplete, Incomplete]]]: ... + def __call__(self, **kwargs) -> Self: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +class NetworkXConfig(Config): + backend_priority: list[str] + backends: Config + cache_converted_graphs: bool + fallback_to_nx: bool + warnings_to_ignore: set[str] + def __init__( + self, + *, + backend_priority: list[str], + backends: Config, + cache_converted_graphs: bool, + fallback_to_nx: bool, + warnings_to_ignore: set[str], + ) -> None: ... + def __new__( + cls, + *, + backend_priority: list[str], + backends: Config, + cache_converted_graphs: bool, + fallback_to_nx: bool, + warnings_to_ignore: set[str], + ) -> Self: ... + +config: NetworkXConfig diff --git a/stubs/networkx/networkx/utils/decorators.pyi b/stubs/networkx/networkx/utils/decorators.pyi new file mode 100644 index 000000000000..66d2cd8121d5 --- /dev/null +++ b/stubs/networkx/networkx/utils/decorators.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import NamedTuple + +__all__ = ["not_implemented_for", "open_file", "nodes_or_number", "np_random_state", "py_random_state", "argmap"] + +def not_implemented_for(*graph_types) -> Callable[..., Incomplete]: ... +def open_file(path_arg: str | int, mode: str = "r") -> Callable[..., Incomplete]: ... +def nodes_or_number(which_args: str | int | Sequence[str | int]) -> Callable[..., Incomplete]: ... +def np_random_state(random_state_argument: str | int) -> Callable[..., Incomplete]: ... +def py_random_state(random_state_argument: str | int) -> Callable[..., Incomplete]: ... + +class argmap: + def __init__(self, func, *args, try_finally: bool = False) -> None: ... + def __call__(self, f) -> Callable[..., Incomplete]: ... + def compile(self, f: Callable[..., Incomplete]) -> Callable[..., Incomplete]: ... + def assemble(self, f: Callable[..., Incomplete]): ... + @classmethod + def signature(cls, f: Callable[..., Incomplete]): ... + + class Signature(NamedTuple): + name: Incomplete + signature: Incomplete + def_sig: Incomplete + call_sig: Incomplete + names: Incomplete + n_positional: Incomplete + args: Incomplete + kwargs: Incomplete diff --git a/stubs/networkx/networkx/utils/heaps.pyi b/stubs/networkx/networkx/utils/heaps.pyi new file mode 100644 index 000000000000..f03e301f9e4b --- /dev/null +++ b/stubs/networkx/networkx/utils/heaps.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +__all__ = ["MinHeap", "PairingHeap", "BinaryHeap"] + +class MinHeap: + class _Item: + __slots__ = ("key", "value") + key: Incomplete + value: Incomplete + def __init__(self, key, value) -> None: ... + + def __init__(self) -> None: ... + def min(self) -> tuple[Incomplete, Incomplete]: ... + def pop(self) -> tuple[Incomplete, Incomplete]: ... + def get(self, key, default=None): ... + def insert(self, key, value, allow_increase: bool = False) -> bool: ... + def __nonzero__(self): ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + +class PairingHeap(MinHeap): + class _Node(MinHeap._Item): + __slots__ = ("left", "next", "prev", "parent") + left: Incomplete + next: Incomplete + prev: Incomplete + parent: Incomplete + def __init__(self, key, value) -> None: ... + + def __init__(self) -> None: ... + def min(self) -> tuple[Incomplete, Incomplete]: ... + def pop(self) -> tuple[Incomplete, Incomplete]: ... + def get(self, key, default=None): ... + def insert(self, key, value, allow_increase: bool = False) -> bool: ... + +class BinaryHeap(MinHeap): + def __init__(self) -> None: ... + def min(self) -> tuple[Incomplete, Incomplete]: ... + def pop(self) -> tuple[Incomplete, Incomplete]: ... + def get(self, key, default=None): ... + def insert(self, key, value, allow_increase: bool = False) -> bool: ... diff --git a/stubs/networkx/networkx/utils/mapped_queue.pyi b/stubs/networkx/networkx/utils/mapped_queue.pyi new file mode 100644 index 000000000000..38710ddb601f --- /dev/null +++ b/stubs/networkx/networkx/utils/mapped_queue.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +__all__ = ["MappedQueue"] + +class _HeapElement: + __slots__ = ["priority", "element", "_hash"] + priority: Incomplete + element: Incomplete + def __init__(self, priority, element) -> None: ... + def __lt__(self, other): ... + def __gt__(self, other): ... + def __eq__(self, other): ... + def __hash__(self): ... + def __getitem__(self, indx): ... + def __iter__(self) -> Iterator[Incomplete]: ... + +class MappedQueue: + heap: Incomplete + position: Incomplete + def __init__(self, data=None) -> None: ... + def __len__(self) -> int: ... + def push(self, elt, priority=None): ... + def pop(self): ... + def update(self, elt, new, priority=None) -> None: ... + def remove(self, elt) -> None: ... diff --git a/stubs/networkx/networkx/utils/misc.pyi b/stubs/networkx/networkx/utils/misc.pyi new file mode 100644 index 000000000000..cc14f1bff944 --- /dev/null +++ b/stubs/networkx/networkx/utils/misc.pyi @@ -0,0 +1,61 @@ +import random +from _typeshed import Incomplete +from collections.abc import Iterable, Iterator +from types import ModuleType +from typing import TypeAlias + +import numpy +from networkx.classes.graph import Graph, _Node + +__all__ = [ + "flatten", + "make_list_of_ints", + "dict_to_numpy_array", + "arbitrary_element", + "pairwise", + "groups", + "create_random_state", + "create_py_random_state", + "PythonRandomInterface", + "PythonRandomViaNumpyBits", + "nodes_equal", + "edges_equal", + "graphs_equal", + "_clear_cache", +] + +_RandomNumberGenerator: TypeAlias = ( + ModuleType | random.Random | numpy.random.RandomState | numpy.random.Generator | PythonRandomInterface +) +_RandomState: TypeAlias = int | _RandomNumberGenerator | None + +def flatten(obj, result=None): ... +def make_list_of_ints(sequence): ... +def dict_to_numpy_array(d, mapping=None): ... +def arbitrary_element(iterable: Iterable[Incomplete]) -> Iterable[Incomplete]: ... +def pairwise(iterable: Iterable[Incomplete], cyclic: bool = False) -> Iterator[Incomplete]: ... +def groups(many_to_one): ... +def create_random_state(random_state=None): ... + +class PythonRandomViaNumpyBits(random.Random): + def __init__(self, rng: numpy.random.Generator | None = None) -> None: ... + def getrandbits(self, k: int) -> int: ... + +class PythonRandomInterface: + def __init__(self, rng=None) -> None: ... + def random(self): ... + def uniform(self, a, b): ... + def randrange(self, a, b=None): ... + def choice(self, seq): ... + def gauss(self, mu, sigma): ... + def shuffle(self, seq): ... + def sample(self, seq, k): ... + def randint(self, a, b): ... + def expovariate(self, scale): ... + def paretovariate(self, shape): ... + +def create_py_random_state(random_state: _RandomState = None): ... +def nodes_equal(nodes1, nodes2) -> bool: ... +def edges_equal(edges1, edges2, *, directed: bool = False) -> bool: ... +def graphs_equal(graph1, graph2) -> bool: ... +def _clear_cache(G: Graph[_Node]) -> None: ... diff --git a/stubs/networkx/networkx/utils/random_sequence.pyi b/stubs/networkx/networkx/utils/random_sequence.pyi new file mode 100644 index 000000000000..1092bf7ab0c0 --- /dev/null +++ b/stubs/networkx/networkx/utils/random_sequence.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +__all__ = [ + "powerlaw_sequence", + "is_valid_tree_degree_sequence", + "zipf_rv", + "cumulative_distribution", + "discrete_sequence", + "random_weighted_sample", + "weighted_choice", +] + +def powerlaw_sequence(n, exponent: float = 2.0, seed=None): ... +def is_valid_tree_degree_sequence(degree_sequence: Iterable[Incomplete]) -> tuple[bool, str]: ... +def zipf_rv(alpha: float, xmin: int = 1, seed=None) -> int: ... +def cumulative_distribution(distribution): ... +def discrete_sequence(n, distribution=None, cdistribution=None, seed=None): ... +def random_weighted_sample(mapping, k, seed=None): ... +def weighted_choice(mapping, seed=None): ... diff --git a/stubs/networkx/networkx/utils/rcm.pyi b/stubs/networkx/networkx/utils/rcm.pyi new file mode 100644 index 000000000000..0f4f4ed838e3 --- /dev/null +++ b/stubs/networkx/networkx/utils/rcm.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node + +__all__ = ["cuthill_mckee_ordering", "reverse_cuthill_mckee_ordering"] + +def cuthill_mckee_ordering( + G: Graph[_Node], heuristic: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete, Incomplete]: ... +def reverse_cuthill_mckee_ordering( + G: Graph[_Node], heuristic: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete, Incomplete, Incomplete]: ... +def connected_cuthill_mckee_ordering(G: Graph[_Node], heuristic=None): ... +def pseudo_peripheral_node(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/utils/union_find.pyi b/stubs/networkx/networkx/utils/union_find.pyi new file mode 100644 index 000000000000..1d73f4eb7b89 --- /dev/null +++ b/stubs/networkx/networkx/utils/union_find.pyi @@ -0,0 +1,13 @@ +from collections.abc import Generator, Iterable, Iterator, Mapping +from typing import Generic, TypeVar + +_T = TypeVar("_T") + +class UnionFind(Generic[_T]): + parents: Mapping[_T, _T] + weights: Mapping[_T, int] + def __init__(self, elements: Iterable[_T] | None = None) -> None: ... + def __getitem__(self, object: _T) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + def to_sets(self) -> Generator[set[_T]]: ... + def union(self, *objects: _T) -> None: ... diff --git a/stubs/oauthlib/@tests/stubtest_allowlist.txt b/stubs/oauthlib/@tests/stubtest_allowlist.txt deleted file mode 100644 index f171c31306d8..000000000000 --- a/stubs/oauthlib/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1 +0,0 @@ -oauthlib.oauth1.rfc5849.parameters.prepare_headers \ No newline at end of file diff --git a/stubs/oauthlib/METADATA.toml b/stubs/oauthlib/METADATA.toml index 84307529a94b..8350fd0e1993 100644 --- a/stubs/oauthlib/METADATA.toml +++ b/stubs/oauthlib/METADATA.toml @@ -1 +1,2 @@ -version = "3.1.*" +version = "4.0.*" +upstream-repository = "https://github.com/oauthlib/oauthlib" diff --git a/stubs/oauthlib/oauthlib/__init__.pyi b/stubs/oauthlib/oauthlib/__init__.pyi index 3440b7c13209..96a9263bbff5 100644 --- a/stubs/oauthlib/oauthlib/__init__.pyi +++ b/stubs/oauthlib/oauthlib/__init__.pyi @@ -1,2 +1,7 @@ -def set_debug(debug_val) -> None: ... -def get_debug(): ... +from typing import Final + +__author__: Final[str] +__version__: Final[str] + +def set_debug(debug_val: bool) -> None: ... +def get_debug() -> bool: ... diff --git a/stubs/oauthlib/oauthlib/common.pyi b/stubs/oauthlib/oauthlib/common.pyi index bdd765525fe8..281303f83078 100644 --- a/stubs/oauthlib/oauthlib/common.pyi +++ b/stubs/oauthlib/oauthlib/common.pyi @@ -1,56 +1,118 @@ -from typing import Any, Dict - -UNICODE_ASCII_CHARACTER_SET: str -CLIENT_ID_CHARACTER_SET: str -SANITIZE_PATTERN: Any -INVALID_HEX_PATTERN: Any -always_safe: str -log: Any - -def quote(s, safe: bytes = ...): ... -def unquote(s): ... -def urlencode(params): ... -def encode_params_utf8(params): ... -def decode_params_utf8(params): ... - -urlencoded: Any - -def urldecode(query): ... -def extract_params(raw): ... -def generate_nonce(): ... -def generate_timestamp(): ... -def generate_token(length: int = ..., chars=...): ... -def generate_signed_token(private_pem, request): ... +import re +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Iterable, Mapping +from logging import Logger +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload + +_T = TypeVar("_T") +_V = TypeVar("_V") + +_HTTPMethod: TypeAlias = Literal["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"] + +UNICODE_ASCII_CHARACTER_SET: Final[str] +CLIENT_ID_CHARACTER_SET: Final[str] +SANITIZE_PATTERN: Final[re.Pattern[str]] +INVALID_HEX_PATTERN: Final[re.Pattern[str]] +always_safe: Final[str] +log: Logger + +def quote(s: str | bytes, safe: bytes = b"/") -> str: ... +def unquote(s: str | bytes) -> str: ... +def urlencode(params: Iterable[tuple[str | bytes, str | bytes]]) -> str: ... +def encode_params_utf8(params: Iterable[tuple[str | bytes, str | bytes]]) -> list[tuple[bytes, bytes]]: ... +def decode_params_utf8(params: Iterable[tuple[str | bytes, str | bytes]]) -> list[tuple[str, str]]: ... + +urlencoded: Final[set[str]] + +def urldecode(query: str | bytes) -> list[tuple[str, str]]: ... +def extract_params(raw: str | bytes | dict[str, str] | Iterable[tuple[str, str]]) -> list[tuple[str, str]] | None: ... +def generate_nonce() -> str: ... +def generate_timestamp() -> str: ... +def generate_token(length: int = 30, chars: SupportsLenAndGetItem[str] = ...) -> str: ... +def generate_signed_token(private_pem: str, request: Request) -> str: ... def verify_signed_token(public_pem, token): ... -def generate_client_id(length: int = ..., chars=...): ... -def add_params_to_qs(query, params): ... -def add_params_to_uri(uri, params, fragment: bool = ...): ... -def safe_string_equals(a, b): ... -def to_unicode(data, encoding: str = ...): ... - -class CaseInsensitiveDict(Dict[Any, Any]): - proxy: Any - def __init__(self, data) -> None: ... - def __contains__(self, k): ... - def __delitem__(self, k) -> None: ... - def __getitem__(self, k): ... - def get(self, k, default: Any | None = ...): ... - def __setitem__(self, k, v) -> None: ... +def generate_client_id(length: int = 30, chars: SupportsLenAndGetItem[str] = ...) -> str: ... +def add_params_to_qs(query: str, params: dict[str, str] | Iterable[tuple[str, str]]) -> str: ... +def add_params_to_uri(uri: str, params: dict[str, str] | Iterable[tuple[str, str]], fragment: bool = False) -> str: ... +def safe_string_equals(a: str, b: str) -> bool: ... + +@overload +def to_unicode(data: str | bytes, encoding: str = "UTF-8") -> str: ... +@overload +def to_unicode(data: Mapping[str, _V] | Mapping[bytes, _V], encoding: str = "UTF-8") -> dict[str, _V]: ... +@overload +def to_unicode(data: _T, encoding: str = "UTF-8") -> _T: ... + +class CaseInsensitiveDict(dict[str, Incomplete]): + proxy: dict[str, str] + def __init__(self, data: dict[str, Incomplete]) -> None: ... + + @overload + def __contains__(self, k: str) -> bool: ... + @overload + def __contains__(self, k: object) -> bool: ... + + def __delitem__(self, k: str) -> None: ... + def __getitem__(self, k: str): ... + + @overload + def get(self, k: str, default: None = None) -> Incomplete | None: ... + @overload + def get(self, k: str, default): ... + + def __setitem__(self, k: str, v) -> None: ... def update(self, *args, **kwargs) -> None: ... class Request: - uri: Any - http_method: Any - headers: Any - body: Any - decoded_body: Any - oauth_params: Any - validator_log: Any - def __init__(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ..., encoding: str = ...): ... - def __getattr__(self, name): ... + uri: str + http_method: _HTTPMethod + headers: CaseInsensitiveDict + body: str | dict[str, str] | list[tuple[str, str]] | None + decoded_body: list[tuple[str, str]] | None + oauth_params: list[str] + validator_log: dict[str, Any] # value type depends on the key + access_token: Incomplete | None + client: Incomplete | None + client_id: Incomplete | None + client_secret: Incomplete | None + code: Incomplete | None + code_challenge: Incomplete | None + code_challenge_method: Incomplete | None + code_verifier: Incomplete | None + extra_credentials: Incomplete | None + grant_type: Incomplete | None + redirect_uri: Incomplete | None + refresh_token: Incomplete | None + request_token: Incomplete | None + response_type: Incomplete | None + scope: Incomplete | None + scopes: Incomplete | None + state: Incomplete | None + token: Incomplete | None + user: Incomplete | None + token_type_hint: Incomplete | None + response_mode: Incomplete | None + nonce: Incomplete | None + display: Incomplete | None + prompt: Incomplete | None + claims: Incomplete | None + max_age: Incomplete | None + ui_locales: Incomplete | None + id_token_hint: Incomplete | None + login_hint: Incomplete | None + acr_values: Incomplete | None + def __init__( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: Mapping[str, str] | None = None, + encoding: str = "utf-8", + ): ... + def __getattr__(self, name: str) -> str | None: ... # or raises AttributeError if attribute is not found @property - def uri_query(self): ... + def uri_query(self) -> str: ... @property - def uri_query_params(self): ... + def uri_query_params(self) -> list[tuple[str, str]]: ... @property - def duplicate_params(self): ... + def duplicate_params(self) -> list[str]: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi index 9dbdbe00b4ad..c5e4a4127326 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi @@ -1,56 +1,68 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from logging import Logger +from typing import Final -log: Any -SIGNATURE_HMAC_SHA1: str -SIGNATURE_HMAC_SHA256: str -SIGNATURE_HMAC_SHA512: str -SIGNATURE_HMAC: str -SIGNATURE_RSA_SHA1: str -SIGNATURE_RSA_SHA256: str -SIGNATURE_RSA_SHA512: str -SIGNATURE_RSA: str -SIGNATURE_PLAINTEXT: str -SIGNATURE_METHODS: Any -SIGNATURE_TYPE_AUTH_HEADER: str -SIGNATURE_TYPE_QUERY: str -SIGNATURE_TYPE_BODY: str -CONTENT_TYPE_FORM_URLENCODED: str +from oauthlib.common import _HTTPMethod + +log: Logger +SIGNATURE_HMAC_SHA1: Final[str] +SIGNATURE_HMAC_SHA256: Final[str] +SIGNATURE_HMAC_SHA512: Final[str] +SIGNATURE_HMAC: Final[str] +SIGNATURE_RSA_SHA1: Final[str] +SIGNATURE_RSA_SHA256: Final[str] +SIGNATURE_RSA_SHA512: Final[str] +SIGNATURE_RSA: Final[str] +SIGNATURE_PLAINTEXT: Final[str] +SIGNATURE_METHODS: Final[tuple[str, str, str, str, str, str, str]] +SIGNATURE_TYPE_AUTH_HEADER: Final[str] +SIGNATURE_TYPE_QUERY: Final[str] +SIGNATURE_TYPE_BODY: Final[str] +CONTENT_TYPE_FORM_URLENCODED: Final[str] class Client: - SIGNATURE_METHODS: Any + SIGNATURE_METHODS: dict[str, Callable[[str, Incomplete], str]] @classmethod def register_signature_method(cls, method_name, method_callback) -> None: ... - client_key: Any - client_secret: Any - resource_owner_key: Any - resource_owner_secret: Any - signature_method: Any - signature_type: Any - callback_uri: Any - rsa_key: Any - verifier: Any - realm: Any - encoding: Any - decoding: Any - nonce: Any - timestamp: Any + client_key: Incomplete + client_secret: Incomplete + resource_owner_key: Incomplete + resource_owner_secret: Incomplete + signature_method: Incomplete + signature_type: Incomplete + callback_uri: Incomplete + rsa_key: Incomplete + verifier: Incomplete + realm: Incomplete + encoding: Incomplete + decoding: Incomplete + nonce: Incomplete + timestamp: Incomplete def __init__( self, - client_key, - client_secret: Any | None = ..., - resource_owner_key: Any | None = ..., - resource_owner_secret: Any | None = ..., - callback_uri: Any | None = ..., - signature_method=..., - signature_type=..., - rsa_key: Any | None = ..., - verifier: Any | None = ..., - realm: Any | None = ..., - encoding: str = ..., - decoding: Any | None = ..., - nonce: Any | None = ..., - timestamp: Any | None = ..., + client_key: str, + client_secret: str | None = None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key=None, + verifier=None, + realm=None, + encoding: str = "utf-8", + decoding=None, + nonce=None, + timestamp=None, ): ... def get_oauth_signature(self, request): ... def get_oauth_params(self, request): ... - def sign(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ..., realm: Any | None = ...): ... + def sign( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: Mapping[str, str] | None = None, + realm=None, + ): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi index d800bdfa801c..1a05e8f7a9b2 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi @@ -1,12 +1,10 @@ -from typing import Any +from logging import Logger from .base import BaseEndpoint as BaseEndpoint -log: Any +log: Logger class AccessTokenEndpoint(BaseEndpoint): def create_access_token(self, request, credentials): ... - def create_access_token_response( - self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ..., credentials: Any | None = ... - ): ... + def create_access_token_response(self, uri, http_method: str = "GET", body=None, headers=None, credentials=None): ... def validate_access_token_request(self, request): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi index ce082c7ff042..478b0dc9ff20 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi @@ -1,16 +1,8 @@ -from typing import Any - from .base import BaseEndpoint as BaseEndpoint class AuthorizationEndpoint(BaseEndpoint): def create_verifier(self, request, credentials): ... def create_authorization_response( - self, - uri, - http_method: str = ..., - body: Any | None = ..., - headers: Any | None = ..., - realms: Any | None = ..., - credentials: Any | None = ..., + self, uri, http_method: str = "GET", body=None, headers=None, realms=None, credentials=None ): ... - def get_realms_and_credentials(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... + def get_realms_and_credentials(self, uri, http_method: str = "GET", body=None, headers=None): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi index 08e523158a94..c409738cdaa9 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi @@ -1,6 +1,6 @@ -from typing import Any +from _typeshed import Incomplete class BaseEndpoint: - request_validator: Any - token_generator: Any - def __init__(self, request_validator, token_generator: Any | None = ...) -> None: ... + request_validator: Incomplete + token_generator: Incomplete + def __init__(self, request_validator, token_generator=None) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi index 6cdaeca376b2..9f8f06aca4d7 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi @@ -1,12 +1,10 @@ -from typing import Any +from logging import Logger from .base import BaseEndpoint as BaseEndpoint -log: Any +log: Logger class RequestTokenEndpoint(BaseEndpoint): def create_request_token(self, request, credentials): ... - def create_request_token_response( - self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ..., credentials: Any | None = ... - ): ... + def create_request_token_response(self, uri, http_method: str = "GET", body=None, headers=None, credentials=None): ... def validate_request_token_request(self, request): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi index 40bf6506b830..a262b1a70729 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi @@ -1,10 +1,8 @@ -from typing import Any +from logging import Logger from .base import BaseEndpoint as BaseEndpoint -log: Any +log: Logger class ResourceEndpoint(BaseEndpoint): - def validate_protected_resource_request( - self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ..., realms: Any | None = ... - ): ... + def validate_protected_resource_request(self, uri, http_method: str = "GET", body=None, headers=None, realms=None): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi index d1959763a11f..8000469a86c3 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi @@ -1,8 +1,8 @@ -from typing import Any +from logging import Logger from .base import BaseEndpoint as BaseEndpoint -log: Any +log: Logger class SignatureOnlyEndpoint(BaseEndpoint): - def validate_request(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... + def validate_request(self, uri, http_method: str = "GET", body=None, headers=None): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi index 3425736948e8..31973a6da123 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi @@ -1,13 +1,11 @@ -from typing import Any +from _typeshed import Incomplete class OAuth1Error(Exception): - error: Any + error: Incomplete description: str - uri: Any - status_code: Any - def __init__( - self, description: Any | None = ..., uri: Any | None = ..., status_code: int = ..., request: Any | None = ... - ) -> None: ... + uri: Incomplete + status_code: Incomplete + def __init__(self, description=None, uri=None, status_code: int = 400, request=None) -> None: ... def in_uri(self, uri): ... @property def twotuples(self): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi index f505bb4b3373..49c06be9d17e 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi @@ -1,5 +1,3 @@ -from typing import Any - -def prepare_headers(oauth_params, headers: Any | None = ..., realm: Any | None = ...): ... +def prepare_headers(params, headers=None, realm=None): ... def prepare_form_encoded_body(oauth_params, body): ... def prepare_request_uri_query(oauth_params, uri): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi index 889992b4e371..3bb84ae34ce1 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi @@ -1,59 +1,67 @@ -from typing import Any +from ...common import Request class RequestValidator: def __init__(self) -> None: ... @property - def allowed_signature_methods(self): ... + def allowed_signature_methods(self) -> tuple[str, ...]: ... @property - def safe_characters(self): ... + def safe_characters(self) -> set[str]: ... @property - def client_key_length(self): ... + def client_key_length(self) -> tuple[int, int]: ... @property - def request_token_length(self): ... + def request_token_length(self) -> tuple[int, int]: ... @property - def access_token_length(self): ... + def access_token_length(self) -> tuple[int, int]: ... @property - def timestamp_lifetime(self): ... + def timestamp_lifetime(self) -> int: ... @property - def nonce_length(self): ... + def nonce_length(self) -> tuple[int, int]: ... @property - def verifier_length(self): ... + def verifier_length(self) -> tuple[int, int]: ... @property - def realms(self): ... + def realms(self) -> list[str]: ... @property - def enforce_ssl(self): ... - def check_client_key(self, client_key): ... - def check_request_token(self, request_token): ... - def check_access_token(self, request_token): ... - def check_nonce(self, nonce): ... - def check_verifier(self, verifier): ... - def check_realms(self, realms): ... + def enforce_ssl(self) -> bool: ... + def check_client_key(self, client_key: str) -> bool: ... + def check_request_token(self, request_token: str) -> bool: ... + def check_access_token(self, request_token: str) -> bool: ... + def check_nonce(self, nonce: str) -> bool: ... + def check_verifier(self, verifier: str) -> bool: ... + def check_realms(self, realms: list[str]) -> bool: ... @property - def dummy_client(self) -> None: ... + def dummy_client(self) -> str: ... @property - def dummy_request_token(self) -> None: ... + def dummy_request_token(self) -> str: ... @property - def dummy_access_token(self) -> None: ... - def get_client_secret(self, client_key, request) -> None: ... - def get_request_token_secret(self, client_key, token, request) -> None: ... - def get_access_token_secret(self, client_key, token, request) -> None: ... - def get_default_realms(self, client_key, request) -> None: ... - def get_realms(self, token, request) -> None: ... - def get_redirect_uri(self, token, request) -> None: ... - def get_rsa_key(self, client_key, request) -> None: ... - def invalidate_request_token(self, client_key, request_token, request) -> None: ... - def validate_client_key(self, client_key, request) -> None: ... - def validate_request_token(self, client_key, token, request) -> None: ... - def validate_access_token(self, client_key, token, request) -> None: ... + def dummy_access_token(self) -> str: ... + def get_client_secret(self, client_key: str, request: Request) -> str: ... + def get_request_token_secret(self, client_key: str, token: str, request: Request) -> str: ... + def get_access_token_secret(self, client_key: str, token: str, request: Request) -> str: ... + def get_default_realms(self, client_key: str, request: Request) -> list[str]: ... + def get_realms(self, token: str, request: Request) -> list[str]: ... + def get_redirect_uri(self, token: str, request: Request) -> str: ... + def get_rsa_key(self, client_key: str, request: Request) -> str: ... + def invalidate_request_token(self, client_key: str, request_token: str, request: Request) -> None: ... + def validate_client_key(self, client_key: str, request: Request) -> bool: ... + def validate_request_token(self, client_key: str, token: str, request: Request) -> bool: ... + def validate_access_token(self, client_key: str, token: str, request: Request) -> bool: ... def validate_timestamp_and_nonce( - self, client_key, timestamp, nonce, request, request_token: Any | None = ..., access_token: Any | None = ... - ) -> None: ... - def validate_redirect_uri(self, client_key, redirect_uri, request) -> None: ... - def validate_requested_realms(self, client_key, realms, request) -> None: ... - def validate_realms(self, client_key, token, request, uri: Any | None = ..., realms: Any | None = ...) -> None: ... - def validate_verifier(self, client_key, token, verifier, request) -> None: ... - def verify_request_token(self, token, request) -> None: ... - def verify_realms(self, token, realms, request) -> None: ... - def save_access_token(self, token, request) -> None: ... - def save_request_token(self, token, request) -> None: ... - def save_verifier(self, token, verifier, request) -> None: ... + self, + client_key: str, + timestamp, + nonce: str, + request: Request, + request_token: str | None = None, + access_token: str | None = None, + ) -> bool: ... + def validate_redirect_uri(self, client_key: str, redirect_uri, request: Request) -> bool: ... + def validate_requested_realms(self, client_key: str, realms: list[str], request: Request) -> bool: ... + def validate_realms( + self, client_key: str, token: str, request: Request, uri: str | None = None, realms: list[str] | None = None + ) -> bool: ... + def validate_verifier(self, client_key: str, token: str, verifier: str, request: Request) -> bool: ... + def verify_request_token(self, token: str, request: Request) -> bool: ... + def verify_realms(self, token: str, realms: list[str], request: Request) -> bool: ... + def save_access_token(self, token: str, request: Request) -> None: ... + def save_request_token(self, token: str, request: Request) -> None: ... + def save_verifier(self, token: str, verifier, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi index bda6f7b0f457..c86e96d0f646 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi @@ -1,32 +1,36 @@ -from typing import Any +from _typeshed import Unused +from collections.abc import Iterable +from logging import Logger -log: Any +from oauthlib.common import Request, _HTTPMethod -def signature_base_string(http_method: str, base_str_uri: str, normalized_encoded_request_parameters: str) -> str: ... -def base_string_uri(uri: str, host: str | None = ...) -> str: ... +log: Logger + +def signature_base_string(http_method: _HTTPMethod, base_str_uri: str, normalized_encoded_request_parameters: str) -> str: ... +def base_string_uri(uri: str, host: str | None = None) -> str: ... def collect_parameters( - uri_query: str = ..., - body: Any | None = ..., - headers: Any | None = ..., - exclude_oauth_signature: bool = ..., - with_realm: bool = ..., -): ... -def normalize_parameters(params) -> str: ... -def sign_hmac_sha1_with_client(sig_base_str, client): ... -def verify_hmac_sha1(request, client_secret: Any | None = ..., resource_owner_secret: Any | None = ...): ... -def sign_hmac_sha1(base_string, client_secret, resource_owner_secret): ... + uri_query: str = "", + body: str | bytes | dict[str, str] | Iterable[tuple[str, str]] | None = None, + headers: dict[str, str] | None = None, + exclude_oauth_signature: bool = True, + with_realm: bool = False, +) -> list[tuple[str, str]]: ... +def normalize_parameters(params: dict[str, str]) -> str: ... +def sign_hmac_sha1_with_client(sig_base_str: str, client): ... +def verify_hmac_sha1(request: Request, client_secret=None, resource_owner_secret=None) -> bool: ... +def sign_hmac_sha1(base_string: str | bytes, client_secret, resource_owner_secret): ... def sign_hmac_sha256_with_client(sig_base_str, client): ... -def verify_hmac_sha256(request, client_secret: Any | None = ..., resource_owner_secret: Any | None = ...): ... -def sign_hmac_sha256(base_string, client_secret, resource_owner_secret): ... +def verify_hmac_sha256(request, client_secret=None, resource_owner_secret=None) -> bool: ... +def sign_hmac_sha256(base_string: str | bytes, client_secret, resource_owner_secret): ... def sign_hmac_sha512_with_client(sig_base_str: str, client): ... -def verify_hmac_sha512(request, client_secret: str | None = ..., resource_owner_secret: str | None = ...): ... -def sign_rsa_sha1_with_client(sig_base_str, client): ... -def verify_rsa_sha1(request, rsa_public_key: str): ... +def verify_hmac_sha512(request, client_secret: str | None = None, resource_owner_secret: str | None = None) -> bool: ... +def sign_rsa_sha1_with_client(sig_base_str: str | bytes, client): ... +def verify_rsa_sha1(request, rsa_public_key: str) -> bool: ... def sign_rsa_sha1(base_string, rsa_private_key): ... def sign_rsa_sha256_with_client(sig_base_str: str, client): ... -def verify_rsa_sha256(request, rsa_public_key: str): ... +def verify_rsa_sha256(request, rsa_public_key: str) -> bool: ... def sign_rsa_sha512_with_client(sig_base_str: str, client): ... -def verify_rsa_sha512(request, rsa_public_key: str): ... -def sign_plaintext_with_client(_signature_base_string, client): ... -def sign_plaintext(client_secret, resource_owner_secret): ... -def verify_plaintext(request, client_secret: Any | None = ..., resource_owner_secret: Any | None = ...): ... +def verify_rsa_sha512(request, rsa_public_key: str) -> bool: ... +def sign_plaintext_with_client(_signature_base_string: Unused, client) -> str: ... +def sign_plaintext(client_secret: str | None, resource_owner_secret: str | None) -> str: ... +def verify_plaintext(request, client_secret: str | None = None, resource_owner_secret: str | None = None) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi index cce8ec232e67..46e93ea192fc 100644 --- a/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi @@ -1,9 +1,18 @@ -UNICODE_ASCII_CHARACTER_SET: str +from collections.abc import Callable, Iterable +from typing import Final, TypeVar -def filter_params(target): ... -def filter_oauth_params(params): ... -def escape(u): ... -def unescape(u): ... -def parse_keqv_list(l): ... -def parse_http_list(u): ... -def parse_authorization_header(authorization_header): ... +_T = TypeVar("_T") + +UNICODE_ASCII_CHARACTER_SET: Final[str] + +def filter_params( + target: Callable[[dict[str, object] | Iterable[tuple[str, object]], _T], object], +) -> Callable[[list[str], _T], object]: ... +def filter_oauth_params( + params: dict[str, object] | Iterable[tuple[str, object]], +) -> list[str]: ... # we don't care about second (object) part +def escape(u: str) -> str: ... +def unescape(u: str) -> str: ... +def parse_keqv_list(l: list[str]) -> dict[str, str]: ... +def parse_http_list(u: str) -> list[str]: ... +def parse_authorization_header(authorization_header: str) -> list[tuple[str, str]]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/__init__.pyi index c56170abc657..117244ab80d8 100644 --- a/stubs/oauthlib/oauthlib/oauth2/__init__.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/__init__.pyi @@ -57,3 +57,9 @@ from .rfc6749.grant_types import ( from .rfc6749.request_validator import RequestValidator as RequestValidator from .rfc6749.tokens import BearerToken as BearerToken, OAuth2Token as OAuth2Token from .rfc6749.utils import is_secure_transport as is_secure_transport +from .rfc8628.clients import DeviceClient as DeviceClient +from .rfc8628.endpoints import ( + DeviceApplicationServer as DeviceApplicationServer, + DeviceAuthorizationEndpoint as DeviceAuthorizationEndpoint, +) +from .rfc8628.grant_types import DeviceCodeGrant as DeviceCodeGrant diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi index efc812cce8bb..f168fb8a2b5d 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi @@ -1,4 +1,4 @@ -from typing import Any +from logging import Logger from .endpoints.base import BaseEndpoint as BaseEndpoint, catch_errors_and_unavailability as catch_errors_and_unavailability from .errors import ( @@ -8,4 +8,4 @@ from .errors import ( TemporarilyUnavailableError as TemporarilyUnavailableError, ) -log: Any +log: Logger diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi index f3c64ec4a50e..7f8ff4894942 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi @@ -1,7 +1,15 @@ -from typing import Any - -from .base import Client as Client +from .base import Client class BackendApplicationClient(Client): grant_type: str - def prepare_request_body(self, body: str = ..., scope: Any | None = ..., include_client_id: bool = ..., **kwargs): ... # type: ignore[override] + def prepare_request_body( + self, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + *, + code_verifier: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi index 1000f338ff7e..aefe555f0d83 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi @@ -1,75 +1,120 @@ -from typing import Any +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Callable +from typing import Final, Literal, TypeAlias -AUTH_HEADER: str -URI_QUERY: str -BODY: str -FORM_ENC_HEADERS: Any +from oauthlib.common import _HTTPMethod +from oauthlib.oauth2.rfc6749.tokens import OAuth2Token + +_TokenPlacement: TypeAlias = Literal["auth_header", "query", "body"] + +AUTH_HEADER: Final[_TokenPlacement] +URI_QUERY: Final[_TokenPlacement] +BODY: Final[_TokenPlacement] +FORM_ENC_HEADERS: Final[dict[str, str]] class Client: refresh_token_key: str - client_id: Any - default_token_placement: Any - token_type: Any - access_token: Any - refresh_token: Any - mac_key: Any - mac_algorithm: Any - token: Any - scope: Any - state_generator: Any - state: Any - redirect_url: Any - code: Any - expires_in: Any + client_id: str + default_token_placement: _TokenPlacement + token_type: str + access_token: str | None + refresh_token: str | None + mac_key: str | bytes | bytearray | None + mac_algorithm: str | None + token: dict[str, Incomplete] + scope: str | set[object] | tuple[object] | list[object] + state_generator: Callable[[], str] + state: str | None + redirect_url: str | None + code: str | None + expires_in: ConvertibleToInt | None + code_verifier: str | None + code_challenge: str | None + code_challenge_method: str | None def __init__( self, - client_id, - default_token_placement=..., - token_type: str = ..., - access_token: Any | None = ..., - refresh_token: Any | None = ..., - mac_key: Any | None = ..., - mac_algorithm: Any | None = ..., - token: Any | None = ..., - scope: Any | None = ..., - state: Any | None = ..., - redirect_url: Any | None = ..., - state_generator=..., + client_id: str, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, **kwargs, ) -> None: ... @property - def token_types(self): ... - def prepare_request_uri(self, *args, **kwargs) -> None: ... - def prepare_request_body(self, *args, **kwargs) -> None: ... - def parse_request_uri_response(self, *args, **kwargs) -> None: ... + def token_types( + self, + ) -> dict[ + Literal["Bearer", "MAC"], + Callable[ + [str, str, str | None, dict[str, str] | None, str | None, Incomplete], tuple[str, dict[str, str] | None, str | None] + ], + ]: ... + def prepare_request_uri(self, *args, **kwargs) -> str: ... + def prepare_request_body(self, *args, **kwargs) -> str: ... + def parse_request_uri_response(self, *args, **kwargs) -> dict[str, str]: ... def add_token( self, - uri, - http_method: str = ..., - body: Any | None = ..., - headers: Any | None = ..., - token_placement: Any | None = ..., + uri: str, + http_method: _HTTPMethod = "GET", + body: str | None = None, + headers: dict[str, str] | None = None, + token_placement: _TokenPlacement | None = None, **kwargs, - ): ... + ) -> tuple[str, dict[str, str] | None, str | None]: ... def prepare_authorization_request( - self, authorization_url, state: Any | None = ..., redirect_url: Any | None = ..., scope: Any | None = ..., **kwargs - ): ... + self, + authorization_url: str, + state: str | None = None, + redirect_url: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + **kwargs, + ) -> tuple[str, dict[str, str], str]: ... def prepare_token_request( self, - token_url, - authorization_response: Any | None = ..., - redirect_url: Any | None = ..., - state: Any | None = ..., - body: str = ..., + token_url: str, + authorization_response: str | None = None, + redirect_url: str | None = None, + state: str | None = None, + body: str = "", **kwargs, - ): ... + ) -> tuple[str, dict[str, str], str]: ... def prepare_refresh_token_request( - self, token_url, refresh_token: Any | None = ..., body: str = ..., scope: Any | None = ..., **kwargs - ): ... + self, + token_url: str, + refresh_token: str | None = None, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + **kwargs, + ) -> tuple[str, dict[str, str], str]: ... def prepare_token_revocation_request( - self, revocation_url, token, token_type_hint: str = ..., body: str = ..., callback: Any | None = ..., **kwargs - ): ... - def parse_request_body_response(self, body, scope: Any | None = ..., **kwargs): ... - def prepare_refresh_body(self, body: str = ..., refresh_token: Any | None = ..., scope: Any | None = ..., **kwargs): ... - def populate_code_attributes(self, response) -> None: ... - def populate_token_attributes(self, response) -> None: ... + self, + revocation_url: str, + token: str, + token_type_hint: Literal["access_token", "refresh_token"] | None = "access_token", + body: str = "", + **kwargs, + ) -> tuple[str, dict[str, str], str]: ... + def parse_request_body_response( + self, body: str, scope: str | set[object] | tuple[object] | list[object] | None = None, **kwargs + ) -> OAuth2Token: ... + def prepare_refresh_body( + self, + body: str = "", + refresh_token: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + **kwargs, + ) -> str: ... + def create_code_verifier(self, length: int) -> str: ... + def create_code_challenge(self, code_verifier: str, code_challenge_method: str | None = None) -> str: ... + def populate_code_attributes(self, response: dict[str, Incomplete]) -> None: ... + def populate_token_attributes(self, response: dict[str, Incomplete]) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi index b7f692737e81..9fe5fd41d0ff 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi @@ -1,10 +1,42 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable -from .base import Client as Client +from .base import Client, _TokenPlacement class LegacyApplicationClient(Client): grant_type: str - def __init__(self, client_id, **kwargs) -> None: ... - def prepare_request_body( # type: ignore[override] - self, username, password, body: str = ..., scope: Any | None = ..., include_client_id: bool = ..., **kwargs - ): ... + def __init__( + self, + client_id: str, + *, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_body( + self, + username: str, + password: str, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + *, + code_verifier: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + code: str | None = None, + redirect_uri: str | None = None, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi index fa9d338b9913..a6b945f79259 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi @@ -1,11 +1,18 @@ -from typing import Any +from oauthlib.oauth2.rfc6749.tokens import OAuth2Token -from .base import Client as Client +from .base import Client class MobileApplicationClient(Client): response_type: str - def prepare_request_uri( # type: ignore[override] - self, uri, redirect_uri: Any | None = ..., scope: Any | None = ..., state: Any | None = ..., **kwargs - ): ... - token: Any - def parse_request_uri_response(self, uri, state: Any | None = ..., scope: Any | None = ...): ... # type: ignore[override] + def prepare_request_uri( + self, + uri, + redirect_uri: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + **kwargs, + ) -> str: ... + token: OAuth2Token + def parse_request_uri_response( + self, uri: str, state: str | None = None, scope: str | set[object] | tuple[object] | list[object] | None = None + ) -> OAuth2Token: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi index 9a8d3575d90e..00b375898b98 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi @@ -1,33 +1,56 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable -from .base import Client as Client +from .base import Client, _TokenPlacement class ServiceApplicationClient(Client): grant_type: str - private_key: Any - subject: Any - issuer: Any - audience: Any + private_key: str | None + subject: str | None + issuer: str | None + audience: str | None def __init__( self, - client_id, - private_key: Any | None = ..., - subject: Any | None = ..., - issuer: Any | None = ..., - audience: Any | None = ..., + client_id: str, + private_key: str | None = None, + subject: str | None = None, + issuer: str | None = None, + audience: str | None = None, + *, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, **kwargs, ) -> None: ... - def prepare_request_body( # type: ignore[override] + def prepare_request_body( self, - private_key: Any | None = ..., - subject: Any | None = ..., - issuer: Any | None = ..., - audience: Any | None = ..., - expires_at: Any | None = ..., - issued_at: Any | None = ..., - extra_claims: Any | None = ..., - body: str = ..., - scope: Any | None = ..., - include_client_id: bool = ..., + private_key: str | None = None, + subject: str | None = None, + issuer: str | None = None, + audience: str | None = None, + expires_at: float | None = None, + issued_at: float | None = None, + extra_claims: dict[str, Incomplete] | None = None, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + *, + not_before: int | None = None, + jwt_id: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + code: str | None = None, + redirect_uri: str | None = None, **kwargs, - ): ... + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi index 054ab27c311b..53d4d600b9c1 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi @@ -1,15 +1,53 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable -from .base import Client as Client +from .base import Client, _TokenPlacement class WebApplicationClient(Client): grant_type: str - code: Any - def __init__(self, client_id, code: Any | None = ..., **kwargs) -> None: ... - def prepare_request_uri( # type: ignore[override] - self, uri, redirect_uri: Any | None = ..., scope: Any | None = ..., state: Any | None = ..., **kwargs - ): ... - def prepare_request_body( # type: ignore[override] - self, code: Any | None = ..., redirect_uri: Any | None = ..., body: str = ..., include_client_id: bool = ..., **kwargs - ): ... - def parse_request_uri_response(self, uri, state: Any | None = ...): ... # type: ignore[override] + code: str | None + def __init__( + self, + client_id: str, + code: str | None = None, + *, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_uri( + self, + uri: str, + redirect_uri: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = "plain", + **kwargs, + ) -> str: ... + def prepare_request_body( + self, + code: str | None = None, + redirect_uri: str | None = None, + body: str = "", + include_client_id: bool = True, + code_verifier: str | None = None, + *, + scope: str | set[object] | tuple[object] | list[object] | None = None, + client_id: str | None = None, + client_secret: str | None = None, + **kwargs, + ) -> str: ... + def parse_request_uri_response(self, uri: str, state: str | None = None) -> dict[str, str]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi index 17d3e3d58bd1..f4604fd1fe0b 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi @@ -1,26 +1,31 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger -from .base import BaseEndpoint as BaseEndpoint +from oauthlib.common import _HTTPMethod -log: Any +from .base import BaseEndpoint + +log: Logger class AuthorizationEndpoint(BaseEndpoint): - def __init__(self, default_response_type, default_token_type, response_types) -> None: ... + def __init__(self, default_response_type: str, default_token_type: str, response_types: dict[str, Incomplete]) -> None: ... @property - def response_types(self): ... + def response_types(self) -> dict[str, Incomplete]: ... @property - def default_response_type(self): ... + def default_response_type(self) -> str: ... @property def default_response_type_handler(self): ... @property def default_token_type(self): ... def create_authorization_response( self, - uri, - http_method: str = ..., - body: Any | None = ..., - headers: Any | None = ..., - scopes: Any | None = ..., - credentials: Any | None = ..., + uri: str, + http_method: _HTTPMethod = "GET", + body: str | None = None, + headers: dict[str, str] | None = None, + scopes=None, + credentials: dict[str, Incomplete] | None = None, + ): ... + def validate_authorization_request( + self, uri: str, http_method: _HTTPMethod = "GET", body: str | None = None, headers: dict[str, str] | None = None ): ... - def validate_authorization_request(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi index a7d18663ee87..d4aade1edbd3 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi @@ -1,20 +1,27 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger -log: Any +log: Logger class BaseEndpoint: def __init__(self) -> None: ... + @property - def valid_request_methods(self): ... + def valid_request_methods(self) -> Sequence[str] | None: ... @valid_request_methods.setter - def valid_request_methods(self, valid_request_methods) -> None: ... + def valid_request_methods(self, valid_request_methods: Sequence[str] | None) -> None: ... + @property - def available(self): ... + def available(self) -> bool: ... @available.setter - def available(self, available) -> None: ... + def available(self, available: bool) -> None: ... + @property - def catch_errors(self): ... + def catch_errors(self) -> bool: ... @catch_errors.setter - def catch_errors(self, catch_errors) -> None: ... + def catch_errors(self, catch_errors: bool) -> None: ... -def catch_errors_and_unavailability(f): ... +def catch_errors_and_unavailability( + f: Callable[..., tuple[dict[str, Incomplete], str, int]], +) -> Callable[..., tuple[dict[str, Incomplete], str, int]]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi index 291bf6ec47e5..49ebf9ae0ff2 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi @@ -1,14 +1,20 @@ -from typing import Any +from logging import Logger +from typing import Literal -from .base import BaseEndpoint as BaseEndpoint +from oauthlib.common import Request, _HTTPMethod -log: Any +from ..request_validator import RequestValidator +from .base import BaseEndpoint + +log: Logger class IntrospectEndpoint(BaseEndpoint): - valid_token_types: Any - valid_request_methods: Any - request_validator: Any - supported_token_types: Any - def __init__(self, request_validator, supported_token_types: Any | None = ...) -> None: ... - def create_introspect_response(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... - def validate_introspect_request(self, request) -> None: ... + valid_token_types: tuple[Literal["access_token"], Literal["refresh_token"]] + valid_request_methods: tuple[Literal["POST"]] + request_validator: RequestValidator + supported_token_types: tuple[str, ...] + def __init__(self, request_validator: RequestValidator, supported_token_types: tuple[str, ...] | None = None) -> None: ... + def create_introspect_response( + self, uri: str, http_method: _HTTPMethod = "POST", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], str, int]: ... + def validate_introspect_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi index c9ef381b3814..fcd53ad14f0d 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi @@ -1,21 +1,27 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterable +from logging import Logger -from .base import BaseEndpoint as BaseEndpoint +from .base import BaseEndpoint -log: Any +log: Logger class MetadataEndpoint(BaseEndpoint): - raise_errors: Any - endpoints: Any - initial_claims: Any - claims: Any - def __init__(self, endpoints, claims=..., raise_errors: bool = ...) -> None: ... - def create_metadata_response(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... + raise_errors: bool + endpoints: Iterable[BaseEndpoint] + initial_claims: dict[str, Incomplete] + claims: dict[str, Incomplete] + def __init__( + self, endpoints: Iterable[BaseEndpoint], claims: dict[str, Incomplete] = {}, raise_errors: bool = True + ) -> None: ... + def create_metadata_response( + self, uri: str, http_method: str = "GET", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], str, int]: ... def validate_metadata( - self, array, key, is_required: bool = ..., is_list: bool = ..., is_url: bool = ..., is_issuer: bool = ... + self, array, key, is_required: bool = False, is_list: bool = False, is_url: bool = False, is_issuer: bool = False ) -> None: ... - def validate_metadata_token(self, claims, endpoint) -> None: ... - def validate_metadata_authorization(self, claims, endpoint): ... - def validate_metadata_revocation(self, claims, endpoint) -> None: ... - def validate_metadata_introspection(self, claims, endpoint) -> None: ... - def validate_metadata_server(self): ... + def validate_metadata_token(self, claims, endpoint: BaseEndpoint) -> None: ... + def validate_metadata_authorization(self, claims, endpoint: BaseEndpoint): ... + def validate_metadata_revocation(self, claims, endpoint: BaseEndpoint) -> None: ... + def validate_metadata_introspection(self, claims, endpoint: BaseEndpoint) -> None: ... + def validate_metadata_server(self) -> dict[str, Incomplete]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi index 0f435639f3c6..02414844d9fc 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi @@ -1,74 +1,83 @@ -from typing import Any +from _typeshed import Unused +from collections.abc import Callable -from .authorization import AuthorizationEndpoint as AuthorizationEndpoint -from .introspect import IntrospectEndpoint as IntrospectEndpoint -from .resource import ResourceEndpoint as ResourceEndpoint -from .revocation import RevocationEndpoint as RevocationEndpoint -from .token import TokenEndpoint as TokenEndpoint +from oauthlib.common import Request +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant + +from ..grant_types import ( + AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant, + RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from ..request_validator import RequestValidator +from ..tokens import BearerToken +from .authorization import AuthorizationEndpoint +from .introspect import IntrospectEndpoint +from .resource import ResourceEndpoint +from .revocation import RevocationEndpoint +from .token import TokenEndpoint class Server(AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint): - auth_grant: Any - implicit_grant: Any - password_grant: Any - credentials_grant: Any - refresh_grant: Any - bearer: Any + auth_grant: AuthorizationCodeGrant + implicit_grant: ImplicitGrant + password_grant: ResourceOwnerPasswordCredentialsGrant + credentials_grant: ClientCredentialsGrant + refresh_grant: RefreshTokenGrant + device_code_grant: DeviceCodeGrant + bearer: BearerToken def __init__( self, - request_validator, - token_expires_in: Any | None = ..., - token_generator: Any | None = ..., - refresh_token_generator: Any | None = ..., - *args, - **kwargs, + request_validator: RequestValidator, + token_expires_in: int | Callable[[Request], int] | None = None, + token_generator: Callable[[Request], str] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + *args: Unused, ) -> None: ... class WebApplicationServer(AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint): - auth_grant: Any - refresh_grant: Any - bearer: Any + auth_grant: AuthorizationCodeGrant + refresh_grant: RefreshTokenGrant + bearer: BearerToken def __init__( self, - request_validator, - token_generator: Any | None = ..., - token_expires_in: Any | None = ..., - refresh_token_generator: Any | None = ..., - **kwargs, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, ) -> None: ... class MobileApplicationServer(AuthorizationEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint): - implicit_grant: Any - bearer: Any + implicit_grant: ImplicitGrant + bearer: BearerToken def __init__( self, - request_validator, - token_generator: Any | None = ..., - token_expires_in: Any | None = ..., - refresh_token_generator: Any | None = ..., - **kwargs, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, ) -> None: ... class LegacyApplicationServer(TokenEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint): - password_grant: Any - refresh_grant: Any - bearer: Any + password_grant: ResourceOwnerPasswordCredentialsGrant + refresh_grant: RefreshTokenGrant + bearer: BearerToken def __init__( self, - request_validator, - token_generator: Any | None = ..., - token_expires_in: Any | None = ..., - refresh_token_generator: Any | None = ..., - **kwargs, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, ) -> None: ... class BackendApplicationServer(TokenEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint): - credentials_grant: Any - bearer: Any + credentials_grant: ClientCredentialsGrant + bearer: BearerToken def __init__( self, - request_validator, - token_generator: Any | None = ..., - token_expires_in: Any | None = ..., - refresh_token_generator: Any | None = ..., - **kwargs, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, ) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi index c44ae9d03fe2..8c27bdffec02 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi @@ -1,18 +1,26 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger -from .base import BaseEndpoint as BaseEndpoint +from oauthlib.common import Request, _HTTPMethod -log: Any +from .base import BaseEndpoint + +log: Logger class ResourceEndpoint(BaseEndpoint): - def __init__(self, default_token, token_types) -> None: ... + def __init__(self, default_token: str, token_types: dict[str, Incomplete]) -> None: ... @property - def default_token(self): ... + def default_token(self) -> str: ... @property def default_token_type_handler(self): ... @property - def tokens(self): ... + def tokens(self) -> dict[str, Incomplete]: ... def verify_request( - self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ..., scopes: Any | None = ... - ): ... - def find_token_type(self, request): ... + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | None = None, + headers: dict[str, str] | None = None, + scopes=None, + ) -> tuple[bool, Request]: ... + def find_token_type(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi index 137581ae548b..fe02a0542729 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi @@ -1,15 +1,20 @@ -from typing import Any +from logging import Logger +from typing import Literal -from .base import BaseEndpoint as BaseEndpoint +from oauthlib.common import Request, _HTTPMethod -log: Any +from ..request_validator import RequestValidator +from .base import BaseEndpoint + +log: Logger class RevocationEndpoint(BaseEndpoint): - valid_token_types: Any - valid_request_methods: Any - request_validator: Any - supported_token_types: Any - enable_jsonp: Any - def __init__(self, request_validator, supported_token_types: Any | None = ..., enable_jsonp: bool = ...) -> None: ... - def create_revocation_response(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... - def validate_revocation_request(self, request) -> None: ... + valid_token_types: tuple[Literal["access_token"], Literal["refresh_token"]] + valid_request_methods: tuple[Literal["POST"]] + request_validator: RequestValidator + supported_token_types: tuple[str, ...] + def __init__(self, request_validator: RequestValidator, supported_token_types: tuple[str, ...] | None = None) -> None: ... + def create_revocation_response( + self, uri: str, http_method: _HTTPMethod = "POST", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], str, int]: ... + def validate_revocation_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi index d67373a63607..421ff886a122 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi @@ -1,28 +1,32 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger +from typing import Literal -from .base import BaseEndpoint as BaseEndpoint +from oauthlib.common import Request, _HTTPMethod -log: Any +from .base import BaseEndpoint + +log: Logger class TokenEndpoint(BaseEndpoint): - valid_request_methods: Any - def __init__(self, default_grant_type, default_token_type, grant_types) -> None: ... + valid_request_methods: tuple[Literal["POST"]] + def __init__(self, default_grant_type: str, default_token_type: str, grant_types: dict[str, Incomplete]) -> None: ... @property - def grant_types(self): ... + def grant_types(self) -> dict[str, Incomplete]: ... @property - def default_grant_type(self): ... + def default_grant_type(self) -> str: ... @property def default_grant_type_handler(self): ... @property - def default_token_type(self): ... + def default_token_type(self) -> str: ... def create_token_response( self, - uri, - http_method: str = ..., - body: Any | None = ..., - headers: Any | None = ..., - credentials: Any | None = ..., - grant_type_for_scope: Any | None = ..., - claims: Any | None = ..., + uri: str, + http_method: _HTTPMethod = "POST", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: dict[str, str] | None = None, + credentials=None, + grant_type_for_scope=None, + claims=None, ): ... - def validate_token_request(self, request) -> None: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi index f45eb1566ba6..d76eea7373a8 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi @@ -1,34 +1,37 @@ -from typing import Any +from _typeshed import Incomplete +from typing_extensions import Never + +from oauthlib.common import Request class OAuth2Error(Exception): - error: Any + error: str | None status_code: int description: str - uri: Any - state: Any - redirect_uri: Any - client_id: Any - scopes: Any - response_type: Any - response_mode: Any - grant_type: Any + uri: str | None + state: str | None + redirect_uri: str | None + client_id: str | None + scopes: Incomplete | None + response_type: str | None + response_mode: str | None + grant_type: str | None def __init__( self, - description: Any | None = ..., - uri: Any | None = ..., - state: Any | None = ..., - status_code: Any | None = ..., - request: Any | None = ..., + description: str | None = None, + uri: str | None = None, + state: str | None = None, + status_code: int | None = None, + request: Request | None = None, ) -> None: ... - def in_uri(self, uri): ... + def in_uri(self, uri: str) -> str: ... @property - def twotuples(self): ... + def twotuples(self) -> list[tuple[str, str | None]]: ... @property - def urlencoded(self): ... + def urlencoded(self) -> str: ... @property - def json(self): ... + def json(self) -> str: ... @property - def headers(self): ... + def headers(self) -> dict[str, str]: ... class TokenExpiredError(OAuth2Error): error: str @@ -134,7 +137,14 @@ class LoginRequired(OAuth2Error): error: str class CustomOAuth2Error(OAuth2Error): - error: Any - def __init__(self, error, *args, **kwargs) -> None: ... + def __init__( + self, + error: str, + description: str | None = None, + uri: str | None = None, + state: str | None = None, + status_code: int | None = None, + request: Request | None = None, + ) -> None: ... -def raise_from_error(error, params: Any | None = ...) -> None: ... +def raise_from_error(error: str, params: dict[str, Incomplete] | None = None) -> Never: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi index 28cd3018e7fc..560dd3d63abf 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi @@ -1,18 +1,24 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request -log: Any +from ..tokens import TokenBase +from .base import GrantTypeBase -def code_challenge_method_s256(verifier, challenge): ... -def code_challenge_method_plain(verifier, challenge): ... +log: Logger + +def code_challenge_method_s256(verifier: str, challenge: str) -> bool: ... +def code_challenge_method_plain(verifier: str, challenge: str) -> bool: ... class AuthorizationCodeGrant(GrantTypeBase): default_response_mode: str - response_types: Any - def create_authorization_code(self, request): ... - def create_authorization_response(self, request, token_handler): ... - def create_token_response(self, request, token_handler): ... - def validate_authorization_request(self, request): ... - def validate_token_request(self, request) -> None: ... - def validate_code_challenge(self, challenge, challenge_method, verifier): ... + response_types: list[str] + def create_authorization_code(self, request: Request) -> dict[str, str]: ... + def create_authorization_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], None, int | None]: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_authorization_request(self, request: Request) -> tuple[Incomplete, dict[str, Incomplete]]: ... + def validate_token_request(self, request: Request) -> None: ... + def validate_code_challenge(self, challenge: str, challenge_method: str, verifier: str) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi index ba8171b0111f..d5d2fa144b45 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi @@ -1,31 +1,70 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from itertools import chain +from logging import Logger +from typing import TypeAlias, TypeVar -log: Any +from oauthlib.common import Request + +from ..request_validator import RequestValidator +from ..tokens import TokenBase + +log: Logger + +_T = TypeVar("_T") +_AuthValidator: TypeAlias = Callable[[Request], dict[str, Incomplete]] +_TokenValidator: TypeAlias = Callable[[Request], None] +_CodeModifier: TypeAlias = Callable[[dict[str, str], TokenBase | None, Request | None], dict[str, str]] +_TokenModifier: TypeAlias = Callable[[dict[str, Incomplete], TokenBase | None, Request | None], dict[str, Incomplete]] class ValidatorsContainer: - pre_auth: Any - post_auth: Any - pre_token: Any - post_token: Any - def __init__(self, post_auth, post_token, pre_auth, pre_token) -> None: ... + pre_auth: Iterable[_AuthValidator] + post_auth: Iterable[_AuthValidator] + pre_token: Iterable[_TokenValidator] + post_token: Iterable[_TokenValidator] + def __init__( + self, + post_auth: Iterable[_AuthValidator], + post_token: Iterable[_TokenValidator], + pre_auth: Iterable[_AuthValidator], + pre_token: Iterable[_TokenValidator], + ) -> None: ... @property - def all_pre(self): ... + def all_pre(self) -> chain[_AuthValidator | _TokenValidator]: ... @property - def all_post(self): ... + def all_post(self) -> chain[_AuthValidator | _TokenValidator]: ... class GrantTypeBase: - error_uri: Any - request_validator: Any + error_uri: str | None + request_validator: RequestValidator | None default_response_mode: str refresh_token: bool - response_types: Any - def __init__(self, request_validator: Any | None = ..., **kwargs) -> None: ... - def register_response_type(self, response_type) -> None: ... - def register_code_modifier(self, modifier) -> None: ... - def register_token_modifier(self, modifier) -> None: ... - def create_authorization_response(self, request, token_handler) -> None: ... - def create_token_response(self, request, token_handler) -> None: ... - def add_token(self, token, token_handler, request): ... - def validate_grant_type(self, request) -> None: ... - def validate_scopes(self, request) -> None: ... - def prepare_authorization_response(self, request, token, headers, body, status): ... + response_types: list[str] + def __init__( + self, + request_validator: RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def register_response_type(self, response_type: str) -> None: ... + def register_code_modifier(self, modifier: _CodeModifier) -> None: ... + def register_token_modifier(self, modifier: _TokenModifier) -> None: ... + def create_authorization_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], str | None, int | None]: ... + def create_token_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], str | None, int | None]: ... + def add_token(self, token: dict[str, _T], token_handler: TokenBase, request: Request) -> dict[str, _T]: ... + def validate_grant_type(self, request: Request) -> None: ... + def validate_scopes(self, request: Request) -> None: ... + def validate_client_confidential(self, request: Request) -> None: ... + def validate_client_public(self, request: Request) -> None: ... + def validate_client_authentication(self, request: Request) -> None: ... + def prepare_authorization_response( + self, request: Request, token: dict[str, Incomplete], headers: dict[str, str], body: str | None, status: int | None + ) -> tuple[dict[str, str], str | None, int | None]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi index 0d33d8298c1a..d500ef4d4655 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi @@ -1,9 +1,12 @@ -from typing import Any +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request -log: Any +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger class ClientCredentialsGrant(GrantTypeBase): - def create_token_response(self, request, token_handler): ... - def validate_token_request(self, request) -> None: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi index 613ac0a050d0..e17902e4b361 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi @@ -1,13 +1,19 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request -log: Any +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger class ImplicitGrant(GrantTypeBase): - response_types: Any + response_types: list[str] grant_allows_refresh_token: bool - def create_authorization_response(self, request, token_handler): ... - def create_token_response(self, request, token_handler): ... - def validate_authorization_request(self, request): ... - def validate_token_request(self, request): ... + def create_authorization_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], str | None, int]: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str | None, int]: ... + def validate_authorization_request(self, request: Request) -> tuple[Incomplete, dict[str, Incomplete]]: ... + def validate_token_request(self, request: Request) -> tuple[Incomplete, dict[str, Incomplete]]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi index 1b590f46f1d4..6d26d66cba39 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi @@ -1,10 +1,25 @@ -from typing import Any +from collections.abc import Iterable +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request -log: Any +from ..request_validator import RequestValidator +from ..tokens import TokenBase +from .base import GrantTypeBase, _AuthValidator, _TokenValidator + +log: Logger class RefreshTokenGrant(GrantTypeBase): - def __init__(self, request_validator: Any | None = ..., issue_new_refresh_tokens: bool = ..., **kwargs) -> None: ... - def create_token_response(self, request, token_handler): ... - def validate_token_request(self, request) -> None: ... + def __init__( + self, + request_validator: RequestValidator | None = None, + issue_new_refresh_tokens: bool = True, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi index 347fa4569b5e..ad407436f188 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi @@ -1,9 +1,12 @@ -from typing import Any +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request -log: Any +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger class ResourceOwnerPasswordCredentialsGrant(GrantTypeBase): - def create_token_response(self, request, token_handler): ... - def validate_token_request(self, request) -> None: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi index 2bc064f027a0..00f13e7f3f07 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi @@ -1,13 +1,45 @@ -from typing import Any +from _typeshed import Incomplete +from typing import Literal + +from .tokens import OAuth2Token def prepare_grant_uri( - uri, client_id, response_type, redirect_uri: Any | None = ..., scope: Any | None = ..., state: Any | None = ..., **kwargs -): ... -def prepare_token_request(grant_type, body: str = ..., include_client_id: bool = ..., **kwargs): ... + uri: str, + client_id: str, + response_type: Literal["code", "token"], + redirect_uri: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = "plain", + **kwargs, +) -> str: ... +def prepare_token_request( + grant_type: str, + body: str = "", + include_client_id: bool = True, + code_verifier: str | None = None, + *, + scope: str | set[object] | tuple[object] | list[object] | None = None, + client_id: str | None = None, + client_secret: str | None = None, + code: str | None = None, + redirect_uri: str | None = None, + **kwargs, +) -> str: ... def prepare_token_revocation_request( - url, token, token_type_hint: str = ..., callback: Any | None = ..., body: str = ..., **kwargs -): ... -def parse_authorization_code_response(uri, state: Any | None = ...): ... -def parse_implicit_response(uri, state: Any | None = ..., scope: Any | None = ...): ... -def parse_token_response(body, scope: Any | None = ...): ... -def validate_token_parameters(params) -> None: ... + url: str, + token: str, + token_type_hint: Literal["access_token", "refresh_token"] | None = "access_token", + body: str = "", + **kwargs, +) -> tuple[str, dict[str, str], str]: ... +def parse_authorization_code_response(uri: str, state: str | None = None) -> dict[str, str]: ... +def parse_implicit_response( + uri: str, state: str | None = None, scope: str | set[object] | tuple[object] | list[object] | None = None +) -> OAuth2Token: ... +def parse_token_response( + body: str | bytes | bytearray, scope: str | set[object] | tuple[object] | list[object] | None = None +) -> OAuth2Token: ... +def validate_token_parameters(params: dict[str, Incomplete]) -> None: ... +def parse_expires(params: dict[str, Incomplete]) -> tuple[int | None, float | None, float | None]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi index 447fd07502be..4c60b62ec170 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi @@ -1,32 +1,62 @@ -from typing import Any +from collections.abc import Mapping +from logging import Logger +from typing import Literal, TypedDict, type_check_only +from typing_extensions import NotRequired -log: Any +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.clients import Client + +@type_check_only +class _BearerToken(TypedDict): + token_type: Literal["Bearer"] + access_token: str + expires_in: int + scope: NotRequired[str] + refresh_token: NotRequired[str] + state: NotRequired[str] + +@type_check_only +class _AuthorizationCode(TypedDict): + code: str + state: NotRequired[str] + nonce: NotRequired[str] + +log: Logger class RequestValidator: - def client_authentication_required(self, request, *args, **kwargs): ... - def authenticate_client(self, request, *args, **kwargs) -> None: ... - def authenticate_client_id(self, client_id, request, *args, **kwargs) -> None: ... - def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs) -> None: ... - def get_default_redirect_uri(self, client_id, request, *args, **kwargs) -> None: ... - def get_default_scopes(self, client_id, request, *args, **kwargs) -> None: ... - def get_original_scopes(self, refresh_token, request, *args, **kwargs) -> None: ... - def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs): ... - def introspect_token(self, token, token_type_hint, request, *args, **kwargs) -> None: ... - def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs) -> None: ... - def revoke_token(self, token, token_type_hint, request, *args, **kwargs) -> None: ... - def rotate_refresh_token(self, request): ... - def save_authorization_code(self, client_id, code, request, *args, **kwargs) -> None: ... - def save_token(self, token, request, *args, **kwargs): ... - def save_bearer_token(self, token, request, *args, **kwargs) -> None: ... - def validate_bearer_token(self, token, scopes, request) -> None: ... - def validate_client_id(self, client_id, request, *args, **kwargs) -> None: ... - def validate_code(self, client_id, code, client, request, *args, **kwargs) -> None: ... - def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs) -> None: ... - def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs) -> None: ... - def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs) -> None: ... - def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs) -> None: ... - def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs) -> None: ... - def validate_user(self, username, password, client, request, *args, **kwargs) -> None: ... - def is_pkce_required(self, client_id, request): ... - def get_code_challenge(self, code, request) -> None: ... - def get_code_challenge_method(self, code, request) -> None: ... + def client_authentication_required(self, request: Request, *args, **kwargs) -> bool: ... + def authenticate_client(self, request: Request, *args, **kwargs) -> bool: ... + def authenticate_client_id(self, client_id: str, request: Request, *args, **kwargs) -> bool: ... + def confirm_redirect_uri( + self, client_id: str, code: str, redirect_uri: str, client: Client, request: Request, *args, **kwargs + ) -> bool: ... + def get_default_redirect_uri(self, client_id: str, request: Request, *args, **kwargs) -> str: ... + def get_default_scopes(self, client_id: str, request: Request, *args, **kwargs) -> list[str]: ... + def get_original_scopes(self, refresh_token: str, request: Request, *args, **kwargs) -> list[str]: ... + def is_within_original_scope( + self, request_scopes: list[str], refresh_token: str, request: Request, *args, **kwargs + ) -> bool: ... + def introspect_token( + self, token: str, token_type_hint: str, request: Request, *args, **kwargs + ) -> dict[str, int | str | list[str]] | None: ... + def invalidate_authorization_code(self, client_id: str, code: str, request: Request, *args, **kwargs) -> None: ... + def revoke_token(self, token: str, token_type_hint: str, request: Request, *args, **kwargs) -> None: ... + def rotate_refresh_token(self, request: Request) -> bool: ... + def save_authorization_code(self, client_id: str, code: _AuthorizationCode, request: Request, *args, **kwargs) -> None: ... + def save_token(self, token: Mapping[str, object], request: Request, *args, **kwargs) -> object: ... + def save_bearer_token(self, token: _BearerToken, request: Request, *args, **kwargs) -> object: ... + def validate_bearer_token(self, token: str, scopes: list[str], request: Request) -> bool: ... + def validate_client_id(self, client_id: str, request: Request, *args, **kwargs) -> bool: ... + def validate_code(self, client_id: str, code: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_grant_type(self, client_id: str, grant_type: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_redirect_uri(self, client_id: str, redirect_uri: str, request: Request, *args, **kwargs) -> bool: ... + def validate_refresh_token(self, refresh_token: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_response_type( + self, client_id: str, response_type: str, client: Client, request: Request, *args, **kwargs + ) -> bool: ... + def validate_scopes(self, client_id: str, scopes: list[str], client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_user(self, username: str, password: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def is_pkce_required(self, client_id: str, request: Request) -> bool: ... + def get_code_challenge(self, code: str, request: Request) -> str: ... + def get_code_challenge_method(self, code: str, request: Request) -> str: ... + def is_origin_allowed(self, client_id: str, origin, request: Request, *args, **kwargs) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi index c11b07b2d41d..d55acfe0f56f 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi @@ -1,59 +1,69 @@ -from typing import Any, Dict +import datetime +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Literal -class OAuth2Token(Dict[Any, Any]): - def __init__(self, params, old_scope: Any | None = ...) -> None: ... +from oauthlib.common import Request, _HTTPMethod +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator + +class OAuth2Token(dict[str, Incomplete]): + def __init__( + self, params: dict[str, Incomplete], old_scope: str | set[object] | tuple[object] | list[object] | None = None + ) -> None: ... @property - def scope_changed(self): ... + def scope_changed(self) -> bool: ... @property - def old_scope(self): ... + def old_scope(self) -> str | None: ... @property - def old_scopes(self): ... + def old_scopes(self) -> list[str]: ... @property - def scope(self): ... + def scope(self) -> str | None: ... @property - def scopes(self): ... + def scopes(self) -> list[str]: ... @property - def missing_scopes(self): ... + def missing_scopes(self) -> list[str]: ... @property - def additional_scopes(self): ... + def additional_scopes(self) -> list[str]: ... def prepare_mac_header( - token, - uri, - key, - http_method, - nonce: Any | None = ..., - headers: Any | None = ..., - body: Any | None = ..., - ext: str = ..., - hash_algorithm: str = ..., - issue_time: Any | None = ..., - draft: int = ..., -): ... -def prepare_bearer_uri(token, uri): ... -def prepare_bearer_headers(token, headers: Any | None = ...): ... -def prepare_bearer_body(token, body: str = ...): ... -def random_token_generator(request, refresh_token: bool = ...): ... -def signed_token_generator(private_pem, **kwargs): ... -def get_token_from_header(request): ... + token: str, + uri: str, + key: str | bytes | bytearray, + http_method: _HTTPMethod, + nonce: str | None = None, + headers: dict[str, str] | None = None, + body: str | None = None, + ext: str = "", + hash_algorithm: str = "hmac-sha-1", + issue_time: datetime.datetime | None = None, + draft: int = 0, +) -> dict[str, str]: ... +def prepare_bearer_uri(token: str, uri: str) -> str: ... +def prepare_bearer_headers(token: str, headers: dict[str, str] | None = None) -> dict[str, str]: ... +def prepare_bearer_body(token: str, body: str = "") -> str: ... +def random_token_generator(request: Request, refresh_token: bool = False) -> str: ... +def signed_token_generator(private_pem: str, **kwargs) -> Callable[[Request], str]: ... +def get_token_from_header(request: Request) -> str | None: ... class TokenBase: - def __call__(self, request, refresh_token: bool = ...) -> None: ... - def validate_request(self, request) -> None: ... - def estimate_type(self, request) -> None: ... + __slots__ = () + def __call__(self, request: Request, refresh_token: bool = False) -> None: ... + def validate_request(self, request: Request) -> bool: ... + def estimate_type(self, request: Request) -> int: ... class BearerToken(TokenBase): - request_validator: Any - token_generator: Any - refresh_token_generator: Any - expires_in: Any + __slots__ = ("request_validator", "token_generator", "refresh_token_generator", "expires_in") + request_validator: RequestValidator | None + token_generator: Callable[[Request], str] + refresh_token_generator: Callable[[Request], str] + expires_in: int | Callable[[Request], int] def __init__( self, - request_validator: Any | None = ..., - token_generator: Any | None = ..., - expires_in: Any | None = ..., - refresh_token_generator: Any | None = ..., + request_validator: RequestValidator | None = None, + token_generator: Callable[[Request], str] | None = None, + expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, ) -> None: ... - def create_token(self, request, refresh_token: bool = ..., **kwargs): ... - def validate_request(self, request): ... - def estimate_type(self, request): ... + def create_token(self, request: Request, refresh_token: bool = False, **kwargs) -> OAuth2Token: ... + def validate_request(self, request: Request) -> bool: ... + def estimate_type(self, request: Request) -> Literal[9, 5, 0]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi index dc660b791580..97f51aa733ac 100644 --- a/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi @@ -1,7 +1,18 @@ -def list_to_scope(scope): ... -def scope_to_list(scope): ... -def params_from_uri(uri): ... -def host_from_uri(uri): ... -def escape(u): ... -def generate_age(issue_time): ... -def is_secure_transport(uri): ... +import datetime +from typing import overload + +@overload +def list_to_scope(scope: None) -> None: ... +@overload +def list_to_scope(scope: str | set[object] | tuple[object] | list[object]) -> str: ... + +@overload +def scope_to_list(scope: None) -> None: ... +@overload +def scope_to_list(scope: str | set[object] | tuple[object] | list[object]) -> list[str]: ... + +def params_from_uri(uri: str) -> dict[str, str | list[str]]: ... +def host_from_uri(uri: str) -> tuple[str, str | None]: ... +def escape(u: str) -> str: ... +def generate_age(issue_time: datetime.datetime | datetime.timedelta) -> str: ... +def is_secure_transport(uri: str) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi new file mode 100644 index 000000000000..8963764427d2 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi @@ -0,0 +1,9 @@ +from logging import Logger + +from .errors import ( + AuthorizationPendingError as AuthorizationPendingError, + ExpiredTokenError as ExpiredTokenError, + SlowDownError as SlowDownError, +) + +log: Logger diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi new file mode 100644 index 000000000000..e03f44a720ca --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi @@ -0,0 +1 @@ +from .device import DeviceClient as DeviceClient diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi new file mode 100644 index 000000000000..e7919258117d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from oauthlib.oauth2.rfc6749.clients.base import Client, _TokenPlacement + +class DeviceClient(Client): + grant_type: str + client_secret: str | None + def __init__( + self, + client_id: str, + *, + client_secret: str | None = None, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_uri( + self, uri: str, scope: str | set[object] | tuple[object] | list[object] | None = None, **kwargs + ) -> str: ... + def prepare_request_body( + self, + device_code: str, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi new file mode 100644 index 000000000000..65712957c40d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi @@ -0,0 +1,2 @@ +from .device_authorization import DeviceAuthorizationEndpoint as DeviceAuthorizationEndpoint +from .pre_configured import DeviceApplicationServer as DeviceApplicationServer diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi new file mode 100644 index 000000000000..ee67416c128a --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable +from logging import Logger + +from oauthlib.common import Request, _HTTPMethod +from oauthlib.oauth2.rfc6749.endpoints.base import BaseEndpoint +from oauthlib.openid.connect.core.request_validator import RequestValidator + +log: Logger + +class DeviceAuthorizationEndpoint(BaseEndpoint): + request_validator: RequestValidator + user_code_generator: Callable[[None], str] | None + def __init__( + self, + request_validator: RequestValidator, + verification_uri: str, + expires_in: int = 1800, + interval: int | None = None, + verification_uri_complete: str | None = None, + user_code_generator: Callable[[None], str] | None = None, + ) -> None: ... + @property + def interval(self) -> int | None: ... + @property + def expires_in(self) -> int: ... + @property + def verification_uri(self) -> str: ... + def verification_uri_complete(self, user_code: str) -> str | None: ... + def validate_device_authorization_request(self, request: Request) -> None: ... + def create_device_authorization_response( + self, uri: str, http_method: _HTTPMethod = "POST", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], dict[str, str | int], int]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi new file mode 100644 index 000000000000..943520667914 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable + +from oauthlib.openid.connect.core.request_validator import RequestValidator + +from .device_authorization import DeviceAuthorizationEndpoint + +class DeviceApplicationServer(DeviceAuthorizationEndpoint): + def __init__( + self, + request_validator: RequestValidator, + verification_uri: str, + interval: int = 5, + verification_uri_complete: str | None = None, + user_code_generator: Callable[[None], str] | None = None, + **kwargs, + ) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi new file mode 100644 index 000000000000..9858cb379e23 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi @@ -0,0 +1,13 @@ +from oauthlib.oauth2.rfc6749.errors import OAuth2Error + +class AuthorizationPendingError(OAuth2Error): + error: str + +class SlowDownError(OAuth2Error): + error: str + +class ExpiredTokenError(OAuth2Error): + error: str + +class AccessDenied(OAuth2Error): + error: str diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi new file mode 100644 index 000000000000..6163747ce035 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi @@ -0,0 +1 @@ +from .device_code import DeviceCodeGrant as DeviceCodeGrant diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi new file mode 100644 index 000000000000..0f70cb3b542b --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi @@ -0,0 +1,8 @@ +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.base import GrantTypeBase +from oauthlib.oauth2.rfc6749.tokens import TokenBase + +class DeviceCodeGrant(GrantTypeBase): + def create_authorization_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int]: ... + def validate_token_request(self, request: Request) -> None: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi new file mode 100644 index 000000000000..9fa7b042c5a0 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi @@ -0,0 +1,5 @@ +from oauthlib.common import Request +from oauthlib.oauth2 import RequestValidator as OAuth2RequestValidator + +class RequestValidator(OAuth2RequestValidator): + def client_authentication_required(self, request: Request, *args, **kwargs) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi index 6d3d4e5ca33f..379d9cd847bf 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi @@ -1,35 +1,54 @@ -from typing import Any +from _typeshed import Unused +from collections.abc import Callable +from oauthlib.common import Request from oauthlib.oauth2.rfc6749.endpoints import ( - AuthorizationEndpoint as AuthorizationEndpoint, - IntrospectEndpoint as IntrospectEndpoint, - ResourceEndpoint as ResourceEndpoint, - RevocationEndpoint as RevocationEndpoint, - TokenEndpoint as TokenEndpoint, + AuthorizationEndpoint, + IntrospectEndpoint, + ResourceEndpoint, + RevocationEndpoint, + TokenEndpoint, ) +from oauthlib.oauth2.rfc6749.grant_types import ( + AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant as OAuth2ImplicitGrant, + RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator +from oauthlib.oauth2.rfc6749.tokens import BearerToken +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant -from .userinfo import UserInfoEndpoint as UserInfoEndpoint +from ..grant_types import AuthorizationCodeGrant, HybridGrant, ImplicitGrant +from ..grant_types.dispatchers import ( + AuthorizationCodeGrantDispatcher, + AuthorizationTokenGrantDispatcher, + ImplicitTokenGrantDispatcher, +) +from ..tokens import JWTToken +from .userinfo import UserInfoEndpoint class Server(AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint, UserInfoEndpoint): - auth_grant: Any - implicit_grant: Any - password_grant: Any - credentials_grant: Any - refresh_grant: Any - openid_connect_auth: Any - openid_connect_implicit: Any - openid_connect_hybrid: Any - bearer: Any - jwt: Any - auth_grant_choice: Any - implicit_grant_choice: Any - token_grant_choice: Any + auth_grant: OAuth2AuthorizationCodeGrant + implicit_grant: OAuth2ImplicitGrant + password_grant: ResourceOwnerPasswordCredentialsGrant + credentials_grant: ClientCredentialsGrant + refresh_grant: RefreshTokenGrant + openid_connect_auth: AuthorizationCodeGrant + openid_connect_implicit: ImplicitGrant + openid_connect_hybrid: HybridGrant + device_code_grant: DeviceCodeGrant + bearer: BearerToken + jwt: JWTToken + auth_grant_choice: AuthorizationCodeGrantDispatcher + implicit_grant_choice: ImplicitTokenGrantDispatcher + token_grant_choice: AuthorizationTokenGrantDispatcher def __init__( self, - request_validator, - token_expires_in: Any | None = ..., - token_generator: Any | None = ..., - refresh_token_generator: Any | None = ..., - *args, - **kwargs, + request_validator: OAuth2RequestValidator, + token_expires_in: int | Callable[[Request], int] | None = None, + token_generator: Callable[[Request], str] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + *args: Unused, ) -> None: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi index 09a098501abe..13a8d4826a71 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi @@ -1,12 +1,22 @@ -from typing import Any +from collections.abc import Mapping +from logging import Logger -from oauthlib.oauth2.rfc6749.endpoints.base import BaseEndpoint as BaseEndpoint +from oauthlib.common import Request, _HTTPMethod +from oauthlib.oauth2.rfc6749.endpoints.base import BaseEndpoint +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator +from oauthlib.oauth2.rfc6749.tokens import BearerToken -log: Any +log: Logger class UserInfoEndpoint(BaseEndpoint): - bearer: Any - request_validator: Any - def __init__(self, request_validator) -> None: ... - def create_userinfo_response(self, uri, http_method: str = ..., body: Any | None = ..., headers: Any | None = ...): ... - def validate_userinfo_request(self, request) -> None: ... + bearer: BearerToken + request_validator: OAuth2RequestValidator + def __init__(self, request_validator: OAuth2RequestValidator) -> None: ... + def create_userinfo_response( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: Mapping[str, str] | None = None, + ) -> tuple[dict[str, str], str, int]: ... + def validate_userinfo_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi index 0a64f1be9e3e..b552251df96a 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi @@ -1,6 +1,4 @@ -from typing import Any - -from oauthlib.oauth2.rfc6749.errors import FatalClientError as FatalClientError, OAuth2Error as OAuth2Error +from oauthlib.oauth2.rfc6749.errors import FatalClientError, OAuth2Error class FatalOpenIDClientError(FatalClientError): ... class OpenIDClientError(OAuth2Error): ... @@ -50,4 +48,4 @@ class InsufficientScopeError(OAuth2Error): status_code: int description: str -def raise_from_error(error, params: Any | None = ...) -> None: ... +def raise_from_error(error: object, params: dict[str, str] | None = None) -> None: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi index 1d5a9ac620c7..9d15b72bbf98 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi @@ -7,3 +7,4 @@ from .dispatchers import ( ) from .hybrid import HybridGrant as HybridGrant from .implicit import ImplicitGrant as ImplicitGrant +from .refresh_token import RefreshTokenGrant as RefreshTokenGrant diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi index 5e61d966c673..ff419e356d09 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi @@ -1,10 +1,25 @@ -from typing import Any +from collections.abc import Iterable +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator -log: Any +from .base import GrantTypeBase + +log: Logger class AuthorizationCodeGrant(GrantTypeBase): - proxy_target: Any - def __init__(self, request_validator: Any | None = ..., **kwargs) -> None: ... - def add_id_token(self, token, token_handler, request): ... + proxy_target: OAuth2AuthorizationCodeGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi index 5ccdd7e76721..c7c3039277b3 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi @@ -1,13 +1,19 @@ -from typing import Any +from _hashlib import HASH +from collections.abc import Callable +from logging import Logger -log: Any +from oauthlib.common import Request + +log: Logger class GrantTypeBase: - def __getattr__(self, attr): ... - def __setattr__(self, attr, value) -> None: ... - def validate_authorization_request(self, request): ... - def id_token_hash(self, value, hashfunc=...): ... - def add_id_token(self, token, token_handler, request, nonce: Any | None = ...): ... - def openid_authorization_validator(self, request): ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def validate_authorization_request(self, request: Request): ... + def id_token_hash( + self, value: str, hashfunc: Callable[..., HASH] = ... # Arguments: ReadableBuffer (string) and bool (usedforsecurity) + ) -> str: ... + def add_id_token(self, token, token_handler, request: Request, nonce=None): ... + def openid_authorization_validator(self, request: Request): ... OpenIDConnectBase = GrantTypeBase diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi index 39673c0dba23..67428ed7d1e8 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi @@ -1,28 +1,32 @@ -from typing import Any +from _typeshed import Incomplete +from logging import Logger -log: Any +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +log: Logger class Dispatcher: - default_grant: Any - oidc_grant: Any + default_grant: Incomplete | None + oidc_grant: Incomplete | None class AuthorizationCodeGrantDispatcher(Dispatcher): - default_grant: Any - oidc_grant: Any - def __init__(self, default_grant: Any | None = ..., oidc_grant: Any | None = ...) -> None: ... - def create_authorization_response(self, request, token_handler): ... - def validate_authorization_request(self, request): ... + default_grant: Incomplete | None + oidc_grant: Incomplete | None + def __init__(self, default_grant=None, oidc_grant=None) -> None: ... + def create_authorization_response(self, request: Request, token_handler): ... + def validate_authorization_request(self, request: Request): ... class ImplicitTokenGrantDispatcher(Dispatcher): - default_grant: Any - oidc_grant: Any - def __init__(self, default_grant: Any | None = ..., oidc_grant: Any | None = ...) -> None: ... - def create_authorization_response(self, request, token_handler): ... - def validate_authorization_request(self, request): ... + default_grant: Incomplete | None + oidc_grant: Incomplete | None + def __init__(self, default_grant=None, oidc_grant=None) -> None: ... + def create_authorization_response(self, request: Request, token_handler): ... + def validate_authorization_request(self, request: Request): ... class AuthorizationTokenGrantDispatcher(Dispatcher): - default_grant: Any - oidc_grant: Any - request_validator: Any - def __init__(self, request_validator, default_grant: Any | None = ..., oidc_grant: Any | None = ...) -> None: ... - def create_token_response(self, request, token_handler): ... + default_grant: Incomplete | None + oidc_grant: Incomplete | None + request_validator: OAuth2RequestValidator + def __init__(self, request_validator: OAuth2RequestValidator, default_grant=None, oidc_grant=None) -> None: ... + def create_token_response(self, request: Request, token_handler): ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi index d04ed913c3da..58532a495671 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi @@ -1,15 +1,29 @@ -from typing import Any +from collections.abc import Iterable +from logging import Logger +from oauthlib.common import Request from oauthlib.oauth2.rfc6749.errors import InvalidRequestError as InvalidRequestError +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator -from ..request_validator import RequestValidator as RequestValidator -from .base import GrantTypeBase as GrantTypeBase +from ..request_validator import RequestValidator +from .base import GrantTypeBase -log: Any +log: Logger class HybridGrant(GrantTypeBase): - request_validator: Any - proxy_target: Any - def __init__(self, request_validator: Any | None = ..., **kwargs) -> None: ... - def add_id_token(self, token, token_handler, request): ... - def openid_authorization_validator(self, request): ... + request_validator: OAuth2RequestValidator | RequestValidator + proxy_target: OAuth2AuthorizationCodeGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] + def openid_authorization_validator(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi index eb3f4a611acb..366627c0b008 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi @@ -1,11 +1,26 @@ -from typing import Any +from collections.abc import Iterable +from logging import Logger -from .base import GrantTypeBase as GrantTypeBase +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.grant_types.implicit import ImplicitGrant as OAuth2ImplicitGrant +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator -log: Any +from .base import GrantTypeBase + +log: Logger class ImplicitGrant(GrantTypeBase): - proxy_target: Any - def __init__(self, request_validator: Any | None = ..., **kwargs) -> None: ... - def add_id_token(self, token, token_handler, request): ... - def openid_authorization_validator(self, request): ... + proxy_target: OAuth2ImplicitGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] + def openid_authorization_validator(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi new file mode 100644 index 000000000000..b9b953ebe478 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.grant_types.refresh_token import RefreshTokenGrant as OAuth2RefreshTokenGrant +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +from .base import GrantTypeBase + +log: Logger + +class RefreshTokenGrant(GrantTypeBase): + proxy_target: OAuth2RefreshTokenGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi index 6790cf455374..ca6de4bf5752 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi @@ -1,18 +1,24 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable +from logging import Logger +from oauthlib.common import Request from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator -log: Any +log: Logger class RequestValidator(OAuth2RequestValidator): - def get_authorization_code_scopes(self, client_id, code, redirect_uri, request) -> None: ... - def get_authorization_code_nonce(self, client_id, code, redirect_uri, request) -> None: ... - def get_jwt_bearer_token(self, token, token_handler, request) -> None: ... - def get_id_token(self, token, token_handler, request) -> None: ... - def finalize_id_token(self, id_token, token, token_handler, request) -> None: ... - def validate_jwt_bearer_token(self, token, scopes, request) -> None: ... - def validate_id_token(self, token, scopes, request) -> None: ... - def validate_silent_authorization(self, request) -> None: ... - def validate_silent_login(self, request) -> None: ... - def validate_user_match(self, id_token_hint, scopes, claims, request) -> None: ... - def get_userinfo_claims(self, request) -> None: ... + def get_authorization_code_scopes(self, client_id: str, code: str, redirect_uri: str, request) -> list[str]: ... + def get_authorization_code_nonce(self, client_id: str, code: str, redirect_uri: str, request) -> str: ... + def get_jwt_bearer_token(self, token: dict[str, Incomplete], token_handler, request: Request) -> str: ... + def get_id_token(self, token: dict[str, Incomplete], token_handler, request: Request) -> str: ... + def finalize_id_token( + self, id_token: dict[str, Incomplete], token: dict[str, Incomplete], token_handler: Callable[..., str], request: Request + ) -> str: ... + def validate_jwt_bearer_token(self, token: str, scopes, request: Request) -> bool: ... + def validate_id_token(self, token: str, scopes, request: Request) -> bool: ... + def validate_silent_authorization(self, request: Request) -> bool: ... + def validate_silent_login(self, request: Request) -> bool: ... + def validate_user_match(self, id_token_hint: str, scopes, claims: dict[str, Incomplete], request: Request) -> bool: ... + def get_userinfo_claims(self, request: Request) -> dict[str, Incomplete] | str: ... + def refresh_id_token(self, request: Request) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi index b78dc4c9761f..39c52b1d0753 100644 --- a/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi +++ b/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi @@ -1,19 +1,23 @@ -from typing import Any +from collections.abc import Callable +from oauthlib.common import Request from oauthlib.oauth2.rfc6749.tokens import TokenBase as TokenBase +from .request_validator import RequestValidator + class JWTToken(TokenBase): - request_validator: Any - token_generator: Any - refresh_token_generator: Any - expires_in: Any + __slots__ = ("request_validator", "token_generator", "refresh_token_generator", "expires_in") + request_validator: RequestValidator + token_generator: Callable[[Request], str] | Callable[[Request, bool], str] + refresh_token_generator: Callable[[Request], str] | Callable[[Request, bool], str] + expires_in: int | Callable[[Request], int] def __init__( self, - request_validator: Any | None = ..., - token_generator: Any | None = ..., - expires_in: Any | None = ..., - refresh_token_generator: Any | None = ..., + request_validator: RequestValidator | None = None, + token_generator: Callable[[Request], str] | None = None, + expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, ) -> None: ... - def create_token(self, request, refresh_token: bool = ...): ... - def validate_request(self, request): ... - def estimate_type(self, request): ... + def create_token(self, request: Request, refresh_token: bool = False): ... + def validate_request(self, request: Request): ... + def estimate_type(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/signals.pyi b/stubs/oauthlib/oauthlib/signals.pyi index 90f27eeee409..e24c057315a5 100644 --- a/stubs/oauthlib/oauthlib/signals.pyi +++ b/stubs/oauthlib/oauthlib/signals.pyi @@ -1,20 +1,20 @@ -from typing import Any +from _typeshed import Incomplete signals_available: bool class Namespace: - def signal(self, name, doc: Any | None = ...): ... + def signal(self, name: str, doc: str | None = None) -> _FakeSignal: ... class _FakeSignal: - name: Any - __doc__: Any - def __init__(self, name, doc: Any | None = ...) -> None: ... - send: Any - connect: Any - disconnect: Any - has_receivers_for: Any - receivers_for: Any - temporarily_connected_to: Any - connected_to: Any + name: str + __doc__: str | None + def __init__(self, name: str, doc: str | None = None) -> None: ... + send: Incomplete + connect: Incomplete + disconnect: Incomplete + has_receivers_for: Incomplete + receivers_for: Incomplete + temporarily_connected_to: Incomplete + connected_to: Incomplete -scope_changed: Any +scope_changed: _FakeSignal diff --git a/stubs/oauthlib/oauthlib/uri_validate.pyi b/stubs/oauthlib/oauthlib/uri_validate.pyi index de635c865f24..f4f90ea4c9f1 100644 --- a/stubs/oauthlib/oauthlib/uri_validate.pyi +++ b/stubs/oauthlib/oauthlib/uri_validate.pyi @@ -1,43 +1,44 @@ -from typing import Any +import re +from typing import Final -DIGIT: str -ALPHA: str -HEXDIG: str -pct_encoded: Any -unreserved: Any -gen_delims: str -sub_delims: str -pchar: Any -reserved: Any -scheme: Any -dec_octet: Any -IPv4address: Any -IPv6address: str -IPvFuture: Any -IP_literal: Any -reg_name: Any -userinfo: Any -host: Any -port: Any -authority: Any -segment: Any -segment_nz: Any -segment_nz_nc: Any -path_abempty: Any -path_absolute: Any -path_noscheme: Any -path_rootless: Any -path_empty: str -path: Any -query: Any -fragment: Any -hier_part: Any -relative_part: Any -relative_ref: Any -URI: Any -URI_reference: Any -absolute_URI: Any +DIGIT: Final[str] +ALPHA: Final[str] +HEXDIG: Final[str] +pct_encoded: Final[str] +unreserved: Final[str] +gen_delims: Final[str] +sub_delims: Final[str] +pchar: Final[str] +reserved: Final[str] +scheme: Final[str] +dec_octet: Final[str] +IPv4address: Final[str] +IPv6address: Final[str] +IPvFuture: Final[str] +IP_literal: Final[str] +reg_name: Final[str] +userinfo: Final[str] +host: Final[str] +port: Final[str] +authority: Final[str] +segment: Final[str] +segment_nz: Final[str] +segment_nz_nc: Final[str] +path_abempty: Final[str] +path_absolute: Final[str] +path_noscheme: Final[str] +path_rootless: Final[str] +path_empty: Final[str] +path: Final[str] +query: Final[str] +fragment: Final[str] +hier_part: Final[str] +relative_part: Final[str] +relative_ref: Final[str] +URI: Final[str] +URI_reference: Final[str] +absolute_URI: Final[str] -def is_uri(uri): ... -def is_uri_reference(uri): ... -def is_absolute_uri(uri): ... +def is_uri(uri: str) -> re.Match[str] | None: ... +def is_uri_reference(uri: str) -> re.Match[str] | None: ... +def is_absolute_uri(uri: str) -> re.Match[str] | None: ... diff --git a/stubs/objgraph/METADATA.toml b/stubs/objgraph/METADATA.toml new file mode 100644 index 000000000000..86459e4d5b5b --- /dev/null +++ b/stubs/objgraph/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.7.*" +upstream-repository = "https://github.com/mgedmin/objgraph" diff --git a/stubs/objgraph/objgraph.pyi b/stubs/objgraph/objgraph.pyi new file mode 100644 index 000000000000..02a4946387ea --- /dev/null +++ b/stubs/objgraph/objgraph.pyi @@ -0,0 +1,90 @@ +from _typeshed import Incomplete, SupportsWrite +from collections import defaultdict +from collections.abc import Callable, Container, Iterable +from types import ModuleType +from typing import Final, Literal, TypeAlias, TypeGuard + +IS_INTERACTIVE: bool + +__author__: Final[str] +__copyright__: Final[str] +__license__: Final[str] +__version__: Final[str] +__date__: Final[str] + +# GraphViz has types, but does not include the py.typed file. +# See https://github.com/xflr6/graphviz/pull/180 +_GraphvizSource: TypeAlias = Incomplete +_Filter: TypeAlias = Callable[[object], bool] + +def count(typename: str, objects: Iterable[object] | None = None) -> int: ... +def typestats( + objects: Iterable[object] | None = None, shortnames: bool = True, filter: _Filter | None = None +) -> dict[str, int]: ... +def most_common_types( + limit: int = 10, objects: Iterable[object] | None = None, shortnames: bool = True, filter: _Filter | None = None +) -> list[tuple[str, int]]: ... +def show_most_common_types( + limit: int = 10, + objects: Iterable[object] | None = None, + shortnames: bool = True, + file: SupportsWrite[str] | None = None, + filter: _Filter | None = None, +) -> None: ... +def growth( + limit: int = 10, peak_stats: dict[str, int] = {}, shortnames: bool = True, filter: _Filter | None = None +) -> list[tuple[str, int, int]]: ... +def show_growth( + limit: int = 10, + peak_stats: dict[str, int] | None = None, + shortnames: bool = True, + file: SupportsWrite[str] | None = None, + filter: _Filter | None = None, +) -> None: ... +def get_new_ids( + skip_update: bool = False, + limit: int = 10, + sortby: Literal["old", "current", "new", "deltas"] = "deltas", + shortnames: bool | None = None, + file: SupportsWrite[str] | None = None, +) -> defaultdict[str, set[int]]: ... +def get_leaking_objects(objects: Iterable[object] | None = None) -> list[object]: ... +def by_type(typename: str, objects: Iterable[object] | None = None) -> list[object]: ... +def at(addr: int) -> object: ... +def at_addrs(address_set: Container[int]) -> list[object]: ... +def find_ref_chain(obj: object, predicate: _Filter, max_depth: int = 20, extra_ignore: Iterable[int] = ()) -> list[object]: ... +def find_backref_chain( + obj: object, predicate: _Filter, max_depth: int = 20, extra_ignore: Iterable[int] = () +) -> list[object]: ... +def show_backrefs( + objs: object, + max_depth: int = 3, + extra_ignore: Iterable[int] = (), + filter: _Filter | None = None, + too_many: int = 10, + highlight: object = None, + filename: str | None = None, + extra_info: Callable[[object], str] | None = None, + refcounts: bool = False, + shortnames: bool = True, + output: SupportsWrite[str] | None = None, + extra_node_attrs: Callable[[object], dict[str, str]] | None = None, +) -> _GraphvizSource | None: ... +def show_refs( + objs: object, + max_depth: int = 3, + extra_ignore: Iterable[int] = (), + filter: _Filter | None = None, + too_many: int = 10, + highlight: object = None, + filename: str | None = None, + extra_info: Callable[[object], str] | None = None, + refcounts: bool = False, + shortnames: bool = True, + output: SupportsWrite[str] | None = None, + extra_node_attrs: Callable[[object], dict[str, str]] | None = None, +) -> _GraphvizSource | None: ... +def show_chain( + *chains: list[object], obj: object, predicate: _Filter, max_depth: int = 20, extra_ignore: Iterable[int] = () +) -> None: ... +def is_proper_module(obj: object) -> TypeGuard[ModuleType]: ... diff --git a/stubs/olefile/@tests/stubtest_allowlist.txt b/stubs/olefile/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f3c51d672f96 --- /dev/null +++ b/stubs/olefile/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +olefile.olefile2.* diff --git a/stubs/olefile/METADATA.toml b/stubs/olefile/METADATA.toml new file mode 100644 index 000000000000..63c57f41365d --- /dev/null +++ b/stubs/olefile/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.47.*" +upstream-repository = "https://github.com/decalage2/olefile" diff --git a/stubs/olefile/olefile/__init__.pyi b/stubs/olefile/olefile/__init__.pyi new file mode 100644 index 000000000000..4697cce81955 --- /dev/null +++ b/stubs/olefile/olefile/__init__.pyi @@ -0,0 +1,2 @@ +from .olefile import * +from .olefile import __all__ as __all__, __author__ as __author__, __date__ as __date__, __version__ as __version__ diff --git a/stubs/olefile/olefile/olefile.pyi b/stubs/olefile/olefile/olefile.pyi new file mode 100644 index 000000000000..3790921224bb --- /dev/null +++ b/stubs/olefile/olefile/olefile.pyi @@ -0,0 +1,247 @@ +import array +import datetime +import io +import logging +import traceback +from collections.abc import Sequence +from typing import IO, AnyStr, Generic, TypeAlias +from typing_extensions import Self + +__date__: str +__version__: str +__author__: str + +__all__ = [ + "isOleFile", + "OleFileIO", + "OleMetadata", + "enable_logging", + "MAGIC", + "STGTY_EMPTY", + "STGTY_STREAM", + "STGTY_STORAGE", + "STGTY_ROOT", + "STGTY_PROPERTY", + "STGTY_LOCKBYTES", + "MINIMAL_OLEFILE_SIZE", + "DEFECT_UNSURE", + "DEFECT_POTENTIAL", + "DEFECT_INCORRECT", + "DEFECT_FATAL", + "DEFAULT_PATH_ENCODING", + "MAXREGSECT", + "DIFSECT", + "FATSECT", + "ENDOFCHAIN", + "FREESECT", + "MAXREGSID", + "NOSTREAM", + "UNKNOWN_SIZE", + "WORD_CLSID", + "OleFileIONotClosed", +] + +UINT32: str + +DEFAULT_PATH_ENCODING: str | None + +def get_logger(name: str, level: int = 51) -> logging.Logger: ... + +log: logging.Logger + +def enable_logging() -> None: ... + +MAGIC: bytes + +MAXREGSECT: int +DIFSECT: int +FATSECT: int +ENDOFCHAIN: int +FREESECT: int + +MAXREGSID: int +NOSTREAM: int + +STGTY_EMPTY: int +STGTY_STORAGE: int +STGTY_STREAM: int +STGTY_LOCKBYTES: int +STGTY_PROPERTY: int +STGTY_ROOT: int + +UNKNOWN_SIZE: int + +VT_EMPTY: int +VT_NULL: int +VT_I2: int +VT_I4: int +VT_R4: int +VT_R8: int +VT_CY: int +VT_DATE: int +VT_BSTR: int +VT_DISPATCH: int +VT_ERROR: int +VT_BOOL: int +VT_VARIANT: int +VT_UNKNOWN: int +VT_DECIMAL: int +VT_I1: int +VT_UI1: int +VT_UI2: int +VT_UI4: int +VT_I8: int +VT_UI8: int +VT_INT: int +VT_UINT: int +VT_VOID: int +VT_HRESULT: int +VT_PTR: int +VT_SAFEARRAY: int +VT_CARRAY: int +VT_USERDEFINED: int +VT_LPSTR: int +VT_LPWSTR: int +VT_FILETIME: int +VT_BLOB: int +VT_STREAM: int +VT_STORAGE: int +VT_STREAMED_OBJECT: int +VT_STORED_OBJECT: int +VT_BLOB_OBJECT: int +VT_CF: int +VT_CLSID: int +VT_VECTOR: int + +VT: dict[int, str] + +WORD_CLSID: str +DEFECT_UNSURE: int +DEFECT_POTENTIAL: int +DEFECT_INCORRECT: int +DEFECT_FATAL: int +MINIMAL_OLEFILE_SIZE: int + +def isOleFile(filename: IO[bytes] | bytes | str | None = None, data: bytes | None = None) -> bool: ... +def i8(c: bytes | int) -> int: ... +def i16(c: bytes, o: int = 0) -> int: ... +def i32(c: bytes, o: int = 0) -> int: ... +def _clsid(clsid: bytes) -> str: ... +def filetime2datetime(filetime: int) -> datetime.datetime: ... + +class OleFileError(IOError): ... +class NotOleFileError(OleFileError): ... + +class OleMetadata: + SUMMARY_ATTRIBS: list[str] + DOCSUM_ATTRIBS: list[str] + + def __init__(self) -> None: ... + def parse_properties(self, ole_file: OleFileIO[AnyStr]) -> None: ... + def dump(self) -> None: ... + +class OleFileIONotClosed(RuntimeWarning): + def __init__(self, stack_of_open: traceback.FrameSummary | None = None) -> None: ... + +class OleStream(io.BytesIO): + def __init__( + self, + fp: IO[bytes], + sect: int, + size: int, + offset: int, + sectorsize: int, + fat: list[int], + filesize: int, + olefileio: OleFileIO[AnyStr], + ) -> None: ... + +class OleDirectoryEntry(Generic[AnyStr]): + STRUCT_DIRENTRY: str + DIRENTRY_SIZE: int + clsid: str + + def __init__(self, entry: bytes, sid: int, ole_file: OleFileIO[AnyStr]) -> None: ... + def build_sect_chain(self, ole_file: OleFileIO[AnyStr]) -> None: ... + def build_storage_tree(self) -> None: ... + def append_kids(self, child_sid: int) -> None: ... + def __eq__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __lt__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... + def __ne__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __le__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... + def dump(self, tab: int = 0) -> None: ... + def getmtime(self) -> datetime.datetime | None: ... + def getctime(self) -> datetime.datetime | None: ... + +_Property: TypeAlias = int | str | bytes | bool | None + +class OleFileIO(Generic[AnyStr]): + root: OleDirectoryEntry[AnyStr] | None + + def __init__( + self, + filename: IO[bytes] | AnyStr | None = None, + raise_defects: int = 40, + write_mode: bool = False, + debug: bool = False, + path_encoding: str | None = DEFAULT_PATH_ENCODING, # noqa: Y011 + ) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def _raise_defect( + self, defect_level: int, message: str, exception_type: type[Exception] = OleFileError # noqa: Y011 + ) -> None: ... + def _decode_utf16_str(self, utf16_str: bytes, errors: str = "replace") -> str | bytes: ... + def open(self, filename: IO[bytes] | AnyStr, write_mode: bool = False) -> None: ... + def close(self) -> None: ... + def _close(self, warn: bool = False) -> None: ... + def _check_duplicate_stream(self, first_sect: int, minifat: bool = False) -> None: ... + def dumpfat(self, fat: Sequence[int], firstindex: int = 0) -> None: ... + def dumpsect(self, sector: bytes, firstindex: int = 0) -> None: ... + def sect2array(self, sect: bytes) -> Sequence[int]: ... + def loadfat_sect(self, sect: bytes | array.array[int]) -> int | None: ... + def loadfat(self, header: bytes) -> None: ... + def loadminifat(self) -> None: ... + def getsect(self, sect: int) -> bytes: ... + def write_sect(self, sect: int, data: bytes, padding: bytes = b"\x00") -> None: ... + def _write_mini_sect(self, fp_pos: int, data: bytes, padding: bytes = b"\x00") -> None: ... + def loaddirectory(self, sect: int) -> None: ... + def _load_direntry(self, sid: int) -> OleDirectoryEntry[AnyStr]: ... + def dumpdirectory(self) -> None: ... + def _open(self, start: int, size: int = 0x7FFFFFFF, force_FAT: bool = False) -> OleStream: ... + def _list( + self, + files: list[list[AnyStr]], + prefix: list[AnyStr], + node: OleDirectoryEntry[AnyStr], + streams: bool = True, + storages: bool = False, + ) -> None: ... + def listdir(self, streams: bool = True, storages: bool = False) -> list[list[AnyStr]]: ... + def _find(self, filename: str | Sequence[str]) -> int: ... + def openstream(self, filename: AnyStr | Sequence[AnyStr]) -> OleStream: ... + def _write_mini_stream(self, entry: OleDirectoryEntry[AnyStr], data_to_write: bytes) -> None: ... + def write_stream(self, stream_name: str | Sequence[str], data: bytes) -> None: ... + def get_type(self, filename: AnyStr | Sequence[AnyStr]) -> bool | int: ... + def getclsid(self, filename: AnyStr | Sequence[AnyStr]) -> str: ... + def getmtime(self, filename: AnyStr | Sequence[AnyStr]) -> datetime.datetime | None: ... + def getctime(self, filename: AnyStr | Sequence[AnyStr]) -> datetime.datetime | None: ... + def exists(self, filename: AnyStr | Sequence[AnyStr]) -> bool: ... + def get_size(self, filename: AnyStr | Sequence[AnyStr]) -> int: ... + def get_rootentry_name(self) -> bytes: ... + def getproperties( + self, filename: AnyStr | Sequence[AnyStr], convert_time: bool = False, no_conversion: list[int] | None = None + ) -> dict[int, list[_Property] | _Property]: ... + def _parse_property( + self, s: bytes, offset: int, property_id: int, property_type: int, convert_time: bool, no_conversion: list[int] + ) -> list[_Property] | _Property: ... + def _parse_property_basic( + self, s: bytes, offset: int, property_id: int, property_type: int, convert_time: bool, no_conversion: list[int] + ) -> tuple[_Property, int]: ... + def get_metadata(self) -> OleMetadata: ... + def get_userdefined_properties( + self, filename: AnyStr | Sequence[AnyStr], convert_time: bool = False, no_conversion: list[int] | None = None + ) -> list[dict[str, bytes | int | None]]: ... + +def main() -> None: ... diff --git a/stubs/openpyxl/@tests/stubtest_allowlist.txt b/stubs/openpyxl/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..20c1b03197d2 --- /dev/null +++ b/stubs/openpyxl/@tests/stubtest_allowlist.txt @@ -0,0 +1,183 @@ +# Unintended re-export from star-import +openpyxl.chart.marker.DRAWING_NS +openpyxl.chart.marker.PRESET_COLORS +openpyxl.chart.shapes.DRAWING_NS +openpyxl.chart.shapes.PRESET_COLORS +openpyxl.descriptors.DEBUG + +# The actual runtime definition depends on what else is installed +# (lxml, defusedxml, et_xmlfile) +openpyxl.xml._functions_overloads + +# Requires numpy to be installed +openpyxl.utils.dataframe + +# Fake getters +openpyxl.descriptors.(base.)?Descriptor.__get__ +openpyxl.descriptors.(base.)?MatchPattern.__get__ +openpyxl.descriptors.(base.)?Typed.__get__ +openpyxl.descriptors.nested.EmptyTag.__get__ +openpyxl.descriptors.nested.Nested.__get__ +openpyxl.descriptors.nested.NestedMinMax.__get__ +openpyxl.descriptors.nested.NestedText.__get__ +openpyxl.descriptors.nested.NestedValue.__get__ + +# Stubtest doesn't like generics here +openpyxl\.descriptors\.(base\.)?Bool\.allow_none +openpyxl\.descriptors\.(base\.)?DateTime\.allow_none +openpyxl\.descriptors\.(base\.)?Float\.allow_none +openpyxl\.descriptors\.(base\.)?Integer\.allow_none +openpyxl\.descriptors\.(base\.)?MatchPattern\.allow_none +openpyxl\.descriptors\.(base\.)?Max\.allow_none +openpyxl\.descriptors\.(base\.)?Min\.allow_none +openpyxl\.descriptors\.(base\.)?MinMax\.allow_none +openpyxl\.descriptors\.(base\.)?String\.allow_none +openpyxl\.descriptors\.(base\.)?Typed\.allow_none + +# Inconsistent methods because +# - using the default value results in an error because of the runtime type-guards +# - or, keyword arguments are explicitly specified +openpyxl.cell.cell.Cell.__init__ +openpyxl.cell.cell.WriteOnlyCell +openpyxl.cell.text.PhoneticProperties.__init__ +openpyxl.cell.text.PhoneticText.__init__ +openpyxl.chart.axis._BaseAxis.__init__ +openpyxl.chart.chartspace.ChartSpace.__init__ +openpyxl.chart.chartspace.ExternalData.__init__ +openpyxl.chart.data_source.NumFmt.__init__ +openpyxl.chart.data_source.NumVal.__init__ +openpyxl.chart.marker.DataPoint.__init__ +openpyxl.chart.pivot.PivotSource.__init__ +openpyxl.chartsheet.custom.CustomChartsheetView.__init__ +openpyxl.chartsheet.publish.WebPublishItem.__init__ +openpyxl.comments.comment_sheet.CommentSheet.__init__ +openpyxl.comments.comment_sheet.Properties.__init__ +openpyxl.descriptors.excel.Extension.__init__ +openpyxl.drawing.colors.HSLColor.__init__ +openpyxl.drawing.colors.RGBPercent.__init__ +openpyxl.drawing.colors.SchemeColor.__init__ +openpyxl.drawing.connector.Connection.__init__ +openpyxl.drawing.connector.ConnectorNonVisual.__init__ +openpyxl.drawing.connector.ConnectorShape.__init__ +openpyxl.drawing.connector.Shape.__init__ +openpyxl.drawing.connector.ShapeMeta.__init__ +openpyxl.drawing.effect.AlphaBiLevelEffect.__init__ +openpyxl.drawing.effect.AlphaModulateEffect.__init__ +openpyxl.drawing.effect.AlphaModulateFixedEffect.__init__ +openpyxl.drawing.effect.AlphaReplaceEffect.__init__ +openpyxl.drawing.effect.BiLevelEffect.__init__ +openpyxl.drawing.effect.BlurEffect.__init__ +openpyxl.drawing.effect.ColorChangeEffect.__init__ +openpyxl.drawing.effect.EffectContainer.__init__ +openpyxl.drawing.effect.FillOverlayEffect.__init__ +openpyxl.drawing.effect.GlowEffect.__init__ +openpyxl.drawing.effect.HSLEffect.__init__ +openpyxl.drawing.effect.InnerShadowEffect.__init__ +openpyxl.drawing.effect.OuterShadow.__init__ +openpyxl.drawing.effect.PresetShadowEffect.__init__ +openpyxl.drawing.effect.ReflectionEffect.__init__ +openpyxl.drawing.effect.SoftEdgesEffect.__init__ +openpyxl.drawing.fill.LinearShadeProperties.__init__ +openpyxl.drawing.fill.PathShadeProperties.__init__ +openpyxl.drawing.fill.TileInfoProperties.__init__ +openpyxl.drawing.geometry.Backdrop.__init__ +openpyxl.drawing.geometry.Bevel.__init__ +openpyxl.drawing.geometry.Camera.__init__ +openpyxl.drawing.geometry.ConnectionSite.__init__ +openpyxl.drawing.geometry.CustomGeometry2D.__init__ +openpyxl.drawing.geometry.GeomGuide.__init__ +openpyxl.drawing.geometry.LightRig.__init__ +openpyxl.drawing.geometry.Path2D.__init__ +openpyxl.drawing.geometry.Point3D.__init__ +openpyxl.drawing.geometry.PositiveSize2D.__init__ +openpyxl.drawing.geometry.PresetGeometry2D.__init__ +openpyxl.drawing.geometry.Scene3D.__init__ +openpyxl.drawing.geometry.ShapeStyle.__init__ +openpyxl.drawing.geometry.SphereCoords.__init__ +openpyxl.drawing.geometry.StyleMatrixReference.__init__ +openpyxl.drawing.geometry.Vector3D.__init__ +openpyxl.drawing.graphic.GroupShape.__init__ +openpyxl.drawing.properties.NonVisualDrawingProps.__init__ +openpyxl.drawing.properties.NonVisualGroupShape.__init__ +openpyxl.drawing.text.AutonumberBullet.__init__ +openpyxl.drawing.text.Font.__init__ +openpyxl.drawing.text.GeomGuide.__init__ +openpyxl.drawing.text.PresetTextShape.__init__ +openpyxl.drawing.text.TextField.__init__ +openpyxl.drawing.text.TextNormalAutofit.__init__ +openpyxl.formatting.rule.DataBar.__init__ +openpyxl.packaging.core.QualifiedDateTime.to_tree +openpyxl.packaging.relationship.get_rel +openpyxl.packaging.relationship.Relationship.__init__ +openpyxl.packaging.workbook.ChildSheet.__init__ +openpyxl.packaging.workbook.PivotCache.__init__ +openpyxl.pivot.cache.CacheDefinition.__init__ +openpyxl.pivot.cache.CacheField.__init__ +openpyxl.pivot.cache.CacheHierarchy.__init__ +openpyxl.pivot.cache.CacheSource.__init__ +openpyxl.pivot.cache.CalculatedItem.__init__ +openpyxl.pivot.cache.CalculatedMember.__init__ +openpyxl.pivot.cache.FieldUsage.__init__ +openpyxl.pivot.cache.GroupLevel.__init__ +openpyxl.pivot.cache.GroupMember.__init__ +openpyxl.pivot.cache.LevelGroup.__init__ +openpyxl.pivot.cache.MeasureGroup.__init__ +openpyxl.pivot.cache.OLAPSet.__init__ +openpyxl.pivot.cache.PageItem.__init__ +openpyxl.pivot.cache.PCDSDTCEntries.__init__ +openpyxl.pivot.cache.PivotDimension.__init__ +openpyxl.pivot.cache.Query.__init__ +openpyxl.pivot.cache.RangeSet.__init__ +openpyxl.pivot.fields.Error.__init__ +openpyxl.pivot.fields.Number.__init__ +openpyxl.pivot.fields.Tuple.__init__ +openpyxl.pivot.fields.TupleList.__init__ +openpyxl.pivot.table.AutoSortScope.__init__ +openpyxl.pivot.table.ChartFormat.__init__ +openpyxl.pivot.table.ConditionalFormat.__init__ +openpyxl.pivot.table.DataField.__init__ +openpyxl.pivot.table.Format.__init__ +openpyxl.pivot.table.HierarchyUsage.__init__ +openpyxl.pivot.table.Location.__init__ +openpyxl.pivot.table.MemberProperty.__init__ +openpyxl.pivot.table.PageField.__init__ +openpyxl.pivot.table.PivotFilter.__init__ +openpyxl.pivot.table.PivotFilters.__init__ +openpyxl.pivot.table.RowColField.__init__ +openpyxl.pivot.table.TableDefinition.__init__ +openpyxl.styles.colors.RgbColor.__init__ +openpyxl.styles.named_styles._NamedCellStyle.__init__ +openpyxl.styles.numbers.NumberFormat.__init__ +openpyxl.styles.table.TableStyle.__init__ +openpyxl.styles.table.TableStyleElement.__init__ +openpyxl.workbook.defined_name.DefinedName.__init__ +openpyxl.workbook.external_link.external.ExternalCell.__init__ +openpyxl.workbook.external_link.external.ExternalDefinedName.__init__ +openpyxl.workbook.external_link.external.ExternalRow.__init__ +openpyxl.workbook.external_link.external.ExternalSheetData.__init__ +openpyxl.workbook.function_group.FunctionGroup.__init__ +openpyxl.workbook.views.CustomWorkbookView.__init__ +openpyxl.workbook.web.WebPublishObject.__init__ +openpyxl.worksheet.cell_watch.CellWatch.__init__ +openpyxl.worksheet.controls.Control.__init__ +openpyxl.worksheet.controls.ControlProperty.__init__ +openpyxl.worksheet.custom.CustomProperty.__init__ +openpyxl.worksheet.dimensions.RowDimension.__init__ +openpyxl.worksheet.dimensions.SheetDimension.__init__ +openpyxl.worksheet.filters.DateGroupItem.__init__ +openpyxl.worksheet.filters.DynamicFilter.__init__ +openpyxl.worksheet.filters.FilterColumn.__init__ +openpyxl.worksheet.filters.IconFilter.__init__ +openpyxl.worksheet.filters.Top10.__init__ +openpyxl.worksheet.hyperlink.Hyperlink.__init__ +openpyxl.worksheet.ole.ObjectAnchor.__init__ +openpyxl.worksheet.ole.ObjectPr.__init__ +openpyxl.worksheet.ole.OleObject.__init__ +openpyxl.worksheet.print_settings.RowRange.__init__ +openpyxl.worksheet.scenario.InputCells.__init__ +openpyxl.worksheet.scenario.Scenario.__init__ +openpyxl.worksheet.smart_tag.CellSmartTag.__init__ +openpyxl.worksheet.smart_tag.CellSmartTagPr.__init__ +openpyxl.worksheet.smart_tag.CellSmartTags.__init__ +openpyxl.worksheet.table.TableColumn.__init__ +openpyxl.worksheet.table.XMLColumnProps.__init__ diff --git a/stubs/openpyxl/@tests/test_cases/check_base_descriptors.py b/stubs/openpyxl/@tests/test_cases/check_base_descriptors.py new file mode 100644 index 000000000000..f200aaf6debc --- /dev/null +++ b/stubs/openpyxl/@tests/test_cases/check_base_descriptors.py @@ -0,0 +1,392 @@ +# Needed until mypy issues are solved or https://github.com/python/mypy/issues/12358 +# pyright: reportUnnecessaryTypeIgnoreComment=false +from __future__ import annotations + +from _typeshed import ReadableBuffer +from datetime import date, datetime, time +from typing import Any, Literal +from typing_extensions import assert_type + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import ( + Bool, + Convertible, + DateTime, + Descriptor, + Float, + Integer, + Length, + MatchPattern, + MinMax, + NoneSet, + Set, + String, + Typed, +) +from openpyxl.descriptors.serialisable import Serialisable + + +class WithDescriptors(Serialisable): + descriptor = Descriptor[str]() + + typed_default = Typed(expected_type=str) + typed_not_none = Typed(expected_type=str, allow_none=False) + typed_none = Typed(expected_type=str, allow_none=True) + + set_tuple = Set(values=("a", 1, 0.0)) + set_list = Set(values=["a", 1, 0.0]) + set_tuple_none = Set(values=("a", 1, 0.0, None)) + + noneset_tuple = NoneSet(values=("a", 1, 0.0)) + noneset_list = NoneSet(values=["a", 1, 0.0]) + + length_tuple = Length[tuple[str, str]](length=1) # Can't validate tuple length in a generic manner + length_list = Length[list[str]](length=1) + length_invalid = Length[object](length=1) # type: ignore + + match_pattern_str_default = MatchPattern(pattern="") + match_pattern_str = MatchPattern(pattern="", allow_none=False) + match_pattern_str_none = MatchPattern(pattern="", allow_none=True) + match_pattern_bytes_default = MatchPattern(pattern=b"") + match_pattern_bytes = MatchPattern(pattern=b"", allow_none=False) + match_pattern_bytes_none = MatchPattern(pattern=b"", allow_none=True) + + convertible_default = Convertible(expected_type=int) + convertible_not_none = Convertible(expected_type=int, allow_none=False) + convertible_none = Convertible(expected_type=int, allow_none=True) + + # NOTE: min and max params are independent of expected_type since int and floats can always be compared together + minmax_default = MinMax(min=0, max=0) + minmax_float = MinMax(min=0, max=0, expected_type=float, allow_none=False) + minmax_float_none = MinMax(min=0, max=0, expected_type=float, allow_none=True) + minmax_int = MinMax(min=0.0, max=0.0, expected_type=int, allow_none=False) + minmax_int_none = MinMax(min=0.0, max=0.0, expected_type=int, allow_none=True) + + bool_default = Bool() + bool_not_none = Bool(allow_none=False) + bool_none = Bool(allow_none=True) + + datetime_default = DateTime() + datetime_not_none = DateTime(allow_none=False) + datetime_none = DateTime(allow_none=True) + + string_default = String() + string_not_none = String(allow_none=False) + string_none = String(allow_none=True) + + float_default = Float() + float_not_none = Float(allow_none=False) + float_none = Float(allow_none=True) + + integer_default = Integer() + integer_not_none = Integer(allow_none=False) + integer_none = Integer(allow_none=True) + + # Test inferred annotation + assert_type(descriptor, Descriptor[str]) + + assert_type(typed_default, Typed[str, Literal[False]]) + assert_type(typed_not_none, Typed[str, Literal[False]]) + assert_type(typed_none, Typed[str, Literal[True]]) + + assert_type(set_tuple, Set[Literal["a", 1] | float]) # type: ignore[assert-type] # False-positive in mypy + assert_type(set_list, Set[str | int | float]) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples + assert_type(set_tuple_none, Set[Literal["a", 1, None] | float]) # type: ignore[assert-type] # False-positive in mypy + + assert_type(noneset_tuple, NoneSet[Literal["a", 1] | float]) # type: ignore[assert-type] # False-positive in mypy + assert_type(noneset_list, NoneSet[str | float]) # type: ignore[assert-type] # False-positive in mypy# int and float are merged in generic unions + + assert_type(length_tuple, Length[tuple[str, str]]) + assert_type(length_list, Length[list[str]]) + + assert_type(match_pattern_str_default, MatchPattern[str, Literal[False]]) + assert_type(match_pattern_str, MatchPattern[str, Literal[False]]) + assert_type(match_pattern_str_none, MatchPattern[str, Literal[True]]) + assert_type(match_pattern_bytes_default, MatchPattern[ReadableBuffer, Literal[False]]) + assert_type(match_pattern_bytes, MatchPattern[ReadableBuffer, Literal[False]]) + assert_type(match_pattern_bytes_none, MatchPattern[ReadableBuffer, Literal[True]]) + + assert_type(convertible_default, Convertible[int, Literal[False]]) + assert_type(convertible_not_none, Convertible[int, Literal[False]]) + assert_type(convertible_none, Convertible[int, Literal[True]]) + + assert_type(minmax_default, MinMax[float, Literal[False]]) + assert_type(minmax_float, MinMax[float, Literal[False]]) + assert_type(minmax_float_none, MinMax[float, Literal[True]]) + assert_type(minmax_int, MinMax[int, Literal[False]]) + assert_type(minmax_int_none, MinMax[int, Literal[True]]) + + assert_type(bool_default, Bool[Literal[False]]) + assert_type(bool_not_none, Bool[Literal[False]]) + assert_type(bool_none, Bool[Literal[True]]) + + assert_type(datetime_default, DateTime[Literal[False]]) + assert_type(datetime_not_none, DateTime[Literal[False]]) + assert_type(datetime_none, DateTime[Literal[True]]) + + assert_type(string_default, String[Literal[False]]) + assert_type(string_not_none, String[Literal[False]]) + assert_type(string_none, String[Literal[True]]) + + assert_type(float_default, Float[Literal[False]]) + assert_type(float_not_none, Float[Literal[False]]) + assert_type(float_none, Float[Literal[True]]) + + assert_type(integer_default, Integer[Literal[False]]) + assert_type(integer_not_none, Integer[Literal[False]]) + assert_type(integer_none, Integer[Literal[True]]) + + +with_descriptors = WithDescriptors() + + +# Test with missing subclass +class NotSerialisable: + descriptor = Descriptor[Any]() + + +NotSerialisable().descriptor = None # type: ignore + + +# Test with Strict subclass +class WithDescriptorsStrict(Strict): + descriptor = Descriptor[Any]() + + +WithDescriptorsStrict().descriptor = None + + +# Test getters +assert_type(with_descriptors.descriptor, str) + +assert_type(with_descriptors.typed_not_none, str) +assert_type(with_descriptors.typed_none, str | None) + +assert_type(with_descriptors.set_tuple, Literal["a", 1] | float) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.set_list, str | int | float) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples +assert_type(with_descriptors.set_tuple_none, Literal["a", 1, None] | float) # type: ignore[assert-type] # False-positive in mypy + +assert_type(with_descriptors.noneset_tuple, Literal["a", 1] | float | None) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.noneset_list, str | float | None) # type: ignore[assert-type] # False-positive in mypy # int and float are merged in generic unions + +assert_type(with_descriptors.length_tuple, tuple[str, str]) +assert_type(with_descriptors.length_list, list[str]) + +assert_type(with_descriptors.match_pattern_str, str) +assert_type(with_descriptors.match_pattern_str_none, str | None) +assert_type(with_descriptors.match_pattern_bytes, ReadableBuffer) +assert_type(with_descriptors.match_pattern_bytes_none, ReadableBuffer | None) + +assert_type(with_descriptors.convertible_not_none, int) +assert_type(with_descriptors.convertible_none, int | None) + +assert_type(with_descriptors.minmax_float, float) +assert_type(with_descriptors.minmax_float_none, float | None) +assert_type(with_descriptors.minmax_int, int) +assert_type(with_descriptors.minmax_int_none, int | None) + +assert_type(with_descriptors.bool_not_none, bool) +assert_type(with_descriptors.bool_none, bool | None) + +assert_type(with_descriptors.datetime_not_none, datetime) +assert_type(with_descriptors.datetime_none, datetime | None) + +assert_type(with_descriptors.string_not_none, str) +assert_type(with_descriptors.string_none, str | None) + +assert_type(with_descriptors.float_not_none, float) +assert_type(with_descriptors.float_none, float | None) + +assert_type(with_descriptors.integer_not_none, int) +assert_type(with_descriptors.integer_none, int | None) + + +# Test setters (expected type, None, unexpected type) +with_descriptors.descriptor = "" +with_descriptors.descriptor = None # type: ignore +with_descriptors.descriptor = 0 # type: ignore + + +with_descriptors.typed_not_none = "" +with_descriptors.typed_not_none = None # type: ignore +with_descriptors.typed_not_none = 0 # type: ignore + +with_descriptors.typed_none = "" +with_descriptors.typed_none = None +with_descriptors.typed_none = 0 # type: ignore + + +# NOTE: Can't check Set for literal int wen used with a float because any int is a valid float +with_descriptors.set_tuple = "a" +with_descriptors.set_tuple = 0 +with_descriptors.set_tuple = 0.0 +with_descriptors.set_tuple = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.set_list = "a" +with_descriptors.set_list = 0 +with_descriptors.set_list = 0.0 +with_descriptors.set_list = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = "none" # can't check literals validity +with_descriptors.set_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.set_tuple_none = "a" +with_descriptors.set_tuple_none = 0 +with_descriptors.set_tuple_none = 0.0 +with_descriptors.set_tuple_none = None +with_descriptors.set_tuple_none = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple_none = object() # type: ignore + + +with_descriptors.noneset_tuple = "a" +with_descriptors.noneset_tuple = 0 +with_descriptors.noneset_tuple = 0.0 +with_descriptors.noneset_tuple = None +with_descriptors.noneset_tuple = "none" +with_descriptors.noneset_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.noneset_list = "a" +with_descriptors.noneset_list = 0 +with_descriptors.noneset_list = 0.0 +with_descriptors.noneset_list = None +with_descriptors.noneset_list = "none" +with_descriptors.noneset_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + + +# NOTE: Can't validate tuple length in a generic manner +with_descriptors.length_tuple = ("a", "a") +with_descriptors.length_tuple = None # type: ignore +with_descriptors.length_tuple = ["a", "a"] # type: ignore +with_descriptors.length_tuple = "" # type: ignore + +with_descriptors.length_list = ["a", "a"] +with_descriptors.length_list = None # type: ignore +with_descriptors.length_list = ("a", "a") # type: ignore +with_descriptors.length_list = "" # type: ignore + + +with_descriptors.match_pattern_str = "" +with_descriptors.match_pattern_str = None # type: ignore +with_descriptors.match_pattern_str = b"" # type: ignore +with_descriptors.match_pattern_str = 0 # type: ignore + +with_descriptors.match_pattern_str_none = "" +with_descriptors.match_pattern_str_none = None +with_descriptors.match_pattern_str_none = b"" # type: ignore +with_descriptors.match_pattern_str_none = 0 # type: ignore + +with_descriptors.match_pattern_bytes = b"" +with_descriptors.match_pattern_bytes = None # type: ignore +with_descriptors.match_pattern_bytes = "" # type: ignore +with_descriptors.match_pattern_bytes = 0 # type: ignore + +with_descriptors.match_pattern_bytes_none = b"" +with_descriptors.match_pattern_bytes_none = None +with_descriptors.match_pattern_bytes_none = "" # type: ignore +with_descriptors.match_pattern_bytes_none = 0 # type: ignore + + +with_descriptors.convertible_not_none = 0 +with_descriptors.convertible_not_none = "0" +with_descriptors.convertible_not_none = None # type: ignore +with_descriptors.convertible_not_none = object() # type: ignore + +with_descriptors.convertible_none = 0 +with_descriptors.convertible_none = "0" +with_descriptors.convertible_none = None +with_descriptors.convertible_none = object() # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.minmax_float = 0 +with_descriptors.minmax_float = "0" +with_descriptors.minmax_float = 0.0 +with_descriptors.minmax_float = None # type: ignore +with_descriptors.minmax_float = object() # type: ignore + +with_descriptors.minmax_float_none = 0 +with_descriptors.minmax_float_none = "0" +with_descriptors.minmax_float_none = 0.0 +with_descriptors.minmax_float_none = None +with_descriptors.minmax_float_none = object() # type: ignore + +with_descriptors.minmax_int = 0 +with_descriptors.minmax_int = "0" +with_descriptors.minmax_int = 0.0 +with_descriptors.minmax_int = None # type: ignore +with_descriptors.minmax_int = object() # type: ignore + +with_descriptors.minmax_int_none = 0 +with_descriptors.minmax_int_none = "0" +with_descriptors.minmax_int_none = 0.0 +with_descriptors.minmax_int_none = None +with_descriptors.minmax_int_none = object() # type: ignore + + +with_descriptors.bool_not_none = False +with_descriptors.bool_not_none = "0" +with_descriptors.bool_not_none = 0 +with_descriptors.bool_not_none = None +with_descriptors.bool_not_none = 0.0 # type: ignore +with_descriptors.bool_not_none = object() # type: ignore + +with_descriptors.bool_none = False +with_descriptors.bool_none = "0" +with_descriptors.bool_none = 0 +with_descriptors.bool_none = None +with_descriptors.bool_none = 0.0 # type: ignore +with_descriptors.bool_none = object() # type: ignore + + +with_descriptors.datetime_not_none = datetime(0, 0, 0) +with_descriptors.datetime_not_none = "" +with_descriptors.datetime_not_none = None # type: ignore +with_descriptors.datetime_not_none = 0 # type: ignore +with_descriptors.datetime_not_none = date(0, 0, 0) # type: ignore +with_descriptors.datetime_not_none = time() # type: ignore + +with_descriptors.datetime_none = datetime(0, 0, 0) +with_descriptors.datetime_none = "" +with_descriptors.datetime_none = None +with_descriptors.datetime_none = 0 # type: ignore +with_descriptors.datetime_none = date(0, 0, 0) # type: ignore +with_descriptors.datetime_none = time() # type: ignore + + +with_descriptors.string_not_none = "" +with_descriptors.string_not_none = None # type: ignore +with_descriptors.string_not_none = 0 # type: ignore + +with_descriptors.string_none = "" +with_descriptors.string_none = None +with_descriptors.string_none = 0 # type: ignore + + +with_descriptors.float_not_none = 0 +with_descriptors.float_not_none = 0.0 +with_descriptors.float_not_none = "0" +with_descriptors.float_not_none = b"0" +with_descriptors.float_not_none = None # type: ignore +with_descriptors.float_not_none = object() # type: ignore + +with_descriptors.float_none = 0 +with_descriptors.float_none = 0.0 +with_descriptors.float_none = "0" +with_descriptors.float_none = b"0" +with_descriptors.float_none = None +with_descriptors.float_none = object() # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.integer_not_none = 0 +with_descriptors.integer_not_none = 0.0 +with_descriptors.integer_not_none = "0" +with_descriptors.integer_not_none = b"0" +with_descriptors.integer_not_none = None # type: ignore +with_descriptors.integer_not_none = object() # type: ignore + +with_descriptors.integer_none = 0 +with_descriptors.integer_none = 0.0 +with_descriptors.integer_none = "0" +with_descriptors.integer_none = b"0" +with_descriptors.integer_none = None +with_descriptors.integer_none = object() # FIXME: False negative(?) in pyright and mypy diff --git a/stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py b/stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py new file mode 100644 index 000000000000..ceb0a1c485d5 --- /dev/null +++ b/stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py @@ -0,0 +1,458 @@ +# Needed until mypy issues are solved or https://github.com/python/mypy/issues/12358 +# pyright: reportUnnecessaryTypeIgnoreComment=false + +# These tests are essentially a mirror of check_base_descriptors +from __future__ import annotations + +from typing import Literal, cast +from typing_extensions import assert_type + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.nested import ( + EmptyTag, + Nested, + NestedBool, + NestedFloat, + NestedInteger, + NestedMinMax, + NestedNoneSet, + NestedSet, + NestedString, + NestedText, + NestedValue, +) +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml._functions_overloads import _HasTagAndGet +from openpyxl.xml.functions import Element + +_ = object() # More concise discard object for casts + +# Ensure the default "Element" matches the _HasTagAndGet protocol +element: _HasTagAndGet[str] = Element("") + + +class WithDescriptors(Serialisable): + descriptor = Nested(expected_type=str) + + set_tuple = NestedSet(values=("a", 1, 0.0)) + set_list = NestedSet(values=["a", 1, 0.0]) + set_tuple_none = NestedSet(values=("a", 1, 0.0, None)) + + noneset_tuple = NestedNoneSet(values=("a", 1, 0.0)) + noneset_list = NestedNoneSet(values=["a", 1, 0.0]) + + convertible_default = NestedValue(expected_type=int) + convertible_not_none = NestedValue(expected_type=int, allow_none=False) + convertible_none = NestedValue(expected_type=int, allow_none=True) + + text_default = NestedText(expected_type=str) + text_str_not_none = NestedText(expected_type=str, allow_none=False) + text_str_none = NestedText(expected_type=str, allow_none=True) + text_int_not_none = NestedText(expected_type=int, allow_none=False) + text_int_none = NestedText(expected_type=int, allow_none=True) + + # NOTE: min and max params are independent of expected_type since int and floats can always be compared together + minmax_default = NestedMinMax(min=0, max=0) + minmax_float = NestedMinMax(min=0, max=0, expected_type=float, allow_none=False) + minmax_float_none = NestedMinMax(min=0, max=0, expected_type=float, allow_none=True) + minmax_int = NestedMinMax(min=0.0, max=0.0, expected_type=int, allow_none=False) + minmax_int_none = NestedMinMax(min=0.0, max=0.0, expected_type=int, allow_none=True) + + bool_default = NestedBool() + bool_not_none = NestedBool(allow_none=False) + bool_none = NestedBool(allow_none=True) + + emptytag_default = EmptyTag() + emptytag_not_none = EmptyTag(allow_none=False) + emptytag_none = EmptyTag(allow_none=True) + + string_default = NestedString() + string_not_none = NestedString(allow_none=False) + string_none = NestedString(allow_none=True) + + float_default = NestedFloat() + float_not_none = NestedFloat(allow_none=False) + float_none = NestedFloat(allow_none=True) + + integer_default = NestedInteger() + integer_not_none = NestedInteger(allow_none=False) + integer_none = NestedInteger(allow_none=True) + + # Test inferred annotation + assert_type(descriptor, Nested[str]) + + assert_type(set_tuple, NestedSet[Literal["a", 1] | float]) # type: ignore[assert-type] # False-positive in mypy + assert_type(set_list, NestedSet[str | int | float]) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples + assert_type(set_tuple_none, NestedSet[Literal["a", 1, None] | float]) # type: ignore[assert-type] # False-positive in mypy + + assert_type(noneset_tuple, NestedNoneSet[Literal["a", 1] | float]) # type: ignore[assert-type] # False-positive in mypy + assert_type(noneset_list, NestedNoneSet[str | float]) # type: ignore[assert-type] # False-positive in mypy# int and float are merged in generic unions + + assert_type(convertible_default, NestedValue[int, Literal[False]]) + assert_type(convertible_not_none, NestedValue[int, Literal[False]]) + assert_type(convertible_none, NestedValue[int, Literal[True]]) + + assert_type(text_default, NestedText[str, Literal[False]]) + assert_type(text_str_not_none, NestedText[str, Literal[False]]) + assert_type(text_str_none, NestedText[str, Literal[True]]) + assert_type(text_int_not_none, NestedText[int, Literal[False]]) + assert_type(text_int_none, NestedText[int, Literal[True]]) + + assert_type(minmax_default, NestedMinMax[float, Literal[False]]) + assert_type(minmax_float, NestedMinMax[float, Literal[False]]) + assert_type(minmax_float_none, NestedMinMax[float, Literal[True]]) + assert_type(minmax_int, NestedMinMax[int, Literal[False]]) + assert_type(minmax_int_none, NestedMinMax[int, Literal[True]]) + + assert_type(bool_default, NestedBool[Literal[False]]) + assert_type(bool_not_none, NestedBool[Literal[False]]) + assert_type(bool_none, NestedBool[Literal[True]]) + + assert_type(emptytag_default, EmptyTag[Literal[False]]) + assert_type(emptytag_not_none, EmptyTag[Literal[False]]) + assert_type(emptytag_none, EmptyTag[Literal[True]]) + + assert_type(string_default, NestedString[Literal[False]]) + assert_type(string_not_none, NestedString[Literal[False]]) + assert_type(string_none, NestedString[Literal[True]]) + + assert_type(float_default, NestedFloat[Literal[False]]) + assert_type(float_not_none, NestedFloat[Literal[False]]) + assert_type(float_none, NestedFloat[Literal[True]]) + + assert_type(integer_default, NestedInteger[Literal[False]]) + assert_type(integer_not_none, NestedInteger[Literal[False]]) + assert_type(integer_none, NestedInteger[Literal[True]]) + + +with_descriptors = WithDescriptors() + + +# Test with missing subclass +class NotSerialisable: + descriptor = Nested(expected_type=object) + + +NotSerialisable().descriptor = None # type: ignore + + +# Test with Strict subclass +class WithDescriptorsStrict(Strict): + descriptor = Nested(expected_type=object) + + +WithDescriptorsStrict().descriptor = None + + +# Test getters +assert_type(with_descriptors.descriptor, str) + +assert_type(with_descriptors.set_tuple, Literal["a", 1] | float) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.set_list, str | int | float) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples +assert_type(with_descriptors.set_tuple_none, Literal["a", 1, None] | float) # type: ignore[assert-type] # False-positive in mypy + +assert_type(with_descriptors.noneset_tuple, Literal["a", 1] | float | None) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.noneset_list, str | float | None) # type: ignore[assert-type] # False-positive in mypy # int and float are merged in generic unions + +assert_type(with_descriptors.convertible_not_none, int) +assert_type(with_descriptors.convertible_none, int | None) + +assert_type(with_descriptors.text_str_not_none, str) +assert_type(with_descriptors.text_str_none, str | None) +assert_type(with_descriptors.text_int_not_none, int) +assert_type(with_descriptors.text_int_none, int | None) + +assert_type(with_descriptors.minmax_float, float) +assert_type(with_descriptors.minmax_float_none, float | None) +assert_type(with_descriptors.minmax_int, int) +assert_type(with_descriptors.minmax_int_none, int | None) + +assert_type(with_descriptors.bool_not_none, bool) +assert_type(with_descriptors.bool_none, bool | None) + +assert_type(with_descriptors.emptytag_not_none, bool) +assert_type(with_descriptors.emptytag_none, bool | None) + +assert_type(with_descriptors.string_not_none, str) +assert_type(with_descriptors.string_none, str | None) + +assert_type(with_descriptors.float_not_none, float) +assert_type(with_descriptors.float_none, float | None) + +assert_type(with_descriptors.integer_not_none, int) +assert_type(with_descriptors.integer_none, int | None) + + +# Test setters (expected type, None, unexpected type, Elements) +with_descriptors.descriptor = "" +with_descriptors.descriptor = None # type: ignore +with_descriptors.descriptor = 0 # type: ignore +with_descriptors.descriptor = cast(_HasTagAndGet[str], _) +with_descriptors.descriptor = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.descriptor = cast(_HasTagAndGet[int], _) # type: ignore + + +# NOTE: Can't check NestedSet for literal int wen used with a float because any int is a valid float +with_descriptors.set_tuple = "a" +with_descriptors.set_tuple = 0 +with_descriptors.set_tuple = 0.0 +with_descriptors.set_tuple = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.set_tuple = cast(_HasTagAndGet[str], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = cast(_HasTagAndGet[None], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[object], _ +) + +with_descriptors.set_list = "a" +with_descriptors.set_list = 0 +with_descriptors.set_list = 0.0 +with_descriptors.set_list = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = "none" # can't check literals validity +with_descriptors.set_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.set_list = cast(_HasTagAndGet[str], _) # can't check literals validity +with_descriptors.set_list = cast(_HasTagAndGet[None], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = cast(_HasTagAndGet[object], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.set_tuple_none = "a" +with_descriptors.set_tuple_none = 0 +with_descriptors.set_tuple_none = 0.0 +with_descriptors.set_tuple_none = None +with_descriptors.set_tuple_none = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple_none = object() # type: ignore +with_descriptors.set_tuple_none = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.set_tuple_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[str], _ +) +with_descriptors.set_tuple_none = cast(_HasTagAndGet[None], _) +with_descriptors.set_tuple_none = cast(_HasTagAndGet[object], _) # type: ignore + + +with_descriptors.noneset_tuple = "a" +with_descriptors.noneset_tuple = 0 +with_descriptors.noneset_tuple = 0.0 +with_descriptors.noneset_tuple = None +with_descriptors.noneset_tuple = "none" +with_descriptors.noneset_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.noneset_tuple = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.noneset_tuple = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[str], _ +) +with_descriptors.noneset_tuple = cast(_HasTagAndGet[None], _) +with_descriptors.noneset_tuple = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[object], _ +) + +with_descriptors.noneset_list = "a" +with_descriptors.noneset_list = 0 +with_descriptors.noneset_list = 0.0 +with_descriptors.noneset_list = None +with_descriptors.noneset_list = "none" +with_descriptors.noneset_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.noneset_list = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.noneset_list = cast(_HasTagAndGet[str], _) +with_descriptors.noneset_list = cast(_HasTagAndGet[None], _) +with_descriptors.noneset_list = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[object], _ +) + + +with_descriptors.convertible_not_none = 0 +with_descriptors.convertible_not_none = "0" +with_descriptors.convertible_not_none = None # type: ignore +with_descriptors.convertible_not_none = object() # type: ignore +with_descriptors.convertible_not_none = cast(_HasTagAndGet[str], _) +with_descriptors.convertible_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.convertible_not_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.convertible_none = 0 +with_descriptors.convertible_none = "0" +with_descriptors.convertible_none = None +with_descriptors.convertible_none = object() # FIXME: False negative(?) in pyright and mypy +with_descriptors.convertible_none = cast(_HasTagAndGet[str], _) +with_descriptors.convertible_none = cast(_HasTagAndGet[None], _) +with_descriptors.convertible_none = cast(_HasTagAndGet[object], _) # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.text_str_not_none = 0 +with_descriptors.text_str_not_none = "0" +with_descriptors.text_str_not_none = None +with_descriptors.text_str_not_none = object() +with_descriptors.text_str_not_none = cast(_HasTagAndGet[str], _) +with_descriptors.text_str_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.text_str_not_none = cast(_HasTagAndGet[object], _) + +with_descriptors.text_str_none = 0 +with_descriptors.text_str_none = "0" +with_descriptors.text_str_none = None +with_descriptors.text_str_none = object() +with_descriptors.text_str_none = cast(_HasTagAndGet[str], _) +with_descriptors.text_str_none = cast(_HasTagAndGet[None], _) +with_descriptors.text_str_none = cast(_HasTagAndGet[object], _) + +with_descriptors.text_int_not_none = 0 +with_descriptors.text_int_not_none = "0" +with_descriptors.text_int_not_none = None # type: ignore +with_descriptors.text_int_not_none = object() # type: ignore +# If expected type (_T) is not str, it's impossible to use an Element as the value +with_descriptors.text_int_not_none = cast(_HasTagAndGet[int], _) # type: ignore +with_descriptors.text_int_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.text_int_not_none = cast(_HasTagAndGet[str], _) # type: ignore + +with_descriptors.text_int_none = 0 +with_descriptors.text_int_none = "0" +with_descriptors.text_int_none = None +with_descriptors.text_int_none = object() # FIXME: False negative(?) in pyright and mypy +# If expected type (_T) is not str, it's impossible to use an Element as the value +with_descriptors.text_int_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[int], _ +) +with_descriptors.text_int_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[None], _ +) +with_descriptors.text_int_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[str], _ +) + + +with_descriptors.minmax_float = 0 +with_descriptors.minmax_float = "0" +with_descriptors.minmax_float = 0.0 +with_descriptors.minmax_float = None # type: ignore +with_descriptors.minmax_float = object() # type: ignore +with_descriptors.minmax_float = cast(_HasTagAndGet[float], _) +with_descriptors.minmax_float = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.minmax_float = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.minmax_float_none = 0 +with_descriptors.minmax_float_none = "0" +with_descriptors.minmax_float_none = 0.0 +with_descriptors.minmax_float_none = None +with_descriptors.minmax_float_none = object() # type: ignore +with_descriptors.minmax_float_none = cast(_HasTagAndGet[float], _) +with_descriptors.minmax_float_none = cast(_HasTagAndGet[None], _) +with_descriptors.minmax_float_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.minmax_int = 0 +with_descriptors.minmax_int = "0" +with_descriptors.minmax_int = 0.0 +with_descriptors.minmax_int = None # type: ignore +with_descriptors.minmax_int = object() # type: ignore +with_descriptors.minmax_int = cast(_HasTagAndGet[int], _) +with_descriptors.minmax_int = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.minmax_int = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.minmax_int_none = 0 +with_descriptors.minmax_int_none = "0" +with_descriptors.minmax_int_none = 0.0 +with_descriptors.minmax_int_none = None +with_descriptors.minmax_int_none = object() # type: ignore +with_descriptors.minmax_int_none = cast(_HasTagAndGet[int], _) +with_descriptors.minmax_int_none = cast(_HasTagAndGet[None], _) +with_descriptors.minmax_int_none = cast(_HasTagAndGet[object], _) # type: ignore + + +with_descriptors.bool_not_none = False +with_descriptors.bool_not_none = "0" +with_descriptors.bool_not_none = 0 +with_descriptors.bool_not_none = None +with_descriptors.bool_not_none = 0.0 # type: ignore +with_descriptors.bool_not_none = object() # type: ignore +with_descriptors.bool_not_none = cast(_HasTagAndGet[bool], _) +with_descriptors.bool_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.bool_not_none = cast(_HasTagAndGet[float], _) # type: ignore + +with_descriptors.bool_none = False +with_descriptors.bool_none = "0" +with_descriptors.bool_none = 0 +with_descriptors.bool_none = None +with_descriptors.bool_none = 0.0 # type: ignore +with_descriptors.bool_none = object() # type: ignore +with_descriptors.bool_none = cast(_HasTagAndGet[bool], _) +with_descriptors.bool_none = cast(_HasTagAndGet[None], _) +with_descriptors.bool_none = cast(_HasTagAndGet[float], _) # type: ignore + + +with_descriptors.emptytag_not_none = False +with_descriptors.emptytag_not_none = "0" +with_descriptors.emptytag_not_none = 0 +with_descriptors.emptytag_not_none = None +with_descriptors.emptytag_not_none = 0.0 # type: ignore +with_descriptors.emptytag_not_none = object() # type: ignore +with_descriptors.emptytag_not_none = cast(_HasTagAndGet[bool], _) +with_descriptors.emptytag_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.emptytag_not_none = cast(_HasTagAndGet[float], _) # type: ignore + +with_descriptors.emptytag_none = False +with_descriptors.emptytag_none = "0" +with_descriptors.emptytag_none = 0 +with_descriptors.emptytag_none = None +with_descriptors.emptytag_none = 0.0 # type: ignore +with_descriptors.emptytag_none = object() # type: ignore +with_descriptors.emptytag_none = cast(_HasTagAndGet[bool], _) +with_descriptors.emptytag_none = cast(_HasTagAndGet[None], _) +with_descriptors.emptytag_none = cast(_HasTagAndGet[float], _) # type: ignore + + +with_descriptors.string_not_none = "" +with_descriptors.string_not_none = None +with_descriptors.string_not_none = 0 +with_descriptors.string_not_none = object() +with_descriptors.string_not_none = cast(_HasTagAndGet[str], _) +with_descriptors.string_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.string_not_none = cast(_HasTagAndGet[int], _) +with_descriptors.string_not_none = cast(_HasTagAndGet[object], _) + +with_descriptors.string_none = "" +with_descriptors.string_none = None +with_descriptors.string_none = 0 +with_descriptors.string_none = object() +with_descriptors.string_none = cast(_HasTagAndGet[str], _) +with_descriptors.string_none = cast(_HasTagAndGet[None], _) +with_descriptors.string_none = cast(_HasTagAndGet[int], _) +with_descriptors.string_none = cast(_HasTagAndGet[object], _) + + +with_descriptors.float_not_none = 0 +with_descriptors.float_not_none = 0.0 +with_descriptors.float_not_none = "0" +with_descriptors.float_not_none = b"0" +with_descriptors.float_not_none = None # type: ignore +with_descriptors.float_not_none = object() # type: ignore +with_descriptors.float_not_none = cast(_HasTagAndGet[float], _) +with_descriptors.float_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.float_not_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.float_none = 0 +with_descriptors.float_none = 0.0 +with_descriptors.float_none = "0" +with_descriptors.float_none = b"0" +with_descriptors.float_none = None +with_descriptors.float_none = object() # FIXME: False negative(?) in pyright and mypy +with_descriptors.float_none = cast(_HasTagAndGet[float], _) +with_descriptors.float_none = cast(_HasTagAndGet[None], _) +with_descriptors.float_none = cast(_HasTagAndGet[object], _) # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.integer_not_none = 0 +with_descriptors.integer_not_none = 0.0 +with_descriptors.integer_not_none = "0" +with_descriptors.integer_not_none = b"0" +with_descriptors.integer_not_none = None # type: ignore +with_descriptors.integer_not_none = object() # type: ignore +with_descriptors.integer_not_none = cast(_HasTagAndGet[int], _) +with_descriptors.integer_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.integer_not_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.integer_none = 0 +with_descriptors.integer_none = 0.0 +with_descriptors.integer_none = "0" +with_descriptors.integer_none = b"0" +with_descriptors.integer_none = None +with_descriptors.integer_none = object() # FIXME: False negative(?) in pyright and mypy +with_descriptors.integer_none = cast(_HasTagAndGet[int], _) +with_descriptors.integer_none = cast(_HasTagAndGet[None], _) +with_descriptors.integer_none = cast(_HasTagAndGet[object], _) # FIXME: False negative(?) in pyright and mypy diff --git a/stubs/openpyxl/METADATA.toml b/stubs/openpyxl/METADATA.toml new file mode 100644 index 000000000000..076eb0ab762f --- /dev/null +++ b/stubs/openpyxl/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.1.5" +upstream-repository = "https://foss.heptapod.net/openpyxl/openpyxl" diff --git a/stubs/openpyxl/openpyxl/__init__.pyi b/stubs/openpyxl/openpyxl/__init__.pyi new file mode 100644 index 000000000000..13e79c8bdc1d --- /dev/null +++ b/stubs/openpyxl/openpyxl/__init__.pyi @@ -0,0 +1,31 @@ +from _typeshed import StrPath, SupportsRead, SupportsWrite +from typing import IO, Literal, Protocol, TypeAlias, type_check_only + +from openpyxl.compat.numbers import NUMPY as NUMPY +from openpyxl.reader.excel import load_workbook as load_workbook +from openpyxl.workbook import Workbook as Workbook +from openpyxl.xml import DEFUSEDXML as DEFUSEDXML, LXML as LXML + +from ._constants import ( + __author__ as __author__, + __author_email__ as __author_email__, + __license__ as __license__, + __maintainer_email__ as __maintainer_email__, + __url__ as __url__, + __version__ as __version__, +) + +DEBUG: bool +open = load_workbook + +# Utility types reused elsewhere +_VisibilityType: TypeAlias = Literal["visible", "hidden", "veryHidden"] # noqa: Y047 + +# TODO: Use a proper protocol from ZipFile. See: #10880 +# This alias is to minimize false-positives +_ZipFileFileProtocol: TypeAlias = StrPath | IO[bytes] | SupportsRead[bytes] # noqa: Y047 +_ZipFileFileWriteProtocol: TypeAlias = StrPath | IO[bytes] | SupportsWrite[bytes] # noqa: Y047 + +@type_check_only +class _Decodable(Protocol): # noqa: Y046 + def decode(self, encoding: str, /) -> str: ... diff --git a/stubs/openpyxl/openpyxl/_constants.pyi b/stubs/openpyxl/openpyxl/_constants.pyi new file mode 100644 index 000000000000..ed593cc2cf45 --- /dev/null +++ b/stubs/openpyxl/openpyxl/_constants.pyi @@ -0,0 +1,7 @@ +__author__: str +__author_email__: str +__license__: str +__maintainer_email__: str +__url__: str +__version__: str +__python__: str diff --git a/stubs/openpyxl/openpyxl/cell/__init__.pyi b/stubs/openpyxl/openpyxl/cell/__init__.pyi new file mode 100644 index 000000000000..7bd4c41d9494 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/__init__.pyi @@ -0,0 +1,27 @@ +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from typing import Any, TypeAlias + +from openpyxl.cell.rich_text import CellRichText +from openpyxl.worksheet.formula import ArrayFormula, DataTableFormula + +from .cell import Cell as Cell, MergedCell as MergedCell, WriteOnlyCell as WriteOnlyCell +from .read_only import ReadOnlyCell as ReadOnlyCell + +_TimeTypes: TypeAlias = datetime | date | time | timedelta +_CellGetValue: TypeAlias = ( # noqa: Y047 # Used in other modules + # if numpy is installed also numpy bool and number types + bool + | float + | Decimal + | str + | CellRichText + | _TimeTypes + | DataTableFormula + | ArrayFormula + | None +) +_AnyCellValue: TypeAlias = Any # AnyOf _CellGetValue # noqa: Y047 # Used in other modules +_CellSetValue: TypeAlias = _CellGetValue | bytes # noqa: Y047 # Used in other modules + +_CellOrMergedCell: TypeAlias = Cell | MergedCell # noqa: Y047 # Used in other modules diff --git a/stubs/openpyxl/openpyxl/cell/_writer.pyi b/stubs/openpyxl/openpyxl/cell/_writer.pyi new file mode 100644 index 000000000000..d079c8c08c77 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/_writer.pyi @@ -0,0 +1,9 @@ +from _typeshed import Unused + +from openpyxl.cell import _CellOrMergedCell + +def etree_write_cell(xf, worksheet: Unused, cell: _CellOrMergedCell, styled=None) -> None: ... +def lxml_write_cell(xf, worksheet: Unused, cell: _CellOrMergedCell, styled: bool = False) -> None: ... + +write_cell = lxml_write_cell +write_cell = etree_write_cell diff --git a/stubs/openpyxl/openpyxl/cell/cell.pyi b/stubs/openpyxl/openpyxl/cell/cell.pyi new file mode 100644 index 000000000000..b16d008d9f4e --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/cell.pyi @@ -0,0 +1,109 @@ +from _typeshed import ReadableBuffer +from datetime import datetime +from re import Pattern +from typing import Final, Literal, overload + +from openpyxl.cell import _CellGetValue, _CellOrMergedCell, _CellSetValue, _TimeTypes +from openpyxl.comments.comments import Comment +from openpyxl.compat.numbers import NUMERIC_TYPES as NUMERIC_TYPES # cell numeric types +from openpyxl.styles.cell_style import StyleArray +from openpyxl.styles.styleable import StyleableObject +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet +from openpyxl.worksheet.hyperlink import Hyperlink + +__docformat__: Final = "restructuredtext en" +TIME_TYPES: Final[tuple[type, ...]] +TIME_FORMATS: Final[dict[type[_TimeTypes], str]] +STRING_TYPES: Final[tuple[type, ...]] +KNOWN_TYPES: Final[tuple[type, ...]] + +ILLEGAL_CHARACTERS_RE: Final[Pattern[str]] +ERROR_CODES: Final[tuple[str, ...]] + +TYPE_STRING: Final = "s" +TYPE_FORMULA: Final = "f" +TYPE_NUMERIC: Final = "n" +TYPE_BOOL: Final = "b" +TYPE_NULL: Final = "n" +TYPE_INLINE: Final = "inlineStr" +TYPE_ERROR: Final = "e" +TYPE_FORMULA_CACHE_STRING: Final = "str" + +VALID_TYPES: Final[tuple[str, ...]] + +def get_type(t: type, value: object) -> Literal["n", "s", "d", "f"] | None: ... +def get_time_format(t: _TimeTypes) -> str: ... + +class Cell(StyleableObject): + __slots__ = ("row", "column", "_value", "data_type", "parent", "_hyperlink", "_comment") + row: int + column: int + data_type: str + # row and column are never meant to be None and would lead to errors + def __init__( + self, + worksheet: _WorkbookChild | ReadOnlyWorksheet, + row: int, + column: int, + value: _CellSetValue = None, + style_array: StyleArray | None = None, + ) -> None: ... + @property + def coordinate(self) -> str: ... + @property + def col_idx(self) -> int: ... + @property + def column_letter(self) -> str: ... + @property + def encoding(self) -> str: ... + @property + def base_date(self) -> datetime: ... + + @overload + def check_string(self, value: None) -> None: ... + @overload + def check_string(self, value: str | ReadableBuffer) -> str: ... + + def check_error(self, value: object) -> str: ... + + @property + def value(self) -> _CellGetValue: ... + @value.setter + def value(self, value: _CellSetValue) -> None: ... + + @property + def internal_value(self) -> _CellGetValue: ... + + @property + def hyperlink(self) -> Hyperlink | None: ... + @hyperlink.setter + def hyperlink(self, val: Hyperlink | str | None) -> None: ... + + @property + def is_date(self) -> bool: ... + def offset(self, row: int = 0, column: int = 0) -> _CellOrMergedCell: ... + + @property + def comment(self) -> Comment | None: ... + @comment.setter + def comment(self, value: Comment | None) -> None: ... + +class MergedCell(StyleableObject): + __slots__ = ("row", "column") + data_type: str + comment: Comment | None + hyperlink: Hyperlink | None + row: int | None + column: int | None + def __init__( + self, worksheet: _WorkbookChild | ReadOnlyWorksheet, row: int | None = None, column: int | None = None + ) -> None: ... + # Same as Cell.coordinate + # https://github.com/python/mypy/issues/6700 + @property + def coordinate(self) -> str: ... + # The value of a MergedCell is always None. + value: None + +def WriteOnlyCell(ws: _WorkbookChild | ReadOnlyWorksheet, value: str | float | datetime | None = None) -> Cell: ... diff --git a/stubs/openpyxl/openpyxl/cell/read_only.pyi b/stubs/openpyxl/openpyxl/cell/read_only.pyi new file mode 100644 index 000000000000..21fe3097e518 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/read_only.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete +from typing import Final + +from openpyxl.cell import _CellGetValue +from openpyxl.styles.alignment import Alignment +from openpyxl.styles.borders import Border +from openpyxl.styles.cell_style import StyleArray +from openpyxl.styles.fills import Fill +from openpyxl.styles.fonts import Font +from openpyxl.styles.protection import Protection +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet + +class ReadOnlyCell: + __slots__ = ("parent", "row", "column", "_value", "data_type", "_style_id") + parent: _WorkbookChild | ReadOnlyWorksheet + row: Incomplete + column: Incomplete + data_type: Incomplete + def __init__( + self, sheet: _WorkbookChild | ReadOnlyWorksheet, row, column, value, data_type: str = "n", style_id: int = 0 + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + # Same as Cell.coordinate + # https://github.com/python/mypy/issues/6700 + # Defined twice in the implementation + @property + def coordinate(self) -> str: ... + # Same as Cell.column_letter + # https://github.com/python/mypy/issues/6700 + @property + def column_letter(self) -> str: ... + @property + def style_array(self) -> StyleArray: ... + @property + def has_style(self) -> bool: ... + @property + def number_format(self) -> str: ... + @property + def font(self) -> Font: ... + @property + def fill(self) -> Fill: ... + @property + def border(self) -> Border: ... + @property + def alignment(self) -> Alignment: ... + @property + def protection(self) -> Protection: ... + # Same as Cell.is_date + # https://github.com/python/mypy/issues/6700 + @property + def is_date(self) -> bool: ... + @property + def internal_value(self) -> _CellGetValue: ... + + @property + def value(self) -> _CellGetValue: ... + @value.setter + def value(self, value: None) -> None: ... + +class EmptyCell: + __slots__ = () + value: Incomplete + is_date: bool + font: Incomplete + border: Incomplete + fill: Incomplete + number_format: Incomplete + alignment: Incomplete + data_type: str + +EMPTY_CELL: Final[EmptyCell] diff --git a/stubs/openpyxl/openpyxl/cell/rich_text.pyi b/stubs/openpyxl/openpyxl/cell/rich_text.pyi new file mode 100644 index 000000000000..68a4e4c0d71f --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/rich_text.pyi @@ -0,0 +1,30 @@ +from collections.abc import Iterable +from typing import Literal, overload +from typing_extensions import Self + +from openpyxl.cell.text import InlineFont +from openpyxl.descriptors import Strict, String, Typed +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element + +class TextBlock(Strict): + font: Typed[InlineFont, Literal[False]] + text: String[Literal[False]] + + def __init__(self, font: InlineFont, text: str) -> None: ... + def __eq__(self, other: TextBlock) -> bool: ... # type: ignore[override] + def to_tree(self) -> Element: ... + +class CellRichText(list[str | TextBlock]): + @overload + def __init__(self, args: list[str] | list[TextBlock] | list[str | TextBlock] | tuple[str | TextBlock, ...], /) -> None: ... + @overload + def __init__(self, *args: str | TextBlock) -> None: ... + + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + def __add__(self, arg: Iterable[str | TextBlock]) -> CellRichText: ... # type: ignore[override] + def append(self, arg: str | TextBlock) -> None: ... + def extend(self, arg: Iterable[str | TextBlock]) -> None: ... + def as_list(self) -> list[str]: ... + def to_tree(self) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/cell/text.pyi b/stubs/openpyxl/openpyxl/cell/text.pyi new file mode 100644 index 000000000000..178fc1611059 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/text.pyi @@ -0,0 +1,97 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Integer, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedString, NestedText, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color +from openpyxl.styles.fonts import Font, _FontScheme, _FontU, _FontVertAlign + +from ..xml._functions_overloads import _HasTagAndGet + +_PhoneticPropertiesType: TypeAlias = Literal["halfwidthKatakana", "fullwidthKatakana", "Hiragana", "noConversion"] +_PhoneticPropertiesAlignment: TypeAlias = Literal["noControl", "left", "center", "distributed"] + +class PhoneticProperties(Serialisable): + tagname: ClassVar[str] + fontId: Integer[Literal[False]] + type: NoneSet[_PhoneticPropertiesType] + alignment: NoneSet[_PhoneticPropertiesAlignment] + def __init__( + self, + fontId: ConvertibleToInt, + type: _PhoneticPropertiesType | Literal["none"] | None = None, + alignment: _PhoneticPropertiesAlignment | Literal["none"] | None = None, + ) -> None: ... + +_PhoneticProperties: TypeAlias = PhoneticProperties + +class PhoneticText(Serialisable): + tagname: ClassVar[str] + sb: Integer[Literal[False]] + eb: Integer[Literal[False]] + t: NestedText[str, Literal[False]] + text: Alias + def __init__(self, sb: ConvertibleToInt, eb: ConvertibleToInt, t: object = None) -> None: ... + +class InlineFont(Font): + tagname: ClassVar[str] + rFont: NestedString[Literal[True]] + # Same as parent + # charset = Font.charset + # family = Font.family + # b = Font.b + # i = Font.i + # strike = Font.strike + # outline = Font.outline + # shadow = Font.shadow + # condense = Font.condense + # extend = Font.extend + # color = Font.color + # sz = Font.sz + # u = Font.u + # vertAlign = Font.vertAlign + # scheme = Font.scheme + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rFont: object = None, + charset: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + family: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + b: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + i: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + strike: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + outline: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + shadow: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + condense: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extend: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + color: Color | None = None, + sz: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + u: _NestedNoneSetParam[_FontU] = None, + vertAlign: _NestedNoneSetParam[_FontVertAlign] = None, + scheme: _NestedNoneSetParam[_FontScheme] = None, + ) -> None: ... + +class RichText(Serialisable): + tagname: ClassVar[str] + rPr: Typed[InlineFont, Literal[True]] + font: Alias + t: NestedText[str, Literal[True]] + text: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rPr: InlineFont | None = None, t: object = None) -> None: ... + +class Text(Serialisable): + tagname: ClassVar[str] + t: NestedText[str, Literal[True]] + plain: Alias + r: Incomplete + formatted: Alias + rPh: Incomplete + phonetic: Alias + phoneticPr: Typed[_PhoneticProperties, Literal[True]] + PhoneticProperties: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, t: object = None, r=(), rPh=(), phoneticPr: _PhoneticProperties | None = None) -> None: ... + @property + def content(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/chart/_3d.pyi b/stubs/openpyxl/openpyxl/chart/_3d.pyi new file mode 100644 index 000000000000..6c12831498f8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/_3d.pyi @@ -0,0 +1,66 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.picture import PictureOptions +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedMinMax +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class View3D(Serialisable): + tagname: ClassVar[str] + rotX: NestedMinMax[float, Literal[True]] + x_rotation: Alias + hPercent: NestedMinMax[float, Literal[True]] + height_percent: Alias + rotY: NestedInteger[Literal[True]] + y_rotation: Alias + depthPercent: NestedInteger[Literal[True]] + rAngAx: NestedBool[Literal[True]] + right_angle_axes: Alias + perspective: NestedInteger[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rotX: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = 15, + hPercent: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + rotY: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = 20, + depthPercent: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + rAngAx: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = True, + perspective: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: Unused = None, + ) -> None: ... + +class Surface(Serialisable): + tagname: ClassVar[str] + thickness: NestedInteger[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + pictureOptions: Typed[PictureOptions, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + thickness: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + spPr: GraphicalProperties | None = None, + pictureOptions: PictureOptions | None = None, + extLst: Unused = None, + ) -> None: ... + +class _3DBase(Serialisable): + tagname: ClassVar[str] + view3D: Typed[View3D, Literal[True]] + floor: Typed[Surface, Literal[True]] + sideWall: Typed[Surface, Literal[True]] + backWall: Typed[Surface, Literal[True]] + def __init__( + self, + view3D: View3D | None = None, + floor: Surface | None = None, + sideWall: Surface | None = None, + backWall: Surface | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/__init__.pyi b/stubs/openpyxl/openpyxl/chart/__init__.pyi new file mode 100644 index 000000000000..5c1c9132ae28 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/__init__.pyi @@ -0,0 +1,18 @@ +from .area_chart import AreaChart as AreaChart, AreaChart3D as AreaChart3D +from .bar_chart import BarChart as BarChart, BarChart3D as BarChart3D +from .bubble_chart import BubbleChart as BubbleChart +from .line_chart import LineChart as LineChart, LineChart3D as LineChart3D +from .pie_chart import ( + DoughnutChart as DoughnutChart, + PieChart as PieChart, + PieChart3D as PieChart3D, + ProjectedPieChart as ProjectedPieChart, +) +from .radar_chart import RadarChart as RadarChart +from .reference import Reference as Reference +from .scatter_chart import ScatterChart as ScatterChart +from .series_factory import SeriesFactory as _SeriesFactory +from .stock_chart import StockChart as StockChart +from .surface_chart import SurfaceChart as SurfaceChart, SurfaceChart3D as SurfaceChart3D + +Series = _SeriesFactory diff --git a/stubs/openpyxl/openpyxl/chart/_chart.pyi b/stubs/openpyxl/openpyxl/chart/_chart.pyi new file mode 100644 index 000000000000..61e472151af8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/_chart.pyi @@ -0,0 +1,50 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.layout import Layout +from openpyxl.chart.legend import Legend +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.title import TitleDescriptor +from openpyxl.descriptors.base import Alias, Bool, Integer, MinMax, Set, Typed +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +_ChartBaseDisplayBlanks: TypeAlias = Literal["span", "gap", "zero"] + +class AxId(Serialisable): + val: Integer[Literal[False]] + def __init__(self, val: ConvertibleToInt) -> None: ... + +def PlotArea(): ... + +class ChartBase(Serialisable): + legend: Typed[Legend, Literal[True]] + layout: Typed[Layout, Literal[True]] + roundedCorners: Bool[Literal[True]] + axId: Incomplete + visible_cells_only: Bool[Literal[True]] + display_blanks: Set[_ChartBaseDisplayBlanks] + ser: Incomplete + series: Alias + title: TitleDescriptor + anchor: str + width: int + height: float + style: MinMax[float, Literal[True]] + mime_type: str + graphical_properties: Typed[GraphicalProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + plot_area: Incomplete + pivotSource: Incomplete + pivotFormats: Incomplete + idx_base: int + def __init__(self, axId=(), **kw: Unused) -> None: ... + def __hash__(self) -> int: ... + def __iadd__(self, other): ... + # namespace is in the wrong order to respect the override. This is an issue in openpyxl itself + def to_tree(self, namespace: Unused = None, tagname: str | None = None, idx: Unused = None) -> Element: ... # type: ignore[override] + def set_categories(self, labels) -> None: ... + def add_data(self, data, from_rows: bool = False, titles_from_data: bool = False) -> None: ... + def append(self, value) -> None: ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/chart/area_chart.pyi b/stubs/openpyxl/openpyxl/chart/area_chart.pyi new file mode 100644 index 000000000000..25c1336a323a --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/area_chart.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines, NumericAxis, SeriesAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedSet + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_AreaChartBaseGrouping: TypeAlias = Literal["percentStacked", "standard", "stacked"] + +class _AreaChartBase(ChartBase): + grouping: NestedSet[_AreaChartBaseGrouping] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + dropLines: Typed[ChartLines, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + grouping: _HasTagAndGet[_AreaChartBaseGrouping] | _AreaChartBaseGrouping = "standard", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + dropLines: ChartLines | None = None, + ) -> None: ... + +class AreaChart(_AreaChartBase): + tagname: ClassVar[str] + # Same as parent + # grouping = _AreaChartBase.grouping + # varyColors = _AreaChartBase.varyColors + # ser = _AreaChartBase.ser + # dLbls = _AreaChartBase.dLbls + # dropLines = _AreaChartBase.dropLines + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, axId: Unused = None, extLst: Unused = None, **kw) -> None: ... + +class AreaChart3D(AreaChart): + tagname: ClassVar[str] + # Same as parent and grandparent + # grouping = _AreaChartBase.grouping + # varyColors = _AreaChartBase.varyColors + # ser = _AreaChartBase.ser + # dLbls = _AreaChartBase.dLbls + # dropLines = _AreaChartBase.dropLines + gapDepth: Incomplete + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + z_axis: Typed[SeriesAxis, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, gapDepth=None, **kw) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/axis.pyi b/stubs/openpyxl/openpyxl/chart/axis.pyi new file mode 100644 index 000000000000..b98f29d87c35 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/axis.pyi @@ -0,0 +1,312 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload +from typing_extensions import Self + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText, Text +from openpyxl.chart.title import Title, TitleDescriptor +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import ( + NestedBool, + NestedFloat, + NestedInteger, + NestedMinMax, + NestedNoneSet, + NestedSet, + _NestedNoneSetParam, +) +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet, _SupportsFindAndIterAndAttribAndText + +_ScalingOrientation: TypeAlias = Literal["maxMin", "minMax"] +_BaseAxisAxPos: TypeAlias = Literal["b", "l", "r", "t"] +_BaseAxisTickMark: TypeAlias = Literal["cross", "in", "out"] +_BaseAxisTickLblPos: TypeAlias = Literal["high", "low", "nextTo"] +_BaseAxisCrosses: TypeAlias = Literal["autoZero", "max", "min"] +_DisplayUnitsLabelListBuiltInUnit: TypeAlias = Literal[ + "hundreds", + "thousands", + "tenThousands", + "hundredThousands", + "millions", + "tenMillions", + "hundredMillions", + "billions", + "trillions", +] +_NumericAxisCrossBetween: TypeAlias = Literal["between", "midCat"] +_TextAxisLblAlgn: TypeAlias = Literal["ctr", "l", "r"] +_DateAxisTimeUnit: TypeAlias = Literal["days", "months", "years"] + +class ChartLines(Serialisable): + tagname: ClassVar[str] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + def __init__(self, spPr: GraphicalProperties | None = None) -> None: ... + +class Scaling(Serialisable): + tagname: ClassVar[str] + logBase: NestedFloat[Literal[True]] + orientation: NestedSet[_ScalingOrientation] + max: NestedFloat[Literal[True]] + min: NestedFloat[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + logBase: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + orientation: _HasTagAndGet[_ScalingOrientation] | _ScalingOrientation = "minMax", + max: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + min: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + extLst: Unused = None, + ) -> None: ... + +class _BaseAxis(Serialisable): + axId: NestedInteger[Literal[False]] + scaling: Typed[Scaling, Literal[False]] + delete: NestedBool[Literal[True]] + axPos: NestedSet[_BaseAxisAxPos] + majorGridlines: Typed[ChartLines, Literal[True]] + minorGridlines: Typed[ChartLines, Literal[True]] + title: TitleDescriptor + numFmt: Incomplete + number_format: Alias + majorTickMark: NestedNoneSet[_BaseAxisTickMark] + minorTickMark: NestedNoneSet[_BaseAxisTickMark] + tickLblPos: NestedNoneSet[_BaseAxisTickLblPos] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + crossAx: NestedInteger[Literal[False]] + crosses: NestedNoneSet[_BaseAxisCrosses] + crossesAt: NestedFloat[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + axId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + scaling: Scaling | None, + delete: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + axPos: _HasTagAndGet[_BaseAxisAxPos] | _BaseAxisAxPos, + majorGridlines: ChartLines | None, + minorGridlines: ChartLines | None, + title: str | Title | None, + numFmt: Incomplete | None, + majorTickMark: _NestedNoneSetParam[_BaseAxisTickMark], + minorTickMark: _NestedNoneSetParam[_BaseAxisTickMark], + tickLblPos: _NestedNoneSetParam[_BaseAxisTickLblPos], + spPr: GraphicalProperties | None, + txPr: RichText | None, + crossAx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + crosses: _NestedNoneSetParam[_BaseAxisCrosses] = None, + crossesAt: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + ) -> None: ... + @overload + def __init__( + self, + axId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + scaling: Scaling | None = None, + delete: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + axPos: _HasTagAndGet[_BaseAxisAxPos] | _BaseAxisAxPos = "l", + majorGridlines: ChartLines | None = None, + minorGridlines: ChartLines | None = None, + title: str | Title | None = None, + numFmt=None, + majorTickMark=None, + minorTickMark=None, + tickLblPos=None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + *, + crossAx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + crosses=None, + crossesAt: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + ) -> None: ... + +class DisplayUnitsLabel(Serialisable): + tagname: ClassVar[str] + layout: Typed[Layout, Literal[True]] + tx: Typed[Text, Literal[True]] + text: Alias + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textPropertes: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layout: Layout | None = None, + tx: Text | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + ) -> None: ... + +class DisplayUnitsLabelList(Serialisable): + tagname: ClassVar[str] + custUnit: NestedFloat[Literal[True]] + builtInUnit: NestedNoneSet[_DisplayUnitsLabelListBuiltInUnit] + dispUnitsLbl: Typed[DisplayUnitsLabel, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + custUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + builtInUnit: ( + _HasTagAndGet[_DisplayUnitsLabelListBuiltInUnit] | _DisplayUnitsLabelListBuiltInUnit | Literal["none"] | None + ) = None, + dispUnitsLbl: DisplayUnitsLabel | None = None, + extLst: Unused = None, + ) -> None: ... + +class NumericAxis(_BaseAxis): + tagname: ClassVar[str] + # Same as parent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + crossBetween: NestedNoneSet[_NumericAxisCrossBetween] + majorUnit: NestedFloat[Literal[True]] + minorUnit: NestedFloat[Literal[True]] + dispUnits: Typed[DisplayUnitsLabelList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + crossBetween: _NestedNoneSetParam[_NumericAxisCrossBetween] = None, + majorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + minorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + dispUnits: DisplayUnitsLabelList | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... + @classmethod + def from_tree(cls, node: _SupportsFindAndIterAndAttribAndText) -> Self: ... + +class TextAxis(_BaseAxis): + tagname: ClassVar[str] + # Same as parent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + auto: NestedBool[Literal[True]] + lblAlgn: NestedNoneSet[_TextAxisLblAlgn] + lblOffset: NestedMinMax[float, Literal[False]] + tickLblSkip: NestedInteger[Literal[True]] + tickMarkSkip: NestedInteger[Literal[True]] + noMultiLvlLbl: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + auto: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + lblAlgn: _NestedNoneSetParam[_TextAxisLblAlgn] = None, + lblOffset: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat = 100, + tickLblSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + tickMarkSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + noMultiLvlLbl: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... + +class DateAxis(TextAxis): + tagname: ClassVar[str] + # Same as parent and grandparent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + auto: NestedBool[Literal[True]] + lblOffset: NestedInteger[Literal[True]] # type: ignore[assignment] + baseTimeUnit: NestedNoneSet[_DateAxisTimeUnit] + majorUnit: NestedFloat[Literal[True]] + majorTimeUnit: NestedNoneSet[_DateAxisTimeUnit] + minorUnit: NestedFloat[Literal[True]] + minorTimeUnit: NestedNoneSet[_DateAxisTimeUnit] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + auto: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + lblOffset: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + baseTimeUnit: _NestedNoneSetParam[_DateAxisTimeUnit] = None, + majorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + majorTimeUnit: _NestedNoneSetParam[_DateAxisTimeUnit] = None, + minorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + minorTimeUnit: _NestedNoneSetParam[_DateAxisTimeUnit] = None, + extLst: Unused = None, + **kw, + ) -> None: ... + +class SeriesAxis(_BaseAxis): + tagname: ClassVar[str] + # Same as parent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + tickLblSkip: NestedInteger[Literal[True]] + tickMarkSkip: NestedInteger[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tickLblSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + tickMarkSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/bar_chart.pyi b/stubs/openpyxl/openpyxl/chart/bar_chart.pyi new file mode 100644 index 000000000000..eecafc725838 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/bar_chart.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines, NumericAxis, SeriesAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedNoneSet, NestedSet, _NestedNoneSetParam + +from ..xml._functions_overloads import _HasTagAndGet +from ._3d import _3DBase +from ._chart import ChartBase + +_BarChartBaseBarDir: TypeAlias = Literal["bar", "col"] +_BarChartBaseGrouping: TypeAlias = Literal["percentStacked", "clustered", "standard", "stacked"] +_BarChart3DShape: TypeAlias = Literal["cone", "coneToMax", "box", "cylinder", "pyramid", "pyramidToMax"] + +class _BarChartBase(ChartBase): + barDir: NestedSet[_BarChartBaseBarDir] + type: Alias + grouping: NestedSet[_BarChartBaseGrouping] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + barDir: _HasTagAndGet[_BarChartBaseBarDir] | _BarChartBaseBarDir = "col", + grouping: _HasTagAndGet[_BarChartBaseGrouping] | _BarChartBaseGrouping = "clustered", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + **kw, + ) -> None: ... + +class BarChart(_BarChartBase): + tagname: ClassVar[str] + # Same as parent + # barDir = _BarChartBase.barDir + # grouping = _BarChartBase.grouping + # varyColors = _BarChartBase.varyColors + # ser = _BarChartBase.ser + # dLbls = _BarChartBase.dLbls + gapWidth: Incomplete + overlap: Incomplete + serLines: Typed[ChartLines, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + legend: Incomplete + def __init__( + self, gapWidth: int = 150, overlap=None, serLines: ChartLines | None = None, extLst: Unused = None, **kw + ) -> None: ... + +class BarChart3D(_BarChartBase, _3DBase): + tagname: ClassVar[str] + # Same as parents + # barDir = _BarChartBase.barDir + # grouping = _BarChartBase.grouping + # varyColors = _BarChartBase.varyColors + # ser = _BarChartBase.ser + # dLbls = _BarChartBase.dLbls + # view3D = _3DBase.view3D + # floor = _3DBase.floor + # sideWall = _3DBase.sideWall + # backWall = _3DBase.backWall + gapWidth: Incomplete + gapDepth: Incomplete + shape: NestedNoneSet[_BarChart3DShape] + serLines: Typed[ChartLines, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + z_axis: Typed[SeriesAxis, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + gapWidth: int = 150, + gapDepth: int = 150, + shape: _NestedNoneSetParam[_BarChart3DShape] = None, + serLines: ChartLines | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/bubble_chart.pyi b/stubs/openpyxl/openpyxl/chart/bubble_chart.pyi new file mode 100644 index 000000000000..d9e1cd4dc4f8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/bubble_chart.pyi @@ -0,0 +1,40 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import NumericAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedMinMax, NestedNoneSet, _NestedNoneSetParam + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_BubbleChartSizeRepresents: TypeAlias = Literal["area", "w"] + +class BubbleChart(ChartBase): + tagname: ClassVar[str] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + bubble3D: NestedBool[Literal[True]] + bubbleScale: NestedMinMax[float, Literal[True]] + showNegBubbles: NestedBool[Literal[True]] + sizeRepresents: NestedNoneSet[_BubbleChartSizeRepresents] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[NumericAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + bubble3D: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + bubbleScale: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + showNegBubbles: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + sizeRepresents: _NestedNoneSetParam[_BubbleChartSizeRepresents] = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/chartspace.pyi b/stubs/openpyxl/openpyxl/chart/chartspace.pyi new file mode 100644 index 000000000000..5e21bb8397a7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/chartspace.pyi @@ -0,0 +1,147 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.chart._3d import Surface, View3D +from openpyxl.chart.legend import Legend +from openpyxl.chart.pivot import PivotSource +from openpyxl.chart.plotarea import PlotArea +from openpyxl.chart.print_settings import PrintSettings +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.chart.title import Title +from openpyxl.descriptors.base import Alias, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedMinMax, NestedNoneSet, NestedString, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorMapping +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +_ChartContainerDispBlanksAs: TypeAlias = Literal["span", "gap", "zero"] + +class ChartContainer(Serialisable): + tagname: ClassVar[str] + title: Typed[Title, Literal[True]] + autoTitleDeleted: NestedBool[Literal[True]] + pivotFmts: Incomplete + + # Same as _3DBase + # https://github.com/python/mypy/issues/6700 + view3D: Typed[View3D, Literal[True]] + floor: Typed[Surface, Literal[True]] + sideWall: Typed[Surface, Literal[True]] + backWall: Typed[Surface, Literal[True]] + + plotArea: Typed[PlotArea, Literal[False]] + legend: Typed[Legend, Literal[True]] + plotVisOnly: NestedBool[Literal[False]] + dispBlanksAs: NestedNoneSet[_ChartContainerDispBlanksAs] + showDLblsOverMax: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + title: Title | None = None, + autoTitleDeleted: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + pivotFmts=(), + view3D: View3D | None = None, + floor: Surface | None = None, + sideWall: Surface | None = None, + backWall: Surface | None = None, + plotArea: PlotArea | None = None, + legend: Legend | None = None, + plotVisOnly: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = True, + dispBlanksAs: _NestedNoneSetParam[_ChartContainerDispBlanksAs] = "gap", + showDLblsOverMax: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class Protection(Serialisable): + tagname: ClassVar[str] + chartObject: NestedBool[Literal[True]] + data: NestedBool[Literal[True]] + formatting: NestedBool[Literal[True]] + selection: NestedBool[Literal[True]] + userInterface: NestedBool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + chartObject: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + data: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + formatting: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + selection: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + userInterface: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ) -> None: ... + +class ExternalData(Serialisable): + tagname: ClassVar[str] + autoUpdate: NestedBool[Literal[True]] + id: String[Literal[False]] + + @overload + def __init__( + self, autoUpdate: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, *, id: str + ) -> None: ... + @overload + def __init__(self, autoUpdate: Incomplete | None, id: str) -> None: ... + +class ChartSpace(Serialisable): + tagname: ClassVar[str] + date1904: NestedBool[Literal[True]] + lang: NestedString[Literal[True]] + roundedCorners: NestedBool[Literal[True]] + style: NestedMinMax[float, Literal[True]] + clrMapOvr: Typed[ColorMapping, Literal[True]] + pivotSource: Typed[PivotSource, Literal[True]] + protection: Typed[Protection, Literal[True]] + chart: Typed[ChartContainer, Literal[False]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphical_properties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + externalData: Typed[ExternalData, Literal[True]] + printSettings: Typed[PrintSettings, Literal[True]] + userShapes: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + date1904: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + lang: object = None, + roundedCorners: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + style: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + clrMapOvr: ColorMapping | None = None, + pivotSource: PivotSource | None = None, + protection: Protection | None = None, + *, + chart: ChartContainer, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + externalData: ExternalData | None = None, + printSettings: PrintSettings | None = None, + userShapes=None, + extLst: Unused = None, + ) -> None: ... + @overload + def __init__( + self, + date1904: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + lang: object, + roundedCorners: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + style: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None, + clrMapOvr: ColorMapping | None, + pivotSource: PivotSource | None, + protection: Protection | None, + chart: ChartContainer, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + externalData: ExternalData | None = None, + printSettings: PrintSettings | None = None, + userShapes=None, + extLst: Unused = None, + ) -> None: ... + + def to_tree(self, tagname: Unused = None, idx: Unused = None, namespace: Unused = None) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/chart/data_source.pyi b/stubs/openpyxl/openpyxl/chart/data_source.pyi new file mode 100644 index 000000000000..fa6460de3ae9 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/data_source.pyi @@ -0,0 +1,122 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, overload +from typing_extensions import Never + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Alias, Bool, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedInteger, NestedText +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class NumFmt(Serialisable): + formatCode: String[Literal[False]] + sourceLinked: Bool[Literal[False]] + def __init__(self, formatCode: str, sourceLinked: _ConvertibleToBool = False) -> None: ... + +class NumberValueDescriptor(NestedText[Incomplete, Incomplete]): + allow_none: bool + expected_type: type[Incomplete] + def __set__(self, instance: Serialisable | Strict, value) -> None: ... # type: ignore[override] + +class NumVal(Serialisable): + idx: Integer[Literal[False]] + formatCode: NestedText[str, Literal[True]] + v: Incomplete + def __init__(self, idx: ConvertibleToInt, formatCode: object = None, v=None) -> None: ... + +class NumData(Serialisable): + formatCode: NestedText[str, Literal[True]] + ptCount: NestedInteger[Literal[True]] + pt: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + formatCode: object = None, + ptCount: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + pt=(), + extLst: Unused = None, + ) -> None: ... + +class NumRef(Serialisable): + f: NestedText[str, Literal[False]] + ref: Alias + numCache: Typed[NumData, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, f: object = None, numCache: NumData | None = None, extLst: Unused = None) -> None: ... + +class StrVal(Serialisable): + tagname: ClassVar[str] + idx: Integer[Literal[False]] + v: NestedText[str, Literal[False]] + def __init__(self, idx: ConvertibleToInt = 0, v: object = None) -> None: ... + +class StrData(Serialisable): + tagname: ClassVar[str] + ptCount: NestedInteger[Literal[True]] + pt: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, ptCount: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, pt=(), extLst: Unused = None + ) -> None: ... + +class StrRef(Serialisable): + tagname: ClassVar[str] + f: NestedText[str, Literal[True]] + strCache: Typed[StrData, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, f: object = None, strCache: StrData | None = None, extLst: Unused = None) -> None: ... + +class NumDataSource(Serialisable): + numRef: Typed[NumRef, Literal[True]] + numLit: Typed[NumData, Literal[True]] + def __init__(self, numRef: NumRef | None = None, numLit: NumData | None = None) -> None: ... + +class Level(Serialisable): + tagname: ClassVar[str] + pt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, pt=()) -> None: ... + +class MultiLevelStrData(Serialisable): + tagname: ClassVar[str] + ptCount: Integer[Literal[True]] + lvl: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ptCount: ConvertibleToInt | None = None, lvl=(), extLst: Unused = None) -> None: ... + +class MultiLevelStrRef(Serialisable): + tagname: ClassVar[str] + f: NestedText[str, Literal[False]] + multiLvlStrCache: Typed[MultiLevelStrData, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, f: object = None, multiLvlStrCache: MultiLevelStrData | None = None, extLst: Unused = None) -> None: ... + +class AxDataSource(Serialisable): + tagname: ClassVar[str] + numRef: Typed[NumRef, Literal[True]] + numLit: Typed[NumData, Literal[True]] + strRef: Typed[StrRef, Literal[True]] + strLit: Typed[StrData, Literal[True]] + multiLvlStrRef: Typed[MultiLevelStrRef, Literal[True]] + + @overload + def __init__( + self, numRef: None = None, numLit: None = None, strRef: None = None, strLit: None = None, multiLvlStrRef: None = None + ) -> Never: ... + @overload + def __init__( + self, + numRef: NumRef | None = None, + numLit: NumData | None = None, + strRef: StrRef | None = None, + strLit: StrData | None = None, + multiLvlStrRef: MultiLevelStrRef | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/descriptors.pyi b/stubs/openpyxl/openpyxl/chart/descriptors.pyi new file mode 100644 index 000000000000..fa6f41d0238c --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/descriptors.pyi @@ -0,0 +1,21 @@ +from typing import Literal + +from openpyxl.chart.data_source import NumFmt +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.nested import NestedMinMax +from openpyxl.descriptors.serialisable import Serialisable + +class NestedGapAmount(NestedMinMax[float, bool]): + allow_none: bool + min: float + max: float + +class NestedOverlap(NestedMinMax[float, bool]): + allow_none: bool + min: float + max: float + +class NumberFormatDescriptor(Typed[NumFmt, Literal[True]]): + expected_type: type[NumFmt] + allow_none: Literal[True] + def __set__(self, instance: Serialisable | Strict, value) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/error_bar.pyi b/stubs/openpyxl/openpyxl/chart/error_bar.pyi new file mode 100644 index 000000000000..f39d64fa107f --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/error_bar.pyi @@ -0,0 +1,44 @@ +from _typeshed import ConvertibleToFloat, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.data_source import NumDataSource +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedNoneSet, NestedSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_ErrorBarsErrBarType: TypeAlias = Literal["both", "minus", "plus"] +_ErrorBarsErrValType: TypeAlias = Literal["cust", "fixedVal", "percentage", "stdDev", "stdErr"] +_ErrorBarsErrDir: TypeAlias = Literal["x", "y"] + +class ErrorBars(Serialisable): + tagname: ClassVar[str] + errDir: NestedNoneSet[_ErrorBarsErrDir] + direction: Alias + errBarType: NestedSet[_ErrorBarsErrBarType] + style: Alias + errValType: NestedSet[_ErrorBarsErrValType] + size: Alias + noEndCap: NestedBool[Literal[True]] + plus: Typed[NumDataSource, Literal[True]] + minus: Typed[NumDataSource, Literal[True]] + val: NestedFloat[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + errDir: _NestedNoneSetParam[_ErrorBarsErrDir] = None, + errBarType: _HasTagAndGet[_ErrorBarsErrBarType] | _ErrorBarsErrBarType = "both", + errValType: _HasTagAndGet[_ErrorBarsErrValType] | _ErrorBarsErrValType = "fixedVal", + noEndCap: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + plus: NumDataSource | None = None, + minus: NumDataSource | None = None, + val: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + spPr: GraphicalProperties | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/label.pyi b/stubs/openpyxl/openpyxl/chart/label.pyi new file mode 100644 index 000000000000..4c3fe53b3320 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/label.pyi @@ -0,0 +1,91 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedNoneSet, NestedString, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_DataLabelBaseDLblPos: TypeAlias = Literal["bestFit", "b", "ctr", "inBase", "inEnd", "l", "outEnd", "r", "t"] + +class _DataLabelBase(Serialisable): + numFmt: NestedString[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + dLblPos: NestedNoneSet[_DataLabelBaseDLblPos] + position: Alias + showLegendKey: NestedBool[Literal[True]] + showVal: NestedBool[Literal[True]] + showCatName: NestedBool[Literal[True]] + showSerName: NestedBool[Literal[True]] + showPercent: NestedBool[Literal[True]] + showBubbleSize: NestedBool[Literal[True]] + showLeaderLines: NestedBool[Literal[True]] + separator: NestedString[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + numFmt: object = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + dLblPos: _NestedNoneSetParam[_DataLabelBaseDLblPos] = None, + showLegendKey: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showVal: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showCatName: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showSerName: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showPercent: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showBubbleSize: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showLeaderLines: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + separator: object = None, + extLst: Unused = None, + ) -> None: ... + +class DataLabel(_DataLabelBase): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + # Same as parent + # numFmt = _DataLabelBase.numFmt + # spPr = _DataLabelBase.spPr + # txPr = _DataLabelBase.txPr + # dLblPos = _DataLabelBase.dLblPos + # showLegendKey = _DataLabelBase.showLegendKey + # showVal = _DataLabelBase.showVal + # showCatName = _DataLabelBase.showCatName + # showSerName = _DataLabelBase.showSerName + # showPercent = _DataLabelBase.showPercent + # showBubbleSize = _DataLabelBase.showBubbleSize + # showLeaderLines = _DataLabelBase.showLeaderLines + # separator = _DataLabelBase.separator + # extLst = _DataLabelBase.extLst + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, **kw) -> None: ... + +class DataLabelList(_DataLabelBase): + tagname: ClassVar[str] + dLbl: Incomplete + delete: NestedBool[Literal[True]] + # Same as parent + # numFmt = _DataLabelBase.numFmt + # spPr = _DataLabelBase.spPr + # txPr = _DataLabelBase.txPr + # dLblPos = _DataLabelBase.dLblPos + # showLegendKey = _DataLabelBase.showLegendKey + # showVal = _DataLabelBase.showVal + # showCatName = _DataLabelBase.showCatName + # showSerName = _DataLabelBase.showSerName + # showPercent = _DataLabelBase.showPercent + # showBubbleSize = _DataLabelBase.showBubbleSize + # showLeaderLines = _DataLabelBase.showLeaderLines + # separator = _DataLabelBase.separator + # extLst = _DataLabelBase.extLst + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, dLbl=(), delete: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, **kw + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/layout.pyi b/stubs/openpyxl/openpyxl/chart/layout.pyi new file mode 100644 index 000000000000..dde22b10a1d7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/layout.pyi @@ -0,0 +1,48 @@ +from _typeshed import ConvertibleToFloat, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedMinMax, NestedNoneSet, NestedSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_ManualLayoutMode: TypeAlias = Literal["edge", "factor"] +_ManualLayoutLayoutTarget: TypeAlias = Literal["inner", "outer"] + +class ManualLayout(Serialisable): + tagname: ClassVar[str] + layoutTarget: NestedNoneSet[_ManualLayoutLayoutTarget] + xMode: NestedNoneSet[_ManualLayoutMode] + yMode: NestedNoneSet[_ManualLayoutMode] + wMode: NestedSet[_ManualLayoutMode] + hMode: NestedSet[_ManualLayoutMode] + x: NestedMinMax[float, Literal[True]] + y: NestedMinMax[float, Literal[True]] + w: NestedMinMax[float, Literal[True]] + width: Alias + h: NestedMinMax[float, Literal[True]] + height: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layoutTarget: _NestedNoneSetParam[_ManualLayoutLayoutTarget] = None, + xMode: _NestedNoneSetParam[_ManualLayoutMode] = None, + yMode: _NestedNoneSetParam[_ManualLayoutMode] = None, + wMode: _HasTagAndGet[_ManualLayoutMode] | _ManualLayoutMode = "factor", + hMode: _HasTagAndGet[_ManualLayoutMode] | _ManualLayoutMode = "factor", + x: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + y: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + w: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + h: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + extLst: Unused = None, + ) -> None: ... + +class Layout(Serialisable): + tagname: ClassVar[str] + manualLayout: Typed[ManualLayout, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, manualLayout: ManualLayout | None = None, extLst: Unused = None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/legend.pyi b/stubs/openpyxl/openpyxl/chart/legend.pyi new file mode 100644 index 000000000000..ba5fc7d3aa82 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/legend.pyi @@ -0,0 +1,53 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedSet +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_LegendLegendPos: TypeAlias = Literal["b", "tr", "l", "r", "t"] + +class LegendEntry(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + delete: NestedBool[Literal[False]] + txPr: Typed[RichText, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + delete: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = False, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +class Legend(Serialisable): + tagname: ClassVar[str] + legendPos: NestedSet[_LegendLegendPos] + position: Alias + legendEntry: Incomplete + layout: Typed[Layout, Literal[True]] + overlay: NestedBool[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + legendPos: _HasTagAndGet[_LegendLegendPos] | _LegendLegendPos = "r", + legendEntry=(), + layout: Layout | None = None, + overlay: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/line_chart.pyi b/stubs/openpyxl/openpyxl/chart/line_chart.pyi new file mode 100644 index 000000000000..4bcdc2abd5c8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/line_chart.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines, NumericAxis, _BaseAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.chart.updown_bars import UpDownBars +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedSet + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_LineChartBaseGrouping: TypeAlias = Literal["percentStacked", "standard", "stacked"] + +class _LineChartBase(ChartBase): + grouping: NestedSet[_LineChartBaseGrouping] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + dropLines: Typed[ChartLines, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + grouping: _HasTagAndGet[_LineChartBaseGrouping] | _LineChartBaseGrouping = "standard", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + dropLines: ChartLines | None = None, + **kw, + ) -> None: ... + +class LineChart(_LineChartBase): + tagname: ClassVar[str] + # Same as parent + # grouping = _LineChartBase.grouping + # varyColors = _LineChartBase.varyColors + # ser = _LineChartBase.ser + # dLbls = _LineChartBase.dLbls + # dropLines = _LineChartBase.dropLines + hiLowLines: Typed[ChartLines, Literal[True]] + upDownBars: Typed[UpDownBars, Literal[True]] + marker: NestedBool[Literal[True]] + smooth: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[_BaseAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + hiLowLines: ChartLines | None = None, + upDownBars: UpDownBars | None = None, + marker: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + smooth: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... + +class LineChart3D(_LineChartBase): + tagname: ClassVar[str] + # Same as parent + # grouping = _LineChartBase.grouping + # varyColors = _LineChartBase.varyColors + # ser = _LineChartBase.ser + # dLbls = _LineChartBase.dLbls + # dropLines = _LineChartBase.dropLines + gapDepth: Incomplete + hiLowLines: Typed[ChartLines, Literal[True]] + upDownBars: Typed[UpDownBars, Literal[True]] + marker: NestedBool[Literal[True]] + smooth: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[ExtensionList, Literal[False]] + y_axis: Typed[ExtensionList, Literal[False]] + z_axis: Typed[ExtensionList, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + gapDepth=None, + hiLowLines: ChartLines | None = None, + upDownBars: UpDownBars | None = None, + marker: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + smooth: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/marker.pyi b/stubs/openpyxl/openpyxl/chart/marker.pyi new file mode 100644 index 000000000000..bd526ee90985 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/marker.pyi @@ -0,0 +1,55 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.picture import PictureOptions +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedMinMax, NestedNoneSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_MarkerSymbol: TypeAlias = Literal[ + "circle", "dash", "diamond", "dot", "picture", "plus", "square", "star", "triangle", "x", "auto" +] + +class Marker(Serialisable): + tagname: ClassVar[str] + symbol: NestedNoneSet[_MarkerSymbol] + size: NestedMinMax[float, Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + symbol: _NestedNoneSetParam[_MarkerSymbol] = None, + size: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + spPr: GraphicalProperties | None = None, + extLst: Unused = None, + ) -> None: ... + +class DataPoint(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + invertIfNegative: NestedBool[Literal[True]] + marker: Typed[Marker, Literal[True]] + bubble3D: NestedBool[Literal[True]] + explosion: NestedInteger[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + pictureOptions: Typed[PictureOptions, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + invertIfNegative: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + marker: Marker | None = None, + bubble3D: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + explosion: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + spPr: GraphicalProperties | None = None, + pictureOptions: PictureOptions | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/picture.pyi b/stubs/openpyxl/openpyxl/chart/picture.pyi new file mode 100644 index 000000000000..ee14ab6f85cd --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/picture.pyi @@ -0,0 +1,27 @@ +from _typeshed import ConvertibleToFloat +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import _ConvertibleToBool +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedNoneSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_PictureOptionsPictureFormat: TypeAlias = Literal["stretch", "stack", "stackScale"] + +class PictureOptions(Serialisable): + tagname: ClassVar[str] + applyToFront: NestedBool[Literal[True]] + applyToSides: NestedBool[Literal[True]] + applyToEnd: NestedBool[Literal[True]] + pictureFormat: NestedNoneSet[_PictureOptionsPictureFormat] + pictureStackUnit: NestedFloat[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + applyToFront: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + applyToSides: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + applyToEnd: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + pictureFormat: _NestedNoneSetParam[_PictureOptionsPictureFormat] = None, + pictureStackUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/pie_chart.pyi b/stubs/openpyxl/openpyxl/chart/pie_chart.pyi new file mode 100644 index 000000000000..c43e6f1dafe6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/pie_chart.pyi @@ -0,0 +1,104 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedMinMax, NestedNoneSet, NestedSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_ProjectedPieChartOfPieType: TypeAlias = Literal["pie", "bar"] +_ProjectedPieChartSplitType: TypeAlias = Literal["auto", "cust", "percent", "pos", "val"] + +class _PieChartBase(ChartBase): + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = True, + ser=(), + dLbls: DataLabelList | None = None, + ) -> None: ... + +class PieChart(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + firstSliceAng: NestedMinMax[float, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, firstSliceAng: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat = 0, extLst: Unused = None, **kw + ) -> None: ... + +class PieChart3D(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + +class DoughnutChart(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + firstSliceAng: NestedMinMax[float, Literal[False]] + holeSize: NestedMinMax[float, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + firstSliceAng: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat = 0, + holeSize: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = 10, + extLst: Unused = None, + **kw, + ) -> None: ... + +class CustomSplit(Serialisable): + tagname: ClassVar[str] + secondPiePt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, secondPiePt=()) -> None: ... + +class ProjectedPieChart(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + ofPieType: NestedSet[_ProjectedPieChartOfPieType] + type: Alias + gapWidth: Incomplete + splitType: NestedNoneSet[_ProjectedPieChartSplitType] + splitPos: NestedFloat[Literal[True]] + custSplit: Typed[CustomSplit, Literal[True]] + secondPieSize: NestedMinMax[float, Literal[True]] + serLines: Typed[ChartLines, Literal[True]] + join_lines: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + ofPieType: _HasTagAndGet[_ProjectedPieChartOfPieType] | _ProjectedPieChartOfPieType = "pie", + gapWidth=None, + splitType: _NestedNoneSetParam[_ProjectedPieChartSplitType] = "auto", + splitPos: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + custSplit: CustomSplit | None = None, + secondPieSize: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = 75, + serLines: ChartLines | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/pivot.pyi b/stubs/openpyxl/openpyxl/chart/pivot.pyi new file mode 100644 index 000000000000..2546e921560c --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/pivot.pyi @@ -0,0 +1,51 @@ +from _typeshed import ConvertibleToInt, Unused +from typing import ClassVar, Literal, overload + +from openpyxl.chart.label import DataLabel as _DataLabel +from openpyxl.chart.marker import Marker +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedInteger, NestedText +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class PivotSource(Serialisable): + tagname: ClassVar[str] + name: NestedText[str, Literal[False]] + fmtId: NestedInteger[Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, name: object, fmtId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, extLst: Unused = None + ) -> None: ... + @overload + def __init__( + self, name: object = None, *, fmtId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, extLst: Unused = None + ) -> None: ... + +class PivotFormat(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + TextBody: Alias + marker: Typed[Marker, Literal[True]] + dLbl: Typed[_DataLabel, Literal[True]] + DataLabel: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + marker: Marker | None = None, + dLbl: _DataLabel | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/plotarea.pyi b/stubs/openpyxl/openpyxl/chart/plotarea.pyi new file mode 100644 index 000000000000..286b8150c5ca --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/plotarea.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal +from typing_extensions import Self + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +class DataTable(Serialisable): + tagname: ClassVar[str] + showHorzBorder: NestedBool[Literal[True]] + showVertBorder: NestedBool[Literal[True]] + showOutline: NestedBool[Literal[True]] + showKeys: NestedBool[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + showHorzBorder: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showVertBorder: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showOutline: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showKeys: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +class PlotArea(Serialisable): + tagname: ClassVar[str] + layout: Typed[Layout, Literal[True]] + dTable: Typed[DataTable, Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + areaChart: Incomplete + area3DChart: Incomplete + lineChart: Incomplete + line3DChart: Incomplete + stockChart: Incomplete + radarChart: Incomplete + scatterChart: Incomplete + pieChart: Incomplete + pie3DChart: Incomplete + doughnutChart: Incomplete + barChart: Incomplete + bar3DChart: Incomplete + ofPieChart: Incomplete + surfaceChart: Incomplete + surface3DChart: Incomplete + bubbleChart: Incomplete + valAx: Incomplete + catAx: Incomplete + dateAx: Incomplete + serAx: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layout: Layout | None = None, + dTable: DataTable | None = None, + spPr: GraphicalProperties | None = None, + _charts=(), + _axes=(), + extLst: Unused = None, + ) -> None: ... + def to_tree(self, tagname: str | None = None, idx: Unused = None, namespace: Unused = None) -> Element: ... + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... diff --git a/stubs/openpyxl/openpyxl/chart/print_settings.pyi b/stubs/openpyxl/openpyxl/chart/print_settings.pyi new file mode 100644 index 000000000000..280114e4d7ac --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/print_settings.pyi @@ -0,0 +1,42 @@ +from _typeshed import ConvertibleToFloat +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Float, Typed +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.header_footer import HeaderFooter +from openpyxl.worksheet.page import PrintPageSetup + +class PageMargins(Serialisable): + tagname: ClassVar[str] + l: Float[Literal[False]] + left: Alias + r: Float[Literal[False]] + right: Alias + t: Float[Literal[False]] + top: Alias + b: Float[Literal[False]] + bottom: Alias + header: Float[Literal[False]] + footer: Float[Literal[False]] + def __init__( + self, + l: ConvertibleToFloat = 0.75, + r: ConvertibleToFloat = 0.75, + t: ConvertibleToFloat = 1, + b: ConvertibleToFloat = 1, + header: ConvertibleToFloat = 0.5, + footer: ConvertibleToFloat = 0.5, + ) -> None: ... + +class PrintSettings(Serialisable): + tagname: ClassVar[str] + headerFooter: Typed[HeaderFooter, Literal[True]] + pageMargins: Typed[PageMargins, Literal[True]] + pageSetup: Typed[PrintPageSetup, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + headerFooter: HeaderFooter | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/radar_chart.pyi b/stubs/openpyxl/openpyxl/chart/radar_chart.pyi new file mode 100644 index 000000000000..bf5cc4ca66ac --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/radar_chart.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import NumericAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedSet + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_RadarChartRadarStyle: TypeAlias = Literal["standard", "marker", "filled"] + +class RadarChart(ChartBase): + tagname: ClassVar[str] + radarStyle: NestedSet[_RadarChartRadarStyle] + type: Alias + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + radarStyle: _HasTagAndGet[_RadarChartRadarStyle] | _RadarChartRadarStyle = "standard", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/reader.pyi b/stubs/openpyxl/openpyxl/chart/reader.pyi new file mode 100644 index 000000000000..0e58541f2c2d --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/reader.pyi @@ -0,0 +1 @@ +def read_chart(chartspace): ... diff --git a/stubs/openpyxl/openpyxl/chart/reference.pyi b/stubs/openpyxl/openpyxl/chart/reference.pyi new file mode 100644 index 000000000000..be2cff94b357 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/reference.pyi @@ -0,0 +1,52 @@ +from _typeshed import ConvertibleToInt, Unused +from collections.abc import Generator +from typing import Literal, overload + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import MinMax, String +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet + +class DummyWorksheet: + title: str + def __init__(self, title: str) -> None: ... + +class Reference(Strict): + min_row: MinMax[int, Literal[False]] + max_row: MinMax[int, Literal[False]] + min_col: MinMax[int, Literal[False]] + max_col: MinMax[int, Literal[False]] + range_string: String[Literal[True]] + worksheet: _WorkbookChild | ReadOnlyWorksheet | DummyWorksheet + + @overload + def __init__( + self, + *, + worksheet: _WorkbookChild | ReadOnlyWorksheet | DummyWorksheet | None = None, + min_col: Unused = None, + min_row: Unused = None, + max_col: Unused = None, + max_row: Unused = None, + range_string: str, + ) -> None: ... + @overload + def __init__( + self, + worksheet: _WorkbookChild | ReadOnlyWorksheet, + min_col: ConvertibleToInt, + min_row: ConvertibleToInt, + max_col: ConvertibleToInt | None = None, + max_row: ConvertibleToInt | None = None, + range_string: str | None = None, + ) -> None: ... + + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + @property + def rows(self) -> Generator[Reference]: ... + @property + def cols(self) -> Generator[Reference]: ... + def pop(self): ... + @property + def sheetname(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/chart/scatter_chart.pyi b/stubs/openpyxl/openpyxl/chart/scatter_chart.pyi new file mode 100644 index 000000000000..787e5c5e66c5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/scatter_chart.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import NumericAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedNoneSet, _NestedNoneSetParam + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase as ChartBase + +_ScatterChartScatterStyle: TypeAlias = Literal["line", "lineMarker", "marker", "smooth", "smoothMarker"] + +class ScatterChart(ChartBase): + tagname: ClassVar[str] + scatterStyle: NestedNoneSet[_ScatterChartScatterStyle] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[NumericAxis | TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scatterStyle: _NestedNoneSetParam[_ScatterChartScatterStyle] = None, + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/series.pyi b/stubs/openpyxl/openpyxl/chart/series.pyi new file mode 100644 index 000000000000..7feb904e0961 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/series.pyi @@ -0,0 +1,106 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.data_source import AxDataSource, NumDataSource, StrRef +from openpyxl.chart.error_bar import ErrorBars +from openpyxl.chart.label import DataLabelList +from openpyxl.chart.marker import Marker +from openpyxl.chart.picture import PictureOptions +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.trendline import Trendline +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedNoneSet, NestedText, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +_SeriesShape: TypeAlias = Literal["cone", "coneToMax", "box", "cylinder", "pyramid", "pyramidToMax"] + +attribute_mapping: Incomplete + +class SeriesLabel(Serialisable): + tagname: ClassVar[str] + strRef: Typed[StrRef, Literal[True]] + v: NestedText[str, Literal[True]] + value: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, strRef: StrRef | None = None, v: object = None) -> None: ... + +class Series(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + order: NestedInteger[Literal[False]] + tx: Typed[SeriesLabel, Literal[True]] + title: Alias + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Incomplete + pictureOptions: Typed[PictureOptions, Literal[True]] + dPt: Incomplete + data_points: Alias + dLbls: Typed[DataLabelList, Literal[True]] + labels: Alias + trendline: Typed[Trendline, Literal[True]] + errBars: Typed[ErrorBars, Literal[True]] + cat: Typed[AxDataSource, Literal[True]] + identifiers: Alias + val: Typed[NumDataSource, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + invertIfNegative: NestedBool[Literal[True]] + shape: NestedNoneSet[_SeriesShape] + xVal: Typed[AxDataSource, Literal[True]] + yVal: Typed[NumDataSource, Literal[True]] + bubbleSize: Typed[NumDataSource, Literal[True]] + zVal: Alias + bubble3D: NestedBool[Literal[True]] + marker: Typed[Marker, Literal[True]] + smooth: NestedBool[Literal[True]] + explosion: NestedInteger[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + order: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + tx: SeriesLabel | None = None, + spPr: GraphicalProperties | None = None, + pictureOptions: PictureOptions | None = None, + dPt=(), + dLbls: DataLabelList | None = None, + trendline: Trendline | None = None, + errBars: ErrorBars | None = None, + cat: AxDataSource | None = None, + val: NumDataSource | None = None, + invertIfNegative: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + shape: _NestedNoneSetParam[_SeriesShape] = None, + xVal: AxDataSource | None = None, + yVal: NumDataSource | None = None, + bubbleSize: NumDataSource | None = None, + bubble3D: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + marker: Marker | None = None, + smooth: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + explosion: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: Unused = None, + ) -> None: ... + def to_tree( # type: ignore[override] + self, tagname: str | None = None, idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt | None = None + ) -> Element: ... + +class XYSeries(Series): + # Same as parent + # idx = Series.idx + # order = Series.order + # tx = Series.tx + # spPr = Series.spPr + # dPt = Series.dPt + # dLbls = Series.dLbls + # trendline = Series.trendline + # errBars = Series.errBars + # xVal = Series.xVal + # yVal = Series.yVal + # invertIfNegative = Series.invertIfNegative + # bubbleSize = Series.bubbleSize + # bubble3D = Series.bubble3D + # marker = Series.marker + # smooth = Series.smooth + ... diff --git a/stubs/openpyxl/openpyxl/chart/series_factory.pyi b/stubs/openpyxl/openpyxl/chart/series_factory.pyi new file mode 100644 index 000000000000..9faddc33a413 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/series_factory.pyi @@ -0,0 +1,9 @@ +from .reference import Reference + +def SeriesFactory( + values: Reference | str, + xvalues: Reference | str | None = None, + zvalues: Reference | str | None = None, + title: object = None, + title_from_data: bool = False, +): ... diff --git a/stubs/openpyxl/openpyxl/chart/shapes.pyi b/stubs/openpyxl/openpyxl/chart/shapes.pyi new file mode 100644 index 000000000000..d2758e4b2cc8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/shapes.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import EmptyTag +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, ColorChoiceDescriptor +from openpyxl.drawing.fill import GradientFillProperties, PatternFillProperties +from openpyxl.drawing.geometry import CustomGeometry2D, PresetGeometry2D, Scene3D, Shape3D, Transform2D +from openpyxl.drawing.line import LineProperties + +from ..xml._functions_overloads import _HasTagAndGet + +_GraphicalPropertiesBwMode: TypeAlias = Literal[ + "clr", "auto", "gray", "ltGray", "invGray", "grayWhite", "blackGray", "blackWhite", "black", "white", "hidden" +] + +class GraphicalProperties(Serialisable): + tagname: ClassVar[str] + bwMode: NoneSet[_GraphicalPropertiesBwMode] + xfrm: Typed[Transform2D, Literal[True]] + transform: Alias + custGeom: Typed[CustomGeometry2D, Literal[True]] + prstGeom: Typed[PresetGeometry2D, Literal[True]] + noFill: EmptyTag[Literal[False]] + solidFill: ColorChoiceDescriptor + gradFill: Typed[GradientFillProperties, Literal[True]] + pattFill: Typed[PatternFillProperties, Literal[True]] + ln: Typed[LineProperties, Literal[True]] + line: Alias + scene3d: Typed[Scene3D, Literal[True]] + sp3d: Typed[Shape3D, Literal[True]] + shape3D: Alias + extLst: Typed[Incomplete, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + bwMode: _GraphicalPropertiesBwMode | Literal["none"] | None = None, + xfrm: Transform2D | None = None, + noFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + solidFill: str | ColorChoice | None = None, + gradFill: GradientFillProperties | None = None, + pattFill: PatternFillProperties | None = None, + ln=None, + scene3d: Scene3D | None = None, + custGeom: CustomGeometry2D | None = None, + prstGeom: PresetGeometry2D | None = None, + sp3d: Shape3D | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/stock_chart.pyi b/stubs/openpyxl/openpyxl/chart/stock_chart.pyi new file mode 100644 index 000000000000..1d2a715e4e6d --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/stock_chart.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.axis import ChartLines, NumericAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.chart.updown_bars import UpDownBars +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList + +from ._chart import ChartBase + +class StockChart(ChartBase): + tagname: ClassVar[str] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + dropLines: Typed[ChartLines, Literal[True]] + hiLowLines: Typed[ChartLines, Literal[True]] + upDownBars: Typed[UpDownBars, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + ser=(), + dLbls: DataLabelList | None = None, + dropLines: ChartLines | None = None, + hiLowLines: ChartLines | None = None, + upDownBars: UpDownBars | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/surface_chart.pyi b/stubs/openpyxl/openpyxl/chart/surface_chart.pyi new file mode 100644 index 000000000000..944a588bd508 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/surface_chart.pyi @@ -0,0 +1,65 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.chart.axis import NumericAxis, SeriesAxis, TextAxis +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet +from ._3d import _3DBase +from ._chart import ChartBase + +class BandFormat(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, spPr: GraphicalProperties | None = None + ) -> None: ... + +class BandFormatList(Serialisable): + tagname: ClassVar[str] + bandFmt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, bandFmt=()) -> None: ... + +class _SurfaceChartBase(ChartBase): + wireframe: NestedBool[Literal[True]] + ser: Incomplete + bandFmts: Typed[BandFormatList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + wireframe: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + bandFmts: BandFormatList | None = None, + **kw, + ) -> None: ... + +class SurfaceChart3D(_SurfaceChartBase, _3DBase): + tagname: ClassVar[str] + # Same as parent + # wireframe = _SurfaceChartBase.wireframe + # ser = _SurfaceChartBase.ser + # bandFmts = _SurfaceChartBase.bandFmts + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + z_axis: Typed[SeriesAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, **kw) -> None: ... + +class SurfaceChart(SurfaceChart3D): + tagname: ClassVar[str] + # Same as parent and grandparent + # wireframe = _SurfaceChartBase.wireframe + # ser = _SurfaceChartBase.ser + # bandFmts = _SurfaceChartBase.bandFmts + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, **kw) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/text.pyi b/stubs/openpyxl/openpyxl/chart/text.pyi new file mode 100644 index 000000000000..b576900cc2e7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/text.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.data_source import StrRef +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.text import ListStyle, RichTextProperties +from openpyxl.xml.functions import Element + +class RichText(Serialisable): + tagname: ClassVar[str] + bodyPr: Typed[RichTextProperties, Literal[False]] + properties: Alias + lstStyle: Typed[ListStyle, Literal[True]] + p: Incomplete + paragraphs: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, bodyPr: RichTextProperties | None = None, lstStyle: ListStyle | None = None, p=None) -> None: ... + +class Text(Serialisable): + tagname: ClassVar[str] + strRef: Typed[StrRef, Literal[True]] + rich: Typed[RichText, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, strRef: StrRef | None = None, rich: RichText | None = None) -> None: ... + def to_tree(self, tagname: str | None = None, idx: Unused = None, namespace: str | None = None) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/chart/title.pyi b/stubs/openpyxl/openpyxl/chart/title.pyi new file mode 100644 index 000000000000..b602afe2e066 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/title.pyi @@ -0,0 +1,42 @@ +from _typeshed import Unused +from typing import ClassVar, Literal + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText, Text +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.base import Alias, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class Title(Serialisable): + tagname: ClassVar[str] + tx: Typed[Text, Literal[True]] + text: Alias + layout: Typed[Layout, Literal[True]] + overlay: NestedBool[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + body: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tx: Text | None = None, + layout: Layout | None = None, + overlay: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +def title_maker(text) -> Title: ... + +class TitleDescriptor(Typed[Title, Literal[True]]): + expected_type: type[Title] + allow_none: Literal[True] + def __set__(self, instance: Serialisable | Strict, value: str | Title | None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/trendline.pyi b/stubs/openpyxl/openpyxl/chart/trendline.pyi new file mode 100644 index 000000000000..9b93515b49b0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/trendline.pyi @@ -0,0 +1,67 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.data_source import NumFmt +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText, Text +from openpyxl.descriptors.base import Alias, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedInteger, NestedSet +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml._functions_overloads import _HasTagAndGet + +_TrendlineTrendlineType: TypeAlias = Literal["exp", "linear", "log", "movingAvg", "poly", "power"] + +class TrendlineLabel(Serialisable): + tagname: ClassVar[str] + layout: Typed[Layout, Literal[True]] + tx: Typed[Text, Literal[True]] + numFmt: Typed[NumFmt, Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layout: Layout | None = None, + tx: Text | None = None, + numFmt: NumFmt | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +class Trendline(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + spPr: Typed[ExtensionList, Literal[True]] + graphicalProperties: Alias + trendlineType: NestedSet[_TrendlineTrendlineType] + order: NestedInteger[Literal[True]] + period: NestedInteger[Literal[True]] + forward: NestedFloat[Literal[True]] + backward: NestedFloat[Literal[True]] + intercept: NestedFloat[Literal[True]] + dispRSqr: NestedBool[Literal[True]] + dispEq: NestedBool[Literal[True]] + trendlineLbl: Typed[ExtensionList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str | None = None, + spPr: ExtensionList | None = None, + trendlineType: _HasTagAndGet[_TrendlineTrendlineType] | _TrendlineTrendlineType = "linear", + order: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + period: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + forward: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + backward: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + intercept: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + dispRSqr: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + dispEq: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + trendlineLbl: ExtensionList | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/updown_bars.pyi b/stubs/openpyxl/openpyxl/chart/updown_bars.pyi new file mode 100644 index 000000000000..15fb09bef0c2 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/updown_bars.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.axis import ChartLines +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +class UpDownBars(Serialisable): + tagname: ClassVar[str] + gapWidth: Incomplete + upBars: Typed[ChartLines, Literal[True]] + downBars: Typed[ChartLines, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, gapWidth: int = 150, upBars: ChartLines | None = None, downBars: ChartLines | None = None, extLst: Unused = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/__init__.pyi b/stubs/openpyxl/openpyxl/chartsheet/__init__.pyi new file mode 100644 index 000000000000..59dba6f1cbf3 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/__init__.pyi @@ -0,0 +1 @@ +from .chartsheet import Chartsheet as Chartsheet diff --git a/stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi b/stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi new file mode 100644 index 000000000000..84d4fafede37 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi @@ -0,0 +1,59 @@ +from _typeshed import Unused +from typing import ClassVar, Literal + +from openpyxl import _Decodable, _VisibilityType +from openpyxl.chartsheet.custom import CustomChartsheetViews +from openpyxl.chartsheet.properties import ChartsheetProperties +from openpyxl.chartsheet.protection import ChartsheetProtection +from openpyxl.chartsheet.publish import WebPublishItems +from openpyxl.chartsheet.relation import DrawingHF, SheetBackgroundPicture +from openpyxl.chartsheet.views import ChartsheetViewList +from openpyxl.descriptors.base import Alias, Set, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.drawing import Drawing +from openpyxl.worksheet.header_footer import HeaderFooter as _HeaderFooter +from openpyxl.worksheet.page import PageMargins, PrintPageSetup +from openpyxl.xml.functions import Element + +class Chartsheet(_WorkbookChild, Serialisable): + tagname: ClassVar[str] + mime_type: str + sheetPr: Typed[ChartsheetProperties, Literal[True]] + sheetViews: Typed[ChartsheetViewList, Literal[False]] + sheetProtection: Typed[ChartsheetProtection, Literal[True]] + customSheetViews: Typed[CustomChartsheetViews, Literal[True]] + pageMargins: Typed[PageMargins, Literal[True]] + pageSetup: Typed[PrintPageSetup, Literal[True]] + drawing: Typed[Drawing, Literal[True]] + drawingHF: Typed[DrawingHF, Literal[True]] + picture: Typed[SheetBackgroundPicture, Literal[True]] + webPublishItems: Typed[WebPublishItems, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + sheet_state: Set[_VisibilityType] + headerFooter: Typed[_HeaderFooter, Literal[False]] + HeaderFooter: Alias # type: ignore[assignment] # Different from parent class + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + sheetPr: ChartsheetProperties | None = None, + sheetViews: ChartsheetViewList | None = None, + sheetProtection: ChartsheetProtection | None = None, + customSheetViews: CustomChartsheetViews | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + headerFooter: _HeaderFooter | None = None, + drawing: Unused = None, + drawingHF: DrawingHF | None = None, + picture: SheetBackgroundPicture | None = None, + webPublishItems: WebPublishItems | None = None, + extLst: Unused = None, + parent: Workbook | None = None, + title: str | _Decodable | None = "", + sheet_state: _VisibilityType = "visible", + ) -> None: ... + def add_chart(self, chart) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/chartsheet/custom.pyi b/stubs/openpyxl/openpyxl/chartsheet/custom.pyi new file mode 100644 index 000000000000..be243e9f8fb2 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/custom.pyi @@ -0,0 +1,49 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl import _VisibilityType +from openpyxl.descriptors.base import Bool, Integer, Set, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.header_footer import HeaderFooter +from openpyxl.worksheet.page import PageMargins, PrintPageSetup + +class CustomChartsheetView(Serialisable): + tagname: ClassVar[str] + guid: Incomplete + scale: Integer[Literal[False]] + state: Set[_VisibilityType] + zoomToFit: Bool[Literal[True]] + pageMargins: Typed[PageMargins, Literal[True]] + pageSetup: Typed[PrintPageSetup, Literal[True]] + headerFooter: Typed[HeaderFooter, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + guid=None, + *, + scale: ConvertibleToInt, + state: _VisibilityType = "visible", + zoomToFit: _ConvertibleToBool | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + headerFooter: HeaderFooter | None = None, + ) -> None: ... + @overload + def __init__( + self, + guid: Incomplete | None, + scale: ConvertibleToInt, + state: _VisibilityType = "visible", + zoomToFit: _ConvertibleToBool | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + headerFooter: HeaderFooter | None = None, + ) -> None: ... + +class CustomChartsheetViews(Serialisable): + tagname: ClassVar[str] + customSheetView: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, customSheetView=None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/properties.pyi b/stubs/openpyxl/openpyxl/chartsheet/properties.pyi new file mode 100644 index 000000000000..c04213b58c33 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/properties.pyi @@ -0,0 +1,15 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color + +class ChartsheetProperties(Serialisable): + tagname: ClassVar[str] + published: Bool[Literal[True]] + codeName: String[Literal[True]] + tabColor: Typed[Color, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, published: _ConvertibleToBool | None = None, codeName: str | None = None, tabColor: Color | None = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/protection.pyi b/stubs/openpyxl/openpyxl/chartsheet/protection.pyi new file mode 100644 index 000000000000..c109380c2dd2 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/protection.pyi @@ -0,0 +1,27 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.protection import _Protected + +class ChartsheetProtection(Serialisable, _Protected): + tagname: ClassVar[str] + algorithmName: String[Literal[True]] + hashValue: Incomplete + saltValue: Incomplete + spinCount: Integer[Literal[True]] + content: Bool[Literal[True]] + objects: Bool[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + password: Incomplete + def __init__( + self, + content: _ConvertibleToBool | None = None, + objects: _ConvertibleToBool | None = None, + hashValue=None, + spinCount: ConvertibleToInt | None = None, + saltValue=None, + algorithmName: str | None = None, + password=None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/publish.pyi b/stubs/openpyxl/openpyxl/chartsheet/publish.pyi new file mode 100644 index 000000000000..e18f600c6991 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/publish.pyi @@ -0,0 +1,53 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, Set, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_WebPublishItemSourceType: TypeAlias = Literal[ + "sheet", "printArea", "autoFilter", "range", "chart", "pivotTable", "query", "label" +] + +class WebPublishItem(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[False]] + divId: String[Literal[False]] + sourceType: Set[_WebPublishItemSourceType] + sourceRef: String[Literal[False]] + sourceObject: String[Literal[True]] + destinationFile: String[Literal[False]] + title: String[Literal[True]] + autoRepublish: Bool[Literal[True]] + + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceType: _WebPublishItemSourceType, + sourceRef: str, + sourceObject: str | None = None, + *, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceType: _WebPublishItemSourceType, + sourceRef: str, + sourceObject: str | None, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + +class WebPublishItems(Serialisable): + tagname: ClassVar[str] + count: Integer[Literal[True]] + webPublishItem: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: ConvertibleToInt | None = None, webPublishItem=None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/relation.pyi b/stubs/openpyxl/openpyxl/chartsheet/relation.pyi new file mode 100644 index 000000000000..d355d7a7b1eb --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/relation.pyi @@ -0,0 +1,71 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Integer +from openpyxl.descriptors.serialisable import Serialisable + +class SheetBackgroundPicture(Serialisable): + tagname: ClassVar[str] + id: Incomplete + def __init__(self, id) -> None: ... + +class DrawingHF(Serialisable): + id: Incomplete + lho: Integer[Literal[True]] + leftHeaderOddPages: Alias + lhe: Integer[Literal[True]] + leftHeaderEvenPages: Alias + lhf: Integer[Literal[True]] + leftHeaderFirstPage: Alias + cho: Integer[Literal[True]] + centerHeaderOddPages: Alias + che: Integer[Literal[True]] + centerHeaderEvenPages: Alias + chf: Integer[Literal[True]] + centerHeaderFirstPage: Alias + rho: Integer[Literal[True]] + rightHeaderOddPages: Alias + rhe: Integer[Literal[True]] + rightHeaderEvenPages: Alias + rhf: Integer[Literal[True]] + rightHeaderFirstPage: Alias + lfo: Integer[Literal[True]] + leftFooterOddPages: Alias + lfe: Integer[Literal[True]] + leftFooterEvenPages: Alias + lff: Integer[Literal[True]] + leftFooterFirstPage: Alias + cfo: Integer[Literal[True]] + centerFooterOddPages: Alias + cfe: Integer[Literal[True]] + centerFooterEvenPages: Alias + cff: Integer[Literal[True]] + centerFooterFirstPage: Alias + rfo: Integer[Literal[True]] + rightFooterOddPages: Alias + rfe: Integer[Literal[True]] + rightFooterEvenPages: Alias + rff: Integer[Literal[True]] + rightFooterFirstPage: Alias + def __init__( + self, + id=None, + lho: ConvertibleToInt | None = None, + lhe: ConvertibleToInt | None = None, + lhf: ConvertibleToInt | None = None, + cho: ConvertibleToInt | None = None, + che: ConvertibleToInt | None = None, + chf: ConvertibleToInt | None = None, + rho: ConvertibleToInt | None = None, + rhe: ConvertibleToInt | None = None, + rhf: ConvertibleToInt | None = None, + lfo: ConvertibleToInt | None = None, + lfe: ConvertibleToInt | None = None, + lff: ConvertibleToInt | None = None, + cfo: ConvertibleToInt | None = None, + cfe: ConvertibleToInt | None = None, + cff: ConvertibleToInt | None = None, + rfo: ConvertibleToInt | None = None, + rfe: ConvertibleToInt | None = None, + rff: ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/views.pyi b/stubs/openpyxl/openpyxl/chartsheet/views.pyi new file mode 100644 index 000000000000..f13138f829b9 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/views.pyi @@ -0,0 +1,30 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +class ChartsheetView(Serialisable): + tagname: ClassVar[str] + tabSelected: Bool[Literal[True]] + zoomScale: Integer[Literal[True]] + workbookViewId: Integer[Literal[False]] + zoomToFit: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tabSelected: _ConvertibleToBool | None = None, + zoomScale: ConvertibleToInt | None = None, + workbookViewId: ConvertibleToInt = 0, + zoomToFit: _ConvertibleToBool | None = True, + extLst: Unused = None, + ) -> None: ... + +class ChartsheetViewList(Serialisable): + tagname: ClassVar[str] + sheetView: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetView=None, extLst: Unused = None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/comments/__init__.pyi b/stubs/openpyxl/openpyxl/comments/__init__.pyi new file mode 100644 index 000000000000..86ce8fc2d81b --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/__init__.pyi @@ -0,0 +1 @@ +from .comments import Comment as Comment diff --git a/stubs/openpyxl/openpyxl/comments/author.pyi b/stubs/openpyxl/openpyxl/comments/author.pyi new file mode 100644 index 000000000000..ceba5327e302 --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/author.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.base import Alias +from openpyxl.descriptors.serialisable import Serialisable + +class AuthorList(Serialisable): + tagname: ClassVar[str] + author: Incomplete + authors: Alias + def __init__(self, author=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/comments/comment_sheet.pyi b/stubs/openpyxl/openpyxl/comments/comment_sheet.pyi new file mode 100644 index 000000000000..f7ea59046e8a --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/comment_sheet.pyi @@ -0,0 +1,124 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Generator +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.cell import _CellOrMergedCell +from openpyxl.cell.text import Text +from openpyxl.comments.author import AuthorList +from openpyxl.comments.comments import Comment +from openpyxl.descriptors.base import Bool, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.ole import ObjectAnchor +from openpyxl.xml.functions import Element + +_PropertiesTextHAlign: TypeAlias = Literal["left", "center", "right", "justify", "distributed"] +_PropertiesTextVAlign: TypeAlias = Literal["top", "center", "bottom", "justify", "distributed"] + +class Properties(Serialisable): + locked: Bool[Literal[True]] + defaultSize: Bool[Literal[True]] + _print: Bool[Literal[True]] # Not private. Avoids name clash + disabled: Bool[Literal[True]] + uiObject: Bool[Literal[True]] + autoFill: Bool[Literal[True]] + autoLine: Bool[Literal[True]] + altText: String[Literal[True]] + textHAlign: Set[_PropertiesTextHAlign] + textVAlign: Set[_PropertiesTextVAlign] + lockText: Bool[Literal[True]] + justLastX: Bool[Literal[True]] + autoScale: Bool[Literal[True]] + rowHidden: Bool[Literal[True]] + colHidden: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + anchor: ObjectAnchor | None + + @overload + def __init__( + self, + locked: _ConvertibleToBool | None = None, + defaultSize: _ConvertibleToBool | None = None, + _print: _ConvertibleToBool | None = None, + disabled: _ConvertibleToBool | None = None, + uiObject: _ConvertibleToBool | None = None, + autoFill: _ConvertibleToBool | None = None, + autoLine: _ConvertibleToBool | None = None, + altText: str | None = None, + *, + textHAlign: _PropertiesTextHAlign, + textVAlign: _PropertiesTextVAlign, + lockText: _ConvertibleToBool | None = None, + justLastX: _ConvertibleToBool | None = None, + autoScale: _ConvertibleToBool | None = None, + rowHidden: _ConvertibleToBool | None = None, + colHidden: _ConvertibleToBool | None = None, + anchor: ObjectAnchor | None = None, + ) -> None: ... + @overload + def __init__( + self, + locked: _ConvertibleToBool | None, + defaultSize: _ConvertibleToBool | None, + _print: _ConvertibleToBool | None, + disabled: _ConvertibleToBool | None, + uiObject: _ConvertibleToBool | None, + autoFill: _ConvertibleToBool | None, + autoLine: _ConvertibleToBool | None, + altText: str | None, + textHAlign: _PropertiesTextHAlign, + textVAlign: _PropertiesTextVAlign, + lockText: _ConvertibleToBool | None = None, + justLastX: _ConvertibleToBool | None = None, + autoScale: _ConvertibleToBool | None = None, + rowHidden: _ConvertibleToBool | None = None, + colHidden: _ConvertibleToBool | None = None, + anchor: ObjectAnchor | None = None, + ) -> None: ... + +class CommentRecord(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + authorId: Integer[Literal[False]] + guid: Incomplete + shapeId: Integer[Literal[True]] + text: Typed[Text, Literal[False]] + commentPr: Typed[Properties, Literal[True]] + author: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + height: Incomplete + width: Incomplete + def __init__( + self, + ref: str = "", + authorId: ConvertibleToInt = 0, + guid=None, + shapeId: ConvertibleToInt | None = 0, + text: Text | None = None, + commentPr: Properties | None = None, + author: str | None = None, + height: int = 79, + width: int = 144, + ) -> None: ... + @classmethod + def from_cell(cls, cell: _CellOrMergedCell): ... + @property + def content(self) -> str: ... + +class CommentSheet(Serialisable): + tagname: ClassVar[str] + authors: Typed[AuthorList, Literal[False]] + commentList: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + mime_type: str + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, authors: AuthorList, commentList=None, extLst: Unused = None) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def comments(self) -> Generator[tuple[str, Comment]]: ... + @classmethod + def from_comments(cls, comments): ... + def write_shapes(self, vml=None): ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/comments/comments.pyi b/stubs/openpyxl/openpyxl/comments/comments.pyi new file mode 100644 index 000000000000..a4966493d9ed --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/comments.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import Any + +class Comment: + content: Incomplete + author: Incomplete + height: Incomplete + width: Incomplete + def __init__(self, text, author, height: int = 79, width: int = 144) -> None: ... + @property + def parent(self) -> Any: ... # AnyOf[Cell, MergedCell, ReadOnlyCell] + def __eq__(self, other: Comment) -> bool: ... # type: ignore[override] + def __copy__(self): ... + def bind(self, cell) -> None: ... + def unbind(self) -> None: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, value: str) -> None: ... diff --git a/stubs/openpyxl/openpyxl/comments/shape_writer.pyi b/stubs/openpyxl/openpyxl/comments/shape_writer.pyi new file mode 100644 index 000000000000..b908498d47a5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/shape_writer.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import Any, TypeAlias + +from ..xml._functions_overloads import _lxml_Element, _ParentElement + +_RootElement: TypeAlias = _ParentElement[Any] | _lxml_Element + +vmlns: str +officens: str +excelns: str + +class ShapeWriter: + vml: Incomplete + vml_path: Incomplete + comments: Incomplete + def __init__(self, comments) -> None: ... + def add_comment_shapetype(self, root: _RootElement) -> None: ... + def add_comment_shape(self, root: _RootElement, idx, coord, height, width) -> None: ... + # Any object missing "findall" is replaced by an Element + def write(self, root: _RootElement | None) -> str: ... diff --git a/stubs/openpyxl/openpyxl/compat/__init__.pyi b/stubs/openpyxl/openpyxl/compat/__init__.pyi new file mode 100644 index 000000000000..5c4b7cd1e711 --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/__init__.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from .numbers import NUMERIC_TYPES as NUMERIC_TYPES +from .strings import safe_string as safe_string + +class DummyCode: ... + +string_types: Incomplete + +def deprecated(reason): ... diff --git a/stubs/openpyxl/openpyxl/compat/abc.pyi b/stubs/openpyxl/openpyxl/compat/abc.pyi new file mode 100644 index 000000000000..5beda934a5fc --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/abc.pyi @@ -0,0 +1 @@ +from abc import ABC as ABC diff --git a/stubs/openpyxl/openpyxl/compat/numbers.pyi b/stubs/openpyxl/openpyxl/compat/numbers.pyi new file mode 100644 index 000000000000..060ba461585a --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/numbers.pyi @@ -0,0 +1,13 @@ +from decimal import Decimal +from typing import Final, TypeAlias + +# NOTE: Can't specify numpy as a dependency because openpyxl doesn't declare it as one +# import numpy +# import numpy._typing +# _NBitBase: TypeAlias = numpy._typing.NBitBase +# _NumericTypes: TypeAlias = int | float | Decimal | numpy.bool_ | numpy.floating[_NBitBase] | numpy.integer[_NBitBase] + +_NumericTypes: TypeAlias = int | float | Decimal +NUMERIC_TYPES: Final[tuple[type[_NumericTypes], ...]] + +NUMPY: Final[bool] diff --git a/stubs/openpyxl/openpyxl/compat/product.pyi b/stubs/openpyxl/openpyxl/compat/product.pyi new file mode 100644 index 000000000000..60e7b2989a5c --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/product.pyi @@ -0,0 +1,3 @@ +def product(sequence): ... + +prod = product diff --git a/stubs/openpyxl/openpyxl/compat/singleton.pyi b/stubs/openpyxl/openpyxl/compat/singleton.pyi new file mode 100644 index 000000000000..65749ec98e3a --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/singleton.pyi @@ -0,0 +1,17 @@ +from typing import Any, overload + +class Singleton(type): + @overload + def __init__(self, o: object, /) -> None: ... + @overload + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + +class Cached(type): + @overload + def __init__(self, o: object, /) -> None: ... + @overload + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + + def __call__(self, *args: Any) -> Any: ... diff --git a/stubs/openpyxl/openpyxl/compat/strings.pyi b/stubs/openpyxl/openpyxl/compat/strings.pyi new file mode 100644 index 000000000000..7d21aa72e2a7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/strings.pyi @@ -0,0 +1,6 @@ +import sys +from typing import Final + +VER: Final[sys._version_info] + +def safe_string(value: object) -> str: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/__init__.pyi b/stubs/openpyxl/openpyxl/descriptors/__init__.pyi new file mode 100644 index 000000000000..18097e820254 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/__init__.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete, Self + +from .base import * +from .sequence import Sequence as Sequence + +class MetaStrict(type): + def __new__(cls: type[Self], clsname: str, bases: tuple[type, ...], methods: dict[str, Descriptor[Incomplete]]) -> Self: ... + +class MetaSerialisable(type): + def __new__(cls: type[Self], clsname: str, bases: tuple[type, ...], methods: dict[str, Descriptor[Incomplete]]) -> Self: ... + +class Strict(metaclass=MetaStrict): ... diff --git a/stubs/openpyxl/openpyxl/descriptors/base.pyi b/stubs/openpyxl/openpyxl/descriptors/base.pyi new file mode 100644 index 000000000000..5636a3b25226 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/base.pyi @@ -0,0 +1,370 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, ReadableBuffer, Unused +from collections.abc import Iterable, Sized +from datetime import datetime +from re import Pattern +from typing import Any, Generic, Literal, TypeAlias, TypeVar, overload + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.fill import Blip +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange + +_T = TypeVar("_T") +_P = TypeVar("_P", str, ReadableBuffer) +_N = TypeVar("_N", bound=bool, default=Literal[False]) +_L = TypeVar("_L", bound=Sized) +_M = TypeVar("_M", int, float) + +_ExpectedTypeParam: TypeAlias = type[_T] | tuple[type[_T], ...] +_ConvertibleToMultiCellRange: TypeAlias = MultiCellRange | str | Iterable[CellRange] +# Since everything is convertible to a bool, this restricts to only intended expected types of intended literals +_ConvertibleToBool: TypeAlias = bool | str | int | None # True | False | "true" | "t" | "false" | "f" | 1 | 0 | None + +class Descriptor(Generic[_T]): + name: str | None + def __init__(self, name: str | None = None, **kw: object) -> None: ... + def __get__(self, instance: Serialisable | Strict, cls: type | None) -> _T: ... + def __set__(self, instance: Serialisable | Strict, value: _T) -> None: ... + +class Typed(Descriptor[_T], Generic[_T, _N]): + __doc__: str + # Members optional in __init__ + expected_type: type[_T] + allow_none: _N + nested: bool + + @overload + def __init__( + self: Typed[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + nested: bool = False, + ) -> None: ... + @overload + def __init__( + self: Typed[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + nested: bool = False, + ) -> None: ... + + @overload + def __get__(self: Typed[_T, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _T | None: ... + @overload + def __get__(self: Typed[_T, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _T: ... + + @overload + def __set__(self: Typed[_T, Literal[True]], instance: Serialisable | Strict, value: _T | None) -> None: ... + @overload + def __set__(self: Typed[_T, Literal[False]], instance: Serialisable | Strict, value: _T) -> None: ... + +class Convertible(Typed[_T, _N]): + @overload + def __init__( + self: Convertible[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + ) -> None: ... + @overload + def __init__( + self: Convertible[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + ) -> None: ... + + # NOTE: It is currently impossible to make a generic based on the parameter type of another generic + # So we implement explicitly the types used internally + # MultiCellRange + @overload + def __set__( + self: Convertible[MultiCellRange, Literal[True]], + instance: Serialisable | Strict, + value: _ConvertibleToMultiCellRange | None, + ) -> None: ... + @overload + def __set__( + self: Convertible[MultiCellRange, Literal[False]], instance: Serialisable | Strict, value: _ConvertibleToMultiCellRange + ) -> None: ... + # str | Blip + @overload + def __set__( + self: Convertible[str, _N] | Convertible[Blip, _N], + instance: Serialisable | Strict, + value: object, # Not[None] when _N = False + ) -> None: ... + # bool + @overload + def __set__(self: Convertible[bool, _N], instance: Serialisable | Strict, value: _ConvertibleToBool) -> None: ... + # int + @overload + def __set__( + self: Convertible[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None + ) -> None: ... + @overload + def __set__(self: Convertible[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + # float + @overload + def __set__( + self: Convertible[float, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToFloat | None + ) -> None: ... + @overload + def __set__(self: Convertible[float, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToFloat) -> None: ... + # Anything else + @overload + def __set__(self: Convertible[_T, Literal[True]], instance: Serialisable | Strict, value: _T | int | Any | None) -> None: ... + +class Max(Convertible[_M, _N]): + expected_type: type[_M] + allow_none: _N + max: float + + @overload + def __init__( + self: Max[int, Literal[True]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[True], max: float + ) -> None: ... + @overload + def __init__( + self: Max[int, Literal[False]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[False] = False, max: float + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: Max[float, Literal[True]], *, expected_type: _ExpectedTypeParam[float] = ..., allow_none: Literal[True], max: float + ) -> None: ... + @overload + def __init__( + self: Max[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + max: float, + ) -> None: ... + + @overload # type: ignore[override] # Different restrictions + def __set__(self: Max[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None) -> None: ... + @overload + def __set__(self: Max[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + @overload + def __set__(self: Max[float, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToFloat | None) -> None: ... + @overload + def __set__(self: Max[float, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToFloat) -> None: ... + +class Min(Convertible[_M, _N]): + expected_type: type[_M] + allow_none: _N + min: float + + @overload + def __init__( + self: Min[int, Literal[True]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[True], min: float + ) -> None: ... + @overload + def __init__( + self: Min[int, Literal[False]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[False] = False, min: float + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: Min[float, Literal[True]], *, expected_type: _ExpectedTypeParam[float] = ..., allow_none: Literal[True], min: float + ) -> None: ... + @overload + def __init__( + self: Min[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + min: float, + ) -> None: ... + + @overload # type: ignore[override] # Different restrictions + def __set__(self: Min[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None) -> None: ... + @overload + def __set__(self: Min[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + @overload + def __set__(self: Min[float, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToFloat | None) -> None: ... + @overload + def __set__(self: Min[float, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToFloat) -> None: ... + +class MinMax(Min[_M, _N], Max[_M, _N]): + expected_type: type[_M] + allow_none: _N + + @overload + def __init__( + self: MinMax[int, Literal[True]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: MinMax[int, Literal[False]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: MinMax[float, Literal[True]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: MinMax[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + +class Set(Descriptor[_T]): + __doc__: str + values: Iterable[_T] + def __init__(self, name: str | None = None, *, values: Iterable[_T]) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _T) -> None: ... + +class NoneSet(Set[_T | None]): + def __init__(self, name: str | None = None, *, values: Iterable[_T | None]) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _T | Literal["none"] | None) -> None: ... + +class Integer(Convertible[int, _N]): + allow_none: _N + expected_type: type[int] + + @overload + def __init__(self: Integer[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: Integer[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class Float(Convertible[float, _N]): + allow_none: _N + expected_type: type[float] + + @overload + def __init__(self: Float[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: Float[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class Bool(Convertible[bool, _N]): + expected_type: type[bool] + allow_none: _N + + @overload + def __init__(self: Bool[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: Bool[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + def __set__(self, instance: Serialisable | Strict, value: _ConvertibleToBool) -> None: ... + +class String(Typed[str, _N]): + allow_none: _N + expected_type: type[str] + + @overload + def __init__(self: String[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: String[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class Text(String[_N], Convertible[str, _N]): ... # unused + +class ASCII(Typed[bytes, _N]): # unused + expected_type: type[bytes] + def __init__(self, name: str | None = None, *, allow_none: bool = False) -> None: ... + +class Tuple(Typed[tuple[Any, ...], _N]): # unused + expected_type: type[tuple[Any, ...]] + def __init__(self, name: str | None = None, *, allow_none: bool = False) -> None: ... + +class Length(Descriptor[_L]): + def __init__(self, name: Unused = None, *, length: int) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _L) -> None: ... + +class Default(Typed[_T, _N]): # unused + def __init__( + self, name: Unused = None, *, expected_type: _ExpectedTypeParam[_T], allow_none: bool = False, defaults: Unused = {} + ) -> None: ... + def __call__(self) -> _T: ... + +# Note: Aliases types can't be inferred. Anyway an alias means there's another option. +# Incomplete: Make it generic with explicit getter/setter type arguments? +class Alias(Descriptor[Incomplete]): + alias: str + def __init__(self, alias: str) -> None: ... + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + def __get__(self, instance: Serialisable | Strict, cls: Unused): ... + +class MatchPattern(Descriptor[_P], Generic[_P, _N]): + allow_none: _N + test_pattern: Pattern[bytes] | Pattern[str] + pattern: str | Pattern[str] | bytes | Pattern[bytes] + + @overload # str + def __init__( + self: MatchPattern[str, Literal[True]], name: str | None = None, *, pattern: str | Pattern[str], allow_none: Literal[True] + ) -> None: ... + @overload # str | None + def __init__( + self: MatchPattern[str, Literal[False]], + name: str | None = None, + *, + pattern: str | Pattern[str], + allow_none: Literal[False] = False, + ) -> None: ... + @overload # bytes + def __init__( + self: MatchPattern[ReadableBuffer, Literal[True]], + name: str | None = None, + *, + pattern: bytes | Pattern[bytes], + allow_none: Literal[True], + ) -> None: ... + @overload # bytes | None + def __init__( + self: MatchPattern[ReadableBuffer, Literal[False]], + name: str | None = None, + *, + pattern: bytes | Pattern[bytes], + allow_none: Literal[False] = False, + ) -> None: ... + + @overload + def __get__(self: MatchPattern[_P, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _P | None: ... + @overload + def __get__(self: MatchPattern[_P, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _P: ... + + @overload + def __set__(self: MatchPattern[_P, Literal[True]], instance: Serialisable | Strict, value: _P | None) -> None: ... + @overload + def __set__(self: MatchPattern[_P, Literal[False]], instance: Serialisable | Strict, value: _P) -> None: ... + +class DateTime(Typed[datetime, _N]): + allow_none: _N + expected_type: type[datetime] + + @overload + def __init__(self: DateTime[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: DateTime[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + @overload + def __set__(self: DateTime[Literal[True]], instance: Serialisable | Strict, value: datetime | str | None) -> None: ... + @overload + def __set__(self: DateTime[Literal[False]], instance: Serialisable | Strict, value: datetime | str) -> None: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/container.pyi b/stubs/openpyxl/openpyxl/descriptors/container.pyi new file mode 100644 index 000000000000..52106f1e6a08 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/container.pyi @@ -0,0 +1,18 @@ +from typing import TypeVar +from typing_extensions import Self + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +_T = TypeVar("_T", bound=Serialisable) + +# Abstract base class. +class ElementList(list[_T]): + @property + def tagname(self) -> str: ... # abstract + @property + def expected_type(self) -> type[_T]: ... # abstract + @classmethod + def from_tree(cls, tree: Element) -> Self: ... + def to_tree(self) -> Element: ... + def append(self, value: _T) -> None: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/excel.pyi b/stubs/openpyxl/openpyxl/descriptors/excel.pyi new file mode 100644 index 000000000000..eabbdcfafe6f --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/excel.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from . import Integer, MatchPattern, MinMax, Strict, String +from .base import _M, _N +from .serialisable import Serialisable + +class HexBinary(MatchPattern[str, Incomplete]): + pattern: str + +class UniversalMeasure(MatchPattern[str, Incomplete]): + pattern: str + +class TextPoint(MinMax[_M, _N]): + expected_type: type[_M] + min: float + max: float + +Coordinate = Integer + +class Percentage(MinMax[float, Incomplete]): + pattern: str + min: float + max: float + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class Extension(Serialisable): + uri: String[Literal[False]] + def __init__(self, uri: str) -> None: ... + +class ExtensionList(Serialisable): + ext: Incomplete + def __init__(self, ext=()) -> None: ... + +class Relation(String[Incomplete]): + namespace: ClassVar[str] + allow_none: bool + +class Base64Binary(MatchPattern[str, Incomplete]): + pattern: str + +class Guid(MatchPattern[str, Incomplete]): + pattern: str + +class CellRange(MatchPattern[str, Incomplete]): + pattern: str + allow_none: bool + def __set__(self, instance: Serialisable | Strict, value) -> None: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/namespace.pyi b/stubs/openpyxl/openpyxl/descriptors/namespace.pyi new file mode 100644 index 000000000000..edb18560d8fa --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/namespace.pyi @@ -0,0 +1,2 @@ +# 'None' shouldn't be a valid tagname and namespaced should always return str +def namespaced(obj: object, tagname: str, namespace: str | None = None) -> str: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/nested.pyi b/stubs/openpyxl/openpyxl/descriptors/nested.pyi new file mode 100644 index 000000000000..4a785b94720f --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/nested.pyi @@ -0,0 +1,289 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from collections.abc import Iterable +from typing import Any, ClassVar, Literal, TypeAlias, overload +from typing_extensions import Never + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Bool, Convertible, Descriptor, Float, Integer, MinMax, NoneSet, Set, String +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.fill import Blip +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasGet, _HasTagAndGet, _HasText +from .base import _M, _N, _T, _ConvertibleToBool, _ExpectedTypeParam + +_NestedNoneSetParam: TypeAlias = _HasTagAndGet[_T | Literal["none"] | None] | _T | Literal["none"] | None + +# NOTE: type: ignore[misc]: Class does not reimplement the relevant methods, so runtime also has incompatible supertypes + +class Nested(Descriptor[_T]): + nested: ClassVar[Literal[True]] + attribute: ClassVar[str] + # Members optional in __init__ + expected_type: type[_T] + allow_none: bool + namespace: str | None + # In usage, "Nested" is closed to "Typed" than "Descriptor", but doesn't use allow_none + def __init__( + self: Nested[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: bool = False, + nested: Unused = True, + namespace: str | None = None, + ) -> None: ... + def __get__(self, instance: Serialisable | Strict, cls: type | None) -> _T: ... + def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_T] | _T) -> None: ... + def from_tree(self, node: _HasGet[_T]) -> _T: ... + + @overload + def to_tree(self, tagname: Unused = None, value: None = None, namespace: Unused = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: object, namespace: str | None = None) -> Element: ... + +class NestedValue(Nested[_T], Convertible[_T, _N]): # type: ignore[misc] + @overload + def __init__( + self: NestedValue[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + ) -> None: ... + @overload + def __init__( + self: NestedValue[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + ) -> None: ... + + @overload + def __get__(self: NestedValue[_T, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _T | None: ... + @overload + def __get__(self: NestedValue[_T, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _T: ... + + # NOTE: It is currently impossible to make a generic based on the parameter type of another generic + # So we implement explicitly the types used internally + # str | Blip + @overload + def __set__( + self: NestedValue[str, _N] | NestedValue[Blip, _N], + instance: Serialisable | Strict, + value: object, # Not[None] when _N = False + ) -> None: ... + # bool + @overload + def __set__( + self: NestedValue[bool, _N], + instance: Serialisable | Strict, + value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool, + ) -> None: ... + # int + @overload + def __set__( + self: NestedValue[int, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + ) -> None: ... + @overload + def __set__( + self: NestedValue[int, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + ) -> None: ... + # float + @overload + def __set__( + self: NestedValue[float, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None, + ) -> None: ... + @overload + def __set__( + self: NestedValue[float, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat, + ) -> None: ... + # Anything else + @overload + def __set__( + self: NestedValue[_T, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[_T | int | Any] | _T | int | Any | None, + ) -> None: ... + +class NestedText(NestedValue[_T, _N]): + @overload + def __init__( + self: NestedText[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + ) -> None: ... + @overload + def __init__( + self: NestedText[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + ) -> None: ... + + @overload + def __get__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _T | None: ... + @overload + def __get__(self: NestedText[_T, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _T: ... + + # NOTE: It is currently impossible to make a generic based on the parameter type of another generic + # So we implement explicitly the types used internally + # str + @overload + def __set__( # type: ignore[overload-overlap] + self: NestedText[str, _N], instance: Serialisable | Strict, value: object # Not[None] when _N = False + ) -> None: ... + # int + @overload + def __set__( + self: NestedText[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None + ) -> None: ... + @overload + def __set__(self: NestedText[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + # If expected type (_T) is not str, it's impossible to use an Element as the value + @overload + def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _HasTagAndGet[Any]) -> Never: ... + # Anything else + @overload + def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _T | int | Any | None) -> None: ... + + def from_tree(self, node: _HasText) -> str: ... # type: ignore[override] + + @overload + def to_tree(self, tagname: Unused = None, value: None = None, namespace: Unused = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: object, namespace: str | None = None) -> Element: ... + +class NestedFloat(NestedValue[float, _N], Float[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedFloat[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedFloat[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class NestedInteger(NestedValue[int, _N], Integer[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedInteger[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedInteger[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class NestedString(NestedValue[str, _N], String[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedString[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedString[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class NestedBool(NestedValue[bool, _N], Bool[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedBool[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedBool[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool) -> None: ... + def from_tree(self, node: _HasGet[bool]) -> bool: ... + +class NestedNoneSet(Nested[_T | None], NoneSet[_T]): + def __init__(self, name: str | None = None, *, values: Iterable[_T | None]) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _NestedNoneSetParam[_T]) -> None: ... + +class NestedSet(Nested[_T], Set[_T]): + def __init__(self, name: str | None = None, *, values: Iterable[_T]) -> None: ... + +class NestedMinMax(Nested[_M], MinMax[_M, _N]): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + @overload + def __init__( + self: NestedMinMax[int, Literal[True]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: NestedMinMax[int, Literal[False]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: NestedMinMax[float, Literal[True]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: NestedMinMax[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + + @overload + def __get__(self: NestedMinMax[_M, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _M | None: ... + @overload + def __get__(self: NestedMinMax[_M, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _M: ... + + @overload # type: ignore[override] # Different restrictions + def __set__( + self: NestedMinMax[int, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + ) -> None: ... + @overload + def __set__( + self: NestedMinMax[int, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + ) -> None: ... + @overload + def __set__( + self: NestedMinMax[float, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None, + ) -> None: ... + @overload + def __set__( + self: NestedMinMax[float, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat, + ) -> None: ... + +class EmptyTag(Nested[bool], Bool[_N]): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + @overload + def __init__(self: EmptyTag[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: EmptyTag[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + @overload + def __get__(self: EmptyTag[Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> bool | None: ... + @overload + def __get__(self: EmptyTag[Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> bool: ... + + def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool) -> None: ... + def from_tree(self, node: Unused) -> Literal[True]: ... + + @overload + def to_tree(self, tagname: Unused = None, value: None = None, namespace: Unused = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: object, namespace: str | None = None) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/sequence.pyi b/stubs/openpyxl/openpyxl/descriptors/sequence.pyi new file mode 100644 index 000000000000..01e44ca1a375 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/sequence.pyi @@ -0,0 +1,76 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator, Iterable, Sized +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.serialisable import Serialisable, _SerialisableTreeElement +from openpyxl.xml._functions_overloads import _HasGet +from openpyxl.xml.functions import Element + +from .base import Alias, Descriptor + +_T = TypeVar("_T") +_ContainerT = TypeVar("_ContainerT") + +@type_check_only +class _SupportsFromTree(Protocol): + @classmethod + def from_tree(cls, node: _SerialisableTreeElement) -> Any: ... + +@type_check_only +class _SupportsToTree(Protocol): + def to_tree(self) -> Element: ... + +# `_ContainerT` is the internal container type (which defaults to `list`), or +# `IndexedList` if unique is `True`. +class Sequence(Descriptor[_ContainerT]): + expected_type: type[Any] # expected type of the sequence elements + seq_types: tuple[type, ...] # allowed settable sequence types, defaults to `list`, `tuple` + idx_base: int + unique: bool + container: type # internal container type, defaults to `list` + # seq must be an instance of any of the declared `seq_types`. + def __set__(self, instance: Serialisable | Strict, seq: Any) -> None: ... + def to_tree(self, tagname: str | None, obj: Iterable[object], namespace: str | None = None) -> Generator[Element]: ... + +# `_T` is the type of the elements in the sequence. +class UniqueSequence(Sequence[set[_T]]): + seq_types: tuple[type, ...] # defaults to `list`, `tuple`, `set` + container: type[set[_T]] + +# See `Sequence` for the meaning of `_ContainerT`. +class ValueSequence(Sequence[_ContainerT]): + attribute: str + def to_tree( + self, tagname: str, obj: Iterable[object], namespace: str | None = None # type: ignore[override] + ) -> Generator[Element]: ... + def from_tree(self, node: _HasGet[_T]) -> _T: ... + +@type_check_only +class _NestedSequenceToTreeObj(Sized, Iterable[_SupportsToTree], Protocol): ... + +# See `Sequence` for the meaning of `_ContainerT`. +class NestedSequence(Sequence[_ContainerT]): + count: bool + expected_type: type[_SupportsFromTree] + def to_tree( # type: ignore[override] + self, tagname: str, obj: _NestedSequenceToTreeObj, namespace: str | None = None + ) -> Element: ... + # returned list generic type should be same as the return type of expected_type.from_tree(node) + # Which can really be anything given the wildly different, and sometimes generic, from_tree return types + def from_tree(self, node: Iterable[_SerialisableTreeElement]) -> list[Any]: ... + +# `_T` is the type of the elements in the sequence. +class MultiSequence(Sequence[list[_T]]): + def __set__(self, instance: Serialisable | Strict, seq: tuple[_T, ...] | list[_T]) -> None: ... + def to_tree( + self, tagname: Unused, obj: Iterable[_SupportsToTree], namespace: str | None = None # type: ignore[override] + ) -> Generator[Element]: ... + +class MultiSequencePart(Alias): + expected_type: type[Incomplete] + store: Incomplete + def __init__(self, expected_type, store) -> None: ... + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + def __get__(self, instance: Unused, cls: Unused) -> Self: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi b/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi new file mode 100644 index 000000000000..4ea4e6bae42b --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi @@ -0,0 +1,54 @@ +from _typeshed import ConvertibleToInt, Incomplete, SupportsIter +from collections.abc import Iterator +from typing import Any, ClassVar, Final, Protocol, type_check_only +from typing_extensions import Self + +from openpyxl.descriptors import MetaSerialisable +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasAttrib, _HasGet, _HasTagAndGet, _HasText, _SupportsFindChartLines + +# For any override directly re-using Serialisable.from_tree +@type_check_only +class _ChildSerialisableTreeElement(_HasAttrib, _HasText, SupportsIter[Incomplete], Protocol): ... + +@type_check_only +class _SerialisableTreeElement(_HasGet[object], _SupportsFindChartLines, _ChildSerialisableTreeElement, Protocol): ... + +KEYWORDS: Final[frozenset[str]] +seq_types: Final[tuple[type[list[Any]], type[tuple[Any, ...]]]] + +class Serialisable(metaclass=MetaSerialisable): + # These dunders are always set at runtime by MetaSerialisable so they can't be None + __attrs__: ClassVar[tuple[str, ...]] + __nested__: ClassVar[tuple[str, ...]] + __elements__: ClassVar[tuple[str, ...]] + __namespaced__: ClassVar[tuple[tuple[str, str], ...]] + idx_base: int + # Needs overrides in many sub-classes. But a lot of subclasses are instantiated without overriding it, so can't be abstract + # Subclasses "overrides" this property with a ClassVar, and Serialisable is too widely used, + # so it can't be typed as Never either without introducing many false-positives. + @property + def tagname(self) -> str: ... + namespace: ClassVar[str | None] + # Note: To respect the Liskov substitution principle, the protocol for node includes all child class requirements. + # Same with the return type to avoid override issues. + # See comment in xml/functions.pyi as to why use a protocol instead of Element + # Child classes should be more precise than _SerialisableTreeElement ! + # Use _ChildSerialisableTreeElement instead for child classes that reuse Serialisable.from_tree directly. + @classmethod + def from_tree(cls, node: _SerialisableTreeElement) -> Self | None: ... + # Note: To respect the Liskov substitution principle, idx is a type union of all child class requirements. + # Use Unused instead for child classes that reuse Serialisable.to_tree directly. + def to_tree( + self, + tagname: str | None = None, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt | None = None, + namespace: str | None = None, + ) -> Element: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __add__(self, other): ... + def __copy__(self): ... diff --git a/stubs/openpyxl/openpyxl/descriptors/slots.pyi b/stubs/openpyxl/openpyxl/descriptors/slots.pyi new file mode 100644 index 000000000000..f74e59307e6e --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/slots.pyi @@ -0,0 +1,4 @@ +from _typeshed import Incomplete, Self + +class AutoSlotProperties(type): + def __new__(mcl: type[Self], classname: str, bases: tuple[type, ...], dictionary: dict[str, Incomplete]) -> Self: ... diff --git a/stubs/openpyxl/openpyxl/drawing/__init__.pyi b/stubs/openpyxl/openpyxl/drawing/__init__.pyi new file mode 100644 index 000000000000..a41cad04e6d8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/__init__.pyi @@ -0,0 +1 @@ +from .drawing import Drawing as Drawing diff --git a/stubs/openpyxl/openpyxl/drawing/colors.pyi b/stubs/openpyxl/openpyxl/drawing/colors.pyi new file mode 100644 index 000000000000..872589fbb8dc --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/colors.pyi @@ -0,0 +1,510 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Final, Literal, TypeAlias, overload + +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.base import Alias, Integer, MinMax, Set, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import EmptyTag, NestedInteger, NestedNoneSet, NestedValue, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_ColorSetType: TypeAlias = Literal[ + "dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink" +] +_SystemColorVal: TypeAlias = Literal[ + "scrollBar", + "background", + "activeCaption", + "inactiveCaption", + "menu", + "window", + "windowFrame", + "menuText", + "windowText", + "captionText", + "activeBorder", + "inactiveBorder", + "appWorkspace", + "highlight", + "highlightText", + "btnFace", + "btnShadow", + "grayText", + "btnText", + "inactiveCaptionText", + "btnHighlight", + "3dDkShadow", + "3dLight", + "infoText", + "infoBk", + "hotLight", + "gradientActiveCaption", + "gradientInactiveCaption", + "menuHighlight", + "menuBar", +] +_SchemeColors: TypeAlias = Literal[ + "bg1", + "tx1", + "bg2", + "tx2", + "accent1", + "accent2", + "accent3", + "accent4", + "accent5", + "accent6", + "hlink", + "folHlink", + "phClr", + "dk1", + "lt1", + "dk2", + "lt2", +] +_PresetColors: TypeAlias = Literal[ + "aliceBlue", + "antiqueWhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedAlmond", + "blue", + "blueViolet", + "brown", + "burlyWood", + "cadetBlue", + "chartreuse", + "chocolate", + "coral", + "cornflowerBlue", + "cornsilk", + "crimson", + "cyan", + "darkBlue", + "darkCyan", + "darkGoldenrod", + "darkGray", + "darkGrey", + "darkGreen", + "darkKhaki", + "darkMagenta", + "darkOliveGreen", + "darkOrange", + "darkOrchid", + "darkRed", + "darkSalmon", + "darkSeaGreen", + "darkSlateBlue", + "darkSlateGray", + "darkSlateGrey", + "darkTurquoise", + "darkViolet", + "dkBlue", + "dkCyan", + "dkGoldenrod", + "dkGray", + "dkGrey", + "dkGreen", + "dkKhaki", + "dkMagenta", + "dkOliveGreen", + "dkOrange", + "dkOrchid", + "dkRed", + "dkSalmon", + "dkSeaGreen", + "dkSlateBlue", + "dkSlateGray", + "dkSlateGrey", + "dkTurquoise", + "dkViolet", + "deepPink", + "deepSkyBlue", + "dimGray", + "dimGrey", + "dodgerBlue", + "firebrick", + "floralWhite", + "forestGreen", + "fuchsia", + "gainsboro", + "ghostWhite", + "gold", + "goldenrod", + "gray", + "grey", + "green", + "greenYellow", + "honeydew", + "hotPink", + "indianRed", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderBlush", + "lawnGreen", + "lemonChiffon", + "lightBlue", + "lightCoral", + "lightCyan", + "lightGoldenrodYellow", + "lightGray", + "lightGrey", + "lightGreen", + "lightPink", + "lightSalmon", + "lightSeaGreen", + "lightSkyBlue", + "lightSlateGray", + "lightSlateGrey", + "lightSteelBlue", + "lightYellow", + "ltBlue", + "ltCoral", + "ltCyan", + "ltGoldenrodYellow", + "ltGray", + "ltGrey", + "ltGreen", + "ltPink", + "ltSalmon", + "ltSeaGreen", + "ltSkyBlue", + "ltSlateGray", + "ltSlateGrey", + "ltSteelBlue", + "ltYellow", + "lime", + "limeGreen", + "linen", + "magenta", + "maroon", + "medAquamarine", + "medBlue", + "medOrchid", + "medPurple", + "medSeaGreen", + "medSlateBlue", + "medSpringGreen", + "medTurquoise", + "medVioletRed", + "mediumAquamarine", + "mediumBlue", + "mediumOrchid", + "mediumPurple", + "mediumSeaGreen", + "mediumSlateBlue", + "mediumSpringGreen", + "mediumTurquoise", + "mediumVioletRed", + "midnightBlue", + "mintCream", + "mistyRose", + "moccasin", + "navajoWhite", + "navy", + "oldLace", + "olive", + "oliveDrab", + "orange", + "orangeRed", + "orchid", + "paleGoldenrod", + "paleGreen", + "paleTurquoise", + "paleVioletRed", + "papayaWhip", + "peachPuff", + "peru", + "pink", + "plum", + "powderBlue", + "purple", + "red", + "rosyBrown", + "royalBlue", + "saddleBrown", + "salmon", + "sandyBrown", + "seaGreen", + "seaShell", + "sienna", + "silver", + "skyBlue", + "slateBlue", + "slateGray", + "slateGrey", + "snow", + "springGreen", + "steelBlue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whiteSmoke", + "yellow", + "yellowGreen", +] + +PRESET_COLORS: Final[list[_PresetColors]] +SCHEME_COLORS: Final[list[_SchemeColors]] + +class Transform(Serialisable): ... + +class SystemColor(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + tint: NestedInteger[Literal[True]] + shade: NestedInteger[Literal[True]] + comp: Typed[Transform, Literal[True]] + inv: Typed[Transform, Literal[True]] + gray: Typed[Transform, Literal[True]] + alpha: NestedInteger[Literal[True]] + alphaOff: NestedInteger[Literal[True]] + alphaMod: NestedInteger[Literal[True]] + hue: NestedInteger[Literal[True]] + hueOff: NestedInteger[Literal[True]] + hueMod: NestedInteger[Literal[True]] + sat: NestedInteger[Literal[True]] + satOff: NestedInteger[Literal[True]] + satMod: NestedInteger[Literal[True]] + lum: NestedInteger[Literal[True]] + lumOff: NestedInteger[Literal[True]] + lumMod: NestedInteger[Literal[True]] + red: NestedInteger[Literal[True]] + redOff: NestedInteger[Literal[True]] + redMod: NestedInteger[Literal[True]] + green: NestedInteger[Literal[True]] + greenOff: NestedInteger[Literal[True]] + greenMod: NestedInteger[Literal[True]] + blue: NestedInteger[Literal[True]] + blueOff: NestedInteger[Literal[True]] + blueMod: NestedInteger[Literal[True]] + gamma: Typed[Transform, Literal[True]] + invGamma: Typed[Transform, Literal[True]] + val: Set[_SystemColorVal] + lastClr: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + val: _SystemColorVal = "windowText", + lastClr=None, + tint: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + shade: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + comp: Transform | None = None, + inv: Transform | None = None, + gray: Transform | None = None, + alpha: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + sat: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lum: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + red: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + green: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + gamma: Transform | None = None, + invGamma: Transform | None = None, + ) -> None: ... + +class HSLColor(Serialisable): + tagname: ClassVar[str] + hue: Integer[Literal[False]] + sat: MinMax[float, Literal[False]] + lum: MinMax[float, Literal[False]] + def __init__(self, hue: ConvertibleToInt, sat: ConvertibleToFloat, lum: ConvertibleToFloat) -> None: ... + +class RGBPercent(Serialisable): + tagname: ClassVar[str] + r: MinMax[float, Literal[False]] + g: MinMax[float, Literal[False]] + b: MinMax[float, Literal[False]] + def __init__(self, r: ConvertibleToFloat, g: ConvertibleToFloat, b: ConvertibleToFloat) -> None: ... + +_RGBPercent: TypeAlias = RGBPercent + +class SchemeColor(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + tint: NestedInteger[Literal[True]] + shade: NestedInteger[Literal[True]] + comp: EmptyTag[Literal[True]] + inv: NestedInteger[Literal[True]] + gray: NestedInteger[Literal[True]] + alpha: NestedInteger[Literal[True]] + alphaOff: NestedInteger[Literal[True]] + alphaMod: NestedInteger[Literal[True]] + hue: NestedInteger[Literal[True]] + hueOff: NestedInteger[Literal[True]] + hueMod: NestedInteger[Literal[True]] + sat: NestedInteger[Literal[True]] + satOff: NestedInteger[Literal[True]] + satMod: NestedInteger[Literal[True]] + lum: NestedInteger[Literal[True]] + lumOff: NestedInteger[Literal[True]] + lumMod: NestedInteger[Literal[True]] + red: NestedInteger[Literal[True]] + redOff: NestedInteger[Literal[True]] + redMod: NestedInteger[Literal[True]] + green: NestedInteger[Literal[True]] + greenOff: NestedInteger[Literal[True]] + greenMod: NestedInteger[Literal[True]] + blue: NestedInteger[Literal[True]] + blueOff: NestedInteger[Literal[True]] + blueMod: NestedInteger[Literal[True]] + gamma: EmptyTag[Literal[True]] + invGamma: EmptyTag[Literal[True]] + val: Set[_SchemeColors] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + tint: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + shade: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + comp: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + inv: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + gray: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alpha: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + sat: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lum: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + red: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + green: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + gamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + invGamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + *, + val: _SchemeColors, + ) -> None: ... + @overload + def __init__( + self, + tint: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + shade: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + comp: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + inv: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + gray: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + alpha: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + alphaOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + alphaMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + hue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + hueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + hueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + sat: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + satOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + satMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + lum: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + lumOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + lumMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + red: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + redOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + redMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + green: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + greenOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + greenMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + blue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + blueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + blueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + gamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + invGamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + val: _SchemeColors, + ) -> None: ... + +class ColorChoice(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + scrgbClr: Typed[_RGBPercent, Literal[True]] + RGBPercent: Alias + srgbClr: NestedValue[_RGBPercent, Literal[True]] + RGB: Alias + hslClr: Typed[HSLColor, Literal[True]] + sysClr: Typed[SystemColor, Literal[True]] + schemeClr: Typed[SystemColor, Literal[True]] + prstClr: NestedNoneSet[_PresetColors] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scrgbClr: _RGBPercent | None = None, + srgbClr: _HasTagAndGet[_RGBPercent | None] | _RGBPercent | None = None, + hslClr: HSLColor | None = None, + sysClr: SystemColor | None = None, + schemeClr: SystemColor | None = None, + prstClr: _NestedNoneSetParam[_PresetColors] = None, + ) -> None: ... + +_COLOR_SET: Final[tuple[_ColorSetType, ...]] + +class ColorMapping(Serialisable): + tagname: ClassVar[str] + bg1: Set[_ColorSetType] + tx1: Set[_ColorSetType] + bg2: Set[_ColorSetType] + tx2: Set[_ColorSetType] + accent1: Set[_ColorSetType] + accent2: Set[_ColorSetType] + accent3: Set[_ColorSetType] + accent4: Set[_ColorSetType] + accent5: Set[_ColorSetType] + accent6: Set[_ColorSetType] + hlink: Set[_ColorSetType] + folHlink: Set[_ColorSetType] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + bg1: str = "lt1", + tx1: str = "dk1", + bg2: str = "lt2", + tx2: str = "dk2", + accent1: str = "accent1", + accent2: str = "accent2", + accent3: str = "accent3", + accent4: str = "accent4", + accent5: str = "accent5", + accent6: str = "accent6", + hlink: str = "hlink", + folHlink: str = "folHlink", + extLst: ExtensionList | None = None, + ) -> None: ... + +class ColorChoiceDescriptor(Typed[ColorChoice, Literal[True]]): + expected_type: type[ColorChoice] + allow_none: Literal[True] + def __init__(self, name: str | None = None) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: str | ColorChoice | None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/connector.pyi b/stubs/openpyxl/openpyxl/drawing/connector.pyi new file mode 100644 index 000000000000..2308021cdfc6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/connector.pyi @@ -0,0 +1,99 @@ +from _typeshed import ConvertibleToInt +from typing import ClassVar, Literal, overload + +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors import Typed +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.geometry import ShapeStyle +from openpyxl.drawing.properties import NonVisualDrawingProps, NonVisualDrawingShapeProps + +class Connection(Serialisable): + id: Integer[Literal[False]] + idx: Integer[Literal[False]] + def __init__(self, id: ConvertibleToInt, idx: ConvertibleToInt) -> None: ... + +class ConnectorLocking(Serialisable): + extLst: Typed[ExtensionList, Literal[True]] + def __init__(self, extLst: ExtensionList | None = None) -> None: ... + +class NonVisualConnectorProperties(Serialisable): + cxnSpLocks: Typed[ConnectorLocking, Literal[True]] + stCxn: Typed[Connection, Literal[True]] + endCxn: Typed[Connection, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + cxnSpLocks: ConnectorLocking | None = None, + stCxn: Connection | None = None, + endCxn: Connection | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class ConnectorNonVisual(Serialisable): + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvCxnSpPr: Typed[NonVisualConnectorProperties, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cNvPr: NonVisualDrawingProps, cNvCxnSpPr: NonVisualConnectorProperties) -> None: ... + +class ConnectorShape(Serialisable): + tagname: ClassVar[str] + nvCxnSpPr: Typed[ConnectorNonVisual, Literal[False]] + spPr: Typed[GraphicalProperties, Literal[False]] + style: Typed[ShapeStyle, Literal[True]] + macro: String[Literal[True]] + fPublished: Bool[Literal[True]] + def __init__( + self, + nvCxnSpPr: ConnectorNonVisual, + spPr: GraphicalProperties, + style: ShapeStyle | None = None, + macro: str | None = None, + fPublished: _ConvertibleToBool | None = None, + ) -> None: ... + +class ShapeMeta(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvSpPr: Typed[NonVisualDrawingShapeProps, Literal[False]] + def __init__(self, cNvPr: NonVisualDrawingProps, cNvSpPr: NonVisualDrawingShapeProps) -> None: ... + +class Shape(Serialisable): + macro: String[Literal[True]] + textlink: String[Literal[True]] + fPublished: Bool[Literal[True]] + fLocksText: Bool[Literal[True]] + nvSpPr: Typed[ShapeMeta, Literal[True]] + meta: Alias + spPr: Typed[GraphicalProperties, Literal[False]] + graphicalProperties: Alias + style: Typed[ShapeStyle, Literal[True]] + txBody: Typed[RichText, Literal[True]] + + @overload + def __init__( + self, + macro: str | None = None, + textlink: str | None = None, + fPublished: _ConvertibleToBool | None = None, + fLocksText: _ConvertibleToBool | None = None, + nvSpPr: ShapeMeta | None = None, + *, + spPr: GraphicalProperties, + style: ShapeStyle | None = None, + txBody: RichText | None = None, + ) -> None: ... + @overload + def __init__( + self, + macro: str | None, + textlink: str | None, + fPublished: _ConvertibleToBool | None, + fLocksText: _ConvertibleToBool | None, + nvSpPr: ShapeMeta | None, + spPr: GraphicalProperties, + style: ShapeStyle | None = None, + txBody: RichText | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/drawing.pyi b/stubs/openpyxl/openpyxl/drawing/drawing.pyi new file mode 100644 index 000000000000..069370e5e02c --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/drawing.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from .spreadsheet_drawing import AbsoluteAnchor, OneCellAnchor + +class Drawing: + count: int + name: str + description: str + coordinates: Incomplete + left: int + top: int + resize_proportional: bool + rotation: int + anchortype: str + anchorcol: int + anchorrow: int + def __init__(self) -> None: ... + + @property + def width(self) -> int: ... + @width.setter + def width(self, w: int) -> None: ... + + @property + def height(self) -> int: ... + @height.setter + def height(self, h: int) -> None: ... + + def set_dimension(self, w: int = 0, h: int = 0) -> None: ... + @property + def anchor(self) -> AbsoluteAnchor | OneCellAnchor: ... diff --git a/stubs/openpyxl/openpyxl/drawing/effect.pyi b/stubs/openpyxl/openpyxl/drawing/effect.pyi new file mode 100644 index 000000000000..d0678bfbc406 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/effect.pyi @@ -0,0 +1,255 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Float, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +from .colors import ColorChoice + +_FillOverlayEffectBlend: TypeAlias = Literal["over", "mult", "screen", "darken", "lighten"] +_EffectContainerType: TypeAlias = Literal["sib", "tree"] +_Algn: TypeAlias = Literal["tl", "t", "tr", "l", "ctr", "r", "bl", "b", "br"] +_PresetShadowEffectPrst: TypeAlias = Literal[ + "shdw1", + "shdw2", + "shdw3", + "shdw4", + "shdw5", + "shdw6", + "shdw7", + "shdw8", + "shdw9", + "shdw10", + "shdw11", + "shdw12", + "shdw13", + "shdw14", + "shdw15", + "shdw16", + "shdw17", + "shdw18", + "shdw19", + "shdw20", +] + +class TintEffect(Serialisable): + tagname: ClassVar[str] + hue: Integer[Literal[False]] + amt: Integer[Literal[False]] + def __init__(self, hue: ConvertibleToInt = 0, amt: ConvertibleToInt = 0) -> None: ... + +class LuminanceEffect(Serialisable): + tagname: ClassVar[str] + bright: Integer[Literal[False]] + contrast: Integer[Literal[False]] + def __init__(self, bright: ConvertibleToInt = 0, contrast: ConvertibleToInt = 0) -> None: ... + +class HSLEffect(Serialisable): + hue: Integer[Literal[False]] + sat: Integer[Literal[False]] + lum: Integer[Literal[False]] + def __init__(self, hue: ConvertibleToInt, sat: ConvertibleToInt, lum: ConvertibleToInt) -> None: ... + +class GrayscaleEffect(Serialisable): + tagname: ClassVar[str] + +class FillOverlayEffect(Serialisable): + blend: Set[_FillOverlayEffectBlend] + def __init__(self, blend: _FillOverlayEffectBlend) -> None: ... + +class DuotoneEffect(Serialisable): ... +class ColorReplaceEffect(Serialisable): ... +class Color(Serialisable): ... + +class ColorChangeEffect(Serialisable): + useA: Bool[Literal[True]] + clrFrom: Typed[Color, Literal[False]] + clrTo: Typed[Color, Literal[False]] + + @overload + def __init__(self, useA: _ConvertibleToBool | None = None, *, clrFrom: Color, clrTo: Color) -> None: ... + @overload + def __init__(self, useA: _ConvertibleToBool | None, clrFrom: Color, clrTo: Color) -> None: ... + +class BlurEffect(Serialisable): + rad: Float[Literal[False]] + grow: Bool[Literal[True]] + def __init__(self, rad: ConvertibleToFloat, grow: _ConvertibleToBool | None = None) -> None: ... + +class BiLevelEffect(Serialisable): + thresh: Integer[Literal[False]] + def __init__(self, thresh: ConvertibleToInt) -> None: ... + +class AlphaReplaceEffect(Serialisable): + a: Integer[Literal[False]] + def __init__(self, a: ConvertibleToInt) -> None: ... + +class AlphaModulateFixedEffect(Serialisable): + amt: Integer[Literal[False]] + def __init__(self, amt: ConvertibleToInt) -> None: ... + +class EffectContainer(Serialisable): + type: Set[_EffectContainerType] + name: String[Literal[True]] + def __init__(self, type: _EffectContainerType, name: str | None = None) -> None: ... + +class AlphaModulateEffect(Serialisable): + cont: Typed[EffectContainer, Literal[False]] + def __init__(self, cont: EffectContainer) -> None: ... + +class AlphaInverseEffect(Serialisable): ... +class AlphaFloorEffect(Serialisable): ... +class AlphaCeilingEffect(Serialisable): ... + +class AlphaBiLevelEffect(Serialisable): + thresh: Integer[Literal[False]] + def __init__(self, thresh: ConvertibleToInt) -> None: ... + +class GlowEffect(ColorChoice): + rad: Float[Literal[False]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rad: ConvertibleToFloat, **kw) -> None: ... + +class InnerShadowEffect(ColorChoice): + blurRad: Float[Literal[False]] + dist: Float[Literal[False]] + dir: Integer[Literal[False]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, blurRad: ConvertibleToFloat, dist: ConvertibleToFloat, dir: ConvertibleToInt, **kw) -> None: ... + +class OuterShadow(ColorChoice): + tagname: ClassVar[str] + blurRad: Float[Literal[True]] + dist: Float[Literal[True]] + dir: Integer[Literal[True]] + sx: Integer[Literal[True]] + sy: Integer[Literal[True]] + kx: Integer[Literal[True]] + ky: Integer[Literal[True]] + algn: Set[_Algn] + rotWithShape: Bool[Literal[True]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + blurRad: ConvertibleToFloat | None = None, + dist: ConvertibleToFloat | None = None, + dir: ConvertibleToInt | None = None, + sx: ConvertibleToInt | None = None, + sy: ConvertibleToInt | None = None, + kx: ConvertibleToInt | None = None, + ky: ConvertibleToInt | None = None, + *, + algn: _Algn, + rotWithShape: _ConvertibleToBool | None = None, + **kw, + ) -> None: ... + @overload + def __init__( + self, + blurRad: ConvertibleToFloat | None, + dist: ConvertibleToFloat | None, + dir: ConvertibleToInt | None, + sx: ConvertibleToInt | None, + sy: ConvertibleToInt | None, + kx: ConvertibleToInt | None, + ky: ConvertibleToInt | None, + algn: _Algn, + rotWithShape: _ConvertibleToBool | None = None, + **kw, + ) -> None: ... + +class PresetShadowEffect(ColorChoice): + prst: Set[_PresetShadowEffectPrst] + dist: Float[Literal[False]] + dir: Integer[Literal[False]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, prst: _PresetShadowEffectPrst, dist: ConvertibleToFloat, dir: ConvertibleToInt, **kw) -> None: ... + +class ReflectionEffect(Serialisable): + blurRad: Float[Literal[False]] + stA: Integer[Literal[False]] + stPos: Integer[Literal[False]] + endA: Integer[Literal[False]] + endPos: Integer[Literal[False]] + dist: Float[Literal[False]] + dir: Integer[Literal[False]] + fadeDir: Integer[Literal[False]] + sx: Integer[Literal[False]] + sy: Integer[Literal[False]] + kx: Integer[Literal[False]] + ky: Integer[Literal[False]] + algn: Set[_Algn] + rotWithShape: Bool[Literal[True]] + def __init__( + self, + blurRad: ConvertibleToFloat, + stA: ConvertibleToInt, + stPos: ConvertibleToInt, + endA: ConvertibleToInt, + endPos: ConvertibleToInt, + dist: ConvertibleToFloat, + dir: ConvertibleToInt, + fadeDir: ConvertibleToInt, + sx: ConvertibleToInt, + sy: ConvertibleToInt, + kx: ConvertibleToInt, + ky: ConvertibleToInt, + algn: _Algn, + rotWithShape: _ConvertibleToBool | None = None, + ) -> None: ... + +class SoftEdgesEffect(Serialisable): + rad: Float[Literal[False]] + def __init__(self, rad: ConvertibleToFloat) -> None: ... + +class EffectList(Serialisable): + blur: Typed[BlurEffect, Literal[True]] + fillOverlay: Typed[FillOverlayEffect, Literal[True]] + glow: Typed[GlowEffect, Literal[True]] + innerShdw: Typed[InnerShadowEffect, Literal[True]] + outerShdw: Typed[OuterShadow, Literal[True]] + prstShdw: Typed[PresetShadowEffect, Literal[True]] + reflection: Typed[ReflectionEffect, Literal[True]] + softEdge: Typed[SoftEdgesEffect, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + blur: BlurEffect | None = None, + fillOverlay: FillOverlayEffect | None = None, + glow: GlowEffect | None = None, + innerShdw: InnerShadowEffect | None = None, + outerShdw: OuterShadow | None = None, + prstShdw: PresetShadowEffect | None = None, + reflection: ReflectionEffect | None = None, + softEdge: SoftEdgesEffect | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/fill.pyi b/stubs/openpyxl/openpyxl/drawing/fill.pyi new file mode 100644 index 000000000000..6ee8f5964c6d --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/fill.pyi @@ -0,0 +1,314 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, Integer, MinMax, NoneSet, Set, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedNoneSet, NestedValue, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, HSLColor, RGBPercent as _RGBPercent, SchemeColor, SystemColor, _PresetColors +from openpyxl.drawing.effect import ( + AlphaBiLevelEffect, + AlphaCeilingEffect, + AlphaFloorEffect, + AlphaInverseEffect, + AlphaModulateEffect, + AlphaModulateFixedEffect, + AlphaReplaceEffect, + BiLevelEffect, + BlurEffect, + ColorChangeEffect, + ColorReplaceEffect, + DuotoneEffect, + FillOverlayEffect, + GrayscaleEffect, + HSLEffect, + LuminanceEffect, + TintEffect, +) + +from ..xml._functions_overloads import _HasTagAndGet + +_PatternFillPropertiesPrst: TypeAlias = Literal[ + "pct5", + "pct10", + "pct20", + "pct25", + "pct30", + "pct40", + "pct50", + "pct60", + "pct70", + "pct75", + "pct80", + "pct90", + "horz", + "vert", + "ltHorz", + "ltVert", + "dkHorz", + "dkVert", + "narHorz", + "narVert", + "dashHorz", + "dashVert", + "cross", + "dnDiag", + "upDiag", + "ltDnDiag", + "ltUpDiag", + "dkDnDiag", + "dkUpDiag", + "wdDnDiag", + "wdUpDiag", + "dashDnDiag", + "dashUpDiag", + "diagCross", + "smCheck", + "lgCheck", + "smGrid", + "lgGrid", + "dotGrid", + "smConfetti", + "lgConfetti", + "horzBrick", + "diagBrick", + "solidDmnd", + "openDmnd", + "dotDmnd", + "plaid", + "sphere", + "weave", + "divot", + "shingle", + "wave", + "trellis", + "zigZag", +] +_PropertiesFlip: TypeAlias = Literal["x", "y", "xy"] +_TileInfoPropertiesAlgn: TypeAlias = Literal["tl", "t", "tr", "l", "ctr", "r", "bl", "b", "br"] +_BlipCstate: TypeAlias = Literal["email", "screen", "print", "hqprint"] +_PathShadePropertiesPath: TypeAlias = Literal["shape", "circle", "rect"] + +class PatternFillProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + prst: NoneSet[_PatternFillPropertiesPrst] + preset: Alias + fgClr: Typed[ColorChoice, Literal[True]] + foreground: Alias + bgClr: Typed[ColorChoice, Literal[True]] + background: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + prst: _PatternFillPropertiesPrst | Literal["none"] | None = None, + fgClr: ColorChoice | None = None, + bgClr: ColorChoice | None = None, + ) -> None: ... + +class RelativeRect(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + l: Incomplete + left: Alias + t: Incomplete + top: Alias + r: Incomplete + right: Alias + b: Incomplete + bottom: Alias + def __init__(self, l=None, t=None, r=None, b=None) -> None: ... + +class StretchInfoProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + fillRect: Typed[RelativeRect, Literal[True]] + def __init__(self, fillRect: RelativeRect = ...) -> None: ... + +class GradientStop(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + pos: MinMax[float, Literal[True]] + scrgbClr: Typed[_RGBPercent, Literal[True]] + RGBPercent: Alias + srgbClr: NestedValue[_RGBPercent, Literal[True]] + RGB: Alias + hslClr: Typed[HSLColor, Literal[True]] + sysClr: Typed[SystemColor, Literal[True]] + schemeClr: Typed[SchemeColor, Literal[True]] + prstClr: NestedNoneSet[_PresetColors] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + pos: ConvertibleToFloat | None = None, + scrgbClr: _RGBPercent | None = None, + srgbClr: _HasTagAndGet[_RGBPercent | None] | _RGBPercent | None = None, + hslClr: HSLColor | None = None, + sysClr: SystemColor | None = None, + schemeClr: SchemeColor | None = None, + prstClr: _NestedNoneSetParam[_PresetColors] = None, + ) -> None: ... + +class LinearShadeProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + ang: Integer[Literal[False]] + scaled: Bool[Literal[True]] + def __init__(self, ang: ConvertibleToInt, scaled: _ConvertibleToBool | None = None) -> None: ... + +class PathShadeProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + path: Set[_PathShadePropertiesPath] + fillToRect: Typed[RelativeRect, Literal[True]] + def __init__(self, path: _PathShadePropertiesPath, fillToRect: RelativeRect | None = None) -> None: ... + +class GradientFillProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + flip: NoneSet[_PropertiesFlip] + rotWithShape: Bool[Literal[True]] + gsLst: Incomplete + stop_list: Alias + lin: Typed[LinearShadeProperties, Literal[True]] + linear: Alias + path: Typed[PathShadeProperties, Literal[True]] + tileRect: Typed[RelativeRect, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + flip: _PropertiesFlip | Literal["none"] | None = None, + rotWithShape: _ConvertibleToBool | None = None, + gsLst=(), + lin: LinearShadeProperties | None = None, + path: PathShadeProperties | None = None, + tileRect: RelativeRect | None = None, + ) -> None: ... + +class SolidColorFillProperties(Serialisable): + tagname: ClassVar[str] + scrgbClr: Typed[_RGBPercent, Literal[True]] + RGBPercent: Alias + srgbClr: NestedValue[_RGBPercent, Literal[True]] + RGB: Alias + hslClr: Typed[HSLColor, Literal[True]] + sysClr: Typed[SystemColor, Literal[True]] + schemeClr: Typed[SchemeColor, Literal[True]] + prstClr: NestedNoneSet[_PresetColors] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scrgbClr: _RGBPercent | None = None, + srgbClr: _HasTagAndGet[_RGBPercent | None] | _RGBPercent | None = None, + hslClr: HSLColor | None = None, + sysClr: SystemColor | None = None, + schemeClr: SchemeColor | None = None, + prstClr: _NestedNoneSetParam[_PresetColors] = None, + ) -> None: ... + +class Blip(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + cstate: NoneSet[_BlipCstate] + embed: Incomplete + link: Incomplete + noGrp: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noRot: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + noEditPoints: Bool[Literal[True]] + noAdjustHandles: Bool[Literal[True]] + noChangeArrowheads: Bool[Literal[True]] + noChangeShapeType: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + alphaBiLevel: Typed[AlphaBiLevelEffect, Literal[True]] + alphaCeiling: Typed[AlphaCeilingEffect, Literal[True]] + alphaFloor: Typed[AlphaFloorEffect, Literal[True]] + alphaInv: Typed[AlphaInverseEffect, Literal[True]] + alphaMod: Typed[AlphaModulateEffect, Literal[True]] + alphaModFix: Typed[AlphaModulateFixedEffect, Literal[True]] + alphaRepl: Typed[AlphaReplaceEffect, Literal[True]] + biLevel: Typed[BiLevelEffect, Literal[True]] + blur: Typed[BlurEffect, Literal[True]] + clrChange: Typed[ColorChangeEffect, Literal[True]] + clrRepl: Typed[ColorReplaceEffect, Literal[True]] + duotone: Typed[DuotoneEffect, Literal[True]] + fillOverlay: Typed[FillOverlayEffect, Literal[True]] + grayscl: Typed[GrayscaleEffect, Literal[True]] + hsl: Typed[HSLEffect, Literal[True]] + lum: Typed[LuminanceEffect, Literal[True]] + tint: Typed[TintEffect, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + cstate: _BlipCstate | Literal["none"] | None = None, + embed=None, + link=None, + noGrp: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noRot: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + noEditPoints: _ConvertibleToBool | None = None, + noAdjustHandles: _ConvertibleToBool | None = None, + noChangeArrowheads: _ConvertibleToBool | None = None, + noChangeShapeType: _ConvertibleToBool | None = None, + extLst: ExtensionList | None = None, + alphaBiLevel: AlphaBiLevelEffect | None = None, + alphaCeiling: AlphaCeilingEffect | None = None, + alphaFloor: AlphaFloorEffect | None = None, + alphaInv: AlphaInverseEffect | None = None, + alphaMod: AlphaModulateEffect | None = None, + alphaModFix: AlphaModulateFixedEffect | None = None, + alphaRepl: AlphaReplaceEffect | None = None, + biLevel: BiLevelEffect | None = None, + blur: BlurEffect | None = None, + clrChange: ColorChangeEffect | None = None, + clrRepl: ColorReplaceEffect | None = None, + duotone: DuotoneEffect | None = None, + fillOverlay: FillOverlayEffect | None = None, + grayscl: GrayscaleEffect | None = None, + hsl: HSLEffect | None = None, + lum: LuminanceEffect | None = None, + tint: TintEffect | None = None, + ) -> None: ... + +class TileInfoProperties(Serialisable): + tx: Integer[Literal[True]] + ty: Integer[Literal[True]] + sx: Integer[Literal[True]] + sy: Integer[Literal[True]] + flip: NoneSet[_PropertiesFlip] + algn: Set[_TileInfoPropertiesAlgn] + def __init__( + self, + tx: ConvertibleToInt | None = None, + ty: ConvertibleToInt | None = None, + sx: ConvertibleToInt | None = None, + sy: ConvertibleToInt | None = None, + flip: _PropertiesFlip | Literal["none"] | None = None, + *, + algn: _TileInfoPropertiesAlgn, + ) -> None: ... + +class BlipFillProperties(Serialisable): + tagname: ClassVar[str] + dpi: Integer[Literal[True]] + rotWithShape: Bool[Literal[True]] + blip: Typed[Blip, Literal[True]] + srcRect: Typed[RelativeRect, Literal[True]] + tile: Typed[TileInfoProperties, Literal[True]] + stretch: Typed[StretchInfoProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + dpi: ConvertibleToInt | None = None, + rotWithShape: _ConvertibleToBool | None = None, + blip: Blip | None = None, + tile: TileInfoProperties | None = None, + stretch: StretchInfoProperties = ..., + srcRect: RelativeRect | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/geometry.pyi b/stubs/openpyxl/openpyxl/drawing/geometry.pyi new file mode 100644 index 000000000000..a15293e0c663 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/geometry.pyi @@ -0,0 +1,577 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Alias, Bool, Float, Integer, MinMax, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import Coordinate, ExtensionList, Percentage +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color + +_BevelPrst: TypeAlias = Literal[ + "relaxedInset", + "circle", + "slope", + "cross", + "angle", + "softRound", + "convex", + "coolSlant", + "divot", + "riblet", + "hardEdge", + "artDeco", +] +_Shape3DPrstMaterial: TypeAlias = Literal[ + "legacyMatte", + "legacyPlastic", + "legacyMetal", + "legacyWireframe", + "matte", + "plastic", + "metal", + "warmMatte", + "translucentPowder", + "powder", + "dkEdge", + "softEdge", + "clear", + "flat", + "softmetal", +] +_Path2DFill: TypeAlias = Literal["norm", "lighten", "lightenLess", "darken", "darkenLess"] +_FontReferenceIdx: TypeAlias = Literal["major", "minor"] +_CameraPrst: TypeAlias = Literal[ + "legacyObliqueTopLeft", + "legacyObliqueTop", + "legacyObliqueTopRight", + "legacyObliqueLeft", + "legacyObliqueFront", + "legacyObliqueRight", + "legacyObliqueBottomLeft", + "legacyObliqueBottom", + "legacyObliqueBottomRight", + "legacyPerspectiveTopLeft", + "legacyPerspectiveTop", + "legacyPerspectiveTopRight", + "legacyPerspectiveLeft", + "legacyPerspectiveFront", + "legacyPerspectiveRight", + "legacyPerspectiveBottomLeft", + "legacyPerspectiveBottom", + "legacyPerspectiveBottomRight", + "orthographicFront", + "isometricTopUp", + "isometricTopDown", + "isometricBottomUp", + "isometricBottomDown", + "isometricLeftUp", + "isometricLeftDown", + "isometricRightUp", + "isometricRightDown", + "isometricOffAxis1Left", + "isometricOffAxis1Right", + "isometricOffAxis1Top", + "isometricOffAxis2Left", + "isometricOffAxis2Right", + "isometricOffAxis2Top", + "isometricOffAxis3Left", + "isometricOffAxis3Right", + "isometricOffAxis3Bottom", + "isometricOffAxis4Left", + "isometricOffAxis4Right", + "isometricOffAxis4Bottom", + "obliqueTopLeft", + "obliqueTop", + "obliqueTopRight", + "obliqueLeft", + "obliqueRight", + "obliqueBottomLeft", + "obliqueBottom", + "obliqueBottomRight", + "perspectiveFront", + "perspectiveLeft", + "perspectiveRight", + "perspectiveAbove", + "perspectiveBelow", + "perspectiveAboveLeftFacing", + "perspectiveAboveRightFacing", + "perspectiveContrastingLeftFacing", + "perspectiveContrastingRightFacing", + "perspectiveHeroicLeftFacing", + "perspectiveHeroicRightFacing", + "perspectiveHeroicExtremeLeftFacing", + "perspectiveHeroicExtremeRightFacing", + "perspectiveRelaxed", + "perspectiveRelaxedModerately", +] +_LightRigRig: TypeAlias = Literal[ + "legacyFlat1", + "legacyFlat2", + "legacyFlat3", + "legacyFlat4", + "legacyNormal1", + "legacyNormal2", + "legacyNormal3", + "legacyNormal4", + "legacyHarsh1", + "legacyHarsh2", + "legacyHarsh3", + "legacyHarsh4", + "threePt", + "balanced", + "soft", + "harsh", + "flood", + "contrasting", + "morning", + "sunrise", + "sunset", + "chilly", + "freezing", + "flat", + "twoPt", + "glow", + "brightRoom", +] +_LightRigDir: TypeAlias = Literal["tl", "t", "tr", "l", "r", "bl", "b", "br"] +_PresetGeometry2DPrst: TypeAlias = Literal[ + "line", + "lineInv", + "triangle", + "rtTriangle", + "rect", + "diamond", + "parallelogram", + "trapezoid", + "nonIsoscelesTrapezoid", + "pentagon", + "hexagon", + "heptagon", + "octagon", + "decagon", + "dodecagon", + "star4", + "star5", + "star6", + "star7", + "star8", + "star10", + "star12", + "star16", + "star24", + "star32", + "roundRect", + "round1Rect", + "round2SameRect", + "round2DiagRect", + "snipRoundRect", + "snip1Rect", + "snip2SameRect", + "snip2DiagRect", + "plaque", + "ellipse", + "teardrop", + "homePlate", + "chevron", + "pieWedge", + "pie", + "blockArc", + "donut", + "noSmoking", + "rightArrow", + "leftArrow", + "upArrow", + "downArrow", + "stripedRightArrow", + "notchedRightArrow", + "bentUpArrow", + "leftRightArrow", + "upDownArrow", + "leftUpArrow", + "leftRightUpArrow", + "quadArrow", + "leftArrowCallout", + "rightArrowCallout", + "upArrowCallout", + "downArrowCallout", + "leftRightArrowCallout", + "upDownArrowCallout", + "quadArrowCallout", + "bentArrow", + "uturnArrow", + "circularArrow", + "leftCircularArrow", + "leftRightCircularArrow", + "curvedRightArrow", + "curvedLeftArrow", + "curvedUpArrow", + "curvedDownArrow", + "swooshArrow", + "cube", + "can", + "lightningBolt", + "heart", + "sun", + "moon", + "smileyFace", + "irregularSeal1", + "irregularSeal2", + "foldedCorner", + "bevel", + "frame", + "halfFrame", + "corner", + "diagStripe", + "chord", + "arc", + "leftBracket", + "rightBracket", + "leftBrace", + "rightBrace", + "bracketPair", + "bracePair", + "straightConnector1", + "bentConnector2", + "bentConnector3", + "bentConnector4", + "bentConnector5", + "curvedConnector2", + "curvedConnector3", + "curvedConnector4", + "curvedConnector5", + "callout1", + "callout2", + "callout3", + "accentCallout1", + "accentCallout2", + "accentCallout3", + "borderCallout1", + "borderCallout2", + "borderCallout3", + "accentBorderCallout1", + "accentBorderCallout2", + "accentBorderCallout3", + "wedgeRectCallout", + "wedgeRoundRectCallout", + "wedgeEllipseCallout", + "cloudCallout", + "cloud", + "ribbon", + "ribbon2", + "ellipseRibbon", + "ellipseRibbon2", + "leftRightRibbon", + "verticalScroll", + "horizontalScroll", + "wave", + "doubleWave", + "plus", + "flowChartProcess", + "flowChartDecision", + "flowChartInputOutput", + "flowChartPredefinedProcess", + "flowChartInternalStorage", + "flowChartDocument", + "flowChartMultidocument", + "flowChartTerminator", + "flowChartPreparation", + "flowChartManualInput", + "flowChartManualOperation", + "flowChartConnector", + "flowChartPunchedCard", + "flowChartPunchedTape", + "flowChartSummingJunction", + "flowChartOr", + "flowChartCollate", + "flowChartSort", + "flowChartExtract", + "flowChartMerge", + "flowChartOfflineStorage", + "flowChartOnlineStorage", + "flowChartMagneticTape", + "flowChartMagneticDisk", + "flowChartMagneticDrum", + "flowChartDisplay", + "flowChartDelay", + "flowChartAlternateProcess", + "flowChartOffpageConnector", + "actionButtonBlank", + "actionButtonHome", + "actionButtonHelp", + "actionButtonInformation", + "actionButtonForwardNext", + "actionButtonBackPrevious", + "actionButtonEnd", + "actionButtonBeginning", + "actionButtonReturn", + "actionButtonDocument", + "actionButtonSound", + "actionButtonMovie", + "gear6", + "gear9", + "funnel", + "mathPlus", + "mathMinus", + "mathMultiply", + "mathDivide", + "mathEqual", + "mathNotEqual", + "cornerTabs", + "squareTabs", + "plaqueTabs", + "chartX", + "chartStar", + "chartPlus", +] + +class Point2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + x: Incomplete + y: Incomplete + def __init__(self, x=None, y=None) -> None: ... + +class PositiveSize2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + cx: Integer[Literal[False]] + width: Alias + cy: Integer[Literal[False]] + height: Alias + def __init__(self, cx: ConvertibleToInt, cy: ConvertibleToInt) -> None: ... + +class Transform2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rot: Integer[Literal[True]] + flipH: Bool[Literal[True]] + flipV: Bool[Literal[True]] + off: Typed[Point2D, Literal[True]] + ext: Typed[PositiveSize2D, Literal[True]] + chOff: Typed[Point2D, Literal[True]] + chExt: Typed[PositiveSize2D, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rot: ConvertibleToInt | None = None, + flipH: _ConvertibleToBool | None = None, + flipV: _ConvertibleToBool | None = None, + off: Point2D | None = None, + ext: PositiveSize2D | None = None, + chOff: Point2D | None = None, + chExt: PositiveSize2D | None = None, + ) -> None: ... + +class GroupTransform2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rot: Integer[Literal[True]] + flipH: Bool[Literal[True]] + flipV: Bool[Literal[True]] + off = Typed(expected_type=Point2D, allow_none=True) + ext = Typed(expected_type=PositiveSize2D, allow_none=True) + chOff = Typed(expected_type=Point2D, allow_none=True) + chExt = Typed(expected_type=PositiveSize2D, allow_none=True) + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rot: ConvertibleToInt | None = 0, + flipH: _ConvertibleToBool | None = None, + flipV: _ConvertibleToBool | None = None, + off: Point2D | None = None, + ext: PositiveSize2D | None = None, + chOff: Point2D | None = None, + chExt: PositiveSize2D | None = None, + ) -> None: ... + +class SphereCoords(Serialisable): + tagname: ClassVar[str] + lat: Integer[Literal[False]] + lon: Integer[Literal[False]] + rev: Integer[Literal[False]] + def __init__(self, lat: ConvertibleToInt, lon: ConvertibleToInt, rev: ConvertibleToInt) -> None: ... + +class Camera(Serialisable): + tagname: ClassVar[str] + prst: Set[_CameraPrst] + fov: Integer[Literal[True]] + zoom: Typed[Percentage, Literal[True]] + rot: Typed[SphereCoords, Literal[True]] + def __init__( + self, + prst: _CameraPrst, + fov: ConvertibleToInt | None = None, + zoom: Percentage | None = None, + rot: SphereCoords | None = None, + ) -> None: ... + +class LightRig(Serialisable): + tagname: ClassVar[str] + rig: Set[_LightRigRig] + dir: Set[_LightRigDir] + rot: Typed[SphereCoords, Literal[True]] + def __init__(self, rig: _LightRigRig, dir: _LightRigDir, rot: SphereCoords | None = None) -> None: ... + +class Vector3D(Serialisable): + tagname: ClassVar[str] + dx: Integer[Literal[False]] + dy: Integer[Literal[False]] + dz: Integer[Literal[False]] + def __init__(self, dx: ConvertibleToInt, dy: ConvertibleToInt, dz: ConvertibleToInt) -> None: ... + +class Point3D(Serialisable): + tagname: ClassVar[str] + x: Integer[Literal[False]] + y: Integer[Literal[False]] + z: Integer[Literal[False]] + def __init__(self, x: ConvertibleToInt, y: ConvertibleToInt, z: ConvertibleToInt) -> None: ... + +class Backdrop(Serialisable): + anchor: Typed[Point3D, Literal[False]] + norm: Typed[Vector3D, Literal[False]] + up: Typed[Vector3D, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__(self, anchor: Point3D, norm: Vector3D, up: Vector3D, extLst: ExtensionList | None = None) -> None: ... + +class Scene3D(Serialisable): + camera: Typed[Camera, Literal[False]] + lightRig: Typed[LightRig, Literal[False]] + backdrop: Typed[Backdrop, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, camera: Camera, lightRig: LightRig, backdrop: Backdrop | None = None, extLst: ExtensionList | None = None + ) -> None: ... + +class Bevel(Serialisable): + tagname: ClassVar[str] + w: Integer[Literal[False]] + h: Integer[Literal[False]] + prst: NoneSet[_BevelPrst] + def __init__(self, w: ConvertibleToInt, h: ConvertibleToInt, prst: _BevelPrst | Literal["none"] | None = None) -> None: ... + +class Shape3D(Serialisable): + namespace: ClassVar[str] + z: Typed[Coordinate[bool], Literal[True]] + extrusionH: Integer[Literal[True]] + contourW: Integer[Literal[True]] + prstMaterial: NoneSet[_Shape3DPrstMaterial] + bevelT: Typed[Bevel, Literal[True]] + bevelB: Typed[Bevel, Literal[True]] + extrusionClr: Typed[Color, Literal[True]] + contourClr: Typed[Color, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + z: Coordinate[bool] | None = None, + extrusionH: ConvertibleToInt | None = None, + contourW: ConvertibleToInt | None = None, + prstMaterial: _Shape3DPrstMaterial | Literal["none"] | None = None, + bevelT: Bevel | None = None, + bevelB: Bevel | None = None, + extrusionClr: Color | None = None, + contourClr: Color | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class Path2D(Serialisable): + w: Float[Literal[False]] + h: Float[Literal[False]] + fill: NoneSet[_Path2DFill] + stroke: Bool[Literal[True]] + extrusionOk: Bool[Literal[True]] + def __init__( + self, + w: ConvertibleToFloat, + h: ConvertibleToFloat, + fill: _Path2DFill | Literal["none"] | None = None, + stroke: _ConvertibleToBool | None = None, + extrusionOk: _ConvertibleToBool | None = None, + ) -> None: ... + +class Path2DList(Serialisable): + path: Typed[Path2D, Literal[True]] + def __init__(self, path: Path2D | None = None) -> None: ... + +class GeomRect(Serialisable): + l: Incomplete + t: Incomplete + r: Incomplete + b: Incomplete + def __init__(self, l=None, t=None, r=None, b=None) -> None: ... + +class AdjPoint2D(Serialisable): + x: Incomplete + y: Incomplete + def __init__(self, x=None, y=None) -> None: ... + +class ConnectionSite(Serialisable): + ang: MinMax[float, Literal[False]] + pos: Typed[AdjPoint2D, Literal[False]] + def __init__(self, ang: ConvertibleToFloat, pos: AdjPoint2D) -> None: ... + +class ConnectionSiteList(Serialisable): + cxn: Typed[ConnectionSite, Literal[True]] + def __init__(self, cxn: ConnectionSite | None = None) -> None: ... + +class AdjustHandleList(Serialisable): ... + +class GeomGuide(Serialisable): + name: String[Literal[False]] + fmla: String[Literal[False]] + def __init__(self, name: str, fmla: str) -> None: ... + +class GeomGuideList(Serialisable): + gd: Typed[GeomGuide, Literal[True]] + def __init__(self, gd: GeomGuide | None = None) -> None: ... + +class CustomGeometry2D(Serialisable): + avLst: Typed[GeomGuideList, Literal[True]] + gdLst: Typed[GeomGuideList, Literal[True]] + ahLst: Typed[AdjustHandleList, Literal[True]] + cxnLst: Typed[ConnectionSiteList, Literal[True]] + pathLst: Typed[Path2DList, Literal[False]] + rect: GeomRect | None + + @overload + def __init__( + self, + avLst: GeomGuideList | None = None, + gdLst: GeomGuideList | None = None, + ahLst: AdjustHandleList | None = None, + cxnLst: ConnectionSiteList | None = None, + rect: Unused = None, + *, + pathLst: Path2DList, + ) -> None: ... + @overload + def __init__( + self, + avLst: GeomGuideList | None, + gdLst: GeomGuideList | None, + ahLst: AdjustHandleList | None, + cxnLst: ConnectionSiteList | None, + rect: Unused, + pathLst: Path2DList, + ) -> None: ... + +class PresetGeometry2D(Serialisable): + namespace: ClassVar[str] + prst: Set[_PresetGeometry2DPrst] + avLst: Typed[GeomGuideList, Literal[True]] + def __init__(self, prst: _PresetGeometry2DPrst, avLst: GeomGuideList | None = None) -> None: ... + +class FontReference(Serialisable): + idx: NoneSet[_FontReferenceIdx] + def __init__(self, idx: _FontReferenceIdx | Literal["none"] | None = None) -> None: ... + +class StyleMatrixReference(Serialisable): + idx: Integer[Literal[False]] + def __init__(self, idx: ConvertibleToInt) -> None: ... + +class ShapeStyle(Serialisable): + lnRef: Typed[StyleMatrixReference, Literal[False]] + fillRef: Typed[StyleMatrixReference, Literal[False]] + effectRef: Typed[StyleMatrixReference, Literal[False]] + fontRef: Typed[FontReference, Literal[False]] + def __init__( + self, lnRef: StyleMatrixReference, fillRef: StyleMatrixReference, effectRef: StyleMatrixReference, fontRef: FontReference + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/graphic.pyi b/stubs/openpyxl/openpyxl/drawing/graphic.pyi new file mode 100644 index 000000000000..38164a99b4ef --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/graphic.pyi @@ -0,0 +1,83 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.picture import PictureFrame +from openpyxl.drawing.properties import GroupShapeProperties, NonVisualGroupShape +from openpyxl.drawing.relation import ChartRelation +from openpyxl.drawing.xdr import XDRTransform2D + +class GraphicFrameLocking(Serialisable): + noGrp: Bool[Literal[True]] + noDrilldown: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + noGrp: _ConvertibleToBool | None = None, + noDrilldown: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class NonVisualGraphicFrameProperties(Serialisable): + tagname: ClassVar[str] + graphicFrameLocks: Typed[GraphicFrameLocking, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__(self, graphicFrameLocks: GraphicFrameLocking | None = None, extLst: ExtensionList | None = None) -> None: ... + +class NonVisualGraphicFrame(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[ExtensionList, Literal[False]] + cNvGraphicFramePr: Typed[ExtensionList, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cNvPr=None, cNvGraphicFramePr=None) -> None: ... + +class GraphicData(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + uri: String[Literal[False]] + chart: Typed[ChartRelation, Literal[True]] + def __init__(self, uri: str = ..., chart: ChartRelation | None = None) -> None: ... + +class GraphicObject(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + graphicData: Typed[GraphicData, Literal[False]] + def __init__(self, graphicData: GraphicData | None = None) -> None: ... + +class GraphicFrame(Serialisable): + tagname: ClassVar[str] + nvGraphicFramePr: Typed[NonVisualGraphicFrame, Literal[False]] + xfrm: Typed[XDRTransform2D, Literal[False]] + graphic: Typed[GraphicObject, Literal[False]] + macro: String[Literal[True]] + fPublished: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + nvGraphicFramePr: NonVisualGraphicFrame | None = None, + xfrm: XDRTransform2D | None = None, + graphic: GraphicObject | None = None, + macro: str | None = None, + fPublished: _ConvertibleToBool | None = None, + ) -> None: ... + +class GroupShape(Serialisable): + nvGrpSpPr: Typed[NonVisualGroupShape, Literal[False]] + nonVisualProperties: Alias + grpSpPr: Typed[GroupShapeProperties, Literal[False]] + visualProperties: Alias + pic: Typed[PictureFrame, Literal[True]] + # Source incorrectly uses a list here instead of a tuple + __elements__: ClassVar[list[str]] # type: ignore[assignment] + def __init__( + self, nvGrpSpPr: NonVisualGroupShape, grpSpPr: GroupShapeProperties, pic: PictureFrame | None = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/image.pyi b/stubs/openpyxl/openpyxl/drawing/image.pyi new file mode 100644 index 000000000000..c3a35a1384b4 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/image.pyi @@ -0,0 +1,23 @@ +from _typeshed import SupportsRead +from pathlib import Path +from types import ModuleType +from typing import Any, Literal, TypeAlias + +from openpyxl.drawing.spreadsheet_drawing import _AnchorBase + +# Is actually PIL.Image.Image +_PILImageImage: TypeAlias = Any +# same as first parameter of PIL.Image.open +_PILImageFilePath: TypeAlias = str | bytes | Path | SupportsRead[bytes] + +PILImage: ModuleType | Literal[False] + +class Image: + anchor: str | _AnchorBase + ref: _PILImageImage | _PILImageFilePath + width: int + height: int + format: str + def __init__(self, img: _PILImageImage | _PILImageFilePath) -> None: ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/drawing/line.pyi b/stubs/openpyxl/openpyxl/drawing/line.pyi new file mode 100644 index 000000000000..209d8165ea15 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/line.pyi @@ -0,0 +1,88 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Integer, MinMax, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import EmptyTag, NestedInteger, NestedNoneSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, ColorChoiceDescriptor +from openpyxl.drawing.fill import GradientFillProperties, PatternFillProperties + +from ..xml._functions_overloads import _HasTagAndGet + +_LineEndPropertiesType: TypeAlias = Literal["none", "triangle", "stealth", "diamond", "oval", "arrow"] +_LineEndPropertiesWLen: TypeAlias = Literal["sm", "med", "lg"] +_LinePropertiesCap: TypeAlias = Literal["rnd", "sq", "flat"] +_LinePropertiesCmpd: TypeAlias = Literal["sng", "dbl", "thickThin", "thinThick", "tri"] +_LinePropertiesAlgn: TypeAlias = Literal["ctr", "in"] +_LinePropertiesPrstDash: TypeAlias = Literal[ + "solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot", "sysDash", "sysDot", "sysDashDot", "sysDashDotDot" +] + +class LineEndProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + type: NoneSet[_LineEndPropertiesType] + w: NoneSet[_LineEndPropertiesWLen] + len: NoneSet[_LineEndPropertiesWLen] + def __init__( + self, + type: _LineEndPropertiesType | Literal["none"] | None = None, + w: _LineEndPropertiesWLen | Literal["none"] | None = None, + len: _LineEndPropertiesWLen | Literal["none"] | None = None, + ) -> None: ... + +class DashStop(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + d: Integer[Literal[False]] + length: Alias + sp: Integer[Literal[False]] + space: Alias + def __init__(self, d: ConvertibleToInt = 0, sp: ConvertibleToInt = 0) -> None: ... + +class DashStopList(Serialisable): + ds: Incomplete + def __init__(self, ds=None) -> None: ... + +class LineProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + w: MinMax[float, Literal[True]] + width: Alias + cap: NoneSet[_LinePropertiesCap] + cmpd: NoneSet[_LinePropertiesCmpd] + algn: NoneSet[_LinePropertiesAlgn] + noFill: EmptyTag[Literal[False]] + solidFill: ColorChoiceDescriptor + gradFill: Typed[GradientFillProperties, Literal[True]] + pattFill: Typed[PatternFillProperties, Literal[True]] + prstDash: NestedNoneSet[_LinePropertiesPrstDash] + dashStyle: Alias + custDash: Typed[DashStop, Literal[True]] + round: EmptyTag[Literal[False]] + bevel: EmptyTag[Literal[False]] + miter: NestedInteger[Literal[True]] + headEnd: Typed[LineEndProperties, Literal[True]] + tailEnd: Typed[LineEndProperties, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + w: ConvertibleToFloat | None = None, + cap: _LinePropertiesCap | Literal["none"] | None = None, + cmpd: _LinePropertiesCmpd | Literal["none"] | None = None, + algn: _LinePropertiesAlgn | Literal["none"] | None = None, + noFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + solidFill: str | ColorChoice | None = None, + gradFill: GradientFillProperties | None = None, + pattFill: PatternFillProperties | None = None, + prstDash: _NestedNoneSetParam[_LinePropertiesPrstDash] = None, + custDash: DashStop | None = None, + round: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + bevel: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + miter: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + headEnd: LineEndProperties | None = None, + tailEnd: LineEndProperties | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/picture.pyi b/stubs/openpyxl/openpyxl/drawing/picture.pyi new file mode 100644 index 000000000000..4a3de4c9ea65 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/picture.pyi @@ -0,0 +1,79 @@ +from _typeshed import Unused +from typing import ClassVar, Literal + +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.fill import BlipFillProperties +from openpyxl.drawing.geometry import ShapeStyle +from openpyxl.drawing.properties import NonVisualDrawingProps + +class PictureLocking(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + noCrop: Bool[Literal[True]] + noGrp: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noRot: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + noEditPoints: Bool[Literal[True]] + noAdjustHandles: Bool[Literal[True]] + noChangeArrowheads: Bool[Literal[True]] + noChangeShapeType: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + noCrop: _ConvertibleToBool | None = None, + noGrp: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noRot: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + noEditPoints: _ConvertibleToBool | None = None, + noAdjustHandles: _ConvertibleToBool | None = None, + noChangeArrowheads: _ConvertibleToBool | None = None, + noChangeShapeType: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class NonVisualPictureProperties(Serialisable): + tagname: ClassVar[str] + preferRelativeResize: Bool[Literal[True]] + picLocks: Typed[PictureLocking, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, preferRelativeResize: _ConvertibleToBool | None = None, picLocks=None, extLst: Unused = None) -> None: ... + +class PictureNonVisual(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvPicPr: Typed[NonVisualPictureProperties, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, cNvPr: NonVisualDrawingProps | None = None, cNvPicPr: NonVisualPictureProperties | None = None + ) -> None: ... + +class PictureFrame(Serialisable): + tagname: ClassVar[str] + macro: String[Literal[True]] + fPublished: Bool[Literal[True]] + nvPicPr: Typed[PictureNonVisual, Literal[False]] + blipFill: Typed[BlipFillProperties, Literal[False]] + spPr: Typed[GraphicalProperties, Literal[False]] + graphicalProperties: Alias + style: Typed[ShapeStyle, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + macro: str | None = None, + fPublished: _ConvertibleToBool | None = None, + nvPicPr: PictureNonVisual | None = None, + blipFill: BlipFillProperties | None = None, + spPr: GraphicalProperties | None = None, + style: ShapeStyle | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/properties.pyi b/stubs/openpyxl/openpyxl/drawing/properties.pyi new file mode 100644 index 000000000000..48aae4d92053 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/properties.pyi @@ -0,0 +1,120 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.geometry import GroupTransform2D, Scene3D +from openpyxl.drawing.text import Hyperlink + +_GroupShapePropertiesBwMode: TypeAlias = Literal[ + "clr", "auto", "gray", "ltGray", "invGray", "grayWhite", "blackGray", "blackWhite", "black", "white", "hidden" +] + +class GroupShapeProperties(Serialisable): + tagname: ClassVar[str] + bwMode: NoneSet[_GroupShapePropertiesBwMode] + xfrm: Typed[GroupTransform2D, Literal[True]] + scene3d: Typed[Scene3D, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + bwMode: _GroupShapePropertiesBwMode | Literal["none"] | None = None, + xfrm: GroupTransform2D | None = None, + scene3d: Scene3D | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class GroupLocking(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + noGrp: Bool[Literal[True]] + noUngrp: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noRot: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + noChangeArrowheads: Bool[Literal[True]] + noEditPoints: Bool[Literal[True]] + noAdjustHandles: Bool[Literal[True]] + noChangeShapeType: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + noGrp: _ConvertibleToBool | None = None, + noUngrp: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noRot: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noChangeArrowheads: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + noEditPoints: _ConvertibleToBool | None = None, + noAdjustHandles: _ConvertibleToBool | None = None, + noChangeShapeType: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class NonVisualGroupDrawingShapeProps(Serialisable): + tagname: ClassVar[str] + grpSpLocks: Typed[GroupLocking, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, grpSpLocks=None, extLst: Unused = None) -> None: ... + +class NonVisualDrawingShapeProps(Serialisable): + tagname: ClassVar[str] + spLocks: Typed[GroupLocking, Literal[True]] + txBax: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + txBox: Incomplete + def __init__(self, spLocks=None, txBox: _ConvertibleToBool | None = None, extLst: Unused = None) -> None: ... + +class NonVisualDrawingProps(Serialisable): + tagname: ClassVar[str] + id: Incomplete + name: String[Literal[False]] + descr: String[Literal[True]] + hidden: Bool[Literal[True]] + title: String[Literal[True]] + hlinkClick: Typed[Hyperlink, Literal[True]] + hlinkHover: Typed[Hyperlink, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + # Source incorrectly uses a list here instead of a tuple + __elements__: ClassVar[list[str]] # type: ignore[assignment] + + @overload + def __init__( + self, + id=None, + *, + name: str, + descr: str | None = None, + hidden: _ConvertibleToBool | None = None, + title: str | None = None, + hlinkClick: Hyperlink | None = None, + hlinkHover: Hyperlink | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: Incomplete | None, + name: str, + descr: str | None = None, + hidden: _ConvertibleToBool | None = None, + title: str | None = None, + hlinkClick: Hyperlink | None = None, + hlinkHover: Hyperlink | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class NonVisualGroupShape(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvGrpSpPr: Typed[NonVisualGroupDrawingShapeProps, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cNvPr: NonVisualDrawingProps, cNvGrpSpPr: NonVisualGroupDrawingShapeProps) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/relation.pyi b/stubs/openpyxl/openpyxl/drawing/relation.pyi new file mode 100644 index 000000000000..46828b6f9767 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/relation.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class ChartRelation(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + id: Incomplete + def __init__(self, id) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi b/stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi new file mode 100644 index 000000000000..f675b423b091 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi @@ -0,0 +1,120 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.connector import Shape +from openpyxl.drawing.graphic import GraphicFrame, GroupShape +from openpyxl.drawing.picture import PictureFrame +from openpyxl.drawing.xdr import XDRPoint2D, XDRPositiveSize2D + +_TwoCellAnchorEditAs: TypeAlias = Literal["twoCell", "oneCell", "absolute"] + +class AnchorClientData(Serialisable): + fLocksWithSheet: Bool[Literal[True]] + fPrintsWithSheet: Bool[Literal[True]] + def __init__( + self, fLocksWithSheet: _ConvertibleToBool | None = None, fPrintsWithSheet: _ConvertibleToBool | None = None + ) -> None: ... + +class AnchorMarker(Serialisable): + tagname: ClassVar[str] + col: NestedText[int, Literal[False]] + colOff: NestedText[int, Literal[False]] + row: NestedText[int, Literal[False]] + rowOff: NestedText[int, Literal[False]] + def __init__( + self, col: ConvertibleToInt = 0, colOff: ConvertibleToInt = 0, row: ConvertibleToInt = 0, rowOff: ConvertibleToInt = 0 + ) -> None: ... + +class _AnchorBase(Serialisable): + sp: Typed[Shape, Literal[True]] + shape: Alias + grpSp: Typed[GroupShape, Literal[True]] + groupShape: Alias + graphicFrame: Typed[GraphicFrame, Literal[True]] + cxnSp: Typed[Shape, Literal[True]] + connectionShape: Alias + pic: Typed[PictureFrame, Literal[True]] + contentPart: Incomplete + clientData: Typed[AnchorClientData, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + clientData: AnchorClientData | None = None, + sp: Shape | None = None, + grpSp: GroupShape | None = None, + graphicFrame: GraphicFrame | None = None, + cxnSp: Shape | None = None, + pic: PictureFrame | None = None, + contentPart=None, + ) -> None: ... + +class AbsoluteAnchor(_AnchorBase): + tagname: ClassVar[str] + pos: Typed[XDRPoint2D, Literal[False]] + ext: Typed[XDRPositiveSize2D, Literal[False]] + # Same as parent + # sp = _AnchorBase.sp + # grpSp = _AnchorBase.grpSp + # graphicFrame = _AnchorBase.graphicFrame + # cxnSp = _AnchorBase.cxnSp + # pic = _AnchorBase.pic + # contentPart = _AnchorBase.contentPart + # clientData = _AnchorBase.clientData + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, pos: XDRPoint2D | None = None, ext: XDRPositiveSize2D | None = None, **kw) -> None: ... + +class OneCellAnchor(_AnchorBase): + tagname: ClassVar[str] + _from: Typed[AnchorMarker, Literal[False]] # Not private. Avoids name clash + ext: Typed[XDRPositiveSize2D, Literal[False]] + # Same as parent + # sp = _AnchorBase.sp + # grpSp = _AnchorBase.grpSp + # graphicFrame = _AnchorBase.graphicFrame + # cxnSp = _AnchorBase.cxnSp + # pic = _AnchorBase.pic + # contentPart = _AnchorBase.contentPart + # clientData = _AnchorBase.clientData + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, _from: AnchorMarker | None = None, ext: XDRPositiveSize2D | None = None, **kw) -> None: ... + +class TwoCellAnchor(_AnchorBase): + tagname: ClassVar[str] + editAs: NoneSet[_TwoCellAnchorEditAs] + _from: Typed[AnchorMarker, Literal[False]] # Not private. Avoids name clash + to: Typed[AnchorMarker, Literal[False]] + # Same as parent + # sp = _AnchorBase.sp + # grpSp = _AnchorBase.grpSp + # graphicFrame = _AnchorBase.graphicFrame + # cxnSp = _AnchorBase.cxnSp + # pic = _AnchorBase.pic + # contentPart = _AnchorBase.contentPart + # clientData = _AnchorBase.clientData + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + editAs: _TwoCellAnchorEditAs | Literal["none"] | None = None, + _from: AnchorMarker | None = None, + to: AnchorMarker | None = None, + **kw, + ) -> None: ... + +class SpreadsheetDrawing(Serialisable): + tagname: ClassVar[str] + mime_type: str + PartName: str + twoCellAnchor: Incomplete + oneCellAnchor: Incomplete + absoluteAnchor: Incomplete + __elements__: ClassVar[tuple[str, ...]] + charts: Incomplete + images: Incomplete + def __init__(self, twoCellAnchor=(), oneCellAnchor=(), absoluteAnchor=()) -> None: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/drawing/text.pyi b/stubs/openpyxl/openpyxl/drawing/text.pyi new file mode 100644 index 000000000000..3ead43febde6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/text.pyi @@ -0,0 +1,515 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, Integer, MinMax, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import Coordinate, ExtensionList +from openpyxl.descriptors.nested import EmptyTag, NestedBool, NestedInteger, NestedText, NestedValue +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, ColorChoiceDescriptor +from openpyxl.drawing.effect import Color, EffectContainer, EffectList +from openpyxl.drawing.fill import Blip, BlipFillProperties, GradientFillProperties, PatternFillProperties +from openpyxl.drawing.geometry import Scene3D +from openpyxl.drawing.line import LineProperties + +from ..xml._functions_overloads import _HasTagAndGet + +_CharacterPropertiesU: TypeAlias = Literal[ + "words", + "sng", + "dbl", + "heavy", + "dotted", + "dottedHeavy", + "dash", + "dashHeavy", + "dashLong", + "dashLongHeavy", + "dotDash", + "dotDashHeavy", + "dotDotDash", + "dotDotDashHeavy", + "wavy", + "wavyHeavy", + "wavyDbl", +] +_CharacterPropertiesStrike: TypeAlias = Literal["noStrike", "sngStrike", "dblStrike"] +_CharacterPropertiesCap: TypeAlias = Literal["small", "all"] +_ParagraphPropertiesAlgn: TypeAlias = Literal["l", "ctr", "r", "just", "justLow", "dist", "thaiDist"] +_ParagraphPropertiesFontAlgn: TypeAlias = Literal["auto", "t", "ctr", "base", "b"] +_RichTextPropertiesVertOverflow: TypeAlias = Literal["overflow", "ellipsis", "clip"] +_RichTextPropertiesHorzOverflow: TypeAlias = Literal["overflow", "clip"] +_RichTextPropertiesVert: TypeAlias = Literal[ + "horz", "vert", "vert270", "wordArtVert", "eaVert", "mongolianVert", "wordArtVertRtl" +] +_RichTextPropertiesWrap: TypeAlias = Literal["none", "square"] +_RichTextPropertiesAnchor: TypeAlias = Literal["t", "ctr", "b", "just", "dist"] +_AutonumberBulletType: TypeAlias = Literal[ + "alphaLcParenBoth", + "alphaUcParenBoth", + "alphaLcParenR", + "alphaUcParenR", + "alphaLcPeriod", + "alphaUcPeriod", + "arabicParenBoth", + "arabicParenR", + "arabicPeriod", + "arabicPlain", + "romanLcParenBoth", + "romanUcParenBoth", + "romanLcParenR", + "romanUcParenR", + "romanLcPeriod", + "romanUcPeriod", + "circleNumDbPlain", + "circleNumWdBlackPlain", + "circleNumWdWhitePlain", + "arabicDbPeriod", + "arabicDbPlain", + "ea1ChsPeriod", + "ea1ChsPlain", + "ea1ChtPeriod", + "ea1ChtPlain", + "ea1JpnChsDbPeriod", + "ea1JpnKorPlain", + "ea1JpnKorPeriod", + "arabic1Minus", + "arabic2Minus", + "hebrew2Minus", + "thaiAlphaPeriod", + "thaiAlphaParenR", + "thaiAlphaParenBoth", + "thaiNumPeriod", + "thaiNumParenR", + "thaiNumParenBoth", + "hindiAlphaPeriod", + "hindiNumPeriod", + "hindiNumParenR", + "hindiAlpha1Period", +] +_TabStopAlgn: TypeAlias = Literal["l", "ctr", "r", "dec"] +_PresetTextShapePrst: TypeAlias = Literal[ + "textNoShape", + "textPlain", + "textStop", + "textTriangle", + "textTriangleInverted", + "textChevron", + "textChevronInverted", + "textRingInside", + "textRingOutside", + "textArchUp", + "textArchDown", + "textCircle", + "textButton", + "textArchUpPour", + "textArchDownPour", + "textCirclePour", + "textButtonPour", + "textCurveUp", + "textCurveDown", + "textCanUp", + "textCanDown", + "textWave1", + "textWave2", + "textDoubleWave1", + "textWave4", + "textInflate", + "textDeflate", + "textInflateBottom", + "textDeflateBottom", + "textInflateTop", + "textDeflateTop", + "textDeflateInflate", + "textDeflateInflateDeflate", + "textFadeRight", + "textFadeLeft", + "textFadeUp", + "textFadeDown", + "textSlantUp", + "textSlantDown", + "textCascadeUp", + "textCascadeDown", +] + +class EmbeddedWAVAudioFile(Serialisable): + name: String[Literal[True]] + def __init__(self, name: str | None = None) -> None: ... + +class Hyperlink(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + invalidUrl: String[Literal[True]] + action: String[Literal[True]] + tgtFrame: String[Literal[True]] + tooltip: String[Literal[True]] + history: Bool[Literal[True]] + highlightClick: Bool[Literal[True]] + endSnd: Bool[Literal[True]] + snd: Typed[EmbeddedWAVAudioFile, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + invalidUrl: str | None = None, + action: str | None = None, + tgtFrame: str | None = None, + tooltip: str | None = None, + history: _ConvertibleToBool | None = None, + highlightClick: _ConvertibleToBool | None = None, + endSnd: _ConvertibleToBool | None = None, + snd: EmbeddedWAVAudioFile | None = None, + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + +class Font(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + typeface: String[Literal[False]] + panose: Incomplete + pitchFamily: MinMax[float, Literal[True]] + charset: Integer[Literal[True]] + def __init__( + self, typeface: str, panose=None, pitchFamily: ConvertibleToFloat | None = None, charset: ConvertibleToInt | None = None + ) -> None: ... + +class CharacterProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + kumimoji: Bool[Literal[True]] + lang: String[Literal[True]] + altLang: String[Literal[True]] + sz: MinMax[float, Literal[True]] + b: Bool[Literal[True]] + i: Bool[Literal[True]] + u: NoneSet[_CharacterPropertiesU] + strike: NoneSet[_CharacterPropertiesStrike] + kern: Integer[Literal[True]] + cap: NoneSet[_CharacterPropertiesCap] + spc: Integer[Literal[True]] + normalizeH: Bool[Literal[True]] + baseline: Integer[Literal[True]] + noProof: Bool[Literal[True]] + dirty: Bool[Literal[True]] + err: Bool[Literal[True]] + smtClean: Bool[Literal[True]] + smtId: Integer[Literal[True]] + bmk: String[Literal[True]] + ln: Typed[LineProperties, Literal[True]] + highlight: Typed[Color, Literal[True]] + latin: Typed[Font, Literal[True]] + ea: Typed[Font, Literal[True]] + cs: Typed[Font, Literal[True]] + sym: Typed[Font, Literal[True]] + hlinkClick: Typed[Hyperlink, Literal[True]] + hlinkMouseOver: Typed[Hyperlink, Literal[True]] + rtl: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + noFill: EmptyTag[Literal[False]] + solidFill: ColorChoiceDescriptor + gradFill: Typed[GradientFillProperties, Literal[True]] + blipFill: Typed[BlipFillProperties, Literal[True]] + pattFill: Typed[PatternFillProperties, Literal[True]] + grpFill: EmptyTag[Literal[False]] + effectLst: Typed[EffectList, Literal[True]] + effectDag: Typed[EffectContainer, Literal[True]] + uLnTx: EmptyTag[Literal[False]] + uLn: Typed[LineProperties, Literal[True]] + uFillTx: EmptyTag[Literal[False]] + uFill: EmptyTag[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + kumimoji: _ConvertibleToBool | None = None, + lang: str | None = None, + altLang: str | None = None, + sz: ConvertibleToFloat | None = None, + b: _ConvertibleToBool | None = None, + i: _ConvertibleToBool | None = None, + u: _CharacterPropertiesU | Literal["none"] | None = None, + strike: _CharacterPropertiesStrike | Literal["none"] | None = None, + kern: ConvertibleToInt | None = None, + cap: _CharacterPropertiesCap | Literal["none"] | None = None, + spc: ConvertibleToInt | None = None, + normalizeH: _ConvertibleToBool | None = None, + baseline: ConvertibleToInt | None = None, + noProof: _ConvertibleToBool | None = None, + dirty: _ConvertibleToBool | None = None, + err: _ConvertibleToBool | None = None, + smtClean: _ConvertibleToBool | None = None, + smtId: ConvertibleToInt | None = None, + bmk: str | None = None, + ln: LineProperties | None = None, + highlight: Color | None = None, + latin: Font | None = None, + ea: Font | None = None, + cs: Font | None = None, + sym: Font | None = None, + hlinkClick: Hyperlink | None = None, + hlinkMouseOver: Hyperlink | None = None, + rtl: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + noFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + solidFill: str | ColorChoice | None = None, + gradFill: GradientFillProperties | None = None, + blipFill: BlipFillProperties | None = None, + pattFill: PatternFillProperties | None = None, + grpFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + effectLst: EffectList | None = None, + effectDag: EffectContainer | None = None, + uLnTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + uLn: LineProperties | None = None, + uFillTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + uFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + ) -> None: ... + +class TabStop(Serialisable): + pos: Typed[Coordinate[bool], Literal[True]] + algn: Typed[Set[_TabStopAlgn], Literal[False]] + def __init__(self, pos: Coordinate[bool] | None = None, algn: Set[_TabStopAlgn] | None = None) -> None: ... + +class TabStopList(Serialisable): + tab: Typed[TabStop, Literal[True]] + def __init__(self, tab=None) -> None: ... + +class Spacing(Serialisable): + spcPct: NestedInteger[Literal[True]] + spcPts: NestedInteger[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + spcPct: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + spcPts: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + ) -> None: ... + +class AutonumberBullet(Serialisable): + type: Set[_AutonumberBulletType] + startAt: Integer[Literal[False]] + def __init__(self, type: _AutonumberBulletType, startAt: ConvertibleToInt) -> None: ... + +class ParagraphProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + marL: Integer[Literal[True]] + marR: Integer[Literal[True]] + lvl: Integer[Literal[True]] + indent: Integer[Literal[True]] + algn: NoneSet[_ParagraphPropertiesAlgn] + defTabSz: Integer[Literal[True]] + rtl: Bool[Literal[True]] + eaLnBrk: Bool[Literal[True]] + fontAlgn: NoneSet[_ParagraphPropertiesFontAlgn] + latinLnBrk: Bool[Literal[True]] + hangingPunct: Bool[Literal[True]] + lnSpc: Typed[Spacing, Literal[True]] + spcBef: Typed[Spacing, Literal[True]] + spcAft: Typed[Spacing, Literal[True]] + tabLst: Typed[TabStopList, Literal[True]] + defRPr: Typed[CharacterProperties, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + buClrTx: EmptyTag[Literal[False]] + buClr: Typed[Color, Literal[True]] + buSzTx: EmptyTag[Literal[False]] + buSzPct: NestedInteger[Literal[True]] + buSzPts: NestedInteger[Literal[True]] + buFontTx: EmptyTag[Literal[False]] + buFont: Typed[Font, Literal[True]] + buNone: EmptyTag[Literal[False]] + buAutoNum: EmptyTag[Literal[False]] + buChar: NestedValue[str, Literal[True]] + buBlip: NestedValue[Blip, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + marL: ConvertibleToInt | None = None, + marR: ConvertibleToInt | None = None, + lvl: ConvertibleToInt | None = None, + indent: ConvertibleToInt | None = None, + algn: _ParagraphPropertiesAlgn | Literal["none"] | None = None, + defTabSz: ConvertibleToInt | None = None, + rtl: _ConvertibleToBool | None = None, + eaLnBrk: _ConvertibleToBool | None = None, + fontAlgn: _ParagraphPropertiesFontAlgn | Literal["none"] | None = None, + latinLnBrk: _ConvertibleToBool | None = None, + hangingPunct: _ConvertibleToBool | None = None, + lnSpc: Spacing | None = None, + spcBef: Spacing | None = None, + spcAft: Spacing | None = None, + tabLst: TabStopList | None = None, + defRPr: CharacterProperties | None = None, + extLst: ExtensionList | None = None, + buClrTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buClr: Color | None = None, + buSzTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buSzPct: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + buSzPts: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + buFontTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buFont: Font | None = None, + buNone: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buAutoNum: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buChar: object = None, + buBlip: object = None, + ) -> None: ... + +class ListStyle(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + defPPr: Typed[ParagraphProperties, Literal[True]] + lvl1pPr: Typed[ParagraphProperties, Literal[True]] + lvl2pPr: Typed[ParagraphProperties, Literal[True]] + lvl3pPr: Typed[ParagraphProperties, Literal[True]] + lvl4pPr: Typed[ParagraphProperties, Literal[True]] + lvl5pPr: Typed[ParagraphProperties, Literal[True]] + lvl6pPr: Typed[ParagraphProperties, Literal[True]] + lvl7pPr: Typed[ParagraphProperties, Literal[True]] + lvl8pPr: Typed[ParagraphProperties, Literal[True]] + lvl9pPr: Typed[ParagraphProperties, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + defPPr: ParagraphProperties | None = None, + lvl1pPr: ParagraphProperties | None = None, + lvl2pPr: ParagraphProperties | None = None, + lvl3pPr: ParagraphProperties | None = None, + lvl4pPr: ParagraphProperties | None = None, + lvl5pPr: ParagraphProperties | None = None, + lvl6pPr: ParagraphProperties | None = None, + lvl7pPr: ParagraphProperties | None = None, + lvl8pPr: ParagraphProperties | None = None, + lvl9pPr: ParagraphProperties | None = None, + extLst: ParagraphProperties | None = None, + ) -> None: ... + +class RegularTextRun(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rPr: Typed[CharacterProperties, Literal[True]] + properties: Alias + t: NestedText[str, Literal[False]] + value: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rPr: CharacterProperties | None = None, t: object = "") -> None: ... + +class LineBreak(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rPr: Typed[CharacterProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rPr: CharacterProperties | None = None) -> None: ... + +class TextField(Serialisable): + id: String[Literal[False]] + type: String[Literal[True]] + rPr: Typed[CharacterProperties, Literal[True]] + pPr: Typed[CharacterProperties, Literal[True]] + t: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + id: str, + type: str | None = None, + rPr: CharacterProperties | None = None, + pPr: CharacterProperties | None = None, + t: str | None = None, + ) -> None: ... + +class Paragraph(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + pPr: Typed[ParagraphProperties, Literal[True]] + properties: Alias + endParaRPr: Typed[CharacterProperties, Literal[True]] + r: Incomplete + text: Alias + br: Typed[LineBreak, Literal[True]] + fld: Typed[TextField, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + pPr: ParagraphProperties | None = None, + endParaRPr: CharacterProperties | None = None, + r=None, + br: LineBreak | None = None, + fld: TextField | None = None, + ) -> None: ... + +class GeomGuide(Serialisable): + name: String[Literal[False]] + fmla: String[Literal[False]] + def __init__(self, name: str, fmla: str) -> None: ... + +class GeomGuideList(Serialisable): + gd: Incomplete + def __init__(self, gd=None) -> None: ... + +class PresetTextShape(Serialisable): + prst: Typed[Set[_PresetTextShapePrst], Literal[False]] + avLst: Typed[GeomGuideList, Literal[True]] + def __init__(self, prst: Set[_PresetTextShapePrst], avLst: GeomGuideList | None = None) -> None: ... + +class TextNormalAutofit(Serialisable): + fontScale: Integer[Literal[False]] + lnSpcReduction: Integer[Literal[False]] + def __init__(self, fontScale: ConvertibleToInt, lnSpcReduction: ConvertibleToInt) -> None: ... + +class RichTextProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rot: Integer[Literal[True]] + spcFirstLastPara: Bool[Literal[True]] + vertOverflow: NoneSet[_RichTextPropertiesVertOverflow] + horzOverflow: NoneSet[_RichTextPropertiesHorzOverflow] + vert: NoneSet[_RichTextPropertiesVert] + wrap: NoneSet[_RichTextPropertiesWrap] + lIns: Integer[Literal[True]] + tIns: Integer[Literal[True]] + rIns: Integer[Literal[True]] + bIns: Integer[Literal[True]] + numCol: Integer[Literal[True]] + spcCol: Integer[Literal[True]] + rtlCol: Bool[Literal[True]] + fromWordArt: Bool[Literal[True]] + anchor: NoneSet[_RichTextPropertiesAnchor] + anchorCtr: Bool[Literal[True]] + forceAA: Bool[Literal[True]] + upright: Bool[Literal[True]] + compatLnSpc: Bool[Literal[True]] + prstTxWarp: Typed[PresetTextShape, Literal[True]] + scene3d: Typed[Scene3D, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + noAutofit: EmptyTag[Literal[False]] + normAutofit: EmptyTag[Literal[False]] + spAutoFit: EmptyTag[Literal[False]] + flatTx: NestedInteger[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rot: ConvertibleToInt | None = None, + spcFirstLastPara: _ConvertibleToBool | None = None, + vertOverflow: _RichTextPropertiesVertOverflow | Literal["none"] | None = None, + horzOverflow: _RichTextPropertiesHorzOverflow | Literal["none"] | None = None, + vert: _RichTextPropertiesVert | Literal["none"] | None = None, + wrap: _RichTextPropertiesWrap | Literal["none"] | None = None, + lIns: ConvertibleToInt | None = None, + tIns: ConvertibleToInt | None = None, + rIns: ConvertibleToInt | None = None, + bIns: ConvertibleToInt | None = None, + numCol: ConvertibleToInt | None = None, + spcCol: ConvertibleToInt | None = None, + rtlCol: _ConvertibleToBool | None = None, + fromWordArt: _ConvertibleToBool | None = None, + anchor: _RichTextPropertiesAnchor | Literal["none"] | None = None, + anchorCtr: _ConvertibleToBool | None = None, + forceAA: _ConvertibleToBool | None = None, + upright: _ConvertibleToBool | None = None, + compatLnSpc: _ConvertibleToBool | None = None, + prstTxWarp: PresetTextShape | None = None, + scene3d: Scene3D | None = None, + extLst: Unused = None, + noAutofit: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + normAutofit: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + spAutoFit: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + flatTx: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/xdr.pyi b/stubs/openpyxl/openpyxl/drawing/xdr.pyi new file mode 100644 index 000000000000..cab346f7587b --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/xdr.pyi @@ -0,0 +1,26 @@ +from typing import ClassVar + +from .geometry import Point2D, PositiveSize2D, Transform2D + +class XDRPoint2D(Point2D): + namespace: ClassVar[None] # type: ignore[assignment] + # Same as parent + # x = Point2D.x + # y = Point2D.y + +class XDRPositiveSize2D(PositiveSize2D): + namespace: ClassVar[None] # type: ignore[assignment] + # Same as parent + # cx = PositiveSize2D.cx + # cy = PositiveSize2D.cy + +class XDRTransform2D(Transform2D): + namespace: ClassVar[None] # type: ignore[assignment] + # Same as parent + # rot = Transform2D.rot + # flipH = Transform2D.flipH + # flipV = Transform2D.flipV + # off = Transform2D.off + # ext = Transform2D.ext + # chOff = Transform2D.chOff + # chExt = Transform2D.chExt diff --git a/stubs/openpyxl/openpyxl/formatting/__init__.pyi b/stubs/openpyxl/openpyxl/formatting/__init__.pyi new file mode 100644 index 000000000000..c4e04ce61425 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formatting/__init__.pyi @@ -0,0 +1 @@ +from .rule import Rule as Rule diff --git a/stubs/openpyxl/openpyxl/formatting/formatting.pyi b/stubs/openpyxl/openpyxl/formatting/formatting.pyi new file mode 100644 index 000000000000..9d6e9e423f1f --- /dev/null +++ b/stubs/openpyxl/openpyxl/formatting/formatting.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterator +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Bool, Convertible, _ConvertibleToBool, _ConvertibleToMultiCellRange +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange + +class ConditionalFormatting(Serialisable): + tagname: ClassVar[str] + sqref: Convertible[MultiCellRange, Literal[False]] + cells: Alias + pivot: Bool[Literal[True]] + cfRule: Incomplete + rules: Alias + def __init__( + self, sqref: _ConvertibleToMultiCellRange = (), pivot: _ConvertibleToBool | None = None, cfRule=(), extLst: Unused = None + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __contains__(self, coord: str | CellRange) -> bool: ... + +class ConditionalFormattingList: + max_priority: int + def __init__(self) -> None: ... + def add(self, range_string, cfRule) -> None: ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[ConditionalFormatting]: ... + def __getitem__(self, key): ... + def __delitem__(self, key) -> None: ... + def __setitem__(self, key, rule) -> None: ... diff --git a/stubs/openpyxl/openpyxl/formatting/rule.pyi b/stubs/openpyxl/openpyxl/formatting/rule.pyi new file mode 100644 index 000000000000..35ab566356c6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formatting/rule.pyi @@ -0,0 +1,202 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors import Float, Strict +from openpyxl.descriptors.base import Bool, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor +from openpyxl.styles.differential import DifferentialStyle + +_IconSetIconSet: TypeAlias = Literal[ + "3Arrows", + "3ArrowsGray", + "3Flags", + "3TrafficLights1", + "3TrafficLights2", + "3Signs", + "3Symbols", + "3Symbols2", + "4Arrows", + "4ArrowsGray", + "4RedToBlack", + "4Rating", + "4TrafficLights", + "5Arrows", + "5ArrowsGray", + "5Rating", + "5Quarters", +] +_RuleOperator: TypeAlias = Literal[ + "lessThan", + "lessThanOrEqual", + "equal", + "notEqual", + "greaterThanOrEqual", + "greaterThan", + "between", + "notBetween", + "containsText", + "notContains", + "beginsWith", + "endsWith", +] +_RuleTimePeriod: TypeAlias = Literal[ + "today", "yesterday", "tomorrow", "last7Days", "thisMonth", "lastMonth", "nextMonth", "thisWeek", "lastWeek", "nextWeek" +] +_FormatObjectType: TypeAlias = Literal["num", "percent", "max", "min", "formula", "percentile"] +_RuleType: TypeAlias = Literal[ + "expression", + "cellIs", + "colorScale", + "dataBar", + "iconSet", + "top10", + "uniqueValues", + "duplicateValues", + "containsText", + "notContainsText", + "beginsWith", + "endsWith", + "containsBlanks", + "notContainsBlanks", + "containsErrors", + "notContainsErrors", + "timePeriod", + "aboveAverage", +] + +class ValueDescriptor(Float[Incomplete]): + expected_type: type[Incomplete] + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class FormatObject(Serialisable): + tagname: ClassVar[str] + type: Set[_FormatObjectType] + val: Incomplete + gte: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, type: _FormatObjectType, val=None, gte: _ConvertibleToBool | None = None, extLst: Unused = None + ) -> None: ... + +class RuleType(Serialisable): + cfvo: Incomplete + +class IconSet(RuleType): + tagname: ClassVar[str] + iconSet: NoneSet[_IconSetIconSet] + showValue: Bool[Literal[True]] + percent: Bool[Literal[True]] + reverse: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + cfvo: Incomplete + def __init__( + self, + iconSet: _IconSetIconSet | Literal["none"] | None = None, + showValue: _ConvertibleToBool | None = None, + percent: _ConvertibleToBool | None = None, + reverse: _ConvertibleToBool | None = None, + cfvo=None, + ) -> None: ... + +class DataBar(RuleType): + tagname: ClassVar[str] + minLength: Integer[Literal[True]] + maxLength: Integer[Literal[True]] + showValue: Bool[Literal[True]] + color: ColorDescriptor[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + cfvo: Incomplete + + @overload + def __init__( + self, + minLength: ConvertibleToInt | None = None, + maxLength: ConvertibleToInt | None = None, + showValue: _ConvertibleToBool | None = None, + cfvo=None, + *, + color: str | Color, + ) -> None: ... + @overload + def __init__( + self, + minLength: ConvertibleToInt | None, + maxLength: ConvertibleToInt | None, + showValue: _ConvertibleToBool | None, + cfvo: Incomplete | None, + color: str | Color, + ) -> None: ... + +class ColorScale(RuleType): + tagname: ClassVar[str] + color: Incomplete + __elements__: ClassVar[tuple[str, ...]] + cfvo: Incomplete + def __init__(self, cfvo=None, color=None) -> None: ... + +class Rule(Serialisable): + tagname: ClassVar[str] + type: Set[_RuleType] + dxfId: Integer[Literal[True]] + priority: Integer[Literal[False]] + stopIfTrue: Bool[Literal[True]] + aboveAverage: Bool[Literal[True]] + percent: Bool[Literal[True]] + bottom: Bool[Literal[True]] + operator: NoneSet[_RuleOperator] + text: String[Literal[True]] + timePeriod: NoneSet[_RuleTimePeriod] + rank: Integer[Literal[True]] + stdDev: Integer[Literal[True]] + equalAverage: Bool[Literal[True]] + formula: Incomplete + colorScale: Typed[ColorScale, Literal[True]] + dataBar: Typed[DataBar, Literal[True]] + iconSet: Typed[IconSet, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + dxf: Typed[DifferentialStyle, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + type: _RuleType, + dxfId: ConvertibleToInt | None = None, + priority: ConvertibleToInt = 0, + stopIfTrue: _ConvertibleToBool | None = None, + aboveAverage: _ConvertibleToBool | None = None, + percent: _ConvertibleToBool | None = None, + bottom: _ConvertibleToBool | None = None, + operator: _RuleOperator | Literal["none"] | None = None, + text: str | None = None, + timePeriod: _RuleTimePeriod | Literal["none"] | None = None, + rank: ConvertibleToInt | None = None, + stdDev: ConvertibleToInt | None = None, + equalAverage: _ConvertibleToBool | None = None, + formula=(), + colorScale: ColorScale | None = None, + dataBar: DataBar | None = None, + iconSet: IconSet | None = None, + extLst: Unused = None, + dxf: DifferentialStyle | None = None, + ) -> None: ... + +def ColorScaleRule( + start_type=None, + start_value=None, + start_color=None, + mid_type=None, + mid_value=None, + mid_color=None, + end_type=None, + end_value=None, + end_color=None, +): ... +def FormulaRule(formula=None, stopIfTrue=None, font=None, border=None, fill=None): ... +def CellIsRule(operator=None, formula=None, stopIfTrue=None, font=None, border=None, fill=None): ... +def IconSetRule(icon_style=None, type=None, values=None, showValue=None, percent=None, reverse=None): ... +def DataBarRule( + start_type=None, start_value=None, end_type=None, end_value=None, color=None, showValue=None, minLength=None, maxLength=None +): ... diff --git a/stubs/openpyxl/openpyxl/formula/__init__.pyi b/stubs/openpyxl/openpyxl/formula/__init__.pyi new file mode 100644 index 000000000000..c2decb330c52 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formula/__init__.pyi @@ -0,0 +1 @@ +from .tokenizer import Tokenizer as Tokenizer diff --git a/stubs/openpyxl/openpyxl/formula/tokenizer.pyi b/stubs/openpyxl/openpyxl/formula/tokenizer.pyi new file mode 100644 index 000000000000..f7b2e270b690 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formula/tokenizer.pyi @@ -0,0 +1,62 @@ +from _typeshed import Incomplete +from re import Pattern +from typing import Final, Literal, TypeAlias + +_TokenTypesNotOperand: TypeAlias = Literal[ + "LITERAL", "FUNC", "ARRAY", "PAREN", "SEP", "OPERATOR-PREFIX", "OPERATOR-INFIX", "OPERATOR-POSTFIX", "WHITE-SPACE" +] +_TokenTypes: TypeAlias = Literal["OPERAND", _TokenTypesNotOperand] +_TokenOperandSubtypes: TypeAlias = Literal["TEXT", "NUMBER", "LOGICAL", "ERROR", "RANGE"] +_TokenSubtypes: TypeAlias = Literal["", _TokenOperandSubtypes, "OPEN", "CLOSE", "ARG", "ROW"] + +class TokenizerError(Exception): ... + +class Tokenizer: + SN_RE: Final[Pattern[str]] + WSPACE_RE: Final[Pattern[str]] + STRING_REGEXES: Final[dict[str, Pattern[str]]] + ERROR_CODES: Final[tuple[str, ...]] + TOKEN_ENDERS: Final = ",;}) +-*/^&=><%" + formula: Incomplete + items: Incomplete + token_stack: Incomplete + offset: int + token: Incomplete + def __init__(self, formula) -> None: ... + def check_scientific_notation(self): ... + def assert_empty_token(self, can_follow=()) -> None: ... + def save_token(self) -> None: ... + def render(self): ... + +class Token: + __slots__ = ["value", "type", "subtype"] + LITERAL: Final = "LITERAL" + OPERAND: Final = "OPERAND" + FUNC: Final = "FUNC" + ARRAY: Final = "ARRAY" + PAREN: Final = "PAREN" + SEP: Final = "SEP" + OP_PRE: Final = "OPERATOR-PREFIX" + OP_IN: Final = "OPERATOR-INFIX" + OP_POST: Final = "OPERATOR-POSTFIX" + WSPACE: Final = "WHITE-SPACE" + value: Incomplete + type: _TokenTypes + subtype: _TokenSubtypes + def __init__(self, value, type_: _TokenTypes, subtype: _TokenSubtypes = "") -> None: ... + TEXT: Final = "TEXT" + NUMBER: Final = "NUMBER" + LOGICAL: Final = "LOGICAL" + ERROR: Final = "ERROR" + RANGE: Final = "RANGE" + @classmethod + def make_operand(cls, value): ... + OPEN: Final = "OPEN" + CLOSE: Final = "CLOSE" + @classmethod + def make_subexp(cls, value, func: bool = False): ... + def get_closer(self): ... + ARG: Final = "ARG" + ROW: Final = "ROW" + @classmethod + def make_separator(cls, value): ... diff --git a/stubs/openpyxl/openpyxl/formula/translate.pyi b/stubs/openpyxl/openpyxl/formula/translate.pyi new file mode 100644 index 000000000000..212f0bedd006 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formula/translate.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from re import Pattern +from typing import Final + +class TranslatorError(Exception): ... + +class Translator: + tokenizer: Incomplete + def __init__(self, formula, origin) -> None: ... + def get_tokens(self): ... + ROW_RANGE_RE: Final[Pattern[str]] + COL_RANGE_RE: Final[Pattern[str]] + CELL_REF_RE: Final[Pattern[str]] + @staticmethod + def translate_row(row_str, rdelta): ... + @staticmethod + def translate_col(col_str, cdelta): ... + @staticmethod + def strip_ws_name(range_str): ... + @classmethod + def translate_range(cls, range_str, rdelta, cdelta): ... + def translate_formula(self, dest=None, row_delta: int = 0, col_delta: int = 0): ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/provision.pyi b/stubs/openpyxl/openpyxl/packaging/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/dialects/postgresql/provision.pyi rename to stubs/openpyxl/openpyxl/packaging/__init__.pyi diff --git a/stubs/openpyxl/openpyxl/packaging/core.pyi b/stubs/openpyxl/openpyxl/packaging/core.pyi new file mode 100644 index 000000000000..d42e5a6adc5f --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/core.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete +from datetime import datetime +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors import DateTime +from openpyxl.descriptors.base import Alias +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +# Does not reimplement the relevant methods, so runtime also has incompatible supertypes +class NestedDateTime(DateTime[Incomplete], NestedText[Incomplete, Incomplete]): # type: ignore[misc] + expected_type: type[Incomplete] + + @overload # type: ignore[override] + def to_tree(self, tagname: str | None = None, value: None = None, namespace: str | None = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: datetime, namespace: str | None = None) -> Element: ... + +class QualifiedDateTime(NestedDateTime): + # value cannot be None or it'll raise + def to_tree(self, tagname: str, value: datetime, namespace: str | None = None) -> Element: ... # type: ignore[override] + +class DocumentProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + category: NestedText[str, Literal[True]] + contentStatus: NestedText[str, Literal[True]] + keywords: NestedText[str, Literal[True]] + lastModifiedBy: NestedText[str, Literal[True]] + lastPrinted: Incomplete + revision: NestedText[str, Literal[True]] + version: NestedText[str, Literal[True]] + last_modified_by: Alias + subject: NestedText[str, Literal[True]] + title: NestedText[str, Literal[True]] + creator: NestedText[str, Literal[True]] + description: NestedText[str, Literal[True]] + identifier: NestedText[str, Literal[True]] + language: NestedText[str, Literal[True]] + created: Incomplete + modified: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + category: object = None, + contentStatus: object = None, + keywords: object = None, + lastModifiedBy: object = None, + lastPrinted=None, + revision: object = None, + version: object = None, + created=None, + creator: object = "openpyxl", + description: object = None, + identifier: object = None, + language: object = None, + modified=None, + subject: object = None, + title: object = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/packaging/custom.pyi b/stubs/openpyxl/openpyxl/packaging/custom.pyi new file mode 100644 index 000000000000..8721ae124986 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/custom.pyi @@ -0,0 +1,66 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from collections.abc import Iterator +from datetime import datetime +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar +from typing_extensions import Self + +from openpyxl.descriptors import Sequence, Strict +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element + +_T = TypeVar("_T") + +# Does not reimplement anything, so runtime also has incompatible supertypes +class NestedBoolText(Bool[Incomplete], NestedText[Incomplete, Incomplete]): ... # type: ignore[misc] + +class _TypedProperty(Strict, Generic[_T]): + name: String[Literal[False]] + # Since this is internal, just list all possible values + value: ( + Integer[Literal[False]] + | Float[Literal[False]] + | String[Literal[True]] + | DateTime[Literal[False]] + | Bool[Literal[False]] + | String[Literal[False]] + ) + def __init__(self, name: str, value: _T) -> None: ... + def __eq__(self, other: _TypedProperty[Any]) -> bool: ... # type: ignore[override] + +class IntProperty(_TypedProperty[ConvertibleToInt]): + value: Integer[Literal[False]] + +class FloatProperty(_TypedProperty[ConvertibleToFloat]): + value: Float[Literal[False]] + +class StringProperty(_TypedProperty[str | None]): + value: String[Literal[True]] + +class DateTimeProperty(_TypedProperty[datetime]): + value: DateTime[Literal[False]] + +class BoolProperty(_TypedProperty[_ConvertibleToBool]): + value: Bool[Literal[False]] + +class LinkProperty(_TypedProperty[str]): + value: String[Literal[False]] + +_MappingPropertyType: TypeAlias = StringProperty | IntProperty | FloatProperty | DateTimeProperty | BoolProperty | LinkProperty +CLASS_MAPPING: Final[dict[type[_MappingPropertyType], str]] +XML_MAPPING: Final[dict[str, type[_MappingPropertyType]]] + +class CustomPropertyList(Strict, Generic[_T]): + props: Sequence[list[_TypedProperty[_T]]] + def __init__(self) -> None: ... + @classmethod + def from_tree(cls, tree: _ChildSerialisableTreeElement) -> Self: ... + def append(self, prop) -> None: ... + def to_tree(self) -> Element: ... + def __len__(self) -> int: ... + @property + def names(self) -> list[str]: ... + def __getitem__(self, name): ... + def __delitem__(self, name) -> None: ... + def __iter__(self) -> Iterator[_TypedProperty[_T]]: ... diff --git a/stubs/openpyxl/openpyxl/packaging/extended.pyi b/stubs/openpyxl/openpyxl/packaging/extended.pyi new file mode 100644 index 000000000000..5f8d7fd051a5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/extended.pyi @@ -0,0 +1,81 @@ +from _typeshed import ConvertibleToInt, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +class DigSigBlob(Serialisable): + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + +class VectorLpstr(Serialisable): + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + +class VectorVariant(Serialisable): + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + +class ExtendedProperties(Serialisable): + tagname: ClassVar[str] + Template: NestedText[str, Literal[True]] + Manager: NestedText[str, Literal[True]] + Company: NestedText[str, Literal[True]] + Pages: NestedText[int, Literal[True]] + Words: NestedText[int, Literal[True]] + Characters: NestedText[int, Literal[True]] + PresentationFormat: NestedText[str, Literal[True]] + Lines: NestedText[int, Literal[True]] + Paragraphs: NestedText[int, Literal[True]] + Slides: NestedText[int, Literal[True]] + Notes: NestedText[int, Literal[True]] + TotalTime: NestedText[int, Literal[True]] + HiddenSlides: NestedText[int, Literal[True]] + MMClips: NestedText[int, Literal[True]] + ScaleCrop: NestedText[str, Literal[True]] + HeadingPairs: Typed[VectorVariant, Literal[True]] + TitlesOfParts: Typed[VectorLpstr, Literal[True]] + LinksUpToDate: NestedText[str, Literal[True]] + CharactersWithSpaces: NestedText[int, Literal[True]] + SharedDoc: NestedText[str, Literal[True]] + HyperlinkBase: NestedText[str, Literal[True]] + HLinks: Typed[VectorVariant, Literal[True]] + HyperlinksChanged: NestedText[str, Literal[True]] + DigSig: Typed[DigSigBlob, Literal[True]] + Application: NestedText[str, Literal[True]] + AppVersion: NestedText[str, Literal[True]] + DocSecurity: NestedText[int, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + Template: object = None, + Manager: object = None, + Company: object = None, + Pages: ConvertibleToInt | None = None, + Words: ConvertibleToInt | None = None, + Characters: ConvertibleToInt | None = None, + PresentationFormat: object = None, + Lines: ConvertibleToInt | None = None, + Paragraphs: ConvertibleToInt | None = None, + Slides: ConvertibleToInt | None = None, + Notes: ConvertibleToInt | None = None, + TotalTime: ConvertibleToInt | None = None, + HiddenSlides: ConvertibleToInt | None = None, + MMClips: ConvertibleToInt | None = None, + ScaleCrop: object = None, + HeadingPairs: Unused = None, + TitlesOfParts: Unused = None, + LinksUpToDate: object = None, + CharactersWithSpaces: ConvertibleToInt | None = None, + SharedDoc: object = None, + HyperlinkBase: object = None, + HLinks: Unused = None, + HyperlinksChanged: object = None, + DigSig: Unused = None, + Application: Unused = None, + AppVersion: str | None = None, + DocSecurity: ConvertibleToInt | None = None, + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/packaging/interface.pyi b/stubs/openpyxl/openpyxl/packaging/interface.pyi new file mode 100644 index 000000000000..45a7da1114ea --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/interface.pyi @@ -0,0 +1,8 @@ +from abc import ABC, abstractmethod + +# This interface is unused. Nothing implements `id` as property either. +# IDs can be ints, strings, None, or a Descriptor returning those throughout the codebase. +class ISerialisableFile(ABC): + @property + @abstractmethod + def id(self) -> str | int | None: ... diff --git a/stubs/openpyxl/openpyxl/packaging/manifest.pyi b/stubs/openpyxl/openpyxl/packaging/manifest.pyi new file mode 100644 index 000000000000..9700c10e2871 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/manifest.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import ClassVar, Final, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +mimetypes: Incomplete + +class FileExtension(Serialisable): + tagname: ClassVar[str] + Extension: String[Literal[False]] + ContentType: String[Literal[False]] + def __init__(self, Extension: str, ContentType: str) -> None: ... + +class Override(Serialisable): + tagname: ClassVar[str] + PartName: String[Literal[False]] + ContentType: String[Literal[False]] + def __init__(self, PartName: str, ContentType: str) -> None: ... + +DEFAULT_TYPES: Final[list[FileExtension]] +DEFAULT_OVERRIDE: Final[list[Override]] + +class Manifest(Serialisable): + tagname: ClassVar[str] + Default: Incomplete + Override: Incomplete + path: str + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, Default=(), Override=()) -> None: ... + @property + def filenames(self) -> list[str]: ... + @property + def extensions(self) -> list[tuple[str, str]]: ... + def to_tree(self) -> Element: ... # type: ignore[override] + def __contains__(self, content_type: str) -> bool: ... + def find(self, content_type): ... + def findall(self, content_type) -> Generator[Incomplete]: ... + def append(self, obj) -> None: ... diff --git a/stubs/openpyxl/openpyxl/packaging/relationship.pyi b/stubs/openpyxl/openpyxl/packaging/relationship.pyi new file mode 100644 index 000000000000..ca6bbb0b97f5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/relationship.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator +from typing import ClassVar, Literal, TypeVar, overload +from zipfile import ZipFile + +from openpyxl.descriptors.base import Alias, String +from openpyxl.descriptors.container import ElementList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.pivot.cache import CacheDefinition +from openpyxl.pivot.record import RecordList +from openpyxl.pivot.table import TableDefinition + +_SerialisableT = TypeVar("_SerialisableT", bound=Serialisable) +_SerialisableRelTypeT = TypeVar("_SerialisableRelTypeT", bound=CacheDefinition | RecordList | TableDefinition) + +class Relationship(Serialisable): + tagname: ClassVar[str] + Type: String[Literal[False]] + Target: String[Literal[False]] + target: Alias + TargetMode: String[Literal[True]] + Id: String[Literal[True]] + id: Alias + + @overload + def __init__( + self, Id: str, Type: Unused = None, *, type: str, Target: str | None = None, TargetMode: str | None = None + ) -> None: ... + @overload + def __init__(self, Id: str, Type: Unused, type: str, Target: str | None = None, TargetMode: str | None = None) -> None: ... + @overload + def __init__( + self, Id: str, Type: str, type: None = None, Target: str | None = None, TargetMode: str | None = None + ) -> None: ... + +class RelationshipList(ElementList[Relationship]): + expected_type: type[Relationship] + def find(self, content_type: str) -> Generator[Relationship]: ... + def get(self, key: str) -> Relationship: ... + def to_dict(self) -> dict[Incomplete, Relationship]: ... + +def get_rels_path(path): ... +def get_dependents(archive: ZipFile, filename: str) -> RelationshipList: ... + +# If `id` is None, `cls` needs to have ClassVar `rel_type`. +# The `deps` attribute used at runtime is for internal use immediately after the return. +# `cls` cannot be None +@overload +def get_rel( + archive: ZipFile, deps: RelationshipList, id: None = None, *, cls: type[_SerialisableRelTypeT] +) -> _SerialisableRelTypeT | None: ... +@overload +def get_rel( + archive: ZipFile, deps: RelationshipList, id: None, cls: type[_SerialisableRelTypeT] +) -> _SerialisableRelTypeT | None: ... +@overload +def get_rel(archive: ZipFile, deps: RelationshipList, id: str, cls: type[_SerialisableT]) -> _SerialisableT: ... diff --git a/stubs/openpyxl/openpyxl/packaging/workbook.pyi b/stubs/openpyxl/openpyxl/packaging/workbook.pyi new file mode 100644 index 000000000000..5eeb46b36fea --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/workbook.pyi @@ -0,0 +1,100 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl import _VisibilityType +from openpyxl.descriptors.base import Alias, Bool, Integer, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedString +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.workbook.defined_name import DefinedNameList +from openpyxl.workbook.function_group import FunctionGroupList +from openpyxl.workbook.properties import CalcProperties, FileVersion, WorkbookProperties +from openpyxl.workbook.protection import FileSharing, WorkbookProtection +from openpyxl.workbook.smart_tags import SmartTagList, SmartTagProperties +from openpyxl.workbook.web import WebPublishing, WebPublishObjectList +from openpyxl.xml.functions import Element + +_WorkbookPackageConformance: TypeAlias = Literal["strict", "transitional"] + +class FileRecoveryProperties(Serialisable): + tagname: ClassVar[str] + autoRecover: Bool[Literal[True]] + crashSave: Bool[Literal[True]] + dataExtractLoad: Bool[Literal[True]] + repairLoad: Bool[Literal[True]] + def __init__( + self, + autoRecover: _ConvertibleToBool | None = None, + crashSave: _ConvertibleToBool | None = None, + dataExtractLoad: _ConvertibleToBool | None = None, + repairLoad: _ConvertibleToBool | None = None, + ) -> None: ... + +class ChildSheet(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + sheetId: Integer[Literal[False]] + state: NoneSet[_VisibilityType] + id: Incomplete + def __init__( + self, name: str, sheetId: ConvertibleToInt, state: _VisibilityType | Literal["none"] | None = "visible", id=None + ) -> None: ... + +class PivotCache(Serialisable): + tagname: ClassVar[str] + cacheId: Integer[Literal[False]] + id: Incomplete + def __init__(self, cacheId: ConvertibleToInt, id=None) -> None: ... + +class WorkbookPackage(Serialisable): + tagname: ClassVar[str] + conformance: NoneSet[_WorkbookPackageConformance] + fileVersion: Typed[FileVersion, Literal[True]] + fileSharing: Typed[FileSharing, Literal[True]] + workbookPr: Typed[WorkbookProperties, Literal[True]] + properties: Alias + workbookProtection: Typed[WorkbookProtection, Literal[True]] + bookViews: Incomplete + sheets: Incomplete # NestedSequence[ChildSheet] + functionGroups: Typed[FunctionGroupList, Literal[True]] + externalReferences: Incomplete + definedNames: Typed[DefinedNameList, Literal[True]] + calcPr: Typed[CalcProperties, Literal[True]] + oleSize: NestedString[Literal[True]] + customWorkbookViews: Incomplete + pivotCaches: Incomplete + smartTagPr: Typed[SmartTagProperties, Literal[True]] + smartTagTypes: Typed[SmartTagList, Literal[True]] + webPublishing: Typed[WebPublishing, Literal[True]] + fileRecoveryPr: Typed[FileRecoveryProperties, Literal[True]] + webPublishObjects: Typed[WebPublishObjectList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + Ignorable: NestedString[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + conformance: _WorkbookPackageConformance | Literal["none"] | None = None, + fileVersion: FileVersion | None = None, + fileSharing: FileSharing | None = None, + workbookPr: WorkbookProperties | None = None, + workbookProtection: WorkbookProtection | None = None, + bookViews=(), + sheets=(), + functionGroups: FunctionGroupList | None = None, + externalReferences=(), + definedNames: DefinedNameList | None = None, + calcPr: CalcProperties | None = None, + oleSize: object = None, + customWorkbookViews=(), + pivotCaches=(), + smartTagPr: SmartTagProperties | None = None, + smartTagTypes: SmartTagList | None = None, + webPublishing: WebPublishing | None = None, + fileRecoveryPr: FileRecoveryProperties | None = None, + webPublishObjects: WebPublishObjectList | None = None, + extLst: Unused = None, + Ignorable: Unused = None, + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def active(self) -> int: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/provision.pyi b/stubs/openpyxl/openpyxl/pivot/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/dialects/sqlite/provision.pyi rename to stubs/openpyxl/openpyxl/pivot/__init__.pyi diff --git a/stubs/openpyxl/openpyxl/pivot/cache.pyi b/stubs/openpyxl/openpyxl/pivot/cache.pyi new file mode 100644 index 000000000000..e2fc7b3f73dc --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/cache.pyi @@ -0,0 +1,649 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from datetime import datetime +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedInteger +from openpyxl.descriptors.sequence import NestedSequence +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.pivot.fields import Error, Missing, Number, Text, TupleList +from openpyxl.pivot.table import PivotArea +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +_RangePrGroupBy: TypeAlias = Literal["range", "seconds", "minutes", "hours", "days", "months", "quarters", "years"] +_CacheSourceType: TypeAlias = Literal["worksheet", "external", "consolidation", "scenario"] + +class MeasureDimensionMap(Serialisable): + tagname: ClassVar[str] + measureGroup: Integer[Literal[True]] + dimension: Integer[Literal[True]] + def __init__(self, measureGroup: ConvertibleToInt | None = None, dimension: ConvertibleToInt | None = None) -> None: ... + +class MeasureGroup(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + caption: String[Literal[False]] + def __init__(self, name: str, caption: str) -> None: ... + +class PivotDimension(Serialisable): + tagname: ClassVar[str] + measure: Bool[Literal[False]] + name: String[Literal[False]] + uniqueName: String[Literal[False]] + caption: String[Literal[False]] + + @overload + def __init__(self, measure: _ConvertibleToBool = None, *, name: str, uniqueName: str, caption: str) -> None: ... + @overload + def __init__(self, measure: _ConvertibleToBool, name: str, uniqueName: str, caption: str) -> None: ... + +class CalculatedMember(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + mdx: String[Literal[False]] + memberName: String[Literal[True]] + hierarchy: String[Literal[True]] + parent: String[Literal[True]] + solveOrder: Integer[Literal[True]] + set: Bool[Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + mdx: str, + memberName: str, + hierarchy: str, + parent: str, + solveOrder: ConvertibleToInt, + set: _ConvertibleToBool = None, + extLst: Unused = None, + ) -> None: ... + +class CalculatedItem(Serialisable): + tagname: ClassVar[str] + field: Integer[Literal[True]] + formula: String[Literal[False]] + pivotArea: Typed[PivotArea, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__(self, field: ConvertibleToInt | None = None, *, formula: str, pivotArea: PivotArea, extLst=None) -> None: ... + @overload + def __init__(self, field: ConvertibleToInt | None, formula: str, pivotArea: PivotArea, extLst=None) -> None: ... + +class ServerFormat(Serialisable): + tagname: ClassVar[str] + culture: String[Literal[True]] + format: String[Literal[True]] + def __init__(self, culture: str | None = None, format: str | None = None) -> None: ... + +class Query(Serialisable): + tagname: ClassVar[str] + mdx: String[Literal[False]] + tpls: Typed[TupleList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, mdx: str, tpls: TupleList | None = None) -> None: ... + +class OLAPSet(Serialisable): + tagname: ClassVar[str] + count: Integer[Literal[False]] + maxRank: Integer[Literal[False]] + setDefinition: String[Literal[False]] + sortType: Incomplete + queryFailed: Bool[Literal[False]] + tpls: Typed[TupleList, Literal[True]] + sortByTuple: Typed[TupleList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + count: ConvertibleToInt, + maxRank: ConvertibleToInt, + setDefinition: str, + sortType=None, + queryFailed: _ConvertibleToBool = None, + tpls: TupleList | None = None, + sortByTuple: TupleList | None = None, + ) -> None: ... + +class PCDSDTCEntries(Serialisable): + tagname: ClassVar[str] + count: Integer[Literal[True]] + m: Typed[Missing, Literal[True]] + n: Typed[Number, Literal[True]] + e: Typed[Error, Literal[True]] + s: Typed[Text, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: ConvertibleToInt, m: Missing, n: Number, e: Error, s: Text) -> None: ... + +class TupleCache(Serialisable): + tagname: ClassVar[str] + entries: Typed[PCDSDTCEntries, Literal[True]] + sets: NestedSequence[list[OLAPSet]] + queryCache: NestedSequence[list[Query]] + serverFormats: NestedSequence[list[ServerFormat]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + entries: PCDSDTCEntries | None = None, + sets: list[OLAPSet] | tuple[OLAPSet, ...] = (), + queryCache: list[Query] | tuple[Query, ...] = (), + serverFormats: list[ServerFormat] | tuple[ServerFormat, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + +class OLAPKPI(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + caption: String[Literal[True]] + displayFolder: String[Literal[True]] + measureGroup: String[Literal[True]] + parent: String[Literal[True]] + value: String[Literal[False]] + goal: String[Literal[True]] + status: String[Literal[True]] + trend: String[Literal[True]] + weight: String[Literal[True]] + time: String[Literal[True]] + def __init__( + self, + uniqueName: str | None = None, + caption: str | None = None, + displayFolder: str | None = None, + measureGroup: str | None = None, + parent: str | None = None, + value: str | None = None, + goal: str | None = None, + status: str | None = None, + trend: str | None = None, + weight: str | None = None, + time: str | None = None, + ) -> None: ... + +class GroupMember(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + group: Bool[Literal[False]] + def __init__(self, uniqueName: str, group: _ConvertibleToBool = None) -> None: ... + +class LevelGroup(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + uniqueName: String[Literal[False]] + caption: String[Literal[False]] + uniqueParent: String[Literal[False]] + id: Integer[Literal[False]] + groupMembers: NestedSequence[list[GroupMember]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + uniqueName: str, + caption: str, + uniqueParent: str, + id: ConvertibleToInt, + groupMembers: list[GroupMember] | tuple[GroupMember, ...] = (), + ) -> None: ... + +class GroupLevel(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + caption: String[Literal[False]] + user: Bool[Literal[False]] + customRollUp: Bool[Literal[False]] + groups: NestedSequence[list[LevelGroup]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + uniqueName: str, + caption: str, + user: _ConvertibleToBool = None, + customRollUp: _ConvertibleToBool = None, + groups: list[LevelGroup] | tuple[LevelGroup, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + +class FieldUsage(Serialisable): + tagname: ClassVar[str] + x: Integer[Literal[False]] + def __init__(self, x: ConvertibleToInt) -> None: ... + +class CacheHierarchy(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + caption: String[Literal[True]] + measure: Bool[Literal[False]] + set: Bool[Literal[False]] + parentSet: Integer[Literal[True]] + iconSet: Integer[Literal[False]] + attribute: Bool[Literal[False]] + time: Bool[Literal[False]] + keyAttribute: Bool[Literal[False]] + defaultMemberUniqueName: String[Literal[True]] + allUniqueName: String[Literal[True]] + allCaption: String[Literal[True]] + dimensionUniqueName: String[Literal[True]] + displayFolder: String[Literal[True]] + measureGroup: String[Literal[True]] + measures: Bool[Literal[False]] + count: Integer[Literal[False]] + oneField: Bool[Literal[False]] + memberValueDatatype: Integer[Literal[True]] + unbalanced: Bool[Literal[True]] + unbalancedGroup: Bool[Literal[True]] + hidden: Bool[Literal[False]] + fieldsUsage: NestedSequence[list[FieldUsage]] + groupLevels: NestedSequence[list[GroupLevel]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + uniqueName: str = "", + caption: str | None = None, + measure: _ConvertibleToBool = None, + set: _ConvertibleToBool = None, + parentSet: ConvertibleToInt | None = None, + iconSet: ConvertibleToInt = 0, + attribute: _ConvertibleToBool = None, + time: _ConvertibleToBool = None, + keyAttribute: _ConvertibleToBool = None, + defaultMemberUniqueName: str | None = None, + allUniqueName: str | None = None, + allCaption: str | None = None, + dimensionUniqueName: str | None = None, + displayFolder: str | None = None, + measureGroup: str | None = None, + measures: _ConvertibleToBool = None, + *, + count: ConvertibleToInt, + oneField: _ConvertibleToBool = None, + memberValueDatatype: ConvertibleToInt | None = None, + unbalanced: _ConvertibleToBool | None = None, + unbalancedGroup: _ConvertibleToBool | None = None, + hidden: _ConvertibleToBool = None, + fieldsUsage: list[FieldUsage] | tuple[FieldUsage, ...] = (), + groupLevels: list[FieldUsage] | tuple[FieldUsage, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + uniqueName: str, + caption: str | None, + measure: _ConvertibleToBool, + set: _ConvertibleToBool, + parentSet: ConvertibleToInt | None, + iconSet: ConvertibleToInt, + attribute: _ConvertibleToBool, + time: _ConvertibleToBool, + keyAttribute: _ConvertibleToBool, + defaultMemberUniqueName: str | None, + allUniqueName: str | None, + allCaption: str | None, + dimensionUniqueName: str | None, + displayFolder: str | None, + measureGroup: str | None, + measures: _ConvertibleToBool, + count: ConvertibleToInt, + oneField: _ConvertibleToBool = None, + memberValueDatatype: ConvertibleToInt | None = None, + unbalanced: _ConvertibleToBool | None = None, + unbalancedGroup: _ConvertibleToBool | None = None, + hidden: _ConvertibleToBool = None, + fieldsUsage: list[FieldUsage] | tuple[FieldUsage, ...] = (), + groupLevels: list[FieldUsage] | tuple[FieldUsage, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + +class GroupItems(Serialisable): + tagname: ClassVar[str] + m: Incomplete + n: Incomplete + b: Incomplete + e: Incomplete + s: Incomplete + d: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, m=(), n=(), b=(), e=(), s=(), d=()) -> None: ... + @property + def count(self) -> int: ... + +class RangePr(Serialisable): + tagname: ClassVar[str] + autoStart: Bool[Literal[True]] + autoEnd: Bool[Literal[True]] + groupBy: NoneSet[_RangePrGroupBy] + startNum: Float[Literal[True]] + endNum: Float[Literal[True]] + startDate: DateTime[Literal[True]] + endDate: DateTime[Literal[True]] + groupInterval: Float[Literal[True]] + def __init__( + self, + autoStart: _ConvertibleToBool | None = True, + autoEnd: _ConvertibleToBool | None = True, + groupBy: _RangePrGroupBy = "range", + startNum: ConvertibleToFloat | None = None, + endNum: ConvertibleToFloat | None = None, + startDate: datetime | str | None = None, + endDate: datetime | str | None = None, + groupInterval: ConvertibleToFloat | None = 1, + ) -> None: ... + +class FieldGroup(Serialisable): + tagname: ClassVar[str] + par: Integer[Literal[True]] + base: Integer[Literal[True]] + rangePr: Typed[RangePr, Literal[True]] + discretePr: NestedSequence[list[NestedInteger[Literal[False]]]] + groupItems: Typed[GroupItems, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + par: ConvertibleToInt | None = None, + base: ConvertibleToInt | None = None, + rangePr: RangePr | None = None, + discretePr: list[NestedInteger[Literal[False]]] | tuple[NestedInteger[Literal[False]], ...] = (), + groupItems: GroupItems | None = None, + ) -> None: ... + +class SharedItems(Serialisable): + tagname: ClassVar[str] + m: Incomplete + n: Incomplete + b: Incomplete + e: Incomplete + s: Incomplete + d: Incomplete + containsSemiMixedTypes: Bool[Literal[True]] + containsNonDate: Bool[Literal[True]] + containsDate: Bool[Literal[True]] + containsString: Bool[Literal[True]] + containsBlank: Bool[Literal[True]] + containsMixedTypes: Bool[Literal[True]] + containsNumber: Bool[Literal[True]] + containsInteger: Bool[Literal[True]] + minValue: Float[Literal[True]] + maxValue: Float[Literal[True]] + minDate: DateTime[Literal[True]] + maxDate: DateTime[Literal[True]] + longText: Bool[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + _fields=(), + containsSemiMixedTypes: _ConvertibleToBool | None = None, + containsNonDate: _ConvertibleToBool | None = None, + containsDate: _ConvertibleToBool | None = None, + containsString: _ConvertibleToBool | None = None, + containsBlank: _ConvertibleToBool | None = None, + containsMixedTypes: _ConvertibleToBool | None = None, + containsNumber: _ConvertibleToBool | None = None, + containsInteger: _ConvertibleToBool | None = None, + minValue: ConvertibleToFloat | None = None, + maxValue: ConvertibleToFloat | None = None, + minDate: datetime | str | None = None, + maxDate: datetime | str | None = None, + count: Unused = None, + longText: _ConvertibleToBool | None = None, + ) -> None: ... + @property + def count(self) -> int: ... + +class CacheField(Serialisable): + tagname: ClassVar[str] + sharedItems: Typed[SharedItems, Literal[True]] + fieldGroup: Typed[FieldGroup, Literal[True]] + mpMap: NestedInteger[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + name: String[Literal[False]] + caption: String[Literal[True]] + propertyName: String[Literal[True]] + serverField: Bool[Literal[True]] + uniqueList: Bool[Literal[True]] + numFmtId: Integer[Literal[True]] + formula: String[Literal[True]] + sqlType: Integer[Literal[True]] + hierarchy: Integer[Literal[True]] + level: Integer[Literal[True]] + databaseField: Bool[Literal[True]] + mappingCount: Integer[Literal[True]] + memberPropertyField: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + sharedItems: SharedItems | None = None, + fieldGroup: FieldGroup | None = None, + mpMap: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: ExtensionList | None = None, + *, + name: str, + caption: str | None = None, + propertyName: str | None = None, + serverField: _ConvertibleToBool | None = None, + uniqueList: _ConvertibleToBool | None = True, + numFmtId: ConvertibleToInt | None = None, + formula: str | None = None, + sqlType: ConvertibleToInt | None = 0, + hierarchy: ConvertibleToInt | None = 0, + level: ConvertibleToInt | None = 0, + databaseField: _ConvertibleToBool | None = True, + mappingCount: ConvertibleToInt | None = None, + memberPropertyField: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + sharedItems: SharedItems | None, + fieldGroup: FieldGroup | None, + mpMap: Incomplete | None, + extLst: ExtensionList | None, + name: str, + caption: str | None = None, + propertyName: str | None = None, + serverField: _ConvertibleToBool | None = None, + uniqueList: _ConvertibleToBool | None = True, + numFmtId: ConvertibleToInt | None = None, + formula: str | None = None, + sqlType: ConvertibleToInt | None = 0, + hierarchy: ConvertibleToInt | None = 0, + level: ConvertibleToInt | None = 0, + databaseField: _ConvertibleToBool | None = True, + mappingCount: ConvertibleToInt | None = None, + memberPropertyField: _ConvertibleToBool | None = None, + ) -> None: ... + +class RangeSet(Serialisable): + tagname: ClassVar[str] + i1: Integer[Literal[True]] + i2: Integer[Literal[True]] + i3: Integer[Literal[True]] + i4: Integer[Literal[True]] + ref: String[Literal[False]] + name: String[Literal[True]] + sheet: String[Literal[True]] + + @overload + def __init__( + self, + i1: ConvertibleToInt | None = None, + i2: ConvertibleToInt | None = None, + i3: ConvertibleToInt | None = None, + i4: ConvertibleToInt | None = None, + *, + ref: str, + name: str | None = None, + sheet: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + i1: ConvertibleToInt | None, + i2: ConvertibleToInt | None, + i3: ConvertibleToInt | None, + i4: ConvertibleToInt | None, + ref: str, + name: str | None = None, + sheet: str | None = None, + ) -> None: ... + +class PageItem(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + def __init__(self, name: str) -> None: ... + +class Consolidation(Serialisable): + tagname: ClassVar[str] + autoPage: Bool[Literal[True]] + pages: NestedSequence[list[PageItem]] + rangeSets: NestedSequence[list[RangeSet]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + autoPage: _ConvertibleToBool | None = None, + pages: list[PageItem] | tuple[PageItem, ...] = (), + rangeSets: list[RangeSet] | tuple[RangeSet, ...] = (), + ) -> None: ... + +class WorksheetSource(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[True]] + name: String[Literal[True]] + sheet: String[Literal[True]] + def __init__(self, ref: str | None = None, name: str | None = None, sheet: str | None = None) -> None: ... + +class CacheSource(Serialisable): + tagname: ClassVar[str] + type: Set[_CacheSourceType] + connectionId: Integer[Literal[True]] + worksheetSource: Typed[WorksheetSource, Literal[True]] + consolidation: Typed[Consolidation, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + type: _CacheSourceType, + connectionId: ConvertibleToInt | None = None, + worksheetSource: WorksheetSource | None = None, + consolidation: Consolidation | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class CacheDefinition(Serialisable): + mime_type: str + rel_type: str + records: Incomplete + tagname: ClassVar[str] + invalid: Bool[Literal[True]] + saveData: Bool[Literal[True]] + refreshOnLoad: Bool[Literal[True]] + optimizeMemory: Bool[Literal[True]] + enableRefresh: Bool[Literal[True]] + refreshedBy: String[Literal[True]] + refreshedDate: Float[Literal[True]] + refreshedDateIso: DateTime[Literal[True]] + backgroundQuery: Bool[Literal[True]] + missingItemsLimit: Integer[Literal[True]] + createdVersion: Integer[Literal[True]] + refreshedVersion: Integer[Literal[True]] + minRefreshableVersion: Integer[Literal[True]] + recordCount: Integer[Literal[True]] + upgradeOnRefresh: Bool[Literal[True]] + supportSubquery: Bool[Literal[True]] + supportAdvancedDrill: Bool[Literal[True]] + cacheSource: Typed[CacheSource, Literal[True]] + cacheFields: Incomplete + cacheHierarchies: Incomplete + kpis: NestedSequence[list[OLAPKPI]] + tupleCache: Typed[TupleCache, Literal[True]] + calculatedItems: Incomplete + calculatedMembers: Incomplete + dimensions: Incomplete + measureGroups: Incomplete + maps: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + invalid: _ConvertibleToBool | None = None, + saveData: _ConvertibleToBool | None = None, + refreshOnLoad: _ConvertibleToBool | None = None, + optimizeMemory: _ConvertibleToBool | None = None, + enableRefresh: _ConvertibleToBool | None = None, + refreshedBy: str | None = None, + refreshedDate: ConvertibleToFloat | None = None, + refreshedDateIso: datetime | str | None = None, + backgroundQuery: _ConvertibleToBool | None = None, + missingItemsLimit: ConvertibleToInt | None = None, + createdVersion: ConvertibleToInt | None = None, + refreshedVersion: ConvertibleToInt | None = None, + minRefreshableVersion: ConvertibleToInt | None = None, + recordCount: ConvertibleToInt | None = None, + upgradeOnRefresh: _ConvertibleToBool | None = None, + tupleCache: TupleCache | None = None, + supportSubquery: _ConvertibleToBool | None = None, + supportAdvancedDrill: _ConvertibleToBool | None = None, + *, + cacheSource: CacheSource, + cacheFields=(), + cacheHierarchies=(), + kpis: list[OLAPKPI] | tuple[OLAPKPI, ...] = (), + calculatedItems=(), + calculatedMembers=(), + dimensions=(), + measureGroups=(), + maps=(), + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + @overload + def __init__( + self, + invalid: _ConvertibleToBool | None, + saveData: _ConvertibleToBool | None, + refreshOnLoad: _ConvertibleToBool | None, + optimizeMemory: _ConvertibleToBool | None, + enableRefresh: _ConvertibleToBool | None, + refreshedBy: str | None, + refreshedDate: ConvertibleToFloat | None, + refreshedDateIso: datetime | str | None, + backgroundQuery: _ConvertibleToBool | None, + missingItemsLimit: ConvertibleToInt | None, + createdVersion: ConvertibleToInt | None, + refreshedVersion: ConvertibleToInt | None, + minRefreshableVersion: ConvertibleToInt | None, + recordCount: ConvertibleToInt | None, + upgradeOnRefresh: _ConvertibleToBool | None, + tupleCache: TupleCache | None, + supportSubquery: _ConvertibleToBool | None, + supportAdvancedDrill: _ConvertibleToBool | None, + cacheSource: CacheSource, + cacheFields=(), + cacheHierarchies=(), + kpis=(), + calculatedItems=(), + calculatedMembers=(), + dimensions=(), + measureGroups=(), + maps=(), + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/pivot/fields.pyi b/stubs/openpyxl/openpyxl/pivot/fields.pyi new file mode 100644 index 000000000000..e2892e328bac --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/fields.pyi @@ -0,0 +1,245 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from datetime import datetime +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Index(Serialisable): + tagname: ClassVar[str] + v: Integer[Literal[True]] + def __init__(self, v: ConvertibleToInt | None = 0) -> None: ... + +class Tuple(Serialisable): + fld: Integer[Literal[True]] + hier: Integer[Literal[True]] + item: Integer[Literal[False]] + def __init__(self, fld: ConvertibleToInt, hier: ConvertibleToInt, item: ConvertibleToInt) -> None: ... + +class TupleList(Serialisable): + c: Integer[Literal[True]] + tpl: Typed[Tuple, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__(self, c: ConvertibleToInt | None = None, *, tpl: Tuple) -> None: ... + @overload + def __init__(self, c: ConvertibleToInt | None, tpl: Tuple) -> None: ... + +class Missing(Serialisable): + tagname: ClassVar[str] + tpls: Incomplete + x: Incomplete + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tpls=(), + x=(), + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class Number(Serialisable): + tagname: ClassVar[str] + tpls: Incomplete + x: Incomplete + v: Float[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + tpls=(), + x=(), + *, + v: ConvertibleToFloat, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + tpls, + x, + v: ConvertibleToFloat, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class Error(Serialisable): + tagname: ClassVar[str] + tpls: Typed[TupleList, Literal[True]] + x: Incomplete + v: String[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + tpls: TupleList | None = None, + x=(), + *, + v: str, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + tpls: TupleList | None, + x, + v: str, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class Boolean(Serialisable): + tagname: ClassVar[str] + x: Incomplete + v: Bool[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + x=(), + v: _ConvertibleToBool = None, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + ) -> None: ... + +class Text(Serialisable): + tagname: ClassVar[str] + tpls: Incomplete + x: Incomplete + v: String[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tpls=(), + x=(), + v=None, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c=None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class DateTimeField(Serialisable): + tagname: ClassVar[str] + x: Incomplete + v: DateTime[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + x=(), + v: datetime | str | None = None, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/pivot/record.pyi b/stubs/openpyxl/openpyxl/pivot/record.pyi new file mode 100644 index 000000000000..219fc70261c6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/record.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +class Record(Serialisable): + tagname: ClassVar[str] + m: Incomplete + n: Incomplete + b: Incomplete + e: Incomplete + s: Incomplete + d: Incomplete + x: Incomplete + def __init__(self, _fields=(), m=None, n=None, b=None, e=None, s=None, d=None, x=None) -> None: ... + +class RecordList(Serialisable): + mime_type: str + rel_type: str + tagname: ClassVar[str] + r: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, r=(), extLst: ExtensionList | None = None) -> None: ... + @property + def count(self) -> int: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/pivot/table.pyi b/stubs/openpyxl/openpyxl/pivot/table.pyi new file mode 100644 index 000000000000..ec1f0dd3fd45 --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/table.pyi @@ -0,0 +1,966 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.filters import AutoFilter +from openpyxl.xml.functions import Element + +_PivotAreaType: TypeAlias = Literal["normal", "data", "all", "origin", "button", "topEnd", "topRight"] +_PivotAxis: TypeAlias = Literal["axisRow", "axisCol", "axisPage", "axisValues"] +_ConditionalFormatType: TypeAlias = Literal["all", "row", "column"] +_FormatAction: TypeAlias = Literal["blank", "formatting", "drill", "formula"] +_PivotFilterType: TypeAlias = Literal[ + "unknown", + "count", + "percent", + "sum", + "captionEqual", + "captionNotEqual", + "captionBeginsWith", + "captionNotBeginsWith", + "captionEndsWith", + "captionNotEndsWith", + "captionContains", + "captionNotContains", + "captionGreaterThan", + "captionGreaterThanOrEqual", + "captionLessThan", + "captionLessThanOrEqual", + "captionBetween", + "captionNotBetween", + "valueEqual", + "valueNotEqual", + "valueGreaterThan", + "valueGreaterThanOrEqual", + "valueLessThan", + "valueLessThanOrEqual", + "valueBetween", + "valueNotBetween", + "dateEqual", + "dateNotEqual", + "dateOlderThan", + "dateOlderThanOrEqual", + "dateNewerThan", + "dateNewerThanOrEqual", + "dateBetween", + "dateNotBetween", + "tomorrow", + "today", + "yesterday", + "nextWeek", + "thisWeek", + "lastWeek", + "nextMonth", + "thisMonth", + "lastMonth", + "nextQuarter", + "thisQuarter", + "lastQuarter", + "nextYear", + "thisYear", + "lastYear", + "yearToDate", + "Q1", + "Q2", + "Q3", + "Q4", + "M1", + "M2", + "M3", + "M4", + "M5", + "M6", + "M7", + "M8", + "M9", + "M10", + "M11", + "M12", +] +_ConditionalFormatScope: TypeAlias = Literal["selection", "data", "field"] +_DataFieldSubtotal: TypeAlias = Literal[ + "average", "count", "countNums", "max", "min", "product", "stdDev", "stdDevp", "sum", "var", "varp" +] +_DataFieldShowDataAs: TypeAlias = Literal[ + "normal", "difference", "percent", "percentDiff", "runTotal", "percentOfRow", "percentOfCol", "percentOfTotal", "index" +] +_ItemType: TypeAlias = Literal[ + "data", + "default", + "sum", + "countA", + "avg", + "max", + "min", + "product", + "count", + "stdDev", + "stdDevP", + "var", + "varP", + "grand", + "blank", +] +_PivotFieldSortType: TypeAlias = Literal["manual", "ascending", "descending"] + +class HierarchyUsage(Serialisable): + tagname: ClassVar[str] + hierarchyUsage: Integer[Literal[False]] + def __init__(self, hierarchyUsage: ConvertibleToInt) -> None: ... + +class ColHierarchiesUsage(Serialisable): + tagname: ClassVar[str] + colHierarchyUsage: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, colHierarchyUsage=()) -> None: ... + @property + def count(self) -> int: ... + +class RowHierarchiesUsage(Serialisable): + tagname: ClassVar[str] + rowHierarchyUsage: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, rowHierarchyUsage=()) -> None: ... + @property + def count(self) -> int: ... + +class PivotFilter(Serialisable): + tagname: ClassVar[str] + fld: Integer[Literal[False]] + mpFld: Integer[Literal[True]] + type: Set[_PivotFilterType] + evalOrder: Integer[Literal[True]] + id: Integer[Literal[False]] + iMeasureHier: Integer[Literal[True]] + iMeasureFld: Integer[Literal[True]] + name: String[Literal[True]] + description: String[Literal[True]] + stringValue1: String[Literal[True]] + stringValue2: String[Literal[True]] + autoFilter: Typed[AutoFilter, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + fld: ConvertibleToInt, + mpFld: ConvertibleToInt | None = None, + *, + type: _PivotFilterType, + evalOrder: ConvertibleToInt | None = None, + id: ConvertibleToInt, + iMeasureHier: ConvertibleToInt | None = None, + iMeasureFld: ConvertibleToInt | None = None, + name: str | None = None, + description: str | None = None, + stringValue1: str | None = None, + stringValue2: str | None = None, + autoFilter: AutoFilter, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + fld: ConvertibleToInt, + mpFld: ConvertibleToInt | None, + type: _PivotFilterType, + evalOrder: ConvertibleToInt | None, + id: ConvertibleToInt, + iMeasureHier: ConvertibleToInt | None, + iMeasureFld: ConvertibleToInt | None, + name: str | None, + description: str | None, + stringValue1: str | None, + stringValue2: str | None, + autoFilter: AutoFilter, + extLst: ExtensionList | None = None, + ) -> None: ... + +class PivotFilters(Serialisable): + count: Integer[Literal[False]] + filter: Typed[PivotFilter, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: ConvertibleToInt, filter: PivotFilter | None = None) -> None: ... + +class PivotTableStyle(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + showRowHeaders: Bool[Literal[False]] + showColHeaders: Bool[Literal[False]] + showRowStripes: Bool[Literal[False]] + showColStripes: Bool[Literal[False]] + showLastColumn: Bool[Literal[False]] + def __init__( + self, + name: str | None = None, + showRowHeaders: _ConvertibleToBool = None, + showColHeaders: _ConvertibleToBool = None, + showRowStripes: _ConvertibleToBool = None, + showColStripes: _ConvertibleToBool = None, + showLastColumn: _ConvertibleToBool = None, + ) -> None: ... + +class MemberList(Serialisable): + tagname: ClassVar[str] + level: Integer[Literal[True]] + member: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, level: ConvertibleToInt | None = None, member=()) -> None: ... + @property + def count(self) -> int: ... + +class MemberProperty(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + showCell: Bool[Literal[True]] + showTip: Bool[Literal[True]] + showAsCaption: Bool[Literal[True]] + nameLen: Integer[Literal[True]] + pPos: Integer[Literal[True]] + pLen: Integer[Literal[True]] + level: Integer[Literal[True]] + field: Integer[Literal[False]] + + @overload + def __init__( + self, + name: str | None = None, + showCell: _ConvertibleToBool | None = None, + showTip: _ConvertibleToBool | None = None, + showAsCaption: _ConvertibleToBool | None = None, + nameLen: ConvertibleToInt | None = None, + pPos: ConvertibleToInt | None = None, + pLen: ConvertibleToInt | None = None, + level: ConvertibleToInt | None = None, + *, + field: ConvertibleToInt, + ) -> None: ... + @overload + def __init__( + self, + name: str | None, + showCell: _ConvertibleToBool | None, + showTip: _ConvertibleToBool | None, + showAsCaption: _ConvertibleToBool | None, + nameLen: ConvertibleToInt | None, + pPos: ConvertibleToInt | None, + pLen: ConvertibleToInt | None, + level: ConvertibleToInt | None, + field: ConvertibleToInt, + ) -> None: ... + +class PivotHierarchy(Serialisable): + tagname: ClassVar[str] + outline: Bool[Literal[False]] + multipleItemSelectionAllowed: Bool[Literal[False]] + subtotalTop: Bool[Literal[False]] + showInFieldList: Bool[Literal[False]] + dragToRow: Bool[Literal[False]] + dragToCol: Bool[Literal[False]] + dragToPage: Bool[Literal[False]] + dragToData: Bool[Literal[False]] + dragOff: Bool[Literal[False]] + includeNewItemsInFilter: Bool[Literal[False]] + caption: String[Literal[True]] + mps: Incomplete + members: Typed[MemberList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + outline: _ConvertibleToBool = None, + multipleItemSelectionAllowed: _ConvertibleToBool = None, + subtotalTop: _ConvertibleToBool = None, + showInFieldList: _ConvertibleToBool = None, + dragToRow: _ConvertibleToBool = None, + dragToCol: _ConvertibleToBool = None, + dragToPage: _ConvertibleToBool = None, + dragToData: _ConvertibleToBool = None, + dragOff: _ConvertibleToBool = None, + includeNewItemsInFilter: _ConvertibleToBool = None, + caption: str | None = None, + mps=(), + members: MemberList | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class Reference(Serialisable): + tagname: ClassVar[str] + field: Integer[Literal[True]] + selected: Bool[Literal[True]] + byPosition: Bool[Literal[True]] + relative: Bool[Literal[True]] + defaultSubtotal: Bool[Literal[True]] + sumSubtotal: Bool[Literal[True]] + countASubtotal: Bool[Literal[True]] + avgSubtotal: Bool[Literal[True]] + maxSubtotal: Bool[Literal[True]] + minSubtotal: Bool[Literal[True]] + productSubtotal: Bool[Literal[True]] + countSubtotal: Bool[Literal[True]] + stdDevSubtotal: Bool[Literal[True]] + stdDevPSubtotal: Bool[Literal[True]] + varSubtotal: Bool[Literal[True]] + varPSubtotal: Bool[Literal[True]] + x: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + field: ConvertibleToInt | None = None, + count: Unused = None, + selected: _ConvertibleToBool | None = None, + byPosition: _ConvertibleToBool | None = None, + relative: _ConvertibleToBool | None = None, + defaultSubtotal: _ConvertibleToBool | None = None, + sumSubtotal: _ConvertibleToBool | None = None, + countASubtotal: _ConvertibleToBool | None = None, + avgSubtotal: _ConvertibleToBool | None = None, + maxSubtotal: _ConvertibleToBool | None = None, + minSubtotal: _ConvertibleToBool | None = None, + productSubtotal: _ConvertibleToBool | None = None, + countSubtotal: _ConvertibleToBool | None = None, + stdDevSubtotal: _ConvertibleToBool | None = None, + stdDevPSubtotal: _ConvertibleToBool | None = None, + varSubtotal: _ConvertibleToBool | None = None, + varPSubtotal: _ConvertibleToBool | None = None, + x: Incomplete | None = (), + extLst: ExtensionList | None = None, + ) -> None: ... + @property + def count(self) -> int: ... + +class PivotArea(Serialisable): + tagname: ClassVar[str] + references: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + field: Integer[Literal[True]] + type: NoneSet[_PivotAreaType] + dataOnly: Bool[Literal[True]] + labelOnly: Bool[Literal[True]] + grandRow: Bool[Literal[True]] + grandCol: Bool[Literal[True]] + cacheIndex: Bool[Literal[True]] + outline: Bool[Literal[True]] + offset: String[Literal[True]] + collapsedLevelsAreSubtotals: Bool[Literal[True]] + axis: NoneSet[_PivotAxis] + fieldPosition: Integer[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + references=(), + extLst: ExtensionList | None = None, + field: ConvertibleToInt | None = None, + type: _PivotAreaType | Literal["none"] | None = "normal", + dataOnly: _ConvertibleToBool | None = True, + labelOnly: _ConvertibleToBool | None = None, + grandRow: _ConvertibleToBool | None = None, + grandCol: _ConvertibleToBool | None = None, + cacheIndex: _ConvertibleToBool | None = None, + outline: _ConvertibleToBool | None = True, + offset: str | None = None, + collapsedLevelsAreSubtotals: _ConvertibleToBool | None = None, + axis: _PivotAxis | Literal["none"] | None = None, + fieldPosition: ConvertibleToInt | None = None, + ) -> None: ... + +class ChartFormat(Serialisable): + tagname: ClassVar[str] + chart: Integer[Literal[False]] + format: Integer[Literal[False]] + series: Bool[Literal[False]] + pivotArea: Typed[PivotArea, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, chart: ConvertibleToInt, format: ConvertibleToInt, series: _ConvertibleToBool = None, *, pivotArea: PivotArea + ) -> None: ... + @overload + def __init__( + self, chart: ConvertibleToInt, format: ConvertibleToInt, series: _ConvertibleToBool, pivotArea: PivotArea + ) -> None: ... + +class ConditionalFormat(Serialisable): + tagname: ClassVar[str] + scope: Set[_ConditionalFormatScope] + type: NoneSet[_ConditionalFormatType] + priority: Integer[Literal[False]] + pivotAreas: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + scope: _ConditionalFormatScope = "selection", + type: _ConditionalFormatType | Literal["none"] | None = None, + *, + priority: ConvertibleToInt, + pivotAreas=(), + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + scope: _ConditionalFormatScope, + type: _ConditionalFormatType | Literal["none"] | None, + priority: ConvertibleToInt, + pivotAreas=(), + extLst: ExtensionList | None = None, + ) -> None: ... + +class ConditionalFormatList(Serialisable): + tagname: ClassVar[str] + conditionalFormat: Incomplete + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, conditionalFormat=(), count=None) -> None: ... + def by_priority(self): ... + @property + def count(self) -> int: ... + def to_tree(self, tagname: str | None = None) -> Element: ... # type: ignore[override] + +class Format(Serialisable): + tagname: ClassVar[str] + action: NoneSet[_FormatAction] + dxfId: Integer[Literal[True]] + pivotArea: Typed[PivotArea, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + action: _FormatAction | Literal["none"] | None = "formatting", + dxfId: ConvertibleToInt | None = None, + *, + pivotArea: PivotArea, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + action: _FormatAction | Literal["none"] | None, + dxfId: ConvertibleToInt | None, + pivotArea: PivotArea, + extLst: ExtensionList | None = None, + ) -> None: ... + +class DataField(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + fld: Integer[Literal[False]] + subtotal: Set[_DataFieldSubtotal] + showDataAs: Set[_DataFieldShowDataAs] + baseField: Integer[Literal[False]] + baseItem: Integer[Literal[False]] + numFmtId: Integer[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + name: str | None = None, + *, + fld: ConvertibleToInt, + subtotal: str = "sum", + showDataAs: str = "normal", + baseField: ConvertibleToInt = -1, + baseItem: ConvertibleToInt = 1048832, + numFmtId: ConvertibleToInt | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + name: str | None, + fld: ConvertibleToInt, + subtotal: str = "sum", + showDataAs: str = "normal", + baseField: ConvertibleToInt = -1, + baseItem: ConvertibleToInt = 1048832, + numFmtId: ConvertibleToInt | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class PageField(Serialisable): + tagname: ClassVar[str] + fld: Integer[Literal[False]] + item: Integer[Literal[True]] + hier: Integer[Literal[True]] + name: String[Literal[True]] + cap: String[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + fld: ConvertibleToInt, + item: ConvertibleToInt | None = None, + hier: ConvertibleToInt | None = None, + name: str | None = None, + cap: str | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class RowColItem(Serialisable): + tagname: ClassVar[str] + t: Set[_ItemType] + r: Integer[Literal[False]] + i: Integer[Literal[False]] + x: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, t: _ItemType = "data", r: ConvertibleToInt = 0, i: ConvertibleToInt = 0, x=()) -> None: ... + +class RowColField(Serialisable): + tagname: ClassVar[str] + x: Integer[Literal[False]] + def __init__(self, x: ConvertibleToInt) -> None: ... + +class AutoSortScope(Serialisable): + pivotArea: Typed[PivotArea, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, pivotArea: PivotArea) -> None: ... + +class FieldItem(Serialisable): + tagname: ClassVar[str] + n: String[Literal[True]] + t: Set[_ItemType] + h: Bool[Literal[True]] + s: Bool[Literal[True]] + sd: Bool[Literal[True]] + f: Bool[Literal[True]] + m: Bool[Literal[True]] + c: Bool[Literal[True]] + x: Integer[Literal[True]] + d: Bool[Literal[True]] + e: Bool[Literal[True]] + def __init__( + self, + n: str | None = None, + t: _ItemType = "data", + h: _ConvertibleToBool | None = None, + s: _ConvertibleToBool | None = None, + sd: _ConvertibleToBool | None = True, + f: _ConvertibleToBool | None = None, + m: _ConvertibleToBool | None = None, + c: _ConvertibleToBool | None = None, + x: ConvertibleToInt | None = None, + d: _ConvertibleToBool | None = None, + e: _ConvertibleToBool | None = None, + ) -> None: ... + +class PivotField(Serialisable): + tagname: ClassVar[str] + items: Incomplete + autoSortScope: Typed[AutoSortScope, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + name: String[Literal[True]] + axis: NoneSet[_PivotAxis] + dataField: Bool[Literal[True]] + subtotalCaption: String[Literal[True]] + showDropDowns: Bool[Literal[True]] + hiddenLevel: Bool[Literal[True]] + uniqueMemberProperty: String[Literal[True]] + compact: Bool[Literal[True]] + allDrilled: Bool[Literal[True]] + numFmtId: Integer[Literal[True]] + outline: Bool[Literal[True]] + subtotalTop: Bool[Literal[True]] + dragToRow: Bool[Literal[True]] + dragToCol: Bool[Literal[True]] + multipleItemSelectionAllowed: Bool[Literal[True]] + dragToPage: Bool[Literal[True]] + dragToData: Bool[Literal[True]] + dragOff: Bool[Literal[True]] + showAll: Bool[Literal[True]] + insertBlankRow: Bool[Literal[True]] + serverField: Bool[Literal[True]] + insertPageBreak: Bool[Literal[True]] + autoShow: Bool[Literal[True]] + topAutoShow: Bool[Literal[True]] + hideNewItems: Bool[Literal[True]] + measureFilter: Bool[Literal[True]] + includeNewItemsInFilter: Bool[Literal[True]] + itemPageCount: Integer[Literal[True]] + sortType: Set[_PivotFieldSortType] + dataSourceSort: Bool[Literal[True]] + nonAutoSortDefault: Bool[Literal[True]] + rankBy: Integer[Literal[True]] + defaultSubtotal: Bool[Literal[True]] + sumSubtotal: Bool[Literal[True]] + countASubtotal: Bool[Literal[True]] + avgSubtotal: Bool[Literal[True]] + maxSubtotal: Bool[Literal[True]] + minSubtotal: Bool[Literal[True]] + productSubtotal: Bool[Literal[True]] + countSubtotal: Bool[Literal[True]] + stdDevSubtotal: Bool[Literal[True]] + stdDevPSubtotal: Bool[Literal[True]] + varSubtotal: Bool[Literal[True]] + varPSubtotal: Bool[Literal[True]] + showPropCell: Bool[Literal[True]] + showPropTip: Bool[Literal[True]] + showPropAsCaption: Bool[Literal[True]] + defaultAttributeDrillState: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + items=(), + autoSortScope: AutoSortScope | None = None, + name: str | None = None, + axis: _PivotAxis | Literal["none"] | None = None, + dataField: _ConvertibleToBool | None = None, + subtotalCaption: str | None = None, + showDropDowns: _ConvertibleToBool | None = True, + hiddenLevel: _ConvertibleToBool | None = None, + uniqueMemberProperty: str | None = None, + compact: _ConvertibleToBool | None = True, + allDrilled: _ConvertibleToBool | None = None, + numFmtId: ConvertibleToInt | None = None, + outline: _ConvertibleToBool | None = True, + subtotalTop: _ConvertibleToBool | None = True, + dragToRow: _ConvertibleToBool | None = True, + dragToCol: _ConvertibleToBool | None = True, + multipleItemSelectionAllowed: _ConvertibleToBool | None = None, + dragToPage: _ConvertibleToBool | None = True, + dragToData: _ConvertibleToBool | None = True, + dragOff: _ConvertibleToBool | None = True, + showAll: _ConvertibleToBool | None = True, + insertBlankRow: _ConvertibleToBool | None = None, + serverField: _ConvertibleToBool | None = None, + insertPageBreak: _ConvertibleToBool | None = None, + autoShow: _ConvertibleToBool | None = None, + topAutoShow: _ConvertibleToBool | None = True, + hideNewItems: _ConvertibleToBool | None = None, + measureFilter: _ConvertibleToBool | None = None, + includeNewItemsInFilter: _ConvertibleToBool | None = None, + itemPageCount: ConvertibleToInt | None = 10, + sortType: _PivotFieldSortType = "manual", + dataSourceSort: _ConvertibleToBool | None = None, + nonAutoSortDefault: _ConvertibleToBool | None = None, + rankBy: ConvertibleToInt | None = None, + defaultSubtotal: _ConvertibleToBool | None = True, + sumSubtotal: _ConvertibleToBool | None = None, + countASubtotal: _ConvertibleToBool | None = None, + avgSubtotal: _ConvertibleToBool | None = None, + maxSubtotal: _ConvertibleToBool | None = None, + minSubtotal: _ConvertibleToBool | None = None, + productSubtotal: _ConvertibleToBool | None = None, + countSubtotal: _ConvertibleToBool | None = None, + stdDevSubtotal: _ConvertibleToBool | None = None, + stdDevPSubtotal: _ConvertibleToBool | None = None, + varSubtotal: _ConvertibleToBool | None = None, + varPSubtotal: _ConvertibleToBool | None = None, + showPropCell: _ConvertibleToBool | None = None, + showPropTip: _ConvertibleToBool | None = None, + showPropAsCaption: _ConvertibleToBool | None = None, + defaultAttributeDrillState: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class Location(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + firstHeaderRow: Integer[Literal[False]] + firstDataRow: Integer[Literal[False]] + firstDataCol: Integer[Literal[False]] + rowPageCount: Integer[Literal[True]] + colPageCount: Integer[Literal[True]] + def __init__( + self, + ref: str, + firstHeaderRow: ConvertibleToInt, + firstDataRow: ConvertibleToInt, + firstDataCol: ConvertibleToInt, + rowPageCount: ConvertibleToInt | None = None, + colPageCount: ConvertibleToInt | None = None, + ) -> None: ... + +class TableDefinition(Serialisable): + mime_type: str + rel_type: str + tagname: ClassVar[str] + cache: Incomplete + name: String[Literal[False]] + cacheId: Integer[Literal[False]] + dataOnRows: Bool[Literal[False]] + dataPosition: Integer[Literal[True]] + dataCaption: String[Literal[False]] + grandTotalCaption: String[Literal[True]] + errorCaption: String[Literal[True]] + showError: Bool[Literal[False]] + missingCaption: String[Literal[True]] + showMissing: Bool[Literal[False]] + pageStyle: String[Literal[True]] + pivotTableStyle: String[Literal[True]] + vacatedStyle: String[Literal[True]] + tag: String[Literal[True]] + updatedVersion: Integer[Literal[False]] + minRefreshableVersion: Integer[Literal[False]] + asteriskTotals: Bool[Literal[False]] + showItems: Bool[Literal[False]] + editData: Bool[Literal[False]] + disableFieldList: Bool[Literal[False]] + showCalcMbrs: Bool[Literal[False]] + visualTotals: Bool[Literal[False]] + showMultipleLabel: Bool[Literal[False]] + showDataDropDown: Bool[Literal[False]] + showDrill: Bool[Literal[False]] + printDrill: Bool[Literal[False]] + showMemberPropertyTips: Bool[Literal[False]] + showDataTips: Bool[Literal[False]] + enableWizard: Bool[Literal[False]] + enableDrill: Bool[Literal[False]] + enableFieldProperties: Bool[Literal[False]] + preserveFormatting: Bool[Literal[False]] + useAutoFormatting: Bool[Literal[False]] + pageWrap: Integer[Literal[False]] + pageOverThenDown: Bool[Literal[False]] + subtotalHiddenItems: Bool[Literal[False]] + rowGrandTotals: Bool[Literal[False]] + colGrandTotals: Bool[Literal[False]] + fieldPrintTitles: Bool[Literal[False]] + itemPrintTitles: Bool[Literal[False]] + mergeItem: Bool[Literal[False]] + showDropZones: Bool[Literal[False]] + createdVersion: Integer[Literal[False]] + indent: Integer[Literal[False]] + showEmptyRow: Bool[Literal[False]] + showEmptyCol: Bool[Literal[False]] + showHeaders: Bool[Literal[False]] + compact: Bool[Literal[False]] + outline: Bool[Literal[False]] + outlineData: Bool[Literal[False]] + compactData: Bool[Literal[False]] + published: Bool[Literal[False]] + gridDropZones: Bool[Literal[False]] + immersive: Bool[Literal[False]] + multipleFieldFilters: Bool[Literal[False]] + chartFormat: Integer[Literal[False]] + rowHeaderCaption: String[Literal[True]] + colHeaderCaption: String[Literal[True]] + fieldListSortAscending: Bool[Literal[False]] + mdxSubqueries: Bool[Literal[False]] + customListSort: Bool[Literal[True]] + autoFormatId: Integer[Literal[True]] + applyNumberFormats: Bool[Literal[False]] + applyBorderFormats: Bool[Literal[False]] + applyFontFormats: Bool[Literal[False]] + applyPatternFormats: Bool[Literal[False]] + applyAlignmentFormats: Bool[Literal[False]] + applyWidthHeightFormats: Bool[Literal[False]] + location: Typed[Location, Literal[False]] + pivotFields: Incomplete + rowFields: Incomplete + rowItems: Incomplete + colFields: Incomplete + colItems: Incomplete + pageFields: Incomplete + dataFields: Incomplete + formats: Incomplete + conditionalFormats: Typed[ConditionalFormatList, Literal[True]] + chartFormats: Incomplete + pivotHierarchies: Incomplete + pivotTableStyleInfo: Typed[PivotTableStyle, Literal[True]] + filters: Incomplete + rowHierarchiesUsage: Typed[RowHierarchiesUsage, Literal[True]] + colHierarchiesUsage: Typed[ColHierarchiesUsage, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + name: str, + cacheId: ConvertibleToInt, + dataOnRows: _ConvertibleToBool = False, + dataPosition: ConvertibleToInt | None = None, + *, + dataCaption: str, + grandTotalCaption: str | None = None, + errorCaption: str | None = None, + showError: _ConvertibleToBool = False, + missingCaption: str | None = None, + showMissing: _ConvertibleToBool = True, + pageStyle: str | None = None, + pivotTableStyle: str | None = None, + vacatedStyle: str | None = None, + tag: str | None = None, + updatedVersion: ConvertibleToInt = 0, + minRefreshableVersion: ConvertibleToInt = 0, + asteriskTotals: _ConvertibleToBool = False, + showItems: _ConvertibleToBool = True, + editData: _ConvertibleToBool = False, + disableFieldList: _ConvertibleToBool = False, + showCalcMbrs: _ConvertibleToBool = True, + visualTotals: _ConvertibleToBool = True, + showMultipleLabel: _ConvertibleToBool = True, + showDataDropDown: _ConvertibleToBool = True, + showDrill: _ConvertibleToBool = True, + printDrill: _ConvertibleToBool = False, + showMemberPropertyTips: _ConvertibleToBool = True, + showDataTips: _ConvertibleToBool = True, + enableWizard: _ConvertibleToBool = True, + enableDrill: _ConvertibleToBool = True, + enableFieldProperties: _ConvertibleToBool = True, + preserveFormatting: _ConvertibleToBool = True, + useAutoFormatting: _ConvertibleToBool = False, + pageWrap: ConvertibleToInt = 0, + pageOverThenDown: _ConvertibleToBool = False, + subtotalHiddenItems: _ConvertibleToBool = False, + rowGrandTotals: _ConvertibleToBool = True, + colGrandTotals: _ConvertibleToBool = True, + fieldPrintTitles: _ConvertibleToBool = False, + itemPrintTitles: _ConvertibleToBool = False, + mergeItem: _ConvertibleToBool = False, + showDropZones: _ConvertibleToBool = True, + createdVersion: ConvertibleToInt = 0, + indent: ConvertibleToInt = 1, + showEmptyRow: _ConvertibleToBool = False, + showEmptyCol: _ConvertibleToBool = False, + showHeaders: _ConvertibleToBool = True, + compact: _ConvertibleToBool = True, + outline: _ConvertibleToBool = False, + outlineData: _ConvertibleToBool = False, + compactData: _ConvertibleToBool = True, + published: _ConvertibleToBool = False, + gridDropZones: _ConvertibleToBool = False, + immersive: _ConvertibleToBool = True, + multipleFieldFilters: _ConvertibleToBool = None, + chartFormat: ConvertibleToInt = 0, + rowHeaderCaption: str | None = None, + colHeaderCaption: str | None = None, + fieldListSortAscending: _ConvertibleToBool = None, + mdxSubqueries: _ConvertibleToBool = None, + customListSort: _ConvertibleToBool | None = None, + autoFormatId: ConvertibleToInt | None = None, + applyNumberFormats: _ConvertibleToBool = False, + applyBorderFormats: _ConvertibleToBool = False, + applyFontFormats: _ConvertibleToBool = False, + applyPatternFormats: _ConvertibleToBool = False, + applyAlignmentFormats: _ConvertibleToBool = False, + applyWidthHeightFormats: _ConvertibleToBool = False, + location: Location, + pivotFields=(), + rowFields=(), + rowItems=(), + colFields=(), + colItems=(), + pageFields=(), + dataFields=(), + formats=(), + conditionalFormats: ConditionalFormatList | None = None, + chartFormats=(), + pivotHierarchies=(), + pivotTableStyleInfo: PivotTableStyle | None = None, + filters=(), + rowHierarchiesUsage: RowHierarchiesUsage | None = None, + colHierarchiesUsage: ColHierarchiesUsage | None = None, + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + @overload + def __init__( + self, + name: str, + cacheId: ConvertibleToInt, + dataOnRows: _ConvertibleToBool, + dataPosition: ConvertibleToInt | None, + dataCaption: str, + grandTotalCaption: str | None, + errorCaption: str | None, + showError: _ConvertibleToBool, + missingCaption: str | None, + showMissing: _ConvertibleToBool, + pageStyle: str | None, + pivotTableStyle: str | None, + vacatedStyle: str | None, + tag: str | None, + updatedVersion: ConvertibleToInt, + minRefreshableVersion: ConvertibleToInt, + asteriskTotals: _ConvertibleToBool, + showItems: _ConvertibleToBool, + editData: _ConvertibleToBool, + disableFieldList: _ConvertibleToBool, + showCalcMbrs: _ConvertibleToBool, + visualTotals: _ConvertibleToBool, + showMultipleLabel: _ConvertibleToBool, + showDataDropDown: _ConvertibleToBool, + showDrill: _ConvertibleToBool, + printDrill: _ConvertibleToBool, + showMemberPropertyTips: _ConvertibleToBool, + showDataTips: _ConvertibleToBool, + enableWizard: _ConvertibleToBool, + enableDrill: _ConvertibleToBool, + enableFieldProperties: _ConvertibleToBool, + preserveFormatting: _ConvertibleToBool, + useAutoFormatting: _ConvertibleToBool, + pageWrap: ConvertibleToInt, + pageOverThenDown: _ConvertibleToBool, + subtotalHiddenItems: _ConvertibleToBool, + rowGrandTotals: _ConvertibleToBool, + colGrandTotals: _ConvertibleToBool, + fieldPrintTitles: _ConvertibleToBool, + itemPrintTitles: _ConvertibleToBool, + mergeItem: _ConvertibleToBool, + showDropZones: _ConvertibleToBool, + createdVersion: ConvertibleToInt, + indent: ConvertibleToInt, + showEmptyRow: _ConvertibleToBool, + showEmptyCol: _ConvertibleToBool, + showHeaders: _ConvertibleToBool, + compact: _ConvertibleToBool, + outline: _ConvertibleToBool, + outlineData: _ConvertibleToBool, + compactData: _ConvertibleToBool, + published: _ConvertibleToBool, + gridDropZones: _ConvertibleToBool, + immersive: _ConvertibleToBool, + multipleFieldFilters: _ConvertibleToBool, + chartFormat: ConvertibleToInt, + rowHeaderCaption: str | None, + colHeaderCaption: str | None, + fieldListSortAscending: _ConvertibleToBool, + mdxSubqueries: _ConvertibleToBool, + customListSort: _ConvertibleToBool | None, + autoFormatId: ConvertibleToInt | None, + applyNumberFormats: _ConvertibleToBool, + applyBorderFormats: _ConvertibleToBool, + applyFontFormats: _ConvertibleToBool, + applyPatternFormats: _ConvertibleToBool, + applyAlignmentFormats: _ConvertibleToBool, + applyWidthHeightFormats: _ConvertibleToBool, + location: Location, + pivotFields=(), + rowFields=(), + rowItems=(), + colFields=(), + colItems=(), + pageFields=(), + dataFields=(), + formats=(), + conditionalFormats: ConditionalFormatList | None = None, + chartFormats=(), + pivotHierarchies=(), + pivotTableStyleInfo: PivotTableStyle | None = None, + filters=(), + rowHierarchiesUsage: RowHierarchiesUsage | None = None, + colHierarchiesUsage: ColHierarchiesUsage | None = None, + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... + def formatted_fields(self) -> dict[Incomplete, list[Incomplete]]: ... + @property + def summary(self) -> str: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/event/legacy.pyi b/stubs/openpyxl/openpyxl/reader/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/event/legacy.pyi rename to stubs/openpyxl/openpyxl/reader/__init__.pyi diff --git a/stubs/openpyxl/openpyxl/reader/drawings.pyi b/stubs/openpyxl/openpyxl/reader/drawings.pyi new file mode 100644 index 000000000000..f2bf8cd0863f --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/drawings.pyi @@ -0,0 +1,6 @@ +from zipfile import ZipFile + +from openpyxl.chart._chart import ChartBase +from openpyxl.drawing.image import Image + +def find_images(archive: ZipFile, path: str) -> tuple[list[ChartBase], list[Image]]: ... diff --git a/stubs/openpyxl/openpyxl/reader/excel.pyi b/stubs/openpyxl/openpyxl/reader/excel.pyi new file mode 100644 index 000000000000..da45a60724e6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/excel.pyi @@ -0,0 +1,53 @@ +from typing import Final, Literal, TypeAlias +from zipfile import ZipFile + +from openpyxl import _ZipFileFileProtocol +from openpyxl.chartsheet.chartsheet import Chartsheet +from openpyxl.packaging.manifest import Manifest +from openpyxl.packaging.relationship import Relationship +from openpyxl.reader.workbook import WorkbookParser +from openpyxl.workbook import Workbook + +_SupportedFormats: TypeAlias = Literal[".xlsx", ".xlsm", ".xltx", ".xltm"] +SUPPORTED_FORMATS: Final[tuple[_SupportedFormats, ...]] + +class ExcelReader: + archive: ZipFile + valid_files: list[str] + read_only: bool + keep_vba: bool + data_only: bool + keep_links: bool + rich_text: bool + shared_strings: list[str] + package: Manifest # defined after call to read_manifest() + parser: WorkbookParser # defined after call to read_workbook() + wb: Workbook # defined after call to read_workbook() + + def __init__( + self, + fn: _ZipFileFileProtocol, + read_only: bool = False, + keep_vba: bool = False, + data_only: bool = False, + keep_links: bool = True, + rich_text: bool = False, + ) -> None: ... + def read_manifest(self) -> None: ... + def read_strings(self) -> None: ... + def read_workbook(self) -> None: ... + def read_properties(self) -> None: ... + def read_custom(self) -> None: ... + def read_theme(self) -> None: ... + def read_chartsheet(self, sheet: Chartsheet, rel: Relationship) -> None: ... + def read_worksheets(self) -> None: ... + def read(self) -> None: ... + +def load_workbook( + filename: _ZipFileFileProtocol, + read_only: bool = False, + keep_vba: bool = False, + data_only: bool = False, + keep_links: bool = True, + rich_text: bool = False, +) -> Workbook: ... diff --git a/stubs/openpyxl/openpyxl/reader/strings.pyi b/stubs/openpyxl/openpyxl/reader/strings.pyi new file mode 100644 index 000000000000..3d6b247ded12 --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/strings.pyi @@ -0,0 +1,6 @@ +from xml.etree.ElementTree import _FileRead + +from openpyxl.cell.rich_text import CellRichText + +def read_string_table(xml_source: _FileRead) -> list[str]: ... +def read_rich_text(xml_source: _FileRead) -> list[CellRichText | str]: ... diff --git a/stubs/openpyxl/openpyxl/reader/workbook.pyi b/stubs/openpyxl/openpyxl/reader/workbook.pyi new file mode 100644 index 000000000000..7a8f3bec60a7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/workbook.pyi @@ -0,0 +1,24 @@ +from collections.abc import Generator +from zipfile import ZipFile + +from openpyxl.packaging.relationship import Relationship, RelationshipList +from openpyxl.packaging.workbook import ChildSheet, PivotCache +from openpyxl.pivot.cache import CacheDefinition +from openpyxl.workbook import Workbook + +class WorkbookParser: + archive: ZipFile + workbook_part_name: str + wb: Workbook + keep_links: bool + sheets: list[ChildSheet] + def __init__(self, archive: ZipFile, workbook_part_name: str, keep_links: bool = True) -> None: ... + @property + def rels(self) -> RelationshipList: ... + # Errors if "parse" is never called. + caches: list[PivotCache] + def parse(self) -> None: ... + def find_sheets(self) -> Generator[tuple[ChildSheet, Relationship]]: ... + def assign_names(self) -> None: ... + @property + def pivot_caches(self) -> dict[int, CacheDefinition]: ... diff --git a/stubs/openpyxl/openpyxl/styles/__init__.pyi b/stubs/openpyxl/openpyxl/styles/__init__.pyi new file mode 100644 index 000000000000..946d3a30b775 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/__init__.pyi @@ -0,0 +1,8 @@ +from .alignment import Alignment as Alignment +from .borders import Border as Border, Side as Side +from .colors import Color as Color +from .fills import Fill as Fill, GradientFill as GradientFill, PatternFill as PatternFill +from .fonts import DEFAULT_FONT as DEFAULT_FONT, Font as Font +from .named_styles import NamedStyle as NamedStyle +from .numbers import NumberFormatDescriptor as NumberFormatDescriptor, is_builtin as is_builtin, is_date_format as is_date_format +from .protection import Protection as Protection diff --git a/stubs/openpyxl/openpyxl/styles/alignment.pyi b/stubs/openpyxl/openpyxl/styles/alignment.pyi new file mode 100644 index 000000000000..40f69c4e46cd --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/alignment.pyi @@ -0,0 +1,46 @@ +from _typeshed import ConvertibleToFloat +from collections.abc import Iterator +from typing import ClassVar, Final, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, Min, MinMax, NoneSet, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_HorizontalAlignmentsType: TypeAlias = Literal[ + "general", "left", "center", "right", "fill", "justify", "centerContinuous", "distributed" +] +_VerticalAlignmentsType: TypeAlias = Literal["top", "center", "bottom", "justify", "distributed"] + +horizontal_alignments: Final[tuple[_HorizontalAlignmentsType, ...]] +vertical_aligments: Final[tuple[_VerticalAlignmentsType, ...]] + +class Alignment(Serialisable): + tagname: ClassVar[str] + horizontal: NoneSet[_HorizontalAlignmentsType] + vertical: NoneSet[_VerticalAlignmentsType] + textRotation: NoneSet[int] + text_rotation: Alias + wrapText: Bool[Literal[True]] + wrap_text: Alias + shrinkToFit: Bool[Literal[True]] + shrink_to_fit: Alias + indent: MinMax[float, Literal[False]] + relativeIndent: MinMax[float, Literal[False]] + justifyLastLine: Bool[Literal[True]] + readingOrder: Min[float, Literal[False]] + def __init__( + self, + horizontal=None, + vertical=None, + textRotation: int = 0, + wrapText: _ConvertibleToBool | None = None, + shrinkToFit: _ConvertibleToBool | None = None, + indent: ConvertibleToFloat = 0, + relativeIndent: ConvertibleToFloat = 0, + justifyLastLine: _ConvertibleToBool | None = None, + readingOrder: ConvertibleToFloat = 0, + text_rotation=None, + wrap_text=None, + shrink_to_fit=None, + mergeCell=None, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... diff --git a/stubs/openpyxl/openpyxl/styles/borders.pyi b/stubs/openpyxl/openpyxl/styles/borders.pyi new file mode 100644 index 000000000000..099ce57e7446 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/borders.pyi @@ -0,0 +1,82 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar, Final, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor + +_SideStyle: TypeAlias = Literal[ + "dashDot", + "dashDotDot", + "dashed", + "dotted", + "double", + "hair", + "medium", + "mediumDashDot", + "mediumDashDotDot", + "mediumDashed", + "slantDashDot", + "thick", + "thin", +] + +BORDER_NONE: Final = None +BORDER_DASHDOT: Final = "dashDot" +BORDER_DASHDOTDOT: Final = "dashDotDot" +BORDER_DASHED: Final = "dashed" +BORDER_DOTTED: Final = "dotted" +BORDER_DOUBLE: Final = "double" +BORDER_HAIR: Final = "hair" +BORDER_MEDIUM: Final = "medium" +BORDER_MEDIUMDASHDOT: Final = "mediumDashDot" +BORDER_MEDIUMDASHDOTDOT: Final = "mediumDashDotDot" +BORDER_MEDIUMDASHED: Final = "mediumDashed" +BORDER_SLANTDASHDOT: Final = "slantDashDot" +BORDER_THICK: Final = "thick" +BORDER_THIN: Final = "thin" + +class Side(Serialisable): + color: ColorDescriptor[Literal[True]] + style: NoneSet[_SideStyle] + border_style: Alias + def __init__( + self, style: _SideStyle | Literal["none"] | None = None, color: str | Color | None = None, border_style=None + ) -> None: ... + +class Border(Serialisable): + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + start: Typed[Side, Literal[True]] + end: Typed[Side, Literal[True]] + left: Typed[Side, Literal[True]] + right: Typed[Side, Literal[True]] + top: Typed[Side, Literal[True]] + bottom: Typed[Side, Literal[True]] + diagonal: Typed[Side, Literal[True]] + vertical: Typed[Side, Literal[True]] + horizontal: Typed[Side, Literal[True]] + outline: Bool[Literal[False]] + diagonalUp: Bool[Literal[False]] + diagonalDown: Bool[Literal[False]] + diagonal_direction: Incomplete + def __init__( + self, + left: Side | None = None, + right: Side | None = None, + top: Side | None = None, + bottom: Side | None = None, + diagonal: Side | None = None, + diagonal_direction=None, + vertical: Side | None = None, + horizontal: Side | None = None, + diagonalUp: _ConvertibleToBool = False, + diagonalDown: _ConvertibleToBool = False, + outline: _ConvertibleToBool = True, + start: Side | None = None, + end: Side | None = None, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + +DEFAULT_BORDER: Final[Border] diff --git a/stubs/openpyxl/openpyxl/styles/builtins.pyi b/stubs/openpyxl/openpyxl/styles/builtins.pyi new file mode 100644 index 000000000000..aabe58d9813f --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/builtins.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete + +normal: str +comma: str +comma_0: str +currency: str +currency_0: str +percent: str +hyperlink: str +followed_hyperlink: str +title: str +headline_1: str +headline_2: str +headline_3: str +headline_4: str +good: str +bad: str +neutral: str +input: str +output: str +calculation: str +linked_cell: str +check_cell: str +warning: str +note: str +explanatory: str +total: str +accent_1: str +accent_1_20: str +accent_1_40: str +accent_1_60: str +accent_2: str +accent_2_20: str +accent_2_40: str +accent_2_60: str +accent_3: str +accent_3_20: str +accent_3_40: str +accent_3_60: str +accent_4: str +accent_4_20: str +accent_4_40: str +accent_4_60: str +accent_5: str +accent_5_20: str +accent_5_40: str +accent_5_60: str +accent_6: str +accent_6_20: str +accent_6_40: str +accent_6_60: str +pandas_highlight: str +styles: Incomplete diff --git a/stubs/openpyxl/openpyxl/styles/cell_style.pyi b/stubs/openpyxl/openpyxl/styles/cell_style.pyi new file mode 100644 index 000000000000..dc7f6c278449 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/cell_style.pyi @@ -0,0 +1,98 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from array import array +from collections.abc import Iterable, MutableSequence +from typing import ClassVar, Generic, Literal, TypeVar +from typing_extensions import Self + +from openpyxl.descriptors.base import Bool, Integer, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.alignment import Alignment +from openpyxl.styles.protection import Protection + +_T = TypeVar("_T") + +class ArrayDescriptor(Generic[_T]): + key: int + def __init__(self, key: int) -> None: ... + def __get__(self, instance: MutableSequence[_T], cls: Unused) -> _T: ... + def __set__(self, instance: MutableSequence[_T], value: _T) -> None: ... + +class StyleArray(array[int]): + __slots__ = () + tagname: ClassVar[str] + fontId: ArrayDescriptor[int] + fillId: ArrayDescriptor[int] + borderId: ArrayDescriptor[int] + numFmtId: ArrayDescriptor[int] + protectionId: ArrayDescriptor[int] + alignmentId: ArrayDescriptor[int] + pivotButton: ArrayDescriptor[int] + quotePrefix: ArrayDescriptor[int] + xfId: ArrayDescriptor[int] + def __new__(cls, args: bytes | bytearray | Iterable[int] = [0, 0, 0, 0, 0, 0, 0, 0, 0]) -> Self: ... + def __hash__(self) -> int: ... # type: ignore[override] + def __copy__(self) -> StyleArray: ... + def __deepcopy__(self, memo: Unused) -> StyleArray: ... + +class CellStyle(Serialisable): + tagname: ClassVar[str] + numFmtId: Integer[Literal[False]] + fontId: Integer[Literal[False]] + fillId: Integer[Literal[False]] + borderId: Integer[Literal[False]] + xfId: Integer[Literal[True]] + quotePrefix: Bool[Literal[True]] + pivotButton: Bool[Literal[True]] + applyNumberFormat: Bool[Literal[True]] + applyFont: Bool[Literal[True]] + applyFill: Bool[Literal[True]] + applyBorder: Bool[Literal[True]] + # Overwritten by properties below + # applyAlignment: Bool[Literal[True]] + # applyProtection: Bool[Literal[True]] + alignment: Typed[Alignment, Literal[True]] + protection: Typed[Protection, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + numFmtId: ConvertibleToInt = 0, + fontId: ConvertibleToInt = 0, + fillId: ConvertibleToInt = 0, + borderId: ConvertibleToInt = 0, + xfId: ConvertibleToInt | None = None, + quotePrefix: _ConvertibleToBool | None = None, + pivotButton: _ConvertibleToBool | None = None, + applyNumberFormat: _ConvertibleToBool | None = None, + applyFont: _ConvertibleToBool | None = None, + applyFill: _ConvertibleToBool | None = None, + applyBorder: _ConvertibleToBool | None = None, + applyAlignment: Unused = None, + applyProtection: Unused = None, + alignment: Alignment | None = None, + protection: Protection | None = None, + extLst: Unused = None, + ) -> None: ... + def to_array(self): ... + @classmethod + def from_array(cls, style): ... + @property + def applyProtection(self) -> Literal[True] | None: ... + @property + def applyAlignment(self) -> Literal[True] | None: ... + +class CellStyleList(Serialisable): + tagname: ClassVar[str] + __attrs__: ClassVar[tuple[str, ...]] + # Overwritten by property below + # count: Integer + xf: Incomplete + alignment: Incomplete + protection: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, xf=()) -> None: ... + @property + def count(self) -> int: ... + def __getitem__(self, idx): ... diff --git a/stubs/openpyxl/openpyxl/styles/colors.pyi b/stubs/openpyxl/openpyxl/styles/colors.pyi new file mode 100644 index 000000000000..be92324686c0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/colors.pyi @@ -0,0 +1,95 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from collections.abc import Iterator +from re import Pattern +from typing import ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Self + +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.base import _N, Bool, Integer, MinMax, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_S = TypeVar("_S", bound=Serialisable) + +COLOR_INDEX: Final[tuple[str, ...]] +BLACK: Final = "00000000" +WHITE: Final = "00FFFFFF" +BLUE: Final = "000000FF" +aRGB_REGEX: Final[Pattern[str]] + +class RGB(Typed[str, _N]): + expected_type: type[str] + + @overload + def __init__(self: RGB[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: RGB[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + @overload + def __set__(self: RGB[Literal[True]], instance: Serialisable | Strict, value: str | None) -> None: ... + @overload + def __set__(self: RGB[Literal[False]], instance: Serialisable | Strict, value: str) -> None: ... + +class Color(Serialisable): + tagname: ClassVar[str] + rgb: RGB[Literal[False]] + indexed: Integer[Literal[False]] + auto: Bool[Literal[False]] + theme: Integer[Literal[False]] + tint: MinMax[float, Literal[False]] + type: String[Literal[False]] + def __init__( + self, + rgb="00000000", + indexed: ConvertibleToInt | None = None, + auto: _ConvertibleToBool | None = None, + theme: ConvertibleToInt | None = None, + tint: ConvertibleToFloat = 0.0, + index: ConvertibleToInt | None = None, + type: Unused = "rgb", + ) -> None: ... + + @property + def value(self) -> str | int | bool: ... + @value.setter + def value(self, value: str | ConvertibleToInt | _ConvertibleToBool) -> None: ... + + def __iter__(self) -> Iterator[tuple[str, str]]: ... + @property + def index(self) -> str | int | bool: ... + + @overload + def __add__(self, other: Color) -> Self: ... + @overload + def __add__(self, other: _S) -> _S: ... + +class ColorDescriptor(Typed[Color, _N]): + expected_type: type[Color] + + @overload + def __init__(self: ColorDescriptor[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__( + self: ColorDescriptor[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False + ) -> None: ... + + @overload + def __set__(self: ColorDescriptor[Literal[True]], instance: Serialisable | Strict, value: str | Color | None) -> None: ... + @overload + def __set__(self: ColorDescriptor[Literal[False]], instance: Serialisable | Strict, value: str | Color) -> None: ... + +class RgbColor(Serialisable): + tagname: ClassVar[str] + rgb: RGB[Literal[False]] + def __init__(self, rgb: str) -> None: ... + +class ColorList(Serialisable): + tagname: ClassVar[str] + indexedColors: Incomplete + mruColors: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, indexedColors: list[RgbColor] | tuple[RgbColor, ...] = (), mruColors: list[Color] | tuple[Color, ...] = () + ) -> None: ... + def __bool__(self) -> bool: ... + @property + def index(self) -> list[str]: ... diff --git a/stubs/openpyxl/openpyxl/styles/differential.pyi b/stubs/openpyxl/openpyxl/styles/differential.pyi new file mode 100644 index 000000000000..aacdc31ef7b0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/differential.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, SupportsIndex + +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles import Alignment, Border, Fill, Font, Protection +from openpyxl.styles.numbers import NumberFormat + +class DifferentialStyle(Serialisable): + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + font: Typed[Font, Literal[True]] + numFmt: Typed[NumberFormat, Literal[True]] + fill: Typed[Fill, Literal[True]] + alignment: Typed[Alignment, Literal[True]] + border: Typed[Border, Literal[True]] + protection: Typed[Protection, Literal[True]] + extLst: ExtensionList | None + def __init__( + self, + font: Font | None = None, + numFmt: NumberFormat | None = None, + fill: Fill | None = None, + alignment: Alignment | None = None, + border: Border | None = None, + protection: Protection | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class DifferentialStyleList(Serialisable): + tagname: ClassVar[str] + dxf: Incomplete + styles: Alias + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, dxf=(), count: Unused = None) -> None: ... + def append(self, dxf: DifferentialStyle) -> None: ... + def add(self, dxf: DifferentialStyle) -> int: ... + def __bool__(self) -> bool: ... + def __getitem__(self, idx: SupportsIndex) -> DifferentialStyle: ... + @property + def count(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/styles/fills.pyi b/stubs/openpyxl/openpyxl/styles/fills.pyi new file mode 100644 index 000000000000..498f9d1a7c15 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/fills.pyi @@ -0,0 +1,117 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from collections.abc import Iterable, Iterator, Sequence as ABCSequence +from typing import ClassVar, Final, Literal, TypeAlias + +from openpyxl.descriptors import Sequence, Strict +from openpyxl.descriptors.base import Alias, Float, MinMax, NoneSet, Set +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _SupportsIterAndAttribAndTextAndTag + +FILL_NONE: Final = "none" +FILL_SOLID: Final = "solid" +FILL_PATTERN_DARKDOWN: Final = "darkDown" +FILL_PATTERN_DARKGRAY: Final = "darkGray" +FILL_PATTERN_DARKGRID: Final = "darkGrid" +FILL_PATTERN_DARKHORIZONTAL: Final = "darkHorizontal" +FILL_PATTERN_DARKTRELLIS: Final = "darkTrellis" +FILL_PATTERN_DARKUP: Final = "darkUp" +FILL_PATTERN_DARKVERTICAL: Final = "darkVertical" +FILL_PATTERN_GRAY0625: Final = "gray0625" +FILL_PATTERN_GRAY125: Final = "gray125" +FILL_PATTERN_LIGHTDOWN: Final = "lightDown" +FILL_PATTERN_LIGHTGRAY: Final = "lightGray" +FILL_PATTERN_LIGHTGRID: Final = "lightGrid" +FILL_PATTERN_LIGHTHORIZONTAL: Final = "lightHorizontal" +FILL_PATTERN_LIGHTTRELLIS: Final = "lightTrellis" +FILL_PATTERN_LIGHTUP: Final = "lightUp" +FILL_PATTERN_LIGHTVERTICAL: Final = "lightVertical" +FILL_PATTERN_MEDIUMGRAY: Final = "mediumGray" + +_GradientFillType: TypeAlias = Literal["linear", "path"] +_FillsType: TypeAlias = Literal[ + "solid", + "darkDown", + "darkGray", + "darkGrid", + "darkHorizontal", + "darkTrellis", + "darkUp", + "darkVertical", + "gray0625", + "gray125", + "lightDown", + "lightGray", + "lightGrid", + "lightHorizontal", + "lightTrellis", + "lightUp", + "lightVertical", + "mediumGray", +] +fills: Final[tuple[_FillsType, ...]] + +class Fill(Serialisable): + tagname: ClassVar[str] + @classmethod + def from_tree(cls, el: Iterable[ABCSequence[_SupportsIterAndAttribAndTextAndTag]]) -> PatternFill | GradientFill | None: ... + +class PatternFill(Fill): + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + patternType: NoneSet[_FillsType] + fill_type: Alias + fgColor: ColorDescriptor[Literal[False]] + start_color: Alias + bgColor: ColorDescriptor[Literal[False]] + end_color: Alias + def __init__( + self, + patternType: _FillsType | Literal["none"] | None = None, + fgColor: str | Color = ..., + bgColor: str | Color = ..., + fill_type: _FillsType | Literal["none"] | None = None, + start_color: str | Color | None = None, + end_color: str | Color | None = None, + ) -> None: ... + def to_tree(self, tagname: Unused = None, idx: Unused = None) -> Element: ... # type: ignore[override] + +DEFAULT_EMPTY_FILL: Final[PatternFill] +DEFAULT_GRAY_FILL: Final[PatternFill] + +class Stop(Serialisable): + tagname: ClassVar[str] + position: MinMax[float, Literal[False]] + color: Incomplete + def __init__(self, color, position: ConvertibleToFloat) -> None: ... + +class StopList(Sequence[list[Stop]]): + expected_type: type[Stop] + def __set__(self, obj: Serialisable | Strict, values: list[Stop] | tuple[Stop, ...]) -> None: ... + +class GradientFill(Fill): + tagname: ClassVar[str] + type: Set[_GradientFillType] + fill_type: Alias + degree: Float[Literal[False]] + left: Float[Literal[False]] + right: Float[Literal[False]] + top: Float[Literal[False]] + bottom: Float[Literal[False]] + stop: Incomplete + def __init__( + self, + type: _GradientFillType = "linear", + degree: ConvertibleToFloat = 0, + left: ConvertibleToFloat = 0, + right: ConvertibleToFloat = 0, + top: ConvertibleToFloat = 0, + bottom: ConvertibleToFloat = 0, + stop=(), + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def to_tree( # type: ignore[override] + self, tagname: Unused = None, namespace: Unused = None, idx: Unused = None + ) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/styles/fonts.pyi b/stubs/openpyxl/openpyxl/styles/fonts.pyi new file mode 100644 index 000000000000..48aeeb27d9b3 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/fonts.pyi @@ -0,0 +1,77 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt +from typing import ClassVar, Final, Literal, TypeAlias +from typing_extensions import Self + +from openpyxl.descriptors.base import Alias, _ConvertibleToBool +from openpyxl.descriptors.nested import ( + NestedBool, + NestedFloat, + NestedInteger, + NestedMinMax, + NestedNoneSet, + NestedString, + _NestedNoneSetParam, +) +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor + +from ..xml._functions_overloads import _HasTagAndGet, _SupportsFindAndIterAndAttribAndText + +_FontU: TypeAlias = Literal["single", "double", "singleAccounting", "doubleAccounting"] +_FontVertAlign: TypeAlias = Literal["superscript", "subscript", "baseline"] +_FontScheme: TypeAlias = Literal["major", "minor"] + +class Font(Serialisable): + UNDERLINE_DOUBLE: Final = "double" + UNDERLINE_DOUBLE_ACCOUNTING: Final = "doubleAccounting" + UNDERLINE_SINGLE: Final = "single" + UNDERLINE_SINGLE_ACCOUNTING: Final = "singleAccounting" + name: NestedString[Literal[True]] + charset: NestedInteger[Literal[True]] + family: NestedMinMax[float, Literal[True]] + sz: NestedFloat[Literal[True]] + size: Alias + b: NestedBool[Literal[False]] + bold: Alias + i: NestedBool[Literal[False]] + italic: Alias + strike: NestedBool[Literal[True]] + strikethrough: Alias + outline: NestedBool[Literal[True]] + shadow: NestedBool[Literal[True]] + condense: NestedBool[Literal[True]] + extend: NestedBool[Literal[True]] + u: NestedNoneSet[_FontU] + underline: Alias + vertAlign: NestedNoneSet[_FontVertAlign] + color: ColorDescriptor[Literal[True]] + scheme: NestedNoneSet[_FontScheme] + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: object = None, + sz: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + b: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + i: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + charset: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + u: _NestedNoneSetParam[_FontU] = None, + strike: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + color: str | Color | None = None, + scheme: _NestedNoneSetParam[_FontScheme] = None, + family: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + size: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat | None = None, + bold: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool | None = None, + italic: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool | None = None, + strikethrough: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool | None = None, + underline: _NestedNoneSetParam[_FontU] = None, + vertAlign: _NestedNoneSetParam[_FontVertAlign] = None, + outline: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + shadow: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + condense: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extend: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ) -> None: ... + @classmethod + def from_tree(cls, node: _SupportsFindAndIterAndAttribAndText) -> Self: ... + +DEFAULT_FONT: Final[Font] diff --git a/stubs/openpyxl/openpyxl/styles/named_styles.pyi b/stubs/openpyxl/openpyxl/styles/named_styles.pyi new file mode 100644 index 000000000000..13af11fa42d8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/named_styles.pyi @@ -0,0 +1,83 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Iterable, Iterator +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.sequence import Sequence +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.alignment import Alignment +from openpyxl.styles.borders import Border +from openpyxl.styles.cell_style import CellStyle, StyleArray +from openpyxl.styles.fills import Fill +from openpyxl.styles.fonts import Font +from openpyxl.styles.protection import Protection +from openpyxl.workbook.workbook import Workbook + +class NamedStyle(Serialisable): + font: Typed[Font, Literal[False]] + fill: Typed[Fill, Literal[False]] + border: Typed[Border, Literal[False]] + alignment: Typed[Alignment, Literal[False]] + number_format: Incomplete + protection: Typed[Protection, Literal[False]] + builtinId: Integer[Literal[True]] + hidden: Bool[Literal[True]] + name: String[Literal[False]] + def __init__( + self, + name: str = "Normal", + font: Font | None = None, + fill: Fill | None = None, + border: Border | None = None, + alignment: Alignment | None = None, + number_format=None, + protection: Protection | None = None, + builtinId: ConvertibleToInt | None = None, + hidden: _ConvertibleToBool | None = False, + ) -> None: ... + def __setattr__(self, attr: str, value) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def bind(self, wb: Workbook) -> None: ... + def as_tuple(self) -> StyleArray: ... + def as_xf(self) -> CellStyle: ... + def as_name(self) -> _NamedCellStyle: ... + +class NamedStyleList(list[NamedStyle]): + def __init__(self, iterable: Iterable[NamedStyle] = ()) -> None: ... + @property + def names(self) -> list[str]: ... + def __getitem__(self, key: int | str) -> NamedStyle: ... # type: ignore[override] + def append(self, style: NamedStyle) -> None: ... + +class _NamedCellStyle(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + xfId: Integer[Literal[False]] + builtinId: Integer[Literal[True]] + iLevel: Integer[Literal[True]] + hidden: Bool[Literal[True]] + customBuiltin: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + xfId: ConvertibleToInt, + builtinId: ConvertibleToInt | None = None, + iLevel: ConvertibleToInt | None = None, + hidden: _ConvertibleToBool | None = None, + customBuiltin: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class _NamedCellStyleList(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer[Literal[True]] + cellStyle: Sequence[list[_NamedCellStyle]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, cellStyle: list[_NamedCellStyle] | tuple[_NamedCellStyle, ...] = ()) -> None: ... + @property + def count(self) -> int: ... + def remove_duplicates(self) -> list[_NamedCellStyle]: ... diff --git a/stubs/openpyxl/openpyxl/styles/numbers.pyi b/stubs/openpyxl/openpyxl/styles/numbers.pyi new file mode 100644 index 000000000000..abadbf89e764 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/numbers.pyi @@ -0,0 +1,86 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from re import Pattern +from typing import ClassVar, Final, Literal, SupportsIndex, TypeGuard, overload + +from openpyxl.descriptors import Strict, String +from openpyxl.descriptors.base import Integer +from openpyxl.descriptors.serialisable import Serialisable + +BUILTIN_FORMATS: Final[dict[int, str]] +BUILTIN_FORMATS_MAX_SIZE: Final = 164 +BUILTIN_FORMATS_REVERSE: Final[dict[str, int]] +FORMAT_GENERAL: Final = "General" +FORMAT_TEXT: Final = "@" +FORMAT_NUMBER: Final = "0" +FORMAT_NUMBER_00: Final = "0.00" +FORMAT_NUMBER_COMMA_SEPARATED1: Final = "#,##0.00" +FORMAT_NUMBER_COMMA_SEPARATED2: Final = "#,##0.00_-" +FORMAT_PERCENTAGE: Final = "0%" +FORMAT_PERCENTAGE_00: Final = "0.00%" +FORMAT_DATE_YYYYMMDD2: Final = "yyyy-mm-dd" +FORMAT_DATE_YYMMDD: Final = "yy-mm-dd" +FORMAT_DATE_DDMMYY: Final = "dd/mm/yy" +FORMAT_DATE_DMYSLASH: Final = "d/m/y" +FORMAT_DATE_DMYMINUS: Final = "d-m-y" +FORMAT_DATE_DMMINUS: Final = "d-m" +FORMAT_DATE_MYMINUS: Final = "m-y" +FORMAT_DATE_XLSX14: Final = "mm-dd-yy" +FORMAT_DATE_XLSX15: Final = "d-mmm-yy" +FORMAT_DATE_XLSX16: Final = "d-mmm" +FORMAT_DATE_XLSX17: Final = "mmm-yy" +FORMAT_DATE_XLSX22: Final = "m/d/yy h:mm" +FORMAT_DATE_DATETIME: Final = "yyyy-mm-dd h:mm:ss" +FORMAT_DATE_TIME1: Final = "h:mm AM/PM" +FORMAT_DATE_TIME2: Final = "h:mm:ss AM/PM" +FORMAT_DATE_TIME3: Final = "h:mm" +FORMAT_DATE_TIME4: Final = "h:mm:ss" +FORMAT_DATE_TIME5: Final = "mm:ss" +FORMAT_DATE_TIME6: Final = "h:mm:ss" +FORMAT_DATE_TIME7: Final = "i:s.S" +FORMAT_DATE_TIME8: Final = "h:mm:ss@" +FORMAT_DATE_TIMEDELTA: Final = "[hh]:mm:ss" +FORMAT_DATE_YYMMDDSLASH: Final = "yy/mm/dd@" +FORMAT_CURRENCY_USD_SIMPLE: Final = '"$"#,##0.00_-' +FORMAT_CURRENCY_USD: Final = "$#,##0_-" +FORMAT_CURRENCY_EUR_SIMPLE: Final = "[$EUR ]#,##0.00_-" + +COLORS: Final[str] +LITERAL_GROUP: Final = r'".*?"' +LOCALE_GROUP: Final = r"\[(?!hh?\]|mm?\]|ss?\])[^\]]*\]" +STRIP_RE: Final[Pattern[str]] +TIMEDELTA_RE: Final[Pattern[str]] + +def is_date_format(fmt: str | None) -> TypeGuard[str]: ... +def is_timedelta_format(fmt: str | None) -> TypeGuard[str]: ... + +@overload +def is_datetime(fmt: None) -> None: ... +@overload +def is_datetime(fmt: str) -> Literal["datetime", "date", "time"] | None: ... + +def is_builtin(fmt: str | None) -> TypeGuard[str]: ... +def builtin_format_code(index: int) -> str | None: ... + +@overload +def builtin_format_id(fmt: None) -> None: ... +@overload +def builtin_format_id(fmt: str) -> int | None: ... + +class NumberFormatDescriptor(String[Incomplete]): + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class NumberFormat(Serialisable): + numFmtId: Integer[Literal[False]] + formatCode: String[Literal[False]] + def __init__(self, numFmtId: ConvertibleToInt, formatCode: str) -> None: ... + +class NumberFormatList(Serialisable): + # Overwritten by property below + # count: Integer + numFmt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, numFmt=()) -> None: ... + @property + def count(self) -> int: ... + def __getitem__(self, idx: SupportsIndex) -> NumberFormat: ... diff --git a/stubs/openpyxl/openpyxl/styles/protection.pyi b/stubs/openpyxl/openpyxl/styles/protection.pyi new file mode 100644 index 000000000000..8d4652f2e5b0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/protection.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Protection(Serialisable): + tagname: ClassVar[str] + locked: Bool[Literal[False]] + hidden: Bool[Literal[False]] + def __init__(self, locked: _ConvertibleToBool = True, hidden: _ConvertibleToBool = False) -> None: ... diff --git a/stubs/openpyxl/openpyxl/styles/proxy.pyi b/stubs/openpyxl/openpyxl/styles/proxy.pyi new file mode 100644 index 000000000000..1fd18127d71e --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/proxy.pyi @@ -0,0 +1,13 @@ +from typing_extensions import deprecated + +class StyleProxy: + __slots__ = "__target" + def __init__(self, target) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def __copy__(self): ... + def __add__(self, other): ... + @deprecated("Use copy(obj) or cell.obj = cell.obj + other") + def copy(self, **kw): ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/styles/styleable.pyi b/stubs/openpyxl/openpyxl/styles/styleable.pyi new file mode 100644 index 000000000000..1601d769d14b --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/styleable.pyi @@ -0,0 +1,54 @@ +from _typeshed import Unused +from collections.abc import Iterable + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet + +from .named_styles import NamedStyle +from .proxy import StyleProxy + +class StyleDescriptor: + collection: str + key: str + def __init__(self, collection: str, key: str) -> None: ... + def __set__(self, instance: StyleableObject, value: Serialisable) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> StyleProxy: ... + +class NumberFormatDescriptor: + key: str + collection: str + def __set__(self, instance: StyleableObject, value: str) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> str: ... + +class NamedStyleDescriptor: + key: str + collection: str + def __set__(self, instance: StyleableObject, value: NamedStyle | str) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> str: ... + +class StyleArrayDescriptor: + key: str + def __init__(self, key: str) -> None: ... + def __set__(self, instance: StyleableObject, value: int) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> bool: ... + +class StyleableObject: + __slots__ = ("parent", "_style") + font: StyleDescriptor + fill: StyleDescriptor + border: StyleDescriptor + number_format: NumberFormatDescriptor + protection: StyleDescriptor + alignment: StyleDescriptor + style: NamedStyleDescriptor + quotePrefix: StyleArrayDescriptor + pivotButton: StyleArrayDescriptor + parent: _WorkbookChild | ReadOnlyWorksheet + def __init__( + self, sheet: _WorkbookChild | ReadOnlyWorksheet, style_array: bytes | bytearray | Iterable[int] | None = None + ) -> None: ... + @property + def style_id(self) -> int: ... + @property + def has_style(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/styles/stylesheet.pyi b/stubs/openpyxl/openpyxl/styles/stylesheet.pyi new file mode 100644 index 000000000000..c977920767fa --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/stylesheet.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeVar +from typing_extensions import Self +from zipfile import ZipFile + +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.styles.cell_style import CellStyleList +from openpyxl.styles.colors import ColorList +from openpyxl.styles.named_styles import _NamedCellStyleList +from openpyxl.styles.numbers import NumberFormatList +from openpyxl.styles.table import TableStyleList +from openpyxl.workbook.workbook import Workbook +from openpyxl.xml.functions import Element + +_WorkbookT = TypeVar("_WorkbookT", bound=Workbook) + +class Stylesheet(Serialisable): + tagname: ClassVar[str] + numFmts: Typed[NumberFormatList, Literal[False]] + fonts: Incomplete + fills: Incomplete + borders: Incomplete + cellStyleXfs: Typed[CellStyleList, Literal[False]] + cellXfs: Typed[CellStyleList, Literal[False]] + cellStyles: Typed[_NamedCellStyleList, Literal[False]] + dxfs: Incomplete + tableStyles: Typed[TableStyleList, Literal[True]] + colors: Typed[ColorList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + number_formats: Incomplete + cell_styles: Incomplete + alignments: Incomplete + protections: Incomplete + named_styles: Incomplete + def __init__( + self, + numFmts: NumberFormatList | None = None, + fonts=(), + fills=(), + borders=(), + cellStyleXfs: CellStyleList | None = None, + cellXfs: CellStyleList | None = None, + cellStyles: _NamedCellStyleList | None = None, + dxfs=(), + tableStyles: TableStyleList | None = None, + colors: ColorList | None = None, + extLst: Unused = None, + ) -> None: ... + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + @property + def custom_formats(self) -> dict[int, str]: ... + def to_tree(self, tagname: str | None = None, idx: Unused = None, namespace: str | None = None) -> Element: ... + +def apply_stylesheet(archive: ZipFile, wb: _WorkbookT) -> _WorkbookT | None: ... +def write_stylesheet(wb: Workbook): ... diff --git a/stubs/openpyxl/openpyxl/styles/table.pyi b/stubs/openpyxl/openpyxl/styles/table.pyi new file mode 100644 index 000000000000..03e629854e3c --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/table.pyi @@ -0,0 +1,79 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, Integer, Set, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_TableStyleElementType: TypeAlias = Literal[ + "wholeTable", + "headerRow", + "totalRow", + "firstColumn", + "lastColumn", + "firstRowStripe", + "secondRowStripe", + "firstColumnStripe", + "secondColumnStripe", + "firstHeaderCell", + "lastHeaderCell", + "firstTotalCell", + "lastTotalCell", + "firstSubtotalColumn", + "secondSubtotalColumn", + "thirdSubtotalColumn", + "firstSubtotalRow", + "secondSubtotalRow", + "thirdSubtotalRow", + "blankRow", + "firstColumnSubheading", + "secondColumnSubheading", + "thirdColumnSubheading", + "firstRowSubheading", + "secondRowSubheading", + "thirdRowSubheading", + "pageFieldLabels", + "pageFieldValues", +] + +class TableStyleElement(Serialisable): + tagname: ClassVar[str] + type: Set[_TableStyleElementType] + size: Integer[Literal[True]] + dxfId: Integer[Literal[True]] + def __init__( + self, type: _TableStyleElementType, size: ConvertibleToInt | None = None, dxfId: ConvertibleToInt | None = None + ) -> None: ... + +class TableStyle(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + pivot: Bool[Literal[True]] + table: Bool[Literal[True]] + count: Integer[Literal[True]] + tableStyleElement: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + pivot: _ConvertibleToBool | None = None, + table: _ConvertibleToBool | None = None, + count: ConvertibleToInt | None = None, + tableStyleElement=(), + ) -> None: ... + +class TableStyleList(Serialisable): + tagname: ClassVar[str] + defaultTableStyle: String[Literal[True]] + defaultPivotStyle: String[Literal[True]] + tableStyle: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + count: Unused = None, + defaultTableStyle: str | None = "TableStyleMedium9", + defaultPivotStyle: str | None = "PivotStyleLight16", + tableStyle=(), + ) -> None: ... + @property + def count(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/utils/__init__.pyi b/stubs/openpyxl/openpyxl/utils/__init__.pyi new file mode 100644 index 000000000000..ba45939538be --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/__init__.pyi @@ -0,0 +1,13 @@ +from .cell import ( + absolute_coordinate as absolute_coordinate, + cols_from_range as cols_from_range, + column_index_from_string as column_index_from_string, + coordinate_to_tuple as coordinate_to_tuple, + get_column_interval as get_column_interval, + get_column_letter as get_column_letter, + quote_sheetname as quote_sheetname, + range_boundaries as range_boundaries, + range_to_tuple as range_to_tuple, + rows_from_range as rows_from_range, +) +from .formulas import FORMULAE as FORMULAE diff --git a/stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi b/stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi new file mode 100644 index 000000000000..c4556fa4bb90 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi @@ -0,0 +1,9 @@ +from collections import defaultdict +from typing import TypeVar + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +class BoundDictionary(defaultdict[_KT, _VT]): + reference: str | None + def __init__(self, reference: str | None = None, *args, **kw) -> None: ... diff --git a/stubs/openpyxl/openpyxl/utils/cell.pyi b/stubs/openpyxl/openpyxl/utils/cell.pyi new file mode 100644 index 000000000000..cb26c68f39be --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/cell.pyi @@ -0,0 +1,26 @@ +from collections.abc import Generator +from re import Pattern +from typing import Final, TypeAlias + +# "1:1" | "A1:A1" | "A:A" +_RangeBoundariesTuple: TypeAlias = tuple[None, int, None, int] | tuple[int, int, int, int] | tuple[int, None, int, None] + +COORD_RE: Final[Pattern[str]] +COL_RANGE: Final = "[A-Z]{1,3}:[A-Z]{1,3}:" +ROW_RANGE: Final = r"\d+:\d+:" +RANGE_EXPR: Final[str] +ABSOLUTE_RE: Final[Pattern[str]] +SHEET_TITLE: Final[str] +SHEETRANGE_RE: Final[Pattern[str]] + +def get_column_interval(start: str | int, end: str | int) -> list[str]: ... +def coordinate_from_string(coord_string: str) -> tuple[str, int]: ... +def absolute_coordinate(coord_string: str) -> str: ... +def get_column_letter(col_idx: int) -> str: ... +def column_index_from_string(col: str) -> int: ... +def range_boundaries(range_string: str) -> _RangeBoundariesTuple: ... +def rows_from_range(range_string: str) -> Generator[tuple[str, ...]]: ... +def cols_from_range(range_string: str) -> Generator[tuple[str, ...]]: ... +def coordinate_to_tuple(coordinate: str) -> tuple[int, int]: ... +def range_to_tuple(range_string: str) -> tuple[str, _RangeBoundariesTuple]: ... +def quote_sheetname(sheetname: str) -> str: ... diff --git a/stubs/openpyxl/openpyxl/utils/dataframe.pyi b/stubs/openpyxl/openpyxl/utils/dataframe.pyi new file mode 100644 index 000000000000..592aded19426 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/dataframe.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +def dataframe_to_rows(df, index: bool = True, header: bool = True) -> Generator[Incomplete]: ... +def expand_index(index, header: bool = False) -> Generator[Incomplete]: ... diff --git a/stubs/openpyxl/openpyxl/utils/datetime.pyi b/stubs/openpyxl/openpyxl/utils/datetime.pyi new file mode 100644 index 000000000000..ecb645ccb656 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/datetime.pyi @@ -0,0 +1,21 @@ +from datetime import datetime +from re import Pattern +from typing import Final + +MAC_EPOCH: Final[datetime] +WINDOWS_EPOCH: Final[datetime] +# The following two constants are defined twice in the implementation. +CALENDAR_WINDOWS_1900 = WINDOWS_EPOCH +CALENDAR_MAC_1904 = MAC_EPOCH +SECS_PER_DAY: Final = 86400 +ISO_FORMAT: Final = "%Y-%m-%dT%H:%M:%SZ" +ISO_REGEX: Final[Pattern[str]] +ISO_DURATION: Final[Pattern[str]] + +def to_ISO8601(dt): ... +def from_ISO8601(formatted_string): ... +def to_excel(dt, epoch=...): ... +def from_excel(value, epoch=..., timedelta: bool = False): ... +def time_to_days(value): ... +def timedelta_to_days(value): ... +def days_to_time(value): ... diff --git a/stubs/openpyxl/openpyxl/utils/escape.pyi b/stubs/openpyxl/openpyxl/utils/escape.pyi new file mode 100644 index 000000000000..0ad3a1008f0a --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/escape.pyi @@ -0,0 +1,2 @@ +def escape(value: str) -> str: ... +def unescape(value: str) -> str: ... diff --git a/stubs/openpyxl/openpyxl/utils/exceptions.pyi b/stubs/openpyxl/openpyxl/utils/exceptions.pyi new file mode 100644 index 000000000000..5e9ebead8950 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/exceptions.pyi @@ -0,0 +1,7 @@ +class CellCoordinatesException(Exception): ... +class IllegalCharacterError(Exception): ... +class NamedRangeException(Exception): ... +class SheetTitleException(Exception): ... +class InvalidFileException(Exception): ... +class ReadOnlyWorkbookException(Exception): ... +class WorkbookAlreadySaved(Exception): ... diff --git a/stubs/openpyxl/openpyxl/utils/formulas.pyi b/stubs/openpyxl/openpyxl/utils/formulas.pyi new file mode 100644 index 000000000000..ea7f2d97bc85 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/formulas.pyi @@ -0,0 +1,5 @@ +from typing import Final + +FORMULAE: Final[frozenset[str]] + +def validate(formula: str) -> None: ... diff --git a/stubs/openpyxl/openpyxl/utils/indexed_list.pyi b/stubs/openpyxl/openpyxl/utils/indexed_list.pyi new file mode 100644 index 000000000000..9bf453a0468b --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/indexed_list.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from typing import TypeVar + +_T = TypeVar("_T") + +class IndexedList(list[_T]): + clean: bool + def __init__(self, iterable: Iterable[_T] | None = None) -> None: ... + def __contains__(self, value: object) -> bool: ... + def index(self, value: _T) -> int: ... # type: ignore[override] + def append(self, value: _T) -> None: ... + def add(self, value: _T) -> int: ... diff --git a/stubs/openpyxl/openpyxl/utils/inference.pyi b/stubs/openpyxl/openpyxl/utils/inference.pyi new file mode 100644 index 000000000000..5787b6f19652 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/inference.pyi @@ -0,0 +1,10 @@ +from re import Pattern +from typing import Final + +PERCENT_REGEX: Final[Pattern[str]] +TIME_REGEX: Final[Pattern[str]] +NUMBER_REGEX: Final[Pattern[str]] + +def cast_numeric(value): ... +def cast_percentage(value): ... +def cast_time(value): ... diff --git a/stubs/openpyxl/openpyxl/utils/protection.pyi b/stubs/openpyxl/openpyxl/utils/protection.pyi new file mode 100644 index 000000000000..4bcddbe2b676 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/protection.pyi @@ -0,0 +1 @@ +def hash_password(plaintext_password: str = "") -> str: ... diff --git a/stubs/openpyxl/openpyxl/utils/units.pyi b/stubs/openpyxl/openpyxl/utils/units.pyi new file mode 100644 index 000000000000..6a799ed06424 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/units.pyi @@ -0,0 +1,24 @@ +from typing import Final + +DEFAULT_ROW_HEIGHT: Final[float] +BASE_COL_WIDTH: Final = 8 +DEFAULT_COLUMN_WIDTH: Final = 13 +DEFAULT_LEFT_MARGIN: Final[float] +DEFAULT_TOP_MARGIN: Final[float] +DEFAULT_HEADER: Final[float] + +def inch_to_dxa(value): ... +def dxa_to_inch(value): ... +def dxa_to_cm(value): ... +def cm_to_dxa(value): ... +def pixels_to_EMU(value): ... +def EMU_to_pixels(value): ... +def cm_to_EMU(value): ... +def EMU_to_cm(value): ... +def inch_to_EMU(value): ... +def EMU_to_inch(value): ... +def pixels_to_points(value, dpi: int = 96): ... +def points_to_pixels(value, dpi: int = 96): ... +def degrees_to_angle(value): ... +def angle_to_degrees(value): ... +def short_color(color): ... diff --git a/stubs/openpyxl/openpyxl/workbook/__init__.pyi b/stubs/openpyxl/openpyxl/workbook/__init__.pyi new file mode 100644 index 000000000000..af0aa0b81088 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/__init__.pyi @@ -0,0 +1 @@ +from .workbook import Workbook as Workbook diff --git a/stubs/openpyxl/openpyxl/workbook/_writer.pyi b/stubs/openpyxl/openpyxl/workbook/_writer.pyi new file mode 100644 index 000000000000..40e639a58d32 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/_writer.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from openpyxl.workbook.workbook import Workbook + +def get_active_sheet(wb: Workbook) -> int | None: ... + +class WorkbookWriter: + wb: Workbook + rels: Incomplete + package: Incomplete + def __init__(self, wb: Workbook) -> None: ... + def write_properties(self) -> None: ... + def write_worksheets(self) -> None: ... + def write_refs(self) -> None: ... + def write_names(self) -> None: ... + def write_pivots(self) -> None: ... + def write_views(self) -> None: ... + def write(self): ... + def write_rels(self): ... + def write_root_rels(self): ... diff --git a/stubs/openpyxl/openpyxl/workbook/child.pyi b/stubs/openpyxl/openpyxl/workbook/child.pyi new file mode 100644 index 000000000000..7e9df7c885a1 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/child.pyi @@ -0,0 +1,57 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Final + +from openpyxl import _Decodable +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.header_footer import HeaderFooter, HeaderFooterItem + +INVALID_TITLE_REGEX: Final[Pattern[str]] + +def avoid_duplicate_name(names: Iterable[str], value: str) -> str: ... + +class _WorkbookChild: + HeaderFooter: HeaderFooter + def __init__(self, parent: Workbook | None = None, title: str | _Decodable | None = None) -> None: ... + @property + def parent(self) -> Workbook | None: ... + @property + def encoding(self) -> str: ... # Will error without a parent. + + @property + def title(self) -> str: ... + @title.setter + def title(self, value: str | _Decodable) -> None: ... + + @property + def oddHeader(self) -> HeaderFooterItem | None: ... + @oddHeader.setter + def oddHeader(self, value: HeaderFooterItem | None) -> None: ... + + @property + def oddFooter(self) -> HeaderFooterItem | None: ... + @oddFooter.setter + def oddFooter(self, value: HeaderFooterItem | None) -> None: ... + + @property + def evenHeader(self) -> HeaderFooterItem | None: ... + @evenHeader.setter + def evenHeader(self, value: HeaderFooterItem | None) -> None: ... + + @property + def evenFooter(self) -> HeaderFooterItem | None: ... + @evenFooter.setter + def evenFooter(self, value: HeaderFooterItem | None) -> None: ... + + @property + def firstHeader(self) -> HeaderFooterItem | None: ... + @firstHeader.setter + def firstHeader(self, value: HeaderFooterItem | None) -> None: ... + + @property + def firstFooter(self) -> HeaderFooterItem | None: ... + @firstFooter.setter + def firstFooter(self, value: HeaderFooterItem | None) -> None: ... + + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/workbook/defined_name.pyi b/stubs/openpyxl/openpyxl/workbook/defined_name.pyi new file mode 100644 index 000000000000..aa8780463371 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/defined_name.pyi @@ -0,0 +1,71 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections import defaultdict +from collections.abc import Generator, Iterator +from re import Pattern +from typing import ClassVar, Final, Literal + +from openpyxl.descriptors import Sequence +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.formula.tokenizer import _TokenOperandSubtypes, _TokenTypesNotOperand + +RESERVED: Final[frozenset[str]] +RESERVED_REGEX: Final[Pattern[str]] + +class DefinedName(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + comment: String[Literal[True]] + customMenu: String[Literal[True]] + description: String[Literal[True]] + help: String[Literal[True]] + statusBar: String[Literal[True]] + localSheetId: Integer[Literal[True]] + hidden: Bool[Literal[True]] + function: Bool[Literal[True]] + vbProcedure: Bool[Literal[True]] + xlm: Bool[Literal[True]] + functionGroupId: Integer[Literal[True]] + shortcutKey: String[Literal[True]] + publishToServer: Bool[Literal[True]] + workbookParameter: Bool[Literal[True]] + attr_text: Incomplete + value: Alias + def __init__( + self, + name: str, + comment: str | None = None, + customMenu: str | None = None, + description: str | None = None, + help: str | None = None, + statusBar: str | None = None, + localSheetId: ConvertibleToInt | None = None, + hidden: _ConvertibleToBool | None = None, + function: _ConvertibleToBool | None = None, + vbProcedure: _ConvertibleToBool | None = None, + xlm: _ConvertibleToBool | None = None, + functionGroupId: ConvertibleToInt | None = None, + shortcutKey: str | None = None, + publishToServer: _ConvertibleToBool | None = None, + workbookParameter: _ConvertibleToBool | None = None, + attr_text=None, + ) -> None: ... + @property + def type(self) -> _TokenTypesNotOperand | _TokenOperandSubtypes: ... + @property + def destinations(self) -> Generator[tuple[str, str]]: ... + @property + def is_reserved(self) -> str | None: ... + @property + def is_external(self) -> bool: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + +class DefinedNameDict(dict[str, DefinedName]): + def add(self, value: DefinedName) -> None: ... + +class DefinedNameList(Serialisable): + tagname: ClassVar[str] + definedName: Sequence[list[DefinedName]] + def __init__(self, definedName: list[DefinedName] | tuple[DefinedName, ...] = ()) -> None: ... + def by_sheet(self) -> defaultdict[int, DefinedNameDict]: ... + def __len__(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi b/stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi new file mode 100644 index 000000000000..37ef93721979 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi @@ -0,0 +1 @@ +from .external import ExternalLink as ExternalLink diff --git a/stubs/openpyxl/openpyxl/workbook/external_link/external.pyi b/stubs/openpyxl/openpyxl/workbook/external_link/external.pyi new file mode 100644 index 000000000000..32cbcbd7371e --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/external_link/external.pyi @@ -0,0 +1,80 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias +from zipfile import ZipFile + +from openpyxl.descriptors.base import Bool, Integer, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.packaging.relationship import Relationship +from openpyxl.xml.functions import Element + +_ExternalCellType: TypeAlias = Literal["b", "d", "n", "e", "s", "str", "inlineStr"] + +class ExternalCell(Serialisable): + r: String[Literal[False]] + t: NoneSet[_ExternalCellType] + vm: Integer[Literal[True]] + v: NestedText[str, Literal[True]] + def __init__( + self, r: str, t: _ExternalCellType | Literal["none"] | None = None, vm: ConvertibleToInt | None = None, v: object = None + ) -> None: ... + +class ExternalRow(Serialisable): + r: Integer[Literal[False]] + cell: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, r: ConvertibleToInt, cell=None) -> None: ... + +class ExternalSheetData(Serialisable): + sheetId: Integer[Literal[False]] + refreshError: Bool[Literal[True]] + row: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetId: ConvertibleToInt, refreshError: _ConvertibleToBool | None = None, row=()) -> None: ... + +class ExternalSheetDataSet(Serialisable): + sheetData: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetData=None) -> None: ... + +class ExternalSheetNames(Serialisable): + sheetName: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetName=()) -> None: ... + +class ExternalDefinedName(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + refersTo: String[Literal[True]] + sheetId: Integer[Literal[True]] + def __init__(self, name: str, refersTo: str | None = None, sheetId: ConvertibleToInt | None = None) -> None: ... + +class ExternalBook(Serialisable): + tagname: ClassVar[str] + sheetNames: Typed[ExternalSheetNames, Literal[True]] + definedNames: Incomplete + sheetDataSet: Typed[ExternalSheetDataSet, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + sheetNames: ExternalSheetNames | None = None, + definedNames=(), + sheetDataSet: ExternalSheetDataSet | None = None, + id=None, + ) -> None: ... + +class ExternalLink(Serialisable): + tagname: ClassVar[str] + mime_type: str + externalBook: Typed[ExternalBook, Literal[True]] + file_link: Typed[Relationship, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, externalBook: ExternalBook | None = None, ddeLink: Unused = None, oleLink: Unused = None, extLst: Unused = None + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... + +def read_external_link(archive: ZipFile, book_path: str) -> ExternalLink: ... diff --git a/stubs/openpyxl/openpyxl/workbook/external_reference.pyi b/stubs/openpyxl/openpyxl/workbook/external_reference.pyi new file mode 100644 index 000000000000..4b202d9ce5ee --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/external_reference.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class ExternalReference(Serialisable): + tagname: ClassVar[str] + id: Incomplete + def __init__(self, id) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/function_group.pyi b/stubs/openpyxl/openpyxl/workbook/function_group.pyi new file mode 100644 index 000000000000..48bc87d80b8d --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/function_group.pyi @@ -0,0 +1,17 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Integer, String +from openpyxl.descriptors.serialisable import Serialisable + +class FunctionGroup(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + def __init__(self, name: str) -> None: ... + +class FunctionGroupList(Serialisable): + tagname: ClassVar[str] + builtInGroupCount: Integer[Literal[True]] + functionGroup: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, builtInGroupCount: ConvertibleToInt | None = 16, functionGroup=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/properties.pyi b/stubs/openpyxl/openpyxl/workbook/properties.pyi new file mode 100644 index 000000000000..145df27bd4b5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/properties.pyi @@ -0,0 +1,102 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_WorkbookPropertiesShowObjects: TypeAlias = Literal["all", "placeholders"] +_WorkbookPropertiesUpdateLinks: TypeAlias = Literal["userSet", "never", "always"] +_CalcPropertiesCalcMode: TypeAlias = Literal["manual", "auto", "autoNoTable"] +_CalcPropertiesRefMode: TypeAlias = Literal["A1", "R1C1"] + +class WorkbookProperties(Serialisable): + tagname: ClassVar[str] + date1904: Bool[Literal[True]] + dateCompatibility: Bool[Literal[True]] + showObjects: NoneSet[_WorkbookPropertiesShowObjects] + showBorderUnselectedTables: Bool[Literal[True]] + filterPrivacy: Bool[Literal[True]] + promptedSolutions: Bool[Literal[True]] + showInkAnnotation: Bool[Literal[True]] + backupFile: Bool[Literal[True]] + saveExternalLinkValues: Bool[Literal[True]] + updateLinks: NoneSet[_WorkbookPropertiesUpdateLinks] + codeName: String[Literal[True]] + hidePivotFieldList: Bool[Literal[True]] + showPivotChartFilter: Bool[Literal[True]] + allowRefreshQuery: Bool[Literal[True]] + publishItems: Bool[Literal[True]] + checkCompatibility: Bool[Literal[True]] + autoCompressPictures: Bool[Literal[True]] + refreshAllConnections: Bool[Literal[True]] + defaultThemeVersion: Integer[Literal[True]] + def __init__( + self, + date1904: _ConvertibleToBool | None = None, + dateCompatibility: _ConvertibleToBool | None = None, + showObjects: _WorkbookPropertiesShowObjects | Literal["none"] | None = None, + showBorderUnselectedTables: _ConvertibleToBool | None = None, + filterPrivacy: _ConvertibleToBool | None = None, + promptedSolutions: _ConvertibleToBool | None = None, + showInkAnnotation: _ConvertibleToBool | None = None, + backupFile: _ConvertibleToBool | None = None, + saveExternalLinkValues: _ConvertibleToBool | None = None, + updateLinks: _WorkbookPropertiesUpdateLinks | Literal["none"] | None = None, + codeName: str | None = None, + hidePivotFieldList: _ConvertibleToBool | None = None, + showPivotChartFilter: _ConvertibleToBool | None = None, + allowRefreshQuery: _ConvertibleToBool | None = None, + publishItems: _ConvertibleToBool | None = None, + checkCompatibility: _ConvertibleToBool | None = None, + autoCompressPictures: _ConvertibleToBool | None = None, + refreshAllConnections: _ConvertibleToBool | None = None, + defaultThemeVersion: ConvertibleToInt | None = None, + ) -> None: ... + +class CalcProperties(Serialisable): + tagname: ClassVar[str] + calcId: Integer[Literal[False]] + calcMode: NoneSet[_CalcPropertiesCalcMode] + fullCalcOnLoad: Bool[Literal[True]] + refMode: NoneSet[_CalcPropertiesRefMode] + iterate: Bool[Literal[True]] + iterateCount: Integer[Literal[True]] + iterateDelta: Float[Literal[True]] + fullPrecision: Bool[Literal[True]] + calcCompleted: Bool[Literal[True]] + calcOnSave: Bool[Literal[True]] + concurrentCalc: Bool[Literal[True]] + concurrentManualCount: Integer[Literal[True]] + forceFullCalc: Bool[Literal[True]] + def __init__( + self, + calcId: ConvertibleToInt = 124519, + calcMode: _CalcPropertiesCalcMode | Literal["none"] | None = None, + fullCalcOnLoad: _ConvertibleToBool | None = True, + refMode: _CalcPropertiesRefMode | Literal["none"] | None = None, + iterate: _ConvertibleToBool | None = None, + iterateCount: ConvertibleToInt | None = None, + iterateDelta: ConvertibleToFloat | None = None, + fullPrecision: _ConvertibleToBool | None = None, + calcCompleted: _ConvertibleToBool | None = None, + calcOnSave: _ConvertibleToBool | None = None, + concurrentCalc: _ConvertibleToBool | None = None, + concurrentManualCount: ConvertibleToInt | None = None, + forceFullCalc: _ConvertibleToBool | None = None, + ) -> None: ... + +class FileVersion(Serialisable): + tagname: ClassVar[str] + appName: String[Literal[True]] + lastEdited: String[Literal[True]] + lowestEdited: String[Literal[True]] + rupBuild: String[Literal[True]] + codeName: Incomplete + def __init__( + self, + appName: str | None = None, + lastEdited: str | None = None, + lowestEdited: str | None = None, + rupBuild: str | None = None, + codeName=None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/protection.pyi b/stubs/openpyxl/openpyxl/workbook/protection.pyi new file mode 100644 index 000000000000..ddedb7960f7b --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/protection.pyi @@ -0,0 +1,97 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload +from typing_extensions import Self + +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _SupportsIterAndAttribAndTextAndGet + +class WorkbookProtection(Serialisable): + tagname: ClassVar[str] + workbook_password: Alias + workbookPasswordCharacterSet: String[Literal[True]] + revision_password: Alias + revisionsPasswordCharacterSet: String[Literal[True]] + lockStructure: Bool[Literal[True]] + lock_structure: Alias + lockWindows: Bool[Literal[True]] + lock_windows: Alias + lockRevision: Bool[Literal[True]] + lock_revision: Alias + revisionsAlgorithmName: String[Literal[True]] + revisionsHashValue: Incomplete + revisionsSaltValue: Incomplete + revisionsSpinCount: Integer[Literal[True]] + workbookAlgorithmName: String[Literal[True]] + workbookHashValue: Incomplete + workbookSaltValue: Incomplete + workbookSpinCount: Integer[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + workbookPassword=None, + workbookPasswordCharacterSet: str | None = None, + revisionsPassword=None, + revisionsPasswordCharacterSet: str | None = None, + lockStructure: _ConvertibleToBool | None = None, + lockWindows: _ConvertibleToBool | None = None, + lockRevision: _ConvertibleToBool | None = None, + revisionsAlgorithmName: str | None = None, + revisionsHashValue=None, + revisionsSaltValue=None, + revisionsSpinCount: ConvertibleToInt | None = None, + workbookAlgorithmName: str | None = None, + workbookHashValue=None, + workbookSaltValue=None, + workbookSpinCount: ConvertibleToInt | None = None, + ) -> None: ... + + @overload + def set_workbook_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_workbook_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_workbook_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + @property + def workbookPassword(self) -> str | None: ... + @workbookPassword.setter + def workbookPassword(self, value: str) -> None: ... + + @overload + def set_revisions_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_revisions_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_revisions_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + @property + def revisionsPassword(self) -> str | None: ... + @revisionsPassword.setter + def revisionsPassword(self, value: str) -> None: ... + + @classmethod + def from_tree(cls, node: _SupportsIterAndAttribAndTextAndGet) -> Self: ... + +DocumentSecurity = WorkbookProtection + +class FileSharing(Serialisable): + tagname: ClassVar[str] + readOnlyRecommended: Bool[Literal[True]] + userName: String[Literal[True]] + reservationPassword: Incomplete + algorithmName: String[Literal[True]] + hashValue: Incomplete + saltValue: Incomplete + spinCount: Integer[Literal[True]] + def __init__( + self, + readOnlyRecommended: _ConvertibleToBool | None = None, + userName: str | None = None, + reservationPassword=None, + algorithmName: str | None = None, + hashValue=None, + saltValue=None, + spinCount: ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/smart_tags.pyi b/stubs/openpyxl/openpyxl/workbook/smart_tags.pyi new file mode 100644 index 000000000000..6f0baf5e448d --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/smart_tags.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, NoneSet, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_SmartTagPropertiesShow: TypeAlias = Literal["all", "noIndicator"] + +class SmartTag(Serialisable): + tagname: ClassVar[str] + namespaceUri: String[Literal[True]] + name: String[Literal[True]] + url: String[Literal[True]] + def __init__(self, namespaceUri: str | None = None, name: str | None = None, url: str | None = None) -> None: ... + +class SmartTagList(Serialisable): + tagname: ClassVar[str] + smartTagType: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, smartTagType=()) -> None: ... + +class SmartTagProperties(Serialisable): + tagname: ClassVar[str] + embed: Bool[Literal[True]] + show: NoneSet[_SmartTagPropertiesShow] + def __init__( + self, embed: _ConvertibleToBool | None = None, show: _SmartTagPropertiesShow | Literal["none"] | None = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/views.pyi b/stubs/openpyxl/openpyxl/workbook/views.pyi new file mode 100644 index 000000000000..f32087949c1c --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/views.pyi @@ -0,0 +1,134 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl import _VisibilityType +from openpyxl.descriptors.base import Bool, Integer, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +_CustomWorkbookViewShowComments: TypeAlias = Literal["commNone", "commIndicator", "commIndAndComment"] +_CustomWorkbookViewShowObjects: TypeAlias = Literal["all", "placeholders"] + +class BookView(Serialisable): + tagname: ClassVar[str] + visibility: NoneSet[_VisibilityType] + minimized: Bool[Literal[True]] + showHorizontalScroll: Bool[Literal[True]] + showVerticalScroll: Bool[Literal[True]] + showSheetTabs: Bool[Literal[True]] + xWindow: Integer[Literal[True]] + yWindow: Integer[Literal[True]] + windowWidth: Integer[Literal[True]] + windowHeight: Integer[Literal[True]] + tabRatio: Integer[Literal[True]] + firstSheet: Integer[Literal[True]] + activeTab: Integer[Literal[True]] + autoFilterDateGrouping: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + visibility: _VisibilityType | Literal["none"] | None = "visible", + minimized: _ConvertibleToBool | None = False, + showHorizontalScroll: _ConvertibleToBool | None = True, + showVerticalScroll: _ConvertibleToBool | None = True, + showSheetTabs: _ConvertibleToBool | None = True, + xWindow: ConvertibleToInt | None = None, + yWindow: ConvertibleToInt | None = None, + windowWidth: ConvertibleToInt | None = None, + windowHeight: ConvertibleToInt | None = None, + tabRatio: ConvertibleToInt | None = 600, + firstSheet: ConvertibleToInt | None = 0, + activeTab: ConvertibleToInt | None = 0, + autoFilterDateGrouping: _ConvertibleToBool | None = True, + extLst: Unused = None, + ) -> None: ... + +class CustomWorkbookView(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + guid: Incomplete + autoUpdate: Bool[Literal[True]] + mergeInterval: Integer[Literal[True]] + changesSavedWin: Bool[Literal[True]] + onlySync: Bool[Literal[True]] + personalView: Bool[Literal[True]] + includePrintSettings: Bool[Literal[True]] + includeHiddenRowCol: Bool[Literal[True]] + maximized: Bool[Literal[True]] + minimized: Bool[Literal[True]] + showHorizontalScroll: Bool[Literal[True]] + showVerticalScroll: Bool[Literal[True]] + showSheetTabs: Bool[Literal[True]] + xWindow: Integer[Literal[False]] + yWindow: Integer[Literal[False]] + windowWidth: Integer[Literal[False]] + windowHeight: Integer[Literal[False]] + tabRatio: Integer[Literal[True]] + activeSheetId: Integer[Literal[False]] + showFormulaBar: Bool[Literal[True]] + showStatusbar: Bool[Literal[True]] + showComments: NoneSet[_CustomWorkbookViewShowComments] + showObjects: NoneSet[_CustomWorkbookViewShowObjects] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + name: str, + guid=None, + autoUpdate: _ConvertibleToBool | None = None, + mergeInterval: ConvertibleToInt | None = None, + changesSavedWin: _ConvertibleToBool | None = None, + onlySync: _ConvertibleToBool | None = None, + personalView: _ConvertibleToBool | None = None, + includePrintSettings: _ConvertibleToBool | None = None, + includeHiddenRowCol: _ConvertibleToBool | None = None, + maximized: _ConvertibleToBool | None = None, + minimized: _ConvertibleToBool | None = None, + showHorizontalScroll: _ConvertibleToBool | None = None, + showVerticalScroll: _ConvertibleToBool | None = None, + showSheetTabs: _ConvertibleToBool | None = None, + *, + xWindow: ConvertibleToInt, + yWindow: ConvertibleToInt, + windowWidth: ConvertibleToInt, + windowHeight: ConvertibleToInt, + tabRatio: ConvertibleToInt | None = None, + activeSheetId: ConvertibleToInt, + showFormulaBar: _ConvertibleToBool | None = None, + showStatusbar: _ConvertibleToBool | None = None, + showComments: _CustomWorkbookViewShowComments | Literal["none"] | None = "commIndicator", + showObjects: _CustomWorkbookViewShowObjects | Literal["none"] | None = "all", + extLst: Unused = None, + ) -> None: ... + @overload + def __init__( + self, + name: str, + guid: Incomplete | None, + autoUpdate: _ConvertibleToBool | None, + mergeInterval: ConvertibleToInt | None, + changesSavedWin: _ConvertibleToBool | None, + onlySync: _ConvertibleToBool | None, + personalView: _ConvertibleToBool | None, + includePrintSettings: _ConvertibleToBool | None, + includeHiddenRowCol: _ConvertibleToBool | None, + maximized: _ConvertibleToBool | None, + minimized: _ConvertibleToBool | None, + showHorizontalScroll: _ConvertibleToBool | None, + showVerticalScroll: _ConvertibleToBool | None, + showSheetTabs: _ConvertibleToBool | None, + xWindow: ConvertibleToInt, + yWindow: ConvertibleToInt, + windowWidth: ConvertibleToInt, + windowHeight: ConvertibleToInt, + tabRatio: ConvertibleToInt | None, + activeSheetId: ConvertibleToInt, + showFormulaBar: _ConvertibleToBool | None = None, + showStatusbar: _ConvertibleToBool | None = None, + showComments: _CustomWorkbookViewShowComments | Literal["none"] | None = "commIndicator", + showObjects: _CustomWorkbookViewShowObjects | Literal["none"] | None = "all", + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/web.pyi b/stubs/openpyxl/openpyxl/workbook/web.pyi new file mode 100644 index 000000000000..fbd5bc0b3cd6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/web.pyi @@ -0,0 +1,84 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, NoneSet, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_WebPublishingTargetScreenSize: TypeAlias = Literal[ + "544x376", + "640x480", + "720x512", + "800x600", + "1024x768", + "1152x882", + "1152x900", + "1280x1024", + "1600x1200", + "1800x1440", + "1920x1200", +] + +class WebPublishObject(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[False]] + divId: String[Literal[False]] + sourceObject: String[Literal[True]] + destinationFile: String[Literal[False]] + title: String[Literal[True]] + autoRepublish: Bool[Literal[True]] + + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceObject: str | None = None, + *, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceObject: str | None, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + +class WebPublishObjectList(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer + webPublishObject: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, webPublishObject=()) -> None: ... + @property + def count(self) -> int: ... + +class WebPublishing(Serialisable): + tagname: ClassVar[str] + css: Bool[Literal[True]] + thicket: Bool[Literal[True]] + longFileNames: Bool[Literal[True]] + vml: Bool[Literal[True]] + allowPng: Bool[Literal[True]] + targetScreenSize: NoneSet[_WebPublishingTargetScreenSize] + dpi: Integer[Literal[True]] + codePage: Integer[Literal[True]] + characterSet: String[Literal[True]] + def __init__( + self, + css: _ConvertibleToBool | None = None, + thicket: _ConvertibleToBool | None = None, + longFileNames: _ConvertibleToBool | None = None, + vml: _ConvertibleToBool | None = None, + allowPng: _ConvertibleToBool | None = None, + targetScreenSize: _WebPublishingTargetScreenSize | Literal["none"] | None = "800x600", + dpi: ConvertibleToInt | None = None, + codePage: ConvertibleToInt | None = None, + characterSet: str | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/workbook.pyi b/stubs/openpyxl/openpyxl/workbook/workbook.pyi new file mode 100644 index 000000000000..3a2851da1574 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/workbook.pyi @@ -0,0 +1,126 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterator +from datetime import datetime +from typing import Any, Final, TypeAlias, type_check_only +from typing_extensions import deprecated +from zipfile import ZipFile + +from openpyxl import _Decodable, _ZipFileFileWriteProtocol +from openpyxl.chartsheet.chartsheet import Chartsheet +from openpyxl.styles.named_styles import NamedStyle +from openpyxl.utils.indexed_list import IndexedList +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet +from openpyxl.worksheet._write_only import WriteOnlyWorksheet +from openpyxl.worksheet.worksheet import Worksheet + +_WorkbookWorksheet: TypeAlias = Worksheet | WriteOnlyWorksheet | ReadOnlyWorksheet +_WorkbookSheet: TypeAlias = _WorkbookWorksheet | Chartsheet + +# The type of worksheets in a workbook are the same as the aliases above. +# However, because Worksheet adds a lots of attributes that other _WorkbookChild subclasses +# don't have (ReadOnlyWorksheet doesn't even inherit from it), this ends up being too +# disruptive to the typical usage of openpyxl where sheets are just Worksheets. +# Using Any may just lose too much type information and duck-typing +# from Worksheet works great here. Allowing instance type check, even if direct +# type comparison might be wrong. +@type_check_only +class _WorksheetLike( # type: ignore[misc] # Incompatible definitions, favor Worksheet # pyrefly: ignore [inconsistent-inheritance] + Worksheet, WriteOnlyWorksheet, ReadOnlyWorksheet +): ... + +@type_check_only +class _WorksheetOrChartsheetLike( # type: ignore[misc] # Incompatible definitions, favor Worksheet + Chartsheet, _WorksheetLike +): ... + +INTEGER_TYPES: Final[tuple[type[int]]] + +class Workbook: + template: bool + path: str + defined_names: Incomplete + properties: Incomplete + security: Incomplete + shared_strings: IndexedList[str] + loaded_theme: Incomplete + vba_archive: ZipFile | None + is_template: bool + code_name: Incomplete + encoding: str + iso_dates: Incomplete + rels: Incomplete + calculation: Incomplete + views: Incomplete + # Useful as a reference of what "sheets" can be for other types + # ExcelReader can add ReadOnlyWorksheet in read_only mode. + # _sheets: list[_WorksheetOrChartsheetLike] + def __init__(self, write_only: bool = False, iso_dates: bool = False) -> None: ... + + @property + def epoch(self) -> datetime: ... + @epoch.setter + def epoch(self, value: datetime) -> None: ... + + @property + def read_only(self) -> bool: ... + @property + def data_only(self) -> bool: ... + @property + def write_only(self) -> bool: ... + @property + def excel_base_date(self) -> datetime: ... + + @property + def active(self) -> _WorksheetOrChartsheetLike | None: ... + @active.setter + def active(self, value: Worksheet | Chartsheet | int) -> None: ... + + # read_only workbook cannot call this method + # Could be generic based on write_only + def create_sheet( + self, title: str | _Decodable | None = None, index: int | None = None + ) -> Any: ... # AnyOf[WriteOnlyWorksheet, Worksheet] + def move_sheet(self, sheet: Worksheet | str, offset: int = 0) -> None: ... + def remove(self, worksheet: _WorkbookSheet) -> None: ... + @deprecated("Use wb.remove(worksheet) or del wb[sheetname]") + def remove_sheet(self, worksheet: _WorkbookSheet) -> None: ... + def create_chartsheet(self, title: str | _Decodable | None = None, index: int | None = None) -> Chartsheet: ... + @deprecated("Use wb[sheetname]") + def get_sheet_by_name(self, name: str) -> _WorksheetOrChartsheetLike: ... + def __contains__(self, key: str) -> bool: ... + def index(self, worksheet: _WorkbookWorksheet) -> int: ... + @deprecated("Use wb.index(worksheet)") + def get_index(self, worksheet: _WorkbookWorksheet) -> int: ... + def __getitem__(self, key: str) -> _WorksheetOrChartsheetLike: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[_WorksheetLike]: ... + @deprecated("Use wb.sheetnames") + def get_sheet_names(self) -> list[str]: ... + @property + def worksheets(self) -> list[_WorksheetLike]: ... + @property + def chartsheets(self) -> list[Chartsheet]: ... + @property + def sheetnames(self) -> list[str]: ... + @deprecated("Assign scoped named ranges directly to worksheets or global ones to the workbook. Deprecated in 3.1") + def create_named_range( + self, + name: str, + worksheet: _WorkbookChild | ReadOnlyWorksheet | None = None, + value: str | Incomplete | None = None, + scope: Unused = None, + ) -> None: ... + def add_named_style(self, style: NamedStyle) -> None: ... + @property + def named_styles(self) -> list[str]: ... + @property + def mime_type(self) -> str: ... + def save(self, filename: _ZipFileFileWriteProtocol) -> None: ... + @property + def style_names(self) -> list[str]: ... + # A write_only and read_only workbooks can't use this method as it requires both reading and writing. + # On an implementation level, a WorksheetCopy is created from the call to self.create_sheet, + # but WorksheetCopy only works with Worksheet. + def copy_worksheet(self, from_worksheet: Worksheet) -> Worksheet: ... + def close(self) -> None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/testing/mock.pyi b/stubs/openpyxl/openpyxl/worksheet/__init__.pyi similarity index 100% rename from stubs/SQLAlchemy/sqlalchemy/testing/mock.pyi rename to stubs/openpyxl/openpyxl/worksheet/__init__.pyi diff --git a/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi b/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi new file mode 100644 index 000000000000..a1f95ee4b577 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi @@ -0,0 +1,40 @@ +from _typeshed import SupportsGetItem +from collections.abc import Generator + +from openpyxl import _VisibilityType +from openpyxl.cell import _CellGetValue, _CellOrMergedCell +from openpyxl.utils.cell import _RangeBoundariesTuple +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.worksheet import Worksheet + +def read_dimension(source) -> _RangeBoundariesTuple | None: ... + +class ReadOnlyWorksheet: + cell = Worksheet.cell + iter_rows = Worksheet.iter_rows + # Same as Worksheet.values + # https://github.com/python/mypy/issues/6700 + @property + def values(self) -> Generator[tuple[_CellGetValue, ...]]: ... + # Same as Worksheet.rows + # https://github.com/python/mypy/issues/6700 + @property + def rows(self) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + __getitem__ = Worksheet.__getitem__ + __iter__ = Worksheet.__iter__ + parent: Workbook + title: str + sheet_state: _VisibilityType + def __init__( + self, parent_workbook: Workbook, title: str, worksheet_path, shared_strings: SupportsGetItem[int, str] + ) -> None: ... + def calculate_dimension(self, force: bool = False): ... + def reset_dimensions(self) -> None: ... + @property + def min_row(self) -> int: ... + @property + def max_row(self) -> int | None: ... + @property + def min_column(self) -> int: ... + @property + def max_column(self) -> int | None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/_reader.pyi b/stubs/openpyxl/openpyxl/worksheet/_reader.pyi new file mode 100644 index 000000000000..789dd30f6c6f --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_reader.pyi @@ -0,0 +1,117 @@ +from _typeshed import Incomplete, SupportsGetItem, Unused +from collections.abc import Container, Generator +from datetime import datetime +from typing import Final +from xml.etree.ElementTree import _FileRead + +from openpyxl.cell import _AnyCellValue, _CellOrMergedCell +from openpyxl.cell.rich_text import CellRichText +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement, _SerialisableTreeElement +from openpyxl.formula.translate import Translator +from openpyxl.utils.cell import _RangeBoundariesTuple + +from ..xml._functions_overloads import _HasAttrib, _SupportsIterAndAttrib +from .hyperlink import HyperlinkList +from .pagebreak import ColBreak, RowBreak +from .protection import SheetProtection +from .table import TablePartList +from .worksheet import Worksheet + +CELL_TAG: Final[str] +VALUE_TAG: Final[str] +FORMULA_TAG: Final[str] +MERGE_TAG: Final[str] +INLINE_STRING: Final[str] +COL_TAG: Final[str] +ROW_TAG: Final[str] +CF_TAG: Final[str] +LEGACY_TAG: Final[str] +PROT_TAG: Final[str] +EXT_TAG: Final[str] +HYPERLINK_TAG: Final[str] +TABLE_TAG: Final[str] +PRINT_TAG: Final[str] +MARGINS_TAG: Final[str] +PAGE_TAG: Final[str] +HEADER_TAG: Final[str] +FILTER_TAG: Final[str] +VALIDATION_TAG: Final[str] +PROPERTIES_TAG: Final[str] +VIEWS_TAG: Final[str] +FORMAT_TAG: Final[str] +ROW_BREAK_TAG: Final[str] +COL_BREAK_TAG: Final[str] +SCENARIOS_TAG: Final[str] +DATA_TAG: Final[str] +DIMENSION_TAG: Final[str] +CUSTOM_VIEWS_TAG: Final[str] + +def parse_richtext_string(element: _ChildSerialisableTreeElement) -> CellRichText | str: ... + +class WorkSheetParser: + min_row: Incomplete | None + min_col: Incomplete | None + epoch: datetime + source: _FileRead + shared_strings: SupportsGetItem[int, str] + data_only: bool + shared_formulae: dict[Incomplete, Translator] + row_counter: int + col_counter: int + tables: TablePartList + date_formats: Container[int] + timedelta_formats: Container[int] + row_dimensions: dict[Incomplete, Incomplete] + column_dimensions: dict[Incomplete, Incomplete] + number_formats: list[Incomplete] + keep_vba: bool + hyperlinks: HyperlinkList + formatting: list[Incomplete] + legacy_drawing: Incomplete | None + merged_cells: Incomplete | None + row_breaks: RowBreak + col_breaks: ColBreak + rich_text: bool + protection: SheetProtection # initialized after call to parse_sheet_protection() + + def __init__( + self, + src: _FileRead, + shared_strings: SupportsGetItem[int, str], + data_only: bool = False, + epoch: datetime = ..., + date_formats: Container[int] = ..., + timedelta_formats: Container[int] = ..., + rich_text: bool = False, + ) -> None: ... + def parse(self) -> Generator[Incomplete]: ... + def parse_dimensions(self) -> _RangeBoundariesTuple | None: ... + def parse_cell(self, element) -> dict[str, _AnyCellValue]: ... + def parse_formula(self, element): ... + def parse_column_dimensions(self, col: _HasAttrib) -> None: ... + def parse_row(self, row: _SupportsIterAndAttrib) -> tuple[int, list[dict[str, _AnyCellValue]]]: ... + def parse_formatting(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_sheet_protection(self, element: _SerialisableTreeElement) -> None: ... + def parse_extensions(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_legacy(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_row_breaks(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_col_breaks(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_custom_views(self, element: Unused) -> None: ... + +class WorksheetReader: + ws: Worksheet + parser: WorkSheetParser + tables: list[Incomplete] + def __init__( + self, ws: Worksheet, xml_source: _FileRead, shared_strings: SupportsGetItem[int, str], data_only: bool, rich_text: bool + ) -> None: ... + def bind_cells(self) -> None: ... + def bind_formatting(self) -> None: ... + def bind_tables(self) -> None: ... + def bind_merged_cells(self) -> None: ... + def bind_hyperlinks(self) -> None: ... + def normalize_merged_cell_link(self, coord: str) -> _CellOrMergedCell | None: ... + def bind_col_dimensions(self) -> None: ... + def bind_row_dimensions(self) -> None: ... + def bind_properties(self) -> None: ... + def bind_all(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/_write_only.pyi b/stubs/openpyxl/openpyxl/worksheet/_write_only.pyi new file mode 100644 index 000000000000..c73e6d964898 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_write_only.pyi @@ -0,0 +1,50 @@ +from collections.abc import Iterable + +from openpyxl import _Decodable +from openpyxl.cell.cell import Cell +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.table import TableList +from openpyxl.worksheet.views import SheetView +from openpyxl.worksheet.worksheet import Worksheet + +class WriteOnlyWorksheet(_WorkbookChild): + mime_type = Worksheet.mime_type + add_chart = Worksheet.add_chart + add_image = Worksheet.add_image + add_table = Worksheet.add_table + + # Same properties as Worksheet + # https://github.com/python/mypy/issues/6700 + @property + def tables(self) -> TableList: ... + @property + def print_titles(self) -> str: ... + + @property + def print_title_cols(self) -> str | None: ... + @print_title_cols.setter + def print_title_cols(self, cols: str | None) -> None: ... + + @property + def print_title_rows(self) -> str | None: ... + @print_title_rows.setter + def print_title_rows(self, rows: str | None) -> None: ... + + @property + def freeze_panes(self) -> str | None: ... + @freeze_panes.setter + def freeze_panes(self, topLeftCell: str | Cell | None = ...) -> None: ... + + @property + def print_area(self) -> str: ... + @print_area.setter + def print_area(self, value: str | Iterable[str] | None) -> None: ... + + @property + def sheet_view(self) -> SheetView: ... + def __init__(self, parent: Workbook | None, title: str | _Decodable | None) -> None: ... + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def append(self, row) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/_writer.pyi b/stubs/openpyxl/openpyxl/worksheet/_writer.pyi new file mode 100644 index 000000000000..40fb98eacdac --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_writer.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete, ReadableBuffer, StrPath, Unused +from collections.abc import Generator, Iterable +from typing import Protocol, TypeAlias, type_check_only + +from openpyxl.cell import _CellOrMergedCell +from openpyxl.worksheet._write_only import WriteOnlyWorksheet +from openpyxl.worksheet.worksheet import Worksheet + +# WorksheetWriter.read has an explicit BytesIO branch. Let's make sure this protocol is viable for BytesIO too. +@type_check_only +class _SupportsCloseAndWrite(Protocol): + def write(self, buffer: ReadableBuffer, /) -> Unused: ... + def close(self) -> Unused: ... + +# et_xmlfile.xmlfile accepts a str | _SupportsCloseAndWrite +# lxml.etree.xmlfile should accept a StrPath | _SupportsClose https://lxml.de/api/lxml.etree.xmlfile-class.html +_OutType: TypeAlias = _SupportsCloseAndWrite | StrPath + +ALL_TEMP_FILES: list[str] + +def create_temporary_file(suffix: str = "") -> str: ... + +class WorksheetWriter: + ws: Worksheet | WriteOnlyWorksheet + out: _OutType + xf: Generator[Incomplete | None, Incomplete] + def __init__(self, ws: Worksheet | WriteOnlyWorksheet, out: _OutType | None = None) -> None: ... + def write_properties(self) -> None: ... + def write_dimensions(self) -> None: ... + def write_format(self) -> None: ... + def write_views(self) -> None: ... + def write_cols(self) -> None: ... + def write_top(self) -> None: ... + def rows(self) -> list[tuple[int, list[_CellOrMergedCell]]]: ... + def write_rows(self) -> None: ... + def write_row(self, xf, row: Iterable[_CellOrMergedCell], row_idx) -> None: ... + def write_protection(self) -> None: ... + def write_scenarios(self) -> None: ... + def write_filter(self) -> None: ... + def write_sort(self) -> None: ... + def write_merged_cells(self) -> None: ... + def write_formatting(self) -> None: ... + def write_validations(self) -> None: ... + def write_hyperlinks(self) -> None: ... + def write_print(self) -> None: ... + def write_margins(self) -> None: ... + def write_page(self) -> None: ... + def write_header(self) -> None: ... + def write_breaks(self) -> None: ... + def write_drawings(self) -> None: ... + def write_legacy(self) -> None: ... + def write_tables(self) -> None: ... + def get_stream(self) -> Generator[Incomplete | None, bool | None]: ... + def write_tail(self) -> None: ... + def write(self) -> None: ... + def close(self) -> None: ... + def read(self) -> bytes: ... + def cleanup(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi b/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi new file mode 100644 index 000000000000..9047a877351e --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi @@ -0,0 +1,105 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Generator, Iterator +from itertools import product +from typing import Any, Literal, overload + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import MinMax +from openpyxl.descriptors.serialisable import Serialisable + +class CellRange(Serialisable): + min_col: MinMax[int, Literal[False]] + min_row: MinMax[int, Literal[False]] + max_col: MinMax[int, Literal[False]] + max_row: MinMax[int, Literal[False]] + title: str | None + + # With `range_string`, min/max parameters go unused. + # Enforcing `None` to avoid confusion upon which params get used + # if the user still tries to pass a `ConvertibleToInt`. + @overload + def __init__( + self, + range_string: str, + min_col: None = None, + min_row: None = None, + max_col: None = None, + max_row: None = None, + title: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + range_string: None = None, + *, + min_col: ConvertibleToInt, + min_row: ConvertibleToInt, + max_col: ConvertibleToInt, + max_row: ConvertibleToInt, + title: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + range_string: None, + min_col: ConvertibleToInt, + min_row: ConvertibleToInt, + max_col: ConvertibleToInt, + max_row: ConvertibleToInt, + title: str | None = None, + ) -> None: ... + + @property + def bounds(self) -> tuple[int, int, int, int]: ... + @property + def coord(self) -> str: ... + @property + def rows(self) -> Generator[list[tuple[int, int]]]: ... + @property + def cols(self) -> Generator[list[tuple[int, int]]]: ... + @property + def cells(self) -> product[tuple[int, int]]: ... + def __copy__(self): ... + def shift(self, col_shift: int = 0, row_shift: int = 0) -> None: ... + def __ne__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def issubset(self, other: CellRange) -> bool: ... + __le__ = issubset + def __lt__(self, other: CellRange) -> bool: ... + def issuperset(self, other: CellRange) -> bool: ... + __ge__ = issuperset + def __contains__(self, coord: str) -> bool: ... + def __gt__(self, other: CellRange) -> bool: ... + def isdisjoint(self, other: CellRange) -> bool: ... + def intersection(self, other): ... + __and__ = intersection + def union(self, other): ... + __or__ = union + # Iterates over class attributes. Value could be anything. + def __iter__(self) -> Iterator[tuple[str, Any]]: ... + def expand(self, right: int = 0, down: int = 0, left: int = 0, up: int = 0) -> None: ... + def shrink(self, right: int = 0, bottom: int = 0, left: int = 0, top: int = 0) -> None: ... + @property + def size(self) -> dict[str, int]: ... + @property + def top(self) -> list[tuple[int, int]]: ... + @property + def bottom(self) -> list[tuple[int, int]]: ... + @property + def left(self) -> list[tuple[int, int]]: ... + @property + def right(self) -> list[tuple[int, int]]: ... + +class MultiCellRange(Strict): + ranges: Incomplete + def __init__(self, ranges=...) -> None: ... + def __contains__(self, coord: str | CellRange) -> bool: ... + def sorted(self) -> list[CellRange]: ... + def add(self, coord) -> None: ... + def __iadd__(self, coord): ... + def __eq__(self, other: str | MultiCellRange) -> bool: ... # type: ignore[override] + def __ne__(self, other: str | MultiCellRange) -> bool: ... # type: ignore[override] + def __bool__(self) -> bool: ... + def remove(self, coord) -> None: ... + def __iter__(self) -> Iterator[CellRange]: ... + def __copy__(self): ... diff --git a/stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi b/stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi new file mode 100644 index 000000000000..5cece50ffa7c --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.serialisable import Serialisable + +class CellWatch(Serialisable): + tagname: ClassVar[str] + r: String[Literal[True]] + def __init__(self, r: str) -> None: ... + +class CellWatches(Serialisable): + tagname: ClassVar[str] + cellWatch: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cellWatch=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/controls.pyi b/stubs/openpyxl/openpyxl/worksheet/controls.pyi new file mode 100644 index 000000000000..2e42831a592c --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/controls.pyi @@ -0,0 +1,65 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.ole import ObjectAnchor + +class ControlProperty(Serialisable): + tagname: ClassVar[str] + anchor: Typed[ObjectAnchor, Literal[False]] + locked: Bool[Literal[True]] + defaultSize: Bool[Literal[True]] + _print: Bool[Literal[True]] # Not private. Avoids name clash + disabled: Bool[Literal[True]] + recalcAlways: Bool[Literal[True]] + uiObject: Bool[Literal[True]] + autoFill: Bool[Literal[True]] + autoLine: Bool[Literal[True]] + autoPict: Bool[Literal[True]] + macro: String[Literal[True]] + altText: String[Literal[True]] + linkedCell: String[Literal[True]] + listFillRange: String[Literal[True]] + cf: String[Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + anchor: ObjectAnchor, + locked: _ConvertibleToBool | None = True, + defaultSize: _ConvertibleToBool | None = True, + _print: _ConvertibleToBool | None = True, + disabled: _ConvertibleToBool | None = False, + recalcAlways: _ConvertibleToBool | None = False, + uiObject: _ConvertibleToBool | None = False, + autoFill: _ConvertibleToBool | None = True, + autoLine: _ConvertibleToBool | None = True, + autoPict: _ConvertibleToBool | None = True, + macro: str | None = None, + altText: str | None = None, + linkedCell: str | None = None, + listFillRange: str | None = None, + cf: str | None = "pict", + id=None, + ) -> None: ... + +class Control(Serialisable): + tagname: ClassVar[str] + controlPr: Typed[ControlProperty, Literal[True]] + shapeId: Integer[Literal[False]] + name: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, controlPr: ControlProperty | None = None, *, shapeId: ConvertibleToInt, name: str | None = None + ) -> None: ... + @overload + def __init__(self, controlPr: ControlProperty | None, shapeId: ConvertibleToInt, name: str | None = None) -> None: ... + +class Controls(Serialisable): + tagname: ClassVar[str] + control: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, control=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/copier.pyi b/stubs/openpyxl/openpyxl/worksheet/copier.pyi new file mode 100644 index 000000000000..e32d38c5747b --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/copier.pyi @@ -0,0 +1,7 @@ +from openpyxl.worksheet.worksheet import Worksheet + +class WorksheetCopy: + source: Worksheet + target: Worksheet + def __init__(self, source_worksheet: Worksheet, target_worksheet: Worksheet) -> None: ... + def copy_worksheet(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/custom.pyi b/stubs/openpyxl/openpyxl/worksheet/custom.pyi new file mode 100644 index 000000000000..53d330806ca1 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/custom.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.serialisable import Serialisable + +class CustomProperty(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + def __init__(self, name: str) -> None: ... + +class CustomProperties(Serialisable): + tagname: ClassVar[str] + customPr: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, customPr=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi b/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi new file mode 100644 index 000000000000..500a40aee250 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi @@ -0,0 +1,109 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, Protocol, TypeAlias, type_check_only + +from openpyxl.descriptors.base import ( + Alias, + Bool, + Convertible, + Integer, + NoneSet, + String, + _ConvertibleToBool, + _ConvertibleToMultiCellRange, +) +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange +from openpyxl.xml.functions import Element + +_DataValidationType: TypeAlias = Literal["whole", "decimal", "list", "date", "time", "textLength", "custom"] +_DataValidationErrorStyle: TypeAlias = Literal["stop", "warning", "information"] +_DataValidationImeMode: TypeAlias = Literal[ + "noControl", + "off", + "on", + "disabled", + "hiragana", + "fullKatakana", + "halfKatakana", + "fullAlpha", + "halfAlpha", + "fullHangul", + "halfHangul", +] +_DataValidationOperator: TypeAlias = Literal[ + "between", "notBetween", "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" +] + +@type_check_only +class _HasCoordinate(Protocol): + coordinate: str | CellRange + +def collapse_cell_addresses(cells, input_ranges=()): ... +def expand_cell_ranges(range_string): ... + +class DataValidation(Serialisable): + tagname: ClassVar[str] + sqref: Convertible[MultiCellRange, Literal[False]] + cells: Alias + ranges: Alias + showDropDown: Bool[Literal[True]] + hide_drop_down: Alias + showInputMessage: Bool[Literal[True]] + showErrorMessage: Bool[Literal[True]] + allowBlank: Bool[Literal[True]] + allow_blank: Alias + errorTitle: String[Literal[True]] + error: String[Literal[True]] + promptTitle: String[Literal[True]] + prompt: String[Literal[True]] + formula1: NestedText[str, Literal[True]] + formula2: NestedText[str, Literal[True]] + type: NoneSet[_DataValidationType] + errorStyle: NoneSet[_DataValidationErrorStyle] + imeMode: NoneSet[_DataValidationImeMode] + operator: NoneSet[_DataValidationOperator] + validation_type: Alias + def __init__( + self, + type: _DataValidationType | Literal["none"] | None = None, + formula1: object = None, + formula2: object = None, + showErrorMessage: _ConvertibleToBool | None = False, + showInputMessage: _ConvertibleToBool | None = False, + showDropDown: _ConvertibleToBool | None = False, + allowBlank: _ConvertibleToBool = False, + sqref: _ConvertibleToMultiCellRange = (), + promptTitle: str | None = None, + errorStyle: _DataValidationErrorStyle | Literal["none"] | None = None, + error: str | None = None, + prompt: str | None = None, + errorTitle: str | None = None, + imeMode: _DataValidationImeMode | Literal["none"] | None = None, + operator: _DataValidationOperator | Literal["none"] | None = None, + allow_blank: _ConvertibleToBool | None = None, + ) -> None: ... + def add(self, cell) -> None: ... + def __contains__(self, cell: _HasCoordinate | str | CellRange) -> bool: ... + +class DataValidationList(Serialisable): + tagname: ClassVar[str] + disablePrompts: Bool[Literal[True]] + xWindow: Integer[Literal[True]] + yWindow: Integer[Literal[True]] + dataValidation: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + disablePrompts: _ConvertibleToBool | None = None, + xWindow: ConvertibleToInt | None = None, + yWindow: ConvertibleToInt | None = None, + count=None, + dataValidation=(), + ) -> None: ... + @property + def count(self) -> int: ... + def __len__(self) -> int: ... + def append(self, dv) -> None: ... + def to_tree(self, tagname: str | None = None) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi b/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi new file mode 100644 index 000000000000..167dfb1c7b1f --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi @@ -0,0 +1,149 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from collections.abc import Callable, Iterator +from typing import ClassVar, Literal, TypeVar +from typing_extensions import Self + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Alias, Bool, Float, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.styleable import StyleableObject +from openpyxl.utils.bound_dictionary import BoundDictionary +from openpyxl.utils.cell import _RangeBoundariesTuple +from openpyxl.worksheet.worksheet import Worksheet +from openpyxl.xml.functions import Element + +_DimKeyT = TypeVar("_DimKeyT", bound=str | int) +_DimT = TypeVar("_DimT", bound=Dimension) + +class Dimension(Strict, StyleableObject): + __fields__: ClassVar[tuple[str, ...]] + + index: Integer[Literal[False]] + hidden: Bool[Literal[False]] + outlineLevel: Integer[Literal[True]] + outline_level: Alias + collapsed: Bool[Literal[False]] + style: Alias # type: ignore[assignment] + + # Dimensions are only meant to be used on Worksheet objects + parent: Worksheet + + def __init__( + self, + index: ConvertibleToInt, + hidden: _ConvertibleToBool, + outlineLevel: ConvertibleToInt | None, + collapsed: _ConvertibleToBool, + worksheet: Worksheet, + visible: Unused = True, + style=None, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def __copy__(self) -> Self: ... + +class RowDimension(Dimension): + r: Alias + s: Alias + ht: Float[Literal[True]] + height: Alias + thickBot: Bool[Literal[False]] + thickTop: Bool[Literal[False]] + def __init__( + self, + worksheet: Worksheet, + index: int = 0, + ht: ConvertibleToFloat | None = None, + customHeight: Unused = None, + s=None, + customFormat: Unused = None, + hidden: _ConvertibleToBool = None, + outlineLevel: ConvertibleToInt | None = 0, + outline_level: ConvertibleToInt | None = None, + collapsed: _ConvertibleToBool = None, + visible=None, + height=None, + r=None, + spans: Unused = None, + thickBot: _ConvertibleToBool = None, + thickTop: _ConvertibleToBool = None, + **kw: Unused, + ) -> None: ... + @property + def customFormat(self) -> bool: ... + @property + def customHeight(self) -> bool: ... + +class ColumnDimension(Dimension): + width: Float[Literal[False]] + bestFit: Bool[Literal[False]] + auto_size: Alias + index: String[Literal[False]] # type: ignore[assignment] + min: Integer[Literal[True]] + max: Integer[Literal[True]] + collapsed: Bool[Literal[False]] + + def __init__( + self, + worksheet: Worksheet, + index: str = "A", + width: ConvertibleToFloat = 13, + bestFit: _ConvertibleToBool = False, + hidden: _ConvertibleToBool = False, + outlineLevel: ConvertibleToInt | None = 0, + outline_level: ConvertibleToInt | None = None, + collapsed: _ConvertibleToBool = False, + style=None, + min: ConvertibleToInt | None = None, + max: ConvertibleToInt | None = None, + customWidth: Unused = False, + visible: bool | None = None, + auto_size: _ConvertibleToBool | None = None, + ) -> None: ... + @property + def customWidth(self) -> bool: ... + def reindex(self) -> None: ... + @property + def range(self) -> str: ... + def to_tree(self) -> Element | None: ... + +class DimensionHolder(BoundDictionary[_DimKeyT, _DimT]): + worksheet: Worksheet + max_outline: int | None + default_factory: Callable[[], _DimT] | None + + def __init__( + self, worksheet: Worksheet, reference: str = "index", default_factory: Callable[[], _DimT] | None = None + ) -> None: ... + def group(self, start: _DimKeyT, end: _DimKeyT | None = None, outline_level: int = 1, hidden: bool = False) -> None: ... + def to_tree(self) -> Element | None: ... + +class SheetFormatProperties(Serialisable): + tagname: ClassVar[str] + baseColWidth: Integer[Literal[True]] + defaultColWidth: Float[Literal[True]] + defaultRowHeight: Float[Literal[False]] + customHeight: Bool[Literal[True]] + zeroHeight: Bool[Literal[True]] + thickTop: Bool[Literal[True]] + thickBottom: Bool[Literal[True]] + outlineLevelRow: Integer[Literal[True]] + outlineLevelCol: Integer[Literal[True]] + def __init__( + self, + baseColWidth: ConvertibleToInt | None = 8, + defaultColWidth: ConvertibleToFloat | None = None, + defaultRowHeight: ConvertibleToFloat = 15, + customHeight: _ConvertibleToBool | None = None, + zeroHeight: _ConvertibleToBool | None = None, + thickTop: _ConvertibleToBool | None = None, + thickBottom: _ConvertibleToBool | None = None, + outlineLevelRow: ConvertibleToInt | None = None, + outlineLevelCol: ConvertibleToInt | None = None, + ) -> None: ... + +class SheetDimension(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + def __init__(self, ref: str) -> None: ... + @property + def boundaries(self) -> _RangeBoundariesTuple: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/drawing.pyi b/stubs/openpyxl/openpyxl/worksheet/drawing.pyi new file mode 100644 index 000000000000..589c271fedea --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/drawing.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class Drawing(Serialisable): + tagname: ClassVar[str] + id: Incomplete + def __init__(self, id=None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/errors.pyi b/stubs/openpyxl/openpyxl/worksheet/errors.pyi new file mode 100644 index 000000000000..67883b448949 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/errors.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Extension(Serialisable): + tagname: ClassVar[str] + uri: String[Literal[True]] + def __init__(self, uri: str | None = None) -> None: ... + +class ExtensionList(Serialisable): + tagname: ClassVar[str] + ext: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ext=()) -> None: ... + +class IgnoredError(Serialisable): + tagname: ClassVar[str] + sqref: Incomplete + evalError: Bool[Literal[True]] + twoDigitTextYear: Bool[Literal[True]] + numberStoredAsText: Bool[Literal[True]] + formula: Bool[Literal[True]] + formulaRange: Bool[Literal[True]] + unlockedFormula: Bool[Literal[True]] + emptyCellReference: Bool[Literal[True]] + listDataValidation: Bool[Literal[True]] + calculatedColumn: Bool[Literal[True]] + def __init__( + self, + sqref=None, + evalError: _ConvertibleToBool | None = False, + twoDigitTextYear: _ConvertibleToBool | None = False, + numberStoredAsText: _ConvertibleToBool | None = False, + formula: _ConvertibleToBool | None = False, + formulaRange: _ConvertibleToBool | None = False, + unlockedFormula: _ConvertibleToBool | None = False, + emptyCellReference: _ConvertibleToBool | None = False, + listDataValidation: _ConvertibleToBool | None = False, + calculatedColumn: _ConvertibleToBool | None = False, + ) -> None: ... + +class IgnoredErrors(Serialisable): + tagname: ClassVar[str] + ignoredError: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ignoredError=(), extLst: ExtensionList | None = None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/filters.pyi b/stubs/openpyxl/openpyxl/worksheet/filters.pyi new file mode 100644 index 000000000000..932b53b604d7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/filters.pyi @@ -0,0 +1,317 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from datetime import datetime +from typing import ClassVar, Final, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import ( + Alias, + Bool, + DateTime, + Float, + Integer, + MinMax, + NoneSet, + Set, + String, + Typed, + _ConvertibleToBool, +) +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +_SortConditionSortBy: TypeAlias = Literal["value", "cellColor", "fontColor", "icon"] +_IconSet: TypeAlias = Literal[ + "3Arrows", + "3ArrowsGray", + "3Flags", + "3TrafficLights1", + "3TrafficLights2", + "3Signs", + "3Symbols", + "3Symbols2", + "4Arrows", + "4ArrowsGray", + "4RedToBlack", + "4Rating", + "4TrafficLights", + "5Arrows", + "5ArrowsGray", + "5Rating", + "5Quarters", +] +_SortStateSortMethod: TypeAlias = Literal["stroke", "pinYin"] +_CustomFilterOperator: TypeAlias = Literal[ + "equal", "lessThan", "lessThanOrEqual", "notEqual", "greaterThanOrEqual", "greaterThan" +] +_StringFilterOperator: TypeAlias = Literal["contains", "startswith", "endswith", "wildcard"] +_FiltersCalendarType: TypeAlias = Literal[ + "gregorian", + "gregorianUs", + "gregorianMeFrench", + "gregorianArabic", + "hijri", + "hebrew", + "taiwan", + "japan", + "thai", + "korea", + "saka", + "gregorianXlitEnglish", + "gregorianXlitFrench", +] +_DynamicFilterType: TypeAlias = Literal[ + "null", + "aboveAverage", + "belowAverage", + "tomorrow", + "today", + "yesterday", + "nextWeek", + "thisWeek", + "lastWeek", + "nextMonth", + "thisMonth", + "lastMonth", + "nextQuarter", + "thisQuarter", + "lastQuarter", + "nextYear", + "thisYear", + "lastYear", + "yearToDate", + "Q1", + "Q2", + "Q3", + "Q4", + "M1", + "M2", + "M3", + "M4", + "M5", + "M6", + "M7", + "M8", + "M9", + "M10", + "M11", + "M12", +] +_DateGroupItemDateTimeGrouping: TypeAlias = Literal["year", "month", "day", "hour", "minute", "second"] + +class SortCondition(Serialisable): + tagname: ClassVar[str] + descending: Bool[Literal[True]] + sortBy: NoneSet[_SortConditionSortBy] + ref: Incomplete + customList: String[Literal[True]] + dxfId: Integer[Literal[True]] + iconSet: NoneSet[_IconSet] + iconId: Integer[Literal[True]] + def __init__( + self, + ref=None, + descending: _ConvertibleToBool | None = None, + sortBy: _SortConditionSortBy | Literal["none"] | None = None, + customList: str | None = None, + dxfId: ConvertibleToInt | None = None, + iconSet: _IconSet | Literal["none"] | None = None, + iconId: ConvertibleToInt | None = None, + ) -> None: ... + +class SortState(Serialisable): + tagname: ClassVar[str] + columnSort: Bool[Literal[True]] + caseSensitive: Bool[Literal[True]] + sortMethod: NoneSet[_SortStateSortMethod] + ref: Incomplete + sortCondition: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + columnSort: _ConvertibleToBool | None = None, + caseSensitive: _ConvertibleToBool | None = None, + sortMethod: _SortStateSortMethod | Literal["none"] | None = None, + ref=None, + sortCondition=(), + extLst: Unused = None, + ) -> None: ... + def __bool__(self) -> bool: ... + +class IconFilter(Serialisable): + tagname: ClassVar[str] + iconSet: Set[_IconSet] + iconId: Integer[Literal[True]] + def __init__(self, iconSet: _IconSet, iconId: ConvertibleToInt | None = None) -> None: ... + +class ColorFilter(Serialisable): + tagname: ClassVar[str] + dxfId: Integer[Literal[True]] + cellColor: Bool[Literal[True]] + def __init__(self, dxfId: ConvertibleToInt | None = None, cellColor: _ConvertibleToBool | None = None) -> None: ... + +class DynamicFilter(Serialisable): + tagname: ClassVar[str] + type: Set[_DynamicFilterType] + val: Float[Literal[True]] + valIso: DateTime[Literal[True]] + maxVal: Float[Literal[True]] + maxValIso: DateTime[Literal[True]] + def __init__( + self, + type: _DynamicFilterType, + val: ConvertibleToFloat | None = None, + valIso: datetime | str | None = None, + maxVal: ConvertibleToFloat | None = None, + maxValIso: datetime | str | None = None, + ) -> None: ... + +class CustomFilter(Serialisable): + tagname: ClassVar[str] + val: String[Literal[False]] + operator: Set[_CustomFilterOperator] + def __init__(self, operator: _CustomFilterOperator = "equal", val: str | None = None) -> None: ... + def convert(self) -> BlankFilter | NumberFilter | StringFilter: ... + +class BlankFilter(CustomFilter): + def __init__(self, **kw: Unused) -> None: ... + @property + def operator(self) -> Literal["notEqual"]: ... # type: ignore[override] + @property + def val(self) -> Literal[" "]: ... # type: ignore[override] + +class NumberFilter(CustomFilter): + val: Float[Literal[False]] # type: ignore[assignment] + def __init__(self, operator: _CustomFilterOperator = "equal", val: ConvertibleToFloat | None = None) -> None: ... + +string_format_mapping: Final[dict[_StringFilterOperator, str]] + +class StringFilter(CustomFilter): + operator: Set[_StringFilterOperator] # type: ignore[assignment] + val: String[Literal[False]] + exclude: Bool[Literal[False]] + def __init__( + self, operator: _StringFilterOperator = "contains", val: str | None = None, exclude: _ConvertibleToBool = False + ) -> None: ... + +class CustomFilters(Serialisable): + tagname: ClassVar[str] + _and: Bool[Literal[True]] # Not private. Avoids name clash + customFilter: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, _and: _ConvertibleToBool | None = None, customFilter=()) -> None: ... + +class Top10(Serialisable): + tagname: ClassVar[str] + top: Bool[Literal[True]] + percent: Bool[Literal[True]] + val: Float[Literal[False]] + filterVal: Float[Literal[True]] + + @overload + def __init__( + self, + top: _ConvertibleToBool | None = None, + percent: _ConvertibleToBool | None = None, + *, + val: ConvertibleToFloat, + filterVal: ConvertibleToFloat | None = None, + ) -> None: ... + @overload + def __init__( + self, + top: _ConvertibleToBool | None, + percent: _ConvertibleToBool | None, + val: ConvertibleToFloat, + filterVal: ConvertibleToFloat | None = None, + ) -> None: ... + +class DateGroupItem(Serialisable): + tagname: ClassVar[str] + year: Integer[Literal[False]] + month: MinMax[float, Literal[True]] + day: MinMax[float, Literal[True]] + hour: MinMax[float, Literal[True]] + minute: MinMax[float, Literal[True]] + second: Integer[Literal[True]] + dateTimeGrouping: Set[_DateGroupItemDateTimeGrouping] + + @overload + def __init__( + self, + year: ConvertibleToInt, + month: ConvertibleToFloat | None = None, + day: ConvertibleToFloat | None = None, + hour: ConvertibleToFloat | None = None, + minute: ConvertibleToFloat | None = None, + second: ConvertibleToInt | None = None, + *, + dateTimeGrouping: _DateGroupItemDateTimeGrouping, + ) -> None: ... + @overload + def __init__( + self, + year: ConvertibleToInt, + month: ConvertibleToFloat | None, + day: ConvertibleToFloat | None, + hour: ConvertibleToFloat | None, + minute: ConvertibleToFloat | None, + second: ConvertibleToInt | None, + dateTimeGrouping: _DateGroupItemDateTimeGrouping, + ) -> None: ... + +class Filters(Serialisable): + tagname: ClassVar[str] + blank: Bool[Literal[True]] + calendarType: NoneSet[_FiltersCalendarType] + filter: Incomplete + dateGroupItem: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + blank: _ConvertibleToBool | None = None, + calendarType: _FiltersCalendarType | Literal["none"] | None = None, + filter=(), + dateGroupItem=(), + ) -> None: ... + +class FilterColumn(Serialisable): + tagname: ClassVar[str] + colId: Integer[Literal[False]] + col_id: Alias + hiddenButton: Bool[Literal[True]] + showButton: Bool[Literal[True]] + filters: Typed[Filters, Literal[True]] + top10: Typed[Top10, Literal[True]] + customFilters: Typed[CustomFilters, Literal[True]] + dynamicFilter: Typed[DynamicFilter, Literal[True]] + colorFilter: Typed[ColorFilter, Literal[True]] + iconFilter: Typed[IconFilter, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + colId: ConvertibleToInt, + hiddenButton: _ConvertibleToBool | None = False, + showButton: _ConvertibleToBool | None = True, + filters: Filters | None = None, + top10: Top10 | None = None, + customFilters: CustomFilters | None = None, + dynamicFilter: DynamicFilter | None = None, + colorFilter: ColorFilter | None = None, + iconFilter: IconFilter | None = None, + extLst: Unused = None, + blank=None, + vals=None, + ) -> None: ... + +class AutoFilter(Serialisable): + tagname: ClassVar[str] + ref: Incomplete + filterColumn: Incomplete + sortState: Typed[SortState, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ref=None, filterColumn=(), sortState: SortState | None = None, extLst: Unused = None) -> None: ... + def __bool__(self) -> bool: ... + def add_filter_column(self, col_id, vals, blank: bool = False) -> None: ... + def add_sort_condition(self, ref, descending: bool = False) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/formula.pyi b/stubs/openpyxl/openpyxl/worksheet/formula.pyi new file mode 100644 index 000000000000..73e3601d9f6d --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/formula.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar + +class DataTableFormula: + t: ClassVar[str] + + ref: Incomplete + ca: bool + dt2D: bool + dtr: bool + r1: Incomplete | None + r2: Incomplete | None + del1: bool + del2: bool + + def __init__( + self, + ref, + ca: bool = False, + dt2D: bool = False, + dtr: bool = False, + r1=None, + r2=None, + del1: bool = False, + del2: bool = False, + **kw, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + +class ArrayFormula: + t: ClassVar[str] + ref: Incomplete + text: Incomplete | None + + def __init__(self, ref, text=None) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi b/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi new file mode 100644 index 000000000000..60936a73b7cd --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi @@ -0,0 +1,73 @@ +from _typeshed import ConvertibleToInt +from re import Pattern +from typing import ClassVar, Final, Literal +from typing_extensions import Self + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Alias, Bool, Integer, MatchPattern, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasText + +FONT_PATTERN: Final = '&"(?P.+)"' +COLOR_PATTERN: Final = "&K(?P[A-F0-9]{6})" +SIZE_REGEX: Final = r"&(?P\d+\s?)" +FORMAT_REGEX: Final[Pattern[str]] + +class _HeaderFooterPart(Strict): + text: String[Literal[True]] + font: String[Literal[True]] + size: Integer[Literal[True]] + RGB: ClassVar[str] + color: MatchPattern[str, Literal[True]] + def __init__( + self, text: str | None = None, font: str | None = None, size: ConvertibleToInt | None = None, color: str | None = None + ) -> None: ... + def __bool__(self) -> bool: ... + @classmethod + def from_str(cls, text): ... + +class HeaderFooterItem(Strict): + left: Typed[_HeaderFooterPart, Literal[False]] + center: Typed[_HeaderFooterPart, Literal[False]] + centre: Alias + right: Typed[_HeaderFooterPart, Literal[False]] + def __init__( + self, + left: _HeaderFooterPart | None = None, + right: _HeaderFooterPart | None = None, + center: _HeaderFooterPart | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... + def to_tree(self, tagname: str) -> Element: ... + @classmethod + def from_tree(cls, node: _HasText) -> Self: ... + +class HeaderFooter(Serialisable): + tagname: ClassVar[str] + differentOddEven: Bool[Literal[True]] + differentFirst: Bool[Literal[True]] + scaleWithDoc: Bool[Literal[True]] + alignWithMargins: Bool[Literal[True]] + oddHeader: Typed[HeaderFooterItem, Literal[True]] + oddFooter: Typed[HeaderFooterItem, Literal[True]] + evenHeader: Typed[HeaderFooterItem, Literal[True]] + evenFooter: Typed[HeaderFooterItem, Literal[True]] + firstHeader: Typed[HeaderFooterItem, Literal[True]] + firstFooter: Typed[HeaderFooterItem, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + differentOddEven: _ConvertibleToBool | None = None, + differentFirst: _ConvertibleToBool | None = None, + scaleWithDoc: _ConvertibleToBool | None = None, + alignWithMargins: _ConvertibleToBool | None = None, + oddHeader: HeaderFooterItem | None = None, + oddFooter: HeaderFooterItem | None = None, + evenHeader: HeaderFooterItem | None = None, + evenFooter: HeaderFooterItem | None = None, + firstHeader: HeaderFooterItem | None = None, + firstFooter: HeaderFooterItem | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi b/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi new file mode 100644 index 000000000000..f569caaae701 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.sequence import Sequence +from openpyxl.descriptors.serialisable import Serialisable + +class Hyperlink(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + location: String[Literal[True]] + tooltip: String[Literal[True]] + display: String[Literal[True]] + id: Incomplete + target: String[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + ref: str, + location: str | None = None, + tooltip: str | None = None, + display: str | None = None, + id=None, + target: str | None = None, + ) -> None: ... + +class HyperlinkList(Serialisable): + tagname: ClassVar[str] + hyperlink: Sequence[list[Hyperlink]] + def __init__(self, hyperlink: list[Hyperlink] | tuple[Hyperlink, ...] = ()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/merge.pyi b/stubs/openpyxl/openpyxl/worksheet/merge.pyi new file mode 100644 index 000000000000..0e97147febae --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/merge.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar + +from openpyxl.cell import _CellOrMergedCell +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.worksheet import Worksheet + +from .cell_range import CellRange + +class MergeCell(CellRange): + tagname: ClassVar[str] + # Same as CellRange.coord + # https://github.com/python/mypy/issues/6700 + @property + def ref(self) -> str: ... + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, ref=None) -> None: ... + def __copy__(self): ... + +class MergeCells(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer + mergeCell: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, mergeCell=()) -> None: ... + @property + def count(self) -> int: ... + +class MergedCellRange(CellRange): + ws: Worksheet + start_cell: _CellOrMergedCell + def __init__(self, worksheet: Worksheet, coord) -> None: ... + def format(self) -> None: ... + def __contains__(self, coord: str) -> bool: ... + def __copy__(self): ... diff --git a/stubs/openpyxl/openpyxl/worksheet/ole.pyi b/stubs/openpyxl/openpyxl/worksheet/ole.pyi new file mode 100644 index 000000000000..fedb4beaf3ef --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/ole.pyi @@ -0,0 +1,116 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.spreadsheet_drawing import AnchorMarker + +_OleObjectDvAspect: TypeAlias = Literal["DVASPECT_CONTENT", "DVASPECT_ICON"] +_OleObjectOleUpdate: TypeAlias = Literal["OLEUPDATE_ALWAYS", "OLEUPDATE_ONCALL"] + +class ObjectAnchor(Serialisable): + tagname: ClassVar[str] + _from: Typed[AnchorMarker, Literal[False]] # Not private. Avoids name clash + to: Typed[AnchorMarker, Literal[False]] + moveWithCells: Bool[Literal[True]] + sizeWithCells: Bool[Literal[True]] + z_order: Integer[Literal[True]] + def __init__( + self, + _from: AnchorMarker, + to: AnchorMarker, + moveWithCells: _ConvertibleToBool | None = False, + sizeWithCells: _ConvertibleToBool | None = False, + z_order: ConvertibleToInt | None = None, + ) -> None: ... + +class ObjectPr(Serialisable): + tagname: ClassVar[str] + anchor: Typed[ObjectAnchor, Literal[False]] + locked: Bool[Literal[True]] + defaultSize: Bool[Literal[True]] + _print: Bool[Literal[True]] # Not private. Avoids name clash + disabled: Bool[Literal[True]] + uiObject: Bool[Literal[True]] + autoFill: Bool[Literal[True]] + autoLine: Bool[Literal[True]] + autoPict: Bool[Literal[True]] + macro: String[Literal[False]] + altText: String[Literal[True]] + dde: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + anchor: ObjectAnchor, + locked: _ConvertibleToBool | None = None, + defaultSize: _ConvertibleToBool | None = None, + _print: _ConvertibleToBool | None = None, + disabled: _ConvertibleToBool | None = None, + uiObject: _ConvertibleToBool | None = None, + autoFill: _ConvertibleToBool | None = None, + autoLine: _ConvertibleToBool | None = None, + autoPict: _ConvertibleToBool | None = None, + *, + macro: str, + altText: str | None = None, + dde: _ConvertibleToBool | None = False, + ) -> None: ... + @overload + def __init__( + self, + anchor: ObjectAnchor, + locked: _ConvertibleToBool | None, + defaultSize: _ConvertibleToBool | None, + _print: _ConvertibleToBool | None, + disabled: _ConvertibleToBool | None, + uiObject: _ConvertibleToBool | None, + autoFill: _ConvertibleToBool | None, + autoLine: _ConvertibleToBool | None, + autoPict: _ConvertibleToBool | None, + macro: str, + altText: str | None = None, + dde: _ConvertibleToBool | None = False, + ) -> None: ... + +class OleObject(Serialisable): + tagname: ClassVar[str] + objectPr: Typed[ObjectPr, Literal[True]] + progId: String[Literal[True]] + dvAspect: Set[_OleObjectDvAspect] + link: String[Literal[True]] + oleUpdate: Set[_OleObjectOleUpdate] + autoLoad: Bool[Literal[True]] + shapeId: Integer[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + objectPr: ObjectPr | None = None, + progId: str | None = None, + dvAspect: _OleObjectDvAspect = "DVASPECT_CONTENT", + link: str | None = None, + *, + oleUpdate: _OleObjectOleUpdate, + autoLoad: _ConvertibleToBool | None = False, + shapeId: ConvertibleToInt, + ) -> None: ... + @overload + def __init__( + self, + objectPr: ObjectPr | None, + progId: str | None, + dvAspect: _OleObjectDvAspect, + link: str | None, + oleUpdate: _OleObjectOleUpdate, + autoLoad: _ConvertibleToBool | None, + shapeId: ConvertibleToInt, + ) -> None: ... + +class OleObjects(Serialisable): + tagname: ClassVar[str] + oleObject: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, oleObject=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/page.pyi b/stubs/openpyxl/openpyxl/worksheet/page.pyi new file mode 100644 index 000000000000..d86b80dd759f --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/page.pyi @@ -0,0 +1,108 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias +from typing_extensions import Self + +from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.worksheet.properties import PageSetupProperties + +_PrintPageSetupOrientation: TypeAlias = Literal["default", "portrait", "landscape"] +_PrintPageSetupPageOrder: TypeAlias = Literal["downThenOver", "overThenDown"] +_PrintPageSetupCellComments: TypeAlias = Literal["asDisplayed", "atEnd"] +_PrintPageSetupErrors: TypeAlias = Literal["displayed", "blank", "dash", "NA"] + +class PrintPageSetup(Serialisable): + tagname: ClassVar[str] + orientation: NoneSet[_PrintPageSetupOrientation] + paperSize: Integer[Literal[True]] + scale: Integer[Literal[True]] + fitToHeight: Integer[Literal[True]] + fitToWidth: Integer[Literal[True]] + firstPageNumber: Integer[Literal[True]] + useFirstPageNumber: Bool[Literal[True]] + paperHeight: Incomplete + paperWidth: Incomplete + pageOrder: NoneSet[_PrintPageSetupPageOrder] + usePrinterDefaults: Bool[Literal[True]] + blackAndWhite: Bool[Literal[True]] + draft: Bool[Literal[True]] + cellComments: NoneSet[_PrintPageSetupCellComments] + errors: NoneSet[_PrintPageSetupErrors] + horizontalDpi: Integer[Literal[True]] + verticalDpi: Integer[Literal[True]] + copies: Integer[Literal[True]] + id: Incomplete + def __init__( + self, + worksheet=None, + orientation: _PrintPageSetupOrientation | Literal["none"] | None = None, + paperSize: ConvertibleToInt | None = None, + scale: ConvertibleToInt | None = None, + fitToHeight: ConvertibleToInt | None = None, + fitToWidth: ConvertibleToInt | None = None, + firstPageNumber: ConvertibleToInt | None = None, + useFirstPageNumber: _ConvertibleToBool | None = None, + paperHeight=None, + paperWidth=None, + pageOrder: _PrintPageSetupPageOrder | Literal["none"] | None = None, + usePrinterDefaults: _ConvertibleToBool | None = None, + blackAndWhite: _ConvertibleToBool | None = None, + draft: _ConvertibleToBool | None = None, + cellComments: _PrintPageSetupCellComments | Literal["none"] | None = None, + errors: _PrintPageSetupErrors | Literal["none"] | None = None, + horizontalDpi: ConvertibleToInt | None = None, + verticalDpi: ConvertibleToInt | None = None, + copies: ConvertibleToInt | None = None, + id=None, + ) -> None: ... + def __bool__(self) -> bool: ... + @property + def sheet_properties(self) -> PageSetupProperties | None: ... + + @property + def fitToPage(self) -> bool | None: ... + @fitToPage.setter + def fitToPage(self, value: _ConvertibleToBool | None) -> None: ... + + @property + def autoPageBreaks(self) -> bool | None: ... + @autoPageBreaks.setter + def autoPageBreaks(self, value: _ConvertibleToBool | None) -> None: ... + + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + +class PrintOptions(Serialisable): + tagname: ClassVar[str] + horizontalCentered: Bool[Literal[True]] + verticalCentered: Bool[Literal[True]] + headings: Bool[Literal[True]] + gridLines: Bool[Literal[True]] + gridLinesSet: Bool[Literal[True]] + def __init__( + self, + horizontalCentered: _ConvertibleToBool | None = None, + verticalCentered: _ConvertibleToBool | None = None, + headings: _ConvertibleToBool | None = None, + gridLines: _ConvertibleToBool | None = None, + gridLinesSet: _ConvertibleToBool | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... + +class PageMargins(Serialisable): + tagname: ClassVar[str] + left: Float[Literal[False]] + right: Float[Literal[False]] + top: Float[Literal[False]] + bottom: Float[Literal[False]] + header: Float[Literal[False]] + footer: Float[Literal[False]] + def __init__( + self, + left: ConvertibleToFloat = 0.75, + right: ConvertibleToFloat = 0.75, + top: ConvertibleToFloat = 1, + bottom: ConvertibleToFloat = 1, + header: ConvertibleToFloat = 0.5, + footer: ConvertibleToFloat = 0.5, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi b/stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi new file mode 100644 index 000000000000..b0fe838d39db --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi @@ -0,0 +1,48 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Break(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[True]] + min: Integer[Literal[True]] + max: Integer[Literal[True]] + man: Bool[Literal[True]] + pt: Bool[Literal[True]] + def __init__( + self, + id: ConvertibleToInt | None = 0, + min: ConvertibleToInt | None = 0, + max: ConvertibleToInt | None = 16383, + man: _ConvertibleToBool | None = True, + pt: _ConvertibleToBool | None = None, + ) -> None: ... + +class RowBreak(Serialisable): + tagname: ClassVar[str] + # Overwritten by properties below + # count: Integer + # manualBreakCount: Integer + brk: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, manualBreakCount: Unused = None, brk=()) -> None: ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + @property + def count(self) -> int: ... + @property + def manualBreakCount(self) -> int: ... + def append(self, brk=None) -> None: ... + +PageBreak = RowBreak + +class ColBreak(RowBreak): + tagname: ClassVar[str] + # Same as parent + # count = RowBreak.count + # manualBreakCount = RowBreak.manualBreakCount + # brk = RowBreak.brk + __attrs__: ClassVar[tuple[str, ...]] diff --git a/stubs/openpyxl/openpyxl/worksheet/picture.pyi b/stubs/openpyxl/openpyxl/worksheet/picture.pyi new file mode 100644 index 000000000000..071947859eab --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/picture.pyi @@ -0,0 +1,6 @@ +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class SheetBackgroundPicture(Serialisable): + tagname: ClassVar[str] diff --git a/stubs/openpyxl/openpyxl/worksheet/print_settings.pyi b/stubs/openpyxl/openpyxl/worksheet/print_settings.pyi new file mode 100644 index 000000000000..f2d0f4c44155 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/print_settings.pyi @@ -0,0 +1,55 @@ +from _typeshed import ConvertibleToInt, Unused +from re import Pattern +from typing import Final, Literal, overload +from typing_extensions import Self + +from openpyxl.descriptors import Integer, Strict, String +from openpyxl.descriptors.base import Typed +from openpyxl.utils.cell import SHEETRANGE_RE as SHEETRANGE_RE + +from .cell_range import MultiCellRange + +COL_RANGE: Final[str] +COL_RANGE_RE: Final[Pattern[str]] +ROW_RANGE: Final[str] +ROW_RANGE_RE: Final[Pattern[str]] +TITLES_REGEX: Final[Pattern[str]] +PRINT_AREA_RE: Final[Pattern[str]] + +class ColRange(Strict): + min_col: String[Literal[False]] + max_col: String[Literal[False]] + + @overload + def __init__(self, range_string: None = None, *, min_col: str, max_col: str) -> None: ... + @overload + def __init__(self, range_string, min_col: Unused = None, max_col: Unused = None) -> None: ... + + def __eq__(self, other: object) -> bool: ... + +class RowRange(Strict): + min_row: Integer[Literal[False]] + max_row: Integer[Literal[False]] + + @overload + def __init__(self, range_string: None, min_row: ConvertibleToInt, max_row: ConvertibleToInt) -> None: ... + @overload + def __init__(self, range_string, min_row: Unused = None, max_row: Unused = None) -> None: ... + + def __eq__(self, other: object) -> bool: ... + +class PrintTitles(Strict): + cols: Typed[ColRange, Literal[True]] + rows: Typed[RowRange, Literal[True]] + title: String[Literal[False]] + def __init__(self, cols: ColRange | None = None, rows: RowRange | None = None, title: str = "") -> None: ... + @classmethod + def from_string(cls, value: str) -> Self: ... + def __eq__(self, other: object) -> bool: ... + +class PrintArea(MultiCellRange): + title: str + @classmethod + def from_string(cls, value) -> Self: ... + def __init__(self, ranges=(), title: Unused = "") -> None: ... + def __eq__(self, other: str | MultiCellRange) -> bool: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/worksheet/properties.pyi b/stubs/openpyxl/openpyxl/worksheet/properties.pyi new file mode 100644 index 000000000000..ff31bb890d13 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/properties.pyi @@ -0,0 +1,56 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor + +class Outline(Serialisable): + tagname: ClassVar[str] + applyStyles: Bool[Literal[True]] + summaryBelow: Bool[Literal[True]] + summaryRight: Bool[Literal[True]] + showOutlineSymbols: Bool[Literal[True]] + def __init__( + self, + applyStyles: _ConvertibleToBool | None = None, + summaryBelow: _ConvertibleToBool | None = None, + summaryRight: _ConvertibleToBool | None = None, + showOutlineSymbols: _ConvertibleToBool | None = None, + ) -> None: ... + +class PageSetupProperties(Serialisable): + tagname: ClassVar[str] + autoPageBreaks: Bool[Literal[True]] + fitToPage: Bool[Literal[True]] + def __init__(self, autoPageBreaks: _ConvertibleToBool | None = None, fitToPage: _ConvertibleToBool | None = None) -> None: ... + +class WorksheetProperties(Serialisable): + tagname: ClassVar[str] + codeName: String[Literal[True]] + enableFormatConditionsCalculation: Bool[Literal[True]] + filterMode: Bool[Literal[True]] + published: Bool[Literal[True]] + syncHorizontal: Bool[Literal[True]] + syncRef: String[Literal[True]] + syncVertical: Bool[Literal[True]] + transitionEvaluation: Bool[Literal[True]] + transitionEntry: Bool[Literal[True]] + tabColor: ColorDescriptor[Literal[True]] + outlinePr: Typed[Outline, Literal[True]] + pageSetUpPr: Typed[PageSetupProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + codeName: str | None = None, + enableFormatConditionsCalculation: _ConvertibleToBool | None = None, + filterMode: _ConvertibleToBool | None = None, + published: _ConvertibleToBool | None = None, + syncHorizontal: _ConvertibleToBool | None = None, + syncRef: str | None = None, + syncVertical: _ConvertibleToBool | None = None, + transitionEvaluation: _ConvertibleToBool | None = None, + transitionEntry: _ConvertibleToBool | None = None, + tabColor: str | Color | None = None, + outlinePr: Outline | None = None, + pageSetUpPr: PageSetupProperties | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/protection.pyi b/stubs/openpyxl/openpyxl/worksheet/protection.pyi new file mode 100644 index 000000000000..02bf4dd923af --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/protection.pyi @@ -0,0 +1,79 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class _Protected: + @overload + def set_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + @property + def password(self) -> str | None: ... + @password.setter + def password(self, value: str) -> None: ... + +class SheetProtection(Serialisable, _Protected): + tagname: ClassVar[str] + sheet: Bool[Literal[False]] + enabled: Alias + objects: Bool[Literal[False]] + scenarios: Bool[Literal[False]] + formatCells: Bool[Literal[False]] + formatColumns: Bool[Literal[False]] + formatRows: Bool[Literal[False]] + insertColumns: Bool[Literal[False]] + insertRows: Bool[Literal[False]] + insertHyperlinks: Bool[Literal[False]] + deleteColumns: Bool[Literal[False]] + deleteRows: Bool[Literal[False]] + selectLockedCells: Bool[Literal[False]] + selectUnlockedCells: Bool[Literal[False]] + sort: Bool[Literal[False]] + autoFilter: Bool[Literal[False]] + pivotTables: Bool[Literal[False]] + saltValue: Incomplete + spinCount: Integer[Literal[True]] + algorithmName: String[Literal[True]] + hashValue: Incomplete + __attrs__: ClassVar[tuple[str, ...]] + password: Incomplete + def __init__( + self, + sheet: _ConvertibleToBool = False, + objects: _ConvertibleToBool = False, + scenarios: _ConvertibleToBool = False, + formatCells: _ConvertibleToBool = True, + formatRows: _ConvertibleToBool = True, + formatColumns: _ConvertibleToBool = True, + insertColumns: _ConvertibleToBool = True, + insertRows: _ConvertibleToBool = True, + insertHyperlinks: _ConvertibleToBool = True, + deleteColumns: _ConvertibleToBool = True, + deleteRows: _ConvertibleToBool = True, + selectLockedCells: _ConvertibleToBool = False, + selectUnlockedCells: _ConvertibleToBool = False, + sort: _ConvertibleToBool = True, + autoFilter: _ConvertibleToBool = True, + pivotTables: _ConvertibleToBool = True, + password=None, + algorithmName: str | None = None, + saltValue=None, + spinCount: ConvertibleToInt | None = None, + hashValue=None, + ) -> None: ... + + @overload + def set_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + def enable(self) -> None: ... + def disable(self) -> None: ... + def __bool__(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/related.pyi b/stubs/openpyxl/openpyxl/worksheet/related.pyi new file mode 100644 index 000000000000..3e31438cea64 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/related.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete, Unused + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +class Related(Serialisable): + id: Incomplete + def __init__(self, id=None) -> None: ... + def to_tree(self, tagname: str | None, idx: Unused = None) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/worksheet/scenario.pyi b/stubs/openpyxl/openpyxl/worksheet/scenario.pyi new file mode 100644 index 000000000000..8ae7f0dca07e --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/scenario.pyi @@ -0,0 +1,89 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, Convertible, Integer, String, _ConvertibleToBool, _ConvertibleToMultiCellRange +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.cell_range import MultiCellRange + +class InputCells(Serialisable): + tagname: ClassVar[str] + r: String[Literal[False]] + deleted: Bool[Literal[True]] + undone: Bool[Literal[True]] + val: String[Literal[False]] + numFmtId: Integer[Literal[True]] + + @overload + def __init__( + self, + r: str, + deleted: _ConvertibleToBool | None = False, + undone: _ConvertibleToBool | None = False, + *, + val: str, + numFmtId: ConvertibleToInt | None = None, + ) -> None: ... + @overload + def __init__( + self, + r: str, + deleted: _ConvertibleToBool | None, + undone: _ConvertibleToBool | None, + val: str, + numFmtId: ConvertibleToInt | None = None, + ) -> None: ... + +class Scenario(Serialisable): + tagname: ClassVar[str] + inputCells: Incomplete + name: String[Literal[False]] + locked: Bool[Literal[True]] + hidden: Bool[Literal[True]] + user: String[Literal[True]] + comment: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + inputCells=(), + *, + name: str, + locked: _ConvertibleToBool | None = False, + hidden: _ConvertibleToBool | None = False, + count: Unused = None, + user: str | None = None, + comment: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + inputCells, + name: str, + locked: _ConvertibleToBool | None = False, + hidden: _ConvertibleToBool | None = False, + count: Unused = None, + user: str | None = None, + comment: str | None = None, + ) -> None: ... + + @property + def count(self) -> int: ... + +class ScenarioList(Serialisable): + tagname: ClassVar[str] + scenario: Incomplete + current: Integer[Literal[True]] + show: Integer[Literal[True]] + sqref: Convertible[MultiCellRange, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scenario=(), + current: ConvertibleToInt | None = None, + show: ConvertibleToInt | None = None, + sqref: _ConvertibleToMultiCellRange | None = None, + ) -> None: ... + def append(self, scenario) -> None: ... + def __bool__(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi b/stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi new file mode 100644 index 000000000000..9e45422c2ec0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi @@ -0,0 +1,50 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class CellSmartTagPr(Serialisable): + tagname: ClassVar[str] + key: String[Literal[False]] + val: String[Literal[False]] + def __init__(self, key: str, val: str) -> None: ... + +class CellSmartTag(Serialisable): + tagname: ClassVar[str] + cellSmartTagPr: Incomplete + type: Integer[Literal[False]] + deleted: Bool[Literal[True]] + xmlBased: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + cellSmartTagPr=(), + *, + type: ConvertibleToInt, + deleted: _ConvertibleToBool | None = False, + xmlBased: _ConvertibleToBool | None = False, + ) -> None: ... + @overload + def __init__( + self, + cellSmartTagPr, + type: ConvertibleToInt, + deleted: _ConvertibleToBool | None = False, + xmlBased: _ConvertibleToBool | None = False, + ) -> None: ... + +class CellSmartTags(Serialisable): + tagname: ClassVar[str] + cellSmartTag: Incomplete + r: String[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cellSmartTag, r: str) -> None: ... + +class SmartTags(Serialisable): + tagname: ClassVar[str] + cellSmartTags: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cellSmartTags=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/table.pyi b/stubs/openpyxl/openpyxl/worksheet/table.pyi new file mode 100644 index 000000000000..f8abd7b02a54 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/table.pyi @@ -0,0 +1,225 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Iterator +from typing import ClassVar, Final, Literal, TypeAlias, overload +from typing_extensions import Self + +from openpyxl.descriptors import Strict, String +from openpyxl.descriptors.base import Alias, Bool, Integer, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.worksheet.filters import AutoFilter, SortState +from openpyxl.xml.functions import Element + +_TableColumnTotalsRowFunction: TypeAlias = Literal[ + "sum", "min", "max", "average", "count", "countNums", "stdDev", "var", "custom" +] +_TableTableType: TypeAlias = Literal["worksheet", "xml", "queryTable"] + +TABLESTYLES: Final[tuple[str, ...]] +PIVOTSTYLES: Final[tuple[str, ...]] + +class TableStyleInfo(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + showFirstColumn: Bool[Literal[True]] + showLastColumn: Bool[Literal[True]] + showRowStripes: Bool[Literal[True]] + showColumnStripes: Bool[Literal[True]] + def __init__( + self, + name: str | None = None, + showFirstColumn: _ConvertibleToBool | None = None, + showLastColumn: _ConvertibleToBool | None = None, + showRowStripes: _ConvertibleToBool | None = None, + showColumnStripes: _ConvertibleToBool | None = None, + ) -> None: ... + +class XMLColumnProps(Serialisable): + tagname: ClassVar[str] + mapId: Integer[Literal[False]] + xpath: String[Literal[False]] + denormalized: Bool[Literal[True]] + xmlDataType: String[Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + mapId: ConvertibleToInt, + xpath: str, + denormalized: _ConvertibleToBool | None = None, + *, + xmlDataType: str, + extLst: Unused = None, + ) -> None: ... + @overload + def __init__( + self, + mapId: ConvertibleToInt, + xpath: str, + denormalized: _ConvertibleToBool | None, + xmlDataType: str, + extLst: Unused = None, + ) -> None: ... + +class TableFormula(Serialisable): + tagname: ClassVar[str] + array: Bool[Literal[True]] + attr_text: Incomplete + text: Alias + def __init__(self, array: _ConvertibleToBool | None = None, attr_text=None) -> None: ... + +class TableColumn(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[False]] + uniqueName: String[Literal[True]] + name: String[Literal[False]] + totalsRowFunction: NoneSet[_TableColumnTotalsRowFunction] + totalsRowLabel: String[Literal[True]] + queryTableFieldId: Integer[Literal[True]] + headerRowDxfId: Integer[Literal[True]] + dataDxfId: Integer[Literal[True]] + totalsRowDxfId: Integer[Literal[True]] + headerRowCellStyle: String[Literal[True]] + dataCellStyle: String[Literal[True]] + totalsRowCellStyle: String[Literal[True]] + calculatedColumnFormula: Typed[TableFormula, Literal[True]] + totalsRowFormula: Typed[TableFormula, Literal[True]] + xmlColumnPr: Typed[XMLColumnProps, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + id: ConvertibleToInt, + uniqueName: str | None = None, + *, + name: str, + totalsRowFunction: _TableColumnTotalsRowFunction | Literal["none"] | None = None, + totalsRowLabel: str | None = None, + queryTableFieldId: ConvertibleToInt | None = None, + headerRowDxfId: ConvertibleToInt | None = None, + dataDxfId: ConvertibleToInt | None = None, + totalsRowDxfId: ConvertibleToInt | None = None, + headerRowCellStyle: str | None = None, + dataCellStyle: str | None = None, + totalsRowCellStyle: str | None = None, + calculatedColumnFormula: TableFormula | None = None, + totalsRowFormula: TableFormula | None = None, + xmlColumnPr: XMLColumnProps | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: ConvertibleToInt, + uniqueName: str | None, + name: str, + totalsRowFunction: _TableColumnTotalsRowFunction | Literal["none"] | None = None, + totalsRowLabel: str | None = None, + queryTableFieldId: ConvertibleToInt | None = None, + headerRowDxfId: ConvertibleToInt | None = None, + dataDxfId: ConvertibleToInt | None = None, + totalsRowDxfId: ConvertibleToInt | None = None, + headerRowCellStyle: str | None = None, + dataCellStyle: str | None = None, + totalsRowCellStyle: str | None = None, + calculatedColumnFormula: TableFormula | None = None, + totalsRowFormula: TableFormula | None = None, + xmlColumnPr: XMLColumnProps | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + + def __iter__(self) -> Iterator[tuple[str, str]]: ... + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + +class TableNameDescriptor(String[Incomplete]): + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class Table(Serialisable): + mime_type: str + tagname: ClassVar[str] + id: Integer[Literal[False]] + name: String[Literal[True]] + displayName: Incomplete + comment: String[Literal[True]] + ref: Incomplete + tableType: NoneSet[_TableTableType] + headerRowCount: Integer[Literal[True]] + insertRow: Bool[Literal[True]] + insertRowShift: Bool[Literal[True]] + totalsRowCount: Integer[Literal[True]] + totalsRowShown: Bool[Literal[True]] + published: Bool[Literal[True]] + headerRowDxfId: Integer[Literal[True]] + dataDxfId: Integer[Literal[True]] + totalsRowDxfId: Integer[Literal[True]] + headerRowBorderDxfId: Integer[Literal[True]] + tableBorderDxfId: Integer[Literal[True]] + totalsRowBorderDxfId: Integer[Literal[True]] + headerRowCellStyle: String[Literal[True]] + dataCellStyle: String[Literal[True]] + totalsRowCellStyle: String[Literal[True]] + connectionId: Integer[Literal[True]] + autoFilter: Typed[AutoFilter, Literal[True]] + sortState: Typed[SortState, Literal[True]] + tableColumns: Incomplete + tableStyleInfo: Typed[TableStyleInfo, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + id: ConvertibleToInt = 1, + displayName=None, + ref=None, + name: str | None = None, + comment: str | None = None, + tableType: _TableTableType | Literal["none"] | None = None, + headerRowCount: ConvertibleToInt | None = 1, + insertRow: _ConvertibleToBool | None = None, + insertRowShift: _ConvertibleToBool | None = None, + totalsRowCount: ConvertibleToInt | None = None, + totalsRowShown: _ConvertibleToBool | None = None, + published: _ConvertibleToBool | None = None, + headerRowDxfId: ConvertibleToInt | None = None, + dataDxfId: ConvertibleToInt | None = None, + totalsRowDxfId: ConvertibleToInt | None = None, + headerRowBorderDxfId: ConvertibleToInt | None = None, + tableBorderDxfId: ConvertibleToInt | None = None, + totalsRowBorderDxfId: ConvertibleToInt | None = None, + headerRowCellStyle: str | None = None, + dataCellStyle: str | None = None, + totalsRowCellStyle: str | None = None, + connectionId: ConvertibleToInt | None = None, + autoFilter: AutoFilter | None = None, + sortState: SortState | None = None, + tableColumns=(), + tableStyleInfo: TableStyleInfo | None = None, + extLst: Unused = None, + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... + @property + def column_names(self) -> list[str]: ... + +class TablePartList(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer + tablePart: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, tablePart=()) -> None: ... + def append(self, part) -> None: ... + @property + def count(self) -> int: ... + def __bool__(self) -> bool: ... + +class TableList(dict[Incomplete, Incomplete]): + def add(self, table) -> None: ... + def get(self, name=None, table_range=None): ... + def items(self): ... diff --git a/stubs/openpyxl/openpyxl/worksheet/views.pyi b/stubs/openpyxl/openpyxl/worksheet/views.pyi new file mode 100644 index 000000000000..70e6420988fd --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/views.pyi @@ -0,0 +1,98 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.sequence import Sequence +from openpyxl.descriptors.serialisable import Serialisable + +_Pane: TypeAlias = Literal["bottomRight", "topRight", "bottomLeft", "topLeft"] +_SheetViewView: TypeAlias = Literal["normal", "pageBreakPreview", "pageLayout"] +_PaneState: TypeAlias = Literal["split", "frozen", "frozenSplit"] + +class Pane(Serialisable): + xSplit: Float[Literal[True]] + ySplit: Float[Literal[True]] + topLeftCell: String[Literal[True]] + activePane: Set[_Pane] + state: Set[_PaneState] + def __init__( + self, + xSplit: ConvertibleToFloat | None = None, + ySplit: ConvertibleToFloat | None = None, + topLeftCell: str | None = None, + activePane: _Pane = "topLeft", + state: _PaneState = "split", + ) -> None: ... + +class Selection(Serialisable): + pane: NoneSet[_Pane] + activeCell: String[Literal[True]] + activeCellId: Integer[Literal[True]] + sqref: String[Literal[True]] + def __init__( + self, + pane: _Pane | Literal["none"] | None = None, + activeCell: str | None = "A1", + activeCellId: ConvertibleToInt | None = None, + sqref: str | None = "A1", + ) -> None: ... + +class SheetView(Serialisable): + tagname: ClassVar[str] + windowProtection: Bool[Literal[True]] + showFormulas: Bool[Literal[True]] + showGridLines: Bool[Literal[True]] + showRowColHeaders: Bool[Literal[True]] + showZeros: Bool[Literal[True]] + rightToLeft: Bool[Literal[True]] + tabSelected: Bool[Literal[True]] + showRuler: Bool[Literal[True]] + showOutlineSymbols: Bool[Literal[True]] + defaultGridColor: Bool[Literal[True]] + showWhiteSpace: Bool[Literal[True]] + view: NoneSet[_SheetViewView] + topLeftCell: String[Literal[True]] + colorId: Integer[Literal[True]] + zoomScale: Integer[Literal[True]] + zoomScaleNormal: Integer[Literal[True]] + zoomScaleSheetLayoutView: Integer[Literal[True]] + zoomScalePageLayoutView: Integer[Literal[True]] + zoomToFit: Bool[Literal[True]] + workbookViewId: Integer[Literal[True]] + selection: Incomplete + pane: Typed[Pane, Literal[True]] + def __init__( + self, + windowProtection: _ConvertibleToBool | None = None, + showFormulas: _ConvertibleToBool | None = None, + showGridLines: _ConvertibleToBool | None = None, + showRowColHeaders: _ConvertibleToBool | None = None, + showZeros: _ConvertibleToBool | None = None, + rightToLeft: _ConvertibleToBool | None = None, + tabSelected: _ConvertibleToBool | None = None, + showRuler: _ConvertibleToBool | None = None, + showOutlineSymbols: _ConvertibleToBool | None = None, + defaultGridColor: _ConvertibleToBool | None = None, + showWhiteSpace: _ConvertibleToBool | None = None, + view: _SheetViewView | Literal["none"] | None = None, + topLeftCell: str | None = None, + colorId: ConvertibleToInt | None = None, + zoomScale: ConvertibleToInt | None = None, + zoomScaleNormal: ConvertibleToInt | None = None, + zoomScaleSheetLayoutView: ConvertibleToInt | None = None, + zoomScalePageLayoutView: ConvertibleToInt | None = None, + zoomToFit: _ConvertibleToBool | None = None, + workbookViewId: ConvertibleToInt | None = 0, + selection=None, + pane: Pane | None = None, + ) -> None: ... + +class SheetViewList(Serialisable): + tagname: ClassVar[str] + sheetView: Sequence[list[SheetView]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetView: SheetView | None = None, extLst: Unused = None) -> None: ... + @property + def active(self) -> SheetView: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi b/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi new file mode 100644 index 000000000000..be41858dc291 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi @@ -0,0 +1,289 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Generator, Iterable, Iterator +from types import GeneratorType +from typing import Any, Final, Literal, overload +from typing_extensions import Never, deprecated + +from openpyxl import _Decodable, _VisibilityType +from openpyxl.cell import _AnyCellValue, _CellGetValue, _CellOrMergedCell, _CellSetValue +from openpyxl.cell.cell import Cell +from openpyxl.chart._chart import ChartBase +from openpyxl.drawing.image import Image +from openpyxl.formatting.formatting import ConditionalFormattingList +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.workbook.defined_name import DefinedNameDict +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange +from openpyxl.worksheet.datavalidation import DataValidation, DataValidationList +from openpyxl.worksheet.dimensions import ColumnDimension, DimensionHolder, RowDimension, SheetFormatProperties +from openpyxl.worksheet.filters import AutoFilter +from openpyxl.worksheet.page import PageMargins, PrintOptions, PrintPageSetup +from openpyxl.worksheet.pagebreak import ColBreak, RowBreak +from openpyxl.worksheet.properties import WorksheetProperties +from openpyxl.worksheet.protection import SheetProtection +from openpyxl.worksheet.scenario import ScenarioList +from openpyxl.worksheet.table import Table, TableList +from openpyxl.worksheet.views import SheetView, SheetViewList + +class Worksheet(_WorkbookChild): + mime_type: str + BREAK_NONE: Final = 0 + BREAK_ROW: Final = 1 + BREAK_COLUMN: Final = 2 + + SHEETSTATE_VISIBLE: Final = "visible" + SHEETSTATE_HIDDEN: Final = "hidden" + SHEETSTATE_VERYHIDDEN: Final = "veryHidden" + + PAPERSIZE_LETTER: Final = "1" + PAPERSIZE_LETTER_SMALL: Final = "2" + PAPERSIZE_TABLOID: Final = "3" + PAPERSIZE_LEDGER: Final = "4" + PAPERSIZE_LEGAL: Final = "5" + PAPERSIZE_STATEMENT: Final = "6" + PAPERSIZE_EXECUTIVE: Final = "7" + PAPERSIZE_A3: Final = "8" + PAPERSIZE_A4: Final = "9" + PAPERSIZE_A4_SMALL: Final = "10" + PAPERSIZE_A5: Final = "11" + + ORIENTATION_PORTRAIT: Final = "portrait" + ORIENTATION_LANDSCAPE: Final = "landscape" + + _cells: dict[tuple[int, int], _CellOrMergedCell] # private but very useful to understand typing + row_dimensions: DimensionHolder[int, RowDimension] + column_dimensions: DimensionHolder[str, ColumnDimension] + row_breaks: RowBreak + col_breaks: ColBreak + merged_cells: MultiCellRange + data_validations: DataValidationList + sheet_state: _VisibilityType + page_setup: PrintPageSetup + print_options: PrintOptions + page_margins: PageMargins + views: SheetViewList + protection: SheetProtection + defined_names: DefinedNameDict + auto_filter: AutoFilter + conditional_formatting: ConditionalFormattingList + legacy_drawing: Incomplete | None + sheet_properties: WorksheetProperties + sheet_format: SheetFormatProperties + scenarios: ScenarioList + + def __init__(self, parent: Workbook | None, title: str | _Decodable | None = None) -> None: ... + @property + def sheet_view(self) -> SheetView: ... + @property + def selected_cell(self) -> str | None: ... + @property + def active_cell(self) -> str | None: ... + @property + def array_formulae(self) -> dict[str, str]: ... + @property + def show_gridlines(self) -> bool | None: ... + + @property + def freeze_panes(self) -> str | None: ... + @freeze_panes.setter + def freeze_panes(self, topLeftCell: str | Cell | None = None) -> None: ... + + # A MergedCell value should be kept to None + @overload + def cell(self, row: int, column: int, value: None = None) -> _CellOrMergedCell: ... + @overload + def cell(self, row: int, column: int, value: _CellSetValue = None) -> Cell: ... + + # An int is necessarily a row selection + @overload + def __getitem__(self, key: int) -> tuple[_CellOrMergedCell, ...]: ... + # A slice is necessarily a row or rows, even if targetting a single cell + @overload + def __getitem__(self, key: slice) -> tuple[Any, ...]: ... # tuple[AnyOf[_CellOrMergedCell, tuple[_CellOrMergedCell, ...]]] + # A str could be an individual cell, row, column or full range + @overload + def __getitem__( + self, key: str + ) -> Any: ... # AnyOf[_CellOrMergedCell, tuple[_CellOrMergedCell, ...], tuple[tuple[_CellOrMergedCell, ...], ...]] + + def __setitem__(self, key: str, value: _CellSetValue) -> None: ... + def __iter__(self) -> Iterator[tuple[_CellOrMergedCell, ...]]: ... + def __delitem__(self, key: str) -> None: ... + @property + def min_row(self) -> int: ... + @property + def max_row(self) -> int: ... + @property + def min_column(self) -> int: ... + @property + def max_column(self) -> int: ... + def calculate_dimension(self) -> str: ... + @property + def dimensions(self) -> str: ... + + @overload + def iter_rows( + self, min_row: int | None, max_row: int | None, min_col: int | None, max_col: int | None, values_only: Literal[True] + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_rows( + self, + min_row: int | None = None, + max_row: int | None = None, + min_col: int | None = None, + max_col: int | None = None, + *, + values_only: Literal[True], + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_rows( + self, + min_row: int | None = None, + max_row: int | None = None, + min_col: int | None = None, + max_col: int | None = None, + values_only: Literal[False] = False, + ) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @overload + def iter_rows( + self, min_row: int | None, max_row: int | None, min_col: int | None, max_col: int | None, values_only: bool + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_rows( + self, + min_row: int | None = None, + max_row: int | None = None, + min_col: int | None = None, + max_col: int | None = None, + *, + values_only: bool, + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + + @property + def rows(self) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @property + def values(self) -> Generator[tuple[_CellGetValue, ...]]: ... + + @overload + def iter_cols( + self, min_col: int | None, max_col: int | None, min_row: int | None, max_row: int | None, values_only: Literal[True] + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_cols( + self, + min_col: int | None = None, + max_col: int | None = None, + min_row: int | None = None, + max_row: int | None = None, + *, + values_only: Literal[True], + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_cols( + self, + min_col: int | None = None, + max_col: int | None = None, + min_row: int | None = None, + max_row: int | None = None, + values_only: Literal[False] = False, + ) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @overload + def iter_cols( + self, min_col: int | None, max_col: int | None, min_row: int | None, max_row: int | None, values_only: bool + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_cols( + self, + min_col: int | None = None, + max_col: int | None = None, + min_row: int | None = None, + max_row: int | None = None, + *, + values_only: bool, + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + + @property + def columns(self) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @property + def column_groups(self) -> list[str]: ... + def set_printer_settings( + self, paper_size: int | None, orientation: Literal["default", "portrait", "landscape"] | None + ) -> None: ... + def add_data_validation(self, data_validation: DataValidation) -> None: ... + def add_chart(self, chart: ChartBase, anchor: str | None = None) -> None: ... + def add_image(self, img: Image, anchor: str | None = None) -> None: ... + def add_table(self, table: Table) -> None: ... + @property + def tables(self) -> TableList: ... + def add_pivot(self, pivot) -> None: ... + + # Same overload as CellRange.__init__ + @overload + def merge_cells( + self, range_string: str, start_row: None = None, start_column: None = None, end_row: None = None, end_column: None = None + ) -> None: ... + @overload + def merge_cells( + self, + range_string: None = None, + *, + start_row: ConvertibleToInt, + start_column: ConvertibleToInt, + end_row: ConvertibleToInt, + end_column: ConvertibleToInt, + ) -> None: ... + @overload + def merge_cells( + self, + range_string: None, + start_row: ConvertibleToInt, + start_column: ConvertibleToInt, + end_row: ConvertibleToInt, + end_column: ConvertibleToInt, + ) -> None: ... + + # Will always raise: TypeError: 'set' object is not subscriptable + @property + @deprecated("Use ws.merged_cells.ranges") + def merged_cell_ranges(self) -> Never: ... + def unmerge_cells( + self, + range_string: str | None = None, + start_row: int | None = None, + start_column: int | None = None, + end_row: int | None = None, + end_column: int | None = None, + ) -> None: ... + def append( + self, + iterable: ( + list[_AnyCellValue] + | tuple[_CellOrMergedCell | _CellGetValue, ...] + | range + | GeneratorType[_CellOrMergedCell | _CellGetValue, object, object] + | dict[int | str, _AnyCellValue] + ), + ) -> None: ... + def insert_rows(self, idx: int, amount: int = 1) -> None: ... + def insert_cols(self, idx: int, amount: int = 1) -> None: ... + def delete_rows(self, idx: int, amount: int = 1) -> None: ... + def delete_cols(self, idx: int, amount: int = 1) -> None: ... + def move_range(self, cell_range: CellRange | str, rows: int = 0, cols: int = 0, translate: bool = False) -> None: ... + + @property + def print_title_rows(self) -> str | None: ... + @print_title_rows.setter + def print_title_rows(self, rows: str | None) -> None: ... + + @property + def print_title_cols(self) -> str | None: ... + @print_title_cols.setter + def print_title_cols(self, cols: str | None) -> None: ... + + @property + def print_titles(self) -> str: ... + + @property + def print_area(self) -> str: ... + @print_area.setter + def print_area(self, value: str | Iterable[str] | None) -> None: ... diff --git a/stubs/babel/babel/localtime/_unix.pyi b/stubs/openpyxl/openpyxl/writer/__init__.pyi similarity index 100% rename from stubs/babel/babel/localtime/_unix.pyi rename to stubs/openpyxl/openpyxl/writer/__init__.pyi diff --git a/stubs/openpyxl/openpyxl/writer/excel.pyi b/stubs/openpyxl/openpyxl/writer/excel.pyi new file mode 100644 index 000000000000..5baba43b2859 --- /dev/null +++ b/stubs/openpyxl/openpyxl/writer/excel.pyi @@ -0,0 +1,18 @@ +from typing import Literal +from zipfile import ZipFile + +from openpyxl import _ZipFileFileProtocol +from openpyxl.packaging.manifest import Manifest +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.worksheet import Worksheet + +class ExcelWriter: + workbook: Workbook + manifest: Manifest + vba_modified: set[str | None] + def __init__(self, workbook: Workbook, archive: ZipFile) -> None: ... + def write_data(self) -> None: ... + def write_worksheet(self, ws: Worksheet) -> None: ... + def save(self) -> None: ... + +def save_workbook(workbook: Workbook, filename: _ZipFileFileProtocol) -> Literal[True]: ... diff --git a/stubs/openpyxl/openpyxl/writer/theme.pyi b/stubs/openpyxl/openpyxl/writer/theme.pyi new file mode 100644 index 000000000000..079c7d6506cb --- /dev/null +++ b/stubs/openpyxl/openpyxl/writer/theme.pyi @@ -0,0 +1,3 @@ +theme_xml: str + +def write_theme(): ... diff --git a/stubs/openpyxl/openpyxl/xml/__init__.pyi b/stubs/openpyxl/openpyxl/xml/__init__.pyi new file mode 100644 index 000000000000..f3d56263e6ee --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/__init__.pyi @@ -0,0 +1,11 @@ +from typing import Final + +def lxml_available() -> bool: ... +def lxml_env_set() -> bool: ... + +LXML: Final[bool] + +def defusedxml_available() -> bool: ... +def defusedxml_env_set() -> bool: ... + +DEFUSEDXML: Final[bool] diff --git a/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi b/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi new file mode 100644 index 000000000000..a4a2d6103f3e --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi @@ -0,0 +1,146 @@ +# This file does not exist at runtime. It is a helper file to overload imported functions in openpyxl.xml.functions + +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable, Iterator, Mapping, Sequence +from typing import Any, Protocol, TypeAlias, TypeVar, overload, type_check_only +from xml.etree.ElementTree import Element, ElementTree, QName, XMLParser, _FileRead + +from openpyxl.chart.axis import ChartLines + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +# Useful protocols, see import comment in openpyxl/xml/functions.pyi + +# Comment from openpyxl.cell.rich_text.py +# Usually an Element() from either lxml or xml.etree (has a 'tag' element) +# lxml.etree._Element +# xml.etree.Element +@type_check_only +class _HasTag(Protocol): + tag: str + +@type_check_only +class _HasGet(Protocol[_T_co]): + def get(self, value: str, /) -> _T_co | None: ... + +@type_check_only +class _HasText(Protocol): + text: str + +@type_check_only +class _HasAttrib(Protocol): + attrib: Iterable[Any] # AnyOf[dict[str, str], Iterable[tuple[str, str]]] + +@type_check_only +class _HasTagAndGet(_HasTag, _HasGet[_T_co], Protocol[_T_co]): ... # noqa: Y046 + +@type_check_only +class _HasTagAndText(_HasTag, _HasText, Protocol): ... # noqa: Y046 + +@type_check_only +class _HasTagAndTextAndAttrib(_HasTag, _HasText, _HasAttrib, Protocol): ... # noqa: Y046 + +@type_check_only +class _SupportsFindChartLines(Protocol): + def find(self, path: str, /) -> ChartLines | None: ... + +@type_check_only +class _SupportsFindAndIterAndAttribAndText( # noqa: Y046 + _SupportsFindChartLines, Iterable[Incomplete], _HasAttrib, _HasText, Protocol +): ... + +@type_check_only +class _SupportsIterAndAttrib(Iterable[Incomplete], _HasAttrib, Protocol): ... # noqa: Y046 + +@type_check_only +class _SupportsIterAndAttribAndTextAndTag(Iterable[Incomplete], _HasAttrib, _HasText, _HasTag, Protocol): ... # noqa: Y046 + +@type_check_only +class _SupportsIterAndAttribAndTextAndGet( # noqa: Y046 + Iterable[Incomplete], _HasAttrib, _HasText, _HasGet[Incomplete], Protocol +): ... + +@type_check_only +class _ParentElement(Protocol[_T]): + def makeelement(self, tag: str, attrib: dict[str, str], /) -> _T: ... + def append(self, element: _T, /) -> object: ... + +# from lxml.etree import _Element +_lxml_Element: TypeAlias = Element # noqa: Y042 +# from lxml.etree import _ElementTree +_lxml_ElementTree: TypeAlias = ElementTree # noqa: Y042 +# from lxml.etree import QName +_lxml_QName: TypeAlias = QName # noqa: Y042 + +# from xml.etree import fromstring +@overload +def SubElement(parent: _ParentElement[_T], tag: str, attrib: dict[str, str] = ..., **extra: str) -> _T: ... + +# from lxml.etree import fromstring +@overload +def SubElement( + _parent: _lxml_Element, # This would be preferable as a protocol, but it's a C-Extension + _tag: str | bytes | _lxml_QName, + attrib: dict[str, str] | dict[bytes, bytes] | None = ..., + nsmap: Mapping[str, str] | None = ..., + **extra: str | bytes, +) -> _lxml_ElementTree: ... + +# from xml.etree.ElementTree import fromstring +@overload +def fromstring(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: ... + +# from lxml.etree import fromstring +# But made partial, removing parser arg +@overload +def fromstring(text: str | bytes, *, base_url: str | bytes = ...) -> _lxml_Element: ... + +# from defusedxml.ElementTree import fromstring +@overload +def fromstring(text: str, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True) -> int: ... + +# from xml.etree.ElementTree import tostring +# But made partial, removing encoding arg +@overload +def tostring( + element: Element, + method: str | None = "xml", + *, + xml_declaration: bool | None = None, + default_namespace: str | None = ..., + short_empty_elements: bool = ..., +) -> str: ... + +# from lxml.etree import Element +# But made partial, removing encoding arg +@overload +def tostring( + element_or_tree: _lxml_Element | _lxml_ElementTree, + method: str = ..., + xml_declaration: bool = ..., + pretty_print: bool = ..., + with_tail: bool = ..., + standalone: bool = ..., + doctype: str = ..., + exclusive: bool = ..., + with_comments: bool = ..., + inclusive_ns_prefixes=..., +) -> bytes: ... + +# from xml.etree.ElementTree import iterparse +@overload +def iterparse( + source: _FileRead, events: Sequence[str] | None = None, parser: XMLParser | None = None +) -> Iterator[tuple[str, Any]]: ... + +# from defusedxml.ElementTree import iterparse +@overload +def iterparse( + source: _FileRead, + events: Sequence[str] | None = None, + parser: XMLParser | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Iterator[tuple[str, Any]]: ... diff --git a/stubs/openpyxl/openpyxl/xml/constants.pyi b/stubs/openpyxl/openpyxl/xml/constants.pyi new file mode 100644 index 000000000000..1c5a15bb8fd7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/constants.pyi @@ -0,0 +1,91 @@ +from typing import Final + +MIN_ROW: Final = 0 +MIN_COLUMN: Final = 0 +MAX_COLUMN: Final = 16384 +MAX_ROW: Final = 1048576 + +PACKAGE_PROPS: Final = "docProps" +PACKAGE_XL: Final = "xl" +PACKAGE_RELS: Final = "_rels" +PACKAGE_THEME: Final = "xl/theme" +PACKAGE_WORKSHEETS: Final = "xl/worksheets" +PACKAGE_CHARTSHEETS: Final = "xl/chartsheets" +PACKAGE_DRAWINGS: Final = "xl/drawings" +PACKAGE_CHARTS: Final = "xl/charts" +PACKAGE_IMAGES: Final = "xl/media" +PACKAGE_WORKSHEET_RELS: Final = "xl/worksheets/_rels" +PACKAGE_CHARTSHEETS_RELS: Final = "xl/chartsheets/_rels" +PACKAGE_PIVOT_TABLE: Final = "xl/pivotTables" +PACKAGE_PIVOT_CACHE: Final = "xl/pivotCache" + +ARC_CONTENT_TYPES: Final = "[Content_Types].xml" +ARC_ROOT_RELS: Final = "_rels/.rels" +ARC_WORKBOOK_RELS: Final = "xl/_rels/workbook.xml.rels" +ARC_CORE: Final = "docProps/core.xml" +ARC_APP: Final = "docProps/app.xml" +ARC_CUSTOM: Final = "docProps/custom.xml" +ARC_WORKBOOK: Final = "xl/workbook.xml" +ARC_STYLE: Final = "xl/styles.xml" +ARC_THEME: Final = "xl/theme/theme1.xml" +ARC_SHARED_STRINGS: Final = "xl/sharedStrings.xml" +ARC_CUSTOM_UI: Final = "customUI/customUI.xml" + +DCORE_NS: Final = "http://purl.org/dc/elements/1.1/" +DCTERMS_NS: Final = "http://purl.org/dc/terms/" +DCTERMS_PREFIX: Final = "dcterms" + +DOC_NS: Final[str] +REL_NS: Final[str] +COMMENTS_NS: Final[str] +IMAGE_NS: Final[str] +VML_NS: Final[str] +VTYPES_NS: Final[str] +XPROPS_NS: Final[str] +CUSTPROPS_NS: Final[str] +EXTERNAL_LINK_NS: Final[str] + +CPROPS_FMTID: Final = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" + +PKG_NS: Final = "http://schemas.openxmlformats.org/package/2006/" +PKG_REL_NS: Final[str] +COREPROPS_NS: Final[str] +CONTYPES_NS: Final[str] + +XSI_NS: Final = "http://www.w3.org/2001/XMLSchema-instance" +XML_NS: Final = "http://www.w3.org/XML/1998/namespace" +SHEET_MAIN_NS: Final[str] + +CHART_NS: Final[str] +DRAWING_NS: Final[str] +SHEET_DRAWING_NS: Final[str] +CHART_DRAWING_NS: Final[str] + +CUSTOMUI_NS: Final[str] + +NAMESPACES: Final[dict[str, str]] + +WORKBOOK_MACRO: Final = "application/vnd.ms-excel.%s.macroEnabled.main+xml" +WORKBOOK: Final[str] +SPREADSHEET: Final[str] +SHARED_STRINGS: Final[str] +EXTERNAL_LINK: Final[str] +WORKSHEET_TYPE: Final[str] +COMMENTS_TYPE: Final[str] +STYLES_TYPE: Final[str] +CHARTSHEET_TYPE: Final[str] +DRAWING_TYPE: Final[str] +CHART_TYPE: Final[str] +CHARTSHAPE_TYPE: Final[str] +THEME_TYPE: Final[str] +CPROPS_TYPE: Final[str] +XLTM: Final[str] +XLSM: Final[str] +XLTX: Final[str] +XLSX: Final[str] + +EXT_TYPES: Final[dict[str, str]] + +CTRL: Final = "application/vnd.ms-excel.controlproperties+xml" +ACTIVEX: Final = "application/vnd.ms-office.activeX+xml" +VBA: Final = "application/vnd.ms-office.vbaProject" diff --git a/stubs/openpyxl/openpyxl/xml/functions.pyi b/stubs/openpyxl/openpyxl/xml/functions.pyi new file mode 100644 index 000000000000..fe6f96c20b23 --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/functions.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from re import Pattern +from typing import Final + +# Can actually be imported from a mix of xml, lxml, et_xmlfile and defusedxml +# But et_xmlfile is untyped. openpyxl does not directly depend on lxml/lxml-stubs. +# And forcing a dependency on defusedxml felt overkill as it just wraps xml +# So for typing purposes, let's pretend xml is the only dependency. +# Prefer using protocols over these for parameters. +from xml.etree.ElementTree import Element as Element, QName as QName + +from ._functions_overloads import ( + SubElement as SubElement, + _HasTag, + _HasText, + fromstring as fromstring, + iterparse as iterparse, + tostring as tostring, +) + +# from lxml.etree import xmlfile +# from et_xmlfile import xmlfile +xmlfile: Incomplete + +NS_REGEX: Final[Pattern[str]] + +def localname(node: _HasTag) -> str: ... +def whitespace(node: _HasText) -> None: ... diff --git a/stubs/opentracing/@tests/stubtest_allowlist.txt b/stubs/opentracing/@tests/stubtest_allowlist.txt index 7c96a34055f8..9f41ee7c2a11 100644 --- a/stubs/opentracing/@tests/stubtest_allowlist.txt +++ b/stubs/opentracing/@tests/stubtest_allowlist.txt @@ -1,3 +1,4 @@ +# They raise ModuleNotFoundError so they are not present at stubtest runtime: opentracing.harness.api_check opentracing.harness.scope_check opentracing.scope_managers.gevent diff --git a/stubs/opentracing/METADATA.toml b/stubs/opentracing/METADATA.toml index bcb78f17fb41..110d9ccd1660 100644 --- a/stubs/opentracing/METADATA.toml +++ b/stubs/opentracing/METADATA.toml @@ -1 +1,2 @@ version = "2.4.*" +upstream-repository = "https://github.com/opentracing/opentracing-python" diff --git a/stubs/opentracing/opentracing/harness/scope_check.pyi b/stubs/opentracing/opentracing/harness/scope_check.pyi index affe51501d6d..10b5ce11d39e 100644 --- a/stubs/opentracing/opentracing/harness/scope_check.pyi +++ b/stubs/opentracing/opentracing/harness/scope_check.pyi @@ -1,10 +1,10 @@ -from typing import Any, Callable +from collections.abc import Callable from ..scope_manager import ScopeManager class ScopeCompatibilityCheckMixin: def scope_manager(self) -> ScopeManager: ... - def run_test(self, test_fn: Callable[[Any], Any]) -> None: ... + def run_test(self, test_fn: Callable[[], object]) -> None: ... def test_missing_active_external(self) -> None: ... def test_missing_active(self) -> None: ... def test_activate(self) -> None: ... diff --git a/stubs/opentracing/opentracing/logs.pyi b/stubs/opentracing/opentracing/logs.pyi index 15cda689b09d..8aa6c11f3e89 100644 --- a/stubs/opentracing/opentracing/logs.pyi +++ b/stubs/opentracing/opentracing/logs.pyi @@ -1,5 +1,7 @@ -ERROR_KIND: str -ERROR_OBJECT: str -EVENT: str -MESSAGE: str -STACK: str +from typing import Final + +ERROR_KIND: Final = "error.kind" +ERROR_OBJECT: Final = "error.object" +EVENT: Final = "event" +MESSAGE: Final = "message" +STACK: Final = "stack" diff --git a/stubs/opentracing/opentracing/mocktracer/context.pyi b/stubs/opentracing/opentracing/mocktracer/context.pyi index ef8ed9214465..09022377e728 100644 --- a/stubs/opentracing/opentracing/mocktracer/context.pyi +++ b/stubs/opentracing/opentracing/mocktracer/context.pyi @@ -1,11 +1,13 @@ -from _typeshed import Self +from typing_extensions import Self import opentracing class SpanContext(opentracing.SpanContext): trace_id: int | None span_id: int | None - def __init__(self, trace_id: int | None = ..., span_id: int | None = ..., baggage: dict[str, str] | None = ...) -> None: ... + def __init__( + self, trace_id: int | None = None, span_id: int | None = None, baggage: dict[str, str] | None = None + ) -> None: ... @property def baggage(self) -> dict[str, str]: ... - def with_baggage_item(self: Self, key: str, value: str) -> Self: ... + def with_baggage_item(self, key: str, value: str) -> Self: ... diff --git a/stubs/opentracing/opentracing/mocktracer/span.pyi b/stubs/opentracing/opentracing/mocktracer/span.pyi index da419aa7a356..229af11b8e16 100644 --- a/stubs/opentracing/opentracing/mocktracer/span.pyi +++ b/stubs/opentracing/opentracing/mocktracer/span.pyi @@ -1,5 +1,5 @@ -from _typeshed import Self from typing import Any +from typing_extensions import Self from ..span import Span from ..tracer import Tracer @@ -17,22 +17,22 @@ class MockSpan(Span): def __init__( self, tracer: Tracer, - operation_name: str | None = ..., - context: SpanContext | None = ..., - parent_id: int | None = ..., - tags: dict[str, Any] | None = ..., - start_time: float | None = ..., + operation_name: str | None = None, + context: SpanContext | None = None, + parent_id: int | None = None, + tags: dict[str, Any] | None = None, + start_time: float | None = None, ) -> None: ... @property def tracer(self) -> MockTracer: ... @property def context(self) -> SpanContext: ... - def set_operation_name(self: Self, operation_name: str) -> Self: ... - def set_tag(self: Self, key: str, value: str | bool | int | float) -> Self: ... - def log_kv(self: Self, key_values: dict[str, Any], timestamp: float | None = ...) -> Self: ... - def set_baggage_item(self: Self, key: str, value: str) -> Self: ... + def set_operation_name(self, operation_name: str) -> Self: ... + def set_tag(self, key: str, value: str | bool | float) -> Self: ... + def log_kv(self, key_values: dict[str, Any], timestamp: float | None = None) -> Self: ... + def set_baggage_item(self, key: str, value: str) -> Self: ... class LogData: key_values: dict[str, Any] timestamp: float | None - def __init__(self, key_values: dict[str, Any], timestamp: float | None = ...) -> None: ... + def __init__(self, key_values: dict[str, Any], timestamp: float | None = None) -> None: ... diff --git a/stubs/opentracing/opentracing/mocktracer/tracer.pyi b/stubs/opentracing/opentracing/mocktracer/tracer.pyi index 9336c1a05b9f..46d12c48fb90 100644 --- a/stubs/opentracing/opentracing/mocktracer/tracer.pyi +++ b/stubs/opentracing/opentracing/mocktracer/tracer.pyi @@ -8,7 +8,7 @@ from .propagator import Propagator from .span import MockSpan class MockTracer(Tracer): - def __init__(self, scope_manager: ScopeManager | None = ...) -> None: ... + def __init__(self, scope_manager: ScopeManager | None = None) -> None: ... @property def active_span(self) -> MockSpan | None: ... def register_propagator(self, format: str, propagator: Propagator) -> None: ... @@ -16,11 +16,11 @@ class MockTracer(Tracer): def reset(self) -> None: ... def start_span( # type: ignore[override] self, - operation_name: str | None = ..., - child_of: Span | SpanContext | None = ..., - references: list[Reference] | None = ..., - tags: dict[Any, Any] | None = ..., - start_time: float | None = ..., - ignore_active_span: bool = ..., + operation_name: str | None = None, + child_of: Span | SpanContext | None = None, + references: list[Reference] | None = None, + tags: dict[Any, Any] | None = None, + start_time: float | None = None, + ignore_active_span: bool = False, ) -> MockSpan: ... def extract(self, format: str, carrier: dict[Any, Any]) -> SpanContext: ... diff --git a/stubs/opentracing/opentracing/propagation.pyi b/stubs/opentracing/opentracing/propagation.pyi index 81307c63f882..3c9607b8f405 100644 --- a/stubs/opentracing/opentracing/propagation.pyi +++ b/stubs/opentracing/opentracing/propagation.pyi @@ -1,8 +1,10 @@ +from typing import Final + class UnsupportedFormatException(Exception): ... class InvalidCarrierException(Exception): ... class SpanContextCorruptedException(Exception): ... class Format: - BINARY: str - TEXT_MAP: str - HTTP_HEADERS: str + BINARY: Final = "binary" + TEXT_MAP: Final = "text_map" + HTTP_HEADERS: Final = "http_headers" diff --git a/stubs/opentracing/opentracing/scope.pyi b/stubs/opentracing/opentracing/scope.pyi index ec2964d5b518..e312df143498 100644 --- a/stubs/opentracing/opentracing/scope.pyi +++ b/stubs/opentracing/opentracing/scope.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import Type +from typing_extensions import Self from .scope_manager import ScopeManager from .span import Span @@ -11,7 +11,7 @@ class Scope: @property def manager(self) -> ScopeManager: ... def close(self) -> None: ... - def __enter__(self) -> Scope: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... diff --git a/stubs/opentracing/opentracing/span.pyi b/stubs/opentracing/opentracing/span.pyi index 847f16bba9f5..dd9bff361ef7 100644 --- a/stubs/opentracing/opentracing/span.pyi +++ b/stubs/opentracing/opentracing/span.pyi @@ -1,6 +1,6 @@ -from _typeshed import Self from types import TracebackType -from typing import Any, Type +from typing import Any +from typing_extensions import Self from .tracer import Tracer @@ -15,15 +15,15 @@ class Span: def context(self) -> SpanContext: ... @property def tracer(self) -> Tracer: ... - def set_operation_name(self: Self, operation_name: str) -> Self: ... - def finish(self, finish_time: float | None = ...) -> None: ... - def set_tag(self: Self, key: str, value: str | bool | int | float) -> Self: ... - def log_kv(self: Self, key_values: dict[str, Any], timestamp: float | None = ...) -> Self: ... - def set_baggage_item(self: Self, key: str, value: str) -> Self: ... + def set_operation_name(self, operation_name: str) -> Self: ... + def finish(self, finish_time: float | None = None) -> None: ... + def set_tag(self, key: str, value: str | bool | float) -> Self: ... + def log_kv(self, key_values: dict[str, Any], timestamp: float | None = None) -> Self: ... + def set_baggage_item(self, key: str, value: str) -> Self: ... def get_baggage_item(self, key: str) -> str | None: ... - def __enter__(self: Self) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... - def log_event(self: Self, event: Any, payload: Any | None = ...) -> Self: ... - def log(self: Self, **kwargs: Any) -> Self: ... + def log_event(self, event: Any, payload=None) -> Self: ... + def log(self, **kwargs: Any) -> Self: ... diff --git a/stubs/opentracing/opentracing/tracer.pyi b/stubs/opentracing/opentracing/tracer.pyi index 6dcc47cd0211..275b9d7f682d 100644 --- a/stubs/opentracing/opentracing/tracer.pyi +++ b/stubs/opentracing/opentracing/tracer.pyi @@ -5,7 +5,7 @@ from .scope_manager import ScopeManager from .span import Span, SpanContext class Tracer: - def __init__(self, scope_manager: ScopeManager | None = ...) -> None: ... + def __init__(self, scope_manager: ScopeManager | None = None) -> None: ... @property def scope_manager(self) -> ScopeManager: ... @property @@ -13,21 +13,21 @@ class Tracer: def start_active_span( self, operation_name: str, - child_of: Span | SpanContext | None = ..., - references: list[Reference] | None = ..., - tags: dict[Any, Any] | None = ..., - start_time: float | None = ..., - ignore_active_span: bool = ..., - finish_on_close: bool = ..., + child_of: Span | SpanContext | None = None, + references: list[Reference] | None = None, + tags: dict[Any, Any] | None = None, + start_time: float | None = None, + ignore_active_span: bool = False, + finish_on_close: bool = True, ) -> Scope: ... def start_span( self, - operation_name: str | None = ..., - child_of: Span | SpanContext | None = ..., - references: list[Reference] | None = ..., - tags: dict[Any, Any] | None = ..., - start_time: float | None = ..., - ignore_active_span: bool = ..., + operation_name: str | None = None, + child_of: Span | SpanContext | None = None, + references: list[Reference] | None = None, + tags: dict[Any, Any] | None = None, + start_time: float | None = None, + ignore_active_span: bool = False, ) -> Span: ... def inject(self, span_context: SpanContext, format: str, carrier: dict[Any, Any]) -> None: ... def extract(self, format: str, carrier: dict[Any, Any]) -> SpanContext: ... @@ -40,8 +40,8 @@ class Reference(NamedTuple): type: str referenced_context: SpanContext | None -def child_of(referenced_context: SpanContext | None = ...) -> Reference: ... -def follows_from(referenced_context: SpanContext | None = ...) -> Reference: ... +def child_of(referenced_context: SpanContext | None = None) -> Reference: ... +def follows_from(referenced_context: SpanContext | None = None) -> Reference: ... def start_child_span( - parent_span: Span, operation_name: str, tags: dict[Any, Any] | None = ..., start_time: float | None = ... + parent_span: Span, operation_name: str, tags: dict[Any, Any] | None = None, start_time: float | None = None ) -> Span: ... diff --git a/stubs/orjson/METADATA.toml b/stubs/orjson/METADATA.toml deleted file mode 100644 index 49ae8203c6e9..000000000000 --- a/stubs/orjson/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "3.6.*" -obsolete_since = "3.6.1" diff --git a/stubs/orjson/orjson.pyi b/stubs/orjson/orjson.pyi deleted file mode 100644 index 0c1293d7dc1a..000000000000 --- a/stubs/orjson/orjson.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from collections.abc import Callable -from typing import Any - -__version__: str - -def dumps(__obj: Any, default: Callable[[Any], Any] | None = ..., option: int | None = ...) -> bytes: ... -def loads(__obj: bytes | str) -> Any: ... - -class JSONDecodeError(ValueError): ... -class JSONEncodeError(TypeError): ... - -OPT_APPEND_NEWLINE: int -OPT_INDENT_2: int -OPT_NAIVE_UTC: int -OPT_NON_STR_KEYS: int -OPT_OMIT_MICROSECONDS: int -OPT_PASSTHROUGH_DATACLASS: int -OPT_PASSTHROUGH_DATETIME: int -OPT_PASSTHROUGH_SUBCLASS: int -OPT_SERIALIZE_DATACLASS: int -OPT_SERIALIZE_NUMPY: int -OPT_SERIALIZE_UUID: int -OPT_SORT_KEYS: int -OPT_STRICT_INTEGER: int -OPT_UTC_Z: int diff --git a/stubs/paramiko/@tests/stubtest_allowlist.txt b/stubs/paramiko/@tests/stubtest_allowlist.txt deleted file mode 100644 index 3b8d828018e8..000000000000 --- a/stubs/paramiko/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,16 +0,0 @@ -paramiko.SFTPServer.__init__ -paramiko.Transport.open_x11_channel -paramiko.Transport.send_ignore -paramiko.Transport.start_server -paramiko._winapi -paramiko.py3compat.input -paramiko.py3compat.BytesIO.readlines -paramiko.py3compat.BytesIO.seek -paramiko.py3compat.StringIO.seek -paramiko.py3compat.StringIO.truncate -paramiko.sftp_server.SFTPServer.__init__ -paramiko.transport.Transport.open_x11_channel -paramiko.transport.Transport.send_ignore -paramiko.transport.Transport.start_server -paramiko.util.SupportsClose -paramiko.win_pageant diff --git a/stubs/paramiko/@tests/stubtest_allowlist_darwin.txt b/stubs/paramiko/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..c510f2c7e366 --- /dev/null +++ b/stubs/paramiko/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +paramiko._winapi +paramiko.win_openssh.* +paramiko.win_pageant diff --git a/stubs/paramiko/@tests/stubtest_allowlist_linux.txt b/stubs/paramiko/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..c510f2c7e366 --- /dev/null +++ b/stubs/paramiko/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +paramiko._winapi +paramiko.win_openssh.* +paramiko.win_pageant diff --git a/stubs/paramiko/@tests/stubtest_allowlist_win32.txt b/stubs/paramiko/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..51664f850f12 --- /dev/null +++ b/stubs/paramiko/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,2 @@ +# Type-checkers don't support architecture checks. So we have to Union +paramiko.win_pageant.ULONG_PTR diff --git a/stubs/paramiko/METADATA.toml b/stubs/paramiko/METADATA.toml index b526e1ea4802..3cde7708908c 100644 --- a/stubs/paramiko/METADATA.toml +++ b/stubs/paramiko/METADATA.toml @@ -1,3 +1,8 @@ -version = "2.8.*" -python2 = true -requires = ["types-cryptography"] +version = "5.0.*" +upstream-repository = "https://github.com/paramiko/paramiko" +# Requires a version of cryptography where cryptography.hazmat.primitives.ciphers.Cipher is generic +dependencies = ["cryptography>=37.0.0"] + +[tool.stubtest] +# linux and darwin are equivalent +ci-platforms = ["linux", "win32"] diff --git a/stubs/paramiko/paramiko/__init__.pyi b/stubs/paramiko/paramiko/__init__.pyi index f3e67d07f6bb..648141acf7eb 100644 --- a/stubs/paramiko/paramiko/__init__.pyi +++ b/stubs/paramiko/paramiko/__init__.pyi @@ -1,5 +1,8 @@ +from typing import Final + +from paramiko import util as util from paramiko.agent import Agent as Agent, AgentKey as AgentKey -from paramiko.channel import Channel as Channel +from paramiko.channel import Channel as Channel, ChannelFile as ChannelFile from paramiko.client import ( AutoAddPolicy as AutoAddPolicy, MissingHostKeyPolicy as MissingHostKeyPolicy, @@ -8,8 +11,7 @@ from paramiko.client import ( WarningPolicy as WarningPolicy, ) from paramiko.common import io_sleep as io_sleep -from paramiko.config import SSHConfig as SSHConfig -from paramiko.dsskey import DSSKey as DSSKey +from paramiko.config import SSHConfig as SSHConfig, SSHConfigDict as SSHConfigDict from paramiko.ecdsakey import ECDSAKey as ECDSAKey from paramiko.ed25519key import Ed25519Key as Ed25519Key from paramiko.file import BufferedFile as BufferedFile @@ -31,11 +33,15 @@ from paramiko.ssh_exception import ( BadAuthenticationType as BadAuthenticationType, BadHostKeyException as BadHostKeyException, ChannelException as ChannelException, + ConfigParseError as ConfigParseError, + CouldNotCanonicalize as CouldNotCanonicalize, PasswordRequiredException as PasswordRequiredException, ProxyCommandFailure as ProxyCommandFailure, SSHException as SSHException, ) from paramiko.transport import SecurityOptions as SecurityOptions, Transport as Transport -# Names in __all__ with no definition: -# util +__version__: Final[str] +__author__: Final[str] +__license__: Final[str] +key_classes: list[type[PKey]] diff --git a/stubs/paramiko/paramiko/_version.pyi b/stubs/paramiko/paramiko/_version.pyi deleted file mode 100644 index 1f2297095207..000000000000 --- a/stubs/paramiko/paramiko/_version.pyi +++ /dev/null @@ -1 +0,0 @@ -__version_info__: tuple[int, int, int] diff --git a/stubs/paramiko/paramiko/_winapi.pyi b/stubs/paramiko/paramiko/_winapi.pyi index 92517ba6cc45..0e3fc8a81869 100644 --- a/stubs/paramiko/paramiko/_winapi.pyi +++ b/stubs/paramiko/paramiko/_winapi.pyi @@ -1,44 +1,47 @@ import builtins import ctypes import sys +from _typeshed import Incomplete from types import TracebackType -from typing import Any, Type, TypeVar +from typing_extensions import Self if sys.platform == "win32": - - _T = TypeVar("_T") def format_system_message(errno: int) -> str | None: ... + class WindowsError(builtins.WindowsError): - def __init__(self, value: int | None = ...) -> None: ... + def __init__(self, value: int | None = None) -> None: ... @property def message(self) -> str: ... @property def code(self) -> int: ... + def handle_nonzero_success(result: int) -> None: ... GMEM_MOVEABLE: int - GlobalAlloc: Any - GlobalLock: Any - GlobalUnlock: Any - GlobalSize: Any - CreateFileMapping: Any - MapViewOfFile: Any - UnmapViewOfFile: Any - RtlMoveMemory: Any + GlobalAlloc: Incomplete + GlobalLock: Incomplete + GlobalUnlock: Incomplete + GlobalSize: Incomplete + CreateFileMapping: Incomplete + MapViewOfFile: Incomplete + UnmapViewOfFile: Incomplete + RtlMoveMemory: Incomplete + class MemoryMap: name: str length: int - security_attributes: Any = ... + security_attributes: Incomplete | None pos: int - filemap: Any = ... - view: Any = ... - def __init__(self, name: str, length: int, security_attributes: Any | None = ...) -> None: ... - def __enter__(self: _T) -> _T: ... + filemap: Incomplete + view: Incomplete + def __init__(self, name: str, length: int, security_attributes=None) -> None: ... + def __enter__(self) -> Self: ... def seek(self, pos: int) -> None: ... def write(self, msg: bytes) -> None: ... def read(self, n: int) -> bytes: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, tb: TracebackType | None ) -> None: ... + READ_CONTROL: int STANDARD_RIGHTS_REQUIRED: int STANDARD_RIGHTS_READ: int @@ -62,24 +65,41 @@ if sys.platform == "win32": POLICY_READ: int POLICY_WRITE: int POLICY_EXECUTE: int + class TokenAccess: TOKEN_QUERY: int + class TokenInformationClass: TokenUser: int + class TOKEN_USER(ctypes.Structure): num: int + SID: Incomplete + ATTRIBUTES: Incomplete + class SECURITY_DESCRIPTOR(ctypes.Structure): - SECURITY_DESCRIPTOR_CONTROL: Any + SECURITY_DESCRIPTOR_CONTROL: Incomplete REVISION: int + Revision: int + Sbz1: Incomplete + Control: Incomplete + Owner: Incomplete + Group: Incomplete + Sacl: Incomplete + Dacl: Incomplete + class SECURITY_ATTRIBUTES(ctypes.Structure): nLength: int - lpSecurityDescriptor: Any - def __init__(self, *args: Any, **kwargs: Any) -> None: ... + lpSecurityDescriptor: int + bInheritHandle: bool + def __init__(self, *args, **kwargs) -> None: ... + @property - def descriptor(self) -> Any: ... + def descriptor(self): ... @descriptor.setter - def descriptor(self, value: Any) -> None: ... - def GetTokenInformation(token: Any, information_class: Any) -> Any: ... - def OpenProcessToken(proc_handle: Any, access: Any) -> Any: ... + def descriptor(self, value) -> None: ... + + def GetTokenInformation(token, information_class): ... + def OpenProcessToken(proc_handle, access): ... def get_current_user() -> TOKEN_USER: ... - def get_security_attributes_for_user(user: TOKEN_USER | None = ...) -> SECURITY_ATTRIBUTES: ... + def get_security_attributes_for_user(user: TOKEN_USER | None = None) -> SECURITY_ATTRIBUTES: ... diff --git a/stubs/paramiko/paramiko/agent.pyi b/stubs/paramiko/paramiko/agent.pyi index bad43a1bc15f..16621e9fa5d2 100644 --- a/stubs/paramiko/paramiko/agent.pyi +++ b/stubs/paramiko/paramiko/agent.pyi @@ -1,24 +1,35 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from logging import _ExcInfoType from socket import _RetAddress, socket from threading import Thread -from typing import Protocol, Tuple +from typing import Final, Protocol, type_check_only from paramiko.channel import Channel -from paramiko.message import Message +from paramiko.message import Message, _LikeBytes from paramiko.pkey import PKey from paramiko.transport import Transport +@type_check_only class _AgentProxy(Protocol): def connect(self) -> None: ... def close(self) -> None: ... -cSSH2_AGENTC_REQUEST_IDENTITIES: bytes -SSH2_AGENT_IDENTITIES_ANSWER: int -cSSH2_AGENTC_SIGN_REQUEST: bytes -SSH2_AGENT_SIGN_RESPONSE: int +cSSH2_AGENTC_REQUEST_IDENTITIES: Final[bytes] +SSH2_AGENT_IDENTITIES_ANSWER: Final = 12 +cSSH2_AGENTC_SIGN_REQUEST: Final[bytes] +SSH2_AGENT_SIGN_RESPONSE: Final = 14 + +SSH_AGENT_RSA_SHA2_256: Final = 2 +SSH_AGENT_RSA_SHA2_512: Final = 4 +ALGORITHM_FLAG_MAP: Final[dict[str, int]] +key: str +value: int class AgentSSH: def __init__(self) -> None: ... - def get_keys(self) -> Tuple[AgentKey, ...]: ... + def get_keys(self) -> tuple[AgentKey, ...]: ... class AgentProxyThread(Thread): def __init__(self, agent: _AgentProxy) -> None: ... @@ -32,6 +43,15 @@ class AgentRemoteProxy(AgentProxyThread): def __init__(self, agent: AgentClientProxy, chan: Channel) -> None: ... def get_connection(self) -> tuple[socket, _RetAddress]: ... +if sys.platform == "win32": + from .win_openssh import OpenSSHAgentConnection + from .win_pageant import PageantConnection + + def get_agent_connection() -> PageantConnection | OpenSSHAgentConnection | None: ... + +else: + def get_agent_connection() -> socket | None: ... + class AgentClientProxy: thread: Thread def __init__(self, chanRemote: Channel) -> None: ... @@ -61,7 +81,18 @@ class AgentKey(PKey): blob: bytes public_blob: None name: str - def __init__(self, agent: AgentSSH, blob: bytes) -> None: ... + comment: str + def __init__(self, agent: AgentSSH, blob: ReadableBuffer, comment: str = "") -> None: ... + def log( + self, + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... def asbytes(self) -> bytes: ... def get_name(self) -> str: ... - def sign_ssh_data(self, data: bytes) -> Message: ... + def sign_ssh_data(self, data: _LikeBytes, algorithm: str | None = None) -> Message: ... diff --git a/stubs/paramiko/paramiko/auth_handler.pyi b/stubs/paramiko/paramiko/auth_handler.pyi index 6c412620ef19..2f6d67a94ad1 100644 --- a/stubs/paramiko/paramiko/auth_handler.pyi +++ b/stubs/paramiko/paramiko/auth_handler.pyi @@ -1,11 +1,12 @@ +from collections.abc import Callable from threading import Event -from typing import Callable, List, Tuple +from typing import TypeAlias +from paramiko.message import Message from paramiko.pkey import PKey -from paramiko.ssh_gss import _SSH_GSSAuth from paramiko.transport import Transport -_InteractiveCallback = Callable[[str, str, List[Tuple[str, bool]]], List[str]] +_InteractiveCallback: TypeAlias = Callable[[str, str, list[tuple[str, bool]]], list[str]] class AuthHandler: transport: Transport @@ -28,20 +29,15 @@ class AuthHandler: def auth_none(self, username: str, event: Event) -> None: ... def auth_publickey(self, username: str, key: PKey, event: Event) -> None: ... def auth_password(self, username: str, password: str, event: Event) -> None: ... - def auth_interactive(self, username: str, handler: _InteractiveCallback, event: Event, submethods: str = ...) -> None: ... - def auth_gssapi_with_mic(self, username: str, gss_host: str, gss_deleg_creds: bool, event: Event) -> None: ... - def auth_gssapi_keyex(self, username: str, event: Event) -> None: ... + def auth_interactive(self, username: str, handler: _InteractiveCallback, event: Event, submethods: str = "") -> None: ... def abort(self) -> None: ... def wait_for_response(self, event: Event) -> list[str]: ... -class GssapiWithMicAuthHandler: - method: str - sshgss: _SSH_GSSAuth - def __init__(self, delegate: AuthHandler, sshgss: _SSH_GSSAuth) -> None: ... - def abort(self) -> None: ... - @property - def transport(self) -> Transport: ... - @property - def auth_username(self) -> str: ... - @property - def gss_host(self) -> str: ... +class AuthOnlyHandler(AuthHandler): + def send_auth_request( + self, username: str, method: str, finish_message: Callable[[Message], None] | None = None + ) -> list[str]: ... + def auth_none(self, username: str) -> list[str]: ... # type: ignore[override] + def auth_publickey(self, username: str, key: PKey) -> list[str]: ... # type: ignore[override] + def auth_password(self, username: str, password: str) -> list[str]: ... # type: ignore[override] + def auth_interactive(self, username: str, handler: _InteractiveCallback, submethods: str = "") -> list[str]: ... # type: ignore[override] diff --git a/stubs/paramiko/paramiko/auth_strategy.pyi b/stubs/paramiko/paramiko/auth_strategy.pyi new file mode 100644 index 000000000000..707dd0f3d964 --- /dev/null +++ b/stubs/paramiko/paramiko/auth_strategy.pyi @@ -0,0 +1,57 @@ +import abc +from collections.abc import Callable, Iterator +from logging import Logger +from pathlib import Path +from typing import NamedTuple + +from paramiko.config import SSHConfig +from paramiko.pkey import PKey +from paramiko.ssh_exception import AuthenticationException +from paramiko.transport import Transport + +class AuthSource: + username: str + def __init__(self, username: str) -> None: ... + @abc.abstractmethod + def authenticate(self, transport: Transport) -> list[str]: ... + +class NoneAuth(AuthSource): + def authenticate(self, transport: Transport) -> list[str]: ... + +class Password(AuthSource): + password_getter: Callable[[], str] + def __init__(self, username: str, password_getter: Callable[[], str]) -> None: ... + def authenticate(self, transport: Transport) -> list[str]: ... + +class PrivateKey(AuthSource): + def authenticate(self, transport: Transport) -> list[str]: ... + +class InMemoryPrivateKey(PrivateKey): + pkey: PKey + def __init__(self, username: str, pkey: PKey) -> None: ... + +class OnDiskPrivateKey(PrivateKey): + source: str + path: Path + pkey: PKey + def __init__(self, username: str, source: str, path: Path, pkey: PKey) -> None: ... + +class SourceResult(NamedTuple): + source: AuthSource + result: list[str] | Exception + +class AuthResult(list[SourceResult]): + strategy: AuthStrategy + def __init__(self, strategy: AuthStrategy, *args: SourceResult, **kwargs: object) -> None: ... + +class AuthFailure(AuthenticationException): + result: AuthResult + def __init__(self, result: AuthResult) -> None: ... + +class AuthStrategy: + ssh_config: SSHConfig + log: Logger + def __init__(self, ssh_config: SSHConfig) -> None: ... + @abc.abstractmethod + def get_sources(self) -> Iterator[AuthSource]: ... + def authenticate(self, transport: Transport) -> list[SourceResult]: ... diff --git a/stubs/paramiko/paramiko/ber.pyi b/stubs/paramiko/paramiko/ber.pyi index 906dd2564338..f0a032a0d1bc 100644 --- a/stubs/paramiko/paramiko/ber.pyi +++ b/stubs/paramiko/paramiko/ber.pyi @@ -1,14 +1,15 @@ -from typing import Any, Iterable +from collections.abc import Iterable +from typing import Any class BERException(Exception): ... class BER: content: bytes idx: int - def __init__(self, content: bytes = ...) -> None: ... + def __init__(self, content: bytes = b"") -> None: ... def asbytes(self) -> bytes: ... - def decode(self) -> None | int | list[int]: ... - def decode_next(self) -> None | int | list[int]: ... + def decode(self) -> int | list[int] | None: ... + def decode_next(self) -> int | list[int] | None: ... @staticmethod def decode_sequence(data: bytes) -> list[int | list[int]]: ... def encode_tlv(self, ident: int, val: bytes) -> None: ... diff --git a/stubs/paramiko/paramiko/buffered_pipe.pyi b/stubs/paramiko/paramiko/buffered_pipe.pyi index 795c49cd9c01..558df9d30549 100644 --- a/stubs/paramiko/paramiko/buffered_pipe.pyi +++ b/stubs/paramiko/paramiko/buffered_pipe.pyi @@ -1,16 +1,14 @@ from threading import Event -from typing import Generic, Text, TypeVar +from typing import AnyStr, Generic -_T = TypeVar("_T", Text, bytes) +class PipeTimeout(OSError): ... -class PipeTimeout(IOError): ... - -class BufferedPipe(Generic[_T]): +class BufferedPipe(Generic[AnyStr]): def __init__(self) -> None: ... def set_event(self, event: Event) -> None: ... - def feed(self, data: _T) -> None: ... + def feed(self, data: AnyStr) -> None: ... def read_ready(self) -> bool: ... - def read(self, nbytes: int, timeout: float | None = ...) -> _T: ... - def empty(self) -> _T: ... + def read(self, nbytes: int, timeout: float | None = None) -> AnyStr: ... + def empty(self) -> AnyStr: ... def close(self) -> None: ... def __len__(self) -> int: ... diff --git a/stubs/paramiko/paramiko/channel.pyi b/stubs/paramiko/paramiko/channel.pyi index 1870c9e1fded..0d8482db0556 100644 --- a/stubs/paramiko/paramiko/channel.pyi +++ b/stubs/paramiko/paramiko/channel.pyi @@ -1,9 +1,12 @@ +from _typeshed import SupportsItems +from collections.abc import Callable from logging import Logger from threading import Condition, Event, Lock -from typing import Any, Callable, Mapping, TypeVar +from typing import Any, Literal, TypeVar from paramiko.buffered_pipe import BufferedPipe from paramiko.file import BufferedFile +from paramiko.message import _LikeBytes from paramiko.transport import Transport from paramiko.util import ClosingContextManager @@ -41,26 +44,26 @@ class Channel(ClosingContextManager): def __init__(self, chanid: int) -> None: ... def __del__(self) -> None: ... def get_pty( - self, term: str | bytes = ..., width: int = ..., height: int = ..., width_pixels: int = ..., height_pixels: int = ... + self, term: _LikeBytes = "vt100", width: int = 80, height: int = 24, width_pixels: int = 0, height_pixels: int = 0 ) -> None: ... def invoke_shell(self) -> None: ... - def exec_command(self, command: str | bytes) -> None: ... - def invoke_subsystem(self, subsystem: str | bytes) -> None: ... - def resize_pty(self, width: int = ..., height: int = ..., width_pixels: int = ..., height_pixels: int = ...) -> None: ... - def update_environment(self, environment: Mapping[str | bytes, str | bytes]) -> None: ... - def set_environment_variable(self, name: str | bytes, value: str | bytes) -> None: ... + def exec_command(self, command: _LikeBytes) -> None: ... + def invoke_subsystem(self, subsystem: _LikeBytes) -> None: ... + def resize_pty(self, width: int = 80, height: int = 24, width_pixels: int = 0, height_pixels: int = 0) -> None: ... + def update_environment(self, environment: SupportsItems[_LikeBytes, _LikeBytes]) -> None: ... + def set_environment_variable(self, name: _LikeBytes, value: _LikeBytes) -> None: ... def exit_status_ready(self) -> bool: ... def recv_exit_status(self) -> int: ... def send_exit_status(self, status: int) -> None: ... def request_x11( self, - screen_number: int = ..., - auth_protocol: str | bytes | None = ..., - auth_cookie: str | bytes | None = ..., - single_connection: bool = ..., - handler: Callable[[Channel, tuple[str, int]], None] | None = ..., + screen_number: int = 0, + auth_protocol: _LikeBytes | None = None, + auth_cookie: _LikeBytes | None = None, + single_connection: bool = False, + handler: Callable[[Channel, tuple[str, int]], object] | None = None, ) -> bytes: ... - def request_forward_agent(self, handler: Callable[[Channel], None]) -> bool: ... + def request_forward_agent(self, handler: Callable[[Channel], object]) -> bool: ... def get_transport(self) -> Transport: ... def set_name(self, name: str) -> None: ... def get_name(self) -> str: ... @@ -68,7 +71,7 @@ class Channel(ClosingContextManager): def set_combine_stderr(self, combine: bool) -> bool: ... def settimeout(self, timeout: float | None) -> None: ... def gettimeout(self) -> float | None: ... - def setblocking(self, blocking: bool) -> None: ... + def setblocking(self, blocking: bool | Literal[0, 1]) -> None: ... def getpeername(self) -> str: ... def close(self) -> None: ... def recv_ready(self) -> bool: ... @@ -76,10 +79,10 @@ class Channel(ClosingContextManager): def recv_stderr_ready(self) -> bool: ... def recv_stderr(self, nbytes: int) -> bytes: ... def send_ready(self) -> bool: ... - def send(self, s: bytes) -> int: ... - def send_stderr(self, s: bytes) -> int: ... - def sendall(self, s: bytes) -> None: ... - def sendall_stderr(self, s: bytes) -> None: ... + def send(self, s: bytes | bytearray) -> int: ... + def send_stderr(self, s: bytes | bytearray) -> int: ... + def sendall(self, s: bytes | bytearray) -> None: ... + def sendall_stderr(self, s: bytes | bytearray) -> None: ... def makefile(self, *params: Any) -> ChannelFile: ... def makefile_stderr(self, *params: Any) -> ChannelStderrFile: ... def makefile_stdin(self, *params: Any) -> ChannelStdinFile: ... @@ -90,7 +93,7 @@ class Channel(ClosingContextManager): class ChannelFile(BufferedFile[Any]): channel: Channel - def __init__(self, channel: Channel, mode: str = ..., bufsize: int = ...) -> None: ... + def __init__(self, channel: Channel, mode: str = "r", bufsize: int = -1) -> None: ... class ChannelStderrFile(ChannelFile): ... diff --git a/stubs/paramiko/paramiko/client.pyi b/stubs/paramiko/paramiko/client.pyi index f088dbe537cb..b020f823fa83 100644 --- a/stubs/paramiko/paramiko/client.pyi +++ b/stubs/paramiko/paramiko/client.pyi @@ -1,61 +1,74 @@ -from socket import socket -from typing import Iterable, Mapping, NoReturn, Type +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable, Mapping +from typing import Protocol, type_check_only +from typing_extensions import Never +from paramiko.auth_strategy import AuthStrategy from paramiko.channel import Channel, ChannelFile, ChannelStderrFile, ChannelStdinFile from paramiko.hostkeys import HostKeys from paramiko.pkey import PKey from paramiko.sftp_client import SFTPClient -from paramiko.transport import Transport +from paramiko.transport import Transport, _SocketLike from paramiko.util import ClosingContextManager +@type_check_only +class _TransportFactory(Protocol): + def __call__( + self, + sock: _SocketLike, + /, + *, + gss_kex: bool, + gss_deleg_creds: bool, + disabled_algorithms: Mapping[str, Iterable[str]] | None, + ) -> Transport: ... + class SSHClient(ClosingContextManager): def __init__(self) -> None: ... - def load_system_host_keys(self, filename: str | None = ...) -> None: ... - def load_host_keys(self, filename: str) -> None: ... - def save_host_keys(self, filename: str) -> None: ... + def load_system_host_keys(self, filename: FileDescriptorOrPath | None = None) -> None: ... + def load_host_keys(self, filename: FileDescriptorOrPath) -> None: ... + def save_host_keys(self, filename: FileDescriptorOrPath) -> None: ... def get_host_keys(self) -> HostKeys: ... def set_log_channel(self, name: str) -> None: ... - def set_missing_host_key_policy(self, policy: Type[MissingHostKeyPolicy] | MissingHostKeyPolicy) -> None: ... + def set_missing_host_key_policy(self, policy: type[MissingHostKeyPolicy] | MissingHostKeyPolicy) -> None: ... def connect( self, hostname: str, - port: int = ..., - username: str | None = ..., - password: str | None = ..., - pkey: PKey | None = ..., - key_filename: str | None = ..., - timeout: float | None = ..., - allow_agent: bool = ..., - look_for_keys: bool = ..., - compress: bool = ..., - sock: socket | None = ..., - gss_auth: bool = ..., - gss_kex: bool = ..., - gss_deleg_creds: bool = ..., - gss_host: str | None = ..., - banner_timeout: float | None = ..., - auth_timeout: float | None = ..., - gss_trust_dns: bool = ..., - passphrase: str | None = ..., - disabled_algorithms: dict[str, Iterable[str]] | None = ..., + port: int = 22, + username: str | None = None, + password: str | None = None, + pkey: PKey | None = None, + key_filename: str | None = None, + timeout: float | None = None, + allow_agent: bool = True, + look_for_keys: bool = True, + compress: bool = False, + sock: _SocketLike | None = None, + banner_timeout: float | None = None, + auth_timeout: float | None = None, + channel_timeout: float | None = None, + passphrase: str | None = None, + disabled_algorithms: Mapping[str, Iterable[str]] | None = None, + transport_factory: _TransportFactory | None = None, + auth_strategy: AuthStrategy | None = None, ) -> None: ... def close(self) -> None: ... def exec_command( self, command: str, - bufsize: int = ..., - timeout: float | None = ..., - get_pty: bool = ..., - environment: dict[str, str] | None = ..., + bufsize: int = -1, + timeout: float | None = None, + get_pty: bool = False, + environment: Mapping[str, str] | None = None, ) -> tuple[ChannelStdinFile, ChannelFile, ChannelStderrFile]: ... def invoke_shell( self, - term: str = ..., - width: int = ..., - height: int = ..., - width_pixels: int = ..., - height_pixels: int = ..., - environment: Mapping[str, str] | None = ..., + term: str = "vt100", + width: int = 80, + height: int = 24, + width_pixels: int = 0, + height_pixels: int = 0, + environment: Mapping[str, str] | None = None, ) -> Channel: ... def open_sftp(self) -> SFTPClient: ... def get_transport(self) -> Transport | None: ... @@ -67,7 +80,7 @@ class AutoAddPolicy(MissingHostKeyPolicy): def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... class RejectPolicy(MissingHostKeyPolicy): - def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> NoReturn: ... + def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> Never: ... class WarningPolicy(MissingHostKeyPolicy): def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... diff --git a/stubs/paramiko/paramiko/common.pyi b/stubs/paramiko/paramiko/common.pyi index 26c09d4f3e40..abe1a14e7fee 100644 --- a/stubs/paramiko/paramiko/common.pyi +++ b/stubs/paramiko/paramiko/common.pyi @@ -1,96 +1,102 @@ -import sys -from typing import Protocol, Text, Union - -MSG_DISCONNECT: int -MSG_IGNORE: int -MSG_UNIMPLEMENTED: int -MSG_DEBUG: int -MSG_SERVICE_REQUEST: int -MSG_SERVICE_ACCEPT: int -MSG_KEXINIT: int -MSG_NEWKEYS: int -MSG_USERAUTH_REQUEST: int -MSG_USERAUTH_FAILURE: int -MSG_USERAUTH_SUCCESS: int -MSG_USERAUTH_BANNER: int -MSG_USERAUTH_PK_OK: int -MSG_USERAUTH_INFO_REQUEST: int -MSG_USERAUTH_INFO_RESPONSE: int -MSG_USERAUTH_GSSAPI_RESPONSE: int -MSG_USERAUTH_GSSAPI_TOKEN: int -MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: int -MSG_USERAUTH_GSSAPI_ERROR: int -MSG_USERAUTH_GSSAPI_ERRTOK: int -MSG_USERAUTH_GSSAPI_MIC: int -HIGHEST_USERAUTH_MESSAGE_ID: int -MSG_GLOBAL_REQUEST: int -MSG_REQUEST_SUCCESS: int -MSG_REQUEST_FAILURE: int -MSG_CHANNEL_OPEN: int -MSG_CHANNEL_OPEN_SUCCESS: int -MSG_CHANNEL_OPEN_FAILURE: int -MSG_CHANNEL_WINDOW_ADJUST: int -MSG_CHANNEL_DATA: int -MSG_CHANNEL_EXTENDED_DATA: int -MSG_CHANNEL_EOF: int -MSG_CHANNEL_CLOSE: int -MSG_CHANNEL_REQUEST: int -MSG_CHANNEL_SUCCESS: int -MSG_CHANNEL_FAILURE: int - -cMSG_DISCONNECT: bytes -cMSG_IGNORE: bytes -cMSG_UNIMPLEMENTED: bytes -cMSG_DEBUG: bytes -cMSG_SERVICE_REQUEST: bytes -cMSG_SERVICE_ACCEPT: bytes -cMSG_KEXINIT: bytes -cMSG_NEWKEYS: bytes -cMSG_USERAUTH_REQUEST: bytes -cMSG_USERAUTH_FAILURE: bytes -cMSG_USERAUTH_SUCCESS: bytes -cMSG_USERAUTH_BANNER: bytes -cMSG_USERAUTH_PK_OK: bytes -cMSG_USERAUTH_INFO_REQUEST: bytes -cMSG_USERAUTH_INFO_RESPONSE: bytes -cMSG_USERAUTH_GSSAPI_RESPONSE: bytes -cMSG_USERAUTH_GSSAPI_TOKEN: bytes -cMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: bytes -cMSG_USERAUTH_GSSAPI_ERROR: bytes -cMSG_USERAUTH_GSSAPI_ERRTOK: bytes -cMSG_USERAUTH_GSSAPI_MIC: bytes -cMSG_GLOBAL_REQUEST: bytes -cMSG_REQUEST_SUCCESS: bytes -cMSG_REQUEST_FAILURE: bytes -cMSG_CHANNEL_OPEN: bytes -cMSG_CHANNEL_OPEN_SUCCESS: bytes -cMSG_CHANNEL_OPEN_FAILURE: bytes -cMSG_CHANNEL_WINDOW_ADJUST: bytes -cMSG_CHANNEL_DATA: bytes -cMSG_CHANNEL_EXTENDED_DATA: bytes -cMSG_CHANNEL_EOF: bytes -cMSG_CHANNEL_CLOSE: bytes -cMSG_CHANNEL_REQUEST: bytes -cMSG_CHANNEL_SUCCESS: bytes -cMSG_CHANNEL_FAILURE: bytes +import logging +from typing import Final + +def byte_ord(c: int | str) -> int: ... +def byte_chr(c: int) -> bytes: ... +def byte_mask(c: int, mask: int) -> bytes: ... + +MSG_DISCONNECT: Final = 1 +MSG_IGNORE: Final = 2 +MSG_UNIMPLEMENTED: Final = 3 +MSG_DEBUG: Final = 4 +MSG_SERVICE_REQUEST: Final = 5 +MSG_SERVICE_ACCEPT: Final = 6 +MSG_EXT_INFO: Final = 7 +MSG_KEXINIT: Final = 20 +MSG_NEWKEYS: Final = 21 +MSG_USERAUTH_REQUEST: Final = 50 +MSG_USERAUTH_FAILURE: Final = 51 +MSG_USERAUTH_SUCCESS: Final = 52 +MSG_USERAUTH_BANNER: Final = 53 +MSG_USERAUTH_PK_OK: Final = 60 +MSG_USERAUTH_INFO_REQUEST: Final = 60 +MSG_USERAUTH_INFO_RESPONSE: Final = 61 +MSG_USERAUTH_GSSAPI_RESPONSE: Final = 60 +MSG_USERAUTH_GSSAPI_TOKEN: Final = 61 +MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: Final = 63 +MSG_USERAUTH_GSSAPI_ERROR: Final = 64 +MSG_USERAUTH_GSSAPI_ERRTOK: Final = 65 +MSG_USERAUTH_GSSAPI_MIC: Final = 66 +HIGHEST_USERAUTH_MESSAGE_ID: Final = 79 +MSG_GLOBAL_REQUEST: Final = 80 +MSG_REQUEST_SUCCESS: Final = 81 +MSG_REQUEST_FAILURE: Final = 82 +MSG_CHANNEL_OPEN: Final = 90 +MSG_CHANNEL_OPEN_SUCCESS: Final = 91 +MSG_CHANNEL_OPEN_FAILURE: Final = 92 +MSG_CHANNEL_WINDOW_ADJUST: Final = 93 +MSG_CHANNEL_DATA: Final = 94 +MSG_CHANNEL_EXTENDED_DATA: Final = 95 +MSG_CHANNEL_EOF: Final = 96 +MSG_CHANNEL_CLOSE: Final = 97 +MSG_CHANNEL_REQUEST: Final = 98 +MSG_CHANNEL_SUCCESS: Final = 99 +MSG_CHANNEL_FAILURE: Final = 100 + +cMSG_DISCONNECT: Final[bytes] +cMSG_IGNORE: Final[bytes] +cMSG_UNIMPLEMENTED: Final[bytes] +cMSG_DEBUG: Final[bytes] +cMSG_SERVICE_REQUEST: Final[bytes] +cMSG_SERVICE_ACCEPT: Final[bytes] +cMSG_EXT_INFO: Final[bytes] +cMSG_KEXINIT: Final[bytes] +cMSG_NEWKEYS: Final[bytes] +cMSG_USERAUTH_REQUEST: Final[bytes] +cMSG_USERAUTH_FAILURE: Final[bytes] +cMSG_USERAUTH_SUCCESS: Final[bytes] +cMSG_USERAUTH_BANNER: Final[bytes] +cMSG_USERAUTH_PK_OK: Final[bytes] +cMSG_USERAUTH_INFO_REQUEST: Final[bytes] +cMSG_USERAUTH_INFO_RESPONSE: Final[bytes] +cMSG_USERAUTH_GSSAPI_RESPONSE: Final[bytes] +cMSG_USERAUTH_GSSAPI_TOKEN: Final[bytes] +cMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: Final[bytes] +cMSG_USERAUTH_GSSAPI_ERROR: Final[bytes] +cMSG_USERAUTH_GSSAPI_ERRTOK: Final[bytes] +cMSG_USERAUTH_GSSAPI_MIC: Final[bytes] +cMSG_GLOBAL_REQUEST: Final[bytes] +cMSG_REQUEST_SUCCESS: Final[bytes] +cMSG_REQUEST_FAILURE: Final[bytes] +cMSG_CHANNEL_OPEN: Final[bytes] +cMSG_CHANNEL_OPEN_SUCCESS: Final[bytes] +cMSG_CHANNEL_OPEN_FAILURE: Final[bytes] +cMSG_CHANNEL_WINDOW_ADJUST: Final[bytes] +cMSG_CHANNEL_DATA: Final[bytes] +cMSG_CHANNEL_EXTENDED_DATA: Final[bytes] +cMSG_CHANNEL_EOF: Final[bytes] +cMSG_CHANNEL_CLOSE: Final[bytes] +cMSG_CHANNEL_REQUEST: Final[bytes] +cMSG_CHANNEL_SUCCESS: Final[bytes] +cMSG_CHANNEL_FAILURE: Final[bytes] MSG_NAMES: dict[int, str] -AUTH_SUCCESSFUL: int -AUTH_PARTIALLY_SUCCESSFUL: int -AUTH_FAILED: int +AUTH_SUCCESSFUL: Final = 0 +AUTH_PARTIALLY_SUCCESSFUL: Final = 1 +AUTH_FAILED: Final = 2 -OPEN_SUCCEEDED: int -OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED: int -OPEN_FAILED_CONNECT_FAILED: int -OPEN_FAILED_UNKNOWN_CHANNEL_TYPE: int -OPEN_FAILED_RESOURCE_SHORTAGE: int +OPEN_SUCCEEDED: Final = 0 +OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED: Final = 1 +OPEN_FAILED_CONNECT_FAILED: Final = 2 +OPEN_FAILED_UNKNOWN_CHANNEL_TYPE: Final = 3 +OPEN_FAILED_RESOURCE_SHORTAGE: Final = 4 CONNECTION_FAILED_CODE: dict[int, str] -DISCONNECT_SERVICE_NOT_AVAILABLE: int -DISCONNECT_AUTH_CANCELLED_BY_USER: int -DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE: int +DISCONNECT_SERVICE_NOT_AVAILABLE: Final = 7 +DISCONNECT_AUTH_CANCELLED_BY_USER: Final = 13 +DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE: Final = 14 zero_byte: bytes one_byte: bytes @@ -99,20 +105,8 @@ max_byte: bytes cr_byte: bytes linefeed_byte: bytes crlf: bytes -if sys.version_info >= (3, 0): - cr_byte_value: int - linefeed_byte_value: int -else: - cr_byte_value: bytes - linefeed_byte_value: bytes - -class _SupportsAsBytes(Protocol): - def asbytes(self) -> bytes: ... - -_LikeBytes = Union[bytes, Text, _SupportsAsBytes] - -def asbytes(s: _LikeBytes) -> bytes: ... - +cr_byte_value: int +linefeed_byte_value: int xffffffff: int x80000000: int o666: int @@ -123,17 +117,17 @@ o777: int o700: int o70: int -DEBUG: int -INFO: int -WARNING: int -ERROR: int -CRITICAL: int +DEBUG = logging.DEBUG +INFO = logging.INFO +WARNING = logging.WARNING +ERROR = logging.ERROR +CRITICAL = logging.CRITICAL io_sleep: float -DEFAULT_WINDOW_SIZE: int -DEFAULT_MAX_PACKET_SIZE: int +DEFAULT_WINDOW_SIZE: Final[int] +DEFAULT_MAX_PACKET_SIZE: Final[int] -MIN_WINDOW_SIZE: int -MIN_PACKET_SIZE: int -MAX_WINDOW_SIZE: int +MIN_WINDOW_SIZE: Final[int] +MIN_PACKET_SIZE: Final[int] +MAX_WINDOW_SIZE: Final[int] diff --git a/stubs/paramiko/paramiko/compress.pyi b/stubs/paramiko/paramiko/compress.pyi index da039479745c..9dd81d17f4f5 100644 --- a/stubs/paramiko/paramiko/compress.pyi +++ b/stubs/paramiko/paramiko/compress.pyi @@ -1,11 +1,12 @@ +from _typeshed import ReadableBuffer from zlib import _Compress, _Decompress class ZlibCompressor: z: _Compress def __init__(self) -> None: ... - def __call__(self, data: bytes) -> bytes: ... + def __call__(self, data: ReadableBuffer) -> bytes: ... class ZlibDecompressor: z: _Decompress def __init__(self) -> None: ... - def __call__(self, data: bytes) -> bytes: ... + def __call__(self, data: ReadableBuffer) -> bytes: ... diff --git a/stubs/paramiko/paramiko/config.pyi b/stubs/paramiko/paramiko/config.pyi index 65bb71f450a8..19b14ed53947 100644 --- a/stubs/paramiko/paramiko/config.pyi +++ b/stubs/paramiko/paramiko/config.pyi @@ -1,7 +1,11 @@ -from typing import IO, Any, Dict, Iterable, Pattern +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable +from re import Pattern +from typing_extensions import Self from paramiko.ssh_exception import ConfigParseError as ConfigParseError, CouldNotCanonicalize as CouldNotCanonicalize +invoke_import_error: ImportError | None SSH_PORT: int class SSHConfig: @@ -9,12 +13,12 @@ class SSHConfig: TOKENS_BY_CONFIG_KEY: dict[str, list[str]] def __init__(self) -> None: ... @classmethod - def from_text(cls, text: str) -> SSHConfig: ... + def from_text(cls, text: str) -> Self: ... @classmethod - def from_path(cls, path: str) -> SSHConfig: ... + def from_path(cls, path: FileDescriptorOrPath) -> Self: ... @classmethod - def from_file(cls, flo: IO[str]) -> SSHConfig: ... - def parse(self, file_obj: IO[str]) -> None: ... + def from_file(cls, flo: Iterable[str]) -> Self: ... + def parse(self, file_obj: Iterable[str]) -> None: ... def lookup(self, hostname: str) -> SSHConfigDict: ... def canonicalize(self, hostname: str, options: SSHConfigDict, domains: Iterable[str]) -> str: ... def get_hostnames(self) -> set[str]: ... @@ -23,9 +27,8 @@ class LazyFqdn: fqdn: str | None config: SSHConfig host: str | None - def __init__(self, config: SSHConfigDict, host: str | None = ...) -> None: ... + def __init__(self, config: SSHConfigDict, host: str | None = None) -> None: ... -class SSHConfigDict(Dict[str, str]): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... +class SSHConfigDict(dict[str, str]): def as_bool(self, key: str) -> bool: ... def as_int(self, key: str) -> int: ... diff --git a/stubs/paramiko/paramiko/dsskey.pyi b/stubs/paramiko/paramiko/dsskey.pyi deleted file mode 100644 index 86a57d5e3916..000000000000 --- a/stubs/paramiko/paramiko/dsskey.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import IO, Any, Callable - -from paramiko.message import Message -from paramiko.pkey import PKey - -class DSSKey(PKey): - p: int | None - q: int | None - g: int | None - y: int | None - x: int | None - public_blob: None - size: int - def __init__( - self, - msg: Message | None = ..., - data: bytes | None = ..., - filename: str | None = ..., - password: str | None = ..., - vals: tuple[int, int, int, int] | None = ..., - file_obj: IO[str] | None = ..., - ) -> None: ... - def asbytes(self) -> bytes: ... - def __hash__(self) -> int: ... - def get_name(self) -> str: ... - def get_bits(self) -> int: ... - def can_sign(self) -> bool: ... - def sign_ssh_data(self, data: bytes) -> Message: ... - def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... - def write_private_key_file(self, filename: str, password: str | None = ...) -> None: ... - def write_private_key(self, file_obj: IO[str], password: str | None = ...) -> None: ... - @staticmethod - def generate(bits: int = ..., progress_func: Callable[..., Any] | None = ...) -> DSSKey: ... diff --git a/stubs/paramiko/paramiko/ecdsakey.pyi b/stubs/paramiko/paramiko/ecdsakey.pyi index 698362879747..804107fb285e 100644 --- a/stubs/paramiko/paramiko/ecdsakey.pyi +++ b/stubs/paramiko/paramiko/ecdsakey.pyi @@ -1,23 +1,25 @@ -from typing import IO, Any, Callable, Sequence, Type +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from collections.abc import Callable, Sequence +from typing import Any from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve, EllipticCurvePrivateKey, EllipticCurvePublicKey from cryptography.hazmat.primitives.hashes import HashAlgorithm from paramiko.message import Message -from paramiko.pkey import PKey +from paramiko.pkey import PKey, _HasReadlines class _ECDSACurve: nist_name: str key_length: int key_format_identifier: str - hash_object: Type[HashAlgorithm] - curve_class: Type[EllipticCurve] - def __init__(self, curve_class: Type[EllipticCurve], nist_name: str) -> None: ... + hash_object: type[HashAlgorithm] + curve_class: type[EllipticCurve] + def __init__(self, curve_class: type[EllipticCurve], nist_name: str) -> None: ... class _ECDSACurveSet: ecdsa_curves: Sequence[_ECDSACurve] def __init__(self, ecdsa_curves: Sequence[_ECDSACurve]) -> None: ... def get_key_format_identifier_list(self) -> list[str]: ... - def get_by_curve_class(self, curve_class: Type[Any]) -> _ECDSACurve | None: ... + def get_by_curve_class(self, curve_class: type[Any]) -> _ECDSACurve | None: ... def get_by_key_format_identifier(self, key_format_identifier: str) -> _ECDSACurve | None: ... def get_by_key_length(self, key_length: int) -> _ECDSACurve | None: ... @@ -28,26 +30,28 @@ class ECDSAKey(PKey): ecdsa_curve: _ECDSACurve | None def __init__( self, - msg: Message | None = ..., - data: bytes | None = ..., - filename: str | None = ..., - password: str | None = ..., - vals: tuple[EllipticCurvePrivateKey, EllipticCurvePublicKey] | None = ..., - file_obj: IO[str] | None = ..., - validate_point: bool = ..., + msg: Message | None = None, + data: ReadableBuffer | None = None, + filename: FileDescriptorOrPath | None = None, + password: str | None = None, + vals: tuple[EllipticCurvePrivateKey, EllipticCurvePublicKey] | None = None, + file_obj: _HasReadlines | None = None, + validate_point: bool = True, ) -> None: ... @classmethod + def identifiers(cls) -> list[str]: ... + @classmethod def supported_key_format_identifiers(cls: Any) -> list[str]: ... def asbytes(self) -> bytes: ... def __hash__(self) -> int: ... def get_name(self) -> str: ... def get_bits(self) -> int: ... def can_sign(self) -> bool: ... - def sign_ssh_data(self, data: bytes) -> Message: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... - def write_private_key_file(self, filename: str, password: str | None = ...) -> None: ... - def write_private_key(self, file_obj: IO[str], password: str | None = ...) -> None: ... + @property + def private_key(self) -> EllipticCurvePrivateKey | None: ... @classmethod def generate( - cls, curve: EllipticCurve = ..., progress_func: Callable[..., Any] | None = ..., bits: int | None = ... + cls, curve: EllipticCurve = ..., progress_func: Callable[..., object] | None = None, bits: int | None = None ) -> ECDSAKey: ... diff --git a/stubs/paramiko/paramiko/ed25519key.pyi b/stubs/paramiko/paramiko/ed25519key.pyi index 1f57ba269701..c57af34f794d 100644 --- a/stubs/paramiko/paramiko/ed25519key.pyi +++ b/stubs/paramiko/paramiko/ed25519key.pyi @@ -1,22 +1,30 @@ -from typing import IO +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from typing import Any, Final, TypeAlias from paramiko.message import Message -from paramiko.pkey import PKey +from paramiko.pkey import PKey, _HasReadlines + +_VerifyKey: TypeAlias = Any # actually nacl.signing.VerifyKey class Ed25519Key(PKey): + name: Final = "ssh-ed25519" + public_blob: None + def __init__( self, - msg: Message | None = ..., - data: bytes | None = ..., - filename: str | None = ..., - password: str | None = ..., - file_obj: IO[str] | None = ..., + msg: Message | None = None, + data: ReadableBuffer | None = None, + filename: FileDescriptorOrPath | None = None, + password: str | None = None, + file_obj: _HasReadlines | None = None, ) -> None: ... def asbytes(self) -> bytes: ... - def __hash__(self) -> int: ... def get_name(self) -> str: ... def get_bits(self) -> int: ... def can_sign(self) -> bool: ... - def sign_ssh_data(self, data: bytes) -> Message: ... + def can_verify(self) -> bool: ... + @property + def verifying_key(self) -> _VerifyKey | None: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... diff --git a/stubs/paramiko/paramiko/file.pyi b/stubs/paramiko/paramiko/file.pyi index dbf35fc39c93..c9216f24036f 100644 --- a/stubs/paramiko/paramiko/file.pyi +++ b/stubs/paramiko/paramiko/file.pyi @@ -1,4 +1,5 @@ -from typing import Any, AnyStr, Generic, Iterable, Tuple +from collections.abc import Iterable +from typing import Any, AnyStr, Generic from paramiko.util import ClosingContextManager @@ -15,7 +16,7 @@ class BufferedFile(ClosingContextManager, Generic[AnyStr]): FLAG_LINE_BUFFERED: int FLAG_UNIVERSAL_NEWLINE: int - newlines: None | AnyStr | Tuple[AnyStr, ...] + newlines: AnyStr | tuple[AnyStr, ...] | None def __init__(self) -> None: ... def __del__(self) -> None: ... def __iter__(self) -> BufferedFile[Any]: ... @@ -26,10 +27,10 @@ class BufferedFile(ClosingContextManager, Generic[AnyStr]): def writable(self) -> bool: ... def seekable(self) -> bool: ... def readinto(self, buff: bytearray) -> int: ... - def read(self, size: int | None = ...) -> bytes: ... - def readline(self, size: int | None = ...) -> AnyStr: ... - def readlines(self, sizehint: int | None = ...) -> list[AnyStr]: ... - def seek(self, offset: int, whence: int = ...) -> None: ... + def read(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> AnyStr: ... + def readlines(self, sizehint: int | None = None) -> list[AnyStr]: ... + def seek(self, offset: int, whence: int = 0) -> None: ... def tell(self) -> int: ... def write(self, data: AnyStr) -> None: ... def writelines(self, sequence: Iterable[AnyStr]) -> None: ... diff --git a/stubs/paramiko/paramiko/hostkeys.pyi b/stubs/paramiko/paramiko/hostkeys.pyi index 32f05bfc0ab6..c9d93b374af9 100644 --- a/stubs/paramiko/paramiko/hostkeys.pyi +++ b/stubs/paramiko/paramiko/hostkeys.pyi @@ -1,9 +1,13 @@ -from typing import Iterator, Mapping, MutableMapping +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterator, Mapping, MutableMapping +from typing import type_check_only +from typing_extensions import Self from paramiko.pkey import PKey +# Internal to HostKeys.lookup(). Calls itself "SubDict". +@type_check_only class _SubDict(MutableMapping[str, PKey]): - # Internal to HostKeys.lookup() def __init__(self, hostname: str, entries: list[HostKeyEntry], hostkeys: HostKeys) -> None: ... def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... @@ -13,10 +17,10 @@ class _SubDict(MutableMapping[str, PKey]): def keys(self) -> list[str]: ... # type: ignore[override] class HostKeys(MutableMapping[str, _SubDict]): - def __init__(self, filename: str | None = ...) -> None: ... + def __init__(self, filename: FileDescriptorOrPath | None = None) -> None: ... def add(self, hostname: str, keytype: str, key: PKey) -> None: ... - def load(self, filename: str) -> None: ... - def save(self, filename: str) -> None: ... + def load(self, filename: FileDescriptorOrPath) -> None: ... + def save(self, filename: FileDescriptorOrPath) -> None: ... def lookup(self, hostname: str) -> _SubDict | None: ... def check(self, hostname: str, key: PKey) -> bool: ... def clear(self) -> None: ... @@ -28,7 +32,7 @@ class HostKeys(MutableMapping[str, _SubDict]): def keys(self) -> list[str]: ... # type: ignore[override] def values(self) -> list[_SubDict]: ... # type: ignore[override] @staticmethod - def hash_host(hostname: str, salt: str | None = ...) -> str: ... + def hash_host(hostname: str, salt: str | None = None) -> str: ... class InvalidHostKey(Exception): line: str @@ -39,7 +43,7 @@ class HostKeyEntry: valid: bool hostnames: list[str] key: PKey - def __init__(self, hostnames: list[str] | None = ..., key: PKey | None = ...) -> None: ... + def __init__(self, hostnames: list[str] | None = None, key: PKey | None = None) -> None: ... @classmethod - def from_line(cls, line: str, lineno: int | None = ...) -> HostKeyEntry | None: ... + def from_line(cls, line: str, lineno: int | None = None) -> Self | None: ... def to_line(self) -> str | None: ... diff --git a/stubs/paramiko/paramiko/kex_curve25519.pyi b/stubs/paramiko/paramiko/kex_curve25519.pyi index c2811dd70c96..be33b1a57ac2 100644 --- a/stubs/paramiko/paramiko/kex_curve25519.pyi +++ b/stubs/paramiko/paramiko/kex_curve25519.pyi @@ -1,16 +1,11 @@ -import sys -from _typeshed import ReadableBuffer as ReadableBuffer -from typing import Callable +from _typeshed import ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey from paramiko.message import Message from paramiko.transport import Transport -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash - c_MSG_KEXECDH_INIT: bytes c_MSG_KEXECDH_REPLY: bytes diff --git a/stubs/paramiko/paramiko/kex_ecdh_nist.pyi b/stubs/paramiko/paramiko/kex_ecdh_nist.pyi index aec8d912aff0..3178b181e5e4 100644 --- a/stubs/paramiko/paramiko/kex_ecdh_nist.pyi +++ b/stubs/paramiko/paramiko/kex_ecdh_nist.pyi @@ -1,16 +1,11 @@ -import sys from _typeshed import ReadableBuffer -from typing import Callable +from collections.abc import Callable +from hashlib import _Hash from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve, EllipticCurvePrivateKey, EllipticCurvePublicKey from paramiko.message import Message from paramiko.transport import Transport -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash - c_MSG_KEXECDH_INIT: bytes c_MSG_KEXECDH_REPLY: bytes diff --git a/stubs/paramiko/paramiko/kex_gex.pyi b/stubs/paramiko/paramiko/kex_gex.pyi index a47717ec9c4f..19795704f7a6 100644 --- a/stubs/paramiko/paramiko/kex_gex.pyi +++ b/stubs/paramiko/paramiko/kex_gex.pyi @@ -1,27 +1,24 @@ -import sys +from _hashlib import HASH from _typeshed import ReadableBuffer -from typing import Callable +from collections.abc import Callable +from typing import ClassVar, Final from paramiko.message import Message from paramiko.transport import Transport -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash +c_MSG_KEXDH_GEX_REQUEST_OLD: Final[bytes] +c_MSG_KEXDH_GEX_GROUP: Final[bytes] +c_MSG_KEXDH_GEX_INIT: Final[bytes] +c_MSG_KEXDH_GEX_REPLY: Final[bytes] +c_MSG_KEXDH_GEX_REQUEST: Final[bytes] -c_MSG_KEXDH_GEX_REQUEST_OLD: bytes -c_MSG_KEXDH_GEX_GROUP: bytes -c_MSG_KEXDH_GEX_INIT: bytes -c_MSG_KEXDH_GEX_REPLY: bytes -c_MSG_KEXDH_GEX_REQUEST: bytes +class KexGexSHA256: + name: ClassVar[str] + min_bits: ClassVar[int] + max_bits: ClassVar[int] + preferred_bits: ClassVar[int] + hash_algo: ClassVar[Callable[[ReadableBuffer], HASH]] -class KexGex: - name: str - min_bits: int - max_bits: int - preferred_bits: int - hash_algo: Callable[[ReadableBuffer], _Hash] = ... transport: Transport p: int | None q: int | None @@ -30,10 +27,7 @@ class KexGex: e: int | None f: int | None old_style: bool + def __init__(self, transport: Transport) -> None: ... - def start_kex(self, _test_old_style: bool = ...) -> None: ... + def start_kex(self, _test_old_style: bool = False) -> None: ... def parse_next(self, ptype: int, m: Message) -> None: ... - -class KexGexSHA256(KexGex): - name: str - hash_algo: Callable[[ReadableBuffer], _Hash] = ... diff --git a/stubs/paramiko/paramiko/kex_group1.pyi b/stubs/paramiko/paramiko/kex_group1.pyi deleted file mode 100644 index 8b6ae8842f34..000000000000 --- a/stubs/paramiko/paramiko/kex_group1.pyi +++ /dev/null @@ -1,29 +0,0 @@ -import sys -from _typeshed import ReadableBuffer -from typing import Callable - -from paramiko.message import Message -from paramiko.transport import Transport - -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash - -c_MSG_KEXDH_INIT: bytes -c_MSG_KEXDH_REPLY: bytes -b7fffffffffffffff: bytes -b0000000000000000: bytes - -class KexGroup1: - P: int - G: int - name: str - hash_algo: Callable[[ReadableBuffer], _Hash] - transport: Transport - x: int - e: int - f: int - def __init__(self, transport: Transport) -> None: ... - def start_kex(self) -> None: ... - def parse_next(self, ptype: int, m: Message) -> None: ... diff --git a/stubs/paramiko/paramiko/kex_group14.pyi b/stubs/paramiko/paramiko/kex_group14.pyi index 276f9e5cd7ed..ce550589cc9b 100644 --- a/stubs/paramiko/paramiko/kex_group14.pyi +++ b/stubs/paramiko/paramiko/kex_group14.pyi @@ -1,20 +1,28 @@ -import sys +from _hashlib import HASH from _typeshed import ReadableBuffer -from typing import Callable +from collections.abc import Callable +from typing import ClassVar, Final -from paramiko.kex_group1 import KexGroup1 as KexGroup1 +from paramiko.message import Message +from paramiko.transport import Transport -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash +c_MSG_KEXDH_INIT: Final[bytes] +c_MSG_KEXDH_REPLY: Final[bytes] +b7fffffffffffffff: Final[bytes] +b0000000000000000: Final[bytes] -class KexGroup14(KexGroup1): - P: int - G: int - name: str - hash_algo: Callable[[ReadableBuffer], _Hash] +class KexGroup14SHA256: + P: ClassVar[int] + G: ClassVar[int] -class KexGroup14SHA256(KexGroup14): - name: str - hash_algo: Callable[[ReadableBuffer], _Hash] + name: ClassVar[str] + hash_algo: ClassVar[Callable[[ReadableBuffer], HASH]] + + transport: Transport + x: int + e: int + f: int + + def __init__(self, transport: Transport) -> None: ... + def start_kex(self) -> None: ... + def parse_next(self, ptype: int, m: Message) -> None: ... diff --git a/stubs/paramiko/paramiko/kex_group16.pyi b/stubs/paramiko/paramiko/kex_group16.pyi index d85490cd486c..d8dd7905f195 100644 --- a/stubs/paramiko/paramiko/kex_group16.pyi +++ b/stubs/paramiko/paramiko/kex_group16.pyi @@ -1,16 +1,3 @@ -import sys -from _typeshed import ReadableBuffer -from typing import Callable +from paramiko.kex_group14 import KexGroup14SHA256 -from paramiko.kex_group1 import KexGroup1 as KexGroup1 - -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash - -class KexGroup16SHA512(KexGroup1): - name: str - P: int - G: int - hash_algo: Callable[[ReadableBuffer], _Hash] +class KexGroup16SHA512(KexGroup14SHA256): ... diff --git a/stubs/paramiko/paramiko/kex_gss.pyi b/stubs/paramiko/paramiko/kex_gss.pyi deleted file mode 100644 index 1fd04c6e6391..000000000000 --- a/stubs/paramiko/paramiko/kex_gss.pyi +++ /dev/null @@ -1,64 +0,0 @@ -from paramiko.message import Message -from paramiko.ssh_gss import _SSH_GSSAuth -from paramiko.transport import Transport - -MSG_KEXGSS_INIT: int -MSG_KEXGSS_CONTINUE: int -MSG_KEXGSS_COMPLETE: int -MSG_KEXGSS_HOSTKEY: int -MSG_KEXGSS_ERROR: int -MSG_KEXGSS_GROUPREQ: int -MSG_KEXGSS_GROUP: int - -c_MSG_KEXGSS_INIT: bytes -c_MSG_KEXGSS_CONTINUE: bytes -c_MSG_KEXGSS_COMPLETE: bytes -c_MSG_KEXGSS_HOSTKEY: bytes -c_MSG_KEXGSS_ERROR: bytes -c_MSG_KEXGSS_GROUPREQ: bytes -c_MSG_KEXGSS_GROUP: bytes - -class KexGSSGroup1: - P: int - G: int - b7fffffffffffffff: bytes - b0000000000000000: bytes - NAME: str - transport: Transport - kexgss: _SSH_GSSAuth - gss_host: str | None - x: int - e: int - f: int - def __init__(self, transport: Transport) -> None: ... - def start_kex(self) -> None: ... - def parse_next(self, ptype: int, m: Message) -> None: ... - -class KexGSSGroup14(KexGSSGroup1): - P: int - G: int - NAME: str - -class KexGSSGex: - NAME: str - min_bits: int - max_bits: int - preferred_bits: int - transport: Transport - kexgss: _SSH_GSSAuth - gss_host: str | None - p: int | None - q: int | None - g: int | None - x: int | None - e: int | None - f: int | None - old_style: bool - def __init__(self, transport: Transport) -> None: ... - def start_kex(self) -> None: ... - def parse_next(self, ptype: int, m: Message) -> None: ... - -class NullHostKey: - key: str - def __init__(self) -> None: ... - def get_name(self) -> str: ... diff --git a/stubs/paramiko/paramiko/message.pyi b/stubs/paramiko/paramiko/message.pyi index e4fd1dfc27da..88bed87b56a7 100644 --- a/stubs/paramiko/paramiko/message.pyi +++ b/stubs/paramiko/paramiko/message.pyi @@ -1,20 +1,20 @@ -import sys -from typing import Any, Iterable, Text +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from io import BytesIO +from typing import Any, Protocol, TypeAlias, type_check_only -from .common import _LikeBytes - -if sys.version_info >= (3, 0): - from io import BytesIO -else: - from StringIO import StringIO +@type_check_only +class _SupportsAsBytes(Protocol): + def asbytes(self) -> bytes: ... - BytesIO = StringIO[bytes] +_LikeBytes: TypeAlias = bytes | str | _SupportsAsBytes | ReadableBuffer class Message: big_int: int packet: BytesIO seqno: int # only when packet.Packetizer.read_message() is used - def __init__(self, content: bytes | None = ...) -> None: ... + def __init__(self, content: ReadableBuffer | None = None) -> None: ... + def __bytes__(self) -> bytes: ... def asbytes(self) -> bytes: ... def rewind(self) -> None: ... def get_remainder(self) -> bytes: ... @@ -27,11 +27,11 @@ class Message: def get_int64(self) -> int: ... def get_mpint(self) -> int: ... def get_string(self) -> bytes: ... - def get_text(self) -> Text: ... + def get_text(self) -> str: ... def get_binary(self) -> bytes: ... def get_list(self) -> list[str]: ... - def add_bytes(self, b: bytes) -> Message: ... - def add_byte(self, b: bytes) -> Message: ... + def add_bytes(self, b: ReadableBuffer) -> Message: ... + def add_byte(self, b: ReadableBuffer) -> Message: ... def add_boolean(self, b: bool) -> Message: ... def add_int(self, n: int) -> Message: ... def add_adaptive_int(self, n: int) -> Message: ... diff --git a/stubs/paramiko/paramiko/packet.pyi b/stubs/paramiko/paramiko/packet.pyi index 5d2c251db650..1dce422c6b2b 100644 --- a/stubs/paramiko/paramiko/packet.pyi +++ b/stubs/paramiko/paramiko/packet.pyi @@ -1,18 +1,15 @@ -import sys +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash from logging import Logger from socket import socket -from typing import Any, Callable +from typing import Any from cryptography.hazmat.primitives.ciphers import Cipher from paramiko.compress import ZlibCompressor, ZlibDecompressor from paramiko.message import Message -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash - -def compute_hmac(key: bytes, message: bytes, digest_class: _Hash) -> bytes: ... +def compute_hmac(key: bytes | bytearray, message: ReadableBuffer, digest_class: _Hash) -> bytes: ... class NeedRekeyException(Exception): ... @@ -26,19 +23,31 @@ class Packetizer: def __init__(self, socket: socket) -> None: ... @property def closed(self) -> bool: ... + def reset_seqno_out(self) -> None: ... + def reset_seqno_in(self) -> None: ... def set_log(self, log: Logger) -> None: ... def set_outbound_cipher( self, - block_engine: Cipher, + block_engine: Cipher[Incomplete], block_size: int, mac_engine: _Hash, mac_size: int, - mac_key: bytes, - sdctr: bool = ..., - etm: bool = ..., + mac_key: bytes | bytearray, + sdctr: bool = False, + etm: bool = False, + aead: bool = False, + iv_out: bytes | None = None, ) -> None: ... def set_inbound_cipher( - self, block_engine: Cipher, block_size: int, mac_engine: _Hash, mac_size: int, mac_key: bytes, etm: bool = ... + self, + block_engine: Cipher[Incomplete], + block_size: int, + mac_engine: _Hash, + mac_size: int, + mac_key: bytes | bytearray, + etm: bool = False, + aead: bool = False, + iv_in: bytes | None = None, ) -> None: ... def set_outbound_compressor(self, compressor: ZlibCompressor) -> None: ... def set_inbound_compressor(self, compressor: ZlibDecompressor) -> None: ... @@ -48,13 +57,13 @@ class Packetizer: def get_mac_size_in(self) -> int: ... def get_mac_size_out(self) -> int: ... def need_rekey(self) -> bool: ... - def set_keepalive(self, interval: int, callback: Callable[[], None]) -> None: ... + def set_keepalive(self, interval: float, callback: Callable[[], object]) -> None: ... def read_timer(self) -> None: ... def start_handshake(self, timeout: float) -> None: ... def handshake_timed_out(self) -> bool: ... def complete_handshake(self) -> None: ... - def read_all(self, n: int, check_rekey: bool = ...) -> bytes: ... - def write_all(self, out: bytes) -> None: ... + def read_all(self, n: int, check_rekey: bool = False) -> bytes: ... + def write_all(self, out: ReadableBuffer) -> None: ... def readline(self, timeout: float) -> str: ... def send_message(self, data: Message) -> None: ... def read_message(self) -> tuple[int, Message]: ... diff --git a/stubs/paramiko/paramiko/pipe.pyi b/stubs/paramiko/paramiko/pipe.pyi index eb7274903f88..4cc8e54b09b4 100644 --- a/stubs/paramiko/paramiko/pipe.pyi +++ b/stubs/paramiko/paramiko/pipe.pyi @@ -1,9 +1,11 @@ -from typing import Protocol +from typing import Protocol, type_check_only +@type_check_only class _BasePipe(Protocol): def clear(self) -> None: ... def set(self) -> None: ... +@type_check_only class _Pipe(_BasePipe, Protocol): def close(self) -> None: ... def fileno(self) -> int: ... @@ -11,7 +13,7 @@ class _Pipe(_BasePipe, Protocol): def make_pipe() -> _Pipe: ... -class PosixPipe(object): +class PosixPipe: def __init__(self) -> None: ... def close(self) -> None: ... def fileno(self) -> int: ... @@ -19,7 +21,7 @@ class PosixPipe(object): def set(self) -> None: ... def set_forever(self) -> None: ... -class WindowsPipe(object): +class WindowsPipe: def __init__(self) -> None: ... def close(self) -> None: ... def fileno(self) -> int: ... diff --git a/stubs/paramiko/paramiko/pkey.pyi b/stubs/paramiko/paramiko/pkey.pyi index 4990501b7384..752039f792cd 100644 --- a/stubs/paramiko/paramiko/pkey.pyi +++ b/stubs/paramiko/paramiko/pkey.pyi @@ -1,46 +1,87 @@ -from typing import IO, Pattern, Type, TypeVar +from _typeshed import StrOrBytesPath, SupportsWrite +from pathlib import Path +from re import Pattern +from typing import Final, NamedTuple, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat from paramiko.message import Message -OPENSSH_AUTH_MAGIC: bytes = ... +@type_check_only +class _HasReadlines(Protocol): + def readlines(self) -> list[str]: ... -def _unpad_openssh(data: bytes) -> bytes: ... +OPENSSH_AUTH_MAGIC: bytes -_PK = TypeVar("_PK", bound=PKey) +_BytesT = TypeVar("_BytesT", bound=bytes | bytearray) + +def _unpad_openssh(data: _BytesT) -> _BytesT: ... + +class UnknownKeyType(Exception): + key_type: str | type | None + key_bytes: bytes | None + def __init__(self, key_type: str | type | None = None, key_bytes: bytes | None = None) -> None: ... + +class FileFormat(NamedTuple): + format: PrivateFormat + encoding: Encoding + +PrivateKey: TypeAlias = RSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey + +PEM: Final[FileFormat] +OPENSSH: Final[FileFormat] class PKey: public_blob: PublicBlob | None BEGIN_TAG: Pattern[str] END_TAG: Pattern[str] - def __init__(self, msg: Message | None = ..., data: str | None = ...) -> None: ... + @staticmethod + def from_path(path: Path | str, password: str | None = None) -> PKey: ... + @staticmethod + def from_type_string(key_type: str, key_bytes: bytes, password: str | None = None) -> PKey: ... + @classmethod + def identifiers(cls) -> list[str]: ... + def __init__(self, msg: Message | None = None, data: str | None = None) -> None: ... def asbytes(self) -> bytes: ... - def __cmp__(self, other: object) -> int: ... + def __bytes__(self) -> bytes: ... def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... def get_name(self) -> str: ... + @property + def algorithm_name(self) -> str: ... def get_bits(self) -> int: ... def can_sign(self) -> bool: ... def get_fingerprint(self) -> bytes: ... + @property + def fingerprint(self) -> str: ... def get_base64(self) -> str: ... - def sign_ssh_data(self, data: bytes) -> Message: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... @classmethod - def from_private_key_file(cls: Type[_PK], filename: str, password: str | None = ...) -> _PK: ... + def from_private_key_file(cls, filename: StrOrBytesPath, password: str | None = None) -> Self: ... @classmethod - def from_private_key(cls: Type[_PK], file_obj: IO[str], password: str | None = ...) -> _PK: ... - def write_private_key_file(self, filename: str, password: str | None = ...) -> None: ... - def write_private_key(self, file_obj: IO[str], password: str | None = ...) -> None: ... + def from_private_key(cls, file_obj: _HasReadlines, password: str | None = None) -> Self: ... + def write_private_key_file( + self, filename: StrOrBytesPath, password: str | None = None, file_format: FileFormat = PEM # noqa: Y011 + ) -> None: ... + def write_private_key( + self, file_obj: SupportsWrite[str], password: str | None = None, file_format: FileFormat = PEM # noqa: Y011 + ) -> None: ... def load_certificate(self, value: Message | str) -> None: ... class PublicBlob: key_type: str - key_blob: str + key_blob: bytes comment: str - def __init__(self, type_: str, blob: bytes, comment: str | None = ...) -> None: ... + def __init__(self, type_: str, blob: bytes, comment: str | None = None) -> None: ... @classmethod - def from_file(cls, filename: str) -> PublicBlob: ... + def from_file(cls, filename: StrOrBytesPath) -> Self: ... @classmethod - def from_string(cls, string: str) -> PublicBlob: ... + def from_string(cls, string: str) -> Self: ... @classmethod - def from_message(cls, message: Message) -> PublicBlob: ... + def from_message(cls, message: Message) -> Self: ... def __eq__(self, other: object) -> bool: ... def __ne__(self, other: object) -> bool: ... diff --git a/stubs/paramiko/paramiko/primes.pyi b/stubs/paramiko/paramiko/primes.pyi index 3d7cccd9a267..a59dedce5b42 100644 --- a/stubs/paramiko/paramiko/primes.pyi +++ b/stubs/paramiko/paramiko/primes.pyi @@ -1,6 +1,8 @@ +from _typeshed import FileDescriptorOrPath + class ModulusPack: pack: dict[int, list[tuple[int, int]]] discarded: list[tuple[int, str]] def __init__(self) -> None: ... - def read_file(self, filename: str) -> None: ... + def read_file(self, filename: FileDescriptorOrPath) -> None: ... def get_modulus(self, min: int, prefer: int, max: int) -> tuple[int, int]: ... diff --git a/stubs/paramiko/paramiko/proxy.pyi b/stubs/paramiko/paramiko/proxy.pyi index 111e056b0c14..c22af8eb32d8 100644 --- a/stubs/paramiko/paramiko/proxy.pyi +++ b/stubs/paramiko/paramiko/proxy.pyi @@ -1,14 +1,17 @@ +from _typeshed import ReadableBuffer from subprocess import Popen from typing import Any from paramiko.util import ClosingContextManager +subprocess_import_error: ImportError | None + class ProxyCommand(ClosingContextManager): cmd: list[str] process: Popen[Any] timeout: float | None def __init__(self, command_line: str) -> None: ... - def send(self, content: bytes) -> int: ... + def send(self, content: ReadableBuffer) -> int: ... def recv(self, size: int) -> bytes: ... def close(self) -> None: ... @property diff --git a/stubs/paramiko/paramiko/py3compat.pyi b/stubs/paramiko/paramiko/py3compat.pyi deleted file mode 100644 index b41a04ff2f14..000000000000 --- a/stubs/paramiko/paramiko/py3compat.pyi +++ /dev/null @@ -1,42 +0,0 @@ -import sys -from typing import Any, Iterable, Sequence, Text, Type, TypeVar - -_T = TypeVar("_T") - -PY2: bool - -string_types: Type[Any] | Sequence[Type[Any]] -text_type: Type[Any] | Sequence[Type[Any]] -bytes_types: Type[Any] | Sequence[Type[Any]] -integer_types: Type[Any] | Sequence[Type[Any]] -long = int - -def input(prompt: Any) -> str: ... -def decodebytes(s: bytes) -> bytes: ... -def encodebytes(s: bytes) -> bytes: ... - -if sys.version_info >= (3, 0): - import builtins as builtins - import io - - StringIO = io.StringIO - BytesIO = io.BytesIO -else: - import __builtin__ as builtins - import cStringIO - - StringIO = cStringIO.StringIO - BytesIO = StringIO - -bytes = builtins.bytes - -def byte_ord(c: int | str) -> int: ... -def byte_chr(c: int) -> bytes: ... -def byte_mask(c: int, mask: int) -> bytes: ... -def b(s: bytes | str, encoding: str = ...) -> bytes: ... -def u(s: bytes | str, encoding: str = ...) -> Text: ... -def b2s(s: bytes | str) -> str: ... -def is_callable(c: Any) -> bool: ... -def next(c: Iterable[_T]) -> _T: ... - -MAXSIZE: int diff --git a/stubs/paramiko/paramiko/rsakey.pyi b/stubs/paramiko/paramiko/rsakey.pyi index 7c76e60e23d9..d5e099a3e442 100644 --- a/stubs/paramiko/paramiko/rsakey.pyi +++ b/stubs/paramiko/paramiko/rsakey.pyi @@ -1,33 +1,40 @@ -from typing import IO, Any, Callable +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from collections.abc import Callable +from typing import Final from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey, RSAPublicNumbers +from cryptography.hazmat.primitives.hashes import HashAlgorithm from paramiko.message import Message -from paramiko.pkey import PKey +from paramiko.pkey import PKey, _HasReadlines class RSAKey(PKey): - key: None | RSAPublicKey | RSAPrivateKey + name: Final = "ssh-rsa" + HASHES: Final[dict[str, type[HashAlgorithm]]] + + key: RSAPublicKey | RSAPrivateKey | None public_blob: None def __init__( self, - msg: Message | None = ..., - data: bytes | None = ..., - filename: str | None = ..., - password: str | None = ..., - key: None | RSAPublicKey | RSAPrivateKey = ..., - file_obj: IO[str] | None = ..., + msg: Message | None = None, + data: ReadableBuffer | None = None, + filename: FileDescriptorOrPath | None = None, + password: str | None = None, + key: RSAPublicKey | RSAPrivateKey | None = None, + file_obj: _HasReadlines | None = None, ) -> None: ... + @classmethod + def identifiers(cls) -> list[str]: ... @property def size(self) -> int: ... @property + def private_key(self) -> RSAPrivateKey | None: ... + @property def public_numbers(self) -> RSAPublicNumbers: ... def asbytes(self) -> bytes: ... - def __hash__(self) -> int: ... def get_name(self) -> str: ... def get_bits(self) -> int: ... def can_sign(self) -> bool: ... - def sign_ssh_data(self, data: bytes) -> Message: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... - def write_private_key_file(self, filename: str, password: str | None = ...) -> None: ... - def write_private_key(self, file_obj: IO[str], password: str | None = ...) -> None: ... @staticmethod - def generate(bits: int, progress_func: Callable[..., Any] | None = ...) -> RSAKey: ... + def generate(bits: int, progress_func: Callable[..., object] | None = None) -> RSAKey: ... diff --git a/stubs/paramiko/paramiko/server.pyi b/stubs/paramiko/paramiko/server.pyi index 22647fd22f69..ad803371917e 100644 --- a/stubs/paramiko/paramiko/server.pyi +++ b/stubs/paramiko/paramiko/server.pyi @@ -1,5 +1,4 @@ import threading -from typing import Tuple from paramiko.channel import Channel from paramiko.message import Message @@ -14,12 +13,9 @@ class ServerInterface: def check_auth_publickey(self, username: str, key: PKey) -> int: ... def check_auth_interactive(self, username: str, submethods: str) -> int | InteractiveQuery: ... def check_auth_interactive_response(self, responses: list[str]) -> int | InteractiveQuery: ... - def check_auth_gssapi_with_mic(self, username: str, gss_authenticated: int = ..., cc_file: str | None = ...) -> int: ... - def check_auth_gssapi_keyex(self, username: str, gss_authenticated: int = ..., cc_file: str | None = ...) -> int: ... - def enable_auth_gssapi(self) -> bool: ... def check_port_forward_request(self, address: str, port: int) -> int: ... def cancel_port_forward_request(self, address: str, port: int) -> None: ... - def check_global_request(self, kind: str, msg: Message) -> bool | Tuple[bool | int | str, ...]: ... + def check_global_request(self, kind: str, msg: Message) -> bool | tuple[bool | int | str, ...]: ... def check_channel_pty_request( self, channel: Channel, term: bytes, width: int, height: int, pixelwidth: int, pixelheight: int, modes: bytes ) -> bool: ... @@ -41,8 +37,8 @@ class InteractiveQuery: name: str instructions: str prompts: list[tuple[str, bool]] - def __init__(self, name: str = ..., instructions: str = ..., *prompts: str | tuple[str, bool]) -> None: ... - def add_prompt(self, prompt: str, echo: bool = ...) -> None: ... + def __init__(self, name: str = "", instructions: str = "", *prompts: str | tuple[str, bool]) -> None: ... + def add_prompt(self, prompt: str, echo: bool = True) -> None: ... class SubsystemHandler(threading.Thread): def __init__(self, channel: Channel, name: str, server: ServerInterface) -> None: ... diff --git a/stubs/paramiko/paramiko/sftp.pyi b/stubs/paramiko/paramiko/sftp.pyi index ec0b050692ac..afcfc224f3d9 100644 --- a/stubs/paramiko/paramiko/sftp.pyi +++ b/stubs/paramiko/paramiko/sftp.pyi @@ -51,6 +51,7 @@ SFTP_FLAG_EXCL: int CMD_NAMES: dict[int, str] +class int64(int): ... class SFTPError(Exception): ... class BaseSFTP: diff --git a/stubs/paramiko/paramiko/sftp_attr.pyi b/stubs/paramiko/paramiko/sftp_attr.pyi index 361e4f0b9930..7594ec937965 100644 --- a/stubs/paramiko/paramiko/sftp_attr.pyi +++ b/stubs/paramiko/paramiko/sftp_attr.pyi @@ -1,4 +1,5 @@ from os import stat_result +from typing_extensions import Self class SFTPAttributes: FLAG_SIZE: int @@ -17,5 +18,5 @@ class SFTPAttributes: attr: dict[str, str] def __init__(self) -> None: ... @classmethod - def from_stat(cls, obj: stat_result, filename: str | None = ...) -> SFTPAttributes: ... + def from_stat(cls, obj: stat_result, filename: str | None = None) -> Self: ... def asbytes(self) -> bytes: ... diff --git a/stubs/paramiko/paramiko/sftp_client.pyi b/stubs/paramiko/paramiko/sftp_client.pyi index fd49ff3be620..f7876c243b9a 100644 --- a/stubs/paramiko/paramiko/sftp_client.pyi +++ b/stubs/paramiko/paramiko/sftp_client.pyi @@ -1,5 +1,8 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterator from logging import Logger -from typing import IO, Any, Callable, Iterator, Text +from typing import IO, TypeAlias +from typing_extensions import Self from paramiko.channel import Channel from paramiko.sftp import BaseSFTP @@ -8,7 +11,7 @@ from paramiko.sftp_file import SFTPFile from paramiko.transport import Transport from paramiko.util import ClosingContextManager -_Callback = Callable[[int, int], Any] +_Callback: TypeAlias = Callable[[int, int], object] b_slash: bytes @@ -19,42 +22,52 @@ class SFTPClient(BaseSFTP, ClosingContextManager): logger: Logger def __init__(self, sock: Channel) -> None: ... @classmethod - def from_transport( - cls, t: Transport, window_size: int | None = ..., max_packet_size: int | None = ... - ) -> SFTPClient | None: ... + def from_transport(cls, t: Transport, window_size: int | None = None, max_packet_size: int | None = None) -> Self | None: ... def close(self) -> None: ... def get_channel(self) -> Channel | None: ... - def listdir(self, path: str = ...) -> list[str]: ... - def listdir_attr(self, path: str = ...) -> list[SFTPAttributes]: ... - def listdir_iter(self, path: bytes | Text = ..., read_aheads: int = ...) -> Iterator[SFTPAttributes]: ... - def open(self, filename: bytes | Text, mode: str = ..., bufsize: int = ...) -> SFTPFile: ... + def listdir(self, path: str = ".") -> list[str]: ... + def listdir_attr(self, path: str = ".") -> list[SFTPAttributes]: ... + def listdir_iter(self, path: bytes | str = ".", read_aheads: int = 50) -> Iterator[SFTPAttributes]: ... + def open(self, filename: bytes | str, mode: str = "r", bufsize: int = -1) -> SFTPFile: ... file = open - def remove(self, path: bytes | Text) -> None: ... + def remove(self, path: bytes | str) -> None: ... unlink = remove - def rename(self, oldpath: bytes | Text, newpath: bytes | Text) -> None: ... - def posix_rename(self, oldpath: bytes | Text, newpath: bytes | Text) -> None: ... - def mkdir(self, path: bytes | Text, mode: int = ...) -> None: ... - def rmdir(self, path: bytes | Text) -> None: ... - def stat(self, path: bytes | Text) -> SFTPAttributes: ... - def lstat(self, path: bytes | Text) -> SFTPAttributes: ... - def symlink(self, source: bytes | Text, dest: bytes | Text) -> None: ... - def chmod(self, path: bytes | Text, mode: int) -> None: ... - def chown(self, path: bytes | Text, uid: int, gid: int) -> None: ... - def utime(self, path: bytes | Text, times: tuple[float, float] | None) -> None: ... - def truncate(self, path: bytes | Text, size: int) -> None: ... - def readlink(self, path: bytes | Text) -> Text | None: ... - def normalize(self, path: bytes | Text) -> Text: ... - def chdir(self, path: None | bytes | Text = ...) -> None: ... - def getcwd(self) -> Text | None: ... + def rename(self, oldpath: bytes | str, newpath: bytes | str) -> None: ... + def posix_rename(self, oldpath: bytes | str, newpath: bytes | str) -> None: ... + def mkdir(self, path: bytes | str, mode: int = 511) -> None: ... + def rmdir(self, path: bytes | str) -> None: ... + def stat(self, path: bytes | str) -> SFTPAttributes: ... + def lstat(self, path: bytes | str) -> SFTPAttributes: ... + def symlink(self, source: bytes | str, dest: bytes | str) -> None: ... + def chmod(self, path: bytes | str, mode: int) -> None: ... + def chown(self, path: bytes | str, uid: int, gid: int) -> None: ... + def utime(self, path: bytes | str, times: tuple[float, float] | None) -> None: ... + def truncate(self, path: bytes | str, size: int) -> None: ... + def readlink(self, path: bytes | str) -> str | None: ... + def normalize(self, path: bytes | str) -> str: ... + def chdir(self, path: bytes | str | None = None) -> None: ... + def getcwd(self) -> str | None: ... def putfo( - self, fl: IO[bytes], remotepath: bytes | Text, file_size: int = ..., callback: _Callback | None = ..., confirm: bool = ... + self, fl: IO[bytes], remotepath: bytes | str, file_size: int = 0, callback: _Callback | None = None, confirm: bool = True ) -> SFTPAttributes: ... def put( - self, localpath: bytes | Text, remotepath: bytes | Text, callback: _Callback | None = ..., confirm: bool = ... + self, localpath: StrOrBytesPath, remotepath: bytes | str, callback: _Callback | None = None, confirm: bool = True ) -> SFTPAttributes: ... - def getfo(self, remotepath: bytes | Text, fl: IO[bytes], callback: _Callback | None = ..., prefetch: bool = ...) -> int: ... + def getfo( + self, + remotepath: bytes | str, + fl: IO[bytes], + callback: _Callback | None = None, + prefetch: bool = True, + max_concurrent_prefetch_requests: int | None = None, + ) -> int: ... def get( - self, remotepath: bytes | Text, localpath: bytes | Text, callback: _Callback | None = ..., prefetch: bool = ... + self, + remotepath: bytes | str, + localpath: StrOrBytesPath, + callback: _Callback | None = None, + prefetch: bool = True, + max_concurrent_prefetch_requests: int | None = None, ) -> None: ... class SFTP(SFTPClient): ... diff --git a/stubs/paramiko/paramiko/sftp_file.pyi b/stubs/paramiko/paramiko/sftp_file.pyi index 9663fccaba31..56a740e06afe 100644 --- a/stubs/paramiko/paramiko/sftp_file.pyi +++ b/stubs/paramiko/paramiko/sftp_file.pyi @@ -1,6 +1,8 @@ -from typing import Any, Iterator, Sequence +from collections.abc import Iterator, Sequence +from typing import Any from paramiko.file import BufferedFile +from paramiko.message import _LikeBytes from paramiko.sftp_attr import SFTPAttributes from paramiko.sftp_client import SFTPClient from paramiko.sftp_handle import SFTPHandle @@ -10,20 +12,22 @@ class SFTPFile(BufferedFile[Any]): sftp: SFTPClient handle: SFTPHandle pipelined: bool - def __init__(self, sftp: SFTPClient, handle: bytes, mode: str = ..., bufsize: int = ...) -> None: ... + def __init__(self, sftp: SFTPClient, handle: _LikeBytes, mode: str = "r", bufsize: int = -1) -> None: ... def __del__(self) -> None: ... def close(self) -> None: ... def settimeout(self, timeout: float) -> None: ... def gettimeout(self) -> float: ... def setblocking(self, blocking: bool) -> None: ... def seekable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... def stat(self) -> SFTPAttributes: ... def chmod(self, mode: int) -> None: ... def chown(self, uid: int, gid: int) -> None: ... def utime(self, times: tuple[float, float] | None) -> None: ... def truncate(self, size: int) -> None: ... - def check(self, hash_algorithm: str, offset: int = ..., length: int = ..., block_size: int = ...) -> bytes: ... - def set_pipelined(self, pipelined: bool = ...) -> None: ... - def prefetch(self, file_size: int | None = ...) -> None: ... - def readv(self, chunks: Sequence[tuple[int, int]]) -> Iterator[bytes]: ... + def check(self, hash_algorithm: str, offset: int = 0, length: int = 0, block_size: int = 0) -> bytes: ... + def set_pipelined(self, pipelined: bool = True) -> None: ... + def prefetch(self, file_size: int | None = None, max_concurrent_requests: int | None = None) -> None: ... + def readv( + self, chunks: Sequence[tuple[int, int]], max_concurrent_prefetch_requests: int | None = None + ) -> Iterator[bytes]: ... diff --git a/stubs/paramiko/paramiko/sftp_handle.pyi b/stubs/paramiko/paramiko/sftp_handle.pyi index 888e3c44ef08..d730c69c4cdb 100644 --- a/stubs/paramiko/paramiko/sftp_handle.pyi +++ b/stubs/paramiko/paramiko/sftp_handle.pyi @@ -1,10 +1,12 @@ +from _typeshed import ReadableBuffer + from paramiko.sftp_attr import SFTPAttributes from paramiko.util import ClosingContextManager class SFTPHandle(ClosingContextManager): - def __init__(self, flags: int = ...) -> None: ... + def __init__(self, flags: int = 0) -> None: ... def close(self) -> None: ... def read(self, offset: int, length: int) -> bytes | int: ... - def write(self, offset: int, data: bytes) -> int: ... + def write(self, offset: int, data: ReadableBuffer) -> int: ... def stat(self) -> int | SFTPAttributes: ... def chattr(self, attr: SFTPAttributes) -> int: ... diff --git a/stubs/paramiko/paramiko/sftp_server.pyi b/stubs/paramiko/paramiko/sftp_server.pyi index 6193ea1cbdb1..b4a289e8e7fb 100644 --- a/stubs/paramiko/paramiko/sftp_server.pyi +++ b/stubs/paramiko/paramiko/sftp_server.pyi @@ -1,5 +1,6 @@ +from _typeshed import FileDescriptorOrPath from logging import Logger -from typing import Any, Type +from typing import Any from paramiko.channel import Channel from paramiko.server import ServerInterface, SubsystemHandler @@ -18,11 +19,17 @@ class SFTPServer(BaseSFTP, SubsystemHandler): server: SFTPServerInterface sock: Channel | None def __init__( - self, channel: Channel, name: str, server: ServerInterface, sftp_si: Type[SFTPServerInterface], *largs: Any, **kwargs: Any + self, + channel: Channel, + name: str, + server: ServerInterface, + sftp_si: type[SFTPServerInterface] = ..., + *args: Any, + **kwargs: Any, ) -> None: ... def start_subsystem(self, name: str, transport: Transport, channel: Channel) -> None: ... def finish_subsystem(self) -> None: ... @staticmethod def convert_errno(e: int) -> int: ... @staticmethod - def set_file_attr(filename: str, attr: SFTPAttributes) -> None: ... + def set_file_attr(filename: FileDescriptorOrPath, attr: SFTPAttributes) -> None: ... diff --git a/stubs/paramiko/paramiko/ssh_exception.pyi b/stubs/paramiko/paramiko/ssh_exception.pyi index c122d63e162b..ddd60331d0ad 100644 --- a/stubs/paramiko/paramiko/ssh_exception.pyi +++ b/stubs/paramiko/paramiko/ssh_exception.pyi @@ -1,5 +1,5 @@ import socket -from typing import Mapping +from collections.abc import Mapping from paramiko.pkey import PKey @@ -16,6 +16,8 @@ class PartialAuthentication(AuthenticationException): allowed_types: list[str] def __init__(self, types: list[str]) -> None: ... +class UnableToAuthenticate(AuthenticationException): ... + class ChannelException(SSHException): code: int text: str @@ -27,11 +29,15 @@ class BadHostKeyException(SSHException): expected_key: PKey def __init__(self, hostname: str, got_key: PKey, expected_key: PKey) -> None: ... +class IncompatiblePeer(SSHException): ... + class ProxyCommandFailure(SSHException): command: str error: str def __init__(self, command: str, error: str) -> None: ... +class MessageOrderError(SSHException): ... + class NoValidConnectionsError(socket.error): errors: Mapping[tuple[str, int] | tuple[str, int, int, int], Exception] def __init__(self, errors: Mapping[tuple[str, int] | tuple[str, int, int, int], Exception]) -> None: ... diff --git a/stubs/paramiko/paramiko/ssh_gss.pyi b/stubs/paramiko/paramiko/ssh_gss.pyi deleted file mode 100644 index aed5ae7672fe..000000000000 --- a/stubs/paramiko/paramiko/ssh_gss.pyi +++ /dev/null @@ -1,52 +0,0 @@ -from typing import Any, Tuple, Type - -GSS_AUTH_AVAILABLE: bool -GSS_EXCEPTIONS: Tuple[Type[Exception], ...] - -def GSSAuth(auth_method: str, gss_deleg_creds: bool = ...) -> _SSH_GSSAuth: ... - -class _SSH_GSSAuth: - cc_file: None - def __init__(self, auth_method: str, gss_deleg_creds: bool) -> None: ... - def set_service(self, service: str) -> None: ... - def set_username(self, username: str) -> None: ... - def ssh_gss_oids(self, mode: str = ...) -> bytes: ... - def ssh_check_mech(self, desired_mech: str) -> bool: ... - -class _SSH_GSSAPI_OLD(_SSH_GSSAuth): - def __init__(self, auth_method: str, gss_deleg_creds: bool) -> None: ... - def ssh_init_sec_context( - self, target: str, desired_mech: str | None = ..., username: str | None = ..., recv_token: str | None = ... - ) -> str | None: ... - def ssh_get_mic(self, session_id: bytes, gss_kex: bool = ...) -> Any: ... - def ssh_accept_sec_context(self, hostname: str, recv_token: str, username: str | None = ...) -> str | None: ... - def ssh_check_mic(self, mic_token: str, session_id: bytes, username: str | None = ...) -> None: ... - @property - def credentials_delegated(self) -> bool: ... - def save_client_creds(self, client_token: str) -> None: ... - -_SSH_GSSAPI = _SSH_GSSAPI_OLD - -class _SSH_GSSAPI_NEW(_SSH_GSSAuth): - def __init__(self, auth_method: str, gss_deleg_creds: bool) -> None: ... - def ssh_init_sec_context( - self, target: str, desired_mech: str | None = ..., username: str | None = ..., recv_token: str | None = ... - ) -> str: ... - def ssh_get_mic(self, session_id: bytes, gss_kex: bool = ...) -> Any: ... - def ssh_accept_sec_context(self, hostname: str, recv_token: str, username: str | None = ...) -> str | None: ... - def ssh_check_mic(self, mic_token: str, session_id: bytes, username: str | None = ...) -> None: ... - @property - def credentials_delegated(self) -> bool: ... - def save_client_creds(self, client_token: str) -> None: ... - -class _SSH_SSPI(_SSH_GSSAuth): - def __init__(self, auth_method: str, gss_deleg_creds: bool) -> None: ... - def ssh_init_sec_context( - self, target: str, desired_mech: str | None = ..., username: str | None = ..., recv_token: str | None = ... - ) -> str: ... - def ssh_get_mic(self, session_id: bytes, gss_kex: bool = ...) -> Any: ... - def ssh_accept_sec_context(self, hostname: str, username: str, recv_token: str) -> str | None: ... - def ssh_check_mic(self, mic_token: str, session_id: bytes, username: str | None = ...) -> None: ... - @property - def credentials_delegated(self) -> bool: ... - def save_client_creds(self, client_token: str) -> None: ... diff --git a/stubs/paramiko/paramiko/transport.pyi b/stubs/paramiko/paramiko/transport.pyi index f294c9ad591c..81b3c170881c 100644 --- a/stubs/paramiko/paramiko/transport.pyi +++ b/stubs/paramiko/paramiko/transport.pyi @@ -1,29 +1,32 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Iterable, Mapping, Sequence from logging import Logger from socket import socket from threading import Condition, Event, Lock, Thread -from types import ModuleType -from typing import Any, Callable, Iterable, Protocol, Sequence, Tuple, Type +from typing import Any, Protocol, TypeAlias, type_check_only -from paramiko.auth_handler import AuthHandler, _InteractiveCallback +from paramiko.auth_handler import AuthHandler, AuthOnlyHandler, _InteractiveCallback from paramiko.channel import Channel from paramiko.message import Message from paramiko.packet import Packetizer from paramiko.pkey import PKey +from paramiko.proxy import ProxyCommand from paramiko.server import ServerInterface, SubsystemHandler from paramiko.sftp_client import SFTPClient -from paramiko.ssh_gss import _SSH_GSSAuth from paramiko.util import ClosingContextManager -_Addr = Tuple[str, int] +_Addr: TypeAlias = tuple[str, int] +_SocketLike: TypeAlias = str | _Addr | socket | Channel | ProxyCommand +@type_check_only class _KexEngine(Protocol): def start_kex(self) -> None: ... def parse_next(self, ptype: int, m: Message) -> None: ... class Transport(Thread, ClosingContextManager): - active: bool - hostname: str | None - sock: socket + daemon: bool + sock: socket | Channel + packetizer: Packetizer local_version: str remote_version: str @@ -34,21 +37,21 @@ class Transport(Thread, ClosingContextManager): session_id: bytes | None host_key_type: str | None host_key: PKey | None - use_gss_kex: bool - gss_kex_used: bool - kexgss_ctxt: _SSH_GSSAuth | None - gss_host: str + kex_engine: _KexEngine | None H: bytes | None K: int | None + initial_kex_done: bool in_kex: bool authenticated: bool lock: Lock + channel_events: dict[int, Event] channels_seen: dict[int, bool] default_max_packet_size: int default_window_size: int + saved_exception: Exception | None clear_to_send: Event clear_to_send_lock: Lock @@ -61,22 +64,26 @@ class Transport(Thread, ClosingContextManager): banner_timeout: float handshake_timeout: float auth_timeout: float - disabled_algorithms: dict[str, Iterable[str]] | None + channel_timeout: float + disabled_algorithms: Mapping[str, Iterable[str]] | None + server_sig_algs: bool + server_mode: bool server_object: ServerInterface | None server_key_dict: dict[str, PKey] server_accepts: list[Channel] server_accept_cv: Condition - subsystem_table: dict[str, tuple[Type[SubsystemHandler], Tuple[Any, ...], dict[str, Any]]] - sys: ModuleType + subsystem_table: dict[str, tuple[type[SubsystemHandler], tuple[Any, ...], dict[str, Any]]] + def __init__( self, - sock: str | tuple[str, int] | socket, - default_window_size: int = ..., - default_max_packet_size: int = ..., - gss_kex: bool = ..., - gss_deleg_creds: bool = ..., - disabled_algorithms: dict[str, Iterable[str]] | None = ..., + sock: _SocketLike, + default_window_size: int = 2097152, + default_max_packet_size: int = 32768, + disabled_algorithms: Mapping[str, Iterable[str]] | None = None, + server_sig_algs: bool = True, + strict_kex: bool = True, + packetizer_class: type[Packetizer] | None = None, ) -> None: ... @property def preferred_ciphers(self) -> Sequence[str]: ... @@ -85,99 +92,95 @@ class Transport(Thread, ClosingContextManager): @property def preferred_keys(self) -> Sequence[str]: ... @property + def preferred_pubkeys(self) -> Sequence[str]: ... + @property def preferred_kex(self) -> Sequence[str]: ... @property def preferred_compression(self) -> Sequence[str]: ... def atfork(self) -> None: ... def get_security_options(self) -> SecurityOptions: ... - def set_gss_host(self, gss_host: str | None, trust_dns: bool = ..., gssapi_requested: bool = ...) -> None: ... - def start_client(self, event: Event | None = ..., timeout: float | None = ...) -> None: ... - def start_server(self, event: Event = ..., server: ServerInterface | None = ...) -> None: ... + def start_client(self, event: Event | None = None, timeout: float | None = None) -> None: ... + def start_server(self, event: Event | None = None, server: ServerInterface | None = None) -> None: ... def add_server_key(self, key: PKey) -> None: ... def get_server_key(self) -> PKey | None: ... @staticmethod - def load_server_moduli(filename: str | None = ...) -> bool: ... + def load_server_moduli(filename: FileDescriptorOrPath | None = None) -> bool: ... def close(self) -> None: ... def get_remote_server_key(self) -> PKey: ... def is_active(self) -> bool: ... def open_session( - self, window_size: int | None = ..., max_packet_size: int | None = ..., timeout: float | None = ... + self, window_size: int | None = None, max_packet_size: int | None = None, timeout: float | None = None ) -> Channel: ... - def open_x11_channel(self, src_addr: _Addr = ...) -> Channel: ... + def open_x11_channel(self, src_addr: _Addr | None = None) -> Channel: ... def open_forward_agent_channel(self) -> Channel: ... def open_forwarded_tcpip_channel(self, src_addr: _Addr, dest_addr: _Addr) -> Channel: ... def open_channel( self, kind: str, - dest_addr: _Addr | None = ..., - src_addr: _Addr | None = ..., - window_size: int | None = ..., - max_packet_size: int | None = ..., - timeout: float | None = ..., + dest_addr: _Addr | None = None, + src_addr: _Addr | None = None, + window_size: int | None = None, + max_packet_size: int | None = None, + timeout: float | None = None, ) -> Channel: ... def request_port_forward( - self, address: str, port: int, handler: Callable[[Channel, _Addr, _Addr], None] | None = ... + self, address: str, port: int, handler: Callable[[Channel, _Addr, _Addr], object] | None = None ) -> int: ... def cancel_port_forward(self, address: str, port: int) -> None: ... def open_sftp_client(self) -> SFTPClient | None: ... - def send_ignore(self, byte_count: int = ...) -> None: ... + def send_ignore(self, byte_count: int | None = None) -> None: ... def renegotiate_keys(self) -> None: ... - def set_keepalive(self, interval: int) -> None: ... - def global_request(self, kind: str, data: Iterable[Any] | None = ..., wait: bool = ...) -> Message | None: ... - def accept(self, timeout: float | None = ...) -> Channel | None: ... + def set_keepalive(self, interval: float) -> None: ... + def global_request(self, kind: str, data: Iterable[Any] | None = None, wait: bool = True) -> Message | None: ... + def accept(self, timeout: float | None = None) -> Channel | None: ... def connect( - self, - hostkey: PKey | None = ..., - username: str = ..., - password: str | None = ..., - pkey: PKey | None = ..., - gss_host: str | None = ..., - gss_auth: bool = ..., - gss_kex: bool = ..., - gss_deleg_creds: bool = ..., - gss_trust_dns: bool = ..., + self, hostkey: PKey | None = None, username: str = "", password: str | None = None, pkey: PKey | None = None ) -> None: ... def get_exception(self) -> Exception | None: ... - def set_subsystem_handler(self, name: str, handler: Type[SubsystemHandler], *larg: Any, **kwarg: Any) -> None: ... + def set_subsystem_handler(self, name: str, handler: type[SubsystemHandler], *larg: Any, **kwarg: Any) -> None: ... def is_authenticated(self) -> bool: ... def get_username(self) -> str | None: ... def get_banner(self) -> bytes | None: ... def auth_none(self, username: str) -> list[str]: ... - def auth_password(self, username: str, password: str, event: Event | None = ..., fallback: bool = ...) -> list[str]: ... - def auth_publickey(self, username: str, key: PKey, event: Event | None = ...) -> list[str]: ... - def auth_interactive(self, username: str, handler: _InteractiveCallback, submethods: str = ...) -> list[str]: ... + def auth_password(self, username: str, password: str, event: Event | None = None, fallback: bool = True) -> list[str]: ... + def auth_publickey(self, username: str, key: PKey, event: Event | None = None) -> list[str]: ... + def auth_interactive(self, username: str, handler: _InteractiveCallback, submethods: str = "") -> list[str]: ... def auth_interactive_dumb( - self, username: str, handler: _InteractiveCallback | None = ..., submethods: str = ... + self, username: str, handler: _InteractiveCallback | None = None, submethods: str = "" ) -> list[str]: ... - def auth_gssapi_with_mic(self, username: str, gss_host: str, gss_deleg_creds: bool) -> list[str]: ... - def auth_gssapi_keyex(self, username: str) -> list[str]: ... def set_log_channel(self, name: str) -> None: ... def get_log_channel(self) -> str: ... def set_hexdump(self, hexdump: bool) -> None: ... def get_hexdump(self) -> bool: ... - def use_compression(self, compress: bool = ...) -> None: ... + def use_compression(self, compress: bool = True) -> None: ... def getpeername(self) -> tuple[str, int]: ... def stop_thread(self) -> None: ... def run(self) -> None: ... class SecurityOptions: + __slots__ = "_transport" def __init__(self, transport: Transport) -> None: ... + @property def ciphers(self) -> Sequence[str]: ... @ciphers.setter def ciphers(self, x: Sequence[str]) -> None: ... + @property def digests(self) -> Sequence[str]: ... @digests.setter def digests(self, x: Sequence[str]) -> None: ... + @property def key_types(self) -> Sequence[str]: ... @key_types.setter def key_types(self, x: Sequence[str]) -> None: ... + @property def kex(self) -> Sequence[str]: ... @kex.setter def kex(self, x: Sequence[str]) -> None: ... + @property def compression(self) -> Sequence[str]: ... @compression.setter @@ -190,3 +193,9 @@ class ChannelMap: def delete(self, chanid: int) -> None: ... def values(self) -> list[Channel]: ... def __len__(self) -> int: ... + +class ServiceRequestingTransport(Transport): + def ensure_session(self) -> None: ... + def get_auth_handler(self) -> AuthOnlyHandler: ... + def auth_password(self, username: str, password: str, fallback: bool = True) -> list[str]: ... # type: ignore[override] + def auth_publickey(self, username: str, key: PKey) -> list[str]: ... # type: ignore[override] diff --git a/stubs/paramiko/paramiko/util.pyi b/stubs/paramiko/paramiko/util.pyi index 05bd5c73ffe8..09e4fcc10cc1 100644 --- a/stubs/paramiko/paramiko/util.pyi +++ b/stubs/paramiko/paramiko/util.pyi @@ -1,52 +1,45 @@ -import sys +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from collections.abc import Iterable +from hashlib import _Hash from logging import Logger, LogRecord from types import TracebackType -from typing import IO, AnyStr, Callable, Protocol, Type, TypeVar +from typing import AnyStr +from typing_extensions import Self from paramiko.config import SSHConfig, SSHConfigDict from paramiko.hostkeys import HostKeys -if sys.version_info >= (3, 0): - from hashlib import _Hash -else: - from hashlib import _hash as _Hash - -class SupportsClose(Protocol): - def close(self) -> None: ... - -_T = TypeVar("_T") -_TC = TypeVar("_TC", bound=SupportsClose) - -def inflate_long(s: bytes, always_positive: bool = ...) -> int: ... - -deflate_zero: int -deflate_ff: int - -def deflate_long(n: int, add_sign_padding: bool = ...) -> bytes: ... -def format_binary(data: bytes, prefix: str = ...) -> list[str]: ... -def format_binary_line(data: bytes) -> str: ... -def safe_string(s: bytes) -> bytes: ... +def inflate_long(s: bytes | bytearray, always_positive: bool = False) -> int: ... +def deflate_long(n: int, add_sign_padding: bool = True) -> bytes: ... +def format_binary(data: bytes | bytearray, prefix: str = "") -> list[str]: ... +def format_binary_line(data: bytes | bytearray) -> str: ... +def safe_string(s: Iterable[int | str]) -> bytes: ... def bit_length(n: int) -> int: ... def tb_strings() -> list[str]: ... -def generate_key_bytes(hash_alg: Type[_Hash], salt: bytes, key: bytes | str, nbytes: int) -> bytes: ... -def load_host_keys(filename: str) -> HostKeys: ... -def parse_ssh_config(file_obj: IO[str]) -> SSHConfig: ... +def generate_key_bytes(hash_alg: type[_Hash], salt: ReadableBuffer, key: bytes | str, nbytes: int) -> bytes: ... +def load_host_keys(filename: FileDescriptorOrPath) -> HostKeys: ... +def parse_ssh_config(file_obj: Iterable[str]) -> SSHConfig: ... def lookup_ssh_host_config(hostname: str, config: SSHConfig) -> SSHConfigDict: ... def mod_inverse(x: int, m: int) -> int: ... def get_thread_id() -> int: ... -def log_to_file(filename: str, level: int = ...) -> None: ... +def log_to_file(filename: FileDescriptorOrPath, level: int = 10) -> None: ... class PFilter: def filter(self, record: LogRecord) -> bool: ... def get_logger(name: str) -> Logger: ... -def retry_on_signal(function: Callable[[], _T]) -> _T: ... def constant_time_bytes_eq(a: AnyStr, b: AnyStr) -> bool: ... class ClosingContextManager: - def __enter__(self: _TC) -> _TC: ... + def __enter__(self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def clamp_value(minimum: int, val: int, maximum: int) -> int: ... + +# This function attempts to convert objects to bytes, +# *but* just returns the object unchanged if that was unsuccessful! +def asbytes(s: object) -> object: ... +def b(s: str | bytes, encoding: str = "utf8") -> bytes: ... +def u(s: str | bytes, encoding: str = "utf8") -> str: ... diff --git a/stubs/paramiko/paramiko/win_openssh.pyi b/stubs/paramiko/paramiko/win_openssh.pyi new file mode 100644 index 000000000000..bc74d4c21f58 --- /dev/null +++ b/stubs/paramiko/paramiko/win_openssh.pyi @@ -0,0 +1,12 @@ +import sys + +if sys.platform == "win32": + PIPE_NAME: str + + def can_talk_to_agent() -> bool: ... + + class OpenSSHAgentConnection: + def __init__(self) -> None: ... + def send(self, data: bytes) -> int: ... + def recv(self, n: int) -> bytes: ... + def close(self) -> None: ... diff --git a/stubs/paramiko/paramiko/win_pageant.pyi b/stubs/paramiko/paramiko/win_pageant.pyi index ed62937fd7b8..1f9edee17eae 100644 --- a/stubs/paramiko/paramiko/win_pageant.pyi +++ b/stubs/paramiko/paramiko/win_pageant.pyi @@ -1,12 +1,21 @@ import ctypes import sys +from _typeshed import Incomplete +from typing import Literal, TypeAlias if sys.platform == "win32": win32con_WM_COPYDATA: int - def can_talk_to_agent(): ... - class COPYDATASTRUCT(ctypes.Structure): ... + def can_talk_to_agent() -> bool: ... + + ULONG_PTR: TypeAlias = ctypes.c_uint64 | ctypes.c_uint32 + + class COPYDATASTRUCT(ctypes.Structure): + num_data: Incomplete + data_size: Incomplete + data_loc: Incomplete + class PageantConnection: def __init__(self) -> None: ... def send(self, data: bytes) -> None: ... - def recv(self, n: int) -> bytes: ... + def recv(self, n: int) -> Literal[""] | bytes: ... def close(self) -> None: ... diff --git a/stubs/parsimonious/@tests/stubtest_allowlist.txt b/stubs/parsimonious/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..abd7877e0cbf --- /dev/null +++ b/stubs/parsimonious/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +parsimonious.nodes.RuleDecoratorMeta.__new__ + +# Tests are shipped with the source, we ignore it: +parsimonious.tests +parsimonious\.tests\..* diff --git a/stubs/parsimonious/METADATA.toml b/stubs/parsimonious/METADATA.toml new file mode 100644 index 000000000000..4cd095524d0e --- /dev/null +++ b/stubs/parsimonious/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.11.*" +upstream-repository = "https://github.com/erikrose/parsimonious" diff --git a/stubs/parsimonious/parsimonious/__init__.pyi b/stubs/parsimonious/parsimonious/__init__.pyi new file mode 100644 index 000000000000..31f99b479767 --- /dev/null +++ b/stubs/parsimonious/parsimonious/__init__.pyi @@ -0,0 +1,8 @@ +from parsimonious.exceptions import ( + BadGrammar as BadGrammar, + IncompleteParseError as IncompleteParseError, + ParseError as ParseError, + UndefinedLabel as UndefinedLabel, +) +from parsimonious.grammar import Grammar as Grammar, TokenGrammar as TokenGrammar +from parsimonious.nodes import NodeVisitor as NodeVisitor, VisitationError as VisitationError, rule as rule diff --git a/stubs/parsimonious/parsimonious/exceptions.pyi b/stubs/parsimonious/parsimonious/exceptions.pyi new file mode 100644 index 000000000000..6b3eb1ac386b --- /dev/null +++ b/stubs/parsimonious/parsimonious/exceptions.pyi @@ -0,0 +1,27 @@ +from parsimonious.expressions import Expression +from parsimonious.grammar import LazyReference +from parsimonious.nodes import Node +from parsimonious.utils import StrAndRepr + +class ParsimoniousError(Exception): ... + +class ParseError(StrAndRepr, ParsimoniousError): + text: str + pos: int + expr: Expression | None + def __init__(self, text: str, pos: int = -1, expr: Expression | None = None) -> None: ... + def line(self) -> int: ... + def column(self) -> int: ... + +class LeftRecursionError(ParseError): ... +class IncompleteParseError(ParseError): ... + +class VisitationError(ParsimoniousError): + original_class: type[BaseException] + def __init__(self, exc: BaseException, exc_class: type[BaseException], node: Node) -> None: ... + +class BadGrammar(StrAndRepr, ParsimoniousError): ... + +class UndefinedLabel(BadGrammar): + label: LazyReference + def __init__(self, label: LazyReference) -> None: ... diff --git a/stubs/parsimonious/parsimonious/expressions.pyi b/stubs/parsimonious/parsimonious/expressions.pyi new file mode 100644 index 000000000000..514768f57b5a --- /dev/null +++ b/stubs/parsimonious/parsimonious/expressions.pyi @@ -0,0 +1,82 @@ +import collections.abc +from collections.abc import Callable, Mapping +from re import Pattern +from typing import Any, TypeAlias +from typing_extensions import Self + +from parsimonious.exceptions import ParseError +from parsimonious.grammar import Grammar +from parsimonious.nodes import Node +from parsimonious.utils import StrAndRepr + +_CALLABLE_RETURN_TYPE: TypeAlias = int | tuple[int, list[Node]] | Node | None +_CALLABLE_TYPE: TypeAlias = ( + Callable[[str, int], _CALLABLE_RETURN_TYPE] + | Callable[[str, int, Mapping[tuple[int, int], Node], ParseError, Grammar], _CALLABLE_RETURN_TYPE] +) + +def is_callable(value: object) -> bool: ... +def expression(callable: _CALLABLE_TYPE, rule_name: str, grammar: Grammar) -> Expression: ... + +IN_PROGRESS: object + +class Expression(StrAndRepr): + __slots__ = ["name", "identity_tuple"] + name: str + identity_tuple: tuple[str] + def __init__(self, name: str = "") -> None: ... + def resolve_refs(self, rule_map: Mapping[str, Expression]) -> Self: ... + def parse(self, text: str, pos: int = 0) -> Node: ... + def match(self, text: str, pos: int = 0) -> Node: ... + def match_core(self, text: str, pos: int, cache: Mapping[tuple[int, int], Node], error: ParseError) -> Node: ... + def as_rule(self) -> str: ... + +class Literal(Expression): + __slots__ = ["literal"] + literal: str + identity_tuple: tuple[str, str] # type: ignore[assignment] + def __init__(self, literal: str, name: str = "") -> None: ... + +class TokenMatcher(Literal): ... + +class Regex(Expression): + __slots__ = ["re"] + re: Pattern[str] + identity_tuple: tuple[str, Pattern[str]] # type: ignore[assignment] + def __init__( + self, + pattern: str, + name: str = "", + ignore_case: bool = False, + locale: bool = False, + multiline: bool = False, + dot_all: bool = False, + unicode: bool = False, + verbose: bool = False, + ascii: bool = False, + ) -> None: ... + +class Compound(Expression): + __slots__ = ["members"] + members: collections.abc.Sequence[Expression] + def __init__(self, *members: Expression, **kwargs: Any) -> None: ... + +class Sequence(Compound): ... +class OneOf(Compound): ... + +class Lookahead(Compound): + __slots__ = ["negativity"] + negativity: bool + def __init__(self, member: Expression, *, negative: bool = False, **kwargs: Any) -> None: ... + +def Not(term: Expression) -> Lookahead: ... + +class Quantifier(Compound): + __slots__ = ["min", "max"] + min: int + max: float + def __init__(self, member: Expression, *, min: int = 0, max: float = ..., name: str = "", **kwargs: Any) -> None: ... + +def ZeroOrMore(member: Expression, name: str = "") -> Quantifier: ... +def OneOrMore(member: Expression, name: str = "", min: int = 1) -> Quantifier: ... +def Optional(member: Expression, name: str = "") -> Quantifier: ... diff --git a/stubs/parsimonious/parsimonious/grammar.pyi b/stubs/parsimonious/parsimonious/grammar.pyi new file mode 100644 index 000000000000..7871c183072c --- /dev/null +++ b/stubs/parsimonious/parsimonious/grammar.pyi @@ -0,0 +1,61 @@ +import collections.abc +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Callable, Mapping +from typing import Any +from typing_extensions import Never + +from parsimonious.expressions import _CALLABLE_TYPE, Expression, Literal, Lookahead, OneOf, Regex, Sequence, TokenMatcher +from parsimonious.nodes import Node, NodeVisitor + +class Grammar(OrderedDict[str, Expression]): + default_rule: Expression | Incomplete + def __init__(self, rules: str = "", **more_rules: Expression | _CALLABLE_TYPE) -> None: ... + def default(self, rule_name: str) -> Grammar: ... + def parse(self, text: str, pos: int = 0) -> Node: ... + def match(self, text: str, pos: int = 0) -> Node: ... + +class TokenGrammar(Grammar): ... +class BootstrappingGrammar(Grammar): ... + +rule_syntax: str + +class LazyReference(str): + name: str + def resolve_refs(self, rule_map: Mapping[str, Expression | LazyReference]) -> Expression: ... + +class RuleVisitor(NodeVisitor[tuple[OrderedDict[str, Expression], Expression | None]]): + quantifier_classes: dict[str, type[Expression]] + visit_expression: Callable[[RuleVisitor, Node, collections.abc.Sequence[Any]], Any] + visit_term: Callable[[RuleVisitor, Node, collections.abc.Sequence[Any]], Any] + visit_atom: Callable[[RuleVisitor, Node, collections.abc.Sequence[Any]], Any] + custom_rules: dict[str, Expression] + def __init__(self, custom_rules: Mapping[str, Expression] | None = None) -> None: ... + def visit_parenthesized(self, node: Node, parenthesized: collections.abc.Sequence[Any]) -> Expression: ... + def visit_quantifier(self, node: Node, quantifier: collections.abc.Sequence[Any]) -> Node: ... + def visit_quantified(self, node: Node, quantified: collections.abc.Sequence[Any]) -> Expression: ... + def visit_lookahead_term(self, node: Node, lookahead_term: collections.abc.Sequence[Any]) -> Lookahead: ... + def visit_not_term(self, node: Node, not_term: collections.abc.Sequence[Any]) -> Lookahead: ... + def visit_rule(self, node: Node, rule: collections.abc.Sequence[Any]) -> Expression: ... + def visit_sequence(self, node: Node, sequence: collections.abc.Sequence[Any]) -> Sequence: ... + def visit_ored(self, node: Node, ored: collections.abc.Sequence[Any]) -> OneOf: ... + def visit_or_term(self, node: Node, or_term: collections.abc.Sequence[Any]) -> Expression: ... + def visit_label(self, node: Node, label: collections.abc.Sequence[Any]) -> str: ... + def visit_reference(self, node: Node, reference: collections.abc.Sequence[Any]) -> LazyReference: ... + def visit_regex(self, node: Node, regex: collections.abc.Sequence[Any]) -> Regex: ... + def visit_spaceless_literal(self, spaceless_literal: Node, visited_children: collections.abc.Sequence[Any]) -> Literal: ... + def visit_literal(self, node: Node, literal: collections.abc.Sequence[Any]) -> Literal: ... + def generic_visit( + self, node: Node, visited_children: collections.abc.Sequence[Any] + ) -> collections.abc.Sequence[Any] | Node: ... + def visit_rules( + self, node: Node, rules_list: collections.abc.Sequence[Any] + ) -> tuple[OrderedDict[str, Expression], Expression | None]: ... + +class TokenRuleVisitor(RuleVisitor): + def visit_spaceless_literal( + self, spaceless_literal: Node, visited_children: collections.abc.Sequence[Any] + ) -> TokenMatcher: ... + def visit_regex(self, node: Node, regex: collections.abc.Sequence[Any]) -> Never: ... + +rule_grammar: Grammar diff --git a/stubs/parsimonious/parsimonious/nodes.pyi b/stubs/parsimonious/parsimonious/nodes.pyi new file mode 100644 index 000000000000..1d67f2f2fd0c --- /dev/null +++ b/stubs/parsimonious/parsimonious/nodes.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterator, Sequence +from re import Match +from typing import Any, Generic, TypeVar + +from parsimonious.exceptions import VisitationError as VisitationError +from parsimonious.expressions import Expression +from parsimonious.grammar import Grammar + +class Node: + __slots__ = ["expr", "full_text", "start", "end", "children"] + expr: Expression + full_text: str + start: int + end: int + children: Sequence[Node] + def __init__( + self, expr: Expression, full_text: str, start: int, end: int, children: Sequence[Node] | None = None + ) -> None: ... + @property + def expr_name(self) -> str: ... + def __iter__(self) -> Iterator[Node]: ... + @property + def text(self) -> str: ... + def prettily(self, error: Node | None = None) -> str: ... + def __repr__(self, top_level: bool = True) -> str: ... + +class RegexNode(Node): + __slots__ = ["match"] + match: Match[str] + +class RuleDecoratorMeta(type): ... + +_VisitResultT = TypeVar("_VisitResultT") +_ChildT = TypeVar("_ChildT") + +class NodeVisitor(Generic[_VisitResultT], metaclass=RuleDecoratorMeta): + grammar: Grammar | Incomplete + unwrapped_exceptions: tuple[type[BaseException], ...] + def visit(self, node: Node) -> _VisitResultT: ... + def generic_visit(self, node: Node, visited_children: Sequence[Any]): ... + def parse(self, text: str, pos: int = 0) -> _VisitResultT: ... + def match(self, text: str, pos: int = 0) -> _VisitResultT: ... + def lift_child(self, node: Node, children: Sequence[_ChildT]) -> _ChildT: ... + +_CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) + +def rule(rule_string: str) -> Callable[[_CallableT], _CallableT]: ... diff --git a/stubs/parsimonious/parsimonious/utils.pyi b/stubs/parsimonious/parsimonious/utils.pyi new file mode 100644 index 000000000000..b9440d08abca --- /dev/null +++ b/stubs/parsimonious/parsimonious/utils.pyi @@ -0,0 +1,11 @@ +import ast +from typing import Any + +class StrAndRepr: ... + +def evaluate_string(string: str | ast.AST) -> Any: ... + +class Token(StrAndRepr): + __slots__ = ["type"] + type: str + def __init__(self, type: str) -> None: ... diff --git a/stubs/passpy/@tests/stubtest_allowlist.txt b/stubs/passpy/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f7e53b666830 --- /dev/null +++ b/stubs/passpy/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +passpy.__main__ + +# Uses `git` dependency: +passpy.git +# Uses `gpg` dependency: +passpy.gpg diff --git a/stubs/passpy/METADATA.toml b/stubs/passpy/METADATA.toml index f3e83f9c456b..e72164f1cb04 100644 --- a/stubs/passpy/METADATA.toml +++ b/stubs/passpy/METADATA.toml @@ -1 +1,2 @@ version = "1.0.*" +upstream-repository = "https://github.com/bfrascher/passpy" diff --git a/stubs/passpy/passpy/store.pyi b/stubs/passpy/passpy/store.pyi index d2a27049e7d1..d69360f2b2c0 100644 --- a/stubs/passpy/passpy/store.pyi +++ b/stubs/passpy/passpy/store.pyi @@ -1,31 +1,31 @@ from _typeshed import StrPath from collections.abc import Iterator -from typing import Match +from re import Match class Store: def __init__( self, - gpg_bin: str = ..., - git_bin: str = ..., - store_dir: str = ..., - use_agent: bool = ..., - interactive: bool = ..., - verbose: bool = ..., + gpg_bin: str = "gpg2", + git_bin: str = "git", + store_dir: str = "~/.password-store", + use_agent: bool = True, + interactive: bool = False, + verbose: bool = False, ) -> None: ... def __iter__(self) -> Iterator[str]: ... def is_init(self) -> bool: ... - def init_store(self, gpg_ids: None | str | list[str], path: StrPath | None = ...) -> None: ... + def init_store(self, gpg_ids: str | list[str] | None, path: StrPath | None = None) -> None: ... def init_git(self) -> None: ... def git(self, method: str, *args: object, **kwargs: object) -> None: ... def get_key(self, path: StrPath | None) -> str | None: ... - def set_key(self, path: StrPath | None, key_data: str, force: bool = ...) -> None: ... - def remove_path(self, path: StrPath, recursive: bool = ..., force: bool = ...) -> None: ... + def set_key(self, path: StrPath | None, key_data: str, force: bool = False) -> None: ... + def remove_path(self, path: StrPath, recursive: bool = False, force: bool = False) -> None: ... def gen_key( - self, path: StrPath | None, length: int, symbols: bool = ..., force: bool = ..., inplace: bool = ... + self, path: StrPath | None, length: int, symbols: bool = True, force: bool = False, inplace: bool = False ) -> str | None: ... - def copy_path(self, old_path: StrPath, new_path: StrPath, force: bool = ...) -> None: ... - def move_path(self, old_path: StrPath, new_path: StrPath, force: bool = ...) -> None: ... + def copy_path(self, old_path: StrPath, new_path: StrPath, force: bool = False) -> None: ... + def move_path(self, old_path: StrPath, new_path: StrPath, force: bool = False) -> None: ... def list_dir(self, path: StrPath) -> tuple[list[str], list[str]]: ... def iter_dir(self, path: StrPath) -> Iterator[str]: ... - def find(self, names: None | str | list[str]) -> list[str]: ... + def find(self, names: str | list[str] | None) -> list[str]: ... def search(self, term: str) -> dict[str, list[tuple[str, Match[str]]]]: ... diff --git a/stubs/passpy/passpy/util.pyi b/stubs/passpy/passpy/util.pyi index e76e8abcab1a..137b613f8916 100644 --- a/stubs/passpy/passpy/util.pyi +++ b/stubs/passpy/passpy/util.pyi @@ -1 +1,13 @@ -def gen_password(length: int, symbols: bool = ...) -> str: ... +from collections.abc import Callable +from typing import Any, TypeVar + +_C = TypeVar("_C", bound=Callable[..., Any]) + +# Technically, the first argument of `_C` must be `Store`, +# but for now we leave it simple: +def initialised(func: _C) -> _C: ... +def trap(path_index: str | int) -> Callable[[_C], _C]: ... +def gen_password(length: int, symbols: bool = True) -> str: ... +def copy_move( + src: str, dst: str, force: bool = False, move: bool = False, interactive: bool = False, verbose: bool = False +) -> str | None: ... diff --git a/stubs/peewee/@tests/stubtest_allowlist.txt b/stubs/peewee/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..63e6f01a49f3 --- /dev/null +++ b/stubs/peewee/@tests/stubtest_allowlist.txt @@ -0,0 +1,43 @@ +# Stubtest doesn't recognize __ as indicating positional-only arg at runtime +# https://github.com/python/mypy/issues/15302 +peewee.Model.insert +peewee.Model.replace +peewee.Model.update + +# Wrapped with @Node.copy which changes the signature to "def (self, *args, **kwargs)" +peewee.DQ.__invert__ +peewee.Window.as_groups +peewee.Window.as_range +peewee.Window.as_rows +peewee._ModelQueryHelper.models + +# Wrapped with @database_required which sometimes injects the database argument +peewee.BaseQuery.execute +peewee.CompoundSelectQuery.exists +peewee.SelectBase.count +peewee.SelectBase.exists +peewee.SelectBase.first +peewee.SelectBase.get +peewee.SelectBase.peek +peewee.SelectBase.scalar +peewee.SelectBase.scalars + +# Descriptor methods exist on FieldAccessor at runtime, but are declared on the +# generic Field classes in the stub so that `instance.field` resolves to the +# field's Python value and `Model.field` resolves to the field (for queries). +peewee.Field.__get__ +peewee.Field.__set__ +# BigBitField overrides __get__ to yield a BigBitFieldData wrapper, not bytes. +peewee.BigBitField.__get__ +peewee.Field.__init__ +# These fields take named constructor args, carried by their __new__ overloads. +peewee.CharField.__init__ +peewee.ForeignKeyField.__init__ +peewee.DecimalField.__init__ +peewee.IdentityField.__init__ + +# Ignore missing playhouse modules and names we don't currently provide +playhouse\.\w+? +playhouse.flask_utils.PaginatedQuery +playhouse.flask_utils.get_\w+ +playhouse.flask_utils.object_list diff --git a/stubs/peewee/@tests/test_cases/check_fields.py b/stubs/peewee/@tests/test_cases/check_fields.py new file mode 100644 index 000000000000..9caafac908a5 --- /dev/null +++ b/stubs/peewee/@tests/test_cases/check_fields.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from peewee import BigBitField, BigBitFieldData, CharField, ForeignKeyField, IntegerField, Model + + +class User(Model): + username = CharField() + age = IntegerField() + nickname = CharField(null=True) + + +class Tweet(Model): + user = ForeignKeyField(User) + author = ForeignKeyField(User, null=True) + + +class Event(Model): + flags = BigBitField() + + +# A field is a descriptor that resolves differently depending on whether it is +# accessed on the model class or on an instance. `Model.field` is the Field +# object itself (used to build queries), while `instance.field` is the stored +# Python value. +assert_type(User.username, CharField[str]) +assert_type(User().username, str) + +assert_type(User.age, IntegerField[int]) +assert_type(User().age, int) + +# `null=True` allows the value to include None, both in the field's own +# parameterization and in the value produced on attribute access. +assert_type(User.nickname, CharField[str | None]) +assert_type(User().nickname, str | None) + +# Foreign keys resolve to the related model instance, or None when nullable. +assert_type(Tweet.user, ForeignKeyField[User]) +assert_type(Tweet().user, User) +assert_type(Tweet().author, User | None) + +# BigBitField is a special case: the instance descriptor yields a +# BigBitFieldData wrapper rather than the underlying bytes. +assert_type(Event.flags, BigBitField) +assert_type(Event().flags, BigBitFieldData) + +# __set__ accepts the field's value type... +user = User() +user.username = "guido" +user.age = 42 +user.nickname = None # nullable field accepts None + +# ...and rejects incompatible values. +user.age = "not an int" # type: ignore +user.username = None # type: ignore # non-null field rejects None diff --git a/stubs/peewee/METADATA.toml b/stubs/peewee/METADATA.toml new file mode 100644 index 000000000000..1fd3fc7dcae9 --- /dev/null +++ b/stubs/peewee/METADATA.toml @@ -0,0 +1,10 @@ +# We're not providing stubs for all playhouse modules right now +# https://github.com/python/typeshed/pull/11731#issuecomment-2065729058 +version = "4.5.1" +upstream-repository = "https://github.com/coleifer/peewee" +partial-stub = true + +[tool.stubtest] +stubtest-dependencies = ["Flask>=2.0.0"] +# Using stubtest_allowlist to ignore playhouse modules we don't provide. +ignore-missing-stub = false diff --git a/stubs/peewee/peewee.pyi b/stubs/peewee/peewee.pyi new file mode 100644 index 000000000000..13bb78bb93c6 --- /dev/null +++ b/stubs/peewee/peewee.pyi @@ -0,0 +1,2224 @@ +import re +import threading +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Generator, Iterable, Iterator +from datetime import date, datetime, time +from decimal import Decimal +from types import TracebackType +from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Self, TypeIs, TypeVar, Unpack +from uuid import UUID + +def callable_(c: object) -> TypeIs[Callable[..., object]]: ... + +multi_types: tuple[type[Incomplete], ...] + +_T = TypeVar("_T") +_R = TypeVar("_R") +_VT = TypeVar("_VT") +_F = TypeVar("_F", bound=Callable[..., Any]) +_Model: TypeAlias = Model +_M = TypeVar("_M", bound=Model, default=Model) +# __get__/__set__ value type. Bare Field defaults to Field[Any]. +_V = TypeVar("_V", default=Any) +_DatabaseType: TypeAlias = Database | DatabaseProxy + +# Common field kwargs, Unpack-ed into the field __new__ overloads. +@type_check_only +class _FieldKwargs(TypedDict, total=False): + index: bool + unique: bool + primary_key: bool + column_name: str | None + default: Any # A value matching the field's type, or a callable returning one + constraints: list[Node] | None + sequence: str | None + collation: str | None + unindexed: bool + choices: Iterable[tuple[Any, str]] | None # (value, display) pairs (value type depends on the field) + help_text: str | None + verbose_name: str | None + index_type: str | None + db_column: str | None + +@type_check_only +class _FKKwargs(_FieldKwargs, total=False): + field: Field[Any] | str | None + backref: str | Callable[[Field[Any]], str] | None + on_delete: str | None + on_update: str | None + deferrable: str | None + to_field: Field[Any] | str | None + object_id_name: str | None + lazy_load: bool + constraint_name: str | None + related_name: str | Callable[[Field[Any]], str] | None + rel_model: type[Model] | None + +class classmethod_only(Generic[_T, _R]): + fn: Callable[[type[_T]], _R] + def __init__(self, fn: Callable[[type[_T]], _R]) -> None: ... + def __get__(self, instance: None, instance_type: type[_T] | None = None) -> Callable[[], _R]: ... + +class attrdict(dict[str, _VT]): + def __getattr__(self, attr: str) -> _VT: ... + def __setattr__(self, attr: str, value: _VT) -> None: ... + # calls dict.update() + def __iadd__(self, rhs: SupportsKeysAndGetItem[str, _VT] | Iterable[tuple[str, _VT]]) -> Self: ... + def __add__(self, rhs: SupportsKeysAndGetItem[str, _VT] | Iterable[tuple[str, _VT]]) -> attrdict[_VT]: ... + +OP: attrdict[str] +DJANGO_MAP: attrdict[Incomplete] +JOIN: attrdict[str] +ROW: attrdict[int] +PREFETCH_TYPE: attrdict[int] +SCOPE_NORMAL: Final = 1 +SCOPE_SOURCE: Final = 2 +SCOPE_VALUES: Final = 4 +SCOPE_CTE: Final = 8 +SCOPE_COLUMN: Final = 16 +CSQ_PARENTHESES_NEVER: Final = 0 +CSQ_PARENTHESES_ALWAYS: Final = 1 +CSQ_PARENTHESES_UNNESTED: Final = 2 +CSQ_PARENTHESES_GROUPED: Final = 3 +CSQ_FLAT: Final = 0 +CSQ_PARENS: Final = 1 +CSQ_WRAP: Final = 2 +SNAKE_CASE_STEP1: Final[re.Pattern[str]] +SNAKE_CASE_STEP2: Final[re.Pattern[str]] +IDENTIFIER_RE: Final[re.Pattern[str]] + +def make_identifier(s: str) -> str: ... +def chunked(it: Iterable[_T], n: int) -> Generator[list[_T]]: ... + +class _callable_context_manager: + __slots__ = () + def __call__(self, fn): ... + +class Proxy: + __slots__ = ("obj", "_callbacks") + def __init__(self) -> None: ... + obj: Incomplete + def initialize(self, obj) -> None: ... + def attach_callback(self, callback): ... + def passthrough(method): ... + __enter__: Incomplete + __exit__: Incomplete + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + +class DatabaseProxy(Proxy): + __slots__ = ("obj", "_callbacks", "_Model") + def connection_context(self) -> ConnectionContext: ... + def atomic(self, *args, **kwargs) -> _atomic: ... + def manual_commit(self) -> _manual: ... + def transaction(self, *args, **kwargs) -> _transaction: ... + def savepoint(self) -> _savepoint: ... + @property + def Model(self) -> type[_Model]: ... + +class ModelDescriptor: ... + +class AliasManager: + __slots__ = ("_counter", "_current_index", "_mapping") + def __init__(self) -> None: ... + @property + def mapping(self): ... + def add(self, source): ... + def get(self, source, any_depth: bool = False): ... + def __getitem__(self, source): ... + def __setitem__(self, source, alias) -> None: ... + def push(self) -> None: ... + def pop(self) -> None: ... + +class State: + __slots__ = ("settings", "scope", "parentheses") + settings: dict[str, Incomplete] + scope: Incomplete + parentheses: bool + def __init__(self, scope=1, parentheses: bool = False, settings=None) -> None: ... + def __call__(self, scope=None, parentheses=None, **kwargs) -> State: ... + def __getattr__(self, attr_name: str): ... + +class Context: + __slots__ = ("stack", "_sql", "_values", "alias_manager", "state") + stack: list[Incomplete] + alias_manager: AliasManager + state: State + def __init__(self, **settings) -> None: ... + def as_new(self) -> Context: ... + def column_sort_key(self, item): ... + @property + def scope(self): ... + @property + def parentheses(self): ... + @property + def subquery(self): ... + def __call__(self, **overrides) -> Self: ... + scope_normal: Incomplete + scope_source: Incomplete + scope_values: Incomplete + scope_cte: Incomplete + scope_column: Incomplete + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def push_alias(self) -> Generator[None]: ... + def sql(self, obj): ... + def literal(self, keyword) -> Self: ... + def value(self, value, converter=None, add_param: bool = True): ... + def __sql__(self, ctx): ... + def parse(self, node): ... + def query(self) -> tuple[str, list[Incomplete]]: ... + +class Node: + __isabstractmethod__: bool + def clone(self) -> Self: ... + def __sql__(self, ctx): ... + @staticmethod + def copy(method): ... + def coerce(self, _coerce: bool = True) -> Self: ... + def is_alias(self) -> bool: ... + def unwrap(self) -> Self: ... + +class ColumnFactory: + __slots__ = ("node",) + node: Node + def __init__(self, node: Node) -> None: ... + def __getattr__(self, attr: str) -> Column: ... + __getitem__ = __getattr__ + +class _DynamicColumn: + __slots__ = () + def __get__(self, instance, instance_type=None): ... + +class _ExplicitColumn: + __slots__ = () + def __get__(self, instance, instance_type=None) -> Self: ... + +class Star(Node): + def __init__(self, source) -> None: ... + def __sql__(self, ctx): ... + +class Source(Node): + c: Incomplete + def __init__(self, alias=None) -> None: ... + def alias(self, name) -> Self: ... + def select(self, *columns) -> Select: ... + @property + def __star__(self) -> Star: ... + def join(self, dest, join_type="INNER JOIN", on=None) -> Join: ... + def left_outer_join(self, dest, on=None) -> Join: ... + def cte(self, name, recursive: bool = False, columns=None, materialized=None) -> CTE: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def apply_alias(self, ctx): ... + def apply_column(self, ctx): ... + +class _HashableSource: + def __init__(self, *args, **kwargs) -> None: ... + def alias(self, name) -> Self: ... + def clone(self) -> _HashableSource: ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] + def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] + __lt__: Callable[[Self, Any], Expression] + __le__: Callable[[Self, Any], Expression] + __gt__: Callable[[Self, Any], Expression] + __ge__: Callable[[Self, Any], Expression] + +class BaseTable(Source): + def __and__(self, other) -> Join: ... + def __add__(self, other) -> Join: ... + def __sub__(self, other) -> Join: ... + def __or__(self, other) -> Join: ... + def __mul__(self, other) -> Join: ... + def __rand__(self, other) -> Join: ... + def __radd__(self, other) -> Join: ... + def __rsub__(self, other) -> Join: ... + def __ror__(self, other) -> Join: ... + def __rmul__(self, other) -> Join: ... + +class _BoundTableContext(_callable_context_manager): + table: Incomplete + database: Incomplete + def __init__(self, table, database: _DatabaseType) -> None: ... + def __enter__(self): ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Table(_HashableSource, BaseTable): # type: ignore[misc] + __name__: Incomplete + c: Incomplete + primary_key: Incomplete + def __init__( + self, name, columns=None, primary_key=None, schema: str | None = None, alias=None, _model=None, _database=None + ) -> None: ... + def clone(self) -> Table: ... + def bind(self, database: _DatabaseType | None = None) -> Self: ... + def bind_ctx(self, database: _DatabaseType | None = None) -> _BoundTableContext: ... + def select(self, *columns) -> Select: ... + def insert(self, insert=None, columns=None, **kwargs) -> Insert: ... + def replace(self, insert=None, columns=None, **kwargs): ... + def update(self, update=None, **kwargs) -> Update: ... + def delete(self) -> Delete: ... + def __sql__(self, ctx): ... + +class Join(BaseTable): + lhs: Incomplete + rhs: Incomplete + join_type: Incomplete + def __init__(self, lhs, rhs, join_type="INNER JOIN", on=None, alias=None) -> None: ... + def on(self, predicate) -> Self: ... + def __sql__(self, ctx): ... + +class ValuesList(_HashableSource, BaseTable): # type: ignore[misc] + def __init__(self, values, columns=None, alias=None) -> None: ... + def columns(self, *names) -> Self: ... + def __sql__(self, ctx): ... + +class CTE(_HashableSource, Source): # type: ignore[misc] + def __init__(self, name, query, recursive: bool = False, columns=None, materialized=None) -> None: ... + def select_from(self, *columns) -> Select: ... + def union_all(self, rhs) -> CTE: ... + __add__ = union_all + def union(self, rhs) -> CTE: ... + __or__ = union + def __sql__(self, ctx): ... + +class ColumnBase(Node): + def converter(self, converter=None) -> Self: ... + def alias(self, alias) -> Alias | Self: ... + def unalias(self) -> Self: ... + def bind_to(self, dest) -> BindTo: ... + def cast(self, as_type) -> Cast: ... + def asc(self, collation=None, nulls=None) -> Ordering: ... + __pos__ = asc + def desc(self, collation=None, nulls=None) -> Ordering: ... + __neg__ = desc + def __invert__(self): ... + __and__: ClassVar[Callable[[Self, Any], Expression]] + __or__: ClassVar[Callable[[Self, Any], Expression]] + def __add__(self, rhs: Any) -> Expression: ... + __sub__: ClassVar[Callable[[Self, Any], Expression]] + __mul__: ClassVar[Callable[[Self, Any], Expression]] + __truediv__: ClassVar[Callable[[Self, Any], Expression]] + __xor__: ClassVar[Callable[[Self, Any], Expression]] + def __radd__(self, rhs: Any) -> Expression: ... + __rsub__: ClassVar[Callable[[Self, Any], Expression]] + __rmul__: ClassVar[Callable[[Self, Any], Expression]] + __rtruediv__: ClassVar[Callable[[Self, Any], Expression]] + __rand__: ClassVar[Callable[[Self, Any], Expression]] + __ror__: ClassVar[Callable[[Self, Any], Expression]] + __rxor__: ClassVar[Callable[[Self, Any], Expression]] + def __eq__(self, rhs) -> Expression: ... # type: ignore[override] + def __ne__(self, rhs) -> Expression: ... # type: ignore[override] + __lt__: ClassVar[Callable[[Self, Any], Expression]] + __le__: ClassVar[Callable[[Self, Any], Expression]] + __gt__: ClassVar[Callable[[Self, Any], Expression]] + __ge__: ClassVar[Callable[[Self, Any], Expression]] + __lshift__: ClassVar[Callable[[Self, Any], Expression]] + __rshift__: ClassVar[Callable[[Self, Any], Expression]] + __mod__: ClassVar[Callable[[Self, Any], Expression]] + __pow__: ClassVar[Callable[[Self, Any], Expression]] + like: ClassVar[Callable[[Self, Any], Expression]] + ilike: ClassVar[Callable[[Self, Any], Expression]] + bin_and: ClassVar[Callable[[Self, Any], Expression]] + bin_or: ClassVar[Callable[[Self, Any], Expression]] + in_: ClassVar[Callable[[Self, Any], Expression]] + not_in: ClassVar[Callable[[Self, Any], Expression]] + regexp: ClassVar[Callable[[Self, Any], Expression]] + iregexp: ClassVar[Callable[[Self, Any], Expression]] + def is_null(self, is_null: bool = True) -> Expression: ... + def contains(self, rhs) -> Expression: ... + def startswith(self, rhs) -> Expression: ... + def endswith(self, rhs) -> Expression: ... + def between(self, lo, hi) -> Expression: ... + def concat(self, rhs) -> StringExpression: ... + def __getitem__(self, item): ... + __iter__: Incomplete + def distinct(self) -> NodeList: ... + def collate(self, collation) -> NodeList: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + +class Column(ColumnBase): + source: Incomplete + name: Incomplete + def __init__(self, source, name) -> None: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def __hash__(self) -> int: ... + def __sql__(self, ctx): ... + +class WrappedNode(ColumnBase): + node: Incomplete + def __init__(self, node) -> None: ... + def is_alias(self) -> bool: ... + def unwrap(self): ... + +class EntityFactory: + __slots__ = ("node",) + node: Incomplete + def __init__(self, node) -> None: ... + def __getattr__(self, attr: str) -> Entity: ... + +class _DynamicEntity: + __slots__ = () + def __get__(self, instance, instance_type=None): ... + +class Alias(WrappedNode): + c: Incomplete + def __init__(self, node, alias) -> None: ... + def __hash__(self) -> int: ... + + @property + def name(self): ... + @name.setter + def name(self, value) -> None: ... + + def alias(self, alias=None): ... + def unalias(self): ... + def is_alias(self) -> bool: ... + def __sql__(self, ctx): ... + +class BindTo(WrappedNode): + dest: Incomplete + def __init__(self, node, dest) -> None: ... + def __sql__(self, ctx): ... + +class Negated(WrappedNode): + def __invert__(self): ... + def __sql__(self, ctx): ... + +class BitwiseMixin: + def __and__(self, other) -> Expression: ... + def __or__(self, other) -> Expression: ... + def __sub__(self, other) -> Expression: ... + def __invert__(self) -> BitwiseNegated: ... + +class BitwiseNegated(BitwiseMixin, WrappedNode): + op: str + def __invert__(self): ... + def __sql__(self, ctx): ... + +class Value(ColumnBase): + value: Incomplete + converter: Incomplete + multi: bool + values: list[Incomplete] | None + def __init__(self, value, converter=None, unpack: bool = True) -> None: ... + def __sql__(self, ctx): ... + +class ValueLiterals(WrappedNode): + def __sql__(self, ctx): ... + +def AsIs(value, converter=None) -> Value: ... + +class Cast(WrappedNode): + def __init__(self, node, cast) -> None: ... + def __sql__(self, ctx): ... + +class Ordering(WrappedNode): + direction: Incomplete + collation: Incomplete + nulls: Incomplete + def __init__(self, node, direction, collation=None, nulls=None) -> None: ... + def collate(self, collation=None) -> Self: ... # type: ignore[override] + def __sql__(self, ctx): ... + +def Asc(node, collation=None, nulls=None) -> Ordering: ... +def Desc(node, collation=None, nulls=None) -> Ordering: ... + +class Expression(ColumnBase): + lhs: Incomplete + op: Incomplete + rhs: Incomplete + flat: bool + def __init__(self, lhs, op, rhs, flat: bool = False) -> None: ... + def __sql__(self, ctx): ... + +class StringExpression(Expression): + def __sql__(self, ctx): ... + def __add__(self, rhs) -> StringExpression: ... + def __radd__(self, lhs) -> StringExpression: ... + +class Entity(ColumnBase): + def __init__(self, *path) -> None: ... + def __getattr__(self, attr: str) -> Entity: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def __hash__(self) -> int: ... + def __sql__(self, ctx): ... + +class SQL(ColumnBase): + sql: Incomplete + params: Incomplete + def __init__(self, sql, params=None) -> None: ... + def __sql__(self, ctx): ... + +def Check(constraint: str, name: str | None = None) -> SQL | NodeList: ... +def Default(value) -> SQL: ... + +class Function(ColumnBase): + no_coerce_functions: ClassVar[set[str]] + name: str | None + arguments: tuple[Any, ...] | None # Positional SQL function args: values, columns, or other nodes + def __init__(self, name, arguments, coerce: bool = True, python_value=None) -> None: ... + # fn.COUNT(...), fn.SUM(...), etc. each build a Function node. + def __getattr__(self, attr: str) -> Callable[..., Function]: ... + def filter(self, where=None) -> Self: ... + def order_by(self, *ordering) -> Self: ... + def python_value(self, func=None) -> Self: ... + def over( + self, partition_by=None, order_by=None, start=None, end=None, frame_type=None, window=None, exclude=None + ) -> NodeList: ... + def __sql__(self, ctx): ... + +fn: Function + +class Window(Node): + CURRENT_ROW: SQL + GROUP: SQL + TIES: SQL + NO_OTHERS: SQL + GROUPS: str + RANGE: str + ROWS: str + partition_by: Incomplete + order_by: Incomplete + start: Incomplete + end: Incomplete + frame_type: Incomplete + def __init__( + self, + partition_by=None, + order_by=None, + start=None, + end=None, + frame_type=None, + extends=None, + exclude=None, + alias=None, + _inline: bool = False, + ) -> None: ... + def alias(self, alias=None) -> Self: ... + def as_range(self) -> Self: ... + def as_rows(self) -> Self: ... + def as_groups(self) -> Self: ... + def extends(self, window=None) -> Self: ... + def exclude(self, frame_exclusion=None) -> Self: ... + @staticmethod + def following(value=None) -> SQL: ... + @staticmethod + def preceding(value=None) -> SQL: ... + def __sql__(self, ctx): ... + +class WindowAlias(Node): + window: Incomplete + def __init__(self, window) -> None: ... + def alias(self, window_alias) -> Self: ... + def __sql__(self, ctx): ... + +class ForUpdate(Node): + def __init__(self, expr, of=None, nowait: bool | None = None, skip_locked: bool | None = None) -> None: ... + def __sql__(self, ctx): ... + +class Case(ColumnBase): + predicate: Incomplete + expression_tuples: Incomplete + default: Incomplete | None + def __init__(self, predicate, expression_tuples, default=None) -> None: ... + def __sql__(self, ctx): ... + +class NodeList(ColumnBase): + nodes: Incomplete + glue: Incomplete + parens: bool + def __init__(self, nodes, glue: str = " ", parens: bool = False) -> None: ... + def __sql__(self, ctx): ... + +def CommaNodeList(nodes) -> NodeList: ... +def EnclosedNodeList(nodes) -> NodeList: ... + +class _Namespace(Node): + __slots__ = ("_name",) + def __init__(self, name) -> None: ... + def __getattr__(self, attr: str) -> NamespaceAttribute: ... + __getitem__ = __getattr__ + +class NamespaceAttribute(ColumnBase): + def __init__(self, namespace, attribute) -> None: ... + def __sql__(self, ctx): ... + +EXCLUDED: Incomplete + +class DQ(ColumnBase): + query: Incomplete + def __init__(self, **query) -> None: ... + def __invert__(self) -> Self: ... # type: ignore[override] + def clone(self) -> DQ: ... + +Tuple: Incomplete + +class QualifiedNames(WrappedNode): + def __init__(self, node, scope: int = 16) -> None: ... + def __sql__(self, ctx): ... + +class OnConflict(Node): + def __init__( + self, + action=None, + update=None, + preserve=None, + where=None, + conflict_target=None, + conflict_where=None, + conflict_constraint=None, + ) -> None: ... + def get_conflict_statement(self, ctx, query): ... + def get_conflict_update(self, ctx, query): ... + def preserve(self, *columns) -> Self: ... + def update(self, _data=None, **kwargs) -> Self: ... + def where(self, *expressions) -> Self: ... + def conflict_target(self, *constraints) -> Self: ... + def conflict_where(self, *expressions) -> Self: ... + def conflict_constraint(self, constraint) -> Self: ... + +class BaseQuery(Node): + default_row_type: Incomplete + def __init__(self, _database=None, **kwargs) -> None: ... + def bind(self, database: _DatabaseType | None = None) -> Self: ... + def clone(self) -> Self: ... + def dicts(self, as_dict: bool = True) -> Self: ... + def tuples(self, as_tuple: bool = True) -> Self: ... + def namedtuples(self, as_namedtuple: bool = True) -> Self: ... + def objects(self, constructor=None) -> Self: ... + def __sql__(self, ctx) -> None: ... + def sql(self) -> tuple[str, list[Any]]: ... # Returns (sql, params), params are bound query values + def execute(self, database: _DatabaseType | None = None): ... + async def aexecute(self, database: _DatabaseType | None = None): ... + def iterator(self, database: _DatabaseType | None = None): ... + def __iter__(self): ... + def __getitem__(self, value): ... + def __len__(self) -> int: ... + +class RawQuery(BaseQuery): + def __init__(self, sql=None, params=None, **kwargs) -> None: ... + def __sql__(self, ctx): ... + +class Query(BaseQuery): + def __init__(self, where=None, order_by=None, limit=None, offset=None, **kwargs) -> None: ... + def with_cte(self, *cte_list) -> Self: ... + def where(self, *expressions) -> Self: ... + def orwhere(self, *expressions) -> Self: ... + def order_by(self, *values) -> Self: ... + def order_by_extend(self, *values) -> Self: ... + def limit(self, value=None) -> Self: ... + def offset(self, value=None) -> Self: ... + def paginate(self, page, paginate_by: int = 20) -> Self: ... + def __sql__(self, ctx): ... + +class SelectQuery(Query): + def union_all(self, other) -> CompoundSelectQuery: ... + def __add__(self, other) -> CompoundSelectQuery: ... + def union(self, other) -> CompoundSelectQuery: ... + def __or__(self, other) -> CompoundSelectQuery: ... + def intersect(self, other) -> CompoundSelectQuery: ... + def __and__(self, other) -> CompoundSelectQuery: ... + def except_(self, other) -> CompoundSelectQuery: ... + def __sub__(self, other) -> CompoundSelectQuery: ... + def __radd__(self, other) -> CompoundSelectQuery: ... + def __ror__(self, other) -> CompoundSelectQuery: ... + def __rand__(self, other) -> CompoundSelectQuery: ... + def __rsub__(self, other) -> CompoundSelectQuery: ... + def select_from(self, *columns) -> Select: ... + +class SelectBase(_HashableSource, Source, SelectQuery): # type: ignore[misc] + def peek(self, database: _DatabaseType | None = None, n: int = 1): ... + def first(self, database: _DatabaseType | None = None, n: int = 1): ... + def scalar(self, database: _DatabaseType | None = None, as_tuple: bool = False, as_dict: bool = False): ... + def scalars(self, database: _DatabaseType | None = None) -> Generator[Incomplete]: ... + def count(self, database: _DatabaseType | None = None, clear_limit: bool = False) -> int: ... + def exists(self, database: _DatabaseType | None = None) -> bool: ... + def get(self, database: _DatabaseType | None = None): ... + +class CompoundSelectQuery(SelectBase): + lhs: Incomplete + op: Incomplete + rhs: Incomplete + def __init__(self, lhs, op, rhs) -> None: ... + def exists(self, database: _DatabaseType | None = None) -> bool: ... + def __sql__(self, ctx): ... + +class Select(SelectBase): + def __init__( + self, + from_list=None, + columns=None, + group_by=None, + having=None, + distinct=None, + windows=None, + for_update=None, + lateral=None, + **kwargs, + ) -> None: ... + def clone(self) -> Self: ... + def columns(self, *columns) -> Self: ... + select = columns + def select_extend(self, *columns) -> Self: ... + + @property + def selected_columns(self): ... + @selected_columns.setter + def selected_columns(self, value) -> None: ... + + def from_(self, *sources) -> Self: ... + def join(self, dest, join_type="INNER JOIN", on=None) -> Self: ... # type: ignore[override] + def left_outer_join(self, dest, on=None) -> Self: ... # type: ignore[override] + def group_by(self, *columns) -> Self: ... + def group_by_extend(self, *values) -> Self: ... + def having(self, *expressions) -> Self: ... + def distinct(self, *columns) -> Self: ... + def window(self, *windows) -> Self: ... + def for_update( + self, for_update: bool = True, of=None, nowait: bool | None = None, skip_locked: bool | None = None + ) -> Self: ... + def lateral(self, lateral: bool = True) -> Self: ... + def __sql_selection__(self, ctx, is_subquery: bool = False): ... + def __sql__(self, ctx): ... + +class _WriteQuery(Query): + table: Incomplete + def __init__(self, table, returning=None, **kwargs) -> None: ... + def cte(self, name, recursive: bool = False, columns=None, materialized=None) -> CTE: ... + def returning(self, *returning) -> Self: ... + def apply_returning(self, ctx): ... + def execute_returning(self, database: _DatabaseType): ... + def handle_result(self, database: _DatabaseType, cursor): ... + def __sql__(self, ctx): ... + +class Update(_WriteQuery): + def __init__(self, table, update=None, **kwargs) -> None: ... + def from_(self, *sources) -> Self: ... + def __sql__(self, ctx): ... + +class Insert(_WriteQuery): + SIMPLE: int + QUERY: int + MULTI: int + + class DefaultValuesException(Exception): ... + + def __init__(self, table, insert=None, columns=None, on_conflict=None, **kwargs) -> None: ... + def where(self, *expressions): ... + def as_rowcount(self, _as_rowcount: bool = True) -> Self: ... + def on_conflict_ignore(self, ignore: bool = True) -> Self: ... + def on_conflict_replace(self, replace: bool = True) -> Self: ... + def on_conflict(self, *args, **kwargs) -> Self: ... + def get_default_data(self): ... + def get_default_columns(self) -> list[Incomplete] | None: ... + def __sql__(self, ctx): ... + def handle_result(self, database: _DatabaseType, cursor): ... + +class Delete(_WriteQuery): + def __sql__(self, ctx): ... + +class Index(Node): + def __init__( + self, name, table, expressions, unique: bool = False, safe: bool = False, where=None, using=None, nulls_distinct=None + ) -> None: ... + def safe(self, _safe: bool = True) -> Self: ... + def where(self, *expressions) -> Self: ... + def using(self, _using=None) -> Self: ... + def nulls_distinct(self, nulls_distinct=None) -> Self: ... + def __sql__(self, ctx): ... + +class ModelIndex(Index): + def __init__( + self, model, fields, unique: bool = False, safe: bool = True, where=None, using=None, name=None, nulls_distinct=None + ) -> None: ... + +class PeeweeException(Exception): + def __init__(self, *args) -> None: ... + +class ImproperlyConfigured(PeeweeException): ... +class DatabaseError(PeeweeException): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InterfaceError(PeeweeException): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... + +class ExceptionWrapper: + __slots__ = ("exceptions",) + exceptions: Incomplete + def __init__(self, exceptions) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +class IndexMetadata(NamedTuple): + name: Incomplete + sql: Incomplete + columns: Incomplete + unique: Incomplete + table: Incomplete + +class ColumnMetadata(NamedTuple): + name: Incomplete + data_type: Incomplete + null: Incomplete + primary_key: Incomplete + table: Incomplete + default: Incomplete + full_type: str | None = None + identity: bool = False + +class ForeignKeyMetadata(NamedTuple): + column: Incomplete + dest_table: Incomplete + dest_column: Incomplete + table: Incomplete + name: str | None = None + on_delete: str | None = None + on_update: str | None = None + +class ViewMetadata(NamedTuple): + name: Incomplete + sql: Incomplete + +class QueryEvent(NamedTuple): + sql: str + params: Incomplete + duration: float + exception: BaseException | None + +class _ConnectionState: + def __init__(self, **kwargs) -> None: ... + closed: bool + conn: Incomplete + ctx: Incomplete + transactions: Incomplete + commit_callbacks: list[Incomplete] + def reset(self) -> None: ... + def set_connection(self, conn) -> None: ... + +class _ConnectionLocal(_ConnectionState, threading.local): ... + +class _NoopLock: + __slots__ = () + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class ConnectionContext(_callable_context_manager): + __slots__ = ("db",) + db: Incomplete + def __init__(self, db) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Database(_callable_context_manager): + context_class: Incomplete + json_methods: Incomplete + field_types: Incomplete + operations: Incomplete + use_concat_function: bool + param: str + quote: str + server_version: Incomplete + compound_select_parentheses: Incomplete + for_update: bool + index_schema_prefix: bool + index_using_precedes_table: bool + index_value_literals: bool + limit_max: int | None + nulls_ordering: bool + returning_clause: bool + safe_create_index: bool + safe_drop_index: bool + sequences: bool + truncate_table: bool + autoconnect: Incomplete + thread_safe: Incomplete + query_hooks: list[Callable[[QueryEvent], Incomplete]] + connect_params: Incomplete + def __deepcopy__(self, memo: Any) -> Self: ... + def __init__( + self, + database: str | None, + thread_safe: bool = True, + autorollback: bool = False, + field_types=None, + operations=None, + autocommit=None, + autoconnect: bool = True, + **kwargs, + ) -> None: ... + database: Incomplete + deferred: Incomplete + def init(self, database: str | None, **kwargs) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def connection_context(self) -> ConnectionContext: ... + def connect(self, reuse_if_open: bool = False) -> bool: ... + def close(self) -> bool: ... + def dispose(self) -> None: ... + def is_closed(self) -> bool: ... + def is_connection_usable(self) -> bool: ... + def connection(self): ... + def cursor(self, named_cursor=None): ... + def execute_sql(self, sql, params=None): ... + def execute(self, query, **context_options): ... + def get_context_options(self) -> dict[str, Incomplete]: ... + def get_sql_context(self, **context_options) -> context_class: ... # pyrefly: ignore [unknown-name] + def conflict_statement(self, on_conflict, query): ... + def conflict_update(self, on_conflict, query): ... + def last_insert_id(self, cursor, query_type=None): ... + def rows_affected(self, cursor): ... + def default_values_insert(self, ctx): ... + def session_start(self) -> _transaction: ... + def session_commit(self) -> bool: ... + def session_rollback(self) -> bool: ... + def in_transaction(self) -> bool: ... + def push_transaction(self, transaction) -> None: ... + def pop_transaction(self): ... + def transaction_depth(self) -> int: ... + def top_transaction(self): ... + def after_commit(self, fn: Callable[[], _R]) -> Callable[[], _R]: ... + def atomic(self, *args, **kwargs) -> _atomic: ... + def manual_commit(self) -> _manual: ... + def transaction(self, *args, **kwargs) -> _transaction: ... + def savepoint(self) -> _savepoint: ... + def begin(self) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def batch_commit(self, it, n) -> Generator[Incomplete]: ... + def table_exists(self, table_name, schema: str | None = None) -> bool: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None): ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def sequence_exists(self, seq, schema: str | None = None) -> bool: ... + def create_tables(self, models: Iterable[type[_Model]], **options) -> None: ... + def drop_tables(self, models: Iterable[type[_Model]], **kwargs) -> None: ... + def extract_date(self, date_part, date_field): ... + def truncate_date(self, date_part, date_field): ... + def to_timestamp(self, date_field): ... + def from_timestamp(self, date_field): ... + def random(self): ... + def bind(self, models: Iterable[type[_Model]], bind_refs: bool = True, bind_backrefs: bool = True) -> None: ... + def bind_ctx( + self, models: Iterable[type[_Model]], bind_refs: bool = True, bind_backrefs: bool = True + ) -> _BoundModelsContext: ... + def get_noop_select(self, ctx): ... + @property + def Model(self) -> type[_Model]: ... + +class SqliteDatabase(Database): + field_types: Incomplete + operations: Incomplete + index_schema_prefix: bool + index_value_literals: bool + limit_max: int + server_version: Incomplete + truncate_table: bool + nulls_ordering: bool + def __init__( + self, + database: str | None, + pragmas=None, + regexp_function: bool = False, + rank_functions: bool = False, + lock_type=None, + *args, + **kwargs, + ) -> None: ... + returning_clause: Incomplete + def init(self, database: str | None, pragmas=None, timeout: int = 5, returning_clause=None, **kwargs) -> None: ... + def pragma(self, key, value=..., permanent: bool = False, schema: str | None = None): ... + cache_size: Incomplete + foreign_keys: Incomplete + journal_mode: Incomplete + journal_size_limit: Incomplete + mmap_size: Incomplete + page_size: Incomplete + read_uncommitted: Incomplete + synchronous: Incomplete + wal_autocheckpoint: Incomplete + application_id: Incomplete + user_version: Incomplete + data_version: Incomplete + + @property + def timeout(self): ... + @timeout.setter + def timeout(self, seconds) -> None: ... + + def register_aggregate(self, klass, name=None, num_params: int = -1) -> None: ... + def aggregate(self, name=None, num_params: int = -1): ... + def register_collation(self, fn, name=None) -> None: ... + def collation(self, name=None): ... + def register_function(self, fn, name: str | None = None, num_params: int = -1, deterministic: bool | None = None) -> None: ... + def func(self, name: str | None = None, num_params: int = -1, deterministic: bool | None = None) -> Callable[[_F], _F]: ... + def register_window_function(self, klass, name=None, num_params: int = -1) -> None: ... + def window_function(self, name=None, num_params: int = -1): ... + def unregister_aggregate(self, name) -> None: ... + def unregister_collation(self, name) -> None: ... + def unregister_function(self, name) -> None: ... + def unregister_window_function(self, name) -> None: ... + def load_extension(self, extension) -> None: ... + def unload_extension(self, extension) -> None: ... + def attach(self, filename, name) -> bool: ... + def detach(self, name) -> bool: ... + def begin(self, lock_type=None) -> None: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None) -> list[Incomplete]: ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def get_binary_type(self): ... + def conflict_statement(self, on_conflict, query) -> SQL | None: ... + def conflict_update(self, oc, query) -> SQL | NodeList | None: ... + def extract_date(self, date_part, date_field) -> Function: ... + def truncate_date(self, date_part, date_field) -> Function: ... + def to_timestamp(self, date_field) -> Cast: ... + def from_timestamp(self, date_field) -> Function: ... + +class _BasePsycopgAdapter: + isolation_levels: dict[int, str] + txn_idle: int | None + txn_inerror: int | None + txn_unknown: int | None + isolation_levels_inv: dict[str, int] + def __init__(self) -> None: ... + + @overload + def isolation_level_int(self, isolation_level: str) -> int: ... + @overload + def isolation_level_int(self, isolation_level: _T) -> _T: ... + + @overload + def isolation_level_str(self, isolation_level: int) -> str: ... + @overload + def isolation_level_str(self, isolation_level: _T) -> _T: ... + + def is_connection_usable(self, conn) -> bool: ... + def is_connection_reusable(self, conn) -> bool: ... + def is_connection_closed(self, conn) -> bool: ... + +class Psycopg2Adapter(_BasePsycopgAdapter): + txn_idle: int | None + txn_inerror: int | None + txn_unknown: int | None + json_type: Incomplete + jsonb_type: Incomplete + cast_json_case: bool + def __init__(self) -> None: ... + def check_driver(self) -> None: ... + def get_binary_type(self) -> type[Incomplete]: ... + def connect(self, db, **params): ... + def get_server_version(self, conn): ... + def txn_status(self, conn) -> int: ... + def rollback(self, conn) -> None: ... + def server_side_cursor(self, conn): ... + +class Psycopg3Adapter(_BasePsycopgAdapter): + txn_idle: int | None + txn_inerror: int | None + txn_unknown: int | None + json_type: Incomplete + jsonb_type: Incomplete + cast_json_case: bool + def __init__(self) -> None: ... + def check_driver(self) -> None: ... + def get_binary_type(self) -> type[Incomplete]: ... + def connect(self, db, **params): ... + def get_server_version(self, conn): ... + def txn_status(self, conn) -> int: ... + def rollback(self, conn) -> None: ... + def server_side_cursor(self, conn): ... + +class PostgresqlDatabase(Database): + field_types: Incomplete + operations: Incomplete + param: str + compound_select_parentheses: Incomplete + for_update: bool + nulls_ordering: bool + returning_clause: bool + sequences: bool + psycopg2_adapter: Incomplete + psycopg3_adapter: Incomplete + def init( + self, + database: str | None, + register_unicode: bool = True, + encoding=None, + isolation_level=None, + *, + prefer_psycopg3: bool = False, + **kwargs, + ) -> None: ... + @property + def index_value_literals(self) -> bool: ... # type: ignore[override] + def is_connection_usable(self) -> bool: ... + def begin(self, isolation_level: str | None = None) -> None: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None) -> list[Incomplete]: ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def sequence_exists(self, sequence, schema: str | None = None) -> bool: ... + def get_binary_type(self) -> type[Incomplete]: ... + def conflict_statement(self, on_conflict, query) -> None: ... + def conflict_update(self, oc, query) -> NodeList: ... + def extract_date(self, date_part, date_field) -> Function: ... + def truncate_date(self, date_part, date_field) -> Function: ... + def interval(self, val) -> NodeList: ... + def to_timestamp(self, date_field) -> Function: ... + def from_timestamp(self, date_field) -> Function: ... + def get_noop_select(self, ctx): ... + def set_time_zone(self, timezone) -> None: ... + def set_isolation_level(self, isolation_level: int | str) -> None: ... + +class MySQLDatabase(Database): + field_types: Incomplete + operations: Incomplete + param: str + quote: str + compound_select_parentheses: Incomplete + for_update: bool + index_using_precedes_table: bool + limit_max: Incomplete + safe_create_index: bool + safe_drop_index: bool + use_concat_function: bool + sql_mode: str | None + mariadb: bool + def init(self, database: str | None, mariadb: bool | None = None, **kwargs) -> None: ... + def is_connection_usable(self) -> bool: ... + def default_values_insert(self, ctx): ... + def begin(self, isolation_level: str | None = None) -> None: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None) -> list[Incomplete]: ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def get_binary_type(self): ... + def conflict_statement(self, on_conflict, query) -> SQL | None: ... + def conflict_update(self, on_conflict, query) -> NodeList | None: ... + def extract_date(self, date_part, date_field) -> Function: ... + def truncate_date(self, date_part, date_field) -> Function: ... + def to_timestamp(self, date_field) -> Function: ... + def from_timestamp(self, date_field) -> Function: ... + def random(self) -> Function: ... + def get_noop_select(self, ctx): ... + +class _manual(_callable_context_manager): + db: Incomplete + def __init__(self, db) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class _atomic(_callable_context_manager): + db: Incomplete + def __init__(self, db, *args, **kwargs) -> None: ... + def __enter__(self) -> _transaction | _savepoint: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class _transaction(_callable_context_manager): + db: Incomplete + def __init__(self, db, *args, **kwargs) -> None: ... + def commit(self, begin: bool = True) -> None: ... + def rollback(self, begin: bool = True) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class _savepoint(_callable_context_manager): + db: Incomplete + sid: Incomplete + quoted_sid: Incomplete + def __init__(self, db, sid=None) -> None: ... + def commit(self, begin: bool = True) -> None: ... + def rollback(self, begin: bool = True) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class CursorWrapper: + cursor: Incomplete + count: int + index: int + initialized: bool + populated: bool + row_cache: list[Incomplete] + def __init__(self, cursor) -> None: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def __len__(self) -> int: ... + def initialize(self) -> None: ... + def iterate(self, cache: bool = True): ... + def process_row(self, row): ... + def iterator(self) -> Generator[Incomplete]: ... + def fill_cache(self, n: int = 0) -> None: ... + def dedupe_columns(self, columns: Iterable[str], valid_identifiers: bool = True) -> list[str]: ... + +class DictCursorWrapper(CursorWrapper): + valid_identifiers: bool + columns: list[str] + ncols: int + def initialize(self) -> None: ... + def process_row(self, row): ... + +class NamedTupleCursorWrapper(CursorWrapper): + tuple_class: Incomplete + def initialize(self) -> None: ... + def process_row(self, row): ... + +class ObjectCursorWrapper(DictCursorWrapper): + valid_identifiers: bool + constructor: Incomplete + def __init__(self, cursor, constructor) -> None: ... + def process_row(self, row): ... + +class ResultIterator: + cursor_wrapper: Incomplete + index: int + def __init__(self, cursor_wrapper) -> None: ... + def __iter__(self) -> Self: ... + def next(self): ... + __next__ = next + +class FieldAccessor: + model: Incomplete + field: Incomplete + name: Incomplete + def __init__(self, model, field, name) -> None: ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class ForeignKeyAccessor(FieldAccessor): + rel_model: Incomplete + def __init__(self, model, field, name) -> None: ... + def get_rel_instance(self, instance): ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, obj) -> None: ... + +class BackrefAccessor: + field: Incomplete + model: Incomplete + rel_model: Incomplete + def __init__(self, field) -> None: ... + def __get__(self, instance, instance_type=None): ... + +class ObjectIdAccessor: + field: Incomplete + def __init__(self, field) -> None: ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class Field(ColumnBase, Generic[_V]): + @overload + def __get__(self, instance: None, owner: Any) -> Self: ... + @overload + def __get__(self, instance: object, owner: Any) -> _V: ... + + def __set__(self, instance: object, value: _V) -> None: ... + accessor_class: Incomplete + auto_increment: bool + default_index_type: Incomplete + field_type: ClassVar[str] + null: Incomplete + index: Incomplete + unique: Incomplete + column_name: Incomplete + default: Incomplete + primary_key: Incomplete + constraints: Incomplete + sequence: Incomplete + collation: Incomplete + unindexed: Incomplete + choices: Incomplete + help_text: Incomplete + verbose_name: Incomplete + index_type: Incomplete + # Field constructor args are typed per-field in the __new__ overloads. + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __hash__(self) -> int: ... + model: Incomplete + name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + @property + def column(self) -> Column: ... + def adapt(self, value): ... + def db_value(self, value): ... + def python_value(self, value): ... + def to_value(self, value) -> Value: ... + def case_value(self, value) -> Value: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def __sql__(self, ctx): ... + def get_modifiers(self) -> list[int] | None: ... + def ddl_datatype(self, ctx) -> SQL: ... + def ddl(self, ctx) -> NodeList: ... + +class AnyField(Field): ... + +class IntegerField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> IntegerField[int | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> IntegerField[int]: ... + + def adapt(self, value): ... + +class BigIntegerField(IntegerField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BigIntegerField[int | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BigIntegerField[int]: ... + +class SmallIntegerField(IntegerField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> SmallIntegerField[int | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> SmallIntegerField[int]: ... + +class AutoField(IntegerField[_V]): + auto_increment: bool + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> AutoField[int]: ... + +class BigAutoField(AutoField[_V]): + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> BigAutoField[int]: ... + +class IdentityField(AutoField[_V]): + def __new__(cls, *args: Any, generate_always: bool = False, **kwargs: Unpack[_FieldKwargs]) -> IdentityField[int]: ... + +class PrimaryKeyField(AutoField[_V]): + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> PrimaryKeyField[int]: ... + +class FloatField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> FloatField[float | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> FloatField[float]: ... + + def adapt(self, value): ... + +class DoubleField(FloatField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> DoubleField[float | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> DoubleField[float]: ... + +class DecimalField(Field[_V]): + max_digits: Incomplete + decimal_places: Incomplete + auto_round: Incomplete + rounding: Incomplete + + @overload + def __new__( + cls, + max_digits: int = ..., + decimal_places: int = ..., + auto_round: bool = ..., + rounding: str | None = ..., + *args: Any, + null: Literal[True], + **kwargs: Unpack[_FieldKwargs], + ) -> DecimalField[Decimal | None]: ... + @overload + def __new__( + cls, + max_digits: int = ..., + decimal_places: int = ..., + auto_round: bool = ..., + rounding: str | None = ..., + *args: Any, + null: Literal[False] = ..., + **kwargs: Unpack[_FieldKwargs], + ) -> DecimalField[Decimal]: ... + + def get_modifiers(self) -> list[int]: ... + def db_value(self, value): ... + def python_value(self, value) -> Decimal | None: ... + +class _StringField(Field[_V]): + def adapt(self, value) -> str: ... + def __add__(self, other) -> StringExpression: ... + def __radd__(self, other) -> StringExpression: ... + +class CharField(_StringField[_V]): + max_length: int + + @overload + def __new__( + cls, max_length: int = 255, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> CharField[str | None]: ... + @overload + def __new__( + cls, max_length: int = 255, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> CharField[str]: ... + + def get_modifiers(self) -> list[int] | None: ... + +class FixedCharField(CharField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> FixedCharField[str | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> FixedCharField[str]: ... + + def adapt(self, value) -> str: ... + +class TextField(_StringField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> TextField[str | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> TextField[str]: ... + +class FieldDatabaseHook: + def bind(self, model, name, set_attribute: bool = True): ... + +class BlobField(FieldDatabaseHook, Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BlobField[bytes | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BlobField[bytes]: ... + + def db_value(self, value): ... + +class JSONPath(ColumnBase): + def __init__(self, field, keys=..., as_text: bool = False) -> None: ... + def __getitem__(self, key) -> JSONPath: ... + def path(self, *keys) -> JSONPath: ... + def as_text(self, as_text: bool = True) -> Self: ... + def as_int(self) -> Cast: ... + def as_float(self) -> Cast: ... + def set(self, value) -> Expression: ... + def insert(self, value) -> Expression: ... + def replace(self, value) -> Expression: ... + def append(self, value) -> Expression: ... + def remove(self) -> Expression: ... + def length(self) -> Expression: ... + def contained_by(self, value) -> Expression: ... + def has_key(self, key) -> Expression: ... + def has_keys(self, key_list) -> Expression: ... + def has_any_keys(self, key_list) -> Expression: ... + +class JSONField(FieldDatabaseHook, Field): + def __init__(self, dumps=None, loads=None, **kwargs) -> None: ... + def path(self, *keys): ... + def length(self) -> Expression: ... + def append(self, value) -> Expression: ... + def update(self, value) -> Expression: ... + def contains(self, value) -> Expression: ... # type: ignore[override] + def contained_by(self, value) -> Expression: ... + def has_key(self, key) -> Expression: ... + def has_keys(self, key_list) -> Expression: ... + def has_any_keys(self, key_list) -> Expression: ... + +class BitField(BitwiseMixin, BigIntegerField[_V]): + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> BitField[int]: ... + def flag(self, value=None): ... + +class BigBitFieldData: + instance: Incomplete + name: Incomplete + def __init__(self, instance, name) -> None: ... + def clear(self) -> None: ... + def set_bit(self, idx) -> None: ... + def clear_bit(self, idx) -> None: ... + def toggle_bit(self, idx) -> bool: ... + def is_set(self, idx) -> bool: ... + __getitem__ = is_set + def __setitem__(self, item: int, value: bool) -> None: ... + __delitem__ = clear_bit + def __len__(self) -> int: ... + def __and__(self, other: BigBitFieldData | bytes | bytearray | memoryview) -> bytearray: ... + def __or__(self, other: BigBitFieldData | bytes | bytearray | memoryview) -> bytearray: ... + def __xor__(self, other: BigBitFieldData | bytes | bytearray | memoryview) -> bytearray: ... + def __iter__(self) -> Iterator[Literal[0, 1]]: ... + def __bytes__(self) -> bytes: ... + +class BigBitFieldAccessor(FieldAccessor): + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class BigBitField(BlobField[bytes]): + accessor_class: Incomplete + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> Self: ... + + @overload # type: ignore[override] + def __get__(self, instance: None, owner: Any) -> Self: ... + @overload + def __get__(self, instance: object, owner: Any) -> BigBitFieldData: ... + + def db_value(self, value): ... + +class UUIDField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> UUIDField[UUID | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> UUIDField[UUID]: ... + + def db_value(self, value): ... + def python_value(self, value) -> UUID | None: ... + +class BinaryUUIDField(BlobField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BinaryUUIDField[UUID | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BinaryUUIDField[UUID]: ... + + def db_value(self, value): ... + def python_value(self, value) -> UUID | None: ... + +class _BaseFormattedField(Field[_V]): + formats: Incomplete + def __init__(self, formats=None, *args, **kwargs) -> None: ... + +class DateTimeField(_BaseFormattedField[_V]): + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> DateTimeField[datetime | None]: ... + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> DateTimeField[datetime]: ... + + formats: list[str] + def adapt(self, value): ... + def to_timestamp(self): ... + def truncate(self, part): ... + @property + def year(self): ... + @property + def month(self): ... + @property + def day(self): ... + @property + def hour(self): ... + @property + def minute(self): ... + @property + def second(self): ... + +class DateField(_BaseFormattedField[_V]): + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> DateField[date | None]: ... + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> DateField[date]: ... + + formats: list[str] + def adapt(self, value): ... + def to_timestamp(self): ... + def truncate(self, part): ... + @property + def year(self): ... + @property + def month(self): ... + @property + def day(self): ... + +class TimeField(_BaseFormattedField[_V]): + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> TimeField[time | None]: ... + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> TimeField[time]: ... + + formats: list[str] + def adapt(self, value): ... + @property + def hour(self): ... + @property + def minute(self): ... + @property + def second(self): ... + +class TimestampField(BigIntegerField[_V]): + valid_resolutions: Incomplete + resolution: Incomplete + ticks_to_microsecond: Incomplete + utc: Incomplete + formats: list[str] + + @overload + def __new__( + cls, *args, resolution: int = 1, utc: bool = False, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> TimestampField[datetime | None]: ... + @overload + def __new__( + cls, *args, resolution: int = 1, utc: bool = False, null: Literal[False] = False, **kwargs: Unpack[_FieldKwargs] + ) -> TimestampField[datetime]: ... + + def get_timestamp(self, value) -> float: ... + def db_value(self, value) -> int | None: ... + def python_value(self, value): ... + def from_timestamp(self): ... + @property + def year(self): ... + @property + def month(self): ... + @property + def day(self): ... + @property + def hour(self): ... + @property + def minute(self): ... + @property + def second(self): ... + +class IPField(BigIntegerField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> IPField[str | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> IPField[str]: ... + + def db_value(self, val): ... + def python_value(self, val) -> str | None: ... + +class BooleanField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BooleanField[bool | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BooleanField[bool]: ... + + adapt: Incomplete + +class BareField(Field): + adapt: Incomplete + def __init__(self, adapt=None, *args, **kwargs) -> None: ... + def ddl_datatype(self, ctx): ... + +class ForeignKeyField(Field[_V]): + accessor_class: Incomplete + backref_accessor_class: Incomplete + rel_model: Incomplete + rel_field: Incomplete + declared_backref: Incomplete + backref: Incomplete + on_delete: Incomplete + on_update: Incomplete + deferrable: Incomplete + deferred: Incomplete + object_id_name: Incomplete + lazy_load: Incomplete + constraint_name: str | None + + @overload + def __new__( + cls, model: type[_M], *args: Any, null: Literal[True], **kwargs: Unpack[_FKKwargs] + ) -> ForeignKeyField[_M | None]: ... + @overload + def __new__( + cls, model: type[_M], *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FKKwargs] + ) -> ForeignKeyField[_M]: ... + @overload + # Self-reference, the only string peewee accepts. Named refs use DeferredForeignKey. + def __new__( + cls, model: Literal["self"] = ..., *args: Any, null: bool = ..., **kwargs: Unpack[_FKKwargs] + ) -> ForeignKeyField[Any]: ... + + @property + def field_type(self): ... # type: ignore[override] + def get_modifiers(self): ... + def adapt(self, value): ... + def db_value(self, value): ... + def python_value(self, value): ... + column_name: Incomplete + safe_name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + def foreign_key_constraint(self, explicit_name: bool = False) -> NodeList: ... + def get_constraint_name(self) -> str: ... + def __getattr__(self, attr: str): ... + +class DeferredForeignKey(Field): + field_kwargs: Incomplete + rel_model_name: Incomplete + # Model named by string, so the related type isn't knowable and null can't refine it. + def __init__(self, rel_model_name: str, *, null: bool = ..., **kwargs: Unpack[_FKKwargs]) -> None: ... + __hash__ = object.__hash__ + def __deepcopy__(self, memo=None) -> DeferredForeignKey: ... + def set_model(self, rel_model) -> None: ... + @staticmethod + def resolve(model_cls) -> None: ... + +class DeferredThroughModel: + def __init__(self) -> None: ... + def set_field(self, model, field, name) -> None: ... + def set_model(self, through_model) -> None: ... + +class MetaField(Field): + column_name: Incomplete + default: Incomplete + model: Incomplete + name: Incomplete + primary_key: bool + +class ManyToManyFieldAccessor(FieldAccessor): + model: Incomplete + rel_model: Incomplete + through_model: Incomplete + src_fk: Incomplete + dest_fk: Incomplete + def __init__(self, model, field, name) -> None: ... + def get_query(self, instance): ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class ManyToManyField(MetaField): + accessor_class: Incomplete + rel_model: Incomplete + backref: Incomplete + def __init__( + self, + model, + backref=None, + through_model=None, + on_delete=None, + on_update=None, + prevent_unsaved: bool = True, + _is_backref: bool = False, + ) -> None: ... + def bind(self, model, name, set_attribute: bool = True) -> None: ... + def get_models(self) -> list[Incomplete]: ... + + @property + def through_model(self): ... + @through_model.setter + def through_model(self, value) -> None: ... + + def get_through_model(self): ... + +class VirtualField(MetaField): + field_class: Incomplete + field_instance: Incomplete + def __init__(self, field_class=None, *args, **kwargs) -> None: ... + def db_value(self, value): ... + def python_value(self, value): ... + model: Incomplete + column_name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + +class CompositeKey(MetaField): + sequence: Incomplete + field_names: Incomplete + def __init__(self, *field_names) -> None: ... + @property + def safe_field_names(self): ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] + def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] + def __hash__(self) -> int: ... + def __sql__(self, ctx): ... + model: Incomplete + column_name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + +class _SortedFieldList: + __slots__ = ("_keys", "_items") + def __init__(self) -> None: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __contains__(self, item) -> bool: ... + def index(self, field) -> int: ... + def insert(self, item) -> None: ... + def remove(self, item) -> None: ... + +class SchemaManager: + model: Incomplete + context_options: Incomplete + def __init__(self, model, database: _DatabaseType | None = None, **context_options) -> None: ... + + @property + def database(self): ... + @database.setter + def database(self, value) -> None: ... + + def create_table(self, safe: bool = True, **options) -> None: ... + def create_table_as(self, table_name, query, safe: bool = True, **meta) -> None: ... + def drop_table(self, safe: bool = True, **options) -> None: ... + def truncate_table(self, restart_identity: bool = False, cascade: bool = False) -> None: ... + def create_indexes(self, safe: bool = True) -> None: ... + def drop_index(self, field=None, index=None, safe: bool = True): ... + def drop_indexes(self, safe: bool = True) -> None: ... + def create_sequence(self, field) -> None: ... + def drop_sequence(self, field) -> None: ... + def create_foreign_key(self, field) -> None: ... + def create_sequences(self) -> None: ... + def create_all(self, safe: bool = True, **table_options) -> None: ... + def drop_sequences(self) -> None: ... + def drop_all(self, safe: bool = True, drop_sequences: bool = True, **options) -> None: ... + +class Metadata: + model: type[Model] + database: Incomplete + fields: Incomplete + columns: Incomplete + combined: Incomplete + sorted_fields: Incomplete + sorted_field_names: Incomplete + defaults: Incomplete + name: Incomplete + table_function: Incomplete + legacy_table_names: Incomplete + table_name: Incomplete + indexes: Incomplete + constraints: Incomplete + primary_key: Field[Any] | Literal[False] + composite_key: Incomplete + only_save_dirty: Incomplete + depends_on: Incomplete + table_settings: Incomplete + without_rowid: Incomplete + strict_tables: Incomplete + temporary: Incomplete + refs: Incomplete + backrefs: Incomplete + model_refs: Incomplete + model_backrefs: Incomplete + manytomany: Incomplete + options: Incomplete + def __init__( + self, + model, + database: _DatabaseType | None = None, + table_name=None, + indexes=None, + primary_key=None, + constraints=None, + schema: str | None = None, + only_save_dirty: bool = False, + depends_on=None, + options=None, + db_table=None, + table_function=None, + table_settings=None, + without_rowid: bool = False, + temporary: bool = False, + strict_tables=None, + legacy_table_names: bool = True, + **kwargs, + ) -> None: ... + def make_table_name(self) -> str: ... + def model_graph( + self, refs: bool = True, backrefs: bool = True, depth_first: bool = True + ) -> list[tuple[Incomplete, Incomplete, Incomplete]]: ... + def add_ref(self, field) -> None: ... + def remove_ref(self, field) -> None: ... + def add_manytomany(self, field) -> None: ... + def remove_manytomany(self, field) -> None: ... + + @property + def table(self) -> Table: ... + @table.deleter + def table(self) -> None: ... + + @property + def schema(self) -> str | None: ... + @schema.setter + def schema(self, value) -> None: ... + + @property + def entity(self) -> Entity: ... + def add_field(self, field_name, field, set_attribute: bool = True) -> None: ... + def remove_field(self, field_name) -> None: ... + auto_increment: Incomplete + def set_primary_key(self, name, field) -> None: ... + def get_primary_keys(self): ... + def get_default_dict(self): ... + def fields_to_index(self) -> list[Incomplete]: ... + def set_database(self, database: _DatabaseType) -> None: ... + def set_table_name(self, table_name) -> None: ... + def get_database_instance(self) -> _DatabaseType | None: ... + +class SubclassAwareMetadata(Metadata): + models: Incomplete + def __init__(self, model, *args, **kwargs) -> None: ... + def map_models(self, fn) -> None: ... + +class DoesNotExist(Exception): ... + +class ModelBase(type): + inheritable: set[str] + def __new__(cls, name, bases, attrs): ... + def __iter__(self): ... + def __getitem__(self, key): ... + def __setitem__(self, key, value) -> None: ... + def __delitem__(self, key) -> None: ... + def __contains__(self, key) -> bool: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __sql__(self, ctx): ... + +class _BoundModelsContext(_callable_context_manager): + models: Incomplete + database: Incomplete + bind_refs: Incomplete + bind_backrefs: Incomplete + def __init__(self, models, database: _DatabaseType, bind_refs, bind_backrefs) -> None: ... + def __enter__(self): ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Model(metaclass=ModelBase): + __data__: Incomplete + __rel__: Incomplete + _meta: Metadata + def __init__(self, *args, **kwargs) -> None: ... + @classmethod + def validate_model(cls) -> None: ... + @classmethod + def alias(cls, alias=None) -> ModelAlias[Self]: ... + @classmethod + def select(cls, *fields) -> ModelSelect[Self]: ... + @classmethod + def update(cls, data=None, /, **update) -> ModelUpdate: ... + @classmethod + def insert(cls, data=None, /, **insert) -> ModelInsert: ... + @classmethod + def insert_many(cls, rows, fields=None) -> ModelInsert: ... + @classmethod + def insert_from(cls, query, fields) -> ModelInsert: ... + @classmethod + def replace(cls, data=None, /, **insert): ... + @classmethod + def replace_many(cls, rows, fields=None): ... + @classmethod + def raw(cls, sql, *params) -> ModelRaw: ... + delete: classmethod_only[Self, ModelDelete] + @classmethod + def create(cls, **query) -> Self: ... + @classmethod + def bulk_create(cls, model_list, batch_size=None) -> None: ... + @classmethod + def bulk_update(cls, model_list, fields, batch_size=None): ... + @classmethod + def noop(cls) -> NoopModelSelect[Self]: ... + @classmethod + def get(cls, *query, **filters) -> Self: ... + @classmethod + def get_or_none(cls, *query, **filters) -> Self | None: ... + @classmethod + def get_by_id(cls, pk) -> Self: ... + @classmethod + def set_by_id(cls, key, value): ... + @classmethod + def delete_by_id(cls, pk): ... + @classmethod + def get_or_create(cls, **kwargs): ... + @classmethod + def filter(cls, *dq_nodes, **filters): ... + def get_id(self): ... + def save(self, force_insert: bool = False, only=None) -> int: ... + def is_dirty(self) -> bool: ... + @property + def dirty_fields(self) -> list[Field[Any]]: ... + @property + def dirty_field_names(self) -> list[str]: ... + def dependencies(self, search_nullable: bool = True, exclude_null_children: bool = False) -> Generator[Incomplete]: ... + def delete_instance(self, recursive: bool = False, delete_nullable: bool = False) -> int: ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] + def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] + def __sql__(self, ctx): ... + @classmethod + def bind(cls, database: _DatabaseType, bind_refs: bool = True, bind_backrefs: bool = True, _exclude=None) -> bool: ... + @classmethod + def bind_ctx(cls, database: _DatabaseType, bind_refs: bool = True, bind_backrefs: bool = True) -> _BoundModelsContext: ... + @classmethod + def table_exists(cls): ... + @classmethod + def create_table(cls, safe: bool = True, **options) -> None: ... + @classmethod + def drop_table(cls, safe: bool = True, drop_sequences: bool = True, **options) -> None: ... + @classmethod + def truncate_table(cls, **options) -> None: ... + @classmethod + def index(cls, *fields, **kwargs) -> ModelIndex: ... + @classmethod + def add_index(cls, *fields, **kwargs) -> None: ... + +class ModelAlias(Node, Generic[_M]): + def __init__(self, model: type[_M], alias=None) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def get_field_aliases(self) -> list[Incomplete]: ... + def select(self, *selection) -> ModelSelect[_M]: ... + def __call__(self, **kwargs): ... + def __sql__(self, ctx): ... + +class FieldAlias(Field): + source: Incomplete + model: Incomplete + field: Incomplete + def __init__(self, source, field) -> None: ... + @classmethod + def create(cls, source, field): ... + def clone(self) -> FieldAlias: ... + def adapt(self, value): ... + def python_value(self, value): ... + def db_value(self, value): ... + def __getattr__(self, attr: str): ... + def __sql__(self, ctx): ... + +class _ModelQueryHelper: + default_row_type: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def objects(self, constructor=None) -> Self: ... + def models(self) -> Self: ... + +class ModelRaw(_ModelQueryHelper, RawQuery): # type: ignore[misc] + model: Incomplete + def __init__(self, model, sql, params, **kwargs) -> None: ... + def get(self) -> Model: ... + +class BaseModelSelect(_ModelQueryHelper): + def union_all(self, rhs) -> ModelCompoundSelectQuery: ... + __add__ = union_all + def union(self, rhs) -> ModelCompoundSelectQuery: ... + __or__ = union + def intersect(self, rhs) -> ModelCompoundSelectQuery: ... + __and__ = intersect + def except_(self, rhs) -> ModelCompoundSelectQuery: ... + __sub__ = except_ + def __iter__(self): ... + def prefetch(self, *subqueries, prefetch_type: int = ...): ... + def with_related(self, *loads: Load | ForeignKeyField[Any] | BackrefAccessor) -> Self: ... + def iterator(self, database: _DatabaseType | None = ...) -> Iterator[Any]: ... + def get(self, database: _DatabaseType | None = None): ... + def get_or_none(self, database: _DatabaseType | None = None): ... + def group_by(self, *columns) -> Self: ... + +class ModelCompoundSelectQuery(BaseModelSelect, CompoundSelectQuery): # type: ignore[misc] + model: Incomplete + def __init__(self, model, *args, **kwargs) -> None: ... + +class ModelSelect(BaseModelSelect, Select, Generic[_M]): # type: ignore[misc] + model: type[_M] + def __init__(self, model, fields_or_models, is_default: bool = False) -> None: ... + def __iter__(self) -> Iterator[_M]: ... + def get(self, database: _DatabaseType | None = None) -> _M: ... + def get_or_none(self, database: _DatabaseType | None = None) -> _M | None: ... + def clone(self) -> Self: ... + def select(self, *fields_or_models) -> ModelSelect[_M]: ... + def select_extend(self, *columns) -> Self: ... + def switch(self, ctx=None) -> Self: ... + def join(self, dest, join_type="INNER JOIN", on=None, src=None, attr=None) -> Self: ... # type: ignore[override] + def left_outer_join(self, dest, on=None, src=None, attr=None) -> Self: ... # type: ignore[override] + def join_from(self, src, dest, join_type="INNER JOIN", on=None, attr=None) -> Self: ... + def ensure_join(self, lm, rm, on=None, **join_kwargs): ... + def convert_dict_to_node(self, qdict) -> tuple[list[Incomplete], list[Incomplete]]: ... + def filter(self, *args, **kwargs) -> Self: ... + def create_table(self, name, safe: bool = True, **meta): ... + def __sql_selection__(self, ctx, is_subquery: bool = False): ... + +class NoopModelSelect(ModelSelect[_M]): + def __sql__(self, ctx): ... + +class _ModelWriteQueryHelper(_ModelQueryHelper): + model: Incomplete + def __init__(self, model, *args, **kwargs) -> None: ... + def returning(self, *returning) -> Self: ... + +class ModelUpdate(_ModelWriteQueryHelper, Update): ... # type: ignore[misc] + +class ModelInsert(_ModelWriteQueryHelper, Insert): # type: ignore[misc] + default_row_type: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def returning(self, *returning) -> Self: ... + def get_default_data(self): ... + def get_default_columns(self): ... + +class ModelDelete(_ModelWriteQueryHelper, Delete): ... # type: ignore[misc] + +class ManyToManyQuery(ModelSelect[_M]): + def __init__(self, instance, accessor, rel, *args, **kwargs) -> None: ... + def add(self, value, clear_existing: bool = False) -> None: ... + def remove(self, value): ... + def clear(self): ... + +class BaseModelCursorWrapper(DictCursorWrapper): + model: Incomplete + select: Incomplete + ncols: int + columns: list[str] + converters: list[Incomplete] + fields: list[Incomplete] + no_convert: list[int] + convert: list[int] + def __init__(self, cursor, model, columns) -> None: ... + def initialize(self) -> None: ... + def process_row(self, row): ... + +class ModelDictCursorWrapper(BaseModelCursorWrapper): + valid_identifiers: bool + unique_columns: list[str] + def initialize(self) -> None: ... + def process_row(self, row) -> dict[str, Incomplete]: ... + +class ModelTupleCursorWrapper(BaseModelCursorWrapper): + constructor: Incomplete + def process_row(self, row) -> tuple[Incomplete, ...]: ... # type: ignore[override] + +class ModelNamedTupleCursorWrapper(ModelTupleCursorWrapper): + impl: Incomplete + constructor: Incomplete + def initialize(self) -> None: ... + +class ModelObjectCursorWrapper(ModelDictCursorWrapper): + valid_identifiers: bool + constructor: Incomplete + is_model: Incomplete + def __init__(self, cursor, model, select, constructor) -> None: ... + def process_row(self, row): ... + +class ModelCursorWrapper(BaseModelCursorWrapper): + from_list: Incomplete + joins: Incomplete + def __init__(self, cursor, model, select, from_list, joins) -> None: ... + key_to_constructor: dict[Incomplete, tuple[Incomplete, Incomplete]] + src_to_dest: list[tuple[Incomplete, Incomplete, Incomplete, bool, Incomplete, bool]] + column_keys: list[Incomplete] + def initialize(self) -> None: ... + def process_row(self, row): ... + +@type_check_only +class _PrefetchQuery(NamedTuple): + query: Incomplete + fields: Incomplete + is_backref: bool + rel_models: Incomplete + field_to_name: Incomplete + model: Incomplete + +class PrefetchQuery(_PrefetchQuery): + def __new__(cls, query, fields=None, is_backref: bool | None = None, rel_models=None, field_to_name=None) -> Self: ... + def populate_instance(self, instance, id_map) -> None: ... + def store_instance(self, instance, id_map) -> None: ... + +def prefetch(sq, *subqueries, prefetch_type: int = ...): ... + +class Load(Node): + def __init__( + self, + rel: ForeignKeyField[Any] | BackrefAccessor, + query: ModelSelect[Any] | None = ..., + strategy: int = ..., + per_parent: int | None = ..., + ) -> None: ... + def then(self, *children: Load | ForeignKeyField[Any] | BackrefAccessor) -> Self: ... + +__all__ = [ + "AnyField", + "AsIs", + "AutoField", + "BareField", + "BigAutoField", + "BigBitField", + "BigIntegerField", + "BinaryUUIDField", + "BitField", + "BlobField", + "BooleanField", + "Case", + "Cast", + "CharField", + "Check", + "chunked", + "Column", + "CompositeKey", + "Context", + "Database", + "DatabaseError", + "DatabaseProxy", + "DataError", + "DateField", + "DateTimeField", + "DecimalField", + "Default", + "DeferredForeignKey", + "DeferredThroughModel", + "DJANGO_MAP", + "DoesNotExist", + "DoubleField", + "DQ", + "Entity", + "EXCLUDED", + "Field", + "FixedCharField", + "FloatField", + "fn", + "ForeignKeyField", + "IdentityField", + "ImproperlyConfigured", + "Index", + "IntegerField", + "IntegrityError", + "InterfaceError", + "InternalError", + "IPField", + "JOIN", + "JSONField", + "Load", + "ManyToManyField", + "Model", + "ModelIndex", + "MySQLDatabase", + "NotSupportedError", + "OP", + "OperationalError", + "PostgresqlDatabase", + "PrimaryKeyField", + "prefetch", + "PREFETCH_TYPE", + "ProgrammingError", + "Proxy", + "QualifiedNames", + "QueryEvent", + "SchemaManager", + "SmallIntegerField", + "Select", + "SQL", + "SqliteDatabase", + "Table", + "TextField", + "TimeField", + "TimestampField", + "Tuple", + "UUIDField", + "Value", + "ValuesList", + "Window", +] diff --git a/stubs/beautifulsoup4/@tests/stubtest_allowlist.txt b/stubs/peewee/playhouse/__init__.pyi similarity index 100% rename from stubs/beautifulsoup4/@tests/stubtest_allowlist.txt rename to stubs/peewee/playhouse/__init__.pyi diff --git a/stubs/peewee/playhouse/flask_utils.pyi b/stubs/peewee/playhouse/flask_utils.pyi new file mode 100644 index 000000000000..a774c4eaa2fc --- /dev/null +++ b/stubs/peewee/playhouse/flask_utils.pyi @@ -0,0 +1,27 @@ +from _typeshed import Unused +from collections.abc import Container +from typing import Any, TypeAlias + +from peewee import Database, ModelBase, Proxy + +# Is actually flask.Flask +_Flask: TypeAlias = Any + +class FlaskDB: + # Omitting undocumented base_model_class on purpose, use FlaskDB.Model instead + database: Database | Proxy + def __init__( + self, + app: _Flask | None = None, + database: Database | Proxy | None = None, + # Is actually type[ModelClass] but stubtest likely confuses with Model property + # https://github.com/python/typeshed/pull/11731#issuecomment-2067694259 + model_class=..., + excluded_routes: Container[str] | None = None, + ) -> None: ... + def init_app(self, app: _Flask) -> None: ... + def get_model_class(self) -> type[ModelBase]: ... + @property + def Model(self) -> type[ModelBase]: ... + def connect_db(self) -> None: ... + def close_db(self, exc: Unused) -> None: ... diff --git a/stubs/pep8-naming/METADATA.toml b/stubs/pep8-naming/METADATA.toml new file mode 100644 index 000000000000..3b73248f1786 --- /dev/null +++ b/stubs/pep8-naming/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.15.*" +upstream-repository = "https://github.com/PyCQA/pep8-naming" diff --git a/stubs/pep8-naming/pep8ext_naming.pyi b/stubs/pep8-naming/pep8ext_naming.pyi new file mode 100644 index 000000000000..758bd4fce074 --- /dev/null +++ b/stubs/pep8-naming/pep8ext_naming.pyi @@ -0,0 +1,163 @@ +import argparse +import ast +import enum +import optparse +from collections import deque +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from typing import Any, Final, Literal +from typing_extensions import Self + +__version__: Final[str] + +CLASS_METHODS: Final[frozenset[Literal["__new__", "__init_subclass__", "__class_getitem__"]]] +METACLASS_BASES: Final[frozenset[Literal["type", "ABCMeta"]]] +METHOD_CONTAINER_NODES: Final[set[ast.AST]] +FUNC_NODES: Final[tuple[type[ast.FunctionDef], type[ast.AsyncFunctionDef]]] + +class BaseASTCheck: + all: list[BaseASTCheck] + codes: tuple[str, ...] + # Per convention, unknown kwargs are passed to the super-class. See there for the types. + def __init_subclass__(cls, **kwargs: Any) -> None: ... + def err(self, node: ast.AST, code: str, **kwargs: str) -> tuple[int, int, str, Self]: ... + +class NameSet(frozenset[str]): + def __new__(cls, iterable: Iterable[str]) -> Self: ... + def __contains__(self, item: object, /) -> bool: ... + +@enum.unique +class FunctionType(enum.Enum): + CLASSMETHOD = "classmethod" + STATICMETHOD = "staticmethod" + FUNCTION = "function" + METHOD = "method" + +class NamingChecker: + name: str + version: str + visitors: Sequence[BaseASTCheck] + decorator_to_type: dict[str, FunctionType] + ignored: NameSet + def __init__(self, tree: ast.AST, filename: str) -> None: ... + @classmethod + def add_options(cls, parser: optparse.OptionParser) -> None: ... + @classmethod + def parse_options(cls, options: argparse.Namespace) -> None: ... + def run(self) -> Generator[tuple[int, int, str, Self]] | tuple[()]: ... + def visit_tree(self, node: ast.AST, parents: deque[ast.AST]) -> Generator[tuple[int, int, str, Self]]: ... + def visit_node(self, node: ast.AST, parents: Sequence[ast.AST]) -> Generator[tuple[int, int, str, Self]]: ... + def tag_class_functions(self, cls_node: ast.ClassDef) -> None: ... + def set_function_nodes_types( + self, nodes: Iterator[ast.AST], ismetaclass: bool, late_decoration: dict[str, FunctionType] + ) -> None: ... + @classmethod + def find_decorator_name(cls, d: ast.Expr) -> str: ... + @staticmethod + def find_global_defs(func_def_node: ast.AST) -> None: ... + +class ClassNameCheck(BaseASTCheck): + codes: tuple[Literal["N801"], Literal["N818"]] + N801: Final[str] + N818: Final[str] + @classmethod + def get_classdef(cls, name: str, parents: Sequence[ast.AST]) -> ast.ClassDef | None: ... + @classmethod + def superclass_names(cls, name: str, parents: Sequence[ast.AST], _names: set[str] | None = None) -> set[str]: ... + def visit_classdef( + self, node: ast.ClassDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class FunctionNameCheck(BaseASTCheck): + codes: tuple[Literal["N802"], Literal["N807"]] + N802: Final[str] + N807: Final[str] + @staticmethod + def has_override_decorator(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool: ... + def visit_functiondef( + self, node: ast.FunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncfunctiondef( + self, node: ast.AsyncFunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class FunctionArgNamesCheck(BaseASTCheck): + codes: tuple[Literal["N803"], Literal["N804"], Literal["N805"]] + N803: Final[str] + N804: Final[str] + N805: Final[str] + def visit_functiondef( + self, node: ast.FunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncfunctiondef( + self, node: ast.AsyncFunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class ImportAsCheck(BaseASTCheck): + codes: tuple[Literal["N811"], Literal["N812"], Literal["N813"], Literal["N814"], Literal["N817"]] + N811: Final[str] + N812: Final[str] + N813: Final[str] + N814: Final[str] + N817: Final[str] + def visit_importfrom( + self, node: ast.ImportFrom, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_import( + self, node: ast.Import, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class VariablesCheck(BaseASTCheck): + codes: tuple[Literal["N806"], Literal["N815"], Literal["N816"]] + N806: Final[str] + N815: Final[str] + N816: Final[str] + @staticmethod + def is_namedtupe(node_value: ast.AST) -> bool: ... + def visit_assign( + self, node: ast.Assign, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_namedexpr( + self, node: ast.NamedExpr, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_annassign( + self, node: ast.AnnAssign, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_with( + self, node: ast.With, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncwith( + self, node: ast.AsyncWith, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_for(self, node: ast.For, parents: Sequence[ast.AST], ignored: NameSet) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncfor( + self, node: ast.AsyncFor, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_excepthandler( + self, node: ast.ExceptHandler, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_generatorexp( + self, node: ast.GeneratorExp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_listcomp( + self, node: ast.ListComp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_dictcomp( + self, node: ast.DictComp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_setcomp( + self, node: ast.SetComp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + @staticmethod + def global_variable_check(name: str) -> Literal["N816"] | None: ... + @staticmethod + def class_variable_check(name: str) -> Literal["N815"] | None: ... + @staticmethod + def function_variable_check(func: Callable[..., object], var_name: str) -> Literal["N806"] | None: ... + +class TypeVarNameCheck(BaseASTCheck): + N808: Final[str] + def visit_module( + self, node: ast.Module, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +def is_mixed_case(name: str) -> bool: ... diff --git a/stubs/pexpect/@tests/stubtest_allowlist.txt b/stubs/pexpect/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c65fb9a6e62e --- /dev/null +++ b/stubs/pexpect/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# python2 shim +pexpect.utils.InterruptedError diff --git a/stubs/pexpect/METADATA.toml b/stubs/pexpect/METADATA.toml new file mode 100644 index 000000000000..6e7cab5fa1ad --- /dev/null +++ b/stubs/pexpect/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.9.*" +upstream-repository = "https://github.com/pexpect/pexpect" diff --git a/stubs/pexpect/pexpect/ANSI.pyi b/stubs/pexpect/pexpect/ANSI.pyi new file mode 100644 index 000000000000..4185ba6fa245 --- /dev/null +++ b/stubs/pexpect/pexpect/ANSI.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete + +from . import screen + +def DoEmit(fsm) -> None: ... +def DoStartNumber(fsm) -> None: ... +def DoBuildNumber(fsm) -> None: ... +def DoBackOne(fsm) -> None: ... +def DoBack(fsm) -> None: ... +def DoDownOne(fsm) -> None: ... +def DoDown(fsm) -> None: ... +def DoForwardOne(fsm) -> None: ... +def DoForward(fsm) -> None: ... +def DoUpReverse(fsm) -> None: ... +def DoUpOne(fsm) -> None: ... +def DoUp(fsm) -> None: ... +def DoHome(fsm) -> None: ... +def DoHomeOrigin(fsm) -> None: ... +def DoEraseDown(fsm) -> None: ... +def DoErase(fsm) -> None: ... +def DoEraseEndOfLine(fsm) -> None: ... +def DoEraseLine(fsm) -> None: ... +def DoEnableScroll(fsm) -> None: ... +def DoCursorSave(fsm) -> None: ... +def DoCursorRestore(fsm) -> None: ... +def DoScrollRegion(fsm) -> None: ... +def DoMode(fsm) -> None: ... +def DoLog(fsm) -> None: ... + +class term(screen.screen): + def __init__(self, r: int = 24, c: int = 80, *args, **kwargs) -> None: ... + +class ANSI(term): + state: Incomplete + def __init__(self, r: int = 24, c: int = 80, *args, **kwargs) -> None: ... + def process(self, c) -> None: ... + def process_list(self, l) -> None: ... + def write(self, s) -> None: ... + def flush(self) -> None: ... + def write_ch(self, ch) -> None: ... + def do_sgr(self, fsm) -> None: ... + def do_decsca(self, fsm) -> None: ... + def do_modecrap(self, fsm) -> None: ... diff --git a/stubs/pexpect/pexpect/FSM.pyi b/stubs/pexpect/pexpect/FSM.pyi new file mode 100644 index 000000000000..abc0cb037638 --- /dev/null +++ b/stubs/pexpect/pexpect/FSM.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete + +class ExceptionFSM(Exception): + value: Incomplete + def __init__(self, value) -> None: ... + +class FSM: + state_transitions: Incomplete + state_transitions_any: Incomplete + default_transition: Incomplete + input_symbol: Incomplete + initial_state: Incomplete + current_state: Incomplete + next_state: Incomplete + action: Incomplete + memory: Incomplete + def __init__(self, initial_state, memory=None) -> None: ... + def reset(self) -> None: ... + def add_transition(self, input_symbol, state, action=None, next_state=None) -> None: ... + def add_transition_list(self, list_input_symbols, state, action=None, next_state=None) -> None: ... + def add_transition_any(self, state, action=None, next_state=None) -> None: ... + def set_default_transition(self, action, next_state) -> None: ... + def get_transition(self, input_symbol, state): ... + def process(self, input_symbol) -> None: ... + def process_list(self, input_symbols) -> None: ... + +PY3: Incomplete + +def BeginBuildNumber(fsm) -> None: ... +def BuildNumber(fsm) -> None: ... +def EndBuildNumber(fsm) -> None: ... +def DoOperator(fsm) -> None: ... +def DoEqual(fsm) -> None: ... +def Error(fsm) -> None: ... +def main() -> None: ... diff --git a/stubs/pexpect/pexpect/__init__.pyi b/stubs/pexpect/pexpect/__init__.pyi new file mode 100644 index 000000000000..bd7f1ddac270 --- /dev/null +++ b/stubs/pexpect/pexpect/__init__.pyi @@ -0,0 +1,20 @@ +from .exceptions import EOF as EOF, TIMEOUT as TIMEOUT, ExceptionPexpect as ExceptionPexpect +from .pty_spawn import spawn as spawn, spawnu as spawnu +from .run import run as run, runu as runu +from .utils import split_command_line as split_command_line, which as which + +__version__: str +__revision__: str +__all__ = [ + "ExceptionPexpect", + "EOF", + "TIMEOUT", + "spawn", + "spawnu", + "run", + "runu", + "which", + "split_command_line", + "__version__", + "__revision__", +] diff --git a/stubs/pexpect/pexpect/_async.pyi b/stubs/pexpect/pexpect/_async.pyi new file mode 100644 index 000000000000..18daf19911dd --- /dev/null +++ b/stubs/pexpect/pexpect/_async.pyi @@ -0,0 +1,19 @@ +import asyncio +from typing import AnyStr, Generic + +from .expect import Expecter + +async def expect_async(expecter: Expecter[AnyStr], timeout: float | None = None) -> int: ... +async def repl_run_command_async(repl, cmdlines, timeout: float | None = -1): ... + +class PatternWaiter(asyncio.Protocol, Generic[AnyStr]): + transport: asyncio.ReadTransport | None + expecter: Expecter[AnyStr] + fut: asyncio.Future[int] + def set_expecter(self, expecter: Expecter[AnyStr]) -> None: ... + def found(self, result: int) -> None: ... + def error(self, exc: BaseException | type[BaseException]) -> None: ... + def connection_made(self, transport: asyncio.BaseTransport) -> None: ... + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> None: ... + def connection_lost(self, exc: BaseException | type[BaseException] | None) -> None: ... diff --git a/stubs/pexpect/pexpect/exceptions.pyi b/stubs/pexpect/pexpect/exceptions.pyi new file mode 100644 index 000000000000..5dc1790c7f20 --- /dev/null +++ b/stubs/pexpect/pexpect/exceptions.pyi @@ -0,0 +1,6 @@ +class ExceptionPexpect(Exception): + def __init__(self, value: str) -> None: ... + def get_trace(self): ... + +class EOF(ExceptionPexpect): ... +class TIMEOUT(ExceptionPexpect): ... diff --git a/stubs/pexpect/pexpect/expect.pyi b/stubs/pexpect/pexpect/expect.pyi new file mode 100644 index 000000000000..ec9c29b52f17 --- /dev/null +++ b/stubs/pexpect/pexpect/expect.pyi @@ -0,0 +1,38 @@ +import re +from collections.abc import Iterable +from typing import AnyStr, Generic + +from .spawnbase import SpawnBase, _CompiledRePattern, _CompiledStringPattern, _Searcher + +class searcher_string(Generic[AnyStr]): + eof_index: int + timeout_index: int + longest_string: int + def __init__(self, strings: Iterable[_CompiledStringPattern[AnyStr]]) -> None: ... + match: AnyStr + start: int + end: int + def search(self, buffer: AnyStr, freshlen: int, searchwindowsize: int | None = None): ... + +class searcher_re(Generic[AnyStr]): + eof_index: int + timeout_index: int + def __init__(self, patterns: Iterable[_CompiledRePattern[AnyStr]]) -> None: ... + match: re.Match[AnyStr] + start: int + end: int + def search(self, buffer: AnyStr, freshlen: int, searchwindowsize: int | None = None): ... + +class Expecter(Generic[AnyStr]): + spawn: SpawnBase[AnyStr] + searcher: _Searcher[AnyStr] + searchwindowsize: int | None + lookback: _Searcher[AnyStr] | int | None + def __init__(self, spawn: SpawnBase[AnyStr], searcher: _Searcher[AnyStr], searchwindowsize: int | None = -1) -> None: ... + def do_search(self, window: AnyStr, freshlen: int) -> int: ... + def existing_data(self) -> int: ... + def new_data(self, data: AnyStr) -> int: ... + def eof(self, err: object = None) -> int: ... + def timeout(self, err: object = None) -> int: ... + def errored(self) -> None: ... + def expect_loop(self, timeout: float | None = -1) -> int: ... diff --git a/stubs/pexpect/pexpect/fdpexpect.pyi b/stubs/pexpect/pexpect/fdpexpect.pyi new file mode 100644 index 000000000000..31a6a0a71ac3 --- /dev/null +++ b/stubs/pexpect/pexpect/fdpexpect.pyi @@ -0,0 +1,36 @@ +from _typeshed import FileDescriptorLike +from collections.abc import Iterable +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +__all__ = ["fdspawn"] + +class fdspawn(SpawnBase[AnyStr]): + args: None + command: None + child_fd: int + own_fd: bool + closed: bool + name: str + use_poll: bool + def __init__( + self, + fd: FileDescriptorLike, + args: None = None, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + use_poll: bool = False, + ) -> None: ... + def close(self) -> None: ... + def isalive(self) -> bool: ... + def terminate(self, force: bool = False) -> None: ... + def send(self, s: str | bytes) -> int: ... + def sendline(self, s: str | bytes) -> int: ... + def write(self, s) -> None: ... + def writelines(self, sequence: Iterable[str | bytes]) -> None: ... + def read_nonblocking(self, size: int = 1, timeout: float | None = -1) -> AnyStr: ... diff --git a/stubs/pexpect/pexpect/popen_spawn.pyi b/stubs/pexpect/pexpect/popen_spawn.pyi new file mode 100644 index 000000000000..601595a9d00c --- /dev/null +++ b/stubs/pexpect/pexpect/popen_spawn.pyi @@ -0,0 +1,33 @@ +import subprocess +from _typeshed import StrOrBytesPath +from collections.abc import Callable +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +class PopenSpawn(SpawnBase[AnyStr]): + proc: subprocess.Popen[AnyStr] + closed: bool + def __init__( + self, + cmd, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + preexec_fn: Callable[[], None] | None = None, + ) -> None: ... + flag_eof: bool + def read_nonblocking(self, size, timeout): ... # type: ignore[override] + def write(self, s) -> None: ... + def writelines(self, sequence) -> None: ... + def send(self, s): ... + def sendline(self, s: str = ""): ... + terminated: bool + def wait(self): ... + def kill(self, sig) -> None: ... + def sendeof(self) -> None: ... diff --git a/stubs/pexpect/pexpect/pty_spawn.pyi b/stubs/pexpect/pexpect/pty_spawn.pyi new file mode 100644 index 000000000000..879915556e35 --- /dev/null +++ b/stubs/pexpect/pexpect/pty_spawn.pyi @@ -0,0 +1,96 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Mapping +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +PY3: bool + +class spawn(SpawnBase[AnyStr]): + use_native_pty_fork: bool + STDIN_FILENO: int + STDOUT_FILENO: int + STDERR_FILENO: int + str_last_chars: int + cwd: FileDescriptorOrPath | None + env: Mapping[str, str] | None + echo: bool + ignore_sighup: bool + command: str + args: list[str] + name: str + use_poll: bool + def __init__( + self, + command: str, + args: list[str] = [], + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + ignore_sighup: bool = False, + echo: bool = True, + preexec_fn: Callable[[], None] | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + dimensions: tuple[int, int] | None = None, + use_poll: bool = False, + ) -> None: ... + child_fd: int + closed: bool + def close(self, force: bool = True) -> None: ... + def isatty(self) -> bool: ... + def waitnoecho(self, timeout: float | None = -1) -> None: ... + def getecho(self) -> bool: ... + def setecho(self, state: bool) -> None: ... + def read_nonblocking(self, size: int = 1, timeout: float | None = -1) -> AnyStr: ... + def write(self, s: str | bytes) -> None: ... + def writelines(self, sequence: list[str | bytes]) -> None: ... + def send(self, s: str | bytes) -> int: ... + def sendline(self, s: str | bytes = "") -> int: ... + def sendcontrol(self, char: str) -> int: ... + def sendeof(self) -> None: ... + def sendintr(self) -> None: ... + + @property + def flag_eof(self) -> bool: ... + @flag_eof.setter + def flag_eof(self, value: bool) -> None: ... + + def eof(self) -> bool: ... + def terminate(self, force: bool = False) -> bool: ... + status: int | None + exitstatus: int | None + signalstatus: int | None + terminated: bool + def wait(self) -> int: ... + def isalive(self) -> bool: ... + def kill(self, sig: int) -> None: ... + def getwinsize(self) -> tuple[int, int]: ... + def setwinsize(self, rows, cols) -> None: ... + def interact( + self, + escape_character="\x1d", + input_filter: Callable[[AnyStr], AnyStr] | None = None, + output_filter: Callable[[AnyStr], AnyStr] | None = None, + ) -> None: ... + +def spawnu( + command: str, + args: list[str] = [], + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + ignore_sighup: bool = False, + echo: bool = True, + preexec_fn: Callable[[], None] | None = None, + encoding: str | None = "utf-8", + codec_errors: str = "strict", + dimensions: tuple[int, int] | None = None, + use_poll: bool = False, +) -> spawn[str]: ... diff --git a/stubs/pexpect/pexpect/pxssh.pyi b/stubs/pexpect/pexpect/pxssh.pyi new file mode 100644 index 000000000000..2904e0ab628b --- /dev/null +++ b/stubs/pexpect/pexpect/pxssh.pyi @@ -0,0 +1,66 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Mapping +from typing import AnyStr, Literal + +from .exceptions import ExceptionPexpect +from .pty_spawn import spawn +from .spawnbase import _Logfile + +__all__ = ["ExceptionPxssh", "pxssh"] + +class ExceptionPxssh(ExceptionPexpect): ... + +class pxssh(spawn[AnyStr]): + name: str + UNIQUE_PROMPT: str + PROMPT: str + PROMPT_SET_SH: str + PROMPT_SET_CSH: str + PROMPT_SET_ZSH: str + SSH_OPTS: str + force_password: bool + debug_command_string: bool + options: dict[str, str] + def __init__( + self, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + ignore_sighup: bool = True, + echo: bool = True, + options: dict[str, str] = {}, + encoding: str | None = None, + codec_errors: str = "strict", + debug_command_string: bool = False, + use_poll: bool = False, + ) -> None: ... + def levenshtein_distance(self, a, b): ... + def try_read_prompt(self, timeout_multiplier): ... + def sync_original_prompt(self, sync_multiplier: float = 1.0): ... + def login( + self, + server, + username: str | None = None, + password: str = "", + terminal_type: str = "ansi", + original_prompt: str = "[#$]", + login_timeout: float | None = 10, + port: int | None = None, + auto_prompt_reset: bool = True, + ssh_key: FileDescriptorOrPath | Literal[True] | None = None, + quiet: bool = True, + sync_multiplier: int = 1, + check_local_ip: bool = True, + password_regex: str = "(?i)(?:password:)|(?:passphrase for key)", + ssh_tunnels: dict[str, list[str | int]] = {}, + spawn_local_ssh: bool = True, + sync_original_prompt: bool = True, + ssh_config: FileDescriptorOrPath | None = None, + cmd: str = "ssh", + ): ... + def logout(self) -> None: ... + def prompt(self, timeout: float | None = -1): ... + def set_unique_prompt(self): ... diff --git a/stubs/pexpect/pexpect/replwrap.pyi b/stubs/pexpect/pexpect/replwrap.pyi new file mode 100644 index 000000000000..1ef0a541ff8c --- /dev/null +++ b/stubs/pexpect/pexpect/replwrap.pyi @@ -0,0 +1,27 @@ +import sys +from _typeshed import Incomplete + +PY3: Incomplete +basestring = str +PEXPECT_PROMPT: str +PEXPECT_CONTINUATION_PROMPT: str + +class REPLWrapper: + child: Incomplete + prompt: Incomplete + continuation_prompt: Incomplete + def __init__( + self, + cmd_or_spawn, + orig_prompt, + prompt_change, + new_prompt="[PEXPECT_PROMPT>", + continuation_prompt="[PEXPECT_PROMPT+", + extra_init_cmd=None, + ) -> None: ... + def set_prompt(self, orig_prompt, prompt_change) -> None: ... + def run_command(self, command, timeout: float | None = -1, async_: bool = False): ... + +def python(command: str = sys.executable): ... +def bash(command: str = "bash"): ... +def zsh(command: str = "zsh", args=("--no-rcs", "-V", "+Z")): ... diff --git a/stubs/pexpect/pexpect/run.pyi b/stubs/pexpect/pexpect/run.pyi new file mode 100644 index 000000000000..b3b0a0b546ad --- /dev/null +++ b/stubs/pexpect/pexpect/run.pyi @@ -0,0 +1,28 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Mapping +from typing import AnyStr + +from .spawnbase import _InputRePattern, _Logfile + +def run( + command: str, + timeout: float | None = 30, + withexitstatus: bool = False, + events: list[tuple[_InputRePattern, AnyStr]] | dict[_InputRePattern, AnyStr] | None = None, + extra_args: None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + **kwargs, +) -> AnyStr | tuple[AnyStr, int]: ... +def runu( + command: str, + timeout: float | None = 30, + withexitstatus: bool = False, + events: list[tuple[_InputRePattern, AnyStr]] | dict[_InputRePattern, AnyStr] | None = None, + extra_args: None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + **kwargs, +) -> AnyStr | tuple[AnyStr, int]: ... diff --git a/stubs/pexpect/pexpect/screen.pyi b/stubs/pexpect/pexpect/screen.pyi new file mode 100644 index 000000000000..dffc81008b60 --- /dev/null +++ b/stubs/pexpect/pexpect/screen.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete + +NUL: int +ENQ: int +BEL: int +BS: int +HT: int +LF: int +VT: int +FF: int +CR: int +SO: int +SI: int +XON: int +XOFF: int +CAN: int +SUB: int +ESC: int +DEL: int +SPACE: str +PY3: Incomplete +unicode = str + +def constrain(n, min, max): ... + +class screen: + rows: Incomplete + cols: Incomplete + encoding: Incomplete + encoding_errors: Incomplete + decoder: Incomplete + cur_r: int + cur_c: int + cur_saved_r: int + cur_saved_c: int + scroll_row_start: int + scroll_row_end: Incomplete + w: Incomplete + def __init__(self, r: int = 24, c: int = 80, encoding: str = "latin-1", encoding_errors: str = "replace") -> None: ... + def dump(self): ... + def pretty(self): ... + def fill(self, ch=" ") -> None: ... + def fill_region(self, rs, cs, re, ce, ch=" ") -> None: ... + def cr(self) -> None: ... + def lf(self) -> None: ... + def crlf(self) -> None: ... + def newline(self) -> None: ... + def put_abs(self, r, c, ch) -> None: ... + def put(self, ch) -> None: ... + def insert_abs(self, r, c, ch) -> None: ... + def insert(self, ch) -> None: ... + def get_abs(self, r, c): ... + def get(self) -> None: ... + def get_region(self, rs, cs, re, ce): ... + def cursor_constrain(self) -> None: ... + def cursor_home(self, r: int = 1, c: int = 1) -> None: ... + def cursor_back(self, count: int = 1) -> None: ... + def cursor_down(self, count: int = 1) -> None: ... + def cursor_forward(self, count: int = 1) -> None: ... + def cursor_up(self, count: int = 1) -> None: ... + def cursor_up_reverse(self) -> None: ... + def cursor_force_position(self, r, c) -> None: ... + def cursor_save(self) -> None: ... + def cursor_unsave(self) -> None: ... + def cursor_save_attrs(self) -> None: ... + def cursor_restore_attrs(self) -> None: ... + def scroll_constrain(self) -> None: ... + def scroll_screen(self) -> None: ... + def scroll_screen_rows(self, rs, re) -> None: ... + def scroll_down(self) -> None: ... + def scroll_up(self) -> None: ... + def erase_end_of_line(self) -> None: ... + def erase_start_of_line(self) -> None: ... + def erase_line(self) -> None: ... + def erase_down(self) -> None: ... + def erase_up(self) -> None: ... + def erase_screen(self) -> None: ... + def set_tab(self) -> None: ... + def clear_tab(self) -> None: ... + def clear_all_tabs(self) -> None: ... diff --git a/stubs/pexpect/pexpect/socket_pexpect.pyi b/stubs/pexpect/pexpect/socket_pexpect.pyi new file mode 100644 index 000000000000..f3c8d42d0b56 --- /dev/null +++ b/stubs/pexpect/pexpect/socket_pexpect.pyi @@ -0,0 +1,35 @@ +from collections.abc import Iterable +from socket import socket as Socket +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +__all__ = ["SocketSpawn"] + +class SocketSpawn(SpawnBase[AnyStr]): + args: None + command: None + socket: Socket + child_fd: int + closed: bool + name: str + use_poll: bool + def __init__( + self, + socket: Socket, + args: None = None, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + use_poll: bool = False, + ) -> None: ... + def close(self) -> None: ... + def isalive(self) -> bool: ... + def send(self, s: str | bytes) -> int: ... + def sendline(self, s: str | bytes) -> int: ... + def write(self, s: str | bytes) -> None: ... + def writelines(self, sequence: Iterable[str | bytes]) -> None: ... + def read_nonblocking(self, size: int = 1, timeout: float | None = -1) -> AnyStr: ... diff --git a/stubs/pexpect/pexpect/spawnbase.pyi b/stubs/pexpect/pexpect/spawnbase.pyi new file mode 100644 index 000000000000..d839fddd57f9 --- /dev/null +++ b/stubs/pexpect/pexpect/spawnbase.pyi @@ -0,0 +1,152 @@ +from asyncio import ReadTransport +from collections.abc import Awaitable, Callable, Iterable +from re import Match, Pattern +from typing import IO, AnyStr, Generic, Literal, Protocol, TextIO, TypeAlias, overload, type_check_only + +from ._async import PatternWaiter +from .exceptions import EOF, TIMEOUT +from .expect import searcher_re, searcher_string + +PY3: bool +text_type: type + +class _NullCoder: + @staticmethod + def encode(b: str, final: bool = False): ... + @staticmethod + def decode(b: str, final: bool = False): ... + +@type_check_only +class _Logfile(Protocol): + def write(self, s, /) -> object: ... + def flush(self) -> object: ... + +_ErrorPattern: TypeAlias = type[EOF | TIMEOUT] +_InputStringPattern: TypeAlias = str | bytes | _ErrorPattern +_InputRePattern: TypeAlias = Pattern[str] | Pattern[bytes] | _InputStringPattern +_CompiledStringPattern: TypeAlias = AnyStr | _ErrorPattern +_CompiledRePattern: TypeAlias = Pattern[AnyStr] | _ErrorPattern +_Searcher: TypeAlias = searcher_string[AnyStr] | searcher_re[AnyStr] + +class SpawnBase(Generic[AnyStr]): + encoding: str | None + pid: int | None + flag_eof: bool + stdin: TextIO + stdout: TextIO + stderr: TextIO + searcher: None + ignorecase: bool + before: AnyStr | None + after: _CompiledStringPattern[AnyStr] | None + match: AnyStr | Match[AnyStr] | _ErrorPattern | None + match_index: int | None + terminated: bool + exitstatus: int | None + signalstatus: int | None + status: int | None + child_fd: int + timeout: float | None + delimiter: type[EOF] + logfile: _Logfile | None + logfile_read: _Logfile | None + logfile_send: _Logfile | None + maxread: int + searchwindowsize: int | None + delaybeforesend: float | None + delayafterclose: float + delayafterterminate: float + delayafterread: float | None + softspace: bool + name: str + closed: bool + codec_errors: str + string_type: type[AnyStr] + buffer_type: IO[AnyStr] + crlf: AnyStr + allowed_string_types: tuple[type, ...] + linesep: AnyStr + write_to_stdout: Callable[[AnyStr], int] + async_pw_transport: tuple[PatternWaiter[AnyStr], ReadTransport] | None + def __init__( + self, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + ) -> None: ... + + @property + def buffer(self) -> AnyStr: ... + @buffer.setter + def buffer(self, value: AnyStr) -> None: ... + + def read_nonblocking(self, size: int = 1, timeout: float | None = None) -> AnyStr: ... + def compile_pattern_list(self, patterns: _InputRePattern | list[_InputRePattern]) -> list[_CompiledRePattern[AnyStr]]: ... + + @overload + def expect( + self, + pattern: _InputRePattern | list[_InputRePattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + async_: Literal[False] = False, + ) -> int: ... + @overload + def expect( + self, + pattern: _InputRePattern | list[_InputRePattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + *, + async_: Literal[True], + ) -> Awaitable[int]: ... + + @overload + def expect_list( + self, + pattern_list: list[_CompiledRePattern[AnyStr]], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + async_: Literal[False] = False, + ) -> int: ... + @overload + def expect_list( + self, + pattern_list: list[_CompiledRePattern[AnyStr]], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + *, + async_: Literal[True], + ) -> Awaitable[int]: ... + + @overload + def expect_exact( + self, + pattern_list: _InputStringPattern | Iterable[_InputStringPattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + async_: Literal[False] = False, + ) -> int: ... + @overload + def expect_exact( + self, + pattern_list: _InputStringPattern | Iterable[_InputStringPattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + *, + async_: Literal[True], + ) -> Awaitable[int]: ... + + def expect_loop(self, searcher: _Searcher[AnyStr], timeout: float | None = -1, searchwindowsize: int | None = -1) -> int: ... + def read(self, size: int = -1) -> AnyStr: ... + def readline(self, size: int = -1) -> AnyStr: ... + def __iter__(self): ... + def readlines(self, sizehint: int = -1) -> list[AnyStr]: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def __enter__(self): ... + def __exit__(self, etype, evalue, tb) -> None: ... diff --git a/stubs/pexpect/pexpect/utils.pyi b/stubs/pexpect/pexpect/utils.pyi new file mode 100644 index 000000000000..29fd1ae2b2cd --- /dev/null +++ b/stubs/pexpect/pexpect/utils.pyi @@ -0,0 +1,10 @@ +from collections.abc import Mapping + +InterruptedError: type +string_types: tuple[type, ...] + +def is_executable_file(path): ... +def which(filename, env: Mapping[str, str] | None = None): ... +def split_command_line(command_line): ... +def select_ignore_interrupts(iwtd, owtd, ewtd, timeout: float | None = None): ... +def poll_ignore_interrupts(fds, timeout: float | None = None): ... diff --git a/stubs/pika/@tests/stubtest_allowlist.txt b/stubs/pika/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..260f43d685f2 --- /dev/null +++ b/stubs/pika/@tests/stubtest_allowlist.txt @@ -0,0 +1,43 @@ +# bytes alias for Python 3 compatibility +pika.spec.str + +# Behind a TYPE_CHECKING guard at runtime. +pika.adapters.select_connection.SELECT_ERROR_T +pika.adapters.select_connection.POLLER_PARAMS + +# The implementation has defaults for the arguments that would make the +# created instances unusable, so we require the arguments in the stub. +pika.spec.Queue.DeclareOk.__init__ + +# Type hackary that is unnecessary in the stubs. +pika.connection.ConnectionParameters.DefaultT +pika.connection.ConnectionParameters.T + +# Arguments have a sentinel default, which is not reflected in the stubs. +pika.connection.ConnectionParameters.__init__ + +# These are defined as None, but on initialization are set as callable attributes. +pika.adapters.base_connection._StreamingProtocolShim.connection_made +pika.adapters.base_connection._StreamingProtocolShim.connection_lost +pika.adapters.base_connection._StreamingProtocolShim.eof_received +pika.adapters.base_connection._StreamingProtocolShim.data_received + +# The following methods are not defined directly on this class; +# they are resolved via __getattr__. +pika.adapters.base_connection._StreamingProtocolShim.add_on_close_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_connection_blocked_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_connection_unblocked_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_open_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_open_error_callback +pika.adapters.base_connection._StreamingProtocolShim.channel +pika.adapters.base_connection._StreamingProtocolShim.update_secret +pika.adapters.base_connection._StreamingProtocolShim.close +pika.adapters.base_connection._StreamingProtocolShim.is_closed +pika.adapters.base_connection._StreamingProtocolShim.is_closing +pika.adapters.base_connection._StreamingProtocolShim.is_open +pika.adapters.base_connection._StreamingProtocolShim.basic_nack +pika.adapters.base_connection._StreamingProtocolShim.consumer_cancel_notify +pika.adapters.base_connection._StreamingProtocolShim.exchange_exchange_bindings +pika.adapters.base_connection._StreamingProtocolShim.publisher_confirms +pika.adapters.base_connection._StreamingProtocolShim.create_connection +pika.adapters.base_connection._StreamingProtocolShim.ioloop diff --git a/stubs/pika/METADATA.toml b/stubs/pika/METADATA.toml new file mode 100644 index 000000000000..217f389fcdcd --- /dev/null +++ b/stubs/pika/METADATA.toml @@ -0,0 +1,7 @@ +version = "1.4.*" +upstream-repository = "https://github.com/pika/pika" +stub-distribution = "types-pika-ts" # https://github.com/python/typeshed/issues/9246 +optional-dependencies = ["types-gevent"] + +[tool.stubtest] +stubtest-dependencies = ["gevent", "tornado", "twisted"] diff --git a/stubs/pika/pika/__init__.pyi b/stubs/pika/pika/__init__.pyi new file mode 100644 index 000000000000..17e07499aa60 --- /dev/null +++ b/stubs/pika/pika/__init__.pyi @@ -0,0 +1,29 @@ +from typing import Final + +from pika import adapters as adapters +from pika.adapters import ( + BaseConnection as BaseConnection, + BlockingConnection as BlockingConnection, + SelectConnection as SelectConnection, +) +from pika.adapters.utils.connection_workflow import AMQPConnectionWorkflow as AMQPConnectionWorkflow +from pika.connection import ConnectionParameters as ConnectionParameters, SSLOptions as SSLOptions, URLParameters as URLParameters +from pika.credentials import PlainCredentials as PlainCredentials +from pika.delivery_mode import DeliveryMode as DeliveryMode +from pika.spec import BasicProperties as BasicProperties + +__version__: Final[str] + +__all__ = [ + "adapters", + "AMQPConnectionWorkflow", + "BaseConnection", + "BasicProperties", + "BlockingConnection", + "ConnectionParameters", + "DeliveryMode", + "PlainCredentials", + "SelectConnection", + "SSLOptions", + "URLParameters", +] diff --git a/stubs/pika/pika/adapters/__init__.pyi b/stubs/pika/pika/adapters/__init__.pyi new file mode 100644 index 000000000000..803376324d51 --- /dev/null +++ b/stubs/pika/pika/adapters/__init__.pyi @@ -0,0 +1,6 @@ +from pika.adapters.asyncio_connection import AsyncioConnection as AsyncioConnection +from pika.adapters.base_connection import BaseConnection as BaseConnection +from pika.adapters.blocking_connection import BlockingConnection as BlockingConnection +from pika.adapters.select_connection import IOLoop as IOLoop, SelectConnection as SelectConnection + +__all__ = ["AsyncioConnection", "BaseConnection", "BlockingConnection", "SelectConnection", "IOLoop"] diff --git a/stubs/pika/pika/adapters/asyncio_connection.pyi b/stubs/pika/pika/adapters/asyncio_connection.pyi new file mode 100644 index 000000000000..b4f5b7d3b656 --- /dev/null +++ b/stubs/pika/pika/adapters/asyncio_connection.pyi @@ -0,0 +1,77 @@ +import asyncio +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing_extensions import Self + +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils import io_services_utils +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import ( + AbstractFileDescriptorServices, + AbstractIOReference, + AbstractIOServices, + AbstractTimerReference, +) +from pika.connection import Parameters + +LOGGER: Logger + +class AsyncioConnection(BaseConnection[asyncio.AbstractEventLoop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: asyncio.AbstractEventLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: asyncio.AbstractEventLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + +class _AsyncioIOServicesAdapter( + io_services_utils.SocketConnectionMixin, + io_services_utils.StreamingConnectionMixin, + AbstractIOServices, + AbstractFileDescriptorServices, +): + def __init__(self, loop: asyncio.AbstractEventLoop | None = None) -> None: ... + def get_native_ioloop(self) -> asyncio.AbstractEventLoop: ... + def close(self) -> None: ... + def run(self) -> None: ... + def stop(self) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], object]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _TimerHandle: ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[[BaseConnection[asyncio.AbstractEventLoop] | BaseException], object], # type: ignore[override] + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... + def set_reader(self, fd: int, on_readable: Callable[[], object]) -> None: ... + def remove_reader(self, fd: int) -> bool: ... + def set_writer(self, fd: int, on_writable: Callable[[], object]) -> None: ... + def remove_writer(self, fd: int) -> bool: ... + +class _TimerHandle(AbstractTimerReference): + def __init__(self, handle: asyncio.Handle) -> None: ... + def cancel(self) -> None: ... + +class _AsyncioIOReference(AbstractIOReference): + def __init__( + self, + future: asyncio.Future[Incomplete], + on_done: Callable[[BaseConnection[asyncio.AbstractEventLoop] | BaseException], object], + ) -> None: ... + def cancel(self) -> bool: ... diff --git a/stubs/pika/pika/adapters/base_connection.pyi b/stubs/pika/pika/adapters/base_connection.pyi new file mode 100644 index 000000000000..2766489ec660 --- /dev/null +++ b/stubs/pika/pika/adapters/base_connection.pyi @@ -0,0 +1,112 @@ +import abc +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Final, Generic, Literal, TypeVar +from typing_extensions import Self + +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol, AbstractStreamTransport +from pika.callback import CallbackManager +from pika.channel import Channel +from pika.connection import Connection, Parameters +from pika.frame import Method +from pika.spec import Connection as SpecConnection + +LOGGER: Logger + +_IOLoop = TypeVar("_IOLoop") + +class BaseConnection(Connection, Generic[_IOLoop], metaclass=abc.ABCMeta): + def __init__( + self, + parameters: Parameters | None, + on_open_callback: Callable[[Self], object] | None, + on_open_error_callback: Callable[[Self, BaseException], object] | None, + on_close_callback: Callable[[Self, BaseException], object] | None, + nbio: AbstractIOServices, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + @abc.abstractmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + @property + def ioloop(self) -> _IOLoop: ... + +class _StreamingProtocolShim(AbstractStreamProtocol, Generic[_IOLoop]): + conn: BaseConnection[_IOLoop] + def __init__(self, conn: BaseConnection[_IOLoop]) -> None: ... + # These are defined as None, but on initialization are set as callable attributes + def connection_made(self, transport: AbstractStreamTransport) -> None: ... + def connection_lost(self, error: BaseException | None) -> None: ... + def eof_received(self) -> bool: ... + def data_received(self, data: bytes) -> None: ... + + # Next attributes are accessed via getattr() from connection.Connection class: + ON_CONNECTION_CLOSED: Final = "_on_connection_closed" + ON_CONNECTION_ERROR: Final = "_on_connection_error" + ON_CONNECTION_OPEN_OK: Final = "_on_connection_open_ok" + CONNECTION_CLOSED: Final = 0 + CONNECTION_INIT: Final = 1 + CONNECTION_PROTOCOL: Final = 2 + CONNECTION_START: Final = 3 + CONNECTION_TUNE: Final = 4 + CONNECTION_OPEN: Final = 5 + CONNECTION_CLOSING: Final = 6 + connection_state: Literal[0, 1, 2, 3, 4, 5, 6] # one of the constants above + params: Parameters + callbacks: CallbackManager + server_capabilities: dict[str, bool] | None + server_properties: dict[str, Incomplete] | None + known_hosts: str | None + def add_on_close_callback(self, callback: Callable[[Self, BaseException], object]) -> None: ... + def add_on_connection_blocked_callback(self, callback: Callable[[Self, Method[SpecConnection.Blocked]], object]) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[Self, Method[SpecConnection.Unblocked]], object] + ) -> None: ... + def add_on_open_callback(self, callback: Callable[[Self], object]) -> None: ... + def add_on_open_error_callback( + self, callback: Callable[[Self, BaseException], object], remove_default: bool = True + ) -> None: ... + def channel( + self, channel_number: int | None = None, on_open_callback: Callable[[Channel], object] | None = None + ) -> Channel: ... + def update_secret( + self, + new_secret: str | bytes, + reason: str | bytes, + callback: Callable[[Method[SpecConnection.UpdateSecretOk]], object] | None = None, + ) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack(self) -> bool: ... + @property + def consumer_cancel_notify(self) -> bool: ... + @property + def exchange_exchange_bindings(self) -> bool: ... + @property + def publisher_confirms(self) -> bool: ... + + # Next attributes are accessed via getattr() from BaseConnection class: + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + @property + def ioloop(self) -> _IOLoop: ... diff --git a/stubs/pika/pika/adapters/blocking_connection.pyi b/stubs/pika/pika/adapters/blocking_connection.pyi new file mode 100644 index 000000000000..5dd25332bacb --- /dev/null +++ b/stubs/pika/pika/adapters/blocking_connection.pyi @@ -0,0 +1,286 @@ +from _typeshed import Incomplete +from collections import deque +from collections.abc import Callable, Generator, Mapping, Sequence +from logging import Logger +from types import TracebackType +from typing import Final, Generic, TypeVar, overload +from typing_extensions import Self + +from pika import connection +from pika.adapters.select_connection import SelectConnection +from pika.channel import Channel +from pika.exchange_type import ExchangeType +from pika.frame import Method +from pika.spec import Basic, BasicProperties, Connection, Exchange, Queue, Tx + +T = TypeVar("T", bound=Connection.Blocked | Connection.Unblocked) # noqa: Y001 + +LOGGER: Logger + +class _IoloopTimerContext: + def __init__(self, duration: float, connection: SelectConnection) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def is_ready(self) -> bool: ... + +class _TimerEvt: + __slots__ = ("timer_id", "_callback") + timer_id: object | None + def __init__(self, callback: Callable[[], None]) -> None: ... + def dispatch(self) -> None: ... + +class _ConnectionBlockedUnblockedEvtBase(Generic[T]): + __slots__ = ("_callback", "_method_frame") + def __init__(self, callback: Callable[[Method[T]], None], method_frame: Method[T]) -> None: ... + def dispatch(self) -> None: ... + +class _ConnectionBlockedEvt(_ConnectionBlockedUnblockedEvtBase[Connection.Blocked]): ... +class _ConnectionUnblockedEvt(_ConnectionBlockedUnblockedEvtBase[Connection.Unblocked]): ... + +class BlockingConnection: + def __init__( + self, + parameters: connection.Parameters | Sequence[connection.Parameters] | None = None, + _impl_class: SelectConnection | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def add_on_connection_blocked_callback( + self, callback: Callable[[connection.Connection, Method[Connection.Blocked]], None] + ) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[connection.Connection, Method[Connection.Unblocked]], None] + ) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> object: ... + def add_callback_threadsafe(self, callback: Callable[..., None]) -> None: ... + def remove_timeout(self, timeout_id: object) -> None: ... + def update_secret(self, new_secret: str, reason: str) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + def process_data_events(self, time_limit: float | None = 0) -> None: ... + def sleep(self, duration: float) -> None: ... + def channel(self, channel_number: int | None = None) -> BlockingChannel: ... + @property + def is_closed(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack_supported(self) -> bool: ... + @property + def consumer_cancel_notify_supported(self) -> bool: ... + @property + def exchange_exchange_bindings_supported(self) -> bool: ... + @property + def publisher_confirms_supported(self) -> bool: ... + basic_nack = basic_nack_supported + consumer_cancel_notify = consumer_cancel_notify_supported + exchange_exchange_bindings = exchange_exchange_bindings_supported + publisher_confirms = publisher_confirms_supported + +class _ChannelPendingEvt: ... + +class _ConsumerDeliveryEvt(_ChannelPendingEvt): + __slots__ = ("method", "properties", "body") + method: Basic.Deliver + properties: BasicProperties + body: bytes + def __init__(self, method: Basic.Deliver, properties: BasicProperties, body: bytes) -> None: ... + +class _ConsumerCancellationEvt(_ChannelPendingEvt): + __slots__ = ("method_frame",) + method_frame: Method[Basic.Cancel] + def __init__(self, method_frame: Method[Basic.Cancel]) -> None: ... + @property + def method(self) -> Basic.Cancel: ... + +class _ReturnedMessageEvt(_ChannelPendingEvt): + __slots__ = ("callback", "channel", "method", "properties", "body") + callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None] + channel: BlockingChannel + method: Basic.Return + properties: BasicProperties + body: bytes + def __init__( + self, + callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None], + channel: BlockingChannel, + method: Basic.Return, + properties: BasicProperties, + body: bytes, + ) -> None: ... + def dispatch(self) -> None: ... + +class ReturnedMessage: + __slots__ = ("method", "properties", "body") + method: Basic.Return + properties: BasicProperties + body: bytes + def __init__(self, method: Basic.Return, properties: BasicProperties, body: bytes) -> None: ... + +class _ConsumerInfo: + __slots__ = ("consumer_tag", "auto_ack", "on_message_callback", "alternate_event_sink", "state") + SETTING_UP: Final = 1 + ACTIVE: Final = 2 + TEARING_DOWN: Final = 3 + CANCELLED_BY_BROKER: Final = 4 + consumer_tag: str + auto_ack: bool + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None] | None + alternate_event_sink: Callable[[_ChannelPendingEvt], None] | None + state: int + + @overload + def __init__( + self, + consumer_tag: str, + auto_ack: bool, + # Only one of them must be non-None: + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None], + alternate_event_sink: None = None, + ) -> None: ... + @overload + def __init__( + self, + consumer_tag: str, + auto_ack: bool, + # Only one of them must be non-None: + on_message_callback: None = None, + alternate_event_sink: Callable[[_ChannelPendingEvt], None] = ..., + ) -> None: ... + + @property + def setting_up(self) -> bool: ... + @property + def active(self) -> bool: ... + @property + def tearing_down(self) -> bool: ... + @property + def cancelled_by_broker(self) -> bool: ... + +class _QueueConsumerGeneratorInfo: + __slots__ = ("params", "consumer_tag", "pending_events") + params: tuple[str, bool, bool] + consumer_tag: str + pending_events: deque[_ChannelPendingEvt] + def __init__(self, params: tuple[str, bool, bool], consumer_tag: str) -> None: ... + +class BlockingChannel: + def __init__(self, channel_impl: Channel, connection: BlockingConnection) -> None: ... + def __int__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + @property + def channel_number(self) -> int: ... + @property + def connection(self) -> BlockingConnection: ... + @property + def is_closed(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def consumer_tags(self) -> list[str]: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown") -> None: ... + def flow(self, active: bool) -> bool: ... + def add_on_cancel_callback(self, callback: Callable[[Method[Basic.Cancel]], None]) -> None: ... + def add_on_return_callback( + self, callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None] + ) -> None: ... + def basic_consume( + self, + queue: str, + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None], + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> str: ... + def basic_cancel(self, consumer_tag: str) -> list[tuple[Basic.Deliver, BasicProperties, bytes]]: ... + def start_consuming(self) -> None: ... + def stop_consuming(self, consumer_tag: str | None = None) -> None: ... + + @overload + def consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + inactivity_timeout: None = None, # different between overloads + consumer_tag: str | None = None, + ) -> Generator[tuple[Basic.Deliver, BasicProperties, bytes]]: ... + @overload + def consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + inactivity_timeout: float = ..., # different between overloads + consumer_tag: str | None = None, + ) -> Generator[tuple[Basic.Deliver, BasicProperties, bytes] | tuple[None, None, None]]: ... + + def get_waiting_message_count(self) -> int: ... + def cancel(self) -> int: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + def basic_get( + self, queue: str, auto_ack: bool = False + ) -> tuple[Basic.GetOk, BasicProperties, bytes] | tuple[None, None, None]: ... + def basic_publish( + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, + ) -> None: ... + def basic_qos(self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False) -> None: ... + def basic_recover(self, requeue: bool = False) -> None: ... + def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None: ... + def confirm_delivery(self) -> None: ... + def exchange_declare( + self, + exchange: str, + exchange_type: ExchangeType | str = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + def exchange_delete(self, exchange: str | None = None, if_unused: bool = False) -> Method[Exchange.DeleteOk]: ... + def exchange_bind( + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None + ) -> Method[Exchange.BindOk]: ... + def exchange_unbind( + self, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + ) -> Method[Exchange.UnbindOk]: ... + def queue_declare( + self, + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Method[Queue.DeclareOk]: ... + def queue_delete(self, queue: str, if_unused: bool = False, if_empty: bool = False) -> Method[Queue.DeleteOk]: ... + def queue_purge(self, queue: str) -> Method[Queue.PurgeOk]: ... + def queue_bind( + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Method[Queue.BindOk]: ... + def queue_unbind( + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Method[Queue.UnbindOk]: ... + def tx_select(self) -> Method[Tx.SelectOk]: ... + def tx_commit(self) -> Method[Tx.CommitOk]: ... + def tx_rollback(self) -> Method[Tx.RollbackOk]: ... diff --git a/stubs/pika/pika/adapters/gevent_connection.pyi b/stubs/pika/pika/adapters/gevent_connection.pyi new file mode 100644 index 000000000000..995579bf4991 --- /dev/null +++ b/stubs/pika/pika/adapters/gevent_connection.pyi @@ -0,0 +1,93 @@ +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Final +from typing_extensions import Self + +from gevent._types import _Loop, _TimerWatcher +from gevent.hub import Hub +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOReference, AbstractIOServices +from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop, SelectorIOServicesAdapter, _SupportsCancel +from pika.connection import Parameters + +LOGGER: Logger + +class GeventConnection(BaseConnection[_Loop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: _Loop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: _Loop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + +class _TSafeCallbackQueue: + def __init__(self) -> None: ... + @property + def fd(self) -> int: ... + def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: ... + def run_next_callback(self) -> None: ... + +class _GeventSelectorIOLoop(AbstractSelectorIOLoop[_TimerWatcher]): + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + def __init__(self, gevent_hub: Hub | None = None) -> None: ... + def close(self) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def add_callback(self, callback: Callable[[], object]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _TimerWatcher: ... + def remove_timeout(self, timeout_handle: _TimerWatcher) -> None: ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fd: int, events: int) -> None: ... + def remove_handler(self, fd: int) -> None: ... + +class _GeventSelectorIOServicesAdapter(SelectorIOServicesAdapter): + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... + +class _GeventIOLoopIOHandle(AbstractIOReference): + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... + +class _GeventAddressResolver: + __slots__ = ("_loop", "_on_done", "_greenlet", "_ga_host", "_ga_port", "_ga_family", "_ga_socktype", "_ga_proto", "_ga_flags") + def __init__( + self, + native_loop: AbstractSelectorIOLoop, + host: str | bytes | None, + port: str | bytes | int | None, + family: int, + socktype: int, + proto: int, + flags: int, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + ) -> None: ... + def start(self) -> None: ... + def cancel(self) -> bool: ... diff --git a/stubs/pika/pika/adapters/select_connection.pyi b/stubs/pika/pika/adapters/select_connection.pyi new file mode 100644 index 000000000000..09d88fde568b --- /dev/null +++ b/stubs/pika/pika/adapters/select_connection.pyi @@ -0,0 +1,118 @@ +import abc +import select +from collections.abc import Callable, Sequence +from logging import Logger +from typing import ClassVar, Final, Literal, TypeAlias, TypedDict +from typing_extensions import Self + +import pika.compat +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices +from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop +from pika.connection import Parameters + +SELECT_ERROR_T: TypeAlias = OSError | IOError | InterruptedError | select.error + +class POLLER_PARAMS(TypedDict): + get_wait_seconds: Callable[[], float | None] + process_timeouts: Callable[[], None] + +LOGGER: Logger +SELECT_TYPE: Literal["epoll", "kqueue", "poll"] | None + +class SelectConnection(BaseConnection[IOLoop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: IOLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + +class _Timeout: + __slots__ = ("deadline", "callback") + deadline: float + callback: Callable[[], None] + def __init__(self, deadline: float, callback: Callable[[], None]) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + +class _Timer: + def __init__(self) -> None: ... + def close(self) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> _Timeout: ... + def remove_timeout(self, timeout: _Timeout) -> None: ... + def get_remaining_interval(self) -> float | None: ... + def process_timeouts(self) -> None: ... + +class PollEvents: + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + HANGUP: Final[int] + +class IOLoop(AbstractSelectorIOLoop[_Timeout]): + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + def __init__(self) -> None: ... + def close(self) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _Timeout: ... + def remove_timeout(self, timeout_handle: _Timeout) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], object]) -> None: ... + add_callback = add_callback_threadsafe + def process_timeouts(self) -> None: ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fd: int, events: int) -> None: ... + def remove_handler(self, fd: int) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def activate_poller(self) -> None: ... + def deactivate_poller(self) -> None: ... + def poll(self) -> None: ... + +class _PollerBase(pika.compat.AbstractBase, metaclass=abc.ABCMeta): + POLL_TIMEOUT_MULT: ClassVar[int] + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... + def close(self) -> None: ... + def wake_threadsafe(self) -> None: ... + def add_handler(self, fileno: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fileno: int, events: int) -> None: ... + def remove_handler(self, fileno: int) -> None: ... + def activate_poller(self) -> None: ... + def deactivate_poller(self) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + @abc.abstractmethod + def poll(self) -> None: ... + +class SelectPoller(_PollerBase): + POLL_TIMEOUT_MULT: ClassVar[int] + def poll(self) -> None: ... + +class KQueuePoller(_PollerBase): + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... + def poll(self) -> None: ... + +class PollPoller(_PollerBase): + POLL_TIMEOUT_MULT: ClassVar[int] + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... + def poll(self) -> None: ... + +class EPollPoller(PollPoller): + POLL_TIMEOUT_MULT: ClassVar[int] diff --git a/stubs/pika/pika/adapters/tornado_connection.pyi b/stubs/pika/pika/adapters/tornado_connection.pyi new file mode 100644 index 000000000000..7a32602a0798 --- /dev/null +++ b/stubs/pika/pika/adapters/tornado_connection.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing import TypeAlias +from typing_extensions import Self + +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices +from pika.connection import Parameters + +_IOLoop: TypeAlias = Incomplete # actual type is tornado.ioloop.IOLoop + +LOGGER: Logger + +class TornadoConnection(BaseConnection[_IOLoop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: _IOLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... diff --git a/stubs/pika/pika/adapters/twisted_connection.pyi b/stubs/pika/pika/adapters/twisted_connection.pyi new file mode 100644 index 000000000000..d7021aafe991 --- /dev/null +++ b/stubs/pika/pika/adapters/twisted_connection.pyi @@ -0,0 +1,163 @@ +# twisted is optional and self-contained in this module. +# We don't want to force it as a dependency but that means we also can't test it with type-checkers given the current setup. + +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import Generic, NamedTuple, TypeVar +from typing_extensions import Self + +from pika import amqp_object +from pika.adapters.utils.nbio_interface import AbstractTimerReference +from pika.channel import Channel +from pika.connection import Connection, ConnectionParameters, Parameters +from pika.exchange_type import ExchangeType +from pika.spec import BasicProperties +from twisted.internet.base import DelayedCall, ReactorBase # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.internet.defer import Deferred, DeferredQueue # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.internet.interfaces import ITransport # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.internet.protocol import Protocol # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.python.failure import Failure # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + +LOGGER: Logger + +_T = TypeVar("_T") + +class ClosableDeferredQueue(DeferredQueue[_T], Generic[_T]): # pyright: ignore[reportUntypedBaseClass] # noqa: Y060 + closed: Failure | BaseException | None + def __init__(self, size: int | None = None, backlog: int | None = None) -> None: ... + # Returns a Deferred with an error if fails. None if success + def put(self, obj: _T) -> Deferred[Failure | BaseException] | None: ... # type: ignore[override] # ignore is not needed for mypy, but is for stubtest + def get(self) -> Deferred[Failure | BaseException | _T]: ... # type: ignore[override] # ignore is not needed for mypy, but is for stubtest + pending: list[_T] + def close(self, reason: Failure | BaseException | None) -> None: ... + +class ReceivedMessage(NamedTuple): + channel: TwistedChannel + method: amqp_object.Method + properties: BasicProperties + body: bytes + +class TwistedChannel: + on_closed: Deferred[Incomplete | Failure | BaseException | None] + def __init__(self, channel: Channel) -> None: ... + @property + def channel_number(self) -> int: ... + @property + def connection(self) -> Connection: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def flow_active(self) -> bool: ... + @property + def consumer_tags(self) -> list[str]: ... + def callback_deferred(self, deferred: Deferred[Incomplete], replies: Iterable[Incomplete]) -> None: ... + def add_on_return_callback(self, callback: Callable[[ReceivedMessage], None]) -> None: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_cancel(self, consumer_tag: str = "") -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Deferred[Incomplete | Failure | BaseException]: ... + def basic_get(self, queue: str, auto_ack: bool = False) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + def basic_publish( + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, + ) -> Deferred[Incomplete | Failure | BaseException]: ... + def basic_qos( + self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_reject(self, delivery_tag: int, requeue: bool = True): ... + def basic_recover(self, requeue: bool = False) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown"): ... + def confirm_delivery(self) -> Deferred[Incomplete | None]: ... + def exchange_bind( + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def exchange_declare( + self, + exchange, + exchange_type: str | ExchangeType = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def exchange_delete( + self, exchange: str | None = None, if_unused: bool = False + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def exchange_unbind( + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def flow(self, active: bool = True) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def open(self): ... + def queue_bind( + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_declare( + self, + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_delete( + self, queue: str, if_unused: bool = False, if_empty: bool = False + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_purge(self, queue: str) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_unbind( + self, queue: str, exchange: str | None, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def tx_commit(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def tx_rollback(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def tx_select(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... + +class _TwistedConnectionAdapter(Connection): + def __init__( + self, + parameters: Parameters | None, + on_open_callback: Callable[[Self], object] | None, + on_open_error_callback: Callable[[Self, BaseException], object] | None, + on_close_callback: Callable[[Self, Exception], object] | None, + custom_reactor: ReactorBase | None = None, + ) -> None: ... + def connection_made(self, transport: ITransport) -> None: ... + def connection_lost(self, error: Exception) -> None: ... + def data_received(self, data: bytes) -> None: ... + +class TwistedProtocolConnection(Protocol): # pyright: ignore[reportUntypedBaseClass] + ready: Deferred[None] | None + closed: Deferred[None] | Failure | BaseException | None + def __init__(self, parameters: ConnectionParameters | None = None, custom_reactor: ReactorBase | None = None) -> None: ... + def channel(self, channel_number: int | None = None) -> Deferred[TwistedChannel]: ... + @property + def is_open(self) -> bool: ... + @property + def is_closed(self) -> bool: ... + def close( + self, reply_code: int = 200, reply_text: str = "Normal shutdown" + ) -> Deferred[None] | Failure | BaseException | None: ... + def dataReceived(self, data: bytes) -> None: ... + def connectionLost(self, reason: Failure | BaseException = ...) -> None: ... + def makeConnection(self, transport: ITransport) -> None: ... + def connectionReady(self) -> TwistedProtocolConnection | Deferred[TwistedProtocolConnection]: ... + +class _TimerHandle(AbstractTimerReference): + def __init__(self, handle: DelayedCall) -> None: ... + def cancel(self) -> None: ... diff --git a/stubs/freezegun/@tests/stubtest_allowlist.txt b/stubs/pika/pika/adapters/utils/__init__.pyi similarity index 100% rename from stubs/freezegun/@tests/stubtest_allowlist.txt rename to stubs/pika/pika/adapters/utils/__init__.pyi diff --git a/stubs/pika/pika/adapters/utils/connection_workflow.pyi b/stubs/pika/pika/adapters/utils/connection_workflow.pyi new file mode 100644 index 000000000000..a2284221bde8 --- /dev/null +++ b/stubs/pika/pika/adapters/utils/connection_workflow.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence + +import pika.compat +import pika.connection +from pika.adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol + +class AMQPConnectorException(Exception): ... +class AMQPConnectorStackTimeout(AMQPConnectorException): ... +class AMQPConnectorAborted(AMQPConnectorException): ... +class AMQPConnectorWrongState(AMQPConnectorException): ... + +class AMQPConnectorPhaseErrorBase(AMQPConnectorException): + exception: BaseException + def __init__(self, exception: BaseException, *args: object) -> None: ... + +class AMQPConnectorSocketConnectError(AMQPConnectorPhaseErrorBase): ... +class AMQPConnectorTransportSetupError(AMQPConnectorPhaseErrorBase): ... +class AMQPConnectorAMQPHandshakeError(AMQPConnectorPhaseErrorBase): ... +class AMQPConnectionWorkflowAborted(AMQPConnectorException): ... +class AMQPConnectionWorkflowWrongState(AMQPConnectorException): ... + +class AMQPConnectionWorkflowFailed(AMQPConnectorException): + exceptions: tuple[BaseException, ...] + def __init__(self, exceptions: Iterable[BaseException], *args: object) -> None: ... + +class AMQPConnector: + def __init__( + self, conn_factory: Callable[[pika.connection.Parameters], AbstractStreamProtocol], nbio: AbstractIOServices + ) -> None: ... + def start( + self, + addr_record: tuple[ # tuple taken result of socket.getaddrinfo + int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes] + ], + conn_params: pika.connection.Parameters, + on_done: Callable[[pika.connection.Connection | BaseException], None], + ) -> None: ... + def abort(self) -> None: ... + +class AbstractAMQPConnectionWorkflow(pika.compat.AbstractBase): + def start( + self, + connection_configs: Sequence[pika.connection.Parameters], + connector_factory: Callable[..., Incomplete], + native_loop, + on_done: Callable[[pika.connection.Connection | AMQPConnectorException], None], + ) -> None: ... + def abort(self) -> None: ... + +class AMQPConnectionWorkflow(AbstractAMQPConnectionWorkflow): + def __init__(self, _until_first_amqp_attempt: bool = False) -> None: ... + def set_io_services(self, nbio: AbstractIOServices) -> None: ... + def start( + self, + connection_configs: Sequence[pika.connection.Parameters], + connector_factory: Callable[..., Incomplete], + native_loop, + on_done: Callable[[pika.connection.Connection | AMQPConnectorException], None], + ) -> None: ... + def abort(self) -> None: ... diff --git a/stubs/pika/pika/adapters/utils/io_services_utils.pyi b/stubs/pika/pika/adapters/utils/io_services_utils.pyi new file mode 100644 index 000000000000..604e533bc5f3 --- /dev/null +++ b/stubs/pika/pika/adapters/utils/io_services_utils.pyi @@ -0,0 +1,89 @@ +import abc +from collections.abc import Callable +from socket import socket +from ssl import SSLContext, SSLSocket +from typing import Any + +from pika.adapters.utils.nbio_interface import ( + AbstractFileDescriptorServices, + AbstractIOReference, + AbstractIOServices, + AbstractStreamProtocol, + AbstractStreamTransport, +) +from pika.adapters.utils.selector_ioloop_adapter import _SupportsCancel + +def check_callback_arg(callback: Callable[..., Any], name: str) -> None: ... +def check_fd_arg(fd: int) -> None: ... + +class SocketConnectionMixin: + def connect_socket( + self, sock: socket, resolved_addr: tuple[str, int], on_done: Callable[[BaseException | None], None] + ) -> _AsyncServiceAsyncHandle: ... + +class StreamingConnectionMixin: + def create_streaming_connection( + self, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ssl_context: SSLContext | None = None, + server_hostname: str | None = None, + ) -> AbstractIOReference: ... + +class _AsyncServiceAsyncHandle(AbstractIOReference): + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... + +class _AsyncSocketConnector: + def __init__( + self, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + sock: socket, + resolved_addr: tuple[str, int], + on_done: Callable[[BaseException | None], None], + ) -> None: ... + def start(self) -> AbstractIOReference: ... + def cancel(self) -> bool: ... + +class _AsyncStreamConnector: + def __init__( + self, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + ssl_context: SSLContext, + server_hostname: str | None, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ) -> None: ... + def start(self) -> AbstractIOReference: ... + def cancel(self) -> bool: ... + +class _AsyncTransportBase(AbstractStreamTransport, metaclass=abc.ABCMeta): + class RxEndOfFile(OSError): + def __init__(self) -> None: ... + + def __init__( + self, + sock: socket | SSLSocket, + protocol: AbstractStreamProtocol, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + ) -> None: ... + def abort(self) -> None: ... + def get_protocol(self) -> AbstractStreamProtocol: ... + def get_write_buffer_size(self) -> int: ... + +class _AsyncPlaintextTransport(_AsyncTransportBase): + def __init__( + self, + sock: socket | SSLSocket, + protocol: AbstractStreamProtocol, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + ) -> None: ... + def write(self, data: bytes) -> None: ... + +class _AsyncSSLTransport(_AsyncTransportBase): + def __init__( + self, sock: SSLSocket, protocol: AbstractStreamProtocol, nbio: AbstractIOServices | AbstractFileDescriptorServices + ) -> None: ... + def write(self, data: bytes) -> None: ... diff --git a/stubs/pika/pika/adapters/utils/nbio_interface.pyi b/stubs/pika/pika/adapters/utils/nbio_interface.pyi new file mode 100644 index 000000000000..6b963642813e --- /dev/null +++ b/stubs/pika/pika/adapters/utils/nbio_interface.pyi @@ -0,0 +1,85 @@ +import abc +from collections.abc import Callable +from socket import socket +from ssl import SSLContext + +import pika.compat + +class AbstractIOServices(pika.compat.AbstractBase, metaclass=abc.ABCMeta): + @abc.abstractmethod + def get_native_ioloop(self) -> object: ... + @abc.abstractmethod + def close(self) -> None: ... + @abc.abstractmethod + def run(self) -> None: ... + @abc.abstractmethod + def stop(self) -> None: ... + @abc.abstractmethod + def add_callback_threadsafe(self, callback: Callable[..., None]) -> None: ... + @abc.abstractmethod + def call_later(self, delay: float, callback: Callable[..., None]) -> AbstractTimerReference: ... + @abc.abstractmethod + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... + @abc.abstractmethod + def connect_socket( + self, sock: socket, resolved_addr: tuple[str, int], on_done: Callable[[BaseException | None], None] + ) -> AbstractIOReference: ... + @abc.abstractmethod + def create_streaming_connection( + self, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ssl_context: SSLContext | None = None, + server_hostname: str | None = None, + ) -> AbstractIOReference: ... + +class AbstractFileDescriptorServices(pika.compat.AbstractBase): + @abc.abstractmethod + def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: ... + @abc.abstractmethod + def remove_reader(self, fd: int) -> bool: ... + @abc.abstractmethod + def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: ... + @abc.abstractmethod + def remove_writer(self, fd: int) -> bool: ... + +class AbstractTimerReference(pika.compat.AbstractBase): + @abc.abstractmethod + def cancel(self) -> None: ... + +class AbstractIOReference(pika.compat.AbstractBase): + @abc.abstractmethod + def cancel(self) -> bool: ... + +class AbstractStreamProtocol(pika.compat.AbstractBase): + @abc.abstractmethod + def connection_made(self, transport: AbstractStreamTransport) -> None: ... + @abc.abstractmethod + def connection_lost(self, error: BaseException | None) -> None: ... + @abc.abstractmethod + def eof_received(self) -> bool | None: ... + @abc.abstractmethod + def data_received(self, data: bytes) -> None: ... + +class AbstractStreamTransport(pika.compat.AbstractBase): + @abc.abstractmethod + def abort(self) -> None: ... + @abc.abstractmethod + def get_protocol(self) -> AbstractStreamProtocol: ... + @abc.abstractmethod + def write(self, data: bytes) -> None: ... + @abc.abstractmethod + def get_write_buffer_size(self) -> int: ... diff --git a/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi b/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi new file mode 100644 index 000000000000..020017eacaf4 --- /dev/null +++ b/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi @@ -0,0 +1,111 @@ +import abc +from collections.abc import Callable +from logging import Logger +from typing import Final, Generic, Protocol, TypeVar, type_check_only + +from pika.adapters.utils import io_services_utils, nbio_interface + +LOGGER: Logger + +_Timeout = TypeVar("_Timeout", bound=object, default=object) + +@type_check_only +class _SupportsCancel(Protocol): + def cancel(self) -> bool: ... + +class AbstractSelectorIOLoop(Generic[_Timeout], metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def READ(self) -> int: ... + @property + @abc.abstractmethod + def WRITE(self) -> int: ... + @property + @abc.abstractmethod + def ERROR(self) -> int: ... + @abc.abstractmethod + def close(self) -> None: ... + @abc.abstractmethod + def start(self) -> None: ... + @abc.abstractmethod + def stop(self) -> None: ... + @abc.abstractmethod + def call_later(self, delay: float, callback: Callable[[], object]) -> _Timeout: ... + @abc.abstractmethod + def remove_timeout(self, timeout_handle: _Timeout) -> None: ... + @abc.abstractmethod + def add_callback(self, callback: Callable[[], object]) -> None: ... + @abc.abstractmethod + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + @abc.abstractmethod + def update_handler(self, fd: int, events: int) -> None: ... + @abc.abstractmethod + def remove_handler(self, fd: int) -> None: ... + +class SelectorIOServicesAdapter( + io_services_utils.SocketConnectionMixin, + io_services_utils.StreamingConnectionMixin, + nbio_interface.AbstractIOServices, + nbio_interface.AbstractFileDescriptorServices, + Generic[_Timeout], +): + def __init__(self, native_loop: AbstractSelectorIOLoop[_Timeout]) -> None: ... + def get_native_ioloop(self) -> AbstractSelectorIOLoop[_Timeout]: ... + def close(self) -> None: ... + def run(self) -> None: ... + def stop(self) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> _TimerHandle: ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> nbio_interface.AbstractIOReference: ... + def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: ... + def remove_reader(self, fd: int) -> bool: ... + def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: ... + def remove_writer(self, fd: int) -> bool: ... + +class _FileDescriptorCallbacks: + __slots__ = ("reader", "writer") + reader: Callable[[], None] + writer: Callable[[], None] + def __init__(self, reader: Callable[[], None] | None = None, writer: Callable[[], None] | None = None) -> None: ... + +class _TimerHandle(nbio_interface.AbstractTimerReference): + def __init__(self, handle: object, loop: AbstractSelectorIOLoop) -> None: ... + def cancel(self) -> None: ... + +class _SelectorIOLoopIOHandle(nbio_interface.AbstractIOReference): + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... + +class _AddressResolver: + NOT_STARTED: Final = 0 + ACTIVE: Final = 1 + CANCELED: Final = 2 + COMPLETED: Final = 3 + def __init__( + self, + native_loop: AbstractSelectorIOLoop, + host: str | bytes | None, + port: str | bytes | int | None, + family: int, + socktype: int, + proto: int, + flags: int, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + ) -> None: ... + def start(self) -> _SelectorIOLoopIOHandle: ... + def cancel(self) -> bool: ... diff --git a/stubs/pika/pika/amqp_object.pyi b/stubs/pika/pika/amqp_object.pyi new file mode 100644 index 000000000000..9f412173e43a --- /dev/null +++ b/stubs/pika/pika/amqp_object.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar + +class AMQPObject: + NAME: ClassVar[str] + INDEX: ClassVar[int | None] + def __eq__(self, other: AMQPObject | None) -> bool: ... # type: ignore[override] + +class Class(AMQPObject): ... + +class Method(AMQPObject): + # This is a class attribute in the implementation, but subclasses use @property, + # so it's more convenient to use that here as well. + @property + def synchronous(self) -> bool: ... + def get_properties(self) -> Properties: ... + def get_body(self) -> bytes: ... + def encode(self) -> list[bytes]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Method: ... + +class Properties(AMQPObject): ... diff --git a/stubs/pika/pika/callback.pyi b/stubs/pika/pika/callback.pyi new file mode 100644 index 000000000000..852fc1643dc5 --- /dev/null +++ b/stubs/pika/pika/callback.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from logging import Logger +from typing import Any, Final, Literal, ParamSpec, TypeAlias, TypeVar + +from .amqp_object import AMQPObject + +_P = ParamSpec("_P") +_R = TypeVar("_R") +AMQPValue: TypeAlias = type[AMQPObject] | AMQPObject | int | str + +LOGGER: Logger + +def name_or_value(value: AMQPValue) -> str: ... +def sanitize_prefix(function: Callable[_P, _R]) -> Callable[_P, _R]: ... +def check_for_prefix_and_key(function: Callable[_P, _R]) -> Callable[_P, _R | Literal[False]]: ... + +class CallbackManager: + CALLS: Final = "calls" + ARGUMENTS: Final = "arguments" + DUPLICATE_WARNING: Final = 'Duplicate callback found for "%s:%s"' + CALLBACK: Final = "callback" + ONE_SHOT: Final = "one_shot" + ONLY_CALLER: Final = "only" + def __init__(self) -> None: ... + def add( + self, + prefix: str | int, + key: AMQPValue, + # Parameter type must match arguments passed to process() + callback: Callable[..., object], + one_shot: bool = True, + only_caller: object | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> tuple[str | int, str | object]: ... + def clear(self) -> None: ... + def cleanup(self, prefix: str | int) -> bool: ... + def pending(self, prefix: str | int, key: AMQPValue) -> int | None: ... + def process( + self, + prefix: str | int, + key: AMQPValue, + caller, + *args: Any, # Arguments depends on callbacks stored on self._stack + **keywords: Any, + ) -> bool: ... + def remove( + self, + prefix: str | int, + key: AMQPValue, + callback_value: Callable[..., object] | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> bool: ... + def remove_all(self, prefix: str | int, key: AMQPValue) -> Literal[False] | None: ... diff --git a/stubs/pika/pika/channel.pyi b/stubs/pika/pika/channel.pyi new file mode 100644 index 000000000000..7fdbbd93d7b6 --- /dev/null +++ b/stubs/pika/pika/channel.pyi @@ -0,0 +1,165 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import Final, TypeVar +from typing_extensions import Self + +from . import amqp_object +from .callback import CallbackManager +from .connection import Connection +from .exchange_type import ExchangeType +from .frame import Body, Header, Method +from .spec import Basic, BasicProperties, Confirm, Exchange, Queue, Tx + +_Method = TypeVar("_Method", bound=amqp_object.Method) + +LOGGER: Logger +MAX_CHANNELS: Final = 65535 + +class Channel: + CLOSED: Final = 0 + OPENING: Final = 1 + OPEN: Final = 2 + CLOSING: Final = 3 + + channel_number: int + callbacks: CallbackManager + connection: Connection + flow_active: bool + + def __init__(self, connection: Connection, channel_number: int, on_open_callback: Callable[[Self], object]) -> None: ... + def __int__(self) -> int: ... + def add_callback(self, callback: Callable[..., object], replies: Iterable[Incomplete], one_shot: bool = True) -> None: ... + def add_on_cancel_callback(self, callback: Callable[[Method[Basic.Cancel]], object]) -> None: ... + def add_on_close_callback(self, callback: Callable[[Channel, Exception], object]) -> None: ... + def add_on_flow_callback(self, callback: Callable[[bool], object]) -> None: ... + def add_on_return_callback(self, callback: Callable[[Channel, Basic.Return, BasicProperties, bytes], object]) -> None: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_cancel( + self, consumer_tag: str = "", callback: Callable[[Method[Basic.CancelOk]], object] | None = None + ) -> None: ... + def basic_consume( + self, + queue: str, + on_message_callback: Callable[[Channel, Basic.Deliver, BasicProperties, bytes], object], + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Basic.ConsumeOk]], object] | None = None, + ) -> str: ... + def basic_get( + self, queue: str, callback: Callable[[Channel, Basic.GetOk, BasicProperties, bytes], object], auto_ack: bool = False + ) -> None: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + def basic_publish( + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, + ) -> None: ... + def basic_qos( + self, + prefetch_size: int = 0, + prefetch_count: int = 0, + global_qos: bool = False, + callback: Callable[[Method[Basic.QosOk]], object] | None = None, + ) -> None: ... + def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None: ... + def basic_recover( + self, requeue: bool = False, callback: Callable[[Method[Basic.RecoverOk]], object] | None = None + ) -> None: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown") -> None: ... + def confirm_delivery( + self, + ack_nack_callback: Callable[[Method[Basic.Ack | Basic.Nack]], object], + callback: Callable[[Method[Confirm.SelectOk]], object] | None = None, + ) -> None: ... + @property + def consumer_tags(self) -> list[str]: ... + def exchange_bind( + self, + destination: str, + source: str, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Exchange.BindOk]], object] | None = None, + ) -> None: ... + def exchange_declare( + self, + exchange: str, + exchange_type: ExchangeType | str = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Exchange.DeclareOk]], object] | None = None, + ) -> None: ... + def exchange_delete( + self, + exchange: str | None = None, + if_unused: bool = False, + callback: Callable[[Method[Exchange.DeleteOk]], object] | None = None, + ) -> None: ... + def exchange_unbind( + self, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Exchange.UnbindOk]], object] | None = None, + ) -> None: ... + def flow(self, active: bool, callback: Callable[[bool], object] | None = None) -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def is_opening(self) -> bool: ... + def open(self) -> None: ... + def queue_bind( + self, + queue: str, + exchange: str, + routing_key: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Queue.BindOk]], object] | None = None, + ) -> None: ... + def queue_declare( + self, + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Queue.DeclareOk]], object] | None = None, + ) -> None: ... + def queue_delete( + self, + queue: str, + if_unused: bool = False, + if_empty: bool = False, + callback: Callable[[Method[Queue.DeleteOk]], object] | None = None, + ) -> None: ... + def queue_purge(self, queue: str, callback: Callable[[Method[Queue.PurgeOk]], object] | None = None) -> None: ... + def queue_unbind( + self, + queue: str, + exchange: str | None = None, + routing_key: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Queue.UnbindOk]], object] | None = None, + ): ... + def tx_commit(self, callback: Callable[[Method[Tx.CommitOk]], object] | None = None) -> None: ... + def tx_rollback(self, callback: Callable[[Method[Tx.RollbackOk]], object] | None = None) -> None: ... + def tx_select(self, callback: Callable[[Method[Tx.SelectOk]], object] | None = None) -> None: ... + +class ContentFrameAssembler: + def __init__(self) -> None: ... + def process(self, frame_value: Method[_Method] | Header | Body) -> tuple[Method[_Method], Header, bytes] | None: ... diff --git a/stubs/pika/pika/compat.pyi b/stubs/pika/pika/compat.pyi new file mode 100644 index 000000000000..19237f6be186 --- /dev/null +++ b/stubs/pika/pika/compat.pyi @@ -0,0 +1,35 @@ +import socket +import sys +from abc import ABCMeta +from re import Pattern +from typing import Final, SupportsIndex + +RE_NUM: Final[Pattern[str]] +ON_LINUX: Final[bool] +ON_OSX: Final[bool] +ON_WINDOWS: Final[bool] + +class AbstractBase(metaclass=ABCMeta): ... + +SOCKET_ERROR = OSError +SOL_TCP: Final[int] +HAVE_SIGNAL: Final[bool] +str_or_bytes: Final[tuple[type[str], type[bytes]]] + +def time_now() -> float: ... +def byte(*args: SupportsIndex) -> bytes: ... + +class long(int): ... + +def as_bytes(value: str | bytes) -> bytes: ... +def to_digit(value: str) -> int: ... +def get_linux_version(release_str: str) -> tuple[int, int, int]: ... + +if sys.platform == "linux": + LINUX_VERSION: Final[tuple[int, int, int]] +else: + LINUX_VERSION: Final[None] + +def nonblocking_socketpair( + family: int = socket.AF_INET, socket_type: int = socket.SOCK_STREAM, proto: int = 0 +) -> tuple[socket.socket, socket.socket]: ... diff --git a/stubs/pika/pika/connection.pyi b/stubs/pika/pika/connection.pyi new file mode 100644 index 000000000000..0264ccc017e0 --- /dev/null +++ b/stubs/pika/pika/connection.pyi @@ -0,0 +1,231 @@ +import abc +import ssl +from _typeshed import Incomplete +from collections.abc import Callable +from logging import Logger +from typing import Final, Literal +from typing_extensions import Self + +from .callback import CallbackManager +from .channel import Channel +from .compat import AbstractBase +from .credentials import PlainCredentials, _Credentials +from .frame import Method +from .spec import Connection as SpecConnection + +PRODUCT: Final = "Pika Python Client Library" +LOGGER: Logger + +class Parameters: + __slots__ = ( + "_blocked_connection_timeout", + "_channel_max", + "_client_properties", + "_connection_attempts", + "_credentials", + "_frame_max", + "_heartbeat", + "_host", + "_locale", + "_port", + "_retry_delay", + "_socket_timeout", + "_stack_timeout", + "_ssl_options", + "_virtual_host", + "_tcp_options", + ) + DEFAULT_USERNAME: Final = "guest" + DEFAULT_PASSWORD: Final = "guest" + DEFAULT_BLOCKED_CONNECTION_TIMEOUT: Final = None + DEFAULT_CHANNEL_MAX: Final = 65535 + DEFAULT_CLIENT_PROPERTIES: Final = None + DEFAULT_CREDENTIALS: Final[PlainCredentials] + DEFAULT_CONNECTION_ATTEMPTS: Final = 1 + DEFAULT_FRAME_MAX: Final = 131072 + DEFAULT_HEARTBEAT_TIMEOUT: None + DEFAULT_HOST: Final = "localhost" + DEFAULT_LOCALE: Final = "en_US" + DEFAULT_PORT: Final = 5672 + DEFAULT_RETRY_DELAY: Final = 2.0 + DEFAULT_SOCKET_TIMEOUT: Final = 10.0 + DEFAULT_STACK_TIMEOUT: Final = 15.0 + DEFAULT_SSL: Final = False + DEFAULT_SSL_OPTIONS: Final = None + DEFAULT_SSL_PORT: Final = 5671 + DEFAULT_VIRTUAL_HOST: Final = "/" + DEFAULT_TCP_OPTIONS: Final = None + def __init__(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + + @property + def blocked_connection_timeout(self) -> float | None: ... + @blocked_connection_timeout.setter + def blocked_connection_timeout(self, value: float | None) -> None: ... + + @property + def channel_max(self) -> int: ... + @channel_max.setter + def channel_max(self, value: int) -> None: ... + + @property + def client_properties(self) -> dict[Incomplete, Incomplete] | None: ... + @client_properties.setter + def client_properties(self, value: dict[Incomplete, Incomplete] | None) -> None: ... + + @property + def connection_attempts(self) -> int: ... + @connection_attempts.setter + def connection_attempts(self, value: int) -> None: ... + + @property + def credentials(self) -> _Credentials: ... + @credentials.setter + def credentials(self, value: _Credentials) -> None: ... + + @property + def frame_max(self) -> int: ... + @frame_max.setter + def frame_max(self, value: int) -> None: ... + + @property + def heartbeat(self) -> int | Callable[[Connection, int], int] | None: ... + @heartbeat.setter + def heartbeat(self, value: int | Callable[[Connection, int], int] | None) -> None: ... + + @property + def host(self) -> str: ... + @host.setter + def host(self, value: str) -> None: ... + + @property + def locale(self) -> str: ... + @locale.setter + def locale(self, value: str) -> None: ... + + @property + def port(self) -> int: ... + @port.setter + def port(self, value: int | str) -> None: ... + + @property + def retry_delay(self) -> int | float: ... + @retry_delay.setter + def retry_delay(self, value: float) -> None: ... + + @property + def socket_timeout(self) -> float | None: ... + @socket_timeout.setter + def socket_timeout(self, value: float | None) -> None: ... + + @property + def stack_timeout(self) -> float | None: ... + @stack_timeout.setter + def stack_timeout(self, value: float | None) -> None: ... + + @property + def ssl_options(self) -> SSLOptions | None: ... + @ssl_options.setter + def ssl_options(self, value: SSLOptions | None) -> None: ... + + @property + def virtual_host(self) -> str: ... + @virtual_host.setter + def virtual_host(self, value: str) -> None: ... + + @property + def tcp_options(self) -> dict[str, Incomplete] | None: ... + @tcp_options.setter + def tcp_options(self, value: dict[str, Incomplete] | None) -> None: ... + +class ConnectionParameters(Parameters): + __slots__ = () + def __init__( + self, + host: str = ..., + port: int = ..., + virtual_host: str = ..., + credentials: _Credentials = ..., + channel_max: int = ..., + frame_max: int = ..., + heartbeat: int | Callable[[Connection, int], int] | None = ..., + ssl_options: SSLOptions | None = ..., + connection_attempts: int = ..., + retry_delay: float = ..., + socket_timeout: float | None = ..., + stack_timeout: float | None = ..., + locale: str = ..., + blocked_connection_timeout: float | None = ..., + client_properties: dict[str, Incomplete] | None = ..., + tcp_options: dict[str, Incomplete] | None = ..., + ) -> None: ... + +class URLParameters(Parameters): + __slots__ = ("_all_url_query_values",) + def __init__(self, url: str) -> None: ... + +class SSLOptions: + __slots__ = ("context", "server_hostname") + context: ssl.SSLContext + server_hostname: str | None + def __init__(self, context: ssl.SSLContext, server_hostname: str | None = None) -> None: ... + +class Connection(AbstractBase, metaclass=abc.ABCMeta): + ON_CONNECTION_CLOSED: Final = "_on_connection_closed" + ON_CONNECTION_ERROR: Final = "_on_connection_error" + ON_CONNECTION_OPEN_OK: Final = "_on_connection_open_ok" + CONNECTION_CLOSED: Final = 0 + CONNECTION_INIT: Final = 1 + CONNECTION_PROTOCOL: Final = 2 + CONNECTION_START: Final = 3 + CONNECTION_TUNE: Final = 4 + CONNECTION_OPEN: Final = 5 + CONNECTION_CLOSING: Final = 6 + connection_state: Literal[0, 1, 2, 3, 4, 5, 6] # one of the constants above + params: Parameters + callbacks: CallbackManager + server_capabilities: dict[str, bool] | None + server_properties: dict[str, Incomplete] | None + known_hosts: str | None + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + def add_on_close_callback(self, callback: Callable[[Self, BaseException], object]) -> None: ... + def add_on_connection_blocked_callback(self, callback: Callable[[Self, Method[SpecConnection.Blocked]], object]) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[Self, Method[SpecConnection.Unblocked]], object] + ) -> None: ... + def add_on_open_callback(self, callback: Callable[[Self], object]) -> None: ... + def add_on_open_error_callback( + self, callback: Callable[[Self, BaseException], object], remove_default: bool = True + ) -> None: ... + def channel( + self, channel_number: int | None = None, on_open_callback: Callable[[Channel], object] | None = None + ) -> Channel: ... + def update_secret( + self, + new_secret: str | bytes, + reason: str | bytes, + callback: Callable[[Method[SpecConnection.UpdateSecretOk]], object] | None = None, + ) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack(self) -> bool: ... + @property + def consumer_cancel_notify(self) -> bool: ... + @property + def exchange_exchange_bindings(self) -> bool: ... + @property + def publisher_confirms(self) -> bool: ... diff --git a/stubs/pika/pika/credentials.pyi b/stubs/pika/pika/credentials.pyi new file mode 100644 index 000000000000..9e6288b7b5f4 --- /dev/null +++ b/stubs/pika/pika/credentials.pyi @@ -0,0 +1,37 @@ +from logging import Logger +from typing import ClassVar, Protocol, type_check_only + +from .spec import Connection + +@type_check_only +class _Credentials(Protocol): + TYPE: ClassVar[str] + erase_on_connect: bool + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def response_for(self, start: Connection.Start) -> tuple[str | None, bytes | None]: ... + def erase_credentials(self) -> None: ... + +LOGGER: Logger + +class PlainCredentials: + TYPE: ClassVar[str] + erase_on_connect: bool + username: str + password: str + def __init__(self, username: str, password: str, erase_on_connect: bool = False) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def response_for(self, start: Connection.Start) -> tuple[str | None, bytes | None]: ... + def erase_credentials(self) -> None: ... + +class ExternalCredentials: + TYPE: ClassVar[str] + erase_on_connect: bool + def __init__(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def response_for(self, start: Connection.Start) -> tuple[str | None, bytes | None]: ... + def erase_credentials(self) -> None: ... + +VALID_TYPES: list[_Credentials] diff --git a/stubs/pika/pika/data.pyi b/stubs/pika/pika/data.pyi new file mode 100644 index 000000000000..18ad67c71a6b --- /dev/null +++ b/stubs/pika/pika/data.pyi @@ -0,0 +1,14 @@ +from collections.abc import Mapping +from datetime import datetime +from decimal import Decimal +from typing import TypeAlias + +_Value: TypeAlias = str | bytes | bool | int | Decimal | datetime | _ArgumentMapping | list[_Value] | None +_ArgumentMapping: TypeAlias = Mapping[str, _Value] + +def encode_short_string(pieces: list[bytes], value: str | bytes) -> int: ... +def decode_short_string(encoded: bytes, offset: int) -> tuple[str | bytes, int]: ... +def encode_table(pieces: list[bytes], table: _ArgumentMapping) -> int: ... +def encode_value(pieces: list[bytes], value: _Value) -> int: ... +def decode_table(encoded: bytes, offset: int) -> tuple[dict[str | bytes, _Value], int]: ... +def decode_value(encoded: bytes, offset: int) -> tuple[_Value, int]: ... diff --git a/stubs/pika/pika/delivery_mode.pyi b/stubs/pika/pika/delivery_mode.pyi new file mode 100644 index 000000000000..61d5aa5c4237 --- /dev/null +++ b/stubs/pika/pika/delivery_mode.pyi @@ -0,0 +1,5 @@ +from enum import Enum + +class DeliveryMode(Enum): + Transient = 1 + Persistent = 2 diff --git a/stubs/pika/pika/diagnostic_utils.pyi b/stubs/pika/pika/diagnostic_utils.pyi new file mode 100644 index 000000000000..0c46e0f8eb33 --- /dev/null +++ b/stubs/pika/pika/diagnostic_utils.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable +from logging import Logger +from typing import Any, TypeVar + +F = TypeVar("F", bound=Callable[..., Any]) # noqa: Y001 + +def create_log_exception_decorator(logger: Logger) -> Callable[[F], F]: ... diff --git a/stubs/pika/pika/exceptions.pyi b/stubs/pika/pika/exceptions.pyi new file mode 100644 index 000000000000..5f77d4d67572 --- /dev/null +++ b/stubs/pika/pika/exceptions.pyi @@ -0,0 +1,62 @@ +from collections.abc import Sequence + +from pika.adapters.blocking_connection import ReturnedMessage + +class AMQPError(Exception): ... +class AMQPConnectionError(AMQPError): ... +class ConnectionOpenAborted(AMQPConnectionError): ... +class StreamLostError(AMQPConnectionError): ... +class IncompatibleProtocolError(AMQPConnectionError): ... +class AuthenticationError(AMQPConnectionError): ... +class ProbableAuthenticationError(AMQPConnectionError): ... +class ProbableAccessDeniedError(AMQPConnectionError): ... +class NoFreeChannels(AMQPConnectionError): ... +class ConnectionWrongStateError(AMQPConnectionError): ... + +class ConnectionClosed(AMQPConnectionError): + def __init__(self, reply_code: int, reply_text: str) -> None: ... + @property + def reply_code(self) -> int: ... + @property + def reply_text(self) -> str: ... + +class ConnectionClosedByBroker(ConnectionClosed): ... +class ConnectionClosedByClient(ConnectionClosed): ... +class ConnectionBlockedTimeout(AMQPConnectionError): ... +class AMQPHeartbeatTimeout(AMQPConnectionError): ... +class AMQPChannelError(AMQPError): ... +class ChannelWrongStateError(AMQPChannelError): ... + +class ChannelClosed(AMQPChannelError): + def __init__(self, reply_code: int, reply_text: str) -> None: ... + @property + def reply_code(self) -> int: ... + @property + def reply_text(self) -> str: ... + +class ChannelClosedByBroker(ChannelClosed): ... +class ChannelClosedByClient(ChannelClosed): ... +class DuplicateConsumerTag(AMQPChannelError): ... +class ConsumerCancelled(AMQPChannelError): ... + +class UnroutableError(AMQPChannelError): + messages: Sequence[ReturnedMessage] + def __init__(self, messages: Sequence[ReturnedMessage]) -> None: ... + +class NackError(AMQPChannelError): + messages: Sequence[ReturnedMessage] + def __init__(self, messages: Sequence[ReturnedMessage]) -> None: ... + +class InvalidChannelNumber(AMQPError): ... +class ProtocolSyntaxError(AMQPError): ... +class UnexpectedFrameError(ProtocolSyntaxError): ... +class ProtocolVersionMismatch(ProtocolSyntaxError): ... +class BodyTooLongError(ProtocolSyntaxError): ... +class InvalidFrameError(ProtocolSyntaxError): ... +class InvalidFieldTypeException(ProtocolSyntaxError): ... +class UnsupportedAMQPFieldException(ProtocolSyntaxError): ... +class MethodNotImplemented(AMQPError): ... +class ChannelError(Exception): ... +class ReentrancyError(Exception): ... +class ShortStringTooLong(AMQPError): ... +class DuplicateGetOkCallback(ChannelError): ... diff --git a/stubs/pika/pika/exchange_type.pyi b/stubs/pika/pika/exchange_type.pyi new file mode 100644 index 000000000000..af625976ee47 --- /dev/null +++ b/stubs/pika/pika/exchange_type.pyi @@ -0,0 +1,19 @@ +import sys + +if sys.version_info >= (3, 11): + from enum import StrEnum + + class ExchangeType(StrEnum): + direct = "direct" + fanout = "fanout" + headers = "headers" + topic = "topic" + +else: + from enum import Enum + + class ExchangeType(str, Enum): + direct = "direct" + fanout = "fanout" + headers = "headers" + topic = "topic" diff --git a/stubs/pika/pika/frame.pyi b/stubs/pika/pika/frame.pyi new file mode 100644 index 000000000000..8b547d8478ee --- /dev/null +++ b/stubs/pika/pika/frame.pyi @@ -0,0 +1,47 @@ +from abc import abstractmethod +from logging import Logger +from typing import Generic, TypeVar + +from . import amqp_object +from .spec import BasicProperties + +_M = TypeVar("_M", bound=amqp_object.Method) + +LOGGER: Logger + +class Frame(amqp_object.AMQPObject): + frame_type: int + channel_number: int + def __init__(self, frame_type: int, channel_number: int) -> None: ... + @abstractmethod + def marshal(self) -> bytes: ... + +class Method(Frame, Generic[_M]): + method: _M + def __init__(self, channel_number: int, method: _M) -> None: ... + def marshal(self) -> bytes: ... + +class Header(Frame): + body_size: int + properties: BasicProperties + def __init__(self, channel_number: int, body_size: int, props: BasicProperties) -> None: ... + def marshal(self) -> bytes: ... + +class Body(Frame): + fragment: bytes + def __init__(self, channel_number: int, fragment: bytes) -> None: ... + def marshal(self) -> bytes: ... + +class Heartbeat(Frame): + def __init__(self) -> None: ... + def marshal(self) -> bytes: ... + +class ProtocolHeader(amqp_object.AMQPObject): + frame_type: int + major: int + minor: int + revision: int + def __init__(self, major: int | None = None, minor: int | None = None, revision: int | None = None) -> None: ... + def marshal(self) -> bytes: ... + +def decode_frame(data_in: bytes) -> tuple[int, Frame | ProtocolHeader | None]: ... diff --git a/stubs/pika/pika/heartbeat.pyi b/stubs/pika/pika/heartbeat.pyi new file mode 100644 index 000000000000..1c6ec89dfc60 --- /dev/null +++ b/stubs/pika/pika/heartbeat.pyi @@ -0,0 +1,14 @@ +from logging import Logger + +from pika.connection import Connection + +LOGGER: Logger + +class HeartbeatChecker: + def __init__(self, connection: Connection, timeout: float) -> None: ... + @property + def bytes_received_on_connection(self) -> int: ... + @property + def connection_is_idle(self) -> bool: ... + def received(self) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/pika/pika/spec.pyi b/stubs/pika/pika/spec.pyi new file mode 100644 index 000000000000..eee768972a16 --- /dev/null +++ b/stubs/pika/pika/spec.pyi @@ -0,0 +1,908 @@ +from _typeshed import Incomplete +from builtins import type as _type +from collections.abc import Mapping +from typing import ClassVar, Final, Literal +from typing_extensions import Self + +from pika.amqp_object import Class, Method, Properties +from pika.data import _ArgumentMapping +from pika.delivery_mode import DeliveryMode + +PROTOCOL_VERSION: Final[tuple[int, int, int]] +PORT: Final = 5672 +ACCESS_REFUSED: Final = 403 +CHANNEL_ERROR: Final = 504 +COMMAND_INVALID: Final = 503 +CONNECTION_FORCED: Final = 320 +CONTENT_TOO_LARGE: Final = 311 +FRAME_BODY: Final = 3 +FRAME_END: Final = 206 +FRAME_END_SIZE: Final = 1 +FRAME_ERROR: Final = 501 +FRAME_HEADER: Final = 2 +FRAME_HEADER_SIZE: Final = 7 +FRAME_HEARTBEAT: Final = 8 +FRAME_MAX_SIZE: Final = 131072 +FRAME_METHOD: Final = 1 +FRAME_MIN_SIZE: Final = 4096 +INTERNAL_ERROR: Final = 541 +INVALID_PATH: Final = 402 +NOT_ALLOWED: Final = 530 +NOT_FOUND: Final = 404 +NOT_IMPLEMENTED: Final = 540 +NO_CONSUMERS: Final = 313 +NO_ROUTE: Final = 312 +PERSISTENT_DELIVERY_MODE: Final = 2 +PRECONDITION_FAILED: Final = 406 +REPLY_SUCCESS: Final = 200 +RESOURCE_ERROR: Final = 506 +RESOURCE_LOCKED: Final = 405 +SYNTAX_ERROR: Final = 502 +TRANSIENT_DELIVERY_MODE: Final = 1 +UNEXPECTED_FRAME: Final = 505 + +class Connection(Class): + INDEX: ClassVar[int] + + class Start(Method): + INDEX: ClassVar[int] + version_major: int + version_minor: int + server_properties: _ArgumentMapping | None + mechanisms: str + locales: str + def __init__( + self, + version_major: int = 0, + version_minor: int = 9, + server_properties: _ArgumentMapping | None = None, + mechanisms: str = "PLAIN", + locales: str = "en_US", + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class StartOk(Method): + INDEX: ClassVar[int] + client_properties: _ArgumentMapping | None + mechanism: str + response: str | None + locale: str + def __init__( + self, + client_properties: _ArgumentMapping | None = None, + mechanism: str = "PLAIN", + response: str | None = None, + locale: str = "en_US", + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Secure(Method): + INDEX: ClassVar[int] + challenge: str | None + def __init__(self, challenge: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class SecureOk(Method): + INDEX: ClassVar[int] + response: str + def __init__(self, response: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Tune(Method): + INDEX: ClassVar[int] + channel_max: int + frame_max: int + heartbeat: int + def __init__(self, channel_max: int = 0, frame_max: int = 0, heartbeat: int = 0) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class TuneOk(Method): + INDEX: ClassVar[int] + channel_max: int + frame_max: int + heartbeat: int + def __init__(self, channel_max: int = 0, frame_max: int = 0, heartbeat: int = 0) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Open(Method): + INDEX: ClassVar[int] + virtual_host: str + capabilities: str + insist: bool + def __init__(self, virtual_host: str = "/", capabilities: str = "", insist: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class OpenOk(Method): + INDEX: ClassVar[int] + known_hosts: str + def __init__(self, known_hosts: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Close(Method): + INDEX: ClassVar[int] + reply_code: int | None + reply_text: str + class_id: int | None + method_id: int | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", class_id: int | None = None, method_id: int | None = None + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CloseOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Blocked(Method): + INDEX: ClassVar[int] + reason: str + def __init__(self, reason: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Unblocked(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UpdateSecret(Method): + INDEX: ClassVar[int] + new_secret: str + reason: str + mechanisms: str + def __init__(self, new_secret: str, reason: str) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UpdateSecretOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Channel(Class): + INDEX: ClassVar[int] + + class Open(Method): + INDEX: ClassVar[int] + out_of_band: str + def __init__(self, out_of_band: str = "") -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class OpenOk(Method): + INDEX: ClassVar[int] + channel_id: str + def __init__(self, channel_id: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Flow(Method): + INDEX: ClassVar[int] + active: bool | None + def __init__(self, active: bool | None = None) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class FlowOk(Method): + INDEX: ClassVar[int] + active: bool | None + def __init__(self, active: bool | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Close(Method): + INDEX: ClassVar[int] + reply_code: int | None + reply_text: str + class_id: int | None + method_id: int | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", class_id: int | None = None, method_id: int | None = None + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CloseOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Access(Class): + INDEX: ClassVar[int] + + class Request(Method): + INDEX: ClassVar[int] + realm: str + exclusive: bool + passive: bool + active: bool + write: bool + read: bool + def __init__( + self, + realm: str = "/data", + exclusive: bool = False, + passive: bool = True, + active: bool = True, + write: bool = True, + read: bool = True, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RequestOk(Method): + INDEX: ClassVar[int] + ticket: int + def __init__(self, ticket: int = 1) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Exchange(Class): + INDEX: ClassVar[int] + + class Declare(Method): + INDEX: ClassVar[int] + ticket: int + exchange: str | None + type: str + passive: bool + durable: bool + auto_delete: bool + internal: bool + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + exchange: str | None = None, + type: str = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeclareOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Delete(Method): + INDEX: ClassVar[int] + ticket: int + exchange: str | None + if_unused: bool + nowait: bool + def __init__( + self, ticket: int = 0, exchange: str | None = None, if_unused: bool = False, nowait: bool = False + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeleteOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Bind(Method): + INDEX: ClassVar[int] + ticket: int + destination: str | None + source: str | None + routing_key: str + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class BindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Unbind(Method): + INDEX: ClassVar[int] + ticket: int + destination: str | None + source: str | None + routing_key: str + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UnbindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Queue(Class): + INDEX: ClassVar[int] + + class Declare(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + passive: bool + durable: bool + exclusive: bool + auto_delete: bool + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeclareOk(Method): + INDEX: ClassVar[int] + queue: str + message_count: int + consumer_count: int + def __init__(self, queue: str, message_count: int, consumer_count: int) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Bind(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + exchange: str | None + routing_key: str + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + exchange: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class BindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Purge(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + nowait: bool + def __init__(self, ticket: int = 0, queue: str = "", nowait: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class PurgeOk(Method): + INDEX: ClassVar[int] + message_count: int | None + def __init__(self, message_count: int | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Delete(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + if_unused: bool + if_empty: bool + nowait: bool + def __init__( + self, ticket: int = 0, queue: str = "", if_unused: bool = False, if_empty: bool = False, nowait: bool = False + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeleteOk(Method): + INDEX: ClassVar[int] + message_count: int | None + def __init__(self, message_count: int | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Unbind(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + exchange: str | None + routing_key: str + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + exchange: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UnbindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Basic(Class): + INDEX: ClassVar[int] + + class Qos(Method): + INDEX: ClassVar[int] + prefetch_size: int + prefetch_count: int + global_qos: bool + def __init__(self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class QosOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Consume(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + consumer_tag: str + no_local: bool + no_ack: bool + exclusive: bool + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + consumer_tag: str = "", + no_local: bool = False, + no_ack: bool = False, + exclusive: bool = False, + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class ConsumeOk(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + def __init__(self, consumer_tag: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Cancel(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + nowait: bool + def __init__(self, consumer_tag: str | None = None, nowait: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CancelOk(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + def __init__(self, consumer_tag: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Publish(Method): + INDEX: ClassVar[int] + ticket: int + exchange: str + routing_key: str + mandatory: bool + immediate: bool + def __init__( + self, ticket: int = 0, exchange: str = "", routing_key: str = "", mandatory: bool = False, immediate: bool = False + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Return(Method): + INDEX: ClassVar[int] + reply_code: int | None + reply_text: str + exchange: str | None + routing_key: str | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", exchange: str | None = None, routing_key: str | None = None + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Deliver(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + delivery_tag: int | None + redelivered: bool + exchange: str | None + routing_key: str | None + def __init__( + self, + consumer_tag: str | None = None, + delivery_tag: int | None = None, + redelivered: bool = False, + exchange: str | None = None, + routing_key: str | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Get(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + no_ack: bool + def __init__(self, ticket: int = 0, queue: str = "", no_ack: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class GetOk(Method): + INDEX: ClassVar[int] + delivery_tag: int | None + redelivered: bool + exchange: str | None + routing_key: str | None + message_count: int | None + def __init__( + self, + delivery_tag: int | None = None, + redelivered: bool = False, + exchange: str | None = None, + routing_key: str | None = None, + message_count: int | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class GetEmpty(Method): + INDEX: ClassVar[int] + cluster_id: str + def __init__(self, cluster_id: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Ack(Method): + INDEX: ClassVar[int] + delivery_tag: int + multiple: bool + def __init__(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Reject(Method): + INDEX: ClassVar[int] + delivery_tag: int | None + requeue: bool + def __init__(self, delivery_tag: int | None = None, requeue: bool = True) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RecoverAsync(Method): + INDEX: ClassVar[int] + requeue: bool + def __init__(self, requeue: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Recover(Method): + INDEX: ClassVar[int] + requeue: bool + def __init__(self, requeue: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RecoverOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Nack(Method): + INDEX: ClassVar[int] + delivery_tag: int + multiple: bool + requeue: bool + def __init__(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Tx(Class): + INDEX: ClassVar[int] + + class Select(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class SelectOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Commit(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CommitOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Rollback(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RollbackOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Confirm(Class): + INDEX: ClassVar[int] + + class Select(Method): + INDEX: ClassVar[int] + nowait: bool + def __init__(self, nowait: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class SelectOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class BasicProperties(Properties): + CLASS: ClassVar[_type[Basic]] + INDEX: ClassVar[int] + FLAG_CONTENT_TYPE: Final = 32768 + FLAG_CONTENT_ENCODING: Final = 16384 + FLAG_HEADERS: Final = 8192 + FLAG_DELIVERY_MODE: Final = 4096 + FLAG_PRIORITY: Final = 2048 + FLAG_CORRELATION_ID: Final = 1024 + FLAG_REPLY_TO: Final = 512 + FLAG_EXPIRATION: Final = 256 + FLAG_MESSAGE_ID: Final = 128 + FLAG_TIMESTAMP: Final = 64 + FLAG_TYPE: Final = 32 + FLAG_USER_ID: Final = 16 + FLAG_APP_ID: Final = 8 + FLAG_CLUSTER_ID: Final = 4 + content_type: str | None + content_encoding: str | None + headers: _ArgumentMapping | None + delivery_mode: Literal[1, 2] | None + priority: int | None + correlation_id: str | None + reply_to: str | None + expiration: str | None + message_id: str | None + timestamp: int | None + type: str | None + user_id: str | None + app_id: str | None + cluster_id: str | None + def __init__( + self, + content_type: str | None = None, + content_encoding: str | None = None, + headers: _ArgumentMapping | None = None, + delivery_mode: DeliveryMode | Literal[1, 2] | None = None, + priority: int | None = None, + correlation_id: str | None = None, + reply_to: str | None = None, + expiration: str | None = None, + message_id: str | None = None, + timestamp: int | None = None, + type: str | None = None, + user_id: str | None = None, + app_id: str | None = None, + cluster_id: str | None = None, + ) -> None: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +methods: Final[dict[int, type[Method]]] +props: Final[dict[int, type[BasicProperties]]] + +def has_content(methodNumber: int) -> bool: ... diff --git a/stubs/pika/pika/tcp_socket_opts.pyi b/stubs/pika/pika/tcp_socket_opts.pyi new file mode 100644 index 000000000000..7c15e0beb5e8 --- /dev/null +++ b/stubs/pika/pika/tcp_socket_opts.pyi @@ -0,0 +1,9 @@ +from _socket import SocketType +from logging import Logger + +LOGGER: Logger + +_SUPPORTED_TCP_OPTIONS: dict[str, int] + +def socket_requires_keepalive(tcp_options: dict[str, int]) -> bool: ... +def set_sock_opts(tcp_options: dict[str, int] | None, sock: SocketType) -> None: ... diff --git a/stubs/pika/pika/validators.pyi b/stubs/pika/pika/validators.pyi new file mode 100644 index 000000000000..07c2bb0f110d --- /dev/null +++ b/stubs/pika/pika/validators.pyi @@ -0,0 +1,15 @@ +from _typeshed import ConvertibleToInt +from collections.abc import Callable +from typing import Literal, overload + +def require_string(value: object, value_name: str) -> None: ... # raise TypeError if value is not string +def require_callback( + callback: object, callback_name: str = "callback" # raise TypeError if callback is not callable +) -> None: ... + +@overload +def rpc_completion_callback(callback: None) -> Literal[True]: ... +@overload +def rpc_completion_callback(callback: Callable[..., object]) -> Literal[False]: ... + +def zero_or_greater(name: str, value: ConvertibleToInt) -> None: ... diff --git a/stubs/polib/@tests/stubtest_allowlist.txt b/stubs/polib/@tests/stubtest_allowlist.txt deleted file mode 100644 index 885e8a53b87d..000000000000 --- a/stubs/polib/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,2 +0,0 @@ -polib.TextWrapper -polib._BaseFile.save diff --git a/stubs/polib/METADATA.toml b/stubs/polib/METADATA.toml index c0a0050d4a68..959b3806d798 100644 --- a/stubs/polib/METADATA.toml +++ b/stubs/polib/METADATA.toml @@ -1,2 +1,2 @@ -version = "1.1.*" -python2 = true +version = "1.2.*" +upstream-repository = "https://github.com/izimobil/polib" diff --git a/stubs/polib/polib.pyi b/stubs/polib/polib.pyi index c4c361f1836c..a41fe1dea93a 100644 --- a/stubs/polib/polib.pyi +++ b/stubs/polib/polib.pyi @@ -1,10 +1,10 @@ -import textwrap -from typing import IO, Any, Callable, Generic, List, Text, Type, TypeVar, overload -from typing_extensions import SupportsIndex +from collections.abc import Callable +from pathlib import Path +from typing import IO, Any, Generic, Literal, SupportsIndex, TypeVar, overload -_TB = TypeVar("_TB", bound="_BaseEntry") -_TP = TypeVar("_TP", bound="POFile") -_TM = TypeVar("_TM", bound="MOFile") +_TB = TypeVar("_TB", bound=_BaseEntry) +_TP = TypeVar("_TP", bound=POFile) +_TM = TypeVar("_TM", bound=MOFile) default_encoding: str @@ -12,40 +12,44 @@ default_encoding: str # encoding: str # check_for_duplicates: bool @overload -def pofile(pofile: Text, *, klass: Type[_TP], **kwargs: Any) -> _TP: ... +def pofile(pofile: str | Path, *, klass: type[_TP], **kwargs: Any) -> _TP: ... @overload -def pofile(pofile: Text, **kwargs: Any) -> POFile: ... +def pofile(pofile: str | Path, **kwargs: Any) -> POFile: ... + @overload -def mofile(mofile: Text, *, klass: Type[_TM], **kwargs: Any) -> _TM: ... +def mofile(mofile: str, *, klass: type[_TM], **kwargs: Any) -> _TM: ... @overload -def mofile(mofile: Text, **kwargs: Any) -> MOFile: ... -def detect_encoding(file: bytes | Text, binary_mode: bool = ...) -> str: ... -def escape(st: Text) -> Text: ... -def unescape(st: Text) -> Text: ... +def mofile(mofile: str, **kwargs: Any) -> MOFile: ... + +def detect_encoding(file: bytes | str, binary_mode: bool = ...) -> str: ... +def escape(st: str) -> str: ... +def unescape(st: str) -> str: ... -class _BaseFile(List[_TB]): - fpath: Text +class _BaseFile(list[_TB]): + fpath: str wrapwidth: int - encoding: Text + encoding: str check_for_duplicates: bool - header: Text - metadata: dict[Text, Text] + header: str + metadata: dict[str, str] metadata_is_fuzzy: bool def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def __unicode__(self) -> Text: ... - def __contains__(self, entry: _TB) -> bool: ... # type: ignore # AttributeError otherwise + def __unicode__(self) -> str: ... + def __contains__(self, entry: _TB) -> bool: ... # type: ignore[override] # AttributeError otherwise def __eq__(self, other: object) -> bool: ... def append(self, entry: _TB) -> None: ... def insert(self, index: SupportsIndex, entry: _TB) -> None: ... def metadata_as_entry(self) -> POEntry: ... - def save(self, fpath: Text | None = ..., repr_method: str = ...) -> None: ... - def find(self, st: Text, by: str = ..., include_obsolete_entries: bool = ..., msgctxt: bool = ...) -> _TB | None: ... - def ordered_metadata(self) -> list[tuple[Text, Text]]: ... + def save(self, fpath: str | None = ..., repr_method: str = ..., newline: str | None = ...) -> None: ... + def find( + self, st: str, by: str = ..., include_obsolete_entries: bool = ..., msgctxt: str | Literal[False] = ... + ) -> _TB | None: ... + def ordered_metadata(self) -> list[tuple[str, str]]: ... def to_binary(self) -> bytes: ... class POFile(_BaseFile[POEntry]): - def __unicode__(self) -> Text: ... - def save_as_mofile(self, fpath: Text) -> None: ... + def __unicode__(self) -> str: ... + def save_as_mofile(self, fpath: str) -> None: ... def percent_translated(self) -> int: ... def translated_entries(self) -> list[POEntry]: ... def untranslated_entries(self) -> list[POEntry]: ... @@ -60,64 +64,66 @@ class MOFile(_BaseFile[MOEntry]): version: int def __init__(self, *args: Any, **kwargs: Any) -> None: ... def save_as_pofile(self, fpath: str) -> None: ... - def save(self, fpath: Text | None = ...) -> None: ... # type: ignore # binary file does not allow argument repr_method + def save(self, fpath: str | None = ...) -> None: ... # type: ignore[override] # binary file does not allow argument repr_method def percent_translated(self) -> int: ... def translated_entries(self) -> list[MOEntry]: ... def untranslated_entries(self) -> list[MOEntry]: ... def fuzzy_entries(self) -> list[MOEntry]: ... def obsolete_entries(self) -> list[MOEntry]: ... -class _BaseEntry(object): - msgid: Text - msgstr: Text - msgid_plural: Text - msgstr_plural: list[Text] - msgctxt: Text +class _BaseEntry: + msgid: str + msgstr: str + msgid_plural: str + msgstr_plural: dict[int, str] + msgctxt: str obsolete: bool encoding: str def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def __unicode__(self, wrapwidth: int = ...) -> Text: ... + def __unicode__(self, wrapwidth: int = ...) -> str: ... def __eq__(self, other: object) -> bool: ... + @property + def msgid_with_context(self) -> str: ... class POEntry(_BaseEntry): - comment: Text - tcomment: Text - occurrences: list[tuple[str, int]] - flags: list[Text] - previous_msgctxt: Text | None - previous_msgid: Text | None - previous_msgid_plural: Text | None + comment: str + tcomment: str + occurrences: list[tuple[str, str]] + flags: list[str] + previous_msgctxt: str | None + previous_msgid: str | None + previous_msgid_plural: str | None linenum: int | None def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def __unicode__(self, wrapwidth: int = ...) -> Text: ... + def __unicode__(self, wrapwidth: int = ...) -> str: ... def __cmp__(self, other: POEntry) -> int: ... def __gt__(self, other: POEntry) -> bool: ... def __lt__(self, other: POEntry) -> bool: ... def __ge__(self, other: POEntry) -> bool: ... def __le__(self, other: POEntry) -> bool: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def __eq__(self, other: POEntry) -> bool: ... # type: ignore[override] + def __ne__(self, other: POEntry) -> bool: ... # type: ignore[override] def translated(self) -> bool: ... def merge(self, other: POEntry) -> None: ... @property def fuzzy(self) -> bool: ... @property - def msgid_with_context(self) -> Text: ... + def msgid_with_context(self) -> str: ... def __hash__(self) -> int: ... class MOEntry(_BaseEntry): - comment: Text - tcomment: Text - occurrences: list[tuple[str, int]] - flags: list[Text] - previous_msgctxt: Text | None - previous_msgid: Text | None - previous_msgid_plural: Text | None + comment: str + tcomment: str + occurrences: list[tuple[str, str]] + flags: list[str] + previous_msgctxt: str | None + previous_msgid: str | None + previous_msgid_plural: str | None def __init__(self, *args: Any, **kwargs: Any) -> None: ... def __hash__(self) -> int: ... class _POFileParser(Generic[_TP]): - fhandle: IO[Text] + fhandle: IO[str] instance: _TP transitions: dict[tuple[str, str], tuple[Callable[[], bool], str]] current_line: int @@ -126,7 +132,7 @@ class _POFileParser(Generic[_TP]): current_token: str | None msgstr_index: int entry_obsolete: int - def __init__(self, pofile: Text, *args: Any, **kwargs: Any) -> None: ... + def __init__(self, pofile: str, *args: Any, **kwargs: Any) -> None: ... def parse(self) -> _TP: ... def add(self, symbol: str, states: list[str], next_state: str) -> None: ... def process(self, symbol: str) -> None: ... @@ -148,10 +154,19 @@ class _POFileParser(Generic[_TP]): class _MOFileParser(Generic[_TM]): fhandle: IO[bytes] instance: _TM - def __init__(self, mofile: Text, *args: Any, **kwargs: Any) -> None: ... + def __init__(self, mofile: str, *args: Any, **kwargs: Any) -> None: ... def __del__(self) -> None: ... def parse(self) -> _TM: ... -class TextWrapper(textwrap.TextWrapper): - drop_whitespace: bool - def __init__(self, *args: Any, **kwargs: Any) -> None: ... +__all__ = [ + "pofile", + "POFile", + "POEntry", + "mofile", + "MOFile", + "MOEntry", + "default_encoding", + "escape", + "unescape", + "detect_encoding", +] diff --git a/stubs/pony/@tests/stubtest_allowlist.txt b/stubs/pony/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5592e76d682c --- /dev/null +++ b/stubs/pony/@tests/stubtest_allowlist.txt @@ -0,0 +1,14 @@ +# Tests should not be part of the stubs +pony.orm.tests.* + +# Modules with ImportError, cannot import third-party libraries: +pony.flask.* +pony.orm.dbproviders.cockroach +pony.orm.dbproviders.mysql +pony.orm.dbproviders.oracle +pony.orm.dbproviders.postgres +pony.orm.integration.bottle_plugin +pony.orm.examples.bottle_example + +# TODO: Incomplete issues in examples dir: +pony.orm.examples.* diff --git a/stubs/pony/METADATA.toml b/stubs/pony/METADATA.toml new file mode 100644 index 000000000000..e5e65e786651 --- /dev/null +++ b/stubs/pony/METADATA.toml @@ -0,0 +1,3 @@ +version = "~=0.7.20" +upstream-repository = "https://github.com/ponyorm/pony" +optional-dependencies = ["types-psycopg2", "types-PyMySQL"] diff --git a/stubs/pony/pony/__init__.pyi b/stubs/pony/pony/__init__.pyi new file mode 100644 index 000000000000..3a6a1123886a --- /dev/null +++ b/stubs/pony/pony/__init__.pyi @@ -0,0 +1,13 @@ +from typing import Final, Literal, TypeAlias + +_Mode: TypeAlias = Literal[ + "GAE-LOCAL", "GAE-SERVER", "MOD_WSGI", "INTERACTIVE", "FCGI-FLUP", "UWSGI", "FLASK", "CHERRYPY", "BOTTLE", "UNKNOWN" +] +__version__: Final[str] + +def detect_mode() -> _Mode: ... + +MODE: Final[_Mode] +MAIN_FILE: Final[str | None] +MAIN_DIR: Final[str | None] +PONY_DIR: Final[str] diff --git a/stubs/pony/pony/converting.pyi b/stubs/pony/pony/converting.pyi new file mode 100644 index 000000000000..631da5e69398 --- /dev/null +++ b/stubs/pony/pony/converting.pyi @@ -0,0 +1,48 @@ +import re +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Sequence +from datetime import date, datetime, time, timedelta +from typing import Any, Literal + +class ValidationError(ValueError): ... + +def check_ip(s: str) -> str: ... +def check_positive(s: ConvertibleToInt) -> int: ... +def check_identifier(s: str) -> str: ... + +isbn_re: re.Pattern[str] + +def isbn10_checksum(digits: Sequence[ConvertibleToInt]) -> str: ... +def isbn13_checksum(digits: Sequence[ConvertibleToInt]) -> str: ... +def check_isbn(s: str, convert_to: Literal[10, 13] | None = None) -> str: ... +def isbn10_to_isbn13(s: str) -> str: ... +def isbn13_to_isbn10(s: str) -> str: ... + +email_re: re.Pattern[str] +rfc2822_email_re: re.Pattern[str] + +def check_email(s: str) -> str: ... +def check_rfc2822_email(s: str) -> str: ... + +date_str_list: list[str] +date_re_list: list[re.Pattern[str]] +time_str: str +time_re: re.Pattern[str] +datetime_re_list: list[re.Pattern[str]] +month_lists: list[list[str]] +month_list: list[str] +i: int +month: str +month_dict: dict[str, int] + +def str2date(s: str) -> date: ... +def str2time(s: str) -> time: ... +def str2datetime(s: str) -> datetime: ... +def str2timedelta(s: str) -> timedelta: ... +def timedelta2str(td: timedelta) -> str: ... + +converters: dict[type | str, tuple[Callable[[str], Any], type[str], str | None]] # Any type from types above + +def str2py( + value: str, type: str | type | tuple[Callable[[str], Any], type[str], str | None] | None +) -> Any: ... # Any type from types above diff --git a/stubs/pony/pony/flask/__init__.pyi b/stubs/pony/pony/flask/__init__.pyi new file mode 100644 index 000000000000..080bcc2272aa --- /dev/null +++ b/stubs/pony/pony/flask/__init__.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from types import ModuleType +from typing import Protocol, type_check_only + +# Protocol for flask.Flask class +@type_check_only +class _Flask(Protocol): + def before_request(self, f): ... + def after_request(self, f): ... + def teardown_request(self, f): ... + +flask_lib: ModuleType +request: Incomplete + +class Pony: + app: _Flask | None + def __init__(self, app: _Flask | None = None) -> None: ... + def init_app(self, app: _Flask) -> None: ... diff --git a/stubs/pony/pony/flask/example/__init__.pyi b/stubs/pony/pony/flask/example/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/flask/example/app.pyi b/stubs/pony/pony/flask/example/app.pyi new file mode 100644 index 000000000000..b45476eba0d9 --- /dev/null +++ b/stubs/pony/pony/flask/example/app.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from pony.flask import _Flask + +app: _Flask +login_manager: Incomplete + +def load_user(user_id): ... diff --git a/stubs/pony/pony/flask/example/config.pyi b/stubs/pony/pony/flask/example/config.pyi new file mode 100644 index 000000000000..0a7fba4bec91 --- /dev/null +++ b/stubs/pony/pony/flask/example/config.pyi @@ -0,0 +1 @@ +config: dict[str, bool | str | dict[str, str | bool]] diff --git a/stubs/pony/pony/flask/example/models.pyi b/stubs/pony/pony/flask/example/models.pyi new file mode 100644 index 000000000000..290f90e958b2 --- /dev/null +++ b/stubs/pony/pony/flask/example/models.pyi @@ -0,0 +1,10 @@ +from datetime import datetime + +from pony.orm.core import Database, Entity + +db: Database + +class User(Entity): + login: str + password: str + last_login: datetime | None diff --git a/stubs/pony/pony/flask/example/views.pyi b/stubs/pony/pony/flask/example/views.pyi new file mode 100644 index 000000000000..2043cc5ca582 --- /dev/null +++ b/stubs/pony/pony/flask/example/views.pyi @@ -0,0 +1,4 @@ +def index() -> str: ... +def login(): ... +def reg(): ... +def logout(): ... diff --git a/stubs/pony/pony/options.pyi b/stubs/pony/pony/options.pyi new file mode 100644 index 000000000000..c65f52a795c0 --- /dev/null +++ b/stubs/pony/pony/options.pyi @@ -0,0 +1,39 @@ +from typing import Final + +DEBUG: Final[bool] +STATIC_DIR: Final[None] +CUT_TRACEBACK: Final[bool] +STD_DOCTYPE: Final[str] +STD_STYLESHEETS: Final[list[tuple[str, ...]]] +BASE_STYLESHEETS_PLACEHOLDER: Final[str] +COMPONENT_STYLESHEETS_PLACEHOLDER: Final[str] +SCRIPTS_PLACEHOLDER: Final[str] +RELOADING_CHECK_INTERVAL: Final[float] +LOG_TO_SQLITE: Final[None] +LOGGING_LEVEL: Final[None] +LOGGING_PONY_LEVEL: Final[None] +MAX_SESSION_CTIME: Final[int] +MAX_SESSION_MTIME: Final[int] +MAX_LONGLIFE_SESSION: Final[int] +COOKIE_SERIALIZATION_TYPE: Final[str] +COOKIE_NAME: Final[str] +COOKIE_PATH: Final[str] +COOKIE_DOMAIN: Final[None] +HASH_ALGORITHM: Final[None] +SESSION_STORAGE: Final[None] +MEMCACHE: Final[None] +ALTERNATIVE_SESSION_MEMCACHE: Final[None] +ALTERNATIVE_ORM_MEMCACHE: Final[None] +ALTERNATIVE_TEMPLATING_MEMCACHE: Final[None] +ALTERNATIVE_RESPONSE_MEMCACHE: Final[None] +PICKLE_START_OFFSET: Final[int] +PICKLE_HTML_AS_PLAIN_STR: Final[bool] +RESTORE_ESCAPES: Final[bool] +SOURCE_ENCODING: Final[None] +CONSOLE_ENCODING: Final[None] +MAX_FETCH_COUNT: Final[None] +CONSOLE_WIDTH: Final[int] +SIMPLE_ALIASES: Final[bool] +INNER_JOIN_SYNTAX: Final[bool] +DEBUGGING_REMOVE_ADDR: Final[bool] +DEBUGGING_RESTORE_ESCAPES: Final[bool] diff --git a/stubs/pony/pony/orm/__init__.pyi b/stubs/pony/pony/orm/__init__.pyi new file mode 100644 index 000000000000..e1dd6b0275cb --- /dev/null +++ b/stubs/pony/pony/orm/__init__.pyi @@ -0,0 +1 @@ +from pony.orm.core import * diff --git a/stubs/pony/pony/orm/asttranslation.pyi b/stubs/pony/pony/orm/asttranslation.pyi new file mode 100644 index 000000000000..ff6469b2cb23 --- /dev/null +++ b/stubs/pony/pony/orm/asttranslation.pyi @@ -0,0 +1,139 @@ +import ast +import sys +from _typeshed import Incomplete +from collections.abc import Callable, Generator +from typing import Any, TypeVar + +_T = TypeVar("_T") + +class TranslationError(Exception): ... + +pre_method_caches: dict[type[ASTTranslator], dict[type[ast.AST], Callable[..., Any]]] +post_method_caches: dict[type[ASTTranslator], dict[type[ast.AST], Callable[..., Any]]] + +class ASTTranslator: + tree: Incomplete + def __init__(self, tree) -> None: ... + def dispatch(self, node: ast.AST) -> None: ... + def call(self, method: Callable[[ASTTranslator, ast.AST], _T], node: ast.AST) -> _T | None: ... + def default_pre(self, node: ast.AST) -> None: ... + def default_post(self, node: ast.AST) -> None: ... + +def priority(p: int): ... +def binop_src(op: str, node) -> str: ... +def ast2src(tree): ... +def get_child_nodes(node: ast.AST) -> Generator[ast.AST]: ... + +class PythonTranslator(ASTTranslator): + def __init__(self, tree) -> None: ... + def call(self, method, node) -> None: ... + def default_pre(self, node: ast.AST): ... + def default_post(self, node: ast.AST) -> None: ... + def postGeneratorExp(self, node: ast.GeneratorExp) -> str: ... + def postcomprehension(self, node: ast.comprehension) -> str: ... + def postGenExprIf(self, node) -> str: ... + def postExpr(self, node: ast.Expr) -> str: ... + def postIfExp(self, node: ast.IfExp) -> str: ... + def postLambda(self, node: ast.Lambda) -> str: ... + def postarguments(self, node: ast.arguments) -> str: ... + def postarg(self, node: ast.arg) -> str: ... + def postOr(self, node: ast.Or) -> str: ... + def postAnd(self, node: ast.And) -> str: ... + def postNot(self, node: ast.Not) -> str: ... + def postCompare(self, node: ast.Compare) -> str: ... + def postEq(self, node: ast.Eq) -> str: ... + def postNotEq(self, node: ast.NotEq) -> str: ... + def postLt(self, node: ast.Lt) -> str: ... + def postLtE(self, node: ast.LtE) -> str: ... + def postGt(self, node: ast.Gt) -> str: ... + def postGtE(self, node: ast.GtE) -> str: ... + def postIs(self, node: ast.Is) -> str: ... + def postIsNot(self, node: ast.IsNot) -> str: ... + def postIn(self, node: ast.In) -> str: ... + def postNotIn(self, node: ast.NotIn) -> str: ... + def postBitOr(self, node: ast.BitOr) -> str: ... + def postBitXor(self, node: ast.BitXor) -> str: ... + def postBitAnd(self, node: ast.BitAnd) -> str: ... + def postLShift(self, node: ast.LShift) -> str: ... + def postRShift(self, node: ast.RShift) -> str: ... + def postAdd(self, node: ast.Add) -> str: ... + def postSub(self, node: ast.Sub) -> str: ... + def postMult(self, node: ast.Mult): ... + def postMatMult(self, node: ast.MatMult) -> None: ... + def postDiv(self, node: ast.Div) -> str: ... + def postFloorDiv(self, node: ast.FloorDiv) -> str: ... + def postMod(self, node: ast.Mod) -> str: ... + def postUSub(self, node: ast.USub) -> str: ... + def postUAdd(self, node: ast.UAdd) -> str: ... + def postInvert(self, node: ast.Invert) -> str: ... + def postPow(self, node: ast.Pow) -> str: ... + def postAttribute(self, node: ast.Attribute) -> str: ... + def postCall(self, node: ast.Call) -> str: ... + def postkeyword(self, node: ast.keyword) -> str: ... + def postStarred(self, node: ast.Starred) -> str: ... + def postSubscript(self, node: ast.Subscript) -> str: ... + def postIndex(self, node: ast.Index) -> str: ... + def postSlice(self, node: ast.Slice) -> str: ... + def postConstant(self, node: ast.Constant) -> str: ... + if sys.version_info >= (3, 14): + def postNameConstant(self, node: ast.Constant) -> str: ... + def postNum(self, node: ast.Constant) -> str: ... + def postStr(self, node: ast.Constant) -> str: ... + def postBytes(self, node: ast.Constant) -> str: ... + else: + def postNameConstant(self, node: ast.NameConstant) -> str: ... + def postNum(self, node: ast.Num) -> str: ... + def postStr(self, node: ast.Str) -> str: ... + def postBytes(self, node: ast.Bytes) -> str: ... + + def postList(self, node: ast.List) -> str: ... + def postTuple(self, node: ast.Tuple) -> str: ... + def postDict(self, node: ast.Dict) -> str: ... + def postSet(self, node: ast.Set) -> str: ... + def postName(self, node: ast.Name) -> str: ... + def postJoinedStr(self, node: ast.JoinedStr) -> str: ... + def postFormattedValue(self, node: ast.FormattedValue) -> str: ... + +nonexternalizable_types: tuple[type[ast.AST], ...] + +class PreTranslator(ASTTranslator): + def __init__(self, tree, globals, locals, special_functions, const_functions, outer_names=()) -> None: ... + def dispatch(self, node) -> None: ... + def preGeneratorExp(self, node: ast.GeneratorExp) -> bool: ... + def preLambda(self, node: ast.Lambda) -> bool: ... + def postName(self, node: ast.Name) -> None: ... + def postSlice(self, node: ast.Slice) -> None: ... + def postStarred(self, node: ast.Starred) -> None: ... + def postConstant(self, node: ast.Constant) -> None: ... + if sys.version_info >= (3, 14): + def postNum(self, node: ast.Constant) -> None: ... + def postStr(self, node: ast.Constant) -> None: ... + def postBytes(self, node: ast.Constant) -> None: ... + else: + def postNum(self, node: ast.Num) -> None: ... + def postStr(self, node: ast.Str) -> None: ... + def postBytes(self, node: ast.Bytes) -> None: ... + + def postDict(self, node: ast.Dict) -> None: ... + def postList(self, node: ast.List) -> None: ... + def postkeyword(self, node: ast.keyword) -> None: ... + def postIndex(self, node: ast.Index) -> None: ... + def postCall(self, node: ast.Call) -> None: ... + def postCompare(self, node: ast.Compare) -> None: ... + def post_binop(self, node: ast.BinOp) -> None: ... + def postBitOr(self, node: ast.BitOr) -> None: ... + def postBitXor(self, node: ast.BitXor) -> None: ... + def postBitAnd(self, node: ast.BitAnd) -> None: ... + def postLShift(self, node: ast.LShift) -> None: ... + def postRShift(self, node: ast.RShift) -> None: ... + def postAdd(self, node: ast.Add) -> None: ... + def postSub(self, node: ast.Sub) -> None: ... + def postMult(self, node: ast.Mult) -> None: ... + def postMatMult(self, node: ast.MatMult) -> None: ... + def postDiv(self, node: ast.Div) -> None: ... + def postFloorDiv(self, node: ast.FloorDiv) -> None: ... + def postMod(self, node: ast.Mod) -> None: ... + +extractors_cache: dict[str | int, tuple[Incomplete, dict[Incomplete, Incomplete]]] + +def create_extractors(code_key: str | int, tree, globals, locals, special_functions, const_functions, outer_names=()): ... diff --git a/stubs/pony/pony/orm/core.pyi b/stubs/pony/pony/orm/core.pyi new file mode 100644 index 000000000000..eca1d4d6dbe3 --- /dev/null +++ b/stubs/pony/pony/orm/core.pyi @@ -0,0 +1,918 @@ +import ast +import itertools +import re +import types +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Callable, Generator +from logging import Logger +from typing import Literal, TypeAlias, TypeVar +from typing_extensions import Never, Self, deprecated + +import pony as pony +from pony.orm.asttranslation import TranslationError as TranslationError +from pony.orm.dbapiprovider import ( + DatabaseError as DatabaseError, + DataError as DataError, + DBException as DBException, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, +) +from pony.orm.ormtypes import ( + Array, + FloatArray as FloatArray, + IntArray as IntArray, + Json as Json, + LongStr as LongStr, + LongUnicode as LongUnicode, + StrArray as StrArray, + raw_sql as raw_sql, +) +from pony.py23compat import buffer as buffer, unicode as unicode +from pony.utils import between as between, coalesce as coalesce, concat as concat, localbase + +_T = TypeVar("_T") +_KnownProvider: TypeAlias = Literal["sqlite", "postgres", "mysql", "oracle"] + +__all__ = [ + "pony", + "DBException", + "RowNotFound", + "MultipleRowsFound", + "TooManyRowsFound", + "Warning", + "Error", + "InterfaceError", + "DatabaseError", + "DataError", + "OperationalError", + "IntegrityError", + "InternalError", + "ProgrammingError", + "NotSupportedError", + "OrmError", + "ERDiagramError", + "DBSchemaError", + "MappingError", + "BindingError", + "TableDoesNotExist", + "TableIsNotEmpty", + "ConstraintError", + "CacheIndexError", + "ObjectNotFound", + "MultipleObjectsFoundError", + "TooManyObjectsFoundError", + "OperationWithDeletedObjectError", + "TransactionError", + "ConnectionClosedError", + "TransactionIntegrityError", + "IsolationError", + "CommitException", + "RollbackException", + "UnrepeatableReadError", + "OptimisticCheckError", + "UnresolvableCyclicDependency", + "UnexpectedError", + "DatabaseSessionIsOver", + "PonyRuntimeWarning", + "DatabaseContainsIncorrectValue", + "DatabaseContainsIncorrectEmptyValue", + "TranslationError", + "ExprEvalError", + "PermissionError", + "Database", + "sql_debug", + "set_sql_debug", + "sql_debugging", + "show", + "PrimaryKey", + "Required", + "Optional", + "Set", + "Discriminator", + "composite_key", + "composite_index", + "flush", + "commit", + "rollback", + "db_session", + "with_transaction", + "make_proxy", + "LongStr", + "LongUnicode", + "Json", + "IntArray", + "StrArray", + "FloatArray", + "select", + "left_join", + "get", + "exists", + "delete", + "count", + "sum", + "min", + "max", + "avg", + "group_concat", + "distinct", + "JOIN", + "desc", + "between", + "concat", + "coalesce", + "raw_sql", + "buffer", + "unicode", + "get_current_user", + "set_current_user", + "perm", + "has_perm", + "get_user_groups", + "get_user_roles", + "get_object_labels", + "user_groups_getter", + "user_roles_getter", + "obj_labels_getter", +] + +suppress_debug_change: bool + +def sql_debug(value: bool) -> None: ... +def set_sql_debug(debug: bool = True, show_values=None) -> None: ... + +orm_logger: Logger +sql_logger: Logger +orm_log_level: int + +def log_orm(msg: object) -> None: ... +def args2str(args: list[object] | tuple[object] | dict[object, object]) -> str: ... + +class OrmError(Exception): ... +class ERDiagramError(OrmError): ... +class DBSchemaError(OrmError): ... +class MappingError(OrmError): ... +class BindingError(OrmError): ... +class TableDoesNotExist(OrmError): ... +class TableIsNotEmpty(OrmError): ... +class ConstraintError(OrmError): ... +class CacheIndexError(OrmError): ... +class RowNotFound(OrmError): ... +class MultipleRowsFound(OrmError): ... +class TooManyRowsFound(OrmError): ... +class PermissionError(OrmError): ... + +class ObjectNotFound(OrmError): + def __init__( + self, entity: Entity, pkval: object | tuple[object, ...] | None = None # pkval passing to repr() builtins function + ) -> None: ... + +class MultipleObjectsFoundError(OrmError): ... +class TooManyObjectsFoundError(OrmError): ... +class OperationWithDeletedObjectError(OrmError): ... +class TransactionError(OrmError): ... +class ConnectionClosedError(TransactionError): ... + +class TransactionIntegrityError(TransactionError): + def __init__(self, msg, original_exc=None) -> None: ... + +class CommitException(TransactionError): + def __init__(self, msg, exceptions) -> None: ... + +class PartialCommitException(TransactionError): + def __init__(self, msg, exceptions) -> None: ... + +class RollbackException(TransactionError): + def __init__(self, msg, exceptions) -> None: ... + +class DatabaseSessionIsOver(TransactionError): ... + +TransactionRolledBack = DatabaseSessionIsOver + +class IsolationError(TransactionError): ... +class UnrepeatableReadError(IsolationError): ... +class OptimisticCheckError(IsolationError): ... +class UnresolvableCyclicDependency(TransactionError): ... + +class UnexpectedError(TransactionError): + def __init__(self, msg, original_exc) -> None: ... + +class ExprEvalError(TranslationError): + def __init__(self, src, cause) -> None: ... + +class PonyInternalException(Exception): ... +class OptimizationFailed(PonyInternalException): ... + +class UseAnotherTranslator(PonyInternalException): + translator: Incomplete + def __init__(self, translator) -> None: ... + +class PonyRuntimeWarning(RuntimeWarning): ... +class DatabaseContainsIncorrectValue(PonyRuntimeWarning): ... +class DatabaseContainsIncorrectEmptyValue(DatabaseContainsIncorrectValue): ... + +class PrefetchContext: + database: Incomplete + attrs_to_prefetch_dict: Incomplete + entities_to_prefetch: Incomplete + relations_to_prefetch_cache: Incomplete + def __init__(self, database=None) -> None: ... + def copy(self): ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def get_frozen_attrs_to_prefetch(self, entity): ... + def get_relations_to_prefetch(self, entity): ... + +class Local(localbase): + def __init__(self) -> None: ... + @property + def prefetch_context(local): ... + def push_debug_state(self, debug, show_values) -> None: ... + def pop_debug_state(self) -> None: ... + +local: Local + +def flush() -> None: ... +def commit() -> None: ... +def rollback() -> None: ... + +class DBSessionContextManager: + __slots__ = ( + "retry", + "retry_exceptions", + "allowed_exceptions", + "immediate", + "ddl", + "serializable", + "strict", + "optimistic", + "sql_debug", + "show_values", + ) + retry: int + ddl: bool + serializable: bool + immediate: bool + strict: bool + optimistic: bool + retry_exceptions: tuple[type[Exception], ...] + allowed_exceptions: tuple[type[Exception], ...] + sql_debug: bool | None + show_values: bool | None + def __init__( + self, + retry: int = 0, + immediate: bool = False, + ddl: bool = False, + serializable: bool = False, + strict: bool = False, + optimistic: bool = True, + retry_exceptions: tuple[type[Exception], ...] = ..., + allowed_exceptions: tuple[type[Exception], ...] = (), + sql_debug: bool | None = None, + show_values: bool | None = None, + ) -> None: ... + def __call__(self, *args, **kwargs): ... + def __enter__(db_session) -> None: ... + def __exit__(db_session, exc_type=None, exc=None, tb=None) -> None: ... + +db_session: DBSessionContextManager + +class SQLDebuggingContextManager: + debug: bool + show_values: Incomplete + def __init__(self, debug: bool = True, show_values=None) -> None: ... + def __call__(self, *args, **kwargs): ... + def __enter__(self) -> None: ... + def __exit__(self, exc_type=None, exc=None, tb=None) -> None: ... + +sql_debugging: SQLDebuggingContextManager + +def throw_db_session_is_over(action: str, obj: Entity, attr: Attribute | None = None) -> Never: ... +@deprecated("@with_transaction decorator is deprecated, use @db_session decorator instead.") +def with_transaction(*args, **kwargs): ... + +known_providers: tuple[_KnownProvider, ...] + +class OnConnectDecorator: + @staticmethod + def check_provider(provider: str | None) -> None: ... + provider: _KnownProvider | None + database: Incomplete + def __init__(self, database: Database, provider: str | None) -> None: ... + def __call__(self, func: types.FunctionType | None = None, provider: str | None = None) -> Self: ... + +db_id_counter: itertools.count[int] + +class Database: + def __deepcopy__(self, memo) -> Self: ... + id: Incomplete + priority: int + entities: Incomplete + schema: Incomplete + Entity: type[Entity] + on_connect: OnConnectDecorator + provider: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def call_on_connect(self, con) -> None: ... + def bind(self, *args, **kwargs) -> None: ... + @property + def last_sql(database): ... + @property + def local_stats(database): ... + def merge_local_stats(self) -> None: ... + @property + def global_stats(database): ... + @property + @deprecated("global_stats_lock is deprecated, just use global_stats property without any locking.") + def global_stats_lock(database): ... + def get_connection(self): ... + def disconnect(self) -> None: ... + def flush(self) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def execute(self, sql, globals=None, locals=None): ... + def select(self, sql, globals=None, locals=None, frame_depth: int = 0): ... + def get(self, sql, globals=None, locals=None): ... + def exists(self, sql, globals=None, locals=None): ... + def insert(self, table_name, returning=None, **kwargs): ... + def generate_mapping(self, filename=None, check_tables: bool = True, create_tables: bool = False): ... + def drop_table(self, table_name, if_exists: bool = False, with_all_data: bool = False) -> None: ... + def drop_all_tables(self, with_all_data: bool = False) -> None: ... + def create_tables(self, check_tables: bool = False) -> None: ... + def check_tables(self) -> None: ... + def set_perms_for(self, *entities) -> Generator[None]: ... + def to_json(self, data, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + def from_json(self, changes, observer=None): ... + +def basic_converter(x): ... +def perm(*args, **kwargs) -> AccessRule: ... +def pop_names_from_kwargs(typename, kwargs, *kwnames): ... + +class AccessRule: + def __init__(self, database, entities, permissions, groups, roles, labels) -> None: ... + def exclude(self, *args) -> None: ... + +def has_perm(user, perm, x) -> bool: ... +def can_view(user, x) -> bool: ... +def can_edit(user, x) -> bool: ... +def can_create(user, x) -> bool: ... +def can_delete(user, x) -> bool: ... +def get_current_user(): ... +def set_current_user(user) -> None: ... + +anybody_frozenset: frozenset[str] + +def get_user_groups(user): ... +def get_user_roles(user, obj): ... +def get_object_labels(obj): ... + +usergroup_functions: list[Incomplete] + +def user_groups_getter(cls=None): ... + +userrole_functions: list[Incomplete] + +def user_roles_getter(user_cls=None, obj_cls=None): ... + +objlabel_functions: list[Incomplete] + +def obj_labels_getter(cls=None): ... + +class DbLocal(localbase): + stats: Incomplete + last_sql: Incomplete + def __init__(self) -> None: ... + +class QueryStat: + def __init__(self, sql, duration=None) -> None: ... + def copy(self): ... + def query_executed(self, duration) -> None: ... + def merge(self, stat2) -> None: ... + @property + def avg_time(stat): ... + +num_counter: itertools.count[int] + +class SessionCache: + is_alive: bool + num: int + database: Database + objects: set[Incomplete] + indexes: defaultdict[Incomplete, dict[Incomplete, Incomplete]] | None + seeds: defaultdict[Incomplete, set[Incomplete]] | None + max_id_cache: dict[Incomplete, Incomplete] | None + collection_statistics: dict[Incomplete, Incomplete] | None + for_update: set[Incomplete] | None + noflush_counter: int + modified_collections: defaultdict[Incomplete, set[Incomplete]] | None + objects_to_save: list[Incomplete] | None + saved_objects: list[Incomplete] | None + query_results: dict[Incomplete, Incomplete] | None + dbvals_deduplication_cache: defaultdict[Incomplete, dict[Incomplete, Incomplete]] | None + modified: bool + db_session: Incomplete + immediate: bool + connection: Incomplete + in_transaction: bool + saved_fk_state: Incomplete + perm_cache: Incomplete + user_roles_cache: defaultdict[Incomplete, dict[Incomplete, Incomplete]] | None + obj_labels_cache: dict[Incomplete, Incomplete] | None + def __init__(self, database: Database) -> None: ... + def connect(self): ... + def reconnect(self, exc): ... + def prepare_connection_for_query_execution(self): ... + def flush_and_commit(self) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def release(self) -> None: ... + def close(self, rollback: bool = True) -> None: ... + def flush_disabled(self) -> Generator[None]: ... + def flush(self) -> None: ... + def call_after_save_hooks(self) -> None: ... + def update_simple_index(self, obj, attr, old_val, new_val, undo) -> None: ... + def db_update_simple_index(self, obj, attr, old_dbval, new_dbval) -> None: ... + def update_composite_index(self, obj, attrs, prev_vals, new_vals, undo) -> None: ... + def db_update_composite_index(self, obj, attrs, prev_vals, new_vals) -> None: ... + +class NotLoadedValueType: ... + +NOT_LOADED: NotLoadedValueType + +class DefaultValueType: ... + +DEFAULT: DefaultValueType + +class DescWrapper: + attr: Attribute + def __init__(self, attr: Attribute) -> None: ... + def __call__(self) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +attr_id_counter: itertools.count[int] + +class Attribute: + __slots__ = ( + "nullable", + "is_required", + "is_discriminator", + "is_unique", + "is_part_of_unique_index", + "is_pk", + "is_collection", + "is_relation", + "is_basic", + "is_string", + "is_volatile", + "is_implicit", + "id", + "pk_offset", + "pk_columns_offset", + "py_type", + "sql_type", + "entity", + "name", + "lazy", + "lazy_sql_cache", + "args", + "auto", + "default", + "reverse", + "composite_keys", + "column", + "columns", + "col_paths", + "_columns_checked", + "converters", + "kwargs", + "cascade_delete", + "index", + "reverse_index", + "original_default", + "sql_default", + "py_check", + "hidden", + "optimistic", + "fk_name", + "type_has_empty_value", + "interleave", + ) + nullable: bool | None + is_required: bool + is_discriminator: bool + is_unique: bool | None + is_part_of_unique_index: bool | None + is_pk: bool + is_collection: bool + is_relation: bool + is_basic: bool + is_string: bool + is_volatile: bool + is_implicit: bool + id: int + pk_offset: int | None + pk_columns_offset: int + py_type: type | str | types.FunctionType | Array + sql_type: Incomplete + entity: Incomplete + name: Incomplete + lazy: bool + lazy_sql_cache: Incomplete + args: tuple[Incomplete, ...] + auto: bool + default: Incomplete + reverse: str | Attribute | None + composite_keys: list[tuple[Incomplete, int]] + column: str | None + columns: list[str] | tuple[str, ...] + col_paths: list[Incomplete] + converters: list[Incomplete] + kwargs: dict[str, Incomplete] + cascade_delete: bool | None + index: str | bool | None + reverse_index: Incomplete + original_default: Incomplete + sql_default: str | bool | None + py_check: Callable[..., bool] | None + hidden: bool + optimistic: bool | None + fk_name: str | None + type_has_empty_value: bool + interleave: bool | None + def __deepcopy__(attr, memo): ... + def __init__(self, py_type: type | str | types.FunctionType | Array, *args, **kwargs) -> None: ... + def linked(self) -> None: ... + def __lt__(attr, other): ... + def validate(self, val, obj=None, entity=None, from_db: bool = False): ... + def parse_value(self, row, offsets, dbvals_deduplication_cache): ... + def load(self, obj: Entity): ... + def __get__(attr, obj, cls=None): ... + def get(self, obj): ... + def __set__(attr, obj, new_val, undo_funcs=None) -> None: ... + def db_set(self, obj, new_dbval, is_reverse_call: bool = False) -> None: ... + def update_reverse(self, obj, old_val, new_val, undo_funcs) -> None: ... + def db_update_reverse(self, obj, old_dbval, new_dbval) -> None: ... + def __delete__(attr, obj) -> None: ... + def get_raw_values(self, val): ... + def get_columns(self) -> list[str] | tuple[str, ...]: ... + @property + def asc(attr) -> Self: ... + @property + def desc(attr) -> DescWrapper: ... + def describe(self) -> str: ... + +class Optional(Attribute): + __slots__: list[str] = [] + +class Required(Attribute): + __slots__: list[str] = [] + def validate(self, val, obj=None, entity=None, from_db: bool = False): ... + +class Discriminator(Required): + __slots__ = ["code2cls"] + code2cls: dict[Incomplete, Incomplete] + def __init__(self, py_type, *args, **kwargs) -> None: ... + @staticmethod + def create_default_attr(entity) -> None: ... + def process_entity_inheritance(self, entity) -> None: ... + def validate(self, val, obj=None, entity=None, from_db: bool = False): ... + def load(self, obj) -> None: ... + def __get__(attr, obj, cls=None): ... + def __set__(attr, obj, new_val) -> None: ... # type: ignore[override] + def db_set(self, obj, new_dbval) -> None: ... # type: ignore[override] + def update_reverse(self, obj, old_val, new_val, undo_funcs) -> None: ... + +class Index: + __slots__ = ("entity", "attrs", "is_pk", "is_unique") + entity: Incomplete + attrs: list[Incomplete] + is_pk: bool + is_unique: bool + def __init__(self, *attrs, **options) -> None: ... + +def composite_index(*attrs) -> None: ... +def composite_key(*attrs) -> None: ... + +class PrimaryKey(Required): + __slots__: list[str] = [] + def __new__(cls, *args, **kwargs): ... + +class Collection(Attribute): + __slots__ = ( + "table", + "wrapper_class", + "symmetric", + "reverse_column", + "reverse_columns", + "nplus1_threshold", + "cached_load_sql", + "cached_add_m2m_sql", + "cached_remove_m2m_sql", + "cached_count_sql", + "cached_empty_sql", + "reverse_fk_name", + ) + table: str | list[str] | tuple[str, ...] | None + wrapper_class: Incomplete + symmetric: bool + reverse_column: Incomplete + reverse_columns: Incomplete + nplus1_threshold: int + cached_load_sql: dict[int, Incomplete] + cached_add_m2m_sql: tuple[Incomplete, Incomplete] | None + cached_remove_m2m_sql: tuple[Incomplete, Incomplete] | None + cached_count_sql: tuple[Incomplete, Incomplete] | None + cached_empty_sql: tuple[Incomplete, Incomplete, Incomplete] | None + reverse_fk_name: Incomplete + def __init__(self, py_type, *args, **kwargs) -> None: ... + def load(self, obj) -> None: ... + def __get__(attr, obj, cls=None) -> None: ... + def __set__(attr, obj, val) -> None: ... # type: ignore[override] + def __delete__(attr, obj) -> None: ... + def prepare(self, obj, val, fromdb: bool = False) -> None: ... + def set(self, obj, val, fromdb: bool = False) -> None: ... + +class SetData(set[Incomplete]): + __slots__ = ("is_fully_loaded", "added", "removed", "absent", "count") + is_fully_loaded: bool + added: Incomplete + removed: Incomplete + absent: Incomplete + count: int | None + def __init__(self) -> None: ... + +def construct_batchload_criteria_list( + alias, columns, converters, batch_size, row_value_syntax, start: int = 0, from_seeds: bool = True +): ... + +class Set(Collection): + __slots__: list[str] = [] + def validate(self, val, obj=None, entity=None, from_db: bool = False): ... + def prefetch_load_all(self, objects): ... + def load(self, obj, items=None): ... + def construct_sql_m2m(self, batch_size: int = 1, items_count: int = 0): ... + def copy(self, obj): ... + def __get__(attr, obj, cls=None): ... + def __set__(attr, obj, new_items, undo_funcs=None) -> None: ... + def __delete__(attr, obj) -> None: ... + def reverse_add(self, objects, item, undo_funcs) -> None: ... + def db_reverse_add(self, objects, item) -> None: ... + def reverse_remove(self, objects, item, undo_funcs) -> None: ... + def db_reverse_remove(self, objects, item) -> None: ... + def get_m2m_columns(self, is_reverse: bool = False): ... + def remove_m2m(self, removed) -> None: ... + def add_m2m(self, added) -> None: ... + def drop_table(self, with_all_data: bool = False) -> None: ... + +def unpickle_setwrapper(obj, attrname, items): ... + +class SetIterator: + def __init__(self, wrapper) -> None: ... + def __iter__(self): ... + def next(self): ... + __next__ = next + +class SetInstance: + __slots__ = ("_obj_", "_attr_", "_attrnames_") + def __init__(self, obj, attr) -> None: ... + def __reduce__(wrapper): ... + def copy(self): ... + def __nonzero__(wrapper): ... + def is_empty(self): ... + def __len__(wrapper) -> int: ... + def count(self): ... + def __iter__(wrapper): ... + def __eq__(wrapper, other): ... + def __ne__(wrapper, other): ... + def __add__(wrapper, new_items): ... + def __sub__(wrapper, items): ... + def __contains__(wrapper, item) -> bool: ... + def create(self, **kwargs): ... + def add(self, new_items) -> None: ... + def __iadd__(wrapper, items): ... + def remove(self, items) -> None: ... + def __isub__(wrapper, items): ... + def clear(self) -> None: ... + def load(self) -> None: ... + def select(self, *args, **kwargs): ... + filter = select + def limit(self, limit=None, offset=None): ... + def page(self, pagenum, pagesize: int = 10): ... + def order_by(self, *args): ... + def sort_by(self, *args): ... + def random(self, limit): ... + +def unpickle_multiset(obj, attrnames, items): ... + +class Multiset: + __slots__ = ["_obj_", "_attrnames_", "_items_"] + def __init__(self, obj, attrnames, items) -> None: ... + def __reduce__(multiset): ... + def distinct(self): ... + def __nonzero__(multiset): ... + def __len__(multiset) -> int: ... + def __iter__(multiset): ... + def __eq__(multiset, other): ... + def __ne__(multiset, other): ... + def __contains__(multiset, item) -> bool: ... + +class EntityIter: + entity: Incomplete + def __init__(self, entity) -> None: ... + def next(self) -> None: ... + __next__ = next + +entity_id_counter: itertools.count[int] +new_instance_id_counter: itertools.count[int] +select_re: re.Pattern[str] +lambda_re: re.Pattern[str] + +class EntityMeta(type): + def __new__(meta, name, bases, cls_dict): ... + def __init__(cls, name, bases, cls_dict) -> None: ... + def __iter__(entity): ... + def __getitem__(entity, key): ... + def exists(cls, *args, **kwargs): ... + def get(cls, *args, **kwargs): ... + def get_for_update(cls, *args, **kwargs): ... + def get_by_sql(cls, sql, globals=None, locals=None): ... + def select(cls, *args, **kwargs): ... + def select_by_sql(cls, sql, globals=None, locals=None): ... + def select_random(cls, limit): ... + def describe(cls) -> str: ... + def drop_table(cls, with_all_data: bool = False) -> None: ... + +def populate_criteria_list( + criteria_list, columns, converters, operations, params_count: int = 0, table_alias=None, optimistic: bool = False +) -> int: ... + +statuses: set[str] +del_statuses: set[str] +created_or_deleted_statuses: set[str] +saved_statuses: set[str] + +def throw_object_was_deleted(obj: Entity) -> Never: ... +def unpickle_entity(d): ... +def safe_repr(obj: Entity) -> str: ... +def make_proxy(obj: Entity) -> EntityProxy: ... + +class EntityProxy: + def __init__(self, obj: Entity) -> None: ... + def __getattr__(self, name: str): ... + def __setattr__(self, name: str, value) -> None: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + +class Entity(metaclass=EntityMeta): + __slots__ = ( + "_session_cache_", + "_status_", + "_pkval_", + "_newid_", + "_dbvals_", + "_vals_", + "_rbits_", + "_wbits_", + "_save_pos_", + "__weakref__", + ) + def __reduce__(obj): ... + def __init__(self, *args, **kwargs) -> None: ... + def get_pk(self): ... + def __lt__(entity, other): ... + def __le__(entity, other): ... + def __gt__(entity, other): ... + def __ge__(entity, other): ... + def load(self, *attrs) -> None: ... + def delete(self) -> None: ... + def set(self, **kwargs) -> None: ... + def find_updated_attributes(self): ... + def flush(self) -> None: ... + def before_insert(self) -> None: ... + def before_update(self) -> None: ... + def before_delete(self) -> None: ... + def after_insert(self) -> None: ... + def after_update(self) -> None: ... + def after_delete(self) -> None: ... + def to_dict( + self, only=None, exclude=None, with_collections: bool = False, with_lazy: bool = False, related_objects: bool = False + ): ... + def to_json(self, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + +def string2ast(s: str) -> ast.Expr: ... +def get_globals_and_locals(args, kwargs, frame_depth, from_generator=False): ... +def make_query(args, frame_depth, left_join: bool = False) -> Query: ... +def select(*args): ... +def left_join(*args): ... +def get(*args): ... +def exists(*args): ... +def delete(*args): ... +def make_aggrfunc(std_func): ... + +count: Incomplete +sum: Incomplete +min: Incomplete +max: Incomplete +avg: Incomplete +group_concat: Incomplete +distinct: Incomplete + +def JOIN(expr: _T) -> _T: ... +def desc(expr): ... +def extract_vars(code_key, filter_num, extractors, globals, locals, cells=None): ... +def unpickle_query(query_result: _T) -> _T: ... + +class Query: + def __init__(self, code_key, tree, globals, locals, cells=None, left_join: bool = False) -> None: ... + def __reduce__(query): ... + def get_sql(self): ... + def prefetch(self, *args): ... + def show(self, width=None, stream=None) -> None: ... + def get(self): ... + def first(self): ... + def without_distinct(self): ... + def distinct(self): ... + def exists(self): ... + def delete(self, bulk=None): ... + def __len__(query) -> int: ... + def __iter__(query): ... + def order_by(self, *args): ... + def sort_by(self, *args): ... + def filter(self, *args, **kwargs): ... + def where(self, *args, **kwargs): ... + def __getitem__(query, key): ... + def fetch(self, limit=None, offset=None): ... + def limit(self, limit=None, offset=None): ... + def page(self, pagenum, pagesize: int = 10): ... + def sum(self, distinct=None): ... + def avg(self, distinct=None): ... + def group_concat(self, sep=None, distinct=None): ... + def min(self): ... + def max(self): ... + def count(self, distinct=None): ... + def for_update(self, nowait: bool = False, skip_locked: bool = False): ... + def random(self, limit): ... + def to_json(self, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + +class QueryResultIterator: + __slots__ = ("_query_result", "_position") + def __init__(self, query_result) -> None: ... + def __iter__(self): ... + def next(self): ... + __next__ = next + def __length_hint__(self) -> int: ... + +def make_query_result_method_error_stub(name: str, title: str | None = None) -> Callable[..., Never]: ... + +class QueryResult: + __slots__ = ("_query", "_limit", "_offset", "_items", "_expr_type", "_col_names") + def __init__(self, query, limit, offset, lazy) -> None: ... + def __iter__(self): ... + def __len__(self) -> int: ... + def __getitem__(self, key): ... + def __contains__(self, item) -> bool: ... + def index(self, item): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __reversed__(self): ... + def reverse(self) -> None: ... + def sort(self, *args, **kwargs) -> None: ... + def shuffle(self) -> None: ... + def show(self, width=None, stream=None): ... + def to_json(self, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + def __add__(self, other): ... + def __radd__(self, other): ... + def to_list(self): ... + __setitem__: Incomplete + __delitem__: Incomplete + __iadd__: Incomplete + __imul__: Incomplete + __mul__: Incomplete + __rmul__: Incomplete + append: Incomplete + clear: Incomplete + extend: Incomplete + insert: Incomplete + pop: Incomplete + remove: Incomplete + +def strcut(s: str, width: int) -> str: ... +def show(entity) -> None: ... + +special_functions: set[Incomplete] +const_functions: set[type] diff --git a/stubs/pony/pony/orm/dbapiprovider.pyi b/stubs/pony/pony/orm/dbapiprovider.pyi new file mode 100644 index 000000000000..700561338f34 --- /dev/null +++ b/stubs/pony/pony/orm/dbapiprovider.pyi @@ -0,0 +1,216 @@ +import json +import re +import types +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar + +from pony.utils import localbase + +class DBException(Exception): + def __init__(self, original_exc, *args) -> None: ... + +class Warning(DBException): ... +class Error(DBException): ... +class InterfaceError(Error): ... +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... + +def wrap_dbapi_exceptions(func, provider, *args, **kwargs): ... +def unexpected_args(attr, args) -> None: ... + +version_re: re.Pattern[str] + +def get_version_tuple(s: str): ... + +class DBAPIProvider: + paramstyle: ClassVar[str] + quote_char: ClassVar[str] + max_params_count: ClassVar[int] + max_name_len: ClassVar[int] + table_if_not_exists_syntax: ClassVar[bool] + index_if_not_exists_syntax: ClassVar[bool] + max_time_precision: ClassVar[int] + default_time_precision: ClassVar[int] + uint64_support: ClassVar[bool] + varchar_default_max_len: ClassVar[int | None] + dialect: ClassVar[str | None] + dbapi_module: ClassVar[types.ModuleType | None] + dbschema_cls: ClassVar[type | None] + translator_cls: ClassVar[type | None] + sqlbuilder_cls: ClassVar[type | None] + array_converter_cls: ClassVar[type | None] + name_before_table: ClassVar[str] + default_schema_name: ClassVar[str | None] + fk_types: ClassVar[dict[str, str]] + converter_classes: Incomplete + def __init__(self, _database, *args, **kwargs) -> None: ... + def inspect_connection(self, connection) -> None: ... + def normalize_name(self, name): ... + def get_default_entity_table_name(self, entity): ... + def get_default_m2m_table_name(self, attr, reverse): ... + def get_default_column_names(self, attr, reverse_pk_columns=None): ... + def get_default_m2m_column_names(self, entity): ... + def get_default_index_name( + self, table_name, column_names, is_pk: bool = False, is_unique: bool = False, m2m: bool = False + ): ... + def get_default_fk_name(self, child_table_name, parent_table_name, child_column_names): ... + def split_table_name(self, table_name): ... + def base_name(self, name): ... + def quote_name(self, name: str | Iterable[str]) -> str: ... + def format_table_name(self, name): ... + def normalize_vars(self, vars, vartypes) -> None: ... + def ast2sql(self, ast): ... + def should_reconnect(self, exc): ... + def connect(self): ... + def set_transaction_mode(self, connection, cache) -> None: ... + def commit(self, connection, cache=None) -> None: ... + def rollback(self, connection, cache=None) -> None: ... + def release(self, connection, cache=None) -> None: ... + def drop(self, connection, cache=None) -> None: ... + def disconnect(self) -> None: ... + def execute(self, cursor, sql, arguments=None, returning_id: bool = False): ... + def get_converter_by_py_type(self, py_type): ... + def get_converter_by_attr(self, attr): ... + def get_pool(self, *args, **kwargs): ... + def table_exists(self, connection, table_name, case_sensitive: bool = True) -> None: ... + def index_exists(self, connection, table_name, index_name, case_sensitive: bool = True) -> None: ... + def fk_exists(self, connection, table_name, fk_name, case_sensitive: bool = True) -> None: ... + def table_has_data(self, connection, table_name): ... + def disable_fk_checks(self, connection) -> None: ... + def enable_fk_checks(self, connection, prev_state) -> None: ... + def drop_table(self, connection, table_name) -> None: ... + +class Pool(localbase): + forked_connections: list[tuple[Incomplete, int | None]] + dbapi_module: types.ModuleType + args: tuple[Incomplete, ...] + kwargs: dict[str, Incomplete] + con: Incomplete + pid: int | None + def __init__(self, dbapi_module: types.ModuleType, *args, **kwargs) -> None: ... + def connect(self) -> tuple[Incomplete, bool]: ... + def release(self, con) -> None: ... + def drop(self, con) -> None: ... + def disconnect(self) -> None: ... + +class Converter: + EQ: str + NE: str + optimistic: bool + def __deepcopy__(converter, memo): ... + def __init__(self, provider, py_type, attr=None) -> None: ... + def init(self, kwargs) -> None: ... + def validate(self, val, obj=None): ... + def py2sql(self, val): ... + def sql2py(self, val): ... + def val2dbval(self, val, obj=None): ... + def dbval2val(self, dbval, obj=None): ... + def dbvals_equal(self, x, y): ... + def get_sql_type(self, attr=None): ... + def get_fk_type(self, sql_type): ... + +class NoneConverter(Converter): + def __init__(self, provider, py_type, attr=None) -> None: ... + def get_sql_type(self, attr=None) -> None: ... + def get_fk_type(self, sql_type) -> None: ... + +class BoolConverter(Converter): + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + def sql_type(self): ... + +class StrConverter(Converter): + def __init__(self, provider, py_type, attr=None) -> None: ... + def init(self, kwargs) -> None: ... + def validate(self, val, obj=None): ... + def sql_type(self): ... + +class IntConverter(Converter): + signed_types: Incomplete + unsigned_types: Incomplete + def init(self, kwargs) -> None: ... + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + def sql_type(self): ... + +class RealConverter(Converter): + EQ: str + NE: str + default_tolerance: float + optimistic: bool + def init(self, kwargs) -> None: ... + def validate(self, val, obj=None): ... + def dbvals_equal(self, x, y): ... + def sql2py(self, val): ... + def sql_type(self): ... + +class DecimalConverter(Converter): + def __init__(self, provider, py_type, attr=None) -> None: ... + def init(self, kwargs) -> None: ... + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + def sql_type(self): ... + +class BlobConverter(Converter): + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + def sql_type(self): ... + +class DateConverter(Converter): + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + def sql_type(self): ... + +class ConverterWithMicroseconds(Converter): + def __init__(self, provider, py_type, attr=None) -> None: ... + def init(self, kwargs) -> None: ... + def round_microseconds_to_precision(self, microseconds, precision): ... + def sql_type(self): ... + +class TimeConverter(ConverterWithMicroseconds): + sql_type_name: ClassVar[str] + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + +class TimedeltaConverter(ConverterWithMicroseconds): + sql_type_name: ClassVar[str] + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + +class DatetimeConverter(ConverterWithMicroseconds): + sql_type_name: ClassVar[str] + def validate(self, val, obj=None): ... + def sql2py(self, val): ... + +class UuidConverter(Converter): + def __init__(self, provider, py_type, attr=None) -> None: ... + def validate(self, val, obj=None): ... + def py2sql(self, val): ... + sql2py = validate + def sql_type(self): ... + +class JsonConverter(Converter): + json_kwargs: Incomplete + + class JsonEncoder(json.JSONEncoder): + def default(self, obj): ... + + def validate(self, val, obj=None): ... + def val2dbval(self, val, obj=None): ... + def dbval2val(self, dbval, obj=None): ... + def dbvals_equal(self, x, y): ... + def sql_type(self): ... + +class ArrayConverter(Converter): + array_types: Incomplete + def __init__(self, provider, py_type, attr=None) -> None: ... + def validate(self, val, obj=None): ... + def dbval2val(self, dbval, obj=None): ... + def val2dbval(self, val, obj=None): ... + def sql_type(self): ... diff --git a/stubs/pony/pony/orm/dbproviders/__init__.pyi b/stubs/pony/pony/orm/dbproviders/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/orm/dbproviders/cockroach.pyi b/stubs/pony/pony/orm/dbproviders/cockroach.pyi new file mode 100644 index 000000000000..2a3cfa5c7a2d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/cockroach.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm import dbapiprovider +from pony.orm.dbproviders.postgres import ( + PGArrayConverter, + PGBlobConverter, + PGColumn, + PGIntConverter, + PGProvider, + PGSchema, + PGSQLBuilder, + PGTimedeltaConverter, + PGTranslator, +) + +NoneType: type[None] + +class CRColumn(PGColumn): + auto_template: ClassVar[str] + +class CRSchema(PGSchema): + column_class: ClassVar[type[CRColumn]] + +class CRTranslator(PGTranslator): ... +class CRSQLBuilder(PGSQLBuilder): ... + +class CRIntConverter(PGIntConverter): + signed_types: Incomplete + unsigned_types: Incomplete + +class CRBlobConverter(PGBlobConverter): + def sql_type(converter): ... + +class CRTimedeltaConverter(PGTimedeltaConverter): ... + +class PGUuidConverter(dbapiprovider.UuidConverter): + def py2sql(converter, val): ... + +class CRArrayConverter(PGArrayConverter): + array_types: Incomplete + +class CRProvider(PGProvider): + dbschema_cls: ClassVar[type[CRSchema]] + translator_cls: ClassVar[type[CRTranslator]] + sqlbuilder_cls: ClassVar[type[CRSQLBuilder]] + array_converter_cls: ClassVar[type[CRArrayConverter]] + +provider_cls = CRProvider diff --git a/stubs/pony/pony/orm/dbproviders/mysql.pyi b/stubs/pony/pony/orm/dbproviders/mysql.pyi new file mode 100644 index 000000000000..79e9dbc4ed09 --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/mysql.pyi @@ -0,0 +1,102 @@ +import types +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm import dbapiprovider, dbschema +from pony.orm.dbapiprovider import DBAPIProvider +from pony.orm.sqlbuilding import SQLBuilder, Value +from pony.orm.sqltranslation import SQLTranslator + +NoneType: type[None] +mysql_module_name: str + +class MySQLColumn(dbschema.Column): + auto_template: ClassVar[str] + +class MySQLSchema(dbschema.DBSchema): + dialect: ClassVar[str] + column_class: ClassVar[type[MySQLColumn]] + +class MySQLTranslator(SQLTranslator): + dialect: ClassVar[str] + +class MySQLValue(Value): + __slots__: list[str] = [] + +class MySQLBuilder(SQLBuilder): + dialect: ClassVar[str] + value_class: ClassVar[type[MySQLValue]] + def CONCAT(builder, *args): ... + def TRIM(builder, expr, chars=None): ... + def LTRIM(builder, expr, chars=None): ... + def RTRIM(builder, expr, chars=None): ... + def TO_INT(builder, expr): ... + def TO_REAL(builder, expr): ... + def TO_STR(builder, expr): ... + def YEAR(builder, expr): ... + def MONTH(builder, expr): ... + def DAY(builder, expr): ... + def HOUR(builder, expr): ... + def MINUTE(builder, expr): ... + def SECOND(builder, expr): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def JSON_QUERY(builder, expr, path): ... + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_ARRAY_LENGTH(builder, value): ... + def JSON_EQ(builder, left, right): ... + def JSON_NE(builder, left, right): ... + def JSON_CONTAINS(builder, expr, path, key): ... + @classmethod + def wrap_param_to_json_array(cls, values): ... + def JSON_PARAM(builder, expr): ... + +class MySQLStrConverter(dbapiprovider.StrConverter): + def sql_type(converter): ... + +class MySQLRealConverter(dbapiprovider.RealConverter): + def sql_type(converter): ... + +class MySQLBlobConverter(dbapiprovider.BlobConverter): + def sql_type(converter): ... + +class MySQLTimeConverter(dbapiprovider.TimeConverter): + def sql2py(converter, val): ... + +class MySQLTimedeltaConverter(dbapiprovider.TimedeltaConverter): ... + +class MySQLUuidConverter(dbapiprovider.UuidConverter): + def sql_type(converter): ... + +class MySQLJsonConverter(dbapiprovider.JsonConverter): + EQ: str + NE: str + def init(self, kwargs) -> None: ... + +class MySQLProvider(DBAPIProvider): + dialect: ClassVar[str] + varchar_default_max_len: ClassVar[int] + dbapi_module: ClassVar[types.ModuleType] + dbschema_cls: ClassVar[type[MySQLSchema]] + translator_cls: ClassVar[type[MySQLTranslator]] + sqlbuilder_cls: ClassVar[type[MySQLBuilder]] + fk_types: ClassVar[dict[str, str]] + converter_classes: Incomplete + def normalize_name(provider, name): ... + def inspect_connection(provider, connection) -> None: ... + def should_reconnect(provider, exc): ... + def get_pool(provider, *args, **kwargs): ... + def set_transaction_mode(provider, connection, cache) -> None: ... + def release(provider, connection, cache=None) -> None: ... + def table_exists(provider, connection, table_name, case_sensitive: bool = True): ... + def index_exists(provider, connection, table_name, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection, table_name, fk_name, case_sensitive: bool = True): ... + +provider_cls = MySQLProvider + +def str2datetime(s): ... diff --git a/stubs/pony/pony/orm/dbproviders/oracle.pyi b/stubs/pony/pony/orm/dbproviders/oracle.pyi new file mode 100644 index 000000000000..220e58f4099d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/oracle.pyi @@ -0,0 +1,159 @@ +import re +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm import dbapiprovider, sqltranslation +from pony.orm.dbapiprovider import DBAPIProvider +from pony.orm.dbschema import Column, DBObject, DBSchema, Table +from pony.orm.sqlbuilding import SQLBuilder + +NoneType: type[None] + +class OraTable(Table): + def get_objects_to_create(table, created_tables=None): ... + +class OraSequence(DBObject): + typename: ClassVar[str] + def __init__(sequence, table, name=None) -> None: ... + def exists(sequence, provider, connection, case_sensitive: bool = True): ... + def get_create_command(sequence): ... + +trigger_template: str + +class OraTrigger(DBObject): + typename: ClassVar[str] + def __init__(trigger, table, column, sequence) -> None: ... + def exists(trigger, provider, connection, case_sensitive: bool = True): ... + def get_create_command(trigger): ... + +class OraColumn(Column): + auto_template: ClassVar[None] # type: ignore[assignment] + +class OraSchema(DBSchema): + dialect: ClassVar[str] + table_class: ClassVar[type[OraTable]] + column_class: ClassVar[type[OraColumn]] + +class OraNoneMonad(sqltranslation.NoneMonad): + def __init__(monad, value=None) -> None: ... + +class OraConstMonad(sqltranslation.ConstMonad): + @staticmethod + def new(value): ... + +class OraTranslator(sqltranslation.SQLTranslator): + dialect: ClassVar[str] + NoneMonad = OraNoneMonad + ConstMonad = OraConstMonad + +class OraBuilder(SQLBuilder): + dialect: ClassVar[str] + def INSERT(builder, table_name, columns, values, returning=None): ... + def SELECT_FOR_UPDATE(builder, nowait, skip_locked, *sections): ... + def SELECT(builder, *sections): ... + def ROWID(builder, *expr_list): ... + def LIMIT(builder, limit, offset=None) -> None: ... + def TO_REAL(builder, expr): ... + def TO_STR(builder, expr): ... + def DATE(builder, expr): ... + def RANDOM(builder): ... + def MOD(builder, a, b): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def build_json_path(builder, path): ... + def JSON_QUERY(builder, expr, path): ... + json_value_type_mapping: Incomplete + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_CONTAINS(builder, expr, path, key): ... + def JSON_ARRAY_LENGTH(builder, value) -> None: ... + def GROUP_CONCAT(builder, distinct, expr, sep=None): ... + +json_item_re: re.Pattern[str] + +class OraBoolConverter(dbapiprovider.BoolConverter): + def py2sql(converter, val): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class OraStrConverter(dbapiprovider.StrConverter): + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class OraIntConverter(dbapiprovider.IntConverter): + signed_types: Incomplete + unsigned_types: Incomplete + def init(self, kwargs) -> None: ... + +class OraRealConverter(dbapiprovider.RealConverter): + def sql_type(converter): ... + +class OraDecimalConverter(dbapiprovider.DecimalConverter): + def sql_type(converter): ... + +class OraBlobConverter(dbapiprovider.BlobConverter): + def sql2py(converter, val): ... + +class OraDateConverter(dbapiprovider.DateConverter): + def sql2py(converter, val): ... + +class OraTimeConverter(dbapiprovider.TimeConverter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class OraTimedeltaConverter(dbapiprovider.TimedeltaConverter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + +class OraDatetimeConverter(dbapiprovider.DatetimeConverter): ... + +class OraUuidConverter(dbapiprovider.UuidConverter): + def sql_type(converter): ... + +class OraJsonConverter(dbapiprovider.JsonConverter): + json_kwargs: Incomplete + optimistic: bool + def sql2py(converter, dbval): ... + def sql_type(converter): ... + +class OraProvider(DBAPIProvider): + dialect: ClassVar[str] + varchar_default_max_len: ClassVar[int] + dbschema_cls: ClassVar[type[OraSchema]] + translator_cls: ClassVar[type[OraTranslator]] + sqlbuilder_cls: ClassVar[type[OraBuilder]] + converter_classes: Incomplete + def inspect_connection(provider, connection) -> None: ... + def should_reconnect(provider, exc): ... + def normalize_name(provider, name): ... + def normalize_vars(provider, vars, vartypes) -> None: ... + def set_transaction_mode(provider, connection, cache) -> None: ... + def execute(provider, cursor, sql, arguments=None, returning_id: bool = False): ... + def get_pool(provider, *args, **kwargs): ... + def table_exists(provider, connection, table_name, case_sensitive: bool = True): ... + def index_exists(provider, connection, table_name, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection, table_name, fk_name, case_sensitive: bool = True): ... + def table_has_data(provider, connection, table_name): ... + def drop_table(provider, connection, table_name) -> None: ... + +provider_cls = OraProvider + +def to_int_or_decimal(val): ... +def to_decimal(val): ... +def output_type_handler(cursor, name, defaultType, size, precision, scale): ... + +class OraPool: + forked_pools: Incomplete + def __init__(pool, **kwargs) -> None: ... + def connect(pool): ... + def release(pool, con) -> None: ... + def drop(pool, con) -> None: ... + def disconnect(pool) -> None: ... + +def get_inputsize(arg): ... +def set_input_sizes(cursor, arguments) -> None: ... diff --git a/stubs/pony/pony/orm/dbproviders/postgres.pyi b/stubs/pony/pony/orm/dbproviders/postgres.pyi new file mode 100644 index 000000000000..a2f472c3890d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/postgres.pyi @@ -0,0 +1,106 @@ +import types +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar + +from pony.orm import dbapiprovider, dbschema +from pony.orm.dbapiprovider import DBAPIProvider, Pool +from pony.orm.sqlbuilding import SQLBuilder, Value +from pony.orm.sqltranslation import SQLTranslator +from psycopg2._psycopg import _Connection + +NoneType: type[None] + +class PGColumn(dbschema.Column): + auto_template: ClassVar[str] + +class PGSchema(dbschema.DBSchema): + dialect: ClassVar[str] + column_class: ClassVar[type[PGColumn]] + +class PGTranslator(SQLTranslator): + dialect: ClassVar[str] + +class PGValue(Value): + __slots__: list[str] = [] + +class PGSQLBuilder(SQLBuilder): + dialect: ClassVar[str] + value_class: ClassVar[type[PGValue]] + def INSERT(builder, table_name, columns, values, returning=None): ... + def TO_INT(builder, expr): ... + def TO_STR(builder, expr): ... + def TO_REAL(builder, expr): ... + def DATE(builder, expr): ... + def RANDOM(builder): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def eval_json_path(builder, values: Iterable[int | str]) -> str: ... # type: ignore[override] + def JSON_QUERY(builder, expr, path): ... + json_value_type_mapping: dict[type, str] + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_CONCAT(builder, left, right): ... + def JSON_CONTAINS(builder, expr, path, key): ... + def JSON_ARRAY_LENGTH(builder, value): ... + def GROUP_CONCAT(builder, distinct, expr, sep=None): ... + def ARRAY_INDEX(builder, col, index): ... + def ARRAY_CONTAINS(builder, key, not_in, col): ... + def ARRAY_SUBSET(builder, array1, not_in, array2): ... + def ARRAY_LENGTH(builder, array): ... + def ARRAY_SLICE(builder, array, start, stop): ... + def MAKE_ARRAY(builder, *items): ... + +class PGIntConverter(dbapiprovider.IntConverter): + signed_types: Incomplete + unsigned_types: Incomplete + +class PGRealConverter(dbapiprovider.RealConverter): + def sql_type(converter): ... + +class PGBlobConverter(dbapiprovider.BlobConverter): + def sql_type(converter): ... + +class PGTimedeltaConverter(dbapiprovider.TimedeltaConverter): ... +class PGDatetimeConverter(dbapiprovider.DatetimeConverter): ... + +class PGUuidConverter(dbapiprovider.UuidConverter): + def py2sql(converter, val): ... + +class PGJsonConverter(dbapiprovider.JsonConverter): + def sql_type(self): ... + +class PGArrayConverter(dbapiprovider.ArrayConverter): + array_types: dict[type, tuple[str, type]] + +class PGPool(Pool): + def release(pool, con) -> None: ... + +ADMIN_SHUTDOWN: str + +class PGProvider(DBAPIProvider): + dialect: ClassVar[str] + dbapi_module: ClassVar[types.ModuleType] + dbschema_cls: ClassVar[type[PGSchema]] + translator_cls: ClassVar[type[PGTranslator]] + sqlbuilder_cls: ClassVar[type[PGSQLBuilder]] + array_converter_cls: ClassVar[type[PGArrayConverter]] + default_schema_name: ClassVar[str] + fk_types: ClassVar[dict[str, str]] + converter_classes: list[tuple[type | tuple[type], type]] + def normalize_name(provider, name: str) -> str: ... + def inspect_connection(provider, connection: _Connection) -> None: ... + def should_reconnect(provider, exc: BaseException | None) -> bool: ... + def get_pool(provider, *args, **kwargs) -> PGPool: ... + def set_transaction_mode(provider, connection: _Connection, cache) -> None: ... + def execute(provider, cursor, sql, arguments=None, returning_id: bool = False): ... + def table_exists(provider, connection: _Connection, table_name: str, case_sensitive: bool = True): ... + def index_exists(provider, connection: _Connection, table_name: str, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection: _Connection, table_name: str, fk_name, case_sensitive: bool = True): ... + def drop_table(provider, connection: _Connection, table_name: str) -> None: ... + +provider_cls = PGProvider diff --git a/stubs/pony/pony/orm/dbproviders/sqlite.pyi b/stubs/pony/pony/orm/dbproviders/sqlite.pyi new file mode 100644 index 000000000000..3c1e85a3546d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/sqlite.pyi @@ -0,0 +1,221 @@ +import re +import sys +import types +from _typeshed import Incomplete, StrOrBytesPath +from sqlite3 import Connection as _Connection +from typing import Any, ClassVar, overload + +from pony.orm import dbapiprovider, dbschema +from pony.orm.dbapiprovider import DBAPIProvider, Pool +from pony.orm.sqlbuilding import SQLBuilder, Value +from pony.orm.sqltranslation import SQLTranslator +from pony.utils import localbase + +class SqliteExtensionUnavailable(Exception): ... + +NoneType: type[None] + +class SQLiteForeignKey(dbschema.ForeignKey): + def get_create_command(self) -> None: ... + +class SQLiteSchema(dbschema.DBSchema): + dialect: ClassVar[str] + fk_class: ClassVar[type[SQLiteForeignKey]] + +def make_overriden_string_func(sqlop): ... + +class SQLiteTranslator(SQLTranslator): + dialect: ClassVar[str] + sqlite_version: tuple[int, int, int] + StringMixin_UPPER: Incomplete + StringMixin_LOWER: Incomplete + +class SQLiteValue(Value): + __slots__: list[str] = [] + +class SQLiteBuilder(SQLBuilder): + dialect: ClassVar[str] + least_func_name: ClassVar[str] + greatest_func_name: ClassVar[str] + value_class: ClassVar[type[SQLiteValue]] + def __init__(self, provider, ast) -> None: ... + def SELECT_FOR_UPDATE(self, nowait, skip_locked, *sections): ... + def INSERT(self, table_name, columns, values, returning=None): ... + def STRING_SLICE(self, expr, start, stop): ... + def IN(self, expr1, x): ... + def NOT_IN(self, expr1, x): ... + def TODAY(self): ... + def NOW(self): ... + def YEAR(self, expr): ... + def MONTH(self, expr): ... + def DAY(self, expr): ... + def HOUR(self, expr): ... + def MINUTE(self, expr): ... + def SECOND(self, expr): ... + def datetime_add(self, funcname, expr, td): ... + def DATE_ADD(self, expr, delta): ... + def DATE_SUB(self, expr, delta): ... + def DATE_DIFF(self, expr1, expr2): ... + def DATETIME_ADD(self, expr, delta): ... + def DATETIME_SUB(self, expr, delta): ... + def DATETIME_DIFF(self, expr1, expr2): ... + def RANDOM(self): ... + PY_UPPER: Incomplete + PY_LOWER: Incomplete + def FLOAT_EQ(self, a, b): ... + def FLOAT_NE(self, a, b): ... + def JSON_QUERY(self, expr, path): ... + json_value_type_mapping: Incomplete + def JSON_VALUE(self, expr, path, type): ... + def JSON_NONZERO(self, expr): ... + def JSON_ARRAY_LENGTH(self, value): ... + def JSON_CONTAINS(self, expr, path, key): ... + def ARRAY_INDEX(self, col, index): ... + def ARRAY_CONTAINS(self, key, not_in, col): ... + def ARRAY_SUBSET(self, array1, not_in, array2): ... + def ARRAY_LENGTH(self, array): ... + def ARRAY_SLICE(self, array, start, stop): ... + def MAKE_ARRAY(self, *items): ... + +class SQLiteIntConverter(dbapiprovider.IntConverter): + def sql_type(self): ... + +class SQLiteDecimalConverter(dbapiprovider.DecimalConverter): + inf: Incomplete + neg_inf: Incomplete + NaN: Incomplete + def sql2py(self, val): ... + def py2sql(self, val): ... + +class SQLiteDateConverter(dbapiprovider.DateConverter): + def sql2py(self, val): ... + def py2sql(self, val): ... + +class SQLiteTimeConverter(dbapiprovider.TimeConverter): + def sql2py(self, val): ... + def py2sql(self, val): ... + +class SQLiteTimedeltaConverter(dbapiprovider.TimedeltaConverter): + def sql2py(self, val): ... + def py2sql(self, val): ... + +class SQLiteDatetimeConverter(dbapiprovider.DatetimeConverter): + def sql2py(self, val): ... + def py2sql(self, val): ... + +class SQLiteJsonConverter(dbapiprovider.JsonConverter): + json_kwargs: Incomplete + +def dumps(items): ... + +class SQLiteArrayConverter(dbapiprovider.ArrayConverter): + array_types: Incomplete + def dbval2val(self, dbval, obj=None): ... + def val2dbval(self, val, obj=None): ... + +class LocalExceptions(localbase): + exc_info: Incomplete + keep_traceback: bool + def __init__(self) -> None: ... + +local_exceptions: LocalExceptions + +def keep_exception(func): ... + +class SQLiteProvider(DBAPIProvider): + dialect: ClassVar[str] + local_exceptions: LocalExceptions + dbapi_module: ClassVar[types.ModuleType] + dbschema_cls: ClassVar[type[SQLiteSchema]] + translator_cls: ClassVar[type[SQLiteTranslator]] + sqlbuilder_cls: ClassVar[type[SQLiteBuilder]] + array_converter_cls: ClassVar[type[SQLiteArrayConverter]] + server_version: tuple[int, int, int] + converter_classes: Incomplete + def __init__(self, database, filename, **kwargs) -> None: ... + def inspect_connection(self, conn) -> None: ... + def restore_exception(self) -> None: ... + def acquire_lock(self) -> None: ... + def release_lock(self) -> None: ... + def set_transaction_mode(self, connection: _Connection, cache) -> None: ... + def commit(self, connection: _Connection, cache=None) -> None: ... + def rollback(self, connection: _Connection, cache=None) -> None: ... + def drop(self, connection: _Connection, cache=None) -> None: ... + def release(self, connection: _Connection, cache=None) -> None: ... + def get_pool(self, is_shared_memory_db, filename, create_db: bool = False, **kwargs): ... + def table_exists(self, connection: _Connection, table_name: str, case_sensitive: bool = True): ... + def index_exists(self, connection: _Connection, table_name: str, index_name, case_sensitive: bool = True): ... + def fk_exists(self, connection: _Connection, table_name: str, fk_name) -> None: ... # type: ignore[override] + def check_json1(self, connection: _Connection) -> bool: ... + +provider_cls = SQLiteProvider + +def make_string_function(name, base_func): ... + +py_upper: Incomplete +py_lower: Incomplete + +@overload +def py_json_unwrap(value: str) -> str | None: ... +@overload +def py_json_unwrap(value: Any) -> None: ... + +path_cache: Incomplete +json_path_re: re.Pattern[str] + +def py_json_extract(expr, *paths): ... +def py_json_query(expr, path, with_wrapper): ... +def py_json_value(expr, path): ... +def py_json_contains(expr, path, key): ... +def py_json_nonzero(expr, path): ... +def py_json_array_length(expr, path=None): ... +def wrap_array_func(func): ... +def py_array_index(array, index): ... +def py_array_contains(array, item): ... +def py_array_subset(array, items): ... +def py_array_length(array): ... +def py_array_slice(array, start, stop): ... +def py_make_array(*items): ... + +@overload +def py_string_slice(s: None, start: str | int | None, end: str | int | None) -> None: ... +@overload +def py_string_slice(s: str, start: str | int | None, end: str | int | None) -> str: ... + +class SQLitePool(Pool): + is_shared_memory_db: bool | None + filename: StrOrBytesPath + create_db: bool | None + kwargs: dict[str, Incomplete] + if sys.version_info >= (3, 12): + def __init__( + self, + is_shared_memory_db: bool | None, + filename: StrOrBytesPath, + create_db: bool | None, + *, + timeout: float = 5.0, + detect_types: int = 0, + check_same_thread: bool = True, + factory: type[_Connection], + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> None: ... + else: + def __init__( + self, + is_shared_memory_db: bool | None, + filename: StrOrBytesPath, + create_db: bool | None, + *, + timeout: float = 5.0, + detect_types: int = 0, + check_same_thread: bool = True, + factory: type[_Connection], + cached_statements: int = 128, + uri: bool = False, + ) -> None: ... + + def disconnect(self) -> None: ... + def drop(self, con: _Connection) -> None: ... diff --git a/stubs/pony/pony/orm/dbschema.pyi b/stubs/pony/pony/orm/dbschema.pyi new file mode 100644 index 000000000000..928aeb88645e --- /dev/null +++ b/stubs/pony/pony/orm/dbschema.pyi @@ -0,0 +1,78 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm.dbapiprovider import DBAPIProvider + +class DBSchema: + dialect: ClassVar[str | None] + inline_fk_syntax: ClassVar[bool] + named_foreign_keys: ClassVar[bool] + table_class: ClassVar[type[Table]] + column_class: ClassVar[type[Column]] + index_class: ClassVar[type[DBIndex]] + fk_class: ClassVar[type[ForeignKey]] + provider: DBAPIProvider + tables: dict[Incomplete, Incomplete] + constraints: dict[Incomplete, Incomplete] + indent: str + command_separator: str + uppercase: bool + names: dict[Incomplete, Incomplete] + def __init__(self, provider: DBAPIProvider, uppercase: bool = True) -> None: ... + def column_list(self, columns): ... + def case(self, s: str) -> str: ... + def add_table(self, table_name, entity=None): ... + def order_tables_to_create(self): ... + def generate_create_script(self): ... + def create_tables(self, provider: DBAPIProvider, connection) -> None: ... + def check_tables(self, provider: DBAPIProvider, connection) -> None: ... + +class DBObject: + def create(self, provider, connection) -> None: ... + +class Table(DBObject): + typename: ClassVar[str] + def __init__(self, name, schema, entity=None) -> None: ... + def add_entity(self, entity) -> None: ... + def exists(self, provider: DBAPIProvider, connection, case_sensitive: bool = True): ... + def get_create_command(self): ... + def format_option(self, name, value): ... + def get_objects_to_create(self, created_tables: set[Table] | None = None) -> list[Table]: ... + def add_column(self, column_name, sql_type, converter, is_not_null: bool | None = None, sql_default=None): ... + def add_index(self, index_name, columns, is_pk: bool = False, is_unique=None, m2m: bool = False): ... + def add_foreign_key( + self, + fk_name, + child_columns, + parent_table, + parent_columns, + index_name=None, + on_delete: bool = False, + interleave: bool = False, + ): ... + +class Column: + auto_template: ClassVar[str] + def __init__(self, name, table, sql_type, converter, is_not_null: bool | None = None, sql_default=None) -> None: ... + def get_sql(self) -> str: ... + +class Constraint(DBObject): + schema: DBSchema + name: str | None + def __init__(self, name: str | None, schema: DBSchema) -> None: ... + +class DBIndex(Constraint): + typename: ClassVar[str] + def __init__(self, name: str | None, table, columns, is_pk: bool = False, is_unique=None) -> None: ... + def exists(self, provider, connection, case_sensitive: bool = True): ... + def get_sql(self) -> str: ... + def get_create_command(self): ... + +class ForeignKey(Constraint): + typename: ClassVar[str] + def __init__( + self, name, child_table, child_columns, parent_table, parent_columns, index_name, on_delete, interleave: bool = False + ) -> None: ... + def exists(self, provider, connection, case_sensitive: bool = True): ... + def get_sql(self) -> str: ... + def get_create_command(self): ... diff --git a/stubs/pony/pony/orm/decompiling.pyi b/stubs/pony/pony/orm/decompiling.pyi new file mode 100644 index 000000000000..9755f2715761 --- /dev/null +++ b/stubs/pony/pony/orm/decompiling.pyi @@ -0,0 +1,153 @@ +import ast +from _typeshed import Incomplete + +class DecompileError(NotImplementedError): ... + +ast_cache: dict[int, tuple[Incomplete | None, set[Incomplete]]] + +def decompile(x): ... +def simplify(clause): ... + +class InvalidQuery(Exception): ... + +def binop(node_type): ... + +operator_mapping: dict[str, type[ast.cmpop]] + +double_load_store_ops: set[str] +direct_jump_to_loop_ops: dict[str, str] + +def clean_assign(node): ... +def make_const(value): ... +def is_const(value) -> bool: ... +def unwrap_str(key) -> str: ... +def slice_to_ast(value): ... + +class Decompiler: + def __init__(self, code, start: int = 0, end=None) -> None: ... + def get_instructions(self) -> None: ... + def analyze_jumps(self) -> None: ... + def decompile(self) -> None: ... + def pop_items(self, size): ... + def store(self, node) -> None: ... + BINARY_POWER: Incomplete + BINARY_MULTIPLY: Incomplete + BINARY_DIVIDE: Incomplete + BINARY_FLOOR_DIVIDE: Incomplete + BINARY_ADD: Incomplete + BINARY_SUBTRACT: Incomplete + BINARY_LSHIFT: Incomplete + BINARY_RSHIFT: Incomplete + BINARY_AND: Incomplete + BINARY_XOR: Incomplete + BINARY_OR: Incomplete + BINARY_TRUE_DIVIDE = BINARY_DIVIDE # pyrefly: ignore [unknown-name] + BINARY_MODULO: Incomplete + def BINARY_OP(self, opcode): ... + def BINARY_SLICE(self): ... + def BINARY_SUBSCR(self): ... + def BUILD_CONST_KEY_MAP(self, length): ... + def BUILD_LIST(self, size): ... + def BUILD_MAP(self, length): ... + def BUILD_SET(self, size): ... + def BUILD_SLICE(self, size): ... + def BUILD_TUPLE(self, size): ... + def BUILD_STRING(self, count): ... + def CALL_FUNCTION(self, argc, star=None, star2=None): ... + def CACHE(self) -> None: ... + def CALL(self, argc): ... + def CALL_FUNCTION_VAR(self, argc): ... + def CALL_FUNCTION_KW(self, argc): ... + def CALL_FUNCTION_VAR_KW(self, argc): ... + def CALL_FUNCTION_EX(self, argc=1): ... + def CALL_METHOD(self, argc): ... + def CALL_KW(self, argc): ... + def COMPARE_OP(self, op): ... + def COPY(self, _) -> None: ... + def COPY_FREE_VARS(self, n) -> None: ... + def CONTAINS_OP(self, invert): ... + def CONVERT_VALUE(self, conversion): ... + def DUP_TOP(self): ... + def FOR_ITER(self, endpos): ... + def FORMAT_VALUE(self, flags): ... + def FORMAT_SIMPLE(self): ... + def FORMAT_WITH_SPEC(self): ... + def GEN_START(self, kind) -> None: ... + def GET_ITER(self) -> None: ... + def JUMP_IF_FALSE(self, endpos): ... + JUMP_IF_FALSE_OR_POP = JUMP_IF_FALSE + def JUMP_IF_NOT_EXC_MATCH(self, endpos) -> None: ... + def JUMP_IF_TRUE(self, endpos): ... + JUMP_IF_TRUE_OR_POP = JUMP_IF_TRUE + def conditional_jump(self, endpos, if_true): ... + def conditional_jump_old(self, endpos, if_true): ... + def conditional_jump_new(self, endpos, if_true): ... + def conditional_jump_none_impl(self, endpos, negate): ... + def jump_if_none(self, endpos): ... + def jump_if_not_none(self, endpos): ... + def process_target(self, pos, partial: bool = False) -> None: ... + def JUMP_FORWARD(self, endpos): ... + def KW_NAMES(self, kw_names) -> None: ... + def IS_OP(self, invert): ... + def LIST_APPEND(self, offset) -> None: ... + def LIST_EXTEND(self, offset): ... + def LIST_TO_TUPLE(self): ... + def LOAD_ATTR(self, attr_name, push_null): ... + def LOAD_CLOSURE(self, freevar): ... + def LOAD_CONST(self, const_value): ... + def LOAD_DEREF(self, freevar): ... + def LOAD_FAST(self, varname): ... + LOAD_FAST_AND_CLEAR = LOAD_FAST + def LOAD_FAST_BORROW(self, varname): ... + def LOAD_FAST_BORROW_LOAD_FAST_BORROW(self, varname1, varname2): ... + def LOAD_FAST_LOAD_FAST(self, varname1, varname2): ... + def LOAD_GLOBAL(self, varname, push_null): ... + def LOAD_METHOD(self, methname): ... + LOOKUP_METHOD = LOAD_METHOD + def LOAD_NAME(self, varname): ... + def LOAD_SMALL_INT(self, value): ... + def MAKE_CELL(self, freevar) -> None: ... + def MAKE_CLOSURE(self, argc): ... + def MAKE_FUNCTION(self, argc=0): ... + POP_JUMP_BACKWARD_IF_FALSE = JUMP_IF_FALSE + POP_JUMP_BACKWARD_IF_TRUE = JUMP_IF_TRUE + POP_JUMP_FORWARD_IF_FALSE = JUMP_IF_FALSE + POP_JUMP_FORWARD_IF_TRUE = JUMP_IF_TRUE + POP_JUMP_IF_FALSE = JUMP_IF_FALSE + POP_JUMP_IF_TRUE = JUMP_IF_TRUE + def POP_JUMP_IF_NONE(self, endpos): ... + def POP_JUMP_IF_NOT_NONE(self, endpos): ... + POP_JUMP_BACKWARD_IF_NONE = jump_if_none + POP_JUMP_BACKWARD_IF_NOT_NONE = jump_if_not_none + POP_JUMP_FORWARD_IF_NONE = jump_if_none + POP_JUMP_FORWARD_IF_NOT_NONE = jump_if_not_none + def POP_TOP(self) -> None: ... + def PRECALL(self, argc) -> None: ... + def PUSH_NULL(self) -> None: ... + def RETURN_VALUE(self): ... + def RETURN_CONST(self, val): ... + def RETURN_GENERATOR(self) -> None: ... + def RESUME(self, where) -> None: ... + def ROT_TWO(self) -> None: ... + def ROT_THREE(self) -> None: ... + def SET_FUNCTION_ATTRIBUTE(self, flag): ... + def SETUP_LOOP(self, endpos) -> None: ... + def STORE_ATTR(self, attrname) -> None: ... + def STORE_DEREF(self, freevar) -> None: ... + def STORE_FAST(self, varname) -> None: ... + def STORE_FAST_LOAD_FAST(self, varname1, varname2): ... + def STORE_FAST_STORE_FAST(self, varname1, varname2): ... + def STORE_MAP(self) -> None: ... + def STORE_SUBSCR(self) -> None: ... + def SWAP(self, _) -> None: ... + def TO_BOOL(self): ... + def UNARY_POSITIVE(self): ... + def UNARY_NEGATIVE(self): ... + def UNARY_NOT(self): ... + def UNARY_INVERT(self): ... + def UNPACK_SEQUENCE(self, count): ... + def YIELD_VALUE(self, _=None): ... + +test_lines: str + +def test(test_line=None) -> None: ... diff --git a/stubs/pony/pony/orm/examples/__init__.pyi b/stubs/pony/pony/orm/examples/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/orm/examples/alessandro_bug.pyi b/stubs/pony/pony/orm/examples/alessandro_bug.pyi new file mode 100644 index 000000000000..f8e36522aaf7 --- /dev/null +++ b/stubs/pony/pony/orm/examples/alessandro_bug.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete + +from pony.orm import * +from pony.orm.core import Database, Entity + +database: Database + +class User(Entity): + __slots__ = () + user_id: PrimaryKey + owned_pokemons: Incomplete + is_admin: Incomplete + is_banned: Incomplete + @staticmethod + def get_or_create(user_id: int) -> User: ... + @staticmethod + def get_by_id(user_id: int) -> User: ... + def catch_pokemon(self, pokemon: Pokemon): ... + def remove_pokemon(self, pokemon: Pokemon): ... + favorite_color: Incomplete + def set_favorite_color(self, color: tuple[Incomplete, ...]): ... + +class Pokemon(Entity): + __slots__ = () + name: Incomplete + pokemon_id: Incomplete + sprite: Incomplete + is_shiny: Incomplete + owner: Incomplete + spawned_chat_id: Incomplete + spawned_message_id: Incomplete + @property + def captured(self) -> bool: ... + def caught_by(self, user: User): ... + +class Chat(Entity): + __slots__ = () + chat_id: Incomplete + active: Incomplete + def activate(self) -> None: ... + def deactivate(self) -> None: ... + @staticmethod + def get_or_create(chat_id: int) -> Chat: ... + @staticmethod + def get_by_id(chat_id: int) -> Chat: ... + +def spawn_pokemon( + chat_id: int, message_id: int, pokemon_json: dict[Incomplete, Incomplete], is_shiny: bool = False +) -> Pokemon: ... +def get_spawned_pokemon(chat_id: int, message_id: int) -> Pokemon | None: ... +def setup() -> None: ... diff --git a/stubs/pony/pony/orm/examples/bottle_example.pyi b/stubs/pony/pony/orm/examples/bottle_example.pyi new file mode 100644 index 000000000000..5ea35b2aacd0 --- /dev/null +++ b/stubs/pony/pony/orm/examples/bottle_example.pyi @@ -0,0 +1,6 @@ +from pony.orm.examples.estore import * + +def all_products() -> str: ... +def show_product(id: int) -> str: ... +def edit_product(id: int) -> str: ... +def save_product(id: int) -> None: ... diff --git a/stubs/pony/pony/orm/examples/bug_ben.pyi b/stubs/pony/pony/orm/examples/bug_ben.pyi new file mode 100644 index 000000000000..3b7ecb074f0e --- /dev/null +++ b/stubs/pony/pony/orm/examples/bug_ben.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class ReconciledPayments(Entity): + id: Incomplete + foo: Incomplete + add_on_id: Incomplete + +class ContractAddOns(Entity): + id: Incomplete + reconciled_payments: Incomplete + +r1: ReconciledPayments +r2: ReconciledPayments +c1: ContractAddOns +old_val: Incomplete diff --git a/stubs/pony/pony/orm/examples/compositekeys.pyi b/stubs/pony/pony/orm/examples/compositekeys.pyi new file mode 100644 index 000000000000..1d48e601587f --- /dev/null +++ b/stubs/pony/pony/orm/examples/compositekeys.pyi @@ -0,0 +1,89 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Group(Entity): + __slots__ = () + dept: Incomplete + year: Incomplete + spec: Incomplete + students: Incomplete + courses: Incomplete + lessons: Incomplete + +class Department(Entity): + __slots__ = () + number: Incomplete + faculty: Incomplete + name: Incomplete + groups: Incomplete + teachers: Incomplete + +class Faculty(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + depts: Incomplete + +class Student(Entity): + __slots__ = () + name: Incomplete + group: Incomplete + dob: Incomplete + grades: Incomplete + +class Grade(Entity): + __slots__ = () + student: Incomplete + task: Incomplete + date: Incomplete + value: Incomplete + +class Task(Entity): + __slots__ = () + course: Incomplete + type: Incomplete + number: Incomplete + descr: Incomplete + grades: Incomplete + +class Course(Entity): + __slots__ = () + subject: Incomplete + semester: Incomplete + groups: Incomplete + tasks: Incomplete + lessons: Incomplete + teachers: Incomplete + +class Subject(Entity): + __slots__ = () + name: Incomplete + descr: Incomplete + courses: Incomplete + +class Room(Entity): + __slots__ = () + building: Incomplete + number: Incomplete + floor: Incomplete + schedules: Incomplete + +class Teacher(Entity): + __slots__ = () + dept: Incomplete + name: Incomplete + courses: Incomplete + lessons: Incomplete + +class Lesson(Entity): + __slots__ = () + groups: Incomplete + course: Incomplete + room: Incomplete + teacher: Incomplete + date: Incomplete + +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/examples/demo.pyi b/stubs/pony/pony/orm/examples/demo.pyi new file mode 100644 index 000000000000..b2b31939bb9b --- /dev/null +++ b/stubs/pony/pony/orm/examples/demo.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Customer(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + email: Incomplete + orders: Incomplete + +class Order(Entity): + __slots__ = () + id: Incomplete + total_price: Incomplete + customer: Incomplete + items: Incomplete + +class Product(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + price: Incomplete + items: Incomplete + +class OrderItem(Entity): + __slots__ = () + quantity: Incomplete + order: Incomplete + product: Incomplete + +def populate_database() -> None: ... diff --git a/stubs/pony/pony/orm/examples/estore.pyi b/stubs/pony/pony/orm/examples/estore.pyi new file mode 100644 index 000000000000..8fdc234bab8d --- /dev/null +++ b/stubs/pony/pony/orm/examples/estore.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Customer(Entity): + __slots__ = () + email: Incomplete + password: Incomplete + name: Incomplete + country: Incomplete + address: Incomplete + cart_items: Incomplete + orders: Incomplete + +class Product(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + categories: Incomplete + description: Incomplete + picture: Incomplete + price: Incomplete + quantity: Incomplete + cart_items: Incomplete + order_items: Incomplete + +class CartItem(Entity): + __slots__ = () + quantity: Incomplete + customer: Incomplete + product: Incomplete + +class OrderItem(Entity): + __slots__ = () + quantity: Incomplete + price: Incomplete + order: Incomplete + product: Incomplete + +class Order(Entity): + __slots__ = () + id: Incomplete + state: Incomplete + date_created: Incomplete + date_shipped: Incomplete + date_delivered: Incomplete + total_price: Incomplete + customer: Incomplete + items: Incomplete + +class Category(Entity): + __slots__ = () + name: Incomplete + products: Incomplete + +CREATED: str +SHIPPED: str +DELIVERED: str +CANCELLED: str + +def populate_database() -> None: ... +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/examples/inheritance1.pyi b/stubs/pony/pony/orm/examples/inheritance1.pyi new file mode 100644 index 000000000000..24518002ee50 --- /dev/null +++ b/stubs/pony/pony/orm/examples/inheritance1.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Person(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + dob: Incomplete + ssn: Incomplete + +class Student(Person): + __slots__ = () + group: Incomplete + mentor: Incomplete + attend_courses: Incomplete + +class Teacher(Person): + __slots__ = () + teach_courses: Incomplete + apprentices: Incomplete + salary: Incomplete + +class Assistant(Student, Teacher): + __slots__ = () + +class Professor(Teacher): + __slots__ = () + position: Incomplete + +class Group(Entity): + __slots__ = () + number: Incomplete + students: Incomplete + +class Course(Entity): + __slots__ = () + name: Incomplete + semester: Incomplete + students: Incomplete + teachers: Incomplete + +def populate_database() -> None: ... +def show_all_persons() -> None: ... diff --git a/stubs/pony/pony/orm/examples/numbers.pyi b/stubs/pony/pony/orm/examples/numbers.pyi new file mode 100644 index 000000000000..ab8105fc29c9 --- /dev/null +++ b/stubs/pony/pony/orm/examples/numbers.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Numbers(Entity): + __slots__ = () + id: Incomplete + int8: Incomplete + int16: Incomplete + int24: Incomplete + int32: Incomplete + int64: Incomplete + uint8: Incomplete + uint16: Incomplete + uint24: Incomplete + uint32: Incomplete + +def populate_database() -> None: ... +def test_data() -> None: ... diff --git a/stubs/pony/pony/orm/examples/session01.pyi b/stubs/pony/pony/orm/examples/session01.pyi new file mode 100644 index 000000000000..418f87b14dd5 --- /dev/null +++ b/stubs/pony/pony/orm/examples/session01.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Person(Entity): + name: str + age: int + +p1: Person +p2: Person +x: int +y: int +q: Incomplete diff --git a/stubs/pony/pony/orm/examples/university1.pyi b/stubs/pony/pony/orm/examples/university1.pyi new file mode 100644 index 000000000000..ced29c56889d --- /dev/null +++ b/stubs/pony/pony/orm/examples/university1.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete +from decimal import Decimal as Decimal + +from pony.orm.core import Database, Entity + +db: Database + +class Department(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + groups: Incomplete + courses: Incomplete + +class Group(Entity): + __slots__ = () + number: Incomplete + major: Incomplete + dept: Incomplete + students: Incomplete + +class Course(Entity): + __slots__ = () + name: Incomplete + semester: Incomplete + lect_hours: Incomplete + lab_hours: Incomplete + credits: Incomplete + dept: Incomplete + students: Incomplete + +class Student(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + dob: Incomplete + tel: Incomplete + picture: Incomplete + gpa: Incomplete + group: Incomplete + courses: Incomplete + +params: dict[str, dict[str, str | bool] | dict[str, str | int]] + +def populate_database() -> None: ... +def print_students(students) -> None: ... +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/examples/university2.pyi b/stubs/pony/pony/orm/examples/university2.pyi new file mode 100644 index 000000000000..cc5baed9e4f0 --- /dev/null +++ b/stubs/pony/pony/orm/examples/university2.pyi @@ -0,0 +1,99 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Faculty(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + departments: Incomplete + +class Department(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + faculty: Incomplete + teachers: Incomplete + majors: Incomplete + groups: Incomplete + +class Group(Entity): + __slots__ = () + number: Incomplete + grad_year: Incomplete + department: Incomplete + lessons: Incomplete + students: Incomplete + +class Student(Entity): + __slots__ = () + name: Incomplete + scholarship: Incomplete + group: Incomplete + grades: Incomplete + +class Major(Entity): + __slots__ = () + name: Incomplete + department: Incomplete + courses: Incomplete + +class Subject(Entity): + __slots__ = () + name: Incomplete + courses: Incomplete + teachers: Incomplete + +class Course(Entity): + __slots__ = () + major: Incomplete + subject: Incomplete + semester: Incomplete + lect_hours: Incomplete + pract_hours: Incomplete + credit: Incomplete + lessons: Incomplete + grades: Incomplete + +class Lesson(Entity): + __slots__ = () + day_of_week: Incomplete + meeting_time: Incomplete + classroom: Incomplete + course: Incomplete + teacher: Incomplete + groups: Incomplete + +class Grade(Entity): + __slots__ = () + student: Incomplete + course: Incomplete + teacher: Incomplete + date: Incomplete + value: Incomplete + +class Teacher(Entity): + __slots__ = () + name: Incomplete + degree: Incomplete + department: Incomplete + subjects: Incomplete + lessons: Incomplete + grades: Incomplete + +class Building(Entity): + __slots__ = () + number: Incomplete + description: Incomplete + classrooms: Incomplete + +class Classroom(Entity): + __slots__ = () + building: Incomplete + number: Incomplete + description: Incomplete + lessons: Incomplete + +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/integration/__init__.pyi b/stubs/pony/pony/orm/integration/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/orm/integration/bottle_plugin.pyi b/stubs/pony/pony/orm/integration/bottle_plugin.pyi new file mode 100644 index 000000000000..d8bf1727386c --- /dev/null +++ b/stubs/pony/pony/orm/integration/bottle_plugin.pyi @@ -0,0 +1,6 @@ +def is_allowed_exception(e: BaseException | None) -> bool: ... + +class PonyPlugin: + name: str + api: int + def apply(self, callback, route): ... diff --git a/stubs/pony/pony/orm/ormtypes.pyi b/stubs/pony/pony/orm/ormtypes.pyi new file mode 100644 index 000000000000..6ae9e0566dba --- /dev/null +++ b/stubs/pony/pony/orm/ormtypes.pyi @@ -0,0 +1,156 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import Any +from typing_extensions import Self + +NoneType: type[None] + +class LongStr(str): + lazy: bool + +LongUnicode = LongStr + +class SetType: + __slots__ = "item_type" + def __deepcopy__(self, memo) -> Self: ... + item_type: Incomplete + def __init__(self, item_type) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... + +class FuncType: + __slots__ = "func" + def __deepcopy__(self, memo) -> Self: ... + func: Incomplete + def __init__(self, func) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... + +class MethodType: + __slots__ = ("obj", "func") + def __deepcopy__(self, memo) -> Self: ... + obj: Incomplete + func: Incomplete + def __init__(self, method) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... + +raw_sql_cache: dict[str, Incomplete] + +def parse_raw_sql(sql: str): ... +def raw_sql(sql: str, result_type=None) -> RawSQL: ... + +class RawSQL: + def __deepcopy__(self, memo) -> None: ... + sql: str + result_type: Incomplete + def __init__( + self, sql: str, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None, result_type=None + ) -> None: ... + +class RawSQLType: + def __deepcopy__(self, memo) -> Self: ... + sql: str + items: Incomplete + types: Incomplete + result_type: Incomplete + def __init__(self, sql: str, items, types, result_type) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + +class QueryType: + query_key: Incomplete + translator: Incomplete + limit: Incomplete + offset: Incomplete + def __init__(self, query, limit=None, offset=None) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + +def normalize(value): ... +def normalize_type(t): ... + +coercions: Incomplete + +def coerce_types(t1, t2): ... +def are_comparable_types(t1, t2, op: str = "=="): ... + +class TrackedValue: + obj_ref: Incomplete + attr: Incomplete + def __init__(self, obj, attr) -> None: ... + @classmethod + def make(cls, obj, attr, value): ... + def get_untracked(self) -> None: ... + +def tracked_method(func): ... + +class TrackedDict(TrackedValue, dict[Incomplete, Incomplete]): + def __init__(self, obj, attr, value) -> None: ... + def __reduce__(self): ... + __setitem__: Incomplete + __delitem__: Incomplete + def update(self, *args, **kwargs): ... + setdefault: Incomplete + pop: Incomplete + popitem: Incomplete + clear: Incomplete + def get_untracked(self): ... + +class TrackedList(TrackedValue, list[Incomplete]): + def __init__(self, obj, attr, value) -> None: ... + def __reduce__(self): ... + __setitem__: Incomplete + __delitem__: Incomplete + extend: Incomplete + append: Incomplete + pop: Incomplete + remove: Incomplete + insert: Incomplete + reverse: Incomplete + sort: Incomplete + clear: Incomplete + def get_untracked(self): ... + +def validate_item(item_type, item): ... + +class TrackedArray(TrackedList): + item_type: Incomplete + def __init__(self, obj, attr, value) -> None: ... + def extend(self, items) -> None: ... + def append(self, item) -> None: ... + def insert(self, index, item) -> None: ... + def __setitem__(self, index, item) -> None: ... + def __contains__(self, item) -> bool: ... + +class Json: + @classmethod + def default_empty_value(cls): ... + wrapped: Incomplete + def __init__(self, wrapped) -> None: ... + +class Array: + item_type: type | None + @classmethod + def default_empty_value(cls): ... + +class IntArray(Array): + item_type: type[int] + +class StrArray(Array): + item_type: type[str] + +class FloatArray(Array): + item_type: type[float] + +numeric_types: set[type] +comparable_types: set[type] +primitive_types: set[type] +function_types: set[type] +type_normalization_dict: dict[type, type] +array_types: dict[type, type[Array]] diff --git a/stubs/pony/pony/orm/serialization.pyi b/stubs/pony/pony/orm/serialization.pyi new file mode 100644 index 000000000000..9d3b953a0c05 --- /dev/null +++ b/stubs/pony/pony/orm/serialization.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Iterable +from datetime import date, datetime +from decimal import Decimal + +from pony.orm.core import Database, Entity + +class Bag: + database: Database + session_cache: Incomplete + entity_configs: dict[Entity, tuple[Incomplete, bool]] + objects: defaultdict[type[Entity], set[Entity]] + vars: dict[Incomplete, Incomplete] + dicts: defaultdict[Incomplete, dict[Incomplete, Incomplete]] + def __init__(self, database: Database) -> None: ... + def config( + self, + entity: Entity, + only=None, + exclude=None, + with_collections: bool = True, + with_lazy: bool = False, + related_objects: bool = True, + ) -> tuple[Incomplete, bool]: ... + def put(self, x: Entity | Iterable[Entity]) -> None: ... + def to_dict(self): ... + def to_json(self) -> str: ... + +def to_dict(objects): ... +def to_json(objects) -> str: ... +def json_converter(x: datetime | date | Decimal) -> str: ... diff --git a/stubs/pony/pony/orm/sqlbuilding.pyi b/stubs/pony/pony/orm/sqlbuilding.pyi new file mode 100644 index 000000000000..8b17488758ed --- /dev/null +++ b/stubs/pony/pony/orm/sqlbuilding.pyi @@ -0,0 +1,159 @@ +import types +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar + +class AstError(Exception): ... + +class Param: + __slots__ = ("style", "id", "paramkey", "converter", "optimistic") + style: Incomplete + id: Incomplete + paramkey: Incomplete + converter: Incomplete + optimistic: bool + def __init__(self, paramstyle, paramkey, converter=None, optimistic: bool = False) -> None: ... + def eval(self, values): ... + +class CompositeParam(Param): + __slots__ = ("items", "func") + items: Iterable[Param | Value] + func: Incomplete + def __init__(self, paramstyle, paramkey, items: Iterable[Param | Value], func) -> None: ... + def eval(self, values): ... + +class Value: + __slots__ = ("paramstyle", "value") + paramstyle: Incomplete + value: Incomplete + def __init__(self, paramstyle, value) -> None: ... + def quote_str(self, s: str) -> str: ... + +def flat(tree): ... +def flat_conditions(conditions): ... +def join(delimiter, items): ... +def move_conditions_from_inner_join_to_where(sections): ... +def make_binary_op(symbol, default_parentheses: bool = False): ... +def make_unary_func(symbol): ... +def indentable(method): ... + +class SQLBuilder: + dialect: ClassVar[str | None] + param_class: ClassVar[type[Param]] + composite_param_class: ClassVar[type[CompositeParam]] + value_class: ClassVar[type[Value]] + indent_spaces: ClassVar[str] + least_func_name: ClassVar[str] + greatest_func_name: ClassVar[str] + def __init__(self, provider, ast) -> None: ... + def __call__(self, ast): ... + def INSERT(self, table_name, columns, values, returning=None): ... + def DEFAULT(self): ... + def UPDATE(self, table_name, pairs, where=None): ... + def DELETE(self, alias, from_ast, where=None): ... + def SELECT(self, *sections): ... + def SELECT_FOR_UPDATE(self, nowait, skip_locked, *sections): ... + def EXISTS(self, *sections): ... + def NOT_EXISTS(self, *sections): ... + def ALL(builder, *expr_list): ... + def DISTINCT(builder, *expr_list): ... + def AGGREGATES(builder, *expr_list): ... + def AS(self, expr, alias): ... + def compound_name(self, name_parts): ... + def sql_join(self, join_type, sources): ... + def FROM(self, *sources): ... + def INNER_JOIN(self, *sources): ... + def LEFT_JOIN(builder, *sources): ... + def WHERE(self, *conditions): ... + def HAVING(self, *conditions): ... + def GROUP_BY(builder, *expr_list): ... + def UNION(builder, kind, *sections): ... + def INTERSECT(builder, *sections): ... + def EXCEPT(builder, *sections): ... + def ORDER_BY(builder, *order_list): ... + def DESC(self, expr): ... + def LIMIT(builder, limit, offset=None): ... + def COLUMN(self, table_alias, col_name): ... + def PARAM(self, paramkey, converter=None, optimistic: bool = False): ... + def make_param(self, param_class, paramkey, *args): ... + def make_composite_param(self, paramkey, items, func): ... + def STAR(self, table_alias): ... + def ROW(self, *items): ... + def VALUE(self, value): ... + def AND(self, *cond_list): ... + def OR(self, *cond_list): ... + def NOT(self, condition): ... + def POW(self, expr1, expr2): ... + EQ: Incomplete + NE: Incomplete + LT: Incomplete + LE: Incomplete + GT: Incomplete + GE: Incomplete + ADD: Incomplete + SUB: Incomplete + MUL: Incomplete + DIV: Incomplete + FLOORDIV: Incomplete + def MOD(self, a, b): ... + def FLOAT_EQ(self, a, b): ... + def FLOAT_NE(self, a, b): ... + def CONCAT(self, *args): ... + def NEG(self, expr): ... + def IS_NULL(self, expr): ... + def IS_NOT_NULL(self, expr): ... + def LIKE(self, expr, template, escape=None): ... + def NOT_LIKE(self, expr, template, escape=None): ... + def BETWEEN(self, expr1, expr2, expr3): ... + def NOT_BETWEEN(self, expr1, expr2, expr3): ... + def IN(self, expr1, x): ... + def NOT_IN(self, expr1, x): ... + def COUNT(self, distinct, *expr_list): ... + def SUM(self, distinct, expr): ... + def AVG(self, distinct, expr): ... + def GROUP_CONCAT(self, distinct, expr, sep=None): ... + UPPER: Incomplete + LOWER: Incomplete + LENGTH: Incomplete + ABS: Incomplete + def COALESCE(self, *args): ... + def MIN(self, distinct, *args): ... + def MAX(self, distinct, *args): ... + def SUBSTR(self, expr, start, len=None): ... + def STRING_SLICE(self, expr, start, stop): ... + def CASE(self, expr, cases, default=None): ... + def IF(self, cond, then, else_): ... + def TRIM(self, expr, chars=None): ... + def LTRIM(self, expr, chars=None): ... + def RTRIM(self, expr, chars=None): ... + def REPLACE(self, str, from_, to): ... + def TO_INT(self, expr): ... + def TO_STR(self, expr): ... + def TO_REAL(self, expr): ... + def TODAY(self): ... + def NOW(self): ... + def DATE(self, expr): ... + def YEAR(self, expr): ... + def MONTH(self, expr): ... + def DAY(self, expr): ... + def HOUR(self, expr): ... + def MINUTE(self, expr): ... + def SECOND(self, expr): ... + def RANDOM(self): ... + def RAWSQL(self, sql): ... + def build_json_path(self, path): ... + @classmethod + def eval_json_path(cls, values: Iterable[int | str | types.EllipsisType | slice]) -> str: ... + def JSON_QUERY(self, expr, path) -> None: ... + def JSON_VALUE(self, expr, path, type) -> None: ... + def JSON_NONZERO(self, expr) -> None: ... + def JSON_CONCAT(self, left, right) -> None: ... + def JSON_CONTAINS(self, expr, path, key) -> None: ... + def JSON_ARRAY_LENGTH(self, value) -> None: ... + def JSON_PARAM(self, expr): ... + def ARRAY_INDEX(self, col, index) -> None: ... + def ARRAY_CONTAINS(self, key, not_in, col) -> None: ... + def ARRAY_SUBSET(self, array1, not_in, array2) -> None: ... + def ARRAY_LENGTH(self, array) -> None: ... + def ARRAY_SLICE(self, array, start, stop) -> None: ... + def MAKE_ARRAY(self, *items) -> None: ... diff --git a/stubs/pony/pony/orm/sqlsymbols.pyi b/stubs/pony/pony/orm/sqlsymbols.pyi new file mode 100644 index 000000000000..237991537b91 --- /dev/null +++ b/stubs/pony/pony/orm/sqlsymbols.pyi @@ -0,0 +1,88 @@ +from typing import Final + +symbols: Final[list[str]] +SELECT: Final = "SELECT" +INSERT: Final = "INSERT" +UPDATE: Final = "UPDATE" +DELETE: Final = "DELETE" +SELECT_FOR_UPDATE: Final = "SELECT_FOR_UPDATE" +FROM: Final = "FROM" +INNER_JOIN: Final = "INNER_JOIN" +LEFT_JOIN: Final = "LEFT_JOIN" +WHERE: Final = "WHERE" +GROUP_BY: Final = "GROUP_BY" +HAVING: Final = "HAVING" +UNION: Final = "UNION" +INTERSECT: Final = "INTERSECT" +EXCEPT: Final = "EXCEPT" +ORDER_BY: Final = "ORDER_BY" +LIMIT: Final = "LIMIT" +ASC: Final = "ASC" +DESC: Final = "DESC" +DISTINCT: Final = "DISTINCT" +ALL: Final = "ALL" +AGGREGATES: Final = "AGGREGATES" +AS: Final = "AS" +COUNT: Final = "COUNT" +SUM: Final = "SUM" +MIN: Final = "MIN" +MAX: Final = "MAX" +AVG: Final = "AVG" +TABLE: Final = "TABLE" +COLUMN: Final = "COLUMN" +PARAM: Final = "PARAM" +VALUE: Final = "VALUE" +AND: Final = "AND" +OR: Final = "OR" +NOT: Final = "NOT" +EQ: Final = "EQ" +NE: Final = "NE" +LT: Final = "LT" +LE: Final = "LE" +GT: Final = "GT" +GE: Final = "GE" +IS_NULL: Final = "IS_NULL" +IS_NOT_NULL: Final = "IS_NOT_NULL" +LIKE: Final = "LIKE" +NOT_LIKE: Final = "NOT_LIKE" +BETWEEN: Final = "BETWEEN" +NOT_BETWEEN: Final = "NOT_BETWEEN" +IN: Final = "IN" +NOT_IN: Final = "NOT_IN" +EXISTS: Final = "EXISTS" +NOT_EXISTS: Final = "NOT_EXISTS" +ROW: Final = "ROW" +ADD: Final = "ADD" +SUB: Final = "SUB" +MUL: Final = "MUL" +DIV: Final = "DIV" +POW: Final = "POW" +NEG: Final = "NEG" +ABS: Final = "ABS" +UPPER: Final = "UPPER" +LOWER: Final = "LOWER" +CONCAT: Final = "CONCAT" +STRIN: Final = "STRIN" +SUBSTR: Final = "SUBSTR" +LENGTH: Final = "LENGTH" +TRIM: Final = "TRIM" +LTRIM: Final = "LTRIM" +RTRIM: Final = "RTRIM" +REPLACE: Final = "REPLACE" +CASE: Final = "CASE" +COALESCE: Final = "COALESCE" +TO_INT: Final = "TO_INT" +RANDOM: Final = "RANDOM" +DATE: Final = "DATE" +YEAR: Final = "YEAR" +MONTH: Final = "MONTH" +DAY: Final = "DAY" +HOUR: Final = "HOUR" +MINUTE: Final = "MINUTE" +SECOND: Final = "SECOND" +TODAY: Final = "TODAY" +NOW: Final = "NOW" +DATE_ADD: Final = "DATE_ADD" +DATE_SUB: Final = "DATE_SUB" +DATETIME_ADD: Final = "DATETIME_ADD" +DATETIME_SUB: Final = "DATETIME_SUB" diff --git a/stubs/pony/pony/orm/sqltranslation.pyi b/stubs/pony/pony/orm/sqltranslation.pyi new file mode 100644 index 000000000000..51d8030f0034 --- /dev/null +++ b/stubs/pony/pony/orm/sqltranslation.pyi @@ -0,0 +1,773 @@ +import ast +import itertools +import re +import sys +import types +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Sequence +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from random import random +from typing import Any, ClassVar +from typing_extensions import Never, Self + +from pony.orm import core +from pony.orm.asttranslation import ASTTranslator +from pony.orm.ormtypes import raw_sql +from pony.utils import between, coalesce, concat, localbase + +NoneType: type[None] + +def check_comparable(left_monad: Monad, right_monad: Monad, op: str = "==") -> None: ... + +class IncomparableTypesError(TypeError): + type1: Incomplete + type2: Incomplete + def __init__(self, type1, type2) -> None: ... + +def sqland(items): ... +def sqlor(items): ... +def join_tables(alias1, alias2, columns1, columns2): ... +def type2str(t) -> str: ... + +class Local(localbase): + translators: list[SQLTranslator] + def __init__(self) -> None: ... + @property + def translator(self) -> SQLTranslator: ... + +translator_counter: itertools.count[int] +local: Local + +class SQLTranslator(ASTTranslator): + dialect: ClassVar[str | None] + row_value_syntax: ClassVar[bool] + json_path_wildcard_syntax: ClassVar[bool] + json_values_are_comparable: ClassVar[bool] + rowid_support: ClassVar[bool] + registered_functions: dict[types.FunctionType, type[FuncMonad]] + def __enter__(translator) -> None: ... + def __exit__(translator, exc_type, exc_val, exc_tb) -> None: ... + def default_post(self, node) -> None: ... + def dispatch(self, node): ... + def dispatch_external(self, node) -> None: ... + def call(self, method, node): ... + def deepcopy(self): ... + def __init__( + self, + tree, + parent_translator, + code_key=None, + filter_num=None, + extractors=None, + vars=None, + vartypes=None, + left_join: bool = False, + optimize=None, + ) -> None: ... + def init( + self, + tree, + parent_translator, + code_key=None, + filter_num=None, + extractors=None, + vars=None, + vartypes=None, + left_join: bool = False, + optimize=None, + ): ... + @property + def namespace(translator): ... + def can_be_optimized(self): ... + def process_query_qual( + self, prev_translator, prev_limit, prev_offset, names, try_extend_prev_query: bool = False + ) -> None: ... + def construct_subquery_ast( + self, limit=None, offset=None, aliases=None, star=None, distinct=None, is_not_null_checks: bool = False + ): ... + def construct_sql_ast( + self, + limit=None, + offset=None, + distinct=None, + aggr_func_name=None, + aggr_func_distinct=None, + sep=None, + for_update: bool = False, + nowait: bool = False, + skip_locked: bool = False, + is_not_null_checks: bool = False, + ): ... + def construct_delete_sql_ast(self): ... + def get_used_attrs(self): ... + def without_order(self) -> Self: ... + def order_by_numbers(self, numbers: Iterable[int]) -> Self: ... + def order_by_attributes(self, attrs: Iterable[core.DescWrapper | core.Attribute]) -> Self: ... + def apply_kwfilters(self, filterattrs, original_names: bool = False) -> Self: ... + def apply_lambda( + self, func_id, filter_num, order_by, func_ast, argnames, original_names, extractors, vars, vartypes + ) -> Self: ... + def preGeneratorExp(self, node: ast.GeneratorExp) -> QuerySetMonad: ... + def postExpr(self, node: ast.Expr): ... + def preCompare(self, node: ast.Compare): ... + def postConstant(self, node: ast.Constant) -> ConstMonad: ... + if sys.version_info >= (3, 14): + def postNameConstant(self, node: ast.Constant): ... + def postNum(self, node: ast.Constant) -> ConstMonad: ... + def postStr(self, node: ast.Constant) -> ConstMonad: ... + def postBytes(self, node: ast.Constant) -> ConstMonad: ... + else: + def postNameConstant(self, node: ast.NameConstant): ... + def postNum(self, node: ast.Num) -> ConstMonad: ... + def postStr(self, node: ast.Str) -> ConstMonad: ... + def postBytes(self, node: ast.Bytes) -> ConstMonad: ... + + def postList(self, node: ast.List) -> ListMonad: ... + def postTuple(self, node: ast.Tuple) -> ListMonad: ... + def postName(self, node: ast.Name) -> Monad: ... + def resolve_name(self, name) -> Monad: ... + def postAdd(self, node: ast.Add): ... + def postSub(self, node: ast.Sub): ... + def postMult(self, node: ast.Mult): ... + def postMatMult(self, node: ast.MatMult) -> Never: ... + def postDiv(self, node: ast.Div): ... + def postFloorDiv(self, node: ast.FloorDiv): ... + def postMod(self, node: ast.Mod): ... + def postLShift(self, node: ast.LShift) -> Never: ... + def postRShift(self, node: ast.RShift) -> Never: ... + def postPow(self, node: ast.Pow): ... + def postUSub(self, node: ast.USub): ... + def postAttribute(self, node: ast.Attribute): ... + def postAnd(self, node: ast.And) -> AndMonad: ... + def postOr(self, node: ast.Or) -> OrMonad: ... + def postBitOr(self, node: ast.BitOr): ... + def postBitAnd(self, node: ast.BitAnd): ... + def postBitXor(self, node: ast.BitXor): ... + def postNot(self, node: ast.Not): ... + def preCall(self, node: ast.Call): ... + def postCall(self, node: ast.Call): ... + def postkeyword(self, node: ast.keyword) -> None: ... + def postSubscript(self, node: ast.Subscript): ... + def postSlice(self, node: ast.Slice) -> None: ... + def postIndex(self, node: ast.Index): ... + def postIfExp(self, node: ast.IfExp) -> ExprMonad: ... + def postJoinedStr(self, node: ast.JoinedStr) -> StringExprMonad: ... + def postFormattedValue(self, node: ast.FormattedValue): ... + +def combine_limit_and_offset(limit, offset, limit2, offset2) -> tuple[Incomplete, Incomplete]: ... +def coerce_monads(m1, m2, for_comparison: bool = False): ... + +max_alias_length: int + +class SqlQuery: + translator: Incomplete + parent_sqlquery: SqlQuery | None + left_join: bool + from_ast: list[Incomplete] + conditions: list[Incomplete] + outer_conditions: list[Incomplete] + tablerefs: dict[Incomplete, Incomplete] + alias_counters: dict[Incomplete, Incomplete] + expr_counter: itertools.count[int] + used_from_subquery: bool + def __init__(self, translator, parent_sqlquery: SqlQuery | None = None, left_join: bool = False) -> None: ... + def get_tableref(self, name_path): ... + def add_tableref(self, name_path, parent_tableref, attr) -> JoinedTableRef: ... + def make_alias(self, name: str) -> str: ... + def join_table(self, parent_alias, alias, table_name, join_cond) -> None: ... + +class TableRef: + sqlquery: SqlQuery + alias: str + name_path: str + entity: Incomplete + joined: bool + can_affect_distinct: bool + used_attrs: set[Incomplete] + def __init__(self, sqlquery: SqlQuery, name: str, entity) -> None: ... + def make_join(self, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class ExprTableRef(TableRef): + def __init__(self, sqlquery: SqlQuery, name: str, subquery_ast, expr_names, expr_aliases) -> None: ... + def make_join(self, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class StarTableRef(TableRef): + def __init__(self, sqlquery: SqlQuery, name: str, entity, subquery_ast) -> None: ... + def make_join(self, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class ExprJoinedTableRef: + def __init__(self, sqlquery: SqlQuery, parent_tableref, parent_columns, name, entity) -> None: ... + def make_join(self, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class JoinedTableRef: + sqlquery: SqlQuery + name_path: str + var_name: str | None + alias: str | None + optimized: bool | None + parent_tableref: Incomplete + attr: Incomplete + entity: Incomplete + joined: bool + can_affect_distinct: bool + used_attrs: set[Incomplete] + def __init__(self, sqlquery: SqlQuery, name_path: str, parent_tableref, attr) -> None: ... + def make_join(self, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +def wrap_monad_method(cls_name: str, func: types.FunctionType): ... + +class MonadMeta(type): + def __new__(meta, cls_name: str, bases: tuple[type, ...], cls_dict: dict[str, Any]): ... + +class MonadMixin(metaclass=MonadMeta): ... + +class Monad(metaclass=MonadMeta): + disable_distinct: ClassVar[bool] + disable_ordering: ClassVar[bool] + node: Incomplete + translator: SQLTranslator + type: Incomplete + nullable: bool + def __init__(self, type, nullable: bool = True) -> None: ... + def mixin_init(self) -> None: ... + def to_single_cell_value(self): ... + def cmp(self, op, monad2): ... + def contains(self, item, not_in: bool = False) -> None: ... + def nonzero(self): ... + def negate(self): ... + def getattr(self, attrname): ... + def len(self) -> None: ... + def count(self, distinct=None): ... + def aggregate(self, func_name, distinct=None, sep=None): ... + def __call__(self, *args, **kwargs) -> None: ... + def __getitem__(monad, key) -> None: ... + def __add__(monad, monad2) -> None: ... + def __sub__(monad, monad2) -> None: ... + def __mul__(monad, monad2) -> None: ... + def __truediv__(monad, monad2) -> None: ... + def __floordiv__(monad, monad2) -> None: ... + def __pow__(monad, monad2) -> None: ... + def __neg__(monad) -> None: ... + def __or__(monad, monad2) -> None: ... + def __and__(monad, monad2) -> None: ... + def __xor__(monad, monad2) -> None: ... + def abs(self) -> None: ... + def cast_from_json(self, type) -> None: ... + def to_int(self): ... + def to_str(self): ... + def to_real(self): ... + +def distinct_from_monad(distinct, default=None): ... + +class RawSQLMonad(Monad): + def __init__(self, rawtype, varkey, nullable: bool = True) -> None: ... + def contains(self, item, not_in: bool = False): ... + def nonzero(self): ... + def getsql(self, sqlquery=None): ... + +typeerror_re_1: re.Pattern[str] +typeerror_re_2: re.Pattern[str] + +def reraise_improved_typeerror(exc: Exception, func_name: str | tuple[str, ...], orig_func_name: str) -> Never: ... +def raise_forgot_parentheses(monad: Monad) -> Never: ... + +class MethodMonad(Monad): + def __init__(self, parent, attrname) -> None: ... + def getattr(self, attrname) -> None: ... + def __call__(self, *args, **kwargs): ... + def contains(self, item, not_in: bool = False) -> None: ... + def nonzero(self) -> None: ... + def negate(self) -> None: ... + def aggregate(self, func_name, distinct=None, sep=None) -> None: ... + def __getitem__(monad, key) -> None: ... + def __add__(monad, monad2) -> None: ... + def __sub__(monad, monad2) -> None: ... + def __mul__(monad, monad2) -> None: ... + def __truediv__(monad, monad2) -> None: ... + def __floordiv__(monad, monad2) -> None: ... + def __pow__(monad, monad2) -> None: ... + def __neg__(monad) -> None: ... + def abs(self) -> None: ... + +class EntityMonad(Monad): + def __init__(self, entity) -> None: ... + def __getitem__(monad, *args) -> None: ... + +class ListMonad(Monad): + def __init__(self, items) -> None: ... + def contains(self, x, not_in: bool = False): ... + def getsql(self, sqlquery=None): ... + +class BufferMixin(MonadMixin): ... +class UuidMixin(MonadMixin): ... + +def make_numeric_binop(op, sqlop): ... + +class NumericMixin(MonadMixin): + def mixin_init(self) -> None: ... + __add__: Incomplete + __sub__: Incomplete + __mul__: Incomplete + __truediv__: Incomplete + __floordiv__: Incomplete + __mod__: Incomplete + __and__: Incomplete + __or__: Incomplete + __xor__: Incomplete + def __pow__(monad, monad2): ... + def __neg__(monad): ... + def abs(self): ... + def nonzero(self): ... + def negate(self): ... + +def numeric_attr_factory(name): ... +def make_datetime_binop(op, sqlop): ... + +class DateMixin(MonadMixin): + def mixin_init(self) -> None: ... + attr_year: Incomplete + attr_month: Incomplete + attr_day: Incomplete + def __add__(monad, other): ... + def __sub__(monad, other): ... + +class TimeMixin(MonadMixin): + def mixin_init(self) -> None: ... + attr_hour: Incomplete + attr_minute: Incomplete + attr_second: Incomplete + +class TimedeltaMixin(MonadMixin): + def mixin_init(self) -> None: ... + +class DatetimeMixin(DateMixin): + def mixin_init(self) -> None: ... + def call_date(self): ... + attr_hour: Incomplete + attr_minute: Incomplete + attr_second: Incomplete + def __add__(monad, other): ... + def __sub__(monad, other): ... + +def make_string_binop(op, sqlop): ... +def make_string_func(sqlop): ... + +class StringMixin(MonadMixin): + def mixin_init(self) -> None: ... + __add__: Incomplete + def __getitem__(monad, index): ... + def negate(self): ... + def nonzero(self): ... + def len(self): ... + def contains(self, item, not_in: bool = False): ... + call_upper: Incomplete + call_lower: Incomplete + def call_startswith(self, arg): ... + def call_endswith(self, arg): ... + def strip(self, chars, strip_type): ... + def call_strip(self, chars=None): ... + def call_lstrip(self, chars=None): ... + def call_rstrip(self, chars=None): ... + +class JsonMixin: + disable_distinct: ClassVar[bool] + disable_ordering: ClassVar[bool] + def mixin_init(self) -> None: ... + def get_path(self): ... + def __getitem__(monad, key): ... + def contains(self, key, not_in: bool = False): ... + def __or__(monad, other): ... + def len(self): ... + def cast_from_json(self, type): ... + def nonzero(self): ... + +class ArrayMixin(MonadMixin): + def contains(self, key, not_in: bool = False): ... + def len(self): ... + def nonzero(self): ... + def __getitem__(monad, index): ... + +class ObjectMixin(MonadMixin): + def mixin_init(self) -> None: ... + def negate(self): ... + def nonzero(self): ... + def getattr(self, attrname): ... + def requires_distinct(self, joined: bool = False): ... + +class ObjectIterMonad(ObjectMixin, Monad): + def __init__(self, tableref, entity) -> None: ... + def getsql(self, sqlquery=None): ... + def requires_distinct(self, joined: bool = False): ... + +class AttrMonad(Monad): + @staticmethod + def new(parent, attr, *args, **kwargs) -> AttrMonad: ... + def __new__(cls, parent, attr): ... + def __init__(self, parent, attr) -> None: ... + def getsql(self, sqlquery=None): ... + +class ObjectAttrMonad(ObjectMixin, AttrMonad): + def __init__(self, parent, attr) -> None: ... + +class StringAttrMonad(StringMixin, AttrMonad): ... +class NumericAttrMonad(NumericMixin, AttrMonad): ... +class DateAttrMonad(DateMixin, AttrMonad): ... +class TimeAttrMonad(TimeMixin, AttrMonad): ... +class TimedeltaAttrMonad(TimedeltaMixin, AttrMonad): ... +class DatetimeAttrMonad(DatetimeMixin, AttrMonad): ... +class BufferAttrMonad(BufferMixin, AttrMonad): ... +class UuidAttrMonad(UuidMixin, AttrMonad): ... +class JsonAttrMonad(JsonMixin, AttrMonad): ... +class ArrayAttrMonad(ArrayMixin, AttrMonad): ... + +class ParamMonad(Monad): + @staticmethod + def new(t, paramkey) -> ParamMonad: ... + def __new__(cls, *args, **kwargs): ... + def __init__(self, t, paramkey) -> None: ... + def getsql(self, sqlquery=None): ... + +class ObjectParamMonad(ObjectMixin, ParamMonad): + def __init__(self, entity, paramkey) -> None: ... + def getsql(self, sqlquery=None): ... + def requires_distinct(self, joined: bool = False) -> None: ... + +class StringParamMonad(StringMixin, ParamMonad): ... +class NumericParamMonad(NumericMixin, ParamMonad): ... +class DateParamMonad(DateMixin, ParamMonad): ... +class TimeParamMonad(TimeMixin, ParamMonad): ... +class TimedeltaParamMonad(TimedeltaMixin, ParamMonad): ... +class DatetimeParamMonad(DatetimeMixin, ParamMonad): ... +class BufferParamMonad(BufferMixin, ParamMonad): ... +class UuidParamMonad(UuidMixin, ParamMonad): ... + +class ArrayParamMonad(ArrayMixin, ParamMonad): + def __init__(self, t, paramkey, list_monad=None) -> None: ... + def contains(self, key, not_in: bool = False): ... + +class JsonParamMonad(JsonMixin, ParamMonad): + def getsql(self, sqlquery=None): ... + +class ExprMonad(Monad): + @staticmethod + def new(t, sql, nullable: bool = True) -> ExprMonad: ... + def __new__(cls, *args, **kwargs): ... + def __init__(self, type, sql, nullable: bool = True) -> None: ... + def getsql(self, sqlquery=None): ... + +class ObjectExprMonad(ObjectMixin, ExprMonad): + def getsql(self, sqlquery=None): ... + +class StringExprMonad(StringMixin, ExprMonad): ... +class NumericExprMonad(NumericMixin, ExprMonad): ... +class DateExprMonad(DateMixin, ExprMonad): ... +class TimeExprMonad(TimeMixin, ExprMonad): ... +class TimedeltaExprMonad(TimedeltaMixin, ExprMonad): ... +class DatetimeExprMonad(DatetimeMixin, ExprMonad): ... +class JsonExprMonad(JsonMixin, ExprMonad): ... +class ArrayExprMonad(ArrayMixin, ExprMonad): ... + +class JsonItemMonad(JsonMixin, Monad): # pyrefly: ignore [inconsistent-inheritance] + def __init__(self, parent, key) -> None: ... + def get_path(self): ... + def to_int(self): ... + def to_str(self): ... + def to_real(self): ... + def cast_from_json(self, type): ... + def getsql(self): ... + +class ConstMonad(Monad): + @staticmethod + def new(value) -> ConstMonad: ... + def __new__(cls, value): ... + def __init__(self, value) -> None: ... + def getsql(self, sqlquery=None): ... + +class NoneMonad(ConstMonad): + type = NoneType + def __new__(cls, value=None): ... + def __init__(self, value=None) -> None: ... + def cmp(self, op, monad2): ... + def contains(self, item, not_in: bool = False): ... + def nonzero(self): ... + def negate(self): ... + def getattr(self, attrname): ... + def len(self): ... + def count(self, distinct=None): ... + def aggregate(self, func_name, distinct=None, sep=None): ... + def __call__(self, *args, **kwargs): ... + def __getitem__(monad, key): ... + def __add__(monad, monad2): ... + def __sub__(monad, monad2): ... + def __mul__(monad, monad2): ... + def __truediv__(monad, monad2): ... + def __floordiv__(monad, monad2): ... + def __pow__(monad, monad2): ... + def __neg__(monad): ... + def __or__(monad, monad2): ... + def __and__(monad, monad2): ... + def __xor__(monad, monad2): ... + def abs(self): ... + def to_int(self): ... + def to_str(self): ... + def to_real(self): ... + +class EllipsisMonad(ConstMonad): ... + +class StringConstMonad(StringMixin, ConstMonad): + def len(self): ... + +class JsonConstMonad(JsonMixin, ConstMonad): ... +class BufferConstMonad(BufferMixin, ConstMonad): ... +class NumericConstMonad(NumericMixin, ConstMonad): ... +class DateConstMonad(DateMixin, ConstMonad): ... +class TimeConstMonad(TimeMixin, ConstMonad): ... +class TimedeltaConstMonad(TimedeltaMixin, ConstMonad): ... +class DatetimeConstMonad(DatetimeMixin, ConstMonad): ... + +class BoolMonad(Monad): + def __init__(self, nullable: bool = True) -> None: ... + def nonzero(self): ... + +sql_negation: dict[str, str] + +class BoolExprMonad(BoolMonad): + def __init__(self, sql, nullable: bool = True) -> None: ... + def getsql(self, sqlquery=None): ... + def negate(self): ... + +cmp_ops: dict[str, str] +cmp_negate: dict[str, str] + +class CmpMonad(BoolMonad): + EQ: str + NE: str + def __init__(self, op: str, left, right) -> None: ... + def negate(self): ... + def getsql(self, sqlquery=None): ... + +class LogicalBinOpMonad(BoolMonad): + def __init__(self, operands) -> None: ... + def getsql(self, sqlquery=None): ... + +class AndMonad(LogicalBinOpMonad): + binop: str + +class OrMonad(LogicalBinOpMonad): + binop: str + +class NotMonad(BoolMonad): + def __init__(self, operand) -> None: ... + def negate(self): ... + def getsql(self, sqlquery=None): ... + +class HybridFuncMonad(Monad): + def __init__(self, func_type, func_name, *params) -> None: ... + def __call__(self, *args, **kwargs): ... + +class HybridMethodMonad(HybridFuncMonad): + def __init__(self, parent, attrname, func) -> None: ... + +registered_functions: dict[types.FunctionType, type[FuncMonad]] + +class FuncMonadMeta(MonadMeta): + def __new__(meta, cls_name: str, bases: tuple[type, ...], cls_dict: dict[str, Any]): ... + +class FuncMonad(Monad, metaclass=FuncMonadMeta): + def __call__(self, *args, **kwargs): ... + +def get_classes(classinfo) -> Generator[Incomplete]: ... + +class FuncIsinstanceMonad(FuncMonad): + func = isinstance + def call(self, obj, classinfo): ... + +class FuncBufferMonad(FuncMonad): + func: type[bytes] + def call(self, source, encoding=None, errors=None): ... + +class FuncBoolMonad(FuncMonad): + func: type[bool] + def call(self, x): ... + +class FuncIntMonad(FuncMonad): + func: type[int] + def call(self, x): ... + +class FuncStrMonad(FuncMonad): + func: type[str] + def call(self, x): ... + +class FuncFloatMonad(FuncMonad): + func: type[float] + def call(self, x): ... + +class FuncDecimalMonad(FuncMonad): + func: type[Decimal] + def call(self, x): ... + +class FuncDateMonad(FuncMonad): + func: type[date] + def call(self, year, month, day): ... + def call_today(self): ... + +class FuncTimeMonad(FuncMonad): + func: type[time] + def call(self, *args): ... + +class FuncTimedeltaMonad(FuncMonad): + func: type[timedelta] + def call(self, days=None, seconds=None, microseconds=None, milliseconds=None, minutes=None, hours=None, weeks=None): ... + +class FuncDatetimeMonad(FuncDateMonad): + func: type[datetime] + def call(self, year, month, day, hour=None, minute=None, second=None, microsecond=None): ... + def call_now(self): ... + +class FuncBetweenMonad(FuncMonad): + func = between + def call(self, x, a, b): ... + +class FuncConcatMonad(FuncMonad): + func = concat + def call(self, *args): ... + +class FuncLenMonad(FuncMonad): + func = len + def call(self, x): ... + +class FuncGetattrMonad(FuncMonad): + func = getattr + def call(self, obj_monad, name_monad): ... + +class FuncRawSQLMonad(FuncMonad): + func = raw_sql + def call(self, *args) -> None: ... + +class FuncCountMonad(FuncMonad): + func: Incomplete + def call(self, x=None, distinct=None): ... + +class FuncAbsMonad(FuncMonad): + func = abs + def call(self, x): ... + +class FuncSumMonad(FuncMonad): + func: Incomplete + def call(self, x, distinct=None): ... + +class FuncAvgMonad(FuncMonad): + func: Incomplete + def call(self, x, distinct=None): ... + +class FuncGroupConcatMonad(FuncMonad): + func: Incomplete + def call(self, x, sep=None, distinct=None): ... + +class FuncCoalesceMonad(FuncMonad): + func = coalesce + def call(self, *args): ... + +class FuncDistinctMonad(FuncMonad): + func: Incomplete + def call(self, x): ... + +class FuncMinMonad(FuncMonad): + func: Incomplete + def call(self, *args): ... + +class FuncMaxMonad(FuncMonad): + func: Incomplete + def call(self, *args): ... + +def minmax(monad, sqlop, *args): ... + +class FuncSelectMonad(FuncMonad): + func = core.select + def call(self, queryset): ... + +class FuncExistsMonad(FuncMonad): + func = core.exists + def call(self, arg): ... + +class FuncDescMonad(FuncMonad): + func = core.desc + def call(self, expr): ... + +class DescMonad(Monad): + def __init__(self, expr) -> None: ... + def getsql(self): ... + +class JoinMonad(Monad): + def __init__(self, type) -> None: ... + def __call__(self, x): ... + +class FuncRandomMonad(FuncMonad): + func = random + def __init__(self, type) -> None: ... + def __call__(self): ... + +class SetMixin(MonadMixin): + forced_distinct: bool + def call_distinct(self): ... + +def make_attrset_binop(op, sqlop): ... + +class AttrSetMonad(SetMixin, Monad): + def __init__(self, parent, attr) -> None: ... + def cmp(self, op, monad2) -> None: ... + def contains(self, item, not_in: bool = False): ... + def getattr(self, name): ... + def call_select(self): ... + call_filter = call_select + def call_exists(self): ... + def requires_distinct(self, joined: bool = False, for_count: bool = False): ... + def count(self, distinct=None): ... + len = count + def aggregate(self, func_name, distinct=None, sep=None): ... + def nonzero(self): ... + def negate(self): ... + call_is_empty = negate + def make_tableref(self, sqlquery): ... + def make_expr_list(self): ... + def getsql(self, sqlquery=None): ... + __add__: Incomplete + __sub__: Incomplete + __mul__: Incomplete + __truediv__: Incomplete + __floordiv__: Incomplete + +def make_numericset_binop(op, sqlop): ... + +class NumericSetExprMonad(SetMixin, Monad): + def __init__(self, op, sqlop, left, right) -> None: ... + def aggregate(self, func_name, distinct=None, sep=None): ... + def getsql(self, sqlquery=None): ... + __add__: Incomplete + __sub__: Incomplete + __mul__: Incomplete + __truediv__: Incomplete + __floordiv__: Incomplete + +class QuerySetMonad(SetMixin, Monad): + nogroup: bool + def __init__(self, subtranslator) -> None: ... + def to_single_cell_value(self): ... + def requires_distinct(self, joined: bool = False) -> None: ... + def call_limit(self, limit=None, offset=None): ... + def contains(self, item, not_in: bool = False): ... + def nonzero(self): ... + def negate(self): ... + def count(self, distinct=None): ... + len = count + def aggregate(self, func_name, distinct=None, sep=None): ... + def call_count(self, distinct=None): ... + def call_sum(self, distinct=None): ... + def call_min(self): ... + def call_max(self): ... + def call_avg(self, distinct=None): ... + def call_group_concat(self, sep=None, distinct=None): ... + def getsql(self): ... + +def find_or_create_having_ast(sections: list[Sequence[str]]): ... diff --git a/stubs/pony/pony/py23compat.pyi b/stubs/pony/pony/py23compat.pyi new file mode 100644 index 000000000000..054c77b6c3e8 --- /dev/null +++ b/stubs/pony/pony/py23compat.pyi @@ -0,0 +1,15 @@ +PYPY: bool +PY36: bool +PY37: bool +PY38: bool +PY39: bool +PY310: bool +PY311: bool +PY312: bool +PY313: bool +PY314: bool +unicode = str +buffer = bytes +int_types: tuple[type[int]] + +def cmp(a, b): ... diff --git a/stubs/pony/pony/thirdparty/__init__.pyi b/stubs/pony/pony/thirdparty/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/thirdparty/decorator.pyi b/stubs/pony/pony/thirdparty/decorator.pyi new file mode 100644 index 000000000000..1f521275e4a8 --- /dev/null +++ b/stubs/pony/pony/thirdparty/decorator.pyi @@ -0,0 +1,31 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from inspect import getfullargspec as getfullargspec +from typing import Final + +__version__: Final[str] +__all__ = ["decorator", "FunctionMaker", "contextmanager"] + +def get_init(cls: object) -> Callable[..., None]: ... + +DEF: re.Pattern[str] + +class FunctionMaker: + shortsignature: Incomplete + name: Incomplete + doc: Incomplete + module: Incomplete + annotations: Incomplete + signature: Incomplete + dict: Incomplete + defaults: Incomplete + def __init__(self, func=None, name=None, signature=None, defaults=None, doc=None, module=None, funcdict=None) -> None: ... + def update(self, func, **kw) -> None: ... + def make(self, src_templ, evaldict=None, addsource: bool = False, **attrs): ... + @classmethod + def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource: bool = True, **attrs): ... + +def decorator(caller, func=None): ... + +contextmanager: Incomplete diff --git a/stubs/pony/pony/utils/__init__.pyi b/stubs/pony/pony/utils/__init__.pyi new file mode 100644 index 000000000000..f08d95e954ed --- /dev/null +++ b/stubs/pony/pony/utils/__init__.pyi @@ -0,0 +1,2 @@ +from .properties import * +from .utils import * diff --git a/stubs/pony/pony/utils/properties.pyi b/stubs/pony/pony/utils/properties.pyi new file mode 100644 index 000000000000..912a26d34900 --- /dev/null +++ b/stubs/pony/pony/utils/properties.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +class cached_property: + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, obj, cls): ... + +class class_property: + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, instance, cls): ... + +class class_cached_property: + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, obj, cls): ... diff --git a/stubs/pony/pony/utils/utils.pyi b/stubs/pony/pony/utils/utils.pyi new file mode 100644 index 000000000000..b7fd74ffca7a --- /dev/null +++ b/stubs/pony/pony/utils/utils.pyi @@ -0,0 +1,103 @@ +import ast +import io +import pickle +import re +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Iterable +from datetime import datetime +from threading import local as _localbase +from types import CodeType, FunctionType, TracebackType +from typing import Any, overload +from typing_extensions import Never + +localbase = _localbase + +class PonyDeprecationWarning(DeprecationWarning): ... + +def deprecated(stacklevel: int, message: str) -> None: ... +def decorator(caller, func=None): ... +def decorator_with_params(dec): ... +def cut_traceback(func): ... + +cut_traceback_depth: int + +@overload +def reraise(exc_type: Unused, exc: None, tb: TracebackType | None) -> None: ... +@overload +def reraise(exc_type: Unused, exc: BaseException, tb: TracebackType | None) -> Never: ... + +def throw(exc_type: Exception | Callable[..., Exception], *args, **kwargs) -> Never: ... +def truncate_repr(s: object, max_len: int = 100) -> str: ... + +codeobjects: dict[int, CodeType] + +def get_codeobject_id(codeobject: CodeType) -> int: ... + +lambda_args_cache: dict[int | ast.Lambda, list[str]] + +def get_lambda_args(func: FunctionType | ast.Lambda) -> list[str]: ... +def error_method(*args: Unused, **kwargs: Unused) -> Never: ... +def is_ident(string: str) -> bool: ... +def split_name(name: str) -> list[str]: ... +def uppercase_name(name: str) -> str: ... +def lowercase_name(name: str) -> str: ... +def camelcase_name(name: str) -> str: ... +def mixedcase_name(name: str) -> str: ... +def import_module(name: str): ... +def is_absolute_path(filename: str) -> bool: ... +def absolutize_path(filename: str, frame_depth: int) -> str: ... +def current_timestamp() -> str: ... +def datetime2timestamp(d: datetime) -> str: ... +def timestamp2datetime(t: str) -> datetime: ... + +expr1_re: re.Pattern[str] +expr2_re: re.Pattern[str] +expr3_re: re.Pattern[str] + +def parse_expr(s: str, pos: int = 0) -> tuple[str, bool]: ... +def tostring(x): ... +def strjoin( + sep: str, strings: Iterable[str], source_encoding: str = "ascii", dest_encoding: str | None = None +) -> str | bytes: ... +def count(*args, **kwargs): ... +def avg(iter: Iterable[float | None]) -> float | None: ... + +@overload +def group_concat(items: None, sep: str = ",") -> None: ... +@overload +def group_concat(items: Iterable[object], sep: str = ",") -> str: ... + +def coalesce(*args: Any) -> Any: ... +def distinct(iter): ... +def concat(*args) -> str: ... +def between(x: float, a: float, b: float) -> bool: ... +def is_utf8(encoding: str) -> bool: ... +def pickle_ast(val): ... +def unpickle_ast(pickled: io.BytesIO): ... +def copy_ast(tree): ... + +class PersistentPickler(pickle.Pickler): + def persistent_id(self, obj): ... + +class PersistentUnpickler(pickle.Unpickler): + def persistent_load(self, persid): ... + +class HashableDict(dict[Incomplete, Incomplete]): + def __hash__(self) -> int: ... # type: ignore[override] + def __deepcopy__(self, memo): ... + __setitem__: Incomplete + __delitem__: Incomplete + clear: Incomplete + pop: Incomplete + popitem: Incomplete + setdefault: Incomplete + update: Incomplete + +class IntegerGenerator: + val: int + def __init__(self, firstval: int = 0) -> None: ... + def __iter__(self): ... + def __next__(self) -> int: ... + +def deref_proxy(value): ... +def deduplicate(value, deduplication_cache): ... diff --git a/stubs/portpicker/METADATA.toml b/stubs/portpicker/METADATA.toml new file mode 100644 index 000000000000..17d27f8a5e10 --- /dev/null +++ b/stubs/portpicker/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.6.*" +upstream-repository = "https://github.com/google/python_portpicker" diff --git a/stubs/portpicker/portpicker.pyi b/stubs/portpicker/portpicker.pyi new file mode 100644 index 000000000000..9162cfa9874a --- /dev/null +++ b/stubs/portpicker/portpicker.pyi @@ -0,0 +1,21 @@ +import socket +from typing import TypeAlias + +_Port: TypeAlias = int + +__all__ = ("bind", "is_port_free", "pick_unused_port", "return_port", "add_reserved_port", "get_port_from_port_server") + +class NoFreePortFoundError(Exception): ... + +def add_reserved_port(port: _Port) -> None: ... +def return_port(port: _Port) -> None: ... +def bind(port: _Port, socket_type: socket.SocketKind, socket_proto: int) -> _Port | None: ... +def is_port_free(port: _Port) -> bool: ... +def pick_unused_port(pid: int | None = None, portserver_address: str | None = None) -> _Port: ... +def get_port_from_port_server(portserver_address: str, pid: int | None = None) -> _Port | None: ... + +# legacy aliases +Bind = bind +GetPortFromPortServer = get_port_from_port_server +IsPortFree = is_port_free +PickUnusedPort = pick_unused_port diff --git a/stubs/prettytable/METADATA.toml b/stubs/prettytable/METADATA.toml deleted file mode 100644 index acdc22b5d432..000000000000 --- a/stubs/prettytable/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "2.1.*" diff --git a/stubs/prettytable/prettytable/__init__.pyi b/stubs/prettytable/prettytable/__init__.pyi deleted file mode 100644 index c6eedb462835..000000000000 --- a/stubs/prettytable/prettytable/__init__.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from .prettytable import ( - ALL as ALL, - DEFAULT as DEFAULT, - FRAME as FRAME, - HEADER as HEADER, - MARKDOWN as MARKDOWN, - MSWORD_FRIENDLY as MSWORD_FRIENDLY, - NONE as NONE, - ORGMODE as ORGMODE, - PLAIN_COLUMNS as PLAIN_COLUMNS, - RANDOM as RANDOM, - PrettyTable as PrettyTable, - TableHandler as TableHandler, - from_csv as from_csv, - from_db_cursor as from_db_cursor, - from_html as from_html, - from_html_one as from_html_one, - from_json as from_json, -) diff --git a/stubs/prettytable/prettytable/prettytable.pyi b/stubs/prettytable/prettytable/prettytable.pyi deleted file mode 100644 index 71eb2a38ea1e..000000000000 --- a/stubs/prettytable/prettytable/prettytable.pyi +++ /dev/null @@ -1,181 +0,0 @@ -from html.parser import HTMLParser -from typing import Any - -FRAME: int -ALL: int -NONE: int -HEADER: int -DEFAULT: int -MSWORD_FRIENDLY: int -PLAIN_COLUMNS: int -MARKDOWN: int -ORGMODE: int -RANDOM: int - -class PrettyTable: - encoding: Any - def __init__(self, field_names: Any | None = ..., **kwargs): ... - def __getattr__(self, name): ... - def __getitem__(self, index): ... - @property - def field_names(self): ... - @field_names.setter - def field_names(self, val) -> None: ... - @property - def align(self): ... - @align.setter - def align(self, val) -> None: ... - @property - def valign(self): ... - @valign.setter - def valign(self, val) -> None: ... - @property - def max_width(self): ... - @max_width.setter - def max_width(self, val) -> None: ... - @property - def min_width(self): ... - @min_width.setter - def min_width(self, val) -> None: ... - @property - def min_table_width(self): ... - @min_table_width.setter - def min_table_width(self, val) -> None: ... - @property - def max_table_width(self): ... - @max_table_width.setter - def max_table_width(self, val) -> None: ... - @property - def fields(self): ... - @fields.setter - def fields(self, val) -> None: ... - @property - def title(self): ... - @title.setter - def title(self, val) -> None: ... - @property - def start(self): ... - @start.setter - def start(self, val) -> None: ... - @property - def end(self): ... - @end.setter - def end(self, val) -> None: ... - @property - def sortby(self): ... - @sortby.setter - def sortby(self, val) -> None: ... - @property - def reversesort(self): ... - @reversesort.setter - def reversesort(self, val) -> None: ... - @property - def sort_key(self): ... - @sort_key.setter - def sort_key(self, val) -> None: ... - @property - def header(self): ... - @header.setter - def header(self, val) -> None: ... - @property - def header_style(self): ... - @header_style.setter - def header_style(self, val) -> None: ... - @property - def border(self): ... - @border.setter - def border(self, val) -> None: ... - @property - def hrules(self): ... - @hrules.setter - def hrules(self, val) -> None: ... - @property - def vrules(self): ... - @vrules.setter - def vrules(self, val) -> None: ... - @property - def int_format(self): ... - @int_format.setter - def int_format(self, val) -> None: ... - @property - def float_format(self): ... - @float_format.setter - def float_format(self, val) -> None: ... - @property - def padding_width(self): ... - @padding_width.setter - def padding_width(self, val) -> None: ... - @property - def left_padding_width(self): ... - @left_padding_width.setter - def left_padding_width(self, val) -> None: ... - @property - def right_padding_width(self): ... - @right_padding_width.setter - def right_padding_width(self, val) -> None: ... - @property - def vertical_char(self): ... - @vertical_char.setter - def vertical_char(self, val) -> None: ... - @property - def horizontal_char(self): ... - @horizontal_char.setter - def horizontal_char(self, val) -> None: ... - @property - def junction_char(self): ... - @junction_char.setter - def junction_char(self, val) -> None: ... - @property - def format(self): ... - @format.setter - def format(self, val) -> None: ... - @property - def print_empty(self): ... - @print_empty.setter - def print_empty(self, val) -> None: ... - @property - def attributes(self): ... - @attributes.setter - def attributes(self, val) -> None: ... - @property - def oldsortslice(self): ... - @oldsortslice.setter - def oldsortslice(self, val) -> None: ... - def set_style(self, style) -> None: ... - def add_rows(self, rows) -> None: ... - def add_row(self, row) -> None: ... - def del_row(self, row_index) -> None: ... - def add_column(self, fieldname, column, align: str = ..., valign: str = ...) -> None: ... - def del_column(self, fieldname) -> None: ... - def clear_rows(self) -> None: ... - def clear(self) -> None: ... - def copy(self): ... - def get_string(self, **kwargs): ... - def paginate(self, page_length: int = ..., **kwargs): ... - def get_csv_string(self, **kwargs): ... - def get_json_string(self, **kwargs): ... - def get_html_string(self, **kwargs): ... - -def from_csv(fp, field_names: Any | None = ..., **kwargs): ... -def from_db_cursor(cursor, **kwargs): ... -def from_json(json_string, **kwargs): ... - -class TableHandler(HTMLParser): - kwargs: Any - tables: Any - last_row: Any - rows: Any - max_row_width: int - active: Any - last_content: str - is_last_row_header: bool - colspan: int - def __init__(self, **kwargs) -> None: ... - def handle_starttag(self, tag, attrs) -> None: ... - def handle_endtag(self, tag) -> None: ... - def handle_data(self, data) -> None: ... - def generate_table(self, rows): ... - def make_fields_unique(self, fields) -> None: ... - -def from_html(html_code, **kwargs): ... -def from_html_one(html_code, **kwargs): ... diff --git a/stubs/protobuf/@tests/stubtest_allowlist.txt b/stubs/protobuf/@tests/stubtest_allowlist.txt index 2c5e07c85e85..38356350e0ca 100644 --- a/stubs/protobuf/@tests/stubtest_allowlist.txt +++ b/stubs/protobuf/@tests/stubtest_allowlist.txt @@ -1,185 +1,34 @@ -google.protobuf.__version__ -google.protobuf.any_pb2.Any.__init__ -google.protobuf.api_pb2.Api.__init__ -google.protobuf.api_pb2.Method.__init__ -google.protobuf.api_pb2.Mixin.__init__ -google.protobuf.compiler.plugin_pb2.CodeGeneratorRequest.__init__ -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse.FEATURE_NONE -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse.FEATURE_PROTO3_OPTIONAL -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse.Feature -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse.File.__init__ -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse._Feature -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse._FeatureEnumTypeWrapper -google.protobuf.compiler.plugin_pb2.CodeGeneratorResponse.__init__ -google.protobuf.compiler.plugin_pb2.Version.__init__ -google.protobuf.descriptor.Descriptor.__new__ -google.protobuf.descriptor.FieldDescriptor.__init__ -google.protobuf.descriptor.FieldDescriptor.__new__ -google.protobuf.descriptor.ServiceDescriptor.__new__ -google.protobuf.descriptor._NestedDescriptorBase.GetTopLevelContainingType -google.protobuf.descriptor_pb2.DescriptorProto.ExtensionRange.__init__ -google.protobuf.descriptor_pb2.DescriptorProto.ReservedRange.__init__ -google.protobuf.descriptor_pb2.DescriptorProto.__init__ -google.protobuf.descriptor_pb2.EnumDescriptorProto.EnumReservedRange.__init__ -google.protobuf.descriptor_pb2.EnumDescriptorProto.__init__ -google.protobuf.descriptor_pb2.EnumOptions.__init__ -google.protobuf.descriptor_pb2.EnumValueDescriptorProto.__init__ -google.protobuf.descriptor_pb2.EnumValueOptions.__init__ -google.protobuf.descriptor_pb2.ExtensionRangeOptions.__init__ -google.protobuf.descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL -google.protobuf.descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED -google.protobuf.descriptor_pb2.FieldDescriptorProto.LABEL_REQUIRED -google.protobuf.descriptor_pb2.FieldDescriptorProto.Label -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_BOOL -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_BYTES -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_DOUBLE -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_ENUM -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_FIXED32 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_FIXED64 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_FLOAT -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_GROUP -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_INT32 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_INT64 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_MESSAGE -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_SFIXED32 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_SFIXED64 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_SINT32 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_SINT64 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_STRING -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_UINT32 -google.protobuf.descriptor_pb2.FieldDescriptorProto.TYPE_UINT64 -google.protobuf.descriptor_pb2.FieldDescriptorProto.Type -google.protobuf.descriptor_pb2.FieldDescriptorProto._Label -google.protobuf.descriptor_pb2.FieldDescriptorProto._LabelEnumTypeWrapper -google.protobuf.descriptor_pb2.FieldDescriptorProto._Type -google.protobuf.descriptor_pb2.FieldDescriptorProto._TypeEnumTypeWrapper -google.protobuf.descriptor_pb2.FieldDescriptorProto.__init__ -google.protobuf.descriptor_pb2.FieldOptions.CORD -google.protobuf.descriptor_pb2.FieldOptions.CType -google.protobuf.descriptor_pb2.FieldOptions.JSType -google.protobuf.descriptor_pb2.FieldOptions.JS_NORMAL -google.protobuf.descriptor_pb2.FieldOptions.JS_NUMBER -google.protobuf.descriptor_pb2.FieldOptions.JS_STRING -google.protobuf.descriptor_pb2.FieldOptions.STRING -google.protobuf.descriptor_pb2.FieldOptions.STRING_PIECE -google.protobuf.descriptor_pb2.FieldOptions._CType -google.protobuf.descriptor_pb2.FieldOptions._CTypeEnumTypeWrapper -google.protobuf.descriptor_pb2.FieldOptions._JSType -google.protobuf.descriptor_pb2.FieldOptions._JSTypeEnumTypeWrapper -google.protobuf.descriptor_pb2.FieldOptions.__init__ -google.protobuf.descriptor_pb2.FileDescriptorProto.__init__ -google.protobuf.descriptor_pb2.FileDescriptorSet.__init__ -google.protobuf.descriptor_pb2.FileOptions.CODE_SIZE -google.protobuf.descriptor_pb2.FileOptions.LITE_RUNTIME -google.protobuf.descriptor_pb2.FileOptions.OptimizeMode -google.protobuf.descriptor_pb2.FileOptions.SPEED -google.protobuf.descriptor_pb2.FileOptions._OptimizeMode -google.protobuf.descriptor_pb2.FileOptions._OptimizeModeEnumTypeWrapper -google.protobuf.descriptor_pb2.FileOptions.__init__ -google.protobuf.descriptor_pb2.GeneratedCodeInfo.Annotation.__init__ -google.protobuf.descriptor_pb2.GeneratedCodeInfo.__init__ -google.protobuf.descriptor_pb2.MessageOptions.__init__ -google.protobuf.descriptor_pb2.MethodDescriptorProto.__init__ -google.protobuf.descriptor_pb2.MethodOptions.IDEMPOTENCY_UNKNOWN -google.protobuf.descriptor_pb2.MethodOptions.IDEMPOTENT -google.protobuf.descriptor_pb2.MethodOptions.IdempotencyLevel -google.protobuf.descriptor_pb2.MethodOptions.NO_SIDE_EFFECTS -google.protobuf.descriptor_pb2.MethodOptions._IdempotencyLevel -google.protobuf.descriptor_pb2.MethodOptions._IdempotencyLevelEnumTypeWrapper -google.protobuf.descriptor_pb2.MethodOptions.__init__ -google.protobuf.descriptor_pb2.OneofDescriptorProto.__init__ -google.protobuf.descriptor_pb2.OneofOptions.__init__ -google.protobuf.descriptor_pb2.ServiceDescriptorProto.__init__ -google.protobuf.descriptor_pb2.ServiceOptions.__init__ -google.protobuf.descriptor_pb2.SourceCodeInfo.Location.__init__ -google.protobuf.descriptor_pb2.SourceCodeInfo.__init__ -google.protobuf.descriptor_pb2.UninterpretedOption.NamePart.__init__ -google.protobuf.descriptor_pb2.UninterpretedOption.__init__ -google.protobuf.duration_pb2.Duration.__init__ -google.protobuf.empty_pb2.Empty.__init__ -google.protobuf.field_mask_pb2.FieldMask.__init__ -google.protobuf.internal.containers.BaseContainer.sort -google.protobuf.internal.containers.Mapping -google.protobuf.internal.containers.MessageMap.__init__ -google.protobuf.internal.containers.MessageMap.get -google.protobuf.internal.containers.MutableMapping.__delitem__ -google.protobuf.internal.containers.MutableMapping.__setitem__ -google.protobuf.internal.containers.MutableMapping.pop -google.protobuf.internal.containers.MutableMapping.setdefault -google.protobuf.internal.containers.RepeatedCompositeFieldContainer.__init__ -google.protobuf.internal.containers.RepeatedScalarFieldContainer.__init__ -google.protobuf.internal.containers.ScalarMap.__init__ -google.protobuf.internal.containers.ScalarMap.get -google.protobuf.internal.decoder.BytesDecoder -google.protobuf.internal.decoder.EnumDecoder -google.protobuf.internal.decoder.MessageSetItemDecoder -google.protobuf.internal.decoder.StringDecoder -google.protobuf.internal.encoder.MapSizer +# Generated pb2 methods diverge for a variety of reasons. They are tested +# carefully in mypy-protobuf which internally runs stubtest. Skip those here. +google.protobuf\..*_pb2\..* + +# While Message and Descriptor are both defined with a null DESCRIPTOR, +# subclasses of Message and instances of EnumTypeWrapper require this value to +# be set, and since these type stubs are intended for use with protoc-generated +# python it's more accurate to make them non-nullable. google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper.DESCRIPTOR -google.protobuf.internal.python_message.GeneratedProtocolMessageType.__init__ -google.protobuf.internal.python_message.GeneratedProtocolMessageType.__new__ -google.protobuf.internal.well_known_types.Any.Pack -google.protobuf.internal.well_known_types.Error -google.protobuf.internal.well_known_types.ParseError google.protobuf.message.Message.DESCRIPTOR + +# Exists at runtime, but via a __getitem__/__setitem__ hack +# See https://github.com/protocolbuffers/protobuf/blob/3ea30d80847cd9561db570ae7f673afc15523545/python/google/protobuf/message.py#L67 google.protobuf.message.Message.Extensions -google.protobuf.message.Message.FromString -google.protobuf.message.Message.SerializePartialToString -google.protobuf.message.Message.SerializeToString -google.protobuf.message.Message.__init__ -google.protobuf.service.Service.GetDescriptor -google.protobuf.source_context_pb2.SourceContext.__init__ -google.protobuf.struct_pb2.ListValue.__init__ -google.protobuf.struct_pb2.NULL_VALUE -google.protobuf.struct_pb2.NullValue -google.protobuf.struct_pb2.Struct.FieldsEntry.__init__ -google.protobuf.struct_pb2.Struct.__init__ -google.protobuf.struct_pb2.Value.__init__ -google.protobuf.text_format.MessageToBytes -google.protobuf.timestamp_pb2.Timestamp.__init__ -google.protobuf.type_pb2.Enum.__init__ -google.protobuf.type_pb2.EnumValue.__init__ -google.protobuf.type_pb2.Field.CARDINALITY_OPTIONAL -google.protobuf.type_pb2.Field.CARDINALITY_REPEATED -google.protobuf.type_pb2.Field.CARDINALITY_REQUIRED -google.protobuf.type_pb2.Field.CARDINALITY_UNKNOWN -google.protobuf.type_pb2.Field.Cardinality -google.protobuf.type_pb2.Field.Kind -google.protobuf.type_pb2.Field.TYPE_BOOL -google.protobuf.type_pb2.Field.TYPE_BYTES -google.protobuf.type_pb2.Field.TYPE_DOUBLE -google.protobuf.type_pb2.Field.TYPE_ENUM -google.protobuf.type_pb2.Field.TYPE_FIXED32 -google.protobuf.type_pb2.Field.TYPE_FIXED64 -google.protobuf.type_pb2.Field.TYPE_FLOAT -google.protobuf.type_pb2.Field.TYPE_GROUP -google.protobuf.type_pb2.Field.TYPE_INT32 -google.protobuf.type_pb2.Field.TYPE_INT64 -google.protobuf.type_pb2.Field.TYPE_MESSAGE -google.protobuf.type_pb2.Field.TYPE_SFIXED32 -google.protobuf.type_pb2.Field.TYPE_SFIXED64 -google.protobuf.type_pb2.Field.TYPE_SINT32 -google.protobuf.type_pb2.Field.TYPE_SINT64 -google.protobuf.type_pb2.Field.TYPE_STRING -google.protobuf.type_pb2.Field.TYPE_UINT32 -google.protobuf.type_pb2.Field.TYPE_UINT64 -google.protobuf.type_pb2.Field.TYPE_UNKNOWN -google.protobuf.type_pb2.Field._Cardinality -google.protobuf.type_pb2.Field._CardinalityEnumTypeWrapper -google.protobuf.type_pb2.Field._Kind -google.protobuf.type_pb2.Field._KindEnumTypeWrapper -google.protobuf.type_pb2.Field.__init__ -google.protobuf.type_pb2.Option.__init__ -google.protobuf.type_pb2.SYNTAX_PROTO2 -google.protobuf.type_pb2.SYNTAX_PROTO3 -google.protobuf.type_pb2.Syntax -google.protobuf.type_pb2.Type.__init__ -google.protobuf.wrappers_pb2.BoolValue.__init__ -google.protobuf.wrappers_pb2.BytesValue.__init__ -google.protobuf.wrappers_pb2.DoubleValue.__init__ -google.protobuf.wrappers_pb2.FloatValue.__init__ -google.protobuf.wrappers_pb2.Int32Value.__init__ -google.protobuf.wrappers_pb2.Int64Value.__init__ -google.protobuf.wrappers_pb2.StringValue.__init__ -google.protobuf.wrappers_pb2.UInt32Value.__init__ -google.protobuf.wrappers_pb2.UInt64Value.__init__ + +# Has *args that would fail at runtime with any positional argument +google.protobuf.internal.containers.BaseContainer.sort + +# These are deliberately omitted in the stub. +# The classes can't be constructed directly anyway, +# so the signatures of their constructors are somewhat irrelevant. +google.protobuf.descriptor.Descriptor.__new__ +google.protobuf.descriptor.ServiceDescriptor.__new__ + +# Set to None at runtime - which doesn't match the Sequence base class. +# It's a hack - just allow it. +google.protobuf.internal.containers.BaseContainer.__hash__ + +# Runtime does not have __iter__ (yet...): hack in spirit of https://github.com/python/typeshed/issues/7813 +google.protobuf.internal.well_known_types.ListValue.__iter__ + +# It's a list at runtime, but if we do that pyright complains about incompatible overrides +# in subclasses that use a tuple for __slots__. +google.protobuf.message.Message.__slots__ diff --git a/stubs/protobuf/@tests/test_cases/check_struct.py b/stubs/protobuf/@tests/test_cases/check_struct.py new file mode 100644 index 000000000000..d3679af470cd --- /dev/null +++ b/stubs/protobuf/@tests/test_cases/check_struct.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from google.protobuf.struct_pb2 import ListValue, Struct + +list_value = ListValue() + +lst = list(list_value) # Ensure type checkers recognise that the class is iterable (doesn't have an `__iter__` method at runtime) + +list_value[0] = 42.42 +list_value[0] = "42" +list_value[0] = None +list_value[0] = True +list_value[0] = [42.42, "42", None, True, [42.42, "42", None, True], {"42": 42}] +list_value[0] = ListValue() +list_value[0] = Struct() + +list_element = list_value[0] diff --git a/stubs/protobuf/METADATA.toml b/stubs/protobuf/METADATA.toml index c551073ba407..70379af2df82 100644 --- a/stubs/protobuf/METADATA.toml +++ b/stubs/protobuf/METADATA.toml @@ -1,4 +1,9 @@ -version = "3.18.*" -python2 = true -requires = ["types-futures"] -extra_description = "Generated with aid from mypy-protobuf v3.0.0" +# Using an exact number in the specifier for scripts/sync_protobuf/google_protobuf.py +# When updating, also re-run the script +version = "~=7.35.1" +upstream-repository = "https://github.com/protocolbuffers/protobuf" +extra-description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 35.1 on [protobuf v35.1](https://github.com/protocolbuffers/protobuf/releases/tag/v35.1) (python `protobuf==7.35.1`)." +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/protobuf/google/_upb/_message.pyi b/stubs/protobuf/google/_upb/_message.pyi new file mode 100644 index 000000000000..454b93febff5 --- /dev/null +++ b/stubs/protobuf/google/_upb/_message.pyi @@ -0,0 +1,334 @@ +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, ClassVar, final +from typing_extensions import Self, disjoint_base + +from google.protobuf.descriptor_pb2 import ( + DescriptorProto, + EnumDescriptorProto, + EnumOptions, + EnumValueOptions, + FeatureSetDefaults, + FieldOptions, + FileDescriptorProto, + FileOptions, + MessageOptions, + MethodDescriptorProto, + MethodOptions, + OneofOptions, + ServiceDescriptorProto, + ServiceOptions, +) + +default_pool: DescriptorPool + +@final +class Arena: ... + +@final +class Descriptor: + containing_type: Descriptor | None + enum_types: Sequence[EnumDescriptor] + enum_types_by_name: Mapping[str, EnumDescriptor] + enum_values_by_name: dict[str, EnumValueDescriptor] + extension_ranges: list[tuple[int, int]] + extensions: Sequence[FieldDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + fields: Sequence[FieldDescriptor] + fields_by_camelcase_name: Mapping[str, FieldDescriptor] + fields_by_name: Mapping[str, FieldDescriptor] + fields_by_number: Mapping[int, FieldDescriptor] + file: FileDescriptor + full_name: str + has_options: bool + is_extendable: bool + name: str + nested_types: Sequence[Descriptor] + nested_types_by_name: Mapping[str, Descriptor] + oneofs: Sequence[OneofDescriptor] + oneofs_by_name: Mapping[str, OneofDescriptor] + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: DescriptorProto, /) -> None: ... + def EnumValueName(self, enum: str, value: int) -> str: ... + def GetOptions(self) -> MessageOptions: ... + +@final +class DescriptorPool: + def __new__(cls, *args, **kwargs) -> Self: ... + def Add(self, file_desc_proto: FileDescriptorProto, /) -> None: ... + def AddSerializedFile(self, serialized_file_desc_proto: bytes, /) -> FileDescriptor: ... + def FindAllExtensions(self, message_descriptor: Descriptor, /) -> list[FieldDescriptor]: ... + def FindEnumTypeByName(self, full_name: str, /) -> EnumDescriptor: ... + def FindExtensionByName(self, full_name: str, /) -> FieldDescriptor: ... + def FindExtensionByNumber(self, message_descriptor: Descriptor, number: int, /) -> FieldDescriptor: ... + def FindFieldByName(self, full_name: str, /) -> FieldDescriptor: ... + def FindFileByName(self, file_name: str, /) -> FileDescriptor: ... + def FindFileContainingSymbol(self, symbol: str, /) -> FileDescriptor: ... + def FindMessageTypeByName(self, full_name: str, /) -> Descriptor: ... + def FindMethodByName(self, full_name: str, /) -> MethodDescriptor: ... + def FindOneofByName(self, full_name: str, /) -> OneofDescriptor: ... + def FindServiceByName(self, full_name: str, /) -> ServiceDescriptor: ... + def SetFeatureSetDefaults(self, defaults: FeatureSetDefaults, /) -> None: ... + +@final +class EnumDescriptor: + containing_type: Descriptor | None + file: FileDescriptor + full_name: str + has_options: bool + is_closed: bool + name: str + values: Sequence[EnumValueDescriptor] + values_by_name: Mapping[str, EnumValueDescriptor] + values_by_number: Mapping[int, EnumValueDescriptor] + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: EnumDescriptorProto, /) -> None: ... + def GetOptions(self) -> EnumOptions: ... + +@final +class EnumValueDescriptor: + has_options: bool + index: int + name: str + number: int + type: EnumDescriptor + def __new__(cls, *args, **kwargs) -> Self: ... + def GetOptions(self) -> EnumValueOptions: ... + +@final +class ExtensionDict: + def __contains__(self, extension_handle: FieldDescriptor, /) -> bool: ... + def __delitem__(self, extension_handle: FieldDescriptor, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __getitem__(self, extension_handle: FieldDescriptor, /) -> Any: ... # Any: Message, scalar, or container + def __gt__(self, other: object, /) -> bool: ... + def __iter__(self) -> ExtensionIterator: ... + def __le__(self, other: object, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __setitem__(self, extension_handle: FieldDescriptor, value: Any, /) -> None: ... # Any: Message, scalar, or container + +@final +class ExtensionIterator: + def __iter__(self) -> Self: ... + def __next__(self) -> FieldDescriptor: ... + +@final +class FieldDescriptor: + CPPTYPE_BOOL: ClassVar[int] = ... + CPPTYPE_BYTES: ClassVar[int] = ... + CPPTYPE_DOUBLE: ClassVar[int] = ... + CPPTYPE_ENUM: ClassVar[int] = ... + CPPTYPE_FLOAT: ClassVar[int] = ... + CPPTYPE_INT32: ClassVar[int] = ... + CPPTYPE_INT64: ClassVar[int] = ... + CPPTYPE_MESSAGE: ClassVar[int] = ... + CPPTYPE_STRING: ClassVar[int] = ... + CPPTYPE_UINT32: ClassVar[int] = ... + CPPTYPE_UINT64: ClassVar[int] = ... + LABEL_OPTIONAL: ClassVar[int] = ... + LABEL_REPEATED: ClassVar[int] = ... + LABEL_REQUIRED: ClassVar[int] = ... + TYPE_BOOL: ClassVar[int] = ... + TYPE_BYTES: ClassVar[int] = ... + TYPE_DOUBLE: ClassVar[int] = ... + TYPE_ENUM: ClassVar[int] = ... + TYPE_FIXED32: ClassVar[int] = ... + TYPE_FIXED64: ClassVar[int] = ... + TYPE_FLOAT: ClassVar[int] = ... + TYPE_GROUP: ClassVar[int] = ... + TYPE_INT32: ClassVar[int] = ... + TYPE_INT64: ClassVar[int] = ... + TYPE_MESSAGE: ClassVar[int] = ... + TYPE_SFIXED32: ClassVar[int] = ... + TYPE_SFIXED64: ClassVar[int] = ... + TYPE_SINT32: ClassVar[int] = ... + TYPE_SINT64: ClassVar[int] = ... + TYPE_STRING: ClassVar[int] = ... + TYPE_UINT32: ClassVar[int] = ... + TYPE_UINT64: ClassVar[int] = ... + camelcase_name: str + containing_oneof: OneofDescriptor | None + containing_type: Descriptor | None + cpp_type: int + default_value: Any # Any: str, int, float, bytes, or bool + enum_type: EnumDescriptor | None + extension_scope: Descriptor | None + file: FileDescriptor + full_name: str + has_default_value: bool + has_options: bool + has_presence: bool + index: int + is_extension: bool + is_packed: bool + is_repeated: bool + is_required: bool + json_name: str + message_type: Descriptor | None + name: str + number: int + type: int + def __new__(cls, *args, **kwargs) -> Self: ... + def GetOptions(self) -> FieldOptions: ... + +@final +class FileDescriptor: + dependencies: Sequence[FileDescriptor] + enum_types_by_name: Mapping[str, EnumDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + has_options: bool + message_types_by_name: Mapping[str, Descriptor] + name: str + package: str + pool: DescriptorPool + public_dependencies: Sequence[FileDescriptor] + serialized_pb: bytes + services_by_name: Mapping[str, ServiceDescriptor] + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: FileDescriptorProto, /) -> None: ... + def GetOptions(self) -> FileOptions: ... + +@final +class MapIterator: + def __iter__(self) -> Self: ... + def __next__(self) -> bool | int | str: ... + +@final +class Message: + Extensions: ExtensionDict + def __init__(self, *args, **kwargs) -> None: ... + def __contains__(self, field_name_or_key: str, /) -> bool: ... + def __deepcopy__(self, memo: Any = None) -> Self: ... + def __delattr__(self, name: str, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __gt__(self, other: object, /) -> bool: ... + def __le__(self, other: object, /) -> bool: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... # Any: str, int, float, bytes, bool, or Message + def MergeFrom(self, other_msg: Message, /) -> None: ... + def CopyFrom(self, other_msg: Message, /) -> None: ... + def Clear(self) -> None: ... + def SetInParent(self) -> None: ... + def IsInitialized(self, errors: list[str] | None = None) -> bool: ... + def MergeFromString(self, serialized: bytes, /) -> int: ... + def ParseFromString(self, serialized: bytes, /) -> int: ... + def SerializeToString(self, *, deterministic: bool = ...) -> bytes: ... + def SerializePartialToString(self, *, deterministic: bool = ...) -> bytes: ... + def ListFields(self) -> list[tuple[FieldDescriptor, Any]]: ... # Any: str, int, float, bytes, bool, or Message + def HasField(self, field_name: str, /) -> bool: ... + def ClearField(self, field_name: str, /) -> None: ... + def WhichOneof(self, oneof_group: str, /) -> str | None: ... + def HasExtension(self, field_descriptor: FieldDescriptor, /) -> bool: ... + def ClearExtension(self, field_descriptor: FieldDescriptor, /) -> None: ... + def UnknownFields(self) -> UnknownFieldSet: ... + def DiscardUnknownFields(self) -> None: ... + def ByteSize(self) -> int: ... + @classmethod + def FromString(cls, s: bytes, /) -> Self: ... + def FindInitializationErrors(self) -> list[str]: ... + +@disjoint_base +class MessageMeta(type): ... + +@final +class MethodDescriptor: + client_streaming: bool + containing_service: ServiceDescriptor + full_name: str + has_options: bool + index: int + input_type: Descriptor + name: str + output_type: Descriptor + server_streaming: bool + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: MethodDescriptorProto, /) -> None: ... + def GetOptions(self) -> MethodOptions: ... + +@final +class OneofDescriptor: + containing_type: Descriptor + fields: Sequence[FieldDescriptor] + full_name: str + has_options: bool + index: int + name: str + def __new__(cls, *args, **kwargs) -> Self: ... + def GetOptions(self) -> OneofOptions: ... + +@final +class RepeatedCompositeContainer: + def __new__(cls, *args, **kwargs) -> Self: ... + def MergeFrom(self, other: RepeatedCompositeContainer | Iterable[Message], /) -> None: ... + def add(self, **kwargs: Any) -> Message: ... # Any: field names and values + def append(self, value: Message, /) -> None: ... + def extend(self, values: Iterable[Message], /) -> None: ... + def insert(self, key: int, value: Message, /) -> None: ... + def pop(self, key: int = -1, /) -> Message: ... + def remove(self, value: Message, /) -> None: ... + def reverse(self) -> None: ... + def sort(self, *, key: Callable[[Any], Any] | None = None, reverse: bool = False) -> None: ... + def clear(self) -> None: ... + def __deepcopy__(self, memo: Any = None) -> RepeatedCompositeContainer: ... + def __delitem__(self, key: int | slice, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __getitem__(self, index: int | slice, /) -> Message: ... + def __gt__(self, other: object, /) -> bool: ... + def __le__(self, other: object, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __setitem__(self, index: int | slice, value: Message, /) -> None: ... + +@final +class RepeatedScalarContainer: + def __new__(cls, *args, **kwargs) -> Self: ... + def MergeFrom(self, other: Any, /) -> None: ... # Any: bool, int, float, str, or bytes + def append(self, value: Any, /) -> None: ... + def extend(self, values: Any, /) -> None: ... + def insert(self, key: int, value: Any, /) -> None: ... + def pop(self, key: int = -1, /) -> Any: ... + def remove(self, value: Any, /) -> None: ... + def reverse(self) -> None: ... + def sort(self, *, key: Callable[[Any], Any] | None = None, reverse: bool = False) -> None: ... + def clear(self) -> None: ... + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: ... # Any: numpy types + def __deepcopy__(self, memo: Any = None) -> RepeatedScalarContainer: ... + def __delitem__(self, key: int | slice, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __getitem__(self, index: int | slice, /) -> Any: ... + def __gt__(self, other: object, /) -> bool: ... + def __le__(self, other: object, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __reduce__(self) -> tuple[Any, ...]: ... + def __setitem__(self, index: int | slice, value: Any, /) -> None: ... + +@final +class ServiceDescriptor: + file: FileDescriptor + full_name: str + has_options: bool + index: int + methods: Sequence[MethodDescriptor] + methods_by_name: Mapping[str, MethodDescriptor] + name: str + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: ServiceDescriptorProto, /) -> None: ... + def FindMethodByName(self, name: str, /) -> MethodDescriptor: ... + def GetOptions(self) -> ServiceOptions: ... + +@final +class UnknownFieldSet: + def __new__(cls, *args, **kwargs) -> Self: ... + def __getitem__(self, index: int, /) -> Any: ... # Any: internal unknown field object + def __len__(self) -> int: ... + +def SetAllowOversizeProtos(allow: bool, /) -> None: ... diff --git a/stubs/protobuf/google/protobuf/__init__.pyi b/stubs/protobuf/google/protobuf/__init__.pyi index aae1f9314354..c5dd95466063 100644 --- a/stubs/protobuf/google/protobuf/__init__.pyi +++ b/stubs/protobuf/google/protobuf/__init__.pyi @@ -1 +1,3 @@ -__version__: bytes +from typing import Final + +__version__: Final[str] diff --git a/stubs/protobuf/google/protobuf/any.pyi b/stubs/protobuf/google/protobuf/any.pyi new file mode 100644 index 000000000000..72be6e49e191 --- /dev/null +++ b/stubs/protobuf/google/protobuf/any.pyi @@ -0,0 +1,13 @@ +from typing import TypeVar + +from google.protobuf.any_pb2 import Any +from google.protobuf.descriptor import Descriptor +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +def pack(msg: Message, type_url_prefix: str | None = "type.googleapis.com/", deterministic: bool | None = None) -> Any: ... +def unpack(any_msg: Any, msg: Message) -> bool: ... +def unpack_as(any_msg: Any, message_type: type[_MessageT]) -> _MessageT: ... +def type_name(any_msg: Any) -> str: ... +def is_type(any_msg: Any, des: Descriptor) -> bool: ... diff --git a/stubs/protobuf/google/protobuf/any_pb2.pyi b/stubs/protobuf/google/protobuf/any_pb2.pyi index 4d800b3048ad..991e4261c80a 100644 --- a/stubs/protobuf/google/protobuf/any_pb2.pyi +++ b/stubs/protobuf/google/protobuf/any_pb2.pyi @@ -1,140 +1,118 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import typing + import google.protobuf.descriptor import google.protobuf.internal.well_known_types import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class Any(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Any): """`Any` contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message. - Protobuf library provides support to pack/unpack Any values in the form - of utility functions or additional generated methods of the Any type. - - Example 1: Pack and unpack a message in C++. - - Foo foo = ...; - Any any; - any.PackFrom(foo); - ... - if (any.UnpackTo(&foo)) { - ... - } - - Example 2: Pack and unpack a message in Java. - - Foo foo = ...; - Any any = Any.pack(foo); - ... - if (any.is(Foo.class)) { - foo = any.unpack(Foo.class); - } - - Example 3: Pack and unpack a message in Python. - - foo = Foo(...) - any = Any() - any.Pack(foo) - ... - if any.Is(Foo.DESCRIPTOR): - any.Unpack(foo) - ... - - Example 4: Pack and unpack a message in Go - - foo := &pb.Foo{...} - any, err := anypb.New(foo) - if err != nil { - ... - } - ... - foo := &pb.Foo{} - if err := any.UnmarshalTo(foo); err != nil { - ... - } - - The pack methods provided by protobuf library will by default use - 'type.googleapis.com/full.type.name' as the type URL and the unpack - methods only use the fully qualified type name after the last '/' - in the type URL, for example "foo.bar.com/x/y.z" will yield type - name "y.z". - - - JSON - ==== - The JSON representation of an `Any` value uses the regular - representation of the deserialized, embedded message, with an - additional field `@type` which contains the type URL. Example: - - package google.profile; - message Person { - string first_name = 1; - string last_name = 2; - } - - { - "@type": "type.googleapis.com/google.profile.Person", - "firstName": , - "lastName": - } - - If the embedded message type is well-known and has a custom JSON - representation, that representation will be embedded adding a field - `value` which holds the custom JSON in addition to the `@type` - field. Example (for message [google.protobuf.Duration][]): - - { - "@type": "type.googleapis.com/google.protobuf.Duration", - "value": "1.212s" - } + In its binary encoding, an `Any` is an ordinary message; but in other wire + forms like JSON, it has a special encoding. The format of the type URL is + described on the `type_url` field. + + Protobuf APIs provide utilities to interact with `Any` values: + + - A 'pack' operation accepts a message and constructs a generic `Any` wrapper + around it. + - An 'unpack' operation reads the content of an `Any` message, either into an + existing message or a new one. Unpack operations must check the type of the + value they unpack against the declared `type_url`. + - An 'is' operation decides whether an `Any` contains a message of the given + type, i.e. whether it can 'unpack' that type. + + The JSON format representation of an `Any` follows one of these cases: + + - For types without special-cased JSON encodings, the JSON format + representation of the `Any` is the same as that of the message, with an + additional `@type` field which contains the type URL. + - For types with special-cased JSON encodings (typically called 'well-known' + types, listed in https://protobuf.dev/programming-guides/json/#any), the + JSON format representation has a key `@type` which contains the type URL + and a key `value` which contains the JSON-serialized value. + + The text format representation of an `Any` is like a message with one field + whose name is the type URL in brackets. For example, an `Any` containing a + `foo.Bar` message may be written `[type.googleapis.com/foo.Bar] { a: 2 }`. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + TYPE_URL_FIELD_NUMBER: builtins.int VALUE_FIELD_NUMBER: builtins.int - type_url: typing.Text = ... - """A URL/resource name that uniquely identifies the type of the serialized - protocol buffer message. This string must contain at least - one "/" character. The last segment of the URL's path must represent - the fully qualified name of the type (as in - `path/google.protobuf.Duration`). The name should be in a canonical form - (e.g., leading "." is not accepted). - - In practice, teams usually precompile into the binary all types that they - expect it to use in the context of Any. However, for URLs which use the - scheme `http`, `https`, or no scheme, one can optionally set up a type - server that maps type URLs to message definitions as follows: - - * If no scheme is provided, `https` is assumed. - * An HTTP GET on the URL must yield a [google.protobuf.Type][] - value in binary format, or produce an error. - * Applications are allowed to cache lookup results based on the - URL, or have them precompiled into a binary to avoid any - lookup. Therefore, binary compatibility needs to be preserved - on changes to types. (Use versioned type names to manage - breaking changes.) - - Note: this functionality is not currently available in the official - protobuf release, and it is not used for type URLs beginning with - type.googleapis.com. - - Schemes other than `http`, `https` (or the empty scheme) might be - used with implementation specific semantics. + type_url: builtins.str + """Identifies the type of the serialized Protobuf message with a URI reference + consisting of a prefix ending in a slash and the fully-qualified type name. + + Example: type.googleapis.com/google.protobuf.StringValue + + This string must contain at least one `/` character, and the content after + the last `/` must be the fully-qualified name of the type in canonical + form, without a leading dot. Do not write a scheme on these URI references + so that clients do not attempt to contact them. + + The prefix is arbitrary and Protobuf implementations are expected to + simply strip off everything up to and including the last `/` to identify + the type. `type.googleapis.com/` is a common default prefix that some + legacy implementations require. This prefix does not indicate the origin of + the type, and URIs containing it are not expected to respond to any + requests. + + All type URL strings must be legal URI references with the additional + restriction (for the text format) that the content of the reference + must consist only of alphanumeric characters, percent-encoded escapes, and + characters in the following set (not including the outer backticks): + `/-.~_!$&()*+,;=`. Despite our allowing percent encodings, implementations + should not unescape them to prevent confusion with existing parsers. For + example, `type.googleapis.com%2FFoo` should be rejected. + + In the original design of `Any`, the possibility of launching a type + resolution service at these type URLs was considered but Protobuf never + implemented one and considers contacting these URLs to be problematic and + a potential security issue. Do not attempt to contact type URLs. """ + value: builtins.bytes + """Holds a Protobuf serialization of the type described by type_url.""" + def __init__(self, *, type_url: builtins.str | None = ..., value: builtins.bytes | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["type_url", b"type_url", "value", b"value"]) -> None: ... - value: builtins.bytes = ... - """Must be a valid serialized protocol buffer of the above specified type.""" - - def __init__(self, - *, - type_url : typing.Text = ..., - value : builtins.bytes = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["type_url",b"type_url","value",b"value"]) -> None: ... global___Any = Any diff --git a/stubs/protobuf/google/protobuf/api_pb2.pyi b/stubs/protobuf/google/protobuf/api_pb2.pyi index c7d3dd04c00d..9c65bc6ac8fc 100644 --- a/stubs/protobuf/google/protobuf/api_pb2.pyi +++ b/stubs/protobuf/google/protobuf/api_pb2.pyi @@ -1,18 +1,50 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import collections.abc +import typing + import google.protobuf.descriptor import google.protobuf.internal.containers import google.protobuf.message import google.protobuf.source_context_pb2 import google.protobuf.type_pb2 -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class Api(google.protobuf.message.Message): """Api is a light-weight descriptor for an API Interface. @@ -23,8 +55,15 @@ class Api(google.protobuf.message.Message): sometimes simply referred to as "APIs" in other contexts, such as the name of this message itself. See https://cloud.google.com/apis/design/glossary for detailed terminology. + + New usages of this message as an alternative to ServiceDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int METHODS_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int @@ -32,20 +71,12 @@ class Api(google.protobuf.message.Message): SOURCE_CONTEXT_FIELD_NUMBER: builtins.int MIXINS_FIELD_NUMBER: builtins.int SYNTAX_FIELD_NUMBER: builtins.int - name: typing.Text = ... + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str """The fully qualified name of this interface, including package name followed by the interface's simple name. """ - - @property - def methods(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Method]: - """The methods of this interface, in unspecified order.""" - pass - @property - def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.type_pb2.Option]: - """Any metadata attached to the interface.""" - pass - version: typing.Text = ... + version: builtins.str """A version string for this interface. If specified, must have the form `major-version.minor-version`, as in `1.10`. If the minor version is omitted, it defaults to zero. If the entire version field is empty, the @@ -66,37 +97,77 @@ class Api(google.protobuf.message.Message): be omitted. Zero major versions must only be used for experimental, non-GA interfaces. """ + syntax: google.protobuf.type_pb2.Syntax.ValueType + """The source syntax of the service.""" + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS.""" + @property + def methods(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Method]: + """The methods of this interface, in unspecified order.""" + + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.type_pb2.Option]: + """Any metadata attached to the interface.""" @property def source_context(self) -> google.protobuf.source_context_pb2.SourceContext: """Source context for the protocol buffer service represented by this message. """ - pass + @property def mixins(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Mixin]: """Included interfaces. See [Mixin][].""" - pass - syntax: google.protobuf.type_pb2.Syntax.V = ... - """The source syntax of the service.""" - def __init__(self, + def __init__( + self, *, - name : typing.Text = ..., - methods : typing.Optional[typing.Iterable[global___Method]] = ..., - options : typing.Optional[typing.Iterable[google.protobuf.type_pb2.Option]] = ..., - version : typing.Text = ..., - source_context : typing.Optional[google.protobuf.source_context_pb2.SourceContext] = ..., - mixins : typing.Optional[typing.Iterable[global___Mixin]] = ..., - syntax : google.protobuf.type_pb2.Syntax.V = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["source_context",b"source_context"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["methods",b"methods","mixins",b"mixins","name",b"name","options",b"options","source_context",b"source_context","syntax",b"syntax","version",b"version"]) -> None: ... + name: builtins.str | None = ..., + methods: collections.abc.Iterable[global___Method] | None = ..., + options: collections.abc.Iterable[google.protobuf.type_pb2.Option] | None = ..., + version: builtins.str | None = ..., + source_context: google.protobuf.source_context_pb2.SourceContext | None = ..., + mixins: collections.abc.Iterable[global___Mixin] | None = ..., + syntax: google.protobuf.type_pb2.Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["source_context", b"source_context"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "methods", + b"methods", + "mixins", + b"mixins", + "name", + b"name", + "options", + b"options", + "source_context", + b"source_context", + "syntax", + b"syntax", + "version", + b"version", + ], + ) -> None: ... + global___Api = Api +@typing.final class Method(google.protobuf.message.Message): - """Method represents a method of an API interface.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + """Method represents a method of an API interface. + + New usages of this message as an alternative to MethodDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int REQUEST_TYPE_URL_FIELD_NUMBER: builtins.int REQUEST_STREAMING_FIELD_NUMBER: builtins.int @@ -104,41 +175,70 @@ class Method(google.protobuf.message.Message): RESPONSE_STREAMING_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int SYNTAX_FIELD_NUMBER: builtins.int - name: typing.Text = ... + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str """The simple name of this method.""" - - request_type_url: typing.Text = ... + request_type_url: builtins.str """A URL of the input message type.""" - - request_streaming: builtins.bool = ... + request_streaming: builtins.bool """If true, the request is streamed.""" - - response_type_url: typing.Text = ... + response_type_url: builtins.str """The URL of the output message type.""" - - response_streaming: builtins.bool = ... + response_streaming: builtins.bool """If true, the response is streamed.""" + syntax: google.protobuf.type_pb2.Syntax.ValueType + """The source syntax of this method. + This field should be ignored, instead the syntax should be inherited from + Api. This is similar to Field and EnumValue. + """ + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS. + + This field should be ignored, instead the edition should be inherited from + Api. This is similar to Field and EnumValue. + """ @property def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.type_pb2.Option]: """Any metadata attached to the method.""" - pass - syntax: google.protobuf.type_pb2.Syntax.V = ... - """The source syntax of this method.""" - def __init__(self, + def __init__( + self, *, - name : typing.Text = ..., - request_type_url : typing.Text = ..., - request_streaming : builtins.bool = ..., - response_type_url : typing.Text = ..., - response_streaming : builtins.bool = ..., - options : typing.Optional[typing.Iterable[google.protobuf.type_pb2.Option]] = ..., - syntax : google.protobuf.type_pb2.Syntax.V = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options","request_streaming",b"request_streaming","request_type_url",b"request_type_url","response_streaming",b"response_streaming","response_type_url",b"response_type_url","syntax",b"syntax"]) -> None: ... + name: builtins.str | None = ..., + request_type_url: builtins.str | None = ..., + request_streaming: builtins.bool | None = ..., + response_type_url: builtins.str | None = ..., + response_streaming: builtins.bool | None = ..., + options: collections.abc.Iterable[google.protobuf.type_pb2.Option] | None = ..., + syntax: google.protobuf.type_pb2.Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "name", + b"name", + "options", + b"options", + "request_streaming", + b"request_streaming", + "request_type_url", + b"request_type_url", + "response_streaming", + b"response_streaming", + "response_type_url", + b"response_type_url", + "syntax", + b"syntax", + ], + ) -> None: ... + global___Method = Method +@typing.final class Mixin(google.protobuf.message.Message): """Declares an API Interface to be included in this interface. The including interface must redeclare all the methods from the included interface, but @@ -219,21 +319,18 @@ class Mixin(google.protobuf.message.Message): ... } """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int ROOT_FIELD_NUMBER: builtins.int - name: typing.Text = ... + name: builtins.str """The fully qualified name of the interface which is included.""" - - root: typing.Text = ... + root: builtins.str """If non-empty specifies a path under which inherited HTTP paths are rooted. """ + def __init__(self, *, name: builtins.str | None = ..., root: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "root", b"root"]) -> None: ... - def __init__(self, - *, - name : typing.Text = ..., - root : typing.Text = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","root",b"root"]) -> None: ... global___Mixin = Mixin diff --git a/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi b/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi index b3e03411506f..a6f744c26074 100644 --- a/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi +++ b/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi @@ -1,67 +1,105 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Author: kenton@google.com (Kenton Varda) + +protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is +just a program that reads a CodeGeneratorRequest from stdin and writes a +CodeGeneratorResponse to stdout. + +Plugins written using C++ can use google/protobuf/compiler/plugin.h instead +of dealing with the raw protocol defined here. + +A plugin executable needs only to be placed somewhere in the path. The +plugin should be named "protoc-gen-$NAME", and will then be used when the +flag "--${NAME}_out" is passed to protoc. """ + import builtins +import collections.abc +import sys +import typing + import google.protobuf.descriptor import google.protobuf.descriptor_pb2 import google.protobuf.internal.containers import google.protobuf.internal.enum_type_wrapper import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class Version(google.protobuf.message.Message): """The version number of protocol compiler.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + MAJOR_FIELD_NUMBER: builtins.int MINOR_FIELD_NUMBER: builtins.int PATCH_FIELD_NUMBER: builtins.int SUFFIX_FIELD_NUMBER: builtins.int - major: builtins.int = ... - minor: builtins.int = ... - patch: builtins.int = ... - suffix: typing.Text = ... + major: builtins.int + minor: builtins.int + patch: builtins.int + suffix: builtins.str """A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should be empty for mainline stable releases. """ - - def __init__(self, + def __init__( + self, *, - major : typing.Optional[builtins.int] = ..., - minor : typing.Optional[builtins.int] = ..., - patch : typing.Optional[builtins.int] = ..., - suffix : typing.Optional[typing.Text] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["major",b"major","minor",b"minor","patch",b"patch","suffix",b"suffix"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["major",b"major","minor",b"minor","patch",b"patch","suffix",b"suffix"]) -> None: ... + major: builtins.int | None = ..., + minor: builtins.int | None = ..., + patch: builtins.int | None = ..., + suffix: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["major", b"major", "minor", b"minor", "patch", b"patch", "suffix", b"suffix"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["major", b"major", "minor", b"minor", "patch", b"patch", "suffix", b"suffix"] + ) -> None: ... + global___Version = Version +@typing.final class CodeGeneratorRequest(google.protobuf.message.Message): """An encoded CodeGeneratorRequest is written to the plugin's stdin.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + FILE_TO_GENERATE_FIELD_NUMBER: builtins.int PARAMETER_FIELD_NUMBER: builtins.int PROTO_FILE_FIELD_NUMBER: builtins.int + SOURCE_FILE_DESCRIPTORS_FIELD_NUMBER: builtins.int COMPILER_VERSION_FIELD_NUMBER: builtins.int + parameter: builtins.str + """The generator parameter passed on the command-line.""" @property - def file_to_generate(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: + def file_to_generate(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """The .proto files that were explicitly listed on the command-line. The code generator should generate code only for these files. Each file's descriptor will be included in proto_file, below. """ - pass - parameter: typing.Text = ... - """The generator parameter passed on the command-line.""" @property - def proto_file(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.descriptor_pb2.FileDescriptorProto]: + def proto_file( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.descriptor_pb2.FileDescriptorProto]: """FileDescriptorProtos for all files in files_to_generate and everything they import. The files will appear in topological order, so each file appears before any file that imports it. + Note: the files listed in files_to_generate will include runtime-retention + options only, but all other files will include source-retention options. + The source_file_descriptors field below is available in case you need + source-retention options for files_to_generate. + protoc guarantees that all proto_files will be written after the fields above, even though this is not technically guaranteed by the protobuf wire format. This theoretically could allow a plugin to stream @@ -73,46 +111,86 @@ class CodeGeneratorRequest(google.protobuf.message.Message): Type names of fields and extensions in the FileDescriptorProto are always fully qualified. """ - pass + + @property + def source_file_descriptors( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.descriptor_pb2.FileDescriptorProto]: + """File descriptors with all options, including source-retention options. + These descriptors are only provided for the files listed in + files_to_generate. + """ + @property def compiler_version(self) -> global___Version: """The version number of protocol compiler.""" - pass - def __init__(self, + + def __init__( + self, *, - file_to_generate : typing.Optional[typing.Iterable[typing.Text]] = ..., - parameter : typing.Optional[typing.Text] = ..., - proto_file : typing.Optional[typing.Iterable[google.protobuf.descriptor_pb2.FileDescriptorProto]] = ..., - compiler_version : typing.Optional[global___Version] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["compiler_version",b"compiler_version","parameter",b"parameter"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["compiler_version",b"compiler_version","file_to_generate",b"file_to_generate","parameter",b"parameter","proto_file",b"proto_file"]) -> None: ... + file_to_generate: collections.abc.Iterable[builtins.str] | None = ..., + parameter: builtins.str | None = ..., + proto_file: collections.abc.Iterable[google.protobuf.descriptor_pb2.FileDescriptorProto] | None = ..., + source_file_descriptors: collections.abc.Iterable[google.protobuf.descriptor_pb2.FileDescriptorProto] | None = ..., + compiler_version: global___Version | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["compiler_version", b"compiler_version", "parameter", b"parameter"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "compiler_version", + b"compiler_version", + "file_to_generate", + b"file_to_generate", + "parameter", + b"parameter", + "proto_file", + b"proto_file", + "source_file_descriptors", + b"source_file_descriptors", + ], + ) -> None: ... + global___CodeGeneratorRequest = CodeGeneratorRequest +@typing.final class CodeGeneratorResponse(google.protobuf.message.Message): """The plugin writes an encoded CodeGeneratorResponse to stdout.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Feature: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _FeatureEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[CodeGeneratorResponse._Feature.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + FEATURE_NONE: CodeGeneratorResponse._Feature.ValueType # 0 + FEATURE_PROTO3_OPTIONAL: CodeGeneratorResponse._Feature.ValueType # 1 + FEATURE_SUPPORTS_EDITIONS: CodeGeneratorResponse._Feature.ValueType # 2 + class Feature(_Feature, metaclass=_FeatureEnumTypeWrapper): """Sync with code_generator.h.""" - pass - class _Feature: - V = typing.NewType('V', builtins.int) - class _FeatureEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Feature.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - FEATURE_NONE = CodeGeneratorResponse.Feature.V(0) - FEATURE_PROTO3_OPTIONAL = CodeGeneratorResponse.Feature.V(1) - FEATURE_NONE = CodeGeneratorResponse.Feature.V(0) - FEATURE_PROTO3_OPTIONAL = CodeGeneratorResponse.Feature.V(1) + FEATURE_NONE: CodeGeneratorResponse.Feature.ValueType # 0 + FEATURE_PROTO3_OPTIONAL: CodeGeneratorResponse.Feature.ValueType # 1 + FEATURE_SUPPORTS_EDITIONS: CodeGeneratorResponse.Feature.ValueType # 2 + @typing.final class File(google.protobuf.message.Message): """Represents a single generated file.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int INSERTION_POINT_FIELD_NUMBER: builtins.int CONTENT_FIELD_NUMBER: builtins.int GENERATED_CODE_INFO_FIELD_NUMBER: builtins.int - name: typing.Text = ... + name: builtins.str """The file name, relative to the output directory. The name must not contain "." or ".." components and must be relative, not be absolute (so, the file cannot lie outside the output directory). "/" must be used as @@ -125,8 +203,7 @@ class CodeGeneratorResponse(google.protobuf.message.Message): this writing protoc does not optimize for this -- it will read the entire CodeGeneratorResponse before writing files to disk. """ - - insertion_point: typing.Text = ... + insertion_point: builtins.str """If non-empty, indicates that the named file should already exist, and the content here is to be inserted into that file at a defined insertion point. This feature allows a code generator to extend the output @@ -165,31 +242,56 @@ class CodeGeneratorResponse(google.protobuf.message.Message): If |insertion_point| is present, |name| must also be present. """ - - content: typing.Text = ... + content: builtins.str """The file contents.""" - @property def generated_code_info(self) -> google.protobuf.descriptor_pb2.GeneratedCodeInfo: """Information describing the file content being inserted. If an insertion point is used, this information will be appropriately offset and inserted into the code generation metadata for the generated files. """ - pass - def __init__(self, + + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - insertion_point : typing.Optional[typing.Text] = ..., - content : typing.Optional[typing.Text] = ..., - generated_code_info : typing.Optional[google.protobuf.descriptor_pb2.GeneratedCodeInfo] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["content",b"content","generated_code_info",b"generated_code_info","insertion_point",b"insertion_point","name",b"name"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["content",b"content","generated_code_info",b"generated_code_info","insertion_point",b"insertion_point","name",b"name"]) -> None: ... + name: builtins.str | None = ..., + insertion_point: builtins.str | None = ..., + content: builtins.str | None = ..., + generated_code_info: google.protobuf.descriptor_pb2.GeneratedCodeInfo | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "content", + b"content", + "generated_code_info", + b"generated_code_info", + "insertion_point", + b"insertion_point", + "name", + b"name", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "content", + b"content", + "generated_code_info", + b"generated_code_info", + "insertion_point", + b"insertion_point", + "name", + b"name", + ], + ) -> None: ... ERROR_FIELD_NUMBER: builtins.int SUPPORTED_FEATURES_FIELD_NUMBER: builtins.int + MINIMUM_EDITION_FIELD_NUMBER: builtins.int + MAXIMUM_EDITION_FIELD_NUMBER: builtins.int FILE_FIELD_NUMBER: builtins.int - error: typing.Text = ... + error: builtins.str """Error message. If non-empty, code generation failed. The plugin process should exit with status code zero even if it reports an error in this way. @@ -199,20 +301,62 @@ class CodeGeneratorResponse(google.protobuf.message.Message): unparseable -- should be reported by writing a message to stderr and exiting with a non-zero status code. """ - - supported_features: builtins.int = ... + supported_features: builtins.int """A bitmask of supported features that the code generator supports. This is a bitwise "or" of values from the Feature enum. """ - + minimum_edition: builtins.int + """The minimum edition this plugin supports. This will be treated as an + Edition enum, but we want to allow unknown values. It should be specified + according the edition enum value, *not* the edition number. Only takes + effect for plugins that have FEATURE_SUPPORTS_EDITIONS set. + """ + maximum_edition: builtins.int + """The maximum edition this plugin supports. This will be treated as an + Edition enum, but we want to allow unknown values. It should be specified + according the edition enum value, *not* the edition number. Only takes + effect for plugins that have FEATURE_SUPPORTS_EDITIONS set. + """ @property - def file(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CodeGeneratorResponse.File]: ... - def __init__(self, + def file( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CodeGeneratorResponse.File]: ... + def __init__( + self, *, - error : typing.Optional[typing.Text] = ..., - supported_features : typing.Optional[builtins.int] = ..., - file : typing.Optional[typing.Iterable[global___CodeGeneratorResponse.File]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["error",b"error","supported_features",b"supported_features"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["error",b"error","file",b"file","supported_features",b"supported_features"]) -> None: ... + error: builtins.str | None = ..., + supported_features: builtins.int | None = ..., + minimum_edition: builtins.int | None = ..., + maximum_edition: builtins.int | None = ..., + file: collections.abc.Iterable[global___CodeGeneratorResponse.File] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "error", + b"error", + "maximum_edition", + b"maximum_edition", + "minimum_edition", + b"minimum_edition", + "supported_features", + b"supported_features", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "error", + b"error", + "file", + b"file", + "maximum_edition", + b"maximum_edition", + "minimum_edition", + b"minimum_edition", + "supported_features", + b"supported_features", + ], + ) -> None: ... + global___CodeGeneratorResponse = CodeGeneratorResponse diff --git a/stubs/protobuf/google/protobuf/descriptor.pyi b/stubs/protobuf/google/protobuf/descriptor.pyi index f79fa775b252..c1fdd5701614 100644 --- a/stubs/protobuf/google/protobuf/descriptor.pyi +++ b/stubs/protobuf/google/protobuf/descriptor.pyi @@ -1,35 +1,43 @@ +from collections.abc import Mapping, Sequence from typing import Any from .descriptor_pb2 import ( + DescriptorProto, + EnumDescriptorProto, EnumOptions, EnumValueOptions, FieldOptions, + FileDescriptorProto, FileOptions, MessageOptions, + MethodDescriptorProto, MethodOptions, OneofOptions, + ServiceDescriptorProto, ServiceOptions, ) +from .descriptor_pool import DescriptorPool from .message import Message class Error(Exception): ... class TypeTransformationError(Error): ... class DescriptorMetaclass(type): - def __instancecheck__(self, obj): ... + def __instancecheck__(cls, obj: object) -> bool: ... _internal_create_key: object +_USE_C_DESCRIPTORS: bool class DescriptorBase(metaclass=DescriptorMetaclass): - has_options: Any - def __init__(self, options, serialized_options, options_class_name) -> None: ... - def GetOptions(self): ... + has_options: bool + def __init__(self, file, options, serialized_options, options_class_name) -> None: ... + def GetOptions(self) -> Any: ... # Any: overridden with specific *Options in subclasses class _NestedDescriptorBase(DescriptorBase): - name: Any - full_name: Any - file: Any - containing_type: Any + name: str + full_name: str + file: FileDescriptor + containing_type: Descriptor | None def __init__( self, options, @@ -38,113 +46,93 @@ class _NestedDescriptorBase(DescriptorBase): full_name, file, containing_type, - serialized_start=..., - serialized_end=..., - serialized_options=..., + serialized_start=None, + serialized_end=None, + serialized_options=None, ) -> None: ... - def GetTopLevelContainingType(self): ... - def CopyToProto(self, proto): ... + def CopyToProto(self, proto: Any) -> None: ... # Any: overridden with specific *Proto in subclasses class Descriptor(_NestedDescriptorBase): - def __new__( - cls, - name, - full_name, - filename, - containing_type, - fields, - nested_types, - enum_types, - extensions, - options=..., - serialized_options=..., - is_extendable=..., - extension_ranges=..., - oneofs=..., - file=..., - serialized_start=..., - serialized_end=..., - syntax=..., - create_key=..., - ): ... - fields: Any - fields_by_number: Any - fields_by_name: Any - nested_types: Any - nested_types_by_name: Any - enum_types: Any - enum_types_by_name: Any - enum_values_by_name: Any - extensions: Any - extensions_by_name: Any - is_extendable: Any - extension_ranges: Any - oneofs: Any - oneofs_by_name: Any - syntax: Any + fields: Sequence[FieldDescriptor] + fields_by_number: Mapping[int, FieldDescriptor] + fields_by_name: Mapping[str, FieldDescriptor] + @property + def fields_by_camelcase_name(self) -> Mapping[str, FieldDescriptor]: ... + nested_types: Sequence[Descriptor] + nested_types_by_name: Mapping[str, Descriptor] + enum_types: Sequence[EnumDescriptor] + enum_types_by_name: Mapping[str, EnumDescriptor] + enum_values_by_name: dict[str, EnumValueDescriptor] + extensions: Sequence[FieldDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + is_extendable: bool + extension_ranges: list[tuple[int, int]] + oneofs: Sequence[OneofDescriptor] + oneofs_by_name: Mapping[str, OneofDescriptor] def __init__( self, - name, - full_name, - filename, - containing_type, - fields, - nested_types, - enum_types, - extensions, - options=..., - serialized_options=..., - is_extendable=..., - extension_ranges=..., - oneofs=..., - file=..., - serialized_start=..., - serialized_end=..., - syntax=..., - create_key=..., - ) -> None: ... - def EnumValueName(self, enum, value): ... - def CopyToProto(self, proto): ... + name: str, + full_name: str, + filename: str | None, + containing_type: Descriptor | None, + fields: list[FieldDescriptor], + nested_types: list[FieldDescriptor], + enum_types: list[EnumDescriptor], + extensions: list[FieldDescriptor], + options: MessageOptions | None = None, + serialized_options: bytes | None = None, + is_extendable: bool | None = True, + extension_ranges: list[tuple[int, int]] | None = None, + oneofs: list[OneofDescriptor] | None = None, + file: FileDescriptor | None = None, + serialized_start: int | None = None, + serialized_end: int | None = None, + syntax: str | None = None, + is_map_entry: bool = False, + create_key: object | None = None, + ): ... + def EnumValueName(self, enum: str, value: int) -> str: ... + def CopyToProto(self, proto: DescriptorProto) -> None: ... def GetOptions(self) -> MessageOptions: ... class FieldDescriptor(DescriptorBase): - TYPE_DOUBLE: Any - TYPE_FLOAT: Any - TYPE_INT64: Any - TYPE_UINT64: Any - TYPE_INT32: Any - TYPE_FIXED64: Any - TYPE_FIXED32: Any - TYPE_BOOL: Any - TYPE_STRING: Any - TYPE_GROUP: Any - TYPE_MESSAGE: Any - TYPE_BYTES: Any - TYPE_UINT32: Any - TYPE_ENUM: Any - TYPE_SFIXED32: Any - TYPE_SFIXED64: Any - TYPE_SINT32: Any - TYPE_SINT64: Any - MAX_TYPE: Any - CPPTYPE_INT32: Any - CPPTYPE_INT64: Any - CPPTYPE_UINT32: Any - CPPTYPE_UINT64: Any - CPPTYPE_DOUBLE: Any - CPPTYPE_FLOAT: Any - CPPTYPE_BOOL: Any - CPPTYPE_ENUM: Any - CPPTYPE_STRING: Any - CPPTYPE_MESSAGE: Any - MAX_CPPTYPE: Any - LABEL_OPTIONAL: Any - LABEL_REQUIRED: Any - LABEL_REPEATED: Any - MAX_LABEL: Any - MAX_FIELD_NUMBER: Any - FIRST_RESERVED_FIELD_NUMBER: Any - LAST_RESERVED_FIELD_NUMBER: Any + TYPE_DOUBLE: int + TYPE_FLOAT: int + TYPE_INT64: int + TYPE_UINT64: int + TYPE_INT32: int + TYPE_FIXED64: int + TYPE_FIXED32: int + TYPE_BOOL: int + TYPE_STRING: int + TYPE_GROUP: int + TYPE_MESSAGE: int + TYPE_BYTES: int + TYPE_UINT32: int + TYPE_ENUM: int + TYPE_SFIXED32: int + TYPE_SFIXED64: int + TYPE_SINT32: int + TYPE_SINT64: int + MAX_TYPE: int + CPPTYPE_INT32: int + CPPTYPE_INT64: int + CPPTYPE_UINT32: int + CPPTYPE_UINT64: int + CPPTYPE_DOUBLE: int + CPPTYPE_FLOAT: int + CPPTYPE_BOOL: int + CPPTYPE_ENUM: int + CPPTYPE_STRING: int + CPPTYPE_MESSAGE: int + MAX_CPPTYPE: int + LABEL_OPTIONAL: int + LABEL_REQUIRED: int + LABEL_REPEATED: int + MAX_LABEL: int + MAX_FIELD_NUMBER: int + FIRST_RESERVED_FIELD_NUMBER: int + LAST_RESERVED_FIELD_NUMBER: int def __new__( cls, name, @@ -160,28 +148,39 @@ class FieldDescriptor(DescriptorBase): containing_type, is_extension, extension_scope, - options=..., - serialized_options=..., - file=..., - has_default_value=..., - containing_oneof=..., - create_key=..., + options=None, + serialized_options=None, + has_default_value=True, + containing_oneof=None, + json_name=None, + file=None, + create_key=None, ): ... - name: Any - full_name: Any - index: Any - number: Any - type: Any - cpp_type: Any - label: Any - has_default_value: Any - default_value: Any - containing_type: Any - message_type: Any - enum_type: Any - is_extension: Any - extension_scope: Any - containing_oneof: Any + name: str + full_name: str + index: int + number: int + type: int + cpp_type: int + @property + def is_required(self) -> bool: ... + @property + def is_repeated(self) -> bool: ... + @property + def camelcase_name(self) -> str: ... + @property + def has_presence(self) -> bool: ... + @property + def is_packed(self) -> bool: ... + has_default_value: bool + default_value: Any # Any: str, int, float, bytes, or bool + containing_type: Descriptor | None + message_type: Descriptor | None + enum_type: EnumDescriptor | None + is_extension: bool + extension_scope: Descriptor | None + containing_oneof: OneofDescriptor | None + json_name: str def __init__( self, name, @@ -197,15 +196,16 @@ class FieldDescriptor(DescriptorBase): containing_type, is_extension, extension_scope, - options=..., - serialized_options=..., - file=..., - has_default_value=..., - containing_oneof=..., - create_key=..., + options=None, + serialized_options=None, + has_default_value=True, + containing_oneof=None, + json_name=None, + file=None, + create_key=None, ) -> None: ... @staticmethod - def ProtoTypeToCppProtoType(proto_type): ... + def ProtoTypeToCppProtoType(proto_type: int) -> int: ... def GetOptions(self) -> FieldOptions: ... class EnumDescriptor(_NestedDescriptorBase): @@ -215,87 +215,76 @@ class EnumDescriptor(_NestedDescriptorBase): full_name, filename, values, - containing_type=..., - options=..., - serialized_options=..., - file=..., - serialized_start=..., - serialized_end=..., - create_key=..., + containing_type=None, + options=None, + serialized_options=None, + file=None, + serialized_start=None, + serialized_end=None, + create_key=None, ): ... - values: Any - values_by_name: Any - values_by_number: Any + values: Sequence[EnumValueDescriptor] + values_by_name: Mapping[str, EnumValueDescriptor] + values_by_number: Mapping[int, EnumValueDescriptor] def __init__( self, name, full_name, filename, values, - containing_type=..., - options=..., - serialized_options=..., - file=..., - serialized_start=..., - serialized_end=..., - create_key=..., + containing_type=None, + options=None, + serialized_options=None, + file=None, + serialized_start=None, + serialized_end=None, + create_key=None, ) -> None: ... - def CopyToProto(self, proto): ... + @property + def is_closed(self) -> bool: ... + def CopyToProto(self, proto: EnumDescriptorProto) -> None: ... def GetOptions(self) -> EnumOptions: ... class EnumValueDescriptor(DescriptorBase): - def __new__(cls, name, index, number, type=..., options=..., serialized_options=..., create_key=...): ... - name: Any - index: Any - number: Any - type: Any - def __init__(self, name, index, number, type=..., options=..., serialized_options=..., create_key=...) -> None: ... + def __new__(cls, name, index, number, type=None, options=None, serialized_options=None, create_key=None): ... + name: str + index: int + number: int + type: EnumDescriptor + def __init__(self, name, index, number, type=None, options=None, serialized_options=None, create_key=None) -> None: ... def GetOptions(self) -> EnumValueOptions: ... -class OneofDescriptor: - def __new__(cls, name, full_name, index, containing_type, fields, options=..., serialized_options=..., create_key=...): ... - name: Any - full_name: Any - index: Any - containing_type: Any - fields: Any +class OneofDescriptor(DescriptorBase): + def __new__(cls, name, full_name, index, containing_type, fields, options=None, serialized_options=None, create_key=None): ... + name: str + full_name: str + index: int + containing_type: Descriptor + fields: Sequence[FieldDescriptor] def __init__( - self, name, full_name, index, containing_type, fields, options=..., serialized_options=..., create_key=... + self, name, full_name, index, containing_type, fields, options=None, serialized_options=None, create_key=None ) -> None: ... def GetOptions(self) -> OneofOptions: ... class ServiceDescriptor(_NestedDescriptorBase): - def __new__( - cls, - name, - full_name, - index, - methods, - options=..., - serialized_options=..., - file=..., - serialized_start=..., - serialized_end=..., - create_key=..., - ): ... - index: Any - methods: Any - methods_by_name: Any + index: int + methods: Sequence[MethodDescriptor] + methods_by_name: Mapping[str, MethodDescriptor] def __init__( self, - name, - full_name, - index, - methods, - options=..., - serialized_options=..., - file=..., - serialized_start=..., - serialized_end=..., - create_key=..., - ) -> None: ... - def FindMethodByName(self, name): ... - def CopyToProto(self, proto): ... + name: str, + full_name: str, + index: int, + methods: list[MethodDescriptor], + options: ServiceOptions | None = None, + serialized_options: bytes | None = None, + file: FileDescriptor | None = None, + serialized_start: int | None = None, + serialized_end: int | None = None, + create_key: object | None = None, + ): ... + def FindMethodByName(self, name: str) -> MethodDescriptor: ... + def CopyToProto(self, proto: ServiceDescriptorProto) -> None: ... def GetOptions(self) -> ServiceOptions: ... class MethodDescriptor(DescriptorBase): @@ -307,16 +296,20 @@ class MethodDescriptor(DescriptorBase): containing_service, input_type, output_type, - options=..., - serialized_options=..., - create_key=..., + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None, ): ... - name: Any - full_name: Any - index: Any - containing_service: Any - input_type: Any - output_type: Any + name: str + full_name: str + index: int + containing_service: ServiceDescriptor + input_type: Descriptor + output_type: Descriptor + client_streaming: bool + server_streaming: bool def __init__( self, name, @@ -325,10 +318,13 @@ class MethodDescriptor(DescriptorBase): containing_service, input_type, output_type, - options=..., - serialized_options=..., - create_key=..., + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None, ) -> None: ... + def CopyToProto(self, proto: MethodDescriptorProto) -> None: ... def GetOptions(self) -> MethodOptions: ... class FileDescriptor(DescriptorBase): @@ -336,42 +332,51 @@ class FileDescriptor(DescriptorBase): cls, name, package, - options=..., - serialized_options=..., - serialized_pb=..., - dependencies=..., - public_dependencies=..., - syntax=..., - pool=..., - create_key=..., + options=None, + serialized_options=None, + serialized_pb=None, + dependencies=None, + public_dependencies=None, + syntax=None, + edition=None, + pool=None, + create_key=None, ): ... _options: Any - pool: Any - message_types_by_name: Any - name: Any - package: Any - syntax: Any - serialized_pb: Any - enum_types_by_name: Any - extensions_by_name: Any - services_by_name: Any - dependencies: Any - public_dependencies: Any + _loaded_options: Any + pool: DescriptorPool + message_types_by_name: Mapping[str, Descriptor] + name: str + package: str + serialized_pb: bytes + enum_types_by_name: Mapping[str, EnumDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + services_by_name: Mapping[str, ServiceDescriptor] + dependencies: Sequence[FileDescriptor] + public_dependencies: Sequence[FileDescriptor] def __init__( self, name, package, - options=..., - serialized_options=..., - serialized_pb=..., - dependencies=..., - public_dependencies=..., - syntax=..., - pool=..., - create_key=..., + options=None, + serialized_options=None, + serialized_pb=None, + dependencies=None, + public_dependencies=None, + syntax=None, + edition=None, + pool=None, + create_key=None, ) -> None: ... - def CopyToProto(self, proto): ... + def CopyToProto(self, proto: FileDescriptorProto) -> None: ... def GetOptions(self) -> FileOptions: ... -def MakeDescriptor(desc_proto, package=..., build_file_if_cpp=..., syntax=...): ... def _ParseOptions(message: Message, string: bytes) -> Message: ... +def MakeDescriptor( + desc_proto: DescriptorProto, + package: str = "", + build_file_if_cpp: bool = True, + syntax: str | None = None, + edition: str | None = None, + file_desc: FileDescriptor | None = None, +) -> Descriptor: ... diff --git a/stubs/protobuf/google/protobuf/descriptor_database.pyi b/stubs/protobuf/google/protobuf/descriptor_database.pyi new file mode 100644 index 000000000000..8f0b1927b502 --- /dev/null +++ b/stubs/protobuf/google/protobuf/descriptor_database.pyi @@ -0,0 +1,16 @@ +from typing import Final + +from google.protobuf.descriptor_pb2 import FileDescriptorProto + +__author__: Final[str] + +class Error(Exception): ... +class DescriptorDatabaseConflictingDefinitionError(Error): ... + +class DescriptorDatabase: + def __init__(self) -> None: ... + def Add(self, file_desc_proto: FileDescriptorProto) -> None: ... + def FindFileByName(self, name: str) -> FileDescriptorProto: ... + def FindFileContainingSymbol(self, symbol: str) -> FileDescriptorProto: ... + def FindFileContainingExtension(self, extendee_name: str, extension_number: int) -> FileDescriptorProto | None: ... + def FindAllExtensionNumbers(self, extendee_name: str) -> list[int]: ... diff --git a/stubs/protobuf/google/protobuf/descriptor_pb2.pyi b/stubs/protobuf/google/protobuf/descriptor_pb2.pyi index 555c151311d4..808972d04292 100644 --- a/stubs/protobuf/google/protobuf/descriptor_pb2.pyi +++ b/stubs/protobuf/google/protobuf/descriptor_pb2.pyi @@ -1,40 +1,167 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Author: kenton@google.com (Kenton Varda) + Based on original Protocol Buffers design by + Sanjay Ghemawat, Jeff Dean, and others. + +The messages in this file describe the definitions found in .proto files. +A valid .proto file can be translated directly to a FileDescriptorProto +without any other information (e.g. without reading its imports). """ + import builtins +import collections.abc +import sys +import typing + import google.protobuf.descriptor import google.protobuf.internal.containers import google.protobuf.internal.enum_type_wrapper import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Edition: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _EditionEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Edition.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + EDITION_UNKNOWN: _Edition.ValueType # 0 + """A placeholder for an unknown edition value.""" + EDITION_LEGACY: _Edition.ValueType # 900 + """A placeholder edition for specifying default behaviors *before* a feature + was first introduced. This is effectively an "infinite past". + """ + EDITION_PROTO2: _Edition.ValueType # 998 + """Legacy syntax "editions". These pre-date editions, but behave much like + distinct editions. These can't be used to specify the edition of proto + files, but feature definitions must supply proto2/proto3 defaults for + backwards compatibility. + """ + EDITION_PROTO3: _Edition.ValueType # 999 + EDITION_2023: _Edition.ValueType # 1000 + """Editions that have been released. The specific values are arbitrary and + should not be depended on, but they will always be time-ordered for easy + comparison. + """ + EDITION_2024: _Edition.ValueType # 1001 + EDITION_2026: _Edition.ValueType # 1002 + EDITION_UNSTABLE: _Edition.ValueType # 9999 + """A placeholder edition for developing and testing unscheduled features.""" + EDITION_1_TEST_ONLY: _Edition.ValueType # 1 + """Placeholder editions for testing feature resolution. These should not be + used or relied on outside of tests. + """ + EDITION_2_TEST_ONLY: _Edition.ValueType # 2 + EDITION_99997_TEST_ONLY: _Edition.ValueType # 99997 + EDITION_99998_TEST_ONLY: _Edition.ValueType # 99998 + EDITION_99999_TEST_ONLY: _Edition.ValueType # 99999 + EDITION_MAX: _Edition.ValueType # 2147483647 + """Placeholder for specifying unbounded edition support. This should only + ever be used by plugins that can expect to never require any changes to + support a new edition. + """ + +class Edition(_Edition, metaclass=_EditionEnumTypeWrapper): + """The full set of known editions.""" +EDITION_UNKNOWN: Edition.ValueType # 0 +"""A placeholder for an unknown edition value.""" +EDITION_LEGACY: Edition.ValueType # 900 +"""A placeholder edition for specifying default behaviors *before* a feature +was first introduced. This is effectively an "infinite past". +""" +EDITION_PROTO2: Edition.ValueType # 998 +"""Legacy syntax "editions". These pre-date editions, but behave much like +distinct editions. These can't be used to specify the edition of proto +files, but feature definitions must supply proto2/proto3 defaults for +backwards compatibility. +""" +EDITION_PROTO3: Edition.ValueType # 999 +EDITION_2023: Edition.ValueType # 1000 +"""Editions that have been released. The specific values are arbitrary and +should not be depended on, but they will always be time-ordered for easy +comparison. +""" +EDITION_2024: Edition.ValueType # 1001 +EDITION_2026: Edition.ValueType # 1002 +EDITION_UNSTABLE: Edition.ValueType # 9999 +"""A placeholder edition for developing and testing unscheduled features.""" +EDITION_1_TEST_ONLY: Edition.ValueType # 1 +"""Placeholder editions for testing feature resolution. These should not be +used or relied on outside of tests. +""" +EDITION_2_TEST_ONLY: Edition.ValueType # 2 +EDITION_99997_TEST_ONLY: Edition.ValueType # 99997 +EDITION_99998_TEST_ONLY: Edition.ValueType # 99998 +EDITION_99999_TEST_ONLY: Edition.ValueType # 99999 +EDITION_MAX: Edition.ValueType # 2147483647 +"""Placeholder for specifying unbounded edition support. This should only +ever be used by plugins that can expect to never require any changes to +support a new edition. +""" +global___Edition = Edition + +class _SymbolVisibility: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _SymbolVisibilityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_SymbolVisibility.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + VISIBILITY_UNSET: _SymbolVisibility.ValueType # 0 + VISIBILITY_LOCAL: _SymbolVisibility.ValueType # 1 + VISIBILITY_EXPORT: _SymbolVisibility.ValueType # 2 + +class SymbolVisibility(_SymbolVisibility, metaclass=_SymbolVisibilityEnumTypeWrapper): + """Describes the 'visibility' of a symbol with respect to the proto import + system. Symbols can only be imported when the visibility rules do not prevent + it (ex: local symbols cannot be imported). Visibility modifiers can only set + on `message` and `enum` as they are the only types available to be referenced + from other files. + """ + +VISIBILITY_UNSET: SymbolVisibility.ValueType # 0 +VISIBILITY_LOCAL: SymbolVisibility.ValueType # 1 +VISIBILITY_EXPORT: SymbolVisibility.ValueType # 2 +global___SymbolVisibility = SymbolVisibility + +@typing.final class FileDescriptorSet(google.protobuf.message.Message): """The protocol compiler can output a FileDescriptorSet containing the .proto files it parses. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + FILE_FIELD_NUMBER: builtins.int @property def file(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FileDescriptorProto]: ... - def __init__(self, - *, - file : typing.Optional[typing.Iterable[global___FileDescriptorProto]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["file",b"file"]) -> None: ... + def __init__(self, *, file: collections.abc.Iterable[global___FileDescriptorProto] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["file", b"file"]) -> None: ... + global___FileDescriptorSet = FileDescriptorSet +@typing.final class FileDescriptorProto(google.protobuf.message.Message): """Describes a complete .proto file.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int PACKAGE_FIELD_NUMBER: builtins.int DEPENDENCY_FIELD_NUMBER: builtins.int PUBLIC_DEPENDENCY_FIELD_NUMBER: builtins.int WEAK_DEPENDENCY_FIELD_NUMBER: builtins.int + OPTION_DEPENDENCY_FIELD_NUMBER: builtins.int MESSAGE_TYPE_FIELD_NUMBER: builtins.int ENUM_TYPE_FIELD_NUMBER: builtins.int SERVICE_FIELD_NUMBER: builtins.int @@ -42,30 +169,50 @@ class FileDescriptorProto(google.protobuf.message.Message): OPTIONS_FIELD_NUMBER: builtins.int SOURCE_CODE_INFO_FIELD_NUMBER: builtins.int SYNTAX_FIELD_NUMBER: builtins.int - name: typing.Text = ... + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str """file name, relative to root of source tree""" - - package: typing.Text = ... + package: builtins.str """e.g. "foo", "foo.bar", etc.""" + syntax: builtins.str + """The syntax of the proto file. + The supported values are "proto2", "proto3", and "editions". + If `edition` is present, this value must be "editions". + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + edition: global___Edition.ValueType + """The edition of the proto file. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ @property - def dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: + def dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """Names of files imported by this file.""" - pass + @property def public_dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: """Indexes of the public imported files in the dependency list above.""" - pass + @property def weak_dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: """Indexes of the weak imported files in the dependency list. For Google-internal migration only. Do not use. """ - pass + + @property + def option_dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Names of files imported by this file purely for the purpose of providing + option extensions. These are excluded from the dependency list above. + """ + @property def message_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto]: """All top-level definitions in this file.""" - pass + @property def enum_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto]: ... @property @@ -81,77 +228,127 @@ class FileDescriptorProto(google.protobuf.message.Message): functionality of the descriptors -- the information is needed only by development tools. """ - pass - syntax: typing.Text = ... - """The syntax of the proto file. - The supported values are "proto2" and "proto3". - """ - def __init__(self, + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - package : typing.Optional[typing.Text] = ..., - dependency : typing.Optional[typing.Iterable[typing.Text]] = ..., - public_dependency : typing.Optional[typing.Iterable[builtins.int]] = ..., - weak_dependency : typing.Optional[typing.Iterable[builtins.int]] = ..., - message_type : typing.Optional[typing.Iterable[global___DescriptorProto]] = ..., - enum_type : typing.Optional[typing.Iterable[global___EnumDescriptorProto]] = ..., - service : typing.Optional[typing.Iterable[global___ServiceDescriptorProto]] = ..., - extension : typing.Optional[typing.Iterable[global___FieldDescriptorProto]] = ..., - options : typing.Optional[global___FileOptions] = ..., - source_code_info : typing.Optional[global___SourceCodeInfo] = ..., - syntax : typing.Optional[typing.Text] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options","package",b"package","source_code_info",b"source_code_info","syntax",b"syntax"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["dependency",b"dependency","enum_type",b"enum_type","extension",b"extension","message_type",b"message_type","name",b"name","options",b"options","package",b"package","public_dependency",b"public_dependency","service",b"service","source_code_info",b"source_code_info","syntax",b"syntax","weak_dependency",b"weak_dependency"]) -> None: ... + name: builtins.str | None = ..., + package: builtins.str | None = ..., + dependency: collections.abc.Iterable[builtins.str] | None = ..., + public_dependency: collections.abc.Iterable[builtins.int] | None = ..., + weak_dependency: collections.abc.Iterable[builtins.int] | None = ..., + option_dependency: collections.abc.Iterable[builtins.str] | None = ..., + message_type: collections.abc.Iterable[global___DescriptorProto] | None = ..., + enum_type: collections.abc.Iterable[global___EnumDescriptorProto] | None = ..., + service: collections.abc.Iterable[global___ServiceDescriptorProto] | None = ..., + extension: collections.abc.Iterable[global___FieldDescriptorProto] | None = ..., + options: global___FileOptions | None = ..., + source_code_info: global___SourceCodeInfo | None = ..., + syntax: builtins.str | None = ..., + edition: global___Edition.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "name", + b"name", + "options", + b"options", + "package", + b"package", + "source_code_info", + b"source_code_info", + "syntax", + b"syntax", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dependency", + b"dependency", + "edition", + b"edition", + "enum_type", + b"enum_type", + "extension", + b"extension", + "message_type", + b"message_type", + "name", + b"name", + "option_dependency", + b"option_dependency", + "options", + b"options", + "package", + b"package", + "public_dependency", + b"public_dependency", + "service", + b"service", + "source_code_info", + b"source_code_info", + "syntax", + b"syntax", + "weak_dependency", + b"weak_dependency", + ], + ) -> None: ... + global___FileDescriptorProto = FileDescriptorProto +@typing.final class DescriptorProto(google.protobuf.message.Message): """Describes a message type.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final class ExtensionRange(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + START_FIELD_NUMBER: builtins.int END_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int - start: builtins.int = ... + start: builtins.int """Inclusive.""" - - end: builtins.int = ... + end: builtins.int """Exclusive.""" - @property def options(self) -> global___ExtensionRangeOptions: ... - def __init__(self, + def __init__( + self, *, - start : typing.Optional[builtins.int] = ..., - end : typing.Optional[builtins.int] = ..., - options : typing.Optional[global___ExtensionRangeOptions] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["end",b"end","options",b"options","start",b"start"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["end",b"end","options",b"options","start",b"start"]) -> None: ... + start: builtins.int | None = ..., + end: builtins.int | None = ..., + options: global___ExtensionRangeOptions | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["end", b"end", "options", b"options", "start", b"start"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end", b"end", "options", b"options", "start", b"start"]) -> None: ... + @typing.final class ReservedRange(google.protobuf.message.Message): """Range of reserved tag numbers. Reserved tag numbers may not be used by fields or extension ranges in the same message. Reserved ranges may not overlap. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + START_FIELD_NUMBER: builtins.int END_FIELD_NUMBER: builtins.int - start: builtins.int = ... + start: builtins.int """Inclusive.""" - - end: builtins.int = ... + end: builtins.int """Exclusive.""" - - def __init__(self, - *, - start : typing.Optional[builtins.int] = ..., - end : typing.Optional[builtins.int] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["end",b"end","start",b"start"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["end",b"end","start",b"start"]) -> None: ... + def __init__(self, *, start: builtins.int | None = ..., end: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> None: ... NAME_FIELD_NUMBER: builtins.int FIELD_FIELD_NUMBER: builtins.int @@ -163,7 +360,10 @@ class DescriptorProto(google.protobuf.message.Message): OPTIONS_FIELD_NUMBER: builtins.int RESERVED_RANGE_FIELD_NUMBER: builtins.int RESERVED_NAME_FIELD_NUMBER: builtins.int - name: typing.Text = ... + VISIBILITY_FIELD_NUMBER: builtins.int + name: builtins.str + visibility: global___SymbolVisibility.ValueType + """Support for `export` and `local` keywords on enums.""" @property def field(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FieldDescriptorProto]: ... @property @@ -173,166 +373,318 @@ class DescriptorProto(google.protobuf.message.Message): @property def enum_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto]: ... @property - def extension_range(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto.ExtensionRange]: ... + def extension_range( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto.ExtensionRange]: ... @property - def oneof_decl(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OneofDescriptorProto]: ... + def oneof_decl( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OneofDescriptorProto]: ... @property def options(self) -> global___MessageOptions: ... @property - def reserved_range(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto.ReservedRange]: ... + def reserved_range( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto.ReservedRange]: ... @property - def reserved_name(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: + def reserved_name(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """Reserved field names, which may not be used by fields in the same message. A given name may only be reserved once. """ - pass - def __init__(self, + + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - field : typing.Optional[typing.Iterable[global___FieldDescriptorProto]] = ..., - extension : typing.Optional[typing.Iterable[global___FieldDescriptorProto]] = ..., - nested_type : typing.Optional[typing.Iterable[global___DescriptorProto]] = ..., - enum_type : typing.Optional[typing.Iterable[global___EnumDescriptorProto]] = ..., - extension_range : typing.Optional[typing.Iterable[global___DescriptorProto.ExtensionRange]] = ..., - oneof_decl : typing.Optional[typing.Iterable[global___OneofDescriptorProto]] = ..., - options : typing.Optional[global___MessageOptions] = ..., - reserved_range : typing.Optional[typing.Iterable[global___DescriptorProto.ReservedRange]] = ..., - reserved_name : typing.Optional[typing.Iterable[typing.Text]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["enum_type",b"enum_type","extension",b"extension","extension_range",b"extension_range","field",b"field","name",b"name","nested_type",b"nested_type","oneof_decl",b"oneof_decl","options",b"options","reserved_name",b"reserved_name","reserved_range",b"reserved_range"]) -> None: ... + name: builtins.str | None = ..., + field: collections.abc.Iterable[global___FieldDescriptorProto] | None = ..., + extension: collections.abc.Iterable[global___FieldDescriptorProto] | None = ..., + nested_type: collections.abc.Iterable[global___DescriptorProto] | None = ..., + enum_type: collections.abc.Iterable[global___EnumDescriptorProto] | None = ..., + extension_range: collections.abc.Iterable[global___DescriptorProto.ExtensionRange] | None = ..., + oneof_decl: collections.abc.Iterable[global___OneofDescriptorProto] | None = ..., + options: global___MessageOptions | None = ..., + reserved_range: collections.abc.Iterable[global___DescriptorProto.ReservedRange] | None = ..., + reserved_name: collections.abc.Iterable[builtins.str] | None = ..., + visibility: global___SymbolVisibility.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["name", b"name", "options", b"options", "visibility", b"visibility"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "enum_type", + b"enum_type", + "extension", + b"extension", + "extension_range", + b"extension_range", + "field", + b"field", + "name", + b"name", + "nested_type", + b"nested_type", + "oneof_decl", + b"oneof_decl", + "options", + b"options", + "reserved_name", + b"reserved_name", + "reserved_range", + b"reserved_range", + "visibility", + b"visibility", + ], + ) -> None: ... + global___DescriptorProto = DescriptorProto +@typing.final class ExtensionRangeOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _VerificationState: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _VerificationStateEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ExtensionRangeOptions._VerificationState.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DECLARATION: ExtensionRangeOptions._VerificationState.ValueType # 0 + """All the extensions of the range must be declared.""" + UNVERIFIED: ExtensionRangeOptions._VerificationState.ValueType # 1 + + class VerificationState(_VerificationState, metaclass=_VerificationStateEnumTypeWrapper): + """The verification state of the extension range.""" + + DECLARATION: ExtensionRangeOptions.VerificationState.ValueType # 0 + """All the extensions of the range must be declared.""" + UNVERIFIED: ExtensionRangeOptions.VerificationState.ValueType # 1 + + @typing.final + class Declaration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NUMBER_FIELD_NUMBER: builtins.int + FULL_NAME_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + RESERVED_FIELD_NUMBER: builtins.int + REPEATED_FIELD_NUMBER: builtins.int + number: builtins.int + """The extension number declared within the extension range.""" + full_name: builtins.str + """The fully-qualified name of the extension field. There must be a leading + dot in front of the full name. + """ + type: builtins.str + """The fully-qualified type name of the extension field. Unlike + Metadata.type, Declaration.type must have a leading dot for messages + and enums. + """ + reserved: builtins.bool + """If true, indicates that the number is reserved in the extension range, + and any extension field with the number will fail to compile. Set this + when a declared extension field is deleted. + """ + repeated: builtins.bool + """If true, indicates that the extension must be defined as repeated. + Otherwise the extension must be defined as optional. + """ + def __init__( + self, + *, + number: builtins.int | None = ..., + full_name: builtins.str | None = ..., + type: builtins.str | None = ..., + reserved: builtins.bool | None = ..., + repeated: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "full_name", b"full_name", "number", b"number", "repeated", b"repeated", "reserved", b"reserved", "type", b"type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "full_name", b"full_name", "number", b"number", "repeated", b"repeated", "reserved", b"reserved", "type", b"type" + ], + ) -> None: ... + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + DECLARATION_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + VERIFICATION_FIELD_NUMBER: builtins.int + verification: global___ExtensionRangeOptions.VerificationState.ValueType + """The verification state of the range. + TODO: flip the default to DECLARATION once all empty ranges + are marked as UNVERIFIED. + """ @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + @property + def declaration( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ExtensionRangeOptions.Declaration]: + """For external users: DO NOT USE. We are in the process of open sourcing + extension declaration and executing internal cleanups before it can be + used externally. + """ + + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition.""" + + def __init__( + self, *, - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["uninterpreted_option",b"uninterpreted_option"]) -> None: ... + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + declaration: collections.abc.Iterable[global___ExtensionRangeOptions.Declaration] | None = ..., + features: global___FeatureSet | None = ..., + verification: global___ExtensionRangeOptions.VerificationState.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["features", b"features", "verification", b"verification"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "declaration", + b"declaration", + "features", + b"features", + "uninterpreted_option", + b"uninterpreted_option", + "verification", + b"verification", + ], + ) -> None: ... + global___ExtensionRangeOptions = ExtensionRangeOptions +@typing.final class FieldDescriptorProto(google.protobuf.message.Message): """Describes a field within a message.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... - class Type(_Type, metaclass=_TypeEnumTypeWrapper): - pass + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + class _Type: - V = typing.NewType('V', builtins.int) - class _TypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Type.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - TYPE_DOUBLE = FieldDescriptorProto.Type.V(1) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldDescriptorProto._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TYPE_DOUBLE: FieldDescriptorProto._Type.ValueType # 1 """0 is reserved for errors. Order is weird for historical reasons. """ - - TYPE_FLOAT = FieldDescriptorProto.Type.V(2) - TYPE_INT64 = FieldDescriptorProto.Type.V(3) + TYPE_FLOAT: FieldDescriptorProto._Type.ValueType # 2 + TYPE_INT64: FieldDescriptorProto._Type.ValueType # 3 """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if negative values are likely. """ - - TYPE_UINT64 = FieldDescriptorProto.Type.V(4) - TYPE_INT32 = FieldDescriptorProto.Type.V(5) + TYPE_UINT64: FieldDescriptorProto._Type.ValueType # 4 + TYPE_INT32: FieldDescriptorProto._Type.ValueType # 5 """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if negative values are likely. """ - - TYPE_FIXED64 = FieldDescriptorProto.Type.V(6) - TYPE_FIXED32 = FieldDescriptorProto.Type.V(7) - TYPE_BOOL = FieldDescriptorProto.Type.V(8) - TYPE_STRING = FieldDescriptorProto.Type.V(9) - TYPE_GROUP = FieldDescriptorProto.Type.V(10) + TYPE_FIXED64: FieldDescriptorProto._Type.ValueType # 6 + TYPE_FIXED32: FieldDescriptorProto._Type.ValueType # 7 + TYPE_BOOL: FieldDescriptorProto._Type.ValueType # 8 + TYPE_STRING: FieldDescriptorProto._Type.ValueType # 9 + TYPE_GROUP: FieldDescriptorProto._Type.ValueType # 10 """Tag-delimited aggregate. - Group type is deprecated and not supported in proto3. However, Proto3 + Group type is deprecated and not supported after google.protobuf. However, Proto3 implementations should still be able to parse the group wire format and - treat group fields as unknown fields. + treat group fields as unknown fields. In Editions, the group wire format + can be enabled via the `message_encoding` feature. """ - - TYPE_MESSAGE = FieldDescriptorProto.Type.V(11) + TYPE_MESSAGE: FieldDescriptorProto._Type.ValueType # 11 """Length-delimited aggregate.""" - - TYPE_BYTES = FieldDescriptorProto.Type.V(12) + TYPE_BYTES: FieldDescriptorProto._Type.ValueType # 12 """New in version 2.""" - - TYPE_UINT32 = FieldDescriptorProto.Type.V(13) - TYPE_ENUM = FieldDescriptorProto.Type.V(14) - TYPE_SFIXED32 = FieldDescriptorProto.Type.V(15) - TYPE_SFIXED64 = FieldDescriptorProto.Type.V(16) - TYPE_SINT32 = FieldDescriptorProto.Type.V(17) + TYPE_UINT32: FieldDescriptorProto._Type.ValueType # 13 + TYPE_ENUM: FieldDescriptorProto._Type.ValueType # 14 + TYPE_SFIXED32: FieldDescriptorProto._Type.ValueType # 15 + TYPE_SFIXED64: FieldDescriptorProto._Type.ValueType # 16 + TYPE_SINT32: FieldDescriptorProto._Type.ValueType # 17 """Uses ZigZag encoding.""" - - TYPE_SINT64 = FieldDescriptorProto.Type.V(18) + TYPE_SINT64: FieldDescriptorProto._Type.ValueType # 18 """Uses ZigZag encoding.""" - - TYPE_DOUBLE = FieldDescriptorProto.Type.V(1) + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + TYPE_DOUBLE: FieldDescriptorProto.Type.ValueType # 1 """0 is reserved for errors. Order is weird for historical reasons. """ - - TYPE_FLOAT = FieldDescriptorProto.Type.V(2) - TYPE_INT64 = FieldDescriptorProto.Type.V(3) + TYPE_FLOAT: FieldDescriptorProto.Type.ValueType # 2 + TYPE_INT64: FieldDescriptorProto.Type.ValueType # 3 """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if negative values are likely. """ - - TYPE_UINT64 = FieldDescriptorProto.Type.V(4) - TYPE_INT32 = FieldDescriptorProto.Type.V(5) + TYPE_UINT64: FieldDescriptorProto.Type.ValueType # 4 + TYPE_INT32: FieldDescriptorProto.Type.ValueType # 5 """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if negative values are likely. """ - - TYPE_FIXED64 = FieldDescriptorProto.Type.V(6) - TYPE_FIXED32 = FieldDescriptorProto.Type.V(7) - TYPE_BOOL = FieldDescriptorProto.Type.V(8) - TYPE_STRING = FieldDescriptorProto.Type.V(9) - TYPE_GROUP = FieldDescriptorProto.Type.V(10) + TYPE_FIXED64: FieldDescriptorProto.Type.ValueType # 6 + TYPE_FIXED32: FieldDescriptorProto.Type.ValueType # 7 + TYPE_BOOL: FieldDescriptorProto.Type.ValueType # 8 + TYPE_STRING: FieldDescriptorProto.Type.ValueType # 9 + TYPE_GROUP: FieldDescriptorProto.Type.ValueType # 10 """Tag-delimited aggregate. - Group type is deprecated and not supported in proto3. However, Proto3 + Group type is deprecated and not supported after google.protobuf. However, Proto3 implementations should still be able to parse the group wire format and - treat group fields as unknown fields. + treat group fields as unknown fields. In Editions, the group wire format + can be enabled via the `message_encoding` feature. """ - - TYPE_MESSAGE = FieldDescriptorProto.Type.V(11) + TYPE_MESSAGE: FieldDescriptorProto.Type.ValueType # 11 """Length-delimited aggregate.""" - - TYPE_BYTES = FieldDescriptorProto.Type.V(12) + TYPE_BYTES: FieldDescriptorProto.Type.ValueType # 12 """New in version 2.""" - - TYPE_UINT32 = FieldDescriptorProto.Type.V(13) - TYPE_ENUM = FieldDescriptorProto.Type.V(14) - TYPE_SFIXED32 = FieldDescriptorProto.Type.V(15) - TYPE_SFIXED64 = FieldDescriptorProto.Type.V(16) - TYPE_SINT32 = FieldDescriptorProto.Type.V(17) + TYPE_UINT32: FieldDescriptorProto.Type.ValueType # 13 + TYPE_ENUM: FieldDescriptorProto.Type.ValueType # 14 + TYPE_SFIXED32: FieldDescriptorProto.Type.ValueType # 15 + TYPE_SFIXED64: FieldDescriptorProto.Type.ValueType # 16 + TYPE_SINT32: FieldDescriptorProto.Type.ValueType # 17 """Uses ZigZag encoding.""" - - TYPE_SINT64 = FieldDescriptorProto.Type.V(18) + TYPE_SINT64: FieldDescriptorProto.Type.ValueType # 18 """Uses ZigZag encoding.""" - - class Label(_Label, metaclass=_LabelEnumTypeWrapper): - pass class _Label: - V = typing.NewType('V', builtins.int) - class _LabelEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Label.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - LABEL_OPTIONAL = FieldDescriptorProto.Label.V(1) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _LabelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldDescriptorProto._Label.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + LABEL_OPTIONAL: FieldDescriptorProto._Label.ValueType # 1 """0 is reserved for errors""" + LABEL_REPEATED: FieldDescriptorProto._Label.ValueType # 3 + LABEL_REQUIRED: FieldDescriptorProto._Label.ValueType # 2 + """The required label is only allowed in google.protobuf. In proto3 and Editions + it's explicitly prohibited. In Editions, the `field_presence` feature + can be used to get this behavior. + """ - LABEL_REQUIRED = FieldDescriptorProto.Label.V(2) - LABEL_REPEATED = FieldDescriptorProto.Label.V(3) - - LABEL_OPTIONAL = FieldDescriptorProto.Label.V(1) + class Label(_Label, metaclass=_LabelEnumTypeWrapper): ... + LABEL_OPTIONAL: FieldDescriptorProto.Label.ValueType # 1 """0 is reserved for errors""" - - LABEL_REQUIRED = FieldDescriptorProto.Label.V(2) - LABEL_REPEATED = FieldDescriptorProto.Label.V(3) + LABEL_REPEATED: FieldDescriptorProto.Label.ValueType # 3 + LABEL_REQUIRED: FieldDescriptorProto.Label.ValueType # 2 + """The required label is only allowed in google.protobuf. In proto3 and Editions + it's explicitly prohibited. In Editions, the `field_presence` feature + can be used to get this behavior. + """ NAME_FIELD_NUMBER: builtins.int NUMBER_FIELD_NUMBER: builtins.int @@ -345,59 +697,50 @@ class FieldDescriptorProto(google.protobuf.message.Message): JSON_NAME_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int PROTO3_OPTIONAL_FIELD_NUMBER: builtins.int - name: typing.Text = ... - number: builtins.int = ... - label: global___FieldDescriptorProto.Label.V = ... - type: global___FieldDescriptorProto.Type.V = ... + name: builtins.str + number: builtins.int + label: global___FieldDescriptorProto.Label.ValueType + type: global___FieldDescriptorProto.Type.ValueType """If type_name is set, this need not be set. If both this and type_name are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. """ - - type_name: typing.Text = ... + type_name: builtins.str """For message and enum types, this is the name of the type. If the name starts with a '.', it is fully-qualified. Otherwise, C++-like scoping rules are used to find the type (i.e. first the nested types within this message are searched, then within the parent, on up to the root namespace). """ - - extendee: typing.Text = ... + extendee: builtins.str """For extensions, this is the name of the type being extended. It is resolved in the same manner as type_name. """ - - default_value: typing.Text = ... + default_value: builtins.str """For numeric types, contains the original text representation of the value. For booleans, "true" or "false". For strings, contains the default text contents (not escaped in any way). For bytes, contains the C escaped value. All bytes >= 128 are escaped. - TODO(kenton): Base-64 encode? """ - - oneof_index: builtins.int = ... + oneof_index: builtins.int """If set, gives the index of a oneof in the containing type's oneof_decl list. This field is a member of that oneof. """ - - json_name: typing.Text = ... + json_name: builtins.str """JSON name of this field. The value is set by protocol compiler. If the user has set a "json_name" option on this field, that option's value will be used. Otherwise, it's deduced from the field's name by converting it to camelCase. """ - - @property - def options(self) -> global___FieldOptions: ... - proto3_optional: builtins.bool = ... + proto3_optional: builtins.bool """If true, this is a proto3 "optional". When a proto3 field is optional, it tracks presence regardless of field type. - When proto3_optional is true, this field must be belong to a oneof to - signal to old proto3 clients that presence is tracked for this field. This - oneof is known as a "synthetic" oneof, and this field must be its sole - member (each proto3 optional field gets its own synthetic oneof). Synthetic - oneofs exist in the descriptor only, and do not generate any API. Synthetic - oneofs must be ordered after all "real" oneofs. + When proto3_optional is true, this field must belong to a oneof to signal + to old proto3 clients that presence is tracked for this field. This oneof + is known as a "synthetic" oneof, and this field must be its sole member + (each proto3 optional field gets its own synthetic oneof). Synthetic oneofs + exist in the descriptor only, and do not generate any API. Synthetic oneofs + must be ordered after all "real" oneofs. For message fields, proto3_optional doesn't create any semantic change, since non-repeated message fields always track presence. However it still @@ -411,45 +754,104 @@ class FieldDescriptorProto(google.protobuf.message.Message): Proto2 optional fields do not set this flag, because they already indicate optional with `LABEL_OPTIONAL`. """ - - def __init__(self, + @property + def options(self) -> global___FieldOptions: ... + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - number : typing.Optional[builtins.int] = ..., - label : typing.Optional[global___FieldDescriptorProto.Label.V] = ..., - type : typing.Optional[global___FieldDescriptorProto.Type.V] = ..., - type_name : typing.Optional[typing.Text] = ..., - extendee : typing.Optional[typing.Text] = ..., - default_value : typing.Optional[typing.Text] = ..., - oneof_index : typing.Optional[builtins.int] = ..., - json_name : typing.Optional[typing.Text] = ..., - options : typing.Optional[global___FieldOptions] = ..., - proto3_optional : typing.Optional[builtins.bool] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["default_value",b"default_value","extendee",b"extendee","json_name",b"json_name","label",b"label","name",b"name","number",b"number","oneof_index",b"oneof_index","options",b"options","proto3_optional",b"proto3_optional","type",b"type","type_name",b"type_name"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["default_value",b"default_value","extendee",b"extendee","json_name",b"json_name","label",b"label","name",b"name","number",b"number","oneof_index",b"oneof_index","options",b"options","proto3_optional",b"proto3_optional","type",b"type","type_name",b"type_name"]) -> None: ... + name: builtins.str | None = ..., + number: builtins.int | None = ..., + label: global___FieldDescriptorProto.Label.ValueType | None = ..., + type: global___FieldDescriptorProto.Type.ValueType | None = ..., + type_name: builtins.str | None = ..., + extendee: builtins.str | None = ..., + default_value: builtins.str | None = ..., + oneof_index: builtins.int | None = ..., + json_name: builtins.str | None = ..., + options: global___FieldOptions | None = ..., + proto3_optional: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "default_value", + b"default_value", + "extendee", + b"extendee", + "json_name", + b"json_name", + "label", + b"label", + "name", + b"name", + "number", + b"number", + "oneof_index", + b"oneof_index", + "options", + b"options", + "proto3_optional", + b"proto3_optional", + "type", + b"type", + "type_name", + b"type_name", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_value", + b"default_value", + "extendee", + b"extendee", + "json_name", + b"json_name", + "label", + b"label", + "name", + b"name", + "number", + b"number", + "oneof_index", + b"oneof_index", + "options", + b"options", + "proto3_optional", + b"proto3_optional", + "type", + b"type", + "type_name", + b"type_name", + ], + ) -> None: ... + global___FieldDescriptorProto = FieldDescriptorProto +@typing.final class OneofDescriptorProto(google.protobuf.message.Message): """Describes a oneof.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int - name: typing.Text = ... + name: builtins.str @property def options(self) -> global___OneofOptions: ... - def __init__(self, - *, - name : typing.Optional[typing.Text] = ..., - options : typing.Optional[global___OneofOptions] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options"]) -> None: ... + def __init__(self, *, name: builtins.str | None = ..., options: global___OneofOptions | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["name", b"name", "options", b"options"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "options", b"options"]) -> None: ... + global___OneofDescriptorProto = OneofDescriptorProto +@typing.final class EnumDescriptorProto(google.protobuf.message.Message): """Describes an enum type.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final class EnumReservedRange(google.protobuf.message.Message): """Range of reserved numeric values. Reserved values may not be used by entries in the same enum. Reserved ranges may not overlap. @@ -458,141 +860,207 @@ class EnumDescriptorProto(google.protobuf.message.Message): is inclusive such that it can appropriately represent the entire int32 domain. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + START_FIELD_NUMBER: builtins.int END_FIELD_NUMBER: builtins.int - start: builtins.int = ... + start: builtins.int """Inclusive.""" - - end: builtins.int = ... + end: builtins.int """Inclusive.""" - - def __init__(self, - *, - start : typing.Optional[builtins.int] = ..., - end : typing.Optional[builtins.int] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["end",b"end","start",b"start"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["end",b"end","start",b"start"]) -> None: ... + def __init__(self, *, start: builtins.int | None = ..., end: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> None: ... NAME_FIELD_NUMBER: builtins.int VALUE_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int RESERVED_RANGE_FIELD_NUMBER: builtins.int RESERVED_NAME_FIELD_NUMBER: builtins.int - name: typing.Text = ... + VISIBILITY_FIELD_NUMBER: builtins.int + name: builtins.str + visibility: global___SymbolVisibility.ValueType + """Support for `export` and `local` keywords on enums.""" @property def value(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumValueDescriptorProto]: ... @property def options(self) -> global___EnumOptions: ... @property - def reserved_range(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto.EnumReservedRange]: + def reserved_range( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto.EnumReservedRange]: """Range of reserved numeric values. Reserved numeric values may not be used by enum values in the same enum declaration. Reserved ranges may not overlap. """ - pass + @property - def reserved_name(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: + def reserved_name(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """Reserved enum value names, which may not be reused. A given name may only be reserved once. """ - pass - def __init__(self, + + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - value : typing.Optional[typing.Iterable[global___EnumValueDescriptorProto]] = ..., - options : typing.Optional[global___EnumOptions] = ..., - reserved_range : typing.Optional[typing.Iterable[global___EnumDescriptorProto.EnumReservedRange]] = ..., - reserved_name : typing.Optional[typing.Iterable[typing.Text]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options","reserved_name",b"reserved_name","reserved_range",b"reserved_range","value",b"value"]) -> None: ... + name: builtins.str | None = ..., + value: collections.abc.Iterable[global___EnumValueDescriptorProto] | None = ..., + options: global___EnumOptions | None = ..., + reserved_range: collections.abc.Iterable[global___EnumDescriptorProto.EnumReservedRange] | None = ..., + reserved_name: collections.abc.Iterable[builtins.str] | None = ..., + visibility: global___SymbolVisibility.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["name", b"name", "options", b"options", "visibility", b"visibility"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "name", + b"name", + "options", + b"options", + "reserved_name", + b"reserved_name", + "reserved_range", + b"reserved_range", + "value", + b"value", + "visibility", + b"visibility", + ], + ) -> None: ... + global___EnumDescriptorProto = EnumDescriptorProto +@typing.final class EnumValueDescriptorProto(google.protobuf.message.Message): """Describes a value within an enum.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int NUMBER_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int - name: typing.Text = ... - number: builtins.int = ... + name: builtins.str + number: builtins.int @property def options(self) -> global___EnumValueOptions: ... - def __init__(self, + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - number : typing.Optional[builtins.int] = ..., - options : typing.Optional[global___EnumValueOptions] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["name",b"name","number",b"number","options",b"options"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","number",b"number","options",b"options"]) -> None: ... + name: builtins.str | None = ..., + number: builtins.int | None = ..., + options: global___EnumValueOptions | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["name", b"name", "number", b"number", "options", b"options"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "number", b"number", "options", b"options"]) -> None: ... + global___EnumValueDescriptorProto = EnumValueDescriptorProto +@typing.final class ServiceDescriptorProto(google.protobuf.message.Message): """Describes a service.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int METHOD_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int - name: typing.Text = ... + name: builtins.str @property def method(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___MethodDescriptorProto]: ... @property def options(self) -> global___ServiceOptions: ... - def __init__(self, + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - method : typing.Optional[typing.Iterable[global___MethodDescriptorProto]] = ..., - options : typing.Optional[global___ServiceOptions] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["name",b"name","options",b"options"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["method",b"method","name",b"name","options",b"options"]) -> None: ... + name: builtins.str | None = ..., + method: collections.abc.Iterable[global___MethodDescriptorProto] | None = ..., + options: global___ServiceOptions | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["name", b"name", "options", b"options"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["method", b"method", "name", b"name", "options", b"options"]) -> None: ... + global___ServiceDescriptorProto = ServiceDescriptorProto +@typing.final class MethodDescriptorProto(google.protobuf.message.Message): """Describes a method of a service.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int INPUT_TYPE_FIELD_NUMBER: builtins.int OUTPUT_TYPE_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int CLIENT_STREAMING_FIELD_NUMBER: builtins.int SERVER_STREAMING_FIELD_NUMBER: builtins.int - name: typing.Text = ... - input_type: typing.Text = ... + name: builtins.str + input_type: builtins.str """Input and output type names. These are resolved in the same way as FieldDescriptorProto.type_name, but must refer to a message type. """ - - output_type: typing.Text = ... - @property - def options(self) -> global___MethodOptions: ... - client_streaming: builtins.bool = ... + output_type: builtins.str + client_streaming: builtins.bool """Identifies if client streams multiple client messages""" - - server_streaming: builtins.bool = ... + server_streaming: builtins.bool """Identifies if server streams multiple server messages""" - - def __init__(self, + @property + def options(self) -> global___MethodOptions: ... + def __init__( + self, *, - name : typing.Optional[typing.Text] = ..., - input_type : typing.Optional[typing.Text] = ..., - output_type : typing.Optional[typing.Text] = ..., - options : typing.Optional[global___MethodOptions] = ..., - client_streaming : typing.Optional[builtins.bool] = ..., - server_streaming : typing.Optional[builtins.bool] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["client_streaming",b"client_streaming","input_type",b"input_type","name",b"name","options",b"options","output_type",b"output_type","server_streaming",b"server_streaming"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["client_streaming",b"client_streaming","input_type",b"input_type","name",b"name","options",b"options","output_type",b"output_type","server_streaming",b"server_streaming"]) -> None: ... + name: builtins.str | None = ..., + input_type: builtins.str | None = ..., + output_type: builtins.str | None = ..., + options: global___MethodOptions | None = ..., + client_streaming: builtins.bool | None = ..., + server_streaming: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "client_streaming", + b"client_streaming", + "input_type", + b"input_type", + "name", + b"name", + "options", + b"options", + "output_type", + b"output_type", + "server_streaming", + b"server_streaming", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "client_streaming", + b"client_streaming", + "input_type", + b"input_type", + "name", + b"name", + "options", + b"options", + "output_type", + b"output_type", + "server_streaming", + b"server_streaming", + ], + ) -> None: ... + global___MethodDescriptorProto = MethodDescriptorProto +@typing.final class FileOptions(google.protobuf.message.Message): - """=================================================================== - Options - - Each of the definitions above may have "options" attached. These are + """Each of the definitions above may have "options" attached. These are just annotations which may cause code to be generated slightly differently or may contain hints for code that manipulates protocol messages. @@ -620,40 +1088,39 @@ class FileOptions(google.protobuf.message.Message): https://developers.google.com/protocol-buffers/docs/proto#options If this turns out to be popular, a web service will be set up to automatically assign option numbers. - """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... - class OptimizeMode(_OptimizeMode, metaclass=_OptimizeModeEnumTypeWrapper): - """Generated classes can be optimized for speed or code size.""" - pass + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + class _OptimizeMode: - V = typing.NewType('V', builtins.int) - class _OptimizeModeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_OptimizeMode.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - SPEED = FileOptions.OptimizeMode.V(1) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _OptimizeModeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FileOptions._OptimizeMode.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SPEED: FileOptions._OptimizeMode.ValueType # 1 """Generate complete code for parsing, serialization,""" - - CODE_SIZE = FileOptions.OptimizeMode.V(2) + CODE_SIZE: FileOptions._OptimizeMode.ValueType # 2 """etc. Use ReflectionOps to implement these methods. """ - - LITE_RUNTIME = FileOptions.OptimizeMode.V(3) + LITE_RUNTIME: FileOptions._OptimizeMode.ValueType # 3 """Generate code using MessageLite and the lite runtime.""" + class OptimizeMode(_OptimizeMode, metaclass=_OptimizeModeEnumTypeWrapper): + """Generated classes can be optimized for speed or code size.""" - SPEED = FileOptions.OptimizeMode.V(1) + SPEED: FileOptions.OptimizeMode.ValueType # 1 """Generate complete code for parsing, serialization,""" - - CODE_SIZE = FileOptions.OptimizeMode.V(2) + CODE_SIZE: FileOptions.OptimizeMode.ValueType # 2 """etc. Use ReflectionOps to implement these methods. """ - - LITE_RUNTIME = FileOptions.OptimizeMode.V(3) + LITE_RUNTIME: FileOptions.OptimizeMode.ValueType # 3 """Generate code using MessageLite and the lite runtime.""" - JAVA_PACKAGE_FIELD_NUMBER: builtins.int JAVA_OUTER_CLASSNAME_FIELD_NUMBER: builtins.int JAVA_MULTIPLE_FILES_FIELD_NUMBER: builtins.int @@ -664,7 +1131,6 @@ class FileOptions(google.protobuf.message.Message): CC_GENERIC_SERVICES_FIELD_NUMBER: builtins.int JAVA_GENERIC_SERVICES_FIELD_NUMBER: builtins.int PY_GENERIC_SERVICES_FIELD_NUMBER: builtins.int - PHP_GENERIC_SERVICES_FIELD_NUMBER: builtins.int DEPRECATED_FIELD_NUMBER: builtins.int CC_ENABLE_ARENAS_FIELD_NUMBER: builtins.int OBJC_CLASS_PREFIX_FIELD_NUMBER: builtins.int @@ -674,23 +1140,22 @@ class FileOptions(google.protobuf.message.Message): PHP_NAMESPACE_FIELD_NUMBER: builtins.int PHP_METADATA_NAMESPACE_FIELD_NUMBER: builtins.int RUBY_PACKAGE_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - java_package: typing.Text = ... + java_package: builtins.str """Sets the Java package where classes generated from this .proto will be placed. By default, the proto package is used, but this is often inappropriate because proto packages do not normally start with backwards domain names. """ - - java_outer_classname: typing.Text = ... + java_outer_classname: builtins.str """Controls the name of the wrapper Java class generated for the .proto file. That class will always contain the .proto file's getDescriptor() method as well as any top-level extensions defined in the .proto file. If java_multiple_files is disabled, then all the other classes from the .proto file will be nested inside the single wrapper outer class. """ - - java_multiple_files: builtins.bool = ... + java_multiple_files: builtins.bool """If enabled, then the Java code generator will generate a separate .java file for each top-level message, enum, and service defined in the .proto file. Thus, these types will *not* be nested inside the wrapper class @@ -698,29 +1163,29 @@ class FileOptions(google.protobuf.message.Message): generated to contain the file's getDescriptor() method as well as any top-level extensions defined in the file. """ - - java_generate_equals_and_hash: builtins.bool = ... + java_generate_equals_and_hash: builtins.bool """This option does nothing.""" + java_string_check_utf8: builtins.bool + """A proto2 file can set this to true to opt in to UTF-8 checking for Java, + which will throw an exception if invalid UTF-8 is parsed from the wire or + assigned to a string field. - java_string_check_utf8: builtins.bool = ... - """If set true, then the Java2 code generator will generate code that - throws an exception whenever an attempt is made to assign a non-UTF-8 - byte sequence to a string field. - Message reflection will do the same. - However, an extension field still accepts non-UTF-8 byte sequences. - This option has no effect on when used with the lite runtime. - """ + TODO: clarify exactly what kinds of field types this option + applies to, and update these docs accordingly. - optimize_for: global___FileOptions.OptimizeMode.V = ... - go_package: typing.Text = ... + Proto3 files already perform these checks. Setting the option explicitly to + false has no effect: it cannot be used to opt proto3 files out of UTF-8 + checks. + """ + optimize_for: global___FileOptions.OptimizeMode.ValueType + go_package: builtins.str """Sets the Go package where structs generated from this .proto will be placed. If omitted, the Go package will be derived from the following: - The basename of the package import path, if provided. - Otherwise, the package statement in the .proto file, if present. - Otherwise, the basename of the .proto file, without extension. """ - - cc_generic_services: builtins.bool = ... + cc_generic_services: builtins.bool """Should generic services be generated in each language? "Generic" services are not specific to any particular RPC system. They are generated by the main code generators in each language (without additional plugins). @@ -732,102 +1197,197 @@ class FileOptions(google.protobuf.message.Message): these default to false. Old code which depends on generic services should explicitly set them to true. """ - - java_generic_services: builtins.bool = ... - py_generic_services: builtins.bool = ... - php_generic_services: builtins.bool = ... - deprecated: builtins.bool = ... + java_generic_services: builtins.bool + py_generic_services: builtins.bool + deprecated: builtins.bool """Is this file deprecated? Depending on the target platform, this can emit Deprecated annotations for everything in the file, or it will be completely ignored; in the very least, this is a formalization for deprecating files. """ - - cc_enable_arenas: builtins.bool = ... + cc_enable_arenas: builtins.bool """Enables the use of arenas for the proto messages in this file. This applies only to generated classes for C++. """ - - objc_class_prefix: typing.Text = ... + objc_class_prefix: builtins.str """Sets the objective c class prefix which is prepended to all objective c generated classes from this .proto. There is no default. """ - - csharp_namespace: typing.Text = ... + csharp_namespace: builtins.str """Namespace for generated classes; defaults to the package.""" - - swift_prefix: typing.Text = ... + swift_prefix: builtins.str """By default Swift generators will take the proto package and CamelCase it replacing '.' with underscore and use that to prefix the types/symbols defined. When this options is provided, they will use this value instead to prefix the types/symbols defined. """ - - php_class_prefix: typing.Text = ... + php_class_prefix: builtins.str """Sets the php class prefix which is prepended to all php generated classes from this .proto. Default is empty. """ - - php_namespace: typing.Text = ... + php_namespace: builtins.str """Use this option to change the namespace of php generated classes. Default is empty. When this option is empty, the package name will be used for determining the namespace. """ - - php_metadata_namespace: typing.Text = ... + php_metadata_namespace: builtins.str """Use this option to change the namespace of php generated metadata classes. Default is empty. When this option is empty, the proto file name will be used for determining the namespace. """ - - ruby_package: typing.Text = ... + ruby_package: builtins.str """Use this option to change the package of ruby generated classes. Default is empty. When this option is not set, the package name will be used for determining the ruby package. """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See the documentation for the "Options" section above. """ - pass - def __init__(self, + + def __init__( + self, *, - java_package : typing.Optional[typing.Text] = ..., - java_outer_classname : typing.Optional[typing.Text] = ..., - java_multiple_files : typing.Optional[builtins.bool] = ..., - java_generate_equals_and_hash : typing.Optional[builtins.bool] = ..., - java_string_check_utf8 : typing.Optional[builtins.bool] = ..., - optimize_for : typing.Optional[global___FileOptions.OptimizeMode.V] = ..., - go_package : typing.Optional[typing.Text] = ..., - cc_generic_services : typing.Optional[builtins.bool] = ..., - java_generic_services : typing.Optional[builtins.bool] = ..., - py_generic_services : typing.Optional[builtins.bool] = ..., - php_generic_services : typing.Optional[builtins.bool] = ..., - deprecated : typing.Optional[builtins.bool] = ..., - cc_enable_arenas : typing.Optional[builtins.bool] = ..., - objc_class_prefix : typing.Optional[typing.Text] = ..., - csharp_namespace : typing.Optional[typing.Text] = ..., - swift_prefix : typing.Optional[typing.Text] = ..., - php_class_prefix : typing.Optional[typing.Text] = ..., - php_namespace : typing.Optional[typing.Text] = ..., - php_metadata_namespace : typing.Optional[typing.Text] = ..., - ruby_package : typing.Optional[typing.Text] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["cc_enable_arenas",b"cc_enable_arenas","cc_generic_services",b"cc_generic_services","csharp_namespace",b"csharp_namespace","deprecated",b"deprecated","go_package",b"go_package","java_generate_equals_and_hash",b"java_generate_equals_and_hash","java_generic_services",b"java_generic_services","java_multiple_files",b"java_multiple_files","java_outer_classname",b"java_outer_classname","java_package",b"java_package","java_string_check_utf8",b"java_string_check_utf8","objc_class_prefix",b"objc_class_prefix","optimize_for",b"optimize_for","php_class_prefix",b"php_class_prefix","php_generic_services",b"php_generic_services","php_metadata_namespace",b"php_metadata_namespace","php_namespace",b"php_namespace","py_generic_services",b"py_generic_services","ruby_package",b"ruby_package","swift_prefix",b"swift_prefix"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["cc_enable_arenas",b"cc_enable_arenas","cc_generic_services",b"cc_generic_services","csharp_namespace",b"csharp_namespace","deprecated",b"deprecated","go_package",b"go_package","java_generate_equals_and_hash",b"java_generate_equals_and_hash","java_generic_services",b"java_generic_services","java_multiple_files",b"java_multiple_files","java_outer_classname",b"java_outer_classname","java_package",b"java_package","java_string_check_utf8",b"java_string_check_utf8","objc_class_prefix",b"objc_class_prefix","optimize_for",b"optimize_for","php_class_prefix",b"php_class_prefix","php_generic_services",b"php_generic_services","php_metadata_namespace",b"php_metadata_namespace","php_namespace",b"php_namespace","py_generic_services",b"py_generic_services","ruby_package",b"ruby_package","swift_prefix",b"swift_prefix","uninterpreted_option",b"uninterpreted_option"]) -> None: ... + java_package: builtins.str | None = ..., + java_outer_classname: builtins.str | None = ..., + java_multiple_files: builtins.bool | None = ..., + java_generate_equals_and_hash: builtins.bool | None = ..., + java_string_check_utf8: builtins.bool | None = ..., + optimize_for: global___FileOptions.OptimizeMode.ValueType | None = ..., + go_package: builtins.str | None = ..., + cc_generic_services: builtins.bool | None = ..., + java_generic_services: builtins.bool | None = ..., + py_generic_services: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + cc_enable_arenas: builtins.bool | None = ..., + objc_class_prefix: builtins.str | None = ..., + csharp_namespace: builtins.str | None = ..., + swift_prefix: builtins.str | None = ..., + php_class_prefix: builtins.str | None = ..., + php_namespace: builtins.str | None = ..., + php_metadata_namespace: builtins.str | None = ..., + ruby_package: builtins.str | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cc_enable_arenas", + b"cc_enable_arenas", + "cc_generic_services", + b"cc_generic_services", + "csharp_namespace", + b"csharp_namespace", + "deprecated", + b"deprecated", + "features", + b"features", + "go_package", + b"go_package", + "java_generate_equals_and_hash", + b"java_generate_equals_and_hash", + "java_generic_services", + b"java_generic_services", + "java_multiple_files", + b"java_multiple_files", + "java_outer_classname", + b"java_outer_classname", + "java_package", + b"java_package", + "java_string_check_utf8", + b"java_string_check_utf8", + "objc_class_prefix", + b"objc_class_prefix", + "optimize_for", + b"optimize_for", + "php_class_prefix", + b"php_class_prefix", + "php_metadata_namespace", + b"php_metadata_namespace", + "php_namespace", + b"php_namespace", + "py_generic_services", + b"py_generic_services", + "ruby_package", + b"ruby_package", + "swift_prefix", + b"swift_prefix", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "cc_enable_arenas", + b"cc_enable_arenas", + "cc_generic_services", + b"cc_generic_services", + "csharp_namespace", + b"csharp_namespace", + "deprecated", + b"deprecated", + "features", + b"features", + "go_package", + b"go_package", + "java_generate_equals_and_hash", + b"java_generate_equals_and_hash", + "java_generic_services", + b"java_generic_services", + "java_multiple_files", + b"java_multiple_files", + "java_outer_classname", + b"java_outer_classname", + "java_package", + b"java_package", + "java_string_check_utf8", + b"java_string_check_utf8", + "objc_class_prefix", + b"objc_class_prefix", + "optimize_for", + b"optimize_for", + "php_class_prefix", + b"php_class_prefix", + "php_metadata_namespace", + b"php_metadata_namespace", + "php_namespace", + b"php_namespace", + "py_generic_services", + b"py_generic_services", + "ruby_package", + b"ruby_package", + "swift_prefix", + b"swift_prefix", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + global___FileOptions = FileOptions +@typing.final class MessageOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + MESSAGE_SET_WIRE_FORMAT_FIELD_NUMBER: builtins.int NO_STANDARD_DESCRIPTOR_ACCESSOR_FIELD_NUMBER: builtins.int DEPRECATED_FIELD_NUMBER: builtins.int MAP_ENTRY_FIELD_NUMBER: builtins.int + DEPRECATED_LEGACY_JSON_FIELD_CONFLICTS_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - message_set_wire_format: builtins.bool = ... + message_set_wire_format: builtins.bool """Set true to use the old proto1 MessageSet wire format for extensions. This is provided for backwards-compatibility with the MessageSet wire format. You should not use this for any other reason: It's less @@ -847,21 +1407,18 @@ class MessageOptions(google.protobuf.message.Message): Because this is an option, the above two restrictions are not enforced by the protocol compiler. """ - - no_standard_descriptor_accessor: builtins.bool = ... + no_standard_descriptor_accessor: builtins.bool """Disables the generation of the standard "descriptor()" accessor, which can conflict with a field of the same name. This is meant to make migration from proto1 easier; new code should avoid fields named "descriptor". """ - - deprecated: builtins.bool = ... + deprecated: builtins.bool """Is this message deprecated? Depending on the target platform, this can emit Deprecated annotations for the message, or it will be completely ignored; in the very least, this is a formalization for deprecating messages. """ - - map_entry: builtins.bool = ... + map_entry: builtins.bool """Whether the message is an automatically generated map entry type for the maps field. @@ -884,92 +1441,316 @@ class MessageOptions(google.protobuf.message.Message): instead. The option should only be implicitly set by the proto compiler parser. """ + deprecated_legacy_json_field_conflicts: builtins.bool + """Enable the legacy handling of JSON field name conflicts. This lowercases + and strips underscored from the fields before comparison in proto3 only. + The new behavior takes `json_name` into account and applies to proto2 as + well. + This should only be used as a temporary measure against broken builds due + to the change in behavior for JSON field name conflicts. + + TODO This is legacy behavior we plan to remove once downstream + teams have had time to migrate. + """ @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - message_set_wire_format : typing.Optional[builtins.bool] = ..., - no_standard_descriptor_accessor : typing.Optional[builtins.bool] = ..., - deprecated : typing.Optional[builtins.bool] = ..., - map_entry : typing.Optional[builtins.bool] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated","map_entry",b"map_entry","message_set_wire_format",b"message_set_wire_format","no_standard_descriptor_accessor",b"no_standard_descriptor_accessor"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated","map_entry",b"map_entry","message_set_wire_format",b"message_set_wire_format","no_standard_descriptor_accessor",b"no_standard_descriptor_accessor","uninterpreted_option",b"uninterpreted_option"]) -> None: ... + message_set_wire_format: builtins.bool | None = ..., + no_standard_descriptor_accessor: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + map_entry: builtins.bool | None = ..., + deprecated_legacy_json_field_conflicts: builtins.bool | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + "map_entry", + b"map_entry", + "message_set_wire_format", + b"message_set_wire_format", + "no_standard_descriptor_accessor", + b"no_standard_descriptor_accessor", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + "map_entry", + b"map_entry", + "message_set_wire_format", + b"message_set_wire_format", + "no_standard_descriptor_accessor", + b"no_standard_descriptor_accessor", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + global___MessageOptions = MessageOptions +@typing.final class FieldOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... - class CType(_CType, metaclass=_CTypeEnumTypeWrapper): - pass + DESCRIPTOR: google.protobuf.descriptor.Descriptor + class _CType: - V = typing.NewType('V', builtins.int) - class _CTypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CType.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - STRING = FieldOptions.CType.V(0) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._CType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + STRING: FieldOptions._CType.ValueType # 0 """Default mode.""" + CORD: FieldOptions._CType.ValueType # 1 + """The option [ctype=CORD] may be applied to a non-repeated field of type + "bytes". It indicates that in C++, the data should be stored in a Cord + instead of a string. For very large strings, this may reduce memory + fragmentation. It may also allow better performance when parsing from a + Cord, or when parsing with aliasing enabled, as the parsed Cord may then + alias the original buffer. + """ + STRING_PIECE: FieldOptions._CType.ValueType # 2 - CORD = FieldOptions.CType.V(1) - STRING_PIECE = FieldOptions.CType.V(2) - - STRING = FieldOptions.CType.V(0) + class CType(_CType, metaclass=_CTypeEnumTypeWrapper): ... + STRING: FieldOptions.CType.ValueType # 0 """Default mode.""" + CORD: FieldOptions.CType.ValueType # 1 + """The option [ctype=CORD] may be applied to a non-repeated field of type + "bytes". It indicates that in C++, the data should be stored in a Cord + instead of a string. For very large strings, this may reduce memory + fragmentation. It may also allow better performance when parsing from a + Cord, or when parsing with aliasing enabled, as the parsed Cord may then + alias the original buffer. + """ + STRING_PIECE: FieldOptions.CType.ValueType # 2 - CORD = FieldOptions.CType.V(1) - STRING_PIECE = FieldOptions.CType.V(2) - - class JSType(_JSType, metaclass=_JSTypeEnumTypeWrapper): - pass class _JSType: - V = typing.NewType('V', builtins.int) - class _JSTypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_JSType.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - JS_NORMAL = FieldOptions.JSType.V(0) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _JSTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._JSType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + JS_NORMAL: FieldOptions._JSType.ValueType # 0 """Use the default type.""" - - JS_STRING = FieldOptions.JSType.V(1) + JS_STRING: FieldOptions._JSType.ValueType # 1 """Use JavaScript strings.""" - - JS_NUMBER = FieldOptions.JSType.V(2) + JS_NUMBER: FieldOptions._JSType.ValueType # 2 """Use JavaScript numbers.""" - - JS_NORMAL = FieldOptions.JSType.V(0) + class JSType(_JSType, metaclass=_JSTypeEnumTypeWrapper): ... + JS_NORMAL: FieldOptions.JSType.ValueType # 0 """Use the default type.""" - - JS_STRING = FieldOptions.JSType.V(1) + JS_STRING: FieldOptions.JSType.ValueType # 1 """Use JavaScript strings.""" - - JS_NUMBER = FieldOptions.JSType.V(2) + JS_NUMBER: FieldOptions.JSType.ValueType # 2 """Use JavaScript numbers.""" + class _OptionRetention: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _OptionRetentionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._OptionRetention.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RETENTION_UNKNOWN: FieldOptions._OptionRetention.ValueType # 0 + RETENTION_RUNTIME: FieldOptions._OptionRetention.ValueType # 1 + RETENTION_SOURCE: FieldOptions._OptionRetention.ValueType # 2 + + class OptionRetention(_OptionRetention, metaclass=_OptionRetentionEnumTypeWrapper): + """If set to RETENTION_SOURCE, the option will be omitted from the binary.""" + + RETENTION_UNKNOWN: FieldOptions.OptionRetention.ValueType # 0 + RETENTION_RUNTIME: FieldOptions.OptionRetention.ValueType # 1 + RETENTION_SOURCE: FieldOptions.OptionRetention.ValueType # 2 + + class _OptionTargetType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _OptionTargetTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._OptionTargetType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TARGET_TYPE_UNKNOWN: FieldOptions._OptionTargetType.ValueType # 0 + TARGET_TYPE_FILE: FieldOptions._OptionTargetType.ValueType # 1 + TARGET_TYPE_EXTENSION_RANGE: FieldOptions._OptionTargetType.ValueType # 2 + TARGET_TYPE_MESSAGE: FieldOptions._OptionTargetType.ValueType # 3 + TARGET_TYPE_FIELD: FieldOptions._OptionTargetType.ValueType # 4 + TARGET_TYPE_ONEOF: FieldOptions._OptionTargetType.ValueType # 5 + TARGET_TYPE_ENUM: FieldOptions._OptionTargetType.ValueType # 6 + TARGET_TYPE_ENUM_ENTRY: FieldOptions._OptionTargetType.ValueType # 7 + TARGET_TYPE_SERVICE: FieldOptions._OptionTargetType.ValueType # 8 + TARGET_TYPE_METHOD: FieldOptions._OptionTargetType.ValueType # 9 + + class OptionTargetType(_OptionTargetType, metaclass=_OptionTargetTypeEnumTypeWrapper): + """This indicates the types of entities that the field may apply to when used + as an option. If it is unset, then the field may be freely used as an + option on any kind of entity. + """ + + TARGET_TYPE_UNKNOWN: FieldOptions.OptionTargetType.ValueType # 0 + TARGET_TYPE_FILE: FieldOptions.OptionTargetType.ValueType # 1 + TARGET_TYPE_EXTENSION_RANGE: FieldOptions.OptionTargetType.ValueType # 2 + TARGET_TYPE_MESSAGE: FieldOptions.OptionTargetType.ValueType # 3 + TARGET_TYPE_FIELD: FieldOptions.OptionTargetType.ValueType # 4 + TARGET_TYPE_ONEOF: FieldOptions.OptionTargetType.ValueType # 5 + TARGET_TYPE_ENUM: FieldOptions.OptionTargetType.ValueType # 6 + TARGET_TYPE_ENUM_ENTRY: FieldOptions.OptionTargetType.ValueType # 7 + TARGET_TYPE_SERVICE: FieldOptions.OptionTargetType.ValueType # 8 + TARGET_TYPE_METHOD: FieldOptions.OptionTargetType.ValueType # 9 + + @typing.final + class EditionDefault(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + edition: global___Edition.ValueType + value: builtins.str + """Textproto value.""" + def __init__(self, *, edition: global___Edition.ValueType | None = ..., value: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["edition", b"edition", "value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["edition", b"edition", "value", b"value"]) -> None: ... + + @typing.final + class FeatureSupport(google.protobuf.message.Message): + """Information about the support window of a feature.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_INTRODUCED_FIELD_NUMBER: builtins.int + EDITION_DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATION_WARNING_FIELD_NUMBER: builtins.int + EDITION_REMOVED_FIELD_NUMBER: builtins.int + REMOVAL_ERROR_FIELD_NUMBER: builtins.int + edition_introduced: global___Edition.ValueType + """The edition that this feature was first available in. In editions + earlier than this one, the default assigned to EDITION_LEGACY will be + used, and proto files will not be able to override it. + """ + edition_deprecated: global___Edition.ValueType + """The edition this feature becomes deprecated in. Using this after this + edition may trigger warnings. + """ + deprecation_warning: builtins.str + """The deprecation warning text if this feature is used after the edition it + was marked deprecated in. + """ + edition_removed: global___Edition.ValueType + """The edition this feature is no longer available in. In editions after + this one, the last default assigned will be used, and proto files will + not be able to override it. + """ + removal_error: builtins.str + """The removal error text if this feature is used after the edition it was + removed in. + """ + def __init__( + self, + *, + edition_introduced: global___Edition.ValueType | None = ..., + edition_deprecated: global___Edition.ValueType | None = ..., + deprecation_warning: builtins.str | None = ..., + edition_removed: global___Edition.ValueType | None = ..., + removal_error: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "deprecation_warning", + b"deprecation_warning", + "edition_deprecated", + b"edition_deprecated", + "edition_introduced", + b"edition_introduced", + "edition_removed", + b"edition_removed", + "removal_error", + b"removal_error", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecation_warning", + b"deprecation_warning", + "edition_deprecated", + b"edition_deprecated", + "edition_introduced", + b"edition_introduced", + "edition_removed", + b"edition_removed", + "removal_error", + b"removal_error", + ], + ) -> None: ... CTYPE_FIELD_NUMBER: builtins.int PACKED_FIELD_NUMBER: builtins.int JSTYPE_FIELD_NUMBER: builtins.int LAZY_FIELD_NUMBER: builtins.int + UNVERIFIED_LAZY_FIELD_NUMBER: builtins.int DEPRECATED_FIELD_NUMBER: builtins.int WEAK_FIELD_NUMBER: builtins.int + DEBUG_REDACT_FIELD_NUMBER: builtins.int + RETENTION_FIELD_NUMBER: builtins.int + TARGETS_FIELD_NUMBER: builtins.int + EDITION_DEFAULTS_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + FEATURE_SUPPORT_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - ctype: global___FieldOptions.CType.V = ... - """The ctype option instructs the C++ code generator to use a different + ctype: global___FieldOptions.CType.ValueType + """NOTE: ctype is deprecated. Use `features.(pb.cpp).string_type` instead. + The ctype option instructs the C++ code generator to use a different representation of the field than it normally would. See the specific - options below. This option is not yet implemented in the open source - release -- sorry, we'll try to include it in a future version! + options below. This option is only implemented to support use of + [ctype=CORD] and [ctype=STRING] (the default) on non-repeated fields of + type "bytes" in the open source release. + TODO: make ctype actually deprecated. """ - - packed: builtins.bool = ... + packed: builtins.bool """The packed option can be enabled for repeated primitive fields to enable a more efficient representation on the wire. Rather than repeatedly writing the tag and type for each element, the entire array is encoded as a single length-delimited blob. In proto3, only explicit setting it to - false will avoid using packed encoding. + false will avoid using packed encoding. This option is prohibited in + Editions, but the `repeated_field_encoding` feature can be used to control + the behavior. """ - - jstype: global___FieldOptions.JSType.V = ... + jstype: global___FieldOptions.JSType.ValueType """The jstype option determines the JavaScript type used for values of the field. The option is permitted only for 64 bit integral and fixed types (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING @@ -982,8 +1763,7 @@ class FieldOptions(google.protobuf.message.Message): This option is an enum to permit additional types to be added, e.g. goog.math.Integer. """ - - lazy: builtins.bool = ... + lazy: builtins.bool """Should this field be parsed lazily? Lazy applies only to message-type fields. It means that when the outer message is initially parsed, the inner message's contents will not be parsed but instead stored in encoded @@ -1001,121 +1781,337 @@ class FieldOptions(google.protobuf.message.Message): call from multiple threads concurrently, while non-const methods continue to require exclusive access. - - Note that implementations may choose not to check required fields within - a lazy sub-message. That is, calling IsInitialized() on the outer message - may return true even if the inner message has missing required fields. - This is necessary because otherwise the inner message would have to be - parsed in order to perform the check, defeating the purpose of lazy - parsing. An implementation which chooses not to check required fields - must be consistent about it. That is, for any particular sub-message, the - implementation must either *always* check its required fields, or *never* - check its required fields, regardless of whether or not the message has - been parsed. + Note that lazy message fields are still eagerly verified to check + ill-formed wireformat or missing required fields. Calling IsInitialized() + on the outer message would fail if the inner message has missing required + fields. Failed verification would result in parsing failure (except when + uninitialized messages are acceptable). """ - - deprecated: builtins.bool = ... + unverified_lazy: builtins.bool + """unverified_lazy does no correctness checks on the byte stream. This should + only be used where lazy with verification is prohibitive for performance + reasons. + """ + deprecated: builtins.bool """Is this field deprecated? Depending on the target platform, this can emit Deprecated annotations for accessors, or it will be completely ignored; in the very least, this is a formalization for deprecating fields. """ - - weak: builtins.bool = ... - """For Google-internal migration only. Do not use.""" + weak: builtins.bool + """DEPRECATED. DO NOT USE! + For Google-internal migration only. Do not use. + """ + debug_redact: builtins.bool + """Indicate that the field value should not be printed out when using debug + formats, e.g. when the field contains sensitive credentials. + """ + retention: global___FieldOptions.OptionRetention.ValueType + @property + def targets( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___FieldOptions.OptionTargetType.ValueType]: ... + @property + def edition_defaults( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FieldOptions.EditionDefault]: ... + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def feature_support(self) -> global___FieldOptions.FeatureSupport: ... + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - ctype : typing.Optional[global___FieldOptions.CType.V] = ..., - packed : typing.Optional[builtins.bool] = ..., - jstype : typing.Optional[global___FieldOptions.JSType.V] = ..., - lazy : typing.Optional[builtins.bool] = ..., - deprecated : typing.Optional[builtins.bool] = ..., - weak : typing.Optional[builtins.bool] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["ctype",b"ctype","deprecated",b"deprecated","jstype",b"jstype","lazy",b"lazy","packed",b"packed","weak",b"weak"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["ctype",b"ctype","deprecated",b"deprecated","jstype",b"jstype","lazy",b"lazy","packed",b"packed","uninterpreted_option",b"uninterpreted_option","weak",b"weak"]) -> None: ... + ctype: global___FieldOptions.CType.ValueType | None = ..., + packed: builtins.bool | None = ..., + jstype: global___FieldOptions.JSType.ValueType | None = ..., + lazy: builtins.bool | None = ..., + unverified_lazy: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + weak: builtins.bool | None = ..., + debug_redact: builtins.bool | None = ..., + retention: global___FieldOptions.OptionRetention.ValueType | None = ..., + targets: collections.abc.Iterable[global___FieldOptions.OptionTargetType.ValueType] | None = ..., + edition_defaults: collections.abc.Iterable[global___FieldOptions.EditionDefault] | None = ..., + features: global___FeatureSet | None = ..., + feature_support: global___FieldOptions.FeatureSupport | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ctype", + b"ctype", + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "feature_support", + b"feature_support", + "features", + b"features", + "jstype", + b"jstype", + "lazy", + b"lazy", + "packed", + b"packed", + "retention", + b"retention", + "unverified_lazy", + b"unverified_lazy", + "weak", + b"weak", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ctype", + b"ctype", + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "edition_defaults", + b"edition_defaults", + "feature_support", + b"feature_support", + "features", + b"features", + "jstype", + b"jstype", + "lazy", + b"lazy", + "packed", + b"packed", + "retention", + b"retention", + "targets", + b"targets", + "uninterpreted_option", + b"uninterpreted_option", + "unverified_lazy", + b"unverified_lazy", + "weak", + b"weak", + ], + ) -> None: ... + global___FieldOptions = FieldOptions +@typing.final class OneofOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURES_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["uninterpreted_option",b"uninterpreted_option"]) -> None: ... + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["features", b"features"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["features", b"features", "uninterpreted_option", b"uninterpreted_option"] + ) -> None: ... + global___OneofOptions = OneofOptions +@typing.final class EnumOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + ALLOW_ALIAS_FIELD_NUMBER: builtins.int DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATED_LEGACY_JSON_FIELD_CONFLICTS_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - allow_alias: builtins.bool = ... + allow_alias: builtins.bool """Set this option to true to allow mapping different tag names to the same value. """ - - deprecated: builtins.bool = ... + deprecated: builtins.bool """Is this enum deprecated? Depending on the target platform, this can emit Deprecated annotations for the enum, or it will be completely ignored; in the very least, this is a formalization for deprecating enums. """ + deprecated_legacy_json_field_conflicts: builtins.bool + """Enable the legacy handling of JSON field name conflicts. This lowercases + and strips underscored from the fields before comparison in proto3 only. + The new behavior takes `json_name` into account and applies to proto2 as + well. + TODO Remove this legacy behavior once downstream teams have + had time to migrate. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - allow_alias : typing.Optional[builtins.bool] = ..., - deprecated : typing.Optional[builtins.bool] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["allow_alias",b"allow_alias","deprecated",b"deprecated"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["allow_alias",b"allow_alias","deprecated",b"deprecated","uninterpreted_option",b"uninterpreted_option"]) -> None: ... + allow_alias: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + deprecated_legacy_json_field_conflicts: builtins.bool | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "allow_alias", + b"allow_alias", + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "allow_alias", + b"allow_alias", + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + global___EnumOptions = EnumOptions +@typing.final class EnumValueOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + DEPRECATED_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + DEBUG_REDACT_FIELD_NUMBER: builtins.int + FEATURE_SUPPORT_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - deprecated: builtins.bool = ... + deprecated: builtins.bool """Is this enum value deprecated? Depending on the target platform, this can emit Deprecated annotations for the enum value, or it will be completely ignored; in the very least, this is a formalization for deprecating enum values. """ + debug_redact: builtins.bool + """Indicate that fields annotated with this enum value should not be printed + out when using debug formats, e.g. when the field contains sensitive + credentials. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def feature_support(self) -> global___FieldOptions.FeatureSupport: + """Information about the support window of a feature value.""" @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - deprecated : typing.Optional[builtins.bool] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated","uninterpreted_option",b"uninterpreted_option"]) -> None: ... + deprecated: builtins.bool | None = ..., + features: global___FeatureSet | None = ..., + debug_redact: builtins.bool | None = ..., + feature_support: global___FieldOptions.FeatureSupport | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "feature_support", + b"feature_support", + "features", + b"features", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "feature_support", + b"feature_support", + "features", + b"features", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + global___EnumValueOptions = EnumValueOptions +@typing.final class ServiceOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURES_FIELD_NUMBER: builtins.int DEPRECATED_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - deprecated: builtins.bool = ... + deprecated: builtins.bool """Note: Field numbers 1 through 32 are reserved for Google's internal RPC framework. We apologize for hoarding these numbers to ourselves, but we were already using them long before we decided to release Protocol @@ -1126,52 +2122,72 @@ class ServiceOptions(google.protobuf.message.Message): for the service, or it will be completely ignored; in the very least, this is a formalization for deprecating services. """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - deprecated : typing.Optional[builtins.bool] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated","uninterpreted_option",b"uninterpreted_option"]) -> None: ... + features: global___FeatureSet | None = ..., + deprecated: builtins.bool | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["deprecated", b"deprecated", "features", b"features"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", b"deprecated", "features", b"features", "uninterpreted_option", b"uninterpreted_option" + ], + ) -> None: ... + global___ServiceOptions = ServiceOptions +@typing.final class MethodOptions(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _IdempotencyLevel: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _IdempotencyLevelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[MethodOptions._IdempotencyLevel.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + IDEMPOTENCY_UNKNOWN: MethodOptions._IdempotencyLevel.ValueType # 0 + NO_SIDE_EFFECTS: MethodOptions._IdempotencyLevel.ValueType # 1 + """implies idempotent""" + IDEMPOTENT: MethodOptions._IdempotencyLevel.ValueType # 2 + """idempotent, but may have side effects""" + class IdempotencyLevel(_IdempotencyLevel, metaclass=_IdempotencyLevelEnumTypeWrapper): """Is this method side-effect-free (or safe in HTTP parlance), or idempotent, or neither? HTTP based RPC implementation may choose GET verb for safe methods, and PUT verb for idempotent methods instead of the default POST. """ - pass - class _IdempotencyLevel: - V = typing.NewType('V', builtins.int) - class _IdempotencyLevelEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_IdempotencyLevel.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - IDEMPOTENCY_UNKNOWN = MethodOptions.IdempotencyLevel.V(0) - NO_SIDE_EFFECTS = MethodOptions.IdempotencyLevel.V(1) - """implies idempotent""" - - IDEMPOTENT = MethodOptions.IdempotencyLevel.V(2) - """idempotent, but may have side effects""" - - IDEMPOTENCY_UNKNOWN = MethodOptions.IdempotencyLevel.V(0) - NO_SIDE_EFFECTS = MethodOptions.IdempotencyLevel.V(1) + IDEMPOTENCY_UNKNOWN: MethodOptions.IdempotencyLevel.ValueType # 0 + NO_SIDE_EFFECTS: MethodOptions.IdempotencyLevel.ValueType # 1 """implies idempotent""" - - IDEMPOTENT = MethodOptions.IdempotencyLevel.V(2) + IDEMPOTENT: MethodOptions.IdempotencyLevel.ValueType # 2 """idempotent, but may have side effects""" - DEPRECATED_FIELD_NUMBER: builtins.int IDEMPOTENCY_LEVEL_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int - deprecated: builtins.bool = ... + deprecated: builtins.bool """Note: Field numbers 1 through 32 are reserved for Google's internal RPC framework. We apologize for hoarding these numbers to ourselves, but we were already using them long before we decided to release Protocol @@ -1182,22 +2198,52 @@ class MethodOptions(google.protobuf.message.Message): for the method, or it will be completely ignored; in the very least, this is a formalization for deprecating methods. """ + idempotency_level: global___MethodOptions.IdempotencyLevel.ValueType + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ - idempotency_level: global___MethodOptions.IdempotencyLevel.V = ... @property - def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" - pass - def __init__(self, + + def __init__( + self, *, - deprecated : typing.Optional[builtins.bool] = ..., - idempotency_level : typing.Optional[global___MethodOptions.IdempotencyLevel.V] = ..., - uninterpreted_option : typing.Optional[typing.Iterable[global___UninterpretedOption]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated","idempotency_level",b"idempotency_level"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["deprecated",b"deprecated","idempotency_level",b"idempotency_level","uninterpreted_option",b"uninterpreted_option"]) -> None: ... + deprecated: builtins.bool | None = ..., + idempotency_level: global___MethodOptions.IdempotencyLevel.ValueType | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "deprecated", b"deprecated", "features", b"features", "idempotency_level", b"idempotency_level" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", + b"deprecated", + "features", + b"features", + "idempotency_level", + b"idempotency_level", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + global___MethodOptions = MethodOptions +@typing.final class UninterpretedOption(google.protobuf.message.Message): """A message representing a option the parser does not recognize. This only appears in options protos created by the compiler::Parser class. @@ -1206,26 +2252,29 @@ class UninterpretedOption(google.protobuf.message.Message): or produced by Descriptor::CopyTo()) will never have UninterpretedOptions in them. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final class NamePart(google.protobuf.message.Message): """The name of the uninterpreted option. Each string represents a segment in a dot-separated name. is_extension is true iff a segment represents an extension (denoted with parentheses in options specs in .proto files). - E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - "foo.(bar.baz).qux". + E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + "foo.(bar.baz).moo". """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_PART_FIELD_NUMBER: builtins.int IS_EXTENSION_FIELD_NUMBER: builtins.int - name_part: typing.Text = ... - is_extension: builtins.bool = ... - def __init__(self, - *, - name_part : typing.Optional[typing.Text] = ..., - is_extension : typing.Optional[builtins.bool] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["is_extension",b"is_extension","name_part",b"name_part"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["is_extension",b"is_extension","name_part",b"name_part"]) -> None: ... + name_part: builtins.str + is_extension: builtins.bool + def __init__(self, *, name_part: builtins.str | None = ..., is_extension: builtins.bool | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["is_extension", b"is_extension", "name_part", b"name_part"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["is_extension", b"is_extension", "name_part", b"name_part"]) -> None: ... NAME_FIELD_NUMBER: builtins.int IDENTIFIER_VALUE_FIELD_NUMBER: builtins.int @@ -1234,32 +2283,413 @@ class UninterpretedOption(google.protobuf.message.Message): DOUBLE_VALUE_FIELD_NUMBER: builtins.int STRING_VALUE_FIELD_NUMBER: builtins.int AGGREGATE_VALUE_FIELD_NUMBER: builtins.int - @property - def name(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption.NamePart]: ... - identifier_value: typing.Text = ... + identifier_value: builtins.str """The value of the uninterpreted option, in whatever type the tokenizer identified it as during parsing. Exactly one of these should be set. """ + positive_int_value: builtins.int + negative_int_value: builtins.int + double_value: builtins.float + string_value: builtins.bytes + aggregate_value: builtins.str + @property + def name( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption.NamePart]: ... + def __init__( + self, + *, + name: collections.abc.Iterable[global___UninterpretedOption.NamePart] | None = ..., + identifier_value: builtins.str | None = ..., + positive_int_value: builtins.int | None = ..., + negative_int_value: builtins.int | None = ..., + double_value: builtins.float | None = ..., + string_value: builtins.bytes | None = ..., + aggregate_value: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "aggregate_value", + b"aggregate_value", + "double_value", + b"double_value", + "identifier_value", + b"identifier_value", + "negative_int_value", + b"negative_int_value", + "positive_int_value", + b"positive_int_value", + "string_value", + b"string_value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "aggregate_value", + b"aggregate_value", + "double_value", + b"double_value", + "identifier_value", + b"identifier_value", + "name", + b"name", + "negative_int_value", + b"negative_int_value", + "positive_int_value", + b"positive_int_value", + "string_value", + b"string_value", + ], + ) -> None: ... + +global___UninterpretedOption = UninterpretedOption + +@typing.final +class FeatureSet(google.protobuf.message.Message): + """=================================================================== + Features + + TODO Enums in C++ gencode (and potentially other languages) are + not well scoped. This means that each of the feature enums below can clash + with each other. The short names we've chosen maximize call-site + readability, but leave us very open to this scenario. A future feature will + be designed and implemented to handle this, hopefully before we ever hit a + conflict here. + """ - positive_int_value: builtins.int = ... - negative_int_value: builtins.int = ... - double_value: builtins.float = ... - string_value: builtins.bytes = ... - aggregate_value: typing.Text = ... - def __init__(self, + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _FieldPresence: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _FieldPresenceEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._FieldPresence.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + FIELD_PRESENCE_UNKNOWN: FeatureSet._FieldPresence.ValueType # 0 + EXPLICIT: FeatureSet._FieldPresence.ValueType # 1 + IMPLICIT: FeatureSet._FieldPresence.ValueType # 2 + LEGACY_REQUIRED: FeatureSet._FieldPresence.ValueType # 3 + + class FieldPresence(_FieldPresence, metaclass=_FieldPresenceEnumTypeWrapper): ... + FIELD_PRESENCE_UNKNOWN: FeatureSet.FieldPresence.ValueType # 0 + EXPLICIT: FeatureSet.FieldPresence.ValueType # 1 + IMPLICIT: FeatureSet.FieldPresence.ValueType # 2 + LEGACY_REQUIRED: FeatureSet.FieldPresence.ValueType # 3 + + class _EnumType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _EnumTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._EnumType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ENUM_TYPE_UNKNOWN: FeatureSet._EnumType.ValueType # 0 + OPEN: FeatureSet._EnumType.ValueType # 1 + CLOSED: FeatureSet._EnumType.ValueType # 2 + + class EnumType(_EnumType, metaclass=_EnumTypeEnumTypeWrapper): ... + ENUM_TYPE_UNKNOWN: FeatureSet.EnumType.ValueType # 0 + OPEN: FeatureSet.EnumType.ValueType # 1 + CLOSED: FeatureSet.EnumType.ValueType # 2 + + class _RepeatedFieldEncoding: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _RepeatedFieldEncodingEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._RepeatedFieldEncoding.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + REPEATED_FIELD_ENCODING_UNKNOWN: FeatureSet._RepeatedFieldEncoding.ValueType # 0 + PACKED: FeatureSet._RepeatedFieldEncoding.ValueType # 1 + EXPANDED: FeatureSet._RepeatedFieldEncoding.ValueType # 2 + + class RepeatedFieldEncoding(_RepeatedFieldEncoding, metaclass=_RepeatedFieldEncodingEnumTypeWrapper): ... + REPEATED_FIELD_ENCODING_UNKNOWN: FeatureSet.RepeatedFieldEncoding.ValueType # 0 + PACKED: FeatureSet.RepeatedFieldEncoding.ValueType # 1 + EXPANDED: FeatureSet.RepeatedFieldEncoding.ValueType # 2 + + class _Utf8Validation: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _Utf8ValidationEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._Utf8Validation.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UTF8_VALIDATION_UNKNOWN: FeatureSet._Utf8Validation.ValueType # 0 + VERIFY: FeatureSet._Utf8Validation.ValueType # 2 + NONE: FeatureSet._Utf8Validation.ValueType # 3 + + class Utf8Validation(_Utf8Validation, metaclass=_Utf8ValidationEnumTypeWrapper): ... + UTF8_VALIDATION_UNKNOWN: FeatureSet.Utf8Validation.ValueType # 0 + VERIFY: FeatureSet.Utf8Validation.ValueType # 2 + NONE: FeatureSet.Utf8Validation.ValueType # 3 + + class _MessageEncoding: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _MessageEncodingEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._MessageEncoding.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MESSAGE_ENCODING_UNKNOWN: FeatureSet._MessageEncoding.ValueType # 0 + LENGTH_PREFIXED: FeatureSet._MessageEncoding.ValueType # 1 + DELIMITED: FeatureSet._MessageEncoding.ValueType # 2 + + class MessageEncoding(_MessageEncoding, metaclass=_MessageEncodingEnumTypeWrapper): ... + MESSAGE_ENCODING_UNKNOWN: FeatureSet.MessageEncoding.ValueType # 0 + LENGTH_PREFIXED: FeatureSet.MessageEncoding.ValueType # 1 + DELIMITED: FeatureSet.MessageEncoding.ValueType # 2 + + class _JsonFormat: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _JsonFormatEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._JsonFormat.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + JSON_FORMAT_UNKNOWN: FeatureSet._JsonFormat.ValueType # 0 + ALLOW: FeatureSet._JsonFormat.ValueType # 1 + LEGACY_BEST_EFFORT: FeatureSet._JsonFormat.ValueType # 2 + + class JsonFormat(_JsonFormat, metaclass=_JsonFormatEnumTypeWrapper): ... + JSON_FORMAT_UNKNOWN: FeatureSet.JsonFormat.ValueType # 0 + ALLOW: FeatureSet.JsonFormat.ValueType # 1 + LEGACY_BEST_EFFORT: FeatureSet.JsonFormat.ValueType # 2 + + class _EnforceNamingStyle: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _EnforceNamingStyleEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._EnforceNamingStyle.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ENFORCE_NAMING_STYLE_UNKNOWN: FeatureSet._EnforceNamingStyle.ValueType # 0 + STYLE2024: FeatureSet._EnforceNamingStyle.ValueType # 1 + STYLE_LEGACY: FeatureSet._EnforceNamingStyle.ValueType # 2 + STYLE2026: FeatureSet._EnforceNamingStyle.ValueType # 3 + + class EnforceNamingStyle(_EnforceNamingStyle, metaclass=_EnforceNamingStyleEnumTypeWrapper): ... + ENFORCE_NAMING_STYLE_UNKNOWN: FeatureSet.EnforceNamingStyle.ValueType # 0 + STYLE2024: FeatureSet.EnforceNamingStyle.ValueType # 1 + STYLE_LEGACY: FeatureSet.EnforceNamingStyle.ValueType # 2 + STYLE2026: FeatureSet.EnforceNamingStyle.ValueType # 3 + + @typing.final + class VisibilityFeature(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _DefaultSymbolVisibility: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _DefaultSymbolVisibilityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ + FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType + ], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 0 + EXPORT_ALL: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 1 + """Default pre-EDITION_2024, all UNSET visibility are export.""" + EXPORT_TOP_LEVEL: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 2 + """All top-level symbols default to export, nested default to local.""" + LOCAL_ALL: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 3 + """All symbols default to local.""" + STRICT: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 4 + """All symbols local by default. Nested types cannot be exported. + With special case caveat for message { enum {} reserved 1 to max; } + This is the recommended setting for new protos. + """ + + class DefaultSymbolVisibility(_DefaultSymbolVisibility, metaclass=_DefaultSymbolVisibilityEnumTypeWrapper): ... + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 0 + EXPORT_ALL: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 1 + """Default pre-EDITION_2024, all UNSET visibility are export.""" + EXPORT_TOP_LEVEL: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 2 + """All top-level symbols default to export, nested default to local.""" + LOCAL_ALL: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 3 + """All symbols default to local.""" + STRICT: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 4 + """All symbols local by default. Nested types cannot be exported. + With special case caveat for message { enum {} reserved 1 to max; } + This is the recommended setting for new protos. + """ + + def __init__(self) -> None: ... + + FIELD_PRESENCE_FIELD_NUMBER: builtins.int + ENUM_TYPE_FIELD_NUMBER: builtins.int + REPEATED_FIELD_ENCODING_FIELD_NUMBER: builtins.int + UTF8_VALIDATION_FIELD_NUMBER: builtins.int + MESSAGE_ENCODING_FIELD_NUMBER: builtins.int + JSON_FORMAT_FIELD_NUMBER: builtins.int + ENFORCE_NAMING_STYLE_FIELD_NUMBER: builtins.int + DEFAULT_SYMBOL_VISIBILITY_FIELD_NUMBER: builtins.int + field_presence: global___FeatureSet.FieldPresence.ValueType + enum_type: global___FeatureSet.EnumType.ValueType + repeated_field_encoding: global___FeatureSet.RepeatedFieldEncoding.ValueType + utf8_validation: global___FeatureSet.Utf8Validation.ValueType + message_encoding: global___FeatureSet.MessageEncoding.ValueType + json_format: global___FeatureSet.JsonFormat.ValueType + enforce_naming_style: global___FeatureSet.EnforceNamingStyle.ValueType + default_symbol_visibility: global___FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType + def __init__( + self, *, - name : typing.Optional[typing.Iterable[global___UninterpretedOption.NamePart]] = ..., - identifier_value : typing.Optional[typing.Text] = ..., - positive_int_value : typing.Optional[builtins.int] = ..., - negative_int_value : typing.Optional[builtins.int] = ..., - double_value : typing.Optional[builtins.float] = ..., - string_value : typing.Optional[builtins.bytes] = ..., - aggregate_value : typing.Optional[typing.Text] = ..., + field_presence: global___FeatureSet.FieldPresence.ValueType | None = ..., + enum_type: global___FeatureSet.EnumType.ValueType | None = ..., + repeated_field_encoding: global___FeatureSet.RepeatedFieldEncoding.ValueType | None = ..., + utf8_validation: global___FeatureSet.Utf8Validation.ValueType | None = ..., + message_encoding: global___FeatureSet.MessageEncoding.ValueType | None = ..., + json_format: global___FeatureSet.JsonFormat.ValueType | None = ..., + enforce_naming_style: global___FeatureSet.EnforceNamingStyle.ValueType | None = ..., + default_symbol_visibility: global___FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "default_symbol_visibility", + b"default_symbol_visibility", + "enforce_naming_style", + b"enforce_naming_style", + "enum_type", + b"enum_type", + "field_presence", + b"field_presence", + "json_format", + b"json_format", + "message_encoding", + b"message_encoding", + "repeated_field_encoding", + b"repeated_field_encoding", + "utf8_validation", + b"utf8_validation", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_symbol_visibility", + b"default_symbol_visibility", + "enforce_naming_style", + b"enforce_naming_style", + "enum_type", + b"enum_type", + "field_presence", + b"field_presence", + "json_format", + b"json_format", + "message_encoding", + b"message_encoding", + "repeated_field_encoding", + b"repeated_field_encoding", + "utf8_validation", + b"utf8_validation", + ], + ) -> None: ... + +global___FeatureSet = FeatureSet + +@typing.final +class FeatureSetDefaults(google.protobuf.message.Message): + """A compiled specification for the defaults of a set of features. These + messages are generated from FeatureSet extensions and can be used to seed + feature resolution. The resolution with this object becomes a simple search + for the closest matching edition, followed by proto merges. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureSetEditionDefault(google.protobuf.message.Message): + """A map from every known edition with a unique set of defaults to its + defaults. Not all editions may be contained here. For a given edition, + the defaults at the closest matching edition ordered at or before it should + be used. This field must be in strict ascending order by edition. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_FIELD_NUMBER: builtins.int + OVERRIDABLE_FEATURES_FIELD_NUMBER: builtins.int + FIXED_FEATURES_FIELD_NUMBER: builtins.int + edition: global___Edition.ValueType + @property + def overridable_features(self) -> global___FeatureSet: + """Defaults of features that can be overridden in this edition.""" + + @property + def fixed_features(self) -> global___FeatureSet: + """Defaults of features that can't be overridden in this edition.""" + + def __init__( + self, + *, + edition: global___Edition.ValueType | None = ..., + overridable_features: global___FeatureSet | None = ..., + fixed_features: global___FeatureSet | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "edition", b"edition", "fixed_features", b"fixed_features", "overridable_features", b"overridable_features" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", b"edition", "fixed_features", b"fixed_features", "overridable_features", b"overridable_features" + ], ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["aggregate_value",b"aggregate_value","double_value",b"double_value","identifier_value",b"identifier_value","negative_int_value",b"negative_int_value","positive_int_value",b"positive_int_value","string_value",b"string_value"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["aggregate_value",b"aggregate_value","double_value",b"double_value","identifier_value",b"identifier_value","name",b"name","negative_int_value",b"negative_int_value","positive_int_value",b"positive_int_value","string_value",b"string_value"]) -> None: ... -global___UninterpretedOption = UninterpretedOption + DEFAULTS_FIELD_NUMBER: builtins.int + MINIMUM_EDITION_FIELD_NUMBER: builtins.int + MAXIMUM_EDITION_FIELD_NUMBER: builtins.int + minimum_edition: global___Edition.ValueType + """The minimum supported edition (inclusive) when this was constructed. + Editions before this will not have defaults. + """ + maximum_edition: global___Edition.ValueType + """The maximum known edition (inclusive) when this was constructed. Editions + after this will not have reliable defaults. + """ + @property + def defaults( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___FeatureSetDefaults.FeatureSetEditionDefault + ]: ... + def __init__( + self, + *, + defaults: collections.abc.Iterable[global___FeatureSetDefaults.FeatureSetEditionDefault] | None = ..., + minimum_edition: global___Edition.ValueType | None = ..., + maximum_edition: global___Edition.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["maximum_edition", b"maximum_edition", "minimum_edition", b"minimum_edition"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "defaults", b"defaults", "maximum_edition", b"maximum_edition", "minimum_edition", b"minimum_edition" + ], + ) -> None: ... + +global___FeatureSetDefaults = FeatureSetDefaults + +@typing.final class SourceCodeInfo(google.protobuf.message.Message): """=================================================================== Optional source code info @@ -1267,51 +2697,19 @@ class SourceCodeInfo(google.protobuf.message.Message): Encapsulates information about the original source file from which a FileDescriptorProto was generated. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final class Location(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + PATH_FIELD_NUMBER: builtins.int SPAN_FIELD_NUMBER: builtins.int LEADING_COMMENTS_FIELD_NUMBER: builtins.int TRAILING_COMMENTS_FIELD_NUMBER: builtins.int LEADING_DETACHED_COMMENTS_FIELD_NUMBER: builtins.int - @property - def path(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: - """Identifies which part of the FileDescriptorProto was defined at this - location. - - Each element is a field number or an index. They form a path from - the root FileDescriptorProto to the place where the definition. For - example, this path: - [ 4, 3, 2, 7, 1 ] - refers to: - file.message_type(3) // 4, 3 - .field(7) // 2, 7 - .name() // 1 - This is because FileDescriptorProto.message_type has field number 4: - repeated DescriptorProto message_type = 4; - and DescriptorProto.field has field number 2: - repeated FieldDescriptorProto field = 2; - and FieldDescriptorProto.name has field number 1: - optional string name = 1; - - Thus, the above path gives the location of a field name. If we removed - the last element: - [ 4, 3, 2, 7 ] - this path refers to the whole field declaration (from the beginning - of the label to the terminating semicolon). - """ - pass - @property - def span(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: - """Always has exactly three or four elements: start line, start column, - end line (optional, otherwise assumed same as start line), end column. - These are packed into a single field for efficiency. Note that line - and column numbers are zero-based -- typically you will want to add - 1 to each before displaying to a user. - """ - pass - leading_comments: typing.Text = ... + leading_comments: builtins.str """If this SourceCodeInfo represents a complete declaration, these are any comments appearing before and after the declaration which appear to be attached to the declaration. @@ -1339,13 +2737,13 @@ class SourceCodeInfo(google.protobuf.message.Message): // Comment attached to baz. // Another line attached to baz. - // Comment attached to qux. + // Comment attached to moo. // - // Another line attached to qux. - optional double qux = 4; + // Another line attached to moo. + optional double moo = 4; // Detached comment for corge. This is not leading or trailing comments - // to qux or corge because there are blank lines separating it from + // to moo or corge because there are blank lines separating it from // both. // Detached comment for corge paragraph 2. @@ -1360,20 +2758,72 @@ class SourceCodeInfo(google.protobuf.message.Message): // ignored detached comments. """ + trailing_comments: builtins.str + @property + def path(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Identifies which part of the FileDescriptorProto was defined at this + location. + + Each element is a field number or an index. They form a path from + the root FileDescriptorProto to the place where the definition appears. + For example, this path: + [ 4, 3, 2, 7, 1 ] + refers to: + file.message_type(3) // 4, 3 + .field(7) // 2, 7 + .name() // 1 + This is because FileDescriptorProto.message_type has field number 4: + repeated DescriptorProto message_type = 4; + and DescriptorProto.field has field number 2: + repeated FieldDescriptorProto field = 2; + and FieldDescriptorProto.name has field number 1: + optional string name = 1; + + Thus, the above path gives the location of a field name. If we removed + the last element: + [ 4, 3, 2, 7 ] + this path refers to the whole field declaration (from the beginning + of the label to the terminating semicolon). + """ - trailing_comments: typing.Text = ... @property - def leading_detached_comments(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: ... - def __init__(self, + def span(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Always has exactly three or four elements: start line, start column, + end line (optional, otherwise assumed same as start line), end column. + These are packed into a single field for efficiency. Note that line + and column numbers are zero-based -- typically you will want to add + 1 to each before displaying to a user. + """ + + @property + def leading_detached_comments(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + def __init__( + self, *, - path : typing.Optional[typing.Iterable[builtins.int]] = ..., - span : typing.Optional[typing.Iterable[builtins.int]] = ..., - leading_comments : typing.Optional[typing.Text] = ..., - trailing_comments : typing.Optional[typing.Text] = ..., - leading_detached_comments : typing.Optional[typing.Iterable[typing.Text]] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["leading_comments",b"leading_comments","trailing_comments",b"trailing_comments"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["leading_comments",b"leading_comments","leading_detached_comments",b"leading_detached_comments","path",b"path","span",b"span","trailing_comments",b"trailing_comments"]) -> None: ... + path: collections.abc.Iterable[builtins.int] | None = ..., + span: collections.abc.Iterable[builtins.int] | None = ..., + leading_comments: builtins.str | None = ..., + trailing_comments: builtins.str | None = ..., + leading_detached_comments: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["leading_comments", b"leading_comments", "trailing_comments", b"trailing_comments"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "leading_comments", + b"leading_comments", + "leading_detached_comments", + b"leading_detached_comments", + "path", + b"path", + "span", + b"span", + "trailing_comments", + b"trailing_comments", + ], + ) -> None: ... LOCATION_FIELD_NUMBER: builtins.int @property @@ -1422,66 +2872,106 @@ class SourceCodeInfo(google.protobuf.message.Message): ignore those that it doesn't understand, as more types of locations could be recorded in the future. """ - pass - def __init__(self, - *, - location : typing.Optional[typing.Iterable[global___SourceCodeInfo.Location]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["location",b"location"]) -> None: ... + + def __init__(self, *, location: collections.abc.Iterable[global___SourceCodeInfo.Location] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["location", b"location"]) -> None: ... + global___SourceCodeInfo = SourceCodeInfo +@typing.final class GeneratedCodeInfo(google.protobuf.message.Message): """Describes the relationship between generated code and its original source file. A GeneratedCodeInfo message is associated with only one generated source file, but may contain references to different source .proto files. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final class Annotation(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Semantic: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _SemanticEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[GeneratedCodeInfo.Annotation._Semantic.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NONE: GeneratedCodeInfo.Annotation._Semantic.ValueType # 0 + """There is no effect or the effect is indescribable.""" + SET: GeneratedCodeInfo.Annotation._Semantic.ValueType # 1 + """The element is set or otherwise mutated.""" + ALIAS: GeneratedCodeInfo.Annotation._Semantic.ValueType # 2 + """An alias to the element is returned.""" + + class Semantic(_Semantic, metaclass=_SemanticEnumTypeWrapper): + """Represents the identified object's effect on the element in the original + .proto file. + """ + + NONE: GeneratedCodeInfo.Annotation.Semantic.ValueType # 0 + """There is no effect or the effect is indescribable.""" + SET: GeneratedCodeInfo.Annotation.Semantic.ValueType # 1 + """The element is set or otherwise mutated.""" + ALIAS: GeneratedCodeInfo.Annotation.Semantic.ValueType # 2 + """An alias to the element is returned.""" + PATH_FIELD_NUMBER: builtins.int SOURCE_FILE_FIELD_NUMBER: builtins.int BEGIN_FIELD_NUMBER: builtins.int END_FIELD_NUMBER: builtins.int - @property - def path(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: - """Identifies the element in the original source .proto file. This field - is formatted the same as SourceCodeInfo.Location.path. - """ - pass - source_file: typing.Text = ... + SEMANTIC_FIELD_NUMBER: builtins.int + source_file: builtins.str """Identifies the filesystem path to the original source .proto.""" - - begin: builtins.int = ... + begin: builtins.int """Identifies the starting offset in bytes in the generated code that relates to the identified object. """ - - end: builtins.int = ... + end: builtins.int """Identifies the ending offset in bytes in the generated code that - relates to the identified offset. The end offset should be one past + relates to the identified object. The end offset should be one past the last relevant byte (so the length of the text = end - begin). """ + semantic: global___GeneratedCodeInfo.Annotation.Semantic.ValueType + @property + def path(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Identifies the element in the original source .proto file. This field + is formatted the same as SourceCodeInfo.Location.path. + """ - def __init__(self, + def __init__( + self, *, - path : typing.Optional[typing.Iterable[builtins.int]] = ..., - source_file : typing.Optional[typing.Text] = ..., - begin : typing.Optional[builtins.int] = ..., - end : typing.Optional[builtins.int] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["begin",b"begin","end",b"end","source_file",b"source_file"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["begin",b"begin","end",b"end","path",b"path","source_file",b"source_file"]) -> None: ... + path: collections.abc.Iterable[builtins.int] | None = ..., + source_file: builtins.str | None = ..., + begin: builtins.int | None = ..., + end: builtins.int | None = ..., + semantic: global___GeneratedCodeInfo.Annotation.Semantic.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["begin", b"begin", "end", b"end", "semantic", b"semantic", "source_file", b"source_file"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "begin", b"begin", "end", b"end", "path", b"path", "semantic", b"semantic", "source_file", b"source_file" + ], + ) -> None: ... ANNOTATION_FIELD_NUMBER: builtins.int @property - def annotation(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___GeneratedCodeInfo.Annotation]: + def annotation( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___GeneratedCodeInfo.Annotation]: """An Annotation connects some span of text in generated code to an element of its generating .proto file. """ - pass - def __init__(self, - *, - annotation : typing.Optional[typing.Iterable[global___GeneratedCodeInfo.Annotation]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["annotation",b"annotation"]) -> None: ... + + def __init__(self, *, annotation: collections.abc.Iterable[global___GeneratedCodeInfo.Annotation] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["annotation", b"annotation"]) -> None: ... + global___GeneratedCodeInfo = GeneratedCodeInfo diff --git a/stubs/protobuf/google/protobuf/descriptor_pool.pyi b/stubs/protobuf/google/protobuf/descriptor_pool.pyi index aabe9d9dca0a..59767efd7817 100644 --- a/stubs/protobuf/google/protobuf/descriptor_pool.pyi +++ b/stubs/protobuf/google/protobuf/descriptor_pool.pyi @@ -1,25 +1,36 @@ -from typing import Any, Optional +from _typeshed import Unused +from typing import Any +from typing_extensions import Self + +from .descriptor import ( + Descriptor, + EnumDescriptor, + FieldDescriptor, + FileDescriptor, + MethodDescriptor, + OneofDescriptor, + ServiceDescriptor, +) +from .descriptor_pb2 import FeatureSetDefaults, FileDescriptorProto class DescriptorPool: - def __new__(cls, descriptor_db: Optional[Any] = ...): ... - def __init__(self, descriptor_db: Optional[Any] = ...) -> None: ... - def Add(self, file_desc_proto): ... - def AddSerializedFile(self, serialized_file_desc_proto): ... - def AddDescriptor(self, desc): ... - def AddEnumDescriptor(self, enum_desc): ... - def AddServiceDescriptor(self, service_desc): ... - def AddExtensionDescriptor(self, extension): ... - def AddFileDescriptor(self, file_desc): ... - def FindFileByName(self, file_name): ... - def FindFileContainingSymbol(self, symbol): ... - def FindMessageTypeByName(self, full_name): ... - def FindEnumTypeByName(self, full_name): ... - def FindFieldByName(self, full_name): ... - def FindOneofByName(self, full_name): ... - def FindExtensionByName(self, full_name): ... - def FindExtensionByNumber(self, message_descriptor, number): ... - def FindAllExtensions(self, message_descriptor): ... - def FindServiceByName(self, full_name): ... - def FindMethodByName(self, full_name): ... + def __new__(cls, descriptor_db: Any = None) -> Self: ... + def __init__( # pyright: ignore[reportInconsistentConstructor] + self, descriptor_db: Any = None, use_deprecated_legacy_json_field_conflicts: Unused = False + ) -> None: ... + def Add(self, file_desc_proto: FileDescriptorProto) -> None: ... + def AddSerializedFile(self, serialized_file_desc_proto: bytes) -> FileDescriptor: ... + def FindFileByName(self, file_name: str) -> FileDescriptor: ... + def FindFileContainingSymbol(self, symbol: str) -> FileDescriptor: ... + def FindMessageTypeByName(self, full_name: str) -> Descriptor: ... + def FindEnumTypeByName(self, full_name: str) -> EnumDescriptor: ... + def FindFieldByName(self, full_name: str) -> FieldDescriptor: ... + def FindOneofByName(self, full_name: str) -> OneofDescriptor: ... + def FindExtensionByName(self, full_name: str) -> FieldDescriptor: ... + def FindExtensionByNumber(self, message_descriptor: Descriptor, number: int) -> FieldDescriptor: ... + def FindAllExtensions(self, message_descriptor: Descriptor) -> list[FieldDescriptor]: ... + def FindServiceByName(self, full_name: str) -> ServiceDescriptor: ... + def FindMethodByName(self, full_name: str) -> MethodDescriptor: ... + def SetFeatureSetDefaults(self, defaults: FeatureSetDefaults) -> None: ... -def Default(): ... +def Default() -> DescriptorPool: ... diff --git a/stubs/protobuf/google/protobuf/duration.pyi b/stubs/protobuf/google/protobuf/duration.pyi new file mode 100644 index 000000000000..c7e858fedbf3 --- /dev/null +++ b/stubs/protobuf/google/protobuf/duration.pyi @@ -0,0 +1,16 @@ +from datetime import timedelta + +from google.protobuf.duration_pb2 import Duration + +def from_json_string(value: str) -> Duration: ... +def from_microseconds(micros: float) -> Duration: ... +def from_milliseconds(millis: float) -> Duration: ... +def from_nanoseconds(nanos: float) -> Duration: ... +def from_seconds(seconds: float) -> Duration: ... +def from_timedelta(td: timedelta) -> Duration: ... +def to_json_string(duration: Duration) -> str: ... +def to_microseconds(duration: Duration) -> int: ... +def to_milliseconds(duration: Duration) -> int: ... +def to_nanoseconds(duration: Duration) -> int: ... +def to_seconds(duration: Duration) -> int: ... +def to_timedelta(duration: Duration) -> timedelta: ... diff --git a/stubs/protobuf/google/protobuf/duration_pb2.pyi b/stubs/protobuf/google/protobuf/duration_pb2.pyi index b2786a8ed92e..2cb846889f4d 100644 --- a/stubs/protobuf/google/protobuf/duration_pb2.pyi +++ b/stubs/protobuf/google/protobuf/duration_pb2.pyi @@ -1,15 +1,47 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import typing + import google.protobuf.descriptor import google.protobuf.internal.well_known_types import google.protobuf.message -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class Duration(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Duration): """A Duration represents a signed, fixed-length span of time represented as a count of seconds and fractions of seconds at nanosecond @@ -70,16 +102,17 @@ class Duration(google.protobuf.message.Message, google.protobuf.internal.well_kn be expressed in JSON format as "3.000000001s", and 3 seconds and 1 microsecond should be expressed in JSON format as "3.000001s". """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + SECONDS_FIELD_NUMBER: builtins.int NANOS_FIELD_NUMBER: builtins.int - seconds: builtins.int = ... + seconds: builtins.int """Signed seconds of the span of time. Must be from -315,576,000,000 to +315,576,000,000 inclusive. Note: these bounds are computed from: 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years """ - - nanos: builtins.int = ... + nanos: builtins.int """Signed fractions of a second at nanosecond resolution of the span of time. Durations less than one second are represented with a 0 `seconds` field and a positive or negative `nanos` field. For durations @@ -87,11 +120,7 @@ class Duration(google.protobuf.message.Message, google.protobuf.internal.well_kn of the same sign as the `seconds` field. Must be from -999,999,999 to +999,999,999 inclusive. """ + def __init__(self, *, seconds: builtins.int | None = ..., nanos: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["nanos", b"nanos", "seconds", b"seconds"]) -> None: ... - def __init__(self, - *, - seconds : builtins.int = ..., - nanos : builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["nanos",b"nanos","seconds",b"seconds"]) -> None: ... global___Duration = Duration diff --git a/stubs/protobuf/google/protobuf/empty_pb2.pyi b/stubs/protobuf/google/protobuf/empty_pb2.pyi index 333e2615873f..317979279540 100644 --- a/stubs/protobuf/google/protobuf/empty_pb2.pyi +++ b/stubs/protobuf/google/protobuf/empty_pb2.pyi @@ -1,12 +1,45 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + +import typing + import google.protobuf.descriptor import google.protobuf.message -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class Empty(google.protobuf.message.Message): """A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request @@ -15,10 +48,10 @@ class Empty(google.protobuf.message.Message): service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } - - The JSON representation for `Empty` is empty JSON object `{}`. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... - def __init__(self, - ) -> None: ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + global___Empty = Empty diff --git a/stubs/protobuf/google/protobuf/field_mask_pb2.pyi b/stubs/protobuf/google/protobuf/field_mask_pb2.pyi index fba06afd7e48..32d7594145a9 100644 --- a/stubs/protobuf/google/protobuf/field_mask_pb2.pyi +++ b/stubs/protobuf/google/protobuf/field_mask_pb2.pyi @@ -1,17 +1,49 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import collections.abc +import typing + import google.protobuf.descriptor import google.protobuf.internal.containers import google.protobuf.internal.well_known_types import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class FieldMask(google.protobuf.message.Message, google.protobuf.internal.well_known_types.FieldMask): """`FieldMask` represents a set of symbolic field paths, for example: @@ -125,24 +157,22 @@ class FieldMask(google.protobuf.message.Message, google.protobuf.internal.well_k An implementation may provide options to override this default behavior for repeated and message fields. - In order to reset a field's value to the default, the field must - be in the mask and set to the default value in the provided resource. - Hence, in order to reset all fields of a resource, provide a default - instance of the resource and set all fields in the mask, or do - not provide a mask as described below. - - If a field mask is not present on update, the operation applies to - all fields (as if a field mask of all fields has been specified). - Note that in the presence of schema evolution, this may mean that - fields the client does not know and has therefore not filled into - the request will be reset to their default. If this is unwanted - behavior, a specific service may require a client to always specify - a field mask, producing an error if not. - - As with get operations, the location of the resource which - describes the updated values in the request message depends on the - operation kind. In any case, the effect of the field mask is - required to be honored by the API. + Note that libraries which implement FieldMask resolution have various + different behaviors in the face of empty masks or the special "*" mask. + When implementing a service you should confirm these cases have the + appropriate behavior in the underlying FieldMask library that you desire, + and you may need to special case those cases in your application code if + the underlying field mask library behavior differs from your intended + service semantics. + + Update methods implementing https://google.aip.dev/134 + - MUST support the special value * meaning "full replace" + - MUST treat an omitted field mask as "replace fields which are present". + + Other methods implementing https://google.aip.dev/157 + - SHOULD support the special value "*" to mean "get all". + - MUST treat an omitted field mask to mean "get all", unless otherwise + documented. ## Considerations for HTTP REST @@ -213,15 +243,15 @@ class FieldMask(google.protobuf.message.Message, google.protobuf.internal.well_k request should verify the included field paths, and return an `INVALID_ARGUMENT` error if any path is unmappable. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + PATHS_FIELD_NUMBER: builtins.int @property - def paths(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: + def paths(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """The set of field mask paths.""" - pass - def __init__(self, - *, - paths : typing.Optional[typing.Iterable[typing.Text]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["paths",b"paths"]) -> None: ... + + def __init__(self, *, paths: collections.abc.Iterable[builtins.str] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["paths", b"paths"]) -> None: ... + global___FieldMask = FieldMask diff --git a/stubs/protobuf/google/protobuf/internal/api_implementation.pyi b/stubs/protobuf/google/protobuf/internal/api_implementation.pyi new file mode 100644 index 000000000000..1cab529368a5 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/api_implementation.pyi @@ -0,0 +1,2 @@ +def Type() -> str: ... +def IsPythonDefaultSerializationDeterministic() -> bool: ... diff --git a/stubs/protobuf/google/protobuf/internal/builder.pyi b/stubs/protobuf/google/protobuf/internal/builder.pyi new file mode 100644 index 000000000000..a183f4c16d13 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/builder.pyi @@ -0,0 +1,9 @@ +from types import ModuleType +from typing import Any + +from google.protobuf.descriptor import FileDescriptor + +def BuildMessageAndEnumDescriptors(file_des: FileDescriptor, module: dict[str, Any]) -> None: ... +def BuildTopDescriptorsAndMessages(file_des: FileDescriptor, module_name: str, module: dict[str, Any]) -> None: ... +def AddHelpersToExtensions(file_des: FileDescriptor) -> None: ... +def BuildServices(file_des: FileDescriptor, module_name: str, module: ModuleType) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/containers.pyi b/stubs/protobuf/google/protobuf/internal/containers.pyi index cef517ec2460..bb48c5bb6ddd 100644 --- a/stubs/protobuf/google/protobuf/internal/containers.pyi +++ b/stubs/protobuf/google/protobuf/internal/containers.pyi @@ -1,94 +1,149 @@ -from typing import ( - Any, - Callable, - Iterable, - Iterator, - List, - Mapping as Mapping, - MutableMapping as MutableMapping, - Optional, - Sequence, - Text, - TypeVar, - Union, - overload, -) -from typing_extensions import SupportsIndex - -from google.protobuf.descriptor import Descriptor +from collections.abc import Callable, Iterable, Iterator, MutableMapping, MutableSequence, Sequence +from typing import Any, Protocol, SupportsIndex, TypeVar, overload, type_check_only + +from google.protobuf.descriptor import Descriptor, FieldDescriptor from google.protobuf.internal.message_listener import MessageListener from google.protobuf.internal.python_message import GeneratedProtocolMessageType from google.protobuf.message import Message _T = TypeVar("_T") -_K = TypeVar("_K", bound=Union[bool, int, Text]) -_ScalarV = TypeVar("_ScalarV", bound=Union[bool, int, float, Text, bytes]) +_K = TypeVar("_K", bound=bool | int | str) +_ScalarV = TypeVar("_ScalarV", bound=bool | int | float | str | bytes) _MessageV = TypeVar("_MessageV", bound=Message) -_M = TypeVar("_M") + +@type_check_only +class _ValueChecker(Protocol[_T]): + def CheckValue(self, proposed_value: _T) -> _T: ... + def DefaultValue(self) -> _T: ... class BaseContainer(Sequence[_T]): + __slots__ = ["_message_listener", "_values"] def __init__(self, message_listener: MessageListener) -> None: ... - def __len__(self) -> int: ... - def __ne__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def __repr__(self) -> str: ... - def sort(self, *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> None: ... + @overload def __getitem__(self, key: SupportsIndex) -> _T: ... @overload - def __getitem__(self, key: slice) -> List[_T]: ... + def __getitem__(self, key: slice) -> list[_T]: ... -class RepeatedScalarFieldContainer(BaseContainer[_ScalarV]): - def __init__(self, message_listener: MessageListener, message_descriptor: Descriptor) -> None: ... + def __len__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + # Same as list.sort, the extra sort_function kwarg errors in Python 3 + def sort(self, *, key: Callable[[_T], Any] | None = None, reverse: bool = False) -> None: ... + def reverse(self) -> None: ... + +class RepeatedScalarFieldContainer(BaseContainer[_ScalarV], MutableSequence[_ScalarV]): + __slots__ = ["_type_checker"] + def __init__( + self, message_listener: MessageListener, type_checker: _ValueChecker[_ScalarV], field: FieldDescriptor | None = None + ) -> None: ... def append(self, value: _ScalarV) -> None: ... def insert(self, key: int, value: _ScalarV) -> None: ... - def extend(self, elem_seq: Optional[Iterable[_ScalarV]]) -> None: ... - def MergeFrom(self: _M, other: _M) -> None: ... + def extend(self, elem_seq: Iterable[_ScalarV] | None) -> None: ... + def MergeFrom(self, other: RepeatedScalarFieldContainer[_ScalarV] | Iterable[_ScalarV]) -> None: ... def remove(self, elem: _ScalarV) -> None: ... - def pop(self, key: int = ...) -> _ScalarV: ... + def pop(self, key: int = -1) -> _ScalarV: ... + @overload def __setitem__(self, key: int, value: _ScalarV) -> None: ... @overload def __setitem__(self, key: slice, value: Iterable[_ScalarV]) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_ScalarV]: ... - def __setslice__(self, start: int, stop: int, values: Iterable[_ScalarV]) -> None: ... - def __delitem__(self, key: Union[int, slice]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... + + def __delitem__(self, key: int | slice) -> None: ... def __eq__(self, other: object) -> bool: ... + def __deepcopy__(self, unused_memo: Any = None) -> RepeatedScalarFieldContainer[_ScalarV]: ... + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: ... # Any: numpy types -class RepeatedCompositeFieldContainer(BaseContainer[_MessageV]): - def __init__(self, message_listener: MessageListener, type_checker: Any) -> None: ... - def add(self, **kwargs: Any) -> _MessageV: ... +class RepeatedCompositeFieldContainer(BaseContainer[_MessageV], MutableSequence[_MessageV]): + __slots__ = ["_message_descriptor"] + def __init__(self, message_listener: MessageListener, message_descriptor: Descriptor) -> None: ... + def add(self, **kwargs: Any) -> _MessageV: ... # Any: field names and values def append(self, value: _MessageV) -> None: ... def insert(self, key: int, value: _MessageV) -> None: ... def extend(self, elem_seq: Iterable[_MessageV]) -> None: ... - def MergeFrom(self: _M, other: _M) -> None: ... + def MergeFrom(self, other: RepeatedCompositeFieldContainer[_MessageV] | Iterable[_MessageV]) -> None: ... def remove(self, elem: _MessageV) -> None: ... - def pop(self, key: int = ...) -> _MessageV: ... - def __getslice__(self, start: int, stop: int) -> List[_MessageV]: ... - def __delitem__(self, key: Union[int, slice]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... + def pop(self, key: int = -1) -> _MessageV: ... + + @overload + def __setitem__(self, key: int, value: _MessageV) -> None: ... + @overload + def __setitem__(self, key: slice, value: Iterable[_MessageV]) -> None: ... + + def __delitem__(self, key: int | slice) -> None: ... def __eq__(self, other: object) -> bool: ... class ScalarMap(MutableMapping[_K, _ScalarV]): - def __setitem__(self, k: _K, v: _ScalarV) -> None: ... - def __delitem__(self, v: _K) -> None: ... - def __getitem__(self, k: _K) -> _ScalarV: ... + __slots__ = ["_key_checker", "_value_checker", "_values", "_message_listener", "_entry_descriptor"] + def __init__( + self, + message_listener: MessageListener, + key_checker: _ValueChecker[_K], + value_checker: _ValueChecker[_ScalarV], + entry_descriptor: Descriptor, + ) -> None: ... + def __getitem__(self, key: _K) -> _ScalarV: ... + + @overload + def get(self, key: _K, default: None = None) -> _ScalarV | None: ... + @overload + def get(self, key: _K, default: _ScalarV) -> _ScalarV: ... + @overload + def get(self, key: _K, default: _T) -> _ScalarV | _T: ... + + def __setitem__(self, key: _K, value: _ScalarV) -> None: ... + def __delitem__(self, key: _K) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_K]: ... def __eq__(self, other: object) -> bool: ... - def MergeFrom(self: _M, other: _M): ... + def setdefault(self, key: _K, value: _ScalarV | None = None) -> _ScalarV: ... + def MergeFrom(self, other: ScalarMap[_K, _ScalarV]) -> None: ... def InvalidateIterators(self) -> None: ... + def clear(self) -> None: ... def GetEntryClass(self) -> GeneratedProtocolMessageType: ... class MessageMap(MutableMapping[_K, _MessageV]): - def __setitem__(self, k: _K, v: _MessageV) -> None: ... - def __delitem__(self, v: _K) -> None: ... - def __getitem__(self, k: _K) -> _MessageV: ... + __slots__ = ["_key_checker", "_values", "_message_listener", "_message_descriptor", "_entry_descriptor"] + def __init__( + self, + message_listener: MessageListener, + message_descriptor: Descriptor, + key_checker: _ValueChecker[_K], + entry_descriptor: Descriptor, + ) -> None: ... + def __getitem__(self, key: _K) -> _MessageV: ... + def get_or_create(self, key: _K) -> _MessageV: ... + + @overload + def get(self, key: _K, default: None = None) -> _MessageV | None: ... + @overload + def get(self, key: _K, default: _MessageV) -> _MessageV: ... + @overload + def get(self, key: _K, default: _T) -> _MessageV | _T: ... + + def __setitem__(self, key: _K, value: _MessageV) -> None: ... + def __delitem__(self, key: _K) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_K]: ... def __eq__(self, other: object) -> bool: ... - def get_or_create(self, key: _K) -> _MessageV: ... - def MergeFrom(self: _M, other: _M): ... + def setdefault(self, key: _K, value: _MessageV | None = None) -> _MessageV: ... + def MergeFrom(self, other: MessageMap[_K, _MessageV]) -> None: ... def InvalidateIterators(self) -> None: ... + def clear(self) -> None: ... def GetEntryClass(self) -> GeneratedProtocolMessageType: ... + +class UnknownFieldRef: + def __init__(self, parent: UnknownFieldSet, index: int) -> None: ... + @property + def field_number(self) -> int: ... + @property + def wire_type(self) -> int: ... + @property + def data(self) -> Any: ... # Any: int, bytes, or UnknownFieldSet + +class UnknownFieldSet: + __slots__ = ["_values"] + def __init__(self) -> None: ... + def __getitem__(self, index: int) -> UnknownFieldRef: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[UnknownFieldRef]: ... diff --git a/stubs/protobuf/google/protobuf/internal/decoder.pyi b/stubs/protobuf/google/protobuf/internal/decoder.pyi index 24774ee286eb..0aabd9ae1acc 100644 --- a/stubs/protobuf/google/protobuf/internal/decoder.pyi +++ b/stubs/protobuf/google/protobuf/internal/decoder.pyi @@ -1,30 +1,156 @@ -from typing import Any +from collections.abc import Callable +from typing import Any, TypeAlias -def ReadTag(buffer, pos): ... -def EnumDecoder(field_number, is_repeated, is_packed, key, new_default): ... +from google.protobuf.descriptor import Descriptor, FieldDescriptor +from google.protobuf.message import Message -Int32Decoder: Any -Int64Decoder: Any -UInt32Decoder: Any -UInt64Decoder: Any -SInt32Decoder: Any -SInt64Decoder: Any -Fixed32Decoder: Any -Fixed64Decoder: Any -SFixed32Decoder: Any -SFixed64Decoder: Any -FloatDecoder: Any -DoubleDecoder: Any -BoolDecoder: Any +_Decoder: TypeAlias = Callable[[memoryview, int, int, Message, dict[FieldDescriptor, Any]], int] +_NewDefault: TypeAlias = Callable[[Message], Any] -def StringDecoder(field_number, is_repeated, is_packed, key, new_default): ... -def BytesDecoder(field_number, is_repeated, is_packed, key, new_default): ... -def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): ... -def MessageDecoder(field_number, is_repeated, is_packed, key, new_default): ... +def IsDefaultScalarValue(value: Any) -> bool: ... +def ReadTag(buffer: memoryview, pos: int) -> tuple[bytes, int]: ... +def DecodeTag(tag_bytes: bytes) -> tuple[int, int]: ... +def EnumDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def Int32Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def Int64Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def UInt32Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def UInt64Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def SInt32Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def SInt64Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def Fixed32Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def Fixed64Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def SFixed32Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def SFixed64Decoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def FloatDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def DoubleDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def BoolDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def StringDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def BytesDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def GroupDecoder( + field_number: int, is_repeated: bool, is_packed: bool, key: FieldDescriptor, new_default: _NewDefault +) -> _Decoder: ... +def MessageDecoder( + field_number: int, is_repeated: bool, is_packed: bool, key: FieldDescriptor, new_default: _NewDefault +) -> _Decoder: ... -MESSAGE_SET_ITEM_TAG: Any +MESSAGE_SET_ITEM_TAG: bytes -def MessageSetItemDecoder(extensions_by_number): ... -def MapDecoder(field_descriptor, new_default, is_message_map): ... +def MessageSetItemDecoder(descriptor: Descriptor) -> _Decoder: ... +def UnknownMessageSetItemDecoder() -> _Decoder: ... +def MapDecoder(field_descriptor: FieldDescriptor, new_default: _NewDefault, is_message_map: bool) -> _Decoder: ... -SkipField: Any +DEFAULT_RECURSION_LIMIT: int + +def SetRecursionLimit(new_limit: int) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/encoder.pyi b/stubs/protobuf/google/protobuf/internal/encoder.pyi index 7a7923fe5d4b..958de8f3f86f 100644 --- a/stubs/protobuf/google/protobuf/internal/encoder.pyi +++ b/stubs/protobuf/google/protobuf/internal/encoder.pyi @@ -1,34 +1,52 @@ -from typing import Any +from collections.abc import Callable +from typing import TypeAlias -Int32Sizer: Any -UInt32Sizer: Any -SInt32Sizer: Any -Fixed32Sizer: Any -Fixed64Sizer: Any -BoolSizer: Any +from google.protobuf.descriptor import FieldDescriptor -def StringSizer(field_number, is_repeated, is_packed): ... -def BytesSizer(field_number, is_repeated, is_packed): ... -def GroupSizer(field_number, is_repeated, is_packed): ... -def MessageSizer(field_number, is_repeated, is_packed): ... -def MessageSetItemSizer(field_number): ... -def MapSizer(field_descriptor): ... -def TagBytes(field_number, wire_type): ... +_Sizer: TypeAlias = Callable[[int, bool, bool], int] -Int32Encoder: Any -UInt32Encoder: Any -SInt32Encoder: Any -Fixed32Encoder: Any -Fixed64Encoder: Any -SFixed32Encoder: Any -SFixed64Encoder: Any -FloatEncoder: Any -DoubleEncoder: Any +Int32Sizer: _Sizer +Int64Sizer: _Sizer +EnumSizer: _Sizer +UInt32Sizer: _Sizer +UInt64Sizer: _Sizer +SInt32Sizer: _Sizer +SInt64Sizer: _Sizer +Fixed32Sizer: _Sizer +SFixed32Sizer: _Sizer +FloatSizer: _Sizer +Fixed64Sizer: _Sizer +SFixed64Sizer: _Sizer +DoubleSizer: _Sizer +BoolSizer: _Sizer -def BoolEncoder(field_number, is_repeated, is_packed): ... -def StringEncoder(field_number, is_repeated, is_packed): ... -def BytesEncoder(field_number, is_repeated, is_packed): ... -def GroupEncoder(field_number, is_repeated, is_packed): ... -def MessageEncoder(field_number, is_repeated, is_packed): ... -def MessageSetItemEncoder(field_number): ... -def MapEncoder(field_descriptor): ... +def StringSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def BytesSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def GroupSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def MessageSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def MessageSetItemSizer(field_number: int) -> _Sizer: ... +def MapSizer(field_descriptor: FieldDescriptor, is_message_map: bool) -> _Sizer: ... +def TagBytes(field_number: int, wire_type: int) -> bytes: ... + +_Encoder: TypeAlias = Callable[[Callable[[bytes], int], bytes, bool], int] + +def Int32Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def Int64Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def EnumEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def UInt32Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def UInt64Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def SInt32Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def SInt64Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def Fixed32Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def Fixed64Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def SFixed32Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def SFixed64Encoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def FloatEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def DoubleEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def BoolEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def StringEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def BytesEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def GroupEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def MessageEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def MessageSetItemEncoder(field_number: int) -> _Encoder: ... +def MapEncoder(field_descriptor: FieldDescriptor) -> _Encoder: ... diff --git a/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi b/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi index f85bb54bb817..6573a8262a81 100644 --- a/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi +++ b/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi @@ -1,4 +1,4 @@ -from typing import Generic, List, Text, Tuple, TypeVar +from typing import Generic, TypeVar, type_check_only from google.protobuf.descriptor import EnumDescriptor @@ -6,13 +6,18 @@ _V = TypeVar("_V", bound=int) # Expose a generic version so that those using mypy-protobuf # can get autogenerated NewType wrapper around the int values -class _EnumTypeWrapper(Generic[_V]): +# NOTE: this doesn't actually inherit from type, +# but mypy doesn't support metaclasses that don't inherit from type, +# so we pretend it does in the stubs... +@type_check_only +class _EnumTypeWrapper(type, Generic[_V]): DESCRIPTOR: EnumDescriptor def __init__(self, enum_type: EnumDescriptor) -> None: ... def Name(self, number: _V) -> str: ... - def Value(self, name: Text | bytes) -> _V: ... - def keys(self) -> List[str]: ... - def values(self) -> List[_V]: ... - def items(self) -> List[Tuple[str, _V]]: ... + def Value(self, name: str | bytes) -> _V: ... + def keys(self) -> list[str]: ... + def values(self) -> list[_V]: ... + def items(self) -> list[tuple[str, _V]]: ... -class EnumTypeWrapper(_EnumTypeWrapper[int]): ... +class EnumTypeWrapper(_EnumTypeWrapper[int]): + ValueType = int diff --git a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi index 486e367eaa15..f2a4c1290a8e 100644 --- a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi +++ b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi @@ -1,4 +1,5 @@ -from typing import Any, Generic, Iterator, Text, TypeVar, Union +from collections.abc import Iterator +from typing import Any, Generic, TypeVar, type_check_only from google.protobuf.descriptor import FieldDescriptor from google.protobuf.internal.containers import RepeatedCompositeFieldContainer, RepeatedScalarFieldContainer @@ -7,9 +8,10 @@ from google.protobuf.message import Message _ContainerMessageT = TypeVar("_ContainerMessageT", bound=Message) _ExtenderMessageT = TypeVar( "_ExtenderMessageT", - bound=Union[Message, RepeatedScalarFieldContainer[Any], RepeatedCompositeFieldContainer[Any], bool, int, float, Text, bytes], + bound=Message | RepeatedScalarFieldContainer[Any] | RepeatedCompositeFieldContainer[Any] | bool | float | str | bytes, ) +@type_check_only class _ExtensionFieldDescriptor(FieldDescriptor, Generic[_ContainerMessageT, _ExtenderMessageT]): ... class _ExtensionDict(Generic[_ContainerMessageT]): @@ -17,10 +19,10 @@ class _ExtensionDict(Generic[_ContainerMessageT]): def __getitem__( self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT] ) -> _ExtenderMessageT: ... + def __len__(self) -> int: ... def __setitem__( self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT], value: _ExtenderMessageT ) -> None: ... def __delitem__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> None: ... - def __contains__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> bool: ... def __iter__(self) -> Iterator[_ExtensionFieldDescriptor[_ContainerMessageT, Any]]: ... - def __len__(self) -> int: ... + def __contains__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> bool: ... diff --git a/stubs/protobuf/google/protobuf/internal/field_mask.pyi b/stubs/protobuf/google/protobuf/internal/field_mask.pyi new file mode 100644 index 000000000000..bd0c7f9aef77 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/field_mask.pyi @@ -0,0 +1,14 @@ +from google.protobuf.descriptor import Descriptor, FieldDescriptor as FieldDescriptor +from google.protobuf.message import Message + +class FieldMask: + def ToJsonString(self) -> str: ... + def FromJsonString(self, value: str) -> None: ... + def IsValidForDescriptor(self, message_descriptor: Descriptor) -> bool: ... + def AllFieldsFromDescriptor(self, message_descriptor: Descriptor) -> None: ... + def CanonicalFormFromMask(self, mask: FieldMask) -> None: ... + def Union(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def Intersect(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def MergeMessage( + self, source: Message, destination: Message, replace_message_field: bool = False, replace_repeated_field: bool = False + ) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/message_listener.pyi b/stubs/protobuf/google/protobuf/internal/message_listener.pyi index e8d33a5a1a47..c1c9d3632b4f 100644 --- a/stubs/protobuf/google/protobuf/internal/message_listener.pyi +++ b/stubs/protobuf/google/protobuf/internal/message_listener.pyi @@ -1,5 +1,5 @@ -class MessageListener(object): +class MessageListener: def Modified(self) -> None: ... -class NullMessageListener(MessageListener): +class NullMessageListener: def Modified(self) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/python_edition_defaults.pyi b/stubs/protobuf/google/protobuf/internal/python_edition_defaults.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/protobuf/google/protobuf/internal/python_message.pyi b/stubs/protobuf/google/protobuf/internal/python_message.pyi index 538d70b447ef..2b37dda98989 100644 --- a/stubs/protobuf/google/protobuf/internal/python_message.pyi +++ b/stubs/protobuf/google/protobuf/internal/python_message.pyi @@ -1 +1,5 @@ -class GeneratedProtocolMessageType(type): ... +from typing import Any + +class GeneratedProtocolMessageType(type): + def __new__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> GeneratedProtocolMessageType: ... + def __init__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi b/stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi new file mode 100644 index 000000000000..f77663b566b6 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi @@ -0,0 +1,21 @@ +from _typeshed import OptExcInfo +from collections.abc import Callable +from typing import TypeVar +from unittest import TestCase as _TestCase, TestResult + +_T = TypeVar("_T") + +class LocalTestResult(TestResult): + parent_result: TestResult + def __init__(self, parent_result: TestResult) -> None: ... + def addError(self, test: _TestCase, error: OptExcInfo) -> None: ... + def addFailure(self, test: _TestCase, error: OptExcInfo) -> None: ... + def addSkip(self, test: _TestCase, reason: str) -> None: ... + def addDuration(self, test: _TestCase, duration: float) -> None: ... + +class ReferenceLeakCheckerMixin: + NB_RUNS: int + def run(self, result: TestResult | None = None) -> TestResult: ... + +def SkipReferenceLeakChecker(reason: str) -> Callable[[_T], _T]: ... +def TestCase(test_class: _T) -> _T: ... diff --git a/stubs/protobuf/google/protobuf/internal/type_checkers.pyi b/stubs/protobuf/google/protobuf/internal/type_checkers.pyi new file mode 100644 index 000000000000..6486de0124b5 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/type_checkers.pyi @@ -0,0 +1,55 @@ +from collections.abc import Callable +from typing import Any, Generic, TypeVar + +from google.protobuf.descriptor import EnumDescriptor, FieldDescriptor + +_T = TypeVar("_T") + +def TruncateToFourByteFloat(original: float) -> float: ... +def ToShortestFloat(original: float) -> float: ... +def GetTypeChecker( + field: FieldDescriptor, +) -> TypeChecker[Any] | IntValueChecker | EnumValueChecker | UnicodeValueChecker | DoubleValueChecker | BoolValueChecker: ... + +class TypeChecker(Generic[_T]): + def __init__(self, *acceptable_types: _T): ... + def CheckValue(self, proposed_value: _T) -> _T: ... + +class TypeCheckerWithDefault(TypeChecker[_T]): + def __init__(self, default_value: _T, *acceptable_types: _T): ... + def DefaultValue(self) -> _T: ... + +class BoolValueChecker: + def CheckValue(self, proposed_value: bool) -> bool: ... + def DefaultValue(self) -> bool: ... + +class IntValueChecker: + def CheckValue(self, proposed_value: int) -> int: ... + def DefaultValue(self) -> int: ... + +class EnumValueChecker: + def __init__(self, enum_type: EnumDescriptor) -> None: ... + def CheckValue(self, proposed_value: int) -> int: ... + def DefaultValue(self) -> int: ... + +class UnicodeValueChecker: + def CheckValue(self, proposed_value: str) -> str: ... + def DefaultValue(self) -> str: ... + +class Int32ValueChecker(IntValueChecker): ... +class Uint32ValueChecker(IntValueChecker): ... +class Int64ValueChecker(IntValueChecker): ... +class Uint64ValueChecker(IntValueChecker): ... + +class DoubleValueChecker: + def CheckValue(self, proposed_value: float) -> float: ... + def DefaultValue(self) -> float: ... + +class FloatValueChecker(DoubleValueChecker): + def CheckValue(self, proposed_value: float) -> float: ... + +TYPE_TO_BYTE_SIZE_FN: dict[int, Callable[..., int]] +TYPE_TO_ENCODER: dict[int, Callable[..., Any]] +TYPE_TO_SIZER: dict[int, Callable[..., Any]] +TYPE_TO_DECODER: dict[int, Callable[..., Any]] +FIELD_TYPE_TO_WIRE_TYPE: dict[int, int] diff --git a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi index 6b6b95a197cf..6324155b8568 100644 --- a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi +++ b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi @@ -1,21 +1,26 @@ -from datetime import datetime, timedelta -from typing import Any as tAny, Dict, Optional, Type +from _typeshed import SupportsItems +from collections.abc import Iterable, Iterator, KeysView, Mapping, Sequence +from datetime import datetime, timedelta, tzinfo +from typing import Any as tAny, TypeAlias -class Error(Exception): ... -class ParseError(Error): ... +from google.protobuf import struct_pb2 +from google.protobuf.descriptor import Descriptor +from google.protobuf.message import Message as _Message class Any: - type_url: tAny = ... - value: tAny = ... - def Pack(self, msg: tAny, type_url_prefix: bytes = ..., deterministic: Optional[tAny] = ...) -> None: ... - def Unpack(self, msg: tAny): ... - def TypeName(self): ... - def Is(self, descriptor: tAny): ... + __slots__ = () + type_url: str + value: bytes + def Pack(self, msg: _Message, type_url_prefix: str = "type.googleapis.com/", deterministic: bool | None = None) -> None: ... + def Unpack(self, msg: _Message) -> bool: ... + def TypeName(self) -> str: ... + def Is(self, descriptor: Descriptor) -> bool: ... class Timestamp: + __slots__ = () def ToJsonString(self) -> str: ... - seconds: int = ... - nanos: int = ... + seconds: int + nanos: int def FromJsonString(self, value: str) -> None: ... def GetCurrentTime(self) -> None: ... def ToNanoseconds(self) -> int: ... @@ -26,14 +31,19 @@ class Timestamp: def FromMicroseconds(self, micros: int) -> None: ... def FromMilliseconds(self, millis: int) -> None: ... def FromSeconds(self, seconds: int) -> None: ... - def ToDatetime(self) -> datetime: ... + def ToDatetime(self, tzinfo: tzinfo | None = None) -> datetime: ... def FromDatetime(self, dt: datetime) -> None: ... + def __add__(self, value: Duration | timedelta) -> datetime: ... + def __radd__(self, value: tAny) -> datetime: ... + def __sub__(self, value: Timestamp | Duration | timedelta) -> datetime | timedelta: ... + def __rsub__(self, dt: datetime) -> timedelta: ... class Duration: + __slots__ = () def ToJsonString(self) -> str: ... - seconds: int = ... - nanos: int = ... - def FromJsonString(self, value: tAny) -> None: ... + seconds: int + nanos: int + def FromJsonString(self, value: str) -> None: ... def ToNanoseconds(self) -> int: ... def ToMicroseconds(self) -> int: ... def ToMilliseconds(self) -> int: ... @@ -44,51 +54,53 @@ class Duration: def FromSeconds(self, seconds: int) -> None: ... def ToTimedelta(self) -> timedelta: ... def FromTimedelta(self, td: timedelta) -> None: ... + def __add__(self, value: Timestamp | timedelta) -> datetime | timedelta: ... + def __radd__(self, value: tAny) -> datetime | timedelta: ... + def __sub__(self, value: Duration | timedelta) -> timedelta: ... + def __rsub__(self, value: datetime | timedelta) -> datetime | timedelta: ... class FieldMask: + __slots__ = () def ToJsonString(self) -> str: ... - def FromJsonString(self, value: tAny) -> None: ... - def IsValidForDescriptor(self, message_descriptor: tAny): ... - def AllFieldsFromDescriptor(self, message_descriptor: tAny) -> None: ... - def CanonicalFormFromMask(self, mask: tAny) -> None: ... - def Union(self, mask1: tAny, mask2: tAny) -> None: ... - def Intersect(self, mask1: tAny, mask2: tAny) -> None: ... + def FromJsonString(self, value: str) -> None: ... + def IsValidForDescriptor(self, message_descriptor: Descriptor) -> bool: ... + def AllFieldsFromDescriptor(self, message_descriptor: Descriptor) -> None: ... + def CanonicalFormFromMask(self, mask: FieldMask) -> None: ... + def Union(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def Intersect(self, mask1: FieldMask, mask2: FieldMask) -> None: ... def MergeMessage( - self, source: tAny, destination: tAny, replace_message_field: bool = ..., replace_repeated_field: bool = ... + self, source: _Message, destination: _Message, replace_message_field: bool = False, replace_repeated_field: bool = False ) -> None: ... -class _FieldMaskTree: - def __init__(self, field_mask: Optional[tAny] = ...) -> None: ... - def MergeFromFieldMask(self, field_mask: tAny) -> None: ... - def AddPath(self, path: tAny): ... - def ToFieldMask(self, field_mask: tAny) -> None: ... - def IntersectPath(self, path: tAny, intersection: tAny): ... - def AddLeafNodes(self, prefix: tAny, node: tAny) -> None: ... - def MergeMessage(self, source: tAny, destination: tAny, replace_message: tAny, replace_repeated: tAny) -> None: ... +_StructValue: TypeAlias = struct_pb2.Struct | struct_pb2.ListValue | str | float | bool | None +_StructValueArg: TypeAlias = _StructValue | Mapping[str, _StructValueArg] | Sequence[_StructValueArg] class Struct: - def __getitem__(self, key: tAny): ... - def __contains__(self, item: tAny): ... - def __setitem__(self, key: tAny, value: tAny) -> None: ... - def __delitem__(self, key: tAny) -> None: ... - def __len__(self): ... - def __iter__(self): ... - def keys(self): ... - def values(self): ... - def items(self): ... - def get_or_create_list(self, key: tAny): ... - def get_or_create_struct(self, key: tAny): ... - def update(self, dictionary: tAny) -> None: ... + __slots__: tuple[str, ...] = () + def __getitem__(self, key: str) -> _StructValue: ... + def __setitem__(self, key: str, value: _StructValueArg) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> list[_StructValue]: ... + def items(self) -> list[tuple[str, _StructValue]]: ... + def get_or_create_list(self, key: str) -> struct_pb2.ListValue: ... + def get_or_create_struct(self, key: str) -> struct_pb2.Struct: ... + def update(self, dictionary: SupportsItems[str, _StructValueArg]) -> None: ... class ListValue: - def __len__(self): ... - def append(self, value: tAny) -> None: ... - def extend(self, elem_seq: tAny) -> None: ... - def __getitem__(self, index: tAny): ... - def __setitem__(self, index: tAny, value: tAny) -> None: ... - def __delitem__(self, key: tAny) -> None: ... - def items(self) -> None: ... - def add_struct(self): ... - def add_list(self): ... + __slots__: tuple[str, ...] = () + def __len__(self) -> int: ... + def append(self, value: _StructValue) -> None: ... + def extend(self, elem_seq: Iterable[_StructValue]) -> None: ... + def __getitem__(self, index: int) -> _StructValue: ... + def __setitem__(self, index: int, value: _StructValueArg) -> None: ... + def __delitem__(self, key: int) -> None: ... + # Doesn't actually exist at runtime; needed so type checkers understand the class is iterable + def __iter__(self) -> Iterator[_StructValue]: ... + def items(self) -> Iterator[_StructValue]: ... + def add_struct(self) -> struct_pb2.Struct: ... + def add_list(self) -> struct_pb2.ListValue: ... -WKTBASES: Dict[str, Type[tAny]] +WKTBASES: dict[str, type[tAny]] diff --git a/stubs/protobuf/google/protobuf/internal/wire_format.pyi b/stubs/protobuf/google/protobuf/internal/wire_format.pyi index 3dcbd04324ed..0d4aa04031ec 100644 --- a/stubs/protobuf/google/protobuf/internal/wire_format.pyi +++ b/stubs/protobuf/google/protobuf/internal/wire_format.pyi @@ -1,50 +1,50 @@ -from typing import Any +from google.protobuf.message import Message -TAG_TYPE_BITS: Any -TAG_TYPE_MASK: Any -WIRETYPE_VARINT: Any -WIRETYPE_FIXED64: Any -WIRETYPE_LENGTH_DELIMITED: Any -WIRETYPE_START_GROUP: Any -WIRETYPE_END_GROUP: Any -WIRETYPE_FIXED32: Any -INT32_MAX: Any -INT32_MIN: Any -UINT32_MAX: Any -INT64_MAX: Any -INT64_MIN: Any -UINT64_MAX: Any -FORMAT_UINT32_LITTLE_ENDIAN: Any -FORMAT_UINT64_LITTLE_ENDIAN: Any -FORMAT_FLOAT_LITTLE_ENDIAN: Any -FORMAT_DOUBLE_LITTLE_ENDIAN: Any +TAG_TYPE_BITS: int +TAG_TYPE_MASK: int +WIRETYPE_VARINT: int +WIRETYPE_FIXED64: int +WIRETYPE_LENGTH_DELIMITED: int +WIRETYPE_START_GROUP: int +WIRETYPE_END_GROUP: int +WIRETYPE_FIXED32: int +INT32_MAX: int +INT32_MIN: int +UINT32_MAX: int +INT64_MAX: int +INT64_MIN: int +UINT64_MAX: int +FORMAT_UINT32_LITTLE_ENDIAN: str +FORMAT_UINT64_LITTLE_ENDIAN: str +FORMAT_FLOAT_LITTLE_ENDIAN: str +FORMAT_DOUBLE_LITTLE_ENDIAN: str -def PackTag(field_number, wire_type): ... -def UnpackTag(tag): ... -def ZigZagEncode(value): ... -def ZigZagDecode(value): ... -def Int32ByteSize(field_number, int32): ... -def Int32ByteSizeNoTag(int32): ... -def Int64ByteSize(field_number, int64): ... -def UInt32ByteSize(field_number, uint32): ... -def UInt64ByteSize(field_number, uint64): ... -def SInt32ByteSize(field_number, int32): ... -def SInt64ByteSize(field_number, int64): ... -def Fixed32ByteSize(field_number, fixed32): ... -def Fixed64ByteSize(field_number, fixed64): ... -def SFixed32ByteSize(field_number, sfixed32): ... -def SFixed64ByteSize(field_number, sfixed64): ... -def FloatByteSize(field_number, flt): ... -def DoubleByteSize(field_number, double): ... -def BoolByteSize(field_number, b): ... -def EnumByteSize(field_number, enum): ... -def StringByteSize(field_number, string): ... -def BytesByteSize(field_number, b): ... -def GroupByteSize(field_number, message): ... -def MessageByteSize(field_number, message): ... -def MessageSetItemByteSize(field_number, msg): ... -def TagByteSize(field_number): ... +def PackTag(field_number: int, wire_type: int) -> int: ... +def UnpackTag(tag: int) -> tuple[int, int]: ... +def ZigZagEncode(value: int) -> int: ... +def ZigZagDecode(value: int) -> int: ... +def Int32ByteSize(field_number: int, int32: int) -> int: ... +def Int32ByteSizeNoTag(int32: int) -> int: ... +def Int64ByteSize(field_number: int, int64: int) -> int: ... +def UInt32ByteSize(field_number: int, uint32: int) -> int: ... +def UInt64ByteSize(field_number: int, uint64: int) -> int: ... +def SInt32ByteSize(field_number: int, int32: int) -> int: ... +def SInt64ByteSize(field_number: int, int64: int) -> int: ... +def Fixed32ByteSize(field_number: int, fixed32: int) -> int: ... +def Fixed64ByteSize(field_number: int, fixed64: int) -> int: ... +def SFixed32ByteSize(field_number: int, sfixed32: int) -> int: ... +def SFixed64ByteSize(field_number: int, sfixed64: int) -> int: ... +def FloatByteSize(field_number: int, flt: float) -> int: ... +def DoubleByteSize(field_number: int, double: float) -> int: ... +def BoolByteSize(field_number: int, b: bool) -> int: ... +def EnumByteSize(field_number: int, enum: int) -> int: ... +def StringByteSize(field_number: int, string: str) -> int: ... +def BytesByteSize(field_number: int, b: bytes) -> int: ... +def GroupByteSize(field_number: int, message: Message) -> int: ... +def MessageByteSize(field_number: int, message: Message) -> int: ... +def MessageSetItemByteSize(field_number: int, msg: Message) -> int: ... +def TagByteSize(field_number: int) -> int: ... -NON_PACKABLE_TYPES: Any +NON_PACKABLE_TYPES: tuple[int, ...] -def IsTypePackable(field_type): ... +def IsTypePackable(field_type: int) -> bool: ... diff --git a/stubs/protobuf/google/protobuf/json_format.pyi b/stubs/protobuf/google/protobuf/json_format.pyi index 75fda13431a6..0ff2c79ccd07 100644 --- a/stubs/protobuf/google/protobuf/json_format.pyi +++ b/stubs/protobuf/google/protobuf/json_format.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, Optional, Text, TypeVar, Union +from typing import Any, TypeVar from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.message import Message @@ -6,33 +6,42 @@ from google.protobuf.message import Message _MessageT = TypeVar("_MessageT", bound=Message) class Error(Exception): ... -class ParseError(Error): ... class SerializeToJsonError(Error): ... +class ParseError(Error): ... +class EnumStringValueParseError(ParseError): ... def MessageToJson( message: Message, - including_default_value_fields: bool = ..., - preserving_proto_field_name: bool = ..., - indent: int = ..., - sort_keys: bool = ..., - use_integers_for_enums: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - float_precision: Optional[int] = ..., + preserving_proto_field_name: bool = False, + indent: int | None = 2, + sort_keys: bool = False, + use_integers_for_enums: bool = False, + descriptor_pool: DescriptorPool | None = None, + ensure_ascii: bool = True, + always_print_fields_with_no_presence: bool = False, + *, + unquote_int64_if_possible: bool = False, ) -> str: ... def MessageToDict( message: Message, - including_default_value_fields: bool = ..., - preserving_proto_field_name: bool = ..., - use_integers_for_enums: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - float_precision: Optional[int] = ..., -) -> Dict[Text, Any]: ... + always_print_fields_with_no_presence: bool = False, + preserving_proto_field_name: bool = False, + use_integers_for_enums: bool = False, + descriptor_pool: DescriptorPool | None = None, + *, + unquote_int64_if_possible: bool = False, +) -> dict[str, Any]: ... def Parse( - text: Union[bytes, Text], + text: bytes | str, message: _MessageT, - ignore_unknown_fields: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + ignore_unknown_fields: bool = False, + descriptor_pool: DescriptorPool | None = None, + max_recursion_depth: int = 100, ) -> _MessageT: ... def ParseDict( - js_dict: Any, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: Optional[DescriptorPool] = ... + js_dict: dict[str, Any], + message: _MessageT, + ignore_unknown_fields: bool = False, + descriptor_pool: DescriptorPool | None = None, + max_recursion_depth: int = 100, ) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/message.pyi b/stubs/protobuf/google/protobuf/message.pyi index 8d63932e1621..bca40ddb4667 100644 --- a/stubs/protobuf/google/protobuf/message.pyi +++ b/stubs/protobuf/google/protobuf/message.pyi @@ -1,5 +1,8 @@ -import sys -from typing import Any, ByteString, Sequence, Tuple, Type, TypeVar, Union +from collections.abc import Sequence +from typing import Any +from typing_extensions import Self + +from google._upb._message import Descriptor as _upb_Descriptor from .descriptor import Descriptor, FieldDescriptor from .internal.extension_dict import _ExtensionDict, _ExtensionFieldDescriptor @@ -8,35 +11,23 @@ class Error(Exception): ... class DecodeError(Error): ... class EncodeError(Error): ... -_M = TypeVar("_M", bound=Message) # message type (of self) - -if sys.version_info >= (3, 0): - _Serialized = ByteString -else: - _Serialized = Union[bytes, buffer, unicode] - class Message: - DESCRIPTOR: Descriptor - def __deepcopy__(self, memo=...): ... - def __eq__(self, other_msg): ... - def __ne__(self, other_msg): ... - def MergeFrom(self: _M, other_msg: _M) -> None: ... - def CopyFrom(self: _M, other_msg: _M) -> None: ... + __slots__: tuple[str, ...] = () + DESCRIPTOR: Descriptor | _upb_Descriptor + def __deepcopy__(self, memo: Any = None) -> Self: ... + def __eq__(self, other_msg: object) -> bool: ... + def __ne__(self, other_msg: object) -> bool: ... + def __contains__(self, field_name_or_key: str) -> bool: ... + def MergeFrom(self, other_msg: Self) -> None: ... + def CopyFrom(self, other_msg: Self) -> None: ... def Clear(self) -> None: ... def SetInParent(self) -> None: ... def IsInitialized(self) -> bool: ... - def MergeFromString(self, serialized: _Serialized) -> int: ... - def ParseFromString(self, serialized: _Serialized) -> int: ... - def SerializeToString(self, deterministic: bool = ...) -> bytes: ... - def SerializePartialToString(self, deterministic: bool = ...) -> bytes: ... - def ListFields(self) -> Sequence[Tuple[FieldDescriptor, Any]]: ... - def HasExtension(self: _M, extension_handle: _ExtensionFieldDescriptor[_M, Any]) -> bool: ... - def ClearExtension(self: _M, extension_handle: _ExtensionFieldDescriptor[_M, Any]) -> None: ... - def ByteSize(self) -> int: ... - @classmethod - def FromString(cls: Type[_M], s: _Serialized) -> _M: ... - @property - def Extensions(self: _M) -> _ExtensionDict[_M]: ... + def MergeFromString(self, serialized: bytes) -> int: ... + def ParseFromString(self, serialized: bytes) -> int: ... + def SerializeToString(self, *, deterministic: bool = ...) -> bytes: ... + def SerializePartialToString(self, *, deterministic: bool = ...) -> bytes: ... + def ListFields(self) -> Sequence[tuple[FieldDescriptor, Any]]: ... # Any: str, int, float, bytes, bool, or Message # Intentionally left out typing on these three methods, because they are # stringly typed and it is not useful to call them on a Message directly. # We prefer more specific typing on individual subclasses of Message @@ -44,5 +35,15 @@ class Message: def HasField(self, field_name: Any) -> bool: ... def ClearField(self, field_name: Any) -> None: ... def WhichOneof(self, oneof_group: Any) -> Any: ... + def HasExtension(self, field_descriptor: _ExtensionFieldDescriptor[Self, Any]) -> bool: ... + def ClearExtension(self, field_descriptor: _ExtensionFieldDescriptor[Self, Any]) -> None: ... + # The TypeVar must be bound to `Message` or we get mypy errors, so we cannot use `Self` for `Extensions` + @property + def Extensions(self) -> _ExtensionDict[Self]: ... + def UnknownFields(self) -> Any: ... # Any: subclasses return UnknownFieldSet + def DiscardUnknownFields(self) -> None: ... + def ByteSize(self) -> int: ... + @classmethod + def FromString(cls, s: bytes) -> Self: ... # TODO: check kwargs - def __init__(self, **kwargs) -> None: ... + def __new__(cls, *args, **kwargs) -> Self: ... diff --git a/stubs/protobuf/google/protobuf/message_factory.pyi b/stubs/protobuf/google/protobuf/message_factory.pyi index d8a42d30bc65..8a902254d2d9 100644 --- a/stubs/protobuf/google/protobuf/message_factory.pyi +++ b/stubs/protobuf/google/protobuf/message_factory.pyi @@ -1,14 +1,15 @@ -from typing import Any, Dict, Iterable, Optional, Type +from collections.abc import Iterable from google.protobuf.descriptor import Descriptor from google.protobuf.descriptor_pb2 import FileDescriptorProto from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.message import Message +def GetMessageClass(descriptor: Descriptor) -> type[Message]: ... +def GetMessageClassesForFiles(files: Iterable[str], pool: DescriptorPool) -> dict[str, type[Message]]: ... + class MessageFactory: - pool: Any - def __init__(self, pool: Optional[DescriptorPool] = ...) -> None: ... - def GetPrototype(self, descriptor: Descriptor) -> Type[Message]: ... - def GetMessages(self, files: Iterable[str]) -> Dict[str, Type[Message]]: ... + pool: DescriptorPool + def __init__(self, pool: DescriptorPool | None = None) -> None: ... -def GetMessages(file_protos: Iterable[FileDescriptorProto]) -> Dict[str, Type[Message]]: ... +def GetMessages(file_protos: Iterable[FileDescriptorProto], pool: DescriptorPool | None = None) -> dict[str, type[Message]]: ... diff --git a/stubs/protobuf/google/protobuf/proto.pyi b/stubs/protobuf/google/protobuf/proto.pyi new file mode 100644 index 000000000000..1f1cb47037cc --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto.pyi @@ -0,0 +1,14 @@ +from io import BytesIO +from typing import TypeVar + +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +def serialize(message: Message, deterministic: bool | None = None) -> bytes: ... +def parse(message_class: type[_MessageT], payload: bytes) -> _MessageT: ... +def serialize_length_prefixed(message: Message, output: BytesIO) -> None: ... +def parse_length_prefixed(message_class: type[_MessageT], input_bytes: BytesIO) -> _MessageT: ... +def byte_size(message: Message) -> int: ... +def clear_message(message: Message) -> None: ... +def clear_field(message: Message, field_name: str) -> None: ... diff --git a/stubs/protobuf/google/protobuf/proto_builder.pyi b/stubs/protobuf/google/protobuf/proto_builder.pyi new file mode 100644 index 000000000000..b204ba32eb69 --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto_builder.pyi @@ -0,0 +1,8 @@ +from collections import OrderedDict + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +def MakeSimpleProtoClass( + fields: dict[str, int] | OrderedDict[str, int], full_name: str | None = None, pool: DescriptorPool | None = None +) -> type[Message]: ... diff --git a/stubs/protobuf/google/protobuf/proto_json.pyi b/stubs/protobuf/google/protobuf/proto_json.pyi new file mode 100644 index 000000000000..9a63de676bb1 --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto_json.pyi @@ -0,0 +1,21 @@ +from typing import Any, TypeVar + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +def serialize( + message: Message, + always_print_fields_with_no_presence: bool = False, + preserving_proto_field_name: bool = False, + use_integers_for_enums: bool = False, + descriptor_pool: DescriptorPool | None = None, +) -> dict[str, Any]: ... +def parse( + message_class: type[_MessageT], + js_dict: dict[str, Any], + ignore_unknown_fields: bool = False, + descriptor_pool: DescriptorPool | None = None, + max_recursion_depth: int = 100, +) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/proto_text.pyi b/stubs/protobuf/google/protobuf/proto_text.pyi new file mode 100644 index 000000000000..7ddff9c19e89 --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto_text.pyi @@ -0,0 +1,31 @@ +from collections.abc import Callable +from typing import TypeAlias, TypeVar + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) +_MsgFormatter: TypeAlias = Callable[[Message, int, bool], str | None] + +def serialize( + message: Message, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + indent: int = 0, + message_formatter: _MsgFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> str: ... +def parse( + message_class: type[_MessageT], + text: str | bytes, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, +) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/reflection.pyi b/stubs/protobuf/google/protobuf/reflection.pyi index 3ca50552a896..0c700523e712 100644 --- a/stubs/protobuf/google/protobuf/reflection.pyi +++ b/stubs/protobuf/google/protobuf/reflection.pyi @@ -1,6 +1,10 @@ -class GeneratedProtocolMessageType(type): - def __new__(cls, name, bases, dictionary): ... - def __init__(self, name, bases, dictionary) -> None: ... +from typing import Any -def ParseMessage(descriptor, byte_str): ... -def MakeClass(descriptor): ... +from google._upb._message import MessageMeta + +MESSAGE_CLASS_CACHE: dict[str, Any] + +class GeneratedProtocolMessageType(MessageMeta): + def __new__( # noqa: Y034 + cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any] + ) -> GeneratedProtocolMessageType: ... diff --git a/stubs/protobuf/google/protobuf/runtime_version.pyi b/stubs/protobuf/google/protobuf/runtime_version.pyi new file mode 100644 index 000000000000..c6e1f8406216 --- /dev/null +++ b/stubs/protobuf/google/protobuf/runtime_version.pyi @@ -0,0 +1,23 @@ +from enum import Enum +from typing import Final + +class Domain(Enum): + GOOGLE_INTERNAL = 1 + PUBLIC = 2 + +OSS_DOMAIN: Final[Domain] +OSS_MAJOR: Final[int] +OSS_MINOR: Final[int] +OSS_PATCH: Final[int] +OSS_SUFFIX: Final[str] +DOMAIN: Final[Domain] +MAJOR: Final[int] +MINOR: Final[int] +PATCH: Final[int] +SUFFIX: Final[str] + +class VersionError(Exception): ... + +def ValidateProtobufRuntimeVersion( + gen_domain: Domain, gen_major: int, gen_minor: int, gen_patch: int, gen_suffix: str, location: str +) -> None: ... diff --git a/stubs/protobuf/google/protobuf/service.pyi b/stubs/protobuf/google/protobuf/service.pyi deleted file mode 100644 index 4874d5356ded..000000000000 --- a/stubs/protobuf/google/protobuf/service.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from concurrent.futures import Future -from typing import Callable, Optional, Text, Type - -from google.protobuf.descriptor import MethodDescriptor, ServiceDescriptor -from google.protobuf.message import Message - -class RpcException(Exception): ... - -class Service: - @staticmethod - def GetDescriptor() -> ServiceDescriptor: ... - def CallMethod( - self, - method_descriptor: MethodDescriptor, - rpc_controller: RpcController, - request: Message, - done: Optional[Callable[[Message], None]], - ) -> Optional[Future[Message]]: ... - def GetRequestClass(self, method_descriptor: MethodDescriptor) -> Type[Message]: ... - def GetResponseClass(self, method_descriptor: MethodDescriptor) -> Type[Message]: ... - -class RpcController: - def Reset(self) -> None: ... - def Failed(self) -> bool: ... - def ErrorText(self) -> Optional[Text]: ... - def StartCancel(self) -> None: ... - def SetFailed(self, reason: Text) -> None: ... - def IsCanceled(self) -> bool: ... - def NotifyOnCancel(self, callback: Callable[[], None]) -> None: ... - -class RpcChannel: - def CallMethod( - self, - method_descriptor: MethodDescriptor, - rpc_controller: RpcController, - request: Message, - response_class: Type[Message], - done: Optional[Callable[[Message], None]], - ) -> Optional[Future[Message]]: ... diff --git a/stubs/protobuf/google/protobuf/service_reflection.pyi b/stubs/protobuf/google/protobuf/service_reflection.pyi new file mode 100644 index 000000000000..c9949d13baca --- /dev/null +++ b/stubs/protobuf/google/protobuf/service_reflection.pyi @@ -0,0 +1,7 @@ +from typing import Any + +class GeneratedServiceType(type): + def __init__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> None: ... + +class GeneratedServiceStubType(GeneratedServiceType): + def __init__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> None: ... diff --git a/stubs/protobuf/google/protobuf/source_context_pb2.pyi b/stubs/protobuf/google/protobuf/source_context_pb2.pyi index 61c2e83e3215..9d74fb3d5926 100644 --- a/stubs/protobuf/google/protobuf/source_context_pb2.pyi +++ b/stubs/protobuf/google/protobuf/source_context_pb2.pyi @@ -1,29 +1,59 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import typing + import google.protobuf.descriptor import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class SourceContext(google.protobuf.message.Message): """`SourceContext` represents information about the source of a protobuf element, like the file in which it is defined. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + FILE_NAME_FIELD_NUMBER: builtins.int - file_name: typing.Text = ... + file_name: builtins.str """The path-qualified name of the .proto file that contained the associated protobuf element. For example: `"google/protobuf/source_context.proto"`. """ + def __init__(self, *, file_name: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["file_name", b"file_name"]) -> None: ... - def __init__(self, - *, - file_name : typing.Text = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["file_name",b"file_name"]) -> None: ... global___SourceContext = SourceContext diff --git a/stubs/protobuf/google/protobuf/struct_pb2.pyi b/stubs/protobuf/google/protobuf/struct_pb2.pyi index 54e8df72afba..deb905128c6d 100644 --- a/stubs/protobuf/google/protobuf/struct_pb2.pyi +++ b/stubs/protobuf/google/protobuf/struct_pb2.pyi @@ -1,140 +1,226 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import collections.abc +import sys +import typing + import google.protobuf.descriptor import google.protobuf.internal.containers import google.protobuf.internal.enum_type_wrapper import google.protobuf.internal.well_known_types import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions -class NullValue(_NullValue, metaclass=_NullValueEnumTypeWrapper): - """`NullValue` is a singleton enumeration to represent the null value for the - `Value` type union. +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor - The JSON representation for `NullValue` is JSON `null`. - """ - pass class _NullValue: - V = typing.NewType('V', builtins.int) -class _NullValueEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_NullValue.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - NULL_VALUE = NullValue.V(0) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _NullValueEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_NullValue.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NULL_VALUE: _NullValue.ValueType # 0 """Null value.""" +class NullValue(_NullValue, metaclass=_NullValueEnumTypeWrapper): + """Represents a JSON `null`. -NULL_VALUE = NullValue.V(0) -"""Null value.""" + `NullValue` is a sentinel, using an enum with only one value to represent + the null value for the `Value` type union. -global___NullValue = NullValue + A field of type `NullValue` with any value other than `0` is considered + invalid. Most ProtoJSON serializers will emit a Value with a `null_value` set + as a JSON `null` regardless of the integer value, and so will round trip to + a `0` value. + """ +NULL_VALUE: NullValue.ValueType # 0 +"""Null value.""" +global___NullValue = NullValue +@typing.final class Struct(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Struct): - """`Struct` represents a structured data value, consisting of fields - which map to dynamically typed values. In some languages, `Struct` - might be supported by a native representation. For example, in - scripting languages like JS a struct is represented as an - object. The details of that representation are described together - with the proto support for the language. - - The JSON representation for `Struct` is JSON object. + """Represents a JSON object. + + An unordered key-value map, intending to perfectly capture the semantics of a + JSON object. This enables parsing any arbitrary JSON payload as a message + field in ProtoJSON format. + + This follows RFC 8259 guidelines for interoperable JSON: notably this type + cannot represent large Int64 values or `NaN`/`Infinity` numbers, + since the JSON format generally does not support those values in its number + type. + + If you do not intend to parse arbitrary JSON into your message, a custom + typed message should be preferred instead of using this type. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final class FieldsEntry(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + DESCRIPTOR: google.protobuf.descriptor.Descriptor + KEY_FIELD_NUMBER: builtins.int VALUE_FIELD_NUMBER: builtins.int - key: typing.Text = ... + key: builtins.str @property def value(self) -> global___Value: ... - def __init__(self, - *, - key : typing.Text = ..., - value : typing.Optional[global___Value] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["value",b"value"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["key",b"key","value",b"value"]) -> None: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___Value | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... FIELDS_FIELD_NUMBER: builtins.int @property - def fields(self) -> google.protobuf.internal.containers.MessageMap[typing.Text, global___Value]: + def fields(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Value]: """Unordered map of dynamically typed values.""" - pass - def __init__(self, - *, - fields : typing.Optional[typing.Mapping[typing.Text, global___Value]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["fields",b"fields"]) -> None: ... + + def __init__(self, *, fields: collections.abc.Mapping[builtins.str, global___Value] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["fields", b"fields"]) -> None: ... + global___Struct = Struct +@typing.final class Value(google.protobuf.message.Message): - """`Value` represents a dynamically typed value which can be either - null, a number, a string, a boolean, a recursive struct value, or a - list of values. A producer of value is expected to set one of that - variants, absence of any variant indicates an error. + """Represents a JSON value. - The JSON representation for `Value` is JSON value. + `Value` represents a dynamically typed value which can be either + null, a number, a string, a boolean, a recursive struct value, or a + list of values. A producer of value is expected to set one of these + variants. Absence of any variant is an invalid state. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NULL_VALUE_FIELD_NUMBER: builtins.int NUMBER_VALUE_FIELD_NUMBER: builtins.int STRING_VALUE_FIELD_NUMBER: builtins.int BOOL_VALUE_FIELD_NUMBER: builtins.int STRUCT_VALUE_FIELD_NUMBER: builtins.int LIST_VALUE_FIELD_NUMBER: builtins.int - null_value: global___NullValue.V = ... - """Represents a null value.""" - - number_value: builtins.float = ... - """Represents a double value.""" - - string_value: typing.Text = ... - """Represents a string value.""" - - bool_value: builtins.bool = ... - """Represents a boolean value.""" - + null_value: global___NullValue.ValueType + """Represents a JSON `null`.""" + number_value: builtins.float + """Represents a JSON number. Must not be `NaN`, `Infinity` or + `-Infinity`, since those are not supported in JSON. This also cannot + represent large Int64 values, since JSON format generally does not + support them in its number type. + """ + string_value: builtins.str + """Represents a JSON string.""" + bool_value: builtins.bool + """Represents a JSON boolean (`true` or `false` literal in JSON).""" @property def struct_value(self) -> global___Struct: - """Represents a structured value.""" - pass + """Represents a JSON object.""" + @property def list_value(self) -> global___ListValue: - """Represents a repeated `Value`.""" - pass - def __init__(self, + """Represents a JSON array.""" + + def __init__( + self, *, - null_value : global___NullValue.V = ..., - number_value : builtins.float = ..., - string_value : typing.Text = ..., - bool_value : builtins.bool = ..., - struct_value : typing.Optional[global___Struct] = ..., - list_value : typing.Optional[global___ListValue] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["bool_value",b"bool_value","kind",b"kind","list_value",b"list_value","null_value",b"null_value","number_value",b"number_value","string_value",b"string_value","struct_value",b"struct_value"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["bool_value",b"bool_value","kind",b"kind","list_value",b"list_value","null_value",b"null_value","number_value",b"number_value","string_value",b"string_value","struct_value",b"struct_value"]) -> None: ... - def WhichOneof(self, oneof_group: typing_extensions.Literal["kind",b"kind"]) -> typing.Optional[typing_extensions.Literal["null_value","number_value","string_value","bool_value","struct_value","list_value"]]: ... + null_value: global___NullValue.ValueType | None = ..., + number_value: builtins.float | None = ..., + string_value: builtins.str | None = ..., + bool_value: builtins.bool | None = ..., + struct_value: global___Struct | None = ..., + list_value: global___ListValue | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "bool_value", + b"bool_value", + "kind", + b"kind", + "list_value", + b"list_value", + "null_value", + b"null_value", + "number_value", + b"number_value", + "string_value", + b"string_value", + "struct_value", + b"struct_value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bool_value", + b"bool_value", + "kind", + b"kind", + "list_value", + b"list_value", + "null_value", + b"null_value", + "number_value", + b"number_value", + "string_value", + b"string_value", + "struct_value", + b"struct_value", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> typing.Literal["null_value", "number_value", "string_value", "bool_value", "struct_value", "list_value"] | None: ... + global___Value = Value +@typing.final class ListValue(google.protobuf.message.Message, google.protobuf.internal.well_known_types.ListValue): - """`ListValue` is a wrapper around a repeated field of values. + """Represents a JSON array.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor - The JSON representation for `ListValue` is JSON array. - """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... VALUES_FIELD_NUMBER: builtins.int @property def values(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Value]: """Repeated field of dynamically typed values.""" - pass - def __init__(self, - *, - values : typing.Optional[typing.Iterable[global___Value]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["values",b"values"]) -> None: ... + + def __init__(self, *, values: collections.abc.Iterable[global___Value] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["values", b"values"]) -> None: ... + global___ListValue = ListValue diff --git a/stubs/protobuf/google/protobuf/symbol_database.pyi b/stubs/protobuf/google/protobuf/symbol_database.pyi index 09e32e9de2f7..6fda0df00fd4 100644 --- a/stubs/protobuf/google/protobuf/symbol_database.pyi +++ b/stubs/protobuf/google/protobuf/symbol_database.pyi @@ -1,16 +1,17 @@ -from typing import Dict, Iterable, Type, Union +from collections.abc import Iterable from google.protobuf.descriptor import Descriptor, EnumDescriptor, FileDescriptor, ServiceDescriptor +from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.message import Message -from google.protobuf.message_factory import MessageFactory -class SymbolDatabase(MessageFactory): - def RegisterMessage(self, message: Union[Type[Message], Message]) -> Union[Type[Message], Message]: ... +class SymbolDatabase: + def __init__(self, pool: DescriptorPool | None = None) -> None: ... + def RegisterMessage(self, message: type[Message] | Message) -> type[Message] | Message: ... def RegisterMessageDescriptor(self, message_descriptor: Descriptor) -> None: ... def RegisterEnumDescriptor(self, enum_descriptor: EnumDescriptor) -> EnumDescriptor: ... def RegisterServiceDescriptor(self, service_descriptor: ServiceDescriptor) -> None: ... def RegisterFileDescriptor(self, file_descriptor: FileDescriptor) -> None: ... - def GetSymbol(self, symbol: str) -> Type[Message]: ... - def GetMessages(self, files: Iterable[str]) -> Dict[str, Type[Message]]: ... + def GetSymbol(self, symbol: str) -> type[Message]: ... + def GetMessages(self, files: Iterable[str]) -> dict[str, type[Message]]: ... -def Default(): ... +def Default() -> SymbolDatabase: ... diff --git a/stubs/protobuf/google/protobuf/text_encoding.pyi b/stubs/protobuf/google/protobuf/text_encoding.pyi new file mode 100644 index 000000000000..69a69bf0e9e6 --- /dev/null +++ b/stubs/protobuf/google/protobuf/text_encoding.pyi @@ -0,0 +1,2 @@ +def CEscape(text: bytes, as_utf8: bool) -> str: ... +def CUnescape(text: str) -> bytes: ... diff --git a/stubs/protobuf/google/protobuf/text_format.pyi b/stubs/protobuf/google/protobuf/text_format.pyi index eafb77a630b3..e1c7b2049dac 100644 --- a/stubs/protobuf/google/protobuf/text_format.pyi +++ b/stubs/protobuf/google/protobuf/text_format.pyi @@ -1,200 +1,193 @@ -import sys from _typeshed import SupportsWrite -from typing import Any, Callable, Iterable, Optional, Text, Tuple, TypeVar, Union +from collections.abc import Callable, Iterable +from typing import Any, TypeAlias, TypeVar from .descriptor import FieldDescriptor from .descriptor_pool import DescriptorPool from .message import Message -if sys.version_info < (3, 0): - long = int - _M = TypeVar("_M", bound=Message) # message type (of self) +__all__ = ["MessageToString", "Parse", "PrintMessage", "PrintField", "PrintFieldValue", "Merge", "MessageToBytes"] + class Error(Exception): ... class ParseError(Error): - def __init__(self, message: Optional[str] = ..., line: Optional[int] = ..., column: Optional[int] = ...) -> None: ... - def GetLine(self) -> Optional[int]: ... - def GetColumn(self) -> Optional[int]: ... + def __init__(self, message: str | None = None, line: int | None = None, column: int | None = None) -> None: ... + def GetLine(self) -> int | None: ... + def GetColumn(self) -> int | None: ... class TextWriter: def __init__(self, as_utf8: bool) -> None: ... - def write(self, val: Text) -> int: ... - def getvalue(self) -> str: ... + def write(self, val: str) -> int: ... def close(self) -> None: ... + def getvalue(self) -> str: ... -_MessageFormatter = Callable[[Message, int, bool], Optional[Text]] +_MessageFormatter: TypeAlias = Callable[[Message, int, bool], str | None] def MessageToString( message: Message, - as_utf8: bool = ..., - as_one_line: bool = ..., - use_short_repeated_primitives: bool = ..., - pointy_brackets: bool = ..., - use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - indent: int = ..., - message_formatter: Optional[_MessageFormatter] = ..., - print_unknown_fields: bool = ..., - force_colon: bool = ..., + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + indent: int = 0, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, ) -> str: ... def MessageToBytes( message: Message, - as_utf8: bool = ..., - as_one_line: bool = ..., - use_short_repeated_primitives: bool = ..., - pointy_brackets: bool = ..., - use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - indent: int = ..., - message_formatter: _MessageFormatter = ..., - print_unknown_fields: bool = ..., - force_colon: bool = ..., + *, + # Same kwargs as MessageToString + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + indent: int = 0, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, ) -> bytes: ... def PrintMessage( message: Message, out: SupportsWrite[str], - indent: int = ..., - as_utf8: bool = ..., - as_one_line: bool = ..., - use_short_repeated_primitives: bool = ..., - pointy_brackets: bool = ..., - use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - message_formatter: Optional[_MessageFormatter] = ..., - print_unknown_fields: bool = ..., - force_colon: bool = ..., + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, ) -> None: ... def PrintField( field: FieldDescriptor, value: Any, out: SupportsWrite[str], - indent: int = ..., - as_utf8: bool = ..., - as_one_line: bool = ..., - use_short_repeated_primitives: bool = ..., - pointy_brackets: bool = ..., - use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - message_formatter: Optional[_MessageFormatter] = ..., - print_unknown_fields: bool = ..., - force_colon: bool = ..., + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, ) -> None: ... def PrintFieldValue( field: FieldDescriptor, value: Any, out: SupportsWrite[str], - indent: int = ..., - as_utf8: bool = ..., - as_one_line: bool = ..., - use_short_repeated_primitives: bool = ..., - pointy_brackets: bool = ..., - use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - message_formatter: Optional[_MessageFormatter] = ..., - print_unknown_fields: bool = ..., - force_colon: bool = ..., + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, ) -> None: ... class _Printer: - out: SupportsWrite[str] = ... - indent: int = ... - as_utf8: bool = ... - as_one_line: bool = ... - use_short_repeated_primitives: bool = ... - pointy_brackets: bool = ... - use_index_order: bool = ... - float_format: Optional[str] = ... - double_format: Optional[str] = ... - use_field_number: bool = ... - descriptor_pool: Optional[DescriptorPool] = ... - message_formatter: Optional[_MessageFormatter] = ... - print_unknown_fields: bool = ... - force_colon: bool = ... + out: SupportsWrite[str] + indent: int + as_utf8: bool + as_one_line: bool + use_short_repeated_primitives: bool + pointy_brackets: bool + use_index_order: bool + use_field_number: bool + descriptor_pool: DescriptorPool | None + message_formatter: _MessageFormatter | None + print_unknown_fields: bool + force_colon: bool def __init__( self, out: SupportsWrite[str], - indent: int = ..., - as_utf8: bool = ..., - as_one_line: bool = ..., - use_short_repeated_primitives: bool = ..., - pointy_brackets: bool = ..., - use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - message_formatter: Optional[_MessageFormatter] = ..., - print_unknown_fields: bool = ..., - force_colon: bool = ..., + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, ) -> None: ... def PrintMessage(self, message: Message) -> None: ... def PrintField(self, field: FieldDescriptor, value: Any) -> None: ... def PrintFieldValue(self, field: FieldDescriptor, value: Any) -> None: ... def Parse( - text: Union[Text, bytes], + text: str | bytes, message: _M, - allow_unknown_extension: bool = ..., - allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - allow_unknown_field: bool = ..., + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, + max_recursion_depth: int | None = None, ) -> _M: ... def Merge( - text: Union[Text, bytes], + text: str | bytes, message: _M, - allow_unknown_extension: bool = ..., - allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - allow_unknown_field: bool = ..., + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, + max_recursion_depth: int | None = None, ) -> _M: ... def MergeLines( - lines: Iterable[Union[Text, bytes]], + lines: Iterable[str | bytes], message: _M, - allow_unknown_extension: bool = ..., - allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - allow_unknown_field: bool = ..., + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, + max_recursion_depth: int | None = None, ) -> _M: ... class _Parser: - allow_unknown_extension: bool = ... - allow_field_number: bool = ... - descriptor_pool: Optional[DescriptorPool] = ... - allow_unknown_field: bool = ... + allow_unknown_extension: bool + allow_field_number: bool + descriptor_pool: DescriptorPool | None + allow_unknown_field: bool + max_recursion_depth: int | None + recursion_depth: int def __init__( self, - allow_unknown_extension: bool = ..., - allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - allow_unknown_field: bool = ..., + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, + max_recursion_depth: int | None = None, ) -> None: ... - def ParseLines(self, lines: Iterable[Union[Text, bytes]], message: _M) -> _M: ... - def MergeLines(self, lines: Iterable[Union[Text, bytes]], message: _M) -> _M: ... + def ParseLines(self, lines: Iterable[str | bytes], message: _M) -> _M: ... + def MergeLines(self, lines: Iterable[str | bytes], message: _M) -> _M: ... -_ParseError = ParseError +_ParseError: TypeAlias = ParseError class Tokenizer: - token: str = ... - def __init__(self, lines: Iterable[str], skip_comments: bool = ...) -> None: ... + token: str + def __init__(self, lines: Iterable[str], skip_comments: bool = True) -> None: ... def LookingAt(self, token: str) -> bool: ... def AtEnd(self) -> bool: ... def TryConsume(self, token: str) -> bool: ... def Consume(self, token: str) -> None: ... def ConsumeComment(self) -> str: ... - def ConsumeCommentOrTrailingComment(self) -> Tuple[bool, str]: ... + def ConsumeCommentOrTrailingComment(self) -> tuple[bool, str]: ... def TryConsumeIdentifier(self) -> bool: ... def ConsumeIdentifier(self) -> str: ... def TryConsumeIdentifierOrNumber(self) -> bool: ... @@ -205,14 +198,16 @@ class Tokenizer: def ConsumeFloat(self) -> float: ... def ConsumeBool(self) -> bool: ... def TryConsumeByteString(self) -> bool: ... - def ConsumeString(self) -> Text: ... + def ConsumeString(self) -> str: ... def ConsumeByteString(self) -> bytes: ... def ConsumeEnum(self, field: FieldDescriptor) -> int: ... + def ConsumeUrlChars(self) -> str: ... + def TryConsumeUrlChars(self) -> bool: ... def ParseErrorPreviousToken(self, message: Message) -> _ParseError: ... def ParseError(self, message: Message) -> _ParseError: ... def NextToken(self) -> None: ... -def ParseInteger(text: str, is_signed: bool = ..., is_long: bool = ...) -> int: ... +def ParseInteger(text: str, is_signed: bool = False, is_long: bool = False) -> int: ... def ParseFloat(text: str) -> float: ... def ParseBool(text: str) -> bool: ... def ParseEnum(field: FieldDescriptor, value: str) -> int: ... diff --git a/stubs/protobuf/google/protobuf/timestamp.pyi b/stubs/protobuf/google/protobuf/timestamp.pyi new file mode 100644 index 000000000000..b6687a744e45 --- /dev/null +++ b/stubs/protobuf/google/protobuf/timestamp.pyi @@ -0,0 +1,16 @@ +from datetime import datetime, tzinfo + +from google.protobuf.timestamp_pb2 import Timestamp + +def from_json_string(value: str) -> Timestamp: ... +def from_microseconds(micros: float) -> Timestamp: ... +def from_milliseconds(millis: float) -> Timestamp: ... +def from_nanoseconds(nanos: float) -> Timestamp: ... +def from_seconds(seconds: float) -> Timestamp: ... +def from_current_time() -> Timestamp: ... +def to_json_string(ts: Timestamp) -> str: ... +def to_microseconds(ts: Timestamp) -> int: ... +def to_milliseconds(ts: Timestamp) -> int: ... +def to_nanoseconds(ts: Timestamp) -> int: ... +def to_seconds(ts: Timestamp) -> int: ... +def to_datetime(ts: Timestamp, tz: tzinfo | None = None) -> datetime: ... diff --git a/stubs/protobuf/google/protobuf/timestamp_pb2.pyi b/stubs/protobuf/google/protobuf/timestamp_pb2.pyi index 846004d18381..ac976d88455b 100644 --- a/stubs/protobuf/google/protobuf/timestamp_pb2.pyi +++ b/stubs/protobuf/google/protobuf/timestamp_pb2.pyi @@ -1,15 +1,47 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import typing + import google.protobuf.descriptor import google.protobuf.internal.well_known_types import google.protobuf.message -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class Timestamp(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Timestamp): """A Timestamp represents a point in time independent of any time zone or local calendar, encoded as a count of seconds and fractions of seconds at @@ -61,7 +93,6 @@ class Timestamp(google.protobuf.message.Message, google.protobuf.internal.well_k Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) .setNanos((int) ((millis % 1000) * 1000000)).build(); - Example 5: Compute Timestamp from Java `Instant.now()`. Instant now = Instant.now(); @@ -70,7 +101,6 @@ class Timestamp(google.protobuf.message.Message, google.protobuf.internal.well_k Timestamp.newBuilder().setSeconds(now.getEpochSecond()) .setNanos(now.getNano()).build(); - Example 6: Compute Timestamp from current time in Python. timestamp = Timestamp() @@ -85,8 +115,8 @@ class Timestamp(google.protobuf.message.Message, google.protobuf.internal.well_k {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone - is required. A proto3 JSON serializer should always use UTC (as indicated by - "Z") when printing the Timestamp type and a proto3 JSON parser should be + is required. A ProtoJSON serializer should always use UTC (as indicated by + "Z") when printing the Timestamp type and a ProtoJSON parser should be able to accept both UTC and other timezones (as indicated by an offset). For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past @@ -100,29 +130,27 @@ class Timestamp(google.protobuf.message.Message, google.protobuf.internal.well_k [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( - http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D + http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() ) to obtain a formatter capable of generating timestamps in this format. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + SECONDS_FIELD_NUMBER: builtins.int NANOS_FIELD_NUMBER: builtins.int - seconds: builtins.int = ... - """Represents seconds of UTC time since Unix epoch - 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - 9999-12-31T23:59:59Z inclusive. + seconds: builtins.int + """Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must + be between -62135596800 and 253402300799 inclusive (which corresponds to + 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z). """ - - nanos: builtins.int = ... - """Non-negative fractions of a second at nanosecond resolution. Negative - second values with fractions must still have non-negative nanos values - that count forward in time. Must be from 0 to 999,999,999 + nanos: builtins.int + """Non-negative fractions of a second at nanosecond resolution. This field is + the nanosecond portion of the duration, not an alternative to seconds. + Negative second values with fractions must still have non-negative nanos + values that count forward in time. Must be between 0 and 999,999,999 inclusive. """ + def __init__(self, *, seconds: builtins.int | None = ..., nanos: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["nanos", b"nanos", "seconds", b"seconds"]) -> None: ... - def __init__(self, - *, - seconds : builtins.int = ..., - nanos : builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["nanos",b"nanos","seconds",b"seconds"]) -> None: ... global___Timestamp = Timestamp diff --git a/stubs/protobuf/google/protobuf/type_pb2.pyi b/stubs/protobuf/google/protobuf/type_pb2.pyi index d79a3c26a3a9..a8a7eb07c778 100644 --- a/stubs/protobuf/google/protobuf/type_pb2.pyi +++ b/stubs/protobuf/google/protobuf/type_pb2.pyi @@ -1,245 +1,283 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ + import builtins +import collections.abc +import sys +import typing + import google.protobuf.any_pb2 import google.protobuf.descriptor import google.protobuf.internal.containers import google.protobuf.internal.enum_type_wrapper import google.protobuf.message import google.protobuf.source_context_pb2 -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor -class Syntax(_Syntax, metaclass=_SyntaxEnumTypeWrapper): - """The syntax in which a protocol buffer element is defined.""" - pass class _Syntax: - V = typing.NewType('V', builtins.int) -class _SyntaxEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Syntax.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - SYNTAX_PROTO2 = Syntax.V(0) - """Syntax `proto2`.""" + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType - SYNTAX_PROTO3 = Syntax.V(1) +class _SyntaxEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Syntax.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SYNTAX_PROTO2: _Syntax.ValueType # 0 + """Syntax `proto2`.""" + SYNTAX_PROTO3: _Syntax.ValueType # 1 """Syntax `proto3`.""" + SYNTAX_EDITIONS: _Syntax.ValueType # 2 + """Syntax `editions`.""" +class Syntax(_Syntax, metaclass=_SyntaxEnumTypeWrapper): + """The syntax in which a protocol buffer element is defined.""" -SYNTAX_PROTO2 = Syntax.V(0) +SYNTAX_PROTO2: Syntax.ValueType # 0 """Syntax `proto2`.""" - -SYNTAX_PROTO3 = Syntax.V(1) +SYNTAX_PROTO3: Syntax.ValueType # 1 """Syntax `proto3`.""" - +SYNTAX_EDITIONS: Syntax.ValueType # 2 +"""Syntax `editions`.""" global___Syntax = Syntax - +@typing.final class Type(google.protobuf.message.Message): - """A protocol buffer message type.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + """A protocol buffer message type. + + New usages of this message as an alternative to DescriptorProto are strongly + discouraged. This message does not reliability preserve all information + necessary to model the schema and preserve semantics. Instead make use of + FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int FIELDS_FIELD_NUMBER: builtins.int ONEOFS_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int SOURCE_CONTEXT_FIELD_NUMBER: builtins.int SYNTAX_FIELD_NUMBER: builtins.int - name: typing.Text = ... + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str """The fully qualified message name.""" - + syntax: global___Syntax.ValueType + """The source syntax.""" + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS.""" @property def fields(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Field]: """The list of fields.""" - pass + @property - def oneofs(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[typing.Text]: + def oneofs(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: """The list of types appearing in `oneof` definitions in this type.""" - pass + @property def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: """The protocol buffer options.""" - pass + @property def source_context(self) -> google.protobuf.source_context_pb2.SourceContext: """The source context.""" - pass - syntax: global___Syntax.V = ... - """The source syntax.""" - def __init__(self, + def __init__( + self, *, - name : typing.Text = ..., - fields : typing.Optional[typing.Iterable[global___Field]] = ..., - oneofs : typing.Optional[typing.Iterable[typing.Text]] = ..., - options : typing.Optional[typing.Iterable[global___Option]] = ..., - source_context : typing.Optional[google.protobuf.source_context_pb2.SourceContext] = ..., - syntax : global___Syntax.V = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["source_context",b"source_context"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["fields",b"fields","name",b"name","oneofs",b"oneofs","options",b"options","source_context",b"source_context","syntax",b"syntax"]) -> None: ... + name: builtins.str | None = ..., + fields: collections.abc.Iterable[global___Field] | None = ..., + oneofs: collections.abc.Iterable[builtins.str] | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + source_context: google.protobuf.source_context_pb2.SourceContext | None = ..., + syntax: global___Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["source_context", b"source_context"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "fields", + b"fields", + "name", + b"name", + "oneofs", + b"oneofs", + "options", + b"options", + "source_context", + b"source_context", + "syntax", + b"syntax", + ], + ) -> None: ... + global___Type = Type +@typing.final class Field(google.protobuf.message.Message): - """A single field of a message type.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... - class Kind(_Kind, metaclass=_KindEnumTypeWrapper): - """Basic field types.""" - pass + """A single field of a message type. + + New usages of this message as an alternative to FieldDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + class _Kind: - V = typing.NewType('V', builtins.int) - class _KindEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Kind.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - TYPE_UNKNOWN = Field.Kind.V(0) - """Field type unknown.""" + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType - TYPE_DOUBLE = Field.Kind.V(1) + class _KindEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Field._Kind.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TYPE_UNKNOWN: Field._Kind.ValueType # 0 + """Field type unknown.""" + TYPE_DOUBLE: Field._Kind.ValueType # 1 """Field type double.""" - - TYPE_FLOAT = Field.Kind.V(2) + TYPE_FLOAT: Field._Kind.ValueType # 2 """Field type float.""" - - TYPE_INT64 = Field.Kind.V(3) + TYPE_INT64: Field._Kind.ValueType # 3 """Field type int64.""" - - TYPE_UINT64 = Field.Kind.V(4) + TYPE_UINT64: Field._Kind.ValueType # 4 """Field type uint64.""" - - TYPE_INT32 = Field.Kind.V(5) + TYPE_INT32: Field._Kind.ValueType # 5 """Field type int32.""" - - TYPE_FIXED64 = Field.Kind.V(6) + TYPE_FIXED64: Field._Kind.ValueType # 6 """Field type fixed64.""" - - TYPE_FIXED32 = Field.Kind.V(7) + TYPE_FIXED32: Field._Kind.ValueType # 7 """Field type fixed32.""" - - TYPE_BOOL = Field.Kind.V(8) + TYPE_BOOL: Field._Kind.ValueType # 8 """Field type bool.""" - - TYPE_STRING = Field.Kind.V(9) + TYPE_STRING: Field._Kind.ValueType # 9 """Field type string.""" - - TYPE_GROUP = Field.Kind.V(10) + TYPE_GROUP: Field._Kind.ValueType # 10 """Field type group. Proto2 syntax only, and deprecated.""" - - TYPE_MESSAGE = Field.Kind.V(11) + TYPE_MESSAGE: Field._Kind.ValueType # 11 """Field type message.""" - - TYPE_BYTES = Field.Kind.V(12) + TYPE_BYTES: Field._Kind.ValueType # 12 """Field type bytes.""" - - TYPE_UINT32 = Field.Kind.V(13) + TYPE_UINT32: Field._Kind.ValueType # 13 """Field type uint32.""" - - TYPE_ENUM = Field.Kind.V(14) + TYPE_ENUM: Field._Kind.ValueType # 14 """Field type enum.""" - - TYPE_SFIXED32 = Field.Kind.V(15) + TYPE_SFIXED32: Field._Kind.ValueType # 15 """Field type sfixed32.""" - - TYPE_SFIXED64 = Field.Kind.V(16) + TYPE_SFIXED64: Field._Kind.ValueType # 16 """Field type sfixed64.""" - - TYPE_SINT32 = Field.Kind.V(17) + TYPE_SINT32: Field._Kind.ValueType # 17 """Field type sint32.""" - - TYPE_SINT64 = Field.Kind.V(18) + TYPE_SINT64: Field._Kind.ValueType # 18 """Field type sint64.""" + class Kind(_Kind, metaclass=_KindEnumTypeWrapper): + """Basic field types.""" - TYPE_UNKNOWN = Field.Kind.V(0) + TYPE_UNKNOWN: Field.Kind.ValueType # 0 """Field type unknown.""" - - TYPE_DOUBLE = Field.Kind.V(1) + TYPE_DOUBLE: Field.Kind.ValueType # 1 """Field type double.""" - - TYPE_FLOAT = Field.Kind.V(2) + TYPE_FLOAT: Field.Kind.ValueType # 2 """Field type float.""" - - TYPE_INT64 = Field.Kind.V(3) + TYPE_INT64: Field.Kind.ValueType # 3 """Field type int64.""" - - TYPE_UINT64 = Field.Kind.V(4) + TYPE_UINT64: Field.Kind.ValueType # 4 """Field type uint64.""" - - TYPE_INT32 = Field.Kind.V(5) + TYPE_INT32: Field.Kind.ValueType # 5 """Field type int32.""" - - TYPE_FIXED64 = Field.Kind.V(6) + TYPE_FIXED64: Field.Kind.ValueType # 6 """Field type fixed64.""" - - TYPE_FIXED32 = Field.Kind.V(7) + TYPE_FIXED32: Field.Kind.ValueType # 7 """Field type fixed32.""" - - TYPE_BOOL = Field.Kind.V(8) + TYPE_BOOL: Field.Kind.ValueType # 8 """Field type bool.""" - - TYPE_STRING = Field.Kind.V(9) + TYPE_STRING: Field.Kind.ValueType # 9 """Field type string.""" - - TYPE_GROUP = Field.Kind.V(10) + TYPE_GROUP: Field.Kind.ValueType # 10 """Field type group. Proto2 syntax only, and deprecated.""" - - TYPE_MESSAGE = Field.Kind.V(11) + TYPE_MESSAGE: Field.Kind.ValueType # 11 """Field type message.""" - - TYPE_BYTES = Field.Kind.V(12) + TYPE_BYTES: Field.Kind.ValueType # 12 """Field type bytes.""" - - TYPE_UINT32 = Field.Kind.V(13) + TYPE_UINT32: Field.Kind.ValueType # 13 """Field type uint32.""" - - TYPE_ENUM = Field.Kind.V(14) + TYPE_ENUM: Field.Kind.ValueType # 14 """Field type enum.""" - - TYPE_SFIXED32 = Field.Kind.V(15) + TYPE_SFIXED32: Field.Kind.ValueType # 15 """Field type sfixed32.""" - - TYPE_SFIXED64 = Field.Kind.V(16) + TYPE_SFIXED64: Field.Kind.ValueType # 16 """Field type sfixed64.""" - - TYPE_SINT32 = Field.Kind.V(17) + TYPE_SINT32: Field.Kind.ValueType # 17 """Field type sint32.""" - - TYPE_SINT64 = Field.Kind.V(18) + TYPE_SINT64: Field.Kind.ValueType # 18 """Field type sint64.""" - - class Cardinality(_Cardinality, metaclass=_CardinalityEnumTypeWrapper): - """Whether a field is optional, required, or repeated.""" - pass class _Cardinality: - V = typing.NewType('V', builtins.int) - class _CardinalityEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Cardinality.V], builtins.type): - DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ... - CARDINALITY_UNKNOWN = Field.Cardinality.V(0) + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CardinalityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Field._Cardinality.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CARDINALITY_UNKNOWN: Field._Cardinality.ValueType # 0 """For fields with unknown cardinality.""" - - CARDINALITY_OPTIONAL = Field.Cardinality.V(1) + CARDINALITY_OPTIONAL: Field._Cardinality.ValueType # 1 """For optional fields.""" - - CARDINALITY_REQUIRED = Field.Cardinality.V(2) + CARDINALITY_REQUIRED: Field._Cardinality.ValueType # 2 """For required fields. Proto2 syntax only.""" - - CARDINALITY_REPEATED = Field.Cardinality.V(3) + CARDINALITY_REPEATED: Field._Cardinality.ValueType # 3 """For repeated fields.""" + class Cardinality(_Cardinality, metaclass=_CardinalityEnumTypeWrapper): + """Whether a field is optional, required, or repeated.""" - CARDINALITY_UNKNOWN = Field.Cardinality.V(0) + CARDINALITY_UNKNOWN: Field.Cardinality.ValueType # 0 """For fields with unknown cardinality.""" - - CARDINALITY_OPTIONAL = Field.Cardinality.V(1) + CARDINALITY_OPTIONAL: Field.Cardinality.ValueType # 1 """For optional fields.""" - - CARDINALITY_REQUIRED = Field.Cardinality.V(2) + CARDINALITY_REQUIRED: Field.Cardinality.ValueType # 2 """For required fields. Proto2 syntax only.""" - - CARDINALITY_REPEATED = Field.Cardinality.V(3) + CARDINALITY_REPEATED: Field.Cardinality.ValueType # 3 """For repeated fields.""" - KIND_FIELD_NUMBER: builtins.int CARDINALITY_FIELD_NUMBER: builtins.int NUMBER_FIELD_NUMBER: builtins.int @@ -250,134 +288,195 @@ class Field(google.protobuf.message.Message): OPTIONS_FIELD_NUMBER: builtins.int JSON_NAME_FIELD_NUMBER: builtins.int DEFAULT_VALUE_FIELD_NUMBER: builtins.int - kind: global___Field.Kind.V = ... + kind: global___Field.Kind.ValueType """The field type.""" - - cardinality: global___Field.Cardinality.V = ... + cardinality: global___Field.Cardinality.ValueType """The field cardinality.""" - - number: builtins.int = ... + number: builtins.int """The field number.""" - - name: typing.Text = ... + name: builtins.str """The field name.""" - - type_url: typing.Text = ... + type_url: builtins.str """The field type URL, without the scheme, for message or enumeration types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. """ - - oneof_index: builtins.int = ... + oneof_index: builtins.int """The index of the field type in `Type.oneofs`, for message or enumeration types. The first type has index 1; zero means the type is not in the list. """ - - packed: builtins.bool = ... + packed: builtins.bool """Whether to use alternative packed wire representation.""" - + json_name: builtins.str + """The field JSON name.""" + default_value: builtins.str + """The string value of the default value of this field. Proto2 syntax only.""" @property def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: """The protocol buffer options.""" - pass - json_name: typing.Text = ... - """The field JSON name.""" - - default_value: typing.Text = ... - """The string value of the default value of this field. Proto2 syntax only.""" - def __init__(self, + def __init__( + self, *, - kind : global___Field.Kind.V = ..., - cardinality : global___Field.Cardinality.V = ..., - number : builtins.int = ..., - name : typing.Text = ..., - type_url : typing.Text = ..., - oneof_index : builtins.int = ..., - packed : builtins.bool = ..., - options : typing.Optional[typing.Iterable[global___Option]] = ..., - json_name : typing.Text = ..., - default_value : typing.Text = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["cardinality",b"cardinality","default_value",b"default_value","json_name",b"json_name","kind",b"kind","name",b"name","number",b"number","oneof_index",b"oneof_index","options",b"options","packed",b"packed","type_url",b"type_url"]) -> None: ... + kind: global___Field.Kind.ValueType | None = ..., + cardinality: global___Field.Cardinality.ValueType | None = ..., + number: builtins.int | None = ..., + name: builtins.str | None = ..., + type_url: builtins.str | None = ..., + oneof_index: builtins.int | None = ..., + packed: builtins.bool | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + json_name: builtins.str | None = ..., + default_value: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "cardinality", + b"cardinality", + "default_value", + b"default_value", + "json_name", + b"json_name", + "kind", + b"kind", + "name", + b"name", + "number", + b"number", + "oneof_index", + b"oneof_index", + "options", + b"options", + "packed", + b"packed", + "type_url", + b"type_url", + ], + ) -> None: ... + global___Field = Field +@typing.final class Enum(google.protobuf.message.Message): - """Enum type definition.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + """Enum type definition. + + New usages of this message as an alternative to EnumDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int ENUMVALUE_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int SOURCE_CONTEXT_FIELD_NUMBER: builtins.int SYNTAX_FIELD_NUMBER: builtins.int - name: typing.Text = ... + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str """Enum type name.""" - + syntax: global___Syntax.ValueType + """The source syntax.""" + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS.""" @property def enumvalue(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumValue]: """Enum value definitions.""" - pass + @property def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: """Protocol buffer options.""" - pass + @property def source_context(self) -> google.protobuf.source_context_pb2.SourceContext: """The source context.""" - pass - syntax: global___Syntax.V = ... - """The source syntax.""" - def __init__(self, + def __init__( + self, *, - name : typing.Text = ..., - enumvalue : typing.Optional[typing.Iterable[global___EnumValue]] = ..., - options : typing.Optional[typing.Iterable[global___Option]] = ..., - source_context : typing.Optional[google.protobuf.source_context_pb2.SourceContext] = ..., - syntax : global___Syntax.V = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["source_context",b"source_context"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["enumvalue",b"enumvalue","name",b"name","options",b"options","source_context",b"source_context","syntax",b"syntax"]) -> None: ... + name: builtins.str | None = ..., + enumvalue: collections.abc.Iterable[global___EnumValue] | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + source_context: google.protobuf.source_context_pb2.SourceContext | None = ..., + syntax: global___Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["source_context", b"source_context"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "enumvalue", + b"enumvalue", + "name", + b"name", + "options", + b"options", + "source_context", + b"source_context", + "syntax", + b"syntax", + ], + ) -> None: ... + global___Enum = Enum +@typing.final class EnumValue(google.protobuf.message.Message): - """Enum value definition.""" - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + """Enum value definition. + + New usages of this message as an alternative to EnumValueDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int NUMBER_FIELD_NUMBER: builtins.int OPTIONS_FIELD_NUMBER: builtins.int - name: typing.Text = ... + name: builtins.str """Enum value name.""" - - number: builtins.int = ... + number: builtins.int """Enum value number.""" - @property def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: """Protocol buffer options.""" - pass - def __init__(self, + + def __init__( + self, *, - name : typing.Text = ..., - number : builtins.int = ..., - options : typing.Optional[typing.Iterable[global___Option]] = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","number",b"number","options",b"options"]) -> None: ... + name: builtins.str | None = ..., + number: builtins.int | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "number", b"number", "options", b"options"]) -> None: ... + global___EnumValue = EnumValue +@typing.final class Option(google.protobuf.message.Message): """A protocol buffer option, which can be attached to a message, field, enumeration, etc. + + New usages of this message as an alternative to FileOptions, MessageOptions, + FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions + are strongly discouraged. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + NAME_FIELD_NUMBER: builtins.int VALUE_FIELD_NUMBER: builtins.int - name: typing.Text = ... + name: builtins.str """The option's name. For protobuf built-in options (options defined in descriptor.proto), this is the short name. For example, `"map_entry"`. For custom options, it should be the fully-qualified name. For example, `"google.api.http"`. """ - @property def value(self) -> google.protobuf.any_pb2.Any: """The option's value packed in an Any message. If the value is a primitive, @@ -385,12 +484,9 @@ class Option(google.protobuf.message.Message): should be used. If the value is an enum, it should be stored as an int32 value using the google.protobuf.Int32Value type. """ - pass - def __init__(self, - *, - name : typing.Text = ..., - value : typing.Optional[google.protobuf.any_pb2.Any] = ..., - ) -> None: ... - def HasField(self, field_name: typing_extensions.Literal["value",b"value"]) -> builtins.bool: ... - def ClearField(self, field_name: typing_extensions.Literal["name",b"name","value",b"value"]) -> None: ... + + def __init__(self, *, name: builtins.str | None = ..., value: google.protobuf.any_pb2.Any | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "value", b"value"]) -> None: ... + global___Option = Option diff --git a/stubs/protobuf/google/protobuf/unknown_fields.pyi b/stubs/protobuf/google/protobuf/unknown_fields.pyi new file mode 100644 index 000000000000..7329b00a4128 --- /dev/null +++ b/stubs/protobuf/google/protobuf/unknown_fields.pyi @@ -0,0 +1,9 @@ +from typing import Any, final + +from google.protobuf.message import Message + +@final +class UnknownFieldSet: + def __new__(cls, msg: Message) -> UnknownFieldSet: ... # noqa: Y034 + def __getitem__(self, index: int, /) -> Any: ... # Any: internal unknown field object + def __len__(self) -> int: ... diff --git a/stubs/protobuf/google/protobuf/wrappers_pb2.pyi b/stubs/protobuf/google/protobuf/wrappers_pb2.pyi index f4cdb76be019..b3d875bccf67 100644 --- a/stubs/protobuf/google/protobuf/wrappers_pb2.pyi +++ b/stubs/protobuf/google/protobuf/wrappers_pb2.pyi @@ -1,164 +1,238 @@ """ @generated by mypy-protobuf. Do not edit manually! isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Wrappers for primitive (non-message) types. These types were needed +for legacy reasons and are not recommended for use in new APIs. + +Historically these wrappers were useful to have presence on proto3 primitive +fields, but proto3 syntax has been updated to support the `optional` keyword. +Using that keyword is now the strongly preferred way to add presence to +proto3 primitive fields. + +A secondary usecase was to embed primitives in the `google.protobuf.Any` +type: it is now recommended that you embed your value in your own wrapper +message which can be specifically documented. + +These wrappers have no meaningful use within repeated fields as they lack +the ability to detect presence on individual elements. +These wrappers have no meaningful use within a map or a oneof since +individual entries of a map or fields of a oneof can already detect presence. """ + import builtins +import typing + import google.protobuf.descriptor import google.protobuf.message -import typing -import typing_extensions -DESCRIPTOR: google.protobuf.descriptor.FileDescriptor = ... +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor +@typing.final class DoubleValue(google.protobuf.message.Message): """Wrapper message for `double`. The JSON representation for `DoubleValue` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.float = ... + value: builtins.float """The double value.""" + def __init__(self, *, value: builtins.float | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.float = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___DoubleValue = DoubleValue +@typing.final class FloatValue(google.protobuf.message.Message): """Wrapper message for `float`. The JSON representation for `FloatValue` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.float = ... + value: builtins.float """The float value.""" + def __init__(self, *, value: builtins.float | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.float = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___FloatValue = FloatValue +@typing.final class Int64Value(google.protobuf.message.Message): """Wrapper message for `int64`. The JSON representation for `Int64Value` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.int = ... + value: builtins.int """The int64 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___Int64Value = Int64Value +@typing.final class UInt64Value(google.protobuf.message.Message): """Wrapper message for `uint64`. The JSON representation for `UInt64Value` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.int = ... + value: builtins.int """The uint64 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___UInt64Value = UInt64Value +@typing.final class Int32Value(google.protobuf.message.Message): """Wrapper message for `int32`. The JSON representation for `Int32Value` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.int = ... + value: builtins.int """The int32 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___Int32Value = Int32Value +@typing.final class UInt32Value(google.protobuf.message.Message): """Wrapper message for `uint32`. The JSON representation for `UInt32Value` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.int = ... + value: builtins.int """The uint32 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___UInt32Value = UInt32Value +@typing.final class BoolValue(google.protobuf.message.Message): """Wrapper message for `bool`. The JSON representation for `BoolValue` is JSON `true` and `false`. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.bool = ... + value: builtins.bool """The bool value.""" + def __init__(self, *, value: builtins.bool | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.bool = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___BoolValue = BoolValue +@typing.final class StringValue(google.protobuf.message.Message): """Wrapper message for `string`. The JSON representation for `StringValue` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: typing.Text = ... + value: builtins.str """The string value.""" + def __init__(self, *, value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : typing.Text = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___StringValue = StringValue +@typing.final class BytesValue(google.protobuf.message.Message): """Wrapper message for `bytes`. The JSON representation for `BytesValue` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. """ - DESCRIPTOR: google.protobuf.descriptor.Descriptor = ... + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + VALUE_FIELD_NUMBER: builtins.int - value: builtins.bytes = ... + value: builtins.bytes """The bytes value.""" + def __init__(self, *, value: builtins.bytes | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... - def __init__(self, - *, - value : builtins.bytes = ..., - ) -> None: ... - def ClearField(self, field_name: typing_extensions.Literal["value",b"value"]) -> None: ... global___BytesValue = BytesValue diff --git a/stubs/psutil/@tests/stubtest_allowlist.txt b/stubs/psutil/@tests/stubtest_allowlist.txt index 1f62a50cb122..0ced949877a2 100644 --- a/stubs/psutil/@tests/stubtest_allowlist.txt +++ b/stubs/psutil/@tests/stubtest_allowlist.txt @@ -1,4 +1,7 @@ +# Stubtest does not support these platforms +psutil._psaix psutil._psbsd -psutil._psosx -psutil._psutil_windows -psutil._pswindows +psutil._pssunos +psutil._psutil_aix +psutil._psutil_bsd +psutil._psutil_sunos diff --git a/stubs/psutil/@tests/stubtest_allowlist_darwin.txt b/stubs/psutil/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..f1bc464326a5 --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,9 @@ +psutil._pslinux +psutil._pswindows +psutil._psutil_linux +psutil._psutil_windows + +# not always available on ARM64, but we test there +psutil.cpu_freq +psutil._psosx.cpu_freq +psutil.__all__ # cpu_freq is only added to __all__ at runtime when it is available diff --git a/stubs/psutil/@tests/stubtest_allowlist_linux.txt b/stubs/psutil/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..5433c30009cc --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,4 @@ +psutil._psosx +psutil._pswindows +psutil._psutil_osx +psutil._psutil_windows diff --git a/stubs/psutil/@tests/stubtest_allowlist_win32.txt b/stubs/psutil/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..1e781db20233 --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,4 @@ +psutil._psosx +psutil._pslinux +psutil._psutil_osx +psutil._psutil_linux diff --git a/stubs/psutil/@tests/test_cases/check_process_iter.py b/stubs/psutil/@tests/test_cases/check_process_iter.py new file mode 100644 index 000000000000..b31fe9d7eefe --- /dev/null +++ b/stubs/psutil/@tests/test_cases/check_process_iter.py @@ -0,0 +1,16 @@ +"""Test cases for psutil.process_iter and its cache_clear method.""" + +from __future__ import annotations + +import psutil + +# Test that process_iter can be called as a function +for proc in psutil.process_iter(): + break + +# Test that process_iter has cache_clear method +psutil.process_iter.cache_clear() + +# Test that cache_clear is callable +clear_method = psutil.process_iter.cache_clear +clear_method() diff --git a/stubs/psutil/METADATA.toml b/stubs/psutil/METADATA.toml index 295659a1622c..4700066c4768 100644 --- a/stubs/psutil/METADATA.toml +++ b/stubs/psutil/METADATA.toml @@ -1 +1,5 @@ -version = "5.8.*" +version = "7.2.2" +upstream-repository = "https://github.com/giampaolo/psutil" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] diff --git a/stubs/psutil/psutil/__init__.pyi b/stubs/psutil/psutil/__init__.pyi index 1eed72c28165..ccfc18019e92 100644 --- a/stubs/psutil/psutil/__init__.pyi +++ b/stubs/psutil/psutil/__init__.pyi @@ -1,8 +1,13 @@ import sys +from _typeshed import Incomplete, StrOrBytesPath +from collections.abc import Callable, Collection, Iterable, Iterator from contextlib import AbstractContextManager -from typing import Any, Callable, Iterable, Iterator, Tuple, TypeVar +from subprocess import _CMD, _ENV, _FILE +from types import TracebackType +from typing import Any, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated -from ._common import ( +from psutil._common import ( AIX as AIX, BSD as BSD, CONN_CLOSE as CONN_CLOSE, @@ -48,31 +53,136 @@ from ._common import ( NoSuchProcess as NoSuchProcess, TimeoutExpired as TimeoutExpired, ZombieProcess as ZombieProcess, - _Status, - pconn, - pcputimes, - pctxsw, - pgids, - pionice, - popenfile, - pthread, - puids, - sbattery, - sconn, - scpufreq, - scpustats, - sdiskio, - sdiskpart, - sdiskusage, - sfan, - shwtemp, - snetio, - snicaddr, - snicstats, - sswap, - suser, ) +from . import _ntuples as _ntp + +__all__ = [ + # exceptions + "Error", + "NoSuchProcess", + "ZombieProcess", + "AccessDenied", + "TimeoutExpired", + # constants + "version_info", + "__version__", + "STATUS_RUNNING", + "STATUS_IDLE", + "STATUS_SLEEPING", + "STATUS_DISK_SLEEP", + "STATUS_STOPPED", + "STATUS_TRACING_STOP", + "STATUS_ZOMBIE", + "STATUS_DEAD", + "STATUS_WAKING", + "STATUS_LOCKED", + "STATUS_WAITING", + "STATUS_PARKED", + "CONN_ESTABLISHED", + "CONN_SYN_SENT", + "CONN_SYN_RECV", + "CONN_FIN_WAIT1", + "CONN_FIN_WAIT2", + "CONN_TIME_WAIT", + "CONN_CLOSE", + "CONN_CLOSE_WAIT", + "CONN_LAST_ACK", + "CONN_LISTEN", + "CONN_CLOSING", + "CONN_NONE", + "AF_LINK", + "NIC_DUPLEX_FULL", + "NIC_DUPLEX_HALF", + "NIC_DUPLEX_UNKNOWN", + "POWER_TIME_UNKNOWN", + "POWER_TIME_UNLIMITED", + "BSD", + "FREEBSD", + "LINUX", + "NETBSD", + "OPENBSD", + "MACOS", + "OSX", + "POSIX", + "SUNOS", + "WINDOWS", + "AIX", + # classes + "Process", + "Popen", + # functions + "pid_exists", + "pids", + "process_iter", + "wait_procs", + "virtual_memory", + "swap_memory", + "cpu_times", + "cpu_percent", + "cpu_times_percent", + "cpu_count", + "cpu_stats", + "cpu_freq", + "getloadavg", + "net_io_counters", + "net_connections", + "net_if_addrs", + "net_if_stats", + "disk_io_counters", + "disk_partitions", + "disk_usage", + "sensors_battery", + "users", + "boot_time", + "heap_info", + "heap_trim", +] + +if sys.platform == "linux": + __all__ += [ + "PROCFS_PATH", + "IOPRIO_CLASS_NONE", + "IOPRIO_CLASS_RT", + "IOPRIO_CLASS_BE", + "IOPRIO_CLASS_IDLE", + "RLIMIT_AS", + "RLIMIT_CORE", + "RLIMIT_CPU", + "RLIMIT_DATA", + "RLIMIT_FSIZE", + "RLIMIT_LOCKS", + "RLIMIT_MEMLOCK", + "RLIMIT_MSGQUEUE", + "RLIMIT_NICE", + "RLIMIT_NOFILE", + "RLIMIT_NPROC", + "RLIMIT_RSS", + "RLIMIT_RTPRIO", + "RLIMIT_RTTIME", + "RLIMIT_SIGPENDING", + "RLIMIT_STACK", + "RLIM_INFINITY", + "sensors_temperatures", + "sensors_fans", + ] +elif sys.platform == "win32": + __all__ += [ + "win_service_iter", + "win_service_get", + "ABOVE_NORMAL_PRIORITY_CLASS", + "BELOW_NORMAL_PRIORITY_CLASS", + "HIGH_PRIORITY_CLASS", + "IDLE_PRIORITY_CLASS", + "NORMAL_PRIORITY_CLASS", + "REALTIME_PRIORITY_CLASS", + "IOPRIO_VERYLOW", + "IOPRIO_LOW", + "IOPRIO_NORMAL", + "IOPRIO_HIGH", + "CONN_DELETE_TCB", + ] + if sys.platform == "linux": from ._pslinux import ( IOPRIO_CLASS_BE as IOPRIO_CLASS_BE, @@ -80,6 +190,26 @@ if sys.platform == "linux": IOPRIO_CLASS_NONE as IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT as IOPRIO_CLASS_RT, ) + def sensors_temperatures(fahrenheit: bool = False) -> dict[str, list[_ntp.shwtemp]]: ... + def sensors_fans() -> dict[str, list[_ntp.sfan]]: ... + PROCFS_PATH: str + RLIMIT_AS: int + RLIMIT_CORE: int + RLIMIT_CPU: int + RLIMIT_DATA: int + RLIMIT_FSIZE: int + RLIMIT_LOCKS: int + RLIMIT_MEMLOCK: int + RLIMIT_MSGQUEUE: int + RLIMIT_NICE: int + RLIMIT_NOFILE: int + RLIMIT_NPROC: int + RLIMIT_RSS: int + RLIMIT_RTPRIO: int + RLIMIT_RTTIME: int + RLIMIT_SIGPENDING: int + RLIMIT_STACK: int + RLIM_INFINITY: int if sys.platform == "win32": from ._psutil_windows import ( ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, @@ -99,35 +229,55 @@ if sys.platform == "win32": win_service_iter as win_service_iter, ) +# Linux + glibc, Windows, macOS, FreeBSD, NetBSD: +def heap_info() -> _ntp.pheap: ... +def heap_trim() -> None: ... + if sys.platform == "linux": - from ._pslinux import pfullmem, pmem + from ._pslinux import sensors_battery as sensors_battery elif sys.platform == "darwin": - from ._psosx import pfullmem, pmem + from ._psosx import sensors_battery as sensors_battery elif sys.platform == "win32": - from ._pswindows import pfullmem, pmem + from ._pswindows import sensors_battery as sensors_battery else: - pmem = Any - pfullmem = Any + def sensors_battery(): ... -if sys.platform == "linux": - PROCFS_PATH: str AF_LINK: int version_info: tuple[int, int, int] __version__: str __author__: str +_Status: TypeAlias = Literal[ + "running", + "sleeping", + "disk-sleep", + "stopped", + "tracing-stop", + "zombie", + "dead", + "wake-kill", + "waking", + "idle", + "locked", + "waiting", + "suspended", + "parked", +] + class Process: - def __init__(self, pid: int | None = ...) -> None: ... + def __init__(self, pid: int | None = None) -> None: ... def __eq__(self, other: object) -> bool: ... def __ne__(self, other: object) -> bool: ... def __hash__(self) -> int: ... @property def pid(self) -> int: ... + # Only present if attrs argument is passed to process_iter + info: dict[str, Incomplete] def oneshot(self) -> AbstractContextManager[None]: ... def as_dict( - self, attrs: list[str] | Tuple[str, ...] | set[str] | frozenset[str] | None = ..., ad_value: Any | None = ... - ) -> dict[str, Any]: ... - def parent(self) -> Process: ... + self, attrs: list[str] | tuple[str, ...] | set[str] | frozenset[str] | None = None, ad_value=None + ) -> dict[str, Incomplete]: ... + def parent(self) -> Process | None: ... def parents(self) -> list[Process]: ... def is_running(self) -> bool: ... def ppid(self) -> int: ... @@ -138,102 +288,188 @@ class Process: def username(self) -> str: ... def create_time(self) -> float: ... def cwd(self) -> str: ... - def nice(self, value: int | None = ...) -> int: ... + def nice(self, value: int | None = None) -> int: ... if sys.platform != "win32": - def uids(self) -> puids: ... - def gids(self) -> pgids: ... + def uids(self) -> _ntp.puids: ... + def gids(self) -> _ntp.pgids: ... def terminal(self) -> str: ... def num_fds(self) -> int: ... if sys.platform != "darwin": - def io_counters(self): ... - def ionice(self, ioclass: int | None = ..., value: int | None = ...) -> pionice: ... - if sys.platform == "linux": - def rlimit(self, resource: int, limits: tuple[int, int] | None = ...) -> tuple[int, int]: ... - if sys.platform != "darwin": - def cpu_affinity(self, cpus: list[int] | None = ...) -> list[int] | None: ... + def io_counters(self) -> _ntp.pio: ... + def ionice(self, ioclass: int | None = None, value: int | None = None) -> _ntp.pionice: ... + + @overload + def cpu_affinity(self, cpus: None = None) -> list[int]: ... + @overload + def cpu_affinity(self, cpus: list[int]) -> None: ... + + @overload + def memory_maps(self, grouped: Literal[True] = True) -> list[_ntp.pmmap_grouped]: ... + @overload + def memory_maps(self, grouped: Literal[False]) -> list[_ntp.pmmap_ext]: ... + @overload + def memory_maps(self, grouped: bool) -> list[_ntp.pmmap_grouped] | list[_ntp.pmmap_ext]: ... + if sys.platform == "linux": + def rlimit(self, resource: int, limits: tuple[int, int] | None = None) -> tuple[int, int]: ... def cpu_num(self) -> int: ... + def environ(self) -> dict[str, str]: ... if sys.platform == "win32": def num_handles(self) -> int: ... - def num_ctx_switches(self) -> pctxsw: ... + + def num_ctx_switches(self) -> _ntp.pctxsw: ... def num_threads(self) -> int: ... - def threads(self) -> list[pthread]: ... - def children(self, recursive: bool = ...) -> list[Process]: ... - def cpu_percent(self, interval: float | None = ...) -> float: ... - def cpu_times(self) -> pcputimes: ... - def memory_info(self) -> pmem: ... - def memory_info_ex(self) -> pmem: ... - def memory_full_info(self) -> pfullmem: ... - def memory_percent(self, memtype: str = ...) -> float: ... - if sys.platform != "darwin": - def memory_maps(self, grouped: bool = ...): ... - def open_files(self) -> list[popenfile]: ... - def connections(self, kind: str = ...) -> list[pconn]: ... + def threads(self) -> list[_ntp.pthread]: ... + def children(self, recursive: bool = False) -> list[Process]: ... + def cpu_percent(self, interval: float | None = None) -> float: ... + def cpu_times(self) -> _ntp.pcputimes: ... + def memory_info(self) -> _ntp.pmem: ... + def memory_full_info(self) -> _ntp.pfullmem: ... + def memory_percent(self, memtype: str = "rss") -> float: ... + def open_files(self) -> list[_ntp.popenfile]: ... + @deprecated('use "net_connections" method instead') + def connections(self, kind: str = "inet") -> list[_ntp.pconn]: ... def send_signal(self, sig: int) -> None: ... def suspend(self) -> None: ... def resume(self) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... - def wait(self, timeout: int | None = ...) -> int: ... - -_Popen = TypeVar("_Popen", bound="Popen") + def wait(self, timeout: float | None = None) -> int: ... + def net_connections(self, kind: str = "inet") -> list[_ntp.pconn]: ... class Popen(Process): - def __init__(self, *args, **kwargs) -> None: ... - def __enter__(self: _Popen) -> _Popen: ... - def __exit__(self, *args, **kwargs) -> None: ... + # sync with subprocess.Popen.__init__: + if sys.version_info >= (3, 11): + def __init__( + self, + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + else: + def __init__( + self, + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... def __getattribute__(self, name: str) -> Any: ... + def __dir__(self) -> list[str]: ... + +@type_check_only +class _ProcessIterCallable(Protocol): + def __call__( + self, attrs: list[str] | tuple[str, ...] | set[str] | frozenset[str] | None = None, ad_value=None + ) -> Iterator[Process]: ... + def cache_clear(self) -> None: ... def pids() -> list[int]: ... def pid_exists(pid: int) -> bool: ... -def process_iter( - attrs: list[str] | Tuple[str, ...] | set[str] | frozenset[str] | None = ..., ad_value: Any | None = ... -) -> Iterator[Process]: ... + +process_iter: _ProcessIterCallable + def wait_procs( - procs: Iterable[Process], timeout: float | None = ..., callback: Callable[[Process], Any] | None = ... + procs: Iterable[Process], timeout: float | None = None, callback: Callable[[Process], object] | None = None ) -> tuple[list[Process], list[Process]]: ... -def cpu_count(logical: bool = ...) -> int: ... -def cpu_times(percpu: bool = ...): ... -def cpu_percent(interval: float | None = ..., percpu: bool = ...) -> float: ... -def cpu_times_percent(interval: float | None = ..., percpu: bool = ...): ... -def cpu_stats() -> scpustats: ... -def cpu_freq(percpu: bool = ...) -> scpufreq: ... +def cpu_count(logical: bool = True) -> int | None: ... + +@overload +def cpu_freq(percpu: Literal[False] = False) -> _ntp.scpufreq: ... +@overload +def cpu_freq(percpu: Literal[True]) -> list[_ntp.scpufreq]: ... + +@overload +def cpu_times(percpu: Literal[False] = False) -> _ntp.scputimes: ... +@overload +def cpu_times(percpu: Literal[True]) -> list[_ntp.scputimes]: ... + +@overload +def cpu_percent(interval: float | None = None, percpu: Literal[False] = False) -> float: ... +@overload +def cpu_percent(interval: float | None, percpu: Literal[True]) -> list[float]: ... +@overload +def cpu_percent(*, percpu: Literal[True]) -> list[float]: ... + +@overload +def cpu_times_percent(interval: float | None = None, percpu: Literal[False] = False) -> _ntp.scputimes: ... +@overload +def cpu_times_percent(interval: float | None, percpu: Literal[True]) -> list[_ntp.scputimes]: ... +@overload +def cpu_times_percent(*, percpu: Literal[True]) -> list[_ntp.scputimes]: ... + +def cpu_stats() -> _ntp.scpustats: ... def getloadavg() -> tuple[float, float, float]: ... -def virtual_memory(): ... -def swap_memory() -> sswap: ... -def disk_usage(path: str) -> sdiskusage: ... -def disk_partitions(all: bool = ...) -> list[sdiskpart]: ... -def disk_io_counters(perdisk: bool = ..., nowrap: bool = ...) -> sdiskio: ... -def net_io_counters(pernic: bool = ..., nowrap: bool = ...) -> snetio: ... -def net_connections(kind: str = ...) -> list[sconn]: ... -def net_if_addrs() -> dict[str, list[snicaddr]]: ... -def net_if_stats() -> dict[str, snicstats]: ... +def virtual_memory() -> _ntp.svmem: ... +def swap_memory() -> _ntp.sswap: ... +def disk_usage(path: str) -> _ntp.sdiskusage: ... +def disk_partitions(all: bool = False) -> list[_ntp.sdiskpart]: ... -if sys.platform == "linux": - def sensors_temperatures(fahrenheit: bool = ...) -> dict[str, list[shwtemp]]: ... - def sensors_fans() -> dict[str, list[sfan]]: ... +# TODO: Incorrect sdiskio for BSD systems: +@overload +def disk_io_counters(perdisk: Literal[False] = False, nowrap: bool = True) -> _ntp.sdiskio | None: ... +@overload +def disk_io_counters(perdisk: Literal[True], nowrap: bool = True) -> dict[str, _ntp.sdiskio]: ... -if sys.platform != "win32": - def sensors_battery() -> sbattery | None: ... +@overload +def net_io_counters(pernic: Literal[False] = False, nowrap: bool = True) -> _ntp.snetio: ... +@overload +def net_io_counters(pernic: Literal[True], nowrap: bool = True) -> dict[str, _ntp.snetio]: ... +def net_connections(kind: str = "inet") -> list[_ntp.sconn]: ... +def net_if_addrs() -> dict[str, list[_ntp.snicaddr]]: ... +def net_if_stats() -> dict[str, _ntp.snicstats]: ... def boot_time() -> float: ... -def users() -> list[suser]: ... - -if sys.platform == "linux": - RLIMIT_AS: int - RLIMIT_CORE: int - RLIMIT_CPU: int - RLIMIT_DATA: int - RLIMIT_FSIZE: int - RLIMIT_LOCKS: int - RLIMIT_MEMLOCK: int - RLIMIT_MSGQUEUE: int - RLIMIT_NICE: int - RLIMIT_NOFILE: int - RLIMIT_NPROC: int - RLIMIT_RSS: int - RLIMIT_RTPRIO: int - RLIMIT_SIGPENDING: int - RLIMIT_STACK: int - RLIM_INFINITY: int +def users() -> list[_ntp.suser]: ... diff --git a/stubs/psutil/psutil/_common.pyi b/stubs/psutil/psutil/_common.pyi index 9fa49d105581..e7a974bc77cc 100644 --- a/stubs/psutil/psutil/_common.pyi +++ b/stubs/psutil/psutil/_common.pyi @@ -1,297 +1,253 @@ import enum -from _typeshed import StrOrBytesPath, SupportsWrite -from socket import AddressFamily, SocketKind -from typing import Any, Callable, NamedTuple, TypeVar, overload -from typing_extensions import Literal - -POSIX: bool -WINDOWS: bool -LINUX: bool -MACOS: bool -OSX: bool -FREEBSD: bool -OPENBSD: bool -NETBSD: bool -BSD: bool -SUNOS: bool -AIX: bool - -STATUS_RUNNING: Literal["running"] -STATUS_SLEEPING: Literal["sleeping"] -STATUS_DISK_SLEEP: Literal["disk-sleep"] -STATUS_STOPPED: Literal["stopped"] -STATUS_TRACING_STOP: Literal["tracing-stop"] -STATUS_ZOMBIE: Literal["zombie"] -STATUS_DEAD: Literal["dead"] -STATUS_WAKE_KILL: Literal["wake-kill"] -STATUS_WAKING: Literal["waking"] -STATUS_IDLE: Literal["idle"] -STATUS_LOCKED: Literal["locked"] -STATUS_WAITING: Literal["waiting"] -STATUS_SUSPENDED: Literal["suspended"] -STATUS_PARKED: Literal["parked"] - -_Status = Literal[ - "running", - "sleeping", - "disk-sleep", - "stopped", - "tracing-stop", - "zombie", - "dead", - "wake-kill", - "waking", - "idle", - "locked", - "waiting", - "suspended", - "parked", -] - -CONN_ESTABLISHED: str -CONN_SYN_SENT: str -CONN_SYN_RECV: str -CONN_FIN_WAIT1: str -CONN_FIN_WAIT2: str -CONN_TIME_WAIT: str -CONN_CLOSE: str -CONN_CLOSE_WAIT: str -CONN_LAST_ACK: str -CONN_LISTEN: str -CONN_CLOSING: str -CONN_NONE: str -NIC_DUPLEX_FULL: int -NIC_DUPLEX_HALF: int -NIC_DUPLEX_UNKNOWN: int +import io +import sys +import threading +from _typeshed import ConvertibleToFloat, FileDescriptorOrPath, Incomplete, StrOrBytesPath, SupportsWrite +from collections import defaultdict +from collections.abc import Callable +from socket import AF_INET6 as AF_INET6, AddressFamily, SocketKind +from typing import BinaryIO, Final, ParamSpec, SupportsIndex, TypeVar, overload + +from . import _ntuples as ntp + +POSIX: Final[bool] +WINDOWS: Final[bool] +LINUX: Final[bool] +MACOS: Final[bool] +OSX: Final[bool] +FREEBSD: Final[bool] +OPENBSD: Final[bool] +NETBSD: Final[bool] +BSD: Final[bool] +SUNOS: Final[bool] +AIX: Final[bool] + +STATUS_RUNNING: Final = "running" +STATUS_SLEEPING: Final = "sleeping" +STATUS_DISK_SLEEP: Final = "disk-sleep" +STATUS_STOPPED: Final = "stopped" +STATUS_TRACING_STOP: Final = "tracing-stop" +STATUS_ZOMBIE: Final = "zombie" +STATUS_DEAD: Final = "dead" +STATUS_WAKE_KILL: Final = "wake-kill" +STATUS_WAKING: Final = "waking" +STATUS_IDLE: Final = "idle" +STATUS_LOCKED: Final = "locked" +STATUS_WAITING: Final = "waiting" +STATUS_SUSPENDED: Final = "suspended" +STATUS_PARKED: Final = "parked" + +CONN_ESTABLISHED: Final = "ESTABLISHED" +CONN_SYN_SENT: Final = "SYN_SENT" +CONN_SYN_RECV: Final = "SYN_RECV" +CONN_FIN_WAIT1: Final = "FIN_WAIT1" +CONN_FIN_WAIT2: Final = "FIN_WAIT2" +CONN_TIME_WAIT: Final = "TIME_WAIT" +CONN_CLOSE: Final = "CLOSE" +CONN_CLOSE_WAIT: Final = "CLOSE_WAIT" +CONN_LAST_ACK: Final = "LAST_ACK" +CONN_LISTEN: Final = "LISTEN" +CONN_CLOSING: Final = "CLOSING" +CONN_NONE: Final = "NONE" class NicDuplex(enum.IntEnum): - NIC_DUPLEX_FULL: int - NIC_DUPLEX_HALF: int - NIC_DUPLEX_UNKNOWN: int + NIC_DUPLEX_FULL = 2 + NIC_DUPLEX_HALF = 1 + NIC_DUPLEX_UNKNOWN = 0 -POWER_TIME_UNKNOWN: int -POWER_TIME_UNLIMITED: int +NIC_DUPLEX_FULL: Final = NicDuplex.NIC_DUPLEX_FULL +NIC_DUPLEX_HALF: Final = NicDuplex.NIC_DUPLEX_HALF +NIC_DUPLEX_UNKNOWN: Final = NicDuplex.NIC_DUPLEX_UNKNOWN class BatteryTime(enum.IntEnum): - POWER_TIME_UNKNOWN: int - POWER_TIME_UNLIMITED: int - -ENCODING: str -ENCODING_ERRS: str - -class sswap(NamedTuple): - total: int - used: int - free: int - percent: float - sin: int - sout: int - -class sdiskusage(NamedTuple): - total: int - used: int - free: int - percent: float - -class sdiskio(NamedTuple): - read_count: int - write_count: int - read_bytes: int - write_bytes: int - read_time: int - write_time: int - -class sdiskpart(NamedTuple): - device: str - mountpoint: str - fstype: str - opts: str - maxfile: int - maxpath: int - -class snetio(NamedTuple): - bytes_sent: int - bytes_recv: int - packets_sent: int - packets_recv: int - errin: int - errout: int - dropin: int - dropout: int - -class suser(NamedTuple): - name: str - terminal: str | None - host: str | None - started: float - pid: str - -class sconn(NamedTuple): - fd: int - family: AddressFamily - type: SocketKind - laddr: addr | tuple[()] - raddr: addr | tuple[()] - status: str - pid: int - -class snicaddr(NamedTuple): - family: AddressFamily - address: str - netmask: str | None - broadcast: str | None - ptp: str | None - -class snicstats(NamedTuple): - isup: bool - duplex: int - speed: int - mtu: int - -class scpustats(NamedTuple): - ctx_switches: int - interrupts: int - soft_interrupts: int - syscalls: int - -class scpufreq(NamedTuple): - current: float - min: float - max: float - -class shwtemp(NamedTuple): - label: str - current: float - high: float | None - critical: float | None - -class sbattery(NamedTuple): - percent: int - secsleft: int - power_plugged: bool + POWER_TIME_UNKNOWN = -1 + POWER_TIME_UNLIMITED = -2 -class sfan(NamedTuple): - label: str - current: int +POWER_TIME_UNKNOWN: Final = BatteryTime.POWER_TIME_UNKNOWN +POWER_TIME_UNLIMITED: Final = BatteryTime.POWER_TIME_UNLIMITED -class pcputimes(NamedTuple): - user: float - system: float - children_user: float - children_system: float - -class popenfile(NamedTuple): - path: str - fd: int - -class pthread(NamedTuple): - id: int - user_time: float - system_time: float - -class puids(NamedTuple): - real: int - effective: int - saved: int - -class pgids(NamedTuple): - real: int - effective: int - saved: int - -class pio(NamedTuple): - read_count: int - write_count: int - read_bytes: int - write_bytes: int - -class pionice(NamedTuple): - ioclass: int - value: int - -class pctxsw(NamedTuple): - voluntary: int - involuntary: int - -class pconn(NamedTuple): - fd: int - family: AddressFamily - type: SocketKind - laddr: addr - raddr: addr - status: str - -class addr(NamedTuple): - ip: str - port: int +ENCODING: Final[str] +ENCODING_ERRS: Final[str] conn_tmap: dict[str, tuple[list[AddressFamily], list[SocketKind]]] -class Error(Exception): - __module__: str - msg: Any - def __init__(self, msg: str = ...) -> None: ... +class Error(Exception): ... class NoSuchProcess(Error): - __module__: str - pid: Any - name: Any - msg: Any - def __init__(self, pid, name: Any | None = ..., msg: Any | None = ...) -> None: ... + pid: int + name: str | None + msg: str + def __init__(self, pid: int, name: str | None = None, msg: str | None = None) -> None: ... class ZombieProcess(NoSuchProcess): - __module__: str - pid: Any - ppid: Any - name: Any - msg: Any - def __init__(self, pid, name: Any | None = ..., ppid: Any | None = ..., msg: Any | None = ...) -> None: ... + ppid: int | None + def __init__(self, pid: int, name: str | None = None, ppid: int | None = None, msg: str | None = None) -> None: ... class AccessDenied(Error): - __module__: str - pid: Any - name: Any - msg: Any - def __init__(self, pid: Any | None = ..., name: Any | None = ..., msg: Any | None = ...) -> None: ... + pid: int | None + name: str | None + msg: str + def __init__(self, pid: int | None = None, name: str | None = None, msg: str | None = None) -> None: ... class TimeoutExpired(Error): - __module__: str - seconds: Any - pid: Any - name: Any - def __init__(self, seconds, pid: Any | None = ..., name: Any | None = ...) -> None: ... + seconds: float + pid: int | None + name: str | None + msg: str + def __init__(self, seconds: float, pid: int | None = None, name: str | None = None) -> None: ... -_Func = TypeVar("_Func", bound=Callable[..., Any]) +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T") -def usage_percent(used, total, round_: int | None = ...) -> float: ... -def memoize(fun: _Func) -> _Func: ... -def memoize_when_activated(fun: _Func) -> _Func: ... +def usage_percent(used: ConvertibleToFloat, total: float, round_: SupportsIndex | None = None) -> float: ... + +# returned function has `cache_clear()` attribute: +def memoize(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + +# returned function has `cache_activate(proc)` and `cache_deactivate(proc)` attributes: +def memoize_when_activated(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... def isfile_strict(path: StrOrBytesPath) -> bool: ... def path_exists_strict(path: StrOrBytesPath) -> bool: ... def supports_ipv6() -> bool: ... -def parse_environ_block(data): ... +def parse_environ_block(data: str) -> dict[str, str]: ... def sockfam_to_enum(num: int) -> AddressFamily: ... def socktype_to_enum(num: int) -> SocketKind: ... + @overload -def conn_to_ntuple(fd: int, fam: int, type_: int, laddr, raddr, status: str, status_map, pid: int) -> sconn: ... +def conn_to_ntuple( + fd: int, + fam: int, + type_: int, + laddr: ntp.addr | tuple[str, int] | tuple[()], + raddr: ntp.addr | tuple[str, int] | tuple[()], + status: int | str, + status_map: dict[int, str] | dict[str, str], + pid: int, +) -> ntp.sconn: ... @overload -def conn_to_ntuple(fd: int, fam: int, type_: int, laddr, raddr, status: str, status_map, pid: None = ...) -> pconn: ... -def deprecated_method(replacement: str) -> Callable[[_Func], _Func]: ... +def conn_to_ntuple( + fd: int, + fam: int, + type_: int, + laddr: ntp.addr | tuple[str, int] | tuple[()], + raddr: ntp.addr | tuple[str, int] | tuple[()], + status: int | str, + status_map: dict[int, str] | dict[str, str], + pid: None = None, +) -> ntp.pconn: ... + +def deprecated_method(replacement: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... class _WrapNumbers: - lock: Any - cache: Any - reminders: Any - reminder_keys: Any + lock: threading.Lock + cache: dict[str, dict[str, tuple[int, ...]]] + reminders: dict[str, defaultdict[Incomplete, int]] + reminder_keys: dict[str, defaultdict[Incomplete, set[Incomplete]]] def __init__(self) -> None: ... - def run(self, input_dict, name): ... - def cache_clear(self, name: Any | None = ...) -> None: ... - def cache_info(self): ... + def run(self, input_dict: dict[str, tuple[int, ...]], name: str) -> dict[str, tuple[int, ...]]: ... + def cache_clear(self, name: str | None = None) -> None: ... + def cache_info( + self, + ) -> tuple[ + dict[str, dict[str, tuple[int, ...]]], + dict[str, defaultdict[Incomplete, int]], + dict[str, defaultdict[Incomplete, set[Incomplete]]], + ]: ... + +def wrap_numbers(input_dict: dict[str, tuple[int, ...]], name: str) -> dict[str, tuple[int, ...]]: ... +def open_binary(fname: FileDescriptorOrPath) -> BinaryIO: ... +def open_text(fname: FileDescriptorOrPath) -> io.TextIOWrapper: ... + +@overload +def cat(fname: FileDescriptorOrPath, _open: Callable[[FileDescriptorOrPath], io.TextIOWrapper] = ...) -> str: ... +@overload +def cat( + fname: FileDescriptorOrPath, fallback: _T = ..., _open: Callable[[FileDescriptorOrPath], io.TextIOWrapper] = ... +) -> str | _T: ... -def wrap_numbers(input_dict, name: str): ... -def bytes2human(n: int, format: str = ...) -> str: ... +@overload +def bcat(fname: FileDescriptorOrPath) -> str: ... +@overload +def bcat(fname: FileDescriptorOrPath, fallback: _T = ...) -> str | _T: ... + +def bytes2human(n: int, format: str = "%(value).1f%(symbol)s") -> str: ... def get_procfs_path() -> str: ... -def term_supports_colors(file: SupportsWrite[str] = ...) -> bool: ... -def hilite(s: str, color: str | None = ..., bold: bool = ...) -> str: ... -def print_color(s: str, color: str | None = ..., bold: bool = ..., file: SupportsWrite[str] = ...) -> None: ... -def debug(msg) -> None: ... +def decode(s: bytes) -> str: ... +def term_supports_colors(file: SupportsWrite[str] = sys.stdout) -> bool: ... +def hilite(s: str, color: str | None = None, bold: bool = False) -> str: ... +def print_color(s: str, color: str | None = None, bold: bool = False, file: SupportsWrite[str] = sys.stdout) -> None: ... +def debug(msg: str | Exception) -> None: ... + +__all__ = [ + # OS constants + "FREEBSD", + "BSD", + "LINUX", + "NETBSD", + "OPENBSD", + "MACOS", + "OSX", + "POSIX", + "SUNOS", + "WINDOWS", + # connection constants + "CONN_CLOSE", + "CONN_CLOSE_WAIT", + "CONN_CLOSING", + "CONN_ESTABLISHED", + "CONN_FIN_WAIT1", + "CONN_FIN_WAIT2", + "CONN_LAST_ACK", + "CONN_LISTEN", + "CONN_NONE", + "CONN_SYN_RECV", + "CONN_SYN_SENT", + "CONN_TIME_WAIT", + # net constants + "NIC_DUPLEX_FULL", + "NIC_DUPLEX_HALF", + "NIC_DUPLEX_UNKNOWN", + # process status constants + "STATUS_DEAD", + "STATUS_DISK_SLEEP", + "STATUS_IDLE", + "STATUS_LOCKED", + "STATUS_RUNNING", + "STATUS_SLEEPING", + "STATUS_STOPPED", + "STATUS_SUSPENDED", + "STATUS_TRACING_STOP", + "STATUS_WAITING", + "STATUS_WAKE_KILL", + "STATUS_WAKING", + "STATUS_ZOMBIE", + "STATUS_PARKED", + # other constants + "ENCODING", + "ENCODING_ERRS", + "AF_INET6", + # utility functions + "conn_tmap", + "deprecated_method", + "isfile_strict", + "memoize", + "parse_environ_block", + "path_exists_strict", + "usage_percent", + "supports_ipv6", + "sockfam_to_enum", + "socktype_to_enum", + "wrap_numbers", + "open_text", + "open_binary", + "cat", + "bcat", + "bytes2human", + "conn_to_ntuple", + "debug", + # shell utils + "hilite", + "term_supports_colors", + "print_color", +] diff --git a/stubs/psutil/psutil/_compat.pyi b/stubs/psutil/psutil/_compat.pyi deleted file mode 100644 index 4031e23fd72d..000000000000 --- a/stubs/psutil/psutil/_compat.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from builtins import ( - ChildProcessError as ChildProcessError, - FileExistsError as FileExistsError, - FileNotFoundError as FileNotFoundError, - InterruptedError as InterruptedError, - PermissionError as PermissionError, - ProcessLookupError as ProcessLookupError, -) diff --git a/stubs/psutil/psutil/_ntuples.pyi b/stubs/psutil/psutil/_ntuples.pyi new file mode 100644 index 000000000000..7e47772cdf77 --- /dev/null +++ b/stubs/psutil/psutil/_ntuples.pyi @@ -0,0 +1,384 @@ +import sys +from _typeshed import Incomplete +from socket import AddressFamily, SocketKind +from typing import Any, NamedTuple + +# All named tuples are defined in this file, but due to the inability to detect some platforms, +# it was decided to store the correct named tuples inside platform-specific files. + +class sswap(NamedTuple): + total: int + used: int + free: int + percent: float + sin: int + sout: int + +class sdiskusage(NamedTuple): + total: int + used: int + free: int + percent: float + +# redefine for linux: +if sys.platform != "linux": + class sdiskio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_time: int + write_time: int + +class sdiskpart(NamedTuple): + device: str + mountpoint: str + fstype: str + opts: str + +class snetio(NamedTuple): + bytes_sent: int + bytes_recv: int + packets_sent: int + packets_recv: int + errin: int + errout: int + dropin: int + dropout: int + +class suser(NamedTuple): + name: str + terminal: str | None + host: str | None + started: float + pid: str + +class sconn(NamedTuple): + fd: int + family: AddressFamily + type: SocketKind + laddr: addr | tuple[()] + raddr: addr | tuple[()] + status: str + pid: int | None + +class snicaddr(NamedTuple): + family: AddressFamily + address: str + netmask: str | None + broadcast: str | None + ptp: str | None + +class snicstats(NamedTuple): + isup: bool + duplex: int + speed: int + mtu: int + flags: str + +class scpustats(NamedTuple): + ctx_switches: int + interrupts: int + soft_interrupts: int + syscalls: int + +class scpufreq(NamedTuple): + current: float + min: float + max: float + +class shwtemp(NamedTuple): + label: str + current: float + high: float | None + critical: float | None + +class sbattery(NamedTuple): + percent: int + secsleft: int + power_plugged: bool + +class sfan(NamedTuple): + label: str + current: int + +if sys.platform == "win32": + class pheap(NamedTuple): + heap_used: int + mmap_used: int + heap_count: int + +else: + # if LINUX or MACOS or BSD: + class pheap(NamedTuple): + heap_used: int + mmap_used: int + +# redefine for linux: +if sys.platform != "linux": + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + + class popenfile(NamedTuple): + path: str + fd: int + +class pthread(NamedTuple): + id: int + user_time: float + system_time: float + +class puids(NamedTuple): + real: int + effective: int + saved: int + +class pgids(NamedTuple): + real: int + effective: int + saved: int + +# redefine for linux and windows: +if sys.platform != "linux" and sys.platform != "win32": + class pio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + +class pionice(NamedTuple): + ioclass: int + value: int + +class pctxsw(NamedTuple): + voluntary: int + involuntary: int + +class pconn(NamedTuple): + fd: int + family: AddressFamily + type: SocketKind + laddr: addr + raddr: addr + status: str + +class addr(NamedTuple): + ip: str + port: int + +if sys.platform == "linux": + class scputimes(NamedTuple): + # Note: scputimes has different fields depending on exactly how Linux + # is setup, but we'll include the "complete" set of fields + user: float + nice: float + system: float + idle: float + iowait: float + irq: float + softirq: float + steal: float + guest: float + guest_nice: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + active: int + inactive: int + buffers: int + cached: int + shared: int + slab: int + + class sdiskio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_time: int + write_time: int + read_merged_count: int + write_merged_count: int + busy_time: int + + class popenfile(NamedTuple): + path: str + fd: int + position: int + mode: str + flags: int + + class pmem(NamedTuple): + rss: int + vms: int + shared: int + text: int + lib: int + data: int + dirty: int + + class pfullmem(NamedTuple): + rss: int + vms: int + shared: int + text: int + lib: int + data: int + dirty: int + uss: int + pss: int + swap: int + + class pmmap_grouped(NamedTuple): + path: str + rss: int + size: int + pss: int + shared_clean: int + shared_dirty: int + private_clean: int + private_dirty: int + referenced: int + anonymous: int + swap: int + + class pmmap_ext(NamedTuple): + addr: str + perms: str + path: str + rss: int + size: int + pss: int + shared_clean: int + shared_dirty: int + private_clean: int + private_dirty: int + referenced: int + anonymous: int + swap: int + + class pio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_chars: int + write_chars: int + + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + iowait: float + +elif sys.platform == "win32": + class scputimes(NamedTuple): + user: float + system: float + idle: float + interrupt: float + dpc: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + + class pmem(NamedTuple): + rss: int + vms: int + num_page_faults: int + peak_wset: int + wset: int + peak_paged_pool: int + paged_pool: int + peak_nonpaged_pool: int + nonpaged_pool: int + pagefile: int + peak_pagefile: int + private: int + + class pfullmem(NamedTuple): + rss: int + vms: int + num_page_faults: int + peak_wset: int + wset: int + peak_paged_pool: int + paged_pool: int + peak_nonpaged_pool: int + nonpaged_pool: int + pagefile: int + peak_pagefile: int + private: int + uss: int + + class pmmap_grouped(NamedTuple): + path: str + rss: int + + class pmmap_ext(NamedTuple): + addr: str + perms: str + path: str + rss: int + + class pio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + other_count: int + other_bytes: int + +elif sys.platform == "darwin": + class scputimes(NamedTuple): + user: float + nice: float + system: float + idle: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + active: int + inactive: int + wired: int + + class pmem(NamedTuple): + rss: int + vms: int + pfaults: int + pageins: int + + class pfullmem(NamedTuple): + rss: int + vms: int + pfaults: int + pageins: int + uss: int + +else: + # See _psbsd.pyi, _pssunos.pyi or _psaix.pyi + # BSD: svmem, scputimes, pmem, pfullmem, pcputimes, pmmap_grouped, pmmap_ext, sdiskio + # SUNOS: scputimes, pcputimes, svmem, pmem, pfullmem, pmmap_grouped, pmmap_ext + # AIX: pmem, pfullmem, scputimes, svmem + + scputimes = Incomplete + + class pmem(Any): ... + class pfullmem(Any): ... + class svmem(Any): ... diff --git a/stubs/psutil/psutil/_psaix.pyi b/stubs/psutil/psutil/_psaix.pyi new file mode 100644 index 000000000000..195fd25591e2 --- /dev/null +++ b/stubs/psutil/psutil/_psaix.pyi @@ -0,0 +1,112 @@ +import sys + +# sys.platform.startswith("aix"): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from collections.abc import Callable + from typing import Final, Literal, NamedTuple, ParamSpec, TypeVar, overload + + from psutil._common import ( + NIC_DUPLEX_FULL as NIC_DUPLEX_FULL, + NIC_DUPLEX_HALF as NIC_DUPLEX_HALF, + NIC_DUPLEX_UNKNOWN as NIC_DUPLEX_UNKNOWN, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + conn_to_ntuple as conn_to_ntuple, + get_procfs_path as get_procfs_path, + memoize_when_activated as memoize_when_activated, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_aix + + __extra__all__: Final[list[str]] + HAS_THREADS: Final[bool] + HAS_NET_IO_COUNTERS: Final[bool] + HAS_PROC_IO_COUNTERS: Final[bool] + PAGE_SIZE: Final[int] + AF_LINK: Final = 18 + PROC_STATUSES: Final[dict[int, str]] + TCP_STATUSES: Final[dict[int, str]] + proc_info_map: Final[dict[str, int]] + + class pmem(NamedTuple): + rss: int + vms: int + + pfullmem = pmem + + class scputimes(NamedTuple): + user: float + system: float + idle: float + iowait: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + def virtual_memory() -> svmem: ... + def swap_memory() -> ntp.sswap: ... + def cpu_times() -> scputimes: ... + def per_cpu_times() -> list[scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + + disk_io_counters = _psutil_aix.disk_io_counters + disk_usage = _psposix.disk_usage + + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + + net_if_addrs = _psutil_aix.net_if_addrs + net_io_counters = _psutil_aix.net_io_counters + + @overload + def net_connections(kind: str, _pid: Literal[-1] = -1) -> list[ntp.sconn]: ... + @overload + def net_connections(kind: str, _pid: int = -1) -> list[ntp.pconn]: ... + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + def pids() -> list[int]: ... + def pid_exists(pid: int | str) -> bool: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def create_time(self) -> float: ... + def num_threads(self) -> int: ... + def threads(self) -> list[ntp.pthread]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def ppid(self) -> int: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.puids: ... + def cpu_times(self) -> ntp.pcputimes: ... + def terminal(self) -> str | None: ... + def cwd(self) -> str: ... + def memory_info(self) -> pmem: ... + memory_full_info = memory_info + def status(self) -> str: ... + def open_files(self) -> list[ntp.popenfile]: ... + def num_fds(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def io_counters(self) -> ntp.pio: ... diff --git a/stubs/psutil/psutil/_psbsd.pyi b/stubs/psutil/psutil/_psbsd.pyi index 4e276e27b9c5..7b7a18140705 100644 --- a/stubs/psutil/psutil/_psbsd.pyi +++ b/stubs/psutil/psutil/_psbsd.pyi @@ -1,163 +1,213 @@ -from contextlib import AbstractContextManager -from typing import Any, NamedTuple - -from ._common import ( - FREEBSD as FREEBSD, - NETBSD as NETBSD, - OPENBSD as OPENBSD, - AccessDenied as AccessDenied, - NoSuchProcess as NoSuchProcess, - ZombieProcess as ZombieProcess, - conn_tmap as conn_tmap, - conn_to_ntuple as conn_to_ntuple, - memoize as memoize, - usage_percent as usage_percent, -) - -__extra__all__: Any -PROC_STATUSES: Any -TCP_STATUSES: Any -PAGESIZE: Any -AF_LINK: Any -HAS_PER_CPU_TIMES: Any -HAS_PROC_NUM_THREADS: Any -HAS_PROC_OPEN_FILES: Any -HAS_PROC_NUM_FDS: Any -kinfo_proc_map: Any - -class svmem(NamedTuple): - total: Any - available: Any - percent: Any - used: Any - free: Any - active: Any - inactive: Any - buffers: Any - cached: Any - shared: Any - wired: Any - -class scputimes(NamedTuple): - user: Any - nice: Any - system: Any - idle: Any - irq: Any - -class pmem(NamedTuple): - rss: Any - vms: Any - text: Any - data: Any - stack: Any - -pfullmem = pmem - -class pcputimes(NamedTuple): - user: Any - system: Any - children_user: Any - children_system: Any - -class pmmap_grouped(NamedTuple): - path: Any - rss: Any - private: Any - ref_count: Any - shadow_count: Any - -class pmmap_ext(NamedTuple): - addr: Any - perms: Any - path: Any - rss: Any - private: Any - ref_count: Any - shadow_count: Any - -class sdiskio(NamedTuple): - read_count: Any - write_count: Any - read_bytes: Any - write_bytes: Any - read_time: Any - write_time: Any - busy_time: Any - -def virtual_memory(): ... -def swap_memory(): ... -def cpu_times(): ... -def per_cpu_times(): ... -def cpu_count_logical(): ... -def cpu_count_physical(): ... -def cpu_stats(): ... -def disk_partitions(all: bool = ...): ... - -disk_usage: Any -disk_io_counters: Any -net_io_counters: Any -net_if_addrs: Any - -def net_if_stats(): ... -def net_connections(kind): ... -def sensors_battery(): ... -def sensors_temperatures(): ... -def cpu_freq(): ... -def boot_time(): ... -def users(): ... -def pids(): ... -def pid_exists(pid): ... -def is_zombie(pid): ... -def wrap_exceptions(fun): ... -def wrap_exceptions_procfs(inst) -> AbstractContextManager[None]: ... - -class Process: - pid: Any - def __init__(self, pid) -> None: ... - def oneshot(self): ... - def oneshot_enter(self) -> None: ... - def oneshot_exit(self) -> None: ... - def name(self): ... - def exe(self): ... - def cmdline(self): ... - def environ(self): ... - def terminal(self): ... - def ppid(self): ... - def uids(self): ... - def gids(self): ... - def cpu_times(self): ... - def cpu_num(self): ... - def memory_info(self): ... - memory_full_info: Any - def create_time(self): ... - def num_threads(self): ... - def num_ctx_switches(self): ... - def threads(self): ... - def connections(self, kind: str = ...): ... - def wait(self, timeout: Any | None = ...): ... - def nice_get(self): ... - def nice_set(self, value): ... - def status(self): ... - def io_counters(self): ... - def cwd(self): ... - class nt_mmap_grouped(NamedTuple): - path: Any - rss: Any - private: Any - ref_count: Any - shadow_count: Any - class nt_mmap_ext(NamedTuple): - addr: Any - perms: Any - path: Any - rss: Any - private: Any - ref_count: Any - shadow_count: Any - def open_files(self): ... - def num_fds(self): ... - def cpu_affinity_get(self): ... - def cpu_affinity_set(self, cpus) -> None: ... - def memory_maps(self): ... - def rlimit(self, resource, limits: Any | None = ...): ... +import sys + +# sys.platform.startswith(("freebsd", "midnightbsd", "openbsd", "netbsd")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from _typeshed import Incomplete + from collections import defaultdict + from collections.abc import Callable + from contextlib import AbstractContextManager + from typing import Final, NamedTuple, ParamSpec, TypeVar, overload + + from psutil._common import ( + FREEBSD as FREEBSD, + NETBSD as NETBSD, + OPENBSD as OPENBSD, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + conn_tmap as conn_tmap, + conn_to_ntuple as conn_to_ntuple, + memoize as memoize, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_bsd + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + PROC_STATUSES: Final[dict[int, str]] + TCP_STATUSES: Final[dict[int, str]] + PAGESIZE: Final[int] + AF_LINK: Final = _psutil_bsd.AF_LINK + HAS_PROC_NUM_THREADS: Final[bool] + kinfo_proc_map: Final[dict[str, int]] + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + active: int + inactive: int + buffers: int + cached: int + shared: int + wired: int + + class scputimes(NamedTuple): + user: float + nice: float + system: float + idle: float + irq: float + + class pmem(NamedTuple): + rss: int + vms: int + text: int + data: int + stack: int + + pfullmem = pmem + + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + + class pmmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + class pmmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + class sdiskio(NamedTuple): + read_count: Incomplete + write_count: Incomplete + read_bytes: Incomplete + write_bytes: Incomplete + read_time: Incomplete + write_time: Incomplete + busy_time: Incomplete + + def virtual_memory() -> svmem: ... + def swap_memory() -> ntp.sswap: ... + heap_info = _psutil_bsd.heap_info # only FreeBSD and NetBSD + heap_trim = _psutil_bsd.heap_trim # only FreeBSD and NetBSD + def cpu_times() -> scputimes: ... + def per_cpu_times() -> list[scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + + disk_usage = _psposix.disk_usage + disk_io_counters = _psutil_bsd.disk_io_counters + net_io_counters = _psutil_bsd.net_io_counters + net_if_addrs = _psutil_bsd.net_if_addrs + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def net_connections(kind: str) -> list[ntp.sconn]: ... + def sensors_battery() -> ntp.sbattery | None: ... # only FreeBSD + def sensors_temperatures() -> defaultdict[str, list[ntp.shwtemp]]: ... # only FreeBSD + def cpu_freq() -> list[ntp.scpufreq]: ... # only FreeBSD and OpenBSD + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + + INIT_BOOT_TIME: Final[float] # only NetBSD + + def adjust_proc_create_time(ctime: float) -> float: ... # only NetBSD + def pids() -> list[int]: ... + def pid_exists(pid: int) -> bool: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + def wrap_exceptions_procfs(inst: Process) -> AbstractContextManager[None]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot( + self, + ) -> tuple[ + int, + int, + int, + int, + int, + int, + int, + int, + int, + float, + int, + int, + int, + int, + float, + float, + float, + float, + int, + int, + int, + int, + int, + int, + str, + ]: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def terminal(self) -> str | None: ... + def ppid(self) -> int: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.pgids: ... + def cpu_times(self) -> ntp.pcputimes: ... + def cpu_num(self) -> int: ... # only FreeBSD + def memory_info(self) -> pmem: ... + memory_full_info = memory_info + def create_time(self, monotonic: bool = False) -> float: ... + def num_threads(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def threads(self) -> list[ntp.pthread]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def status(self) -> str: ... + def io_counters(self) -> ntp.pio: ... + def cwd(self) -> str: ... + + class nt_mmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + class nt_mmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + def open_files(self) -> list[ntp.popenfile]: ... + def num_fds(self) -> int: ... + def cpu_affinity_get(self) -> list[int]: ... # only FreeBSD + def cpu_affinity_set(self, cpus: list[int]) -> None: ... # only FreeBSD + def memory_maps(self) -> list[tuple[str, str, str, int, int, int, int]]: ... # only FreeBSD + + @overload + def rlimit(self, resource: int, limits: tuple[int, int]) -> None: ... # only FreeBSD + @overload + def rlimit(self, resource: int, limits: None = None) -> tuple[int, int]: ... # only FreeBSD diff --git a/stubs/psutil/psutil/_pslinux.pyi b/stubs/psutil/psutil/_pslinux.pyi index 6794cfb3bd5b..34bb16456b44 100644 --- a/stubs/psutil/psutil/_pslinux.pyi +++ b/stubs/psutil/psutil/_pslinux.pyi @@ -1,206 +1,183 @@ -import enum -from typing import Any, NamedTuple - -from ._common import ( - NIC_DUPLEX_FULL as NIC_DUPLEX_FULL, - NIC_DUPLEX_HALF as NIC_DUPLEX_HALF, - NIC_DUPLEX_UNKNOWN as NIC_DUPLEX_UNKNOWN, - AccessDenied as AccessDenied, - NoSuchProcess as NoSuchProcess, - ZombieProcess as ZombieProcess, - isfile_strict as isfile_strict, - parse_environ_block as parse_environ_block, - path_exists_strict as path_exists_strict, - supports_ipv6 as supports_ipv6, - usage_percent as usage_percent, -) - -__extra__all__: Any -POWER_SUPPLY_PATH: str -HAS_SMAPS: Any -HAS_PROC_IO_PRIORITY: Any -HAS_CPU_AFFINITY: Any -CLOCK_TICKS: Any -PAGESIZE: Any -BOOT_TIME: Any -BIGFILE_BUFFERING: Any -LITTLE_ENDIAN: Any -DISK_SECTOR_SIZE: int -AF_LINK: Any -AddressFamily: Any -IOPRIO_CLASS_NONE: int -IOPRIO_CLASS_RT: int -IOPRIO_CLASS_BE: int -IOPRIO_CLASS_IDLE: int - -class IOPriority(enum.IntEnum): - IOPRIO_CLASS_NONE: int - IOPRIO_CLASS_RT: int - IOPRIO_CLASS_BE: int - IOPRIO_CLASS_IDLE: int - -PROC_STATUSES: Any -TCP_STATUSES: Any - -class svmem(NamedTuple): - total: Any - available: Any - percent: Any - used: Any - free: Any - active: Any - inactive: Any - buffers: Any - cached: Any - shared: Any - slab: Any - -class sdiskio(NamedTuple): - read_count: Any - write_count: Any - read_bytes: Any - write_bytes: Any - read_time: Any - write_time: Any - read_merged_count: Any - write_merged_count: Any - busy_time: Any - -class popenfile(NamedTuple): - path: Any - fd: Any - position: Any - mode: Any - flags: Any - -class pmem(NamedTuple): - rss: Any - vms: Any - shared: Any - text: Any - lib: Any - data: Any - dirty: Any - -pfullmem: Any - -class pmmap_grouped(NamedTuple): - path: Any - rss: Any - size: Any - pss: Any - shared_clean: Any - shared_dirty: Any - private_clean: Any - private_dirty: Any - referenced: Any - anonymous: Any - swap: Any - -pmmap_ext: Any - -class pio(NamedTuple): - read_count: Any - write_count: Any - read_bytes: Any - write_bytes: Any - read_chars: Any - write_chars: Any - -class pcputimes(NamedTuple): - user: Any - system: Any - children_user: Any - children_system: Any - iowait: Any - -def readlink(path): ... -def file_flags_to_mode(flags): ... -def is_storage_device(name): ... -def set_scputimes_ntuple(procfs_path) -> None: ... -def cat(fname, fallback=..., binary: bool = ...): ... - -scputimes: Any -prlimit: Any - -def calculate_avail_vmem(mems): ... -def virtual_memory(): ... -def swap_memory(): ... -def cpu_times(): ... -def per_cpu_times(): ... -def cpu_count_logical(): ... -def cpu_count_physical(): ... -def cpu_stats(): ... -def cpu_freq(): ... - -net_if_addrs: Any - -class _Ipv6UnsupportedError(Exception): ... - -class Connections: - tmap: Any - def __init__(self) -> None: ... - def get_proc_inodes(self, pid): ... - def get_all_inodes(self): ... - @staticmethod - def decode_address(addr, family): ... - @staticmethod - def process_inet(file, family, type_, inodes, filter_pid: Any | None = ...) -> None: ... - @staticmethod - def process_unix(file, family, inodes, filter_pid: Any | None = ...) -> None: ... - def retrieve(self, kind, pid: Any | None = ...): ... - -def net_connections(kind: str = ...): ... -def net_io_counters(): ... -def net_if_stats(): ... - -disk_usage: Any - -def disk_io_counters(perdisk: bool = ...): ... -def disk_partitions(all: bool = ...): ... -def sensors_temperatures(): ... -def sensors_fans(): ... -def sensors_battery(): ... -def users(): ... -def boot_time(): ... -def pids(): ... -def pid_exists(pid): ... -def ppid_map(): ... -def wrap_exceptions(fun): ... - -class Process: - pid: Any - def __init__(self, pid) -> None: ... - def oneshot_enter(self) -> None: ... - def oneshot_exit(self) -> None: ... - def name(self): ... - def exe(self): ... - def cmdline(self): ... - def environ(self): ... - def terminal(self): ... - def io_counters(self): ... - def cpu_times(self): ... - def cpu_num(self): ... - def wait(self, timeout: Any | None = ...): ... - def create_time(self): ... - def memory_info(self): ... - def memory_full_info(self, _private_re=..., _pss_re=..., _swap_re=...): ... - def memory_maps(self): ... - def cwd(self): ... - def num_ctx_switches(self, _ctxsw_re=...): ... - def num_threads(self, _num_threads_re=...): ... - def threads(self): ... - def nice_get(self): ... - def nice_set(self, value): ... - def cpu_affinity_get(self): ... - def cpu_affinity_set(self, cpus) -> None: ... - def ionice_get(self): ... - def ionice_set(self, ioclass, value): ... - def rlimit(self, resource_, limits: Any | None = ...): ... - def status(self): ... - def open_files(self): ... - def connections(self, kind: str = ...): ... - def num_fds(self): ... - def ppid(self): ... - def uids(self, _uids_re=...): ... - def gids(self, _gids_re=...): ... +import sys + +if sys.platform == "linux": + import enum + import re + from _typeshed import FileDescriptorOrPath + from collections import defaultdict + from collections.abc import Callable, Generator, Sequence + from typing import Final, ParamSpec, TypeVar, overload + + from psutil._common import ( + ENCODING as ENCODING, + NIC_DUPLEX_FULL as NIC_DUPLEX_FULL, + NIC_DUPLEX_HALF as NIC_DUPLEX_HALF, + NIC_DUPLEX_UNKNOWN as NIC_DUPLEX_UNKNOWN, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + bcat as bcat, + cat as cat, + debug as debug, + decode as decode, + get_procfs_path as get_procfs_path, + isfile_strict as isfile_strict, + memoize as memoize, + memoize_when_activated as memoize_when_activated, + open_binary as open_binary, + open_text as open_text, + parse_environ_block as parse_environ_block, + path_exists_strict as path_exists_strict, + supports_ipv6 as supports_ipv6, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_linux + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + POWER_SUPPLY_PATH: Final = "/sys/class/power_supply" + HAS_PROC_SMAPS: Final[bool] + HAS_PROC_SMAPS_ROLLUP: Final[bool] + HAS_PROC_IO_PRIORITY: Final[bool] + HAS_CPU_AFFINITY: Final[bool] + CLOCK_TICKS: Final[int] + PAGESIZE: Final[int] + LITTLE_ENDIAN: Final[bool] + UNSET: object + DISK_SECTOR_SIZE: Final = 512 + + class AddressFamily(enum.IntEnum): + AF_LINK = 17 # = socket.AF_PACKET + + AF_LINK: Final = AddressFamily.AF_LINK + + class IOPriority(enum.IntEnum): + IOPRIO_CLASS_NONE = 0 + IOPRIO_CLASS_RT = 1 + IOPRIO_CLASS_BE = 2 + IOPRIO_CLASS_IDLE = 3 + + IOPRIO_CLASS_NONE: Final = IOPriority.IOPRIO_CLASS_NONE + IOPRIO_CLASS_RT: Final = IOPriority.IOPRIO_CLASS_RT + IOPRIO_CLASS_BE: Final = IOPriority.IOPRIO_CLASS_BE + IOPRIO_CLASS_IDLE: Final = IOPriority.IOPRIO_CLASS_IDLE + + PROC_STATUSES: Final[dict[str, str]] + TCP_STATUSES: Final[dict[str, str]] + + def readlink(path: str) -> str: ... + def file_flags_to_mode(flags: int) -> str: ... + def is_storage_device(name: str) -> bool: ... + def _scputimes_ntuple(procfs_path: str) -> type[ntp.scputimes]: ... + scputimes = ntp.scputimes + def calculate_avail_vmem(mems: dict[bytes, int]) -> int: ... + def virtual_memory() -> ntp.svmem: ... + def swap_memory() -> ntp.sswap: ... + heap_info = _psutil_linux.heap_info + heap_trim = _psutil_linux.heap_trim + def cpu_times() -> ntp.scputimes: ... + def per_cpu_times() -> list[ntp.scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def cpu_freq() -> list[ntp.scpufreq]: ... + + net_if_addrs = _psutil_linux.net_if_addrs + + class _Ipv6UnsupportedError(Exception): ... + + class NetConnections: + tmap: dict[str, tuple[tuple[str, int, int | None], ...]] + def __init__(self) -> None: ... + def get_proc_inodes(self, pid: int) -> defaultdict[str, list[tuple[int, int]]]: ... + def get_all_inodes(self) -> dict[str, list[tuple[int, int]]]: ... + @staticmethod + def decode_address(addr: str, family: int) -> ntp.addr | tuple[()]: ... + @staticmethod + def process_inet( + file: str, family: int, type_: int, inodes: dict[str, list[tuple[int, int]]], filter_pid: int | None = None + ) -> Generator[tuple[int, int, int, ntp.addr | tuple[()], ntp.addr | tuple[()], str, int | None]]: ... + @staticmethod + def process_unix( + file: FileDescriptorOrPath, family: int, inodes: dict[str, list[tuple[int, int]]], filter_pid: int | None = None + ) -> Generator[tuple[int, int, int, str, str, str, int | None]]: ... + + @overload + def retrieve(self, kind: str, pid: int) -> list[ntp.pconn]: ... + @overload + def retrieve(self, kind: str, pid: None = None) -> list[ntp.sconn]: ... + + def net_connections(kind: str = "inet") -> list[ntp.sconn]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def net_if_stats() -> dict[str, ntp.snicstats]: ... + + disk_usage = _psposix.disk_usage + + def disk_io_counters(perdisk: bool = False) -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + + class RootFsDeviceFinder: + __slots__ = ["major", "minor"] + major: int + minor: int + def __init__(self) -> None: ... + def ask_proc_partitions(self) -> str | None: ... + def ask_sys_dev_block(self) -> str | None: ... + def ask_sys_class_block(self) -> str | None: ... + def find(self) -> str | None: ... + + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + def sensors_temperatures() -> dict[str, list[tuple[str, float, float | None, float | None]]]: ... + def sensors_fans() -> dict[str, list[ntp.sfan]]: ... + def sensors_battery() -> ntp.sbattery | None: ... + def users() -> list[ntp.suser]: ... + def boot_time() -> float: ... + def pids() -> list[int]: ... + def pid_exists(pid: int) -> bool: ... + def ppid_map() -> dict[int, int]: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_ctime", "_name", "_ppid", "_procfs_path", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def terminal(self) -> str | None: ... + def io_counters(self) -> ntp.pio: ... + def cpu_times(self) -> ntp.pcputimes: ... + def cpu_num(self) -> int: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def create_time(self, monotonic: bool = False) -> float: ... + def memory_info(self) -> ntp.pmem: ... + def memory_full_info(self) -> ntp.pfullmem: ... + def memory_maps(self) -> list[tuple[str, str, str, int, int, int, int, int, int, int, int, int, int]]: ... + def cwd(self) -> str: ... + def num_ctx_switches(self, _ctxsw_re: re.Pattern[bytes] = ...) -> ntp.pctxsw: ... + def num_threads(self, _num_threads_re: re.Pattern[bytes] = ...) -> int: ... + def threads(self) -> list[ntp.pthread]: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def cpu_affinity_get(self) -> list[int]: ... + def cpu_affinity_set(self, cpus: Sequence[int]) -> None: ... + def ionice_get(self) -> ntp.pionice: ... + def ionice_set(self, ioclass: int, value: int | None) -> None: ... + + @overload + def rlimit(self, resource_: int, limits: tuple[int, int]) -> None: ... + @overload + def rlimit(self, resource_: int, limits: None = None) -> tuple[int, int]: ... + + def status(self) -> str: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def num_fds(self) -> int: ... + def ppid(self) -> int: ... + def uids(self, _uids_re: re.Pattern[bytes] = ...) -> ntp.puids: ... + def gids(self, _gids_re: re.Pattern[bytes] = ...) -> ntp.pgids: ... diff --git a/stubs/psutil/psutil/_psosx.pyi b/stubs/psutil/psutil/_psosx.pyi index e62d9de09cd8..b8f5cbce2acc 100644 --- a/stubs/psutil/psutil/_psosx.pyi +++ b/stubs/psutil/psutil/_psosx.pyi @@ -1,104 +1,89 @@ -from contextlib import AbstractContextManager -from typing import Any, NamedTuple +import sys -from ._common import ( - AccessDenied as AccessDenied, - NoSuchProcess as NoSuchProcess, - ZombieProcess as ZombieProcess, - conn_tmap as conn_tmap, - conn_to_ntuple as conn_to_ntuple, - isfile_strict as isfile_strict, - parse_environ_block as parse_environ_block, - usage_percent as usage_percent, -) +if sys.platform == "darwin": + from collections.abc import Callable + from typing import Final, ParamSpec, TypeVar -__extra__all__: Any -PAGESIZE: Any -AF_LINK: Any -TCP_STATUSES: Any -PROC_STATUSES: Any -kinfo_proc_map: Any -pidtaskinfo_map: Any + from psutil._common import ( + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + conn_tmap as conn_tmap, + conn_to_ntuple as conn_to_ntuple, + debug as debug, + isfile_strict as isfile_strict, + memoize_when_activated as memoize_when_activated, + parse_environ_block as parse_environ_block, + usage_percent as usage_percent, + ) -class scputimes(NamedTuple): - user: Any - nice: Any - system: Any - idle: Any + from . import _ntuples as ntp, _psposix, _psutil_osx -class svmem(NamedTuple): - total: Any - available: Any - percent: Any - used: Any - free: Any - active: Any - inactive: Any - wired: Any + _P = ParamSpec("_P") + _R = TypeVar("_R") -class pmem(NamedTuple): - rss: Any - vms: Any - pfaults: Any - pageins: Any + __extra__all__: Final[list[str]] + PAGESIZE: Final[int] + AF_LINK: Final[int] + TCP_STATUSES: Final[dict[int, str]] + PROC_STATUSES: Final[dict[int, str]] + kinfo_proc_map: Final[dict[str, int]] + pidtaskinfo_map: Final[dict[str, int]] -pfullmem: Any + def virtual_memory() -> ntp.svmem: ... + def swap_memory() -> ntp.sswap: ... + heap_info = _psutil_osx.heap_info + heap_trim = _psutil_osx.heap_trim + def cpu_times() -> ntp.scputimes: ... + def per_cpu_times() -> list[ntp.scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def cpu_freq() -> list[ntp.scpufreq]: ... -def virtual_memory(): ... -def swap_memory(): ... -def cpu_times(): ... -def per_cpu_times(): ... -def cpu_count_logical(): ... -def cpu_count_physical(): ... -def cpu_stats(): ... -def cpu_freq(): ... + disk_usage = _psposix.disk_usage + disk_io_counters = _psutil_osx.disk_io_counters + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + def sensors_battery() -> ntp.sbattery | None: ... -disk_usage: Any -disk_io_counters: Any + net_io_counters = _psutil_osx.net_io_counters + net_if_addrs = _psutil_osx.net_if_addrs + def net_connections(kind: str = "inet") -> list[ntp.sconn]: ... + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def boot_time() -> float: ... + INIT_BOOT_TIME: float + def adjust_proc_create_time(ctime: float) -> float: ... + def users() -> list[ntp.suser]: ... + def pids() -> list[int]: ... + pid_exists = _psposix.pid_exists + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... -def disk_partitions(all: bool = ...): ... -def sensors_battery(): ... - -net_io_counters: Any -net_if_addrs: Any - -def net_connections(kind: str = ...): ... -def net_if_stats(): ... -def boot_time(): ... -def users(): ... -def pids(): ... - -pid_exists: Any - -def is_zombie(pid): ... -def wrap_exceptions(fun): ... -def catch_zombie(proc) -> AbstractContextManager[None]: ... - -class Process: - pid: Any - def __init__(self, pid) -> None: ... - def oneshot_enter(self) -> None: ... - def oneshot_exit(self) -> None: ... - def name(self): ... - def exe(self): ... - def cmdline(self): ... - def environ(self): ... - def ppid(self): ... - def cwd(self): ... - def uids(self): ... - def gids(self): ... - def terminal(self): ... - def memory_info(self): ... - def memory_full_info(self): ... - def cpu_times(self): ... - def create_time(self): ... - def num_ctx_switches(self): ... - def num_threads(self): ... - def open_files(self): ... - def connections(self, kind: str = ...): ... - def num_fds(self): ... - def wait(self, timeout: Any | None = ...): ... - def nice_get(self): ... - def nice_set(self, value): ... - def status(self): ... - def threads(self): ... + class Process: + __slots__ = ["_cache", "_name", "_ppid", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def ppid(self) -> int: ... + def cwd(self) -> str: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.puids: ... + def terminal(self) -> str | None: ... + def memory_info(self) -> ntp.pmem: ... + def memory_full_info(self) -> ntp.pfullmem: ... + def cpu_times(self) -> ntp.pcputimes: ... + def create_time(self, monotonic: bool = False) -> float: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def num_threads(self) -> int: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def num_fds(self) -> int: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def status(self) -> str: ... + def threads(self) -> list[ntp.pthread]: ... diff --git a/stubs/psutil/psutil/_psposix.pyi b/stubs/psutil/psutil/_psposix.pyi index 8b754aff0821..69694bfa4490 100644 --- a/stubs/psutil/psutil/_psposix.pyi +++ b/stubs/psutil/psutil/_psposix.pyi @@ -1,8 +1,85 @@ -from typing import Any - -def pid_exists(pid): ... -def wait_pid( - pid, timeout: Any | None = ..., proc_name: Any | None = ..., _waitpid=..., _timer=..., _min=..., _sleep=..., _pid_exists=... -): ... -def disk_usage(path): ... -def get_terminal_map(): ... +import enum +import sys +from _typeshed import FileDescriptorOrPath, Incomplete, StrOrBytesPath, Unused +from collections.abc import Callable + +from . import _ntuples as ntp + +def pid_exists(pid: int) -> bool: ... + +# Sync with `signal.Signals`, but with opposite values: +class Negsignal(enum.IntEnum): + SIGABRT = -6 + SIGFPE = -8 + SIGILL = -4 + SIGINT = -2 + SIGSEGV = -11 + SIGTERM = -15 + + if sys.platform == "win32": + SIGBREAK = -21 + CTRL_C_EVENT = 0 + CTRL_BREAK_EVENT = -1 + else: + SIGALRM = -14 + SIGBUS = -7 + SIGCHLD = -17 + SIGCONT = -18 + SIGHUP = -1 + SIGIO = -29 + SIGIOT = -6 + SIGKILL = -9 + SIGPIPE = -13 + SIGPROF = -27 + SIGQUIT = -3 + SIGSTOP = -19 + SIGSYS = -31 + SIGTRAP = -5 + SIGTSTP = -20 + SIGTTIN = -21 + SIGTTOU = -22 + SIGURG = -23 + SIGUSR1 = -10 + SIGUSR2 = -12 + SIGVTALRM = -26 + SIGWINCH = -28 + SIGXCPU = -24 + SIGXFSZ = -25 + if sys.platform != "linux": + SIGEMT = -7 + SIGINFO = -29 + if sys.platform != "darwin": + SIGCLD = -17 + SIGPOLL = -29 + SIGPWR = -30 + SIGRTMAX = -64 + SIGRTMIN = -34 + if sys.version_info >= (3, 11): + SIGSTKFLT = -16 + +def negsig_to_enum(num: int) -> int: ... +def convert_exit_code(status: int) -> int: ... +def wait_pid_posix( + pid: int, + timeout: float | None = None, + _waitpid: Unused = ..., + _timer: Callable[[], float] = ..., + _min: Callable[..., Incomplete] = ..., + _sleep: Callable[[float], None] = ..., + _pid_exists: Callable[[int], bool] = ..., +) -> int | None: ... +def wait_pid_pidfd_open(pid: int, timeout: float | None = None) -> int | None: ... +def wait_pid_kqueue(pid: int, timeout: float | None = None) -> int | None: ... +def can_use_pidfd_open() -> bool: ... +def can_use_kqueue() -> bool: ... +def wait_pid(pid: int, timeout: float | None = None) -> int | None: ... + +if sys.platform == "darwin": + def disk_usage(path: StrOrBytesPath) -> ntp.sdiskusage: ... + +else: + def disk_usage(path: FileDescriptorOrPath) -> ntp.sdiskusage: ... + +def get_terminal_map() -> dict[int, str]: ... + +__all__ = ["pid_exists", "wait_pid", "disk_usage", "get_terminal_map"] diff --git a/stubs/psutil/psutil/_pssunos.pyi b/stubs/psutil/psutil/_pssunos.pyi new file mode 100644 index 000000000000..d1e3b6dba4aa --- /dev/null +++ b/stubs/psutil/psutil/_pssunos.pyi @@ -0,0 +1,151 @@ +import sys + +# sys.platform.startswith(("sunos", "solaris")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from _typeshed import Incomplete + from collections.abc import Callable + from typing import Final, Literal, NamedTuple, ParamSpec, TypeVar, overload + + from psutil._common import ( + AF_INET6 as AF_INET6, + ENCODING as ENCODING, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + debug as debug, + get_procfs_path as get_procfs_path, + isfile_strict as isfile_strict, + memoize_when_activated as memoize_when_activated, + sockfam_to_enum as sockfam_to_enum, + socktype_to_enum as socktype_to_enum, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_sunos + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + PAGE_SIZE: Final[int] + AF_LINK: Final[int] + IS_64_BIT: Final[bool] + CONN_IDLE: Final = "IDLE" + CONN_BOUND: Final = "BOUND" + PROC_STATUSES: Final[dict[int, str]] + TCP_STATUSES: Final[dict[int, str]] + proc_info_map: Final[dict[str, int]] + + class scputimes(NamedTuple): + user: float + system: float + idle: float + iowait: float + + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + + class pmem(NamedTuple): + rss: int + vms: int + + pfullmem = pmem + + class pmmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + anonymous: Incomplete + locked: Incomplete + + class pmmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + anonymous: Incomplete + locked: Incomplete + + def virtual_memory() -> svmem: ... + def swap_memory() -> ntp.sswap: ... + def cpu_times() -> scputimes: ... + def per_cpu_times() -> list[scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + + disk_io_counters = _psutil_sunos.disk_io_counters + disk_usage = _psposix.disk_usage + + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + + net_io_counters = _psutil_sunos.net_io_counters + net_if_addrs = _psutil_sunos.net_if_addrs + + @overload + def net_connections(kind: str, _pid: Literal[-1] = -1) -> list[ntp.sconn]: ... + @overload + def net_connections(kind: str, _pid: int = -1) -> list[ntp.pconn]: ... + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + def pids() -> list[int]: ... + def pid_exists(pid: int) -> bool: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str] | None: ... + def environ(self) -> dict[str, str]: ... + def create_time(self) -> float: ... + def num_threads(self) -> int: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def ppid(self) -> int: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.puids: ... + def cpu_times(self) -> ntp.pcputimes: ... + def cpu_num(self) -> int: ... + def terminal(self) -> str | None: ... + def cwd(self) -> str: ... + def memory_info(self) -> pmem: ... + memory_full_info = memory_info + def status(self) -> str: ... + def threads(self) -> list[ntp.pthread]: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + + class nt_mmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + anon: Incomplete + locked: Incomplete + + class nt_mmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + anon: Incomplete + locked: Incomplete + + def memory_maps(self) -> list[tuple[str, str, str, int, int, int]]: ... + def num_fds(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def wait(self, timeout: float | None = None) -> int | None: ... diff --git a/stubs/psutil/psutil/_psutil_aix.pyi b/stubs/psutil/psutil/_psutil_aix.pyi new file mode 100644 index 000000000000..17977e3eadcb --- /dev/null +++ b/stubs/psutil/psutil/_psutil_aix.pyi @@ -0,0 +1,58 @@ +import sys + +# sys.platform.startswith("aix"): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from typing import Final + + AF_LINK: Final = 18 + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + + version: Final[int] + SIDL: Final[int] + SZOMB: Final[int] + SACTIVE: Final[int] + SSWAP: Final[int] + SSTOP: Final[int] + TCPS_CLOSED: Final[int] + TCPS_CLOSING: Final[int] + TCPS_CLOSE_WAIT: Final[int] + TCPS_LISTEN: Final[int] + TCPS_ESTABLISHED: Final[int] + TCPS_SYN_SENT: Final[int] + TCPS_SYN_RCVD: Final[int] + TCPS_FIN_WAIT_1: Final[int] + TCPS_FIN_WAIT_2: Final[int] + TCPS_LAST_ACK: Final[int] + TCPS_TIME_WAIT: Final[int] + PSUTIL_CONN_NONE: Final = 128 + + def proc_args(pid: int, /) -> list[str]: ... + def proc_basic_info(pid: int, procfs_path: str, /) -> tuple[int, int, int, float, int, int, int, int]: ... + def proc_cpu_times(pid: int, procfs_path: str, /) -> tuple[float, float, float, float]: ... + def proc_cred(pid: int, procfs_path: str, /) -> tuple[int, int, int, int, int, int]: ... + def proc_environ(pid: int, /) -> dict[str, str]: ... + def proc_name(pid: int, procfs_path: str, /) -> str: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def proc_io_counters(pid: int, /) -> tuple[int, int, int, int]: ... + def proc_num_ctx_switches(requested_pid: int, /) -> tuple[int, int]: ... + def boot_time() -> float: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float]]: ... + def swap_mem() -> tuple[int, int, int, int]: ... + def virtual_mem() -> tuple[int, int, int, int, int]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def cpu_stats() -> tuple[int, int, int, int]: ... + def net_connections( + requested_pid: int, / + ) -> list[tuple[int, int, int, str | tuple[str, int], str | tuple[str, int] | tuple[()], int, int]]: ... + def net_if_stats(nic_name: str, /) -> tuple[bool, int]: ... # It's actually list of 2 elements + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_bsd.pyi b/stubs/psutil/psutil/_psutil_bsd.pyi new file mode 100644 index 000000000000..9aabf5116d03 --- /dev/null +++ b/stubs/psutil/psutil/_psutil_bsd.pyi @@ -0,0 +1,145 @@ +import sys + +# sys.platform.startswith(("freebsd", "midnightbsd", "openbsd", "netbsd")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from collections.abc import Sequence + from socket import AddressFamily, SocketKind + from typing import Final, overload + + AF_LINK: Final[int] + RLIMIT_AS: Final[int] # only FreeBSD + RLIMIT_CORE: Final[int] # only FreeBSD + RLIMIT_CPU: Final[int] # only FreeBSD + RLIMIT_DATA: Final[int] # only FreeBSD + RLIMIT_FSIZE: Final[int] # only FreeBSD + RLIMIT_MEMLOCK: Final[int] # only FreeBSD + RLIMIT_NOFILE: Final[int] # only FreeBSD + RLIMIT_NPROC: Final[int] # only FreeBSD + RLIMIT_RSS: Final[int] # only FreeBSD + RLIMIT_STACK: Final[int] # only FreeBSD + RLIMIT_SWAP: Final[int] # only FreeBSD + RLIMIT_SBSIZE: Final[int] # only FreeBSD + RLIMIT_NPTS: Final[int] # only FreeBSD + RLIM_INFINITY: Final[int] # only FreeBSD + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def net_if_duplex_speed(nic_name: str, /) -> tuple[int, int]: ... # It's actually list of 2 elements + def proc_is_zombie(pid: int, /) -> bool: ... + + version: Final[int] + SIDL: Final[int] + SRUN: Final[int] + SSLEEP: Final[int] + SSTOP: Final[int] + SZOMB: Final[int] + SWAIT: Final[int] # only FreeBSD + SLOCK: Final[int] # only FreeBSD + SDEAD: Final[int] # only OpenBSD and NetBSD + SONPROC: Final[int] # only OpenBSD and NetBSD + SSUSPENDED: Final[int] # only NetBSD + TCPS_CLOSED: Final[int] + TCPS_CLOSING: Final[int] + TCPS_CLOSE_WAIT: Final[int] + TCPS_LISTEN: Final[int] + TCPS_ESTABLISHED: Final[int] + TCPS_SYN_SENT: Final[int] + TCPS_SYN_RECEIVED: Final[int] + TCPS_FIN_WAIT_1: Final[int] + TCPS_FIN_WAIT_2: Final[int] + TCPS_LAST_ACK: Final[int] + TCPS_TIME_WAIT: Final[int] + PSUTIL_CONN_NONE: Final = 128 + + def proc_cmdline(pid: int, /) -> list[str]: ... + def proc_cwd(pid: int, /) -> str: ... + def proc_environ(pid: int, /) -> dict[str, str]: ... + def proc_name(pid: int, /) -> str: ... + def proc_num_fds(pid: int, /) -> int: ... + def proc_oneshot_info( + pid: int, / + ) -> tuple[ + int, + int, + int, + int, + int, + int, + int, + int, + int, + float, + int, + int, + int, + int, + float, + float, + float, + float, + int, + int, + int, + int, + int, + int, + str, + ]: ... + def proc_open_files(pid: int, /) -> list[tuple[str, int]]: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def proc_num_threads(pid: int, /) -> int: ... # only FreeBSD and NetBSD + def proc_cpu_affinity_get(pid: int, /) -> list[int]: ... # only FreeBSD + def proc_cpu_affinity_set(pid: int, cpu_set: Sequence[int], /) -> None: ... # only FreeBSD + def proc_exe(pid: int, /) -> str: ... # only FreeBSD + def proc_getrlimit(pid: int, resource: int, /) -> tuple[int, int]: ... # only FreeBSD + def proc_memory_maps(pid: int, /) -> list[tuple[str, str, str, int, int, int, int]]: ... # only FreeBSD + def proc_net_connections( # only FreeBSD + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int] | tuple[int, int, int, str, str, int]]: ... + def proc_setrlimit(pid: int, resource: int, soft: int, hard: int, /) -> None: ... # only FreeBSD + def boot_time() -> float: ... + def cpu_count_logical() -> int | None: ... + def cpu_stats() -> tuple[int, ...]: ... # tuple's length depends on OS + def cpu_times() -> tuple[float, float, float, float, float]: ... + def disk_io_counters() -> dict[str, tuple[int, ...]]: ... # tuple's length depends on OS + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + + @overload # for FreeBSD + def net_connections( + af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[ + tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int, int] | tuple[int, int, int, str, str, int, int] + ]: ... + @overload # for OpenBSD + def net_connections( + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[ + tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int, int] | tuple[int, int, int, str, str, int, int] + ]: ... + @overload # for NetBSD + def net_connections(pid: int, kind: str, /) -> list[tuple[int, int, int, str, str, int, int]]: ... + + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float, float]]: ... + def pids() -> list[int]: ... + def swap_mem() -> tuple[int, int, int, int, int]: ... + def heap_info() -> tuple[int, int]: ... # only FreeBSD and NetBSD + def heap_trim() -> None: ... # only FreeBSD and NetBSD + def users() -> list[tuple[str, str, str, float, int | None]]: ... # returns None only in OpenBSD + def virtual_mem() -> tuple[int, ...]: ... # tuple's length depends on OS + + @overload + def cpu_freq() -> int: ... # only OpenBSD + @overload + def cpu_freq(core: int, /) -> tuple[int, str]: ... # only FreeBSD + + def cpu_topology() -> str | None: ... # only FreeBSD + def sensors_battery() -> tuple[int, int, int]: ... # only FreeBSD + def sensors_cpu_temperature(core: int, /) -> tuple[int, int]: ... # only FreeBSD + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_linux.pyi b/stubs/psutil/psutil/_psutil_linux.pyi index 949d6a7e7c69..d24279961311 100644 --- a/stubs/psutil/psutil/_psutil_linux.pyi +++ b/stubs/psutil/psutil/_psutil_linux.pyi @@ -1,16 +1,49 @@ -from typing import Any +import sys -DUPLEX_FULL: int -DUPLEX_HALF: int -DUPLEX_UNKNOWN: int -version: int +if sys.platform == "linux": + from collections.abc import Sequence + from typing import Final -def disk_partitions(*args, **kwargs) -> Any: ... -def linux_sysinfo(*args, **kwargs) -> Any: ... -def net_if_duplex_speed(*args, **kwargs) -> Any: ... -def proc_cpu_affinity_get(*args, **kwargs) -> Any: ... -def proc_cpu_affinity_set(*args, **kwargs) -> Any: ... -def proc_ioprio_get(*args, **kwargs) -> Any: ... -def proc_ioprio_set(*args, **kwargs) -> Any: ... -def set_testing(*args, **kwargs) -> Any: ... -def users(*args, **kwargs) -> Any: ... + RLIMIT_AS: Final[int] + RLIMIT_CORE: Final[int] + RLIMIT_CPU: Final[int] + RLIMIT_DATA: Final[int] + RLIMIT_FSIZE: Final[int] + RLIMIT_MEMLOCK: Final[int] + RLIMIT_NOFILE: Final[int] + RLIMIT_NPROC: Final[int] + RLIMIT_RSS: Final[int] + RLIMIT_STACK: Final[int] + RLIMIT_LOCKS: Final[int] + RLIMIT_MSGQUEUE: Final[int] + RLIMIT_NICE: Final[int] + RLIMIT_RTPRIO: Final[int] + RLIMIT_RTTIME: Final[int] + RLIMIT_SIGPENDING: Final[int] + RLIM_INFINITY: Final[int] + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def users() -> list[tuple[str, str, str, float, int]]: ... + + version: Final[int] + DUPLEX_FULL: Final[int] + DUPLEX_HALF: Final[int] + DUPLEX_UNKNOWN: Final[int] + + def proc_ioprio_get(pid: int, /) -> tuple[int, int]: ... + def proc_ioprio_set(pid: int, ioclass: int, iodata: int, /) -> None: ... + def proc_cpu_affinity_get(pid: int, /) -> list[int]: ... + def proc_cpu_affinity_set(pid: int, cpu_set: Sequence[int], /) -> None: ... + def disk_partitions(mtab_path: str, /) -> list[tuple[str, str, str, str]]: ... + def net_if_duplex_speed(nic_name: str, /) -> tuple[int, int]: ... # It's actually list of 2 elements + def heap_info() -> tuple[int, int]: ... + def heap_trim() -> bool: ... + def linux_sysinfo() -> tuple[int, int, int, int, int, int, int]: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_osx.pyi b/stubs/psutil/psutil/_psutil_osx.pyi new file mode 100644 index 000000000000..2ea2baca3d05 --- /dev/null +++ b/stubs/psutil/psutil/_psutil_osx.pyi @@ -0,0 +1,79 @@ +import sys + +if sys.platform == "darwin": + from _typeshed import StrOrBytesPath + from collections.abc import Sequence + from socket import AddressFamily, SocketKind + from typing import Final, TypeVar + + _T = TypeVar("_T") + + AF_LINK: Final = 18 + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def net_if_duplex_speed(nic_name: str, /) -> tuple[int, int]: ... # It's actually list of 2 elements + def users() -> list[tuple[str, str, str, float, int]]: ... + def proc_is_zombie(pid: int, /) -> bool: ... + + version: Final[int] + SIDL: Final = 1 + SRUN: Final = 2 + SSLEEP: Final = 3 + SSTOP: Final = 4 + SZOMB: Final = 5 + TCPS_CLOSED: Final = 0 + TCPS_CLOSING: Final = 7 + TCPS_CLOSE_WAIT: Final = 5 + TCPS_LISTEN: Final = 1 + TCPS_ESTABLISHED: Final = 4 + TCPS_SYN_SENT: Final = 2 + TCPS_SYN_RECEIVED: Final = 3 + TCPS_FIN_WAIT_1: Final = 6 + TCPS_FIN_WAIT_2: Final = 9 + TCPS_LAST_ACK: Final = 8 + TCPS_TIME_WAIT: Final = 10 + PSUTIL_CONN_NONE: Final = 128 + + def proc_cmdline(pid: int, /) -> list[str]: ... + def proc_cwd(pid: int, /) -> str: ... + def proc_environ(pid: int, /) -> str: ... + def proc_exe(pid: int, /) -> str: ... + def proc_kinfo_oneshot(pid: int, /) -> tuple[int, int, int, int, int, int, int, float, int, str]: ... + def proc_memory_uss(pid: int, /) -> int: ... + def proc_name(pid: int, /) -> str: ... + def proc_net_connections( + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[ + tuple[int, int, int, tuple[str | None, int], tuple[str | None, int] | tuple[()], int] + | tuple[int, int, int, str, str, int] + ]: ... + def proc_num_fds(pid: int, /) -> int: ... + def proc_open_files(pid: int, /) -> list[tuple[str, int]]: ... + def proc_pidtaskinfo_oneshot(pid: int, /) -> tuple[float, float, int, int, int, int, int, int]: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def boot_time() -> float: ... + def cpu_count_cores() -> int | None: ... + def cpu_count_logical() -> int | None: ... + def cpu_freq() -> tuple[int, int, int]: ... + def cpu_stats() -> tuple[int, int, int, int, int]: ... + def cpu_times() -> tuple[float, float, float, float]: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + def disk_usage_used(mount_point: StrOrBytesPath, default: _T, /) -> int | _T: ... + def has_cpu_freq() -> bool: ... + def heap_info() -> tuple[int, int]: ... + def heap_trim() -> None: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float]]: ... + def pids() -> list[int]: ... + def sensors_battery() -> tuple[int, int, int]: ... + def swap_mem() -> tuple[int, int, int, int, int]: ... + def virtual_mem() -> tuple[int, int, int, int, int, int]: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_posix.pyi b/stubs/psutil/psutil/_psutil_posix.pyi deleted file mode 100644 index 91e2302ec9cd..000000000000 --- a/stubs/psutil/psutil/_psutil_posix.pyi +++ /dev/null @@ -1,31 +0,0 @@ -import sys -from typing import Any - -if sys.platform == "linux": - RLIMIT_AS: int - RLIMIT_CORE: int - RLIMIT_CPU: int - RLIMIT_DATA: int - RLIMIT_FSIZE: int - RLIMIT_LOCKS: int - RLIMIT_MEMLOCK: int - RLIMIT_MSGQUEUE: int - RLIMIT_NICE: int - RLIMIT_NOFILE: int - RLIMIT_NPROC: int - RLIMIT_RSS: int - RLIMIT_RTPRIO: int - RLIMIT_SIGPENDING: int - RLIMIT_STACK: int - RLIM_INFINITY: int - -def getpagesize(*args, **kwargs) -> Any: ... -def getpriority(*args, **kwargs) -> Any: ... -def net_if_addrs(*args, **kwargs) -> Any: ... -def net_if_is_running(*args, **kwargs) -> Any: ... -def net_if_mtu(*args, **kwargs) -> Any: ... - -if sys.platform == "darwin": - def net_if_duplex_speed(*args, **kwargs): ... - -def setpriority(*args, **kwargs) -> Any: ... diff --git a/stubs/psutil/psutil/_psutil_sunos.pyi b/stubs/psutil/psutil/_psutil_sunos.pyi new file mode 100644 index 000000000000..fe56efa827ba --- /dev/null +++ b/stubs/psutil/psutil/_psutil_sunos.pyi @@ -0,0 +1,63 @@ +import sys + +# sys.platform.startswith(("sunos", "solaris")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from typing import Final + + AF_LINK: Final[int] + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def users() -> list[tuple[str, str, str, float, int]]: ... + + version: Final[int] + # They could be different between different versions of SunOS/Solaris: + SSLEEP: Final[int] + SRUN: Final[int] + SZOMB: Final[int] + SSTOP: Final[int] + SIDL: Final[int] + SONPROC: Final[int] + SWAIT: Final[int] + PRNODEV: Final[int] + TCPS_CLOSED: Final[int] + TCPS_CLOSING: Final[int] + TCPS_CLOSE_WAIT: Final[int] + TCPS_LISTEN: Final[int] + TCPS_ESTABLISHED: Final[int] + TCPS_SYN_SENT: Final[int] + TCPS_SYN_RCVD: Final[int] + TCPS_FIN_WAIT_1: Final[int] + TCPS_FIN_WAIT_2: Final[int] + TCPS_LAST_ACK: Final[int] + TCPS_TIME_WAIT: Final[int] + TCPS_IDLE: Final[int] + TCPS_BOUND: Final[int] + PSUTIL_CONN_NONE: Final = 128 + + def proc_basic_info(pid: int, procfs_path: str, /) -> tuple[int, int, int, float, int, int, int, int, int, int, int, int]: ... + def proc_cpu_num(pid: int, procfs_path: str, /) -> int: ... + def proc_cpu_times(pid: int, procfs_path: str, /) -> tuple[float, float, float, float]: ... + def proc_cred(pid: int, procfs_path: str, /) -> tuple[int, int, int, int, int, int]: ... + def proc_environ(pid: int, procfs_path: str, /) -> dict[str, str]: ... + def proc_memory_maps(pid: int, procfs_path: str, /) -> list[tuple[int, int, str, str, int, int, int]]: ... + def proc_name_and_args(pid: int, procfs_path: str, /) -> tuple[str, list[str] | None]: ... + def proc_num_ctx_switches(pid: int, procfs_path: str, /) -> tuple[int, int]: ... + def query_process_thread(pid: int, tid: int, procfs_path: str, /) -> tuple[float, float]: ... + def boot_time() -> float: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> tuple[int, int, int, int]: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + def net_connections(pid: int, /) -> list[tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int, int]]: ... + def net_if_stats() -> dict[str, tuple[bool, int, int, int]]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float]]: ... + def swap_mem() -> tuple[int, int]: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_windows.pyi b/stubs/psutil/psutil/_psutil_windows.pyi index 964e6fa3f426..f48ed77998b2 100644 --- a/stubs/psutil/psutil/_psutil_windows.pyi +++ b/stubs/psutil/psutil/_psutil_windows.pyi @@ -1,3 +1,105 @@ -from typing import Any +import sys -def __getattr__(name: str) -> Any: ... # incomplete +if sys.platform == "win32": + from collections.abc import Sequence + from socket import AddressFamily, SocketKind + from typing import Final + + version: Final[int] + ABOVE_NORMAL_PRIORITY_CLASS: Final = 32768 + BELOW_NORMAL_PRIORITY_CLASS: Final = 16384 + HIGH_PRIORITY_CLASS: Final = 128 + IDLE_PRIORITY_CLASS: Final = 64 + NORMAL_PRIORITY_CLASS: Final = 32 + REALTIME_PRIORITY_CLASS: Final = 256 + MIB_TCP_STATE_CLOSED: Final = 1 + MIB_TCP_STATE_CLOSING: Final = 9 + MIB_TCP_STATE_CLOSE_WAIT: Final = 8 + MIB_TCP_STATE_LISTEN: Final = 2 + MIB_TCP_STATE_ESTAB: Final = 5 + MIB_TCP_STATE_SYN_SENT: Final = 3 + MIB_TCP_STATE_SYN_RCVD: Final = 4 + MIB_TCP_STATE_FIN_WAIT1: Final = 6 + MIB_TCP_STATE_FIN_WAIT2: Final = 7 + MIB_TCP_STATE_LAST_ACK: Final = 10 + MIB_TCP_STATE_TIME_WAIT: Final = 11 + MIB_TCP_STATE_DELETE_TCB: Final = 12 + PSUTIL_CONN_NONE: Final = 128 + INFINITE: Final[int] + ERROR_ACCESS_DENIED: Final = 5 + ERROR_INVALID_NAME: Final = 123 + ERROR_SERVICE_DOES_NOT_EXIST: Final = 1060 + ERROR_PRIVILEGE_NOT_HELD: Final = 1314 + WINVER: Final[int] + WINDOWS_VISTA: Final = 60 + WINDOWS_7: Final = 61 + WINDOWS_8: Final = 62 + WINDOWS_8_1: Final = 63 + WINDOWS_10: Final = 100 + + class TimeoutAbandoned(Exception): ... + class TimeoutExpired(Exception): ... + + def proc_cmdline(pid: int, use_peb: bool = True) -> list[str]: ... + def proc_cpu_affinity_get(pid: int, /) -> int: ... + def proc_cpu_affinity_set(pid: int, mask: int, /) -> None: ... + def proc_cwd(pid: int, /) -> str: ... + def proc_environ(pid: int, /) -> str: ... + def proc_exe(pid: int, /) -> str: ... + def proc_io_counters(pid: int, /) -> tuple[int, int, int, int, int, int]: ... + def proc_io_priority_get(pid: int, /) -> int: ... + def proc_io_priority_set(pid: int, priority: int, /) -> None: ... + def proc_is_suspended(pid: int, /) -> bool: ... + def proc_kill(pid: int, /) -> None: ... + def proc_memory_info(pid: int, /) -> tuple[int, int, int, int, int, int, int, int, int, int]: ... + def proc_memory_maps(pid: int, /) -> list[tuple[int, str, str, int]]: ... + def proc_memory_uss(pid: int, /) -> int: ... + def proc_num_handles(pid: int, /) -> int: ... + def proc_open_files(pid: int, /) -> list[str]: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def proc_suspend_or_resume(pid: int, suspend: bool | None, /) -> None: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def proc_times(pid: int, /) -> tuple[float, float, float]: ... + def proc_username(pid: int, /) -> tuple[str, str]: ... + def proc_wait(pid: int, timeout: int, /) -> int | None: ... + def proc_info( + pid: int, / + ) -> tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int]: ... + def uptime() -> float: ... + def cpu_count_cores() -> int | None: ... + def cpu_count_logical() -> int | None: ... + def cpu_freq() -> tuple[int, int]: ... + def cpu_stats() -> tuple[int, int, int, int]: ... + def cpu_times() -> tuple[float, float, float]: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions(all: bool, /) -> list[tuple[str, str, str, str]]: ... + def disk_usage(path: str, /) -> tuple[int, int, int]: ... + def getloadavg() -> tuple[float, float, float]: ... + def getpagesize() -> int: ... + def swap_percent() -> float: ... + def init_loadavg_counter() -> None: ... + def heap_info() -> tuple[int, int, int]: ... + def heap_trim() -> int: ... + def net_connections( + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[tuple[int, int, int, tuple[str | None, int], tuple[str | None, int], int, int]]: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, None, None]]: ... + def net_if_stats() -> dict[str, tuple[bool, int, int, int]]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float, float]]: ... + def pid_exists(pid: int, /) -> bool: ... + def pids() -> list[int]: ... + def ppid_map() -> dict[int, int]: ... + def sensors_battery() -> tuple[int, int, int, int]: ... + def users() -> list[tuple[str, str | None, float]]: ... + def virtual_mem() -> tuple[int, int, int, int]: ... + def winservice_enumerate() -> list[tuple[str, str]]: ... + def winservice_query_config(service_name: str, /) -> tuple[str, str, str, str]: ... + def winservice_query_descr(service_name: str, /) -> str: ... + def winservice_query_status(service_name: str, /) -> tuple[str, int] | str: ... + def winservice_start(service_name: str, /) -> None: ... + def winservice_stop(service_name: str, /) -> None: ... + def QueryDosDevice(device_path: str, /) -> str: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_pswindows.pyi b/stubs/psutil/psutil/_pswindows.pyi index 6d39f0e752da..8d9d89e1d783 100644 --- a/stubs/psutil/psutil/_pswindows.pyi +++ b/stubs/psutil/psutil/_pswindows.pyi @@ -1,186 +1,179 @@ -import enum -from typing import Any, NamedTuple - -from ._common import ( - ENCODING as ENCODING, - ENCODING_ERRS as ENCODING_ERRS, - AccessDenied as AccessDenied, - NoSuchProcess as NoSuchProcess, - TimeoutExpired as TimeoutExpired, - conn_tmap as conn_tmap, - conn_to_ntuple as conn_to_ntuple, - debug as debug, - isfile_strict as isfile_strict, - memoize as memoize, - parse_environ_block as parse_environ_block, - usage_percent as usage_percent, -) -from ._psutil_windows import ( - ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, - BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, - HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, - IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, - NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, - REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, -) - -msg: str -__extra__all__: Any -CONN_DELETE_TCB: str -ERROR_PARTIAL_COPY: int -PYPY: Any -AF_LINK: int -AddressFamily: Any -TCP_STATUSES: Any - -class Priority(enum.IntEnum): - ABOVE_NORMAL_PRIORITY_CLASS: Any - BELOW_NORMAL_PRIORITY_CLASS: Any - HIGH_PRIORITY_CLASS: Any - IDLE_PRIORITY_CLASS: Any - NORMAL_PRIORITY_CLASS: Any - REALTIME_PRIORITY_CLASS: Any - -IOPRIO_VERYLOW: int -IOPRIO_LOW: int -IOPRIO_NORMAL: int -IOPRIO_HIGH: int - -class IOPriority(enum.IntEnum): - IOPRIO_VERYLOW: int - IOPRIO_LOW: int - IOPRIO_NORMAL: int - IOPRIO_HIGH: int - -pinfo_map: Any - -class scputimes(NamedTuple): - user: Any - system: Any - idle: Any - interrupt: Any - dpc: Any - -class svmem(NamedTuple): - total: Any - available: Any - percent: Any - used: Any - free: Any - -class pmem(NamedTuple): - rss: Any - vms: Any - num_page_faults: Any - peak_wset: Any - wset: Any - peak_paged_pool: Any - paged_pool: Any - peak_nonpaged_pool: Any - nonpaged_pool: Any - pagefile: Any - peak_pagefile: Any - private: Any - -pfullmem: Any - -class pmmap_grouped(NamedTuple): - path: Any - rss: Any - -pmmap_ext: Any - -class pio(NamedTuple): - read_count: Any - write_count: Any - read_bytes: Any - write_bytes: Any - other_count: Any - other_bytes: Any - -def convert_dos_path(s): ... -def py2_strencode(s): ... -def getpagesize(): ... -def virtual_memory(): ... -def swap_memory(): ... - -disk_io_counters: Any - -def disk_usage(path): ... -def disk_partitions(all): ... -def cpu_times(): ... -def per_cpu_times(): ... -def cpu_count_logical(): ... -def cpu_count_physical(): ... -def cpu_stats(): ... -def cpu_freq(): ... -def getloadavg(): ... -def net_connections(kind, _pid: int = ...): ... -def net_if_stats(): ... -def net_io_counters(): ... -def net_if_addrs(): ... -def sensors_battery(): ... -def boot_time(): ... -def users(): ... -def win_service_iter() -> None: ... -def win_service_get(name): ... - -class WindowsService: - def __init__(self, name, display_name) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def name(self): ... - def display_name(self): ... - def binpath(self): ... - def username(self): ... - def start_type(self): ... - def pid(self): ... - def status(self): ... - def description(self): ... - def as_dict(self): ... - -pids: Any -pid_exists: Any -ppid_map: Any - -def is_permission_err(exc): ... -def convert_oserror(exc, pid: Any | None = ..., name: Any | None = ...): ... -def wrap_exceptions(fun): ... -def retry_error_partial_copy(fun): ... - -class Process: - pid: Any - def __init__(self, pid) -> None: ... - def oneshot_enter(self) -> None: ... - def oneshot_exit(self) -> None: ... - def name(self): ... - def exe(self): ... - def cmdline(self): ... - def environ(self): ... - def ppid(self): ... - def memory_info(self): ... - def memory_full_info(self): ... - def memory_maps(self) -> None: ... - def kill(self): ... - def send_signal(self, sig) -> None: ... - def wait(self, timeout: Any | None = ...): ... - def username(self): ... - def create_time(self): ... - def num_threads(self): ... - def threads(self): ... - def cpu_times(self): ... - def suspend(self) -> None: ... - def resume(self) -> None: ... - def cwd(self): ... - def open_files(self): ... - def connections(self, kind: str = ...): ... - def nice_get(self): ... - def nice_set(self, value): ... - def ionice_get(self): ... - def ionice_set(self, ioclass, value) -> None: ... - def io_counters(self): ... - def status(self): ... - def cpu_affinity_get(self): ... - def cpu_affinity_set(self, value): ... - def num_handles(self): ... - def num_ctx_switches(self): ... +import sys + +if sys.platform == "win32": + import enum + from collections.abc import Callable, Iterable, Iterator + from signal import Signals + from typing import Final, Literal, ParamSpec, TypedDict, TypeVar, overload, type_check_only + + from psutil import _psutil_windows + from psutil._common import ( + ENCODING as ENCODING, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + TimeoutExpired as TimeoutExpired, + conn_tmap as conn_tmap, + conn_to_ntuple as conn_to_ntuple, + debug as debug, + isfile_strict as isfile_strict, + memoize as memoize, + memoize_when_activated as memoize_when_activated, + parse_environ_block as parse_environ_block, + usage_percent as usage_percent, + ) + from psutil._psutil_windows import ( + ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, + BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, + HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, + IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, + NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, + REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, + ) + + from . import _ntuples as ntp + + __extra__all__: Final[list[str]] + CONN_DELETE_TCB: Final = "DELETE_TCB" + ERROR_PARTIAL_COPY: Final = 299 + PYPY: Final[bool] + + class AddressFamily(enum.IntEnum): + AF_LINK = -1 + + AF_LINK: Final = AddressFamily.AF_LINK + TCP_STATUSES: Final[dict[int, str]] + + # These noqas workaround https://github.com/astral-sh/ruff/issues/10874 + class Priority(enum.IntEnum): + ABOVE_NORMAL_PRIORITY_CLASS = _psutil_windows.ABOVE_NORMAL_PRIORITY_CLASS + BELOW_NORMAL_PRIORITY_CLASS = _psutil_windows.BELOW_NORMAL_PRIORITY_CLASS + HIGH_PRIORITY_CLASS = _psutil_windows.HIGH_PRIORITY_CLASS + IDLE_PRIORITY_CLASS = _psutil_windows.IDLE_PRIORITY_CLASS + NORMAL_PRIORITY_CLASS = _psutil_windows.NORMAL_PRIORITY_CLASS + REALTIME_PRIORITY_CLASS = _psutil_windows.REALTIME_PRIORITY_CLASS + + class IOPriority(enum.IntEnum): + IOPRIO_VERYLOW = 0 + IOPRIO_LOW = 1 + IOPRIO_NORMAL = 2 + IOPRIO_HIGH = 3 + + IOPRIO_VERYLOW: Final = IOPriority.IOPRIO_VERYLOW + IOPRIO_LOW: Final = IOPriority.IOPRIO_LOW + IOPRIO_NORMAL: Final = IOPriority.IOPRIO_NORMAL + IOPRIO_HIGH: Final = IOPriority.IOPRIO_HIGH + + pinfo_map: Final[dict[str, int]] + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + def convert_dos_path(s: str) -> str: ... + def getpagesize() -> int: ... + def virtual_memory() -> ntp.svmem: ... + def swap_memory() -> ntp.sswap: ... + + heap_info = _psutil_windows.heap_info + heap_trim = _psutil_windows.heap_trim + disk_io_counters = _psutil_windows.disk_io_counters + + def disk_usage(path: str) -> ntp.sdiskusage: ... + def disk_partitions(all: bool) -> list[ntp.sdiskpart]: ... + def cpu_times() -> ntp.scputimes: ... + def per_cpu_times() -> list[ntp.scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def cpu_freq() -> list[ntp.scpufreq]: ... + def getloadavg() -> tuple[float, float, float]: ... + + @overload + def net_connections(kind: str, _pid: Literal[-1] = -1) -> list[ntp.sconn]: ... + @overload + def net_connections(kind: str, _pid: int = -1) -> list[ntp.pconn]: ... + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, None, None]]: ... + def sensors_battery() -> ntp.sbattery | None: ... + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + def win_service_iter() -> Iterator[WindowsService]: ... + def win_service_get(name: str) -> WindowsService: ... + + @type_check_only + class _WindowsServiceAttrs(TypedDict): + name: str + display_name: str | None + description: str + binpath: str + username: str + start_type: str + status: str + pid: int | None + + class WindowsService: + def __init__(self, name: str, display_name: str | None) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def name(self) -> str: ... + def display_name(self) -> str | None: ... + def binpath(self) -> str: ... + def username(self) -> str: ... + def start_type(self) -> str: ... + def pid(self) -> int: ... + def status(self) -> str: ... + def description(self) -> str: ... + def as_dict(self) -> _WindowsServiceAttrs: ... + + pids = _psutil_windows.pids + pid_exists = _psutil_windows.pid_exists + ppid_map = _psutil_windows.ppid_map + + def is_permission_err(exc: OSError) -> bool: ... + + @overload + def convert_oserror(exc: PermissionError, pid: int | None = None, name: str | None = None) -> AccessDenied: ... + @overload + def convert_oserror(exc: OSError, pid: int | None = None, name: str | None = None) -> AccessDenied | NoSuchProcess: ... + + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + def retry_error_partial_copy(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def ppid(self) -> int: ... + def memory_info(self) -> ntp.pmem: ... + def memory_full_info(self) -> ntp.pfullmem: ... + def memory_maps(self) -> Iterator[tuple[str, str, str, int]]: ... + def kill(self) -> None: ... + def send_signal(self, sig: Literal[Signals.SIGTERM, Signals.CTRL_C_EVENT, Signals.CTRL_BREAK_EVENT]) -> None: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def username(self) -> str: ... + def create_time(self, fast_only: bool = False) -> float: ... + def num_threads(self) -> int: ... + def threads(self) -> list[ntp.pthread]: ... + def cpu_times(self) -> ntp.pcputimes: ... + def suspend(self) -> None: ... + def resume(self) -> None: ... + def cwd(self) -> str: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def nice_get(self) -> Priority: ... + def nice_set(self, value: int) -> None: ... + def ionice_get(self) -> IOPriority: ... + def ionice_set(self, ioclass: int, value: None) -> None: ... + def io_counters(self) -> ntp.pio: ... + def status(self) -> Literal["stopped", "running"]: ... + def cpu_affinity_get(self) -> list[int]: ... + def cpu_affinity_set(self, value: Iterable[int]) -> None: ... + def num_handles(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... diff --git a/stubs/psycopg2/@tests/stubtest_allowlist.txt b/stubs/psycopg2/@tests/stubtest_allowlist.txt index 0a93eaedc654..685b7d8f6f55 100644 --- a/stubs/psycopg2/@tests/stubtest_allowlist.txt +++ b/stubs/psycopg2/@tests/stubtest_allowlist.txt @@ -1,5 +1,2 @@ -psycopg2.connection -psycopg2.cursor -psycopg2.pool.AbstractConnectionPool.closeall -psycopg2.pool.AbstractConnectionPool.getconn -psycopg2.pool.AbstractConnectionPool.putconn +psycopg2.pool.AbstractConnectionPool.(closeall|getconn|putconn) +psycopg2.(_psycopg|extensions).connection.async # async is a reserved keyword diff --git a/stubs/psycopg2/@tests/test_cases/check_connect.py b/stubs/psycopg2/@tests/test_cases/check_connect.py new file mode 100644 index 000000000000..527ba9d3d88a --- /dev/null +++ b/stubs/psycopg2/@tests/test_cases/check_connect.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +import psycopg2 +from psycopg2.extensions import connection, cursor + + +class MyCursor(cursor): + pass + + +class MyConnection(connection): + pass + + +def custom_connection(dsn: str) -> MyConnection: + return MyConnection(dsn, async_=0) + + +# -> psycopg2.extensions.connection +assert_type(psycopg2.connect(), connection) +assert_type(psycopg2.connect("test-conn"), connection) +assert_type(psycopg2.connect(None), connection) +assert_type(psycopg2.connect("test-conn", connection_factory=None), connection) + +assert_type(psycopg2.connect(cursor_factory=MyCursor), connection) +assert_type(psycopg2.connect("test-conn", cursor_factory=MyCursor), connection) +assert_type(psycopg2.connect(None, cursor_factory=MyCursor), connection) +assert_type(psycopg2.connect("test-conn", connection_factory=None, cursor_factory=MyCursor), connection) + +# -> custom_connection +assert_type(psycopg2.connect(connection_factory=MyConnection), MyConnection) +assert_type(psycopg2.connect("test-conn", connection_factory=MyConnection), MyConnection) +assert_type(psycopg2.connect("test-conn", MyConnection), MyConnection) +assert_type(psycopg2.connect(connection_factory=custom_connection), MyConnection) + +assert_type(psycopg2.connect(connection_factory=MyConnection, cursor_factory=MyCursor), MyConnection) +assert_type(psycopg2.connect("test-conn", connection_factory=MyConnection, cursor_factory=MyCursor), MyConnection) +assert_type(psycopg2.connect(connection_factory=custom_connection, cursor_factory=MyCursor), MyConnection) diff --git a/stubs/psycopg2/@tests/test_cases/check_extensions.py b/stubs/psycopg2/@tests/test_cases/check_extensions.py new file mode 100644 index 000000000000..d8a2fb8d1d8e --- /dev/null +++ b/stubs/psycopg2/@tests/test_cases/check_extensions.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import io +from typing_extensions import assert_type + +import psycopg2.extensions +import psycopg2.extras +from psycopg2.extensions import make_dsn + +# make_dsn +# -------- + +# (None) -> str +assert_type(make_dsn(), str) +assert_type(make_dsn(None), str) +assert_type(make_dsn(dsn=None), str) + +# (bytes) -> bytes +assert_type(make_dsn(b""), bytes) +assert_type(make_dsn(dsn=b""), bytes) + +# (bytes, **Kwargs) -> str +assert_type(make_dsn(b"", database=""), str) +assert_type(make_dsn(dsn=b"", database=""), str) + +# (str, **OptionalKwargs) -> str +assert_type(make_dsn(""), str) +assert_type(make_dsn(dsn=""), str) +assert_type(make_dsn("", database=None), str) +assert_type(make_dsn(dsn="", database=None), str) + + +# connection.cursor +# ----------------- + +# (name?, None?, ...) -> psycopg2.extensions.cursor +conn = psycopg2.connect("test-conn") +assert_type(conn.cursor(), psycopg2.extensions.cursor) +assert_type(conn.cursor("test-cur"), psycopg2.extensions.cursor) +assert_type(conn.cursor("test-cur", None), psycopg2.extensions.cursor) +assert_type(conn.cursor("test-cur", cursor_factory=None), psycopg2.extensions.cursor) + + +# (name?, cursor_factory(), ...) -> custom_cursor +class MyCursor(psycopg2.extensions.cursor): + pass + + +assert_type(conn.cursor("test-cur", cursor_factory=MyCursor), MyCursor) +assert_type(conn.cursor("test-cur", cursor_factory=lambda c, n: MyCursor(c, n)), MyCursor) + +dconn = psycopg2.extras.DictConnection("test-dconn") +assert_type(dconn.cursor(), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur"), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur", None), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur", cursor_factory=None), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur", cursor_factory=MyCursor), MyCursor) + +# file protocols +# -------------- +cur = conn.cursor() +cur.copy_from(io.StringIO(), "table") diff --git a/stubs/psycopg2/METADATA.toml b/stubs/psycopg2/METADATA.toml index 0009f38f042f..a7f508256cc8 100644 --- a/stubs/psycopg2/METADATA.toml +++ b/stubs/psycopg2/METADATA.toml @@ -1 +1,3 @@ -version = "2.9.*" \ No newline at end of file +version = "2.9.13" +upstream-repository = "https://github.com/psycopg/psycopg2" +partial-stub = false diff --git a/stubs/psycopg2/psycopg2/__init__.pyi b/stubs/psycopg2/psycopg2/__init__.pyi index d1165cd2d4ec..501a3d0f6ecc 100644 --- a/stubs/psycopg2/psycopg2/__init__.pyi +++ b/stubs/psycopg2/psycopg2/__init__.pyi @@ -1,6 +1,7 @@ -from typing import Any +from collections.abc import Callable +from typing import Any, TypeVar, overload -# connection and cursor not available at runtime +from psycopg2 import errors as errors, extensions as extensions from psycopg2._psycopg import ( BINARY as BINARY, DATETIME as DATETIME, @@ -26,12 +27,33 @@ from psycopg2._psycopg import ( Warning as Warning, __libpq_version__ as __libpq_version__, apilevel as apilevel, - connection as connection, - cursor as cursor, + connection, + cursor, paramstyle as paramstyle, threadsafety as threadsafety, ) +_T_conn = TypeVar("_T_conn", bound=connection) + +@overload +def connect( + dsn: str | None, + connection_factory: Callable[..., _T_conn], + cursor_factory: Callable[[connection, str | bytes | None], cursor] | None = None, + **kwargs: Any, +) -> _T_conn: ... +@overload +def connect( + dsn: str | None = None, + *, + connection_factory: Callable[..., _T_conn], + cursor_factory: Callable[[connection, str | bytes | None], cursor] | None = None, + **kwargs: Any, +) -> _T_conn: ... +@overload def connect( - dsn: Any | None = ..., connection_factory: Any | None = ..., cursor_factory: Any | None = ..., **kwargs + dsn: str | None = None, + connection_factory: Callable[..., connection] | None = None, + cursor_factory: Callable[[connection, str | bytes | None], cursor] | None = None, + **kwargs: Any, ) -> connection: ... diff --git a/stubs/psycopg2/psycopg2/_ipaddress.pyi b/stubs/psycopg2/psycopg2/_ipaddress.pyi index c3476617f856..60085a3beb22 100644 --- a/stubs/psycopg2/psycopg2/_ipaddress.pyi +++ b/stubs/psycopg2/psycopg2/_ipaddress.pyi @@ -1,8 +1,9 @@ -from typing import Any +import ipaddress as ipaddress +from _typeshed import Unused -ipaddress: Any +from psycopg2._psycopg import QuotedString, connection, cursor -def register_ipaddress(conn_or_curs: Any | None = ...) -> None: ... -def cast_interface(s, cur: Any | None = ...): ... -def cast_network(s, cur: Any | None = ...): ... -def adapt_ipaddress(obj): ... +def register_ipaddress(conn_or_curs: connection | cursor | None = None) -> None: ... +def cast_interface(s: str, cur: Unused = None) -> ipaddress.IPv4Interface | ipaddress.IPv6Interface | None: ... +def cast_network(s: str, cur: Unused = None) -> ipaddress.IPv4Network | ipaddress.IPv6Network | None: ... +def adapt_ipaddress(obj: object) -> QuotedString: ... diff --git a/stubs/psycopg2/psycopg2/_json.pyi b/stubs/psycopg2/psycopg2/_json.pyi index e7e8619c6081..40ce54d4aef8 100644 --- a/stubs/psycopg2/psycopg2/_json.pyi +++ b/stubs/psycopg2/psycopg2/_json.pyi @@ -1,4 +1,8 @@ +from collections.abc import Callable from typing import Any +from typing_extensions import Self + +from psycopg2._psycopg import _type, connection, cursor JSON_OID: int JSONARRAY_OID: int @@ -7,19 +11,23 @@ JSONBARRAY_OID: int class Json: adapted: Any - def __init__(self, adapted, dumps: Any | None = ...) -> None: ... - def __conform__(self, proto): ... - def dumps(self, obj): ... - def prepare(self, conn) -> None: ... - def getquoted(self): ... + def __init__(self, adapted: Any, dumps: Callable[..., str] | None = None) -> None: ... + def __conform__(self, proto) -> Self | None: ... + def dumps(self, obj: Any) -> str: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... def register_json( - conn_or_curs: Any | None = ..., - globally: bool = ..., - loads: Any | None = ..., - oid: Any | None = ..., - array_oid: Any | None = ..., - name: str = ..., -): ... -def register_default_json(conn_or_curs: Any | None = ..., globally: bool = ..., loads: Any | None = ...): ... -def register_default_jsonb(conn_or_curs: Any | None = ..., globally: bool = ..., loads: Any | None = ...): ... + conn_or_curs: connection | cursor | None = None, + globally: bool = False, + loads: Callable[..., Any] | None = None, + oid: int | None = None, + array_oid: int | None = None, + name: str = "json", +) -> tuple[_type, _type | None]: ... +def register_default_json( + conn_or_curs: connection | cursor | None = None, globally: bool = False, loads: Callable[..., Any] | None = None +) -> tuple[_type, _type | None]: ... +def register_default_jsonb( + conn_or_curs: connection | cursor | None = None, globally: bool = False, loads: Callable[..., Any] | None = None +) -> tuple[_type, _type | None]: ... diff --git a/stubs/psycopg2/psycopg2/_psycopg.pyi b/stubs/psycopg2/psycopg2/_psycopg.pyi index 149a29f52276..1cde17a9a4de 100644 --- a/stubs/psycopg2/psycopg2/_psycopg.pyi +++ b/stubs/psycopg2/psycopg2/_psycopg.pyi @@ -1,86 +1,199 @@ -from typing import Any, Callable, Tuple, TypeVar, overload - -import psycopg2 -import psycopg2.extensions - -BINARY: Any -BINARYARRAY: Any -BOOLEAN: Any -BOOLEANARRAY: Any -BYTES: Any -BYTESARRAY: Any -CIDRARRAY: Any -DATE: Any -DATEARRAY: Any -DATETIME: Any -DATETIMEARRAY: Any -DATETIMETZ: Any -DATETIMETZARRAY: Any -DECIMAL: Any -DECIMALARRAY: Any -FLOAT: Any -FLOATARRAY: Any -INETARRAY: Any -INTEGER: Any -INTEGERARRAY: Any -INTERVAL: Any -INTERVALARRAY: Any -LONGINTEGER: Any -LONGINTEGERARRAY: Any -MACADDRARRAY: Any -NUMBER: Any -PYDATE: Any -PYDATEARRAY: Any -PYDATETIME: Any -PYDATETIMEARRAY: Any -PYDATETIMETZ: Any -PYDATETIMETZARRAY: Any -PYINTERVAL: Any -PYINTERVALARRAY: Any -PYTIME: Any -PYTIMEARRAY: Any +import datetime as dt +from _typeshed import ConvertibleToInt, Incomplete, SupportsRead, SupportsReadline, SupportsWrite, Unused +from collections.abc import Callable, Iterable, Mapping, Sequence +from types import TracebackType +from typing import Any, Literal, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, disjoint_base + +from psycopg2.extras import ReplicationCursor as extras_ReplicationCursor +from psycopg2.sql import Composable + +_Vars: TypeAlias = Sequence[Any] | Mapping[str, Any] | None + +@type_check_only +class _type: + # The class doesn't exist at runtime but following attributes have type "psycopg2._psycopg.type" + name: str + values: tuple[int, ...] + def __call__(self, value: str | bytes | None, cur: cursor | None, /) -> Any: ... + +BINARY: _type +BINARYARRAY: _type +BOOLEAN: _type +BOOLEANARRAY: _type +BYTES: _type +BYTESARRAY: _type +CIDRARRAY: _type +DATE: _type +DATEARRAY: _type +DATETIME: _type +DATETIMEARRAY: _type +DATETIMETZ: _type +DATETIMETZARRAY: _type +DECIMAL: _type +DECIMALARRAY: _type +FLOAT: _type +FLOATARRAY: _type +INETARRAY: _type +INTEGER: _type +INTEGERARRAY: _type +INTERVAL: _type +INTERVALARRAY: _type +LONGINTEGER: _type +LONGINTEGERARRAY: _type +MACADDRARRAY: _type +NUMBER: _type +PYDATE: _type +PYDATEARRAY: _type +PYDATETIME: _type +PYDATETIMEARRAY: _type +PYDATETIMETZ: _type +PYDATETIMETZARRAY: _type +PYINTERVAL: _type +PYINTERVALARRAY: _type +PYTIME: _type +PYTIMEARRAY: _type +ROWID: _type +ROWIDARRAY: _type +STRING: _type +STRINGARRAY: _type +TIME: _type +TIMEARRAY: _type +UNICODE: _type +UNICODEARRAY: _type +UNKNOWN: _type + REPLICATION_LOGICAL: int REPLICATION_PHYSICAL: int -ROWID: Any -ROWIDARRAY: Any -STRING: Any -STRINGARRAY: Any -TIME: Any -TIMEARRAY: Any -UNICODE: Any -UNICODEARRAY: Any -UNKNOWN: Any -adapters: dict[Any, Any] + +@type_check_only +class _ISQLQuoteProto(Protocol): + # Objects conforming this protocol should implement a getquoted() and optionally a prepare() method. + # The real ISQLQuote class is implemented below with more stuff. + def getquoted(self) -> bytes: ... + # def prepare(self, __conn: connection) -> None: ... # optional + +adapters: dict[tuple[type[Any], type[ISQLQuote]], Callable[[Any], _ISQLQuoteProto]] apilevel: str binary_types: dict[Any, Any] -encodings: dict[Any, Any] +encodings: dict[str, str] paramstyle: str -sqlstate_errors: dict[Any, Any] -string_types: dict[Any, Any] +sqlstate_errors: dict[str, type[Error]] +string_types: dict[int, _type] threadsafety: int __libpq_version__: int +_T_co = TypeVar("_T_co", covariant=True) + +@type_check_only +class _SupportsReadAndReadline(SupportsRead[_T_co], SupportsReadline[_T_co], Protocol[_T_co]): ... + +@disjoint_base +class cursor: + arraysize: int + binary_types: Incomplete | None + connection: _Connection + itersize: int + row_factory: Incomplete | None + scrollable: bool | None + string_types: Incomplete | None + tzinfo_factory: Callable[..., dt.tzinfo] + withhold: bool + def __init__(self, conn: _Connection, name: str | bytes | None = None) -> None: ... + @property + def closed(self) -> bool: ... + @property + def lastrowid(self) -> int: ... + @property + def name(self) -> Incomplete | None: ... + @property + def query(self) -> bytes | None: ... + @property + def description(self) -> tuple[Column, ...] | None: ... + @property + def rowcount(self) -> int: ... + @property + def rownumber(self) -> int: ... + @property + def typecaster(self) -> Incomplete | None: ... + @property + def statusmessage(self) -> str | None: ... + @property + def pgresult_ptr(self) -> int | None: ... + def callproc(self, procname: str | bytes, parameters: _Vars = None, /) -> None: ... + def cast(self, oid: int, s: str | bytes, /) -> Any: ... + def close(self) -> None: ... + def copy_expert( + self, + sql: str | bytes | Composable, + file: _SupportsReadAndReadline[bytes] | SupportsWrite[bytes] | TextIO, + size: int = 8192, + ) -> None: ... + def copy_from( + self, + file: _SupportsReadAndReadline[bytes] | _SupportsReadAndReadline[str], + table: str, + sep: str = "\t", + null: str = "\\N", + size: int = 8192, + columns: Iterable[str] | None = None, + ) -> None: ... + def copy_to( + self, + file: SupportsWrite[bytes] | TextIO, + table: str, + sep: str = "\t", + null: str = "\\N", + columns: Iterable[str] | None = None, + ) -> None: ... + def execute(self, query: str | bytes | Composable, vars: _Vars = None) -> None: ... + def executemany(self, query: str | bytes | Composable, vars_list: Iterable[_Vars]) -> None: ... + def fetchall(self) -> list[tuple[Any, ...]]: ... + def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]: ... + def fetchone(self) -> tuple[Any, ...] | None: ... + def mogrify(self, query: str | bytes | Composable, vars: _Vars | None = None) -> bytes: ... + def nextset(self) -> Never: ... # not supported + def scroll(self, value: int, mode: Literal["absolute", "relative"] = "relative") -> None: ... + def setinputsizes(self, sizes: Unused) -> None: ... + def setoutputsize(self, size: int, column: int = ..., /) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[Any, ...]: ... + +_Cursor: TypeAlias = cursor + +@disjoint_base class AsIs: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, obj: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... +@disjoint_base class Binary: - adapted: Any - buffer: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def prepare(self, conn): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, str: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def buffer(self) -> Any: ... + def getquoted(self) -> bytes: ... + def prepare(self, conn: connection, /) -> None: ... + def __conform__(self, proto, /) -> Self | None: ... +@disjoint_base class Boolean: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, obj: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... +@disjoint_base class Column: display_size: Any internal_size: Any @@ -92,158 +205,202 @@ class Column: table_oid: Any type_code: Any def __init__(self, *args, **kwargs) -> None: ... - def __eq__(self, other): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... + def __eq__(self, other, /): ... + def __ge__(self, other, /): ... + def __getitem__(self, index, /): ... def __getstate__(self): ... - def __gt__(self, other): ... - def __le__(self, other): ... - def __len__(self): ... - def __lt__(self, other): ... - def __ne__(self, other): ... - def __setstate__(self, state): ... + def __gt__(self, other, /): ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + def __setstate__(self, state, /): ... +@disjoint_base class ConnectionInfo: - backend_pid: Any - dbname: Any - dsn_parameters: Any - error_message: Any - host: Any - needs_password: Any - options: Any - password: Any - port: Any - protocol_version: Any - server_version: Any - socket: Any - ssl_attribute_names: Any - ssl_in_use: Any - status: Any - transaction_status: Any - used_password: Any - user: Any - def __init__(self, *args, **kwargs) -> None: ... - def parameter_status(self, *args, **kwargs): ... - def ssl_attribute(self, *args, **kwargs): ... - -class DataError(psycopg2.DatabaseError): ... -class DatabaseError(psycopg2.Error): ... - -class Decimal: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... - -class Diagnostics: - column_name: Any - constraint_name: Any - context: Any - datatype_name: Any - internal_position: Any - internal_query: Any - message_detail: Any - message_hint: Any - message_primary: Any - schema_name: Any - severity: Any - severity_nonlocalized: Any - source_file: Any - source_function: Any - source_line: Any - sqlstate: Any - statement_position: Any - table_name: Any + # Note: the following properties can be None if their corresponding libpq function + # returns NULL. They're not annotated as such, because this is very unlikely in + # practice---the psycopg2 docs [1] don't even mention this as a possibility! + # + # - db_name + # - user + # - password + # - host + # - port + # - options + # + # (To prove this, one needs to inspect the psycopg2 source code [2], plus the + # documentation [3] and source code [4] of the corresponding libpq calls.) + # + # [1]: https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.ConnectionInfo + # [2]: https://github.com/psycopg/psycopg2/blob/1d3a89a0bba621dc1cc9b32db6d241bd2da85ad1/psycopg/conninfo_type.c#L52 and below + # [3]: https://www.postgresql.org/docs/current/libpq-status.html + # [4]: https://github.com/postgres/postgres/blob/b39838889e76274b107935fa8e8951baf0e8b31b/src/interfaces/libpq/fe-connect.c#L6754 and below # ruff: ignore[line-too-long] + @property + def backend_pid(self) -> int: ... + @property + def dbname(self) -> str: ... + @property + def dsn_parameters(self) -> dict[str, str]: ... + @property + def error_message(self) -> str | None: ... + @property + def host(self) -> str: ... + @property + def needs_password(self) -> bool: ... + @property + def options(self) -> str: ... + @property + def password(self) -> str: ... + @property + def port(self) -> int: ... + @property + def protocol_version(self) -> int: ... + @property + def server_version(self) -> int: ... + @property + def socket(self) -> int: ... + @property + def ssl_attribute_names(self) -> list[str]: ... + @property + def ssl_in_use(self) -> bool: ... + @property + def status(self) -> int: ... + @property + def transaction_status(self) -> int: ... + @property + def used_password(self) -> bool: ... + @property + def user(self) -> str: ... def __init__(self, *args, **kwargs) -> None: ... + def parameter_status(self, name: str) -> str | None: ... + def ssl_attribute(self, name: str) -> str | None: ... +@disjoint_base class Error(Exception): - cursor: Any - diag: Any - pgcode: Any - pgerror: Any + cursor: _Cursor | None + diag: Diagnostics + pgcode: str | None + pgerror: str | None def __init__(self, *args, **kwargs) -> None: ... def __reduce__(self): ... - def __setstate__(self, state): ... + def __setstate__(self, state, /): ... -class Float: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class QueryCanceledError(OperationalError): ... +class TransactionRollbackError(OperationalError): ... +class InterfaceError(Error): ... +class Warning(Exception): ... +@disjoint_base class ISQLQuote: _wrapped: Any - def __init__(self, *args, **kwargs) -> None: ... - def getbinary(self, *args, **kwargs): ... - def getbuffer(self, *args, **kwargs): ... - def getquoted(self, *args, **kwargs): ... + def __init__(self, wrapped: object, /, **kwargs) -> None: ... + def getbinary(self): ... + def getbuffer(self): ... + def getquoted(self) -> bytes: ... -class Int: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... +@disjoint_base +class Decimal: + def __init__(self, value: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... -class IntegrityError(psycopg2.DatabaseError): ... -class InterfaceError(psycopg2.Error): ... -class InternalError(psycopg2.DatabaseError): ... +@disjoint_base +class Diagnostics: + column_name: str | None + constraint_name: str | None + context: str | None + datatype_name: str | None + internal_position: str | None + internal_query: str | None + message_detail: str | None + message_hint: str | None + message_primary: str | None + schema_name: str | None + severity: str | None + severity_nonlocalized: str | None + source_file: str | None + source_function: str | None + source_line: str | None + sqlstate: str | None + statement_position: str | None + table_name: str | None + def __init__(self, err: Error, /) -> None: ... -class List: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def prepare(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... +@disjoint_base +class Float: + def __init__(self, value: float, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> float: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Int: + def __init__(self, value: ConvertibleToInt, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... -class NotSupportedError(psycopg2.DatabaseError): ... +@disjoint_base +class List: + def __init__(self, objs: list[object], /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> list[Any]: ... + def getquoted(self) -> bytes: ... + def prepare(self, conn: connection, /) -> None: ... + def __conform__(self, proto, /) -> Self | None: ... +@disjoint_base class Notify: channel: Any payload: Any pid: Any def __init__(self, *args, **kwargs) -> None: ... - def __eq__(self, other): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... - def __gt__(self, other): ... - def __hash__(self): ... - def __le__(self, other): ... - def __len__(self): ... - def __lt__(self, other): ... - def __ne__(self, other): ... - -class OperationalError(psycopg2.DatabaseError): ... -class ProgrammingError(psycopg2.DatabaseError): ... -class QueryCanceledError(psycopg2.OperationalError): ... + def __eq__(self, other, /): ... + def __ge__(self, other, /): ... + def __getitem__(self, index, /): ... + def __gt__(self, other, /): ... + def __hash__(self) -> int: ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... +@disjoint_base class QuotedString: - adapted: Any - buffer: Any - encoding: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def prepare(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... - -class ReplicationConnection(psycopg2.extensions.connection): - autocommit: Any - isolation_level: Any - replication_type: Any - reset: Any - set_isolation_level: Any - set_session: Any - def __init__(self, *args, **kwargs) -> None: ... + encoding: str + def __init__(self, str: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def buffer(self) -> Any: ... + def getquoted(self) -> bytes: ... + def prepare(self, conn: connection, /) -> None: ... + def __conform__(self, proto, /) -> Self | None: ... -class ReplicationCursor(psycopg2.extensions.cursor): +@disjoint_base +class ReplicationCursor(cursor): feedback_timestamp: Any io_timestamp: Any wal_end: Any def __init__(self, *args, **kwargs) -> None: ... def consume_stream(self, consumer, keepalive_interval=...): ... - def read_message(self, *args, **kwargs): ... + def read_message(self) -> Incomplete | None: ... def send_feedback(self, write_lsn=..., flush_lsn=..., apply_lsn=..., reply=..., force=...): ... def start_replication_expert(self, command, decode=..., status_interval=...): ... +@disjoint_base class ReplicationMessage: cursor: Any data_size: Any @@ -253,9 +410,7 @@ class ReplicationMessage: wal_end: Any def __init__(self, *args, **kwargs) -> None: ... -class TransactionRollbackError(psycopg2.OperationalError): ... -class Warning(Exception): ... - +@disjoint_base class Xid: bqual: Any database: Any @@ -265,114 +420,170 @@ class Xid: prepared: Any def __init__(self, *args, **kwargs) -> None: ... def from_string(self, *args, **kwargs): ... - def __getitem__(self, index): ... - def __len__(self): ... + def __getitem__(self, index, /): ... + def __len__(self) -> int: ... -_cursor = cursor -_T_cur = TypeVar("_T_cur", bound=_cursor) +_T_cur = TypeVar("_T_cur", bound=cursor) +_Lobject: TypeAlias = lobject +@disjoint_base class connection: - DataError: Any - DatabaseError: Any - Error: Any - IntegrityError: Any - InterfaceError: Any - InternalError: Any - NotSupportedError: Any - OperationalError: Any - ProgrammingError: Any - Warning: Any - async_: Any + DataError: type[DataError] + DatabaseError: type[DatabaseError] + Error: type[Error] + IntegrityError: type[IntegrityError] + InterfaceError: type[InterfaceError] + InternalError: type[InternalError] + NotSupportedError: type[NotSupportedError] + OperationalError: type[OperationalError] + ProgrammingError: type[ProgrammingError] + Warning: type[Warning] + @property + def async_(self) -> int: ... + autocommit: bool + @property + def binary_types(self) -> dict[Incomplete, Incomplete]: ... + @property + def closed(self) -> int: ... + cursor_factory: Callable[[connection, str | bytes | None], _Cursor] + @property + def dsn(self) -> str: ... + @property + def encoding(self) -> str: ... + @property + def info(self) -> ConnectionInfo: ... + + @property + def isolation_level(self) -> int | None: ... + @isolation_level.setter + def isolation_level(self, value: str | bytes | int | None, /) -> None: ... + + notices: list[str] + notifies: list[Notify] + @property + def pgconn_ptr(self) -> int | None: ... + @property + def protocol_version(self) -> int: ... + + @property + def deferrable(self) -> bool | None: ... + @deferrable.setter + def deferrable(self, value: Literal["default"] | bool | None, /) -> None: ... + + @property + def readonly(self) -> bool | None: ... + @readonly.setter + def readonly(self, value: Literal["default"] | bool | None, /) -> None: ... + + @property + def server_version(self) -> int: ... + @property + def status(self) -> int: ... + @property + def string_types(self) -> dict[Incomplete, Incomplete]: ... + # Really it's dsn: str, async: int = 0, async_: int = 0, but + # that would be a syntax error. + def __init__(self, dsn: str, *, async_: int = 0) -> None: ... + def cancel(self) -> None: ... + def close(self) -> None: ... + def commit(self) -> None: ... + + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> _Cursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + + def fileno(self) -> int: ... + def get_backend_pid(self) -> int: ... + def get_dsn_parameters(self) -> dict[str, str]: ... + def get_native_connection(self): ... + def get_parameter_status(self, parameter: str) -> str | None: ... + def get_transaction_status(self) -> int: ... + def isexecuting(self) -> bool: ... + def lobject( + self, + oid: int = ..., + mode: str | None = ..., + new_oid: int = ..., + new_file: str | None = ..., + lobject_factory: type[_Lobject] = ..., + ) -> _Lobject: ... + def poll(self) -> int: ... + def reset(self) -> None: ... + def rollback(self) -> None: ... + def set_client_encoding(self, encoding: str) -> None: ... + def set_isolation_level(self, level: int | None) -> None: ... + def set_session( + self, + isolation_level: str | bytes | int | None = ..., + readonly: bool | Literal["default", b"default"] | None = ..., + deferrable: bool | Literal["default", b"default"] | None = ..., + autocommit: bool = ..., + ) -> None: ... + def tpc_begin(self, xid: str | bytes | Xid) -> None: ... + def tpc_commit(self, xid: str | bytes | Xid = ..., /) -> None: ... + def tpc_prepare(self) -> None: ... + def tpc_recover(self) -> list[Xid]: ... + def tpc_rollback(self, xid: str | bytes | Xid = ..., /) -> None: ... + def xid(self, format_id, gtrid, bqual) -> Xid: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, name: BaseException | None, tb: TracebackType | None, /) -> None: ... + +_Connection: TypeAlias = connection + +@disjoint_base +class ReplicationConnection(connection): autocommit: Any - binary_types: Any - closed: Any - cursor_factory: Callable[..., _cursor] - deferrable: Any - dsn: Any - encoding: Any - info: Any isolation_level: Any - notices: Any - notifies: Any - pgconn_ptr: Any - protocol_version: Any - readonly: Any - server_version: Any - status: Any - string_types: Any + replication_type: Any + reset: Any + set_isolation_level: Any + set_session: Any def __init__(self, *args, **kwargs) -> None: ... - def cancel(self, *args, **kwargs): ... - def close(self, *args, **kwargs): ... - def commit(self, *args, **kwargs): ... + + # https://github.com/python/typeshed/issues/11282 + # The return type should be exactly extras.ReplicationCursor (not _psycopg.ReplicationCursor) + # See the C code: replicationConnection_init(), psyco_conn_cursor() @overload - def cursor(self, name=..., *, scrollable=..., withhold=...) -> _cursor: ... + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> extras_ReplicationCursor: ... @overload - def cursor(self, name=..., cursor_factory: Callable[..., _T_cur] = ..., scrollable=..., withhold=...) -> _T_cur: ... - def fileno(self, *args, **kwargs): ... - def get_backend_pid(self, *args, **kwargs): ... - def get_dsn_parameters(self, *args, **kwargs): ... - def get_native_connection(self, *args, **kwargs): ... - def get_parameter_status(self, parameter): ... - def get_transaction_status(self): ... - def isexecuting(self, *args, **kwargs): ... - def lobject(self, oid=..., mode=..., new_oid=..., new_file=..., lobject_factory=...): ... - def poll(self, *args, **kwargs): ... - def reset(self): ... - def rollback(self): ... - def set_client_encoding(self, encoding): ... - def set_isolation_level(self, level): ... - def set_session(self, *args, **kwargs): ... - def tpc_begin(self, xid): ... - def tpc_commit(self, *args, **kwargs): ... - def tpc_prepare(self): ... - def tpc_recover(self): ... - def tpc_rollback(self, *args, **kwargs): ... - def xid(self, format_id, gtrid, bqual): ... - def __enter__(self): ... - def __exit__(self, type, value, traceback): ... - -class cursor: - arraysize: int - binary_types: Any - closed: Any - connection: Any - description: Any - itersize: Any - lastrowid: Any - name: Any - pgresult_ptr: Any - query: Any - row_factory: Any - rowcount: int - rownumber: int - scrollable: Any - statusmessage: Any - string_types: Any - typecaster: Any - tzinfo_factory: Any - withhold: Any - def __init__(self, *args, **kwargs) -> None: ... - def callproc(self, procname, parameters=...): ... - def cast(self, oid, s): ... - def close(self): ... - def copy_expert(self, sql, file, size=...): ... - def copy_from(self, file, table, sep=..., null=..., size=..., columns=...): ... - def copy_to(self, file, table, sep=..., null=..., columns=...): ... - def execute(self, query, vars=...): ... - def executemany(self, query, vars_list): ... - def fetchall(self) -> list[Tuple[Any, ...]]: ... - def fetchmany(self, size=...) -> list[Tuple[Any, ...]]: ... - def fetchone(self) -> Tuple[Any, ...] | Any: ... - def mogrify(self, *args, **kwargs): ... - def nextset(self): ... - def scroll(self, value, mode=...): ... - def setinputsizes(self, sizes): ... - def setoutputsize(self, size, column=...): ... - def __enter__(self): ... - def __exit__(self, type, value, traceback): ... - def __iter__(self): ... - def __next__(self): ... + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... +@disjoint_base class lobject: closed: Any mode: Any @@ -387,24 +598,43 @@ class lobject: def unlink(self): ... def write(self, str): ... -def Date(year, month, day): ... -def DateFromPy(*args, **kwargs): ... -def DateFromTicks(ticks): ... -def IntervalFromPy(*args, **kwargs): ... -def Time(hour, minutes, seconds, tzinfo=...): ... -def TimeFromPy(*args, **kwargs): ... -def TimeFromTicks(ticks): ... -def Timestamp(year, month, day, hour, minutes, seconds, tzinfo=...): ... -def TimestampFromPy(*args, **kwargs): ... -def TimestampFromTicks(ticks): ... +@type_check_only +class _datetime: + # The class doesn't exist at runtime but functions below return "psycopg2._psycopg.datetime" objects + # XXX: This and other classes that implement the `ISQLQuote` protocol could be made generic + # in the return type of their `adapted` property if someone asks for it. + def __init__(self, obj: object, type: int = -1, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def type(self) -> int: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +def Date(year: int, month: int, day: int, /) -> _datetime: ... +def DateFromPy(date: dt.date, /) -> _datetime: ... +def DateFromTicks(ticks: float, /) -> _datetime: ... +def IntervalFromPy(interval: dt.timedelta, /) -> _datetime: ... +def Time(hour: int, minutes: int, seconds: float, tzinfo: dt.tzinfo | None = None, /) -> _datetime: ... +def TimeFromPy(time: dt.time, /) -> _datetime: ... +def TimeFromTicks(ticks: float, /) -> _datetime: ... +def Timestamp( + year: int, month: int, day: int, hour: int = 0, minutes: int = 0, seconds: float = 0, tzinfo: dt.tzinfo | None = None, / +) -> _datetime: ... +def TimestampFromPy(datetime: dt.datetime, /) -> _datetime: ... +def TimestampFromTicks(ticks: float, /) -> _datetime: ... def _connect(*args, **kwargs): ... -def adapt(*args, **kwargs): ... -def encrypt_password(*args, **kwargs): ... -def get_wait_callback(*args, **kwargs): ... -def libpq_version(*args, **kwargs): ... -def new_array_type(oids, name, baseobj): ... -def new_type(oids, name, castobj): ... -def parse_dsn(*args, **kwargs): ... -def quote_ident(*args, **kwargs): ... -def register_type(*args, **kwargs): ... -def set_wait_callback(_none): ... +def adapt(obj: object, protocol=..., alternate=..., /) -> Any: ... +def encrypt_password( + password: str | bytes, user: str | bytes, scope: connection | cursor | None = None, algorithm: str | None = None +) -> str: ... +def get_wait_callback() -> Incomplete | None: ... +def libpq_version() -> int: ... +def new_array_type(values: tuple[int, ...], name: str, baseobj: _type) -> _type: ... +def new_type( + values: tuple[int, ...], name: str, castobj: Callable[[str | bytes | None, cursor], Any] | None = None, baseobj=None +) -> _type: ... +def parse_dsn(dsn: str | bytes) -> dict[str, Any]: ... +def quote_ident(ident: str | bytes, scope) -> str: ... +def register_type(obj: _type, conn_or_curs: connection | cursor | None = None, /) -> None: ... +def set_wait_callback(none: Callable[..., Incomplete] | None, /) -> None: ... diff --git a/stubs/psycopg2/psycopg2/_range.pyi b/stubs/psycopg2/psycopg2/_range.pyi index fa60fd1bcb1a..254aadd5516e 100644 --- a/stubs/psycopg2/psycopg2/_range.pyi +++ b/stubs/psycopg2/psycopg2/_range.pyi @@ -1,60 +1,86 @@ -from typing import Any +import datetime as dt +from _typeshed import SupportsAllComparisons +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self -class Range: - def __init__(self, lower: Any | None = ..., upper: Any | None = ..., bounds: str = ..., empty: bool = ...) -> None: ... +from psycopg2._psycopg import _type, connection, cursor + +_T_co = TypeVar("_T_co", covariant=True) + +class Range(Generic[_T_co]): + __slots__ = ("_lower", "_upper", "_bounds") + def __init__( + self, lower: _T_co | None = None, upper: _T_co | None = None, bounds: str = "[)", empty: bool = False + ) -> None: ... @property - def lower(self): ... + def lower(self) -> _T_co | None: ... @property - def upper(self): ... + def upper(self) -> _T_co | None: ... @property - def isempty(self): ... + def isempty(self) -> bool: ... @property - def lower_inf(self): ... + def lower_inf(self) -> bool: ... @property - def upper_inf(self): ... + def upper_inf(self) -> bool: ... @property - def lower_inc(self): ... + def lower_inc(self) -> bool: ... @property - def upper_inc(self): ... - def __contains__(self, x): ... - def __bool__(self): ... - def __nonzero__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __hash__(self): ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... - -def register_range(pgrange, pyrange, conn_or_curs, globally: bool = ...): ... + def upper_inc(self) -> bool: ... + def __contains__(self, x: SupportsAllComparisons) -> bool: ... + def __bool__(self) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Range[_T_co]) -> bool: ... + def __le__(self, other: Range[_T_co]) -> bool: ... + def __gt__(self, other: Range[_T_co]) -> bool: ... + def __ge__(self, other: Range[_T_co]) -> bool: ... + +def register_range( + pgrange: str, pyrange: str | type[Range[Any]], conn_or_curs: connection | cursor, globally: bool = False +) -> RangeCaster: ... class RangeAdapter: - name: Any - adapted: Any - def __init__(self, adapted) -> None: ... - def __conform__(self, proto): ... - def prepare(self, conn) -> None: ... - def getquoted(self): ... + name: str | None = None + adapted: Range[Any] + def __init__(self, adapted: Range[Any]) -> None: ... + def __conform__(self, proto) -> Self | None: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... class RangeCaster: - subtype_oid: Any - typecaster: Any - array_typecaster: Any - def __init__(self, pgrange, pyrange, oid, subtype_oid, array_oid: Any | None = ...) -> None: ... - def parse(self, s, cur: Any | None = ...): ... + adapter: type[RangeAdapter] + range: type[Range[Any]] + subtype_oid: int + typecaster: _type + array_typecaster: _type | None + def __init__( + self, + pgrange: str | type[RangeAdapter], + pyrange: str | type[Range[Any]], + oid: int, + subtype_oid: int, + array_oid: int | None = None, + ) -> None: ... -class NumericRange(Range): ... -class DateRange(Range): ... -class DateTimeRange(Range): ... -class DateTimeTZRange(Range): ... + @overload + def parse(self, s: None, cur: cursor | None = None) -> None: ... + @overload + def parse(self, s: str, cur: cursor | None = None) -> Range[Any]: ... + @overload + def parse(self, s: str | None, cur: cursor | None = None) -> Range[Any] | None: ... + +class NumericRange(Range[float]): ... +class DateRange(Range[dt.date]): ... +class DateTimeRange(Range[dt.datetime]): ... +class DateTimeTZRange(Range[dt.datetime]): ... class NumberRangeAdapter(RangeAdapter): - def getquoted(self): ... - -int4range_caster: Any -int8range_caster: Any -numrange_caster: Any -daterange_caster: Any -tsrange_caster: Any -tstzrange_caster: Any + def getquoted(self) -> bytes: ... + +int4range_caster: RangeCaster +int8range_caster: RangeCaster +numrange_caster: RangeCaster +daterange_caster: RangeCaster +tsrange_caster: RangeCaster +tstzrange_caster: RangeCaster diff --git a/stubs/psycopg2/psycopg2/errorcodes.pyi b/stubs/psycopg2/psycopg2/errorcodes.pyi index f4726bd14c07..aecb7fc53f0b 100644 --- a/stubs/psycopg2/psycopg2/errorcodes.pyi +++ b/stubs/psycopg2/psycopg2/errorcodes.pyi @@ -1,304 +1,312 @@ -def lookup(code, _cache=...): ... +from typing import Final -CLASS_SUCCESSFUL_COMPLETION: str -CLASS_WARNING: str -CLASS_NO_DATA: str -CLASS_SQL_STATEMENT_NOT_YET_COMPLETE: str -CLASS_CONNECTION_EXCEPTION: str -CLASS_TRIGGERED_ACTION_EXCEPTION: str -CLASS_FEATURE_NOT_SUPPORTED: str -CLASS_INVALID_TRANSACTION_INITIATION: str -CLASS_LOCATOR_EXCEPTION: str -CLASS_INVALID_GRANTOR: str -CLASS_INVALID_ROLE_SPECIFICATION: str -CLASS_DIAGNOSTICS_EXCEPTION: str -CLASS_CASE_NOT_FOUND: str -CLASS_CARDINALITY_VIOLATION: str -CLASS_DATA_EXCEPTION: str -CLASS_INTEGRITY_CONSTRAINT_VIOLATION: str -CLASS_INVALID_CURSOR_STATE: str -CLASS_INVALID_TRANSACTION_STATE: str -CLASS_INVALID_SQL_STATEMENT_NAME: str -CLASS_TRIGGERED_DATA_CHANGE_VIOLATION: str -CLASS_INVALID_AUTHORIZATION_SPECIFICATION: str -CLASS_DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST: str -CLASS_INVALID_TRANSACTION_TERMINATION: str -CLASS_SQL_ROUTINE_EXCEPTION: str -CLASS_INVALID_CURSOR_NAME: str -CLASS_EXTERNAL_ROUTINE_EXCEPTION: str -CLASS_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION: str -CLASS_SAVEPOINT_EXCEPTION: str -CLASS_INVALID_CATALOG_NAME: str -CLASS_INVALID_SCHEMA_NAME: str -CLASS_TRANSACTION_ROLLBACK: str -CLASS_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION: str -CLASS_WITH_CHECK_OPTION_VIOLATION: str -CLASS_INSUFFICIENT_RESOURCES: str -CLASS_PROGRAM_LIMIT_EXCEEDED: str -CLASS_OBJECT_NOT_IN_PREREQUISITE_STATE: str -CLASS_OPERATOR_INTERVENTION: str -CLASS_SYSTEM_ERROR: str -CLASS_SNAPSHOT_FAILURE: str -CLASS_CONFIGURATION_FILE_ERROR: str -CLASS_FOREIGN_DATA_WRAPPER_ERROR: str -CLASS_PL_PGSQL_ERROR: str -CLASS_INTERNAL_ERROR: str -SUCCESSFUL_COMPLETION: str -WARNING: str -NULL_VALUE_ELIMINATED_IN_SET_FUNCTION: str -STRING_DATA_RIGHT_TRUNCATION_: str -PRIVILEGE_NOT_REVOKED: str -PRIVILEGE_NOT_GRANTED: str -IMPLICIT_ZERO_BIT_PADDING: str -DYNAMIC_RESULT_SETS_RETURNED: str -DEPRECATED_FEATURE: str -NO_DATA: str -NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED: str -SQL_STATEMENT_NOT_YET_COMPLETE: str -CONNECTION_EXCEPTION: str -SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION: str -CONNECTION_DOES_NOT_EXIST: str -SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION: str -CONNECTION_FAILURE: str -TRANSACTION_RESOLUTION_UNKNOWN: str -PROTOCOL_VIOLATION: str -TRIGGERED_ACTION_EXCEPTION: str -FEATURE_NOT_SUPPORTED: str -INVALID_TRANSACTION_INITIATION: str -LOCATOR_EXCEPTION: str -INVALID_LOCATOR_SPECIFICATION: str -INVALID_GRANTOR: str -INVALID_GRANT_OPERATION: str -INVALID_ROLE_SPECIFICATION: str -DIAGNOSTICS_EXCEPTION: str -STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER: str -CASE_NOT_FOUND: str -CARDINALITY_VIOLATION: str -DATA_EXCEPTION: str -STRING_DATA_RIGHT_TRUNCATION: str -NULL_VALUE_NO_INDICATOR_PARAMETER: str -NUMERIC_VALUE_OUT_OF_RANGE: str -NULL_VALUE_NOT_ALLOWED_: str -ERROR_IN_ASSIGNMENT: str -INVALID_DATETIME_FORMAT: str -DATETIME_FIELD_OVERFLOW: str -INVALID_TIME_ZONE_DISPLACEMENT_VALUE: str -ESCAPE_CHARACTER_CONFLICT: str -INVALID_USE_OF_ESCAPE_CHARACTER: str -INVALID_ESCAPE_OCTET: str -ZERO_LENGTH_CHARACTER_STRING: str -MOST_SPECIFIC_TYPE_MISMATCH: str -SEQUENCE_GENERATOR_LIMIT_EXCEEDED: str -NOT_AN_XML_DOCUMENT: str -INVALID_XML_DOCUMENT: str -INVALID_XML_CONTENT: str -INVALID_XML_COMMENT: str -INVALID_XML_PROCESSING_INSTRUCTION: str -INVALID_INDICATOR_PARAMETER_VALUE: str -SUBSTRING_ERROR: str -DIVISION_BY_ZERO: str -INVALID_PRECEDING_OR_FOLLOWING_SIZE: str -INVALID_ARGUMENT_FOR_NTILE_FUNCTION: str -INTERVAL_FIELD_OVERFLOW: str -INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION: str -INVALID_CHARACTER_VALUE_FOR_CAST: str -INVALID_ESCAPE_CHARACTER: str -INVALID_REGULAR_EXPRESSION: str -INVALID_ARGUMENT_FOR_LOGARITHM: str -INVALID_ARGUMENT_FOR_POWER_FUNCTION: str -INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION: str -INVALID_ROW_COUNT_IN_LIMIT_CLAUSE: str -INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE: str -INVALID_LIMIT_VALUE: str -CHARACTER_NOT_IN_REPERTOIRE: str -INDICATOR_OVERFLOW: str -INVALID_PARAMETER_VALUE: str -UNTERMINATED_C_STRING: str -INVALID_ESCAPE_SEQUENCE: str -STRING_DATA_LENGTH_MISMATCH: str -TRIM_ERROR: str -ARRAY_SUBSCRIPT_ERROR: str -INVALID_TABLESAMPLE_REPEAT: str -INVALID_TABLESAMPLE_ARGUMENT: str -DUPLICATE_JSON_OBJECT_KEY_VALUE: str -INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION: str -INVALID_JSON_TEXT: str -INVALID_SQL_JSON_SUBSCRIPT: str -MORE_THAN_ONE_SQL_JSON_ITEM: str -NO_SQL_JSON_ITEM: str -NON_NUMERIC_SQL_JSON_ITEM: str -NON_UNIQUE_KEYS_IN_A_JSON_OBJECT: str -SINGLETON_SQL_JSON_ITEM_REQUIRED: str -SQL_JSON_ARRAY_NOT_FOUND: str -SQL_JSON_MEMBER_NOT_FOUND: str -SQL_JSON_NUMBER_NOT_FOUND: str -SQL_JSON_OBJECT_NOT_FOUND: str -TOO_MANY_JSON_ARRAY_ELEMENTS: str -TOO_MANY_JSON_OBJECT_MEMBERS: str -SQL_JSON_SCALAR_REQUIRED: str -FLOATING_POINT_EXCEPTION: str -INVALID_TEXT_REPRESENTATION: str -INVALID_BINARY_REPRESENTATION: str -BAD_COPY_FILE_FORMAT: str -UNTRANSLATABLE_CHARACTER: str -NONSTANDARD_USE_OF_ESCAPE_CHARACTER: str -INTEGRITY_CONSTRAINT_VIOLATION: str -RESTRICT_VIOLATION: str -NOT_NULL_VIOLATION: str -FOREIGN_KEY_VIOLATION: str -UNIQUE_VIOLATION: str -CHECK_VIOLATION: str -EXCLUSION_VIOLATION: str -INVALID_CURSOR_STATE: str -INVALID_TRANSACTION_STATE: str -ACTIVE_SQL_TRANSACTION: str -BRANCH_TRANSACTION_ALREADY_ACTIVE: str -INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION: str -INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION: str -NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION: str -READ_ONLY_SQL_TRANSACTION: str -SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED: str -HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL: str -NO_ACTIVE_SQL_TRANSACTION: str -IN_FAILED_SQL_TRANSACTION: str -IDLE_IN_TRANSACTION_SESSION_TIMEOUT: str -INVALID_SQL_STATEMENT_NAME: str -TRIGGERED_DATA_CHANGE_VIOLATION: str -INVALID_AUTHORIZATION_SPECIFICATION: str -INVALID_PASSWORD: str -DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST: str -DEPENDENT_OBJECTS_STILL_EXIST: str -INVALID_TRANSACTION_TERMINATION: str -SQL_ROUTINE_EXCEPTION: str -MODIFYING_SQL_DATA_NOT_PERMITTED_: str -PROHIBITED_SQL_STATEMENT_ATTEMPTED_: str -READING_SQL_DATA_NOT_PERMITTED_: str -FUNCTION_EXECUTED_NO_RETURN_STATEMENT: str -INVALID_CURSOR_NAME: str -EXTERNAL_ROUTINE_EXCEPTION: str -CONTAINING_SQL_NOT_PERMITTED: str -MODIFYING_SQL_DATA_NOT_PERMITTED: str -PROHIBITED_SQL_STATEMENT_ATTEMPTED: str -READING_SQL_DATA_NOT_PERMITTED: str -EXTERNAL_ROUTINE_INVOCATION_EXCEPTION: str -INVALID_SQLSTATE_RETURNED: str -NULL_VALUE_NOT_ALLOWED: str -TRIGGER_PROTOCOL_VIOLATED: str -SRF_PROTOCOL_VIOLATED: str -EVENT_TRIGGER_PROTOCOL_VIOLATED: str -SAVEPOINT_EXCEPTION: str -INVALID_SAVEPOINT_SPECIFICATION: str -INVALID_CATALOG_NAME: str -INVALID_SCHEMA_NAME: str -TRANSACTION_ROLLBACK: str -SERIALIZATION_FAILURE: str -TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION: str -STATEMENT_COMPLETION_UNKNOWN: str -DEADLOCK_DETECTED: str -SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION: str -INSUFFICIENT_PRIVILEGE: str -SYNTAX_ERROR: str -INVALID_NAME: str -INVALID_COLUMN_DEFINITION: str -NAME_TOO_LONG: str -DUPLICATE_COLUMN: str -AMBIGUOUS_COLUMN: str -UNDEFINED_COLUMN: str -UNDEFINED_OBJECT: str -DUPLICATE_OBJECT: str -DUPLICATE_ALIAS: str -DUPLICATE_FUNCTION: str -AMBIGUOUS_FUNCTION: str -GROUPING_ERROR: str -DATATYPE_MISMATCH: str -WRONG_OBJECT_TYPE: str -INVALID_FOREIGN_KEY: str -CANNOT_COERCE: str -UNDEFINED_FUNCTION: str -GENERATED_ALWAYS: str -RESERVED_NAME: str -UNDEFINED_TABLE: str -UNDEFINED_PARAMETER: str -DUPLICATE_CURSOR: str -DUPLICATE_DATABASE: str -DUPLICATE_PREPARED_STATEMENT: str -DUPLICATE_SCHEMA: str -DUPLICATE_TABLE: str -AMBIGUOUS_PARAMETER: str -AMBIGUOUS_ALIAS: str -INVALID_COLUMN_REFERENCE: str -INVALID_CURSOR_DEFINITION: str -INVALID_DATABASE_DEFINITION: str -INVALID_FUNCTION_DEFINITION: str -INVALID_PREPARED_STATEMENT_DEFINITION: str -INVALID_SCHEMA_DEFINITION: str -INVALID_TABLE_DEFINITION: str -INVALID_OBJECT_DEFINITION: str -INDETERMINATE_DATATYPE: str -INVALID_RECURSION: str -WINDOWING_ERROR: str -COLLATION_MISMATCH: str -INDETERMINATE_COLLATION: str -WITH_CHECK_OPTION_VIOLATION: str -INSUFFICIENT_RESOURCES: str -DISK_FULL: str -OUT_OF_MEMORY: str -TOO_MANY_CONNECTIONS: str -CONFIGURATION_LIMIT_EXCEEDED: str -PROGRAM_LIMIT_EXCEEDED: str -STATEMENT_TOO_COMPLEX: str -TOO_MANY_COLUMNS: str -TOO_MANY_ARGUMENTS: str -OBJECT_NOT_IN_PREREQUISITE_STATE: str -OBJECT_IN_USE: str -CANT_CHANGE_RUNTIME_PARAM: str -LOCK_NOT_AVAILABLE: str -UNSAFE_NEW_ENUM_VALUE_USAGE: str -OPERATOR_INTERVENTION: str -QUERY_CANCELED: str -ADMIN_SHUTDOWN: str -CRASH_SHUTDOWN: str -CANNOT_CONNECT_NOW: str -DATABASE_DROPPED: str -SYSTEM_ERROR: str -IO_ERROR: str -UNDEFINED_FILE: str -DUPLICATE_FILE: str -SNAPSHOT_TOO_OLD: str -CONFIG_FILE_ERROR: str -LOCK_FILE_EXISTS: str -FDW_ERROR: str -FDW_OUT_OF_MEMORY: str -FDW_DYNAMIC_PARAMETER_VALUE_NEEDED: str -FDW_INVALID_DATA_TYPE: str -FDW_COLUMN_NAME_NOT_FOUND: str -FDW_INVALID_DATA_TYPE_DESCRIPTORS: str -FDW_INVALID_COLUMN_NAME: str -FDW_INVALID_COLUMN_NUMBER: str -FDW_INVALID_USE_OF_NULL_POINTER: str -FDW_INVALID_STRING_FORMAT: str -FDW_INVALID_HANDLE: str -FDW_INVALID_OPTION_INDEX: str -FDW_INVALID_OPTION_NAME: str -FDW_OPTION_NAME_NOT_FOUND: str -FDW_REPLY_HANDLE: str -FDW_UNABLE_TO_CREATE_EXECUTION: str -FDW_UNABLE_TO_CREATE_REPLY: str -FDW_UNABLE_TO_ESTABLISH_CONNECTION: str -FDW_NO_SCHEMAS: str -FDW_SCHEMA_NOT_FOUND: str -FDW_TABLE_NOT_FOUND: str -FDW_FUNCTION_SEQUENCE_ERROR: str -FDW_TOO_MANY_HANDLES: str -FDW_INCONSISTENT_DESCRIPTOR_INFORMATION: str -FDW_INVALID_ATTRIBUTE_VALUE: str -FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH: str -FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER: str -PLPGSQL_ERROR: str -RAISE_EXCEPTION: str -NO_DATA_FOUND: str -TOO_MANY_ROWS: str -ASSERT_FAILURE: str -INTERNAL_ERROR: str -DATA_CORRUPTED: str -INDEX_CORRUPTED: str +def lookup(code: str, _cache: dict[str, str] = {}) -> str: ... + +CLASS_SUCCESSFUL_COMPLETION: Final[str] +CLASS_WARNING: Final[str] +CLASS_NO_DATA: Final[str] +CLASS_SQL_STATEMENT_NOT_YET_COMPLETE: Final[str] +CLASS_CONNECTION_EXCEPTION: Final[str] +CLASS_TRIGGERED_ACTION_EXCEPTION: Final[str] +CLASS_FEATURE_NOT_SUPPORTED: Final[str] +CLASS_INVALID_TRANSACTION_INITIATION: Final[str] +CLASS_LOCATOR_EXCEPTION: Final[str] +CLASS_INVALID_GRANTOR: Final[str] +CLASS_INVALID_ROLE_SPECIFICATION: Final[str] +CLASS_DIAGNOSTICS_EXCEPTION: Final[str] +CLASS_XQUERY_ERROR: Final[str] +CLASS_CASE_NOT_FOUND: Final[str] +CLASS_CARDINALITY_VIOLATION: Final[str] +CLASS_DATA_EXCEPTION: Final[str] +CLASS_INTEGRITY_CONSTRAINT_VIOLATION: Final[str] +CLASS_INVALID_CURSOR_STATE: Final[str] +CLASS_INVALID_TRANSACTION_STATE: Final[str] +CLASS_INVALID_SQL_STATEMENT_NAME: Final[str] +CLASS_TRIGGERED_DATA_CHANGE_VIOLATION: Final[str] +CLASS_INVALID_AUTHORIZATION_SPECIFICATION: Final[str] +CLASS_DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST: Final[str] +CLASS_INVALID_TRANSACTION_TERMINATION: Final[str] +CLASS_SQL_ROUTINE_EXCEPTION: Final[str] +CLASS_INVALID_CURSOR_NAME: Final[str] +CLASS_EXTERNAL_ROUTINE_EXCEPTION: Final[str] +CLASS_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION: Final[str] +CLASS_SAVEPOINT_EXCEPTION: Final[str] +CLASS_INVALID_CATALOG_NAME: Final[str] +CLASS_INVALID_SCHEMA_NAME: Final[str] +CLASS_TRANSACTION_ROLLBACK: Final[str] +CLASS_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION: Final[str] +CLASS_WITH_CHECK_OPTION_VIOLATION: Final[str] +CLASS_INSUFFICIENT_RESOURCES: Final[str] +CLASS_PROGRAM_LIMIT_EXCEEDED: Final[str] +CLASS_OBJECT_NOT_IN_PREREQUISITE_STATE: Final[str] +CLASS_OPERATOR_INTERVENTION: Final[str] +CLASS_SYSTEM_ERROR: Final[str] +CLASS_SNAPSHOT_FAILURE: Final[str] +CLASS_CONFIGURATION_FILE_ERROR: Final[str] +CLASS_FOREIGN_DATA_WRAPPER_ERROR: Final[str] +CLASS_PL_PGSQL_ERROR: Final[str] +CLASS_INTERNAL_ERROR: Final[str] +SUCCESSFUL_COMPLETION: Final[str] +WARNING: Final[str] +NULL_VALUE_ELIMINATED_IN_SET_FUNCTION: Final[str] +STRING_DATA_RIGHT_TRUNCATION_: Final[str] +PRIVILEGE_NOT_REVOKED: Final[str] +PRIVILEGE_NOT_GRANTED: Final[str] +IMPLICIT_ZERO_BIT_PADDING: Final[str] +DYNAMIC_RESULT_SETS_RETURNED: Final[str] +DEPRECATED_FEATURE: Final[str] +NO_DATA: Final[str] +NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED: Final[str] +SQL_STATEMENT_NOT_YET_COMPLETE: Final[str] +CONNECTION_EXCEPTION: Final[str] +SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION: Final[str] +CONNECTION_DOES_NOT_EXIST: Final[str] +SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION: Final[str] +CONNECTION_FAILURE: Final[str] +TRANSACTION_RESOLUTION_UNKNOWN: Final[str] +PROTOCOL_VIOLATION: Final[str] +TRIGGERED_ACTION_EXCEPTION: Final[str] +FEATURE_NOT_SUPPORTED: Final[str] +INVALID_TRANSACTION_INITIATION: Final[str] +LOCATOR_EXCEPTION: Final[str] +INVALID_LOCATOR_SPECIFICATION: Final[str] +INVALID_GRANTOR: Final[str] +INVALID_GRANT_OPERATION: Final[str] +INVALID_ROLE_SPECIFICATION: Final[str] +DIAGNOSTICS_EXCEPTION: Final[str] +STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER: Final[str] +INVALID_ARGUMENT_FOR_XQUERY: Final[str] +CASE_NOT_FOUND: Final[str] +CARDINALITY_VIOLATION: Final[str] +DATA_EXCEPTION: Final[str] +STRING_DATA_RIGHT_TRUNCATION: Final[str] +NULL_VALUE_NO_INDICATOR_PARAMETER: Final[str] +NUMERIC_VALUE_OUT_OF_RANGE: Final[str] +NULL_VALUE_NOT_ALLOWED_: Final[str] +ERROR_IN_ASSIGNMENT: Final[str] +INVALID_DATETIME_FORMAT: Final[str] +DATETIME_FIELD_OVERFLOW: Final[str] +INVALID_TIME_ZONE_DISPLACEMENT_VALUE: Final[str] +ESCAPE_CHARACTER_CONFLICT: Final[str] +INVALID_USE_OF_ESCAPE_CHARACTER: Final[str] +INVALID_ESCAPE_OCTET: Final[str] +ZERO_LENGTH_CHARACTER_STRING: Final[str] +MOST_SPECIFIC_TYPE_MISMATCH: Final[str] +SEQUENCE_GENERATOR_LIMIT_EXCEEDED: Final[str] +NOT_AN_XML_DOCUMENT: Final[str] +INVALID_XML_DOCUMENT: Final[str] +INVALID_XML_CONTENT: Final[str] +INVALID_XML_COMMENT: Final[str] +INVALID_XML_PROCESSING_INSTRUCTION: Final[str] +INVALID_INDICATOR_PARAMETER_VALUE: Final[str] +SUBSTRING_ERROR: Final[str] +DIVISION_BY_ZERO: Final[str] +INVALID_PRECEDING_OR_FOLLOWING_SIZE: Final[str] +INVALID_ARGUMENT_FOR_NTILE_FUNCTION: Final[str] +INTERVAL_FIELD_OVERFLOW: Final[str] +INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION: Final[str] +INVALID_CHARACTER_VALUE_FOR_CAST: Final[str] +INVALID_ESCAPE_CHARACTER: Final[str] +INVALID_REGULAR_EXPRESSION: Final[str] +INVALID_ARGUMENT_FOR_LOGARITHM: Final[str] +INVALID_ARGUMENT_FOR_POWER_FUNCTION: Final[str] +INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION: Final[str] +INVALID_ROW_COUNT_IN_LIMIT_CLAUSE: Final[str] +INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE: Final[str] +INVALID_LIMIT_VALUE: Final[str] +CHARACTER_NOT_IN_REPERTOIRE: Final[str] +INDICATOR_OVERFLOW: Final[str] +INVALID_PARAMETER_VALUE: Final[str] +UNTERMINATED_C_STRING: Final[str] +INVALID_ESCAPE_SEQUENCE: Final[str] +STRING_DATA_LENGTH_MISMATCH: Final[str] +TRIM_ERROR: Final[str] +ARRAY_SUBSCRIPT_ERROR: Final[str] +INVALID_TABLESAMPLE_REPEAT: Final[str] +INVALID_TABLESAMPLE_ARGUMENT: Final[str] +DUPLICATE_JSON_OBJECT_KEY_VALUE: Final[str] +INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION: Final[str] +INVALID_JSON_TEXT: Final[str] +INVALID_SQL_JSON_SUBSCRIPT: Final[str] +MORE_THAN_ONE_SQL_JSON_ITEM: Final[str] +NO_SQL_JSON_ITEM: Final[str] +NON_NUMERIC_SQL_JSON_ITEM: Final[str] +NON_UNIQUE_KEYS_IN_A_JSON_OBJECT: Final[str] +SINGLETON_SQL_JSON_ITEM_REQUIRED: Final[str] +SQL_JSON_ARRAY_NOT_FOUND: Final[str] +SQL_JSON_MEMBER_NOT_FOUND: Final[str] +SQL_JSON_NUMBER_NOT_FOUND: Final[str] +SQL_JSON_OBJECT_NOT_FOUND: Final[str] +TOO_MANY_JSON_ARRAY_ELEMENTS: Final[str] +TOO_MANY_JSON_OBJECT_MEMBERS: Final[str] +SQL_JSON_SCALAR_REQUIRED: Final[str] +FLOATING_POINT_EXCEPTION: Final[str] +INVALID_TEXT_REPRESENTATION: Final[str] +INVALID_BINARY_REPRESENTATION: Final[str] +BAD_COPY_FILE_FORMAT: Final[str] +UNTRANSLATABLE_CHARACTER: Final[str] +NONSTANDARD_USE_OF_ESCAPE_CHARACTER: Final[str] +INTEGRITY_CONSTRAINT_VIOLATION: Final[str] +RESTRICT_VIOLATION: Final[str] +NOT_NULL_VIOLATION: Final[str] +FOREIGN_KEY_VIOLATION: Final[str] +UNIQUE_VIOLATION: Final[str] +CHECK_VIOLATION: Final[str] +EXCLUSION_VIOLATION: Final[str] +INVALID_CURSOR_STATE: Final[str] +INVALID_TRANSACTION_STATE: Final[str] +ACTIVE_SQL_TRANSACTION: Final[str] +BRANCH_TRANSACTION_ALREADY_ACTIVE: Final[str] +INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION: Final[str] +INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION: Final[str] +NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION: Final[str] +READ_ONLY_SQL_TRANSACTION: Final[str] +SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED: Final[str] +HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL: Final[str] +NO_ACTIVE_SQL_TRANSACTION: Final[str] +IN_FAILED_SQL_TRANSACTION: Final[str] +IDLE_IN_TRANSACTION_SESSION_TIMEOUT: Final[str] +INVALID_SQL_STATEMENT_NAME: Final[str] +TRIGGERED_DATA_CHANGE_VIOLATION: Final[str] +INVALID_AUTHORIZATION_SPECIFICATION: Final[str] +INVALID_PASSWORD: Final[str] +DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST: Final[str] +DEPENDENT_OBJECTS_STILL_EXIST: Final[str] +INVALID_TRANSACTION_TERMINATION: Final[str] +SQL_ROUTINE_EXCEPTION: Final[str] +MODIFYING_SQL_DATA_NOT_PERMITTED_: Final[str] +PROHIBITED_SQL_STATEMENT_ATTEMPTED_: Final[str] +READING_SQL_DATA_NOT_PERMITTED_: Final[str] +FUNCTION_EXECUTED_NO_RETURN_STATEMENT: Final[str] +INVALID_CURSOR_NAME: Final[str] +EXTERNAL_ROUTINE_EXCEPTION: Final[str] +CONTAINING_SQL_NOT_PERMITTED: Final[str] +MODIFYING_SQL_DATA_NOT_PERMITTED: Final[str] +PROHIBITED_SQL_STATEMENT_ATTEMPTED: Final[str] +READING_SQL_DATA_NOT_PERMITTED: Final[str] +EXTERNAL_ROUTINE_INVOCATION_EXCEPTION: Final[str] +INVALID_SQLSTATE_RETURNED: Final[str] +NULL_VALUE_NOT_ALLOWED: Final[str] +TRIGGER_PROTOCOL_VIOLATED: Final[str] +SRF_PROTOCOL_VIOLATED: Final[str] +EVENT_TRIGGER_PROTOCOL_VIOLATED: Final[str] +SAVEPOINT_EXCEPTION: Final[str] +INVALID_SAVEPOINT_SPECIFICATION: Final[str] +INVALID_CATALOG_NAME: Final[str] +INVALID_SCHEMA_NAME: Final[str] +TRANSACTION_ROLLBACK: Final[str] +SERIALIZATION_FAILURE: Final[str] +TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION: Final[str] +STATEMENT_COMPLETION_UNKNOWN: Final[str] +DEADLOCK_DETECTED: Final[str] +SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION: Final[str] +INSUFFICIENT_PRIVILEGE: Final[str] +SYNTAX_ERROR: Final[str] +INVALID_NAME: Final[str] +INVALID_COLUMN_DEFINITION: Final[str] +NAME_TOO_LONG: Final[str] +DUPLICATE_COLUMN: Final[str] +AMBIGUOUS_COLUMN: Final[str] +UNDEFINED_COLUMN: Final[str] +UNDEFINED_OBJECT: Final[str] +DUPLICATE_OBJECT: Final[str] +DUPLICATE_ALIAS: Final[str] +DUPLICATE_FUNCTION: Final[str] +AMBIGUOUS_FUNCTION: Final[str] +GROUPING_ERROR: Final[str] +DATATYPE_MISMATCH: Final[str] +WRONG_OBJECT_TYPE: Final[str] +INVALID_FOREIGN_KEY: Final[str] +CANNOT_COERCE: Final[str] +UNDEFINED_FUNCTION: Final[str] +GENERATED_ALWAYS: Final[str] +RESERVED_NAME: Final[str] +UNDEFINED_TABLE: Final[str] +UNDEFINED_PARAMETER: Final[str] +DUPLICATE_CURSOR: Final[str] +DUPLICATE_DATABASE: Final[str] +DUPLICATE_PREPARED_STATEMENT: Final[str] +DUPLICATE_SCHEMA: Final[str] +DUPLICATE_TABLE: Final[str] +AMBIGUOUS_PARAMETER: Final[str] +AMBIGUOUS_ALIAS: Final[str] +INVALID_COLUMN_REFERENCE: Final[str] +INVALID_CURSOR_DEFINITION: Final[str] +INVALID_DATABASE_DEFINITION: Final[str] +INVALID_FUNCTION_DEFINITION: Final[str] +INVALID_PREPARED_STATEMENT_DEFINITION: Final[str] +INVALID_SCHEMA_DEFINITION: Final[str] +INVALID_TABLE_DEFINITION: Final[str] +INVALID_OBJECT_DEFINITION: Final[str] +INDETERMINATE_DATATYPE: Final[str] +INVALID_RECURSION: Final[str] +WINDOWING_ERROR: Final[str] +COLLATION_MISMATCH: Final[str] +INDETERMINATE_COLLATION: Final[str] +WITH_CHECK_OPTION_VIOLATION: Final[str] +INSUFFICIENT_RESOURCES: Final[str] +DISK_FULL: Final[str] +OUT_OF_MEMORY: Final[str] +TOO_MANY_CONNECTIONS: Final[str] +CONFIGURATION_LIMIT_EXCEEDED: Final[str] +PROGRAM_LIMIT_EXCEEDED: Final[str] +STATEMENT_TOO_COMPLEX: Final[str] +TOO_MANY_COLUMNS: Final[str] +TOO_MANY_ARGUMENTS: Final[str] +OBJECT_NOT_IN_PREREQUISITE_STATE: Final[str] +OBJECT_IN_USE: Final[str] +CANT_CHANGE_RUNTIME_PARAM: Final[str] +LOCK_NOT_AVAILABLE: Final[str] +UNSAFE_NEW_ENUM_VALUE_USAGE: Final[str] +OPERATOR_INTERVENTION: Final[str] +QUERY_CANCELED: Final[str] +ADMIN_SHUTDOWN: Final[str] +CRASH_SHUTDOWN: Final[str] +CANNOT_CONNECT_NOW: Final[str] +DATABASE_DROPPED: Final[str] +SYSTEM_ERROR: Final[str] +IO_ERROR: Final[str] +UNDEFINED_FILE: Final[str] +DUPLICATE_FILE: Final[str] +FILE_NAME_TOO_LONG: Final[str] +SNAPSHOT_TOO_OLD: Final[str] +CONFIG_FILE_ERROR: Final[str] +LOCK_FILE_EXISTS: Final[str] +FDW_ERROR: Final[str] +FDW_OUT_OF_MEMORY: Final[str] +FDW_DYNAMIC_PARAMETER_VALUE_NEEDED: Final[str] +FDW_INVALID_DATA_TYPE: Final[str] +FDW_COLUMN_NAME_NOT_FOUND: Final[str] +FDW_INVALID_DATA_TYPE_DESCRIPTORS: Final[str] +FDW_INVALID_COLUMN_NAME: Final[str] +FDW_INVALID_COLUMN_NUMBER: Final[str] +FDW_INVALID_USE_OF_NULL_POINTER: Final[str] +FDW_INVALID_STRING_FORMAT: Final[str] +FDW_INVALID_HANDLE: Final[str] +FDW_INVALID_OPTION_INDEX: Final[str] +FDW_INVALID_OPTION_NAME: Final[str] +FDW_OPTION_NAME_NOT_FOUND: Final[str] +FDW_REPLY_HANDLE: Final[str] +FDW_UNABLE_TO_CREATE_EXECUTION: Final[str] +FDW_UNABLE_TO_CREATE_REPLY: Final[str] +FDW_UNABLE_TO_ESTABLISH_CONNECTION: Final[str] +FDW_NO_SCHEMAS: Final[str] +FDW_SCHEMA_NOT_FOUND: Final[str] +FDW_TABLE_NOT_FOUND: Final[str] +FDW_FUNCTION_SEQUENCE_ERROR: Final[str] +FDW_TOO_MANY_HANDLES: Final[str] +FDW_INCONSISTENT_DESCRIPTOR_INFORMATION: Final[str] +FDW_INVALID_ATTRIBUTE_VALUE: Final[str] +FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH: Final[str] +FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER: Final[str] +PLPGSQL_ERROR: Final[str] +RAISE_EXCEPTION: Final[str] +NO_DATA_FOUND: Final[str] +TOO_MANY_ROWS: Final[str] +ASSERT_FAILURE: Final[str] +INTERNAL_ERROR: Final[str] +DATA_CORRUPTED: Final[str] +INDEX_CORRUPTED: Final[str] +IDLE_SESSION_TIMEOUT: Final[str] +SQL_JSON_ITEM_CANNOT_BE_CAST_TO_TARGET_TYPE: Final[str] +TRANSACTION_TIMEOUT: Final[str] diff --git a/stubs/psycopg2/psycopg2/errors.pyi b/stubs/psycopg2/psycopg2/errors.pyi index bf7d357959bd..fed1290832de 100644 --- a/stubs/psycopg2/psycopg2/errors.pyi +++ b/stubs/psycopg2/psycopg2/errors.pyi @@ -1,11 +1,19 @@ -from psycopg2._psycopg import Error as Error, Warning as Warning +from psycopg2._psycopg import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + QueryCanceledError as QueryCanceledError, + TransactionRollbackError as TransactionRollbackError, + Warning as Warning, +) -class DatabaseError(Error): ... -class InterfaceError(Error): ... -class DataError(DatabaseError): ... class DiagnosticsException(DatabaseError): ... -class IntegrityError(DatabaseError): ... -class InternalError(DatabaseError): ... class InvalidGrantOperation(DatabaseError): ... class InvalidGrantor(DatabaseError): ... class InvalidLocatorSpecification(DatabaseError): ... @@ -14,12 +22,10 @@ class InvalidTransactionInitiation(DatabaseError): ... class LocatorException(DatabaseError): ... class NoAdditionalDynamicResultSetsReturned(DatabaseError): ... class NoData(DatabaseError): ... -class NotSupportedError(DatabaseError): ... -class OperationalError(DatabaseError): ... -class ProgrammingError(DatabaseError): ... class SnapshotTooOld(DatabaseError): ... class SqlStatementNotYetComplete(DatabaseError): ... class StackedDiagnosticsAccessedWithoutActiveHandler(DatabaseError): ... +class InvalidArgumentForXquery(DatabaseError): ... class TriggeredActionException(DatabaseError): ... class ActiveSqlTransaction(InternalError): ... class AdminShutdown(OperationalError): ... @@ -60,6 +66,7 @@ class DuplicateColumn(ProgrammingError): ... class DuplicateCursor(ProgrammingError): ... class DuplicateDatabase(ProgrammingError): ... class DuplicateFile(OperationalError): ... +class FileNameTooLong(OperationalError): ... class DuplicateFunction(ProgrammingError): ... class DuplicateJsonObjectKeyValue(DataError): ... class DuplicateObject(ProgrammingError): ... @@ -201,7 +208,6 @@ class ProgramLimitExceeded(OperationalError): ... class ProhibitedSqlStatementAttempted(InternalError): ... class ProhibitedSqlStatementAttemptedExt(InternalError): ... class ProtocolViolation(OperationalError): ... -class QueryCanceledError(OperationalError): ... class RaiseException(InternalError): ... class ReadOnlySqlTransaction(InternalError): ... class ReadingSqlDataNotPermitted(InternalError): ... @@ -235,7 +241,7 @@ class TooManyJsonArrayElements(DataError): ... class TooManyJsonObjectMembers(DataError): ... class TooManyRows(InternalError): ... class TransactionResolutionUnknown(OperationalError): ... -class TransactionRollbackError(OperationalError): ... +class TransactionTimeout(InternalError): ... class TriggerProtocolViolated(InternalError): ... class TriggeredDataChangeViolation(OperationalError): ... class TrimError(DataError): ... @@ -259,5 +265,7 @@ class SerializationFailure(TransactionRollbackError): ... class StatementCompletionUnknown(TransactionRollbackError): ... class TransactionIntegrityConstraintViolation(TransactionRollbackError): ... class TransactionRollback(TransactionRollbackError): ... +class IdleSessionTimeout(OperationalError): ... +class SqlJsonItemCannotBeCastToTargetType(DataError): ... -def lookup(code): ... +def lookup(code: str) -> type[Error]: ... diff --git a/stubs/psycopg2/psycopg2/extensions.pyi b/stubs/psycopg2/psycopg2/extensions.pyi index 634f07d27d20..77e12076674f 100644 --- a/stubs/psycopg2/psycopg2/extensions.pyi +++ b/stubs/psycopg2/psycopg2/extensions.pyi @@ -1,4 +1,6 @@ -from typing import Any +from _typeshed import Unused +from collections.abc import Callable, Iterable +from typing import Any, TypeVar, overload from psycopg2._psycopg import ( BINARYARRAY as BINARYARRAY, @@ -53,6 +55,8 @@ from psycopg2._psycopg import ( TimestampFromPy as TimestampFromPy, TransactionRollbackError as TransactionRollbackError, Xid as Xid, + _ISQLQuoteProto, + _type, adapt as adapt, adapters as adapters, binary_types as binary_types, @@ -95,20 +99,27 @@ TRANSACTION_STATUS_INTRANS: int TRANSACTION_STATUS_INERROR: int TRANSACTION_STATUS_UNKNOWN: int -def register_adapter(typ, callable) -> None: ... +_T = TypeVar("_T") + +def register_adapter(typ: type[_T], callable: Callable[[_T], _ISQLQuoteProto]) -> None: ... class SQL_IN: - def __init__(self, seq) -> None: ... - def prepare(self, conn) -> None: ... - def getquoted(self): ... + def __init__(self, seq: Iterable[object]) -> None: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... class NoneAdapter: - def __init__(self, obj) -> None: ... - def getquoted(self, _null: bytes = ...): ... + def __init__(self, obj: Unused) -> None: ... + def getquoted(self, _null: bytes = b"NULL") -> bytes: ... -def make_dsn(dsn: Any | None = ..., **kwargs): ... +@overload +def make_dsn(dsn: bytes) -> bytes: ... # type: ignore[overload-overlap] +@overload +def make_dsn(dsn: None = None) -> str: ... +@overload +def make_dsn(dsn: str | bytes | None = None, **kwargs: Any) -> str: ... -JSON: Any -JSONARRAY: Any -JSONB: Any -JSONBARRAY: Any +JSON: _type +JSONARRAY: _type | None +JSONB: _type +JSONBARRAY: _type | None diff --git a/stubs/psycopg2/psycopg2/extras.pyi b/stubs/psycopg2/psycopg2/extras.pyi index 364de1a2f85a..1820c9c0f055 100644 --- a/stubs/psycopg2/psycopg2/extras.pyi +++ b/stubs/psycopg2/psycopg2/extras.pyi @@ -1,5 +1,6 @@ from collections import OrderedDict -from typing import Any, List +from collections.abc import Callable +from typing import Any, NamedTuple, TypeVar, overload from psycopg2._ipaddress import register_ipaddress as register_ipaddress from psycopg2._json import ( @@ -14,6 +15,10 @@ from psycopg2._psycopg import ( ReplicationConnection as _replicationConnection, ReplicationCursor as _replicationCursor, ReplicationMessage as ReplicationMessage, + _Vars, + connection as _connection, + cursor as _cursor, + quote_ident as quote_ident, ) from psycopg2._range import ( DateRange as DateRange, @@ -25,64 +30,129 @@ from psycopg2._range import ( RangeCaster as RangeCaster, register_range as register_range, ) +from psycopg2.sql import Composable -from .extensions import connection as _connection, cursor as _cursor, quote_ident as quote_ident +_T_cur = TypeVar("_T_cur", bound=_cursor) class DictCursorBase(_cursor): - row_factory: Any def __init__(self, *args, **kwargs) -> None: ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - def __iter__(self): ... class DictConnection(_connection): - def cursor(self, *args, **kwargs): ... + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> DictCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... class DictCursor(DictCursorBase): def __init__(self, *args, **kwargs) -> None: ... index: Any - def execute(self, query, vars: Any | None = ...): ... - def callproc(self, procname, vars: Any | None = ...): ... - -class DictRow(List[Any]): + def execute(self, query, vars=None): ... + def callproc(self, procname, vars=None): ... + def fetchone(self) -> DictRow | None: ... # type: ignore[override] + def fetchmany(self, size: int | None = None) -> list[DictRow]: ... # type: ignore[override] + def fetchall(self) -> list[DictRow]: ... # type: ignore[override] + def __next__(self) -> DictRow: ... # type: ignore[override] + +class DictRow(list[Any]): + __slots__ = ("_index",) def __init__(self, cursor) -> None: ... def __getitem__(self, x): ... def __setitem__(self, x, v) -> None: ... def items(self): ... def keys(self): ... def values(self): ... - def get(self, x, default: Any | None = ...): ... + def get(self, x, default=None): ... def copy(self): ... def __contains__(self, x): ... def __reduce__(self): ... class RealDictConnection(_connection): - def cursor(self, *args, **kwargs): ... + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> RealDictCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... class RealDictCursor(DictCursorBase): def __init__(self, *args, **kwargs) -> None: ... column_mapping: Any - def execute(self, query, vars: Any | None = ...): ... - def callproc(self, procname, vars: Any | None = ...): ... + def execute(self, query: str | bytes | Composable, vars: _Vars = None) -> None: ... + def callproc(self, procname, vars=None): ... + def fetchone(self) -> RealDictRow | None: ... # type: ignore[override] + def fetchmany(self, size: int | None = None) -> list[RealDictRow]: ... # type: ignore[override] + def fetchall(self) -> list[RealDictRow]: ... # type: ignore[override] + def __next__(self) -> RealDictRow: ... # type: ignore[override] class RealDictRow(OrderedDict[Any, Any]): def __init__(self, *args, **kwargs) -> None: ... def __setitem__(self, key, value) -> None: ... class NamedTupleConnection(_connection): - def cursor(self, *args, **kwargs): ... + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> NamedTupleCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... class NamedTupleCursor(_cursor): Record: Any MAX_CACHE: int - def execute(self, query, vars: Any | None = ...): ... + def execute(self, query, vars=None): ... def executemany(self, query, vars): ... - def callproc(self, procname, vars: Any | None = ...): ... - def fetchone(self): ... - def fetchmany(self, size: Any | None = ...): ... - def fetchall(self): ... - def __iter__(self): ... + def callproc(self, procname, vars=None): ... + def fetchone(self) -> NamedTuple | None: ... + def fetchmany(self, size: int | None = None) -> list[NamedTuple]: ... # type: ignore[override] + def fetchall(self) -> list[NamedTuple]: ... # type: ignore[override] + def __next__(self) -> NamedTuple: ... class LoggingConnection(_connection): log: Any @@ -91,18 +161,18 @@ class LoggingConnection(_connection): def cursor(self, *args, **kwargs): ... class LoggingCursor(_cursor): - def execute(self, query, vars: Any | None = ...): ... - def callproc(self, procname, vars: Any | None = ...): ... + def execute(self, query, vars=None): ... + def callproc(self, procname, vars=None): ... class MinTimeLoggingConnection(LoggingConnection): - def initialize(self, logobj, mintime: int = ...) -> None: ... + def initialize(self, logobj, mintime: int = 0) -> None: ... def filter(self, msg, curs): ... def cursor(self, *args, **kwargs): ... class MinTimeLoggingCursor(LoggingCursor): timestamp: Any - def execute(self, query, vars: Any | None = ...): ... - def callproc(self, procname, vars: Any | None = ...): ... + def execute(self, query, vars=None): ... + def callproc(self, procname, vars=None): ... class LogicalReplicationConnection(_replicationConnection): def __init__(self, *args, **kwargs) -> None: ... @@ -113,26 +183,29 @@ class PhysicalReplicationConnection(_replicationConnection): class StopReplication(Exception): ... class ReplicationCursor(_replicationCursor): - def create_replication_slot(self, slot_name, slot_type: Any | None = ..., output_plugin: Any | None = ...) -> None: ... + def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None) -> None: ... def drop_replication_slot(self, slot_name) -> None: ... def start_replication( self, - slot_name: Any | None = ..., - slot_type: Any | None = ..., - start_lsn: int = ..., - timeline: int = ..., - options: Any | None = ..., - decode: bool = ..., - status_interval: int = ..., + slot_name=None, + slot_type=None, + start_lsn: int = 0, + timeline: int = 0, + options=None, + decode: bool = False, + status_interval: int = 10, ) -> None: ... def fileno(self): ... + def consume_stream( + self, consume: Callable[[ReplicationMessage], object], keepalive_interval: float | None = None + ) -> None: ... class UUID_adapter: def __init__(self, uuid) -> None: ... def __conform__(self, proto): ... def getquoted(self): ... -def register_uuid(oids: Any | None = ..., conn_or_curs: Any | None = ...): ... +def register_uuid(oids=None, conn_or_curs=None): ... class Inet: addr: Any @@ -141,7 +214,7 @@ class Inet: def getquoted(self): ... def __conform__(self, proto): ... -def register_inet(oid: Any | None = ..., conn_or_curs: Any | None = ...): ... +def register_inet(oid=None, conn_or_curs=None): ... def wait_select(conn) -> None: ... class HstoreAdapter: @@ -157,9 +230,7 @@ class HstoreAdapter: @classmethod def get_oids(cls, conn_or_curs): ... -def register_hstore( - conn_or_curs, globally: bool = ..., unicode: bool = ..., oid: Any | None = ..., array_oid: Any | None = ... -) -> None: ... +def register_hstore(conn_or_curs, globally: bool = False, unicode: bool = False, oid=None, array_oid=None) -> None: ... class CompositeCaster: name: Any @@ -170,12 +241,12 @@ class CompositeCaster: atttypes: Any typecaster: Any array_typecaster: Any - def __init__(self, name, oid, attrs, array_oid: Any | None = ..., schema: Any | None = ...) -> None: ... + def __init__(self, name, oid, attrs, array_oid=None, schema=None) -> None: ... def parse(self, s, curs): ... def make(self, values): ... @classmethod def tokenize(cls, s): ... -def register_composite(name, conn_or_curs, globally: bool = ..., factory: Any | None = ...): ... -def execute_batch(cur, sql, argslist, page_size: int = ...) -> None: ... -def execute_values(cur, sql, argslist, template: Any | None = ..., page_size: int = ..., fetch: bool = ...): ... +def register_composite(name, conn_or_curs, globally: bool = False, factory=None): ... +def execute_batch(cur, sql, argslist, page_size: int = 100) -> None: ... +def execute_values(cur, sql, argslist, template=None, page_size: int = 100, fetch: bool = False): ... diff --git a/stubs/psycopg2/psycopg2/pool.pyi b/stubs/psycopg2/psycopg2/pool.pyi index 6bcf1b6d9fe5..a883d74f0ed8 100644 --- a/stubs/psycopg2/psycopg2/pool.pyi +++ b/stubs/psycopg2/psycopg2/pool.pyi @@ -1,18 +1,20 @@ -from typing import Any +from _typeshed import ConvertibleToInt +from collections.abc import Hashable import psycopg2 +from psycopg2.extensions import connection class PoolError(psycopg2.Error): ... class AbstractConnectionPool: - minconn: Any - maxconn: Any + minconn: int + maxconn: int closed: bool - def __init__(self, minconn, maxconn, *args, **kwargs) -> None: ... + def __init__(self, minconn: ConvertibleToInt, maxconn: ConvertibleToInt, *args, **kwargs) -> None: ... # getconn, putconn and closeall are officially documented as methods of the # abstract base class, but in reality, they only exist on the children classes - def getconn(self, key: Any | None = ...): ... - def putconn(self, conn: Any, key: Any | None = ..., close: bool = ...) -> None: ... + def getconn(self, key: Hashable | None = None) -> connection: ... + def putconn(self, conn: connection, key: Hashable | None = None, close: bool = False) -> None: ... def closeall(self) -> None: ... class SimpleConnectionPool(AbstractConnectionPool): ... @@ -20,4 +22,4 @@ class SimpleConnectionPool(AbstractConnectionPool): ... class ThreadedConnectionPool(AbstractConnectionPool): # This subclass has a default value for conn which doesn't exist # in the SimpleConnectionPool class, nor in the documentation - def putconn(self, conn: Any | None = ..., key: Any | None = ..., close: bool = ...) -> None: ... + def putconn(self, conn: connection | None = None, key: Hashable | None = None, close: bool = False) -> None: ... diff --git a/stubs/psycopg2/psycopg2/sql.pyi b/stubs/psycopg2/psycopg2/sql.pyi index be30d720ff3d..60f7d8714223 100644 --- a/stubs/psycopg2/psycopg2/sql.pyi +++ b/stubs/psycopg2/psycopg2/sql.pyi @@ -1,48 +1,49 @@ -from typing import Any +from collections.abc import Iterable, Iterator +from typing import Any, Generic, TypeVar + +from psycopg2._psycopg import connection, cursor + +_T = TypeVar("_T") class Composable: - def __init__(self, wrapped) -> None: ... - def as_string(self, context) -> None: ... - def __add__(self, other): ... - def __mul__(self, n): ... - def __eq__(self, other): ... - def __ne__(self, other): ... + def __init__(self, wrapped: Any) -> None: ... + def as_string(self, context: connection | cursor) -> str: ... + def __add__(self, other: Composable) -> Composed: ... + def __mul__(self, n: int) -> Composed: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... class Composed(Composable): - def __init__(self, seq) -> None: ... + def __init__(self, seq: Iterable[Composable]) -> None: ... @property - def seq(self): ... - def as_string(self, context): ... - def __iter__(self): ... - def __add__(self, other): ... - def join(self, joiner): ... + def seq(self) -> list[Composable]: ... + def __iter__(self) -> Iterator[Composable]: ... + def __add__(self, other: Composable) -> Composed: ... + def join(self, joiner: str | SQL) -> Composed: ... class SQL(Composable): - def __init__(self, string) -> None: ... + def __init__(self, string: str) -> None: ... @property - def string(self): ... - def as_string(self, context): ... - def format(self, *args, **kwargs): ... - def join(self, seq): ... + def string(self) -> str: ... + def format(self, *args: Composable, **kwargs: Composable) -> Composed: ... + def join(self, seq: Iterable[Composable]) -> Composed: ... class Identifier(Composable): - def __init__(self, *strings) -> None: ... + def __init__(self, *strings: str) -> None: ... @property - def strings(self): ... + def strings(self) -> tuple[str, ...]: ... @property - def string(self): ... - def as_string(self, context): ... + def string(self) -> str: ... -class Literal(Composable): +class Literal(Composable, Generic[_T]): + def __init__(self, wrapped: _T) -> None: ... @property - def wrapped(self): ... - def as_string(self, context): ... + def wrapped(self) -> _T: ... class Placeholder(Composable): - def __init__(self, name: Any | None = ...) -> None: ... + def __init__(self, name: str | None = None) -> None: ... @property - def name(self): ... - def as_string(self, context): ... + def name(self) -> str | None: ... -NULL: Any -DEFAULT: Any +NULL: SQL +DEFAULT: SQL diff --git a/stubs/psycopg2/psycopg2/tz.pyi b/stubs/psycopg2/psycopg2/tz.pyi index 613e411323c7..75d1484805f7 100644 --- a/stubs/psycopg2/psycopg2/tz.pyi +++ b/stubs/psycopg2/psycopg2/tz.pyi @@ -1,25 +1,26 @@ import datetime from typing import Any +from typing_extensions import Self -ZERO: Any +ZERO: datetime.timedelta class FixedOffsetTimezone(datetime.tzinfo): - def __init__(self, offset: Any | None = ..., name: Any | None = ...) -> None: ... - def __new__(cls, offset: Any | None = ..., name: Any | None = ...): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __getinitargs__(self): ... - def utcoffset(self, dt): ... - def tzname(self, dt): ... - def dst(self, dt): ... + def __init__(self, offset: datetime.timedelta | float | None = None, name: str | None = None) -> None: ... + def __new__(cls, offset: datetime.timedelta | float | None = None, name: str | None = None) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __getinitargs__(self) -> tuple[Any, ...]: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... -STDOFFSET: Any -DSTOFFSET: Any -DSTDIFF: Any +STDOFFSET: datetime.timedelta +DSTOFFSET: datetime.timedelta +DSTDIFF: datetime.timedelta class LocalTimezone(datetime.tzinfo): - def utcoffset(self, dt): ... - def dst(self, dt): ... - def tzname(self, dt): ... + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def tzname(self, dt: datetime.datetime) -> str: ... # type: ignore[override] -LOCAL: Any +LOCAL: LocalTimezone diff --git a/stubs/punq/@tests/stubtest_allowlist.txt b/stubs/punq/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..9a0d8e0f9e3a --- /dev/null +++ b/stubs/punq/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +punq._Empty.__init__ +punq._Registration.__class_getitem__ diff --git a/stubs/punq/METADATA.toml b/stubs/punq/METADATA.toml new file mode 100644 index 000000000000..0c23131200c7 --- /dev/null +++ b/stubs/punq/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.8.*" +upstream-repository = "https://github.com/bobthemighty/punq" +obsolete-since = {version = "0.9.0", date = "2026-09-08"} diff --git a/stubs/punq/punq/__init__.pyi b/stubs/punq/punq/__init__.pyi new file mode 100644 index 000000000000..1fb20df72028 --- /dev/null +++ b/stubs/punq/punq/__init__.pyi @@ -0,0 +1,138 @@ +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Callable +from enum import Enum, unique +from typing import Any, Final, Generic, NamedTuple, NewType, TypeVar, overload +from typing_extensions import Self, deprecated + +_T = TypeVar("_T", default=Any) + +__version__: Final[str] + +@deprecated("Deprecated alias for `MissingDependencyError`.") +class MissingDependencyException(Exception): ... + +class MissingDependencyError(MissingDependencyException): ... + +@deprecated("Deprecated alias for `InvalidRegistrationError`.") +class InvalidRegistrationException(Exception): ... + +class InvalidRegistrationError(InvalidRegistrationException): ... + +class InvalidFactoryError(InvalidRegistrationError): + def __init__(self, service, factory) -> None: ... + +class InvalidSelfRegistrationError(InvalidRegistrationError): + def __init__(self, service) -> None: ... + +@deprecated("Deprecated alias for `InvalidForwardReferenceError`.") +class InvalidForwardReferenceException(Exception): ... + +class InvalidForwardReferenceError(InvalidForwardReferenceException): ... + +# TODO: Make this class Generic +class RegistrationScope: + parent: RegistrationScope | None + entries: defaultdict[Incomplete, list[Incomplete]] + def __init__(self, parent: RegistrationScope | None = None) -> None: ... + def child(self) -> Self: ... + def append(self, key, value) -> None: ... + def get(self, key) -> list[Incomplete]: ... + +@unique +class Scope(Enum): + transient = 0 + singleton = 1 + +class _Registration(NamedTuple, Generic[_T]): + service: type[_T] | str + scope: Scope + builder: Callable[..., _T] + needs: dict[str, Any] # the type hints of the builder's parameters + args: dict[str, Any] # passed to builder at instantiation time + cache: bool + +_Empty = NewType("_Empty", object) # a class at runtime +empty: Final[_Empty] + +class _Registry: + def __init__(self, parent: _Registry | None = None) -> None: ... + def register_service_and_impl( + self, + service: type[_T] | str, + scope: Scope, + impl: type[_T], + resolve_args: dict[str, Any], # forwarded to _Registration.builder + cache: bool = True, + ) -> None: ... + def register_service_and_instance(self, service: type[_T] | str, instance: _T) -> None: ... + def register_concrete_service( + self, + service: type | str, + scope: Scope, + resolve_args: dict[str, Any] | None = None, # forwarded to _Registration.builder + cache: bool = True, + ) -> None: ... + def build_context(self, key: type | str, existing: _ResolutionContext | None = None) -> _ResolutionContext: ... + def register( + self, + service: type[_T] | str, + factory: Callable[..., _T] | _Empty = ..., + instance: _T | _Empty = ..., + scope: Scope = Scope.transient, + cache: bool = True, + **kwargs: Any, # forwarded to _Registration.builder + ) -> None: ... + +class _ResolutionTarget(Generic[_T]): + service: type[_T] | str + impls: list[_Registration[_T]] + def __init__(self, key: type[_T] | str, impls: list[_Registration[_T]]) -> None: ... + def is_generic_list(self) -> bool: ... + @property + def generic_parameter(self) -> Any: ... # returns the first annotated generic parameter of the service + def next_impl(self) -> _Registration[_T] | None: ... + +class _ResolutionContext: + targets: dict[type | str, _ResolutionTarget[Any]] + cache: dict[type | str, Any] # resolved objects during this resolution + service: type | str + def __init__(self, key: type | str, impls: list[_Registration[Any]]) -> None: ... + def target(self, key: type[_T] | str) -> _ResolutionTarget[_T]: ... + def has_cached(self, key: type | str) -> bool: ... + def __getitem__(self, key: type[_T] | str) -> _T: ... + def __setitem__(self, key: type[_T] | str, value: _T) -> None: ... + def all_registrations(self, service: type[_T] | str) -> list[_Registration[_T]]: ... + +class Container: + registrations: _Registry + def __init__(self, registrations: _Registry | None = None, auto_register: bool = False) -> None: ... + + # all kwargs are forwarded to _Registration.builder + @overload + def register(self, service: type[_T] | str, *, instance: _T, cache: bool = True, **kwargs: Any) -> Self: ... + @overload + def register( + self, + service: type[_T] | str, + factory: Callable[..., _T] | _Empty = ..., + *, + scope: Scope = Scope.transient, + cache: bool = True, + **kwargs: Any, + ) -> Self: ... + @overload + def register( + self, + service: type[_T] | str, + factory: Callable[..., _T] | _Empty = ..., + instance: _T | _Empty = ..., + scope: Scope = Scope.transient, + cache: bool = True, + **kwargs: Any, + ) -> Self: ... + + def resolve_all(self, service: type[_T] | str, **kwargs: Any) -> list[_T]: ... + def resolve(self, service_key: type[_T] | str, **kwargs: Any) -> _T: ... + def instantiate(self, service_key: type[_T] | str, **kwargs: Any) -> _T: ... + def child(self) -> Self: ... diff --git a/stubs/pyOpenSSL/@tests/stubtest_allowlist.txt b/stubs/pyOpenSSL/@tests/stubtest_allowlist.txt deleted file mode 100644 index ade54ad26213..000000000000 --- a/stubs/pyOpenSSL/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1 +0,0 @@ -OpenSSL.SSL.Context.__getattr__ diff --git a/stubs/pyOpenSSL/METADATA.toml b/stubs/pyOpenSSL/METADATA.toml deleted file mode 100644 index 4be158bf0ef1..000000000000 --- a/stubs/pyOpenSSL/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -version = "21.0.*" -python2 = true -requires = ["types-cryptography"] diff --git a/stubs/pyOpenSSL/OpenSSL/SSL.pyi b/stubs/pyOpenSSL/OpenSSL/SSL.pyi deleted file mode 100644 index e947c788b667..000000000000 --- a/stubs/pyOpenSSL/OpenSSL/SSL.pyi +++ /dev/null @@ -1,155 +0,0 @@ -import socket -from typing import Any, Callable, Sequence - -from OpenSSL.crypto import X509, PKey - -OPENSSL_VERSION_NUMBER: int -SSLEAY_VERSION: int -SSLEAY_CFLAGS: int -SSLEAY_PLATFORM: int -SSLEAY_DIR: int -SSLEAY_BUILT_ON: int - -SENT_SHUTDOWN: int -RECEIVED_SHUTDOWN: int - -SSLv2_METHOD: int -SSLv3_METHOD: int -SSLv23_METHOD: int -TLSv1_METHOD: int -TLSv1_1_METHOD: int -TLSv1_2_METHOD: int - -TLS_METHOD: int -TLS_SERVER_METHOD: int -TLS_CLIENT_METHOD: int - -SSL3_VERSION: int -TLS1_VERSION: int -TLS1_1_VERSION: int -TLS1_2_VERSION: int -TLS1_3_VERSION: int - -OP_NO_SSLv2: int -OP_NO_SSLv3: int -OP_NO_TLSv1: int -OP_NO_TLSv1_1: int -OP_NO_TLSv1_2: int -OP_NO_TLSv1_3: int - -MODE_RELEASE_BUFFERS: int - -OP_SINGLE_DH_USE: int -OP_SINGLE_ECDH_USE: int -OP_EPHEMERAL_RSA: int -OP_MICROSOFT_SESS_ID_BUG: int -OP_NETSCAPE_CHALLENGE_BUG: int -OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: int - -OP_SSLREF2_REUSE_CERT_TYPE_BUG: int -OP_MICROSOFT_BIG_SSLV3_BUFFER: int -OP_MSIE_SSLV2_RSA_PADDING: int -OP_SSLEAY_080_CLIENT_DH_BUG: int -OP_TLS_D5_BUG: int -OP_TLS_BLOCK_PADDING_BUG: int -OP_DONT_INSERT_EMPTY_FRAGMENTS: int -OP_CIPHER_SERVER_PREFERENCE: int -OP_TLS_ROLLBACK_BUG: int -OP_PKCS1_CHECK_1: int -OP_PKCS1_CHECK_2: int -OP_NETSCAPE_CA_DN_BUG: int -OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: int - -OP_NO_COMPRESSION: int - -OP_NO_QUERY_MTU: int -OP_COOKIE_EXCHANGE: int -OP_NO_TICKET: int - -OP_ALL: int - -VERIFY_PEER: int -VERIFY_FAIL_IF_NO_PEER_CERT: int -VERIFY_CLIENT_ONCE: int -VERIFY_NONE: int - -SESS_CACHE_OFF: int -SESS_CACHE_CLIENT: int -SESS_CACHE_SERVER: int -SESS_CACHE_BOTH: int -SESS_CACHE_NO_AUTO_CLEAR: int -SESS_CACHE_NO_INTERNAL_LOOKUP: int -SESS_CACHE_NO_INTERNAL_STORE: int -SESS_CACHE_NO_INTERNAL: int - -SSL_ST_CONNECT: int -SSL_ST_ACCEPT: int -SSL_ST_MASK: int - -SSL_CB_LOOP: int -SSL_CB_EXIT: int -SSL_CB_READ: int -SSL_CB_WRITE: int -SSL_CB_ALERT: int -SSL_CB_READ_ALERT: int -SSL_CB_WRITE_ALERT: int -SSL_CB_ACCEPT_LOOP: int -SSL_CB_ACCEPT_EXIT: int -SSL_CB_CONNECT_LOOP: int -SSL_CB_CONNECT_EXIT: int -SSL_CB_HANDSHAKE_START: int -SSL_CB_HANDSHAKE_DONE: int - -NO_OVERLAPPING_PROTOCOLS: object - -class Error(Exception): ... -class WantReadError(Error): ... -class WantWriteError(Error): ... -class WantX509LookupError(Error): ... -class ZeroReturnError(Error): ... -class SysCallError(Error): ... - -def SSLeay_version(type: int) -> str: ... - -class Session(object): ... - -class Connection(object): - def __getattr__(self, name: str) -> Any: ... # incomplete - def __init__(self, context: Context, socket: socket.socket | None = ...) -> None: ... - def connect(self, addr: str | bytes | Sequence[str | int]) -> None: ... - def do_handshake(self) -> None: ... - def get_peer_certificate(self) -> X509: ... - def set_tlsext_host_name(self, name: bytes) -> None: ... - def bio_read(self, bufsiz: int) -> bytes: ... - def bio_write(self, buf: bytes) -> int: ... - def recv(self, bufsiz: int, flags: int | None = ...) -> bytes: ... - def sendall(self, buf: bytes, flags: int = ...) -> int: ... - def set_accept_state(self) -> None: ... - def set_connect_state(self) -> None: ... - def get_peer_cert_chain(self) -> list[X509]: ... - def get_alpn_proto_negotiated(self) -> bytes: ... - def get_cipher_name(self) -> str | None: ... - def get_protocol_version_name(self) -> str: ... - def get_shutdown(self) -> int: ... - def get_app_data(self) -> Any: ... - def set_app_data(self, data: Any) -> None: ... - -class Context(object): - def __getattr__(self, name: str) -> Any: ... # incomplete - def __init__(self, method: int) -> None: ... - def load_verify_locations(self, cafile: str | None, capath: str | None = ...) -> None: ... - def set_options(self, options: int) -> None: ... - def set_verify(self, mode: int, callback: Callable[[Connection, X509, int, int, int], bool] | None = ...) -> None: ... - # will be added in pyOpenSSL 21 - # def set_min_proto_version(self, version: int) -> None: ... - # def set_max_proto_version(self, version: int) -> None: ... - def use_certificate_chain_file(self, certfile: str | bytes) -> None: ... - def use_certificate_file(self, certfile: str | bytes, filetype: int = ...) -> None: ... - def use_certificate(self, cert: X509) -> None: ... - def use_privatekey_file(self, keyfile: str | bytes, filetype: int | None = ...) -> None: ... - def use_privatekey(self, pkey: PKey) -> None: ... - def add_extra_chain_cert(self, certobj: X509) -> None: ... - def set_cipher_list(self, cipher_list: bytes) -> None: ... - def set_keylog_callback(self, callback: Callable[[Connection, bytes], None]) -> None: ... - def set_alpn_protos(self, protos: Sequence[bytes]) -> None: ... - def set_alpn_select_callback(self, callback: Callable[[Connection, list[bytes]], bytes]) -> None: ... diff --git a/stubs/pyOpenSSL/OpenSSL/crypto.pyi b/stubs/pyOpenSSL/OpenSSL/crypto.pyi deleted file mode 100644 index abfb1e3ab85d..000000000000 --- a/stubs/pyOpenSSL/OpenSSL/crypto.pyi +++ /dev/null @@ -1,203 +0,0 @@ -from datetime import datetime -from typing import Any, Callable, Iterable, Sequence, Text, Tuple, Union - -from cryptography.hazmat.primitives.asymmetric.dsa import DSAPrivateKey, DSAPublicKey -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey -from cryptography.x509 import Certificate, CertificateRevocationList, CertificateSigningRequest - -_Key = Union[DSAPrivateKey, DSAPublicKey, RSAPrivateKey, RSAPublicKey] - -FILETYPE_PEM: int -FILETYPE_ASN1: int -FILETYPE_TEXT: int - -TYPE_RSA: int -TYPE_DSA: int - -class _EllipticCurve: - def __init__(self, lib: Any | None, nid: int, name: str) -> None: ... - -class Error(Exception): ... - -class PKey: - def __init__(self) -> None: ... - def bits(self) -> int: ... - def check(self) -> bool: ... - @classmethod - def from_cryptography_key(cls, crypto_key: _Key) -> PKey: ... - def generate_key(self, type: int, bits: int) -> None: ... - def to_cryptography_key(self) -> _Key: ... - def type(self) -> int: ... - -class X509Name: - countryName: Text - C: Text - stateOrProvinceName: Text - ST: Text - localityName: Text - L: Text - organizationName: Text - O: Text - organizationalUnitName: Text - OU: Text - commonName: Text - CN: Text - emailAddress: Text - def __init__(self, name: X509Name) -> None: ... - def der(self) -> bytes: ... - def get_components(self) -> list[tuple[bytes, bytes]]: ... - def hash(self) -> int: ... - -class X509: - def __init__(self) -> None: ... - def add_extensions(self, extensions: Iterable[X509Extension]) -> None: ... - def digest(self, digest_name: bytes) -> bytes: ... - @classmethod - def from_cryptography(cls, crypto_cert: Certificate) -> X509: ... - def get_extension(self, index: int) -> X509Extension: ... - def get_extension_count(self) -> int: ... - def get_issuer(self) -> X509Name: ... - def get_notAfter(self) -> bytes | None: ... - def get_notBefore(self) -> bytes | None: ... - def get_pubkey(self) -> PKey: ... - def get_serial_number(self) -> int: ... - def get_signature_algorithm(self) -> bytes: ... - def get_subject(self) -> X509Name: ... - def get_version(self) -> int: ... - def gmtime_adj_notAfter(self, amount: int) -> None: ... - def gmtime_adj_notBefore(self, amount: int) -> None: ... - def has_expired(self) -> bool: ... - def set_issuer(self, issuer: X509Name) -> None: ... - def set_notAfter(self, when: bytes) -> None: ... - def set_notBefore(self, when: bytes) -> None: ... - def set_pubkey(self, pkey: PKey) -> None: ... - def set_serial_number(self, serial: int) -> None: ... - def set_subject(self, subject: X509Name) -> None: ... - def set_version(self, version: int) -> None: ... - def sign(self, pkey: PKey, digest: Text | bytes) -> None: ... - def subject_name_hash(self) -> bytes: ... - def to_cryptography(self) -> Certificate: ... - -class X509Req: - def __init__(self) -> None: ... - def add_extensions(self, extensions: Iterable[X509Extension]) -> None: ... - @classmethod - def from_cryptography(cls, crypto_req: CertificateSigningRequest) -> X509Req: ... - def get_extensions(self) -> list[X509Extension]: ... - def get_pubkey(self) -> PKey: ... - def get_subject(self) -> X509Name: ... - def get_version(self) -> int: ... - def set_pubkey(self, pkey: PKey) -> None: ... - def set_version(self, version: int) -> None: ... - def sign(self, pkey: PKey, digest: Text | bytes) -> None: ... - def to_cryptography(self) -> CertificateSigningRequest: ... - def verify(self, pkey: PKey) -> bool: ... - -class X509Extension: - def __init__( - self, type_name: bytes, critical: bool, value: bytes, subject: X509 | None = ..., issuer: X509 | None = ... - ) -> None: ... - def get_critical(self) -> bool: ... - def get_data(self) -> bytes: ... - def get_short_name(self) -> bytes: ... - -class Revoked: - def __init__(self) -> None: ... - def all_reasons(self) -> list[bytes]: ... - def get_reason(self) -> bytes | None: ... - def get_rev_date(self) -> bytes: ... - def get_serial(self) -> bytes: ... - def set_reason(self, reason: bytes | None) -> None: ... - def set_rev_date(self, when: bytes) -> None: ... - def set_serial(self, hex_str: bytes) -> None: ... - -class CRL: - def __init__(self) -> None: ... - def add_revoked(self, revoked: Revoked) -> None: ... - def export(self, cert: X509, key: PKey, type: int = ..., days: int = ..., digest: bytes = ...) -> bytes: ... - @classmethod - def from_cryptography(cls, crypto_crl: CertificateRevocationList) -> CRL: ... - def get_issuer(self) -> X509Name: ... - def get_revoked(self) -> Tuple[Revoked, ...]: ... - def set_lastUpdate(self, when: bytes) -> None: ... - def set_nextUpdate(self, when: bytes) -> None: ... - def set_version(self, version: int) -> None: ... - def sign(self, issuer_cert: X509, issuer_key: PKey, digest: bytes) -> None: ... - def to_cryptography(self) -> CertificateRevocationList: ... - -class X509Store: - def __init__(self) -> None: ... - def add_cert(self, cert: X509) -> None: ... - def add_crl(self, crl: CRL) -> None: ... - def load_locations(self, cafile: Text | bytes, capath: Text | bytes | None = ...) -> None: ... - def set_flags(self, flags: int) -> None: ... - def set_time(self, vfy_time: datetime) -> None: ... - -class X509StoreContext: - def __init__(self, store: X509Store, certificate: X509, chain: Sequence[X509] | None = ...) -> None: ... - def get_verified_chain(self) -> list[X509]: ... - def set_store(self, store: X509Store) -> None: ... - def verify_certificate(self) -> None: ... - -class X509StoreContextError(Exception): - certificate: X509 - def __init__(self, message: Text | bytes, certificate: X509) -> None: ... - -class X509StoreFlags: - CRL_CHECK: int - CRL_CHECK_ALL: int - IGNORE_CRITICAL: int - X509_STRICT: int - ALLOW_PROXY_CERTS: int - POLICY_CHECK: int - EXPLICIT_POLICY: int - INHIBIT_MAP: int - NOTIFY_POLICY: int - CHECK_SS_SIGNATURE: int - CB_ISSUER_CHECK: int - -class PKCS7: - def get_type_name(self) -> Text: ... - def type_is_data(self) -> bool: ... - def type_is_enveloped(self) -> bool: ... - def type_is_signed(self) -> bool: ... - def type_is_signedAndEnveloped(self) -> bool: ... - -class PKCS12: - def __init__(self) -> None: ... - def export(self, passphrase: bytes | None = ..., iter: int = ..., maciter: int = ...) -> bytes: ... - def get_ca_certificates(self) -> Tuple[X509, ...]: ... - def get_certificate(self) -> X509: ... - def get_friendlyname(self) -> bytes | None: ... - def get_privatekey(self) -> PKey: ... - def set_ca_certificates(self, cacerts: Iterable[X509] | None) -> None: ... - def set_certificate(self, cert: X509) -> None: ... - def set_friendlyname(self, name: bytes | None) -> None: ... - def set_privatekey(self, pkey: PKey) -> None: ... - -class NetscapeSPKI: - def __init__(self) -> None: ... - def b64_encode(self) -> bytes: ... - def get_pubkey(self) -> PKey: ... - def set_pubkey(self, pkey: PKey) -> None: ... - def sign(self, pkey: PKey, digest: bytes) -> None: ... - def verify(self, key: PKey) -> bool: ... - -def get_elliptic_curves() -> set[_EllipticCurve]: ... -def get_elliptic_curve(name: Text) -> _EllipticCurve: ... -def dump_certificate(type: int, cert: X509) -> bytes: ... -def load_certificate(type: int, buffer: bytes) -> X509: ... -def dump_certificate_request(type: int, req: X509Req) -> bytes: ... -def load_certificate_request(type: int, buffer: bytes) -> X509Req: ... -def dump_privatekey( - type: int, pkey: PKey, cipher: bytes | None = ..., passphrase: bytes | Callable[[], bytes] | None = ... -) -> bytes: ... -def load_privatekey(type: int, buffer: Text | bytes, passphrase: bytes | Callable[[], bytes] | None = ...) -> PKey: ... -def dump_publickey(type: int, pkey: PKey) -> bytes: ... -def load_publickey(type: int, buffer: Text | bytes) -> PKey: ... -def dump_crl(type: int, crl: CRL) -> bytes: ... -def load_crl(type: int, buffer: Text | bytes) -> CRL: ... -def load_pkcs7_data(type: int, buffer: Text | bytes) -> PKCS7: ... -def load_pkcs12(buffer: Text | bytes, passphrase: bytes | None = ...) -> PKCS12: ... -def sign(pkey: PKey, data: Text | bytes, digest: Text | bytes) -> bytes: ... -def verify(cert: X509, signature: bytes, data: Text | bytes, digest: Text | bytes) -> None: ... diff --git a/stubs/pyRFC3339/METADATA.toml b/stubs/pyRFC3339/METADATA.toml deleted file mode 100644 index bad265e4fe3f..000000000000 --- a/stubs/pyRFC3339/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "1.1" diff --git a/stubs/pyRFC3339/pyrfc3339/__init__.pyi b/stubs/pyRFC3339/pyrfc3339/__init__.pyi deleted file mode 100644 index d8c1ca5e88c7..000000000000 --- a/stubs/pyRFC3339/pyrfc3339/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from .generator import generate as generate -from .parser import parse as parse diff --git a/stubs/pyRFC3339/pyrfc3339/generator.pyi b/stubs/pyRFC3339/pyrfc3339/generator.pyi deleted file mode 100644 index 9375b5b61109..000000000000 --- a/stubs/pyRFC3339/pyrfc3339/generator.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from datetime import datetime - -def generate(dt: datetime, utc: bool = ..., accept_naive: bool = ..., microseconds: bool = ...) -> str: ... diff --git a/stubs/pyRFC3339/pyrfc3339/parser.pyi b/stubs/pyRFC3339/pyrfc3339/parser.pyi deleted file mode 100644 index 445b542c38cd..000000000000 --- a/stubs/pyRFC3339/pyrfc3339/parser.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from datetime import datetime - -def parse(timestamp: str, utc: bool = ..., produce_naive: bool = ...) -> datetime: ... diff --git a/stubs/pyRFC3339/pyrfc3339/utils.pyi b/stubs/pyRFC3339/pyrfc3339/utils.pyi deleted file mode 100644 index 54588acf74a5..000000000000 --- a/stubs/pyRFC3339/pyrfc3339/utils.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from datetime import datetime, timedelta, tzinfo - -class FixedOffset(tzinfo): - def __init__(self, hours: float, minutes: float) -> None: ... - def dst(self, dt: datetime | None) -> timedelta: ... - def utcoffset(self, dt: datetime | None) -> timedelta: ... - def tzname(self, dt: datetime | None) -> str: ... - -def timedelta_seconds(td: timedelta) -> int: ... -def timezone(utcoffset: float) -> str: ... diff --git a/stubs/pyasn1/METADATA.toml b/stubs/pyasn1/METADATA.toml new file mode 100644 index 000000000000..c9d5651dfeeb --- /dev/null +++ b/stubs/pyasn1/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.6.*" +upstream-repository = "https://github.com/pyasn1/pyasn1" diff --git a/stubs/pyasn1/pyasn1/__init__.pyi b/stubs/pyasn1/pyasn1/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/pyasn1/pyasn1/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/pyasn1/pyasn1/codec/__init__.pyi b/stubs/pyasn1/pyasn1/codec/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/ber/__init__.pyi b/stubs/pyasn1/pyasn1/codec/ber/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/ber/decoder.pyi b/stubs/pyasn1/pyasn1/codec/ber/decoder.pyi new file mode 100644 index 000000000000..587e25b84992 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/ber/decoder.pyi @@ -0,0 +1,356 @@ +from _typeshed import Incomplete, Unused +from abc import ABCMeta, abstractmethod +from collections.abc import Callable + +from pyasn1.type import base, char, univ, useful +from pyasn1.type.base import Asn1Type +from pyasn1.type.tag import TagSet + +__all__ = ["StreamingDecoder", "Decoder", "decode"] + +class AbstractPayloadDecoder: + protoComponent: Asn1Type | None + @abstractmethod + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ) -> None: ... + # Abstract, but implementation is optional + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ) -> None: ... + +class AbstractSimplePayloadDecoder(AbstractPayloadDecoder, metaclass=ABCMeta): + @staticmethod + def substrateCollector(asn1Object, substrate, length, options): ... + +class RawPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Any + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class IntegerPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Integer + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class BooleanPayloadDecoder(IntegerPayloadDecoder): + protoComponent: univ.Boolean + +class BitStringPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.BitString + supportConstructedForm: bool + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class OctetStringPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.OctetString + supportConstructedForm: bool + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class NullPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Null + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class ObjectIdentifierPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.ObjectIdentifier + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class RealPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Real + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class AbstractConstructedPayloadDecoder(AbstractPayloadDecoder, metaclass=ABCMeta): + protoComponent: base.ConstructedAsn1Type | None + +class ConstructedPayloadDecoderBase(AbstractConstructedPayloadDecoder): + protoRecordComponent: univ.SequenceAndSetBase | None + protoSequenceComponent: univ.SequenceOfAndSetOfBase | None + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class SequenceOrSequenceOfPayloadDecoder(ConstructedPayloadDecoderBase): + protoRecordComponent: univ.Sequence + protoSequenceComponent: univ.SequenceOf + +class SequencePayloadDecoder(SequenceOrSequenceOfPayloadDecoder): + protoComponent: univ.Sequence + +class SequenceOfPayloadDecoder(SequenceOrSequenceOfPayloadDecoder): + protoComponent: univ.SequenceOf + +class SetOrSetOfPayloadDecoder(ConstructedPayloadDecoderBase): + protoRecordComponent: univ.Set + protoSequenceComponent: univ.SetOf + +class SetPayloadDecoder(SetOrSetOfPayloadDecoder): + protoComponent: univ.Set + +class SetOfPayloadDecoder(SetOrSetOfPayloadDecoder): + protoComponent: univ.SetOf + +class ChoicePayloadDecoder(AbstractConstructedPayloadDecoder): + protoComponent: univ.Choice + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class AnyPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Any + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class UTF8StringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.UTF8String + +class NumericStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.NumericString + +class PrintableStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.PrintableString + +class TeletexStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.TeletexString + +class VideotexStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.VideotexString + +class IA5StringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.IA5String + +class GraphicStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.GraphicString + +class VisibleStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.VisibleString + +class GeneralStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.GeneralString + +class UniversalStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.UniversalString + +class BMPStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.BMPString + +class ObjectDescriptorPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: useful.ObjectDescriptor + +class GeneralizedTimePayloadDecoder(OctetStringPayloadDecoder): + protoComponent: useful.GeneralizedTime + +class UTCTimePayloadDecoder(OctetStringPayloadDecoder): + protoComponent: useful.UTCTime + +TAG_MAP: dict[TagSet, AbstractPayloadDecoder] +TYPE_MAP: dict[int, AbstractPayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder: + defaultErrorState: int + defaultRawDecoder: AnyPayloadDecoder + supportIndefLength: bool + TAG_MAP: dict[TagSet, AbstractPayloadDecoder] + TYPE_MAP: dict[int, AbstractPayloadDecoder] + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__( + self, + substrate, + asn1Spec: Asn1Type | None = None, + tagSet: TagSet | None = None, + length: int | None = None, + state=0, + decodeFun: Unused = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +decode: Decoder + +class StreamingDecoder: + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + + def __init__(self, substrate, asn1Spec=None, *, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __iter__(self): ... + +class Decoder: + STREAMING_DECODER: type[StreamingDecoder] + + @classmethod + def __call__(cls, substrate, asn1Spec=None, *, tagMap=..., typeMap=..., **ignored: Unused): ... diff --git a/stubs/pyasn1/pyasn1/codec/ber/encoder.pyi b/stubs/pyasn1/pyasn1/codec/ber/encoder.pyi new file mode 100644 index 000000000000..58a9193b1a17 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/ber/encoder.pyi @@ -0,0 +1,84 @@ +from _typeshed import Unused +from abc import abstractmethod + +from pyasn1.type.base import Asn1Type +from pyasn1.type.tag import TagSet + +__all__ = ["Encoder", "encode"] + +class AbstractItemEncoder: + supportIndefLenMode: bool + eooIntegerSubstrate: tuple[int, int] + eooOctetsSubstrate: bytes + def encodeTag(self, singleTag, isConstructed): ... + def encodeLength(self, length, defMode): ... + @abstractmethod + def encodeValue(self, value, asn1Spec, encodeFun, **options) -> None: ... + def encode(self, value, asn1Spec: Asn1Type | None = None, encodeFun=None, **options): ... + +class EndOfOctetsEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class BooleanEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class IntegerEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + supportCompactZero: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class BitStringEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class OctetStringEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class NullEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class ObjectIdentifierEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class RealEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + binEncBase: int + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceEncoder(AbstractItemEncoder): + omitEmptyOptionals: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceOfEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class ChoiceEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class AnyEncoder(OctetStringEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +TAG_MAP: dict[TagSet, AbstractItemEncoder] +TYPE_MAP: dict[int, AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder: + fixedDefLengthMode: bool | None + fixedChunkSize: int | None + TAG_MAP: dict[TagSet, AbstractItemEncoder] + TYPE_MAP: dict[int, AbstractItemEncoder] + + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__(self, value, asn1Spec: Asn1Type | None = None, **options): ... + +class Encoder: + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + + def __init__(self, tagMap=..., typeMap=..., **options: Unused) -> None: ... + def __call__(self, pyObject, asn1Spec: Asn1Type | None = None, **options): ... + +encode: Encoder diff --git a/stubs/pyasn1/pyasn1/codec/ber/eoo.pyi b/stubs/pyasn1/pyasn1/codec/ber/eoo.pyi new file mode 100644 index 000000000000..00375f576216 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/ber/eoo.pyi @@ -0,0 +1,11 @@ +from pyasn1.type import base +from pyasn1.type.tag import TagSet + +__all__ = ["endOfOctets"] + +class EndOfOctets(base.SimpleAsn1Type): + defaultValue: int + tagSet: TagSet + def __new__(cls, *args, **kwargs): ... + +endOfOctets: EndOfOctets diff --git a/stubs/pyasn1/pyasn1/codec/cer/__init__.pyi b/stubs/pyasn1/pyasn1/codec/cer/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/cer/decoder.pyi b/stubs/pyasn1/pyasn1/codec/cer/decoder.pyi new file mode 100644 index 000000000000..f847313ad438 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/cer/decoder.pyi @@ -0,0 +1,43 @@ +from _typeshed import Unused + +from pyasn1.codec.ber import decoder +from pyasn1.type import univ +from pyasn1.type.tag import TagSet + +__all__ = ["decode", "StreamingDecoder"] + +class BooleanPayloadDecoder(decoder.AbstractSimplePayloadDecoder): + protoComponent: univ.Boolean + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +BitStringPayloadDecoder = decoder.BitStringPayloadDecoder +OctetStringPayloadDecoder = decoder.OctetStringPayloadDecoder +RealPayloadDecoder = decoder.RealPayloadDecoder + +TAG_MAP: dict[TagSet, decoder.AbstractPayloadDecoder] +TYPE_MAP: dict[int, decoder.AbstractPayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder(decoder.SingleItemDecoder): + TAG_MAP: dict[TagSet, decoder.AbstractPayloadDecoder] + TYPE_MAP: dict[int, decoder.AbstractPayloadDecoder] + +class StreamingDecoder(decoder.StreamingDecoder): + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + +class Decoder(decoder.Decoder): + STREAMING_DECODER: type[StreamingDecoder] + +decode: Decoder diff --git a/stubs/pyasn1/pyasn1/codec/cer/encoder.pyi b/stubs/pyasn1/pyasn1/codec/cer/encoder.pyi new file mode 100644 index 000000000000..25552d917862 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/cer/encoder.pyi @@ -0,0 +1,55 @@ +from typing import ClassVar + +from pyasn1.codec.ber import encoder +from pyasn1.type.tag import TagSet + +__all__ = ["Encoder", "encode"] + +class BooleanEncoder(encoder.IntegerEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class RealEncoder(encoder.RealEncoder): ... + +class TimeEncoderMixIn: + Z_CHAR: ClassVar[int] + PLUS_CHAR: ClassVar[int] + MINUS_CHAR: ClassVar[int] + COMMA_CHAR: ClassVar[int] + DOT_CHAR: ClassVar[int] + ZERO_CHAR: ClassVar[int] + MIN_LENGTH: ClassVar[int] + MAX_LENGTH: ClassVar[int] + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class GeneralizedTimeEncoder(TimeEncoderMixIn, encoder.OctetStringEncoder): ... +class UTCTimeEncoder(TimeEncoderMixIn, encoder.OctetStringEncoder): ... + +class SetOfEncoder(encoder.SequenceOfEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceOfEncoder(encoder.SequenceOfEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SetEncoder(encoder.SequenceEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceEncoder(encoder.SequenceEncoder): + omitEmptyOptionals: bool + +TAG_MAP: dict[TagSet, encoder.AbstractItemEncoder] +TYPE_MAP: dict[int, encoder.AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder(encoder.SingleItemEncoder): + fixedDefLengthMode: bool + fixedChunkSize: int + + TAG_MAP: dict[TagSet, encoder.AbstractItemEncoder] + TYPE_MAP: dict[int, encoder.AbstractItemEncoder] + +class Encoder(encoder.Encoder): + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + +encode: Encoder diff --git a/stubs/pyasn1/pyasn1/codec/der/__init__.pyi b/stubs/pyasn1/pyasn1/codec/der/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/der/decoder.pyi b/stubs/pyasn1/pyasn1/codec/der/decoder.pyi new file mode 100644 index 000000000000..042470f21b68 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/der/decoder.pyi @@ -0,0 +1,33 @@ +from pyasn1.codec.ber.decoder import AbstractPayloadDecoder +from pyasn1.codec.cer import decoder +from pyasn1.type.tag import TagSet + +__all__ = ["decode", "StreamingDecoder"] + +class BitStringPayloadDecoder(decoder.BitStringPayloadDecoder): + supportConstructedForm: bool + +class OctetStringPayloadDecoder(decoder.OctetStringPayloadDecoder): + supportConstructedForm: bool + +RealPayloadDecoder = decoder.RealPayloadDecoder + +TAG_MAP: dict[TagSet, AbstractPayloadDecoder] +TYPE_MAP: dict[int, AbstractPayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder(decoder.SingleItemDecoder): + TAG_MAP: dict[TagSet, AbstractPayloadDecoder] + TYPE_MAP: dict[int, AbstractPayloadDecoder] + + supportIndefLength: bool + +class StreamingDecoder(decoder.StreamingDecoder): + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + +class Decoder(decoder.Decoder): + STREAMING_DECODER: type[StreamingDecoder] + +decode: Decoder diff --git a/stubs/pyasn1/pyasn1/codec/der/encoder.pyi b/stubs/pyasn1/pyasn1/codec/der/encoder.pyi new file mode 100644 index 000000000000..3b1b5a4a6d9e --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/der/encoder.pyi @@ -0,0 +1,25 @@ +from pyasn1.codec.ber.encoder import AbstractItemEncoder +from pyasn1.codec.cer import encoder +from pyasn1.type.tag import TagSet + +__all__ = ["Encoder", "encode"] + +class SetEncoder(encoder.SetEncoder): ... + +TAG_MAP: dict[TagSet, AbstractItemEncoder] +TYPE_MAP: dict[int, AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder(encoder.SingleItemEncoder): + fixedDefLengthMode: bool + fixedChunkSize: int + + TAG_MAP: dict[TagSet, AbstractItemEncoder] + TYPE_MAP: dict[int, AbstractItemEncoder] + +class Encoder(encoder.Encoder): + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + +encode: Encoder diff --git a/stubs/pyasn1/pyasn1/codec/native/__init__.pyi b/stubs/pyasn1/pyasn1/codec/native/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/native/decoder.pyi b/stubs/pyasn1/pyasn1/codec/native/decoder.pyi new file mode 100644 index 000000000000..ecc906bf43b8 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/native/decoder.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable + +from pyasn1.type.tag import TagSet + +__all__ = ["decode"] + +class AbstractScalarPayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Unused = None, **options): ... + +class BitStringPayloadDecoder(AbstractScalarPayloadDecoder): + def __call__(self, pyObject, asn1Spec, decodeFun: Unused = None, **options): ... + +class SequenceOrSetPayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Callable[..., Incomplete] | None = None, **options): ... + +class SequenceOfOrSetOfPayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Callable[..., Incomplete] | None = None, **options): ... + +class ChoicePayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Callable[..., Incomplete] | None = None, **options): ... + +TAG_MAP: dict[TagSet, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] +TYPE_MAP: dict[int, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder: + TAG_MAP: dict[TagSet, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] + TYPE_MAP: dict[int, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] + + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__(self, pyObject, asn1Spec, **options): ... + +class Decoder: + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + + def __init__(self, *, tagMap=..., typeMap=..., **options: Unused) -> None: ... + def __call__(self, pyObject, asn1Spec=None, **kwargs): ... + +decode: Decoder diff --git a/stubs/pyasn1/pyasn1/codec/native/encoder.pyi b/stubs/pyasn1/pyasn1/codec/native/encoder.pyi new file mode 100644 index 000000000000..83abcc3b4a78 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/native/encoder.pyi @@ -0,0 +1,71 @@ +from _typeshed import Unused +from abc import abstractmethod +from collections import OrderedDict + +from pyasn1.type.tag import TagSet + +__all__ = ["encode"] + +class AbstractItemEncoder: + @abstractmethod + def encode(self, value, encodeFun, **options) -> None: ... + +class BooleanEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class IntegerEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class BitStringEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class OctetStringEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class TextStringEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class NullEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options) -> None: ... + +class ObjectIdentifierEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class RealEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class SetEncoder(AbstractItemEncoder): + protoDict = dict + def encode(self, value, encodeFun, **options): ... + +class SequenceEncoder(SetEncoder): + protoDict = OrderedDict + +class SequenceOfEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class ChoiceEncoder(SequenceEncoder): ... + +class AnyEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +TAG_MAP: dict[TagSet, AbstractItemEncoder] +TYPE_MAP: dict[int, AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder: + TAG_MAP: dict[TagSet, AbstractItemEncoder] + TYPE_MAP: dict[int, AbstractItemEncoder] + + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__(self, value, **options): ... + +class Encoder: + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + + def __init__(self, *, tagMap=..., typeMap=..., **options: Unused): ... + def __call__(self, pyObject, asn1Spec=None, **options): ... + +encode: SingleItemEncoder diff --git a/stubs/pyasn1/pyasn1/codec/streaming.pyi b/stubs/pyasn1/pyasn1/codec/streaming.pyi new file mode 100644 index 000000000000..b9ff83bec767 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/streaming.pyi @@ -0,0 +1,21 @@ +import io +from _typeshed import Incomplete +from collections.abc import Generator + +from pyasn1 import error as error +from pyasn1.type import univ as univ + +class CachingStreamWrapper(io.IOBase): + def __init__(self, raw) -> None: ... + def peek(self, n): ... + def seekable(self): ... + def seek(self, n: int = -1, whence=0): ... + def read(self, n: int = -1): ... + @property + def markedPosition(self): ... + def tell(self): ... + +def asSeekableStream(substrate): ... +def isEndOfStream(substrate) -> Generator[Incomplete]: ... +def peekIntoStream(substrate, size: int = -1) -> Generator[Incomplete]: ... +def readFromStream(substrate, size: int = -1, context=None) -> Generator[Incomplete]: ... diff --git a/stubs/pyasn1/pyasn1/compat/__init__.pyi b/stubs/pyasn1/pyasn1/compat/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/compat/integer.pyi b/stubs/pyasn1/pyasn1/compat/integer.pyi new file mode 100644 index 000000000000..ecc0e4208a9a --- /dev/null +++ b/stubs/pyasn1/pyasn1/compat/integer.pyi @@ -0,0 +1 @@ +def to_bytes(value: int, signed: bool = False, length: int = 0) -> bytes: ... diff --git a/stubs/pyasn1/pyasn1/debug.pyi b/stubs/pyasn1/pyasn1/debug.pyi new file mode 100644 index 000000000000..b0060f42bcb4 --- /dev/null +++ b/stubs/pyasn1/pyasn1/debug.pyi @@ -0,0 +1,28 @@ +import logging +from typing import TextIO + +__all__ = ["Debug", "setLogger", "hexdump"] + +class Printer: + def __init__( + self, + logger: logging.Logger | None = None, + handler: logging.StreamHandler[TextIO] | None = None, + formatter: logging.Formatter | None = None, + ) -> None: ... + def __call__(self, msg) -> None: ... + +class Debug: + defaultPrinter: Printer + def __init__(self, *flags, **options) -> None: ... + def __call__(self, msg) -> None: ... + def __and__(self, flag): ... + def __rand__(self, flag): ... + +def setLogger(userLogger) -> None: ... +def hexdump(octets): ... + +class Scope: + def __init__(self) -> None: ... + def push(self, token) -> None: ... + def pop(self): ... diff --git a/stubs/pyasn1/pyasn1/error.pyi b/stubs/pyasn1/pyasn1/error.pyi new file mode 100644 index 000000000000..2625bb2cdc06 --- /dev/null +++ b/stubs/pyasn1/pyasn1/error.pyi @@ -0,0 +1,15 @@ +class PyAsn1Error(Exception): + def __init__(self, *args, **kwargs) -> None: ... + @property + def context(self): ... + +class ValueConstraintError(PyAsn1Error): ... +class SubstrateUnderrunError(PyAsn1Error): ... +class EndOfStreamError(SubstrateUnderrunError): ... +class UnsupportedSubstrateError(PyAsn1Error): ... + +class PyAsn1UnicodeError(PyAsn1Error, UnicodeError): + def __init__(self, message, unicode_error: UnicodeError | None = None) -> None: ... + +class PyAsn1UnicodeDecodeError(PyAsn1UnicodeError, UnicodeDecodeError): ... +class PyAsn1UnicodeEncodeError(PyAsn1UnicodeError, UnicodeEncodeError): ... diff --git a/stubs/pyasn1/pyasn1/type/__init__.pyi b/stubs/pyasn1/pyasn1/type/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/type/base.pyi b/stubs/pyasn1/pyasn1/type/base.pyi new file mode 100644 index 000000000000..0e2da760e4e4 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/base.pyi @@ -0,0 +1,151 @@ +from _typeshed import Incomplete, Unused +from typing import final, type_check_only +from typing_extensions import Never + +from pyasn1.type import constraint, namedtype +from pyasn1.type.tag import TagSet + +__all__ = ["Asn1Item", "Asn1Type", "SimpleAsn1Type", "ConstructedAsn1Type"] + +class Asn1Item: + @classmethod + def getTypeId(cls, increment: int = 1): ... + +class Asn1Type(Asn1Item): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int | None + def __init__(self, **kwargs) -> None: ... + def __setattr__(self, name, value) -> None: ... + @property + def readOnly(self): ... + @property + def effectiveTagSet(self): ... + @property + def tagMap(self): ... + def isSameTypeWith(self, other, matchTags: bool = True, matchConstraints: bool = True): ... + def isSuperTypeOf(self, other, matchTags: bool = True, matchConstraints: bool = True): ... + @staticmethod + def isNoValue(*values): ... + def prettyPrint(self, scope: int = 0) -> None: ... + def getTagSet(self): ... + def getEffectiveTagSet(self): ... + def getTagMap(self): ... + def getSubtypeSpec(self): ... + def hasValue(self): ... + +Asn1ItemBase = Asn1Type + +@final +class NoValue: + skipMethods: set[str] + def __new__(cls): ... + def __getattr__(self, attr) -> None: ... + # def __new__..getPlug..plug + @type_check_only + def plug(self, *args: Unused, **kw: Unused) -> Never: ... + # Magic methods assigned dynamically, priority from right to left: plug < str < int < list < dict + __abs__ = int.__abs__ + __add__ = list.__add__ + __and__ = int.__and__ + __bool__ = int.__bool__ + __ceil__ = int.__ceil__ + __class_getitem__ = plug + __contains__ = dict.__contains__ + __delitem__ = dict.__delitem__ + __dir__ = plug + __divmod__ = int.__divmod__ + __float__ = int.__float__ + __floor__ = int.__floor__ + __floordiv__ = int.__floordiv__ + __ge__ = list.__ge__ + __getitem__ = dict.__getitem__ + __gt__ = list.__gt__ + __iadd__ = list.__iadd__ + __imul__ = list.__imul__ + __index__ = int.__index__ + # self instead of cls + __init_subclass__ = plug # pyright: ignore[reportAssignmentType] + __int__ = int.__int__ + __invert__ = int.__invert__ + __ior__ = plug + __iter__ = dict.__iter__ + __le__ = list.__le__ + __len__ = dict.__len__ + __lshift__ = int.__lshift__ + __lt__ = list.__lt__ + __mod__ = int.__mod__ + __mul__ = list.__mul__ + __neg__ = int.__neg__ + __or__ = int.__or__ + __pos__ = int.__pos__ + __pow__ = int.__pow__ + __radd__ = int.__radd__ + __rand__ = int.__rand__ + __rdivmod__ = int.__rdivmod__ + __reversed__ = list.__reversed__ + __rfloordiv__ = int.__rfloordiv__ + __rlshift__ = int.__rlshift__ + __rmod__ = int.__rmod__ + __rmul__ = list.__rmul__ + __ror__ = int.__ror__ + __round__ = int.__round__ + __rpow__ = int.__rpow__ + __rrshift__ = int.__rrshift__ + __rshift__ = int.__rshift__ + __rsub__ = int.__rsub__ + __rtruediv__ = int.__rtruediv__ + __rxor__ = int.__rxor__ + __setitem__ = list.__setitem__ + __str__ = plug + __sub__ = int.__sub__ + __truediv__ = int.__truediv__ + __trunc__ = int.__trunc__ + __xor__ = int.__xor__ + +class SimpleAsn1Type(Asn1Type): + defaultValue: Incomplete | NoValue + def __init__(self, value=..., **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + def __hash__(self): ... + @property + def isValue(self): ... + def clone(self, value=..., **kwargs): ... + def subtype(self, value=..., **kwargs): ... + def prettyIn(self, value): ... + def prettyOut(self, value): ... + def prettyPrint(self, scope: int = 0): ... + def prettyPrintType(self, scope: int = 0): ... + +AbstractSimpleAsn1Item = SimpleAsn1Type + +class ConstructedAsn1Type(Asn1Type): + strictConstraints: bool + componentType: namedtype.NamedTypes | Asn1Type | None + sizeSpec: constraint.ConstraintsIntersection + def __init__(self, **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + @property + def components(self) -> None: ... + def clone(self, **kwargs): ... + def subtype(self, **kwargs): ... + def getComponentByPosition(self, idx) -> None: ... + def setComponentByPosition(self, idx, value, verifyConstraints: bool = True) -> None: ... + def setComponents(self, *args, **kwargs): ... + def setDefaultComponents(self) -> None: ... + def getComponentType(self): ... + def verifySizeSpec(self) -> None: ... + +AbstractConstructedAsn1Item = ConstructedAsn1Type diff --git a/stubs/pyasn1/pyasn1/type/char.pyi b/stubs/pyasn1/pyasn1/type/char.pyi new file mode 100644 index 000000000000..8791c07abcfb --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/char.pyi @@ -0,0 +1,88 @@ +from pyasn1.type import univ +from pyasn1.type.tag import TagSet + +__all__ = [ + "NumericString", + "PrintableString", + "TeletexString", + "T61String", + "VideotexString", + "IA5String", + "GraphicString", + "VisibleString", + "ISO646String", + "GeneralString", + "UniversalString", + "BMPString", + "UTF8String", +] + +class AbstractCharacterString(univ.OctetString): + def __bytes__(self) -> bytes: ... + def prettyIn(self, value): ... + def asOctets(self, padding: bool = True): ... + def asNumbers(self, padding: bool = True): ... + def prettyOut(self, value): ... + def prettyPrint(self, scope: int = 0): ... + def __reversed__(self): ... + +class NumericString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class PrintableString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class TeletexString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class T61String(TeletexString): + typeId: int + +class VideotexString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class IA5String(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class GraphicString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class VisibleString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class ISO646String(VisibleString): + typeId: int + +class GeneralString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class UniversalString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class BMPString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class UTF8String(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int diff --git a/stubs/pyasn1/pyasn1/type/constraint.pyi b/stubs/pyasn1/pyasn1/type/constraint.pyi new file mode 100644 index 000000000000..df8d2c55806b --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/constraint.pyi @@ -0,0 +1,52 @@ +__all__ = [ + "SingleValueConstraint", + "ContainedSubtypeConstraint", + "ValueRangeConstraint", + "ValueSizeConstraint", + "PermittedAlphabetConstraint", + "InnerTypeConstraint", + "ConstraintsExclusion", + "ConstraintsIntersection", + "ConstraintsUnion", +] + +class AbstractConstraint: + def __init__(self, *values) -> None: ... + def __call__(self, value, idx: int | None = None) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + def __hash__(self): ... + def getValueMap(self): ... + def isSuperTypeOf(self, otherConstraint): ... + def isSubTypeOf(self, otherConstraint): ... + +class SingleValueConstraint(AbstractConstraint): + def __contains__(self, item) -> bool: ... + def __iter__(self): ... + def __add__(self, constraint): ... + def __sub__(self, constraint): ... + +class ContainedSubtypeConstraint(AbstractConstraint): ... +class ValueRangeConstraint(AbstractConstraint): ... +class ValueSizeConstraint(ValueRangeConstraint): ... +class PermittedAlphabetConstraint(SingleValueConstraint): ... +class ComponentPresentConstraint(AbstractConstraint): ... +class ComponentAbsentConstraint(AbstractConstraint): ... +class WithComponentsConstraint(AbstractConstraint): ... +class InnerTypeConstraint(AbstractConstraint): ... +class ConstraintsExclusion(AbstractConstraint): ... + +class AbstractConstraintSet(AbstractConstraint): + def __getitem__(self, idx): ... + def __iter__(self): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __len__(self) -> int: ... + +class ConstraintsIntersection(AbstractConstraintSet): ... +class ConstraintsUnion(AbstractConstraintSet): ... diff --git a/stubs/pyasn1/pyasn1/type/error.pyi b/stubs/pyasn1/pyasn1/type/error.pyi new file mode 100644 index 000000000000..b2562205991b --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/error.pyi @@ -0,0 +1,3 @@ +from pyasn1.error import PyAsn1Error + +class ValueConstraintError(PyAsn1Error): ... diff --git a/stubs/pyasn1/pyasn1/type/namedtype.pyi b/stubs/pyasn1/pyasn1/type/namedtype.pyi new file mode 100644 index 000000000000..c8d12b5de381 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/namedtype.pyi @@ -0,0 +1,73 @@ +__all__ = ["NamedType", "OptionalNamedType", "DefaultedNamedType", "NamedTypes"] + +class NamedType: + isOptional: bool + isDefaulted: bool + def __init__(self, name, asn1Object, openType: type | None = None) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, idx): ... + def __iter__(self): ... + @property + def name(self): ... + @property + def asn1Object(self): ... + @property + def openType(self): ... + def getName(self): ... + def getType(self): ... + +class OptionalNamedType(NamedType): + isOptional: bool + +class DefaultedNamedType(NamedType): + isDefaulted: bool + +class NamedTypes: + def __init__(self, *namedTypes, **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, idx): ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def values(self): ... + def keys(self): ... + def items(self): ... + def clone(self): ... + + class PostponedError: + def __init__(self, errorMsg) -> None: ... + def __getitem__(self, item) -> None: ... + + def getTypeByPosition(self, idx): ... + def getPositionByType(self, tagSet): ... + def getNameByPosition(self, idx): ... + def getPositionByName(self, name): ... + def getTagMapNearPosition(self, idx): ... + def getPositionNearType(self, tagSet, idx): ... + @property + def minTagSet(self): ... + @property + def tagMap(self): ... + @property + def tagMapUnique(self): ... + @property + def hasOptionalOrDefault(self): ... + @property + def hasOpenTypes(self): ... + @property + def namedTypes(self): ... + @property + def requiredComponents(self): ... diff --git a/stubs/pyasn1/pyasn1/type/namedval.pyi b/stubs/pyasn1/pyasn1/type/namedval.pyi new file mode 100644 index 000000000000..1f638b960f6d --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/namedval.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +__all__ = ["NamedValues"] + +class NamedValues: + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, key): ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def values(self): ... + def keys(self): ... + def items(self) -> Generator[Incomplete]: ... + def __add__(self, namedValues): ... + def clone(self, *args, **kwargs): ... + def getName(self, value): ... + def getValue(self, name): ... + def getValues(self, *names): ... diff --git a/stubs/pyasn1/pyasn1/type/opentype.pyi b/stubs/pyasn1/pyasn1/type/opentype.pyi new file mode 100644 index 000000000000..8317aa0dbf9c --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/opentype.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from pyasn1.type.base import Asn1Type + +__all__ = ["OpenType"] + +class OpenType: + def __init__(self, name, typeMap: Mapping[Incomplete, Asn1Type] | None = None) -> None: ... + @property + def name(self): ... + def values(self): ... + def keys(self): ... + def items(self): ... + def __contains__(self, key) -> bool: ... + def __getitem__(self, key): ... + def __iter__(self): ... diff --git a/stubs/pyasn1/pyasn1/type/tag.pyi b/stubs/pyasn1/pyasn1/type/tag.pyi new file mode 100644 index 000000000000..15d26de05087 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/tag.pyi @@ -0,0 +1,64 @@ +__all__ = [ + "tagClassUniversal", + "tagClassApplication", + "tagClassContext", + "tagClassPrivate", + "tagFormatSimple", + "tagFormatConstructed", + "tagCategoryImplicit", + "tagCategoryExplicit", + "tagCategoryUntagged", + "Tag", + "TagSet", +] +tagClassUniversal: int +tagClassApplication: int +tagClassContext: int +tagClassPrivate: int +tagFormatSimple: int +tagFormatConstructed: int +tagCategoryImplicit: int +tagCategoryExplicit: int +tagCategoryUntagged: int + +class Tag: + def __init__(self, tagClass, tagFormat, tagId) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, idx): ... + def __iter__(self): ... + def __and__(self, otherTag): ... + def __or__(self, otherTag): ... + @property + def tagClass(self): ... + @property + def tagFormat(self): ... + @property + def tagId(self): ... + +class TagSet: + def __init__(self, baseTag=(), *superTags) -> None: ... + def __add__(self, superTag): ... + def __radd__(self, superTag): ... + def __getitem__(self, i): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __len__(self) -> int: ... + @property + def baseTag(self): ... + @property + def superTags(self): ... + def tagExplicitly(self, superTag): ... + def tagImplicitly(self, superTag): ... + def isSuperTagSetOf(self, tagSet): ... + def getBaseTag(self): ... diff --git a/stubs/pyasn1/pyasn1/type/tagmap.pyi b/stubs/pyasn1/pyasn1/type/tagmap.pyi new file mode 100644 index 000000000000..b842e0a4a5c1 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/tagmap.pyi @@ -0,0 +1,25 @@ +from collections.abc import Container, Mapping + +from pyasn1.type.base import Asn1Type + +__all__ = ["TagMap"] + +class TagMap: + def __init__( + self, + presentTypes: Mapping[TagMap, Asn1Type] | None = None, + skipTypes: Container[TagMap] | None = None, + defaultType: Asn1Type | None = None, + ) -> None: ... + def __contains__(self, tagSet) -> bool: ... + def __getitem__(self, tagSet): ... + def __iter__(self): ... + @property + def presentTypes(self): ... + @property + def skipTypes(self): ... + @property + def defaultType(self): ... + def getPosMap(self): ... + def getNegMap(self): ... + def getDef(self): ... diff --git a/stubs/pyasn1/pyasn1/type/univ.pyi b/stubs/pyasn1/pyasn1/type/univ.pyi new file mode 100644 index 000000000000..ad2a65391381 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/univ.pyi @@ -0,0 +1,398 @@ +from _typeshed import ConvertibleToInt, Incomplete, SupportsRichComparison +from collections.abc import Callable, Generator +from typing_extensions import Self + +from pyasn1.type import base, constraint, namedtype, namedval +from pyasn1.type.tag import TagSet + +__all__ = [ + "Integer", + "Boolean", + "BitString", + "OctetString", + "Null", + "ObjectIdentifier", + "Real", + "Enumerated", + "SequenceOfAndSetOfBase", + "SequenceOf", + "SetOf", + "SequenceAndSetBase", + "Sequence", + "Set", + "Choice", + "Any", + "NoValue", + "noValue", +] + +NoValue = base.NoValue +noValue: NoValue + +class Integer(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + namedValues: namedval.NamedValues + typeId: int + def __init__(self, value=..., **kwargs) -> None: ... + def __and__(self, value): ... + def __rand__(self, value): ... + def __or__(self, value): ... + def __ror__(self, value): ... + def __xor__(self, value): ... + def __rxor__(self, value): ... + def __lshift__(self, value): ... + def __rshift__(self, value): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __sub__(self, value): ... + def __rsub__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __mod__(self, value): ... + def __rmod__(self, value): ... + # Accepts everything builtins.pow does + def __pow__(self, value: complex, modulo: int | None = None) -> Self: ... + def __rpow__(self, value): ... + def __floordiv__(self, value): ... + def __rfloordiv__(self, value): ... + def __truediv__(self, value): ... + def __rtruediv__(self, value): ... + def __divmod__(self, value): ... + def __rdivmod__(self, value): ... + __hash__ = base.SimpleAsn1Type.__hash__ + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self): ... + def __index__(self) -> int: ... + def __pos__(self): ... + def __neg__(self): ... + def __invert__(self): ... + def __round__(self, n: int = 0): ... + def __floor__(self): ... + def __ceil__(self): ... + def __trunc__(self): ... + def __lt__(self, value): ... + def __le__(self, value): ... + def __eq__(self, value): ... + def __ne__(self, value): ... + def __gt__(self, value): ... + def __ge__(self, value): ... + def prettyIn(self, value): ... + def prettyOut(self, value): ... + def getNamedValues(self): ... + +class Boolean(Integer): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + namedValues: namedval.NamedValues + typeId: int + +class SizedInteger(int): + bitLength: int | None + leadingZeroBits: int | None + def setBitLength(self, bitLength): ... + def __len__(self) -> int: ... + +class BitString(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + namedValues: namedval.NamedValues + typeId: int + defaultBinValue: str | base.NoValue + defaultHexValue: str | base.NoValue + def __init__(self, value=..., **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __len__(self) -> int: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __reversed__(self): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __lshift__(self, count): ... + def __rshift__(self, count): ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def asNumbers(self): ... + def asOctets(self): ... + def asInteger(self): ... + def asBinary(self): ... + @classmethod + def fromHexString(cls, value, internalFormat: bool = False, prepend: ConvertibleToInt | None = None): ... + @classmethod + def fromBinaryString(cls, value, internalFormat: bool = False, prepend: ConvertibleToInt | None = None): ... + @classmethod + def fromOctetString(cls, value, internalFormat: bool = False, prepend: ConvertibleToInt | None = None, padding: int = 0): ... + def prettyIn(self, value): ... + +class OctetString(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + defaultBinValue: str | base.NoValue + defaultHexValue: str | base.NoValue + encoding: str + def __init__(self, value=..., **kwargs) -> None: ... + def prettyIn(self, value): ... + def __bytes__(self) -> bytes: ... + def asOctets(self): ... + def asNumbers(self): ... + def prettyOut(self, value): ... + def prettyPrint(self, scope: int = 0): ... + @staticmethod + def fromBinaryString(value): ... + @staticmethod + def fromHexString(value): ... + def __len__(self) -> int: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __contains__(self, value) -> bool: ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __reversed__(self): ... + +class Null(OctetString): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def prettyIn(self, value): ... + +class ObjectIdentifier(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def __add__(self, other): ... + def __radd__(self, other): ... + def asTuple(self): ... + def __len__(self) -> int: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __contains__(self, value) -> bool: ... + def index(self, suboid): ... + def isPrefixOf(self, other): ... + def prettyIn(self, value): ... + def prettyOut(self, value): ... + +class Real(base.SimpleAsn1Type): + binEncBase: int | None + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def prettyIn(self, value): ... + def prettyPrint(self, scope: int = 0): ... + @property + def isPlusInf(self): ... + @property + def isMinusInf(self): ... + @property + def isInf(self): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __sub__(self, value): ... + def __rsub__(self, value): ... + def __mod__(self, value): ... + def __rmod__(self, value): ... + # Accepts everything builtins.pow with a float base does + def __pow__(self, value: complex, modulo: int | None = None) -> Self: ... + def __rpow__(self, value): ... + def __truediv__(self, value): ... + def __rtruediv__(self, value): ... + def __divmod__(self, value): ... + def __rdivmod__(self, value): ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self): ... + def __pos__(self): ... + def __neg__(self): ... + def __round__(self, n: int = 0): ... + def __floor__(self): ... + def __ceil__(self): ... + def __trunc__(self): ... + def __lt__(self, value): ... + def __le__(self, value): ... + def __eq__(self, value): ... + def __ne__(self, value): ... + def __gt__(self, value): ... + def __ge__(self, value): ... + def __bool__(self) -> bool: ... + __hash__ = base.SimpleAsn1Type.__hash__ + def __getitem__(self, idx): ... + def isPlusInfinity(self): ... + def isMinusInfinity(self): ... + def isInfinity(self): ... + +class Enumerated(Integer): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + namedValues: namedval.NamedValues + +class SequenceOfAndSetOfBase(base.ConstructedAsn1Type): + componentType: base.Asn1Type | None + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + def __init__( + self, + *args, + componentType: base.Asn1Type | None = ..., + tagSet: TagSet = ..., + subtypeSpec: constraint.ConstraintsIntersection = ..., + ) -> None: ... + def __getitem__(self, idx): ... + def __setitem__(self, idx, value) -> None: ... + def append(self, value) -> None: ... + def count(self, value): ... + def extend(self, values) -> None: ... + def index(self, value, start: int = 0, stop: int | None = None): ... + def reverse(self) -> None: ... + def sort(self, key: Callable[[Incomplete], SupportsRichComparison] | None = None, reverse: bool = False) -> None: ... + def __len__(self) -> int: ... + def __iter__(self): ... + def getComponentByPosition(self, idx, default=..., instantiate: bool = True): ... + def setComponentByPosition( + self, idx, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + @property + def componentTagMap(self): ... + @property + def components(self): ... + def clear(self): ... + def reset(self): ... + def prettyPrint(self, scope: int = 0): ... + def prettyPrintType(self, scope: int = 0): ... + @property + def isValue(self): ... + @property + def isInconsistent(self): ... + +class SequenceOf(SequenceOfAndSetOfBase): + typeId: int + +class SetOf(SequenceOfAndSetOfBase): + typeId: int + +class SequenceAndSetBase(base.ConstructedAsn1Type): + componentType: namedtype.NamedTypes + + class DynamicNames: + def __init__(self) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, item) -> bool: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def getNameByPosition(self, idx): ... + def getPositionByName(self, name): ... + def addField(self, idx) -> None: ... + + def __init__(self, **kwargs) -> None: ... + def __getitem__(self, idx): ... + def __setitem__(self, idx, value) -> None: ... + def __contains__(self, key) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self): ... + def values(self) -> Generator[Incomplete]: ... + def keys(self): ... + def items(self) -> Generator[Incomplete]: ... + def update(self, *iterValue, **mappingValue) -> None: ... + def clear(self): ... + def reset(self): ... + @property + def components(self): ... + def getComponentByName(self, name, default=..., instantiate: bool = True): ... + def setComponentByName( + self, name, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + def getComponentByPosition(self, idx, default=..., instantiate: bool = True): ... + def setComponentByPosition( + self, idx, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + @property + def isValue(self): ... + @property + def isInconsistent(self): ... + def prettyPrint(self, scope: int = 0): ... + def prettyPrintType(self, scope: int = 0): ... + def setDefaultComponents(self): ... + def getComponentType(self): ... + def getNameByPosition(self, idx): ... + +class Sequence(SequenceAndSetBase): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + componentType: namedtype.NamedTypes + typeId: int + def getComponentTagMapNearPosition(self, idx): ... + def getComponentPositionNearType(self, tagSet, idx): ... + +class Set(SequenceAndSetBase): + tagSet: TagSet + componentType: namedtype.NamedTypes + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def getComponent(self, innerFlag: bool = False): ... + def getComponentByType(self, tagSet, default=..., instantiate: bool = True, innerFlag: bool = False): ... + def setComponentByType( + self, + tagSet, + value=..., + verifyConstraints: bool = True, + matchTags: bool = True, + matchConstraints: bool = True, + innerFlag: bool = False, + ): ... + @property + def componentTagMap(self): ... + +class Choice(Set): + tagSet: TagSet + componentType: namedtype.NamedTypes + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def values(self) -> Generator[Incomplete]: ... + def keys(self) -> Generator[Incomplete]: ... + def items(self) -> Generator[Incomplete]: ... + def checkConsistency(self) -> None: ... + def getComponentByPosition(self, idx, default=..., instantiate: bool = True): ... + def setComponentByPosition( + self, idx, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + @property + def effectiveTagSet(self): ... + @property + def tagMap(self): ... + def getComponent(self, innerFlag: bool = False): ... + def getName(self, innerFlag: bool = False): ... + @property + def isValue(self): ... + def clear(self): ... + def getMinTagSet(self): ... + +class Any(OctetString): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + @property + def tagMap(self): ... diff --git a/stubs/pyasn1/pyasn1/type/useful.pyi b/stubs/pyasn1/pyasn1/type/useful.pyi new file mode 100644 index 000000000000..559d7f0847d0 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/useful.pyi @@ -0,0 +1,31 @@ +import datetime + +from pyasn1.type import char +from pyasn1.type.tag import TagSet + +__all__ = ["ObjectDescriptor", "GeneralizedTime", "UTCTime"] + +class ObjectDescriptor(char.GraphicString): + tagSet: TagSet + typeId: int + +class TimeMixIn: + class FixedOffset(datetime.tzinfo): + def __init__(self, offset: int = 0, name: str = "UTC") -> None: ... + def utcoffset(self, dt): ... + def tzname(self, dt): ... + def dst(self, dt): ... + + UTC: FixedOffset + @property + def asDateTime(self): ... + @classmethod + def fromDateTime(cls, dt): ... + +class GeneralizedTime(char.VisibleString, TimeMixIn): + tagSet: TagSet + typeId: int + +class UTCTime(char.VisibleString, TimeMixIn): + tagSet: TagSet + typeId: int diff --git a/stubs/pyaudio/METADATA.toml b/stubs/pyaudio/METADATA.toml index 6928f6e1901c..29a84c09f459 100644 --- a/stubs/pyaudio/METADATA.toml +++ b/stubs/pyaudio/METADATA.toml @@ -1,2 +1,9 @@ version = "0.2.*" -python2 = true +# There is no web portal for the source, this is the official source link: +# upstream-repository = "https://people.csail.mit.edu/hubert/pyaudio/#sources" + +[tool.stubtest] +# linux and win32 are equivalent +ci-platforms = ["darwin", "linux"] +apt-dependencies = ["portaudio19-dev"] +brew-dependencies = ["portaudio"] diff --git a/stubs/pyaudio/pyaudio.pyi b/stubs/pyaudio/pyaudio.pyi index 6849056b1d47..8df1043bb36b 100644 --- a/stubs/pyaudio/pyaudio.pyi +++ b/stubs/pyaudio/pyaudio.pyi @@ -1,76 +1,100 @@ -from typing import Callable, Mapping, Optional, Sequence, Tuple, Union -from typing_extensions import Final +import sys +from collections.abc import Callable, Mapping, Sequence +from typing import ClassVar, Final, TypeAlias -paFloat32: Final[int] = ... -paInt32: Final[int] = ... -paInt24: Final[int] = ... -paInt16: Final[int] = ... -paInt8: Final[int] = ... -paUInt8: Final[int] = ... -paCustomFormat: Final[int] = ... +__docformat__: str -paInDevelopment: Final[int] = ... -paDirectSound: Final[int] = ... -paMME: Final[int] = ... -paASIO: Final[int] = ... -paSoundManager: Final[int] = ... -paCoreAudio: Final[int] = ... -paOSS: Final[int] = ... -paALSA: Final[int] = ... -paAL: Final[int] = ... -paBeOS: Final[int] = ... -paWDMKS: Final[int] = ... -paJACK: Final[int] = ... -paWASAPI: Final[int] = ... -paNoDevice: Final[int] = ... +paFloat32: Final[int] +paInt32: Final[int] +paInt24: Final[int] +paInt16: Final[int] +paInt8: Final[int] +paUInt8: Final[int] +paCustomFormat: Final[int] -paNoError: Final[int] = ... -paNotInitialized: Final[int] = ... -paUnanticipatedHostError: Final[int] = ... -paInvalidChannelCount: Final[int] = ... -paInvalidSampleRate: Final[int] = ... -paInvalidDevice: Final[int] = ... -paInvalidFlag: Final[int] = ... -paSampleFormatNotSupported: Final[int] = ... -paBadIODeviceCombination: Final[int] = ... -paInsufficientMemory: Final[int] = ... -paBufferTooBig: Final[int] = ... -paBufferTooSmall: Final[int] = ... -paNullCallback: Final[int] = ... -paBadStreamPtr: Final[int] = ... -paTimedOut: Final[int] = ... -paInternalError: Final[int] = ... -paDeviceUnavailable: Final[int] = ... -paIncompatibleHostApiSpecificStreamInfo: Final[int] = ... -paStreamIsStopped: Final[int] = ... -paStreamIsNotStopped: Final[int] = ... -paInputOverflowed: Final[int] = ... -paOutputUnderflowed: Final[int] = ... -paHostApiNotFound: Final[int] = ... -paInvalidHostApi: Final[int] = ... -paCanNotReadFromACallbackStream: Final[int] = ... -paCanNotWriteToACallbackStream: Final[int] = ... -paCanNotReadFromAnOutputOnlyStream: Final[int] = ... -paCanNotWriteToAnInputOnlyStream: Final[int] = ... -paIncompatibleStreamHostApi: Final[int] = ... +paInDevelopment: Final[int] +paDirectSound: Final[int] +paMME: Final[int] +paASIO: Final[int] +paSoundManager: Final[int] +paCoreAudio: Final[int] +paOSS: Final[int] +paALSA: Final[int] +paAL: Final[int] +paBeOS: Final[int] +paWDMKS: Final[int] +paJACK: Final[int] +paWASAPI: Final[int] +paNoDevice: Final[int] -paContinue: Final[int] = ... -paComplete: Final[int] = ... -paAbort: Final[int] = ... +paNoError: Final[int] +paNotInitialized: Final[int] +paUnanticipatedHostError: Final[int] +paInvalidChannelCount: Final[int] +paInvalidSampleRate: Final[int] +paInvalidDevice: Final[int] +paInvalidFlag: Final[int] +paSampleFormatNotSupported: Final[int] +paBadIODeviceCombination: Final[int] +paInsufficientMemory: Final[int] +paBufferTooBig: Final[int] +paBufferTooSmall: Final[int] +paNullCallback: Final[int] +paBadStreamPtr: Final[int] +paTimedOut: Final[int] +paInternalError: Final[int] +paDeviceUnavailable: Final[int] +paIncompatibleHostApiSpecificStreamInfo: Final[int] +paStreamIsStopped: Final[int] +paStreamIsNotStopped: Final[int] +paInputOverflowed: Final[int] +paOutputUnderflowed: Final[int] +paHostApiNotFound: Final[int] +paInvalidHostApi: Final[int] +paCanNotReadFromACallbackStream: Final[int] +paCanNotWriteToACallbackStream: Final[int] +paCanNotReadFromAnOutputOnlyStream: Final[int] +paCanNotWriteToAnInputOnlyStream: Final[int] +paIncompatibleStreamHostApi: Final[int] -paInputUnderflow: Final[int] = ... -paInputOverflow: Final[int] = ... -paOutputUnderflow: Final[int] = ... -paOutputOverflow: Final[int] = ... -paPrimingOutput: Final[int] = ... +paContinue: Final[int] +paComplete: Final[int] +paAbort: Final[int] -paMacCoreStreamInfo: PaMacCoreStreamInfo +paInputUnderflow: Final[int] +paInputOverflow: Final[int] +paOutputUnderflow: Final[int] +paOutputOverflow: Final[int] +paPrimingOutput: Final[int] + +paFramesPerBufferUnspecified: Final[int] + +if sys.platform == "darwin": + class PaMacCoreStreamInfo: + paMacCoreChangeDeviceParameters: Final[int] + paMacCoreFailIfConversionRequired: Final[int] + paMacCoreConversionQualityMin: Final[int] + paMacCoreConversionQualityMedium: Final[int] + paMacCoreConversionQualityLow: Final[int] + paMacCoreConversionQualityHigh: Final[int] + paMacCoreConversionQualityMax: Final[int] + paMacCorePlayNice: Final[int] + paMacCorePro: Final[int] + paMacCoreMinimizeCPUButPlayNice: Final[int] + paMacCoreMinimizeCPU: Final[int] + def __init__(self, flags: int | None = ..., channel_map: _ChannelMap | None = ...) -> None: ... + def get_flags(self) -> int: ... + def get_channel_map(self) -> _ChannelMap | None: ... + + _PaMacCoreStreamInfo: TypeAlias = PaMacCoreStreamInfo +else: + _PaMacCoreStreamInfo: TypeAlias = None # Auxiliary types -_ChannelMap = Sequence[int] -_PaHostApiInfo = Mapping[str, Union[str, int]] -_PaDeviceInfo = Mapping[str, Union[str, int, float]] -_StreamCallback = Callable[[Optional[bytes], int, Mapping[str, float], int], Tuple[Optional[bytes], int]] +_ChannelMap: TypeAlias = Sequence[int] +_PaHostApiInfo: TypeAlias = Mapping[str, str | int] +_PaDeviceInfo: TypeAlias = Mapping[str, str | int | float] +_StreamCallback: TypeAlias = Callable[[bytes | None, int, Mapping[str, float], int], tuple[bytes | None, int]] def get_format_from_width(width: int, unsigned: bool = ...) -> int: ... def get_portaudio_version() -> int: ... @@ -90,8 +114,8 @@ class Stream: output_device_index: int | None = ..., frames_per_buffer: int = ..., start: bool = ..., - input_host_api_specific_stream_info: PaMacCoreStreamInfo | None = ..., - output_host_api_specific_stream_info: PaMacCoreStreamInfo | None = ..., + input_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., + output_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., stream_callback: _StreamCallback | None = ..., ) -> None: ... def close(self) -> None: ... @@ -108,9 +132,13 @@ class Stream: def stop_stream(self) -> None: ... def write(self, frames: bytes, num_frames: int | None = ..., exception_on_underflow: bool = ...) -> None: ... +# Use an alias to workaround pyright complaints about recursive definitions in the PyAudio class +_Stream = Stream + class PyAudio: + Stream: ClassVar[type[_Stream]] def __init__(self) -> None: ... - def close(self, stream: Stream) -> None: ... + def close(self, stream: _Stream) -> None: ... def get_default_host_api_info(self) -> _PaHostApiInfo: ... def get_default_input_device_info(self) -> _PaDeviceInfo: ... def get_default_output_device_info(self) -> _PaDeviceInfo: ... @@ -143,24 +171,8 @@ class PyAudio: output_device_index: int | None = ..., frames_per_buffer: int = ..., start: bool = ..., - input_host_api_specific_stream_info: PaMacCoreStreamInfo | None = ..., - output_host_api_specific_stream_info: PaMacCoreStreamInfo | None = ..., + input_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., + output_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., stream_callback: _StreamCallback | None = ..., - ) -> Stream: ... + ) -> _Stream: ... def terminate(self) -> None: ... - -class PaMacCoreStreamInfo: - paMacCoreChangeDeviceParameters: Final[int] = ... - paMacCoreFailIfConversionRequired: Final[int] = ... - paMacCoreConversionQualityMin: Final[int] = ... - paMacCoreConversionQualityMedium: Final[int] = ... - paMacCoreConversionQualityLow: Final[int] = ... - paMacCoreConversionQualityHigh: Final[int] = ... - paMacCoreConversionQualityMax: Final[int] = ... - paMacCorePlayNice: Final[int] = ... - paMacCorePro: Final[int] = ... - paMacCoreMinimizeCPUButPlayNice: Final[int] = ... - paMacCoreMinimizeCPU: Final[int] = ... - def __init__(self, flags: int | None = ..., channel_map: _ChannelMap | None = ...) -> None: ... - def get_flags(self) -> int: ... - def get_channel_map(self) -> _ChannelMap | None: ... diff --git a/stubs/pycocotools/METADATA.toml b/stubs/pycocotools/METADATA.toml new file mode 100644 index 000000000000..672320ca392c --- /dev/null +++ b/stubs/pycocotools/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.0.*" +upstream-repository = "https://github.com/ppwwyyxx/cocoapi" +dependencies = ["numpy>=2.0.0rc1"] diff --git a/stubs/pycocotools/pycocotools/__init__.pyi b/stubs/pycocotools/pycocotools/__init__.pyi new file mode 100644 index 000000000000..129b5a07c312 --- /dev/null +++ b/stubs/pycocotools/pycocotools/__init__.pyi @@ -0,0 +1,7 @@ +from typing import TypedDict, type_check_only + +# Unused in this module, but imported in multiple submodules. +@type_check_only +class _EncodedRLE(TypedDict): # noqa: Y049 + size: list[int] + counts: str | bytes diff --git a/stubs/pycocotools/pycocotools/coco.pyi b/stubs/pycocotools/pycocotools/coco.pyi new file mode 100644 index 000000000000..6e5af237bddb --- /dev/null +++ b/stubs/pycocotools/pycocotools/coco.pyi @@ -0,0 +1,96 @@ +from collections.abc import Collection, Sequence +from pathlib import Path +from typing import Generic, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +import numpy as np +import numpy.typing as npt + +from . import _EncodedRLE + +PYTHON_VERSION: int + +@type_check_only +class _Image(TypedDict): + id: int + width: int + height: int + file_name: str + +_TPolygonSegmentation: TypeAlias = list[list[float]] + +@type_check_only +class _RLE(TypedDict): + size: list[int] + counts: list[int] + +@type_check_only +class _Annotation(TypedDict): + id: int + image_id: int + category_id: int + segmentation: _TPolygonSegmentation | _RLE | _EncodedRLE + area: float + bbox: list[float] + iscrowd: int + +_TSeg = TypeVar("_TSeg", _TPolygonSegmentation, _RLE, _EncodedRLE) + +@type_check_only +class _AnnotationG(TypedDict, Generic[_TSeg]): + id: int + image_id: int + category_id: int + segmentation: _TSeg + area: float + bbox: list[float] + iscrowd: int + +@type_check_only +class _Category(TypedDict): + id: int + name: str + supercategory: str + +@type_check_only +class _Dataset(TypedDict): + images: list[_Image] + annotations: list[_Annotation] + categories: list[_Category] + +class COCO: + anns: dict[int, _Annotation] + dataset: _Dataset + cats: dict[int, _Category] + imgs: dict[int, _Image] + imgToAnns: dict[int, list[_Annotation]] + catToImgs: dict[int, list[int]] + def __init__(self, annotation_file: str | Path | None = None) -> None: ... + def createIndex(self) -> None: ... + def info(self) -> None: ... + def getAnnIds( + self, + imgIds: Collection[int] | int = [], + catIds: Collection[int] | int = [], + areaRng: Sequence[float] = [], + iscrowd: bool | None = None, + ) -> list[int]: ... + def getCatIds( + self, catNms: Collection[str] | str = [], supNms: Collection[str] | str = [], catIds: Collection[int] | int = [] + ) -> list[int]: ... + def getImgIds(self, imgIds: Collection[int] | int = [], catIds: list[int] | int = []) -> list[int]: ... + def loadAnns(self, ids: Collection[int] | int = []) -> list[_Annotation]: ... + def loadCats(self, ids: Collection[int] | int = []) -> list[_Category]: ... + def loadImgs(self, ids: Collection[int] | int = []) -> list[_Image]: ... + def showAnns(self, anns: Sequence[_Annotation], draw_bbox: bool = False) -> None: ... + def loadRes(self, resFile: str) -> COCO: ... + def download(self, tarDir: str | None = None, imgIds: Collection[int] = []) -> Literal[-1] | None: ... + def loadNumpyAnnotations(self, data: npt.NDArray[np.float64]) -> list[_Annotation]: ... + + @overload + def annToRLE(self, ann: _AnnotationG[_RLE]) -> _RLE: ... + @overload + def annToRLE(self, ann: _AnnotationG[_EncodedRLE]) -> _EncodedRLE: ... + @overload + def annToRLE(self, ann: _AnnotationG[_TPolygonSegmentation]) -> _EncodedRLE: ... + + def annToMask(self, ann: _Annotation) -> npt.NDArray[np.uint8]: ... diff --git a/stubs/pycocotools/pycocotools/cocoeval.pyi b/stubs/pycocotools/pycocotools/cocoeval.pyi new file mode 100644 index 000000000000..ab763578101a --- /dev/null +++ b/stubs/pycocotools/pycocotools/cocoeval.pyi @@ -0,0 +1,64 @@ +from typing import Literal, TypeAlias, TypedDict, type_check_only + +import numpy as np +import numpy.typing as npt + +from .coco import COCO + +_NDFloatArray: TypeAlias = npt.NDArray[np.float64] +_TIOU: TypeAlias = Literal["segm", "bbox", "keypoints"] + +@type_check_only +class _ImageEvaluationResult(TypedDict): + image_id: int + category_id: int + aRng: list[int] + maxDet: int + dtIds: list[int] + gtIds: list[int] + dtMatches: _NDFloatArray + gtMatches: _NDFloatArray + dtScores: list[float] + gtIgnore: _NDFloatArray + dtIgnore: _NDFloatArray + +@type_check_only +class _EvaluationResult(TypedDict): + params: Params + counts: list[int] + date: str + precision: _NDFloatArray + recall: _NDFloatArray + scores: _NDFloatArray + +class COCOeval: + cocoGt: COCO + cocoDt: COCO + evalImgs: list[_ImageEvaluationResult] + eval: _EvaluationResult + params: Params + stats: _NDFloatArray + ious: dict[tuple[int, int], list[float]] + def __init__(self, cocoGt: COCO | None = None, cocoDt: COCO | None = None, iouType: _TIOU = "segm") -> None: ... + def evaluate(self) -> None: ... + def computeIoU(self, imgId: int, catId: int) -> list[float]: ... + def computeOks(self, imgId: int, catId: int) -> _NDFloatArray: ... + def evaluateImg(self, imgId: int, catId: int, aRng: list[int], maxDet: int) -> _ImageEvaluationResult: ... + def accumulate(self, p: Params | None = None) -> None: ... + def summarize(self) -> None: ... + +class Params: + imgIds: list[int] + catIds: list[int] + iouThrs: _NDFloatArray + recThrs: _NDFloatArray + maxDets: list[int] + areaRng: list[list[float]] + areaRngLbl: list[str] + useCats: int + kpt_oks_sigmas: _NDFloatArray + iouType: _TIOU + useSegm: int | None + def __init__(self, iouType: _TIOU = "segm") -> None: ... + def setDetParams(self) -> None: ... + def setKpParams(self) -> None: ... diff --git a/stubs/pycocotools/pycocotools/mask.pyi b/stubs/pycocotools/pycocotools/mask.pyi new file mode 100644 index 000000000000..84e85c3bf215 --- /dev/null +++ b/stubs/pycocotools/pycocotools/mask.pyi @@ -0,0 +1,29 @@ +from typing import Any, TypeAlias, overload + +import numpy as np +import numpy.typing as npt + +from . import _EncodedRLE + +_NPUInt32: TypeAlias = np.uint32 +_NDArrayUInt8: TypeAlias = npt.NDArray[np.uint8] +_NDArrayUInt32: TypeAlias = npt.NDArray[np.uint32] +_NDArrayFloat64: TypeAlias = npt.NDArray[np.float64] + +def iou( + dt: _NDArrayUInt32 | list[float] | list[_EncodedRLE], + gt: _NDArrayUInt32 | list[float] | list[_EncodedRLE], + pyiscrowd: list[int] | _NDArrayUInt8, +) -> list[Any] | _NDArrayFloat64: ... +def merge(rleObjs: list[_EncodedRLE], intersect: int = 0) -> _EncodedRLE: ... + +# ignore an "overlapping overloads" error due to _NDArrayInt32 being an alias for `Incomplete` for now +@overload +def frPyObjects(pyobj: _NDArrayUInt32 | list[list[int]] | list[_EncodedRLE], h: int, w: int) -> list[_EncodedRLE]: ... +@overload +def frPyObjects(pyobj: list[int] | _EncodedRLE, h: int, w: int) -> _EncodedRLE: ... + +def encode(bimask: _NDArrayUInt8) -> _EncodedRLE: ... +def decode(rleObjs: _EncodedRLE) -> _NDArrayUInt8: ... +def area(rleObjs: _EncodedRLE) -> _NPUInt32: ... +def toBbox(rleObjs: _EncodedRLE) -> _NDArrayFloat64: ... diff --git a/stubs/pycups/METADATA.toml b/stubs/pycups/METADATA.toml new file mode 100644 index 000000000000..e8cde2087247 --- /dev/null +++ b/stubs/pycups/METADATA.toml @@ -0,0 +1,5 @@ +version = "2.0.*" +upstream-repository = "https://github.com/OpenPrinting/pycups" + +[tool.stubtest] +apt-dependencies = ["libcups2-dev"] diff --git a/stubs/pycups/cups.pyi b/stubs/pycups/cups.pyi new file mode 100644 index 000000000000..3ccf11bcbd8c --- /dev/null +++ b/stubs/pycups/cups.pyi @@ -0,0 +1,899 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from io import IOBase +from typing import Final, Literal, TypeAlias, TypedDict, TypeVar, final, overload, type_check_only +from typing_extensions import NotRequired + +_T = TypeVar("_T") + +_FileOrFd: TypeAlias = IOBase | int + +_CupsDevice = TypedDict( + "_CupsDevice", + {"device-class": str, "device-info": str, "device-make-and-model": str, "device-id": str, "device-location": str}, +) + +_CupsDocument = TypedDict("_CupsDocument", {"file": str, "document-format": NotRequired[str], "document-name": NotRequired[str]}) + +_CupsPPD = TypedDict( + "_CupsPPD", + { + "ppd-natural-language": str, + "ppd-make": str, + "ppd-make-and-model": str, + "ppd-device-id": str, + "ppd-product": str, + "ppd-psversion": str, + "ppd-type": str, + "ppd-model-number": int, + }, +) + +_CupsPPD2 = TypedDict( + "_CupsPPD2", + { + "ppd-natural-language": list[str], + "ppd-make": list[str], + "ppd-make-and-model": list[str], + "ppd-device-id": list[str], + "ppd-product": list[str], + "ppd-psversion": list[str], + "ppd-type": list[str], + "ppd-model-number": list[int], + }, +) + +_CupsJob = TypedDict( + "_CupsJob", + { + "number-of-documents": int, + "job-media-progress": int, + "job-more-info": str, + "job-preserved": bool, + "job-printer-up-time": int, + "job-printer-uri": str, + "job-uri": str, + "printer-uri": str, + "document-format-detected": str, + "document-format": str, + "job-priority": int, + "job-uuid": str, + "date-time-at-completed": str, + "date-time-at-creation": str, + "date-time-at-processing": str, + "time-at-completed": int, + "time-at-creation": int, + "time-at-processing": int, + "job-state": int, + "job-state-reasons": str, + "job-impressions-completed": int, + "job-media-sheets-completed": int, + "job-k-octets": int, + "job-hold-until": str, + "job-sheets": list[str], + "job-printer-state-message": str, + "job-printer-state-reasons": str, + "job-name": str, + "job-originating-user-name": str, + }, +) + +_CupsAttributeInfo = TypedDict( + "_CupsAttributeInfo", {"attributes-charset": str, "attributes-natural-language": str, "job-id": int} +) + +@type_check_only +class _CupsOptionChoice(TypedDict): + choice: str + text: str + marked: bool + +@type_check_only +class _CupsJobWithAttributeInfo(_CupsJob, _CupsAttributeInfo): ... + +_CupsEvent = TypedDict( # noqa: Y049 + "_CupsEvent", + { + "notify-charset": str, + "notify-natural-language": str, + "notify-subscription-id": int, + "notify-sequence-number": int, + "notify-subscribed-event": str, + "printer-up-time": int, + "notify-text": str, + "notify-printer-uri": str, + "printer-name": str, + "printer-state": int, + "printer-state-reasons": list[str], + "printer-is-accepting-jobs": bool, + "notify-job-id": int, + "job-state": int, + "job-name": str, + "job-state-reasons": str, + "job-impressions-completed": int, + }, +) + +_CupsNotifications = TypedDict( + "_CupsNotifications", {"notify-get-interval": int, "printer-up-time": int, "events": list[_CupsEvent]} +) + +_CupsPrinter = TypedDict( + "_CupsPrinter", + { + "marker-change-time": int, + "printer-config-change-date-time": str, + "printer-config-change-time": int, + "printer-current-time": str, + "printer-dns-sd-name": str | None, + "printer-error-policy": str, + "printer-error-policy-supported": list[str], + "printer-icons": str, + "printer-is-accepting-jobs": bool, + "printer-is-shared": bool, + "printer-is-temporary": bool, + "printer-more-info": str, + "printer-op-policy": str, + "printer-state": int, + "printer-state-change-date-time": str, + "printer-state-change-time": int, + "printer-state-message": str, + "printer-state-reasons": list[str], + "printer-strings-uri": str, + "printer-type": int, + "printer-up-time": int, + "printer-uri-supported": list[str], + "queued-job-count": int, + "uri-security-supported": list[str], + "uri-authentication-supported": list[str], + "printer-id": int, + "printer-name": str, + "printer-location": str, + "printer-geo-location": str, + "printer-info": str, + "printer-organization": str, + "printer-organizational-unit": str, + "printer-uuid": str, + "job-quota-period": int, + "job-k-limit": int, + "job-page-limit": int, + "job-sheets-default": tuple[str, str], + "device-uri": str, + "document-format-supported": list[str], + "copies-default": int, + "document-format-default": str, + "job-cancel-after-default": int, + "job-hold-until-default": str, + "job-priority-default": int, + "number-up-default": int, + "notify-lease-duration-default": int, + "notify-events-default": list[str], + "orientation-requested-default": int | None, + "print-color-mode-default": str, + "print-quality-default": int, + "copies-supported": tuple[int, int], + "ipp-features-supported": list[str], + "job-creation-attributes-supported": list[str], + "printer-make-and-model": str, + "finishings-supported": list[int], + "finishings-default": int, + "charset-configured": str, + "charset-supported": list[str], + "compression-supported": list[str], + "cups-version": str, + "generated-natural-language-supported": list[str], + "ipp-versions-supported": list[str], + "ippget-event-life": int, + "job-cancel-after-supported": tuple[int, int], + "job-hold-until-supported": list[str], + "job-ids-supported": bool, + "job-k-octets-supported": tuple[int, int], + "job-priority-supported": list[int], + "job-settable-attributes-supported": list[str], + "job-sheets-supported": list[str], + "jpeg-k-octets-supported": tuple[int, int], + "jpeg-x-dimension-supported": tuple[int, int], + "jpeg-y-dimension-supported": tuple[int, int], + "media-col-supported": list[str], + "multiple-document-handling-supported": list[str], + "multiple-document-jobs-supported": bool, + "multiple-operation-time-out": int, + "multiple-operation-time-out-action": str, + "natural-language-configured": str, + "notify-attributes-supported": list[str], + "notify-lease-duration-supported": tuple[int, int], + "notify-max-events-supported": list[int], + "notify-events-supported": list[str], + "notify-pull-method-supported": list[str], + "notify-schemes-supported": list[str], + "number-up-supported": list[int], + "number-up-layout-supported": list[str], + "operations-supported": list[int], + "orientation-requested-supported": list[int], + "page-delivery-supported": list[str], + "page-ranges-supported": bool, + "pdf-k-octets-supported": tuple[int, int], + "pdf-versions-supported": list[str], + "pdl-override-supported": list[str], + "print-scaling-supported": list[str], + "printer-get-attributes-supported": list[str], + "printer-op-policy-supported": list[str], + "printer-settable-attributes-supported": list[str], + "server-is-sharing-printers": bool, + "which-jobs-supported": list[str], + }, +) + +_CupsPrinterSimple = TypedDict( + "_CupsPrinterSimple", + { + "printer-is-shared": bool, + "printer-state": int, + "printer-state-message": str, + "printer-state-reasons": list[str], + "printer-type": int, + "printer-uri-supported": str, + "printer-location": str, + "printer-info": str, + "device-uri": str, + "printer-make-and-model": str, + }, +) + +_CupsSubscription = TypedDict( + "_CupsSubscription", + { + "notify-events": list[str], + "notify-lease-duration": int, + "notify-pull-method": NotRequired[str], + "notify-recipient-uri": NotRequired[str], + "notify-subscriber-user-name": str, + "notify-time-interval": int, + "notify-subscription-id": int, + }, +) + +CUPS_DEST_FLAGS_CANCELED: Final[int] +CUPS_DEST_FLAGS_CONNECTING: Final[int] +CUPS_DEST_FLAGS_ERROR: Final[int] +CUPS_DEST_FLAGS_MORE: Final[int] +CUPS_DEST_FLAGS_NONE: Final[int] +CUPS_DEST_FLAGS_REMOVED: Final[int] +CUPS_DEST_FLAGS_RESOLVING: Final[int] +CUPS_DEST_FLAGS_UNCONNECTED: Final[int] +CUPS_FORMAT_AUTO: Final[str] +CUPS_FORMAT_COMMAND: Final[str] +CUPS_FORMAT_PDF: Final[str] +CUPS_FORMAT_POSTSCRIPT: Final[str] +CUPS_FORMAT_RAW: Final[str] +CUPS_FORMAT_TEXT: Final[str] +CUPS_PRINTER_AUTHENTICATED: Final[int] +CUPS_PRINTER_BIND: Final[int] +CUPS_PRINTER_BW: Final[int] +CUPS_PRINTER_CLASS: Final[int] +CUPS_PRINTER_COLLATE: Final[int] +CUPS_PRINTER_COLOR: Final[int] +CUPS_PRINTER_COMMANDS: Final[int] +CUPS_PRINTER_COPIES: Final[int] +CUPS_PRINTER_COVER: Final[int] +CUPS_PRINTER_DEFAULT: Final[int] +CUPS_PRINTER_DELETE: Final[int] +CUPS_PRINTER_DISCOVERED: Final[int] +CUPS_PRINTER_DUPLEX: Final[int] +CUPS_PRINTER_FAX: Final[int] +CUPS_PRINTER_IMPLICIT: Final[int] +CUPS_PRINTER_LARGE: Final[int] +CUPS_PRINTER_LOCAL: Final[int] +CUPS_PRINTER_MEDIUM: Final[int] +CUPS_PRINTER_NOT_SHARED: Final[int] +CUPS_PRINTER_OPTIONS: Final[int] +CUPS_PRINTER_PUNCH: Final[int] +CUPS_PRINTER_REJECTING: Final[int] +CUPS_PRINTER_REMOTE: Final[int] +CUPS_PRINTER_SMALL: Final[int] +CUPS_PRINTER_SORT: Final[int] +CUPS_PRINTER_STAPLE: Final[int] +CUPS_PRINTER_VARIABLE: Final[int] +CUPS_SERVER_DEBUG_LOGGING: Final[str] +CUPS_SERVER_REMOTE_ADMIN: Final[str] +CUPS_SERVER_REMOTE_ANY: Final[str] +CUPS_SERVER_REMOTE_PRINTERS: Final[str] +CUPS_SERVER_SHARE_PRINTERS: Final[str] +CUPS_SERVER_USER_CANCEL_ANY: Final[str] +HTTP_AUTHORIZATION_CANCELED: Final[int] +HTTP_BAD_GATEWAY: Final[int] +HTTP_BAD_REQUEST: Final[int] +HTTP_ENCRYPT_ALWAYS: Final[int] +HTTP_ENCRYPT_IF_REQUESTED: Final[int] +HTTP_ENCRYPT_NEVER: Final[int] +HTTP_ENCRYPT_REQUIRED: Final[int] +HTTP_ERROR: Final[int] +HTTP_FORBIDDEN: Final[int] +HTTP_GATEWAY_TIMEOUT: Final[int] +HTTP_NOT_FOUND: Final[int] +HTTP_NOT_IMPLEMENTED: Final[int] +HTTP_NOT_MODIFIED: Final[int] +HTTP_NOT_SUPPORTED: Final[int] +HTTP_OK: Final[int] +HTTP_PKI_ERROR: Final[int] +HTTP_REQUEST_TIMEOUT: Final[int] +HTTP_SERVER_ERROR: Final[int] +HTTP_SERVICE_UNAVAILABLE: Final[int] +HTTP_STATUS_BAD_GATEWAY: Final[int] +HTTP_STATUS_BAD_REQUEST: Final[int] +HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED: Final[int] +HTTP_STATUS_CUPS_PKI_ERROR: Final[int] +HTTP_STATUS_ERROR: Final[int] +HTTP_STATUS_FORBIDDEN: Final[int] +HTTP_STATUS_GATEWAY_TIMEOUT: Final[int] +HTTP_STATUS_NOT_FOUND: Final[int] +HTTP_STATUS_NOT_IMPLEMENTED: Final[int] +HTTP_STATUS_NOT_MODIFIED: Final[int] +HTTP_STATUS_NOT_SUPPORTED: Final[int] +HTTP_STATUS_OK: Final[int] +HTTP_STATUS_REQUEST_TIMEOUT: Final[int] +HTTP_STATUS_SERVER_ERROR: Final[int] +HTTP_STATUS_SERVICE_UNAVAILABLE: Final[int] +HTTP_STATUS_UNAUTHORIZED: Final[int] +HTTP_STATUS_UPGRADE_REQUIRED: Final[int] +HTTP_UNAUTHORIZED: Final[int] +HTTP_UPGRADE_REQUIRED: Final[int] +IPP_ATTRIBUTE: Final[int] +IPP_ATTRIBUTES: Final[int] +IPP_ATTRIBUTES_NOT_SETTABLE: Final[int] +IPP_AUTHENTICATION_CANCELED: Final[int] +IPP_BAD_REQUEST: Final[int] +IPP_CHARSET: Final[int] +IPP_COMPRESSION_ERROR: Final[int] +IPP_COMPRESSION_NOT_SUPPORTED: Final[int] +IPP_CONFLICT: Final[int] +IPP_CREATE_JOB_SUBSCRIPTION: Final[int] +IPP_CREATE_PRINTER_SUBSCRIPTION: Final[int] +IPP_DATA: Final[int] +IPP_DEVICE_ERROR: Final[int] +IPP_DOCUMENT_ACCESS_ERROR: Final[int] +IPP_DOCUMENT_FORMAT: Final[int] +IPP_DOCUMENT_FORMAT_ERROR: Final[int] +IPP_ERROR: Final[int] +IPP_ERROR_JOB_CANCELED: Final[int] +IPP_FINISHINGS_BALE: Final[int] +IPP_FINISHINGS_BIND: Final[int] +IPP_FINISHINGS_BIND_BOTTOM: Final[int] +IPP_FINISHINGS_BIND_LEFT: Final[int] +IPP_FINISHINGS_BIND_RIGHT: Final[int] +IPP_FINISHINGS_BIND_TOP: Final[int] +IPP_FINISHINGS_BOOKLET_MAKER: Final[int] +IPP_FINISHINGS_COVER: Final[int] +IPP_FINISHINGS_EDGE_STITCH: Final[int] +IPP_FINISHINGS_EDGE_STITCH_BOTTOM: Final[int] +IPP_FINISHINGS_EDGE_STITCH_LEFT: Final[int] +IPP_FINISHINGS_EDGE_STITCH_RIGHT: Final[int] +IPP_FINISHINGS_EDGE_STITCH_TOP: Final[int] +IPP_FINISHINGS_FOLD: Final[int] +IPP_FINISHINGS_JOB_OFFSET: Final[int] +IPP_FINISHINGS_NONE: Final[int] +IPP_FINISHINGS_PUNCH: Final[int] +IPP_FINISHINGS_SADDLE_STITCH: Final[int] +IPP_FINISHINGS_STAPLE: Final[int] +IPP_FINISHINGS_STAPLE_BOTTOM_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_BOTTOM: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_RIGHT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_TOP: Final[int] +IPP_FINISHINGS_STAPLE_TOP_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_TOP_RIGHT: Final[int] +IPP_FINISHINGS_TRIM: Final[int] +IPP_FORBIDDEN: Final[int] +IPP_GONE: Final[int] +IPP_HEADER: Final[int] +IPP_IDLE: Final[int] +IPP_IGNORED_ALL_NOTIFICATIONS: Final[int] +IPP_IGNORED_ALL_SUBSCRIPTIONS: Final[int] +IPP_INTERNAL_ERROR: Final[int] +IPP_JOB_ABORTED: Final[int] +IPP_JOB_CANCELED: Final[int] +IPP_JOB_COMPLETED: Final[int] +IPP_JOB_HELD: Final[int] +IPP_JOB_PENDING: Final[int] +IPP_JOB_PROCESSING: Final[int] +IPP_JOB_STOPPED: Final[int] +IPP_LANDSCAPE: Final[int] +IPP_MAX_NAME: Final[int] +IPP_MULTIPLE_JOBS_NOT_SUPPORTED: Final[int] +IPP_NOT_ACCEPTING: Final[int] +IPP_NOT_AUTHENTICATED: Final[int] +IPP_NOT_AUTHORIZED: Final[int] +IPP_NOT_FOUND: Final[int] +IPP_NOT_POSSIBLE: Final[int] +IPP_OK: Final[int] +IPP_OK_BUT_CANCEL_SUBSCRIPTION: Final[int] +IPP_OK_CONFLICT: Final[int] +IPP_OK_EVENTS_COMPLETE: Final[int] +IPP_OK_IGNORED_NOTIFICATIONS: Final[int] +IPP_OK_IGNORED_SUBSCRIPTIONS: Final[int] +IPP_OK_SUBST: Final[int] +IPP_OK_TOO_MANY_EVENTS: Final[int] +IPP_OPERATION_NOT_SUPPORTED: Final[int] +IPP_OP_ACTIVATE_PRINTER: Final[int] +IPP_OP_CANCEL_CURRENT_JOB: Final[int] +IPP_OP_CANCEL_JOB: Final[int] +IPP_OP_CANCEL_JOBS: Final[int] +IPP_OP_CANCEL_MY_JOBS: Final[int] +IPP_OP_CANCEL_SUBSCRIPTION: Final[int] +IPP_OP_CLOSE_JOB: Final[int] +IPP_OP_CREATE_JOB: Final[int] +IPP_OP_CREATE_JOB_SUBSCRIPTIONS: Final[int] +IPP_OP_CREATE_PRINTER_SUBSCRIPTIONS: Final[int] +IPP_OP_CUPS_ACCEPT_JOBS: Final[int] +IPP_OP_CUPS_ADD_MODIFY_CLASS: Final[int] +IPP_OP_CUPS_ADD_MODIFY_PRINTER: Final[int] +IPP_OP_CUPS_AUTHENTICATE_JOB: Final[int] +IPP_OP_CUPS_DELETE_CLASS: Final[int] +IPP_OP_CUPS_DELETE_PRINTER: Final[int] +IPP_OP_CUPS_GET_CLASSES: Final[int] +IPP_OP_CUPS_GET_DEFAULT: Final[int] +IPP_OP_CUPS_GET_DOCUMENT: Final[int] +IPP_OP_CUPS_GET_PPD: Final[int] +IPP_OP_CUPS_GET_PPDS: Final[int] +IPP_OP_CUPS_GET_PRINTERS: Final[int] +IPP_OP_CUPS_MOVE_JOB: Final[int] +IPP_OP_CUPS_REJECT_JOBS: Final[int] +IPP_OP_CUPS_SET_DEFAULT: Final[int] +IPP_OP_DEACTIVATE_PRINTER: Final[int] +IPP_OP_DISABLE_PRINTER: Final[int] +IPP_OP_ENABLE_PRINTER: Final[int] +IPP_OP_GET_JOBS: Final[int] +IPP_OP_GET_JOB_ATTRIBUTES: Final[int] +IPP_OP_GET_NOTIFICATIONS: Final[int] +IPP_OP_GET_PRINTER_ATTRIBUTES: Final[int] +IPP_OP_GET_PRINTER_SUPPORTED_VALUES: Final[int] +IPP_OP_GET_PRINT_SUPPORT_FILES: Final[int] +IPP_OP_GET_RESOURCES: Final[int] +IPP_OP_GET_RESOURCE_ATTRIBUTES: Final[int] +IPP_OP_GET_RESOURCE_DATA: Final[int] +IPP_OP_GET_SUBSCRIPTIONS: Final[int] +IPP_OP_HOLD_JOB: Final[int] +IPP_OP_HOLD_NEW_JOBS: Final[int] +IPP_OP_IDENTIFY_PRINTER: Final[int] +IPP_OP_PAUSE_PRINTER: Final[int] +IPP_OP_PAUSE_PRINTER_AFTER_CURRENT_JOB: Final[int] +IPP_OP_PRINT_JOB: Final[int] +IPP_OP_PRINT_URI: Final[int] +IPP_OP_PROMOTE_JOB: Final[int] +IPP_OP_PURGE_JOBS: Final[int] +IPP_OP_RELEASE_HELD_NEW_JOBS: Final[int] +IPP_OP_RELEASE_JOB: Final[int] +IPP_OP_RENEW_SUBSCRIPTION: Final[int] +IPP_OP_REPROCESS_JOB: Final[int] +IPP_OP_RESTART_JOB: Final[int] +IPP_OP_RESTART_PRINTER: Final[int] +IPP_OP_RESUBMIT_JOB: Final[int] +IPP_OP_RESUME_JOB: Final[int] +IPP_OP_RESUME_PRINTER: Final[int] +IPP_OP_SCHEDULE_JOB_AFTER: Final[int] +IPP_OP_SEND_DOCUMENT: Final[int] +IPP_OP_SEND_HARDCOPY_DOCUMENT: Final[int] +IPP_OP_SEND_NOTIFICATIONS: Final[int] +IPP_OP_SEND_URI: Final[int] +IPP_OP_SET_JOB_ATTRIBUTES: Final[int] +IPP_OP_SET_PRINTER_ATTRIBUTES: Final[int] +IPP_OP_SHUTDOWN_PRINTER: Final[int] +IPP_OP_STARTUP_PRINTER: Final[int] +IPP_OP_SUSPEND_CURRENT_JOB: Final[int] +IPP_OP_VALIDATE_DOCUMENT: Final[int] +IPP_OP_VALIDATE_JOB: Final[int] +IPP_ORIENT_LANDSCAPE: Final[int] +IPP_ORIENT_PORTRAIT: Final[int] +IPP_ORIENT_REVERSE_LANDSCAPE: Final[int] +IPP_ORIENT_REVERSE_PORTRAIT: Final[int] +IPP_PKI_ERROR: Final[int] +IPP_PORTRAIT: Final[int] +IPP_PRINTER_BUSY: Final[int] +IPP_PRINTER_IDLE: Final[int] +IPP_PRINTER_IS_DEACTIVATED: Final[int] +IPP_PRINTER_PROCESSING: Final[int] +IPP_PRINTER_STOPPED: Final[int] +IPP_PRINT_SUPPORT_FILE_NOT_FOUND: Final[int] +IPP_QUALITY_DRAFT: Final[int] +IPP_QUALITY_HIGH: Final[int] +IPP_QUALITY_NORMAL: Final[int] +IPP_REDIRECTION_OTHER_SITE: Final[int] +IPP_REQUEST_ENTITY: Final[int] +IPP_REQUEST_VALUE: Final[int] +IPP_RES_PER_CM: Final[int] +IPP_RES_PER_INCH: Final[int] +IPP_REVERSE_LANDSCAPE: Final[int] +IPP_REVERSE_PORTRAIT: Final[int] +IPP_SERVICE_UNAVAILABLE: Final[int] +IPP_STATE_ATTRIBUTE: Final[int] +IPP_STATE_DATA: Final[int] +IPP_STATE_ERROR: Final[int] +IPP_STATE_HEADER: Final[int] +IPP_STATE_IDLE: Final[int] +IPP_STATUS_ERROR_ATTRIBUTES_NOT_SETTABLE: Final[int] +IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES: Final[int] +IPP_STATUS_ERROR_BAD_REQUEST: Final[int] +IPP_STATUS_ERROR_BUSY: Final[int] +IPP_STATUS_ERROR_CHARSET: Final[int] +IPP_STATUS_ERROR_COMPRESSION_ERROR: Final[int] +IPP_STATUS_ERROR_COMPRESSION_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_CONFLICTING: Final[int] +IPP_STATUS_ERROR_CUPS_AUTHENTICATION_CANCELED: Final[int] +IPP_STATUS_ERROR_CUPS_PKI: Final[int] +IPP_STATUS_ERROR_CUPS_UPGRADE_REQUIRED: Final[int] +IPP_STATUS_ERROR_DEVICE: Final[int] +IPP_STATUS_ERROR_DOCUMENT_ACCESS: Final[int] +IPP_STATUS_ERROR_DOCUMENT_FORMAT_ERROR: Final[int] +IPP_STATUS_ERROR_DOCUMENT_FORMAT_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_FORBIDDEN: Final[int] +IPP_STATUS_ERROR_GONE: Final[int] +IPP_STATUS_ERROR_IGNORED_ALL_NOTIFICATIONS: Final[int] +IPP_STATUS_ERROR_IGNORED_ALL_SUBSCRIPTIONS: Final[int] +IPP_STATUS_ERROR_INTERNAL: Final[int] +IPP_STATUS_ERROR_JOB_CANCELED: Final[int] +IPP_STATUS_ERROR_MULTIPLE_JOBS_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_NOT_ACCEPTING_JOBS: Final[int] +IPP_STATUS_ERROR_NOT_AUTHENTICATED: Final[int] +IPP_STATUS_ERROR_NOT_AUTHORIZED: Final[int] +IPP_STATUS_ERROR_NOT_FOUND: Final[int] +IPP_STATUS_ERROR_NOT_POSSIBLE: Final[int] +IPP_STATUS_ERROR_OPERATION_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_PRINTER_IS_DEACTIVATED: Final[int] +IPP_STATUS_ERROR_PRINT_SUPPORT_FILE_NOT_FOUND: Final[int] +IPP_STATUS_ERROR_REQUEST_ENTITY: Final[int] +IPP_STATUS_ERROR_REQUEST_VALUE: Final[int] +IPP_STATUS_ERROR_SERVICE_UNAVAILABLE: Final[int] +IPP_STATUS_ERROR_TEMPORARY: Final[int] +IPP_STATUS_ERROR_TIMEOUT: Final[int] +IPP_STATUS_ERROR_TOO_MANY_SUBSCRIPTIONS: Final[int] +IPP_STATUS_ERROR_URI_SCHEME: Final[int] +IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED: Final[int] +IPP_STATUS_OK: Final[int] +IPP_STATUS_OK_BUT_CANCEL_SUBSCRIPTION: Final[int] +IPP_STATUS_OK_CONFLICTING: Final[int] +IPP_STATUS_OK_EVENTS_COMPLETE: Final[int] +IPP_STATUS_OK_IGNORED_NOTIFICATIONS: Final[int] +IPP_STATUS_OK_IGNORED_OR_SUBSTITUTED: Final[int] +IPP_STATUS_OK_IGNORED_SUBSCRIPTIONS: Final[int] +IPP_STATUS_OK_TOO_MANY_EVENTS: Final[int] +IPP_STATUS_REDIRECTION_OTHER_SITE: Final[int] +IPP_TAG_BOOLEAN: Final[int] +IPP_TAG_CHARSET: Final[int] +IPP_TAG_ENUM: Final[int] +IPP_TAG_INTEGER: Final[int] +IPP_TAG_JOB: Final[int] +IPP_TAG_KEYWORD: Final[int] +IPP_TAG_LANGUAGE: Final[int] +IPP_TAG_MIMETYPE: Final[int] +IPP_TAG_NAME: Final[int] +IPP_TAG_OPERATION: Final[int] +IPP_TAG_PRINTER: Final[int] +IPP_TAG_RANGE: Final[int] +IPP_TAG_STRING: Final[int] +IPP_TAG_TEXT: Final[int] +IPP_TAG_URI: Final[int] +IPP_TAG_ZERO: Final[int] +IPP_TEMPORARY_ERROR: Final[int] +IPP_TIMEOUT: Final[int] +IPP_TOO_MANY_SUBSCRIPTIONS: Final[int] +IPP_UPGRADE_REQUIRED: Final[int] +IPP_URI_SCHEME: Final[int] +IPP_VERSION_NOT_SUPPORTED: Final[int] +PPD_CONFORM_RELAXED: Final[int] +PPD_CONFORM_STRICT: Final[int] +PPD_ORDER_ANY: Final[int] +PPD_ORDER_DOCUMENT: Final[int] +PPD_ORDER_EXIT: Final[int] +PPD_ORDER_JCL: Final[int] +PPD_ORDER_PAGE: Final[int] +PPD_ORDER_PROLOG: Final[int] +PPD_UI_BOOLEAN: Final[int] +PPD_UI_PICKMANY: Final[int] +PPD_UI_PICKONE: Final[int] + +@final +class Attribute: + @property + def name(self) -> str: ... + @property + def spec(self) -> str: ... + @property + def text(self) -> str: ... + @property + def value(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Connection: + def __init__(self, host: str = ..., port: int = ..., encryption: int = ...) -> None: ... + def acceptJobs(self, name: str, /) -> None: ... + + @overload + def addPrinter(self, name: str, filename: str = ..., *, info: str = ..., location: str = ..., device: str = ...) -> None: ... + @overload + def addPrinter(self, name: str, *, ppdname: str = ..., info: str = ..., location: str = ..., device: str = ...) -> None: ... + @overload + def addPrinter(self, name: str, *, info: str = ..., location: str = ..., device: str = ..., ppd: PPD = ...) -> None: ... + + def addPrinterOptionDefault(self, name: str, option: str, value: str | int | Sequence[str | int], /) -> None: ... + def addPrinterToClass(self, name: str, _class: str, /) -> None: ... + def adminExportSamba(self, name: str, server: str, user: str, password: str, /): ... + def adminGetServerSettings(self) -> dict[str, str]: ... + def adminSetServerSettings(self, settings: dict[str, str], /) -> None: ... + def authenticateJob(self, jobid: int, auth_info: list[str] = ..., /) -> None: ... + + @overload + def cancelAllJobs(self, name: str, *, my_jobs: bool = False, purge_jobs: bool = True) -> None: ... + @overload + def cancelAllJobs(self, *, uri: str, my_jobs: bool = False, purge_jobs: bool = True) -> None: ... + + def cancelJob(self, job_id: int, purge_job: bool = False) -> None: ... + def cancelSubscription(self, id: int, /) -> None: ... + def createJob(self, printer: str, title: str, options: dict[str, str]) -> int: ... + def createSubscription( + self, + uri: str, + events: list[str] = ..., + job_id: int = ..., + recipient_uri: str = ..., + lease_duration: int = ..., + time_interval: int = ..., + user_data: str = ..., + ) -> int: ... + def deleteClass(self, _class: str, /) -> None: ... + def deletePrinter(self, name: str, /) -> None: ... + def deletePrinterFromClass(self, name: str, _class: str, /) -> None: ... + def deletePrinterOptionDefault(self, name: str, option: str, /) -> None: ... + def disablePrinter(self, name: str, reason: str = ...) -> None: ... + def enablePrinter(self, name: str, /) -> None: ... + def finishDocument(self, printer: str) -> int: ... + def getClasses(self) -> dict[str, str | list[str]]: ... + def getDefault(self) -> str | None: ... + def getDests(self) -> dict[tuple[str, str] | tuple[None, None], Dest]: ... + def getDevices( + self, limit: int = 0, exclude_schemes: list[str] = ..., include_schemes: list[str] = ..., timeout: int = 0 + ) -> dict[str, _CupsDevice]: ... + def getDocument(self, printer_uri: str, job_id: int, document_number: int, /) -> _CupsDocument: ... + + @overload + def getFile(self, resource: str, filename: str = ...) -> None: ... + @overload + def getFile(self, resource: str, *, fd: int) -> None: ... + @overload + def getFile(self, resource: str, *, file: _FileOrFd) -> None: ... + + def getJobAttributes(self, job_id: int, requested_attributes: list[str] = ...) -> _CupsJobWithAttributeInfo: ... + def getJobs( + self, + which_jobs: Literal["completed", "not-completed", "all"] = "not-completed", + my_jobs: bool = False, + limit: int = ..., + first_job_id: int = ..., + requested_attributes: list[str] = ["job-id", "job-uri"], + ) -> dict[int, _CupsJob]: ... + def getNotifications(self, subscription_ids: list[int], sequence_numbers: list[int] = ...) -> _CupsNotifications: ... + def getPPD(self, name: str, /) -> str: ... + def getPPD3(self, name: str, modtime: float = ..., filename: str = ...) -> tuple[int, float, str]: ... + def getPPDs( + self, + limit: int = ..., + exclude_schemes: list[str] = ..., + include_schemes: list[str] = ..., + ppd_natural_language: str = ..., + ppd_device_id: str = ..., + ppd_make: str = ..., + ppd_make_and_model: str = ..., + ppd_model_number: int = ..., + ppd_product: str = ..., + ppd_psversion: str = ..., + ppd_type: str = ..., + ) -> dict[str, _CupsPPD]: ... + def getPPDs2( + self, + limit: int = ..., + exclude_schemes: list[str] = ..., + include_schemes: list[str] = ..., + ppd_natural_language: str = ..., + ppd_device_id: str = ..., + ppd_make: str = ..., + ppd_make_and_model: str = ..., + ppd_model_number: int = ..., + ppd_product: str = ..., + ppd_psversion: str = ..., + ppd_type: str = ..., + ) -> dict[str, _CupsPPD2]: ... + + @overload + def getPrinterAttributes(self, name: str, *, requested_attributes: list[str] = ...) -> _CupsPrinter: ... + @overload + def getPrinterAttributes(self, *, uri: str, requested_attributes: list[str] = ...) -> _CupsPrinter: ... + + def getPrinters(self) -> dict[str, _CupsPrinterSimple]: ... + def getServerPPD(self, ppd_name: str, /) -> str: ... + def getSubscriptions(self, uri: str, my_subscriptions: bool = False, job_id: int = ...) -> list[_CupsSubscription]: ... + + @overload + def moveJob(self, printer_uri: str, job_id: int, job_printer_uri: str) -> None: ... + @overload + def moveJob(self, printer_uri: str, *, job_printer_uri: str) -> None: ... + @overload + def moveJob(self, *, job_id: int, job_printer_uri: str) -> None: ... + + def printFile(self, printer: str, filename: str, title: str, options: dict[str, str]) -> int: ... + def printFiles(self, printer: str, filenames: list[str], title: str, options: dict[str, str]) -> int: ... + def printTestPage(self, name: str) -> int: ... + + @overload + def putFile(self, resource: str, filename: str) -> None: ... + @overload + def putFile(self, resource: str, *, fd: int) -> None: ... + @overload + def putFile(self, resource: str, *, file: _FileOrFd) -> None: ... + + def rejectJobs(self, name: str, reason: str = ...) -> None: ... + def renewSubscription(self, id: int, lease_duration: int = ...) -> None: ... + def restartJob(self, job_id: int, job_hold_until: str = ...) -> None: ... + def setDefault(self, name: str, /) -> None: ... + def setJobHoldUntil(self, job_id: int, job_hold_until: str, /) -> None: ... + def setPrinterDevice(self, name: str, device_uri: str, /) -> None: ... + def setPrinterErrorPolicy(self, name: str, policy: str, /) -> None: ... + def setPrinterInfo(self, name: str, info: str, /) -> None: ... + def setPrinterJobSheets(self, name: str, start: str, end: str, /) -> None: ... + def setPrinterLocation(self, name: str, location: str, /) -> None: ... + def setPrinterOpPolicy(self, name: str, policy: str, /) -> None: ... + def setPrinterShared(self, name: str, shared: bool, /) -> None: ... + def setPrinterUsersAllowed(self, name: str, allowed: list[str], /) -> None: ... + def setPrinterUsersDenied(self, name: str, denied: list[str], /) -> None: ... + def startDocument(self, printer: str, job_id: int, doc_name: str, format: str, last_document: bool) -> int: ... + def writeRequestData(self, buffer: bytes, length: int) -> int: ... + +@final +class Constraint: + @property + def choice1(self) -> str: ... + @property + def choice2(self) -> str: ... + @property + def option1(self) -> str: ... + @property + def option2(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Dest: + @property + def instance(self) -> str | None: ... + @property + def is_default(self) -> bool: ... + @property + def name(self) -> str: ... + @property + def options(self) -> dict[str, str]: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Group: + @property + def name(self) -> str: ... + @property + def options(self) -> list[Option]: ... + @property + def subgroups(self) -> list[Group]: ... + @property + def text(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +class HTTPError(Exception): ... + +@final +class IPPAttribute: + @property + def group_tag(self) -> int: ... + @property + def name(self) -> str: ... + @property + def value_tag(self) -> int: ... + @property + def values(self) -> list[int | str | bool]: ... + def __init__(self, group_tag: int, value_tag: int, name: str, value: str = ..., /) -> None: ... + +class IPPError(Exception): ... + +@final +class IPPRequest: + @property + def attributes(self) -> list[IPPAttribute]: ... + @property + def operation(self) -> int: ... + + @property + def state(self) -> int: ... + @state.setter + def state(self, value: int) -> None: ... + + @property + def statuscode(self) -> int: ... + @statuscode.setter + def statuscode(self, value: int) -> None: ... + + def __init__(self, op: int = ..., /) -> None: ... + def add(self, attr: IPPAttribute, /) -> IPPAttribute: ... + def addSeparator(self) -> IPPAttribute: ... + def readIO(self, read_fn: Callable[[int], int], blocking: bool = True) -> int: ... + def writeIO(self, write_fn: Callable[[bytes], int], blocking: bool = True) -> int: ... + +@final +class Option: + @property + def choices(self) -> list[_CupsOptionChoice]: ... + @property + def conflicted(self) -> bool: ... + @property + def defchoice(self) -> str: ... + @property + def keyword(self) -> str: ... + @property + def text(self) -> str: ... + @property + def ui(self) -> int: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class PPD: + @property + def attributes(self) -> list[Attribute]: ... + @property + def constraints(self) -> list[Constraint]: ... + @property + def optionGroups(self) -> list[Group]: ... + def __init__(self, filename: str, /) -> None: ... + def conflicts(self) -> int: ... + def emit(self, file: _FileOrFd, section: int, /) -> None: ... + def emitAfterOrder(self, file: _FileOrFd, section: int, limit: int, min_order: float, /) -> None: ... + def emitFd(self, fd: int, section: int, /) -> None: ... + def emitJCL(self, file: _FileOrFd, job_id: int, user: str, title: str, /) -> None: ... + def emitJCLEnd(self, file: _FileOrFd, /) -> None: ... + def emitString(self, section: int, min_order: float, /) -> str: ... + def findAttr(self, name: str, spec: str = ...) -> Attribute | None: ... + def findNextAttr(self, name: str, spec: str = ...) -> Attribute | None: ... + def findOption(self, name: str, /) -> Option | None: ... + def localize(self) -> None: ... + def localizeIPPReason(self, reason: str, scheme: str = ...) -> str | None: ... + def localizeMarkerName(self, name: str, /) -> str | None: ... + def markDefaults(self) -> None: ... + def markOption(self, option: str, choice: str, /) -> int: ... + def nondefaultsMarked(self) -> bool: ... + def writeFd(self, fd: int, /) -> None: ... + +def connectDest( + dest: Dest, cb: Callable[[_T, int, Dest], Literal[0, 1]], flags: int = 0, msec: int = -1, user_data: _T = ... +) -> tuple[Connection, str]: ... +def enumDests( + cb: Callable[[_T, int, Dest], Literal[0, 1]], + flags: int = 0, + msec: int = -1, + type: int = 0, + mask: int = 0, + user_data: _T = ..., +) -> None: ... +def getEncryption() -> int: ... +def getPort() -> int: ... +def getServer() -> str: ... +def getUser() -> str: ... +def ippErrorString(status_code: int, /) -> str: ... +def ippOpString(op: int, /) -> str: ... +def modelSort(s1: str, s2: str, /) -> Literal[-1, 0, 1]: ... +def ppdSetConformance(level: int, /) -> None: ... +def require(version: str, /) -> None: ... +def setEncryption(policy: int, /) -> None: ... +def setPasswordCB(fn: Callable[[str], str | None], /) -> None: ... + +@overload +def setPasswordCB2(fn: Callable[[str, Connection, str, str], str | None] | None, /) -> None: ... +@overload +def setPasswordCB2(fn: Callable[[str, Connection, str, str, _T], str | None], context: _T = ..., /) -> None: ... + +def setPort(port: int, /) -> None: ... +def setServer(server: str, /) -> None: ... +def setUser(user: str, /) -> None: ... diff --git a/stubs/pycurl/@tests/stubtest_allowlist.txt b/stubs/pycurl/@tests/stubtest_allowlist.txt index d4ba5cd3d50e..5db17c304cd3 100644 --- a/stubs/pycurl/@tests/stubtest_allowlist.txt +++ b/stubs/pycurl/@tests/stubtest_allowlist.txt @@ -1 +1,3 @@ -pycurl +# The runtime computes __all__ dynamically (dir(_pycurl) + AsyncCurlMulti), so +# its exact contents depend on the libcurl feature set pycurl was built against. +pycurl.__all__ diff --git a/stubs/pycurl/METADATA.toml b/stubs/pycurl/METADATA.toml index fafbc99588cb..a55af894295f 100644 --- a/stubs/pycurl/METADATA.toml +++ b/stubs/pycurl/METADATA.toml @@ -1 +1,5 @@ -version = "7.44.*" +version = "7.48.0" +upstream-repository = "https://github.com/pycurl/pycurl" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] diff --git a/stubs/pycurl/pycurl.pyi b/stubs/pycurl/pycurl.pyi deleted file mode 100644 index f69b2b6c0060..000000000000 --- a/stubs/pycurl/pycurl.pyi +++ /dev/null @@ -1,644 +0,0 @@ -# TODO(MichalPokorny): more precise types - -from typing import Any, Text, Tuple - -GLOBAL_ACK_EINTR: int -GLOBAL_ALL: int -GLOBAL_DEFAULT: int -GLOBAL_NOTHING: int -GLOBAL_SSL: int -GLOBAL_WIN32: int - -def global_init(option: int) -> None: ... -def global_cleanup() -> None: ... - -version: str - -def version_info() -> tuple[int, str, int, str, int, str, int, str, Tuple[str, ...], Any, int, Any]: ... - -class error(Exception): ... - -class Curl(object): - def close(self) -> None: ... - def setopt(self, option: int, value: Any) -> None: ... - def setopt_string(self, option: int, value: str) -> None: ... - def perform(self) -> None: ... - def perform_rb(self) -> bytes: ... - def perform_rs(self) -> Text: ... - def getinfo(self, info: Any) -> Any: ... - def getinfo_raw(self, info: Any) -> Any: ... - def reset(self) -> None: ... - def unsetopt(self, option: int) -> Any: ... - def pause(self, bitmask: Any) -> Any: ... - def errstr(self) -> str: ... - # TODO(MichalPokorny): wat? - USERPWD: int - -class CurlMulti(object): - def close(self) -> None: ... - def add_handle(self, obj: Curl) -> None: ... - def remove_handle(self, obj: Curl) -> None: ... - def perform(self) -> tuple[Any, int]: ... - def fdset(self) -> tuple[list[Any], list[Any], list[Any]]: ... - def select(self, timeout: float = ...) -> int: ... - def info_read(self, max_objects: int = ...) -> tuple[int, list[Any], list[Any]]: ... - def socket_action(self, sockfd: int, ev_bitmask: int) -> tuple[int, int]: ... - -class CurlShare(object): - def close(self) -> None: ... - def setopt(self, option: int, value: Any) -> Any: ... - -ACCEPTTIMEOUT_MS: int -ACCEPT_ENCODING: int -ADDRESS_SCOPE: int -APPCONNECT_TIME: int -APPEND: int -AUTOREFERER: int -BUFFERSIZE: int -CAINFO: int -CAPATH: int -CLOSESOCKETFUNCTION: int -COMPILE_LIBCURL_VERSION_NUM: int -COMPILE_PY_VERSION_HEX: int -CONDITION_UNMET: int -CONNECTTIMEOUT: int -CONNECTTIMEOUT_MS: int -CONNECT_ONLY: int -CONNECT_TIME: int -CONNECT_TO: int -CONTENT_LENGTH_DOWNLOAD: int -CONTENT_LENGTH_UPLOAD: int -CONTENT_TYPE: int -COOKIE: int -COOKIEFILE: int -COOKIEJAR: int -COOKIELIST: int -COOKIESESSION: int -COPYPOSTFIELDS: int -CRLF: int -CRLFILE: int -CSELECT_ERR: int -CSELECT_IN: int -CSELECT_OUT: int -CURL_HTTP_VERSION_1_0: int -CURL_HTTP_VERSION_1_1: int -CURL_HTTP_VERSION_2: int -CURL_HTTP_VERSION_2_0: int -CURL_HTTP_VERSION_LAST: int -CURL_HTTP_VERSION_NONE: int -CUSTOMREQUEST: int -DEBUGFUNCTION: int -DEFAULT_PROTOCOL: int -DIRLISTONLY: int -DNS_CACHE_TIMEOUT: int -DNS_SERVERS: int -DNS_USE_GLOBAL_CACHE: int -EFFECTIVE_URL: int -EGDSOCKET: int -ENCODING: int -EXPECT_100_TIMEOUT_MS: int -FAILONERROR: int -FILE: int -FOLLOWLOCATION: int -FORBID_REUSE: int -FORM_BUFFER: int -FORM_BUFFERPTR: int -FORM_CONTENTS: int -FORM_CONTENTTYPE: int -FORM_FILE: int -FORM_FILENAME: int -FRESH_CONNECT: int -FTPAPPEND: int -FTPAUTH_DEFAULT: int -FTPAUTH_SSL: int -FTPAUTH_TLS: int -FTPLISTONLY: int -FTPMETHOD_DEFAULT: int -FTPMETHOD_MULTICWD: int -FTPMETHOD_NOCWD: int -FTPMETHOD_SINGLECWD: int -FTPPORT: int -FTPSSLAUTH: int -FTPSSL_ALL: int -FTPSSL_CONTROL: int -FTPSSL_NONE: int -FTPSSL_TRY: int -FTP_ACCOUNT: int -FTP_ALTERNATIVE_TO_USER: int -FTP_CREATE_MISSING_DIRS: int -FTP_ENTRY_PATH: int -FTP_FILEMETHOD: int -FTP_RESPONSE_TIMEOUT: int -FTP_SKIP_PASV_IP: int -FTP_SSL: int -FTP_SSL_CCC: int -FTP_USE_EPRT: int -FTP_USE_EPSV: int -FTP_USE_PRET: int -GSSAPI_DELEGATION: int -GSSAPI_DELEGATION_FLAG: int -GSSAPI_DELEGATION_NONE: int -GSSAPI_DELEGATION_POLICY_FLAG: int -HEADER: int -HEADERFUNCTION: int -HEADEROPT: int -HEADER_SEPARATE: int -HEADER_SIZE: int -HEADER_UNIFIED: int -HTTP200ALIASES: int -HTTPAUTH: int -HTTPAUTH_ANY: int -HTTPAUTH_ANYSAFE: int -HTTPAUTH_AVAIL: int -HTTPAUTH_BASIC: int -HTTPAUTH_DIGEST: int -HTTPAUTH_DIGEST_IE: int -HTTPAUTH_GSSNEGOTIATE: int -HTTPAUTH_NEGOTIATE: int -HTTPAUTH_NONE: int -HTTPAUTH_NTLM: int -HTTPAUTH_NTLM_WB: int -HTTPAUTH_ONLY: int -HTTPGET: int -HTTPHEADER: int -HTTPPOST: int -HTTPPROXYTUNNEL: int -HTTP_CODE: int -HTTP_CONNECTCODE: int -HTTP_CONTENT_DECODING: int -HTTP_TRANSFER_DECODING: int -HTTP_VERSION: int -IGNORE_CONTENT_LENGTH: int -INFILE: int -INFILESIZE: int -INFILESIZE_LARGE: int -INFOTYPE_DATA_IN: int -INFOTYPE_DATA_OUT: int -INFOTYPE_HEADER_IN: int -INFOTYPE_HEADER_OUT: int -INFOTYPE_SSL_DATA_IN: int -INFOTYPE_SSL_DATA_OUT: int -INFOTYPE_TEXT: int -INFO_CERTINFO: int -INFO_COOKIELIST: int -INFO_FILETIME: int -INFO_HTTP_VERSION: int -INFO_RTSP_CLIENT_CSEQ: int -INFO_RTSP_CSEQ_RECV: int -INFO_RTSP_SERVER_CSEQ: int -INFO_RTSP_SESSION_ID: int -INTERFACE: int -IOCMD_NOP: int -IOCMD_RESTARTREAD: int -IOCTLFUNCTION: int -IOE_FAILRESTART: int -IOE_OK: int -IOE_UNKNOWNCMD: int -IPRESOLVE: int -IPRESOLVE_V4: int -IPRESOLVE_V6: int -IPRESOLVE_WHATEVER: int -ISSUERCERT: int -KEYPASSWD: int -KHMATCH_MISMATCH: int -KHMATCH_MISSING: int -KHMATCH_OK: int -KHSTAT_DEFER: int -KHSTAT_FINE: int -KHSTAT_FINE_ADD_TO_FILE: int -KHSTAT_REJECT: int -KHTYPE_DSS: int -KHTYPE_RSA: int -KHTYPE_RSA1: int -KHTYPE_UNKNOWN: int -KRB4LEVEL: int -KRBLEVEL: int -LASTSOCKET: int -LOCALPORT: int -LOCALPORTRANGE: int -LOCAL_IP: int -LOCAL_PORT: int -LOCK_DATA_COOKIE: int -LOCK_DATA_DNS: int -LOCK_DATA_SSL_SESSION: int -LOGIN_OPTIONS: int -LOW_SPEED_LIMIT: int -LOW_SPEED_TIME: int -MAIL_AUTH: int -MAIL_FROM: int -MAIL_RCPT: int -MAXCONNECTS: int -MAXFILESIZE: int -MAXFILESIZE_LARGE: int -MAXREDIRS: int -MAX_RECV_SPEED_LARGE: int -MAX_SEND_SPEED_LARGE: int -M_CHUNK_LENGTH_PENALTY_SIZE: int -M_CONTENT_LENGTH_PENALTY_SIZE: int -M_MAXCONNECTS: int -M_MAX_HOST_CONNECTIONS: int -M_MAX_PIPELINE_LENGTH: int -M_MAX_TOTAL_CONNECTIONS: int -M_PIPELINING: int -M_PIPELINING_SERVER_BL: int -M_PIPELINING_SITE_BL: int -M_SOCKETFUNCTION: int -M_TIMERFUNCTION: int -NAMELOOKUP_TIME: int -NETRC: int -NETRC_FILE: int -NETRC_IGNORED: int -NETRC_OPTIONAL: int -NETRC_REQUIRED: int -NEW_DIRECTORY_PERMS: int -NEW_FILE_PERMS: int -NOBODY: int -NOPROGRESS: int -NOPROXY: int -NOSIGNAL: int -NUM_CONNECTS: int -OPENSOCKETFUNCTION: int -OPT_CERTINFO: int -OPT_COOKIELIST: int -OPT_FILETIME: int -OPT_RTSP_CLIENT_CSEQ: int -OPT_RTSP_REQUEST: int -OPT_RTSP_SERVER_CSEQ: int -OPT_RTSP_SESSION_ID: int -OPT_RTSP_STREAM_URI: int -OPT_RTSP_TRANSPORT: int -OS_ERRNO: int -PASSWORD: int -PATH_AS_IS: int -PAUSE_ALL: int -PAUSE_CONT: int -PAUSE_RECV: int -PAUSE_SEND: int -PINNEDPUBLICKEY: int -PIPEWAIT: int -PIPE_MULTIPLEX: int -PIPE_NOTHING: int -POLL_IN: int -POLL_INOUT: int -POLL_NONE: int -POLL_OUT: int -POLL_REMOVE: int -PORT: int -POST: int -POST301: int -POSTFIELDS: int -POSTFIELDSIZE: int -POSTFIELDSIZE_LARGE: int -POSTQUOTE: int -POSTREDIR: int -PREQUOTE: int -PRETRANSFER_TIME: int -PRE_PROXY: int -PRIMARY_IP: int -PRIMARY_PORT: int -PROGRESSFUNCTION: int -PROTOCOLS: int -PROTO_ALL: int -PROTO_DICT: int -PROTO_FILE: int -PROTO_FTP: int -PROTO_FTPS: int -PROTO_GOPHER: int -PROTO_HTTP: int -PROTO_HTTPS: int -PROTO_IMAP: int -PROTO_IMAPS: int -PROTO_LDAP: int -PROTO_LDAPS: int -PROTO_POP3: int -PROTO_POP3S: int -PROTO_RTMP: int -PROTO_RTMPE: int -PROTO_RTMPS: int -PROTO_RTMPT: int -PROTO_RTMPTE: int -PROTO_RTMPTS: int -PROTO_RTSP: int -PROTO_SCP: int -PROTO_SFTP: int -PROTO_SMB: int -PROTO_SMBS: int -PROTO_SMTP: int -PROTO_SMTPS: int -PROTO_TELNET: int -PROTO_TFTP: int -PROXY: int -PROXYAUTH: int -PROXYAUTH_AVAIL: int -PROXYHEADER: int -PROXYPASSWORD: int -PROXYPORT: int -PROXYTYPE: int -PROXYTYPE_HTTP: int -PROXYTYPE_HTTP_1_0: int -PROXYTYPE_SOCKS4: int -PROXYTYPE_SOCKS4A: int -PROXYTYPE_SOCKS5: int -PROXYTYPE_SOCKS5_HOSTNAME: int -PROXYUSERNAME: int -PROXYUSERPWD: int -PROXY_CAINFO: int -PROXY_CAPATH: int -PROXY_SERVICE_NAME: int -PROXY_SSLCERT: int -PROXY_SSLCERTTYPE: int -PROXY_SSLKEY: int -PROXY_SSLKEYTYPE: int -PROXY_SSL_VERIFYHOST: int -PROXY_SSL_VERIFYPEER: int -PROXY_TRANSFER_MODE: int -PUT: int -QUOTE: int -RANDOM_FILE: int -RANGE: int -READDATA: int -READFUNCTION: int -READFUNC_ABORT: int -READFUNC_PAUSE: int -REDIRECT_COUNT: int -REDIRECT_TIME: int -REDIRECT_URL: int -REDIR_POST_301: int -REDIR_POST_302: int -REDIR_POST_303: int -REDIR_POST_ALL: int -REDIR_PROTOCOLS: int -REFERER: int -REQUEST_SIZE: int -RESOLVE: int -RESPONSE_CODE: int -RESUME_FROM: int -RESUME_FROM_LARGE: int -RTSPREQ_ANNOUNCE: int -RTSPREQ_DESCRIBE: int -RTSPREQ_GET_PARAMETER: int -RTSPREQ_LAST: int -RTSPREQ_NONE: int -RTSPREQ_OPTIONS: int -RTSPREQ_PAUSE: int -RTSPREQ_PLAY: int -RTSPREQ_RECEIVE: int -RTSPREQ_RECORD: int -RTSPREQ_SETUP: int -RTSPREQ_SET_PARAMETER: int -RTSPREQ_TEARDOWN: int -SASL_IR: int -SEEKFUNCTION: int -SEEKFUNC_CANTSEEK: int -SEEKFUNC_FAIL: int -SEEKFUNC_OK: int -SERVICE_NAME: int -SHARE: int -SH_SHARE: int -SH_UNSHARE: int -SIZE_DOWNLOAD: int -SIZE_UPLOAD: int -SOCKET_BAD: int -SOCKET_TIMEOUT: int -SOCKOPTFUNCTION: int -SOCKOPT_ALREADY_CONNECTED: int -SOCKOPT_ERROR: int -SOCKOPT_OK: int -SOCKS5_GSSAPI_NEC: int -SOCKS5_GSSAPI_SERVICE: int -SOCKTYPE_ACCEPT: int -SOCKTYPE_IPCXN: int -SPEED_DOWNLOAD: int -SPEED_UPLOAD: int -SSH_AUTH_AGENT: int -SSH_AUTH_ANY: int -SSH_AUTH_DEFAULT: int -SSH_AUTH_HOST: int -SSH_AUTH_KEYBOARD: int -SSH_AUTH_NONE: int -SSH_AUTH_PASSWORD: int -SSH_AUTH_PUBLICKEY: int -SSH_AUTH_TYPES: int -SSH_HOST_PUBLIC_KEY_MD5: int -SSH_KEYFUNCTION: int -SSH_KNOWNHOSTS: int -SSH_PRIVATE_KEYFILE: int -SSH_PUBLIC_KEYFILE: int -SSLCERT: int -SSLCERTPASSWD: int -SSLCERTTYPE: int -SSLENGINE: int -SSLENGINE_DEFAULT: int -SSLKEY: int -SSLKEYPASSWD: int -SSLKEYTYPE: int -SSLOPT_ALLOW_BEAST: int -SSLOPT_NO_REVOKE: int -SSLVERSION: int -SSLVERSION_DEFAULT: int -SSLVERSION_SSLv2: int -SSLVERSION_SSLv3: int -SSLVERSION_TLSv1: int -SSLVERSION_TLSv1_0: int -SSLVERSION_TLSv1_1: int -SSLVERSION_TLSv1_2: int -SSLVERSION_MAX_DEFAULT: int -SSL_CIPHER_LIST: int -SSL_ENABLE_ALPN: int -SSL_ENABLE_NPN: int -SSL_ENGINES: int -SSL_FALSESTART: int -SSL_OPTIONS: int -SSL_SESSIONID_CACHE: int -SSL_VERIFYHOST: int -SSL_VERIFYPEER: int -SSL_VERIFYRESULT: int -SSL_VERIFYSTATUS: int -STARTTRANSFER_TIME: int -STDERR: int -TCP_FASTOPEN: int -TCP_KEEPALIVE: int -TCP_KEEPIDLE: int -TCP_KEEPINTVL: int -TCP_NODELAY: int -TELNETOPTIONS: int -TFTP_BLKSIZE: int -TIMECONDITION: int -TIMECONDITION_IFMODSINCE: int -TIMECONDITION_IFUNMODSINCE: int -TIMECONDITION_LASTMOD: int -TIMECONDITION_NONE: int -TIMEOUT: int -TIMEOUT_MS: int -TIMEVALUE: int -TLSAUTH_PASSWORD: int -TLSAUTH_TYPE: int -TLSAUTH_USERNAME: int -TOTAL_TIME: int -TRANSFERTEXT: int -TRANSFER_ENCODING: int -UNIX_SOCKET_PATH: int -UNRESTRICTED_AUTH: int -UPLOAD: int -URL: int -USERAGENT: int -USERNAME: int -USERPWD: int -USESSL_ALL: int -USESSL_CONTROL: int -USESSL_NONE: int -USESSL_TRY: int -USE_SSL: int -VERBOSE: int -VERSION_ASYNCHDNS: int -VERSION_CONV: int -VERSION_CURLDEBUG: int -VERSION_DEBUG: int -VERSION_FIRST: int -VERSION_GSSAPI: int -VERSION_GSSNEGOTIATE: int -VERSION_HTTP2: int -VERSION_IDN: int -VERSION_IPV6: int -VERSION_KERBEROS4: int -VERSION_KERBEROS5: int -VERSION_LARGEFILE: int -VERSION_LIBZ: int -VERSION_NTLM: int -VERSION_NTLM_WB: int -VERSION_PSL: int -VERSION_SPNEGO: int -VERSION_SSL: int -VERSION_SSPI: int -VERSION_TLSAUTH_SRP: int -VERSION_UNIX_SOCKETS: int -WILDCARDMATCH: int -WRITEDATA: int -WRITEFUNCTION: int -WRITEFUNC_PAUSE: int -WRITEHEADER: int -XFERINFOFUNCTION: int -XOAUTH2_BEARER: int - -E_ABORTED_BY_CALLBACK: int -E_AGAIN: int -E_ALREADY_COMPLETE: int -E_BAD_CALLING_ORDER: int -E_BAD_CONTENT_ENCODING: int -E_BAD_DOWNLOAD_RESUME: int -E_BAD_FUNCTION_ARGUMENT: int -E_BAD_PASSWORD_ENTERED: int -E_CALL_MULTI_PERFORM: int -E_CHUNK_FAILED: int -E_CONV_FAILED: int -E_CONV_REQD: int -E_COULDNT_CONNECT: int -E_COULDNT_RESOLVE_HOST: int -E_COULDNT_RESOLVE_PROXY: int -E_FAILED_INIT: int -E_FILESIZE_EXCEEDED: int -E_FILE_COULDNT_READ_FILE: int -E_FTP_ACCEPT_FAILED: int -E_FTP_ACCEPT_TIMEOUT: int -E_FTP_ACCESS_DENIED: int -E_FTP_BAD_DOWNLOAD_RESUME: int -E_FTP_BAD_FILE_LIST: int -E_FTP_CANT_GET_HOST: int -E_FTP_CANT_RECONNECT: int -E_FTP_COULDNT_GET_SIZE: int -E_FTP_COULDNT_RETR_FILE: int -E_FTP_COULDNT_SET_ASCII: int -E_FTP_COULDNT_SET_BINARY: int -E_FTP_COULDNT_SET_TYPE: int -E_FTP_COULDNT_STOR_FILE: int -E_FTP_COULDNT_USE_REST: int -E_FTP_PARTIAL_FILE: int -E_FTP_PORT_FAILED: int -E_FTP_PRET_FAILED: int -E_FTP_QUOTE_ERROR: int -E_FTP_SSL_FAILED: int -E_FTP_USER_PASSWORD_INCORRECT: int -E_FTP_WEIRD_227_FORMAT: int -E_FTP_WEIRD_PASS_REPLY: int -E_FTP_WEIRD_PASV_REPLY: int -E_FTP_WEIRD_SERVER_REPLY: int -E_FTP_WEIRD_USER_REPLY: int -E_FTP_WRITE_ERROR: int -E_FUNCTION_NOT_FOUND: int -E_GOT_NOTHING: int -E_HTTP2: int -E_HTTP_NOT_FOUND: int -E_HTTP_PORT_FAILED: int -E_HTTP_POST_ERROR: int -E_HTTP_RANGE_ERROR: int -E_HTTP_RETURNED_ERROR: int -E_INTERFACE_FAILED: int -E_LDAP_CANNOT_BIND: int -E_LDAP_INVALID_URL: int -E_LDAP_SEARCH_FAILED: int -E_LIBRARY_NOT_FOUND: int -E_LOGIN_DENIED: int -E_MALFORMAT_USER: int -E_MULTI_ADDED_ALREADY: int -E_MULTI_BAD_EASY_HANDLE: int -E_MULTI_BAD_HANDLE: int -E_MULTI_BAD_SOCKET: int -E_MULTI_CALL_MULTI_PERFORM: int -E_MULTI_CALL_MULTI_SOCKET: int -E_MULTI_INTERNAL_ERROR: int -E_MULTI_OK: int -E_MULTI_OUT_OF_MEMORY: int -E_MULTI_UNKNOWN_OPTION: int -E_NOT_BUILT_IN: int -E_NO_CONNECTION_AVAILABLE: int -E_OK: int -E_OPERATION_TIMEDOUT: int -E_OPERATION_TIMEOUTED: int -E_OUT_OF_MEMORY: int -E_PARTIAL_FILE: int -E_PEER_FAILED_VERIFICATION: int -E_QUOTE_ERROR: int -E_RANGE_ERROR: int -E_READ_ERROR: int -E_RECV_ERROR: int -E_REMOTE_ACCESS_DENIED: int -E_REMOTE_DISK_FULL: int -E_REMOTE_FILE_EXISTS: int -E_REMOTE_FILE_NOT_FOUND: int -E_RTSP_CSEQ_ERROR: int -E_RTSP_SESSION_ERROR: int -E_SEND_ERROR: int -E_SEND_FAIL_REWIND: int -E_SHARE_IN_USE: int -E_SSH: int -E_SSL_CACERT: int -E_SSL_CACERT_BADFILE: int -E_SSL_CERTPROBLEM: int -E_SSL_CIPHER: int -E_SSL_CONNECT_ERROR: int -E_SSL_CRL_BADFILE: int -E_SSL_ENGINE_INITFAILED: int -E_SSL_ENGINE_NOTFOUND: int -E_SSL_ENGINE_SETFAILED: int -E_SSL_INVALIDCERTSTATUS: int -E_SSL_ISSUER_ERROR: int -E_SSL_PEER_CERTIFICATE: int -E_SSL_PINNEDPUBKEYNOTMATCH: int -E_SSL_SHUTDOWN_FAILED: int -E_TELNET_OPTION_SYNTAX: int -E_TFTP_DISKFULL: int -E_TFTP_EXISTS: int -E_TFTP_ILLEGAL: int -E_TFTP_NOSUCHUSER: int -E_TFTP_NOTFOUND: int -E_TFTP_PERM: int -E_TFTP_UNKNOWNID: int -E_TOO_MANY_REDIRECTS: int -E_UNKNOWN_OPTION: int -E_UNKNOWN_TELNET_OPTION: int -E_UNSUPPORTED_PROTOCOL: int -E_UPLOAD_FAILED: int -E_URL_MALFORMAT: int -E_URL_MALFORMAT_USER: int -E_USE_SSL_FAILED: int -E_WRITE_ERROR: int diff --git a/stubs/pycurl/pycurl/__init__.pyi b/stubs/pycurl/pycurl/__init__.pyi new file mode 100644 index 000000000000..43856c3618eb --- /dev/null +++ b/stubs/pycurl/pycurl/__init__.pyi @@ -0,0 +1,2 @@ +from pycurl._pycurl import * +from pycurl.async_multi import AsyncCurlMulti as AsyncCurlMulti diff --git a/stubs/pycurl/pycurl/_pycurl.pyi b/stubs/pycurl/pycurl/_pycurl.pyi new file mode 100644 index 000000000000..1c021a37c23a --- /dev/null +++ b/stubs/pycurl/pycurl/_pycurl.pyi @@ -0,0 +1,1056 @@ +# Stub for the pycurl C extension (imported at runtime as `pycurl._pycurl`). +import sys +from _typeshed import ReadableBuffer, Unused, WriteableBuffer +from collections.abc import Callable +from datetime import datetime +from types import TracebackType +from typing import Any, Final, Literal, NamedTuple +from typing_extensions import Self, disjoint_base + +version: str + +def global_init(option: int) -> None: ... +def global_cleanup() -> None: ... +def version_info( + stamp: int = ..., +) -> tuple[int, str, int, str, int, str, int, str, tuple[str, ...], str | None, int, str | None]: ... +def easy_strerror(errornum: int) -> str: ... +def multi_strerror(errornum: int) -> str: ... +def share_strerror(errornum: int) -> str: ... +def url_strerror(errornum: int) -> str: ... + +class error(Exception): + # libcurl protocol errors raise (code, message); arg-parse errors raise (message,). + args: tuple[int, str] | tuple[str] + +class WsFrame(NamedTuple): + age: int + flags: int + offset: int + bytesleft: int + len: int + +class HstsEntry(NamedTuple): + host: bytes + expire: datetime | None + include_subdomains: bool + +class HstsIndex(NamedTuple): + idx: int + total: int + +class KhKey(NamedTuple): + key: bytes + keytype: int + +class CurlSockAddr(NamedTuple): + family: int + socktype: int + protocol: int + addr: tuple[str, int] | tuple[str, int, int, int] | bytes + +@disjoint_base +class Curl: + USERPWD: int + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + # For `setopt()` the exact `value` type depends on the passed `option`; `None` used to unassign: + # http://pycurl.io/docs/latest/curlobject.html#pycurl.Curl.setopt + def setopt(self, option: int, value: Any | None, *, use_memoryview: bool = False) -> None: ... + def setopt_string(self, option: int, value: str) -> None: ... + def perform(self) -> None: ... + def perform_rb(self) -> bytes: ... + def perform_rs(self) -> str: ... + # For getinfo and getinfo_raw, the exact return type depends on the passed value: + # http://pycurl.io/docs/latest/curlobject.html#pycurl.Curl.getinfo + def getinfo(self, info: int) -> Any: ... + def getinfo_raw(self, info: int) -> Any: ... + def reset(self) -> None: ... + def unsetopt(self, option: int) -> None: ... + def pause(self, bitmask: int = ...) -> None: ... + def unpause(self) -> None: ... + def errstr(self) -> str: ... + def duphandle(self) -> Self: ... + def errstr_raw(self) -> bytes: ... + def multi(self) -> CurlMulti | None: ... + def share(self) -> CurlShare | None: ... + def recv(self, buffersize: int, /) -> bytes: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int = 0) -> int: ... + def send(self, data: ReadableBuffer, /) -> int: ... + def ws_send( + self, data: ReadableBuffer | str, flags: int | None = None, fragsize: int = 0, encoding: str = "utf-8" + ) -> int: ... + def ws_recv(self, buffersize: int, /) -> tuple[bytes, WsFrame]: ... + def ws_recv_into(self, buffer: WriteableBuffer, nbytes: int = 0) -> tuple[int, WsFrame]: ... + def ws_meta(self) -> WsFrame | None: ... + def ws_close(self, code: int | None = None, reason: ReadableBuffer | str | None = None, encoding: str = "utf-8") -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + if sys.platform == "linux" or sys.platform == "darwin": + def set_ca_certs(self, value: str | bytes, /) -> None: ... + +@disjoint_base +class CurlMulti: + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def add_handle(self, obj: Curl) -> None: ... + def remove_handle(self, obj: Curl) -> None: ... + def setopt( + self, + option: int, + value: ( + bool + | int + | list[str | bytes] + | tuple[str | bytes, ...] + | Callable[[int], Literal[-1, 0] | None] + | Callable[[int, int, Self, Any | None], Literal[-1, 0] | None] # See `assign()` below for `Any | None` + | Callable[[int, Curl | None], object] # `M_NOTIFYFUNCTION` (notify) callback; return value ignored + | None + ), + ) -> None: ... + def perform(self) -> tuple[int, int]: ... + def fdset(self) -> tuple[list[int], list[int], list[int]]: ... + def select(self, timeout: float) -> int: ... + def info_read(self, max_objects: int = ...) -> tuple[int, list[Curl], list[tuple[Curl, int, str]]]: ... + def socket_action(self, sockfd: int, ev_bitmask: int) -> tuple[int, int]: ... + # `assign()` accepts literally any object, it's only passed to callbacks and not processed; `None` used to unassign + def assign(self, sockfd: int, obj: Any | None, /) -> None: ... + def unassign(self, sock_fd: int, /) -> None: ... + def notify_enable(self, *notifications: int) -> None: ... + def notify_disable(self, *notifications: int) -> None: ... + def socket_all(self) -> tuple[int, int]: ... + def timeout(self) -> int: ... + def __contains__(self, key: Curl, /) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +@disjoint_base +class CurlShare: + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + # Currently this `setopt()` is very limited; `None` to unset is also not accepted: + # http://pycurl.io/docs/latest/curlshareobject.html#pycurl.CurlShare.setopt + def setopt(self, option: int, value: int) -> None: ... + def share(self, *lock_data: int) -> None: ... + def unshare(self, *lock_data: int) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +@disjoint_base +class CurlMime: + def __new__(cls, curl: Curl) -> Self: ... + def add( + self, + name: str | bytes | None = None, + data: ReadableBuffer | str | None = None, + file: str | bytes | None = None, + filename: str | bytes | None = None, + content_type: str | bytes | None = None, + headers: list[str | bytes] | tuple[str | bytes, ...] | None = None, + encoder: str | bytes | None = None, + ) -> CurlMimePart: ... + def add_field( + self, + name: str | bytes, + value: str | bytes, + content_type: str | bytes | None = None, + encoder: str | bytes | None = None, + headers: list[str | bytes] | tuple[str | bytes, ...] | None = None, + ) -> CurlMimePart: ... + def add_file( + self, + name: str | bytes, + path: str | bytes, + filename: str | bytes | None = None, + content_type: str | bytes | None = None, + headers: list[str | bytes] | tuple[str | bytes, ...] | None = None, + encoder: str | bytes | None = None, + ) -> CurlMimePart: ... + def add_multipart(self, name: str | bytes | None = None, subtype: str | bytes | None = None) -> CurlMime: ... + def addpart(self) -> CurlMimePart: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +@disjoint_base +class CurlMimePart: + def name(self, name: str | bytes, /) -> None: ... + def data(self, data: ReadableBuffer | str, /) -> None: ... + def data_cb( + self, + datasize: int | None, + read: Callable[[Any, int], ReadableBuffer | str | int], + seek: Callable[[Any, int, int], int | None] | None = None, + free: Callable[[Any], object] | None = None, + userdata: Any = None, + ) -> None: ... + def filedata(self, path: str | bytes, /) -> None: ... + def filename(self, name: str | bytes, /) -> None: ... + def type(self, content_type: str | bytes, /) -> None: ... + def encoder(self, name: str | bytes, /) -> None: ... + def headers(self, headers: list[str | bytes] | tuple[str | bytes, ...] | None, /) -> None: ... + def subparts(self, mime: CurlMime, /) -> None: ... + +@disjoint_base +class CurlUrl: + def __new__(cls, url: str | bytes | None = None, flags: int = 0) -> Self: ... + def getpart(self, part: int, flags: int = 0, /) -> str | None: ... + def setpart(self, part: int, value: str | bytes | None, flags: int = 0, /) -> None: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Unused, /) -> Self: ... + + @property + def url(self) -> str | None: ... + @url.setter + def url(self, value: str | bytes | None) -> None: ... + @url.deleter + def url(self) -> None: ... + + @property + def scheme(self) -> str | None: ... + @scheme.setter + def scheme(self, value: str | bytes | None) -> None: ... + @scheme.deleter + def scheme(self) -> None: ... + + @property + def user(self) -> str | None: ... + @user.setter + def user(self, value: str | bytes | None) -> None: ... + @user.deleter + def user(self) -> None: ... + + @property + def password(self) -> str | None: ... + @password.setter + def password(self, value: str | bytes | None) -> None: ... + @password.deleter + def password(self) -> None: ... + + @property + def options(self) -> str | None: ... + @options.setter + def options(self, value: str | bytes | None) -> None: ... + @options.deleter + def options(self) -> None: ... + + @property + def host(self) -> str | None: ... + @host.setter + def host(self, value: str | bytes | None) -> None: ... + @host.deleter + def host(self) -> None: ... + + @property + def port(self) -> str | None: ... + @port.setter + def port(self, value: str | bytes | int | None) -> None: ... + @port.deleter + def port(self) -> None: ... + + @property + def path(self) -> str | None: ... + @path.setter + def path(self, value: str | bytes | None) -> None: ... + @path.deleter + def path(self) -> None: ... + + @property + def query(self) -> str | None: ... + @query.setter + def query(self, value: str | bytes | None) -> None: ... + @query.deleter + def query(self) -> None: ... + + @property + def fragment(self) -> str | None: ... + @fragment.setter + def fragment(self, value: str | bytes | None) -> None: ... + @fragment.deleter + def fragment(self) -> None: ... + + @property + def zoneid(self) -> str | None: ... + @zoneid.setter + def zoneid(self, value: str | bytes | None) -> None: ... + @zoneid.deleter + def zoneid(self) -> None: ... + +APPCONNECT_TIME_T: Final[int] = ... +CONNECT_TIME_T: Final[int] = ... +CONTENT_LENGTH_DOWNLOAD_T: Final[int] = ... +CONTENT_LENGTH_UPLOAD_T: Final[int] = ... +EARLYDATA_SENT_T: Final[int] = ... +FILETIME_T: Final[int] = ... +NAMELOOKUP_TIME_T: Final[int] = ... +POSTTRANSFER_TIME_T: Final[int] = ... +PRETRANSFER_TIME_T: Final[int] = ... +QUEUE_TIME_T: Final[int] = ... +REDIRECT_TIME_T: Final[int] = ... +SIZE_DOWNLOAD_T: Final[int] = ... +SIZE_UPLOAD_T: Final[int] = ... +SPEED_DOWNLOAD_T: Final[int] = ... +SPEED_UPLOAD_T: Final[int] = ... +STARTTRANSFER_TIME_T: Final[int] = ... +TOTAL_TIME_T: Final[int] = ... + +ACCEPTTIMEOUT_MS: Final = 212 +ACCEPT_ENCODING: Final = 10102 +ACTIVESOCKET: Final[int] +ADDRESS_SCOPE: Final = 171 +APPCONNECT_TIME: Final = 3145761 +APPEND: Final = 50 +AUTOREFERER: Final = 58 +AWS_SIGV4: Final = 10305 +BUFFERSIZE: Final = 98 +CAINFO: Final = 10065 +CAINFO_BLOB: Final = 40309 +CAPATH: Final = 10097 +CLOSESOCKETFUNCTION: Final = 20208 +COMPILE_LIBCURL_VERSION_NUM: Final[int] +COMPILE_PY_VERSION_HEX: Final[int] +COMPILE_SSL_LIB: Final[str] +CONDITION_UNMET: Final = 2097187 +CONNECTTIMEOUT: Final = 78 +CONNECTTIMEOUT_MS: Final = 156 +CONNECT_ONLY: Final = 141 +CONNECT_TIME: Final = 3145733 +CONNECT_TO: Final = 10243 +CONN_ID: Final[int] +CONTENT_LENGTH_DOWNLOAD: Final = 3145743 +CONTENT_LENGTH_UPLOAD: Final = 3145744 +CONTENT_TYPE: Final = 1048594 +COOKIE: Final = 10022 +COOKIEFILE: Final = 10031 +COOKIEJAR: Final = 10082 +COOKIELIST: Final = 10135 +COOKIESESSION: Final = 96 +COPYPOSTFIELDS: Final = 10165 +CRLF: Final = 27 +CRLFILE: Final = 10169 +CSELECT_ERR: Final = 4 +CSELECT_IN: Final = 1 +CSELECT_OUT: Final = 2 +CURLHSTS_ENABLE: Final[int] +CURLHSTS_READONLYFILE: Final[int] +CURLSTS_DONE: Final[int] +CURLSTS_FAIL: Final[int] +CURLSTS_OK: Final[int] +CURLU: Final[int] +CURL_HTTP_VERSION_1_0: Final = 1 +CURL_HTTP_VERSION_1_1: Final = 2 +CURL_HTTP_VERSION_2: Final = 3 +CURL_HTTP_VERSION_2TLS: Final = 4 +CURL_HTTP_VERSION_2_0: Final = 3 +CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE: Final = 5 +CURL_HTTP_VERSION_3: Final = 30 +CURL_HTTP_VERSION_3ONLY: Final = 31 +CURL_HTTP_VERSION_LAST: Final = 32 +CURL_HTTP_VERSION_NONE: Final = 0 +CURL_VERSION_ALTSVC: Final = 16777216 +CURL_VERSION_BROTLI: Final = 8388608 +CURL_VERSION_GSASL: Final = 536870912 +CURL_VERSION_HSTS: Final = 268435456 +CURL_VERSION_HTTP3: Final = 33554432 +CURL_VERSION_HTTPS_PROXY: Final = 2097152 +CURL_VERSION_MULTI_SSL: Final = 4194304 +CURL_VERSION_UNICODE: Final = 134217728 +CURL_VERSION_ZSTD: Final = 67108864 +CUSTOMREQUEST: Final = 10036 +DEBUGFUNCTION: Final = 20094 +DEFAULT_PROTOCOL: Final = 10238 +DIRLISTONLY: Final = 48 +DNS_CACHE_TIMEOUT: Final = 92 +DNS_SERVERS: Final = 10211 +DNS_USE_GLOBAL_CACHE: Final = 91 +DOH_URL: Final = 10279 +EFFECTIVE_URL: Final = 1048577 +EFFECTIVE_METHOD: Final = 1048634 +EGDSOCKET: Final = 10077 +ENCODING: Final = 10102 +EXPECT_100_TIMEOUT_MS: Final = 227 +E_ABORTED_BY_CALLBACK: Final = 42 +E_AGAIN: Final = 81 +E_ALREADY_COMPLETE: Final = 99999 +E_BAD_CALLING_ORDER: Final = 44 +E_BAD_CONTENT_ENCODING: Final = 61 +E_BAD_DOWNLOAD_RESUME: Final = 36 +E_BAD_FUNCTION_ARGUMENT: Final = 43 +E_BAD_PASSWORD_ENTERED: Final = 46 +E_CALL_MULTI_PERFORM: Final = -1 +E_CHUNK_FAILED: Final = 88 +E_CONV_FAILED: Final = 75 +E_CONV_REQD: Final = 76 +E_COULDNT_CONNECT: Final = 7 +E_COULDNT_RESOLVE_HOST: Final = 6 +E_COULDNT_RESOLVE_PROXY: Final = 5 +E_FAILED_INIT: Final = 2 +E_FILESIZE_EXCEEDED: Final = 63 +E_FILE_COULDNT_READ_FILE: Final = 37 +E_FTP_ACCEPT_FAILED: Final = 10 +E_FTP_ACCEPT_TIMEOUT: Final = 12 +E_FTP_ACCESS_DENIED: Final = 9 +E_FTP_BAD_DOWNLOAD_RESUME: Final = 36 +E_FTP_BAD_FILE_LIST: Final = 87 +E_FTP_CANT_GET_HOST: Final = 15 +E_FTP_CANT_RECONNECT: Final = 16 +E_FTP_COULDNT_GET_SIZE: Final = 32 +E_FTP_COULDNT_RETR_FILE: Final = 19 +E_FTP_COULDNT_SET_ASCII: Final = 29 +E_FTP_COULDNT_SET_BINARY: Final = 17 +E_FTP_COULDNT_SET_TYPE: Final = 17 +E_FTP_COULDNT_STOR_FILE: Final = 25 +E_FTP_COULDNT_USE_REST: Final = 31 +E_FTP_PARTIAL_FILE: Final = 18 +E_FTP_PORT_FAILED: Final = 30 +E_FTP_PRET_FAILED: Final = 84 +E_FTP_QUOTE_ERROR: Final = 21 +E_FTP_SSL_FAILED: Final = 64 +E_FTP_USER_PASSWORD_INCORRECT: Final = 10 +E_FTP_WEIRD_227_FORMAT: Final = 14 +E_FTP_WEIRD_PASS_REPLY: Final = 11 +E_FTP_WEIRD_PASV_REPLY: Final = 13 +E_FTP_WEIRD_SERVER_REPLY: Final = 8 +E_FTP_WEIRD_USER_REPLY: Final = 12 +E_FTP_WRITE_ERROR: Final = 20 +E_FUNCTION_NOT_FOUND: Final = 41 +E_GOT_NOTHING: Final = 52 +E_HTTP2: Final = 16 +E_HTTP_NOT_FOUND: Final = 22 +E_HTTP_PORT_FAILED: Final = 45 +E_HTTP_POST_ERROR: Final = 34 +E_HTTP_RANGE_ERROR: Final = 33 +E_HTTP_RETURNED_ERROR: Final = 22 +E_INTERFACE_FAILED: Final = 45 +E_LDAP_CANNOT_BIND: Final = 38 +E_LDAP_INVALID_URL: Final = 62 +E_LDAP_SEARCH_FAILED: Final = 39 +E_LIBRARY_NOT_FOUND: Final = 40 +E_LOGIN_DENIED: Final = 67 +E_MALFORMAT_USER: Final = 24 +E_MULTI_ADDED_ALREADY: Final = 7 +E_MULTI_BAD_EASY_HANDLE: Final = 2 +E_MULTI_BAD_HANDLE: Final = 1 +E_MULTI_BAD_SOCKET: Final = 5 +E_MULTI_CALL_MULTI_PERFORM: Final = -1 +E_MULTI_CALL_MULTI_SOCKET: Final = -1 +E_MULTI_INTERNAL_ERROR: Final = 4 +E_MULTI_OK: Final = 0 +E_MULTI_OUT_OF_MEMORY: Final = 3 +E_MULTI_UNKNOWN_OPTION: Final = 6 +E_NOT_BUILT_IN: Final = 4 +E_NO_CONNECTION_AVAILABLE: Final = 89 +E_OK: Final = 0 +E_OPERATION_TIMEDOUT: Final = 28 +E_OPERATION_TIMEOUTED: Final = 28 +E_OUT_OF_MEMORY: Final = 27 +E_PARTIAL_FILE: Final = 18 +E_PEER_FAILED_VERIFICATION: Final = 60 +E_QUOTE_ERROR: Final = 21 +E_RANGE_ERROR: Final = 33 +E_READ_ERROR: Final = 26 +E_RECV_ERROR: Final = 56 +E_REMOTE_ACCESS_DENIED: Final = 9 +E_REMOTE_DISK_FULL: Final = 70 +E_REMOTE_FILE_EXISTS: Final = 73 +E_REMOTE_FILE_NOT_FOUND: Final = 78 +E_RTSP_CSEQ_ERROR: Final = 85 +E_RTSP_SESSION_ERROR: Final = 86 +E_SEND_ERROR: Final = 55 +E_SEND_FAIL_REWIND: Final = 65 +E_SHARE_IN_USE: Final = 57 +E_SSH: Final = 79 +E_SSL_CACERT: Final = 60 +E_SSL_CACERT_BADFILE: Final = 77 +E_SSL_CERTPROBLEM: Final = 58 +E_SSL_CIPHER: Final = 59 +E_SSL_CONNECT_ERROR: Final = 35 +E_SSL_CRL_BADFILE: Final = 82 +E_SSL_ENGINE_INITFAILED: Final = 66 +E_SSL_ENGINE_NOTFOUND: Final = 53 +E_SSL_ENGINE_SETFAILED: Final = 54 +E_SSL_INVALIDCERTSTATUS: Final = 91 +E_SSL_ISSUER_ERROR: Final = 83 +E_SSL_PEER_CERTIFICATE: Final = 60 +E_SSL_PINNEDPUBKEYNOTMATCH: Final = 90 +E_SSL_SHUTDOWN_FAILED: Final = 80 +E_TELNET_OPTION_SYNTAX: Final = 49 +E_TFTP_DISKFULL: Final = 70 +E_TFTP_EXISTS: Final = 73 +E_TFTP_ILLEGAL: Final = 71 +E_TFTP_NOSUCHUSER: Final = 74 +E_TFTP_NOTFOUND: Final = 68 +E_TFTP_PERM: Final = 69 +E_TFTP_UNKNOWNID: Final = 72 +E_TOO_MANY_REDIRECTS: Final = 47 +E_UNKNOWN_OPTION: Final = 48 +E_UNKNOWN_TELNET_OPTION: Final = 48 +E_UNSUPPORTED_PROTOCOL: Final = 1 +E_UPLOAD_FAILED: Final = 25 +E_URL_MALFORMAT: Final = 3 +E_URL_MALFORMAT_USER: Final = 4 +E_USE_SSL_FAILED: Final = 64 +E_WRITE_ERROR: Final = 23 +FAILONERROR: Final = 45 +FILE: Final = 10001 +FNMATCHFUNC_FAIL: Final[int] +FNMATCHFUNC_MATCH: Final[int] +FNMATCHFUNC_NOMATCH: Final[int] +FNMATCH_DATA: Final[int] +FNMATCH_FUNCTION: Final[int] +FOLLOWLOCATION: Final = 52 +FORBID_REUSE: Final = 75 +FORM_BUFFER: Final = 11 +FORM_BUFFERPTR: Final = 12 +FORM_CONTENTS: Final = 4 +FORM_CONTENTTYPE: Final = 14 +FORM_FILE: Final = 10 +FORM_FILENAME: Final = 16 +FRESH_CONNECT: Final = 74 +FTPAPPEND: Final = 50 +FTPAUTH_DEFAULT: Final = 0 +FTPAUTH_SSL: Final = 1 +FTPAUTH_TLS: Final = 2 +FTPLISTONLY: Final = 48 +FTPMETHOD_DEFAULT: Final = 0 +FTPMETHOD_MULTICWD: Final = 1 +FTPMETHOD_NOCWD: Final = 2 +FTPMETHOD_SINGLECWD: Final = 3 +FTPPORT: Final = 10017 +FTPSSLAUTH: Final = 129 +FTPSSL_ALL: Final = 3 +FTPSSL_CONTROL: Final = 2 +FTPSSL_NONE: Final = 0 +FTPSSL_TRY: Final = 1 +FTP_ACCOUNT: Final = 10134 +FTP_ALTERNATIVE_TO_USER: Final = 10147 +FTP_CREATE_MISSING_DIRS: Final = 110 +FTP_ENTRY_PATH: Final = 1048606 +FTP_FILEMETHOD: Final = 138 +FTP_RESPONSE_TIMEOUT: Final = 112 +FTP_SKIP_PASV_IP: Final = 137 +FTP_SSL: Final = 119 +FTP_SSL_CCC: Final = 154 +FTP_USE_EPRT: Final = 106 +FTP_USE_EPSV: Final = 85 +FTP_USE_PRET: Final = 188 +GLOBAL_ACK_EINTR: Final = 4 +GLOBAL_ALL: Final = 3 +GLOBAL_DEFAULT: Final = 3 +GLOBAL_NOTHING: Final = 0 +GLOBAL_SSL: Final = 1 +GLOBAL_WIN32: Final = 2 +GSSAPI_DELEGATION: Final = 210 +GSSAPI_DELEGATION_FLAG: Final = 2 +GSSAPI_DELEGATION_NONE: Final = 0 +GSSAPI_DELEGATION_POLICY_FLAG: Final = 1 +HAPROXYPROTOCOL: Final = 274 +HAPROXY_CLIENT_IP: Final = 10323 +ECH: Final = 10325 +HEADER: Final = 42 +HEADERFUNCTION: Final = 20079 +HEADEROPT: Final = 229 +HEADER_SEPARATE: Final = 1 +HEADER_SIZE: Final = 2097163 +HEADER_UNIFIED: Final = 0 +HSTS: Final[int] +HSTSREADDATA: Final[int] +HSTSREADFUNCTION: Final[int] +HSTSWRITEDATA: Final[int] +HSTSWRITEFUNCTION: Final[int] +HSTS_CTRL: Final[int] +HTTP09_ALLOWED: Final = 285 +HTTP200ALIASES: Final = 10104 +HTTPAUTH: Final = 107 +HTTPAUTH_ANY: Final[int] +HTTPAUTH_ANYSAFE: Final[int] +HTTPAUTH_AVAIL: Final = 2097175 +HTTPAUTH_BASIC: Final = 1 +HTTPAUTH_DIGEST: Final = 2 +HTTPAUTH_DIGEST_IE: Final = 16 +HTTPAUTH_GSSNEGOTIATE: Final = 4 +HTTPAUTH_NEGOTIATE: Final = 4 +HTTPAUTH_NONE: Final = 0 +HTTPAUTH_NTLM: Final = 8 +HTTPAUTH_NTLM_WB: Final = 32 +HTTPAUTH_ONLY: Final[int] +HTTPGET: Final = 80 +HTTPHEADER: Final = 10023 +HTTPPOST: Final = 10024 +HTTPPROXYTUNNEL: Final = 61 +HTTP_CODE: Final = 2097154 +HTTP_CONNECTCODE: Final = 2097174 +HTTP_CONTENT_DECODING: Final = 158 +HTTP_TRANSFER_DECODING: Final = 157 +HTTP_VERSION: Final = 84 +IGNORE_CONTENT_LENGTH: Final = 136 +INFILE: Final = 10009 +INFILESIZE: Final = 30115 +INFILESIZE_LARGE: Final = 30115 +INFOTYPE_DATA_IN: Final = 3 +INFOTYPE_DATA_OUT: Final = 4 +INFOTYPE_HEADER_IN: Final = 1 +INFOTYPE_HEADER_OUT: Final = 2 +INFOTYPE_SSL_DATA_IN: Final = 5 +INFOTYPE_SSL_DATA_OUT: Final = 6 +INFOTYPE_TEXT: Final = 0 +INFO_CERTINFO: Final = 4194338 +INFO_COOKIELIST: Final = 4194332 +INFO_FILETIME: Final = 2097166 +INFO_HTTP_VERSION: Final = 2097198 +INFO_REFERER: Final[int] +INFO_RTSP_CLIENT_CSEQ: Final = 2097189 +INFO_RTSP_CSEQ_RECV: Final = 2097191 +INFO_RTSP_SERVER_CSEQ: Final = 2097190 +INFO_RTSP_SESSION_ID: Final = 1048612 +INTERFACE: Final = 10062 +IOCMD_NOP: Final = 0 +IOCMD_RESTARTREAD: Final = 1 +IOCTLFUNCTION: Final = 20130 +IOE_FAILRESTART: Final = 2 +IOE_OK: Final = 0 +IOE_UNKNOWNCMD: Final = 1 +IPRESOLVE: Final = 113 +IPRESOLVE_V4: Final = 1 +IPRESOLVE_V6: Final = 2 +IPRESOLVE_WHATEVER: Final = 0 +ISSUERCERT: Final = 10170 +ISSUERCERT_BLOB: Final = 40295 +KEYPASSWD: Final = 10026 +KHMATCH_MISMATCH: Final = 1 +KHMATCH_MISSING: Final = 2 +KHMATCH_OK: Final = 0 +KHSTAT_DEFER: Final = 3 +KHSTAT_FINE: Final = 1 +KHSTAT_FINE_ADD_TO_FILE: Final = 0 +KHSTAT_REJECT: Final = 2 +KHTYPE_DSS: Final = 3 +KHTYPE_RSA: Final = 2 +KHTYPE_RSA1: Final = 1 +KHTYPE_UNKNOWN: Final = 0 +KRB4LEVEL: Final = 10063 +KRBLEVEL: Final = 10063 +LASTSOCKET: Final = 2097181 +LOCALPORT: Final = 139 +LOCALPORTRANGE: Final = 140 +LOCAL_IP: Final = 1048617 +LOCAL_PORT: Final = 2097194 +LOCK_DATA_CONNECT: Final = 5 +LOCK_DATA_COOKIE: Final = 2 +LOCK_DATA_DNS: Final = 3 +LOCK_DATA_HSTS: Final[int] +LOCK_DATA_PSL: Final = 6 +LOCK_DATA_SSL_SESSION: Final = 4 +LOGIN_OPTIONS: Final = 10224 +LOW_SPEED_LIMIT: Final = 19 +LOW_SPEED_TIME: Final = 20 +MAIL_AUTH: Final = 10217 +MAIL_FROM: Final = 10186 +MAIL_RCPT: Final = 10187 +MAXAGE_CONN: Final = 288 +MAXCONNECTS: Final = 71 +MAXFILESIZE: Final = 30117 +MAXFILESIZE_LARGE: Final = 30117 +MAXLIFETIME_CONN: Final = 314 +PREREQFUNCTION: Final = 20312 +PREREQFUNC_OK: Final = 0 +PREREQFUNC_ABORT: Final = 1 +MAXREDIRS: Final = 68 +MAX_RECV_SPEED_LARGE: Final = 30146 +MAX_SEND_SPEED_LARGE: Final = 30145 +MIMEPOST: Final[int] +M_CHUNK_LENGTH_PENALTY_SIZE: Final = 30010 +M_CONTENT_LENGTH_PENALTY_SIZE: Final = 30009 +M_MAXCONNECTS: Final = 6 +M_MAX_CONCURRENT_STREAMS: Final = 16 +M_MAX_HOST_CONNECTIONS: Final = 7 +M_MAX_PIPELINE_LENGTH: Final = 8 +M_MAX_TOTAL_CONNECTIONS: Final = 13 +M_NOTIFYFUNCTION: Final[int] +M_NOTIFY_EASY_DONE: Final[int] +M_NOTIFY_INFO_READ: Final[int] +M_PIPELINING: Final = 3 +M_PIPELINING_SERVER_BL: Final = 10012 +M_PIPELINING_SITE_BL: Final = 10011 +M_SOCKETFUNCTION: Final = 20001 +M_TIMERFUNCTION: Final = 20004 +NAMELOOKUP_TIME: Final = 3145732 +NETRC: Final = 51 +NETRC_FILE: Final = 10118 +NETRC_IGNORED: Final = 0 +NETRC_OPTIONAL: Final = 1 +NETRC_REQUIRED: Final = 2 +NEW_DIRECTORY_PERMS: Final = 160 +NEW_FILE_PERMS: Final = 159 +NOBODY: Final = 44 +NOPROGRESS: Final = 43 +NOPROXY: Final = 10177 +NOSIGNAL: Final = 99 +NUM_CONNECTS: Final = 2097178 +OPENSOCKETFUNCTION: Final = 20163 +OPT_CERTINFO: Final = 172 +OPT_COOKIELIST: Final = 10135 +OPT_FILETIME: Final = 69 +OPT_RTSP_CLIENT_CSEQ: Final = 193 +OPT_RTSP_REQUEST: Final = 189 +OPT_RTSP_SERVER_CSEQ: Final = 194 +OPT_RTSP_SESSION_ID: Final = 10190 +OPT_RTSP_STREAM_URI: Final = 10191 +OPT_RTSP_TRANSPORT: Final = 10192 +OS_ERRNO: Final = 2097177 +PASSWORD: Final = 10174 +PATH_AS_IS: Final = 234 +PAUSE_ALL: Final = 5 +PAUSE_CONT: Final = 0 +PAUSE_RECV: Final = 1 +PAUSE_SEND: Final = 4 +PINNEDPUBLICKEY: Final = 10230 +PIPEWAIT: Final = 237 +PIPE_HTTP1: Final = 1 +PIPE_MULTIPLEX: Final = 2 +PIPE_NOTHING: Final = 0 +POLL_IN: Final = 1 +POLL_INOUT: Final = 3 +POLL_NONE: Final = 0 +POLL_OUT: Final = 2 +POLL_REMOVE: Final = 4 +PORT: Final = 3 +POST: Final = 47 +POST301: Final = 161 +POSTFIELDS: Final = 10015 +POSTFIELDSIZE: Final = 30120 +POSTFIELDSIZE_LARGE: Final = 30120 +POSTQUOTE: Final = 10039 +POSTREDIR: Final = 161 +PREQUOTE: Final = 10093 +PRETRANSFER_TIME: Final = 3145734 +PRE_PROXY: Final = 10262 +PRIMARY_IP: Final = 1048608 +PRIMARY_PORT: Final = 2097192 +PROGRESSFUNCTION: Final = 20056 +PROTOCOLS: Final = 181 +PROTO_ALL: Final[int] +PROTO_DICT: Final = 512 +PROTO_FILE: Final = 1024 +PROTO_FTP: Final = 4 +PROTO_FTPS: Final = 8 +PROTO_GOPHER: Final = 33554432 +PROTO_HTTP: Final = 1 +PROTO_HTTPS: Final = 2 +PROTO_IMAP: Final = 4096 +PROTO_IMAPS: Final = 8192 +PROTO_LDAP: Final = 128 +PROTO_LDAPS: Final = 256 +PROTO_POP3: Final = 16384 +PROTO_POP3S: Final = 32768 +PROTO_RTMP: Final = 524288 +PROTO_RTMPE: Final = 2097152 +PROTO_RTMPS: Final = 8388608 +PROTO_RTMPT: Final = 1048576 +PROTO_RTMPTE: Final = 4194304 +PROTO_RTMPTS: Final = 16777216 +PROTO_RTSP: Final = 262144 +PROTO_SCP: Final = 16 +PROTO_SFTP: Final = 32 +PROTO_SMB: Final = 67108864 +PROTO_SMBS: Final = 134217728 +PROTO_SMTP: Final = 65536 +PROTO_SMTPS: Final = 131072 +PROTO_TELNET: Final = 64 +PROTO_TFTP: Final = 2048 +PROXY: Final = 10004 +PROXYAUTH: Final = 111 +PROXYAUTH_AVAIL: Final = 2097176 +PROXYHEADER: Final = 10228 +PROXYPASSWORD: Final = 10176 +PROXYPORT: Final = 59 +PROXYTYPE: Final = 101 +PROXYTYPE_HTTP: Final = 0 +PROXYTYPE_HTTP_1_0: Final = 1 +PROXYTYPE_SOCKS4: Final = 4 +PROXYTYPE_SOCKS4A: Final = 6 +PROXYTYPE_SOCKS5: Final = 5 +PROXYTYPE_SOCKS5_HOSTNAME: Final = 7 +PROXYUSERNAME: Final = 10175 +PROXYUSERPWD: Final = 10006 +PROXY_CAINFO: Final = 10246 +PROXY_CAINFO_BLOB: Final = 40310 +PROXY_CAPATH: Final = 10247 +PROXY_CRLFILE: Final = 10260 +PROXY_ERROR: Final[int] +PROXY_ISSUERCERT: Final = 10296 +PROXY_ISSUERCERT_BLOB: Final = 40297 +PROXY_KEYPASSWD: Final = 10258 +PROXY_PINNEDPUBLICKEY: Final = 10263 +PROXY_SERVICE_NAME: Final = 10235 +PROXY_SSLCERT: Final = 10254 +PROXY_SSLCERTTYPE: Final = 10255 +PROXY_SSLCERT_BLOB: Final = 40293 +PROXY_SSLKEY: Final = 10256 +PROXY_SSLKEYTYPE: Final = 10257 +PROXY_SSLKEY_BLOB: Final = 40294 +PROXY_SSLVERSION: Final = 250 +PROXY_SSL_CIPHER_LIST: Final = 10259 +PROXY_SSL_OPTIONS: Final = 261 +PROXY_SSL_VERIFYHOST: Final = 249 +PROXY_SSL_VERIFYPEER: Final = 248 +PROXY_SSL_VERIFYRESULT: Final[int] +PROXY_TLS13_CIPHERS: Final = 10277 +PROXY_TLSAUTH_PASSWORD: Final = 10252 +PROXY_TLSAUTH_TYPE: Final = 10253 +PROXY_TLSAUTH_USERNAME: Final = 10251 +PROXY_TRANSFER_MODE: Final = 166 +PUT: Final = 54 +QUOTE: Final = 10028 +RANDOM_FILE: Final = 10076 +RANGE: Final = 10007 +READDATA: Final = 10009 +READFUNCTION: Final = 20012 +READFUNC_ABORT: Final = 268435456 +READFUNC_PAUSE: Final = 268435457 +REDIRECT_COUNT: Final = 2097172 +REDIRECT_TIME: Final = 3145747 +REDIRECT_URL: Final = 1048607 +REDIR_POST_301: Final = 1 +REDIR_POST_302: Final = 2 +REDIR_POST_303: Final = 4 +REDIR_POST_ALL: Final = 7 +REDIR_PROTOCOLS: Final = 182 +REFERER: Final = 10016 +REQUEST_SIZE: Final = 2097164 +REQUEST_TARGET: Final = 10266 +RESOLVE: Final = 10203 +RESOLVER_START_DATA: Final[int] +RESOLVER_START_FUNCTION: Final[int] +RESPONSE_CODE: Final = 2097154 +RESUME_FROM: Final = 30116 +RESUME_FROM_LARGE: Final = 30116 +RETRY_AFTER: Final[int] +RTSPREQ_ANNOUNCE: Final = 3 +RTSPREQ_DESCRIBE: Final = 2 +RTSPREQ_GET_PARAMETER: Final = 8 +RTSPREQ_LAST: Final = 12 +RTSPREQ_NONE: Final = 0 +RTSPREQ_OPTIONS: Final = 1 +RTSPREQ_PAUSE: Final = 6 +RTSPREQ_PLAY: Final = 5 +RTSPREQ_RECEIVE: Final = 11 +RTSPREQ_RECORD: Final = 10 +RTSPREQ_SETUP: Final = 4 +RTSPREQ_SET_PARAMETER: Final = 9 +RTSPREQ_TEARDOWN: Final = 7 +SASL_IR: Final = 218 +SCHEME: Final[int] +SEEKFUNCTION: Final = 20167 +SEEKFUNC_CANTSEEK: Final = 2 +SEEKFUNC_FAIL: Final = 1 +SEEKFUNC_OK: Final = 0 +SERVICE_NAME: Final = 10236 +SHARE: Final = 10100 +SH_SHARE: Final = 1 +SH_UNSHARE: Final = 2 +SIZE_DELIVERED: Final[int] +SIZE_DOWNLOAD: Final = 3145736 +SIZE_UPLOAD: Final = 3145735 +SOCKET_BAD: Final = -1 +SOCKET_TIMEOUT: Final = -1 +SOCKOPTFUNCTION: Final = 20148 +SOCKOPT_ALREADY_CONNECTED: Final = 2 +SOCKOPT_ERROR: Final = 1 +SOCKOPT_OK: Final = 0 +SOCKS5_GSSAPI_NEC: Final = 180 +SOCKS5_GSSAPI_SERVICE: Final = 10179 +SOCKTYPE_ACCEPT: Final = 1 +SOCKTYPE_IPCXN: Final = 0 +SPEED_DOWNLOAD: Final = 3145737 +SPEED_UPLOAD: Final = 3145738 +SSH_AUTH_AGENT: Final = 16 +SSH_AUTH_ANY: Final[int] +SSH_AUTH_DEFAULT: Final[int] +SSH_AUTH_HOST: Final = 4 +SSH_AUTH_KEYBOARD: Final = 8 +SSH_AUTH_NONE: Final = 0 +SSH_AUTH_PASSWORD: Final = 2 +SSH_AUTH_PUBLICKEY: Final = 1 +SSH_AUTH_TYPES: Final = 151 +SSH_HOST_PUBLIC_KEY_MD5: Final = 10162 +SSH_KEYFUNCTION: Final = 20184 +SSH_KNOWNHOSTS: Final = 10183 +SSH_PRIVATE_KEYFILE: Final = 10153 +SSH_PUBLIC_KEYFILE: Final = 10152 +SSLCERT: Final = 10025 +SSLCERTPASSWD: Final = 10026 +SSLCERTTYPE: Final = 10086 +SSLCERT_BLOB: Final = 40291 +SSLENGINE: Final = 10089 +SSLENGINE_DEFAULT: Final = 90 +SSLKEY: Final = 10087 +SSLKEYPASSWD: Final = 10026 +SSLKEYTYPE: Final = 10088 +SSLKEY_BLOB: Final = 40292 +SSLOPT_ALLOW_BEAST: Final = 1 +SSLOPT_AUTO_CLIENT_CERT: Final[int] +SSLOPT_EARLYDATA: Final[int] +SSLOPT_NATIVE_CA: Final[int] +SSLOPT_NO_PARTIALCHAIN: Final[int] +SSLOPT_NO_REVOKE: Final = 2 +SSLOPT_REVOKE_BEST_EFFORT: Final[int] +SSLVERSION: Final = 32 +SSLVERSION_DEFAULT: Final = 0 +SSLVERSION_MAX_DEFAULT: Final = 65536 +SSLVERSION_MAX_TLSv1_0: Final = 262144 +SSLVERSION_MAX_TLSv1_1: Final = 327680 +SSLVERSION_MAX_TLSv1_2: Final = 393216 +SSLVERSION_MAX_TLSv1_3: Final = 458752 +SSLVERSION_SSLv2: Final = 2 +SSLVERSION_SSLv3: Final = 3 +SSLVERSION_TLSv1: Final = 1 +SSLVERSION_TLSv1_0: Final = 4 +SSLVERSION_TLSv1_1: Final = 5 +SSLVERSION_TLSv1_2: Final = 6 +SSLVERSION_TLSv1_3: Final = 7 +SSL_CIPHER_LIST: Final = 10083 +SSL_EC_CURVES: Final[int] +SSL_ENABLE_ALPN: Final = 226 +SSL_ENABLE_NPN: Final = 225 +SSL_ENGINES: Final = 4194331 +SSL_FALSESTART: Final = 233 +SSL_OPTIONS: Final = 216 +SSL_SESSIONID_CACHE: Final = 150 +SSL_SIGNATURE_ALGORITHMS: Final[int] +SSL_VERIFYHOST: Final = 81 +SSL_VERIFYPEER: Final = 64 +SSL_VERIFYRESULT: Final = 2097165 +SSL_VERIFYSTATUS: Final = 232 +STARTTRANSFER_TIME: Final = 3145745 +STDERR: Final = 10037 +TCP_FASTOPEN: Final = 244 +TCP_KEEPALIVE: Final = 213 +TCP_KEEPIDLE: Final = 214 +TCP_KEEPINTVL: Final = 215 +TCP_NODELAY: Final = 121 +TELNETOPTIONS: Final = 10070 +TFTP_BLKSIZE: Final = 178 +TIMECONDITION: Final = 33 +TIMECONDITION_IFMODSINCE: Final = 1 +TIMECONDITION_IFUNMODSINCE: Final = 2 +TIMECONDITION_LASTMOD: Final = 3 +TIMECONDITION_NONE: Final = 0 +TIMEOUT: Final = 13 +TIMEOUT_MS: Final = 155 +TIMEVALUE: Final = 34 +TLS13_CIPHERS: Final = 10276 +TLSAUTH_PASSWORD: Final = 10205 +TLSAUTH_TYPE: Final = 10206 +TLSAUTH_USERNAME: Final = 10204 +TOTAL_TIME: Final = 3145731 +TRAILERDATA: Final[int] +TRAILERFUNCTION: Final[int] +TRAILERFUNC_ABORT: Final[int] +TRAILERFUNC_OK: Final[int] +TRANSFERTEXT: Final = 53 +TRANSFER_ENCODING: Final = 207 +UNIX_SOCKET_PATH: Final = 10231 +UNRESTRICTED_AUTH: Final = 105 +UPART_FRAGMENT: Final[int] +UPART_HOST: Final[int] +UPART_OPTIONS: Final[int] +UPART_PASSWORD: Final[int] +UPART_PATH: Final[int] +UPART_PORT: Final[int] +UPART_QUERY: Final[int] +UPART_SCHEME: Final[int] +UPART_URL: Final[int] +UPART_USER: Final[int] +UPART_ZONEID: Final[int] +UPLOAD: Final = 46 +UPLOAD_BUFFERSIZE: Final = 280 +URL: Final = 10002 +USED_PROXY: Final[int] +USERAGENT: Final = 10018 +USERNAME: Final = 10173 +USERPWD: Final = 10005 +USESSL_ALL: Final = 3 +USESSL_CONTROL: Final = 2 +USESSL_NONE: Final = 0 +USESSL_TRY: Final = 1 +USE_SSL: Final = 119 +U_ALLOW_SPACE: Final[int] +U_APPENDQUERY: Final[int] +U_DEFAULT_PORT: Final[int] +U_DEFAULT_SCHEME: Final[int] +U_DISALLOW_USER: Final[int] +U_GET_EMPTY: Final[int] +U_GUESS_SCHEME: Final[int] +U_NON_SUPPORT_SCHEME: Final[int] +U_NO_AUTHORITY: Final[int] +U_NO_DEFAULT_PORT: Final[int] +U_NO_GUESS_SCHEME: Final[int] +U_PATH_AS_IS: Final[int] +U_PUNY2IDN: Final[int] +U_PUNYCODE: Final[int] +U_URLDECODE: Final[int] +U_URLENCODE: Final[int] +VERBOSE: Final = 41 +VERSION_ALTSVC: Final = 16777216 +VERSION_ASYNCHDNS: Final = 128 +VERSION_BROTLI: Final = 8388608 +VERSION_CONV: Final = 4096 +VERSION_CURLDEBUG: Final = 8192 +VERSION_DEBUG: Final = 64 +VERSION_GSASL: Final = 536870912 +VERSION_GSSAPI: Final = 131072 +VERSION_GSSNEGOTIATE: Final = 32 +VERSION_HSTS: Final = 268435456 +VERSION_HTTP2: Final = 65536 +VERSION_HTTP3: Final = 33554432 +VERSION_HTTPS_PROXY: Final = 2097152 +VERSION_IDN: Final = 1024 +VERSION_IPV6: Final = 1 +VERSION_KERBEROS4: Final = 2 +VERSION_KERBEROS5: Final = 262144 +VERSION_LARGEFILE: Final = 512 +VERSION_LIBZ: Final = 8 +VERSION_MULTI_SSL: Final = 4194304 +VERSION_NTLM: Final = 16 +VERSION_NTLM_WB: Final = 32768 +VERSION_PSL: Final = 1048576 +VERSION_SPNEGO: Final = 256 +VERSION_SSL: Final = 4 +VERSION_SSPI: Final = 2048 +VERSION_TLSAUTH_SRP: Final = 16384 +VERSION_UNICODE: Final = 134217728 +VERSION_UNIX_SOCKETS: Final = 524288 +VERSION_ZSTD: Final = 67108864 +WILDCARDMATCH: Final = 197 +WRITEDATA: Final = 10001 +WRITEFUNCTION: Final = 20011 +WRITEFUNC_PAUSE: Final = 268435457 +WRITEHEADER: Final = 10029 +WS_BINARY: Final[int] +WS_CLOSE: Final[int] +WS_CONT: Final[int] +WS_NOAUTOPONG: Final[int] +WS_OFFSET: Final[int] +WS_OPTIONS: Final[int] +WS_PING: Final[int] +WS_PONG: Final[int] +WS_RAW_MODE: Final[int] +WS_TEXT: Final[int] +XFERINFOFUNCTION: Final = 20219 +XFER_ID: Final[int] +XOAUTH2_BEARER: Final = 10220 diff --git a/stubs/pycurl/pycurl/async_multi.pyi b/stubs/pycurl/pycurl/async_multi.pyi new file mode 100644 index 000000000000..0d1868bae07b --- /dev/null +++ b/stubs/pycurl/pycurl/async_multi.pyi @@ -0,0 +1,22 @@ +import asyncio +from collections.abc import Iterable +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from pycurl._pycurl import Curl + +class AsyncCurlMulti: + def __init__(self, close_handles: bool = False) -> None: ... + def setopt(self, option: int, value: Any) -> None: ... # type of value depends on the option + def add_handle(self, curl: Curl) -> asyncio.Future[Curl]: ... + def remove_handle(self, curl: Curl) -> None: ... + async def perform(self, curl: Curl) -> Curl: ... + def futures(self, curls: Iterable[Curl] | None = None) -> tuple[asyncio.Future[Curl], ...]: ... + @property + def closed(self) -> bool: ... + async def aclose(self) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... diff --git a/stubs/pyfarmhash/METADATA.toml b/stubs/pyfarmhash/METADATA.toml index a42da251bed5..a01e9062adcd 100644 --- a/stubs/pyfarmhash/METADATA.toml +++ b/stubs/pyfarmhash/METADATA.toml @@ -1 +1,2 @@ -version = "0.2.*" +version = "0.5.*" +upstream-repository = "https://github.com/veelion/python-farmhash" diff --git a/stubs/pyfarmhash/farmhash.pyi b/stubs/pyfarmhash/farmhash.pyi index 8b8fd0e96d29..cdb08e53a3c3 100644 --- a/stubs/pyfarmhash/farmhash.pyi +++ b/stubs/pyfarmhash/farmhash.pyi @@ -1,9 +1,9 @@ -def fingerprint128(__a: str) -> tuple[int, int]: ... -def fingerprint32(__a: str) -> int: ... -def fingerprint64(__a: str) -> int: ... -def hash128(__a: str) -> tuple[int, int]: ... -def hash128withseed(__a: str, __seed_low: int, __seed_high: int) -> tuple[int, int]: ... -def hash32(__a: str) -> int: ... -def hash32withseed(__a: str, __seed: int) -> int: ... -def hash64(__a: str) -> int: ... -def hash64withseed(__a: str, __seed: int) -> int: ... +def fingerprint128(a: str, /) -> tuple[int, int]: ... +def fingerprint32(a: str, /) -> int: ... +def fingerprint64(a: str, /) -> int: ... +def hash128(a: str, /) -> tuple[int, int]: ... +def hash128withseed(a: str, seed_low: int, seed_high: int, /) -> tuple[int, int]: ... +def hash32(a: str, /) -> int: ... +def hash32withseed(a: str, seed: int, /) -> int: ... +def hash64(a: str, /) -> int: ... +def hash64withseed(a: str, seed: int, /) -> int: ... diff --git a/stubs/pyflakes/@tests/stubtest_allowlist.txt b/stubs/pyflakes/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..109ee305c802 --- /dev/null +++ b/stubs/pyflakes/@tests/stubtest_allowlist.txt @@ -0,0 +1,30 @@ +# These all have class-level defaults that differ from the instance attributes +pyflakes.messages.DuplicateArgument.message_args +pyflakes.messages.ForwardAnnotationSyntaxError.message_args +pyflakes.messages.FutureFeatureNotDefined.message_args +pyflakes.messages.ImportShadowedByLoopVar.message_args +pyflakes.messages.ImportStarNotPermitted.message_args +pyflakes.messages.ImportStarUsage.message_args +pyflakes.messages.ImportStarUsed.message_args +pyflakes.messages.MultiValueRepeatedKeyLiteral.message_args +pyflakes.messages.MultiValueRepeatedKeyVariable.message_args +pyflakes.messages.PercentFormatExtraNamedArguments.message_args +pyflakes.messages.PercentFormatInvalidFormat.message_args +pyflakes.messages.PercentFormatMissingArgument.message_args +pyflakes.messages.PercentFormatPositionalCountMismatch.message_args +pyflakes.messages.PercentFormatUnsupportedFormatCharacter.message_args +pyflakes.messages.RedefinedWhileUnused.message_args +pyflakes.messages.StringDotFormatExtraNamedArguments.message_args +pyflakes.messages.StringDotFormatExtraPositionalArguments.message_args +pyflakes.messages.StringDotFormatInvalidFormat.message_args +pyflakes.messages.StringDotFormatMissingArgument.message_args +pyflakes.messages.UndefinedExport.message_args +pyflakes.messages.UndefinedLocal.message_args +pyflakes.messages.UndefinedName.message_args +pyflakes.messages.UnusedAnnotation.message_args +pyflakes.messages.UnusedImport.message_args +pyflakes.messages.UnusedIndirectAssignment.message_args +pyflakes.messages.UnusedVariable.message_args + +# Tests are not included: +pyflakes.test.* diff --git a/stubs/pyflakes/METADATA.toml b/stubs/pyflakes/METADATA.toml new file mode 100644 index 000000000000..4619a579594b --- /dev/null +++ b/stubs/pyflakes/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.4.*" +upstream-repository = "https://github.com/PyCQA/pyflakes" diff --git a/stubs/pyflakes/pyflakes/__init__.pyi b/stubs/pyflakes/pyflakes/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/pyflakes/pyflakes/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/pyflakes/pyflakes/__main__.pyi b/stubs/pyflakes/pyflakes/__main__.pyi new file mode 100644 index 000000000000..e70d627ae91d --- /dev/null +++ b/stubs/pyflakes/pyflakes/__main__.pyi @@ -0,0 +1 @@ +from pyflakes.api import main as main diff --git a/stubs/pyflakes/pyflakes/api.pyi b/stubs/pyflakes/pyflakes/api.pyi new file mode 100644 index 000000000000..c3e9477ab53e --- /dev/null +++ b/stubs/pyflakes/pyflakes/api.pyi @@ -0,0 +1,18 @@ +from _typeshed import GenericPath +from collections.abc import Iterable, Iterator, Sequence +from re import Pattern +from typing import Final +from typing_extensions import Never + +from pyflakes.reporter import Reporter + +__all__ = ["check", "checkPath", "checkRecursive", "iterSourceCode", "main"] + +PYTHON_SHEBANG_REGEX: Final[Pattern[bytes]] + +def check(codeString: str, filename: str, reporter: Reporter | None = None) -> int: ... +def checkPath(filename: str, reporter: Reporter | None = None) -> int: ... +def isPythonFile(filename: str) -> bool: ... +def iterSourceCode(paths: Iterable[GenericPath[str]]) -> Iterator[GenericPath[str]]: ... +def checkRecursive(paths: Iterable[GenericPath[str]], reporter: Reporter) -> int: ... +def main(prog: str | None = None, args: Sequence[str] | None = None) -> Never: ... diff --git a/stubs/pyflakes/pyflakes/checker.pyi b/stubs/pyflakes/pyflakes/checker.pyi new file mode 100644 index 000000000000..4e7bc16642cb --- /dev/null +++ b/stubs/pyflakes/pyflakes/checker.pyi @@ -0,0 +1,343 @@ +import ast +import sys +from _typeshed import StrOrLiteralStr, Unused +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import contextmanager +from re import Pattern +from typing import Any, ClassVar, Final, Literal, ParamSpec, TypeAlias, TypeVar, overload +from typing_extensions import Never + +from pyflakes.messages import Message + +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +PYPY: Final[bool] +builtin_vars: Final[list[str]] + +def parse_format_string( + format_string: StrOrLiteralStr, +) -> Iterable[tuple[StrOrLiteralStr, StrOrLiteralStr | None, StrOrLiteralStr | None, StrOrLiteralStr | None]]: ... +def getAlternatives(n: ast.If | ast.Try | ast.Match) -> list[ast.AST]: ... + +FOR_TYPES: Final[tuple[type[ast.For], type[ast.AsyncFor]]] +MAPPING_KEY_RE: Final[Pattern[str]] +CONVERSION_FLAG_RE: Final[Pattern[str]] +WIDTH_RE: Final[Pattern[str]] +PRECISION_RE: Final[Pattern[str]] +LENGTH_RE: Final[Pattern[str]] +VALID_CONVERSIONS: frozenset[str] + +_FormatType: TypeAlias = tuple[str | None, str | None, str | None, str | None, str] +_PercentFormat: TypeAlias = tuple[str, _FormatType | None] + +def parse_percent_format(s: str) -> tuple[_PercentFormat, ...]: ... + +class _FieldsOrder(dict[type[ast.AST], tuple[str, ...]]): + def __missing__(self, node_class: type[ast.AST]) -> tuple[str, ...]: ... + +_OmitType: TypeAlias = str | tuple[str, ...] | None + +def iter_child_nodes(node: ast.AST, omit: _OmitType = None, _fields_order: _FieldsOrder = ...) -> Iterator[ast.AST]: ... + +@overload +def convert_to_value(item: ast.Constant) -> Any: ... # type: ignore[overload-overlap] # See ast.Constant.value for possible return types +@overload +def convert_to_value(item: ast.Tuple) -> tuple[Any, ...]: ... # type: ignore[overload-overlap] # Tuple items depend on their ast type +@overload +def convert_to_value(item: ast.Name) -> VariableKey: ... # type: ignore[overload-overlap] +@overload +def convert_to_value(item: ast.AST) -> UnhandledKeyType: ... + +def is_notimplemented_name_node(node: ast.AST) -> bool: ... + +class Binding: + name: str + source: ast.AST | None + used: Literal[False] | tuple[Scope, ast.AST] + def __init__(self, name: str, source: ast.AST | None) -> None: ... + def redefines(self, other: Binding) -> bool: ... + +class Definition(Binding): ... + +class Builtin(Definition): + def __init__(self, name: str) -> None: ... + +class UnhandledKeyType: ... + +class VariableKey: + name: str + def __init__(self, item: ast.Name) -> None: ... + def __eq__(self, compare: object) -> bool: ... + def __hash__(self) -> int: ... + +class Importation(Definition): + fullName: str + redefined: list[ast.AST] + def __init__(self, name: str, source: ast.AST | None, full_name: str | None = None) -> None: ... + @property + def source_statement(self) -> str: ... + +class SubmoduleImportation(Importation): + def __init__(self, name: str, source: ast.Import | None) -> None: ... + +class ImportationFrom(Importation): + module: str + real_name: str + def __init__(self, name: str, source: ast.AST, module: str, real_name: str | None = None) -> None: ... + +class StarImportation(Importation): + def __init__(self, name: str, source: ast.AST) -> None: ... + +class FutureImportation(ImportationFrom): + used: tuple[Scope, ast.AST] + def __init__(self, name: str, source: ast.AST, scope: Scope) -> None: ... + +class Argument(Binding): ... +class Assignment(Binding): ... +class NamedExprAssignment(Assignment): ... + +class Annotation(Binding): + def redefines(self, other: Binding) -> Literal[False]: ... + +class FunctionDefinition(Definition): ... +class ClassDefinition(Definition): ... + +class ExportBinding(Binding): + names: list[str] + def __init__(self, name: str, source: ast.AST, scope: Scope) -> None: ... + +class Scope(dict[str, Binding]): + importStarred: bool + +class ClassScope(Scope): + def __init__(self) -> None: ... + +class FunctionScope(Scope): + usesLocals: bool + alwaysUsed: ClassVar[set[str]] + globals: set[str] + returnValue: ast.expr | None + isGenerator: bool + def __init__(self) -> None: ... + def unused_assignments(self) -> Iterator[tuple[str, Binding]]: ... + def unused_annotations(self) -> Iterator[tuple[str, Annotation]]: ... + +class TypeScope(Scope): ... +class GeneratorScope(Scope): ... +class ModuleScope(Scope): ... +class DoctestScope(ModuleScope): ... + +class DetectClassScopedMagic: + names: list[str] + +def getNodeName(node: ast.AST) -> str: ... + +TYPING_MODULES: frozenset[Literal["typing", "typing_extensions"]] + +def is_typing_overload(value: Binding, scope_stack: Sequence[Scope]) -> bool: ... + +class AnnotationState: + NONE: ClassVar[Literal[0]] + STRING: ClassVar[Literal[1]] + BARE: ClassVar[Literal[2]] + +def in_annotation(func: _F) -> _F: ... +def in_string_annotation(func: _F) -> _F: ... + +if sys.version_info >= (3, 12): + _TypeVar: TypeAlias = ast.TypeVar + _ParamSpec: TypeAlias = ast.ParamSpec + _TypeVarTuple: TypeAlias = ast.TypeVarTuple + _TypeAlias: TypeAlias = ast.TypeAlias +else: + # The methods using these should never be called on Python < 3.12. + _TypeVar: TypeAlias = Never + _ParamSpec: TypeAlias = Never + _TypeVarTuple: TypeAlias = Never + _TypeAlias: TypeAlias = Never + +if sys.version_info >= (3, 14): + _NameConstant: TypeAlias = Never + _TemplateStr: TypeAlias = ast.TemplateStr + _Interpolation: TypeAlias = ast.Interpolation +else: + _NameConstant: TypeAlias = ast.NameConstant + # The methods using these should never be called on Python < 3.14. + _TemplateStr: TypeAlias = Never + _Interpolation: TypeAlias = Never + +class Checker: + nodeDepth: int + offset: tuple[int, int] | None + builtIns: set[str] + deadScopes: list[Scope] + messages: list[Message] + filename: str + withDoctest: bool + scopeStack: list[Scope] + exceptHandlers: list[tuple[()] | str] + root: ast.AST + def __init__( + self, + tree: ast.AST, + filename: str = "(none)", + builtins: Iterable[str] | None = None, + withDoctest: bool = False, + file_tokens: Unused = (), + ) -> None: ... + def deferFunction(self, callable: Callable[..., Any]) -> None: ... + + @property + def futuresAllowed(self) -> bool: ... + @futuresAllowed.setter + def futuresAllowed(self, value: Literal[False]) -> None: ... + + @property + def annotationsFutureEnabled(self) -> bool: ... + @annotationsFutureEnabled.setter + def annotationsFutureEnabled(self, value: Literal[True]) -> None: ... + + @property + def scope(self) -> Scope: ... + @contextmanager + def in_scope(self, cls: Callable[[], Scope]) -> Generator[None]: ... + def checkDeadScopes(self) -> None: ... + def report(self, messageClass: Callable[_P, Message], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def getParent(self, node: ast.AST) -> ast.AST: ... + def getCommonAncestor(self, lnode: ast.AST, rnode: ast.AST, stop: ast.AST) -> ast.AST: ... + def descendantOf(self, node: ast.AST, ancestors: ast.AST, stop: ast.AST) -> bool: ... + def getScopeNode(self, node: ast.AST) -> ast.AST | None: ... + def differentForks(self, lnode: ast.AST, rnode: ast.AST) -> bool: ... + def addBinding(self, node: ast.AST, value: Binding) -> None: ... + def getNodeHandler(self, node_class: type[ast.AST]) -> Callable[[ast.AST], None]: ... + def handleNodeLoad(self, node: ast.AST, parent: ast.AST | None) -> None: ... + def handleNodeStore(self, node: ast.AST) -> None: ... + def handleNodeDelete(self, node: ast.AST) -> None: ... + def handleChildren(self, tree: ast.AST, omit: _OmitType = None) -> None: ... + def isLiteralTupleUnpacking(self, node: ast.AST) -> bool | None: ... + def isDocstring(self, node: ast.AST) -> bool: ... + def getDocstring(self, node: ast.AST) -> tuple[str, int] | tuple[None, None]: ... + def handleNode(self, node: ast.AST | None, parent: ast.AST | None) -> None: ... + def handleDoctests(self, node: ast.AST) -> None: ... + def handleStringAnnotation(self, s: str, node: ast.AST, ref_lineno: int, ref_col_offset: int, err: type[Message]) -> None: ... + def handle_annotation_always_deferred(self, annotation: ast.AST, parent: ast.AST) -> None: ... + def handleAnnotation(self, annotation: ast.AST, node: ast.AST) -> None: ... + def ignore(self, node: ast.AST) -> None: ... + def DELETE(self, tree: ast.Delete, omit: _OmitType = None) -> None: ... + def FOR(self, tree: ast.For, omit: _OmitType = None) -> None: ... + def ASYNCFOR(self, tree: ast.AsyncFor, omit: _OmitType = None) -> None: ... + def WHILE(self, tree: ast.While, omit: _OmitType = None) -> None: ... + def WITH(self, tree: ast.With, omit: _OmitType = None) -> None: ... + def WITHITEM(self, tree: ast.AST, omit: _OmitType = None) -> None: ... + def ASYNCWITH(self, tree: ast.AsyncWith, omit: _OmitType = None) -> None: ... + def EXPR(self, tree: ast.AST, omit: _OmitType = None) -> None: ... + def ASSIGN(self, tree: ast.Assign, omit: _OmitType = None) -> None: ... + def PASS(self, node: ast.AST) -> None: ... + def BOOLOP(self, tree: ast.BoolOp, omit: _OmitType = None) -> None: ... + def UNARYOP(self, tree: ast.UnaryOp, omit: _OmitType = None) -> None: ... + def SET(self, tree: ast.Set, omit: _OmitType = None) -> None: ... + def ATTRIBUTE(self, tree: ast.Attribute, omit: _OmitType = None) -> None: ... + def STARRED(self, tree: ast.Starred, omit: _OmitType = None) -> None: ... + def NAMECONSTANT(self, tree: _NameConstant, omit: _OmitType = None) -> None: ... + def NAMEDEXPR(self, tree: ast.NamedExpr, omit: _OmitType = None) -> None: ... + def SUBSCRIPT(self, node: ast.Subscript) -> None: ... + def CALL(self, node: ast.Call) -> None: ... + def BINOP(self, node: ast.BinOp) -> None: ... + def CONSTANT(self, node: ast.Constant) -> None: ... + def SLICE(self, tree: ast.Slice, omit: _OmitType = None) -> None: ... + def EXTSLICE(self, tree: ast.ExtSlice, omit: _OmitType = None) -> None: ... + def INDEX(self, tree: ast.Index, omit: _OmitType = None) -> None: ... + def LOAD(self, node: ast.Load) -> None: ... + def STORE(self, node: ast.Store) -> None: ... + def DEL(self, node: ast.Del) -> None: ... + def AUGLOAD(self, node: ast.AugLoad) -> None: ... + def AUGSTORE(self, node: ast.AugStore) -> None: ... + def PARAM(self, node: ast.Param) -> None: ... + def AND(self, node: ast.And) -> None: ... + def OR(self, node: ast.Or) -> None: ... + def ADD(self, node: ast.Add) -> None: ... + def SUB(self, node: ast.Sub) -> None: ... + def MULT(self, node: ast.Mult) -> None: ... + def DIV(self, node: ast.Div) -> None: ... + def MOD(self, node: ast.Mod) -> None: ... + def POW(self, node: ast.Pow) -> None: ... + def LSHIFT(self, node: ast.LShift) -> None: ... + def RSHIFT(self, node: ast.RShift) -> None: ... + def BITOR(self, node: ast.BitOr) -> None: ... + def BITXOR(self, node: ast.BitXor) -> None: ... + def BITAND(self, node: ast.BitAnd) -> None: ... + def FLOORDIV(self, node: ast.FloorDiv) -> None: ... + def INVERT(self, node: ast.Invert) -> None: ... + def NOT(self, node: ast.Not) -> None: ... + def UADD(self, node: ast.UAdd) -> None: ... + def USUB(self, node: ast.USub) -> None: ... + def EQ(self, node: ast.Eq) -> None: ... + def NOTEQ(self, node: ast.NotEq) -> None: ... + def LT(self, node: ast.Lt) -> None: ... + def LTE(self, node: ast.LtE) -> None: ... + def GT(self, node: ast.Gt) -> None: ... + def GTE(self, node: ast.GtE) -> None: ... + def IS(self, node: ast.Is) -> None: ... + def ISNOT(self, node: ast.IsNot) -> None: ... + def IN(self, node: ast.In) -> None: ... + def NOTIN(self, node: ast.NotIn) -> None: ... + def MATMULT(self, node: ast.MatMult) -> None: ... + def RAISE(self, node: ast.Raise) -> None: ... + def COMPREHENSION(self, tree: ast.comprehension, omit: _OmitType = None) -> None: ... + def KEYWORD(self, tree: ast.keyword, omit: _OmitType = None) -> None: ... + def FORMATTEDVALUE(self, tree: ast.FormattedValue, omit: _OmitType = None) -> None: ... + def JOINEDSTR(self, node: ast.AST) -> None: ... + def TEMPLATESTR(self, node: _TemplateStr) -> None: ... + def INTERPOLATION(self, tree: _Interpolation, omit: _OmitType = None) -> None: ... + def DICT(self, node: ast.Dict) -> None: ... + def IF(self, node: ast.If) -> None: ... + def IFEXP(self, node: ast.If) -> None: ... + def ASSERT(self, node: ast.Assert) -> None: ... + def GLOBAL(self, node: ast.Global) -> None: ... + def NONLOCAL(self, node: ast.Nonlocal) -> None: ... + def GENERATOREXP(self, node: ast.GeneratorExp) -> None: ... + def LISTCOMP(self, node: ast.ListComp) -> None: ... + def DICTCOMP(self, node: ast.DictComp) -> None: ... + def SETCOMP(self, node: ast.SetComp) -> None: ... + def NAME(self, node: ast.Name) -> None: ... + def CONTINUE(self, node: ast.Continue) -> None: ... + def BREAK(self, node: ast.Break) -> None: ... + def RETURN(self, node: ast.Return) -> None: ... + def YIELD(self, node: ast.Yield) -> None: ... + def AWAIT(self, node: ast.Await) -> None: ... + def YIELDFROM(self, node: ast.YieldFrom) -> None: ... + def FUNCTIONDEF(self, node: ast.FunctionDef) -> None: ... + def ASYNCFUNCTIONDEF(self, node: ast.AsyncFunctionDef) -> None: ... + def LAMBDA(self, node: ast.Lambda) -> None: ... + def ARGUMENTS(self, node: ast.arguments) -> None: ... + def ARG(self, node: ast.arg) -> None: ... + def CLASSDEF(self, node: ast.ClassDef) -> None: ... + def AUGASSIGN(self, node: ast.AugAssign) -> None: ... + def TUPLE(self, node: ast.Tuple) -> None: ... + def LIST(self, node: ast.List) -> None: ... + def IMPORT(self, node: ast.Import) -> None: ... + def IMPORTFROM(self, node: ast.ImportFrom) -> None: ... + def TRY(self, node: ast.Try) -> None: ... + if sys.version_info >= (3, 11): + def TRYSTAR(self, node: ast.TryStar) -> None: ... + else: + def TRYSTAR(self, node: ast.Try) -> None: ... + + def EXCEPTHANDLER(self, node: ast.ExceptHandler) -> None: ... + def ANNASSIGN(self, node: ast.AnnAssign) -> None: ... + def COMPARE(self, node: ast.Compare) -> None: ... + def MATCH(self, tree: ast.Match, omit: _OmitType = None) -> None: ... + def MATCH_CASE(self, tree: ast.match_case, omit: _OmitType = None) -> None: ... + def MATCHCLASS(self, tree: ast.MatchClass, omit: _OmitType = None) -> None: ... + def MATCHOR(self, tree: ast.MatchOr, omit: _OmitType = None) -> None: ... + def MATCHSEQUENCE(self, tree: ast.MatchSequence, omit: _OmitType = None) -> None: ... + def MATCHSINGLETON(self, tree: ast.MatchSingleton, omit: _OmitType = None) -> None: ... + def MATCHVALUE(self, tree: ast.MatchValue, omit: _OmitType = None) -> None: ... + def MATCHAS(self, node: ast.MatchAs) -> None: ... + def MATCHMAPPING(self, node: ast.MatchMapping) -> None: ... + def MATCHSTAR(self, node: ast.MatchStar) -> None: ... + def TYPEVAR(self, node: _TypeVar) -> None: ... + def PARAMSPEC(self, node: _ParamSpec) -> None: ... + def TYPEVARTUPLE(self, node: _TypeVarTuple) -> None: ... + def TYPEALIAS(self, node: _TypeAlias) -> None: ... diff --git a/stubs/pyflakes/pyflakes/messages.pyi b/stubs/pyflakes/pyflakes/messages.pyi new file mode 100644 index 000000000000..4db703f30c7c --- /dev/null +++ b/stubs/pyflakes/pyflakes/messages.pyi @@ -0,0 +1,148 @@ +import ast +from typing import Any, ClassVar + +class Message: + message: ClassVar[str] + message_args: tuple[Any, ...] # Tuple types differ between sub-classes. + filename: str + lineno: int + col: int + def __init__(self, filename: str, loc: ast.AST) -> None: ... + +class UnusedImport(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class RedefinedWhileUnused(Message): + message_args: tuple[str, int] + def __init__(self, filename: str, loc: ast.AST, name: str, orig_loc: ast.AST) -> None: ... + +class ImportShadowedByLoopVar(Message): + message_args: tuple[str, int] + def __init__(self, filename: str, loc: ast.AST, name: str, orig_loc: ast.AST) -> None: ... + +class ImportStarNotPermitted(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, modname: str) -> None: ... + +class ImportStarUsed(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, modname: str) -> None: ... + +class ImportStarUsage(Message): + message_args: tuple[str, str] + def __init__(self, filename: str, loc: ast.AST, name: str, from_list: str) -> None: ... + +class UndefinedName(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class DoctestSyntaxError(Message): + message_args: tuple[()] + def __init__(self, filename: str, loc: ast.AST, position: tuple[int, int] | None = None) -> None: ... + +class UndefinedExport(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class UndefinedLocal(Message): + default: ClassVar[str] + builtin: ClassVar[str] + message_args: tuple[str, int] + def __init__(self, filename: str, loc: ast.AST, name: str, orig_loc: ast.AST) -> None: ... + +class DuplicateArgument(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class MultiValueRepeatedKeyLiteral(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, key: str) -> None: ... + +class MultiValueRepeatedKeyVariable(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, key: str) -> None: ... + +class LateFutureImport(Message): + message_args: tuple[()] + def __init__(self, filename: str, loc: ast.AST) -> None: ... + +class FutureFeatureNotDefined(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class UnusedVariable(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, names: str) -> None: ... + +class UnusedAnnotation(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, names: str) -> None: ... + +class UnusedIndirectAssignment(Message): + message_args: tuple[str, str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class ReturnOutsideFunction(Message): ... +class YieldOutsideFunction(Message): ... +class ContinueOutsideLoop(Message): ... +class BreakOutsideLoop(Message): ... +class DefaultExceptNotLast(Message): ... +class TwoStarredExpressions(Message): ... +class TooManyExpressionsInStarredAssignment(Message): ... +class IfTuple(Message): ... +class AssertTuple(Message): ... + +class ForwardAnnotationSyntaxError(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, annotation: str) -> None: ... + +class RaiseNotImplemented(Message): ... +class InvalidPrintSyntax(Message): ... +class IsLiteral(Message): ... +class FStringMissingPlaceholders(Message): ... +class TStringMissingPlaceholders(Message): ... + +class StringDotFormatExtraPositionalArguments(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, extra_positions: str) -> None: ... + +class StringDotFormatExtraNamedArguments(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, extra_keywords: str) -> None: ... + +class StringDotFormatMissingArgument(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, missing_arguments: str) -> None: ... + +class StringDotFormatMixingAutomatic(Message): ... + +class StringDotFormatInvalidFormat(Message): + message_args: tuple[str] | tuple[Exception] + def __init__(self, filename: str, loc: ast.AST, error: str | Exception) -> None: ... + +class PercentFormatInvalidFormat(Message): + message_args: tuple[str] | tuple[Exception] + def __init__(self, filename: str, loc: ast.AST, error: str | Exception) -> None: ... + +class PercentFormatMixedPositionalAndNamed(Message): ... + +class PercentFormatUnsupportedFormatCharacter(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, c: str) -> None: ... + +class PercentFormatPositionalCountMismatch(Message): + message_args: tuple[int, int] + def __init__(self, filename: str, loc: ast.AST, n_placeholders: int, n_substitutions: int) -> None: ... + +class PercentFormatExtraNamedArguments(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, extra_keywords: str) -> None: ... + +class PercentFormatMissingArgument(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, missing_arguments: str) -> None: ... + +class PercentFormatExpectedMapping(Message): ... +class PercentFormatExpectedSequence(Message): ... +class PercentFormatStarRequiresSequence(Message): ... diff --git a/stubs/pyflakes/pyflakes/reporter.pyi b/stubs/pyflakes/pyflakes/reporter.pyi new file mode 100644 index 000000000000..f6470e8c298e --- /dev/null +++ b/stubs/pyflakes/pyflakes/reporter.pyi @@ -0,0 +1,9 @@ +from _typeshed import SupportsWrite + +from .messages import Message + +class Reporter: + def __init__(self, warningStream: SupportsWrite[str], errorStream: SupportsWrite[str]) -> None: ... + def unexpectedError(self, filename: str, msg: str) -> None: ... + def syntaxError(self, filename: str, msg: str, lineno: int, offset: int | None, text: str | None) -> None: ... + def flake(self, message: Message) -> None: ... diff --git a/stubs/pyflakes/pyflakes/scripts/__init__.pyi b/stubs/pyflakes/pyflakes/scripts/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyflakes/pyflakes/scripts/pyflakes.pyi b/stubs/pyflakes/pyflakes/scripts/pyflakes.pyi new file mode 100644 index 000000000000..233bdc97b39f --- /dev/null +++ b/stubs/pyflakes/pyflakes/scripts/pyflakes.pyi @@ -0,0 +1,8 @@ +__all__ = ["check", "checkPath", "checkRecursive", "iterSourceCode", "main"] +from pyflakes.api import ( + check as check, + checkPath as checkPath, + checkRecursive as checkRecursive, + iterSourceCode as iterSourceCode, + main as main, +) diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist.txt b/stubs/pyinstaller/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f04987c54a02 --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist.txt @@ -0,0 +1,53 @@ +# fake module, only exists once the app is frozen +pyi_splash + +# Undocumented and clearly not meant to be exposed +PyInstaller\..+?\.logger +PyInstaller.__main__.generate_parser +PyInstaller.__main__.run_build +PyInstaller.__main__.run_makespec +PyInstaller.utils.hooks.conda.lib_dir + +# A mix of modules meant to be private, and shallow incomplete type references for other modules +PyInstaller\.building\.build_main\..* +PyInstaller.building.datastruct.unique_name +PyInstaller\.depend\.analysis\..* +PyInstaller\.isolated\._parent\..* +PyInstaller\.lib\.modulegraph\.modulegraph\.\w+? + +# Most modules are not meant to be used, yet are not marked as private +PyInstaller\.archive(\.\w+)* +PyInstaller.building.icon +PyInstaller.building.makespec +PyInstaller.building.osx +PyInstaller.building.splash_templates +PyInstaller.building.templates +PyInstaller.building.utils +PyInstaller.config +PyInstaller.configure +PyInstaller.depend.bindepend +PyInstaller.depend.bytecode +PyInstaller.depend.dylib +PyInstaller.depend.imphook +PyInstaller.depend.utils +PyInstaller.exceptions +PyInstaller\.hooks(\.[\w-]+)* # weird hyphens in runtime module names +PyInstaller.lib.modulegraph.__main__ +PyInstaller.lib.modulegraph.find_modules +PyInstaller.lib.modulegraph.util +PyInstaller\.loader(\.\w+)* +PyInstaller.log +PyInstaller\.utils\.cliutils(\.\w+)* +PyInstaller.utils.conftest +PyInstaller.utils.hooks.django +PyInstaller.utils.hooks.gi +PyInstaller.utils.hooks.qt +PyInstaller.utils.hooks.setuptools +PyInstaller.utils.misc +PyInstaller.utils.osx +PyInstaller.utils.run_tests +PyInstaller.utils.tests +PyInstaller.utils.win32.icon +PyInstaller.utils.win32.winmanifest +PyInstaller.utils.win32.winresource +PyInstaller.utils.win32.winutils diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt b/stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..93e1392cfd96 --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# Module can't be imported at runtime on non-win32 platforms +PyInstaller.utils.win32.versioninfo diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt b/stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..93e1392cfd96 --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# Module can't be imported at runtime on non-win32 platforms +PyInstaller.utils.win32.versioninfo diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt b/stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..72a93bf6d30a --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1 @@ +PyInstaller\.utils\.win32\.versioninfo\.\w+? diff --git a/stubs/pyinstaller/@tests/test_cases/check_versioninfo.py b/stubs/pyinstaller/@tests/test_cases/check_versioninfo.py new file mode 100644 index 000000000000..dc16ebe27d98 --- /dev/null +++ b/stubs/pyinstaller/@tests/test_cases/check_versioninfo.py @@ -0,0 +1,63 @@ +from PyInstaller.utils.win32.versioninfo import ( + FixedFileInfo, + StringFileInfo, + StringStruct, + StringTable, + VarFileInfo, + VarStruct, + VSVersionInfo, +) + +# Everything below this line is the content from running `pyi-grab_version python3` +# ============================================================================== + +# UTF-8 +# +# For more details about fixed file info 'ffi' see: +# http://msdn.microsoft.com/en-us/library/ms646997.aspx +VSVersionInfo( + ffi=FixedFileInfo( + # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4) + # Set not needed items to zero 0. + filevers=(3, 13, 1150, 1013), + prodvers=(3, 13, 1150, 1013), + # Contains a bitmask that specifies the valid bits 'flags'r + mask=0x3F, + # Contains a bitmask that specifies the Boolean attributes of the file. + flags=0x0, + # The operating system for which this file was designed. + # 0x4 - NT and there is no need to change it. + OS=0x4, + # The general type of file. + # 0x1 - the file is an application. + fileType=0x2, + # The function of the file. + # 0x0 - the function is not defined for this fileType + subtype=0x0, + # Creation date and time stamp. + date=(0, 0), + ), + kids=[ + StringFileInfo( + [ + StringTable( + "000004b0", + [ + StringStruct("CompanyName", "Python Software Foundation"), + StringStruct("FileDescription", "Python Core"), + StringStruct("FileVersion", "3.13.1"), + StringStruct("InternalName", "Python DLL"), + StringStruct( + "LegalCopyright", + "Copyright © 2001-2024 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.", + ), + StringStruct("OriginalFilename", "python3.dll"), + StringStruct("ProductName", "Python"), + StringStruct("ProductVersion", "3.13.1"), + ], + ) + ] + ), + VarFileInfo([VarStruct("Translation", [0, 1200])]), + ], +) diff --git a/stubs/pyinstaller/METADATA.toml b/stubs/pyinstaller/METADATA.toml new file mode 100644 index 000000000000..d1de5cab055d --- /dev/null +++ b/stubs/pyinstaller/METADATA.toml @@ -0,0 +1,3 @@ +version = "~=6.22.1" +upstream-repository = "https://github.com/pyinstaller/pyinstaller" +partial-stub = true diff --git a/stubs/pyinstaller/PyInstaller/__init__.pyi b/stubs/pyinstaller/PyInstaller/__init__.pyi new file mode 100644 index 000000000000..a36cbd690d8b --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/__init__.pyi @@ -0,0 +1,12 @@ +from typing import Final +from typing_extensions import LiteralString + +from PyInstaller import compat as compat + +__all__ = ("HOMEPATH", "PLATFORM", "__version__", "DEFAULT_DISTPATH", "DEFAULT_SPECPATH", "DEFAULT_WORKPATH") +__version__: Final[str] +HOMEPATH: Final[str] +DEFAULT_SPECPATH: Final[str] +DEFAULT_DISTPATH: Final[str] +DEFAULT_WORKPATH: Final[str] +PLATFORM: Final[LiteralString] diff --git a/stubs/pyinstaller/PyInstaller/__main__.pyi b/stubs/pyinstaller/PyInstaller/__main__.pyi new file mode 100644 index 000000000000..9f6397bdab29 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/__main__.pyi @@ -0,0 +1,12 @@ +from _typeshed import SupportsKeysAndGetItem +from collections.abc import Iterable +from typing import TypeAlias + +# Used to update PyInstaller.config.CONF +_PyIConfig: TypeAlias = ( + SupportsKeysAndGetItem[str, bool | str | list[str] | None] | Iterable[tuple[str, bool | str | list[str] | None]] +) + +# https://pyinstaller.org/en/stable/usage.html#running-pyinstaller-from-python-code +def run(pyi_args: Iterable[str] | None = None, pyi_config: _PyIConfig | None = None) -> None: ... +def check_unsafe_privileges() -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/building/__init__.pyi b/stubs/pyinstaller/PyInstaller/building/__init__.pyi new file mode 100644 index 000000000000..bf87a78779b4 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/__init__.pyi @@ -0,0 +1,7 @@ +from typing import TypeAlias + +# PyiBlockCipher is deprecated and misleads users into thinking it adds any security. Runtime deprecation warning: +# DEPRECATION: Bytecode encryption will be removed in PyInstaller v6. +# Please remove cipher and block_cipher parameters from your spec file to avoid breakages on upgrade. +# For the rationale/alternatives see https://github.com/pyinstaller/pyinstaller/pull/6999 +_PyiBlockCipher: TypeAlias = None # noqa: Y047 # Used by other modules diff --git a/stubs/pyinstaller/PyInstaller/building/api.pyi b/stubs/pyinstaller/PyInstaller/building/api.pyi new file mode 100644 index 000000000000..97e2c340c5a9 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/api.pyi @@ -0,0 +1,175 @@ +# PYZ, EXE and COLLECT referenced in https://pyinstaller.org/en/stable/spec-files.html#spec-file-operation +# MERGE is referenced in https://pyinstaller.org/en/stable/spec-files.html#example-merge-spec-file +# hide_console referenced in https://pyinstaller.org/en/stable/feature-notes.html#automatic-hiding-and-minimization-of-console-window-under-windows +# Not to be imported during runtime, but is the type reference for spec files which are executed as python code +import sys +from _typeshed import FileDescriptorOrPath, StrOrBytesPath, StrPath, Unused +from collections.abc import Iterable, Mapping, Sequence +from types import CodeType +from typing import ClassVar, Final, Literal, TypeAlias + +from PyInstaller.building import _PyiBlockCipher +from PyInstaller.building.build_main import Analysis +from PyInstaller.building.datastruct import Target, _TOCTuple +from PyInstaller.building.splash import Splash +from PyInstaller.utils.win32.versioninfo import VSVersionInfo + +if sys.platform == "darwin": + _TargetArch: TypeAlias = Literal["x86_64", "arm64", "universal2"] + _SupportedTargetArchParam: TypeAlias = _TargetArch | None + _CodesignIdentity: TypeAlias = str | None + _CodesignIdentityParam: TypeAlias = str | None +else: + _TargetArch: TypeAlias = None + _SupportedTargetArchParam: TypeAlias = Unused + _CodesignIdentity: TypeAlias = None + _CodesignIdentityParam: TypeAlias = Unused + +if sys.platform == "win32": + _Icon: TypeAlias = list[StrPath] | str + _IconParam: TypeAlias = StrPath | list[StrPath] | None +elif sys.platform == "darwin": + _Icon: TypeAlias = list[StrPath] | None + _IconParam: TypeAlias = StrPath | list[StrPath] | None +else: + _Icon: TypeAlias = None + _IconParam: TypeAlias = Unused + +if sys.platform == "win32": + _VersionSrc: TypeAlias = VSVersionInfo | None + _VersionParam: TypeAlias = VSVersionInfo | StrOrBytesPath | None + _Manifest: TypeAlias = bytes + _ManifestParam: TypeAlias = str | None +else: + _VersionSrc: TypeAlias = None + _VersionParam: TypeAlias = Unused + _Manifest: TypeAlias = None + _ManifestParam: TypeAlias = Unused + +_HideConsole: TypeAlias = Literal["hide-early", "minimize-early", "hide-late", "minimize-late"] | None + +class PYZ(Target): + name: str + cipher: _PyiBlockCipher + dependencies: list[_TOCTuple] + toc: list[_TOCTuple] + code_dict: dict[str, CodeType] + def __init__(self, *tocs: Iterable[_TOCTuple], name: str | None = None, cipher: _PyiBlockCipher = None) -> None: ... + def assemble(self) -> None: ... + +class PKG(Target): + xformdict: ClassVar[dict[str, str]] + toc: list[_TOCTuple] + cdict: Mapping[str, bool] + python_lib_name: str + name: str + exclude_binaries: bool + strip_binaries: bool + upx_binaries: bool + upx_exclude: Iterable[str] + target_arch: _TargetArch | None + codesign_identity: _CodesignIdentity + entitlements_file: FileDescriptorOrPath | None + def __init__( + self, + toc: Iterable[_TOCTuple], + python_lib_name: str, + name: str | None = None, + cdict: Mapping[str, bool] | None = None, + exclude_binaries: bool = False, + strip_binaries: bool = False, + upx_binaries: bool = False, + upx_exclude: Iterable[str] | None = None, + target_arch: _SupportedTargetArchParam = None, + codesign_identity: _CodesignIdentityParam = None, + entitlements_file: FileDescriptorOrPath | None = None, + ) -> None: ... + def assemble(self) -> None: ... + +class EXE(Target): + exclude_binaries: bool + bootloader_ignore_signals: bool + console: bool + hide_console: _HideConsole + disable_windowed_traceback: bool + debug: bool + name: str + icon: _Icon + versrsrc: _VersionSrc + manifest: _Manifest + embed_manifest: bool + resources: Sequence[str] + strip: bool + upx_exclude: Iterable[str] + runtime_tmpdir: str | None + contents_directory: str | None + append_pkg: bool + uac_admin: bool + uac_uiaccess: bool + argv_emulation: bool + target_arch: _TargetArch + codesign_identity: _CodesignIdentity + entitlements_file: FileDescriptorOrPath | None + upx: bool + pkgname: str + toc: list[_TOCTuple] + pkg: PKG + dependencies: list[_TOCTuple] + exefiles: list[_TOCTuple] + def __init__( + self, + *args: Iterable[_TOCTuple] | PYZ | Splash, + exclude_binaries: bool = False, + bootloader_ignore_signals: bool = False, + console: bool = True, + hide_console: _HideConsole = None, + disable_windowed_traceback: bool = False, + debug: bool = False, + name: str | None = None, + icon: _IconParam = None, + version: _VersionParam = None, + manifest: _ManifestParam = None, + embed_manifest: Literal[True] = True, + resources: Sequence[str] = ..., + strip: bool = False, + upx_exclude: Iterable[str] = ..., + runtime_tmpdir: str | None = None, + contents_directory: str = "_internal", + append_pkg: bool = True, + uac_admin: bool = False, + uac_uiaccess: bool = False, + argv_emulation: bool = False, + target_arch: _SupportedTargetArchParam = None, + codesign_identity: _CodesignIdentityParam = None, + entitlements_file: FileDescriptorOrPath | None = None, + upx: bool = False, + cdict: Mapping[str, bool] | None = None, + ) -> None: ... + mtm: float + def assemble(self) -> None: ... + +class COLLECT(Target): + strip_binaries: bool + upx_exclude: Iterable[str] + console: bool + target_arch: _TargetArch | None + codesign_identity: _CodesignIdentity + entitlements_file: FileDescriptorOrPath | None + upx_binaries: bool + name: str + toc: list[_TOCTuple] + def __init__( + self, + *args: Iterable[_TOCTuple] | EXE, + strip: bool = False, + upx_exclude: Iterable[str] = ..., + upx: bool = False, + name: str, + ) -> None: ... + def assemble(self) -> None: ... + +class MERGE: + def __init__(self, *args: tuple[Analysis, Unused, str]) -> None: ... + +UNCOMPRESSED: Final = False +COMPRESSED: Final = True diff --git a/stubs/pyinstaller/PyInstaller/building/build_main.pyi b/stubs/pyinstaller/PyInstaller/building/build_main.pyi new file mode 100644 index 000000000000..a5d93774a9f7 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/build_main.pyi @@ -0,0 +1,55 @@ +from _typeshed import StrPath +from collections.abc import Iterable +from typing import Any, Literal + +from PyInstaller.building import _PyiBlockCipher +from PyInstaller.building.datastruct import Target, _TOCTuple + +# Referenced in: https://pyinstaller.org/en/stable/hooks.html#PyInstaller.utils.hooks.get_hook_config +# Not to be imported during runtime, but is the type reference for hooks and analysis configuration +# Also referenced in https://pyinstaller.org/en/stable/spec-files.html +# Not to be imported during runtime, but is the type reference for spec files which are executed as python code +class Analysis(Target): + # https://pyinstaller.org/en/stable/hooks-config.html#hook-configuration-options + hooksconfig: dict[str, dict[str, object]] + # https://pyinstaller.org/en/stable/spec-files.html#spec-file-operation + # https://pyinstaller.org/en/stable/feature-notes.html + pure: list[_TOCTuple] + zipped_data: list[_TOCTuple] + # https://pyinstaller.org/en/stable/spec-files.html#giving-run-time-python-options + # https://pyinstaller.org/en/stable/spec-files.html#the-splash-target + scripts: list[_TOCTuple] + # https://pyinstaller.org/en/stable/feature-notes.html#practical-examples + binaries: list[_TOCTuple] + zipfiles: list[_TOCTuple] + datas: list[_TOCTuple] + + inputs: list[str] + dependencies: list[_TOCTuple] + noarchive: bool + optimize: int + pathex: list[StrPath] + hiddenimports: list[str] + hookspath: list[tuple[StrPath, int]] + excludes: list[str] + custom_runtime_hooks: list[StrPath] + # https://pyinstaller.org/en/stable/hooks.html#hook-global-variables + module_collection_mode: dict[str, str] + def __init__( + self, + scripts: Iterable[StrPath], + pathex: Iterable[StrPath] | None = None, + binaries: Iterable[tuple[StrPath, StrPath]] | None = None, + datas: Iterable[tuple[StrPath, StrPath]] | None = None, + hiddenimports: Iterable[str] | None = None, + hookspath: Iterable[StrPath] | None = None, + hooksconfig: dict[str, dict[str, Any]] | None = None, + excludes: Iterable[str] | None = None, + runtime_hooks: Iterable[StrPath] | None = None, + cipher: _PyiBlockCipher = None, + win_no_prefer_redirects: bool = False, + win_private_assemblies: bool = False, + noarchive: bool = False, + module_collection_mode: dict[str, str] | None = None, + optimize: Literal[-1, 0, 1, 2] | None = -1, + ) -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/building/datastruct.pyi b/stubs/pyinstaller/PyInstaller/building/datastruct.pyi new file mode 100644 index 000000000000..0c3878a0b9ce --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/datastruct.pyi @@ -0,0 +1,47 @@ +# https://pyinstaller.org/en/stable/advanced-topics.html#the-toc-and-tree-classes +from collections.abc import Iterable, Sequence +from typing import ClassVar, Literal, SupportsIndex, TypeAlias +from typing_extensions import LiteralString, Self + +_TypeCode: TypeAlias = Literal["DEPENDENCY", "SYMLINK", "DATA", "BINARY", "EXECUTABLE", "EXTENSION", "OPTION"] +_TOCTuple: TypeAlias = tuple[str, str | None, _TypeCode | None] + +class TOC(list[_TOCTuple]): + filenames: set[str] + def __init__(self, initlist: Iterable[_TOCTuple] | None = None) -> None: ... + def append(self, entry: _TOCTuple) -> None: ... + def insert(self, pos: SupportsIndex, entry: _TOCTuple) -> None: ... + def __add__(self, other: Iterable[_TOCTuple]) -> TOC: ... # type: ignore[override] + def __radd__(self, other: Iterable[_TOCTuple]) -> TOC: ... + def __iadd__(self, other: Iterable[_TOCTuple]) -> Self: ... # type: ignore[override] + def extend(self, other: Iterable[_TOCTuple]) -> None: ... + def __sub__(self, other: Iterable[_TOCTuple]) -> TOC: ... + def __rsub__(self, other: Iterable[_TOCTuple]) -> TOC: ... + # slicing a TOC is not supported, but has a special case for slice(None, None, None) + def __setitem__(self, key: int | slice, value: Iterable[_TOCTuple]) -> None: ... # type: ignore[override] + +class Target: + invcnum: ClassVar[int] + tocfilename: LiteralString + tocbasename: LiteralString + dependencies: list[_TOCTuple] + def __init__(self) -> None: ... + def __postinit__(self) -> None: ... + +class Tree(Target, list[_TOCTuple]): + root: str | None + prefix: str | None + excludes: Sequence[str] + typecode: _TypeCode + def __init__( + self, + root: str | None = None, + prefix: str | None = None, + excludes: Sequence[str] | None = None, + typecode: _TypeCode = "DATA", + ) -> None: ... + def assemble(self) -> None: ... + +def normalize_toc(toc: Iterable[_TOCTuple]) -> list[_TOCTuple]: ... +def normalize_pyz_toc(toc: Iterable[_TOCTuple]) -> list[_TOCTuple]: ... +def toc_process_symbolic_links(toc: Iterable[_TOCTuple]) -> list[_TOCTuple]: ... diff --git a/stubs/pyinstaller/PyInstaller/building/splash.pyi b/stubs/pyinstaller/PyInstaller/building/splash.pyi new file mode 100644 index 000000000000..4fd52ed03b96 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/splash.pyi @@ -0,0 +1,51 @@ +from _typeshed import StrPath + +from PyInstaller.building.datastruct import Target, _TOCTuple +from PyInstaller.utils.hooks.tcl_tk import TclTkInfo + +# Referenced in https://pyinstaller.org/en/stable/spec-files.html#example-merge-spec-file +# Not to be imported during runtime, but is the type reference for spec files which are executed as python code +class Splash(Target): + image_file: str + full_tk: bool + tcl_lib: str + tk_lib: str + tcl_data_dir: str + tk_data_dir: str + name: str + script_name: StrPath + minify_script: bool + max_img_size: tuple[int, int] + text_pos: tuple[int, int] | None + text_size: int + text_font: str + text_color: str + text_default: str + always_on_top: bool + uses_tkinter: bool + script: str + splash_requirements: set[str] + binaries: list[_TOCTuple] + def __init__( + self, + image_file: StrPath, + binaries: list[_TOCTuple], + datas: list[_TOCTuple], + *, + text_pos: tuple[int, int] | None = ..., + text_size: int = 12, + text_font: str = ..., + text_color: str = "black", + text_default: str = "Initializing", + full_tk: bool = False, + minify_script: bool = True, + name: str = ..., + script_name: StrPath = ..., + max_img_size: tuple[int, int] | None = (760, 480), + always_on_top: bool = True, + ) -> None: ... + def assemble(self) -> None: ... + # This private method is the only way to match Splash Screen support validation without triggering an actual build + @staticmethod + def _check_tcl_tk_compatibility(tcltk_info: TclTkInfo) -> None: ... + def generate_script(self) -> str: ... diff --git a/stubs/pyinstaller/PyInstaller/compat.pyi b/stubs/pyinstaller/PyInstaller/compat.pyi new file mode 100644 index 000000000000..dd51f4aeb530 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/compat.pyi @@ -0,0 +1,88 @@ +# https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.compat +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable +from types import ModuleType +from typing import Final, Literal, overload + +strict_collect_mode: bool +is_64bits: Final[bool] +is_py35: Final = True +is_py36: Final = True +is_py37: Final = True +is_py38: Final = True +is_py39: Final = True +is_py310: Final = True +is_py311: Final[bool] +is_py312: Final[bool] +is_py313: Final[bool] +is_py314: Final[bool] +is_py315: Final[bool] +is_win: Final[bool] +is_win_10: Final[bool] +is_win_11: Final[bool] +is_win_wine: Final[bool] +is_cygwin: Final[bool] +is_darwin: Final[bool] +is_android: Final[bool] +is_linux: Final[bool] +is_solar: Final[bool] +is_aix: Final[bool] +is_freebsd: Final[bool] +is_openbsd: Final[bool] +is_netbsd: Final[bool] +is_hpux: Final[bool] +is_unix: Final[bool] +is_musl: Final[bool] +is_termux: Final[bool] +is_macos_11_compat: Final[bool] +is_macos_11_native: Final[bool] +is_macos_11: Final[bool] +is_nogil: Final[bool] +base_prefix: Final[str] +is_venv: Final[bool] +is_virtualenv: Final[bool] +is_conda: Final[bool] +is_pure_conda: Final[bool] +python_executable: Final[str] +is_ms_app_store: Final[bool] +BYTECODE_MAGIC: Final[bytes] +EXTENSION_SUFFIXES: Final[list[str]] +ALL_SUFFIXES: Final[list[str]] + +architecture: Final[Literal["64bit", "n32bit", "32bit"]] +system: Final[Literal["Cygwin", "Linux", "Darwin", "Java", "Windows"]] +machine: Final[ + Literal["AMD64", "x86", "ARM64", "sw_64", "loongarch64", "arm", "intel", "ppc", "mips", "riscv", "s390x", "unknown"] | None +] + +def is_wine_dll(filename: FileDescriptorOrPath) -> bool: ... + +@overload +def getenv(name: str, default: str) -> str: ... +@overload +def getenv(name: str, default: None = None) -> str | None: ... + +def setenv(name: str, value: str) -> None: ... +def unsetenv(name: str) -> None: ... +def exec_command( + *cmdargs: str, encoding: str | None = None, raise_enoent: bool | None = None, **kwargs: int | bool | Iterable[int] | None +) -> str: ... +def exec_command_rc(*cmdargs: str, **kwargs: float | bool | Iterable[int] | None) -> int: ... +def exec_command_all( + *cmdargs: str, encoding: str | None = None, **kwargs: int | bool | Iterable[int] | None +) -> tuple[int, str, str]: ... +def exec_python(*args: str, **kwargs: str | None) -> str: ... +def exec_python_rc(*args: str, **kwargs: str | None) -> int: ... +def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: ... +def importlib_load_source(name: str, pathname: str) -> ModuleType: ... + +PY3_BASE_MODULES: Final[set[str]] +PURE_PYTHON_MODULE_TYPES: Final[set[str]] +SPECIAL_MODULE_TYPES: Final[set[str]] +BINARY_MODULE_TYPES: Final[set[str]] +VALID_MODULE_TYPES: Final[set[str]] +BAD_MODULE_TYPES: Final[set[str]] +ALL_MODULE_TYPES: Final[set[str]] +MODULE_TYPES_TO_TOC_DICT: Final[dict[str, str]] + +def check_requirements() -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/depend/__init__.pyi b/stubs/pyinstaller/PyInstaller/depend/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/depend/analysis.pyi b/stubs/pyinstaller/PyInstaller/depend/analysis.pyi new file mode 100644 index 000000000000..8e6f37c238d3 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/depend/analysis.pyi @@ -0,0 +1,27 @@ +# https://pyinstaller.org/en/stable/hooks.html#the-pre-safe-import-module-psim-api-method + +# The documentation explicitly mentions that "Normally you do not need to know about the module-graph." +# However, some PyiModuleGraph typed class attributes are still documented as existing in imphookapi. +from _typeshed import Incomplete, StrPath, SupportsKeysAndGetItem +from collections.abc import Iterable +from typing import TypeAlias + +from PyInstaller.lib.modulegraph.modulegraph import Alias, Node + +_LazyNode: TypeAlias = Iterable[Node] | Iterable[str] | Alias | None +# from altgraph.Graph import Graph +_Graph: TypeAlias = Incomplete + +class PyiModuleGraph: # incomplete + def __init__( + self, + pyi_homepath: str, + user_hook_dirs: Iterable[StrPath] = (), + excludes: Iterable[str] = (), + *, + path: Iterable[str] | None = None, + replace_paths: Iterable[tuple[StrPath, StrPath]] = ..., + implies: SupportsKeysAndGetItem[str, _LazyNode] | Iterable[tuple[str, _LazyNode]] = ..., + graph: _Graph | None = None, + debug: bool = False, + ) -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi b/stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi new file mode 100644 index 000000000000..286aac070973 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi @@ -0,0 +1,71 @@ +# https://pyinstaller.org/en/stable/hooks-config.html#adding-an-option-to-the-hook `hook_api` is a PostGraphAPI +# Nothing in this module is meant to be initialized externally. +# Instances are exposed through hooks during build. + +from _typeshed import StrOrBytesPath +from collections.abc import Generator, Iterable +from types import CodeType +from typing import Literal + +from PyInstaller.building.build_main import Analysis +from PyInstaller.building.datastruct import TOC +from PyInstaller.depend.analysis import PyiModuleGraph +from PyInstaller.lib.modulegraph.modulegraph import Package + +# https://pyinstaller.org/en/stable/hooks.html#the-pre-safe-import-module-psim-api-method +class PreSafeImportModuleAPI: + module_basename: str + module_name: str + def __init__( + self, module_graph: PyiModuleGraph, module_basename: str, module_name: str, parent_package: Package | None + ) -> None: ... + @property + def module_graph(self) -> PyiModuleGraph: ... + @property + def parent_package(self) -> Package | None: ... + def add_runtime_module(self, module_name: str) -> None: ... + def add_runtime_package(self, package_name: str) -> None: ... + def add_alias_module(self, real_module_name: str, alias_module_name: str) -> None: ... + def append_package_path(self, directory: str) -> None: ... + +# https://pyinstaller.org/en/stable/hooks.html#the-pre-find-module-path-pfmp-api-method +class PreFindModulePathAPI: + search_dirs: Iterable[StrOrBytesPath] + def __init__(self, module_graph: PyiModuleGraph, module_name: str, search_dirs: Iterable[StrOrBytesPath]) -> None: ... + @property + def module_graph(self) -> PyiModuleGraph: ... + @property + def module_name(self) -> str: ... + +# https://pyinstaller.org/en/stable/hooks.html#the-hook-hook-api-function +class PostGraphAPI: + module_graph: PyiModuleGraph + module: Package + def __init__(self, module_name: str, module_graph: PyiModuleGraph, analysis: Analysis) -> None: ... + @property + def __file__(self) -> str: ... + @property + def __path__(self) -> tuple[str, ...] | None: ... + @property + def __name__(self) -> str: ... + # Compiled code. See stdlib.builtins.compile + @property + def co(self) -> CodeType: ... + @property + def analysis(self) -> Analysis: ... + @property + def name(self) -> str: ... + @property + def graph(self) -> PyiModuleGraph: ... + @property + def node(self) -> Package: ... + @property + def imports(self) -> Generator[Package]: ... + def add_imports(self, *module_names: str) -> None: ... + def del_imports(self, *module_names: str) -> None: ... + def add_binaries(self, binaries: TOC | Iterable[tuple[StrOrBytesPath, StrOrBytesPath]]) -> None: ... + def add_datas(self, datas: TOC | Iterable[tuple[StrOrBytesPath, StrOrBytesPath]]) -> None: ... + def set_module_collection_mode( + self, name: str | None, mode: Literal["pyz", "pyc", "py", "pyz+py", "py+pyz"] | None + ) -> None: ... + def add_bindepend_symlink_suppression_pattern(self, pattern: str) -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/isolated/__init__.pyi b/stubs/pyinstaller/PyInstaller/isolated/__init__.pyi new file mode 100644 index 000000000000..6f084bfc40ea --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/isolated/__init__.pyi @@ -0,0 +1,2 @@ +# https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.isolated +from PyInstaller.isolated._parent import Python as Python, call as call, decorate as decorate diff --git a/stubs/pyinstaller/PyInstaller/isolated/_parent.pyi b/stubs/pyinstaller/PyInstaller/isolated/_parent.pyi new file mode 100644 index 000000000000..78b20d73f9cb --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/isolated/_parent.pyi @@ -0,0 +1,19 @@ +from collections.abc import Callable +from types import TracebackType +from typing import ParamSpec, TypeVar +from typing_extensions import Self + +_AC = TypeVar("_AC", bound=Callable[..., object]) +_R = TypeVar("_R") +_P = ParamSpec("_P") + +class Python: + def __init__(self, strict_mode: bool | None = None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def call(self, function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + +def call(function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... +def decorate(function: _AC) -> _AC: ... diff --git a/stubs/pyinstaller/PyInstaller/lib/__init__.pyi b/stubs/pyinstaller/PyInstaller/lib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/lib/modulegraph/__init__.pyi b/stubs/pyinstaller/PyInstaller/lib/modulegraph/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi b/stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi new file mode 100644 index 000000000000..2783e2249008 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi @@ -0,0 +1,57 @@ +# Partial typing of the vendored modulegraph package. +# We reference the vendored package rather than depending on the original untyped module. +# Anything not referenced in the PyInstaller stubs doesn't need to be added here. + +from types import CodeType +from typing import Protocol, type_check_only + +@type_check_only +class _SupportsGraphident(Protocol): + graphident: str + +# code, filename and packagepath are always initialized to None. But they can be given a value later. +class Node: + # Compiled code. See stdlib.builtins.compile + __slots__ = [ + "code", + "filename", + "graphident", + "identifier", + "packagepath", + "_deferred_imports", + "_global_attr_names", + "_starimported_ignored_module_names", + "_submodule_basename_to_node", + ] + code: CodeType | None + filename: str | None + graphident: str + identifier: str + packagepath: str | None + def __init__(self, identifier: str) -> None: ... + def is_global_attr(self, attr_name: str) -> bool: ... + def is_submodule(self, submodule_basename: str) -> bool: ... + def add_global_attr(self, attr_name: str) -> None: ... + def add_global_attrs_from_module(self, target_module: Node) -> None: ... + def add_submodule(self, submodule_basename: str, submodule_node: Node) -> None: ... + def get_submodule(self, submodule_basename: str) -> Node: ... + def get_submodule_or_none(self, submodule_basename: str) -> Node | None: ... + def remove_global_attr_if_found(self, attr_name: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: _SupportsGraphident) -> bool: ... + def __le__(self, other: _SupportsGraphident) -> bool: ... + def __gt__(self, other: _SupportsGraphident) -> bool: ... + def __ge__(self, other: _SupportsGraphident) -> bool: ... + def infoTuple(self) -> tuple[str]: ... + +class Alias(str): ... + +class BaseModule(Node): + filename: str + packagepath: str + def __init__(self, name: str, filename: str | None = None, path: str | None = None) -> None: ... + # Returns a tuple of length 0, 1, 2, or 3 + def infoTuple(self) -> tuple[str, ...]: ... # type: ignore[override] + +class Package(BaseModule): ... diff --git a/stubs/pyinstaller/PyInstaller/utils/__init__.pyi b/stubs/pyinstaller/PyInstaller/utils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi b/stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi new file mode 100644 index 000000000000..bab6ffebfa1b --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi @@ -0,0 +1,76 @@ +# https://pyinstaller.org/en/stable/hooks.html + +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Callable, Iterable +from typing import Any, Final, Literal + +from PyInstaller import HOMEPATH as HOMEPATH +from PyInstaller.depend.imphookapi import PostGraphAPI +from PyInstaller.utils.hooks import conda + +conda_support = conda + +PY_IGNORE_EXTENSIONS: Final[set[str]] +hook_variables: dict[str, str] + +def exec_statement(statement: str) -> str | int: ... +def exec_statement_rc(statement: str) -> str | int: ... +def eval_statement(statement: str) -> Any | Literal[""]: ... +def get_pyextension_imports(module_name: str) -> list[str]: ... +def get_homebrew_path(formula: str = "") -> str | None: ... +def remove_prefix(string: str, prefix: str) -> str: ... +def remove_suffix(string: str, suffix: str) -> str: ... +def remove_file_extension(filename: str) -> str: ... +def can_import_module(module_name: str) -> bool: ... +def get_module_attribute(module_name: str, attr_name: str) -> Any: ... +def get_module_file_attribute(package: str) -> str | None: ... +def get_pywin32_module_file_attribute(module_name: str) -> str | None: ... +def check_requirement(requirement: str) -> bool: ... +def is_module_satisfies(requirements: str, version: None = None, version_attr: None = None) -> bool: ... +def is_package(module_name: str) -> bool: ... +def get_all_package_paths(package: str) -> list[str]: ... +def package_base_path(package_path: str, package: str) -> str: ... +def get_package_paths(package: str) -> tuple[str, str]: ... +def collect_submodules( + package: str, filter: Callable[[str], bool] = ..., on_error: Literal["ignore", "warn once", "warn", "raise"] = "warn once" +) -> list[str]: ... +def is_module_or_submodule(name: str, mod_or_submod: str) -> bool: ... + +PY_DYLIB_PATTERNS: Final[list[str]] + +def collect_dynamic_libs( + package: str, destdir: object = None, search_patterns: Iterable[str] = ["*.dll", "*.dylib", "lib*.so"] +) -> list[tuple[str, str]]: ... +def collect_data_files( + package: str, + include_py_files: bool = False, + subdir: StrPath | None = None, + excludes: Iterable[str] | None = None, + includes: Iterable[str] | None = None, +) -> list[tuple[str, str]]: ... +def collect_system_data_files( + path: str, destdir: StrPath | None = None, include_py_files: bool = False +) -> list[tuple[str, str]]: ... +def copy_metadata(package_name: str, recursive: bool = False) -> list[tuple[str, str]]: ... +def get_installer(dist_name: str) -> str | None: ... +def collect_all( + package_name: str, + include_py_files: bool = True, + filter_submodules: Callable[[str], bool] = ..., + exclude_datas: Iterable[str] | None = None, + include_datas: Iterable[str] | None = None, + on_error: Literal["ignore", "warn once", "warn", "raise"] = "warn once", +) -> tuple[list[tuple[str, str]], list[tuple[str, str]], list[str]]: ... +def collect_entry_point(name: str) -> tuple[list[tuple[str, str]], list[str]]: ... +def get_hook_config(hook_api: PostGraphAPI, module_name: str, key: str) -> None: ... +def include_or_exclude_file( + filename: StrOrBytesPath, + include_list: Iterable[StrOrBytesPath] | None = None, + exclude_list: Iterable[StrOrBytesPath] | None = None, +) -> bool: ... +def collect_delvewheel_libs_directory( + package_name: str, + libdir_name: StrPath | None = None, + datas: list[tuple[str, str]] | None = None, + binaries: list[tuple[str, str]] | None = None, +) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]: ... diff --git a/stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi b/stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi new file mode 100644 index 000000000000..0fc169607cc0 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi @@ -0,0 +1,48 @@ +# https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.utils.hooks.conda + +from _typeshed import StrOrBytesPath +from collections.abc import Iterable +from importlib.metadata import PackagePath as _PackagePath +from pathlib import Path +from typing import Final, TypedDict, type_check_only + +CONDA_ROOT: Final[Path] +CONDA_META_DIR: Final[Path] +PYTHONPATH_PREFIXES: Final[list[Path]] + +@type_check_only +class _RawDict(TypedDict): + name: str + version: str + files: list[StrOrBytesPath] + depends: list[str] + +class Distribution: + raw: _RawDict + name: str + version: str + files: list[PackagePath] + dependencies: list[str] + packages: list[str] + def __init__(self, json_path: str) -> None: ... + @classmethod + def from_name(cls, name: str) -> Distribution: ... + @classmethod + def from_package_name(cls, name: str) -> Distribution: ... + +# distribution and package_distribution are meant to be used and are not internal helpers +distribution = Distribution.from_name +package_distribution = Distribution.from_package_name + +class PackagePath(_PackagePath): + def locate(self) -> Path: ... + +def walk_dependency_tree(initial: str, excludes: Iterable[str] | None = None) -> dict[str, Distribution]: ... +def requires(name: str, strip_versions: bool = False) -> list[str]: ... +def files(name: str, dependencies: bool = False, excludes: Iterable[str] | None = None) -> list[PackagePath]: ... +def collect_dynamic_libs( + name: str, dest: str = ".", dependencies: bool = True, excludes: Iterable[str] | None = None +) -> list[tuple[str, str]]: ... + +distributions: dict[str, Distribution] +distributions_by_package: dict[str | None, Distribution] diff --git a/stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi b/stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi new file mode 100644 index 000000000000..e73a5e1193dc --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi @@ -0,0 +1,22 @@ +from typing import Final + +class TclTkInfo: + TCL_ROOTNAME: Final = "_tcl_data" + TK_ROOTNAME: Final = "_tk_data" + def __init__(self) -> None: ... + available: bool + tkinter_extension_file: str | None + tcl_version: tuple[int, int] | None + tk_version: tuple[int, int] | None + tcl_threaded: bool + tcl_data_dir: str | None + tk_data_dir: str | None + tcl_module_dir: str | None + tcl_data_missing: bool + tk_data_missing: bool + is_macos_system_framework: bool + tcl_shared_library: str | None + tk_shared_library: str | None + data_files: list[tuple[str, str, str]] + +tcltk_info: TclTkInfo diff --git a/stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi b/stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi new file mode 100644 index 000000000000..1e2e7c6425ef --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi @@ -0,0 +1,98 @@ +from _typeshed import SliceableBuffer, Unused +from collections.abc import Sequence +from typing import Any, Protocol, TypeAlias, type_check_only + +_FourIntSequence: TypeAlias = Sequence[int] +_TwoIntSequence: TypeAlias = Sequence[int] + +@type_check_only +class _Kid(Protocol): + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "", /) -> str: ... + +# All the classes below are used in version_file_info generated by `pyi-grab_version` +# See: https://pyinstaller.org/en/stable/usage.html#capturing-windows-version-data + +# VSVersionInfo is also by other types referenced in https://pyinstaller.org/en/stable/spec-files.html#spec-file-operation +class VSVersionInfo: + ffi: FixedFileInfo | None + kids: list[_Kid] + def __init__(self, ffi: FixedFileInfo | None = None, kids: list[_Kid] | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class FixedFileInfo: + sig: int + strucVersion: int + fileVersionMS: int + fileVersionLS: int + productVersionMS: int + productVersionLS: int + fileFlagsMask: int + fileFlags: int + fileOS: int + fileType: int + fileSubtype: int + fileDateMS: int + fileDateLS: int + def __init__( + self, + filevers: _FourIntSequence = (0, 0, 0, 0), + prodvers: _FourIntSequence = (0, 0, 0, 0), + mask: int = 0x3F, + flags: int = 0x0, + OS: int = 0x40004, + fileType: int = 0x1, + subtype: int = 0x0, + date: _TwoIntSequence = (0, 0), + ) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class StringFileInfo: + name: str + kids: list[_Kid] + def __init__(self, kids: list[_Kid] | None = None) -> None: ... + def fromRaw(self, sublen: Unused, vallen: Unused, name: str, data: SliceableBuffer, i: int, limit: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class StringTable: + name: str + kids: list[_Kid] + def __init__(self, name: str | None = None, kids: list[_Kid] | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int, limit: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class StringStruct: + name: str + val: str + def __init__(self, name: str | None = None, val: str | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int, limit: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: Unused = "") -> str: ... + +class VarFileInfo: + kids: list[_Kid] + def __init__(self, kids: list[_Kid] | None = None) -> None: ... + sublen: int + vallen: int + name: str + def fromRaw(self, sublen: int, vallen: int, name: str, data: SliceableBuffer, i: int, limit: int) -> int: ... + wType: int + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class VarStruct: + name: str + kids: list[Any] # Whatever can be passed to struct.pack + def __init__(self, name: str | None = None, kids: list[Any] | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int, limit: Unused) -> int: ... + wValueLength: int + wType: int + sublen: int + def toRaw(self) -> bytes: ... + def __str__(self, indent: Unused = "") -> str: ... diff --git a/stubs/pyinstaller/pyi_splash/__init__.pyi b/stubs/pyinstaller/pyi_splash/__init__.pyi new file mode 100644 index 000000000000..6be5e623decc --- /dev/null +++ b/stubs/pyinstaller/pyi_splash/__init__.pyi @@ -0,0 +1,13 @@ +# Referenced in: https://pyinstaller.org/en/stable/advanced-topics.html#module-pyi_splash +# Source: https://github.com/pyinstaller/pyinstaller/blob/develop/PyInstaller/fake-modules/pyi_splash.py + +from typing import Final + +__all__ = ["CLOSE_CONNECTION", "FLUSH_CHARACTER", "is_alive", "close", "update_text"] + +def is_alive() -> bool: ... +def update_text(msg: str) -> None: ... +def close() -> None: ... + +CLOSE_CONNECTION: Final = b"\x04" +FLUSH_CHARACTER: Final = b"\x0d" diff --git a/stubs/pyjks/@tests/stubtest_allowlist.txt b/stubs/pyjks/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ad6b02338ea7 --- /dev/null +++ b/stubs/pyjks/@tests/stubtest_allowlist.txt @@ -0,0 +1,35 @@ +# Attributes implemented by __getattr__ +jks.jks.PrivateKeyEntry.algorithm_oid +jks.jks.PrivateKeyEntry.pkey +jks.jks.PrivateKeyEntry.pkey_pkcs8 +jks.jks.SecretKeyEntry.algorithm +jks.jks.SecretKeyEntry.key +jks.jks.SecretKeyEntry.key_size + +# Implicit imports, not re-exported +jks.DSA_OID +jks.DSA_WITH_SHA1_OID +jks.ENTRY_TYPE_CERTIFICATE +jks.ENTRY_TYPE_KEY +jks.ENTRY_TYPE_SEALED +jks.ENTRY_TYPE_SECRET +jks.KEY_TYPE_PRIVATE +jks.KEY_TYPE_PUBLIC +jks.KEY_TYPE_SECRET +jks.MAGIC_NUMBER_JCEKS +jks.MAGIC_NUMBER_JKS +jks.RSA_ENCRYPTION_OID +jks.SIGNATURE_WHITENING +jks.py23basestring +jks.bks.DSA_OID +jks.bks.DSA_WITH_SHA1_OID +jks.bks.RSA_ENCRYPTION_OID +jks.bks.py23basestring +jks.jks.DSA_OID +jks.jks.DSA_WITH_SHA1_OID +jks.jks.RSA_ENCRYPTION_OID +jks.jks.py23basestring +jks.sun_crypto.DSA_OID +jks.sun_crypto.DSA_WITH_SHA1_OID +jks.sun_crypto.RSA_ENCRYPTION_OID +jks.sun_crypto.py23basestring diff --git a/stubs/pyjks/METADATA.toml b/stubs/pyjks/METADATA.toml new file mode 100644 index 000000000000..20eeae1e0c06 --- /dev/null +++ b/stubs/pyjks/METADATA.toml @@ -0,0 +1,3 @@ +version = "20.0.*" +upstream-repository = "https://github.com/kurtbrose/pyjks" +dependencies = ["types-pyasn1"] diff --git a/stubs/pyjks/jks/__init__.pyi b/stubs/pyjks/jks/__init__.pyi new file mode 100644 index 000000000000..26eee4cd284a --- /dev/null +++ b/stubs/pyjks/jks/__init__.pyi @@ -0,0 +1,48 @@ +# pyjks exports lots of junk such as jks.jks.SIGNATURE_WHITENING, jks.util.b8 etc. +# We don't mark those as re-exported as those don't seem like intended part of the public API. +from .bks import ( + AbstractBksEntry as AbstractBksEntry, + BksKeyEntry as BksKeyEntry, + BksKeyStore as BksKeyStore, + BksSealedKeyEntry as BksSealedKeyEntry, + BksSecretKeyEntry as BksSecretKeyEntry, + BksTrustedCertEntry as BksTrustedCertEntry, + UberKeyStore as UberKeyStore, +) +from .jks import ( + KeyStore as KeyStore, + PrivateKeyEntry as PrivateKeyEntry, + SecretKeyEntry as SecretKeyEntry, + TrustedCertEntry as TrustedCertEntry, + __version__ as __version__, + __version_info__ as __version_info__, +) +from .util import ( + AbstractKeystore as AbstractKeystore, + AbstractKeystoreEntry as AbstractKeystoreEntry, + BadDataLengthException as BadDataLengthException, + BadHashCheckException as BadHashCheckException, + BadKeystoreFormatException as BadKeystoreFormatException, + BadPaddingException as BadPaddingException, + DecryptionFailureException as DecryptionFailureException, + DuplicateAliasException as DuplicateAliasException, + KeystoreException as KeystoreException, + KeystoreSignatureException as KeystoreSignatureException, + NotYetDecryptedException as NotYetDecryptedException, + UnexpectedAlgorithmException as UnexpectedAlgorithmException, + UnexpectedJavaTypeException as UnexpectedJavaTypeException, + UnexpectedKeyEncodingException as UnexpectedKeyEncodingException, + UnsupportedKeyFormatException as UnsupportedKeyFormatException, + UnsupportedKeystoreEntryTypeException as UnsupportedKeystoreEntryTypeException, + UnsupportedKeystoreTypeException as UnsupportedKeystoreTypeException, + UnsupportedKeystoreVersionException as UnsupportedKeystoreVersionException, + add_pkcs7_padding as add_pkcs7_padding, + as_hex as as_hex, + as_pem as as_pem, + bitstring_to_bytes as bitstring_to_bytes, + pkey_as_pem as pkey_as_pem, + print_pem as print_pem, + strip_pkcs5_padding as strip_pkcs5_padding, + strip_pkcs7_padding as strip_pkcs7_padding, + xor_bytearrays as xor_bytearrays, +) diff --git a/stubs/pyjks/jks/bks.pyi b/stubs/pyjks/jks/bks.pyi new file mode 100644 index 000000000000..d083d6b95d2f --- /dev/null +++ b/stubs/pyjks/jks/bks.pyi @@ -0,0 +1,125 @@ +from _typeshed import SupportsKeysAndGetItem, Unused +from typing import Final, Literal, TypeAlias +from typing_extensions import Self + +from .jks import TrustedCertEntry +from .util import AbstractKeystore, AbstractKeystoreEntry + +_BksType: TypeAlias = Literal["bks", "uber"] +_CertType: TypeAlias = Literal["X.509"] +_EntryFormat: TypeAlias = Literal["PKCS8", "PKCS#8", "X.509", "X509", "RAW"] +_BksVersion: TypeAlias = Literal[1, 2] + +ENTRY_TYPE_CERTIFICATE: Final = 1 +ENTRY_TYPE_KEY: Final = 2 +ENTRY_TYPE_SECRET: Final = 3 +ENTRY_TYPE_SEALED: Final = 4 + +KEY_TYPE_PRIVATE: Final = 0 +KEY_TYPE_PUBLIC: Final = 1 +KEY_TYPE_SECRET: Final = 2 +_KeyType: TypeAlias = Literal[0, 1, 2] + +class AbstractBksEntry(AbstractKeystoreEntry): + store_type: _BksType | None + cert_chain: list[tuple[_CertType, bytes]] + def __init__( + self, + *, + cert_chain: list[tuple[_CertType, bytes]] = ..., + encrypted: bytes | None = None, + store_type: _BksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + +class BksTrustedCertEntry(TrustedCertEntry): + store_type: _BksType | None # type: ignore[assignment] + +class BksKeyEntry(AbstractBksEntry): + type: _KeyType + format: _EntryFormat + algorithm: str + encoded: bytes + # type == KEY_TYPE_PRIVATE + pkey_pkcs8: bytes + pkey: bytes + algorithm_oid: tuple[int, ...] + # type == KEY_TYPE_PUBLIC + public_key_info: bytes + public_key: bytes + # type == KEY_TYPE_SECRET + key: bytes + key_size: int + def __init__( + self, + type: _KeyType, + format: _EntryFormat, + algorithm: str, + encoded: bytes, + *, + cert_chain: list[tuple[_CertType, bytes]] = ..., + encrypted: bytes | None = None, + store_type: _BksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + @classmethod + def type2str(cls, t: _KeyType) -> Literal["PRIVATE", "PUBLIC", "SECRET"]: ... + def is_decrypted(self) -> Literal[True]: ... + +class BksSecretKeyEntry(AbstractBksEntry): + key: bytes + def is_decrypted(self) -> Literal[True]: ... + +class BksSealedKeyEntry(AbstractBksEntry): + # Properties provided by __getattr__ + nested: BksKeyEntry | None + # __getattr__ proxies all attributes of nested BksKeyEntry after decrypting + type: _KeyType + format: _EntryFormat + algorithm: str + encoded: bytes + # if type == KEY_TYPE_PRIVATE + pkey_pkcs8: bytes + pkey: bytes + algorithm_oid: tuple[int, ...] + # if type == KEY_TYPE_PUBLIC + public_key_info: bytes + public_key: bytes + # if type == KEY_TYPE_SECRET + key: bytes + key_size: int + +class BksKeyStore(AbstractKeystore): + store_type: Literal["bks"] + entries: dict[str, BksTrustedCertEntry | BksKeyEntry | BksSealedKeyEntry | BksSecretKeyEntry] # type: ignore[assignment] + version: _BksVersion + def __init__( + self, + store_type: Literal["bks"], + entries: SupportsKeysAndGetItem[str, BksTrustedCertEntry | BksKeyEntry | BksSealedKeyEntry | BksSecretKeyEntry], + version: _BksVersion = 2, + ) -> None: ... + @property + def certs(self) -> dict[str, BksTrustedCertEntry]: ... + @property + def plain_keys(self) -> dict[str, BksKeyEntry]: ... + @property + def sealed_keys(self) -> dict[str, BksSealedKeyEntry]: ... + @property + def secret_keys(self) -> dict[str, BksSecretKeyEntry]: ... + @classmethod + def loads(cls, data: bytes, store_password: str, try_decrypt_keys: bool = True) -> Self: ... + +class UberKeyStore(BksKeyStore): + store_type: Literal["uber"] # type: ignore[assignment] + version: Literal[1] + def __init__( + self, + store_type: Literal["uber"], + entries: SupportsKeysAndGetItem[str, BksTrustedCertEntry | BksKeyEntry | BksSealedKeyEntry | BksSecretKeyEntry], + version: Literal[1] = 1, + ) -> None: ... diff --git a/stubs/pyjks/jks/jks.pyi b/stubs/pyjks/jks/jks.pyi new file mode 100644 index 000000000000..d6c22d6e2998 --- /dev/null +++ b/stubs/pyjks/jks/jks.pyi @@ -0,0 +1,131 @@ +from _typeshed import SupportsKeysAndGetItem, Unused +from collections.abc import Iterable +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Never, Self + +from .util import AbstractKeystore, AbstractKeystoreEntry + +__version_info__: Final[tuple[int, int, int] | tuple[int, int, int, str]] +__version__: Final[str] +MAGIC_NUMBER_JKS: Final[bytes] +MAGIC_NUMBER_JCEKS: Final[bytes] +SIGNATURE_WHITENING: Final[bytes] + +_JksType: TypeAlias = Literal["jks", "jceks"] +_CertType: TypeAlias = Literal["X.509"] +_KeyFormat: TypeAlias = Literal["pkcs8", "rsa_raw"] + +class TrustedCertEntry(AbstractKeystoreEntry): + store_type: _JksType | None + type: _CertType | None + cert: bytes + # NB! For most use cases, use TrustedCertEntry.new() classmethod. + def __init__( + self, + *, + type: _CertType | None = None, + cert: bytes, + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + @classmethod + def new(cls, alias: str, cert: bytes) -> Self: ... # type: ignore[override] + def is_decrypted(self) -> Literal[True]: ... + +class PrivateKeyEntry(AbstractKeystoreEntry): + store_type: _JksType | None + cert_chain: list[tuple[_CertType, bytes]] + # Properties provided by __getattr__ after decryption + @property + def pkey(self) -> bytes: ... + @property + def pkey_pkcs8(self) -> bytes: ... + @property + def algorithm_oid(self) -> tuple[int, ...]: ... + + # NB! For most use cases, use PrivateKeyEntry.new() classmethod. + # Overloaded: must provide `encrypted` OR `pkey`, `pkey_pkcs8`, `algorithm_oid` + @overload + def __init__( + self, + *, + cert_chain: list[tuple[_CertType, bytes]], + encrypted: bytes, + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + @overload + def __init__( + self, + *, + cert_chain: list[tuple[_CertType, bytes]], + pkey: bytes, + pkey_pkcs8: bytes, + algorithm_oid: tuple[int, ...], + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + + @classmethod + def new( # type: ignore[override] + cls, alias: str, certs: Iterable[bytes], key: bytes, key_format: _KeyFormat = "pkcs8" + ) -> Self: ... + +class SecretKeyEntry(AbstractKeystoreEntry): + store_type: _JksType | None + # Properties provided by __getattr__ + @property + def algorithm(self) -> str: ... + @property + def key(self) -> bytes: ... + @property + def key_size(self) -> int: ... + + # Overloaded: must provide `sealed_obj` OR `algorithm`, `key`, `key_size` + @overload + def __init__( + self, *, sealed_obj: bytes, store_type: _JksType | None = None, alias: str, timestamp: int, **kwargs: Unused + ) -> None: ... + @overload + def __init__( + self, + *, + algorithm: str, + key: bytes, + key_size: int, + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + + # Not implemented by pyjks + @classmethod + def new(cls, alias: str, sealed_obj: bool, algorithm: str, key: bytes, key_size: int) -> Never: ... # type: ignore[override] + # Not implemented by pyjks + def encrypt(self, key_password: str) -> Never: ... + +class KeyStore(AbstractKeystore): + entries: dict[str, TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry] # type: ignore[assignment] + store_type: _JksType + @classmethod + def new(cls, store_type: _JksType, store_entries: Iterable[TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry]) -> Self: ... + @classmethod + def loads(cls, data: bytes, store_password: str | None, try_decrypt_keys: bool = True) -> Self: ... + def saves(self, store_password: str) -> bytes: ... + # NB! For most use cases, use KeyStore.new() classmethod. + def __init__( + self, store_type: _JksType, entries: SupportsKeysAndGetItem[str, TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry] + ) -> None: ... + @property + def certs(self) -> dict[str, TrustedCertEntry]: ... + @property + def secret_keys(self) -> dict[str, SecretKeyEntry]: ... + @property + def private_keys(self) -> dict[str, PrivateKeyEntry]: ... diff --git a/stubs/pyjks/jks/rfc2898.pyi b/stubs/pyjks/jks/rfc2898.pyi new file mode 100644 index 000000000000..b6711c502262 --- /dev/null +++ b/stubs/pyjks/jks/rfc2898.pyi @@ -0,0 +1,5 @@ +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.univ import Sequence + +class PBEParameter(Sequence): + componentType: NamedTypes diff --git a/stubs/pyjks/jks/rfc7292.pyi b/stubs/pyjks/jks/rfc7292.pyi new file mode 100644 index 000000000000..400f6d577568 --- /dev/null +++ b/stubs/pyjks/jks/rfc7292.pyi @@ -0,0 +1,28 @@ +from hashlib import _Hash +from typing import Final, Literal, TypeAlias + +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.univ import Sequence + +PBE_WITH_SHA1_AND_TRIPLE_DES_CBC_OID: Final[tuple[int, ...]] +PURPOSE_KEY_MATERIAL: Final = 1 +PURPOSE_IV_MATERIAL: Final = 2 +PURPOSE_MAC_MATERIAL: Final = 3 + +_Purpose: TypeAlias = Literal[1, 2, 3] + +class Pkcs12PBEParams(Sequence): + componentType: NamedTypes + +def derive_key( + hashfn: _Hash, purpose_byte: _Purpose, password_str: str, salt: bytes, iteration_count: int, desired_key_size: int +) -> bytes: ... +def decrypt_PBEWithSHAAnd3KeyTripleDESCBC( + data: bytes | bytearray, password_str: str, salt: bytes, iteration_count: int +) -> bytes: ... +def decrypt_PBEWithSHAAndTwofishCBC( + encrypted_data: bytes | bytearray, password: str, salt: bytes, iteration_count: int +) -> bytes: ... +def encrypt_PBEWithSHAAndTwofishCBC( + plaintext_data: bytes | bytearray, password: str, salt: bytes, iteration_count: int +) -> bytes: ... diff --git a/stubs/pyjks/jks/sun_crypto.pyi b/stubs/pyjks/jks/sun_crypto.pyi new file mode 100644 index 000000000000..94ae49d4b828 --- /dev/null +++ b/stubs/pyjks/jks/sun_crypto.pyi @@ -0,0 +1,8 @@ +from typing import Final + +SUN_JKS_ALGO_ID: Final[tuple[int, ...]] +SUN_JCE_ALGO_ID: Final[tuple[int, ...]] + +def jks_pkey_encrypt(key: bytes | bytearray, password_str: str) -> bytes: ... +def jks_pkey_decrypt(data: bytes | bytearray, password_str: str) -> bytes: ... +def jce_pbe_decrypt(data: bytes | bytearray, password: str, salt: bytes, iteration_count: int) -> bytes: ... diff --git a/stubs/pyjks/jks/util.pyi b/stubs/pyjks/jks/util.pyi new file mode 100644 index 000000000000..8e913d36654c --- /dev/null +++ b/stubs/pyjks/jks/util.pyi @@ -0,0 +1,66 @@ +from _typeshed import FileDescriptorOrPath, SupportsKeysAndGetItem, Unused +from collections.abc import Iterable +from struct import Struct +from typing import Final, Literal, TypeAlias +from typing_extensions import Self + +from .bks import BksKeyEntry +from .jks import PrivateKeyEntry + +b8: Final[Struct] +b4: Final[Struct] +b2: Final[Struct] +b1: Final[Struct] +py23basestring: Final[tuple[type[str], type[str]]] +RSA_ENCRYPTION_OID: Final[tuple[int, ...]] +DSA_OID: Final[tuple[int, ...]] +DSA_WITH_SHA1_OID: Final[tuple[int, ...]] + +_KeystoreType: TypeAlias = Literal["jks", "jceks", "bks", "uber"] +_PemType: TypeAlias = Literal["CERTIFICATE", "PUBLIC KEY", "PRIVATE KEY", "RSA PRIVATE KEY"] + +class KeystoreException(Exception): ... +class KeystoreSignatureException(KeystoreException): ... +class DuplicateAliasException(KeystoreException): ... +class NotYetDecryptedException(KeystoreException): ... +class BadKeystoreFormatException(KeystoreException): ... +class BadDataLengthException(KeystoreException): ... +class BadPaddingException(KeystoreException): ... +class BadHashCheckException(KeystoreException): ... +class DecryptionFailureException(KeystoreException): ... +class UnsupportedKeystoreVersionException(KeystoreException): ... +class UnexpectedJavaTypeException(KeystoreException): ... +class UnexpectedAlgorithmException(KeystoreException): ... +class UnexpectedKeyEncodingException(KeystoreException): ... +class UnsupportedKeystoreTypeException(KeystoreException): ... +class UnsupportedKeystoreEntryTypeException(KeystoreException): ... +class UnsupportedKeyFormatException(KeystoreException): ... + +class AbstractKeystore: + store_type: _KeystoreType + entries: dict[str, AbstractKeystoreEntry] + def __init__(self, store_type: _KeystoreType, entries: SupportsKeysAndGetItem[str, AbstractKeystoreEntry]) -> None: ... + @classmethod + def load(cls, filename: FileDescriptorOrPath, store_password: str | None, try_decrypt_keys: bool = True) -> Self: ... + def save(self, filename: FileDescriptorOrPath, store_password: str) -> None: ... + +class AbstractKeystoreEntry: + store_type: _KeystoreType | None + alias: str + timestamp: int + def __init__(self, *, store_type: _KeystoreType | None = None, alias: str, timestamp: int, **kwargs: Unused) -> None: ... + @classmethod + def new(cls, alias: str) -> Self: ... + def is_decrypted(self) -> bool: ... + def decrypt(self, key_password: str) -> None: ... + def encrypt(self, key_password: str) -> None: ... + +def as_hex(ba: bytes | bytearray) -> str: ... +def as_pem(der_bytes: bytes, type: _PemType) -> str: ... +def bitstring_to_bytes(bitstr: Iterable[int]) -> bytes: ... +def xor_bytearrays(a: bytes | bytearray, b: bytes | bytearray) -> bytearray: ... +def print_pem(der_bytes: bytes, type: _PemType) -> None: ... +def pkey_as_pem(pk: PrivateKeyEntry | BksKeyEntry) -> str: ... +def strip_pkcs5_padding(m: bytes | bytearray) -> bytes: ... +def strip_pkcs7_padding(m: bytes | bytearray, block_size: int) -> bytes: ... +def add_pkcs7_padding(m: bytes | bytearray, block_size: int) -> bytes: ... diff --git a/stubs/pyluach/@tests/stubtest_allowlist.txt b/stubs/pyluach/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7d6b35fd3a3a --- /dev/null +++ b/stubs/pyluach/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Module with no public API, for internal use only: +pyluach.gematria diff --git a/stubs/pyluach/METADATA.toml b/stubs/pyluach/METADATA.toml new file mode 100644 index 000000000000..102e7dfd01db --- /dev/null +++ b/stubs/pyluach/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.3.*" +upstream-repository = "https://github.com/simlist/pyluach" diff --git a/stubs/pyluach/pyluach/__init__.pyi b/stubs/pyluach/pyluach/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/pyluach/pyluach/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/pyluach/pyluach/dates.pyi b/stubs/pyluach/pyluach/dates.pyi new file mode 100644 index 000000000000..3cc936a8c592 --- /dev/null +++ b/stubs/pyluach/pyluach/dates.pyi @@ -0,0 +1,109 @@ +import abc +import builtins +import datetime +from collections.abc import Generator +from enum import Enum +from typing import TypedDict, overload, type_check_only +from typing_extensions import Self + +@type_check_only +class _DateDict(TypedDict): + year: int + month: int + day: int + +class Rounding(Enum): + PREVIOUS_DAY = 1 + NEXT_DAY = 2 + EXCEPTION = 3 + +class BaseDate(abc.ABC, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def jd(self) -> float: ... + @abc.abstractmethod + def to_heb(self) -> HebrewDate: ... + def __hash__(self) -> int: ... + def __add__(self, other: float) -> BaseDate: ... + + @overload + def __sub__(self, other: float) -> BaseDate: ... + @overload + def __sub__(self, other: BaseDate) -> int: ... + + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def shabbos(self) -> Self: ... + def fast_day(self, hebrew: bool = False) -> str | None: ... + def festival( + self, israel: bool = False, hebrew: bool = False, include_working_days: bool = True, prefix_day: bool = False + ) -> str | None: ... + def holiday(self, israel: bool = False, hebrew: bool = False, prefix_day: bool = False) -> str | None: ... + +class CalendarDateMixin: + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int, jd: float | None = None) -> None: ... + def __iter__(self) -> Generator[int]: ... + def tuple(self) -> builtins.tuple[int, int, int]: ... + def dict(self) -> _DateDict: ... + def replace(self, year: int | None = None, month: int | None = None, day: int | None = None) -> Self: ... + +class JulianDay(BaseDate): + day: float + def __init__(self, day: float) -> None: ... + @property + def jd(self) -> float: ... + @staticmethod + def from_pydate(pydate: datetime.date) -> JulianDay: ... + @staticmethod + def today() -> JulianDay: ... + def to_greg(self) -> GregorianDate: ... + def to_heb(self) -> HebrewDate: ... + def to_pydate(self) -> datetime.date: ... + +class GregorianDate(BaseDate, CalendarDateMixin): + def __init__(self, year: int, month: int, day: int, jd: float | None = None) -> None: ... + def __format__(self, fmt: str) -> str: ... + def strftime(self, fmt: str) -> str: ... + @property + def jd(self) -> float: ... + @classmethod + def from_pydate(cls, pydate: datetime.date) -> Self: ... + @staticmethod + def today() -> GregorianDate: ... + def is_leap(self) -> bool: ... + def to_jd(self) -> JulianDay: ... + def to_heb(self) -> HebrewDate: ... + def to_pydate(self) -> datetime.date: ... + +class HebrewDate(BaseDate, CalendarDateMixin): + def __init__(self, year: int, month: int, day: int, jd: float | None = None) -> None: ... + def __format__(self, fmt: str) -> str: ... + @property + def jd(self) -> float: ... + @staticmethod + def from_pydate(pydate: datetime.date) -> HebrewDate: ... + @staticmethod + def today() -> HebrewDate: ... + def to_jd(self) -> JulianDay: ... + def to_greg(self) -> GregorianDate: ... + def to_pydate(self) -> datetime.date: ... + def to_heb(self) -> HebrewDate: ... + def month_name(self, hebrew: bool = False) -> str: ... + def hebrew_day(self, withgershayim: bool = True) -> str: ... + def hebrew_year(self, thousands: bool = False, withgershayim: bool = True) -> str: ... + def hebrew_date_string(self, thousands: bool = False) -> str: ... + def add( + self, years: int = 0, months: int = 0, days: int = 0, adar1: bool | None = False, rounding: Rounding = Rounding.NEXT_DAY + ) -> HebrewDate: ... + def subtract( + self, years: int = 0, months: int = 0, days: int = 0, adar1: bool | None = False, rounding: Rounding = Rounding.NEXT_DAY + ) -> HebrewDate: ... diff --git a/stubs/pyluach/pyluach/hebrewcal.pyi b/stubs/pyluach/pyluach/hebrewcal.pyi new file mode 100644 index 000000000000..925354719149 --- /dev/null +++ b/stubs/pyluach/pyluach/hebrewcal.pyi @@ -0,0 +1,147 @@ +import calendar +import datetime +from collections.abc import Generator +from typing import Literal, TypedDict, overload, type_check_only +from typing_extensions import Self + +from .dates import BaseDate, HebrewDate + +@type_check_only +class _MoladDict(TypedDict): + weekday: int + hours: int + parts: int + +@type_check_only +class _MoladAnnouncementDict(TypedDict): + weekday: int + hour: int + minutes: int + parts: int + +class IllegalMonthError(ValueError): + month: int + def __init__(self, month: int) -> None: ... + +class IllegalWeekdayError(ValueError): + weekday: int + def __init__(self, weekday: int) -> None: ... + +class Year: + year: int + leap: bool + def __init__(self, year: int) -> None: ... + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __add__(self, other: int) -> Year: ... + + @overload + def __sub__(self, other: int) -> Year: ... + @overload + def __sub__(self, other: Year) -> int: ... + + def __gt__(self, other: Year) -> bool: ... + def __ge__(self, other: Year) -> bool: ... + def __lt__(self, other: Year) -> bool: ... + def __le__(self, other: Year) -> bool: ... + def __iter__(self) -> Generator[int]: ... + def monthscount(self) -> Literal[12, 13]: ... + def itermonths(self) -> Generator[Month]: ... + def iterdays(self) -> Generator[int]: ... + def iterdates(self) -> Generator[HebrewDate]: ... + @classmethod + def from_date(cls, date: BaseDate) -> Self: ... + @classmethod + def from_pydate(cls, pydate: datetime.date) -> Self: ... + def year_string(self, thousands: bool = False) -> str: ... + +class Month: + year: int + month: int + def __init__(self, year: int, month: int) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Generator[int]: ... + def __eq__(self, other: object) -> bool: ... + def __add__(self, other: int) -> Month: ... + + @overload + def __sub__(self, other: int) -> Month: ... + @overload + def __sub__(self, other: Month) -> int: ... + + def __gt__(self, other: Month) -> bool: ... + def __ge__(self, other: Month) -> bool: ... + def __lt__(self, other: Month) -> bool: ... + def __le__(self, other: Month) -> bool: ... + @classmethod + def from_date(cls, date: BaseDate) -> Month: ... + @classmethod + def from_pydate(cls, pydate: datetime.date) -> Month: ... + def month_name(self, hebrew: bool = False) -> str: ... + def month_string(self, thousands: bool = False) -> str: ... + def starting_weekday(self) -> int: ... + def iterdates(self) -> Generator[HebrewDate]: ... + def molad(self) -> _MoladDict: ... + def molad_announcement(self) -> _MoladAnnouncementDict: ... + +def to_hebrew_numeral(num: int, thousands: bool = False, withgershayim: bool = True) -> str: ... + +class HebrewCalendar(calendar.Calendar): + hebrewnumerals: bool + hebrewweekdays: bool + hebrewmonths: bool + hebrewyear: bool + def __init__( + self, + firstweekday: int = 1, + hebrewnumerals: bool = True, + hebrewweekdays: bool = False, + hebrewmonths: bool = False, + hebrewyear: bool = False, + ) -> None: ... + + @property + def firstweekday(self) -> int: ... + @firstweekday.setter + def firstweekday(self, thefirstweekday: int) -> None: ... + + def iterweekdays(self) -> Generator[int]: ... + def itermonthdates(self, year: int, month: int) -> Generator[HebrewDate]: ... # type: ignore[override] + def itermonthdays(self, year: int, month: int) -> Generator[int]: ... + def itermonthdays2(self, year: int, month: int) -> Generator[tuple[int, int]]: ... + def itermonthdays3(self, year: int, month: int) -> Generator[tuple[int, int, int]]: ... + def itermonthdays4(self, year: int, month: int) -> Generator[tuple[int, int, int, int]]: ... + def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[HebrewDate]]]]: ... # type: ignore[override] + def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]: ... + def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]: ... + def monthdatescalendar(self, year: int, month: int) -> list[list[HebrewDate]]: ... # type: ignore[override] + +class HebrewHTMLCalendar(HebrewCalendar, calendar.HTMLCalendar): + rtl: bool + def __init__( + self, + firstweekday: int = 1, + hebrewnumerals: bool = True, + hebrewweekdays: bool = False, + hebrewmonths: bool = False, + hebrewyear: bool = False, + rtl: bool = False, + ) -> None: ... + def formatday(self, day: int, weekday: int) -> str: ... + def formatweekday(self, day: int) -> str: ... + def formatyearnumber(self, theyear: int) -> int | str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + def formatyear(self, theyear: int, width: int = 3) -> str: ... + +class HebrewTextCalendar(HebrewCalendar, calendar.TextCalendar): + def formatday(self, day: int, weekday: int, width: int) -> str: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int = 0, withyear: bool = True) -> str: ... + def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... + +def fast_day(date: BaseDate, hebrew: bool = False) -> str | None: ... +def festival( + date: BaseDate, israel: bool = False, hebrew: bool = False, include_working_days: bool = True, prefix_day: bool = False +) -> str | None: ... +def holiday(date: BaseDate, israel: bool = False, hebrew: bool = False, prefix_day: bool = False) -> str | None: ... diff --git a/stubs/pyluach/pyluach/parshios.pyi b/stubs/pyluach/pyluach/parshios.pyi new file mode 100644 index 000000000000..ff1a4d8c4b20 --- /dev/null +++ b/stubs/pyluach/pyluach/parshios.pyi @@ -0,0 +1,14 @@ +from collections import OrderedDict +from collections.abc import Generator +from typing import Final + +from .dates import BaseDate, HebrewDate + +PARSHIOS: Final[list[str]] +PARSHIOS_HEBREW: Final[list[str]] + +def getparsha(date: BaseDate, israel: bool = False) -> list[int] | None: ... +def getparsha_string(date: BaseDate, israel: bool = False, hebrew: bool = False) -> str | None: ... +def iterparshios(year: int, israel: bool = False) -> Generator[list[int] | None]: ... +def parshatable(year: int, israel: bool = False) -> OrderedDict[HebrewDate, list[int] | None]: ... +def four_parshios(date: BaseDate, hebrew: bool = False) -> str: ... diff --git a/stubs/pyluach/pyluach/utils.pyi b/stubs/pyluach/pyluach/utils.pyi new file mode 100644 index 000000000000..2c0f3e71e30f --- /dev/null +++ b/stubs/pyluach/pyluach/utils.pyi @@ -0,0 +1,32 @@ +from enum import Enum +from typing import Final + +class _Days(Enum): + ROSH_HASHANA = "Rosh Hashana" + YOM_KIPPUR = "Yom Kippur" + SUCCOS = "Succos" + SHMINI_ATZERES = "Shmini Atzeres" + SIMCHAS_TORAH = "Simchas Torah" + CHANUKA = "Chanuka" + TU_BSHVAT = "Tu B'shvat" + PURIM_KATAN = "Purim Katan" + PURIM = "Purim" + SHUSHAN_PURIM = "Shushan Purim" + PESACH = "Pesach" + PESACH_SHENI = "Pesach Sheni" + LAG_BAOMER = "Lag Ba'omer" + SHAVUOS = "Shavuos" + TU_BAV = "Tu B'av" + TZOM_GEDALIA = "Tzom Gedalia" + TENTH_OF_TEVES = "10 of Teves" + TAANIS_ESTHER = "Taanis Esther" + SEVENTEENTH_OF_TAMUZ = "17 of Tamuz" + NINTH_OF_AV = "9 of Av" + +MONTH_NAMES: Final[list[str]] +MONTH_NAMES_HEBREW: Final[list[str]] +FAST_DAYS: Final[list[str]] +FAST_DAYS_HEBREW: Final[list[str]] +FESTIVALS: Final[list[str]] +FESTIVALS_HEBREW: Final[list[str]] +WEEKDAYS: Final[dict[int, str]] diff --git a/stubs/pynput/@tests/stubtest_allowlist.txt b/stubs/pynput/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..415752653a84 --- /dev/null +++ b/stubs/pynput/@tests/stubtest_allowlist.txt @@ -0,0 +1,8 @@ +# Platform specific private utils: +pynput._util.xorg_keysyms +pynput._util.xorg +pynput._util.win32_vks +pynput._util.win32 +pynput._util.uinput +pynput._util.darwin_vks +pynput._util.darwin diff --git a/stubs/pynput/METADATA.toml b/stubs/pynput/METADATA.toml new file mode 100644 index 000000000000..66307d3bc98e --- /dev/null +++ b/stubs/pynput/METADATA.toml @@ -0,0 +1,5 @@ +version = "~=1.8.1" +upstream-repository = "https://github.com/moses-palmer/pynput" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] diff --git a/stubs/pynput/pynput/__init__.pyi b/stubs/pynput/pynput/__init__.pyi new file mode 100644 index 000000000000..1b92738f9891 --- /dev/null +++ b/stubs/pynput/pynput/__init__.pyi @@ -0,0 +1 @@ +from . import keyboard as keyboard, mouse as mouse diff --git a/stubs/pynput/pynput/_info.pyi b/stubs/pynput/pynput/_info.pyi new file mode 100644 index 000000000000..e6655bdd2e3d --- /dev/null +++ b/stubs/pynput/pynput/_info.pyi @@ -0,0 +1,2 @@ +__author__: str +__version__: tuple[int, int, int] diff --git a/stubs/pynput/pynput/_util.pyi b/stubs/pynput/pynput/_util.pyi new file mode 100644 index 000000000000..675a633379fd --- /dev/null +++ b/stubs/pynput/pynput/_util.pyi @@ -0,0 +1,73 @@ +import threading +from _typeshed import OptExcInfo +from collections.abc import Callable +from queue import Queue +from types import ModuleType, TracebackType +from typing import Any, ClassVar, Generic, ParamSpec, TypedDict, TypeVar, type_check_only +from typing_extensions import Self + +_T = TypeVar("_T") +_AbstractListenerT = TypeVar("_AbstractListenerT", bound=AbstractListener) +_P = ParamSpec("_P") + +@type_check_only +class _RESOLUTIONS(TypedDict): + darwin: str + uinput: str + xorg: str + +RESOLUTIONS: _RESOLUTIONS + +def backend(package: str) -> ModuleType: ... +def prefix(base: type | tuple[type | tuple[Any, ...], ...], cls: type) -> str | None: ... + +class AbstractListener(threading.Thread): + class StopException(Exception): ... + _HANDLED_EXCEPTIONS: ClassVar[tuple[type | tuple[Any, ...], ...]] # undocumented + _suppress: bool # undocumented + _running: bool # undocumented + _thread: threading.Thread # undocumented + _condition: threading.Condition # undocumented + _ready: bool # undocumented + _queue: Queue[OptExcInfo | None] # undocumented + daemon: bool + def __init__(self, suppress: bool = False, **kwargs: Callable[..., bool | None] | None) -> None: ... + @property + def suppress(self) -> bool: ... + @property + def running(self) -> bool: ... + def stop(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def wait(self) -> None: ... + def run(self) -> None: ... + @classmethod + def _emitter(cls, f: Callable[_P, _T]) -> Callable[_P, _T]: ... # undocumented + def _mark_ready(self) -> None: ... # undocumented + def _run(self) -> None: ... # undocumented + def _stop_platform(self) -> None: ... # undocumented + def join(self, timeout: float | None = None, *args: Any) -> None: ... + +class Events(Generic[_T, _AbstractListenerT]): + _Listener: type[_AbstractListenerT] | None # undocumented + + class Event: + def __eq__(self, other: object) -> bool: ... + + _event_queue: Queue[_T] # undocumented + _sentinel: object # undocumented + _listener: _AbstractListenerT # undocumented + start: Callable[[], None] + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + def get(self, timeout: float | None = None) -> _T | None: ... + def _event_mapper(self, event: Callable[_P, object]) -> Callable[_P, None]: ... + +class NotifierMixin: ... diff --git a/stubs/pynput/pynput/keyboard/__init__.pyi b/stubs/pynput/pynput/keyboard/__init__.pyi new file mode 100644 index 000000000000..8d553e0087f9 --- /dev/null +++ b/stubs/pynput/pynput/keyboard/__init__.pyi @@ -0,0 +1,32 @@ +from _typeshed import SupportsItems +from collections.abc import Callable +from typing import Any + +from pynput import _util + +from ._base import Controller as Controller, Key as Key, KeyCode as KeyCode, Listener as Listener + +class Events(_util.Events[Any, Listener]): + class Press(_util.Events.Event): + key: Key | KeyCode | None + injected: bool + def __init__(self, key: Key | KeyCode | None, injected: bool) -> None: ... + + class Release(_util.Events.Event): + key: Key | KeyCode | None + injected: bool + def __init__(self, key: Key | KeyCode | None, injected: bool) -> None: ... + + def __init__(self) -> None: ... + def __next__(self) -> Press | Release: ... + def get(self, timeout: float | None = None) -> Press | Release | None: ... + +class HotKey: + def __init__(self, keys: list[KeyCode], on_activate: Callable[[], object]) -> None: ... + @staticmethod + def parse(keys: str) -> list[KeyCode]: ... + def press(self, key: Key | KeyCode) -> None: ... + def release(self, key: Key | KeyCode) -> None: ... + +class GlobalHotKeys(Listener): + def __init__(self, hotkeys: SupportsItems[str, Callable[[], None]], *args: Any, **kwargs: Any) -> None: ... diff --git a/stubs/pynput/pynput/keyboard/_base.pyi b/stubs/pynput/pynput/keyboard/_base.pyi new file mode 100644 index 000000000000..fee88c0135dd --- /dev/null +++ b/stubs/pynput/pynput/keyboard/_base.pyi @@ -0,0 +1,146 @@ +import builtins +import contextlib +import enum +import sys +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import Any, ClassVar, cast +from typing_extensions import Self + +from pynput._util import AbstractListener + +class KeyCode: + _PLATFORM_EXTENSIONS: ClassVar[Iterable[str]] # undocumented + vk: int | None + char: str | None + is_dead: bool | None + combining: str | None + def __init__(self, vk: str | None = None, char: str | None = None, is_dead: bool = False, **kwargs: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def join(self, key: Self) -> Self: ... + @classmethod + def from_vk(cls, vk: int, **kwargs: Any) -> Self: ... + @classmethod + def from_char(cls, char: str, **kwargs: Any) -> Self: ... + @classmethod + def from_dead(cls, char: str, **kwargs: Any) -> Self: ... + +class Key(enum.Enum): + alt = cast(KeyCode, ...) + alt_l = cast(KeyCode, ...) + alt_r = cast(KeyCode, ...) + alt_gr = cast(KeyCode, ...) + backspace = cast(KeyCode, ...) + caps_lock = cast(KeyCode, ...) + cmd = cast(KeyCode, ...) + cmd_l = cast(KeyCode, ...) + cmd_r = cast(KeyCode, ...) + ctrl = cast(KeyCode, ...) + ctrl_l = cast(KeyCode, ...) + ctrl_r = cast(KeyCode, ...) + delete = cast(KeyCode, ...) + down = cast(KeyCode, ...) + end = cast(KeyCode, ...) + enter = cast(KeyCode, ...) + esc = cast(KeyCode, ...) + f1 = cast(KeyCode, ...) + f2 = cast(KeyCode, ...) + f3 = cast(KeyCode, ...) + f4 = cast(KeyCode, ...) + f5 = cast(KeyCode, ...) + f6 = cast(KeyCode, ...) + f7 = cast(KeyCode, ...) + f8 = cast(KeyCode, ...) + f9 = cast(KeyCode, ...) + f10 = cast(KeyCode, ...) + f11 = cast(KeyCode, ...) + f12 = cast(KeyCode, ...) + f13 = cast(KeyCode, ...) + f14 = cast(KeyCode, ...) + f15 = cast(KeyCode, ...) + f16 = cast(KeyCode, ...) + f17 = cast(KeyCode, ...) + f18 = cast(KeyCode, ...) + f19 = cast(KeyCode, ...) + f20 = cast(KeyCode, ...) + if sys.platform == "win32": + f21 = cast(KeyCode, ...) + f22 = cast(KeyCode, ...) + f23 = cast(KeyCode, ...) + f24 = cast(KeyCode, ...) + home = cast(KeyCode, ...) + left = cast(KeyCode, ...) + page_down = cast(KeyCode, ...) + page_up = cast(KeyCode, ...) + right = cast(KeyCode, ...) + shift = cast(KeyCode, ...) + shift_l = cast(KeyCode, ...) + shift_r = cast(KeyCode, ...) + space = cast(KeyCode, ...) + tab = cast(KeyCode, ...) + up = cast(KeyCode, ...) + media_play_pause = cast(KeyCode, ...) + media_stop = cast(KeyCode, ...) + media_volume_mute = cast(KeyCode, ...) + media_volume_down = cast(KeyCode, ...) + media_volume_up = cast(KeyCode, ...) + media_previous = cast(KeyCode, ...) + media_next = cast(KeyCode, ...) + if sys.platform == "darwin": + media_eject = cast(KeyCode, ...) + insert = cast(KeyCode, ...) + menu = cast(KeyCode, ...) + num_lock = cast(KeyCode, ...) + pause = cast(KeyCode, ...) + print_screen = cast(KeyCode, ...) + scroll_lock = cast(KeyCode, ...) + +class Controller: + _KeyCode: ClassVar[builtins.type[KeyCode]] # undocumented + _Key: ClassVar[builtins.type[Key]] # undocumented + + if sys.platform == "linux": + CTRL_MASK: ClassVar[int] + SHIFT_MASK: ClassVar[int] + + class InvalidKeyException(Exception): ... + class InvalidCharacterException(Exception): ... + + def __init__(self) -> None: ... + def press(self, key: str | Key | KeyCode) -> None: ... + def release(self, key: str | Key | KeyCode) -> None: ... + def tap(self, key: str | Key | KeyCode) -> None: ... + def touch(self, key: str | Key | KeyCode, is_press: bool) -> None: ... + @contextlib.contextmanager + def pressed(self, *args: str | Key | KeyCode) -> Generator[None]: ... + def type(self, string: str) -> None: ... + @property + def modifiers(self) -> contextlib.AbstractContextManager[Iterator[set[Key]]]: ... + @property + def alt_pressed(self) -> bool: ... + @property + def alt_gr_pressed(self) -> bool: ... + @property + def ctrl_pressed(self) -> bool: ... + @property + def shift_pressed(self) -> bool: ... + +class Listener(AbstractListener): + def __init__( + self, + on_press: ( + Callable[[], bool | None] + | Callable[[Key | KeyCode | None], bool | None] + | Callable[[Key | KeyCode | None, bool], bool | None] + | None + ) = None, + on_release: ( + Callable[[], bool | None] + | Callable[[Key | KeyCode | None], bool | None] + | Callable[[Key | KeyCode | None, bool], bool | None] + | None + ) = None, + suppress: bool = False, + **kwargs: Any, + ) -> None: ... + def canonical(self, key: Key | KeyCode) -> Key | KeyCode: ... diff --git a/stubs/pynput/pynput/keyboard/_dummy.pyi b/stubs/pynput/pynput/keyboard/_dummy.pyi new file mode 100644 index 000000000000..f49ca47776ea --- /dev/null +++ b/stubs/pynput/pynput/keyboard/_dummy.pyi @@ -0,0 +1 @@ +from ._base import Controller as Controller, Key as Key, KeyCode as KeyCode, Listener as Listener diff --git a/stubs/pynput/pynput/mouse/__init__.pyi b/stubs/pynput/pynput/mouse/__init__.pyi new file mode 100644 index 000000000000..42738f852a09 --- /dev/null +++ b/stubs/pynput/pynput/mouse/__init__.pyi @@ -0,0 +1,32 @@ +from typing import Any + +from pynput import _util + +from ._base import Button as Button, Controller as Controller, Listener as Listener + +class Events(_util.Events[Any, Listener]): + class Move(_util.Events.Event): + x: int + y: int + injected: bool + def __init__(self, x: int, y: int, injected: bool) -> None: ... + + class Click(_util.Events.Event): + x: int + y: int + button: Button + pressed: bool + injected: bool + def __init__(self, x: int, y: int, button: Button, pressed: bool, injected: bool) -> None: ... + + class Scroll(_util.Events.Event): + x: int + y: int + dx: int + dy: int + injected: bool + def __init__(self, x: int, y: int, dx: int, dy: int, injected: bool) -> None: ... + + def __init__(self) -> None: ... + def __next__(self) -> Move | Click | Scroll: ... + def get(self, timeout: float | None = None) -> Move | Click | Scroll | None: ... diff --git a/stubs/pynput/pynput/mouse/_base.pyi b/stubs/pynput/pynput/mouse/_base.pyi new file mode 100644 index 000000000000..69cfd78ac520 --- /dev/null +++ b/stubs/pynput/pynput/mouse/_base.pyi @@ -0,0 +1,118 @@ +import enum +import sys +from collections.abc import Callable +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from pynput._util import AbstractListener + +class Button(enum.Enum): + unknown = 0 + left = 1 + middle = 2 + right = 3 + if sys.platform == "linux": + button8 = 8 + button9 = 9 + button10 = 10 + button11 = 11 + button12 = 12 + button13 = 13 + button14 = 14 + button15 = 15 + button16 = 16 + button17 = 17 + button18 = 18 + button19 = 19 + button20 = 20 + button21 = 21 + button22 = 22 + button23 = 23 + button24 = 24 + button25 = 25 + button26 = 26 + button27 = 27 + button28 = 28 + button29 = 29 + button30 = 30 + scroll_down = 5 + scroll_left = 6 + scroll_right = 7 + scroll_up = 4 + if sys.platform == "win32": + x1 = 0 # Value unknown + x2 = 0 # Value unknown + +class Controller: + def __init__(self) -> None: ... + + @property + def position(self) -> tuple[int, int]: ... + @position.setter + def position(self, position: tuple[int, int]) -> None: ... + + def scroll(self, dx: int, dy: int) -> None: ... + def press(self, button: Button) -> None: ... + def release(self, button: Button) -> None: ... + def move(self, dx: int, dy: int) -> None: ... + def click(self, button: Button, count: int = 1) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Listener(AbstractListener): + if sys.platform == "win32": + WM_LBUTTONDOWN: int + WM_LBUTTONUP: int + WM_MBUTTONDOWN: int + WM_MBUTTONUP: int + WM_MOUSEMOVE: int + WM_MOUSEWHEEL: int + WM_MOUSEHWHEEL: int + WM_RBUTTONDOWN: int + WM_RBUTTONUP: int + WM_XBUTTONDOWN: int + WM_XBUTTONUP: int + + MK_XBUTTON1: int + MK_XBUTTON2: int + + XBUTTON1: int + XBUTTON2: int + + CLICK_BUTTONS: dict[int, tuple[Button, bool]] + X_BUTTONS: dict[int, dict[int, tuple[Button, bool]]] + SCROLL_BUTTONS: dict[int, tuple[int, int]] + + def __init__( + self, + on_move: ( + Callable[[], bool | None] + | Callable[[int], bool | None] + | Callable[[int, int], bool | None] + | Callable[[int, int, bool], bool | None] + | None + ) = None, + on_click: ( + Callable[[], bool | None] + | Callable[[int], bool | None] + | Callable[[int, int], bool | None] + | Callable[[int, int, Button], bool | None] + | Callable[[int, int, Button, bool], bool | None] + | Callable[[int, int, Button, bool, bool], bool | None] + | None + ) = None, + on_scroll: ( + Callable[[], bool | None] + | Callable[[int], bool | None] + | Callable[[int, int], bool | None] + | Callable[[int, int, int], bool | None] + | Callable[[int, int, int, int], bool | None] + | Callable[[int, int, int, int, bool], bool | None] + | None + ) = None, + suppress: bool = False, + **kwargs: Any, + ) -> None: ... diff --git a/stubs/pynput/pynput/mouse/_dummy.pyi b/stubs/pynput/pynput/mouse/_dummy.pyi new file mode 100644 index 000000000000..c799f582b620 --- /dev/null +++ b/stubs/pynput/pynput/mouse/_dummy.pyi @@ -0,0 +1 @@ +from ._base import Button as Button, Controller as Controller, Listener as Listener diff --git a/stubs/pyogrio/@tests/stubtest_allowlist.txt b/stubs/pyogrio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..9ac53dcdeb3e --- /dev/null +++ b/stubs/pyogrio/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +pyogrio\.tests(\..*)? +pyogrio\._typing # stubs only module diff --git a/stubs/pyogrio/METADATA.toml b/stubs/pyogrio/METADATA.toml new file mode 100644 index 000000000000..a5b8927e9444 --- /dev/null +++ b/stubs/pyogrio/METADATA.toml @@ -0,0 +1,5 @@ +version = "0.13.*" +upstream-repository = "https://github.com/geopandas/pyogrio" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] +optional-dependencies = ["types-geopandas"] diff --git a/stubs/pyogrio/pyogrio/__init__.pyi b/stubs/pyogrio/pyogrio/__init__.pyi new file mode 100644 index 000000000000..22149bb24903 --- /dev/null +++ b/stubs/pyogrio/pyogrio/__init__.pyi @@ -0,0 +1,47 @@ +from .core import ( + __gdal_geos_version__ as __gdal_geos_version__, + __gdal_version__ as __gdal_version__, + __gdal_version_string__ as __gdal_version_string__, + detect_write_driver as detect_write_driver, + get_gdal_config_option as get_gdal_config_option, + get_gdal_data_path as get_gdal_data_path, + list_drivers as list_drivers, + list_drivers_details as list_drivers_details, + list_layers as list_layers, + read_bounds as read_bounds, + read_info as read_info, + set_gdal_config_options as set_gdal_config_options, + vsi_curl_clear_cache as vsi_curl_clear_cache, + vsi_listtree as vsi_listtree, + vsi_rmtree as vsi_rmtree, + vsi_unlink as vsi_unlink, +) +from .geopandas import read_dataframe as read_dataframe, write_dataframe as write_dataframe +from .raw import open_arrow as open_arrow, read_arrow as read_arrow, write_arrow as write_arrow + +__all__ = [ + "__gdal_geos_version__", + "__gdal_version__", + "__gdal_version_string__", + "__version__", + "detect_write_driver", + "get_gdal_config_option", + "get_gdal_data_path", + "list_drivers", + "list_drivers_details", + "list_layers", + "open_arrow", + "read_arrow", + "read_bounds", + "read_dataframe", + "read_info", + "set_gdal_config_options", + "vsi_curl_clear_cache", + "vsi_listtree", + "vsi_rmtree", + "vsi_unlink", + "write_arrow", + "write_dataframe", +] + +__version__: str diff --git a/stubs/pyogrio/pyogrio/_typing.pyi b/stubs/pyogrio/pyogrio/_typing.pyi new file mode 100644 index 000000000000..ac1e0f912d6a --- /dev/null +++ b/stubs/pyogrio/pyogrio/_typing.pyi @@ -0,0 +1,28 @@ +import io +from _typeshed import SupportsRead +from collections.abc import Collection +from pathlib import Path +from typing import Any, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import CapsuleType + +import numpy as np + +_T = TypeVar("_T") +_G = TypeVar("_G", bound=np.generic) +_G_co = TypeVar("_G_co", bound=np.generic, covariant=True) + +@type_check_only +class SupportsArrowCStream(Protocol): + def __arrow_c_stream__(self, requested_schema: object | None = None) -> CapsuleType: ... + +@type_check_only +class SupportsArray(Protocol[_G_co]): + def __array__(self) -> np.ndarray[Any, np.dtype[_G_co]]: ... + +Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_G]] +Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_G]] +ReadPathOrBuffer: TypeAlias = str | Path | bytes | SupportsRead[bytes] +WritePathOrBuffer: TypeAlias = str | Path | io.BytesIO + +DualArrayLike: TypeAlias = SupportsArray[_G] | Collection[_T] | _T +ArrayLikeInt: TypeAlias = DualArrayLike[np.bool | np.integer, int] diff --git a/stubs/pyogrio/pyogrio/core.pyi b/stubs/pyogrio/pyogrio/core.pyi new file mode 100644 index 000000000000..a3b0264eebc6 --- /dev/null +++ b/stubs/pyogrio/pyogrio/core.pyi @@ -0,0 +1,82 @@ +from pathlib import Path +from typing import Any, Literal, TypedDict, type_check_only + +import numpy as np +import shapely as shp + +from ._typing import Array1D, Array2D, ReadPathOrBuffer + +__gdal_version__: tuple[int, int, int] +__gdal_version_string__: str +__gdal_geos_version__: tuple[int, int, int] | None + +@type_check_only +class _Capabilities(TypedDict): + random_read: bool + fast_set_next_by_index: bool + fast_spatial_filter: bool + fast_feature_count: bool + fast_total_bounds: bool + +@type_check_only +class _LayerInfo(TypedDict): + layer_name: str + # crs is `None` for non-spatial layers + crs: str | None + fields: Array1D[np.object_] # field names (strings) + dtypes: Array1D[np.object_] # field dtypes (strings) + ogr_types: list[str] + ogr_subtypes: list[str] + encoding: str + fid_column: str + geometry_name: str + # geometry_type is `None` for non-spatial layers + geometry_type: str | None + features: int + # total_bounds is `None` for non-spatial layers or if expensive to compute + total_bounds: tuple[float, float, float, float] | None + driver: str + capabilities: _Capabilities + dataset_metadata: dict[str, str] | None + layer_metadata: dict[str, str] | None + +@type_check_only +class _DriverDetails(TypedDict): + long_name: str + read: bool + append: bool + write: bool + supports_vsi: bool + help_topic_url: str | None + extensions: list[str] | None + +def list_drivers(read: bool = False, write: bool = False, append: bool = False) -> dict[str, Literal["r", "rw"]]: ... +def list_drivers_details() -> dict[str, _DriverDetails]: ... +def detect_write_driver(path: str | Path) -> str: ... # `path` is coerced to string internally +def list_layers(path_or_buffer: ReadPathOrBuffer, /) -> Array2D[np.object_]: ... +def read_bounds( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, +) -> tuple[Array1D[np.int64], Array2D[np.float64]]: ... +def read_info( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + force_feature_count: bool = False, + force_total_bounds: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> _LayerInfo: ... +def set_gdal_config_options(options: dict[str, Any]) -> None: ... +def get_gdal_config_option(name: str) -> Any: ... # Could return str, int, bool, or None +def get_gdal_data_path() -> str: ... +def vsi_listtree(path: str | Path, pattern: str | None = None) -> list[str]: ... +def vsi_rmtree(path: str | Path) -> None: ... +def vsi_unlink(path: str | Path) -> None: ... +def vsi_curl_clear_cache(prefix: str | Path = "") -> None: ... diff --git a/stubs/pyogrio/pyogrio/errors.pyi b/stubs/pyogrio/pyogrio/errors.pyi new file mode 100644 index 000000000000..38f893ce66c9 --- /dev/null +++ b/stubs/pyogrio/pyogrio/errors.pyi @@ -0,0 +1,6 @@ +class DataSourceError(RuntimeError): ... +class DataLayerError(RuntimeError): ... +class CRSError(DataLayerError): ... +class FeatureError(DataLayerError): ... +class GeometryError(DataLayerError): ... +class FieldError(DataLayerError): ... diff --git a/stubs/pyogrio/pyogrio/geopandas.pyi b/stubs/pyogrio/pyogrio/geopandas.pyi new file mode 100644 index 000000000000..ec6f67fb1829 --- /dev/null +++ b/stubs/pyogrio/pyogrio/geopandas.pyi @@ -0,0 +1,80 @@ +import os +from collections.abc import Collection, Mapping +from typing import Any, Literal, overload + +import geopandas as gpd +import pandas as pd +import shapely as shp + +from ._typing import ArrayLikeInt, ReadPathOrBuffer, WritePathOrBuffer + +@overload +def read_dataframe( + path_or_buffer: ReadPathOrBuffer | os.PathLike[str], + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: Literal[True] = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + fid_as_index: bool = False, + use_arrow: bool | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + arrow_to_pandas_kwargs: Mapping[str, Any] | None = None, + datetime_as_string: bool = False, + mixed_offsets_as_utc: bool = True, + **kwargs: Any, # Dataset open options passed to OGR +) -> gpd.GeoDataFrame: ... +@overload +def read_dataframe( + path_or_buffer: ReadPathOrBuffer | os.PathLike[str], + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + *, + read_geometry: Literal[False], + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + fid_as_index: bool = False, + use_arrow: bool | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + arrow_to_pandas_kwargs: Mapping[str, Any] | None = None, + datetime_as_string: bool = False, + mixed_offsets_as_utc: bool = True, + **kwargs: Any, # Dataset open options passed to OGR +) -> pd.DataFrame: ... + +def write_dataframe( + df: pd.DataFrame, + path: WritePathOrBuffer, + layer: str | None = None, + driver: str | None = None, + encoding: str | None = None, + geometry_type: str | None = None, + promote_to_multi: bool | None = None, + nan_as_null: bool = True, + append: bool = False, + use_arrow: bool | None = None, + dataset_metadata: dict[str, Any] | None = None, + layer_metadata: dict[str, Any] | None = None, + metadata: dict[str, Any] | None = None, + dataset_options: dict[str, Any] | None = None, + layer_options: dict[str, Any] | None = None, + **kwargs: Any, # Additional driver-specific dataset or layer creation options passed to OGR +) -> None: ... diff --git a/stubs/pyogrio/pyogrio/raw.pyi b/stubs/pyogrio/pyogrio/raw.pyi new file mode 100644 index 000000000000..2271f506f985 --- /dev/null +++ b/stubs/pyogrio/pyogrio/raw.pyi @@ -0,0 +1,179 @@ +from collections.abc import Collection, Iterable +from contextlib import AbstractContextManager +from typing import Any, Literal, TypedDict, overload, type_check_only + +import numpy as np +import pyarrow as pa # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] # ty:ignore[unresolved-import] # pyrefly: ignore [missing-import] +import shapely as shp + +from ._typing import Array1D, ArrayLikeInt, ReadPathOrBuffer, SupportsArrowCStream, WritePathOrBuffer + +DRIVERS_NO_MIXED_SINGLE_MULTI: set[str] +DRIVERS_NO_MIXED_DIMENSIONS: set[str] + +@type_check_only +class _Meta(TypedDict): + crs: str + fields: Array1D[np.object_] + dtypes: Array1D[np.object_] + ogr_types: list[str] + ogr_subtypes: list[str] + encoding: str + geometry_type: str + geometry_name: str + fid_column: str + +@overload +def read( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: Literal[False] = False, + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> tuple[_Meta, None, Array1D[np.object_] | None, list[np.ndarray]]: ... +@overload +def read( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + *, + return_fids: Literal[True], + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> tuple[_Meta, Array1D[np.int64], Array1D[np.object_] | None, list[np.ndarray]]: ... + +def read_arrow( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: bool = False, + datetime_as_string: bool = False, + *, + batch_size: int = 65536, # Extracted from kwargs + **kwargs: Any, # Dataset open options passed to OGR +) -> tuple[_Meta, pa.Table]: ... + +@overload +def open_arrow( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: bool = False, + batch_size: int = 65536, + use_pyarrow: Literal[False] = False, + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> AbstractContextManager[tuple[_Meta, SupportsArrowCStream]]: ... +@overload +def open_arrow( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: bool = False, + batch_size: int = 65536, + *, + use_pyarrow: Literal[True], + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> AbstractContextManager[tuple[_Meta, pa.RecordBatchReader]]: ... + +def write( + path: WritePathOrBuffer, + geometry: np.ndarray | None, # ndarray of WKB encoded geometries or None + field_data: Iterable[np.ndarray] | None, + fields: Iterable[str], + field_mask: Iterable[np.ndarray | None] | None = None, + layer: str | None = None, + driver: str | None = None, + geometry_type: str | None = None, + crs: str | None = None, + encoding: str | None = None, + promote_to_multi: bool | None = None, + nan_as_null: bool = True, + append: bool = False, + dataset_metadata: dict[str, str] | None = None, + layer_metadata: dict[str, str] | None = None, + metadata: dict[str, str] | None = None, + dataset_options: dict[str, Any] | None = None, + layer_options: dict[str, Any] | None = None, + gdal_tz_offsets: dict[str, Any] | None = None, + **kwargs: Any, # Additional driver-specific dataset or layer creation options passed to OGR +) -> None: ... +def write_arrow( + arrow_obj: SupportsArrowCStream, + path: WritePathOrBuffer, + layer: str | None = None, + driver: str | None = None, + geometry_name: str | None = None, + geometry_type: str | None = None, + crs: str | None = None, + encoding: str | None = None, + append: bool = False, + dataset_metadata: dict[str, str] | None = None, + layer_metadata: dict[str, str] | None = None, + metadata: dict[str, str] | None = None, + dataset_options: dict[str, Any] | None = None, + layer_options: dict[str, Any] | None = None, + **kwargs: Any, # Additional driver-specific dataset or layer creation options passed to OGR +) -> None: ... diff --git a/stubs/pyogrio/pyogrio/util.pyi b/stubs/pyogrio/pyogrio/util.pyi new file mode 100644 index 000000000000..758089b2791a --- /dev/null +++ b/stubs/pyogrio/pyogrio/util.pyi @@ -0,0 +1,11 @@ +from pathlib import Path + +from ._typing import ReadPathOrBuffer + +def get_vsi_path_or_buffer(path_or_buffer: ReadPathOrBuffer) -> str | bytes: ... +def vsi_path(path: str | Path) -> str: ... + +SCHEMES: dict[str, str] +CURLSCHEMES: set[str] + +def vsimem_rmtree_toplevel(path: str | Path) -> None: ... diff --git a/stubs/pyperclip/@tests/stubtest_allowlist.txt b/stubs/pyperclip/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..096a897229c8 --- /dev/null +++ b/stubs/pyperclip/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +pyperclip.__main__ diff --git a/stubs/pyperclip/METADATA.toml b/stubs/pyperclip/METADATA.toml new file mode 100644 index 000000000000..a2f5db7c354d --- /dev/null +++ b/stubs/pyperclip/METADATA.toml @@ -0,0 +1,6 @@ +version = "1.11.*" +upstream-repository = "https://github.com/asweigart/pyperclip" + +[tool.stubtest] +ci-platforms = ["win32", "linux", "darwin"] +apt-dependencies = ["xclip"] diff --git a/stubs/pyperclip/pyperclip/__init__.pyi b/stubs/pyperclip/pyperclip/__init__.pyi new file mode 100644 index 000000000000..28ac5248078d --- /dev/null +++ b/stubs/pyperclip/pyperclip/__init__.pyi @@ -0,0 +1,23 @@ +__all__ = ["copy", "paste", "set_clipboard", "determine_clipboard"] + +from collections.abc import Callable +from typing import Literal, TypeAlias + +class PyperclipException(RuntimeError): ... + +class PyperclipWindowsException(PyperclipException): + def __init__(self, message: str) -> None: ... + +class PyperclipTimeoutException(PyperclipException): ... + +_ClipboardMechanismName: TypeAlias = Literal[ + "pbcopy", "pyobjc", "qt", "xclip", "xsel", "wl-clipboard", "klipper", "windows", "no" +] +_ClipboardCopyMechanism: TypeAlias = Callable[[str], None] +_ClipboardPasteMechanism: TypeAlias = Callable[[], str] + +def copy(text: str) -> None: ... +def paste() -> str: ... +def set_clipboard(clipboard: _ClipboardMechanismName) -> None: ... +def determine_clipboard() -> tuple[_ClipboardCopyMechanism, _ClipboardPasteMechanism]: ... +def is_available() -> bool: ... diff --git a/stubs/pyphen/METADATA.toml b/stubs/pyphen/METADATA.toml new file mode 100644 index 000000000000..92717610dff0 --- /dev/null +++ b/stubs/pyphen/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.18.1" +upstream-repository = "https://github.com/Kozea/Pyphen" diff --git a/stubs/pyphen/pyphen/__init__.pyi b/stubs/pyphen/pyphen/__init__.pyi new file mode 100644 index 000000000000..157358ea6fda --- /dev/null +++ b/stubs/pyphen/pyphen/__init__.pyi @@ -0,0 +1,43 @@ +from collections.abc import Generator +from pathlib import Path +from typing import SupportsInt, TypeAlias +from typing_extensions import Self + +__all__ = ("LANGUAGES", "Pyphen", "language_fallback") +LANGUAGES: dict[str, Path] +_Data: TypeAlias = tuple[str, int, int] + +def language_fallback(language: str) -> str: ... + +class AlternativeParser: + change: str + index: int + cut: int + + def __init__(self, pattern: str, alternative: str) -> None: ... + def __call__(self, value: str | SupportsInt) -> int: ... + +class DataInt(int): + data: _Data | None + + def __new__(cls, value: int, data: _Data | None = ..., reference: DataInt | None = ...) -> Self: ... + +class HyphDict: + patterns: dict[str, tuple[int, tuple[int, ...]]] + cache: dict[str, list[DataInt]] + maxlen: int + + def __init__(self, path: Path) -> None: ... + def positions(self, word: str) -> list[DataInt]: ... + +class Pyphen: + hd: HyphDict + + def __init__( + self, filename: str | Path | None = ..., lang: str | None = ..., left: int = 2, right: int = 2, cache: bool = True + ) -> None: ... + def positions(self, word: str) -> list[DataInt]: ... + def iterate(self, word: str) -> Generator[tuple[str, str]]: ... + def wrap(self, word: str, width: int, hyphen: str = "-") -> tuple[str, str] | None: ... + def inserted(self, word: str, hyphen: str = "-") -> str: ... + __call__ = iterate diff --git a/stubs/pyserial/@tests/stubtest_allowlist.txt b/stubs/pyserial/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..69717d5f7fd3 --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist.txt @@ -0,0 +1,48 @@ +# Error: failed to import +# ======================= +serial.__main__ # SystemExit +serial.serialcli # (IronPython) ModuleNotFoundError: No module named 'System' +serial.serialjava # No Java Communications API implementation found + +# Error: is inconsistent +# ====================== +# These are positional only argument in the stub because they inherit from io.RawIOBase +# but at runtime they are normal arguments that don't have consistent names. +serial.serialutil.SerialBase.readinto +serial.rfc2217.Serial.write +serial.rs485.RS485.write +serial.urlhandler.protocol_cp2110.Serial.write +serial.urlhandler.protocol_loop.Serial.write +serial.urlhandler.protocol_socket.Serial.write +serial.urlhandler.protocol_spy.Serial.write + +# Error: is not present in stub +# ============================= +# Python 2 compatibility +serial.basestring +serial.serialutil.basestring +serial.serialutil.iterbytes +serial.serialutil.to_bytes +serial.serialutil.unicode +serial.tools.hexlify_codec.unicode +serial.tools.miniterm.raw_input +serial.tools.miniterm.unichr +serial.urlhandler.protocol_hwgrep.basestring + +# Deprecated aliases +serial.serialutil.SerialBase.applySettingsDict +serial.serialutil.SerialBase.flushInput +serial.serialutil.SerialBase.flushOutput +serial.serialutil.SerialBase.getCD +serial.serialutil.SerialBase.getCTS +serial.serialutil.SerialBase.getDSR +serial.serialutil.SerialBase.getRI +serial.serialutil.SerialBase.getSettingsDict +serial.serialutil.SerialBase.inWaiting +serial.serialutil.SerialBase.interCharTimeout +serial.serialutil.SerialBase.isOpen +serial.serialutil.SerialBase.sendBreak +serial.serialutil.SerialBase.setDTR +serial.serialutil.SerialBase.setPort +serial.serialutil.SerialBase.setRTS +serial.serialutil.SerialBase.writeTimeout diff --git a/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt b/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..ebfc25005da3 --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,16 @@ +# Error: failed to import +# ======================= +serial.serialwin32 # Windows only +serial.win32 # Windows only +serial.tools.list_ports_windows # Windows only + +# Error: is inconsistent +# ====================== +# Methods defined with positional-only argument in the stub because they inherit from +# io.RawIOBase but at runtime they are normal arguments that don't have consistent +# names. +serial.serialposix.Serial.write + +# intended to be private aliases +serial.tools.list_ports_posix.plat +serial.serialposix.plat diff --git a/stubs/pyserial/@tests/stubtest_allowlist_linux.txt b/stubs/pyserial/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..6de3777701dd --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,18 @@ +# Error: failed to import +# ======================= +serial.serialwin32 # Windows only +serial.win32 # Windows only +serial.tools.list_ports_osx # Mac only +serial.tools.list_ports_windows # Windows only + +# Error: is inconsistent +# ====================== +# Methods defined with positional-only argument in the stub because they inherit from +# io.RawIOBase but at runtime they are normal arguments that don't have consistent +# names. +serial.serialposix.Serial.write + +# Error: is missing from the stub (intended to be private aliases) +# ================================================================ +serial.tools.list_ports_posix.plat +serial.serialposix.plat diff --git a/stubs/pyserial/@tests/stubtest_allowlist_win32.txt b/stubs/pyserial/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..7ba9097251f6 --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,16 @@ +# Error: failed to import +# ======================= +serial.serialposix # Posix only +serial.tools.list_ports_osx # Mac only +serial.tools.list_ports_posix # Posix only + +# Error: is inconsistent +# ====================== +# Methods defined with positional-only argument in the stub because they inherit from +# io.RawIOBase but at runtime they are normal arguments that don't have consistent +# names. +serial.serialwin32.Serial.write + +# Depending on the Windows variant, ULONG_PTR is either c_longlong or c_ulong, +# but when running stubtest, only one of these is seen. +serial.win32.ULONG_PTR diff --git a/stubs/pyserial/METADATA.toml b/stubs/pyserial/METADATA.toml new file mode 100644 index 000000000000..3726b119da44 --- /dev/null +++ b/stubs/pyserial/METADATA.toml @@ -0,0 +1,6 @@ +version = "3.5.*" +upstream-repository = "https://github.com/pyserial/pyserial" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] +extras = ["cp2110"] diff --git a/stubs/pyserial/serial/__init__.pyi b/stubs/pyserial/serial/__init__.pyi new file mode 100644 index 000000000000..7677f130ed41 --- /dev/null +++ b/stubs/pyserial/serial/__init__.pyi @@ -0,0 +1,30 @@ +import sys + +from serial.serialutil import * + +if sys.platform == "win32": + from serial.serialwin32 import Serial as Serial +else: + from serial.serialposix import PosixPollSerial as PosixPollSerial, Serial as Serial, VTIMESerial as VTIMESerial +# TODO: java? cli? These platforms raise flake8-pyi Y008. Should they be included with a noqa? + +__version__: str +VERSION: str +protocol_handler_packages: list[str] + +def serial_for_url( + url: str | None, + baudrate: int = ..., + bytesize: int = ..., + parity: str = ..., + stopbits: float = ..., + timeout: float | None = ..., + xonxoff: bool = ..., + rtscts: bool = ..., + write_timeout: float | None = ..., + dsrdtr: bool = ..., + inter_byte_timeout: float | None = ..., + exclusive: float | None = ..., + *, + do_not_open: bool = ..., +) -> Serial: ... diff --git a/stubs/pyserial/serial/__main__.pyi b/stubs/pyserial/serial/__main__.pyi new file mode 100644 index 000000000000..195cbe7140dc --- /dev/null +++ b/stubs/pyserial/serial/__main__.pyi @@ -0,0 +1 @@ +from serial.tools import miniterm as miniterm diff --git a/stubs/pyserial/serial/rfc2217.pyi b/stubs/pyserial/serial/rfc2217.pyi new file mode 100644 index 000000000000..39275b8b7e8f --- /dev/null +++ b/stubs/pyserial/serial/rfc2217.pyi @@ -0,0 +1,187 @@ +import logging +from _typeshed import ReadableBuffer +from collections.abc import Callable, Generator +from typing import Any + +from serial.serialutil import SerialBase + +LOGGER_LEVELS: dict[str, int] +SE: bytes +NOP: bytes +DM: bytes +BRK: bytes +IP: bytes +AO: bytes +AYT: bytes +EC: bytes +EL: bytes +GA: bytes +SB: bytes +WILL: bytes +WONT: bytes +DO: bytes +DONT: bytes +IAC: bytes +IAC_DOUBLED: bytes +BINARY: bytes +ECHO: bytes +SGA: bytes +COM_PORT_OPTION: bytes +SET_BAUDRATE: bytes +SET_DATASIZE: bytes +SET_PARITY: bytes +SET_STOPSIZE: bytes +SET_CONTROL: bytes +NOTIFY_LINESTATE: bytes +NOTIFY_MODEMSTATE: bytes +FLOWCONTROL_SUSPEND: bytes +FLOWCONTROL_RESUME: bytes +SET_LINESTATE_MASK: bytes +SET_MODEMSTATE_MASK: bytes +PURGE_DATA: bytes +SERVER_SET_BAUDRATE: bytes +SERVER_SET_DATASIZE: bytes +SERVER_SET_PARITY: bytes +SERVER_SET_STOPSIZE: bytes +SERVER_SET_CONTROL: bytes +SERVER_NOTIFY_LINESTATE: bytes +SERVER_NOTIFY_MODEMSTATE: bytes +SERVER_FLOWCONTROL_SUSPEND: bytes +SERVER_FLOWCONTROL_RESUME: bytes +SERVER_SET_LINESTATE_MASK: bytes +SERVER_SET_MODEMSTATE_MASK: bytes +SERVER_PURGE_DATA: bytes +RFC2217_ANSWER_MAP: dict[bytes, bytes] +SET_CONTROL_REQ_FLOW_SETTING: bytes +SET_CONTROL_USE_NO_FLOW_CONTROL: bytes +SET_CONTROL_USE_SW_FLOW_CONTROL: bytes +SET_CONTROL_USE_HW_FLOW_CONTROL: bytes +SET_CONTROL_REQ_BREAK_STATE: bytes +SET_CONTROL_BREAK_ON: bytes +SET_CONTROL_BREAK_OFF: bytes +SET_CONTROL_REQ_DTR: bytes +SET_CONTROL_DTR_ON: bytes +SET_CONTROL_DTR_OFF: bytes +SET_CONTROL_REQ_RTS: bytes +SET_CONTROL_RTS_ON: bytes +SET_CONTROL_RTS_OFF: bytes +SET_CONTROL_REQ_FLOW_SETTING_IN: bytes +SET_CONTROL_USE_NO_FLOW_CONTROL_IN: bytes +SET_CONTROL_USE_SW_FLOW_CONTOL_IN: bytes +SET_CONTROL_USE_HW_FLOW_CONTOL_IN: bytes +SET_CONTROL_USE_DCD_FLOW_CONTROL: bytes +SET_CONTROL_USE_DTR_FLOW_CONTROL: bytes +SET_CONTROL_USE_DSR_FLOW_CONTROL: bytes +LINESTATE_MASK_TIMEOUT: int +LINESTATE_MASK_SHIFTREG_EMPTY: int +LINESTATE_MASK_TRANSREG_EMPTY: int +LINESTATE_MASK_BREAK_DETECT: int +LINESTATE_MASK_FRAMING_ERROR: int +LINESTATE_MASK_PARTIY_ERROR: int +LINESTATE_MASK_OVERRUN_ERROR: int +LINESTATE_MASK_DATA_READY: int +MODEMSTATE_MASK_CD: int +MODEMSTATE_MASK_RI: int +MODEMSTATE_MASK_DSR: int +MODEMSTATE_MASK_CTS: int +MODEMSTATE_MASK_CD_CHANGE: int +MODEMSTATE_MASK_RI_CHANGE: int +MODEMSTATE_MASK_DSR_CHANGE: int +MODEMSTATE_MASK_CTS_CHANGE: int +PURGE_RECEIVE_BUFFER: bytes +PURGE_TRANSMIT_BUFFER: bytes +PURGE_BOTH_BUFFERS: bytes +RFC2217_PARITY_MAP: dict[str, int] +RFC2217_REVERSE_PARITY_MAP: dict[int, str] +RFC2217_STOPBIT_MAP: dict[int | float, int] +RFC2217_REVERSE_STOPBIT_MAP: dict[int, int | float] +M_NORMAL: int +M_IAC_SEEN: int +M_NEGOTIATE: int +REQUESTED: str +ACTIVE: str +INACTIVE: str +REALLY_INACTIVE: str + +class TelnetOption: + connection: Serial + name: str + option: bytes + send_yes: bytes + send_no: bytes + ack_yes: bytes + ack_no: bytes + state: str + active: bool + activation_callback: Callable[[], Any] + + def __init__( + self, + connection: Serial, + name: str, + option: bytes, + send_yes: bytes, + send_no: bytes, + ack_yes: bytes, + ack_no: bytes, + initial_state: str, + activation_callback: Callable[[], Any] | None = None, + ) -> None: ... + def process_incoming(self, command: bytes) -> None: ... + +class TelnetSubnegotiation: + connection: Serial + name: str + option: bytes + value: bytes | None + ack_option: bytes + state: str + def __init__(self, connection: Serial, name: str, option: bytes, ack_option: bytes | None = None) -> None: ... + def set(self, value: bytes) -> None: ... + def is_ready(self) -> bool: ... + @property + def active(self) -> bool: ... + def wait(self, timeout: float = 3) -> None: ... + def check_answer(self, suboption: bytes) -> None: ... + +class Serial(SerialBase): + logger: logging.Logger | None + def open(self) -> None: ... + def from_url(self, url: str) -> tuple[str, int]: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... + def telnet_send_option(self, action: bytes, option: bytes) -> None: ... + def rfc2217_send_subnegotiation(self, option: bytes, value: bytes = b"") -> None: ... + def rfc2217_send_purge(self, value: bytes) -> None: ... + def rfc2217_set_control(self, value: bytes) -> None: ... + def rfc2217_flow_server_ready(self) -> None: ... + def get_modem_state(self) -> int: ... + +class PortManager: + serial: Serial + connection: Serial + logger: logging.Logger | None + mode: int + suboption: bytes | None + telnet_command: bytes | None + modemstate_mask: int + last_modemstate: int | None + linstate_mask: int + def __init__(self, serial_port: Serial, connection: Serial, logger: logging.Logger | None = None) -> None: ... + def telnet_send_option(self, action: bytes, option: bytes) -> None: ... + def rfc2217_send_subnegotiation(self, option: bytes, value: bytes = b"") -> None: ... + def check_modem_lines(self, force_notification: bool = False) -> None: ... + def escape(self, data: bytes) -> Generator[bytes]: ... + def filter(self, data: bytes) -> Generator[bytes]: ... diff --git a/stubs/pyserial/serial/rs485.pyi b/stubs/pyserial/serial/rs485.pyi new file mode 100644 index 000000000000..b76617efb818 --- /dev/null +++ b/stubs/pyserial/serial/rs485.pyi @@ -0,0 +1,18 @@ +import serial + +class RS485Settings: + rts_level_for_tx: bool + rts_level_for_rx: bool + loopback: bool + delay_before_tx: float | None + delay_before_rx: float | None + def __init__( + self, + rts_level_for_tx: bool = True, + rts_level_for_rx: bool = False, + loopback: bool = False, + delay_before_tx: float | None = None, + delay_before_rx: float | None = None, + ) -> None: ... + +class RS485(serial.Serial): ... diff --git a/stubs/pyserial/serial/serialcli.pyi b/stubs/pyserial/serial/serialcli.pyi new file mode 100644 index 000000000000..f243980d4c03 --- /dev/null +++ b/stubs/pyserial/serial/serialcli.pyi @@ -0,0 +1,25 @@ +from _typeshed import ReadableBuffer +from typing import Any + +from serial.serialutil import * + +sab: Any # IronPython object + +def as_byte_array(string: bytes) -> Any: ... # IronPython object + +class Serial(SerialBase): + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/serialjava.pyi b/stubs/pyserial/serial/serialjava.pyi new file mode 100644 index 000000000000..de4dcd57e6fc --- /dev/null +++ b/stubs/pyserial/serial/serialjava.pyi @@ -0,0 +1,30 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Any + +from serial.serialutil import * + +def my_import(name: str) -> Any: ... # Java object +def detect_java_comm(names: Iterable[str]) -> Any: ... # Java object + +comm: Any # Java object + +def device(portnumber: int) -> str: ... + +class Serial(SerialBase): + sPort: Any # Java object + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/serialposix.pyi b/stubs/pyserial/serial/serialposix.pyi new file mode 100644 index 000000000000..2313419ca368 --- /dev/null +++ b/stubs/pyserial/serial/serialposix.pyi @@ -0,0 +1,88 @@ +import sys +from _typeshed import ReadableBuffer +from typing_extensions import Never + +from serial.serialutil import SerialBase + +class PlatformSpecificBase: + BAUDRATE_CONSTANTS: dict[int, int] + def set_low_latency_mode(self, low_latency_settings: bool) -> None: ... + +CMSPAR: int +if sys.platform == "linux": + TCGETS2: int + TCSETS2: int + BOTHER: int + TIOCGRS485: int + TIOCSRS485: int + SER_RS485_ENABLED: int + SER_RS485_RTS_ON_SEND: int + SER_RS485_RTS_AFTER_SEND: int + SER_RS485_RX_DURING_TX: int + +if sys.platform == "darwin": + IOSSIOSPEED: int + + class PlatformSpecific(PlatformSpecificBase): + osx_version: list[str] + TIOCSBRK: int + TIOCCBRK: int + +else: + class PlatformSpecific(PlatformSpecificBase): ... + +TIOCMGET: int +TIOCMBIS: int +TIOCMBIC: int +TIOCMSET: int +TIOCM_DTR: int +TIOCM_RTS: int +TIOCM_CTS: int +TIOCM_CAR: int +TIOCM_RNG: int +TIOCM_DSR: int +TIOCM_CD: int +TIOCM_RI: int +TIOCINQ: int +TIOCOUTQ: int +TIOCM_zero_str: bytes +TIOCM_RTS_str: bytes +TIOCM_DTR_str: bytes +TIOCSBRK: int +TIOCCBRK: int + +class Serial(SerialBase, PlatformSpecific): + fd: int | None + pipe_abort_read_w: int | None + pipe_abort_read_r: int | None + pipe_abort_write_w: int | None + pipe_abort_write_r: int | None + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def cancel_read(self) -> None: ... + def cancel_write(self) -> None: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + def send_break(self, duration: float = 0.25) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... + @property + def out_waiting(self) -> int: ... + def set_input_flow_control(self, enable: bool = True) -> None: ... + def set_output_flow_control(self, enable: bool = True) -> None: ... + def nonblocking(self) -> None: ... + +class PosixPollSerial(Serial): ... + +class VTIMESerial(Serial): + @property + def cancel_read(self) -> Never: ... diff --git a/stubs/pyserial/serial/serialutil.pyi b/stubs/pyserial/serial/serialutil.pyi new file mode 100644 index 000000000000..a21681d688e7 --- /dev/null +++ b/stubs/pyserial/serial/serialutil.pyi @@ -0,0 +1,169 @@ +import io +from _typeshed import ReadableBuffer, WriteableBuffer +from abc import abstractmethod +from collections.abc import Callable, Generator +from typing import Any, Final + +from serial.rs485 import RS485Settings + +XON: Final = b"\x11" +XOFF: Final = b"\x13" +CR: Final = b"\r" +LF: Final = b"\n" +PARITY_NONE: Final = "N" +PARITY_EVEN: Final = "E" +PARITY_ODD: Final = "O" +PARITY_MARK: Final = "M" +PARITY_SPACE: Final = "S" +STOPBITS_ONE: Final = 1 +STOPBITS_ONE_POINT_FIVE: float +STOPBITS_TWO: Final = 2 +FIVEBITS: Final = 5 +SIXBITS: Final = 6 +SEVENBITS: Final = 7 +EIGHTBITS: Final = 8 +PARITY_NAMES: dict[str, str] + +class SerialException(OSError): ... +class SerialTimeoutException(SerialException): ... + +class PortNotOpenError(SerialException): + def __init__(self) -> None: ... + +class Timeout: + TIME: Callable[[], float] + is_infinite: bool + is_non_blocking: bool + duration: float + target_time: float + def __init__(self, duration: float) -> None: ... + def expired(self) -> bool: ... + def time_left(self) -> float: ... + def restart(self, duration: float) -> None: ... + +class SerialBase(io.RawIOBase): + BAUDRATES: tuple[int, ...] + BYTESIZES: tuple[int, ...] + PARITIES: tuple[str, ...] + STOPBITS: tuple[int, float, int] + is_open: bool + portstr: str | None + name: str | None + def __init__( + self, + port: str | None = None, + baudrate: int = 9600, + bytesize: int = 8, + parity: str = "N", + stopbits: float = 1, + timeout: float | None = None, + xonxoff: bool = False, + rtscts: bool = False, + write_timeout: float | None = None, + dsrdtr: bool = False, + inter_byte_timeout: float | None = None, + exclusive: bool | None = None, + ) -> None: ... + + # Return type: + # ------------ + # `io.RawIOBase`, the super class, declares the return type of read as `-> bytes | None`. + # `SerialBase` does not define `read` at runtime but REQUIRES subclasses to implement it and + # require it to return `bytes`. + # Abstract: + # --------- + # `io.RawIOBase` implements `read` in terms of `readinto`. `SerialBase` implements `readinto` + # in terms of `read`. If subclasses do not implement `read`, any call to `read` or `read_into` + # will fail at runtime with a `RecursionError`. + @abstractmethod + def read(self, size: int = -1, /) -> bytes: ... + @abstractmethod + def write(self, b: ReadableBuffer, /) -> int | None: ... + + @property + def port(self) -> str | None: ... + @port.setter + def port(self, port: str | None) -> None: ... + + @property + def baudrate(self) -> int: ... + @baudrate.setter + def baudrate(self, baudrate: int) -> None: ... + + @property + def bytesize(self) -> int: ... + @bytesize.setter + def bytesize(self, bytesize: int) -> None: ... + + @property + def exclusive(self) -> bool | None: ... + @exclusive.setter + def exclusive(self, exclusive: bool | None) -> None: ... + + @property + def parity(self) -> str: ... + @parity.setter + def parity(self, parity: str) -> None: ... + + @property + def stopbits(self) -> float: ... + @stopbits.setter + def stopbits(self, stopbits: float) -> None: ... + + @property + def timeout(self) -> float | None: ... + @timeout.setter + def timeout(self, timeout: float | None) -> None: ... + + @property + def write_timeout(self) -> float | None: ... + @write_timeout.setter + def write_timeout(self, timeout: float | None) -> None: ... + + @property + def inter_byte_timeout(self) -> float | None: ... + @inter_byte_timeout.setter + def inter_byte_timeout(self, ic_timeout: float | None) -> None: ... + + @property + def xonxoff(self) -> bool: ... + @xonxoff.setter + def xonxoff(self, xonxoff: bool) -> None: ... + + @property + def rtscts(self) -> bool: ... + @rtscts.setter + def rtscts(self, rtscts: bool) -> None: ... + + @property + def dsrdtr(self) -> bool: ... + @dsrdtr.setter + def dsrdtr(self, dsrdtr: bool | None = ...) -> None: ... + + @property + def rts(self) -> bool: ... + @rts.setter + def rts(self, value: bool) -> None: ... + + @property + def dtr(self) -> bool: ... + @dtr.setter + def dtr(self, value: bool) -> None: ... + + @property + def break_condition(self) -> bool: ... + @break_condition.setter + def break_condition(self, value: bool) -> None: ... + + @property + def rs485_mode(self) -> RS485Settings | None: ... + @rs485_mode.setter + def rs485_mode(self, rs485_settings: RS485Settings | None) -> None: ... + + def get_settings(self) -> dict[str, Any]: ... + def apply_settings(self, d: dict[str, Any]) -> None: ... + def readinto(self, buffer: WriteableBuffer, /) -> int: ... # returns int unlike `io.RawIOBase` + def send_break(self, duration: float = 0.25) -> None: ... + def read_all(self) -> bytes: ... + def read_until(self, expected: bytes = b"\n", size: int | None = None) -> bytes: ... + def iread_until(self, expected: bytes = ..., size: int | None = ...) -> Generator[bytes]: ... diff --git a/stubs/pyserial/serial/serialwin32.pyi b/stubs/pyserial/serial/serialwin32.pyi new file mode 100644 index 000000000000..8fb2e3ba38d6 --- /dev/null +++ b/stubs/pyserial/serial/serialwin32.pyi @@ -0,0 +1,26 @@ +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +class Serial(SerialBase): + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... + def set_buffer_size(self, rx_size: int = 4096, tx_size: int | None = None) -> None: ... + def set_output_flow_control(self, enable: bool = True) -> None: ... + @property + def out_waiting(self) -> int: ... + def cancel_read(self) -> None: ... + def cancel_write(self) -> None: ... diff --git a/stubs/pyserial/serial/threaded/__init__.pyi b/stubs/pyserial/serial/threaded/__init__.pyi new file mode 100644 index 000000000000..4cc3c15648ee --- /dev/null +++ b/stubs/pyserial/serial/threaded/__init__.pyi @@ -0,0 +1,51 @@ +import threading +from _typeshed import ReadableBuffer +from collections.abc import Callable +from types import TracebackType +from typing import Generic, TypeVar +from typing_extensions import Self + +from serial import Serial + +_P = TypeVar("_P", bound=Protocol, default=Protocol) + +class Protocol: + def connection_made(self, transport: ReaderThread[Self]) -> None: ... + def data_received(self, data: bytes) -> None: ... + def connection_lost(self, exc: BaseException | None) -> None: ... + +class Packetizer(Protocol): + TERMINATOR: bytes + buffer: bytearray + transport: ReaderThread[Self] | None + def handle_packet(self, packet: bytes) -> None: ... + +class FramedPacket(Protocol): + START: bytes + STOP: bytes + packet: bytearray + in_packet: bool + transport: ReaderThread[Self] | None + def handle_packet(self, packet: bytes) -> None: ... + def handle_out_of_packet_data(self, data: bytes) -> None: ... + +class LineReader(Packetizer): + ENCODING: str + UNICODE_HANDLING: str + def handle_line(self, line: str) -> None: ... + def write_line(self, text: str) -> None: ... + +class ReaderThread(threading.Thread, Generic[_P]): + serial: Serial + protocol_factory: Callable[[], _P] + alive: bool + protocol: _P + def __init__(self, serial_instance: Serial, protocol_factory: Callable[[], _P]) -> None: ... + def stop(self) -> None: ... + def write(self, data: ReadableBuffer) -> int: ... + def close(self) -> None: ... + def connect(self) -> tuple[Self, _P]: ... + def __enter__(self) -> _P: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... diff --git a/stubs/pyserial/serial/tools/__init__.pyi b/stubs/pyserial/serial/tools/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyserial/serial/tools/hexlify_codec.pyi b/stubs/pyserial/serial/tools/hexlify_codec.pyi new file mode 100644 index 000000000000..10e43143ee48 --- /dev/null +++ b/stubs/pyserial/serial/tools/hexlify_codec.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import ReadableBuffer + +HEXDIGITS: str + +def hex_encode(data: str, errors: str = "strict") -> tuple[bytes, int]: ... +def hex_decode(data: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class Codec(codecs.Codec): + def encode(self, data: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, data: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + state: int + def encode(self, data: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, data: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stubs/pyserial/serial/tools/list_ports.pyi b/stubs/pyserial/serial/tools/list_ports.pyi new file mode 100644 index 000000000000..be96fdc686fb --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports.pyi @@ -0,0 +1,13 @@ +import re +import sys +from collections.abc import Generator + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform == "win32": + from serial.tools.list_ports_windows import comports as comports +else: + from serial.tools.list_ports_posix import comports as comports + +def grep(regexp: str | re.Pattern[str], include_links: bool = False) -> Generator[ListPortInfo]: ... +def main() -> None: ... diff --git a/stubs/pyserial/serial/tools/list_ports_common.pyi b/stubs/pyserial/serial/tools/list_ports_common.pyi new file mode 100644 index 000000000000..465bb04062aa --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_common.pyi @@ -0,0 +1,33 @@ +from collections.abc import Collection +from typing import Any + +def numsplit(text: str) -> list[str | int]: ... + +class ListPortInfo: + device: str + name: str + description: str + hwid: str + # USB specific data: the vid and pid attributes below are specific to USB devices only and + # should be marked as Optional. Since the majority of the serial devices nowadays are USB + # devices, typing them as Optional will be unnecessarily annoying. We type them with as + # `int | Any` so that obvious typing errors like ListPortInfo.pid + "str" are flagged. + # As desired, this will cause a false negative if the value is ever None, but may also cause + # other false negatives from the Any proliferating. The other USB attributes are correctly + # typed as Optional because they may be `None` even for USB devices + # Original discussion at https://github.com/python/typeshed/pull/9347#issuecomment-1358245865. + vid: int | Any + pid: int | Any + serial_number: str | None + location: str | None + manufacturer: str | None + product: str | None + interface: str | None + def __init__(self, device: str, skip_link_detection: bool = False) -> None: ... + def usb_description(self) -> str: ... + def usb_info(self) -> str: ... + def apply_usb_info(self) -> None: ... + def __lt__(self, other: ListPortInfo) -> bool: ... + def __getitem__(self, index: int) -> str: ... + +def list_links(devices: Collection[str]) -> list[str]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_linux.pyi b/stubs/pyserial/serial/tools/list_ports_linux.pyi new file mode 100644 index 000000000000..a56d2c581132 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_linux.pyi @@ -0,0 +1,11 @@ +from serial.tools.list_ports_common import ListPortInfo + +class SysFS(ListPortInfo): + usb_device_path: str | None + device_path: str | None + subsystem: str | None + usb_interface_path: str | None + def __init__(self, device: str) -> None: ... + def read_line(self, *args: str) -> str | None: ... + +def comports(include_links: bool = False) -> list[SysFS]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_osx.pyi b/stubs/pyserial/serial/tools/list_ports_osx.pyi new file mode 100644 index 000000000000..49746028a3f7 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_osx.pyi @@ -0,0 +1,36 @@ +import ctypes +import sys + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform == "darwin": + iokit: ctypes.CDLL + cf: ctypes.CDLL + kIOMasterPortDefault: int + kCFAllocatorDefault: ctypes.c_void_p + kCFStringEncodingMacRoman: int + kCFStringEncodingUTF8: int + kUSBVendorString: str + kUSBSerialNumberString: str + io_name_size: int + KERN_SUCCESS: int + kern_return_t = ctypes.c_int + kCFNumberSInt8Type: int + kCFNumberSInt16Type: int + kCFNumberSInt32Type: int + kCFNumberSInt64Type: int + + def get_string_property(device_type: ctypes._CData, property: str) -> str | None: ... + def get_int_property(device_type: ctypes._CData, property: str, cf_number_type: int) -> int | None: ... + def IORegistryEntryGetName(device: ctypes._CData) -> str | None: ... + def IOObjectGetClass(device: ctypes._CData) -> bytes: ... + def GetParentDeviceByType(device: ctypes._CData, parent_type: str) -> ctypes._CData | None: ... + def GetIOServicesByType(service_type: str) -> list[ctypes._CData]: ... + def location_to_string(locationID: int) -> str: ... + + # `SuitableSerialInterface` has required attributes `id: int` and `name: str` but they are not defined on the class + class SuitableSerialInterface: ... + + def scan_interfaces() -> list[SuitableSerialInterface]: ... + def search_for_locationID_in_interfaces(serial_interfaces: list[SuitableSerialInterface], locationID: int) -> str | None: ... + def comports(include_links: bool = False) -> list[ListPortInfo]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_posix.pyi b/stubs/pyserial/serial/tools/list_ports_posix.pyi new file mode 100644 index 000000000000..969dfd42ef45 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_posix.pyi @@ -0,0 +1,11 @@ +import sys + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform != "win32": + if sys.platform == "linux": + from serial.tools.list_ports_linux import comports as comports + elif sys.platform == "darwin": + from serial.tools.list_ports_osx import comports as comports + else: + def comports(include_links: bool = ...) -> list[ListPortInfo]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_windows.pyi b/stubs/pyserial/serial/tools/list_ports_windows.pyi new file mode 100644 index 000000000000..b5ba02fc7714 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_windows.pyi @@ -0,0 +1,78 @@ +import ctypes +import sys +from _typeshed import Incomplete +from collections.abc import Generator +from ctypes.wintypes import DWORD + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform == "win32": + + def ValidHandle( + value: type[ctypes._CData] | None, func: ctypes._FuncPointer, arguments: tuple[ctypes._CData, ...] + ) -> ctypes._CData: ... + + NULL: int + HDEVINFO = ctypes.c_void_p + LPCTSTR = ctypes.c_wchar_p + PCTSTR = ctypes.c_wchar_p + PTSTR = ctypes.c_wchar_p + LPDWORD: ctypes._Pointer[DWORD] + PDWORD: ctypes._Pointer[DWORD] + LPBYTE = ctypes.c_void_p + PBYTE = ctypes.c_void_p + ACCESS_MASK = DWORD + REGSAM = ACCESS_MASK + + class GUID(ctypes.Structure): + Data1: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data2: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data3: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data4: ctypes._CField[Incomplete, Incomplete, Incomplete] + + class SP_DEVINFO_DATA(ctypes.Structure): + cbSize: ctypes._CField[Incomplete, Incomplete, Incomplete] + ClassGuid: ctypes._CField[Incomplete, Incomplete, Incomplete] + DevInst: ctypes._CField[Incomplete, Incomplete, Incomplete] + Reserved: ctypes._CField[Incomplete, Incomplete, Incomplete] + + PSP_DEVINFO_DATA: type[ctypes._Pointer[SP_DEVINFO_DATA]] + PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p + setupapi: ctypes.WinDLL + SetupDiDestroyDeviceInfoList: ctypes._NamedFuncPointer + SetupDiClassGuidsFromName: ctypes._NamedFuncPointer + SetupDiEnumDeviceInfo: ctypes._NamedFuncPointer + SetupDiGetClassDevs: ctypes._NamedFuncPointer + SetupDiGetDeviceRegistryProperty: ctypes._NamedFuncPointer + SetupDiGetDeviceInstanceId: ctypes._NamedFuncPointer + SetupDiOpenDevRegKey: ctypes._NamedFuncPointer + advapi32: ctypes.WinDLL + RegCloseKey: ctypes._NamedFuncPointer + RegQueryValueEx: ctypes._NamedFuncPointer + cfgmgr32: ctypes.WinDLL + CM_Get_Parent: ctypes._NamedFuncPointer + CM_Get_Device_IDW: ctypes._NamedFuncPointer + CM_MapCrToWin32Err: ctypes._NamedFuncPointer + DIGCF_PRESENT: int + DIGCF_DEVICEINTERFACE: int + INVALID_HANDLE_VALUE: int + ERROR_INSUFFICIENT_BUFFER: int + ERROR_NOT_FOUND: int + SPDRP_HARDWAREID: int + SPDRP_FRIENDLYNAME: int + SPDRP_LOCATION_PATHS: int + SPDRP_MFG: int + DICS_FLAG_GLOBAL: int + DIREG_DEV: int + KEY_READ: int + MAX_USB_DEVICE_TREE_TRAVERSAL_DEPTH: int + + def get_parent_serial_number( + child_devinst: ctypes._CData, + child_vid: int | None, + child_pid: int | None, + depth: int = 0, + last_serial_number: str | None = None, + ) -> str: ... + def iterate_comports() -> Generator[ListPortInfo]: ... + def comports(include_links: bool = False) -> list[ListPortInfo]: ... diff --git a/stubs/pyserial/serial/tools/miniterm.pyi b/stubs/pyserial/serial/tools/miniterm.pyi new file mode 100644 index 000000000000..2d541ea056ba --- /dev/null +++ b/stubs/pyserial/serial/tools/miniterm.pyi @@ -0,0 +1,122 @@ +import codecs +import sys +import threading +from _typeshed import SupportsFlush, SupportsWrite, Unused +from collections.abc import Iterable +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from serial import Serial + +_AnyStrT_contra = TypeVar("_AnyStrT_contra", contravariant=True) + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[_AnyStrT_contra], SupportsFlush, Protocol): ... + +@type_check_only +class _SupportsRead(Protocol): + def read(self, n: int, /) -> str: ... + +def key_description(character: str) -> str: ... + +class ConsoleBase: + byte_output: _SupportsWriteAndFlush[bytes] + output: _SupportsWriteAndFlush[str] + def __init__(self) -> None: ... + def setup(self) -> None: ... + def cleanup(self) -> None: ... + def getkey(self) -> None: ... + def write_bytes(self, byte_string: bytes) -> None: ... + def write(self, text: str) -> None: ... + def cancel(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused, **kwargs: Unused) -> None: ... + +if sys.platform == "win32": + class Out: + fd: int + def __init__(self, fd: int) -> None: ... + def flush(self) -> None: ... + def write(self, s: bytes) -> None: ... + + class Console(ConsoleBase): + fncodes: dict[str, str] + navcodes: dict[str, str] + def __del__(self) -> None: ... + +else: + class Console(ConsoleBase): + fd: int + old: list[Any] # return type of termios.tcgetattr() + enc_stdin: _SupportsRead + +class Transform: + def rx(self, text: str) -> str: ... + def tx(self, text: str) -> str: ... + def echo(self, text: str) -> str: ... + +class CRLF(Transform): ... +class CR(Transform): ... +class LF(Transform): ... + +class NoTerminal(Transform): + REPLACEMENT_MAP: dict[int, int] + +class NoControls(NoTerminal): + REPLACEMENT_MAP: dict[int, int] + +class Printable(Transform): ... + +class Colorize(Transform): + input_color: str + echo_color: str + +class DebugIO(Transform): ... + +EOL_TRANSFORMATIONS: dict[str, type[Transform]] +TRANSFORMATIONS: dict[str, type[Transform]] + +def ask_for_port() -> str: ... + +class Miniterm: + console: Console + serial: Serial + echo: bool + raw: bool + input_encoding: str + output_encoding: str + eol: str + filters: Iterable[str] + exit_character: str + menu_character: str + alive: bool | None + receiver_thread: threading.Thread | None + rx_decoder: codecs.IncrementalDecoder | None + tx_decoder: codecs.IncrementalDecoder | None + tx_encoder: codecs.IncrementalEncoder | None + def __init__(self, serial_instance: Serial, echo: bool = False, eol: str = "crlf", filters: Iterable[str] = ()) -> None: ... + transmitter_thread: threading.Thread + def start(self) -> None: ... + def stop(self) -> None: ... + def join(self, transmit_only: bool = False) -> None: ... + def close(self) -> None: ... + tx_transformations: list[Transform] + rx_transformations: list[Transform] + def update_transformations(self) -> None: ... + def set_rx_encoding(self, encoding: str, errors: str = "replace") -> None: ... + def set_tx_encoding(self, encoding: str, errors: str = "replace") -> None: ... + def dump_port_settings(self) -> None: ... + def reader(self) -> None: ... + def writer(self) -> None: ... + def handle_menu_key(self, c: str) -> None: ... + def upload_file(self) -> None: ... + def change_filter(self) -> None: ... + def change_encoding(self) -> None: ... + def change_baudrate(self) -> None: ... + def change_port(self) -> None: ... + def suspend_port(self) -> None: ... + def get_help_text(self) -> str: ... + +def main( + default_port: str | None = None, default_baudrate: int = 9600, default_rts: int | None = None, default_dtr: int | None = None +) -> None: ... diff --git a/stubs/pyserial/serial/urlhandler/__init__.pyi b/stubs/pyserial/serial/urlhandler/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyserial/serial/urlhandler/protocol_alt.pyi b/stubs/pyserial/serial/urlhandler/protocol_alt.pyi new file mode 100644 index 000000000000..9711af93c435 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_alt.pyi @@ -0,0 +1,3 @@ +from serial import Serial + +def serial_class_for_url(url: str) -> tuple[str, Serial]: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi b/stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi new file mode 100644 index 000000000000..661e9d3830a4 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi @@ -0,0 +1,13 @@ +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +class Serial(SerialBase): + def open(self) -> None: ... + def from_url(self, url: str) -> bytes: ... + @property + def in_waiting(self) -> int: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi b/stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi new file mode 100644 index 000000000000..93dc1402ae55 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi @@ -0,0 +1,4 @@ +import serial + +class Serial(serial.Serial): + def from_url(self, url: str) -> str: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_loop.pyi b/stubs/pyserial/serial/urlhandler/protocol_loop.pyi new file mode 100644 index 000000000000..97db0d4dfcf1 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_loop.pyi @@ -0,0 +1,32 @@ +import logging +import queue as _queue +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +LOGGER_LEVELS: dict[str, int] + +class Serial(SerialBase): + buffer_size: int + queue: _queue.Queue[bytes | None] | None + logger: logging.Logger | None + def open(self) -> None: ... + def from_url(self, url: str) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def cancel_read(self) -> None: ... + def cancel_write(self) -> None: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def out_waiting(self) -> int: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi b/stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi new file mode 100644 index 000000000000..82903b51464b --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi @@ -0,0 +1 @@ +from serial.rfc2217 import Serial as Serial diff --git a/stubs/pyserial/serial/urlhandler/protocol_socket.pyi b/stubs/pyserial/serial/urlhandler/protocol_socket.pyi new file mode 100644 index 000000000000..9ac407eb76db --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_socket.pyi @@ -0,0 +1,26 @@ +import logging +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +LOGGER_LEVELS: dict[str, int] +POLL_TIMEOUT: float + +class Serial(SerialBase): + logger: logging.Logger | None + def open(self) -> None: ... + def from_url(self, url: str) -> tuple[str, int]: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_spy.pyi b/stubs/pyserial/serial/urlhandler/protocol_spy.pyi new file mode 100644 index 000000000000..29b45167dc76 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_spy.pyi @@ -0,0 +1,35 @@ +from collections.abc import Generator +from typing import TextIO, type_check_only + +import serial + +def sixteen(data: bytes) -> Generator[tuple[str, str] | tuple[None, None]]: ... +def hexdump(data: bytes) -> Generator[tuple[int, str]]: ... + +@type_check_only +class _Formatter: + def rx(self, data: bytes) -> None: ... + def tx(self, data: bytes) -> None: ... + def control(self, name: str, value: str) -> None: ... + +class FormatRaw(_Formatter): + output: TextIO + color: bool + rx_color: str + tx_color: str + def __init__(self, output: TextIO, color: bool) -> None: ... + +class FormatHexdump(_Formatter): + start_time: float + output: TextIO + color: bool + rx_color: str + tx_color: str + control_color: str + def __init__(self, output: TextIO, color: bool) -> None: ... + def write_line(self, timestamp: float, label: str, value: str, value2: str = "") -> None: ... + +class Serial(serial.Serial): + formatter: FormatRaw | FormatHexdump | None + show_all: bool + def from_url(self, url: str) -> str: ... diff --git a/stubs/pyserial/serial/win32.pyi b/stubs/pyserial/serial/win32.pyi new file mode 100644 index 000000000000..807f2679c4e5 --- /dev/null +++ b/stubs/pyserial/serial/win32.pyi @@ -0,0 +1,253 @@ +import sys +from _typeshed import Incomplete +from ctypes import Structure, Union, _CField, _NamedFuncPointer, _Pointer, c_int64, c_ulong, c_void_p +from ctypes.wintypes import DWORD +from typing import TypeAlias + +if sys.platform == "win32": + def is_64bit() -> bool: ... + + ULONG_PTR: type[c_int64 | c_ulong] + + class _SECURITY_ATTRIBUTES(Structure): + nLength: _CField[Incomplete, Incomplete, Incomplete] + lpSecurityDescriptor: _CField[Incomplete, Incomplete, Incomplete] + bInheritHandle: _CField[Incomplete, Incomplete, Incomplete] + + LPSECURITY_ATTRIBUTES: type[_Pointer[_SECURITY_ATTRIBUTES]] + CreateEvent: _NamedFuncPointer + CreateFile: _NamedFuncPointer + # The following are included in __all__ but their existence is not guaranteed as + # they are defined in a try/except block. Their aliases above are always defined. + CreateEventW: _NamedFuncPointer + CreateFileW: _NamedFuncPointer + + class _OVERLAPPED(Structure): + Internal: _CField[Incomplete, Incomplete, Incomplete] + InternalHigh: _CField[Incomplete, Incomplete, Incomplete] + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + Pointer: _CField[Incomplete, Incomplete, Incomplete] + hEvent: _CField[Incomplete, Incomplete, Incomplete] + + OVERLAPPED: TypeAlias = _OVERLAPPED + + class _COMSTAT(Structure): + fCtsHold: _CField[Incomplete, Incomplete, Incomplete] + fDsrHold: _CField[Incomplete, Incomplete, Incomplete] + fRlsdHold: _CField[Incomplete, Incomplete, Incomplete] + fXoffHold: _CField[Incomplete, Incomplete, Incomplete] + fXoffSent: _CField[Incomplete, Incomplete, Incomplete] + fEof: _CField[Incomplete, Incomplete, Incomplete] + fTxim: _CField[Incomplete, Incomplete, Incomplete] + fReserved: _CField[Incomplete, Incomplete, Incomplete] + cbInQue: _CField[Incomplete, Incomplete, Incomplete] + cbOutQue: _CField[Incomplete, Incomplete, Incomplete] + + COMSTAT: TypeAlias = _COMSTAT + + class _DCB(Structure): + DCBlength: _CField[Incomplete, Incomplete, Incomplete] + BaudRate: _CField[Incomplete, Incomplete, Incomplete] + fBinary: _CField[Incomplete, Incomplete, Incomplete] + fParity: _CField[Incomplete, Incomplete, Incomplete] + fOutxCtsFlow: _CField[Incomplete, Incomplete, Incomplete] + fOutxDsrFlow: _CField[Incomplete, Incomplete, Incomplete] + fDtrControl: _CField[Incomplete, Incomplete, Incomplete] + fDsrSensitivity: _CField[Incomplete, Incomplete, Incomplete] + fTXContinueOnXoff: _CField[Incomplete, Incomplete, Incomplete] + fOutX: _CField[Incomplete, Incomplete, Incomplete] + fInX: _CField[Incomplete, Incomplete, Incomplete] + fErrorChar: _CField[Incomplete, Incomplete, Incomplete] + fNull: _CField[Incomplete, Incomplete, Incomplete] + fRtsControl: _CField[Incomplete, Incomplete, Incomplete] + fAbortOnError: _CField[Incomplete, Incomplete, Incomplete] + fDummy2: _CField[Incomplete, Incomplete, Incomplete] + wReserved: _CField[Incomplete, Incomplete, Incomplete] + XonLim: _CField[Incomplete, Incomplete, Incomplete] + XoffLim: _CField[Incomplete, Incomplete, Incomplete] + ByteSize: _CField[Incomplete, Incomplete, Incomplete] + Parity: _CField[Incomplete, Incomplete, Incomplete] + StopBits: _CField[Incomplete, Incomplete, Incomplete] + XonChar: _CField[Incomplete, Incomplete, Incomplete] + XoffChar: _CField[Incomplete, Incomplete, Incomplete] + ErrorChar: _CField[Incomplete, Incomplete, Incomplete] + EofChar: _CField[Incomplete, Incomplete, Incomplete] + EvtChar: _CField[Incomplete, Incomplete, Incomplete] + wReserved1: _CField[Incomplete, Incomplete, Incomplete] + + DCB: TypeAlias = _DCB + + class _COMMTIMEOUTS(Structure): + ReadIntervalTimeout: _CField[Incomplete, Incomplete, Incomplete] + ReadTotalTimeoutMultiplier: _CField[Incomplete, Incomplete, Incomplete] + ReadTotalTimeoutConstant: _CField[Incomplete, Incomplete, Incomplete] + WriteTotalTimeoutMultiplier: _CField[Incomplete, Incomplete, Incomplete] + WriteTotalTimeoutConstant: _CField[Incomplete, Incomplete, Incomplete] + + COMMTIMEOUTS: TypeAlias = _COMMTIMEOUTS + + GetLastError: _NamedFuncPointer + LPOVERLAPPED: type[_Pointer[_OVERLAPPED]] + LPDWORD: type[_Pointer[DWORD]] + GetOverlappedResult: _NamedFuncPointer + ResetEvent: _NamedFuncPointer + LPCVOID = c_void_p + WriteFile: _NamedFuncPointer + LPVOID = c_void_p + ReadFile: _NamedFuncPointer + CloseHandle: _NamedFuncPointer + ClearCommBreak: _NamedFuncPointer + LPCOMSTAT: type[_Pointer[_COMSTAT]] + ClearCommError: _NamedFuncPointer + SetupComm: _NamedFuncPointer + EscapeCommFunction: _NamedFuncPointer + GetCommModemStatus: _NamedFuncPointer + LPDCB: type[_Pointer[_DCB]] + GetCommState: _NamedFuncPointer + LPCOMMTIMEOUTS: type[_Pointer[_COMMTIMEOUTS]] + GetCommTimeouts: _NamedFuncPointer + PurgeComm: _NamedFuncPointer + SetCommBreak: _NamedFuncPointer + SetCommMask: _NamedFuncPointer + SetCommState: _NamedFuncPointer + SetCommTimeouts: _NamedFuncPointer + WaitForSingleObject: _NamedFuncPointer + WaitCommEvent: _NamedFuncPointer + CancelIoEx: _NamedFuncPointer + + ONESTOPBIT: int + TWOSTOPBITS: int + NOPARITY: int + ODDPARITY: int + EVENPARITY: int + RTS_CONTROL_HANDSHAKE: int + RTS_CONTROL_ENABLE: int + DTR_CONTROL_HANDSHAKE: int + DTR_CONTROL_ENABLE: int + MS_DSR_ON: int + EV_RING: int + EV_PERR: int + EV_ERR: int + SETXOFF: int + EV_RXCHAR: int + GENERIC_WRITE: int + PURGE_TXCLEAR: int + FILE_FLAG_OVERLAPPED: int + EV_DSR: int + MAXDWORD: int + EV_RLSD: int + ERROR_IO_PENDING: int + MS_CTS_ON: int + EV_EVENT1: int + EV_RX80FULL: int + PURGE_RXABORT: int + FILE_ATTRIBUTE_NORMAL: int + PURGE_TXABORT: int + SETXON: int + OPEN_EXISTING: int + MS_RING_ON: int + EV_TXEMPTY: int + EV_RXFLAG: int + MS_RLSD_ON: int + GENERIC_READ: int + EV_EVENT2: int + EV_CTS: int + EV_BREAK: int + PURGE_RXCLEAR: int + + class N11_OVERLAPPED4DOLLAR_48E(Union): + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + Pointer: _CField[Incomplete, Incomplete, Incomplete] + + class N11_OVERLAPPED4DOLLAR_484DOLLAR_49E(Structure): + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + + PVOID: TypeAlias = c_void_p + + __all__ = [ + "GetLastError", + "MS_CTS_ON", + "FILE_ATTRIBUTE_NORMAL", + "DTR_CONTROL_ENABLE", + "_COMSTAT", + "MS_RLSD_ON", + "GetOverlappedResult", + "SETXON", + "PURGE_TXABORT", + "PurgeComm", + "N11_OVERLAPPED4DOLLAR_48E", + "EV_RING", + "ONESTOPBIT", + "SETXOFF", + "PURGE_RXABORT", + "GetCommState", + "RTS_CONTROL_ENABLE", + "_DCB", + "CreateEvent", + "_COMMTIMEOUTS", + "_SECURITY_ATTRIBUTES", + "EV_DSR", + "EV_PERR", + "EV_RXFLAG", + "OPEN_EXISTING", + "DCB", + "FILE_FLAG_OVERLAPPED", + "EV_CTS", + "SetupComm", + "LPOVERLAPPED", + "EV_TXEMPTY", + "ClearCommBreak", + "LPSECURITY_ATTRIBUTES", + "SetCommBreak", + "SetCommTimeouts", + "COMMTIMEOUTS", + "ODDPARITY", + "EV_RLSD", + "GetCommModemStatus", + "EV_EVENT2", + "PURGE_TXCLEAR", + "EV_BREAK", + "EVENPARITY", + "LPCVOID", + "COMSTAT", + "ReadFile", + "PVOID", + "_OVERLAPPED", + "WriteFile", + "GetCommTimeouts", + "ResetEvent", + "EV_RXCHAR", + "LPCOMSTAT", + "ClearCommError", + "ERROR_IO_PENDING", + "EscapeCommFunction", + "GENERIC_READ", + "RTS_CONTROL_HANDSHAKE", + "OVERLAPPED", + "DTR_CONTROL_HANDSHAKE", + "PURGE_RXCLEAR", + "GENERIC_WRITE", + "LPDCB", + "CreateEventW", + "SetCommMask", + "EV_EVENT1", + "SetCommState", + "LPVOID", + "CreateFileW", + "LPDWORD", + "EV_RX80FULL", + "TWOSTOPBITS", + "LPCOMMTIMEOUTS", + "MAXDWORD", + "MS_DSR_ON", + "MS_RING_ON", + "N11_OVERLAPPED4DOLLAR_484DOLLAR_49E", + "EV_ERR", + "ULONG_PTR", + "CreateFile", + "NOPARITY", + "CloseHandle", + ] diff --git a/stubs/pysftp/METADATA.toml b/stubs/pysftp/METADATA.toml deleted file mode 100644 index e3748bd7b73d..000000000000 --- a/stubs/pysftp/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -version = "0.2.*" -python2 = true -requires = ["types-paramiko"] diff --git a/stubs/pysftp/pysftp/__init__.pyi b/stubs/pysftp/pysftp/__init__.pyi deleted file mode 100644 index 58e051248fc2..000000000000 --- a/stubs/pysftp/pysftp/__init__.pyi +++ /dev/null @@ -1,126 +0,0 @@ -from stat import S_IMODE as S_IMODE -from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Sequence, Text, Type, Union -from typing_extensions import Literal - -import paramiko -from paramiko import AuthenticationException as AuthenticationException -from pysftp.exceptions import ( - ConnectionException as ConnectionException, - CredentialException as CredentialException, - HostKeysException as HostKeysException, -) -from pysftp.helpers import ( - WTCallbacks as WTCallbacks, - _PathCallback, - cd as cd, - known_hosts as known_hosts, - path_advance as path_advance, - path_retreat as path_retreat, - reparent as reparent, - st_mode_to_int as st_mode_to_int, - walktree as walktree, -) - -class CnOpts: - log: bool = ... - compression: bool = ... - ciphers: Sequence[str] | None = ... - hostkeys: paramiko.HostKeys = ... - def __init__(self, knownhosts: str | None = ...) -> None: ... - def get_hostkey(self, host: str) -> paramiko.PKey: ... - -_Callback = Callable[[int, int], Any] -_Path = Union[Text, bytes] - -class Connection: - def __init__( - self, - host: str, - username: str | None = ..., - private_key: str | paramiko.RSAKey | paramiko.AgentKey | None = ..., - password: str | None = ..., - port: int = ..., - private_key_pass: str | None = ..., - ciphers: Sequence[str] | None = ..., - log: bool = ..., - cnopts: CnOpts | None = ..., - default_path: _Path | None = ..., - ) -> None: ... - @property - def pwd(self) -> str: ... - def get( - self, remotepath: _Path, localpath: _Path | None = ..., callback: _Callback | None = ..., preserve_mtime: bool = ... - ) -> None: ... - def get_d(self, remotedir: _Path, localdir: _Path, preserve_mtime: bool = ...) -> None: ... - def get_r(self, remotedir: _Path, localdir: _Path, preserve_mtime: bool = ...) -> None: ... - def getfo(self, remotepath: _Path, flo: IO[bytes], callback: _Callback | None = ...) -> int: ... - def put( - self, - localpath: _Path, - remotepath: _Path | None = ..., - callback: _Callback | None = ..., - confirm: bool = ..., - preserve_mtime: bool = ..., - ) -> paramiko.SFTPAttributes: ... - def put_d(self, localpath: _Path, remotepath: _Path, confirm: bool = ..., preserve_mtime: bool = ...) -> None: ... - def put_r(self, localpath: _Path, remotepath: _Path, confirm: bool = ..., preserve_mtime: bool = ...) -> None: ... - def putfo( - self, - flo: IO[bytes], - remotepath: _Path | None = ..., - file_size: int = ..., - callback: _Callback | None = ..., - confirm: bool = ..., - ) -> paramiko.SFTPAttributes: ... - def execute(self, command: str) -> list[str]: ... - def cd(self, remotepath: _Path | None = ...) -> ContextManager[None]: ... # noqa: F811 - def chdir(self, remotepath: _Path) -> None: ... - def cwd(self, remotepath: _Path) -> None: ... - def chmod(self, remotepath: _Path, mode: int = ...) -> None: ... - def chown(self, remotepath: _Path, uid: int | None = ..., gid: int | None = ...) -> None: ... - def getcwd(self) -> str: ... - def listdir(self, remotepath: _Path = ...) -> list[str]: ... - def listdir_attr(self, remotepath: _Path = ...) -> list[paramiko.SFTPAttributes]: ... - def mkdir(self, remotepath: _Path, mode: int = ...) -> None: ... - def normalize(self, remotepath: _Path) -> str: ... - def isdir(self, remotepath: _Path) -> bool: ... - def isfile(self, remotepath: _Path) -> bool: ... - def makedirs(self, remotedir: _Path, mode: int = ...) -> None: ... - def readlink(self, remotelink: _Path) -> str: ... - def remove(self, remotefile: _Path) -> None: ... - def unlink(self, remotefile: _Path) -> None: ... - def rmdir(self, remotepath: _Path) -> None: ... - def rename(self, remote_src: _Path, remote_dest: _Path) -> None: ... - def stat(self, remotepath: _Path) -> paramiko.SFTPAttributes: ... - def lstat(self, remotepath: _Path) -> paramiko.SFTPAttributes: ... - def close(self) -> None: ... - def open(self, remote_file: _Path, mode: str = ..., bufsize: int = ...) -> paramiko.SFTPFile: ... - def exists(self, remotepath: _Path) -> bool: ... - def lexists(self, remotepath: _Path) -> bool: ... - def symlink(self, remote_src: _Path, remote_dest: _Path) -> None: ... - def truncate(self, remotepath: _Path, size: int) -> int: ... - def walktree( # noqa: F811 - self, remotepath: _Path, fcallback: _PathCallback, dcallback: _PathCallback, ucallback: _PathCallback, recurse: bool = ... - ) -> None: ... - @property - def sftp_client(self) -> paramiko.SFTPClient: ... - @property - def active_ciphers(self) -> tuple[str, str]: ... - @property - def active_compression(self) -> tuple[str, str]: ... - @property - def security_options(self) -> paramiko.SecurityOptions: ... - @property - def logfile(self) -> str | Literal[False]: ... - @property - def timeout(self) -> float | None: ... - @timeout.setter - def timeout(self, val: float | None) -> None: ... - @property - def remote_server_key(self) -> paramiko.PKey: ... - def __del__(self) -> None: ... - def __enter__(self) -> "Connection": ... - def __exit__( - self, etype: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> None: ... diff --git a/stubs/pysftp/pysftp/exceptions.pyi b/stubs/pysftp/pysftp/exceptions.pyi deleted file mode 100644 index 7416456a83d0..000000000000 --- a/stubs/pysftp/pysftp/exceptions.pyi +++ /dev/null @@ -1,9 +0,0 @@ -class ConnectionException(Exception): - message: str = ... - def __init__(self, host: str, port: int) -> None: ... - -class CredentialException(Exception): - message: str = ... - def __init__(self, message: str) -> None: ... - -class HostKeysException(Exception): ... diff --git a/stubs/pysftp/pysftp/helpers.pyi b/stubs/pysftp/pysftp/helpers.pyi deleted file mode 100644 index c1e0138d47f9..000000000000 --- a/stubs/pysftp/pysftp/helpers.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Callable, ContextManager, Iterator - -def known_hosts() -> str: ... -def st_mode_to_int(val: int) -> int: ... - -class WTCallbacks: - def __init__(self) -> None: ... - def file_cb(self, pathname: str) -> None: ... - def dir_cb(self, pathname: str) -> None: ... - def unk_cb(self, pathname: str) -> None: ... - @property - def flist(self) -> list[str]: ... - @flist.setter - def flist(self, val: list[str]) -> None: ... - @property - def dlist(self) -> list[str]: ... - @dlist.setter - def dlist(self, val: list[str]) -> None: ... - @property - def ulist(self) -> list[str]: ... - @ulist.setter - def ulist(self, val: list[str]) -> None: ... - -def path_advance(thepath: str, sep: str = ...) -> Iterator[str]: ... -def path_retreat(thepath: str, sep: str = ...) -> Iterator[str]: ... -def reparent(newparent: str, oldpath: str) -> str: ... - -_PathCallback = Callable[[str], None] - -def walktree( - localpath: str, fcallback: _PathCallback, dcallback: _PathCallback, ucallback: _PathCallback, recurse: bool = ... -) -> None: ... -def cd(localpath: str | None = ...) -> ContextManager[None]: ... diff --git a/stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt b/stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7d0609ba5797 --- /dev/null +++ b/stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt @@ -0,0 +1,13 @@ +# Part of the pytest API, which is internal: +pytest_lazyfixture.pytest_.* + +# Internal undocumented API: +pytest_lazyfixture.fillfixtures +pytest_lazyfixture.normalize_call +pytest_lazyfixture.normalize_metafunc_calls +pytest_lazyfixture.sorted_by_dependency +pytest_lazyfixture.copy_metafunc + +# Compat: +pytest_lazyfixture.PY3 +pytest_lazyfixture.string_type diff --git a/stubs/pytest-lazy-fixture/METADATA.toml b/stubs/pytest-lazy-fixture/METADATA.toml index 03031f1e9559..60f7b81673f3 100644 --- a/stubs/pytest-lazy-fixture/METADATA.toml +++ b/stubs/pytest-lazy-fixture/METADATA.toml @@ -1 +1,2 @@ version = "0.6.*" +upstream-repository = "https://github.com/tvorog/pytest-lazy-fixture" diff --git a/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi b/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi index b5cc42079cb1..3f9f07febe87 100644 --- a/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi +++ b/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi @@ -1,4 +1,6 @@ -from typing import Any, Iterable, overload +from collections.abc import Iterable +from typing import Any, overload +from typing_extensions import TypeIs class LazyFixture: name: str @@ -9,6 +11,5 @@ class LazyFixture: def lazy_fixture(names: str) -> LazyFixture: ... @overload def lazy_fixture(names: Iterable[str]) -> list[LazyFixture] | Any: ... -def is_lazy_fixture(val: Any) -> bool: ... -def pytest_configure() -> None: ... -def __getattr__(name: str) -> Any: ... # incomplete + +def is_lazy_fixture(val: object) -> TypeIs[LazyFixture]: ... diff --git a/stubs/python-crontab/@tests/stubtest_allowlist.txt b/stubs/python-crontab/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..51b8a2b6fb81 --- /dev/null +++ b/stubs/python-crontab/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +# Runtime only-hack that doesn't affect typing: +crontabs.CronTabs.__new__ +# stub does not have *args argument "args", but function doesn't actually accept positional args +crontab.CronTab.remove_all +crontab.OrderedVariableList.__init__ diff --git a/stubs/python-crontab/METADATA.toml b/stubs/python-crontab/METADATA.toml new file mode 100644 index 000000000000..292eef4021f2 --- /dev/null +++ b/stubs/python-crontab/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.4.*" +upstream-repository = "https://gitlab.com/doctormo/python-crontab" +dependencies = ["types-croniter"] diff --git a/stubs/python-crontab/cronlog.pyi b/stubs/python-crontab/cronlog.pyi new file mode 100644 index 000000000000..2d5d5b8ac5aa --- /dev/null +++ b/stubs/python-crontab/cronlog.pyi @@ -0,0 +1,36 @@ +from _typeshed import StrOrBytesPath +from codecs import StreamReaderWriter +from collections.abc import Generator, Iterator +from datetime import datetime +from types import TracebackType +from typing_extensions import Self + +MATCHER: str + +class LogReader: + filename: StrOrBytesPath + mass: int + size: int + read: int + pipe: StreamReaderWriter | None + def __init__(self, filename: StrOrBytesPath, mass: int = 4096) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, error_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def readlines(self, until: int = 0) -> Generator[tuple[int, str]]: ... + +def cron_date_to_datetime(cron_str: str) -> datetime: ... + +class CronLog(LogReader): + user: str | None + def __init__(self, filename: StrOrBytesPath = "/var/log/syslog", user: str | None = None) -> None: ... + def for_program(self, command: str) -> ProgramLog: ... + def __iter__(self) -> dict[str, str | None]: ... # type: ignore[override] + +class ProgramLog: + log: CronLog + command: str + def __init__(self, log: CronLog, command: str) -> None: ... + def __iter__(self) -> dict[str, str | None]: ... diff --git a/stubs/python-crontab/crontab.pyi b/stubs/python-crontab/crontab.pyi new file mode 100644 index 000000000000..5e22b4dea803 --- /dev/null +++ b/stubs/python-crontab/crontab.pyi @@ -0,0 +1,334 @@ +import re +import subprocess +from _typeshed import StrPath +from builtins import range as _range +from collections import OrderedDict +from collections.abc import Callable, Generator, Iterable, Iterator +from datetime import datetime +from logging import Logger +from types import TracebackType +from typing import Any, Final, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from croniter.croniter import croniter +from cronlog import CronLog + +_User: TypeAlias = str | bool | None +_K = TypeVar("_K") +_V = TypeVar("_V") + +# cron_descriptor.Options class +@type_check_only +class _Options(Protocol): + casing_type: Literal[1, 2, 3] + verbose: bool + day_of_week_start_index_zero: bool + use_24hour_time_format: bool + locale_location: StrPath | None + locale_code: str | None + def __init__(self) -> None: ... + +__pkgname__: Final[str] +__version__: Final[str] +ITEMREX: Final[re.Pattern[str]] +SPECREX: Final[re.Pattern[str]] +DEVNULL: Final[str] +WEEK_ENUM: Final[list[str]] +MONTH_ENUM: Final[list[str | None]] +SPECIALS_CONVERSION: bool | None +SPECIALS: Final[dict[str, str]] +SPECIAL_IGNORE: Final[list[str]] +S_INFO: Final[list[dict[str, str | int | list[str] | list[str | None]]]] +WINOS: Final[bool] +POSIX: Final[bool] +SYSTEMV: Final[bool] +ZERO_PAD: Final[bool] +LOG: Logger +CRON_COMMAND: Final[str] +SHELL: Final[str] +current_user: Callable[[], str | None] + +class Process: + env: subprocess._ENV | None + args: tuple[str, ...] + has_run: bool + stdout: str | None + stderr: str | None + returncode: int | None + # `posix` and `env` are known special kwargs: + def __init__(self, cmd: str, *args: str, posix: bool = ..., env: subprocess._ENV | None = None, **flags: object) -> None: ... + def run(self) -> Self: ... + def __int__(self) -> int: ... # technically, it can return `None` before `run` is called + def __eq__(self, other: object) -> bool: ... + +class CronTab: + lines: list[str | CronItem] | None + crons: list[CronItem] | None + filen: str | None + cron_command: str + env: OrderedVariableList[str, str] | None + root: bool + intab: str | None + tabfile: str | None + def __init__( + self, user: _User = None, tab: str | None = None, tabfile: str | None = None, log: CronLog | str | None = None + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + @property + def log(self) -> CronLog: ... + @property + def user(self) -> _User: ... + @property + def user_opt(self) -> dict[str, str]: ... + def read(self, filename: str | None = None) -> None: ... + def append( + self, + item: CronItem, + line: str = "", + read: bool = False, + before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = None, + ) -> None: ... + def write(self, filename: str | None = None, user: _User = None, errors: bool = False) -> None: ... + def write_to_user(self, user: bool | str = True) -> None: ... + # Usually `kwargs` are just `now: datetime | None`, but technically this can + # work for `CronItem` subclasses, which might define other kwargs. + def run_pending(self, *, now: datetime | None = None, **kwargs: Any) -> Iterator[str]: ... + def run_scheduler(self, timeout: int = -1, cadence: int | float = 60, warp: bool = False) -> Iterator[str]: ... + async def run_scheduler_async(self, timeout: int = -1, cadence: int | float = 60, warp: bool = False) -> Iterator[str]: ... + def render(self, errors: bool = False) -> str: ... + def new( + self, + command: str = "", + comment: str = "", + user: str | None = None, + pre_comment: bool = False, + before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = None, + ) -> CronItem: ... + def find_command(self, command: str | re.Pattern[str]) -> Iterator[CronItem]: ... + def find_comment(self, comment: str | re.Pattern[str]) -> Iterator[CronItem]: ... + def find_time(self, *args: Any) -> Iterator[CronItem]: ... + @property + def commands(self) -> Iterator[str]: ... + @property + def comments(self) -> Iterator[str]: ... + # You cannot actually pass `*args`, it will raise an exception, + # also known kwargs are added: + def remove_all( + self, *, command: str | re.Pattern[str] = ..., comment: str | re.Pattern[str] = ..., time: Any = ..., **kwargs: object + ) -> int: ... + def remove(self, *items: CronItem | Iterable[CronItem]) -> int: ... + def __iter__(self) -> Iterator[CronItem]: ... + def __getitem__(self, i: SupportsIndex) -> CronItem: ... + def __len__(self) -> int: ... + +class CronItem: + cron: CronTab | None + user: _User + valid: bool + enabled: bool + special: bool + comment: str + command: str | None + last_run: datetime | None + env: OrderedVariableList[str, str] + pre_comment: bool + marker: str | None + stdin: str | None + slices: CronSlices + def __init__(self, command: str = "", comment: str = "", user: _User = None, pre_comment: bool = False) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + @classmethod + def from_line(cls, line: str, user: str | None = None, cron: CronTab | None = None) -> Self: ... + def delete(self) -> None: ... + def set_command(self, cmd: str, parse_stdin: bool = False) -> None: ... + def set_comment(self, cmt: str, pre_comment: bool = False) -> None: ... + def parse(self, line: str) -> None: ... + def enable(self, enabled: bool = True) -> bool: ... + def is_enabled(self) -> bool: ... + def is_valid(self) -> bool: ... + def render(self) -> str: ... + def every_reboot(self) -> None: ... + def every(self, unit: int = 1) -> Every: ... + def setall(self, *args: Any) -> None: ... + def clear(self) -> None: ... + def frequency(self, year: int | None = None) -> int: ... + def frequency_per_year(self, year: int | None = None) -> int: ... + def frequency_per_day(self) -> int: ... + def frequency_per_hour(self) -> int: ... + def frequency_at_year(self, year: int | None = None) -> int: ... + + @overload + def frequency_at_month(self, year: int, month: int) -> int: ... + @overload + def frequency_at_month(self, year: None = None, month: None = None) -> int: ... + + @overload + def frequency_at_day(self, year: int, month: int, day: int) -> int: ... + @overload + def frequency_at_day(self, year: None = None, month: None = None, day: None = None) -> int: ... + + @overload + def frequency_at_hour(self, year: int, month: int, day: int, hour: int) -> int: ... + @overload + def frequency_at_hour(self, year: None = None, month: None = None, day: None = None, hour: None = None) -> int: ... + + def run_pending(self, now: datetime | None = None) -> int | str: ... + def run(self) -> str: ... + def schedule(self, date_from: datetime | None = None) -> croniter: ... + def description( + self, + *, + options: _Options | None = None, + casing_type: Literal[1, 2, 3] = 2, + verbose: bool = False, + day_of_week_start_index_zero: bool = True, + use_24hour_time_format: bool = ..., + locale_location: StrPath | None = None, + locale_code: str | None = ..., + ) -> str | None: ... + @property + def log(self) -> CronLog: ... + @property + def minute(self) -> int | str: ... + @property + def minutes(self) -> int | str: ... + @property + def hour(self) -> int | str: ... + @property + def hours(self) -> int | str: ... + @property + def day(self) -> int | str: ... + @property + def dom(self) -> int | str: ... + @property + def month(self) -> int | str: ... + @property + def months(self) -> int | str: ... + @property + def dow(self) -> int | str: ... + def __len__(self) -> int: ... + def __getitem__(self, key: int | str) -> int | str: ... + def __lt__(self, value: object) -> bool: ... + def __gt__(self, value: object) -> bool: ... + +class Every: + slices: CronSlices + unit: int + # TODO: add generated attributes + def __init__(self, item: CronSlices, units: int) -> None: ... + def set_attr(self, target: int) -> Callable[[], None]: ... + def year(self) -> None: ... + +class CronSlices(list[CronSlice]): + special: bool | None + def __init__(self, *args: Any) -> None: ... + def is_self_valid(self, *args: Any) -> bool: ... + @classmethod + def is_valid(cls, *args: Any) -> bool: ... + def setall(self, *slices: str) -> None: ... + def clean_render(self) -> str: ... + def render(self) -> str: ... + def clear(self) -> None: ... + def frequency(self, year: int | None = None) -> int: ... + def frequency_per_year(self, year: int | None = None) -> int: ... + def frequency_per_day(self) -> int: ... + def frequency_per_hour(self) -> int: ... + def frequency_at_year(self, year: int | None = None) -> int: ... + + @overload + def frequency_at_month(self, year: int, month: int) -> int: ... + @overload + def frequency_at_month(self, year: None = None, month: None = None) -> int: ... + + @overload + def frequency_at_day(self, year: int, month: int, day: int) -> int: ... + @overload + def frequency_at_day(self, year: None = None, month: None = None, day: None = None) -> int: ... + + @overload + def frequency_at_hour(self, year: int, month: int, day: int, hour: int) -> int: ... + @overload + def frequency_at_hour(self, year: None = None, month: None = None, day: None = None, hour: None = None) -> int: ... + + def __eq__(self, arg: object) -> bool: ... + +class SundayError(KeyError): ... + +class Also: + obj: CronSlice + def __init__(self, obj: CronSlice) -> None: ... + # These method actually use `*args`, but pass them to `CronSlice` methods, + # this is why they are typed as `Any`. + def every(self, *a: Any) -> _Part: ... + def on(self, *a: Any) -> list[_Part]: ... + def during(self, *a: Any) -> _Part: ... + +_Part: TypeAlias = int | CronValue | CronRange + +class CronSlice: + min: int | None + max: int | None + name: str | None + enum: list[str | None] | None + parts: list[_Part] + def __init__(self, info: int | dict[str, Any], value: str | None = None) -> None: ... + def __hash__(self) -> int: ... + def parse(self, value: str | None) -> None: ... + def render(self, resolve: bool = False) -> str: ... + def __eq__(self, arg: object) -> bool: ... + def every(self, n_value: int, also: bool = False, random: bool = False) -> _Part: ... + # The only known kwarg, others are unused, + # `*args`` are passed to `parse_value`, so they are `Any` + def on(self, *n_value: Any, also: bool = False) -> list[_Part]: ... + def during(self, vfrom: int | str, vto: int | str, also: bool = False, random: bool = False) -> _Part: ... + def random_during(self, vfrom: int | str, vto: int | str) -> _Part: ... + @property + def also(self) -> Also: ... + def clear(self) -> None: ... + def get_range(self, *vrange: int | str | CronValue, random: bool = False) -> list[int | CronRange]: ... + def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... + def parse_value(self, val: str, sunday: int | None = None) -> int | CronValue: ... + def test_value(self, value: str, sunday: int | None = None) -> str: ... + +def get_cronvalue(value: int, enums: list[str]) -> int | CronValue: ... + +class CronValue: + text: str + value: int + def __init__(self, value: str, enums: list[str]) -> None: ... + def __lt__(self, value: object) -> bool: ... + def __int__(self) -> int: ... + +class CronRange: + dangling: int | None + slice: str + cron: CronTab | None + seq: int + is_random_range: bool + def __init__(self, vslice: str, *vrange: int | str | CronValue, random: bool = False) -> None: ... + # Are not set in `__init__`: + vfrom: int | CronValue + vto: int | CronValue + def parse(self, value: str) -> None: ... + def all(self) -> None: ... + def render(self, resolve: bool = False) -> str: ... + def range(self) -> _range: ... + def every(self, value: int | str) -> None: ... + def __lt__(self, value: object) -> bool: ... + def __gt__(self, value: object) -> bool: ... + def __int__(self) -> int: ... + +class OrderedVariableList(OrderedDict[_K, _V]): + job: CronItem | None + # You cannot actually pass `*args`, it will raise an exception, + # also known kwargs are added: + def __init__(self, *, job: CronItem | None = None, **kw: _V) -> None: ... + @property + def previous(self) -> Self | None: ... + def all(self) -> Self: ... + def __getitem__(self, key: _K) -> _V: ... diff --git a/stubs/python-crontab/crontabs.pyi b/stubs/python-crontab/crontabs.pyi new file mode 100644 index 000000000000..fcdfb77d8e42 --- /dev/null +++ b/stubs/python-crontab/crontabs.pyi @@ -0,0 +1,24 @@ +from typing import Any + +from crontab import CronTab + +class UserSpool(list[CronTab]): + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... + def listdir(self, loc: str) -> list[str]: ... + def get_owner(self, path: str) -> str: ... + def generate(self, loc: str, username: str) -> CronTab: ... + +class SystemTab(list[CronTab]): + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... + +class AnaCronTab(list[CronTab]): + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... + def add(self, loc: str, item: str, anajob: CronTab) -> CronTab: ... + +KNOWN_LOCATIONS: list[tuple[UserSpool | SystemTab | AnaCronTab, str]] + +class CronTabs(list[UserSpool | SystemTab | AnaCronTab]): + def __init__(self) -> None: ... + def add(self, cls: type[UserSpool | SystemTab | AnaCronTab], *args: Any) -> None: ... + @property + def all(self) -> CronTab: ... diff --git a/stubs/python-dateutil/@tests/stubtest_allowlist.txt b/stubs/python-dateutil/@tests/stubtest_allowlist.txt index 28312e9628ed..8484bd3fe67d 100644 --- a/stubs/python-dateutil/@tests/stubtest_allowlist.txt +++ b/stubs/python-dateutil/@tests/stubtest_allowlist.txt @@ -1,7 +1,7 @@ -dateutil.parser._tzparser.__init__ -dateutil.parser.parserinfo.convertyear dateutil.rrule.weekday.__init__ dateutil.tz.tz.tzoffset.instance dateutil.tz.tz.tzstr.instance -dateutil.tz.tzoffset.instance -dateutil.tz.tzstr.instance + +# Metaclass differs: +dateutil.tz.tz.tzoffset +dateutil.tz.tz.tzutc diff --git a/stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt b/stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..b667fc149971 --- /dev/null +++ b/stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +# Cannot import these Windows packages at stubtest runtime: +dateutil.tzwin +dateutil.tz.win diff --git a/stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt b/stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..b667fc149971 --- /dev/null +++ b/stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +# Cannot import these Windows packages at stubtest runtime: +dateutil.tzwin +dateutil.tz.win diff --git a/stubs/python-dateutil/@tests/test_cases/check_inheritance.py b/stubs/python-dateutil/@tests/test_cases/check_inheritance.py new file mode 100644 index 000000000000..3ab5a78cdda2 --- /dev/null +++ b/stubs/python-dateutil/@tests/test_cases/check_inheritance.py @@ -0,0 +1,21 @@ +from datetime import date, datetime +from typing_extensions import assert_type + +from dateutil.relativedelta import relativedelta + + +class MyDateTime(datetime): + pass + + +d = MyDateTime.now() +x = d - relativedelta(days=1) +assert_type(x, MyDateTime) + +d3 = datetime.today() +x3 = d3 - relativedelta(days=1) +assert_type(x3, datetime) + +d2 = date.today() +x2 = d2 - relativedelta(days=1) +assert_type(x2, date) diff --git a/stubs/python-dateutil/@tests/test_cases/check_relativedelta.py b/stubs/python-dateutil/@tests/test_cases/check_relativedelta.py new file mode 100644 index 000000000000..8e83759df123 --- /dev/null +++ b/stubs/python-dateutil/@tests/test_cases/check_relativedelta.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from dateutil import relativedelta + + +# An illustrative example for why we re-export dateutil._common.weekday from dateutil.relativedelta in the stub +class Calendar: + def __init__(self, week_start: relativedelta.weekday = relativedelta.MO) -> None: + self.week_start = week_start diff --git a/stubs/python-dateutil/@tests/test_cases/check_rrule.py b/stubs/python-dateutil/@tests/test_cases/check_rrule.py new file mode 100644 index 000000000000..db0810b38cdb --- /dev/null +++ b/stubs/python-dateutil/@tests/test_cases/check_rrule.py @@ -0,0 +1,13 @@ +from typing import Union +from typing_extensions import assert_type + +from dateutil.rrule import rrule, rruleset, rrulestr + +rs1 = rrulestr("", forceset=True) +assert_type(rs1, rruleset) + +rs2 = rrulestr("", compatible=True) +assert_type(rs2, rruleset) + +rs3 = rrulestr("") +assert_type(rs3, Union[rrule, rruleset]) diff --git a/stubs/python-dateutil/METADATA.toml b/stubs/python-dateutil/METADATA.toml index c00bfdcaeadc..995b1aa6aa82 100644 --- a/stubs/python-dateutil/METADATA.toml +++ b/stubs/python-dateutil/METADATA.toml @@ -1,3 +1,2 @@ -version = "2.8.*" -python2 = true -requires = [] +version = "2.9.*" +upstream-repository = "https://github.com/dateutil/dateutil" diff --git a/stubs/python-dateutil/dateutil/__init__.pyi b/stubs/python-dateutil/dateutil/__init__.pyi index e69de29bb2d1..9fb5d4b1fe59 100644 --- a/stubs/python-dateutil/dateutil/__init__.pyi +++ b/stubs/python-dateutil/dateutil/__init__.pyi @@ -0,0 +1,5 @@ +from dateutil import easter, parser, relativedelta, rrule, tz, utils, zoneinfo + +__all__ = ["easter", "parser", "relativedelta", "rrule", "tz", "utils", "zoneinfo"] + +def __dir__() -> list[str]: ... diff --git a/stubs/python-dateutil/dateutil/_common.pyi b/stubs/python-dateutil/dateutil/_common.pyi index a437f85035a3..af892a5d7a0d 100644 --- a/stubs/python-dateutil/dateutil/_common.pyi +++ b/stubs/python-dateutil/dateutil/_common.pyi @@ -1,12 +1,10 @@ -from typing import TypeVar +from typing_extensions import Self -_T = TypeVar("_T") - -class weekday(object): - def __init__(self, weekday: int, n: int | None = ...) -> None: ... - def __call__(self: _T, n: int) -> _T: ... +class weekday: + __slots__ = ["weekday", "n"] + def __init__(self, weekday: int, n: int | None = None) -> None: ... + def __call__(self, n: int) -> Self: ... def __eq__(self, other: object) -> bool: ... - def __repr__(self) -> str: ... def __hash__(self) -> int: ... weekday: int n: int diff --git a/stubs/python-dateutil/dateutil/_version.pyi b/stubs/python-dateutil/dateutil/_version.pyi new file mode 100644 index 000000000000..840633ef6e91 --- /dev/null +++ b/stubs/python-dateutil/dateutil/_version.pyi @@ -0,0 +1,6 @@ +from typing import Final + +__version__: Final[str] +version: Final[str] +__version_tuple__: Final[tuple[int, int, int]] +version_tuple: Final[tuple[int, int, int]] diff --git a/stubs/python-dateutil/dateutil/easter.pyi b/stubs/python-dateutil/dateutil/easter.pyi index 33e366d476ae..695faa222541 100644 --- a/stubs/python-dateutil/dateutil/easter.pyi +++ b/stubs/python-dateutil/dateutil/easter.pyi @@ -1,8 +1,10 @@ from datetime import date -from typing_extensions import Literal +from typing import Final, Literal -EASTER_JULIAN: Literal[1] -EASTER_ORTHODOX: Literal[2] -EASTER_WESTERN: Literal[3] +__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] -def easter(year: int, method: Literal[1, 2, 3] = ...) -> date: ... +EASTER_JULIAN: Final = 1 +EASTER_ORTHODOX: Final = 2 +EASTER_WESTERN: Final = 3 + +def easter(year: int, method: Literal[1, 2, 3] = 3) -> date: ... diff --git a/stubs/python-dateutil/dateutil/parser/__init__.pyi b/stubs/python-dateutil/dateutil/parser/__init__.pyi index 7782cc0074b4..1041c050d7a7 100644 --- a/stubs/python-dateutil/dateutil/parser/__init__.pyi +++ b/stubs/python-dateutil/dateutil/parser/__init__.pyi @@ -1,48 +1,12 @@ -from datetime import datetime, tzinfo -from typing import IO, Any, Mapping, Text, Union - +from ._parser import ( + DEFAULTPARSER as DEFAULTPARSER, + DEFAULTTZPARSER as DEFAULTTZPARSER, + ParserError as ParserError, + UnknownTimezoneWarning as UnknownTimezoneWarning, + parse as parse, + parser as parser, + parserinfo as parserinfo, +) from .isoparser import isoparse as isoparse, isoparser as isoparser -_FileOrStr = Union[bytes, Text, IO[str], IO[Any]] - -class parserinfo(object): - JUMP: list[str] - WEEKDAYS: list[tuple[str, ...]] - MONTHS: list[tuple[str, ...]] - HMS: list[tuple[str, str, str]] - AMPM: list[tuple[str, str]] - UTCZONE: list[str] - PERTAIN: list[str] - TZOFFSET: dict[str, int] - def __init__(self, dayfirst: bool = ..., yearfirst: bool = ...) -> None: ... - def jump(self, name: Text) -> bool: ... - def weekday(self, name: Text) -> int | None: ... - def month(self, name: Text) -> int | None: ... - def hms(self, name: Text) -> int | None: ... - def ampm(self, name: Text) -> int | None: ... - def pertain(self, name: Text) -> bool: ... - def utczone(self, name: Text) -> bool: ... - def tzoffset(self, name: Text) -> int | None: ... - def convertyear(self, year: int) -> int: ... - def validate(self, res: datetime) -> bool: ... - -class parser(object): - def __init__(self, info: parserinfo | None = ...) -> None: ... - def parse( - self, - timestr: _FileOrStr, - default: datetime | None = ..., - ignoretz: bool = ..., - tzinfos: Mapping[Text, tzinfo] | None = ..., - **kwargs: Any, - ) -> datetime: ... - -DEFAULTPARSER: parser - -def parse(timestr: _FileOrStr, parserinfo: parserinfo | None = ..., **kwargs: Any) -> datetime: ... - -class _tzparser: ... - -DEFAULTTZPARSER: _tzparser - -class ParserError(ValueError): ... +__all__ = ["parse", "parser", "parserinfo", "isoparse", "isoparser", "ParserError", "UnknownTimezoneWarning"] diff --git a/stubs/python-dateutil/dateutil/parser/_parser.pyi b/stubs/python-dateutil/dateutil/parser/_parser.pyi new file mode 100644 index 000000000000..700b9fad63c1 --- /dev/null +++ b/stubs/python-dateutil/dateutil/parser/_parser.pyi @@ -0,0 +1,164 @@ +import re +from _typeshed import SupportsRead +from collections.abc import Callable, Mapping +from datetime import _TzInfo, datetime +from io import StringIO +from typing import IO, Any, Literal, TypeAlias, overload +from typing_extensions import Self + +_FileOrStr: TypeAlias = bytes | str | IO[str] | IO[Any] +_TzData: TypeAlias = _TzInfo | int | str | None +_TzInfos: TypeAlias = Mapping[str, _TzData] | Callable[[str, int], _TzData] + +__all__ = ["parse", "parserinfo", "ParserError"] + +class _timelex: + _split_decimal: re.Pattern[str] + instream: StringIO | SupportsRead[str] + charstack: list[str] + tokenstack: list[str] + eof: bool + def __init__(self, instream: str | bytes | bytearray | SupportsRead[str]) -> None: ... + def get_token(self) -> str | None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> str: ... + def next(self) -> str: ... + @classmethod + def split(cls, s: str) -> list[str]: ... + @classmethod + def isword(cls, nextchar: str) -> bool: ... + @classmethod + def isnum(cls, nextchar: str) -> bool: ... + @classmethod + def isspace(cls, nextchar: str) -> bool: ... + +class _resultbase: + def __init__(self) -> None: ... + def _repr(self, classname: str) -> str: ... + def __len__(self) -> int: ... + +class parserinfo: + JUMP: list[str] + WEEKDAYS: list[tuple[str, str]] + MONTHS: list[tuple[str, str] | tuple[str, str, str]] + HMS: list[tuple[str, str, str]] + AMPM: list[tuple[str, str]] + UTCZONE: list[str] + PERTAIN: list[str] + TZOFFSET: dict[str, int] + def __init__(self, dayfirst: bool = False, yearfirst: bool = False) -> None: ... + def jump(self, name: str) -> bool: ... + def weekday(self, name: str) -> int | None: ... + def month(self, name: str) -> int | None: ... + def hms(self, name: str) -> int | None: ... + def ampm(self, name: str) -> int | None: ... + def pertain(self, name: str) -> bool: ... + def utczone(self, name: str) -> bool: ... + def tzoffset(self, name: str) -> int | None: ... + def convertyear(self, year: int, century_specified: bool = False) -> int: ... + def validate(self, res: datetime) -> bool: ... + +class _ymd(list[int]): + century_specified: bool + dstridx: int | None + mstridx: int | None + ystridx: int | None + @property + def has_year(self) -> bool: ... + @property + def has_month(self) -> bool: ... + @property + def has_day(self) -> bool: ... + def could_be_day(self, value: int) -> bool: ... + def append(self, val: str | int, label: str | None = None) -> None: ... + def _resolve_from_stridxs(self, strids: dict[str, int]) -> tuple[int, int, int]: ... + def resolve_ymd(self, yearfirst: bool | None, dayfirst: bool | None) -> tuple[int, int, int]: ... + +class parser: + info: parserinfo + def __init__(self, info: parserinfo | None = None) -> None: ... + + @overload + def parse( + self, + timestr: _FileOrStr, + default: datetime | None = None, + ignoretz: bool = False, + tzinfos: _TzInfos | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[False] = False, + ) -> datetime: ... + @overload + def parse( + self, + timestr: _FileOrStr, + default: datetime | None = None, + ignoretz: bool = False, + tzinfos: _TzInfos | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[True], + ) -> tuple[datetime, tuple[str, ...]]: ... + +DEFAULTPARSER: parser + +@overload +def parse( + timestr: _FileOrStr, + parserinfo: parserinfo | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + ignoretz: bool = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[False] = False, + default: datetime | None = ..., + tzinfos: _TzInfos | None = ..., +) -> datetime: ... +@overload +def parse( + timestr: _FileOrStr, + parserinfo: parserinfo | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + ignoretz: bool = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[True], + default: datetime | None = ..., + tzinfos: _TzInfos | None = ..., +) -> tuple[datetime, tuple[str, ...]]: ... + +class _tzparser: + class _result(_resultbase): + __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] + stdabbr: str | None + stdoffset: int | None + dstabbr: str | None + dstoffset: int | None + start: _attr # pyrefly: ignore [unknown-name] + end: _attr # pyrefly: ignore [unknown-name] + + class _attr(_resultbase): + __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] + month: int | None + week: int | None + weekday: int | None + yday: int | None + jyday: int | None + day: int | None + time: int | None + + def __init__(self) -> None: ... + + def parse(self, tzstr: str | re.Pattern[str]) -> _result | None: ... + +DEFAULTTZPARSER: _tzparser + +class ParserError(ValueError): ... +class UnknownTimezoneWarning(RuntimeWarning): ... diff --git a/stubs/python-dateutil/dateutil/parser/isoparser.pyi b/stubs/python-dateutil/dateutil/parser/isoparser.pyi index ed24582d43c4..bf589f592296 100644 --- a/stubs/python-dateutil/dateutil/parser/isoparser.pyi +++ b/stubs/python-dateutil/dateutil/parser/isoparser.pyi @@ -1,15 +1,17 @@ from _typeshed import SupportsRead from datetime import date, datetime, time, tzinfo -from typing import Text, Union +from typing import TypeAlias -_Readable = SupportsRead[Union[Text, bytes]] -_TakesAscii = Union[Text, bytes, _Readable] +_Readable: TypeAlias = SupportsRead[str | bytes] +_TakesAscii: TypeAlias = str | bytes | _Readable + +__all__ = ["isoparse", "isoparser"] class isoparser: - def __init__(self, sep: Text | bytes | None = ...): ... + def __init__(self, sep: str | bytes | None = None) -> None: ... def isoparse(self, dt_str: _TakesAscii) -> datetime: ... def parse_isodate(self, datestr: _TakesAscii) -> date: ... def parse_isotime(self, timestr: _TakesAscii) -> time: ... - def parse_tzstr(self, tzstr: _TakesAscii, zero_as_utc: bool = ...) -> tzinfo: ... + def parse_tzstr(self, tzstr: _TakesAscii, zero_as_utc: bool = True) -> tzinfo: ... def isoparse(dt_str: _TakesAscii) -> datetime: ... diff --git a/stubs/python-dateutil/dateutil/relativedelta.pyi b/stubs/python-dateutil/dateutil/relativedelta.pyi index ec2adea537fa..e8f2528a9ac6 100644 --- a/stubs/python-dateutil/dateutil/relativedelta.pyi +++ b/stubs/python-dateutil/dateutil/relativedelta.pyi @@ -1,12 +1,13 @@ -from datetime import date, datetime, timedelta -from typing import SupportsFloat, TypeVar, overload +from datetime import date, timedelta +from typing import SupportsFloat, TypeAlias, TypeVar, overload +from typing_extensions import Self -from ._common import weekday +# See #9817 for why we reexport this here +from ._common import weekday as weekday -_SelfT = TypeVar("_SelfT", bound=relativedelta) -_DateT = TypeVar("_DateT", date, datetime) +_DateT = TypeVar("_DateT", bound=date) # Work around attribute and type having the same name. -_weekday = weekday +_Weekday: TypeAlias = weekday MO: weekday TU: weekday @@ -16,7 +17,9 @@ FR: weekday SA: weekday SU: weekday -class relativedelta(object): +__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] + +class relativedelta: years: int months: int days: int @@ -27,7 +30,7 @@ class relativedelta(object): microseconds: int year: int | None month: int | None - weekday: _weekday | None + weekday: _Weekday | None day: int | None hour: int | None minute: int | None @@ -35,63 +38,60 @@ class relativedelta(object): microsecond: int | None def __init__( self, - dt1: date | None = ..., - dt2: date | None = ..., - years: int | None = ..., - months: int | None = ..., - days: int | None = ..., - leapdays: int | None = ..., - weeks: int | None = ..., - hours: int | None = ..., - minutes: int | None = ..., - seconds: int | None = ..., - microseconds: int | None = ..., - year: int | None = ..., - month: int | None = ..., - day: int | None = ..., - weekday: int | _weekday | None = ..., - yearday: int | None = ..., - nlyearday: int | None = ..., - hour: int | None = ..., - minute: int | None = ..., - second: int | None = ..., - microsecond: int | None = ..., + dt1: date | None = None, + dt2: date | None = None, + years: int = 0, + months: int = 0, + days: int = 0, + leapdays: int = 0, + weeks: int = 0, + hours: int = 0, + minutes: int = 0, + seconds: int = 0, + microseconds: int = 0, + year: int | None = None, + month: int | None = None, + day: int | None = None, + weekday: int | _Weekday | None = None, + yearday: int | None = None, + nlyearday: int | None = None, + hour: int | None = None, + minute: int | None = None, + second: int | None = None, + microsecond: int | None = None, ) -> None: ... + @property def weeks(self) -> int: ... @weeks.setter def weeks(self, value: int) -> None: ... - def normalized(self: _SelfT) -> _SelfT: ... - # TODO: use Union when mypy will handle it properly in overloaded operator - # methods (#2129, #1442, #1264 in mypy) - @overload - def __add__(self: _SelfT, other: relativedelta) -> _SelfT: ... + + def normalized(self) -> Self: ... + @overload - def __add__(self: _SelfT, other: timedelta) -> _SelfT: ... + def __add__(self, other: timedelta | relativedelta) -> Self: ... @overload def __add__(self, other: _DateT) -> _DateT: ... + @overload - def __radd__(self: _SelfT, other: relativedelta) -> _SelfT: ... - @overload - def __radd__(self: _SelfT, other: timedelta) -> _SelfT: ... + def __radd__(self, other: timedelta | relativedelta) -> Self: ... @overload def __radd__(self, other: _DateT) -> _DateT: ... + @overload - def __rsub__(self: _SelfT, other: relativedelta) -> _SelfT: ... - @overload - def __rsub__(self: _SelfT, other: timedelta) -> _SelfT: ... + def __rsub__(self, other: timedelta | relativedelta) -> Self: ... @overload def __rsub__(self, other: _DateT) -> _DateT: ... - def __sub__(self: _SelfT, other: relativedelta) -> _SelfT: ... - def __neg__(self: _SelfT) -> _SelfT: ... + + def __sub__(self, other: relativedelta) -> Self: ... + def __neg__(self) -> Self: ... def __bool__(self) -> bool: ... def __nonzero__(self) -> bool: ... - def __mul__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... - def __rmul__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... + def __mul__(self, other: SupportsFloat) -> Self: ... + def __rmul__(self, other: SupportsFloat) -> Self: ... def __eq__(self, other: object) -> bool: ... def __ne__(self, other: object) -> bool: ... - def __div__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... - def __truediv__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... - def __repr__(self) -> str: ... - def __abs__(self: _SelfT) -> _SelfT: ... + def __div__(self, other: SupportsFloat) -> Self: ... + def __truediv__(self, other: SupportsFloat) -> Self: ... + def __abs__(self) -> Self: ... def __hash__(self) -> int: ... diff --git a/stubs/python-dateutil/dateutil/rrule.pyi b/stubs/python-dateutil/dateutil/rrule.pyi index bc95dcf2aa6e..64cf1ef8e1cb 100644 --- a/stubs/python-dateutil/dateutil/rrule.pyi +++ b/stubs/python-dateutil/dateutil/rrule.pyi @@ -1,18 +1,53 @@ import datetime -from typing import Any, Iterable +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Self + +from dateutil.parser._parser import _TzInfos from ._common import weekday as weekdaybase -YEARLY: int -MONTHLY: int -WEEKLY: int -DAILY: int -HOURLY: int -MINUTELY: int -SECONDLY: int +__all__ = [ + "rrule", + "rruleset", + "rrulestr", + "YEARLY", + "MONTHLY", + "WEEKLY", + "DAILY", + "HOURLY", + "MINUTELY", + "SECONDLY", + "MO", + "TU", + "WE", + "TH", + "FR", + "SA", + "SU", +] + +M366MASK: Final[tuple[int, ...]] +MDAY366MASK: Final[tuple[int, ...]] +MDAY365MASK: Final[tuple[int, ...]] +NMDAY366MASK: Final[tuple[int, ...]] +NMDAY365MASK: Final[list[int]] +M366RANGE: Final[tuple[int, ...]] +M365RANGE: Final[tuple[int, ...]] +WDAYMASK: Final[list[int]] +M365MASK: Final[tuple[int, ...]] +FREQNAMES: Final[list[str]] +YEARLY: Final = 0 +MONTHLY: Final = 1 +WEEKLY: Final = 2 +DAILY: Final = 3 +HOURLY: Final = 4 +MINUTELY: Final = 5 +SECONDLY: Final = 6 class weekday(weekdaybase): ... +weekdays: tuple[weekday, weekday, weekday, weekday, weekday, weekday, weekday] MO: weekday TU: weekday WE: weekday @@ -22,86 +57,167 @@ SA: weekday SU: weekday class rrulebase: - def __init__(self, cache: bool = ...) -> None: ... - def __iter__(self): ... - def __getitem__(self, item): ... - def __contains__(self, item): ... - def count(self): ... - def before(self, dt, inc: bool = ...): ... - def after(self, dt, inc: bool = ...): ... - def xafter(self, dt, count: Any | None = ..., inc: bool = ...): ... - def between(self, after, before, inc: bool = ..., count: int = ...): ... + def __init__(self, cache: bool | None = False) -> None: ... + def __iter__(self) -> Iterator[datetime.datetime]: ... + def __getitem__(self, item: int | slice) -> datetime.datetime: ... + def __contains__(self, item: datetime.datetime) -> bool: ... + def count(self) -> int | None: ... + def before(self, dt: datetime.datetime, inc: bool = False) -> datetime.datetime | None: ... + def after(self, dt: datetime.datetime, inc: bool = False) -> datetime.datetime | None: ... + def xafter(self, dt: datetime.datetime, count: int | None = None, inc: bool = False) -> Generator[datetime.datetime]: ... + def between( + self, after: datetime.datetime, before: datetime.datetime, inc: bool = False, count: int = 1 + ) -> list[datetime.datetime]: ... class rrule(rrulebase): def __init__( self, - freq, + freq: Literal[0, 1, 2, 3, 4, 5, 6], + dtstart: datetime.date | None = None, + interval: int = 1, + wkst: weekday | int | None = None, + count: int | None = None, + until: datetime.date | int | None = None, + bysetpos: int | Iterable[int] | None = None, + bymonth: int | Iterable[int] | None = None, + bymonthday: int | Iterable[int] | None = None, + byyearday: int | Iterable[int] | None = None, + byeaster: int | Iterable[int] | None = None, + byweekno: int | Iterable[int] | None = None, + byweekday: int | weekday | Iterable[int] | Iterable[weekday] | None = None, + byhour: int | Iterable[int] | None = None, + byminute: int | Iterable[int] | None = None, + bysecond: int | Iterable[int] | None = None, + cache: bool | None = False, + ) -> None: ... + def replace( + self, + *, + freq: Literal[0, 1, 2, 3, 4, 5, 6] = ..., dtstart: datetime.date | None = ..., interval: int = ..., wkst: weekday | int | None = ..., count: int | None = ..., until: datetime.date | int | None = ..., - bysetpos: int | Iterable[int] | None = ..., - bymonth: int | Iterable[int] | None = ..., - bymonthday: int | Iterable[int] | None = ..., - byyearday: int | Iterable[int] | None = ..., - byeaster: int | Iterable[int] | None = ..., - byweekno: int | Iterable[int] | None = ..., - byweekday: int | weekday | Iterable[int] | Iterable[weekday] | None = ..., - byhour: int | Iterable[int] | None = ..., - byminute: int | Iterable[int] | None = ..., - bysecond: int | Iterable[int] | None = ..., - cache: bool = ..., - ) -> None: ... - def replace(self, **kwargs): ... + bysetpos: int | Iterable[int] | None = None, + bymonth: int | Iterable[int] | None = None, + bymonthday: int | Iterable[int] | None = None, + byyearday: int | Iterable[int] | None = None, + byeaster: int | Iterable[int] | None = None, + byweekno: int | Iterable[int] | None = None, + byweekday: int | weekday | Iterable[int] | Iterable[weekday] | None = None, + byhour: int | Iterable[int] | None = None, + byminute: int | Iterable[int] | None = None, + bysecond: int | Iterable[int] | None = None, + cache: bool | None = ..., + ) -> Self: ... -class _iterinfo: - rrule: Any = ... - def __init__(self, rrule) -> None: ... - yearlen: int = ... - nextyearlen: int = ... - yearordinal: int = ... - yearweekday: int = ... - mmask: Any = ... - mdaymask: Any = ... - nmdaymask: Any = ... - wdaymask: Any = ... - mrange: Any = ... - wnomask: Any = ... - nwdaymask: Any = ... - eastermask: Any = ... - lastyear: int = ... - lastmonth: int = ... - def rebuild(self, year, month): ... - def ydayset(self, year, month, day): ... - def mdayset(self, year, month, day): ... - def wdayset(self, year, month, day): ... - def ddayset(self, year, month, day): ... - def htimeset(self, hour, minute, second): ... - def mtimeset(self, hour, minute, second): ... - def stimeset(self, hour, minute, second): ... +_RRule: TypeAlias = rrule -_rrule = rrule +class _iterinfo: + __slots__ = [ + "rrule", + "lastyear", + "lastmonth", + "yearlen", + "nextyearlen", + "yearordinal", + "yearweekday", + "mmask", + "mrange", + "mdaymask", + "nmdaymask", + "wdaymask", + "wnomask", + "nwdaymask", + "eastermask", + ] + rrule: _RRule + def __init__(self, rrule: _RRule) -> None: ... + yearlen: int | None + nextyearlen: int | None + yearordinal: int | None + yearweekday: int | None + mmask: Sequence[int] | None + mdaymask: Sequence[int] | None + nmdaymask: Sequence[int] | None + wdaymask: Sequence[int] | None + mrange: Sequence[int] | None + wnomask: Sequence[int] | None + nwdaymask: Sequence[int] | None + eastermask: Sequence[int] | None + lastyear: int | None + lastmonth: int | None + def rebuild(self, year: int, month: int) -> None: ... + def ydayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def mdayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def wdayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def ddayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def htimeset(self, hour: int, minute: int, second: int) -> list[datetime.time]: ... + def mtimeset(self, hour: int, minute: int, second: int) -> list[datetime.time]: ... + def stimeset(self, hour: int, minute: int, second: int) -> tuple[datetime.time, ...]: ... class rruleset(rrulebase): class _genitem: - dt: Any = ... - genlist: Any = ... - gen: Any = ... - def __init__(self, genlist, gen) -> None: ... - def __next__(self): ... - next: Any = ... - def __lt__(self, other): ... - def __gt__(self, other): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __init__(self, cache: bool = ...) -> None: ... - def rrule(self, rrule: _rrule): ... - def rdate(self, rdate): ... - def exrule(self, exrule): ... - def exdate(self, exdate): ... + dt: datetime.datetime + genlist: list[Self] + gen: Iterator[datetime.datetime] + def __init__(self, genlist: list[Self], gen: Iterator[datetime.datetime]) -> None: ... + def __next__(self) -> None: ... + next = __next__ + def __lt__(self, other: Self) -> bool: ... + def __gt__(self, other: Self) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + + def __init__(self, cache: bool | None = False) -> None: ... + def rrule(self, rrule: _RRule) -> None: ... + def rdate(self, rdate: datetime.datetime) -> None: ... + def exrule(self, exrule: _RRule) -> None: ... + def exdate(self, exdate: datetime.datetime) -> None: ... class _rrulestr: - def __call__(self, s, **kwargs): ... + @overload + def __call__( + self, + s: str, + *, + forceset: Literal[True], + dtstart: datetime.date | None = None, + cache: bool | None = None, + unfold: bool = False, + compatible: bool = False, + ignoretz: bool = False, + tzids: Callable[[str], datetime.tzinfo] | Mapping[str, datetime.tzinfo] | None = None, + tzinfos: _TzInfos | None = None, + ) -> rruleset: ... + @overload + def __call__( + self, + s: str, + *, + compatible: Literal[True], + dtstart: datetime.date | None = None, + cache: bool | None = None, + unfold: bool = False, + forceset: bool = False, + ignoretz: bool = False, + tzids: Callable[[str], datetime.tzinfo] | Mapping[str, datetime.tzinfo] | None = None, + tzinfos: _TzInfos | None = None, + ) -> rruleset: ... + @overload + def __call__( + self, + s: str, + *, + dtstart: datetime.date | None = None, + cache: bool | None = False, + unfold: bool = False, + forceset: bool = False, + compatible: bool = False, + ignoretz: bool = False, + tzids: Callable[[str], datetime.tzinfo] | Mapping[str, datetime.tzinfo] | None = None, + tzinfos: _TzInfos | None = None, + ) -> rrule | rruleset: ... rrulestr: _rrulestr diff --git a/stubs/python-dateutil/dateutil/tz/__init__.pyi b/stubs/python-dateutil/dateutil/tz/__init__.pyi index 334ca4825094..406980bdfdab 100644 --- a/stubs/python-dateutil/dateutil/tz/__init__.pyi +++ b/stubs/python-dateutil/dateutil/tz/__init__.pyi @@ -1,6 +1,13 @@ +import builtins +import sys +from datetime import datetime +from typing_extensions import Self + +from ._common import tzrangebase from .tz import ( datetime_ambiguous as datetime_ambiguous, datetime_exists as datetime_exists, + enfold as enfold, gettz as gettz, resolve_imaginary as resolve_imaginary, tzfile as tzfile, @@ -12,4 +19,50 @@ from .tz import ( tzutc as tzutc, ) +# UTC, tzwin, tzwinlocal are defined in this class +# otherwise pyright complains about unknown import symbol: +if sys.platform == "win32": + class tzwinbase(tzrangebase): + hasdst: bool + def __eq__(self, other: tzwinbase) -> bool: ... # type: ignore[override] + @staticmethod + def list() -> builtins.list[str]: ... + def display(self) -> str | None: ... + def transitions(self, year: int) -> tuple[datetime, datetime] | None: ... + + class tzwin(tzwinbase): + hasdst: bool + def __init__(self, name: str) -> None: ... + def __reduce__(self) -> tuple[type[Self], tuple[str, ...]]: ... # type: ignore[override] + + class tzwinlocal(tzwinbase): + hasdst: bool + def __init__(self) -> None: ... + def __reduce__(self) -> tuple[type[Self], tuple[str, ...]]: ... # type: ignore[override] + +else: + tzwin: None + tzwinlocal: None + UTC: tzutc + +__all__ = [ + "tzutc", + "tzoffset", + "tzlocal", + "tzfile", + "tzrange", + "tzstr", + "tzical", + "tzwin", + "tzwinlocal", + "gettz", + "enfold", + "datetime_ambiguous", + "datetime_exists", + "resolve_imaginary", + "UTC", + "DeprecatedTzFormatWarning", +] + +class DeprecatedTzFormatWarning(Warning): ... diff --git a/stubs/python-dateutil/dateutil/tz/_common.pyi b/stubs/python-dateutil/dateutil/tz/_common.pyi index 807789fef776..b160d0bc7398 100644 --- a/stubs/python-dateutil/dateutil/tz/_common.pyi +++ b/stubs/python-dateutil/dateutil/tz/_common.pyi @@ -1,14 +1,23 @@ +import abc +from collections.abc import Callable from datetime import datetime, timedelta, tzinfo -from typing import Any +from typing import ClassVar, ParamSpec, TypeVar -def tzname_in_python2(namefunc): ... -def enfold(dt: datetime, fold: int = ...): ... +ZERO: timedelta -class _DatetimeWithFold(datetime): - @property - def fold(self): ... +__all__ = ["tzname_in_python2", "enfold"] -class _tzinfo(tzinfo): +_P = ParamSpec("_P") +_R = TypeVar("_R") +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +def tzname_in_python2(namefunc: Callable[_P, _R]) -> Callable[_P, _R]: ... +def enfold(dt: _DateTimeT, fold: int = 1) -> _DateTimeT: ... + +# Doesn't actually have ABCMeta as the metaclass at runtime, +# but mypy complains if we don't have it in the stub. +# See discussion in #8908 +class _tzinfo(tzinfo, metaclass=abc.ABCMeta): def is_ambiguous(self, dt: datetime) -> bool: ... def fromutc(self, dt: datetime) -> datetime: ... @@ -19,6 +28,6 @@ class tzrangebase(_tzinfo): def tzname(self, dt: datetime | None) -> str: ... def fromutc(self, dt: datetime) -> datetime: ... def is_ambiguous(self, dt: datetime) -> bool: ... - __hash__: Any - def __ne__(self, other): ... - __reduce__: Any + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ diff --git a/stubs/python-dateutil/dateutil/tz/tz.pyi b/stubs/python-dateutil/dateutil/tz/tz.pyi index dad7fa15a0b3..fe2eaf50ee22 100644 --- a/stubs/python-dateutil/dateutil/tz/tz.pyi +++ b/stubs/python-dateutil/dateutil/tz/tz.pyi @@ -1,104 +1,139 @@ -import datetime -from typing import IO, Any, Text, TypeVar, Union +import sys +from _typeshed import Unused +from datetime import datetime, timedelta, tzinfo +from typing import Any, ClassVar, Literal, Protocol, TypeVar, type_check_only +from typing_extensions import Self from ..relativedelta import relativedelta -from ._common import _tzinfo as _tzinfo, enfold as enfold, tzname_in_python2 as tzname_in_python2, tzrangebase as tzrangebase +from ._common import _tzinfo, enfold as enfold, tzrangebase -_FileObj = Union[str, Text, IO[str], IO[Text]] -_DT = TypeVar("_DT", bound=datetime.datetime) +if sys.platform == "win32": + from .win import tzwin as tzwin, tzwinlocal as tzwinlocal +else: + tzwin: None + tzwinlocal: None -ZERO: datetime.timedelta -EPOCH: datetime.datetime +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +ZERO: timedelta +EPOCH: datetime EPOCHORDINAL: int -class tzutc(datetime.tzinfo): - def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def tzname(self, dt: datetime.datetime | None) -> str: ... - def is_ambiguous(self, dt: datetime.datetime | None) -> bool: ... - def fromutc(self, dt: _DT) -> _DT: ... - def __eq__(self, other): ... - __hash__: Any - def __ne__(self, other): ... - __reduce__: Any - -class tzoffset(datetime.tzinfo): - def __init__(self, name, offset) -> None: ... - def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def is_ambiguous(self, dt: datetime.datetime | None) -> bool: ... - def tzname(self, dt: datetime.datetime | None) -> str: ... - def fromutc(self, dt: _DT) -> _DT: ... - def __eq__(self, other): ... - __hash__: Any - def __ne__(self, other): ... - __reduce__: Any +class tzutc(tzinfo): + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def is_ambiguous(self, dt: datetime | None) -> bool: ... + def fromutc(self, dt: _DateTimeT) -> _DateTimeT: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ + +UTC: tzutc + +class tzoffset(tzinfo): + def __init__(self, name: str | None, offset: float | timedelta) -> None: ... + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def is_ambiguous(self, dt: datetime | None) -> bool: ... + def tzname(self, dt: datetime | None) -> str: ... + def fromutc(self, dt: _DateTimeT) -> _DateTimeT: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ @classmethod - def instance(cls, name, offset) -> tzoffset: ... + def instance(cls, name: str | None, offset: float | timedelta) -> tzoffset: ... class tzlocal(_tzinfo): def __init__(self) -> None: ... - def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def tzname(self, dt: datetime.datetime | None) -> str: ... - def is_ambiguous(self, dt: datetime.datetime | None) -> bool: ... - def __eq__(self, other): ... - __hash__: Any - def __ne__(self, other): ... - __reduce__: Any + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def is_ambiguous(self, dt: datetime | None) -> bool: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ class _ttinfo: + __slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt", "dstoffset"] + offset: float + delta: timedelta + isdst: bool + abbr: str + isstd: bool + isgmt: bool + dstoffset: timedelta def __init__(self) -> None: ... - def __eq__(self, other): ... - __hash__: Any - def __ne__(self, other): ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + +@type_check_only +class _TZFileReader(Protocol): + # optional attribute: + # name: str + def read(self, size: int, /) -> bytes: ... + def seek(self, target: int, whence: Literal[1], /) -> object: ... class tzfile(_tzinfo): - def __init__(self, fileobj: _FileObj, filename: Text | None = ...) -> None: ... - def is_ambiguous(self, dt: datetime.datetime | None, idx: int | None = ...) -> bool: ... - def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... - def tzname(self, dt: datetime.datetime | None) -> str: ... - def __eq__(self, other): ... - __hash__: Any - def __ne__(self, other): ... - def __reduce__(self): ... - def __reduce_ex__(self, protocol): ... + def __init__(self, fileobj: str | _TZFileReader, filename: str | None = None) -> None: ... + def is_ambiguous(self, dt: datetime | None, idx: int | None = None) -> bool: ... + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + def __reduce__(self) -> tuple[type[Self], tuple[None, str], dict[str, Any]]: ... + def __reduce_ex__(self, protocol: Unused) -> tuple[type[Self], tuple[None, str], dict[str, Any]]: ... class tzrange(tzrangebase): hasdst: bool def __init__( self, - stdabbr: Text, - stdoffset: int | datetime.timedelta | None = ..., - dstabbr: Text | None = ..., - dstoffset: int | datetime.timedelta | None = ..., - start: relativedelta | None = ..., - end: relativedelta | None = ..., + stdabbr: str, + stdoffset: int | timedelta | None = None, + dstabbr: str | None = None, + dstoffset: int | timedelta | None = None, + start: relativedelta | None = None, + end: relativedelta | None = None, ) -> None: ... - def transitions(self, year: int) -> tuple[datetime.datetime, datetime.datetime]: ... - def __eq__(self, other): ... + def transitions(self, year: int) -> tuple[datetime, datetime]: ... + def __eq__(self, other: object) -> bool: ... class tzstr(tzrange): hasdst: bool - def __init__(self, s: bytes | _FileObj, posix_offset: bool = ...) -> None: ... + def __init__(self, s: str, posix_offset: bool = False) -> None: ... @classmethod - def instance(cls, name, offset) -> tzoffset: ... + def instance(cls, name: str | None, offset: float | timedelta) -> tzoffset: ... + +@type_check_only +class _ICalReader(Protocol): + # optional attribute: + # name: str + def read(self) -> str: ... class tzical: - def __init__(self, fileobj: _FileObj) -> None: ... - def keys(self): ... - def get(self, tzid: Any | None = ...): ... + def __init__(self, fileobj: str | _ICalReader) -> None: ... + def keys(self) -> list[str]: ... + def get(self, tzid: str | None = None) -> tzinfo | None: ... TZFILES: list[str] TZPATHS: list[str] -def datetime_exists(dt: datetime.datetime, tz: datetime.tzinfo | None = ...) -> bool: ... -def datetime_ambiguous(dt: datetime.datetime, tz: datetime.tzinfo | None = ...) -> bool: ... -def resolve_imaginary(dt: datetime.datetime) -> datetime.datetime: ... +def datetime_exists(dt: datetime, tz: tzinfo | None = None) -> bool: ... +def datetime_ambiguous(dt: datetime, tz: tzinfo | None = None) -> bool: ... +def resolve_imaginary(dt: _DateTimeT) -> _DateTimeT: ... +# Singleton type defined locally in a function. Calls itself "GettzFunc". +@type_check_only class _GetTZ: - def __call__(self, name: Text | None = ...) -> datetime.tzinfo | None: ... - def nocache(self, name: Text | None) -> datetime.tzinfo | None: ... + def __call__(self, name: str | None = None) -> tzinfo | None: ... + def set_cache_size(self, size: int) -> None: ... + def cache_clear(self) -> None: ... + def nocache(self, name: str | None) -> tzinfo | None: ... gettz: _GetTZ diff --git a/stubs/python-dateutil/dateutil/tz/win.pyi b/stubs/python-dateutil/dateutil/tz/win.pyi new file mode 100644 index 000000000000..8d02d23acb01 --- /dev/null +++ b/stubs/python-dateutil/dateutil/tz/win.pyi @@ -0,0 +1,27 @@ +import sys +from ctypes import _NameTypes, _Pointer, c_wchar +from datetime import datetime, timedelta +from typing import Any, ClassVar, Final + +from dateutil.tz import tzwin as tzwin, tzwinlocal as tzwinlocal + +if sys.platform == "win32": + from winreg import _KeyType + + __all__ = ["tzwin", "tzwinlocal", "tzres"] + + ONEWEEK: timedelta + TZKEYNAMENT: Final[str] + TZKEYNAME9X: Final[str] + TZLOCALKEYNAME: Final[str] + TZKEYNAME: Final[str] + + class tzres: + p_wchar: ClassVar[type[_Pointer[c_wchar]]] + tzres_loc: _NameTypes + def __init__(self, tzres_loc: _NameTypes = "tzres.dll") -> None: ... + def load_name(self, offset: int) -> str: ... + def name_from_string(self, tzname_str: str) -> str: ... + + def picknthweekday(year: int, month: int, dayofweek: int, hour: int, minute: int, whichweek: int) -> datetime: ... + def valuestodict(key: _KeyType) -> dict[str, Any]: ... # keys and values in dict are results of winreg.EnumValue() function diff --git a/stubs/python-dateutil/dateutil/tzwin.pyi b/stubs/python-dateutil/dateutil/tzwin.pyi new file mode 100644 index 000000000000..f021d35938e6 --- /dev/null +++ b/stubs/python-dateutil/dateutil/tzwin.pyi @@ -0,0 +1,4 @@ +import sys + +if sys.platform == "win32": + from .tz.win import tzres as tzres, tzwin as tzwin, tzwinlocal as tzwinlocal diff --git a/stubs/python-dateutil/dateutil/utils.pyi b/stubs/python-dateutil/dateutil/utils.pyi index 6ebd4031fdb7..ce4d8d38ccc0 100644 --- a/stubs/python-dateutil/dateutil/utils.pyi +++ b/stubs/python-dateutil/dateutil/utils.pyi @@ -1,5 +1,8 @@ -from datetime import datetime, timedelta, tzinfo +from datetime import _TzInfo, datetime, timedelta +from typing import TypeVar -def default_tzinfo(dt: datetime, tzinfo: tzinfo) -> datetime: ... -def today(tzinfo: tzinfo | None = ...) -> datetime: ... +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +def today(tzinfo: _TzInfo | None = None) -> datetime: ... +def default_tzinfo(dt: _DateTimeT, tzinfo: _TzInfo) -> _DateTimeT: ... def within_delta(dt1: datetime, dt2: datetime, delta: timedelta) -> bool: ... diff --git a/stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi b/stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi new file mode 100644 index 000000000000..adee85032da2 --- /dev/null +++ b/stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from io import BytesIO +from tarfile import _Fileobj +from typing import Final, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated + +from dateutil.tz import tzfile as _tzfile + +_T = TypeVar("_T") +_MetadataType: TypeAlias = dict[str, Incomplete] + +__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] + +ZONEFILENAME: Final[str] +METADATA_FN: Final[str] + +class tzfile(_tzfile): + # source code does this override, changing the type + def __reduce__(self) -> tuple[Callable[[str], Self], tuple[str]]: ... # type: ignore[override] + +def getzoneinfofile_stream() -> BytesIO | None: ... + +class ZoneInfoFile: + zones: dict[str, _tzfile] + metadata: _MetadataType | None + def __init__(self, zonefile_stream: _Fileobj | None = None) -> None: ... + + @overload + def get(self, name: str, default: None = None) -> _tzfile | None: ... + @overload + def get(self, name: str, default: _tzfile) -> _tzfile: ... + @overload + def get(self, name: str, default: _T) -> _tzfile | _T: ... + +def get_zonefile_instance(new_instance: bool = False) -> ZoneInfoFile: ... +@deprecated( + "zoneinfo.gettz() will be removed in future versions, to use the dateutil-provided " + "zoneinfo files, instantiate a ZoneInfoFile object and use ZoneInfoFile.zones.get() instead." +) +def gettz(name: str) -> _tzfile: ... +@deprecated( + "zoneinfo.gettz_db_metadata() will be removed in future versions, to use the " + "dateutil-provided zoneinfo files, ZoneInfoFile object and query the 'metadata' attribute instead." +) +def gettz_db_metadata() -> _MetadataType: ... diff --git a/stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi b/stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi new file mode 100644 index 000000000000..325950a2eea3 --- /dev/null +++ b/stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrOrBytesPath, Unused +from collections.abc import Iterable + +from ..zoneinfo import _MetadataType + +def rebuild( + filename: StrOrBytesPath, + tag: Unused | None = None, + format: str = "gz", + zonegroups: Iterable[str] = [], + metadata: _MetadataType | None = None, +) -> None: ... diff --git a/stubs/python-gflags/@tests/stubtest_allowlist.txt b/stubs/python-gflags/@tests/stubtest_allowlist.txt deleted file mode 100644 index f37b2b810ccf..000000000000 --- a/stubs/python-gflags/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1 +0,0 @@ -gflags diff --git a/stubs/python-gflags/METADATA.toml b/stubs/python-gflags/METADATA.toml deleted file mode 100644 index ac2fd418911a..000000000000 --- a/stubs/python-gflags/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "3.1.*" -python2 = true diff --git a/stubs/python-gflags/gflags.pyi b/stubs/python-gflags/gflags.pyi deleted file mode 100644 index bc674935cb24..000000000000 --- a/stubs/python-gflags/gflags.pyi +++ /dev/null @@ -1,310 +0,0 @@ -from types import ModuleType -from typing import IO, Any, Callable, Iterable, Sequence, Text - -class Error(Exception): ... - -FlagsError = Error - -class DuplicateFlag(FlagsError): ... -class CantOpenFlagFileError(FlagsError): ... -class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): ... - -class DuplicateFlagError(DuplicateFlag): - def __init__(self, flagname: str, flag_values: FlagValues, other_flag_values: FlagValues = ...) -> None: ... - -class IllegalFlagValueError(FlagsError): ... - -IllegalFlagValue = IllegalFlagValueError - -class UnrecognizedFlag(FlagsError): ... - -class UnrecognizedFlagError(UnrecognizedFlag): - def __init__(self, flagname: str, flagvalue: str = ...) -> None: ... - -def get_help_width() -> int: ... - -GetHelpWidth = get_help_width - -def text_wrap(text: str, length: int = ..., indent: str = ..., firstline_indent: str = ..., tabs: str = ...) -> str: ... - -TextWrap = text_wrap - -def doc_to_help(doc: str) -> str: ... - -DocToHelp = doc_to_help - -class FlagValues: - def __init__(self) -> None: ... - def UseGnuGetOpt(self, use_gnu_getopt: bool = ...) -> None: ... - def is_gnu_getopt(self) -> bool: ... - IsGnuGetOpt = is_gnu_getopt - # TODO dict type - def FlagDict(self) -> dict[Any, Any]: ... - def flags_by_module_dict(self) -> dict[str, list[Flag]]: ... - FlagsByModuleDict = flags_by_module_dict - def flags_by_module_id_dict(self) -> dict[int, list[Flag]]: ... - FlagsByModuleIdDict = flags_by_module_id_dict - def key_flags_by_module_dict(self) -> dict[str, list[Flag]]: ... - KeyFlagsByModuleDict = key_flags_by_module_dict - def find_module_defining_flag(self, flagname: str, default: str = ...) -> str: ... - FindModuleDefiningFlag = find_module_defining_flag - def find_module_id_defining_flag(self, flagname: str, default: int = ...) -> int: ... - FindModuleIdDefiningFlag = find_module_id_defining_flag - def append_flag_values(self, flag_values: FlagValues) -> None: ... - AppendFlagValues = append_flag_values - def remove_flag_values(self, flag_values: FlagValues) -> None: ... - RemoveFlagValues = remove_flag_values - def __setitem__(self, name: str, flag: Flag) -> None: ... - def __getitem__(self, name: str) -> Flag: ... - def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, flag_name: str) -> None: ... - def set_default(self, name: str, value: Any) -> None: ... - SetDefault = set_default - def __contains__(self, name: str) -> bool: ... - has_key = __contains__ - def __iter__(self) -> Iterable[str]: ... - def __call__(self, argv: list[str], known_only: bool = ...) -> list[str]: ... - def reset(self) -> None: ... - Reset = reset - def RegisteredFlags(self) -> list[str]: ... - def flag_values_dict(self) -> dict[str, Any]: ... - FlagValuesDict = flag_values_dict - def __str__(self) -> str: ... - def GetHelp(self, prefix: str = ...) -> str: ... - def module_help(self, module: ModuleType | str) -> str: ... - ModuleHelp = module_help - def main_module_help(self) -> str: ... - MainModuleHelp = main_module_help - def get(self, name: str, default: Any) -> Any: ... - def ShortestUniquePrefixes(self, fl: dict[str, Flag]) -> dict[str, str]: ... - def ExtractFilename(self, flagfile_str: str) -> str: ... - def read_flags_from_files(self, argv: list[str], force_gnu: bool = ...) -> list[str]: ... - ReadFlagsFromFiles = read_flags_from_files - def flags_into_string(self) -> str: ... - FlagsIntoString = flags_into_string - def append_flags_into_file(self, filename: str) -> None: ... - AppendFlagsIntoFile = append_flags_into_file - def write_help_in_xml_format(self, outfile: IO[str] = ...) -> None: ... - WriteHelpInXMLFormat = write_help_in_xml_format - # TODO validator: gflags_validators.Validator - def AddValidator(self, validator: Any) -> None: ... - def is_parsed(self) -> bool: ... - IsParsed = is_parsed - -FLAGS: FlagValues - -class Flag: - name: str - default: Any - default_as_str: str - value: Any - help: str - short_name: str - boolean = False - present = False - parser: ArgumentParser - serializer: ArgumentSerializer - allow_override = False - def __init__( - self, - parser: ArgumentParser, - serializer: ArgumentSerializer, - name: str, - default: str | None, - help_string: str, - short_name: str = ..., - boolean: bool = ..., - allow_override: bool = ..., - ) -> None: ... - def Parse(self, argument: Any) -> Any: ... - def Unparse(self) -> None: ... - def Serialize(self) -> str: ... - def SetDefault(self, value: Any) -> None: ... - def Type(self) -> str: ... - def WriteInfoInXMLFormat(self, outfile: IO[str], module_name: str, is_key: bool = ..., indent: str = ...) -> None: ... - -class ArgumentParser(object): - syntactic_help: str - # TODO what is this - def parse(self, argument: Any) -> Any: ... - Parser = parse - def flag_type(self) -> str: ... - Type = flag_type - def WriteCustomInfoInXMLFormat(self, outfile: IO[str], indent: str) -> None: ... - -class ArgumentSerializer: - def Serialize(self, value: Any) -> Text: ... - -class ListSerializer(ArgumentSerializer): - def __init__(self, list_sep: str) -> None: ... - def Serialize(self, value: list[Any]) -> str: ... - -def register_validator( - flag_name: str, checker: Callable[[Any], bool], message: str = ..., flag_values: FlagValues = ... -) -> None: ... - -RegisterValidator = register_validator - -def mark_flag_as_required(flag_name: str, flag_values: FlagValues = ...) -> None: ... - -MarkFlagAsRequired = mark_flag_as_required - -def mark_flags_as_required(flag_names: Iterable[str], flag_values: FlagValues = ...) -> None: ... - -MarkFlagsAsRequired = mark_flags_as_required - -def mark_flags_as_mutual_exclusive(flag_names: Iterable[str], required: bool = ..., flag_values: FlagValues = ...) -> None: ... - -MarkFlagsAsMutualExclusive = mark_flags_as_mutual_exclusive - -def DEFINE( - parser: ArgumentParser, - name: str, - default: Any, - help: str, - flag_values: FlagValues = ..., - serializer: ArgumentSerializer = ..., - **args: Any, -) -> None: ... -def DEFINE_flag(flag: Flag, flag_values: FlagValues = ...) -> None: ... -def declare_key_flag(flag_name: str, flag_values: FlagValues = ...) -> None: ... - -DECLARE_key_flag = declare_key_flag - -def adopt_module_key_flags(module: ModuleType, flag_values: FlagValues = ...) -> None: ... - -ADOPT_module_key_flags = adopt_module_key_flags - -def DEFINE_string(name: str, default: str | None, help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... - -class BooleanParser(ArgumentParser): - def Convert(self, argument: Any) -> bool: ... - def Parse(self, argument: Any) -> bool: ... - -class BooleanFlag(Flag): - def __init__(self, name: str, default: bool | None, help: str, short_name: str = ..., **args: Any) -> None: ... - -def DEFINE_boolean(name: str, default: bool | None, help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... - -DEFINE_bool = DEFINE_boolean - -class HelpFlag(BooleanFlag): - def __init__(self) -> None: ... - def Parse(self, arg: Any) -> None: ... - -class HelpXMLFlag(BooleanFlag): - def __init__(self) -> None: ... - def Parse(self, arg: Any) -> None: ... - -class HelpshortFlag(BooleanFlag): - def __init__(self) -> None: ... - def Parse(self, arg: Any) -> None: ... - -class NumericParser(ArgumentParser): - def IsOutsideBounds(self, val: float) -> bool: ... - def Parse(self, argument: Any) -> float: ... - def WriteCustomInfoInXMLFormat(self, outfile: IO[str], indent: str) -> None: ... - def Convert(self, argument: Any) -> Any: ... - -class FloatParser(NumericParser): - number_article: str - number_name: str - syntactic_help: str - def __init__(self, lower_bound: float = ..., upper_bound: float = ...) -> None: ... - def Convert(self, argument: Any) -> float: ... - -def DEFINE_float( - name: str, - default: float | None, - help: str, - lower_bound: float = ..., - upper_bound: float = ..., - flag_values: FlagValues = ..., - **args: Any, -) -> None: ... - -class IntegerParser(NumericParser): - number_article: str - number_name: str - syntactic_help: str - def __init__(self, lower_bound: int = ..., upper_bound: int = ...) -> None: ... - def Convert(self, argument: Any) -> int: ... - -def DEFINE_integer( - name: str, - default: int | None, - help: str, - lower_bound: int = ..., - upper_bound: int = ..., - flag_values: FlagValues = ..., - **args: Any, -) -> None: ... - -class EnumParser(ArgumentParser): - def __init__(self, enum_values: list[str]) -> None: ... - def Parse(self, argument: Any) -> Any: ... - -class EnumFlag(Flag): - def __init__( - self, name: str, default: str | None, help: str, enum_values: list[str], short_name: str, **args: Any - ) -> None: ... - -def DEFINE_enum( - name: str, default: str | None, enum_values: Iterable[str], help: str, flag_values: FlagValues = ..., **args: Any -) -> None: ... - -class BaseListParser(ArgumentParser): - def __init__(self, token: str = ..., name: str = ...) -> None: ... - def Parse(self, argument: Any) -> list[Any]: ... - -class ListParser(BaseListParser): - def __init__(self) -> None: ... - -class WhitespaceSeparatedListParser(BaseListParser): - def __init__(self) -> None: ... - -def DEFINE_list(name: str, default: list[str] | None, help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... -def DEFINE_spaceseplist(name: str, default: list[str] | None, help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... - -class MultiFlag(Flag): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def Parse(self, arguments: Any) -> None: ... - def Serialize(self) -> str: ... - -def DEFINE_multi_string( - name: str, default: str | list[str] | None, help: str, flag_values: FlagValues = ..., **args: Any -) -> None: ... - -DEFINE_multistring = DEFINE_multi_string - -def DEFINE_multi_integer( - name: str, - default: int | list[int] | None, - help: str, - lower_bound: int = ..., - upper_bound: int = ..., - flag_values: FlagValues = ..., - **args: Any, -) -> None: ... - -DEFINE_multi_int = DEFINE_multi_integer - -def DEFINE_multi_float( - name: str, - default: float | list[float] | None, - help: str, - lower_bound: float = ..., - upper_bound: float = ..., - flag_values: FlagValues = ..., - **args: Any, -) -> None: ... -def DEFINE_multi_enum( - name: str, - default: Sequence[str] | str | None, - enum_values: Sequence[str], - help: str, - flag_values: FlagValues = ..., - case_sensitive: bool = ..., - **args: Any, -) -> None: ... diff --git a/stubs/python-http-client/@tests/stubtest_allowlist.txt b/stubs/python-http-client/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f1c4ead36ecf --- /dev/null +++ b/stubs/python-http-client/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +python_http_client.version_file diff --git a/stubs/python-http-client/METADATA.toml b/stubs/python-http-client/METADATA.toml new file mode 100644 index 000000000000..f93b0770d472 --- /dev/null +++ b/stubs/python-http-client/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.3.7" +upstream-repository = "https://github.com/sendgrid/python-http-client" diff --git a/stubs/python-http-client/python_http_client/__init__.pyi b/stubs/python-http-client/python_http_client/__init__.pyi new file mode 100644 index 000000000000..1c17420c7594 --- /dev/null +++ b/stubs/python-http-client/python_http_client/__init__.pyi @@ -0,0 +1,20 @@ +from typing import Final + +from .client import Client as Client +from .exceptions import ( + BadRequestsError as BadRequestsError, + ForbiddenError as ForbiddenError, + GatewayTimeoutError as GatewayTimeoutError, + HTTPError as HTTPError, + InternalServerError as InternalServerError, + MethodNotAllowedError as MethodNotAllowedError, + NotFoundError as NotFoundError, + PayloadTooLargeError as PayloadTooLargeError, + ServiceUnavailableError as ServiceUnavailableError, + TooManyRequestsError as TooManyRequestsError, + UnauthorizedError as UnauthorizedError, + UnsupportedMediaTypeError as UnsupportedMediaTypeError, +) + +dir_path: Final[str] +__version__: Final[str] diff --git a/stubs/python-http-client/python_http_client/client.pyi b/stubs/python-http-client/python_http_client/client.pyi new file mode 100644 index 000000000000..aceb5f6cbaa8 --- /dev/null +++ b/stubs/python-http-client/python_http_client/client.pyi @@ -0,0 +1,32 @@ +from email.message import Message +from http.client import HTTPResponse +from typing import Any, Final + +class Response: + def __init__(self, response: HTTPResponse) -> None: ... + @property + def status_code(self) -> int: ... + @property + def body(self) -> bytes: ... + @property + def headers(self) -> Message: ... + @property + def to_dict(self) -> dict[str, Any] | None: ... # dict of response from API if body is not empty + +class Client: + methods: Final[set[str]] + host: str + request_headers: dict[str, str] + append_slash: bool + timeout: int + def __init__( + self, + host: str, + request_headers: dict[str, str] | None = None, + version: int | None = None, + url_path: list[str] | None = None, + append_slash: bool = False, + timeout: int | None = None, + ) -> None: ... + def _(self, name: str) -> Client: ... + def __getattr__(self, name: str) -> Client | Response: ... diff --git a/stubs/python-http-client/python_http_client/exceptions.pyi b/stubs/python-http-client/python_http_client/exceptions.pyi new file mode 100644 index 000000000000..6fc504b17b57 --- /dev/null +++ b/stubs/python-http-client/python_http_client/exceptions.pyi @@ -0,0 +1,34 @@ +from email.message import Message +from typing import Any, Final, overload +from urllib.error import HTTPError as _HTTPError + +class HTTPError(Exception): + status_code: int + reason: str + body: bytes + headers: Message + + @overload + def __init__(self, status_code: int, reason: str, body: bytes, headers: Message, /) -> None: ... + @overload + def __init__(self, http_error: _HTTPError, /) -> None: ... + + def __reduce__(self) -> tuple[type[HTTPError], tuple[int, str, bytes, Message]]: ... + @property + def to_dict(self) -> dict[str, Any]: ... # dict of response error from the API + +class BadRequestsError(HTTPError): ... +class UnauthorizedError(HTTPError): ... +class ForbiddenError(HTTPError): ... +class NotFoundError(HTTPError): ... +class MethodNotAllowedError(HTTPError): ... +class PayloadTooLargeError(HTTPError): ... +class UnsupportedMediaTypeError(HTTPError): ... +class TooManyRequestsError(HTTPError): ... +class InternalServerError(HTTPError): ... +class ServiceUnavailableError(HTTPError): ... +class GatewayTimeoutError(HTTPError): ... + +err_dict: Final[dict[int, type[HTTPError]]] + +def handle_error(error: _HTTPError) -> HTTPError: ... diff --git a/stubs/python-jenkins/@tests/stubtest_allowlist.txt b/stubs/python-jenkins/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..787864001fed --- /dev/null +++ b/stubs/python-jenkins/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# The default value for the timeout parameter is a token from urllib3 which is private and should not be used by end-users +jenkins.Jenkins.__init__ diff --git a/stubs/python-jenkins/METADATA.toml b/stubs/python-jenkins/METADATA.toml new file mode 100644 index 000000000000..2f60657ee621 --- /dev/null +++ b/stubs/python-jenkins/METADATA.toml @@ -0,0 +1,3 @@ +version = "~=1.8.3" +upstream-repository = "https://opendev.org/jjb/python-jenkins" +dependencies = ["requests>=2.34.0"] diff --git a/stubs/python-jenkins/jenkins/__init__.pyi b/stubs/python-jenkins/jenkins/__init__.pyi new file mode 100644 index 000000000000..1f392073916e --- /dev/null +++ b/stubs/python-jenkins/jenkins/__init__.pyi @@ -0,0 +1,254 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, MutableMapping, Sequence +from re import Pattern +from typing import Any, Final, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Required, deprecated + +import requests +from requests._types import AuthType +from requests.models import Request, Response + +LAUNCHER_SSH: Final[str] +LAUNCHER_COMMAND: Final[str] +LAUNCHER_JNLP: Final[str] +LAUNCHER_WINDOWS_SERVICE: Final[str] +DEFAULT_HEADERS: Final[dict[str, str]] +DEFAULT_TIMEOUT: Final[float] +DEFAULT_RETRIES: Final = 0 +INFO: Final[str] +PLUGIN_INFO: Final[str] +CRUMB_URL: Final[str] +WHOAMI_URL: Final[str] +JOBS_QUERY: Final[str] +JOBS_QUERY_TREE: Final[str] +JOB_INFO: Final[str] +JOB_NAME: Final[str] +ALL_BUILDS: Final[str] +Q_INFO: Final[str] +Q_ITEM: Final[str] +CANCEL_QUEUE: Final[str] +CREATE_JOB: Final[str] +CONFIG_JOB: Final[str] +DELETE_JOB: Final[str] +ENABLE_JOB: Final[str] +DISABLE_JOB: Final[str] +CHECK_JENKINSFILE_SYNTAX: Final[str] +SET_JOB_BUILD_NUMBER: Final[str] +COPY_JOB: Final[str] +RENAME_JOB: Final[str] +BUILD_JOB: Final[str] +STOP_BUILD: Final[str] +BUILD_WITH_PARAMS_JOB: Final[str] +BUILD_INFO: Final[str] +BUILD_CONSOLE_OUTPUT: Final[str] +BUILD_ENV_VARS: Final[str] +BUILD_TEST_REPORT: Final[str] +BUILD_ARTIFACT: Final[str] +BUILD_STAGES: Final[str] +DELETE_BUILD: Final[str] +WIPEOUT_JOB_WORKSPACE: Final[str] +NODE_LIST: Final[str] +CREATE_NODE: Final[str] +DELETE_NODE: Final[str] +NODE_INFO: Final[str] +NODE_TYPE: Final[str] +TOGGLE_OFFLINE: Final[str] +CONFIG_NODE: Final[str] +VIEW_NAME: Final[str] +VIEW_JOBS: Final[str] +CREATE_VIEW: Final[str] +CONFIG_VIEW: Final[str] +DELETE_VIEW: Final[str] +SCRIPT_TEXT: Final[str] +NODE_SCRIPT_TEXT: Final[str] +PROMOTION_NAME: Final[str] +PROMOTION_INFO: Final[str] +DELETE_PROMOTION: Final[str] +CREATE_PROMOTION: Final[str] +CONFIG_PROMOTION: Final[str] +LIST_CREDENTIALS: Final[str] +CREATE_CREDENTIAL: Final[str] +CONFIG_CREDENTIAL: Final[str] +CREDENTIAL_INFO: Final[str] +QUIET_DOWN: Final[str] +EMPTY_CONFIG_XML: Final[str] +EMPTY_FOLDER_XML: Final[str] +RECONFIG_XML: Final[str] +EMPTY_VIEW_CONFIG_XML: Final[str] +EMPTY_PROMO_CONFIG_XML: Final[str] +PROMO_RECONFIG_XML: Final[str] + +class JenkinsException(Exception): ... +class NotFoundException(JenkinsException): ... +class EmptyResponseException(JenkinsException): ... +class BadHTTPException(JenkinsException): ... +class TimeoutException(JenkinsException): ... + +class WrappedSession(requests.Session): + # merge_environment_settings wraps requests.Session.merge_environment_settings + # w/o changing the type signature + ... + +_JSONValue: TypeAlias = Any # too many possibilities to express +_JSON: TypeAlias = dict[str, _JSONValue] + +@type_check_only +class _Job(TypedDict, total=False): + _class: Required[str] + url: Required[str] + color: str + name: Required[str] + fullname: Required[str] + jobs: list[_Job] + +class Jenkins: + server: str + auth: AuthType | None + crumb: Mapping[str, Incomplete] | bool | Incomplete + timeout: int + def __init__( + self, url: str, username: str | None = None, password: str | None = None, timeout: int = ..., retries: int = 0 + ) -> None: ... + def maybe_add_crumb(self, req: Request) -> None: ... + def get_job_info(self, name: str, depth: int = 0, fetch_all_builds: bool = False) -> _JSON: ... + def get_job_info_regex( + self, pattern: str | Pattern[str], depth: int = 0, folder_depth: int = 0, folder_depth_per_request: int = 10 + ) -> list[_JSON]: ... + def get_job_name(self, name: str) -> str | None: ... + def debug_job_info(self, job_name: str) -> None: ... + def jenkins_open(self, req: Request, add_crumb: bool = True, resolve_auth: bool = True) -> str: ... + def jenkins_open_stream(self, req: Request, add_crumb: bool = True, resolve_auth: bool = True) -> Response: ... + def jenkins_request( + self, req: Request, add_crumb: bool = True, resolve_auth: bool = True, stream: bool | None = None + ) -> Response: ... + def get_queue_item(self, number: int, depth: int = 0) -> _JSON: ... + def get_build_info(self, name: str, number: int, depth: int = 0) -> _JSON: ... + def get_build_env_vars(self, name: str, number: int, depth: int = 0) -> _JSON | None: ... + def get_build_test_report(self, name: str, number: int, depth: int = 0, tree: str | None = None) -> _JSON | None: ... + def get_build_artifact(self, name: str, number: int, artifact: str) -> _JSON: ... + def get_build_artifact_as_bytes(self, name: str, number: int, artifact: str) -> bytes: ... + def get_build_stages(self, name: str, number: int) -> _JSON: ... + def get_queue_info(self) -> _JSON: ... + def cancel_queue(self, id: int) -> None: ... + def get_info(self, item: str = "", query: str | None = None) -> _JSON: ... + def get_whoami(self, depth: int = 0) -> _JSON: ... + def get_version(self) -> str: ... + @deprecated("Deprecated since 0.4.9. Use `get_plugins` instead.") + def get_plugins_info(self, depth: int = 2) -> _JSON: ... + def get_plugin_info(self, name: str, depth: int = 2) -> _JSON: ... + def get_plugins(self, depth: int = 2) -> _JSON: ... + def get_jobs(self, folder_depth: int = 0, folder_depth_per_request: int = 10, view_name: str | None = None) -> list[_Job]: ... + def get_all_jobs(self, folder_depth: int | None = None, folder_depth_per_request: int = 10) -> list[_Job]: ... + def copy_job(self, from_name: str, to_name: str) -> None: ... + def rename_job(self, from_name: str, to_name: str) -> None: ... + def delete_job(self, name: str) -> None: ... + def enable_job(self, name: str) -> None: ... + def disable_job(self, name: str) -> None: ... + def set_next_build_number(self, name: str, number: int) -> None: ... + def job_exists(self, name: str) -> bool: ... + def jobs_count(self) -> int: ... + def assert_job_exists(self, name: str, exception_message: str = "job[%s] does not exist") -> None: ... + def create_folder(self, folder_name: str, ignore_failures: bool = False) -> None: ... + def upsert_job(self, name: str, config_xml: str) -> None: ... + def check_jenkinsfile_syntax(self, jenkinsfile: str) -> list[str]: ... + def create_job(self, name: str, config_xml: str) -> None: ... + def get_job_config(self, name: str) -> str: ... + def reconfig_job(self, name: str, config_xml: str) -> None: ... + + @overload + def build_job_url( + self, + name: str, + parameters: Mapping[str, Incomplete] | Sequence[tuple[str, Incomplete]] | None = None, + token: Literal[""] | None = None, + ) -> str: ... + @overload + def build_job_url( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None, token: str + ) -> str: ... + @overload + def build_job_url( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None = None, *, token: str + ) -> str: ... + + @overload + def build_job( + self, + name: str, + parameters: Mapping[str, Incomplete] | Sequence[tuple[str, Incomplete]] | None = None, + token: Literal[""] | None = None, + ) -> int: ... + @overload + def build_job( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None, token: str + ) -> int: ... + @overload + def build_job( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None = None, *, token: str + ) -> int: ... + + def run_script(self, script: str, node: str | None = None) -> str: ... + def install_plugin(self, name: str, include_dependencies: bool = True) -> bool: ... + def stop_build(self, name: str, number: int) -> None: ... + def delete_build(self, name: str, number: int) -> None: ... + def wipeout_job_workspace(self, name: str) -> None: ... + def get_running_builds(self) -> list[_JSON]: ... + def get_nodes_with_info(self, depth: int = 0) -> list[_JSON]: ... + def get_nodes(self, depth: int = 0) -> list[_JSON]: ... + def get_node_info(self, name: str, depth: int = 0) -> _JSON: ... + def node_exists(self, name: str) -> bool: ... + def assert_node_exists(self, name: str, exception_message: str = "node[%s] does not exist") -> None: ... + def delete_node(self, name: str) -> None: ... + def disable_node(self, name: str, msg: str = "") -> None: ... + def enable_node(self, name: str) -> None: ... + def create_node( + self, + name: str, + numExecutors: int = 2, + nodeDescription: str | None = None, + remoteFS: str = "/var/lib/jenkins", + labels: str | None = None, + exclusive: bool = False, + launcher: str = "hudson.slaves.CommandLauncher", + launcher_params: MutableMapping[str, Incomplete] = {}, + ) -> None: ... + def get_node_config(self, name: str) -> str: ... + def reconfig_node(self, name: str, config_xml: str) -> None: ... + def get_build_console_output(self, name: str, number: int) -> str: ... + def get_view_name(self, name: str) -> str | None: ... + def assert_view_exists(self, name: str, exception_message: str = "view[%s] does not exist") -> None: ... + def view_exists(self, name: str) -> bool: ... + def get_views(self) -> list[_JSON]: ... + def delete_view(self, name: str) -> None: ... + def create_view(self, name: str, config_xml: str) -> None: ... + def reconfig_view(self, name: str, config_xml: str) -> None: ... + def get_view_config(self, name: str) -> str: ... + def get_promotion_name(self, name: str, job_name: str) -> str | None: ... + def assert_promotion_exists( + self, name: str, job_name: str, exception_message: str = "promotion[%s] does not exist for job[%s]" + ) -> None: ... + def promotion_exists(self, name: str, job_name: str) -> bool: ... + def get_promotions_info(self, job_name: str, depth: int = 0) -> _JSON: ... + def get_promotions(self, job_name: str) -> list[_JSON]: ... + def delete_promotion(self, name: str, job_name: str) -> None: ... + def create_promotion(self, name: str, job_name: str, config_xml: str) -> None: ... + def reconfig_promotion(self, name: str, job_name: str, config_xml: str) -> None: ... + def get_promotion_config(self, name: str, job_name: str) -> str: ... + def assert_folder(self, name: str, exception_message: str = "job[%s] is not a folder") -> None: ... + def is_folder(self, name: str) -> bool: ... + def assert_credential_exists( + self, + name: str, + folder_name: str, + domain_name: str = "_", + exception_message: str = "credential[%s] does not exist in the domain[%s] of [%s]", # noqa: Y053 + ) -> None: ... + def credential_exists(self, name: str, folder_name: str, domain_name: str = "_") -> bool: ... + def get_credential_info(self, name: str, folder_name: str, domain_name: str = "_") -> _JSON: ... + def get_credential_config(self, name: str, folder_name: str, domain_name: str = "_") -> str: ... + def create_credential(self, folder_name: str, config_xml: str, domain_name: str = "_") -> None: ... + def delete_credential(self, name: str, folder_name: str, domain_name: str = "_") -> None: ... + def reconfig_credential(self, folder_name: str, config_xml: str, domain_name: str = "_") -> None: ... + def list_credentials(self, folder_name: str, domain_name: str = "_") -> list[Incomplete]: ... + def quiet_down(self) -> None: ... + def wait_for_normal_op(self, timeout: int) -> bool: ... diff --git a/stubs/python-jenkins/jenkins/plugins.pyi b/stubs/python-jenkins/jenkins/plugins.pyi new file mode 100644 index 000000000000..aa3ce52a1da9 --- /dev/null +++ b/stubs/python-jenkins/jenkins/plugins.pyi @@ -0,0 +1,15 @@ +from typing import Any + +# Any: Union of possible plugin values is too complex +class Plugin(dict[str, Any]): + # __init__ wraps dict.__init__ w/o changing the type signature + def __setitem__(self, key: str, value: Any) -> None: ... + +class PluginVersion(str): + def __init__(self, version: str) -> None: ... + def __le__(self, version: object) -> bool: ... + def __lt__(self, version: object) -> bool: ... + def __ge__(self, version: object) -> bool: ... + def __gt__(self, version: object) -> bool: ... + def __eq__(self, version: object) -> bool: ... + def __ne__(self, version: object) -> bool: ... diff --git a/stubs/python-jenkins/jenkins/version.pyi b/stubs/python-jenkins/jenkins/version.pyi new file mode 100644 index 000000000000..7b63c09e3d72 --- /dev/null +++ b/stubs/python-jenkins/jenkins/version.pyi @@ -0,0 +1,3 @@ +from _typeshed import Incomplete + +version_info: Incomplete # pbr.version.VersionInfo diff --git a/stubs/python-jose/@tests/stubtest_allowlist.txt b/stubs/python-jose/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b0c651965b8a --- /dev/null +++ b/stubs/python-jose/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +jose.backends.cryptography_backend diff --git a/stubs/python-jose/METADATA.toml b/stubs/python-jose/METADATA.toml new file mode 100644 index 000000000000..5248bfa71dfb --- /dev/null +++ b/stubs/python-jose/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.5.*" +upstream-repository = "https://github.com/mpdavis/python-jose" +dependencies = ["types-pyasn1"] # excluding pyrsa, cryptography until typing is available diff --git a/stubs/python-jose/jose/__init__.pyi b/stubs/python-jose/jose/__init__.pyi new file mode 100644 index 000000000000..dcd21e1f413b --- /dev/null +++ b/stubs/python-jose/jose/__init__.pyi @@ -0,0 +1,11 @@ +from .exceptions import ( + ExpiredSignatureError as ExpiredSignatureError, + JOSEError as JOSEError, + JWSError as JWSError, + JWTError as JWTError, +) + +__version__: str +__author__: str +__license__: str +__copyright__: str diff --git a/stubs/python-jose/jose/backends/__init__.pyi b/stubs/python-jose/jose/backends/__init__.pyi new file mode 100644 index 000000000000..9aae87f033e7 --- /dev/null +++ b/stubs/python-jose/jose/backends/__init__.pyi @@ -0,0 +1,18 @@ +from .base import DIRKey as DIRKey +from .cryptography_backend import ( + CryptographyAESKey as CryptographyAESKey, + CryptographyECKey as CryptographyECKey, + CryptographyHMACKey as CryptographyHMACKey, + CryptographyRSAKey as CryptographyRSAKey, +) +from .ecdsa_backend import ECDSAECKey as ECDSAECKey +from .native import HMACKey as NativeHMACKey, get_random_bytes as get_random_bytes +from .rsa_backend import RSAKey as BackendRSAKey + +# python-jose relies on importing from cryptography_backend +# then falling back on other imports +# these are all the potential options +AESKey: type[CryptographyAESKey] | None +HMACKey: type[CryptographyHMACKey | NativeHMACKey] +RSAKey: type[CryptographyRSAKey | BackendRSAKey] | None +ECKey: type[CryptographyECKey | ECDSAECKey] diff --git a/stubs/python-jose/jose/backends/_asn1.pyi b/stubs/python-jose/jose/backends/_asn1.pyi new file mode 100644 index 000000000000..b4fce464ced1 --- /dev/null +++ b/stubs/python-jose/jose/backends/_asn1.pyi @@ -0,0 +1,17 @@ +from pyasn1.type import namedtype, univ + +RSA_ENCRYPTION_ASN1_OID: str + +class RsaAlgorithmIdentifier(univ.Sequence): + componentType: namedtype.NamedTypes + +class PKCS8PrivateKey(univ.Sequence): + componentType: namedtype.NamedTypes + +class PublicKeyInfo(univ.Sequence): + componentType: namedtype.NamedTypes + +def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key) -> bytes: ... +def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key) -> bytes: ... +def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key) -> bytes: ... +def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key) -> bytes: ... diff --git a/stubs/python-jose/jose/backends/base.pyi b/stubs/python-jose/jose/backends/base.pyi new file mode 100644 index 000000000000..f13da256d148 --- /dev/null +++ b/stubs/python-jose/jose/backends/base.pyi @@ -0,0 +1,23 @@ +from typing import Any +from typing_extensions import Self + +class Key: + # Enable when we can use stubs from installed dependencies, + # as `key` can be of type cryptography.x509.base.Certificate: + # from cryptography.x509 import Certificate + def __init__(self, key, algorithm) -> None: ... + def sign(self, msg: bytes) -> bytes: ... + def verify(self, msg: bytes, sig: bytes) -> bool: ... + def public_key(self) -> Self: ... + def to_pem(self) -> bytes: ... + def to_dict(self) -> dict[str, Any]: ... + def encrypt(self, plain_text: str | bytes, aad: bytes | None = None) -> tuple[bytes, bytes, bytes | None]: ... + def decrypt( + self, cipher_text: str | bytes, iv: str | bytes | None = None, aad: bytes | None = None, tag: bytes | None = None + ) -> bytes: ... + def wrap_key(self, key_data: bytes) -> bytes: ... + def unwrap_key(self, wrapped_key: bytes) -> bytes: ... + +class DIRKey(Key): + def __init__(self, key_data: str | bytes, algorithm: str) -> None: ... + def to_dict(self) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/backends/cryptography_backend.pyi b/stubs/python-jose/jose/backends/cryptography_backend.pyi new file mode 100644 index 000000000000..dce249e54bf3 --- /dev/null +++ b/stubs/python-jose/jose/backends/cryptography_backend.pyi @@ -0,0 +1,66 @@ +from typing import Any, ClassVar + +from . import get_random_bytes as get_random_bytes +from .base import Key + +# Enable when we can use stubs from installed dependencies: +# from cryptography.hazmat import backends +class CryptographyECKey(Key): + SHA256: Any + SHA384: Any + SHA512: Any + hash_alg: Any + cryptography_backend: Any + prepared_key: Any + def __init__(self, key, algorithm, cryptography_backend=...) -> None: ... + def sign(self, msg): ... + def verify(self, msg, sig): ... + def is_public(self): ... + def public_key(self): ... + def to_pem(self): ... + def to_dict(self): ... + +class CryptographyRSAKey(Key): + SHA256: Any + SHA384: Any + SHA512: Any + RSA1_5: Any + RSA_OAEP: Any + RSA_OAEP_256: Any + hash_alg: Any + padding: Any + cryptography_backend: Any + prepared_key: Any + def __init__(self, key, algorithm, cryptography_backend=...) -> None: ... + def sign(self, msg): ... + def verify(self, msg, sig): ... + def is_public(self): ... + def public_key(self): ... + def to_pem(self, pem_format: str = "PKCS8"): ... + def to_dict(self): ... + def wrap_key(self, key_data): ... + def unwrap_key(self, wrapped_key): ... + +class CryptographyAESKey(Key): + KEY_128: Any + KEY_192: Any + KEY_256: Any + KEY_384: Any + KEY_512: Any + AES_KW_ALGS: Any + MODES: Any + IV_BYTE_LENGTH_MODE_MAP: ClassVar[dict[str, int]] + def __init__(self, key, algorithm) -> None: ... + def to_dict(self): ... + def encrypt(self, plain_text, aad=None): ... + def decrypt(self, cipher_text, iv=None, aad=None, tag=None): ... + def wrap_key(self, key_data): ... + def unwrap_key(self, wrapped_key): ... + +class CryptographyHMACKey(Key): + ALG_MAP: Any + prepared_key: Any + def __init__(self, key, algorithm) -> None: ... + def to_dict(self): ... + def sign(self, msg): ... + def verify(self, msg, sig): ... diff --git a/stubs/python-jose/jose/backends/ecdsa_backend.pyi b/stubs/python-jose/jose/backends/ecdsa_backend.pyi new file mode 100644 index 000000000000..fea488c785ad --- /dev/null +++ b/stubs/python-jose/jose/backends/ecdsa_backend.pyi @@ -0,0 +1,25 @@ +from collections.abc import Callable +from hashlib import _Hash +from typing import Any +from typing_extensions import Self + +from .base import Key + +# Enable when we can use stubs from installed dependencies: +# from ecdsa.curves import Curve +class ECDSAECKey(Key): + SHA256: Callable[[bytes], _Hash] + SHA384: Callable[[bytes], _Hash] + SHA512: Callable[[bytes], _Hash] + CURVE_MAP: Any + CURVE_NAMES: Any + hash_alg: Any + curve: Any + prepared_key: Any + def __init__(self, key, algorithm) -> None: ... + def sign(self, msg): ... + def verify(self, msg, sig): ... + def is_public(self) -> bool: ... + def public_key(self) -> Self: ... + def to_pem(self): ... + def to_dict(self) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/backends/native.pyi b/stubs/python-jose/jose/backends/native.pyi new file mode 100644 index 000000000000..8c1626b59089 --- /dev/null +++ b/stubs/python-jose/jose/backends/native.pyi @@ -0,0 +1,21 @@ +from _typeshed import ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash +from typing import Any + +from .base import Key + +def get_random_bytes(num_bytes: int) -> bytes: ... + +class HMACKey(Key): + HASHES: dict[str, Callable[[bytes], _Hash]] + prepared_key: bytes + def __init__( + self, + # explicitly checks for key_data as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any], + algorithm: str, + ) -> None: ... + def sign(self, msg: ReadableBuffer | None) -> bytes: ... + def verify(self, msg: ReadableBuffer | None, sig: str | bytes) -> bool: ... + def to_dict(self) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/backends/rsa_backend.pyi b/stubs/python-jose/jose/backends/rsa_backend.pyi new file mode 100644 index 000000000000..495b39a4fb0b --- /dev/null +++ b/stubs/python-jose/jose/backends/rsa_backend.pyi @@ -0,0 +1,27 @@ +from typing import Any +from typing_extensions import Self + +from .base import Key + +LEGACY_INVALID_PKCS8_RSA_HEADER: bytes +ASN1_SEQUENCE_ID: bytes +RSA_ENCRYPTION_ASN1_OID: str + +# Enable when we can use stubs from installed dependencies: +# from rsa import PublicKey +def pem_to_spki(pem, fmt: str = "PKCS8"): ... + +class RSAKey(Key): + SHA256: str + SHA384: str + SHA512: str + hash_alg: str + def __init__(self, key, algorithm) -> None: ... + def sign(self, msg: bytes) -> bytes: ... + def verify(self, msg: bytes, sig: bytes) -> bool: ... + def is_public(self) -> bool: ... + def public_key(self) -> Self: ... + def to_pem(self, pem_format: str = "PKCS8") -> bytes: ... + def to_dict(self) -> dict[str, Any]: ... + def wrap_key(self, key_data: bytes) -> bytes: ... + def unwrap_key(self, wrapped_key: bytes) -> bytes: ... diff --git a/stubs/python-jose/jose/constants.pyi b/stubs/python-jose/jose/constants.pyi new file mode 100644 index 000000000000..a8df8f155333 --- /dev/null +++ b/stubs/python-jose/jose/constants.pyi @@ -0,0 +1,75 @@ +from collections.abc import Callable, Mapping +from hashlib import _Hash +from typing import Final + +from .backends.base import Key + +class Algorithms: + NONE: str + HS256: str + HS384: str + HS512: str + RS256: str + RS384: str + RS512: str + ES256: str + ES384: str + ES512: str + A128CBC_HS256: str + A192CBC_HS384: str + A256CBC_HS512: str + A128GCM: str + A192GCM: str + A256GCM: str + A128CBC: str + A192CBC: str + A256CBC: str + DIR: str + RSA1_5: str + RSA_OAEP: str + RSA_OAEP_256: str + A128KW: str + A192KW: str + A256KW: str + ECDH_ES: str + ECDH_ES_A128KW: str + ECDH_ES_A192KW: str + ECDH_ES_A256KW: str + A128GCMKW: str + A192GCMKW: str + A256GCMKW: str + PBES2_HS256_A128KW: str + PBES2_HS384_A192KW: str + PBES2_HS512_A256KW: str + DEF: str + HMAC: set[str] + RSA_DS: set[str] + RSA_KW: set[str] + RSA: set[str] + EC_DS: set[str] + EC_KW: set[str] + EC: set[str] + AES_PSEUDO: set[str] + AES_JWE_ENC: set[str] + AES_ENC: set[str] + AES_KW: set[str] + AEC_GCM_KW: set[str] + AES: set[str] + PBES2_KW: set[str] + HMAC_AUTH_TAG: set[str] + GCM: set[str] + SUPPORTED: set[str] + ALL: set[str] + HASHES: Mapping[str, Callable[[bytes], _Hash]] + KEYS: Mapping[str, type[Key]] + +ALGORITHMS: Algorithms + +class Zips: + DEF: str + NONE: None + SUPPORTED: set[str | None] + +ZIPS: Zips + +JWE_SIZE_LIMIT: Final[int] diff --git a/stubs/python-jose/jose/exceptions.pyi b/stubs/python-jose/jose/exceptions.pyi new file mode 100644 index 000000000000..d7ab2176ce06 --- /dev/null +++ b/stubs/python-jose/jose/exceptions.pyi @@ -0,0 +1,12 @@ +class JOSEError(Exception): ... +class JWSError(JOSEError): ... +class JWSSignatureError(JWSError): ... +class JWSAlgorithmError(JWSError): ... +class JWTError(JOSEError): ... +class JWTClaimsError(JWTError): ... +class ExpiredSignatureError(JWTError): ... +class JWKError(JOSEError): ... +class JWEError(JOSEError): ... +class JWEParseError(JWEError): ... +class JWEInvalidAuth(JWEError): ... +class JWEAlgorithmUnsupportedError(JWEError): ... diff --git a/stubs/python-jose/jose/jwe.pyi b/stubs/python-jose/jose/jwe.pyi new file mode 100644 index 000000000000..e49a1cb093d7 --- /dev/null +++ b/stubs/python-jose/jose/jwe.pyi @@ -0,0 +1,22 @@ +from typing import Any + +from .backends.base import Key + +def encrypt( + plaintext: str | bytes, + # Internally it's passed down to jwk.construct(), which explicitly checks for + # key as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any] | Key, + encryption: str = "A256GCM", + algorithm: str = "dir", + zip: str | None = None, + cty: str | None = None, + kid: str | None = None, +) -> bytes: ... +def decrypt( + jwe_str: str | bytes, + # Internally it's passed down to jwk.construct(), which explicitly checks for + # key as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any] | Key, +) -> bytes | None: ... +def get_unverified_header(jwe_str: str | bytes | None) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/jwk.pyi b/stubs/python-jose/jose/jwk.pyi new file mode 100644 index 000000000000..27df5ef42b9d --- /dev/null +++ b/stubs/python-jose/jose/jwk.pyi @@ -0,0 +1,12 @@ +from typing import Any, Literal + +from .backends import AESKey as AESKey, ECKey as ECKey, HMACKey as HMACKey, RSAKey as RSAKey +from .backends.base import DIRKey as DIRKey, Key + +def get_key(algorithm: str) -> type[Key] | None: ... +def register_key(algorithm: str, key_class: type[Key]) -> Literal[True]: ... +def construct( + # explicitly checks for key_data as dict instance, instead of a Mapping + key_data: str | bytes | dict[str, Any] | Key, + algorithm: str | None = None, +) -> Key: ... diff --git a/stubs/python-jose/jose/jws.pyi b/stubs/python-jose/jose/jws.pyi new file mode 100644 index 000000000000..3f8194f6f243 --- /dev/null +++ b/stubs/python-jose/jose/jws.pyi @@ -0,0 +1,24 @@ +from collections.abc import Container, Iterable, Mapping +from typing import Any + +from .backends.base import Key + +def sign( + payload: bytes | Mapping[str, Any], + # Internally it's passed down to jwk.construct(), which explicitly checks for + # key as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any] | Key, + headers: Mapping[str, Any] | None = None, + algorithm: str = "HS256", +) -> str: ... +def verify( + token: str | bytes, + key: str | bytes | Mapping[str, Any] | Key | Iterable[str], + # Callers of this function, like jwt.decode(), and functions called internally, + # like jws._verify_signature(), use and accept algorithms=None + algorithms: str | Container[str] | None, + verify: bool = True, +) -> bytes: ... +def get_unverified_header(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_headers(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_claims(token: str | bytes) -> bytes: ... diff --git a/stubs/python-jose/jose/jwt.pyi b/stubs/python-jose/jose/jwt.pyi new file mode 100644 index 000000000000..1f4254ac48b3 --- /dev/null +++ b/stubs/python-jose/jose/jwt.pyi @@ -0,0 +1,29 @@ +from collections.abc import Container, Iterable, Mapping, MutableMapping +from datetime import timezone +from typing import Any + +from .backends.base import Key + +UTC: timezone + +def encode( + claims: MutableMapping[str, Any], + # Internally it calls jws.sign() that expects a key dict instance instead of Mapping + key: str | bytes | dict[str, Any] | Key, + algorithm: str = "HS256", + headers: Mapping[str, Any] | None = None, + access_token: str | None = None, +) -> str: ... +def decode( + token: str | bytes, + key: str | bytes | Mapping[str, Any] | Key | Iterable[str], + algorithms: str | Container[str] | None = None, + options: Mapping[str, Any] | None = None, + audience: str | None = None, + issuer: str | Iterable[str] | None = None, + subject: str | None = None, + access_token: str | None = None, +) -> dict[str, Any]: ... +def get_unverified_header(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_headers(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_claims(token: str | bytes) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/utils.pyi b/stubs/python-jose/jose/utils.pyi new file mode 100644 index 000000000000..52db52b82809 --- /dev/null +++ b/stubs/python-jose/jose/utils.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable, Iterable +from datetime import timedelta +from hashlib import _Hash +from typing import Any + +def long_to_bytes(n: int, blocksize: int | None = 0) -> bytes: ... +def long_to_base64(data: int, size: int | None = 0) -> bytes: ... +def int_arr_to_long(arr: Iterable[Any]) -> int: ... +def base64_to_long(data: str | bytes) -> int: ... +def calculate_at_hash(access_token: str, hash_alg: Callable[[bytes], _Hash]) -> str: ... +def base64url_decode(input: bytes) -> bytes: ... +def base64url_encode(input: bytes) -> bytes: ... +def timedelta_total_seconds(delta: timedelta) -> int: ... +def ensure_binary(s: str | bytes) -> bytes: ... +def is_pem_format(key: bytes) -> bool: ... +def is_ssh_key(key: bytes) -> bool: ... diff --git a/stubs/python-nmap/@tests/stubtest_allowlist.txt b/stubs/python-nmap/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7e144572d598 --- /dev/null +++ b/stubs/python-nmap/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +nmap.test_nmap diff --git a/stubs/python-nmap/METADATA.toml b/stubs/python-nmap/METADATA.toml index aed349a93a97..5adab60f78fd 100644 --- a/stubs/python-nmap/METADATA.toml +++ b/stubs/python-nmap/METADATA.toml @@ -1,3 +1,2 @@ -version = "0.6.*" -python2 = true -requires = [] +version = "0.7.*" +upstream-repository = "https://bitbucket.org/xael/python-nmap" diff --git a/stubs/python-nmap/nmap/__init__.pyi b/stubs/python-nmap/nmap/__init__.pyi index d495f0489abd..d2e6aef65bb4 100644 --- a/stubs/python-nmap/nmap/__init__.pyi +++ b/stubs/python-nmap/nmap/__init__.pyi @@ -1 +1,2 @@ from .nmap import * +from .nmap import __author__ as __author__, __last_modification__ as __last_modification__, __version__ as __version__ diff --git a/stubs/python-nmap/nmap/nmap.pyi b/stubs/python-nmap/nmap/nmap.pyi index a07d4b5e13ba..740467d72e55 100644 --- a/stubs/python-nmap/nmap/nmap.pyi +++ b/stubs/python-nmap/nmap/nmap.pyi @@ -1,27 +1,32 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, Text, TypeVar -from typing_extensions import TypedDict +from collections.abc import Callable, Iterable, Iterator +from typing import Any, TypeAlias, TypedDict, TypeVar, type_check_only _T = TypeVar("_T") -_Callback = Callable[[str, _Result], Any] +_Callback: TypeAlias = Callable[[str, _Result], object] +@type_check_only class _Result(TypedDict): nmap: _ResultNmap scan: dict[str, PortScannerHostDict] +@type_check_only class _ResultNmap(TypedDict): command_line: str scaninfo: _ResultNmapInfo scanstats: _ResultNampStats +@type_check_only class _ResultNmapInfo(TypedDict, total=False): error: str warning: str protocol: _ResultNampInfoProtocol +@type_check_only class _ResultNampInfoProtocol(TypedDict): method: str services: str +@type_check_only class _ResultNampStats(TypedDict): timestr: str elapsed: str @@ -29,14 +34,17 @@ class _ResultNampStats(TypedDict): downhosts: str totalhosts: str +@type_check_only class _ResulHostUptime(TypedDict): seconds: str lastboot: str +@type_check_only class _ResultHostNames(TypedDict): type: str name: str +@type_check_only class _ResultHostPort(TypedDict): conf: str cpe: str @@ -48,23 +56,28 @@ class _ResultHostPort(TypedDict): version: str __last_modification__: str +__author__: str +__version__: str -class PortScanner(object): - def __init__(self, nmap_search_path: Iterable[str] = ...) -> None: ... - def get_nmap_last_output(self) -> Text: ... +class PortScanner: + def __init__( + self, + nmap_search_path: Iterable[str] = ("nmap", "/usr/bin/nmap", "/usr/local/bin/nmap", "/sw/bin/nmap", "/opt/local/bin/nmap"), + ) -> None: ... + def get_nmap_last_output(self) -> str: ... def nmap_version(self) -> tuple[int, int]: ... - def listscan(self, hosts: str = ...) -> list[str]: ... + def listscan(self, hosts: str = "127.0.0.1") -> list[str]: ... def scan( - self, hosts: Text = ..., ports: Text | None = ..., arguments: Text = ..., sudo: bool = ..., timeout: int = ... + self, hosts: str = "127.0.0.1", ports: str | None = None, arguments: str = "-sV", sudo: bool = False, timeout: int = 0 ) -> _Result: ... def analyse_nmap_xml_scan( self, - nmap_xml_output: str | None = ..., - nmap_err: str = ..., - nmap_err_keep_trace: str = ..., - nmap_warn_keep_trace: str = ..., + nmap_xml_output: str | None = None, + nmap_err: str = "", + nmap_err_keep_trace: str = "", + nmap_warn_keep_trace: str = "", ) -> _Result: ... - def __getitem__(self, host: Text) -> PortScannerHostDict: ... + def __getitem__(self, host: str) -> PortScannerHostDict: ... def all_hosts(self) -> list[str]: ... def command_line(self) -> str: ... def scaninfo(self) -> _ResultNmapInfo: ... @@ -73,35 +86,35 @@ class PortScanner(object): def csv(self) -> str: ... def __scan_progressive__( - self: object, hosts: Text, ports: Text, arguments: Text, callback: _Callback | None, sudo: bool, timeout: int + self: object, hosts: str, ports: str, arguments: str, callback: _Callback | None, sudo: bool, timeout: int ) -> None: ... -class PortScannerAsync(object): +class PortScannerAsync: def __init__(self) -> None: ... def __del__(self) -> None: ... def scan( self, - hosts: Text = ..., - ports: Text | None = ..., - arguments: Text = ..., - callback: _Callback | None = ..., - sudo: bool = ..., - timeout: int = ..., + hosts: str = "127.0.0.1", + ports: str | None = None, + arguments: str = "-sV", + callback: _Callback | None = None, + sudo: bool = False, + timeout: int = 0, ) -> None: ... def stop(self) -> None: ... - def wait(self, timeout: int | None = ...) -> None: ... + def wait(self, timeout: int | None = None) -> None: ... def still_scanning(self) -> bool: ... class PortScannerYield(PortScannerAsync): def __init__(self) -> None: ... def scan( # type: ignore[override] - self, hosts: str = ..., ports: str | None = ..., arguments: str = ..., sudo: bool = ..., timeout: int = ... + self, hosts: str = "127.0.0.1", ports: str | None = None, arguments: str = "-sV", sudo: bool = False, timeout: int = 0 ) -> Iterator[tuple[str, _Result]]: ... def stop(self) -> None: ... - def wait(self, timeout: int | None = ...) -> None: ... + def wait(self, timeout: int | None = None) -> None: ... def still_scanning(self) -> None: ... # type: ignore[override] -class PortScannerHostDict(Dict[str, Any]): +class PortScannerHostDict(dict[str, Any]): def hostnames(self) -> list[_ResultHostNames]: ... def hostname(self) -> str: ... def state(self) -> str: ... @@ -126,4 +139,4 @@ class PortScannerError(Exception): class PortScannerTimeout(PortScannerError): ... -def convert_nmap_output_to_encoding(value: _T, code: str = ...) -> _T: ... +def convert_nmap_output_to_encoding(value: _T, code: str = "ascii") -> _T: ... diff --git a/stubs/python-slugify/METADATA.toml b/stubs/python-slugify/METADATA.toml deleted file mode 100644 index c98db63045e7..000000000000 --- a/stubs/python-slugify/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "5.0.*" diff --git a/stubs/python-slugify/slugify/__init__.pyi b/stubs/python-slugify/slugify/__init__.pyi deleted file mode 100644 index 1a7847377d10..000000000000 --- a/stubs/python-slugify/slugify/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from .slugify import * -from .special import * diff --git a/stubs/python-slugify/slugify/slugify.pyi b/stubs/python-slugify/slugify/slugify.pyi deleted file mode 100644 index 1a3ef13cddfe..000000000000 --- a/stubs/python-slugify/slugify/slugify.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Iterable - -def smart_truncate( - string: str, max_length: int = ..., word_boundary: bool = ..., separator: str = ..., save_order: bool = ... -) -> str: ... -def slugify( - text: str, - entities: bool = ..., - decimal: bool = ..., - hexadecimal: bool = ..., - max_length: int = ..., - word_boundary: bool = ..., - separator: str = ..., - save_order: bool = ..., - stopwords: Iterable[str] = ..., - regex_pattern: str | None = ..., - lowercase: bool = ..., - replacements: Iterable[Iterable[str]] = ..., -) -> str: ... diff --git a/stubs/python-slugify/slugify/special.pyi b/stubs/python-slugify/slugify/special.pyi deleted file mode 100644 index 29ca15bdad61..000000000000 --- a/stubs/python-slugify/slugify/special.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Sequence - -def add_uppercase_char(char_list: Sequence[tuple[str, str]]) -> Sequence[tuple[str, str]]: ... - -CYRILLIC: Sequence[tuple[str, str]] -GERMAN: Sequence[tuple[str, str]] -GREEK: Sequence[tuple[str, str]] -PRE_TRANSLATIONS: Sequence[tuple[str, str]] diff --git a/stubs/python-xlib/@tests/stubtest_allowlist.txt b/stubs/python-xlib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..731b14c8c3df --- /dev/null +++ b/stubs/python-xlib/@tests/stubtest_allowlist.txt @@ -0,0 +1,25 @@ +# Type helpers +Xlib._typing + +# __all__ is a map at runtime +# https://github.com/python-xlib/python-xlib/pull/238 +Xlib.ext(\.__all__)? + +# These will unconditionally fail at runtime +# See: https://github.com/python-xlib/python-xlib/issues/253 +Xlib.protocol.rq.DictWrapper.__gt__ +Xlib.protocol.rq.DictWrapper.__lt__ +Xlib.protocol.rq.Event.__gt__ +Xlib.protocol.rq.Event.__lt__ + +# should allow setting any attribute +Xlib.protocol.rq.GetAttrData.__setattr__ + +# Can be None or str once instantiated +Xlib.protocol.rq.*.structcode +# Should only ever be str once instantiated +Xlib.protocol.rq.*.name + +# Iteration variable that bleeds into the global scope +Xlib.protocol.rq.c +Xlib.protocol.rq.size diff --git a/stubs/python-xlib/METADATA.toml b/stubs/python-xlib/METADATA.toml new file mode 100644 index 000000000000..8bb5fab0a6bd --- /dev/null +++ b/stubs/python-xlib/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.33.*" +upstream-repository = "https://github.com/python-xlib/python-xlib" diff --git a/stubs/python-xlib/Xlib/X.pyi b/stubs/python-xlib/Xlib/X.pyi new file mode 100644 index 000000000000..cef7a5cdfced --- /dev/null +++ b/stubs/python-xlib/Xlib/X.pyi @@ -0,0 +1,347 @@ +from typing import Final + +NONE: Final = 0 +ParentRelative: Final = 1 +CopyFromParent: Final = 0 +PointerWindow: Final = 0 +InputFocus: Final = 1 +PointerRoot: Final = 1 +AnyPropertyType: Final = 0 +AnyKey: Final = 0 +AnyButton: Final = 0 +AllTemporary: Final = 0 +CurrentTime: Final = 0 +NoSymbol: Final = 0 +NoEventMask: Final = 0x0000000 +KeyPressMask: Final = 0x0000001 +KeyReleaseMask: Final = 0x0000002 +ButtonPressMask: Final = 0x0000004 +ButtonReleaseMask: Final = 0x0000008 +EnterWindowMask: Final = 0x0000010 +LeaveWindowMask: Final = 0x0000020 +PointerMotionMask: Final = 0x0000040 +PointerMotionHintMask: Final = 0x0000080 +Button1MotionMask: Final = 0x0000100 +Button2MotionMask: Final = 0x0000200 +Button3MotionMask: Final = 0x0000400 +Button4MotionMask: Final = 0x0000800 +Button5MotionMask: Final = 0x0001000 +ButtonMotionMask: Final = 0x0002000 +KeymapStateMask: Final = 0x0004000 +ExposureMask: Final = 0x0008000 +VisibilityChangeMask: Final = 0x0010000 +StructureNotifyMask: Final = 0x0020000 +ResizeRedirectMask: Final = 0x0040000 +SubstructureNotifyMask: Final = 0x0080000 +SubstructureRedirectMask: Final = 0x0100000 +FocusChangeMask: Final = 0x0200000 +PropertyChangeMask: Final = 0x0400000 +ColormapChangeMask: Final = 0x0800000 +OwnerGrabButtonMask: Final = 0x1000000 +KeyPress: Final = 2 +KeyRelease: Final = 3 +ButtonPress: Final = 4 +ButtonRelease: Final = 5 +MotionNotify: Final = 6 +EnterNotify: Final = 7 +LeaveNotify: Final = 8 +FocusIn: Final = 9 +FocusOut: Final = 10 +KeymapNotify: Final = 11 +Expose: Final = 12 +GraphicsExpose: Final = 13 +NoExpose: Final = 14 +VisibilityNotify: Final = 15 +CreateNotify: Final = 16 +DestroyNotify: Final = 17 +UnmapNotify: Final = 18 +MapNotify: Final = 19 +MapRequest: Final = 20 +ReparentNotify: Final = 21 +ConfigureNotify: Final = 22 +ConfigureRequest: Final = 23 +GravityNotify: Final = 24 +ResizeRequest: Final = 25 +CirculateNotify: Final = 26 +CirculateRequest: Final = 27 +PropertyNotify: Final = 28 +SelectionClear: Final = 29 +SelectionRequest: Final = 30 +SelectionNotify: Final = 31 +ColormapNotify: Final = 32 +ClientMessage: Final = 33 +MappingNotify: Final = 34 +LASTEvent: Final = 35 +ShiftMapIndex: Final = 0 +LockMapIndex: Final = 1 +ControlMapIndex: Final = 2 +Mod1MapIndex: Final = 3 +Mod2MapIndex: Final = 4 +Mod3MapIndex: Final = 5 +Mod4MapIndex: Final = 6 +Mod5MapIndex: Final = 7 +ShiftMask: Final = 0x0001 +LockMask: Final = 0x0002 +ControlMask: Final = 0x0004 +Mod1Mask: Final = 0x0008 +Mod2Mask: Final = 0x0010 +Mod3Mask: Final = 0x0020 +Mod4Mask: Final = 0x0040 +Mod5Mask: Final = 0x0080 +Button1Mask: Final = 0x0100 +Button2Mask: Final = 0x0200 +Button3Mask: Final = 0x0400 +Button4Mask: Final = 0x0800 +Button5Mask: Final = 0x1000 +AnyModifier: Final = 0x8000 +Button1: Final = 1 +Button2: Final = 2 +Button3: Final = 3 +Button4: Final = 4 +Button5: Final = 5 +NotifyNormal: Final = 0 +NotifyGrab: Final = 1 +NotifyUngrab: Final = 2 +NotifyWhileGrabbed: Final = 3 +NotifyHint: Final = 1 +NotifyAncestor: Final = 0 +NotifyVirtual: Final = 1 +NotifyInferior: Final = 2 +NotifyNonlinear: Final = 3 +NotifyNonlinearVirtual: Final = 4 +NotifyPointer: Final = 5 +NotifyPointerRoot: Final = 6 +NotifyDetailNone: Final = 7 +VisibilityUnobscured: Final = 0 +VisibilityPartiallyObscured: Final = 1 +VisibilityFullyObscured: Final = 2 +PlaceOnTop: Final = 0 +PlaceOnBottom: Final = 1 +FamilyInternet: Final = 0 +FamilyDECnet: Final = 1 +FamilyChaos: Final = 2 +FamilyServerInterpreted: Final = 5 +FamilyInternetV6: Final = 6 +PropertyNewValue: Final = 0 +PropertyDelete: Final = 1 +ColormapUninstalled: Final = 0 +ColormapInstalled: Final = 1 +GrabModeSync: Final = 0 +GrabModeAsync: Final = 1 +GrabSuccess: Final = 0 +AlreadyGrabbed: Final = 1 +GrabInvalidTime: Final = 2 +GrabNotViewable: Final = 3 +GrabFrozen: Final = 4 +AsyncPointer: Final = 0 +SyncPointer: Final = 1 +ReplayPointer: Final = 2 +AsyncKeyboard: Final = 3 +SyncKeyboard: Final = 4 +ReplayKeyboard: Final = 5 +AsyncBoth: Final = 6 +SyncBoth: Final = 7 +RevertToNone: Final = 0 +RevertToPointerRoot: Final = PointerRoot +RevertToParent: Final = 2 +Success: Final = 0 +BadRequest: Final = 1 +BadValue: Final = 2 +BadWindow: Final = 3 +BadPixmap: Final = 4 +BadAtom: Final = 5 +BadCursor: Final = 6 +BadFont: Final = 7 +BadMatch: Final = 8 +BadDrawable: Final = 9 +BadAccess: Final = 10 +BadAlloc: Final = 11 +BadColor: Final = 12 +BadGC: Final = 13 +BadIDChoice: Final = 14 +BadName: Final = 15 +BadLength: Final = 16 +BadImplementation: Final = 17 +FirstExtensionError: Final = 128 +LastExtensionError: Final = 255 +InputOutput: Final = 1 +InputOnly: Final = 2 +CWBackPixmap: Final = 0x0001 +CWBackPixel: Final = 0x0002 +CWBorderPixmap: Final = 0x0004 +CWBorderPixel: Final = 0x0008 +CWBitGravity: Final = 0x0010 +CWWinGravity: Final = 0x0020 +CWBackingStore: Final = 0x0040 +CWBackingPlanes: Final = 0x0080 +CWBackingPixel: Final = 0x0100 +CWOverrideRedirect: Final = 0x0200 +CWSaveUnder: Final = 0x0400 +CWEventMask: Final = 0x0800 +CWDontPropagate: Final = 0x1000 +CWColormap: Final = 0x2000 +CWCursor: Final = 0x4000 +CWX: Final = 0x01 +CWY: Final = 0x02 +CWWidth: Final = 0x04 +CWHeight: Final = 0x08 +CWBorderWidth: Final = 0x10 +CWSibling: Final = 0x20 +CWStackMode: Final = 0x40 +ForgetGravity: Final = 0 +NorthWestGravity: Final = 1 +NorthGravity: Final = 2 +NorthEastGravity: Final = 3 +WestGravity: Final = 4 +CenterGravity: Final = 5 +EastGravity: Final = 6 +SouthWestGravity: Final = 7 +SouthGravity: Final = 8 +SouthEastGravity: Final = 9 +StaticGravity: Final = 10 +UnmapGravity: Final = 0 +NotUseful: Final = 0 +WhenMapped: Final = 1 +Always: Final = 2 +IsUnmapped: Final = 0 +IsUnviewable: Final = 1 +IsViewable: Final = 2 +SetModeInsert: Final = 0 +SetModeDelete: Final = 1 +DestroyAll: Final = 0 +RetainPermanent: Final = 1 +RetainTemporary: Final = 2 +Above: Final = 0 +Below: Final = 1 +TopIf: Final = 2 +BottomIf: Final = 3 +Opposite: Final = 4 +RaiseLowest: Final = 0 +LowerHighest: Final = 1 +PropModeReplace: Final = 0 +PropModePrepend: Final = 1 +PropModeAppend: Final = 2 +GXclear: Final = 0x0 +GXand: Final = 0x1 +GXandReverse: Final = 0x2 +GXcopy: Final = 0x3 +GXandInverted: Final = 0x4 +GXnoop: Final = 0x5 +GXxor: Final = 0x6 +GXor: Final = 0x7 +GXnor: Final = 0x8 +GXequiv: Final = 0x9 +GXinvert: Final = 0xA +GXorReverse: Final = 0xB +GXcopyInverted: Final = 0xC +GXorInverted: Final = 0xD +GXnand: Final = 0xE +GXset: Final = 0xF +LineSolid: Final = 0 +LineOnOffDash: Final = 1 +LineDoubleDash: Final = 2 +CapNotLast: Final = 0 +CapButt: Final = 1 +CapRound: Final = 2 +CapProjecting: Final = 3 +JoinMiter: Final = 0 +JoinRound: Final = 1 +JoinBevel: Final = 2 +FillSolid: Final = 0 +FillTiled: Final = 1 +FillStippled: Final = 2 +FillOpaqueStippled: Final = 3 +EvenOddRule: Final = 0 +WindingRule: Final = 1 +ClipByChildren: Final = 0 +IncludeInferiors: Final = 1 +Unsorted: Final = 0 +YSorted: Final = 1 +YXSorted: Final = 2 +YXBanded: Final = 3 +CoordModeOrigin: Final = 0 +CoordModePrevious: Final = 1 +Complex: Final = 0 +Nonconvex: Final = 1 +Convex: Final = 2 +ArcChord: Final = 0 +ArcPieSlice: Final = 1 +GCFunction: Final = 0x000001 +GCPlaneMask: Final = 0x000002 +GCForeground: Final = 0x000004 +GCBackground: Final = 0x000008 +GCLineWidth: Final = 0x000010 +GCLineStyle: Final = 0x000020 +GCCapStyle: Final = 0x000040 +GCJoinStyle: Final = 0x000080 +GCFillStyle: Final = 0x000100 +GCFillRule: Final = 0x000200 +GCTile: Final = 0x000400 +GCStipple: Final = 0x000800 +GCTileStipXOrigin: Final = 0x001000 +GCTileStipYOrigin: Final = 0x002000 +GCFont: Final = 0x004000 +GCSubwindowMode: Final = 0x008000 +GCGraphicsExposures: Final = 0x010000 +GCClipXOrigin: Final = 0x020000 +GCClipYOrigin: Final = 0x040000 +GCClipMask: Final = 0x080000 +GCDashOffset: Final = 0x100000 +GCDashList: Final = 0x200000 +GCArcMode: Final = 0x400000 +GCLastBit: Final = 22 +FontLeftToRight: Final = 0 +FontRightToLeft: Final = 1 +FontChange: Final = 255 +XYBitmap: Final = 0 +XYPixmap: Final = 1 +ZPixmap: Final = 2 +AllocNone: Final = 0 +AllocAll: Final = 1 +DoRed: Final = 0x1 +DoGreen: Final = 0x2 +DoBlue: Final = 0x4 +CursorShape: Final = 0 +TileShape: Final = 1 +StippleShape: Final = 2 +AutoRepeatModeOff: Final = 0 +AutoRepeatModeOn: Final = 1 +AutoRepeatModeDefault: Final = 2 +LedModeOff: Final = 0 +LedModeOn: Final = 1 +KBKeyClickPercent: Final = 0x01 +KBBellPercent: Final = 0x02 +KBBellPitch: Final = 0x04 +KBBellDuration: Final = 0x08 +KBLed: Final = 0x10 +KBLedMode: Final = 0x20 +KBKey: Final = 0x40 +KBAutoRepeatMode: Final = 0x80 +MappingSuccess: Final = 0 +MappingBusy: Final = 1 +MappingFailed: Final = 2 +MappingModifier: Final = 0 +MappingKeyboard: Final = 1 +MappingPointer: Final = 2 +DontPreferBlanking: Final = 0 +PreferBlanking: Final = 1 +DefaultBlanking: Final = 2 +DisableScreenSaver: Final = 0 +DisableScreenInterval: Final = 0 +DontAllowExposures: Final = 0 +AllowExposures: Final = 1 +DefaultExposures: Final = 2 +ScreenSaverReset: Final = 0 +ScreenSaverActive: Final = 1 +HostInsert: Final = 0 +HostDelete: Final = 1 +EnableAccess: Final = 1 +DisableAccess: Final = 0 +StaticGray: Final = 0 +GrayScale: Final = 1 +StaticColor: Final = 2 +PseudoColor: Final = 3 +TrueColor: Final = 4 +DirectColor: Final = 5 +LSBFirst: Final = 0 +MSBFirst: Final = 1 diff --git a/stubs/python-xlib/Xlib/XK.pyi b/stubs/python-xlib/Xlib/XK.pyi new file mode 100644 index 000000000000..01ad548182df --- /dev/null +++ b/stubs/python-xlib/Xlib/XK.pyi @@ -0,0 +1,7 @@ +from Xlib.keysymdef.latin1 import * +from Xlib.keysymdef.miscellany import * +from Xlib.X import NoSymbol as NoSymbol + +def string_to_keysym(keysym: str) -> int: ... +def load_keysym_group(group: str) -> None: ... +def keysym_to_string(keysym: int) -> str | None: ... diff --git a/stubs/python-xlib/Xlib/Xatom.pyi b/stubs/python-xlib/Xlib/Xatom.pyi new file mode 100644 index 000000000000..5f71b24f0d92 --- /dev/null +++ b/stubs/python-xlib/Xlib/Xatom.pyi @@ -0,0 +1,71 @@ +from typing import Final + +PRIMARY: Final = 1 +SECONDARY: Final = 2 +ARC: Final = 3 +ATOM: Final = 4 +BITMAP: Final = 5 +CARDINAL: Final = 6 +COLORMAP: Final = 7 +CURSOR: Final = 8 +CUT_BUFFER0: Final = 9 +CUT_BUFFER1: Final = 10 +CUT_BUFFER2: Final = 11 +CUT_BUFFER3: Final = 12 +CUT_BUFFER4: Final = 13 +CUT_BUFFER5: Final = 14 +CUT_BUFFER6: Final = 15 +CUT_BUFFER7: Final = 16 +DRAWABLE: Final = 17 +FONT: Final = 18 +INTEGER: Final = 19 +PIXMAP: Final = 20 +POINT: Final = 21 +RECTANGLE: Final = 22 +RESOURCE_MANAGER: Final = 23 +RGB_COLOR_MAP: Final = 24 +RGB_BEST_MAP: Final = 25 +RGB_BLUE_MAP: Final = 26 +RGB_DEFAULT_MAP: Final = 27 +RGB_GRAY_MAP: Final = 28 +RGB_GREEN_MAP: Final = 29 +RGB_RED_MAP: Final = 30 +STRING: Final = 31 +VISUALID: Final = 32 +WINDOW: Final = 33 +WM_COMMAND: Final = 34 +WM_HINTS: Final = 35 +WM_CLIENT_MACHINE: Final = 36 +WM_ICON_NAME: Final = 37 +WM_ICON_SIZE: Final = 38 +WM_NAME: Final = 39 +WM_NORMAL_HINTS: Final = 40 +WM_SIZE_HINTS: Final = 41 +WM_ZOOM_HINTS: Final = 42 +MIN_SPACE: Final = 43 +NORM_SPACE: Final = 44 +MAX_SPACE: Final = 45 +END_SPACE: Final = 46 +SUPERSCRIPT_X: Final = 47 +SUPERSCRIPT_Y: Final = 48 +SUBSCRIPT_X: Final = 49 +SUBSCRIPT_Y: Final = 50 +UNDERLINE_POSITION: Final = 51 +UNDERLINE_THICKNESS: Final = 52 +STRIKEOUT_ASCENT: Final = 53 +STRIKEOUT_DESCENT: Final = 54 +ITALIC_ANGLE: Final = 55 +X_HEIGHT: Final = 56 +QUAD_WIDTH: Final = 57 +WEIGHT: Final = 58 +POINT_SIZE: Final = 59 +RESOLUTION: Final = 60 +COPYRIGHT: Final = 61 +NOTICE: Final = 62 +FONT_NAME: Final = 63 +FAMILY_NAME: Final = 64 +FULL_NAME: Final = 65 +CAP_HEIGHT: Final = 66 +WM_CLASS: Final = 67 +WM_TRANSIENT_FOR: Final = 68 +LAST_PREDEFINED: Final = 68 diff --git a/stubs/python-xlib/Xlib/Xcursorfont.pyi b/stubs/python-xlib/Xlib/Xcursorfont.pyi new file mode 100644 index 000000000000..a4d20b804d48 --- /dev/null +++ b/stubs/python-xlib/Xlib/Xcursorfont.pyi @@ -0,0 +1,80 @@ +from typing import Final + +num_glyphs: Final = 154 +X_cursor: Final = 0 +arrow: Final = 2 +based_arrow_down: Final = 4 +based_arrow_up: Final = 6 +boat: Final = 8 +bogosity: Final = 10 +bottom_left_corner: Final = 12 +bottom_right_corner: Final = 14 +bottom_side: Final = 16 +bottom_tee: Final = 18 +box_spiral: Final = 20 +center_ptr: Final = 22 +circle: Final = 24 +clock: Final = 26 +coffee_mug: Final = 28 +cross: Final = 30 +cross_reverse: Final = 32 +crosshair: Final = 34 +diamond_cross: Final = 36 +dot: Final = 38 +dotbox: Final = 40 +double_arrow: Final = 42 +draft_large: Final = 44 +draft_small: Final = 46 +draped_box: Final = 48 +exchange: Final = 50 +fleur: Final = 52 +gobbler: Final = 54 +gumby: Final = 56 +hand1: Final = 58 +hand2: Final = 60 +heart: Final = 62 +icon: Final = 64 +iron_cross: Final = 66 +left_ptr: Final = 68 +left_side: Final = 70 +left_tee: Final = 72 +leftbutton: Final = 74 +ll_angle: Final = 76 +lr_angle: Final = 78 +man: Final = 80 +middlebutton: Final = 82 +mouse: Final = 84 +pencil: Final = 86 +pirate: Final = 88 +plus: Final = 90 +question_arrow: Final = 92 +right_ptr: Final = 94 +right_side: Final = 96 +right_tee: Final = 98 +rightbutton: Final = 100 +rtl_logo: Final = 102 +sailboat: Final = 104 +sb_down_arrow: Final = 106 +sb_h_double_arrow: Final = 108 +sb_left_arrow: Final = 110 +sb_right_arrow: Final = 112 +sb_up_arrow: Final = 114 +sb_v_double_arrow: Final = 116 +shuttle: Final = 118 +sizing: Final = 120 +spider: Final = 122 +spraycan: Final = 124 +star: Final = 126 +target: Final = 128 +tcross: Final = 130 +top_left_arrow: Final = 132 +top_left_corner: Final = 134 +top_right_corner: Final = 136 +top_side: Final = 138 +top_tee: Final = 140 +trek: Final = 142 +ul_angle: Final = 144 +umbrella: Final = 146 +ur_angle: Final = 148 +watch: Final = 150 +xterm: Final = 152 diff --git a/stubs/python-xlib/Xlib/Xutil.pyi b/stubs/python-xlib/Xlib/Xutil.pyi new file mode 100644 index 000000000000..71ee250b8ce3 --- /dev/null +++ b/stubs/python-xlib/Xlib/Xutil.pyi @@ -0,0 +1,59 @@ +from typing import Final + +NoValue: Final = 0x0000 +XValue: Final = 0x0001 +YValue: Final = 0x0002 +WidthValue: Final = 0x0004 +HeightValue: Final = 0x0008 +AllValues: Final = 0x000F +XNegative: Final = 0x0010 +YNegative: Final = 0x0020 +USPosition: Final = 0x001 +USSize: Final = 0x002 +PPosition: Final = 0x004 +PSize: Final = 0x008 +PMinSize: Final = 0x010 +PMaxSize: Final = 0x020 +PResizeInc: Final = 0x040 +PAspect: Final = 0x080 +PBaseSize: Final = 0x100 +PWinGravity: Final = 0x200 +PAllHints: Final = 252 +InputHint: Final = 0x001 +StateHint: Final = 0x002 +IconPixmapHint: Final = 0x004 +IconWindowHint: Final = 0x008 +IconPositionHint: Final = 0x010 +IconMaskHint: Final = 0x020 +WindowGroupHint: Final = 0x040 +MessageHint: Final = 0x080 +UrgencyHint: Final = 0x100 +AllHints: Final = 511 +WithdrawnState: Final = 0 +NormalState: Final = 1 +IconicState: Final = 3 +DontCareState: Final = 0 +ZoomState: Final = 2 +InactiveState: Final = 4 +RectangleOut: Final = 0 +RectangleIn: Final = 1 +RectanglePart: Final = 2 +VisualNoMask: Final = 0x0 +VisualIDMask: Final = 0x1 +VisualScreenMask: Final = 0x2 +VisualDepthMask: Final = 0x4 +VisualClassMask: Final = 0x8 +VisualRedMaskMask: Final = 0x10 +VisualGreenMaskMask: Final = 0x20 +VisualBlueMaskMask: Final = 0x40 +VisualColormapSizeMask: Final = 0x80 +VisualBitsPerRGBMask: Final = 0x100 +VisualAllMask: Final = 0x1FF +ReleaseByFreeingColormap: Final = 1 +BitmapSuccess: Final = 0 +BitmapOpenFailed: Final = 1 +BitmapFileInvalid: Final = 2 +BitmapNoMemory: Final = 3 +XCSUCCESS: Final = 0 +XCNOMEM: Final = 1 +XCNOENT: Final = 2 diff --git a/stubs/python-xlib/Xlib/__init__.pyi b/stubs/python-xlib/Xlib/__init__.pyi new file mode 100644 index 000000000000..988134c01302 --- /dev/null +++ b/stubs/python-xlib/Xlib/__init__.pyi @@ -0,0 +1,14 @@ +from Xlib import ( + XK as XK, + X as X, + Xatom as Xatom, + Xcursorfont as Xcursorfont, + Xutil as Xutil, + display as display, + error as error, + rdb as rdb, +) + +__all__ = ["X", "XK", "Xatom", "Xcursorfont", "Xutil", "display", "error", "rdb"] + +# Shared types throughout the stub diff --git a/stubs/python-xlib/Xlib/_typing.pyi b/stubs/python-xlib/Xlib/_typing.pyi new file mode 100644 index 000000000000..90f05ff16109 --- /dev/null +++ b/stubs/python-xlib/Xlib/_typing.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from typing import TypeAlias, TypeVar + +from Xlib.error import XError +from Xlib.protocol.rq import Request + +_T = TypeVar("_T") +ErrorHandler: TypeAlias = Callable[[XError, Request | None], _T] diff --git a/stubs/python-xlib/Xlib/display.pyi b/stubs/python-xlib/Xlib/display.pyi new file mode 100644 index 000000000000..66444284f836 --- /dev/null +++ b/stubs/python-xlib/Xlib/display.pyi @@ -0,0 +1,170 @@ +from collections.abc import Callable, Iterable, Sequence +from re import Pattern +from types import FunctionType, MethodType +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only + +from Xlib import error +from Xlib._typing import ErrorHandler +from Xlib.protocol import display, request, rq +from Xlib.xobject import ( + colormap as _colormap, + cursor as _cursor, + drawable as _drawable, + fontable as _fontable, + resource as _resource, +) + +_ResourceBaseClass: TypeAlias = ( + _resource.Resource + | _drawable.Drawable + | _drawable.Window + | _drawable.Pixmap + | _fontable.Fontable + | _fontable.Font + | _fontable.GC + | _colormap.Colormap + | _cursor.Cursor +) + +# Is the type of the `_resource_baseclasses` variable, defined in this file at runtime +@type_check_only +class _ResourceBaseClassesType(TypedDict): # noqa: Y049 + resource: type[_resource.Resource] + drawable: type[_drawable.Drawable] + window: type[_drawable.Window] + pixmap: type[_drawable.Pixmap] + fontable: type[_fontable.Fontable] + font: type[_fontable.Font] + gc: type[_fontable.GC] + colormap: type[_colormap.Colormap] + cursor: type[_cursor.Cursor] + +class _BaseDisplay(display.Display): + def __init__(self, display: str | None = None) -> None: ... + def get_atom(self, atomname: str, only_if_exists: bool = False) -> int: ... + +class Display: + display: _BaseDisplay + keysym_translations: dict[int, str] + extensions: list[str] + class_extension_dicts: dict[str, dict[str, FunctionType]] + display_extension_methods: dict[str, Callable[..., Any]] + extension_event: rq.DictWrapper + def __init__(self, display: str | None = None) -> None: ... + def get_display_name(self) -> str: ... + def fileno(self) -> int: ... + def close(self) -> None: ... + def set_error_handler(self, handler: ErrorHandler[object] | None) -> None: ... + def flush(self) -> None: ... + def sync(self) -> None: ... + def next_event(self) -> rq.Event: ... + def pending_events(self) -> int: ... + def has_extension(self, extension: str) -> bool: ... + + @overload + def create_resource_object(self, type: Literal["resource"], id: int) -> _resource.Resource: ... + @overload + def create_resource_object(self, type: Literal["drawable"], id: int) -> _drawable.Drawable: ... + @overload + def create_resource_object(self, type: Literal["window"], id: int) -> _drawable.Window: ... + @overload + def create_resource_object(self, type: Literal["pixmap"], id: int) -> _drawable.Pixmap: ... + @overload + def create_resource_object(self, type: Literal["fontable"], id: int) -> _fontable.Fontable: ... + @overload + def create_resource_object(self, type: Literal["font"], id: int) -> _fontable.Font: ... + @overload + def create_resource_object(self, type: Literal["gc"], id: int) -> _fontable.GC: ... + @overload + def create_resource_object(self, type: Literal["colormap"], id: int) -> _colormap.Colormap: ... + @overload + def create_resource_object(self, type: Literal["cursor"], id: int) -> _cursor.Cursor: ... + @overload + def create_resource_object(self, type: str, id: int) -> _resource.Resource: ... + + def __getattr__(self, attr: str) -> MethodType: ... + def screen(self, sno: int | None = None) -> rq.Struct: ... + def screen_count(self) -> int: ... + def get_default_screen(self) -> int: ... + def extension_add_method(self, object: str, name: str, function: Callable[..., Any]) -> None: ... + def extension_add_event(self, code: int, evt: type, name: str | None = None) -> None: ... + def extension_add_subevent(self, code: int, subcode: int | None, evt: type[rq.Event], name: str | None = None) -> None: ... + def extension_add_error(self, code: int, err: type[error.XError]) -> None: ... + def keycode_to_keysym(self, keycode: int, index: int) -> int: ... + def keysym_to_keycode(self, keysym: int) -> int: ... + def keysym_to_keycodes(self, keysym: int) -> Iterable[tuple[int, int]]: ... + def refresh_keyboard_mapping(self, evt: rq.Event) -> None: ... + def lookup_string(self, keysym: int) -> str | None: ... + def rebind_string(self, keysym: int, newstring: str | None) -> None: ... + def intern_atom(self, name: str, only_if_exists: bool = False) -> int: ... + def get_atom(self, atom: str, only_if_exists: bool = False) -> int: ... + def get_atom_name(self, atom: int) -> str: ... + def get_selection_owner(self, selection: int) -> int: ... + def send_event( + self, + destination: int, + event: rq.Event, + event_mask: int = 0, + propagate: bool = False, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def ungrab_pointer(self, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def change_active_pointer_grab( + self, event_mask: int, cursor: _cursor.Cursor, time: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def ungrab_keyboard(self, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def allow_events(self, mode: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def grab_server(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def ungrab_server(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def warp_pointer( + self, + x: int, + y: int, + src_window: int = 0, + src_x: int = 0, + src_y: int = 0, + src_width: int = 0, + src_height: int = 0, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def set_input_focus(self, focus: int, revert_to: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_input_focus(self) -> request.GetInputFocus: ... + def query_keymap(self) -> bytes: ... # TODO: Validate if this is correct + def open_font(self, name: str) -> _ResourceBaseClass | None: ... + def list_fonts(self, pattern: Pattern[str] | str, max_names: int) -> list[str]: ... + def list_fonts_with_info(self, pattern: Pattern[str] | str, max_names: int) -> request.ListFontsWithInfo: ... + def set_font_path(self, path: Sequence[str], onerror: ErrorHandler[object] | None = None) -> None: ... + def get_font_path(self) -> list[str]: ... + def query_extension(self, name: str) -> request.QueryExtension | None: ... + def list_extensions(self) -> list[str]: ... + def change_keyboard_mapping( + self, first_keycode: int, keysyms: Sequence[Sequence[int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def get_keyboard_mapping(self, first_keycode: int, count: int) -> list[tuple[int, ...]]: ... + def change_keyboard_control(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def get_keyboard_control(self) -> request.GetKeyboardControl: ... + def bell(self, percent: int = 0, onerror: ErrorHandler[object] | None = None) -> None: ... + def change_pointer_control( + self, accel: tuple[int, int] | None = None, threshold: int | None = None, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def get_pointer_control(self) -> request.GetPointerControl: ... + def set_screen_saver( + self, timeout: int, interval: int, prefer_blank: int, allow_exposures: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def get_screen_saver(self) -> request.GetScreenSaver: ... + def change_hosts( + self, + mode: int, + host_family: int, + host: Sequence[int] | Sequence[bytes], # TODO: validate + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def list_hosts(self) -> request.ListHosts: ... + def set_access_control(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_close_down_mode(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def force_screen_saver(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_pointer_mapping(self, map: Sequence[int]) -> int: ... + def get_pointer_mapping(self) -> list[int]: ... + def set_modifier_mapping(self, keycodes: rq._ModifierMappingList8Elements) -> int: ... + def get_modifier_mapping(self) -> Sequence[Sequence[int]]: ... + def no_operation(self, onerror: ErrorHandler[object] | None = None) -> None: ... diff --git a/stubs/python-xlib/Xlib/error.pyi b/stubs/python-xlib/Xlib/error.pyi new file mode 100644 index 000000000000..e78f9130f896 --- /dev/null +++ b/stubs/python-xlib/Xlib/error.pyi @@ -0,0 +1,57 @@ +from _typeshed import SliceableBuffer +from typing import Final, Literal + +from Xlib.protocol import display, rq + +class DisplayError(Exception): + display: object + def __init__(self, display: object) -> None: ... + +class DisplayNameError(DisplayError): ... + +class DisplayConnectionError(DisplayError): + display: object + msg: object + def __init__(self, display: object, msg: object) -> None: ... + +class ConnectionClosedError(Exception): + whom: object + def __init__(self, whom: object) -> None: ... + +class XauthError(Exception): ... +class XNoAuthError(Exception): ... +class ResourceIDError(Exception): ... + +class XError(rq.GetAttrData, Exception): + def __init__(self, display: display.Display, data: SliceableBuffer) -> None: ... + +class XResourceError(XError): ... +class BadRequest(XError): ... +class BadValue(XError): ... +class BadWindow(XResourceError): ... +class BadPixmap(XResourceError): ... +class BadAtom(XError): ... +class BadCursor(XResourceError): ... +class BadFont(XResourceError): ... +class BadMatch(XError): ... +class BadDrawable(XResourceError): ... +class BadAccess(XError): ... +class BadAlloc(XError): ... +class BadColor(XResourceError): ... +class BadGC(XResourceError): ... +class BadIDChoice(XResourceError): ... +class BadName(XError): ... +class BadLength(XError): ... +class BadImplementation(XError): ... + +xerror_class: Final[dict[int, type[XError]]] + +class CatchError: + error_types: tuple[type[XError], ...] + error: XError | None + request: rq.Request | None + def __init__(self, *errors: type[XError]) -> None: ... + def __call__(self, error: XError, request: rq.Request | None) -> Literal[0, 1]: ... + def get_error(self) -> XError | None: ... + def get_request(self) -> rq.Request | None: ... + def reset(self) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/__init__.pyi b/stubs/python-xlib/Xlib/ext/__init__.pyi new file mode 100644 index 000000000000..17afcdcac8f2 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/__init__.pyi @@ -0,0 +1,35 @@ +from Xlib.ext import ( + composite as composite, + damage as damage, + dpms as dpms, + ge as ge, + nvcontrol as nvcontrol, + randr as randr, + record as record, + res as res, + screensaver as screensaver, + security as security, + shape as shape, + xfixes as xfixes, + xinerama as xinerama, + xinput as xinput, + xtest as xtest, +) + +__all__ = [ + "ge", + "xtest", + "shape", + "xinerama", + "record", + "composite", + "randr", + "xfixes", + "security", + "xinput", + "nvcontrol", + "damage", + "dpms", + "res", + "screensaver", +] diff --git a/stubs/python-xlib/Xlib/ext/composite.pyi b/stubs/python-xlib/Xlib/ext/composite.pyi new file mode 100644 index 000000000000..9582ae777e6c --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/composite.pyi @@ -0,0 +1,47 @@ +from _typeshed import Unused +from collections.abc import Callable +from typing import Any, Final, TypeAlias + +from Xlib._typing import ErrorHandler +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import drawable, resource + +_Update: TypeAlias = Callable[[rq.DictWrapper | dict[str, Any]], object] + +extname: Final = "Composite" +RedirectAutomatic: Final = 0 +RedirectManual: Final = 1 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class RedirectWindow(rq.Request): ... + +def redirect_window(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class RedirectSubwindows(rq.Request): ... + +def redirect_subwindows(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class UnredirectWindow(rq.Request): ... + +def unredirect_window(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class UnredirectSubindows(rq.Request): ... + +def unredirect_subwindows(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class CreateRegionFromBorderClip(rq.Request): ... + +def create_region_from_border_clip(self: drawable.Window, onerror: ErrorHandler[object] | None = None) -> int: ... + +class NameWindowPixmap(rq.Request): ... + +def name_window_pixmap(self: Display | resource.Resource, onerror: ErrorHandler[object] | None = None) -> drawable.Pixmap: ... + +class GetOverlayWindow(rq.ReplyRequest): ... + +def get_overlay_window(self: Display) -> GetOverlayWindow: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/damage.pyi b/stubs/python-xlib/Xlib/ext/damage.pyi new file mode 100644 index 000000000000..27320b17e444 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/damage.pyi @@ -0,0 +1,41 @@ +from typing import Final, Literal + +from Xlib.display import Display +from Xlib.error import XError +from Xlib.protocol import request, rq +from Xlib.xobject import resource + +extname: Final = "DAMAGE" +DamageNotifyCode: Final = 0 +BadDamageCode: Final = 0 +DamageReportRawRectangles: Final = 0 +DamageReportDeltaRectangles: Final = 1 +DamageReportBoundingBox: Final = 2 +DamageReportNonEmpty: Final = 3 +DamageReportLevel: Final[tuple[Literal[0], Literal[1], Literal[2], Literal[3]]] +DAMAGE = rq.Card32 + +class BadDamageError(XError): ... +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class DamageCreate(rq.Request): ... + +def damage_create(self: Display | resource.Resource, level: int) -> int: ... + +class DamageDestroy(rq.Request): ... + +def damage_destroy(self: Display | resource.Resource, damage: int) -> None: ... + +class DamageSubtract(rq.Request): ... + +def damage_subtract(self: Display | resource.Resource, damage: int, repair: int = 0, parts: int = 0) -> None: ... + +class DamageAdd(rq.Request): ... + +def damage_add(self: Display | resource.Resource, repair: int, parts: int) -> None: ... + +class DamageNotify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/dpms.pyi b/stubs/python-xlib/Xlib/ext/dpms.pyi new file mode 100644 index 000000000000..1319a5c88442 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/dpms.pyi @@ -0,0 +1,48 @@ +from _typeshed import Unused +from typing import Final, Literal + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "DPMS" +DPMSModeOn: Final = 0 +DPMSModeStandby: Final = 1 +DPMSModeSuspend: Final = 2 +DPMSModeOff: Final = 3 +DPMSPowerLevel: Final[tuple[Literal[0], Literal[1], Literal[2], Literal[3]]] + +class DPMSGetVersion(rq.ReplyRequest): ... + +def get_version(self: Display | resource.Resource) -> DPMSGetVersion: ... + +class DPMSCapable(rq.ReplyRequest): ... + +def capable(self: Display | resource.Resource) -> DPMSCapable: ... + +class DPMSGetTimeouts(rq.ReplyRequest): ... + +def get_timeouts(self: Display | resource.Resource) -> DPMSGetTimeouts: ... + +class DPMSSetTimeouts(rq.Request): ... + +def set_timeouts( + self: Display | resource.Resource, standby_timeout: int, suspend_timeout: int, off_timeout: int +) -> DPMSSetTimeouts: ... + +class DPMSEnable(rq.Request): ... + +def enable(self: Display | resource.Resource) -> DPMSEnable: ... + +class DPMSDisable(rq.Request): ... + +def disable(self: Display | resource.Resource) -> DPMSDisable: ... + +class DPMSForceLevel(rq.Request): ... + +def force_level(self: Display | resource.Resource, power_level: int) -> DPMSForceLevel: ... + +class DPMSInfo(rq.ReplyRequest): ... + +def info(self: Display | resource.Resource) -> DPMSInfo: ... +def init(disp: Display, _info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/ge.pyi b/stubs/python-xlib/Xlib/ext/ge.pyi new file mode 100644 index 000000000000..1689e2af60c8 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/ge.pyi @@ -0,0 +1,18 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "Generic Event Extension" +GenericEventCode: Final = 35 + +class GEQueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> GEQueryVersion: ... + +class GenericEvent(rq.Event): ... + +def add_event_data(self: Display | resource.Resource, extension: int, evtype: int, estruct: int) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/nvcontrol.pyi b/stubs/python-xlib/Xlib/ext/nvcontrol.pyi new file mode 100644 index 000000000000..e8087a1ee37b --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/nvcontrol.pyi @@ -0,0 +1,1065 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "NV-CONTROL" + +def query_target_count(self: Display | resource.Resource, target: Target) -> int: ... +def query_int_attribute(self: Display | resource.Resource, target: Target, display_mask: int, attr: int) -> int | None: ... +def set_int_attribute(self: Display | resource.Resource, target: Target, display_mask: int, attr: int, value: int) -> bool: ... +def query_string_attribute(self: Display | resource.Resource, target: Target, display_mask: int, attr: int) -> str | None: ... +def query_valid_attr_values( + self: Display | resource.Resource, target: Target, display_mask: int, attr: int +) -> tuple[int, int] | None: ... +def query_binary_data(self: Display | resource.Resource, target: Target, display_mask: int, attr: int) -> bytes | None: ... +def get_coolers_used_by_gpu(self: Display | resource.Resource, target: Target) -> list[int] | None: ... +def get_gpu_count(self: Display | resource.Resource) -> int: ... +def get_name(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_driver_version(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_vbios_version(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_gpu_uuid(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_utilization_rates(self: Display | resource.Resource, target: Target) -> dict[str, str | int]: ... +def get_performance_modes(self: Display | resource.Resource, target: Target) -> list[dict[str, str | int]]: ... +def get_clock_info(self: Display | resource.Resource, target: Target) -> dict[str, str | int]: ... +def get_vram(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_irq(self: Display | resource.Resource, target: Target) -> int | None: ... +def supports_framelock(self: Display | resource.Resource, target: Target) -> int | None: ... +def gvo_supported(self: Display | resource.Resource, screen: Target) -> int | None: ... +def get_core_temp(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_core_threshold(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_default_core_threshold(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_max_core_threshold(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_ambient_temp(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_cuda_cores(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_memory_bus_width(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_total_dedicated_gpu_memory(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_used_dedicated_gpu_memory(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_curr_pcie_link_width(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_max_pcie_link_width(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_curr_pcie_link_generation(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_encoder_utilization(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_decoder_utilization(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_current_performance_level(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_gpu_nvclock_offset(self: Display | resource.Resource, target: Target, perf_level: int) -> int | None: ... +def set_gpu_nvclock_offset(self: Display | resource.Resource, target: Target, perf_level: int, offset: int) -> bool: ... +def set_gpu_nvclock_offset_all_levels(self: Display | resource.Resource, target: Target, offset: int) -> bool: ... +def get_gpu_nvclock_offset_range( + self: Display | resource.Resource, target: Target, perf_level: int +) -> tuple[int, int] | None: ... +def get_mem_transfer_rate_offset(self: Display | resource.Resource, target: Target, perf_level: int) -> int | None: ... +def set_mem_transfer_rate_offset(self: Display | resource.Resource, target: Target, perf_level: int, offset: int) -> bool: ... +def set_mem_transfer_rate_offset_all_levels(self: Display | resource.Resource, target: Target, offset: int) -> bool: ... +def get_mem_transfer_rate_offset_range( + self: Display | resource.Resource, target: Target, perf_level: int +) -> tuple[int, int] | None: ... +def get_cooler_manual_control_enabled(self: Display | resource.Resource, target: Target) -> int | None: ... +def set_cooler_manual_control_enabled(self: Display | resource.Resource, target: Target, enabled: bool) -> bool: ... +def get_fan_duty(self: Display | resource.Resource, target: Target) -> int | None: ... +def set_fan_duty(self: Display | resource.Resource, cooler: Target, speed: int) -> bool: ... +def get_fan_rpm(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_max_displays(self: Display | resource.Resource, target: Target) -> int | None: ... +def init(disp: Display, info: Unused) -> None: ... + +NV_CTRL_FLATPANEL_SCALING: Final = 2 +NV_CTRL_FLATPANEL_SCALING_DEFAULT: Final = 0 +NV_CTRL_FLATPANEL_SCALING_NATIVE: Final = 1 +NV_CTRL_FLATPANEL_SCALING_SCALED: Final = 2 +NV_CTRL_FLATPANEL_SCALING_CENTERED: Final = 3 +NV_CTRL_FLATPANEL_SCALING_ASPECT_SCALED: Final = 4 +NV_CTRL_FLATPANEL_DITHERING: Final = 3 +NV_CTRL_FLATPANEL_DITHERING_DEFAULT: Final = 0 +NV_CTRL_FLATPANEL_DITHERING_ENABLED: Final = 1 +NV_CTRL_FLATPANEL_DITHERING_DISABLED: Final = 2 +NV_CTRL_DITHERING: Final = 3 +NV_CTRL_DITHERING_AUTO: Final = 0 +NV_CTRL_DITHERING_ENABLED: Final = 1 +NV_CTRL_DITHERING_DISABLED: Final = 2 +NV_CTRL_DIGITAL_VIBRANCE: Final = 4 +NV_CTRL_BUS_TYPE: Final = 5 +NV_CTRL_BUS_TYPE_AGP: Final = 0 +NV_CTRL_BUS_TYPE_PCI: Final = 1 +NV_CTRL_BUS_TYPE_PCI_EXPRESS: Final = 2 +NV_CTRL_BUS_TYPE_INTEGRATED: Final = 3 +NV_CTRL_TOTAL_GPU_MEMORY: Final = 6 +NV_CTRL_VIDEO_RAM: Final = NV_CTRL_TOTAL_GPU_MEMORY +NV_CTRL_IRQ: Final = 7 +NV_CTRL_OPERATING_SYSTEM: Final = 8 +NV_CTRL_OPERATING_SYSTEM_LINUX: Final = 0 +NV_CTRL_OPERATING_SYSTEM_FREEBSD: Final = 1 +NV_CTRL_OPERATING_SYSTEM_SUNOS: Final = 2 +NV_CTRL_SYNC_TO_VBLANK: Final = 9 +NV_CTRL_SYNC_TO_VBLANK_OFF: Final = 0 +NV_CTRL_SYNC_TO_VBLANK_ON: Final = 1 +NV_CTRL_LOG_ANISO: Final = 10 +NV_CTRL_FSAA_MODE: Final = 11 +NV_CTRL_FSAA_MODE_NONE: Final = 0 +NV_CTRL_FSAA_MODE_2x: Final = 1 +NV_CTRL_FSAA_MODE_2x_5t: Final = 2 +NV_CTRL_FSAA_MODE_15x15: Final = 3 +NV_CTRL_FSAA_MODE_2x2: Final = 4 +NV_CTRL_FSAA_MODE_4x: Final = 5 +NV_CTRL_FSAA_MODE_4x_9t: Final = 6 +NV_CTRL_FSAA_MODE_8x: Final = 7 +NV_CTRL_FSAA_MODE_16x: Final = 8 +NV_CTRL_FSAA_MODE_8xS: Final = 9 +NV_CTRL_FSAA_MODE_8xQ: Final = 10 +NV_CTRL_FSAA_MODE_16xS: Final = 11 +NV_CTRL_FSAA_MODE_16xQ: Final = 12 +NV_CTRL_FSAA_MODE_32xS: Final = 13 +NV_CTRL_FSAA_MODE_32x: Final = 14 +NV_CTRL_FSAA_MODE_64xS: Final = 15 +NV_CTRL_FSAA_MODE_MAX: Final = NV_CTRL_FSAA_MODE_64xS +NV_CTRL_UBB: Final = 13 +NV_CTRL_UBB_OFF: Final = 0 +NV_CTRL_UBB_ON: Final = 1 +NV_CTRL_OVERLAY: Final = 14 +NV_CTRL_OVERLAY_OFF: Final = 0 +NV_CTRL_OVERLAY_ON: Final = 1 +NV_CTRL_STEREO: Final = 16 +NV_CTRL_STEREO_OFF: Final = 0 +NV_CTRL_STEREO_DDC: Final = 1 +NV_CTRL_STEREO_BLUELINE: Final = 2 +NV_CTRL_STEREO_DIN: Final = 3 +NV_CTRL_STEREO_PASSIVE_EYE_PER_DPY: Final = 4 +NV_CTRL_STEREO_VERTICAL_INTERLACED: Final = 5 +NV_CTRL_STEREO_COLOR_INTERLACED: Final = 6 +NV_CTRL_STEREO_HORIZONTAL_INTERLACED: Final = 7 +NV_CTRL_STEREO_CHECKERBOARD_PATTERN: Final = 8 +NV_CTRL_STEREO_INVERSE_CHECKERBOARD_PATTERN: Final = 9 +NV_CTRL_STEREO_3D_VISION: Final = 10 +NV_CTRL_STEREO_3D_VISION_PRO: Final = 11 +NV_CTRL_STEREO_HDMI_3D: Final = 12 +NV_CTRL_STEREO_TRIDELITY_SL: Final = 13 +NV_CTRL_STEREO_INBAND_STEREO_SIGNALING: Final = 14 +NV_CTRL_STEREO_MAX: Final = NV_CTRL_STEREO_INBAND_STEREO_SIGNALING +NV_CTRL_EMULATE: Final = 17 +NV_CTRL_EMULATE_NONE: Final = 0 +NV_CTRL_TWINVIEW: Final = 18 +NV_CTRL_TWINVIEW_NOT_ENABLED: Final = 0 +NV_CTRL_TWINVIEW_ENABLED: Final = 1 +NV_CTRL_CONNECTED_DISPLAYS: Final = 19 +NV_CTRL_ENABLED_DISPLAYS: Final = 20 +NV_CTRL_FRAMELOCK: Final = 21 +NV_CTRL_FRAMELOCK_NOT_SUPPORTED: Final = 0 +NV_CTRL_FRAMELOCK_SUPPORTED: Final = 1 +NV_CTRL_FRAMELOCK_MASTER: Final = 22 +NV_CTRL_FRAMELOCK_MASTER_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_MASTER_TRUE: Final = 1 +NV_CTRL_FRAMELOCK_POLARITY: Final = 23 +NV_CTRL_FRAMELOCK_POLARITY_RISING_EDGE: Final = 0x1 +NV_CTRL_FRAMELOCK_POLARITY_FALLING_EDGE: Final = 0x2 +NV_CTRL_FRAMELOCK_POLARITY_BOTH_EDGES: Final = 0x3 +NV_CTRL_FRAMELOCK_SYNC_DELAY: Final = 24 +NV_CTRL_FRAMELOCK_SYNC_DELAY_MAX: Final = 2047 +NV_CTRL_FRAMELOCK_SYNC_DELAY_FACTOR: Final[float] +NV_CTRL_FRAMELOCK_SYNC_INTERVAL: Final = 25 +NV_CTRL_FRAMELOCK_PORT0_STATUS: Final = 26 +NV_CTRL_FRAMELOCK_PORT0_STATUS_INPUT: Final = 0 +NV_CTRL_FRAMELOCK_PORT0_STATUS_OUTPUT: Final = 1 +NV_CTRL_FRAMELOCK_PORT1_STATUS: Final = 27 +NV_CTRL_FRAMELOCK_PORT1_STATUS_INPUT: Final = 0 +NV_CTRL_FRAMELOCK_PORT1_STATUS_OUTPUT: Final = 1 +NV_CTRL_FRAMELOCK_HOUSE_STATUS: Final = 28 +NV_CTRL_FRAMELOCK_HOUSE_STATUS_NOT_DETECTED: Final = 0 +NV_CTRL_FRAMELOCK_HOUSE_STATUS_DETECTED: Final = 1 +NV_CTRL_FRAMELOCK_SYNC: Final = 29 +NV_CTRL_FRAMELOCK_SYNC_DISABLE: Final = 0 +NV_CTRL_FRAMELOCK_SYNC_ENABLE: Final = 1 +NV_CTRL_FRAMELOCK_SYNC_READY: Final = 30 +NV_CTRL_FRAMELOCK_SYNC_READY_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_SYNC_READY_TRUE: Final = 1 +NV_CTRL_FRAMELOCK_STEREO_SYNC: Final = 31 +NV_CTRL_FRAMELOCK_STEREO_SYNC_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_STEREO_SYNC_TRUE: Final = 1 +NV_CTRL_FRAMELOCK_TEST_SIGNAL: Final = 32 +NV_CTRL_FRAMELOCK_TEST_SIGNAL_DISABLE: Final = 0 +NV_CTRL_FRAMELOCK_TEST_SIGNAL_ENABLE: Final = 1 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED: Final = 33 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED_NONE: Final = 0 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED_PORT0: Final = 0x1 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED_PORT1: Final = 0x2 +NV_CTRL_FRAMELOCK_VIDEO_MODE: Final = 34 +NV_CTRL_FRAMELOCK_VIDEO_MODE_NONE: Final = 0 +NV_CTRL_FRAMELOCK_VIDEO_MODE_TTL: Final = 1 +NV_CTRL_FRAMELOCK_VIDEO_MODE_NTSCPALSECAM: Final = 2 +NV_CTRL_FRAMELOCK_VIDEO_MODE_HDTV: Final = 3 +NV_CTRL_FRAMELOCK_VIDEO_MODE_COMPOSITE_AUTO: Final = 0 +NV_CTRL_FRAMELOCK_VIDEO_MODE_COMPOSITE_BI_LEVEL: Final = 2 +NV_CTRL_FRAMELOCK_VIDEO_MODE_COMPOSITE_TRI_LEVEL: Final = 3 +NV_CTRL_FRAMELOCK_SYNC_RATE: Final = 35 +NV_CTRL_FORCE_GENERIC_CPU: Final = 37 +NV_CTRL_FORCE_GENERIC_CPU_DISABLE: Final = 0 +NV_CTRL_FORCE_GENERIC_CPU_ENABLE: Final = 1 +NV_CTRL_OPENGL_AA_LINE_GAMMA: Final = 38 +NV_CTRL_OPENGL_AA_LINE_GAMMA_DISABLE: Final = 0 +NV_CTRL_OPENGL_AA_LINE_GAMMA_ENABLE: Final = 1 +NV_CTRL_FRAMELOCK_TIMING: Final = 39 +NV_CTRL_FRAMELOCK_TIMING_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_TIMING_TRUE: Final = 1 +NV_CTRL_FLIPPING_ALLOWED: Final = 40 +NV_CTRL_FLIPPING_ALLOWED_FALSE: Final = 0 +NV_CTRL_FLIPPING_ALLOWED_TRUE: Final = 1 +NV_CTRL_ARCHITECTURE: Final = 41 +NV_CTRL_ARCHITECTURE_X86: Final = 0 +NV_CTRL_ARCHITECTURE_X86_64: Final = 1 +NV_CTRL_ARCHITECTURE_IA64: Final = 2 +NV_CTRL_ARCHITECTURE_ARM: Final = 3 +NV_CTRL_ARCHITECTURE_AARCH64: Final = 4 +NV_CTRL_ARCHITECTURE_PPC64LE: Final = 5 +NV_CTRL_TEXTURE_CLAMPING: Final = 42 +NV_CTRL_TEXTURE_CLAMPING_EDGE: Final = 0 +NV_CTRL_TEXTURE_CLAMPING_SPEC: Final = 1 +NV_CTRL_CURSOR_SHADOW: Final = 43 +NV_CTRL_CURSOR_SHADOW_DISABLE: Final = 0 +NV_CTRL_CURSOR_SHADOW_ENABLE: Final = 1 +NV_CTRL_CURSOR_SHADOW_ALPHA: Final = 44 +NV_CTRL_CURSOR_SHADOW_RED: Final = 45 +NV_CTRL_CURSOR_SHADOW_GREEN: Final = 46 +NV_CTRL_CURSOR_SHADOW_BLUE: Final = 47 +NV_CTRL_CURSOR_SHADOW_X_OFFSET: Final = 48 +NV_CTRL_CURSOR_SHADOW_Y_OFFSET: Final = 49 +NV_CTRL_FSAA_APPLICATION_CONTROLLED: Final = 50 +NV_CTRL_FSAA_APPLICATION_CONTROLLED_ENABLED: Final = 1 +NV_CTRL_FSAA_APPLICATION_CONTROLLED_DISABLED: Final = 0 +NV_CTRL_LOG_ANISO_APPLICATION_CONTROLLED: Final = 51 +NV_CTRL_LOG_ANISO_APPLICATION_CONTROLLED_ENABLED: Final = 1 +NV_CTRL_LOG_ANISO_APPLICATION_CONTROLLED_DISABLED: Final = 0 +NV_CTRL_IMAGE_SHARPENING: Final = 52 +NV_CTRL_TV_OVERSCAN: Final = 53 +NV_CTRL_TV_FLICKER_FILTER: Final = 54 +NV_CTRL_TV_BRIGHTNESS: Final = 55 +NV_CTRL_TV_HUE: Final = 56 +NV_CTRL_TV_CONTRAST: Final = 57 +NV_CTRL_TV_SATURATION: Final = 58 +NV_CTRL_TV_RESET_SETTINGS: Final = 59 +NV_CTRL_GPU_CORE_TEMPERATURE: Final = 60 +NV_CTRL_GPU_CORE_THRESHOLD: Final = 61 +NV_CTRL_GPU_DEFAULT_CORE_THRESHOLD: Final = 62 +NV_CTRL_GPU_MAX_CORE_THRESHOLD: Final = 63 +NV_CTRL_AMBIENT_TEMPERATURE: Final = 64 +NV_CTRL_PBUFFER_SCANOUT_SUPPORTED: Final = 65 +NV_CTRL_PBUFFER_SCANOUT_FALSE: Final = 0 +NV_CTRL_PBUFFER_SCANOUT_TRUE: Final = 1 +NV_CTRL_PBUFFER_SCANOUT_XID: Final = 66 +NV_CTRL_GVO_SUPPORTED: Final = 67 +NV_CTRL_GVO_SUPPORTED_FALSE: Final = 0 +NV_CTRL_GVO_SUPPORTED_TRUE: Final = 1 +NV_CTRL_GVO_SYNC_MODE: Final = 68 +NV_CTRL_GVO_SYNC_MODE_FREE_RUNNING: Final = 0 +NV_CTRL_GVO_SYNC_MODE_GENLOCK: Final = 1 +NV_CTRL_GVO_SYNC_MODE_FRAMELOCK: Final = 2 +NV_CTRL_GVO_SYNC_SOURCE: Final = 69 +NV_CTRL_GVO_SYNC_SOURCE_COMPOSITE: Final = 0 +NV_CTRL_GVO_SYNC_SOURCE_SDI: Final = 1 +NV_CTRL_GVIO_REQUESTED_VIDEO_FORMAT: Final = 70 +NV_CTRL_GVIO_VIDEO_FORMAT_NONE: Final = 0 +NV_CTRL_GVIO_VIDEO_FORMAT_487I_59_94_SMPTE259_NTSC: Final = 1 +NV_CTRL_GVIO_VIDEO_FORMAT_576I_50_00_SMPTE259_PAL: Final = 2 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_59_94_SMPTE296: Final = 3 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_60_00_SMPTE296: Final = 4 +NV_CTRL_GVIO_VIDEO_FORMAT_1035I_59_94_SMPTE260: Final = 5 +NV_CTRL_GVIO_VIDEO_FORMAT_1035I_60_00_SMPTE260: Final = 6 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_50_00_SMPTE295: Final = 7 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_50_00_SMPTE274: Final = 8 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_59_94_SMPTE274: Final = 9 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_60_00_SMPTE274: Final = 10 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_23_976_SMPTE274: Final = 11 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_24_00_SMPTE274: Final = 12 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_25_00_SMPTE274: Final = 13 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_29_97_SMPTE274: Final = 14 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_30_00_SMPTE274: Final = 15 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_50_00_SMPTE296: Final = 16 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_48_00_SMPTE274: Final = 17 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_47_96_SMPTE274: Final = 18 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_30_00_SMPTE296: Final = 19 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_29_97_SMPTE296: Final = 20 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_25_00_SMPTE296: Final = 21 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_24_00_SMPTE296: Final = 22 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_23_98_SMPTE296: Final = 23 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_25_00_SMPTE274: Final = 24 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_29_97_SMPTE274: Final = 25 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_30_00_SMPTE274: Final = 26 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_24_00_SMPTE274: Final = 27 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_23_98_SMPTE274: Final = 28 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_30_00_SMPTE372: Final = 29 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_29_97_SMPTE372: Final = 30 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_60_00_SMPTE372: Final = 31 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_59_94_SMPTE372: Final = 32 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_25_00_SMPTE372: Final = 33 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_50_00_SMPTE372: Final = 34 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_24_00_SMPTE372: Final = 35 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_23_98_SMPTE372: Final = 36 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_48_00_SMPTE372: Final = 37 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_47_96_SMPTE372: Final = 38 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_50_00_3G_LEVEL_A_SMPTE274: Final = 39 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_59_94_3G_LEVEL_A_SMPTE274: Final = 40 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_60_00_3G_LEVEL_A_SMPTE274: Final = 41 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_60_00_3G_LEVEL_B_SMPTE274: Final = 42 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_60_00_3G_LEVEL_B_SMPTE274: Final = 43 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_60_00_3G_LEVEL_B_SMPTE372: Final = 44 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_50_00_3G_LEVEL_B_SMPTE274: Final = 45 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_50_00_3G_LEVEL_B_SMPTE274: Final = 46 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_50_00_3G_LEVEL_B_SMPTE372: Final = 47 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_30_00_3G_LEVEL_B_SMPTE274: Final = 48 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_30_00_3G_LEVEL_B_SMPTE372: Final = 49 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_25_00_3G_LEVEL_B_SMPTE274: Final = 50 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_25_00_3G_LEVEL_B_SMPTE372: Final = 51 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_24_00_3G_LEVEL_B_SMPTE274: Final = 52 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_24_00_3G_LEVEL_B_SMPTE372: Final = 53 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_48_00_3G_LEVEL_B_SMPTE274: Final = 54 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_48_00_3G_LEVEL_B_SMPTE372: Final = 55 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_59_94_3G_LEVEL_B_SMPTE274: Final = 56 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_59_94_3G_LEVEL_B_SMPTE274: Final = 57 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_59_94_3G_LEVEL_B_SMPTE372: Final = 58 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_29_97_3G_LEVEL_B_SMPTE274: Final = 59 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_29_97_3G_LEVEL_B_SMPTE372: Final = 60 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_23_98_3G_LEVEL_B_SMPTE274: Final = 61 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_23_98_3G_LEVEL_B_SMPTE372: Final = 62 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_47_96_3G_LEVEL_B_SMPTE274: Final = 63 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_47_96_3G_LEVEL_B_SMPTE372: Final = 64 +NV_CTRL_GVO_OUTPUT_VIDEO_FORMAT: Final = 70 +NV_CTRL_GVO_VIDEO_FORMAT_NONE: Final = 0 +NV_CTRL_GVO_VIDEO_FORMAT_487I_59_94_SMPTE259_NTSC: Final = 1 +NV_CTRL_GVO_VIDEO_FORMAT_576I_50_00_SMPTE259_PAL: Final = 2 +NV_CTRL_GVO_VIDEO_FORMAT_720P_59_94_SMPTE296: Final = 3 +NV_CTRL_GVO_VIDEO_FORMAT_720P_60_00_SMPTE296: Final = 4 +NV_CTRL_GVO_VIDEO_FORMAT_1035I_59_94_SMPTE260: Final = 5 +NV_CTRL_GVO_VIDEO_FORMAT_1035I_60_00_SMPTE260: Final = 6 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_50_00_SMPTE295: Final = 7 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_50_00_SMPTE274: Final = 8 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_59_94_SMPTE274: Final = 9 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_60_00_SMPTE274: Final = 10 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_23_976_SMPTE274: Final = 11 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_24_00_SMPTE274: Final = 12 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_25_00_SMPTE274: Final = 13 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_29_97_SMPTE274: Final = 14 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_30_00_SMPTE274: Final = 15 +NV_CTRL_GVO_VIDEO_FORMAT_720P_50_00_SMPTE296: Final = 16 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_48_00_SMPTE274: Final = 17 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_47_96_SMPTE274: Final = 18 +NV_CTRL_GVO_VIDEO_FORMAT_720P_30_00_SMPTE296: Final = 19 +NV_CTRL_GVO_VIDEO_FORMAT_720P_29_97_SMPTE296: Final = 20 +NV_CTRL_GVO_VIDEO_FORMAT_720P_25_00_SMPTE296: Final = 21 +NV_CTRL_GVO_VIDEO_FORMAT_720P_24_00_SMPTE296: Final = 22 +NV_CTRL_GVO_VIDEO_FORMAT_720P_23_98_SMPTE296: Final = 23 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_25_00_SMPTE274: Final = 24 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_29_97_SMPTE274: Final = 25 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_30_00_SMPTE274: Final = 26 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_24_00_SMPTE274: Final = 27 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_23_98_SMPTE274: Final = 28 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_30_00_SMPTE372: Final = 29 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_29_97_SMPTE372: Final = 30 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_60_00_SMPTE372: Final = 31 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_59_94_SMPTE372: Final = 32 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_25_00_SMPTE372: Final = 33 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_50_00_SMPTE372: Final = 34 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_24_00_SMPTE372: Final = 35 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_23_98_SMPTE372: Final = 36 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_48_00_SMPTE372: Final = 37 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_47_96_SMPTE372: Final = 38 +NV_CTRL_GVIO_DETECTED_VIDEO_FORMAT: Final = 71 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT: Final = 71 +NV_CTRL_GVO_DATA_FORMAT: Final = 72 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8_TO_YCRCB444: Final = 0 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8A8_TO_YCRCBA4444: Final = 1 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8Z10_TO_YCRCBZ4444: Final = 2 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8_TO_YCRCB422: Final = 3 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8A8_TO_YCRCBA4224: Final = 4 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8Z10_TO_YCRCBZ4224: Final = 5 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8_TO_RGB444: Final = 6 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8_444_PASSTHRU: Final = 6 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8A8_TO_RGBA4444: Final = 7 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8A8_4444_PASSTHRU: Final = 7 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8Z10_TO_RGBZ4444: Final = 8 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8Z8_4444_PASSTHRU: Final = 8 +NV_CTRL_GVO_DATA_FORMAT_Y10CR10CB10_TO_YCRCB444: Final = 9 +NV_CTRL_GVO_DATA_FORMAT_X10X10X10_444_PASSTHRU: Final = 9 +NV_CTRL_GVO_DATA_FORMAT_Y10CR8CB8_TO_YCRCB444: Final = 10 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8_444_PASSTHRU: Final = 10 +NV_CTRL_GVO_DATA_FORMAT_Y10CR8CB8A10_TO_YCRCBA4444: Final = 11 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8A10_4444_PASSTHRU: Final = 11 +NV_CTRL_GVO_DATA_FORMAT_Y10CR8CB8Z10_TO_YCRCBZ4444: Final = 12 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8Z10_4444_PASSTHRU: Final = 12 +NV_CTRL_GVO_DATA_FORMAT_DUAL_R8G8B8_TO_DUAL_YCRCB422: Final = 13 +NV_CTRL_GVO_DATA_FORMAT_DUAL_Y8CR8CB8_TO_DUAL_YCRCB422: Final = 14 +NV_CTRL_GVO_DATA_FORMAT_DUAL_X8X8X8_TO_DUAL_422_PASSTHRU: Final = 14 +NV_CTRL_GVO_DATA_FORMAT_R10G10B10_TO_YCRCB422: Final = 15 +NV_CTRL_GVO_DATA_FORMAT_R10G10B10_TO_YCRCB444: Final = 16 +NV_CTRL_GVO_DATA_FORMAT_Y12CR12CB12_TO_YCRCB444: Final = 17 +NV_CTRL_GVO_DATA_FORMAT_X12X12X12_444_PASSTHRU: Final = 17 +NV_CTRL_GVO_DATA_FORMAT_R12G12B12_TO_YCRCB444: Final = 18 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8_422_PASSTHRU: Final = 19 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8A8_4224_PASSTHRU: Final = 20 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8Z8_4224_PASSTHRU: Final = 21 +NV_CTRL_GVO_DATA_FORMAT_X10X10X10_422_PASSTHRU: Final = 22 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8_422_PASSTHRU: Final = 23 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8A10_4224_PASSTHRU: Final = 24 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8Z10_4224_PASSTHRU: Final = 25 +NV_CTRL_GVO_DATA_FORMAT_X12X12X12_422_PASSTHRU: Final = 26 +NV_CTRL_GVO_DATA_FORMAT_R12G12B12_TO_YCRCB422: Final = 27 +NV_CTRL_GVO_DISPLAY_X_SCREEN: Final = 73 +NV_CTRL_GVO_DISPLAY_X_SCREEN_ENABLE: Final = 1 +NV_CTRL_GVO_DISPLAY_X_SCREEN_DISABLE: Final = 0 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECTED: Final = 74 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECTED_FALSE: Final = 0 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECTED_TRUE: Final = 1 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE: Final = 75 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE_AUTO: Final = 0 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE_BI_LEVEL: Final = 1 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE_TRI_LEVEL: Final = 2 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED: Final = 76 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED_NONE: Final = 0 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED_HD: Final = 1 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED_SD: Final = 2 +NV_CTRL_GVO_VIDEO_OUTPUTS: Final = 77 +NV_CTRL_GVO_VIDEO_OUTPUTS_NONE: Final = 0 +NV_CTRL_GVO_VIDEO_OUTPUTS_VIDEO1: Final = 1 +NV_CTRL_GVO_VIDEO_OUTPUTS_VIDEO2: Final = 2 +NV_CTRL_GVO_VIDEO_OUTPUTS_VIDEO_BOTH: Final = 3 +NV_CTRL_GVO_FIRMWARE_VERSION: Final = 78 +NV_CTRL_GVO_SYNC_DELAY_PIXELS: Final = 79 +NV_CTRL_GVO_SYNC_DELAY_LINES: Final = 80 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT_REACQUIRE: Final = 81 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT_REACQUIRE_FALSE: Final = 0 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT_REACQUIRE_TRUE: Final = 1 +NV_CTRL_GVO_GLX_LOCKED: Final = 82 +NV_CTRL_GVO_GLX_LOCKED_FALSE: Final = 0 +NV_CTRL_GVO_GLX_LOCKED_TRUE: Final = 1 +NV_CTRL_GVIO_VIDEO_FORMAT_WIDTH: Final = 83 +NV_CTRL_GVIO_VIDEO_FORMAT_HEIGHT: Final = 84 +NV_CTRL_GVIO_VIDEO_FORMAT_REFRESH_RATE: Final = 85 +NV_CTRL_GVO_VIDEO_FORMAT_WIDTH: Final = 83 +NV_CTRL_GVO_VIDEO_FORMAT_HEIGHT: Final = 84 +NV_CTRL_GVO_VIDEO_FORMAT_REFRESH_RATE: Final = 85 +NV_CTRL_GVO_X_SCREEN_PAN_X: Final = 86 +NV_CTRL_GVO_X_SCREEN_PAN_Y: Final = 87 +NV_CTRL_GPU_OVERCLOCKING_STATE: Final = 88 +NV_CTRL_GPU_OVERCLOCKING_STATE_NONE: Final = 0 +NV_CTRL_GPU_OVERCLOCKING_STATE_MANUAL: Final = 1 +NV_CTRL_GPU_2D_CLOCK_FREQS: Final = 89 +NV_CTRL_GPU_3D_CLOCK_FREQS: Final = 90 +NV_CTRL_GPU_DEFAULT_2D_CLOCK_FREQS: Final = 91 +NV_CTRL_GPU_DEFAULT_3D_CLOCK_FREQS: Final = 92 +NV_CTRL_GPU_CURRENT_CLOCK_FREQS: Final = 93 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS: Final = 94 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_INVALID: Final = 0 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION: Final = 95 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_START: Final = 0 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_CANCEL: Final = 1 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_STATE: Final = 96 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_STATE_IDLE: Final = 0 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_STATE_BUSY: Final = 1 +NV_CTRL_FLATPANEL_CHIP_LOCATION: Final = 215 +NV_CTRL_FLATPANEL_CHIP_LOCATION_INTERNAL: Final = 0 +NV_CTRL_FLATPANEL_CHIP_LOCATION_EXTERNAL: Final = 1 +NV_CTRL_FLATPANEL_LINK: Final = 216 +NV_CTRL_FLATPANEL_LINK_SINGLE: Final = 0 +NV_CTRL_FLATPANEL_LINK_DUAL: Final = 1 +NV_CTRL_FLATPANEL_LINK_QUAD: Final = 3 +NV_CTRL_FLATPANEL_SIGNAL: Final = 217 +NV_CTRL_FLATPANEL_SIGNAL_LVDS: Final = 0 +NV_CTRL_FLATPANEL_SIGNAL_TMDS: Final = 1 +NV_CTRL_FLATPANEL_SIGNAL_DISPLAYPORT: Final = 2 +NV_CTRL_USE_HOUSE_SYNC: Final = 218 +NV_CTRL_USE_HOUSE_SYNC_DISABLED: Final = 0 +NV_CTRL_USE_HOUSE_SYNC_INPUT: Final = 1 +NV_CTRL_USE_HOUSE_SYNC_OUTPUT: Final = 2 +NV_CTRL_USE_HOUSE_SYNC_FALSE: Final = 0 +NV_CTRL_USE_HOUSE_SYNC_TRUE: Final = 1 +NV_CTRL_EDID_AVAILABLE: Final = 219 +NV_CTRL_EDID_AVAILABLE_FALSE: Final = 0 +NV_CTRL_EDID_AVAILABLE_TRUE: Final = 1 +NV_CTRL_FORCE_STEREO: Final = 220 +NV_CTRL_FORCE_STEREO_FALSE: Final = 0 +NV_CTRL_FORCE_STEREO_TRUE: Final = 1 +NV_CTRL_IMAGE_SETTINGS: Final = 221 +NV_CTRL_IMAGE_SETTINGS_HIGH_QUALITY: Final = 0 +NV_CTRL_IMAGE_SETTINGS_QUALITY: Final = 1 +NV_CTRL_IMAGE_SETTINGS_PERFORMANCE: Final = 2 +NV_CTRL_IMAGE_SETTINGS_HIGH_PERFORMANCE: Final = 3 +NV_CTRL_XINERAMA: Final = 222 +NV_CTRL_XINERAMA_OFF: Final = 0 +NV_CTRL_XINERAMA_ON: Final = 1 +NV_CTRL_XINERAMA_STEREO: Final = 223 +NV_CTRL_XINERAMA_STEREO_FALSE: Final = 0 +NV_CTRL_XINERAMA_STEREO_TRUE: Final = 1 +NV_CTRL_BUS_RATE: Final = 224 +NV_CTRL_GPU_PCIE_MAX_LINK_WIDTH: Final = NV_CTRL_BUS_RATE +NV_CTRL_SHOW_SLI_VISUAL_INDICATOR: Final = 225 +NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_SHOW_SLI_HUD: Final = NV_CTRL_SHOW_SLI_VISUAL_INDICATOR +NV_CTRL_SHOW_SLI_HUD_FALSE: Final = NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_FALSE +NV_CTRL_SHOW_SLI_HUD_TRUE: Final = NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_TRUE +NV_CTRL_XV_SYNC_TO_DISPLAY: Final = 226 +NV_CTRL_GVIO_REQUESTED_VIDEO_FORMAT2: Final = 227 +NV_CTRL_GVO_OUTPUT_VIDEO_FORMAT2: Final = 227 +NV_CTRL_GVO_OVERRIDE_HW_CSC: Final = 228 +NV_CTRL_GVO_OVERRIDE_HW_CSC_FALSE: Final = 0 +NV_CTRL_GVO_OVERRIDE_HW_CSC_TRUE: Final = 1 +NV_CTRL_GVO_CAPABILITIES: Final = 229 +NV_CTRL_GVO_CAPABILITIES_APPLY_CSC_IMMEDIATELY: Final = 0x00000001 +NV_CTRL_GVO_CAPABILITIES_APPLY_CSC_TO_X_SCREEN: Final = 0x00000002 +NV_CTRL_GVO_CAPABILITIES_COMPOSITE_TERMINATION: Final = 0x00000004 +NV_CTRL_GVO_CAPABILITIES_SHARED_SYNC_BNC: Final = 0x00000008 +NV_CTRL_GVO_CAPABILITIES_MULTIRATE_SYNC: Final = 0x00000010 +NV_CTRL_GVO_CAPABILITIES_ADVANCE_SYNC_SKEW: Final = 0x00000020 +NV_CTRL_GVO_COMPOSITE_TERMINATION: Final = 230 +NV_CTRL_GVO_COMPOSITE_TERMINATION_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE_TERMINATION_DISABLE: Final = 0 +NV_CTRL_ASSOCIATED_DISPLAY_DEVICES: Final = 231 +NV_CTRL_FRAMELOCK_SLAVES: Final = 232 +NV_CTRL_FRAMELOCK_MASTERABLE: Final = 233 +NV_CTRL_PROBE_DISPLAYS: Final = 234 +NV_CTRL_REFRESH_RATE: Final = 235 +NV_CTRL_GVO_FLIP_QUEUE_SIZE: Final = 236 +NV_CTRL_CURRENT_SCANLINE: Final = 237 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT: Final = 238 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_FORCE_SYSMEM: Final = 0 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_SYSMEM: Final = 1 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_VIDMEM: Final = 2 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_RESERVED: Final = 3 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_GPU_SYSMEM: Final = 4 +NV_CTRL_PCI_BUS: Final = 239 +NV_CTRL_PCI_DEVICE: Final = 240 +NV_CTRL_PCI_FUNCTION: Final = 241 +NV_CTRL_FRAMELOCK_FPGA_REVISION: Final = 242 +NV_CTRL_MAX_SCREEN_WIDTH: Final = 243 +NV_CTRL_MAX_SCREEN_HEIGHT: Final = 244 +NV_CTRL_MAX_DISPLAYS: Final = 245 +NV_CTRL_DYNAMIC_TWINVIEW: Final = 246 +NV_CTRL_MULTIGPU_DISPLAY_OWNER: Final = 247 +NV_CTRL_GPU_SCALING: Final = 248 +NV_CTRL_GPU_SCALING_TARGET_INVALID: Final = 0 +NV_CTRL_GPU_SCALING_TARGET_FLATPANEL_BEST_FIT: Final = 1 +NV_CTRL_GPU_SCALING_TARGET_FLATPANEL_NATIVE: Final = 2 +NV_CTRL_GPU_SCALING_METHOD_INVALID: Final = 0 +NV_CTRL_GPU_SCALING_METHOD_STRETCHED: Final = 1 +NV_CTRL_GPU_SCALING_METHOD_CENTERED: Final = 2 +NV_CTRL_GPU_SCALING_METHOD_ASPECT_SCALED: Final = 3 +NV_CTRL_FRONTEND_RESOLUTION: Final = 249 +NV_CTRL_BACKEND_RESOLUTION: Final = 250 +NV_CTRL_FLATPANEL_NATIVE_RESOLUTION: Final = 251 +NV_CTRL_FLATPANEL_BEST_FIT_RESOLUTION: Final = 252 +NV_CTRL_GPU_SCALING_ACTIVE: Final = 253 +NV_CTRL_DFP_SCALING_ACTIVE: Final = 254 +NV_CTRL_FSAA_APPLICATION_ENHANCED: Final = 255 +NV_CTRL_FSAA_APPLICATION_ENHANCED_ENABLED: Final = 1 +NV_CTRL_FSAA_APPLICATION_ENHANCED_DISABLED: Final = 0 +NV_CTRL_FRAMELOCK_SYNC_RATE_4: Final = 256 +NV_CTRL_GVO_LOCK_OWNER: Final = 257 +NV_CTRL_GVO_LOCK_OWNER_NONE: Final = 0 +NV_CTRL_GVO_LOCK_OWNER_GLX: Final = 1 +NV_CTRL_GVO_LOCK_OWNER_CLONE: Final = 2 +NV_CTRL_GVO_LOCK_OWNER_X_SCREEN: Final = 3 +NV_CTRL_HWOVERLAY: Final = 258 +NV_CTRL_HWOVERLAY_FALSE: Final = 0 +NV_CTRL_HWOVERLAY_TRUE: Final = 1 +NV_CTRL_NUM_GPU_ERRORS_RECOVERED: Final = 259 +NV_CTRL_REFRESH_RATE_3: Final = 260 +NV_CTRL_ONDEMAND_VBLANK_INTERRUPTS: Final = 261 +NV_CTRL_ONDEMAND_VBLANK_INTERRUPTS_OFF: Final = 0 +NV_CTRL_ONDEMAND_VBLANK_INTERRUPTS_ON: Final = 1 +NV_CTRL_GPU_POWER_SOURCE: Final = 262 +NV_CTRL_GPU_POWER_SOURCE_AC: Final = 0 +NV_CTRL_GPU_POWER_SOURCE_BATTERY: Final = 1 +NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE: Final = 263 +NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE_DESKTOP: Final = 0 +NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE_MAXPERF: Final = 1 +NV_CTRL_GLYPH_CACHE: Final = 264 +NV_CTRL_GLYPH_CACHE_DISABLED: Final = 0 +NV_CTRL_GLYPH_CACHE_ENABLED: Final = 1 +NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL: Final = 265 +NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE: Final = 266 +NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE_DISABLED: Final = 0 +NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE_ENABLED: Final = 1 +NV_CTRL_GVO_OUTPUT_VIDEO_LOCKED: Final = 267 +NV_CTRL_GVO_OUTPUT_VIDEO_LOCKED_FALSE: Final = 0 +NV_CTRL_GVO_OUTPUT_VIDEO_LOCKED_TRUE: Final = 1 +NV_CTRL_GVO_SYNC_LOCK_STATUS: Final = 268 +NV_CTRL_GVO_SYNC_LOCK_STATUS_UNLOCKED: Final = 0 +NV_CTRL_GVO_SYNC_LOCK_STATUS_LOCKED: Final = 1 +NV_CTRL_GVO_ANC_TIME_CODE_GENERATION: Final = 269 +NV_CTRL_GVO_ANC_TIME_CODE_GENERATION_DISABLE: Final = 0 +NV_CTRL_GVO_ANC_TIME_CODE_GENERATION_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE: Final = 270 +NV_CTRL_GVO_COMPOSITE_DISABLE: Final = 0 +NV_CTRL_GVO_COMPOSITE_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE_ALPHA_KEY: Final = 271 +NV_CTRL_GVO_COMPOSITE_ALPHA_KEY_DISABLE: Final = 0 +NV_CTRL_GVO_COMPOSITE_ALPHA_KEY_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE_LUMA_KEY_RANGE: Final = 272 +NV_CTRL_GVO_COMPOSITE_CR_KEY_RANGE: Final = 273 +NV_CTRL_GVO_COMPOSITE_CB_KEY_RANGE: Final = 274 +NV_CTRL_GVO_COMPOSITE_NUM_KEY_RANGES: Final = 275 +NV_CTRL_SWITCH_TO_DISPLAYS: Final = 276 +NV_CTRL_NOTEBOOK_DISPLAY_CHANGE_LID_EVENT: Final = 277 +NV_CTRL_NOTEBOOK_INTERNAL_LCD: Final = 278 +NV_CTRL_DEPTH_30_ALLOWED: Final = 279 +NV_CTRL_MODE_SET_EVENT: Final = 280 +NV_CTRL_OPENGL_AA_LINE_GAMMA_VALUE: Final = 281 +NV_CTRL_VCSC_HIGH_PERF_MODE: Final = 282 +NV_CTRL_VCSC_HIGH_PERF_MODE_DISABLE: Final = 0 +NV_CTRL_VCSC_HIGH_PERF_MODE_ENABLE: Final = 1 +NV_CTRL_DISPLAYPORT_LINK_RATE: Final = 291 +NV_CTRL_DISPLAYPORT_LINK_RATE_DISABLED: Final = 0x0 +NV_CTRL_DISPLAYPORT_LINK_RATE_1_62GBPS: Final = 0x6 +NV_CTRL_DISPLAYPORT_LINK_RATE_2_70GBPS: Final = 0xA +NV_CTRL_STEREO_EYES_EXCHANGE: Final = 292 +NV_CTRL_STEREO_EYES_EXCHANGE_OFF: Final = 0 +NV_CTRL_STEREO_EYES_EXCHANGE_ON: Final = 1 +NV_CTRL_NO_SCANOUT: Final = 293 +NV_CTRL_NO_SCANOUT_DISABLED: Final = 0 +NV_CTRL_NO_SCANOUT_ENABLED: Final = 1 +NV_CTRL_GVO_CSC_CHANGED_EVENT: Final = 294 +NV_CTRL_FRAMELOCK_SLAVEABLE: Final = 295 +NV_CTRL_GVO_SYNC_TO_DISPLAY: Final = 296 +NV_CTRL_GVO_SYNC_TO_DISPLAY_DISABLE: Final = 0 +NV_CTRL_GVO_SYNC_TO_DISPLAY_ENABLE: Final = 1 +NV_CTRL_X_SERVER_UNIQUE_ID: Final = 297 +NV_CTRL_PIXMAP_CACHE: Final = 298 +NV_CTRL_PIXMAP_CACHE_DISABLE: Final = 0 +NV_CTRL_PIXMAP_CACHE_ENABLE: Final = 1 +NV_CTRL_PIXMAP_CACHE_ROUNDING_SIZE_KB: Final = 299 +NV_CTRL_IS_GVO_DISPLAY: Final = 300 +NV_CTRL_IS_GVO_DISPLAY_FALSE: Final = 0 +NV_CTRL_IS_GVO_DISPLAY_TRUE: Final = 1 +NV_CTRL_PCI_ID: Final = 301 +NV_CTRL_GVO_FULL_RANGE_COLOR: Final = 302 +NV_CTRL_GVO_FULL_RANGE_COLOR_DISABLED: Final = 0 +NV_CTRL_GVO_FULL_RANGE_COLOR_ENABLED: Final = 1 +NV_CTRL_SLI_MOSAIC_MODE_AVAILABLE: Final = 303 +NV_CTRL_SLI_MOSAIC_MODE_AVAILABLE_FALSE: Final = 0 +NV_CTRL_SLI_MOSAIC_MODE_AVAILABLE_TRUE: Final = 1 +NV_CTRL_GVO_ENABLE_RGB_DATA: Final = 304 +NV_CTRL_GVO_ENABLE_RGB_DATA_DISABLE: Final = 0 +NV_CTRL_GVO_ENABLE_RGB_DATA_ENABLE: Final = 1 +NV_CTRL_IMAGE_SHARPENING_DEFAULT: Final = 305 +NV_CTRL_PCI_DOMAIN: Final = 306 +NV_CTRL_GVI_NUM_JACKS: Final = 307 +NV_CTRL_GVI_MAX_LINKS_PER_STREAM: Final = 308 +NV_CTRL_GVI_DETECTED_CHANNEL_BITS_PER_COMPONENT: Final = 309 +NV_CTRL_GVI_BITS_PER_COMPONENT_UNKNOWN: Final = 0 +NV_CTRL_GVI_BITS_PER_COMPONENT_8: Final = 1 +NV_CTRL_GVI_BITS_PER_COMPONENT_10: Final = 2 +NV_CTRL_GVI_BITS_PER_COMPONENT_12: Final = 3 +NV_CTRL_GVI_REQUESTED_STREAM_BITS_PER_COMPONENT: Final = 310 +NV_CTRL_GVI_DETECTED_CHANNEL_COMPONENT_SAMPLING: Final = 311 +NV_CTRL_GVI_COMPONENT_SAMPLING_UNKNOWN: Final = 0 +NV_CTRL_GVI_COMPONENT_SAMPLING_4444: Final = 1 +NV_CTRL_GVI_COMPONENT_SAMPLING_4224: Final = 2 +NV_CTRL_GVI_COMPONENT_SAMPLING_444: Final = 3 +NV_CTRL_GVI_COMPONENT_SAMPLING_422: Final = 4 +NV_CTRL_GVI_COMPONENT_SAMPLING_420: Final = 5 +NV_CTRL_GVI_REQUESTED_STREAM_COMPONENT_SAMPLING: Final = 312 +NV_CTRL_GVI_REQUESTED_STREAM_CHROMA_EXPAND: Final = 313 +NV_CTRL_GVI_CHROMA_EXPAND_FALSE: Final = 0 +NV_CTRL_GVI_CHROMA_EXPAND_TRUE: Final = 1 +NV_CTRL_GVI_DETECTED_CHANNEL_COLOR_SPACE: Final = 314 +NV_CTRL_GVI_COLOR_SPACE_UNKNOWN: Final = 0 +NV_CTRL_GVI_COLOR_SPACE_GBR: Final = 1 +NV_CTRL_GVI_COLOR_SPACE_GBRA: Final = 2 +NV_CTRL_GVI_COLOR_SPACE_GBRD: Final = 3 +NV_CTRL_GVI_COLOR_SPACE_YCBCR: Final = 4 +NV_CTRL_GVI_COLOR_SPACE_YCBCRA: Final = 5 +NV_CTRL_GVI_COLOR_SPACE_YCBCRD: Final = 6 +NV_CTRL_GVI_DETECTED_CHANNEL_LINK_ID: Final = 315 +NV_CTRL_GVI_LINK_ID_UNKNOWN: Final = 0xFFFF +NV_CTRL_GVI_DETECTED_CHANNEL_SMPTE352_IDENTIFIER: Final = 316 +NV_CTRL_GVI_GLOBAL_IDENTIFIER: Final = 317 +NV_CTRL_FRAMELOCK_SYNC_DELAY_RESOLUTION: Final = 318 +NV_CTRL_GPU_COOLER_MANUAL_CONTROL: Final = 319 +NV_CTRL_GPU_COOLER_MANUAL_CONTROL_FALSE: Final = 0 +NV_CTRL_GPU_COOLER_MANUAL_CONTROL_TRUE: Final = 1 +NV_CTRL_THERMAL_COOLER_LEVEL: Final = 320 +NV_CTRL_THERMAL_COOLER_LEVEL_SET_DEFAULT: Final = 321 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE: Final = 322 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE_NONE: Final = 0 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE_TOGGLE: Final = 1 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE_VARIABLE: Final = 2 +NV_CTRL_THERMAL_COOLER_TARGET: Final = 323 +NV_CTRL_THERMAL_COOLER_TARGET_NONE: Final = 0 +NV_CTRL_THERMAL_COOLER_TARGET_GPU: Final = 1 +NV_CTRL_THERMAL_COOLER_TARGET_MEMORY: Final = 2 +NV_CTRL_THERMAL_COOLER_TARGET_POWER_SUPPLY: Final = 4 +NV_CTRL_THERMAL_COOLER_TARGET_GPU_RELATED: Final = 7 +NV_CTRL_GPU_ECC_SUPPORTED: Final = 324 +NV_CTRL_GPU_ECC_SUPPORTED_FALSE: Final = 0 +NV_CTRL_GPU_ECC_SUPPORTED_TRUE: Final = 1 +NV_CTRL_GPU_ECC_STATUS: Final = 325 +NV_CTRL_GPU_ECC_STATUS_DISABLED: Final = 0 +NV_CTRL_GPU_ECC_STATUS_ENABLED: Final = 1 +NV_CTRL_GPU_ECC_CONFIGURATION_SUPPORTED: Final = 326 +NV_CTRL_GPU_ECC_CONFIGURATION_SUPPORTED_FALSE: Final = 0 +NV_CTRL_GPU_ECC_CONFIGURATION_SUPPORTED_TRUE: Final = 1 +NV_CTRL_GPU_ECC_CONFIGURATION: Final = 327 +NV_CTRL_GPU_ECC_CONFIGURATION_DISABLED: Final = 0 +NV_CTRL_GPU_ECC_CONFIGURATION_ENABLED: Final = 1 +NV_CTRL_GPU_ECC_DEFAULT_CONFIGURATION: Final = 328 +NV_CTRL_GPU_ECC_DEFAULT_CONFIGURATION_DISABLED: Final = 0 +NV_CTRL_GPU_ECC_DEFAULT_CONFIGURATION_ENABLED: Final = 1 +NV_CTRL_GPU_ECC_SINGLE_BIT_ERRORS: Final = 329 +NV_CTRL_GPU_ECC_DOUBLE_BIT_ERRORS: Final = 330 +NV_CTRL_GPU_ECC_AGGREGATE_SINGLE_BIT_ERRORS: Final = 331 +NV_CTRL_GPU_ECC_AGGREGATE_DOUBLE_BIT_ERRORS: Final = 332 +NV_CTRL_GPU_ECC_RESET_ERROR_STATUS: Final = 333 +NV_CTRL_GPU_ECC_RESET_ERROR_STATUS_VOLATILE: Final = 0x00000001 +NV_CTRL_GPU_ECC_RESET_ERROR_STATUS_AGGREGATE: Final = 0x00000002 +NV_CTRL_GPU_POWER_MIZER_MODE: Final = 334 +NV_CTRL_GPU_POWER_MIZER_MODE_ADAPTIVE: Final = 0 +NV_CTRL_GPU_POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE: Final = 1 +NV_CTRL_GPU_POWER_MIZER_MODE_AUTO: Final = 2 +NV_CTRL_GPU_POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE: Final = 3 +NV_CTRL_GVI_SYNC_OUTPUT_FORMAT: Final = 335 +NV_CTRL_GVI_MAX_CHANNELS_PER_JACK: Final = 336 +NV_CTRL_GVI_MAX_STREAMS: Final = 337 +NV_CTRL_GVI_NUM_CAPTURE_SURFACES: Final = 338 +NV_CTRL_OVERSCAN_COMPENSATION: Final = 339 +NV_CTRL_GPU_PCIE_GENERATION: Final = 341 +NV_CTRL_GPU_PCIE_GENERATION1: Final = 0x00000001 +NV_CTRL_GPU_PCIE_GENERATION2: Final = 0x00000002 +NV_CTRL_GPU_PCIE_GENERATION3: Final = 0x00000003 +NV_CTRL_GVI_BOUND_GPU: Final = 342 +NV_CTRL_GVIO_REQUESTED_VIDEO_FORMAT3: Final = 343 +NV_CTRL_ACCELERATE_TRAPEZOIDS: Final = 344 +NV_CTRL_ACCELERATE_TRAPEZOIDS_DISABLE: Final = 0 +NV_CTRL_ACCELERATE_TRAPEZOIDS_ENABLE: Final = 1 +NV_CTRL_GPU_CORES: Final = 345 +NV_CTRL_GPU_MEMORY_BUS_WIDTH: Final = 346 +NV_CTRL_GVI_TEST_MODE: Final = 347 +NV_CTRL_GVI_TEST_MODE_DISABLE: Final = 0 +NV_CTRL_GVI_TEST_MODE_ENABLE: Final = 1 +NV_CTRL_COLOR_SPACE: Final = 348 +NV_CTRL_COLOR_SPACE_RGB: Final = 0 +NV_CTRL_COLOR_SPACE_YCbCr422: Final = 1 +NV_CTRL_COLOR_SPACE_YCbCr444: Final = 2 +NV_CTRL_COLOR_RANGE: Final = 349 +NV_CTRL_COLOR_RANGE_FULL: Final = 0 +NV_CTRL_COLOR_RANGE_LIMITED: Final = 1 +NV_CTRL_GPU_SCALING_DEFAULT_TARGET: Final = 350 +NV_CTRL_GPU_SCALING_DEFAULT_METHOD: Final = 351 +NV_CTRL_DITHERING_MODE: Final = 352 +NV_CTRL_DITHERING_MODE_AUTO: Final = 0 +NV_CTRL_DITHERING_MODE_DYNAMIC_2X2: Final = 1 +NV_CTRL_DITHERING_MODE_STATIC_2X2: Final = 2 +NV_CTRL_DITHERING_MODE_TEMPORAL: Final = 3 +NV_CTRL_CURRENT_DITHERING: Final = 353 +NV_CTRL_CURRENT_DITHERING_DISABLED: Final = 0 +NV_CTRL_CURRENT_DITHERING_ENABLED: Final = 1 +NV_CTRL_CURRENT_DITHERING_MODE: Final = 354 +NV_CTRL_CURRENT_DITHERING_MODE_NONE: Final = 0 +NV_CTRL_CURRENT_DITHERING_MODE_DYNAMIC_2X2: Final = 1 +NV_CTRL_CURRENT_DITHERING_MODE_STATIC_2X2: Final = 2 +NV_CTRL_CURRENT_DITHERING_MODE_TEMPORAL: Final = 3 +NV_CTRL_THERMAL_SENSOR_READING: Final = 355 +NV_CTRL_THERMAL_SENSOR_PROVIDER: Final = 356 +NV_CTRL_THERMAL_SENSOR_PROVIDER_NONE: Final = 0 +NV_CTRL_THERMAL_SENSOR_PROVIDER_GPU_INTERNAL: Final = 1 +NV_CTRL_THERMAL_SENSOR_PROVIDER_ADM1032: Final = 2 +NV_CTRL_THERMAL_SENSOR_PROVIDER_ADT7461: Final = 3 +NV_CTRL_THERMAL_SENSOR_PROVIDER_MAX6649: Final = 4 +NV_CTRL_THERMAL_SENSOR_PROVIDER_MAX1617: Final = 5 +NV_CTRL_THERMAL_SENSOR_PROVIDER_LM99: Final = 6 +NV_CTRL_THERMAL_SENSOR_PROVIDER_LM89: Final = 7 +NV_CTRL_THERMAL_SENSOR_PROVIDER_LM64: Final = 8 +NV_CTRL_THERMAL_SENSOR_PROVIDER_G781: Final = 9 +NV_CTRL_THERMAL_SENSOR_PROVIDER_ADT7473: Final = 10 +NV_CTRL_THERMAL_SENSOR_PROVIDER_SBMAX6649: Final = 11 +NV_CTRL_THERMAL_SENSOR_PROVIDER_VBIOSEVT: Final = 12 +NV_CTRL_THERMAL_SENSOR_PROVIDER_OS: Final = 13 +NV_CTRL_THERMAL_SENSOR_PROVIDER_UNKNOWN: Final = 0xFFFFFFFF +NV_CTRL_THERMAL_SENSOR_TARGET: Final = 357 +NV_CTRL_THERMAL_SENSOR_TARGET_NONE: Final = 0 +NV_CTRL_THERMAL_SENSOR_TARGET_GPU: Final = 1 +NV_CTRL_THERMAL_SENSOR_TARGET_MEMORY: Final = 2 +NV_CTRL_THERMAL_SENSOR_TARGET_POWER_SUPPLY: Final = 4 +NV_CTRL_THERMAL_SENSOR_TARGET_BOARD: Final = 8 +NV_CTRL_THERMAL_SENSOR_TARGET_UNKNOWN: Final = 0xFFFFFFFF +NV_CTRL_SHOW_MULTIGPU_VISUAL_INDICATOR: Final = 358 +NV_CTRL_SHOW_MULTIGPU_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_MULTIGPU_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_GPU_CURRENT_PROCESSOR_CLOCK_FREQS: Final = 359 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS: Final = 360 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_NONE: Final = 0x00000000 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_INTERLACED: Final = 0x00000001 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_PROGRESSIVE: Final = 0x00000002 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_PSF: Final = 0x00000004 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G_LEVEL_A: Final = 0x00000008 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G_LEVEL_B: Final = 0x00000010 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G: Final = 24 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G_1080P_NO_12BPC: Final = 0x00000020 +NV_CTRL_GPU_PCIE_MAX_LINK_SPEED: Final = 361 +NV_CTRL_3D_VISION_PRO_RESET_TRANSCEIVER_TO_FACTORY_SETTINGS: Final = 363 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL: Final = 364 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE: Final = 365 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_INVALID: Final = 0 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_LOW_RANGE: Final = 1 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_MEDIUM_RANGE: Final = 2 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_HIGH_RANGE: Final = 3 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_COUNT: Final = 4 +NV_CTRL_SYNCHRONOUS_PALETTE_UPDATES: Final = 367 +NV_CTRL_SYNCHRONOUS_PALETTE_UPDATES_DISABLE: Final = 0 +NV_CTRL_SYNCHRONOUS_PALETTE_UPDATES_ENABLE: Final = 1 +NV_CTRL_DITHERING_DEPTH: Final = 368 +NV_CTRL_DITHERING_DEPTH_AUTO: Final = 0 +NV_CTRL_DITHERING_DEPTH_6_BITS: Final = 1 +NV_CTRL_DITHERING_DEPTH_8_BITS: Final = 2 +NV_CTRL_CURRENT_DITHERING_DEPTH: Final = 369 +NV_CTRL_CURRENT_DITHERING_DEPTH_NONE: Final = 0 +NV_CTRL_CURRENT_DITHERING_DEPTH_6_BITS: Final = 1 +NV_CTRL_CURRENT_DITHERING_DEPTH_8_BITS: Final = 2 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL_FREQUENCY: Final = 370 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL_QUALITY: Final = 371 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL_COUNT: Final = 372 +NV_CTRL_3D_VISION_PRO_PAIR_GLASSES: Final = 373 +NV_CTRL_3D_VISION_PRO_PAIR_GLASSES_STOP: Final = 0 +NV_CTRL_3D_VISION_PRO_PAIR_GLASSES_BEACON: Final = 0xFFFFFFFF +NV_CTRL_3D_VISION_PRO_UNPAIR_GLASSES: Final = 374 +NV_CTRL_3D_VISION_PRO_DISCOVER_GLASSES: Final = 375 +NV_CTRL_3D_VISION_PRO_IDENTIFY_GLASSES: Final = 376 +NV_CTRL_3D_VISION_PRO_GLASSES_SYNC_CYCLE: Final = 378 +NV_CTRL_3D_VISION_PRO_GLASSES_MISSED_SYNC_CYCLES: Final = 379 +NV_CTRL_3D_VISION_PRO_GLASSES_BATTERY_LEVEL: Final = 380 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION: Final = 381 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION_AUTO: Final = 0 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION_ON: Final = 1 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION_OFF: Final = 2 +NV_CTRL_3D_VISION_PRO_GLASSES_PAIR_EVENT: Final = 382 +NV_CTRL_3D_VISION_PRO_GLASSES_UNPAIR_EVENT: Final = 383 +NV_CTRL_GPU_PCIE_CURRENT_LINK_WIDTH: Final = 384 +NV_CTRL_GPU_PCIE_CURRENT_LINK_SPEED: Final = 385 +NV_CTRL_GVO_AUDIO_BLANKING: Final = 386 +NV_CTRL_GVO_AUDIO_BLANKING_DISABLE: Final = 0 +NV_CTRL_GVO_AUDIO_BLANKING_ENABLE: Final = 1 +NV_CTRL_CURRENT_METAMODE_ID: Final = 387 +NV_CTRL_DISPLAY_ENABLED: Final = 388 +NV_CTRL_DISPLAY_ENABLED_TRUE: Final = 1 +NV_CTRL_DISPLAY_ENABLED_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_INCOMING_HOUSE_SYNC_RATE: Final = 389 +NV_CTRL_FXAA: Final = 390 +NV_CTRL_FXAA_DISABLE: Final = 0 +NV_CTRL_FXAA_ENABLE: Final = 1 +NV_CTRL_DISPLAY_RANDR_OUTPUT_ID: Final = 391 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG: Final = 392 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG_DISABLED: Final = 0 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG_CLIENT: Final = 1 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG_SERVER: Final = 2 +NV_CTRL_TOTAL_DEDICATED_GPU_MEMORY: Final = 393 +NV_CTRL_USED_DEDICATED_GPU_MEMORY: Final = 394 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_IMMEDIATE: Final = 395 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_IMMEDIATE_DISABLED: Final = 0 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_IMMEDIATE_ENABLED: Final = 1 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_REBOOT: Final = 396 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_REBOOT_DISABLED: Final = 0 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_REBOOT_ENALED: Final = 1 +NV_CTRL_DPY_HDMI_3D: Final = 397 +NV_CTRL_DPY_HDMI_3D_DISABLED: Final = 0 +NV_CTRL_DPY_HDMI_3D_ENABLED: Final = 1 +NV_CTRL_BASE_MOSAIC: Final = 398 +NV_CTRL_BASE_MOSAIC_DISABLED: Final = 0 +NV_CTRL_BASE_MOSAIC_FULL: Final = 1 +NV_CTRL_BASE_MOSAIC_LIMITED: Final = 2 +NV_CTRL_MULTIGPU_MASTER_POSSIBLE: Final = 399 +NV_CTRL_MULTIGPU_MASTER_POSSIBLE_FALSE: Final = 0 +NV_CTRL_MULTIGPU_MASTER_POSSIBLE_TRUE: Final = 1 +NV_CTRL_GPU_POWER_MIZER_DEFAULT_MODE: Final = 400 +NV_CTRL_XV_SYNC_TO_DISPLAY_ID: Final = 401 +NV_CTRL_XV_SYNC_TO_DISPLAY_ID_AUTO: Final = 0xFFFFFFFF +NV_CTRL_BACKLIGHT_BRIGHTNESS: Final = 402 +NV_CTRL_GPU_LOGO_BRIGHTNESS: Final = 403 +NV_CTRL_GPU_SLI_LOGO_BRIGHTNESS: Final = 404 +NV_CTRL_THERMAL_COOLER_SPEED: Final = 405 +NV_CTRL_PALETTE_UPDATE_EVENT: Final = 406 +NV_CTRL_VIDEO_ENCODER_UTILIZATION: Final = 407 +NV_CTRL_GSYNC_ALLOWED: Final = 408 +NV_CTRL_GSYNC_ALLOWED_FALSE: Final = 0 +NV_CTRL_GSYNC_ALLOWED_TRUE: Final = 1 +NV_CTRL_GPU_NVCLOCK_OFFSET: Final = 409 +NV_CTRL_GPU_MEM_TRANSFER_RATE_OFFSET: Final = 410 +NV_CTRL_VIDEO_DECODER_UTILIZATION: Final = 411 +NV_CTRL_GPU_OVER_VOLTAGE_OFFSET: Final = 412 +NV_CTRL_GPU_CURRENT_CORE_VOLTAGE: Final = 413 +NV_CTRL_CURRENT_COLOR_SPACE: Final = 414 +NV_CTRL_CURRENT_COLOR_SPACE_RGB: Final = 0 +NV_CTRL_CURRENT_COLOR_SPACE_YCbCr422: Final = 1 +NV_CTRL_CURRENT_COLOR_SPACE_YCbCr444: Final = 2 +NV_CTRL_CURRENT_COLOR_SPACE_YCbCr420: Final = 3 +NV_CTRL_CURRENT_COLOR_RANGE: Final = 415 +NV_CTRL_CURRENT_COLOR_RANGE_FULL: Final = 0 +NV_CTRL_CURRENT_COLOR_RANGE_LIMITED: Final = 1 +NV_CTRL_SHOW_GSYNC_VISUAL_INDICATOR: Final = 416 +NV_CTRL_SHOW_GSYNC_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_GSYNC_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_THERMAL_COOLER_CURRENT_LEVEL: Final = 417 +NV_CTRL_STEREO_SWAP_MODE: Final = 418 +NV_CTRL_STEREO_SWAP_MODE_APPLICATION_CONTROL: Final = 0 +NV_CTRL_STEREO_SWAP_MODE_PER_EYE: Final = 1 +NV_CTRL_STEREO_SWAP_MODE_PER_EYE_PAIR: Final = 2 +NV_CTRL_CURRENT_XV_SYNC_TO_DISPLAY_ID: Final = 419 +NV_CTRL_GPU_FRAMELOCK_FIRMWARE_UNSUPPORTED: Final = 420 +NV_CTRL_GPU_FRAMELOCK_FIRMWARE_UNSUPPORTED_FALSE: Final = 0 +NV_CTRL_GPU_FRAMELOCK_FIRMWARE_UNSUPPORTED_TRUE: Final = 1 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE: Final = 421 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_UNKNOWN: Final = 0 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_DISPLAYPORT: Final = 1 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_HDMI: Final = 2 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_DVI: Final = 3 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_VGA: Final = 4 +NV_CTRL_DISPLAYPORT_IS_MULTISTREAM: Final = 422 +NV_CTRL_DISPLAYPORT_SINK_IS_AUDIO_CAPABLE: Final = 423 +NV_CTRL_GPU_NVCLOCK_OFFSET_ALL_PERFORMANCE_LEVELS: Final = 424 +NV_CTRL_GPU_MEM_TRANSFER_RATE_OFFSET_ALL_PERFORMANCE_LEVELS: Final = 425 +NV_CTRL_FRAMELOCK_FIRMWARE_VERSION: Final = 426 +NV_CTRL_FRAMELOCK_FIRMWARE_MINOR_VERSION: Final = 427 +NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR: Final = 428 +NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_LAST_ATTRIBUTE: Final = NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR +NV_CTRL_STRING_PRODUCT_NAME: Final = 0 +NV_CTRL_STRING_VBIOS_VERSION: Final = 1 +NV_CTRL_STRING_NVIDIA_DRIVER_VERSION: Final = 3 +NV_CTRL_STRING_DISPLAY_DEVICE_NAME: Final = 4 +NV_CTRL_STRING_TV_ENCODER_NAME: Final = 5 +NV_CTRL_STRING_GVIO_FIRMWARE_VERSION: Final = 8 +NV_CTRL_STRING_GVO_FIRMWARE_VERSION: Final = 8 +NV_CTRL_STRING_CURRENT_MODELINE: Final = 9 +NV_CTRL_STRING_ADD_MODELINE: Final = 10 +NV_CTRL_STRING_DELETE_MODELINE: Final = 11 +NV_CTRL_STRING_CURRENT_METAMODE: Final = 12 +NV_CTRL_STRING_CURRENT_METAMODE_VERSION_1: Final = NV_CTRL_STRING_CURRENT_METAMODE +NV_CTRL_STRING_ADD_METAMODE: Final = 13 +NV_CTRL_STRING_DELETE_METAMODE: Final = 14 +NV_CTRL_STRING_VCSC_PRODUCT_NAME: Final = 15 +NV_CTRL_STRING_VCSC_PRODUCT_ID: Final = 16 +NV_CTRL_STRING_VCSC_SERIAL_NUMBER: Final = 17 +NV_CTRL_STRING_VCSC_BUILD_DATE: Final = 18 +NV_CTRL_STRING_VCSC_FIRMWARE_VERSION: Final = 19 +NV_CTRL_STRING_VCSC_FIRMWARE_REVISION: Final = 20 +NV_CTRL_STRING_VCSC_HARDWARE_VERSION: Final = 21 +NV_CTRL_STRING_VCSC_HARDWARE_REVISION: Final = 22 +NV_CTRL_STRING_MOVE_METAMODE: Final = 23 +NV_CTRL_STRING_VALID_HORIZ_SYNC_RANGES: Final = 24 +NV_CTRL_STRING_VALID_VERT_REFRESH_RANGES: Final = 25 +NV_CTRL_STRING_SCREEN_RECTANGLE: Final = 26 +NV_CTRL_STRING_XINERAMA_SCREEN_INFO: Final = 26 +NV_CTRL_STRING_NVIDIA_XINERAMA_INFO_ORDER: Final = 27 +NV_CTRL_STRING_TWINVIEW_XINERAMA_INFO_ORDER: Final = NV_CTRL_STRING_NVIDIA_XINERAMA_INFO_ORDER +NV_CTRL_STRING_SLI_MODE: Final = 28 +NV_CTRL_STRING_PERFORMANCE_MODES: Final = 29 +NV_CTRL_STRING_VCSC_FAN_STATUS: Final = 30 +NV_CTRL_STRING_VCSC_TEMPERATURES: Final = 31 +NV_CTRL_STRING_VCSC_PSU_INFO: Final = 32 +NV_CTRL_STRING_GVIO_VIDEO_FORMAT_NAME: Final = 33 +NV_CTRL_STRING_GVO_VIDEO_FORMAT_NAME: Final = 33 +NV_CTRL_STRING_GPU_CURRENT_CLOCK_FREQS: Final = 34 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_HARDWARE_REVISION: Final = 35 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_VERSION_A: Final = 36 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_DATE_A: Final = 37 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_VERSION_B: Final = 38 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_DATE_B: Final = 39 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_ADDRESS: Final = 40 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_FIRMWARE_VERSION_A: Final = 41 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_FIRMWARE_DATE_A: Final = 42 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_ADDRESS: Final = 43 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_NAME: Final = 44 +NV_CTRL_STRING_CURRENT_METAMODE_VERSION_2: Final = 45 +NV_CTRL_STRING_DISPLAY_NAME_TYPE_BASENAME: Final = 46 +NV_CTRL_STRING_DISPLAY_NAME_TYPE_ID: Final = 47 +NV_CTRL_STRING_DISPLAY_NAME_DP_GUID: Final = 48 +NV_CTRL_STRING_DISPLAY_NAME_EDID_HASH: Final = 49 +NV_CTRL_STRING_DISPLAY_NAME_TARGET_INDEX: Final = 50 +NV_CTRL_STRING_DISPLAY_NAME_RANDR: Final = 51 +NV_CTRL_STRING_GPU_UUID: Final = 52 +NV_CTRL_STRING_GPU_UTILIZATION: Final = 53 +NV_CTRL_STRING_MULTIGPU_MODE: Final = 54 +NV_CTRL_STRING_PRIME_OUTPUTS_DATA: Final = 55 +NV_CTRL_STRING_LAST_ATTRIBUTE: Final = NV_CTRL_STRING_PRIME_OUTPUTS_DATA +NV_CTRL_BINARY_DATA_EDID: Final = 0 +NV_CTRL_BINARY_DATA_MODELINES: Final = 1 +NV_CTRL_BINARY_DATA_METAMODES: Final = 2 +NV_CTRL_BINARY_DATA_METAMODES_VERSION_1: Final = NV_CTRL_BINARY_DATA_METAMODES +NV_CTRL_BINARY_DATA_XSCREENS_USING_GPU: Final = 3 +NV_CTRL_BINARY_DATA_GPUS_USED_BY_XSCREEN: Final = 4 +NV_CTRL_BINARY_DATA_GPUS_USING_FRAMELOCK: Final = 5 +NV_CTRL_BINARY_DATA_DISPLAY_VIEWPORT: Final = 6 +NV_CTRL_BINARY_DATA_FRAMELOCKS_USED_BY_GPU: Final = 7 +NV_CTRL_BINARY_DATA_GPUS_USING_VCSC: Final = 8 +NV_CTRL_BINARY_DATA_VCSCS_USED_BY_GPU: Final = 9 +NV_CTRL_BINARY_DATA_COOLERS_USED_BY_GPU: Final = 10 +NV_CTRL_BINARY_DATA_GPUS_USED_BY_LOGICAL_XSCREEN: Final = 11 +NV_CTRL_BINARY_DATA_THERMAL_SENSORS_USED_BY_GPU: Final = 12 +NV_CTRL_BINARY_DATA_GLASSES_PAIRED_TO_3D_VISION_PRO_TRANSCEIVER: Final = 13 +NV_CTRL_BINARY_DATA_DISPLAY_TARGETS: Final = 14 +NV_CTRL_BINARY_DATA_DISPLAYS_CONNECTED_TO_GPU: Final = 15 +NV_CTRL_BINARY_DATA_METAMODES_VERSION_2: Final = 16 +NV_CTRL_BINARY_DATA_DISPLAYS_ENABLED_ON_XSCREEN: Final = 17 +NV_CTRL_BINARY_DATA_DISPLAYS_ASSIGNED_TO_XSCREEN: Final = 18 +NV_CTRL_BINARY_DATA_GPU_FLAGS: Final = 19 +NV_CTRL_BINARY_DATA_GPU_FLAGS_STEREO_DISPLAY_TRANSFORM_EXCLUSIVE: Final = 0 +NV_CTRL_BINARY_DATA_GPU_FLAGS_OVERLAY_DISPLAY_TRANSFORM_EXCLUSIVE: Final = 1 +NV_CTRL_BINARY_DATA_GPU_FLAGS_DEPTH_8_DISPLAY_TRANSFORM_EXCLUSIVE: Final = 2 +NV_CTRL_BINARY_DATA_DISPLAYS_ON_GPU: Final = 20 +NV_CTRL_BINARY_DATA_LAST_ATTRIBUTE: Final = NV_CTRL_BINARY_DATA_DISPLAYS_ON_GPU +NV_CTRL_STRING_OPERATION_ADD_METAMODE: Final = 0 +NV_CTRL_STRING_OPERATION_GTF_MODELINE: Final = 1 +NV_CTRL_STRING_OPERATION_CVT_MODELINE: Final = 2 +NV_CTRL_STRING_OPERATION_BUILD_MODEPOOL: Final = 3 +NV_CTRL_STRING_OPERATION_GVI_CONFIGURE_STREAMS: Final = 4 +NV_CTRL_STRING_OPERATION_PARSE_METAMODE: Final = 5 +NV_CTRL_STRING_OPERATION_LAST_ATTRIBUTE: Final = NV_CTRL_STRING_OPERATION_PARSE_METAMODE +X_nvCtrlQueryExtension: Final = 0 +X_nvCtrlQueryAttribute: Final = 2 +X_nvCtrlQueryStringAttribute: Final = 4 +X_nvCtrlQueryValidAttributeValues: Final = 5 +X_nvCtrlSetStringAttribute: Final = 9 +X_nvCtrlSetAttributeAndGetStatus: Final = 19 +X_nvCtrlQueryBinaryData: Final = 20 +X_nvCtrlQueryTargetCount: Final = 24 +X_nvCtrlStringOperation: Final = 25 +ATTRIBUTE_TYPE_UNKNOWN: Final = 0 +ATTRIBUTE_TYPE_INTEGER: Final = 1 +ATTRIBUTE_TYPE_BITMASK: Final = 2 +ATTRIBUTE_TYPE_BOOL: Final = 3 +ATTRIBUTE_TYPE_RANGE: Final = 4 +ATTRIBUTE_TYPE_INT_BITS: Final = 5 +ATTRIBUTE_TYPE_READ: Final = 0x01 +ATTRIBUTE_TYPE_WRITE: Final = 0x02 +ATTRIBUTE_TYPE_DISPLAY: Final = 0x04 +ATTRIBUTE_TYPE_GPU: Final = 0x08 +ATTRIBUTE_TYPE_FRAMELOCK: Final = 0x10 +ATTRIBUTE_TYPE_X_SCREEN: Final = 0x20 +ATTRIBUTE_TYPE_XINERAMA: Final = 0x40 +ATTRIBUTE_TYPE_VCSC: Final = 0x80 +NV_CTRL_TARGET_TYPE_X_SCREEN: Final = 0 +NV_CTRL_TARGET_TYPE_GPU: Final = 1 +NV_CTRL_TARGET_TYPE_FRAMELOCK: Final = 2 +NV_CTRL_TARGET_TYPE_VCSC: Final = 3 +NV_CTRL_TARGET_TYPE_GVI: Final = 4 +NV_CTRL_TARGET_TYPE_COOLER: Final = 5 +NV_CTRL_TARGET_TYPE_THERMAL_SENSOR: Final = 6 +NV_CTRL_TARGET_TYPE_3D_VISION_PRO_TRANSCEIVER: Final = 7 +NV_CTRL_TARGET_TYPE_DISPLAY: Final = 8 + +class Target: + def id(self) -> int: ... + def type(self) -> int: ... + +class Gpu(Target): + def __init__(self, ngpu: int = 0) -> None: ... + +class Screen(Target): + def __init__(self, nscr: int = 0) -> None: ... + +class Cooler(Target): + def __init__(self, nfan: int = 0) -> None: ... + +class NVCtrlQueryTargetCountReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryAttributeReplyRequest(rq.ReplyRequest): ... +class NVCtrlSetAttributeAndGetStatusReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryStringAttributeReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryValidAttributeValuesReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryBinaryDataReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryListCard32ReplyRequest(rq.ReplyRequest): ... diff --git a/stubs/python-xlib/Xlib/ext/randr.pyi b/stubs/python-xlib/Xlib/ext/randr.pyi new file mode 100644 index 000000000000..9aac2eee1301 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/randr.pyi @@ -0,0 +1,261 @@ +from collections.abc import Sequence +from typing import Final, TypeAlias + +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.xobject import drawable, resource + +_RandRModeInfo13IntSequence: TypeAlias = Sequence[int] + +extname: Final = "RANDR" +RRScreenChangeNotify: Final = 0 +RRNotify: Final = 1 +RRNotify_CrtcChange: Final = 0 +RRNotify_OutputChange: Final = 1 +RRNotify_OutputProperty: Final = 2 +RRScreenChangeNotifyMask: Final = 0x1 +RRCrtcChangeNotifyMask: Final = 0x2 +RROutputChangeNotifyMask: Final = 0x4 +RROutputPropertyNotifyMask: Final = 0x8 +SetConfigSuccess: Final = 0 +SetConfigInvalidConfigTime: Final = 1 +SetConfigInvalidTime: Final = 2 +SetConfigFailed: Final = 3 +Rotate_0: Final = 1 +Rotate_90: Final = 2 +Rotate_180: Final = 4 +Rotate_270: Final = 8 +Reflect_X: Final = 16 +Reflect_Y: Final = 32 +HSyncPositive: Final = 0x00000001 +HSyncNegative: Final = 0x00000002 +VSyncPositive: Final = 0x00000004 +VSyncNegative: Final = 0x00000008 +Interlace: Final = 0x00000010 +DoubleScan: Final = 0x00000020 +CSync: Final = 0x00000040 +CSyncPositive: Final = 0x00000080 +CSyncNegative: Final = 0x00000100 +HSkewPresent: Final = 0x00000200 +BCast: Final = 0x00000400 +PixelMultiplex: Final = 0x00000800 +DoubleClock: Final = 0x00001000 +ClockDivideBy2: Final = 0x00002000 +Connected: Final = 0 +Disconnected: Final = 1 +UnknownConnection: Final = 2 +PROPERTY_RANDR_EDID: Final = "EDID" +PROPERTY_SIGNAL_FORMAT: Final = "SignalFormat" +PROPERTY_SIGNAL_PROPERTIES: Final = "SignalProperties" +PROPERTY_CONNECTOR_TYPE: Final = "ConnectorType" +PROPERTY_CONNECTOR_NUMBER: Final = "ConnectorNumber" +PROPERTY_COMPATIBILITY_LIST: Final = "CompatibilityList" +PROPERTY_CLONE_LIST: Final = "CloneList" +SubPixelUnknown: Final = 0 +SubPixelHorizontalRGB: Final = 1 +SubPixelHorizontalBGR: Final = 2 +SubPixelVerticalRGB: Final = 3 +SubPixelVerticalBGR: Final = 4 +SubPixelNone: Final = 5 +BadRROutput: Final = 0 +BadRRCrtc: Final = 1 +BadRRMode: Final = 2 + +class BadRROutputError(Exception): ... +class BadRRCrtcError(Exception): ... +class BadRRModeError(Exception): ... + +RandR_ScreenSizes: rq.Struct +RandR_ModeInfo: rq.Struct +RandR_Rates: rq.Struct +Render_Transform: rq.Struct +MonitorInfo: rq.Struct + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class _1_0SetScreenConfig(rq.ReplyRequest): ... +class SetScreenConfig(rq.ReplyRequest): ... + +def set_screen_config( + self: drawable.Drawable, size_id: int, rotation: int, config_timestamp: int, rate: int = 0, timestamp: int = 0 +) -> SetScreenConfig: ... + +class SelectInput(rq.Request): ... + +def select_input(self: drawable.Window, mask: int) -> SelectInput: ... + +class GetScreenInfo(rq.ReplyRequest): ... + +def get_screen_info(self: drawable.Window) -> GetScreenInfo: ... + +class GetScreenSizeRange(rq.ReplyRequest): ... + +def get_screen_size_range(self: drawable.Window) -> GetScreenSizeRange: ... + +class SetScreenSize(rq.Request): ... + +def set_screen_size( + self: drawable.Window, + width: int, + height: int, + width_in_millimeters: int | None = None, + height_in_millimeters: int | None = None, +) -> SetScreenSize: ... + +class GetScreenResources(rq.ReplyRequest): ... + +def get_screen_resources(self: drawable.Window) -> GetScreenResources: ... + +class GetOutputInfo(rq.ReplyRequest): ... + +def get_output_info(self: Display | resource.Resource, output: int, config_timestamp: int) -> GetOutputInfo: ... + +class ListOutputProperties(rq.ReplyRequest): ... + +def list_output_properties(self: Display | resource.Resource, output: int) -> ListOutputProperties: ... + +class QueryOutputProperty(rq.ReplyRequest): ... + +def query_output_property(self: Display | resource.Resource, output: int, property: int) -> QueryOutputProperty: ... + +class ConfigureOutputProperty(rq.Request): ... + +def configure_output_property(self: Display | resource.Resource, output: int, property: int) -> ConfigureOutputProperty: ... + +class ChangeOutputProperty(rq.Request): ... + +def change_output_property( + self: Display | resource.Resource, output: int, property: int, type: int, mode: int, value: Sequence[float] | Sequence[str] +) -> ChangeOutputProperty: ... + +class DeleteOutputProperty(rq.Request): ... + +def delete_output_property(self: Display | resource.Resource, output: int, property: int) -> DeleteOutputProperty: ... + +class GetOutputProperty(rq.ReplyRequest): ... + +def get_output_property( + self: Display | resource.Resource, + output: int, + property: int, + type: int, + long_offset: int, + long_length: int, + delete: bool = False, + pending: bool = False, +) -> GetOutputProperty: ... + +class CreateMode(rq.ReplyRequest): ... + +def create_mode(self: drawable.Window, mode: _RandRModeInfo13IntSequence, name: str) -> CreateMode: ... + +class DestroyMode(rq.Request): ... + +def destroy_mode(self: Display | resource.Resource, mode: int) -> DestroyMode: ... + +class AddOutputMode(rq.Request): ... + +def add_output_mode(self: Display | resource.Resource, output: int, mode: int) -> AddOutputMode: ... + +class DeleteOutputMode(rq.Request): ... + +def delete_output_mode(self: Display | resource.Resource, output: int, mode: int) -> DeleteOutputMode: ... + +class GetCrtcInfo(rq.ReplyRequest): ... + +def get_crtc_info(self: Display | resource.Resource, crtc: int, config_timestamp: int) -> GetCrtcInfo: ... + +class SetCrtcConfig(rq.ReplyRequest): ... + +def set_crtc_config( + self: Display | resource.Resource, + crtc: int, + config_timestamp: int, + x: int, + y: int, + mode: int, + rotation: int, + outputs: Sequence[int], + timestamp: int = 0, +) -> SetCrtcConfig: ... + +class GetCrtcGammaSize(rq.ReplyRequest): ... + +def get_crtc_gamma_size(self: Display | resource.Resource, crtc: int) -> GetCrtcGammaSize: ... + +class GetCrtcGamma(rq.ReplyRequest): ... + +def get_crtc_gamma(self: Display | resource.Resource, crtc: int) -> GetCrtcGamma: ... + +class SetCrtcGamma(rq.Request): ... + +def set_crtc_gamma( + self: Display | resource.Resource, crtc: int, size: int, red: Sequence[int], green: Sequence[int], blue: Sequence[int] +) -> SetCrtcGamma: ... + +class GetScreenResourcesCurrent(rq.ReplyRequest): ... + +def get_screen_resources_current(self: drawable.Window) -> GetScreenResourcesCurrent: ... + +class SetCrtcTransform(rq.Request): ... + +def set_crtc_transform(self: Display | resource.Resource, crtc: int, n_bytes_filter: Sequence[int]) -> SetCrtcTransform: ... + +class GetCrtcTransform(rq.ReplyRequest): ... + +def get_crtc_transform(self: Display | resource.Resource, crtc: int) -> GetCrtcTransform: ... + +class GetPanning(rq.ReplyRequest): ... + +def get_panning(self: Display | resource.Resource, crtc: int) -> GetPanning: ... + +class SetPanning(rq.ReplyRequest): ... + +def set_panning( + self: Display | resource.Resource, + crtc: int, + left: int, + top: int, + width: int, + height: int, + track_left: int, + track_top: int, + track_width: int, + track_height: int, + border_left: int, + border_top: int, + border_width: int, + border_height: int, + timestamp: int = 0, +) -> SetPanning: ... + +class SetOutputPrimary(rq.Request): ... + +def set_output_primary(self: drawable.Window, output: int) -> SetOutputPrimary: ... + +class GetOutputPrimary(rq.ReplyRequest): ... + +def get_output_primary(self: drawable.Window) -> GetOutputPrimary: ... + +class GetMonitors(rq.ReplyRequest): ... + +def get_monitors(self: drawable.Window, is_active: bool = True) -> GetMonitors: ... + +class SetMonitor(rq.Request): ... + +def set_monitor( + self: drawable.Window, monitor_info: tuple[int, bool, bool, Sequence[int], int, int, int, int, int] +) -> SetMonitor: ... + +class DeleteMonitor(rq.Request): ... + +def delete_monitor(self: Display | resource.Resource, name: str) -> DeleteMonitor: ... + +class ScreenChangeNotify(rq.Event): ... +class CrtcChangeNotify(rq.Event): ... +class OutputChangeNotify(rq.Event): ... +class OutputPropertyNotify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/record.pyi b/stubs/python-xlib/Xlib/ext/record.pyi new file mode 100644 index 000000000000..4cac2039e09f --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/record.pyi @@ -0,0 +1,115 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence, Sized +from typing import Any, Final, Literal, TypeVar + +from Xlib.display import Display +from Xlib.protocol import display, rq +from Xlib.xobject import resource + +_T = TypeVar("_T") +_S = TypeVar("_S", bound=Sized) + +extname: Final = "RECORD" + +FromServerTime: Final = 0x01 +FromClientTime: Final = 0x02 +FromClientSequence: Final = 0x04 + +CurrentClients: Final = 1 +FutureClients: Final = 2 +AllClients: Final = 3 + +FromServer: Final = 0 +FromClient: Final = 1 +ClientStarted: Final = 2 +ClientDied: Final = 3 +StartOfData: Final = 4 +EndOfData: Final = 5 +Record_Range8: rq.Struct +Record_Range16: rq.Struct +Record_ExtRange: rq.Struct +Record_Range: rq.Struct +Record_ClientInfo: rq.Struct + +class RawField(rq.ValueField): + structcode: None + def pack_value(self, val: _S) -> tuple[_S, int, None]: ... # type: ignore[override] + def parse_binary_value(self, data: _T, display: Unused, length: Unused, format: Unused) -> tuple[_T, Literal[""]]: ... # type: ignore[override] # See: https://github.com/python-xlib/python-xlib/pull/249 + +class GetVersion(rq.ReplyRequest): ... + +def get_version(self: Display | resource.Resource, major: int, minor: int) -> GetVersion: ... + +class CreateContext(rq.Request): ... + +def create_context( + self: Display | resource.Resource, + datum_flags: int, + clients: Sequence[int], + ranges: Sequence[ + tuple[ + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + bool, + bool, + ] + ], +) -> int: ... + +class RegisterClients(rq.Request): ... + +def register_clients( + self: Display | resource.Resource, + context: int, + element_header: int, + clients: int, + ranges: Sequence[ + tuple[ + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + bool, + bool, + ] + ], +) -> None: ... + +class UnregisterClients(rq.Request): ... + +def unregister_clients(self: Display | resource.Resource, context: int, clients: Sequence[int]) -> None: ... + +class GetContext(rq.ReplyRequest): ... + +def get_context(self: Display | resource.Resource, context: int) -> GetContext: ... + +class EnableContext(rq.ReplyRequest): + def __init__( + self, + callback: Callable[[rq.DictWrapper | dict[str, Any]], Any], + display: display.Display, + defer: bool = False, + *args: object | bool, + **keys: object | bool, + ) -> None: ... + +def enable_context( + self: Display | resource.Resource, context: int, callback: Callable[[rq.DictWrapper | dict[str, Any]], Any] +) -> None: ... + +class DisableContext(rq.Request): ... + +def disable_context(self: Display | resource.Resource, context: int) -> None: ... + +class FreeContext(rq.Request): ... + +def free_context(self: Display | resource.Resource, context: int) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/res.pyi b/stubs/python-xlib/Xlib/ext/res.pyi new file mode 100644 index 000000000000..27df703789fa --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/res.pyi @@ -0,0 +1,62 @@ +from _typeshed import Unused +from collections.abc import Sequence +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +RES_MAJOR_VERSION: Final = 1 +RES_MINOR_VERSION: Final = 2 +extname: Final = "X-Resource" +ResQueryVersion: Final = 0 +ResQueryClients: Final = 1 +ResQueryClientResources: Final = 2 +ResQueryClientPixmapBytes: Final = 3 +ResQueryClientIds: Final = 4 +ResQueryResourceBytes: Final = 5 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource, client_major: int = 1, client_minor: int = 2) -> QueryVersion: ... + +Client: rq.Struct + +class QueryClients(rq.ReplyRequest): ... + +def query_clients(self: Display | resource.Resource) -> QueryClients: ... + +Type: rq.Struct + +class QueryClientResources(rq.ReplyRequest): ... + +def query_client_resources(self: Display | resource.Resource, client: int) -> QueryClientResources: ... + +class QueryClientPixmapBytes(rq.ReplyRequest): ... + +def query_client_pixmap_bytes(self: Display | resource.Resource, client: int) -> QueryClientPixmapBytes: ... + +class SizeOf(rq.LengthOf): + item_size: int + def __init__(self, name: str | list[str] | tuple[str, ...], size: int, item_size: int) -> None: ... + def parse_value(self, length: int, display: Unused) -> int: ... # type: ignore[override] + +ClientXIDMask: Final = 0x1 +LocalClientPIDMask: Final = 0x2 +ClientIdSpec: rq.Struct +ClientIdValue: rq.Struct + +class QueryClientIds(rq.ReplyRequest): ... + +def query_client_ids(self: Display | resource.Resource, specs: Sequence[tuple[int, int]]) -> QueryClientIds: ... + +ResourceIdSpec: rq.Struct +ResourceSizeSpec: rq.Struct +ResourceSizeValue: rq.Struct + +class QueryResourceBytes(rq.ReplyRequest): ... + +def query_resource_bytes( + self: Display | resource.Resource, client: int, specs: Sequence[tuple[int, int]] +) -> QueryResourceBytes: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/screensaver.pyi b/stubs/python-xlib/Xlib/ext/screensaver.pyi new file mode 100644 index 000000000000..24ac6750bb89 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/screensaver.pyi @@ -0,0 +1,52 @@ +from typing import Final + +from Xlib._typing import ErrorHandler +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.xobject import drawable + +extname: Final = "MIT-SCREEN-SAVER" +NotifyMask: Final = 1 +CycleMask: Final = 2 +StateOff: Final = 0 +StateOn: Final = 1 +StateCycle: Final = 2 +KindBlanked: Final = 0 +KindInternal: Final = 1 +KindExternal: Final = 2 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: drawable.Drawable) -> QueryVersion: ... + +class QueryInfo(rq.ReplyRequest): ... + +def query_info(self: drawable.Drawable) -> QueryInfo: ... + +class SelectInput(rq.Request): ... + +def select_input(self: drawable.Drawable, mask: int) -> SelectInput: ... + +class SetAttributes(rq.Request): ... + +def set_attributes( + self: drawable.Drawable, + x: int, + y: int, + width: int, + height: int, + border_width: int, + window_class: int = 0, + depth: int = 0, + visual: int = 0, + onerror: ErrorHandler[object] | None = None, + **keys: object, +) -> SetAttributes: ... + +class UnsetAttributes(rq.Request): ... + +def unset_attributes(self: drawable.Drawable, onerror: ErrorHandler[object] | None = None) -> UnsetAttributes: ... + +class Notify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/security.pyi b/stubs/python-xlib/Xlib/ext/security.pyi new file mode 100644 index 000000000000..b8445fe245ea --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/security.pyi @@ -0,0 +1,33 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "SECURITY" +SecurityClientTrusted: Final = 0 +SecurityClientUntrusted: Final = 1 +SecurityAuthorizationRevokedMask: Final = 1 +AUTHID = rq.Card32 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class SecurityGenerateAuthorization(rq.ReplyRequest): ... + +def generate_authorization( + self: Display | resource.Resource, + auth_proto: str, + auth_data: bytes | bytearray = b"", + timeout: int | None = None, + trust_level: int | None = None, + group: int | None = None, + event_mask: int | None = None, +) -> SecurityGenerateAuthorization: ... + +class SecurityRevokeAuthorization(rq.Request): ... + +def revoke_authorization(self: Display | resource.Resource, authid: int) -> SecurityRevokeAuthorization: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/shape.pyi b/stubs/python-xlib/Xlib/ext/shape.pyi new file mode 100644 index 000000000000..9a72b1f1736a --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/shape.pyi @@ -0,0 +1,62 @@ +from collections.abc import Sequence +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.protocol.structs import _Rectangle4IntSequence +from Xlib.xobject import drawable, resource + +extname: Final = "SHAPE" +OP = rq.Card8 + +class SO: + Set: int + Union: int + Intersect: int + Subtract: int + Invert: int + +class SK: + Bounding: int + Clip: int + Input: int + +class KIND(rq.Set): + def __init__(self, name: str) -> None: ... + +class NotifyEventData(rq.Event): ... +class QueryVersion(rq.ReplyRequest): ... +class Rectangles(rq.Request): ... +class Mask(rq.Request): ... +class Combine(rq.Request): ... +class Offset(rq.Request): ... +class QueryExtents(rq.ReplyRequest): ... +class SelectInput(rq.Request): ... +class InputSelected(rq.ReplyRequest): ... +class GetRectangles(rq.ReplyRequest): ... + +class Event: + Notify: int + +def combine( + self: drawable.Window, operation: int, destination_kind: int, source_kind: int, x_offset: int, y_offset: int +) -> None: ... +def get_rectangles(self: drawable.Window, source_kind: int) -> GetRectangles: ... +def input_selected(self: drawable.Window) -> InputSelected: ... +def mask( + self: drawable.Window, operation: int, destination_kind: int, x_offset: int, y_offset: int, source_bitmap: int +) -> None: ... +def offset(self: drawable.Window, destination_kind: int, x_offset: int, y_offset: int) -> None: ... +def query_extents(self: drawable.Window) -> QueryExtents: ... +def query_version(self: Display | resource.Resource) -> QueryVersion: ... +def rectangles( + self: drawable.Window, + operation: int, + destination_kind: int, + ordering: int, + x_offset: int, + y_offset: int, + rectangles: Sequence[_Rectangle4IntSequence], +) -> None: ... +def select_input(self: drawable.Window, enable: int) -> None: ... +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xfixes.pyi b/stubs/python-xlib/Xlib/ext/xfixes.pyi new file mode 100644 index 000000000000..cb9bdc42cd48 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xfixes.pyi @@ -0,0 +1,50 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.xobject import drawable, resource + +extname: Final = "XFIXES" +XFixesSelectionNotify: Final = 0 +XFixesCursorNotify: Final = 1 +XFixesSetSelectionOwnerNotifyMask: Final = 0x1 +XFixesSelectionWindowDestroyNotifyMask: Final = 0x2 +XFixesSelectionClientCloseNotifyMask: Final = 0x4 +XFixesDisplayCursorNotifyMask: Final = 0x1 +XFixesSetSelectionOwnerNotify: Final = 0 +XFixesSelectionWindowDestroyNotify: Final = 1 +XFixesSelectionClientCloseNotify: Final = 2 +XFixesDisplayCursorNotify: Final = 0 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class HideCursor(rq.Request): ... + +def hide_cursor(self: drawable.Window) -> None: ... + +class ShowCursor(rq.Request): ... + +def show_cursor(self: drawable.Window) -> None: ... + +class SelectSelectionInput(rq.Request): ... + +def select_selection_input(self: Display | resource.Resource, window: int, selection: int, mask: int) -> SelectSelectionInput: ... + +class SelectionNotify(rq.Event): ... +class SetSelectionOwnerNotify(SelectionNotify): ... +class SelectionWindowDestroyNotify(SelectionNotify): ... +class SelectionClientCloseNotify(SelectionNotify): ... +class SelectCursorInput(rq.Request): ... + +def select_cursor_input(self: Display | resource.Resource, window: int, mask: int) -> SelectCursorInput: ... + +class GetCursorImage(rq.ReplyRequest): ... + +def get_cursor_image(self: Display | resource.Resource, window: Unused) -> GetCursorImage: ... + +class DisplayCursorNotify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xinerama.pyi b/stubs/python-xlib/Xlib/ext/xinerama.pyi new file mode 100644 index 000000000000..e47a080ac65a --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xinerama.pyi @@ -0,0 +1,37 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import drawable, resource + +extname: Final = "XINERAMA" + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class GetState(rq.ReplyRequest): ... + +def get_state(self: drawable.Window) -> GetState: ... + +class GetScreenCount(rq.ReplyRequest): ... + +def get_screen_count(self: drawable.Window) -> GetScreenCount: ... + +class GetScreenSize(rq.ReplyRequest): ... + +def get_screen_size(self: drawable.Window, screen_no: int) -> GetScreenSize: ... + +class IsActive(rq.ReplyRequest): ... + +def is_active(self: Display | resource.Resource) -> int: ... + +class QueryScreens(rq.ReplyRequest): ... + +def query_screens(self: Display | resource.Resource) -> QueryScreens: ... + +class GetInfo(rq.ReplyRequest): ... + +def get_info(self: Display | resource.Resource, visual: int) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xinput.pyi b/stubs/python-xlib/Xlib/ext/xinput.pyi new file mode 100644 index 000000000000..6711faef3570 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xinput.pyi @@ -0,0 +1,249 @@ +from _typeshed import ConvertibleToFloat, SliceableBuffer, Unused +from collections.abc import Iterable, Sequence +from typing import Final, TypeVar + +from Xlib.display import Display +from Xlib.protocol import display, request, rq +from Xlib.xobject import drawable, resource + +_T = TypeVar("_T") + +extname: Final = "XInputExtension" +PropertyDeleted: Final = 0 +PropertyCreated: Final = 1 +PropertyModified: Final = 2 +NotifyNormal: Final = 0 +NotifyGrab: Final = 1 +NotifyUngrab: Final = 2 +NotifyWhileGrabbed: Final = 3 +NotifyPassiveGrab: Final = 4 +NotifyPassiveUngrab: Final = 5 +NotifyAncestor: Final = 0 +NotifyVirtual: Final = 1 +NotifyInferior: Final = 2 +NotifyNonlinear: Final = 3 +NotifyNonlinearVirtual: Final = 4 +NotifyPointer: Final = 5 +NotifyPointerRoot: Final = 6 +NotifyDetailNone: Final = 7 +GrabtypeButton: Final = 0 +GrabtypeKeycode: Final = 1 +GrabtypeEnter: Final = 2 +GrabtypeFocusIn: Final = 3 +GrabtypeTouchBegin: Final = 4 +AnyModifier: Final = 0x80000000 +AnyButton: Final = 0 +AnyKeycode: Final = 0 +AsyncDevice: Final = 0 +SyncDevice: Final = 1 +ReplayDevice: Final = 2 +AsyncPairedDevice: Final = 3 +AsyncPair: Final = 4 +SyncPair: Final = 5 +SlaveSwitch: Final = 1 +DeviceChange: Final = 2 +MasterAdded: Final = 0x01 +MasterRemoved: Final = 0x02 +SlaveAdded: Final = 0x04 +SlaveRemoved: Final = 0x08 +SlaveAttached: Final = 0x10 +SlaveDetached: Final = 0x20 +DeviceEnabled: Final = 0x40 +DeviceDisabled: Final = 0x80 +AddMaster: Final = 1 +RemoveMaster: Final = 2 +AttachSlave: Final = 3 +DetachSlave: Final = 4 +AttachToMaster: Final = 1 +Floating: Final = 2 +ModeRelative: Final = 0 +ModeAbsolute: Final = 1 +MasterPointer: Final = 1 +MasterKeyboard: Final = 2 +SlavePointer: Final = 3 +SlaveKeyboard: Final = 4 +FloatingSlave: Final = 5 +KeyClass: Final = 0 +ButtonClass: Final = 1 +ValuatorClass: Final = 2 +ScrollClass: Final = 3 +TouchClass: Final = 8 +KeyRepeat: Final = 0x10000 +AllDevices: Final = 0 +AllMasterDevices: Final = 1 +DeviceChanged: Final = 1 +KeyPress: Final = 2 +KeyRelease: Final = 3 +ButtonPress: Final = 4 +ButtonRelease: Final = 5 +Motion: Final = 6 +Enter: Final = 7 +Leave: Final = 8 +FocusIn: Final = 9 +FocusOut: Final = 10 +HierarchyChanged: Final = 11 +PropertyEvent: Final = 12 +RawKeyPress: Final = 13 +RawKeyRelease: Final = 14 +RawButtonPress: Final = 15 +RawButtonRelease: Final = 16 +RawMotion: Final = 17 +DeviceChangedMask: Final = 0x00002 +KeyPressMask: Final = 0x00004 +KeyReleaseMask: Final = 0x00008 +ButtonPressMask: Final = 0x00010 +ButtonReleaseMask: Final = 0x00020 +MotionMask: Final = 0x00040 +EnterMask: Final = 0x00080 +LeaveMask: Final = 0x00100 +FocusInMask: Final = 0x00200 +FocusOutMask: Final = 0x00400 +HierarchyChangedMask: Final = 0x00800 +PropertyEventMask: Final = 0x01000 +RawKeyPressMask: Final = 0x02000 +RawKeyReleaseMask: Final = 0x04000 +RawButtonPressMask: Final = 0x08000 +RawButtonReleaseMask: Final = 0x10000 +RawMotionMask: Final = 0x20000 +GrabModeSync: Final = 0 +GrabModeAsync: Final = 1 +GrabModeTouch: Final = 2 +DEVICEID = rq.Card16 +DEVICE = rq.Card16 +DEVICEUSE = rq.Card8 +PROPERTY_TYPE_FLOAT: Final = "FLOAT" + +# ignore[override] because of Liskov substitution principle violations +class FP1616(rq.Int32): + def check_value(self, value: float) -> int: ... # type: ignore[override] + def parse_value(self, value: ConvertibleToFloat, display: Unused) -> float: ... # type: ignore[override] + +class FP3232(rq.ValueField): + structcode: str + def check_value(self, value: _T) -> _T: ... # type: ignore[override] + def parse_value(self, value: tuple[ConvertibleToFloat, ConvertibleToFloat], display: Unused) -> float: ... # type: ignore[override] + +class XIQueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> XIQueryVersion: ... + +class Mask(rq.List): + def __init__(self, name: str) -> None: ... + def pack_value(self, val: int | Iterable[int]) -> tuple[bytes, int, None]: ... # type: ignore[override] + +EventMask: rq.Struct + +class XISelectEvents(rq.Request): ... + +def select_events(self: drawable.Window, event_masks: Sequence[tuple[int, Sequence[int]]]) -> XISelectEvents: ... + +AnyInfo: rq.Struct + +class ButtonMask: + def __init__(self, value: int, length: int) -> None: ... + def __getitem__(self, key: int) -> int: ... + def __len__(self) -> int: ... + +class ButtonState(rq.ValueField): + structcode: None + def __init__(self, name: str) -> None: ... + def parse_binary_value( # type: ignore[override] # length: None will error. See: https://github.com/python-xlib/python-xlib/pull/248 + self, data: SliceableBuffer, display: Unused, length: int, fmt: Unused + ) -> tuple[ButtonMask, SliceableBuffer]: ... + +ButtonInfo: rq.Struct +KeyInfo: rq.Struct +ValuatorInfo: rq.Struct +ScrollInfo: rq.Struct +TouchInfo: rq.Struct +INFO_CLASSES: Final[dict[int, rq.Struct]] + +class ClassInfoClass: + structcode: None + def parse_binary(self, data: SliceableBuffer, display: display.Display | None) -> tuple[rq.DictWrapper, SliceableBuffer]: ... + +ClassInfo: ClassInfoClass +DeviceInfo: rq.Struct + +class XIQueryDevice(rq.ReplyRequest): ... + +def query_device(self: Display | resource.Resource, deviceid: int) -> XIQueryDevice: ... + +class XIListProperties(rq.ReplyRequest): ... + +def list_device_properties(self: Display | resource.Resource, deviceid: int) -> XIListProperties: ... + +class XIGetProperty(rq.ReplyRequest): ... + +def get_device_property( + self: Display | resource.Resource, deviceid: int, property: int, type: int, offset: int, length: int, delete: bool = False +) -> XIGetProperty: ... + +class XIChangeProperty(rq.Request): ... + +def change_device_property( + self: Display | resource.Resource, deviceid: int, property: int, type: int, mode: int, value: Sequence[float] | Sequence[str] +) -> XIChangeProperty: ... + +class XIDeleteProperty(rq.Request): ... + +def delete_device_property(self: Display | resource.Resource, deviceid: int, property: int) -> XIDeleteProperty: ... + +class XIGrabDevice(rq.ReplyRequest): ... + +def grab_device( + self: drawable.Window, + deviceid: int, + time: int, + grab_mode: int, + paired_device_mode: int, + owner_events: bool, + event_mask: Sequence[int], +) -> XIGrabDevice: ... + +class XIUngrabDevice(rq.Request): ... + +def ungrab_device(self: Display | resource.Resource, deviceid: int, time: int) -> XIUngrabDevice: ... + +class XIPassiveGrabDevice(rq.ReplyRequest): ... + +def passive_grab_device( + self: drawable.Window, + deviceid: int, + time: int, + detail: int, + grab_type: int, + grab_mode: int, + paired_device_mode: int, + owner_events: bool, + event_mask: Sequence[int], + modifiers: Sequence[int], +) -> XIPassiveGrabDevice: ... +def grab_keycode( + self: drawable.Window, + deviceid: int, + time: int, + keycode: int, + grab_mode: int, + paired_device_mode: int, + owner_events: bool, + event_mask: Sequence[int], + modifiers: Sequence[int], +) -> XIPassiveGrabDevice: ... + +class XIPassiveUngrabDevice(rq.Request): ... + +def passive_ungrab_device( + self: drawable.Window, deviceid: int, detail: int, grab_type: int, modifiers: Sequence[int] +) -> XIPassiveUngrabDevice: ... +def ungrab_keycode(self: drawable.Window, deviceid: int, keycode: int, modifiers: Sequence[int]) -> XIPassiveUngrabDevice: ... + +HierarchyInfo: rq.Struct +HierarchyEventData: rq.Struct +ModifierInfo: rq.Struct +GroupInfo: rq.Struct +DeviceEventData: rq.Struct +DeviceChangedEventData: rq.Struct +PropertyEventData: rq.Struct + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xtest.pyi b/stubs/python-xlib/Xlib/ext/xtest.pyi new file mode 100644 index 000000000000..5734b7195f51 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xtest.pyi @@ -0,0 +1,28 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "XTEST" +CurrentCursor: Final = 1 + +class GetVersion(rq.ReplyRequest): ... + +def get_version(self: Display | resource.Resource, major: int, minor: int) -> GetVersion: ... + +class CompareCursor(rq.ReplyRequest): ... + +def compare_cursor(self: Display | resource.Resource, cursor: int) -> int: ... + +class FakeInput(rq.Request): ... + +def fake_input( + self: Display | resource.Resource, event_type: int, detail: int = 0, time: int = 0, root: int = 0, x: int = 0, y: int = 0 +) -> None: ... + +class GrabControl(rq.Request): ... + +def grab_control(self: Display | resource.Resource, impervious: bool) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/keysymdef/__init__.pyi b/stubs/python-xlib/Xlib/keysymdef/__init__.pyi new file mode 100644 index 000000000000..ca535d0ea135 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/__init__.pyi @@ -0,0 +1,43 @@ +from Xlib.keysymdef import ( + apl as apl, + arabic as arabic, + cyrillic as cyrillic, + greek as greek, + hebrew as hebrew, + katakana as katakana, + korean as korean, + latin1 as latin1, + latin2 as latin2, + latin3 as latin3, + latin4 as latin4, + miscellany as miscellany, + publishing as publishing, + special as special, + technical as technical, + thai as thai, + xf86 as xf86, + xk3270 as xk3270, + xkb as xkb, +) + +__all__ = [ + "apl", + "arabic", + "cyrillic", + "greek", + "hebrew", + "katakana", + "korean", + "latin1", + "latin2", + "latin3", + "latin4", + "miscellany", + "publishing", + "special", + "technical", + "thai", + "xf86", + "xk3270", + "xkb", +] diff --git a/stubs/python-xlib/Xlib/keysymdef/apl.pyi b/stubs/python-xlib/Xlib/keysymdef/apl.pyi new file mode 100644 index 000000000000..869a0592657b --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/apl.pyi @@ -0,0 +1,21 @@ +from typing import Final + +XK_leftcaret: Final = 0xBA3 +XK_rightcaret: Final = 0xBA6 +XK_downcaret: Final = 0xBA8 +XK_upcaret: Final = 0xBA9 +XK_overbar: Final = 0xBC0 +XK_downtack: Final = 0xBC2 +XK_upshoe: Final = 0xBC3 +XK_downstile: Final = 0xBC4 +XK_underbar: Final = 0xBC6 +XK_jot: Final = 0xBCA +XK_quad: Final = 0xBCC +XK_uptack: Final = 0xBCE +XK_circle: Final = 0xBCF +XK_upstile: Final = 0xBD3 +XK_downshoe: Final = 0xBD6 +XK_rightshoe: Final = 0xBD8 +XK_leftshoe: Final = 0xBDA +XK_lefttack: Final = 0xBDC +XK_righttack: Final = 0xBFC diff --git a/stubs/python-xlib/Xlib/keysymdef/arabic.pyi b/stubs/python-xlib/Xlib/keysymdef/arabic.pyi new file mode 100644 index 000000000000..6823007c72ec --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/arabic.pyi @@ -0,0 +1,52 @@ +from typing import Final + +XK_Arabic_comma: Final = 0x5AC +XK_Arabic_semicolon: Final = 0x5BB +XK_Arabic_question_mark: Final = 0x5BF +XK_Arabic_hamza: Final = 0x5C1 +XK_Arabic_maddaonalef: Final = 0x5C2 +XK_Arabic_hamzaonalef: Final = 0x5C3 +XK_Arabic_hamzaonwaw: Final = 0x5C4 +XK_Arabic_hamzaunderalef: Final = 0x5C5 +XK_Arabic_hamzaonyeh: Final = 0x5C6 +XK_Arabic_alef: Final = 0x5C7 +XK_Arabic_beh: Final = 0x5C8 +XK_Arabic_tehmarbuta: Final = 0x5C9 +XK_Arabic_teh: Final = 0x5CA +XK_Arabic_theh: Final = 0x5CB +XK_Arabic_jeem: Final = 0x5CC +XK_Arabic_hah: Final = 0x5CD +XK_Arabic_khah: Final = 0x5CE +XK_Arabic_dal: Final = 0x5CF +XK_Arabic_thal: Final = 0x5D0 +XK_Arabic_ra: Final = 0x5D1 +XK_Arabic_zain: Final = 0x5D2 +XK_Arabic_seen: Final = 0x5D3 +XK_Arabic_sheen: Final = 0x5D4 +XK_Arabic_sad: Final = 0x5D5 +XK_Arabic_dad: Final = 0x5D6 +XK_Arabic_tah: Final = 0x5D7 +XK_Arabic_zah: Final = 0x5D8 +XK_Arabic_ain: Final = 0x5D9 +XK_Arabic_ghain: Final = 0x5DA +XK_Arabic_tatweel: Final = 0x5E0 +XK_Arabic_feh: Final = 0x5E1 +XK_Arabic_qaf: Final = 0x5E2 +XK_Arabic_kaf: Final = 0x5E3 +XK_Arabic_lam: Final = 0x5E4 +XK_Arabic_meem: Final = 0x5E5 +XK_Arabic_noon: Final = 0x5E6 +XK_Arabic_ha: Final = 0x5E7 +XK_Arabic_heh: Final = 0x5E7 +XK_Arabic_waw: Final = 0x5E8 +XK_Arabic_alefmaksura: Final = 0x5E9 +XK_Arabic_yeh: Final = 0x5EA +XK_Arabic_fathatan: Final = 0x5EB +XK_Arabic_dammatan: Final = 0x5EC +XK_Arabic_kasratan: Final = 0x5ED +XK_Arabic_fatha: Final = 0x5EE +XK_Arabic_damma: Final = 0x5EF +XK_Arabic_kasra: Final = 0x5F0 +XK_Arabic_shadda: Final = 0x5F1 +XK_Arabic_sukun: Final = 0x5F2 +XK_Arabic_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi b/stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi new file mode 100644 index 000000000000..4ad19a16ea64 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi @@ -0,0 +1,109 @@ +from typing import Final + +XK_Serbian_dje: Final = 0x6A1 +XK_Macedonia_gje: Final = 0x6A2 +XK_Cyrillic_io: Final = 0x6A3 +XK_Ukrainian_ie: Final = 0x6A4 +XK_Ukranian_je: Final = 0x6A4 +XK_Macedonia_dse: Final = 0x6A5 +XK_Ukrainian_i: Final = 0x6A6 +XK_Ukranian_i: Final = 0x6A6 +XK_Ukrainian_yi: Final = 0x6A7 +XK_Ukranian_yi: Final = 0x6A7 +XK_Cyrillic_je: Final = 0x6A8 +XK_Serbian_je: Final = 0x6A8 +XK_Cyrillic_lje: Final = 0x6A9 +XK_Serbian_lje: Final = 0x6A9 +XK_Cyrillic_nje: Final = 0x6AA +XK_Serbian_nje: Final = 0x6AA +XK_Serbian_tshe: Final = 0x6AB +XK_Macedonia_kje: Final = 0x6AC +XK_Byelorussian_shortu: Final = 0x6AE +XK_Cyrillic_dzhe: Final = 0x6AF +XK_Serbian_dze: Final = 0x6AF +XK_numerosign: Final = 0x6B0 +XK_Serbian_DJE: Final = 0x6B1 +XK_Macedonia_GJE: Final = 0x6B2 +XK_Cyrillic_IO: Final = 0x6B3 +XK_Ukrainian_IE: Final = 0x6B4 +XK_Ukranian_JE: Final = 0x6B4 +XK_Macedonia_DSE: Final = 0x6B5 +XK_Ukrainian_I: Final = 0x6B6 +XK_Ukranian_I: Final = 0x6B6 +XK_Ukrainian_YI: Final = 0x6B7 +XK_Ukranian_YI: Final = 0x6B7 +XK_Cyrillic_JE: Final = 0x6B8 +XK_Serbian_JE: Final = 0x6B8 +XK_Cyrillic_LJE: Final = 0x6B9 +XK_Serbian_LJE: Final = 0x6B9 +XK_Cyrillic_NJE: Final = 0x6BA +XK_Serbian_NJE: Final = 0x6BA +XK_Serbian_TSHE: Final = 0x6BB +XK_Macedonia_KJE: Final = 0x6BC +XK_Byelorussian_SHORTU: Final = 0x6BE +XK_Cyrillic_DZHE: Final = 0x6BF +XK_Serbian_DZE: Final = 0x6BF +XK_Cyrillic_yu: Final = 0x6C0 +XK_Cyrillic_a: Final = 0x6C1 +XK_Cyrillic_be: Final = 0x6C2 +XK_Cyrillic_tse: Final = 0x6C3 +XK_Cyrillic_de: Final = 0x6C4 +XK_Cyrillic_ie: Final = 0x6C5 +XK_Cyrillic_ef: Final = 0x6C6 +XK_Cyrillic_ghe: Final = 0x6C7 +XK_Cyrillic_ha: Final = 0x6C8 +XK_Cyrillic_i: Final = 0x6C9 +XK_Cyrillic_shorti: Final = 0x6CA +XK_Cyrillic_ka: Final = 0x6CB +XK_Cyrillic_el: Final = 0x6CC +XK_Cyrillic_em: Final = 0x6CD +XK_Cyrillic_en: Final = 0x6CE +XK_Cyrillic_o: Final = 0x6CF +XK_Cyrillic_pe: Final = 0x6D0 +XK_Cyrillic_ya: Final = 0x6D1 +XK_Cyrillic_er: Final = 0x6D2 +XK_Cyrillic_es: Final = 0x6D3 +XK_Cyrillic_te: Final = 0x6D4 +XK_Cyrillic_u: Final = 0x6D5 +XK_Cyrillic_zhe: Final = 0x6D6 +XK_Cyrillic_ve: Final = 0x6D7 +XK_Cyrillic_softsign: Final = 0x6D8 +XK_Cyrillic_yeru: Final = 0x6D9 +XK_Cyrillic_ze: Final = 0x6DA +XK_Cyrillic_sha: Final = 0x6DB +XK_Cyrillic_e: Final = 0x6DC +XK_Cyrillic_shcha: Final = 0x6DD +XK_Cyrillic_che: Final = 0x6DE +XK_Cyrillic_hardsign: Final = 0x6DF +XK_Cyrillic_YU: Final = 0x6E0 +XK_Cyrillic_A: Final = 0x6E1 +XK_Cyrillic_BE: Final = 0x6E2 +XK_Cyrillic_TSE: Final = 0x6E3 +XK_Cyrillic_DE: Final = 0x6E4 +XK_Cyrillic_IE: Final = 0x6E5 +XK_Cyrillic_EF: Final = 0x6E6 +XK_Cyrillic_GHE: Final = 0x6E7 +XK_Cyrillic_HA: Final = 0x6E8 +XK_Cyrillic_I: Final = 0x6E9 +XK_Cyrillic_SHORTI: Final = 0x6EA +XK_Cyrillic_KA: Final = 0x6EB +XK_Cyrillic_EL: Final = 0x6EC +XK_Cyrillic_EM: Final = 0x6ED +XK_Cyrillic_EN: Final = 0x6EE +XK_Cyrillic_O: Final = 0x6EF +XK_Cyrillic_PE: Final = 0x6F0 +XK_Cyrillic_YA: Final = 0x6F1 +XK_Cyrillic_ER: Final = 0x6F2 +XK_Cyrillic_ES: Final = 0x6F3 +XK_Cyrillic_TE: Final = 0x6F4 +XK_Cyrillic_U: Final = 0x6F5 +XK_Cyrillic_ZHE: Final = 0x6F6 +XK_Cyrillic_VE: Final = 0x6F7 +XK_Cyrillic_SOFTSIGN: Final = 0x6F8 +XK_Cyrillic_YERU: Final = 0x6F9 +XK_Cyrillic_ZE: Final = 0x6FA +XK_Cyrillic_SHA: Final = 0x6FB +XK_Cyrillic_E: Final = 0x6FC +XK_Cyrillic_SHCHA: Final = 0x6FD +XK_Cyrillic_CHE: Final = 0x6FE +XK_Cyrillic_HARDSIGN: Final = 0x6FF diff --git a/stubs/python-xlib/Xlib/keysymdef/greek.pyi b/stubs/python-xlib/Xlib/keysymdef/greek.pyi new file mode 100644 index 000000000000..2da0ef6907e3 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/greek.pyi @@ -0,0 +1,76 @@ +from typing import Final + +XK_Greek_ALPHAaccent: Final = 0x7A1 +XK_Greek_EPSILONaccent: Final = 0x7A2 +XK_Greek_ETAaccent: Final = 0x7A3 +XK_Greek_IOTAaccent: Final = 0x7A4 +XK_Greek_IOTAdiaeresis: Final = 0x7A5 +XK_Greek_OMICRONaccent: Final = 0x7A7 +XK_Greek_UPSILONaccent: Final = 0x7A8 +XK_Greek_UPSILONdieresis: Final = 0x7A9 +XK_Greek_OMEGAaccent: Final = 0x7AB +XK_Greek_accentdieresis: Final = 0x7AE +XK_Greek_horizbar: Final = 0x7AF +XK_Greek_alphaaccent: Final = 0x7B1 +XK_Greek_epsilonaccent: Final = 0x7B2 +XK_Greek_etaaccent: Final = 0x7B3 +XK_Greek_iotaaccent: Final = 0x7B4 +XK_Greek_iotadieresis: Final = 0x7B5 +XK_Greek_iotaaccentdieresis: Final = 0x7B6 +XK_Greek_omicronaccent: Final = 0x7B7 +XK_Greek_upsilonaccent: Final = 0x7B8 +XK_Greek_upsilondieresis: Final = 0x7B9 +XK_Greek_upsilonaccentdieresis: Final = 0x7BA +XK_Greek_omegaaccent: Final = 0x7BB +XK_Greek_ALPHA: Final = 0x7C1 +XK_Greek_BETA: Final = 0x7C2 +XK_Greek_GAMMA: Final = 0x7C3 +XK_Greek_DELTA: Final = 0x7C4 +XK_Greek_EPSILON: Final = 0x7C5 +XK_Greek_ZETA: Final = 0x7C6 +XK_Greek_ETA: Final = 0x7C7 +XK_Greek_THETA: Final = 0x7C8 +XK_Greek_IOTA: Final = 0x7C9 +XK_Greek_KAPPA: Final = 0x7CA +XK_Greek_LAMDA: Final = 0x7CB +XK_Greek_LAMBDA: Final = 0x7CB +XK_Greek_MU: Final = 0x7CC +XK_Greek_NU: Final = 0x7CD +XK_Greek_XI: Final = 0x7CE +XK_Greek_OMICRON: Final = 0x7CF +XK_Greek_PI: Final = 0x7D0 +XK_Greek_RHO: Final = 0x7D1 +XK_Greek_SIGMA: Final = 0x7D2 +XK_Greek_TAU: Final = 0x7D4 +XK_Greek_UPSILON: Final = 0x7D5 +XK_Greek_PHI: Final = 0x7D6 +XK_Greek_CHI: Final = 0x7D7 +XK_Greek_PSI: Final = 0x7D8 +XK_Greek_OMEGA: Final = 0x7D9 +XK_Greek_alpha: Final = 0x7E1 +XK_Greek_beta: Final = 0x7E2 +XK_Greek_gamma: Final = 0x7E3 +XK_Greek_delta: Final = 0x7E4 +XK_Greek_epsilon: Final = 0x7E5 +XK_Greek_zeta: Final = 0x7E6 +XK_Greek_eta: Final = 0x7E7 +XK_Greek_theta: Final = 0x7E8 +XK_Greek_iota: Final = 0x7E9 +XK_Greek_kappa: Final = 0x7EA +XK_Greek_lamda: Final = 0x7EB +XK_Greek_lambda: Final = 0x7EB +XK_Greek_mu: Final = 0x7EC +XK_Greek_nu: Final = 0x7ED +XK_Greek_xi: Final = 0x7EE +XK_Greek_omicron: Final = 0x7EF +XK_Greek_pi: Final = 0x7F0 +XK_Greek_rho: Final = 0x7F1 +XK_Greek_sigma: Final = 0x7F2 +XK_Greek_finalsmallsigma: Final = 0x7F3 +XK_Greek_tau: Final = 0x7F4 +XK_Greek_upsilon: Final = 0x7F5 +XK_Greek_phi: Final = 0x7F6 +XK_Greek_chi: Final = 0x7F7 +XK_Greek_psi: Final = 0x7F8 +XK_Greek_omega: Final = 0x7F9 +XK_Greek_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/hebrew.pyi b/stubs/python-xlib/Xlib/keysymdef/hebrew.pyi new file mode 100644 index 000000000000..a5db68c6c317 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/hebrew.pyi @@ -0,0 +1,42 @@ +from typing import Final + +XK_hebrew_doublelowline: Final = 0xCDF +XK_hebrew_aleph: Final = 0xCE0 +XK_hebrew_bet: Final = 0xCE1 +XK_hebrew_beth: Final = 0xCE1 +XK_hebrew_gimel: Final = 0xCE2 +XK_hebrew_gimmel: Final = 0xCE2 +XK_hebrew_dalet: Final = 0xCE3 +XK_hebrew_daleth: Final = 0xCE3 +XK_hebrew_he: Final = 0xCE4 +XK_hebrew_waw: Final = 0xCE5 +XK_hebrew_zain: Final = 0xCE6 +XK_hebrew_zayin: Final = 0xCE6 +XK_hebrew_chet: Final = 0xCE7 +XK_hebrew_het: Final = 0xCE7 +XK_hebrew_tet: Final = 0xCE8 +XK_hebrew_teth: Final = 0xCE8 +XK_hebrew_yod: Final = 0xCE9 +XK_hebrew_finalkaph: Final = 0xCEA +XK_hebrew_kaph: Final = 0xCEB +XK_hebrew_lamed: Final = 0xCEC +XK_hebrew_finalmem: Final = 0xCED +XK_hebrew_mem: Final = 0xCEE +XK_hebrew_finalnun: Final = 0xCEF +XK_hebrew_nun: Final = 0xCF0 +XK_hebrew_samech: Final = 0xCF1 +XK_hebrew_samekh: Final = 0xCF1 +XK_hebrew_ayin: Final = 0xCF2 +XK_hebrew_finalpe: Final = 0xCF3 +XK_hebrew_pe: Final = 0xCF4 +XK_hebrew_finalzade: Final = 0xCF5 +XK_hebrew_finalzadi: Final = 0xCF5 +XK_hebrew_zade: Final = 0xCF6 +XK_hebrew_zadi: Final = 0xCF6 +XK_hebrew_qoph: Final = 0xCF7 +XK_hebrew_kuf: Final = 0xCF7 +XK_hebrew_resh: Final = 0xCF8 +XK_hebrew_shin: Final = 0xCF9 +XK_hebrew_taw: Final = 0xCFA +XK_hebrew_taf: Final = 0xCFA +XK_Hebrew_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/katakana.pyi b/stubs/python-xlib/Xlib/keysymdef/katakana.pyi new file mode 100644 index 000000000000..bf83f8c053e6 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/katakana.pyi @@ -0,0 +1,72 @@ +from typing import Final + +XK_overline: Final = 0x47E +XK_kana_fullstop: Final = 0x4A1 +XK_kana_openingbracket: Final = 0x4A2 +XK_kana_closingbracket: Final = 0x4A3 +XK_kana_comma: Final = 0x4A4 +XK_kana_conjunctive: Final = 0x4A5 +XK_kana_middledot: Final = 0x4A5 +XK_kana_WO: Final = 0x4A6 +XK_kana_a: Final = 0x4A7 +XK_kana_i: Final = 0x4A8 +XK_kana_u: Final = 0x4A9 +XK_kana_e: Final = 0x4AA +XK_kana_o: Final = 0x4AB +XK_kana_ya: Final = 0x4AC +XK_kana_yu: Final = 0x4AD +XK_kana_yo: Final = 0x4AE +XK_kana_tsu: Final = 0x4AF +XK_kana_tu: Final = 0x4AF +XK_prolongedsound: Final = 0x4B0 +XK_kana_A: Final = 0x4B1 +XK_kana_I: Final = 0x4B2 +XK_kana_U: Final = 0x4B3 +XK_kana_E: Final = 0x4B4 +XK_kana_O: Final = 0x4B5 +XK_kana_KA: Final = 0x4B6 +XK_kana_KI: Final = 0x4B7 +XK_kana_KU: Final = 0x4B8 +XK_kana_KE: Final = 0x4B9 +XK_kana_KO: Final = 0x4BA +XK_kana_SA: Final = 0x4BB +XK_kana_SHI: Final = 0x4BC +XK_kana_SU: Final = 0x4BD +XK_kana_SE: Final = 0x4BE +XK_kana_SO: Final = 0x4BF +XK_kana_TA: Final = 0x4C0 +XK_kana_CHI: Final = 0x4C1 +XK_kana_TI: Final = 0x4C1 +XK_kana_TSU: Final = 0x4C2 +XK_kana_TU: Final = 0x4C2 +XK_kana_TE: Final = 0x4C3 +XK_kana_TO: Final = 0x4C4 +XK_kana_NA: Final = 0x4C5 +XK_kana_NI: Final = 0x4C6 +XK_kana_NU: Final = 0x4C7 +XK_kana_NE: Final = 0x4C8 +XK_kana_NO: Final = 0x4C9 +XK_kana_HA: Final = 0x4CA +XK_kana_HI: Final = 0x4CB +XK_kana_FU: Final = 0x4CC +XK_kana_HU: Final = 0x4CC +XK_kana_HE: Final = 0x4CD +XK_kana_HO: Final = 0x4CE +XK_kana_MA: Final = 0x4CF +XK_kana_MI: Final = 0x4D0 +XK_kana_MU: Final = 0x4D1 +XK_kana_ME: Final = 0x4D2 +XK_kana_MO: Final = 0x4D3 +XK_kana_YA: Final = 0x4D4 +XK_kana_YU: Final = 0x4D5 +XK_kana_YO: Final = 0x4D6 +XK_kana_RA: Final = 0x4D7 +XK_kana_RI: Final = 0x4D8 +XK_kana_RU: Final = 0x4D9 +XK_kana_RE: Final = 0x4DA +XK_kana_RO: Final = 0x4DB +XK_kana_WA: Final = 0x4DC +XK_kana_N: Final = 0x4DD +XK_voicedsound: Final = 0x4DE +XK_semivoicedsound: Final = 0x4DF +XK_kana_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/korean.pyi b/stubs/python-xlib/Xlib/keysymdef/korean.pyi new file mode 100644 index 000000000000..492965233730 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/korean.pyi @@ -0,0 +1,109 @@ +from typing import Final + +XK_Hangul: Final = 0xFF31 +XK_Hangul_Start: Final = 0xFF32 +XK_Hangul_End: Final = 0xFF33 +XK_Hangul_Hanja: Final = 0xFF34 +XK_Hangul_Jamo: Final = 0xFF35 +XK_Hangul_Romaja: Final = 0xFF36 +XK_Hangul_Codeinput: Final = 0xFF37 +XK_Hangul_Jeonja: Final = 0xFF38 +XK_Hangul_Banja: Final = 0xFF39 +XK_Hangul_PreHanja: Final = 0xFF3A +XK_Hangul_PostHanja: Final = 0xFF3B +XK_Hangul_SingleCandidate: Final = 0xFF3C +XK_Hangul_MultipleCandidate: Final = 0xFF3D +XK_Hangul_PreviousCandidate: Final = 0xFF3E +XK_Hangul_Special: Final = 0xFF3F +XK_Hangul_switch: Final = 0xFF7E +XK_Hangul_Kiyeog: Final = 0xEA1 +XK_Hangul_SsangKiyeog: Final = 0xEA2 +XK_Hangul_KiyeogSios: Final = 0xEA3 +XK_Hangul_Nieun: Final = 0xEA4 +XK_Hangul_NieunJieuj: Final = 0xEA5 +XK_Hangul_NieunHieuh: Final = 0xEA6 +XK_Hangul_Dikeud: Final = 0xEA7 +XK_Hangul_SsangDikeud: Final = 0xEA8 +XK_Hangul_Rieul: Final = 0xEA9 +XK_Hangul_RieulKiyeog: Final = 0xEAA +XK_Hangul_RieulMieum: Final = 0xEAB +XK_Hangul_RieulPieub: Final = 0xEAC +XK_Hangul_RieulSios: Final = 0xEAD +XK_Hangul_RieulTieut: Final = 0xEAE +XK_Hangul_RieulPhieuf: Final = 0xEAF +XK_Hangul_RieulHieuh: Final = 0xEB0 +XK_Hangul_Mieum: Final = 0xEB1 +XK_Hangul_Pieub: Final = 0xEB2 +XK_Hangul_SsangPieub: Final = 0xEB3 +XK_Hangul_PieubSios: Final = 0xEB4 +XK_Hangul_Sios: Final = 0xEB5 +XK_Hangul_SsangSios: Final = 0xEB6 +XK_Hangul_Ieung: Final = 0xEB7 +XK_Hangul_Jieuj: Final = 0xEB8 +XK_Hangul_SsangJieuj: Final = 0xEB9 +XK_Hangul_Cieuc: Final = 0xEBA +XK_Hangul_Khieuq: Final = 0xEBB +XK_Hangul_Tieut: Final = 0xEBC +XK_Hangul_Phieuf: Final = 0xEBD +XK_Hangul_Hieuh: Final = 0xEBE +XK_Hangul_A: Final = 0xEBF +XK_Hangul_AE: Final = 0xEC0 +XK_Hangul_YA: Final = 0xEC1 +XK_Hangul_YAE: Final = 0xEC2 +XK_Hangul_EO: Final = 0xEC3 +XK_Hangul_E: Final = 0xEC4 +XK_Hangul_YEO: Final = 0xEC5 +XK_Hangul_YE: Final = 0xEC6 +XK_Hangul_O: Final = 0xEC7 +XK_Hangul_WA: Final = 0xEC8 +XK_Hangul_WAE: Final = 0xEC9 +XK_Hangul_OE: Final = 0xECA +XK_Hangul_YO: Final = 0xECB +XK_Hangul_U: Final = 0xECC +XK_Hangul_WEO: Final = 0xECD +XK_Hangul_WE: Final = 0xECE +XK_Hangul_WI: Final = 0xECF +XK_Hangul_YU: Final = 0xED0 +XK_Hangul_EU: Final = 0xED1 +XK_Hangul_YI: Final = 0xED2 +XK_Hangul_I: Final = 0xED3 +XK_Hangul_J_Kiyeog: Final = 0xED4 +XK_Hangul_J_SsangKiyeog: Final = 0xED5 +XK_Hangul_J_KiyeogSios: Final = 0xED6 +XK_Hangul_J_Nieun: Final = 0xED7 +XK_Hangul_J_NieunJieuj: Final = 0xED8 +XK_Hangul_J_NieunHieuh: Final = 0xED9 +XK_Hangul_J_Dikeud: Final = 0xEDA +XK_Hangul_J_Rieul: Final = 0xEDB +XK_Hangul_J_RieulKiyeog: Final = 0xEDC +XK_Hangul_J_RieulMieum: Final = 0xEDD +XK_Hangul_J_RieulPieub: Final = 0xEDE +XK_Hangul_J_RieulSios: Final = 0xEDF +XK_Hangul_J_RieulTieut: Final = 0xEE0 +XK_Hangul_J_RieulPhieuf: Final = 0xEE1 +XK_Hangul_J_RieulHieuh: Final = 0xEE2 +XK_Hangul_J_Mieum: Final = 0xEE3 +XK_Hangul_J_Pieub: Final = 0xEE4 +XK_Hangul_J_PieubSios: Final = 0xEE5 +XK_Hangul_J_Sios: Final = 0xEE6 +XK_Hangul_J_SsangSios: Final = 0xEE7 +XK_Hangul_J_Ieung: Final = 0xEE8 +XK_Hangul_J_Jieuj: Final = 0xEE9 +XK_Hangul_J_Cieuc: Final = 0xEEA +XK_Hangul_J_Khieuq: Final = 0xEEB +XK_Hangul_J_Tieut: Final = 0xEEC +XK_Hangul_J_Phieuf: Final = 0xEED +XK_Hangul_J_Hieuh: Final = 0xEEE +XK_Hangul_RieulYeorinHieuh: Final = 0xEEF +XK_Hangul_SunkyeongeumMieum: Final = 0xEF0 +XK_Hangul_SunkyeongeumPieub: Final = 0xEF1 +XK_Hangul_PanSios: Final = 0xEF2 +XK_Hangul_KkogjiDalrinIeung: Final = 0xEF3 +XK_Hangul_SunkyeongeumPhieuf: Final = 0xEF4 +XK_Hangul_YeorinHieuh: Final = 0xEF5 +XK_Hangul_AraeA: Final = 0xEF6 +XK_Hangul_AraeAE: Final = 0xEF7 +XK_Hangul_J_PanSios: Final = 0xEF8 +XK_Hangul_J_KkogjiDalrinIeung: Final = 0xEF9 +XK_Hangul_J_YeorinHieuh: Final = 0xEFA +XK_Korean_Won: Final = 0xEFF diff --git a/stubs/python-xlib/Xlib/keysymdef/latin1.pyi b/stubs/python-xlib/Xlib/keysymdef/latin1.pyi new file mode 100644 index 000000000000..2659a0a55b63 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin1.pyi @@ -0,0 +1,197 @@ +from typing import Final + +XK_space: Final = 0x020 +XK_exclam: Final = 0x021 +XK_quotedbl: Final = 0x022 +XK_numbersign: Final = 0x023 +XK_dollar: Final = 0x024 +XK_percent: Final = 0x025 +XK_ampersand: Final = 0x026 +XK_apostrophe: Final = 0x027 +XK_quoteright: Final = 0x027 +XK_parenleft: Final = 0x028 +XK_parenright: Final = 0x029 +XK_asterisk: Final = 0x02A +XK_plus: Final = 0x02B +XK_comma: Final = 0x02C +XK_minus: Final = 0x02D +XK_period: Final = 0x02E +XK_slash: Final = 0x02F +XK_0: Final = 0x030 +XK_1: Final = 0x031 +XK_2: Final = 0x032 +XK_3: Final = 0x033 +XK_4: Final = 0x034 +XK_5: Final = 0x035 +XK_6: Final = 0x036 +XK_7: Final = 0x037 +XK_8: Final = 0x038 +XK_9: Final = 0x039 +XK_colon: Final = 0x03A +XK_semicolon: Final = 0x03B +XK_less: Final = 0x03C +XK_equal: Final = 0x03D +XK_greater: Final = 0x03E +XK_question: Final = 0x03F +XK_at: Final = 0x040 +XK_A: Final = 0x041 +XK_B: Final = 0x042 +XK_C: Final = 0x043 +XK_D: Final = 0x044 +XK_E: Final = 0x045 +XK_F: Final = 0x046 +XK_G: Final = 0x047 +XK_H: Final = 0x048 +XK_I: Final = 0x049 +XK_J: Final = 0x04A +XK_K: Final = 0x04B +XK_L: Final = 0x04C +XK_M: Final = 0x04D +XK_N: Final = 0x04E +XK_O: Final = 0x04F +XK_P: Final = 0x050 +XK_Q: Final = 0x051 +XK_R: Final = 0x052 +XK_S: Final = 0x053 +XK_T: Final = 0x054 +XK_U: Final = 0x055 +XK_V: Final = 0x056 +XK_W: Final = 0x057 +XK_X: Final = 0x058 +XK_Y: Final = 0x059 +XK_Z: Final = 0x05A +XK_bracketleft: Final = 0x05B +XK_backslash: Final = 0x05C +XK_bracketright: Final = 0x05D +XK_asciicircum: Final = 0x05E +XK_underscore: Final = 0x05F +XK_grave: Final = 0x060 +XK_quoteleft: Final = 0x060 +XK_a: Final = 0x061 +XK_b: Final = 0x062 +XK_c: Final = 0x063 +XK_d: Final = 0x064 +XK_e: Final = 0x065 +XK_f: Final = 0x066 +XK_g: Final = 0x067 +XK_h: Final = 0x068 +XK_i: Final = 0x069 +XK_j: Final = 0x06A +XK_k: Final = 0x06B +XK_l: Final = 0x06C +XK_m: Final = 0x06D +XK_n: Final = 0x06E +XK_o: Final = 0x06F +XK_p: Final = 0x070 +XK_q: Final = 0x071 +XK_r: Final = 0x072 +XK_s: Final = 0x073 +XK_t: Final = 0x074 +XK_u: Final = 0x075 +XK_v: Final = 0x076 +XK_w: Final = 0x077 +XK_x: Final = 0x078 +XK_y: Final = 0x079 +XK_z: Final = 0x07A +XK_braceleft: Final = 0x07B +XK_bar: Final = 0x07C +XK_braceright: Final = 0x07D +XK_asciitilde: Final = 0x07E +XK_nobreakspace: Final = 0x0A0 +XK_exclamdown: Final = 0x0A1 +XK_cent: Final = 0x0A2 +XK_sterling: Final = 0x0A3 +XK_currency: Final = 0x0A4 +XK_yen: Final = 0x0A5 +XK_brokenbar: Final = 0x0A6 +XK_section: Final = 0x0A7 +XK_diaeresis: Final = 0x0A8 +XK_copyright: Final = 0x0A9 +XK_ordfeminine: Final = 0x0AA +XK_guillemotleft: Final = 0x0AB +XK_notsign: Final = 0x0AC +XK_hyphen: Final = 0x0AD +XK_registered: Final = 0x0AE +XK_macron: Final = 0x0AF +XK_degree: Final = 0x0B0 +XK_plusminus: Final = 0x0B1 +XK_twosuperior: Final = 0x0B2 +XK_threesuperior: Final = 0x0B3 +XK_acute: Final = 0x0B4 +XK_mu: Final = 0x0B5 +XK_paragraph: Final = 0x0B6 +XK_periodcentered: Final = 0x0B7 +XK_cedilla: Final = 0x0B8 +XK_onesuperior: Final = 0x0B9 +XK_masculine: Final = 0x0BA +XK_guillemotright: Final = 0x0BB +XK_onequarter: Final = 0x0BC +XK_onehalf: Final = 0x0BD +XK_threequarters: Final = 0x0BE +XK_questiondown: Final = 0x0BF +XK_Agrave: Final = 0x0C0 +XK_Aacute: Final = 0x0C1 +XK_Acircumflex: Final = 0x0C2 +XK_Atilde: Final = 0x0C3 +XK_Adiaeresis: Final = 0x0C4 +XK_Aring: Final = 0x0C5 +XK_AE: Final = 0x0C6 +XK_Ccedilla: Final = 0x0C7 +XK_Egrave: Final = 0x0C8 +XK_Eacute: Final = 0x0C9 +XK_Ecircumflex: Final = 0x0CA +XK_Ediaeresis: Final = 0x0CB +XK_Igrave: Final = 0x0CC +XK_Iacute: Final = 0x0CD +XK_Icircumflex: Final = 0x0CE +XK_Idiaeresis: Final = 0x0CF +XK_ETH: Final = 0x0D0 +XK_Eth: Final = 0x0D0 +XK_Ntilde: Final = 0x0D1 +XK_Ograve: Final = 0x0D2 +XK_Oacute: Final = 0x0D3 +XK_Ocircumflex: Final = 0x0D4 +XK_Otilde: Final = 0x0D5 +XK_Odiaeresis: Final = 0x0D6 +XK_multiply: Final = 0x0D7 +XK_Ooblique: Final = 0x0D8 +XK_Ugrave: Final = 0x0D9 +XK_Uacute: Final = 0x0DA +XK_Ucircumflex: Final = 0x0DB +XK_Udiaeresis: Final = 0x0DC +XK_Yacute: Final = 0x0DD +XK_THORN: Final = 0x0DE +XK_Thorn: Final = 0x0DE +XK_ssharp: Final = 0x0DF +XK_agrave: Final = 0x0E0 +XK_aacute: Final = 0x0E1 +XK_acircumflex: Final = 0x0E2 +XK_atilde: Final = 0x0E3 +XK_adiaeresis: Final = 0x0E4 +XK_aring: Final = 0x0E5 +XK_ae: Final = 0x0E6 +XK_ccedilla: Final = 0x0E7 +XK_egrave: Final = 0x0E8 +XK_eacute: Final = 0x0E9 +XK_ecircumflex: Final = 0x0EA +XK_ediaeresis: Final = 0x0EB +XK_igrave: Final = 0x0EC +XK_iacute: Final = 0x0ED +XK_icircumflex: Final = 0x0EE +XK_idiaeresis: Final = 0x0EF +XK_eth: Final = 0x0F0 +XK_ntilde: Final = 0x0F1 +XK_ograve: Final = 0x0F2 +XK_oacute: Final = 0x0F3 +XK_ocircumflex: Final = 0x0F4 +XK_otilde: Final = 0x0F5 +XK_odiaeresis: Final = 0x0F6 +XK_division: Final = 0x0F7 +XK_oslash: Final = 0x0F8 +XK_ugrave: Final = 0x0F9 +XK_uacute: Final = 0x0FA +XK_ucircumflex: Final = 0x0FB +XK_udiaeresis: Final = 0x0FC +XK_yacute: Final = 0x0FD +XK_thorn: Final = 0x0FE +XK_ydiaeresis: Final = 0x0FF diff --git a/stubs/python-xlib/Xlib/keysymdef/latin2.pyi b/stubs/python-xlib/Xlib/keysymdef/latin2.pyi new file mode 100644 index 000000000000..f867732c6158 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin2.pyi @@ -0,0 +1,59 @@ +from typing import Final + +XK_Aogonek: Final = 0x1A1 +XK_breve: Final = 0x1A2 +XK_Lstroke: Final = 0x1A3 +XK_Lcaron: Final = 0x1A5 +XK_Sacute: Final = 0x1A6 +XK_Scaron: Final = 0x1A9 +XK_Scedilla: Final = 0x1AA +XK_Tcaron: Final = 0x1AB +XK_Zacute: Final = 0x1AC +XK_Zcaron: Final = 0x1AE +XK_Zabovedot: Final = 0x1AF +XK_aogonek: Final = 0x1B1 +XK_ogonek: Final = 0x1B2 +XK_lstroke: Final = 0x1B3 +XK_lcaron: Final = 0x1B5 +XK_sacute: Final = 0x1B6 +XK_caron: Final = 0x1B7 +XK_scaron: Final = 0x1B9 +XK_scedilla: Final = 0x1BA +XK_tcaron: Final = 0x1BB +XK_zacute: Final = 0x1BC +XK_doubleacute: Final = 0x1BD +XK_zcaron: Final = 0x1BE +XK_zabovedot: Final = 0x1BF +XK_Racute: Final = 0x1C0 +XK_Abreve: Final = 0x1C3 +XK_Lacute: Final = 0x1C5 +XK_Cacute: Final = 0x1C6 +XK_Ccaron: Final = 0x1C8 +XK_Eogonek: Final = 0x1CA +XK_Ecaron: Final = 0x1CC +XK_Dcaron: Final = 0x1CF +XK_Dstroke: Final = 0x1D0 +XK_Nacute: Final = 0x1D1 +XK_Ncaron: Final = 0x1D2 +XK_Odoubleacute: Final = 0x1D5 +XK_Rcaron: Final = 0x1D8 +XK_Uring: Final = 0x1D9 +XK_Udoubleacute: Final = 0x1DB +XK_Tcedilla: Final = 0x1DE +XK_racute: Final = 0x1E0 +XK_abreve: Final = 0x1E3 +XK_lacute: Final = 0x1E5 +XK_cacute: Final = 0x1E6 +XK_ccaron: Final = 0x1E8 +XK_eogonek: Final = 0x1EA +XK_ecaron: Final = 0x1EC +XK_dcaron: Final = 0x1EF +XK_dstroke: Final = 0x1F0 +XK_nacute: Final = 0x1F1 +XK_ncaron: Final = 0x1F2 +XK_odoubleacute: Final = 0x1F5 +XK_udoubleacute: Final = 0x1FB +XK_rcaron: Final = 0x1F8 +XK_uring: Final = 0x1F9 +XK_tcedilla: Final = 0x1FE +XK_abovedot: Final = 0x1FF diff --git a/stubs/python-xlib/Xlib/keysymdef/latin3.pyi b/stubs/python-xlib/Xlib/keysymdef/latin3.pyi new file mode 100644 index 000000000000..acd840e78847 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin3.pyi @@ -0,0 +1,24 @@ +from typing import Final + +XK_Hstroke: Final = 0x2A1 +XK_Hcircumflex: Final = 0x2A6 +XK_Iabovedot: Final = 0x2A9 +XK_Gbreve: Final = 0x2AB +XK_Jcircumflex: Final = 0x2AC +XK_hstroke: Final = 0x2B1 +XK_hcircumflex: Final = 0x2B6 +XK_idotless: Final = 0x2B9 +XK_gbreve: Final = 0x2BB +XK_jcircumflex: Final = 0x2BC +XK_Cabovedot: Final = 0x2C5 +XK_Ccircumflex: Final = 0x2C6 +XK_Gabovedot: Final = 0x2D5 +XK_Gcircumflex: Final = 0x2D8 +XK_Ubreve: Final = 0x2DD +XK_Scircumflex: Final = 0x2DE +XK_cabovedot: Final = 0x2E5 +XK_ccircumflex: Final = 0x2E6 +XK_gabovedot: Final = 0x2F5 +XK_gcircumflex: Final = 0x2F8 +XK_ubreve: Final = 0x2FD +XK_scircumflex: Final = 0x2FE diff --git a/stubs/python-xlib/Xlib/keysymdef/latin4.pyi b/stubs/python-xlib/Xlib/keysymdef/latin4.pyi new file mode 100644 index 000000000000..5b7a58c9f8d7 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin4.pyi @@ -0,0 +1,38 @@ +from typing import Final + +XK_kra: Final = 0x3A2 +XK_kappa: Final = 0x3A2 +XK_Rcedilla: Final = 0x3A3 +XK_Itilde: Final = 0x3A5 +XK_Lcedilla: Final = 0x3A6 +XK_Emacron: Final = 0x3AA +XK_Gcedilla: Final = 0x3AB +XK_Tslash: Final = 0x3AC +XK_rcedilla: Final = 0x3B3 +XK_itilde: Final = 0x3B5 +XK_lcedilla: Final = 0x3B6 +XK_emacron: Final = 0x3BA +XK_gcedilla: Final = 0x3BB +XK_tslash: Final = 0x3BC +XK_ENG: Final = 0x3BD +XK_eng: Final = 0x3BF +XK_Amacron: Final = 0x3C0 +XK_Iogonek: Final = 0x3C7 +XK_Eabovedot: Final = 0x3CC +XK_Imacron: Final = 0x3CF +XK_Ncedilla: Final = 0x3D1 +XK_Omacron: Final = 0x3D2 +XK_Kcedilla: Final = 0x3D3 +XK_Uogonek: Final = 0x3D9 +XK_Utilde: Final = 0x3DD +XK_Umacron: Final = 0x3DE +XK_amacron: Final = 0x3E0 +XK_iogonek: Final = 0x3E7 +XK_eabovedot: Final = 0x3EC +XK_imacron: Final = 0x3EF +XK_ncedilla: Final = 0x3F1 +XK_omacron: Final = 0x3F2 +XK_kcedilla: Final = 0x3F3 +XK_uogonek: Final = 0x3F9 +XK_utilde: Final = 0x3FD +XK_umacron: Final = 0x3FE diff --git a/stubs/python-xlib/Xlib/keysymdef/miscellany.pyi b/stubs/python-xlib/Xlib/keysymdef/miscellany.pyi new file mode 100644 index 000000000000..70b11a05430d --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/miscellany.pyi @@ -0,0 +1,171 @@ +from typing import Final + +XK_BackSpace: Final = 0xFF08 +XK_Tab: Final = 0xFF09 +XK_Linefeed: Final = 0xFF0A +XK_Clear: Final = 0xFF0B +XK_Return: Final = 0xFF0D +XK_Pause: Final = 0xFF13 +XK_Scroll_Lock: Final = 0xFF14 +XK_Sys_Req: Final = 0xFF15 +XK_Escape: Final = 0xFF1B +XK_Delete: Final = 0xFFFF +XK_Multi_key: Final = 0xFF20 +XK_SingleCandidate: Final = 0xFF3C +XK_MultipleCandidate: Final = 0xFF3D +XK_PreviousCandidate: Final = 0xFF3E +XK_Kanji: Final = 0xFF21 +XK_Muhenkan: Final = 0xFF22 +XK_Henkan_Mode: Final = 0xFF23 +XK_Henkan: Final = 0xFF23 +XK_Romaji: Final = 0xFF24 +XK_Hiragana: Final = 0xFF25 +XK_Katakana: Final = 0xFF26 +XK_Hiragana_Katakana: Final = 0xFF27 +XK_Zenkaku: Final = 0xFF28 +XK_Hankaku: Final = 0xFF29 +XK_Zenkaku_Hankaku: Final = 0xFF2A +XK_Touroku: Final = 0xFF2B +XK_Massyo: Final = 0xFF2C +XK_Kana_Lock: Final = 0xFF2D +XK_Kana_Shift: Final = 0xFF2E +XK_Eisu_Shift: Final = 0xFF2F +XK_Eisu_toggle: Final = 0xFF30 +XK_Zen_Koho: Final = 0xFF3D +XK_Mae_Koho: Final = 0xFF3E +XK_Home: Final = 0xFF50 +XK_Left: Final = 0xFF51 +XK_Up: Final = 0xFF52 +XK_Right: Final = 0xFF53 +XK_Down: Final = 0xFF54 +XK_Prior: Final = 0xFF55 +XK_Page_Up: Final = 0xFF55 +XK_Next: Final = 0xFF56 +XK_Page_Down: Final = 0xFF56 +XK_End: Final = 0xFF57 +XK_Begin: Final = 0xFF58 +XK_Select: Final = 0xFF60 +XK_Print: Final = 0xFF61 +XK_Execute: Final = 0xFF62 +XK_Insert: Final = 0xFF63 +XK_Undo: Final = 0xFF65 +XK_Redo: Final = 0xFF66 +XK_Menu: Final = 0xFF67 +XK_Find: Final = 0xFF68 +XK_Cancel: Final = 0xFF69 +XK_Help: Final = 0xFF6A +XK_Break: Final = 0xFF6B +XK_Mode_switch: Final = 0xFF7E +XK_script_switch: Final = 0xFF7E +XK_Num_Lock: Final = 0xFF7F +XK_KP_Space: Final = 0xFF80 +XK_KP_Tab: Final = 0xFF89 +XK_KP_Enter: Final = 0xFF8D +XK_KP_F1: Final = 0xFF91 +XK_KP_F2: Final = 0xFF92 +XK_KP_F3: Final = 0xFF93 +XK_KP_F4: Final = 0xFF94 +XK_KP_Home: Final = 0xFF95 +XK_KP_Left: Final = 0xFF96 +XK_KP_Up: Final = 0xFF97 +XK_KP_Right: Final = 0xFF98 +XK_KP_Down: Final = 0xFF99 +XK_KP_Prior: Final = 0xFF9A +XK_KP_Page_Up: Final = 0xFF9A +XK_KP_Next: Final = 0xFF9B +XK_KP_Page_Down: Final = 0xFF9B +XK_KP_End: Final = 0xFF9C +XK_KP_Begin: Final = 0xFF9D +XK_KP_Insert: Final = 0xFF9E +XK_KP_Delete: Final = 0xFF9F +XK_KP_Equal: Final = 0xFFBD +XK_KP_Multiply: Final = 0xFFAA +XK_KP_Add: Final = 0xFFAB +XK_KP_Separator: Final = 0xFFAC +XK_KP_Subtract: Final = 0xFFAD +XK_KP_Decimal: Final = 0xFFAE +XK_KP_Divide: Final = 0xFFAF +XK_KP_0: Final = 0xFFB0 +XK_KP_1: Final = 0xFFB1 +XK_KP_2: Final = 0xFFB2 +XK_KP_3: Final = 0xFFB3 +XK_KP_4: Final = 0xFFB4 +XK_KP_5: Final = 0xFFB5 +XK_KP_6: Final = 0xFFB6 +XK_KP_7: Final = 0xFFB7 +XK_KP_8: Final = 0xFFB8 +XK_KP_9: Final = 0xFFB9 +XK_F1: Final = 0xFFBE +XK_F2: Final = 0xFFBF +XK_F3: Final = 0xFFC0 +XK_F4: Final = 0xFFC1 +XK_F5: Final = 0xFFC2 +XK_F6: Final = 0xFFC3 +XK_F7: Final = 0xFFC4 +XK_F8: Final = 0xFFC5 +XK_F9: Final = 0xFFC6 +XK_F10: Final = 0xFFC7 +XK_F11: Final = 0xFFC8 +XK_L1: Final = 0xFFC8 +XK_F12: Final = 0xFFC9 +XK_L2: Final = 0xFFC9 +XK_F13: Final = 0xFFCA +XK_L3: Final = 0xFFCA +XK_F14: Final = 0xFFCB +XK_L4: Final = 0xFFCB +XK_F15: Final = 0xFFCC +XK_L5: Final = 0xFFCC +XK_F16: Final = 0xFFCD +XK_L6: Final = 0xFFCD +XK_F17: Final = 0xFFCE +XK_L7: Final = 0xFFCE +XK_F18: Final = 0xFFCF +XK_L8: Final = 0xFFCF +XK_F19: Final = 0xFFD0 +XK_L9: Final = 0xFFD0 +XK_F20: Final = 0xFFD1 +XK_L10: Final = 0xFFD1 +XK_F21: Final = 0xFFD2 +XK_R1: Final = 0xFFD2 +XK_F22: Final = 0xFFD3 +XK_R2: Final = 0xFFD3 +XK_F23: Final = 0xFFD4 +XK_R3: Final = 0xFFD4 +XK_F24: Final = 0xFFD5 +XK_R4: Final = 0xFFD5 +XK_F25: Final = 0xFFD6 +XK_R5: Final = 0xFFD6 +XK_F26: Final = 0xFFD7 +XK_R6: Final = 0xFFD7 +XK_F27: Final = 0xFFD8 +XK_R7: Final = 0xFFD8 +XK_F28: Final = 0xFFD9 +XK_R8: Final = 0xFFD9 +XK_F29: Final = 0xFFDA +XK_R9: Final = 0xFFDA +XK_F30: Final = 0xFFDB +XK_R10: Final = 0xFFDB +XK_F31: Final = 0xFFDC +XK_R11: Final = 0xFFDC +XK_F32: Final = 0xFFDD +XK_R12: Final = 0xFFDD +XK_F33: Final = 0xFFDE +XK_R13: Final = 0xFFDE +XK_F34: Final = 0xFFDF +XK_R14: Final = 0xFFDF +XK_F35: Final = 0xFFE0 +XK_R15: Final = 0xFFE0 +XK_Shift_L: Final = 0xFFE1 +XK_Shift_R: Final = 0xFFE2 +XK_Control_L: Final = 0xFFE3 +XK_Control_R: Final = 0xFFE4 +XK_Caps_Lock: Final = 0xFFE5 +XK_Shift_Lock: Final = 0xFFE6 +XK_Meta_L: Final = 0xFFE7 +XK_Meta_R: Final = 0xFFE8 +XK_Alt_L: Final = 0xFFE9 +XK_Alt_R: Final = 0xFFEA +XK_Super_L: Final = 0xFFEB +XK_Super_R: Final = 0xFFEC +XK_Hyper_L: Final = 0xFFED +XK_Hyper_R: Final = 0xFFEE diff --git a/stubs/python-xlib/Xlib/keysymdef/publishing.pyi b/stubs/python-xlib/Xlib/keysymdef/publishing.pyi new file mode 100644 index 000000000000..3c7e8f8cdb5f --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/publishing.pyi @@ -0,0 +1,85 @@ +from typing import Final + +XK_emspace: Final = 0xAA1 +XK_enspace: Final = 0xAA2 +XK_em3space: Final = 0xAA3 +XK_em4space: Final = 0xAA4 +XK_digitspace: Final = 0xAA5 +XK_punctspace: Final = 0xAA6 +XK_thinspace: Final = 0xAA7 +XK_hairspace: Final = 0xAA8 +XK_emdash: Final = 0xAA9 +XK_endash: Final = 0xAAA +XK_signifblank: Final = 0xAAC +XK_ellipsis: Final = 0xAAE +XK_doubbaselinedot: Final = 0xAAF +XK_onethird: Final = 0xAB0 +XK_twothirds: Final = 0xAB1 +XK_onefifth: Final = 0xAB2 +XK_twofifths: Final = 0xAB3 +XK_threefifths: Final = 0xAB4 +XK_fourfifths: Final = 0xAB5 +XK_onesixth: Final = 0xAB6 +XK_fivesixths: Final = 0xAB7 +XK_careof: Final = 0xAB8 +XK_figdash: Final = 0xABB +XK_leftanglebracket: Final = 0xABC +XK_decimalpoint: Final = 0xABD +XK_rightanglebracket: Final = 0xABE +XK_marker: Final = 0xABF +XK_oneeighth: Final = 0xAC3 +XK_threeeighths: Final = 0xAC4 +XK_fiveeighths: Final = 0xAC5 +XK_seveneighths: Final = 0xAC6 +XK_trademark: Final = 0xAC9 +XK_signaturemark: Final = 0xACA +XK_trademarkincircle: Final = 0xACB +XK_leftopentriangle: Final = 0xACC +XK_rightopentriangle: Final = 0xACD +XK_emopencircle: Final = 0xACE +XK_emopenrectangle: Final = 0xACF +XK_leftsinglequotemark: Final = 0xAD0 +XK_rightsinglequotemark: Final = 0xAD1 +XK_leftdoublequotemark: Final = 0xAD2 +XK_rightdoublequotemark: Final = 0xAD3 +XK_prescription: Final = 0xAD4 +XK_minutes: Final = 0xAD6 +XK_seconds: Final = 0xAD7 +XK_latincross: Final = 0xAD9 +XK_hexagram: Final = 0xADA +XK_filledrectbullet: Final = 0xADB +XK_filledlefttribullet: Final = 0xADC +XK_filledrighttribullet: Final = 0xADD +XK_emfilledcircle: Final = 0xADE +XK_emfilledrect: Final = 0xADF +XK_enopencircbullet: Final = 0xAE0 +XK_enopensquarebullet: Final = 0xAE1 +XK_openrectbullet: Final = 0xAE2 +XK_opentribulletup: Final = 0xAE3 +XK_opentribulletdown: Final = 0xAE4 +XK_openstar: Final = 0xAE5 +XK_enfilledcircbullet: Final = 0xAE6 +XK_enfilledsqbullet: Final = 0xAE7 +XK_filledtribulletup: Final = 0xAE8 +XK_filledtribulletdown: Final = 0xAE9 +XK_leftpointer: Final = 0xAEA +XK_rightpointer: Final = 0xAEB +XK_club: Final = 0xAEC +XK_diamond: Final = 0xAED +XK_heart: Final = 0xAEE +XK_maltesecross: Final = 0xAF0 +XK_dagger: Final = 0xAF1 +XK_doubledagger: Final = 0xAF2 +XK_checkmark: Final = 0xAF3 +XK_ballotcross: Final = 0xAF4 +XK_musicalsharp: Final = 0xAF5 +XK_musicalflat: Final = 0xAF6 +XK_malesymbol: Final = 0xAF7 +XK_femalesymbol: Final = 0xAF8 +XK_telephone: Final = 0xAF9 +XK_telephonerecorder: Final = 0xAFA +XK_phonographcopyright: Final = 0xAFB +XK_caret: Final = 0xAFC +XK_singlelowquotemark: Final = 0xAFD +XK_doublelowquotemark: Final = 0xAFE +XK_cursor: Final = 0xAFF diff --git a/stubs/python-xlib/Xlib/keysymdef/special.pyi b/stubs/python-xlib/Xlib/keysymdef/special.pyi new file mode 100644 index 000000000000..7a3897ce4656 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/special.pyi @@ -0,0 +1,26 @@ +from typing import Final + +XK_blank: Final = 0x9DF +XK_soliddiamond: Final = 0x9E0 +XK_checkerboard: Final = 0x9E1 +XK_ht: Final = 0x9E2 +XK_ff: Final = 0x9E3 +XK_cr: Final = 0x9E4 +XK_lf: Final = 0x9E5 +XK_nl: Final = 0x9E8 +XK_vt: Final = 0x9E9 +XK_lowrightcorner: Final = 0x9EA +XK_uprightcorner: Final = 0x9EB +XK_upleftcorner: Final = 0x9EC +XK_lowleftcorner: Final = 0x9ED +XK_crossinglines: Final = 0x9EE +XK_horizlinescan1: Final = 0x9EF +XK_horizlinescan3: Final = 0x9F0 +XK_horizlinescan5: Final = 0x9F1 +XK_horizlinescan7: Final = 0x9F2 +XK_horizlinescan9: Final = 0x9F3 +XK_leftt: Final = 0x9F4 +XK_rightt: Final = 0x9F5 +XK_bott: Final = 0x9F6 +XK_topt: Final = 0x9F7 +XK_vertbar: Final = 0x9F8 diff --git a/stubs/python-xlib/Xlib/keysymdef/technical.pyi b/stubs/python-xlib/Xlib/keysymdef/technical.pyi new file mode 100644 index 000000000000..02038da50954 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/technical.pyi @@ -0,0 +1,51 @@ +from typing import Final + +XK_leftradical: Final = 0x8A1 +XK_topleftradical: Final = 0x8A2 +XK_horizconnector: Final = 0x8A3 +XK_topintegral: Final = 0x8A4 +XK_botintegral: Final = 0x8A5 +XK_vertconnector: Final = 0x8A6 +XK_topleftsqbracket: Final = 0x8A7 +XK_botleftsqbracket: Final = 0x8A8 +XK_toprightsqbracket: Final = 0x8A9 +XK_botrightsqbracket: Final = 0x8AA +XK_topleftparens: Final = 0x8AB +XK_botleftparens: Final = 0x8AC +XK_toprightparens: Final = 0x8AD +XK_botrightparens: Final = 0x8AE +XK_leftmiddlecurlybrace: Final = 0x8AF +XK_rightmiddlecurlybrace: Final = 0x8B0 +XK_topleftsummation: Final = 0x8B1 +XK_botleftsummation: Final = 0x8B2 +XK_topvertsummationconnector: Final = 0x8B3 +XK_botvertsummationconnector: Final = 0x8B4 +XK_toprightsummation: Final = 0x8B5 +XK_botrightsummation: Final = 0x8B6 +XK_rightmiddlesummation: Final = 0x8B7 +XK_lessthanequal: Final = 0x8BC +XK_notequal: Final = 0x8BD +XK_greaterthanequal: Final = 0x8BE +XK_integral: Final = 0x8BF +XK_therefore: Final = 0x8C0 +XK_variation: Final = 0x8C1 +XK_infinity: Final = 0x8C2 +XK_nabla: Final = 0x8C5 +XK_approximate: Final = 0x8C8 +XK_similarequal: Final = 0x8C9 +XK_ifonlyif: Final = 0x8CD +XK_implies: Final = 0x8CE +XK_identical: Final = 0x8CF +XK_radical: Final = 0x8D6 +XK_includedin: Final = 0x8DA +XK_includes: Final = 0x8DB +XK_intersection: Final = 0x8DC +XK_union: Final = 0x8DD +XK_logicaland: Final = 0x8DE +XK_logicalor: Final = 0x8DF +XK_partialderivative: Final = 0x8EF +XK_function: Final = 0x8F6 +XK_leftarrow: Final = 0x8FB +XK_uparrow: Final = 0x8FC +XK_rightarrow: Final = 0x8FD +XK_downarrow: Final = 0x8FE diff --git a/stubs/python-xlib/Xlib/keysymdef/thai.pyi b/stubs/python-xlib/Xlib/keysymdef/thai.pyi new file mode 100644 index 000000000000..2d652844b333 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/thai.pyi @@ -0,0 +1,86 @@ +from typing import Final + +XK_Thai_kokai: Final = 0xDA1 +XK_Thai_khokhai: Final = 0xDA2 +XK_Thai_khokhuat: Final = 0xDA3 +XK_Thai_khokhwai: Final = 0xDA4 +XK_Thai_khokhon: Final = 0xDA5 +XK_Thai_khorakhang: Final = 0xDA6 +XK_Thai_ngongu: Final = 0xDA7 +XK_Thai_chochan: Final = 0xDA8 +XK_Thai_choching: Final = 0xDA9 +XK_Thai_chochang: Final = 0xDAA +XK_Thai_soso: Final = 0xDAB +XK_Thai_chochoe: Final = 0xDAC +XK_Thai_yoying: Final = 0xDAD +XK_Thai_dochada: Final = 0xDAE +XK_Thai_topatak: Final = 0xDAF +XK_Thai_thothan: Final = 0xDB0 +XK_Thai_thonangmontho: Final = 0xDB1 +XK_Thai_thophuthao: Final = 0xDB2 +XK_Thai_nonen: Final = 0xDB3 +XK_Thai_dodek: Final = 0xDB4 +XK_Thai_totao: Final = 0xDB5 +XK_Thai_thothung: Final = 0xDB6 +XK_Thai_thothahan: Final = 0xDB7 +XK_Thai_thothong: Final = 0xDB8 +XK_Thai_nonu: Final = 0xDB9 +XK_Thai_bobaimai: Final = 0xDBA +XK_Thai_popla: Final = 0xDBB +XK_Thai_phophung: Final = 0xDBC +XK_Thai_fofa: Final = 0xDBD +XK_Thai_phophan: Final = 0xDBE +XK_Thai_fofan: Final = 0xDBF +XK_Thai_phosamphao: Final = 0xDC0 +XK_Thai_moma: Final = 0xDC1 +XK_Thai_yoyak: Final = 0xDC2 +XK_Thai_rorua: Final = 0xDC3 +XK_Thai_ru: Final = 0xDC4 +XK_Thai_loling: Final = 0xDC5 +XK_Thai_lu: Final = 0xDC6 +XK_Thai_wowaen: Final = 0xDC7 +XK_Thai_sosala: Final = 0xDC8 +XK_Thai_sorusi: Final = 0xDC9 +XK_Thai_sosua: Final = 0xDCA +XK_Thai_hohip: Final = 0xDCB +XK_Thai_lochula: Final = 0xDCC +XK_Thai_oang: Final = 0xDCD +XK_Thai_honokhuk: Final = 0xDCE +XK_Thai_paiyannoi: Final = 0xDCF +XK_Thai_saraa: Final = 0xDD0 +XK_Thai_maihanakat: Final = 0xDD1 +XK_Thai_saraaa: Final = 0xDD2 +XK_Thai_saraam: Final = 0xDD3 +XK_Thai_sarai: Final = 0xDD4 +XK_Thai_saraii: Final = 0xDD5 +XK_Thai_saraue: Final = 0xDD6 +XK_Thai_sarauee: Final = 0xDD7 +XK_Thai_sarau: Final = 0xDD8 +XK_Thai_sarauu: Final = 0xDD9 +XK_Thai_phinthu: Final = 0xDDA +XK_Thai_maihanakat_maitho: Final = 0xDDE +XK_Thai_baht: Final = 0xDDF +XK_Thai_sarae: Final = 0xDE0 +XK_Thai_saraae: Final = 0xDE1 +XK_Thai_sarao: Final = 0xDE2 +XK_Thai_saraaimaimuan: Final = 0xDE3 +XK_Thai_saraaimaimalai: Final = 0xDE4 +XK_Thai_lakkhangyao: Final = 0xDE5 +XK_Thai_maiyamok: Final = 0xDE6 +XK_Thai_maitaikhu: Final = 0xDE7 +XK_Thai_maiek: Final = 0xDE8 +XK_Thai_maitho: Final = 0xDE9 +XK_Thai_maitri: Final = 0xDEA +XK_Thai_maichattawa: Final = 0xDEB +XK_Thai_thanthakhat: Final = 0xDEC +XK_Thai_nikhahit: Final = 0xDED +XK_Thai_leksun: Final = 0xDF0 +XK_Thai_leknung: Final = 0xDF1 +XK_Thai_leksong: Final = 0xDF2 +XK_Thai_leksam: Final = 0xDF3 +XK_Thai_leksi: Final = 0xDF4 +XK_Thai_lekha: Final = 0xDF5 +XK_Thai_lekhok: Final = 0xDF6 +XK_Thai_lekchet: Final = 0xDF7 +XK_Thai_lekpaet: Final = 0xDF8 +XK_Thai_lekkao: Final = 0xDF9 diff --git a/stubs/python-xlib/Xlib/keysymdef/xf86.pyi b/stubs/python-xlib/Xlib/keysymdef/xf86.pyi new file mode 100644 index 000000000000..7f2d9d330880 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/xf86.pyi @@ -0,0 +1,186 @@ +from typing import Final + +XK_XF86_ModeLock: Final = 0x1008FF01 +XK_XF86_MonBrightnessUp: Final = 0x1008FF02 +XK_XF86_MonBrightnessDown: Final = 0x1008FF03 +XK_XF86_KbdLightOnOff: Final = 0x1008FF04 +XK_XF86_KbdBrightnessUp: Final = 0x1008FF05 +XK_XF86_KbdBrightnessDown: Final = 0x1008FF06 +XK_XF86_MonBrightnessCycle: Final = 0x1008FF07 +XK_XF86_Standby: Final = 0x1008FF10 +XK_XF86_AudioLowerVolume: Final = 0x1008FF11 +XK_XF86_AudioMute: Final = 0x1008FF12 +XK_XF86_AudioRaiseVolume: Final = 0x1008FF13 +XK_XF86_AudioPlay: Final = 0x1008FF14 +XK_XF86_AudioStop: Final = 0x1008FF15 +XK_XF86_AudioPrev: Final = 0x1008FF16 +XK_XF86_AudioNext: Final = 0x1008FF17 +XK_XF86_HomePage: Final = 0x1008FF18 +XK_XF86_Mail: Final = 0x1008FF19 +XK_XF86_Start: Final = 0x1008FF1A +XK_XF86_Search: Final = 0x1008FF1B +XK_XF86_AudioRecord: Final = 0x1008FF1C +XK_XF86_Calculator: Final = 0x1008FF1D +XK_XF86_Memo: Final = 0x1008FF1E +XK_XF86_ToDoList: Final = 0x1008FF1F +XK_XF86_Calendar: Final = 0x1008FF20 +XK_XF86_PowerDown: Final = 0x1008FF21 +XK_XF86_ContrastAdjust: Final = 0x1008FF22 +XK_XF86_RockerUp: Final = 0x1008FF23 +XK_XF86_RockerDown: Final = 0x1008FF24 +XK_XF86_RockerEnter: Final = 0x1008FF25 +XK_XF86_Back: Final = 0x1008FF26 +XK_XF86_Forward: Final = 0x1008FF27 +XK_XF86_Stop: Final = 0x1008FF28 +XK_XF86_Refresh: Final = 0x1008FF29 +XK_XF86_PowerOff: Final = 0x1008FF2A +XK_XF86_WakeUp: Final = 0x1008FF2B +XK_XF86_Eject: Final = 0x1008FF2C +XK_XF86_ScreenSaver: Final = 0x1008FF2D +XK_XF86_WWW: Final = 0x1008FF2E +XK_XF86_Sleep: Final = 0x1008FF2F +XK_XF86_Favorites: Final = 0x1008FF30 +XK_XF86_AudioPause: Final = 0x1008FF31 +XK_XF86_AudioMedia: Final = 0x1008FF32 +XK_XF86_MyComputer: Final = 0x1008FF33 +XK_XF86_VendorHome: Final = 0x1008FF34 +XK_XF86_LightBulb: Final = 0x1008FF35 +XK_XF86_Shop: Final = 0x1008FF36 +XK_XF86_History: Final = 0x1008FF37 +XK_XF86_OpenURL: Final = 0x1008FF38 +XK_XF86_AddFavorite: Final = 0x1008FF39 +XK_XF86_HotLinks: Final = 0x1008FF3A +XK_XF86_BrightnessAdjust: Final = 0x1008FF3B +XK_XF86_Finance: Final = 0x1008FF3C +XK_XF86_Community: Final = 0x1008FF3D +XK_XF86_AudioRewind: Final = 0x1008FF3E +XK_XF86_XF86BackForward: Final = 0x1008FF3F +XK_XF86_Launch0: Final = 0x1008FF40 +XK_XF86_Launch1: Final = 0x1008FF41 +XK_XF86_Launch2: Final = 0x1008FF42 +XK_XF86_Launch3: Final = 0x1008FF43 +XK_XF86_Launch4: Final = 0x1008FF44 +XK_XF86_Launch5: Final = 0x1008FF45 +XK_XF86_Launch6: Final = 0x1008FF46 +XK_XF86_Launch7: Final = 0x1008FF47 +XK_XF86_Launch8: Final = 0x1008FF48 +XK_XF86_Launch9: Final = 0x1008FF49 +XK_XF86_LaunchA: Final = 0x1008FF4A +XK_XF86_LaunchB: Final = 0x1008FF4B +XK_XF86_LaunchC: Final = 0x1008FF4C +XK_XF86_LaunchD: Final = 0x1008FF4D +XK_XF86_LaunchE: Final = 0x1008FF4E +XK_XF86_LaunchF: Final = 0x1008FF4F +XK_XF86_ApplicationLeft: Final = 0x1008FF50 +XK_XF86_ApplicationRight: Final = 0x1008FF51 +XK_XF86_Book: Final = 0x1008FF52 +XK_XF86_CD: Final = 0x1008FF53 +XK_XF86_Calculater: Final = 0x1008FF54 +XK_XF86_Clear: Final = 0x1008FF55 +XK_XF86_Close: Final = 0x1008FF56 +XK_XF86_Copy: Final = 0x1008FF57 +XK_XF86_Cut: Final = 0x1008FF58 +XK_XF86_Display: Final = 0x1008FF59 +XK_XF86_DOS: Final = 0x1008FF5A +XK_XF86_Documents: Final = 0x1008FF5B +XK_XF86_Excel: Final = 0x1008FF5C +XK_XF86_Explorer: Final = 0x1008FF5D +XK_XF86_Game: Final = 0x1008FF5E +XK_XF86_Go: Final = 0x1008FF5F +XK_XF86_iTouch: Final = 0x1008FF60 +XK_XF86_LogOff: Final = 0x1008FF61 +XK_XF86_Market: Final = 0x1008FF62 +XK_XF86_Meeting: Final = 0x1008FF63 +XK_XF86_MenuKB: Final = 0x1008FF65 +XK_XF86_MenuPB: Final = 0x1008FF66 +XK_XF86_MySites: Final = 0x1008FF67 +XK_XF86_New: Final = 0x1008FF68 +XK_XF86_News: Final = 0x1008FF69 +XK_XF86_OfficeHome: Final = 0x1008FF6A +XK_XF86_Open: Final = 0x1008FF6B +XK_XF86_Option: Final = 0x1008FF6C +XK_XF86_Paste: Final = 0x1008FF6D +XK_XF86_Phone: Final = 0x1008FF6E +XK_XF86_Q: Final = 0x1008FF70 +XK_XF86_Reply: Final = 0x1008FF72 +XK_XF86_Reload: Final = 0x1008FF73 +XK_XF86_RotateWindows: Final = 0x1008FF74 +XK_XF86_RotationPB: Final = 0x1008FF75 +XK_XF86_RotationKB: Final = 0x1008FF76 +XK_XF86_Save: Final = 0x1008FF77 +XK_XF86_ScrollUp: Final = 0x1008FF78 +XK_XF86_ScrollDown: Final = 0x1008FF79 +XK_XF86_ScrollClick: Final = 0x1008FF7A +XK_XF86_Send: Final = 0x1008FF7B +XK_XF86_Spell: Final = 0x1008FF7C +XK_XF86_SplitScreen: Final = 0x1008FF7D +XK_XF86_Support: Final = 0x1008FF7E +XK_XF86_TaskPane: Final = 0x1008FF7F +XK_XF86_Terminal: Final = 0x1008FF80 +XK_XF86_Tools: Final = 0x1008FF81 +XK_XF86_Travel: Final = 0x1008FF82 +XK_XF86_UserPB: Final = 0x1008FF84 +XK_XF86_User1KB: Final = 0x1008FF85 +XK_XF86_User2KB: Final = 0x1008FF86 +XK_XF86_Video: Final = 0x1008FF87 +XK_XF86_WheelButton: Final = 0x1008FF88 +XK_XF86_Word: Final = 0x1008FF89 +XK_XF86_Xfer: Final = 0x1008FF8A +XK_XF86_ZoomIn: Final = 0x1008FF8B +XK_XF86_ZoomOut: Final = 0x1008FF8C +XK_XF86_Away: Final = 0x1008FF8D +XK_XF86_Messenger: Final = 0x1008FF8E +XK_XF86_WebCam: Final = 0x1008FF8F +XK_XF86_MailForward: Final = 0x1008FF90 +XK_XF86_Pictures: Final = 0x1008FF91 +XK_XF86_Music: Final = 0x1008FF92 +XK_XF86_Battery: Final = 0x1008FF93 +XK_XF86_Bluetooth: Final = 0x1008FF94 +XK_XF86_WLAN: Final = 0x1008FF95 +XK_XF86_UWB: Final = 0x1008FF96 +XK_XF86_AudioForward: Final = 0x1008FF97 +XK_XF86_AudioRepeat: Final = 0x1008FF98 +XK_XF86_AudioRandomPlay: Final = 0x1008FF99 +XK_XF86_Subtitle: Final = 0x1008FF9A +XK_XF86_AudioCycleTrack: Final = 0x1008FF9B +XK_XF86_CycleAngle: Final = 0x1008FF9C +XK_XF86_FrameBack: Final = 0x1008FF9D +XK_XF86_FrameForward: Final = 0x1008FF9E +XK_XF86_Time: Final = 0x1008FF9F +XK_XF86_Select: Final = 0x1008FFA0 +XK_XF86_View: Final = 0x1008FFA1 +XK_XF86_TopMenu: Final = 0x1008FFA2 +XK_XF86_Red: Final = 0x1008FFA3 +XK_XF86_Green: Final = 0x1008FFA4 +XK_XF86_Yellow: Final = 0x1008FFA5 +XK_XF86_Blue: Final = 0x1008FFA6 +XK_XF86_Suspend: Final = 0x1008FFA7 +XK_XF86_Hibernate: Final = 0x1008FFA8 +XK_XF86_TouchpadToggle: Final = 0x1008FFA9 +XK_XF86_TouchpadOn: Final = 0x1008FFB0 +XK_XF86_TouchpadOff: Final = 0x1008FFB1 +XK_XF86_AudioMicMute: Final = 0x1008FFB2 +XK_XF86_Keyboard: Final = 0x1008FFB3 +XK_XF86_WWAN: Final = 0x1008FFB4 +XK_XF86_RFKill: Final = 0x1008FFB5 +XK_XF86_AudioPreset: Final = 0x1008FFB6 +XK_XF86_RotationLockToggle: Final = 0x1008FFB7 +XK_XF86_FullScreen: Final = 0x1008FFB8 +XK_XF86_Switch_VT_1: Final = 0x1008FE01 +XK_XF86_Switch_VT_2: Final = 0x1008FE02 +XK_XF86_Switch_VT_3: Final = 0x1008FE03 +XK_XF86_Switch_VT_4: Final = 0x1008FE04 +XK_XF86_Switch_VT_5: Final = 0x1008FE05 +XK_XF86_Switch_VT_6: Final = 0x1008FE06 +XK_XF86_Switch_VT_7: Final = 0x1008FE07 +XK_XF86_Switch_VT_8: Final = 0x1008FE08 +XK_XF86_Switch_VT_9: Final = 0x1008FE09 +XK_XF86_Switch_VT_10: Final = 0x1008FE0A +XK_XF86_Switch_VT_11: Final = 0x1008FE0B +XK_XF86_Switch_VT_12: Final = 0x1008FE0C +XK_XF86_Ungrab: Final = 0x1008FE20 +XK_XF86_ClearGrab: Final = 0x1008FE21 +XK_XF86_Next_VMode: Final = 0x1008FE22 +XK_XF86_Prev_VMode: Final = 0x1008FE23 +XK_XF86_LogWindowTree: Final = 0x1008FE24 +XK_XF86_LogGrabInfo: Final = 0x1008FE25 diff --git a/stubs/python-xlib/Xlib/keysymdef/xk3270.pyi b/stubs/python-xlib/Xlib/keysymdef/xk3270.pyi new file mode 100644 index 000000000000..92741d4b0563 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/xk3270.pyi @@ -0,0 +1,32 @@ +from typing import Final + +XK_3270_Duplicate: Final = 0xFD01 +XK_3270_FieldMark: Final = 0xFD02 +XK_3270_Right2: Final = 0xFD03 +XK_3270_Left2: Final = 0xFD04 +XK_3270_BackTab: Final = 0xFD05 +XK_3270_EraseEOF: Final = 0xFD06 +XK_3270_EraseInput: Final = 0xFD07 +XK_3270_Reset: Final = 0xFD08 +XK_3270_Quit: Final = 0xFD09 +XK_3270_PA1: Final = 0xFD0A +XK_3270_PA2: Final = 0xFD0B +XK_3270_PA3: Final = 0xFD0C +XK_3270_Test: Final = 0xFD0D +XK_3270_Attn: Final = 0xFD0E +XK_3270_CursorBlink: Final = 0xFD0F +XK_3270_AltCursor: Final = 0xFD10 +XK_3270_KeyClick: Final = 0xFD11 +XK_3270_Jump: Final = 0xFD12 +XK_3270_Ident: Final = 0xFD13 +XK_3270_Rule: Final = 0xFD14 +XK_3270_Copy: Final = 0xFD15 +XK_3270_Play: Final = 0xFD16 +XK_3270_Setup: Final = 0xFD17 +XK_3270_Record: Final = 0xFD18 +XK_3270_ChangeScreen: Final = 0xFD19 +XK_3270_DeleteWord: Final = 0xFD1A +XK_3270_ExSelect: Final = 0xFD1B +XK_3270_CursorSelect: Final = 0xFD1C +XK_3270_PrintScreen: Final = 0xFD1D +XK_3270_Enter: Final = 0xFD1E diff --git a/stubs/python-xlib/Xlib/keysymdef/xkb.pyi b/stubs/python-xlib/Xlib/keysymdef/xkb.pyi new file mode 100644 index 000000000000..f72fa6704cd7 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/xkb.pyi @@ -0,0 +1,102 @@ +from typing import Final + +XK_ISO_Lock: Final = 0xFE01 +XK_ISO_Level2_Latch: Final = 0xFE02 +XK_ISO_Level3_Shift: Final = 0xFE03 +XK_ISO_Level3_Latch: Final = 0xFE04 +XK_ISO_Level3_Lock: Final = 0xFE05 +XK_ISO_Group_Shift: Final = 0xFF7E +XK_ISO_Group_Latch: Final = 0xFE06 +XK_ISO_Group_Lock: Final = 0xFE07 +XK_ISO_Next_Group: Final = 0xFE08 +XK_ISO_Next_Group_Lock: Final = 0xFE09 +XK_ISO_Prev_Group: Final = 0xFE0A +XK_ISO_Prev_Group_Lock: Final = 0xFE0B +XK_ISO_First_Group: Final = 0xFE0C +XK_ISO_First_Group_Lock: Final = 0xFE0D +XK_ISO_Last_Group: Final = 0xFE0E +XK_ISO_Last_Group_Lock: Final = 0xFE0F +XK_ISO_Left_Tab: Final = 0xFE20 +XK_ISO_Move_Line_Up: Final = 0xFE21 +XK_ISO_Move_Line_Down: Final = 0xFE22 +XK_ISO_Partial_Line_Up: Final = 0xFE23 +XK_ISO_Partial_Line_Down: Final = 0xFE24 +XK_ISO_Partial_Space_Left: Final = 0xFE25 +XK_ISO_Partial_Space_Right: Final = 0xFE26 +XK_ISO_Set_Margin_Left: Final = 0xFE27 +XK_ISO_Set_Margin_Right: Final = 0xFE28 +XK_ISO_Release_Margin_Left: Final = 0xFE29 +XK_ISO_Release_Margin_Right: Final = 0xFE2A +XK_ISO_Release_Both_Margins: Final = 0xFE2B +XK_ISO_Fast_Cursor_Left: Final = 0xFE2C +XK_ISO_Fast_Cursor_Right: Final = 0xFE2D +XK_ISO_Fast_Cursor_Up: Final = 0xFE2E +XK_ISO_Fast_Cursor_Down: Final = 0xFE2F +XK_ISO_Continuous_Underline: Final = 0xFE30 +XK_ISO_Discontinuous_Underline: Final = 0xFE31 +XK_ISO_Emphasize: Final = 0xFE32 +XK_ISO_Center_Object: Final = 0xFE33 +XK_ISO_Enter: Final = 0xFE34 +XK_dead_grave: Final = 0xFE50 +XK_dead_acute: Final = 0xFE51 +XK_dead_circumflex: Final = 0xFE52 +XK_dead_tilde: Final = 0xFE53 +XK_dead_macron: Final = 0xFE54 +XK_dead_breve: Final = 0xFE55 +XK_dead_abovedot: Final = 0xFE56 +XK_dead_diaeresis: Final = 0xFE57 +XK_dead_abovering: Final = 0xFE58 +XK_dead_doubleacute: Final = 0xFE59 +XK_dead_caron: Final = 0xFE5A +XK_dead_cedilla: Final = 0xFE5B +XK_dead_ogonek: Final = 0xFE5C +XK_dead_iota: Final = 0xFE5D +XK_dead_voiced_sound: Final = 0xFE5E +XK_dead_semivoiced_sound: Final = 0xFE5F +XK_dead_belowdot: Final = 0xFE60 +XK_First_Virtual_Screen: Final = 0xFED0 +XK_Prev_Virtual_Screen: Final = 0xFED1 +XK_Next_Virtual_Screen: Final = 0xFED2 +XK_Last_Virtual_Screen: Final = 0xFED4 +XK_Terminate_Server: Final = 0xFED5 +XK_AccessX_Enable: Final = 0xFE70 +XK_AccessX_Feedback_Enable: Final = 0xFE71 +XK_RepeatKeys_Enable: Final = 0xFE72 +XK_SlowKeys_Enable: Final = 0xFE73 +XK_BounceKeys_Enable: Final = 0xFE74 +XK_StickyKeys_Enable: Final = 0xFE75 +XK_MouseKeys_Enable: Final = 0xFE76 +XK_MouseKeys_Accel_Enable: Final = 0xFE77 +XK_Overlay1_Enable: Final = 0xFE78 +XK_Overlay2_Enable: Final = 0xFE79 +XK_AudibleBell_Enable: Final = 0xFE7A +XK_Pointer_Left: Final = 0xFEE0 +XK_Pointer_Right: Final = 0xFEE1 +XK_Pointer_Up: Final = 0xFEE2 +XK_Pointer_Down: Final = 0xFEE3 +XK_Pointer_UpLeft: Final = 0xFEE4 +XK_Pointer_UpRight: Final = 0xFEE5 +XK_Pointer_DownLeft: Final = 0xFEE6 +XK_Pointer_DownRight: Final = 0xFEE7 +XK_Pointer_Button_Dflt: Final = 0xFEE8 +XK_Pointer_Button1: Final = 0xFEE9 +XK_Pointer_Button2: Final = 0xFEEA +XK_Pointer_Button3: Final = 0xFEEB +XK_Pointer_Button4: Final = 0xFEEC +XK_Pointer_Button5: Final = 0xFEED +XK_Pointer_DblClick_Dflt: Final = 0xFEEE +XK_Pointer_DblClick1: Final = 0xFEEF +XK_Pointer_DblClick2: Final = 0xFEF0 +XK_Pointer_DblClick3: Final = 0xFEF1 +XK_Pointer_DblClick4: Final = 0xFEF2 +XK_Pointer_DblClick5: Final = 0xFEF3 +XK_Pointer_Drag_Dflt: Final = 0xFEF4 +XK_Pointer_Drag1: Final = 0xFEF5 +XK_Pointer_Drag2: Final = 0xFEF6 +XK_Pointer_Drag3: Final = 0xFEF7 +XK_Pointer_Drag4: Final = 0xFEF8 +XK_Pointer_Drag5: Final = 0xFEFD +XK_Pointer_EnableKeys: Final = 0xFEF9 +XK_Pointer_Accelerate: Final = 0xFEFA +XK_Pointer_DfltBtnNext: Final = 0xFEFB +XK_Pointer_DfltBtnPrev: Final = 0xFEFC diff --git a/stubs/python-xlib/Xlib/protocol/__init__.pyi b/stubs/python-xlib/Xlib/protocol/__init__.pyi new file mode 100644 index 000000000000..1252a6dc5030 --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/__init__.pyi @@ -0,0 +1,3 @@ +from Xlib.protocol import display as display, event as event, request as request, rq as rq, structs as structs + +__all__ = ["display", "event", "request", "rq", "structs"] diff --git a/stubs/python-xlib/Xlib/protocol/display.pyi b/stubs/python-xlib/Xlib/protocol/display.pyi new file mode 100644 index 000000000000..b099d6463f0a --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/display.pyi @@ -0,0 +1,122 @@ +from _typeshed import SizedBuffer +from socket import socket +from typing import Literal, TypeVar, overload + +from Xlib import error +from Xlib._typing import ErrorHandler +from Xlib.display import _ResourceBaseClass, _ResourceBaseClassesType +from Xlib.protocol import rq +from Xlib.support import lock +from Xlib.xobject import colormap, cursor, drawable, fontable, resource + +_T = TypeVar("_T") + +class bytesview: + view: memoryview + + @overload + def __init__(self, data: bytes | bytesview, offset: int, size: int) -> None: ... + @overload + def __init__(self, data: SizedBuffer, offset: int = 0, size: int | None = None) -> None: ... + + @overload + def __getitem__(self, key: slice) -> bytes: ... + @overload + def __getitem__(self, key: int) -> int: ... + + def __len__(self) -> int: ... + +class Display: + extension_major_opcodes: dict[str, int] + error_classes: dict[int, type[error.XError]] + event_classes: dict[int, type[rq.Event] | dict[int, type[rq.Event]]] + resource_classes: _ResourceBaseClassesType | None + display_name: str + default_screen: int + socket: socket + socket_error_lock: lock._DummyLock + socket_error: Exception | None + event_queue_read_lock: lock._DummyLock + event_queue_write_lock: lock._DummyLock + event_queue: list[rq.Event] + request_queue_lock: lock._DummyLock + request_serial: int + request_queue: list[tuple[rq.Request | rq.ReplyRequest | ConnectionSetupRequest, int]] + send_recv_lock: lock._DummyLock + send_active: int + recv_active: int + event_waiting: int + event_wait_lock: lock._DummyLock + request_waiting: int + request_wait_lock: lock._DummyLock + recv_buffer_size: int + sent_requests: list[rq.Request | rq.ReplyRequest | ConnectionSetupRequest] + recv_packet_len: int + data_send: bytes + data_recv: bytes + data_sent_bytes: int + resource_id_lock: lock._DummyLock + resource_ids: dict[int, None] + last_resource_id: int + error_handler: ErrorHandler[object] | None + big_endian: bool + info: ConnectionSetupRequest + def __init__(self, display: str | None = None) -> None: ... + def get_display_name(self) -> str: ... + def get_default_screen(self) -> int: ... + def fileno(self) -> int: ... + def next_event(self) -> rq.Event: ... + def pending_events(self) -> int: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def set_error_handler(self, handler: ErrorHandler[object] | None) -> None: ... + def allocate_resource_id(self) -> int: ... + def free_resource_id(self, rid: int) -> None: ... + + @overload + def get_resource_class(self, class_name: Literal["resource"], default: object = None) -> type[resource.Resource]: ... + @overload + def get_resource_class(self, class_name: Literal["drawable"], default: object = None) -> type[drawable.Drawable]: ... + @overload + def get_resource_class(self, class_name: Literal["window"], default: object = None) -> type[drawable.Window]: ... + @overload + def get_resource_class(self, class_name: Literal["pixmap"], default: object = None) -> type[drawable.Pixmap]: ... + @overload + def get_resource_class(self, class_name: Literal["fontable"], default: object = None) -> type[fontable.Fontable]: ... + @overload + def get_resource_class(self, class_name: Literal["font"], default: object = None) -> type[fontable.Font]: ... + @overload + def get_resource_class(self, class_name: Literal["gc"], default: object = None) -> type[fontable.GC]: ... + @overload + def get_resource_class(self, class_name: Literal["colormap"], default: object = None) -> type[colormap.Colormap]: ... + @overload + def get_resource_class(self, class_name: Literal["cursor"], default: object) -> type[cursor.Cursor]: ... + @overload + def get_resource_class(self, class_name: str, default: _T) -> type[_ResourceBaseClass] | _T: ... + @overload + def get_resource_class(self, class_name: str, default: None = None) -> type[_ResourceBaseClass] | None: ... + + def set_extension_major(self, extname: str, major: int) -> None: ... + def get_extension_major(self, extname: str) -> int: ... + def add_extension_event(self, code: int, evt: type[rq.Event], subcode: int | None = None) -> None: ... + def add_extension_error(self, code: int, err: type[error.XError]) -> None: ... + def check_for_error(self) -> None: ... + def send_request(self, request: rq.Request | rq.ReplyRequest | ConnectionSetupRequest, wait_for_response: bool) -> None: ... + def close_internal(self, whom: object) -> None: ... + def send_and_recv(self, flush: bool = False, event: bool = False, request: int | None = None, recv: bool = False) -> None: ... + def parse_response(self, request: int) -> bool: ... + def parse_error_response(self, request: int) -> bool: ... + def default_error_handler(self, err: object) -> None: ... + def parse_request_response(self, request: int) -> bool: ... + def parse_event_response(self, etype: int) -> None: ... + def get_waiting_request(self, sno: int) -> rq.ReplyRequest | ConnectionSetupRequest | None: ... + def get_waiting_replyrequest(self) -> rq.ReplyRequest | ConnectionSetupRequest: ... + def parse_connection_setup(self) -> bool: ... + +PixmapFormat: rq.Struct +VisualType: rq.Struct +Depth: rq.Struct +Screen: rq.Struct + +class ConnectionSetupRequest(rq.GetAttrData): + def __init__(self, display: Display, *args: object, **keys: object) -> None: ... diff --git a/stubs/python-xlib/Xlib/protocol/event.pyi b/stubs/python-xlib/Xlib/protocol/event.pyi new file mode 100644 index 000000000000..f033a985b030 --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/event.pyi @@ -0,0 +1,82 @@ +from typing import Final, TypeAlias + +from Xlib.protocol import rq + +class AnyEvent(rq.Event): ... +class KeyButtonPointer(rq.Event): ... +class KeyPress(KeyButtonPointer): ... +class KeyRelease(KeyButtonPointer): ... +class ButtonPress(KeyButtonPointer): ... +class ButtonRelease(KeyButtonPointer): ... +class MotionNotify(KeyButtonPointer): ... +class EnterLeave(rq.Event): ... +class EnterNotify(EnterLeave): ... +class LeaveNotify(EnterLeave): ... +class Focus(rq.Event): ... +class FocusIn(Focus): ... +class FocusOut(Focus): ... +class Expose(rq.Event): ... +class GraphicsExpose(rq.Event): ... +class NoExpose(rq.Event): ... +class VisibilityNotify(rq.Event): ... +class CreateNotify(rq.Event): ... +class DestroyNotify(rq.Event): ... +class UnmapNotify(rq.Event): ... +class MapNotify(rq.Event): ... +class MapRequest(rq.Event): ... +class ReparentNotify(rq.Event): ... +class ConfigureNotify(rq.Event): ... +class ConfigureRequest(rq.Event): ... +class GravityNotify(rq.Event): ... +class ResizeRequest(rq.Event): ... +class Circulate(rq.Event): ... +class CirculateNotify(Circulate): ... +class CirculateRequest(Circulate): ... +class PropertyNotify(rq.Event): ... +class SelectionClear(rq.Event): ... +class SelectionRequest(rq.Event): ... +class SelectionNotify(rq.Event): ... +class ColormapNotify(rq.Event): ... +class MappingNotify(rq.Event): ... +class ClientMessage(rq.Event): ... +class KeymapNotify(rq.Event): ... + +_EventClass: TypeAlias = dict[ + int, + type[ + KeyPress + | KeyRelease + | ButtonPress + | ButtonRelease + | MotionNotify + | EnterNotify + | LeaveNotify + | FocusIn + | FocusOut + | KeymapNotify + | Expose + | GraphicsExpose + | NoExpose + | VisibilityNotify + | CreateNotify + | DestroyNotify + | UnmapNotify + | MapNotify + | MapRequest + | ReparentNotify + | ConfigureNotify + | ConfigureRequest + | GravityNotify + | ResizeRequest + | CirculateNotify + | CirculateRequest + | PropertyNotify + | SelectionClear + | SelectionRequest + | SelectionNotify + | ColormapNotify + | ClientMessage + | MappingNotify + ], +] +event_class: Final[_EventClass] diff --git a/stubs/python-xlib/Xlib/protocol/request.pyi b/stubs/python-xlib/Xlib/protocol/request.pyi new file mode 100644 index 000000000000..1095bbad5cff --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/request.pyi @@ -0,0 +1,134 @@ +from typing import Final +from typing_extensions import Never + +from Xlib import display +from Xlib.protocol import rq + +class CreateWindow(rq.Request): ... +class ChangeWindowAttributes(rq.Request): ... +class GetWindowAttributes(rq.ReplyRequest): ... +class DestroyWindow(rq.Request): ... +class DestroySubWindows(rq.Request): ... +class ChangeSaveSet(rq.Request): ... +class ReparentWindow(rq.Request): ... +class MapWindow(rq.Request): ... +class MapSubwindows(rq.Request): ... +class UnmapWindow(rq.Request): ... +class UnmapSubwindows(rq.Request): ... +class ConfigureWindow(rq.Request): ... +class CirculateWindow(rq.Request): ... +class GetGeometry(rq.ReplyRequest): ... +class QueryTree(rq.ReplyRequest): ... +class InternAtom(rq.ReplyRequest): ... +class GetAtomName(rq.ReplyRequest): ... +class ChangeProperty(rq.Request): ... +class DeleteProperty(rq.Request): ... +class GetProperty(rq.ReplyRequest): ... +class ListProperties(rq.ReplyRequest): ... +class SetSelectionOwner(rq.Request): ... +class GetSelectionOwner(rq.ReplyRequest): ... +class ConvertSelection(rq.Request): ... +class SendEvent(rq.Request): ... +class GrabPointer(rq.ReplyRequest): ... +class UngrabPointer(rq.Request): ... +class GrabButton(rq.Request): ... +class UngrabButton(rq.Request): ... +class ChangeActivePointerGrab(rq.Request): ... +class GrabKeyboard(rq.ReplyRequest): ... +class UngrabKeyboard(rq.Request): ... +class GrabKey(rq.Request): ... +class UngrabKey(rq.Request): ... +class AllowEvents(rq.Request): ... +class GrabServer(rq.Request): ... +class UngrabServer(rq.Request): ... +class QueryPointer(rq.ReplyRequest): ... +class GetMotionEvents(rq.ReplyRequest): ... +class TranslateCoords(rq.ReplyRequest): ... +class WarpPointer(rq.Request): ... +class SetInputFocus(rq.Request): ... +class GetInputFocus(rq.ReplyRequest): ... +class QueryKeymap(rq.ReplyRequest): ... +class OpenFont(rq.Request): ... +class CloseFont(rq.Request): ... +class QueryFont(rq.ReplyRequest): ... +class QueryTextExtents(rq.ReplyRequest): ... +class ListFonts(rq.ReplyRequest): ... + +class ListFontsWithInfo(rq.ReplyRequest): + def __init__(self, display: display.Display, defer: bool = False, *args: object, **keys: object) -> None: ... + def __getattr__(self, attr: object) -> Never: ... + def __getitem__(self, item: str) -> object: ... + def __len__(self) -> int: ... + +class SetFontPath(rq.Request): ... +class GetFontPath(rq.ReplyRequest): ... +class CreatePixmap(rq.Request): ... +class FreePixmap(rq.Request): ... +class CreateGC(rq.Request): ... +class ChangeGC(rq.Request): ... +class CopyGC(rq.Request): ... +class SetDashes(rq.Request): ... +class SetClipRectangles(rq.Request): ... +class FreeGC(rq.Request): ... +class ClearArea(rq.Request): ... +class CopyArea(rq.Request): ... +class CopyPlane(rq.Request): ... +class PolyPoint(rq.Request): ... +class PolyLine(rq.Request): ... +class PolySegment(rq.Request): ... +class PolyRectangle(rq.Request): ... +class PolyArc(rq.Request): ... +class FillPoly(rq.Request): ... +class PolyFillRectangle(rq.Request): ... +class PolyFillArc(rq.Request): ... +class PutImage(rq.Request): ... +class GetImage(rq.ReplyRequest): ... +class PolyText8(rq.Request): ... +class PolyText16(rq.Request): ... +class ImageText8(rq.Request): ... +class ImageText16(rq.Request): ... +class CreateColormap(rq.Request): ... +class FreeColormap(rq.Request): ... +class CopyColormapAndFree(rq.Request): ... +class InstallColormap(rq.Request): ... +class UninstallColormap(rq.Request): ... +class ListInstalledColormaps(rq.ReplyRequest): ... +class AllocColor(rq.ReplyRequest): ... +class AllocNamedColor(rq.ReplyRequest): ... +class AllocColorCells(rq.ReplyRequest): ... +class AllocColorPlanes(rq.ReplyRequest): ... +class FreeColors(rq.Request): ... +class StoreColors(rq.Request): ... +class StoreNamedColor(rq.Request): ... +class QueryColors(rq.ReplyRequest): ... +class LookupColor(rq.ReplyRequest): ... +class CreateCursor(rq.Request): ... +class CreateGlyphCursor(rq.Request): ... +class FreeCursor(rq.Request): ... +class RecolorCursor(rq.Request): ... +class QueryBestSize(rq.ReplyRequest): ... +class QueryExtension(rq.ReplyRequest): ... +class ListExtensions(rq.ReplyRequest): ... +class ChangeKeyboardMapping(rq.Request): ... +class GetKeyboardMapping(rq.ReplyRequest): ... +class ChangeKeyboardControl(rq.Request): ... +class GetKeyboardControl(rq.ReplyRequest): ... +class Bell(rq.Request): ... +class ChangePointerControl(rq.Request): ... +class GetPointerControl(rq.ReplyRequest): ... +class SetScreenSaver(rq.Request): ... +class GetScreenSaver(rq.ReplyRequest): ... +class ChangeHosts(rq.Request): ... +class ListHosts(rq.ReplyRequest): ... +class SetAccessControl(rq.Request): ... +class SetCloseDownMode(rq.Request): ... +class KillClient(rq.Request): ... +class RotateProperties(rq.Request): ... +class ForceScreenSaver(rq.Request): ... +class SetPointerMapping(rq.ReplyRequest): ... +class GetPointerMapping(rq.ReplyRequest): ... +class SetModifierMapping(rq.ReplyRequest): ... +class GetModifierMapping(rq.ReplyRequest): ... +class NoOperation(rq.Request): ... + +major_codes: Final[dict[int, type[rq.Request]]] diff --git a/stubs/python-xlib/Xlib/protocol/rq.pyi b/stubs/python-xlib/Xlib/protocol/rq.pyi new file mode 100644 index 000000000000..1c89b6964ed0 --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/rq.pyi @@ -0,0 +1,400 @@ +from _typeshed import ConvertibleToInt, SliceableBuffer, Unused +from array import array + +# Avoid name collision with List.type +from builtins import type as Type +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import LiteralString + +from Xlib._typing import ErrorHandler +from Xlib.display import _BaseDisplay, _ResourceBaseClass +from Xlib.error import XError +from Xlib.ext.xinput import ClassInfoClass +from Xlib.protocol import display + +_T = TypeVar("_T") +_ModifierMappingList8Elements: TypeAlias = Sequence[Sequence[int]] + +def decode_string(bs: bytes | bytearray) -> str: ... +def encode_array(a: array[Any] | memoryview) -> str: ... + +class BadDataError(Exception): ... + +signed_codes: Final[dict[int, str]] +unsigned_codes: Final[dict[int, str]] +array_unsigned_codes: Final[dict[int, LiteralString]] +struct_to_array_codes: Final[dict[str, LiteralString]] + +class Field: + name: str + default: int | None + pack_value: Callable[[Any], tuple[Any, int | None, int | None]] | None + structcode: str | None + structvalues: int + check_value: Callable[[Any], Any] | None + parse_value: Callable[[Any, Any], Any] | None + keyword_args: int + + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: int | None, format: int + ) -> tuple[Any, SliceableBuffer]: ... + +class Pad(Field): + size: int + value: bytes + structcode: str + def __init__(self, size: int) -> None: ... + +class ConstantField(Field): + value: int + def __init__(self, value: int) -> None: ... + +class Opcode(ConstantField): + structcode: str + +class ReplyCode(ConstantField): + structcode: str + value: int + def __init__(self) -> None: ... + +class LengthField(Field): + structcode: str + other_fields: list[str] | tuple[str, ...] | None + def calc_length(self, length: int) -> int: ... + +class TotalLengthField(LengthField): ... +class RequestLength(TotalLengthField): ... +class ReplyLength(TotalLengthField): ... + +class LengthOf(LengthField): + other_fields: list[str] | tuple[str, ...] | None + def __init__(self, name: str | list[str] | tuple[str, ...], size: int) -> None: ... + +class OddLength(LengthField): + def __init__(self, name: str) -> None: ... + def parse_value(self, value: int, display: Unused) -> Literal["even", "odd"]: ... # type: ignore[override] + +class FormatField(Field): + structcode: str + def __init__(self, name: str, size: int) -> None: ... + +Format = FormatField + +class ValueField(Field): + def __init__(self, name: str, default: int | None = None) -> None: ... + +class Int8(ValueField): + structcode: str + +class Int16(ValueField): + structcode: str + +class Int32(ValueField): + structcode: str + +class Card8(ValueField): + structcode: str + +class Card16(ValueField): + structcode: str + +class Card32(ValueField): + structcode: str + +class Resource(Card32): + cast_function: str + class_name: str + codes: tuple[int, ...] + def __init__(self, name: str, codes: tuple[int, ...] = (), default: int | None = None) -> None: ... + + @overload # type: ignore[override] + def check_value(self, value: Callable[[], _T]) -> _T: ... + @overload + def check_value(self, value: _T) -> _T: ... + + def parse_value(self, value: int, display: _BaseDisplay) -> int: ... # type: ignore[override] # display: None will error. See: https://github.com/python-xlib/python-xlib/pull/248 + +class Window(Resource): + cast_function: str + class_name: str + +class Pixmap(Resource): + cast_function: str + class_name: str + +class Drawable(Resource): + cast_function: str + class_name: str + +class Fontable(Resource): + cast_function: str + class_name: str + +class Font(Resource): + cast_function: str + class_name: str + +class GC(Resource): + cast_function: str + class_name: str + +class Colormap(Resource): + cast_function: str + class_name: str + +class Cursor(Resource): + cast_function: str + class_name: str + +class Bool(ValueField): + structcode: str + def check_value(self, value: object) -> bool: ... # type: ignore[override] + +class Set(ValueField): + structcode: str + values: Sequence[object] + def __init__(self, name: str, size: int, values: Sequence[object], default: int | None = None) -> None: ... + def check_value(self, val: _T) -> _T: ... # type: ignore[override] + +class Gravity(Set): + def __init__(self, name: str) -> None: ... + +class FixedBinary(ValueField): + structcode: str + def __init__(self, name: str, size: int) -> None: ... + +class Binary(ValueField): + structcode: None + pad: int + def __init__(self, name: str, pad: int = 1) -> None: ... + def pack_value( # type: ignore[override] # Override Callable + self, val: bytes | bytearray + ) -> tuple[bytes | bytearray, int, None]: ... + + @overload # type: ignore[override] # Overload for specific values + def parse_binary_value(self, data: _T, display: Unused, length: None, format: Unused) -> tuple[_T, Literal[b""]]: ... + @overload + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: int, format: Unused + ) -> tuple[SliceableBuffer, SliceableBuffer]: ... + +class String8(ValueField): + structcode: None + pad: int + def __init__(self, name: str, pad: int = 1) -> None: ... + def pack_value(self, val: bytes | str) -> tuple[bytes, int, None]: ... # type: ignore[override] # Override Callable + + @overload # type: ignore[override] # Overload for specific values + def parse_binary_value( + self, data: bytes | bytearray, display: Unused, length: None, format: Unused + ) -> tuple[str, Literal[b""]]: ... + @overload + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: int, format: Unused + ) -> tuple[str, SliceableBuffer]: ... + +class String16(ValueField): + structcode: None + pad: int + def __init__(self, name: str, pad: int = 1) -> None: ... + def pack_value(self, val: Sequence[object]) -> tuple[bytes, int, None]: ... # type: ignore[override] # Override Callable + def parse_binary_value( # type: ignore[override] # length: None will error. See: https://github.com/python-xlib/python-xlib/pull/248 + self, data: SliceableBuffer, display: Unused, length: int | Literal["odd", "even"], format: Unused + ) -> tuple[tuple[Any, ...], SliceableBuffer]: ... + +class List(ValueField): + structcode: None + type: Struct | ScalarObj | ResourceObj | ClassInfoClass | Type[ValueField] + pad: int + def __init__( + self, name: str, type: Struct | ScalarObj | ResourceObj | ClassInfoClass | Type[ValueField], pad: int = 1 + ) -> None: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: SupportsIndex | None, format: Unused + ) -> tuple[list[DictWrapper | None], SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, val: Sequence[object] | dict[str, Any] + ) -> tuple[bytes, int, None]: ... + +class FixedList(List): + size: int + def __init__(self, name: str, size: int, type: Struct | ScalarObj, pad: int = 1) -> None: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[list[DictWrapper | None], SliceableBuffer]: ... + +class Object(ValueField): + type: Struct + structcode: str | None + def __init__(self, name: str, type: Struct, default: int | None = None) -> None: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[DictWrapper, SliceableBuffer]: ... + def parse_value(self, val: SliceableBuffer, display: display.Display | None) -> DictWrapper: ... # type: ignore[override] + def pack_value( # type: ignore[override] # Override Callable + self, val: tuple[object, ...] | dict[str, Any] | DictWrapper + ) -> bytes: ... + def check_value(self, val: tuple[_T, ...] | dict[str, _T] | DictWrapper) -> list[_T]: ... # type: ignore[override] + +class PropertyData(ValueField): + structcode: None + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: ConvertibleToInt | None, format: int + ) -> tuple[tuple[int, SliceableBuffer] | None, SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, value: tuple[int, Sequence[float] | Sequence[str]] + ) -> tuple[bytes, int, Literal[8, 16, 32]]: ... + +class FixedPropertyData(PropertyData): + size: int + def __init__(self, name: str, size: int) -> None: ... + +class ValueList(Field): + structcode: None + keyword_args: int + default: str # type: ignore[assignment] # Actually different from base class + maskcode: bytes + maskcodelen: int + fields: list[tuple[Field, int]] + def __init__(self, name: str, mask: int, pad: int, *fields: Field) -> None: ... + def pack_value( # type: ignore[override] # Override Callable + self, arg: str | dict[str, Any], keys: dict[str, Any] + ) -> tuple[bytes, None, None]: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[DictWrapper, SliceableBuffer]: ... + +class KeyboardMapping(ValueField): + structcode: None + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: int | None, format: int + ) -> tuple[list[int], SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, value: Sequence[Sequence[object]] + ) -> tuple[bytes, int, int]: ... + +class ModifierMapping(ValueField): + structcode: None + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: Unused, format: int + ) -> tuple[list[array[int]], SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, value: _ModifierMappingList8Elements + ) -> tuple[bytes, int, int]: ... + +class EventField(ValueField): + structcode: None + def pack_value(self, value: Event) -> tuple[SliceableBuffer, None, None]: ... # type: ignore[override] # Override Callable + def parse_binary_value( # type: ignore[override] + self, data: SliceableBuffer, display: display.Display, length: Unused, format: Unused + ) -> tuple[Event, SliceableBuffer]: ... + +class ScalarObj: + structcode: str + structvalues: int + parse_value: None + check_value: None + def __init__(self, code: str) -> None: ... + +Card8Obj: ScalarObj +Card16Obj: ScalarObj +Card32Obj: ScalarObj + +class ResourceObj: + structcode: str + structvalues: int + class_name: str + check_value: None + def __init__(self, class_name: str) -> None: ... + def parse_value(self, value: int, display: _BaseDisplay) -> int | _ResourceBaseClass: ... + +WindowObj: ResourceObj +ColormapObj: ResourceObj + +class StrClass: + structcode: None + def pack_value(self, val: str) -> bytes: ... + def parse_binary(self, data: bytes | bytearray, display: Unused) -> tuple[str, bytes | bytearray]: ... + +Str: StrClass + +class Struct: + name: str + check_value: Callable[[Any], Any] | None + keyword_args: bool + fields: tuple[Field] + static_codes: str + static_values: int + static_fields: list[Field] + static_size: int + var_fields: list[Field] + structcode: str | None + structvalues: int + def __init__(self, *fields: Field) -> None: ... + def to_binary(self, *varargs: object, **keys: object) -> bytes: ... + def pack_value(self, value: tuple[object, ...] | dict[str, Any] | DictWrapper) -> bytes: ... + + @overload + def parse_value(self, val: SliceableBuffer, display: display.Display | None, rawdict: Literal[True]) -> dict[str, Any]: ... + @overload + def parse_value( + self, val: SliceableBuffer, display: display.Display | None, rawdict: Literal[False] = False + ) -> DictWrapper: ... + + @overload + def parse_binary( + self, data: SliceableBuffer, display: display.Display | None, rawdict: Literal[True] + ) -> tuple[dict[str, Any], SliceableBuffer]: ... + @overload + def parse_binary( + self, data: SliceableBuffer, display: display.Display | None, rawdict: Literal[False] = False + ) -> tuple[DictWrapper, SliceableBuffer]: ... + + # Structs generate their attributes + # TODO: Create a specific type-only class for all instances of `Struct` + @type_check_only + def __getattr__(self, name: str, /) -> Any: ... + +class TextElements8(ValueField): + string_textitem: Struct + def pack_value( # type: ignore[override] # Override Callable + self, value: Iterable[Field | str | bytes | tuple[Sequence[object], ...] | dict[str, Sequence[object]] | DictWrapper] + ) -> tuple[bytes, None, None]: ... + def parse_binary_value( # type: ignore[override] # See: https://github.com/python-xlib/python-xlib/pull/249 + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[list[DictWrapper], Literal[""]]: ... + +class TextElements16(TextElements8): + string_textitem: Struct + +class GetAttrData: + # GetAttrData classes get their attributes dynamically + # TODO: Complete all classes inheriting from GetAttrData + def __getattr__(self, attr: str) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +class DictWrapper(GetAttrData): + def __init__(self, dict: dict[str, Any]) -> None: ... + def __getitem__(self, key: str) -> object: ... + def __setitem__(self, key: str, value: object) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __setattr__(self, key: str, value: object) -> None: ... + +class Request: + def __init__( + self, display: _BaseDisplay, onerror: ErrorHandler[object] | None = None, *args: object, **keys: object + ) -> None: ... + +class ReplyRequest(GetAttrData): + def __init__(self, display: display.Display, defer: bool = False, *args: object, **keys: object) -> None: ... + def reply(self) -> None: ... + +class Event(GetAttrData): + def __init__( + self, binarydata: SliceableBuffer | None = None, display: display.Display | None = None, **keys: object + ) -> None: ... + +def call_error_handler( + handler: Callable[[XError, Request | None], _T], error: XError, request: Request | None +) -> _T | Literal[0]: ... diff --git a/stubs/python-xlib/Xlib/protocol/structs.pyi b/stubs/python-xlib/Xlib/protocol/structs.pyi new file mode 100644 index 000000000000..47508e6a636c --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/structs.pyi @@ -0,0 +1,26 @@ +from collections.abc import Iterable, Sequence +from typing import TypeAlias + +from Xlib.protocol import rq + +# Aliases used in other modules +_RGB3IntIterable: TypeAlias = Iterable[int] # noqa: Y047 +_Rectangle4IntSequence: TypeAlias = Sequence[int] # noqa: Y047 +_Segment4IntSequence: TypeAlias = Sequence[int] # noqa: Y047 +_Arc6IntSequence: TypeAlias = Sequence[int] # noqa: Y047 + +# TODO: Complete all classes using WindowValues and GCValues +# Currently *object is used to represent the ValueList instead of the possible attribute types +def WindowValues(arg: str) -> rq.ValueList: ... +def GCValues(arg: str) -> rq.ValueList: ... + +TimeCoord: rq.Struct +Host: rq.Struct +CharInfo: rq.Struct +FontProp: rq.Struct +ColorItem: rq.Struct +RGB: rq.Struct +Point: rq.Struct +Segment: rq.Struct +Rectangle: rq.Struct +Arc: rq.Struct diff --git a/stubs/python-xlib/Xlib/rdb.pyi b/stubs/python-xlib/Xlib/rdb.pyi new file mode 100644 index 000000000000..4c0ed9cdaab0 --- /dev/null +++ b/stubs/python-xlib/Xlib/rdb.pyi @@ -0,0 +1,99 @@ +from _typeshed import SupportsDunderGT, SupportsDunderLT, SupportsRead +from collections.abc import Iterable, Mapping, Sequence +from re import Pattern +from typing import Any, Final, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from Xlib.display import Display +from Xlib.support.lock import _DummyLock + +_T = TypeVar("_T") +_T_contra = TypeVar("_T_contra", contravariant=True) + +_DB: TypeAlias = dict[str, tuple[_DB, ...]] +# A recursive type can be a bit annoying due to dict invariance, +# so this is a slightly less precise version of the _DB alias for parameter annotations +_DB_Param: TypeAlias = dict[str, Any] + +@type_check_only +class _SupportsComparisons(SupportsDunderLT[_T_contra], SupportsDunderGT[_T_contra], Protocol[_T_contra]): ... + +comment_re: Final[Pattern[str]] +resource_spec_re: Final[Pattern[str]] +value_escape_re: Final[Pattern[str]] +resource_parts_re: Final[Pattern[str]] +NAME_MATCH: Final = 0 +CLASS_MATCH: Final = 2 +WILD_MATCH: Final = 4 +MATCH_SKIP: Final = 6 + +class OptionError(Exception): ... + +class ResourceDB: + db: _DB + lock: _DummyLock + def __init__( + self, + file: bytes | SupportsRead[str] | None = None, + string: str | None = None, + resources: Iterable[tuple[str, object]] | None = None, + ) -> None: ... + def insert_file(self, file: bytes | SupportsRead[str]) -> None: ... + def insert_string(self, data: str) -> None: ... + def insert_resources(self, resources: Iterable[tuple[str, object]]) -> None: ... + def insert(self, resource: str, value: object) -> None: ... + def __getitem__(self, keys_tuple: tuple[str, str]) -> Any: ... + + @overload + def get(self, res: str, cls: str, default: None = None) -> Any: ... + @overload + def get(self, res: str, cls: str, default: _T) -> _T: ... + + def update(self, db: ResourceDB) -> None: ... + def output(self) -> str: ... + def getopt(self, name: str, argv: Sequence[str], opts: Mapping[str, Option]) -> Sequence[str]: ... + +def bin_insert(list: list[_SupportsComparisons[_T]], element: _SupportsComparisons[_T]) -> None: ... +def update_db(dest: _DB_Param, src: _DB_Param) -> None: ... +def copy_group(group: tuple[_DB_Param, ...]) -> tuple[_DB, ...]: ... +def copy_db(db: _DB_Param) -> _DB: ... +def output_db(prefix: str, db: _DB_Param) -> str: ... +def output_escape(value: object) -> str: ... + +class Option: + def parse(self, name: str, db: ResourceDB, args: Sequence[_T]) -> Sequence[_T]: ... + +class NoArg(Option): + specifier: str + value: object + def __init__(self, specifier: str, value: object) -> None: ... + +class IsArg(Option): + specifier: str + def __init__(self, specifier: str) -> None: ... + +class SepArg(Option): + specifier: str + def __init__(self, specifier: str) -> None: ... + +class ResArgClass(Option): + def parse(self, name: str, db: ResourceDB, args: Sequence[str]) -> Sequence[str]: ... # type: ignore[override] + +ResArg: ResArgClass + +class SkipArgClass(Option): ... + +SkipArg: SkipArgClass + +class SkipLineClass(Option): ... + +SkipLine: SkipLineClass + +class SkipNArgs(Option): + count: int + def __init__(self, count: int) -> None: ... + +def get_display_opts( + options: Mapping[str, Option], argv: Sequence[str] = ... +) -> tuple[Display, str, ResourceDB, Sequence[str]]: ... + +stdopts: Final[dict[str, SepArg | NoArg | ResArgClass]] diff --git a/stubs/python-xlib/Xlib/support/__init__.pyi b/stubs/python-xlib/Xlib/support/__init__.pyi new file mode 100644 index 000000000000..63adc8192d7e --- /dev/null +++ b/stubs/python-xlib/Xlib/support/__init__.pyi @@ -0,0 +1,3 @@ +from Xlib.support import connect as connect, lock as lock + +__all__ = ["lock", "connect"] diff --git a/stubs/python-xlib/Xlib/support/connect.pyi b/stubs/python-xlib/Xlib/support/connect.pyi new file mode 100644 index 000000000000..7aa8e41c5baf --- /dev/null +++ b/stubs/python-xlib/Xlib/support/connect.pyi @@ -0,0 +1,6 @@ +# Ignore OpenVMS in typeshed +from typing import Final + +from Xlib.support.unix_connect import get_auth as get_auth, get_display as get_display, get_socket as get_socket + +platform: Final[str] diff --git a/stubs/python-xlib/Xlib/support/lock.pyi b/stubs/python-xlib/Xlib/support/lock.pyi new file mode 100644 index 000000000000..236e96e502f1 --- /dev/null +++ b/stubs/python-xlib/Xlib/support/lock.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable + +class _DummyLock: + acquire: Callable[..., None] + release: Callable[..., None] + locked: Callable[..., None] + +def allocate_lock() -> _DummyLock: ... diff --git a/stubs/python-xlib/Xlib/support/unix_connect.pyi b/stubs/python-xlib/Xlib/support/unix_connect.pyi new file mode 100644 index 000000000000..74e6a749ff91 --- /dev/null +++ b/stubs/python-xlib/Xlib/support/unix_connect.pyi @@ -0,0 +1,24 @@ +import sys +from _socket import _Address +from _typeshed import Unused +from platform import uname_result +from re import Pattern +from socket import socket +from typing import Final, Literal, TypeAlias + +if sys.platform == "darwin": + SUPPORTED_PROTOCOLS: Final[tuple[None, Literal["tcp"], Literal["unix"], Literal["darwin"]]] + _Protocol: TypeAlias = Literal["tcp", "unix", "darwin"] | None + DARWIN_DISPLAY_RE: Final[Pattern[str]] +else: + SUPPORTED_PROTOCOLS: Final[tuple[None, Literal["tcp"], Literal["unix"]]] + _Protocol: TypeAlias = Literal["tcp", "unix"] | None +uname: uname_result +DISPLAY_RE: Final[Pattern[str]] + +def get_display(display: str | None) -> tuple[str, str | None, str | None, int, int]: ... +def get_socket(dname: _Address, protocol: _Protocol, host: _Address | None, dno: int) -> socket: ... +def new_get_auth(sock: socket, dname: Unused, protocol: _Protocol, host: Unused, dno: int) -> tuple[bytes, bytes]: ... +def old_get_auth(sock: Unused, dname: _Address, host: Unused, dno: Unused) -> tuple[str | Literal[b""], bytes]: ... + +get_auth = new_get_auth diff --git a/stubs/python-xlib/Xlib/support/vms_connect.pyi b/stubs/python-xlib/Xlib/support/vms_connect.pyi new file mode 100644 index 000000000000..f812f2be8320 --- /dev/null +++ b/stubs/python-xlib/Xlib/support/vms_connect.pyi @@ -0,0 +1,11 @@ +from _socket import _Address +from _typeshed import Unused +from re import Pattern +from socket import socket +from typing import Final + +display_re: Final[Pattern[str]] + +def get_display(display: str | None) -> tuple[str, None, str, int, int]: ... +def get_socket(dname: _Address, protocol: Unused, host: _Address, dno: int) -> socket: ... +def get_auth(sock: Unused, dname: Unused, host: Unused, dno: Unused) -> tuple[str, str]: ... diff --git a/stubs/python-xlib/Xlib/threaded.pyi b/stubs/python-xlib/Xlib/threaded.pyi new file mode 100644 index 000000000000..c7314799e154 --- /dev/null +++ b/stubs/python-xlib/Xlib/threaded.pyi @@ -0,0 +1,4 @@ +# This isn't just a re-export from from Xlib.support import lock +# Importing from this module will cause the lock.allocate_lock function to +# return a basic Python lock, instead of the default dummy lock +from Xlib.support import lock as lock diff --git a/stubs/python-xlib/Xlib/xauth.pyi b/stubs/python-xlib/Xlib/xauth.pyi new file mode 100644 index 000000000000..e6490c569673 --- /dev/null +++ b/stubs/python-xlib/Xlib/xauth.pyi @@ -0,0 +1,21 @@ +from _typeshed import FileDescriptorOrPath +from typing import Final + +from Xlib.X import ( + FamilyChaos as FamilyChaos, + FamilyDECnet as FamilyDECnet, + FamilyInternet as FamilyInternet, + FamilyInternetV6 as FamilyInternetV6, + FamilyServerInterpreted as FamilyServerInterpreted, +) + +FamilyLocal: Final = 256 + +class Xauthority: + entries: list[tuple[bytes, bytes, bytes, bytes, bytes]] + def __init__(self, filename: FileDescriptorOrPath | None = None) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, i: int) -> tuple[bytes, bytes, bytes, bytes, bytes]: ... + def get_best_auth( + self, family: bytes, address: bytes, dispno: bytes, types: tuple[bytes, ...] = (b"MIT-MAGIC-COOKIE-1",) + ) -> tuple[bytes, bytes]: ... diff --git a/stubs/python-xlib/Xlib/xobject/__init__.pyi b/stubs/python-xlib/Xlib/xobject/__init__.pyi new file mode 100644 index 000000000000..5d06a9d37e44 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/__init__.pyi @@ -0,0 +1,10 @@ +from Xlib.xobject import ( + colormap as colormap, + cursor as cursor, + drawable as drawable, + fontable as fontable, + icccm as icccm, + resource as resource, +) + +__all__ = ["colormap", "cursor", "drawable", "fontable", "icccm", "resource"] diff --git a/stubs/python-xlib/Xlib/xobject/colormap.pyi b/stubs/python-xlib/Xlib/xobject/colormap.pyi new file mode 100644 index 000000000000..a38c9b0dea36 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/colormap.pyi @@ -0,0 +1,25 @@ +from collections.abc import Sequence +from re import Pattern +from typing import Final + +from Xlib._typing import ErrorHandler +from Xlib.protocol import request, rq +from Xlib.xobject import resource + +rgb_res: Final[list[Pattern[str]]] + +class Colormap(resource.Resource): + __colormap__ = resource.Resource.__resource__ + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def copy_colormap_and_free(self, scr_cmap: int) -> Colormap: ... + def install_colormap(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def uninstall_colormap(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def alloc_color(self, red: int, green: int, blue: int) -> request.AllocColor: ... + def alloc_named_color(self, name: str) -> request.AllocColor | request.AllocNamedColor | None: ... + def alloc_color_cells(self, contiguous: bool, colors: int, planes: int) -> request.AllocColorCells: ... + def alloc_color_planes(self, contiguous: bool, colors: int, red: int, green: int, blue: int) -> request.AllocColorPlanes: ... + def free_colors(self, pixels: Sequence[int], plane_mask: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def store_colors(self, items: dict[str, int], onerror: ErrorHandler[object] | None = None) -> None: ... + def store_named_color(self, name: str, pixel: int, flags: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_colors(self, pixels: Sequence[int]) -> rq.Struct: ... + def lookup_color(self, name: str) -> request.LookupColor: ... diff --git a/stubs/python-xlib/Xlib/xobject/cursor.pyi b/stubs/python-xlib/Xlib/xobject/cursor.pyi new file mode 100644 index 000000000000..3d6952cebdc2 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/cursor.pyi @@ -0,0 +1,10 @@ +from Xlib._typing import ErrorHandler +from Xlib.protocol.structs import _RGB3IntIterable +from Xlib.xobject import resource + +class Cursor(resource.Resource): + __cursor__ = resource.Resource.__resource__ + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def recolor( + self, foreground: _RGB3IntIterable, background: _RGB3IntIterable, onerror: ErrorHandler[object] | None = None + ) -> None: ... diff --git a/stubs/python-xlib/Xlib/xobject/drawable.pyi b/stubs/python-xlib/Xlib/xobject/drawable.pyi new file mode 100644 index 000000000000..5aa7fadf3ef2 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/drawable.pyi @@ -0,0 +1,274 @@ +from collections.abc import Iterable, Sequence +from typing import Any, Literal, Protocol, type_check_only + +from Xlib._typing import ErrorHandler +from Xlib.protocol import request, rq +from Xlib.protocol.structs import _Arc6IntSequence, _Rectangle4IntSequence, _RGB3IntIterable, _Segment4IntSequence +from Xlib.xobject import colormap, cursor, fontable, resource + +# Protocol for the parts of PIL.Image.Image used by python-xlib. +@type_check_only +class _PilImage(Protocol): + @property + def mode(self) -> str: ... + @property + def size(self) -> tuple[int, int]: ... + def crop(self, box: tuple[int, int, int, int], /) -> _PilImage: ... + def tobytes(self, encoder_name: Literal["raw"], rawmode: str, stride: int, x: Literal[0], /) -> bytes: ... + +class Drawable(resource.Resource): + __drawable__ = resource.Resource.__resource__ + def get_geometry(self) -> request.GetGeometry: ... + def create_pixmap(self, width: int, height: int, depth: int) -> Pixmap: ... + def create_gc(self, **keys: object) -> fontable.GC: ... + def copy_area( + self, + gc: int, + src_drawable: int, + src_x: int, + src_y: int, + width: int, + height: int, + dst_x: int, + dst_y: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def copy_plane( + self, + gc: int, + src_drawable: int, + src_x: int, + src_y: int, + width: int, + height: int, + dst_x: int, + dst_y: int, + bit_plane: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def poly_point( + self, gc: int, coord_mode: int, points: Sequence[tuple[int, int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def point(self, gc: int, x: int, y: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def poly_line( + self, gc: int, coord_mode: int, points: Sequence[tuple[int, int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def line(self, gc: int, x1: int, y1: int, x2: int, y2: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def poly_segment( + self, gc: int, segments: Sequence[_Segment4IntSequence], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_rectangle( + self, gc: int, rectangles: Sequence[_Rectangle4IntSequence], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def rectangle( + self, gc: int, x: int, y: int, width: int, height: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_arc(self, gc: int, arcs: Sequence[_Arc6IntSequence], onerror: ErrorHandler[object] | None = None) -> None: ... + def arc( + self, + gc: int, + x: int, + y: int, + width: int, + height: int, + angle1: int, + angle2: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def fill_poly( + self, gc: int, shape: int, coord_mode: int, points: Sequence[tuple[int, int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_fill_rectangle( + self, gc: int, rectangles: Sequence[_Rectangle4IntSequence], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def fill_rectangle( + self, gc: int, x: int, y: int, width: int, height: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_fill_arc(self, gc: int, arcs: Sequence[_Arc6IntSequence], onerror: ErrorHandler[object] | None = None) -> None: ... + def fill_arc( + self, + gc: int, + x: int, + y: int, + width: int, + height: int, + angle1: int, + angle2: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def put_image( + self, + gc: int, + x: int, + y: int, + width: int, + height: int, + format: int, + depth: int, + left_pad: int, + data: bytes | bytearray, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def put_pil_image(self, gc: int, x: int, y: int, image: _PilImage, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_image(self, x: int, y: int, width: int, height: int, format: int, plane_mask: int) -> request.GetImage: ... + def draw_text( + self, gc: int, x: int, y: int, text: dict[str, str | int], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_text( + self, gc: int, x: int, y: int, items: Sequence[dict[str, str | int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_text_16( + self, gc: int, x: int, y: int, items: Sequence[dict[str, str | int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def image_text(self, gc: int, x: int, y: int, string: str, onerror: ErrorHandler[object] | None = None) -> None: ... + def image_text_16(self, gc: int, x: int, y: int, string: str, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_best_size(self, item_class: int, width: int, height: int) -> request.QueryBestSize: ... + +class Window(Drawable): + __window__ = resource.Resource.__resource__ + def create_window( + self, + x: int, + y: int, + width: int, + height: int, + border_width: int, + depth: int, + window_class: int = 0, + visual: int = 0, + onerror: ErrorHandler[object] | None = None, + **keys: object, + ) -> Window: ... + def change_attributes(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def get_attributes(self) -> request.GetWindowAttributes: ... + def destroy(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def destroy_sub_windows(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def change_save_set(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def reparent(self, parent: int, x: int, y: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def map(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def map_sub_windows(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def unmap(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def unmap_sub_windows(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def configure(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def circulate(self, direction: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def raise_window(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_tree(self) -> request.QueryTree: ... + def change_property( + self, + property: int, + property_type: int, + format: int, + data: Sequence[float] | Sequence[str], + mode: int = 0, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def change_text_property( + self, property: int, property_type: int, data: bytes | str, mode: int = 0, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def delete_property(self, property: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_property( + self, property: int, property_type: int, offset: int, length: int, delete: bool = False + ) -> request.GetProperty | None: ... + def get_full_property(self, property: int, property_type: int, sizehint: int = 10) -> request.GetProperty | None: ... + def get_full_text_property(self, property: int, property_type: int = 0, sizehint: int = 10) -> str | None: ... + def list_properties(self) -> list[int]: ... + def set_selection_owner(self, selection: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def convert_selection( + self, selection: int, target: int, property: int, time: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def send_event( + self, event: rq.Event, event_mask: int = 0, propagate: bool = False, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def grab_pointer( + self, owner_events: bool, event_mask: int, pointer_mode: int, keyboard_mode: int, confine_to: int, cursor: int, time: int + ) -> int: ... + def grab_button( + self, + button: int, + modifiers: int, + owner_events: bool, + event_mask: int, + pointer_mode: int, + keyboard_mode: int, + confine_to: int, + cursor: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def ungrab_button(self, button: int, modifiers: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def grab_keyboard(self, owner_events: bool, pointer_mode: int, keyboard_mode: int, time: int) -> int: ... + def grab_key( + self, + key: int, + modifiers: int, + owner_events: bool, + pointer_mode: int, + keyboard_mode: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def ungrab_key(self, key: int, modifiers: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_pointer(self) -> request.QueryPointer: ... + def get_motion_events(self, start: int, stop: int) -> rq.Struct: ... + def translate_coords(self, src_window: int, src_x: int, src_y: int) -> request.TranslateCoords: ... + def warp_pointer( + self, + x: int, + y: int, + src_window: int = 0, + src_x: int = 0, + src_y: int = 0, + src_width: int = 0, + src_height: int = 0, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def set_input_focus(self, revert_to: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def clear_area( + self, + x: int = 0, + y: int = 0, + width: int = 0, + height: int = 0, + exposures: bool = False, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def create_colormap(self, visual: int, alloc: int) -> colormap.Colormap: ... + def list_installed_colormaps(self) -> list[colormap.Colormap]: ... + def rotate_properties(self, properties: Sequence[int], delta: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_wm_name(self, name: bytes | str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_name(self) -> str | None: ... + def set_wm_icon_name(self, name: bytes | str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_icon_name(self) -> str | None: ... + def set_wm_class(self, inst: str, cls: str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_class(self) -> tuple[str, str] | None: ... + def set_wm_transient_for(self, window: Window, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_transient_for(self) -> Window | None: ... + def set_wm_protocols(self, protocols: Iterable[int], onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_protocols(self) -> list[int]: ... + def set_wm_colormap_windows(self, windows: Iterable[Window], onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_colormap_windows(self) -> Iterable[Window]: ... + def set_wm_client_machine(self, name: bytes | str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_client_machine(self) -> str | None: ... + def set_wm_normal_hints( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_normal_hints(self) -> rq.DictWrapper | None: ... + def set_wm_hints( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_hints(self) -> rq.DictWrapper | None: ... + def set_wm_state( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_state(self) -> rq.DictWrapper | None: ... + def set_wm_icon_size( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_icon_size(self) -> rq.DictWrapper | None: ... + +class Pixmap(Drawable): + __pixmap__ = resource.Resource.__resource__ + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def create_cursor( + self, mask: int, foreground: _RGB3IntIterable, background: _RGB3IntIterable, x: int, y: int + ) -> cursor.Cursor: ... + +def roundup(value: int, unit: int) -> int: ... diff --git a/stubs/python-xlib/Xlib/xobject/fontable.pyi b/stubs/python-xlib/Xlib/xobject/fontable.pyi new file mode 100644 index 000000000000..2f3c57844e73 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/fontable.pyi @@ -0,0 +1,33 @@ +from collections.abc import Sequence + +from Xlib._typing import ErrorHandler +from Xlib.protocol import request +from Xlib.protocol.structs import _RGB3IntIterable +from Xlib.xobject import cursor, resource + +class Fontable(resource.Resource): + __fontable__ = resource.Resource.__resource__ + def query(self) -> request.QueryFont: ... + def query_text_extents(self, string: str) -> request.QueryTextExtents: ... + +class GC(Fontable): + __gc__ = resource.Resource.__resource__ + def change(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def copy(self, src_gc: int, mask: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_dashes(self, offset: int, dashes: Sequence[int], onerror: ErrorHandler[object] | None = None) -> None: ... + def set_clip_rectangles( + self, + x_origin: int, + y_origin: int, + rectangles: Sequence[dict[str, int]], + ordering: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + +class Font(Fontable): + __font__ = resource.Resource.__resource__ + def close(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def create_glyph_cursor( + self, mask: Font, source_char: int, mask_char: int, foreground: _RGB3IntIterable, background: _RGB3IntIterable + ) -> cursor.Cursor: ... diff --git a/stubs/python-xlib/Xlib/xobject/icccm.pyi b/stubs/python-xlib/Xlib/xobject/icccm.pyi new file mode 100644 index 000000000000..8f64f1b06009 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/icccm.pyi @@ -0,0 +1,7 @@ +from Xlib.protocol import rq + +Aspect: rq.Struct +WMNormalHints: rq.Struct +WMHints: rq.Struct +WMState: rq.Struct +WMIconSize: rq.Struct diff --git a/stubs/python-xlib/Xlib/xobject/resource.pyi b/stubs/python-xlib/Xlib/xobject/resource.pyi new file mode 100644 index 000000000000..9ef991b6c91e --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/resource.pyi @@ -0,0 +1,10 @@ +from Xlib._typing import ErrorHandler +from Xlib.display import _BaseDisplay + +class Resource: + display: _BaseDisplay + id: int + owner: int + def __init__(self, display: _BaseDisplay, rid: int, owner: int = 0) -> None: ... + def __resource__(self) -> int: ... + def kill_client(self, onerror: ErrorHandler[object] | None = None) -> None: ... diff --git a/stubs/pytz/@tests/stubtest_allowlist.txt b/stubs/pytz/@tests/stubtest_allowlist.txt index c25eb8283ebb..564e96683da3 100644 --- a/stubs/pytz/@tests/stubtest_allowlist.txt +++ b/stubs/pytz/@tests/stubtest_allowlist.txt @@ -1,5 +1,3 @@ # "Abstract" methods, see the .pyi file for more details. -pytz.BaseTzInfo.localize -pytz.BaseTzInfo.normalize pytz.tzinfo.BaseTzInfo.localize pytz.tzinfo.BaseTzInfo.normalize diff --git a/stubs/pytz/METADATA.toml b/stubs/pytz/METADATA.toml index 0bdf109638a1..04a58c3e7c29 100644 --- a/stubs/pytz/METADATA.toml +++ b/stubs/pytz/METADATA.toml @@ -1,2 +1,3 @@ -version = "2021.3" -python2 = true +# This is a mirror of https://git.launchpad.net/pytz/tree, see https://pythonhosted.org/pytz/#latest-versions +version = "2026.5" +upstream-repository = "https://github.com/stub42/pytz" diff --git a/stubs/pytz/pytz/__init__.pyi b/stubs/pytz/pytz/__init__.pyi index 4838e7614128..2f243cbb3bf4 100644 --- a/stubs/pytz/pytz/__init__.pyi +++ b/stubs/pytz/pytz/__init__.pyi @@ -1,5 +1,7 @@ import datetime -from typing import ClassVar, Mapping +from _typeshed import Unused +from collections.abc import Mapping +from typing import ClassVar, type_check_only from .exceptions import ( AmbiguousTimeError as AmbiguousTimeError, @@ -10,9 +12,10 @@ from .exceptions import ( from .tzinfo import BaseTzInfo as BaseTzInfo, DstTzInfo, StaticTzInfo # Actually named UTC and then masked with a singleton with the same name +@type_check_only class _UTCclass(BaseTzInfo): - def localize(self, dt: datetime.datetime, is_dst: bool | None = ...) -> datetime.datetime: ... - def normalize(self, dt: datetime.datetime) -> datetime.datetime: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... def tzname(self, dt: datetime.datetime | None) -> str: ... def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... @@ -25,13 +28,13 @@ def timezone(zone: str) -> _UTCclass | StaticTzInfo | DstTzInfo: ... class _FixedOffset(datetime.tzinfo): zone: ClassVar[None] def __init__(self, minutes: int) -> None: ... - def utcoffset(self, dt: object) -> datetime.timedelta | None: ... - def dst(self, dt: object) -> datetime.timedelta: ... - def tzname(self, dt: object) -> None: ... - def localize(self, dt: datetime.datetime, is_dst: bool = ...) -> datetime.datetime: ... - def normalize(self, dt: datetime.datetime, is_dst: bool = ...) -> datetime.datetime: ... + def utcoffset(self, dt: Unused) -> datetime.timedelta | None: ... + def dst(self, dt: Unused) -> datetime.timedelta: ... + def tzname(self, dt: Unused) -> None: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... -def FixedOffset(offset: int, _tzinfos: dict[int, _FixedOffset] = ...) -> _UTCclass | _FixedOffset: ... +def FixedOffset(offset: int, _tzinfos: dict[int, _FixedOffset] = {}) -> _UTCclass | _FixedOffset: ... all_timezones: list[str] all_timezones_set: set[str] @@ -42,3 +45,20 @@ country_names: Mapping[str, str] ZERO: datetime.timedelta HOUR: datetime.timedelta VERSION: str + +__all__ = [ + "timezone", + "utc", + "country_timezones", + "country_names", + "AmbiguousTimeError", + "InvalidTimeError", + "NonExistentTimeError", + "UnknownTimeZoneError", + "all_timezones", + "all_timezones_set", + "common_timezones", + "common_timezones_set", + "BaseTzInfo", + "FixedOffset", +] diff --git a/stubs/pytz/pytz/lazy.pyi b/stubs/pytz/pytz/lazy.pyi new file mode 100644 index 000000000000..b0b5ca565aa2 --- /dev/null +++ b/stubs/pytz/pytz/lazy.pyi @@ -0,0 +1,20 @@ +from collections.abc import Iterator, Mapping as DictMixin +from typing import TypeVar + +_T = TypeVar("_T") +_VT = TypeVar("_VT") + +class LazyDict(DictMixin[str, _VT]): + data: dict[str, _VT] | None + def __getitem__(self, key: str) -> _VT: ... + def __contains__(self, key: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class LazyList(list[_T]): + # does not return `Self` type: + def __new__(cls, fill_iter: _T | None = None) -> LazyList[_T]: ... + +class LazySet(set[_T]): + # does not return `Self` type: + def __new__(cls, fill_iter: _T | None = None) -> LazySet[_T]: ... diff --git a/stubs/pytz/pytz/reference.pyi b/stubs/pytz/pytz/reference.pyi new file mode 100644 index 000000000000..be187db03f33 --- /dev/null +++ b/stubs/pytz/pytz/reference.pyi @@ -0,0 +1,40 @@ +import datetime + +from pytz import UTC as UTC + +class FixedOffset(datetime.tzinfo): + def __init__(self, offset: float, name: str) -> None: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + +STDOFFSET: datetime.timedelta +DSTOFFSET: datetime.timedelta + +class LocalTimezone(datetime.tzinfo): + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def tzname(self, dt: datetime.datetime) -> str: ... # type: ignore[override] + +Local: LocalTimezone +DSTSTART: datetime.datetime +DSTEND: datetime.datetime + +def first_sunday_on_or_after(dt: datetime.datetime) -> datetime.datetime: ... + +class USTimeZone(datetime.tzinfo): + stdoffset: datetime.timedelta + reprname: str + stdname: str + dstname: str + def __init__(self, hours: float, reprname: str, stdname: str, dstname: str) -> None: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + +Eastern: USTimeZone +Central: USTimeZone +Mountain: USTimeZone +Pacific: USTimeZone + +__all__ = ["FixedOffset", "LocalTimezone", "USTimeZone", "Eastern", "Central", "Mountain", "Pacific", "UTC"] diff --git a/stubs/pytz/pytz/tzfile.pyi b/stubs/pytz/pytz/tzfile.pyi new file mode 100644 index 000000000000..db28b7573915 --- /dev/null +++ b/stubs/pytz/pytz/tzfile.pyi @@ -0,0 +1,5 @@ +from typing import IO + +from pytz.tzinfo import DstTzInfo + +def build_tzinfo(zone: str, fp: IO[bytes]) -> DstTzInfo: ... diff --git a/stubs/pytz/pytz/tzinfo.pyi b/stubs/pytz/pytz/tzinfo.pyi index d60864ec035f..115dbc76a032 100644 --- a/stubs/pytz/pytz/tzinfo.pyi +++ b/stubs/pytz/pytz/tzinfo.pyi @@ -1,35 +1,45 @@ import datetime from abc import abstractmethod -from typing import Any +from typing import Any, overload class BaseTzInfo(datetime.tzinfo): + _utcoffset: datetime.timedelta | None + _tzname: str | None zone: str | None # Actually None but should be set on concrete subclasses # The following abstract methods don't exist in the implementation, but # are implemented by all sub-classes. @abstractmethod - def localize(self, dt: datetime.datetime) -> datetime.datetime: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = ...) -> datetime.datetime: ... @abstractmethod def normalize(self, dt: datetime.datetime) -> datetime.datetime: ... @abstractmethod - def tzname(self, dt: datetime.datetime | None) -> str: ... + def tzname(self, dt: datetime.datetime | None, /) -> str: ... @abstractmethod - def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... + def utcoffset(self, dt: datetime.datetime | None, /) -> datetime.timedelta | None: ... @abstractmethod - def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None: ... + def dst(self, dt: datetime.datetime | None, /) -> datetime.timedelta | None: ... class StaticTzInfo(BaseTzInfo): def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ... - def localize(self, dt: datetime.datetime, is_dst: bool = ...) -> datetime.datetime: ... - def normalize(self, dt: datetime.datetime, is_dst: bool = ...) -> datetime.datetime: ... - def tzname(self, dt: datetime.datetime | None, is_dst: bool | None = ...) -> str: ... - def utcoffset(self, dt: datetime.datetime | None, is_dst: bool | None = ...) -> datetime.timedelta: ... - def dst(self, dt: datetime.datetime | None, is_dst: bool | None = ...) -> datetime.timedelta: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def tzname(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> str: ... + def utcoffset(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> datetime.timedelta: ... + def dst(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> datetime.timedelta: ... class DstTzInfo(BaseTzInfo): - def __init__(self, _inf: Any = ..., _tzinfos: Any = ...) -> None: ... + def __init__(self, _inf: Any = None, _tzinfos: Any = None) -> None: ... def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ... - def localize(self, dt: datetime.datetime, is_dst: bool | None = ...) -> datetime.datetime: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... def normalize(self, dt: datetime.datetime) -> datetime.datetime: ... - def tzname(self, dt: datetime.datetime | None, is_dst: bool | None = ...) -> str: ... - def utcoffset(self, dt: datetime.datetime | None, is_dst: bool | None = ...) -> datetime.timedelta | None: ... - def dst(self, dt: datetime.datetime | None, is_dst: bool | None = ...) -> datetime.timedelta | None: ... + def tzname(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> str: ... + + # https://github.com/python/mypy/issues/12379 + @overload # type: ignore[override] + def utcoffset(self, dt: None, is_dst: bool | None = None) -> None: ... + @overload + def utcoffset(self, dt: datetime.datetime, is_dst: bool | None = None) -> datetime.timedelta: ... + + def dst(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> datetime.timedelta | None: ... + +__all__: list[str] = [] diff --git a/stubs/pyvmomi/@tests/stubtest_allowlist.txt b/stubs/pyvmomi/@tests/stubtest_allowlist.txt deleted file mode 100644 index b14e3eb36003..000000000000 --- a/stubs/pyvmomi/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,8 +0,0 @@ -pyVmomi.vim -pyVmomi.vim.event -pyVmomi.vim.fault -pyVmomi.vim.option -pyVmomi.vim.view -pyVmomi.vmodl -pyVmomi.vmodl.fault -pyVmomi.vmodl.query diff --git a/stubs/pyvmomi/METADATA.toml b/stubs/pyvmomi/METADATA.toml deleted file mode 100644 index 678b938f43f9..000000000000 --- a/stubs/pyvmomi/METADATA.toml +++ /dev/null @@ -1,3 +0,0 @@ -version = "7.0.*" -python2 = true -requires = ["types-enum34"] diff --git a/stubs/pyvmomi/pyVmomi/vim/__init__.pyi b/stubs/pyvmomi/pyVmomi/vim/__init__.pyi deleted file mode 100644 index a06b018224d4..000000000000 --- a/stubs/pyvmomi/pyVmomi/vim/__init__.pyi +++ /dev/null @@ -1,69 +0,0 @@ -from datetime import datetime -from enum import Enum -from typing import Any - -from ..vmodl.query import PropertyCollector -from .event import EventManager -from .option import OptionManager -from .view import ViewManager - -def __getattr__(name: str) -> Any: ... # incomplete - -class ManagedObject: ... - -class ManagedEntity(ManagedObject): - _moId: str - obj: None - name: str - def __getattr__(self, name: str) -> Any: ... # incomplete - -class ServiceInstanceContent: - setting: OptionManager - propertyCollector: PropertyCollector - rootFolder: Folder - viewManager: ViewManager - perfManager: PerformanceManager - eventManager: EventManager - def __getattr__(self, name: str) -> Any: ... # incomplete - -class ServiceInstance: - content: ServiceInstanceContent - def CurrentTime(self) -> datetime: ... - def __getattr__(self, name: str) -> Any: ... # incomplete - -class PerformanceManager: - class MetricId: - counterId: int - instance: str - def __init__(self, counterId: int, instance: str): ... - class PerfCounterInfo: - key: int - groupInfo: Any - nameInfo: Any - rollupType: Any - def __getattr__(self, name: str) -> Any: ... # incomplete - class QuerySpec: - entity: ManagedEntity - metricId: list[PerformanceManager.MetricId] - intervalId: int - maxSample: int - startTime: datetime - def __getattr__(self, name: str) -> Any: ... # incomplete - class EntityMetricBase: - entity: ManagedEntity - def QueryPerfCounterByLevel(self, collection_level: int) -> list[PerformanceManager.PerfCounterInfo]: ... - def QueryPerf(self, querySpec: list[PerformanceManager.QuerySpec]) -> list[PerformanceManager.EntityMetricBase]: ... - def __getattr__(self, name: str) -> Any: ... # incomplete - -class ClusterComputeResource(ManagedEntity): ... -class ComputeResource(ManagedEntity): ... -class Datacenter(ManagedEntity): ... -class Datastore(ManagedEntity): ... -class Folder(ManagedEntity): ... -class HostSystem(ManagedEntity): ... -class VirtualMachine(ManagedEntity): ... - -class VirtualMachinePowerState(Enum): - poweredOff: int - poweredOn: int - suspended: int diff --git a/stubs/pyvmomi/pyVmomi/vim/event.pyi b/stubs/pyvmomi/pyVmomi/vim/event.pyi deleted file mode 100644 index 4a422e3f1a7d..000000000000 --- a/stubs/pyvmomi/pyVmomi/vim/event.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from datetime import datetime -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete - -class Event: - createdTime: datetime - -class EventFilterSpec: - class ByTime: - def __init__(self, beginTime: datetime): ... - time: EventFilterSpec.ByTime - -class EventManager: - latestEvent: Event - def QueryEvents(self, filer: EventFilterSpec) -> list[Event]: ... diff --git a/stubs/pyvmomi/pyVmomi/vim/fault.pyi b/stubs/pyvmomi/pyVmomi/vim/fault.pyi deleted file mode 100644 index 80a1dac07b1f..000000000000 --- a/stubs/pyvmomi/pyVmomi/vim/fault.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete - -class InvalidName(Exception): ... -class RestrictedByAdministrator(Exception): ... -class NoPermission(Exception): ... diff --git a/stubs/pyvmomi/pyVmomi/vim/option.pyi b/stubs/pyvmomi/pyVmomi/vim/option.pyi deleted file mode 100644 index da6e05385ccd..000000000000 --- a/stubs/pyvmomi/pyVmomi/vim/option.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete - -class OptionManager: - def QueryOptions(self, name: str) -> list[OptionValue]: ... - -class OptionValue: - value: Any diff --git a/stubs/pyvmomi/pyVmomi/vim/view.pyi b/stubs/pyvmomi/pyVmomi/vim/view.pyi deleted file mode 100644 index c00ad51db1c7..000000000000 --- a/stubs/pyvmomi/pyVmomi/vim/view.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any, Type - -from pyVmomi.vim import ManagedEntity - -def __getattr__(name: str) -> Any: ... # incomplete - -class ContainerView: - def Destroy(self) -> None: ... - -class ViewManager: - # Doc says the `type` parameter of CreateContainerView is a `list[str]`, - # but in practice it seems to be `list[Type[ManagedEntity]]` - # Source: https://pubs.vmware.com/vi-sdk/visdk250/ReferenceGuide/vim.view.ViewManager.html - @staticmethod - def CreateContainerView(container: ManagedEntity, type: list[Type[ManagedEntity]], recursive: bool) -> ContainerView: ... diff --git a/stubs/pyvmomi/pyVmomi/vmodl/__init__.pyi b/stubs/pyvmomi/pyVmomi/vmodl/__init__.pyi deleted file mode 100644 index 9aff822ccc7b..000000000000 --- a/stubs/pyvmomi/pyVmomi/vmodl/__init__.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -class DynamicProperty: - def __init__(self, *, name: str = ..., val: Any = ...) -> None: ... - name: str - val: Any diff --git a/stubs/pyvmomi/pyVmomi/vmodl/fault.pyi b/stubs/pyvmomi/pyVmomi/vmodl/fault.pyi deleted file mode 100644 index 3876a513caf5..000000000000 --- a/stubs/pyvmomi/pyVmomi/vmodl/fault.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any - -def __getattr__(name: str) -> Any: ... # incomplete - -class InvalidArgument(Exception): ... diff --git a/stubs/pyvmomi/pyVmomi/vmodl/query.pyi b/stubs/pyvmomi/pyVmomi/vmodl/query.pyi deleted file mode 100644 index 89f2769c13f8..000000000000 --- a/stubs/pyvmomi/pyVmomi/vmodl/query.pyi +++ /dev/null @@ -1,57 +0,0 @@ -from typing import Any, Type - -from pyVmomi.vim import ManagedEntity -from pyVmomi.vim.view import ContainerView -from pyVmomi.vmodl import DynamicProperty - -class PropertyCollector: - class PropertySpec: - def __init__(self, *, all: bool = ..., type: Type[ManagedEntity] = ..., pathSet: list[str] = ...) -> None: ... - all: bool - type: Type[ManagedEntity] - pathSet: list[str] - class TraversalSpec: - def __init__( - self, *, path: str = ..., skip: bool = ..., type: Type[ContainerView] = ..., **kwargs: Any # incomplete - ) -> None: ... - path: str - skip: bool - type: Type[ContainerView] - def __getattr__(self, name: str) -> Any: ... # incomplete - class RetrieveOptions: - def __init__(self, *, maxObjects: int) -> None: ... - maxObjects: int - class ObjectSpec: - def __init__( - self, *, skip: bool = ..., selectSet: list[PropertyCollector.TraversalSpec] = ..., obj: Any = ... - ) -> None: ... - skip: bool - selectSet: list[PropertyCollector.TraversalSpec] - obj: Any - class FilterSpec: - def __init__( - self, - *, - propSet: list[PropertyCollector.PropertySpec] = ..., - objectSet: list[PropertyCollector.ObjectSpec] = ..., - **kwargs: Any, # incomplete - ) -> None: ... - propSet: list[PropertyCollector.PropertySpec] - objectSet: list[PropertyCollector.ObjectSpec] - def __getattr__(self, name: str) -> Any: ... # incomplete - class ObjectContent: - def __init__( - self, *, obj: ManagedEntity = ..., propSet: list[DynamicProperty] = ..., **kwargs: Any # incomplete - ) -> None: ... - obj: ManagedEntity - propSet: list[DynamicProperty] - def __getattr__(self, name: str) -> Any: ... # incomplete - class RetrieveResult: - def __init__(self, *, objects: list[PropertyCollector.ObjectContent] = ..., token: str | None = ...) -> None: ... - objects: list[PropertyCollector.ObjectContent] - token: str | None - def RetrievePropertiesEx( - self, specSet: list[PropertyCollector.FilterSpec], options: PropertyCollector.RetrieveOptions - ) -> PropertyCollector.RetrieveResult: ... - def ContinueRetrievePropertiesEx(self, token: str) -> PropertyCollector.RetrieveResult: ... - def __getattr__(self, name: str) -> Any: ... # incomplete diff --git a/stubs/pywin32/@tests/stubtest_allowlist_win32.txt b/stubs/pywin32/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..4ca47866f755 --- /dev/null +++ b/stubs/pywin32/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,51 @@ +# Not available at runtime. Contains type definitions that are otherwise not exposed +_win32typing + +# False-positive, stubtest shouldn't want to expose TYPE_CHECKING +(win32\.lib\.)?pywintypes\.TYPE_CHECKING + +# PyWin tool / debugger +pythonwin.start_pythonwin +pythonwin.pywin.* +win32com.client.combrowse +win32com.client.tlbrowse + +# Utilities to generate python bindings +win32com.client.CLSIDToClass +win32com.client.connect +win32com.client.genpy +win32com.client.makepy +win32com.client.selecttlb +win32com.client.util +win32com.makegw.* +(win32.lib.)?pywintypes.__import_pywin32_system_module__ + +# COM object servers scripts +win32com.servers.* +# Active X Scripts +win32com(ext)?.axscript.client.pyscript_rexec +win32com(ext)?.axscript.client.pyscript +win32com(ext)?.axscript.client.scriptdispatch + +# Demos, tests and debugging +win32com.demos.* +win32com.servers.test_pycomtest +win32com.test.* +win32com(ext)?.axdebug.dump +win32com(ext)?.axscript.client.pydumper +win32com(ext)?.directsound.test.* + +# Deprecated and makes a buffer of random junk. Use something like `b"\x00" * bufferSize` instead +# It's safer to not even expose this method as deprecated. +(win32.)?win32gui.PyMakeBuffer + +# failed to import, ImportError: DLL load failed while importing axdebug: The specified module could not be found. +win32com(ext)?.axdebug.adb +win32com(ext)?.axdebug.axdebug +win32com(ext)?.axdebug.codecontainer +win32com(ext)?.axdebug.contexts +win32com(ext)?.axdebug.debugger +win32com(ext)?.axdebug.documents +win32com(ext)?.axdebug.expressions +win32com(ext)?.axdebug.gateways +win32com(ext)?.axdebug.stackframe diff --git a/stubs/pywin32/METADATA.toml b/stubs/pywin32/METADATA.toml new file mode 100644 index 000000000000..05ca769e62be --- /dev/null +++ b/stubs/pywin32/METADATA.toml @@ -0,0 +1,6 @@ +version = "312.*" +upstream-repository = "https://github.com/mhammond/pywin32" + +[tool.stubtest] +supported-platforms = ["win32"] +ci-platforms = ["win32"] diff --git a/stubs/pywin32/_win32typing.pyi b/stubs/pywin32/_win32typing.pyi new file mode 100644 index 000000000000..306d778f56f7 --- /dev/null +++ b/stubs/pywin32/_win32typing.pyi @@ -0,0 +1,6462 @@ +# Not available at runtime. Contains type definitions that are otherwise not exposed and not part of a specific module. +from _typeshed import Incomplete, ReadableBuffer, Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Literal, SupportsIndex, TypeAlias, TypedDict, final, overload, type_check_only +from typing_extensions import Never, NotRequired, Required, Self, deprecated, disjoint_base + +from win32.lib.pywintypes import TimeType + +_TwoIntSequence: TypeAlias = Sequence[int] +_FourIntSequence: TypeAlias = Sequence[int] +# Is actually pywin.mfc.DocTemplate +DocTemplate: TypeAlias = Incomplete + +class ArgNotFound: ... +class PyOleEmpty: ... +class PyOleMissing: ... +class PyOleNothing: ... + +@disjoint_base +class PyDSCAPSType: + @property + def dwFlags(self): ... + @property + def dwFreeHw3DAllBuffers(self): ... + @property + def dwFreeHw3DStaticBuffers(self): ... + @property + def dwFreeHw3DStreamingBuffers(self): ... + @property + def dwFreeHwMemBytes(self): ... + @property + def dwFreeHwMixingAllBuffers(self): ... + @property + def dwFreeHwMixingStaticBuffers(self): ... + @property + def dwFreeHwMixingStreamingBuffers(self): ... + @property + def dwMaxContigFreeHwMemBytes(self): ... + @property + def dwMaxHw3DAllBuffers(self): ... + @property + def dwMaxHw3DStaticBuffers(self): ... + @property + def dwMaxHw3DStreamingBuffers(self): ... + @property + def dwMaxHwMixingAllBuffers(self): ... + @property + def dwMaxHwMixingStaticBuffers(self): ... + @property + def dwMaxHwMixingStreamingBuffers(self): ... + @property + def dwMaxSecondarySampleRate(self): ... + @property + def dwMinSecondarySampleRate(self): ... + @property + def dwPlayCpuOverheadSwBuffers(self): ... + @property + def dwPrimaryBuffers(self): ... + @property + def dwTotalHwMemBytes(self): ... + @property + def dwUnlockTransferRateHwBuffers(self): ... + +@disjoint_base +class PyDSCBCAPSType: + @property + def dwBufferBytes(self): ... + @property + def dwFlags(self): ... + +@disjoint_base +class PyDSCCAPSType: + @property + def dwChannels(self): ... + @property + def dwFlags(self): ... + @property + def dwFormats(self): ... + +@final +class PyNCB: + @property + def Bufflen(self): ... + + @property + def Callname(self) -> str: ... + @Callname.setter + def Callname(self, value: str | bytes) -> None: ... + + Cmd_cplt: int + Command: int + Event: int + Lana_num: int + Lsn: int + + @property + def Name(self) -> str: ... + @Name.setter + def Name(self, value: str | bytes) -> None: ... + + Num: int + Post: int + def Reset(self) -> None: ... + Retcode: int + Rto: int + Sto: int + +class COMMTIMEOUTS: ... +class CopyProgressRoutine: ... + +class DOCINFO: + @property + def DocName(self) -> str: ... + @property + def Output(self) -> str: ... + @property + def DataType(self) -> str: ... + @property + def Type(self): ... + +class ExportCallback: ... + +@type_check_only +class PrinterExtents(TypedDict): + Length: int + Width: int + +@type_check_only +class PrinterDpi(TypedDict): + xdpi: int + ydpi: int + +@type_check_only +class PrinterPaperSize(TypedDict): + x: int + y: int + +@type_check_only +class SizeL(TypedDict): + cx: int + cy: int + +@type_check_only +class RectL(TypedDict): + bottom: int + left: int + right: int + top: int + +@type_check_only +class FormInfo1(TypedDict): + Flags: int + Name: str + Size: SizeL + ImageableArea: RectL + +class ImportCallback: ... + +# Note: Don't use these, use `int` instead. Or an overload with a deprecation message on the tuple param. +# We're only keeping these here as a reminder when typing from source code. +# Deprecated: Support for passing 2 integers to create a 64bit value is deprecated - pass a long instead +LARGE_INTEGER: TypeAlias = int | tuple[int, int] +ULARGE_INTEGER: TypeAlias = int | tuple[int, int] + +class NCB: + @property + def Command(self): ... + @property + def Retcode(self): ... + @property + def Lsn(self): ... + @property + def Num(self): ... + @property + def Bufflen(self): ... + @property + def Callname(self) -> str: ... + @property + def Name(self) -> str: ... + @property + def Rto(self) -> str: ... + @property + def Sto(self) -> str: ... + @property + def Lana_num(self): ... + @property + def Cmd_cplt(self): ... + @property + def Event(self): ... + @property + def Post(self): ... + +@type_check_only +class PrinterDefaults(TypedDict, total=False): + pDataType: str | None + pDevMode: PyDEVMODEW | None + DesiredAccess: Required[int] + +@type_check_only +class PrinterInfo1(TypedDict): + Flags: int + pDescription: str + pName: str + pComment: str + +PrinterInfo1Tuple: TypeAlias = tuple[int, str, str, str] + +@type_check_only +class PrinterInfo2(TypedDict): + Attributes: int + AveragePPM: int + DefaultPriority: int + Priority: int + StartTime: int + Status: int + UntilTime: int + cJobs: int + pComment: str | None + pDatatype: str | None + pDevMode: PyDEVMODEW | None + pDriverName: str + pLocation: str | None + pParameters: str | None + pPortName: str + pPrintProcessor: str + pPrinterName: str + pSecurityDescriptor: PySECURITY_DESCRIPTOR | None + pSepFile: str | None + pServerName: str | None + pShareName: str | None + +PrinterInfo2Tuple: TypeAlias = tuple[ + str | None, # pServerName + str, # pPrinterName + str, # pShareName + str, # pPortName + str, # pDriverName + str, # pComment + str, # pLocation + None, # (always None) + str, # pSepFile + str, # pPrintProcessor + str, # pDatatype + str, # pParameters + None, # (always None) + int, # Attributes + int, # Priority + int, # DefaultPriority + int, # StartTime + int, # UntilTime + int, # Status + int, # cJobs + int, # AveragePPM +] + +@type_check_only +class PrinterInfo3(TypedDict): + pSecurityDescriptor: PySECURITY_DESCRIPTOR + +@type_check_only +class PrinterInfo4(TypedDict): + Attributes: int + pPrinterName: str + pServerName: str | None + +@type_check_only +class PrinterInfo5(TypedDict): + Attributes: int + DeviceNotSelectedTimeout: int + TransmissionRetryTimeout: int + pPortName: str + pPrinterName: str + +@type_check_only +class PrinterInfo6(TypedDict): + Status: int + +@type_check_only +class PrinterInfo7(TypedDict): + Action: int + ObjectGUID: str | None + +@type_check_only +class PrinterInfo89(TypedDict): + pDevMode: PyDEVMODEW | None + +@type_check_only +class JobInfo1(TypedDict): + JobId: int + pPrinterName: str + pMachineName: str + pUserName: str + pDocument: str + pDatatype: str + pStatus: str | None + Status: int + Priority: int + Position: int + TotalPages: int + PagesPrinted: int + Submitted: TimeType + +@type_check_only +class JobInfo2(JobInfo1): + pNotifyName: str + pPrintProcessor: str + pParameters: str + pDriverName: str + pDevMode: PyDEVMODEW + pSecurityDescriptor: PySECURITY_DESCRIPTOR | None + StartTime: int + UntilTime: int + Size: int + Time: int + +@type_check_only +class JobInfo3(TypedDict): + JobId: int + NextJobId: int + Reserved: int + +@type_check_only +class DriverInfo1(TypedDict): + Name: str + +MonitorInfo1: TypeAlias = DriverInfo1 +PortInfo1: TypeAlias = DriverInfo1 + +@type_check_only +class MonitorInfo2(MonitorInfo1): + DLLName: str + Environment: str + +@type_check_only +class PortInfo2(PortInfo1): + Description: str + MonitorName: str + PortType: int + Reserved: int + +@type_check_only +class DriverInfo2(DriverInfo1): + ConfigFile: str + DataFile: str + DriverPath: str + Environment: str + Version: int + +@type_check_only +class DriverInfo3(DriverInfo2): + DefaultDataType: str | None + DependentFiles: list[str] + HelpFile: str | None + MonitorName: str | None + +@type_check_only +class DriverInfo4(DriverInfo3): + PreviousNames: str | None + +@type_check_only +class DriverInfo5(DriverInfo2): + ConfigVersion: int + DriverAttributes: int + DriverVersion: int + +@type_check_only +class DriverInfo6(DriverInfo4): + MfgName: str + OEMUrl: str | None + Provider: str + DriverDate: TimeType + DriverVersion: int + +class PyACL: + def Initialize(self) -> None: ... + def IsValid(self) -> bool: ... + + @overload + @deprecated("""\ +Early versions of this function supported only two arguments. \ +This has been deprecated in preference of the three argument version, \ +which reflects the win32 API and the new functions in this module.""") + def AddAccessAllowedAce(self, access: int, sid: PySID, /) -> None: ... + @overload + def AddAccessAllowedAce(self, revision: int, access: int, sid: PySID, /) -> None: ... + + def AddAccessAllowedAceEx(self, revision: int, aceflags: int, access: int, sid: PySID, /) -> None: ... + def AddAccessAllowedObjectAce( + self, AceRevision, AceFlags, AccessMask, ObjectTypeGuid: PyIID, InheritedObjectTypeGuid: PyIID, sid: PySID, / + ) -> None: ... + + @overload + @deprecated("""\ +Early versions of this function supported only two arguments. \ +This has been deprecated in preference of the three argument version, \ +which reflects the win32 API and the new functions in this module.""") + def AddAccessDeniedAce(self, access: int, sid: PySID, /) -> None: ... + @overload + def AddAccessDeniedAce(self, revision: int, access: int, sid: PySID, /) -> None: ... + + def AddAccessDeniedAceEx(self, revision: int, aceflags: int, access: int, sid: PySID, /) -> None: ... + def AddMandatoryAce(self, AceRevision, AceFlags, MandatoryPolicy, LabelSid: PySID, /) -> None: ... + def AddAuditAccessAce(self, dwAceRevision, dwAccessMask, sid: PySID, bAuditSuccess, bAuditFailure, /) -> None: ... + def AddAuditAccessAceEx(self, dwAceRevision, AceFlags, dwAccessMask, sid: PySID, bAuditSuccess, bAuditFailure, /) -> None: ... + def AddAuditAccessObjectAce( + self, + dwAceRevision, + AceFlags, + dwAccessMask, + ObjectTypeGuid: PyIID, + InheritedObjectTypeGuid: PyIID, + sid: PySID, + bAuditSuccess, + bAuditFailure, + /, + ) -> None: ... + def GetAclSize(self): ... + def GetAclRevision(self): ... + def GetAceCount(self) -> int: ... + def GetAce(self, index: int, /) -> tuple[tuple[int, int], int, PySID]: ... + def DeleteAce(self, index: int, /) -> None: ... + def GetEffectiveRightsFromAcl(self, trustee: PyTRUSTEE | dict[str, int | PySID], /) -> int: ... + def GetAuditedPermissionsFromAcl(self, trustee: PyTRUSTEE, /) -> tuple[Incomplete, Incomplete]: ... + def SetEntriesInAcl(self, obexpl_list: tuple[dict[str, int | dict[str, int | PySID]], ...], /) -> PyACL: ... + def GetExplicitEntriesFromAcl(self) -> tuple[dict[str, int | dict[str, int | PySID]]] | None: ... + +class PyBITMAP: + @property + def bmType(self) -> int: ... + @property + def bmWidth(self) -> int: ... + @property + def bmHeight(self) -> int: ... + @property + def bmWidthBytes(self) -> int: ... + @property + def bmPlanes(self) -> int: ... + +class PyBLENDFUNCTION: ... +class PyCEHANDLE: ... + +class PyCERTSTORE: + @property + def HCERTSTORE(self): ... + + @overload + def CertCloseStore(self) -> None: ... + @overload + @deprecated("""\ +`Flags` argument has been deprecated as it is likely to crash the process if \ +`CERT_CLOSE_STORE_FORCE_FLAG` is specified. The underlying function is now \ +always called with `CERT_CLOSE_STORE_CHECK_FLAG`, and support for this \ +param will be dropped at some point in the future.""") + def CertCloseStore(self, Flags: int) -> None: ... + + def CertControlStore(self, Flags, CtrlType, CtrlPara: int) -> None: ... + def CertEnumCertificatesInStore(self) -> list[PyCERT_CONTEXT]: ... + def CertEnumCTLsInStore(self) -> list[PyCTL_CONTEXT]: ... + def CertSaveStore(self, MsgAndCertEncodingType, SaveAs, SaveTo, SaveToPara: str | int, Flags=...) -> None: ... + def CertAddEncodedCertificateToStore(self, CertEncodingType, CertEncoded, AddDisposition) -> PyCERT_CONTEXT: ... + def CertAddCertificateContextToStore(self, CertContext: PyCERT_CONTEXT, AddDisposition) -> PyCERT_CONTEXT: ... + def CertAddCertificateLinkToStore(self, CertContext: PyCERT_CONTEXT, AddDisposition) -> PyCERT_CONTEXT: ... + def CertAddCTLContextToStore(self, CtlContext: PyCTL_CONTEXT, AddDisposition) -> PyCTL_CONTEXT: ... + def CertAddCTLLinkToStore(self, CtlContext: PyCTL_CONTEXT, AddDisposition) -> PyCTL_CONTEXT: ... + def CertAddStoreToCollection(self, SiblingStore: PyCERTSTORE, UpdateFlag: int = ..., Priority: int = ...) -> None: ... + def CertRemoveStoreFromCollection(self, SiblingStore: PyCERTSTORE) -> None: ... + def PFXExportCertStoreEx(self, Password: Incomplete | None = ..., Flags=...): ... + +class PyCERT_ALT_NAME_ENTRY: ... +class PyCERT_ALT_NAME_INFO: ... + +class PyCERT_AUTHORITY_KEY_ID_INFO: + @property + def KeyId(self): ... + @property + def CertIssuer(self): ... + @property + def CertSerialNumber(self): ... + +class PyCERT_BASIC_CONSTRAINTS2_INFO: + @property + def fCA(self): ... + @property + def fPathLenConstraint(self): ... + @property + def PathLenConstraint(self): ... + +class PyCERT_BASIC_CONSTRAINTS_INFO: + @property + def SubjectType(self) -> PyCRYPT_BIT_BLOB: ... + @property + def fPathLenConstraint(self): ... + @property + def PathLenConstraint(self): ... + @property + def SubtreesConstraint(self): ... + +class PyCERT_CONTEXT: + @property + def HANDLE(self): ... + @property + def CertStore(self) -> PyCERTSTORE: ... + @property + def CertEncoded(self): ... + @property + def CertEncodingType(self): ... + @property + def Version(self): ... + @property + def Subject(self) -> str: ... + @property + def Issuer(self) -> str: ... + @property + def NotBefore(self) -> TimeType: ... + @property + def NotAfter(self) -> TimeType: ... + @property + def SignatureAlgorithm(self): ... + @property + def Extension(self) -> tuple[PyCERT_EXTENSION, ...]: ... + @property + def SubjectPublicKeyInfo(self) -> PyCERT_PUBLIC_KEY_INFO: ... + @property + def SerialNumber(self): ... + def CertFreeCertificateContext(self) -> None: ... + def CertEnumCertificateContextProperties(self) -> list[Incomplete]: ... + def CryptAcquireCertificatePrivateKey(self, Flags: int = ...) -> tuple[Incomplete, PyCRYPTPROV]: ... + def CertGetIntendedKeyUsage(self): ... + def CertGetEnhancedKeyUsage(self, Flags: int = ...): ... + def CertSerializeCertificateStoreElement(self, Flags: int = ...) -> str: ... + def CertVerifySubjectCertificateContext(self, Issuer: PyCERT_CONTEXT, Flags): ... + def CertDeleteCertificateFromStore(self) -> None: ... + def CertGetCertificateContextProperty(self, PropId): ... + def CertSetCertificateContextProperty(self, PropId, Data, Flags: int = ...) -> None: ... + +class PyCERT_EXTENSION: + @property + def ObjId(self): ... + @property + def Critical(self): ... + @property + def Value(self): ... + +class PyCERT_KEY_ATTRIBUTES_INFO: + @property + def KeyId(self): ... + @property + def IntendedKeyUsage(self) -> PyCRYPT_BIT_BLOB: ... + @property + def PrivateKeyUsagePeriod(self): ... + +class PyCERT_NAME_INFO: ... +class PyCERT_NAME_VALUE: ... +class PyCERT_OTHER_NAME: ... + +class PyCERT_POLICY_INFO: + @property + def PolicyIdentifier(self): ... + @property + def PolicyQualifier(self): ... + +class PyCERT_PUBLIC_KEY_INFO: + @property + def Algorithm(self) -> PyCRYPT_ALGORITHM_IDENTIFIER: ... + @property + def PublicKey(self) -> PyCRYPT_BIT_BLOB: ... + +class PyCOMSTAT: + @property + def cbInQue(self) -> int: ... + @property + def cbOutQue(self) -> int: ... + @property + def fCtsHold(self) -> int: ... + @property + def fDsrHold(self) -> int: ... + @property + def fRlsdHold(self) -> int: ... + @property + def fXoffHold(self) -> int: ... + @property + def fXoffSent(self) -> int: ... + @property + def fEof(self) -> int: ... + @property + def fTxim(self) -> int: ... + @property + def fReserved(self) -> int: ... + +@final +class PyCOORD: + def __new__(self, X: int = ..., Y: int = ...) -> Self: ... + X: int + Y: int + +class PyCREDENTIAL: + @property + def Flags(self): ... + @property + def Type(self): ... + @property + def TargetName(self) -> str: ... + @property + def Comment(self) -> str: ... + @property + def LastWritten(self) -> TimeType: ... + @property + def CredentialBlob(self) -> str: ... + @property + def Persist(self): ... + @property + def Attributes(self): ... + @property + def TargetAlias(self) -> str: ... + @property + def UserName(self) -> str: ... + +class PyCREDENTIAL_ATTRIBUTE: + @property + def Keyword(self) -> str: ... + @property + def Flags(self): ... + @property + def Value(self): ... + +class PyCREDENTIAL_TARGET_INFORMATION: + @property + def TargetName(self) -> str: ... + @property + def NetbiosServerName(self) -> str: ... + @property + def DnsServerName(self) -> str: ... + @property + def NetbiosDomainName(self) -> str: ... + @property + def DnsDomainName(self) -> str: ... + @property + def DnsTreeName(self) -> str: ... + @property + def PackageName(self) -> str: ... + @property + def Flags(self): ... + @property + def CredTypes(self) -> tuple[Incomplete, ...]: ... + +class PyCREDUI_INFO: + @property + def Parent(self) -> int: ... + @property + def MessageText(self) -> str: ... + @property + def CaptionText(self) -> str: ... + @property + def Banner(self) -> int: ... + +class PyCRYPTHASH: + def CryptDestroyHash(self) -> None: ... + def CryptDuplicateHash(self, Flags: int = ...) -> PyCRYPTHASH: ... + def CryptHashData(self, Data: str, Flags: int = ...) -> None: ... + def CryptHashSessionKey(self, Key: PyCRYPTKEY, Flags: int = ...) -> None: ... + def CryptSignHash(self, KeySpec, Flags: int = ...) -> str: ... + def CryptVerifySignature(self, Signature: str, PubKey: PyCRYPTKEY, Flags: int = ...) -> None: ... + def CryptGetHashParam(self, Param, Flags: int = ...): ... + +class PyCRYPTKEY: + @property + def HCRYPTPROV(self): ... + @property + def HCRYPTKEY(self): ... + def CryptDestroyKey(self) -> None: ... + def CryptExportKey(self, ExpKey: PyCRYPTKEY, BlobType, Flags: int = ...): ... + def CryptGetKeyParam(self, Param, Flags: int = ...): ... + def CryptDuplicateKey(self, Reserved: int = ..., Flags: int = ...) -> PyCRYPTKEY: ... + def CryptEncrypt(self, Final, Data, Hash: PyCRYPTHASH | None = ..., Flags: int = ...): ... + def CryptDecrypt(self, Final, Data, Hash: PyCRYPTHASH | None = ..., Flags: int = ...): ... + +class PyCRYPTMSG: + @property + def HCRYPTMSG(self): ... + def CryptMsgClose(self) -> None: ... + +class PyCRYPTPROTECT_PROMPTSTRUCT: ... + +class PyCRYPTPROV: + def CryptReleaseContext(self, Flags: int = ...) -> None: ... + def CryptGenKey(self, Algid, Flags, KeyLen: int = ...) -> PyCRYPTKEY: ... + def CryptGetProvParam(self, Param, Flags: int = ...) -> None: ... + def CryptGetUserKey(self, KeySpec) -> PyCRYPTKEY: ... + def CryptGenRandom(self, Len, SeedData: str | None = ...) -> str: ... + def CryptCreateHash(self, Algid, Key: PyCRYPTKEY | None = ..., Flags: int = ...) -> PyCRYPTHASH: ... + def CryptImportKey(self, Data, PubKey: PyCRYPTKEY | None = ..., Flags: int = ...) -> PyCRYPTKEY: ... + def CryptExportPublicKeyInfo(self, KeySpec, CertEncodingType=...) -> PyCERT_PUBLIC_KEY_INFO: ... + def CryptImportPublicKeyInfo(self, Info, CertEncodingType=...) -> PyCRYPTKEY: ... + +class PyCRYPT_ALGORITHM_IDENTIFIER: + @property + def ObjId(self): ... + @property + def Parameters(self): ... + +class PyCRYPT_ATTRIBUTE: + @property + def ObjId(self): ... + @property + def Value(self) -> tuple[Incomplete, ...]: ... + +class PyCRYPT_BIT_BLOB: + @property + def Data(self): ... + @property + def UnusedBits(self): ... + +class PyCRYPT_DECRYPT_MESSAGE_PARA: + @property + def CertStores(self) -> tuple[Incomplete, ...]: ... + @property + def MsgAndCertEncodingType(self): ... + @property + def Flags(self): ... + +class PyCRYPT_ENCRYPT_MESSAGE_PARA: + @property + def ContentEncryptionAlgorithm(self) -> PyCRYPT_ALGORITHM_IDENTIFIER: ... + @property + def CryptProv(self) -> PyCRYPTPROV: ... + @property + def EncryptionAuxInfo(self): ... + @property + def Flags(self): ... + @property + def InnerContentType(self): ... + @property + def MsgEncodingType(self): ... + +class PyCRYPT_SIGN_MESSAGE_PARA: + @property + def SigningCert(self) -> PyCERT_CONTEXT: ... + @property + def HashAlgorithm(self) -> PyCRYPT_ALGORITHM_IDENTIFIER: ... + @property + def HashAuxInfo(self): ... + @property + def MsgCert(self) -> tuple[PyCERT_CONTEXT, ...]: ... + @property + def MsgCrl(self) -> tuple[Incomplete, ...]: ... + @property + def AuthAttr(self) -> tuple[PyCRYPT_ATTRIBUTE, ...]: ... + @property + def UnauthAttr(self) -> tuple[PyCRYPT_ATTRIBUTE, ...]: ... + @property + def Flags(self): ... + @property + def InnerContentType(self): ... + @property + def MsgEncodingType(self): ... + +class PyCRYPT_VERIFY_MESSAGE_PARA: + @property + def MsgAndCertEncodingType(self): ... + @property + def CryptProv(self) -> PyCRYPTPROV: ... + @property + def PyGetSignerCertificate(self): ... + @property + def GetArg(self): ... + +class PyCTL_CONTEXT: + @property + def HCTL_CONTEXT(self): ... + def CertFreeCTLContext(self) -> None: ... + def CertEnumCTLContextProperties(self) -> tuple[Incomplete, ...]: ... + def CertEnumSubjectInSortedCTL(self) -> tuple[tuple[Incomplete, Incomplete], ...]: ... + def CertDeleteCTLFromStore(self) -> None: ... + def CertSerializeCTLStoreElement(self, Flags: int = ...) -> str: ... + +class PyCTL_USAGE: ... + +@type_check_only +class OIDInfo(TypedDict): + OID: str + Name: str | None + GroupId: int + Value: int + ExtraInfo: bytes + +@type_check_only +class ProveParam(TypedDict): + Param: int + Flags: int + Data: Incomplete + +@type_check_only +class ProveInfo(TypedDict): + ContainerName: str | None + ProvName: str | None + ProvType: int + Flags: int + KeySpec: int + ProvParam: tuple[ProveParam, ...] + +@type_check_only +class KeyIdentifierProperty(TypedDict): + PropId: int + Data: ProveInfo | bytes + +@type_check_only +class KeyIdentifier(TypedDict): + KeyIdentifier: bytes + Props: tuple[KeyIdentifierProperty] + +@type_check_only +class QueryObject(TypedDict): + MsgAndCertEncodingType: int + ContentType: int + FormatType: int + CertStore: PyCERTSTORE | None + Msg: PyCRYPTMSG | None + Context: PyCERT_CONTEXT | PyCTL_CONTEXT | int | None + +@type_check_only +class DecryptMessagePara(TypedDict): + CertStores: Iterable[PyCERTSTORE] + MsgAndCertEncodingType: NotRequired[int] + Flags: NotRequired[int] + +@type_check_only +class VerifyMessagePara(TypedDict): + MsgAndCertEncodingType: NotRequired[int] + CryptProv: NotRequired[PyCRYPTPROV | None] + GetSignerCertificate: NotRequired[Callable[..., Incomplete] | None] + GetArg: NotRequired[Callable[..., Incomplete] | None] + +@type_check_only +class DecodeMessage(TypedDict): + MsgType: int + InnerContentType: int + Decoded: bytes | None + XchgCert: PyCERT_CONTEXT | None + SignerCert: PyCERT_CONTEXT | None + +@type_check_only +class AlgorithmIdentifier(TypedDict): + ObjId: str + Parameters: ReadableBuffer | None + +@type_check_only +class EncryptMessagePara(TypedDict): + ContentEncryptionAlgorithm: AlgorithmIdentifier + CryptProv: NotRequired[PyCRYPTPROV | None] + EncryptionAuxInfo: NotRequired[None] + Flags: NotRequired[int] + InnerContentType: NotRequired[int] + MsgEncodingType: NotRequired[int] + +@type_check_only +class SignMessagePara(TypedDict): + SigningCert: PyCERT_CONTEXT + HashAlgorithm: AlgorithmIdentifier + HashAuxInfo: NotRequired[None] + MsgCert: NotRequired[Iterable[PyCERT_CONTEXT] | None] + MsgCrl: NotRequired[None] + AuthAttr: NotRequired[Iterable[dict[str, Incomplete]] | None] + UnauthAttr: NotRequired[Iterable[dict[str, Incomplete]] | None] + Flags: NotRequired[int] + InnerContentType: NotRequired[int] + MsgEncodingType: NotRequired[int] + +@type_check_only +class VerifyMessageSignature(TypedDict): + SignerCert: PyCERT_CONTEXT + Decoded: bytes | None + +@type_check_only +class DecryptAndVerifyMessageSignature(TypedDict): + Decrypted: bytes + XchgCert: PyCERT_CONTEXT + SignerCert: PyCERT_CONTEXT + +@type_check_only +class CryptBitBlob(TypedDict): + Data: ReadableBuffer + UnusedBits: int + +@final +class PyConsoleScreenBuffer: + def __new__(self, Handle) -> Self: ... + def SetConsoleActiveScreenBuffer(self) -> None: ... + def GetConsoleCursorInfo(self) -> tuple[Incomplete, Incomplete]: ... + def SetConsoleCursorInfo(self, Size, Visible) -> None: ... + def GetConsoleMode(self): ... + def SetConsoleMode(self, Mode) -> None: ... + def ReadConsole(self, NumberOfCharsToRead): ... + def WriteConsole(self, Buffer: str) -> int: ... + def FlushConsoleInputBuffer(self) -> None: ... + def SetConsoleTextAttribute(self, Attributes: int) -> None: ... + def SetConsoleCursorPosition(self, CursorPosition: PyCOORD) -> None: ... + def SetConsoleScreenBufferSize(self, Size: PyCOORD) -> None: ... + def SetConsoleWindowInfo(self, Absolute, ConsoleWindow: PySMALL_RECT) -> None: ... + def GetConsoleScreenBufferInfo(self): ... + def GetLargestConsoleWindowSize(self) -> PyCOORD: ... + def FillConsoleOutputAttribute(self, Attribute, Length, WriteCoord: PyCOORD): ... + def FillConsoleOutputCharacter(self, Character, Length, WriteCoord: PyCOORD): ... + def ReadConsoleOutputCharacter(self, Length, ReadCoord: PyCOORD) -> str: ... + def ReadConsoleOutputAttribute(self, Length, ReadCoord: PyCOORD) -> tuple[Incomplete, ...]: ... + def WriteConsoleOutputCharacter(self, Characters, WriteCoord: PyCOORD): ... + def WriteConsoleOutputAttribute(self, Attributes: tuple[Incomplete, ...], WriteCoord: PyCOORD): ... + def ScrollConsoleScreenBuffer( + self, ScrollRectangle: PySMALL_RECT, ClipRectangle: PySMALL_RECT, DestinationOrigin: PyCOORD, FillCharacter, FillAttribute + ) -> None: ... + def GetCurrentConsoleFont(self, MaximumWindow: bool = ...) -> tuple[int, PyCOORD]: ... + def GetConsoleFontSize(self, Font) -> PyCOORD: ... + def SetConsoleFont(self, Font) -> None: ... + def SetStdHandle(self, StdHandle) -> None: ... + def SetConsoleDisplayMode(self, Flags, NewScreenBufferDimensions: PyCOORD) -> None: ... + def WriteConsoleInput(self, Buffer: Iterable[PyINPUT_RECORD]): ... + def ReadConsoleInput(self, Length) -> tuple[PyINPUT_RECORD, ...]: ... + def PeekConsoleInput(self, Length) -> tuple[PyINPUT_RECORD, ...]: ... + def GetNumberOfConsoleInputEvents(self): ... + def Close(self) -> None: ... + def Detach(self) -> int: ... + +@disjoint_base +class PyCredHandle: + def Detach(self): ... + def FreeCredentialsHandle(self) -> None: ... + def QueryCredentialsAttributes(self, Attribute: int, /) -> str: ... + +@disjoint_base +class PyCtxtHandle: + def Detach(self): ... + def CompleteAuthToken(self, Token: PySecBufferDesc, /) -> None: ... + def QueryContextAttributes(self, Attribute, /) -> None: ... + def DeleteSecurityContext(self) -> None: ... + def QuerySecurityContextToken(self): ... + def MakeSignature(self, fqop, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def VerifySignature(self, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def EncryptMessage(self, fqop, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def DecryptMessage(self, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def ImpersonateSecurityContext(self) -> None: ... + def RevertSecurityContext(self) -> None: ... + +class PyDCB: + @property + def BaudRate(self) -> int: ... + @property + def wReserved(self) -> int: ... + @property + def XonLim(self) -> int: ... + @property + def XoffLim(self) -> int: ... + @property + def ByteSize(self) -> int: ... + @property + def Parity(self) -> int: ... + @property + def StopBits(self) -> int: ... + @property + def XonChar(self) -> str: ... + @property + def XoffChar(self) -> str: ... + @property + def ErrorChar(self) -> str: ... + @property + def EofChar(self) -> str: ... + @property + def EvtChar(self) -> str: ... + @property + def wReserved1(self) -> int: ... + @property + def fBinary(self) -> int: ... + @property + def fParity(self) -> int: ... + @property + def fOutxCtsFlow(self) -> int: ... + @property + def fOutxDsrFlow(self) -> int: ... + @property + def fDtrControl(self) -> int: ... + @property + def fDsrSensitivity(self) -> int: ... + @property + def fTXContinueOnXoff(self) -> int: ... + @property + def fOutX(self) -> int: ... + @property + def fInX(self) -> int: ... + @property + def fErrorChar(self) -> int: ... + @property + def fNull(self) -> int: ... + @property + def fRtsControl(self) -> int: ... + @property + def fAbortOnError(self) -> int: ... + @property + def fDummy2(self) -> int: ... + +@disjoint_base +class PyDEVMODEW: + def __new__(self, DriverExtra: int = 0) -> Self: ... + def Clear(self) -> None: ... + SpecVersion: int + DriverVersion: int + @property + def Size(self) -> int: ... + @property + def DriverExtra(self) -> int: ... + Fields: int + Orientation: int + PaperSize: int + PaperLength: int + PaperWidth: int + Position_x: int + Position_y: int + DisplayOrientation: int + DisplayFixedOutput: int + Scale: int + Copies: int + DefaultSource: int + PrintQuality: int + Color: int + Duplex: int + YResolution: int + TTOption: int + Collate: int + LogPixels: int + BitsPerPel: int + PelsWidth: int + PelsHeight: int + DisplayFlags: int + DisplayFrequency: int + ICMMethod: int + ICMIntent: int + MediaType: int + DitherType: int + Reserved1: int + Reserved2: int + Nup: int + PanningWidth: int + PanningHeight: int + DeviceName: str + FormName: str + + @property + def DriverData(self) -> bytes | None: ... + @DriverData.setter + def DriverData(self, value: bytes) -> None: ... + +@disjoint_base +class PyDISPLAY_DEVICE: + @property + def Size(self) -> int: ... + @property + def DeviceName(self) -> str: ... + @property + def DeviceString(self) -> str: ... + @property + def StateFlags(self) -> int: ... + @property + def DeviceID(self) -> str: ... + @property + def DeviceKey(self) -> str: ... + def Clear(self) -> None: ... + +class PyDLGITEMTEMPLATE: ... +class PyDLGTEMPLATE: ... +class PyDS_HANDLE: ... +class PyDS_NAME_RESULT_ITEM: ... +class PyDialogTemplate: ... +class PyEVTLOG_HANDLE: ... +class PyEVT_HANDLE: ... +class PyEVT_RPC_LOGIN: ... + +class PyEventLogRecord: + @property + def Reserved(self) -> int: ... + @property + def RecordNumber(self) -> int: ... + @property + def TimeGenerated(self) -> TimeType: ... + @property + def TimeWritten(self) -> TimeType: ... + @property + def EventID(self) -> int: ... + @property + def EventType(self) -> int: ... + @property + def EventCategory(self) -> int: ... + @property + def ReservedFlags(self) -> int: ... + @property + def ClosingRecordNumber(self) -> int: ... + @property + def SourceName(self) -> str: ... + @property + def StringInserts(self) -> tuple[str, ...]: ... + @property + def Sid(self) -> PySID | None: ... + @property + def Data(self) -> str: ... + @property + def ComputerName(self) -> str: ... + +class PyGROUP_INFO_0: + @property + def name(self) -> str: ... + +class PyGROUP_INFO_1: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + +class PyGROUP_INFO_1002: + @property + def comment(self) -> str: ... + +class PyGROUP_INFO_1005: + @property + def attributes(self): ... + +class PyGROUP_INFO_2: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def group_id(self): ... + @property + def attributes(self): ... + +class PyGROUP_USERS_INFO_0: + @property + def name(self) -> str: ... + +class PyGROUP_USERS_INFO_1: + @property + def name(self) -> str: ... + @property + def attributes(self): ... + +class PyGdiHANDLE: ... +class PyGetSignerCertificate: ... + +@disjoint_base +class PyHANDLE: # type: ignore[type-var] + def __new__(cls, *args: Never) -> Never: ... + @property + def handle(self) -> int: ... + def Close(self) -> None: ... + def close(self) -> None: ... + def Detach(self) -> Self: ... + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + # PyHANDLE sets a lot more dunder methods, only to make them all raise with `TypeError: bad operand type` + +@final +class PyHDESK: + def __new__(self, handle) -> Self: ... + def SetThreadDesktop(self) -> None: ... + def EnumDesktopWindows(self) -> tuple[int, ...]: ... + def SwitchDesktop(self) -> None: ... + def CloseDesktop(self) -> None: ... + def Detach(self) -> int: ... + +class PyHDEVNOTIFY: ... + +class PyHHNTRACK: + @property + def action(self): ... + @property + def hdr(self): ... + @property + def curUrl(self) -> str: ... + @property + def winType(self): ... + +class PyHHN_NOTIFY: + @property + def hdr(self): ... + @property + def url(self) -> str: ... + +class PyHH_AKLINK: + @property + def indexOnFail(self): ... + @property + def keywords(self) -> str: ... + @property + def url(self) -> str: ... + @property + def msgText(self) -> str: ... + @property + def msgTitle(self) -> str: ... + @property + def window(self) -> str: ... + +class PyHH_FTS_QUERY: + @property + def uniCodeStrings(self): ... + @property + def proximity(self): ... + @property + def stemmedSearch(self): ... + @property + def titleOnly(self): ... + @property + def execute(self): ... + @property + def searchQuery(self) -> str: ... + +class PyHH_POPUP: + @property + def hinst(self): ... + @property + def idString(self): ... + @property + def clrForeground(self): ... + @property + def clrBackground(self): ... + @property + def text(self) -> str: ... + @property + def font(self) -> str: ... + @property + def pt(self): ... + @property + def margins(self): ... + +class PyHH_WINTYPE: + @property + def uniCodeStrings(self): ... + @property + def validMembers(self): ... + @property + def winProperties(self): ... + @property + def styles(self): ... + @property + def exStyles(self): ... + @property + def showState(self): ... + @property + def hwndHelp(self): ... + @property + def hwndCaller(self): ... + @property + def hwndToolBar(self): ... + @property + def hwndNavigation(self): ... + @property + def hwndHTML(self): ... + @property + def navWidth(self): ... + @property + def toolBarFlags(self): ... + @property + def notExpanded(self): ... + @property + def curNavType(self): ... + @property + def idNotify(self): ... + @property + def typeName(self) -> str: ... + @property + def caption(self) -> str: ... + @property + def windowPos(self): ... + @property + def HTMLPos(self): ... + @property + def toc(self) -> str: ... + @property + def index(self) -> str: ... + @property + def file(self) -> str: ... + @property + def home(self) -> str: ... + @property + def jump1(self) -> str: ... + @property + def jump2(self) -> str: ... + @property + def urlJump1(self) -> str: ... + @property + def urlJump2(self) -> str: ... + +class PyHINTERNET: ... + +class PyHKEY: + def Close(self): ... + +class PyHTHEME: ... + +@final +class PyHWINSTA: + def __new__(self, handle) -> Self: ... + def EnumDesktops(self) -> tuple[Incomplete, ...]: ... + def SetProcessWindowStation(self) -> None: ... + def CloseWindowStation(self) -> None: ... + def Detach(self) -> int: ... + +class PyICONINFO: ... + +@final +class PyIID: ... + +@final +class PyINPUT_RECORD: + def __new__(self, EventType: int) -> Self: ... + EventType: int + KeyDown: int | bool + RepeatCount: int + VirtualKeyCode: int + VirtualScanCode: Incomplete + Char: str + ControlKeyState: int + ButtonState: int + EventFlags: int + MousePosition: PyCOORD + Size: PyCOORD + SetFocus: Incomplete + CommandId: Incomplete + +class PyLOCALGROUP_INFO_0: + @property + def name(self) -> str: ... + +class PyLOCALGROUP_INFO_1: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + +class PyLOCALGROUP_INFO_1002: + @property + def comment(self) -> str: ... + +class PyLOCALGROUP_MEMBERS_INFO_0: + @property + def sid(self) -> PySID: ... + +class PyLOCALGROUP_MEMBERS_INFO_1: + @property + def sid(self) -> PySID: ... + @property + def sidusage(self): ... + @property + def name(self) -> str: ... + +class PyLOCALGROUP_MEMBERS_INFO_2: + @property + def sid(self) -> PySID: ... + @property + def sidusage(self): ... + @property + def domainandname(self) -> str: ... + +class PyLOCALGROUP_MEMBERS_INFO_3: + @property + def domainandname(self) -> str: ... + +class PyLOGBRUSH: + @property + def Style(self): ... + @property + def Color(self): ... + @property + def Hatch(self) -> int: ... + +class PyLOGFONT: + @property + def lfHeight(self) -> int: ... + @property + def lfWidth(self) -> int: ... + @property + def lfEscapement(self) -> int: ... + @property + def lfOrientation(self) -> int: ... + @property + def lfWeight(self) -> int: ... + @property + def lfItalic(self) -> int: ... + @property + def lfUnderline(self) -> int: ... + @property + def lfStrikeOut(self) -> int: ... + @property + def lfCharSet(self) -> int: ... + @property + def lfOutPrecision(self) -> int: ... + @property + def lfClipPrecision(self) -> int: ... + @property + def lfQuality(self) -> int: ... + @property + def lfPitchAndFamily(self) -> int: ... + @property + def lfFaceName(self) -> str: ... + +class PyLSA_HANDLE: ... +class PyLUID_AND_ATTRIBUTES: ... +class PyLsaLogon_HANDLE: ... +class PyMSG: ... + +@final +class PyNETRESOURCE: + dwScope: int + dwType: int + dwDisplayType: int + dwUsage: int + lpComment: str | None + lpLocalName: str | None + lpProvider: str | None + lpRemoteName: str | None + +class PyNET_VALIDATE_AUTHENTICATION_INPUT_ARG: ... +class PyNET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG: ... +class PyNET_VALIDATE_PERSISTED_FIELDS: ... + +class PyNMHDR: + @property + def hwndFrom(self): ... + @property + def idFrom(self): ... + @property + def code(self): ... + +class PyNOTIFYICONDATA: ... + +class PyOVERLAPPED: + Offset: int + OffsetHigh: int + object: object + dword: int + hEvent: int + Internal: int + InternalHigh: int + +class PyOVERLAPPEDReadBuffer: ... + +class PyPERF_COUNTER_DEFINITION: + @property + def DefaultScale(self) -> int: ... + @property + def DetailLevel(self) -> int: ... + @property + def CounterType(self) -> int: ... + @property + def CounterNameTitleIndex(self) -> int: ... + @property + def CounterHelpTitleIndex(self) -> int: ... + def Increment(self) -> None: ... + def Decrement(self) -> None: ... + def Set(self) -> None: ... + def Get(self) -> None: ... + +class PyPERF_OBJECT_TYPE: + @property + def ObjectNameTitleIndex(self) -> int: ... + @property + def ObjectHelpTitleIndex(self) -> int: ... + @property + def DefaultCounterIndex(self) -> int: ... + def Close(self) -> None: ... + +class PyPOINT: ... + +class PyPROFILEINFO: + @property + def UserName(self) -> str: ... + @property + def Flags(self): ... + @property + def ProfilePath(self) -> str: ... + @property + def DefaultPath(self) -> str: ... + @property + def ServerName(self) -> str: ... + @property + def PolicyPath(self) -> str: ... + @property + def Profile(self) -> PyHKEY: ... + +class PyPerfMonManager: + def Close(self) -> None: ... + +class PyPrinterHANDLE(PyHANDLE): ... +class PyRECT: ... +class PyResourceId: ... +class PySCROLLINFO: ... +class PySC_HANDLE: ... + +class PySECURITY_ATTRIBUTES: + bInheritHandle: int + SECURITY_DESCRIPTOR: PySECURITY_DESCRIPTOR + +class PySECURITY_DESCRIPTOR: + def Initialize(self) -> None: ... + def GetSecurityDescriptorOwner(self) -> PySID: ... + def GetSecurityDescriptorDacl(self) -> PyACL: ... + def GetSecurityDescriptorSacl(self) -> PyACL: ... + def GetSecurityDescriptorControl(self) -> tuple[Incomplete, Incomplete]: ... + def SetSecurityDescriptorOwner(self, sid: PySID, bOwnerDefaulted: int | bool, /) -> None: ... + def SetSecurityDescriptorGroup(self, sid: PySID, bOwnerDefaulted, /): ... + def SetSecurityDescriptorDacl(self, bSaclPresent: int | bool, SACL: PyACL, bSaclDefaulted: int | bool, /) -> None: ... + def SetSecurityDescriptorSacl(self, bSaclPresent, SACL: PyACL, bSaclDefaulted, /) -> None: ... + def SetSecurityDescriptorControl(self, ControlBitsOfInterest, ControlBitsToSet, /) -> None: ... + def IsValid(self) -> bool: ... + def GetLength(self) -> None: ... + def IsSelfRelative(self) -> bool: ... + +class PySERVER_INFO_100: + @property + def platform_id(self): ... + @property + def name(self) -> str: ... + +class PySERVER_INFO_101: + @property + def platform_id(self): ... + @property + def name(self) -> str: ... + @property + def version_major(self): ... + @property + def version_minor(self): ... + @property + def type(self): ... + @property + def comment(self) -> str: ... + +class PySERVER_INFO_102: + @property + def platform_id(self): ... + @property + def name(self) -> str: ... + @property + def version_major(self): ... + @property + def version_minor(self): ... + @property + def type(self): ... + @property + def comment(self) -> str: ... + @property + def users(self): ... + @property + def disc(self): ... + @property + def hidden(self): ... + @property + def announce(self): ... + @property + def anndelta(self): ... + @property + def userpath(self) -> str: ... + +class PySERVER_INFO_402: + @property + def ulist_mtime(self): ... + @property + def glist_mtime(self): ... + @property + def alist_mtime(self): ... + @property + def security(self): ... + @property + def numadmin(self): ... + @property + def lanmask(self): ... + @property + def guestacct(self) -> str: ... + @property + def chdevs(self): ... + @property + def chdevq(self): ... + @property + def chdevjobs(self): ... + @property + def connections(self): ... + @property + def shares(self): ... + @property + def openfiles(self): ... + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def sessreqs(self): ... + @property + def opensearch(self): ... + @property + def activelocks(self): ... + @property + def numreqbuf(self): ... + @property + def sizreqbuf(self): ... + @property + def numbigbuf(self): ... + @property + def numfiletasks(self): ... + @property + def alertsched(self): ... + @property + def erroralert(self): ... + @property + def logonalert(self): ... + @property + def accessalert(self): ... + @property + def diskalert(self): ... + @property + def netioalert(self): ... + @property + def maxauditsz(self): ... + @property + def srvheuristics(self) -> str: ... + +class PySERVER_INFO_403: + @property + def ulist_mtime(self): ... + @property + def glist_mtime(self): ... + @property + def alist_mtime(self): ... + @property + def security(self): ... + @property + def numadmin(self): ... + @property + def lanmask(self): ... + @property + def guestacct(self) -> str: ... + @property + def chdevs(self): ... + @property + def chdevq(self): ... + @property + def chdevjobs(self): ... + @property + def connections(self): ... + @property + def shares(self): ... + @property + def openfiles(self): ... + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def sessreqs(self): ... + @property + def opensearch(self): ... + @property + def activelocks(self): ... + @property + def numreqbuf(self): ... + @property + def sizreqbuf(self): ... + @property + def numbigbuf(self): ... + @property + def numfiletasks(self): ... + @property + def alertsched(self): ... + @property + def erroralert(self): ... + @property + def logonalert(self): ... + @property + def accessalert(self): ... + @property + def diskalert(self): ... + @property + def netioalert(self): ... + @property + def maxauditsz(self): ... + @property + def srvheuristics(self) -> str: ... + @property + def auditedevents(self): ... + @property + def autoprofile(self): ... + @property + def autopath(self) -> str: ... + +class PySERVER_INFO_502: + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def opensearch(self): ... + @property + def sizreqbuf(self): ... + @property + def initworkitems(self): ... + @property + def maxworkitems(self): ... + @property + def rawworkitems(self): ... + @property + def irpstacksize(self): ... + @property + def maxrawbuflen(self): ... + @property + def sessusers(self): ... + @property + def sessconns(self): ... + @property + def maxpagedmemoryusage(self): ... + @property + def maxnonpagedmemoryusage(self): ... + @property + def enableforcedlogoff(self): ... + @property + def timesource(self): ... + @property + def acceptdownlevelapis(self): ... + @property + def lmannounce(self): ... + +class PySERVER_INFO_503: + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def opensearch(self): ... + @property + def sizreqbuf(self): ... + @property + def initworkitems(self): ... + @property + def maxworkitems(self): ... + @property + def rawworkitems(self): ... + @property + def irpstacksize(self): ... + @property + def maxrawbuflen(self): ... + @property + def sessusers(self): ... + @property + def sessconns(self): ... + @property + def maxpagedmemoryusage(self): ... + @property + def maxnonpagedmemoryusage(self): ... + @property + def enableforcedlogoff(self): ... + @property + def timesource(self): ... + @property + def acceptdownlevelapis(self): ... + @property + def lmannounce(self): ... + @property + def domain(self) -> str: ... + @property + def maxkeepsearch(self): ... + @property + def scavtimeout(self): ... + @property + def minrcvqueue(self): ... + @property + def minfreeworkitems(self): ... + @property + def xactmemsize(self): ... + @property + def threadpriority(self): ... + @property + def maxmpxct(self): ... + @property + def oplockbreakwait(self): ... + @property + def oplockbreakresponsewait(self): ... + @property + def enableoplocks(self): ... + @property + def enablefcbopens(self): ... + @property + def enableraw(self): ... + @property + def enablesharednetdrives(self): ... + @property + def minfreeconnections(self): ... + @property + def maxfreeconnections(self): ... + +class PySHARE_INFO_0: + @property + def netname(self) -> str: ... + +class PySHARE_INFO_1: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + +class PySHARE_INFO_2: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + @property + def permissions(self): ... + @property + def max_uses(self): ... + @property + def current_uses(self): ... + @property + def path(self) -> str: ... + @property + def passwd(self) -> str: ... + +class PySHARE_INFO_501: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + @property + def flags(self): ... + +class PySHARE_INFO_502: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + @property + def permissions(self): ... + @property + def max_uses(self): ... + @property + def current_uses(self): ... + @property + def path(self) -> str: ... + @property + def passwd(self) -> str: ... + @property + def reserved(self): ... + @property + def security_descriptor(self) -> PySECURITY_DESCRIPTOR: ... + +class PySID: + def Initialize(self, idAuthority, numSubauthorities, /) -> None: ... + def IsValid(self) -> bool: ... + def SetSubAuthority(self, index, val, /) -> None: ... + def GetLength(self): ... + def GetSubAuthorityCount(self): ... + def GetSubAuthority(self): ... + def GetSidIdentifierAuthority(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... + +class PySID_AND_ATTRIBUTES: ... +class PySIZE: ... + +@final +class PySMALL_RECT: + def __new__(self, Left: int = ..., Top: int = ..., Right: int = ..., Bottom: int = ...) -> Self: ... + Left: int + Top: int + Right: int + Bottom: int + +class PySTARTUPINFO: + dwX: int + dwY: int + dwXSize: int + dwYSize: int + dwXCountChars: int + dwYCountChars: int + dwFillAttribute: int + dwFlags: int + wShowWindow: int + hStdInput: int + hStdOutput: int + hStdError: int + lpDesktop: str + lpTitle: str + +@disjoint_base +class PySecBuffer: + def __new__(self, BufferSize, BufferType) -> Self: ... + @property + def BufferType(self): ... + @property + def Buffer(self) -> str: ... + @property + def BufferSize(self): ... + @property + def MaxBufferSize(self): ... + def Clear(self) -> None: ... + +@disjoint_base +class PySecBufferDesc: + def __new__(self, Version=...) -> Self: ... + Version: Incomplete + Buffer: Incomplete + def append(self, buffer, /) -> None: ... + def __getitem__(self, index: SupportsIndex, /) -> PySecBuffer: ... + +class PyTOKEN_GROUPS: ... +class PyTOKEN_PRIVILEGES: ... + +class PyTRIVERTEX: + @property + def x(self): ... + @property + def y(self): ... + @property + def Red(self): ... + @property + def Green(self): ... + @property + def Blue(self): ... + @property + def Alpha(self): ... + +# Properties Multiple* are ignored +class PyTRUSTEE: + @property + def TrusteeForm(self) -> int: ... + @property + def TrusteeType(self) -> int: ... + @property + def Identifier(self) -> PySID: ... + @property + def MultipleTrustee(self) -> None: ... + @property + def MultipleTrusteeOperation(self) -> Literal[0]: ... + +class PyTS_HANDLE: ... + +class PyUSER_INFO_0: + @property + def name(self) -> str: ... + +class PyUSER_INFO_1: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + +class PyUSER_INFO_10: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def full_name(self) -> str: ... + +class PyUSER_INFO_1003: + @property + def password(self) -> str: ... + +class PyUSER_INFO_1005: + @property + def priv(self): ... + +class PyUSER_INFO_1006: + @property + def home_dir(self) -> str: ... + +class PyUSER_INFO_1007: + @property + def comment(self) -> str: ... + +class PyUSER_INFO_1008: + @property + def flags(self): ... + +class PyUSER_INFO_1009: + @property + def script_path(self) -> str: ... + +class PyUSER_INFO_1010: + @property + def auth_flags(self): ... + +class PyUSER_INFO_1011: + @property + def full_name(self) -> str: ... + +class PyUSER_INFO_11: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def full_name(self) -> str: ... + @property + def priv(self): ... + @property + def auth_flags(self): ... + @property + def password_age(self): ... + @property + def home_dir(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def workstations(self) -> str: ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def code_page(self): ... + +class PyUSER_INFO_2: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + @property + def auth_flags(self): ... + @property + def full_name(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def workstations(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def acct_expires(self): ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def code_page(self): ... + +class PyUSER_INFO_20: + @property + def name(self) -> str: ... + @property + def full_name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def user_id(self): ... + +class PyUSER_INFO_3: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + @property + def auth_flags(self): ... + @property + def full_name(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def workstations(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def acct_expires(self): ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def code_page(self): ... + @property + def user_id(self): ... + @property + def primary_group_id(self): ... + @property + def profile(self) -> str: ... + @property + def home_dir_drive(self) -> str: ... + @property + def password_expired(self): ... + +class PyUSER_INFO_4: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + @property + def auth_flags(self): ... + @property + def full_name(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def workstations(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def acct_expires(self): ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def code_page(self): ... + @property + def user_sid(self) -> PySID: ... + @property + def primary_group_id(self): ... + @property + def profile(self) -> str: ... + @property + def home_dir_drive(self) -> str: ... + @property + def password_expired(self): ... + +class PyUSER_MODALS_INFO_0: + @property + def min_passwd_len(self): ... + @property + def max_passwd_age(self): ... + @property + def min_passwd_age(self): ... + @property + def force_logoff(self): ... + @property + def password_hist_len(self): ... + +class PyUSER_MODALS_INFO_1: + @property + def role(self): ... + @property + def primary(self) -> str: ... + +class PyUSER_MODALS_INFO_2: + @property + def domain_name(self) -> str: ... + @property + def domain_id(self) -> PySID: ... + +class PyUSER_MODALS_INFO_3: + @property + def lockout_duration(self): ... + @property + def lockout_observation_window(self): ... + @property + def usrmod3_lockout_threshold(self): ... + +class PyUSE_INFO_0: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + +class PyUSE_INFO_1: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + @property + def password(self) -> str: ... + @property + def status(self): ... + @property + def asg_type(self): ... + @property + def refcount(self): ... + @property + def usecount(self): ... + +class PyUSE_INFO_2: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + @property + def password(self) -> str: ... + @property + def status(self): ... + @property + def asg_type(self): ... + @property + def refcount(self): ... + @property + def usecount(self): ... + @property + def username(self) -> str: ... + @property + def domainname(self) -> str: ... + +class PyUSE_INFO_3: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + @property + def password(self) -> str: ... + @property + def status(self): ... + @property + def asg_type(self): ... + @property + def refcount(self): ... + @property + def usecount(self): ... + @property + def username(self) -> str: ... + @property + def domainname(self) -> str: ... + @property + def flags(self): ... + +class PyUrlCacheHANDLE: ... + +class PyWAVEFORMATEX: + @property + def wFormatTag(self) -> int: ... + @property + def nChannels(self) -> int: ... + @property + def nSamplesPerSec(self) -> int: ... + @property + def nAvgBytesPerSec(self) -> int: ... + @property + def nBlockAlign(self) -> int: ... + @property + def wBitsPerSample(self) -> int: ... + +class PyWINHTTP_AUTOPROXY_OPTIONS: ... +class PyWINHTTP_PROXY_INFO: ... + +class PyWKSTA_INFO_100: + @property + def platform_id(self): ... + @property + def computername(self) -> str: ... + @property + def langroup(self) -> str: ... + @property + def ver_major(self): ... + @property + def ver_minor(self): ... + +class PyWKSTA_INFO_101: + @property + def platform_id(self): ... + @property + def computername(self) -> str: ... + @property + def langroup(self) -> str: ... + @property + def ver_major(self): ... + @property + def ver_minor(self): ... + @property + def lanroot(self) -> str: ... + +class PyWKSTA_INFO_102: + @property + def platform_id(self): ... + @property + def computername(self) -> str: ... + @property + def langroup(self) -> str: ... + @property + def ver_major(self): ... + @property + def ver_minor(self): ... + @property + def lanroot(self) -> str: ... + @property + def logged_on_users(self): ... + +class PyWKSTA_INFO_302: + @property + def char_wait(self): ... + @property + def collection_time(self): ... + @property + def maximum_collection_count(self): ... + @property + def keep_conn(self): ... + @property + def keep_search(self): ... + @property + def max_cmds(self): ... + @property + def num_work_buf(self): ... + @property + def siz_work_buf(self): ... + @property + def max_wrk_cache(self): ... + @property + def siz_error(self): ... + @property + def num_alerts(self): ... + @property + def num_services(self): ... + @property + def errlog_sz(self): ... + @property + def print_buf_time(self): ... + @property + def num_char_buf(self): ... + @property + def siz_char_buf(self): ... + @property + def wrk_heuristics(self) -> str: ... + @property + def mailslots(self): ... + @property + def num_dgram_buf(self): ... + +class PyWKSTA_INFO_402: + @property + def char_wait(self): ... + @property + def collection_time(self): ... + @property + def maximum_collection_count(self) -> str: ... + @property + def keep_conn(self): ... + @property + def keep_search(self): ... + @property + def max_cmds(self): ... + @property + def num_work_buf(self): ... + @property + def siz_work_buf(self): ... + @property + def max_wrk_cache(self): ... + @property + def sess_timeout(self): ... + @property + def siz_error(self): ... + @property + def num_alerts(self): ... + @property + def num_services(self): ... + @property + def errlog_sz(self): ... + @property + def print_buf_time(self): ... + @property + def num_char_buf(self): ... + @property + def siz_char_buf(self): ... + @property + def mailslots(self): ... + @property + def num_dgram_buf(self): ... + @property + def max_threads(self): ... + +class PyWKSTA_INFO_502: + @property + def char_wait(self): ... + @property + def collection_time(self): ... + @property + def maximum_collection_count(self): ... + @property + def keep_conn(self): ... + @property + def max_cmds(self): ... + @property + def max_wrk_cache(self): ... + @property + def siz_char_buf(self): ... + @property + def lock_quota(self): ... + @property + def lock_increment(self): ... + @property + def lock_maximum(self): ... + @property + def pipe_increment(self): ... + @property + def pipe_maximum(self): ... + @property + def cache_file_timeout(self): ... + @property + def dormant_file_limit(self): ... + @property + def read_ahead_throughput(self): ... + @property + def num_mailslot_buffers(self): ... + @property + def num_srv_announce_buffers(self): ... + @property + def max_illegal_datagram_events(self): ... + @property + def illegal_datagram_event_reset_frequency(self): ... + @property + def log_election_packets(self): ... + @property + def use_opportunistic_locking(self): ... + @property + def use_unlock_behind(self): ... + @property + def use_close_behind(self): ... + @property + def buf_named_pipes(self): ... + @property + def use_lock_read_unlock(self): ... + @property + def utilize_nt_caching(self): ... + @property + def use_raw_read(self): ... + @property + def use_raw_write(self): ... + @property + def use_write_raw_data(self): ... + @property + def use_encryption(self): ... + @property + def buf_files_deny_write(self): ... + @property + def buf_read_only_files(self): ... + @property + def force_core_create_mode(self): ... + @property + def use_512_byte_max_transfer(self): ... + +class PyWKSTA_TRANSPORT_INFO_0: + @property + def quality_of_service(self): ... + @property + def number_of_vcs(self): ... + @property + def transport_name(self) -> str: ... + @property + def transport_address(self) -> str: ... + @property + def wan_ish(self): ... + +class PyWKSTA_USER_INFO_0: + @property + def username(self) -> str: ... + +class PyWKSTA_USER_INFO_1: + @property + def username(self) -> str: ... + @property + def logon_domain(self) -> str: ... + @property + def oth_domains(self) -> str: ... + @property + def logon_server(self) -> str: ... + +class PyWNDCLASS: + @property + def style(self) -> int: ... + @property + def cbWndExtra(self) -> int: ... + @property + def hInstance(self) -> int: ... + @property + def hIcon(self) -> int: ... + @property + def hCursor(self) -> int: ... + @property + def hbrBackground(self) -> int: ... + @property + def lpszMenuName(self) -> str: ... + @property + def lpszClassName(self) -> str: ... + @property + def lpfnWndProc(self): ... + def SetDialogProc(self) -> None: ... + +class PyXFORM: + @property + def M11(self) -> float: ... + @property + def M12(self) -> float: ... + @property + def M21(self) -> float: ... + @property + def M22(self) -> float: ... + @property + def Dx(self) -> float: ... + @property + def Dy(self) -> float: ... + +class Pymmapfile: + def close(self) -> None: ... + def find(self, needle, start, /): ... + def flush(self, offset: int = ..., size: int = ..., /) -> None: ... + def move(self, dest, src, count, /) -> None: ... + def read(self, num_bytes, /): ... + def read_byte(self): ... + def read_line(self): ... + def resize(self, MaximumSize, FileOffset: int = ..., NumberOfBytesToMap: int = ...) -> None: ... + def seek(self, dist: int, how: int = ..., /) -> None: ... + def size(self): ... + def tell(self): ... + def write(self, data, /) -> None: ... + def write_byte(self, char, /) -> None: ... + +class PyRASEAPUSERIDENTITY: + @property + def userName(self) -> str: ... + @property + def szUserName(self) -> str: ... + @property + def eapInfo(self) -> bytes: ... + @property + def pbEapInfo(self) -> bytes: ... + +class PyRASDIALEXTENSIONS: + @property + def dwfOptions(self) -> int: ... + @dwfOptions.setter + def dwfOptions(self, val: int) -> None: ... + + @property + def fOptions(self) -> int: ... + @fOptions.setter + def fOptions(self, val: int) -> None: ... + + @property + def hwndParent(self) -> int: ... + @hwndParent.setter + def hwndParent(self, val: int) -> None: ... + + @property + def reserved(self) -> int: ... + @reserved.setter + def reserved(self, val: int) -> None: ... + + @property + def reserved1(self) -> int: ... + @reserved1.setter + def reserved1(self, val: int) -> None: ... + + @property + def RasEapInfo(self): ... + @RasEapInfo.setter + def RasEapInfo(self, val: PyRASEAPUSERIDENTITY) -> None: ... + +class RASDIALPARAMS: ... + +class SC_ACTION: + @property + def Type(self): ... + @property + def Delay(self): ... + +class SERVICE_FAILURE_ACTIONS: + @property + def ResetPeriod(self): ... + @property + def RebootMsg(self) -> str: ... + @property + def Command(self) -> str: ... + @property + def Actions(self): ... + +class SERVICE_STATUS: + def __getitem__(self, i: int, /) -> int: ... + +class TRACKMOUSEEVENT: ... +class WIN32_FIND_DATA: ... + +class connection: + def setautocommit(self, c, /) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def cursor(self) -> None: ... + def close(self) -> None: ... + +class cursor: + def close(self) -> None: ... + def execute(self, sql: str, arg, /): ... + def fetchone(self): ... + def fetchmany(self) -> list[Incomplete]: ... + def fetchall(self) -> list[Incomplete]: ... + def setinputsizes(self) -> None: ... + def setoutputsize(self) -> None: ... + +class COMPONENT: + @property + def ID(self): ... + @property + def ComponentType(self): ... + @property + def Checked(self): ... + @property + def fDirty(self): ... + @property + def NoScroll(self): ... + @property + def Pos(self): ... + @property + def FriendlyName(self): ... + @property + def Source(self): ... + @property + def SubscribedURL(self): ... + @property + def CurItemState(self): ... + @property + def Original(self): ... + @property + def Restored(self): ... + @property + def Size(self): ... + +class COMPONENTSOPT: + @property + def EnableComponents(self): ... + @property + def ActiveDesktop(self): ... + @property + def Size(self): ... + +class COMPPOS: + @property + def Left(self): ... + @property + def Top(self): ... + @property + def Width(self): ... + @property + def Height(self): ... + @property + def Index(self): ... + @property + def CanResize(self): ... + @property + def CanResizeX(self): ... + @property + def CanResizeY(self): ... + @property + def PreferredLeftPercent(self): ... + @property + def PreferredTopPercent(self): ... + @property + def Size(self): ... + +class COMPSTATEINFO: + @property + def Left(self): ... + @property + def Top(self): ... + @property + def Width(self): ... + @property + def Height(self): ... + @property + def dwItemState(self): ... + @property + def Size(self): ... + +class DEFCONTENTMENU: ... +class ELEMDESC: ... + +class EXP_DARWIN_LINK: + @property + def Signature(self): ... + @property + def DarwinID(self): ... + @property + def wDarwinID(self): ... + @property + def Size(self): ... + +class EXP_SPECIAL_FOLDER: + @property + def Signature(self): ... + @property + def idSpecialFolder(self): ... + @property + def Offset(self): ... + @property + def Size(self): ... + +class EXP_SZ_LINK: + @property + def Signature(self): ... + @property + def Target(self): ... + @property + def wTarget(self): ... + @property + def Size(self): ... + +class FUNCDESC: + @property + def memid(self) -> int: ... + @property + def scodeArray(self) -> tuple[Incomplete, ...]: ... + @property + def args(self) -> tuple[ELEMDESC, ...]: ... + @property + def funckind(self): ... + @property + def invkind(self): ... + @property + def callconv(self): ... + @property + def cParamsOpt(self): ... + @property + def oVft(self): ... + @property + def rettype(self) -> ELEMDESC: ... + @property + def wFuncFlags(self): ... + +class IDLDESC: ... +class MAPIINIT_0: ... + +class NT_CONSOLE_PROPS: + @property + def Signature(self): ... + @property + def FillAttribute(self): ... + @property + def PopupFillAttribute(self): ... + @property + def ScreenBufferSize(self) -> tuple[Incomplete, Incomplete]: ... + @property + def WindowSize(self) -> tuple[Incomplete, Incomplete]: ... + @property + def WindowOrigin(self) -> tuple[Incomplete, Incomplete]: ... + @property + def nFont(self): ... + @property + def InputBufferSize(self): ... + @property + def FontSize(self) -> tuple[Incomplete, Incomplete]: ... + @property + def FontFamily(self): ... + @property + def FontWeight(self): ... + @property + def FaceName(self): ... + @property + def CursorSize(self): ... + @property + def FullScreen(self): ... + @property + def QuickEdit(self): ... + @property + def InsertMode(self): ... + @property + def AutoPosition(self): ... + @property + def HistoryBufferSize(self): ... + @property + def NumberOfHistoryBuffers(self): ... + @property + def HistoryNoDup(self): ... + @property + def ColorTable(self): ... + @property + def Size(self): ... + +class NT_FE_CONSOLE_PROPS: + @property + def Signature(self): ... + @property + def CodePage(self): ... + @property + def Size(self): ... + +class PROPSPEC: ... +class PyADSVALUE: ... + +class PyADS_ATTR_INFO: + @property + def AttrName(self): ... + @property + def ControlCode(self) -> int: ... + @property + def ADsType(self) -> int: ... + @property + def Values(self) -> list[Incomplete]: ... + +class PyADS_OBJECT_INFO: + @property + def RDN(self): ... + @property + def ObjectDN(self): ... + @property + def ParentDN(self): ... + @property + def ClassName(self): ... + +class PyADS_SEARCHPREF_INFO: ... + +class PyBIND_OPTS: + @property + def Flags(self): ... + @property + def Mode(self): ... + @property + def TickCountDeadline(self): ... + @property + def cbStruct(self): ... + +class PyCMINVOKECOMMANDINFO: ... + +@disjoint_base +class PyDSBCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwUnlockTransferRate(self) -> int: ... + @property + def dwBufferBytes(self): ... + @property + def dwPlayCpuOverhead(self): ... + +@disjoint_base +class PyDSBUFFERDESC: + @property + def dwFlags(self) -> int: ... + @property + def dwBufferBytes(self) -> int: ... + @property + def lpwfxFormat(self): ... + +@disjoint_base +class PyDSCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwMinSecondarySampleRate(self) -> int: ... + @property + def dwMaxSecondarySampleRate(self) -> int: ... + @property + def dwPrimaryBuffers(self) -> int: ... + @property + def dwMaxHwMixingAllBuffers(self) -> int: ... + @property + def dwMaxHwMixingStaticBuffers(self) -> int: ... + @property + def dwMaxHwMixingStreamingBuffers(self) -> int: ... + @property + def dwFreeHwMixingAllBuffers(self) -> int: ... + @property + def dwFreeHwMixingStaticBuffers(self) -> int: ... + @property + def dwFreeHwMixingStreamingBuffers(self) -> int: ... + @property + def dwMaxHw3DAllBuffers(self) -> int: ... + @property + def dwMaxHw3DStaticBuffers(self) -> int: ... + @property + def dwMaxHw3DStreamingBuffers(self) -> int: ... + @property + def dwFreeHw3DAllBuffers(self) -> int: ... + @property + def dwFreeHw3DStaticBuffers(self) -> int: ... + @property + def dwFreeHw3DStreamingBuffers(self) -> int: ... + @property + def dwTotalHwMemBytes(self) -> int: ... + @property + def dwFreeHwMemBytes(self) -> int: ... + @property + def dwMaxContigFreeHwMemBytes(self) -> int: ... + @property + def dwUnlockTransferRateHwBuffers(self) -> int: ... + @property + def dwPlayCpuOverheadSwBuffers(self) -> int: ... + +@disjoint_base +class PyDSCBCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwBufferBytes(self) -> int: ... + +@disjoint_base +class PyDSCBUFFERDESC: + @property + def dwFlags(self) -> int: ... + @property + def dwBufferBytes(self) -> int: ... + @property + def lpwfxFormat(self): ... + +@disjoint_base +class PyDSCCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwFormats(self) -> int: ... + @property + def dwChannels(self) -> int: ... + +class PyDSOP_FILTER_FLAGS: + @property + def uplevel(self) -> PyDSOP_UPLEVEL_FILTER_FLAGS: ... + @property + def downlevel(self): ... + +class PyDSOP_SCOPE_INIT_INFO: + @property + def type(self): ... + @property + def scope(self): ... + @property + def hr(self): ... + @property + def dcName(self) -> str: ... + @property + def filterFlags(self) -> PyDSOP_FILTER_FLAGS: ... + +@disjoint_base +class PyDSOP_SCOPE_INIT_INFOs: + def __new__(cls, size, /): ... + +class PyDSOP_UPLEVEL_FILTER_FLAGS: + @property + def bothModes(self): ... + @property + def mixedModeOnly(self): ... + @property + def nativeModeOnly(self): ... + +class PyFORMATETC: ... + +class PyGFileOperationProgressSink: + def StartOperations(self) -> None: ... + def FinishOperations(self, Result, /) -> None: ... + def PreRenameItem(self, Flags, Item: PyIShellItem, NewName, /) -> None: ... + def PostRenameItem(self, Flags, Item: PyIShellItem, NewName, hrRename, NewlyCreated: PyIShellItem, /) -> None: ... + def PreMoveItem(self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, /) -> None: ... + def PostMoveItem( + self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, hrMove, NewlyCreated: PyIShellItem, / + ) -> None: ... + def PreCopyItem(self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, /) -> None: ... + def PostCopyItem( + self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, hrCopy, NewlyCreated: PyIShellItem, / + ) -> None: ... + def PreDeleteItem(self, Flags, Item: PyIShellItem, /) -> None: ... + def PostDeleteItem(self, Flags, Item: PyIShellItem, hrDelete, NewlyCreated: PyIShellItem, /) -> None: ... + def PreNewItem(self, Flags, DestinationFolder: PyIShellItem, NewName, /) -> None: ... + def PostNewItem( + self, Flags, DestinationFolder: PyIShellItem, NewName, TemplateName, FileAttributes, hrNew, NewItem: PyIShellItem, / + ) -> None: ... + def UpdateProgress(self, WorkTotal, WorkSoFar, /) -> None: ... + def ResetTimer(self) -> None: ... + def PauseTimer(self) -> None: ... + def ResumeTimer(self) -> None: ... + +class PyGSecurityInformation: + def GetObjectInformation(self) -> SI_OBJECT_INFO: ... + def GetSecurity(self, RequestedInformation, Default, /) -> PySECURITY_DESCRIPTOR: ... + def SetSecurity(self, SecurityInformation, SecurityDescriptor: PySECURITY_DESCRIPTOR, /) -> None: ... + def GetAccessRights(self, ObjectType: PyIID, Flags, /) -> tuple[SI_ACCESS, Incomplete]: ... + def MapGeneric(self, ObjectType: PyIID, AceFlags, Mask, /): ... + def GetInheritTypes(self) -> tuple[SI_INHERIT_TYPE, ...]: ... + def PropertySheetPageCallback(self, hwnd: int, Msg, Page, /) -> None: ... + +class PyIADesktopP2: + def UpdateAllDesktopSubscriptions(self) -> None: ... + +class PyIADs: + @property + def ADsPath(self) -> str: ... + @property + def AdsPath(self) -> str: ... + @property + def Class(self) -> str: ... + @property + def GUID(self) -> str: ... + @property + def Name(self) -> str: ... + @property + def Parent(self) -> str: ... + @property + def Schema(self) -> str: ... + def GetInfo(self) -> None: ... + def SetInfo(self) -> None: ... + def Get(self, prop: str, /): ... + def Put(self, _property: str, val, /) -> None: ... + def get(self, prop: str, /): ... + def put(self, _property: str, val, /) -> None: ... + +class PyIADsContainer: + def GetObject(self, _class: str, relativeName: str, /) -> PyIDispatch: ... + def get_Count(self): ... + def get_Filter(self): ... + def put_Filter(self, val, /) -> None: ... + def get_Hints(self): ... + def put_Hints(self, val, /) -> None: ... + +class PyIADsUser: + def get_AccountDisabled(self): ... + def put_AccountDisabled(self, val, /) -> None: ... + def get_AccountExpirationDate(self): ... + def put_AccountExpirationDate(self, val: TimeType, /) -> None: ... + def get_BadLoginAddress(self): ... + def get_BadLoginCount(self): ... + def get_Department(self): ... + def put_Department(self, val, /) -> None: ... + def get_Description(self): ... + def put_Description(self, val, /) -> None: ... + def get_Division(self): ... + def put_Division(self, val, /) -> None: ... + def get_EmailAddress(self): ... + def put_EmailAddress(self, val, /) -> None: ... + def get_EmployeeID(self): ... + def put_EmployeeID(self, val, /) -> None: ... + def get_FirstName(self): ... + def put_FirstName(self, val, /) -> None: ... + def get_FullName(self): ... + def put_FullName(self, val, /) -> None: ... + def get_HomeDirectory(self): ... + def put_HomeDirectory(self, val, /) -> None: ... + def get_HomePage(self): ... + def put_HomePage(self, val, /) -> None: ... + def get_LoginScript(self): ... + def put_LoginScript(self, val, /) -> None: ... + def SetPassword(self, val, /) -> None: ... + def ChangePassword(self, oldval, newval, /) -> None: ... + +class PyIActiveDesktop: + def ApplyChanges(self, Flags, /) -> None: ... + def GetWallpaper(self, cchWallpaper, Reserved: int = ..., /): ... + def SetWallpaper(self, Wallpaper, Reserved: int = ..., /) -> None: ... + def GetWallpaperOptions(self, Reserved: int = ..., /): ... + def SetWallpaperOptions(self, Style, Reserved: int = ..., /) -> None: ... + def GetPattern(self, cchPattern: int = ..., Reserved: int = ..., /) -> None: ... + def SetPattern(self, Pattern, Reserved: int = ..., /) -> None: ... + def GetDesktopItemOptions(self): ... + def SetDesktopItemOptions(self, comp, Reserved: int = ..., /) -> None: ... + def AddDesktopItem(self, comp, Reserved: int = ..., /) -> None: ... + def AddDesktopItemWithUI(self, hwnd: int, comp, Flags, /) -> None: ... + def ModifyDesktopItem(self, comp, Flags, /) -> None: ... + def RemoveDesktopItem(self, comp, Reserved: int = ..., /) -> None: ... + def GetDesktopItemCount(self) -> None: ... + def GetDesktopItem(self, Component, Reserved: int = ..., /): ... + def GetDesktopItemByID(self, ID, reserved: int = ..., /): ... + def GenerateDesktopItemHtml(self, FileName, comp, Reserved: int = ..., /) -> None: ... + def AddUrl(self, hwnd: int, Source, comp, Flags, /) -> None: ... + def GetDesktopItemBySource(self, Source, Reserved: int = ..., /): ... + +class PyIActiveDesktopP: + def SetSafeMode(self, Flags, /) -> None: ... + +class PyIActiveScriptDebug: + def GetScriptTextAttributes(self, pstrCode: str, pstrDelimiter: str, dwFlags, /) -> tuple[Incomplete, ...]: ... + def GetScriptletTextAttributes(self, pstrCode: str, pstrDelimiter: str, dwFlags, /) -> None: ... + def EnumCodeContextsOfPosition(self, dwSourceContext, uCharacterOffset, uNumChars, /) -> None: ... + +class PyIActiveScriptError: + def GetExceptionInfo(self) -> None: ... + def GetSourcePosition(self) -> None: ... + def GetSourceLineText(self) -> None: ... + +class PyIActiveScriptErrorDebug: + def GetDocumentContext(self) -> None: ... + def GetStackFrame(self) -> None: ... + +class PyIActiveScriptParseProcedure: + def ParseProcedureText( + self, + pstrCode, + pstrFormalParams, + pstrProcedureName, + pstrItemName, + punkContext: PyIUnknown, + pstrDelimiter, + dwSourceContextCookie, + ulStartingLineNumber, + dwFlags, + /, + ) -> None: ... + +class PyIActiveScriptSite: + def GetLCID(self): ... + def GetItemInfo(self): ... + def GetDocVersionString(self): ... + def OnStateChange(self): ... + def OnEnterScript(self): ... + def OnLeaveScript(self): ... + def OnScriptError(self): ... + def OnScriptTerminate(self): ... + +class PyIActiveScriptSiteDebug: + def GetDocumentContextFromPosition(self, dwSourceContext, uCharacterOffset, uNumChars, /) -> None: ... + def GetApplication(self) -> None: ... + def GetRootApplicationNode(self) -> None: ... + def OnScriptErrorDebug(self) -> tuple[Incomplete, Incomplete]: ... + +class PyIAddrBook: + def ResolveName(self, uiParm, flags, entryTitle: str, ADRlist, /) -> None: ... + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def CompareEntryIDs(self, entryId: str, entryId1: str, flags: int = ..., /): ... + +class PyIApplicationDebugger: + def QueryAlive(self) -> None: ... + def CreateInstanceAtDebugger(self, rclsid: PyIID, pUnkOuter: PyIUnknown, dwClsContext, riid: PyIID, /) -> None: ... + def onDebugOutput(self, pstr, /) -> None: ... + def onHandleBreakPoint(self, prpt: PyIRemoteDebugApplicationThread, br, pError, /) -> None: ... + def onClose(self) -> None: ... + def onDebuggerEvent(self, guid: PyIID, uUnknown: PyIUnknown, /) -> None: ... + +class PyIApplicationDestinations: + def SetAppID(self, AppID, /) -> None: ... + def RemoveDestination(self, punk: PyIUnknown, /) -> None: ... + def RemoveAllDestinations(self) -> None: ... + +class PyIApplicationDocumentlists: + def SetAppID(self, AppID, /) -> None: ... + def Getlist(self, listType, riid: PyIID, ItemsDesired: int = ..., /) -> PyIEnumObjects: ... + +class PyIAsyncOperation: + def SetAsyncMode(self, fDoOpAsync, /) -> None: ... + def GetAsyncMode(self): ... + def StartOperation(self, pbcReserved: PyIBindCtx, /) -> None: ... + def InOperation(self) -> None: ... + def EndOperation(self, hResult, pbcReserved: PyIBindCtx, dwEffects, /) -> None: ... + +class PyIAttach: + def GetLastError(self, hr, flags, /): ... + +class PyIBindCtx: + def GetRunningObjectTable(self) -> PyIRunningObjectTable: ... + def GetBindOptions(self) -> PyBIND_OPTS: ... + def SetBindOptions(self, bindopts, /) -> None: ... + def RegisterObjectParam(self, Key: str, punk: PyIUnknown, /) -> None: ... + def RevokeObjectParam(self, Key: str, /) -> None: ... + def GetObjectParam(self, Key: str, /) -> PyIUnknown: ... + def EnumObjectParam(self) -> PyIEnumString: ... + +class PyIBrowserFrameOptions: + def GetFrameOptions(self, dwMask, /) -> None: ... + +class PyICancelMethodCalls: + def Cancel(self, Seconds, /) -> None: ... + def TestCancel(self): ... + +class PyICatInformation: + def EnumCategories(self, lcid: int = ..., /) -> PyIEnumCATEGORYINFO: ... + def GetCategoryDesc(self, lcid: int = ..., /) -> str: ... + def EnumClassesOfCategories( + self, listIIdImplemented: list[PyIID] | None = ..., listIIdRequired: Incomplete | None = ..., / + ) -> PyIEnumGUID: ... + +class PyICatRegister: + def RegisterCategories(self, arg: list[tuple[PyIID, Incomplete, str]], /) -> None: ... + def UnRegisterCategories(self, arg: list[PyIID], /) -> None: ... + def RegisterClassImplCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + def UnRegisterClassImplCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + def RegisterClassReqCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + def UnRegisterClassReqCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + +class PyICategoryProvider: + def CanCategorizeOnSCID(self, pscid, /) -> None: ... + def GetDefaultCategory(self) -> None: ... + def GetCategoryForSCID(self, pscid, /) -> None: ... + def EnumCategories(self) -> None: ... + def GetCategoryName(self, guid: PyIID, /) -> None: ... + def CreateCategory(self, guid: PyIID, riid: PyIID, /) -> None: ... + +class PyIClassFactory: + def CreateInstance(self, outerUnknown: PyIUnknown, iid: PyIID, /) -> PyIUnknown: ... + def LockServer(self, bInc, /) -> None: ... + +class PyIClientSecurity: + def QueryBlanket(self, Proxy: PyIUnknown, /): ... + def SetBlanket( + self, Proxy: PyIUnknown, AuthnSvc, AuthzSvc, ServerPrincipalName: str, AuthnLevel, ImpLevel, AuthInfo, Capabilities, / + ) -> None: ... + def CopyProxy(self, Proxy: PyIUnknown, /) -> PyIUnknown: ... + +class PyIColumnProvider: + def Initialize(self, psci, /) -> None: ... + def GetColumnInfo(self, dwIndex, /) -> None: ... + def GetItemData(self, pscid, pscd, /) -> None: ... + +class PyIConnectionPoint: + def GetConnectionInterface(self) -> PyIID: ... + def GetConnectionPointContainer(self) -> PyIConnectionPointContainer: ... + def Advise(self, unk: PyIUnknown, /): ... + def Unadvise(self, cookie, /) -> None: ... + def EnumConnections(self) -> PyIEnumConnections: ... + +class PyIConnectionPointContainer: + def EnumConnectionPoints(self) -> PyIEnumConnectionPoints: ... + def FindConnectionPoint(self, iid: PyIID, /) -> PyIConnectionPoint: ... + +class PyIContext: + def SetProperty(self, rpolicyId: PyIID, flags, pUnk: PyIUnknown, /) -> None: ... + def RemoveProperty(self, rPolicyId: PyIID, /) -> None: ... + def GetProperty(self, rGuid: PyIID, /) -> tuple[Incomplete, PyIUnknown]: ... + def EnumContextProps(self) -> PyIEnumContextProps: ... + +class PyIContextMenu: + def QueryContextMenu(self, hmenu: int, indexMenu, idCmdFirst, idCmdLast, uFlags, /): ... + def InvokeCommand(self, pici: PyCMINVOKECOMMANDINFO, /) -> None: ... + def GetCommandString(self, idCmd, uType, cchMax: int = ..., /): ... + +class PyICopyHookA: + def CopyCallback(self, hwnd: int, wFunc, wFlags, srcFile: str, srcAttribs, destFile: str, destAttribs, /) -> None: ... + +class PyICopyHookW: + def CopyCallback(self, hwnd: int, wFunc, wFlags, srcFile: str, srcAttribs, destFile: str, destAttribs, /) -> None: ... + +class PyICreateTypeInfo: + def SetGuid(self, guid: PyIID, /) -> None: ... + def SetTypeFlags(self, uTypeFlags, /) -> None: ... + def SetDocString(self, pStrDoc, /) -> None: ... + def SetHelpContext(self, dwHelpContext, /) -> None: ... + def SetVersion(self, wMajorVerNum, wMinorVerNum, /) -> None: ... + def AddRefTypeInfo(self, pTInfo: PyITypeInfo, /) -> None: ... + def AddFuncDesc(self, index, /) -> None: ... + def AddImplType(self, index, hRefType, /) -> None: ... + def SetImplTypeFlags(self, index, implTypeFlags, /) -> None: ... + def SetAlignment(self, cbAlignment, /) -> None: ... + def SetSchema(self, pStrSchema, /) -> None: ... + def AddVarDesc(self, index, /) -> None: ... + def SetFuncAndParamNames(self, index, rgszNames: tuple[Incomplete, ...], /) -> None: ... + def SetVarName(self, index, szName, /) -> None: ... + def SetTypeDescAlias(self) -> None: ... + def DefineFuncAsDllEntry(self, index, szDllName, szProcName, /) -> None: ... + def SetFuncDocString(self, index, szDocString, /) -> None: ... + def SetVarDocString(self, index, szDocString, /) -> None: ... + def SetFuncHelpContext(self, index, dwHelpContext, /) -> None: ... + def SetVarHelpContext(self, index, dwHelpContext, /) -> None: ... + def SetMops(self, index, bstrMops, /) -> None: ... + def LayOut(self) -> None: ... + +class PyICreateTypeLib: + def CreateTypeInfo(self, szName, /) -> None: ... + def SetName(self, szName, /) -> None: ... + def SetVersion(self, wMajorVerNum, wMinorVerNum, /) -> None: ... + def SetGuid(self, guid: PyIID, /) -> None: ... + def SetDocString(self, szDoc, /) -> None: ... + def SetHelpFileName(self, szHelpFileName, /) -> None: ... + def SetHelpContext(self, dwHelpContext, /) -> None: ... + def SetLcid(self) -> None: ... + def SetLibFlags(self, uLibFlags, /) -> None: ... + def SaveAllChanges(self) -> None: ... + +class PyICreateTypeLib2: + def CreateTypeInfo(self, szName, /) -> None: ... + def SetName(self, szName, /) -> None: ... + def SetVersion(self, wMajorVerNum, wMinorVerNum, /) -> None: ... + def SetGuid(self, guid: PyIID, /) -> None: ... + def SetDocString(self, szDoc, /) -> None: ... + def SetHelpFileName(self, szHelpFileName, /) -> None: ... + def SetHelpContext(self, dwHelpContext, /) -> None: ... + def SetLcid(self) -> None: ... + def SetLibFlags(self, uLibFlags, /) -> None: ... + def SaveAllChanges(self) -> None: ... + +class PyICurrentItem: ... + +class PyICustomDestinationlist: + def SetAppID(self, AppID, /) -> None: ... + def Beginlist(self, riid: PyIID, /) -> tuple[Incomplete, PyIObjectArray]: ... + def AppendCategory(self, Category, Items: PyIObjectArray, /) -> None: ... + def AppendKnownCategory(self, Category, /) -> None: ... + def AddUserTasks(self, Items: PyIObjectArray, /) -> None: ... + def Commitlist(self) -> None: ... + def GetRemovedDestinations(self, riid: PyIID, /) -> PyIObjectArray: ... + def Deletelist(self, AppID: Incomplete | None = ..., /) -> None: ... + def Abortlist(self) -> None: ... + +class PyIDL: ... + +class PyIDataObject: + def GetData(self, pformatetcIn: PyFORMATETC, /) -> PySTGMEDIUM: ... + def GetDataHere(self, pformatetcIn: PyFORMATETC, /) -> PySTGMEDIUM: ... + def QueryGetData(self, pformatetc: PyFORMATETC, /) -> None: ... + def GetCanonicalFormatEtc(self, pformatectIn: PyFORMATETC, /) -> PyFORMATETC: ... + def SetData(self, pformatetc: PyFORMATETC, pmedium: PySTGMEDIUM, fRelease, /) -> None: ... + def EnumFormatEtc(self, dwDirection, /) -> PyIEnumFORMATETC: ... + def DAdvise(self, pformatetc: PyFORMATETC, advf, pAdvSink, /): ... + def DUnadvise(self, dwConnection, /) -> None: ... + def EnumDAdvise(self): ... + +class PyIDebugApplication: + def SetName(self, pstrName, /) -> None: ... + def StepOutComplete(self) -> None: ... + def DebugOutput(self, pstr, /) -> None: ... + def StartDebugSession(self) -> None: ... + def HandleBreakPoint(self, br, /): ... + def Close(self) -> None: ... + def GetBreakFlags(self): ... + def GetCurrentThread(self) -> PyIDebugApplicationThread: ... + def CreateAsyncDebugOperation(self, psdo: PyIDebugSyncOperation, /) -> None: ... + def AddStackFrameSniffer(self, pdsfs: PyIDebugStackFrameSniffer, /): ... + def RemoveStackFrameSniffer(self, dwCookie, /) -> None: ... + def QueryCurrentThreadIsDebuggerThread(self) -> None: ... + def SynchronousCallInDebuggerThread(self, pptc, dwParam1, dwParam2, dwParam3, /) -> None: ... + def CreateApplicationNode(self) -> PyIDebugApplicationNode: ... + def FireDebuggerEvent(self, guid, unknown: PyIUnknown, /) -> None: ... + def HandleRuntimeError(self, pErrorDebug: PyIActiveScriptErrorDebug, pScriptSite: PyIActiveScriptSite, /) -> None: ... + def FCanJitDebug(self) -> None: ... + def FIsAutoJitDebugEnabled(self) -> None: ... + def AddGlobalExpressionContextProvider(self, pdsfs: PyIProvideExpressionContexts, /) -> None: ... + def RemoveGlobalExpressionContextProvider(self, dwCookie, /) -> None: ... + +class PyIDebugApplicationNode: + def EnumChildren(self) -> None: ... + def GetParent(self) -> PyIDebugApplicationNode: ... + def SetDocumentProvider(self, pddp: PyIDebugDocumentProvider, /) -> None: ... + def Close(self) -> None: ... + def Attach(self, pdanParent: PyIDebugApplicationNode, /) -> None: ... + def Detach(self) -> None: ... + +class PyIDebugApplicationNodeEvents: + def onAddChild(self, prddpChild: PyIDebugApplicationNode, /) -> None: ... + def onRemoveChild(self, prddpChild: PyIDebugApplicationNode, /) -> None: ... + def onDetach(self) -> None: ... + def onAttach(self, prddpParent: PyIDebugApplicationNode, /) -> None: ... + +class PyIDebugApplicationThread: + def SynchronousCallIntoThread(self, pstcb, dwParam1, dwParam2, dwParam3, /) -> None: ... + def QueryIsCurrentThread(self) -> None: ... + def QueryIsDebuggerThread(self) -> None: ... + +class PyIDebugCodeContext: + def GetDocumentContext(self) -> None: ... + def SetBreakPoint(self, bps, /) -> None: ... + +class PyIDebugDocument: ... + +class PyIDebugDocumentContext: + def GetDocument(self) -> None: ... + def EnumCodeContexts(self) -> None: ... + +class PyIDebugDocumentHelper: + def Init(self, pda: PyIDebugApplication, pszShortName, pszLongName, docAttr, /) -> None: ... + def Attach(self, pddhParent: PyIDebugDocumentHelper, /) -> None: ... + def Detach(self) -> None: ... + def AddUnicodeText(self, pszText, /) -> None: ... + def AddDBCSText(self) -> None: ... + def SetDebugDocumentHost(self, pddh: PyIDebugDocumentHost, /) -> None: ... + def AddDeferredText(self, cChars, dwTextStartCookie, /) -> None: ... + def DefineScriptBlock(self, ulCharOffset, cChars, pas, fScriptlet, /) -> None: ... + def SetDefaultTextAttr(self, staTextAttr, /) -> None: ... + def SetTextAttributes(self, ulCharOffset, obAttr, /) -> None: ... + def SetLongName(self, pszLongName, /) -> None: ... + def SetShortName(self, pszShortName, /) -> None: ... + def SetDocumentAttr(self, pszAttributes, /) -> None: ... + def GetDebugApplicationNode(self) -> None: ... + def GetScriptBlockInfo(self, dwSourceContext, /) -> None: ... + def CreateDebugDocumentContext(self, iCharPos, cChars, /) -> None: ... + def BringDocumentToTop(self) -> None: ... + def BringDocumentContextToTop(self, pddc: PyIDebugDocumentContext, /) -> None: ... + +class PyIDebugDocumentHost: + def GetDeferredText(self, dwTextStartCookie, cMaxChars, /) -> None: ... + def GetScriptTextAttributes(self, pstrCode, pstrDelimiter, dwFlags, /) -> None: ... + def OnCreateDocumentContext(self) -> None: ... + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class PyIDebugDocumentInfo: + def GetName(self) -> None: ... + def GetDocumentClassId(self) -> PyIID: ... + +class PyIDebugDocumentProvider: + def GetDocument(self) -> PyIDebugDocument: ... + +class PyIDebugDocumentText: + def GetDocumentAttributes(self) -> None: ... + def GetSize(self) -> None: ... + def GetPositionOfLine(self, cLineNumber, /) -> None: ... + def GetLineOfPosition(self, cCharacterPosition, /) -> None: ... + def GetText(self, cCharacterPosition, cMaxChars, bWantAttr: int = ..., /) -> None: ... + def GetPositionOfContext(self, psc: PyIDebugDocumentContext, /) -> None: ... + def GetContextOfPosition(self, cCharacterPosition, cNumChars, /) -> None: ... + +class PyIDebugDocumentTextAuthor: + def InsertText(self, cCharacterPosition, cNumToInsert, pcharText, /) -> None: ... + def RemoveText(self, cCharacterPosition, cNumToRemove, /) -> None: ... + def ReplaceText(self, cCharacterPosition, cNumToReplace, pcharText, /) -> None: ... + +class PyIDebugDocumentTextEvents: + def onDestroy(self) -> None: ... + def onInsertText(self, cCharacterPosition, cNumToInsert, /) -> None: ... + def onRemoveText(self, cCharacterPosition, cNumToRemove, /) -> None: ... + def onReplaceText(self, cCharacterPosition, cNumToReplace, /) -> None: ... + def onUpdateTextAttributes(self, cCharacterPosition, cNumToUpdate, /) -> None: ... + def onUpdateDocumentAttributes(self, textdocattr, /) -> None: ... + +class PyIDebugDocumentTextExternalAuthor: + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class PyIDebugExpression: + def Start(self, pdecb: PyIDebugExpressionCallBack, /) -> None: ... + def Abort(self) -> None: ... + def QueryIsComplete(self) -> None: ... + def GetResultAsString(self) -> None: ... + def GetResultAsDebugProperties(self) -> None: ... + +class PyIDebugExpressionCallBack: + def onComplete(self) -> None: ... + +class PyIDebugExpressionContext: + def ParseLanguageText(self, pstrCode, nRadix, pstrDelimiter, dwFlags, /) -> None: ... + def GetLanguageInfo(self) -> None: ... + +class PyIDebugProperty: + def GetPropertyInfo(self, dwFieldSpec, nRadix, /) -> None: ... + def GetExtendedInfo(self) -> None: ... + def SetValueAsString(self, pszValue, nRadix, /) -> None: ... + def EnumMembers(self, dwFieldSpec, nRadix, refiid: PyIID, /) -> None: ... + def GetParent(self) -> None: ... + +class PyIDebugSessionProvider: + def StartDebugSession(self, pda: PyIRemoteDebugApplication, /) -> None: ... + +class PyIDebugStackFrame: + def GetCodeContext(self) -> None: ... + def GetDescriptionString(self, fLong, /): ... + def GetLanguageString(self, fLong, /): ... + def GetThread(self) -> PyIDebugApplicationThread: ... + +class PyIDebugStackFrameSniffer: + def EnumStackFrames(self) -> None: ... + +class PyIDebugStackFrameSnifferEx: + def EnumStackFramesEx(self) -> None: ... + +class PyIDebugSyncOperation: + def GetTargetThread(self) -> None: ... + def Execute(self) -> None: ... + def InProgressAbort(self) -> None: ... + +class PyIDefaultExtractIconInit: + def SetFlags(self, uFlags, /) -> None: ... + def SetKey(self, hkey: PyHKEY, /) -> None: ... + def SetNormalIcon(self, pszFile, iIcon, /) -> None: ... + def SetOpenIcon(self, pszFile, iIcon, /) -> None: ... + def SetShortcutIcon(self, pszFile, iIcon, /) -> None: ... + def SetDefaultIcon(self, pszFile, iIcon, /) -> None: ... + +class PyIDirectSound: + def Initialize(self, guid: PyIID, /) -> None: ... + def SetCooperativeLevel(self, hwnd: int, level, /) -> None: ... + def CreateSoundBuffer(self, lpDSCBufferDesc: PyDSCBUFFERDESC, unk: Incomplete | None = ..., /) -> None: ... + def GetCaps(self) -> None: ... + def Compact(self) -> None: ... + +class PyIDirectSoundBuffer: + def Initialize(self) -> None: ... + def GetStatus(self) -> None: ... + def GetCaps(self) -> None: ... + def Restore(self) -> None: ... + def GetCurrentPosition(self) -> None: ... + def Play(self) -> None: ... + def SetCurrentPosition(self) -> None: ... + def Stop(self) -> None: ... + def GetFrequency(self) -> None: ... + def GetPan(self) -> None: ... + def GetVolume(self) -> None: ... + def SetFrequency(self) -> None: ... + def SetPan(self) -> None: ... + def SetVolume(self) -> None: ... + +class PyIDirectSoundCapture: + def Initialize(self) -> None: ... + def GetCaps(self) -> None: ... + +class PyIDirectSoundCaptureBuffer: + def Initialize(self) -> None: ... + def GetStatus(self) -> None: ... + def GetCurrentPosition(self) -> None: ... + def Stop(self) -> None: ... + +class PyIDirectSoundNotify: ... + +class PyIDirectoryObject: + def GetObjectInformation(self) -> PyADS_OBJECT_INFO: ... + def GetObjectAttributes(self, names: tuple[str, ...], /) -> tuple[PyADS_ATTR_INFO, ...]: ... + def SetObjectAttributes(self, attrs: tuple[PyADS_ATTR_INFO, ...], /): ... + def CreateDSObject(self, rdn: str, attrs: tuple[PyADS_ATTR_INFO, ...], /) -> PyIDispatch: ... + def DeleteDSObject(self, rdn: str, /) -> None: ... + +class PyIDirectorySearch: + def SetSearchPreference(self, prefs, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def ExecuteSearch(self, _filter: str, attrNames: list[str], /): ... + def GetNextRow(self, handle, /): ... + def GetFirstRow(self, handle, /): ... + def GetPreviousRow(self, handle, /): ... + def CloseSearchHandle(self, handle, /) -> None: ... + def AdandonSearch(self, handle, /) -> None: ... + def GetColumn(self, handle, name: str, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetNextColumnName(self) -> None: ... + +@final +class PyIDispatch: + def Invoke(self, dispid, lcid, flags, bResultWanted, arg: tuple[Incomplete, ...], /): ... + def InvokeTypes( + self, dispid, lcid, wFlags, resultTypeDesc, typeDescs: tuple[Incomplete, ...], args: tuple[Incomplete, ...], / + ): ... + def GetIDsOfNames(self, name: str, arg, /) -> tuple[Incomplete, Incomplete]: ... + def GetTypeInfo(self, locale, index: int = ..., /) -> PyITypeInfo: ... + def GetTypeInfoCount(self): ... + +class PyIDispatchEx: + def GetDispID(self, name: str, fdex, /): ... + def InvokeEx( + self, + dispid, + lcid, + flags, + args: list[Incomplete], + types: list[Incomplete] | None = ..., + returnDesc: int = ..., + serviceProvider: PyIServiceProvider | None = ..., + /, + ): ... + def DeleteMemberByName(self, name: str, fdex, /) -> None: ... + def DeleteMemberByDispID(self, dispid, /) -> None: ... + def GetMemberProperties(self, dispid, fdex, /): ... + def GetMemberName(self, dispid, /): ... + def GetNextDispID(self, fdex, dispid, /): ... + +class PyIDisplayItem: ... + +class PyIDocHostUIHandler: + def ShowContextMenu( + self, dwID, pt: tuple[Incomplete, Incomplete], pcmdtReserved: PyIUnknown, pdispReserved: PyIDispatch, / + ) -> None: ... + def GetHostInfo(self) -> None: ... + def ShowUI( + self, + dwID, + pActiveObject: PyIOleInPlaceActiveObject, + pCommandTarget: PyIOleCommandTarget, + pFrame: PyIOleInPlaceFrame, + pDoc: PyIOleInPlaceUIWindow, + /, + ) -> None: ... + def HideUI(self) -> None: ... + def UpdateUI(self) -> None: ... + def EnableModeless(self, fEnable, /) -> None: ... + def OnDocWindowActivate(self, fActivate, /) -> None: ... + def OnFrameWindowActivate(self, fActivate, /) -> None: ... + def ResizeBorder( + self, prcBorder: tuple[Incomplete, Incomplete, Incomplete, Incomplete], pUIWindow: PyIOleInPlaceUIWindow, fRameWindow, / + ) -> None: ... + def TranslateAccelerator(self, lpMsg, pguidCmdGroup: PyIID, nCmdID, /) -> None: ... + def GetOptionKeyPath(self, dw, /) -> None: ... + def GetDropTarget(self, pDropTarget: PyIDropTarget, /) -> None: ... + def GetExternal(self) -> None: ... + def TranslateUrl(self, dwTranslate, pchURLIn, /) -> None: ... + def FilterDataObject(self, pDO: PyIDataObject, /) -> None: ... + +class PyIDropSource: + def QueryContinueDrag(self, fEscapePressed, grfKeyState, /) -> None: ... + def GiveFeedback(self, dwEffect, /) -> None: ... + +class PyIDropTarget: + def DragEnter(self, pDataObj: PyIDataObject, grfKeyState, pt: tuple[Incomplete, Incomplete], pdwEffect, /): ... + def DragOver(self, grfKeyState, pt: tuple[Incomplete, Incomplete], pdwEffect, /): ... + def DragLeave(self) -> None: ... + def Drop(self, pDataObj: PyIDataObject, grfKeyState, pt: tuple[Incomplete, Incomplete], dwEffect, /): ... + +class PyIDropTargetHelper: + def DragEnter(self, hwnd: int, pDataObj: PyIDataObject, pt: tuple[Incomplete, Incomplete], dwEffect, /) -> None: ... + def DragOver(self, hwnd: int, pt: tuple[Incomplete, Incomplete], pdwEffect, /) -> None: ... + def DragLeave(self) -> None: ... + def Drop(self, pDataObj: PyIDataObject, pt: tuple[Incomplete, Incomplete], dwEffect, /) -> None: ... + +class PyIDsObjectPicker: + def Initialize( + self, targetComputer: str, scopeInfos: PyDSOP_SCOPE_INIT_INFOs, options: int = ..., attrNames: list[str] | None = ..., / + ) -> None: ... + def InvokeDialog(self, hwnd: int, /) -> PyIDataObject: ... + +class PyIEmptyVolumeCache: ... +class PyIEmptyVolumeCache2: ... + +class PyIEmptyVolumeCacheCallBack: + def ScanProgress(self, dwlSpaceUsed, dwFlags, pcwszStatus, /) -> None: ... + def PurgeProgress(self, dwlSpaceFreed, spaceFreed, spaceToFree, flags, status, /) -> None: ... + +class PyIEnumCATEGORYINFO: + def Next(self, num: int = ..., /) -> tuple[tuple[PyIID, Incomplete, str], ...]: ... + def Skip(self, num, /) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumCATEGORYINFO: ... + +class PyIEnumConnectionPoints: + def Next(self, num: int = ..., /) -> tuple[PyIConnectionPoint, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumConnectionPoints: ... + +class PyIEnumConnections: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumConnections: ... + +class PyIEnumContextProps: + def Next(self, num: int = ..., /) -> tuple[tuple[PyIID, Incomplete, PyIUnknown], ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumContextProps: ... + +class PyIEnumDebugApplicationNodes: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugApplicationNodes: ... + +class PyIEnumDebugCodeContexts: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugCodeContexts: ... + +class PyIEnumDebugExpressionContexts: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugExpressionContexts: ... + +class PyIEnumDebugPropertyInfo: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugPropertyInfo: ... + def GetCount(self): ... + +class PyIEnumDebugStackFrames: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugStackFrames: ... + +class PyIEnumExplorerCommand: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumExplorerCommand: ... + +class PyIEnumFORMATETC: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumFORMATETC: ... + +class PyIEnumGUID: + def Next(self, num: int = ..., /) -> tuple[PyIID, ...]: ... + def Skip(self, num, /) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumGUID: ... + +class PyIEnumIDlist: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumIDlist: ... + +class PyIEnumMoniker: + def Next(self, num: int = ..., /) -> PyIMoniker: ... + def Skip(self, num, /) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumMoniker: ... + +class PyIEnumObjects: + def Next(self, riid: PyIID, num: int = ..., /) -> tuple[PyIUnknown, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumObjects: ... + +class PyIEnumRemoteDebugApplicationThreads: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumRemoteDebugApplicationThreads: ... + +class PyIEnumRemoteDebugApplications: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumRemoteDebugApplications: ... + +class PyIEnumResources: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumResources: ... + +class PyIEnumSTATPROPSETSTG: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumSTATPROPSETSTG: ... + +class PyIEnumSTATPROPSTG: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumSTATPROPSTG: ... + +class PyIEnumSTATSTG: + def Next(self, num: int = ..., /) -> tuple[STATSTG, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumSTATSTG: ... + +class PyIEnumShellItems: + def Next(self, num: int = ..., /) -> tuple[PyIShellItem, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumShellItems: ... + +class PyIEnumString: + def Next(self, num: int = ..., /) -> tuple[str, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumString: ... + +class PyIErrorLog: + def AddError(self, propName: str, excepInfo: Incomplete | None = ..., /) -> None: ... + +class PyIExplorerBrowser: + def Initialize(self, hwndParent, prc: PyRECT, pfs, /) -> None: ... + def Destroy(self) -> None: ... + def SetRect(self, hdwp, rcBrowser: PyRECT, /) -> int: ... + def SetPropertyBag(self, PropertyBag, /) -> None: ... + def SetEmptyText(self, EmptyText, /) -> None: ... + def SetFolderSettings(self, pfs, /) -> None: ... + def Advise(self, psbe: PyIExplorerBrowserEvents, /): ... + def Unadvise(self, dwCookie, /) -> None: ... + def SetOptions(self, dwFlag, /) -> None: ... + def GetOptions(self): ... + def BrowseToIDlist(self, pidl, uFlags, /) -> None: ... + def BrowseToObject(self, punk: PyIUnknown, uFlags, /) -> None: ... + def FillFromObject(self, punk: PyIUnknown, dwFlags, /) -> None: ... + def RemoveAll(self) -> None: ... + def GetCurrentView(self, riid: PyIID, /) -> PyIUnknown: ... + +class PyIExplorerBrowserEvents: + def OnNavigationPending(self, pidlFolder, /) -> None: ... + def OnViewCreated(self, psv: PyIShellView, /) -> None: ... + def OnNavigationComplete(self, pidlFolder, /) -> None: ... + def OnNavigationFailed(self, pidlFolder, /) -> None: ... + +class PyIExplorerCommand: + def GetTitle(self, psiItemArray: PyIShellItemArray, /): ... + def GetIcon(self, psiItemArray: PyIShellItemArray, /): ... + def GetToolTip(self, psiItemArray: PyIShellItemArray, /): ... + def GetCanonicalName(self) -> PyIID: ... + def GetState(self, psiItemArray: PyIShellItemArray, fOkToBeSlow, /): ... + def Invoke(self, psiItemArray: PyIShellItemArray, pbc: PyIBindCtx, /) -> None: ... + def GetFlags(self): ... + def EnumSubCommands(self) -> PyIEnumExplorerCommand: ... + +class PyIExplorerCommandProvider: ... +class PyIExplorerPaneVisibility: ... + +class PyIExternalConnection: + def AddConnection(self, extconn, reserved: int = ..., /): ... + def ReleaseConnection(self, extconn, reserved, fLastReleaseCloses, /): ... + +class PyIExtractIcon: + def Extract(self, pszFile, nIconIndex, nIconSize, /) -> None: ... + def GetIconLocation(self, uFlags, cchMax, /) -> None: ... + +class PyIExtractIconW: + def Extract(self, pszFile, nIconIndex, nIconSize, /) -> None: ... + def GetIconLocation(self, uFlags, cchMax, /) -> None: ... + +class PyIExtractImage: + def GetLocation(self, dwPriority, size: tuple[Incomplete, Incomplete], dwRecClrDepth, pdwFlags, /) -> None: ... + def Extract(self) -> None: ... + +class PyIFileOperation: + def Advise(self, Sink: PyGFileOperationProgressSink, /): ... + def Unadvise(self, Cookie, /) -> None: ... + def SetOperationFlags(self, OperationFlags, /) -> None: ... + def SetProgressMessage(self, Message, /) -> None: ... + def SetProgressDialog(self, popd, /) -> None: ... + def SetProperties(self, proparray: PyIPropertyChangeArray, /) -> None: ... + def SetOwnerWindow(self, Owner: int, /) -> None: ... + def ApplyPropertiesToItem(self, Item: PyIShellItem, /) -> None: ... + def ApplyPropertiesToItems(self, Items: PyIUnknown, /) -> None: ... + def RenameItem(self, Item: PyIShellItem, NewName, Sink: PyGFileOperationProgressSink | None = ..., /) -> None: ... + def RenameItems(self, pUnkItems: PyIUnknown, NewName, /) -> None: ... + def MoveItem( + self, + Item: PyIShellItem, + DestinationFolder: PyIShellItem, + pszNewName: Incomplete | None = ..., + Sink: PyGFileOperationProgressSink | None = ..., + /, + ) -> None: ... + def MoveItems(self, Items: PyIUnknown, DestinationFolder: PyIShellItem, /) -> None: ... + def CopyItem( + self, + Item: PyIShellItem, + DestinationFolder: PyIShellItem, + CopyName: Incomplete | None = ..., + Sink: PyGFileOperationProgressSink | None = ..., + /, + ) -> None: ... + def CopyItems(self, Items: PyIUnknown, DestinationFolder: PyIShellItem, /) -> None: ... + def DeleteItem(self, Item: PyIShellItem, Sink: PyGFileOperationProgressSink | None = ..., /) -> None: ... + def DeleteItems(self, Items: PyIUnknown, /) -> None: ... + def NewItem( + self, + DestinationFolder: PyIShellItem, + FileAttributes, + Name, + TemplateName: Incomplete | None = ..., + Sink: PyGFileOperationProgressSink | None = ..., + /, + ) -> None: ... + def PerformOperations(self) -> None: ... + def GetAnyOperationsAborted(self): ... + +class PyIFolderView: + def GetCurrentViewMode(self): ... + def SetCurrentViewMode(self, ViewMode: int, /): ... + def GetFolder(self, riid: PyIID | None, /): ... + def Item(self, iItemIndex: int, /): ... + def ItemCount(self, uFlags: int, /): ... + def Items(self) -> Never: ... # Not Implemented + def GetSelectionMarkedItem(self): ... + def GetFocusedItem(self): ... + def GetItemPosition(self, pidl: PyIDL | None, /): ... + def GetSpacing(self, pt_x: int, pt_y: int, /): ... + def GetDefaultSpacing(self): ... + def GetAutoArrange(self): ... + def SelectItem(self, iItem: int, dwFlags: int, /): ... + def SelectAndPositionItems(self) -> Never: ... # Not Implemented + def SelectAndPositionItem(self, apidl: PyIDL | None, pt: tuple[int, int], dwFlags: int, /): ... + +class PyIIdentityName: ... + +class PyIInitializeWithFile: + def Initialize(self, FilePath, Mode, /) -> None: ... + +class PyIInitializeWithStream: + def Initialize(self, Stream: PyIStream, Mode, /) -> None: ... + +class PyIInputObject: + def TranslateAccelerator(self, pmsg, /) -> None: ... + def UIActivate(self, uState, /) -> None: ... + def HasFocusIO(self) -> None: ... + +class PyIInternetBindInfo: + def GetBindInfo(self) -> None: ... + def GetBindString(self) -> None: ... + +class PyIInternetPriority: + def SetPriority(self, nPriority, /) -> None: ... + def GetPriority(self) -> None: ... + +class PyIInternetProtocol: + def Read(self, cb, /) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def Seek(self, dlibMove: tuple[int, int], dwOrigin, /) -> None: ... + @overload + def Seek(self, dlibMove: int, dwOrigin, /) -> None: ... + + def LockRequest(self, dwOptions, /) -> None: ... + def UnlockRequest(self) -> None: ... + +class PyIInternetProtocolInfo: + def ParseUrl(self, pwzUrl, ParseAction, dwParseFlags, cchResult, dwReserved, /) -> None: ... + def CombineUrl(self, pwzBaseUrl, pwzRelativeUrl, dwCombineFlags, cchResult, dwReserved, /) -> None: ... + def CompareUrl(self, pwzUrl1, pwzUrl2, dwCompareFlags, /) -> None: ... + def QueryInfo(self, pwzUrl, OueryOption, dwQueryFlags, cbBuffer, dwReserved, /): ... + +class PyIInternetProtocolRoot: + def Start( + self, szUrl, pOIProtSink: PyIInternetProtocolSink, pOIBindInfo: PyIInternetBindInfo, grfPI, dwReserved, / + ) -> None: ... + def Continue(self) -> None: ... + def Abort(self, hrReason, dwOptions, /) -> None: ... + def Terminate(self, dwOptions, /) -> None: ... + def Suspend(self) -> None: ... + def Resume(self) -> None: ... + +class PyIInternetProtocolSink: + def Switch(self) -> None: ... + def ReportProgress(self, ulStatusCode, szStatusText, /) -> None: ... + def ReportData(self, grfBSCF, ulProgress, ulProgressMax, /) -> None: ... + def ReportResult(self, hrResult, dwError, szResult, /) -> None: ... + +class PyIInternetSecurityManager: + def SetSecuritySite(self, pSite, /) -> None: ... + def GetSecuritySite(self) -> None: ... + def MapUrlToZone(self, pwszUrl, dwFlags, /) -> None: ... + def GetSecurityId(self, pwszUrl, pcbSecurityId, /) -> None: ... + def ProcessUrlAction(self, pwszUrl, dwAction, context, dwFlags, /) -> None: ... + def SetZoneMapping(self, dwZone, lpszPattern, dwFlags, /) -> None: ... + def GetZoneMappings(self, dwZone, dwFlags, /) -> None: ... + +class PyIKnownFolder: + def GetId(self) -> PyIID: ... + def GetCategory(self): ... + def GetShellItem(self, riid: PyIID, Flags: int = ..., /) -> PyIShellItem: ... + def GetPath(self, Flags: int = ..., /): ... + def SetPath(self, Flags, Path, /) -> None: ... + def GetIDlist(self, Flags, /) -> PyIDL: ... + def GetFolderType(self) -> PyIID: ... + def GetRedirectionCapabilities(self): ... + def GetFolderDefinition(self): ... + +class PyIKnownFolderManager: + def FolderIdFromCsidl(self, Csidl, /) -> PyIID: ... + def FolderIdToCsidl(self, _id: PyIID, /): ... + def GetFolderIds(self) -> tuple[PyIID, ...]: ... + def GetFolder(self, _id: PyIID, /) -> PyIKnownFolder: ... + def GetFolderByName(self, Name, /) -> PyIKnownFolder: ... + def RegisterFolder(self, _id: PyIID, Definition, /) -> None: ... + def UnregisterFolder(self, _id: PyIID, /) -> None: ... + def FindFolderFromPath(self, Path, Mode, /) -> PyIKnownFolder: ... + def FindFolderFromIDlist(self, pidl: PyIDL, /) -> PyIKnownFolder: ... + def Redirect(self, _id: PyIID, hwnd: int, flags, TargetPath, Exclusion: tuple[PyIID, ...], /) -> None: ... + +class PyILockBytes: + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def ReadAt(self, ulOffset: tuple[int, int], cb, /) -> str: ... + @overload + def ReadAt(self, ulOffset: int, cb, /) -> str: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def WriteAt(self, ulOffset: tuple[int, int], data: str, /): ... + @overload + def WriteAt(self, ulOffset: int, data: str, /): ... + + def Flush(self) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def SetSize(self, cb: tuple[int, int], /) -> None: ... + @overload + def SetSize(self, cb: int, /) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def LockRegion(self, libOffset: tuple[int, int], cb: tuple[int, int], dwLockType, /) -> None: ... + @overload + def LockRegion(self, libOffset: int, cb: int, dwLockType, /) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def UnlockRegion(self, libOffset: tuple[int, int], cb: tuple[int, int], dwLockType, /) -> None: ... + @overload + def UnlockRegion(self, libOffset: int, cb: int, dwLockType, /) -> None: ... + +class PyIMAPIContainer: + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def GetContentsTable(self, flags, /) -> PyIMAPITable: ... + def GetHierarchyTable(self, flags, /) -> PyIMAPITable: ... + +class PyIMAPIFolder: + def GetLastError(self, hr, flags, /): ... + def CreateFolder( + self, folderType, folderName: str, folderComment: str | None = ..., iid: PyIID | None = ..., flags=..., / + ) -> PyIMAPIFolder: ... + def CreateMessage(self, iid: PyIID, flags, /) -> PyIMessage: ... + def CopyMessages(self, msgs: PySBinaryArray, iid: PyIID, folder: PyIMAPIFolder, ulUIParam, progress, flags, /): ... + def DeleteFolder(self, entryId: str, uiParam, progress, /) -> None: ... + def DeleteMessages(self, msgs: PySBinaryArray, uiParam, progress, flags, /): ... + def EmptyFolder(self, uiParam, progress, flags, /): ... + def SetReadFlags(self, msgs: PySBinaryArray, uiParam, progress, flag, /) -> None: ... + +class PyIMAPIProp: + def GetProps(self, proplist: PySPropTagArray, flags: int = ..., /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def DeleteProps( + self, proplist: PySPropTagArray, wantProblems: bool = ..., / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def SetProps( + self, proplist: tuple[Incomplete, Incomplete], wantProblems: bool = ..., / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def CopyTo( + self, + IIDExcludelist: tuple[Incomplete, Incomplete], + propTags: PySPropTagArray, + uiParam, + progress, + resultIID: PyIID, + dest: PyIMAPIProp, + flags, + wantProblems: bool = ..., + /, + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def CopyProps( + self, + propTags: PySPropTagArray, + uiParam, + progress, + resultIID: PyIID, + dest: PyIMAPIProp, + flags, + wantProblems: bool = ..., + /, + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def OpenProperty(self, propTag, iid: PyIID, interfaceOptions, flags, /) -> PyIUnknown: ... + def GetIDsFromNames(self, nameIds: PyMAPINAMEIDArray, flags: int = ..., /) -> PySPropTagArray: ... + def GetNamesFromIDs( + self, propTags: PySPropTagArray, propSetGuid: PyIID | None = ..., flags=..., / + ) -> tuple[Incomplete, PySPropTagArray, PyMAPINAMEIDArray]: ... + def GetLastError(self, hr, flags, /): ... + def SaveChanges(self, flags, /) -> None: ... + def GetProplist(self, flags, /) -> PySPropTagArray: ... + +class PyIMAPISession: + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def OpenMsgStore(self, uiParam, entryId: str, iid: PyIID, flags, /) -> PyIUnknown: ... + def QueryIdentity(self) -> str: ... + def Advise(self, entryId: str, mask, sink, /): ... + def Unadvise(self, connection, /) -> None: ... + def CompareEntryIDs(self, entryId: str, entryId1: str, flags: int = ..., /): ... + def GetLastError(self, hr, flags, /): ... + def GetMsgStoresTable(self, flags, /) -> PyIMAPITable: ... + def GetStatusTable(self, flags, /) -> PyIMAPITable: ... + def Logoff(self, uiParm, flags, reserved, /) -> None: ... + def OpenAddressBook(self, uiParm, iid: PyIID, flags, /) -> PyIAddrBook: ... + def OpenProfileSection(self, iidSection: PyIID, iid: PyIID, flags, /): ... + def AdminServices(self, flags: int = ..., /) -> PyIMsgServiceAdmin: ... + +class PyIMAPIStatus: + def ChangePassword(self, oldPassword, newPassword, ulFlags, /) -> None: ... + def SettingsDialog(self, ulUIParam, ulFlags, /) -> None: ... + def ValidateState(self, ulUIParam, ulFlags, /) -> None: ... + def FlushQueues(self, ulUIParam, transport: str, ulFlags, /) -> None: ... + +class PyIMAPITable: + def GetLastError(self, hr, flags, /): ... + def Advise(self, eventMask, adviseSink, /): ... + def SeekRow(self, bookmark, rowCount, /): ... + def SeekRowApprox(self, numerator, denominator, /) -> None: ... + def GetRowCount(self, flags, /): ... + def QueryRows(self, rowCount, flags, /): ... + def SetColumns(self, propTags, flags, /) -> None: ... + def GetStatus(self) -> None: ... + def QueryPosition(self) -> None: ... + def QueryColumns(self, flags, /): ... + def Abort(self) -> None: ... + def FreeBookmark(self, bookmark, /) -> None: ... + def CreateBookmark(self): ... + def Restrict(self, restriction: PySRestriction, flags, /) -> None: ... + def FindRow(self, restriction: PySRestriction, bookmarkOrigin, flags, /) -> None: ... + def SortTable(self, sortOrderSet: PySSortOrderSet, flags, /) -> None: ... + def Unadvise(self, handle, /) -> None: ... + +class PyIMachineDebugManager: + def AddApplication(self, pda: PyIRemoteDebugApplication, /) -> None: ... + def RemoveApplication(self, dwAppCookie, /) -> None: ... + def EnumApplications(self) -> None: ... + +class PyIMachineDebugManagerEvents: + def onAddApplication(self, pda: PyIRemoteDebugApplication, dwAppCookie, /) -> None: ... + def onRemoveApplication(self, pda: PyIRemoteDebugApplication, dwAppCookie, /) -> None: ... + +class PyIMessage: + def SetReadFlag(self, flag, /) -> None: ... + def GetAttachmentTable(self, flags, /) -> PyIMAPITable: ... + def OpenAttach(self, attachmentNum, interface: PyIID, flags, /) -> PyIAttach: ... + def CreateAttach(self, interface: PyIID, flags, /) -> tuple[Incomplete, PyIAttach]: ... + def DeleteAttach(self, attachmentNum, ulUIParam, interface, flags, /) -> None: ... + def ModifyRecipients(self, flags, mods, /) -> None: ... + def GetRecipientTable(self, flags, /) -> PyIMAPITable: ... + def SubmitMessage(self, flags, /) -> None: ... + +class PyIMoniker: + def BindToObject(self, bindCtx: PyIBindCtx, moniker: PyIMoniker, iidResult, /) -> PyIUnknown: ... + def BindToStorage(self, bindCtx: PyIBindCtx, moniker: PyIMoniker, iidResult, /) -> PyIUnknown: ... + def GetDisplayName(self, bindCtx: PyIBindCtx, moniker: PyIMoniker, /) -> str: ... + def ComposeWith(self, mkRight: PyIMoniker, fOnlyIfNotGeneric, /) -> PyIMoniker: ... + def Enum(self, fForward: bool = ..., /) -> PyIEnumMoniker: ... + def IsEqual(self, other: PyIMoniker, /) -> bool: ... + def IsSystemMoniker(self) -> bool: ... + def Hash(self): ... + +class PyIMsgServiceAdmin: + def GetLastError(self, hr, flags, /): ... + def CreateMsgService(self, serviceName: str, displayName: str, flags, uiParam: int = ..., /) -> None: ... + def ConfigureMsgService(self, iid: PyIID, ulUIParam, ulFlags, arg: list[Incomplete], /) -> None: ... + def GetMsgServiceTable(self, flags, /) -> PyIMAPITable: ... + def GetProviderTable(self, flags, /) -> PyIMAPITable: ... + def DeleteMsgService(self, uuid: PyIID, /) -> None: ... + @deprecated("This is deprecated, and there is no replacement referenced to use instead.") + def RenameMsgService(self, uuid: PyIID, flags, newName: str, /) -> None: ... + def OpenProfileSection(self, uuid: PyIID, iid: PyIID, flags, /): ... + def AdminProviders(self, uuid: PyIID, flags, /): ... + +class PyIMsgStore: + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def StoreLogoff(self, flags: int, /): ... + def GetReceiveFolder(self, messageClass: str | None = ..., flags: int = ..., /) -> tuple[PyIID, str]: ... + def GetReceiveFolderTable(self, flags, /) -> PyIMAPITable: ... + def CompareEntryIDs(self, entryId: str, entryId1: str, flags: int = ..., /): ... + def GetLastError(self, hr, flags, /): ... + def AbortSubmit(self, entryId: str, flags: int = ..., /): ... + def Advise(self, entryId: str, eventMask, adviseSink, /) -> None: ... + def Unadvise(self, connection, /) -> None: ... + +class PyINameSpaceTreeControl: + def Initialize(self, hwndParent, prc: tuple[Incomplete, Incomplete, Incomplete, Incomplete], nsctsFlags, /) -> None: ... + def TreeAdvise(self, punk: PyIUnknown, /) -> None: ... + def TreeUnadvise(self, dwCookie, /) -> None: ... + def AppendRoot(self, psiRoot: PyIShellItem, grfEnumFlags, grfRootStyle, pif, /) -> None: ... + def InsertRoot(self, iIndex, psiRoot: PyIShellItem, grfEnumFlags, grfRootStyle, pif, /) -> None: ... + def RemoveRoot(self, psiRoot: PyIShellItem, /) -> None: ... + def RemoveAllRoots(self) -> None: ... + def GetRootItems(self) -> None: ... + def SetItemState(self, psi: PyIShellItem, nstcisMask, nstcisFlags, /) -> None: ... + def GetItemState(self, psi: PyIShellItem, nstcisMask, /) -> None: ... + def GetSelectedItems(self) -> None: ... + def GetItemCustomState(self, psi: PyIShellItem, /) -> None: ... + def SetItemCustomState(self, psi: PyIShellItem, iStateNumber, /) -> None: ... + def EnsureItemVisible(self, psi: PyIShellItem, /) -> None: ... + def SetTheme(self, pszTheme, /) -> None: ... + def GetNextItem(self, psi: PyIShellItem, nstcgi, /) -> None: ... + def HitTest(self, pt: tuple[Incomplete, Incomplete], /) -> None: ... + def GetItemRect(self) -> None: ... + def CollapseAll(self) -> None: ... + +class PyINamedPropertyStore: + def GetNamedValue(self, Name, /) -> PyPROPVARIANT: ... + def SetNamedValue(self, propvar, /) -> None: ... + def GetNameCount(self): ... + def GetNameAt(self, Index, /): ... + +class PyIObjectArray: + def GetCount(self): ... + def GetAt(self, Index, riid: PyIID, /) -> PyIUnknown: ... + +class PyIObjectCollection: + def AddObject(self, punk: PyIUnknown, /) -> None: ... + def AddFromArray(self, Source: PyIObjectArray, /) -> None: ... + def RemoveObjectAt(self, Index, /) -> None: ... + def Clear(self) -> None: ... + +class PyIObjectWithPropertyKey: + def SetPropertyKey(self, key: PyPROPERTYKEY, /) -> None: ... + def GetPropertyKey(self) -> PyPROPERTYKEY: ... + +class PyIObjectWithSite: + def SetSite(self, pUnkSite, /) -> None: ... + def GetSite(self, riid: PyIID, /) -> None: ... + +class PyIOleClientSite: + def SaveObject(self) -> None: ... + def GetMoniker(self, dwAssign, dwWhichMoniker, /) -> None: ... + def GetContainer(self) -> None: ... + def ShowObject(self) -> None: ... + def OnShowWindow(self, fShow, /) -> None: ... + def RequestNewObjectLayout(self) -> None: ... + +class PyIOleCommandTarget: + def QueryStatus(self) -> None: ... + def Exec(self) -> None: ... + +class PyIOleControl: + def GetControlInfo(self) -> None: ... + def OnMnemonic(self, msg, /) -> None: ... + def OnAmbientPropertyChange(self, dispID, /) -> None: ... + def FreezeEvents(self, bFreeze, /) -> None: ... + +class PyIOleControlSite: + def OnControlInfoChanged(self) -> None: ... + def LockInPlaceActive(self, fLock, /) -> None: ... + def GetExtendedControl(self) -> None: ... + def TransformCoords( + self, PtlHimetric: tuple[Incomplete, Incomplete], pPtfContainer: tuple[float, float], dwFlags, / + ) -> None: ... + def TranslateAccelerator(self, pMsg: PyMSG, grfModifiers, /) -> None: ... + def OnFocus(self, fGotFocus, /) -> None: ... + def ShowPropertyFrame(self) -> None: ... + +class PyIOleInPlaceActiveObject: + def TranslateAccelerator(self, lpmsg: PyMSG, /) -> None: ... + def OnFrameWindowActivate(self, fActivate, /) -> None: ... + def OnDocWindowActivate(self, fActivate, /) -> None: ... + def ResizeBorder( + self, rcBorder: tuple[Incomplete, Incomplete, Incomplete, Incomplete], pUIWindow: PyIOleInPlaceUIWindow, fFrameWindow, / + ) -> None: ... + def EnableModeless(self, fEnable, /) -> None: ... + +class PyIOleInPlaceFrame: + def InsertMenus(self, hmenuShared, menuWidths: PyOLEMENUGROUPWIDTHS, /) -> None: ... + def SetMenu(self, hmenuShared, holemenu, hwndActiveObject, /) -> None: ... + def RemoveMenus(self, hmenuShared, /) -> None: ... + def SetStatusText(self, pszStatusText, /) -> None: ... + def EnableModeless(self, fEnable, /) -> None: ... + def TranslateAccelerator(self, lpmsg: PyMSG, wID, /) -> None: ... + +class PyIOleInPlaceObject: + def InPlaceDeactivate(self) -> None: ... + def UIDeactivate(self) -> None: ... + def SetObjectRects(self) -> None: ... + def ReactivateAndUndo(self) -> None: ... + +class PyIOleInPlaceSite: + def CanInPlaceActivate(self) -> None: ... + def OnInPlaceActivate(self) -> None: ... + def OnUIActivate(self) -> None: ... + def GetWindowContext(self) -> None: ... + def Scroll(self) -> None: ... + def OnUIDeactivate(self, fUndoable, /) -> None: ... + def OnInPlaceDeactivate(self) -> None: ... + def DiscardUndoState(self) -> None: ... + def DeactivateAndUndo(self) -> None: ... + def OnPosRectChange(self) -> None: ... + +class PyIOleInPlaceSiteEx: + def OnInPlaceActivateEx(self, dwFlags, /) -> None: ... + def OnInPlaceDeactivateEx(self, fNoRedraw, /) -> None: ... + def RequestUIActivate(self) -> None: ... + +class PyIOleInPlaceSiteWindowless: + def CanWindowlessActivate(self) -> None: ... + def GetCapture(self) -> None: ... + def SetCapture(self, fCapture, /) -> None: ... + def GetFocus(self) -> None: ... + def SetFocus(self, fFocus, /) -> None: ... + def GetDC(self, grfFlags, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def ReleaseDC(self, hDC: PyCDC, /) -> None: ... + def InvalidateRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], fErase, /) -> None: ... + def InvalidateRgn(self, hRgn, fErase, /) -> None: ... + def ScrollRect(self, dx, dy, /) -> None: ... + def AdjustRect(self) -> None: ... + def OnDefWindowMessage(self, msg, wParam, lParam, /) -> None: ... + +class PyIOleInPlaceUIWindow: + def GetBorder(self) -> None: ... + def RequestBorderSpace(self, borderwidths: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def SetBorderSpace(self, borderwidths: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def SetActiveObject(self, pActiveObject: PyIOleInPlaceActiveObject, pszObjName, /) -> None: ... + +class PyIOleObject: + def SetClientSite(self, pClientSite: PyIOleClientSite, /) -> None: ... + def GetClientSite(self) -> None: ... + def SetHostNames(self, szContainerApp, szContainerObj, /) -> None: ... + def Close(self, dwSaveOption, /) -> None: ... + def SetMoniker(self, dwWhichMoniker, pmk: PyIMoniker, /) -> None: ... + def GetMoniker(self, dwAssign, dwWhichMoniker, /) -> None: ... + def InitFromData(self, pDataObject: PyIDataObject, fCreation, dwReserved, /) -> None: ... + def GetClipboardData(self, dwReserved, /) -> None: ... + def DoVerb( + self, + iVerb, + msg: PyMSG, + pActiveSite: PyIOleClientSite, + lindex, + hwndParent, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + /, + ) -> None: ... + def EnumVerbs(self) -> None: ... + def Update(self) -> None: ... + def IsUpToDate(self) -> bool: ... + def GetUserClassID(self) -> None: ... + def GetUserType(self, dwFormOfType, /) -> None: ... + def SetExtent(self, dwDrawAspect, size: tuple[Incomplete, Incomplete], /) -> None: ... + def GetExtent(self, dwDrawAspect, size: tuple[Incomplete, Incomplete], /) -> None: ... + def Advise(self, pAdvSink, /) -> None: ... + def Unadvise(self, dwConnection, /) -> None: ... + def EnumAdvise(self) -> None: ... + def GetMiscStatus(self, dwAspect, /) -> None: ... + def SetColorScheme(self) -> None: ... + +class PyIOleWindow: + def GetWindow(self) -> None: ... + def ContextSensitiveHelp(self, fEnterMode, /) -> None: ... + +class PyIPersist: + def GetClassID(self) -> PyIID: ... + +class PyIPersistFile: + def IsDirty(self) -> bool: ... + def Load(self, FileName, Mode, /) -> None: ... + def Save(self, FileName, fRemember, /) -> None: ... + def SaveCompleted(self, FileName, /) -> None: ... + def GetCurFile(self): ... + +class PyIPersistFolder: + def Initialize(self, pidl: PyIDL, /) -> None: ... + +class PyIPersistFolder2: + def GetCurFolder(self) -> None: ... + +class PyIPersistPropertyBag: + def InitNew(self) -> None: ... + def Load(self, bag: PyIPropertyBag, log: PyIErrorLog | None = ..., /) -> None: ... + def Save(self, bag: PyIPropertyBag, clearDirty, saveProperties, /) -> None: ... + +class PyIPersistSerializedPropStorage: + def SetFlags(self, flags, /) -> None: ... + def SetPropertyStorage(self, ps, /) -> None: ... + def GetPropertyStorage(self): ... + +class PyIPersistStorage: + def IsDirty(self) -> bool: ... + def InitNew(self, PyIStorage: PyIStorage, /) -> None: ... + def Load(self, storage: PyIStorage, /) -> None: ... + def Save(self, PyIStorage: PyIStorage, _int, /) -> None: ... + def SaveCompleted(self, PyIStorage: PyIStorage, /) -> None: ... + def HandsOffStorage(self) -> None: ... + +class PyIPersistStream: + def IsDirty(self) -> bool: ... + def Load(self, stream: PyIStream, /) -> None: ... + def Save(self, stream: PyIStream, bClearDirty, /) -> None: ... + def GetSizeMax(self) -> int: ... + +class PyIPersistStreamInit: + def InitNew(self) -> None: ... + +class PyIProcessDebugManager: + def CreateApplication(self) -> None: ... + def GetDefaultApplication(self) -> None: ... + def AddApplication(self, pda: PyIDebugApplication, /) -> None: ... + def RemoveApplication(self, dwAppCookie, /) -> None: ... + def CreateDebugDocumentHelper(self, unkOuter, /) -> None: ... + +class PyIProfAdmin: + def GetLastError(self, hr, flags, /): ... + def CreateProfile(self, oldProfileName: str, Password: str, uiParam: int = ..., flags: int = ..., /) -> None: ... + def DeleteProfile(self, oldProfileName: str, flags: int = ..., /) -> None: ... + def CopyProfile(self, oldProfileName: str, Password: str, newProfileName: str, uiParam: int = ..., flags=..., /) -> None: ... + def RenameProfile( + self, oldProfileName: str, Password: str, newProfileName: str, uiParam: int = ..., flags=..., / + ) -> None: ... + def SetDefaultProfile(self, profileName: str, flags: int = ..., /) -> None: ... + def AdminServices(self, profileName: str, Password: str | None = ..., uiParam: int = ..., flags=..., /) -> PyIProfAdmin: ... + +class PyIPropertyBag: + def Read(self, propName, propType, errorLog: PyIErrorLog | None = ..., /): ... + def Write(self, propName, value, /) -> None: ... + +class PyIPropertyChange: + def ApplyToPropVariant(self, OrigVal: PyPROPVARIANT, /) -> PyPROPVARIANT: ... + +class PyIPropertyChangeArray: + def GetCount(self): ... + def GetAt(self, Index, riid: PyIID, /) -> PyIPropertyChange: ... + def InsertAt(self, Index, PropChange: PyIPropertyChange, /) -> None: ... + def Append(self, PropChange: PyIPropertyChange, /) -> None: ... + def AppendOrReplace(self, PropChange: PyIPropertyChange, /) -> None: ... + def RemoveAt(self, Index, /) -> None: ... + def IsKeyInArray(self, key: PyPROPERTYKEY, /) -> bool: ... + +class PyIPropertyDescription: + def GetPropertyKey(self) -> PyPROPERTYKEY: ... + def GetCanonicalName(self): ... + def GetPropertyType(self): ... + def GetDisplayName(self): ... + def GetEditInvitation(self): ... + def GetTypeFlags(self, mask, /): ... + def GetViewFlags(self): ... + def GetDefaultColumnWidth(self): ... + def GetDisplayType(self): ... + def GetColumnState(self): ... + def GetGroupingRange(self): ... + def GetRelativeDescriptionType(self): ... + def GetRelativeDescription(self, var1: PyPROPVARIANT, var2: PyPROPVARIANT, /) -> tuple[Incomplete, Incomplete]: ... + def GetSortDescription(self): ... + def GetSortDescriptionLabel(self, Descending, /): ... + def GetAggregationType(self): ... + def GetConditionType(self) -> tuple[Incomplete, Incomplete]: ... + def GetEnumTypelist(self, riid: PyIID, /) -> PyIPropertyEnumTypelist: ... + def CoerceToCanonicalValue(self, Value: PyPROPVARIANT, /): ... + def FormatForDisplay(self, Value: PyPROPVARIANT, Flags, /): ... + def IsValueCanonical(self, Value, /) -> bool: ... + +class PyIPropertyDescriptionAliasInfo: + def GetSortByAlias(self, riid: PyIID, /) -> PyIPropertyDescription: ... + def GetAdditionalSortByAliases(self, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + +class PyIPropertyDescriptionlist: + def GetCount(self): ... + def GetAt(self, Elem, riid: PyIID, /) -> PyIPropertyDescription: ... + +class PyIPropertyDescriptionSearchInfo: + def GetSearchInfoFlags(self): ... + def GetColumnIndexType(self): ... + def GetProjectionString(self): ... + def GetMaxSize(self): ... + +class PyIPropertyEnumType: + def GetEnumType(self): ... + def GetValue(self) -> PyPROPVARIANT: ... + def GetRangeMinValue(self) -> PyPROPVARIANT: ... + def GetRangeSetValue(self) -> PyPROPVARIANT: ... + def GetDisplayText(self) -> None: ... + +class PyIPropertyEnumTypelist: + def GetCount(self): ... + def GetAt(self, itype, riid: PyIID, /) -> PyIPropertyEnumType: ... + def FindMatchingIndex(self, Cmp: PyPROPVARIANT, /): ... + +class PyIPropertySetStorage: + def Create(self, fmtid: PyIID, clsid: PyIID, Flags, Mode, /) -> PyIPropertyStorage: ... + def Open(self, fmtid: PyIID, Mode, /) -> PyIPropertyStorage: ... + def Delete(self, fmtid: PyIID, /) -> None: ... + def Enum(self) -> PyIEnumSTATPROPSETSTG: ... + +class PyIPropertyStorage: + def ReadMultiple(self, props: tuple[PROPSPEC, ...], /) -> tuple[Incomplete, ...]: ... + def WriteMultiple( + self, props: tuple[PROPSPEC, ...], values: tuple[Incomplete, ...], propidNameFirst: int = ..., / + ) -> None: ... + def DeleteMultiple(self, props: tuple[PROPSPEC, ...], /) -> None: ... + def ReadPropertyNames(self, props: tuple[Incomplete, ...], /) -> tuple[Incomplete, ...]: ... + def WritePropertyNames(self, props: tuple[Incomplete, ...], names: tuple[str, ...], /) -> None: ... + def DeletePropertyNames(self, props: tuple[Incomplete, ...], /) -> None: ... + def Commit(self, CommitFlags, /) -> None: ... + def Revert(self) -> None: ... + def Enum(self) -> PyIEnumSTATPROPSTG: ... + def SetTimes(self, ctime: TimeType, atime: TimeType, mtime: TimeType, /) -> None: ... + def SetClass(self, clsid: PyIID, /) -> None: ... + def Stat(self): ... + +class PyIPropertyStore: + def GetCount(self): ... + def GetAt(self, iProp, /) -> PyPROPERTYKEY: ... + def GetValue(self, Key: PyPROPERTYKEY, /) -> PyPROPVARIANT: ... + def SetValue(self, Key: PyPROPERTYKEY, Value: PyPROPVARIANT, /) -> None: ... + def Commit(self) -> None: ... + +class PyIPropertyStoreCache: + def GetState(self, key: PyPROPERTYKEY, /): ... + def GetValueAndState(self, key: PyPROPERTYKEY, /) -> tuple[PyPROPVARIANT, Incomplete]: ... + def SetState(self, key: PyPROPERTYKEY, state, /) -> None: ... + def SetValueAndState(self, key: PyPROPERTYKEY, value: PyPROPVARIANT, state, /) -> None: ... + +class PyIPropertyStoreCapabilities: + def IsPropertyWritable(self, key: PyPROPERTYKEY, /) -> bool: ... + +class PyIPropertySystem: + def GetPropertyDescription(self, Key: PyPROPERTYKEY, riid: PyIID, /) -> PyIPropertyDescription: ... + def GetPropertyDescriptionByName(self, CanonicalName, riid: PyIID, /) -> PyIPropertyDescription: ... + def GetPropertyDescriptionlistFromString(self, Proplist, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def EnumeratePropertyDescriptions(self, Filter, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def FormatForDisplay(self, Key: PyPROPERTYKEY, Value: PyPROPVARIANT, Flags, /): ... + def RegisterPropertySchema(self, Path, /) -> None: ... + def UnregisterPropertySchema(self, Path, /) -> None: ... + def RefreshPropertySchema(self) -> None: ... + +class PyIProvideClassInfo: + def GetClassInfo(self) -> PyITypeInfo: ... + +class PyIProvideClassInfo2: + def GetGUID(self, flags, /) -> PyIID: ... + +class PyIProvideExpressionContexts: + def EnumExpressionContexts(self) -> None: ... + +class PyIProvideTaskPage: + def GetPage(self, tpType, PersistChanges, /) -> None: ... + +class PyIQueryAssociations: + def Init(self, flags, assoc: str, hkeyProgId: PyHKEY | None = ..., hwnd: int | None = ..., /) -> None: ... + def GetKey(self, flags, assocKey, arg: str, /): ... + def GetString(self, flags, assocStr, arg: str, /): ... + +class PyIRelatedItem: + def GetItemIDlist(self) -> PyIDL: ... + def GetItem(self) -> PyIShellItem: ... + +class PyIRemoteDebugApplication: + def ResumeFromBreakPoint(self, prptFocus: PyIRemoteDebugApplicationThread, bra, era, /) -> None: ... + def CauseBreak(self) -> None: ... + def ConnectDebugger(self, pad: PyIApplicationDebugger, /) -> None: ... + def DisconnectDebugger(self) -> None: ... + def GetDebugger(self) -> PyIApplicationDebugger: ... + def CreateInstanceAtApplication(self, rclsid: PyIID, pUnkOuter: PyIUnknown, dwClsContext, riid: PyIID, /) -> PyIUnknown: ... + def QueryAlive(self) -> None: ... + def EnumThreads(self) -> PyIEnumRemoteDebugApplicationThreads: ... + def GetName(self) -> None: ... + def GetRootNode(self) -> PyIDebugApplicationNode: ... + def EnumGlobalExpressionContexts(self): ... + +class PyIRemoteDebugApplicationEvents: + def OnConnectDebugger(self, pad: PyIApplicationDebugger, /) -> None: ... + def OnDisconnectDebugger(self) -> None: ... + def OnSetName(self, pstrName, /) -> None: ... + def OnDebugOutput(self, pstr, /) -> None: ... + def OnClose(self) -> None: ... + def OnEnterBreakPoint(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnLeaveBreakPoint(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnCreateThread(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnDestroyThread(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnBreakFlagChange(self, abf, prdatSteppingThread: PyIRemoteDebugApplicationThread, /) -> None: ... + +class PyIRemoteDebugApplicationThread: + def GetSystemThreadId(self) -> None: ... + def GetApplication(self) -> None: ... + def EnumStackFrames(self) -> None: ... + def GetDescription(self) -> None: ... + def SetNextStatement(self, pStackFrame: PyIDebugStackFrame, pCodeContext: PyIDebugCodeContext, /) -> None: ... + def GetState(self) -> None: ... + def Suspend(self) -> None: ... + def Resume(self) -> None: ... + def GetSuspendCount(self) -> None: ... + +class PyIRunningObjectTable: + def Register(self): ... + def Revoke(self): ... + def IsRunning(self, objectName: PyIMoniker, /) -> bool: ... + def GetObject(self, objectName: PyIMoniker, /) -> PyIUnknown: ... + def EnumRunning(self) -> PyIEnumMoniker: ... + +class PyIScheduledWorkItem: + def CreateTrigger(self) -> tuple[Incomplete, PyITaskTrigger]: ... + def DeleteTrigger(self, Trigger, /) -> None: ... + def GetTriggerCount(self): ... + def GetTrigger(self, iTrigger, /) -> PyITaskTrigger: ... + def GetTriggerString(self): ... + def GetRunTimes(self, Count, Begin: TimeType, End: TimeType, /) -> tuple[TimeType, Incomplete, Incomplete, Incomplete]: ... + def GetNextRunTime(self) -> TimeType: ... + def SetIdleWait(self, wIdleMinutes, wDeadlineMinutes, /) -> None: ... + def GetIdleWait(self) -> tuple[Incomplete, Incomplete]: ... + def Run(self) -> None: ... + def Terminate(self) -> None: ... + def EditWorkItem(self, hParent: int, dwReserved, /) -> None: ... + def GetMostRecentRunTime(self) -> TimeType: ... + def GetStatus(self): ... + def GetExitCode(self) -> tuple[Incomplete, Incomplete]: ... + def SetComment(self, Comment, /) -> None: ... + def GetComment(self) -> str: ... + def SetCreator(self, Creator, /) -> None: ... + def GetCreator(self) -> None: ... + def SetWorkItemData(self, Data: str, /) -> None: ... + def GetWorkItemData(self) -> str: ... + def SetErrorRetryCount(self, wRetryCount, /) -> None: ... + def GetErrorRetryCount(self) -> None: ... + def SetErrorRetryInterval(self, RetryInterval, /) -> None: ... + def GetErrorRetryInterval(self) -> None: ... + def SetFlags(self, dwFlags, /) -> None: ... + def GetFlags(self): ... + def SetAccountInformation(self, AccountName, Password, /) -> None: ... + def GetAccountInformation(self): ... + +class PyIServerSecurity: + def QueryBlanket(self, Capabilities: int = ..., /): ... + def ImpersonateClient(self) -> None: ... + def RevertToSelf(self) -> None: ... + def IsImpersonating(self) -> bool: ... + +class PyIServiceProvider: + def QueryService(self, clsid: PyIID, iid: PyIID, /) -> PyIUnknown: ... + +class PyIShellBrowser: + def InsertMenusSB(self, hmenuShared: int, lpMenuWidths: PyOLEMENUGROUPWIDTHS, /) -> PyOLEMENUGROUPWIDTHS: ... + def SetMenuSB(self, hmenuShared: int, holemenuRes: int, hwndActiveObject: int, /) -> None: ... + def RemoveMenusSB(self, hmenuShared: int, /) -> None: ... + def SetStatusTextSB(self, pszStatusText, /) -> None: ... + def EnableModelessSB(self, fEnable, /) -> None: ... + def TranslateAcceleratorSB(self, pmsg: PyMSG, wID, /) -> None: ... + def BrowseObject(self, pidl: PyIDL, wFlags, /) -> None: ... + def GetViewStateStream(self, grfMode, /) -> PyIStream: ... + def GetControlWindow(self, _id, /) -> None: ... + def SendControlMsg(self, _id, uMsg, wParam, lParam, /): ... + def QueryActiveShellView(self) -> PyIShellView: ... + def OnViewWindowActive(self, pshv: PyIShellView, /) -> None: ... + def SetToolbarItems(self, lpButtons, uFlags, /) -> None: ... + +class PyIShellExtInit: + def Initialize(self, pFolder: PyIDL, pDataObject: PyIDataObject, hkey: int, /) -> None: ... + +class PyIShellFolder: + def ParseDisplayName(self, hwndOwner: int, pbc: PyIBindCtx, DisplayName, Attributes: int = ..., /): ... + def EnumObjects(self, grfFlags, hwndOwner: int | None = ..., /) -> PyIEnumIDlist: ... + def BindToObject(self, pidl: PyIDL, pbc: PyIBindCtx, riid: PyIID, /) -> PyIShellFolder: ... + def BindToStorage(self, pidl: PyIDL, pbc: PyIBindCtx, riid: PyIID, /): ... + def CompareIDs(self, lparam, pidl1: PyIDL, pidl2: PyIDL, /): ... + def CreateViewObject(self, hwndOwner, riid: PyIID, /) -> PyIShellView: ... + def GetAttributesOf(self, pidl: tuple[PyIDL, ...], rgfInOut, /): ... + def GetUIObjectOf( + self, hwndOwner: int, pidl: tuple[PyIDL, ...], riid: PyIID, iidout: PyIID, Reserved=..., / + ) -> tuple[Incomplete, PyIUnknown]: ... + def GetDisplayNameOf(self, pidl: PyIDL, uFlags, /): ... + def SetNameOf(self, hwndOwner, pidl: PyIDL, Name, Flags, /) -> PyIDL: ... + +class PyIShellFolder2: + def GetDefaultSearchGUID(self, pguid: PyIID, /) -> PyIID: ... + def EnumSearches(self): ... + def GetDefaultColumn(self) -> tuple[Incomplete, Incomplete]: ... + def GetDefaultColumnState(self, iColumn, /): ... + def GetDetailsEx(self, pidl: PyIDL, pscid, /): ... + def GetDetailsOf(self, pidl: PyIDL, iColumn, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def MapColumnToSCID(self, Column, /): ... + +class PyIShellIcon: + def GetIconOf(self, pidl: PyIDL, /) -> None: ... + +class PyIShellIconOverlay: + def GetOverlayIndex(self, pidl: PyIDL, /) -> None: ... + def GetOverlayIconIndex(self, pidl: PyIDL, /) -> None: ... + +class PyIShellIconOverlayIdentifier: + def IsMemberOf(self, path: str, attrib, /) -> bool: ... + def GetOverlayInfo(self) -> tuple[str, Incomplete, Incomplete]: ... + def GetPriority(self): ... + +class PyIShellIconOverlayManager: + def GetFileOverlayInfo(self, path, attrib, flags, /): ... + def GetReservedOverlayInfo(self, path, attrib, flags, ireservedID, /) -> None: ... + def RefreshOverlayImages(self, flags, /) -> None: ... + def LoadNonloadedOverlayIdentifiers(self) -> None: ... + def OverlayIndexFromImageIndex(self, iImage, fAdd, /) -> None: ... + +class PyIShellItem: + def BindToHandler(self, pbc: PyIBindCtx, bhid: PyIID, riid: PyIID, /): ... + def GetParent(self) -> PyIShellItem: ... + def GetDisplayName(self, sigdnName, /): ... + def GetAttributes(self, Mask, /): ... + def Compare(self, psi: PyIShellItem, hint, /): ... + +class PyIShellItem2: + def GetPropertyStore(self, Flags, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyStoreForKeys(self, Keys: tuple[Incomplete, ...], Flags, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyStoreWithCreateObject(self, Flags, CreateObject: PyIUnknown, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyDescriptionlist(self, Type: PyPROPERTYKEY, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def Update(self, BindCtx: Incomplete | None = ..., /) -> None: ... + def GetProperty(self, key: PyPROPERTYKEY, /): ... + def GetCLSID(self, key: PyPROPERTYKEY, /) -> PyIID: ... + def GetFileTime(self, key: PyPROPERTYKEY, /) -> TimeType: ... + def GetInt32(self, key: PyPROPERTYKEY, /): ... + def GetString(self, key: PyPROPERTYKEY, /): ... + def GetUInt32(self, key: PyPROPERTYKEY, /): ... + def GetUInt64(self, key: PyPROPERTYKEY, /): ... + def GetBool(self, key: PyPROPERTYKEY, /): ... + +class PyIShellItemArray: + def BindToHandler(self, pbc: PyIBindCtx, rbhid: PyIID, riid: PyIID, /): ... + def GetPropertyStore(self, flags, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyDescriptionlist(self, Type: PyPROPERTYKEY, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def GetAttributes(self, AttribFlags, Mask, /): ... + def GetCount(self): ... + def GetItemAt(self, dwIndex, /) -> PyIShellItem: ... + def EnumItems(self) -> PyIEnumShellItems: ... + +class PyIShellItemResources: + def GetAttributes(self) -> None: ... + def GetSize(self): ... + def GetTimes(self) -> None: ... + def SetTimes(self, pftCreation: TimeType, pftWrite: TimeType, pftAccess: TimeType, /) -> None: ... + def GetResourceDescription(self, pcsir: PySHELL_ITEM_RESOURCE, /) -> None: ... + def EnumResources(self) -> PyIEnumResources: ... + def SupportsResource(self, pcsir: PySHELL_ITEM_RESOURCE, /): ... + def OpenResource(self, pcsir: PySHELL_ITEM_RESOURCE, riid: PyIID, /) -> PyIUnknown: ... + def CreateResource(self, sir: PySHELL_ITEM_RESOURCE, riid: PyIID, /): ... + def MarkForDelete(self) -> None: ... + +class PyIShellLibrary: + def LoadLibraryFromItem(self, Library: PyIShellItem, Mode, /) -> None: ... + def LoadLibraryFromKnownFolder(self, Library: PyIID, Mode, /) -> None: ... + def AddFolder(self, Location: PyIShellItem, /) -> None: ... + def RemoveFolder(self, Location: PyIShellItem, /) -> None: ... + def GetFolders(self, Filter, riid: PyIID, /) -> PyIShellItemArray: ... + def ResolveFolder(self, FolderToResolve: PyIShellItem, Timeout, riid: PyIID, /) -> PyIShellItem: ... + def GetDefaultSaveFolder(self, Type, riid: PyIID, /) -> PyIShellItem: ... + def SetDefaultSaveFolder(self, Type, SaveFolder: PyIShellItem, /) -> None: ... + def GetOptions(self): ... + def SetOptions(self, Mask, Options, /) -> None: ... + def GetFolderType(self) -> PyIID: ... + def SetFolderType(self, Type: PyIID, /) -> None: ... + def GetIcon(self): ... + def SetIcon(self, Icon, /) -> None: ... + def Commit(self) -> None: ... + def Save(self, FolderToSaveIn: PyIShellItem, LibraryName, Flags, /) -> PyIShellItem: ... + def SaveInKnownFolder(self, FolderToSaveIn: PyIID, LibraryName, Flags, /) -> PyIShellItem: ... + +class PyIShellLink: + def GetPath(self, fFlags, cchMaxPath, /) -> tuple[Incomplete, WIN32_FIND_DATA]: ... + def GetIDlist(self) -> PyIDL: ... + def SetIDlist(self, pidl: PyIDL, /) -> None: ... + def GetDescription(self, cchMaxName: int = ..., /): ... + def SetDescription(self, Name, /) -> None: ... + def GetWorkingDirectory(self, cchMaxName: int = ..., /): ... + def SetWorkingDirectory(self, Dir, /) -> None: ... + def GetArguments(self, cchMaxName: int = ..., /): ... + def SetArguments(self, args, /) -> None: ... + def GetHotkey(self): ... + def SetHotkey(self, wHotkey, /) -> None: ... + def GetShowCmd(self): ... + def SetShowCmd(self, iShowCmd, /) -> None: ... + def GetIconLocation(self, cchMaxPath, /): ... + def SetIconLocation(self, iconPath: str, iIcon, /) -> None: ... + def SetRelativePath(self, relPath: str, reserved: int = ..., /) -> None: ... + def Resolve(self, hwnd: int, fFlags, /) -> None: ... + def SetPath(self, path: str, /) -> None: ... + +class PyIShellLinkDatalist: + def AddDataBlock(self, DataBlock, /) -> None: ... + def CopyDataBlock(self, Sig, /): ... + def GetFlags(self): ... + def RemoveDataBlock(self, Sig, /) -> None: ... + def SetFlags(self, Flags, /) -> None: ... + +class PyIShellView: + def TranslateAccelerator(self, pmsg, /): ... + def EnableModeless(self, fEnable, /) -> None: ... + def UIActivate(self, uState, /) -> None: ... + def Refresh(self) -> None: ... + def CreateViewWindow( + self, + psvPrevious: PyIShellView, + pfs: tuple[Incomplete, Incomplete], + psb: PyIShellBrowser, + prcView: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + /, + ): ... + def DestroyViewWindow(self) -> None: ... + def GetCurrentInfo(self): ... + def SaveViewState(self) -> None: ... + def SelectItem(self, pidlItem: PyIDL, uFlags, /) -> None: ... + def GetItemObject(self, uItem, riid: PyIID, /) -> PyIUnknown: ... + +class PyISpecifyPropertyPages: + def GetPages(self) -> None: ... + +class PyIStorage: + def CreateStream(self, Name, Mode, reserved1: int = ..., reserved2: int = ..., /) -> PyIStream: ... + def OpenStream(self, Name, reserved1, Mode, reserved2: int = ..., /) -> PyIStream: ... + def CreateStorage(self, Name, Mode, StgFmt, reserved2: int = ..., /) -> PyIStorage: ... + def OpenStorage(self, Name, Priority: PyIStorage, Mode, snbExclude, reserved=..., /) -> PyIStorage: ... + def CopyTo(self, rgiidExclude: tuple[Incomplete, Incomplete], snbExclude, stgDest: PyIStorage, /) -> None: ... + def MoveElementTo(self, Name, stgDest: PyIStorage, NewName, Flags, /) -> None: ... + def Commit(self, grfCommitFlags, /) -> None: ... + def Revert(self) -> None: ... + def EnumElements( + self, reserved1: int = ..., reserved2: Incomplete | None = ..., reserved3: int = ..., / + ) -> PyIEnumSTATSTG: ... + def DestroyElement(self, name: str, /) -> None: ... + def RenameElement(self, OldName, NewName, /) -> None: ... + def SetElementTimes(self, name, ctime: TimeType, atime: TimeType, mtime: TimeType, /) -> None: ... + def SetClass(self, clsid: PyIID, /) -> None: ... + def SetStateBits(self, grfStateBits, grfMask, /) -> None: ... + def Stat(self, grfStatFlag, /) -> STATSTG: ... + +class PyIStream: + def Read(self, numBytes, /) -> str: ... + def read(self, numBytes, /) -> str: ... + def Write(self, data: str, /) -> None: ... + def write(self, data: str, /) -> None: ... + + @overload + def Seek(self, offset: int, origin: int, /) -> int: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def Seek(self, offset: tuple[int, int], origin: int, /) -> int: ... + + @overload + def SetSize(self, newSize: int, /) -> None: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def SetSize(self, newSize: tuple[int, int], /) -> None: ... + + @overload + def CopyTo(self, stream: PyIStream, cb: int, /) -> int: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def CopyTo(self, stream: PyIStream, cb: tuple[int, int], /) -> int: ... + + def Commit(self, flags, /) -> None: ... + def Revert(self) -> None: ... + + @overload + def LockRegion(self, offset: int, cb: int, lockType, /) -> None: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def LockRegion(self, offset: tuple[int, int], cb: tuple[int, int], lockType, /) -> None: ... + + @overload + def UnLockRegion(self, offset: int, cb: int, lockType, /) -> None: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def UnLockRegion(self, offset: tuple[int, int], cb: tuple[int, int], lockType, /) -> None: ... + + def Clone(self) -> PyIStream: ... + def Stat(self, grfStatFlag: int = ..., /) -> STATSTG: ... + +class PyITask: + def SetApplicationName(self, ApplicationName, /) -> None: ... + def GetApplicationName(self): ... + def SetParameters(self, Parameters, /) -> None: ... + def GetParameters(self): ... + def SetWorkingDirectory(self, WorkingDirectory, /) -> None: ... + def GetWorkingDirectory(self): ... + def SetPriority(self, Priority, /) -> None: ... + def GetPriority(self): ... + def SetTaskFlags(self, dwFlags, /) -> None: ... + def GetTaskFlags(self): ... + def SetMaxRunTime(self, MaxRunTimeMS, /) -> None: ... + def GetMaxRunTime(self): ... + +class PyITaskScheduler: + def SetTargetComputer(self, Computer, /) -> None: ... + def GetTargetComputer(self): ... + def Enum(self) -> tuple[str, ...]: ... + def Activate(self, Name, riid: PyIID, /) -> PyITask: ... + def Delete(self, TaskName, /) -> None: ... + def NewWorkItem(self, TaskName, rclsid: PyIID, riid: PyIID, /) -> PyITask: ... + def AddWorkItem(self, TaskName, WorkItem: PyITask, /) -> None: ... + def IsOfType(self, Name, riid: PyIID, /) -> bool: ... + +class PyITaskTrigger: + def SetTrigger(self, Trigger: PyTASK_TRIGGER, /) -> None: ... + def GetTrigger(self) -> PyTASK_TRIGGER: ... + def GetTriggerString(self) -> str: ... + +class PyITaskbarlist: + def HrInit(self) -> None: ... + def AddTab(self, hwnd: int, /) -> None: ... + def DeleteTab(self, hwnd: int, /) -> None: ... + def ActivateTab(self, hwnd: int, /) -> None: ... + def SetActiveAlt(self, hwnd: int, /) -> None: ... + +class PyITransferAdviseSink: + def UpdateProgress(self, SizeCurrent, SizeTotal, FilesCurrent, FilesTotal, FoldersCurrent, FoldersTotal, /) -> None: ... + def UpdateTransferState(self, State, /) -> None: ... + def ConfirmOverwrite(self, Source: PyIShellItem, DestParent: PyIShellItem, Name, /): ... + def ConfirmEncryptionLoss(self, Source: PyIShellItem, /): ... + def FileFailure(self, Item: PyIShellItem, ItemName, Error, /) -> tuple[Incomplete, Incomplete]: ... + def SubStreamFailure(self, Item: PyIShellItem, StreamName, Error, /): ... + def PropertyFailure(self, Item: PyIShellItem, key: PyPROPERTYKEY, Error, /): ... + +class PyITransferDestination: + def Advise(self, Sink: PyITransferAdviseSink, /): ... + def Unadvise(self, Cookie, /) -> None: ... + def CreateItem( + self, Name, Attributes, Size, Flags, riidItem: PyIID, riidResources: PyIID, / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +class PyITransferMediumItem: ... + +class PyITransferSource: + def Advise(self, Sink: PyITransferAdviseSink, /): ... + def Unadvise(self, Cookie, /) -> None: ... + def SetProperties(self, proparray: PyIPropertyChangeArray, /) -> None: ... + def OpenItem(self, Item: PyIShellItem, flags, riid: PyIID, /) -> tuple[Incomplete, PyIShellItemResources]: ... + def MoveItem(self, Item: PyIShellItem, ParentDst: PyIShellItem, NameDst, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def RecycleItem(self, Source: PyIShellItem, ParentDest: PyIShellItem, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def RemoveItem(self, Source: PyIShellItem, flags, /): ... + def RenameItem(self, Source: PyIShellItem, NewName, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def LinkItem(self, Source: PyIShellItem, ParentDest: PyIShellItem, NewName, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def ApplyPropertiesToItem(self, Source: PyIShellItem, /) -> PyIShellItem: ... + def GetDefaultDestinationName(self, Source: PyIShellItem, ParentDest: PyIShellItem, /): ... + def EnterFolder(self, ChildFolderDest: PyIShellItem, /): ... + def LeaveFolder(self, ChildFolderDest: PyIShellItem, /): ... + +class PyITypeComp: + def Bind(self, szName: str, wflags: int = ..., /): ... + def BindType(self, szName: str, /): ... + +class PyITypeInfo: + def GetContainingTypeLib(self) -> tuple[PyITypeLib, Incomplete]: ... + def GetDocumentation(self, memberId, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetFuncDesc(self, memberId, /) -> FUNCDESC: ... + def GetImplTypeFlags(self, index, /): ... + def GetIDsOfNames(self): ... + def GetNames(self, memberId, /): ... + def GetTypeAttr(self) -> TYPEATTR: ... + def GetRefTypeInfo(self, hRefType, /) -> PyITypeInfo: ... + def GetRefTypeOfImplType(self, hRefType, /): ... + def GetVarDesc(self, memberId, /) -> VARDESC: ... + def GetTypeComp(self) -> PyITypeComp: ... + +class PyITypeLib: + def GetDocumentation(self, index, /): ... + def GetLibAttr(self) -> TLIBATTR: ... + def GetTypeComp(self) -> PyITypeComp: ... + def GetTypeInfo(self, index, /) -> PyITypeInfo: ... + def GetTypeInfoCount(self): ... + def GetTypeInfoOfGuid(self, iid: PyIID, /) -> PyITypeInfo: ... + def GetTypeInfoType(self, index, /): ... + +class PyIUniformResourceLocator: + def GetURL(self): ... + def SetURL(self, URL, InFlags: int = ..., /) -> None: ... + def InvokeCommand(self, Verb, Flags: int = ..., hwndParent: int = ..., /): ... + +@final +class PyIUnknown: + def QueryInterface(self, iid, useIID: Incomplete | None = ..., /) -> PyIUnknown: ... + +class PyIViewObject: + def Draw( + self, + dwDrawAspect, + lindex, + aspectFlags, + hdcTargetDev, + hdcDraw, + arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + arg1: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + funcContinue, + obContinue, + /, + ) -> None: ... + def GetColorSet(self, dwDrawAspect, lindex, aspectFlags, hicTargetDev, /) -> None: ... + def Freeze(self, dwDrawAspect, lindex, aspectFlags, /) -> None: ... + def Unfreeze(self, dwFreeze, /) -> None: ... + def SetAdvise(self, aspects, advf, pAdvSink, /) -> None: ... + def GetAdvise(self) -> None: ... + +class PyIViewObject2: + def GetExtent(self, dwDrawAspect, lindex, targetDevice, /) -> None: ... + +class PyMAPINAMEIDArray: ... +class PyOLEMENUGROUPWIDTHS: ... +class PyPROPERTYKEY: ... + +@final +class PyPROPVARIANT: + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def __new__(self, Value: tuple[int, int], Type=...) -> Self: ... + @overload + def __new__(self, Value, Type=...) -> Self: ... + + @property + def vt(self): ... + def GetValue(self): ... + def ToString(self): ... + def ChangeType(self, Type, Flags: int = ..., /) -> PyPROPVARIANT: ... + +class PySAndRestriction: ... +class PySBinaryArray: ... +class PySBitMaskRestriction: ... +class PySContentRestriction: ... +class PySExistRestriction: ... +class PySHELL_ITEM_RESOURCE: ... +class PySNotRestriction: ... +class PySOrRestriction: ... +class PySPropTagArray: ... +class PySPropValue: ... +class PySPropValueArray: ... +class PySPropertyRestriction: ... +class PySRestriction: ... +class PySRow: ... +class PySRowSet: ... +class PySSortOrderItem: ... +class PySSortOrderSet: ... + +class PySTGMEDIUM: + @property + def tymed(self): ... + @property + def data(self): ... + @property + def data_handle(self): ... + def set(self, tymed, data, /) -> None: ... + +class PyTASK_TRIGGER: ... +class RTF_WCSINFO: ... +class SHFILEINFO: ... +class SHFILEOPSTRUCT: ... +class SI_ACCESS: ... +class SI_INHERIT_TYPE: ... +class SI_OBJECT_INFO: ... + +STATSTG: TypeAlias = tuple[str | None, int, int, TimeType, TimeType, TimeType, int, int, PyIID, int, int] + +class TLIBATTR: ... + +class TYPEATTR: + @property + def iid(self) -> PyIID: ... + @property + def lcid(self): ... + @property + def memidConstructor(self): ... + @property + def memidDestructor(self): ... + @property + def cbSizeInstance(self): ... + @property + def typekind(self): ... + @property + def cFuncs(self): ... + @property + def cVars(self): ... + @property + def cImplTypes(self): ... + @property + def cbSizeVft(self): ... + @property + def cbAlignment(self): ... + @property + def wTypeFlags(self): ... + @property + def wMajorVerNum(self): ... + @property + def wMinorVerNum(self): ... + @property + def tdescAlias(self) -> TYPEDESC: ... + @property + def idldeskType(self) -> IDLDESC: ... + +class TYPEDESC: ... + +class VARDESC: + @property + def memid(self): ... + @property + def value(self): ... + @property + def elemdescVar(self) -> ELEMDESC: ... + @property + def varFlags(self): ... + @property + def varkind(self): ... + +class CHARFORMAT: ... +class CREATESTRUCT: ... +class LV_COLUMN: ... +class LV_ITEM: ... +class PARAFORMAT: ... +class PyAssocCObject: ... + +class PyAssocObject: + def AttachObject(self) -> None: ... + def GetAttachedObject(self): ... + +class PyCBitmap: + def CreateCompatibleBitmap(self, dc: PyCDC, width: int, height: int, /) -> None: ... + def GetSize(self) -> tuple[Incomplete, Incomplete]: ... + def GetHandle(self, *args: Unused) -> int: ... + def LoadBitmap(self, idRes, obDLL: PyDLL | None = ..., /) -> None: ... + def LoadBitmapFile(self, fileObject, /) -> None: ... + def LoadPPMFile(self, fileObject, cols, rows, /) -> None: ... + def Paint( + self, + dcObject: PyCDC, + arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + arg1: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + /, + ) -> None: ... + def GetInfo(self): ... + + @overload + def GetBitmapBits(self, asString: Literal[False] = False, /) -> tuple[int, ...]: ... + @overload + def GetBitmapBits(self, asString: Literal[True], /) -> bytes: ... + @overload + def GetBitmapBits(self, asString: bool, /) -> tuple[int, ...] | bytes: ... + + def SaveBitmapFile(self, dcObject: PyCDC, Filename: str, /): ... + +class PyCBrush: + def CreateSolidBrush(self, i: int) -> None: ... + def GetSafeHandle(self): ... + +class PyCButton: + def CreateWindow( + self, caption: str, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def GetBitmap(self): ... + def SetBitmap(self, hBitmap: int = ..., /): ... + def GetCheck(self): ... + def SetCheck(self, idCheck, /) -> None: ... + def GetState(self): ... + def SetState(self, bHighlight, /): ... + def GetButtonStyle(self): ... + def SetButtonStyle(self, style, bRedraw: int = ..., /): ... + +class PyCCmdTarget: + def BeginWaitCursor(self) -> None: ... + def EndWaitCursor(self) -> None: ... + def HookCommand(self, obHandler, _id, /): ... + def HookCommandUpdate(self, obHandler, _id, /): ... + def HookOleEvent(self): ... + def HookNotify(self, obHandler, _id, /): ... + def RestoreWaitCursor(self) -> None: ... + +class PyCCmdUI: + @property + def m_nIndex(self): ... + @property + def m_nID(self): ... + @property + def m_pMenu(self) -> PyCMenu: ... + @property + def m_pSubMenu(self) -> PyCMenu: ... + def Enable(self, bEnable: int = ..., /) -> None: ... + def SetCheck(self, state: int = ..., /) -> None: ... + def SetRadio(self, bOn: int = ..., /) -> None: ... + def SetText(self, text: str, /) -> None: ... + def ContinueRouting(self) -> None: ... + +class PyCColorDialog: + def GetColor(self): ... + def DoModal(self): ... + def GetSavedCustomColors(self): ... + def SetCurrentColor(self, color, /) -> None: ... + def SetCustomColors(self, colors: Sequence[int], /) -> None: ... + def GetCustomColors(self) -> tuple[Incomplete, ...]: ... + +class PyCComboBox: + def AddString(self, _object, /): ... + def DeleteString(self, pos, /): ... + def Dir(self, attr, wild: str, /): ... + def GetCount(self): ... + def GetCurSel(self): ... + def GetEditSel(self): ... + def GetExtendedUI(self): ... + def GetItemData(self, item, /): ... + def GetItemValue(self, item, /): ... + def GetLBText(self, index, /) -> str: ... + def GetLBTextLen(self, index, /): ... + def InsertString(self, pos, _object, /): ... + def LimitText(self, _max, /): ... + def ResetContent(self) -> None: ... + def SelectString(self, after, string: str, /) -> None: ... + def SetCurSel(self, index, /) -> None: ... + def SetEditSel(self, start, end, /) -> None: ... + def SetExtendedUI(self, bExtended: int = ..., /) -> None: ... + def SetItemData(self, item, Data, /): ... + def SetItemValue(self, item, data, /): ... + def ShowDropDown(self, bShowIt: int = ..., /) -> None: ... + +class PyCCommonDialog: ... +class PyCControl: ... + +class PyCControlBar: + @property + def dockSite(self) -> PyCFrameWnd: ... + @property + def dockBar(self) -> PyCWnd: ... + @property + def dockContext(self) -> PyCDockContext: ... + @property + def dwStyle(self): ... + @property + def dwDockStyle(self): ... + def CalcDynamicLayout(self, length, dwMode, /): ... + def CalcFixedLayout(self, bStretch, bHorz, /): ... + def EnableDocking(self, style, /) -> None: ... + def EraseNonClient(self) -> None: ... + def GetBarStyle(self): ... + def GetCount(self): ... + def GetDockingFrame(self) -> PyCFrameWnd: ... + def IsFloating(self) -> bool: ... + def SetBarStyle(self, style, /) -> None: ... + def ShowWindow(self): ... + +class PyCCtrlView: + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCDC: + def AbortDoc(self) -> None: ... + def Arc( + self, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + pointStart: tuple[Incomplete, Incomplete], + pointEnd: tuple[Incomplete, Incomplete], + /, + ) -> None: ... + def BeginPath(self) -> None: ... + def BitBlt( + self, destPos: tuple[int, int], size: tuple[int, int], dc: PyCDC, srcPos: tuple[int, int], rop: int, / + ) -> None: ... + def Chord( + self, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + pointStart: tuple[Incomplete, Incomplete], + pointEnd: tuple[Incomplete, Incomplete], + /, + ) -> None: ... + def CreateCompatibleDC(self, dcFrom: PyCDC | None = ..., /) -> PyCDC: ... + def CreatePrinterDC(self, printerName: str | None = ..., /) -> None: ... + def DeleteDC(self) -> None: ... + def DPtoLP(self, point: tuple[Incomplete, Incomplete], x, y, /) -> tuple[Incomplete, Incomplete]: ... + def Draw3dRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], colorTopLeft, colorBotRight, /) -> None: ... + def DrawFocusRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def DrawFrameControl(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], typ, state, /) -> None: ... + def DrawIcon(self, point: tuple[Incomplete, Incomplete], hIcon: int, /) -> None: ... + def DrawText( + self, s: str, _tuple: tuple[Incomplete, Incomplete, Incomplete, Incomplete], _format, / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def Ellipse(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def EndDoc(self) -> None: ... + def EndPage(self) -> None: ... + def EndPath(self) -> None: ... + def ExtTextOut( + self, + _int, + _int1, + _int2, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + string, + _tuple: tuple[tuple[Incomplete, Incomplete], ...], + /, + ) -> None: ... + def FillPath(self) -> None: ... + def FillRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], brush: PyCBrush, /) -> None: ... + def FillSolidRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], color, /) -> None: ... + def FrameRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], brush: PyCBrush, /) -> None: ... + def GetBrushOrg(self) -> tuple[Incomplete, Incomplete]: ... + def GetClipBox(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetCurrentPosition(self) -> tuple[Incomplete, Incomplete]: ... + def GetDeviceCaps(self, index, /): ... + def GetHandleAttrib(self): ... + def GetHandleOutput(self): ... + def GetMapMode(self): ... + def GetNearestColor(self, color, /): ... + def GetPixel(self, x, y, /) -> None: ... + def GetSafeHdc(self) -> int: ... + def GetTextExtent(self, text: str, /) -> tuple[Incomplete, Incomplete]: ... + def GetTextExtentPoint(self, text: str, /) -> tuple[Incomplete, Incomplete]: ... + def GetTextFace(self) -> str: ... + def GetTextMetrics(self): ... + def GetViewportExt(self) -> tuple[Incomplete, Incomplete]: ... + def GetViewportOrg(self) -> tuple[Incomplete, Incomplete]: ... + def GetWindowExt(self) -> tuple[Incomplete, Incomplete]: ... + def GetWindowOrg(self) -> tuple[Incomplete, Incomplete]: ... + def IntersectClipRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def IsPrinting(self) -> bool: ... + def LineTo(self, point: tuple[Incomplete, Incomplete], x, y, /) -> None: ... + def LPtoDP(self, point: tuple[Incomplete, Incomplete], x, y, /) -> tuple[Incomplete, Incomplete]: ... + def MoveTo(self, point: tuple[Incomplete, Incomplete], x, y, /) -> tuple[Incomplete, Incomplete]: ... + def OffsetWindowOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def OffsetViewportOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def PatBlt(self, destPos: tuple[Incomplete, Incomplete], size: tuple[Incomplete, Incomplete], rop, /) -> None: ... + def Pie(self, x1, y1, x2, y2, x3, y3, x4, y4, /) -> None: ... + def PolyBezier(self) -> None: ... + def Polygon(self) -> None: ... + def Polyline(self, points: list[tuple[Incomplete, Incomplete]], /) -> None: ... + def RealizePalette(self): ... + def Rectangle(self): ... + def RectVisible(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /): ... + def RestoreDC(self, saved, /) -> None: ... + def SaveDC(self): ... + def ScaleWindowExt(self) -> tuple[Incomplete, Incomplete]: ... + def ScaleViewportExt(self) -> tuple[Incomplete, Incomplete]: ... + def SelectClipRgn(self): ... + def SelectObject(self, ob: PyCBitmap, /) -> PyCBitmap: ... + def SetBkColor(self, color, /): ... + def SetBkMode(self, mode, /): ... + def SetBrushOrg(self, point: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetGraphicsMode(self, mode, /): ... + def SetMapMode(self, newMode, /): ... + def SetPixel(self, x, y, color, /) -> None: ... + def SetPolyFillMode(self, point: tuple[Incomplete, Incomplete], /): ... + def SetROP2(self, mode, /): ... + def SetTextAlign(self, newFlags, /): ... + def SetTextColor(self, color, /): ... + def SetWindowExt(self, size: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetWindowOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetViewportExt(self, size: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetViewportOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetWorldTransform(self): ... + def StartDoc(self, docName: str, outputFile: str, /) -> None: ... + def StartPage(self) -> None: ... + def StretchBlt( + self, + destPos: tuple[Incomplete, Incomplete], + size: tuple[Incomplete, Incomplete], + dc: PyCDC, + srcPos: tuple[Incomplete, Incomplete], + size1: tuple[Incomplete, Incomplete], + rop, + /, + ) -> None: ... + def StrokeAndFillPath(self) -> None: ... + def StrokePath(self) -> None: ... + def TextOut(self, _int, _int1, string, /) -> None: ... + +class PyCDialog: + def CreateWindow(self, obParent: PyCWnd | None = ..., /) -> None: ... + def DoModal(self): ... + def EndDialog(self, result, /) -> None: ... + def GotoDlgCtrl(self, control: PyCWnd, /) -> None: ... + def MapDialogRect( + self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], / + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def OnCancel(self) -> None: ... + def OnOK(self) -> None: ... + def OnInitDialog(self): ... + +class PyCDialogBar: + def CreateWindow(self, parent: PyCWnd, template: PyResourceId, style, _id, /) -> None: ... + +class PyCDocTemplate: + def DoCreateDoc(self, fileName: str | None = ..., /) -> PyCDocument: ... + def FindOpenDocument(self, fileName: str, /) -> PyCDocument: ... + def GetDocString(self, docIndex, /) -> str: ... + def GetDocumentlist(self): ... + def GetResourceID(self) -> None: ... + def GetSharedMenu(self) -> PyCMenu: ... + def InitialUpdateFrame( + self, frame: PyCFrameWnd | None = ..., doc: PyCDocument | None = ..., bMakeVisible: int = ..., / + ) -> None: ... + def SetContainerInfo(self, _id, /) -> None: ... + def SetDocStrings(self, docStrings: str, /) -> None: ... + def OpenDocumentFile(self, filename: str, bMakeVisible: int = ..., /) -> PyCDocument | None: ... + +class PyCDockContext: + @property + def ptLast(self) -> tuple[Incomplete, Incomplete]: ... + @property + def rectLast(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def sizeLast(self) -> tuple[Incomplete, Incomplete]: ... + @property + def bDitherLast(self): ... + @property + def rectDragHorz(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def rectDragVert(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def rectFrameDragHorz(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def rectFrameDragVert(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def dwDockStyle(self): ... + @property + def dwOverDockStyle(self): ... + @property + def dwStyle(self): ... + @property + def bFlip(self): ... + @property + def bForceFrame(self): ... + @property + def bDragging(self): ... + @property + def nHitTest(self): ... + @property + def uMRUDockID(self): ... + @property + def rectMRUDockPos(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def dwMRUFloatStyle(self): ... + @property + def ptMRUFloatPos(self) -> tuple[Incomplete, Incomplete]: ... + def EndDrag(self): ... + def StartDrag(self, pt: tuple[Incomplete, Incomplete], /): ... + def EndResize(self): ... + def StartResize(self, hittest, pt: tuple[Incomplete, Incomplete], /): ... + def ToggleDocking(self): ... + +class PyCDocument: + def DeleteContents(self) -> None: ... + def DoSave(self, fileName: str, bReplace: int = ..., /) -> None: ... + def DoFileSave(self) -> None: ... + def GetDocTemplate(self) -> PyCDocTemplate: ... + def GetAllViews(self) -> list[Incomplete]: ... + def GetFirstView(self) -> PyCView: ... + def GetPathName(self) -> str: ... + def GetTitle(self) -> str: ... + def IsModified(self) -> bool: ... + def OnChangedViewlist(self) -> None: ... + def OnCloseDocument(self) -> None: ... + def OnNewDocument(self) -> None: ... + def OnOpenDocument(self, pathName: str, /) -> None: ... + def OnSaveDocument(self, pathName: str, /) -> None: ... + def SetModifiedFlag(self, bModified: int = ..., /) -> None: ... + def SaveModified(self): ... + def SetPathName(self, path: str, /) -> None: ... + def SetTitle(self, title: str, /) -> None: ... + def UpdateAllViews(self, sender: PyCView, hint: Incomplete | None = ..., /) -> None: ... + +class PyCEdit: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def Clear(self): ... + def Copy(self) -> None: ... + def Cut(self) -> None: ... + def FmtLines(self, bAddEOL, /): ... + def GetFirstVisibleLine(self): ... + def GetSel(self) -> tuple[Incomplete, Incomplete]: ... + def GetLine(self, lineNo, /): ... + def GetLineCount(self): ... + def LimitText(self, nChars: int = ..., /) -> None: ... + def LineFromChar(self, charNo: int = ..., /): ... + def LineIndex(self, lineNo: int = ..., /): ... + def LineScroll(self, nLines, nChars: int = ..., /): ... + def Paste(self) -> None: ... + def ReplaceSel(self, text: str, /) -> None: ... + def SetReadOnly(self, bReadOnly: int = ..., /) -> None: ... + def SetSel(self, start, end, arg, bNoScroll1, bNoScroll: int = ..., /) -> None: ... + +class PyCEditView: + def IsModified(self) -> bool: ... + def LoadFile(self, fileName: str, /) -> None: ... + def SetModifiedFlag(self, bModified: int = ..., /) -> None: ... + def GetEditCtrl(self): ... + def PreCreateWindow(self, createStruct, /): ... + def SaveFile(self, fileName: str, /) -> None: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCFileDialog: + def GetPathName(self) -> str: ... + def GetFileName(self) -> str: ... + def GetFileExt(self) -> str: ... + def GetFileTitle(self) -> str: ... + def GetPathNames(self) -> str: ... + def GetReadOnlyPref(self): ... + def SetOFNTitle(self, title: str, /) -> None: ... + def SetOFNInitialDir(self, title: str, /) -> None: ... + +class PyCFont: + def GetSafeHandle(self): ... + +class PyCFontDialog: + def DoModal(self): ... + def GetCurrentFont(self): ... + def GetCharFormat(self): ... + def GetColor(self): ... + def GetFaceName(self) -> str: ... + def GetStyleName(self) -> str: ... + def GetSize(self): ... + def GetWeight(self): ... + def IsStrikeOut(self) -> bool: ... + def IsUnderline(self) -> bool: ... + def IsBold(self) -> bool: ... + def IsItalic(self) -> bool: ... + +class PyCFormView: + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCFrameWnd: + def BeginModalState(self) -> None: ... + def CreateWindow( + self, + wndClass: str, + title: str, + style, + PyCWnd, + menuId, + styleEx, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., + createContext: Incomplete | None = ..., + /, + ): ... + def EndModalState(self) -> None: ... + def DockControlBar( + self, controlBar: PyCControlBar, arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], dockBarId: int = ..., / + ) -> None: ... + def EnableDocking(self, style, /) -> None: ... + def FloatControlBar(self, controlBar: PyCControlBar, arg: tuple[Incomplete, Incomplete], style, /) -> None: ... + def GetActiveDocument(self) -> PyCDocument: ... + def GetControlBar(self, _id, /) -> PyCControlBar: ... + def GetMessageString(self, _id, /) -> str: ... + def GetMessageBar(self) -> PyCWnd: ... + def IsTracking(self) -> bool: ... + def InModalState(self): ... + def LoadAccelTable(self, _id: PyResourceId, /) -> None: ... + def LoadFrame( + self, idResource, style: int = ..., wndParent: PyCWnd | None = ..., context: Incomplete | None = ..., / + ) -> None: ... + def LoadBarState(self, profileName: str, /) -> None: ... + def PreCreateWindow(self, createStruct, /): ... + def SaveBarState(self, profileName: str, /) -> None: ... + def ShowControlBar(self, controlBar: PyCControlBar, bShow, bDelay, /) -> None: ... + def RecalcLayout(self, bNotify: int = ..., /) -> None: ... + def GetActiveView(self) -> PyCView: ... + def OnBarCheck(self, _id, /): ... + def OnUpdateControlBarMenu(self, cmdUI: PyCCmdUI, /): ... + def SetActiveView(self, view: PyCView, bNotify: int = ..., /) -> None: ... + +class PyCGdiObject: ... + +class PyCImagelist: + def Add(self, arg: tuple[Incomplete, Incomplete], bitmap, color, hIcon, /): ... + def Destroy(self) -> None: ... + def DeleteImagelist(self) -> None: ... + def GetBkColor(self): ... + def GetSafeHandle(self): ... + def GetImageCount(self): ... + def GetImageInfo(self, index, /): ... + def SetBkColor(self, color, /) -> None: ... + +class PyClistBox: + def AddString(self, _object, /): ... + def DeleteString(self, pos, /): ... + def Dir(self, attr, wild: str, /): ... + def GetCaretIndex(self): ... + def GetCount(self): ... + def GetCurSel(self): ... + def GetItemData(self, item, /): ... + def GetItemValue(self, item, /): ... + def GetSel(self, index, /): ... + def GetSelCount(self): ... + def GetSelItems(self): ... + def GetSelTextItems(self): ... + def GetTopIndex(self): ... + def GetText(self, index, /) -> str: ... + def GetTextLen(self, index, /): ... + def InsertString(self, pos, _object, /): ... + def ResetContent(self) -> None: ... + def SetCaretIndex(self, index, bScroll: int = ..., /) -> None: ... + def SelectString(self, after, string: str, /) -> None: ... + def SelItemRange(self, bSel, start, end, /) -> None: ... + def SetCurSel(self, index, /) -> None: ... + def SetItemData(self, item, Data, /): ... + def SetItemValue(self, item, data, /): ... + def SetSel(self, index, bSel: int = ..., /) -> None: ... + def SetTabStops(self, eachTabStop, tabStops, /) -> None: ... + def SetTopIndex(self, index, /) -> None: ... + +class PyClistCtrl: + def Arrange(self, code, /) -> None: ... + def CreateWindow(self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], PyCWnd, _id, /) -> None: ... + def DeleteAllItems(self) -> None: ... + def DeleteItem(self, item, /) -> None: ... + def GetTextColor(self): ... + def SetTextColor(self, color, /) -> None: ... + def GetBkColor(self): ... + def SetBkColor(self, color, /) -> None: ... + def GetItem(self, item, sub, /) -> LV_ITEM: ... + def GetItemCount(self): ... + def GetItemRect(self, item, bTextOnly, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetEditControl(self) -> PyCEdit: ... + def EditLabel(self, item, /) -> PyCEdit: ... + def EnsureVisible(self, item, bPartialOK, /): ... + def CreateDragImage(self, item, /) -> tuple[PyCImagelist, Incomplete, Incomplete]: ... + def GetImagelist(self, nImagelist, /) -> PyCImagelist: ... + def GetNextItem(self, item, flags, /): ... + def InsertColumn(self, colNo, item: LV_COLUMN, /): ... + def InsertItem(self, item: LV_ITEM, item1, text, image, item2, text1, /): ... + def SetImagelist(self, imagelist: PyCImagelist, imageType, /): ... + def GetColumn(self, column, /) -> LV_COLUMN: ... + def GetTextBkColor(self): ... + def SetTextBkColor(self, color, /) -> None: ... + def GetTopIndex(self): ... + def GetCountPerPage(self): ... + def GetSelectedCount(self): ... + def SetItem(self, item: LV_ITEM, /): ... + def SetItemState(self, item, state, mask, /): ... + def GetItemState(self, item, mask, /): ... + def SetItemData(self, item, Data, /): ... + def GetItemData(self, item, /): ... + def SetItemCount(self, count, /) -> None: ... + def SetItemText(self, item, sub, text: str, /): ... + def GetItemText(self, item, sub, /): ... + def RedrawItems(self, first, first1, /): ... + def Update(self, item, /) -> None: ... + def SetColumn(self, colNo, item: LV_COLUMN, /): ... + def DeleteColumn(self, first, /): ... + def GetColumnWidth(self, first, /): ... + def SetColumnWidth(self, first, first1, /): ... + def GetStringWidth(self, first, /): ... + def HitTest(self, arg, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetItemPosition(self, item, /) -> tuple[Incomplete, Incomplete]: ... + +class PyClistView: + def PreCreateWindow(self, createStruct, /): ... + def GetlistCtrl(self) -> PyClistCtrl: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCMDIChildWnd: + def ActivateFrame(self, cmdShow: int = ..., /) -> None: ... + def CreateWindow( + self, + wndClass: str, + title: str, + style, + PyCWnd, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., + createContext: Incomplete | None = ..., + /, + ): ... + def GetMDIFrame(self) -> None: ... + def MDIActivate(self, cmdShow: int = ..., /) -> None: ... + def PreCreateWindow(self, createStruct, /): ... + def PreTranslateMessage(self) -> None: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + def OnClose(self) -> None: ... + +class PyCMDIFrameWnd: + def GetMDIClient(self) -> PyCMDIFrameWnd: ... + def MDIGetActive(self) -> tuple[PyCMDIChildWnd, Incomplete]: ... + def MDIActivate(self, window: PyCWnd, /) -> PyCMDIFrameWnd: ... + def MDINext(self, fNext: int = ..., /) -> None: ... + def PreCreateWindow(self, createStruct, /): ... + def PreTranslateMessage(self) -> None: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + def OnContextHelp(self): ... + def OnClose(self) -> None: ... + +class PyCMenu: + def AppendMenu(self, flags, _id: int = ..., value: str | None = ..., /) -> None: ... + def DeleteMenu(self, _id, flags, /) -> str: ... + def EnableMenuItem(self, _id, flags, /): ... + def GetMenuItemCount(self): ... + def GetMenuItemID(self, pos, /): ... + def GetMenuString(self, _id, arg, /) -> str: ... + def GetSubMenu(self, pos, /) -> PyCMenu: ... + def InsertMenu(self, pos, flags, _id: PyCMenu | int = ..., value: str | None = ..., /) -> None: ... + def ModifyMenu(self, pos, flags, _id: int = ..., value: str | None = ..., /) -> None: ... + def TrackPopupMenu(self, x_y: _TwoIntSequence, flags: int = ..., owner: PyCWnd = ..., /) -> None: ... + +class PyCOleClientItem: + def CreateNewItem(self) -> None: ... + def Close(self) -> None: ... + def DoVerb(self) -> None: ... + def Draw(self) -> None: ... + def GetActiveView(self) -> PyCView: ... + def GetDocument(self) -> PyCDocument: ... + def GetInPlaceWindow(self) -> PyCWnd: ... + def GetItemState(self) -> None: ... + def GetObject(self) -> PyIUnknown: ... + def GetStorage(self) -> None: ... + def OnActivate(self) -> None: ... + def OnChange(self) -> None: ... + def OnChangeItemPosition(self): ... + def OnDeactivateUI(self): ... + def Run(self) -> None: ... + def SetItemRects(self) -> None: ... + +class PyCOleDialog: ... + +class PyCOleDocument: + def EnableCompoundFile(self, bEnable: int = ..., /) -> None: ... + def GetStartPosition(self): ... + def GetNextItem(self, pos, /) -> tuple[Incomplete, PyCOleClientItem]: ... + def GetInPlaceActiveItem(self, wnd: PyCWnd, /) -> PyCOleClientItem: ... + +class PyCOleInsertDialog: + def GetClassID(self): ... + def GetSelectionType(self): ... + def GetPathName(self): ... + +class PyCPrintDialog: ... + +class PyCPrintInfo: + def DocObject(self) -> None: ... + def GetDwFlags(self) -> None: ... + def SetDwFlags(self) -> None: ... + def GetDocOffsetPage(self) -> None: ... + def SetDocOffsetPage(self) -> None: ... + def SetPrintDialog(self) -> None: ... + def GetDirect(self) -> None: ... + def SetDirect(self) -> None: ... + def GetPreview(self) -> None: ... + def SetPreview(self) -> None: ... + def GetContinuePrinting(self) -> None: ... + def SetContinuePrinting(self) -> None: ... + def GetCurPage(self) -> None: ... + def SetCurPage(self) -> None: ... + def GetNumPreviewPages(self) -> None: ... + def SetNumPreviewPages(self) -> None: ... + def GetUserData(self) -> None: ... + def SetUserData(self) -> None: ... + def GetDraw(self) -> None: ... + def SetDraw(self) -> None: ... + def GetPageDesc(self) -> None: ... + def SetPageDesc(self) -> None: ... + def GetMinPage(self) -> None: ... + def SetMinPage(self) -> None: ... + def GetMaxPage(self) -> None: ... + def SetMaxPage(self) -> None: ... + def GetOffsetPage(self) -> None: ... + def GetFromPage(self) -> None: ... + def GetToPage(self) -> None: ... + def SetHDC(self, hdc, /) -> None: ... + def CreatePrinterDC(self) -> None: ... + def DoModal(self) -> None: ... + def GetCopies(self) -> None: ... + def GetDefaults(self) -> None: ... + def FreeDefaults(self) -> None: ... + def GetDeviceName(self) -> None: ... + def GetDriverName(self) -> None: ... + def GetDlgFromPage(self) -> None: ... + def GetDlgToPage(self) -> None: ... + def GetPortName(self) -> None: ... + def GetPrinterDC(self) -> None: ... + def PrintAll(self) -> None: ... + def PrintCollate(self) -> None: ... + def PrintRange(self) -> None: ... + def PrintSelection(self) -> None: ... + def GetHDC(self) -> None: ... + def GetFlags(self) -> None: ... + def SetFlags(self) -> None: ... + def SetFromPage(self) -> None: ... + def SetToPage(self) -> None: ... + def GetPRINTDLGMinPage(self) -> None: ... + def SetPRINTDLGMinPage(self) -> None: ... + def GetPRINTDLGCopies(self) -> None: ... + def SetPRINTDLGCopies(self) -> None: ... + +class PyCProgressCtrl: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def SetRange(self, nLower: int = ..., nUpper: int = ..., /) -> None: ... + def SetPos(self, nPos: int = ..., /): ... + def OffsetPos(self, nPos: int = ..., /): ... + def SetStep(self, nStep: int = ..., /): ... + def StepIt(self): ... + +class PyCPropertyPage: + def CancelToClose(self) -> None: ... + def OnCancel(self) -> None: ... + def OnOK(self) -> None: ... + def OnApply(self) -> None: ... + def OnReset(self) -> None: ... + def OnQueryCancel(self) -> None: ... + def OnWizardBack(self) -> None: ... + def OnWizardNext(self) -> None: ... + def OnWizardFinish(self) -> None: ... + def OnSetActive(self): ... + def OnKillActive(self): ... + def SetModified(self, bChanged: int = ..., /) -> None: ... + def SetPSPBit(self, bitMask, bitValue, /) -> None: ... + +class PyCPropertySheet: + def AddPage(self, page: PyCPropertyPage, /) -> None: ... + def CreateWindow(self, style, exStyle, parent: PyCWnd | None = ..., /) -> None: ... + def DoModal(self): ... + def EnableStackedTabs(self, stacked, /) -> PyCPropertyPage: ... + def EndDialog(self, result, /) -> None: ... + def GetActiveIndex(self): ... + def GetActivePage(self) -> PyCPropertyPage: ... + def GetPage(self, pageNo, /) -> PyCPropertyPage: ... + def GetPageIndex(self, page: PyCPropertyPage, /): ... + def GetPageCount(self): ... + def GetTabCtrl(self) -> PyCTabCtrl: ... + def OnInitDialog(self): ... + def PressButton(self, button, /) -> None: ... + def RemovePage(self, offset, page, /) -> None: ... + def SetActivePage(self, page: PyCPropertyPage, /) -> None: ... + def SetTitle(self, title: str, /) -> None: ... + def SetFinishText(self, text: str, /) -> None: ... + def SetWizardMode(self) -> None: ... + def SetWizardButtons(self, flags, /) -> None: ... + def SetPSHBit(self, bitMask, bitValue, /) -> None: ... + +class PyCRect: ... +class PyCRgn: ... + +class PyCRichEditCtrl: + def Clear(self): ... + def Copy(self) -> None: ... + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def Cut(self) -> None: ... + def FindText(self, charPos, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetCharPos(self, charPos, /): ... + def GetDefaultCharFormat(self): ... + def GetEventMask(self): ... + def GetSelectionCharFormat(self): ... + def GetFirstVisibleLine(self): ... + def GetParaFormat(self): ... + def GetSel(self) -> tuple[Incomplete, Incomplete]: ... + def GetSelText(self) -> str: ... + def GetTextLength(self): ... + def GetLine(self, lineNo, /): ... + def GetModify(self): ... + def GetLineCount(self): ... + def LimitText(self, nChars: int = ..., /) -> None: ... + def LineFromChar(self, charNo: int = ..., /): ... + def LineIndex(self, lineNo: int = ..., /): ... + def LineScroll(self, nLines, nChars: int = ..., /): ... + def Paste(self) -> None: ... + def ReplaceSel(self, text: str, /) -> None: ... + def SetBackgroundColor(self, bSysColor, cr: int = ..., /): ... + def SetDefaultCharFormat(self, charFormat, /) -> None: ... + def SetEventMask(self, eventMask, /): ... + def SetSelectionCharFormat(self, charFormat, /) -> None: ... + def SetModify(self, modified: int = ..., /) -> None: ... + def SetOptions(self, op, flags, /) -> None: ... + def SetParaFormat(self, paraFormat, /): ... + def SetReadOnly(self, bReadOnly: int = ..., /) -> None: ... + def SetSel(self, start, end, arg, /) -> None: ... + def SetSelAndCharFormat(self, charFormat, /) -> None: ... + def SetTargetDevice(self, dc: PyCDC, lineWidth, /) -> None: ... + def StreamIn(self, _format, method, /) -> tuple[Incomplete, Incomplete]: ... + def StreamOut(self, _format, method, /) -> tuple[Incomplete, Incomplete]: ... + +class PyCRichEditDoc: + def OnCloseDocument(self) -> None: ... + +class PyCRichEditDocTemplate: + def DoCreateRichEditDoc(self, fileName: str | None = ..., /) -> PyCRichEditDoc: ... + +class PyCRichEditView: + def GetRichEditCtrl(self) -> PyCRichEditCtrl: ... + def SetWordWrap(self, wordWrap, /): ... + def WrapChanged(self): ... + def SaveTextFile(self, FileName, /): ... + +class PyCScrollView: + def GetDeviceScrollPosition(self) -> tuple[Incomplete, Incomplete]: ... + def GetDC(self) -> PyCDC: ... + def GetScrollPosition(self) -> tuple[Incomplete, Incomplete]: ... + def GetTotalSize(self) -> tuple[Incomplete, Incomplete]: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + def ResizeParentToFit(self, bShrinkOnly: int = ..., /): ... + def SetScaleToFitSize(self, size: tuple[Incomplete, Incomplete], /) -> None: ... + def ScrollToPosition(self, position: tuple[Incomplete, Incomplete], /) -> None: ... + def SetScrollSizes( + self, + mapMode, + sizeTotal: tuple[Incomplete, Incomplete], + arg: tuple[Incomplete, Incomplete], + arg1: tuple[Incomplete, Incomplete], + /, + ) -> None: ... + def UpdateBars(self) -> None: ... + +class PyCSliderCtrl: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def GetLineSize(self): ... + def SetLineSize(self, nLineSize: int = ..., /): ... + def GetPageSize(self): ... + def SetPageSize(self, nPageSize: int = ..., /): ... + def GetRangeMax(self): ... + def GetRangeMin(self): ... + def GetRange(self): ... + def SetRange(self, nRangeMin: int = ..., nRangeMax: int = ..., bRedraw: int = ..., /): ... + def GetSelection(self): ... + def SetSelection(self, nRangeMin: int = ..., nRangeMax: int = ..., /): ... + def GetChannelRect(self): ... + def GetThumbRect(self): ... + def GetPos(self): ... + def SetPos(self, nPos: int = ..., /): ... + def GetNumTics(self): ... + def GetTicArray(self): ... + def GetTic(self, nTic: int = ..., /): ... + def GetTicPos(self, nTic: int = ..., /): ... + def SetTic(self, nTic: int = ..., /): ... + def SetTicFreq(self, nFreq: int = ..., /): ... + def ClearSel(self, bRedraw: int = ..., /): ... + def VerifyPos(self): ... + def ClearTics(self, bRedraw: int = ..., /): ... + +class PyCSpinButtonCtrl: + def GetPos(self): ... + def SetPos(self, pos, /): ... + def SetRange(self): ... + def SetRange32(self): ... + +class PyCSplitterWnd: # aka PyCSplitter + def GetPane(self, row, col, /) -> PyCWnd: ... + def CreateView(self, view: PyCView, row, col, arg: tuple[Incomplete, Incomplete], /) -> None: ... + def CreateStatic(self, parent: PyCSplitterWnd, rows, cols, style=..., _id=..., /) -> None: ... + def SetColumnInfo(self, column, ideal, _min, /) -> None: ... + def SetRowInfo(self, row, ideal, _min, /) -> None: ... + def IdFromRowCol(self, row, col, /) -> None: ... + def DoKeyboardSplit(self): ... + +class PyCStatusBar: + def GetPaneInfo(self, index, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetStatusBarCtrl(self) -> PyCStatusBarCtrl: ... + def SetIndicators(self, indicators, /) -> None: ... + def SetPaneInfo(self, index, _id, style, width, /) -> None: ... + +class PyCStatusBarCtrl: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def GetBorders(self) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetParts(self, nParts, /): ... + def GetRect(self, nPane, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetText(self, nPane, /): ... + def GetTextAttr(self, nPane, /): ... + def GetTextLength(self, nPane, /): ... + def SetMinHeight(self, nHeight, /) -> None: ... + def SetParts(self, coord, /) -> None: ... + def SetText(self, text: str, nPane, nType, /) -> None: ... + def SetTipText(self, nPane, text: str, /) -> None: ... + +class PyCTabCtrl: + def GetCurSel(self): ... + def GetItemCountl(self): ... + def SetCurSel(self, index, /): ... + +class PyCToolBar: + def GetButtonStyle(self, index, /) -> None: ... + def GetButtonText(self, index, /) -> str: ... + def GetItemID(self, index, /) -> None: ... + def SetButtonInfo(self, index, ID, style, imageIx, /) -> None: ... + def GetToolBarCtrl(self) -> PyCToolBarCtrl: ... + def LoadBitmap(self, _id: PyResourceId, /) -> None: ... + def LoadToolBar(self, _id: PyResourceId, /) -> None: ... + def SetBarStyle(self, style, /) -> None: ... + def SetBitmap(self, hBitmap, /) -> None: ... + def SetButtons(self, buttons, numButtons, /) -> None: ... + def SetButtonStyle(self, index, style, /) -> None: ... + def SetHeight(self, height, /) -> None: ... + def SetSizes(self, sizeButton: tuple[Incomplete, Incomplete], sizeButton1: tuple[Incomplete, Incomplete], /) -> None: ... + +class PyCToolBarCtrl: + def AddBitmap(self, numButtons, bitmap, /): ... + def AddButtons(self): ... + def AddStrings(self, strings, /): ... + def AutoSize(self) -> None: ... + def CheckButton(self, nID, bCheck: int = ..., /): ... + def CommandToIndex(self, nID, /): ... + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def Customize(self) -> None: ... + def DeleteButton(self, nID, /) -> None: ... + def EnableButton(self, nID, bEnable: int = ..., /) -> None: ... + def GetBitmapFlags(self): ... + def GetButton(self, nID, /): ... + def GetButtonCount(self): ... + def GetItemRect(self, nID, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetRows(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def HideButton(self, nID, bEnable: int = ..., /) -> None: ... + def Indeterminate(self, nID, bEnable: int = ..., /) -> None: ... + def InsertButton(self, nID, button: PyCToolBarCtrl, /): ... + def IsButtonChecked(self, nID, /) -> bool: ... + def IsButtonEnabled(self, nID, /) -> bool: ... + def IsButtonHidden(self, nID, /) -> bool: ... + def IsButtonIndeterminate(self, nID, /) -> bool: ... + def IsButtonPressed(self, nID, /) -> bool: ... + def PressButton(self, nID, bEnable: int = ..., /) -> None: ... + def SetBitmapSize(self, width1, height1, width: int = ..., height: int = ..., /) -> None: ... + def SetButtonSize(self, width1, height1, width: int = ..., height: int = ..., /) -> None: ... + def SetCmdID(self, nIndex, nID, /) -> None: ... + def SetRows(self, nRows, bLarger, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + +class PyCToolTipCtrl: + def CreateWindow(self, parent: PyCWnd, style, /) -> None: ... + def UpdateTipText(self, text: str, wnd: PyCWnd, _id, /) -> None: ... + def AddTool( + self, wnd: PyCWnd, text: str, _id, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., / + ) -> None: ... + def SetMaxTipWidth(self, width, /): ... + +class PyCTreeCtrl: + def CreateWindow(self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], PyCWnd, _id, /) -> None: ... + def GetCount(self): ... + def GetIndent(self): ... + def SetIndent(self, indent, /) -> None: ... + def GetImagelist(self, nImagelist, /) -> PyCImagelist: ... + def SetImagelist(self, imagelist: PyCImagelist, imageType, /): ... + def GetNextItem(self, item, code, /): ... + def ItemHasChildren(self, item, /): ... + def GetChildItem(self, item, /): ... + def GetNextSiblingItem(self, item, /): ... + def GetPrevSiblingItem(self, item, /): ... + def GetParentItem(self, item, /): ... + def GetFirstVisibleItem(self): ... + def GetNextVisibleItem(self, item, /): ... + def GetSelectedItem(self): ... + def GetDropHilightItem(self): ... + def GetRootItem(self): ... + def GetToolTips(self): ... + def GetItem(self, item, arg, /) -> TV_ITEM: ... + def SetItem(self, item: TV_ITEM, /): ... + def GetItemState(self, item, stateMask, /) -> tuple[Incomplete, Incomplete]: ... + def SetItemState(self, item, state, stateMask, /) -> None: ... + def GetItemImage(self, item, /) -> tuple[Incomplete, Incomplete]: ... + def SetItemImage(self, item, iImage, iSelectedImage, /) -> None: ... + def SetItemText(self, item, text: str, /): ... + def GetItemText(self, item, /): ... + def GetItemData(self, item, /): ... + def SetItemData(self, item, Data, /): ... + def GetItemRect(self, item, bTextOnly, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetEditControl(self) -> PyCEdit: ... + def GetVisibleCount(self): ... + def InsertItem( + self, + hParent, + hInsertAfter, + item: TV_ITEM, + mask, + text, + image, + selectedImage, + state, + stateMask, + lParam, + parent, + parent1, + text1, + image1, + selectedImage1, + parent2, + insertAfter, + text2, + parent3, + parent4, + /, + ): ... + def DeleteItem(self, item, /) -> None: ... + def DeleteAllItems(self): ... + def Expand(self, item, code, /) -> None: ... + def Select(self, item, code, /) -> None: ... + def SelectItem(self, item, /) -> None: ... + def SelectDropTarget(self, item, /) -> None: ... + def SelectSetFirstVisible(self, item, /) -> None: ... + def EditLabel(self, item, /) -> PyCEdit: ... + def CreateDragImage(self, item, /) -> PyCImagelist: ... + def SortChildren(self, item, /) -> None: ... + def EnsureVisible(self, item, /): ... + def HitTest(self, arg, /) -> tuple[Incomplete, Incomplete]: ... + +class PyCTreeView: + def PreCreateWindow(self, createStruct, /): ... + def GetTreeCtrl(self) -> PyCTreeCtrl: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCView: + def CreateWindow(self, parent: PyCWnd, arg, arg1, arg2: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def GetDocument(self) -> PyCDocument: ... + def OnActivateView(self, activate, activateView: PyCView, DeactivateView: PyCView, /): ... + def OnInitialUpdate(self) -> None: ... + def OnMouseActivate(self, wnd: PyCWnd, hittest, message, /): ... + def PreCreateWindow(self, createStruct, /): ... + def OnFilePrint(self) -> None: ... + def DoPreparePrinting(self): ... + def OnBeginPrinting(self) -> None: ... + def OnEndPrinting(self) -> None: ... + +class PyCWinApp: + def AddDocTemplate(self, template: PyCDocTemplate | DocTemplate, /) -> None: ... + def FindOpenDocument(self, fileName: str, /) -> PyCDocument: ... + def GetDocTemplatelist(self) -> list[Incomplete]: ... + def InitDlgInstance(self, dialog: PyCDialog, /) -> None: ... + def LoadCursor(self, cursorId: PyResourceId, /): ... + def LoadStandardCursor(self, cursorId: PyResourceId, /): ... + def LoadOEMCursor(self, cursorId, /): ... + def LoadIcon(self, idResource: int, /) -> int: ... + def LoadStandardIcon(self, resourceName: PyResourceId, /): ... + def OpenDocumentFile(self, fileName: str, /) -> PyCDocument | None: ... + def OnFileNew(self) -> None: ... + def OnFileOpen(self) -> None: ... + def RemoveDocTemplate(self, template: PyCDocTemplate | DocTemplate, /) -> None: ... + def Run(self): ... + def IsInproc(self) -> bool: ... + +class PyCWinThread: + def CreateThread(self) -> None: ... + def PumpIdle(self) -> None: ... + def PumpMessages(self) -> None: ... + def Run(self): ... + def SetMainFrame(self, mainFrame: PyCWnd, /) -> None: ... + def SetThreadPriority(self, priority: PyCWnd, /) -> None: ... + +class PyCWnd: + def ActivateFrame(self, cmdShow, /) -> None: ... + def BringWindowToTop(self) -> None: ... + def BeginPaint(self) -> tuple[PyCDC, Incomplete]: ... + def CalcWindowRect( + self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], nAdjustType, / + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def CenterWindow(self, altwin: PyCWnd | None = ..., /) -> None: ... + def CheckRadioButton(self, idFirst, idLast, idCheck, /) -> None: ... + def ChildWindowFromPoint(self, x, y, flag: int = ..., /) -> PyCWnd: ... + def ClientToScreen( + self, point: tuple[Incomplete, Incomplete], rect, / + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... + def CreateWindow( + self, + classId: str, + windowName: str, + style, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + parent: PyCWnd, + _id, + context: Incomplete | None = ..., + /, + ) -> None: ... + def CreateWindowEx( + self, + styleEx, + classId: str, + windowName: str, + style, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + parent: PyCWnd, + _id, + createStruct1, + createStruct: CREATESTRUCT | None = ..., + /, + ) -> None: ... + def DefWindowProc(self, message, idLast, idCheck, /): ... + def DestroyWindow(self) -> None: ... + def DlgDirlist(self, defPath: str, idlistbox, idStaticPath, fileType, /) -> None: ... + def DlgDirlistComboBox(self) -> None: ... + def DlgDirSelect(self, idlistbox, /) -> str: ... + def DlgDirSelectComboBox(self, idlistbox, /) -> str: ... + def DragAcceptFiles(self, bAccept: int = ..., /) -> None: ... + def DrawMenuBar(self) -> None: ... + def EnableWindow(self, bEnable: int = ..., /): ... + def EndModalLoop(self, result, /) -> None: ... + def EndPaint(self, paintStruct, /) -> None: ... + def GetCheckedRadioButton(self, idFirst, idLast, /): ... + def GetClientRect(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetDC(self) -> PyCDC: ... + def GetDCEx(self) -> PyCDC: ... + def GetDlgCtrlID(self): ... + def GetDlgItem(self, idControl, /) -> PyCWnd: ... + def GetDlgItemInt(self, idControl, bUnsigned: int = ..., /): ... + def GetDlgItemText(self, idControl, /) -> str: ... + def GetLastActivePopup(self) -> PyCWnd: ... + def GetMenu(self) -> PyCMenu: ... + def GetParent(self) -> PyCWnd: ... + def GetParentFrame(self) -> PyCWnd: ... + def GetSafeHwnd(self): ... + def GetScrollInfo(self, nBar, mask, /): ... + def GetScrollPos(self, nBar, /): ... + def GetStyle(self): ... + def GetExStyle(self): ... + def GetSystemMenu(self) -> PyCMenu: ... + def GetTopLevelFrame(self) -> PyCWnd: ... + def GetTopLevelOwner(self) -> PyCWnd: ... + def GetTopLevelParent(self) -> PyCWnd: ... + def GetTopWindow(self) -> PyCWnd: ... + def GetWindow(self, _type, /) -> PyCWnd: ... + def GetWindowDC(self) -> PyCDC: ... + def GetWindowPlacement(self): ... + def GetWindowRect(self) -> tuple[int, int, int, int]: ... + def GetWindowText(self) -> str: ... + def HideCaret(self) -> None: ... + def HookAllKeyStrokes(self, obHandler, /) -> None: ... + def HookKeyStroke(self, obHandler, ch, /): ... + def HookMessage(self, obHandler, message, /): ... + def InvalidateRect(self, arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], bErase: int = ..., /) -> None: ... + def InvalidateRgn(self, region: PyCRgn, bErase: int = ..., /) -> None: ... + def IsChild(self, obWnd: PyCWnd, /) -> bool: ... + def IsDlgButtonChecked(self, idCtl, /) -> bool: ... + def IsIconic(self) -> bool: ... + def IsZoomed(self) -> bool: ... + def IsWindow(self) -> bool: ... + def IsWindowVisible(self) -> bool: ... + def KillTimer(self): ... + def LockWindowUpdate(self) -> None: ... + def MapWindowPoints(self, wnd: PyCWnd, points: list[tuple[Incomplete, Incomplete]], /) -> None: ... + def MouseCaptured(self): ... + def MessageBox(self, message: str, arg, title: str | None = ..., /) -> None: ... + def ModifyStyle(self, remove, add, flags: int = ..., /): ... + def ModifyStyleEx(self, remove, add, flags: int = ..., /): ... + def MoveWindow(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], bRepaint: int = ..., /) -> None: ... + def OnClose(self): ... + def OnCtlColor(self, dc: PyCDC, control, _type, /): ... + def OnEraseBkgnd(self, dc: PyCDC, /): ... + def OnNcHitTest(self, arg: tuple[Incomplete, Incomplete], /): ... + def OnPaint(self): ... + def OnQueryDragIcon(self): ... + def OnQueryNewPalette(self): ... + def OnSetCursor(self, wnd: PyCWnd, hittest, message, /): ... + def OnMouseActivate(self, wnd: PyCWnd, hittest, message, /): ... + def OnWndMsg(self, msg, wParam, lParam, /) -> tuple[Incomplete, Incomplete]: ... + def PreCreateWindow(self, createStruct, /): ... + def PumpWaitingMessages(self, firstMsg, lastMsg, /) -> None: ... + def RedrawWindow( + self, _object: PyCRgn, flags, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., / + ) -> None: ... + def ReleaseCapture(self) -> None: ... + def ReleaseDC(self, dc: PyCDC, /) -> None: ... + def RepositionBars(self, idFirst, idLast, idLeftOver, /) -> None: ... + def RunModalLoop(self, flags, /): ... + def PostMessage(self, idMessage, wParam: int = ..., lParam: int = ..., /) -> None: ... + def SendMessageToDescendants(self, idMessage, wParam: int = ..., lParam: int = ..., bDeep: int = ..., /) -> None: ... + def SendMessage(self, idMessage, wParam: int = ..., lParam: int = ..., /) -> None: ... + def SetActiveWindow(self) -> PyCWnd: ... + def SetForegroundWindow(self) -> None: ... + def SetWindowPos( + self, hWndInsertAfter, position: tuple[Incomplete, Incomplete, Incomplete, Incomplete], flags, / + ) -> None: ... + + @overload + def ScreenToClient(self, rect: tuple[int, int], /) -> tuple[int, int]: ... + @overload + def ScreenToClient(self, rect: tuple[int, int, int, int], /) -> tuple[int, int, int, int]: ... + @overload + def ScreenToClient(self, rect: _TwoIntSequence | _FourIntSequence, /) -> tuple[int, int] | tuple[int, int, int, int]: ... + + def SetCapture(self) -> None: ... + def SetDlgItemText(self, idControl, text: str, /) -> None: ... + def SetFocus(self) -> None: ... + def SetFont(self, font: PyCFont, bRedraw: int = ..., /) -> None: ... + def SetIcon(self): ... + def SetMenu(self, menuObj: PyCMenu, /) -> None: ... + def SetRedraw(self, bState: int = ..., /) -> None: ... + def SetScrollPos(self, nBar, nPos, redraw: int = ..., /): ... + def SetScrollInfo(self, nBar, ScrollInfo, redraw: int = ..., /): ... + def SetTimer(self, idEvent, elapse, /): ... + def SetWindowPlacement(self, placement, /) -> None: ... + def SetWindowText(self, text: str, /) -> None: ... + def ShowCaret(self) -> None: ... + def ShowScrollBar(self, nBar, bShow: int = ..., /) -> None: ... + def ShowWindow(self, arg, /): ... + def UnLockWindowUpdate(self) -> None: ... + def UpdateData(self, bSaveAndValidate: int = ..., /): ... + def UpdateDialogControls(self, pTarget: PyCCmdTarget, disableIfNoHandler, /): ... + def UpdateWindow(self) -> None: ... + +class PyDDEConv: + def ConnectTo(self, service: str, topic: str, /) -> None: ... + def Connected(self) -> None: ... + def Exec(self, Cmd: str, /) -> None: ... + def Request(self) -> None: ... + def Poke(self) -> None: ... + +class PyDDEServer: + def AddTopic(self, topic: PyDDETopic, /) -> None: ... + def Create(self, name: str, filterFlags: int = ..., /) -> None: ... + def Destroy(self) -> None: ... + def GetLastError(self): ... + def Shutdown(self) -> None: ... + +class PyDDEStringItem: + def SetData(self, data: str, /) -> None: ... + +class PyDDETopic: + def AddItem(self, item, /) -> None: ... + def Destroy(self) -> None: ... + +class PyDLL: + def GetFileName(self) -> str: ... + def AttachToMFC(self) -> None: ... + +class SCROLLINFO: ... +class TV_ITEM: ... + +class EXTENSION_CONTROL_BLOCK: + @property + def Version(self) -> int: ... + @property + def TotalBytes(self): ... + @property + def AvailableBytes(self): ... + @property + def HttpStatusCode(self): ... + @property + def Method(self): ... + @property + def ConnID(self): ... + @property + def QueryString(self): ... + @property + def PathInfo(self): ... + @property + def PathTranslated(self): ... + @property + def AvailableData(self): ... + @property + def ContentType(self): ... + @property + def LogData(self): ... + def WriteClient(self, data: str, reserved: int = ..., /): ... + def GetServerVariable(self, variable: str, default, /) -> str: ... + def ReadClient(self, nbytes, /) -> str: ... + def SendResponseHeaders(self, reply: str, headers: str, keepAlive: bool = ..., /) -> None: ... + def SetFlushFlag(self, flag, /) -> None: ... + def TransmitFile(self, callback, param, hFile, statusCode: str, BytesToWrite, Offset, head: str, tail: str, flags, /): ... + def MapURLToPath(self) -> None: ... + def DoneWithSession(self, status, /) -> None: ... + def Redirect(self, url: str, /) -> None: ... + def IsKeepAlive(self) -> bool: ... + def GetAnonymousToken(self, metabase_path: str, /): ... + def GetImpersonationToken(self): ... + def IsKeepConn(self) -> bool: ... + def ExecURL(self, url: str, method: str, clientHeaders: str, info, entity, flags, /): ... + def GetExecURLStatus(self): ... + def IOCompletion(self, func, arg: Incomplete | None = ..., /): ... + def ReportUnhealthy(self, reason: str | None = ..., /): ... + def IOCallback(self, ecb: EXTENSION_CONTROL_BLOCK, arg, cbIO, dwError, /): ... + +class HSE_VERSION_INFO: + @property + def ExtensionDesc(self) -> str: ... + +class HTTP_FILTER_AUTHENT: + @property + def User(self) -> str: ... + @property + def Password(self) -> str: ... + +class HTTP_FILTER_CONTEXT: + @property + def Revision(self): ... + @property + def fIsSecurePort(self): ... + @property + def NotificationType(self): ... + @property + def FilterContext(self): ... + def GetData(self): ... + def GetServerVariable(self, variable: str, default, /) -> str: ... + def WriteClient(self, data: str, reserved: int = ..., /) -> None: ... + def AddResponseHeaders(self, data: str, reserved: int = ..., /) -> None: ... + def SendResponseHeader(self, status: str, header: str, /) -> None: ... + def DisableNotifications(self, flags, /) -> None: ... + +class HTTP_FILTER_LOG: + @property + def ClientHostName(self) -> str: ... + @property + def ClientUserName(self) -> str: ... + @property + def ServerName(self) -> str: ... + @property + def Operation(self) -> str: ... + @property + def Target(self) -> str: ... + @property + def Parameters(self) -> str: ... + @property + def HttpStatus(self): ... + +class HTTP_FILTER_PREPROC_HEADERS: + def GetHeader(self, header: str, default, /) -> str: ... + def SetHeader(self, name: str, val: str, /) -> None: ... + def AddHeader(self) -> None: ... + +class HTTP_FILTER_RAW_DATA: + @property + def InData(self) -> str: ... + +class HTTP_FILTER_URL_MAP: + @property + def URL(self) -> str: ... + @property + def PhysicalPath(self) -> str: ... + +class HTTP_FILTER_VERSION: + @property + def ServerFilterVersion(self): ... + @property + def FilterVersion(self): ... + @property + def Flags(self): ... + @property + def FilterDesc(self) -> str: ... + +class PySYSTEM_CPU_SET_INFORMATION: + Id: int + Group: int + LogicalProcessorIndex: int + CoreIndex: int + LastLevelCacheIndex: int + NumaNodeIndex: int + EfficiencyClass: int + SchedulingClass: int + AllocationTag: int diff --git a/stubs/pywin32/commctrl.pyi b/stubs/pywin32/commctrl.pyi new file mode 100644 index 000000000000..603c5703aff7 --- /dev/null +++ b/stubs/pywin32/commctrl.pyi @@ -0,0 +1 @@ +from win32.lib.commctrl import * diff --git a/stubs/pywin32/dde.pyi b/stubs/pywin32/dde.pyi new file mode 100644 index 000000000000..90a5be0f0c7f --- /dev/null +++ b/stubs/pywin32/dde.pyi @@ -0,0 +1 @@ +from pythonwin.dde import * diff --git a/stubs/pywin32/isapi/__init__.pyi b/stubs/pywin32/isapi/__init__.pyi new file mode 100644 index 000000000000..107d2b2c9e26 --- /dev/null +++ b/stubs/pywin32/isapi/__init__.pyi @@ -0,0 +1,9 @@ +class ISAPIError(Exception): + errno: int + strerror: str | None + funcname: str | None + def __init__(self, errno: int, strerror: str | None = None, funcname: str | None = None) -> None: ... + +class FilterError(ISAPIError): ... +class ExtensionError(ISAPIError): ... +class InternalReloadException(Exception): ... diff --git a/stubs/pywin32/isapi/install.pyi b/stubs/pywin32/isapi/install.pyi new file mode 100644 index 000000000000..ae3a54a2402f --- /dev/null +++ b/stubs/pywin32/isapi/install.pyi @@ -0,0 +1,101 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsGetItem, Unused +from collections.abc import Callable, Iterable, Mapping +from optparse import OptionParser +from typing import Final, Literal + +this_dir: str + +class FilterParameters: + Name: Incomplete + Description: Incomplete + Path: Incomplete + Server: Incomplete + AddExtensionFile: bool + AddExtensionFile_Enabled: bool + AddExtensionFile_GroupID: Incomplete + AddExtensionFile_CanDelete: bool + AddExtensionFile_Description: Incomplete + def __init__(self, **kw) -> None: ... + +class VirtualDirParameters: + Name: Incomplete + Description: Incomplete + AppProtection: Incomplete + Headers: Incomplete + Path: Incomplete + Type: Incomplete + AccessExecute: Incomplete + AccessRead: Incomplete + AccessWrite: Incomplete + AccessScript: Incomplete + ContentIndexed: Incomplete + EnableDirBrowsing: Incomplete + EnableDefaultDoc: Incomplete + DefaultDoc: Incomplete + ScriptMaps: list[ScriptMapParams] + ScriptMapUpdate: str + Server: Incomplete + def __init__(self, **kw) -> None: ... + def is_root(self) -> bool: ... + def split_path(self) -> list[str]: ... + +class ScriptMapParams: + Extension: Incomplete + Module: Incomplete + Flags: int + Verbs: str + AddExtensionFile: bool + AddExtensionFile_Enabled: bool + AddExtensionFile_GroupID: Incomplete + AddExtensionFile_CanDelete: bool + AddExtensionFile_Description: Incomplete + def __init__(self, **kw) -> None: ... + +class ISAPIParameters: + ServerName: Incomplete + Filters: list[FilterParameters] + VirtualDirs: list[VirtualDirParameters] + def __init__(self, **kw) -> None: ... + +verbose: int + +def log(level: int, what: object) -> None: ... + +class InstallationError(Exception): ... +class ItemNotFound(InstallationError): ... +class ConfigurationError(InstallationError): ... + +def FindPath(options, server: str | bytes | bytearray, name: str) -> str: ... +def LocateWebServerPath(description: str): ... +def GetWebServer(description: str | None = None): ... +def LoadWebServer(path): ... +def FindWebServer(options, server_desc: str | bytes | bytearray | None) -> str: ... +def split_path(path: str) -> list[str]: ... +def CreateDirectory(params, options): ... +def AssignScriptMaps(script_maps: Iterable[ScriptMapParams], target, update: str = "replace") -> None: ... +def get_unique_items(sequence, reference): ... +def CreateISAPIFilter(filterParams, options): ... +def DeleteISAPIFilter(filterParams, options) -> None: ... +def AddExtensionFiles(params, options) -> None: ... +def DeleteExtensionFileRecords(params, options) -> None: ... +def CheckLoaderModule(dll_name: StrOrBytesPath) -> None: ... +def Install(params, options) -> None: ... +def RemoveDirectory(params, options) -> None: ... +def RemoveScriptMaps(vd_params, options) -> None: ... +def Uninstall(params, options) -> None: ... +def GetLoaderModuleName(mod_name: StrPath, check_module: bool | None = None) -> str: ... +def InstallModule(conf_module_name: StrPath, params, options, log: Callable[[int, str], Unused] = ...) -> None: ... +def UninstallModule(conf_module_name: StrPath, params, options, log: Callable[[int, str], Unused] = ...) -> None: ... + +standard_arguments: Final[dict[Literal["install", "remove"], Callable[..., Incomplete]]] + +def build_usage(handler_map: Mapping[str, object]) -> str: ... +def MergeStandardOptions(options, params) -> None: ... +def HandleCommandLine( + params, + argv: SupportsGetItem[int, str] | None = None, + conf_module_name: str | None = None, + default_arg: str = "install", + opt_parser: OptionParser | None = None, + custom_arg_handlers: Mapping[str, object] = {}, +) -> None: ... diff --git a/stubs/pywin32/isapi/isapicon.pyi b/stubs/pywin32/isapi/isapicon.pyi new file mode 100644 index 000000000000..33ee18759595 --- /dev/null +++ b/stubs/pywin32/isapi/isapicon.pyi @@ -0,0 +1,86 @@ +from typing import Final + +HTTP_CONTINUE: Final = 100 +HTTP_SWITCHING_PROTOCOLS: Final = 101 +HTTP_PROCESSING: Final = 102 +HTTP_OK: Final = 200 +HTTP_CREATED: Final = 201 +HTTP_ACCEPTED: Final = 202 +HTTP_NON_AUTHORITATIVE: Final = 203 +HTTP_NO_CONTENT: Final = 204 +HTTP_RESET_CONTENT: Final = 205 +HTTP_PARTIAL_CONTENT: Final = 206 +HTTP_MULTI_STATUS: Final = 207 +HTTP_MULTIPLE_CHOICES: Final = 300 +HTTP_MOVED_PERMANENTLY: Final = 301 +HTTP_MOVED_TEMPORARILY: Final = 302 +HTTP_SEE_OTHER: Final = 303 +HTTP_NOT_MODIFIED: Final = 304 +HTTP_USE_PROXY: Final = 305 +HTTP_TEMPORARY_REDIRECT: Final = 307 +HTTP_BAD_REQUEST: Final = 400 +HTTP_UNAUTHORIZED: Final = 401 +HTTP_PAYMENT_REQUIRED: Final = 402 +HTTP_FORBIDDEN: Final = 403 +HTTP_NOT_FOUND: Final = 404 +HTTP_METHOD_NOT_ALLOWED: Final = 405 +HTTP_NOT_ACCEPTABLE: Final = 406 +HTTP_PROXY_AUTHENTICATION_REQUIRED: Final = 407 +HTTP_REQUEST_TIME_OUT: Final = 408 +HTTP_CONFLICT: Final = 409 +HTTP_GONE: Final = 410 +HTTP_LENGTH_REQUIRED: Final = 411 +HTTP_PRECONDITION_FAILED: Final = 412 +HTTP_REQUEST_ENTITY_TOO_LARGE: Final = 413 +HTTP_REQUEST_URI_TOO_LARGE: Final = 414 +HTTP_UNSUPPORTED_MEDIA_TYPE: Final = 415 +HTTP_RANGE_NOT_SATISFIABLE: Final = 416 +HTTP_EXPECTATION_FAILED: Final = 417 +HTTP_UNPROCESSABLE_ENTITY: Final = 422 +HTTP_INTERNAL_SERVER_ERROR: Final = 500 +HTTP_NOT_IMPLEMENTED: Final = 501 +HTTP_BAD_GATEWAY: Final = 502 +HTTP_SERVICE_UNAVAILABLE: Final = 503 +HTTP_GATEWAY_TIME_OUT: Final = 504 +HTTP_VERSION_NOT_SUPPORTED: Final = 505 +HTTP_VARIANT_ALSO_VARIES: Final = 506 +HSE_STATUS_SUCCESS: Final = 1 +HSE_STATUS_SUCCESS_AND_KEEP_CONN: Final = 2 +HSE_STATUS_PENDING: Final = 3 +HSE_STATUS_ERROR: Final = 4 +SF_NOTIFY_SECURE_PORT: Final = 0x00000001 +SF_NOTIFY_NONSECURE_PORT: Final = 0x00000002 +SF_NOTIFY_READ_RAW_DATA: Final = 0x00008000 +SF_NOTIFY_PREPROC_HEADERS: Final = 0x00004000 +SF_NOTIFY_AUTHENTICATION: Final = 0x00002000 +SF_NOTIFY_URL_MAP: Final = 0x00001000 +SF_NOTIFY_ACCESS_DENIED: Final = 0x00000800 +SF_NOTIFY_SEND_RESPONSE: Final = 0x00000040 +SF_NOTIFY_SEND_RAW_DATA: Final = 0x00000400 +SF_NOTIFY_LOG: Final = 0x00000200 +SF_NOTIFY_END_OF_REQUEST: Final = 0x00000080 +SF_NOTIFY_END_OF_NET_SESSION: Final = 0x00000100 +SF_NOTIFY_ORDER_HIGH: Final = 0x00080000 +SF_NOTIFY_ORDER_MEDIUM: Final = 0x00040000 +SF_NOTIFY_ORDER_LOW: Final = 0x00020000 +SF_NOTIFY_ORDER_DEFAULT: Final = SF_NOTIFY_ORDER_LOW +SF_NOTIFY_ORDER_MASK: Final = 917504 +SF_STATUS_REQ_FINISHED: Final = 134217728 +SF_STATUS_REQ_FINISHED_KEEP_CONN: Final = 134217729 +SF_STATUS_REQ_NEXT_NOTIFICATION: Final = 134217730 +SF_STATUS_REQ_HANDLED_NOTIFICATION: Final = 134217731 +SF_STATUS_REQ_ERROR: Final = 134217732 +SF_STATUS_REQ_READ_NEXT: Final = 134217733 +HSE_IO_SYNC: Final = 0x00000001 +HSE_IO_ASYNC: Final = 0x00000002 +HSE_IO_DISCONNECT_AFTER_SEND: Final = 0x00000004 +HSE_IO_SEND_HEADERS: Final = 0x00000008 +HSE_IO_NODELAY: Final = 0x00001000 +HSE_IO_FINAL_SEND: Final = 0x00000010 +HSE_IO_CACHE_RESPONSE: Final = 0x00000020 +HSE_EXEC_URL_NO_HEADERS: Final = 0x02 +HSE_EXEC_URL_IGNORE_CURRENT_INTERCEPTOR: Final = 0x04 +HSE_EXEC_URL_IGNORE_VALIDATION_AND_RANGE: Final = 0x10 +HSE_EXEC_URL_DISABLE_CUSTOM_ERROR: Final = 0x20 +HSE_EXEC_URL_SSI_CMD: Final = 0x40 +HSE_EXEC_URL_HTTP_CACHE_ELIGIBLE: Final = 0x80 diff --git a/stubs/pywin32/isapi/simple.pyi b/stubs/pywin32/isapi/simple.pyi new file mode 100644 index 000000000000..5d913c510d35 --- /dev/null +++ b/stubs/pywin32/isapi/simple.pyi @@ -0,0 +1,10 @@ +class SimpleExtension: + def GetExtensionVersion(self, vi) -> None: ... + def HttpExtensionProc(self, control_block) -> int | None: ... + def TerminateExtension(self, status) -> None: ... + +class SimpleFilter: + filter_flags: int | None + def GetFilterVersion(self, fv) -> None: ... + def HttpFilterProc(self, fc) -> None: ... + def TerminateFilter(self, status) -> None: ... diff --git a/stubs/pywin32/isapi/threaded_extension.pyi b/stubs/pywin32/isapi/threaded_extension.pyi new file mode 100644 index 000000000000..ead5c5ddcb1e --- /dev/null +++ b/stubs/pywin32/isapi/threaded_extension.pyi @@ -0,0 +1,29 @@ +import threading +from _typeshed import Unused +from collections.abc import Callable +from typing import Final + +import isapi.simple + +ISAPI_REQUEST: Final = 1 +ISAPI_SHUTDOWN: Final = 2 + +class WorkerThread(threading.Thread): + running: bool + io_req_port: int + extension: ThreadPoolExtension + def __init__(self, extension: ThreadPoolExtension, io_req_port: int) -> None: ... + def call_handler(self, cblock) -> None: ... + +class ThreadPoolExtension(isapi.simple.SimpleExtension): + max_workers: int + worker_shutdown_wait: int + workers: list[WorkerThread] + dispatch_map: dict[int, Callable[..., Unused]] + io_req_port: int + def GetExtensionVersion(self, vi) -> None: ... + def HttpExtensionProc(self, control_block) -> int: ... + def TerminateExtension(self, status) -> None: ... + def DispatchConnection(self, errCode, bytes, key, overlapped) -> None: ... + def Dispatch(self, ecb) -> None: ... + def HandleDispatchError(self, ecb) -> None: ... diff --git a/stubs/pywin32/mmapfile.pyi b/stubs/pywin32/mmapfile.pyi new file mode 100644 index 000000000000..0b18e7600318 --- /dev/null +++ b/stubs/pywin32/mmapfile.pyi @@ -0,0 +1 @@ +from win32.mmapfile import * diff --git a/stubs/pywin32/mmsystem.pyi b/stubs/pywin32/mmsystem.pyi new file mode 100644 index 000000000000..600475d287e2 --- /dev/null +++ b/stubs/pywin32/mmsystem.pyi @@ -0,0 +1 @@ +from win32.lib.mmsystem import * diff --git a/stubs/pywin32/ntsecuritycon.pyi b/stubs/pywin32/ntsecuritycon.pyi new file mode 100644 index 000000000000..0b23754827e0 --- /dev/null +++ b/stubs/pywin32/ntsecuritycon.pyi @@ -0,0 +1 @@ +from win32.lib.ntsecuritycon import * diff --git a/stubs/pywin32/odbc.pyi b/stubs/pywin32/odbc.pyi new file mode 100644 index 000000000000..4671d862c439 --- /dev/null +++ b/stubs/pywin32/odbc.pyi @@ -0,0 +1 @@ +from win32.odbc import * diff --git a/stubs/pywin32/perfmon.pyi b/stubs/pywin32/perfmon.pyi new file mode 100644 index 000000000000..eae890e08fbe --- /dev/null +++ b/stubs/pywin32/perfmon.pyi @@ -0,0 +1 @@ +from win32.perfmon import * diff --git a/stubs/pywin32/pythoncom.pyi b/stubs/pywin32/pythoncom.pyi new file mode 100644 index 000000000000..83404871ff7a --- /dev/null +++ b/stubs/pywin32/pythoncom.pyi @@ -0,0 +1,500 @@ +from _typeshed import Incomplete, Unused +from abc import abstractmethod +from collections.abc import Sequence +from typing import ClassVar, SupportsInt, TypeAlias, overload +from typing_extensions import deprecated, disjoint_base + +import _win32typing +from win32.lib.pywintypes import TimeType, com_error as com_error + +error: TypeAlias = com_error # noqa: Y042 + +class internal_error(Exception): ... + +@disjoint_base +class com_record: + @abstractmethod + def __init__(self, /, *args, **kwargs) -> None: ... + TLBID: ClassVar[str] + MJVER: ClassVar[int] + MNVER: ClassVar[int] + LCID: ClassVar[int] + GUID: ClassVar[str] + +def CoCreateFreeThreadedMarshaler(unk: _win32typing.PyIUnknown, /) -> _win32typing.PyIUnknown: ... +def CoCreateInstanceEx( + clsid: _win32typing.PyIID, + unkOuter: _win32typing.PyIUnknown, + context, + serverInfo: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + iids: list[_win32typing.PyIID], + /, +) -> _win32typing.PyIUnknown: ... +def CoCreateInstance( + clsid: _win32typing.PyIID, unkOuter: _win32typing.PyIUnknown | None, context: int, iid: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def CoFreeUnusedLibraries() -> None: ... +def CoInitialize() -> None: ... +def CoInitializeEx(flags, /) -> None: ... +def CoInitializeSecurity( + sd: _win32typing.PySECURITY_DESCRIPTOR, authSvc, reserved1, authnLevel, impLevel, authInfo, capabilities, reserved2, / +) -> None: ... +def CoGetInterfaceAndReleaseStream(stream: _win32typing.PyIStream, iid: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def CoMarshalInterThreadInterfaceInStream(iid: _win32typing.PyIID, unk: _win32typing.PyIUnknown, /) -> _win32typing.PyIStream: ... +def CoMarshalInterface( + Stm: _win32typing.PyIStream, riid: _win32typing.PyIID, Unk: _win32typing.PyIUnknown, DestContext, flags, / +) -> None: ... +def CoUnmarshalInterface(Stm: _win32typing.PyIStream, riid: _win32typing.PyIID, /): ... +def CoReleaseMarshalData(Stm: _win32typing.PyIStream, /) -> None: ... +def CoGetObject(name: str, iid: _win32typing.PyIID, bindOpts: Incomplete | None = ..., /) -> _win32typing.PyIUnknown: ... +def CoUninitialize() -> None: ... +def CoRegisterClassObject(iid: _win32typing.PyIID, factory: _win32typing.PyIUnknown, context, flags, /) -> int: ... +def CoResumeClassObjects() -> None: ... +def CoRevokeClassObject(reg: int, /) -> None: ... +def CoTreatAsClass(clsidold: _win32typing.PyIID, clsidnew: _win32typing.PyIID, /) -> None: ... +def CoWaitForMultipleHandles(Flags, Timeout, Handles: list[int], /): ... +def Connect(cls, /) -> _win32typing.PyIDispatch: ... +def connect(cls, /) -> _win32typing.PyIDispatch: ... +def CreateGuid() -> _win32typing.PyIID: ... +def CreateBindCtx() -> _win32typing.PyIBindCtx: ... +def CreateFileMoniker(filename: str, /) -> _win32typing.PyIMoniker: ... +def CreateItemMoniker(delim: str, item: str, /) -> _win32typing.PyIMoniker: ... +def CreatePointerMoniker(IUnknown: _win32typing.PyIUnknown, /) -> _win32typing.PyIMoniker: ... +def CreateURLMonikerEx(Context, URL, Flags: int = ..., /): ... +def CreateTypeLib(): ... +def CreateTypeLib2(): ... +def CreateStreamOnHGlobal(hGlobal: int | None = ..., DeleteOnRelease: bool = ..., /) -> _win32typing.PyIStream: ... +def CreateILockBytesOnHGlobal(hGlobal: int | None = ..., DeleteOnRelease: bool = ..., /) -> _win32typing.PyILockBytes: ... +def EnableQuitMessage(threadId, /) -> None: ... +def FUNCDESC() -> _win32typing.FUNCDESC: ... +def GetActiveObject(cls, /) -> _win32typing.PyIUnknown: ... +def GetClassFile(fileName, /) -> _win32typing.PyIID: ... +def GetFacilityString(scode, /) -> str: ... +def GetRecordFromGuids( + iid: str | _win32typing.PyIID, + verMajor: int, + verMinor: int, + lcid: int, + infoIID: str | _win32typing.PyIID, + data: Incomplete | None = ..., + /, +): ... +def GetRecordFromTypeInfo(TypeInfo: _win32typing.PyITypeInfo, /): ... +def GetRunningObjectTable(reserved: int = ..., /) -> _win32typing.PyIRunningObjectTable: ... +def GetScodeString(scode, /) -> str: ... +def GetScodeRangeString(scode, /) -> str: ... +def GetSeverityString(scode, /) -> str: ... +def IsGatewayRegistered(iid: _win32typing.PyIID | None, /) -> int: ... +def LoadRegTypeLib(iid: _win32typing.PyIID, versionMajor, versionMinor, lcid, /) -> _win32typing.PyITypeLib: ... +def LoadTypeLib(libFileName: str, /) -> _win32typing.PyITypeLib: ... +def MakePyFactory(iid: _win32typing.PyIID, /) -> _win32typing.PyIClassFactory: ... +@deprecated("Use pywintypes.IID() instead.") +def MakeIID(iidString: str, is_bytes: bool = ..., /) -> _win32typing.PyIID: ... +@deprecated("Use pywintypes.Time() instead.") +def MakeTime(timeRepr: SupportsInt | Sequence[SupportsInt] | TimeType, /) -> TimeType: ... +def MkParseDisplayName( + displayName: str, bindCtx: _win32typing.PyIBindCtx | None = ..., / +) -> tuple[_win32typing.PyIMoniker, Incomplete, _win32typing.PyIBindCtx]: ... +def new(iid: _win32typing.PyIID | str, /): ... +def New(cls, /) -> _win32typing.PyIDispatch: ... +def ObjectFromAddress(address, iid: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def ObjectFromLresult(lresult, iid: _win32typing.PyIID, wparm, /) -> _win32typing.PyIUnknown: ... +def OleInitialize() -> None: ... +def OleGetClipboard() -> _win32typing.PyIDataObject: ... +def OleFlushClipboard() -> None: ... +def OleIsCurrentClipboard(dataObj: _win32typing.PyIDataObject, /): ... +def OleSetClipboard(dataObj: _win32typing.PyIDataObject, /) -> None: ... +def OleLoadFromStream(stream: _win32typing.PyIStream, iid: _win32typing.PyIID, /) -> None: ... +def OleSaveToStream(persist: _win32typing.PyIPersistStream, stream: _win32typing.PyIStream, /) -> None: ... +def OleLoad(storage: _win32typing.PyIStorage, iid: _win32typing.PyIID, site: _win32typing.PyIOleClientSite, /) -> None: ... +def ProgIDFromCLSID(clsid, /) -> str: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def PumpMessages() -> None: ... +def QueryPathOfRegTypeLib(iid: _win32typing.PyIID, versionMajor, versionMinor, lcid, /) -> str: ... +def ReadClassStg(storage: _win32typing.PyIStorage, /) -> _win32typing.PyIID: ... +def ReadClassStm(Stm: _win32typing.PyIStream, /) -> _win32typing.PyIID: ... +def RegisterTypeLib(typelib: _win32typing.PyITypeLib, fullPath: str, lcid, helpDir: str | None = ..., /) -> None: ... +def UnRegisterTypeLib(iid: _win32typing.PyIID, versionMajor, versionMinor, lcid, syskind, /) -> str: ... +def RegisterActiveObject(obUnknown: _win32typing.PyIUnknown, clsid: _win32typing.PyIID, flags, /): ... +def RevokeActiveObject(handle, /) -> None: ... +def RegisterDragDrop(hwnd: int, dropTarget: _win32typing.PyIDropTarget, /) -> None: ... +def RevokeDragDrop(hwnd: int, /) -> None: ... +def DoDragDrop() -> None: ... +def StgCreateDocfile(name: str | None, mode: int, reserved: int = ..., /) -> _win32typing.PyIStorage: ... +def StgCreateDocfileOnILockBytes(lockBytes: _win32typing.PyILockBytes, mode, reserved=..., /) -> _win32typing.PyIStorage: ... +def StgOpenStorageOnILockBytes( + lockBytes: _win32typing.PyILockBytes, + stgPriority: _win32typing.PyIStorage, + mode, + snbExclude: Incomplete | None = ..., + reserved: int = ..., + /, +) -> _win32typing.PyIStorage: ... +def StgIsStorageFile(name: str, /): ... +def STGMEDIUM() -> _win32typing.PySTGMEDIUM: ... + +@overload +def StgOpenStorage( + name: str | None, other: _win32typing.PyIStorage, mode: int, snbExclude: Unused = ..., reserved: int = ..., / +) -> _win32typing.PyIStorage: ... +@overload +def StgOpenStorage( + name: str, other: _win32typing.PyIStorage | None, mode: int, snbExclude: Unused = ..., reserved: int = ..., / +) -> _win32typing.PyIStorage: ... + +def StgOpenStorageEx( + Name: str, Mode: int, stgfmt: int, Attrs: int, riid: _win32typing.PyIID, StgOptions: Incomplete | None = ... +) -> _win32typing.PyIStorage: ... +def StgCreateStorageEx( + Name: str, + Mode: int, + stgfmt: int, + Attrs: int, + riid: _win32typing.PyIID, + StgOptions: Incomplete | None = ..., + SecurityDescriptor: _win32typing.PySECURITY_DESCRIPTOR | None = ..., +) -> _win32typing.PyIStorage: ... +def TYPEATTR() -> _win32typing.TYPEATTR: ... +def VARDESC() -> _win32typing.VARDESC: ... +def WrapObject(ob, gatewayIID: _win32typing.PyIID, interfaceIID: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def WriteClassStg(storage: _win32typing.PyIStorage, iid: _win32typing.PyIID, /) -> None: ... +def WriteClassStm(Stm: _win32typing.PyIStream, clsid: _win32typing.PyIID, /) -> None: ... +def UnwrapObject(ob: _win32typing.PyIUnknown, /) -> _win32typing.PyIDispatch: ... +def FmtIdToPropStgName(fmtid: _win32typing.PyIID, /): ... +def PropStgNameToFmtId(Name: str, /) -> _win32typing.PyIID: ... +def CoGetCallContext(riid: _win32typing.PyIID, /) -> _win32typing.PyIServerSecurity: ... +def CoGetObjectContext(riid: _win32typing.PyIID, /) -> _win32typing.PyIContext: ... +def CoGetCancelObject(riid: _win32typing.PyIID, ThreadID: int = ..., /) -> _win32typing.PyICancelMethodCalls: ... +def CoSetCancelObject(Unk: _win32typing.PyIUnknown, /) -> None: ... +def CoEnableCallCancellation() -> None: ... +def CoDisableCallCancellation() -> None: ... + +ACTIVEOBJECT_STRONG: int +ACTIVEOBJECT_WEAK: int +ArgNotFound: _win32typing.ArgNotFound +CLSCTX_ALL: int +CLSCTX_INPROC: int +CLSCTX_INPROC_HANDLER: int +CLSCTX_INPROC_SERVER: int +CLSCTX_LOCAL_SERVER: int +CLSCTX_REMOTE_SERVER: int +CLSCTX_SERVER: int +CLSID_DCOMAccessControl: _win32typing.PyIID +CLSID_StdComponentCategoriesMgr: _win32typing.PyIID +CLSID_StdGlobalInterfaceTable: _win32typing.PyIID +COINIT_APARTMENTTHREADED: int +COINIT_DISABLE_OLE1DDE: int +COINIT_MULTITHREADED: int +COINIT_SPEED_OVER_MEMORY: int +COWAIT_ALERTABLE: int +COWAIT_WAITALL: int +DATADIR_GET: int +DATADIR_SET: int +DESCKIND_FUNCDESC: int +DESCKIND_VARDESC: int +DISPATCH_METHOD: int +DISPATCH_PROPERTYGET: int +DISPATCH_PROPERTYPUT: int +DISPATCH_PROPERTYPUTREF: int +DISPID_COLLECT: int +DISPID_CONSTRUCTOR: int +DISPID_DESTRUCTOR: int +DISPID_EVALUATE: int +DISPID_NEWENUM: int +DISPID_PROPERTYPUT: int +DISPID_STARTENUM: int +DISPID_THIS: int +DISPID_UNKNOWN: int +DISPID_VALUE: int +DVASPECT_CONTENT: int +DVASPECT_DOCPRINT: int +DVASPECT_ICON: int +DVASPECT_THUMBNAIL: int +EOAC_ACCESS_CONTROL: int +EOAC_ANY_AUTHORITY: int +EOAC_APPID: int +EOAC_AUTO_IMPERSONATE: int +EOAC_DEFAULT: int +EOAC_DISABLE_AAA: int +EOAC_DYNAMIC: int +EOAC_DYNAMIC_CLOAKING: int +EOAC_MAKE_FULLSIC: int +EOAC_MUTUAL_AUTH: int +EOAC_NONE: int +EOAC_NO_CUSTOM_MARSHAL: int +EOAC_REQUIRE_FULLSIC: int +EOAC_SECURE_REFS: int +EOAC_STATIC_CLOAKING: int +EXTCONN_CALLABLE: int +EXTCONN_STRONG: int +EXTCONN_WEAK: int +Empty: _win32typing.PyOleEmpty +FMTID_DocSummaryInformation: _win32typing.PyIID +FMTID_SummaryInformation: _win32typing.PyIID +FMTID_UserDefinedProperties: _win32typing.PyIID +FUNCFLAG_FBINDABLE: int +FUNCFLAG_FDEFAULTBIND: int +FUNCFLAG_FDISPLAYBIND: int +FUNCFLAG_FHIDDEN: int +FUNCFLAG_FREQUESTEDIT: int +FUNCFLAG_FRESTRICTED: int +FUNCFLAG_FSOURCE: int +FUNCFLAG_FUSESGETLASTERROR: int +FUNC_DISPATCH: int +FUNC_NONVIRTUAL: int +FUNC_PUREVIRTUAL: int +FUNC_STATIC: int +FUNC_VIRTUAL: int +IDLFLAG_FIN: int +IDLFLAG_FLCID: int +IDLFLAG_FOUT: int +IDLFLAG_FRETVAL: int +IDLFLAG_NONE: int +IID_IBindCtx: _win32typing.PyIID +IID_ICancelMethodCalls: _win32typing.PyIID +IID_ICatInformation: _win32typing.PyIID +IID_ICatRegister: _win32typing.PyIID +IID_IClassFactory: _win32typing.PyIID +IID_IClientSecurity: _win32typing.PyIID +IID_IConnectionPoint: _win32typing.PyIID +IID_IConnectionPointContainer: _win32typing.PyIID +IID_IContext: _win32typing.PyIID +IID_ICreateTypeInfo: _win32typing.PyIID +IID_ICreateTypeLib: _win32typing.PyIID +IID_ICreateTypeLib2: _win32typing.PyIID +IID_IDataObject: _win32typing.PyIID +IID_IDispatch: _win32typing.PyIID +IID_IDispatchEx: _win32typing.PyIID +IID_IDropSource: _win32typing.PyIID +IID_IDropTarget: _win32typing.PyIID +IID_IEnumCATEGORYINFO: _win32typing.PyIID +IID_IEnumConnectionPoints: _win32typing.PyIID +IID_IEnumConnections: _win32typing.PyIID +IID_IEnumContextProps: _win32typing.PyIID +IID_IEnumFORMATETC: _win32typing.PyIID +IID_IEnumGUID: _win32typing.PyIID +IID_IEnumMoniker: _win32typing.PyIID +IID_IEnumSTATPROPSETSTG: _win32typing.PyIID +IID_IEnumSTATPROPSTG: _win32typing.PyIID +IID_IEnumSTATSTG: _win32typing.PyIID +IID_IEnumString: _win32typing.PyIID +IID_IEnumVARIANT: _win32typing.PyIID +IID_IErrorLog: _win32typing.PyIID +IID_IExternalConnection: _win32typing.PyIID +IID_IGlobalInterfaceTable: _win32typing.PyIID +IID_ILockBytes: _win32typing.PyIID +IID_IMarshal: _win32typing.PyIID +IID_IMoniker: _win32typing.PyIID +IID_IOleWindow: _win32typing.PyIID +IID_IPersist: _win32typing.PyIID +IID_IPersistFile: _win32typing.PyIID +IID_IPersistPropertyBag: _win32typing.PyIID +IID_IPersistStorage: _win32typing.PyIID +IID_IPersistStream: _win32typing.PyIID +IID_IPersistStreamInit: _win32typing.PyIID +IID_IPropertyBag: _win32typing.PyIID +IID_IPropertySetStorage: _win32typing.PyIID +IID_IPropertyStorage: _win32typing.PyIID +IID_IProvideClassInfo: _win32typing.PyIID +IID_IProvideClassInfo2: _win32typing.PyIID +IID_IRunningObjectTable: _win32typing.PyIID +IID_IServerSecurity: _win32typing.PyIID +IID_IServiceProvider: _win32typing.PyIID +IID_IStdMarshalInfo: _win32typing.PyIID +IID_IStorage: _win32typing.PyIID +IID_IStream: _win32typing.PyIID +IID_ITypeComp: _win32typing.PyIID +IID_ITypeInfo: _win32typing.PyIID +IID_ITypeLib: _win32typing.PyIID +IID_IUnknown: _win32typing.PyIID +IID_NULL: _win32typing.PyIID +IID_StdOle: _win32typing.PyIID +IMPLTYPEFLAG_FDEFAULT: int +IMPLTYPEFLAG_FRESTRICTED: int +IMPLTYPEFLAG_FSOURCE: int +INVOKE_FUNC: int +INVOKE_PROPERTYGET: int +INVOKE_PROPERTYPUT: int +INVOKE_PROPERTYPUTREF: int +InterfaceNames: dict[str, _win32typing.PyIID] +MKSYS_ANTIMONIKER: int +MKSYS_CLASSMONIKER: int +MKSYS_FILEMONIKER: int +MKSYS_GENERICCOMPOSITE: int +MKSYS_ITEMMONIKER: int +MKSYS_NONE: int +MKSYS_POINTERMONIKER: int +MSHCTX_DIFFERENTMACHINE: int +MSHCTX_INPROC: int +MSHCTX_LOCAL: int +MSHCTX_NOSHAREDMEM: int +MSHLFLAGS_NOPING: int +MSHLFLAGS_NORMAL: int +MSHLFLAGS_TABLESTRONG: int +MSHLFLAGS_TABLEWEAK: int +Missing: _win32typing.PyOleMissing +Nothing: _win32typing.PyOleNothing +PARAMFLAG_FHASDEFAULT: int +PARAMFLAG_FIN: int +PARAMFLAG_FLCID: int +PARAMFLAG_FOPT: int +PARAMFLAG_FOUT: int +PARAMFLAG_FRETVAL: int +PARAMFLAG_NONE: int +REGCLS_MULTIPLEUSE: int +REGCLS_MULTI_SEPARATE: int +REGCLS_SINGLEUSE: int +REGCLS_SUSPENDED: int +ROTFLAGS_ALLOWANYCLIENT: int +ROTFLAGS_REGISTRATIONKEEPSALIVE: int +RPC_C_AUTHN_DCE_PRIVATE: int +RPC_C_AUTHN_DCE_PUBLIC: int +RPC_C_AUTHN_DEC_PUBLIC: int +RPC_C_AUTHN_DEFAULT: int +RPC_C_AUTHN_DPA: int +RPC_C_AUTHN_GSS_KERBEROS: int +RPC_C_AUTHN_GSS_NEGOTIATE: int +RPC_C_AUTHN_GSS_SCHANNEL: int +RPC_C_AUTHN_LEVEL_CALL: int +RPC_C_AUTHN_LEVEL_CONNECT: int +RPC_C_AUTHN_LEVEL_DEFAULT: int +RPC_C_AUTHN_LEVEL_NONE: int +RPC_C_AUTHN_LEVEL_PKT: int +RPC_C_AUTHN_LEVEL_PKT_INTEGRITY: int +RPC_C_AUTHN_LEVEL_PKT_PRIVACY: int +RPC_C_AUTHN_MQ: int +RPC_C_AUTHN_MSN: int +RPC_C_AUTHN_NONE: int +RPC_C_AUTHN_WINNT: int +RPC_C_AUTHZ_DCE: int +RPC_C_AUTHZ_DEFAULT: int +RPC_C_AUTHZ_NAME: int +RPC_C_AUTHZ_NONE: int +RPC_C_IMP_LEVEL_ANONYMOUS: int +RPC_C_IMP_LEVEL_DEFAULT: int +RPC_C_IMP_LEVEL_DELEGATE: int +RPC_C_IMP_LEVEL_IDENTIFY: int +RPC_C_IMP_LEVEL_IMPERSONATE: int +STDOLE2_LCID: int +STDOLE2_MAJORVERNUM: int +STDOLE2_MINORVERNUM: int +STDOLE_LCID: int +STDOLE_MAJORVERNUM: int +STDOLE_MINORVERNUM: int +STREAM_SEEK_CUR: int +STREAM_SEEK_END: int +STREAM_SEEK_SET: int +SYS_MAC: int +SYS_WIN16: int +SYS_WIN32: int +ServerInterfaces: dict[_win32typing.PyIID, bytes] +TKIND_ALIAS: int +TKIND_COCLASS: int +TKIND_DISPATCH: int +TKIND_ENUM: int +TKIND_INTERFACE: int +TKIND_MODULE: int +TKIND_RECORD: int +TKIND_UNION: int +TYMED_ENHMF: int +TYMED_FILE: int +TYMED_GDI: int +TYMED_HGLOBAL: int +TYMED_ISTORAGE: int +TYMED_ISTREAM: int +TYMED_MFPICT: int +TYMED_NULL: int +TYPEFLAG_FAGGREGATABLE: int +TYPEFLAG_FAPPOBJECT: int +TYPEFLAG_FCANCREATE: int +TYPEFLAG_FCONTROL: int +TYPEFLAG_FDISPATCHABLE: int +TYPEFLAG_FDUAL: int +TYPEFLAG_FHIDDEN: int +TYPEFLAG_FLICENSED: int +TYPEFLAG_FNONEXTENSIBLE: int +TYPEFLAG_FOLEAUTOMATION: int +TYPEFLAG_FPREDECLID: int +TYPEFLAG_FREPLACEABLE: int +TYPEFLAG_FRESTRICTED: int +TYPEFLAG_FREVERSEBIND: int +RecordClasses: dict[str, com_record] +TypeIIDs: dict[_win32typing.PyIID, type] +URL_MK_LEGACY: int +URL_MK_UNIFORM: int +VARFLAG_FREADONLY: int +VAR_CONST: int +VAR_DISPATCH: int +VAR_PERINSTANCE: int +VAR_STATIC: int +VT_ARRAY: int +VT_BLOB: int +VT_BLOB_OBJECT: int +VT_BOOL: int +VT_BSTR: int +VT_BSTR_BLOB: int +VT_BYREF: int +VT_CARRAY: int +VT_CF: int +VT_CLSID: int +VT_CY: int +VT_DATE: int +VT_DECIMAL: int +VT_DISPATCH: int +VT_EMPTY: int +VT_ERROR: int +VT_FILETIME: int +VT_HRESULT: int +VT_I1: int +VT_I2: int +VT_I4: int +VT_I8: int +VT_ILLEGAL: int +VT_ILLEGALMASKED: int +VT_INT: int +VT_LPSTR: int +VT_LPWSTR: int +VT_NULL: int +VT_PTR: int +VT_R4: int +VT_R8: int +VT_RECORD: int +VT_RESERVED: int +VT_SAFEARRAY: int +VT_STORAGE: int +VT_STORED_OBJECT: int +VT_STREAM: int +VT_STREAMED_OBJECT: int +VT_TYPEMASK: int +VT_UI1: int +VT_UI2: int +VT_UI4: int +VT_UI8: int +VT_UINT: int +VT_UNKNOWN: int +VT_USERDEFINED: int +VT_VARIANT: int +VT_VECTOR: int +VT_VOID: int + +dcom: int +fdexNameCaseInsensitive: int +fdexNameCaseSensitive: int +fdexNameEnsure: int +fdexNameImplicit: int +fdexPropCanCall: int +fdexPropCanConstruct: int +fdexPropCanGet: int +fdexPropCanPut: int +fdexPropCanPutRef: int +fdexPropCanSourceEvents: int +fdexPropCannotCall: int +fdexPropCannotConstruct: int +fdexPropCannotGet: int +fdexPropCannotPut: int +fdexPropCannotPutRef: int +fdexPropCannotSourceEvents: int +fdexPropDynamicType: int +fdexPropNoSideEffects: int +# Deprecated: Use `getattr(sys, "frozen", False)` directly instead. +frozen: int diff --git a/stubs/pywin32/pythonwin/__init__.pyi b/stubs/pywin32/pythonwin/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/pythonwin/dde.pyi b/stubs/pywin32/pythonwin/dde.pyi new file mode 100644 index 000000000000..6281353490ac --- /dev/null +++ b/stubs/pywin32/pythonwin/dde.pyi @@ -0,0 +1,36 @@ +# Can't generate with stubgen because: +# "ImportError: This must be an MFC application - try 'import win32ui' first" +from typing import Final + +import _win32typing + +class error(Exception): ... + +def CreateConversation(Server, /) -> _win32typing.PyDDEConv: ... +def CreateServer() -> _win32typing.PyDDEServer: ... +def CreateServerSystemTopic(): ... +def CreateTopic(name: str, /) -> _win32typing.PyDDETopic: ... +def CreateStringItem(name: str, /) -> _win32typing.PyDDEStringItem: ... + +APPCLASS_MONITOR: Final[int] +APPCLASS_STANDARD: Final[int] +APPCMD_CLIENTONLY: Final[int] +APPCMD_FILTERINITS: Final[int] +CBF_FAIL_ALLSVRXACTIONS: Final[int] +CBF_FAIL_ADVISES: Final[int] +CBF_FAIL_CONNECTIONS: Final[int] +CBF_FAIL_EXECUTES: Final[int] +CBF_FAIL_POKES: Final[int] +CBF_FAIL_REQUESTS: Final[int] +CBF_FAIL_SELFCONNECTIONS: Final[int] +CBF_SKIP_ALLNOTIFICATIONS: Final[int] +CBF_SKIP_CONNECT_CONFIRMS: Final[int] +CBF_SKIP_DISCONNECTS: Final[int] +CBF_SKIP_REGISTRATIONS: Final[int] +MF_CALLBACKS: Final[int] +MF_CONV: Final[int] +MF_ERRORS: Final[int] +MF_HSZ_INFO: Final[int] +MF_LINKS: Final[int] +MF_POSTMSGS: Final[int] +MF_SENDMSGS: Final[int] diff --git a/stubs/pywin32/pythonwin/win32ui.pyi b/stubs/pywin32/pythonwin/win32ui.pyi new file mode 100644 index 000000000000..44cba4009a78 --- /dev/null +++ b/stubs/pywin32/pythonwin/win32ui.pyi @@ -0,0 +1,422 @@ +from _typeshed import FileDescriptorOrPath, Incomplete, OptExcInfo, Unused +from collections.abc import Callable, Iterable, Mapping, Sequence +from types import TracebackType +from typing import Final, Literal, overload + +import _win32typing + +class error(Exception): ... + +def ComparePath(path1: str, path2: str, /) -> int: ... +def CreateMDIFrame() -> _win32typing.PyCMDIFrameWnd: ... +def CreateMDIChild() -> _win32typing.PyCMDIChildWnd: ... +def CreateBitmap(*args: Unused) -> _win32typing.PyCBitmap: ... +def CreateBitmapFromHandle(handle: int | _win32typing.PyHANDLE | None, /) -> _win32typing.PyCBitmap: ... + +@overload +def CreateBrush() -> _win32typing.PyCBrush: ... +@overload +def CreateBrush(style: int, color: int, hatch: int, /) -> _win32typing.PyCBrush: ... + +def CreateButton() -> _win32typing.PyCButton: ... +def CreateColorDialog( + initColor: int = 0, flags: int = 0, parent: _win32typing.PyCWnd | None = None, / +) -> _win32typing.PyCColorDialog: ... +def CreateControl( + classId: str, + windowName: str | None, + style: int, + rect: tuple[int, int, int, int], + parent: _win32typing.PyCWnd, + id: int, + obPersist: Unused = None, + bStorage: bool | Literal[0, 1] = False, + licKey: str | None = None, + /, +) -> _win32typing.PyCWnd: ... +def CreateControlBar() -> _win32typing.PyCControlBar: ... +def CreateCtrlView(doc: _win32typing.PyCDocument, className: str, style: int = 0, /) -> _win32typing.PyCCtrlView: ... +def CreateDC() -> _win32typing.PyCDC: ... +def CreateDCFromHandle(handle: int | _win32typing.PyHANDLE | None, /) -> _win32typing.PyCDC: ... +def CreateDialog(idRes: int, dll: _win32typing.PyDLL | None = None, /) -> _win32typing.PyCDialog: ... +def CreateDialogBar() -> _win32typing.PyCDialogBar: ... +def CreateDialogIndirect( + oblist: Iterable[_win32typing.PyDLGTEMPLATE | _win32typing.PyDLGITEMTEMPLATE], / +) -> _win32typing.PyCDialog: ... +def CreatePrintDialog( + idRes: int, + bPrintSetupOnly: bool | Literal[0, 1] = False, + dwFlags: int = ..., + parent: _win32typing.PyCWnd | None = None, + dll: _win32typing.PyDLL | None = None, + /, +) -> _win32typing.PyCPrintDialog: ... +def CreateDocTemplate(idRes: int, /) -> _win32typing.PyCDocTemplate: ... +def CreateEdit() -> _win32typing.PyCEdit: ... +def CreateFileDialog( + bFileOpen: int, + defExt: str | None = None, + fileName: str | None = None, + flags: int = ..., + filter: str | None = None, + parent: _win32typing.PyCWnd | None = None, + /, +) -> _win32typing.PyCFileDialog: ... +def CreateFontDialog( + font: tuple[int, int, int, int, int, int, int, str | None] | Mapping[str, int | str | None] | None = None, + flags: int = ..., + dcPrinter: _win32typing.PyCDC | None = None, + parent: _win32typing.PyCWnd | None = None, + /, +) -> _win32typing.PyCFontDialog: ... +def CreateFormView( + doc: _win32typing.PyCDocument, Template: int | str | _win32typing.PyResourceId, / +) -> _win32typing.PyCFormView: ... +def CreateFrame() -> _win32typing.PyCFrameWnd: ... +def CreateTreeCtrl(*args: Unused) -> _win32typing.PyCTreeCtrl: ... +def CreateTreeView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyCTreeView: ... +def CreatePalette(lp: Sequence[tuple[int, int, int, int]], /) -> int: ... +def CreatePopupMenu() -> _win32typing.PyCMenu: ... +def CreateMenu() -> _win32typing.PyCMenu: ... +def CreatePen(style: int, width: int, color: int, /): ... +def CreateProgressCtrl() -> _win32typing.PyCProgressCtrl: ... +def CreatePropertyPage(resource: int | str | _win32typing.PyResourceId, caption: int = 0, /) -> _win32typing.PyCPropertyPage: ... +def CreatePropertyPageIndirect( + resourceList: Iterable[Incomplete] | _win32typing.PyDialogTemplate, caption: int = 0, / +) -> _win32typing.PyCPropertyPage: ... +def CreatePropertySheet( + caption: int | str | _win32typing.PyResourceId, parent: _win32typing.PyCWnd | None = None, select: int = 0, / +) -> _win32typing.PyCPropertySheet: ... +def CreateRgn() -> _win32typing.PyCRgn: ... +def CreateRichEditCtrl() -> _win32typing.PyCRichEditCtrl: ... +def CreateRichEditDocTemplate(idRes: int, /) -> _win32typing.PyCRichEditDocTemplate: ... +def CreateRichEditView(doc: _win32typing.PyCDocument | None = None, /) -> _win32typing.PyCRichEditView: ... +def CreateSliderCtrl() -> _win32typing.PyCSliderCtrl: ... +def CreateSplitter() -> _win32typing.PyCSplitterWnd: ... +def CreateStatusBar( + parent: _win32typing.PyCWnd, style: int = ..., windowId: int = ..., ctrlStype: int = 0, / +) -> _win32typing.PyCStatusBar: ... +def CreateStatusBarCtrl() -> _win32typing.PyCStatusBarCtrl: ... +def CreateFont(properties: Mapping[str, int | str | None], pydc: _win32typing.PyCDC = ..., /) -> _win32typing.PyCFont: ... +def CreateToolBar(parent: _win32typing.PyCWnd, style: int, windowId: int = ..., /) -> _win32typing.PyCToolBar: ... +def CreateToolBarCtrl() -> _win32typing.PyCToolBarCtrl: ... +def CreateToolTipCtrl() -> _win32typing.PyCToolTipCtrl: ... + +@overload +def CreateThread() -> _win32typing.PyCWinThread: ... +@overload +def CreateThread(func: Callable[..., Incomplete], args=None, /) -> _win32typing.PyCWinThread: ... + +def CreateView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyCScrollView: ... +def CreateEditView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyCEditView: ... +def CreateDebuggerThread() -> None: ... +def CreateWindowFromHandle(hwnd: int | _win32typing.PyHANDLE | None, /) -> _win32typing.PyCWnd: ... +def CreateWnd() -> _win32typing.PyCWnd: ... +def DestroyDebuggerThread() -> None: ... +def DoWaitCursor(code: Literal[-1, 0, 1], /) -> None: ... +def DisplayTraceback(exc_info: OptExcInfo, title: str | None = None, /) -> None: ... +def Enable3dControls() -> int: ... +def FindWindow(className: str | None, windowName: str | None, /) -> _win32typing.PyCWnd: ... +def FindWindowEx( + parentWindow: _win32typing.PyCWnd | None, + childAfter: _win32typing.PyCWnd | None, + className: str | None, + windowName: str | None, + /, +) -> _win32typing.PyCWnd: ... +def FullPath(path: str, /) -> str: ... +def GetActiveWindow() -> _win32typing.PyCWnd: ... +def GetApp() -> _win32typing.PyCWinApp: ... +def GetAppName() -> str: ... +def GetAppRegistryKey() -> _win32typing.PyHKEY: ... +def GetBytes(address: int, size: int, /) -> bytes: ... +def GetCommandLine() -> str: ... +def GetDeviceCaps(hdc: int | _win32typing.PyHANDLE | None, index: int, /) -> int: ... +def GetFileTitle(fileName: str, /) -> str: ... +def GetFocus() -> _win32typing.PyCWnd: ... +def GetForegroundWindow() -> _win32typing.PyCWnd: ... +def GetHalftoneBrush(*args: Unused) -> _win32typing.PyCBrush: ... +def GetInitialStateRequest() -> int: ... +def GetMainFrame() -> _win32typing.PyCWnd: ... +def GetName() -> str: ... +def GetProfileFileName() -> str: ... + +@overload +def GetProfileVal(section: str, entry: str, defValue: str | None, /) -> str: ... +@overload +def GetProfileVal(section: str, entry: str, defValue: int, /) -> int: ... + +def GetResource() -> _win32typing.PyDLL: ... +def GetThread() -> _win32typing.PyCWinApp: ... +def GetType(name: str, /): ... +def InitRichEdit() -> None: ... +def InstallCallbackCaller(caller: Callable[..., Incomplete] | None = None, /): ... +def IsDebug() -> Literal[0, 1]: ... +def IsWin32s() -> bool: ... +def IsObject(o: object, /) -> bool: ... +def LoadDialogResource(idRes: int, dll: _win32typing.PyDLL | None = None, /) -> list[Incomplete]: ... +def LoadLibrary(fileName: str, flags: int = 0, /) -> _win32typing.PyDLL: ... +def LoadMenu(id: int, dll: _win32typing.PyDLL | None = None, /) -> _win32typing.PyCMenu: ... +def LoadStdProfileSettings(maxFiles: int = ..., /) -> None: ... +def LoadString(stringId: int, /) -> str: ... +def MessageBox(message: str, title: str | None = None, style: int = 0, /) -> int: ... +def EnableControlContainer() -> None: ... +def PrintTraceback(tb: TracebackType, output: FileDescriptorOrPath, /) -> None: ... +def PumpWaitingMessages(firstMessage: int = 15, lastMessage: int = 15, /) -> Literal[0, 1]: ... +def RegisterWndClass( + style: int, + hCursor: int | _win32typing.PyHANDLE | None = 0, + hBrush: int | _win32typing.PyHANDLE | None = 0, + hIcon: int | _win32typing.PyHANDLE | None = 0, + /, +) -> str: ... +def RemoveRecentFile(index: int = 0, /) -> None: ... +def SetAppHelpPath(name: str, /) -> None: ... +def SetAppName(appName: str, /) -> None: ... +def SetCurrentInstanceHandle(newVal: int | _win32typing.PyHANDLE | None, /) -> int: ... +def SetCurrentResourceHandle(newVal: int, /) -> int: ... +def SetDialogBkColor(clrCtlBk: int = ..., clrCtlText: int = ..., /) -> None: ... +def SetProfileFileName(filename: str, /) -> None: ... +def SetRegistryKey(key: str, /) -> None: ... +def SetResource(dll: _win32typing.PyDLL, /) -> _win32typing.PyDLL: ... +def SetStatusText(msg: str, bForce: bool | Literal[0, 1] = False, /) -> None: ... +def StartDebuggerPump() -> None: ... +def StopDebuggerPump() -> None: ... +def TranslateMessage(msg: tuple[int, int, int, int, int, tuple[int, int]]) -> int: ... +def TranslateVirtualKey(vk: int, /) -> bytes | None: ... +def WinHelp(cmd: int, data: str | int, /) -> None: ... +def WriteProfileVal(section: str, entry: str, value: str | int, /) -> int: ... +def AddToRecentFileList(fileName: str, /) -> None: ... + +@overload +def CreateImageList(cx: int, cy: int, mask: bool | Literal[0, 1], initial: int, grow: int, /) -> _win32typing.PyCImagelist: ... +@overload +def CreateImageList( + bitmapId: int | str | _win32typing.PyResourceId, cx: int, grow: int, crMask: int, / +) -> _win32typing.PyCImagelist: ... + +def CreateListCtrl(*args: Unused) -> _win32typing.PyClistCtrl: ... +def CreateListView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyClistView: ... +def CreateRectRgn(rect: tuple[int, int, int, int], /) -> Literal[0, 1]: ... +def GetRecentFileList() -> list[str]: ... +def OutputDebug(msg: str, /) -> None: ... +def OutputDebugString(msg: str, /) -> None: ... + +AFX_IDW_PANE_FIRST: Final[int] +AFX_IDW_PANE_LAST: Final[int] +AFX_WS_DEFAULT_VIEW: Final[int] +FWS_ADDTOTITLE: Final[int] +FWS_PREFIXTITLE: Final[int] +FWS_SNAPTOBARS: Final[int] +IDD_ABOUTBOX: Final[int] +IDD_DUMMYPROPPAGE: Final[int] +IDD_PROPDEMO1: Final[int] +IDD_PROPDEMO2: Final[int] +IDB_DEBUGGER_HIER: Final[int] +IDB_HIERFOLDERS: Final[int] +IDB_BROWSER_HIER: Final[int] +IDD_GENERAL_STATUS: Final[int] +IDD_LARGE_EDIT: Final[int] +IDD_TREE: Final[int] +IDD_TREE_MB: Final[int] +IDD_RUN_SCRIPT: Final[int] +IDD_PP_EDITOR: Final[int] +IDD_PP_DEBUGGER: Final[int] +IDD_PP_FORMAT: Final[int] +IDD_PP_IDE: Final[int] +IDD_PP_TABS: Final[int] +IDD_PP_TOOLMENU: Final[int] +IDD_SIMPLE_INPUT: Final[int] +IDD_SET_TABSTOPS: Final[int] +IDC_DBG_STEP: Final[int] +IDC_DBG_STEPOUT: Final[int] +IDC_DBG_STEPOVER: Final[int] +IDC_DBG_GO: Final[int] +IDC_DBG_ADD: Final[int] +IDC_DBG_CLEAR: Final[int] +IDC_DBG_CLOSE: Final[int] +IDC_DBG_STACK: Final[int] +IDC_DBG_BREAKPOINTS: Final[int] +IDC_DBG_WATCH: Final[int] +IDC_ABOUT_VERSION: Final[int] +IDC_AUTO_RELOAD: Final[int] +IDC_BUTTON1: Final[int] +IDC_BUTTON2: Final[int] +IDC_BUTTON3: Final[int] +IDC_BUTTON4: Final[int] +IDC_CHECK1: Final[int] +IDC_CHECK2: Final[int] +IDC_CHECK3: Final[int] +IDC_COMBO1: Final[int] +IDC_COMBO2: Final[int] +IDC_EDIT1: Final[int] +IDC_EDIT2: Final[int] +IDC_EDIT3: Final[int] +IDC_EDIT4: Final[int] +IDC_EDIT_TABS: Final[int] +IDC_EDITOR_COLOR: Final[int] +IDC_FOLD_SHOW_LINES: Final[int] +IDC_FOLD_ENABLE: Final[int] +IDC_FOLD_ON_OPEN: Final[int] +IDC_INDENT_SIZE: Final[int] +IDC_KEYBOARD_CONFIG: Final[int] +IDC_MARGIN_LINENUMBER: Final[int] +IDC_MARGIN_FOLD: Final[int] +IDC_MARGIN_MARKER: Final[int] +IDC_LIST1: Final[int] +IDC_PROMPT_TABS: Final[int] +IDC_PROMPT1: Final[int] +IDC_PROMPT2: Final[int] +IDC_PROMPT3: Final[int] +IDC_PROMPT4: Final[int] +IDC_RADIO1: Final[int] +IDC_RADIO2: Final[int] +IDC_RIGHTEDGE_COLUMN: Final[int] +IDC_RIGHTEDGE_ENABLE: Final[int] +IDC_RIGHTEDGE_SAMPLE: Final[int] +IDC_RIGHTEDGE_DEFINE: Final[int] +IDC_TABTIMMY_NONE: Final[int] +IDC_TABTIMMY_IND: Final[int] +IDC_TABTIMMY_BG: Final[int] +IDC_VIEW_WHITESPACE: Final[int] +IDC_VIEW_EOL: Final[int] +IDC_VIEW_INDENTATIONGUIDES: Final[int] +IDC_AUTOCOMPLETE: Final[int] +IDC_CALLTIPS: Final[int] +IDC_SPIN1: Final[int] +IDC_SPIN2: Final[int] +IDC_SPIN3: Final[int] +IDC_TAB_SIZE: Final[int] +IDC_USE_TABS: Final[int] +IDC_USE_SMART_TABS: Final[int] +IDC_VSS_INTEGRATE: Final[int] +ID_INDICATOR_LINENUM: Final[int] +ID_INDICATOR_COLNUM: Final[int] +ID_FILE_NEW: Final[int] +ID_FILE_OPEN: Final[int] +ID_FILE_CLOSE: Final[int] +ID_FILE_RUN: Final[int] +ID_FILE_IMPORT: Final[int] +ID_FILE_LOCATE: Final[int] +ID_FILE_CHECK: Final[int] +ID_FILE_SAVE: Final[int] +ID_FILE_SAVE_AS: Final[int] +ID_FILE_SAVE_ALL: Final[int] +ID_FILE_PAGE_SETUP: Final[int] +ID_FILE_PRINT_SETUP: Final[int] +ID_FILE_PRINT: Final[int] +ID_FILE_PRINT_PREVIEW: Final[int] +ID_HELP_PYTHON: Final[int] +ID_HELP_GUI_REF: Final[int] +ID_HELP_OTHER: Final[int] +ID_APP_ABOUT: Final[int] +ID_APP_EXIT: Final[int] +ID_FILE_MRU_FILE1: Final[int] +ID_FILE_MRU_FILE2: Final[int] +ID_FILE_MRU_FILE3: Final[int] +ID_FILE_MRU_FILE4: Final[int] +ID_VIEW_BROWSE: Final[int] +ID_VIEW_FIXED_FONT: Final[int] +ID_VIEW_INTERACTIVE: Final[int] +ID_VIEW_OPTIONS: Final[int] +ID_VIEW_TOOLBAR_DBG: Final[int] +ID_VIEW_WHITESPACE: Final[int] +ID_VIEW_INDENTATIONGUIDES: Final[int] +ID_VIEW_EOL: Final[int] +ID_VIEW_FOLD_EXPAND: Final[int] +ID_VIEW_FOLD_EXPAND_ALL: Final[int] +ID_VIEW_FOLD_COLLAPSE: Final[int] +ID_VIEW_FOLD_COLLAPSE_ALL: Final[int] +ID_VIEW_FOLD_TOPLEVEL: Final[int] +ID_VIEW_RIGHT_EDGE: Final[int] +ID_NEXT_PANE: Final[int] +ID_PREV_PANE: Final[int] +ID_WINDOW_NEW: Final[int] +ID_WINDOW_ARRANGE: Final[int] +ID_WINDOW_CASCADE: Final[int] +ID_WINDOW_TILE_HORZ: Final[int] +ID_WINDOW_TILE_VERT: Final[int] +ID_WINDOW_SPLIT: Final[int] +ID_EDIT_CLEAR: Final[int] +ID_EDIT_CLEAR_ALL: Final[int] +ID_EDIT_COPY: Final[int] +ID_EDIT_CUT: Final[int] +ID_EDIT_FIND: Final[int] +ID_EDIT_GOTO_LINE: Final[int] +ID_EDIT_PASTE: Final[int] +ID_EDIT_REPEAT: Final[int] +ID_EDIT_REPLACE: Final[int] +ID_EDIT_SELECT_ALL: Final[int] +ID_EDIT_SELECT_BLOCK: Final[int] +ID_EDIT_UNDO: Final[int] +ID_EDIT_REDO: Final[int] +ID_VIEW_TOOLBAR: Final[int] +ID_VIEW_STATUS_BAR: Final[int] +ID_SEPARATOR: Final[int] +IDR_DEBUGGER: Final[int] +IDR_PYTHONTYPE_CNTR_IP: Final[int] +IDR_MAINFRAME: Final[int] +IDR_PYTHONTYPE: Final[int] +IDR_PYTHONCONTYPE: Final[int] +IDR_TEXTTYPE: Final[int] +IDR_CNTR_INPLACE: Final[int] +CDocTemplate_windowTitle: Final[int] +CDocTemplate_docName: Final[int] +CDocTemplate_fileNewName: Final[int] +CDocTemplate_filterName: Final[int] +CDocTemplate_filterExt: Final[int] +CDocTemplate_regFileTypeId: Final[int] +CDocTemplate_regFileTypeName: Final[int] +CDocTemplate_Confidence_noAttempt: Final[int] +CDocTemplate_Confidence_maybeAttemptForeign: Final[int] +CDocTemplate_Confidence_maybeAttemptNative: Final[int] +CDocTemplate_Confidence_yesAttemptForeign: Final[int] +CDocTemplate_Confidence_yesAttemptNative: Final[int] +CDocTemplate_Confidence_yesAlreadyOpen: Final[int] +CRichEditView_WrapNone: Final[int] +CRichEditView_WrapToWindow: Final[int] +CRichEditView_WrapToTargetDevice: Final[int] +PD_ALLPAGES: Final[int] +PD_COLLATE: Final[int] +PD_DISABLEPRINTTOFILE: Final[int] +PD_ENABLEPRINTHOOK: Final[int] +PD_ENABLEPRINTTEMPLATE: Final[int] +PD_ENABLEPRINTTEMPLATEHANDLE: Final[int] +PD_ENABLESETUPHOOK: Final[int] +PD_ENABLESETUPTEMPLATE: Final[int] +PD_ENABLESETUPTEMPLATEHANDLE: Final[int] +PD_HIDEPRINTTOFILE: Final[int] +PD_NONETWORKBUTTON: Final[int] +PD_NOPAGENUMS: Final[int] +PD_NOSELECTION: Final[int] +PD_NOWARNING: Final[int] +PD_PAGENUMS: Final[int] +PD_PRINTSETUP: Final[int] +PD_PRINTTOFILE: Final[int] +PD_RETURNDC: Final[int] +PD_RETURNDEFAULT: Final[int] +PD_RETURNIC: Final[int] +PD_SELECTION: Final[int] +PD_SHOWHELP: Final[int] +PD_USEDEVMODECOPIES: Final[int] +PD_USEDEVMODECOPIESANDCOLLATE: Final[int] +PSWIZB_BACK: Final[int] +PSWIZB_NEXT: Final[int] +PSWIZB_FINISH: Final[int] +PSWIZB_DISABLEDFINISH: Final[int] +MFS_SYNCACTIVE: Final[int] +MFS_4THICKFRAME: Final[int] +MFS_THICKFRAME: Final[int] +MFS_MOVEFRAME: Final[int] +MFS_BLOCKSYSMENU: Final[int] +LM_STRETCH: Final[int] +LM_HORZ: Final[int] +LM_MRUWIDTH: Final[int] +LM_HORZDOCK: Final[int] +LM_VERTDOCK: Final[int] +LM_LENGTHY: Final[int] +LM_COMMIT: Final[int] +debug: Final[int] +copyright: Final[str] +dllhandle: Final[int] +types: Final[dict[str, type]] diff --git a/stubs/pywin32/pythonwin/win32uiole.pyi b/stubs/pywin32/pythonwin/win32uiole.pyi new file mode 100644 index 000000000000..211e0629a923 --- /dev/null +++ b/stubs/pywin32/pythonwin/win32uiole.pyi @@ -0,0 +1,29 @@ +from typing import Final, Literal + +import _win32typing + +def AfxOleInit() -> bool: ... +def CreateInsertDialog() -> _win32typing.PyCOleInsertDialog: ... +def CreateOleClientItem(doc: _win32typing.PyCOleDocument) -> _win32typing.PyCOleClientItem: ... +def CreateOleDocument( + template: _win32typing.PyCDocTemplate | _win32typing.DocTemplate, fileName: str | None = None, / +) -> _win32typing.PyCOleDocument: ... +def DaoGetEngine() -> _win32typing.PyIDispatch: ... +def GetIDispatchForWindow(Wnd, /) -> _win32typing.PyIDispatch: ... +def OleGetUserCtrl() -> int: ... +def OleSetUserCtrl(bUserCtrl: bool | Literal[0, 1], /) -> None: ... +def SetMessagePendingDelay(delay: int, /) -> None: ... +def EnableNotRespondingDialog(enabled: bool | Literal[0, 1], /) -> None: ... +def EnableBusyDialog(enabled: bool | Literal[0, 1], /) -> None: ... + +COleClientItem_emptyState: Final[int] +COleClientItem_loadedState: Final[int] +COleClientItem_openState: Final[int] +COleClientItem_activeState: Final[int] +COleClientItem_activeUIState: Final[int] +OLE_CHANGED: Final[int] +OLE_SAVED: Final[int] +OLE_CLOSED: Final[int] +OLE_RENAMED: Final[int] +OLE_CHANGED_STATE: Final[int] +OLE_CHANGED_ASPECT: Final[int] diff --git a/stubs/pywin32/pywintypes.pyi b/stubs/pywin32/pywintypes.pyi new file mode 100644 index 000000000000..64c9f845cf94 --- /dev/null +++ b/stubs/pywin32/pywintypes.pyi @@ -0,0 +1 @@ +from win32.lib.pywintypes import * diff --git a/stubs/pywin32/regutil.pyi b/stubs/pywin32/regutil.pyi new file mode 100644 index 000000000000..ef4d7a48c231 --- /dev/null +++ b/stubs/pywin32/regutil.pyi @@ -0,0 +1 @@ +from win32.lib.regutil import * diff --git a/stubs/pywin32/servicemanager.pyi b/stubs/pywin32/servicemanager.pyi new file mode 100644 index 000000000000..91dbd289360e --- /dev/null +++ b/stubs/pywin32/servicemanager.pyi @@ -0,0 +1 @@ +from win32.servicemanager import * diff --git a/stubs/pywin32/sspicon.pyi b/stubs/pywin32/sspicon.pyi new file mode 100644 index 000000000000..0618e191ed7e --- /dev/null +++ b/stubs/pywin32/sspicon.pyi @@ -0,0 +1 @@ +from win32.lib.sspicon import * diff --git a/stubs/pywin32/timer.pyi b/stubs/pywin32/timer.pyi new file mode 100644 index 000000000000..d3d280166cc4 --- /dev/null +++ b/stubs/pywin32/timer.pyi @@ -0,0 +1 @@ +from win32.timer import * diff --git a/stubs/pywin32/win2kras.pyi b/stubs/pywin32/win2kras.pyi new file mode 100644 index 000000000000..e9b12664e3e3 --- /dev/null +++ b/stubs/pywin32/win2kras.pyi @@ -0,0 +1 @@ +from win32.lib.win2kras import * diff --git a/stubs/pywin32/win32/__init__.pyi b/stubs/pywin32/win32/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32/lib/__init__.pyi b/stubs/pywin32/win32/lib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32/lib/commctrl.pyi b/stubs/pywin32/win32/lib/commctrl.pyi new file mode 100644 index 000000000000..e88a3f760ce0 --- /dev/null +++ b/stubs/pywin32/win32/lib/commctrl.pyi @@ -0,0 +1,1522 @@ +from typing import Final + +WM_USER: Final = 1024 +ICC_LISTVIEW_CLASSES: Final = 1 +ICC_TREEVIEW_CLASSES: Final = 2 +ICC_BAR_CLASSES: Final = 4 +ICC_TAB_CLASSES: Final = 8 +ICC_UPDOWN_CLASS: Final = 16 +ICC_PROGRESS_CLASS: Final = 32 +ICC_HOTKEY_CLASS: Final = 64 +ICC_ANIMATE_CLASS: Final = 128 +ICC_WIN95_CLASSES: Final = 255 +ICC_DATE_CLASSES: Final = 256 +ICC_USEREX_CLASSES: Final = 512 +ICC_COOL_CLASSES: Final = 1024 +ICC_INTERNET_CLASSES: Final = 2048 +ICC_PAGESCROLLER_CLASS: Final = 4096 +ICC_NATIVEFNTCTL_CLASS: Final = 8192 +ODT_HEADER: Final = 100 +ODT_TAB: Final = 101 +ODT_LISTVIEW: Final = 102 +PY_0U: Final = 0 +NM_FIRST: Final = PY_0U +NM_LAST: Final = -99 +LVN_FIRST: Final = -100 +LVN_LAST: Final = -199 +HDN_FIRST: Final = -300 +HDN_LAST: Final = -399 +TVN_FIRST: Final = -400 +TVN_LAST: Final = -499 +TTN_FIRST: Final = -520 +TTN_LAST: Final = -549 +TCN_FIRST: Final = -550 +TCN_LAST: Final = -580 +CDN_FIRST: Final = -601 +CDN_LAST: Final = -699 +TBN_FIRST: Final = -700 +TBN_LAST: Final = -720 +UDN_FIRST: Final = -721 +UDN_LAST: Final = -740 +MCN_FIRST: Final = -750 +MCN_LAST: Final = -759 +DTN_FIRST: Final = -760 +DTN_LAST: Final = -799 +CBEN_FIRST: Final = -800 +CBEN_LAST: Final = -830 +RBN_FIRST: Final = -831 +RBN_LAST: Final = -859 +IPN_FIRST: Final = -860 +IPN_LAST: Final = -879 +SBN_FIRST: Final = -880 +SBN_LAST: Final = -899 +PGN_FIRST: Final = -900 +PGN_LAST: Final = -950 +LVM_FIRST: Final = 4096 +TV_FIRST: Final = 4352 +HDM_FIRST: Final = 4608 +TCM_FIRST: Final = 4864 +PGM_FIRST: Final = 5120 +CCM_FIRST: Final = 8192 +CCM_SETBKCOLOR: Final = 8193 +CCM_SETCOLORSCHEME: Final = 8194 +CCM_GETCOLORSCHEME: Final = 8195 +CCM_GETDROPTARGET: Final = 8196 +CCM_SETUNICODEFORMAT: Final = 8197 +CCM_GETUNICODEFORMAT: Final = 8198 +INFOTIPSIZE: Final = 1024 +NM_OUTOFMEMORY: Final = -1 +NM_CLICK: Final = -2 +NM_DBLCLK: Final = -3 +NM_RETURN: Final = -4 +NM_RCLICK: Final = -5 +NM_RDBLCLK: Final = -6 +NM_SETFOCUS: Final = -7 +NM_KILLFOCUS: Final = -8 +NM_CUSTOMDRAW: Final = -12 +NM_HOVER: Final = -13 +NM_NCHITTEST: Final = -14 +NM_KEYDOWN: Final = -15 +NM_RELEASEDCAPTURE: Final = -16 +NM_SETCURSOR: Final = -17 +NM_CHAR: Final = -18 +MSGF_COMMCTRL_BEGINDRAG: Final = 16896 +MSGF_COMMCTRL_SIZEHEADER: Final = 16897 +MSGF_COMMCTRL_DRAGSELECT: Final = 16898 +MSGF_COMMCTRL_TOOLBARCUST: Final = 16899 +CDRF_DODEFAULT: Final = 0 +CDRF_NEWFONT: Final = 2 +CDRF_SKIPDEFAULT: Final = 4 +CDRF_NOTIFYPOSTPAINT: Final = 16 +CDRF_NOTIFYITEMDRAW: Final = 32 +CDRF_NOTIFYSUBITEMDRAW: Final = 32 +CDRF_NOTIFYPOSTERASE: Final = 64 +CDDS_PREPAINT: Final = 1 +CDDS_POSTPAINT: Final = 2 +CDDS_PREERASE: Final = 3 +CDDS_POSTERASE: Final = 4 +CDDS_ITEM: Final = 65536 +CDDS_ITEMPREPAINT: Final = 65537 +CDDS_ITEMPOSTPAINT: Final = 65538 +CDDS_ITEMPREERASE: Final = 65539 +CDDS_ITEMPOSTERASE: Final = 65540 +CDDS_SUBITEM: Final = 131072 +CDIS_SELECTED: Final = 1 +CDIS_GRAYED: Final = 2 +CDIS_DISABLED: Final = 4 +CDIS_CHECKED: Final = 8 +CDIS_FOCUS: Final = 16 +CDIS_DEFAULT: Final = 32 +CDIS_HOT: Final = 64 +CDIS_MARKED: Final = 128 +CDIS_INDETERMINATE: Final = 256 +CLR_NONE: Final = -1 +CLR_DEFAULT: Final = -16777216 +ILC_MASK: Final = 1 +ILC_COLOR: Final = 0 +ILC_COLORDDB: Final = 254 +ILC_COLOR4: Final = 4 +ILC_COLOR8: Final = 8 +ILC_COLOR16: Final = 16 +ILC_COLOR24: Final = 24 +ILC_COLOR32: Final = 32 +ILC_PALETTE: Final = 2048 +ILD_NORMAL: Final = 0 +ILD_TRANSPARENT: Final = 1 +ILD_MASK: Final = 16 +ILD_IMAGE: Final = 32 +ILD_ROP: Final = 64 +ILD_BLEND25: Final = 2 +ILD_BLEND50: Final = 4 +ILD_OVERLAYMASK: Final = 3840 +ILD_SELECTED: Final = ILD_BLEND50 +ILD_FOCUS: Final = ILD_BLEND25 +ILD_BLEND: Final = ILD_BLEND50 +CLR_HILIGHT: Final = CLR_DEFAULT +ILCF_MOVE: Final = 0 +ILCF_SWAP: Final = 1 +WC_HEADERA: Final = "SysHeader32" +WC_HEADER: Final = WC_HEADERA +HDS_HORZ: Final = 0 +HDS_BUTTONS: Final = 2 +HDS_HOTTRACK: Final = 4 +HDS_HIDDEN: Final = 8 +HDS_DRAGDROP: Final = 64 +HDS_FULLDRAG: Final = 128 +HDI_WIDTH: Final = 1 +HDI_HEIGHT: Final = HDI_WIDTH +HDI_TEXT: Final = 2 +HDI_FORMAT: Final = 4 +HDI_LPARAM: Final = 8 +HDI_BITMAP: Final = 16 +HDI_IMAGE: Final = 32 +HDI_DI_SETITEM: Final = 64 +HDI_ORDER: Final = 128 +HDF_LEFT: Final = 0 +HDF_RIGHT: Final = 1 +HDF_CENTER: Final = 2 +HDF_JUSTIFYMASK: Final = 3 +HDF_RTLREADING: Final = 4 +HDF_OWNERDRAW: Final = 32768 +HDF_STRING: Final = 16384 +HDF_BITMAP: Final = 8192 +HDF_BITMAP_ON_RIGHT: Final = 4096 +HDF_IMAGE: Final = 2048 +HDM_GETITEMCOUNT: Final = 4608 +HDM_INSERTITEMA: Final = 4609 +HDM_INSERTITEMW: Final = 4618 +HDM_INSERTITEM: Final = HDM_INSERTITEMA +HDM_DELETEITEM: Final = 4610 +HDM_GETITEMA: Final = 4611 +HDM_GETITEMW: Final = 4619 +HDM_GETITEM: Final = HDM_GETITEMA +HDM_SETITEMA: Final = 4612 +HDM_SETITEMW: Final = 4620 +HDM_SETITEM: Final = HDM_SETITEMA +HDM_LAYOUT: Final = 4613 +HHT_NOWHERE: Final = 1 +HHT_ONHEADER: Final = 2 +HHT_ONDIVIDER: Final = 4 +HHT_ONDIVOPEN: Final = 8 +HHT_ABOVE: Final = 256 +HHT_BELOW: Final = 512 +HHT_TORIGHT: Final = 1024 +HHT_TOLEFT: Final = 2048 +HDM_HITTEST: Final = 4614 +HDM_GETITEMRECT: Final = 4615 +HDM_SETIMAGELIST: Final = 4616 +HDM_GETIMAGELIST: Final = 4617 +HDM_ORDERTOINDEX: Final = 4623 +HDM_CREATEDRAGIMAGE: Final = 4624 +HDM_GETORDERARRAY: Final = 4625 +HDM_SETORDERARRAY: Final = 4626 +HDM_SETHOTDIVIDER: Final = 4627 +HDM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +HDM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +HDN_ITEMCHANGINGA: Final = -300 +HDN_ITEMCHANGINGW: Final = -320 +HDN_ITEMCHANGEDA: Final = -301 +HDN_ITEMCHANGEDW: Final = -321 +HDN_ITEMCLICKA: Final = -302 +HDN_ITEMCLICKW: Final = -322 +HDN_ITEMDBLCLICKA: Final = -303 +HDN_ITEMDBLCLICKW: Final = -323 +HDN_DIVIDERDBLCLICKA: Final = -305 +HDN_DIVIDERDBLCLICKW: Final = -325 +HDN_BEGINTRACKA: Final = -306 +HDN_BEGINTRACKW: Final = -326 +HDN_ENDTRACKA: Final = -307 +HDN_ENDTRACKW: Final = -327 +HDN_TRACKA: Final = -308 +HDN_TRACKW: Final = -328 +HDN_GETDISPINFOA: Final = -309 +HDN_GETDISPINFOW: Final = -329 +HDN_BEGINDRAG: Final = -310 +HDN_ENDDRAG: Final = -311 +HDN_ITEMCHANGING: Final = HDN_ITEMCHANGINGA +HDN_ITEMCHANGED: Final = HDN_ITEMCHANGEDA +HDN_ITEMCLICK: Final = HDN_ITEMCLICKA +HDN_ITEMDBLCLICK: Final = HDN_ITEMDBLCLICKA +HDN_DIVIDERDBLCLICK: Final = HDN_DIVIDERDBLCLICKA +HDN_BEGINTRACK: Final = HDN_BEGINTRACKA +HDN_ENDTRACK: Final = HDN_ENDTRACKA +HDN_TRACK: Final = HDN_TRACKA +HDN_GETDISPINFO: Final = HDN_GETDISPINFOA +TOOLBARCLASSNAMEA: Final = "ToolbarWindow32" +TOOLBARCLASSNAME: Final = TOOLBARCLASSNAMEA +CMB_MASKED: Final = 2 +TBSTATE_CHECKED: Final = 1 +TBSTATE_PRESSED: Final = 2 +TBSTATE_ENABLED: Final = 4 +TBSTATE_HIDDEN: Final = 8 +TBSTATE_INDETERMINATE: Final = 16 +TBSTATE_WRAP: Final = 32 +TBSTATE_ELLIPSES: Final = 64 +TBSTATE_MARKED: Final = 128 +TBSTYLE_BUTTON: Final = 0 +TBSTYLE_SEP: Final = 1 +TBSTYLE_CHECK: Final = 2 +TBSTYLE_GROUP: Final = 4 +TBSTYLE_CHECKGROUP: Final = 6 +TBSTYLE_DROPDOWN: Final = 8 +TBSTYLE_AUTOSIZE: Final = 16 +TBSTYLE_NOPREFIX: Final = 32 +TBSTYLE_TOOLTIPS: Final = 256 +TBSTYLE_WRAPABLE: Final = 512 +TBSTYLE_ALTDRAG: Final = 1024 +TBSTYLE_FLAT: Final = 2048 +TBSTYLE_LIST: Final = 4096 +TBSTYLE_CUSTOMERASE: Final = 8192 +TBSTYLE_REGISTERDROP: Final = 16384 +TBSTYLE_TRANSPARENT: Final = 32768 +TBSTYLE_EX_DRAWDDARROWS: Final = 1 +BTNS_BUTTON: Final = TBSTYLE_BUTTON +BTNS_SEP: Final = TBSTYLE_SEP +BTNS_CHECK: Final = TBSTYLE_CHECK +BTNS_GROUP: Final = TBSTYLE_GROUP +BTNS_CHECKGROUP: Final = TBSTYLE_CHECKGROUP +BTNS_DROPDOWN: Final = TBSTYLE_DROPDOWN +BTNS_AUTOSIZE: Final = TBSTYLE_AUTOSIZE +BTNS_NOPREFIX: Final = TBSTYLE_NOPREFIX +BTNS_SHOWTEXT: Final = 64 +BTNS_WHOLEDROPDOWN: Final = 128 +TBCDRF_NOEDGES: Final = 65536 +TBCDRF_HILITEHOTTRACK: Final = 131072 +TBCDRF_NOOFFSET: Final = 262144 +TBCDRF_NOMARK: Final = 524288 +TBCDRF_NOETCHEDEFFECT: Final = 1048576 +TB_ENABLEBUTTON: Final = 1025 +TB_CHECKBUTTON: Final = 1026 +TB_PRESSBUTTON: Final = 1027 +TB_HIDEBUTTON: Final = 1028 +TB_INDETERMINATE: Final = 1029 +TB_MARKBUTTON: Final = 1030 +TB_ISBUTTONENABLED: Final = 1033 +TB_ISBUTTONCHECKED: Final = 1034 +TB_ISBUTTONPRESSED: Final = 1035 +TB_ISBUTTONHIDDEN: Final = 1036 +TB_ISBUTTONINDETERMINATE: Final = 1037 +TB_ISBUTTONHIGHLIGHTED: Final = 1038 +TB_SETSTATE: Final = 1041 +TB_GETSTATE: Final = 1042 +TB_ADDBITMAP: Final = 1043 +HINST_COMMCTRL: Final = -1 +IDB_STD_SMALL_COLOR: Final = 0 +IDB_STD_LARGE_COLOR: Final = 1 +IDB_VIEW_SMALL_COLOR: Final = 4 +IDB_VIEW_LARGE_COLOR: Final = 5 +IDB_HIST_SMALL_COLOR: Final = 8 +IDB_HIST_LARGE_COLOR: Final = 9 +STD_CUT: Final = 0 +STD_COPY: Final = 1 +STD_PASTE: Final = 2 +STD_UNDO: Final = 3 +STD_REDOW: Final = 4 +STD_DELETE: Final = 5 +STD_FILENEW: Final = 6 +STD_FILEOPEN: Final = 7 +STD_FILESAVE: Final = 8 +STD_PRINTPRE: Final = 9 +STD_PROPERTIES: Final = 10 +STD_HELP: Final = 11 +STD_FIND: Final = 12 +STD_REPLACE: Final = 13 +STD_PRINT: Final = 14 +VIEW_LARGEICONS: Final = 0 +VIEW_SMALLICONS: Final = 1 +VIEW_LIST: Final = 2 +VIEW_DETAILS: Final = 3 +VIEW_SORTNAME: Final = 4 +VIEW_SORTSIZE: Final = 5 +VIEW_SORTDATE: Final = 6 +VIEW_SORTTYPE: Final = 7 +VIEW_PARENTFOLDER: Final = 8 +VIEW_NETCONNECT: Final = 9 +VIEW_NETDISCONNECT: Final = 10 +VIEW_NEWFOLDER: Final = 11 +VIEW_VIEWMENU: Final = 12 +HIST_BACK: Final = 0 +HIST_FORWARD: Final = 1 +HIST_FAVORITES: Final = 2 +HIST_ADDTOFAVORITES: Final = 3 +HIST_VIEWTREE: Final = 4 +TB_ADDBUTTONSA: Final = 1044 +TB_INSERTBUTTONA: Final = 1045 +TB_ADDBUTTONS: Final = 1044 +TB_INSERTBUTTON: Final = 1045 +TB_DELETEBUTTON: Final = 1046 +TB_GETBUTTON: Final = 1047 +TB_BUTTONCOUNT: Final = 1048 +TB_COMMANDTOINDEX: Final = 1049 +TB_SAVERESTOREA: Final = 1050 +TB_SAVERESTOREW: Final = 1100 +TB_CUSTOMIZE: Final = 1051 +TB_ADDSTRINGA: Final = 1052 +TB_ADDSTRINGW: Final = 1101 +TB_GETITEMRECT: Final = 1053 +TB_BUTTONSTRUCTSIZE: Final = 1054 +TB_SETBUTTONSIZE: Final = 1055 +TB_SETBITMAPSIZE: Final = 1056 +TB_AUTOSIZE: Final = 1057 +TB_GETTOOLTIPS: Final = 1059 +TB_SETTOOLTIPS: Final = 1060 +TB_SETPARENT: Final = 1061 +TB_SETROWS: Final = 1063 +TB_GETROWS: Final = 1064 +TB_SETCMDID: Final = 1066 +TB_CHANGEBITMAP: Final = 1067 +TB_GETBITMAP: Final = 1068 +TB_GETBUTTONTEXTA: Final = 1069 +TB_GETBUTTONTEXTW: Final = 1099 +TB_REPLACEBITMAP: Final = 1070 +TB_SETINDENT: Final = 1071 +TB_SETIMAGELIST: Final = 1072 +TB_GETIMAGELIST: Final = 1073 +TB_LOADIMAGES: Final = 1074 +TB_GETRECT: Final = 1075 +TB_SETHOTIMAGELIST: Final = 1076 +TB_GETHOTIMAGELIST: Final = 1077 +TB_SETDISABLEDIMAGELIST: Final = 1078 +TB_GETDISABLEDIMAGELIST: Final = 1079 +TB_SETSTYLE: Final = 1080 +TB_GETSTYLE: Final = 1081 +TB_GETBUTTONSIZE: Final = 1082 +TB_SETBUTTONWIDTH: Final = 1083 +TB_SETMAXTEXTROWS: Final = 1084 +TB_GETTEXTROWS: Final = 1085 +TB_GETBUTTONTEXT: Final = TB_GETBUTTONTEXTA +TB_SAVERESTORE: Final = TB_SAVERESTOREA +TB_ADDSTRING: Final = TB_ADDSTRINGA +TB_GETOBJECT: Final = 1086 +TB_GETHOTITEM: Final = 1095 +TB_SETHOTITEM: Final = 1096 +TB_SETANCHORHIGHLIGHT: Final = 1097 +TB_GETANCHORHIGHLIGHT: Final = 1098 +TB_MAPACCELERATORA: Final = 1102 +TBIMHT_AFTER: Final = 1 +TBIMHT_BACKGROUND: Final = 2 +TB_GETINSERTMARK: Final = 1103 +TB_SETINSERTMARK: Final = 1104 +TB_INSERTMARKHITTEST: Final = 1105 +TB_MOVEBUTTON: Final = 1106 +TB_GETMAXSIZE: Final = 1107 +TB_SETEXTENDEDSTYLE: Final = 1108 +TB_GETEXTENDEDSTYLE: Final = 1109 +TB_GETPADDING: Final = 1110 +TB_SETPADDING: Final = 1111 +TB_SETINSERTMARKCOLOR: Final = 1112 +TB_GETINSERTMARKCOLOR: Final = 1113 +TB_SETCOLORSCHEME: Final = CCM_SETCOLORSCHEME +TB_GETCOLORSCHEME: Final = CCM_GETCOLORSCHEME +TB_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +TB_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +TB_MAPACCELERATORW: Final = 1114 +TB_MAPACCELERATOR: Final = TB_MAPACCELERATORA +TBBF_LARGE: Final = 1 +TB_GETBITMAPFLAGS: Final = 1065 +TBIF_IMAGE: Final = 1 +TBIF_TEXT: Final = 2 +TBIF_STATE: Final = 4 +TBIF_STYLE: Final = 8 +TBIF_LPARAM: Final = 16 +TBIF_COMMAND: Final = 32 +TBIF_SIZE: Final = 64 +TB_GETBUTTONINFOW: Final = 1087 +TB_SETBUTTONINFOW: Final = 1088 +TB_GETBUTTONINFOA: Final = 1089 +TB_SETBUTTONINFOA: Final = 1090 +TB_INSERTBUTTONW: Final = 1091 +TB_ADDBUTTONSW: Final = 1092 +TB_HITTEST: Final = 1093 +TB_SETDRAWTEXTFLAGS: Final = 1094 +TBN_GETBUTTONINFOA: Final = -700 +TBN_GETBUTTONINFOW: Final = -720 +TBN_BEGINDRAG: Final = -701 +TBN_ENDDRAG: Final = -702 +TBN_BEGINADJUST: Final = -703 +TBN_ENDADJUST: Final = -704 +TBN_RESET: Final = -705 +TBN_QUERYINSERT: Final = -706 +TBN_QUERYDELETE: Final = -707 +TBN_TOOLBARCHANGE: Final = -708 +TBN_CUSTHELP: Final = -709 +TBN_DROPDOWN: Final = -710 +TBN_GETOBJECT: Final = -712 +HICF_OTHER: Final = 0 +HICF_MOUSE: Final = 1 +HICF_ARROWKEYS: Final = 2 +HICF_ACCELERATOR: Final = 4 +HICF_DUPACCEL: Final = 8 +HICF_ENTERING: Final = 16 +HICF_LEAVING: Final = 32 +HICF_RESELECT: Final = 64 +TBN_HOTITEMCHANGE: Final = -713 +TBN_DRAGOUT: Final = -714 +TBN_DELETINGBUTTON: Final = -715 +TBN_GETDISPINFOA: Final = -716 +TBN_GETDISPINFOW: Final = -717 +TBN_GETINFOTIPA: Final = -718 +TBN_GETINFOTIPW: Final = -719 +TBN_GETINFOTIP: Final = TBN_GETINFOTIPA +TBNF_IMAGE: Final = 1 +TBNF_TEXT: Final = 2 +TBNF_DI_SETITEM: Final = 268435456 +TBN_GETDISPINFO: Final = TBN_GETDISPINFOA +TBDDRET_DEFAULT: Final = 0 +TBDDRET_NODEFAULT: Final = 1 +TBDDRET_TREATPRESSED: Final = 2 +TBN_GETBUTTONINFO: Final = TBN_GETBUTTONINFOA +REBARCLASSNAMEA: Final = "ReBarWindow32" +REBARCLASSNAME: Final = REBARCLASSNAMEA +RBIM_IMAGELIST: Final = 1 +RBS_TOOLTIPS: Final = 256 +RBS_VARHEIGHT: Final = 512 +RBS_BANDBORDERS: Final = 1024 +RBS_FIXEDORDER: Final = 2048 +RBS_REGISTERDROP: Final = 4096 +RBS_AUTOSIZE: Final = 8192 +RBS_VERTICALGRIPPER: Final = 16384 +RBS_DBLCLKTOGGLE: Final = 32768 +RBBS_BREAK: Final = 1 +RBBS_FIXEDSIZE: Final = 2 +RBBS_CHILDEDGE: Final = 4 +RBBS_HIDDEN: Final = 8 +RBBS_NOVERT: Final = 16 +RBBS_FIXEDBMP: Final = 32 +RBBS_VARIABLEHEIGHT: Final = 64 +RBBS_GRIPPERALWAYS: Final = 128 +RBBS_NOGRIPPER: Final = 256 +RBBIM_STYLE: Final = 1 +RBBIM_COLORS: Final = 2 +RBBIM_TEXT: Final = 4 +RBBIM_IMAGE: Final = 8 +RBBIM_CHILD: Final = 16 +RBBIM_CHILDSIZE: Final = 32 +RBBIM_SIZE: Final = 64 +RBBIM_BACKGROUND: Final = 128 +RBBIM_ID: Final = 256 +RBBIM_IDEALSIZE: Final = 512 +RBBIM_LPARAM: Final = 1024 +RB_INSERTBANDA: Final = 1025 +RB_DELETEBAND: Final = 1026 +RB_GETBARINFO: Final = 1027 +RB_SETBARINFO: Final = 1028 +RB_SETBANDINFOA: Final = 1030 +RB_SETPARENT: Final = 1031 +RB_HITTEST: Final = 1032 +RB_GETRECT: Final = 1033 +RB_INSERTBANDW: Final = 1034 +RB_SETBANDINFOW: Final = 1035 +RB_GETBANDCOUNT: Final = 1036 +RB_GETROWCOUNT: Final = 1037 +RB_GETROWHEIGHT: Final = 1038 +RB_IDTOINDEX: Final = 1040 +RB_GETTOOLTIPS: Final = 1041 +RB_SETTOOLTIPS: Final = 1042 +RB_SETBKCOLOR: Final = 1043 +RB_GETBKCOLOR: Final = 1044 +RB_SETTEXTCOLOR: Final = 1045 +RB_GETTEXTCOLOR: Final = 1046 +RB_SIZETORECT: Final = 1047 +RB_SETCOLORSCHEME: Final = CCM_SETCOLORSCHEME +RB_GETCOLORSCHEME: Final = CCM_GETCOLORSCHEME +RB_INSERTBAND: Final = RB_INSERTBANDA +RB_SETBANDINFO: Final = RB_SETBANDINFOA +RB_BEGINDRAG: Final = 1048 +RB_ENDDRAG: Final = 1049 +RB_DRAGMOVE: Final = 1050 +RB_GETBARHEIGHT: Final = 1051 +RB_GETBANDINFOW: Final = 1052 +RB_GETBANDINFOA: Final = 1053 +RB_GETBANDINFO: Final = RB_GETBANDINFOA +RB_MINIMIZEBAND: Final = 1054 +RB_MAXIMIZEBAND: Final = 1055 +RB_GETDROPTARGET: Final = CCM_GETDROPTARGET +RB_GETBANDBORDERS: Final = 1058 +RB_SHOWBAND: Final = 1059 +RB_SETPALETTE: Final = 1061 +RB_GETPALETTE: Final = 1062 +RB_MOVEBAND: Final = 1063 +RB_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +RB_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +RBN_HEIGHTCHANGE: Final = -831 +RBN_GETOBJECT: Final = -832 +RBN_LAYOUTCHANGED: Final = -833 +RBN_AUTOSIZE: Final = -834 +RBN_BEGINDRAG: Final = -835 +RBN_ENDDRAG: Final = -836 +RBN_DELETINGBAND: Final = -837 +RBN_DELETEDBAND: Final = -838 +RBN_CHILDSIZE: Final = -839 +RBNM_ID: Final = 1 +RBNM_STYLE: Final = 2 +RBNM_LPARAM: Final = 4 +RBHT_NOWHERE: Final = 1 +RBHT_CAPTION: Final = 2 +RBHT_CLIENT: Final = 3 +RBHT_GRABBER: Final = 4 +TOOLTIPS_CLASSA: Final = "tooltips_class32" +TOOLTIPS_CLASS: Final = TOOLTIPS_CLASSA +TTS_ALWAYSTIP: Final = 1 +TTS_NOPREFIX: Final = 2 +TTF_IDISHWND: Final = 1 +TTF_CENTERTIP: Final = 2 +TTF_RTLREADING: Final = 4 +TTF_SUBCLASS: Final = 16 +TTF_TRACK: Final = 32 +TTF_ABSOLUTE: Final = 128 +TTF_TRANSPARENT: Final = 256 +TTF_DI_SETITEM: Final = 32768 +TTDT_AUTOMATIC: Final = 0 +TTDT_RESHOW: Final = 1 +TTDT_AUTOPOP: Final = 2 +TTDT_INITIAL: Final = 3 +TTM_ACTIVATE: Final = 1025 +TTM_SETDELAYTIME: Final = 1027 +TTM_ADDTOOLA: Final = 1028 +TTM_ADDTOOLW: Final = 1074 +TTM_DELTOOLA: Final = 1029 +TTM_DELTOOLW: Final = 1075 +TTM_NEWTOOLRECTA: Final = 1030 +TTM_NEWTOOLRECTW: Final = 1076 +TTM_RELAYEVENT: Final = 1031 +TTM_GETTOOLINFOA: Final = 1032 +TTM_GETTOOLINFOW: Final = 1077 +TTM_SETTOOLINFOA: Final = 1033 +TTM_SETTOOLINFOW: Final = 1078 +TTM_HITTESTA: Final = 1034 +TTM_HITTESTW: Final = 1079 +TTM_GETTEXTA: Final = 1035 +TTM_GETTEXTW: Final = 1080 +TTM_UPDATETIPTEXTA: Final = 1036 +TTM_UPDATETIPTEXTW: Final = 1081 +TTM_GETTOOLCOUNT: Final = 1037 +TTM_ENUMTOOLSA: Final = 1038 +TTM_ENUMTOOLSW: Final = 1082 +TTM_GETCURRENTTOOLA: Final = 1039 +TTM_GETCURRENTTOOLW: Final = 1083 +TTM_WINDOWFROMPOINT: Final = 1040 +TTM_TRACKACTIVATE: Final = 1041 +TTM_TRACKPOSITION: Final = 1042 +TTM_SETTIPBKCOLOR: Final = 1043 +TTM_SETTIPTEXTCOLOR: Final = 1044 +TTM_GETDELAYTIME: Final = 1045 +TTM_GETTIPBKCOLOR: Final = 1046 +TTM_GETTIPTEXTCOLOR: Final = 1047 +TTM_SETMAXTIPWIDTH: Final = 1048 +TTM_GETMAXTIPWIDTH: Final = 1049 +TTM_SETMARGIN: Final = 1050 +TTM_GETMARGIN: Final = 1051 +TTM_POP: Final = 1052 +TTM_UPDATE: Final = 1053 +TTM_ADDTOOL: Final = TTM_ADDTOOLA +TTM_DELTOOL: Final = TTM_DELTOOLA +TTM_NEWTOOLRECT: Final = TTM_NEWTOOLRECTA +TTM_GETTOOLINFO: Final = TTM_GETTOOLINFOA +TTM_SETTOOLINFO: Final = TTM_SETTOOLINFOA +TTM_HITTEST: Final = TTM_HITTESTA +TTM_GETTEXT: Final = TTM_GETTEXTA +TTM_UPDATETIPTEXT: Final = TTM_UPDATETIPTEXTA +TTM_ENUMTOOLS: Final = TTM_ENUMTOOLSA +TTM_GETCURRENTTOOL: Final = TTM_GETCURRENTTOOLA +TTN_GETDISPINFOA: Final = -520 +TTN_GETDISPINFOW: Final = -530 +TTN_SHOW: Final = -521 +TTN_POP: Final = -522 +TTN_GETDISPINFO: Final = TTN_GETDISPINFOA +TTN_NEEDTEXT: Final = TTN_GETDISPINFO +TTN_NEEDTEXTA: Final = TTN_GETDISPINFOA +TTN_NEEDTEXTW: Final = TTN_GETDISPINFOW +SBARS_SIZEGRIP: Final = 256 +SBARS_TOOLTIPS: Final = 2048 +STATUSCLASSNAMEA: Final = "msctls_statusbar32" +STATUSCLASSNAME: Final = STATUSCLASSNAMEA +SB_SETTEXTA: Final = 1025 +SB_SETTEXTW: Final = 1035 +SB_GETTEXTA: Final = 1026 +SB_GETTEXTW: Final = 1037 +SB_GETTEXTLENGTHA: Final = 1027 +SB_GETTEXTLENGTHW: Final = 1036 +SB_GETTEXT: Final = SB_GETTEXTA +SB_SETTEXT: Final = SB_SETTEXTA +SB_GETTEXTLENGTH: Final = SB_GETTEXTLENGTHA +SB_SETPARTS: Final = 1028 +SB_GETPARTS: Final = 1030 +SB_GETBORDERS: Final = 1031 +SB_SETMINHEIGHT: Final = 1032 +SB_SIMPLE: Final = 1033 +SB_GETRECT: Final = 1034 +SB_ISSIMPLE: Final = 1038 +SB_SETICON: Final = 1039 +SB_SETTIPTEXTA: Final = 1040 +SB_SETTIPTEXTW: Final = 1041 +SB_GETTIPTEXTA: Final = 1042 +SB_GETTIPTEXTW: Final = 1043 +SB_GETICON: Final = 1044 +SB_SETTIPTEXT: Final = SB_SETTIPTEXTA +SB_GETTIPTEXT: Final = SB_GETTIPTEXTA +SB_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +SB_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +SBT_OWNERDRAW: Final = 4096 +SBT_NOBORDERS: Final = 256 +SBT_POPOUT: Final = 512 +SBT_RTLREADING: Final = 1024 +SBT_NOTABPARSING: Final = 2048 +SBT_TOOLTIPS: Final = 2048 +SB_SETBKCOLOR: Final = CCM_SETBKCOLOR +SBN_SIMPLEMODECHANGE: Final = -880 +TRACKBAR_CLASSA: Final = "msctls_trackbar32" +TRACKBAR_CLASS: Final = TRACKBAR_CLASSA +TBS_AUTOTICKS: Final = 1 +TBS_VERT: Final = 2 +TBS_HORZ: Final = 0 +TBS_TOP: Final = 4 +TBS_BOTTOM: Final = 0 +TBS_LEFT: Final = 4 +TBS_RIGHT: Final = 0 +TBS_BOTH: Final = 8 +TBS_NOTICKS: Final = 16 +TBS_ENABLESELRANGE: Final = 32 +TBS_FIXEDLENGTH: Final = 64 +TBS_NOTHUMB: Final = 128 +TBS_TOOLTIPS: Final = 256 +TBM_GETPOS: Final = WM_USER +TBM_GETRANGEMIN: Final = 1025 +TBM_GETRANGEMAX: Final = 1026 +TBM_GETTIC: Final = 1027 +TBM_SETTIC: Final = 1028 +TBM_SETPOS: Final = 1029 +TBM_SETRANGE: Final = 1030 +TBM_SETRANGEMIN: Final = 1031 +TBM_SETRANGEMAX: Final = 1032 +TBM_CLEARTICS: Final = 1033 +TBM_SETSEL: Final = 1034 +TBM_SETSELSTART: Final = 1035 +TBM_SETSELEND: Final = 1036 +TBM_GETPTICS: Final = 1038 +TBM_GETTICPOS: Final = 1039 +TBM_GETNUMTICS: Final = 1040 +TBM_GETSELSTART: Final = 1041 +TBM_GETSELEND: Final = 1042 +TBM_CLEARSEL: Final = 1043 +TBM_SETTICFREQ: Final = 1044 +TBM_SETPAGESIZE: Final = 1045 +TBM_GETPAGESIZE: Final = 1046 +TBM_SETLINESIZE: Final = 1047 +TBM_GETLINESIZE: Final = 1048 +TBM_GETTHUMBRECT: Final = 1049 +TBM_GETCHANNELRECT: Final = 1050 +TBM_SETTHUMBLENGTH: Final = 1051 +TBM_GETTHUMBLENGTH: Final = 1052 +TBM_SETTOOLTIPS: Final = 1053 +TBM_GETTOOLTIPS: Final = 1054 +TBM_SETTIPSIDE: Final = 1055 +TBTS_TOP: Final = 0 +TBTS_LEFT: Final = 1 +TBTS_BOTTOM: Final = 2 +TBTS_RIGHT: Final = 3 +TBM_SETBUDDY: Final = 1056 +TBM_GETBUDDY: Final = 1057 +TBM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +TBM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +TB_LINEUP: Final = 0 +TB_LINEDOWN: Final = 1 +TB_PAGEUP: Final = 2 +TB_PAGEDOWN: Final = 3 +TB_THUMBPOSITION: Final = 4 +TB_THUMBTRACK: Final = 5 +TB_TOP: Final = 6 +TB_BOTTOM: Final = 7 +TB_ENDTRACK: Final = 8 +TBCD_TICS: Final = 1 +TBCD_THUMB: Final = 2 +TBCD_CHANNEL: Final = 3 +DL_BEGINDRAG: Final = 1157 +DL_DRAGGING: Final = 1158 +DL_DROPPED: Final = 1159 +DL_CANCELDRAG: Final = 1160 +DL_CURSORSET: Final = 0 +DL_STOPCURSOR: Final = 1 +DL_COPYCURSOR: Final = 2 +DL_MOVECURSOR: Final = 3 +DRAGLISTMSGSTRING: Final = "commctrl_DragListMsg" +UPDOWN_CLASSA: Final = "msctls_updown32" +UPDOWN_CLASS: Final = UPDOWN_CLASSA +UD_MAXVAL: Final = 32767 +UD_MINVAL: Final = -32767 +UDS_WRAP: Final = 1 +UDS_SETBUDDYINT: Final = 2 +UDS_ALIGNRIGHT: Final = 4 +UDS_ALIGNLEFT: Final = 8 +UDS_AUTOBUDDY: Final = 16 +UDS_ARROWKEYS: Final = 32 +UDS_HORZ: Final = 64 +UDS_NOTHOUSANDS: Final = 128 +UDS_HOTTRACK: Final = 256 +UDM_SETRANGE: Final = 1125 +UDM_GETRANGE: Final = 1126 +UDM_SETPOS: Final = 1127 +UDM_GETPOS: Final = 1128 +UDM_SETBUDDY: Final = 1129 +UDM_GETBUDDY: Final = 1130 +UDM_SETACCEL: Final = 1131 +UDM_GETACCEL: Final = 1132 +UDM_SETBASE: Final = 1133 +UDM_GETBASE: Final = 1134 +UDM_SETRANGE32: Final = 1135 +UDM_GETRANGE32: Final = 1136 +UDM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +UDM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +UDN_DELTAPOS: Final = -722 +PROGRESS_CLASSA: Final = "msctls_progress32" +PROGRESS_CLASS: Final = PROGRESS_CLASSA +PBS_SMOOTH: Final = 1 +PBS_VERTICAL: Final = 4 +PBM_SETRANGE: Final = 1025 +PBM_SETPOS: Final = 1026 +PBM_DELTAPOS: Final = 1027 +PBM_SETSTEP: Final = 1028 +PBM_STEPIT: Final = 1029 +PBM_SETRANGE32: Final = 1030 +PBM_GETRANGE: Final = 1031 +PBM_GETPOS: Final = 1032 +PBM_SETBARCOLOR: Final = 1033 +PBM_SETBKCOLOR: Final = CCM_SETBKCOLOR +HOTKEYF_SHIFT: Final = 1 +HOTKEYF_CONTROL: Final = 2 +HOTKEYF_ALT: Final = 4 +HOTKEYF_EXT: Final = 8 +HKCOMB_NONE: Final = 1 +HKCOMB_S: Final = 2 +HKCOMB_C: Final = 4 +HKCOMB_A: Final = 8 +HKCOMB_SC: Final = 16 +HKCOMB_SA: Final = 32 +HKCOMB_CA: Final = 64 +HKCOMB_SCA: Final = 128 +HKM_SETHOTKEY: Final = 1025 +HKM_GETHOTKEY: Final = 1026 +HKM_SETRULES: Final = 1027 +HOTKEY_CLASSA: Final = "msctls_hotkey32" +HOTKEY_CLASS: Final = HOTKEY_CLASSA +CCS_TOP: Final = 0x00000001 +CCS_NOMOVEY: Final = 0x00000002 +CCS_BOTTOM: Final = 0x00000003 +CCS_NORESIZE: Final = 0x00000004 +CCS_NOPARENTALIGN: Final = 0x00000008 +CCS_ADJUSTABLE: Final = 0x00000020 +CCS_NODIVIDER: Final = 0x00000040 +CCS_VERT: Final = 0x00000080 +CCS_LEFT: Final = 0x00000081 +CCS_RIGHT: Final = 0x00000083 +CCS_NOMOVEX: Final = 0x00000082 +WC_LISTVIEWA: Final = "SysListView32" +WC_LISTVIEW: Final = WC_LISTVIEWA +LVS_ICON: Final = 0 +LVS_REPORT: Final = 1 +LVS_SMALLICON: Final = 2 +LVS_LIST: Final = 3 +LVS_TYPEMASK: Final = 3 +LVS_SINGLESEL: Final = 4 +LVS_SHOWSELALWAYS: Final = 8 +LVS_SORTASCENDING: Final = 16 +LVS_SORTDESCENDING: Final = 32 +LVS_SHAREIMAGELISTS: Final = 64 +LVS_NOLABELWRAP: Final = 128 +LVS_AUTOARRANGE: Final = 256 +LVS_EDITLABELS: Final = 512 +LVS_OWNERDATA: Final = 4096 +LVS_NOSCROLL: Final = 8192 +LVS_TYPESTYLEMASK: Final = 64512 +LVS_ALIGNTOP: Final = 0 +LVS_ALIGNLEFT: Final = 2048 +LVS_ALIGNMASK: Final = 3072 +LVS_OWNERDRAWFIXED: Final = 1024 +LVS_NOCOLUMNHEADER: Final = 16384 +LVS_NOSORTHEADER: Final = 32768 +LVM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +LVM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +LVM_GETBKCOLOR: Final = 4096 +LVM_SETBKCOLOR: Final = 4097 +LVM_GETIMAGELIST: Final = 4098 +LVSIL_NORMAL: Final = 0 +LVSIL_SMALL: Final = 1 +LVSIL_STATE: Final = 2 +LVM_SETIMAGELIST: Final = 4099 +LVM_GETITEMCOUNT: Final = 4100 +LVIF_TEXT: Final = 1 +LVIF_IMAGE: Final = 2 +LVIF_PARAM: Final = 4 +LVIF_STATE: Final = 8 +LVIF_INDENT: Final = 16 +LVIF_NORECOMPUTE: Final = 2048 +LVIS_FOCUSED: Final = 1 +LVIS_SELECTED: Final = 2 +LVIS_CUT: Final = 4 +LVIS_DROPHILITED: Final = 8 +LVIS_ACTIVATING: Final = 32 +LVIS_OVERLAYMASK: Final = 3840 +LVIS_STATEIMAGEMASK: Final = 61440 +I_INDENTCALLBACK: Final = -1 +LPSTR_TEXTCALLBACKA: Final = -1 +LPSTR_TEXTCALLBACK: Final = LPSTR_TEXTCALLBACKA +I_IMAGECALLBACK: Final = -1 +LVM_GETITEMA: Final = 4101 +LVM_GETITEMW: Final = 4171 +LVM_GETITEM: Final = LVM_GETITEMA +LVM_SETITEMA: Final = 4102 +LVM_SETITEMW: Final = 4172 +LVM_SETITEM: Final = LVM_SETITEMA +LVM_INSERTITEMA: Final = 4103 +LVM_INSERTITEMW: Final = 4173 +LVM_INSERTITEM: Final = LVM_INSERTITEMA +LVM_DELETEITEM: Final = 4104 +LVM_DELETEALLITEMS: Final = 4105 +LVM_GETCALLBACKMASK: Final = 4106 +LVM_SETCALLBACKMASK: Final = 4107 +LVNI_ALL: Final = 0 +LVNI_FOCUSED: Final = 1 +LVNI_SELECTED: Final = 2 +LVNI_CUT: Final = 4 +LVNI_DROPHILITED: Final = 8 +LVNI_ABOVE: Final = 256 +LVNI_BELOW: Final = 512 +LVNI_TOLEFT: Final = 1024 +LVNI_TORIGHT: Final = 2048 +LVM_GETNEXTITEM: Final = 4108 +LVFI_PARAM: Final = 1 +LVFI_STRING: Final = 2 +LVFI_PARTIAL: Final = 8 +LVFI_WRAP: Final = 32 +LVFI_NEARESTXY: Final = 64 +LVM_FINDITEMA: Final = 4109 +LVM_FINDITEMW: Final = 4179 +LVM_FINDITEM: Final = LVM_FINDITEMA +LVIR_BOUNDS: Final = 0 +LVIR_ICON: Final = 1 +LVIR_LABEL: Final = 2 +LVIR_SELECTBOUNDS: Final = 3 +LVM_GETITEMRECT: Final = 4110 +LVM_SETITEMPOSITION: Final = 4111 +LVM_GETITEMPOSITION: Final = 4112 +LVM_GETSTRINGWIDTHA: Final = 4113 +LVM_GETSTRINGWIDTHW: Final = 4183 +LVM_GETSTRINGWIDTH: Final = LVM_GETSTRINGWIDTHA +LVHT_NOWHERE: Final = 1 +LVHT_ONITEMICON: Final = 2 +LVHT_ONITEMLABEL: Final = 4 +LVHT_ONITEMSTATEICON: Final = 8 +LVHT_ONITEM: Final = 14 +LVHT_ABOVE: Final = 8 +LVHT_BELOW: Final = 16 +LVHT_TORIGHT: Final = 32 +LVHT_TOLEFT: Final = 64 +LVM_HITTEST: Final = 4114 +LVM_ENSUREVISIBLE: Final = 4115 +LVM_SCROLL: Final = 4116 +LVM_REDRAWITEMS: Final = 4117 +LVA_DEFAULT: Final = 0 +LVA_ALIGNLEFT: Final = 1 +LVA_ALIGNTOP: Final = 2 +LVA_SNAPTOGRID: Final = 5 +LVM_ARRANGE: Final = 4118 +LVM_EDITLABELA: Final = 4119 +LVM_EDITLABELW: Final = 4214 +LVM_EDITLABEL: Final = LVM_EDITLABELA +LVM_GETEDITCONTROL: Final = 4120 +LVCF_FMT: Final = 1 +LVCF_WIDTH: Final = 2 +LVCF_TEXT: Final = 4 +LVCF_SUBITEM: Final = 8 +LVCF_IMAGE: Final = 16 +LVCF_ORDER: Final = 32 +LVCFMT_LEFT: Final = 0 +LVCFMT_RIGHT: Final = 1 +LVCFMT_CENTER: Final = 2 +LVCFMT_JUSTIFYMASK: Final = 3 +LVCFMT_IMAGE: Final = 2048 +LVCFMT_BITMAP_ON_RIGHT: Final = 4096 +LVCFMT_COL_HAS_IMAGES: Final = 32768 +LVM_GETCOLUMNA: Final = 4121 +LVM_GETCOLUMNW: Final = 4191 +LVM_GETCOLUMN: Final = LVM_GETCOLUMNA +LVM_SETCOLUMNA: Final = 4122 +LVM_SETCOLUMNW: Final = 4192 +LVM_SETCOLUMN: Final = LVM_SETCOLUMNA +LVM_INSERTCOLUMNA: Final = 4123 +LVM_INSERTCOLUMNW: Final = 4193 +LVM_INSERTCOLUMN: Final = LVM_INSERTCOLUMNA +LVM_DELETECOLUMN: Final = 4124 +LVM_GETCOLUMNWIDTH: Final = 4125 +LVSCW_AUTOSIZE: Final = -1 +LVSCW_AUTOSIZE_USEHEADER: Final = -2 +LVM_SETCOLUMNWIDTH: Final = 4126 +LVM_GETHEADER: Final = 4127 +LVM_CREATEDRAGIMAGE: Final = 4129 +LVM_GETVIEWRECT: Final = 4130 +LVM_GETTEXTCOLOR: Final = 4131 +LVM_SETTEXTCOLOR: Final = 4132 +LVM_GETTEXTBKCOLOR: Final = 4133 +LVM_SETTEXTBKCOLOR: Final = 4134 +LVM_GETTOPINDEX: Final = 4135 +LVM_GETCOUNTPERPAGE: Final = 4136 +LVM_GETORIGIN: Final = 4137 +LVM_UPDATE: Final = 4138 +LVM_SETITEMSTATE: Final = 4139 +LVM_GETITEMSTATE: Final = 4140 +LVM_GETITEMTEXTA: Final = 4141 +LVM_GETITEMTEXTW: Final = 4211 +LVM_GETITEMTEXT: Final = LVM_GETITEMTEXTA +LVM_SETITEMTEXTA: Final = 4142 +LVM_SETITEMTEXTW: Final = 4212 +LVM_SETITEMTEXT: Final = LVM_SETITEMTEXTA +LVSICF_NOINVALIDATEALL: Final = 1 +LVSICF_NOSCROLL: Final = 2 +LVM_SETITEMCOUNT: Final = 4143 +LVM_SORTITEMS: Final = 4144 +LVM_SETITEMPOSITION32: Final = 4145 +LVM_GETSELECTEDCOUNT: Final = 4146 +LVM_GETITEMSPACING: Final = 4147 +LVM_GETISEARCHSTRINGA: Final = 4148 +LVM_GETISEARCHSTRINGW: Final = 4213 +LVM_GETISEARCHSTRING: Final = LVM_GETISEARCHSTRINGA +LVM_SETICONSPACING: Final = 4149 +LVM_SETEXTENDEDLISTVIEWSTYLE: Final = 4150 +LVM_GETEXTENDEDLISTVIEWSTYLE: Final = 4151 +LVS_EX_GRIDLINES: Final = 1 +LVS_EX_SUBITEMIMAGES: Final = 2 +LVS_EX_CHECKBOXES: Final = 4 +LVS_EX_TRACKSELECT: Final = 8 +LVS_EX_HEADERDRAGDROP: Final = 16 +LVS_EX_FULLROWSELECT: Final = 32 +LVS_EX_ONECLICKACTIVATE: Final = 64 +LVS_EX_TWOCLICKACTIVATE: Final = 128 +LVS_EX_FLATSB: Final = 256 +LVS_EX_REGIONAL: Final = 512 +LVS_EX_INFOTIP: Final = 1024 +LVS_EX_UNDERLINEHOT: Final = 2048 +LVS_EX_UNDERLINECOLD: Final = 4096 +LVS_EX_MULTIWORKAREAS: Final = 8192 +LVM_GETSUBITEMRECT: Final = 4152 +LVM_SUBITEMHITTEST: Final = 4153 +LVM_SETCOLUMNORDERARRAY: Final = 4154 +LVM_GETCOLUMNORDERARRAY: Final = 4155 +LVM_SETHOTITEM: Final = 4156 +LVM_GETHOTITEM: Final = 4157 +LVM_SETHOTCURSOR: Final = 4158 +LVM_GETHOTCURSOR: Final = 4159 +LVM_APPROXIMATEVIEWRECT: Final = 4160 +LV_MAX_WORKAREAS: Final = 16 +LVM_SETWORKAREAS: Final = 4161 +LVM_GETWORKAREAS: Final = 4166 +LVM_GETNUMBEROFWORKAREAS: Final = 4169 +LVM_GETSELECTIONMARK: Final = 4162 +LVM_SETSELECTIONMARK: Final = 4163 +LVM_SETHOVERTIME: Final = 4167 +LVM_GETHOVERTIME: Final = 4168 +LVM_SETTOOLTIPS: Final = 4170 +LVM_GETTOOLTIPS: Final = 4174 +LVBKIF_SOURCE_NONE: Final = 0 +LVBKIF_SOURCE_HBITMAP: Final = 1 +LVBKIF_SOURCE_URL: Final = 2 +LVBKIF_SOURCE_MASK: Final = 3 +LVBKIF_STYLE_NORMAL: Final = 0 +LVBKIF_STYLE_TILE: Final = 16 +LVBKIF_STYLE_MASK: Final = 16 +LVM_SETBKIMAGEA: Final = 4164 +LVM_SETBKIMAGEW: Final = 4234 +LVM_GETBKIMAGEA: Final = 4165 +LVM_GETBKIMAGEW: Final = 4235 +LVKF_ALT: Final = 1 +LVKF_CONTROL: Final = 2 +LVKF_SHIFT: Final = 4 +LVN_ITEMCHANGING: Final = -100 +LVN_ITEMCHANGED: Final = -101 +LVN_INSERTITEM: Final = -102 +LVN_DELETEITEM: Final = -103 +LVN_DELETEALLITEMS: Final = -104 +LVN_BEGINLABELEDITA: Final = -105 +LVN_BEGINLABELEDITW: Final = -175 +LVN_ENDLABELEDITA: Final = -106 +LVN_ENDLABELEDITW: Final = -176 +LVN_COLUMNCLICK: Final = -108 +LVN_BEGINDRAG: Final = -109 +LVN_BEGINRDRAG: Final = -111 +LVN_ODCACHEHINT: Final = -113 +LVN_ODFINDITEMA: Final = -152 +LVN_ODFINDITEMW: Final = -179 +LVN_ITEMACTIVATE: Final = -114 +LVN_ODSTATECHANGED: Final = -115 +LVN_ODFINDITEM: Final = LVN_ODFINDITEMA +LVN_HOTTRACK: Final = -121 +LVN_GETDISPINFOA: Final = -150 +LVN_GETDISPINFOW: Final = -177 +LVN_SETDISPINFOA: Final = -151 +LVN_SETDISPINFOW: Final = -178 +LVN_BEGINLABELEDIT: Final = LVN_BEGINLABELEDITA +LVN_ENDLABELEDIT: Final = LVN_ENDLABELEDITA +LVN_GETDISPINFO: Final = LVN_GETDISPINFOA +LVN_SETDISPINFO: Final = LVN_SETDISPINFOA +LVIF_DI_SETITEM: Final = 4096 +LVN_KEYDOWN: Final = -155 +LVN_MARQUEEBEGIN: Final = -156 +LVGIT_UNFOLDED: Final = 1 +LVN_GETINFOTIPA: Final = -157 +LVN_GETINFOTIPW: Final = -158 +LVN_GETINFOTIP: Final = LVN_GETINFOTIPA +WC_TREEVIEWA: Final = "SysTreeView32" +WC_TREEVIEW: Final = WC_TREEVIEWA +TVS_HASBUTTONS: Final = 1 +TVS_HASLINES: Final = 2 +TVS_LINESATROOT: Final = 4 +TVS_EDITLABELS: Final = 8 +TVS_DISABLEDRAGDROP: Final = 16 +TVS_SHOWSELALWAYS: Final = 32 +TVS_RTLREADING: Final = 64 +TVS_NOTOOLTIPS: Final = 128 +TVS_CHECKBOXES: Final = 256 +TVS_TRACKSELECT: Final = 512 +TVS_SINGLEEXPAND: Final = 1024 +TVS_INFOTIP: Final = 2048 +TVS_FULLROWSELECT: Final = 4096 +TVS_NOSCROLL: Final = 8192 +TVS_NONEVENHEIGHT: Final = 16384 +TVIF_TEXT: Final = 1 +TVIF_IMAGE: Final = 2 +TVIF_PARAM: Final = 4 +TVIF_STATE: Final = 8 +TVIF_HANDLE: Final = 16 +TVIF_SELECTEDIMAGE: Final = 32 +TVIF_CHILDREN: Final = 64 +TVIF_INTEGRAL: Final = 128 +TVIS_SELECTED: Final = 2 +TVIS_CUT: Final = 4 +TVIS_DROPHILITED: Final = 8 +TVIS_BOLD: Final = 16 +TVIS_EXPANDED: Final = 32 +TVIS_EXPANDEDONCE: Final = 64 +TVIS_EXPANDPARTIAL: Final = 128 +TVIS_OVERLAYMASK: Final = 3840 +TVIS_STATEIMAGEMASK: Final = 61440 +TVIS_USERMASK: Final = 61440 +I_CHILDRENCALLBACK: Final = -1 +TVI_ROOT: Final = -65536 +TVI_FIRST: Final = -65535 +TVI_LAST: Final = -65534 +TVI_SORT: Final = -65533 +TVM_INSERTITEMA: Final = 4352 +TVM_INSERTITEMW: Final = 4402 +TVM_INSERTITEM: Final = TVM_INSERTITEMA +TVM_DELETEITEM: Final = 4353 +TVM_EXPAND: Final = 4354 +TVE_COLLAPSE: Final = 1 +TVE_EXPAND: Final = 2 +TVE_TOGGLE: Final = 3 +TVE_EXPANDPARTIAL: Final = 16384 +TVE_COLLAPSERESET: Final = 32768 +TVM_GETITEMRECT: Final = 4356 +TVM_GETCOUNT: Final = 4357 +TVM_GETINDENT: Final = 4358 +TVM_SETINDENT: Final = 4359 +TVM_GETIMAGELIST: Final = 4360 +TVSIL_NORMAL: Final = 0 +TVSIL_STATE: Final = 2 +TVM_SETIMAGELIST: Final = 4361 +TVM_GETNEXTITEM: Final = 4362 +TVGN_ROOT: Final = 0 +TVGN_NEXT: Final = 1 +TVGN_PREVIOUS: Final = 2 +TVGN_PARENT: Final = 3 +TVGN_CHILD: Final = 4 +TVGN_FIRSTVISIBLE: Final = 5 +TVGN_NEXTVISIBLE: Final = 6 +TVGN_PREVIOUSVISIBLE: Final = 7 +TVGN_DROPHILITE: Final = 8 +TVGN_CARET: Final = 9 +TVGN_LASTVISIBLE: Final = 10 +TVM_SELECTITEM: Final = 4363 +TVM_GETITEMA: Final = 4364 +TVM_GETITEMW: Final = 4414 +TVM_GETITEM: Final = TVM_GETITEMA +TVM_SETITEMA: Final = 4365 +TVM_SETITEMW: Final = 4415 +TVM_SETITEM: Final = TVM_SETITEMA +TVM_EDITLABELA: Final = 4366 +TVM_EDITLABELW: Final = 4417 +TVM_EDITLABEL: Final = TVM_EDITLABELA +TVM_GETEDITCONTROL: Final = 4367 +TVM_GETVISIBLECOUNT: Final = 4368 +TVM_HITTEST: Final = 4369 +TVHT_NOWHERE: Final = 1 +TVHT_ONITEMICON: Final = 2 +TVHT_ONITEMLABEL: Final = 4 +TVHT_ONITEMINDENT: Final = 8 +TVHT_ONITEMBUTTON: Final = 16 +TVHT_ONITEMRIGHT: Final = 32 +TVHT_ONITEMSTATEICON: Final = 64 +TVHT_ABOVE: Final = 256 +TVHT_BELOW: Final = 512 +TVHT_TORIGHT: Final = 1024 +TVHT_TOLEFT: Final = 2048 +TVHT_ONITEM: Final = 70 +TVM_CREATEDRAGIMAGE: Final = 4370 +TVM_SORTCHILDREN: Final = 4371 +TVM_ENSUREVISIBLE: Final = 4372 +TVM_SORTCHILDRENCB: Final = 4373 +TVM_ENDEDITLABELNOW: Final = 4374 +TVM_GETISEARCHSTRINGA: Final = 4375 +TVM_GETISEARCHSTRINGW: Final = 4416 +TVM_GETISEARCHSTRING: Final = TVM_GETISEARCHSTRINGA +TVM_SETTOOLTIPS: Final = 4376 +TVM_GETTOOLTIPS: Final = 4377 +TVM_SETINSERTMARK: Final = 4378 +TVM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +TVM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +TVM_SETITEMHEIGHT: Final = 4379 +TVM_GETITEMHEIGHT: Final = 4380 +TVM_SETBKCOLOR: Final = 4381 +TVM_SETTEXTCOLOR: Final = 4382 +TVM_GETBKCOLOR: Final = 4383 +TVM_GETTEXTCOLOR: Final = 4384 +TVM_SETSCROLLTIME: Final = 4385 +TVM_GETSCROLLTIME: Final = 4386 +TVM_SETINSERTMARKCOLOR: Final = 4389 +TVM_GETINSERTMARKCOLOR: Final = 4390 +TVN_SELCHANGINGA: Final = -401 +TVN_SELCHANGINGW: Final = -450 +TVN_SELCHANGEDA: Final = -402 +TVN_SELCHANGEDW: Final = -451 +TVC_UNKNOWN: Final = 0 +TVC_BYMOUSE: Final = 1 +TVC_BYKEYBOARD: Final = 2 +TVN_GETDISPINFOA: Final = -403 +TVN_GETDISPINFOW: Final = -452 +TVN_SETDISPINFOA: Final = -404 +TVN_SETDISPINFOW: Final = -453 +TVIF_DI_SETITEM: Final = 4096 +TVN_ITEMEXPANDINGA: Final = -405 +TVN_ITEMEXPANDINGW: Final = -454 +TVN_ITEMEXPANDEDA: Final = -406 +TVN_ITEMEXPANDEDW: Final = -455 +TVN_BEGINDRAGA: Final = -407 +TVN_BEGINDRAGW: Final = -456 +TVN_BEGINRDRAGA: Final = -408 +TVN_BEGINRDRAGW: Final = -457 +TVN_DELETEITEMA: Final = -409 +TVN_DELETEITEMW: Final = -458 +TVN_BEGINLABELEDITA: Final = -410 +TVN_BEGINLABELEDITW: Final = -459 +TVN_ENDLABELEDITA: Final = -411 +TVN_ENDLABELEDITW: Final = -460 +TVN_KEYDOWN: Final = -412 +TVN_GETINFOTIPA: Final = -413 +TVN_GETINFOTIPW: Final = -414 +TVN_SINGLEEXPAND: Final = -415 +TVN_SELCHANGING: Final = TVN_SELCHANGINGA +TVN_SELCHANGED: Final = TVN_SELCHANGEDA +TVN_GETDISPINFO: Final = TVN_GETDISPINFOA +TVN_SETDISPINFO: Final = TVN_SETDISPINFOA +TVN_ITEMEXPANDING: Final = TVN_ITEMEXPANDINGA +TVN_ITEMEXPANDED: Final = TVN_ITEMEXPANDEDA +TVN_BEGINDRAG: Final = TVN_BEGINDRAGA +TVN_BEGINRDRAG: Final = TVN_BEGINRDRAGA +TVN_DELETEITEM: Final = TVN_DELETEITEMA +TVN_BEGINLABELEDIT: Final = TVN_BEGINLABELEDITA +TVN_ENDLABELEDIT: Final = TVN_ENDLABELEDITA +TVN_GETINFOTIP: Final = TVN_GETINFOTIPA +TVCDRF_NOIMAGES: Final = 65536 +WC_COMBOBOXEXA: Final = "ComboBoxEx32" +WC_COMBOBOXEX: Final = WC_COMBOBOXEXA +CBEIF_TEXT: Final = 1 +CBEIF_IMAGE: Final = 2 +CBEIF_SELECTEDIMAGE: Final = 4 +CBEIF_OVERLAY: Final = 8 +CBEIF_INDENT: Final = 16 +CBEIF_LPARAM: Final = 32 +CBEIF_DI_SETITEM: Final = 268435456 +CBEM_INSERTITEMA: Final = 1025 +CBEM_SETIMAGELIST: Final = 1026 +CBEM_GETIMAGELIST: Final = 1027 +CBEM_GETITEMA: Final = 1028 +CBEM_SETITEMA: Final = 1029 +CBEM_GETCOMBOCONTROL: Final = 1030 +CBEM_GETEDITCONTROL: Final = 1031 +CBEM_SETEXSTYLE: Final = 1032 +CBEM_SETEXTENDEDSTYLE: Final = 1038 +CBEM_GETEXSTYLE: Final = 1033 +CBEM_GETEXTENDEDSTYLE: Final = 1033 +CBEM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +CBEM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +CBEM_HASEDITCHANGED: Final = 1034 +CBEM_INSERTITEMW: Final = 1035 +CBEM_SETITEMW: Final = 1036 +CBEM_GETITEMW: Final = 1037 +CBEM_INSERTITEM: Final = CBEM_INSERTITEMA +CBEM_SETITEM: Final = CBEM_SETITEMA +CBEM_GETITEM: Final = CBEM_GETITEMA +CBES_EX_NOEDITIMAGE: Final = 1 +CBES_EX_NOEDITIMAGEINDENT: Final = 2 +CBES_EX_PATHWORDBREAKPROC: Final = 4 +CBES_EX_NOSIZELIMIT: Final = 8 +CBES_EX_CASESENSITIVE: Final = 16 +CBEN_GETDISPINFO: Final = -800 +CBEN_GETDISPINFOA: Final = -800 +CBEN_INSERTITEM: Final = -801 +CBEN_DELETEITEM: Final = -802 +CBEN_BEGINEDIT: Final = -804 +CBEN_ENDEDITA: Final = -805 +CBEN_ENDEDITW: Final = -806 +CBEN_GETDISPINFOW: Final = -807 +CBEN_DRAGBEGINA: Final = -808 +CBEN_DRAGBEGINW: Final = -809 +CBEN_DRAGBEGIN: Final = CBEN_DRAGBEGINA +CBEN_ENDEDIT: Final = CBEN_ENDEDITA +CBENF_KILLFOCUS: Final = 1 +CBENF_RETURN: Final = 2 +CBENF_ESCAPE: Final = 3 +CBENF_DROPDOWN: Final = 4 +CBEMAXSTRLEN: Final = 260 +WC_TABCONTROLA: Final = "SysTabControl32" +WC_TABCONTROL: Final = WC_TABCONTROLA +TCS_SCROLLOPPOSITE: Final = 1 +TCS_BOTTOM: Final = 2 +TCS_RIGHT: Final = 2 +TCS_MULTISELECT: Final = 4 +TCS_FLATBUTTONS: Final = 8 +TCS_FORCEICONLEFT: Final = 16 +TCS_FORCELABELLEFT: Final = 32 +TCS_HOTTRACK: Final = 64 +TCS_VERTICAL: Final = 128 +TCS_TABS: Final = 0 +TCS_BUTTONS: Final = 256 +TCS_SINGLELINE: Final = 0 +TCS_MULTILINE: Final = 512 +TCS_RIGHTJUSTIFY: Final = 0 +TCS_FIXEDWIDTH: Final = 1024 +TCS_RAGGEDRIGHT: Final = 2048 +TCS_FOCUSONBUTTONDOWN: Final = 4096 +TCS_OWNERDRAWFIXED: Final = 8192 +TCS_TOOLTIPS: Final = 16384 +TCS_FOCUSNEVER: Final = 32768 +TCS_EX_FLATSEPARATORS: Final = 1 +TCS_EX_REGISTERDROP: Final = 2 +TCM_GETIMAGELIST: Final = 4866 +TCM_SETIMAGELIST: Final = 4867 +TCM_GETITEMCOUNT: Final = 4868 +TCIF_TEXT: Final = 1 +TCIF_IMAGE: Final = 2 +TCIF_RTLREADING: Final = 4 +TCIF_PARAM: Final = 8 +TCIF_STATE: Final = 16 +TCIS_BUTTONPRESSED: Final = 1 +TCIS_HIGHLIGHTED: Final = 2 +TCM_GETITEMA: Final = 4869 +TCM_GETITEMW: Final = 4924 +TCM_GETITEM: Final = TCM_GETITEMA +TCM_SETITEMA: Final = 4870 +TCM_SETITEMW: Final = 4925 +TCM_SETITEM: Final = TCM_SETITEMA +TCM_INSERTITEMA: Final = 4871 +TCM_INSERTITEMW: Final = 4926 +TCM_INSERTITEM: Final = TCM_INSERTITEMA +TCM_DELETEITEM: Final = 4872 +TCM_DELETEALLITEMS: Final = 4873 +TCM_GETITEMRECT: Final = 4874 +TCM_GETCURSEL: Final = 4875 +TCM_SETCURSEL: Final = 4876 +TCHT_NOWHERE: Final = 1 +TCHT_ONITEMICON: Final = 2 +TCHT_ONITEMLABEL: Final = 4 +TCHT_ONITEM: Final = 6 +TCM_HITTEST: Final = 4877 +TCM_SETITEMEXTRA: Final = 4878 +TCM_ADJUSTRECT: Final = 4904 +TCM_SETITEMSIZE: Final = 4905 +TCM_REMOVEIMAGE: Final = 4906 +TCM_SETPADDING: Final = 4907 +TCM_GETROWCOUNT: Final = 4908 +TCM_GETTOOLTIPS: Final = 4909 +TCM_SETTOOLTIPS: Final = 4910 +TCM_GETCURFOCUS: Final = 4911 +TCM_SETCURFOCUS: Final = 4912 +TCM_SETMINTABWIDTH: Final = 4913 +TCM_DESELECTALL: Final = 4914 +TCM_HIGHLIGHTITEM: Final = 4915 +TCM_SETEXTENDEDSTYLE: Final = 4916 +TCM_GETEXTENDEDSTYLE: Final = 4917 +TCM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +TCM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +TCN_KEYDOWN: Final = -550 +ANIMATE_CLASSA: Final = "SysAnimate32" +ANIMATE_CLASS: Final = ANIMATE_CLASSA +ACS_CENTER: Final = 1 +ACS_TRANSPARENT: Final = 2 +ACS_AUTOPLAY: Final = 4 +ACS_TIMER: Final = 8 +ACM_OPENA: Final = 1124 +ACM_OPENW: Final = 1127 +ACM_OPEN: Final = ACM_OPENA +ACM_PLAY: Final = 1125 +ACM_STOP: Final = 1126 +ACN_START: Final = 1 +ACN_STOP: Final = 2 +MONTHCAL_CLASSA: Final = "SysMonthCal32" +MONTHCAL_CLASS: Final = MONTHCAL_CLASSA +MCM_FIRST: Final = 4096 +MCM_GETCURSEL: Final = 4097 +MCM_SETCURSEL: Final = 4098 +MCM_GETMAXSELCOUNT: Final = 4099 +MCM_SETMAXSELCOUNT: Final = 4100 +MCM_GETSELRANGE: Final = 4101 +MCM_SETSELRANGE: Final = 4102 +MCM_GETMONTHRANGE: Final = 4103 +MCM_SETDAYSTATE: Final = 4104 +MCM_GETMINREQRECT: Final = 4105 +MCM_SETCOLOR: Final = 4106 +MCM_GETCOLOR: Final = 4107 +MCSC_BACKGROUND: Final = 0 +MCSC_TEXT: Final = 1 +MCSC_TITLEBK: Final = 2 +MCSC_TITLETEXT: Final = 3 +MCSC_MONTHBK: Final = 4 +MCSC_TRAILINGTEXT: Final = 5 +MCM_SETTODAY: Final = 4108 +MCM_GETTODAY: Final = 4109 +MCM_HITTEST: Final = 4110 +MCHT_TITLE: Final = 65536 +MCHT_CALENDAR: Final = 131072 +MCHT_TODAYLINK: Final = 196608 +MCHT_NEXT: Final = 16777216 +MCHT_PREV: Final = 33554432 +MCHT_NOWHERE: Final = 0 +MCHT_TITLEBK: Final = MCHT_TITLE +MCHT_TITLEMONTH: Final = 65537 +MCHT_TITLEYEAR: Final = 65538 +MCHT_TITLEBTNNEXT: Final = 16842755 +MCHT_TITLEBTNPREV: Final = 33619971 +MCHT_CALENDARBK: Final = MCHT_CALENDAR +MCHT_CALENDARDATE: Final = 131073 +MCHT_CALENDARDATENEXT: Final = 16908289 +MCHT_CALENDARDATEPREV: Final = 33685505 +MCHT_CALENDARDAY: Final = 131074 +MCHT_CALENDARWEEKNUM: Final = 131075 +MCM_SETFIRSTDAYOFWEEK: Final = 4111 +MCM_GETFIRSTDAYOFWEEK: Final = 4112 +MCM_GETRANGE: Final = 4113 +MCM_SETRANGE: Final = 4114 +MCM_GETMONTHDELTA: Final = 4115 +MCM_SETMONTHDELTA: Final = 4116 +MCM_GETMAXTODAYWIDTH: Final = 4117 +MCM_SETUNICODEFORMAT: Final = CCM_SETUNICODEFORMAT +MCM_GETUNICODEFORMAT: Final = CCM_GETUNICODEFORMAT +MCN_SELCHANGE: Final = -749 +MCN_GETDAYSTATE: Final = -747 +MCN_SELECT: Final = -746 +MCS_DAYSTATE: Final = 1 +MCS_MULTISELECT: Final = 2 +MCS_WEEKNUMBERS: Final = 4 +MCS_NOTODAYCIRCLE: Final = 8 +MCS_NOTODAY: Final = 8 +GMR_VISIBLE: Final = 0 +GMR_DAYSTATE: Final = 1 +DATETIMEPICK_CLASSA: Final = "SysDateTimePick32" +DATETIMEPICK_CLASS: Final = DATETIMEPICK_CLASSA +DTM_FIRST: Final = 4096 +DTM_GETSYSTEMTIME: Final = 4097 +DTM_SETSYSTEMTIME: Final = 4098 +DTM_GETRANGE: Final = 4099 +DTM_SETRANGE: Final = 4100 +DTM_SETFORMATA: Final = 4101 +DTM_SETFORMATW: Final = 4146 +DTM_SETFORMAT: Final = DTM_SETFORMATA +DTM_SETMCCOLOR: Final = 4102 +DTM_GETMCCOLOR: Final = 4103 +DTM_GETMONTHCAL: Final = 4104 +DTM_SETMCFONT: Final = 4105 +DTM_GETMCFONT: Final = 4106 +DTS_UPDOWN: Final = 1 +DTS_SHOWNONE: Final = 2 +DTS_SHORTDATEFORMAT: Final = 0 +DTS_LONGDATEFORMAT: Final = 4 +DTS_TIMEFORMAT: Final = 9 +DTS_APPCANPARSE: Final = 16 +DTS_RIGHTALIGN: Final = 32 +DTN_DATETIMECHANGE: Final = -759 +DTN_USERSTRINGA: Final = -758 +DTN_USERSTRINGW: Final = -745 +DTN_USERSTRING: Final = DTN_USERSTRINGW +DTN_WMKEYDOWNA: Final = -757 +DTN_WMKEYDOWNW: Final = -744 +DTN_WMKEYDOWN: Final = DTN_WMKEYDOWNA +DTN_FORMATA: Final = -756 +DTN_FORMATW: Final = -743 +DTN_FORMAT: Final = DTN_FORMATA +DTN_FORMATQUERYA: Final = -755 +DTN_FORMATQUERYW: Final = -742 +DTN_FORMATQUERY: Final = DTN_FORMATQUERYA +DTN_DROPDOWN: Final = -754 +DTN_CLOSEUP: Final = -753 +GDTR_MIN: Final = 1 +GDTR_MAX: Final = 2 +GDT_ERROR: Final = -1 +GDT_VALID: Final = 0 +GDT_NONE: Final = 1 +IPM_CLEARADDRESS: Final = 1124 +IPM_SETADDRESS: Final = 1125 +IPM_GETADDRESS: Final = 1126 +IPM_SETRANGE: Final = 1127 +IPM_SETFOCUS: Final = 1128 +IPM_ISBLANK: Final = 1129 +WC_IPADDRESSA: Final = "SysIPAddress32" +WC_IPADDRESS: Final = WC_IPADDRESSA +IPN_FIELDCHANGED: Final = -860 +WC_PAGESCROLLERA: Final = "SysPager" +WC_PAGESCROLLER: Final = WC_PAGESCROLLERA +PGS_VERT: Final = 0 +PGS_HORZ: Final = 1 +PGS_AUTOSCROLL: Final = 2 +PGS_DRAGNDROP: Final = 4 +PGF_INVISIBLE: Final = 0 +PGF_NORMAL: Final = 1 +PGF_GRAYED: Final = 2 +PGF_DEPRESSED: Final = 4 +PGF_HOT: Final = 8 +PGB_TOPORLEFT: Final = 0 +PGB_BOTTOMORRIGHT: Final = 1 +PGM_SETCHILD: Final = 5121 +PGM_RECALCSIZE: Final = 5122 +PGM_FORWARDMOUSE: Final = 5123 +PGM_SETBKCOLOR: Final = 5124 +PGM_GETBKCOLOR: Final = 5125 +PGM_SETBORDER: Final = 5126 +PGM_GETBORDER: Final = 5127 +PGM_SETPOS: Final = 5128 +PGM_GETPOS: Final = 5129 +PGM_SETBUTTONSIZE: Final = 5130 +PGM_GETBUTTONSIZE: Final = 5131 +PGM_GETBUTTONSTATE: Final = 5132 +PGM_GETDROPTARGET: Final = CCM_GETDROPTARGET +PGN_SCROLL: Final = -901 +PGF_SCROLLUP: Final = 1 +PGF_SCROLLDOWN: Final = 2 +PGF_SCROLLLEFT: Final = 4 +PGF_SCROLLRIGHT: Final = 8 +PGK_SHIFT: Final = 1 +PGK_CONTROL: Final = 2 +PGK_MENU: Final = 4 +PGN_CALCSIZE: Final = -902 +PGF_CALCWIDTH: Final = 1 +PGF_CALCHEIGHT: Final = 2 +WC_NATIVEFONTCTLA: Final = "NativeFontCtl" +WC_NATIVEFONTCTL: Final = WC_NATIVEFONTCTLA +NFS_EDIT: Final = 1 +NFS_STATIC: Final = 2 +NFS_LISTCOMBO: Final = 4 +NFS_BUTTON: Final = 8 +NFS_ALL: Final = 16 +WM_MOUSEHOVER: Final = 673 +WM_MOUSELEAVE: Final = 675 +TME_HOVER: Final = 1 +TME_LEAVE: Final = 2 +TME_QUERY: Final = 1073741824 +TME_CANCEL: Final = -2147483648 +HOVER_DEFAULT: Final = -1 +WSB_PROP_CYVSCROLL: Final = 0x00000001 +WSB_PROP_CXHSCROLL: Final = 0x00000002 +WSB_PROP_CYHSCROLL: Final = 0x00000004 +WSB_PROP_CXVSCROLL: Final = 0x00000008 +WSB_PROP_CXHTHUMB: Final = 0x00000010 +WSB_PROP_CYVTHUMB: Final = 0x00000020 +WSB_PROP_VBKGCOLOR: Final = 0x00000040 +WSB_PROP_HBKGCOLOR: Final = 0x00000080 +WSB_PROP_VSTYLE: Final = 0x00000100 +WSB_PROP_HSTYLE: Final = 0x00000200 +WSB_PROP_WINSTYLE: Final = 0x00000400 +WSB_PROP_PALETTE: Final = 0x00000800 +WSB_PROP_MASK: Final = 0x00000FFF +FSB_FLAT_MODE: Final = 2 +FSB_ENCARTA_MODE: Final = 1 +FSB_REGULAR_MODE: Final = 0 + +def INDEXTOOVERLAYMASK(i: int) -> int: ... +def INDEXTOSTATEIMAGEMASK(i: int) -> int: ... diff --git a/stubs/pywin32/win32/lib/mmsystem.pyi b/stubs/pywin32/win32/lib/mmsystem.pyi new file mode 100644 index 000000000000..6167cfd6eabd --- /dev/null +++ b/stubs/pywin32/win32/lib/mmsystem.pyi @@ -0,0 +1,858 @@ +from typing import Final + +MAXPNAMELEN: Final = 32 +MAXERRORLENGTH: Final = 256 +MAX_JOYSTICKOEMVXDNAME: Final = 260 +MM_MICROSOFT: Final = 1 +MM_MIDI_MAPPER: Final = 1 +MM_WAVE_MAPPER: Final = 2 +MM_SNDBLST_MIDIOUT: Final = 3 +MM_SNDBLST_MIDIIN: Final = 4 +MM_SNDBLST_SYNTH: Final = 5 +MM_SNDBLST_WAVEOUT: Final = 6 +MM_SNDBLST_WAVEIN: Final = 7 +MM_ADLIB: Final = 9 +MM_MPU401_MIDIOUT: Final = 10 +MM_MPU401_MIDIIN: Final = 11 +MM_PC_JOYSTICK: Final = 12 +TIME_MS: Final = 0x0001 +TIME_SAMPLES: Final = 0x0002 +TIME_BYTES: Final = 0x0004 +TIME_SMPTE: Final = 0x0008 +TIME_MIDI: Final = 0x0010 +TIME_TICKS: Final = 0x0020 +MM_JOY1MOVE: Final = 0x3A0 +MM_JOY2MOVE: Final = 0x3A1 +MM_JOY1ZMOVE: Final = 0x3A2 +MM_JOY2ZMOVE: Final = 0x3A3 +MM_JOY1BUTTONDOWN: Final = 0x3B5 +MM_JOY2BUTTONDOWN: Final = 0x3B6 +MM_JOY1BUTTONUP: Final = 0x3B7 +MM_JOY2BUTTONUP: Final = 0x3B8 +MM_MCINOTIFY: Final = 0x3B9 +MM_WOM_OPEN: Final = 0x3BB +MM_WOM_CLOSE: Final = 0x3BC +MM_WOM_DONE: Final = 0x3BD +MM_WIM_OPEN: Final = 0x3BE +MM_WIM_CLOSE: Final = 0x3BF +MM_WIM_DATA: Final = 0x3C0 +MM_MIM_OPEN: Final = 0x3C1 +MM_MIM_CLOSE: Final = 0x3C2 +MM_MIM_DATA: Final = 0x3C3 +MM_MIM_LONGDATA: Final = 0x3C4 +MM_MIM_ERROR: Final = 0x3C5 +MM_MIM_LONGERROR: Final = 0x3C6 +MM_MOM_OPEN: Final = 0x3C7 +MM_MOM_CLOSE: Final = 0x3C8 +MM_MOM_DONE: Final = 0x3C9 +MM_STREAM_OPEN: Final = 0x3D4 +MM_STREAM_CLOSE: Final = 0x3D5 +MM_STREAM_DONE: Final = 0x3D6 +MM_STREAM_ERROR: Final = 0x3D7 +MM_MOM_POSITIONCB: Final = 0x3CA +MM_MIM_MOREDATA: Final = 0x3CC +MM_MIXM_LINE_CHANGE: Final = 0x3D0 +MM_MIXM_CONTROL_CHANGE: Final = 0x3D1 +MMSYSERR_BASE: Final = 0 +WAVERR_BASE: Final = 32 +MIDIERR_BASE: Final = 64 +TIMERR_BASE: Final = 96 +JOYERR_BASE: Final = 160 +MCIERR_BASE: Final = 256 +MIXERR_BASE: Final = 1024 +MCI_STRING_OFFSET: Final = 512 +MCI_VD_OFFSET: Final = 1024 +MCI_CD_OFFSET: Final = 1088 +MCI_WAVE_OFFSET: Final = 1152 +MCI_SEQ_OFFSET: Final = 1216 +MMSYSERR_NOERROR: Final = 0 +MMSYSERR_ERROR: Final = 1 +MMSYSERR_BADDEVICEID: Final = 2 +MMSYSERR_NOTENABLED: Final = 3 +MMSYSERR_ALLOCATED: Final = 4 +MMSYSERR_INVALHANDLE: Final = 5 +MMSYSERR_NODRIVER: Final = 6 +MMSYSERR_NOMEM: Final = 7 +MMSYSERR_NOTSUPPORTED: Final = 8 +MMSYSERR_BADERRNUM: Final = 9 +MMSYSERR_INVALFLAG: Final = 10 +MMSYSERR_INVALPARAM: Final = 11 +MMSYSERR_HANDLEBUSY: Final = 12 +MMSYSERR_INVALIDALIAS: Final = 13 +MMSYSERR_BADDB: Final = 14 +MMSYSERR_KEYNOTFOUND: Final = 15 +MMSYSERR_READERROR: Final = 16 +MMSYSERR_WRITEERROR: Final = 17 +MMSYSERR_DELETEERROR: Final = 18 +MMSYSERR_VALNOTFOUND: Final = 19 +MMSYSERR_NODRIVERCB: Final = 20 +MMSYSERR_LASTERROR: Final = 20 +DRV_LOAD: Final = 0x0001 +DRV_ENABLE: Final = 0x0002 +DRV_OPEN: Final = 0x0003 +DRV_CLOSE: Final = 0x0004 +DRV_DISABLE: Final = 0x0005 +DRV_FREE: Final = 0x0006 +DRV_CONFIGURE: Final = 0x0007 +DRV_QUERYCONFIGURE: Final = 0x0008 +DRV_INSTALL: Final = 0x0009 +DRV_REMOVE: Final = 0x000A +DRV_EXITSESSION: Final = 0x000B +DRV_POWER: Final = 0x000F +DRV_RESERVED: Final = 0x0800 +DRV_USER: Final = 0x4000 +DRVCNF_CANCEL: Final = 0x0000 +DRVCNF_OK: Final = 0x0001 +DRVCNF_RESTART: Final = 0x0002 +DRV_CANCEL: Final = DRVCNF_CANCEL +DRV_OK: Final = DRVCNF_OK +DRV_RESTART: Final = DRVCNF_RESTART +DRV_MCI_FIRST: Final = DRV_RESERVED +DRV_MCI_LAST: Final = 0x17FF +CALLBACK_TYPEMASK: Final = 0x00070000 +CALLBACK_NULL: Final = 0x00000000 +CALLBACK_WINDOW: Final = 0x00010000 +CALLBACK_TASK: Final = 0x00020000 +CALLBACK_FUNCTION: Final = 0x00030000 +CALLBACK_THREAD: Final = CALLBACK_TASK +CALLBACK_EVENT: Final = 0x00050000 +SND_SYNC: Final = 0x0000 +SND_ASYNC: Final = 0x0001 +SND_NODEFAULT: Final = 0x0002 +SND_MEMORY: Final = 0x0004 +SND_LOOP: Final = 0x0008 +SND_NOSTOP: Final = 0x0010 +SND_NOWAIT: Final = 0x00002000 +SND_ALIAS: Final = 0x00010000 +SND_ALIAS_ID: Final = 0x00110000 +SND_FILENAME: Final = 0x00020000 +SND_RESOURCE: Final = 0x00040004 +SND_PURGE: Final = 0x0040 +SND_APPLICATION: Final = 0x0080 +SND_ALIAS_START: Final = 0 +WAVERR_BADFORMAT: Final = 32 +WAVERR_STILLPLAYING: Final = 33 +WAVERR_UNPREPARED: Final = 34 +WAVERR_SYNC: Final = 35 +WAVERR_LASTERROR: Final = 35 +WOM_OPEN: Final = MM_WOM_OPEN +WOM_CLOSE: Final = MM_WOM_CLOSE +WOM_DONE: Final = MM_WOM_DONE +WIM_OPEN: Final = MM_WIM_OPEN +WIM_CLOSE: Final = MM_WIM_CLOSE +WIM_DATA: Final = MM_WIM_DATA +WAVE_MAPPER: Final = -1 +WAVE_FORMAT_QUERY: Final = 0x0001 +WAVE_ALLOWSYNC: Final = 0x0002 +WAVE_MAPPED: Final = 0x0004 +WAVE_FORMAT_DIRECT: Final = 0x0008 +WAVE_FORMAT_DIRECT_QUERY: Final = 0x0009 +WHDR_DONE: Final = 0x00000001 +WHDR_PREPARED: Final = 0x00000002 +WHDR_BEGINLOOP: Final = 0x00000004 +WHDR_ENDLOOP: Final = 0x00000008 +WHDR_INQUEUE: Final = 0x00000010 +WAVECAPS_PITCH: Final = 0x0001 +WAVECAPS_PLAYBACKRATE: Final = 0x0002 +WAVECAPS_VOLUME: Final = 0x0004 +WAVECAPS_LRVOLUME: Final = 0x0008 +WAVECAPS_SYNC: Final = 0x0010 +WAVECAPS_SAMPLEACCURATE: Final = 0x0020 +WAVECAPS_DIRECTSOUND: Final = 0x0040 +WAVE_INVALIDFORMAT: Final = 0x00000000 +WAVE_FORMAT_1M08: Final = 0x00000001 +WAVE_FORMAT_1S08: Final = 0x00000002 +WAVE_FORMAT_1M16: Final = 0x00000004 +WAVE_FORMAT_1S16: Final = 0x00000008 +WAVE_FORMAT_2M08: Final = 0x00000010 +WAVE_FORMAT_2S08: Final = 0x00000020 +WAVE_FORMAT_2M16: Final = 0x00000040 +WAVE_FORMAT_2S16: Final = 0x00000080 +WAVE_FORMAT_4M08: Final = 0x00000100 +WAVE_FORMAT_4S08: Final = 0x00000200 +WAVE_FORMAT_4M16: Final = 0x00000400 +WAVE_FORMAT_4S16: Final = 0x00000800 +WAVE_FORMAT_PCM: Final = 1 +WAVE_FORMAT_IEEE_FLOAT: Final = 3 +MIDIERR_UNPREPARED: Final = 64 +MIDIERR_STILLPLAYING: Final = 65 +MIDIERR_NOMAP: Final = 66 +MIDIERR_NOTREADY: Final = 67 +MIDIERR_NODEVICE: Final = 68 +MIDIERR_INVALIDSETUP: Final = 69 +MIDIERR_BADOPENMODE: Final = 70 +MIDIERR_DONT_CONTINUE: Final = 71 +MIDIERR_LASTERROR: Final = 71 +MIDIPATCHSIZE: Final = 128 +MIM_OPEN: Final = MM_MIM_OPEN +MIM_CLOSE: Final = MM_MIM_CLOSE +MIM_DATA: Final = MM_MIM_DATA +MIM_LONGDATA: Final = MM_MIM_LONGDATA +MIM_ERROR: Final = MM_MIM_ERROR +MIM_LONGERROR: Final = MM_MIM_LONGERROR +MOM_OPEN: Final = MM_MOM_OPEN +MOM_CLOSE: Final = MM_MOM_CLOSE +MOM_DONE: Final = MM_MOM_DONE +MIM_MOREDATA: Final = MM_MIM_MOREDATA +MOM_POSITIONCB: Final = MM_MOM_POSITIONCB +MIDI_IO_STATUS: Final = 0x00000020 +MIDI_CACHE_ALL: Final = 1 +MIDI_CACHE_BESTFIT: Final = 2 +MIDI_CACHE_QUERY: Final = 3 +MIDI_UNCACHE: Final = 4 +MOD_MIDIPORT: Final = 1 +MOD_SYNTH: Final = 2 +MOD_SQSYNTH: Final = 3 +MOD_FMSYNTH: Final = 4 +MOD_MAPPER: Final = 5 +MIDICAPS_VOLUME: Final = 0x0001 +MIDICAPS_LRVOLUME: Final = 0x0002 +MIDICAPS_CACHE: Final = 0x0004 +MIDICAPS_STREAM: Final = 0x0008 +MHDR_DONE: Final = 0x00000001 +MHDR_PREPARED: Final = 0x00000002 +MHDR_INQUEUE: Final = 0x00000004 +MHDR_ISSTRM: Final = 0x00000008 +MEVT_F_SHORT: Final = 0x00000000 +MEVT_F_LONG: Final = -0x80000000 +MEVT_F_CALLBACK: Final = 0x40000000 + +def MEVT_EVENTTYPE(x: int) -> int: ... +def MEVT_EVENTPARM(x: int) -> int: ... + +MIDISTRM_ERROR: Final = -2 +MIDIPROP_SET: Final = -0x80000000 +MIDIPROP_GET: Final = 0x40000000 +MIDIPROP_TIMEDIV: Final = 0x00000001 +MIDIPROP_TEMPO: Final = 0x00000002 +AUXCAPS_CDAUDIO: Final = 1 +AUXCAPS_AUXIN: Final = 2 +AUXCAPS_VOLUME: Final = 0x0001 +AUXCAPS_LRVOLUME: Final = 0x0002 +MIXER_SHORT_NAME_CHARS: Final = 16 +MIXER_LONG_NAME_CHARS: Final = 64 +MIXERR_INVALLINE: Final = 1024 +MIXERR_INVALCONTROL: Final = 1025 +MIXERR_INVALVALUE: Final = 1026 +MIXERR_LASTERROR: Final = 1026 +MIXER_OBJECTF_HANDLE: Final = -0x80000000 +MIXER_OBJECTF_MIXER: Final = 0x00000000 +MIXER_OBJECTF_HMIXER: Final = -0x80000000 +MIXER_OBJECTF_WAVEOUT: Final = 0x10000000 +MIXER_OBJECTF_HWAVEOUT: Final = -0x70000000 +MIXER_OBJECTF_WAVEIN: Final = 0x20000000 +MIXER_OBJECTF_HWAVEIN: Final = -0x60000000 +MIXER_OBJECTF_MIDIOUT: Final = 0x30000000 +MIXER_OBJECTF_HMIDIOUT: Final = -0x50000000 +MIXER_OBJECTF_MIDIIN: Final = 0x40000000 +MIXER_OBJECTF_HMIDIIN: Final = -0x40000000 +MIXER_OBJECTF_AUX: Final = 0x50000000 +MIXERLINE_LINEF_ACTIVE: Final = 0x00000001 +MIXERLINE_LINEF_DISCONNECTED: Final = 0x00008000 +MIXERLINE_LINEF_SOURCE: Final = -0x80000000 +MIXERLINE_COMPONENTTYPE_DST_FIRST: Final = 0x00000000 +MIXERLINE_COMPONENTTYPE_DST_UNDEFINED: Final = 0x00000000 +MIXERLINE_COMPONENTTYPE_DST_DIGITAL: Final = 0x00000001 +MIXERLINE_COMPONENTTYPE_DST_LINE: Final = 0x00000002 +MIXERLINE_COMPONENTTYPE_DST_MONITOR: Final = 0x00000003 +MIXERLINE_COMPONENTTYPE_DST_SPEAKERS: Final = 0x00000004 +MIXERLINE_COMPONENTTYPE_DST_HEADPHONES: Final = 0x00000005 +MIXERLINE_COMPONENTTYPE_DST_TELEPHONE: Final = 0x00000006 +MIXERLINE_COMPONENTTYPE_DST_WAVEIN: Final = 0x00000007 +MIXERLINE_COMPONENTTYPE_DST_VOICEIN: Final = 0x00000008 +MIXERLINE_COMPONENTTYPE_DST_LAST: Final = 0x00000008 +MIXERLINE_COMPONENTTYPE_SRC_FIRST: Final = 0x00001000 +MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED: Final = 0x00001000 +MIXERLINE_COMPONENTTYPE_SRC_DIGITAL: Final = 0x00001001 +MIXERLINE_COMPONENTTYPE_SRC_LINE: Final = 0x00001002 +MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE: Final = 0x00001003 +MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER: Final = 0x00001004 +MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC: Final = 0x00001005 +MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE: Final = 0x00001006 +MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER: Final = 0x00001007 +MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT: Final = 0x00001008 +MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY: Final = 0x00001009 +MIXERLINE_COMPONENTTYPE_SRC_ANALOG: Final = 0x0000100A +MIXERLINE_COMPONENTTYPE_SRC_LAST: Final = 0x0000100A +MIXERLINE_TARGETTYPE_UNDEFINED: Final = 0 +MIXERLINE_TARGETTYPE_WAVEOUT: Final = 1 +MIXERLINE_TARGETTYPE_WAVEIN: Final = 2 +MIXERLINE_TARGETTYPE_MIDIOUT: Final = 3 +MIXERLINE_TARGETTYPE_MIDIIN: Final = 4 +MIXERLINE_TARGETTYPE_AUX: Final = 5 +MIXER_GETLINEINFOF_DESTINATION: Final = 0x00000000 +MIXER_GETLINEINFOF_SOURCE: Final = 0x00000001 +MIXER_GETLINEINFOF_LINEID: Final = 0x00000002 +MIXER_GETLINEINFOF_COMPONENTTYPE: Final = 0x00000003 +MIXER_GETLINEINFOF_TARGETTYPE: Final = 0x00000004 +MIXER_GETLINEINFOF_QUERYMASK: Final = 0x0000000F +MIXERCONTROL_CONTROLF_UNIFORM: Final = 0x00000001 +MIXERCONTROL_CONTROLF_MULTIPLE: Final = 0x00000002 +MIXERCONTROL_CONTROLF_DISABLED: Final = -0x80000000 +MIXERCONTROL_CT_CLASS_MASK: Final = -0x10000000 +MIXERCONTROL_CT_CLASS_CUSTOM: Final = 0x00000000 +MIXERCONTROL_CT_CLASS_METER: Final = 0x10000000 +MIXERCONTROL_CT_CLASS_SWITCH: Final = 0x20000000 +MIXERCONTROL_CT_CLASS_NUMBER: Final = 0x30000000 +MIXERCONTROL_CT_CLASS_SLIDER: Final = 0x40000000 +MIXERCONTROL_CT_CLASS_FADER: Final = 0x50000000 +MIXERCONTROL_CT_CLASS_TIME: Final = 0x60000000 +MIXERCONTROL_CT_CLASS_LIST: Final = 0x70000000 +MIXERCONTROL_CT_SUBCLASS_MASK: Final = 0x0F000000 +MIXERCONTROL_CT_SC_SWITCH_BOOLEAN: Final = 0x00000000 +MIXERCONTROL_CT_SC_SWITCH_BUTTON: Final = 0x01000000 +MIXERCONTROL_CT_SC_METER_POLLED: Final = 0x00000000 +MIXERCONTROL_CT_SC_TIME_MICROSECS: Final = 0x00000000 +MIXERCONTROL_CT_SC_TIME_MILLISECS: Final = 0x01000000 +MIXERCONTROL_CT_SC_LIST_SINGLE: Final = 0x00000000 +MIXERCONTROL_CT_SC_LIST_MULTIPLE: Final = 0x01000000 +MIXERCONTROL_CT_UNITS_MASK: Final = 0x00FF0000 +MIXERCONTROL_CT_UNITS_CUSTOM: Final = 0x00000000 +MIXERCONTROL_CT_UNITS_BOOLEAN: Final = 0x00010000 +MIXERCONTROL_CT_UNITS_SIGNED: Final = 0x00020000 +MIXERCONTROL_CT_UNITS_UNSIGNED: Final = 0x00030000 +MIXERCONTROL_CT_UNITS_DECIBELS: Final = 0x00040000 +MIXERCONTROL_CT_UNITS_PERCENT: Final = 0x00050000 +MIXERCONTROL_CONTROLTYPE_CUSTOM: Final = 0x00000000 +MIXERCONTROL_CONTROLTYPE_BOOLEANMETER: Final = 0x10010000 +MIXERCONTROL_CONTROLTYPE_SIGNEDMETER: Final = 0x10020000 +MIXERCONTROL_CONTROLTYPE_PEAKMETER: Final = 0x10020001 +MIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER: Final = 0x10030000 +MIXERCONTROL_CONTROLTYPE_BOOLEAN: Final = 0x20010000 +MIXERCONTROL_CONTROLTYPE_ONOFF: Final = 0x20010001 +MIXERCONTROL_CONTROLTYPE_MUTE: Final = 0x20010002 +MIXERCONTROL_CONTROLTYPE_MONO: Final = 0x20010003 +MIXERCONTROL_CONTROLTYPE_LOUDNESS: Final = 0x20010004 +MIXERCONTROL_CONTROLTYPE_STEREOENH: Final = 0x20010005 +MIXERCONTROL_CONTROLTYPE_BUTTON: Final = 0x21010000 +MIXERCONTROL_CONTROLTYPE_DECIBELS: Final = 0x30040000 +MIXERCONTROL_CONTROLTYPE_SIGNED: Final = 0x30020000 +MIXERCONTROL_CONTROLTYPE_UNSIGNED: Final = 0x30030000 +MIXERCONTROL_CONTROLTYPE_PERCENT: Final = 0x30050000 +MIXERCONTROL_CONTROLTYPE_SLIDER: Final = 0x40020000 +MIXERCONTROL_CONTROLTYPE_PAN: Final = 0x40020001 +MIXERCONTROL_CONTROLTYPE_QSOUNDPAN: Final = 0x40020002 +MIXERCONTROL_CONTROLTYPE_FADER: Final = 0x50030000 +MIXERCONTROL_CONTROLTYPE_VOLUME: Final = 0x50030001 +MIXERCONTROL_CONTROLTYPE_BASS: Final = 0x50030002 +MIXERCONTROL_CONTROLTYPE_TREBLE: Final = 0x50030003 +MIXERCONTROL_CONTROLTYPE_EQUALIZER: Final = 0x50030004 +MIXERCONTROL_CONTROLTYPE_SINGLESELECT: Final = 0x70010000 +MIXERCONTROL_CONTROLTYPE_MUX: Final = 0x70010001 +MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT: Final = 0x71010000 +MIXERCONTROL_CONTROLTYPE_MIXER: Final = 0x71010001 +MIXERCONTROL_CONTROLTYPE_MICROTIME: Final = 0x60030000 +MIXERCONTROL_CONTROLTYPE_MILLITIME: Final = 0x61030000 +MIXER_GETLINECONTROLSF_ALL: Final = 0x00000000 +MIXER_GETLINECONTROLSF_ONEBYID: Final = 0x00000001 +MIXER_GETLINECONTROLSF_ONEBYTYPE: Final = 0x00000002 +MIXER_GETLINECONTROLSF_QUERYMASK: Final = 0x0000000F +MIXER_GETCONTROLDETAILSF_VALUE: Final = 0x00000000 +MIXER_GETCONTROLDETAILSF_LISTTEXT: Final = 0x00000001 +MIXER_GETCONTROLDETAILSF_QUERYMASK: Final = 0x0000000F +MIXER_SETCONTROLDETAILSF_VALUE: Final = 0x00000000 +MIXER_SETCONTROLDETAILSF_CUSTOM: Final = 0x00000001 +MIXER_SETCONTROLDETAILSF_QUERYMASK: Final = 0x0000000F +TIMERR_NOERROR: Final = 0 +TIMERR_NOCANDO: Final = 97 +TIMERR_STRUCT: Final = 129 +TIME_ONESHOT: Final = 0x0000 +TIME_PERIODIC: Final = 0x0001 +TIME_CALLBACK_FUNCTION: Final = 0x0000 +TIME_CALLBACK_EVENT_SET: Final = 0x0010 +TIME_CALLBACK_EVENT_PULSE: Final = 0x0020 +JOYERR_NOERROR: Final = 0 +JOYERR_PARMS: Final = 165 +JOYERR_NOCANDO: Final = 166 +JOYERR_UNPLUGGED: Final = 167 +JOY_BUTTON1: Final = 0x0001 +JOY_BUTTON2: Final = 0x0002 +JOY_BUTTON3: Final = 0x0004 +JOY_BUTTON4: Final = 0x0008 +JOY_BUTTON1CHG: Final = 0x0100 +JOY_BUTTON2CHG: Final = 0x0200 +JOY_BUTTON3CHG: Final = 0x0400 +JOY_BUTTON4CHG: Final = 0x0800 +JOY_BUTTON5: Final = 0x00000010 +JOY_BUTTON6: Final = 0x00000020 +JOY_BUTTON7: Final = 0x00000040 +JOY_BUTTON8: Final = 0x00000080 +JOY_BUTTON9: Final = 0x00000100 +JOY_BUTTON10: Final = 0x00000200 +JOY_BUTTON11: Final = 0x00000400 +JOY_BUTTON12: Final = 0x00000800 +JOY_BUTTON13: Final = 0x00001000 +JOY_BUTTON14: Final = 0x00002000 +JOY_BUTTON15: Final = 0x00004000 +JOY_BUTTON16: Final = 0x00008000 +JOY_BUTTON17: Final = 0x00010000 +JOY_BUTTON18: Final = 0x00020000 +JOY_BUTTON19: Final = 0x00040000 +JOY_BUTTON20: Final = 0x00080000 +JOY_BUTTON21: Final = 0x00100000 +JOY_BUTTON22: Final = 0x00200000 +JOY_BUTTON23: Final = 0x00400000 +JOY_BUTTON24: Final = 0x00800000 +JOY_BUTTON25: Final = 0x01000000 +JOY_BUTTON26: Final = 0x02000000 +JOY_BUTTON27: Final = 0x04000000 +JOY_BUTTON28: Final = 0x08000000 +JOY_BUTTON29: Final = 0x10000000 +JOY_BUTTON30: Final = 0x20000000 +JOY_BUTTON31: Final = 0x40000000 +JOY_BUTTON32: Final = -0x80000000 +JOY_POVFORWARD: Final = 0 +JOY_POVRIGHT: Final = 9000 +JOY_POVBACKWARD: Final = 18000 +JOY_POVLEFT: Final = 27000 +JOY_RETURNX: Final = 0x00000001 +JOY_RETURNY: Final = 0x00000002 +JOY_RETURNZ: Final = 0x00000004 +JOY_RETURNR: Final = 0x00000008 +JOY_RETURNU: Final = 0x00000010 +JOY_RETURNV: Final = 0x00000020 +JOY_RETURNPOV: Final = 0x00000040 +JOY_RETURNBUTTONS: Final = 0x00000080 +JOY_RETURNRAWDATA: Final = 0x00000100 +JOY_RETURNPOVCTS: Final = 0x00000200 +JOY_RETURNCENTERED: Final = 0x00000400 +JOY_USEDEADZONE: Final = 0x00000800 +JOY_RETURNALL: Final = 0x000000FF +JOY_CAL_READALWAYS: Final = 0x00010000 +JOY_CAL_READXYONLY: Final = 0x00020000 +JOY_CAL_READ3: Final = 0x00040000 +JOY_CAL_READ4: Final = 0x00080000 +JOY_CAL_READXONLY: Final = 0x00100000 +JOY_CAL_READYONLY: Final = 0x00200000 +JOY_CAL_READ5: Final = 0x00400000 +JOY_CAL_READ6: Final = 0x00800000 +JOY_CAL_READZONLY: Final = 0x01000000 +JOY_CAL_READRONLY: Final = 0x02000000 +JOY_CAL_READUONLY: Final = 0x04000000 +JOY_CAL_READVONLY: Final = 0x08000000 +JOYSTICKID1: Final = 0 +JOYSTICKID2: Final = 1 +JOYCAPS_HASZ: Final = 0x0001 +JOYCAPS_HASR: Final = 0x0002 +JOYCAPS_HASU: Final = 0x0004 +JOYCAPS_HASV: Final = 0x0008 +JOYCAPS_HASPOV: Final = 0x0010 +JOYCAPS_POV4DIR: Final = 0x0020 +JOYCAPS_POVCTS: Final = 0x0040 +MMIOERR_BASE: Final = 256 +MMIOERR_FILENOTFOUND: Final = 257 +MMIOERR_OUTOFMEMORY: Final = 258 +MMIOERR_CANNOTOPEN: Final = 259 +MMIOERR_CANNOTCLOSE: Final = 260 +MMIOERR_CANNOTREAD: Final = 261 +MMIOERR_CANNOTWRITE: Final = 262 +MMIOERR_CANNOTSEEK: Final = 263 +MMIOERR_CANNOTEXPAND: Final = 264 +MMIOERR_CHUNKNOTFOUND: Final = 265 +MMIOERR_UNBUFFERED: Final = 266 +MMIOERR_PATHNOTFOUND: Final = 267 +MMIOERR_ACCESSDENIED: Final = 268 +MMIOERR_SHARINGVIOLATION: Final = 269 +MMIOERR_NETWORKERROR: Final = 270 +MMIOERR_TOOMANYOPENFILES: Final = 271 +MMIOERR_INVALIDFILE: Final = 272 +CFSEPCHAR: Final = 43 +MMIO_RWMODE: Final = 0x00000003 +MMIO_SHAREMODE: Final = 0x00000070 +MMIO_CREATE: Final = 0x00001000 +MMIO_PARSE: Final = 0x00000100 +MMIO_DELETE: Final = 0x00000200 +MMIO_EXIST: Final = 0x00004000 +MMIO_ALLOCBUF: Final = 0x00010000 +MMIO_GETTEMP: Final = 0x00020000 +MMIO_DIRTY: Final = 0x10000000 +MMIO_READ: Final = 0x00000000 +MMIO_WRITE: Final = 0x00000001 +MMIO_READWRITE: Final = 0x00000002 +MMIO_COMPAT: Final = 0x00000000 +MMIO_EXCLUSIVE: Final = 0x00000010 +MMIO_DENYWRITE: Final = 0x00000020 +MMIO_DENYREAD: Final = 0x00000030 +MMIO_DENYNONE: Final = 0x00000040 +MMIO_FHOPEN: Final = 0x0010 +MMIO_EMPTYBUF: Final = 0x0010 +MMIO_TOUPPER: Final = 0x0010 +MMIO_INSTALLPROC: Final = 0x00010000 +MMIO_GLOBALPROC: Final = 0x10000000 +MMIO_REMOVEPROC: Final = 0x00020000 +MMIO_UNICODEPROC: Final = 0x01000000 +MMIO_FINDPROC: Final = 0x00040000 +MMIO_FINDCHUNK: Final = 0x0010 +MMIO_FINDRIFF: Final = 0x0020 +MMIO_FINDLIST: Final = 0x0040 +MMIO_CREATERIFF: Final = 0x0020 +MMIO_CREATELIST: Final = 0x0040 +MMIOM_READ: Final = MMIO_READ +MMIOM_WRITE: Final = MMIO_WRITE +MMIOM_SEEK: Final = 2 +MMIOM_OPEN: Final = 3 +MMIOM_CLOSE: Final = 4 +MMIOM_WRITEFLUSH: Final = 5 +MMIOM_RENAME: Final = 6 +MMIOM_USER: Final = 0x8000 +SEEK_SET: Final = 0 +SEEK_CUR: Final = 1 +SEEK_END: Final = 2 +MMIO_DEFAULTBUFFER: Final = 8192 +MCIERR_INVALID_DEVICE_ID: Final = 257 +MCIERR_UNRECOGNIZED_KEYWORD: Final = 259 +MCIERR_UNRECOGNIZED_COMMAND: Final = 261 +MCIERR_HARDWARE: Final = 262 +MCIERR_INVALID_DEVICE_NAME: Final = 263 +MCIERR_OUT_OF_MEMORY: Final = 264 +MCIERR_DEVICE_OPEN: Final = 265 +MCIERR_CANNOT_LOAD_DRIVER: Final = 266 +MCIERR_MISSING_COMMAND_STRING: Final = 267 +MCIERR_PARAM_OVERFLOW: Final = 268 +MCIERR_MISSING_STRING_ARGUMENT: Final = 269 +MCIERR_BAD_INTEGER: Final = 270 +MCIERR_PARSER_INTERNAL: Final = 271 +MCIERR_DRIVER_INTERNAL: Final = 272 +MCIERR_MISSING_PARAMETER: Final = 273 +MCIERR_UNSUPPORTED_FUNCTION: Final = 274 +MCIERR_FILE_NOT_FOUND: Final = 275 +MCIERR_DEVICE_NOT_READY: Final = 276 +MCIERR_INTERNAL: Final = 277 +MCIERR_DRIVER: Final = 278 +MCIERR_CANNOT_USE_ALL: Final = 279 +MCIERR_MULTIPLE: Final = 280 +MCIERR_EXTENSION_NOT_FOUND: Final = 281 +MCIERR_OUTOFRANGE: Final = 282 +MCIERR_FLAGS_NOT_COMPATIBLE: Final = 284 +MCIERR_FILE_NOT_SAVED: Final = 286 +MCIERR_DEVICE_TYPE_REQUIRED: Final = 287 +MCIERR_DEVICE_LOCKED: Final = 288 +MCIERR_DUPLICATE_ALIAS: Final = 289 +MCIERR_BAD_CONSTANT: Final = 290 +MCIERR_MUST_USE_SHAREABLE: Final = 291 +MCIERR_MISSING_DEVICE_NAME: Final = 292 +MCIERR_BAD_TIME_FORMAT: Final = 293 +MCIERR_NO_CLOSING_QUOTE: Final = 294 +MCIERR_DUPLICATE_FLAGS: Final = 295 +MCIERR_INVALID_FILE: Final = 296 +MCIERR_NULL_PARAMETER_BLOCK: Final = 297 +MCIERR_UNNAMED_RESOURCE: Final = 298 +MCIERR_NEW_REQUIRES_ALIAS: Final = 299 +MCIERR_NOTIFY_ON_AUTO_OPEN: Final = 300 +MCIERR_NO_ELEMENT_ALLOWED: Final = 301 +MCIERR_NONAPPLICABLE_FUNCTION: Final = 302 +MCIERR_ILLEGAL_FOR_AUTO_OPEN: Final = 303 +MCIERR_FILENAME_REQUIRED: Final = 304 +MCIERR_EXTRA_CHARACTERS: Final = 305 +MCIERR_DEVICE_NOT_INSTALLED: Final = 306 +MCIERR_GET_CD: Final = 307 +MCIERR_SET_CD: Final = 308 +MCIERR_SET_DRIVE: Final = 309 +MCIERR_DEVICE_LENGTH: Final = 310 +MCIERR_DEVICE_ORD_LENGTH: Final = 311 +MCIERR_NO_INTEGER: Final = 312 +MCIERR_WAVE_OUTPUTSINUSE: Final = 320 +MCIERR_WAVE_SETOUTPUTINUSE: Final = 321 +MCIERR_WAVE_INPUTSINUSE: Final = 322 +MCIERR_WAVE_SETINPUTINUSE: Final = 323 +MCIERR_WAVE_OUTPUTUNSPECIFIED: Final = 324 +MCIERR_WAVE_INPUTUNSPECIFIED: Final = 325 +MCIERR_WAVE_OUTPUTSUNSUITABLE: Final = 326 +MCIERR_WAVE_SETOUTPUTUNSUITABLE: Final = 327 +MCIERR_WAVE_INPUTSUNSUITABLE: Final = 328 +MCIERR_WAVE_SETINPUTUNSUITABLE: Final = 329 +MCIERR_SEQ_DIV_INCOMPATIBLE: Final = 336 +MCIERR_SEQ_PORT_INUSE: Final = 337 +MCIERR_SEQ_PORT_NONEXISTENT: Final = 338 +MCIERR_SEQ_PORT_MAPNODEVICE: Final = 339 +MCIERR_SEQ_PORT_MISCERROR: Final = 340 +MCIERR_SEQ_TIMER: Final = 341 +MCIERR_SEQ_PORTUNSPECIFIED: Final = 342 +MCIERR_SEQ_NOMIDIPRESENT: Final = 343 +MCIERR_NO_WINDOW: Final = 346 +MCIERR_CREATEWINDOW: Final = 347 +MCIERR_FILE_READ: Final = 348 +MCIERR_FILE_WRITE: Final = 349 +MCIERR_NO_IDENTITY: Final = 350 +MCIERR_CUSTOM_DRIVER_BASE: Final = 512 +MCI_FIRST: Final = DRV_MCI_FIRST +MCI_OPEN: Final = 0x0803 +MCI_CLOSE: Final = 0x0804 +MCI_ESCAPE: Final = 0x0805 +MCI_PLAY: Final = 0x0806 +MCI_SEEK: Final = 0x0807 +MCI_STOP: Final = 0x0808 +MCI_PAUSE: Final = 0x0809 +MCI_INFO: Final = 0x080A +MCI_GETDEVCAPS: Final = 0x080B +MCI_SPIN: Final = 0x080C +MCI_SET: Final = 0x080D +MCI_STEP: Final = 0x080E +MCI_RECORD: Final = 0x080F +MCI_SYSINFO: Final = 0x0810 +MCI_BREAK: Final = 0x0811 +MCI_SAVE: Final = 0x0813 +MCI_STATUS: Final = 0x0814 +MCI_CUE: Final = 0x0830 +MCI_REALIZE: Final = 0x0840 +MCI_WINDOW: Final = 0x0841 +MCI_PUT: Final = 0x0842 +MCI_WHERE: Final = 0x0843 +MCI_FREEZE: Final = 0x0844 +MCI_UNFREEZE: Final = 0x0845 +MCI_LOAD: Final = 0x0850 +MCI_CUT: Final = 0x0851 +MCI_COPY: Final = 0x0852 +MCI_PASTE: Final = 0x0853 +MCI_UPDATE: Final = 0x0854 +MCI_RESUME: Final = 0x0855 +MCI_DELETE: Final = 0x0856 +MCI_USER_MESSAGES: Final = 0x0C00 +MCI_LAST: Final = 0x0FFF +MCI_DEVTYPE_VCR: Final = 513 +MCI_DEVTYPE_VIDEODISC: Final = 514 +MCI_DEVTYPE_OVERLAY: Final = 515 +MCI_DEVTYPE_CD_AUDIO: Final = 516 +MCI_DEVTYPE_DAT: Final = 517 +MCI_DEVTYPE_SCANNER: Final = 518 +MCI_DEVTYPE_ANIMATION: Final = 519 +MCI_DEVTYPE_DIGITAL_VIDEO: Final = 520 +MCI_DEVTYPE_OTHER: Final = 521 +MCI_DEVTYPE_WAVEFORM_AUDIO: Final = 522 +MCI_DEVTYPE_SEQUENCER: Final = 523 +MCI_DEVTYPE_FIRST: Final = MCI_DEVTYPE_VCR +MCI_DEVTYPE_LAST: Final = MCI_DEVTYPE_SEQUENCER +MCI_DEVTYPE_FIRST_USER: Final = 0x1000 +MCI_MODE_NOT_READY: Final = 524 +MCI_MODE_STOP: Final = 525 +MCI_MODE_PLAY: Final = 526 +MCI_MODE_RECORD: Final = 527 +MCI_MODE_SEEK: Final = 528 +MCI_MODE_PAUSE: Final = 529 +MCI_MODE_OPEN: Final = 530 +MCI_FORMAT_MILLISECONDS: Final = 0 +MCI_FORMAT_HMS: Final = 1 +MCI_FORMAT_MSF: Final = 2 +MCI_FORMAT_FRAMES: Final = 3 +MCI_FORMAT_SMPTE_24: Final = 4 +MCI_FORMAT_SMPTE_25: Final = 5 +MCI_FORMAT_SMPTE_30: Final = 6 +MCI_FORMAT_SMPTE_30DROP: Final = 7 +MCI_FORMAT_BYTES: Final = 8 +MCI_FORMAT_SAMPLES: Final = 9 +MCI_FORMAT_TMSF: Final = 10 + +def MCI_MSF_MINUTE(msf: int) -> int: ... +def MCI_MSF_SECOND(msf: int) -> int: ... +def MCI_MSF_FRAME(msf: int) -> int: ... +def MCI_TMSF_TRACK(tmsf: int) -> int: ... +def MCI_TMSF_MINUTE(tmsf: int) -> int: ... +def MCI_TMSF_SECOND(tmsf: int) -> int: ... +def MCI_TMSF_FRAME(tmsf: int) -> int: ... +def MCI_HMS_HOUR(hms: int) -> int: ... +def MCI_HMS_MINUTE(hms: int) -> int: ... +def MCI_HMS_SECOND(hms: int) -> int: ... + +MCI_NOTIFY_SUCCESSFUL: Final = 0x0001 +MCI_NOTIFY_SUPERSEDED: Final = 0x0002 +MCI_NOTIFY_ABORTED: Final = 0x0004 +MCI_NOTIFY_FAILURE: Final = 0x0008 +MCI_NOTIFY: Final = 0x00000001 +MCI_WAIT: Final = 0x00000002 +MCI_FROM: Final = 0x00000004 +MCI_TO: Final = 0x00000008 +MCI_TRACK: Final = 0x00000010 +MCI_OPEN_SHAREABLE: Final = 0x00000100 +MCI_OPEN_ELEMENT: Final = 0x00000200 +MCI_OPEN_ALIAS: Final = 0x00000400 +MCI_OPEN_ELEMENT_ID: Final = 0x00000800 +MCI_OPEN_TYPE_ID: Final = 0x00001000 +MCI_OPEN_TYPE: Final = 0x00002000 +MCI_SEEK_TO_START: Final = 0x00000100 +MCI_SEEK_TO_END: Final = 0x00000200 +MCI_STATUS_ITEM: Final = 0x00000100 +MCI_STATUS_START: Final = 0x00000200 +MCI_STATUS_LENGTH: Final = 0x00000001 +MCI_STATUS_POSITION: Final = 0x00000002 +MCI_STATUS_NUMBER_OF_TRACKS: Final = 0x00000003 +MCI_STATUS_MODE: Final = 0x00000004 +MCI_STATUS_MEDIA_PRESENT: Final = 0x00000005 +MCI_STATUS_TIME_FORMAT: Final = 0x00000006 +MCI_STATUS_READY: Final = 0x00000007 +MCI_STATUS_CURRENT_TRACK: Final = 0x00000008 +MCI_INFO_PRODUCT: Final = 0x00000100 +MCI_INFO_FILE: Final = 0x00000200 +MCI_INFO_MEDIA_UPC: Final = 0x00000400 +MCI_INFO_MEDIA_IDENTITY: Final = 0x00000800 +MCI_INFO_NAME: Final = 0x00001000 +MCI_INFO_COPYRIGHT: Final = 0x00002000 +MCI_GETDEVCAPS_ITEM: Final = 0x00000100 +MCI_GETDEVCAPS_CAN_RECORD: Final = 0x00000001 +MCI_GETDEVCAPS_HAS_AUDIO: Final = 0x00000002 +MCI_GETDEVCAPS_HAS_VIDEO: Final = 0x00000003 +MCI_GETDEVCAPS_DEVICE_TYPE: Final = 0x00000004 +MCI_GETDEVCAPS_USES_FILES: Final = 0x00000005 +MCI_GETDEVCAPS_COMPOUND_DEVICE: Final = 0x00000006 +MCI_GETDEVCAPS_CAN_EJECT: Final = 0x00000007 +MCI_GETDEVCAPS_CAN_PLAY: Final = 0x00000008 +MCI_GETDEVCAPS_CAN_SAVE: Final = 0x00000009 +MCI_SYSINFO_QUANTITY: Final = 0x00000100 +MCI_SYSINFO_OPEN: Final = 0x00000200 +MCI_SYSINFO_NAME: Final = 0x00000400 +MCI_SYSINFO_INSTALLNAME: Final = 0x00000800 +MCI_SET_DOOR_OPEN: Final = 0x00000100 +MCI_SET_DOOR_CLOSED: Final = 0x00000200 +MCI_SET_TIME_FORMAT: Final = 0x00000400 +MCI_SET_AUDIO: Final = 0x00000800 +MCI_SET_VIDEO: Final = 0x00001000 +MCI_SET_ON: Final = 0x00002000 +MCI_SET_OFF: Final = 0x00004000 +MCI_SET_AUDIO_ALL: Final = 0x00000000 +MCI_SET_AUDIO_LEFT: Final = 0x00000001 +MCI_SET_AUDIO_RIGHT: Final = 0x00000002 +MCI_BREAK_KEY: Final = 0x00000100 +MCI_BREAK_HWND: Final = 0x00000200 +MCI_BREAK_OFF: Final = 0x00000400 +MCI_RECORD_INSERT: Final = 0x00000100 +MCI_RECORD_OVERWRITE: Final = 0x00000200 +MCI_SAVE_FILE: Final = 0x00000100 +MCI_LOAD_FILE: Final = 0x00000100 +MCI_VD_MODE_PARK: Final = 1025 +MCI_VD_MEDIA_CLV: Final = 1026 +MCI_VD_MEDIA_CAV: Final = 1027 +MCI_VD_MEDIA_OTHER: Final = 1028 +MCI_VD_FORMAT_TRACK: Final = 0x4001 +MCI_VD_PLAY_REVERSE: Final = 0x00010000 +MCI_VD_PLAY_FAST: Final = 0x00020000 +MCI_VD_PLAY_SPEED: Final = 0x00040000 +MCI_VD_PLAY_SCAN: Final = 0x00080000 +MCI_VD_PLAY_SLOW: Final = 0x00100000 +MCI_VD_SEEK_REVERSE: Final = 0x00010000 +MCI_VD_STATUS_SPEED: Final = 0x00004002 +MCI_VD_STATUS_FORWARD: Final = 0x00004003 +MCI_VD_STATUS_MEDIA_TYPE: Final = 0x00004004 +MCI_VD_STATUS_SIDE: Final = 0x00004005 +MCI_VD_STATUS_DISC_SIZE: Final = 0x00004006 +MCI_VD_GETDEVCAPS_CLV: Final = 0x00010000 +MCI_VD_GETDEVCAPS_CAV: Final = 0x00020000 +MCI_VD_SPIN_UP: Final = 0x00010000 +MCI_VD_SPIN_DOWN: Final = 0x00020000 +MCI_VD_GETDEVCAPS_CAN_REVERSE: Final = 0x00004002 +MCI_VD_GETDEVCAPS_FAST_RATE: Final = 0x00004003 +MCI_VD_GETDEVCAPS_SLOW_RATE: Final = 0x00004004 +MCI_VD_GETDEVCAPS_NORMAL_RATE: Final = 0x00004005 +MCI_VD_STEP_FRAMES: Final = 0x00010000 +MCI_VD_STEP_REVERSE: Final = 0x00020000 +MCI_VD_ESCAPE_STRING: Final = 0x00000100 +MCI_CDA_STATUS_TYPE_TRACK: Final = 0x00004001 +MCI_CDA_TRACK_AUDIO: Final = 1088 +MCI_CDA_TRACK_OTHER: Final = 1089 +MCI_WAVE_PCM: Final = 1152 +MCI_WAVE_MAPPER: Final = 1153 +MCI_WAVE_OPEN_BUFFER: Final = 0x00010000 +MCI_WAVE_SET_FORMATTAG: Final = 0x00010000 +MCI_WAVE_SET_CHANNELS: Final = 0x00020000 +MCI_WAVE_SET_SAMPLESPERSEC: Final = 0x00040000 +MCI_WAVE_SET_AVGBYTESPERSEC: Final = 0x00080000 +MCI_WAVE_SET_BLOCKALIGN: Final = 0x00100000 +MCI_WAVE_SET_BITSPERSAMPLE: Final = 0x00200000 +MCI_WAVE_INPUT: Final = 0x00400000 +MCI_WAVE_OUTPUT: Final = 0x00800000 +MCI_WAVE_STATUS_FORMATTAG: Final = 0x00004001 +MCI_WAVE_STATUS_CHANNELS: Final = 0x00004002 +MCI_WAVE_STATUS_SAMPLESPERSEC: Final = 0x00004003 +MCI_WAVE_STATUS_AVGBYTESPERSEC: Final = 0x00004004 +MCI_WAVE_STATUS_BLOCKALIGN: Final = 0x00004005 +MCI_WAVE_STATUS_BITSPERSAMPLE: Final = 0x00004006 +MCI_WAVE_STATUS_LEVEL: Final = 0x00004007 +MCI_WAVE_SET_ANYINPUT: Final = 0x04000000 +MCI_WAVE_SET_ANYOUTPUT: Final = 0x08000000 +MCI_WAVE_GETDEVCAPS_INPUTS: Final = 0x00004001 +MCI_WAVE_GETDEVCAPS_OUTPUTS: Final = 0x00004002 +MCI_SEQ_DIV_PPQN: Final = 1216 +MCI_SEQ_DIV_SMPTE_24: Final = 1217 +MCI_SEQ_DIV_SMPTE_25: Final = 1218 +MCI_SEQ_DIV_SMPTE_30DROP: Final = 1219 +MCI_SEQ_DIV_SMPTE_30: Final = 1220 +MCI_SEQ_FORMAT_SONGPTR: Final = 0x4001 +MCI_SEQ_FILE: Final = 0x4002 +MCI_SEQ_MIDI: Final = 0x4003 +MCI_SEQ_SMPTE: Final = 0x4004 +MCI_SEQ_NONE: Final = 65533 +MCI_SEQ_MAPPER: Final = 65535 +MCI_SEQ_STATUS_TEMPO: Final = 0x00004002 +MCI_SEQ_STATUS_PORT: Final = 0x00004003 +MCI_SEQ_STATUS_SLAVE: Final = 0x00004007 +MCI_SEQ_STATUS_MASTER: Final = 0x00004008 +MCI_SEQ_STATUS_OFFSET: Final = 0x00004009 +MCI_SEQ_STATUS_DIVTYPE: Final = 0x0000400A +MCI_SEQ_STATUS_NAME: Final = 0x0000400B +MCI_SEQ_STATUS_COPYRIGHT: Final = 0x0000400C +MCI_SEQ_SET_TEMPO: Final = 0x00010000 +MCI_SEQ_SET_PORT: Final = 0x00020000 +MCI_SEQ_SET_SLAVE: Final = 0x00040000 +MCI_SEQ_SET_MASTER: Final = 0x00080000 +MCI_SEQ_SET_OFFSET: Final = 0x01000000 +MCI_ANIM_OPEN_WS: Final = 0x00010000 +MCI_ANIM_OPEN_PARENT: Final = 0x00020000 +MCI_ANIM_OPEN_NOSTATIC: Final = 0x00040000 +MCI_ANIM_PLAY_SPEED: Final = 0x00010000 +MCI_ANIM_PLAY_REVERSE: Final = 0x00020000 +MCI_ANIM_PLAY_FAST: Final = 0x00040000 +MCI_ANIM_PLAY_SLOW: Final = 0x00080000 +MCI_ANIM_PLAY_SCAN: Final = 0x00100000 +MCI_ANIM_STEP_REVERSE: Final = 0x00010000 +MCI_ANIM_STEP_FRAMES: Final = 0x00020000 +MCI_ANIM_STATUS_SPEED: Final = 0x00004001 +MCI_ANIM_STATUS_FORWARD: Final = 0x00004002 +MCI_ANIM_STATUS_HWND: Final = 0x00004003 +MCI_ANIM_STATUS_HPAL: Final = 0x00004004 +MCI_ANIM_STATUS_STRETCH: Final = 0x00004005 +MCI_ANIM_INFO_TEXT: Final = 0x00010000 +MCI_ANIM_GETDEVCAPS_CAN_REVERSE: Final = 0x00004001 +MCI_ANIM_GETDEVCAPS_FAST_RATE: Final = 0x00004002 +MCI_ANIM_GETDEVCAPS_SLOW_RATE: Final = 0x00004003 +MCI_ANIM_GETDEVCAPS_NORMAL_RATE: Final = 0x00004004 +MCI_ANIM_GETDEVCAPS_PALETTES: Final = 0x00004006 +MCI_ANIM_GETDEVCAPS_CAN_STRETCH: Final = 0x00004007 +MCI_ANIM_GETDEVCAPS_MAX_WINDOWS: Final = 0x00004008 +MCI_ANIM_REALIZE_NORM: Final = 0x00010000 +MCI_ANIM_REALIZE_BKGD: Final = 0x00020000 +MCI_ANIM_WINDOW_HWND: Final = 0x00010000 +MCI_ANIM_WINDOW_STATE: Final = 0x00040000 +MCI_ANIM_WINDOW_TEXT: Final = 0x00080000 +MCI_ANIM_WINDOW_ENABLE_STRETCH: Final = 0x00100000 +MCI_ANIM_WINDOW_DISABLE_STRETCH: Final = 0x00200000 +MCI_ANIM_WINDOW_DEFAULT: Final = 0x00000000 +MCI_ANIM_RECT: Final = 0x00010000 +MCI_ANIM_PUT_SOURCE: Final = 0x00020000 +MCI_ANIM_PUT_DESTINATION: Final = 0x00040000 +MCI_ANIM_WHERE_SOURCE: Final = 0x00020000 +MCI_ANIM_WHERE_DESTINATION: Final = 0x00040000 +MCI_ANIM_UPDATE_HDC: Final = 0x00020000 +MCI_OVLY_OPEN_WS: Final = 0x00010000 +MCI_OVLY_OPEN_PARENT: Final = 0x00020000 +MCI_OVLY_STATUS_HWND: Final = 0x00004001 +MCI_OVLY_STATUS_STRETCH: Final = 0x00004002 +MCI_OVLY_INFO_TEXT: Final = 0x00010000 +MCI_OVLY_GETDEVCAPS_CAN_STRETCH: Final = 0x00004001 +MCI_OVLY_GETDEVCAPS_CAN_FREEZE: Final = 0x00004002 +MCI_OVLY_GETDEVCAPS_MAX_WINDOWS: Final = 0x00004003 +MCI_OVLY_WINDOW_HWND: Final = 0x00010000 +MCI_OVLY_WINDOW_STATE: Final = 0x00040000 +MCI_OVLY_WINDOW_TEXT: Final = 0x00080000 +MCI_OVLY_WINDOW_ENABLE_STRETCH: Final = 0x00100000 +MCI_OVLY_WINDOW_DISABLE_STRETCH: Final = 0x00200000 +MCI_OVLY_WINDOW_DEFAULT: Final = 0x00000000 +MCI_OVLY_RECT: Final = 0x00010000 +MCI_OVLY_PUT_SOURCE: Final = 0x00020000 +MCI_OVLY_PUT_DESTINATION: Final = 0x00040000 +MCI_OVLY_PUT_FRAME: Final = 0x00080000 +MCI_OVLY_PUT_VIDEO: Final = 0x00100000 +MCI_OVLY_WHERE_SOURCE: Final = 0x00020000 +MCI_OVLY_WHERE_DESTINATION: Final = 0x00040000 +MCI_OVLY_WHERE_FRAME: Final = 0x00080000 +MCI_OVLY_WHERE_VIDEO: Final = 0x00100000 +SELECTDIB: Final = 41 + +def DIBINDEX(n): ... diff --git a/stubs/pywin32/win32/lib/ntsecuritycon.pyi b/stubs/pywin32/win32/lib/ntsecuritycon.pyi new file mode 100644 index 000000000000..15be9129670f --- /dev/null +++ b/stubs/pywin32/win32/lib/ntsecuritycon.pyi @@ -0,0 +1,552 @@ +from typing import Final + +DELETE: Final = 65536 +READ_CONTROL: Final = 131072 +WRITE_DAC: Final = 262144 +WRITE_OWNER: Final = 524288 +SYNCHRONIZE: Final = 1048576 +STANDARD_RIGHTS_REQUIRED: Final = 983040 +STANDARD_RIGHTS_READ: Final = READ_CONTROL +STANDARD_RIGHTS_WRITE: Final = READ_CONTROL +STANDARD_RIGHTS_EXECUTE: Final = READ_CONTROL +STANDARD_RIGHTS_ALL: Final = 2031616 +SPECIFIC_RIGHTS_ALL: Final = 65535 +ACCESS_SYSTEM_SECURITY: Final = 16777216 +MAXIMUM_ALLOWED: Final = 33554432 +GENERIC_READ: Final = -2147483648 +GENERIC_WRITE: Final = 1073741824 +GENERIC_EXECUTE: Final = 536870912 +GENERIC_ALL: Final = 268435456 +FILE_READ_DATA: Final = 1 +FILE_LIST_DIRECTORY: Final = 1 +FILE_WRITE_DATA: Final = 2 +FILE_ADD_FILE: Final = 2 +FILE_APPEND_DATA: Final = 4 +FILE_ADD_SUBDIRECTORY: Final = 4 +FILE_CREATE_PIPE_INSTANCE: Final = 4 +FILE_READ_EA: Final = 8 +FILE_WRITE_EA: Final = 16 +FILE_EXECUTE: Final = 32 +FILE_TRAVERSE: Final = 32 +FILE_DELETE_CHILD: Final = 64 +FILE_READ_ATTRIBUTES: Final = 128 +FILE_WRITE_ATTRIBUTES: Final = 256 +FILE_ALL_ACCESS: Final = 2032127 +FILE_GENERIC_READ: Final = 1179785 +FILE_GENERIC_WRITE: Final = 1179926 +FILE_GENERIC_EXECUTE: Final = 1179808 +SECURITY_NULL_SID_AUTHORITY: Final = (0, 0, 0, 0, 0, 0) +SECURITY_WORLD_SID_AUTHORITY: Final = (0, 0, 0, 0, 0, 1) +SECURITY_LOCAL_SID_AUTHORITY: Final = (0, 0, 0, 0, 0, 2) +SECURITY_CREATOR_SID_AUTHORITY: Final = (0, 0, 0, 0, 0, 3) +SECURITY_NON_UNIQUE_AUTHORITY: Final = (0, 0, 0, 0, 0, 4) +SECURITY_RESOURCE_MANAGER_AUTHORITY: Final = (0, 0, 0, 0, 0, 9) +SECURITY_NULL_RID: Final = 0 +SECURITY_WORLD_RID: Final = 0 +SECURITY_LOCAL_RID: Final = 0x00000000 +SECURITY_CREATOR_OWNER_RID: Final = 0 +SECURITY_CREATOR_GROUP_RID: Final = 1 +SECURITY_CREATOR_OWNER_SERVER_RID: Final = 2 +SECURITY_CREATOR_GROUP_SERVER_RID: Final = 3 +SECURITY_CREATOR_OWNER_RIGHTS_RID: Final = 4 +SECURITY_NT_AUTHORITY: Final = (0, 0, 0, 0, 0, 5) +SECURITY_DIALUP_RID: Final = 1 +SECURITY_NETWORK_RID: Final = 2 +SECURITY_BATCH_RID: Final = 3 +SECURITY_INTERACTIVE_RID: Final = 4 +SECURITY_SERVICE_RID: Final = 6 +SECURITY_ANONYMOUS_LOGON_RID: Final = 7 +SECURITY_PROXY_RID: Final = 8 +SECURITY_SERVER_LOGON_RID: Final = 9 +SECURITY_LOGON_IDS_RID: Final = 5 +SECURITY_LOGON_IDS_RID_COUNT: Final = 3 +SECURITY_LOCAL_SYSTEM_RID: Final = 18 +SECURITY_NT_NON_UNIQUE: Final = 21 +SECURITY_BUILTIN_DOMAIN_RID: Final = 32 +DOMAIN_USER_RID_ADMIN: Final = 500 +DOMAIN_USER_RID_GUEST: Final = 501 +DOMAIN_USER_RID_KRBTGT: Final = 502 +DOMAIN_USER_RID_MAX: Final = 999 +DOMAIN_GROUP_RID_ADMINS: Final = 512 +DOMAIN_GROUP_RID_USERS: Final = 513 +DOMAIN_GROUP_RID_GUESTS: Final = 514 +DOMAIN_GROUP_RID_COMPUTERS: Final = 515 +DOMAIN_GROUP_RID_CONTROLLERS: Final = 516 +DOMAIN_GROUP_RID_CERT_ADMINS: Final = 517 +DOMAIN_GROUP_RID_SCHEMA_ADMINS: Final = 518 +DOMAIN_GROUP_RID_ENTERPRISE_ADMINS: Final = 519 +DOMAIN_GROUP_RID_POLICY_ADMINS: Final = 520 +DOMAIN_GROUP_RID_READONLY_CONTROLLERS: Final = 521 +DOMAIN_ALIAS_RID_ADMINS: Final = 544 +DOMAIN_ALIAS_RID_USERS: Final = 545 +DOMAIN_ALIAS_RID_GUESTS: Final = 546 +DOMAIN_ALIAS_RID_POWER_USERS: Final = 547 +DOMAIN_ALIAS_RID_ACCOUNT_OPS: Final = 548 +DOMAIN_ALIAS_RID_SYSTEM_OPS: Final = 549 +DOMAIN_ALIAS_RID_PRINT_OPS: Final = 550 +DOMAIN_ALIAS_RID_BACKUP_OPS: Final = 551 +DOMAIN_ALIAS_RID_REPLICATOR: Final = 552 +DOMAIN_ALIAS_RID_RAS_SERVERS: Final = 553 +DOMAIN_ALIAS_RID_PREW2KCOMPACCESS: Final = 554 +DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS: Final = 555 +DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS: Final = 556 +DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS: Final = 557 +DOMAIN_ALIAS_RID_MONITORING_USERS: Final = 558 +DOMAIN_ALIAS_RID_LOGGING_USERS: Final = 559 +DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS: Final = 560 +DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS: Final = 561 +DOMAIN_ALIAS_RID_DCOM_USERS: Final = 562 +DOMAIN_ALIAS_RID_IUSERS: Final = 568 +DOMAIN_ALIAS_RID_CRYPTO_OPERATORS: Final = 569 +DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP: Final = 571 +DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP: Final = 572 +DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP: Final = 573 +SECURITY_MANDATORY_LABEL_AUTHORITY: Final = (0, 0, 0, 0, 0, 16) +SECURITY_MANDATORY_UNTRUSTED_RID: Final = 0x00000000 +SECURITY_MANDATORY_LOW_RID: Final = 0x00001000 +SECURITY_MANDATORY_MEDIUM_RID: Final = 0x00002000 +SECURITY_MANDATORY_HIGH_RID: Final = 0x00003000 +SECURITY_MANDATORY_SYSTEM_RID: Final = 0x00004000 +SECURITY_MANDATORY_PROTECTED_PROCESS_RID: Final = 0x00005000 +SECURITY_MANDATORY_MAXIMUM_USER_RID: Final = SECURITY_MANDATORY_SYSTEM_RID +SYSTEM_LUID: Final = (999, 0) +ANONYMOUS_LOGON_LUID: Final = (998, 0) +LOCALSERVICE_LUID: Final = (997, 0) +NETWORKSERVICE_LUID: Final = (996, 0) +IUSER_LUID: Final = (995, 0) +SE_GROUP_MANDATORY: Final = 1 +SE_GROUP_ENABLED_BY_DEFAULT: Final = 2 +SE_GROUP_ENABLED: Final = 4 +SE_GROUP_OWNER: Final = 8 +SE_GROUP_USE_FOR_DENY_ONLY: Final = 16 +SE_GROUP_INTEGRITY: Final = 32 +SE_GROUP_INTEGRITY_ENABLED: Final = 64 +SE_GROUP_RESOURCE: Final = 536870912 +SE_GROUP_LOGON_ID: Final = -1073741824 +ACCESS_MIN_MS_ACE_TYPE: Final = 0 +ACCESS_ALLOWED_ACE_TYPE: Final = 0 +ACCESS_DENIED_ACE_TYPE: Final = 1 +SYSTEM_AUDIT_ACE_TYPE: Final = 2 +SYSTEM_ALARM_ACE_TYPE: Final = 3 +ACCESS_MAX_MS_V2_ACE_TYPE: Final = 3 +ACCESS_ALLOWED_COMPOUND_ACE_TYPE: Final = 4 +ACCESS_MAX_MS_V3_ACE_TYPE: Final = 4 +ACCESS_MIN_MS_OBJECT_ACE_TYPE: Final = 5 +ACCESS_ALLOWED_OBJECT_ACE_TYPE: Final = 5 +ACCESS_DENIED_OBJECT_ACE_TYPE: Final = 6 +SYSTEM_AUDIT_OBJECT_ACE_TYPE: Final = 7 +SYSTEM_ALARM_OBJECT_ACE_TYPE: Final = 8 +ACCESS_MAX_MS_OBJECT_ACE_TYPE: Final = 8 +ACCESS_MAX_MS_V4_ACE_TYPE: Final = 8 +ACCESS_MAX_MS_ACE_TYPE: Final = 8 +ACCESS_ALLOWED_CALLBACK_ACE_TYPE: Final = 9 +ACCESS_DENIED_CALLBACK_ACE_TYPE: Final = 10 +ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: Final = 11 +ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: Final = 12 +SYSTEM_AUDIT_CALLBACK_ACE_TYPE: Final = 13 +SYSTEM_ALARM_CALLBACK_ACE_TYPE: Final = 14 +SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE: Final = 15 +SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE: Final = 16 +SYSTEM_MANDATORY_LABEL_ACE_TYPE: Final = 17 +ACCESS_MAX_MS_V5_ACE_TYPE: Final = 17 +OBJECT_INHERIT_ACE: Final = 1 +CONTAINER_INHERIT_ACE: Final = 2 +NO_PROPAGATE_INHERIT_ACE: Final = 4 +INHERIT_ONLY_ACE: Final = 8 +VALID_INHERIT_FLAGS: Final = 15 +SUCCESSFUL_ACCESS_ACE_FLAG: Final = 64 +FAILED_ACCESS_ACE_FLAG: Final = 128 +SE_OWNER_DEFAULTED: Final = 1 +SE_GROUP_DEFAULTED: Final = 2 +SE_DACL_PRESENT: Final = 4 +SE_DACL_DEFAULTED: Final = 8 +SE_SACL_PRESENT: Final = 16 +SE_SACL_DEFAULTED: Final = 32 +SE_SELF_RELATIVE: Final = 32768 +SE_PRIVILEGE_ENABLED_BY_DEFAULT: Final = 1 +SE_PRIVILEGE_ENABLED: Final = 2 +SE_PRIVILEGE_USED_FOR_ACCESS: Final = -2147483648 +PRIVILEGE_SET_ALL_NECESSARY: Final = 1 +SE_CREATE_TOKEN_NAME: Final = "SeCreateTokenPrivilege" +SE_ASSIGNPRIMARYTOKEN_NAME: Final = "SeAssignPrimaryTokenPrivilege" +SE_LOCK_MEMORY_NAME: Final = "SeLockMemoryPrivilege" +SE_INCREASE_QUOTA_NAME: Final = "SeIncreaseQuotaPrivilege" +SE_UNSOLICITED_INPUT_NAME: Final = "SeUnsolicitedInputPrivilege" +SE_MACHINE_ACCOUNT_NAME: Final = "SeMachineAccountPrivilege" +SE_TCB_NAME: Final = "SeTcbPrivilege" +SE_SECURITY_NAME: Final = "SeSecurityPrivilege" +SE_TAKE_OWNERSHIP_NAME: Final = "SeTakeOwnershipPrivilege" +SE_LOAD_DRIVER_NAME: Final = "SeLoadDriverPrivilege" +SE_SYSTEM_PROFILE_NAME: Final = "SeSystemProfilePrivilege" +SE_SYSTEMTIME_NAME: Final = "SeSystemtimePrivilege" +SE_PROF_SINGLE_PROCESS_NAME: Final = "SeProfileSingleProcessPrivilege" +SE_INC_BASE_PRIORITY_NAME: Final = "SeIncreaseBasePriorityPrivilege" +SE_CREATE_PAGEFILE_NAME: Final = "SeCreatePagefilePrivilege" +SE_CREATE_PERMANENT_NAME: Final = "SeCreatePermanentPrivilege" +SE_BACKUP_NAME: Final = "SeBackupPrivilege" +SE_RESTORE_NAME: Final = "SeRestorePrivilege" +SE_SHUTDOWN_NAME: Final = "SeShutdownPrivilege" +SE_DEBUG_NAME: Final = "SeDebugPrivilege" +SE_AUDIT_NAME: Final = "SeAuditPrivilege" +SE_SYSTEM_ENVIRONMENT_NAME: Final = "SeSystemEnvironmentPrivilege" +SE_CHANGE_NOTIFY_NAME: Final = "SeChangeNotifyPrivilege" +SE_REMOTE_SHUTDOWN_NAME: Final = "SeRemoteShutdownPrivilege" +SecurityAnonymous: Final = 0 +SecurityIdentification: Final = 1 +SecurityImpersonation: Final = 2 +SecurityDelegation: Final = 3 +SECURITY_MAX_IMPERSONATION_LEVEL: Final = SecurityDelegation +DEFAULT_IMPERSONATION_LEVEL: Final = SecurityImpersonation +TOKEN_ASSIGN_PRIMARY: Final = 1 +TOKEN_DUPLICATE: Final = 2 +TOKEN_IMPERSONATE: Final = 4 +TOKEN_QUERY: Final = 8 +TOKEN_QUERY_SOURCE: Final = 16 +TOKEN_ADJUST_PRIVILEGES: Final = 32 +TOKEN_ADJUST_GROUPS: Final = 64 +TOKEN_ADJUST_DEFAULT: Final = 128 +TOKEN_ALL_ACCESS: Final = 983295 +TOKEN_READ: Final = 131080 +TOKEN_WRITE: Final = 131296 +TOKEN_EXECUTE: Final = STANDARD_RIGHTS_EXECUTE +SidTypeUser: Final = 1 +SidTypeGroup: Final = 2 +SidTypeDomain: Final = 3 +SidTypeAlias: Final = 4 +SidTypeWellKnownGroup: Final = 5 +SidTypeDeletedAccount: Final = 6 +SidTypeInvalid: Final = 7 +SidTypeUnknown: Final = 8 +SidTypeComputer: Final = 9 +SidTypeLabel: Final = 10 +TokenPrimary: Final = 1 +TokenImpersonation: Final = 2 +TokenUser: Final = 1 +TokenGroups: Final = 2 +TokenPrivileges: Final = 3 +TokenOwner: Final = 4 +TokenPrimaryGroup: Final = 5 +TokenDefaultDacl: Final = 6 +TokenSource: Final = 7 +TokenType: Final = 8 +TokenImpersonationLevel: Final = 9 +TokenStatistics: Final = 10 +TokenRestrictedSids: Final = 11 +TokenSessionId: Final = 12 +TokenGroupsAndPrivileges: Final = 13 +TokenSessionReference: Final = 14 +TokenSandBoxInert: Final = 15 +TokenAuditPolicy: Final = 16 +TokenOrigin: Final = 17 +TokenElevationType: Final = 18 +TokenLinkedToken: Final = 19 +TokenElevation: Final = 20 +TokenHasRestrictions: Final = 21 +TokenAccessInformation: Final = 22 +TokenVirtualizationAllowed: Final = 23 +TokenVirtualizationEnabled: Final = 24 +TokenIntegrityLevel: Final = 25 +TokenUIAccess: Final = 26 +TokenMandatoryPolicy: Final = 27 +TokenLogonSid: Final = 28 +DS_BEHAVIOR_WIN2000: Final = 0 +DS_BEHAVIOR_WIN2003_WITH_MIXED_DOMAINS: Final = 1 +DS_BEHAVIOR_WIN2003: Final = 2 +DS_SYNCED_EVENT_NAME: Final = "NTDSInitialSyncsCompleted" +ACTRL_DS_OPEN: Final = 0x00000000 +ACTRL_DS_CREATE_CHILD: Final = 0x00000001 +ACTRL_DS_DELETE_CHILD: Final = 0x00000002 +ACTRL_DS_LIST: Final = 0x00000004 +ACTRL_DS_SELF: Final = 0x00000008 +ACTRL_DS_READ_PROP: Final = 0x00000010 +ACTRL_DS_WRITE_PROP: Final = 0x00000020 +ACTRL_DS_DELETE_TREE: Final = 0x00000040 +ACTRL_DS_LIST_OBJECT: Final = 0x00000080 +ACTRL_DS_CONTROL_ACCESS: Final = 0x00000100 +NTDSAPI_BIND_ALLOW_DELEGATION: Final = 0x00000001 +DS_REPSYNC_ASYNCHRONOUS_OPERATION: Final = 0x00000001 +DS_REPSYNC_WRITEABLE: Final = 0x00000002 +DS_REPSYNC_PERIODIC: Final = 0x00000004 +DS_REPSYNC_INTERSITE_MESSAGING: Final = 0x00000008 +DS_REPSYNC_ALL_SOURCES: Final = 0x00000010 +DS_REPSYNC_FULL: Final = 0x00000020 +DS_REPSYNC_URGENT: Final = 0x00000040 +DS_REPSYNC_NO_DISCARD: Final = 0x00000080 +DS_REPSYNC_FORCE: Final = 0x00000100 +DS_REPSYNC_ADD_REFERENCE: Final = 0x00000200 +DS_REPSYNC_NEVER_COMPLETED: Final = 0x00000400 +DS_REPSYNC_TWO_WAY: Final = 0x00000800 +DS_REPSYNC_NEVER_NOTIFY: Final = 0x00001000 +DS_REPSYNC_INITIAL: Final = 0x00002000 +DS_REPSYNC_USE_COMPRESSION: Final = 0x00004000 +DS_REPSYNC_ABANDONED: Final = 0x00008000 +DS_REPSYNC_INITIAL_IN_PROGRESS: Final = 0x00010000 +DS_REPSYNC_PARTIAL_ATTRIBUTE_SET: Final = 0x00020000 +DS_REPSYNC_REQUEUE: Final = 0x00040000 +DS_REPSYNC_NOTIFICATION: Final = 0x00080000 +DS_REPSYNC_ASYNCHRONOUS_REPLICA: Final = 0x00100000 +DS_REPSYNC_CRITICAL: Final = 0x00200000 +DS_REPSYNC_FULL_IN_PROGRESS: Final = 0x00400000 +DS_REPSYNC_PREEMPTED: Final = 0x00800000 +DS_REPADD_ASYNCHRONOUS_OPERATION: Final = 0x00000001 +DS_REPADD_WRITEABLE: Final = 0x00000002 +DS_REPADD_INITIAL: Final = 0x00000004 +DS_REPADD_PERIODIC: Final = 0x00000008 +DS_REPADD_INTERSITE_MESSAGING: Final = 0x00000010 +DS_REPADD_ASYNCHRONOUS_REPLICA: Final = 0x00000020 +DS_REPADD_DISABLE_NOTIFICATION: Final = 0x00000040 +DS_REPADD_DISABLE_PERIODIC: Final = 0x00000080 +DS_REPADD_USE_COMPRESSION: Final = 0x00000100 +DS_REPADD_NEVER_NOTIFY: Final = 0x00000200 +DS_REPADD_TWO_WAY: Final = 0x00000400 +DS_REPADD_CRITICAL: Final = 0x00000800 +DS_REPDEL_ASYNCHRONOUS_OPERATION: Final = 0x00000001 +DS_REPDEL_WRITEABLE: Final = 0x00000002 +DS_REPDEL_INTERSITE_MESSAGING: Final = 0x00000004 +DS_REPDEL_IGNORE_ERRORS: Final = 0x00000008 +DS_REPDEL_LOCAL_ONLY: Final = 0x00000010 +DS_REPDEL_NO_SOURCE: Final = 0x00000020 +DS_REPDEL_REF_OK: Final = 0x00000040 +DS_REPMOD_ASYNCHRONOUS_OPERATION: Final = 0x00000001 +DS_REPMOD_WRITEABLE: Final = 0x00000002 +DS_REPMOD_UPDATE_FLAGS: Final = 0x00000001 +DS_REPMOD_UPDATE_ADDRESS: Final = 0x00000002 +DS_REPMOD_UPDATE_SCHEDULE: Final = 0x00000004 +DS_REPMOD_UPDATE_RESULT: Final = 0x00000008 +DS_REPMOD_UPDATE_TRANSPORT: Final = 0x00000010 +DS_REPUPD_ASYNCHRONOUS_OPERATION: Final = 0x00000001 +DS_REPUPD_WRITEABLE: Final = 0x00000002 +DS_REPUPD_ADD_REFERENCE: Final = 0x00000004 +DS_REPUPD_DELETE_REFERENCE: Final = 0x00000008 +DS_INSTANCETYPE_IS_NC_HEAD: Final = 0x00000001 +DS_INSTANCETYPE_NC_IS_WRITEABLE: Final = 0x00000004 +DS_INSTANCETYPE_NC_COMING: Final = 0x00000010 +DS_INSTANCETYPE_NC_GOING: Final = 0x00000020 +NTDSDSA_OPT_IS_GC: Final = 1 +NTDSDSA_OPT_DISABLE_INBOUND_REPL: Final = 2 +NTDSDSA_OPT_DISABLE_OUTBOUND_REPL: Final = 4 +NTDSDSA_OPT_DISABLE_NTDSCONN_XLATE: Final = 8 +NTDSCONN_OPT_IS_GENERATED: Final = 1 +NTDSCONN_OPT_TWOWAY_SYNC: Final = 2 +NTDSCONN_OPT_OVERRIDE_NOTIFY_DEFAULT: Final = 4 +NTDSCONN_OPT_USE_NOTIFY: Final = 8 +NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION: Final = 16 +NTDSCONN_OPT_USER_OWNED_SCHEDULE: Final = 32 +NTDSCONN_KCC_NO_REASON: Final = 0 +NTDSCONN_KCC_GC_TOPOLOGY: Final = 1 +NTDSCONN_KCC_RING_TOPOLOGY: Final = 2 +NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY: Final = 4 +NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY: Final = 8 +NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY: Final = 16 +NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY: Final = 32 +NTDSCONN_KCC_INTERSITE_TOPOLOGY: Final = 64 +NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY: Final = 128 +NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY: Final = 256 +NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY: Final = 512 +FRSCONN_PRIORITY_MASK: Final = 0x70000000 +FRSCONN_MAX_PRIORITY: Final = 0x8 +NTDSCONN_OPT_IGNORE_SCHEDULE_MASK: Final = -2147483648 +NTDSSETTINGS_OPT_IS_AUTO_TOPOLOGY_DISABLED: Final = 1 +NTDSSETTINGS_OPT_IS_TOPL_CLEANUP_DISABLED: Final = 2 +NTDSSETTINGS_OPT_IS_TOPL_MIN_HOPS_DISABLED: Final = 4 +NTDSSETTINGS_OPT_IS_TOPL_DETECT_STALE_DISABLED: Final = 8 +NTDSSETTINGS_OPT_IS_INTER_SITE_AUTO_TOPOLOGY_DISABLED: Final = 16 +NTDSSETTINGS_OPT_IS_GROUP_CACHING_ENABLED: Final = 32 +NTDSSETTINGS_OPT_FORCE_KCC_WHISTLER_BEHAVIOR: Final = 64 +NTDSSETTINGS_OPT_FORCE_KCC_W2K_ELECTION: Final = 128 +NTDSSETTINGS_OPT_IS_RAND_BH_SELECTION_DISABLED: Final = 256 +NTDSSETTINGS_OPT_IS_SCHEDULE_HASHING_ENABLED: Final = 512 +NTDSSETTINGS_OPT_IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED: Final = 1024 +NTDSSETTINGS_DEFAULT_SERVER_REDUNDANCY: Final = 2 +NTDSTRANSPORT_OPT_IGNORE_SCHEDULES: Final = 1 +NTDSTRANSPORT_OPT_BRIDGES_REQUIRED: Final = 2 +NTDSSITECONN_OPT_USE_NOTIFY: Final = 1 +NTDSSITECONN_OPT_TWOWAY_SYNC: Final = 2 +NTDSSITECONN_OPT_DISABLE_COMPRESSION: Final = 4 +NTDSSITELINK_OPT_USE_NOTIFY: Final = 1 +NTDSSITELINK_OPT_TWOWAY_SYNC: Final = 2 +NTDSSITELINK_OPT_DISABLE_COMPRESSION: Final = 4 +GUID_USERS_CONTAINER_A: Final = "a9d1ca15768811d1aded00c04fd8d5cd" +GUID_COMPUTRS_CONTAINER_A: Final = "aa312825768811d1aded00c04fd8d5cd" +GUID_SYSTEMS_CONTAINER_A: Final = "ab1d30f3768811d1aded00c04fd8d5cd" +GUID_DOMAIN_CONTROLLERS_CONTAINER_A: Final = "a361b2ffffd211d1aa4b00c04fd7d83a" +GUID_INFRASTRUCTURE_CONTAINER_A: Final = "2fbac1870ade11d297c400c04fd8d5cd" +GUID_DELETED_OBJECTS_CONTAINER_A: Final = "18e2ea80684f11d2b9aa00c04f79f805" +GUID_LOSTANDFOUND_CONTAINER_A: Final = "ab8153b7768811d1aded00c04fd8d5cd" +GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_A: Final = "22b70c67d56e4efb91e9300fca3dc1aa" +GUID_PROGRAM_DATA_CONTAINER_A: Final = "09460c08ae1e4a4ea0f64aee7daa1e5a" +GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_A: Final = "f4be92a4c777485e878e9421d53087db" +GUID_NTDS_QUOTAS_CONTAINER_A: Final = "6227f0af1fc2410d8e3bb10615bb5b0f" +GUID_USERS_CONTAINER_BYTE: Final = "\xa9\xd1\xca\x15\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd" +GUID_COMPUTRS_CONTAINER_BYTE: Final = "\xaa\x31\x28\x25\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd" +GUID_SYSTEMS_CONTAINER_BYTE: Final = "\xab\x1d\x30\xf3\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd" +GUID_DOMAIN_CONTROLLERS_CONTAINER_BYTE: Final = "\xa3\x61\xb2\xff\xff\xd2\x11\xd1\xaa\x4b\x00\xc0\x4f\xd7\xd8\x3a" +GUID_INFRASTRUCTURE_CONTAINER_BYTE: Final = "\x2f\xba\xc1\x87\x0a\xde\x11\xd2\x97\xc4\x00\xc0\x4f\xd8\xd5\xcd" +GUID_DELETED_OBJECTS_CONTAINER_BYTE: Final = "\x18\xe2\xea\x80\x68\x4f\x11\xd2\xb9\xaa\x00\xc0\x4f\x79\xf8\x05" +GUID_LOSTANDFOUND_CONTAINER_BYTE: Final = "\xab\x81\x53\xb7\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd" +GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE: Final = "\x22\xb7\x0c\x67\xd5\x6e\x4e\xfb\x91\xe9\x30\x0f\xca\x3d\xc1\xaa" +GUID_PROGRAM_DATA_CONTAINER_BYTE: Final = "\x09\x46\x0c\x08\xae\x1e\x4a\x4e\xa0\xf6\x4a\xee\x7d\xaa\x1e\x5a" +GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_BYTE: Final = "\xf4\xbe\x92\xa4\xc7\x77\x48\x5e\x87\x8e\x94\x21\xd5\x30\x87\xdb" +GUID_NTDS_QUOTAS_CONTAINER_BYTE: Final = "\x62\x27\xf0\xaf\x1f\xc2\x41\x0d\x8e\x3b\xb1\x06\x15\xbb\x5b\x0f" +DS_REPSYNCALL_NO_OPTIONS: Final = 0x00000000 +DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE: Final = 0x00000001 +DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY: Final = 0x00000002 +DS_REPSYNCALL_ID_SERVERS_BY_DN: Final = 0x00000004 +DS_REPSYNCALL_DO_NOT_SYNC: Final = 0x00000008 +DS_REPSYNCALL_SKIP_INITIAL_CHECK: Final = 0x00000010 +DS_REPSYNCALL_PUSH_CHANGES_OUTWARD: Final = 0x00000020 +DS_REPSYNCALL_CROSS_SITE_BOUNDARIES: Final = 0x00000040 +DS_LIST_DSA_OBJECT_FOR_SERVER: Final = 0 +DS_LIST_DNS_HOST_NAME_FOR_SERVER: Final = 1 +DS_LIST_ACCOUNT_OBJECT_FOR_SERVER: Final = 2 +DS_ROLE_SCHEMA_OWNER: Final = 0 +DS_ROLE_DOMAIN_OWNER: Final = 1 +DS_ROLE_PDC_OWNER: Final = 2 +DS_ROLE_RID_OWNER: Final = 3 +DS_ROLE_INFRASTRUCTURE_OWNER: Final = 4 +DS_SCHEMA_GUID_NOT_FOUND: Final = 0 +DS_SCHEMA_GUID_ATTR: Final = 1 +DS_SCHEMA_GUID_ATTR_SET: Final = 2 +DS_SCHEMA_GUID_CLASS: Final = 3 +DS_SCHEMA_GUID_CONTROL_RIGHT: Final = 4 +DS_KCC_FLAG_ASYNC_OP: Final = 1 +DS_KCC_FLAG_DAMPED: Final = 2 +DS_EXIST_ADVISORY_MODE: Final = 0x1 +DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS: Final = 0x00000001 +DS_REPL_NBR_WRITEABLE: Final = 0x00000010 +DS_REPL_NBR_SYNC_ON_STARTUP: Final = 0x00000020 +DS_REPL_NBR_DO_SCHEDULED_SYNCS: Final = 0x00000040 +DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT: Final = 0x00000080 +DS_REPL_NBR_TWO_WAY_SYNC: Final = 0x00000200 +DS_REPL_NBR_RETURN_OBJECT_PARENTS: Final = 0x00000800 +DS_REPL_NBR_FULL_SYNC_IN_PROGRESS: Final = 0x00010000 +DS_REPL_NBR_FULL_SYNC_NEXT_PACKET: Final = 0x00020000 +DS_REPL_NBR_NEVER_SYNCED: Final = 0x00200000 +DS_REPL_NBR_PREEMPTED: Final = 0x01000000 +DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS: Final = 0x04000000 +DS_REPL_NBR_DISABLE_SCHEDULED_SYNC: Final = 0x08000000 +DS_REPL_NBR_COMPRESS_CHANGES: Final = 0x10000000 +DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS: Final = 0x20000000 +DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET: Final = 0x40000000 +DS_REPL_NBR_MODIFIABLE_MASK: Final = 0x3C000260 +DS_UNKNOWN_NAME: Final = 0 +DS_FQDN_1779_NAME: Final = 1 +DS_NT4_ACCOUNT_NAME: Final = 2 +DS_DISPLAY_NAME: Final = 3 +DS_UNIQUE_ID_NAME: Final = 6 +DS_CANONICAL_NAME: Final = 7 +DS_USER_PRINCIPAL_NAME: Final = 8 +DS_CANONICAL_NAME_EX: Final = 9 +DS_SERVICE_PRINCIPAL_NAME: Final = 10 +DS_SID_OR_SID_HISTORY_NAME: Final = 11 +DS_DNS_DOMAIN_NAME: Final = 12 +DS_DOMAIN_SIMPLE_NAME: Final = DS_USER_PRINCIPAL_NAME +DS_ENTERPRISE_SIMPLE_NAME: Final = DS_USER_PRINCIPAL_NAME +DS_NAME_NO_FLAGS: Final = 0x0 +DS_NAME_FLAG_SYNTACTICAL_ONLY: Final = 0x1 +DS_NAME_FLAG_EVAL_AT_DC: Final = 0x2 +DS_NAME_FLAG_GCVERIFY: Final = 0x4 +DS_NAME_FLAG_TRUST_REFERRAL: Final = 0x8 +DS_NAME_NO_ERROR: Final = 0 +DS_NAME_ERROR_RESOLVING: Final = 1 +DS_NAME_ERROR_NOT_FOUND: Final = 2 +DS_NAME_ERROR_NOT_UNIQUE: Final = 3 +DS_NAME_ERROR_NO_MAPPING: Final = 4 +DS_NAME_ERROR_DOMAIN_ONLY: Final = 5 +DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: Final = 6 +DS_NAME_ERROR_TRUST_REFERRAL: Final = 7 +DS_SPN_DNS_HOST: Final = 0 +DS_SPN_DN_HOST: Final = 1 +DS_SPN_NB_HOST: Final = 2 +DS_SPN_DOMAIN: Final = 3 +DS_SPN_NB_DOMAIN: Final = 4 +DS_SPN_SERVICE: Final = 5 +DS_SPN_ADD_SPN_OP: Final = 0 +DS_SPN_REPLACE_SPN_OP: Final = 1 +DS_SPN_DELETE_SPN_OP: Final = 2 +DS_FORCE_REDISCOVERY: Final = 0x00000001 +DS_DIRECTORY_SERVICE_REQUIRED: Final = 0x00000010 +DS_DIRECTORY_SERVICE_PREFERRED: Final = 0x00000020 +DS_GC_SERVER_REQUIRED: Final = 0x00000040 +DS_PDC_REQUIRED: Final = 0x00000080 +DS_BACKGROUND_ONLY: Final = 0x00000100 +DS_IP_REQUIRED: Final = 0x00000200 +DS_KDC_REQUIRED: Final = 0x00000400 +DS_TIMESERV_REQUIRED: Final = 0x00000800 +DS_WRITABLE_REQUIRED: Final = 0x00001000 +DS_GOOD_TIMESERV_PREFERRED: Final = 0x00002000 +DS_AVOID_SELF: Final = 0x00004000 +DS_ONLY_LDAP_NEEDED: Final = 0x00008000 +DS_IS_FLAT_NAME: Final = 0x00010000 +DS_IS_DNS_NAME: Final = 0x00020000 +DS_RETURN_DNS_NAME: Final = 0x40000000 +DS_RETURN_FLAT_NAME: Final = -2147483648 +DSGETDC_VALID_FLAGS: Final = -0x3FFC000F +DS_INET_ADDRESS: Final = 1 +DS_NETBIOS_ADDRESS: Final = 2 +DS_PDC_FLAG: Final = 0x00000001 +DS_GC_FLAG: Final = 0x00000004 +DS_LDAP_FLAG: Final = 0x00000008 +DS_DS_FLAG: Final = 0x00000010 +DS_KDC_FLAG: Final = 0x00000020 +DS_TIMESERV_FLAG: Final = 0x00000040 +DS_CLOSEST_FLAG: Final = 0x00000080 +DS_WRITABLE_FLAG: Final = 0x00000100 +DS_GOOD_TIMESERV_FLAG: Final = 0x00000200 +DS_NDNC_FLAG: Final = 0x00000400 +DS_PING_FLAGS: Final = 0x0000FFFF +DS_DNS_CONTROLLER_FLAG: Final = 0x20000000 +DS_DNS_DOMAIN_FLAG: Final = 0x40000000 +DS_DNS_FOREST_FLAG: Final = -2147483648 +DS_DOMAIN_IN_FOREST: Final = 0x0001 +DS_DOMAIN_DIRECT_OUTBOUND: Final = 0x0002 +DS_DOMAIN_TREE_ROOT: Final = 0x0004 +DS_DOMAIN_PRIMARY: Final = 0x0008 +DS_DOMAIN_NATIVE_MODE: Final = 0x0010 +DS_DOMAIN_DIRECT_INBOUND: Final = 0x0020 +DS_DOMAIN_VALID_FLAGS: Final = 0x3F +DS_GFTI_UPDATE_TDO: Final = 0x1 +DS_GFTI_VALID_FLAGS: Final = 0x1 +DS_ONLY_DO_SITE_NAME: Final = 0x01 +DS_NOTIFY_AFTER_SITE_RECORDS: Final = 0x02 +DS_OPEN_VALID_OPTION_FLAGS: Final = 0x03 +DS_OPEN_VALID_FLAGS: Final = 0x000094C1 +SI_EDIT_PERMS: Final = 0x00000000 +SI_EDIT_OWNER: Final = 0x00000001 +SI_EDIT_AUDITS: Final = 0x00000002 +SI_CONTAINER: Final = 0x00000004 +SI_READONLY: Final = 0x00000008 +SI_ADVANCED: Final = 0x00000010 +SI_RESET: Final = 0x00000020 +SI_OWNER_READONLY: Final = 0x00000040 +SI_EDIT_PROPERTIES: Final = 0x00000080 +SI_OWNER_RECURSE: Final = 0x00000100 +SI_NO_ACL_PROTECT: Final = 0x00000200 +SI_NO_TREE_APPLY: Final = 0x00000400 +SI_PAGE_TITLE: Final = 0x00000800 +SI_SERVER_IS_DC: Final = 0x00001000 +SI_RESET_DACL_TREE: Final = 0x00004000 +SI_RESET_SACL_TREE: Final = 0x00008000 +SI_OBJECT_GUID: Final = 0x00010000 +SI_EDIT_EFFECTIVE: Final = 0x00020000 +SI_RESET_DACL: Final = 0x00040000 +SI_RESET_SACL: Final = 0x00080000 +SI_RESET_OWNER: Final = 0x00100000 +SI_NO_ADDITIONAL_PERMISSION: Final = 0x00200000 +SI_MAY_WRITE: Final = 0x10000000 +SI_EDIT_ALL: Final = 0x00000003 +SI_AUDITS_ELEVATION_REQUIRED: Final = 0x02000000 +SI_VIEW_ONLY: Final = 0x00400000 +SI_OWNER_ELEVATION_REQUIRED: Final = 0x04000000 +SI_PERMS_ELEVATION_REQUIRED: Final = 0x01000000 +SI_ACCESS_SPECIFIC: Final = 0x00010000 +SI_ACCESS_GENERAL: Final = 0x00020000 +SI_ACCESS_CONTAINER: Final = 0x00040000 +SI_ACCESS_PROPERTY: Final = 0x00080000 +SI_PAGE_PERM: Final = 0 +SI_PAGE_ADVPERM: Final = 1 +SI_PAGE_AUDIT: Final = 2 +SI_PAGE_OWNER: Final = 3 +SI_PAGE_EFFECTIVE: Final = 4 +CFSTR_ACLUI_SID_INFO_LIST: Final = "CFSTR_ACLUI_SID_INFO_LIST" +PSPCB_SI_INITDIALOG: Final = 1025 diff --git a/stubs/pywin32/win32/lib/pywintypes.pyi b/stubs/pywin32/win32/lib/pywintypes.pyi new file mode 100644 index 000000000000..e4965177a0c0 --- /dev/null +++ b/stubs/pywin32/win32/lib/pywintypes.pyi @@ -0,0 +1,51 @@ +# Can't generate with stubgen because `import pywintypes` must be called first. +# Otherwise you get the error: "KeyError: 'pywintypes'" +from _typeshed import Incomplete +from collections.abc import Sequence +from datetime import datetime +from typing import ClassVar, Final, SupportsInt, overload +from typing_extensions import deprecated + +import _win32typing + +class error(Exception): + winerror: int + funcname: str + strerror: str + def __init__(self, winerror: int, funcname: str, strerror: str, /): ... + +class com_error(Exception): ... + +class TimeType(datetime): # aka: PyTime, PyDateTime + __name__: ClassVar[str] = "datetime" + def Format(self, format: str = "%c") -> str: ... + +HANDLEType = _win32typing.PyHANDLE +DEVMODEType = _win32typing.PyDEVMODEW +DEVMODEWType = _win32typing.PyDEVMODEW +IIDType = _win32typing.PyIID + +def DosDateTimeToTime(FatDate: int, FatTime: int, /) -> TimeType: ... +def UnicodeFromRaw(_str: str, /) -> str: ... +def IsTextUnicode(_str: str, flags, /) -> tuple[Incomplete, Incomplete]: ... +def OVERLAPPED() -> _win32typing.PyOVERLAPPED: ... +def IID(iidString: str, is_bytes: bool = ..., /) -> _win32typing.PyIID: ... +def Time(timeRepr: SupportsInt | Sequence[SupportsInt] | TimeType, /) -> TimeType: ... +def CreateGuid() -> _win32typing.PyIID: ... +def ACL(bufSize: int = ..., /) -> _win32typing.PyACL: ... +def SID(buffer, idAuthority, subAuthorities, bufSize=..., /) -> _win32typing.PySID: ... +def SECURITY_ATTRIBUTES() -> _win32typing.PySECURITY_ATTRIBUTES: ... +def SECURITY_DESCRIPTOR() -> _win32typing.PySECURITY_DESCRIPTOR: ... +def HANDLE() -> _win32typing.PyHANDLE: ... +def HKEY() -> _win32typing.PyHKEY: ... +def WAVEFORMATEX() -> _win32typing.PyWAVEFORMATEX: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def TimeStamp(timestamp: tuple[int, int], /) -> TimeType: ... +@overload +def TimeStamp(timestamp: int, /) -> TimeType: ... + +FALSE: Final = False +TRUE: Final = True +WAVE_FORMAT_PCM: int diff --git a/stubs/pywin32/win32/lib/regutil.pyi b/stubs/pywin32/win32/lib/regutil.pyi new file mode 100644 index 000000000000..60a3e80cc6bc --- /dev/null +++ b/stubs/pywin32/win32/lib/regutil.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +CLSIDPyFile: str +RegistryIDPyFile: str +RegistryIDPycFile: str + +def BuildDefaultPythonKey(): ... +def GetRootKey(): ... +def GetRegistryDefaultValue(subkey, rootkey: Incomplete | None = ...): ... +def SetRegistryDefaultValue(subKey, value, rootkey: Incomplete | None = ...) -> None: ... +def GetAppPathsKey(): ... +def RegisterPythonExe(exeFullPath, exeAlias: Incomplete | None = ..., exeAppPath: Incomplete | None = ...) -> None: ... +def GetRegisteredExe(exeAlias): ... +def UnregisterPythonExe(exeAlias) -> None: ... +def RegisterNamedPath(name, path) -> None: ... +def UnregisterNamedPath(name) -> None: ... +def GetRegisteredNamedPath(name): ... +def RegisterModule(modName, modPath) -> None: ... +def UnregisterModule(modName) -> None: ... +def GetRegisteredHelpFile(helpDesc): ... +def RegisterHelpFile(helpFile, helpPath, helpDesc: Incomplete | None = ..., bCheckFile: int = ...) -> None: ... +def UnregisterHelpFile(helpFile, helpDesc: Incomplete | None = ...) -> None: ... +def RegisterCoreDLL(coredllName: Incomplete | None = ...) -> None: ... +def RegisterFileExtensions(defPyIcon, defPycIcon, runCommand) -> None: ... +def RegisterShellCommand(shellCommand, exeCommand, shellUserCommand: Incomplete | None = ...) -> None: ... +def RegisterDDECommand(shellCommand, ddeApp, ddeTopic, ddeCommand) -> None: ... diff --git a/stubs/pywin32/win32/lib/sspicon.pyi b/stubs/pywin32/win32/lib/sspicon.pyi new file mode 100644 index 000000000000..a09a88bc048a --- /dev/null +++ b/stubs/pywin32/win32/lib/sspicon.pyi @@ -0,0 +1,459 @@ +from typing import Final + +ISSP_LEVEL: Final = 32 +ISSP_MODE: Final = 1 + +def SEC_SUCCESS(Status: int) -> bool: ... + +SECPKG_FLAG_INTEGRITY: Final = 1 +SECPKG_FLAG_PRIVACY: Final = 2 +SECPKG_FLAG_TOKEN_ONLY: Final = 4 +SECPKG_FLAG_DATAGRAM: Final = 8 +SECPKG_FLAG_CONNECTION: Final = 16 +SECPKG_FLAG_MULTI_REQUIRED: Final = 32 +SECPKG_FLAG_CLIENT_ONLY: Final = 64 +SECPKG_FLAG_EXTENDED_ERROR: Final = 128 +SECPKG_FLAG_IMPERSONATION: Final = 256 +SECPKG_FLAG_ACCEPT_WIN32_NAME: Final = 512 +SECPKG_FLAG_STREAM: Final = 1024 +SECPKG_FLAG_NEGOTIABLE: Final = 2048 +SECPKG_FLAG_GSS_COMPATIBLE: Final = 4096 +SECPKG_FLAG_LOGON: Final = 8192 +SECPKG_FLAG_ASCII_BUFFERS: Final = 16384 +SECPKG_FLAG_FRAGMENT: Final = 32768 +SECPKG_FLAG_MUTUAL_AUTH: Final = 65536 +SECPKG_FLAG_DELEGATION: Final = 131072 +SECPKG_FLAG_READONLY_WITH_CHECKSUM: Final = 262144 +SECPKG_ID_NONE: Final = 65535 +SECBUFFER_VERSION: Final = 0 +SECBUFFER_EMPTY: Final = 0 +SECBUFFER_DATA: Final = 1 +SECBUFFER_TOKEN: Final = 2 +SECBUFFER_PKG_PARAMS: Final = 3 +SECBUFFER_MISSING: Final = 4 +SECBUFFER_EXTRA: Final = 5 +SECBUFFER_STREAM_TRAILER: Final = 6 +SECBUFFER_STREAM_HEADER: Final = 7 +SECBUFFER_NEGOTIATION_INFO: Final = 8 +SECBUFFER_PADDING: Final = 9 +SECBUFFER_STREAM: Final = 10 +SECBUFFER_MECHLIST: Final = 11 +SECBUFFER_MECHLIST_SIGNATURE: Final = 12 +SECBUFFER_TARGET: Final = 13 +SECBUFFER_CHANNEL_BINDINGS: Final = 14 +SECBUFFER_ATTRMASK: Final = -268435456 +SECBUFFER_READONLY: Final = -2147483648 +SECBUFFER_READONLY_WITH_CHECKSUM: Final = 268435456 +SECBUFFER_RESERVED: Final = 1610612736 +SECURITY_NATIVE_DREP: Final = 16 +SECURITY_NETWORK_DREP: Final = 0 +SECPKG_CRED_INBOUND: Final = 1 +SECPKG_CRED_OUTBOUND: Final = 2 +SECPKG_CRED_BOTH: Final = 3 +SECPKG_CRED_DEFAULT: Final = 4 +SECPKG_CRED_RESERVED: Final = -268435456 +ISC_REQ_DELEGATE: Final = 1 +ISC_REQ_MUTUAL_AUTH: Final = 2 +ISC_REQ_REPLAY_DETECT: Final = 4 +ISC_REQ_SEQUENCE_DETECT: Final = 8 +ISC_REQ_CONFIDENTIALITY: Final = 16 +ISC_REQ_USE_SESSION_KEY: Final = 32 +ISC_REQ_PROMPT_FOR_CREDS: Final = 64 +ISC_REQ_USE_SUPPLIED_CREDS: Final = 128 +ISC_REQ_ALLOCATE_MEMORY: Final = 256 +ISC_REQ_USE_DCE_STYLE: Final = 512 +ISC_REQ_DATAGRAM: Final = 1024 +ISC_REQ_CONNECTION: Final = 2048 +ISC_REQ_CALL_LEVEL: Final = 4096 +ISC_REQ_FRAGMENT_SUPPLIED: Final = 8192 +ISC_REQ_EXTENDED_ERROR: Final = 16384 +ISC_REQ_STREAM: Final = 32768 +ISC_REQ_INTEGRITY: Final = 65536 +ISC_REQ_IDENTIFY: Final = 131072 +ISC_REQ_NULL_SESSION: Final = 262144 +ISC_REQ_MANUAL_CRED_VALIDATION: Final = 524288 +ISC_REQ_RESERVED1: Final = 1048576 +ISC_REQ_FRAGMENT_TO_FIT: Final = 2097152 +ISC_REQ_HTTP: Final = 0x10000000 +ISC_RET_DELEGATE: Final = 1 +ISC_RET_MUTUAL_AUTH: Final = 2 +ISC_RET_REPLAY_DETECT: Final = 4 +ISC_RET_SEQUENCE_DETECT: Final = 8 +ISC_RET_CONFIDENTIALITY: Final = 16 +ISC_RET_USE_SESSION_KEY: Final = 32 +ISC_RET_USED_COLLECTED_CREDS: Final = 64 +ISC_RET_USED_SUPPLIED_CREDS: Final = 128 +ISC_RET_ALLOCATED_MEMORY: Final = 256 +ISC_RET_USED_DCE_STYLE: Final = 512 +ISC_RET_DATAGRAM: Final = 1024 +ISC_RET_CONNECTION: Final = 2048 +ISC_RET_INTERMEDIATE_RETURN: Final = 4096 +ISC_RET_CALL_LEVEL: Final = 8192 +ISC_RET_EXTENDED_ERROR: Final = 16384 +ISC_RET_STREAM: Final = 32768 +ISC_RET_INTEGRITY: Final = 65536 +ISC_RET_IDENTIFY: Final = 131072 +ISC_RET_NULL_SESSION: Final = 262144 +ISC_RET_MANUAL_CRED_VALIDATION: Final = 524288 +ISC_RET_RESERVED1: Final = 1048576 +ISC_RET_FRAGMENT_ONLY: Final = 2097152 +ASC_REQ_DELEGATE: Final = 1 +ASC_REQ_MUTUAL_AUTH: Final = 2 +ASC_REQ_REPLAY_DETECT: Final = 4 +ASC_REQ_SEQUENCE_DETECT: Final = 8 +ASC_REQ_CONFIDENTIALITY: Final = 16 +ASC_REQ_USE_SESSION_KEY: Final = 32 +ASC_REQ_ALLOCATE_MEMORY: Final = 256 +ASC_REQ_USE_DCE_STYLE: Final = 512 +ASC_REQ_DATAGRAM: Final = 1024 +ASC_REQ_CONNECTION: Final = 2048 +ASC_REQ_CALL_LEVEL: Final = 4096 +ASC_REQ_EXTENDED_ERROR: Final = 32768 +ASC_REQ_STREAM: Final = 65536 +ASC_REQ_INTEGRITY: Final = 131072 +ASC_REQ_LICENSING: Final = 262144 +ASC_REQ_IDENTIFY: Final = 524288 +ASC_REQ_ALLOW_NULL_SESSION: Final = 1048576 +ASC_REQ_ALLOW_NON_USER_LOGONS: Final = 2097152 +ASC_REQ_ALLOW_CONTEXT_REPLAY: Final = 4194304 +ASC_REQ_FRAGMENT_TO_FIT: Final = 8388608 +ASC_REQ_FRAGMENT_SUPPLIED: Final = 8192 +ASC_REQ_NO_TOKEN: Final = 16777216 +ASC_RET_DELEGATE: Final = 1 +ASC_RET_MUTUAL_AUTH: Final = 2 +ASC_RET_REPLAY_DETECT: Final = 4 +ASC_RET_SEQUENCE_DETECT: Final = 8 +ASC_RET_CONFIDENTIALITY: Final = 16 +ASC_RET_USE_SESSION_KEY: Final = 32 +ASC_RET_ALLOCATED_MEMORY: Final = 256 +ASC_RET_USED_DCE_STYLE: Final = 512 +ASC_RET_DATAGRAM: Final = 1024 +ASC_RET_CONNECTION: Final = 2048 +ASC_RET_CALL_LEVEL: Final = 8192 +ASC_RET_THIRD_LEG_FAILED: Final = 16384 +ASC_RET_EXTENDED_ERROR: Final = 32768 +ASC_RET_STREAM: Final = 65536 +ASC_RET_INTEGRITY: Final = 131072 +ASC_RET_LICENSING: Final = 262144 +ASC_RET_IDENTIFY: Final = 524288 +ASC_RET_NULL_SESSION: Final = 1048576 +ASC_RET_ALLOW_NON_USER_LOGONS: Final = 2097152 +ASC_RET_ALLOW_CONTEXT_REPLAY: Final = 4194304 +ASC_RET_FRAGMENT_ONLY: Final = 8388608 +SECPKG_CRED_ATTR_NAMES: Final = 1 +SECPKG_ATTR_SIZES: Final = 0 +SECPKG_ATTR_NAMES: Final = 1 +SECPKG_ATTR_LIFESPAN: Final = 2 +SECPKG_ATTR_DCE_INFO: Final = 3 +SECPKG_ATTR_STREAM_SIZES: Final = 4 +SECPKG_ATTR_KEY_INFO: Final = 5 +SECPKG_ATTR_AUTHORITY: Final = 6 +SECPKG_ATTR_PROTO_INFO: Final = 7 +SECPKG_ATTR_PASSWORD_EXPIRY: Final = 8 +SECPKG_ATTR_SESSION_KEY: Final = 9 +SECPKG_ATTR_PACKAGE_INFO: Final = 10 +SECPKG_ATTR_USER_FLAGS: Final = 11 +SECPKG_ATTR_NEGOTIATION_INFO: Final = 12 +SECPKG_ATTR_NATIVE_NAMES: Final = 13 +SECPKG_ATTR_FLAGS: Final = 14 +SECPKG_ATTR_USE_VALIDATED: Final = 15 +SECPKG_ATTR_CREDENTIAL_NAME: Final = 16 +SECPKG_ATTR_TARGET_INFORMATION: Final = 17 +SECPKG_ATTR_ACCESS_TOKEN: Final = 18 +SECPKG_ATTR_TARGET: Final = 19 +SECPKG_ATTR_AUTHENTICATION_ID: Final = 20 +SECPKG_ATTR_REMOTE_CERT_CONTEXT: Final = 83 +SECPKG_ATTR_LOCAL_CERT_CONTEXT: Final = 84 +SECPKG_ATTR_ROOT_STORE: Final = 85 +SECPKG_ATTR_SUPPORTED_ALGS: Final = 86 +SECPKG_ATTR_CIPHER_STRENGTHS: Final = 87 +SECPKG_ATTR_SUPPORTED_PROTOCOLS: Final = 88 +SECPKG_ATTR_ISSUER_LIST_EX: Final = 89 +SECPKG_ATTR_CONNECTION_INFO: Final = 90 +SECPKG_ATTR_EAP_KEY_BLOCK: Final = 91 +SECPKG_ATTR_MAPPED_CRED_ATTR: Final = 92 +SECPKG_ATTR_SESSION_INFO: Final = 93 +SECPKG_ATTR_APP_DATA: Final = 94 +SECPKG_NEGOTIATION_COMPLETE: Final = 0 +SECPKG_NEGOTIATION_OPTIMISTIC: Final = 1 +SECPKG_NEGOTIATION_IN_PROGRESS: Final = 2 +SECPKG_NEGOTIATION_DIRECT: Final = 3 +SECPKG_NEGOTIATION_TRY_MULTICRED: Final = 4 +SECPKG_CONTEXT_EXPORT_RESET_NEW: Final = 1 +SECPKG_CONTEXT_EXPORT_DELETE_OLD: Final = 2 +SECQOP_WRAP_NO_ENCRYPT: Final = -2147483647 +SECURITY_ENTRYPOINT_ANSIW: Final = "InitSecurityInterfaceW" +SECURITY_ENTRYPOINT_ANSIA: Final = "InitSecurityInterfaceA" +SECURITY_ENTRYPOINT16: Final = "INITSECURITYINTERFACEA" +SECURITY_ENTRYPOINT: Final = SECURITY_ENTRYPOINT16 +SECURITY_ENTRYPOINT_ANSI: Final = SECURITY_ENTRYPOINT16 +SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION: Final = 1 +SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_2: Final = 2 +SASL_OPTION_SEND_SIZE: Final = 1 +SASL_OPTION_RECV_SIZE: Final = 2 +SASL_OPTION_AUTHZ_STRING: Final = 3 +SASL_OPTION_AUTHZ_PROCESSING: Final = 4 +SEC_WINNT_AUTH_IDENTITY_ANSI: Final = 1 +SEC_WINNT_AUTH_IDENTITY_UNICODE: Final = 2 +SEC_WINNT_AUTH_IDENTITY_VERSION: Final = 512 +SEC_WINNT_AUTH_IDENTITY_MARSHALLED: Final = 4 +SEC_WINNT_AUTH_IDENTITY_ONLY: Final = 8 +SECPKG_OPTIONS_TYPE_UNKNOWN: Final = 0 +SECPKG_OPTIONS_TYPE_LSA: Final = 1 +SECPKG_OPTIONS_TYPE_SSPI: Final = 2 +SECPKG_OPTIONS_PERMANENT: Final = 1 +SEC_E_INSUFFICIENT_MEMORY: Final = -2146893056 +SEC_E_INVALID_HANDLE: Final = -2146893055 +SEC_E_UNSUPPORTED_FUNCTION: Final = -2146893054 +SEC_E_TARGET_UNKNOWN: Final = -2146893053 +SEC_E_INTERNAL_ERROR: Final = -2146893052 +SEC_E_SECPKG_NOT_FOUND: Final = -2146893051 +SEC_E_NOT_OWNER: Final = -2146893050 +SEC_E_CANNOT_INSTALL: Final = -2146893049 +SEC_E_INVALID_TOKEN: Final = -2146893048 +SEC_E_CANNOT_PACK: Final = -2146893047 +SEC_E_QOP_NOT_SUPPORTED: Final = -2146893046 +SEC_E_NO_IMPERSONATION: Final = -2146893045 +SEC_E_LOGON_DENIED: Final = -2146893044 +SEC_E_UNKNOWN_CREDENTIALS: Final = -2146893043 +SEC_E_NO_CREDENTIALS: Final = -2146893042 +SEC_E_MESSAGE_ALTERED: Final = -2146893041 +SEC_E_OUT_OF_SEQUENCE: Final = -2146893040 +SEC_E_NO_AUTHENTICATING_AUTHORITY: Final = -2146893039 +SEC_I_CONTINUE_NEEDED: Final = 590610 +SEC_I_COMPLETE_NEEDED: Final = 590611 +SEC_I_COMPLETE_AND_CONTINUE: Final = 590612 +SEC_I_LOCAL_LOGON: Final = 590613 +SEC_E_BAD_PKGID: Final = -2146893034 +SEC_E_CONTEXT_EXPIRED: Final = -2146893033 +SEC_I_CONTEXT_EXPIRED: Final = 590615 +SEC_E_INCOMPLETE_MESSAGE: Final = -2146893032 +SEC_E_INCOMPLETE_CREDENTIALS: Final = -2146893024 +SEC_E_BUFFER_TOO_SMALL: Final = -2146893023 +SEC_I_INCOMPLETE_CREDENTIALS: Final = 590624 +SEC_I_RENEGOTIATE: Final = 590625 +SEC_E_WRONG_PRINCIPAL: Final = -2146893022 +SEC_I_NO_LSA_CONTEXT: Final = 590627 +SEC_E_TIME_SKEW: Final = -2146893020 +SEC_E_UNTRUSTED_ROOT: Final = -2146893019 +SEC_E_ILLEGAL_MESSAGE: Final = -2146893018 +SEC_E_CERT_UNKNOWN: Final = -2146893017 +SEC_E_CERT_EXPIRED: Final = -2146893016 +SEC_E_ENCRYPT_FAILURE: Final = -2146893015 +SEC_E_DECRYPT_FAILURE: Final = -2146893008 +SEC_E_ALGORITHM_MISMATCH: Final = -2146893007 +SEC_E_SECURITY_QOS_FAILED: Final = -2146893006 +SEC_E_UNFINISHED_CONTEXT_DELETED: Final = -2146893005 +SEC_E_NO_TGT_REPLY: Final = -2146893004 +SEC_E_NO_IP_ADDRESSES: Final = -2146893003 +SEC_E_WRONG_CREDENTIAL_HANDLE: Final = -2146893002 +SEC_E_CRYPTO_SYSTEM_INVALID: Final = -2146893001 +SEC_E_MAX_REFERRALS_EXCEEDED: Final = -2146893000 +SEC_E_MUST_BE_KDC: Final = -2146892999 +SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: Final = -2146892998 +SEC_E_TOO_MANY_PRINCIPALS: Final = -2146892997 +SEC_E_NO_PA_DATA: Final = -2146892996 +SEC_E_PKINIT_NAME_MISMATCH: Final = -2146892995 +SEC_E_SMARTCARD_LOGON_REQUIRED: Final = -2146892994 +SEC_E_SHUTDOWN_IN_PROGRESS: Final = -2146892993 +SEC_E_KDC_INVALID_REQUEST: Final = -2146892992 +SEC_E_KDC_UNABLE_TO_REFER: Final = -2146892991 +SEC_E_KDC_UNKNOWN_ETYPE: Final = -2146892990 +SEC_E_UNSUPPORTED_PREAUTH: Final = -2146892989 +SEC_E_DELEGATION_REQUIRED: Final = -2146892987 +SEC_E_BAD_BINDINGS: Final = -2146892986 +SEC_E_MULTIPLE_ACCOUNTS: Final = -2146892985 +SEC_E_NO_KERB_KEY: Final = -2146892984 +ERROR_IPSEC_QM_POLICY_EXISTS: Final = 13000 +ERROR_IPSEC_QM_POLICY_NOT_FOUND: Final = 13001 +ERROR_IPSEC_QM_POLICY_IN_USE: Final = 13002 +ERROR_IPSEC_MM_POLICY_EXISTS: Final = 13003 +ERROR_IPSEC_MM_POLICY_NOT_FOUND: Final = 13004 +ERROR_IPSEC_MM_POLICY_IN_USE: Final = 13005 +ERROR_IPSEC_MM_FILTER_EXISTS: Final = 13006 +ERROR_IPSEC_MM_FILTER_NOT_FOUND: Final = 13007 +ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: Final = 13008 +ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: Final = 13009 +ERROR_IPSEC_MM_AUTH_EXISTS: Final = 13010 +ERROR_IPSEC_MM_AUTH_NOT_FOUND: Final = 13011 +ERROR_IPSEC_MM_AUTH_IN_USE: Final = 13012 +ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: Final = 13013 +ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: Final = 13014 +ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: Final = 13015 +ERROR_IPSEC_TUNNEL_FILTER_EXISTS: Final = 13016 +ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: Final = 13017 +ERROR_IPSEC_MM_FILTER_PENDING_DELETION: Final = 13018 +ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: Final = 13019 +ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: Final = 13020 +ERROR_IPSEC_MM_POLICY_PENDING_DELETION: Final = 13021 +ERROR_IPSEC_MM_AUTH_PENDING_DELETION: Final = 13022 +ERROR_IPSEC_QM_POLICY_PENDING_DELETION: Final = 13023 +WARNING_IPSEC_MM_POLICY_PRUNED: Final = 13024 +WARNING_IPSEC_QM_POLICY_PRUNED: Final = 13025 +ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: Final = 13800 +ERROR_IPSEC_IKE_AUTH_FAIL: Final = 13801 +ERROR_IPSEC_IKE_ATTRIB_FAIL: Final = 13802 +ERROR_IPSEC_IKE_NEGOTIATION_PENDING: Final = 13803 +ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: Final = 13804 +ERROR_IPSEC_IKE_TIMED_OUT: Final = 13805 +ERROR_IPSEC_IKE_NO_CERT: Final = 13806 +ERROR_IPSEC_IKE_SA_DELETED: Final = 13807 +ERROR_IPSEC_IKE_SA_REAPED: Final = 13808 +ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: Final = 13809 +ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: Final = 13810 +ERROR_IPSEC_IKE_QUEUE_DROP_MM: Final = 13811 +ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: Final = 13812 +ERROR_IPSEC_IKE_DROP_NO_RESPONSE: Final = 13813 +ERROR_IPSEC_IKE_MM_DELAY_DROP: Final = 13814 +ERROR_IPSEC_IKE_QM_DELAY_DROP: Final = 13815 +ERROR_IPSEC_IKE_ERROR: Final = 13816 +ERROR_IPSEC_IKE_CRL_FAILED: Final = 13817 +ERROR_IPSEC_IKE_INVALID_KEY_USAGE: Final = 13818 +ERROR_IPSEC_IKE_INVALID_CERT_TYPE: Final = 13819 +ERROR_IPSEC_IKE_NO_PRIVATE_KEY: Final = 13820 +ERROR_IPSEC_IKE_DH_FAIL: Final = 13822 +ERROR_IPSEC_IKE_INVALID_HEADER: Final = 13824 +ERROR_IPSEC_IKE_NO_POLICY: Final = 13825 +ERROR_IPSEC_IKE_INVALID_SIGNATURE: Final = 13826 +ERROR_IPSEC_IKE_KERBEROS_ERROR: Final = 13827 +ERROR_IPSEC_IKE_NO_PUBLIC_KEY: Final = 13828 +ERROR_IPSEC_IKE_PROCESS_ERR: Final = 13829 +ERROR_IPSEC_IKE_PROCESS_ERR_SA: Final = 13830 +ERROR_IPSEC_IKE_PROCESS_ERR_PROP: Final = 13831 +ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: Final = 13832 +ERROR_IPSEC_IKE_PROCESS_ERR_KE: Final = 13833 +ERROR_IPSEC_IKE_PROCESS_ERR_ID: Final = 13834 +ERROR_IPSEC_IKE_PROCESS_ERR_CERT: Final = 13835 +ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: Final = 13836 +ERROR_IPSEC_IKE_PROCESS_ERR_HASH: Final = 13837 +ERROR_IPSEC_IKE_PROCESS_ERR_SIG: Final = 13838 +ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: Final = 13839 +ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: Final = 13840 +ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: Final = 13841 +ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: Final = 13842 +ERROR_IPSEC_IKE_INVALID_PAYLOAD: Final = 13843 +ERROR_IPSEC_IKE_LOAD_SOFT_SA: Final = 13844 +ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: Final = 13845 +ERROR_IPSEC_IKE_INVALID_COOKIE: Final = 13846 +ERROR_IPSEC_IKE_NO_PEER_CERT: Final = 13847 +ERROR_IPSEC_IKE_PEER_CRL_FAILED: Final = 13848 +ERROR_IPSEC_IKE_POLICY_CHANGE: Final = 13849 +ERROR_IPSEC_IKE_NO_MM_POLICY: Final = 13850 +ERROR_IPSEC_IKE_NOTCBPRIV: Final = 13851 +ERROR_IPSEC_IKE_SECLOADFAIL: Final = 13852 +ERROR_IPSEC_IKE_FAILSSPINIT: Final = 13853 +ERROR_IPSEC_IKE_FAILQUERYSSP: Final = 13854 +ERROR_IPSEC_IKE_SRVACQFAIL: Final = 13855 +ERROR_IPSEC_IKE_SRVQUERYCRED: Final = 13856 +ERROR_IPSEC_IKE_GETSPIFAIL: Final = 13857 +ERROR_IPSEC_IKE_INVALID_FILTER: Final = 13858 +ERROR_IPSEC_IKE_OUT_OF_MEMORY: Final = 13859 +ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: Final = 13860 +ERROR_IPSEC_IKE_INVALID_POLICY: Final = 13861 +ERROR_IPSEC_IKE_UNKNOWN_DOI: Final = 13862 +ERROR_IPSEC_IKE_INVALID_SITUATION: Final = 13863 +ERROR_IPSEC_IKE_DH_FAILURE: Final = 13864 +ERROR_IPSEC_IKE_INVALID_GROUP: Final = 13865 +ERROR_IPSEC_IKE_ENCRYPT: Final = 13866 +ERROR_IPSEC_IKE_DECRYPT: Final = 13867 +ERROR_IPSEC_IKE_POLICY_MATCH: Final = 13868 +ERROR_IPSEC_IKE_UNSUPPORTED_ID: Final = 13869 +ERROR_IPSEC_IKE_INVALID_HASH: Final = 13870 +ERROR_IPSEC_IKE_INVALID_HASH_ALG: Final = 13871 +ERROR_IPSEC_IKE_INVALID_HASH_SIZE: Final = 13872 +ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: Final = 13873 +ERROR_IPSEC_IKE_INVALID_AUTH_ALG: Final = 13874 +ERROR_IPSEC_IKE_INVALID_SIG: Final = 13875 +ERROR_IPSEC_IKE_LOAD_FAILED: Final = 13876 +ERROR_IPSEC_IKE_RPC_DELETE: Final = 13877 +ERROR_IPSEC_IKE_BENIGN_REINIT: Final = 13878 +ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: Final = 13879 +ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: Final = 13881 +ERROR_IPSEC_IKE_MM_LIMIT: Final = 13882 +ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: Final = 13883 +ERROR_IPSEC_IKE_NEG_STATUS_END: Final = 13884 +CRYPT_E_MSG_ERROR: Final = -2146889727 +CRYPT_E_UNKNOWN_ALGO: Final = -2146889726 +CRYPT_E_OID_FORMAT: Final = -2146889725 +CRYPT_E_INVALID_MSG_TYPE: Final = -2146889724 +CRYPT_E_UNEXPECTED_ENCODING: Final = -2146889723 +CRYPT_E_AUTH_ATTR_MISSING: Final = -2146889722 +CRYPT_E_HASH_VALUE: Final = -2146889721 +CRYPT_E_INVALID_INDEX: Final = -2146889720 +CRYPT_E_ALREADY_DECRYPTED: Final = -2146889719 +CRYPT_E_NOT_DECRYPTED: Final = -2146889718 +CRYPT_E_RECIPIENT_NOT_FOUND: Final = -2146889717 +CRYPT_E_CONTROL_TYPE: Final = -2146889716 +CRYPT_E_ISSUER_SERIALNUMBER: Final = -2146889715 +CRYPT_E_SIGNER_NOT_FOUND: Final = -2146889714 +CRYPT_E_ATTRIBUTES_MISSING: Final = -2146889713 +CRYPT_E_STREAM_MSG_NOT_READY: Final = -2146889712 +CRYPT_E_STREAM_INSUFFICIENT_DATA: Final = -2146889711 +CRYPT_I_NEW_PROTECTION_REQUIRED: Final = 593938 +CRYPT_E_BAD_LEN: Final = -2146885631 +CRYPT_E_BAD_ENCODE: Final = -2146885630 +CRYPT_E_FILE_ERROR: Final = -2146885629 +CRYPT_E_NOT_FOUND: Final = -2146885628 +CRYPT_E_EXISTS: Final = -2146885627 +CRYPT_E_NO_PROVIDER: Final = -2146885626 +CRYPT_E_SELF_SIGNED: Final = -2146885625 +CRYPT_E_DELETED_PREV: Final = -2146885624 +CRYPT_E_NO_MATCH: Final = -2146885623 +CRYPT_E_UNEXPECTED_MSG_TYPE: Final = -2146885622 +CRYPT_E_NO_KEY_PROPERTY: Final = -2146885621 +CRYPT_E_NO_DECRYPT_CERT: Final = -2146885620 +CRYPT_E_BAD_MSG: Final = -2146885619 +CRYPT_E_NO_SIGNER: Final = -2146885618 +CRYPT_E_PENDING_CLOSE: Final = -2146885617 +CRYPT_E_REVOKED: Final = -2146885616 +CRYPT_E_NO_REVOCATION_DLL: Final = -2146885615 +CRYPT_E_NO_REVOCATION_CHECK: Final = -2146885614 +CRYPT_E_REVOCATION_OFFLINE: Final = -2146885613 +CRYPT_E_NOT_IN_REVOCATION_DATABASE: Final = -2146885612 +CRYPT_E_INVALID_NUMERIC_STRING: Final = -2146885600 +CRYPT_E_INVALID_PRINTABLE_STRING: Final = -2146885599 +CRYPT_E_INVALID_IA5_STRING: Final = -2146885598 +CRYPT_E_INVALID_X500_STRING: Final = -2146885597 +CRYPT_E_NOT_CHAR_STRING: Final = -2146885596 +CRYPT_E_FILERESIZED: Final = -2146885595 +CRYPT_E_SECURITY_SETTINGS: Final = -2146885594 +CRYPT_E_NO_VERIFY_USAGE_DLL: Final = -2146885593 +CRYPT_E_NO_VERIFY_USAGE_CHECK: Final = -2146885592 +CRYPT_E_VERIFY_USAGE_OFFLINE: Final = -2146885591 +CRYPT_E_NOT_IN_CTL: Final = -2146885590 +CRYPT_E_NO_TRUSTED_SIGNER: Final = -2146885589 +CRYPT_E_MISSING_PUBKEY_PARA: Final = -2146885588 +CRYPT_E_OSS_ERROR: Final = -2146881536 +KerbDebugRequestMessage: Final = 0 +KerbQueryTicketCacheMessage: Final = 1 +KerbChangeMachinePasswordMessage: Final = 2 +KerbVerifyPacMessage: Final = 3 +KerbRetrieveTicketMessage: Final = 4 +KerbUpdateAddressesMessage: Final = 5 +KerbPurgeTicketCacheMessage: Final = 6 +KerbChangePasswordMessage: Final = 7 +KerbRetrieveEncodedTicketMessage: Final = 8 +KerbDecryptDataMessage: Final = 9 +KerbAddBindingCacheEntryMessage: Final = 10 +KerbSetPasswordMessage: Final = 11 +KerbSetPasswordExMessage: Final = 12 +KerbVerifyCredentialsMessage: Final = 13 +KerbQueryTicketCacheExMessage: Final = 14 +KerbPurgeTicketCacheExMessage: Final = 15 +KerbRefreshSmartcardCredentialsMessage: Final = 16 +KerbAddExtraCredentialsMessage: Final = 17 +KerbQuerySupplementalCredentialsMessage: Final = 18 +MsV1_0Lm20ChallengeRequest: Final = 0 +MsV1_0Lm20GetChallengeResponse: Final = 1 +MsV1_0EnumerateUsers: Final = 2 +MsV1_0GetUserInfo: Final = 3 +MsV1_0ReLogonUsers: Final = 4 +MsV1_0ChangePassword: Final = 5 +MsV1_0ChangeCachedPassword: Final = 6 +MsV1_0GenericPassthrough: Final = 7 +MsV1_0CacheLogon: Final = 8 +MsV1_0SubAuth: Final = 9 +MsV1_0DeriveCredential: Final = 10 +MsV1_0CacheLookup: Final = 11 +MsV1_0SetProcessOption: Final = 12 +SEC_E_OK: Final = 0 diff --git a/stubs/pywin32/win32/lib/win2kras.pyi b/stubs/pywin32/win32/lib/win2kras.pyi new file mode 100644 index 000000000000..455d2763b253 --- /dev/null +++ b/stubs/pywin32/win32/lib/win2kras.pyi @@ -0,0 +1 @@ +from win32.win32ras import * diff --git a/stubs/pywin32/win32/lib/win32con.pyi b/stubs/pywin32/win32/lib/win32con.pyi new file mode 100644 index 000000000000..1322355791df --- /dev/null +++ b/stubs/pywin32/win32/lib/win32con.pyi @@ -0,0 +1,4910 @@ +from typing import Final + +WINVER: Final = 1280 +WM_USER: Final = 1024 +PY_0U: Final = 0 +OFN_READONLY: Final = 1 +OFN_OVERWRITEPROMPT: Final = 2 +OFN_HIDEREADONLY: Final = 4 +OFN_NOCHANGEDIR: Final = 8 +OFN_SHOWHELP: Final = 16 +OFN_ENABLEHOOK: Final = 32 +OFN_ENABLETEMPLATE: Final = 64 +OFN_ENABLETEMPLATEHANDLE: Final = 128 +OFN_NOVALIDATE: Final = 256 +OFN_ALLOWMULTISELECT: Final = 512 +OFN_EXTENSIONDIFFERENT: Final = 1024 +OFN_PATHMUSTEXIST: Final = 2048 +OFN_FILEMUSTEXIST: Final = 4096 +OFN_CREATEPROMPT: Final = 8192 +OFN_SHAREAWARE: Final = 16384 +OFN_NOREADONLYRETURN: Final = 32768 +OFN_NOTESTFILECREATE: Final = 65536 +OFN_NONETWORKBUTTON: Final = 131072 +OFN_NOLONGNAMES: Final = 262144 +OFN_EXPLORER: Final = 524288 +OFN_NODEREFERENCELINKS: Final = 1048576 +OFN_LONGNAMES: Final = 2097152 +OFN_ENABLEINCLUDENOTIFY: Final = 4194304 +OFN_ENABLESIZING: Final = 8388608 +OFN_DONTADDTORECENT: Final = 33554432 +OFN_FORCESHOWHIDDEN: Final = 268435456 +OFN_EX_NOPLACESBAR: Final = 1 +OFN_SHAREFALLTHROUGH: Final = 2 +OFN_SHARENOWARN: Final = 1 +OFN_SHAREWARN: Final = 0 +CDN_FIRST: Final[int] +CDN_LAST: Final[int] +CDN_INITDONE: Final[int] +CDN_SELCHANGE: Final[int] +CDN_FOLDERCHANGE: Final[int] +CDN_SHAREVIOLATION: Final[int] +CDN_HELP: Final[int] +CDN_FILEOK: Final[int] +CDN_TYPECHANGE: Final[int] +CDN_INCLUDEITEM: Final[int] +CDM_FIRST: Final[int] +CDM_LAST: Final[int] +CDM_GETSPEC: Final[int] +CDM_GETFILEPATH: Final[int] +CDM_GETFOLDERPATH: Final[int] +CDM_GETFOLDERIDLIST: Final[int] +CDM_SETCONTROLTEXT: Final[int] +CDM_HIDECONTROL: Final[int] +CDM_SETDEFEXT: Final[int] +CC_RGBINIT: Final = 1 +CC_FULLOPEN: Final = 2 +CC_PREVENTFULLOPEN: Final = 4 +CC_SHOWHELP: Final = 8 +CC_ENABLEHOOK: Final = 16 +CC_ENABLETEMPLATE: Final = 32 +CC_ENABLETEMPLATEHANDLE: Final = 64 +CC_SOLIDCOLOR: Final = 128 +CC_ANYCOLOR: Final = 256 +FR_DOWN: Final = 1 +FR_WHOLEWORD: Final = 2 +FR_MATCHCASE: Final = 4 +FR_FINDNEXT: Final = 8 +FR_REPLACE: Final = 16 +FR_REPLACEALL: Final = 32 +FR_DIALOGTERM: Final = 64 +FR_SHOWHELP: Final = 128 +FR_ENABLEHOOK: Final = 256 +FR_ENABLETEMPLATE: Final = 512 +FR_NOUPDOWN: Final = 1024 +FR_NOMATCHCASE: Final = 2048 +FR_NOWHOLEWORD: Final = 4096 +FR_ENABLETEMPLATEHANDLE: Final = 8192 +FR_HIDEUPDOWN: Final = 16384 +FR_HIDEMATCHCASE: Final = 32768 +FR_HIDEWHOLEWORD: Final = 65536 +CF_SCREENFONTS: Final = 1 +CF_PRINTERFONTS: Final = 2 +CF_BOTH: Final[int] +CF_SHOWHELP: Final = 4 +CF_ENABLEHOOK: Final = 8 +CF_ENABLETEMPLATE: Final = 16 +CF_ENABLETEMPLATEHANDLE: Final = 32 +CF_INITTOLOGFONTSTRUCT: Final = 64 +CF_USESTYLE: Final = 128 +CF_EFFECTS: Final = 256 +CF_APPLY: Final = 512 +CF_ANSIONLY: Final = 1024 +CF_SCRIPTSONLY: Final = CF_ANSIONLY +CF_NOVECTORFONTS: Final = 2048 +CF_NOOEMFONTS: Final = CF_NOVECTORFONTS +CF_NOSIMULATIONS: Final = 4096 +CF_LIMITSIZE: Final = 8192 +CF_FIXEDPITCHONLY: Final = 16384 +CF_WYSIWYG: Final = 32768 +CF_FORCEFONTEXIST: Final = 65536 +CF_SCALABLEONLY: Final = 131072 +CF_TTONLY: Final = 262144 +CF_NOFACESEL: Final = 524288 +CF_NOSTYLESEL: Final = 1048576 +CF_NOSIZESEL: Final = 2097152 +CF_SELECTSCRIPT: Final = 4194304 +CF_NOSCRIPTSEL: Final = 8388608 +CF_NOVERTFONTS: Final = 16777216 +SIMULATED_FONTTYPE: Final = 32768 +PRINTER_FONTTYPE: Final = 16384 +SCREEN_FONTTYPE: Final = 8192 +BOLD_FONTTYPE: Final = 256 +ITALIC_FONTTYPE: Final = 512 +REGULAR_FONTTYPE: Final = 1024 +OPENTYPE_FONTTYPE: Final = 65536 +TYPE1_FONTTYPE: Final = 131072 +DSIG_FONTTYPE: Final = 262144 +WM_CHOOSEFONT_GETLOGFONT: Final[int] +WM_CHOOSEFONT_SETLOGFONT: Final[int] +WM_CHOOSEFONT_SETFLAGS: Final[int] +LBSELCHSTRINGA: Final = "commdlg_LBSelChangedNotify" +SHAREVISTRINGA: Final = "commdlg_ShareViolation" +FILEOKSTRINGA: Final = "commdlg_FileNameOK" +COLOROKSTRINGA: Final = "commdlg_ColorOK" +SETRGBSTRINGA: Final = "commdlg_SetRGBColor" +HELPMSGSTRINGA: Final = "commdlg_help" +FINDMSGSTRINGA: Final = "commdlg_FindReplace" +LBSELCHSTRING: Final = LBSELCHSTRINGA +SHAREVISTRING: Final = SHAREVISTRINGA +FILEOKSTRING: Final = FILEOKSTRINGA +COLOROKSTRING: Final = COLOROKSTRINGA +SETRGBSTRING: Final = SETRGBSTRINGA +HELPMSGSTRING: Final = HELPMSGSTRINGA +FINDMSGSTRING: Final = FINDMSGSTRINGA +CD_LBSELNOITEMS: Final = -1 +CD_LBSELCHANGE: Final = 0 +CD_LBSELSUB: Final = 1 +CD_LBSELADD: Final = 2 +PD_ALLPAGES: Final = 0 +PD_SELECTION: Final = 1 +PD_PAGENUMS: Final = 2 +PD_NOSELECTION: Final = 4 +PD_NOPAGENUMS: Final = 8 +PD_COLLATE: Final = 16 +PD_PRINTTOFILE: Final = 32 +PD_PRINTSETUP: Final = 64 +PD_NOWARNING: Final = 128 +PD_RETURNDC: Final = 256 +PD_RETURNIC: Final = 512 +PD_RETURNDEFAULT: Final = 1024 +PD_SHOWHELP: Final = 2048 +PD_ENABLEPRINTHOOK: Final = 4096 +PD_ENABLESETUPHOOK: Final = 8192 +PD_ENABLEPRINTTEMPLATE: Final = 16384 +PD_ENABLESETUPTEMPLATE: Final = 32768 +PD_ENABLEPRINTTEMPLATEHANDLE: Final = 65536 +PD_ENABLESETUPTEMPLATEHANDLE: Final = 131072 +PD_USEDEVMODECOPIES: Final = 262144 +PD_DISABLEPRINTTOFILE: Final = 524288 +PD_HIDEPRINTTOFILE: Final = 1048576 +PD_NONETWORKBUTTON: Final = 2097152 +DN_DEFAULTPRN: Final = 1 +WM_PSD_PAGESETUPDLG: Final = WM_USER +WM_PSD_FULLPAGERECT: Final[int] +WM_PSD_MINMARGINRECT: Final[int] +WM_PSD_MARGINRECT: Final[int] +WM_PSD_GREEKTEXTRECT: Final[int] +WM_PSD_ENVSTAMPRECT: Final[int] +WM_PSD_YAFULLPAGERECT: Final[int] +PSD_DEFAULTMINMARGINS: Final = 0 +PSD_INWININIINTLMEASURE: Final = 0 +PSD_MINMARGINS: Final = 1 +PSD_MARGINS: Final = 2 +PSD_INTHOUSANDTHSOFINCHES: Final = 4 +PSD_INHUNDREDTHSOFMILLIMETERS: Final = 8 +PSD_DISABLEMARGINS: Final = 16 +PSD_DISABLEPRINTER: Final = 32 +PSD_NOWARNING: Final = 128 +PSD_DISABLEORIENTATION: Final = 256 +PSD_RETURNDEFAULT: Final = 1024 +PSD_DISABLEPAPER: Final = 512 +PSD_SHOWHELP: Final = 2048 +PSD_ENABLEPAGESETUPHOOK: Final = 8192 +PSD_ENABLEPAGESETUPTEMPLATE: Final = 32768 +PSD_ENABLEPAGESETUPTEMPLATEHANDLE: Final = 131072 +PSD_ENABLEPAGEPAINTHOOK: Final = 262144 +PSD_DISABLEPAGEPAINTING: Final = 524288 +PSD_NONETWORKBUTTON: Final = 2097152 + +HKEY_CLASSES_ROOT: Final = -2147483648 +HKEY_CURRENT_USER: Final = -2147483647 +HKEY_LOCAL_MACHINE: Final = -2147483646 +HKEY_USERS: Final = -2147483645 +HKEY_PERFORMANCE_DATA: Final = -2147483644 +HKEY_CURRENT_CONFIG: Final = -2147483643 +HKEY_DYN_DATA: Final = -2147483642 +HKEY_PERFORMANCE_TEXT: Final = -2147483568 +HKEY_PERFORMANCE_NLSTEXT: Final = -2147483552 + +HWND_BROADCAST: Final = 65535 +HWND_DESKTOP: Final = 0 +HWND_TOP: Final = 0 +HWND_BOTTOM: Final = 1 +HWND_TOPMOST: Final = -1 +HWND_NOTOPMOST: Final = -2 +HWND_MESSAGE: Final = -3 + +SM_CXSCREEN: Final = 0 +SM_CYSCREEN: Final = 1 +SM_CXVSCROLL: Final = 2 +SM_CYHSCROLL: Final = 3 +SM_CYCAPTION: Final = 4 +SM_CXBORDER: Final = 5 +SM_CYBORDER: Final = 6 +SM_CXDLGFRAME: Final = 7 +SM_CYDLGFRAME: Final = 8 +SM_CYVTHUMB: Final = 9 +SM_CXHTHUMB: Final = 10 +SM_CXICON: Final = 11 +SM_CYICON: Final = 12 +SM_CXCURSOR: Final = 13 +SM_CYCURSOR: Final = 14 +SM_CYMENU: Final = 15 +SM_CXFULLSCREEN: Final = 16 +SM_CYFULLSCREEN: Final = 17 +SM_CYKANJIWINDOW: Final = 18 +SM_MOUSEPRESENT: Final = 19 +SM_CYVSCROLL: Final = 20 +SM_CXHSCROLL: Final = 21 +SM_DEBUG: Final = 22 +SM_SWAPBUTTON: Final = 23 +SM_RESERVED1: Final = 24 +SM_RESERVED2: Final = 25 +SM_RESERVED3: Final = 26 +SM_RESERVED4: Final = 27 +SM_CXMIN: Final = 28 +SM_CYMIN: Final = 29 +SM_CXSIZE: Final = 30 +SM_CYSIZE: Final = 31 +SM_CXFRAME: Final = 32 +SM_CYFRAME: Final = 33 +SM_CXMINTRACK: Final = 34 +SM_CYMINTRACK: Final = 35 +SM_CXDOUBLECLK: Final = 36 +SM_CYDOUBLECLK: Final = 37 +SM_CXICONSPACING: Final = 38 +SM_CYICONSPACING: Final = 39 +SM_MENUDROPALIGNMENT: Final = 40 +SM_PENWINDOWS: Final = 41 +SM_DBCSENABLED: Final = 42 +SM_CMOUSEBUTTONS: Final = 43 +SM_CXFIXEDFRAME: Final = SM_CXDLGFRAME +SM_CYFIXEDFRAME: Final = SM_CYDLGFRAME +SM_CXSIZEFRAME: Final = SM_CXFRAME +SM_CYSIZEFRAME: Final = SM_CYFRAME +SM_SECURE: Final = 44 +SM_CXEDGE: Final = 45 +SM_CYEDGE: Final = 46 +SM_CXMINSPACING: Final = 47 +SM_CYMINSPACING: Final = 48 +SM_CXSMICON: Final = 49 +SM_CYSMICON: Final = 50 +SM_CYSMCAPTION: Final = 51 +SM_CXSMSIZE: Final = 52 +SM_CYSMSIZE: Final = 53 +SM_CXMENUSIZE: Final = 54 +SM_CYMENUSIZE: Final = 55 +SM_ARRANGE: Final = 56 +SM_CXMINIMIZED: Final = 57 +SM_CYMINIMIZED: Final = 58 +SM_CXMAXTRACK: Final = 59 +SM_CYMAXTRACK: Final = 60 +SM_CXMAXIMIZED: Final = 61 +SM_CYMAXIMIZED: Final = 62 +SM_NETWORK: Final = 63 +SM_CLEANBOOT: Final = 67 +SM_CXDRAG: Final = 68 +SM_CYDRAG: Final = 69 +SM_SHOWSOUNDS: Final = 70 +SM_CXMENUCHECK: Final = 71 +SM_CYMENUCHECK: Final = 72 +SM_SLOWMACHINE: Final = 73 +SM_MIDEASTENABLED: Final = 74 +SM_MOUSEWHEELPRESENT: Final = 75 +SM_XVIRTUALSCREEN: Final = 76 +SM_YVIRTUALSCREEN: Final = 77 +SM_CXVIRTUALSCREEN: Final = 78 +SM_CYVIRTUALSCREEN: Final = 79 +SM_CMONITORS: Final = 80 +SM_SAMEDISPLAYFORMAT: Final = 81 +SM_CMETRICS: Final = 83 +MNC_IGNORE: Final = 0 +MNC_CLOSE: Final = 1 +MNC_EXECUTE: Final = 2 +MNC_SELECT: Final = 3 +MNS_NOCHECK: Final = -2147483648 +MNS_MODELESS: Final = 1073741824 +MNS_DRAGDROP: Final = 536870912 +MNS_AUTODISMISS: Final = 268435456 +MNS_NOTIFYBYPOS: Final = 134217728 +MNS_CHECKORBMP: Final = 67108864 +MIM_MAXHEIGHT: Final = 1 +MIM_BACKGROUND: Final = 2 +MIM_HELPID: Final = 4 +MIM_MENUDATA: Final = 8 +MIM_STYLE: Final = 16 +MIM_APPLYTOSUBMENUS: Final = -2147483648 +MND_CONTINUE: Final = 0 +MND_ENDMENU: Final = 1 +MNGOF_GAP: Final = 3 +MNGO_NOINTERFACE: Final = 0 +MNGO_NOERROR: Final = 1 +MIIM_STATE: Final = 1 +MIIM_ID: Final = 2 +MIIM_SUBMENU: Final = 4 +MIIM_CHECKMARKS: Final = 8 +MIIM_TYPE: Final = 16 +MIIM_DATA: Final = 32 +MIIM_STRING: Final = 64 +MIIM_BITMAP: Final = 128 +MIIM_FTYPE: Final = 256 +HBMMENU_CALLBACK: Final = -1 +HBMMENU_SYSTEM: Final = 1 +HBMMENU_MBAR_RESTORE: Final = 2 +HBMMENU_MBAR_MINIMIZE: Final = 3 +HBMMENU_MBAR_CLOSE: Final = 5 +HBMMENU_MBAR_CLOSE_D: Final = 6 +HBMMENU_MBAR_MINIMIZE_D: Final = 7 +HBMMENU_POPUP_CLOSE: Final = 8 +HBMMENU_POPUP_RESTORE: Final = 9 +HBMMENU_POPUP_MAXIMIZE: Final = 10 +HBMMENU_POPUP_MINIMIZE: Final = 11 +GMDI_USEDISABLED: Final = 1 +GMDI_GOINTOPOPUPS: Final = 2 +TPM_LEFTBUTTON: Final = 0 +TPM_RIGHTBUTTON: Final = 2 +TPM_LEFTALIGN: Final = 0 +TPM_CENTERALIGN: Final = 4 +TPM_RIGHTALIGN: Final = 8 +TPM_TOPALIGN: Final = 0 +TPM_VCENTERALIGN: Final = 16 +TPM_BOTTOMALIGN: Final = 32 +TPM_HORIZONTAL: Final = 0 +TPM_VERTICAL: Final = 64 +TPM_NONOTIFY: Final = 128 +TPM_RETURNCMD: Final = 256 +TPM_RECURSE: Final = 1 +DOF_EXECUTABLE: Final = 32769 +DOF_DOCUMENT: Final = 32770 +DOF_DIRECTORY: Final = 32771 +DOF_MULTIPLE: Final = 32772 +DOF_PROGMAN: Final = 1 +DOF_SHELLDATA: Final = 2 +DO_DROPFILE: Final = 1162627398 +DO_PRINTFILE: Final = 1414419024 +DT_TOP: Final = 0 +DT_LEFT: Final = 0 +DT_CENTER: Final = 1 +DT_RIGHT: Final = 2 +DT_VCENTER: Final = 4 +DT_BOTTOM: Final = 8 +DT_WORDBREAK: Final = 16 +DT_SINGLELINE: Final = 32 +DT_EXPANDTABS: Final = 64 +DT_TABSTOP: Final = 128 +DT_NOCLIP: Final = 256 +DT_EXTERNALLEADING: Final = 512 +DT_CALCRECT: Final = 1024 +DT_NOPREFIX: Final = 2048 +DT_INTERNAL: Final = 4096 +DT_EDITCONTROL: Final = 8192 +DT_PATH_ELLIPSIS: Final = 16384 +DT_END_ELLIPSIS: Final = 32768 +DT_MODIFYSTRING: Final = 65536 +DT_RTLREADING: Final = 131072 +DT_WORD_ELLIPSIS: Final = 262144 +DST_COMPLEX: Final = 0 +DST_TEXT: Final = 1 +DST_PREFIXTEXT: Final = 2 +DST_ICON: Final = 3 +DST_BITMAP: Final = 4 +DSS_NORMAL: Final = 0 +DSS_UNION: Final = 16 +DSS_DISABLED: Final = 32 +DSS_MONO: Final = 128 +DSS_RIGHT: Final = 32768 +DCX_WINDOW: Final = 1 +DCX_CACHE: Final = 2 +DCX_NORESETATTRS: Final = 4 +DCX_CLIPCHILDREN: Final = 8 +DCX_CLIPSIBLINGS: Final = 16 +DCX_PARENTCLIP: Final = 32 +DCX_EXCLUDERGN: Final = 64 +DCX_INTERSECTRGN: Final = 128 +DCX_EXCLUDEUPDATE: Final = 256 +DCX_INTERSECTUPDATE: Final = 512 +DCX_LOCKWINDOWUPDATE: Final = 1024 +DCX_VALIDATE: Final = 2097152 +CUDR_NORMAL: Final = 0 +CUDR_NOSNAPTOGRID: Final = 1 +CUDR_NORESOLVEPOSITIONS: Final = 2 +CUDR_NOCLOSEGAPS: Final = 4 +CUDR_NEGATIVECOORDS: Final = 8 +CUDR_NOPRIMARY: Final = 16 +RDW_INVALIDATE: Final = 1 +RDW_INTERNALPAINT: Final = 2 +RDW_ERASE: Final = 4 +RDW_VALIDATE: Final = 8 +RDW_NOINTERNALPAINT: Final = 16 +RDW_NOERASE: Final = 32 +RDW_NOCHILDREN: Final = 64 +RDW_ALLCHILDREN: Final = 128 +RDW_UPDATENOW: Final = 256 +RDW_ERASENOW: Final = 512 +RDW_FRAME: Final = 1024 +RDW_NOFRAME: Final = 2048 +SW_SCROLLCHILDREN: Final = 1 +SW_INVALIDATE: Final = 2 +SW_ERASE: Final = 4 +SW_SMOOTHSCROLL: Final = 16 +ESB_ENABLE_BOTH: Final = 0 +ESB_DISABLE_BOTH: Final = 3 +ESB_DISABLE_LEFT: Final = 1 +ESB_DISABLE_RIGHT: Final = 2 +ESB_DISABLE_UP: Final = 1 +ESB_DISABLE_DOWN: Final = 2 +ESB_DISABLE_LTUP: Final = ESB_DISABLE_LEFT +ESB_DISABLE_RTDN: Final = ESB_DISABLE_RIGHT +HELPINFO_WINDOW: Final = 1 +HELPINFO_MENUITEM: Final = 2 +MB_OK: Final = 0 +MB_OKCANCEL: Final = 1 +MB_ABORTRETRYIGNORE: Final = 2 +MB_YESNOCANCEL: Final = 3 +MB_YESNO: Final = 4 +MB_RETRYCANCEL: Final = 5 +MB_ICONHAND: Final = 16 +MB_ICONQUESTION: Final = 32 +MB_ICONEXCLAMATION: Final = 48 +MB_ICONASTERISK: Final = 64 +MB_ICONWARNING: Final = MB_ICONEXCLAMATION +MB_ICONERROR: Final = MB_ICONHAND +MB_ICONINFORMATION: Final = MB_ICONASTERISK +MB_ICONSTOP: Final = MB_ICONHAND +MB_DEFBUTTON1: Final = 0 +MB_DEFBUTTON2: Final = 256 +MB_DEFBUTTON3: Final = 512 +MB_DEFBUTTON4: Final = 768 +MB_APPLMODAL: Final = 0 +MB_SYSTEMMODAL: Final = 4096 +MB_TASKMODAL: Final = 8192 +MB_HELP: Final = 16384 +MB_NOFOCUS: Final = 32768 +MB_SETFOREGROUND: Final = 65536 +MB_DEFAULT_DESKTOP_ONLY: Final = 131072 +MB_TOPMOST: Final = 262144 +MB_RIGHT: Final = 524288 +MB_RTLREADING: Final = 1048576 +MB_SERVICE_NOTIFICATION: Final = 2097152 +MB_TYPEMASK: Final = 15 +MB_USERICON: Final = 128 +MB_ICONMASK: Final = 240 +MB_DEFMASK: Final = 3840 +MB_MODEMASK: Final = 12288 +MB_MISCMASK: Final = 49152 + +CWP_ALL: Final = 0 +CWP_SKIPINVISIBLE: Final = 1 +CWP_SKIPDISABLED: Final = 2 +CWP_SKIPTRANSPARENT: Final = 4 +CTLCOLOR_MSGBOX: Final = 0 +CTLCOLOR_EDIT: Final = 1 +CTLCOLOR_LISTBOX: Final = 2 +CTLCOLOR_BTN: Final = 3 +CTLCOLOR_DLG: Final = 4 +CTLCOLOR_SCROLLBAR: Final = 5 +CTLCOLOR_STATIC: Final = 6 +CTLCOLOR_MAX: Final = 7 +COLOR_SCROLLBAR: Final = 0 +COLOR_BACKGROUND: Final = 1 +COLOR_ACTIVECAPTION: Final = 2 +COLOR_INACTIVECAPTION: Final = 3 +COLOR_MENU: Final = 4 +COLOR_WINDOW: Final = 5 +COLOR_WINDOWFRAME: Final = 6 +COLOR_MENUTEXT: Final = 7 +COLOR_WINDOWTEXT: Final = 8 +COLOR_CAPTIONTEXT: Final = 9 +COLOR_ACTIVEBORDER: Final = 10 +COLOR_INACTIVEBORDER: Final = 11 +COLOR_APPWORKSPACE: Final = 12 +COLOR_HIGHLIGHT: Final = 13 +COLOR_HIGHLIGHTTEXT: Final = 14 +COLOR_BTNFACE: Final = 15 +COLOR_BTNSHADOW: Final = 16 +COLOR_GRAYTEXT: Final = 17 +COLOR_BTNTEXT: Final = 18 +COLOR_INACTIVECAPTIONTEXT: Final = 19 +COLOR_BTNHIGHLIGHT: Final = 20 +COLOR_3DDKSHADOW: Final = 21 +COLOR_3DLIGHT: Final = 22 +COLOR_INFOTEXT: Final = 23 +COLOR_INFOBK: Final = 24 +COLOR_HOTLIGHT: Final = 26 +COLOR_GRADIENTACTIVECAPTION: Final = 27 +COLOR_GRADIENTINACTIVECAPTION: Final = 28 +COLOR_DESKTOP: Final = COLOR_BACKGROUND +COLOR_3DFACE: Final = COLOR_BTNFACE +COLOR_3DSHADOW: Final = COLOR_BTNSHADOW +COLOR_3DHIGHLIGHT: Final = COLOR_BTNHIGHLIGHT +COLOR_3DHILIGHT: Final = COLOR_BTNHIGHLIGHT +COLOR_BTNHILIGHT: Final = COLOR_BTNHIGHLIGHT +GW_HWNDFIRST: Final = 0 +GW_HWNDLAST: Final = 1 +GW_HWNDNEXT: Final = 2 +GW_HWNDPREV: Final = 3 +GW_OWNER: Final = 4 +GW_CHILD: Final = 5 +GW_ENABLEDPOPUP: Final = 6 +GW_MAX: Final = 6 +MF_INSERT: Final = 0 +MF_CHANGE: Final = 128 +MF_APPEND: Final = 256 +MF_DELETE: Final = 512 +MF_REMOVE: Final = 4096 +MF_BYCOMMAND: Final = 0 +MF_BYPOSITION: Final = 1024 +MF_SEPARATOR: Final = 2048 +MF_ENABLED: Final = 0 +MF_GRAYED: Final = 1 +MF_DISABLED: Final = 2 +MF_UNCHECKED: Final = 0 +MF_CHECKED: Final = 8 +MF_USECHECKBITMAPS: Final = 512 +MF_STRING: Final = 0 +MF_BITMAP: Final = 4 +MF_OWNERDRAW: Final = 256 +MF_POPUP: Final = 16 +MF_MENUBARBREAK: Final = 32 +MF_MENUBREAK: Final = 64 +MF_UNHILITE: Final = 0 +MF_HILITE: Final = 128 +MF_DEFAULT: Final = 4096 +MF_SYSMENU: Final = 8192 +MF_HELP: Final = 16384 +MF_RIGHTJUSTIFY: Final = 16384 +MF_MOUSESELECT: Final = 32768 +MF_END: Final = 128 +MFT_STRING: Final = MF_STRING +MFT_BITMAP: Final = MF_BITMAP +MFT_MENUBARBREAK: Final = MF_MENUBARBREAK +MFT_MENUBREAK: Final = MF_MENUBREAK +MFT_OWNERDRAW: Final = MF_OWNERDRAW +MFT_RADIOCHECK: Final = 512 +MFT_SEPARATOR: Final = MF_SEPARATOR +MFT_RIGHTORDER: Final = 8192 +MFT_RIGHTJUSTIFY: Final = MF_RIGHTJUSTIFY +MFS_GRAYED: Final = 3 +MFS_DISABLED: Final = MFS_GRAYED +MFS_CHECKED: Final = MF_CHECKED +MFS_HILITE: Final = MF_HILITE +MFS_ENABLED: Final = MF_ENABLED +MFS_UNCHECKED: Final = MF_UNCHECKED +MFS_UNHILITE: Final = MF_UNHILITE +MFS_DEFAULT: Final = MF_DEFAULT +MFS_MASK: Final = 4235 +MFS_HOTTRACKDRAWN: Final = 268435456 +MFS_CACHEDBMP: Final = 536870912 +MFS_BOTTOMGAPDROP: Final = 1073741824 +MFS_TOPGAPDROP: Final = -2147483648 +MFS_GAPDROP: Final = -1073741824 +SC_SIZE: Final = 61440 +SC_MOVE: Final = 61456 +SC_MINIMIZE: Final = 61472 +SC_MAXIMIZE: Final = 61488 +SC_NEXTWINDOW: Final = 61504 +SC_PREVWINDOW: Final = 61520 +SC_CLOSE: Final = 61536 +SC_VSCROLL: Final = 61552 +SC_HSCROLL: Final = 61568 +SC_MOUSEMENU: Final = 61584 +SC_KEYMENU: Final = 61696 +SC_ARRANGE: Final = 61712 +SC_RESTORE: Final = 61728 +SC_TASKLIST: Final = 61744 +SC_SCREENSAVE: Final = 61760 +SC_HOTKEY: Final = 61776 +SC_DEFAULT: Final = 61792 +SC_MONITORPOWER: Final = 61808 +SC_CONTEXTHELP: Final = 61824 +SC_SEPARATOR: Final = 61455 +SC_ICON: Final = SC_MINIMIZE +SC_ZOOM: Final = SC_MAXIMIZE +IDC_ARROW: Final = 32512 +IDC_IBEAM: Final = 32513 +IDC_WAIT: Final = 32514 +IDC_CROSS: Final = 32515 +IDC_UPARROW: Final = 32516 +IDC_SIZE: Final = 32640 +IDC_ICON: Final = 32641 +IDC_SIZENWSE: Final = 32642 +IDC_SIZENESW: Final = 32643 +IDC_SIZEWE: Final = 32644 +IDC_SIZENS: Final = 32645 +IDC_SIZEALL: Final = 32646 +IDC_NO: Final = 32648 +IDC_HAND: Final = 32649 +IDC_APPSTARTING: Final = 32650 +IDC_HELP: Final = 32651 +IDC_PIN: Final = 32671 +IDC_PERSON: Final = 32672 +IMAGE_BITMAP: Final = 0 +IMAGE_ICON: Final = 1 +IMAGE_CURSOR: Final = 2 +IMAGE_ENHMETAFILE: Final = 3 +LR_DEFAULTCOLOR: Final = 0 +LR_MONOCHROME: Final = 1 +LR_COLOR: Final = 2 +LR_COPYRETURNORG: Final = 4 +LR_COPYDELETEORG: Final = 8 +LR_LOADFROMFILE: Final = 16 +LR_LOADTRANSPARENT: Final = 32 +LR_DEFAULTSIZE: Final = 64 +LR_LOADREALSIZE: Final = 128 +LR_LOADMAP3DCOLORS: Final = 4096 +LR_CREATEDIBSECTION: Final = 8192 +LR_COPYFROMRESOURCE: Final = 16384 +LR_SHARED: Final = 32768 +DI_MASK: Final = 1 +DI_IMAGE: Final = 2 +DI_NORMAL: Final = 3 +DI_COMPAT: Final = 4 +DI_DEFAULTSIZE: Final = 8 +RES_ICON: Final = 1 +RES_CURSOR: Final = 2 +OBM_CLOSE: Final = 32754 +OBM_UPARROW: Final = 32753 +OBM_DNARROW: Final = 32752 +OBM_RGARROW: Final = 32751 +OBM_LFARROW: Final = 32750 +OBM_REDUCE: Final = 32749 +OBM_ZOOM: Final = 32748 +OBM_RESTORE: Final = 32747 +OBM_REDUCED: Final = 32746 +OBM_ZOOMD: Final = 32745 +OBM_RESTORED: Final = 32744 +OBM_UPARROWD: Final = 32743 +OBM_DNARROWD: Final = 32742 +OBM_RGARROWD: Final = 32741 +OBM_LFARROWD: Final = 32740 +OBM_MNARROW: Final = 32739 +OBM_COMBO: Final = 32738 +OBM_UPARROWI: Final = 32737 +OBM_DNARROWI: Final = 32736 +OBM_RGARROWI: Final = 32735 +OBM_LFARROWI: Final = 32734 +OBM_OLD_CLOSE: Final = 32767 +OBM_SIZE: Final = 32766 +OBM_OLD_UPARROW: Final = 32765 +OBM_OLD_DNARROW: Final = 32764 +OBM_OLD_RGARROW: Final = 32763 +OBM_OLD_LFARROW: Final = 32762 +OBM_BTSIZE: Final = 32761 +OBM_CHECK: Final = 32760 +OBM_CHECKBOXES: Final = 32759 +OBM_BTNCORNERS: Final = 32758 +OBM_OLD_REDUCE: Final = 32757 +OBM_OLD_ZOOM: Final = 32756 +OBM_OLD_RESTORE: Final = 32755 +OCR_NORMAL: Final = 32512 +OCR_IBEAM: Final = 32513 +OCR_WAIT: Final = 32514 +OCR_CROSS: Final = 32515 +OCR_UP: Final = 32516 +OCR_SIZE: Final = 32640 +OCR_ICON: Final = 32641 +OCR_SIZENWSE: Final = 32642 +OCR_SIZENESW: Final = 32643 +OCR_SIZEWE: Final = 32644 +OCR_SIZENS: Final = 32645 +OCR_SIZEALL: Final = 32646 +OCR_ICOCUR: Final = 32647 +OCR_NO: Final = 32648 +OCR_HAND: Final = 32649 +OCR_APPSTARTING: Final = 32650 + +OIC_SAMPLE: Final = 32512 +OIC_HAND: Final = 32513 +OIC_QUES: Final = 32514 +OIC_BANG: Final = 32515 +OIC_NOTE: Final = 32516 +OIC_WINLOGO: Final = 32517 +OIC_WARNING: Final = OIC_BANG +OIC_ERROR: Final = OIC_HAND +OIC_INFORMATION: Final = OIC_NOTE +ORD_LANGDRIVER: Final = 1 +IDI_APPLICATION: Final = 32512 +IDI_HAND: Final = 32513 +IDI_QUESTION: Final = 32514 +IDI_EXCLAMATION: Final = 32515 +IDI_ASTERISK: Final = 32516 +IDI_WINLOGO: Final = 32517 +IDI_WARNING: Final = IDI_EXCLAMATION +IDI_ERROR: Final = IDI_HAND +IDI_INFORMATION: Final = IDI_ASTERISK +IDOK: Final = 1 +IDCANCEL: Final = 2 +IDABORT: Final = 3 +IDRETRY: Final = 4 +IDIGNORE: Final = 5 +IDYES: Final = 6 +IDNO: Final = 7 +IDCLOSE: Final = 8 +IDHELP: Final = 9 +ES_LEFT: Final = 0 +ES_CENTER: Final = 1 +ES_RIGHT: Final = 2 +ES_MULTILINE: Final = 4 +ES_UPPERCASE: Final = 8 +ES_LOWERCASE: Final = 16 +ES_PASSWORD: Final = 32 +ES_AUTOVSCROLL: Final = 64 +ES_AUTOHSCROLL: Final = 128 +ES_NOHIDESEL: Final = 256 +ES_OEMCONVERT: Final = 1024 +ES_READONLY: Final = 2048 +ES_WANTRETURN: Final = 4096 +ES_NUMBER: Final = 8192 +EN_SETFOCUS: Final = 256 +EN_KILLFOCUS: Final = 512 +EN_CHANGE: Final = 768 +EN_UPDATE: Final = 1024 +EN_ERRSPACE: Final = 1280 +EN_MAXTEXT: Final = 1281 +EN_HSCROLL: Final = 1537 +EN_VSCROLL: Final = 1538 +EC_LEFTMARGIN: Final = 1 +EC_RIGHTMARGIN: Final = 2 +EC_USEFONTINFO: Final = 65535 +EMSIS_COMPOSITIONSTRING: Final = 1 +EIMES_GETCOMPSTRATONCE: Final = 1 +EIMES_CANCELCOMPSTRINFOCUS: Final = 2 +EIMES_COMPLETECOMPSTRKILLFOCUS: Final = 4 +EM_GETSEL: Final = 176 +EM_SETSEL: Final = 177 +EM_GETRECT: Final = 178 +EM_SETRECT: Final = 179 +EM_SETRECTNP: Final = 180 +EM_SCROLL: Final = 181 +EM_LINESCROLL: Final = 182 +EM_SCROLLCARET: Final = 183 +EM_GETMODIFY: Final = 184 +EM_SETMODIFY: Final = 185 +EM_GETLINECOUNT: Final = 186 +EM_LINEINDEX: Final = 187 +EM_SETHANDLE: Final = 188 +EM_GETHANDLE: Final = 189 +EM_GETTHUMB: Final = 190 +EM_LINELENGTH: Final = 193 +EM_REPLACESEL: Final = 194 +EM_GETLINE: Final = 196 +EM_LIMITTEXT: Final = 197 +EM_CANUNDO: Final = 198 +EM_UNDO: Final = 199 +EM_FMTLINES: Final = 200 +EM_LINEFROMCHAR: Final = 201 +EM_SETTABSTOPS: Final = 203 +EM_SETPASSWORDCHAR: Final = 204 +EM_EMPTYUNDOBUFFER: Final = 205 +EM_GETFIRSTVISIBLELINE: Final = 206 +EM_SETREADONLY: Final = 207 +EM_SETWORDBREAKPROC: Final = 208 +EM_GETWORDBREAKPROC: Final = 209 +EM_GETPASSWORDCHAR: Final = 210 +EM_SETMARGINS: Final = 211 +EM_GETMARGINS: Final = 212 +EM_SETLIMITTEXT: Final = EM_LIMITTEXT +EM_GETLIMITTEXT: Final = 213 +EM_POSFROMCHAR: Final = 214 +EM_CHARFROMPOS: Final = 215 +EM_SETIMESTATUS: Final = 216 +EM_GETIMESTATUS: Final = 217 +WB_LEFT: Final = 0 +WB_RIGHT: Final = 1 +WB_ISDELIMITER: Final = 2 +BS_PUSHBUTTON: Final = 0 +BS_DEFPUSHBUTTON: Final = 1 +BS_CHECKBOX: Final = 2 +BS_AUTOCHECKBOX: Final = 3 +BS_RADIOBUTTON: Final = 4 +BS_3STATE: Final = 5 +BS_AUTO3STATE: Final = 6 +BS_GROUPBOX: Final = 7 +BS_USERBUTTON: Final = 8 +BS_AUTORADIOBUTTON: Final = 9 +BS_OWNERDRAW: Final = 11 +BS_LEFTTEXT: Final = 32 +BS_TEXT: Final = 0 +BS_ICON: Final = 64 +BS_BITMAP: Final = 128 +BS_LEFT: Final = 256 +BS_RIGHT: Final = 512 +BS_CENTER: Final = 768 +BS_TOP: Final = 1024 +BS_BOTTOM: Final = 2048 +BS_VCENTER: Final = 3072 +BS_PUSHLIKE: Final = 4096 +BS_MULTILINE: Final = 8192 +BS_NOTIFY: Final = 16384 +BS_FLAT: Final = 32768 +BS_RIGHTBUTTON: Final = BS_LEFTTEXT +BN_CLICKED: Final = 0 +BN_PAINT: Final = 1 +BN_HILITE: Final = 2 +BN_UNHILITE: Final = 3 +BN_DISABLE: Final = 4 +BN_DOUBLECLICKED: Final = 5 +BN_PUSHED: Final = BN_HILITE +BN_UNPUSHED: Final = BN_UNHILITE +BN_DBLCLK: Final = BN_DOUBLECLICKED +BN_SETFOCUS: Final = 6 +BN_KILLFOCUS: Final = 7 +BM_GETCHECK: Final = 240 +BM_SETCHECK: Final = 241 +BM_GETSTATE: Final = 242 +BM_SETSTATE: Final = 243 +BM_SETSTYLE: Final = 244 +BM_CLICK: Final = 245 +BM_GETIMAGE: Final = 246 +BM_SETIMAGE: Final = 247 +BST_UNCHECKED: Final = 0 +BST_CHECKED: Final = 1 +BST_INDETERMINATE: Final = 2 +BST_PUSHED: Final = 4 +BST_FOCUS: Final = 8 +SS_LEFT: Final = 0 +SS_CENTER: Final = 1 +SS_RIGHT: Final = 2 +SS_ICON: Final = 3 +SS_BLACKRECT: Final = 4 +SS_GRAYRECT: Final = 5 +SS_WHITERECT: Final = 6 +SS_BLACKFRAME: Final = 7 +SS_GRAYFRAME: Final = 8 +SS_WHITEFRAME: Final = 9 +SS_USERITEM: Final = 10 +SS_SIMPLE: Final = 11 +SS_LEFTNOWORDWRAP: Final = 12 +SS_BITMAP: Final = 14 +SS_OWNERDRAW: Final = 13 +SS_ENHMETAFILE: Final = 15 +SS_ETCHEDHORZ: Final = 16 +SS_ETCHEDVERT: Final = 17 +SS_ETCHEDFRAME: Final = 18 +SS_TYPEMASK: Final = 31 +SS_NOPREFIX: Final = 128 +SS_NOTIFY: Final = 256 +SS_CENTERIMAGE: Final = 512 +SS_RIGHTJUST: Final = 1024 +SS_REALSIZEIMAGE: Final = 2048 +SS_SUNKEN: Final = 4096 +SS_ENDELLIPSIS: Final = 16384 +SS_PATHELLIPSIS: Final = 32768 +SS_WORDELLIPSIS: Final = 49152 +SS_ELLIPSISMASK: Final = 49152 +STM_SETICON: Final = 368 +STM_GETICON: Final = 369 +STM_SETIMAGE: Final = 370 +STM_GETIMAGE: Final = 371 +STN_CLICKED: Final = 0 +STN_DBLCLK: Final = 1 +STN_ENABLE: Final = 2 +STN_DISABLE: Final = 3 +STM_MSGMAX: Final = 372 +DWL_MSGRESULT: Final = 0 +DWL_DLGPROC: Final = 4 +DWL_USER: Final = 8 +DDL_READWRITE: Final = 0 +DDL_READONLY: Final = 1 +DDL_HIDDEN: Final = 2 +DDL_SYSTEM: Final = 4 +DDL_DIRECTORY: Final = 16 +DDL_ARCHIVE: Final = 32 +DDL_POSTMSGS: Final = 8192 +DDL_DRIVES: Final = 16384 +DDL_EXCLUSIVE: Final = 32768 + +RT_CURSOR: Final = 1 +RT_BITMAP: Final = 2 +RT_ICON: Final = 3 +RT_MENU: Final = 4 +RT_DIALOG: Final = 5 +RT_STRING: Final = 6 +RT_FONTDIR: Final = 7 +RT_FONT: Final = 8 +RT_ACCELERATOR: Final = 9 +RT_RCDATA: Final = 10 +RT_MESSAGETABLE: Final = 11 +DIFFERENCE: Final = 11 +RT_GROUP_CURSOR: Final[int] +RT_GROUP_ICON: Final[int] +RT_VERSION: Final = 16 +RT_DLGINCLUDE: Final = 17 +RT_PLUGPLAY: Final = 19 +RT_VXD: Final = 20 +RT_ANICURSOR: Final = 21 +RT_ANIICON: Final = 22 +RT_HTML: Final = 23 + +SB_HORZ: Final = 0 +SB_VERT: Final = 1 +SB_CTL: Final = 2 +SB_BOTH: Final = 3 +SB_LINEUP: Final = 0 +SB_LINELEFT: Final = 0 +SB_LINEDOWN: Final = 1 +SB_LINERIGHT: Final = 1 +SB_PAGEUP: Final = 2 +SB_PAGELEFT: Final = 2 +SB_PAGEDOWN: Final = 3 +SB_PAGERIGHT: Final = 3 +SB_THUMBPOSITION: Final = 4 +SB_THUMBTRACK: Final = 5 +SB_TOP: Final = 6 +SB_LEFT: Final = 6 +SB_BOTTOM: Final = 7 +SB_RIGHT: Final = 7 +SB_ENDSCROLL: Final = 8 +SW_HIDE: Final = 0 +SW_SHOWNORMAL: Final = 1 +SW_NORMAL: Final = 1 +SW_SHOWMINIMIZED: Final = 2 +SW_SHOWMAXIMIZED: Final = 3 +SW_MAXIMIZE: Final = 3 +SW_SHOWNOACTIVATE: Final = 4 +SW_SHOW: Final = 5 +SW_MINIMIZE: Final = 6 +SW_SHOWMINNOACTIVE: Final = 7 +SW_SHOWNA: Final = 8 +SW_RESTORE: Final = 9 +SW_SHOWDEFAULT: Final = 10 +SW_FORCEMINIMIZE: Final = 11 +SW_MAX: Final = 11 +HIDE_WINDOW: Final = 0 +SHOW_OPENWINDOW: Final = 1 +SHOW_ICONWINDOW: Final = 2 +SHOW_FULLSCREEN: Final = 3 +SHOW_OPENNOACTIVATE: Final = 4 +SW_PARENTCLOSING: Final = 1 +SW_OTHERZOOM: Final = 2 +SW_PARENTOPENING: Final = 3 +SW_OTHERUNZOOM: Final = 4 +AW_HOR_POSITIVE: Final = 1 +AW_HOR_NEGATIVE: Final = 2 +AW_VER_POSITIVE: Final = 4 +AW_VER_NEGATIVE: Final = 8 +AW_CENTER: Final = 16 +AW_HIDE: Final = 65536 +AW_ACTIVATE: Final = 131072 +AW_SLIDE: Final = 262144 +AW_BLEND: Final = 524288 +KF_EXTENDED: Final = 256 +KF_DLGMODE: Final = 2048 +KF_MENUMODE: Final = 4096 +KF_ALTDOWN: Final = 8192 +KF_REPEAT: Final = 16384 +KF_UP: Final = 32768 +VK_LBUTTON: Final = 1 +VK_RBUTTON: Final = 2 +VK_CANCEL: Final = 3 +VK_MBUTTON: Final = 4 +VK_BACK: Final = 8 +VK_TAB: Final = 9 +VK_CLEAR: Final = 12 +VK_RETURN: Final = 13 +VK_SHIFT: Final = 16 +VK_CONTROL: Final = 17 +VK_MENU: Final = 18 +VK_PAUSE: Final = 19 +VK_CAPITAL: Final = 20 +VK_KANA: Final = 21 +VK_HANGEUL: Final = 21 +VK_HANGUL: Final = 21 +VK_JUNJA: Final = 23 +VK_FINAL: Final = 24 +VK_HANJA: Final = 25 +VK_KANJI: Final = 25 +VK_ESCAPE: Final = 27 +VK_CONVERT: Final = 28 +VK_NONCONVERT: Final = 29 +VK_ACCEPT: Final = 30 +VK_MODECHANGE: Final = 31 +VK_SPACE: Final = 32 +VK_PRIOR: Final = 33 +VK_NEXT: Final = 34 +VK_END: Final = 35 +VK_HOME: Final = 36 +VK_LEFT: Final = 37 +VK_UP: Final = 38 +VK_RIGHT: Final = 39 +VK_DOWN: Final = 40 +VK_SELECT: Final = 41 +VK_PRINT: Final = 42 +VK_EXECUTE: Final = 43 +VK_SNAPSHOT: Final = 44 +VK_INSERT: Final = 45 +VK_DELETE: Final = 46 +VK_HELP: Final = 47 +VK_LWIN: Final = 91 +VK_RWIN: Final = 92 +VK_APPS: Final = 93 +VK_NUMPAD0: Final = 96 +VK_NUMPAD1: Final = 97 +VK_NUMPAD2: Final = 98 +VK_NUMPAD3: Final = 99 +VK_NUMPAD4: Final = 100 +VK_NUMPAD5: Final = 101 +VK_NUMPAD6: Final = 102 +VK_NUMPAD7: Final = 103 +VK_NUMPAD8: Final = 104 +VK_NUMPAD9: Final = 105 +VK_MULTIPLY: Final = 106 +VK_ADD: Final = 107 +VK_SEPARATOR: Final = 108 +VK_SUBTRACT: Final = 109 +VK_DECIMAL: Final = 110 +VK_DIVIDE: Final = 111 +VK_F1: Final = 112 +VK_F2: Final = 113 +VK_F3: Final = 114 +VK_F4: Final = 115 +VK_F5: Final = 116 +VK_F6: Final = 117 +VK_F7: Final = 118 +VK_F8: Final = 119 +VK_F9: Final = 120 +VK_F10: Final = 121 +VK_F11: Final = 122 +VK_F12: Final = 123 +VK_F13: Final = 124 +VK_F14: Final = 125 +VK_F15: Final = 126 +VK_F16: Final = 127 +VK_F17: Final = 128 +VK_F18: Final = 129 +VK_F19: Final = 130 +VK_F20: Final = 131 +VK_F21: Final = 132 +VK_F22: Final = 133 +VK_F23: Final = 134 +VK_F24: Final = 135 +VK_NUMLOCK: Final = 144 +VK_SCROLL: Final = 145 +VK_LSHIFT: Final = 160 +VK_RSHIFT: Final = 161 +VK_LCONTROL: Final = 162 +VK_RCONTROL: Final = 163 +VK_LMENU: Final = 164 +VK_RMENU: Final = 165 +VK_PROCESSKEY: Final = 229 +VK_ATTN: Final = 246 +VK_CRSEL: Final = 247 +VK_EXSEL: Final = 248 +VK_EREOF: Final = 249 +VK_PLAY: Final = 250 +VK_ZOOM: Final = 251 +VK_NONAME: Final = 252 +VK_PA1: Final = 253 +VK_OEM_CLEAR: Final = 254 + +VK_XBUTTON1: Final = 0x05 +VK_XBUTTON2: Final = 0x06 +VK_VOLUME_MUTE: Final = 0xAD +VK_VOLUME_DOWN: Final = 0xAE +VK_VOLUME_UP: Final = 0xAF +VK_MEDIA_NEXT_TRACK: Final = 0xB0 +VK_MEDIA_PREV_TRACK: Final = 0xB1 +VK_MEDIA_PLAY_PAUSE: Final = 0xB3 +VK_BROWSER_BACK: Final = 0xA6 +VK_BROWSER_FORWARD: Final = 0xA7 +WH_MIN: Final = -1 +WH_MSGFILTER: Final = -1 +WH_JOURNALRECORD: Final = 0 +WH_JOURNALPLAYBACK: Final = 1 +WH_KEYBOARD: Final = 2 +WH_GETMESSAGE: Final = 3 +WH_CALLWNDPROC: Final = 4 +WH_CBT: Final = 5 +WH_SYSMSGFILTER: Final = 6 +WH_MOUSE: Final = 7 +WH_HARDWARE: Final = 8 +WH_DEBUG: Final = 9 +WH_SHELL: Final = 10 +WH_FOREGROUNDIDLE: Final = 11 +WH_CALLWNDPROCRET: Final = 12 +WH_KEYBOARD_LL: Final = 13 +WH_MOUSE_LL: Final = 14 +WH_MAX: Final = 14 +WH_MINHOOK: Final = WH_MIN +WH_MAXHOOK: Final = WH_MAX +HC_ACTION: Final = 0 +HC_GETNEXT: Final = 1 +HC_SKIP: Final = 2 +HC_NOREMOVE: Final = 3 +HC_NOREM: Final = HC_NOREMOVE +HC_SYSMODALON: Final = 4 +HC_SYSMODALOFF: Final = 5 +HCBT_MOVESIZE: Final = 0 +HCBT_MINMAX: Final = 1 +HCBT_QS: Final = 2 +HCBT_CREATEWND: Final = 3 +HCBT_DESTROYWND: Final = 4 +HCBT_ACTIVATE: Final = 5 +HCBT_CLICKSKIPPED: Final = 6 +HCBT_KEYSKIPPED: Final = 7 +HCBT_SYSCOMMAND: Final = 8 +HCBT_SETFOCUS: Final = 9 +MSGF_DIALOGBOX: Final = 0 +MSGF_MESSAGEBOX: Final = 1 +MSGF_MENU: Final = 2 + +MSGF_SCROLLBAR: Final = 5 +MSGF_NEXTWINDOW: Final = 6 + +MSGF_MAX: Final = 8 +MSGF_USER: Final = 4096 +HSHELL_WINDOWCREATED: Final = 1 +HSHELL_WINDOWDESTROYED: Final = 2 +HSHELL_ACTIVATESHELLWINDOW: Final = 3 +HSHELL_WINDOWACTIVATED: Final = 4 +HSHELL_GETMINRECT: Final = 5 +HSHELL_REDRAW: Final = 6 +HSHELL_TASKMAN: Final = 7 +HSHELL_LANGUAGE: Final = 8 +HSHELL_ACCESSIBILITYSTATE: Final = 11 +ACCESS_STICKYKEYS: Final = 1 +ACCESS_FILTERKEYS: Final = 2 +ACCESS_MOUSEKEYS: Final = 3 + +LLKHF_EXTENDED: Final = 1 +LLKHF_INJECTED: Final = 16 +LLKHF_ALTDOWN: Final = 32 +LLKHF_UP: Final = 128 +LLKHF_LOWER_IL_INJECTED: Final = 2 +LLMHF_INJECTED: Final = 1 +LLMHF_LOWER_IL_INJECTED: Final = 2 + +HKL_PREV: Final = 0 +HKL_NEXT: Final = 1 +KLF_ACTIVATE: Final = 1 +KLF_SUBSTITUTE_OK: Final = 2 +KLF_UNLOADPREVIOUS: Final = 4 +KLF_REORDER: Final = 8 +KLF_REPLACELANG: Final = 16 +KLF_NOTELLSHELL: Final = 128 +KLF_SETFORPROCESS: Final = 256 +KL_NAMELENGTH: Final = 9 +DESKTOP_READOBJECTS: Final = 1 +DESKTOP_CREATEWINDOW: Final = 2 +DESKTOP_CREATEMENU: Final = 4 +DESKTOP_HOOKCONTROL: Final = 8 +DESKTOP_JOURNALRECORD: Final = 16 +DESKTOP_JOURNALPLAYBACK: Final = 32 +DESKTOP_ENUMERATE: Final = 64 +DESKTOP_WRITEOBJECTS: Final = 128 +DESKTOP_SWITCHDESKTOP: Final = 256 +DF_ALLOWOTHERACCOUNTHOOK: Final = 1 +WINSTA_ENUMDESKTOPS: Final = 1 +WINSTA_READATTRIBUTES: Final = 2 +WINSTA_ACCESSCLIPBOARD: Final = 4 +WINSTA_CREATEDESKTOP: Final = 8 +WINSTA_WRITEATTRIBUTES: Final = 16 +WINSTA_ACCESSGLOBALATOMS: Final = 32 +WINSTA_EXITWINDOWS: Final = 64 +WINSTA_ENUMERATE: Final = 256 +WINSTA_READSCREEN: Final = 512 +WSF_VISIBLE: Final = 1 +UOI_FLAGS: Final = 1 +UOI_NAME: Final = 2 +UOI_TYPE: Final = 3 +UOI_USER_SID: Final = 4 +GWL_WNDPROC: Final = -4 +GWL_HINSTANCE: Final = -6 +GWL_HWNDPARENT: Final = -8 +GWL_STYLE: Final = -16 +GWL_EXSTYLE: Final = -20 +GWL_USERDATA: Final = -21 +GWL_ID: Final = -12 +GCL_MENUNAME: Final = -8 +GCL_HBRBACKGROUND: Final = -10 +GCL_HCURSOR: Final = -12 +GCL_HICON: Final = -14 +GCL_HMODULE: Final = -16 +GCL_CBWNDEXTRA: Final = -18 +GCL_CBCLSEXTRA: Final = -20 +GCL_WNDPROC: Final = -24 +GCL_STYLE: Final = -26 +GCW_ATOM: Final = -32 +GCL_HICONSM: Final = -34 + +WM_NULL: Final = 0 +WM_CREATE: Final = 1 +WM_DESTROY: Final = 2 +WM_MOVE: Final = 3 +WM_SIZE: Final = 5 +WM_ACTIVATE: Final = 6 +WA_INACTIVE: Final = 0 +WA_ACTIVE: Final = 1 +WA_CLICKACTIVE: Final = 2 +WM_SETFOCUS: Final = 7 +WM_KILLFOCUS: Final = 8 +WM_ENABLE: Final = 10 +WM_SETREDRAW: Final = 11 +WM_SETTEXT: Final = 12 +WM_GETTEXT: Final = 13 +WM_GETTEXTLENGTH: Final = 14 +WM_PAINT: Final = 15 +WM_CLOSE: Final = 16 +WM_QUERYENDSESSION: Final = 17 +WM_QUIT: Final = 18 +WM_QUERYOPEN: Final = 19 +WM_ERASEBKGND: Final = 20 +WM_SYSCOLORCHANGE: Final = 21 +WM_ENDSESSION: Final = 22 +WM_SHOWWINDOW: Final = 24 +WM_WININICHANGE: Final = 26 +WM_SETTINGCHANGE: Final = WM_WININICHANGE +WM_DEVMODECHANGE: Final = 27 +WM_ACTIVATEAPP: Final = 28 +WM_FONTCHANGE: Final = 29 +WM_TIMECHANGE: Final = 30 +WM_CANCELMODE: Final = 31 +WM_SETCURSOR: Final = 32 +WM_MOUSEACTIVATE: Final = 33 +WM_CHILDACTIVATE: Final = 34 +WM_QUEUESYNC: Final = 35 +WM_GETMINMAXINFO: Final = 36 +WM_PAINTICON: Final = 38 +WM_ICONERASEBKGND: Final = 39 +WM_NEXTDLGCTL: Final = 40 +WM_SPOOLERSTATUS: Final = 42 +WM_DRAWITEM: Final = 43 +WM_MEASUREITEM: Final = 44 +WM_DELETEITEM: Final = 45 +WM_VKEYTOITEM: Final = 46 +WM_CHARTOITEM: Final = 47 +WM_SETFONT: Final = 48 +WM_GETFONT: Final = 49 +WM_SETHOTKEY: Final = 50 +WM_GETHOTKEY: Final = 51 +WM_QUERYDRAGICON: Final = 55 +WM_COMPAREITEM: Final = 57 +WM_GETOBJECT: Final = 61 +WM_COMPACTING: Final = 65 +WM_COMMNOTIFY: Final = 68 +WM_WINDOWPOSCHANGING: Final = 70 +WM_WINDOWPOSCHANGED: Final = 71 +WM_POWER: Final = 72 +PWR_OK: Final = 1 +PWR_FAIL: Final = -1 +PWR_SUSPENDREQUEST: Final = 1 +PWR_SUSPENDRESUME: Final = 2 +PWR_CRITICALRESUME: Final = 3 +WM_COPYDATA: Final = 74 +WM_CANCELJOURNAL: Final = 75 +WM_INPUTLANGCHANGEREQUEST: Final = 80 +WM_INPUTLANGCHANGE: Final = 81 +WM_TCARD: Final = 82 +WM_HELP: Final = 83 +WM_USERCHANGED: Final = 84 +WM_NOTIFYFORMAT: Final = 85 +NFR_ANSI: Final = 1 +NFR_UNICODE: Final = 2 +NF_QUERY: Final = 3 +NF_REQUERY: Final = 4 +WM_STYLECHANGING: Final = 124 +WM_STYLECHANGED: Final = 125 +WM_DISPLAYCHANGE: Final = 126 +WM_GETICON: Final = 127 +WM_SETICON: Final = 128 +WM_NCCREATE: Final = 129 +WM_NCDESTROY: Final = 130 +WM_NCCALCSIZE: Final = 131 +WM_NCHITTEST: Final = 132 +WM_NCPAINT: Final = 133 +WM_NCACTIVATE: Final = 134 +WM_GETDLGCODE: Final = 135 +WM_SYNCPAINT: Final = 136 +WM_NCMOUSEMOVE: Final = 160 +WM_NCLBUTTONDOWN: Final = 161 +WM_NCLBUTTONUP: Final = 162 +WM_NCLBUTTONDBLCLK: Final = 163 +WM_NCRBUTTONDOWN: Final = 164 +WM_NCRBUTTONUP: Final = 165 +WM_NCRBUTTONDBLCLK: Final = 166 +WM_NCMBUTTONDOWN: Final = 167 +WM_NCMBUTTONUP: Final = 168 +WM_NCMBUTTONDBLCLK: Final = 169 +WM_KEYFIRST: Final = 256 +WM_KEYDOWN: Final = 256 +WM_KEYUP: Final = 257 +WM_CHAR: Final = 258 +WM_DEADCHAR: Final = 259 +WM_SYSKEYDOWN: Final = 260 +WM_SYSKEYUP: Final = 261 +WM_SYSCHAR: Final = 262 +WM_SYSDEADCHAR: Final = 263 +WM_KEYLAST: Final = 264 +WM_IME_STARTCOMPOSITION: Final = 269 +WM_IME_ENDCOMPOSITION: Final = 270 +WM_IME_COMPOSITION: Final = 271 +WM_IME_KEYLAST: Final = 271 +WM_INITDIALOG: Final = 272 +WM_COMMAND: Final = 273 +WM_SYSCOMMAND: Final = 274 +WM_TIMER: Final = 275 +WM_HSCROLL: Final = 276 +WM_VSCROLL: Final = 277 +WM_INITMENU: Final = 278 +WM_INITMENUPOPUP: Final = 279 +WM_MENUSELECT: Final = 287 +WM_MENUCHAR: Final = 288 +WM_ENTERIDLE: Final = 289 +WM_MENURBUTTONUP: Final = 290 +WM_MENUDRAG: Final = 291 +WM_MENUGETOBJECT: Final = 292 +WM_UNINITMENUPOPUP: Final = 293 +WM_MENUCOMMAND: Final = 294 +WM_CTLCOLORMSGBOX: Final = 306 +WM_CTLCOLOREDIT: Final = 307 +WM_CTLCOLORLISTBOX: Final = 308 +WM_CTLCOLORBTN: Final = 309 +WM_CTLCOLORDLG: Final = 310 +WM_CTLCOLORSCROLLBAR: Final = 311 +WM_CTLCOLORSTATIC: Final = 312 +WM_MOUSEFIRST: Final = 512 +WM_MOUSEMOVE: Final = 512 +WM_LBUTTONDOWN: Final = 513 +WM_LBUTTONUP: Final = 514 +WM_LBUTTONDBLCLK: Final = 515 +WM_RBUTTONDOWN: Final = 516 +WM_RBUTTONUP: Final = 517 +WM_RBUTTONDBLCLK: Final = 518 +WM_MBUTTONDOWN: Final = 519 +WM_MBUTTONUP: Final = 520 +WM_MBUTTONDBLCLK: Final = 521 +WM_MOUSEWHEEL: Final = 522 +WM_MOUSELAST: Final = 522 +WHEEL_DELTA: Final = 120 +WHEEL_PAGESCROLL: Final = -1 +WM_PARENTNOTIFY: Final = 528 +MENULOOP_WINDOW: Final = 0 +MENULOOP_POPUP: Final = 1 +WM_ENTERMENULOOP: Final = 529 +WM_EXITMENULOOP: Final = 530 +WM_NEXTMENU: Final = 531 +WM_SIZING: Final = 532 +WM_CAPTURECHANGED: Final = 533 +WM_MOVING: Final = 534 +WM_POWERBROADCAST: Final = 536 +PBT_APMQUERYSUSPEND: Final = 0 +PBT_APMQUERYSTANDBY: Final = 1 +PBT_APMQUERYSUSPENDFAILED: Final = 2 +PBT_APMQUERYSTANDBYFAILED: Final = 3 +PBT_APMSUSPEND: Final = 4 +PBT_APMSTANDBY: Final = 5 +PBT_APMRESUMECRITICAL: Final = 6 +PBT_APMRESUMESUSPEND: Final = 7 +PBT_APMRESUMESTANDBY: Final = 8 +PBTF_APMRESUMEFROMFAILURE: Final = 1 +PBT_APMBATTERYLOW: Final = 9 +PBT_APMPOWERSTATUSCHANGE: Final = 10 +PBT_APMOEMEVENT: Final = 11 +PBT_APMRESUMEAUTOMATIC: Final = 18 +WM_MDICREATE: Final = 544 +WM_MDIDESTROY: Final = 545 +WM_MDIACTIVATE: Final = 546 +WM_MDIRESTORE: Final = 547 +WM_MDINEXT: Final = 548 +WM_MDIMAXIMIZE: Final = 549 +WM_MDITILE: Final = 550 +WM_MDICASCADE: Final = 551 +WM_MDIICONARRANGE: Final = 552 +WM_MDIGETACTIVE: Final = 553 +WM_MDISETMENU: Final = 560 +WM_ENTERSIZEMOVE: Final = 561 +WM_EXITSIZEMOVE: Final = 562 +WM_DROPFILES: Final = 563 +WM_MDIREFRESHMENU: Final = 564 +WM_IME_SETCONTEXT: Final = 641 +WM_IME_NOTIFY: Final = 642 +WM_IME_CONTROL: Final = 643 +WM_IME_COMPOSITIONFULL: Final = 644 +WM_IME_SELECT: Final = 645 +WM_IME_CHAR: Final = 646 +WM_IME_REQUEST: Final = 648 +WM_IME_KEYDOWN: Final = 656 +WM_IME_KEYUP: Final = 657 +WM_MOUSEHOVER: Final = 673 +WM_MOUSELEAVE: Final = 675 +WM_CUT: Final = 768 +WM_COPY: Final = 769 +WM_PASTE: Final = 770 +WM_CLEAR: Final = 771 +WM_UNDO: Final = 772 +WM_RENDERFORMAT: Final = 773 +WM_RENDERALLFORMATS: Final = 774 +WM_DESTROYCLIPBOARD: Final = 775 +WM_DRAWCLIPBOARD: Final = 776 +WM_PAINTCLIPBOARD: Final = 777 +WM_VSCROLLCLIPBOARD: Final = 778 +WM_SIZECLIPBOARD: Final = 779 +WM_ASKCBFORMATNAME: Final = 780 +WM_CHANGECBCHAIN: Final = 781 +WM_HSCROLLCLIPBOARD: Final = 782 +WM_QUERYNEWPALETTE: Final = 783 +WM_PALETTEISCHANGING: Final = 784 +WM_PALETTECHANGED: Final = 785 +WM_HOTKEY: Final = 786 +WM_PRINT: Final = 791 +WM_HANDHELDFIRST: Final = 856 +WM_HANDHELDLAST: Final = 863 +WM_AFXFIRST: Final = 864 +WM_AFXLAST: Final = 895 +WM_PENWINFIRST: Final = 896 +WM_PENWINLAST: Final = 911 +WM_APP: Final = 32768 +WMSZ_LEFT: Final = 1 +WMSZ_RIGHT: Final = 2 +WMSZ_TOP: Final = 3 +WMSZ_TOPLEFT: Final = 4 +WMSZ_TOPRIGHT: Final = 5 +WMSZ_BOTTOM: Final = 6 +WMSZ_BOTTOMLEFT: Final = 7 +WMSZ_BOTTOMRIGHT: Final = 8 + +HTERROR: Final = -2 +HTTRANSPARENT: Final = -1 +HTNOWHERE: Final = 0 +HTCLIENT: Final = 1 +HTCAPTION: Final = 2 +HTSYSMENU: Final = 3 +HTGROWBOX: Final = 4 +HTSIZE: Final = HTGROWBOX +HTMENU: Final = 5 +HTHSCROLL: Final = 6 +HTVSCROLL: Final = 7 +HTMINBUTTON: Final = 8 +HTMAXBUTTON: Final = 9 +HTLEFT: Final = 10 +HTRIGHT: Final = 11 +HTTOP: Final = 12 +HTTOPLEFT: Final = 13 +HTTOPRIGHT: Final = 14 +HTBOTTOM: Final = 15 +HTBOTTOMLEFT: Final = 16 +HTBOTTOMRIGHT: Final = 17 +HTBORDER: Final = 18 +HTREDUCE: Final = HTMINBUTTON +HTZOOM: Final = HTMAXBUTTON +HTSIZEFIRST: Final = HTLEFT +HTSIZELAST: Final = HTBOTTOMRIGHT +HTOBJECT: Final = 19 +HTCLOSE: Final = 20 +HTHELP: Final = 21 +SMTO_NORMAL: Final = 0 +SMTO_BLOCK: Final = 1 +SMTO_ABORTIFHUNG: Final = 2 +SMTO_NOTIMEOUTIFNOTHUNG: Final = 8 +MA_ACTIVATE: Final = 1 +MA_ACTIVATEANDEAT: Final = 2 +MA_NOACTIVATE: Final = 3 +MA_NOACTIVATEANDEAT: Final = 4 +ICON_SMALL: Final = 0 +ICON_BIG: Final = 1 +SIZE_RESTORED: Final = 0 +SIZE_MINIMIZED: Final = 1 +SIZE_MAXIMIZED: Final = 2 +SIZE_MAXSHOW: Final = 3 +SIZE_MAXHIDE: Final = 4 +SIZENORMAL: Final = SIZE_RESTORED +SIZEICONIC: Final = SIZE_MINIMIZED +SIZEFULLSCREEN: Final = SIZE_MAXIMIZED +SIZEZOOMSHOW: Final = SIZE_MAXSHOW +SIZEZOOMHIDE: Final = SIZE_MAXHIDE +WVR_ALIGNTOP: Final = 16 +WVR_ALIGNLEFT: Final = 32 +WVR_ALIGNBOTTOM: Final = 64 +WVR_ALIGNRIGHT: Final = 128 +WVR_HREDRAW: Final = 256 +WVR_VREDRAW: Final = 512 +WVR_REDRAW: Final[int] +WVR_VALIDRECTS: Final = 1024 +MK_LBUTTON: Final = 1 +MK_RBUTTON: Final = 2 +MK_SHIFT: Final = 4 +MK_CONTROL: Final = 8 +MK_MBUTTON: Final = 16 +TME_HOVER: Final = 1 +TME_LEAVE: Final = 2 +TME_QUERY: Final = 1073741824 +TME_CANCEL: Final = -2147483648 +HOVER_DEFAULT: Final = -1 +WS_OVERLAPPED: Final = 0 +WS_POPUP: Final = -2147483648 +WS_CHILD: Final = 1073741824 +WS_MINIMIZE: Final = 536870912 +WS_VISIBLE: Final = 268435456 +WS_DISABLED: Final = 134217728 +WS_CLIPSIBLINGS: Final = 67108864 +WS_CLIPCHILDREN: Final = 33554432 +WS_MAXIMIZE: Final = 16777216 +WS_CAPTION: Final = 12582912 +WS_BORDER: Final = 8388608 +WS_DLGFRAME: Final = 4194304 +WS_VSCROLL: Final = 2097152 +WS_HSCROLL: Final = 1048576 +WS_SYSMENU: Final = 524288 +WS_THICKFRAME: Final = 262144 +WS_GROUP: Final = 131072 +WS_TABSTOP: Final = 65536 +WS_MINIMIZEBOX: Final = 131072 +WS_MAXIMIZEBOX: Final = 65536 +WS_TILED: Final = WS_OVERLAPPED +WS_ICONIC: Final = WS_MINIMIZE +WS_SIZEBOX: Final = WS_THICKFRAME +WS_OVERLAPPEDWINDOW: Final[int] +WS_POPUPWINDOW: Final[int] +WS_CHILDWINDOW: Final = WS_CHILD +WS_TILEDWINDOW: Final = WS_OVERLAPPEDWINDOW +WS_EX_DLGMODALFRAME: Final = 1 +WS_EX_NOPARENTNOTIFY: Final = 4 +WS_EX_TOPMOST: Final = 8 +WS_EX_ACCEPTFILES: Final = 16 +WS_EX_TRANSPARENT: Final = 32 +WS_EX_MDICHILD: Final = 64 +WS_EX_TOOLWINDOW: Final = 128 +WS_EX_WINDOWEDGE: Final = 256 +WS_EX_CLIENTEDGE: Final = 512 +WS_EX_CONTEXTHELP: Final = 1024 +WS_EX_RIGHT: Final = 4096 +WS_EX_LEFT: Final = 0 +WS_EX_RTLREADING: Final = 8192 +WS_EX_LTRREADING: Final = 0 +WS_EX_LEFTSCROLLBAR: Final = 16384 +WS_EX_RIGHTSCROLLBAR: Final = 0 +WS_EX_CONTROLPARENT: Final = 65536 +WS_EX_STATICEDGE: Final = 131072 +WS_EX_APPWINDOW: Final = 262144 +WS_EX_OVERLAPPEDWINDOW: Final[int] +WS_EX_PALETTEWINDOW: Final[int] +WS_EX_LAYERED: Final = 0x00080000 +WS_EX_NOINHERITLAYOUT: Final = 0x00100000 +WS_EX_LAYOUTRTL: Final = 0x00400000 +WS_EX_COMPOSITED: Final = 0x02000000 +WS_EX_NOACTIVATE: Final = 0x08000000 + +CS_VREDRAW: Final = 1 +CS_HREDRAW: Final = 2 + +CS_DBLCLKS: Final = 8 +CS_OWNDC: Final = 32 +CS_CLASSDC: Final = 64 +CS_PARENTDC: Final = 128 + +CS_NOCLOSE: Final = 512 +CS_SAVEBITS: Final = 2048 +CS_BYTEALIGNCLIENT: Final = 4096 +CS_BYTEALIGNWINDOW: Final = 8192 +CS_GLOBALCLASS: Final = 16384 +CS_IME: Final = 65536 +PRF_CHECKVISIBLE: Final = 1 +PRF_NONCLIENT: Final = 2 +PRF_CLIENT: Final = 4 +PRF_ERASEBKGND: Final = 8 +PRF_CHILDREN: Final = 16 +PRF_OWNED: Final = 32 +BDR_RAISEDOUTER: Final = 1 +BDR_SUNKENOUTER: Final = 2 +BDR_RAISEDINNER: Final = 4 +BDR_SUNKENINNER: Final = 8 +BDR_OUTER: Final = 3 +BDR_INNER: Final = 12 + +EDGE_RAISED: Final[int] +EDGE_SUNKEN: Final[int] +EDGE_ETCHED: Final[int] +EDGE_BUMP: Final[int] + +ISMEX_NOSEND: Final = 0 +ISMEX_SEND: Final = 1 +ISMEX_NOTIFY: Final = 2 +ISMEX_CALLBACK: Final = 4 +ISMEX_REPLIED: Final = 8 +CW_USEDEFAULT: Final = -2147483648 +FLASHW_STOP: Final = 0 +FLASHW_CAPTION: Final = 1 +FLASHW_TRAY: Final = 2 +FLASHW_ALL: Final[int] +FLASHW_TIMER: Final = 4 +FLASHW_TIMERNOFG: Final = 12 + +DS_ABSALIGN: Final = 1 +DS_SYSMODAL: Final = 2 +DS_LOCALEDIT: Final = 32 +DS_SETFONT: Final = 64 +DS_MODALFRAME: Final = 128 +DS_NOIDLEMSG: Final = 256 +DS_SETFOREGROUND: Final = 512 +DS_3DLOOK: Final = 4 +DS_FIXEDSYS: Final = 8 +DS_NOFAILCREATE: Final = 16 +DS_CONTROL: Final = 1024 +DS_CENTER: Final = 2048 +DS_CENTERMOUSE: Final = 4096 +DS_CONTEXTHELP: Final = 8192 +DM_GETDEFID: Final[int] +DM_SETDEFID: Final[int] +DM_REPOSITION: Final[int] + +DC_HASDEFID: Final = 21323 +DLGC_WANTARROWS: Final = 1 +DLGC_WANTTAB: Final = 2 +DLGC_WANTALLKEYS: Final = 4 +DLGC_WANTMESSAGE: Final = 4 +DLGC_HASSETSEL: Final = 8 +DLGC_DEFPUSHBUTTON: Final = 16 +DLGC_UNDEFPUSHBUTTON: Final = 32 +DLGC_RADIOBUTTON: Final = 64 +DLGC_WANTCHARS: Final = 128 +DLGC_STATIC: Final = 256 +DLGC_BUTTON: Final = 8192 +LB_CTLCODE: Final = 0 +LB_OKAY: Final = 0 +LB_ERR: Final = -1 +LB_ERRSPACE: Final = -2 +LBN_ERRSPACE: Final = -2 +LBN_SELCHANGE: Final = 1 +LBN_DBLCLK: Final = 2 +LBN_SELCANCEL: Final = 3 +LBN_SETFOCUS: Final = 4 +LBN_KILLFOCUS: Final = 5 +LB_ADDSTRING: Final = 384 +LB_INSERTSTRING: Final = 385 +LB_DELETESTRING: Final = 386 +LB_SELITEMRANGEEX: Final = 387 +LB_RESETCONTENT: Final = 388 +LB_SETSEL: Final = 389 +LB_SETCURSEL: Final = 390 +LB_GETSEL: Final = 391 +LB_GETCURSEL: Final = 392 +LB_GETTEXT: Final = 393 +LB_GETTEXTLEN: Final = 394 +LB_GETCOUNT: Final = 395 +LB_SELECTSTRING: Final = 396 +LB_DIR: Final = 397 +LB_GETTOPINDEX: Final = 398 +LB_FINDSTRING: Final = 399 +LB_GETSELCOUNT: Final = 400 +LB_GETSELITEMS: Final = 401 +LB_SETTABSTOPS: Final = 402 +LB_GETHORIZONTALEXTENT: Final = 403 +LB_SETHORIZONTALEXTENT: Final = 404 +LB_SETCOLUMNWIDTH: Final = 405 +LB_ADDFILE: Final = 406 +LB_SETTOPINDEX: Final = 407 +LB_GETITEMRECT: Final = 408 +LB_GETITEMDATA: Final = 409 +LB_SETITEMDATA: Final = 410 +LB_SELITEMRANGE: Final = 411 +LB_SETANCHORINDEX: Final = 412 +LB_GETANCHORINDEX: Final = 413 +LB_SETCARETINDEX: Final = 414 +LB_GETCARETINDEX: Final = 415 +LB_SETITEMHEIGHT: Final = 416 +LB_GETITEMHEIGHT: Final = 417 +LB_FINDSTRINGEXACT: Final = 418 +LB_SETLOCALE: Final = 421 +LB_GETLOCALE: Final = 422 +LB_SETCOUNT: Final = 423 +LB_INITSTORAGE: Final = 424 +LB_ITEMFROMPOINT: Final = 425 +LB_MSGMAX: Final = 432 +LBS_NOTIFY: Final = 1 +LBS_SORT: Final = 2 +LBS_NOREDRAW: Final = 4 +LBS_MULTIPLESEL: Final = 8 +LBS_OWNERDRAWFIXED: Final = 16 +LBS_OWNERDRAWVARIABLE: Final = 32 +LBS_HASSTRINGS: Final = 64 +LBS_USETABSTOPS: Final = 128 +LBS_NOINTEGRALHEIGHT: Final = 256 +LBS_MULTICOLUMN: Final = 512 +LBS_WANTKEYBOARDINPUT: Final = 1024 +LBS_EXTENDEDSEL: Final = 2048 +LBS_DISABLENOSCROLL: Final = 4096 +LBS_NODATA: Final = 8192 +LBS_NOSEL: Final = 16384 +LBS_STANDARD: Final[int] +CB_OKAY: Final = 0 +CB_ERR: Final = -1 +CB_ERRSPACE: Final = -2 +CBN_ERRSPACE: Final = -1 +CBN_SELCHANGE: Final = 1 +CBN_DBLCLK: Final = 2 +CBN_SETFOCUS: Final = 3 +CBN_KILLFOCUS: Final = 4 +CBN_EDITCHANGE: Final = 5 +CBN_EDITUPDATE: Final = 6 +CBN_DROPDOWN: Final = 7 +CBN_CLOSEUP: Final = 8 +CBN_SELENDOK: Final = 9 +CBN_SELENDCANCEL: Final = 10 +CBS_SIMPLE: Final = 1 +CBS_DROPDOWN: Final = 2 +CBS_DROPDOWNLIST: Final = 3 +CBS_OWNERDRAWFIXED: Final = 16 +CBS_OWNERDRAWVARIABLE: Final = 32 +CBS_AUTOHSCROLL: Final = 64 +CBS_OEMCONVERT: Final = 128 +CBS_SORT: Final = 256 +CBS_HASSTRINGS: Final = 512 +CBS_NOINTEGRALHEIGHT: Final = 1024 +CBS_DISABLENOSCROLL: Final = 2048 +CBS_UPPERCASE: Final = 8192 +CBS_LOWERCASE: Final = 16384 +CB_GETEDITSEL: Final = 320 +CB_LIMITTEXT: Final = 321 +CB_SETEDITSEL: Final = 322 +CB_ADDSTRING: Final = 323 +CB_DELETESTRING: Final = 324 +CB_DIR: Final = 325 +CB_GETCOUNT: Final = 326 +CB_GETCURSEL: Final = 327 +CB_GETLBTEXT: Final = 328 +CB_GETLBTEXTLEN: Final = 329 +CB_INSERTSTRING: Final = 330 +CB_RESETCONTENT: Final = 331 +CB_FINDSTRING: Final = 332 +CB_SELECTSTRING: Final = 333 +CB_SETCURSEL: Final = 334 +CB_SHOWDROPDOWN: Final = 335 +CB_GETITEMDATA: Final = 336 +CB_SETITEMDATA: Final = 337 +CB_GETDROPPEDCONTROLRECT: Final = 338 +CB_SETITEMHEIGHT: Final = 339 +CB_GETITEMHEIGHT: Final = 340 +CB_SETEXTENDEDUI: Final = 341 +CB_GETEXTENDEDUI: Final = 342 +CB_GETDROPPEDSTATE: Final = 343 +CB_FINDSTRINGEXACT: Final = 344 +CB_SETLOCALE: Final = 345 +CB_GETLOCALE: Final = 346 +CB_GETTOPINDEX: Final = 347 +CB_SETTOPINDEX: Final = 348 +CB_GETHORIZONTALEXTENT: Final = 349 +CB_SETHORIZONTALEXTENT: Final = 350 +CB_GETDROPPEDWIDTH: Final = 351 +CB_SETDROPPEDWIDTH: Final = 352 +CB_INITSTORAGE: Final = 353 +CB_MSGMAX: Final = 354 +SBS_HORZ: Final = 0 +SBS_VERT: Final = 1 +SBS_TOPALIGN: Final = 2 +SBS_LEFTALIGN: Final = 2 +SBS_BOTTOMALIGN: Final = 4 +SBS_RIGHTALIGN: Final = 4 +SBS_SIZEBOXTOPLEFTALIGN: Final = 2 +SBS_SIZEBOXBOTTOMRIGHTALIGN: Final = 4 +SBS_SIZEBOX: Final = 8 +SBS_SIZEGRIP: Final = 16 +SBM_SETPOS: Final = 224 +SBM_GETPOS: Final = 225 +SBM_SETRANGE: Final = 226 +SBM_SETRANGEREDRAW: Final = 230 +SBM_GETRANGE: Final = 227 +SBM_ENABLE_ARROWS: Final = 228 +SBM_SETSCROLLINFO: Final = 233 +SBM_GETSCROLLINFO: Final = 234 +SIF_RANGE: Final = 1 +SIF_PAGE: Final = 2 +SIF_POS: Final = 4 +SIF_DISABLENOSCROLL: Final = 8 +SIF_TRACKPOS: Final = 16 +SIF_ALL: Final[int] +MDIS_ALLCHILDSTYLES: Final = 1 +MDITILE_VERTICAL: Final = 0 +MDITILE_HORIZONTAL: Final = 1 +MDITILE_SKIPDISABLED: Final = 2 +MDITILE_ZORDER: Final = 4 + +IMC_GETCANDIDATEPOS: Final = 7 +IMC_SETCANDIDATEPOS: Final = 8 +IMC_GETCOMPOSITIONFONT: Final = 9 +IMC_SETCOMPOSITIONFONT: Final = 10 +IMC_GETCOMPOSITIONWINDOW: Final = 11 +IMC_SETCOMPOSITIONWINDOW: Final = 12 +IMC_GETSTATUSWINDOWPOS: Final = 15 +IMC_SETSTATUSWINDOWPOS: Final = 16 +IMC_CLOSESTATUSWINDOW: Final = 33 +IMC_OPENSTATUSWINDOW: Final = 34 + +DELETE: Final = 65536 +READ_CONTROL: Final = 131072 +WRITE_DAC: Final = 262144 +WRITE_OWNER: Final = 524288 +SYNCHRONIZE: Final = 1048576 +STANDARD_RIGHTS_REQUIRED: Final = 983040 +STANDARD_RIGHTS_READ: Final = READ_CONTROL +STANDARD_RIGHTS_WRITE: Final = READ_CONTROL +STANDARD_RIGHTS_EXECUTE: Final = READ_CONTROL +STANDARD_RIGHTS_ALL: Final = 2031616 +SPECIFIC_RIGHTS_ALL: Final = 65535 +ACCESS_SYSTEM_SECURITY: Final = 16777216 +MAXIMUM_ALLOWED: Final = 33554432 +GENERIC_READ: Final = -2147483648 +GENERIC_WRITE: Final = 1073741824 +GENERIC_EXECUTE: Final = 536870912 +GENERIC_ALL: Final = 268435456 + +SERVICE_KERNEL_DRIVER: Final = 1 +SERVICE_FILE_SYSTEM_DRIVER: Final = 2 +SERVICE_ADAPTER: Final = 4 +SERVICE_RECOGNIZER_DRIVER: Final = 8 +SERVICE_DRIVER: Final[int] +SERVICE_WIN32_OWN_PROCESS: Final = 16 +SERVICE_WIN32_SHARE_PROCESS: Final = 32 +SERVICE_WIN32: Final[int] +SERVICE_INTERACTIVE_PROCESS: Final = 256 +SERVICE_TYPE_ALL: Final[int] +SERVICE_BOOT_START: Final = 0 +SERVICE_SYSTEM_START: Final = 1 +SERVICE_AUTO_START: Final = 2 +SERVICE_DEMAND_START: Final = 3 +SERVICE_DISABLED: Final = 4 +SERVICE_ERROR_IGNORE: Final = 0 +SERVICE_ERROR_NORMAL: Final = 1 +SERVICE_ERROR_SEVERE: Final = 2 +SERVICE_ERROR_CRITICAL: Final = 3 +TAPE_ERASE_SHORT: Final = 0 +TAPE_ERASE_LONG: Final = 1 +TAPE_LOAD: Final = 0 +TAPE_UNLOAD: Final = 1 +TAPE_TENSION: Final = 2 +TAPE_LOCK: Final = 3 +TAPE_UNLOCK: Final = 4 +TAPE_FORMAT: Final = 5 +TAPE_SETMARKS: Final = 0 +TAPE_FILEMARKS: Final = 1 +TAPE_SHORT_FILEMARKS: Final = 2 +TAPE_LONG_FILEMARKS: Final = 3 +TAPE_ABSOLUTE_POSITION: Final = 0 +TAPE_LOGICAL_POSITION: Final = 1 +TAPE_PSEUDO_LOGICAL_POSITION: Final = 2 +TAPE_REWIND: Final = 0 +TAPE_ABSOLUTE_BLOCK: Final = 1 +TAPE_LOGICAL_BLOCK: Final = 2 +TAPE_PSEUDO_LOGICAL_BLOCK: Final = 3 +TAPE_SPACE_END_OF_DATA: Final = 4 +TAPE_SPACE_RELATIVE_BLOCKS: Final = 5 +TAPE_SPACE_FILEMARKS: Final = 6 +TAPE_SPACE_SEQUENTIAL_FMKS: Final = 7 +TAPE_SPACE_SETMARKS: Final = 8 +TAPE_SPACE_SEQUENTIAL_SMKS: Final = 9 +TAPE_DRIVE_FIXED: Final = 1 +TAPE_DRIVE_SELECT: Final = 2 +TAPE_DRIVE_INITIATOR: Final = 4 +TAPE_DRIVE_ERASE_SHORT: Final = 16 +TAPE_DRIVE_ERASE_LONG: Final = 32 +TAPE_DRIVE_ERASE_BOP_ONLY: Final = 64 +TAPE_DRIVE_ERASE_IMMEDIATE: Final = 128 +TAPE_DRIVE_TAPE_CAPACITY: Final = 256 +TAPE_DRIVE_TAPE_REMAINING: Final = 512 +TAPE_DRIVE_FIXED_BLOCK: Final = 1024 +TAPE_DRIVE_VARIABLE_BLOCK: Final = 2048 +TAPE_DRIVE_WRITE_PROTECT: Final = 4096 +TAPE_DRIVE_EOT_WZ_SIZE: Final = 8192 +TAPE_DRIVE_ECC: Final = 65536 +TAPE_DRIVE_COMPRESSION: Final = 131072 +TAPE_DRIVE_PADDING: Final = 262144 +TAPE_DRIVE_REPORT_SMKS: Final = 524288 +TAPE_DRIVE_GET_ABSOLUTE_BLK: Final = 1048576 +TAPE_DRIVE_GET_LOGICAL_BLK: Final = 2097152 +TAPE_DRIVE_SET_EOT_WZ_SIZE: Final = 4194304 +TAPE_DRIVE_LOAD_UNLOAD: Final = -2147483647 +TAPE_DRIVE_TENSION: Final = -2147483646 +TAPE_DRIVE_LOCK_UNLOCK: Final = -2147483644 +TAPE_DRIVE_REWIND_IMMEDIATE: Final = -2147483640 +TAPE_DRIVE_SET_BLOCK_SIZE: Final = -2147483632 +TAPE_DRIVE_LOAD_UNLD_IMMED: Final = -2147483616 +TAPE_DRIVE_TENSION_IMMED: Final = -2147483584 +TAPE_DRIVE_LOCK_UNLK_IMMED: Final = -2147483520 +TAPE_DRIVE_SET_ECC: Final = -2147483392 +TAPE_DRIVE_SET_COMPRESSION: Final = -2147483136 +TAPE_DRIVE_SET_PADDING: Final = -2147482624 +TAPE_DRIVE_SET_REPORT_SMKS: Final = -2147481600 +TAPE_DRIVE_ABSOLUTE_BLK: Final = -2147479552 +TAPE_DRIVE_ABS_BLK_IMMED: Final = -2147475456 +TAPE_DRIVE_LOGICAL_BLK: Final = -2147467264 +TAPE_DRIVE_LOG_BLK_IMMED: Final = -2147450880 +TAPE_DRIVE_END_OF_DATA: Final = -2147418112 +TAPE_DRIVE_RELATIVE_BLKS: Final = -2147352576 +TAPE_DRIVE_FILEMARKS: Final = -2147221504 +TAPE_DRIVE_SEQUENTIAL_FMKS: Final = -2146959360 +TAPE_DRIVE_SETMARKS: Final = -2146435072 +TAPE_DRIVE_SEQUENTIAL_SMKS: Final = -2145386496 +TAPE_DRIVE_REVERSE_POSITION: Final = -2143289344 +TAPE_DRIVE_SPACE_IMMEDIATE: Final = -2139095040 +TAPE_DRIVE_WRITE_SETMARKS: Final = -2130706432 +TAPE_DRIVE_WRITE_FILEMARKS: Final = -2113929216 +TAPE_DRIVE_WRITE_SHORT_FMKS: Final = -2080374784 +TAPE_DRIVE_WRITE_LONG_FMKS: Final = -2013265920 +TAPE_DRIVE_WRITE_MARK_IMMED: Final = -1879048192 +TAPE_DRIVE_FORMAT: Final = -1610612736 +TAPE_DRIVE_FORMAT_IMMEDIATE: Final = -1073741824 +TAPE_FIXED_PARTITIONS: Final = 0 +TAPE_SELECT_PARTITIONS: Final = 1 +TAPE_INITIATOR_PARTITIONS: Final = 2 + +APPLICATION_ERROR_MASK: Final = 536870912 +ERROR_SEVERITY_SUCCESS: Final = 0 +ERROR_SEVERITY_INFORMATIONAL: Final = 1073741824 +ERROR_SEVERITY_WARNING: Final = -2147483648 +ERROR_SEVERITY_ERROR: Final = -1073741824 +MINCHAR: Final = 128 +MAXCHAR: Final = 127 +MINSHORT: Final = 32768 +MAXSHORT: Final = 32767 +MINLONG: Final = -2147483648 +MAXLONG: Final = 2147483647 +MAXBYTE: Final = 255 +MAXWORD: Final = 65535 +MAXDWORD: Final = -1 +LANG_NEUTRAL: Final = 0 +LANG_BULGARIAN: Final = 2 +LANG_CHINESE: Final = 4 +LANG_CROATIAN: Final = 26 +LANG_CZECH: Final = 5 +LANG_DANISH: Final = 6 +LANG_DUTCH: Final = 19 +LANG_ENGLISH: Final = 9 +LANG_FINNISH: Final = 11 +LANG_FRENCH: Final = 12 +LANG_GERMAN: Final = 7 +LANG_GREEK: Final = 8 +LANG_HUNGARIAN: Final = 14 +LANG_ICELANDIC: Final = 15 +LANG_ITALIAN: Final = 16 +LANG_JAPANESE: Final = 17 +LANG_KOREAN: Final = 18 +LANG_NORWEGIAN: Final = 20 +LANG_POLISH: Final = 21 +LANG_PORTUGUESE: Final = 22 +LANG_ROMANIAN: Final = 24 +LANG_RUSSIAN: Final = 25 +LANG_SLOVAK: Final = 27 +LANG_SLOVENIAN: Final = 36 +LANG_SPANISH: Final = 10 +LANG_SWEDISH: Final = 29 +LANG_TURKISH: Final = 31 +SUBLANG_NEUTRAL: Final = 0 +SUBLANG_DEFAULT: Final = 1 +SUBLANG_SYS_DEFAULT: Final = 2 +SUBLANG_CHINESE_TRADITIONAL: Final = 1 +SUBLANG_CHINESE_SIMPLIFIED: Final = 2 +SUBLANG_CHINESE_HONGKONG: Final = 3 +SUBLANG_CHINESE_SINGAPORE: Final = 4 +SUBLANG_DUTCH: Final = 1 +SUBLANG_DUTCH_BELGIAN: Final = 2 +SUBLANG_ENGLISH_US: Final = 1 +SUBLANG_ENGLISH_UK: Final = 2 +SUBLANG_ENGLISH_AUS: Final = 3 +SUBLANG_ENGLISH_CAN: Final = 4 +SUBLANG_ENGLISH_NZ: Final = 5 +SUBLANG_ENGLISH_EIRE: Final = 6 +SUBLANG_FRENCH: Final = 1 +SUBLANG_FRENCH_BELGIAN: Final = 2 +SUBLANG_FRENCH_CANADIAN: Final = 3 +SUBLANG_FRENCH_SWISS: Final = 4 +SUBLANG_GERMAN: Final = 1 +SUBLANG_GERMAN_SWISS: Final = 2 +SUBLANG_GERMAN_AUSTRIAN: Final = 3 +SUBLANG_ITALIAN: Final = 1 +SUBLANG_ITALIAN_SWISS: Final = 2 +SUBLANG_NORWEGIAN_BOKMAL: Final = 1 +SUBLANG_NORWEGIAN_NYNORSK: Final = 2 +SUBLANG_PORTUGUESE: Final = 2 +SUBLANG_PORTUGUESE_BRAZILIAN: Final = 1 +SUBLANG_SPANISH: Final = 1 +SUBLANG_SPANISH_MEXICAN: Final = 2 +SUBLANG_SPANISH_MODERN: Final = 3 +SORT_DEFAULT: Final = 0 +SORT_JAPANESE_XJIS: Final = 0 +SORT_JAPANESE_UNICODE: Final = 1 +SORT_CHINESE_BIG5: Final = 0 +SORT_CHINESE_UNICODE: Final = 1 +SORT_KOREAN_KSC: Final = 0 +SORT_KOREAN_UNICODE: Final = 1 + +def PRIMARYLANGID(lgid: int) -> int: ... +def SUBLANGID(lgid: int) -> int: ... + +NLS_VALID_LOCALE_MASK: Final = 1048575 +CONTEXT_PORTABLE_32BIT: Final = 1048576 +CONTEXT_ALPHA: Final = 131072 +SIZE_OF_80387_REGISTERS: Final = 80 +CONTEXT_CONTROL: Final = 1 +CONTEXT_FLOATING_POINT: Final = 2 +CONTEXT_INTEGER: Final = 4 +CONTEXT_FULL: Final[int] +PROCESS_TERMINATE: Final = 1 +PROCESS_CREATE_THREAD: Final = 2 +PROCESS_VM_OPERATION: Final = 8 +PROCESS_VM_READ: Final = 16 +PROCESS_VM_WRITE: Final = 32 +PROCESS_DUP_HANDLE: Final = 64 +PROCESS_CREATE_PROCESS: Final = 128 +PROCESS_SET_QUOTA: Final = 256 +PROCESS_SET_INFORMATION: Final = 512 +PROCESS_QUERY_INFORMATION: Final = 1024 +PROCESS_SUSPEND_RESUME: Final = 2048 +PROCESS_QUERY_LIMITED_INFORMATION: Final = 4096 +PROCESS_SET_LIMITED_INFORMATION: Final = 8192 +PROCESS_ALL_ACCESS: Final[int] +THREAD_TERMINATE: Final = 1 +THREAD_SUSPEND_RESUME: Final = 2 +THREAD_GET_CONTEXT: Final = 8 +THREAD_SET_CONTEXT: Final = 16 +THREAD_SET_INFORMATION: Final = 32 +THREAD_QUERY_INFORMATION: Final = 64 +THREAD_SET_THREAD_TOKEN: Final = 128 +THREAD_IMPERSONATE: Final = 256 +THREAD_DIRECT_IMPERSONATION: Final = 512 +THREAD_SET_LIMITED_INFORMATION: Final = 1024 +THREAD_QUERY_LIMITED_INFORMATION: Final = 2048 +THREAD_RESUME: Final = 4096 +TLS_MINIMUM_AVAILABLE: Final = 64 +EVENT_MODIFY_STATE: Final = 2 +MUTANT_QUERY_STATE: Final = 1 +SEMAPHORE_MODIFY_STATE: Final = 2 +TIME_ZONE_ID_UNKNOWN: Final = 0 +TIME_ZONE_ID_STANDARD: Final = 1 +TIME_ZONE_ID_DAYLIGHT: Final = 2 +PROCESSOR_INTEL_386: Final = 386 +PROCESSOR_INTEL_486: Final = 486 +PROCESSOR_INTEL_PENTIUM: Final = 586 +PROCESSOR_INTEL_860: Final = 860 +PROCESSOR_MIPS_R2000: Final = 2000 +PROCESSOR_MIPS_R3000: Final = 3000 +PROCESSOR_MIPS_R4000: Final = 4000 +PROCESSOR_ALPHA_21064: Final = 21064 +PROCESSOR_PPC_601: Final = 601 +PROCESSOR_PPC_603: Final = 603 +PROCESSOR_PPC_604: Final = 604 +PROCESSOR_PPC_620: Final = 620 +SECTION_QUERY: Final = 1 +SECTION_MAP_WRITE: Final = 2 +SECTION_MAP_READ: Final = 4 +SECTION_MAP_EXECUTE: Final = 8 +SECTION_EXTEND_SIZE: Final = 16 +PAGE_NOACCESS: Final = 1 +PAGE_READONLY: Final = 2 +PAGE_READWRITE: Final = 4 +PAGE_WRITECOPY: Final = 8 +PAGE_EXECUTE: Final = 16 +PAGE_EXECUTE_READ: Final = 32 +PAGE_EXECUTE_READWRITE: Final = 64 +PAGE_EXECUTE_WRITECOPY: Final = 128 +PAGE_GUARD: Final = 256 +PAGE_NOCACHE: Final = 512 +MEM_COMMIT: Final = 4096 +MEM_RESERVE: Final = 8192 +MEM_DECOMMIT: Final = 16384 +MEM_RELEASE: Final = 32768 +MEM_FREE: Final = 65536 +MEM_PRIVATE: Final = 131072 +MEM_MAPPED: Final = 262144 +MEM_TOP_DOWN: Final = 1048576 + +SEC_FILE: Final = 8388608 +SEC_IMAGE: Final = 16777216 +SEC_RESERVE: Final = 67108864 +SEC_COMMIT: Final = 134217728 +SEC_NOCACHE: Final = 268435456 +MEM_IMAGE: Final = SEC_IMAGE +FILE_SHARE_READ: Final = 1 +FILE_SHARE_WRITE: Final = 2 +FILE_SHARE_DELETE: Final = 4 +FILE_ATTRIBUTE_READONLY: Final = 1 +FILE_ATTRIBUTE_HIDDEN: Final = 2 +FILE_ATTRIBUTE_SYSTEM: Final = 4 +FILE_ATTRIBUTE_DIRECTORY: Final = 16 +FILE_ATTRIBUTE_ARCHIVE: Final = 32 +FILE_ATTRIBUTE_DEVICE: Final = 64 +FILE_ATTRIBUTE_NORMAL: Final = 128 +FILE_ATTRIBUTE_TEMPORARY: Final = 256 +FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 +FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 +FILE_ATTRIBUTE_COMPRESSED: Final = 2048 +FILE_ATTRIBUTE_OFFLINE: Final = 4096 +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 +FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 +FILE_ATTRIBUTE_VIRTUAL: Final = 65536 + +FILE_NOTIFY_CHANGE_FILE_NAME: Final = 1 +FILE_NOTIFY_CHANGE_DIR_NAME: Final = 2 +FILE_NOTIFY_CHANGE_ATTRIBUTES: Final = 4 +FILE_NOTIFY_CHANGE_SIZE: Final = 8 +FILE_NOTIFY_CHANGE_LAST_WRITE: Final = 16 +FILE_NOTIFY_CHANGE_SECURITY: Final = 256 +FILE_CASE_SENSITIVE_SEARCH: Final = 1 +FILE_CASE_PRESERVED_NAMES: Final = 2 +FILE_FILE_COMPRESSION: Final = 16 +FILE_NAMED_STREAMS: Final = 262144 +FILE_PERSISTENT_ACLS: Final = 0x00000008 +FILE_READ_ONLY_VOLUME: Final = 0x00080000 +FILE_SEQUENTIAL_WRITE_ONCE: Final = 0x00100000 +FILE_SUPPORTS_ENCRYPTION: Final = 0x00020000 +FILE_SUPPORTS_EXTENDED_ATTRIBUTES: Final = 0x00800000 +FILE_SUPPORTS_HARD_LINKS: Final = 0x00400000 +FILE_SUPPORTS_OBJECT_IDS: Final = 0x00010000 +FILE_SUPPORTS_OPEN_BY_FILE_ID: Final = 0x01000000 +FILE_SUPPORTS_REPARSE_POINTS: Final = 0x00000080 +FILE_SUPPORTS_SPARSE_FILES: Final = 0x00000040 +FILE_SUPPORTS_TRANSACTIONS: Final = 0x00200000 +FILE_SUPPORTS_USN_JOURNAL: Final = 0x02000000 +FILE_UNICODE_ON_DISK: Final = 0x00000004 +FILE_VOLUME_QUOTAS: Final = 0x00000020 +FILE_VOLUME_IS_COMPRESSED: Final = 32768 +IO_COMPLETION_MODIFY_STATE: Final = 2 +DUPLICATE_CLOSE_SOURCE: Final = 1 +DUPLICATE_SAME_ACCESS: Final = 2 +SID_MAX_SUB_AUTHORITIES: Final = 15 +SECURITY_NULL_RID: Final = 0 +SECURITY_WORLD_RID: Final = 0 +SECURITY_LOCAL_RID: Final = 0x00000000 +SECURITY_CREATOR_OWNER_RID: Final = 0 +SECURITY_CREATOR_GROUP_RID: Final = 1 +SECURITY_DIALUP_RID: Final = 1 +SECURITY_NETWORK_RID: Final = 2 +SECURITY_BATCH_RID: Final = 3 +SECURITY_INTERACTIVE_RID: Final = 4 +SECURITY_SERVICE_RID: Final = 6 +SECURITY_ANONYMOUS_LOGON_RID: Final = 7 +SECURITY_LOGON_IDS_RID: Final = 5 +SECURITY_LOGON_IDS_RID_COUNT: Final = 3 +SECURITY_LOCAL_SYSTEM_RID: Final = 18 +SECURITY_NT_NON_UNIQUE: Final = 21 +SECURITY_BUILTIN_DOMAIN_RID: Final = 32 +DOMAIN_USER_RID_ADMIN: Final = 500 +DOMAIN_USER_RID_GUEST: Final = 501 +DOMAIN_GROUP_RID_ADMINS: Final = 512 +DOMAIN_GROUP_RID_USERS: Final = 513 +DOMAIN_GROUP_RID_GUESTS: Final = 514 +DOMAIN_ALIAS_RID_ADMINS: Final = 544 +DOMAIN_ALIAS_RID_USERS: Final = 545 +DOMAIN_ALIAS_RID_GUESTS: Final = 546 +DOMAIN_ALIAS_RID_POWER_USERS: Final = 547 +DOMAIN_ALIAS_RID_ACCOUNT_OPS: Final = 548 +DOMAIN_ALIAS_RID_SYSTEM_OPS: Final = 549 +DOMAIN_ALIAS_RID_PRINT_OPS: Final = 550 +DOMAIN_ALIAS_RID_BACKUP_OPS: Final = 551 +DOMAIN_ALIAS_RID_REPLICATOR: Final = 552 +SE_GROUP_MANDATORY: Final = 1 +SE_GROUP_ENABLED_BY_DEFAULT: Final = 2 +SE_GROUP_ENABLED: Final = 4 +SE_GROUP_OWNER: Final = 8 +SE_GROUP_LOGON_ID: Final = -1073741824 +ACL_REVISION: Final = 2 +ACL_REVISION1: Final = 1 +ACL_REVISION2: Final = 2 +ACCESS_ALLOWED_ACE_TYPE: Final = 0 +ACCESS_DENIED_ACE_TYPE: Final = 1 +SYSTEM_AUDIT_ACE_TYPE: Final = 2 +SYSTEM_ALARM_ACE_TYPE: Final = 3 +OBJECT_INHERIT_ACE: Final = 1 +CONTAINER_INHERIT_ACE: Final = 2 +NO_PROPAGATE_INHERIT_ACE: Final = 4 +INHERIT_ONLY_ACE: Final = 8 +VALID_INHERIT_FLAGS: Final = 15 +SUCCESSFUL_ACCESS_ACE_FLAG: Final = 64 +FAILED_ACCESS_ACE_FLAG: Final = 128 +SECURITY_DESCRIPTOR_REVISION: Final = 1 +SECURITY_DESCRIPTOR_REVISION1: Final = 1 +SECURITY_DESCRIPTOR_MIN_LENGTH: Final = 20 +SE_OWNER_DEFAULTED: Final = 1 +SE_GROUP_DEFAULTED: Final = 2 +SE_DACL_PRESENT: Final = 4 +SE_DACL_DEFAULTED: Final = 8 +SE_SACL_PRESENT: Final = 16 +SE_SACL_DEFAULTED: Final = 32 +SE_SELF_RELATIVE: Final = 32768 +SE_PRIVILEGE_ENABLED_BY_DEFAULT: Final = 1 +SE_PRIVILEGE_ENABLED: Final = 2 +SE_PRIVILEGE_USED_FOR_ACCESS: Final = -2147483648 +PRIVILEGE_SET_ALL_NECESSARY: Final = 1 +SE_CREATE_TOKEN_NAME: Final = "SeCreateTokenPrivilege" +SE_ASSIGNPRIMARYTOKEN_NAME: Final = "SeAssignPrimaryTokenPrivilege" +SE_LOCK_MEMORY_NAME: Final = "SeLockMemoryPrivilege" +SE_INCREASE_QUOTA_NAME: Final = "SeIncreaseQuotaPrivilege" +SE_UNSOLICITED_INPUT_NAME: Final = "SeUnsolicitedInputPrivilege" +SE_MACHINE_ACCOUNT_NAME: Final = "SeMachineAccountPrivilege" +SE_TCB_NAME: Final = "SeTcbPrivilege" +SE_SECURITY_NAME: Final = "SeSecurityPrivilege" +SE_TAKE_OWNERSHIP_NAME: Final = "SeTakeOwnershipPrivilege" +SE_LOAD_DRIVER_NAME: Final = "SeLoadDriverPrivilege" +SE_SYSTEM_PROFILE_NAME: Final = "SeSystemProfilePrivilege" +SE_SYSTEMTIME_NAME: Final = "SeSystemtimePrivilege" +SE_PROF_SINGLE_PROCESS_NAME: Final = "SeProfileSingleProcessPrivilege" +SE_INC_BASE_PRIORITY_NAME: Final = "SeIncreaseBasePriorityPrivilege" +SE_CREATE_PAGEFILE_NAME: Final = "SeCreatePagefilePrivilege" +SE_CREATE_PERMANENT_NAME: Final = "SeCreatePermanentPrivilege" +SE_BACKUP_NAME: Final = "SeBackupPrivilege" +SE_RESTORE_NAME: Final = "SeRestorePrivilege" +SE_SHUTDOWN_NAME: Final = "SeShutdownPrivilege" +SE_DEBUG_NAME: Final = "SeDebugPrivilege" +SE_AUDIT_NAME: Final = "SeAuditPrivilege" +SE_SYSTEM_ENVIRONMENT_NAME: Final = "SeSystemEnvironmentPrivilege" +SE_CHANGE_NOTIFY_NAME: Final = "SeChangeNotifyPrivilege" +SE_REMOTE_SHUTDOWN_NAME: Final = "SeRemoteShutdownPrivilege" + +TOKEN_ASSIGN_PRIMARY: Final = 1 +TOKEN_DUPLICATE: Final = 2 +TOKEN_IMPERSONATE: Final = 4 +TOKEN_QUERY: Final = 8 +TOKEN_QUERY_SOURCE: Final = 16 +TOKEN_ADJUST_PRIVILEGES: Final = 32 +TOKEN_ADJUST_GROUPS: Final = 64 +TOKEN_ADJUST_DEFAULT: Final = 128 +TOKEN_ADJUST_SESSIONID: Final = 256 +TOKEN_ALL_ACCESS: Final[int] +TOKEN_READ: Final[int] +TOKEN_WRITE: Final[int] +TOKEN_EXECUTE: Final = STANDARD_RIGHTS_EXECUTE +TOKEN_SOURCE_LENGTH: Final = 8 + +KEY_QUERY_VALUE: Final = 1 +KEY_SET_VALUE: Final = 2 +KEY_CREATE_SUB_KEY: Final = 4 +KEY_ENUMERATE_SUB_KEYS: Final = 8 +KEY_NOTIFY: Final = 16 +KEY_CREATE_LINK: Final = 32 +KEY_WOW64_32KEY: Final = 512 +KEY_WOW64_64KEY: Final = 256 +KEY_WOW64_RES: Final = 768 +KEY_READ: Final[int] +KEY_WRITE: Final[int] +KEY_EXECUTE: Final[int] +KEY_ALL_ACCESS: Final[int] +REG_NOTIFY_CHANGE_ATTRIBUTES: Final = 2 +REG_NOTIFY_CHANGE_SECURITY: Final = 8 +REG_NONE: Final = 0 +REG_SZ: Final = 1 +REG_EXPAND_SZ: Final = 2 + +REG_BINARY: Final = 3 +REG_DWORD: Final = 4 +REG_DWORD_LITTLE_ENDIAN: Final = 4 +REG_DWORD_BIG_ENDIAN: Final = 5 +REG_LINK: Final = 6 +REG_MULTI_SZ: Final = 7 +REG_RESOURCE_LIST: Final = 8 +REG_FULL_RESOURCE_DESCRIPTOR: Final = 9 +REG_RESOURCE_REQUIREMENTS_LIST: Final = 10 +REG_QWORD: Final = 11 +REG_QWORD_LITTLE_ENDIAN: Final = 11 + +_NLSCMPERROR: Final = 2147483647 +NULL: Final = 0 +HEAP_NO_SERIALIZE: Final = 1 +HEAP_GROWABLE: Final = 2 +HEAP_GENERATE_EXCEPTIONS: Final = 4 +HEAP_ZERO_MEMORY: Final = 8 +HEAP_REALLOC_IN_PLACE_ONLY: Final = 16 +HEAP_TAIL_CHECKING_ENABLED: Final = 32 +HEAP_FREE_CHECKING_ENABLED: Final = 64 +HEAP_DISABLE_COALESCE_ON_FREE: Final = 128 +IS_TEXT_UNICODE_ASCII16: Final = 1 +IS_TEXT_UNICODE_REVERSE_ASCII16: Final = 16 +IS_TEXT_UNICODE_STATISTICS: Final = 2 +IS_TEXT_UNICODE_REVERSE_STATISTICS: Final = 32 +IS_TEXT_UNICODE_CONTROLS: Final = 4 +IS_TEXT_UNICODE_REVERSE_CONTROLS: Final = 64 +IS_TEXT_UNICODE_SIGNATURE: Final = 8 +IS_TEXT_UNICODE_REVERSE_SIGNATURE: Final = 128 +IS_TEXT_UNICODE_ILLEGAL_CHARS: Final = 256 +IS_TEXT_UNICODE_ODD_LENGTH: Final = 512 +IS_TEXT_UNICODE_DBCS_LEADBYTE: Final = 1024 +IS_TEXT_UNICODE_NULL_BYTES: Final = 4096 +IS_TEXT_UNICODE_UNICODE_MASK: Final = 15 +IS_TEXT_UNICODE_REVERSE_MASK: Final = 240 +IS_TEXT_UNICODE_NOT_UNICODE_MASK: Final = 3840 +IS_TEXT_UNICODE_NOT_ASCII_MASK: Final = 61440 +COMPRESSION_FORMAT_NONE: Final = 0 +COMPRESSION_FORMAT_DEFAULT: Final = 1 +COMPRESSION_FORMAT_LZNT1: Final = 2 +COMPRESSION_ENGINE_STANDARD: Final = 0 +COMPRESSION_ENGINE_MAXIMUM: Final = 256 +MESSAGE_RESOURCE_UNICODE: Final = 1 +RTL_CRITSECT_TYPE: Final = 0 +RTL_RESOURCE_TYPE: Final = 1 +DLL_PROCESS_ATTACH: Final = 1 +DLL_THREAD_ATTACH: Final = 2 +DLL_THREAD_DETACH: Final = 3 +DLL_PROCESS_DETACH: Final = 0 +EVENTLOG_SEQUENTIAL_READ: Final = 0x0001 +EVENTLOG_SEEK_READ: Final = 0x0002 +EVENTLOG_FORWARDS_READ: Final = 0x0004 +EVENTLOG_BACKWARDS_READ: Final = 0x0008 +EVENTLOG_SUCCESS: Final = 0x0000 +EVENTLOG_ERROR_TYPE: Final = 1 +EVENTLOG_WARNING_TYPE: Final = 2 +EVENTLOG_INFORMATION_TYPE: Final = 4 +EVENTLOG_AUDIT_SUCCESS: Final = 8 +EVENTLOG_AUDIT_FAILURE: Final = 16 +EVENTLOG_START_PAIRED_EVENT: Final = 1 +EVENTLOG_END_PAIRED_EVENT: Final = 2 +EVENTLOG_END_ALL_PAIRED_EVENTS: Final = 4 +EVENTLOG_PAIRED_EVENT_ACTIVE: Final = 8 +EVENTLOG_PAIRED_EVENT_INACTIVE: Final = 16 + +OWNER_SECURITY_INFORMATION: Final = 0x00000001 +GROUP_SECURITY_INFORMATION: Final = 0x00000002 +DACL_SECURITY_INFORMATION: Final = 0x00000004 +SACL_SECURITY_INFORMATION: Final = 0x00000008 +IMAGE_SIZEOF_FILE_HEADER: Final = 20 +IMAGE_FILE_MACHINE_UNKNOWN: Final = 0 +IMAGE_NUMBEROF_DIRECTORY_ENTRIES: Final = 16 +IMAGE_SIZEOF_ROM_OPTIONAL_HEADER: Final = 56 +IMAGE_SIZEOF_STD_OPTIONAL_HEADER: Final = 28 +IMAGE_SIZEOF_NT_OPTIONAL_HEADER: Final = 224 +IMAGE_NT_OPTIONAL_HDR_MAGIC: Final = 267 +IMAGE_ROM_OPTIONAL_HDR_MAGIC: Final = 263 +IMAGE_SIZEOF_SHORT_NAME: Final = 8 +IMAGE_SIZEOF_SECTION_HEADER: Final = 40 +IMAGE_SIZEOF_SYMBOL: Final = 18 +IMAGE_SYM_CLASS_NULL: Final = 0 +IMAGE_SYM_CLASS_AUTOMATIC: Final = 1 +IMAGE_SYM_CLASS_EXTERNAL: Final = 2 +IMAGE_SYM_CLASS_STATIC: Final = 3 +IMAGE_SYM_CLASS_REGISTER: Final = 4 +IMAGE_SYM_CLASS_EXTERNAL_DEF: Final = 5 +IMAGE_SYM_CLASS_LABEL: Final = 6 +IMAGE_SYM_CLASS_UNDEFINED_LABEL: Final = 7 +IMAGE_SYM_CLASS_MEMBER_OF_STRUCT: Final = 8 +IMAGE_SYM_CLASS_ARGUMENT: Final = 9 +IMAGE_SYM_CLASS_STRUCT_TAG: Final = 10 +IMAGE_SYM_CLASS_MEMBER_OF_UNION: Final = 11 +IMAGE_SYM_CLASS_UNION_TAG: Final = 12 +IMAGE_SYM_CLASS_TYPE_DEFINITION: Final = 13 +IMAGE_SYM_CLASS_UNDEFINED_STATIC: Final = 14 +IMAGE_SYM_CLASS_ENUM_TAG: Final = 15 +IMAGE_SYM_CLASS_MEMBER_OF_ENUM: Final = 16 +IMAGE_SYM_CLASS_REGISTER_PARAM: Final = 17 +IMAGE_SYM_CLASS_BIT_FIELD: Final = 18 +IMAGE_SYM_CLASS_BLOCK: Final = 100 +IMAGE_SYM_CLASS_FUNCTION: Final = 101 +IMAGE_SYM_CLASS_END_OF_STRUCT: Final = 102 +IMAGE_SYM_CLASS_FILE: Final = 103 +IMAGE_SYM_CLASS_SECTION: Final = 104 +IMAGE_SYM_CLASS_WEAK_EXTERNAL: Final = 105 +N_BTMASK: Final = 15 +N_TMASK: Final = 48 +N_TMASK1: Final = 192 +N_TMASK2: Final = 240 +N_BTSHFT: Final = 4 +N_TSHIFT: Final = 2 +IMAGE_SIZEOF_AUX_SYMBOL: Final = 18 +IMAGE_COMDAT_SELECT_NODUPLICATES: Final = 1 +IMAGE_COMDAT_SELECT_ANY: Final = 2 +IMAGE_COMDAT_SELECT_SAME_SIZE: Final = 3 +IMAGE_COMDAT_SELECT_EXACT_MATCH: Final = 4 +IMAGE_COMDAT_SELECT_ASSOCIATIVE: Final = 5 +IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY: Final = 1 +IMAGE_WEAK_EXTERN_SEARCH_LIBRARY: Final = 2 +IMAGE_WEAK_EXTERN_SEARCH_ALIAS: Final = 3 +IMAGE_SIZEOF_RELOCATION: Final = 10 +IMAGE_REL_I386_SECTION: Final = 10 +IMAGE_REL_I386_SECREL: Final = 11 +IMAGE_REL_MIPS_REFHALF: Final = 1 +IMAGE_REL_MIPS_REFWORD: Final = 2 +IMAGE_REL_MIPS_JMPADDR: Final = 3 +IMAGE_REL_MIPS_REFHI: Final = 4 +IMAGE_REL_MIPS_REFLO: Final = 5 +IMAGE_REL_MIPS_GPREL: Final = 6 +IMAGE_REL_MIPS_LITERAL: Final = 7 +IMAGE_REL_MIPS_SECTION: Final = 10 +IMAGE_REL_MIPS_SECREL: Final = 11 +IMAGE_REL_MIPS_REFWORDNB: Final = 34 +IMAGE_REL_MIPS_PAIR: Final = 37 +IMAGE_REL_ALPHA_ABSOLUTE: Final = 0 +IMAGE_REL_ALPHA_REFLONG: Final = 1 +IMAGE_REL_ALPHA_REFQUAD: Final = 2 +IMAGE_REL_ALPHA_GPREL32: Final = 3 +IMAGE_REL_ALPHA_LITERAL: Final = 4 +IMAGE_REL_ALPHA_LITUSE: Final = 5 +IMAGE_REL_ALPHA_GPDISP: Final = 6 +IMAGE_REL_ALPHA_BRADDR: Final = 7 +IMAGE_REL_ALPHA_HINT: Final = 8 +IMAGE_REL_ALPHA_INLINE_REFLONG: Final = 9 +IMAGE_REL_ALPHA_REFHI: Final = 10 +IMAGE_REL_ALPHA_REFLO: Final = 11 +IMAGE_REL_ALPHA_PAIR: Final = 12 +IMAGE_REL_ALPHA_MATCH: Final = 13 +IMAGE_REL_ALPHA_SECTION: Final = 14 +IMAGE_REL_ALPHA_SECREL: Final = 15 +IMAGE_REL_ALPHA_REFLONGNB: Final = 16 +IMAGE_SIZEOF_BASE_RELOCATION: Final = 8 +IMAGE_REL_BASED_ABSOLUTE: Final = 0 +IMAGE_REL_BASED_HIGH: Final = 1 +IMAGE_REL_BASED_LOW: Final = 2 +IMAGE_REL_BASED_HIGHLOW: Final = 3 +IMAGE_REL_BASED_HIGHADJ: Final = 4 +IMAGE_REL_BASED_MIPS_JMPADDR: Final = 5 +IMAGE_SIZEOF_LINENUMBER: Final = 6 +IMAGE_ARCHIVE_START_SIZE: Final = 8 +IMAGE_ARCHIVE_START: Final = "!\n" +IMAGE_ARCHIVE_END: Final = "`\n" +IMAGE_ARCHIVE_PAD: Final = "\n" +IMAGE_ARCHIVE_LINKER_MEMBER: Final = "/ " +IMAGE_ARCHIVE_LONGNAMES_MEMBER: Final = "// " +IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR: Final = 60 +IMAGE_ORDINAL_FLAG: Final = -2147483648 + +def IMAGE_SNAP_BY_ORDINAL(Ordinal: int) -> bool: ... +def IMAGE_ORDINAL(Ordinal: int) -> int: ... + +IMAGE_RESOURCE_NAME_IS_STRING: Final = -2147483648 +IMAGE_RESOURCE_DATA_IS_DIRECTORY: Final = -2147483648 +IMAGE_DEBUG_TYPE_UNKNOWN: Final = 0 +IMAGE_DEBUG_TYPE_COFF: Final = 1 +IMAGE_DEBUG_TYPE_CODEVIEW: Final = 2 +IMAGE_DEBUG_TYPE_FPO: Final = 3 +IMAGE_DEBUG_TYPE_MISC: Final = 4 +IMAGE_DEBUG_TYPE_EXCEPTION: Final = 5 +IMAGE_DEBUG_TYPE_FIXUP: Final = 6 +IMAGE_DEBUG_TYPE_OMAP_TO_SRC: Final = 7 +IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: Final = 8 +FRAME_FPO: Final = 0 +FRAME_TRAP: Final = 1 +FRAME_TSS: Final = 2 +SIZEOF_RFPO_DATA: Final = 16 +IMAGE_DEBUG_MISC_EXENAME: Final = 1 +IMAGE_SEPARATE_DEBUG_SIGNATURE: Final = 18756 + +NEWFRAME: Final = 1 +ABORTDOC: Final = 2 +NEXTBAND: Final = 3 +SETCOLORTABLE: Final = 4 +GETCOLORTABLE: Final = 5 +FLUSHOUTPUT: Final = 6 +DRAFTMODE: Final = 7 +QUERYESCSUPPORT: Final = 8 +SETABORTPROC: Final = 9 +STARTDOC: Final = 10 +ENDDOC: Final = 11 +GETPHYSPAGESIZE: Final = 12 +GETPRINTINGOFFSET: Final = 13 +GETSCALINGFACTOR: Final = 14 +MFCOMMENT: Final = 15 +GETPENWIDTH: Final = 16 +SETCOPYCOUNT: Final = 17 +SELECTPAPERSOURCE: Final = 18 +DEVICEDATA: Final = 19 +PASSTHROUGH: Final = 19 +GETTECHNOLGY: Final = 20 +GETTECHNOLOGY: Final = 20 +SETLINECAP: Final = 21 +SETLINEJOIN: Final = 22 +SETMITERLIMIT: Final = 23 +BANDINFO: Final = 24 +DRAWPATTERNRECT: Final = 25 +GETVECTORPENSIZE: Final = 26 +GETVECTORBRUSHSIZE: Final = 27 +ENABLEDUPLEX: Final = 28 +GETSETPAPERBINS: Final = 29 +GETSETPRINTORIENT: Final = 30 +ENUMPAPERBINS: Final = 31 +SETDIBSCALING: Final = 32 +EPSPRINTING: Final = 33 +ENUMPAPERMETRICS: Final = 34 +GETSETPAPERMETRICS: Final = 35 +POSTSCRIPT_DATA: Final = 37 +POSTSCRIPT_IGNORE: Final = 38 +MOUSETRAILS: Final = 39 +GETDEVICEUNITS: Final = 42 +GETEXTENDEDTEXTMETRICS: Final = 256 +GETEXTENTTABLE: Final = 257 +GETPAIRKERNTABLE: Final = 258 +GETTRACKKERNTABLE: Final = 259 +EXTTEXTOUT: Final = 512 +GETFACENAME: Final = 513 +DOWNLOADFACE: Final = 514 +ENABLERELATIVEWIDTHS: Final = 768 +ENABLEPAIRKERNING: Final = 769 +SETKERNTRACK: Final = 770 +SETALLJUSTVALUES: Final = 771 +SETCHARSET: Final = 772 +STRETCHBLT: Final = 2048 +GETSETSCREENPARAMS: Final = 3072 +BEGIN_PATH: Final = 4096 +CLIP_TO_PATH: Final = 4097 +END_PATH: Final = 4098 +EXT_DEVICE_CAPS: Final = 4099 +RESTORE_CTM: Final = 4100 +SAVE_CTM: Final = 4101 +SET_ARC_DIRECTION: Final = 4102 +SET_BACKGROUND_COLOR: Final = 4103 +SET_POLY_MODE: Final = 4104 +SET_SCREEN_ANGLE: Final = 4105 +SET_SPREAD: Final = 4106 +TRANSFORM_CTM: Final = 4107 +SET_CLIP_BOX: Final = 4108 +SET_BOUNDS: Final = 4109 +SET_MIRROR_MODE: Final = 4110 +OPENCHANNEL: Final = 4110 +DOWNLOADHEADER: Final = 4111 +CLOSECHANNEL: Final = 4112 +POSTSCRIPT_PASSTHROUGH: Final = 4115 +ENCAPSULATED_POSTSCRIPT: Final = 4116 +SP_NOTREPORTED: Final = 16384 +SP_ERROR: Final = -1 +SP_APPABORT: Final = -2 +SP_USERABORT: Final = -3 +SP_OUTOFDISK: Final = -4 +SP_OUTOFMEMORY: Final = -5 +PR_JOBSTATUS: Final = 0 + +OBJ_PEN: Final = 1 +OBJ_BRUSH: Final = 2 +OBJ_DC: Final = 3 +OBJ_METADC: Final = 4 +OBJ_PAL: Final = 5 +OBJ_FONT: Final = 6 +OBJ_BITMAP: Final = 7 +OBJ_REGION: Final = 8 +OBJ_METAFILE: Final = 9 +OBJ_MEMDC: Final = 10 +OBJ_EXTPEN: Final = 11 +OBJ_ENHMETADC: Final = 12 +OBJ_ENHMETAFILE: Final = 13 +OBJ_COLORSPACE: Final = 14 + +MWT_IDENTITY: Final = 1 +MWT_LEFTMULTIPLY: Final = 2 +MWT_RIGHTMULTIPLY: Final = 3 +MWT_MIN: Final = MWT_IDENTITY +MWT_MAX: Final = MWT_RIGHTMULTIPLY +BI_RGB: Final = 0 +BI_RLE8: Final = 1 +BI_RLE4: Final = 2 +BI_BITFIELDS: Final = 3 +TMPF_FIXED_PITCH: Final = 1 +TMPF_VECTOR: Final = 2 +TMPF_DEVICE: Final = 8 +TMPF_TRUETYPE: Final = 4 +NTM_REGULAR: Final = 64 +NTM_BOLD: Final = 32 +NTM_ITALIC: Final = 1 +LF_FACESIZE: Final = 32 +LF_FULLFACESIZE: Final = 64 +OUT_DEFAULT_PRECIS: Final = 0 +OUT_STRING_PRECIS: Final = 1 +OUT_CHARACTER_PRECIS: Final = 2 +OUT_STROKE_PRECIS: Final = 3 +OUT_TT_PRECIS: Final = 4 +OUT_DEVICE_PRECIS: Final = 5 +OUT_RASTER_PRECIS: Final = 6 +OUT_TT_ONLY_PRECIS: Final = 7 +OUT_OUTLINE_PRECIS: Final = 8 +CLIP_DEFAULT_PRECIS: Final = 0 +CLIP_CHARACTER_PRECIS: Final = 1 +CLIP_STROKE_PRECIS: Final = 2 +CLIP_MASK: Final = 15 +CLIP_LH_ANGLES: Final[int] +CLIP_TT_ALWAYS: Final[int] +CLIP_EMBEDDED: Final[int] +DEFAULT_QUALITY: Final = 0 +DRAFT_QUALITY: Final = 1 +PROOF_QUALITY: Final = 2 +NONANTIALIASED_QUALITY: Final = 3 +ANTIALIASED_QUALITY: Final = 4 +CLEARTYPE_QUALITY: Final = 5 +CLEARTYPE_NATURAL_QUALITY: Final = 6 +DEFAULT_PITCH: Final = 0 +FIXED_PITCH: Final = 1 +VARIABLE_PITCH: Final = 2 +ANSI_CHARSET: Final = 0 +DEFAULT_CHARSET: Final = 1 +SYMBOL_CHARSET: Final = 2 +SHIFTJIS_CHARSET: Final = 128 +HANGEUL_CHARSET: Final = 129 +CHINESEBIG5_CHARSET: Final = 136 +OEM_CHARSET: Final = 255 +JOHAB_CHARSET: Final = 130 +HEBREW_CHARSET: Final = 177 +ARABIC_CHARSET: Final = 178 +GREEK_CHARSET: Final = 161 +TURKISH_CHARSET: Final = 162 +VIETNAMESE_CHARSET: Final = 163 +THAI_CHARSET: Final = 222 +EASTEUROPE_CHARSET: Final = 238 +RUSSIAN_CHARSET: Final = 204 +MAC_CHARSET: Final = 77 +BALTIC_CHARSET: Final = 186 +FF_DONTCARE: Final[int] +FF_ROMAN: Final[int] +FF_SWISS: Final[int] +FF_MODERN: Final[int] +FF_SCRIPT: Final[int] +FF_DECORATIVE: Final[int] +FW_DONTCARE: Final = 0 +FW_THIN: Final = 100 +FW_EXTRALIGHT: Final = 200 +FW_LIGHT: Final = 300 +FW_NORMAL: Final = 400 +FW_MEDIUM: Final = 500 +FW_SEMIBOLD: Final = 600 +FW_BOLD: Final = 700 +FW_EXTRABOLD: Final = 800 +FW_HEAVY: Final = 900 +FW_ULTRALIGHT: Final = FW_EXTRALIGHT +FW_REGULAR: Final = FW_NORMAL +FW_DEMIBOLD: Final = FW_SEMIBOLD +FW_ULTRABOLD: Final = FW_EXTRABOLD +FW_BLACK: Final = FW_HEAVY + +BS_SOLID: Final = 0 +BS_NULL: Final = 1 +BS_HOLLOW: Final = BS_NULL +BS_HATCHED: Final = 2 +BS_PATTERN: Final = 3 +BS_INDEXED: Final = 4 +BS_DIBPATTERN: Final = 5 +BS_DIBPATTERNPT: Final = 6 +BS_PATTERN8X8: Final = 7 +BS_DIBPATTERN8X8: Final = 8 +HS_HORIZONTAL: Final = 0 +HS_VERTICAL: Final = 1 +HS_FDIAGONAL: Final = 2 +HS_BDIAGONAL: Final = 3 +HS_CROSS: Final = 4 +HS_DIAGCROSS: Final = 5 +HS_FDIAGONAL1: Final = 6 +HS_BDIAGONAL1: Final = 7 +HS_SOLID: Final = 8 +HS_DENSE1: Final = 9 +HS_DENSE2: Final = 10 +HS_DENSE3: Final = 11 +HS_DENSE4: Final = 12 +HS_DENSE5: Final = 13 +HS_DENSE6: Final = 14 +HS_DENSE7: Final = 15 +HS_DENSE8: Final = 16 +HS_NOSHADE: Final = 17 +HS_HALFTONE: Final = 18 +HS_SOLIDCLR: Final = 19 +HS_DITHEREDCLR: Final = 20 +HS_SOLIDTEXTCLR: Final = 21 +HS_DITHEREDTEXTCLR: Final = 22 +HS_SOLIDBKCLR: Final = 23 +HS_DITHEREDBKCLR: Final = 24 +HS_API_MAX: Final = 25 +PS_SOLID: Final = 0 +PS_DASH: Final = 1 +PS_DOT: Final = 2 +PS_DASHDOT: Final = 3 +PS_DASHDOTDOT: Final = 4 +PS_NULL: Final = 5 +PS_INSIDEFRAME: Final = 6 +PS_USERSTYLE: Final = 7 +PS_ALTERNATE: Final = 8 +PS_STYLE_MASK: Final = 15 +PS_ENDCAP_ROUND: Final = 0 +PS_ENDCAP_SQUARE: Final = 256 +PS_ENDCAP_FLAT: Final = 512 +PS_ENDCAP_MASK: Final = 3840 +PS_JOIN_ROUND: Final = 0 +PS_JOIN_BEVEL: Final = 4096 +PS_JOIN_MITER: Final = 8192 +PS_JOIN_MASK: Final = 61440 +PS_COSMETIC: Final = 0 +PS_GEOMETRIC: Final = 65536 +PS_TYPE_MASK: Final = 983040 +AD_COUNTERCLOCKWISE: Final = 1 +AD_CLOCKWISE: Final = 2 +DRIVERVERSION: Final = 0 +TECHNOLOGY: Final = 2 +HORZSIZE: Final = 4 +VERTSIZE: Final = 6 +HORZRES: Final = 8 +VERTRES: Final = 10 +BITSPIXEL: Final = 12 +PLANES: Final = 14 +NUMBRUSHES: Final = 16 +NUMPENS: Final = 18 +NUMMARKERS: Final = 20 +NUMFONTS: Final = 22 +NUMCOLORS: Final = 24 +PDEVICESIZE: Final = 26 +CURVECAPS: Final = 28 +LINECAPS: Final = 30 +POLYGONALCAPS: Final = 32 +TEXTCAPS: Final = 34 +CLIPCAPS: Final = 36 +RASTERCAPS: Final = 38 +ASPECTX: Final = 40 +ASPECTY: Final = 42 +ASPECTXY: Final = 44 +LOGPIXELSX: Final = 88 +LOGPIXELSY: Final = 90 +SIZEPALETTE: Final = 104 +NUMRESERVED: Final = 106 +COLORRES: Final = 108 + +PHYSICALWIDTH: Final = 110 +PHYSICALHEIGHT: Final = 111 +PHYSICALOFFSETX: Final = 112 +PHYSICALOFFSETY: Final = 113 +SCALINGFACTORX: Final = 114 +SCALINGFACTORY: Final = 115 +VREFRESH: Final = 116 +DESKTOPVERTRES: Final = 117 +DESKTOPHORZRES: Final = 118 +BLTALIGNMENT: Final = 119 +SHADEBLENDCAPS: Final = 120 +COLORMGMTCAPS: Final = 121 + +DT_PLOTTER: Final = 0 +DT_RASDISPLAY: Final = 1 +DT_RASPRINTER: Final = 2 +DT_RASCAMERA: Final = 3 +DT_CHARSTREAM: Final = 4 +DT_METAFILE: Final = 5 +DT_DISPFILE: Final = 6 +CC_NONE: Final = 0 +CC_CIRCLES: Final = 1 +CC_PIE: Final = 2 +CC_CHORD: Final = 4 +CC_ELLIPSES: Final = 8 +CC_WIDE: Final = 16 +CC_STYLED: Final = 32 +CC_WIDESTYLED: Final = 64 +CC_INTERIORS: Final = 128 +CC_ROUNDRECT: Final = 256 +LC_NONE: Final = 0 +LC_POLYLINE: Final = 2 +LC_MARKER: Final = 4 +LC_POLYMARKER: Final = 8 +LC_WIDE: Final = 16 +LC_STYLED: Final = 32 +LC_WIDESTYLED: Final = 64 +LC_INTERIORS: Final = 128 +PC_NONE: Final = 0 +PC_POLYGON: Final = 1 +PC_RECTANGLE: Final = 2 +PC_WINDPOLYGON: Final = 4 +PC_TRAPEZOID: Final = 4 +PC_SCANLINE: Final = 8 +PC_WIDE: Final = 16 +PC_STYLED: Final = 32 +PC_WIDESTYLED: Final = 64 +PC_INTERIORS: Final = 128 +CP_NONE: Final = 0 +CP_RECTANGLE: Final = 1 +CP_REGION: Final = 2 +TC_OP_CHARACTER: Final = 1 +TC_OP_STROKE: Final = 2 +TC_CP_STROKE: Final = 4 +TC_CR_90: Final = 8 +TC_CR_ANY: Final = 16 +TC_SF_X_YINDEP: Final = 32 +TC_SA_DOUBLE: Final = 64 +TC_SA_INTEGER: Final = 128 +TC_SA_CONTIN: Final = 256 +TC_EA_DOUBLE: Final = 512 +TC_IA_ABLE: Final = 1024 +TC_UA_ABLE: Final = 2048 +TC_SO_ABLE: Final = 4096 +TC_RA_ABLE: Final = 8192 +TC_VA_ABLE: Final = 16384 +TC_RESERVED: Final = 32768 +TC_SCROLLBLT: Final = 65536 +RC_BITBLT: Final = 1 +RC_BANDING: Final = 2 +RC_SCALING: Final = 4 +RC_BITMAP64: Final = 8 +RC_GDI20_OUTPUT: Final = 16 +RC_GDI20_STATE: Final = 32 +RC_SAVEBITMAP: Final = 64 +RC_DI_BITMAP: Final = 128 +RC_PALETTE: Final = 256 +RC_DIBTODEV: Final = 512 +RC_BIGFONT: Final = 1024 +RC_STRETCHBLT: Final = 2048 +RC_FLOODFILL: Final = 4096 +RC_STRETCHDIB: Final = 8192 +RC_OP_DX_OUTPUT: Final = 16384 +RC_DEVBITS: Final = 32768 +DIB_RGB_COLORS: Final = 0 +DIB_PAL_COLORS: Final = 1 +DIB_PAL_INDICES: Final = 2 +DIB_PAL_PHYSINDICES: Final = 2 +DIB_PAL_LOGINDICES: Final = 4 +SYSPAL_ERROR: Final = 0 +SYSPAL_STATIC: Final = 1 +SYSPAL_NOSTATIC: Final = 2 +CBM_CREATEDIB: Final = 2 +CBM_INIT: Final = 4 +FLOODFILLBORDER: Final = 0 +FLOODFILLSURFACE: Final = 1 +CCHFORMNAME: Final = 32 + +DM_SPECVERSION: Final = 800 +DM_ORIENTATION: Final = 1 +DM_PAPERSIZE: Final = 2 +DM_PAPERLENGTH: Final = 4 +DM_PAPERWIDTH: Final = 8 +DM_SCALE: Final = 16 +DM_POSITION: Final = 32 +DM_NUP: Final = 64 +DM_DISPLAYORIENTATION: Final = 128 +DM_COPIES: Final = 256 +DM_DEFAULTSOURCE: Final = 512 +DM_PRINTQUALITY: Final = 1024 +DM_COLOR: Final = 2048 +DM_DUPLEX: Final = 4096 +DM_YRESOLUTION: Final = 8192 +DM_TTOPTION: Final = 16384 +DM_COLLATE: Final = 32768 +DM_FORMNAME: Final = 65536 +DM_LOGPIXELS: Final = 131072 +DM_BITSPERPEL: Final = 262144 +DM_PELSWIDTH: Final = 524288 +DM_PELSHEIGHT: Final = 1048576 +DM_DISPLAYFLAGS: Final = 2097152 +DM_DISPLAYFREQUENCY: Final = 4194304 +DM_ICMMETHOD: Final = 8388608 +DM_ICMINTENT: Final = 16777216 +DM_MEDIATYPE: Final = 33554432 +DM_DITHERTYPE: Final = 67108864 +DM_PANNINGWIDTH: Final = 134217728 +DM_PANNINGHEIGHT: Final = 268435456 +DM_DISPLAYFIXEDOUTPUT: Final = 536870912 + +DMORIENT_PORTRAIT: Final = 1 +DMORIENT_LANDSCAPE: Final = 2 + +DMDO_DEFAULT: Final = 0 +DMDO_90: Final = 1 +DMDO_180: Final = 2 +DMDO_270: Final = 3 + +DMDFO_DEFAULT: Final = 0 +DMDFO_STRETCH: Final = 1 +DMDFO_CENTER: Final = 2 + +DMPAPER_LETTER: Final = 1 +DMPAPER_LETTERSMALL: Final = 2 +DMPAPER_TABLOID: Final = 3 +DMPAPER_LEDGER: Final = 4 +DMPAPER_LEGAL: Final = 5 +DMPAPER_STATEMENT: Final = 6 +DMPAPER_EXECUTIVE: Final = 7 +DMPAPER_A3: Final = 8 +DMPAPER_A4: Final = 9 +DMPAPER_A4SMALL: Final = 10 +DMPAPER_A5: Final = 11 +DMPAPER_B4: Final = 12 +DMPAPER_B5: Final = 13 +DMPAPER_FOLIO: Final = 14 +DMPAPER_QUARTO: Final = 15 +DMPAPER_10X14: Final = 16 +DMPAPER_11X17: Final = 17 +DMPAPER_NOTE: Final = 18 +DMPAPER_ENV_9: Final = 19 +DMPAPER_ENV_10: Final = 20 +DMPAPER_ENV_11: Final = 21 +DMPAPER_ENV_12: Final = 22 +DMPAPER_ENV_14: Final = 23 +DMPAPER_CSHEET: Final = 24 +DMPAPER_DSHEET: Final = 25 +DMPAPER_ESHEET: Final = 26 +DMPAPER_ENV_DL: Final = 27 +DMPAPER_ENV_C5: Final = 28 +DMPAPER_ENV_C3: Final = 29 +DMPAPER_ENV_C4: Final = 30 +DMPAPER_ENV_C6: Final = 31 +DMPAPER_ENV_C65: Final = 32 +DMPAPER_ENV_B4: Final = 33 +DMPAPER_ENV_B5: Final = 34 +DMPAPER_ENV_B6: Final = 35 +DMPAPER_ENV_ITALY: Final = 36 +DMPAPER_ENV_MONARCH: Final = 37 +DMPAPER_ENV_PERSONAL: Final = 38 +DMPAPER_FANFOLD_US: Final = 39 +DMPAPER_FANFOLD_STD_GERMAN: Final = 40 +DMPAPER_FANFOLD_LGL_GERMAN: Final = 41 +DMPAPER_ISO_B4: Final = 42 +DMPAPER_JAPANESE_POSTCARD: Final = 43 +DMPAPER_9X11: Final = 44 +DMPAPER_10X11: Final = 45 +DMPAPER_15X11: Final = 46 +DMPAPER_ENV_INVITE: Final = 47 +DMPAPER_RESERVED_48: Final = 48 +DMPAPER_RESERVED_49: Final = 49 +DMPAPER_LETTER_EXTRA: Final = 50 +DMPAPER_LEGAL_EXTRA: Final = 51 +DMPAPER_TABLOID_EXTRA: Final = 52 +DMPAPER_A4_EXTRA: Final = 53 +DMPAPER_LETTER_TRANSVERSE: Final = 54 +DMPAPER_A4_TRANSVERSE: Final = 55 +DMPAPER_LETTER_EXTRA_TRANSVERSE: Final = 56 +DMPAPER_A_PLUS: Final = 57 +DMPAPER_B_PLUS: Final = 58 +DMPAPER_LETTER_PLUS: Final = 59 +DMPAPER_A4_PLUS: Final = 60 +DMPAPER_A5_TRANSVERSE: Final = 61 +DMPAPER_B5_TRANSVERSE: Final = 62 +DMPAPER_A3_EXTRA: Final = 63 +DMPAPER_A5_EXTRA: Final = 64 +DMPAPER_B5_EXTRA: Final = 65 +DMPAPER_A2: Final = 66 +DMPAPER_A3_TRANSVERSE: Final = 67 +DMPAPER_A3_EXTRA_TRANSVERSE: Final = 68 +DMPAPER_DBL_JAPANESE_POSTCARD: Final = 69 +DMPAPER_A6: Final = 70 +DMPAPER_JENV_KAKU2: Final = 71 +DMPAPER_JENV_KAKU3: Final = 72 +DMPAPER_JENV_CHOU3: Final = 73 +DMPAPER_JENV_CHOU4: Final = 74 +DMPAPER_LETTER_ROTATED: Final = 75 +DMPAPER_A3_ROTATED: Final = 76 +DMPAPER_A4_ROTATED: Final = 77 +DMPAPER_A5_ROTATED: Final = 78 +DMPAPER_B4_JIS_ROTATED: Final = 79 +DMPAPER_B5_JIS_ROTATED: Final = 80 +DMPAPER_JAPANESE_POSTCARD_ROTATED: Final = 81 +DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED: Final = 82 +DMPAPER_A6_ROTATED: Final = 83 +DMPAPER_JENV_KAKU2_ROTATED: Final = 84 +DMPAPER_JENV_KAKU3_ROTATED: Final = 85 +DMPAPER_JENV_CHOU3_ROTATED: Final = 86 +DMPAPER_JENV_CHOU4_ROTATED: Final = 87 +DMPAPER_B6_JIS: Final = 88 +DMPAPER_B6_JIS_ROTATED: Final = 89 +DMPAPER_12X11: Final = 90 +DMPAPER_JENV_YOU4: Final = 91 +DMPAPER_JENV_YOU4_ROTATED: Final = 92 +DMPAPER_P16K: Final = 93 +DMPAPER_P32K: Final = 94 +DMPAPER_P32KBIG: Final = 95 +DMPAPER_PENV_1: Final = 96 +DMPAPER_PENV_2: Final = 97 +DMPAPER_PENV_3: Final = 98 +DMPAPER_PENV_4: Final = 99 +DMPAPER_PENV_5: Final = 100 +DMPAPER_PENV_6: Final = 101 +DMPAPER_PENV_7: Final = 102 +DMPAPER_PENV_8: Final = 103 +DMPAPER_PENV_9: Final = 104 +DMPAPER_PENV_10: Final = 105 +DMPAPER_P16K_ROTATED: Final = 106 +DMPAPER_P32K_ROTATED: Final = 107 +DMPAPER_P32KBIG_ROTATED: Final = 108 +DMPAPER_PENV_1_ROTATED: Final = 109 +DMPAPER_PENV_2_ROTATED: Final = 110 +DMPAPER_PENV_3_ROTATED: Final = 111 +DMPAPER_PENV_4_ROTATED: Final = 112 +DMPAPER_PENV_5_ROTATED: Final = 113 +DMPAPER_PENV_6_ROTATED: Final = 114 +DMPAPER_PENV_7_ROTATED: Final = 115 +DMPAPER_PENV_8_ROTATED: Final = 116 +DMPAPER_PENV_9_ROTATED: Final = 117 +DMPAPER_PENV_10_ROTATED: Final = 118 +DMPAPER_LAST: Final = DMPAPER_PENV_10_ROTATED +DMPAPER_USER: Final = 256 + +DMBIN_UPPER: Final = 1 +DMBIN_ONLYONE: Final = 1 +DMBIN_LOWER: Final = 2 +DMBIN_MIDDLE: Final = 3 +DMBIN_MANUAL: Final = 4 +DMBIN_ENVELOPE: Final = 5 +DMBIN_ENVMANUAL: Final = 6 +DMBIN_AUTO: Final = 7 +DMBIN_TRACTOR: Final = 8 +DMBIN_SMALLFMT: Final = 9 +DMBIN_LARGEFMT: Final = 10 +DMBIN_LARGECAPACITY: Final = 11 +DMBIN_CASSETTE: Final = 14 +DMBIN_FORMSOURCE: Final = 15 +DMBIN_LAST: Final = DMBIN_FORMSOURCE +DMBIN_USER: Final = 256 + +DMRES_DRAFT: Final = -1 +DMRES_LOW: Final = -2 +DMRES_MEDIUM: Final = -3 +DMRES_HIGH: Final = -4 + +DMCOLOR_MONOCHROME: Final = 1 +DMCOLOR_COLOR: Final = 2 + +DMDUP_SIMPLEX: Final = 1 +DMDUP_VERTICAL: Final = 2 +DMDUP_HORIZONTAL: Final = 3 + +DMTT_BITMAP: Final = 1 +DMTT_DOWNLOAD: Final = 2 +DMTT_SUBDEV: Final = 3 +DMTT_DOWNLOAD_OUTLINE: Final = 4 + +DMCOLLATE_FALSE: Final = 0 +DMCOLLATE_TRUE: Final = 1 + +DM_GRAYSCALE: Final = 1 +DM_INTERLACED: Final = 2 + +DMICMMETHOD_NONE: Final = 1 +DMICMMETHOD_SYSTEM: Final = 2 +DMICMMETHOD_DRIVER: Final = 3 +DMICMMETHOD_DEVICE: Final = 4 +DMICMMETHOD_USER: Final = 256 + +DMICM_SATURATE: Final = 1 +DMICM_CONTRAST: Final = 2 +DMICM_COLORIMETRIC: Final = 3 +DMICM_ABS_COLORIMETRIC: Final = 4 +DMICM_USER: Final = 256 + +DMMEDIA_STANDARD: Final = 1 +DMMEDIA_TRANSPARENCY: Final = 2 +DMMEDIA_GLOSSY: Final = 3 +DMMEDIA_USER: Final = 256 + +DMDITHER_NONE: Final = 1 +DMDITHER_COARSE: Final = 2 +DMDITHER_FINE: Final = 3 +DMDITHER_LINEART: Final = 4 +DMDITHER_ERRORDIFFUSION: Final = 5 +DMDITHER_RESERVED6: Final = 6 +DMDITHER_RESERVED7: Final = 7 +DMDITHER_RESERVED8: Final = 8 +DMDITHER_RESERVED9: Final = 9 +DMDITHER_GRAYSCALE: Final = 10 +DMDITHER_USER: Final = 256 + +DMNUP_SYSTEM: Final = 1 +DMNUP_ONEUP: Final = 2 + +FEATURESETTING_NUP: Final = 0 +FEATURESETTING_OUTPUT: Final = 1 +FEATURESETTING_PSLEVEL: Final = 2 +FEATURESETTING_CUSTPAPER: Final = 3 +FEATURESETTING_MIRROR: Final = 4 +FEATURESETTING_NEGATIVE: Final = 5 +FEATURESETTING_PROTOCOL: Final = 6 +FEATURESETTING_PRIVATE_BEGIN: Final = 0x1000 +FEATURESETTING_PRIVATE_END: Final = 0x1FFF + +RDH_RECTANGLES: Final = 1 +GGO_METRICS: Final = 0 +GGO_BITMAP: Final = 1 +GGO_NATIVE: Final = 2 +TT_POLYGON_TYPE: Final = 24 +TT_PRIM_LINE: Final = 1 +TT_PRIM_QSPLINE: Final = 2 +TT_AVAILABLE: Final = 1 +TT_ENABLED: Final = 2 +DM_UPDATE: Final = 1 +DM_COPY: Final = 2 +DM_PROMPT: Final = 4 +DM_MODIFY: Final = 8 +DM_IN_BUFFER: Final = DM_MODIFY +DM_IN_PROMPT: Final = DM_PROMPT +DM_OUT_BUFFER: Final = DM_COPY +DM_OUT_DEFAULT: Final = DM_UPDATE + +DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: Final = 1 +DISPLAY_DEVICE_MULTI_DRIVER: Final = 2 +DISPLAY_DEVICE_PRIMARY_DEVICE: Final = 4 +DISPLAY_DEVICE_MIRRORING_DRIVER: Final = 8 +DISPLAY_DEVICE_VGA_COMPATIBLE: Final = 16 +DISPLAY_DEVICE_REMOVABLE: Final = 32 +DISPLAY_DEVICE_MODESPRUNED: Final = 134217728 +DISPLAY_DEVICE_REMOTE: Final = 67108864 +DISPLAY_DEVICE_DISCONNECT: Final = 33554432 + +DC_FIELDS: Final = 1 +DC_PAPERS: Final = 2 +DC_PAPERSIZE: Final = 3 +DC_MINEXTENT: Final = 4 +DC_MAXEXTENT: Final = 5 +DC_BINS: Final = 6 +DC_DUPLEX: Final = 7 +DC_SIZE: Final = 8 +DC_EXTRA: Final = 9 +DC_VERSION: Final = 10 +DC_DRIVER: Final = 11 +DC_BINNAMES: Final = 12 +DC_ENUMRESOLUTIONS: Final = 13 +DC_FILEDEPENDENCIES: Final = 14 +DC_TRUETYPE: Final = 15 +DC_PAPERNAMES: Final = 16 +DC_ORIENTATION: Final = 17 +DC_COPIES: Final = 18 +DC_BINADJUST: Final = 19 +DC_EMF_COMPLIANT: Final = 20 +DC_DATATYPE_PRODUCED: Final = 21 +DC_COLLATE: Final = 22 +DC_MANUFACTURER: Final = 23 +DC_MODEL: Final = 24 +DC_PERSONALITY: Final = 25 +DC_PRINTRATE: Final = 26 +DC_PRINTRATEUNIT: Final = 27 +DC_PRINTERMEM: Final = 28 +DC_MEDIAREADY: Final = 29 +DC_STAPLE: Final = 30 +DC_PRINTRATEPPM: Final = 31 +DC_COLORDEVICE: Final = 32 +DC_NUP: Final = 33 +DC_MEDIATYPENAMES: Final = 34 +DC_MEDIATYPES: Final = 35 + +PRINTRATEUNIT_PPM: Final = 1 +PRINTRATEUNIT_CPS: Final = 2 +PRINTRATEUNIT_LPM: Final = 3 +PRINTRATEUNIT_IPM: Final = 4 + +DCTT_BITMAP: Final = 1 +DCTT_DOWNLOAD: Final = 2 +DCTT_SUBDEV: Final = 4 +DCTT_DOWNLOAD_OUTLINE: Final = 8 + +DCBA_FACEUPNONE: Final = 0 +DCBA_FACEUPCENTER: Final = 1 +DCBA_FACEUPLEFT: Final = 2 +DCBA_FACEUPRIGHT: Final = 3 +DCBA_FACEDOWNNONE: Final = 256 +DCBA_FACEDOWNCENTER: Final = 257 +DCBA_FACEDOWNLEFT: Final = 258 +DCBA_FACEDOWNRIGHT: Final = 259 + +CA_NEGATIVE: Final = 1 +CA_LOG_FILTER: Final = 2 +ILLUMINANT_DEVICE_DEFAULT: Final = 0 +ILLUMINANT_A: Final = 1 +ILLUMINANT_B: Final = 2 +ILLUMINANT_C: Final = 3 +ILLUMINANT_D50: Final = 4 +ILLUMINANT_D55: Final = 5 +ILLUMINANT_D65: Final = 6 +ILLUMINANT_D75: Final = 7 +ILLUMINANT_F2: Final = 8 +ILLUMINANT_MAX_INDEX: Final = ILLUMINANT_F2 +ILLUMINANT_TUNGSTEN: Final = ILLUMINANT_A +ILLUMINANT_DAYLIGHT: Final = ILLUMINANT_C +ILLUMINANT_FLUORESCENT: Final = ILLUMINANT_F2 +ILLUMINANT_NTSC: Final = ILLUMINANT_C + +FONTMAPPER_MAX: Final = 10 +ENHMETA_SIGNATURE: Final = 1179469088 +ENHMETA_STOCK_OBJECT: Final = -2147483648 +EMR_HEADER: Final = 1 +EMR_POLYBEZIER: Final = 2 +EMR_POLYGON: Final = 3 +EMR_POLYLINE: Final = 4 +EMR_POLYBEZIERTO: Final = 5 +EMR_POLYLINETO: Final = 6 +EMR_POLYPOLYLINE: Final = 7 +EMR_POLYPOLYGON: Final = 8 +EMR_SETWINDOWEXTEX: Final = 9 +EMR_SETWINDOWORGEX: Final = 10 +EMR_SETVIEWPORTEXTEX: Final = 11 +EMR_SETVIEWPORTORGEX: Final = 12 +EMR_SETBRUSHORGEX: Final = 13 +EMR_EOF: Final = 14 +EMR_SETPIXELV: Final = 15 +EMR_SETMAPPERFLAGS: Final = 16 +EMR_SETMAPMODE: Final = 17 +EMR_SETBKMODE: Final = 18 +EMR_SETPOLYFILLMODE: Final = 19 +EMR_SETROP2: Final = 20 +EMR_SETSTRETCHBLTMODE: Final = 21 +EMR_SETTEXTALIGN: Final = 22 +EMR_SETCOLORADJUSTMENT: Final = 23 +EMR_SETTEXTCOLOR: Final = 24 +EMR_SETBKCOLOR: Final = 25 +EMR_OFFSETCLIPRGN: Final = 26 +EMR_MOVETOEX: Final = 27 +EMR_SETMETARGN: Final = 28 +EMR_EXCLUDECLIPRECT: Final = 29 +EMR_INTERSECTCLIPRECT: Final = 30 +EMR_SCALEVIEWPORTEXTEX: Final = 31 +EMR_SCALEWINDOWEXTEX: Final = 32 +EMR_SAVEDC: Final = 33 +EMR_RESTOREDC: Final = 34 +EMR_SETWORLDTRANSFORM: Final = 35 +EMR_MODIFYWORLDTRANSFORM: Final = 36 +EMR_SELECTOBJECT: Final = 37 +EMR_CREATEPEN: Final = 38 +EMR_CREATEBRUSHINDIRECT: Final = 39 +EMR_DELETEOBJECT: Final = 40 +EMR_ANGLEARC: Final = 41 +EMR_ELLIPSE: Final = 42 +EMR_RECTANGLE: Final = 43 +EMR_ROUNDRECT: Final = 44 +EMR_ARC: Final = 45 +EMR_CHORD: Final = 46 +EMR_PIE: Final = 47 +EMR_SELECTPALETTE: Final = 48 +EMR_CREATEPALETTE: Final = 49 +EMR_SETPALETTEENTRIES: Final = 50 +EMR_RESIZEPALETTE: Final = 51 +EMR_REALIZEPALETTE: Final = 52 +EMR_EXTFLOODFILL: Final = 53 +EMR_LINETO: Final = 54 +EMR_ARCTO: Final = 55 +EMR_POLYDRAW: Final = 56 +EMR_SETARCDIRECTION: Final = 57 +EMR_SETMITERLIMIT: Final = 58 +EMR_BEGINPATH: Final = 59 +EMR_ENDPATH: Final = 60 +EMR_CLOSEFIGURE: Final = 61 +EMR_FILLPATH: Final = 62 +EMR_STROKEANDFILLPATH: Final = 63 +EMR_STROKEPATH: Final = 64 +EMR_FLATTENPATH: Final = 65 +EMR_WIDENPATH: Final = 66 +EMR_SELECTCLIPPATH: Final = 67 +EMR_ABORTPATH: Final = 68 +EMR_GDICOMMENT: Final = 70 +EMR_FILLRGN: Final = 71 +EMR_FRAMERGN: Final = 72 +EMR_INVERTRGN: Final = 73 +EMR_PAINTRGN: Final = 74 +EMR_EXTSELECTCLIPRGN: Final = 75 +EMR_BITBLT: Final = 76 +EMR_STRETCHBLT: Final = 77 +EMR_MASKBLT: Final = 78 +EMR_PLGBLT: Final = 79 +EMR_SETDIBITSTODEVICE: Final = 80 +EMR_STRETCHDIBITS: Final = 81 +EMR_EXTCREATEFONTINDIRECTW: Final = 82 +EMR_EXTTEXTOUTA: Final = 83 +EMR_EXTTEXTOUTW: Final = 84 +EMR_POLYBEZIER16: Final = 85 +EMR_POLYGON16: Final = 86 +EMR_POLYLINE16: Final = 87 +EMR_POLYBEZIERTO16: Final = 88 +EMR_POLYLINETO16: Final = 89 +EMR_POLYPOLYLINE16: Final = 90 +EMR_POLYPOLYGON16: Final = 91 +EMR_POLYDRAW16: Final = 92 +EMR_CREATEMONOBRUSH: Final = 93 +EMR_CREATEDIBPATTERNBRUSHPT: Final = 94 +EMR_EXTCREATEPEN: Final = 95 +EMR_POLYTEXTOUTA: Final = 96 +EMR_POLYTEXTOUTW: Final = 97 +EMR_MIN: Final = 1 +EMR_MAX: Final = 97 + +PANOSE_COUNT: Final = 10 +PAN_FAMILYTYPE_INDEX: Final = 0 +PAN_SERIFSTYLE_INDEX: Final = 1 +PAN_WEIGHT_INDEX: Final = 2 +PAN_PROPORTION_INDEX: Final = 3 +PAN_CONTRAST_INDEX: Final = 4 +PAN_STROKEVARIATION_INDEX: Final = 5 +PAN_ARMSTYLE_INDEX: Final = 6 +PAN_LETTERFORM_INDEX: Final = 7 +PAN_MIDLINE_INDEX: Final = 8 +PAN_XHEIGHT_INDEX: Final = 9 +PAN_CULTURE_LATIN: Final = 0 +PAN_ANY: Final = 0 +PAN_NO_FIT: Final = 1 +PAN_FAMILY_TEXT_DISPLAY: Final = 2 +PAN_FAMILY_SCRIPT: Final = 3 +PAN_FAMILY_DECORATIVE: Final = 4 +PAN_FAMILY_PICTORIAL: Final = 5 +PAN_SERIF_COVE: Final = 2 +PAN_SERIF_OBTUSE_COVE: Final = 3 +PAN_SERIF_SQUARE_COVE: Final = 4 +PAN_SERIF_OBTUSE_SQUARE_COVE: Final = 5 +PAN_SERIF_SQUARE: Final = 6 +PAN_SERIF_THIN: Final = 7 +PAN_SERIF_BONE: Final = 8 +PAN_SERIF_EXAGGERATED: Final = 9 +PAN_SERIF_TRIANGLE: Final = 10 +PAN_SERIF_NORMAL_SANS: Final = 11 +PAN_SERIF_OBTUSE_SANS: Final = 12 +PAN_SERIF_PERP_SANS: Final = 13 +PAN_SERIF_FLARED: Final = 14 +PAN_SERIF_ROUNDED: Final = 15 +PAN_WEIGHT_VERY_LIGHT: Final = 2 +PAN_WEIGHT_LIGHT: Final = 3 +PAN_WEIGHT_THIN: Final = 4 +PAN_WEIGHT_BOOK: Final = 5 +PAN_WEIGHT_MEDIUM: Final = 6 +PAN_WEIGHT_DEMI: Final = 7 +PAN_WEIGHT_BOLD: Final = 8 +PAN_WEIGHT_HEAVY: Final = 9 +PAN_WEIGHT_BLACK: Final = 10 +PAN_WEIGHT_NORD: Final = 11 +PAN_PROP_OLD_STYLE: Final = 2 +PAN_PROP_MODERN: Final = 3 +PAN_PROP_EVEN_WIDTH: Final = 4 +PAN_PROP_EXPANDED: Final = 5 +PAN_PROP_CONDENSED: Final = 6 +PAN_PROP_VERY_EXPANDED: Final = 7 +PAN_PROP_VERY_CONDENSED: Final = 8 +PAN_PROP_MONOSPACED: Final = 9 +PAN_CONTRAST_NONE: Final = 2 +PAN_CONTRAST_VERY_LOW: Final = 3 +PAN_CONTRAST_LOW: Final = 4 +PAN_CONTRAST_MEDIUM_LOW: Final = 5 +PAN_CONTRAST_MEDIUM: Final = 6 +PAN_CONTRAST_MEDIUM_HIGH: Final = 7 +PAN_CONTRAST_HIGH: Final = 8 +PAN_CONTRAST_VERY_HIGH: Final = 9 +PAN_STROKE_GRADUAL_DIAG: Final = 2 +PAN_STROKE_GRADUAL_TRAN: Final = 3 +PAN_STROKE_GRADUAL_VERT: Final = 4 +PAN_STROKE_GRADUAL_HORZ: Final = 5 +PAN_STROKE_RAPID_VERT: Final = 6 +PAN_STROKE_RAPID_HORZ: Final = 7 +PAN_STROKE_INSTANT_VERT: Final = 8 +PAN_STRAIGHT_ARMS_HORZ: Final = 2 +PAN_STRAIGHT_ARMS_WEDGE: Final = 3 +PAN_STRAIGHT_ARMS_VERT: Final = 4 +PAN_STRAIGHT_ARMS_SINGLE_SERIF: Final = 5 +PAN_STRAIGHT_ARMS_DOUBLE_SERIF: Final = 6 +PAN_BENT_ARMS_HORZ: Final = 7 +PAN_BENT_ARMS_WEDGE: Final = 8 +PAN_BENT_ARMS_VERT: Final = 9 +PAN_BENT_ARMS_SINGLE_SERIF: Final = 10 +PAN_BENT_ARMS_DOUBLE_SERIF: Final = 11 +PAN_LETT_NORMAL_CONTACT: Final = 2 +PAN_LETT_NORMAL_WEIGHTED: Final = 3 +PAN_LETT_NORMAL_BOXED: Final = 4 +PAN_LETT_NORMAL_FLATTENED: Final = 5 +PAN_LETT_NORMAL_ROUNDED: Final = 6 +PAN_LETT_NORMAL_OFF_CENTER: Final = 7 +PAN_LETT_NORMAL_SQUARE: Final = 8 +PAN_LETT_OBLIQUE_CONTACT: Final = 9 +PAN_LETT_OBLIQUE_WEIGHTED: Final = 10 +PAN_LETT_OBLIQUE_BOXED: Final = 11 +PAN_LETT_OBLIQUE_FLATTENED: Final = 12 +PAN_LETT_OBLIQUE_ROUNDED: Final = 13 +PAN_LETT_OBLIQUE_OFF_CENTER: Final = 14 +PAN_LETT_OBLIQUE_SQUARE: Final = 15 +PAN_MIDLINE_STANDARD_TRIMMED: Final = 2 +PAN_MIDLINE_STANDARD_POINTED: Final = 3 +PAN_MIDLINE_STANDARD_SERIFED: Final = 4 +PAN_MIDLINE_HIGH_TRIMMED: Final = 5 +PAN_MIDLINE_HIGH_POINTED: Final = 6 +PAN_MIDLINE_HIGH_SERIFED: Final = 7 +PAN_MIDLINE_CONSTANT_TRIMMED: Final = 8 +PAN_MIDLINE_CONSTANT_POINTED: Final = 9 +PAN_MIDLINE_CONSTANT_SERIFED: Final = 10 +PAN_MIDLINE_LOW_TRIMMED: Final = 11 +PAN_MIDLINE_LOW_POINTED: Final = 12 +PAN_MIDLINE_LOW_SERIFED: Final = 13 +PAN_XHEIGHT_CONSTANT_SMALL: Final = 2 +PAN_XHEIGHT_CONSTANT_STD: Final = 3 +PAN_XHEIGHT_CONSTANT_LARGE: Final = 4 +PAN_XHEIGHT_DUCKING_SMALL: Final = 5 +PAN_XHEIGHT_DUCKING_STD: Final = 6 +PAN_XHEIGHT_DUCKING_LARGE: Final = 7 +ELF_VENDOR_SIZE: Final = 4 +ELF_VERSION: Final = 0 +ELF_CULTURE_LATIN: Final = 0 +RASTER_FONTTYPE: Final = 1 +DEVICE_FONTTYPE: Final = 2 +TRUETYPE_FONTTYPE: Final = 4 + +def PALETTEINDEX(i: int) -> int: ... + +PC_RESERVED: Final = 1 +PC_EXPLICIT: Final = 2 +PC_NOCOLLAPSE: Final = 4 + +def GetRValue(rgb: int) -> int: ... +def GetGValue(rgb: int) -> int: ... +def GetBValue(rgb: int) -> int: ... + +TRANSPARENT: Final = 1 +OPAQUE: Final = 2 +BKMODE_LAST: Final = 2 +GM_COMPATIBLE: Final = 1 +GM_ADVANCED: Final = 2 +GM_LAST: Final = 2 +PT_CLOSEFIGURE: Final = 1 +PT_LINETO: Final = 2 +PT_BEZIERTO: Final = 4 +PT_MOVETO: Final = 6 +MM_TEXT: Final = 1 +MM_LOMETRIC: Final = 2 +MM_HIMETRIC: Final = 3 +MM_LOENGLISH: Final = 4 +MM_HIENGLISH: Final = 5 +MM_TWIPS: Final = 6 +MM_ISOTROPIC: Final = 7 +MM_ANISOTROPIC: Final = 8 +MM_MIN: Final = MM_TEXT +MM_MAX: Final = MM_ANISOTROPIC +MM_MAX_FIXEDSCALE: Final = MM_TWIPS +ABSOLUTE: Final = 1 +RELATIVE: Final = 2 +WHITE_BRUSH: Final = 0 +LTGRAY_BRUSH: Final = 1 +GRAY_BRUSH: Final = 2 +DKGRAY_BRUSH: Final = 3 +BLACK_BRUSH: Final = 4 +NULL_BRUSH: Final = 5 +HOLLOW_BRUSH: Final = NULL_BRUSH +WHITE_PEN: Final = 6 +BLACK_PEN: Final = 7 +NULL_PEN: Final = 8 +OEM_FIXED_FONT: Final = 10 +ANSI_FIXED_FONT: Final = 11 +ANSI_VAR_FONT: Final = 12 +SYSTEM_FONT: Final = 13 +DEVICE_DEFAULT_FONT: Final = 14 +DEFAULT_PALETTE: Final = 15 +SYSTEM_FIXED_FONT: Final = 16 +STOCK_LAST: Final = 16 +CLR_INVALID: Final = -1 + +DC_BRUSH: Final = 18 +DC_PEN: Final = 19 + +STATUS_WAIT_0: Final = 0 +STATUS_ABANDONED_WAIT_0: Final = 128 +STATUS_USER_APC: Final = 192 +STATUS_TIMEOUT: Final = 258 +STATUS_PENDING: Final = 259 +STATUS_SEGMENT_NOTIFICATION: Final = 1073741829 +STATUS_GUARD_PAGE_VIOLATION: Final = -2147483647 +STATUS_DATATYPE_MISALIGNMENT: Final = -2147483646 +STATUS_BREAKPOINT: Final = -2147483645 +STATUS_SINGLE_STEP: Final = -2147483644 +STATUS_ACCESS_VIOLATION: Final = -1073741819 +STATUS_IN_PAGE_ERROR: Final = -1073741818 +STATUS_INVALID_HANDLE: Final = -1073741816 +STATUS_NO_MEMORY: Final = -1073741801 +STATUS_ILLEGAL_INSTRUCTION: Final = -1073741795 +STATUS_NONCONTINUABLE_EXCEPTION: Final = -1073741787 +STATUS_INVALID_DISPOSITION: Final = -1073741786 +STATUS_ARRAY_BOUNDS_EXCEEDED: Final = -1073741684 +STATUS_FLOAT_DENORMAL_OPERAND: Final = -1073741683 +STATUS_FLOAT_DIVIDE_BY_ZERO: Final = -1073741682 +STATUS_FLOAT_INEXACT_RESULT: Final = -1073741681 +STATUS_FLOAT_INVALID_OPERATION: Final = -1073741680 +STATUS_FLOAT_OVERFLOW: Final = -1073741679 +STATUS_FLOAT_STACK_CHECK: Final = -1073741678 +STATUS_FLOAT_UNDERFLOW: Final = -1073741677 +STATUS_INTEGER_DIVIDE_BY_ZERO: Final = -1073741676 +STATUS_INTEGER_OVERFLOW: Final = -1073741675 +STATUS_PRIVILEGED_INSTRUCTION: Final = -1073741674 +STATUS_STACK_OVERFLOW: Final = -1073741571 +STATUS_CONTROL_C_EXIT: Final = -1073741510 + +WAIT_FAILED: Final = -1 +WAIT_OBJECT_0: Final[int] + +WAIT_ABANDONED: Final[int] +WAIT_ABANDONED_0: Final[int] + +WAIT_TIMEOUT: Final = STATUS_TIMEOUT +WAIT_IO_COMPLETION: Final = STATUS_USER_APC +STILL_ACTIVE: Final = STATUS_PENDING +EXCEPTION_ACCESS_VIOLATION: Final = STATUS_ACCESS_VIOLATION +EXCEPTION_DATATYPE_MISALIGNMENT: Final = STATUS_DATATYPE_MISALIGNMENT +EXCEPTION_BREAKPOINT: Final = STATUS_BREAKPOINT +EXCEPTION_SINGLE_STEP: Final = STATUS_SINGLE_STEP +EXCEPTION_ARRAY_BOUNDS_EXCEEDED: Final = STATUS_ARRAY_BOUNDS_EXCEEDED +EXCEPTION_FLT_DENORMAL_OPERAND: Final = STATUS_FLOAT_DENORMAL_OPERAND +EXCEPTION_FLT_DIVIDE_BY_ZERO: Final = STATUS_FLOAT_DIVIDE_BY_ZERO +EXCEPTION_FLT_INEXACT_RESULT: Final = STATUS_FLOAT_INEXACT_RESULT +EXCEPTION_FLT_INVALID_OPERATION: Final = STATUS_FLOAT_INVALID_OPERATION +EXCEPTION_FLT_OVERFLOW: Final = STATUS_FLOAT_OVERFLOW +EXCEPTION_FLT_STACK_CHECK: Final = STATUS_FLOAT_STACK_CHECK +EXCEPTION_FLT_UNDERFLOW: Final = STATUS_FLOAT_UNDERFLOW +EXCEPTION_INT_DIVIDE_BY_ZERO: Final = STATUS_INTEGER_DIVIDE_BY_ZERO +EXCEPTION_INT_OVERFLOW: Final = STATUS_INTEGER_OVERFLOW +EXCEPTION_PRIV_INSTRUCTION: Final = STATUS_PRIVILEGED_INSTRUCTION +EXCEPTION_IN_PAGE_ERROR: Final = STATUS_IN_PAGE_ERROR +EXCEPTION_ILLEGAL_INSTRUCTION: Final = STATUS_ILLEGAL_INSTRUCTION +EXCEPTION_NONCONTINUABLE_EXCEPTION: Final = STATUS_NONCONTINUABLE_EXCEPTION +EXCEPTION_STACK_OVERFLOW: Final = STATUS_STACK_OVERFLOW +EXCEPTION_INVALID_DISPOSITION: Final = STATUS_INVALID_DISPOSITION +EXCEPTION_GUARD_PAGE: Final = STATUS_GUARD_PAGE_VIOLATION +EXCEPTION_INVALID_HANDLE: Final = STATUS_INVALID_HANDLE +CONTROL_C_EXIT: Final = STATUS_CONTROL_C_EXIT + +SPI_GETBEEP: Final = 1 +SPI_SETBEEP: Final = 2 +SPI_GETMOUSE: Final = 3 +SPI_SETMOUSE: Final = 4 +SPI_GETBORDER: Final = 5 +SPI_SETBORDER: Final = 6 +SPI_GETKEYBOARDSPEED: Final = 10 +SPI_SETKEYBOARDSPEED: Final = 11 +SPI_LANGDRIVER: Final = 12 +SPI_ICONHORIZONTALSPACING: Final = 13 +SPI_GETSCREENSAVETIMEOUT: Final = 14 +SPI_SETSCREENSAVETIMEOUT: Final = 15 +SPI_GETSCREENSAVEACTIVE: Final = 16 +SPI_SETSCREENSAVEACTIVE: Final = 17 +SPI_GETGRIDGRANULARITY: Final = 18 +SPI_SETGRIDGRANULARITY: Final = 19 +SPI_SETDESKWALLPAPER: Final = 20 +SPI_SETDESKPATTERN: Final = 21 +SPI_GETKEYBOARDDELAY: Final = 22 +SPI_SETKEYBOARDDELAY: Final = 23 +SPI_ICONVERTICALSPACING: Final = 24 +SPI_GETICONTITLEWRAP: Final = 25 +SPI_SETICONTITLEWRAP: Final = 26 +SPI_GETMENUDROPALIGNMENT: Final = 27 +SPI_SETMENUDROPALIGNMENT: Final = 28 +SPI_SETDOUBLECLKWIDTH: Final = 29 +SPI_SETDOUBLECLKHEIGHT: Final = 30 +SPI_GETICONTITLELOGFONT: Final = 31 +SPI_SETDOUBLECLICKTIME: Final = 32 +SPI_SETMOUSEBUTTONSWAP: Final = 33 +SPI_SETICONTITLELOGFONT: Final = 34 +SPI_GETFASTTASKSWITCH: Final = 35 +SPI_SETFASTTASKSWITCH: Final = 36 +SPI_SETDRAGFULLWINDOWS: Final = 37 +SPI_GETDRAGFULLWINDOWS: Final = 38 +SPI_GETNONCLIENTMETRICS: Final = 41 +SPI_SETNONCLIENTMETRICS: Final = 42 +SPI_GETMINIMIZEDMETRICS: Final = 43 +SPI_SETMINIMIZEDMETRICS: Final = 44 +SPI_GETICONMETRICS: Final = 45 +SPI_SETICONMETRICS: Final = 46 +SPI_SETWORKAREA: Final = 47 +SPI_GETWORKAREA: Final = 48 +SPI_SETPENWINDOWS: Final = 49 +SPI_GETFILTERKEYS: Final = 50 +SPI_SETFILTERKEYS: Final = 51 +SPI_GETTOGGLEKEYS: Final = 52 +SPI_SETTOGGLEKEYS: Final = 53 +SPI_GETMOUSEKEYS: Final = 54 +SPI_SETMOUSEKEYS: Final = 55 +SPI_GETSHOWSOUNDS: Final = 56 +SPI_SETSHOWSOUNDS: Final = 57 +SPI_GETSTICKYKEYS: Final = 58 +SPI_SETSTICKYKEYS: Final = 59 +SPI_GETACCESSTIMEOUT: Final = 60 +SPI_SETACCESSTIMEOUT: Final = 61 +SPI_GETSERIALKEYS: Final = 62 +SPI_SETSERIALKEYS: Final = 63 +SPI_GETSOUNDSENTRY: Final = 64 +SPI_SETSOUNDSENTRY: Final = 65 +SPI_GETHIGHCONTRAST: Final = 66 +SPI_SETHIGHCONTRAST: Final = 67 +SPI_GETKEYBOARDPREF: Final = 68 +SPI_SETKEYBOARDPREF: Final = 69 +SPI_GETSCREENREADER: Final = 70 +SPI_SETSCREENREADER: Final = 71 +SPI_GETANIMATION: Final = 72 +SPI_SETANIMATION: Final = 73 +SPI_GETFONTSMOOTHING: Final = 74 +SPI_SETFONTSMOOTHING: Final = 75 +SPI_SETDRAGWIDTH: Final = 76 +SPI_SETDRAGHEIGHT: Final = 77 +SPI_SETHANDHELD: Final = 78 +SPI_GETLOWPOWERTIMEOUT: Final = 79 +SPI_GETPOWEROFFTIMEOUT: Final = 80 +SPI_SETLOWPOWERTIMEOUT: Final = 81 +SPI_SETPOWEROFFTIMEOUT: Final = 82 +SPI_GETLOWPOWERACTIVE: Final = 83 +SPI_GETPOWEROFFACTIVE: Final = 84 +SPI_SETLOWPOWERACTIVE: Final = 85 +SPI_SETPOWEROFFACTIVE: Final = 86 +SPI_SETCURSORS: Final = 87 +SPI_SETICONS: Final = 88 +SPI_GETDEFAULTINPUTLANG: Final = 89 +SPI_SETDEFAULTINPUTLANG: Final = 90 +SPI_SETLANGTOGGLE: Final = 91 +SPI_GETWINDOWSEXTENSION: Final = 92 +SPI_SETMOUSETRAILS: Final = 93 +SPI_GETMOUSETRAILS: Final = 94 +SPI_GETSNAPTODEFBUTTON: Final = 95 +SPI_SETSNAPTODEFBUTTON: Final = 96 +SPI_SETSCREENSAVERRUNNING: Final = 97 +SPI_SCREENSAVERRUNNING: Final = SPI_SETSCREENSAVERRUNNING +SPI_GETMOUSEHOVERWIDTH: Final = 98 +SPI_SETMOUSEHOVERWIDTH: Final = 99 +SPI_GETMOUSEHOVERHEIGHT: Final = 100 +SPI_SETMOUSEHOVERHEIGHT: Final = 101 +SPI_GETMOUSEHOVERTIME: Final = 102 +SPI_SETMOUSEHOVERTIME: Final = 103 +SPI_GETWHEELSCROLLLINES: Final = 104 +SPI_SETWHEELSCROLLLINES: Final = 105 +SPI_GETMENUSHOWDELAY: Final = 106 +SPI_SETMENUSHOWDELAY: Final = 107 + +SPI_GETSHOWIMEUI: Final = 110 +SPI_SETSHOWIMEUI: Final = 111 +SPI_GETMOUSESPEED: Final = 112 +SPI_SETMOUSESPEED: Final = 113 +SPI_GETSCREENSAVERRUNNING: Final = 114 +SPI_GETDESKWALLPAPER: Final = 115 + +SPI_GETACTIVEWINDOWTRACKING: Final = 4096 +SPI_SETACTIVEWINDOWTRACKING: Final = 4097 +SPI_GETMENUANIMATION: Final = 4098 +SPI_SETMENUANIMATION: Final = 4099 +SPI_GETCOMBOBOXANIMATION: Final = 4100 +SPI_SETCOMBOBOXANIMATION: Final = 4101 +SPI_GETLISTBOXSMOOTHSCROLLING: Final = 4102 +SPI_SETLISTBOXSMOOTHSCROLLING: Final = 4103 +SPI_GETGRADIENTCAPTIONS: Final = 4104 +SPI_SETGRADIENTCAPTIONS: Final = 4105 +SPI_GETKEYBOARDCUES: Final = 4106 +SPI_SETKEYBOARDCUES: Final = 4107 +SPI_GETMENUUNDERLINES: Final = 4106 +SPI_SETMENUUNDERLINES: Final = 4107 +SPI_GETACTIVEWNDTRKZORDER: Final = 4108 +SPI_SETACTIVEWNDTRKZORDER: Final = 4109 +SPI_GETHOTTRACKING: Final = 4110 +SPI_SETHOTTRACKING: Final = 4111 + +SPI_GETMENUFADE: Final = 4114 +SPI_SETMENUFADE: Final = 4115 +SPI_GETSELECTIONFADE: Final = 4116 +SPI_SETSELECTIONFADE: Final = 4117 +SPI_GETTOOLTIPANIMATION: Final = 4118 +SPI_SETTOOLTIPANIMATION: Final = 4119 +SPI_GETTOOLTIPFADE: Final = 4120 +SPI_SETTOOLTIPFADE: Final = 4121 +SPI_GETCURSORSHADOW: Final = 4122 +SPI_SETCURSORSHADOW: Final = 4123 +SPI_GETMOUSESONAR: Final = 4124 +SPI_SETMOUSESONAR: Final = 4125 +SPI_GETMOUSECLICKLOCK: Final = 4126 +SPI_SETMOUSECLICKLOCK: Final = 4127 +SPI_GETMOUSEVANISH: Final = 4128 +SPI_SETMOUSEVANISH: Final = 4129 +SPI_GETFLATMENU: Final = 4130 +SPI_SETFLATMENU: Final = 4131 +SPI_GETDROPSHADOW: Final = 4132 +SPI_SETDROPSHADOW: Final = 4133 +SPI_GETBLOCKSENDINPUTRESETS: Final = 4134 +SPI_SETBLOCKSENDINPUTRESETS: Final = 4135 +SPI_GETUIEFFECTS: Final = 4158 +SPI_SETUIEFFECTS: Final = 4159 + +SPI_GETFOREGROUNDLOCKTIMEOUT: Final = 8192 +SPI_SETFOREGROUNDLOCKTIMEOUT: Final = 8193 +SPI_GETACTIVEWNDTRKTIMEOUT: Final = 8194 +SPI_SETACTIVEWNDTRKTIMEOUT: Final = 8195 +SPI_GETFOREGROUNDFLASHCOUNT: Final = 8196 +SPI_SETFOREGROUNDFLASHCOUNT: Final = 8197 +SPI_GETCARETWIDTH: Final = 8198 +SPI_SETCARETWIDTH: Final = 8199 +SPI_GETMOUSECLICKLOCKTIME: Final = 8200 +SPI_SETMOUSECLICKLOCKTIME: Final = 8201 +SPI_GETFONTSMOOTHINGTYPE: Final = 8202 +SPI_SETFONTSMOOTHINGTYPE: Final = 8203 +SPI_GETFONTSMOOTHINGCONTRAST: Final = 8204 +SPI_SETFONTSMOOTHINGCONTRAST: Final = 8205 +SPI_GETFOCUSBORDERWIDTH: Final = 8206 +SPI_SETFOCUSBORDERWIDTH: Final = 8207 +SPI_GETFOCUSBORDERHEIGHT: Final = 8208 +SPI_SETFOCUSBORDERHEIGHT: Final = 8209 +SPI_GETFONTSMOOTHINGORIENTATION: Final = 8210 +SPI_SETFONTSMOOTHINGORIENTATION: Final = 8211 + +SPIF_UPDATEINIFILE: Final = 1 +SPIF_SENDWININICHANGE: Final = 2 +SPIF_SENDCHANGE: Final = SPIF_SENDWININICHANGE + +FE_FONTSMOOTHINGSTANDARD: Final = 1 +FE_FONTSMOOTHINGCLEARTYPE: Final = 2 +FE_FONTSMOOTHINGDOCKING: Final = 32768 + +METRICS_USEDEFAULT: Final = -1 +ARW_BOTTOMLEFT: Final = 0 +ARW_BOTTOMRIGHT: Final = 1 +ARW_TOPLEFT: Final = 2 +ARW_TOPRIGHT: Final = 3 +ARW_STARTMASK: Final = 3 +ARW_STARTRIGHT: Final = 1 +ARW_STARTTOP: Final = 2 +ARW_LEFT: Final = 0 +ARW_RIGHT: Final = 0 +ARW_UP: Final = 4 +ARW_DOWN: Final = 4 +ARW_HIDE: Final = 8 + +SERKF_SERIALKEYSON: Final = 1 +SERKF_AVAILABLE: Final = 2 +SERKF_INDICATOR: Final = 4 +HCF_HIGHCONTRASTON: Final = 1 +HCF_AVAILABLE: Final = 2 +HCF_HOTKEYACTIVE: Final = 4 +HCF_CONFIRMHOTKEY: Final = 8 +HCF_HOTKEYSOUND: Final = 16 +HCF_INDICATOR: Final = 32 +HCF_HOTKEYAVAILABLE: Final = 64 +CDS_UPDATEREGISTRY: Final = 1 +CDS_TEST: Final = 2 +CDS_FULLSCREEN: Final = 4 +CDS_GLOBAL: Final = 8 +CDS_SET_PRIMARY: Final = 16 +CDS_RESET: Final = 1073741824 +CDS_SETRECT: Final = 536870912 +CDS_NORESET: Final = 268435456 + +DISP_CHANGE_SUCCESSFUL: Final = 0 +DISP_CHANGE_RESTART: Final = 1 +DISP_CHANGE_FAILED: Final = -1 +DISP_CHANGE_BADMODE: Final = -2 +DISP_CHANGE_NOTUPDATED: Final = -3 +DISP_CHANGE_BADFLAGS: Final = -4 +DISP_CHANGE_BADPARAM: Final = -5 +DISP_CHANGE_BADDUALVIEW: Final = -6 + +ENUM_CURRENT_SETTINGS: Final = -1 +ENUM_REGISTRY_SETTINGS: Final = -2 +FKF_FILTERKEYSON: Final = 1 +FKF_AVAILABLE: Final = 2 +FKF_HOTKEYACTIVE: Final = 4 +FKF_CONFIRMHOTKEY: Final = 8 +FKF_HOTKEYSOUND: Final = 16 +FKF_INDICATOR: Final = 32 +FKF_CLICKON: Final = 64 +SKF_STICKYKEYSON: Final = 1 +SKF_AVAILABLE: Final = 2 +SKF_HOTKEYACTIVE: Final = 4 +SKF_CONFIRMHOTKEY: Final = 8 +SKF_HOTKEYSOUND: Final = 16 +SKF_INDICATOR: Final = 32 +SKF_AUDIBLEFEEDBACK: Final = 64 +SKF_TRISTATE: Final = 128 +SKF_TWOKEYSOFF: Final = 256 +SKF_LALTLATCHED: Final = 268435456 +SKF_LCTLLATCHED: Final = 67108864 +SKF_LSHIFTLATCHED: Final = 16777216 +SKF_RALTLATCHED: Final = 536870912 +SKF_RCTLLATCHED: Final = 134217728 +SKF_RSHIFTLATCHED: Final = 33554432 +SKF_LWINLATCHED: Final = 1073741824 +SKF_RWINLATCHED: Final = -2147483648 +SKF_LALTLOCKED: Final = 1048576 +SKF_LCTLLOCKED: Final = 262144 +SKF_LSHIFTLOCKED: Final = 65536 +SKF_RALTLOCKED: Final = 2097152 +SKF_RCTLLOCKED: Final = 524288 +SKF_RSHIFTLOCKED: Final = 131072 +SKF_LWINLOCKED: Final = 4194304 +SKF_RWINLOCKED: Final = 8388608 +MKF_MOUSEKEYSON: Final = 1 +MKF_AVAILABLE: Final = 2 +MKF_HOTKEYACTIVE: Final = 4 +MKF_CONFIRMHOTKEY: Final = 8 +MKF_HOTKEYSOUND: Final = 16 +MKF_INDICATOR: Final = 32 +MKF_MODIFIERS: Final = 64 +MKF_REPLACENUMBERS: Final = 128 +MKF_LEFTBUTTONSEL: Final = 268435456 +MKF_RIGHTBUTTONSEL: Final = 536870912 +MKF_LEFTBUTTONDOWN: Final = 16777216 +MKF_RIGHTBUTTONDOWN: Final = 33554432 +MKF_MOUSEMODE: Final = -2147483648 +ATF_TIMEOUTON: Final = 1 +ATF_ONOFFFEEDBACK: Final = 2 +SSGF_NONE: Final = 0 +SSGF_DISPLAY: Final = 3 +SSTF_NONE: Final = 0 +SSTF_CHARS: Final = 1 +SSTF_BORDER: Final = 2 +SSTF_DISPLAY: Final = 3 +SSWF_NONE: Final = 0 +SSWF_TITLE: Final = 1 +SSWF_WINDOW: Final = 2 +SSWF_DISPLAY: Final = 3 +SSWF_CUSTOM: Final = 4 +SSF_SOUNDSENTRYON: Final = 1 +SSF_AVAILABLE: Final = 2 +SSF_INDICATOR: Final = 4 +TKF_TOGGLEKEYSON: Final = 1 +TKF_AVAILABLE: Final = 2 +TKF_HOTKEYACTIVE: Final = 4 +TKF_CONFIRMHOTKEY: Final = 8 +TKF_HOTKEYSOUND: Final = 16 +TKF_INDICATOR: Final = 32 +SLE_ERROR: Final = 1 +SLE_MINORERROR: Final = 2 +SLE_WARNING: Final = 3 +MONITOR_DEFAULTTONULL: Final = 0 +MONITOR_DEFAULTTOPRIMARY: Final = 1 +MONITOR_DEFAULTTONEAREST: Final = 2 +MONITORINFOF_PRIMARY: Final = 1 +CCHDEVICENAME: Final = 32 +CHILDID_SELF: Final = 0 +INDEXID_OBJECT: Final = 0 +INDEXID_CONTAINER: Final = 0 +OBJID_WINDOW: Final = 0 +OBJID_SYSMENU: Final = -1 +OBJID_TITLEBAR: Final = -2 +OBJID_MENU: Final = -3 +OBJID_CLIENT: Final = -4 +OBJID_VSCROLL: Final = -5 +OBJID_HSCROLL: Final = -6 +OBJID_SIZEGRIP: Final = -7 +OBJID_CARET: Final = -8 +OBJID_CURSOR: Final = -9 +OBJID_ALERT: Final = -10 +OBJID_SOUND: Final = -11 +EVENT_MIN: Final = 1 +EVENT_MAX: Final = 2147483647 +EVENT_SYSTEM_SOUND: Final = 1 +EVENT_SYSTEM_ALERT: Final = 2 +EVENT_SYSTEM_FOREGROUND: Final = 3 +EVENT_SYSTEM_MENUSTART: Final = 4 +EVENT_SYSTEM_MENUEND: Final = 5 +EVENT_SYSTEM_MENUPOPUPSTART: Final = 6 +EVENT_SYSTEM_MENUPOPUPEND: Final = 7 +EVENT_SYSTEM_CAPTURESTART: Final = 8 +EVENT_SYSTEM_CAPTUREEND: Final = 9 +EVENT_SYSTEM_MOVESIZESTART: Final = 10 +EVENT_SYSTEM_MOVESIZEEND: Final = 11 +EVENT_SYSTEM_CONTEXTHELPSTART: Final = 12 +EVENT_SYSTEM_CONTEXTHELPEND: Final = 13 +EVENT_SYSTEM_DRAGDROPSTART: Final = 14 +EVENT_SYSTEM_DRAGDROPEND: Final = 15 +EVENT_SYSTEM_DIALOGSTART: Final = 16 +EVENT_SYSTEM_DIALOGEND: Final = 17 +EVENT_SYSTEM_SCROLLINGSTART: Final = 18 +EVENT_SYSTEM_SCROLLINGEND: Final = 19 +EVENT_SYSTEM_SWITCHSTART: Final = 20 +EVENT_SYSTEM_SWITCHEND: Final = 21 +EVENT_SYSTEM_MINIMIZESTART: Final = 22 +EVENT_SYSTEM_MINIMIZEEND: Final = 23 +EVENT_OBJECT_CREATE: Final = 32768 +EVENT_OBJECT_DESTROY: Final = 32769 +EVENT_OBJECT_SHOW: Final = 32770 +EVENT_OBJECT_HIDE: Final = 32771 +EVENT_OBJECT_REORDER: Final = 32772 +EVENT_OBJECT_FOCUS: Final = 32773 +EVENT_OBJECT_SELECTION: Final = 32774 +EVENT_OBJECT_SELECTIONADD: Final = 32775 +EVENT_OBJECT_SELECTIONREMOVE: Final = 32776 +EVENT_OBJECT_SELECTIONWITHIN: Final = 32777 +EVENT_OBJECT_STATECHANGE: Final = 32778 +EVENT_OBJECT_LOCATIONCHANGE: Final = 32779 +EVENT_OBJECT_NAMECHANGE: Final = 32780 +EVENT_OBJECT_DESCRIPTIONCHANGE: Final = 32781 +EVENT_OBJECT_VALUECHANGE: Final = 32782 +EVENT_OBJECT_PARENTCHANGE: Final = 32783 +EVENT_OBJECT_HELPCHANGE: Final = 32784 +EVENT_OBJECT_DEFACTIONCHANGE: Final = 32785 +EVENT_OBJECT_ACCELERATORCHANGE: Final = 32786 +SOUND_SYSTEM_STARTUP: Final = 1 +SOUND_SYSTEM_SHUTDOWN: Final = 2 +SOUND_SYSTEM_BEEP: Final = 3 +SOUND_SYSTEM_ERROR: Final = 4 +SOUND_SYSTEM_QUESTION: Final = 5 +SOUND_SYSTEM_WARNING: Final = 6 +SOUND_SYSTEM_INFORMATION: Final = 7 +SOUND_SYSTEM_MAXIMIZE: Final = 8 +SOUND_SYSTEM_MINIMIZE: Final = 9 +SOUND_SYSTEM_RESTOREUP: Final = 10 +SOUND_SYSTEM_RESTOREDOWN: Final = 11 +SOUND_SYSTEM_APPSTART: Final = 12 +SOUND_SYSTEM_FAULT: Final = 13 +SOUND_SYSTEM_APPEND: Final = 14 +SOUND_SYSTEM_MENUCOMMAND: Final = 15 +SOUND_SYSTEM_MENUPOPUP: Final = 16 +CSOUND_SYSTEM: Final = 16 +ALERT_SYSTEM_INFORMATIONAL: Final = 1 +ALERT_SYSTEM_WARNING: Final = 2 +ALERT_SYSTEM_ERROR: Final = 3 +ALERT_SYSTEM_QUERY: Final = 4 +ALERT_SYSTEM_CRITICAL: Final = 5 +CALERT_SYSTEM: Final = 6 +WINEVENT_OUTOFCONTEXT: Final = 0 +WINEVENT_SKIPOWNTHREAD: Final = 1 +WINEVENT_SKIPOWNPROCESS: Final = 2 +WINEVENT_INCONTEXT: Final = 4 +GUI_CARETBLINKING: Final = 1 +GUI_INMOVESIZE: Final = 2 +GUI_INMENUMODE: Final = 4 +GUI_SYSTEMMENUMODE: Final = 8 +GUI_POPUPMENUMODE: Final = 16 +STATE_SYSTEM_UNAVAILABLE: Final = 1 +STATE_SYSTEM_SELECTED: Final = 2 +STATE_SYSTEM_FOCUSED: Final = 4 +STATE_SYSTEM_PRESSED: Final = 8 +STATE_SYSTEM_CHECKED: Final = 16 +STATE_SYSTEM_MIXED: Final = 32 +STATE_SYSTEM_READONLY: Final = 64 +STATE_SYSTEM_HOTTRACKED: Final = 128 +STATE_SYSTEM_DEFAULT: Final = 256 +STATE_SYSTEM_EXPANDED: Final = 512 +STATE_SYSTEM_COLLAPSED: Final = 1024 +STATE_SYSTEM_BUSY: Final = 2048 +STATE_SYSTEM_FLOATING: Final = 4096 +STATE_SYSTEM_MARQUEED: Final = 8192 +STATE_SYSTEM_ANIMATED: Final = 16384 +STATE_SYSTEM_INVISIBLE: Final = 32768 +STATE_SYSTEM_OFFSCREEN: Final = 65536 +STATE_SYSTEM_SIZEABLE: Final = 131072 +STATE_SYSTEM_MOVEABLE: Final = 262144 +STATE_SYSTEM_SELFVOICING: Final = 524288 +STATE_SYSTEM_FOCUSABLE: Final = 1048576 +STATE_SYSTEM_SELECTABLE: Final = 2097152 +STATE_SYSTEM_LINKED: Final = 4194304 +STATE_SYSTEM_TRAVERSED: Final = 8388608 +STATE_SYSTEM_MULTISELECTABLE: Final = 16777216 +STATE_SYSTEM_EXTSELECTABLE: Final = 33554432 +STATE_SYSTEM_ALERT_LOW: Final = 67108864 +STATE_SYSTEM_ALERT_MEDIUM: Final = 134217728 +STATE_SYSTEM_ALERT_HIGH: Final = 268435456 +STATE_SYSTEM_VALID: Final = 536870911 +CCHILDREN_TITLEBAR: Final = 5 +CCHILDREN_SCROLLBAR: Final = 5 +CURSOR_SHOWING: Final = 1 +WS_ACTIVECAPTION: Final = 1 +GA_MIC: Final = 1 +GA_PARENT: Final = 1 +GA_ROOT: Final = 2 +GA_ROOTOWNER: Final = 3 +GA_MAC: Final = 4 + +BF_LEFT: Final = 1 +BF_TOP: Final = 2 +BF_RIGHT: Final = 4 +BF_BOTTOM: Final = 8 +BF_TOPLEFT: Final[int] +BF_TOPRIGHT: Final[int] +BF_BOTTOMLEFT: Final[int] +BF_BOTTOMRIGHT: Final[int] +BF_RECT: Final[int] +BF_DIAGONAL: Final = 16 +BF_DIAGONAL_ENDTOPRIGHT: Final[int] +BF_DIAGONAL_ENDTOPLEFT: Final[int] +BF_DIAGONAL_ENDBOTTOMLEFT: Final[int] +BF_DIAGONAL_ENDBOTTOMRIGHT: Final[int] +BF_MIDDLE: Final = 2048 +BF_SOFT: Final = 4096 +BF_ADJUST: Final = 8192 +BF_FLAT: Final = 16384 +BF_MONO: Final = 32768 +DFC_CAPTION: Final = 1 +DFC_MENU: Final = 2 +DFC_SCROLL: Final = 3 +DFC_BUTTON: Final = 4 +DFC_POPUPMENU: Final = 5 +DFCS_CAPTIONCLOSE: Final = 0 +DFCS_CAPTIONMIN: Final = 1 +DFCS_CAPTIONMAX: Final = 2 +DFCS_CAPTIONRESTORE: Final = 3 +DFCS_CAPTIONHELP: Final = 4 +DFCS_MENUARROW: Final = 0 +DFCS_MENUCHECK: Final = 1 +DFCS_MENUBULLET: Final = 2 +DFCS_MENUARROWRIGHT: Final = 4 +DFCS_SCROLLUP: Final = 0 +DFCS_SCROLLDOWN: Final = 1 +DFCS_SCROLLLEFT: Final = 2 +DFCS_SCROLLRIGHT: Final = 3 +DFCS_SCROLLCOMBOBOX: Final = 5 +DFCS_SCROLLSIZEGRIP: Final = 8 +DFCS_SCROLLSIZEGRIPRIGHT: Final = 16 +DFCS_BUTTONCHECK: Final = 0 +DFCS_BUTTONRADIOIMAGE: Final = 1 +DFCS_BUTTONRADIOMASK: Final = 2 +DFCS_BUTTONRADIO: Final = 4 +DFCS_BUTTON3STATE: Final = 8 +DFCS_BUTTONPUSH: Final = 16 +DFCS_INACTIVE: Final = 256 +DFCS_PUSHED: Final = 512 +DFCS_CHECKED: Final = 1024 +DFCS_TRANSPARENT: Final = 2048 +DFCS_HOT: Final = 4096 +DFCS_ADJUSTRECT: Final = 8192 +DFCS_FLAT: Final = 16384 +DFCS_MONO: Final = 32768 +DC_ACTIVE: Final = 1 +DC_SMALLCAP: Final = 2 +DC_ICON: Final = 4 +DC_TEXT: Final = 8 +DC_INBUTTON: Final = 16 +DC_GRADIENT: Final = 32 +IDANI_OPEN: Final = 1 +IDANI_CLOSE: Final = 2 +IDANI_CAPTION: Final = 3 +CF_TEXT: Final = 1 +CF_BITMAP: Final = 2 +CF_METAFILEPICT: Final = 3 +CF_SYLK: Final = 4 +CF_DIF: Final = 5 +CF_TIFF: Final = 6 +CF_OEMTEXT: Final = 7 +CF_DIB: Final = 8 +CF_PALETTE: Final = 9 +CF_PENDATA: Final = 10 +CF_RIFF: Final = 11 +CF_WAVE: Final = 12 +CF_UNICODETEXT: Final = 13 +CF_ENHMETAFILE: Final = 14 +CF_HDROP: Final = 15 +CF_LOCALE: Final = 16 +CF_DIBV5: Final = 17 +CF_MAX: Final = 18 +CF_OWNERDISPLAY: Final = 128 +CF_DSPTEXT: Final = 129 +CF_DSPBITMAP: Final = 130 +CF_DSPMETAFILEPICT: Final = 131 +CF_DSPENHMETAFILE: Final = 142 +CF_PRIVATEFIRST: Final = 512 +CF_PRIVATELAST: Final = 767 +CF_GDIOBJFIRST: Final = 768 +CF_GDIOBJLAST: Final = 1023 +FVIRTKEY: Final = 1 +FNOINVERT: Final = 2 +FSHIFT: Final = 4 +FCONTROL: Final = 8 +FALT: Final = 16 +WPF_SETMINPOSITION: Final = 1 +WPF_RESTORETOMAXIMIZED: Final = 2 +ODT_MENU: Final = 1 +ODT_LISTBOX: Final = 2 +ODT_COMBOBOX: Final = 3 +ODT_BUTTON: Final = 4 +ODT_STATIC: Final = 5 +ODA_DRAWENTIRE: Final = 1 +ODA_SELECT: Final = 2 +ODA_FOCUS: Final = 4 +ODS_SELECTED: Final = 1 +ODS_GRAYED: Final = 2 +ODS_DISABLED: Final = 4 +ODS_CHECKED: Final = 8 +ODS_FOCUS: Final = 16 +ODS_DEFAULT: Final = 32 +ODS_COMBOBOXEDIT: Final = 4096 +ODS_HOTLIGHT: Final = 64 +ODS_INACTIVE: Final = 128 +PM_NOREMOVE: Final = 0 +PM_REMOVE: Final = 1 +PM_NOYIELD: Final = 2 +MOD_ALT: Final = 1 +MOD_CONTROL: Final = 2 +MOD_SHIFT: Final = 4 +MOD_WIN: Final = 8 +MOD_NOREPEAT: Final = 16384 +IDHOT_SNAPWINDOW: Final = -1 +IDHOT_SNAPDESKTOP: Final = -2 + +ENDSESSION_LOGOFF: Final = -2147483648 +EWX_LOGOFF: Final = 0 +EWX_SHUTDOWN: Final = 1 +EWX_REBOOT: Final = 2 +EWX_FORCE: Final = 4 +EWX_POWEROFF: Final = 8 +EWX_FORCEIFHUNG: Final = 16 +BSM_ALLDESKTOPS: Final = 16 +BROADCAST_QUERY_DENY: Final = 1112363332 + +DBWF_LPARAMPOINTER: Final = 32768 + +SWP_NOSIZE: Final = 1 +SWP_NOMOVE: Final = 2 +SWP_NOZORDER: Final = 4 +SWP_NOREDRAW: Final = 8 +SWP_NOACTIVATE: Final = 16 +SWP_FRAMECHANGED: Final = 32 +SWP_SHOWWINDOW: Final = 64 +SWP_HIDEWINDOW: Final = 128 +SWP_NOCOPYBITS: Final = 256 +SWP_NOOWNERZORDER: Final = 512 +SWP_NOSENDCHANGING: Final = 1024 +SWP_DRAWFRAME: Final = SWP_FRAMECHANGED +SWP_NOREPOSITION: Final = SWP_NOOWNERZORDER +SWP_DEFERERASE: Final = 8192 +SWP_ASYNCWINDOWPOS: Final = 16384 + +DLGWINDOWEXTRA: Final = 30 + +KEYEVENTF_EXTENDEDKEY: Final = 1 +KEYEVENTF_KEYUP: Final = 2 +KEYEVENTF_UNICODE: Final = 4 +KEYEVENTF_SCANCODE: Final = 8 +MOUSEEVENTF_MOVE: Final = 1 +MOUSEEVENTF_LEFTDOWN: Final = 2 +MOUSEEVENTF_LEFTUP: Final = 4 +MOUSEEVENTF_RIGHTDOWN: Final = 8 +MOUSEEVENTF_RIGHTUP: Final = 16 +MOUSEEVENTF_MIDDLEDOWN: Final = 32 +MOUSEEVENTF_MIDDLEUP: Final = 64 +MOUSEEVENTF_XDOWN: Final = 128 +MOUSEEVENTF_XUP: Final = 256 +MOUSEEVENTF_WHEEL: Final = 2048 +MOUSEEVENTF_HWHEEL: Final = 4096 +MOUSEEVENTF_MOVE_NOCOALESCE: Final = 8192 +MOUSEEVENTF_VIRTUALDESK: Final = 16384 +MOUSEEVENTF_ABSOLUTE: Final = 32768 +INPUT_MOUSE: Final = 0 +INPUT_KEYBOARD: Final = 1 +INPUT_HARDWARE: Final = 2 +MWMO_WAITALL: Final = 1 +MWMO_ALERTABLE: Final = 2 +MWMO_INPUTAVAILABLE: Final = 4 +QS_KEY: Final = 1 +QS_MOUSEMOVE: Final = 2 +QS_MOUSEBUTTON: Final = 4 +QS_POSTMESSAGE: Final = 8 +QS_TIMER: Final = 16 +QS_PAINT: Final = 32 +QS_SENDMESSAGE: Final = 64 +QS_HOTKEY: Final = 128 +QS_MOUSE: Final[int] +QS_INPUT: Final[int] +QS_ALLEVENTS: Final[int] +QS_ALLINPUT: Final[int] + +IMN_CLOSESTATUSWINDOW: Final = 1 +IMN_OPENSTATUSWINDOW: Final = 2 +IMN_CHANGECANDIDATE: Final = 3 +IMN_CLOSECANDIDATE: Final = 4 +IMN_OPENCANDIDATE: Final = 5 +IMN_SETCONVERSIONMODE: Final = 6 +IMN_SETSENTENCEMODE: Final = 7 +IMN_SETOPENSTATUS: Final = 8 +IMN_SETCANDIDATEPOS: Final = 9 +IMN_SETCOMPOSITIONFONT: Final = 10 +IMN_SETCOMPOSITIONWINDOW: Final = 11 +IMN_SETSTATUSWINDOWPOS: Final = 12 +IMN_GUIDELINE: Final = 13 +IMN_PRIVATE: Final = 14 + +HELP_CONTEXT: Final = 1 +HELP_QUIT: Final = 2 +HELP_INDEX: Final = 3 +HELP_CONTENTS: Final = 3 +HELP_HELPONHELP: Final = 4 +HELP_SETINDEX: Final = 5 +HELP_SETCONTENTS: Final = 5 +HELP_CONTEXTPOPUP: Final = 8 +HELP_FORCEFILE: Final = 9 +HELP_KEY: Final = 257 +HELP_COMMAND: Final = 258 +HELP_PARTIALKEY: Final = 261 +HELP_MULTIKEY: Final = 513 +HELP_SETWINPOS: Final = 515 +HELP_CONTEXTMENU: Final = 10 +HELP_FINDER: Final = 11 +HELP_WM_HELP: Final = 12 +HELP_SETPOPUP_POS: Final = 13 +HELP_TCARD: Final = 32768 +HELP_TCARD_DATA: Final = 16 +HELP_TCARD_OTHER_CALLER: Final = 17 +IDH_NO_HELP: Final = 28440 +IDH_MISSING_CONTEXT: Final = 28441 +IDH_GENERIC_HELP_BUTTON: Final = 28442 +IDH_OK: Final = 28443 +IDH_CANCEL: Final = 28444 +IDH_HELP: Final = 28445 +GR_GDIOBJECTS: Final = 0 +GR_USEROBJECTS: Final = 1 + +SRCCOPY: Final = 13369376 +SRCPAINT: Final = 15597702 +SRCAND: Final = 8913094 +SRCINVERT: Final = 6684742 +SRCERASE: Final = 4457256 +NOTSRCCOPY: Final = 3342344 +NOTSRCERASE: Final = 1114278 +MERGECOPY: Final = 12583114 +MERGEPAINT: Final = 12255782 +PATCOPY: Final = 15728673 +PATPAINT: Final = 16452105 +PATINVERT: Final = 5898313 +DSTINVERT: Final = 5570569 +BLACKNESS: Final = 66 +WHITENESS: Final = 16711778 + +R2_BLACK: Final = 1 +R2_NOTMERGEPEN: Final = 2 +R2_MASKNOTPEN: Final = 3 +R2_NOTCOPYPEN: Final = 4 +R2_MASKPENNOT: Final = 5 +R2_NOT: Final = 6 +R2_XORPEN: Final = 7 +R2_NOTMASKPEN: Final = 8 +R2_MASKPEN: Final = 9 +R2_NOTXORPEN: Final = 10 +R2_NOP: Final = 11 +R2_MERGENOTPEN: Final = 12 +R2_COPYPEN: Final = 13 +R2_MERGEPENNOT: Final = 14 +R2_MERGEPEN: Final = 15 +R2_WHITE: Final = 16 +R2_LAST: Final = 16 +GDI_ERROR: Final = -1 +ERROR: Final = 0 +NULLREGION: Final = 1 +SIMPLEREGION: Final = 2 +COMPLEXREGION: Final = 3 +RGN_ERROR: Final = ERROR +RGN_AND: Final = 1 +RGN_OR: Final = 2 +RGN_XOR: Final = 3 +RGN_DIFF: Final = 4 +RGN_COPY: Final = 5 +RGN_MIN: Final = RGN_AND +RGN_MAX: Final = RGN_COPY + +BLACKONWHITE: Final = 1 +WHITEONBLACK: Final = 2 +COLORONCOLOR: Final = 3 +HALFTONE: Final = 4 +MAXSTRETCHBLTMODE: Final = 4 +STRETCH_ANDSCANS: Final = BLACKONWHITE +STRETCH_ORSCANS: Final = WHITEONBLACK +STRETCH_DELETESCANS: Final = COLORONCOLOR +STRETCH_HALFTONE: Final = HALFTONE + +ALTERNATE: Final = 1 +WINDING: Final = 2 +POLYFILL_LAST: Final = 2 + +LAYOUT_RTL: Final = 1 +LAYOUT_BTT: Final = 2 +LAYOUT_VBH: Final = 4 +LAYOUT_ORIENTATIONMASK: Final[int] +LAYOUT_BITMAPORIENTATIONPRESERVED: Final = 8 + +TA_NOUPDATECP: Final = 0 +TA_UPDATECP: Final = 1 +TA_LEFT: Final = 0 +TA_RIGHT: Final = 2 +TA_CENTER: Final = 6 +TA_TOP: Final = 0 +TA_BOTTOM: Final = 8 +TA_BASELINE: Final = 24 +TA_MASK: Final[int] +VTA_BASELINE: Final = TA_BASELINE +VTA_LEFT: Final = TA_BOTTOM +VTA_RIGHT: Final = TA_TOP +VTA_CENTER: Final = TA_CENTER +VTA_BOTTOM: Final = TA_RIGHT +VTA_TOP: Final = TA_LEFT +ETO_GRAYED: Final = 1 +ETO_OPAQUE: Final = 2 +ETO_CLIPPED: Final = 4 +ASPECT_FILTERING: Final = 1 +DCB_RESET: Final = 1 +DCB_ACCUMULATE: Final = 2 +DCB_DIRTY: Final = DCB_ACCUMULATE +DCB_SET: Final[int] +DCB_ENABLE: Final = 4 +DCB_DISABLE: Final = 8 +META_SETBKCOLOR: Final = 513 +META_SETBKMODE: Final = 258 +META_SETMAPMODE: Final = 259 +META_SETROP2: Final = 260 +META_SETRELABS: Final = 261 +META_SETPOLYFILLMODE: Final = 262 +META_SETSTRETCHBLTMODE: Final = 263 +META_SETTEXTCHAREXTRA: Final = 264 +META_SETTEXTCOLOR: Final = 521 +META_SETTEXTJUSTIFICATION: Final = 522 +META_SETWINDOWORG: Final = 523 +META_SETWINDOWEXT: Final = 524 +META_SETVIEWPORTORG: Final = 525 +META_SETVIEWPORTEXT: Final = 526 +META_OFFSETWINDOWORG: Final = 527 +META_SCALEWINDOWEXT: Final = 1040 +META_OFFSETVIEWPORTORG: Final = 529 +META_SCALEVIEWPORTEXT: Final = 1042 +META_LINETO: Final = 531 +META_MOVETO: Final = 532 +META_EXCLUDECLIPRECT: Final = 1045 +META_INTERSECTCLIPRECT: Final = 1046 +META_ARC: Final = 2071 +META_ELLIPSE: Final = 1048 +META_FLOODFILL: Final = 1049 +META_PIE: Final = 2074 +META_RECTANGLE: Final = 1051 +META_ROUNDRECT: Final = 1564 +META_PATBLT: Final = 1565 +META_SAVEDC: Final = 30 +META_SETPIXEL: Final = 1055 +META_OFFSETCLIPRGN: Final = 544 +META_TEXTOUT: Final = 1313 +META_BITBLT: Final = 2338 +META_STRETCHBLT: Final = 2851 +META_POLYGON: Final = 804 +META_POLYLINE: Final = 805 +META_ESCAPE: Final = 1574 +META_RESTOREDC: Final = 295 +META_FILLREGION: Final = 552 +META_FRAMEREGION: Final = 1065 +META_INVERTREGION: Final = 298 +META_PAINTREGION: Final = 299 +META_SELECTCLIPREGION: Final = 300 +META_SELECTOBJECT: Final = 301 +META_SETTEXTALIGN: Final = 302 +META_CHORD: Final = 2096 +META_SETMAPPERFLAGS: Final = 561 +META_EXTTEXTOUT: Final = 2610 +META_SETDIBTODEV: Final = 3379 +META_SELECTPALETTE: Final = 564 +META_REALIZEPALETTE: Final = 53 +META_ANIMATEPALETTE: Final = 1078 +META_SETPALENTRIES: Final = 55 +META_POLYPOLYGON: Final = 1336 +META_RESIZEPALETTE: Final = 313 +META_DIBBITBLT: Final = 2368 +META_DIBSTRETCHBLT: Final = 2881 +META_DIBCREATEPATTERNBRUSH: Final = 322 +META_STRETCHDIB: Final = 3907 +META_EXTFLOODFILL: Final = 1352 +META_DELETEOBJECT: Final = 496 +META_CREATEPALETTE: Final = 247 +META_CREATEPATTERNBRUSH: Final = 505 +META_CREATEPENINDIRECT: Final = 762 +META_CREATEFONTINDIRECT: Final = 763 +META_CREATEBRUSHINDIRECT: Final = 764 +META_CREATEREGION: Final = 1791 +FILE_BEGIN: Final = 0 +FILE_CURRENT: Final = 1 +FILE_END: Final = 2 +FILE_FLAG_WRITE_THROUGH: Final = -2147483648 +FILE_FLAG_OVERLAPPED: Final = 1073741824 +FILE_FLAG_NO_BUFFERING: Final = 536870912 +FILE_FLAG_RANDOM_ACCESS: Final = 268435456 +FILE_FLAG_SEQUENTIAL_SCAN: Final = 134217728 +FILE_FLAG_DELETE_ON_CLOSE: Final = 67108864 +FILE_FLAG_BACKUP_SEMANTICS: Final = 33554432 +FILE_FLAG_POSIX_SEMANTICS: Final = 16777216 +CREATE_NEW: Final = 1 +CREATE_ALWAYS: Final = 2 +OPEN_EXISTING: Final = 3 +OPEN_ALWAYS: Final = 4 +TRUNCATE_EXISTING: Final = 5 +PIPE_ACCESS_INBOUND: Final = 1 +PIPE_ACCESS_OUTBOUND: Final = 2 +PIPE_ACCESS_DUPLEX: Final = 3 +PIPE_CLIENT_END: Final = 0 +PIPE_SERVER_END: Final = 1 +PIPE_WAIT: Final = 0 +PIPE_NOWAIT: Final = 1 +PIPE_READMODE_BYTE: Final = 0 +PIPE_READMODE_MESSAGE: Final = 2 +PIPE_TYPE_BYTE: Final = 0 +PIPE_TYPE_MESSAGE: Final = 4 +PIPE_UNLIMITED_INSTANCES: Final = 255 +SECURITY_CONTEXT_TRACKING: Final = 262144 +SECURITY_EFFECTIVE_ONLY: Final = 524288 +SECURITY_SQOS_PRESENT: Final = 1048576 +SECURITY_VALID_SQOS_FLAGS: Final = 2031616 +DTR_CONTROL_DISABLE: Final = 0 +DTR_CONTROL_ENABLE: Final = 1 +DTR_CONTROL_HANDSHAKE: Final = 2 +RTS_CONTROL_DISABLE: Final = 0 +RTS_CONTROL_ENABLE: Final = 1 +RTS_CONTROL_HANDSHAKE: Final = 2 +RTS_CONTROL_TOGGLE: Final = 3 +GMEM_FIXED: Final = 0 +GMEM_MOVEABLE: Final = 2 +GMEM_NOCOMPACT: Final = 16 +GMEM_NODISCARD: Final = 32 +GMEM_ZEROINIT: Final = 64 +GMEM_MODIFY: Final = 128 +GMEM_DISCARDABLE: Final = 256 +GMEM_NOT_BANKED: Final = 4096 +GMEM_SHARE: Final = 8192 +GMEM_DDESHARE: Final = 8192 +GMEM_NOTIFY: Final = 16384 +GMEM_LOWER: Final = GMEM_NOT_BANKED +GMEM_VALID_FLAGS: Final = 32626 +GMEM_INVALID_HANDLE: Final = 32768 +GHND: Final[int] +GPTR: Final[int] +GMEM_DISCARDED: Final = 16384 +GMEM_LOCKCOUNT: Final = 255 +LMEM_FIXED: Final = 0 +LMEM_MOVEABLE: Final = 2 +LMEM_NOCOMPACT: Final = 16 +LMEM_NODISCARD: Final = 32 +LMEM_ZEROINIT: Final = 64 +LMEM_MODIFY: Final = 128 +LMEM_DISCARDABLE: Final = 3840 +LMEM_VALID_FLAGS: Final = 3954 +LMEM_INVALID_HANDLE: Final = 32768 +LHND: Final[int] +LPTR: Final[int] +NONZEROLHND: Final = LMEM_MOVEABLE +NONZEROLPTR: Final = LMEM_FIXED +LMEM_DISCARDED: Final = 16384 +LMEM_LOCKCOUNT: Final = 255 +DEBUG_PROCESS: Final = 1 +DEBUG_ONLY_THIS_PROCESS: Final = 2 +CREATE_SUSPENDED: Final = 4 +DETACHED_PROCESS: Final = 8 +CREATE_NEW_CONSOLE: Final = 16 +NORMAL_PRIORITY_CLASS: Final = 32 +IDLE_PRIORITY_CLASS: Final = 64 +HIGH_PRIORITY_CLASS: Final = 128 +REALTIME_PRIORITY_CLASS: Final = 256 +CREATE_NEW_PROCESS_GROUP: Final = 512 +CREATE_UNICODE_ENVIRONMENT: Final = 1024 +CREATE_SEPARATE_WOW_VDM: Final = 2048 +CREATE_SHARED_WOW_VDM: Final = 4096 +CREATE_DEFAULT_ERROR_MODE: Final = 67108864 +CREATE_NO_WINDOW: Final = 134217728 +PROFILE_USER: Final = 268435456 +PROFILE_KERNEL: Final = 536870912 +PROFILE_SERVER: Final = 1073741824 +THREAD_BASE_PRIORITY_LOWRT: Final = 15 +THREAD_BASE_PRIORITY_MAX: Final = 2 +THREAD_BASE_PRIORITY_MIN: Final = -2 +THREAD_BASE_PRIORITY_IDLE: Final = -15 +THREAD_PRIORITY_LOWEST: Final = THREAD_BASE_PRIORITY_MIN +THREAD_PRIORITY_BELOW_NORMAL: Final[int] +THREAD_PRIORITY_HIGHEST: Final = THREAD_BASE_PRIORITY_MAX +THREAD_PRIORITY_ABOVE_NORMAL: Final[int] +THREAD_PRIORITY_ERROR_RETURN: Final = MAXLONG +THREAD_PRIORITY_TIME_CRITICAL: Final = THREAD_BASE_PRIORITY_LOWRT +THREAD_PRIORITY_IDLE: Final = THREAD_BASE_PRIORITY_IDLE +THREAD_PRIORITY_NORMAL: Final = 0 +THREAD_MODE_BACKGROUND_BEGIN: Final = 0x00010000 +THREAD_MODE_BACKGROUND_END: Final = 0x00020000 + +EXCEPTION_DEBUG_EVENT: Final = 1 +CREATE_THREAD_DEBUG_EVENT: Final = 2 +CREATE_PROCESS_DEBUG_EVENT: Final = 3 +EXIT_THREAD_DEBUG_EVENT: Final = 4 +EXIT_PROCESS_DEBUG_EVENT: Final = 5 +LOAD_DLL_DEBUG_EVENT: Final = 6 +UNLOAD_DLL_DEBUG_EVENT: Final = 7 +OUTPUT_DEBUG_STRING_EVENT: Final = 8 +RIP_EVENT: Final = 9 +DRIVE_UNKNOWN: Final = 0 +DRIVE_NO_ROOT_DIR: Final = 1 +DRIVE_REMOVABLE: Final = 2 +DRIVE_FIXED: Final = 3 +DRIVE_REMOTE: Final = 4 +DRIVE_CDROM: Final = 5 +DRIVE_RAMDISK: Final = 6 +FILE_TYPE_UNKNOWN: Final = 0 +FILE_TYPE_DISK: Final = 1 +FILE_TYPE_CHAR: Final = 2 +FILE_TYPE_PIPE: Final = 3 +FILE_TYPE_REMOTE: Final = 32768 +NOPARITY: Final = 0 +ODDPARITY: Final = 1 +EVENPARITY: Final = 2 +MARKPARITY: Final = 3 +SPACEPARITY: Final = 4 +ONESTOPBIT: Final = 0 +ONE5STOPBITS: Final = 1 +TWOSTOPBITS: Final = 2 +CBR_110: Final = 110 +CBR_300: Final = 300 +CBR_600: Final = 600 +CBR_1200: Final = 1200 +CBR_2400: Final = 2400 +CBR_4800: Final = 4800 +CBR_9600: Final = 9600 +CBR_14400: Final = 14400 +CBR_19200: Final = 19200 +CBR_38400: Final = 38400 +CBR_56000: Final = 56000 +CBR_57600: Final = 57600 +CBR_115200: Final = 115200 +CBR_128000: Final = 128000 +CBR_256000: Final = 256000 +S_QUEUEEMPTY: Final = 0 +S_THRESHOLD: Final = 1 +S_ALLTHRESHOLD: Final = 2 +S_NORMAL: Final = 0 +S_LEGATO: Final = 1 +S_STACCATO: Final = 2 +NMPWAIT_WAIT_FOREVER: Final = -1 +NMPWAIT_NOWAIT: Final = 1 +NMPWAIT_USE_DEFAULT_WAIT: Final = 0 +OF_READ: Final = 0 +OF_WRITE: Final = 1 +OF_READWRITE: Final = 2 +OF_SHARE_COMPAT: Final = 0 +OF_SHARE_EXCLUSIVE: Final = 16 +OF_SHARE_DENY_WRITE: Final = 32 +OF_SHARE_DENY_READ: Final = 48 +OF_SHARE_DENY_NONE: Final = 64 +OF_PARSE: Final = 256 +OF_DELETE: Final = 512 +OF_VERIFY: Final = 1024 +OF_CANCEL: Final = 2048 +OF_CREATE: Final = 4096 +OF_PROMPT: Final = 8192 +OF_EXIST: Final = 16384 +OF_REOPEN: Final = 32768 +OFS_MAXPATHNAME: Final = 128 +MAXINTATOM: Final = 49152 + +PROCESS_HEAP_REGION: Final = 1 +PROCESS_HEAP_UNCOMMITTED_RANGE: Final = 2 +PROCESS_HEAP_ENTRY_BUSY: Final = 4 +PROCESS_HEAP_ENTRY_MOVEABLE: Final = 16 +PROCESS_HEAP_ENTRY_DDESHARE: Final = 32 +SCS_32BIT_BINARY: Final = 0 +SCS_DOS_BINARY: Final = 1 +SCS_WOW_BINARY: Final = 2 +SCS_PIF_BINARY: Final = 3 +SCS_POSIX_BINARY: Final = 4 +SCS_OS216_BINARY: Final = 5 +SEM_FAILCRITICALERRORS: Final = 1 +SEM_NOGPFAULTERRORBOX: Final = 2 +SEM_NOALIGNMENTFAULTEXCEPT: Final = 4 +SEM_NOOPENFILEERRORBOX: Final = 32768 +LOCKFILE_FAIL_IMMEDIATELY: Final = 1 +LOCKFILE_EXCLUSIVE_LOCK: Final = 2 +HANDLE_FLAG_INHERIT: Final = 1 +HANDLE_FLAG_PROTECT_FROM_CLOSE: Final = 2 +HINSTANCE_ERROR: Final = 32 +GET_TAPE_MEDIA_INFORMATION: Final = 0 +GET_TAPE_DRIVE_INFORMATION: Final = 1 +SET_TAPE_MEDIA_INFORMATION: Final = 0 +SET_TAPE_DRIVE_INFORMATION: Final = 1 +FORMAT_MESSAGE_ALLOCATE_BUFFER: Final = 256 +FORMAT_MESSAGE_IGNORE_INSERTS: Final = 512 +FORMAT_MESSAGE_FROM_STRING: Final = 1024 +FORMAT_MESSAGE_FROM_HMODULE: Final = 2048 +FORMAT_MESSAGE_FROM_SYSTEM: Final = 4096 +FORMAT_MESSAGE_ARGUMENT_ARRAY: Final = 8192 +FORMAT_MESSAGE_MAX_WIDTH_MASK: Final = 255 +BACKUP_INVALID: Final = 0 +BACKUP_DATA: Final = 1 +BACKUP_EA_DATA: Final = 2 +BACKUP_SECURITY_DATA: Final = 3 +BACKUP_ALTERNATE_DATA: Final = 4 +BACKUP_LINK: Final = 5 +BACKUP_PROPERTY_DATA: Final = 6 +BACKUP_OBJECT_ID: Final = 7 +BACKUP_REPARSE_DATA: Final = 8 +BACKUP_SPARSE_BLOCK: Final = 9 + +STREAM_NORMAL_ATTRIBUTE: Final = 0 +STREAM_MODIFIED_WHEN_READ: Final = 1 +STREAM_CONTAINS_SECURITY: Final = 2 +STREAM_CONTAINS_PROPERTIES: Final = 4 +STARTF_USESHOWWINDOW: Final = 1 +STARTF_USESIZE: Final = 2 +STARTF_USEPOSITION: Final = 4 +STARTF_USECOUNTCHARS: Final = 8 +STARTF_USEFILLATTRIBUTE: Final = 16 +STARTF_FORCEONFEEDBACK: Final = 64 +STARTF_FORCEOFFFEEDBACK: Final = 128 +STARTF_USESTDHANDLES: Final = 256 +STARTF_USEHOTKEY: Final = 512 +SHUTDOWN_NORETRY: Final = 1 +DONT_RESOLVE_DLL_REFERENCES: Final = 1 +LOAD_LIBRARY_AS_DATAFILE: Final = 2 +LOAD_WITH_ALTERED_SEARCH_PATH: Final = 8 +DDD_RAW_TARGET_PATH: Final = 1 +DDD_REMOVE_DEFINITION: Final = 2 +DDD_EXACT_MATCH_ON_REMOVE: Final = 4 +MOVEFILE_REPLACE_EXISTING: Final = 1 +MOVEFILE_COPY_ALLOWED: Final = 2 +MOVEFILE_DELAY_UNTIL_REBOOT: Final = 4 +MAX_COMPUTERNAME_LENGTH: Final = 15 +LOGON32_LOGON_INTERACTIVE: Final = 2 +LOGON32_LOGON_NETWORK: Final = 3 +LOGON32_LOGON_BATCH: Final = 4 +LOGON32_LOGON_SERVICE: Final = 5 +LOGON32_LOGON_UNLOCK: Final = 7 +LOGON32_LOGON_NETWORK_CLEARTEXT: Final = 8 +LOGON32_LOGON_NEW_CREDENTIALS: Final = 9 +LOGON32_PROVIDER_DEFAULT: Final = 0 +LOGON32_PROVIDER_WINNT35: Final = 1 +LOGON32_PROVIDER_WINNT40: Final = 2 +LOGON32_PROVIDER_WINNT50: Final = 3 +VER_PLATFORM_WIN32s: Final = 0 +VER_PLATFORM_WIN32_WINDOWS: Final = 1 +VER_PLATFORM_WIN32_NT: Final = 2 +TC_NORMAL: Final = 0 +TC_HARDERR: Final = 1 +TC_GP_TRAP: Final = 2 +TC_SIGNAL: Final = 3 +AC_LINE_OFFLINE: Final = 0 +AC_LINE_ONLINE: Final = 1 +AC_LINE_BACKUP_POWER: Final = 2 +AC_LINE_UNKNOWN: Final = 255 +BATTERY_FLAG_HIGH: Final = 1 +BATTERY_FLAG_LOW: Final = 2 +BATTERY_FLAG_CRITICAL: Final = 4 +BATTERY_FLAG_CHARGING: Final = 8 +BATTERY_FLAG_NO_BATTERY: Final = 128 +BATTERY_FLAG_UNKNOWN: Final = 255 +BATTERY_PERCENTAGE_UNKNOWN: Final = 255 +BATTERY_LIFE_UNKNOWN: Final = -1 + +cchTextLimitDefault: Final = 32767 +WM_CONTEXTMENU: Final = 123 +WM_PRINTCLIENT: Final = 792 +EN_MSGFILTER: Final = 1792 +EN_REQUESTRESIZE: Final = 1793 +EN_SELCHANGE: Final = 1794 +EN_DROPFILES: Final = 1795 +EN_PROTECTED: Final = 1796 +EN_CORRECTTEXT: Final = 1797 +EN_STOPNOUNDO: Final = 1798 +EN_IMECHANGE: Final = 1799 +EN_SAVECLIPBOARD: Final = 1800 +EN_OLEOPFAILED: Final = 1801 +ENM_NONE: Final = 0 +ENM_CHANGE: Final = 1 +ENM_UPDATE: Final = 2 +ENM_SCROLL: Final = 4 +ENM_KEYEVENTS: Final = 65536 +ENM_MOUSEEVENTS: Final = 131072 +ENM_REQUESTRESIZE: Final = 262144 +ENM_SELCHANGE: Final = 524288 +ENM_DROPFILES: Final = 1048576 +ENM_PROTECTED: Final = 2097152 +ENM_CORRECTTEXT: Final = 4194304 +ENM_IMECHANGE: Final = 8388608 +ES_SAVESEL: Final = 32768 +ES_SUNKEN: Final = 16384 +ES_DISABLENOSCROLL: Final = 8192 +ES_SELECTIONBAR: Final = 16777216 +ES_EX_NOCALLOLEINIT: Final = 16777216 +ES_VERTICAL: Final = 4194304 +ES_NOIME: Final = 524288 +ES_SELFIME: Final = 262144 +ECO_AUTOWORDSELECTION: Final = 1 +ECO_AUTOVSCROLL: Final = 64 +ECO_AUTOHSCROLL: Final = 128 +ECO_NOHIDESEL: Final = 256 +ECO_READONLY: Final = 2048 +ECO_WANTRETURN: Final = 4096 +ECO_SAVESEL: Final = 32768 +ECO_SELECTIONBAR: Final = 16777216 +ECO_VERTICAL: Final = 4194304 +ECOOP_SET: Final = 1 +ECOOP_OR: Final = 2 +ECOOP_AND: Final = 3 +ECOOP_XOR: Final = 4 +WB_CLASSIFY: Final = 3 +WB_MOVEWORDLEFT: Final = 4 +WB_MOVEWORDRIGHT: Final = 5 +WB_LEFTBREAK: Final = 6 +WB_RIGHTBREAK: Final = 7 +WB_MOVEWORDPREV: Final = 4 +WB_MOVEWORDNEXT: Final = 5 +WB_PREVBREAK: Final = 6 +WB_NEXTBREAK: Final = 7 +PC_FOLLOWING: Final = 1 +PC_LEADING: Final = 2 +PC_OVERFLOW: Final = 3 +PC_DELIMITER: Final = 4 +WBF_WORDWRAP: Final = 16 +WBF_WORDBREAK: Final = 32 +WBF_OVERFLOW: Final = 64 +WBF_LEVEL1: Final = 128 +WBF_LEVEL2: Final = 256 +WBF_CUSTOM: Final = 512 +CFM_BOLD: Final = 1 +CFM_ITALIC: Final = 2 +CFM_UNDERLINE: Final = 4 +CFM_STRIKEOUT: Final = 8 +CFM_PROTECTED: Final = 16 +CFM_SIZE: Final = -2147483648 +CFM_COLOR: Final = 1073741824 +CFM_FACE: Final = 536870912 +CFM_OFFSET: Final = 268435456 +CFM_CHARSET: Final = 134217728 +CFE_BOLD: Final = 1 +CFE_ITALIC: Final = 2 +CFE_UNDERLINE: Final = 4 +CFE_STRIKEOUT: Final = 8 +CFE_PROTECTED: Final = 16 +CFE_AUTOCOLOR: Final = 1073741824 +yHeightCharPtsMost: Final = 1638 +SCF_SELECTION: Final = 1 +SCF_WORD: Final = 2 +SF_TEXT: Final = 1 +SF_RTF: Final = 2 +SF_RTFNOOBJS: Final = 3 +SF_TEXTIZED: Final = 4 +SFF_SELECTION: Final = 32768 +SFF_PLAINRTF: Final = 16384 +MAX_TAB_STOPS: Final = 32 +lDefaultTab: Final = 720 +PFM_STARTINDENT: Final = 1 +PFM_RIGHTINDENT: Final = 2 +PFM_OFFSET: Final = 4 +PFM_ALIGNMENT: Final = 8 +PFM_TABSTOPS: Final = 16 +PFM_NUMBERING: Final = 32 +PFM_OFFSETINDENT: Final = -2147483648 +PFN_BULLET: Final = 1 +PFA_LEFT: Final = 1 +PFA_RIGHT: Final = 2 +PFA_CENTER: Final = 3 +WM_NOTIFY: Final = 78 +SEL_EMPTY: Final = 0 +SEL_TEXT: Final = 1 +SEL_OBJECT: Final = 2 +SEL_MULTICHAR: Final = 4 +SEL_MULTIOBJECT: Final = 8 +OLEOP_DOVERB: Final = 1 +CF_RTF: Final = "Rich Text Format" +CF_RTFNOOBJS: Final = "Rich Text Format Without Objects" +CF_RETEXTOBJ: Final = "RichEdit Text and Objects" + +RIGHT_ALT_PRESSED: Final = 1 +LEFT_ALT_PRESSED: Final = 2 +RIGHT_CTRL_PRESSED: Final = 4 +LEFT_CTRL_PRESSED: Final = 8 +SHIFT_PRESSED: Final = 16 +NUMLOCK_ON: Final = 32 +SCROLLLOCK_ON: Final = 64 +CAPSLOCK_ON: Final = 128 +ENHANCED_KEY: Final = 256 +NLS_DBCSCHAR: Final = 65536 +NLS_ALPHANUMERIC: Final = 0 +NLS_KATAKANA: Final = 131072 +NLS_HIRAGANA: Final = 262144 +NLS_ROMAN: Final = 4194304 +NLS_IME_CONVERSION: Final = 8388608 +NLS_IME_DISABLE: Final = 536870912 + +FROM_LEFT_1ST_BUTTON_PRESSED: Final = 1 +RIGHTMOST_BUTTON_PRESSED: Final = 2 +FROM_LEFT_2ND_BUTTON_PRESSED: Final = 4 +FROM_LEFT_3RD_BUTTON_PRESSED: Final = 8 +FROM_LEFT_4TH_BUTTON_PRESSED: Final = 16 + +CTRL_C_EVENT: Final = 0 +CTRL_BREAK_EVENT: Final = 1 +CTRL_CLOSE_EVENT: Final = 2 +CTRL_LOGOFF_EVENT: Final = 5 +CTRL_SHUTDOWN_EVENT: Final = 6 + +MOUSE_MOVED: Final = 1 +DOUBLE_CLICK: Final = 2 +MOUSE_WHEELED: Final = 4 + +PSM_SETCURSEL: Final[int] +PSM_REMOVEPAGE: Final[int] +PSM_ADDPAGE: Final[int] +PSM_CHANGED: Final[int] +PSM_RESTARTWINDOWS: Final[int] +PSM_REBOOTSYSTEM: Final[int] +PSM_CANCELTOCLOSE: Final[int] +PSM_QUERYSIBLINGS: Final[int] +PSM_UNCHANGED: Final[int] +PSM_APPLY: Final[int] +PSM_SETTITLEA: Final[int] +PSM_SETTITLEW: Final[int] +PSM_SETWIZBUTTONS: Final[int] +PSM_PRESSBUTTON: Final[int] +PSM_SETCURSELID: Final[int] +PSM_SETFINISHTEXTA: Final[int] +PSM_SETFINISHTEXTW: Final[int] +PSM_GETTABCONTROL: Final[int] +PSM_ISDIALOGMESSAGE: Final[int] +PSM_GETCURRENTPAGEHWND: Final[int] +PSM_INSERTPAGE: Final[int] +PSM_SETHEADERTITLEA: Final[int] +PSM_SETHEADERTITLEW: Final[int] +PSM_SETHEADERSUBTITLEA: Final[int] +PSM_SETHEADERSUBTITLEW: Final[int] +PSM_HWNDTOINDEX: Final[int] +PSM_INDEXTOHWND: Final[int] +PSM_PAGETOINDEX: Final[int] +PSM_INDEXTOPAGE: Final[int] +PSM_IDTOINDEX: Final[int] +PSM_INDEXTOID: Final[int] +PSM_GETRESULT: Final[int] +PSM_RECALCPAGESIZES: Final[int] + +NameUnknown: Final = 0 +NameFullyQualifiedDN: Final = 1 +NameSamCompatible: Final = 2 +NameDisplay: Final = 3 +NameUniqueId: Final = 6 +NameCanonical: Final = 7 +NameUserPrincipal: Final = 8 +NameCanonicalEx: Final = 9 +NameServicePrincipal: Final = 10 +NameDnsDomain: Final = 12 + +ComputerNameNetBIOS: Final = 0 +ComputerNameDnsHostname: Final = 1 +ComputerNameDnsDomain: Final = 2 +ComputerNameDnsFullyQualified: Final = 3 +ComputerNamePhysicalNetBIOS: Final = 4 +ComputerNamePhysicalDnsHostname: Final = 5 +ComputerNamePhysicalDnsDomain: Final = 6 +ComputerNamePhysicalDnsFullyQualified: Final = 7 + +LWA_COLORKEY: Final = 0x00000001 +LWA_ALPHA: Final = 0x00000002 +ULW_COLORKEY: Final = 0x00000001 +ULW_ALPHA: Final = 0x00000002 +ULW_OPAQUE: Final = 0x00000004 + +TRUE: Final = 1 +FALSE: Final = 0 +MAX_PATH: Final = 260 + +AC_SRC_OVER: Final = 0 +AC_SRC_ALPHA: Final = 1 +GRADIENT_FILL_RECT_H: Final = 0 +GRADIENT_FILL_RECT_V: Final = 1 +GRADIENT_FILL_TRIANGLE: Final = 2 +GRADIENT_FILL_OP_FLAG: Final = 255 + +MM_WORKING_SET_MAX_HARD_ENABLE: Final = 1 +MM_WORKING_SET_MAX_HARD_DISABLE: Final = 2 +MM_WORKING_SET_MIN_HARD_ENABLE: Final = 4 +MM_WORKING_SET_MIN_HARD_DISABLE: Final = 8 + +VOLUME_NAME_DOS: Final = 0 +VOLUME_NAME_GUID: Final = 1 +VOLUME_NAME_NT: Final = 2 +VOLUME_NAME_NONE: Final = 4 +FILE_NAME_NORMALIZED: Final = 0 +FILE_NAME_OPENED: Final = 8 + +DEVICE_NOTIFY_WINDOW_HANDLE: Final = 0x00000000 +DEVICE_NOTIFY_SERVICE_HANDLE: Final = 0x00000001 + +WM_DEVICECHANGE: Final = 0x0219 +BSF_QUERY: Final = 0x00000001 +BSF_IGNORECURRENTTASK: Final = 0x00000002 +BSF_FLUSHDISK: Final = 0x00000004 +BSF_NOHANG: Final = 0x00000008 +BSF_POSTMESSAGE: Final = 0x00000010 +BSF_FORCEIFHUNG: Final = 0x00000020 +BSF_NOTIMEOUTIFNOTHUNG: Final = 0x00000040 +BSF_MSGSRV32ISOK: Final = -2147483648 +BSF_MSGSRV32ISOK_BIT: Final = 31 +BSM_ALLCOMPONENTS: Final = 0x00000000 +BSM_VXDS: Final = 0x00000001 +BSM_NETDRIVER: Final = 0x00000002 +BSM_INSTALLABLEDRIVERS: Final = 0x00000004 +BSM_APPLICATIONS: Final = 0x00000008 +DBT_APPYBEGIN: Final = 0x0000 +DBT_APPYEND: Final = 0x0001 +DBT_DEVNODES_CHANGED: Final = 0x0007 +DBT_QUERYCHANGECONFIG: Final = 0x0017 +DBT_CONFIGCHANGED: Final = 0x0018 +DBT_CONFIGCHANGECANCELED: Final = 0x0019 +DBT_MONITORCHANGE: Final = 0x001B +DBT_SHELLLOGGEDON: Final = 0x0020 +DBT_CONFIGMGAPI32: Final = 0x0022 +DBT_VXDINITCOMPLETE: Final = 0x0023 +DBT_VOLLOCKQUERYLOCK: Final = 0x8041 +DBT_VOLLOCKLOCKTAKEN: Final = 0x8042 +DBT_VOLLOCKLOCKFAILED: Final = 0x8043 +DBT_VOLLOCKQUERYUNLOCK: Final = 0x8044 +DBT_VOLLOCKLOCKRELEASED: Final = 0x8045 +DBT_VOLLOCKUNLOCKFAILED: Final = 0x8046 +LOCKP_ALLOW_WRITES: Final = 0x01 +LOCKP_FAIL_WRITES: Final = 0x00 +LOCKP_FAIL_MEM_MAPPING: Final = 0x02 +LOCKP_ALLOW_MEM_MAPPING: Final = 0x00 +LOCKP_USER_MASK: Final = 0x03 +LOCKP_LOCK_FOR_FORMAT: Final = 0x04 +LOCKF_LOGICAL_LOCK: Final = 0x00 +LOCKF_PHYSICAL_LOCK: Final = 0x01 +DBT_NO_DISK_SPACE: Final = 0x0047 +DBT_LOW_DISK_SPACE: Final = 0x0048 +DBT_CONFIGMGPRIVATE: Final = 0x7FFF +DBT_DEVICEARRIVAL: Final = 0x8000 +DBT_DEVICEQUERYREMOVE: Final = 0x8001 +DBT_DEVICEQUERYREMOVEFAILED: Final = 0x8002 +DBT_DEVICEREMOVEPENDING: Final = 0x8003 +DBT_DEVICEREMOVECOMPLETE: Final = 0x8004 +DBT_DEVICETYPESPECIFIC: Final = 0x8005 +DBT_CUSTOMEVENT: Final = 0x8006 +DBT_DEVTYP_OEM: Final = 0x00000000 +DBT_DEVTYP_DEVNODE: Final = 0x00000001 +DBT_DEVTYP_VOLUME: Final = 0x00000002 +DBT_DEVTYP_PORT: Final = 0x00000003 +DBT_DEVTYP_NET: Final = 0x00000004 +DBT_DEVTYP_DEVICEINTERFACE: Final = 0x00000005 +DBT_DEVTYP_HANDLE: Final = 0x00000006 +DBTF_MEDIA: Final = 0x0001 +DBTF_NET: Final = 0x0002 +DBTF_RESOURCE: Final = 0x00000001 +DBTF_XPORT: Final = 0x00000002 +DBTF_SLOWNET: Final = 0x00000004 +DBT_VPOWERDAPI: Final = 0x8100 +DBT_USERDEFINED: Final = 0xFFFF + +IME_CMODE_ALPHANUMERIC: Final = 0x0000 +IME_CMODE_NATIVE: Final = 0x0001 +IME_CMODE_CHINESE: Final = IME_CMODE_NATIVE +IME_CMODE_HANGUL: Final = IME_CMODE_NATIVE +IME_CMODE_JAPANESE: Final = IME_CMODE_NATIVE +IME_CMODE_KATAKANA: Final = 0x0002 +IME_CMODE_LANGUAGE: Final = 0x0003 +IME_CMODE_FULLSHAPE: Final = 0x0008 +IME_CMODE_ROMAN: Final = 0x0010 +IME_CMODE_CHARCODE: Final = 0x0020 +IME_CMODE_HANJACONVERT: Final = 0x0040 +IME_CMODE_NATIVESYMBOL: Final = 0x0080 diff --git a/stubs/pywin32/win32/lib/win32cryptcon.pyi b/stubs/pywin32/win32/lib/win32cryptcon.pyi new file mode 100644 index 000000000000..7a3dca662ebb --- /dev/null +++ b/stubs/pywin32/win32/lib/win32cryptcon.pyi @@ -0,0 +1,1792 @@ +from typing import Final + +def GET_ALG_CLASS(x: int) -> int: ... +def GET_ALG_TYPE(x: int) -> int: ... +def GET_ALG_SID(x: int) -> int: ... + +ALG_CLASS_ANY: Final = 0 +ALG_CLASS_SIGNATURE: Final = 0x2000 +ALG_CLASS_MSG_ENCRYPT: Final = 0x4000 +ALG_CLASS_DATA_ENCRYPT: Final = 0x6000 +ALG_CLASS_HASH: Final = 0x8000 +ALG_CLASS_KEY_EXCHANGE: Final = 0xA000 +ALG_CLASS_ALL: Final = 0xE000 +ALG_TYPE_ANY: Final = 0x0000 +ALG_TYPE_DSS: Final = 0x0200 +ALG_TYPE_RSA: Final = 0x0400 +ALG_TYPE_BLOCK: Final = 0x0600 +ALG_TYPE_STREAM: Final = 0x0800 +ALG_TYPE_DH: Final = 0x0A00 +ALG_TYPE_SECURECHANNEL: Final = 0x0C00 +ALG_SID_ANY: Final = 0 +ALG_SID_RSA_ANY: Final = 0 +ALG_SID_RSA_PKCS: Final = 1 +ALG_SID_RSA_MSATWORK: Final = 2 +ALG_SID_RSA_ENTRUST: Final = 3 +ALG_SID_RSA_PGP: Final = 4 +ALG_SID_DSS_ANY: Final = 0 +ALG_SID_DSS_PKCS: Final = 1 +ALG_SID_DSS_DMS: Final = 2 +ALG_SID_DES: Final = 1 +ALG_SID_3DES: Final = 3 +ALG_SID_DESX: Final = 4 +ALG_SID_IDEA: Final = 5 +ALG_SID_CAST: Final = 6 +ALG_SID_SAFERSK64: Final = 7 +ALG_SID_SAFERSK128: Final = 8 +ALG_SID_3DES_112: Final = 9 +ALG_SID_CYLINK_MEK: Final = 12 +ALG_SID_RC5: Final = 13 +ALG_SID_AES_128: Final = 14 +ALG_SID_AES_192: Final = 15 +ALG_SID_AES_256: Final = 16 +ALG_SID_AES: Final = 17 +ALG_SID_SKIPJACK: Final = 10 +ALG_SID_TEK: Final = 11 +CRYPT_MODE_CBCI: Final = 6 +CRYPT_MODE_CFBP: Final = 7 +CRYPT_MODE_OFBP: Final = 8 +CRYPT_MODE_CBCOFM: Final = 9 +CRYPT_MODE_CBCOFMI: Final = 10 +ALG_SID_RC2: Final = 2 +ALG_SID_RC4: Final = 1 +ALG_SID_SEAL: Final = 2 +ALG_SID_DH_SANDF: Final = 1 +ALG_SID_DH_EPHEM: Final = 2 +ALG_SID_AGREED_KEY_ANY: Final = 3 +ALG_SID_KEA: Final = 4 +ALG_SID_MD2: Final = 1 +ALG_SID_MD4: Final = 2 +ALG_SID_MD5: Final = 3 +ALG_SID_SHA: Final = 4 +ALG_SID_SHA1: Final = 4 +ALG_SID_MAC: Final = 5 +ALG_SID_RIPEMD: Final = 6 +ALG_SID_RIPEMD160: Final = 7 +ALG_SID_SSL3SHAMD5: Final = 8 +ALG_SID_HMAC: Final = 9 +ALG_SID_TLS1PRF: Final = 10 +ALG_SID_HASH_REPLACE_OWF: Final = 11 +ALG_SID_SHA_256: Final = 12 +ALG_SID_SHA_384: Final = 13 +ALG_SID_SHA_512: Final = 14 +ALG_SID_SSL3_MASTER: Final = 1 +ALG_SID_SCHANNEL_MASTER_HASH: Final = 2 +ALG_SID_SCHANNEL_MAC_KEY: Final = 3 +ALG_SID_PCT1_MASTER: Final = 4 +ALG_SID_SSL2_MASTER: Final = 5 +ALG_SID_TLS1_MASTER: Final = 6 +ALG_SID_SCHANNEL_ENC_KEY: Final = 7 +ALG_SID_EXAMPLE: Final = 80 +CALG_MD2: Final = 0x8001 +CALG_MD4: Final = 0x8002 +CALG_MD5: Final = 0x8003 +CALG_SHA: Final = 0x8004 +CALG_SHA1: Final = 0x8004 +CALG_MAC: Final = 0x8005 +CALG_RSA_SIGN: Final = 0x2400 +CALG_DSS_SIGN: Final = 0x2200 +CALG_NO_SIGN: Final = 0x2000 +CALG_RSA_KEYX: Final = 0xA400 +CALG_DES: Final = 0x6601 +CALG_3DES_112: Final = 0x6609 +CALG_3DES: Final = 0x6603 +CALG_DESX: Final = 0x6604 +CALG_RC2: Final = 0x6602 +CALG_RC4: Final = 0x6801 +CALG_SEAL: Final = 0x6802 +CALG_DH_SF: Final = 0xAA01 +CALG_DH_EPHEM: Final = 0xAA02 +CALG_AGREEDKEY_ANY: Final = 0xAA03 +CALG_KEA_KEYX: Final = 0xAA04 +CALG_HUGHES_MD5: Final = 0xA003 +CALG_SKIPJACK: Final = 0x660A +CALG_TEK: Final = 0x660B +CALG_CYLINK_MEK: Final = 0x660C +CALG_SSL3_SHAMD5: Final = 0x8008 +CALG_SSL3_MASTER: Final = 0x4C01 +CALG_SCHANNEL_MASTER_HASH: Final = 0x4C02 +CALG_SCHANNEL_MAC_KEY: Final = 0x4C03 +CALG_SCHANNEL_ENC_KEY: Final = 0x4C07 +CALG_PCT1_MASTER: Final = 0x4C04 +CALG_SSL2_MASTER: Final = 0x4C05 +CALG_TLS1_MASTER: Final = 0x4C06 +CALG_RC5: Final = 0x660D +CALG_HMAC: Final = 0x8009 +CALG_TLS1PRF: Final = 0x800A +CALG_HASH_REPLACE_OWF: Final = 0x800B +CALG_AES_128: Final = 0x660E +CALG_AES_192: Final = 0x660F +CALG_AES_256: Final = 0x6610 +CALG_AES: Final = 0x6611 +CALG_SHA_256: Final = 0x800C +CALG_SHA_384: Final = 0x800D +CALG_SHA_512: Final = 0x800E +CRYPT_VERIFYCONTEXT: Final = -268435456 +CRYPT_NEWKEYSET: Final = 0x00000008 +CRYPT_DELETEKEYSET: Final = 0x00000010 +CRYPT_MACHINE_KEYSET: Final = 0x00000020 +CRYPT_SILENT: Final = 0x00000040 +CRYPT_EXPORTABLE: Final = 0x00000001 +CRYPT_USER_PROTECTED: Final = 0x00000002 +CRYPT_CREATE_SALT: Final = 0x00000004 +CRYPT_UPDATE_KEY: Final = 0x00000008 +CRYPT_NO_SALT: Final = 0x00000010 +CRYPT_PREGEN: Final = 0x00000040 +CRYPT_RECIPIENT: Final = 0x00000010 +CRYPT_INITIATOR: Final = 0x00000040 +CRYPT_ONLINE: Final = 0x00000080 +CRYPT_SF: Final = 0x00000100 +CRYPT_CREATE_IV: Final = 0x00000200 +CRYPT_KEK: Final = 0x00000400 +CRYPT_DATA_KEY: Final = 0x00000800 +CRYPT_VOLATILE: Final = 0x00001000 +CRYPT_SGCKEY: Final = 0x00002000 +CRYPT_ARCHIVABLE: Final = 0x00004000 +RSA1024BIT_KEY: Final = 0x04000000 +CRYPT_SERVER: Final = 0x00000400 +KEY_LENGTH_MASK: Final = -65536 +CRYPT_Y_ONLY: Final = 0x00000001 +CRYPT_SSL2_FALLBACK: Final = 0x00000002 +CRYPT_DESTROYKEY: Final = 0x00000004 +CRYPT_OAEP: Final = 0x00000040 +CRYPT_BLOB_VER3: Final = 0x00000080 +CRYPT_IPSEC_HMAC_KEY: Final = 0x00000100 +CRYPT_DECRYPT_RSA_NO_PADDING_CHECK: Final = 0x00000020 +CRYPT_SECRETDIGEST: Final = 0x00000001 +CRYPT_OWF_REPL_LM_HASH: Final = 0x00000001 +CRYPT_LITTLE_ENDIAN: Final = 0x00000001 +CRYPT_NOHASHOID: Final = 0x00000001 +CRYPT_TYPE2_FORMAT: Final = 0x00000002 +CRYPT_X931_FORMAT: Final = 0x00000004 +CRYPT_MACHINE_DEFAULT: Final = 0x00000001 +CRYPT_USER_DEFAULT: Final = 0x00000002 +CRYPT_DELETE_DEFAULT: Final = 0x00000004 +SIMPLEBLOB: Final = 0x1 +PUBLICKEYBLOB: Final = 0x6 +PRIVATEKEYBLOB: Final = 0x7 +PLAINTEXTKEYBLOB: Final = 0x8 +OPAQUEKEYBLOB: Final = 0x9 +PUBLICKEYBLOBEX: Final = 0xA +SYMMETRICWRAPKEYBLOB: Final = 0xB +AT_KEYEXCHANGE: Final = 1 +AT_SIGNATURE: Final = 2 +CRYPT_USERDATA: Final = 1 +KP_IV: Final = 1 +KP_SALT: Final = 2 +KP_PADDING: Final = 3 +KP_MODE: Final = 4 +KP_MODE_BITS: Final = 5 +KP_PERMISSIONS: Final = 6 +KP_ALGID: Final = 7 +KP_BLOCKLEN: Final = 8 +KP_KEYLEN: Final = 9 +KP_SALT_EX: Final = 10 +KP_P: Final = 11 +KP_G: Final = 12 +KP_Q: Final = 13 +KP_X: Final = 14 +KP_Y: Final = 15 +KP_RA: Final = 16 +KP_RB: Final = 17 +KP_INFO: Final = 18 +KP_EFFECTIVE_KEYLEN: Final = 19 +KP_SCHANNEL_ALG: Final = 20 +KP_CLIENT_RANDOM: Final = 21 +KP_SERVER_RANDOM: Final = 22 +KP_RP: Final = 23 +KP_PRECOMP_MD5: Final = 24 +KP_PRECOMP_SHA: Final = 25 +KP_CERTIFICATE: Final = 26 +KP_CLEAR_KEY: Final = 27 +KP_PUB_EX_LEN: Final = 28 +KP_PUB_EX_VAL: Final = 29 +KP_KEYVAL: Final = 30 +KP_ADMIN_PIN: Final = 31 +KP_KEYEXCHANGE_PIN: Final = 32 +KP_SIGNATURE_PIN: Final = 33 +KP_PREHASH: Final = 34 +KP_ROUNDS: Final = 35 +KP_OAEP_PARAMS: Final = 36 +KP_CMS_KEY_INFO: Final = 37 +KP_CMS_DH_KEY_INFO: Final = 38 +KP_PUB_PARAMS: Final = 39 +KP_VERIFY_PARAMS: Final = 40 +KP_HIGHEST_VERSION: Final = 41 +KP_GET_USE_COUNT: Final = 42 +PKCS5_PADDING: Final = 1 +RANDOM_PADDING: Final = 2 +ZERO_PADDING: Final = 3 +CRYPT_MODE_CBC: Final = 1 +CRYPT_MODE_ECB: Final = 2 +CRYPT_MODE_OFB: Final = 3 +CRYPT_MODE_CFB: Final = 4 +CRYPT_MODE_CTS: Final = 5 +CRYPT_ENCRYPT: Final = 0x0001 +CRYPT_DECRYPT: Final = 0x0002 +CRYPT_EXPORT: Final = 0x0004 +CRYPT_READ: Final = 0x0008 +CRYPT_WRITE: Final = 0x0010 +CRYPT_MAC: Final = 0x0020 +CRYPT_EXPORT_KEY: Final = 0x0040 +CRYPT_IMPORT_KEY: Final = 0x0080 +CRYPT_ARCHIVE: Final = 0x0100 +HP_ALGID: Final = 0x0001 +HP_HASHVAL: Final = 0x0002 +HP_HASHSIZE: Final = 0x0004 +HP_HMAC_INFO: Final = 0x0005 +HP_TLS1PRF_LABEL: Final = 0x0006 +HP_TLS1PRF_SEED: Final = 0x0007 +CRYPT_FAILED: Final = 0 +CRYPT_SUCCEED: Final = 1 + +def RCRYPT_SUCCEEDED(rt: int) -> bool: ... +def RCRYPT_FAILED(rt: int) -> bool: ... + +PP_ENUMALGS: Final = 1 +PP_ENUMCONTAINERS: Final = 2 +PP_IMPTYPE: Final = 3 +PP_NAME: Final = 4 +PP_VERSION: Final = 5 +PP_CONTAINER: Final = 6 +PP_CHANGE_PASSWORD: Final = 7 +PP_KEYSET_SEC_DESCR: Final = 8 +PP_CERTCHAIN: Final = 9 +PP_KEY_TYPE_SUBTYPE: Final = 10 +PP_PROVTYPE: Final = 16 +PP_KEYSTORAGE: Final = 17 +PP_APPLI_CERT: Final = 18 +PP_SYM_KEYSIZE: Final = 19 +PP_SESSION_KEYSIZE: Final = 20 +PP_UI_PROMPT: Final = 21 +PP_ENUMALGS_EX: Final = 22 +PP_ENUMMANDROOTS: Final = 25 +PP_ENUMELECTROOTS: Final = 26 +PP_KEYSET_TYPE: Final = 27 +PP_ADMIN_PIN: Final = 31 +PP_KEYEXCHANGE_PIN: Final = 32 +PP_SIGNATURE_PIN: Final = 33 +PP_SIG_KEYSIZE_INC: Final = 34 +PP_KEYX_KEYSIZE_INC: Final = 35 +PP_UNIQUE_CONTAINER: Final = 36 +PP_SGC_INFO: Final = 37 +PP_USE_HARDWARE_RNG: Final = 38 +PP_KEYSPEC: Final = 39 +PP_ENUMEX_SIGNING_PROT: Final = 40 +PP_CRYPT_COUNT_KEY_USE: Final = 41 +CRYPT_FIRST: Final = 1 +CRYPT_NEXT: Final = 2 +CRYPT_SGC_ENUM: Final = 4 +CRYPT_IMPL_HARDWARE: Final = 1 +CRYPT_IMPL_SOFTWARE: Final = 2 +CRYPT_IMPL_MIXED: Final = 3 +CRYPT_IMPL_UNKNOWN: Final = 4 +CRYPT_IMPL_REMOVABLE: Final = 8 +CRYPT_SEC_DESCR: Final = 0x00000001 +CRYPT_PSTORE: Final = 0x00000002 +CRYPT_UI_PROMPT: Final = 0x00000004 +CRYPT_FLAG_PCT1: Final = 0x0001 +CRYPT_FLAG_SSL2: Final = 0x0002 +CRYPT_FLAG_SSL3: Final = 0x0004 +CRYPT_FLAG_TLS1: Final = 0x0008 +CRYPT_FLAG_IPSEC: Final = 0x0010 +CRYPT_FLAG_SIGNING: Final = 0x0020 +CRYPT_SGC: Final = 0x0001 +CRYPT_FASTSGC: Final = 0x0002 +PP_CLIENT_HWND: Final = 1 +PP_CONTEXT_INFO: Final = 11 +PP_KEYEXCHANGE_KEYSIZE: Final = 12 +PP_SIGNATURE_KEYSIZE: Final = 13 +PP_KEYEXCHANGE_ALG: Final = 14 +PP_SIGNATURE_ALG: Final = 15 +PP_DELETEKEY: Final = 24 +PROV_RSA_FULL: Final = 1 +PROV_RSA_SIG: Final = 2 +PROV_DSS: Final = 3 +PROV_FORTEZZA: Final = 4 +PROV_MS_EXCHANGE: Final = 5 +PROV_SSL: Final = 6 +PROV_RSA_SCHANNEL: Final = 12 +PROV_DSS_DH: Final = 13 +PROV_EC_ECDSA_SIG: Final = 14 +PROV_EC_ECNRA_SIG: Final = 15 +PROV_EC_ECDSA_FULL: Final = 16 +PROV_EC_ECNRA_FULL: Final = 17 +PROV_DH_SCHANNEL: Final = 18 +PROV_SPYRUS_LYNKS: Final = 20 +PROV_RNG: Final = 21 +PROV_INTEL_SEC: Final = 22 +PROV_REPLACE_OWF: Final = 23 +PROV_RSA_AES: Final = 24 +MS_DEF_PROV_A: Final = "Microsoft Base Cryptographic Provider v1.0" +MS_DEF_PROV: Final = MS_DEF_PROV_A +MS_ENHANCED_PROV_A: Final = "Microsoft Enhanced Cryptographic Provider v1.0" +MS_ENHANCED_PROV: Final = MS_ENHANCED_PROV_A +MS_STRONG_PROV_A: Final = "Microsoft Strong Cryptographic Provider" +MS_STRONG_PROV: Final = MS_STRONG_PROV_A +MS_DEF_RSA_SIG_PROV_A: Final = "Microsoft RSA Signature Cryptographic Provider" +MS_DEF_RSA_SIG_PROV: Final = MS_DEF_RSA_SIG_PROV_A +MS_DEF_RSA_SCHANNEL_PROV_A: Final = "Microsoft RSA SChannel Cryptographic Provider" +MS_DEF_RSA_SCHANNEL_PROV: Final = MS_DEF_RSA_SCHANNEL_PROV_A +MS_DEF_DSS_PROV_A: Final = "Microsoft Base DSS Cryptographic Provider" +MS_DEF_DSS_PROV: Final = MS_DEF_DSS_PROV_A +MS_DEF_DSS_DH_PROV_A: Final[str] +MS_DEF_DSS_DH_PROV: Final = MS_DEF_DSS_DH_PROV_A +MS_ENH_DSS_DH_PROV_A: Final[str] +MS_ENH_DSS_DH_PROV: Final = MS_ENH_DSS_DH_PROV_A +MS_DEF_DH_SCHANNEL_PROV_A: Final = "Microsoft DH SChannel Cryptographic Provider" +MS_DEF_DH_SCHANNEL_PROV: Final = MS_DEF_DH_SCHANNEL_PROV_A +MS_SCARD_PROV_A: Final = "Microsoft Base Smart Card Crypto Provider" +MS_SCARD_PROV: Final = MS_SCARD_PROV_A +MS_ENH_RSA_AES_PROV_A: Final[str] +MS_ENH_RSA_AES_PROV: Final = MS_ENH_RSA_AES_PROV_A +MAXUIDLEN: Final = 64 +EXPO_OFFLOAD_REG_VALUE: Final = "ExpoOffload" +EXPO_OFFLOAD_FUNC_NAME: Final = "OffloadModExpo" +szKEY_CRYPTOAPI_PRIVATE_KEY_OPTIONS: Final = "Software\\Policies\\Microsoft\\Cryptography" +szFORCE_KEY_PROTECTION: Final = "ForceKeyProtection" +dwFORCE_KEY_PROTECTION_DISABLED: Final = 0x0 +dwFORCE_KEY_PROTECTION_USER_SELECT: Final = 0x1 +dwFORCE_KEY_PROTECTION_HIGH: Final = 0x2 +szKEY_CACHE_ENABLED: Final = "CachePrivateKeys" +szKEY_CACHE_SECONDS: Final = "PrivateKeyLifetimeSeconds" +CUR_BLOB_VERSION: Final = 2 +SCHANNEL_MAC_KEY: Final = 0x00000000 +SCHANNEL_ENC_KEY: Final = 0x00000001 +INTERNATIONAL_USAGE: Final = 0x00000001 +szOID_RSA: Final = "1.2.840.113549" +szOID_PKCS: Final = "1.2.840.113549.1" +szOID_RSA_HASH: Final = "1.2.840.113549.2" +szOID_RSA_ENCRYPT: Final = "1.2.840.113549.3" +szOID_PKCS_1: Final = "1.2.840.113549.1.1" +szOID_PKCS_2: Final = "1.2.840.113549.1.2" +szOID_PKCS_3: Final = "1.2.840.113549.1.3" +szOID_PKCS_4: Final = "1.2.840.113549.1.4" +szOID_PKCS_5: Final = "1.2.840.113549.1.5" +szOID_PKCS_6: Final = "1.2.840.113549.1.6" +szOID_PKCS_7: Final = "1.2.840.113549.1.7" +szOID_PKCS_8: Final = "1.2.840.113549.1.8" +szOID_PKCS_9: Final = "1.2.840.113549.1.9" +szOID_PKCS_10: Final = "1.2.840.113549.1.10" +szOID_PKCS_12: Final = "1.2.840.113549.1.12" +szOID_RSA_RSA: Final = "1.2.840.113549.1.1.1" +szOID_RSA_MD2RSA: Final = "1.2.840.113549.1.1.2" +szOID_RSA_MD4RSA: Final = "1.2.840.113549.1.1.3" +szOID_RSA_MD5RSA: Final = "1.2.840.113549.1.1.4" +szOID_RSA_SHA1RSA: Final = "1.2.840.113549.1.1.5" +szOID_RSA_SETOAEP_RSA: Final = "1.2.840.113549.1.1.6" +szOID_RSA_DH: Final = "1.2.840.113549.1.3.1" +szOID_RSA_data: Final = "1.2.840.113549.1.7.1" +szOID_RSA_signedData: Final = "1.2.840.113549.1.7.2" +szOID_RSA_envelopedData: Final = "1.2.840.113549.1.7.3" +szOID_RSA_signEnvData: Final = "1.2.840.113549.1.7.4" +szOID_RSA_digestedData: Final = "1.2.840.113549.1.7.5" +szOID_RSA_hashedData: Final = "1.2.840.113549.1.7.5" +szOID_RSA_encryptedData: Final = "1.2.840.113549.1.7.6" +szOID_RSA_emailAddr: Final = "1.2.840.113549.1.9.1" +szOID_RSA_unstructName: Final = "1.2.840.113549.1.9.2" +szOID_RSA_contentType: Final = "1.2.840.113549.1.9.3" +szOID_RSA_messageDigest: Final = "1.2.840.113549.1.9.4" +szOID_RSA_signingTime: Final = "1.2.840.113549.1.9.5" +szOID_RSA_counterSign: Final = "1.2.840.113549.1.9.6" +szOID_RSA_challengePwd: Final = "1.2.840.113549.1.9.7" +szOID_RSA_unstructAddr: Final = "1.2.840.113549.1.9.8" +szOID_RSA_extCertAttrs: Final = "1.2.840.113549.1.9.9" +szOID_RSA_certExtensions: Final = "1.2.840.113549.1.9.14" +szOID_RSA_SMIMECapabilities: Final = "1.2.840.113549.1.9.15" +szOID_RSA_preferSignedData: Final = "1.2.840.113549.1.9.15.1" +szOID_RSA_SMIMEalg: Final = "1.2.840.113549.1.9.16.3" +szOID_RSA_SMIMEalgESDH: Final = "1.2.840.113549.1.9.16.3.5" +szOID_RSA_SMIMEalgCMS3DESwrap: Final = "1.2.840.113549.1.9.16.3.6" +szOID_RSA_SMIMEalgCMSRC2wrap: Final = "1.2.840.113549.1.9.16.3.7" +szOID_RSA_MD2: Final = "1.2.840.113549.2.2" +szOID_RSA_MD4: Final = "1.2.840.113549.2.4" +szOID_RSA_MD5: Final = "1.2.840.113549.2.5" +szOID_RSA_RC2CBC: Final = "1.2.840.113549.3.2" +szOID_RSA_RC4: Final = "1.2.840.113549.3.4" +szOID_RSA_DES_EDE3_CBC: Final = "1.2.840.113549.3.7" +szOID_RSA_RC5_CBCPad: Final = "1.2.840.113549.3.9" +szOID_ANSI_X942: Final = "1.2.840.10046" +szOID_ANSI_X942_DH: Final = "1.2.840.10046.2.1" +szOID_X957: Final = "1.2.840.10040" +szOID_X957_DSA: Final = "1.2.840.10040.4.1" +szOID_X957_SHA1DSA: Final = "1.2.840.10040.4.3" +szOID_DS: Final = "2.5" +szOID_DSALG: Final = "2.5.8" +szOID_DSALG_CRPT: Final = "2.5.8.1" +szOID_DSALG_HASH: Final = "2.5.8.2" +szOID_DSALG_SIGN: Final = "2.5.8.3" +szOID_DSALG_RSA: Final = "2.5.8.1.1" +szOID_OIW: Final = "1.3.14" +szOID_OIWSEC: Final = "1.3.14.3.2" +szOID_OIWSEC_md4RSA: Final = "1.3.14.3.2.2" +szOID_OIWSEC_md5RSA: Final = "1.3.14.3.2.3" +szOID_OIWSEC_md4RSA2: Final = "1.3.14.3.2.4" +szOID_OIWSEC_desECB: Final = "1.3.14.3.2.6" +szOID_OIWSEC_desCBC: Final = "1.3.14.3.2.7" +szOID_OIWSEC_desOFB: Final = "1.3.14.3.2.8" +szOID_OIWSEC_desCFB: Final = "1.3.14.3.2.9" +szOID_OIWSEC_desMAC: Final = "1.3.14.3.2.10" +szOID_OIWSEC_rsaSign: Final = "1.3.14.3.2.11" +szOID_OIWSEC_dsa: Final = "1.3.14.3.2.12" +szOID_OIWSEC_shaDSA: Final = "1.3.14.3.2.13" +szOID_OIWSEC_mdc2RSA: Final = "1.3.14.3.2.14" +szOID_OIWSEC_shaRSA: Final = "1.3.14.3.2.15" +szOID_OIWSEC_dhCommMod: Final = "1.3.14.3.2.16" +szOID_OIWSEC_desEDE: Final = "1.3.14.3.2.17" +szOID_OIWSEC_sha: Final = "1.3.14.3.2.18" +szOID_OIWSEC_mdc2: Final = "1.3.14.3.2.19" +szOID_OIWSEC_dsaComm: Final = "1.3.14.3.2.20" +szOID_OIWSEC_dsaCommSHA: Final = "1.3.14.3.2.21" +szOID_OIWSEC_rsaXchg: Final = "1.3.14.3.2.22" +szOID_OIWSEC_keyHashSeal: Final = "1.3.14.3.2.23" +szOID_OIWSEC_md2RSASign: Final = "1.3.14.3.2.24" +szOID_OIWSEC_md5RSASign: Final = "1.3.14.3.2.25" +szOID_OIWSEC_sha1: Final = "1.3.14.3.2.26" +szOID_OIWSEC_dsaSHA1: Final = "1.3.14.3.2.27" +szOID_OIWSEC_dsaCommSHA1: Final = "1.3.14.3.2.28" +szOID_OIWSEC_sha1RSASign: Final = "1.3.14.3.2.29" +szOID_OIWDIR: Final = "1.3.14.7.2" +szOID_OIWDIR_CRPT: Final = "1.3.14.7.2.1" +szOID_OIWDIR_HASH: Final = "1.3.14.7.2.2" +szOID_OIWDIR_SIGN: Final = "1.3.14.7.2.3" +szOID_OIWDIR_md2: Final = "1.3.14.7.2.2.1" +szOID_OIWDIR_md2RSA: Final = "1.3.14.7.2.3.1" +szOID_INFOSEC: Final = "2.16.840.1.101.2.1" +szOID_INFOSEC_sdnsSignature: Final = "2.16.840.1.101.2.1.1.1" +szOID_INFOSEC_mosaicSignature: Final = "2.16.840.1.101.2.1.1.2" +szOID_INFOSEC_sdnsConfidentiality: Final = "2.16.840.1.101.2.1.1.3" +szOID_INFOSEC_mosaicConfidentiality: Final = "2.16.840.1.101.2.1.1.4" +szOID_INFOSEC_sdnsIntegrity: Final = "2.16.840.1.101.2.1.1.5" +szOID_INFOSEC_mosaicIntegrity: Final = "2.16.840.1.101.2.1.1.6" +szOID_INFOSEC_sdnsTokenProtection: Final = "2.16.840.1.101.2.1.1.7" +szOID_INFOSEC_mosaicTokenProtection: Final = "2.16.840.1.101.2.1.1.8" +szOID_INFOSEC_sdnsKeyManagement: Final = "2.16.840.1.101.2.1.1.9" +szOID_INFOSEC_mosaicKeyManagement: Final = "2.16.840.1.101.2.1.1.10" +szOID_INFOSEC_sdnsKMandSig: Final = "2.16.840.1.101.2.1.1.11" +szOID_INFOSEC_mosaicKMandSig: Final = "2.16.840.1.101.2.1.1.12" +szOID_INFOSEC_SuiteASignature: Final = "2.16.840.1.101.2.1.1.13" +szOID_INFOSEC_SuiteAConfidentiality: Final = "2.16.840.1.101.2.1.1.14" +szOID_INFOSEC_SuiteAIntegrity: Final = "2.16.840.1.101.2.1.1.15" +szOID_INFOSEC_SuiteATokenProtection: Final = "2.16.840.1.101.2.1.1.16" +szOID_INFOSEC_SuiteAKeyManagement: Final = "2.16.840.1.101.2.1.1.17" +szOID_INFOSEC_SuiteAKMandSig: Final = "2.16.840.1.101.2.1.1.18" +szOID_INFOSEC_mosaicUpdatedSig: Final = "2.16.840.1.101.2.1.1.19" +szOID_INFOSEC_mosaicKMandUpdSig: Final = "2.16.840.1.101.2.1.1.20" +szOID_INFOSEC_mosaicUpdatedInteg: Final = "2.16.840.1.101.2.1.1.21" +szOID_COMMON_NAME: Final = "2.5.4.3" +szOID_SUR_NAME: Final = "2.5.4.4" +szOID_DEVICE_SERIAL_NUMBER: Final = "2.5.4.5" +szOID_COUNTRY_NAME: Final = "2.5.4.6" +szOID_LOCALITY_NAME: Final = "2.5.4.7" +szOID_STATE_OR_PROVINCE_NAME: Final = "2.5.4.8" +szOID_STREET_ADDRESS: Final = "2.5.4.9" +szOID_ORGANIZATION_NAME: Final = "2.5.4.10" +szOID_ORGANIZATIONAL_UNIT_NAME: Final = "2.5.4.11" +szOID_TITLE: Final = "2.5.4.12" +szOID_DESCRIPTION: Final = "2.5.4.13" +szOID_SEARCH_GUIDE: Final = "2.5.4.14" +szOID_BUSINESS_CATEGORY: Final = "2.5.4.15" +szOID_POSTAL_ADDRESS: Final = "2.5.4.16" +szOID_POSTAL_CODE: Final = "2.5.4.17" +szOID_POST_OFFICE_BOX: Final = "2.5.4.18" +szOID_PHYSICAL_DELIVERY_OFFICE_NAME: Final = "2.5.4.19" +szOID_TELEPHONE_NUMBER: Final = "2.5.4.20" +szOID_TELEX_NUMBER: Final = "2.5.4.21" +szOID_TELETEXT_TERMINAL_IDENTIFIER: Final = "2.5.4.22" +szOID_FACSIMILE_TELEPHONE_NUMBER: Final = "2.5.4.23" +szOID_X21_ADDRESS: Final = "2.5.4.24" +szOID_INTERNATIONAL_ISDN_NUMBER: Final = "2.5.4.25" +szOID_REGISTERED_ADDRESS: Final = "2.5.4.26" +szOID_DESTINATION_INDICATOR: Final = "2.5.4.27" +szOID_PREFERRED_DELIVERY_METHOD: Final = "2.5.4.28" +szOID_PRESENTATION_ADDRESS: Final = "2.5.4.29" +szOID_SUPPORTED_APPLICATION_CONTEXT: Final = "2.5.4.30" +szOID_MEMBER: Final = "2.5.4.31" +szOID_OWNER: Final = "2.5.4.32" +szOID_ROLE_OCCUPANT: Final = "2.5.4.33" +szOID_SEE_ALSO: Final = "2.5.4.34" +szOID_USER_PASSWORD: Final = "2.5.4.35" +szOID_USER_CERTIFICATE: Final = "2.5.4.36" +szOID_CA_CERTIFICATE: Final = "2.5.4.37" +szOID_AUTHORITY_REVOCATION_LIST: Final = "2.5.4.38" +szOID_CERTIFICATE_REVOCATION_LIST: Final = "2.5.4.39" +szOID_CROSS_CERTIFICATE_PAIR: Final = "2.5.4.40" +szOID_GIVEN_NAME: Final = "2.5.4.42" +szOID_INITIALS: Final = "2.5.4.43" +szOID_DN_QUALIFIER: Final = "2.5.4.46" +szOID_DOMAIN_COMPONENT: Final = "0.9.2342.19200300.100.1.25" +szOID_PKCS_12_FRIENDLY_NAME_ATTR: Final = "1.2.840.113549.1.9.20" +szOID_PKCS_12_LOCAL_KEY_ID: Final = "1.2.840.113549.1.9.21" +szOID_PKCS_12_KEY_PROVIDER_NAME_ATTR: Final = "1.3.6.1.4.1.311.17.1" +szOID_LOCAL_MACHINE_KEYSET: Final = "1.3.6.1.4.1.311.17.2" +szOID_KEYID_RDN: Final = "1.3.6.1.4.1.311.10.7.1" +CERT_RDN_ANY_TYPE: Final = 0 +CERT_RDN_ENCODED_BLOB: Final = 1 +CERT_RDN_OCTET_STRING: Final = 2 +CERT_RDN_NUMERIC_STRING: Final = 3 +CERT_RDN_PRINTABLE_STRING: Final = 4 +CERT_RDN_TELETEX_STRING: Final = 5 +CERT_RDN_T61_STRING: Final = 5 +CERT_RDN_VIDEOTEX_STRING: Final = 6 +CERT_RDN_IA5_STRING: Final = 7 +CERT_RDN_GRAPHIC_STRING: Final = 8 +CERT_RDN_VISIBLE_STRING: Final = 9 +CERT_RDN_ISO646_STRING: Final = 9 +CERT_RDN_GENERAL_STRING: Final = 10 +CERT_RDN_UNIVERSAL_STRING: Final = 11 +CERT_RDN_INT4_STRING: Final = 11 +CERT_RDN_BMP_STRING: Final = 12 +CERT_RDN_UNICODE_STRING: Final = 12 +CERT_RDN_UTF8_STRING: Final = 13 +CERT_RDN_TYPE_MASK: Final = 0x000000FF +CERT_RDN_FLAGS_MASK: Final = -16777216 +CERT_RDN_ENABLE_T61_UNICODE_FLAG: Final = -2147483648 +CERT_RDN_ENABLE_UTF8_UNICODE_FLAG: Final = 0x20000000 +CERT_RDN_DISABLE_CHECK_TYPE_FLAG: Final = 0x40000000 +CERT_RDN_DISABLE_IE4_UTF8_FLAG: Final = 0x01000000 +CERT_RSA_PUBLIC_KEY_OBJID: Final = szOID_RSA_RSA +CERT_DEFAULT_OID_PUBLIC_KEY_SIGN: Final = szOID_RSA_RSA +CERT_DEFAULT_OID_PUBLIC_KEY_XCHG: Final = szOID_RSA_RSA +CERT_V1: Final = 0 +CERT_V2: Final = 1 +CERT_V3: Final = 2 +CERT_INFO_VERSION_FLAG: Final = 1 +CERT_INFO_SERIAL_NUMBER_FLAG: Final = 2 +CERT_INFO_SIGNATURE_ALGORITHM_FLAG: Final = 3 +CERT_INFO_ISSUER_FLAG: Final = 4 +CERT_INFO_NOT_BEFORE_FLAG: Final = 5 +CERT_INFO_NOT_AFTER_FLAG: Final = 6 +CERT_INFO_SUBJECT_FLAG: Final = 7 +CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG: Final = 8 +CERT_INFO_ISSUER_UNIQUE_ID_FLAG: Final = 9 +CERT_INFO_SUBJECT_UNIQUE_ID_FLAG: Final = 10 +CERT_INFO_EXTENSION_FLAG: Final = 11 +CRL_V1: Final = 0 +CRL_V2: Final = 1 +CERT_REQUEST_V1: Final = 0 +CERT_KEYGEN_REQUEST_V1: Final = 0 +CTL_V1: Final = 0 +CERT_ENCODING_TYPE_MASK: Final = 0x0000FFFF +CMSG_ENCODING_TYPE_MASK: Final = -65536 + +def GET_CERT_ENCODING_TYPE(X: int) -> int: ... +def GET_CMSG_ENCODING_TYPE(X: int) -> int: ... + +CRYPT_ASN_ENCODING: Final = 0x00000001 +CRYPT_NDR_ENCODING: Final = 0x00000002 +X509_ASN_ENCODING: Final = 0x00000001 +X509_NDR_ENCODING: Final = 0x00000002 +PKCS_7_ASN_ENCODING: Final = 0x00010000 +PKCS_7_NDR_ENCODING: Final = 0x00020000 +CRYPT_FORMAT_STR_MULTI_LINE: Final = 0x0001 +CRYPT_FORMAT_STR_NO_HEX: Final = 0x0010 +CRYPT_FORMAT_SIMPLE: Final = 0x0001 +CRYPT_FORMAT_X509: Final = 0x0002 +CRYPT_FORMAT_OID: Final = 0x0004 +CRYPT_FORMAT_RDN_SEMICOLON: Final = 0x0100 +CRYPT_FORMAT_RDN_CRLF: Final = 0x0200 +CRYPT_FORMAT_RDN_UNQUOTE: Final = 0x0400 +CRYPT_FORMAT_RDN_REVERSE: Final = 0x0800 +CRYPT_FORMAT_COMMA: Final = 0x1000 +CRYPT_FORMAT_SEMICOLON: Final = CRYPT_FORMAT_RDN_SEMICOLON +CRYPT_FORMAT_CRLF: Final = CRYPT_FORMAT_RDN_CRLF +CRYPT_ENCODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: Final = 0x8 +CRYPT_ENCODE_ALLOC_FLAG: Final = 0x8000 +CRYPT_UNICODE_NAME_ENCODE_ENABLE_T61_UNICODE_FLAG: Final = CERT_RDN_ENABLE_T61_UNICODE_FLAG +CRYPT_UNICODE_NAME_ENCODE_ENABLE_UTF8_UNICODE_FLAG: Final = CERT_RDN_ENABLE_UTF8_UNICODE_FLAG +CRYPT_UNICODE_NAME_ENCODE_DISABLE_CHECK_TYPE_FLAG: Final = CERT_RDN_DISABLE_CHECK_TYPE_FLAG +CRYPT_SORTED_CTL_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: Final = 0x10000 +CRYPT_DECODE_NOCOPY_FLAG: Final = 0x1 +CRYPT_DECODE_TO_BE_SIGNED_FLAG: Final = 0x2 +CRYPT_DECODE_SHARE_OID_STRING_FLAG: Final = 0x4 +CRYPT_DECODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: Final = 0x8 +CRYPT_DECODE_ALLOC_FLAG: Final = 0x8000 +CRYPT_UNICODE_NAME_DECODE_DISABLE_IE4_UTF8_FLAG: Final = CERT_RDN_DISABLE_IE4_UTF8_FLAG +CRYPT_ENCODE_DECODE_NONE: Final = 0 +X509_CERT: Final = 1 +X509_CERT_TO_BE_SIGNED: Final = 2 +X509_CERT_CRL_TO_BE_SIGNED: Final = 3 +X509_CERT_REQUEST_TO_BE_SIGNED: Final = 4 +X509_EXTENSIONS: Final = 5 +X509_NAME_VALUE: Final = 6 +X509_NAME: Final = 7 +X509_PUBLIC_KEY_INFO: Final = 8 +X509_AUTHORITY_KEY_ID: Final = 9 +X509_KEY_ATTRIBUTES: Final = 10 +X509_KEY_USAGE_RESTRICTION: Final = 11 +X509_ALTERNATE_NAME: Final = 12 +X509_BASIC_CONSTRAINTS: Final = 13 +X509_KEY_USAGE: Final = 14 +X509_BASIC_CONSTRAINTS2: Final = 15 +X509_CERT_POLICIES: Final = 16 +PKCS_UTC_TIME: Final = 17 +PKCS_TIME_REQUEST: Final = 18 +RSA_CSP_PUBLICKEYBLOB: Final = 19 +X509_UNICODE_NAME: Final = 20 +X509_KEYGEN_REQUEST_TO_BE_SIGNED: Final = 21 +PKCS_ATTRIBUTE: Final = 22 +PKCS_CONTENT_INFO_SEQUENCE_OF_ANY: Final = 23 +X509_UNICODE_NAME_VALUE: Final = 24 +X509_ANY_STRING: Final = X509_NAME_VALUE +X509_UNICODE_ANY_STRING: Final = X509_UNICODE_NAME_VALUE +X509_OCTET_STRING: Final = 25 +X509_BITS: Final = 26 +X509_INTEGER: Final = 27 +X509_MULTI_BYTE_INTEGER: Final = 28 +X509_ENUMERATED: Final = 29 +X509_CHOICE_OF_TIME: Final = 30 +X509_AUTHORITY_KEY_ID2: Final = 31 +X509_AUTHORITY_INFO_ACCESS: Final = 32 +X509_SUBJECT_INFO_ACCESS: Final = X509_AUTHORITY_INFO_ACCESS +X509_CRL_REASON_CODE: Final = X509_ENUMERATED +PKCS_CONTENT_INFO: Final = 33 +X509_SEQUENCE_OF_ANY: Final = 34 +X509_CRL_DIST_POINTS: Final = 35 +X509_ENHANCED_KEY_USAGE: Final = 36 +PKCS_CTL: Final = 37 +X509_MULTI_BYTE_UINT: Final = 38 +X509_DSS_PUBLICKEY: Final = X509_MULTI_BYTE_UINT +X509_DSS_PARAMETERS: Final = 39 +X509_DSS_SIGNATURE: Final = 40 +PKCS_RC2_CBC_PARAMETERS: Final = 41 +PKCS_SMIME_CAPABILITIES: Final = 42 +X509_QC_STATEMENTS_EXT: Final = 42 +PKCS_RSA_PRIVATE_KEY: Final = 43 +PKCS_PRIVATE_KEY_INFO: Final = 44 +PKCS_ENCRYPTED_PRIVATE_KEY_INFO: Final = 45 +X509_PKIX_POLICY_QUALIFIER_USERNOTICE: Final = 46 +X509_DH_PUBLICKEY: Final = X509_MULTI_BYTE_UINT +X509_DH_PARAMETERS: Final = 47 +PKCS_ATTRIBUTES: Final = 48 +PKCS_SORTED_CTL: Final = 49 +X509_ECC_SIGNATURE: Final = 47 +X942_DH_PARAMETERS: Final = 50 +X509_BITS_WITHOUT_TRAILING_ZEROES: Final = 51 +X942_OTHER_INFO: Final = 52 +X509_CERT_PAIR: Final = 53 +X509_ISSUING_DIST_POINT: Final = 54 +X509_NAME_CONSTRAINTS: Final = 55 +X509_POLICY_MAPPINGS: Final = 56 +X509_POLICY_CONSTRAINTS: Final = 57 +X509_CROSS_CERT_DIST_POINTS: Final = 58 +CMC_DATA: Final = 59 +CMC_RESPONSE: Final = 60 +CMC_STATUS: Final = 61 +CMC_ADD_EXTENSIONS: Final = 62 +CMC_ADD_ATTRIBUTES: Final = 63 +X509_CERTIFICATE_TEMPLATE: Final = 64 +OCSP_SIGNED_REQUEST: Final = 65 +OCSP_REQUEST: Final = 66 +OCSP_RESPONSE: Final = 67 +OCSP_BASIC_SIGNED_RESPONSE: Final = 68 +OCSP_BASIC_RESPONSE: Final = 69 +X509_LOGOTYPE_EXT: Final = 70 +X509_BIOMETRIC_EXT: Final = 71 +CNG_RSA_PUBLIC_KEY_BLOB: Final = 72 +X509_OBJECT_IDENTIFIER: Final = 73 +X509_ALGORITHM_IDENTIFIER: Final = 74 +PKCS_RSA_SSA_PSS_PARAMETERS: Final = 75 +PKCS_RSAES_OAEP_PARAMETERS: Final = 76 +ECC_CMS_SHARED_INFO: Final = 77 +TIMESTAMP_REQUEST: Final = 78 +TIMESTAMP_RESPONSE: Final = 79 +TIMESTAMP_INFO: Final = 80 +X509_CERT_BUNDLE: Final = 81 +PKCS7_SIGNER_INFO: Final = 500 +CMS_SIGNER_INFO: Final = 501 +szOID_AUTHORITY_KEY_IDENTIFIER: Final = "2.5.29.1" +szOID_KEY_ATTRIBUTES: Final = "2.5.29.2" +szOID_CERT_POLICIES_95: Final = "2.5.29.3" +szOID_KEY_USAGE_RESTRICTION: Final = "2.5.29.4" +szOID_SUBJECT_ALT_NAME: Final = "2.5.29.7" +szOID_ISSUER_ALT_NAME: Final = "2.5.29.8" +szOID_BASIC_CONSTRAINTS: Final = "2.5.29.10" +szOID_KEY_USAGE: Final = "2.5.29.15" +szOID_PRIVATEKEY_USAGE_PERIOD: Final = "2.5.29.16" +szOID_BASIC_CONSTRAINTS2: Final = "2.5.29.19" +szOID_CERT_POLICIES: Final = "2.5.29.32" +szOID_ANY_CERT_POLICY: Final = "2.5.29.32.0" +szOID_AUTHORITY_KEY_IDENTIFIER2: Final = "2.5.29.35" +szOID_SUBJECT_KEY_IDENTIFIER: Final = "2.5.29.14" +szOID_SUBJECT_ALT_NAME2: Final = "2.5.29.17" +szOID_ISSUER_ALT_NAME2: Final = "2.5.29.18" +szOID_CRL_REASON_CODE: Final = "2.5.29.21" +szOID_REASON_CODE_HOLD: Final = "2.5.29.23" +szOID_CRL_DIST_POINTS: Final = "2.5.29.31" +szOID_ENHANCED_KEY_USAGE: Final = "2.5.29.37" +szOID_CRL_NUMBER: Final = "2.5.29.20" +szOID_DELTA_CRL_INDICATOR: Final = "2.5.29.27" +szOID_ISSUING_DIST_POINT: Final = "2.5.29.28" +szOID_FRESHEST_CRL: Final = "2.5.29.46" +szOID_NAME_CONSTRAINTS: Final = "2.5.29.30" +szOID_POLICY_MAPPINGS: Final = "2.5.29.33" +szOID_LEGACY_POLICY_MAPPINGS: Final = "2.5.29.5" +szOID_POLICY_CONSTRAINTS: Final = "2.5.29.36" +szOID_RENEWAL_CERTIFICATE: Final = "1.3.6.1.4.1.311.13.1" +szOID_ENROLLMENT_NAME_VALUE_PAIR: Final = "1.3.6.1.4.1.311.13.2.1" +szOID_ENROLLMENT_CSP_PROVIDER: Final = "1.3.6.1.4.1.311.13.2.2" +szOID_OS_VERSION: Final = "1.3.6.1.4.1.311.13.2.3" +szOID_ENROLLMENT_AGENT: Final = "1.3.6.1.4.1.311.20.2.1" +szOID_PKIX: Final = "1.3.6.1.5.5.7" +szOID_PKIX_PE: Final = "1.3.6.1.5.5.7.1" +szOID_AUTHORITY_INFO_ACCESS: Final = "1.3.6.1.5.5.7.1.1" +szOID_CERT_EXTENSIONS: Final = "1.3.6.1.4.1.311.2.1.14" +szOID_NEXT_UPDATE_LOCATION: Final = "1.3.6.1.4.1.311.10.2" +szOID_REMOVE_CERTIFICATE: Final = "1.3.6.1.4.1.311.10.8.1" +szOID_CROSS_CERT_DIST_POINTS: Final = "1.3.6.1.4.1.311.10.9.1" +szOID_CTL: Final = "1.3.6.1.4.1.311.10.1" +szOID_SORTED_CTL: Final = "1.3.6.1.4.1.311.10.1.1" +szOID_SERIALIZED: Final = "1.3.6.1.4.1.311.10.3.3.1" +szOID_NT_PRINCIPAL_NAME: Final = "1.3.6.1.4.1.311.20.2.3" +szOID_PRODUCT_UPDATE: Final = "1.3.6.1.4.1.311.31.1" +szOID_ANY_APPLICATION_POLICY: Final = "1.3.6.1.4.1.311.10.12.1" +szOID_AUTO_ENROLL_CTL_USAGE: Final = "1.3.6.1.4.1.311.20.1" +szOID_ENROLL_CERTTYPE_EXTENSION: Final = "1.3.6.1.4.1.311.20.2" +szOID_CERT_MANIFOLD: Final = "1.3.6.1.4.1.311.20.3" +szOID_CERTSRV_CA_VERSION: Final = "1.3.6.1.4.1.311.21.1" +szOID_CERTSRV_PREVIOUS_CERT_HASH: Final = "1.3.6.1.4.1.311.21.2" +szOID_CRL_VIRTUAL_BASE: Final = "1.3.6.1.4.1.311.21.3" +szOID_CRL_NEXT_PUBLISH: Final = "1.3.6.1.4.1.311.21.4" +szOID_KP_CA_EXCHANGE: Final = "1.3.6.1.4.1.311.21.5" +szOID_KP_KEY_RECOVERY_AGENT: Final = "1.3.6.1.4.1.311.21.6" +szOID_CERTIFICATE_TEMPLATE: Final = "1.3.6.1.4.1.311.21.7" +szOID_ENTERPRISE_OID_ROOT: Final = "1.3.6.1.4.1.311.21.8" +szOID_RDN_DUMMY_SIGNER: Final = "1.3.6.1.4.1.311.21.9" +szOID_APPLICATION_CERT_POLICIES: Final = "1.3.6.1.4.1.311.21.10" +szOID_APPLICATION_POLICY_MAPPINGS: Final = "1.3.6.1.4.1.311.21.11" +szOID_APPLICATION_POLICY_CONSTRAINTS: Final = "1.3.6.1.4.1.311.21.12" +szOID_ARCHIVED_KEY_ATTR: Final = "1.3.6.1.4.1.311.21.13" +szOID_CRL_SELF_CDP: Final = "1.3.6.1.4.1.311.21.14" +szOID_REQUIRE_CERT_CHAIN_POLICY: Final = "1.3.6.1.4.1.311.21.15" +szOID_ARCHIVED_KEY_CERT_HASH: Final = "1.3.6.1.4.1.311.21.16" +szOID_ISSUED_CERT_HASH: Final = "1.3.6.1.4.1.311.21.17" +szOID_DS_EMAIL_REPLICATION: Final = "1.3.6.1.4.1.311.21.19" +szOID_REQUEST_CLIENT_INFO: Final = "1.3.6.1.4.1.311.21.20" +szOID_ENCRYPTED_KEY_HASH: Final = "1.3.6.1.4.1.311.21.21" +szOID_CERTSRV_CROSSCA_VERSION: Final = "1.3.6.1.4.1.311.21.22" +szOID_NTDS_REPLICATION: Final = "1.3.6.1.4.1.311.25.1" +szOID_SUBJECT_DIR_ATTRS: Final = "2.5.29.9" +szOID_PKIX_KP: Final = "1.3.6.1.5.5.7.3" +szOID_PKIX_KP_SERVER_AUTH: Final = "1.3.6.1.5.5.7.3.1" +szOID_PKIX_KP_CLIENT_AUTH: Final = "1.3.6.1.5.5.7.3.2" +szOID_PKIX_KP_CODE_SIGNING: Final = "1.3.6.1.5.5.7.3.3" +szOID_PKIX_KP_EMAIL_PROTECTION: Final = "1.3.6.1.5.5.7.3.4" +szOID_PKIX_KP_IPSEC_END_SYSTEM: Final = "1.3.6.1.5.5.7.3.5" +szOID_PKIX_KP_IPSEC_TUNNEL: Final = "1.3.6.1.5.5.7.3.6" +szOID_PKIX_KP_IPSEC_USER: Final = "1.3.6.1.5.5.7.3.7" +szOID_PKIX_KP_TIMESTAMP_SIGNING: Final = "1.3.6.1.5.5.7.3.8" +szOID_IPSEC_KP_IKE_INTERMEDIATE: Final = "1.3.6.1.5.5.8.2.2" +szOID_KP_CTL_USAGE_SIGNING: Final = "1.3.6.1.4.1.311.10.3.1" +szOID_KP_TIME_STAMP_SIGNING: Final = "1.3.6.1.4.1.311.10.3.2" +szOID_SERVER_GATED_CRYPTO: Final = "1.3.6.1.4.1.311.10.3.3" +szOID_SGC_NETSCAPE: Final = "2.16.840.1.113730.4.1" +szOID_KP_EFS: Final = "1.3.6.1.4.1.311.10.3.4" +szOID_EFS_RECOVERY: Final = "1.3.6.1.4.1.311.10.3.4.1" +szOID_WHQL_CRYPTO: Final = "1.3.6.1.4.1.311.10.3.5" +szOID_NT5_CRYPTO: Final = "1.3.6.1.4.1.311.10.3.6" +szOID_OEM_WHQL_CRYPTO: Final = "1.3.6.1.4.1.311.10.3.7" +szOID_EMBEDDED_NT_CRYPTO: Final = "1.3.6.1.4.1.311.10.3.8" +szOID_ROOT_LIST_SIGNER: Final = "1.3.6.1.4.1.311.10.3.9" +szOID_KP_QUALIFIED_SUBORDINATION: Final = "1.3.6.1.4.1.311.10.3.10" +szOID_KP_KEY_RECOVERY: Final = "1.3.6.1.4.1.311.10.3.11" +szOID_KP_DOCUMENT_SIGNING: Final = "1.3.6.1.4.1.311.10.3.12" +szOID_KP_LIFETIME_SIGNING: Final = "1.3.6.1.4.1.311.10.3.13" +szOID_KP_MOBILE_DEVICE_SOFTWARE: Final = "1.3.6.1.4.1.311.10.3.14" +szOID_DRM: Final = "1.3.6.1.4.1.311.10.5.1" +szOID_DRM_INDIVIDUALIZATION: Final = "1.3.6.1.4.1.311.10.5.2" +szOID_LICENSES: Final = "1.3.6.1.4.1.311.10.6.1" +szOID_LICENSE_SERVER: Final = "1.3.6.1.4.1.311.10.6.2" +szOID_KP_SMARTCARD_LOGON: Final = "1.3.6.1.4.1.311.20.2.2" +szOID_YESNO_TRUST_ATTR: Final = "1.3.6.1.4.1.311.10.4.1" +szOID_PKIX_POLICY_QUALIFIER_CPS: Final = "1.3.6.1.5.5.7.2.1" +szOID_PKIX_POLICY_QUALIFIER_USERNOTICE: Final = "1.3.6.1.5.5.7.2.2" +szOID_CERT_POLICIES_95_QUALIFIER1: Final = "2.16.840.1.113733.1.7.1.1" +CERT_UNICODE_RDN_ERR_INDEX_MASK: Final = 0x3FF +CERT_UNICODE_RDN_ERR_INDEX_SHIFT: Final = 22 +CERT_UNICODE_ATTR_ERR_INDEX_MASK: Final = 0x003F +CERT_UNICODE_ATTR_ERR_INDEX_SHIFT: Final = 16 +CERT_UNICODE_VALUE_ERR_INDEX_MASK: Final = 0x0000FFFF +CERT_UNICODE_VALUE_ERR_INDEX_SHIFT: Final = 0 +CERT_DIGITAL_SIGNATURE_KEY_USAGE: Final = 0x80 +CERT_NON_REPUDIATION_KEY_USAGE: Final = 0x40 +CERT_KEY_ENCIPHERMENT_KEY_USAGE: Final = 0x20 +CERT_DATA_ENCIPHERMENT_KEY_USAGE: Final = 0x10 +CERT_KEY_AGREEMENT_KEY_USAGE: Final = 0x08 +CERT_KEY_CERT_SIGN_KEY_USAGE: Final = 0x04 +CERT_OFFLINE_CRL_SIGN_KEY_USAGE: Final = 0x02 +CERT_CRL_SIGN_KEY_USAGE: Final = 0x02 +CERT_ENCIPHER_ONLY_KEY_USAGE: Final = 0x01 +CERT_DECIPHER_ONLY_KEY_USAGE: Final = 0x80 +CERT_ALT_NAME_OTHER_NAME: Final = 1 +CERT_ALT_NAME_RFC822_NAME: Final = 2 +CERT_ALT_NAME_DNS_NAME: Final = 3 +CERT_ALT_NAME_X400_ADDRESS: Final = 4 +CERT_ALT_NAME_DIRECTORY_NAME: Final = 5 +CERT_ALT_NAME_EDI_PARTY_NAME: Final = 6 +CERT_ALT_NAME_URL: Final = 7 +CERT_ALT_NAME_IP_ADDRESS: Final = 8 +CERT_ALT_NAME_REGISTERED_ID: Final = 9 +CERT_ALT_NAME_ENTRY_ERR_INDEX_MASK: Final = 0xFF +CERT_ALT_NAME_ENTRY_ERR_INDEX_SHIFT: Final = 16 +CERT_ALT_NAME_VALUE_ERR_INDEX_MASK: Final = 0x0000FFFF +CERT_ALT_NAME_VALUE_ERR_INDEX_SHIFT: Final = 0 +CERT_CA_SUBJECT_FLAG: Final = 0x80 +CERT_END_ENTITY_SUBJECT_FLAG: Final = 0x40 +szOID_PKIX_ACC_DESCR: Final = "1.3.6.1.5.5.7.48" +szOID_PKIX_OCSP: Final = "1.3.6.1.5.5.7.48.1" +szOID_PKIX_CA_ISSUERS: Final = "1.3.6.1.5.5.7.48.2" +CRL_REASON_UNSPECIFIED: Final = 0 +CRL_REASON_KEY_COMPROMISE: Final = 1 +CRL_REASON_CA_COMPROMISE: Final = 2 +CRL_REASON_AFFILIATION_CHANGED: Final = 3 +CRL_REASON_SUPERSEDED: Final = 4 +CRL_REASON_CESSATION_OF_OPERATION: Final = 5 +CRL_REASON_CERTIFICATE_HOLD: Final = 6 +CRL_REASON_REMOVE_FROM_CRL: Final = 8 +CRL_DIST_POINT_NO_NAME: Final = 0 +CRL_DIST_POINT_FULL_NAME: Final = 1 +CRL_DIST_POINT_ISSUER_RDN_NAME: Final = 2 +CRL_REASON_UNUSED_FLAG: Final = 0x80 +CRL_REASON_KEY_COMPROMISE_FLAG: Final = 0x40 +CRL_REASON_CA_COMPROMISE_FLAG: Final = 0x20 +CRL_REASON_AFFILIATION_CHANGED_FLAG: Final = 0x10 +CRL_REASON_SUPERSEDED_FLAG: Final = 0x08 +CRL_REASON_CESSATION_OF_OPERATION_FLAG: Final = 0x04 +CRL_REASON_CERTIFICATE_HOLD_FLAG: Final = 0x02 +CRL_DIST_POINT_ERR_INDEX_MASK: Final = 0x7F +CRL_DIST_POINT_ERR_INDEX_SHIFT: Final = 24 +CRL_DIST_POINT_ERR_CRL_ISSUER_BIT: Final = -2147483648 +CROSS_CERT_DIST_POINT_ERR_INDEX_MASK: Final = 0xFF +CROSS_CERT_DIST_POINT_ERR_INDEX_SHIFT: Final = 24 +CERT_EXCLUDED_SUBTREE_BIT: Final = -2147483648 +SORTED_CTL_EXT_FLAGS_OFFSET: Final = 0 +SORTED_CTL_EXT_COUNT_OFFSET: Final = 4 +SORTED_CTL_EXT_MAX_COLLISION_OFFSET: Final = 8 +SORTED_CTL_EXT_HASH_BUCKET_OFFSET: Final = 12 +SORTED_CTL_EXT_HASHED_SUBJECT_IDENTIFIER_FLAG: Final = 0x1 +CERT_DSS_R_LEN: Final = 20 +CERT_DSS_S_LEN: Final = 20 +CERT_DSS_SIGNATURE_LEN: Final = 40 +CERT_MAX_ASN_ENCODED_DSS_SIGNATURE_LEN: Final = 48 +CRYPT_X942_COUNTER_BYTE_LENGTH: Final = 4 +CRYPT_X942_KEY_LENGTH_BYTE_LENGTH: Final = 4 +CRYPT_X942_PUB_INFO_BYTE_LENGTH: Final = 64.0 +CRYPT_RC2_40BIT_VERSION: Final = 160 +CRYPT_RC2_56BIT_VERSION: Final = 52 +CRYPT_RC2_64BIT_VERSION: Final = 120 +CRYPT_RC2_128BIT_VERSION: Final = 58 +szOID_VERISIGN_PRIVATE_6_9: Final = "2.16.840.1.113733.1.6.9" +szOID_VERISIGN_ONSITE_JURISDICTION_HASH: Final = "2.16.840.1.113733.1.6.11" +szOID_VERISIGN_BITSTRING_6_13: Final = "2.16.840.1.113733.1.6.13" +szOID_VERISIGN_ISS_STRONG_CRYPTO: Final = "2.16.840.1.113733.1.8.1" +szOID_NETSCAPE: Final = "2.16.840.1.113730" +szOID_NETSCAPE_CERT_EXTENSION: Final = "2.16.840.1.113730.1" +szOID_NETSCAPE_CERT_TYPE: Final = "2.16.840.1.113730.1.1" +szOID_NETSCAPE_BASE_URL: Final = "2.16.840.1.113730.1.2" +szOID_NETSCAPE_REVOCATION_URL: Final = "2.16.840.1.113730.1.3" +szOID_NETSCAPE_CA_REVOCATION_URL: Final = "2.16.840.1.113730.1.4" +szOID_NETSCAPE_CERT_RENEWAL_URL: Final = "2.16.840.1.113730.1.7" +szOID_NETSCAPE_CA_POLICY_URL: Final = "2.16.840.1.113730.1.8" +szOID_NETSCAPE_SSL_SERVER_NAME: Final = "2.16.840.1.113730.1.12" +szOID_NETSCAPE_COMMENT: Final = "2.16.840.1.113730.1.13" +szOID_NETSCAPE_DATA_TYPE: Final = "2.16.840.1.113730.2" +szOID_NETSCAPE_CERT_SEQUENCE: Final = "2.16.840.1.113730.2.5" +NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE: Final = 0x80 +NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE: Final = 0x40 +NETSCAPE_SMIME_CERT_TYPE: Final = 0x20 +NETSCAPE_SIGN_CERT_TYPE: Final = 0x10 +NETSCAPE_SSL_CA_CERT_TYPE: Final = 0x04 +NETSCAPE_SMIME_CA_CERT_TYPE: Final = 0x02 +NETSCAPE_SIGN_CA_CERT_TYPE: Final = 0x01 +szOID_CT_PKI_DATA: Final = "1.3.6.1.5.5.7.12.2" +szOID_CT_PKI_RESPONSE: Final = "1.3.6.1.5.5.7.12.3" +szOID_PKIX_NO_SIGNATURE: Final = "1.3.6.1.5.5.7.6.2" +szOID_CMC: Final = "1.3.6.1.5.5.7.7" +szOID_CMC_STATUS_INFO: Final = "1.3.6.1.5.5.7.7.1" +szOID_CMC_IDENTIFICATION: Final = "1.3.6.1.5.5.7.7.2" +szOID_CMC_IDENTITY_PROOF: Final = "1.3.6.1.5.5.7.7.3" +szOID_CMC_DATA_RETURN: Final = "1.3.6.1.5.5.7.7.4" +szOID_CMC_TRANSACTION_ID: Final = "1.3.6.1.5.5.7.7.5" +szOID_CMC_SENDER_NONCE: Final = "1.3.6.1.5.5.7.7.6" +szOID_CMC_RECIPIENT_NONCE: Final = "1.3.6.1.5.5.7.7.7" +szOID_CMC_ADD_EXTENSIONS: Final = "1.3.6.1.5.5.7.7.8" +szOID_CMC_ENCRYPTED_POP: Final = "1.3.6.1.5.5.7.7.9" +szOID_CMC_DECRYPTED_POP: Final = "1.3.6.1.5.5.7.7.10" +szOID_CMC_LRA_POP_WITNESS: Final = "1.3.6.1.5.5.7.7.11" +szOID_CMC_GET_CERT: Final = "1.3.6.1.5.5.7.7.15" +szOID_CMC_GET_CRL: Final = "1.3.6.1.5.5.7.7.16" +szOID_CMC_REVOKE_REQUEST: Final = "1.3.6.1.5.5.7.7.17" +szOID_CMC_REG_INFO: Final = "1.3.6.1.5.5.7.7.18" +szOID_CMC_RESPONSE_INFO: Final = "1.3.6.1.5.5.7.7.19" +szOID_CMC_QUERY_PENDING: Final = "1.3.6.1.5.5.7.7.21" +szOID_CMC_ID_POP_LINK_RANDOM: Final = "1.3.6.1.5.5.7.7.22" +szOID_CMC_ID_POP_LINK_WITNESS: Final = "1.3.6.1.5.5.7.7.23" +szOID_CMC_ID_CONFIRM_CERT_ACCEPTANCE: Final = "1.3.6.1.5.5.7.7.24" +szOID_CMC_ADD_ATTRIBUTES: Final = "1.3.6.1.4.1.311.10.10.1" +CMC_TAGGED_CERT_REQUEST_CHOICE: Final = 1 +CMC_OTHER_INFO_NO_CHOICE: Final = 0 +CMC_OTHER_INFO_FAIL_CHOICE: Final = 1 +CMC_OTHER_INFO_PEND_CHOICE: Final = 2 +CMC_STATUS_SUCCESS: Final = 0 +CMC_STATUS_FAILED: Final = 2 +CMC_STATUS_PENDING: Final = 3 +CMC_STATUS_NO_SUPPORT: Final = 4 +CMC_STATUS_CONFIRM_REQUIRED: Final = 5 +CMC_FAIL_BAD_ALG: Final = 0 +CMC_FAIL_BAD_MESSAGE_CHECK: Final = 1 +CMC_FAIL_BAD_REQUEST: Final = 2 +CMC_FAIL_BAD_TIME: Final = 3 +CMC_FAIL_BAD_CERT_ID: Final = 4 +CMC_FAIL_UNSUPORTED_EXT: Final = 5 +CMC_FAIL_MUST_ARCHIVE_KEYS: Final = 6 +CMC_FAIL_BAD_IDENTITY: Final = 7 +CMC_FAIL_POP_REQUIRED: Final = 8 +CMC_FAIL_POP_FAILED: Final = 9 +CMC_FAIL_NO_KEY_REUSE: Final = 10 +CMC_FAIL_INTERNAL_CA_ERROR: Final = 11 +CMC_FAIL_TRY_LATER: Final = 12 +CRYPT_OID_ENCODE_OBJECT_FUNC: Final = "CryptDllEncodeObject" +CRYPT_OID_DECODE_OBJECT_FUNC: Final = "CryptDllDecodeObject" +CRYPT_OID_ENCODE_OBJECT_EX_FUNC: Final = "CryptDllEncodeObjectEx" +CRYPT_OID_DECODE_OBJECT_EX_FUNC: Final = "CryptDllDecodeObjectEx" +CRYPT_OID_CREATE_COM_OBJECT_FUNC: Final = "CryptDllCreateCOMObject" +CRYPT_OID_VERIFY_REVOCATION_FUNC: Final = "CertDllVerifyRevocation" +CRYPT_OID_VERIFY_CTL_USAGE_FUNC: Final = "CertDllVerifyCTLUsage" +CRYPT_OID_FORMAT_OBJECT_FUNC: Final = "CryptDllFormatObject" +CRYPT_OID_FIND_OID_INFO_FUNC: Final = "CryptDllFindOIDInfo" +CRYPT_OID_FIND_LOCALIZED_NAME_FUNC: Final = "CryptDllFindLocalizedName" +CRYPT_OID_REGPATH: Final = "Software\\Microsoft\\Cryptography\\OID" +CRYPT_OID_REG_ENCODING_TYPE_PREFIX: Final = "EncodingType " +CRYPT_OID_REG_DLL_VALUE_NAME: Final = "Dll" +CRYPT_OID_REG_FUNC_NAME_VALUE_NAME: Final = "FuncName" +CRYPT_OID_REG_FUNC_NAME_VALUE_NAME_A: Final = "FuncName" +CRYPT_OID_REG_FLAGS_VALUE_NAME: Final = "CryptFlags" +CRYPT_DEFAULT_OID: Final = "DEFAULT" +CRYPT_INSTALL_OID_FUNC_BEFORE_FLAG: Final = 1 +CRYPT_GET_INSTALLED_OID_FUNC_FLAG: Final = 0x1 +CRYPT_REGISTER_FIRST_INDEX: Final = 0 +CRYPT_REGISTER_LAST_INDEX: Final = -1 +CRYPT_MATCH_ANY_ENCODING_TYPE: Final = -1 +CRYPT_HASH_ALG_OID_GROUP_ID: Final = 1 +CRYPT_ENCRYPT_ALG_OID_GROUP_ID: Final = 2 +CRYPT_PUBKEY_ALG_OID_GROUP_ID: Final = 3 +CRYPT_SIGN_ALG_OID_GROUP_ID: Final = 4 +CRYPT_RDN_ATTR_OID_GROUP_ID: Final = 5 +CRYPT_EXT_OR_ATTR_OID_GROUP_ID: Final = 6 +CRYPT_ENHKEY_USAGE_OID_GROUP_ID: Final = 7 +CRYPT_POLICY_OID_GROUP_ID: Final = 8 +CRYPT_TEMPLATE_OID_GROUP_ID: Final = 9 +CRYPT_LAST_OID_GROUP_ID: Final = 9 +CRYPT_FIRST_ALG_OID_GROUP_ID: Final = CRYPT_HASH_ALG_OID_GROUP_ID +CRYPT_LAST_ALG_OID_GROUP_ID: Final = CRYPT_SIGN_ALG_OID_GROUP_ID +CRYPT_OID_INHIBIT_SIGNATURE_FORMAT_FLAG: Final = 0x1 +CRYPT_OID_USE_PUBKEY_PARA_FOR_PKCS7_FLAG: Final = 0x2 +CRYPT_OID_NO_NULL_ALGORITHM_PARA_FLAG: Final = 0x4 +CRYPT_OID_INFO_OID_KEY: Final = 1 +CRYPT_OID_INFO_NAME_KEY: Final = 2 +CRYPT_OID_INFO_ALGID_KEY: Final = 3 +CRYPT_OID_INFO_SIGN_KEY: Final = 4 +CRYPT_INSTALL_OID_INFO_BEFORE_FLAG: Final = 1 +CRYPT_LOCALIZED_NAME_ENCODING_TYPE: Final = 0 +CRYPT_LOCALIZED_NAME_OID: Final = "LocalizedNames" +szOID_PKCS_7_DATA: Final = "1.2.840.113549.1.7.1" +szOID_PKCS_7_SIGNED: Final = "1.2.840.113549.1.7.2" +szOID_PKCS_7_ENVELOPED: Final = "1.2.840.113549.1.7.3" +szOID_PKCS_7_SIGNEDANDENVELOPED: Final = "1.2.840.113549.1.7.4" +szOID_PKCS_7_DIGESTED: Final = "1.2.840.113549.1.7.5" +szOID_PKCS_7_ENCRYPTED: Final = "1.2.840.113549.1.7.6" +szOID_PKCS_9_CONTENT_TYPE: Final = "1.2.840.113549.1.9.3" +szOID_PKCS_9_MESSAGE_DIGEST: Final = "1.2.840.113549.1.9.4" +CMSG_DATA: Final = 1 +CMSG_SIGNED: Final = 2 +CMSG_ENVELOPED: Final = 3 +CMSG_SIGNED_AND_ENVELOPED: Final = 4 +CMSG_HASHED: Final = 5 +CMSG_ENCRYPTED: Final = 6 +CMSG_ALL_FLAGS: Final = -1 +CMSG_DATA_FLAG: Final = 2 +CMSG_SIGNED_FLAG: Final = 4 +CMSG_ENVELOPED_FLAG: Final = 8 +CMSG_SIGNED_AND_ENVELOPED_FLAG: Final = 16 +CMSG_HASHED_FLAG: Final = 32 +CMSG_ENCRYPTED_FLAG: Final = 64 +CERT_ID_ISSUER_SERIAL_NUMBER: Final = 1 +CERT_ID_KEY_IDENTIFIER: Final = 2 +CERT_ID_SHA1_HASH: Final = 3 +CMSG_KEY_AGREE_EPHEMERAL_KEY_CHOICE: Final = 1 +CMSG_KEY_AGREE_STATIC_KEY_CHOICE: Final = 2 +CMSG_MAIL_LIST_HANDLE_KEY_CHOICE: Final = 1 +CMSG_KEY_TRANS_RECIPIENT: Final = 1 +CMSG_KEY_AGREE_RECIPIENT: Final = 2 +CMSG_MAIL_LIST_RECIPIENT: Final = 3 +CMSG_SP3_COMPATIBLE_ENCRYPT_FLAG: Final = -2147483648 +CMSG_RC4_NO_SALT_FLAG: Final = 0x40000000 +CMSG_INDEFINITE_LENGTH: Final = -1 +CMSG_BARE_CONTENT_FLAG: Final = 0x00000001 +CMSG_LENGTH_ONLY_FLAG: Final = 0x00000002 +CMSG_DETACHED_FLAG: Final = 0x00000004 +CMSG_AUTHENTICATED_ATTRIBUTES_FLAG: Final = 0x00000008 +CMSG_CONTENTS_OCTETS_FLAG: Final = 0x00000010 +CMSG_MAX_LENGTH_FLAG: Final = 0x00000020 +CMSG_CMS_ENCAPSULATED_CONTENT_FLAG: Final = 0x00000040 +CMSG_CRYPT_RELEASE_CONTEXT_FLAG: Final = 0x00008000 +CMSG_TYPE_PARAM: Final = 1 +CMSG_CONTENT_PARAM: Final = 2 +CMSG_BARE_CONTENT_PARAM: Final = 3 +CMSG_INNER_CONTENT_TYPE_PARAM: Final = 4 +CMSG_SIGNER_COUNT_PARAM: Final = 5 +CMSG_SIGNER_INFO_PARAM: Final = 6 +CMSG_SIGNER_CERT_INFO_PARAM: Final = 7 +CMSG_SIGNER_HASH_ALGORITHM_PARAM: Final = 8 +CMSG_SIGNER_AUTH_ATTR_PARAM: Final = 9 +CMSG_SIGNER_UNAUTH_ATTR_PARAM: Final = 10 +CMSG_CERT_COUNT_PARAM: Final = 11 +CMSG_CERT_PARAM: Final = 12 +CMSG_CRL_COUNT_PARAM: Final = 13 +CMSG_CRL_PARAM: Final = 14 +CMSG_ENVELOPE_ALGORITHM_PARAM: Final = 15 +CMSG_RECIPIENT_COUNT_PARAM: Final = 17 +CMSG_RECIPIENT_INDEX_PARAM: Final = 18 +CMSG_RECIPIENT_INFO_PARAM: Final = 19 +CMSG_HASH_ALGORITHM_PARAM: Final = 20 +CMSG_HASH_DATA_PARAM: Final = 21 +CMSG_COMPUTED_HASH_PARAM: Final = 22 +CMSG_ENCRYPT_PARAM: Final = 26 +CMSG_ENCRYPTED_DIGEST: Final = 27 +CMSG_ENCODED_SIGNER: Final = 28 +CMSG_ENCODED_MESSAGE: Final = 29 +CMSG_VERSION_PARAM: Final = 30 +CMSG_ATTR_CERT_COUNT_PARAM: Final = 31 +CMSG_ATTR_CERT_PARAM: Final = 32 +CMSG_CMS_RECIPIENT_COUNT_PARAM: Final = 33 +CMSG_CMS_RECIPIENT_INDEX_PARAM: Final = 34 +CMSG_CMS_RECIPIENT_ENCRYPTED_KEY_INDEX_PARAM: Final = 35 +CMSG_CMS_RECIPIENT_INFO_PARAM: Final = 36 +CMSG_UNPROTECTED_ATTR_PARAM: Final = 37 +CMSG_SIGNER_CERT_ID_PARAM: Final = 38 +CMSG_CMS_SIGNER_INFO_PARAM: Final = 39 +CMSG_SIGNED_DATA_V1: Final = 1 +CMSG_SIGNED_DATA_V3: Final = 3 +CMSG_SIGNED_DATA_PKCS_1_5_VERSION: Final = CMSG_SIGNED_DATA_V1 +CMSG_SIGNED_DATA_CMS_VERSION: Final = CMSG_SIGNED_DATA_V3 +CMSG_SIGNER_INFO_V1: Final = 1 +CMSG_SIGNER_INFO_V3: Final = 3 +CMSG_SIGNER_INFO_PKCS_1_5_VERSION: Final = CMSG_SIGNER_INFO_V1 +CMSG_SIGNER_INFO_CMS_VERSION: Final = CMSG_SIGNER_INFO_V3 +CMSG_HASHED_DATA_V0: Final = 0 +CMSG_HASHED_DATA_V2: Final = 2 +CMSG_HASHED_DATA_PKCS_1_5_VERSION: Final = CMSG_HASHED_DATA_V0 +CMSG_HASHED_DATA_CMS_VERSION: Final = CMSG_HASHED_DATA_V2 +CMSG_ENVELOPED_DATA_V0: Final = 0 +CMSG_ENVELOPED_DATA_V2: Final = 2 +CMSG_ENVELOPED_DATA_PKCS_1_5_VERSION: Final = CMSG_ENVELOPED_DATA_V0 +CMSG_ENVELOPED_DATA_CMS_VERSION: Final = CMSG_ENVELOPED_DATA_V2 +CMSG_KEY_AGREE_ORIGINATOR_CERT: Final = 1 +CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY: Final = 2 +CMSG_ENVELOPED_RECIPIENT_V0: Final = 0 +CMSG_ENVELOPED_RECIPIENT_V2: Final = 2 +CMSG_ENVELOPED_RECIPIENT_V3: Final = 3 +CMSG_ENVELOPED_RECIPIENT_V4: Final = 4 +CMSG_KEY_TRANS_PKCS_1_5_VERSION: Final = CMSG_ENVELOPED_RECIPIENT_V0 +CMSG_KEY_TRANS_CMS_VERSION: Final = CMSG_ENVELOPED_RECIPIENT_V2 +CMSG_KEY_AGREE_VERSION: Final = CMSG_ENVELOPED_RECIPIENT_V3 +CMSG_MAIL_LIST_VERSION: Final = CMSG_ENVELOPED_RECIPIENT_V4 +CMSG_CTRL_VERIFY_SIGNATURE: Final = 1 +CMSG_CTRL_DECRYPT: Final = 2 +CMSG_CTRL_VERIFY_HASH: Final = 5 +CMSG_CTRL_ADD_SIGNER: Final = 6 +CMSG_CTRL_DEL_SIGNER: Final = 7 +CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR: Final = 8 +CMSG_CTRL_DEL_SIGNER_UNAUTH_ATTR: Final = 9 +CMSG_CTRL_ADD_CERT: Final = 10 +CMSG_CTRL_DEL_CERT: Final = 11 +CMSG_CTRL_ADD_CRL: Final = 12 +CMSG_CTRL_DEL_CRL: Final = 13 +CMSG_CTRL_ADD_ATTR_CERT: Final = 14 +CMSG_CTRL_DEL_ATTR_CERT: Final = 15 +CMSG_CTRL_KEY_TRANS_DECRYPT: Final = 16 +CMSG_CTRL_KEY_AGREE_DECRYPT: Final = 17 +CMSG_CTRL_MAIL_LIST_DECRYPT: Final = 18 +CMSG_CTRL_VERIFY_SIGNATURE_EX: Final = 19 +CMSG_CTRL_ADD_CMS_SIGNER_INFO: Final = 20 +CMSG_VERIFY_SIGNER_PUBKEY: Final = 1 +CMSG_VERIFY_SIGNER_CERT: Final = 2 +CMSG_VERIFY_SIGNER_CHAIN: Final = 3 +CMSG_VERIFY_SIGNER_NULL: Final = 4 +CMSG_OID_GEN_ENCRYPT_KEY_FUNC: Final = "CryptMsgDllGenEncryptKey" +CMSG_OID_EXPORT_ENCRYPT_KEY_FUNC: Final = "CryptMsgDllExportEncryptKey" +CMSG_OID_IMPORT_ENCRYPT_KEY_FUNC: Final = "CryptMsgDllImportEncryptKey" +CMSG_CONTENT_ENCRYPT_PAD_ENCODED_LEN_FLAG: Final = 0x00000001 +CMSG_DEFAULT_INSTALLABLE_FUNC_OID: Final = 1 +CMSG_CONTENT_ENCRYPT_FREE_PARA_FLAG: Final = 0x00000001 +CMSG_CONTENT_ENCRYPT_RELEASE_CONTEXT_FLAG: Final = 0x00008000 +CMSG_OID_GEN_CONTENT_ENCRYPT_KEY_FUNC: Final = "CryptMsgDllGenContentEncryptKey" +CMSG_KEY_TRANS_ENCRYPT_FREE_PARA_FLAG: Final = 0x00000001 +CMSG_OID_EXPORT_KEY_TRANS_FUNC: Final = "CryptMsgDllExportKeyTrans" +CMSG_KEY_AGREE_ENCRYPT_FREE_PARA_FLAG: Final = 0x00000001 +CMSG_KEY_AGREE_ENCRYPT_FREE_MATERIAL_FLAG: Final = 0x00000002 +CMSG_KEY_AGREE_ENCRYPT_FREE_PUBKEY_ALG_FLAG: Final = 0x00000004 +CMSG_KEY_AGREE_ENCRYPT_FREE_PUBKEY_PARA_FLAG: Final = 0x00000008 +CMSG_KEY_AGREE_ENCRYPT_FREE_PUBKEY_BITS_FLAG: Final = 0x00000010 +CMSG_OID_EXPORT_KEY_AGREE_FUNC: Final = "CryptMsgDllExportKeyAgree" +CMSG_MAIL_LIST_ENCRYPT_FREE_PARA_FLAG: Final = 0x00000001 +CMSG_OID_EXPORT_MAIL_LIST_FUNC: Final = "CryptMsgDllExportMailList" +CMSG_OID_IMPORT_KEY_TRANS_FUNC: Final = "CryptMsgDllImportKeyTrans" +CMSG_OID_IMPORT_KEY_AGREE_FUNC: Final = "CryptMsgDllImportKeyAgree" +CMSG_OID_IMPORT_MAIL_LIST_FUNC: Final = "CryptMsgDllImportMailList" +CERT_KEY_PROV_HANDLE_PROP_ID: Final = 1 +CERT_KEY_PROV_INFO_PROP_ID: Final = 2 +CERT_SHA1_HASH_PROP_ID: Final = 3 +CERT_MD5_HASH_PROP_ID: Final = 4 +CERT_HASH_PROP_ID: Final = CERT_SHA1_HASH_PROP_ID +CERT_KEY_CONTEXT_PROP_ID: Final = 5 +CERT_KEY_SPEC_PROP_ID: Final = 6 +CERT_IE30_RESERVED_PROP_ID: Final = 7 +CERT_PUBKEY_HASH_RESERVED_PROP_ID: Final = 8 +CERT_ENHKEY_USAGE_PROP_ID: Final = 9 +CERT_CTL_USAGE_PROP_ID: Final = CERT_ENHKEY_USAGE_PROP_ID +CERT_NEXT_UPDATE_LOCATION_PROP_ID: Final = 10 +CERT_FRIENDLY_NAME_PROP_ID: Final = 11 +CERT_PVK_FILE_PROP_ID: Final = 12 +CERT_DESCRIPTION_PROP_ID: Final = 13 +CERT_ACCESS_STATE_PROP_ID: Final = 14 +CERT_SIGNATURE_HASH_PROP_ID: Final = 15 +CERT_SMART_CARD_DATA_PROP_ID: Final = 16 +CERT_EFS_PROP_ID: Final = 17 +CERT_FORTEZZA_DATA_PROP_ID: Final = 18 +CERT_ARCHIVED_PROP_ID: Final = 19 +CERT_KEY_IDENTIFIER_PROP_ID: Final = 20 +CERT_AUTO_ENROLL_PROP_ID: Final = 21 +CERT_PUBKEY_ALG_PARA_PROP_ID: Final = 22 +CERT_CROSS_CERT_DIST_POINTS_PROP_ID: Final = 23 +CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID: Final = 24 +CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID: Final = 25 +CERT_ENROLLMENT_PROP_ID: Final = 26 +CERT_DATE_STAMP_PROP_ID: Final = 27 +CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: Final = 28 +CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: Final = 29 +CERT_EXTENDED_ERROR_INFO_PROP_ID: Final = 30 +CERT_RENEWAL_PROP_ID: Final = 64 +CERT_ARCHIVED_KEY_HASH_PROP_ID: Final = 65 +CERT_AUTO_ENROLL_RETRY_PROP_ID: Final = 66 +CERT_AIA_URL_RETRIEVED_PROP_ID: Final = 67 +CERT_AUTHORITY_INFO_ACCESS_PROP_ID: Final = 68 +CERT_BACKED_UP_PROP_ID: Final = 69 +CERT_OCSP_RESPONSE_PROP_ID: Final = 70 +CERT_REQUEST_ORIGINATOR_PROP_ID: Final = 71 +CERT_SOURCE_LOCATION_PROP_ID: Final = 72 +CERT_SOURCE_URL_PROP_ID: Final = 73 +CERT_NEW_KEY_PROP_ID: Final = 74 +CERT_OCSP_CACHE_PREFIX_PROP_ID: Final = 75 +CERT_SMART_CARD_ROOT_INFO_PROP_ID: Final = 76 +CERT_NO_AUTO_EXPIRE_CHECK_PROP_ID: Final = 77 +CERT_NCRYPT_KEY_HANDLE_PROP_ID: Final = 78 +CERT_HCRYPTPROV_OR_NCRYPT_KEY_HANDLE_PROP_ID: Final = 79 +CERT_SUBJECT_INFO_ACCESS_PROP_ID: Final = 80 +CERT_CA_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: Final = 81 +CERT_CA_DISABLE_CRL_PROP_ID: Final = 82 +CERT_ROOT_PROGRAM_CERT_POLICIES_PROP_ID: Final = 83 +CERT_ROOT_PROGRAM_NAME_CONSTRAINTS_PROP_ID: Final = 84 +CERT_SUBJECT_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: Final = 85 +CERT_SUBJECT_DISABLE_CRL_PROP_ID: Final = 86 +CERT_CEP_PROP_ID: Final = 87 +CERT_SIGN_HASH_CNG_ALG_PROP_ID: Final = 89 +CERT_SCARD_PIN_ID_PROP_ID: Final = 90 +CERT_SCARD_PIN_INFO_PROP_ID: Final = 91 +CERT_FIRST_RESERVED_PROP_ID: Final = 92 +CERT_LAST_RESERVED_PROP_ID: Final = 0x00007FFF +CERT_FIRST_USER_PROP_ID: Final = 0x00008000 +CERT_LAST_USER_PROP_ID: Final = 0x0000FFFF +szOID_CERT_PROP_ID_PREFIX: Final = "1.3.6.1.4.1.311.10.11." +szOID_CERT_KEY_IDENTIFIER_PROP_ID: Final = "1.3.6.1.4.1.311.10.11.20" +szOID_CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: Final = "1.3.6.1.4.1.311.10.11.28" +szOID_CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: Final = "1.3.6.1.4.1.311.10.11.29" +CERT_ACCESS_STATE_WRITE_PERSIST_FLAG: Final = 0x1 +CERT_ACCESS_STATE_SYSTEM_STORE_FLAG: Final = 0x2 +CERT_ACCESS_STATE_LM_SYSTEM_STORE_FLAG: Final = 0x4 +CERT_SET_KEY_PROV_HANDLE_PROP_ID: Final = 0x00000001 +CERT_SET_KEY_CONTEXT_PROP_ID: Final = 0x00000001 +sz_CERT_STORE_PROV_MEMORY: Final = "Memory" +sz_CERT_STORE_PROV_FILENAME_W: Final = "File" +sz_CERT_STORE_PROV_FILENAME: Final = sz_CERT_STORE_PROV_FILENAME_W +sz_CERT_STORE_PROV_SYSTEM_W: Final = "System" +sz_CERT_STORE_PROV_SYSTEM: Final = sz_CERT_STORE_PROV_SYSTEM_W +sz_CERT_STORE_PROV_PKCS7: Final = "PKCS7" +sz_CERT_STORE_PROV_SERIALIZED: Final = "Serialized" +sz_CERT_STORE_PROV_COLLECTION: Final = "Collection" +sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W: Final = "SystemRegistry" +sz_CERT_STORE_PROV_SYSTEM_REGISTRY: Final = sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W +sz_CERT_STORE_PROV_PHYSICAL_W: Final = "Physical" +sz_CERT_STORE_PROV_PHYSICAL: Final = sz_CERT_STORE_PROV_PHYSICAL_W +sz_CERT_STORE_PROV_SMART_CARD_W: Final = "SmartCard" +sz_CERT_STORE_PROV_SMART_CARD: Final = sz_CERT_STORE_PROV_SMART_CARD_W +sz_CERT_STORE_PROV_LDAP_W: Final = "Ldap" +sz_CERT_STORE_PROV_LDAP: Final = sz_CERT_STORE_PROV_LDAP_W +CERT_STORE_SIGNATURE_FLAG: Final = 0x00000001 +CERT_STORE_TIME_VALIDITY_FLAG: Final = 0x00000002 +CERT_STORE_REVOCATION_FLAG: Final = 0x00000004 +CERT_STORE_NO_CRL_FLAG: Final = 0x00010000 +CERT_STORE_NO_ISSUER_FLAG: Final = 0x00020000 +CERT_STORE_BASE_CRL_FLAG: Final = 0x00000100 +CERT_STORE_DELTA_CRL_FLAG: Final = 0x00000200 +CERT_STORE_NO_CRYPT_RELEASE_FLAG: Final = 0x00000001 +CERT_STORE_SET_LOCALIZED_NAME_FLAG: Final = 0x00000002 +CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG: Final = 0x00000004 +CERT_STORE_DELETE_FLAG: Final = 0x00000010 +CERT_STORE_UNSAFE_PHYSICAL_FLAG: Final = 0x00000020 +CERT_STORE_SHARE_STORE_FLAG: Final = 0x00000040 +CERT_STORE_SHARE_CONTEXT_FLAG: Final = 0x00000080 +CERT_STORE_MANIFOLD_FLAG: Final = 0x00000100 +CERT_STORE_ENUM_ARCHIVED_FLAG: Final = 0x00000200 +CERT_STORE_UPDATE_KEYID_FLAG: Final = 0x00000400 +CERT_STORE_BACKUP_RESTORE_FLAG: Final = 0x00000800 +CERT_STORE_READONLY_FLAG: Final = 0x00008000 +CERT_STORE_OPEN_EXISTING_FLAG: Final = 0x00004000 +CERT_STORE_CREATE_NEW_FLAG: Final = 0x00002000 +CERT_STORE_MAXIMUM_ALLOWED_FLAG: Final = 0x00001000 +CERT_SYSTEM_STORE_MASK: Final = -65536 +CERT_SYSTEM_STORE_RELOCATE_FLAG: Final = -2147483648 +CERT_SYSTEM_STORE_UNPROTECTED_FLAG: Final = 0x40000000 +CERT_SYSTEM_STORE_LOCATION_MASK: Final = 0x00FF0000 +CERT_SYSTEM_STORE_LOCATION_SHIFT: Final = 16 +CERT_SYSTEM_STORE_CURRENT_USER_ID: Final = 1 +CERT_SYSTEM_STORE_LOCAL_MACHINE_ID: Final = 2 +CERT_SYSTEM_STORE_CURRENT_SERVICE_ID: Final = 4 +CERT_SYSTEM_STORE_SERVICES_ID: Final = 5 +CERT_SYSTEM_STORE_USERS_ID: Final = 6 +CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID: Final = 7 +CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID: Final = 8 +CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID: Final = 9 +CERT_SYSTEM_STORE_CURRENT_USER: Final = 65536 +CERT_SYSTEM_STORE_LOCAL_MACHINE: Final = 131072 +CERT_SYSTEM_STORE_CURRENT_SERVICE: Final = 262144 +CERT_SYSTEM_STORE_SERVICES: Final = 327680 +CERT_SYSTEM_STORE_USERS: Final = 393216 +CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY: Final = 458752 +CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY: Final = 524288 +CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE: Final = 589824 +CERT_PROT_ROOT_DISABLE_CURRENT_USER_FLAG: Final = 0x1 +CERT_PROT_ROOT_INHIBIT_ADD_AT_INIT_FLAG: Final = 0x2 +CERT_PROT_ROOT_INHIBIT_PURGE_LM_FLAG: Final = 0x4 +CERT_PROT_ROOT_DISABLE_LM_AUTH_FLAG: Final = 0x8 +CERT_PROT_ROOT_ONLY_LM_GPT_FLAG: Final = 0x8 +CERT_PROT_ROOT_DISABLE_NT_AUTH_REQUIRED_FLAG: Final = 0x10 +CERT_PROT_ROOT_DISABLE_NOT_DEFINED_NAME_CONSTRAINT_FLAG: Final = 0x20 +CERT_TRUST_PUB_ALLOW_TRUST_MASK: Final = 0x00000003 +CERT_TRUST_PUB_ALLOW_END_USER_TRUST: Final = 0x00000000 +CERT_TRUST_PUB_ALLOW_MACHINE_ADMIN_TRUST: Final = 0x00000001 +CERT_TRUST_PUB_ALLOW_ENTERPRISE_ADMIN_TRUST: Final = 0x00000002 +CERT_TRUST_PUB_CHECK_PUBLISHER_REV_FLAG: Final = 0x00000100 +CERT_TRUST_PUB_CHECK_TIMESTAMP_REV_FLAG: Final = 0x00000200 +CERT_AUTH_ROOT_AUTO_UPDATE_DISABLE_UNTRUSTED_ROOT_LOGGING_FLAG: Final = 0x1 +CERT_AUTH_ROOT_AUTO_UPDATE_DISABLE_PARTIAL_CHAIN_LOGGING_FLAG: Final = 0x2 +CERT_AUTH_ROOT_AUTO_UPDATE_ROOT_DIR_URL_VALUE_NAME: Final = "RootDirUrl" +CERT_AUTH_ROOT_AUTO_UPDATE_SYNC_DELTA_TIME_VALUE_NAME: Final = "SyncDeltaTime" +CERT_AUTH_ROOT_AUTO_UPDATE_FLAGS_VALUE_NAME: Final = "Flags" +CERT_AUTH_ROOT_CTL_FILENAME: Final = "authroot.stl" +CERT_AUTH_ROOT_CTL_FILENAME_A: Final = "authroot.stl" +CERT_AUTH_ROOT_CAB_FILENAME: Final = "authrootstl.cab" +CERT_AUTH_ROOT_SEQ_FILENAME: Final = "authrootseq.txt" +CERT_AUTH_ROOT_CERT_EXT: Final = ".crt" +CERT_GROUP_POLICY_SYSTEM_STORE_REGPATH: Final = r"Software\Policies\Microsoft\SystemCertificates" +CERT_EFSBLOB_REGPATH: Final = r"Software\Policies\Microsoft\SystemCertificates\EFS" +CERT_EFSBLOB_VALUE_NAME: Final = "EFSBlob" +CERT_PROT_ROOT_FLAGS_REGPATH: Final[str] +CERT_PROT_ROOT_FLAGS_VALUE_NAME: Final = "Flags" +CERT_TRUST_PUB_SAFER_GROUP_POLICY_REGPATH: Final[str] +CERT_LOCAL_MACHINE_SYSTEM_STORE_REGPATH: Final = r"Software\Microsoft\SystemCertificates" +CERT_TRUST_PUB_SAFER_LOCAL_MACHINE_REGPATH: Final[str] +CERT_TRUST_PUB_AUTHENTICODE_FLAGS_VALUE_NAME: Final = "AuthenticodeFlags" +CERT_OCM_SUBCOMPONENTS_LOCAL_MACHINE_REGPATH: Final[str] +CERT_OCM_SUBCOMPONENTS_ROOT_AUTO_UPDATE_VALUE_NAME: Final = r"RootAutoUpdate" +CERT_DISABLE_ROOT_AUTO_UPDATE_REGPATH: Final[str] +CERT_DISABLE_ROOT_AUTO_UPDATE_VALUE_NAME: Final = "DisableRootAutoUpdate" +CERT_AUTH_ROOT_AUTO_UPDATE_LOCAL_MACHINE_REGPATH: Final[str] +CERT_REGISTRY_STORE_REMOTE_FLAG: Final = 0x10000 +CERT_REGISTRY_STORE_SERIALIZED_FLAG: Final = 0x20000 +CERT_REGISTRY_STORE_CLIENT_GPT_FLAG: Final = -2147483648 +CERT_REGISTRY_STORE_LM_GPT_FLAG: Final = 0x01000000 +CERT_REGISTRY_STORE_ROAMING_FLAG: Final = 0x40000 +CERT_REGISTRY_STORE_MY_IE_DIRTY_FLAG: Final = 0x80000 +CERT_IE_DIRTY_FLAGS_REGPATH: Final = r"Software\Microsoft\Cryptography\IEDirtyFlags" +CERT_FILE_STORE_COMMIT_ENABLE_FLAG: Final = 0x10000 +CERT_LDAP_STORE_SIGN_FLAG: Final = 0x10000 +CERT_LDAP_STORE_AREC_EXCLUSIVE_FLAG: Final = 0x20000 +CERT_LDAP_STORE_OPENED_FLAG: Final = 0x40000 +CERT_LDAP_STORE_UNBIND_FLAG: Final = 0x80000 +CRYPT_OID_OPEN_STORE_PROV_FUNC: Final = "CertDllOpenStoreProv" +CERT_STORE_PROV_EXTERNAL_FLAG: Final = 0x1 +CERT_STORE_PROV_DELETED_FLAG: Final = 0x2 +CERT_STORE_PROV_NO_PERSIST_FLAG: Final = 0x4 +CERT_STORE_PROV_SYSTEM_STORE_FLAG: Final = 0x8 +CERT_STORE_PROV_LM_SYSTEM_STORE_FLAG: Final = 0x10 +CERT_STORE_PROV_CLOSE_FUNC: Final = 0 +CERT_STORE_PROV_READ_CERT_FUNC: Final = 1 +CERT_STORE_PROV_WRITE_CERT_FUNC: Final = 2 +CERT_STORE_PROV_DELETE_CERT_FUNC: Final = 3 +CERT_STORE_PROV_SET_CERT_PROPERTY_FUNC: Final = 4 +CERT_STORE_PROV_READ_CRL_FUNC: Final = 5 +CERT_STORE_PROV_WRITE_CRL_FUNC: Final = 6 +CERT_STORE_PROV_DELETE_CRL_FUNC: Final = 7 +CERT_STORE_PROV_SET_CRL_PROPERTY_FUNC: Final = 8 +CERT_STORE_PROV_READ_CTL_FUNC: Final = 9 +CERT_STORE_PROV_WRITE_CTL_FUNC: Final = 10 +CERT_STORE_PROV_DELETE_CTL_FUNC: Final = 11 +CERT_STORE_PROV_SET_CTL_PROPERTY_FUNC: Final = 12 +CERT_STORE_PROV_CONTROL_FUNC: Final = 13 +CERT_STORE_PROV_FIND_CERT_FUNC: Final = 14 +CERT_STORE_PROV_FREE_FIND_CERT_FUNC: Final = 15 +CERT_STORE_PROV_GET_CERT_PROPERTY_FUNC: Final = 16 +CERT_STORE_PROV_FIND_CRL_FUNC: Final = 17 +CERT_STORE_PROV_FREE_FIND_CRL_FUNC: Final = 18 +CERT_STORE_PROV_GET_CRL_PROPERTY_FUNC: Final = 19 +CERT_STORE_PROV_FIND_CTL_FUNC: Final = 20 +CERT_STORE_PROV_FREE_FIND_CTL_FUNC: Final = 21 +CERT_STORE_PROV_GET_CTL_PROPERTY_FUNC: Final = 22 +CERT_STORE_PROV_WRITE_ADD_FLAG: Final = 0x1 +CERT_STORE_SAVE_AS_STORE: Final = 1 +CERT_STORE_SAVE_AS_PKCS7: Final = 2 +CERT_STORE_SAVE_TO_FILE: Final = 1 +CERT_STORE_SAVE_TO_MEMORY: Final = 2 +CERT_STORE_SAVE_TO_FILENAME_A: Final = 3 +CERT_STORE_SAVE_TO_FILENAME_W: Final = 4 +CERT_STORE_SAVE_TO_FILENAME: Final = CERT_STORE_SAVE_TO_FILENAME_W +CERT_CLOSE_STORE_FORCE_FLAG: Final = 0x00000001 +CERT_CLOSE_STORE_CHECK_FLAG: Final = 0x00000002 +CERT_COMPARE_MASK: Final = 0xFFFF +CERT_COMPARE_SHIFT: Final = 16 +CERT_COMPARE_ANY: Final = 0 +CERT_COMPARE_SHA1_HASH: Final = 1 +CERT_COMPARE_NAME: Final = 2 +CERT_COMPARE_ATTR: Final = 3 +CERT_COMPARE_MD5_HASH: Final = 4 +CERT_COMPARE_PROPERTY: Final = 5 +CERT_COMPARE_PUBLIC_KEY: Final = 6 +CERT_COMPARE_HASH: Final = CERT_COMPARE_SHA1_HASH +CERT_COMPARE_NAME_STR_A: Final = 7 +CERT_COMPARE_NAME_STR_W: Final = 8 +CERT_COMPARE_KEY_SPEC: Final = 9 +CERT_COMPARE_ENHKEY_USAGE: Final = 10 +CERT_COMPARE_CTL_USAGE: Final = CERT_COMPARE_ENHKEY_USAGE +CERT_COMPARE_SUBJECT_CERT: Final = 11 +CERT_COMPARE_ISSUER_OF: Final = 12 +CERT_COMPARE_EXISTING: Final = 13 +CERT_COMPARE_SIGNATURE_HASH: Final = 14 +CERT_COMPARE_KEY_IDENTIFIER: Final = 15 +CERT_COMPARE_CERT_ID: Final = 16 +CERT_COMPARE_CROSS_CERT_DIST_POINTS: Final = 17 +CERT_COMPARE_PUBKEY_MD5_HASH: Final = 18 +CERT_FIND_ANY: Final = 0x00000000 +CERT_FIND_SHA1_HASH: Final = 0x00010000 +CERT_FIND_MD5_HASH: Final = 0x00040000 +CERT_FIND_SIGNATURE_HASH: Final = 0x000E0000 +CERT_FIND_KEY_IDENTIFIER: Final = 0x000F0000 +CERT_FIND_HASH: Final = CERT_FIND_SHA1_HASH +CERT_FIND_PROPERTY: Final = 0x00050000 +CERT_FIND_PUBLIC_KEY: Final = 0x00060000 +CERT_FIND_SUBJECT_NAME: Final = 0x00020007 +CERT_FIND_SUBJECT_ATTR: Final = 0x00030007 +CERT_FIND_ISSUER_NAME: Final = 0x00020004 +CERT_FIND_ISSUER_ATTR: Final = 0x00030004 +CERT_FIND_SUBJECT_STR_A: Final = 0x00070007 +CERT_FIND_SUBJECT_STR_W: Final = 0x00080007 +CERT_FIND_SUBJECT_STR: Final = CERT_FIND_SUBJECT_STR_W +CERT_FIND_ISSUER_STR_A: Final = 0x00070004 +CERT_FIND_ISSUER_STR_W: Final = 0x00080004 +CERT_FIND_ISSUER_STR: Final = CERT_FIND_ISSUER_STR_W +CERT_FIND_KEY_SPEC: Final = 0x00090000 +CERT_FIND_ENHKEY_USAGE: Final = 0x000A0000 +CERT_FIND_CTL_USAGE: Final = CERT_FIND_ENHKEY_USAGE +CERT_FIND_SUBJECT_CERT: Final = 0x000B0000 +CERT_FIND_ISSUER_OF: Final = 0x000C0000 +CERT_FIND_EXISTING: Final = 0x000D0000 +CERT_FIND_CERT_ID: Final = 0x00100000 +CERT_FIND_CROSS_CERT_DIST_POINTS: Final = 0x00110000 +CERT_FIND_PUBKEY_MD5_HASH: Final = 0x00120000 +CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG: Final = 0x1 +CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG: Final = 0x2 +CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG: Final = 0x4 +CERT_FIND_NO_ENHKEY_USAGE_FLAG: Final = 0x8 +CERT_FIND_OR_ENHKEY_USAGE_FLAG: Final = 0x10 +CERT_FIND_VALID_ENHKEY_USAGE_FLAG: Final = 0x20 +CERT_FIND_OPTIONAL_CTL_USAGE_FLAG: Final = CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG +CERT_FIND_EXT_ONLY_CTL_USAGE_FLAG: Final = CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG +CERT_FIND_PROP_ONLY_CTL_USAGE_FLAG: Final = CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG +CERT_FIND_NO_CTL_USAGE_FLAG: Final = CERT_FIND_NO_ENHKEY_USAGE_FLAG +CERT_FIND_OR_CTL_USAGE_FLAG: Final = CERT_FIND_OR_ENHKEY_USAGE_FLAG +CERT_FIND_VALID_CTL_USAGE_FLAG: Final = CERT_FIND_VALID_ENHKEY_USAGE_FLAG +CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG: Final = -2147483648 +CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG: Final = 0x40000000 +CTL_ENTRY_FROM_PROP_CHAIN_FLAG: Final = 0x1 +CRL_FIND_ANY: Final = 0 +CRL_FIND_ISSUED_BY: Final = 1 +CRL_FIND_EXISTING: Final = 2 +CRL_FIND_ISSUED_FOR: Final = 3 +CRL_FIND_ISSUED_BY_AKI_FLAG: Final = 0x1 +CRL_FIND_ISSUED_BY_SIGNATURE_FLAG: Final = 0x2 +CRL_FIND_ISSUED_BY_DELTA_FLAG: Final = 0x4 +CRL_FIND_ISSUED_BY_BASE_FLAG: Final = 0x8 +CERT_STORE_ADD_NEW: Final = 1 +CERT_STORE_ADD_USE_EXISTING: Final = 2 +CERT_STORE_ADD_REPLACE_EXISTING: Final = 3 +CERT_STORE_ADD_ALWAYS: Final = 4 +CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: Final = 5 +CERT_STORE_ADD_NEWER: Final = 6 +CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES: Final = 7 +CERT_STORE_CERTIFICATE_CONTEXT: Final = 1 +CERT_STORE_CRL_CONTEXT: Final = 2 +CERT_STORE_CTL_CONTEXT: Final = 3 +CERT_STORE_ALL_CONTEXT_FLAG: Final = -1 +CERT_STORE_CERTIFICATE_CONTEXT_FLAG: Final = 2 +CERT_STORE_CRL_CONTEXT_FLAG: Final = 4 +CERT_STORE_CTL_CONTEXT_FLAG: Final = 8 +CTL_ANY_SUBJECT_TYPE: Final = 1 +CTL_CERT_SUBJECT_TYPE: Final = 2 +CTL_FIND_ANY: Final = 0 +CTL_FIND_SHA1_HASH: Final = 1 +CTL_FIND_MD5_HASH: Final = 2 +CTL_FIND_USAGE: Final = 3 +CTL_FIND_SUBJECT: Final = 4 +CTL_FIND_EXISTING: Final = 5 +CTL_FIND_NO_LIST_ID_CBDATA: Final = -1 +CTL_FIND_SAME_USAGE_FLAG: Final = 0x1 +CERT_STORE_CTRL_RESYNC: Final = 1 +CERT_STORE_CTRL_NOTIFY_CHANGE: Final = 2 +CERT_STORE_CTRL_COMMIT: Final = 3 +CERT_STORE_CTRL_AUTO_RESYNC: Final = 4 +CERT_STORE_CTRL_CANCEL_NOTIFY: Final = 5 +CERT_STORE_CTRL_INHIBIT_DUPLICATE_HANDLE_FLAG: Final = 0x1 +CERT_STORE_CTRL_COMMIT_FORCE_FLAG: Final = 0x1 +CERT_STORE_CTRL_COMMIT_CLEAR_FLAG: Final = 0x2 +CERT_STORE_LOCALIZED_NAME_PROP_ID: Final = 0x1000 +CERT_CREATE_CONTEXT_NOCOPY_FLAG: Final = 0x1 +CERT_CREATE_CONTEXT_SORTED_FLAG: Final = 0x2 +CERT_CREATE_CONTEXT_NO_HCRYPTMSG_FLAG: Final = 0x4 +CERT_CREATE_CONTEXT_NO_ENTRY_FLAG: Final = 0x8 +CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG: Final = 0x1 +CERT_PHYSICAL_STORE_OPEN_DISABLE_FLAG: Final = 0x2 +CERT_PHYSICAL_STORE_REMOTE_OPEN_DISABLE_FLAG: Final = 0x4 +CERT_PHYSICAL_STORE_INSERT_COMPUTER_NAME_ENABLE_FLAG: Final = 0x8 +CERT_PHYSICAL_STORE_PREDEFINED_ENUM_FLAG: Final = 0x1 +CERT_PHYSICAL_STORE_DEFAULT_NAME: Final = ".Default" +CERT_PHYSICAL_STORE_GROUP_POLICY_NAME: Final = ".GroupPolicy" +CERT_PHYSICAL_STORE_LOCAL_MACHINE_NAME: Final = ".LocalMachine" +CERT_PHYSICAL_STORE_DS_USER_CERTIFICATE_NAME: Final = ".UserCertificate" +CERT_PHYSICAL_STORE_LOCAL_MACHINE_GROUP_POLICY_NAME: Final = ".LocalMachineGroupPolicy" +CERT_PHYSICAL_STORE_ENTERPRISE_NAME: Final = ".Enterprise" +CERT_PHYSICAL_STORE_AUTH_ROOT_NAME: Final = ".AuthRoot" +CERT_PHYSICAL_STORE_SMART_CARD_NAME: Final = ".SmartCard" +CRYPT_OID_OPEN_SYSTEM_STORE_PROV_FUNC: Final = "CertDllOpenSystemStoreProv" +CRYPT_OID_REGISTER_SYSTEM_STORE_FUNC: Final = "CertDllRegisterSystemStore" +CRYPT_OID_UNREGISTER_SYSTEM_STORE_FUNC: Final = "CertDllUnregisterSystemStore" +CRYPT_OID_ENUM_SYSTEM_STORE_FUNC: Final = "CertDllEnumSystemStore" +CRYPT_OID_REGISTER_PHYSICAL_STORE_FUNC: Final = "CertDllRegisterPhysicalStore" +CRYPT_OID_UNREGISTER_PHYSICAL_STORE_FUNC: Final = "CertDllUnregisterPhysicalStore" +CRYPT_OID_ENUM_PHYSICAL_STORE_FUNC: Final = "CertDllEnumPhysicalStore" +CRYPT_OID_SYSTEM_STORE_LOCATION_VALUE_NAME: Final = "SystemStoreLocation" +CMSG_TRUSTED_SIGNER_FLAG: Final = 0x1 +CMSG_SIGNER_ONLY_FLAG: Final = 0x2 +CMSG_USE_SIGNER_INDEX_FLAG: Final = 0x4 +CMSG_CMS_ENCAPSULATED_CTL_FLAG: Final = 0x00008000 +CMSG_ENCODE_SORTED_CTL_FLAG: Final = 0x1 +CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: Final = 0x2 +CERT_VERIFY_INHIBIT_CTL_UPDATE_FLAG: Final = 0x1 +CERT_VERIFY_TRUSTED_SIGNERS_FLAG: Final = 0x2 +CERT_VERIFY_NO_TIME_CHECK_FLAG: Final = 0x4 +CERT_VERIFY_ALLOW_MORE_USAGE_FLAG: Final = 0x8 +CERT_VERIFY_UPDATED_CTL_FLAG: Final = 0x1 +CERT_CONTEXT_REVOCATION_TYPE: Final = 1 +CERT_VERIFY_REV_CHAIN_FLAG: Final = 0x00000001 +CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION: Final = 0x00000002 +CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG: Final = 0x00000004 +CERT_UNICODE_IS_RDN_ATTRS_FLAG: Final = 0x1 +CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG: Final = 0x2 +CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB: Final = 1 +CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT: Final = 2 +CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL: Final = 3 +CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY: Final = 1 +CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT: Final = 2 +CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: Final = 3 +CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL: Final = 4 +CRYPT_DEFAULT_CONTEXT_AUTO_RELEASE_FLAG: Final = 0x00000001 +CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG: Final = 0x00000002 +CRYPT_DEFAULT_CONTEXT_CERT_SIGN_OID: Final = 1 +CRYPT_DEFAULT_CONTEXT_MULTI_CERT_SIGN_OID: Final = 2 +CRYPT_OID_EXPORT_PUBLIC_KEY_INFO_FUNC: Final = "CryptDllExportPublicKeyInfoEx" +CRYPT_OID_IMPORT_PUBLIC_KEY_INFO_FUNC: Final = "CryptDllImportPublicKeyInfoEx" +CRYPT_ACQUIRE_CACHE_FLAG: Final = 0x00000001 +CRYPT_ACQUIRE_USE_PROV_INFO_FLAG: Final = 0x00000002 +CRYPT_ACQUIRE_COMPARE_KEY_FLAG: Final = 0x00000004 +CRYPT_ACQUIRE_SILENT_FLAG: Final = 0x00000040 +CRYPT_FIND_USER_KEYSET_FLAG: Final = 0x00000001 +CRYPT_FIND_MACHINE_KEYSET_FLAG: Final = 0x00000002 +CRYPT_FIND_SILENT_KEYSET_FLAG: Final = 0x00000040 +CRYPT_OID_IMPORT_PRIVATE_KEY_INFO_FUNC: Final = "CryptDllImportPrivateKeyInfoEx" +CRYPT_OID_EXPORT_PRIVATE_KEY_INFO_FUNC: Final = "CryptDllExportPrivateKeyInfoEx" +CRYPT_DELETE_KEYSET: Final = CRYPT_DELETEKEYSET +CERT_SIMPLE_NAME_STR: Final = 1 +CERT_OID_NAME_STR: Final = 2 +CERT_X500_NAME_STR: Final = 3 +CERT_NAME_STR_SEMICOLON_FLAG: Final = 0x40000000 +CERT_NAME_STR_NO_PLUS_FLAG: Final = 0x20000000 +CERT_NAME_STR_NO_QUOTING_FLAG: Final = 0x10000000 +CERT_NAME_STR_CRLF_FLAG: Final = 0x08000000 +CERT_NAME_STR_COMMA_FLAG: Final = 0x04000000 +CERT_NAME_STR_REVERSE_FLAG: Final = 0x02000000 +CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG: Final = 0x00010000 +CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG: Final = 0x00020000 +CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG: Final = 0x00040000 +CERT_NAME_EMAIL_TYPE: Final = 1 +CERT_NAME_RDN_TYPE: Final = 2 +CERT_NAME_ATTR_TYPE: Final = 3 +CERT_NAME_SIMPLE_DISPLAY_TYPE: Final = 4 +CERT_NAME_FRIENDLY_DISPLAY_TYPE: Final = 5 +CERT_NAME_DNS_TYPE: Final = 6 +CERT_NAME_URL_TYPE: Final = 7 +CERT_NAME_UPN_TYPE: Final = 8 +CERT_NAME_ISSUER_FLAG: Final = 0x1 +CERT_NAME_DISABLE_IE4_UTF8_FLAG: Final = 0x00010000 +CRYPT_MESSAGE_BARE_CONTENT_OUT_FLAG: Final = 0x00000001 +CRYPT_MESSAGE_ENCAPSULATED_CONTENT_OUT_FLAG: Final = 0x00000002 +CRYPT_MESSAGE_KEYID_SIGNER_FLAG: Final = 0x00000004 +CRYPT_MESSAGE_SILENT_KEYSET_FLAG: Final = 0x00000040 +CRYPT_MESSAGE_KEYID_RECIPIENT_FLAG: Final = 0x4 +CERT_QUERY_OBJECT_FILE: Final = 0x00000001 +CERT_QUERY_OBJECT_BLOB: Final = 0x00000002 +CERT_QUERY_CONTENT_CERT: Final = 1 +CERT_QUERY_CONTENT_CTL: Final = 2 +CERT_QUERY_CONTENT_CRL: Final = 3 +CERT_QUERY_CONTENT_SERIALIZED_STORE: Final = 4 +CERT_QUERY_CONTENT_SERIALIZED_CERT: Final = 5 +CERT_QUERY_CONTENT_SERIALIZED_CTL: Final = 6 +CERT_QUERY_CONTENT_SERIALIZED_CRL: Final = 7 +CERT_QUERY_CONTENT_PKCS7_SIGNED: Final = 8 +CERT_QUERY_CONTENT_PKCS7_UNSIGNED: Final = 9 +CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED: Final = 10 +CERT_QUERY_CONTENT_PKCS10: Final = 11 +CERT_QUERY_CONTENT_PFX: Final = 12 +CERT_QUERY_CONTENT_CERT_PAIR: Final = 13 +CERT_QUERY_CONTENT_FLAG_CERT: Final = 0x00000002 +CERT_QUERY_CONTENT_FLAG_CTL: Final = 0x00000004 +CERT_QUERY_CONTENT_FLAG_CRL: Final = 0x00000008 +CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE: Final = 0x00000010 +CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT: Final = 0x00000020 +CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL: Final = 0x00000040 +CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL: Final = 0x00000080 +CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED: Final = 0x00000100 +CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED: Final = 0x00000200 +CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED: Final = 0x00000400 +CERT_QUERY_CONTENT_FLAG_PKCS10: Final = 0x00000800 +CERT_QUERY_CONTENT_FLAG_PFX: Final = 0x00001000 +CERT_QUERY_CONTENT_FLAG_CERT_PAIR: Final = 0x00002000 +CERT_QUERY_CONTENT_FLAG_ALL: Final = 0x00003FFE +CERT_QUERY_FORMAT_BINARY: Final = 1 +CERT_QUERY_FORMAT_BASE64_ENCODED: Final = 2 +CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED: Final = 3 +CERT_QUERY_FORMAT_FLAG_BINARY: Final = 0x00000002 +CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED: Final = 0x00000004 +CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED: Final = 0x00000008 +CERT_QUERY_FORMAT_FLAG_ALL: Final = 0x0000000E +CREDENTIAL_OID_PASSWORD_CREDENTIALS_A: Final = 1 +CREDENTIAL_OID_PASSWORD_CREDENTIALS_W: Final = 2 +CREDENTIAL_OID_PASSWORD_CREDENTIALS: Final = CREDENTIAL_OID_PASSWORD_CREDENTIALS_W +SCHEME_OID_RETRIEVE_ENCODED_OBJECT_FUNC: Final = "SchemeDllRetrieveEncodedObject" +SCHEME_OID_RETRIEVE_ENCODED_OBJECTW_FUNC: Final = "SchemeDllRetrieveEncodedObjectW" +CONTEXT_OID_CREATE_OBJECT_CONTEXT_FUNC: Final = "ContextDllCreateObjectContext" +CONTEXT_OID_CERTIFICATE: Final = 1 +CONTEXT_OID_CRL: Final = 2 +CONTEXT_OID_CTL: Final = 3 +CONTEXT_OID_PKCS7: Final = 4 +CONTEXT_OID_CAPI2_ANY: Final = 5 +CONTEXT_OID_OCSP_RESP: Final = 6 +CRYPT_RETRIEVE_MULTIPLE_OBJECTS: Final = 0x00000001 +CRYPT_CACHE_ONLY_RETRIEVAL: Final = 0x00000002 +CRYPT_WIRE_ONLY_RETRIEVAL: Final = 0x00000004 +CRYPT_DONT_CACHE_RESULT: Final = 0x00000008 +CRYPT_ASYNC_RETRIEVAL: Final = 0x00000010 +CRYPT_STICKY_CACHE_RETRIEVAL: Final = 0x00001000 +CRYPT_LDAP_SCOPE_BASE_ONLY_RETRIEVAL: Final = 0x00002000 +CRYPT_OFFLINE_CHECK_RETRIEVAL: Final = 0x00004000 +CRYPT_LDAP_INSERT_ENTRY_ATTRIBUTE: Final = 0x00008000 +CRYPT_LDAP_SIGN_RETRIEVAL: Final = 0x00010000 +CRYPT_NO_AUTH_RETRIEVAL: Final = 0x00020000 +CRYPT_LDAP_AREC_EXCLUSIVE_RETRIEVAL: Final = 0x00040000 +CRYPT_AIA_RETRIEVAL: Final = 0x00080000 +CRYPT_VERIFY_CONTEXT_SIGNATURE: Final = 0x00000020 +CRYPT_VERIFY_DATA_HASH: Final = 0x00000040 +CRYPT_KEEP_TIME_VALID: Final = 0x00000080 +CRYPT_DONT_VERIFY_SIGNATURE: Final = 0x00000100 +CRYPT_DONT_CHECK_TIME_VALIDITY: Final = 0x00000200 +CRYPT_CHECK_FRESHNESS_TIME_VALIDITY: Final = 0x00000400 +CRYPT_ACCUMULATIVE_TIMEOUT: Final = 0x00000800 +CRYPT_PARAM_ASYNC_RETRIEVAL_COMPLETION: Final = 1 +CRYPT_PARAM_CANCEL_ASYNC_RETRIEVAL: Final = 2 +CRYPT_GET_URL_FROM_PROPERTY: Final = 0x00000001 +CRYPT_GET_URL_FROM_EXTENSION: Final = 0x00000002 +CRYPT_GET_URL_FROM_UNAUTH_ATTRIBUTE: Final = 0x00000004 +CRYPT_GET_URL_FROM_AUTH_ATTRIBUTE: Final = 0x00000008 +URL_OID_GET_OBJECT_URL_FUNC: Final = "UrlDllGetObjectUrl" +TIME_VALID_OID_GET_OBJECT_FUNC: Final = "TimeValidDllGetObject" +TIME_VALID_OID_FLUSH_OBJECT_FUNC: Final = "TimeValidDllFlushObject" +TIME_VALID_OID_GET_CTL: Final = 1 +TIME_VALID_OID_GET_CRL: Final = 2 +TIME_VALID_OID_GET_CRL_FROM_CERT: Final = 3 +TIME_VALID_OID_GET_FRESHEST_CRL_FROM_CERT: Final = 4 +TIME_VALID_OID_GET_FRESHEST_CRL_FROM_CRL: Final = 5 +TIME_VALID_OID_FLUSH_CTL: Final = 1 +TIME_VALID_OID_FLUSH_CRL: Final = 2 +TIME_VALID_OID_FLUSH_CRL_FROM_CERT: Final = 3 +TIME_VALID_OID_FLUSH_FRESHEST_CRL_FROM_CERT: Final = 4 +TIME_VALID_OID_FLUSH_FRESHEST_CRL_FROM_CRL: Final = 5 +CRYPTPROTECT_PROMPT_ON_UNPROTECT: Final = 0x1 +CRYPTPROTECT_PROMPT_ON_PROTECT: Final = 0x2 +CRYPTPROTECT_PROMPT_RESERVED: Final = 0x04 +CRYPTPROTECT_PROMPT_STRONG: Final = 0x08 +CRYPTPROTECT_PROMPT_REQUIRE_STRONG: Final = 0x10 +CRYPTPROTECT_UI_FORBIDDEN: Final = 0x1 +CRYPTPROTECT_LOCAL_MACHINE: Final = 0x4 +CRYPTPROTECT_CRED_SYNC: Final = 0x8 +CRYPTPROTECT_AUDIT: Final = 0x10 +CRYPTPROTECT_NO_RECOVERY: Final = 0x20 +CRYPTPROTECT_VERIFY_PROTECTION: Final = 0x40 +CRYPTPROTECT_CRED_REGENERATE: Final = 0x80 +CRYPTPROTECT_FIRST_RESERVED_FLAGVAL: Final = 0x0FFFFFFF +CRYPTPROTECT_LAST_RESERVED_FLAGVAL: Final = -1 +CRYPTPROTECTMEMORY_BLOCK_SIZE: Final = 16 +CRYPTPROTECTMEMORY_SAME_PROCESS: Final = 0x00 +CRYPTPROTECTMEMORY_CROSS_PROCESS: Final = 0x01 +CRYPTPROTECTMEMORY_SAME_LOGON: Final = 0x02 +CERT_CREATE_SELFSIGN_NO_SIGN: Final = 1 +CERT_CREATE_SELFSIGN_NO_KEY_INFO: Final = 2 +CRYPT_KEYID_MACHINE_FLAG: Final = 0x00000020 +CRYPT_KEYID_ALLOC_FLAG: Final = 0x00008000 +CRYPT_KEYID_DELETE_FLAG: Final = 0x00000010 +CRYPT_KEYID_SET_NEW_FLAG: Final = 0x00002000 +CERT_CHAIN_MAX_AIA_URL_COUNT_IN_CERT_DEFAULT: Final = 5 +CERT_CHAIN_MAX_AIA_URL_RETRIEVAL_COUNT_PER_CHAIN_DEFAULT: Final = 10 +CERT_CHAIN_MAX_AIA_URL_RETRIEVAL_BYTE_COUNT_DEFAULT: Final = 100000 +CERT_CHAIN_MAX_AIA_URL_RETRIEVAL_CERT_COUNT_DEFAULT: Final = 10 +CERT_CHAIN_CACHE_END_CERT: Final = 0x00000001 +CERT_CHAIN_THREAD_STORE_SYNC: Final = 0x00000002 +CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL: Final = 0x00000004 +CERT_CHAIN_USE_LOCAL_MACHINE_STORE: Final = 0x00000008 +CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE: Final = 0x00000010 +CERT_CHAIN_ENABLE_SHARE_STORE: Final = 0x00000020 +CERT_TRUST_NO_ERROR: Final = 0x00000000 +CERT_TRUST_IS_NOT_TIME_VALID: Final = 0x00000001 +CERT_TRUST_IS_NOT_TIME_NESTED: Final = 0x00000002 +CERT_TRUST_IS_REVOKED: Final = 0x00000004 +CERT_TRUST_IS_NOT_SIGNATURE_VALID: Final = 0x00000008 +CERT_TRUST_IS_NOT_VALID_FOR_USAGE: Final = 0x00000010 +CERT_TRUST_IS_UNTRUSTED_ROOT: Final = 0x00000020 +CERT_TRUST_REVOCATION_STATUS_UNKNOWN: Final = 0x00000040 +CERT_TRUST_IS_CYCLIC: Final = 0x00000080 +CERT_TRUST_INVALID_EXTENSION: Final = 0x00000100 +CERT_TRUST_INVALID_POLICY_CONSTRAINTS: Final = 0x00000200 +CERT_TRUST_INVALID_BASIC_CONSTRAINTS: Final = 0x00000400 +CERT_TRUST_INVALID_NAME_CONSTRAINTS: Final = 0x00000800 +CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT: Final = 0x00001000 +CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT: Final = 0x00002000 +CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT: Final = 0x00004000 +CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT: Final = 0x00008000 +CERT_TRUST_IS_OFFLINE_REVOCATION: Final = 0x01000000 +CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY: Final = 0x02000000 +CERT_TRUST_IS_PARTIAL_CHAIN: Final = 0x00010000 +CERT_TRUST_CTL_IS_NOT_TIME_VALID: Final = 0x00020000 +CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID: Final = 0x00040000 +CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE: Final = 0x00080000 +CERT_TRUST_HAS_EXACT_MATCH_ISSUER: Final = 0x00000001 +CERT_TRUST_HAS_KEY_MATCH_ISSUER: Final = 0x00000002 +CERT_TRUST_HAS_NAME_MATCH_ISSUER: Final = 0x00000004 +CERT_TRUST_IS_SELF_SIGNED: Final = 0x00000008 +CERT_TRUST_HAS_PREFERRED_ISSUER: Final = 0x00000100 +CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY: Final = 0x00000200 +CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS: Final = 0x00000400 +CERT_TRUST_IS_COMPLEX_CHAIN: Final = 0x00010000 +USAGE_MATCH_TYPE_AND: Final = 0x00000000 +USAGE_MATCH_TYPE_OR: Final = 0x00000001 +CERT_CHAIN_REVOCATION_CHECK_END_CERT: Final = 0x10000000 +CERT_CHAIN_REVOCATION_CHECK_CHAIN: Final = 0x20000000 +CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT: Final = 0x40000000 +CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY: Final = -2147483648 +CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT: Final = 0x08000000 +CERT_CHAIN_DISABLE_PASS1_QUALITY_FILTERING: Final = 0x00000040 +CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS: Final = 0x00000080 +CERT_CHAIN_DISABLE_AUTH_ROOT_AUTO_UPDATE: Final = 0x00000100 +CERT_CHAIN_TIMESTAMP_TIME: Final = 0x00000200 +REVOCATION_OID_CRL_REVOCATION: Final = 1 +CERT_CHAIN_FIND_BY_ISSUER: Final = 1 +CERT_CHAIN_FIND_BY_ISSUER_COMPARE_KEY_FLAG: Final = 0x0001 +CERT_CHAIN_FIND_BY_ISSUER_COMPLEX_CHAIN_FLAG: Final = 0x0002 +CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG: Final = 0x0004 +CERT_CHAIN_FIND_BY_ISSUER_LOCAL_MACHINE_FLAG: Final = 0x0008 +CERT_CHAIN_FIND_BY_ISSUER_NO_KEY_FLAG: Final = 0x4000 +CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG: Final = 0x8000 +CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG: Final = 0x00000001 +CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG: Final = 0x00000002 +CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG: Final = 0x00000004 +CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG: Final = 0x00000008 +CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS: Final = 0x00000007 +CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG: Final = 0x00000010 +CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG: Final = 0x00000020 +CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG: Final = 0x00000040 +CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG: Final = 0x00000080 +CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG: Final = 0x00000100 +CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG: Final = 0x00000200 +CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG: Final = 0x00000400 +CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG: Final = 0x00000800 +CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS: Final = 0x00000F00 +CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG: Final = 0x00008000 +CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG: Final = 0x00004000 +CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC: Final = "CertDllVerifyCertificateChainPolicy" +AUTHTYPE_CLIENT: Final = 1 +AUTHTYPE_SERVER: Final = 2 +BASIC_CONSTRAINTS_CERT_CHAIN_POLICY_CA_FLAG: Final = -2147483648 +BASIC_CONSTRAINTS_CERT_CHAIN_POLICY_END_ENTITY_FLAG: Final = 0x40000000 +MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG: Final = 0x00010000 +CRYPT_STRING_BASE64HEADER: Final = 0x00000000 +CRYPT_STRING_BASE64: Final = 0x00000001 +CRYPT_STRING_BINARY: Final = 0x00000002 +CRYPT_STRING_BASE64REQUESTHEADER: Final = 0x00000003 +CRYPT_STRING_HEX: Final = 0x00000004 +CRYPT_STRING_HEXASCII: Final = 0x00000005 +CRYPT_STRING_BASE64_ANY: Final = 0x00000006 +CRYPT_STRING_ANY: Final = 0x00000007 +CRYPT_STRING_HEX_ANY: Final = 0x00000008 +CRYPT_STRING_BASE64X509CRLHEADER: Final = 0x00000009 +CRYPT_STRING_HEXADDR: Final = 0x0000000A +CRYPT_STRING_HEXASCIIADDR: Final = 0x0000000B +CRYPT_STRING_NOCR: Final = -2147483648 +CRYPT_USER_KEYSET: Final = 0x00001000 +PKCS12_IMPORT_RESERVED_MASK: Final = -65536 +REPORT_NO_PRIVATE_KEY: Final = 0x0001 +REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY: Final = 0x0002 +EXPORT_PRIVATE_KEYS: Final = 0x0004 +PKCS12_EXPORT_RESERVED_MASK: Final = -65536 +CERT_STORE_PROV_MSG: Final = 1 +CERT_STORE_PROV_MEMORY: Final = 2 +CERT_STORE_PROV_FILE: Final = 3 +CERT_STORE_PROV_REG: Final = 4 +CERT_STORE_PROV_PKCS7: Final = 5 +CERT_STORE_PROV_SERIALIZED: Final = 6 +CERT_STORE_PROV_FILENAME: Final = 8 +CERT_STORE_PROV_SYSTEM: Final = 10 +CERT_STORE_PROV_COLLECTION: Final = 11 +CERT_STORE_PROV_SYSTEM_REGISTRY: Final = 13 +CERT_STORE_PROV_PHYSICAL: Final = 14 +CERT_STORE_PROV_SMART_CARD: Final = 15 +CERT_STORE_PROV_LDAP: Final = 16 +URL_OID_CERTIFICATE_ISSUER: Final = 1 +URL_OID_CERTIFICATE_CRL_DIST_POINT: Final = 2 +URL_OID_CTL_ISSUER: Final = 3 +URL_OID_CTL_NEXT_UPDATE: Final = 4 +URL_OID_CRL_ISSUER: Final = 5 +URL_OID_CERTIFICATE_FRESHEST_CRL: Final = 6 +URL_OID_CRL_FRESHEST_CRL: Final = 7 +URL_OID_CROSS_CERT_DIST_POINT: Final = 8 +URL_OID_CERTIFICATE_OCSP: Final = 9 +URL_OID_CERTIFICATE_OCSP_AND_CRL_DIST_POINT: Final = 10 +URL_OID_CERTIFICATE_CRL_DIST_POINT_AND_OCSP: Final = 11 +URL_OID_CROSS_CERT_SUBJECT_INFO_ACCESS: Final = 12 +URL_OID_CERTIFICATE_ONLY_OCSP: Final = 13 diff --git a/stubs/pywin32/win32/lib/win32evtlogutil.pyi b/stubs/pywin32/win32/lib/win32evtlogutil.pyi new file mode 100644 index 000000000000..7ab2cff5e46b --- /dev/null +++ b/stubs/pywin32/win32/lib/win32evtlogutil.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import _win32typing +import win32api + +error = win32api.error +langid: Incomplete + +def AddSourceToRegistry( + appName, msgDLL=None, eventLogType: str = "Application", eventLogFlags=None, categoryDLL=None, categoryCount: int = 0 +) -> None: ... +def RemoveSourceFromRegistry(appName, eventLogType: str = ...) -> None: ... +def ReportEvent( + appName: str, + eventID: int, + eventCategory: int = ..., + eventType: int = ..., + strings: Iterable[str] | None = ..., + data: bytes | None = ..., + sid: _win32typing.PySID | None = ..., +) -> None: ... +def FormatMessage(eventLogRecord: _win32typing.PyEventLogRecord, logType: str = ...): ... +def SafeFormatMessage(eventLogRecord, logType: Incomplete | None = ...): ... +def FeedEventLogRecords(feeder, machineName: Incomplete | None = ..., logName: str = ..., readFlags: Incomplete | None = ...): ... diff --git a/stubs/pywin32/win32/lib/win32gui_struct.pyi b/stubs/pywin32/win32/lib/win32gui_struct.pyi new file mode 100644 index 000000000000..fd8708e0f738 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32gui_struct.pyi @@ -0,0 +1,210 @@ +from _typeshed import Incomplete, ReadableBuffer +from array import array +from typing import NamedTuple, type_check_only + +is64bit: bool + +@type_check_only +class _WMNOTIFY(NamedTuple): + hwndFrom: Incomplete + idFrom: Incomplete + code: Incomplete + +def UnpackWMNOTIFY(lparam: int) -> _WMNOTIFY: ... + +@type_check_only +class _NMITEMACTIVATE(NamedTuple): + hwndFrom: Incomplete + idFrom: Incomplete + code: Incomplete + iItem: Incomplete + iSubItem: Incomplete + uNewState: Incomplete + uOldState: Incomplete + uChanged: Incomplete + actionx: Incomplete + actiony: Incomplete + lParam: Incomplete + +def UnpackNMITEMACTIVATE(lparam) -> _NMITEMACTIVATE: ... +def PackMENUITEMINFO( + fType: Incomplete | None = ..., + fState: Incomplete | None = ..., + wID: Incomplete | None = ..., + hSubMenu: Incomplete | None = ..., + hbmpChecked: Incomplete | None = ..., + hbmpUnchecked: Incomplete | None = ..., + dwItemData: Incomplete | None = ..., + text: Incomplete | None = ..., + hbmpItem: Incomplete | None = ..., + dwTypeData: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _MENUITEMINFO(NamedTuple): + fType: int | None + fState: int | None + wID: int | None + hSubMenu: int | None + hbmpChecked: int | None + hbmpUnchecked: int | None + dwItemData: int | None + text: str | None + hbmpItem: int | None + +def UnpackMENUITEMINFO(s: ReadableBuffer) -> _MENUITEMINFO: ... +def EmptyMENUITEMINFO(mask: Incomplete | None = ..., text_buf_size: int = ...) -> tuple[array[int], list[array[int]]]: ... +def PackMENUINFO( + dwStyle: Incomplete | None = ..., + cyMax: Incomplete | None = ..., + hbrBack: Incomplete | None = ..., + dwContextHelpID: Incomplete | None = ..., + dwMenuData: Incomplete | None = ..., + fMask: int = ..., +) -> array[int]: ... + +@type_check_only +class _MENUINFO(NamedTuple): + dwStyle: Incomplete | None + cyMax: Incomplete | None + hbrBack: Incomplete | None + dwContextHelpID: Incomplete | None + dwMenuData: Incomplete | None + +def UnpackMENUINFO(s: ReadableBuffer) -> _MENUINFO: ... +def EmptyMENUINFO(mask: Incomplete | None = ...) -> array[int]: ... +def PackTVINSERTSTRUCT(parent, insertAfter, tvitem) -> tuple[bytes, list[Incomplete]]: ... +def PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param) -> tuple[array[int], list[Incomplete]]: ... +def EmptyTVITEM(hitem, mask: Incomplete | None = ..., text_buf_size: int = ...) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _TVITEM(NamedTuple): + item_hItem: Incomplete + item_state: Incomplete | None + item_stateMask: Incomplete | None + text: Incomplete | None + item_image: Incomplete | None + item_selimage: Incomplete | None + item_cChildren: Incomplete | None + item_param: Incomplete | None + +def UnpackTVITEM(buffer: ReadableBuffer) -> _TVITEM: ... + +@type_check_only +class _TVNOTIFY(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + action: Incomplete + item_old: _TVITEM + item_new: _TVITEM + +def UnpackTVNOTIFY(lparam: int) -> _TVNOTIFY: ... + +@type_check_only +class _TVDISPINFO(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + item: _TVITEM + +def UnpackTVDISPINFO(lparam: int) -> _TVDISPINFO: ... +def PackLVITEM( + item: Incomplete | None = ..., + subItem: Incomplete | None = ..., + state: Incomplete | None = ..., + stateMask: Incomplete | None = ..., + text: Incomplete | None = ..., + image: Incomplete | None = ..., + param: Incomplete | None = ..., + indent: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _LVITEM(NamedTuple): + item_item: Incomplete + item_subItem: Incomplete + item_state: Incomplete | None + item_stateMask: Incomplete | None + text: Incomplete | None + item_image: Incomplete | None + item_param: Incomplete | None + item_indent: Incomplete | None + +def UnpackLVITEM(buffer: ReadableBuffer) -> _LVITEM: ... + +@type_check_only +class _LVDISPINFO(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + item: _LVITEM + +def UnpackLVDISPINFO(lparam: int) -> _LVDISPINFO: ... + +@type_check_only +class _UnpackLVNOTIFY(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + item: Incomplete + subitem: Incomplete + newstate: Incomplete + oldstate: Incomplete + changed: Incomplete + pt: tuple[Incomplete, Incomplete] + lparam: Incomplete + +def UnpackLVNOTIFY(lparam: int) -> _UnpackLVNOTIFY: ... +def EmptyLVITEM( + item, subitem, mask: Incomplete | None = ..., text_buf_size: int = ... +) -> tuple[array[int], list[Incomplete]]: ... +def PackLVCOLUMN( + fmt: Incomplete | None = ..., + cx: Incomplete | None = ..., + text: Incomplete | None = ..., + subItem: Incomplete | None = ..., + image: Incomplete | None = ..., + order: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _LVCOLUMN(NamedTuple): + fmt: Incomplete | None + cx: Incomplete | None + text: Incomplete | None + subItem: Incomplete | None + image: Incomplete | None + order: Incomplete | None + +def UnpackLVCOLUMN(lparam: ReadableBuffer) -> _LVCOLUMN: ... +def EmptyLVCOLUMN(mask: Incomplete | None = ..., text_buf_size: int = ...) -> tuple[array[int], list[Incomplete]]: ... +def PackLVHITTEST(pt) -> tuple[array[int], None]: ... + +@type_check_only +class _LVHITTEST(NamedTuple): + pt: tuple[Incomplete, Incomplete] + flags: Incomplete + item: Incomplete + subitem: Incomplete + +def UnpackLVHITTEST(buf: ReadableBuffer) -> tuple[tuple[Incomplete, Incomplete], Incomplete, Incomplete, Incomplete]: ... +def PackHDITEM( + cxy: Incomplete | None = ..., + text: Incomplete | None = ..., + hbm: Incomplete | None = ..., + fmt: Incomplete | None = ..., + param: Incomplete | None = ..., + image: Incomplete | None = ..., + order: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... +def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=...) -> bytes: ... +def PackDEV_BROADCAST_HANDLE(handle, hdevnotify: int = ..., guid=..., name_offset: int = ..., data=...) -> bytes: ... +def PackDEV_BROADCAST_VOLUME(unitmask, flags) -> bytes: ... +def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name: str = ...) -> bytes: ... + +class DEV_BROADCAST_INFO: + devicetype: Incomplete + def __init__(self, devicetype, **kw) -> None: ... + +def UnpackDEV_BROADCAST(lparam: int) -> DEV_BROADCAST_INFO | None: ... diff --git a/stubs/pywin32/win32/lib/win32inetcon.pyi b/stubs/pywin32/win32/lib/win32inetcon.pyi new file mode 100644 index 000000000000..85c2963d16a9 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32inetcon.pyi @@ -0,0 +1,991 @@ +from typing import Final + +INTERNET_INVALID_PORT_NUMBER: Final = 0 +INTERNET_DEFAULT_PORT: Final = 0 +INTERNET_DEFAULT_FTP_PORT: Final = 21 +INTERNET_DEFAULT_GOPHER_PORT: Final = 70 +INTERNET_DEFAULT_HTTP_PORT: Final = 80 +INTERNET_DEFAULT_HTTPS_PORT: Final = 443 +INTERNET_DEFAULT_SOCKS_PORT: Final = 1080 +INTERNET_MAX_HOST_NAME_LENGTH: Final = 256 +INTERNET_MAX_USER_NAME_LENGTH: Final = 128 +INTERNET_MAX_PASSWORD_LENGTH: Final = 128 +INTERNET_MAX_PORT_NUMBER_LENGTH: Final = 5 +INTERNET_MAX_PORT_NUMBER_VALUE: Final = 65535 +INTERNET_MAX_PATH_LENGTH: Final = 2048 +INTERNET_MAX_SCHEME_LENGTH: Final = 32 +INTERNET_KEEP_ALIVE_ENABLED: Final = 1 +INTERNET_KEEP_ALIVE_DISABLED: Final = 0 +INTERNET_REQFLAG_FROM_CACHE: Final = 0x00000001 +INTERNET_REQFLAG_ASYNC: Final = 0x00000002 +INTERNET_REQFLAG_VIA_PROXY: Final = 0x00000004 +INTERNET_REQFLAG_NO_HEADERS: Final = 0x00000008 +INTERNET_REQFLAG_PASSIVE: Final = 0x00000010 +INTERNET_REQFLAG_CACHE_WRITE_DISABLED: Final = 0x00000040 +INTERNET_REQFLAG_NET_TIMEOUT: Final = 0x00000080 +INTERNET_FLAG_RELOAD: Final = -2147483648 +INTERNET_FLAG_RAW_DATA: Final = 0x40000000 +INTERNET_FLAG_EXISTING_CONNECT: Final = 0x20000000 +INTERNET_FLAG_ASYNC: Final = 0x10000000 +INTERNET_FLAG_PASSIVE: Final = 0x08000000 +INTERNET_FLAG_NO_CACHE_WRITE: Final = 0x04000000 +INTERNET_FLAG_DONT_CACHE: Final = INTERNET_FLAG_NO_CACHE_WRITE +INTERNET_FLAG_MAKE_PERSISTENT: Final = 0x02000000 +INTERNET_FLAG_FROM_CACHE: Final = 0x01000000 +INTERNET_FLAG_OFFLINE: Final = INTERNET_FLAG_FROM_CACHE +INTERNET_FLAG_SECURE: Final = 0x00800000 +INTERNET_FLAG_KEEP_CONNECTION: Final = 0x00400000 +INTERNET_FLAG_NO_AUTO_REDIRECT: Final = 0x00200000 +INTERNET_FLAG_READ_PREFETCH: Final = 0x00100000 +INTERNET_FLAG_NO_COOKIES: Final = 0x00080000 +INTERNET_FLAG_NO_AUTH: Final = 0x00040000 +INTERNET_FLAG_RESTRICTED_ZONE: Final = 0x00020000 +INTERNET_FLAG_CACHE_IF_NET_FAIL: Final = 0x00010000 +INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP: Final = 0x00008000 +INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS: Final = 0x00004000 +INTERNET_FLAG_IGNORE_CERT_DATE_INVALID: Final = 0x00002000 +INTERNET_FLAG_IGNORE_CERT_CN_INVALID: Final = 0x00001000 +INTERNET_FLAG_RESYNCHRONIZE: Final = 0x00000800 +INTERNET_FLAG_HYPERLINK: Final = 0x00000400 +INTERNET_FLAG_NO_UI: Final = 0x00000200 +INTERNET_FLAG_PRAGMA_NOCACHE: Final = 0x00000100 +INTERNET_FLAG_CACHE_ASYNC: Final = 0x00000080 +INTERNET_FLAG_FORMS_SUBMIT: Final = 0x00000040 +INTERNET_FLAG_FWD_BACK: Final = 0x00000020 +INTERNET_FLAG_NEED_FILE: Final = 0x00000010 +INTERNET_FLAG_MUST_CACHE_REQUEST: Final = INTERNET_FLAG_NEED_FILE +SECURITY_INTERNET_MASK: Final = 0x0000F000 +INTERNET_ERROR_MASK_INSERT_CDROM: Final = 0x1 +INTERNET_ERROR_MASK_COMBINED_SEC_CERT: Final = 0x2 +INTERNET_ERROR_MASK_NEED_MSN_SSPI_PKG: Final = 0x4 +INTERNET_ERROR_MASK_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: Final = 0x8 +WININET_API_FLAG_ASYNC: Final = 0x00000001 +WININET_API_FLAG_SYNC: Final = 0x00000004 +WININET_API_FLAG_USE_CONTEXT: Final = 0x00000008 +INTERNET_NO_CALLBACK: Final = 0 +IDSI_FLAG_KEEP_ALIVE: Final = 0x00000001 +IDSI_FLAG_SECURE: Final = 0x00000002 +IDSI_FLAG_PROXY: Final = 0x00000004 +IDSI_FLAG_TUNNEL: Final = 0x00000008 +INTERNET_PER_CONN_FLAGS: Final = 1 +INTERNET_PER_CONN_PROXY_SERVER: Final = 2 +INTERNET_PER_CONN_PROXY_BYPASS: Final = 3 +INTERNET_PER_CONN_AUTOCONFIG_URL: Final = 4 +INTERNET_PER_CONN_AUTODISCOVERY_FLAGS: Final = 5 +INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL: Final = 6 +INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS: Final = 7 +INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME: Final = 8 +INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL: Final = 9 +PROXY_TYPE_DIRECT: Final = 0x00000001 +PROXY_TYPE_PROXY: Final = 0x00000002 +PROXY_TYPE_AUTO_PROXY_URL: Final = 0x00000004 +PROXY_TYPE_AUTO_DETECT: Final = 0x00000008 +AUTO_PROXY_FLAG_USER_SET: Final = 0x00000001 +AUTO_PROXY_FLAG_ALWAYS_DETECT: Final = 0x00000002 +AUTO_PROXY_FLAG_DETECTION_RUN: Final = 0x00000004 +AUTO_PROXY_FLAG_MIGRATED: Final = 0x00000008 +AUTO_PROXY_FLAG_DONT_CACHE_PROXY_RESULT: Final = 0x00000010 +AUTO_PROXY_FLAG_CACHE_INIT_RUN: Final = 0x00000020 +AUTO_PROXY_FLAG_DETECTION_SUSPECT: Final = 0x00000040 +ISO_FORCE_DISCONNECTED: Final = 0x00000001 +INTERNET_RFC1123_FORMAT: Final = 0 +INTERNET_RFC1123_BUFSIZE: Final = 30 +ICU_ESCAPE: Final = -2147483648 +ICU_ESCAPE_AUTHORITY: Final = 0x00002000 +ICU_REJECT_USERPWD: Final = 0x00004000 +ICU_USERNAME: Final = 0x40000000 +ICU_NO_ENCODE: Final = 0x20000000 +ICU_DECODE: Final = 0x10000000 +ICU_NO_META: Final = 0x08000000 +ICU_ENCODE_SPACES_ONLY: Final = 0x04000000 +ICU_BROWSER_MODE: Final = 0x02000000 +ICU_ENCODE_PERCENT: Final = 0x00001000 +INTERNET_OPEN_TYPE_PRECONFIG: Final = 0 +INTERNET_OPEN_TYPE_DIRECT: Final = 1 +INTERNET_OPEN_TYPE_PROXY: Final = 3 +INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY: Final = 4 +PRE_CONFIG_INTERNET_ACCESS: Final = INTERNET_OPEN_TYPE_PRECONFIG +LOCAL_INTERNET_ACCESS: Final = INTERNET_OPEN_TYPE_DIRECT +CERN_PROXY_INTERNET_ACCESS: Final = INTERNET_OPEN_TYPE_PROXY +INTERNET_SERVICE_FTP: Final = 1 +INTERNET_SERVICE_GOPHER: Final = 2 +INTERNET_SERVICE_HTTP: Final = 3 +IRF_ASYNC: Final = WININET_API_FLAG_ASYNC +IRF_SYNC: Final = WININET_API_FLAG_SYNC +IRF_USE_CONTEXT: Final = WININET_API_FLAG_USE_CONTEXT +IRF_NO_WAIT: Final = 0x00000008 +ISO_GLOBAL: Final = 0x00000001 +ISO_REGISTRY: Final = 0x00000002 +ISO_VALID_FLAGS: Final = 0x00000003 +INTERNET_OPTION_CALLBACK: Final = 1 +INTERNET_OPTION_CONNECT_TIMEOUT: Final = 2 +INTERNET_OPTION_CONNECT_RETRIES: Final = 3 +INTERNET_OPTION_CONNECT_BACKOFF: Final = 4 +INTERNET_OPTION_SEND_TIMEOUT: Final = 5 +INTERNET_OPTION_CONTROL_SEND_TIMEOUT: Final = INTERNET_OPTION_SEND_TIMEOUT +INTERNET_OPTION_RECEIVE_TIMEOUT: Final = 6 +INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT: Final = INTERNET_OPTION_RECEIVE_TIMEOUT +INTERNET_OPTION_DATA_SEND_TIMEOUT: Final = 7 +INTERNET_OPTION_DATA_RECEIVE_TIMEOUT: Final = 8 +INTERNET_OPTION_HANDLE_TYPE: Final = 9 +INTERNET_OPTION_LISTEN_TIMEOUT: Final = 11 +INTERNET_OPTION_READ_BUFFER_SIZE: Final = 12 +INTERNET_OPTION_WRITE_BUFFER_SIZE: Final = 13 +INTERNET_OPTION_ASYNC_ID: Final = 15 +INTERNET_OPTION_ASYNC_PRIORITY: Final = 16 +INTERNET_OPTION_PARENT_HANDLE: Final = 21 +INTERNET_OPTION_KEEP_CONNECTION: Final = 22 +INTERNET_OPTION_REQUEST_FLAGS: Final = 23 +INTERNET_OPTION_EXTENDED_ERROR: Final = 24 +INTERNET_OPTION_OFFLINE_MODE: Final = 26 +INTERNET_OPTION_CACHE_STREAM_HANDLE: Final = 27 +INTERNET_OPTION_USERNAME: Final = 28 +INTERNET_OPTION_PASSWORD: Final = 29 +INTERNET_OPTION_ASYNC: Final = 30 +INTERNET_OPTION_SECURITY_FLAGS: Final = 31 +INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: Final = 32 +INTERNET_OPTION_DATAFILE_NAME: Final = 33 +INTERNET_OPTION_URL: Final = 34 +INTERNET_OPTION_SECURITY_CERTIFICATE: Final = 35 +INTERNET_OPTION_SECURITY_KEY_BITNESS: Final = 36 +INTERNET_OPTION_REFRESH: Final = 37 +INTERNET_OPTION_PROXY: Final = 38 +INTERNET_OPTION_SETTINGS_CHANGED: Final = 39 +INTERNET_OPTION_VERSION: Final = 40 +INTERNET_OPTION_USER_AGENT: Final = 41 +INTERNET_OPTION_END_BROWSER_SESSION: Final = 42 +INTERNET_OPTION_PROXY_USERNAME: Final = 43 +INTERNET_OPTION_PROXY_PASSWORD: Final = 44 +INTERNET_OPTION_CONTEXT_VALUE: Final = 45 +INTERNET_OPTION_CONNECT_LIMIT: Final = 46 +INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT: Final = 47 +INTERNET_OPTION_POLICY: Final = 48 +INTERNET_OPTION_DISCONNECTED_TIMEOUT: Final = 49 +INTERNET_OPTION_CONNECTED_STATE: Final = 50 +INTERNET_OPTION_IDLE_STATE: Final = 51 +INTERNET_OPTION_OFFLINE_SEMANTICS: Final = 52 +INTERNET_OPTION_SECONDARY_CACHE_KEY: Final = 53 +INTERNET_OPTION_CALLBACK_FILTER: Final = 54 +INTERNET_OPTION_CONNECT_TIME: Final = 55 +INTERNET_OPTION_SEND_THROUGHPUT: Final = 56 +INTERNET_OPTION_RECEIVE_THROUGHPUT: Final = 57 +INTERNET_OPTION_REQUEST_PRIORITY: Final = 58 +INTERNET_OPTION_HTTP_VERSION: Final = 59 +INTERNET_OPTION_RESET_URLCACHE_SESSION: Final = 60 +INTERNET_OPTION_ERROR_MASK: Final = 62 +INTERNET_OPTION_FROM_CACHE_TIMEOUT: Final = 63 +INTERNET_OPTION_BYPASS_EDITED_ENTRY: Final = 64 +INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO: Final = 67 +INTERNET_OPTION_CODEPAGE: Final = 68 +INTERNET_OPTION_CACHE_TIMESTAMPS: Final = 69 +INTERNET_OPTION_DISABLE_AUTODIAL: Final = 70 +INTERNET_OPTION_MAX_CONNS_PER_SERVER: Final = 73 +INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER: Final = 74 +INTERNET_OPTION_PER_CONNECTION_OPTION: Final = 75 +INTERNET_OPTION_DIGEST_AUTH_UNLOAD: Final = 76 +INTERNET_OPTION_IGNORE_OFFLINE: Final = 77 +INTERNET_OPTION_IDENTITY: Final = 78 +INTERNET_OPTION_REMOVE_IDENTITY: Final = 79 +INTERNET_OPTION_ALTER_IDENTITY: Final = 80 +INTERNET_OPTION_SUPPRESS_BEHAVIOR: Final = 81 +INTERNET_OPTION_AUTODIAL_MODE: Final = 82 +INTERNET_OPTION_AUTODIAL_CONNECTION: Final = 83 +INTERNET_OPTION_CLIENT_CERT_CONTEXT: Final = 84 +INTERNET_OPTION_AUTH_FLAGS: Final = 85 +INTERNET_OPTION_COOKIES_3RD_PARTY: Final = 86 +INTERNET_OPTION_DISABLE_PASSPORT_AUTH: Final = 87 +INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY: Final = 88 +INTERNET_OPTION_EXEMPT_CONNECTION_LIMIT: Final = 89 +INTERNET_OPTION_ENABLE_PASSPORT_AUTH: Final = 90 +INTERNET_OPTION_HIBERNATE_INACTIVE_WORKER_THREADS: Final = 91 +INTERNET_OPTION_ACTIVATE_WORKER_THREADS: Final = 92 +INTERNET_OPTION_RESTORE_WORKER_THREAD_DEFAULTS: Final = 93 +INTERNET_OPTION_SOCKET_SEND_BUFFER_LENGTH: Final = 94 +INTERNET_OPTION_PROXY_SETTINGS_CHANGED: Final = 95 +INTERNET_FIRST_OPTION: Final = INTERNET_OPTION_CALLBACK +INTERNET_LAST_OPTION: Final = INTERNET_OPTION_PROXY_SETTINGS_CHANGED +INTERNET_PRIORITY_FOREGROUND: Final = 1000 +INTERNET_HANDLE_TYPE_INTERNET: Final = 1 +INTERNET_HANDLE_TYPE_CONNECT_FTP: Final = 2 +INTERNET_HANDLE_TYPE_CONNECT_GOPHER: Final = 3 +INTERNET_HANDLE_TYPE_CONNECT_HTTP: Final = 4 +INTERNET_HANDLE_TYPE_FTP_FIND: Final = 5 +INTERNET_HANDLE_TYPE_FTP_FIND_HTML: Final = 6 +INTERNET_HANDLE_TYPE_FTP_FILE: Final = 7 +INTERNET_HANDLE_TYPE_FTP_FILE_HTML: Final = 8 +INTERNET_HANDLE_TYPE_GOPHER_FIND: Final = 9 +INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML: Final = 10 +INTERNET_HANDLE_TYPE_GOPHER_FILE: Final = 11 +INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML: Final = 12 +INTERNET_HANDLE_TYPE_HTTP_REQUEST: Final = 13 +INTERNET_HANDLE_TYPE_FILE_REQUEST: Final = 14 +AUTH_FLAG_DISABLE_NEGOTIATE: Final = 0x00000001 +AUTH_FLAG_ENABLE_NEGOTIATE: Final = 0x00000002 +SECURITY_FLAG_SECURE: Final = 0x00000001 +SECURITY_FLAG_STRENGTH_WEAK: Final = 0x10000000 +SECURITY_FLAG_STRENGTH_MEDIUM: Final = 0x40000000 +SECURITY_FLAG_STRENGTH_STRONG: Final = 0x20000000 +SECURITY_FLAG_UNKNOWNBIT: Final = -2147483648 +SECURITY_FLAG_FORTEZZA: Final = 0x08000000 +SECURITY_FLAG_NORMALBITNESS: Final = SECURITY_FLAG_STRENGTH_WEAK +SECURITY_FLAG_SSL: Final = 0x00000002 +SECURITY_FLAG_SSL3: Final = 0x00000004 +SECURITY_FLAG_PCT: Final = 0x00000008 +SECURITY_FLAG_PCT4: Final = 0x00000010 +SECURITY_FLAG_IETFSSL4: Final = 0x00000020 +SECURITY_FLAG_40BIT: Final = SECURITY_FLAG_STRENGTH_WEAK +SECURITY_FLAG_128BIT: Final = SECURITY_FLAG_STRENGTH_STRONG +SECURITY_FLAG_56BIT: Final = SECURITY_FLAG_STRENGTH_MEDIUM +SECURITY_FLAG_IGNORE_REVOCATION: Final = 0x00000080 +SECURITY_FLAG_IGNORE_UNKNOWN_CA: Final = 0x00000100 +SECURITY_FLAG_IGNORE_WRONG_USAGE: Final = 0x00000200 +SECURITY_FLAG_IGNORE_CERT_CN_INVALID: Final = INTERNET_FLAG_IGNORE_CERT_CN_INVALID +SECURITY_FLAG_IGNORE_CERT_DATE_INVALID: Final = INTERNET_FLAG_IGNORE_CERT_DATE_INVALID +SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE: Final = 0x00000200 +SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS: Final = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS +SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP: Final = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP +SECURITY_SET_MASK: Final = 0x00003380 +AUTODIAL_MODE_NEVER: Final = 1 +AUTODIAL_MODE_ALWAYS: Final = 2 +AUTODIAL_MODE_NO_NETWORK_PRESENT: Final = 4 +INTERNET_STATUS_RESOLVING_NAME: Final = 10 +INTERNET_STATUS_NAME_RESOLVED: Final = 11 +INTERNET_STATUS_CONNECTING_TO_SERVER: Final = 20 +INTERNET_STATUS_CONNECTED_TO_SERVER: Final = 21 +INTERNET_STATUS_SENDING_REQUEST: Final = 30 +INTERNET_STATUS_REQUEST_SENT: Final = 31 +INTERNET_STATUS_RECEIVING_RESPONSE: Final = 40 +INTERNET_STATUS_RESPONSE_RECEIVED: Final = 41 +INTERNET_STATUS_CTL_RESPONSE_RECEIVED: Final = 42 +INTERNET_STATUS_PREFETCH: Final = 43 +INTERNET_STATUS_CLOSING_CONNECTION: Final = 50 +INTERNET_STATUS_CONNECTION_CLOSED: Final = 51 +INTERNET_STATUS_HANDLE_CREATED: Final = 60 +INTERNET_STATUS_HANDLE_CLOSING: Final = 70 +INTERNET_STATUS_DETECTING_PROXY: Final = 80 +INTERNET_STATUS_REQUEST_COMPLETE: Final = 100 +INTERNET_STATUS_REDIRECT: Final = 110 +INTERNET_STATUS_INTERMEDIATE_RESPONSE: Final = 120 +INTERNET_STATUS_USER_INPUT_REQUIRED: Final = 140 +INTERNET_STATUS_STATE_CHANGE: Final = 200 +INTERNET_STATUS_COOKIE_SENT: Final = 320 +INTERNET_STATUS_COOKIE_RECEIVED: Final = 321 +INTERNET_STATUS_PRIVACY_IMPACTED: Final = 324 +INTERNET_STATUS_P3P_HEADER: Final = 325 +INTERNET_STATUS_P3P_POLICYREF: Final = 326 +INTERNET_STATUS_COOKIE_HISTORY: Final = 327 +INTERNET_STATE_CONNECTED: Final = 0x00000001 +INTERNET_STATE_DISCONNECTED: Final = 0x00000002 +INTERNET_STATE_DISCONNECTED_BY_USER: Final = 0x00000010 +INTERNET_STATE_IDLE: Final = 0x00000100 +INTERNET_STATE_BUSY: Final = 0x00000200 +FTP_TRANSFER_TYPE_UNKNOWN: Final = 0x00000000 +FTP_TRANSFER_TYPE_ASCII: Final = 0x00000001 +FTP_TRANSFER_TYPE_BINARY: Final = 0x00000002 +FTP_TRANSFER_TYPE_MASK: Final = 0x00000003 +MAX_GOPHER_DISPLAY_TEXT: Final = 128 +MAX_GOPHER_SELECTOR_TEXT: Final = 256 +MAX_GOPHER_HOST_NAME: Final = INTERNET_MAX_HOST_NAME_LENGTH +MAX_GOPHER_LOCATOR_LENGTH: Final = 653 +GOPHER_TYPE_TEXT_FILE: Final = 0x00000001 +GOPHER_TYPE_DIRECTORY: Final = 0x00000002 +GOPHER_TYPE_CSO: Final = 0x00000004 +GOPHER_TYPE_ERROR: Final = 0x00000008 +GOPHER_TYPE_MAC_BINHEX: Final = 0x00000010 +GOPHER_TYPE_DOS_ARCHIVE: Final = 0x00000020 +GOPHER_TYPE_UNIX_UUENCODED: Final = 0x00000040 +GOPHER_TYPE_INDEX_SERVER: Final = 0x00000080 +GOPHER_TYPE_TELNET: Final = 0x00000100 +GOPHER_TYPE_BINARY: Final = 0x00000200 +GOPHER_TYPE_REDUNDANT: Final = 0x00000400 +GOPHER_TYPE_TN3270: Final = 0x00000800 +GOPHER_TYPE_GIF: Final = 0x00001000 +GOPHER_TYPE_IMAGE: Final = 0x00002000 +GOPHER_TYPE_BITMAP: Final = 0x00004000 +GOPHER_TYPE_MOVIE: Final = 0x00008000 +GOPHER_TYPE_SOUND: Final = 0x00010000 +GOPHER_TYPE_HTML: Final = 0x00020000 +GOPHER_TYPE_PDF: Final = 0x00040000 +GOPHER_TYPE_CALENDAR: Final = 0x00080000 +GOPHER_TYPE_INLINE: Final = 0x00100000 +GOPHER_TYPE_UNKNOWN: Final = 0x20000000 +GOPHER_TYPE_ASK: Final = 0x40000000 +GOPHER_TYPE_GOPHER_PLUS: Final = -2147483648 +GOPHER_TYPE_FILE_MASK: Final = 0x001FF271 +MAX_GOPHER_CATEGORY_NAME: Final = 128 +MAX_GOPHER_ATTRIBUTE_NAME: Final = 128 +MIN_GOPHER_ATTRIBUTE_LENGTH: Final = 256 +GOPHER_ATTRIBUTE_ID_BASE: Final = -0x54333400 +GOPHER_CATEGORY_ID_ALL: Final = -0x543333FF +GOPHER_CATEGORY_ID_INFO: Final = -0x543333FE +GOPHER_CATEGORY_ID_ADMIN: Final = -0x543333FD +GOPHER_CATEGORY_ID_VIEWS: Final = -0x543333FC +GOPHER_CATEGORY_ID_ABSTRACT: Final = -0x543333FB +GOPHER_CATEGORY_ID_VERONICA: Final = -0x543333FA +GOPHER_CATEGORY_ID_ASK: Final = -0x543333F9 +GOPHER_CATEGORY_ID_UNKNOWN: Final = -0x543333F8 +GOPHER_ATTRIBUTE_ID_ALL: Final = -0x543333F7 +GOPHER_ATTRIBUTE_ID_ADMIN: Final = -0x543333F6 +GOPHER_ATTRIBUTE_ID_MOD_DATE: Final = -0x543333F5 +GOPHER_ATTRIBUTE_ID_TTL: Final = -0x543333F4 +GOPHER_ATTRIBUTE_ID_SCORE: Final = -0x543333F3 +GOPHER_ATTRIBUTE_ID_RANGE: Final = -0x543333F2 +GOPHER_ATTRIBUTE_ID_SITE: Final = -0x543333F1 +GOPHER_ATTRIBUTE_ID_ORG: Final = -0x543333F0 +GOPHER_ATTRIBUTE_ID_LOCATION: Final = -0x543333EF +GOPHER_ATTRIBUTE_ID_GEOG: Final = -0x543333EE +GOPHER_ATTRIBUTE_ID_TIMEZONE: Final = -0x543333ED +GOPHER_ATTRIBUTE_ID_PROVIDER: Final = -0x543333EC +GOPHER_ATTRIBUTE_ID_VERSION: Final = -0x543333EB +GOPHER_ATTRIBUTE_ID_ABSTRACT: Final = -0x543333EA +GOPHER_ATTRIBUTE_ID_VIEW: Final = -0x543333E9 +GOPHER_ATTRIBUTE_ID_TREEWALK: Final = -0x543333E8 +GOPHER_ATTRIBUTE_ID_UNKNOWN: Final = -0x543333E7 +HTTP_MAJOR_VERSION: Final = 1 +HTTP_MINOR_VERSION: Final = 0 +HTTP_VERSIONA: Final = "HTTP/1.0" +HTTP_VERSION: Final = HTTP_VERSIONA +HTTP_QUERY_MIME_VERSION: Final = 0 +HTTP_QUERY_CONTENT_TYPE: Final = 1 +HTTP_QUERY_CONTENT_TRANSFER_ENCODING: Final = 2 +HTTP_QUERY_CONTENT_ID: Final = 3 +HTTP_QUERY_CONTENT_DESCRIPTION: Final = 4 +HTTP_QUERY_CONTENT_LENGTH: Final = 5 +HTTP_QUERY_CONTENT_LANGUAGE: Final = 6 +HTTP_QUERY_ALLOW: Final = 7 +HTTP_QUERY_PUBLIC: Final = 8 +HTTP_QUERY_DATE: Final = 9 +HTTP_QUERY_EXPIRES: Final = 10 +HTTP_QUERY_LAST_MODIFIED: Final = 11 +HTTP_QUERY_MESSAGE_ID: Final = 12 +HTTP_QUERY_URI: Final = 13 +HTTP_QUERY_DERIVED_FROM: Final = 14 +HTTP_QUERY_COST: Final = 15 +HTTP_QUERY_LINK: Final = 16 +HTTP_QUERY_PRAGMA: Final = 17 +HTTP_QUERY_VERSION: Final = 18 +HTTP_QUERY_STATUS_CODE: Final = 19 +HTTP_QUERY_STATUS_TEXT: Final = 20 +HTTP_QUERY_RAW_HEADERS: Final = 21 +HTTP_QUERY_RAW_HEADERS_CRLF: Final = 22 +HTTP_QUERY_CONNECTION: Final = 23 +HTTP_QUERY_ACCEPT: Final = 24 +HTTP_QUERY_ACCEPT_CHARSET: Final = 25 +HTTP_QUERY_ACCEPT_ENCODING: Final = 26 +HTTP_QUERY_ACCEPT_LANGUAGE: Final = 27 +HTTP_QUERY_AUTHORIZATION: Final = 28 +HTTP_QUERY_CONTENT_ENCODING: Final = 29 +HTTP_QUERY_FORWARDED: Final = 30 +HTTP_QUERY_FROM: Final = 31 +HTTP_QUERY_IF_MODIFIED_SINCE: Final = 32 +HTTP_QUERY_LOCATION: Final = 33 +HTTP_QUERY_ORIG_URI: Final = 34 +HTTP_QUERY_REFERER: Final = 35 +HTTP_QUERY_RETRY_AFTER: Final = 36 +HTTP_QUERY_SERVER: Final = 37 +HTTP_QUERY_TITLE: Final = 38 +HTTP_QUERY_USER_AGENT: Final = 39 +HTTP_QUERY_WWW_AUTHENTICATE: Final = 40 +HTTP_QUERY_PROXY_AUTHENTICATE: Final = 41 +HTTP_QUERY_ACCEPT_RANGES: Final = 42 +HTTP_QUERY_SET_COOKIE: Final = 43 +HTTP_QUERY_COOKIE: Final = 44 +HTTP_QUERY_REQUEST_METHOD: Final = 45 +HTTP_QUERY_REFRESH: Final = 46 +HTTP_QUERY_CONTENT_DISPOSITION: Final = 47 +HTTP_QUERY_AGE: Final = 48 +HTTP_QUERY_CACHE_CONTROL: Final = 49 +HTTP_QUERY_CONTENT_BASE: Final = 50 +HTTP_QUERY_CONTENT_LOCATION: Final = 51 +HTTP_QUERY_CONTENT_MD5: Final = 52 +HTTP_QUERY_CONTENT_RANGE: Final = 53 +HTTP_QUERY_ETAG: Final = 54 +HTTP_QUERY_HOST: Final = 55 +HTTP_QUERY_IF_MATCH: Final = 56 +HTTP_QUERY_IF_NONE_MATCH: Final = 57 +HTTP_QUERY_IF_RANGE: Final = 58 +HTTP_QUERY_IF_UNMODIFIED_SINCE: Final = 59 +HTTP_QUERY_MAX_FORWARDS: Final = 60 +HTTP_QUERY_PROXY_AUTHORIZATION: Final = 61 +HTTP_QUERY_RANGE: Final = 62 +HTTP_QUERY_TRANSFER_ENCODING: Final = 63 +HTTP_QUERY_UPGRADE: Final = 64 +HTTP_QUERY_VARY: Final = 65 +HTTP_QUERY_VIA: Final = 66 +HTTP_QUERY_WARNING: Final = 67 +HTTP_QUERY_EXPECT: Final = 68 +HTTP_QUERY_PROXY_CONNECTION: Final = 69 +HTTP_QUERY_UNLESS_MODIFIED_SINCE: Final = 70 +HTTP_QUERY_ECHO_REQUEST: Final = 71 +HTTP_QUERY_ECHO_REPLY: Final = 72 +HTTP_QUERY_ECHO_HEADERS: Final = 73 +HTTP_QUERY_ECHO_HEADERS_CRLF: Final = 74 +HTTP_QUERY_PROXY_SUPPORT: Final = 75 +HTTP_QUERY_AUTHENTICATION_INFO: Final = 76 +HTTP_QUERY_PASSPORT_URLS: Final = 77 +HTTP_QUERY_PASSPORT_CONFIG: Final = 78 +HTTP_QUERY_MAX: Final = 78 +HTTP_QUERY_CUSTOM: Final = 65535 +HTTP_QUERY_FLAG_REQUEST_HEADERS: Final = -2147483648 +HTTP_QUERY_FLAG_SYSTEMTIME: Final = 0x40000000 +HTTP_QUERY_FLAG_NUMBER: Final = 0x20000000 +HTTP_QUERY_FLAG_COALESCE: Final = 0x10000000 +HTTP_QUERY_MODIFIER_FLAGS_MASK: Final = -0x10000000 +HTTP_QUERY_HEADER_MASK: Final = 0xFFFFFFF +HTTP_STATUS_CONTINUE: Final = 100 +HTTP_STATUS_SWITCH_PROTOCOLS: Final = 101 +HTTP_STATUS_OK: Final = 200 +HTTP_STATUS_CREATED: Final = 201 +HTTP_STATUS_ACCEPTED: Final = 202 +HTTP_STATUS_PARTIAL: Final = 203 +HTTP_STATUS_NO_CONTENT: Final = 204 +HTTP_STATUS_RESET_CONTENT: Final = 205 +HTTP_STATUS_PARTIAL_CONTENT: Final = 206 +HTTP_STATUS_WEBDAV_MULTI_STATUS: Final = 207 +HTTP_STATUS_AMBIGUOUS: Final = 300 +HTTP_STATUS_MOVED: Final = 301 +HTTP_STATUS_REDIRECT: Final = 302 +HTTP_STATUS_REDIRECT_METHOD: Final = 303 +HTTP_STATUS_NOT_MODIFIED: Final = 304 +HTTP_STATUS_USE_PROXY: Final = 305 +HTTP_STATUS_REDIRECT_KEEP_VERB: Final = 307 +HTTP_STATUS_BAD_REQUEST: Final = 400 +HTTP_STATUS_DENIED: Final = 401 +HTTP_STATUS_PAYMENT_REQ: Final = 402 +HTTP_STATUS_FORBIDDEN: Final = 403 +HTTP_STATUS_NOT_FOUND: Final = 404 +HTTP_STATUS_BAD_METHOD: Final = 405 +HTTP_STATUS_NONE_ACCEPTABLE: Final = 406 +HTTP_STATUS_PROXY_AUTH_REQ: Final = 407 +HTTP_STATUS_REQUEST_TIMEOUT: Final = 408 +HTTP_STATUS_CONFLICT: Final = 409 +HTTP_STATUS_GONE: Final = 410 +HTTP_STATUS_LENGTH_REQUIRED: Final = 411 +HTTP_STATUS_PRECOND_FAILED: Final = 412 +HTTP_STATUS_REQUEST_TOO_LARGE: Final = 413 +HTTP_STATUS_URI_TOO_LONG: Final = 414 +HTTP_STATUS_UNSUPPORTED_MEDIA: Final = 415 +HTTP_STATUS_RETRY_WITH: Final = 449 +HTTP_STATUS_SERVER_ERROR: Final = 500 +HTTP_STATUS_NOT_SUPPORTED: Final = 501 +HTTP_STATUS_BAD_GATEWAY: Final = 502 +HTTP_STATUS_SERVICE_UNAVAIL: Final = 503 +HTTP_STATUS_GATEWAY_TIMEOUT: Final = 504 +HTTP_STATUS_VERSION_NOT_SUP: Final = 505 +HTTP_STATUS_FIRST: Final = HTTP_STATUS_CONTINUE +HTTP_STATUS_LAST: Final = HTTP_STATUS_VERSION_NOT_SUP +HTTP_ADDREQ_INDEX_MASK: Final = 0x0000FFFF +HTTP_ADDREQ_FLAGS_MASK: Final = -65536 +HTTP_ADDREQ_FLAG_ADD_IF_NEW: Final = 0x10000000 +HTTP_ADDREQ_FLAG_ADD: Final = 0x20000000 +HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA: Final = 0x40000000 +HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON: Final = 0x01000000 +HTTP_ADDREQ_FLAG_COALESCE: Final = HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA +HTTP_ADDREQ_FLAG_REPLACE: Final = -2147483648 +HSR_ASYNC: Final = WININET_API_FLAG_ASYNC +HSR_SYNC: Final = WININET_API_FLAG_SYNC +HSR_USE_CONTEXT: Final = WININET_API_FLAG_USE_CONTEXT +HSR_INITIATE: Final = 0x00000008 +HSR_DOWNLOAD: Final = 0x00000010 +HSR_CHUNKED: Final = 0x00000020 +INTERNET_COOKIE_IS_SECURE: Final = 0x01 +INTERNET_COOKIE_IS_SESSION: Final = 0x02 +INTERNET_COOKIE_THIRD_PARTY: Final = 0x10 +INTERNET_COOKIE_PROMPT_REQUIRED: Final = 0x20 +INTERNET_COOKIE_EVALUATE_P3P: Final = 0x40 +INTERNET_COOKIE_APPLY_P3P: Final = 0x80 +INTERNET_COOKIE_P3P_ENABLED: Final = 0x100 +INTERNET_COOKIE_IS_RESTRICTED: Final = 0x200 +INTERNET_COOKIE_IE6: Final = 0x400 +INTERNET_COOKIE_IS_LEGACY: Final = 0x800 +FLAG_ICC_FORCE_CONNECTION: Final = 0x00000001 +FLAGS_ERROR_UI_FILTER_FOR_ERRORS: Final = 0x01 +FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS: Final = 0x02 +FLAGS_ERROR_UI_FLAGS_GENERATE_DATA: Final = 0x04 +FLAGS_ERROR_UI_FLAGS_NO_UI: Final = 0x08 +FLAGS_ERROR_UI_SERIALIZE_DIALOGS: Final = 0x10 +INTERNET_ERROR_BASE: Final = 12000 +ERROR_INTERNET_OUT_OF_HANDLES: Final = 12001 +ERROR_INTERNET_TIMEOUT: Final = 12002 +ERROR_INTERNET_EXTENDED_ERROR: Final = 12003 +ERROR_INTERNET_INTERNAL_ERROR: Final = 12004 +ERROR_INTERNET_INVALID_URL: Final = 12005 +ERROR_INTERNET_UNRECOGNIZED_SCHEME: Final = 12006 +ERROR_INTERNET_NAME_NOT_RESOLVED: Final = 12007 +ERROR_INTERNET_PROTOCOL_NOT_FOUND: Final = 12008 +ERROR_INTERNET_INVALID_OPTION: Final = 12009 +ERROR_INTERNET_BAD_OPTION_LENGTH: Final = 12010 +ERROR_INTERNET_OPTION_NOT_SETTABLE: Final = 12011 +ERROR_INTERNET_SHUTDOWN: Final = 12012 +ERROR_INTERNET_INCORRECT_USER_NAME: Final = 12013 +ERROR_INTERNET_INCORRECT_PASSWORD: Final = 12014 +ERROR_INTERNET_LOGIN_FAILURE: Final = 12015 +ERROR_INTERNET_INVALID_OPERATION: Final = 12016 +ERROR_INTERNET_OPERATION_CANCELLED: Final = 12017 +ERROR_INTERNET_INCORRECT_HANDLE_TYPE: Final = 12018 +ERROR_INTERNET_INCORRECT_HANDLE_STATE: Final = 12019 +ERROR_INTERNET_NOT_PROXY_REQUEST: Final = 12020 +ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND: Final = 12021 +ERROR_INTERNET_BAD_REGISTRY_PARAMETER: Final = 12022 +ERROR_INTERNET_NO_DIRECT_ACCESS: Final = 12023 +ERROR_INTERNET_NO_CONTEXT: Final = 12024 +ERROR_INTERNET_NO_CALLBACK: Final = 12025 +ERROR_INTERNET_REQUEST_PENDING: Final = 12026 +ERROR_INTERNET_INCORRECT_FORMAT: Final = 12027 +ERROR_INTERNET_ITEM_NOT_FOUND: Final = 12028 +ERROR_INTERNET_CANNOT_CONNECT: Final = 12029 +ERROR_INTERNET_CONNECTION_ABORTED: Final = 12030 +ERROR_INTERNET_CONNECTION_RESET: Final = 12031 +ERROR_INTERNET_FORCE_RETRY: Final = 12032 +ERROR_INTERNET_INVALID_PROXY_REQUEST: Final = 12033 +ERROR_INTERNET_NEED_UI: Final = 12034 +ERROR_INTERNET_HANDLE_EXISTS: Final = 12036 +ERROR_INTERNET_SEC_CERT_DATE_INVALID: Final = 12037 +ERROR_INTERNET_SEC_CERT_CN_INVALID: Final = 12038 +ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR: Final = 12039 +ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR: Final = 12040 +ERROR_INTERNET_MIXED_SECURITY: Final = 12041 +ERROR_INTERNET_CHG_POST_IS_NON_SECURE: Final = 12042 +ERROR_INTERNET_POST_IS_NON_SECURE: Final = 12043 +ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED: Final = 12044 +ERROR_INTERNET_INVALID_CA: Final = 12045 +ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP: Final = 12046 +ERROR_INTERNET_ASYNC_THREAD_FAILED: Final = 12047 +ERROR_INTERNET_REDIRECT_SCHEME_CHANGE: Final = 12048 +ERROR_INTERNET_DIALOG_PENDING: Final = 12049 +ERROR_INTERNET_RETRY_DIALOG: Final = 12050 +ERROR_INTERNET_HTTPS_HTTP_SUBMIT_REDIR: Final = 12052 +ERROR_INTERNET_INSERT_CDROM: Final = 12053 +ERROR_INTERNET_FORTEZZA_LOGIN_NEEDED: Final = 12054 +ERROR_INTERNET_SEC_CERT_ERRORS: Final = 12055 +ERROR_INTERNET_SEC_CERT_NO_REV: Final = 12056 +ERROR_INTERNET_SEC_CERT_REV_FAILED: Final = 12057 +ERROR_FTP_TRANSFER_IN_PROGRESS: Final = 12110 +ERROR_FTP_DROPPED: Final = 12111 +ERROR_FTP_NO_PASSIVE_MODE: Final = 12112 +ERROR_GOPHER_PROTOCOL_ERROR: Final = 12130 +ERROR_GOPHER_NOT_FILE: Final = 12131 +ERROR_GOPHER_DATA_ERROR: Final = 12132 +ERROR_GOPHER_END_OF_DATA: Final = 12133 +ERROR_GOPHER_INVALID_LOCATOR: Final = 12134 +ERROR_GOPHER_INCORRECT_LOCATOR_TYPE: Final = 12135 +ERROR_GOPHER_NOT_GOPHER_PLUS: Final = 12136 +ERROR_GOPHER_ATTRIBUTE_NOT_FOUND: Final = 12137 +ERROR_GOPHER_UNKNOWN_LOCATOR: Final = 12138 +ERROR_HTTP_HEADER_NOT_FOUND: Final = 12150 +ERROR_HTTP_DOWNLEVEL_SERVER: Final = 12151 +ERROR_HTTP_INVALID_SERVER_RESPONSE: Final = 12152 +ERROR_HTTP_INVALID_HEADER: Final = 12153 +ERROR_HTTP_INVALID_QUERY_REQUEST: Final = 12154 +ERROR_HTTP_HEADER_ALREADY_EXISTS: Final = 12155 +ERROR_HTTP_REDIRECT_FAILED: Final = 12156 +ERROR_INTERNET_SECURITY_CHANNEL_ERROR: Final = 12157 +ERROR_INTERNET_UNABLE_TO_CACHE_FILE: Final = 12158 +ERROR_INTERNET_TCPIP_NOT_INSTALLED: Final = 12159 +ERROR_HTTP_NOT_REDIRECTED: Final = 12160 +ERROR_HTTP_COOKIE_NEEDS_CONFIRMATION: Final = 12161 +ERROR_HTTP_COOKIE_DECLINED: Final = 12162 +ERROR_INTERNET_DISCONNECTED: Final = 12163 +ERROR_INTERNET_SERVER_UNREACHABLE: Final = 12164 +ERROR_INTERNET_PROXY_SERVER_UNREACHABLE: Final = 12165 +ERROR_INTERNET_BAD_AUTO_PROXY_SCRIPT: Final = 12166 +ERROR_INTERNET_UNABLE_TO_DOWNLOAD_SCRIPT: Final = 12167 +ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION: Final = 12168 +ERROR_INTERNET_SEC_INVALID_CERT: Final = 12169 +ERROR_INTERNET_SEC_CERT_REVOKED: Final = 12170 +ERROR_INTERNET_FAILED_DUETOSECURITYCHECK: Final = 12171 +ERROR_INTERNET_NOT_INITIALIZED: Final = 12172 +ERROR_INTERNET_NEED_MSN_SSPI_PKG: Final = 12173 +ERROR_INTERNET_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: Final = 12174 +INTERNET_ERROR_LAST: Final = ERROR_INTERNET_LOGIN_FAILURE_DISPLAY_ENTITY_BODY +NORMAL_CACHE_ENTRY: Final = 0x00000001 +STICKY_CACHE_ENTRY: Final = 0x00000004 +EDITED_CACHE_ENTRY: Final = 0x00000008 +TRACK_OFFLINE_CACHE_ENTRY: Final = 0x00000010 +TRACK_ONLINE_CACHE_ENTRY: Final = 0x00000020 +SPARSE_CACHE_ENTRY: Final = 0x00010000 +COOKIE_CACHE_ENTRY: Final = 0x00100000 +URLHISTORY_CACHE_ENTRY: Final = 0x00200000 +URLCACHE_FIND_DEFAULT_FILTER: Final = 0x300035 +CACHEGROUP_ATTRIBUTE_GET_ALL: Final = -1 +CACHEGROUP_ATTRIBUTE_BASIC: Final = 0x00000001 +CACHEGROUP_ATTRIBUTE_FLAG: Final = 0x00000002 +CACHEGROUP_ATTRIBUTE_TYPE: Final = 0x00000004 +CACHEGROUP_ATTRIBUTE_QUOTA: Final = 0x00000008 +CACHEGROUP_ATTRIBUTE_GROUPNAME: Final = 0x00000010 +CACHEGROUP_ATTRIBUTE_STORAGE: Final = 0x00000020 +CACHEGROUP_FLAG_NONPURGEABLE: Final = 0x00000001 +CACHEGROUP_FLAG_GIDONLY: Final = 0x00000004 +CACHEGROUP_FLAG_FLUSHURL_ONDELETE: Final = 0x00000002 +CACHEGROUP_SEARCH_ALL: Final = 0x00000000 +CACHEGROUP_SEARCH_BYURL: Final = 0x00000001 +CACHEGROUP_TYPE_INVALID: Final = 0x00000001 +CACHEGROUP_READWRITE_MASK: Final = 60 +GROUPNAME_MAX_LENGTH: Final = 120 +GROUP_OWNER_STORAGE_SIZE: Final = 4 +CACHE_ENTRY_ATTRIBUTE_FC: Final = 0x00000004 +CACHE_ENTRY_HITRATE_FC: Final = 0x00000010 +CACHE_ENTRY_MODTIME_FC: Final = 0x00000040 +CACHE_ENTRY_EXPTIME_FC: Final = 0x00000080 +CACHE_ENTRY_ACCTIME_FC: Final = 0x00000100 +CACHE_ENTRY_SYNCTIME_FC: Final = 0x00000200 +CACHE_ENTRY_HEADERINFO_FC: Final = 0x00000400 +CACHE_ENTRY_EXEMPT_DELTA_FC: Final = 0x00000800 +INTERNET_CACHE_GROUP_ADD: Final = 0 +INTERNET_CACHE_GROUP_REMOVE: Final = 1 +INTERNET_DIAL_FORCE_PROMPT: Final = 0x2000 +INTERNET_DIAL_SHOW_OFFLINE: Final = 0x4000 +INTERNET_DIAL_UNATTENDED: Final = 0x8000 +INTERENT_GOONLINE_REFRESH: Final = 0x00000001 +INTERENT_GOONLINE_MASK: Final = 0x00000001 +INTERNET_AUTODIAL_FORCE_ONLINE: Final = 1 +INTERNET_AUTODIAL_FORCE_UNATTENDED: Final = 2 +INTERNET_AUTODIAL_FAILIFSECURITYCHECK: Final = 4 +INTERNET_AUTODIAL_OVERRIDE_NET_PRESENT: Final = 8 +INTERNET_AUTODIAL_FLAGS_MASK: Final = 15 +PROXY_AUTO_DETECT_TYPE_DHCP: Final = 1 +PROXY_AUTO_DETECT_TYPE_DNS_A: Final = 2 +INTERNET_CONNECTION_MODEM: Final = 0x01 +INTERNET_CONNECTION_LAN: Final = 0x02 +INTERNET_CONNECTION_PROXY: Final = 0x04 +INTERNET_CONNECTION_MODEM_BUSY: Final = 0x08 +INTERNET_RAS_INSTALLED: Final = 0x10 +INTERNET_CONNECTION_OFFLINE: Final = 0x20 +INTERNET_CONNECTION_CONFIGURED: Final = 0x40 +INTERNET_CUSTOMDIAL_CONNECT: Final = 0 +INTERNET_CUSTOMDIAL_UNATTENDED: Final = 1 +INTERNET_CUSTOMDIAL_DISCONNECT: Final = 2 +INTERNET_CUSTOMDIAL_SHOWOFFLINE: Final = 4 +INTERNET_CUSTOMDIAL_SAFE_FOR_UNATTENDED: Final = 1 +INTERNET_CUSTOMDIAL_WILL_SUPPLY_STATE: Final = 2 +INTERNET_CUSTOMDIAL_CAN_HANGUP: Final = 4 +INTERNET_DIALSTATE_DISCONNECTED: Final = 1 +INTERNET_IDENTITY_FLAG_PRIVATE_CACHE: Final = 0x01 +INTERNET_IDENTITY_FLAG_SHARED_CACHE: Final = 0x02 +INTERNET_IDENTITY_FLAG_CLEAR_DATA: Final = 0x04 +INTERNET_IDENTITY_FLAG_CLEAR_COOKIES: Final = 0x08 +INTERNET_IDENTITY_FLAG_CLEAR_HISTORY: Final = 0x10 +INTERNET_IDENTITY_FLAG_CLEAR_CONTENT: Final = 0x20 +INTERNET_SUPPRESS_RESET_ALL: Final = 0x00 +INTERNET_SUPPRESS_COOKIE_POLICY: Final = 0x01 +INTERNET_SUPPRESS_COOKIE_POLICY_RESET: Final = 0x02 +PRIVACY_TEMPLATE_NO_COOKIES: Final = 0 +PRIVACY_TEMPLATE_HIGH: Final = 1 +PRIVACY_TEMPLATE_MEDIUM_HIGH: Final = 2 +PRIVACY_TEMPLATE_MEDIUM: Final = 3 +PRIVACY_TEMPLATE_MEDIUM_LOW: Final = 4 +PRIVACY_TEMPLATE_LOW: Final = 5 +PRIVACY_TEMPLATE_CUSTOM: Final = 100 +PRIVACY_TEMPLATE_ADVANCED: Final = 101 +PRIVACY_TEMPLATE_MAX: Final = PRIVACY_TEMPLATE_LOW +PRIVACY_TYPE_FIRST_PARTY: Final = 0 +PRIVACY_TYPE_THIRD_PARTY: Final = 1 +WINHTTP_FLAG_ASYNC: Final = 0x10000000 +WINHTTP_FLAG_SECURE: Final = 0x00800000 +WINHTTP_FLAG_ESCAPE_PERCENT: Final = 0x00000004 +WINHTTP_FLAG_NULL_CODEPAGE: Final = 0x00000008 +WINHTTP_FLAG_BYPASS_PROXY_CACHE: Final = 0x00000100 +WINHTTP_FLAG_REFRESH: Final = WINHTTP_FLAG_BYPASS_PROXY_CACHE +WINHTTP_FLAG_ESCAPE_DISABLE: Final = 0x00000040 +WINHTTP_FLAG_ESCAPE_DISABLE_QUERY: Final = 0x00000080 +INTERNET_SCHEME_HTTP: Final = 1 +INTERNET_SCHEME_HTTPS: Final = 2 +WINHTTP_AUTOPROXY_AUTO_DETECT: Final = 0x00000001 +WINHTTP_AUTOPROXY_CONFIG_URL: Final = 0x00000002 +WINHTTP_AUTOPROXY_RUN_INPROCESS: Final = 0x00010000 +WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY: Final = 0x00020000 +WINHTTP_AUTO_DETECT_TYPE_DHCP: Final = 0x00000001 +WINHTTP_AUTO_DETECT_TYPE_DNS_A: Final = 0x00000002 +WINHTTP_TIME_FORMAT_BUFSIZE: Final = 62 +WINHTTP_ACCESS_TYPE_DEFAULT_PROXY: Final = 0 +WINHTTP_ACCESS_TYPE_NO_PROXY: Final = 1 +WINHTTP_ACCESS_TYPE_NAMED_PROXY: Final = 3 +WINHTTP_OPTION_CALLBACK: Final = 1 +WINHTTP_OPTION_RESOLVE_TIMEOUT: Final = 2 +WINHTTP_OPTION_CONNECT_TIMEOUT: Final = 3 +WINHTTP_OPTION_CONNECT_RETRIES: Final = 4 +WINHTTP_OPTION_SEND_TIMEOUT: Final = 5 +WINHTTP_OPTION_RECEIVE_TIMEOUT: Final = 6 +WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT: Final = 7 +WINHTTP_OPTION_HANDLE_TYPE: Final = 9 +WINHTTP_OPTION_READ_BUFFER_SIZE: Final = 12 +WINHTTP_OPTION_WRITE_BUFFER_SIZE: Final = 13 +WINHTTP_OPTION_PARENT_HANDLE: Final = 21 +WINHTTP_OPTION_EXTENDED_ERROR: Final = 24 +WINHTTP_OPTION_SECURITY_FLAGS: Final = 31 +WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT: Final = 32 +WINHTTP_OPTION_URL: Final = 34 +WINHTTP_OPTION_SECURITY_KEY_BITNESS: Final = 36 +WINHTTP_OPTION_PROXY: Final = 38 +WINHTTP_OPTION_USER_AGENT: Final = 41 +WINHTTP_OPTION_CONTEXT_VALUE: Final = 45 +WINHTTP_OPTION_CLIENT_CERT_CONTEXT: Final = 47 +WINHTTP_OPTION_REQUEST_PRIORITY: Final = 58 +WINHTTP_OPTION_HTTP_VERSION: Final = 59 +WINHTTP_OPTION_DISABLE_FEATURE: Final = 63 +WINHTTP_OPTION_CODEPAGE: Final = 68 +WINHTTP_OPTION_MAX_CONNS_PER_SERVER: Final = 73 +WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER: Final = 74 +WINHTTP_OPTION_AUTOLOGON_POLICY: Final = 77 +WINHTTP_OPTION_SERVER_CERT_CONTEXT: Final = 78 +WINHTTP_OPTION_ENABLE_FEATURE: Final = 79 +WINHTTP_OPTION_WORKER_THREAD_COUNT: Final = 80 +WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT: Final = 81 +WINHTTP_OPTION_PASSPORT_COBRANDING_URL: Final = 82 +WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH: Final = 83 +WINHTTP_OPTION_SECURE_PROTOCOLS: Final = 84 +WINHTTP_OPTION_ENABLETRACING: Final = 85 +WINHTTP_OPTION_PASSPORT_SIGN_OUT: Final = 86 +WINHTTP_OPTION_PASSPORT_RETURN_URL: Final = 87 +WINHTTP_OPTION_REDIRECT_POLICY: Final = 88 +WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS: Final = 89 +WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE: Final = 90 +WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE: Final = 91 +WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE: Final = 92 +WINHTTP_OPTION_CONNECTION_INFO: Final = 93 +WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST: Final = 94 +WINHTTP_OPTION_SPN: Final = 96 +WINHTTP_OPTION_GLOBAL_PROXY_CREDS: Final = 97 +WINHTTP_OPTION_GLOBAL_SERVER_CREDS: Final = 98 +WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT: Final = 99 +WINHTTP_OPTION_REJECT_USERPWD_IN_URL: Final = 100 +WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS: Final = 101 +WINHTTP_LAST_OPTION: Final = WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS +WINHTTP_OPTION_USERNAME: Final = 0x1000 +WINHTTP_OPTION_PASSWORD: Final = 0x1001 +WINHTTP_OPTION_PROXY_USERNAME: Final = 0x1002 +WINHTTP_OPTION_PROXY_PASSWORD: Final = 0x1003 +WINHTTP_CONNS_PER_SERVER_UNLIMITED: Final = -1 +WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM: Final = 0 +WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW: Final = 1 +WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH: Final = 2 +WINHTTP_AUTOLOGON_SECURITY_LEVEL_DEFAULT: Final = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM +WINHTTP_OPTION_REDIRECT_POLICY_NEVER: Final = 0 +WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP: Final = 1 +WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS: Final = 2 +WINHTTP_OPTION_REDIRECT_POLICY_LAST: Final = WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS +WINHTTP_OPTION_REDIRECT_POLICY_DEFAULT: Final = WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP +WINHTTP_DISABLE_PASSPORT_AUTH: Final = 0x00000000 +WINHTTP_ENABLE_PASSPORT_AUTH: Final = 0x10000000 +WINHTTP_DISABLE_PASSPORT_KEYRING: Final = 0x20000000 +WINHTTP_ENABLE_PASSPORT_KEYRING: Final = 0x40000000 +WINHTTP_DISABLE_COOKIES: Final = 0x00000001 +WINHTTP_DISABLE_REDIRECTS: Final = 0x00000002 +WINHTTP_DISABLE_AUTHENTICATION: Final = 0x00000004 +WINHTTP_DISABLE_KEEP_ALIVE: Final = 0x00000008 +WINHTTP_ENABLE_SSL_REVOCATION: Final = 0x00000001 +WINHTTP_ENABLE_SSL_REVERT_IMPERSONATION: Final = 0x00000002 +WINHTTP_DISABLE_SPN_SERVER_PORT: Final = 0x00000000 +WINHTTP_ENABLE_SPN_SERVER_PORT: Final = 0x00000001 +WINHTTP_OPTION_SPN_MASK: Final = WINHTTP_ENABLE_SPN_SERVER_PORT +WINHTTP_HANDLE_TYPE_SESSION: Final = 1 +WINHTTP_HANDLE_TYPE_CONNECT: Final = 2 +WINHTTP_HANDLE_TYPE_REQUEST: Final = 3 +WINHTTP_AUTH_SCHEME_BASIC: Final = 0x00000001 +WINHTTP_AUTH_SCHEME_NTLM: Final = 0x00000002 +WINHTTP_AUTH_SCHEME_PASSPORT: Final = 0x00000004 +WINHTTP_AUTH_SCHEME_DIGEST: Final = 0x00000008 +WINHTTP_AUTH_SCHEME_NEGOTIATE: Final = 0x00000010 +WINHTTP_AUTH_TARGET_SERVER: Final = 0x00000000 +WINHTTP_AUTH_TARGET_PROXY: Final = 0x00000001 +WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED: Final = 0x00000001 +WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT: Final = 0x00000002 +WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED: Final = 0x00000004 +WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA: Final = 0x00000008 +WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID: Final = 0x00000010 +WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID: Final = 0x00000020 +WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE: Final = 0x00000040 +WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR: Final = -2147483648 +WINHTTP_FLAG_SECURE_PROTOCOL_SSL2: Final = 0x00000008 +WINHTTP_FLAG_SECURE_PROTOCOL_SSL3: Final = 0x00000020 +WINHTTP_FLAG_SECURE_PROTOCOL_TLS1: Final = 0x00000080 +WINHTTP_FLAG_SECURE_PROTOCOL_ALL: Final = 0x000000A8 +WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: Final = 0x00000001 +WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: Final = 0x00000002 +WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: Final = 0x00000004 +WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: Final = 0x00000008 +WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: Final = 0x00000010 +WINHTTP_CALLBACK_STATUS_REQUEST_SENT: Final = 0x00000020 +WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: Final = 0x00000040 +WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: Final = 0x00000080 +WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: Final = 0x00000100 +WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: Final = 0x00000200 +WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: Final = 0x00000400 +WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: Final = 0x00000800 +WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: Final = 0x00001000 +WINHTTP_CALLBACK_STATUS_REDIRECT: Final = 0x00004000 +WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: Final = 0x00008000 +WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: Final = 0x00010000 +WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: Final = 0x00020000 +WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: Final = 0x00040000 +WINHTTP_CALLBACK_STATUS_READ_COMPLETE: Final = 0x00080000 +WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: Final = 0x00100000 +WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: Final = 0x00200000 +WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: Final = 0x00400000 +API_RECEIVE_RESPONSE: Final = 1 +API_QUERY_DATA_AVAILABLE: Final = 2 +API_READ_DATA: Final = 3 +API_WRITE_DATA: Final = 4 +API_SEND_REQUEST: Final = 5 +WINHTTP_CALLBACK_FLAG_RESOLVE_NAME: Final = 3 +WINHTTP_CALLBACK_FLAG_CONNECT_TO_SERVER: Final = 12 +WINHTTP_CALLBACK_FLAG_SEND_REQUEST: Final = 48 +WINHTTP_CALLBACK_FLAG_RECEIVE_RESPONSE: Final = 192 +WINHTTP_CALLBACK_FLAG_CLOSE_CONNECTION: Final = 768 +WINHTTP_CALLBACK_FLAG_HANDLES: Final = 3072 +WINHTTP_CALLBACK_FLAG_DETECTING_PROXY: Final = WINHTTP_CALLBACK_STATUS_DETECTING_PROXY +WINHTTP_CALLBACK_FLAG_REDIRECT: Final = WINHTTP_CALLBACK_STATUS_REDIRECT +WINHTTP_CALLBACK_FLAG_INTERMEDIATE_RESPONSE: Final = WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE +WINHTTP_CALLBACK_FLAG_SECURE_FAILURE: Final = WINHTTP_CALLBACK_STATUS_SECURE_FAILURE +WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE: Final = WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE +WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE: Final = WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE +WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE: Final = WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE +WINHTTP_CALLBACK_FLAG_READ_COMPLETE: Final = WINHTTP_CALLBACK_STATUS_READ_COMPLETE +WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE: Final = WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE +WINHTTP_CALLBACK_FLAG_REQUEST_ERROR: Final = WINHTTP_CALLBACK_STATUS_REQUEST_ERROR +WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS: Final = 0x007E0000 +WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS: Final = -1 +WINHTTP_QUERY_MIME_VERSION: Final = 0 +WINHTTP_QUERY_CONTENT_TYPE: Final = 1 +WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING: Final = 2 +WINHTTP_QUERY_CONTENT_ID: Final = 3 +WINHTTP_QUERY_CONTENT_DESCRIPTION: Final = 4 +WINHTTP_QUERY_CONTENT_LENGTH: Final = 5 +WINHTTP_QUERY_CONTENT_LANGUAGE: Final = 6 +WINHTTP_QUERY_ALLOW: Final = 7 +WINHTTP_QUERY_PUBLIC: Final = 8 +WINHTTP_QUERY_DATE: Final = 9 +WINHTTP_QUERY_EXPIRES: Final = 10 +WINHTTP_QUERY_LAST_MODIFIED: Final = 11 +WINHTTP_QUERY_MESSAGE_ID: Final = 12 +WINHTTP_QUERY_URI: Final = 13 +WINHTTP_QUERY_DERIVED_FROM: Final = 14 +WINHTTP_QUERY_COST: Final = 15 +WINHTTP_QUERY_LINK: Final = 16 +WINHTTP_QUERY_PRAGMA: Final = 17 +WINHTTP_QUERY_VERSION: Final = 18 +WINHTTP_QUERY_STATUS_CODE: Final = 19 +WINHTTP_QUERY_STATUS_TEXT: Final = 20 +WINHTTP_QUERY_RAW_HEADERS: Final = 21 +WINHTTP_QUERY_RAW_HEADERS_CRLF: Final = 22 +WINHTTP_QUERY_CONNECTION: Final = 23 +WINHTTP_QUERY_ACCEPT: Final = 24 +WINHTTP_QUERY_ACCEPT_CHARSET: Final = 25 +WINHTTP_QUERY_ACCEPT_ENCODING: Final = 26 +WINHTTP_QUERY_ACCEPT_LANGUAGE: Final = 27 +WINHTTP_QUERY_AUTHORIZATION: Final = 28 +WINHTTP_QUERY_CONTENT_ENCODING: Final = 29 +WINHTTP_QUERY_FORWARDED: Final = 30 +WINHTTP_QUERY_FROM: Final = 31 +WINHTTP_QUERY_IF_MODIFIED_SINCE: Final = 32 +WINHTTP_QUERY_LOCATION: Final = 33 +WINHTTP_QUERY_ORIG_URI: Final = 34 +WINHTTP_QUERY_REFERER: Final = 35 +WINHTTP_QUERY_RETRY_AFTER: Final = 36 +WINHTTP_QUERY_SERVER: Final = 37 +WINHTTP_QUERY_TITLE: Final = 38 +WINHTTP_QUERY_USER_AGENT: Final = 39 +WINHTTP_QUERY_WWW_AUTHENTICATE: Final = 40 +WINHTTP_QUERY_PROXY_AUTHENTICATE: Final = 41 +WINHTTP_QUERY_ACCEPT_RANGES: Final = 42 +WINHTTP_QUERY_SET_COOKIE: Final = 43 +WINHTTP_QUERY_COOKIE: Final = 44 +WINHTTP_QUERY_REQUEST_METHOD: Final = 45 +WINHTTP_QUERY_REFRESH: Final = 46 +WINHTTP_QUERY_CONTENT_DISPOSITION: Final = 47 +WINHTTP_QUERY_AGE: Final = 48 +WINHTTP_QUERY_CACHE_CONTROL: Final = 49 +WINHTTP_QUERY_CONTENT_BASE: Final = 50 +WINHTTP_QUERY_CONTENT_LOCATION: Final = 51 +WINHTTP_QUERY_CONTENT_MD5: Final = 52 +WINHTTP_QUERY_CONTENT_RANGE: Final = 53 +WINHTTP_QUERY_ETAG: Final = 54 +WINHTTP_QUERY_HOST: Final = 55 +WINHTTP_QUERY_IF_MATCH: Final = 56 +WINHTTP_QUERY_IF_NONE_MATCH: Final = 57 +WINHTTP_QUERY_IF_RANGE: Final = 58 +WINHTTP_QUERY_IF_UNMODIFIED_SINCE: Final = 59 +WINHTTP_QUERY_MAX_FORWARDS: Final = 60 +WINHTTP_QUERY_PROXY_AUTHORIZATION: Final = 61 +WINHTTP_QUERY_RANGE: Final = 62 +WINHTTP_QUERY_TRANSFER_ENCODING: Final = 63 +WINHTTP_QUERY_UPGRADE: Final = 64 +WINHTTP_QUERY_VARY: Final = 65 +WINHTTP_QUERY_VIA: Final = 66 +WINHTTP_QUERY_WARNING: Final = 67 +WINHTTP_QUERY_EXPECT: Final = 68 +WINHTTP_QUERY_PROXY_CONNECTION: Final = 69 +WINHTTP_QUERY_UNLESS_MODIFIED_SINCE: Final = 70 +WINHTTP_QUERY_PROXY_SUPPORT: Final = 75 +WINHTTP_QUERY_AUTHENTICATION_INFO: Final = 76 +WINHTTP_QUERY_PASSPORT_URLS: Final = 77 +WINHTTP_QUERY_PASSPORT_CONFIG: Final = 78 +WINHTTP_QUERY_MAX: Final = 78 +WINHTTP_QUERY_CUSTOM: Final = 65535 +WINHTTP_QUERY_FLAG_REQUEST_HEADERS: Final = -2147483648 +WINHTTP_QUERY_FLAG_SYSTEMTIME: Final = 0x40000000 +WINHTTP_QUERY_FLAG_NUMBER: Final = 0x20000000 +WINHTTP_ADDREQ_INDEX_MASK: Final = 0x0000FFFF +WINHTTP_ADDREQ_FLAGS_MASK: Final = -65536 +WINHTTP_ADDREQ_FLAG_ADD_IF_NEW: Final = 0x10000000 +WINHTTP_ADDREQ_FLAG_ADD: Final = 0x20000000 +WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA: Final = 0x40000000 +WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON: Final = 0x01000000 +WINHTTP_ADDREQ_FLAG_COALESCE: Final = WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA +WINHTTP_ADDREQ_FLAG_REPLACE: Final = -2147483648 +WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH: Final = 0 +WINHTTP_ERROR_BASE: Final = 12000 +ERROR_WINHTTP_OUT_OF_HANDLES: Final = 12001 +ERROR_WINHTTP_TIMEOUT: Final = 12002 +ERROR_WINHTTP_INTERNAL_ERROR: Final = 12004 +ERROR_WINHTTP_INVALID_URL: Final = 12005 +ERROR_WINHTTP_UNRECOGNIZED_SCHEME: Final = 12006 +ERROR_WINHTTP_NAME_NOT_RESOLVED: Final = 12007 +ERROR_WINHTTP_INVALID_OPTION: Final = 12009 +ERROR_WINHTTP_OPTION_NOT_SETTABLE: Final = 12011 +ERROR_WINHTTP_SHUTDOWN: Final = 12012 +ERROR_WINHTTP_LOGIN_FAILURE: Final = 12015 +ERROR_WINHTTP_OPERATION_CANCELLED: Final = 12017 +ERROR_WINHTTP_INCORRECT_HANDLE_TYPE: Final = 12018 +ERROR_WINHTTP_INCORRECT_HANDLE_STATE: Final = 12019 +ERROR_WINHTTP_CANNOT_CONNECT: Final = 12029 +ERROR_WINHTTP_CONNECTION_ERROR: Final = 12030 +ERROR_WINHTTP_RESEND_REQUEST: Final = 12032 +ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: Final = 12044 +ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN: Final = 12100 +ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND: Final = 12101 +ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND: Final = 12102 +ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN: Final = 12103 +ERROR_WINHTTP_HEADER_NOT_FOUND: Final = 12150 +ERROR_WINHTTP_INVALID_SERVER_RESPONSE: Final = 12152 +ERROR_WINHTTP_INVALID_HEADER: Final = 12153 +ERROR_WINHTTP_INVALID_QUERY_REQUEST: Final = 12154 +ERROR_WINHTTP_HEADER_ALREADY_EXISTS: Final = 12155 +ERROR_WINHTTP_REDIRECT_FAILED: Final = 12156 +ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT: Final = 12166 +ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: Final = 12167 +ERROR_WINHTTP_NOT_INITIALIZED: Final = 12172 +ERROR_WINHTTP_SECURE_FAILURE: Final = 12175 +ERROR_WINHTTP_SECURE_CERT_DATE_INVALID: Final = 12037 +ERROR_WINHTTP_SECURE_CERT_CN_INVALID: Final = 12038 +ERROR_WINHTTP_SECURE_INVALID_CA: Final = 12045 +ERROR_WINHTTP_SECURE_CERT_REV_FAILED: Final = 12057 +ERROR_WINHTTP_SECURE_CHANNEL_ERROR: Final = 12157 +ERROR_WINHTTP_SECURE_INVALID_CERT: Final = 12169 +ERROR_WINHTTP_SECURE_CERT_REVOKED: Final = 12170 +ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR: Final = 12178 +ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE: Final = 12179 +ERROR_WINHTTP_AUTODETECTION_FAILED: Final = 12180 +ERROR_WINHTTP_HEADER_COUNT_EXCEEDED: Final = 12181 +ERROR_WINHTTP_HEADER_SIZE_OVERFLOW: Final = 12182 +ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW: Final = 12183 +ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW: Final = 12184 +ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY: Final = 12185 +ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY: Final = 12186 +WINHTTP_ERROR_LAST: Final = 12186 +WINHTTP_NO_PROXY_NAME: Final = None +WINHTTP_NO_PROXY_BYPASS: Final = None +WINHTTP_NO_REFERER: Final = None +WINHTTP_DEFAULT_ACCEPT_TYPES: Final = None +WINHTTP_NO_ADDITIONAL_HEADERS: Final = None +WINHTTP_NO_REQUEST_DATA: Final = None diff --git a/stubs/pywin32/win32/lib/win32netcon.pyi b/stubs/pywin32/win32/lib/win32netcon.pyi new file mode 100644 index 000000000000..cbe32eeb8acf --- /dev/null +++ b/stubs/pywin32/win32/lib/win32netcon.pyi @@ -0,0 +1,573 @@ +from typing import Final + +CNLEN: Final = 15 +LM20_CNLEN: Final = 15 +DNLEN: Final = CNLEN +LM20_DNLEN: Final = LM20_CNLEN +UNCLEN: Final = 17 +LM20_UNCLEN: Final = 17 +NNLEN: Final = 80 +LM20_NNLEN: Final = 12 +RMLEN: Final = 98 +LM20_RMLEN: Final = 30 +SNLEN: Final = 80 +LM20_SNLEN: Final = 15 +STXTLEN: Final = 256 +LM20_STXTLEN: Final = 63 +PATHLEN: Final = 256 +LM20_PATHLEN: Final = 256 +DEVLEN: Final = 80 +LM20_DEVLEN: Final = 8 +EVLEN: Final = 16 +UNLEN: Final = 256 +LM20_UNLEN: Final = 20 +GNLEN: Final = UNLEN +LM20_GNLEN: Final = LM20_UNLEN +PWLEN: Final = 256 +LM20_PWLEN: Final = 14 +SHPWLEN: Final = 8 +CLTYPE_LEN: Final = 12 +MAXCOMMENTSZ: Final = 256 +LM20_MAXCOMMENTSZ: Final = 48 +QNLEN: Final = NNLEN +LM20_QNLEN: Final = LM20_NNLEN +ALERTSZ: Final = 128 +NETBIOS_NAME_LEN: Final = 16 +CRYPT_KEY_LEN: Final = 7 +CRYPT_TXT_LEN: Final = 8 +ENCRYPTED_PWLEN: Final = 16 +SESSION_PWLEN: Final = 24 +SESSION_CRYPT_KLEN: Final = 21 +PARMNUM_ALL: Final = 0 +PARM_ERROR_NONE: Final = 0 +PARMNUM_BASE_INFOLEVEL: Final = 1000 +NULL: Final = 0 +PLATFORM_ID_DOS: Final = 300 +PLATFORM_ID_OS2: Final = 400 +PLATFORM_ID_NT: Final = 500 +PLATFORM_ID_OSF: Final = 600 +PLATFORM_ID_VMS: Final = 700 +MAX_LANMAN_MESSAGE_ID: Final = 5799 +UF_SCRIPT: Final = 1 +UF_ACCOUNTDISABLE: Final = 2 +UF_HOMEDIR_REQUIRED: Final = 8 +UF_LOCKOUT: Final = 16 +UF_PASSWD_NOTREQD: Final = 32 +UF_PASSWD_CANT_CHANGE: Final = 64 +UF_TEMP_DUPLICATE_ACCOUNT: Final = 256 +UF_NORMAL_ACCOUNT: Final = 512 +UF_INTERDOMAIN_TRUST_ACCOUNT: Final = 2048 +UF_WORKSTATION_TRUST_ACCOUNT: Final = 4096 +UF_SERVER_TRUST_ACCOUNT: Final = 8192 +UF_MACHINE_ACCOUNT_MASK: Final = 14336 +UF_ACCOUNT_TYPE_MASK: Final = 15104 +UF_DONT_EXPIRE_PASSWD: Final = 65536 +UF_MNS_LOGON_ACCOUNT: Final = 131072 +UF_SETTABLE_BITS: Final = 211835 +FILTER_TEMP_DUPLICATE_ACCOUNT: Final = 1 +FILTER_NORMAL_ACCOUNT: Final = 2 +FILTER_INTERDOMAIN_TRUST_ACCOUNT: Final = 8 +FILTER_WORKSTATION_TRUST_ACCOUNT: Final = 16 +FILTER_SERVER_TRUST_ACCOUNT: Final = 32 +LG_INCLUDE_INDIRECT: Final = 1 +AF_OP_PRINT: Final = 1 +AF_OP_COMM: Final = 2 +AF_OP_SERVER: Final = 4 +AF_OP_ACCOUNTS: Final = 8 +AF_SETTABLE_BITS: Final = 15 +UAS_ROLE_STANDALONE: Final = 0 +UAS_ROLE_MEMBER: Final = 1 +UAS_ROLE_BACKUP: Final = 2 +UAS_ROLE_PRIMARY: Final = 3 +USER_NAME_PARMNUM: Final = 1 +USER_PASSWORD_PARMNUM: Final = 3 +USER_PASSWORD_AGE_PARMNUM: Final = 4 +USER_PRIV_PARMNUM: Final = 5 +USER_HOME_DIR_PARMNUM: Final = 6 +USER_COMMENT_PARMNUM: Final = 7 +USER_FLAGS_PARMNUM: Final = 8 +USER_SCRIPT_PATH_PARMNUM: Final = 9 +USER_AUTH_FLAGS_PARMNUM: Final = 10 +USER_FULL_NAME_PARMNUM: Final = 11 +USER_USR_COMMENT_PARMNUM: Final = 12 +USER_PARMS_PARMNUM: Final = 13 +USER_WORKSTATIONS_PARMNUM: Final = 14 +USER_LAST_LOGON_PARMNUM: Final = 15 +USER_LAST_LOGOFF_PARMNUM: Final = 16 +USER_ACCT_EXPIRES_PARMNUM: Final = 17 +USER_MAX_STORAGE_PARMNUM: Final = 18 +USER_UNITS_PER_WEEK_PARMNUM: Final = 19 +USER_LOGON_HOURS_PARMNUM: Final = 20 +USER_PAD_PW_COUNT_PARMNUM: Final = 21 +USER_NUM_LOGONS_PARMNUM: Final = 22 +USER_LOGON_SERVER_PARMNUM: Final = 23 +USER_COUNTRY_CODE_PARMNUM: Final = 24 +USER_CODE_PAGE_PARMNUM: Final = 25 +USER_PRIMARY_GROUP_PARMNUM: Final = 51 +USER_PROFILE: Final = 52 +USER_PROFILE_PARMNUM: Final = 52 +USER_HOME_DIR_DRIVE_PARMNUM: Final = 53 +USER_NAME_INFOLEVEL: Final = 1001 +USER_PASSWORD_INFOLEVEL: Final = 1003 +USER_PASSWORD_AGE_INFOLEVEL: Final = 1004 +USER_PRIV_INFOLEVEL: Final = 1005 +USER_HOME_DIR_INFOLEVEL: Final = 1006 +USER_COMMENT_INFOLEVEL: Final = 1007 +USER_FLAGS_INFOLEVEL: Final = 1008 +USER_SCRIPT_PATH_INFOLEVEL: Final = 1009 +USER_AUTH_FLAGS_INFOLEVEL: Final = 1010 +USER_FULL_NAME_INFOLEVEL: Final = 1011 +USER_USR_COMMENT_INFOLEVEL: Final = 1012 +USER_PARMS_INFOLEVEL: Final = 1013 +USER_WORKSTATIONS_INFOLEVEL: Final = 1014 +USER_LAST_LOGON_INFOLEVEL: Final = 1015 +USER_LAST_LOGOFF_INFOLEVEL: Final = 1016 +USER_ACCT_EXPIRES_INFOLEVEL: Final = 1017 +USER_MAX_STORAGE_INFOLEVEL: Final = 1018 +USER_UNITS_PER_WEEK_INFOLEVEL: Final = 1019 +USER_LOGON_HOURS_INFOLEVEL: Final = 1020 +USER_PAD_PW_COUNT_INFOLEVEL: Final = 1021 +USER_NUM_LOGONS_INFOLEVEL: Final = 1022 +USER_LOGON_SERVER_INFOLEVEL: Final = 1023 +USER_COUNTRY_CODE_INFOLEVEL: Final = 1024 +USER_CODE_PAGE_INFOLEVEL: Final = 1025 +USER_PRIMARY_GROUP_INFOLEVEL: Final = 1051 +USER_HOME_DIR_DRIVE_INFOLEVEL: Final = 1053 +NULL_USERSETINFO_PASSWD: Final = " " +UNITS_PER_DAY: Final = 24 +UNITS_PER_WEEK: Final = 168 +USER_PRIV_MASK: Final = 3 +USER_PRIV_GUEST: Final = 0 +USER_PRIV_USER: Final = 1 +USER_PRIV_ADMIN: Final = 2 +MAX_PASSWD_LEN: Final = PWLEN +DEF_MIN_PWLEN: Final = 6 +DEF_PWUNIQUENESS: Final = 5 +DEF_MAX_PWHIST: Final = 8 +DEF_MAX_BADPW: Final = 0 +VALIDATED_LOGON: Final = 0 +PASSWORD_EXPIRED: Final = 2 +NON_VALIDATED_LOGON: Final = 3 +VALID_LOGOFF: Final = 1 +MODALS_MIN_PASSWD_LEN_PARMNUM: Final = 1 +MODALS_MAX_PASSWD_AGE_PARMNUM: Final = 2 +MODALS_MIN_PASSWD_AGE_PARMNUM: Final = 3 +MODALS_FORCE_LOGOFF_PARMNUM: Final = 4 +MODALS_PASSWD_HIST_LEN_PARMNUM: Final = 5 +MODALS_ROLE_PARMNUM: Final = 6 +MODALS_PRIMARY_PARMNUM: Final = 7 +MODALS_DOMAIN_NAME_PARMNUM: Final = 8 +MODALS_DOMAIN_ID_PARMNUM: Final = 9 +MODALS_LOCKOUT_DURATION_PARMNUM: Final = 10 +MODALS_LOCKOUT_OBSERVATION_WINDOW_PARMNUM: Final = 11 +MODALS_LOCKOUT_THRESHOLD_PARMNUM: Final = 12 +MODALS_MIN_PASSWD_LEN_INFOLEVEL: Final = 1001 +MODALS_MAX_PASSWD_AGE_INFOLEVEL: Final = 1002 +MODALS_MIN_PASSWD_AGE_INFOLEVEL: Final = 1003 +MODALS_FORCE_LOGOFF_INFOLEVEL: Final = 1004 +MODALS_PASSWD_HIST_LEN_INFOLEVEL: Final = 1005 +MODALS_ROLE_INFOLEVEL: Final = 1006 +MODALS_PRIMARY_INFOLEVEL: Final = 1007 +MODALS_DOMAIN_NAME_INFOLEVEL: Final = 1008 +MODALS_DOMAIN_ID_INFOLEVEL: Final = 1009 +GROUPIDMASK: Final = 32768 +GROUP_ALL_PARMNUM: Final = 0 +GROUP_NAME_PARMNUM: Final = 1 +GROUP_COMMENT_PARMNUM: Final = 2 +GROUP_ATTRIBUTES_PARMNUM: Final = 3 +GROUP_ALL_INFOLEVEL: Final = 1000 +GROUP_NAME_INFOLEVEL: Final = 1001 +GROUP_COMMENT_INFOLEVEL: Final = 1002 +GROUP_ATTRIBUTES_INFOLEVEL: Final = 1003 +LOCALGROUP_NAME_PARMNUM: Final = 1 +LOCALGROUP_COMMENT_PARMNUM: Final = 2 +MAXPERMENTRIES: Final = 64 +ACCESS_NONE: Final = 0 +ACCESS_READ: Final = 1 +ACCESS_WRITE: Final = 2 +ACCESS_CREATE: Final = 4 +ACCESS_EXEC: Final = 8 +ACCESS_DELETE: Final = 16 +ACCESS_ATRIB: Final = 32 +ACCESS_PERM: Final = 64 +ACCESS_GROUP: Final = 32768 +ACCESS_AUDIT: Final = 1 +ACCESS_SUCCESS_OPEN: Final = 16 +ACCESS_SUCCESS_WRITE: Final = 32 +ACCESS_SUCCESS_DELETE: Final = 64 +ACCESS_SUCCESS_ACL: Final = 128 +ACCESS_SUCCESS_MASK: Final = 240 +ACCESS_FAIL_OPEN: Final = 256 +ACCESS_FAIL_WRITE: Final = 512 +ACCESS_FAIL_DELETE: Final = 1024 +ACCESS_FAIL_ACL: Final = 2048 +ACCESS_FAIL_MASK: Final = 3840 +ACCESS_FAIL_SHIFT: Final = 4 +ACCESS_RESOURCE_NAME_PARMNUM: Final = 1 +ACCESS_ATTR_PARMNUM: Final = 2 +ACCESS_COUNT_PARMNUM: Final = 3 +ACCESS_ACCESS_LIST_PARMNUM: Final = 4 +ACCESS_RESOURCE_NAME_INFOLEVEL: Final = 1001 +ACCESS_ATTR_INFOLEVEL: Final = 1002 +ACCESS_COUNT_INFOLEVEL: Final = 1003 +ACCESS_ACCESS_LIST_INFOLEVEL: Final = 1004 +ACCESS_LETTERS: Final = "RWCXDAP " +NETLOGON_CONTROL_QUERY: Final = 1 +NETLOGON_CONTROL_REPLICATE: Final = 2 +NETLOGON_CONTROL_SYNCHRONIZE: Final = 3 +NETLOGON_CONTROL_PDC_REPLICATE: Final = 4 +NETLOGON_CONTROL_REDISCOVER: Final = 5 +NETLOGON_CONTROL_TC_QUERY: Final = 6 +NETLOGON_CONTROL_TRANSPORT_NOTIFY: Final = 7 +NETLOGON_CONTROL_FIND_USER: Final = 8 +NETLOGON_CONTROL_UNLOAD_NETLOGON_DLL: Final = 65531 +NETLOGON_CONTROL_BACKUP_CHANGE_LOG: Final = 65532 +NETLOGON_CONTROL_TRUNCATE_LOG: Final = 65533 +NETLOGON_CONTROL_SET_DBFLAG: Final = 65534 +NETLOGON_CONTROL_BREAKPOINT: Final = 65535 +NETLOGON_REPLICATION_NEEDED: Final = 1 +NETLOGON_REPLICATION_IN_PROGRESS: Final = 2 +NETLOGON_FULL_SYNC_REPLICATION: Final = 4 +NETLOGON_REDO_NEEDED: Final = 8 + +def TEXT(x: str) -> str: ... + +MAX_PREFERRED_LENGTH: Final = -1 +PARM_ERROR_UNKNOWN: Final = -1 +MESSAGE_FILENAME: Final = "NETMSG" +OS2MSG_FILENAME: Final = "BASE" +HELP_MSG_FILENAME: Final = "NETH" +BACKUP_MSG_FILENAME: Final = "BAK.MSG" +TIMEQ_FOREVER: Final = -1 +USER_MAXSTORAGE_UNLIMITED: Final = -1 +USER_NO_LOGOFF: Final = -1 +DEF_MAX_PWAGE: Final = TIMEQ_FOREVER +DEF_MIN_PWAGE: Final = 0 +DEF_FORCE_LOGOFF: Final = -1 +ONE_DAY: Final = 86400 +GROUP_SPECIALGRP_USERS: Final = "USERS" +GROUP_SPECIALGRP_ADMINS: Final = "ADMINS" +GROUP_SPECIALGRP_GUESTS: Final = "GUESTS" +GROUP_SPECIALGRP_LOCAL: Final = "LOCAL" +ACCESS_ALL: Final = 127 +SV_PLATFORM_ID_OS2: Final = 400 +SV_PLATFORM_ID_NT: Final = 500 +MAJOR_VERSION_MASK: Final = 15 +SV_TYPE_WORKSTATION: Final = 1 +SV_TYPE_SERVER: Final = 2 +SV_TYPE_SQLSERVER: Final = 4 +SV_TYPE_DOMAIN_CTRL: Final = 8 +SV_TYPE_DOMAIN_BAKCTRL: Final = 16 +SV_TYPE_TIME_SOURCE: Final = 32 +SV_TYPE_AFP: Final = 64 +SV_TYPE_NOVELL: Final = 128 +SV_TYPE_DOMAIN_MEMBER: Final = 256 +SV_TYPE_PRINTQ_SERVER: Final = 512 +SV_TYPE_DIALIN_SERVER: Final = 1024 +SV_TYPE_XENIX_SERVER: Final = 2048 +SV_TYPE_SERVER_UNIX: Final = SV_TYPE_XENIX_SERVER +SV_TYPE_NT: Final = 4096 +SV_TYPE_WFW: Final = 8192 +SV_TYPE_SERVER_MFPN: Final = 16384 +SV_TYPE_SERVER_NT: Final = 32768 +SV_TYPE_POTENTIAL_BROWSER: Final = 65536 +SV_TYPE_BACKUP_BROWSER: Final = 131072 +SV_TYPE_MASTER_BROWSER: Final = 262144 +SV_TYPE_DOMAIN_MASTER: Final = 524288 +SV_TYPE_SERVER_OSF: Final = 1048576 +SV_TYPE_SERVER_VMS: Final = 2097152 +SV_TYPE_WINDOWS: Final = 4194304 +SV_TYPE_DFS: Final = 8388608 +SV_TYPE_CLUSTER_NT: Final = 16777216 +SV_TYPE_DCE: Final = 268435456 +SV_TYPE_ALTERNATE_XPORT: Final = 536870912 +SV_TYPE_LOCAL_LIST_ONLY: Final = 1073741824 +SV_TYPE_DOMAIN_ENUM: Final = -2147483648 +SV_TYPE_ALL: Final = -1 +SV_NODISC: Final = -1 +SV_USERSECURITY: Final = 1 +SV_SHARESECURITY: Final = 0 +SV_HIDDEN: Final = 1 +SV_VISIBLE: Final = 0 +SV_PLATFORM_ID_PARMNUM: Final = 101 +SV_NAME_PARMNUM: Final = 102 +SV_VERSION_MAJOR_PARMNUM: Final = 103 +SV_VERSION_MINOR_PARMNUM: Final = 104 +SV_TYPE_PARMNUM: Final = 105 +SV_COMMENT_PARMNUM: Final = 5 +SV_USERS_PARMNUM: Final = 107 +SV_DISC_PARMNUM: Final = 10 +SV_HIDDEN_PARMNUM: Final = 16 +SV_ANNOUNCE_PARMNUM: Final = 17 +SV_ANNDELTA_PARMNUM: Final = 18 +SV_USERPATH_PARMNUM: Final = 112 +SV_ULIST_MTIME_PARMNUM: Final = 401 +SV_GLIST_MTIME_PARMNUM: Final = 402 +SV_ALIST_MTIME_PARMNUM: Final = 403 +SV_ALERTS_PARMNUM: Final = 11 +SV_SECURITY_PARMNUM: Final = 405 +SV_NUMADMIN_PARMNUM: Final = 406 +SV_LANMASK_PARMNUM: Final = 407 +SV_GUESTACC_PARMNUM: Final = 408 +SV_CHDEVQ_PARMNUM: Final = 410 +SV_CHDEVJOBS_PARMNUM: Final = 411 +SV_CONNECTIONS_PARMNUM: Final = 412 +SV_SHARES_PARMNUM: Final = 413 +SV_OPENFILES_PARMNUM: Final = 414 +SV_SESSREQS_PARMNUM: Final = 417 +SV_ACTIVELOCKS_PARMNUM: Final = 419 +SV_NUMREQBUF_PARMNUM: Final = 420 +SV_NUMBIGBUF_PARMNUM: Final = 422 +SV_NUMFILETASKS_PARMNUM: Final = 423 +SV_ALERTSCHED_PARMNUM: Final = 37 +SV_ERRORALERT_PARMNUM: Final = 38 +SV_LOGONALERT_PARMNUM: Final = 39 +SV_ACCESSALERT_PARMNUM: Final = 40 +SV_DISKALERT_PARMNUM: Final = 41 +SV_NETIOALERT_PARMNUM: Final = 42 +SV_MAXAUDITSZ_PARMNUM: Final = 43 +SV_SRVHEURISTICS_PARMNUM: Final = 431 +SV_SESSOPENS_PARMNUM: Final = 501 +SV_SESSVCS_PARMNUM: Final = 502 +SV_OPENSEARCH_PARMNUM: Final = 503 +SV_SIZREQBUF_PARMNUM: Final = 504 +SV_INITWORKITEMS_PARMNUM: Final = 505 +SV_MAXWORKITEMS_PARMNUM: Final = 506 +SV_RAWWORKITEMS_PARMNUM: Final = 507 +SV_IRPSTACKSIZE_PARMNUM: Final = 508 +SV_MAXRAWBUFLEN_PARMNUM: Final = 509 +SV_SESSUSERS_PARMNUM: Final = 510 +SV_SESSCONNS_PARMNUM: Final = 511 +SV_MAXNONPAGEDMEMORYUSAGE_PARMNUM: Final = 512 +SV_MAXPAGEDMEMORYUSAGE_PARMNUM: Final = 513 +SV_ENABLESOFTCOMPAT_PARMNUM: Final = 514 +SV_ENABLEFORCEDLOGOFF_PARMNUM: Final = 515 +SV_TIMESOURCE_PARMNUM: Final = 516 +SV_ACCEPTDOWNLEVELAPIS_PARMNUM: Final = 517 +SV_LMANNOUNCE_PARMNUM: Final = 518 +SV_DOMAIN_PARMNUM: Final = 519 +SV_MAXCOPYREADLEN_PARMNUM: Final = 520 +SV_MAXCOPYWRITELEN_PARMNUM: Final = 521 +SV_MINKEEPSEARCH_PARMNUM: Final = 522 +SV_MAXKEEPSEARCH_PARMNUM: Final = 523 +SV_MINKEEPCOMPLSEARCH_PARMNUM: Final = 524 +SV_MAXKEEPCOMPLSEARCH_PARMNUM: Final = 525 +SV_THREADCOUNTADD_PARMNUM: Final = 526 +SV_NUMBLOCKTHREADS_PARMNUM: Final = 527 +SV_SCAVTIMEOUT_PARMNUM: Final = 528 +SV_MINRCVQUEUE_PARMNUM: Final = 529 +SV_MINFREEWORKITEMS_PARMNUM: Final = 530 +SV_XACTMEMSIZE_PARMNUM: Final = 531 +SV_THREADPRIORITY_PARMNUM: Final = 532 +SV_MAXMPXCT_PARMNUM: Final = 533 +SV_OPLOCKBREAKWAIT_PARMNUM: Final = 534 +SV_OPLOCKBREAKRESPONSEWAIT_PARMNUM: Final = 535 +SV_ENABLEOPLOCKS_PARMNUM: Final = 536 +SV_ENABLEOPLOCKFORCECLOSE_PARMNUM: Final = 537 +SV_ENABLEFCBOPENS_PARMNUM: Final = 538 +SV_ENABLERAW_PARMNUM: Final = 539 +SV_ENABLESHAREDNETDRIVES_PARMNUM: Final = 540 +SV_MINFREECONNECTIONS_PARMNUM: Final = 541 +SV_MAXFREECONNECTIONS_PARMNUM: Final = 542 +SV_INITSESSTABLE_PARMNUM: Final = 543 +SV_INITCONNTABLE_PARMNUM: Final = 544 +SV_INITFILETABLE_PARMNUM: Final = 545 +SV_INITSEARCHTABLE_PARMNUM: Final = 546 +SV_ALERTSCHEDULE_PARMNUM: Final = 547 +SV_ERRORTHRESHOLD_PARMNUM: Final = 548 +SV_NETWORKERRORTHRESHOLD_PARMNUM: Final = 549 +SV_DISKSPACETHRESHOLD_PARMNUM: Final = 550 +SV_MAXLINKDELAY_PARMNUM: Final = 552 +SV_MINLINKTHROUGHPUT_PARMNUM: Final = 553 +SV_LINKINFOVALIDTIME_PARMNUM: Final = 554 +SV_SCAVQOSINFOUPDATETIME_PARMNUM: Final = 555 +SV_MAXWORKITEMIDLETIME_PARMNUM: Final = 556 +SV_MAXRAWWORKITEMS_PARMNUM: Final = 557 +SV_PRODUCTTYPE_PARMNUM: Final = 560 +SV_SERVERSIZE_PARMNUM: Final = 561 +SV_CONNECTIONLESSAUTODISC_PARMNUM: Final = 562 +SV_SHARINGVIOLATIONRETRIES_PARMNUM: Final = 563 +SV_SHARINGVIOLATIONDELAY_PARMNUM: Final = 564 +SV_MAXGLOBALOPENSEARCH_PARMNUM: Final = 565 +SV_REMOVEDUPLICATESEARCHES_PARMNUM: Final = 566 +SV_LOCKVIOLATIONRETRIES_PARMNUM: Final = 567 +SV_LOCKVIOLATIONOFFSET_PARMNUM: Final = 568 +SV_LOCKVIOLATIONDELAY_PARMNUM: Final = 569 +SV_MDLREADSWITCHOVER_PARMNUM: Final = 570 +SV_CACHEDOPENLIMIT_PARMNUM: Final = 571 +SV_CRITICALTHREADS_PARMNUM: Final = 572 +SV_RESTRICTNULLSESSACCESS_PARMNUM: Final = 573 +SV_ENABLEWFW311DIRECTIPX_PARMNUM: Final = 574 +SV_OTHERQUEUEAFFINITY_PARMNUM: Final = 575 +SV_QUEUESAMPLESECS_PARMNUM: Final = 576 +SV_BALANCECOUNT_PARMNUM: Final = 577 +SV_PREFERREDAFFINITY_PARMNUM: Final = 578 +SV_MAXFREERFCBS_PARMNUM: Final = 579 +SV_MAXFREEMFCBS_PARMNUM: Final = 580 +SV_MAXFREELFCBS_PARMNUM: Final = 581 +SV_MAXFREEPAGEDPOOLCHUNKS_PARMNUM: Final = 582 +SV_MINPAGEDPOOLCHUNKSIZE_PARMNUM: Final = 583 +SV_MAXPAGEDPOOLCHUNKSIZE_PARMNUM: Final = 584 +SV_SENDSFROMPREFERREDPROCESSOR_PARMNUM: Final = 585 +SV_MAXTHREADSPERQUEUE_PARMNUM: Final = 586 +SV_CACHEDDIRECTORYLIMIT_PARMNUM: Final = 587 +SV_MAXCOPYLENGTH_PARMNUM: Final = 588 +SV_ENABLEBULKTRANSFER_PARMNUM: Final = 589 +SV_ENABLECOMPRESSION_PARMNUM: Final = 590 +SV_AUTOSHAREWKS_PARMNUM: Final = 591 +SV_AUTOSHARESERVER_PARMNUM: Final = 592 +SV_ENABLESECURITYSIGNATURE_PARMNUM: Final = 593 +SV_REQUIRESECURITYSIGNATURE_PARMNUM: Final = 594 +SV_MINCLIENTBUFFERSIZE_PARMNUM: Final = 595 +SV_CONNECTIONNOSESSIONSTIMEOUT_PARMNUM: Final = 596 +SVI1_NUM_ELEMENTS: Final = 5 +SVI2_NUM_ELEMENTS: Final = 40 +SVI3_NUM_ELEMENTS: Final = 44 +SW_AUTOPROF_LOAD_MASK: Final = 1 +SW_AUTOPROF_SAVE_MASK: Final = 2 +SV_MAX_SRV_HEUR_LEN: Final = 32 +SV_USERS_PER_LICENSE: Final = 5 +SVTI2_REMAP_PIPE_NAMES: Final = 2 +SHARE_NETNAME_PARMNUM: Final = 1 +SHARE_TYPE_PARMNUM: Final = 3 +SHARE_REMARK_PARMNUM: Final = 4 +SHARE_PERMISSIONS_PARMNUM: Final = 5 +SHARE_MAX_USES_PARMNUM: Final = 6 +SHARE_CURRENT_USES_PARMNUM: Final = 7 +SHARE_PATH_PARMNUM: Final = 8 +SHARE_PASSWD_PARMNUM: Final = 9 +SHARE_FILE_SD_PARMNUM: Final = 501 +SHI1_NUM_ELEMENTS: Final = 4 +SHI2_NUM_ELEMENTS: Final = 10 +STYPE_DISKTREE: Final = 0 +STYPE_PRINTQ: Final = 1 +STYPE_DEVICE: Final = 2 +STYPE_IPC: Final = 3 +STYPE_SPECIAL: Final = -2147483648 +SHI1005_FLAGS_DFS: Final = 1 +SHI1005_FLAGS_DFS_ROOT: Final = 2 +COW_PERMACHINE: Final = 4 +COW_PERUSER: Final = 8 +CSC_CACHEABLE: Final = 16 +CSC_NOFLOWOPS: Final = 32 +CSC_AUTO_INWARD: Final = 64 +CSC_AUTO_OUTWARD: Final = 128 +SHI1005_VALID_FLAGS_SET: Final = 252 +SHI1007_VALID_FLAGS_SET: Final = SHI1005_VALID_FLAGS_SET +SESS_GUEST: Final = 1 +SESS_NOENCRYPTION: Final = 2 +SESI1_NUM_ELEMENTS: Final = 8 +SESI2_NUM_ELEMENTS: Final = 9 +PERM_FILE_READ: Final = 1 +PERM_FILE_WRITE: Final = 2 +PERM_FILE_CREATE: Final = 4 +WNNC_NET_MSNET: Final = 65536 +WNNC_NET_LANMAN: Final = 131072 +WNNC_NET_NETWARE: Final = 196608 +WNNC_NET_VINES: Final = 262144 +WNNC_NET_10NET: Final = 327680 +WNNC_NET_LOCUS: Final = 393216 +WNNC_NET_SUN_PC_NFS: Final = 458752 +WNNC_NET_LANSTEP: Final = 524288 +WNNC_NET_9TILES: Final = 589824 +WNNC_NET_LANTASTIC: Final = 655360 +WNNC_NET_AS400: Final = 720896 +WNNC_NET_FTP_NFS: Final = 786432 +WNNC_NET_PATHWORKS: Final = 851968 +WNNC_NET_LIFENET: Final = 917504 +WNNC_NET_POWERLAN: Final = 983040 +WNNC_NET_BWNFS: Final = 1048576 +WNNC_NET_COGENT: Final = 1114112 +WNNC_NET_FARALLON: Final = 1179648 +WNNC_NET_APPLETALK: Final = 1245184 +WNNC_NET_INTERGRAPH: Final = 1310720 +WNNC_NET_SYMFONET: Final = 1376256 +WNNC_NET_CLEARCASE: Final = 1441792 +WNNC_NET_FRONTIER: Final = 1507328 +WNNC_NET_BMC: Final = 1572864 +WNNC_NET_DCE: Final = 1638400 +WNNC_NET_DECORB: Final = 2097152 +WNNC_NET_PROTSTOR: Final = 2162688 +WNNC_NET_FJ_REDIR: Final = 2228224 +WNNC_NET_DISTINCT: Final = 2293760 +WNNC_NET_TWINS: Final = 2359296 +WNNC_NET_RDR2SAMPLE: Final = 2424832 +RESOURCE_CONNECTED: Final = 1 +RESOURCE_GLOBALNET: Final = 2 +RESOURCE_REMEMBERED: Final = 3 +RESOURCE_RECENT: Final = 4 +RESOURCE_CONTEXT: Final = 5 +RESOURCETYPE_ANY: Final = 0 +RESOURCETYPE_DISK: Final = 1 +RESOURCETYPE_PRINT: Final = 2 +RESOURCETYPE_RESERVED: Final = 8 +RESOURCETYPE_UNKNOWN: Final = -1 +RESOURCEUSAGE_CONNECTABLE: Final = 1 +RESOURCEUSAGE_CONTAINER: Final = 2 +RESOURCEUSAGE_NOLOCALDEVICE: Final = 4 +RESOURCEUSAGE_SIBLING: Final = 8 +RESOURCEUSAGE_ATTACHED: Final = 16 +RESOURCEUSAGE_ALL: Final = 19 +RESOURCEUSAGE_RESERVED: Final = -2147483648 +RESOURCEDISPLAYTYPE_GENERIC: Final = 0 +RESOURCEDISPLAYTYPE_DOMAIN: Final = 1 +RESOURCEDISPLAYTYPE_SERVER: Final = 2 +RESOURCEDISPLAYTYPE_SHARE: Final = 3 +RESOURCEDISPLAYTYPE_FILE: Final = 4 +RESOURCEDISPLAYTYPE_GROUP: Final = 5 +RESOURCEDISPLAYTYPE_NETWORK: Final = 6 +RESOURCEDISPLAYTYPE_ROOT: Final = 7 +RESOURCEDISPLAYTYPE_SHAREADMIN: Final = 8 +RESOURCEDISPLAYTYPE_DIRECTORY: Final = 9 +RESOURCEDISPLAYTYPE_TREE: Final = 10 +RESOURCEDISPLAYTYPE_NDSCONTAINER: Final = 11 +NETPROPERTY_PERSISTENT: Final = 1 +CONNECT_UPDATE_PROFILE: Final = 1 +CONNECT_UPDATE_RECENT: Final = 2 +CONNECT_TEMPORARY: Final = 4 +CONNECT_INTERACTIVE: Final = 8 +CONNECT_PROMPT: Final = 16 +CONNECT_NEED_DRIVE: Final = 32 +CONNECT_REFCOUNT: Final = 64 +CONNECT_REDIRECT: Final = 128 +CONNECT_LOCALDRIVE: Final = 256 +CONNECT_CURRENT_MEDIA: Final = 512 +CONNECT_DEFERRED: Final = 1024 +CONNECT_RESERVED: Final = -16777216 +CONNDLG_RO_PATH: Final = 1 +CONNDLG_CONN_POINT: Final = 2 +CONNDLG_USE_MRU: Final = 4 +CONNDLG_HIDE_BOX: Final = 8 +CONNDLG_PERSIST: Final = 16 +CONNDLG_NOT_PERSIST: Final = 32 +DISC_UPDATE_PROFILE: Final = 1 +DISC_NO_FORCE: Final = 64 +UNIVERSAL_NAME_INFO_LEVEL: Final = 1 +REMOTE_NAME_INFO_LEVEL: Final = 2 +WNFMT_MULTILINE: Final = 1 +WNFMT_ABBREVIATED: Final = 2 +WNFMT_INENUM: Final = 16 +WNFMT_CONNECTION: Final = 32 +NETINFO_DLL16: Final = 1 +NETINFO_DISKRED: Final = 4 +NETINFO_PRINTERRED: Final = 8 +RP_LOGON: Final = 1 +RP_INIFILE: Final = 2 +PP_DISPLAYERRORS: Final = 1 +WNCON_FORNETCARD: Final = 1 +WNCON_NOTROUTED: Final = 2 +WNCON_SLOWLINK: Final = 4 +WNCON_DYNAMIC: Final = 8 +NetSetupUnknown: Final = 0 +NetSetupMachine: Final = 1 +NetSetupWorkgroup: Final = 2 +NetSetupDomain: Final = 3 +NetSetupNonExistentDomain: Final = 4 +NetSetupDnsMachine: Final = 5 +NetSetupUnknownStatus: Final = 0 +NetSetupUnjoined: Final = 1 +NetSetupWorkgroupName: Final = 2 +NetSetupDomainName: Final = 3 +NetValidateAuthentication: Final = 1 +NetValidatePasswordChange: Final = 2 +NetValidatePasswordReset: Final = 3 diff --git a/stubs/pywin32/win32/lib/win32pdhquery.pyi b/stubs/pywin32/win32/lib/win32pdhquery.pyi new file mode 100644 index 000000000000..62753b214e80 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32pdhquery.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +class BaseQuery: + counters: Incomplete + paths: Incomplete + active: int + curpaths: Incomplete + def __init__(self, paths: Incomplete | None = ...) -> None: ... + def addcounterbybrowsing(self, flags=..., windowtitle: str = ...) -> None: ... + def rawaddcounter( + self, object, counter, instance: Incomplete | None = ..., inum: int = ..., machine: Incomplete | None = ... + ) -> None: ... + def addcounter( + self, object, counter, instance: Incomplete | None = ..., inum: int = ..., machine: Incomplete | None = ... + ): ... + def open(self): ... + def killbase(self, base: Incomplete | None = ...) -> None: ... + def close(self) -> None: ... + __del__: Incomplete + def collectdata(self, format=...): ... + def collectdataslave(self, format=...): ... + def __getinitargs__(self): ... + +class Query(BaseQuery): + volatilecounters: Incomplete + def __init__(self, *args, **namedargs) -> None: ... + @deprecated("Use `addcounterbybrowsing` instead.") + def addperfcounter(self, object, counter, machine=None): ... + def addinstcounter( + self, object, counter, machine: Incomplete | None = ..., objtype: str = ..., volatile: int = ..., format=... + ) -> None: ... + def getinstpaths(self, object, counter, machine: Incomplete | None = ..., objtype: str = ..., format=...): ... + def open(self, *args, **namedargs) -> None: ... + curresults: Incomplete + def collectdatafor(self, totalperiod, period: int = ...) -> None: ... + collectdatawhile_active: int + def collectdatawhile(self, period: int = ...) -> None: ... + def collectdatawhile_stop(self) -> None: ... + def collectdatawhile_slave(self, period) -> None: ... + def __getinitargs__(self): ... + +class QueryError: + query: Incomplete + def __init__(self, query) -> None: ... diff --git a/stubs/pywin32/win32/lib/win32serviceutil.pyi b/stubs/pywin32/win32/lib/win32serviceutil.pyi new file mode 100644 index 000000000000..d31471255b4a --- /dev/null +++ b/stubs/pywin32/win32/lib/win32serviceutil.pyi @@ -0,0 +1,81 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Sequence + +error = RuntimeError + +def LocatePythonServiceExe(exe: Incomplete | None = ...): ... +def SmartOpenService(hscm, name, access): ... +def LocateSpecificServiceExe(serviceName): ... +def InstallPerfmonForService(serviceName, iniName, dllName: Incomplete | None = ...) -> None: ... +def InstallService( + pythonClassString, + serviceName, + displayName, + startType: Incomplete | None = ..., + errorControl: Incomplete | None = ..., + bRunInteractive: int = ..., + serviceDeps: Incomplete | None = ..., + userName: Incomplete | None = ..., + password: Incomplete | None = ..., + exeName: Incomplete | None = ..., + perfMonIni: Incomplete | None = ..., + perfMonDll: Incomplete | None = ..., + exeArgs: Incomplete | None = ..., + description: Incomplete | None = ..., + delayedstart: Incomplete | None = ..., +) -> None: ... +def ChangeServiceConfig( + pythonClassString, + serviceName, + startType: Incomplete | None = ..., + errorControl: Incomplete | None = ..., + bRunInteractive: int = ..., + serviceDeps: Incomplete | None = ..., + userName: Incomplete | None = ..., + password: Incomplete | None = ..., + exeName: Incomplete | None = ..., + displayName: Incomplete | None = ..., + perfMonIni: Incomplete | None = ..., + perfMonDll: Incomplete | None = ..., + exeArgs: Incomplete | None = ..., + description: Incomplete | None = ..., + delayedstart: Incomplete | None = ..., +) -> None: ... +def InstallPythonClassString(pythonClassString, serviceName) -> None: ... +def SetServiceCustomOption(serviceName, option, value) -> None: ... +def GetServiceCustomOption(serviceName, option, defaultValue: Incomplete | None = ...): ... +def RemoveService(serviceName) -> None: ... +def ControlService(serviceName, code, machine: Incomplete | None = ...): ... +def WaitForServiceStatus(serviceName, status, waitSecs, machine: Incomplete | None = ...) -> None: ... +def StopServiceWithDeps(serviceName, machine: Incomplete | None = ..., waitSecs: int = ...) -> None: ... +def StopService(serviceName, machine: Incomplete | None = ...): ... +def StartService(serviceName, args: Incomplete | None = ..., machine: Incomplete | None = ...) -> None: ... +def RestartService( + serviceName, args: Incomplete | None = ..., waitSeconds: int = ..., machine: Incomplete | None = ... +) -> None: ... +def DebugService(cls, argv=...) -> None: ... +def GetServiceClassString(cls, argv: Incomplete | None = ...): ... +def QueryServiceStatus(serviceName, machine: Incomplete | None = ...): ... +def usage() -> None: ... +def HandleCommandLine( + cls: type[ServiceFramework], + serviceClassString: Incomplete | None = ..., + argv: Sequence[str] | None = ..., + customInstallOptions: str = ..., + customOptionHandler: Incomplete | None = ..., +): ... + +class ServiceFramework: + ssh: Incomplete + checkPoint: int + def __init__(self, args: Iterable[str]) -> None: ... + def GetAcceptedControls(self): ... + def ReportServiceStatus( + self, serviceStatus, waitHint: int = ..., win32ExitCode: int = ..., svcExitCode: int = ... + ) -> None: ... + def SvcInterrogate(self) -> None: ... + def SvcOther(self, control) -> None: ... + def ServiceCtrlHandler(self, control): ... + def SvcOtherEx(self, control, event_type, data): ... + def ServiceCtrlHandlerEx(self, control, event_type, data): ... + def SvcRun(self) -> None: ... diff --git a/stubs/pywin32/win32/lib/win32timezone.pyi b/stubs/pywin32/win32/lib/win32timezone.pyi new file mode 100644 index 000000000000..15508cc26158 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32timezone.pyi @@ -0,0 +1,120 @@ +import datetime +from _operator import _SupportsComparison +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import ClassVar, TypeVar, overload, type_check_only +from typing_extensions import Self + +_RangeMapKT = TypeVar("_RangeMapKT", bound=_SupportsComparison) + +_T = TypeVar("_T") +_VT = TypeVar("_VT") + +log: Logger + +class _SimpleStruct: + def __init__(self, *args, **kw) -> None: ... + def field_names(self) -> list[str]: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class SYSTEMTIME(_SimpleStruct): ... +class TIME_ZONE_INFORMATION(_SimpleStruct): ... +class DYNAMIC_TIME_ZONE_INFORMATION(_SimpleStruct): ... + +class TimeZoneDefinition(DYNAMIC_TIME_ZONE_INFORMATION): + def __init__(self, *args, **kwargs) -> None: ... + # TIME_ZONE_INFORMATION fields as obtained by __getattribute__ + bias: datetime.timedelta + standard_name: str + standard_start: SYSTEMTIME + standard_bias: datetime.timedelta + daylight_name: str + daylight_start: SYSTEMTIME + daylight_bias: datetime.timedelta + def __getattribute__(self, attr: str): ... + @classmethod + def current(cls) -> tuple[int, Self]: ... + def set(self) -> None: ... + def copy(self) -> Self: ... + def locate_daylight_start(self, year) -> datetime.datetime: ... + def locate_standard_start(self, year) -> datetime.datetime: ... + +class TimeZoneInfo(datetime.tzinfo): + tzRegKey: ClassVar[str] + timeZoneName: str + fixedStandardTime: bool + def __init__(self, param: str | TimeZoneDefinition, fix_standard_time: bool = False) -> None: ... + + @overload # type: ignore[override] # Split definition into overrides + def tzname(self, dt: datetime.datetime) -> str: ... + @overload + def tzname(self, dt: None) -> None: ... + + def getWinInfo(self, targetYear: int) -> TimeZoneDefinition: ... + + @overload # type: ignore[override] # False-positive, our overload covers all base types + def utcoffset(self, dt: None) -> None: ... + @overload + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... + + @overload # type: ignore[override] # False-positive, our overload covers all base types + def dst(self, dt: None) -> None: ... + @overload + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... + + def GetDSTStartTime(self, year: int) -> datetime.datetime: ... + def GetDSTEndTime(self, year: int) -> datetime.datetime: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + @classmethod + def local(cls) -> Self: ... + @classmethod + def utc(cls) -> Self: ... + @staticmethod + def get_sorted_time_zone_names() -> list[str]: ... + @staticmethod + def get_all_time_zones() -> list[TimeZoneInfo]: ... + @staticmethod + def get_sorted_time_zones(key: Incomplete | None = ...): ... + +def utcnow() -> datetime.datetime: ... +def now() -> datetime.datetime: ... +def GetTZCapabilities() -> dict[str, bool]: ... + +class DLLHandleCache: + def __getitem__(self, filename: str) -> int: ... + +DLLCache: DLLHandleCache + +def resolveMUITimeZone(spec: str) -> str | None: ... + +class RangeMap(dict[_RangeMapKT, _VT]): + sort_params: Mapping[str, Incomplete] + match: Callable[[_RangeMapKT, _RangeMapKT], bool] + def __init__( + self, + source: SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]], + sort_params: Mapping[str, Incomplete] = {}, + key_match_comparator: Callable[[_RangeMapKT, _RangeMapKT], bool] = ..., + ) -> None: ... + @classmethod + def left(cls, source: SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]]) -> Self: ... + def __getitem__(self, item: _RangeMapKT) -> _VT: ... + + @overload # type: ignore[override] # Signature simplified over dict and Mapping + def get(self, key: _RangeMapKT, default: _T) -> _VT | _T: ... + @overload + def get(self, key: _RangeMapKT, default: None = None) -> _VT | None: ... + + def bounds(self) -> tuple[_RangeMapKT, _RangeMapKT]: ... + + @type_check_only + class RangeValueUndefined: ... + + undefined_value: RangeValueUndefined + + class Item(int): ... + first_item: Item + last_item: Item diff --git a/stubs/pywin32/win32/lib/win32verstamp.pyi b/stubs/pywin32/win32/lib/win32verstamp.pyi new file mode 100644 index 000000000000..cac01f8475e1 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32verstamp.pyi @@ -0,0 +1,21 @@ +from typing import Final + +VS_FFI_SIGNATURE: Final = -17890115 +VS_FFI_STRUCVERSION: Final = 0x00010000 +VS_FFI_FILEFLAGSMASK: Final = 0x0000003F +VOS_NT_WINDOWS32: Final = 0x00040004 +null_byte: Final = b"\0" + +def file_flags(debug): ... +def file_type(is_dll): ... +def VS_FIXEDFILEINFO(maj, min, sub, build, debug: int = 0, is_dll: int = 1): ... +def nullterm(s): ... +def pad32(s, extra: int = 2): ... +def addlen(s): ... +def String(key, value): ... +def StringTable(key, data): ... +def StringFileInfo(data): ... +def Var(key, value): ... +def VarFileInfo(data): ... +def VS_VERSION_INFO(maj, min, sub, build, sdata, vdata, debug: int = 0, is_dll: int = 1): ... +def stamp(pathname, options) -> None: ... diff --git a/stubs/pywin32/win32/lib/winerror.pyi b/stubs/pywin32/win32/lib/winerror.pyi new file mode 100644 index 000000000000..a40ca554ca0b --- /dev/null +++ b/stubs/pywin32/win32/lib/winerror.pyi @@ -0,0 +1,7270 @@ +from typing import Final + +ERROR_INSTALL_SERVICE: Final = 1601 +ERROR_BAD_DATABASE_VERSION: Final = 1613 +win16_E_NOTIMPL: Final = -2147483647 +win16_E_OUTOFMEMORY: Final = -2147483646 +win16_E_INVALIDARG: Final = -2147483645 +win16_E_NOINTERFACE: Final = -2147483644 +win16_E_POINTER: Final = -2147483643 +win16_E_HANDLE: Final = -2147483642 +win16_E_ABORT: Final = -2147483641 +win16_E_FAIL: Final = -2147483640 +win16_E_ACCESSDENIED: Final = -2147483639 +CERTDB_E_JET_ERROR: Final = -2146873344 + +FACILITY_NULL: Final = 0 +FACILITY_RPC: Final = 1 +FACILITY_DISPATCH: Final = 2 +FACILITY_STORAGE: Final = 3 +FACILITY_ITF: Final = 4 +FACILITY_WIN32: Final = 7 +FACILITY_WINDOWS: Final = 8 +FACILITY_SSPI: Final = 9 +FACILITY_SECURITY: Final = 9 +FACILITY_CONTROL: Final = 10 +FACILITY_CERT: Final = 11 +FACILITY_INTERNET: Final = 12 +FACILITY_MEDIASERVER: Final = 13 +FACILITY_MSMQ: Final = 14 +FACILITY_SETUPAPI: Final = 15 +FACILITY_SCARD: Final = 16 +FACILITY_COMPLUS: Final = 17 +FACILITY_AAF: Final = 18 +FACILITY_URT: Final = 19 +FACILITY_ACS: Final = 20 +FACILITY_DPLAY: Final = 21 +FACILITY_UMI: Final = 22 +FACILITY_SXS: Final = 23 +FACILITY_WINDOWS_CE: Final = 24 +FACILITY_HTTP: Final = 25 +FACILITY_USERMODE_COMMONLOG: Final = 26 +FACILITY_WER: Final = 27 +FACILITY_USERMODE_FILTER_MANAGER: Final = 31 +FACILITY_BACKGROUNDCOPY: Final = 32 +FACILITY_CONFIGURATION: Final = 33 +FACILITY_WIA: Final = 33 +FACILITY_STATE_MANAGEMENT: Final = 34 +FACILITY_METADIRECTORY: Final = 35 +FACILITY_WINDOWSUPDATE: Final = 36 +FACILITY_DIRECTORYSERVICE: Final = 37 +FACILITY_GRAPHICS: Final = 38 +FACILITY_SHELL: Final = 39 +FACILITY_NAP: Final = 39 +FACILITY_TPM_SERVICES: Final = 40 +FACILITY_TPM_SOFTWARE: Final = 41 +FACILITY_UI: Final = 42 +FACILITY_XAML: Final = 43 +FACILITY_ACTION_QUEUE: Final = 44 +FACILITY_PLA: Final = 48 +FACILITY_WINDOWS_SETUP: Final = 48 +FACILITY_FVE: Final = 49 +FACILITY_FWP: Final = 50 +FACILITY_WINRM: Final = 51 +FACILITY_NDIS: Final = 52 +FACILITY_USERMODE_HYPERVISOR: Final = 53 +FACILITY_CMI: Final = 54 +FACILITY_USERMODE_VIRTUALIZATION: Final = 55 +FACILITY_USERMODE_VOLMGR: Final = 56 +FACILITY_BCD: Final = 57 +FACILITY_USERMODE_VHD: Final = 58 +FACILITY_USERMODE_HNS: Final = 59 +FACILITY_SDIAG: Final = 60 +FACILITY_WEBSERVICES: Final = 61 +FACILITY_WINPE: Final = 61 +FACILITY_WPN: Final = 62 +FACILITY_WINDOWS_STORE: Final = 63 +FACILITY_INPUT: Final = 64 +FACILITY_QUIC: Final = 65 +FACILITY_EAP: Final = 66 +FACILITY_IORING: Final = 70 +FACILITY_WINDOWS_DEFENDER: Final = 80 +FACILITY_OPC: Final = 81 +FACILITY_XPS: Final = 82 +FACILITY_MBN: Final = 84 +FACILITY_POWERSHELL: Final = 84 +FACILITY_RAS: Final = 83 +FACILITY_P2P_INT: Final = 98 +FACILITY_P2P: Final = 99 +FACILITY_DAF: Final = 100 +FACILITY_BLUETOOTH_ATT: Final = 101 +FACILITY_AUDIO: Final = 102 +FACILITY_STATEREPOSITORY: Final = 103 +FACILITY_VISUALCPP: Final = 109 +FACILITY_SCRIPT: Final = 112 +FACILITY_PARSE: Final = 113 +FACILITY_BLB: Final = 120 +FACILITY_BLB_CLI: Final = 121 +FACILITY_WSBAPP: Final = 122 +FACILITY_BLBUI: Final = 128 +FACILITY_USN: Final = 129 +FACILITY_USERMODE_VOLSNAP: Final = 130 +FACILITY_TIERING: Final = 131 +FACILITY_WSB_ONLINE: Final = 133 +FACILITY_ONLINE_ID: Final = 134 +FACILITY_DEVICE_UPDATE_AGENT: Final = 135 +FACILITY_DRVSERVICING: Final = 136 +FACILITY_DLS: Final = 153 +FACILITY_DELIVERY_OPTIMIZATION: Final = 208 +FACILITY_USERMODE_SPACES: Final = 231 +FACILITY_USER_MODE_SECURITY_CORE: Final = 232 +FACILITY_USERMODE_LICENSING: Final = 234 +FACILITY_SOS: Final = 160 +FACILITY_OCP_UPDATE_AGENT: Final = 173 +FACILITY_DEBUGGERS: Final = 176 +FACILITY_SPP: Final = 256 +FACILITY_RESTORE: Final = 256 +FACILITY_DMSERVER: Final = 256 +FACILITY_DEPLOYMENT_SERVICES_SERVER: Final = 257 +FACILITY_DEPLOYMENT_SERVICES_IMAGING: Final = 258 +FACILITY_DEPLOYMENT_SERVICES_MANAGEMENT: Final = 259 +FACILITY_DEPLOYMENT_SERVICES_UTIL: Final = 260 +FACILITY_DEPLOYMENT_SERVICES_BINLSVC: Final = 261 +FACILITY_DEPLOYMENT_SERVICES_PXE: Final = 263 +FACILITY_DEPLOYMENT_SERVICES_TFTP: Final = 264 +FACILITY_DEPLOYMENT_SERVICES_TRANSPORT_MANAGEMENT: Final = 272 +FACILITY_DEPLOYMENT_SERVICES_DRIVER_PROVISIONING: Final = 278 +FACILITY_DEPLOYMENT_SERVICES_MULTICAST_SERVER: Final = 289 +FACILITY_DEPLOYMENT_SERVICES_MULTICAST_CLIENT: Final = 290 +FACILITY_DEPLOYMENT_SERVICES_CONTENT_PROVIDER: Final = 293 +FACILITY_HSP_SERVICES: Final = 296 +FACILITY_HSP_SOFTWARE: Final = 297 +FACILITY_LINGUISTIC_SERVICES: Final = 305 +FACILITY_AUDIOSTREAMING: Final = 1094 +FACILITY_TTD: Final = 1490 +FACILITY_ACCELERATOR: Final = 1536 +FACILITY_WMAAECMA: Final = 1996 +FACILITY_DIRECTMUSIC: Final = 2168 +FACILITY_DIRECT3D10: Final = 2169 +FACILITY_DXGI: Final = 2170 +FACILITY_DXGI_DDI: Final = 2171 +FACILITY_DIRECT3D11: Final = 2172 +FACILITY_DIRECT3D11_DEBUG: Final = 2173 +FACILITY_DIRECT3D12: Final = 2174 +FACILITY_DIRECT3D12_DEBUG: Final = 2175 +FACILITY_DXCORE: Final = 2176 +FACILITY_PRESENTATION: Final = 2177 +FACILITY_LEAP: Final = 2184 +FACILITY_AUDCLNT: Final = 2185 +FACILITY_WINCODEC_DWRITE_DWM: Final = 2200 +FACILITY_WINML: Final = 2192 +FACILITY_DIRECT2D: Final = 2201 +FACILITY_DEFRAG: Final = 2304 +FACILITY_USERMODE_SDBUS: Final = 2305 +FACILITY_JSCRIPT: Final = 2306 +FACILITY_PIDGENX: Final = 2561 +FACILITY_EAS: Final = 85 +FACILITY_WEB: Final = 885 +FACILITY_WEB_SOCKET: Final = 886 +FACILITY_MOBILE: Final = 1793 +FACILITY_SQLITE: Final = 1967 +FACILITY_SERVICE_FABRIC: Final = 1968 +FACILITY_UTC: Final = 1989 +FACILITY_WEP: Final = 2049 +FACILITY_SYNCENGINE: Final = 2050 +FACILITY_XBOX: Final = 2339 +FACILITY_GAME: Final = 2340 +FACILITY_PIX: Final = 2748 +ERROR_SUCCESS: Final = 0 +NO_ERROR: Final = 0 +SEC_E_OK: Final = 0x00000000 +ERROR_INVALID_FUNCTION: Final = 1 +ERROR_FILE_NOT_FOUND: Final = 2 +ERROR_PATH_NOT_FOUND: Final = 3 +ERROR_TOO_MANY_OPEN_FILES: Final = 4 +ERROR_ACCESS_DENIED: Final = 5 +ERROR_INVALID_HANDLE: Final = 6 +ERROR_ARENA_TRASHED: Final = 7 +ERROR_NOT_ENOUGH_MEMORY: Final = 8 +ERROR_INVALID_BLOCK: Final = 9 +ERROR_BAD_ENVIRONMENT: Final = 10 +ERROR_BAD_FORMAT: Final = 11 +ERROR_INVALID_ACCESS: Final = 12 +ERROR_INVALID_DATA: Final = 13 +ERROR_OUTOFMEMORY: Final = 14 +ERROR_INVALID_DRIVE: Final = 15 +ERROR_CURRENT_DIRECTORY: Final = 16 +ERROR_NOT_SAME_DEVICE: Final = 17 +ERROR_NO_MORE_FILES: Final = 18 +ERROR_WRITE_PROTECT: Final = 19 +ERROR_BAD_UNIT: Final = 20 +ERROR_NOT_READY: Final = 21 +ERROR_BAD_COMMAND: Final = 22 +ERROR_CRC: Final = 23 +ERROR_BAD_LENGTH: Final = 24 +ERROR_SEEK: Final = 25 +ERROR_NOT_DOS_DISK: Final = 26 +ERROR_SECTOR_NOT_FOUND: Final = 27 +ERROR_OUT_OF_PAPER: Final = 28 +ERROR_WRITE_FAULT: Final = 29 +ERROR_READ_FAULT: Final = 30 +ERROR_GEN_FAILURE: Final = 31 +ERROR_SHARING_VIOLATION: Final = 32 +ERROR_LOCK_VIOLATION: Final = 33 +ERROR_WRONG_DISK: Final = 34 +ERROR_SHARING_BUFFER_EXCEEDED: Final = 36 +ERROR_HANDLE_EOF: Final = 38 +ERROR_HANDLE_DISK_FULL: Final = 39 +ERROR_NOT_SUPPORTED: Final = 50 +ERROR_REM_NOT_LIST: Final = 51 +ERROR_DUP_NAME: Final = 52 +ERROR_BAD_NETPATH: Final = 53 +ERROR_NETWORK_BUSY: Final = 54 +ERROR_DEV_NOT_EXIST: Final = 55 +ERROR_TOO_MANY_CMDS: Final = 56 +ERROR_ADAP_HDW_ERR: Final = 57 +ERROR_BAD_NET_RESP: Final = 58 +ERROR_UNEXP_NET_ERR: Final = 59 +ERROR_BAD_REM_ADAP: Final = 60 +ERROR_PRINTQ_FULL: Final = 61 +ERROR_NO_SPOOL_SPACE: Final = 62 +ERROR_PRINT_CANCELLED: Final = 63 +ERROR_NETNAME_DELETED: Final = 64 +ERROR_NETWORK_ACCESS_DENIED: Final = 65 +ERROR_BAD_DEV_TYPE: Final = 66 +ERROR_BAD_NET_NAME: Final = 67 +ERROR_TOO_MANY_NAMES: Final = 68 +ERROR_TOO_MANY_SESS: Final = 69 +ERROR_SHARING_PAUSED: Final = 70 +ERROR_REQ_NOT_ACCEP: Final = 71 +ERROR_REDIR_PAUSED: Final = 72 +ERROR_FILE_EXISTS: Final = 80 +ERROR_CANNOT_MAKE: Final = 82 +ERROR_FAIL_I24: Final = 83 +ERROR_OUT_OF_STRUCTURES: Final = 84 +ERROR_ALREADY_ASSIGNED: Final = 85 +ERROR_INVALID_PASSWORD: Final = 86 +ERROR_INVALID_PARAMETER: Final = 87 +ERROR_NET_WRITE_FAULT: Final = 88 +ERROR_NO_PROC_SLOTS: Final = 89 +ERROR_TOO_MANY_SEMAPHORES: Final = 100 +ERROR_EXCL_SEM_ALREADY_OWNED: Final = 101 +ERROR_SEM_IS_SET: Final = 102 +ERROR_TOO_MANY_SEM_REQUESTS: Final = 103 +ERROR_INVALID_AT_INTERRUPT_TIME: Final = 104 +ERROR_SEM_OWNER_DIED: Final = 105 +ERROR_SEM_USER_LIMIT: Final = 106 +ERROR_DISK_CHANGE: Final = 107 +ERROR_DRIVE_LOCKED: Final = 108 +ERROR_BROKEN_PIPE: Final = 109 +ERROR_OPEN_FAILED: Final = 110 +ERROR_BUFFER_OVERFLOW: Final = 111 +ERROR_DISK_FULL: Final = 112 +ERROR_NO_MORE_SEARCH_HANDLES: Final = 113 +ERROR_INVALID_TARGET_HANDLE: Final = 114 +ERROR_INVALID_CATEGORY: Final = 117 +ERROR_INVALID_VERIFY_SWITCH: Final = 118 +ERROR_BAD_DRIVER_LEVEL: Final = 119 +ERROR_CALL_NOT_IMPLEMENTED: Final = 120 +ERROR_SEM_TIMEOUT: Final = 121 +ERROR_INSUFFICIENT_BUFFER: Final = 122 +ERROR_INVALID_NAME: Final = 123 +ERROR_INVALID_LEVEL: Final = 124 +ERROR_NO_VOLUME_LABEL: Final = 125 +ERROR_MOD_NOT_FOUND: Final = 126 +ERROR_PROC_NOT_FOUND: Final = 127 +ERROR_WAIT_NO_CHILDREN: Final = 128 +ERROR_CHILD_NOT_COMPLETE: Final = 129 +ERROR_DIRECT_ACCESS_HANDLE: Final = 130 +ERROR_NEGATIVE_SEEK: Final = 131 +ERROR_SEEK_ON_DEVICE: Final = 132 +ERROR_IS_JOIN_TARGET: Final = 133 +ERROR_IS_JOINED: Final = 134 +ERROR_IS_SUBSTED: Final = 135 +ERROR_NOT_JOINED: Final = 136 +ERROR_NOT_SUBSTED: Final = 137 +ERROR_JOIN_TO_JOIN: Final = 138 +ERROR_SUBST_TO_SUBST: Final = 139 +ERROR_JOIN_TO_SUBST: Final = 140 +ERROR_SUBST_TO_JOIN: Final = 141 +ERROR_BUSY_DRIVE: Final = 142 +ERROR_SAME_DRIVE: Final = 143 +ERROR_DIR_NOT_ROOT: Final = 144 +ERROR_DIR_NOT_EMPTY: Final = 145 +ERROR_IS_SUBST_PATH: Final = 146 +ERROR_IS_JOIN_PATH: Final = 147 +ERROR_PATH_BUSY: Final = 148 +ERROR_IS_SUBST_TARGET: Final = 149 +ERROR_SYSTEM_TRACE: Final = 150 +ERROR_INVALID_EVENT_COUNT: Final = 151 +ERROR_TOO_MANY_MUXWAITERS: Final = 152 +ERROR_INVALID_LIST_FORMAT: Final = 153 +ERROR_LABEL_TOO_LONG: Final = 154 +ERROR_TOO_MANY_TCBS: Final = 155 +ERROR_SIGNAL_REFUSED: Final = 156 +ERROR_DISCARDED: Final = 157 +ERROR_NOT_LOCKED: Final = 158 +ERROR_BAD_THREADID_ADDR: Final = 159 +ERROR_BAD_ARGUMENTS: Final = 160 +ERROR_BAD_PATHNAME: Final = 161 +ERROR_SIGNAL_PENDING: Final = 162 +ERROR_MAX_THRDS_REACHED: Final = 164 +ERROR_LOCK_FAILED: Final = 167 +ERROR_BUSY: Final = 170 +ERROR_DEVICE_SUPPORT_IN_PROGRESS: Final = 171 +ERROR_CANCEL_VIOLATION: Final = 173 +ERROR_ATOMIC_LOCKS_NOT_SUPPORTED: Final = 174 +ERROR_INVALID_SEGMENT_NUMBER: Final = 180 +ERROR_INVALID_ORDINAL: Final = 182 +ERROR_ALREADY_EXISTS: Final = 183 +ERROR_INVALID_FLAG_NUMBER: Final = 186 +ERROR_SEM_NOT_FOUND: Final = 187 +ERROR_INVALID_STARTING_CODESEG: Final = 188 +ERROR_INVALID_STACKSEG: Final = 189 +ERROR_INVALID_MODULETYPE: Final = 190 +ERROR_INVALID_EXE_SIGNATURE: Final = 191 +ERROR_EXE_MARKED_INVALID: Final = 192 +ERROR_BAD_EXE_FORMAT: Final = 193 +ERROR_ITERATED_DATA_EXCEEDS_64k: Final = 194 +ERROR_INVALID_MINALLOCSIZE: Final = 195 +ERROR_DYNLINK_FROM_INVALID_RING: Final = 196 +ERROR_IOPL_NOT_ENABLED: Final = 197 +ERROR_INVALID_SEGDPL: Final = 198 +ERROR_AUTODATASEG_EXCEEDS_64k: Final = 199 +ERROR_RING2SEG_MUST_BE_MOVABLE: Final = 200 +ERROR_RELOC_CHAIN_XEEDS_SEGLIM: Final = 201 +ERROR_INFLOOP_IN_RELOC_CHAIN: Final = 202 +ERROR_ENVVAR_NOT_FOUND: Final = 203 +ERROR_NO_SIGNAL_SENT: Final = 205 +ERROR_FILENAME_EXCED_RANGE: Final = 206 +ERROR_RING2_STACK_IN_USE: Final = 207 +ERROR_META_EXPANSION_TOO_LONG: Final = 208 +ERROR_INVALID_SIGNAL_NUMBER: Final = 209 +ERROR_THREAD_1_INACTIVE: Final = 210 +ERROR_LOCKED: Final = 212 +ERROR_TOO_MANY_MODULES: Final = 214 +ERROR_NESTING_NOT_ALLOWED: Final = 215 +ERROR_EXE_MACHINE_TYPE_MISMATCH: Final = 216 +ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY: Final = 217 +ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY: Final = 218 +ERROR_FILE_CHECKED_OUT: Final = 220 +ERROR_CHECKOUT_REQUIRED: Final = 221 +ERROR_BAD_FILE_TYPE: Final = 222 +ERROR_FILE_TOO_LARGE: Final = 223 +ERROR_FORMS_AUTH_REQUIRED: Final = 224 +ERROR_VIRUS_INFECTED: Final = 225 +ERROR_VIRUS_DELETED: Final = 226 +ERROR_PIPE_LOCAL: Final = 229 +ERROR_BAD_PIPE: Final = 230 +ERROR_PIPE_BUSY: Final = 231 +ERROR_NO_DATA: Final = 232 +ERROR_PIPE_NOT_CONNECTED: Final = 233 +ERROR_MORE_DATA: Final = 234 +ERROR_NO_WORK_DONE: Final = 235 +ERROR_VC_DISCONNECTED: Final = 240 +ERROR_INVALID_EA_NAME: Final = 254 +ERROR_EA_LIST_INCONSISTENT: Final = 255 +WAIT_TIMEOUT: Final = 258 +ERROR_NO_MORE_ITEMS: Final = 259 +ERROR_CANNOT_COPY: Final = 266 +ERROR_DIRECTORY: Final = 267 +ERROR_EAS_DIDNT_FIT: Final = 275 +ERROR_EA_FILE_CORRUPT: Final = 276 +ERROR_EA_TABLE_FULL: Final = 277 +ERROR_INVALID_EA_HANDLE: Final = 278 +ERROR_EAS_NOT_SUPPORTED: Final = 282 +ERROR_NOT_OWNER: Final = 288 +ERROR_TOO_MANY_POSTS: Final = 298 +ERROR_PARTIAL_COPY: Final = 299 +ERROR_OPLOCK_NOT_GRANTED: Final = 300 +ERROR_INVALID_OPLOCK_PROTOCOL: Final = 301 +ERROR_DISK_TOO_FRAGMENTED: Final = 302 +ERROR_DELETE_PENDING: Final = 303 +ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING: Final = 304 +ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME: Final = 305 +ERROR_SECURITY_STREAM_IS_INCONSISTENT: Final = 306 +ERROR_INVALID_LOCK_RANGE: Final = 307 +ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT: Final = 308 +ERROR_NOTIFICATION_GUID_ALREADY_DEFINED: Final = 309 +ERROR_INVALID_EXCEPTION_HANDLER: Final = 310 +ERROR_DUPLICATE_PRIVILEGES: Final = 311 +ERROR_NO_RANGES_PROCESSED: Final = 312 +ERROR_NOT_ALLOWED_ON_SYSTEM_FILE: Final = 313 +ERROR_DISK_RESOURCES_EXHAUSTED: Final = 314 +ERROR_INVALID_TOKEN: Final = 315 +ERROR_DEVICE_FEATURE_NOT_SUPPORTED: Final = 316 +ERROR_MR_MID_NOT_FOUND: Final = 317 +ERROR_SCOPE_NOT_FOUND: Final = 318 +ERROR_UNDEFINED_SCOPE: Final = 319 +ERROR_INVALID_CAP: Final = 320 +ERROR_DEVICE_UNREACHABLE: Final = 321 +ERROR_DEVICE_NO_RESOURCES: Final = 322 +ERROR_DATA_CHECKSUM_ERROR: Final = 323 +ERROR_INTERMIXED_KERNEL_EA_OPERATION: Final = 324 +ERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED: Final = 326 +ERROR_OFFSET_ALIGNMENT_VIOLATION: Final = 327 +ERROR_INVALID_FIELD_IN_PARAMETER_LIST: Final = 328 +ERROR_OPERATION_IN_PROGRESS: Final = 329 +ERROR_BAD_DEVICE_PATH: Final = 330 +ERROR_TOO_MANY_DESCRIPTORS: Final = 331 +ERROR_SCRUB_DATA_DISABLED: Final = 332 +ERROR_NOT_REDUNDANT_STORAGE: Final = 333 +ERROR_RESIDENT_FILE_NOT_SUPPORTED: Final = 334 +ERROR_COMPRESSED_FILE_NOT_SUPPORTED: Final = 335 +ERROR_DIRECTORY_NOT_SUPPORTED: Final = 336 +ERROR_NOT_READ_FROM_COPY: Final = 337 +ERROR_FT_WRITE_FAILURE: Final = 338 +ERROR_FT_DI_SCAN_REQUIRED: Final = 339 +ERROR_INVALID_KERNEL_INFO_VERSION: Final = 340 +ERROR_INVALID_PEP_INFO_VERSION: Final = 341 +ERROR_OBJECT_NOT_EXTERNALLY_BACKED: Final = 342 +ERROR_EXTERNAL_BACKING_PROVIDER_UNKNOWN: Final = 343 +ERROR_COMPRESSION_NOT_BENEFICIAL: Final = 344 +ERROR_STORAGE_TOPOLOGY_ID_MISMATCH: Final = 345 +ERROR_BLOCKED_BY_PARENTAL_CONTROLS: Final = 346 +ERROR_BLOCK_TOO_MANY_REFERENCES: Final = 347 +ERROR_MARKED_TO_DISALLOW_WRITES: Final = 348 +ERROR_ENCLAVE_FAILURE: Final = 349 +ERROR_FAIL_NOACTION_REBOOT: Final = 350 +ERROR_FAIL_SHUTDOWN: Final = 351 +ERROR_FAIL_RESTART: Final = 352 +ERROR_MAX_SESSIONS_REACHED: Final = 353 +ERROR_NETWORK_ACCESS_DENIED_EDP: Final = 354 +ERROR_DEVICE_HINT_NAME_BUFFER_TOO_SMALL: Final = 355 +ERROR_EDP_POLICY_DENIES_OPERATION: Final = 356 +ERROR_EDP_DPL_POLICY_CANT_BE_SATISFIED: Final = 357 +ERROR_CLOUD_FILE_SYNC_ROOT_METADATA_CORRUPT: Final = 358 +ERROR_DEVICE_IN_MAINTENANCE: Final = 359 +ERROR_NOT_SUPPORTED_ON_DAX: Final = 360 +ERROR_DAX_MAPPING_EXISTS: Final = 361 +ERROR_CLOUD_FILE_PROVIDER_NOT_RUNNING: Final = 362 +ERROR_CLOUD_FILE_METADATA_CORRUPT: Final = 363 +ERROR_CLOUD_FILE_METADATA_TOO_LARGE: Final = 364 +ERROR_CLOUD_FILE_PROPERTY_BLOB_TOO_LARGE: Final = 365 +ERROR_CLOUD_FILE_PROPERTY_BLOB_CHECKSUM_MISMATCH: Final = 366 +ERROR_CHILD_PROCESS_BLOCKED: Final = 367 +ERROR_STORAGE_LOST_DATA_PERSISTENCE: Final = 368 +ERROR_FILE_SYSTEM_VIRTUALIZATION_UNAVAILABLE: Final = 369 +ERROR_FILE_SYSTEM_VIRTUALIZATION_METADATA_CORRUPT: Final = 370 +ERROR_FILE_SYSTEM_VIRTUALIZATION_BUSY: Final = 371 +ERROR_FILE_SYSTEM_VIRTUALIZATION_PROVIDER_UNKNOWN: Final = 372 +ERROR_GDI_HANDLE_LEAK: Final = 373 +ERROR_CLOUD_FILE_TOO_MANY_PROPERTY_BLOBS: Final = 374 +ERROR_CLOUD_FILE_PROPERTY_VERSION_NOT_SUPPORTED: Final = 375 +ERROR_NOT_A_CLOUD_FILE: Final = 376 +ERROR_CLOUD_FILE_NOT_IN_SYNC: Final = 377 +ERROR_CLOUD_FILE_ALREADY_CONNECTED: Final = 378 +ERROR_CLOUD_FILE_NOT_SUPPORTED: Final = 379 +ERROR_CLOUD_FILE_INVALID_REQUEST: Final = 380 +ERROR_CLOUD_FILE_READ_ONLY_VOLUME: Final = 381 +ERROR_CLOUD_FILE_CONNECTED_PROVIDER_ONLY: Final = 382 +ERROR_CLOUD_FILE_VALIDATION_FAILED: Final = 383 +ERROR_SMB1_NOT_AVAILABLE: Final = 384 +ERROR_FILE_SYSTEM_VIRTUALIZATION_INVALID_OPERATION: Final = 385 +ERROR_CLOUD_FILE_AUTHENTICATION_FAILED: Final = 386 +ERROR_CLOUD_FILE_INSUFFICIENT_RESOURCES: Final = 387 +ERROR_CLOUD_FILE_NETWORK_UNAVAILABLE: Final = 388 +ERROR_CLOUD_FILE_UNSUCCESSFUL: Final = 389 +ERROR_CLOUD_FILE_NOT_UNDER_SYNC_ROOT: Final = 390 +ERROR_CLOUD_FILE_IN_USE: Final = 391 +ERROR_CLOUD_FILE_PINNED: Final = 392 +ERROR_CLOUD_FILE_REQUEST_ABORTED: Final = 393 +ERROR_CLOUD_FILE_PROPERTY_CORRUPT: Final = 394 +ERROR_CLOUD_FILE_ACCESS_DENIED: Final = 395 +ERROR_CLOUD_FILE_INCOMPATIBLE_HARDLINKS: Final = 396 +ERROR_CLOUD_FILE_PROPERTY_LOCK_CONFLICT: Final = 397 +ERROR_CLOUD_FILE_REQUEST_CANCELED: Final = 398 +ERROR_EXTERNAL_SYSKEY_NOT_SUPPORTED: Final = 399 +ERROR_THREAD_MODE_ALREADY_BACKGROUND: Final = 400 +ERROR_THREAD_MODE_NOT_BACKGROUND: Final = 401 +ERROR_PROCESS_MODE_ALREADY_BACKGROUND: Final = 402 +ERROR_PROCESS_MODE_NOT_BACKGROUND: Final = 403 +ERROR_CLOUD_FILE_PROVIDER_TERMINATED: Final = 404 +ERROR_NOT_A_CLOUD_SYNC_ROOT: Final = 405 +ERROR_FILE_PROTECTED_UNDER_DPL: Final = 406 +ERROR_VOLUME_NOT_CLUSTER_ALIGNED: Final = 407 +ERROR_NO_PHYSICALLY_ALIGNED_FREE_SPACE_FOUND: Final = 408 +ERROR_APPX_FILE_NOT_ENCRYPTED: Final = 409 +ERROR_RWRAW_ENCRYPTED_FILE_NOT_ENCRYPTED: Final = 410 +ERROR_RWRAW_ENCRYPTED_INVALID_EDATAINFO_FILEOFFSET: Final = 411 +ERROR_RWRAW_ENCRYPTED_INVALID_EDATAINFO_FILERANGE: Final = 412 +ERROR_RWRAW_ENCRYPTED_INVALID_EDATAINFO_PARAMETER: Final = 413 +ERROR_LINUX_SUBSYSTEM_NOT_PRESENT: Final = 414 +ERROR_FT_READ_FAILURE: Final = 415 +ERROR_STORAGE_RESERVE_ID_INVALID: Final = 416 +ERROR_STORAGE_RESERVE_DOES_NOT_EXIST: Final = 417 +ERROR_STORAGE_RESERVE_ALREADY_EXISTS: Final = 418 +ERROR_STORAGE_RESERVE_NOT_EMPTY: Final = 419 +ERROR_NOT_A_DAX_VOLUME: Final = 420 +ERROR_NOT_DAX_MAPPABLE: Final = 421 +ERROR_TIME_SENSITIVE_THREAD: Final = 422 +ERROR_DPL_NOT_SUPPORTED_FOR_USER: Final = 423 +ERROR_CASE_DIFFERING_NAMES_IN_DIR: Final = 424 +ERROR_FILE_NOT_SUPPORTED: Final = 425 +ERROR_CLOUD_FILE_REQUEST_TIMEOUT: Final = 426 +ERROR_NO_TASK_QUEUE: Final = 427 +ERROR_SRC_SRV_DLL_LOAD_FAILED: Final = 428 +ERROR_NOT_SUPPORTED_WITH_BTT: Final = 429 +ERROR_ENCRYPTION_DISABLED: Final = 430 +ERROR_ENCRYPTING_METADATA_DISALLOWED: Final = 431 +ERROR_CANT_CLEAR_ENCRYPTION_FLAG: Final = 432 +ERROR_NO_SUCH_DEVICE: Final = 433 +ERROR_CLOUD_FILE_DEHYDRATION_DISALLOWED: Final = 434 +ERROR_FILE_SNAP_IN_PROGRESS: Final = 435 +ERROR_FILE_SNAP_USER_SECTION_NOT_SUPPORTED: Final = 436 +ERROR_FILE_SNAP_MODIFY_NOT_SUPPORTED: Final = 437 +ERROR_FILE_SNAP_IO_NOT_COORDINATED: Final = 438 +ERROR_FILE_SNAP_UNEXPECTED_ERROR: Final = 439 +ERROR_FILE_SNAP_INVALID_PARAMETER: Final = 440 +ERROR_UNSATISFIED_DEPENDENCIES: Final = 441 +ERROR_CASE_SENSITIVE_PATH: Final = 442 +ERROR_UNEXPECTED_NTCACHEMANAGER_ERROR: Final = 443 +ERROR_LINUX_SUBSYSTEM_UPDATE_REQUIRED: Final = 444 +ERROR_DLP_POLICY_WARNS_AGAINST_OPERATION: Final = 445 +ERROR_DLP_POLICY_DENIES_OPERATION: Final = 446 +ERROR_SECURITY_DENIES_OPERATION: Final = 447 +ERROR_UNTRUSTED_MOUNT_POINT: Final = 448 +ERROR_DLP_POLICY_SILENTLY_FAIL: Final = 449 +ERROR_CAPAUTHZ_NOT_DEVUNLOCKED: Final = 450 +ERROR_CAPAUTHZ_CHANGE_TYPE: Final = 451 +ERROR_CAPAUTHZ_NOT_PROVISIONED: Final = 452 +ERROR_CAPAUTHZ_NOT_AUTHORIZED: Final = 453 +ERROR_CAPAUTHZ_NO_POLICY: Final = 454 +ERROR_CAPAUTHZ_DB_CORRUPTED: Final = 455 +ERROR_CAPAUTHZ_SCCD_INVALID_CATALOG: Final = 456 +ERROR_CAPAUTHZ_SCCD_NO_AUTH_ENTITY: Final = 457 +ERROR_CAPAUTHZ_SCCD_PARSE_ERROR: Final = 458 +ERROR_CAPAUTHZ_SCCD_DEV_MODE_REQUIRED: Final = 459 +ERROR_CAPAUTHZ_SCCD_NO_CAPABILITY_MATCH: Final = 460 +ERROR_CIMFS_IMAGE_CORRUPT: Final = 470 +ERROR_CIMFS_IMAGE_VERSION_NOT_SUPPORTED: Final = 471 +ERROR_STORAGE_STACK_ACCESS_DENIED: Final = 472 +ERROR_INSUFFICIENT_VIRTUAL_ADDR_RESOURCES: Final = 473 +ERROR_INDEX_OUT_OF_BOUNDS: Final = 474 +ERROR_CLOUD_FILE_US_MESSAGE_TIMEOUT: Final = 475 +ERROR_NOT_A_DEV_VOLUME: Final = 476 +ERROR_FS_GUID_MISMATCH: Final = 477 +ERROR_CANT_ATTACH_TO_DEV_VOLUME: Final = 478 +ERROR_INVALID_CONFIG_VALUE: Final = 479 +ERROR_PNP_QUERY_REMOVE_DEVICE_TIMEOUT: Final = 480 +ERROR_PNP_QUERY_REMOVE_RELATED_DEVICE_TIMEOUT: Final = 481 +ERROR_PNP_QUERY_REMOVE_UNRELATED_DEVICE_TIMEOUT: Final = 482 +ERROR_DEVICE_HARDWARE_ERROR: Final = 483 +ERROR_INVALID_ADDRESS: Final = 487 +ERROR_HAS_SYSTEM_CRITICAL_FILES: Final = 488 +ERROR_ENCRYPTED_FILE_NOT_SUPPORTED: Final = 489 +ERROR_SPARSE_FILE_NOT_SUPPORTED: Final = 490 +ERROR_PAGEFILE_NOT_SUPPORTED: Final = 491 +ERROR_VOLUME_NOT_SUPPORTED: Final = 492 +ERROR_NOT_SUPPORTED_WITH_BYPASSIO: Final = 493 +ERROR_NO_BYPASSIO_DRIVER_SUPPORT: Final = 494 +ERROR_NOT_SUPPORTED_WITH_ENCRYPTION: Final = 495 +ERROR_NOT_SUPPORTED_WITH_COMPRESSION: Final = 496 +ERROR_NOT_SUPPORTED_WITH_REPLICATION: Final = 497 +ERROR_NOT_SUPPORTED_WITH_DEDUPLICATION: Final = 498 +ERROR_NOT_SUPPORTED_WITH_AUDITING: Final = 499 +ERROR_USER_PROFILE_LOAD: Final = 500 +ERROR_SESSION_KEY_TOO_SHORT: Final = 501 +ERROR_ACCESS_DENIED_APPDATA: Final = 502 +ERROR_NOT_SUPPORTED_WITH_MONITORING: Final = 503 +ERROR_NOT_SUPPORTED_WITH_SNAPSHOT: Final = 504 +ERROR_NOT_SUPPORTED_WITH_VIRTUALIZATION: Final = 505 +ERROR_BYPASSIO_FLT_NOT_SUPPORTED: Final = 506 +ERROR_DEVICE_RESET_REQUIRED: Final = 507 +ERROR_VOLUME_WRITE_ACCESS_DENIED: Final = 508 +ERROR_NOT_SUPPORTED_WITH_CACHED_HANDLE: Final = 509 +ERROR_FS_METADATA_INCONSISTENT: Final = 510 +ERROR_BLOCK_WEAK_REFERENCE_INVALID: Final = 511 +ERROR_BLOCK_SOURCE_WEAK_REFERENCE_INVALID: Final = 512 +ERROR_BLOCK_TARGET_WEAK_REFERENCE_INVALID: Final = 513 +ERROR_BLOCK_SHARED: Final = 514 +ERROR_VOLUME_UPGRADE_NOT_NEEDED: Final = 515 +ERROR_VOLUME_UPGRADE_PENDING: Final = 516 +ERROR_VOLUME_UPGRADE_DISABLED: Final = 517 +ERROR_VOLUME_UPGRADE_DISABLED_TILL_OS_DOWNGRADE_EXPIRED: Final = 518 +ERROR_ARITHMETIC_OVERFLOW: Final = 534 +ERROR_PIPE_CONNECTED: Final = 535 +ERROR_PIPE_LISTENING: Final = 536 +ERROR_VERIFIER_STOP: Final = 537 +ERROR_ABIOS_ERROR: Final = 538 +ERROR_WX86_WARNING: Final = 539 +ERROR_WX86_ERROR: Final = 540 +ERROR_TIMER_NOT_CANCELED: Final = 541 +ERROR_UNWIND: Final = 542 +ERROR_BAD_STACK: Final = 543 +ERROR_INVALID_UNWIND_TARGET: Final = 544 +ERROR_INVALID_PORT_ATTRIBUTES: Final = 545 +ERROR_PORT_MESSAGE_TOO_LONG: Final = 546 +ERROR_INVALID_QUOTA_LOWER: Final = 547 +ERROR_DEVICE_ALREADY_ATTACHED: Final = 548 +ERROR_INSTRUCTION_MISALIGNMENT: Final = 549 +ERROR_PROFILING_NOT_STARTED: Final = 550 +ERROR_PROFILING_NOT_STOPPED: Final = 551 +ERROR_COULD_NOT_INTERPRET: Final = 552 +ERROR_PROFILING_AT_LIMIT: Final = 553 +ERROR_CANT_WAIT: Final = 554 +ERROR_CANT_TERMINATE_SELF: Final = 555 +ERROR_UNEXPECTED_MM_CREATE_ERR: Final = 556 +ERROR_UNEXPECTED_MM_MAP_ERROR: Final = 557 +ERROR_UNEXPECTED_MM_EXTEND_ERR: Final = 558 +ERROR_BAD_FUNCTION_TABLE: Final = 559 +ERROR_NO_GUID_TRANSLATION: Final = 560 +ERROR_INVALID_LDT_SIZE: Final = 561 +ERROR_INVALID_LDT_OFFSET: Final = 563 +ERROR_INVALID_LDT_DESCRIPTOR: Final = 564 +ERROR_TOO_MANY_THREADS: Final = 565 +ERROR_THREAD_NOT_IN_PROCESS: Final = 566 +ERROR_PAGEFILE_QUOTA_EXCEEDED: Final = 567 +ERROR_LOGON_SERVER_CONFLICT: Final = 568 +ERROR_SYNCHRONIZATION_REQUIRED: Final = 569 +ERROR_NET_OPEN_FAILED: Final = 570 +ERROR_IO_PRIVILEGE_FAILED: Final = 571 +ERROR_CONTROL_C_EXIT: Final = 572 +ERROR_MISSING_SYSTEMFILE: Final = 573 +ERROR_UNHANDLED_EXCEPTION: Final = 574 +ERROR_APP_INIT_FAILURE: Final = 575 +ERROR_PAGEFILE_CREATE_FAILED: Final = 576 +ERROR_INVALID_IMAGE_HASH: Final = 577 +ERROR_NO_PAGEFILE: Final = 578 +ERROR_ILLEGAL_FLOAT_CONTEXT: Final = 579 +ERROR_NO_EVENT_PAIR: Final = 580 +ERROR_DOMAIN_CTRLR_CONFIG_ERROR: Final = 581 +ERROR_ILLEGAL_CHARACTER: Final = 582 +ERROR_UNDEFINED_CHARACTER: Final = 583 +ERROR_FLOPPY_VOLUME: Final = 584 +ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT: Final = 585 +ERROR_BACKUP_CONTROLLER: Final = 586 +ERROR_MUTANT_LIMIT_EXCEEDED: Final = 587 +ERROR_FS_DRIVER_REQUIRED: Final = 588 +ERROR_CANNOT_LOAD_REGISTRY_FILE: Final = 589 +ERROR_DEBUG_ATTACH_FAILED: Final = 590 +ERROR_SYSTEM_PROCESS_TERMINATED: Final = 591 +ERROR_DATA_NOT_ACCEPTED: Final = 592 +ERROR_VDM_HARD_ERROR: Final = 593 +ERROR_DRIVER_CANCEL_TIMEOUT: Final = 594 +ERROR_REPLY_MESSAGE_MISMATCH: Final = 595 +ERROR_LOST_WRITEBEHIND_DATA: Final = 596 +ERROR_CLIENT_SERVER_PARAMETERS_INVALID: Final = 597 +ERROR_NOT_TINY_STREAM: Final = 598 +ERROR_STACK_OVERFLOW_READ: Final = 599 +ERROR_CONVERT_TO_LARGE: Final = 600 +ERROR_FOUND_OUT_OF_SCOPE: Final = 601 +ERROR_ALLOCATE_BUCKET: Final = 602 +ERROR_MARSHALL_OVERFLOW: Final = 603 +ERROR_INVALID_VARIANT: Final = 604 +ERROR_BAD_COMPRESSION_BUFFER: Final = 605 +ERROR_AUDIT_FAILED: Final = 606 +ERROR_TIMER_RESOLUTION_NOT_SET: Final = 607 +ERROR_INSUFFICIENT_LOGON_INFO: Final = 608 +ERROR_BAD_DLL_ENTRYPOINT: Final = 609 +ERROR_BAD_SERVICE_ENTRYPOINT: Final = 610 +ERROR_IP_ADDRESS_CONFLICT1: Final = 611 +ERROR_IP_ADDRESS_CONFLICT2: Final = 612 +ERROR_REGISTRY_QUOTA_LIMIT: Final = 613 +ERROR_NO_CALLBACK_ACTIVE: Final = 614 +ERROR_PWD_TOO_SHORT: Final = 615 +ERROR_PWD_TOO_RECENT: Final = 616 +ERROR_PWD_HISTORY_CONFLICT: Final = 617 +ERROR_UNSUPPORTED_COMPRESSION: Final = 618 +ERROR_INVALID_HW_PROFILE: Final = 619 +ERROR_INVALID_PLUGPLAY_DEVICE_PATH: Final = 620 +ERROR_QUOTA_LIST_INCONSISTENT: Final = 621 +ERROR_EVALUATION_EXPIRATION: Final = 622 +ERROR_ILLEGAL_DLL_RELOCATION: Final = 623 +ERROR_DLL_INIT_FAILED_LOGOFF: Final = 624 +ERROR_VALIDATE_CONTINUE: Final = 625 +ERROR_NO_MORE_MATCHES: Final = 626 +ERROR_RANGE_LIST_CONFLICT: Final = 627 +ERROR_SERVER_SID_MISMATCH: Final = 628 +ERROR_CANT_ENABLE_DENY_ONLY: Final = 629 +ERROR_FLOAT_MULTIPLE_FAULTS: Final = 630 +ERROR_FLOAT_MULTIPLE_TRAPS: Final = 631 +ERROR_NOINTERFACE: Final = 632 +ERROR_DRIVER_FAILED_SLEEP: Final = 633 +ERROR_CORRUPT_SYSTEM_FILE: Final = 634 +ERROR_COMMITMENT_MINIMUM: Final = 635 +ERROR_PNP_RESTART_ENUMERATION: Final = 636 +ERROR_SYSTEM_IMAGE_BAD_SIGNATURE: Final = 637 +ERROR_PNP_REBOOT_REQUIRED: Final = 638 +ERROR_INSUFFICIENT_POWER: Final = 639 +ERROR_MULTIPLE_FAULT_VIOLATION: Final = 640 +ERROR_SYSTEM_SHUTDOWN: Final = 641 +ERROR_PORT_NOT_SET: Final = 642 +ERROR_DS_VERSION_CHECK_FAILURE: Final = 643 +ERROR_RANGE_NOT_FOUND: Final = 644 +ERROR_NOT_SAFE_MODE_DRIVER: Final = 646 +ERROR_FAILED_DRIVER_ENTRY: Final = 647 +ERROR_DEVICE_ENUMERATION_ERROR: Final = 648 +ERROR_MOUNT_POINT_NOT_RESOLVED: Final = 649 +ERROR_INVALID_DEVICE_OBJECT_PARAMETER: Final = 650 +ERROR_MCA_OCCURED: Final = 651 +ERROR_DRIVER_DATABASE_ERROR: Final = 652 +ERROR_SYSTEM_HIVE_TOO_LARGE: Final = 653 +ERROR_DRIVER_FAILED_PRIOR_UNLOAD: Final = 654 +ERROR_VOLSNAP_PREPARE_HIBERNATE: Final = 655 +ERROR_HIBERNATION_FAILURE: Final = 656 +ERROR_PWD_TOO_LONG: Final = 657 +ERROR_FILE_SYSTEM_LIMITATION: Final = 665 +ERROR_ASSERTION_FAILURE: Final = 668 +ERROR_ACPI_ERROR: Final = 669 +ERROR_WOW_ASSERTION: Final = 670 +ERROR_PNP_BAD_MPS_TABLE: Final = 671 +ERROR_PNP_TRANSLATION_FAILED: Final = 672 +ERROR_PNP_IRQ_TRANSLATION_FAILED: Final = 673 +ERROR_PNP_INVALID_ID: Final = 674 +ERROR_WAKE_SYSTEM_DEBUGGER: Final = 675 +ERROR_HANDLES_CLOSED: Final = 676 +ERROR_EXTRANEOUS_INFORMATION: Final = 677 +ERROR_RXACT_COMMIT_NECESSARY: Final = 678 +ERROR_MEDIA_CHECK: Final = 679 +ERROR_GUID_SUBSTITUTION_MADE: Final = 680 +ERROR_STOPPED_ON_SYMLINK: Final = 681 +ERROR_LONGJUMP: Final = 682 +ERROR_PLUGPLAY_QUERY_VETOED: Final = 683 +ERROR_UNWIND_CONSOLIDATE: Final = 684 +ERROR_REGISTRY_HIVE_RECOVERED: Final = 685 +ERROR_DLL_MIGHT_BE_INSECURE: Final = 686 +ERROR_DLL_MIGHT_BE_INCOMPATIBLE: Final = 687 +ERROR_DBG_EXCEPTION_NOT_HANDLED: Final = 688 +ERROR_DBG_REPLY_LATER: Final = 689 +ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE: Final = 690 +ERROR_DBG_TERMINATE_THREAD: Final = 691 +ERROR_DBG_TERMINATE_PROCESS: Final = 692 +ERROR_DBG_CONTROL_C: Final = 693 +ERROR_DBG_PRINTEXCEPTION_C: Final = 694 +ERROR_DBG_RIPEXCEPTION: Final = 695 +ERROR_DBG_CONTROL_BREAK: Final = 696 +ERROR_DBG_COMMAND_EXCEPTION: Final = 697 +ERROR_OBJECT_NAME_EXISTS: Final = 698 +ERROR_THREAD_WAS_SUSPENDED: Final = 699 +ERROR_IMAGE_NOT_AT_BASE: Final = 700 +ERROR_RXACT_STATE_CREATED: Final = 701 +ERROR_SEGMENT_NOTIFICATION: Final = 702 +ERROR_BAD_CURRENT_DIRECTORY: Final = 703 +ERROR_FT_READ_RECOVERY_FROM_BACKUP: Final = 704 +ERROR_FT_WRITE_RECOVERY: Final = 705 +ERROR_IMAGE_MACHINE_TYPE_MISMATCH: Final = 706 +ERROR_RECEIVE_PARTIAL: Final = 707 +ERROR_RECEIVE_EXPEDITED: Final = 708 +ERROR_RECEIVE_PARTIAL_EXPEDITED: Final = 709 +ERROR_EVENT_DONE: Final = 710 +ERROR_EVENT_PENDING: Final = 711 +ERROR_CHECKING_FILE_SYSTEM: Final = 712 +ERROR_FATAL_APP_EXIT: Final = 713 +ERROR_PREDEFINED_HANDLE: Final = 714 +ERROR_WAS_UNLOCKED: Final = 715 +ERROR_SERVICE_NOTIFICATION: Final = 716 +ERROR_WAS_LOCKED: Final = 717 +ERROR_LOG_HARD_ERROR: Final = 718 +ERROR_ALREADY_WIN32: Final = 719 +ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE: Final = 720 +ERROR_NO_YIELD_PERFORMED: Final = 721 +ERROR_TIMER_RESUME_IGNORED: Final = 722 +ERROR_ARBITRATION_UNHANDLED: Final = 723 +ERROR_CARDBUS_NOT_SUPPORTED: Final = 724 +ERROR_MP_PROCESSOR_MISMATCH: Final = 725 +ERROR_HIBERNATED: Final = 726 +ERROR_RESUME_HIBERNATION: Final = 727 +ERROR_FIRMWARE_UPDATED: Final = 728 +ERROR_DRIVERS_LEAKING_LOCKED_PAGES: Final = 729 +ERROR_WAKE_SYSTEM: Final = 730 +ERROR_WAIT_1: Final = 731 +ERROR_WAIT_2: Final = 732 +ERROR_WAIT_3: Final = 733 +ERROR_WAIT_63: Final = 734 +ERROR_ABANDONED_WAIT_0: Final = 735 +ERROR_ABANDONED_WAIT_63: Final = 736 +ERROR_USER_APC: Final = 737 +ERROR_KERNEL_APC: Final = 738 +ERROR_ALERTED: Final = 739 +ERROR_ELEVATION_REQUIRED: Final = 740 +ERROR_REPARSE: Final = 741 +ERROR_OPLOCK_BREAK_IN_PROGRESS: Final = 742 +ERROR_VOLUME_MOUNTED: Final = 743 +ERROR_RXACT_COMMITTED: Final = 744 +ERROR_NOTIFY_CLEANUP: Final = 745 +ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED: Final = 746 +ERROR_PAGE_FAULT_TRANSITION: Final = 747 +ERROR_PAGE_FAULT_DEMAND_ZERO: Final = 748 +ERROR_PAGE_FAULT_COPY_ON_WRITE: Final = 749 +ERROR_PAGE_FAULT_GUARD_PAGE: Final = 750 +ERROR_PAGE_FAULT_PAGING_FILE: Final = 751 +ERROR_CACHE_PAGE_LOCKED: Final = 752 +ERROR_CRASH_DUMP: Final = 753 +ERROR_BUFFER_ALL_ZEROS: Final = 754 +ERROR_REPARSE_OBJECT: Final = 755 +ERROR_RESOURCE_REQUIREMENTS_CHANGED: Final = 756 +ERROR_TRANSLATION_COMPLETE: Final = 757 +ERROR_NOTHING_TO_TERMINATE: Final = 758 +ERROR_PROCESS_NOT_IN_JOB: Final = 759 +ERROR_PROCESS_IN_JOB: Final = 760 +ERROR_VOLSNAP_HIBERNATE_READY: Final = 761 +ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY: Final = 762 +ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED: Final = 763 +ERROR_INTERRUPT_STILL_CONNECTED: Final = 764 +ERROR_WAIT_FOR_OPLOCK: Final = 765 +ERROR_DBG_EXCEPTION_HANDLED: Final = 766 +ERROR_DBG_CONTINUE: Final = 767 +ERROR_CALLBACK_POP_STACK: Final = 768 +ERROR_COMPRESSION_DISABLED: Final = 769 +ERROR_CANTFETCHBACKWARDS: Final = 770 +ERROR_CANTSCROLLBACKWARDS: Final = 771 +ERROR_ROWSNOTRELEASED: Final = 772 +ERROR_BAD_ACCESSOR_FLAGS: Final = 773 +ERROR_ERRORS_ENCOUNTERED: Final = 774 +ERROR_NOT_CAPABLE: Final = 775 +ERROR_REQUEST_OUT_OF_SEQUENCE: Final = 776 +ERROR_VERSION_PARSE_ERROR: Final = 777 +ERROR_BADSTARTPOSITION: Final = 778 +ERROR_MEMORY_HARDWARE: Final = 779 +ERROR_DISK_REPAIR_DISABLED: Final = 780 +ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE: Final = 781 +ERROR_SYSTEM_POWERSTATE_TRANSITION: Final = 782 +ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION: Final = 783 +ERROR_MCA_EXCEPTION: Final = 784 +ERROR_ACCESS_AUDIT_BY_POLICY: Final = 785 +ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY: Final = 786 +ERROR_ABANDON_HIBERFILE: Final = 787 +ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED: Final = 788 +ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR: Final = 789 +ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR: Final = 790 +ERROR_BAD_MCFG_TABLE: Final = 791 +ERROR_DISK_REPAIR_REDIRECTED: Final = 792 +ERROR_DISK_REPAIR_UNSUCCESSFUL: Final = 793 +ERROR_CORRUPT_LOG_OVERFULL: Final = 794 +ERROR_CORRUPT_LOG_CORRUPTED: Final = 795 +ERROR_CORRUPT_LOG_UNAVAILABLE: Final = 796 +ERROR_CORRUPT_LOG_DELETED_FULL: Final = 797 +ERROR_CORRUPT_LOG_CLEARED: Final = 798 +ERROR_ORPHAN_NAME_EXHAUSTED: Final = 799 +ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE: Final = 800 +ERROR_CANNOT_GRANT_REQUESTED_OPLOCK: Final = 801 +ERROR_CANNOT_BREAK_OPLOCK: Final = 802 +ERROR_OPLOCK_HANDLE_CLOSED: Final = 803 +ERROR_NO_ACE_CONDITION: Final = 804 +ERROR_INVALID_ACE_CONDITION: Final = 805 +ERROR_FILE_HANDLE_REVOKED: Final = 806 +ERROR_IMAGE_AT_DIFFERENT_BASE: Final = 807 +ERROR_ENCRYPTED_IO_NOT_POSSIBLE: Final = 808 +ERROR_FILE_METADATA_OPTIMIZATION_IN_PROGRESS: Final = 809 +ERROR_QUOTA_ACTIVITY: Final = 810 +ERROR_HANDLE_REVOKED: Final = 811 +ERROR_CALLBACK_INVOKE_INLINE: Final = 812 +ERROR_CPU_SET_INVALID: Final = 813 +ERROR_ENCLAVE_NOT_TERMINATED: Final = 814 +ERROR_ENCLAVE_VIOLATION: Final = 815 +ERROR_SERVER_TRANSPORT_CONFLICT: Final = 816 +ERROR_CERTIFICATE_VALIDATION_PREFERENCE_CONFLICT: Final = 817 +ERROR_FT_READ_FROM_COPY_FAILURE: Final = 818 +ERROR_SECTION_DIRECT_MAP_ONLY: Final = 819 +ERROR_EA_ACCESS_DENIED: Final = 994 +ERROR_OPERATION_ABORTED: Final = 995 +ERROR_IO_INCOMPLETE: Final = 996 +ERROR_IO_PENDING: Final = 997 +ERROR_NOACCESS: Final = 998 +ERROR_SWAPERROR: Final = 999 +ERROR_STACK_OVERFLOW: Final = 1001 +ERROR_INVALID_MESSAGE: Final = 1002 +ERROR_CAN_NOT_COMPLETE: Final = 1003 +ERROR_INVALID_FLAGS: Final = 1004 +ERROR_UNRECOGNIZED_VOLUME: Final = 1005 +ERROR_FILE_INVALID: Final = 1006 +ERROR_FULLSCREEN_MODE: Final = 1007 +ERROR_NO_TOKEN: Final = 1008 +ERROR_BADDB: Final = 1009 +ERROR_BADKEY: Final = 1010 +ERROR_CANTOPEN: Final = 1011 +ERROR_CANTREAD: Final = 1012 +ERROR_CANTWRITE: Final = 1013 +ERROR_REGISTRY_RECOVERED: Final = 1014 +ERROR_REGISTRY_CORRUPT: Final = 1015 +ERROR_REGISTRY_IO_FAILED: Final = 1016 +ERROR_NOT_REGISTRY_FILE: Final = 1017 +ERROR_KEY_DELETED: Final = 1018 +ERROR_NO_LOG_SPACE: Final = 1019 +ERROR_KEY_HAS_CHILDREN: Final = 1020 +ERROR_CHILD_MUST_BE_VOLATILE: Final = 1021 +ERROR_NOTIFY_ENUM_DIR: Final = 1022 +ERROR_DEPENDENT_SERVICES_RUNNING: Final = 1051 +ERROR_INVALID_SERVICE_CONTROL: Final = 1052 +ERROR_SERVICE_REQUEST_TIMEOUT: Final = 1053 +ERROR_SERVICE_NO_THREAD: Final = 1054 +ERROR_SERVICE_DATABASE_LOCKED: Final = 1055 +ERROR_SERVICE_ALREADY_RUNNING: Final = 1056 +ERROR_INVALID_SERVICE_ACCOUNT: Final = 1057 +ERROR_SERVICE_DISABLED: Final = 1058 +ERROR_CIRCULAR_DEPENDENCY: Final = 1059 +ERROR_SERVICE_DOES_NOT_EXIST: Final = 1060 +ERROR_SERVICE_CANNOT_ACCEPT_CTRL: Final = 1061 +ERROR_SERVICE_NOT_ACTIVE: Final = 1062 +ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: Final = 1063 +ERROR_EXCEPTION_IN_SERVICE: Final = 1064 +ERROR_DATABASE_DOES_NOT_EXIST: Final = 1065 +ERROR_SERVICE_SPECIFIC_ERROR: Final = 1066 +ERROR_PROCESS_ABORTED: Final = 1067 +ERROR_SERVICE_DEPENDENCY_FAIL: Final = 1068 +ERROR_SERVICE_LOGON_FAILED: Final = 1069 +ERROR_SERVICE_START_HANG: Final = 1070 +ERROR_INVALID_SERVICE_LOCK: Final = 1071 +ERROR_SERVICE_MARKED_FOR_DELETE: Final = 1072 +ERROR_SERVICE_EXISTS: Final = 1073 +ERROR_ALREADY_RUNNING_LKG: Final = 1074 +ERROR_SERVICE_DEPENDENCY_DELETED: Final = 1075 +ERROR_BOOT_ALREADY_ACCEPTED: Final = 1076 +ERROR_SERVICE_NEVER_STARTED: Final = 1077 +ERROR_DUPLICATE_SERVICE_NAME: Final = 1078 +ERROR_DIFFERENT_SERVICE_ACCOUNT: Final = 1079 +ERROR_CANNOT_DETECT_DRIVER_FAILURE: Final = 1080 +ERROR_CANNOT_DETECT_PROCESS_ABORT: Final = 1081 +ERROR_NO_RECOVERY_PROGRAM: Final = 1082 +ERROR_SERVICE_NOT_IN_EXE: Final = 1083 +ERROR_NOT_SAFEBOOT_SERVICE: Final = 1084 +ERROR_END_OF_MEDIA: Final = 1100 +ERROR_FILEMARK_DETECTED: Final = 1101 +ERROR_BEGINNING_OF_MEDIA: Final = 1102 +ERROR_SETMARK_DETECTED: Final = 1103 +ERROR_NO_DATA_DETECTED: Final = 1104 +ERROR_PARTITION_FAILURE: Final = 1105 +ERROR_INVALID_BLOCK_LENGTH: Final = 1106 +ERROR_DEVICE_NOT_PARTITIONED: Final = 1107 +ERROR_UNABLE_TO_LOCK_MEDIA: Final = 1108 +ERROR_UNABLE_TO_UNLOAD_MEDIA: Final = 1109 +ERROR_MEDIA_CHANGED: Final = 1110 +ERROR_BUS_RESET: Final = 1111 +ERROR_NO_MEDIA_IN_DRIVE: Final = 1112 +ERROR_NO_UNICODE_TRANSLATION: Final = 1113 +ERROR_DLL_INIT_FAILED: Final = 1114 +ERROR_SHUTDOWN_IN_PROGRESS: Final = 1115 +ERROR_NO_SHUTDOWN_IN_PROGRESS: Final = 1116 +ERROR_IO_DEVICE: Final = 1117 +ERROR_SERIAL_NO_DEVICE: Final = 1118 +ERROR_IRQ_BUSY: Final = 1119 +ERROR_MORE_WRITES: Final = 1120 +ERROR_COUNTER_TIMEOUT: Final = 1121 +ERROR_FLOPPY_ID_MARK_NOT_FOUND: Final = 1122 +ERROR_FLOPPY_WRONG_CYLINDER: Final = 1123 +ERROR_FLOPPY_UNKNOWN_ERROR: Final = 1124 +ERROR_FLOPPY_BAD_REGISTERS: Final = 1125 +ERROR_DISK_RECALIBRATE_FAILED: Final = 1126 +ERROR_DISK_OPERATION_FAILED: Final = 1127 +ERROR_DISK_RESET_FAILED: Final = 1128 +ERROR_EOM_OVERFLOW: Final = 1129 +ERROR_NOT_ENOUGH_SERVER_MEMORY: Final = 1130 +ERROR_POSSIBLE_DEADLOCK: Final = 1131 +ERROR_MAPPED_ALIGNMENT: Final = 1132 +ERROR_SET_POWER_STATE_VETOED: Final = 1140 +ERROR_SET_POWER_STATE_FAILED: Final = 1141 +ERROR_TOO_MANY_LINKS: Final = 1142 +ERROR_OLD_WIN_VERSION: Final = 1150 +ERROR_APP_WRONG_OS: Final = 1151 +ERROR_SINGLE_INSTANCE_APP: Final = 1152 +ERROR_RMODE_APP: Final = 1153 +ERROR_INVALID_DLL: Final = 1154 +ERROR_NO_ASSOCIATION: Final = 1155 +ERROR_DDE_FAIL: Final = 1156 +ERROR_DLL_NOT_FOUND: Final = 1157 +ERROR_NO_MORE_USER_HANDLES: Final = 1158 +ERROR_MESSAGE_SYNC_ONLY: Final = 1159 +ERROR_SOURCE_ELEMENT_EMPTY: Final = 1160 +ERROR_DESTINATION_ELEMENT_FULL: Final = 1161 +ERROR_ILLEGAL_ELEMENT_ADDRESS: Final = 1162 +ERROR_MAGAZINE_NOT_PRESENT: Final = 1163 +ERROR_DEVICE_REINITIALIZATION_NEEDED: Final = 1164 +ERROR_DEVICE_REQUIRES_CLEANING: Final = 1165 +ERROR_DEVICE_DOOR_OPEN: Final = 1166 +ERROR_DEVICE_NOT_CONNECTED: Final = 1167 +ERROR_NOT_FOUND: Final = 1168 +ERROR_NO_MATCH: Final = 1169 +ERROR_SET_NOT_FOUND: Final = 1170 +ERROR_POINT_NOT_FOUND: Final = 1171 +ERROR_NO_TRACKING_SERVICE: Final = 1172 +ERROR_NO_VOLUME_ID: Final = 1173 +ERROR_UNABLE_TO_REMOVE_REPLACED: Final = 1175 +ERROR_UNABLE_TO_MOVE_REPLACEMENT: Final = 1176 +ERROR_UNABLE_TO_MOVE_REPLACEMENT_2: Final = 1177 +ERROR_JOURNAL_DELETE_IN_PROGRESS: Final = 1178 +ERROR_JOURNAL_NOT_ACTIVE: Final = 1179 +ERROR_POTENTIAL_FILE_FOUND: Final = 1180 +ERROR_JOURNAL_ENTRY_DELETED: Final = 1181 +ERROR_PARTITION_TERMINATING: Final = 1184 +ERROR_SHUTDOWN_IS_SCHEDULED: Final = 1190 +ERROR_SHUTDOWN_USERS_LOGGED_ON: Final = 1191 +ERROR_SHUTDOWN_DISKS_NOT_IN_MAINTENANCE_MODE: Final = 1192 +ERROR_BAD_DEVICE: Final = 1200 +ERROR_CONNECTION_UNAVAIL: Final = 1201 +ERROR_DEVICE_ALREADY_REMEMBERED: Final = 1202 +ERROR_NO_NET_OR_BAD_PATH: Final = 1203 +ERROR_BAD_PROVIDER: Final = 1204 +ERROR_CANNOT_OPEN_PROFILE: Final = 1205 +ERROR_BAD_PROFILE: Final = 1206 +ERROR_NOT_CONTAINER: Final = 1207 +ERROR_EXTENDED_ERROR: Final = 1208 +ERROR_INVALID_GROUPNAME: Final = 1209 +ERROR_INVALID_COMPUTERNAME: Final = 1210 +ERROR_INVALID_EVENTNAME: Final = 1211 +ERROR_INVALID_DOMAINNAME: Final = 1212 +ERROR_INVALID_SERVICENAME: Final = 1213 +ERROR_INVALID_NETNAME: Final = 1214 +ERROR_INVALID_SHARENAME: Final = 1215 +ERROR_INVALID_PASSWORDNAME: Final = 1216 +ERROR_INVALID_MESSAGENAME: Final = 1217 +ERROR_INVALID_MESSAGEDEST: Final = 1218 +ERROR_SESSION_CREDENTIAL_CONFLICT: Final = 1219 +ERROR_REMOTE_SESSION_LIMIT_EXCEEDED: Final = 1220 +ERROR_DUP_DOMAINNAME: Final = 1221 +ERROR_NO_NETWORK: Final = 1222 +ERROR_CANCELLED: Final = 1223 +ERROR_USER_MAPPED_FILE: Final = 1224 +ERROR_CONNECTION_REFUSED: Final = 1225 +ERROR_GRACEFUL_DISCONNECT: Final = 1226 +ERROR_ADDRESS_ALREADY_ASSOCIATED: Final = 1227 +ERROR_ADDRESS_NOT_ASSOCIATED: Final = 1228 +ERROR_CONNECTION_INVALID: Final = 1229 +ERROR_CONNECTION_ACTIVE: Final = 1230 +ERROR_NETWORK_UNREACHABLE: Final = 1231 +ERROR_HOST_UNREACHABLE: Final = 1232 +ERROR_PROTOCOL_UNREACHABLE: Final = 1233 +ERROR_PORT_UNREACHABLE: Final = 1234 +ERROR_REQUEST_ABORTED: Final = 1235 +ERROR_CONNECTION_ABORTED: Final = 1236 +ERROR_RETRY: Final = 1237 +ERROR_CONNECTION_COUNT_LIMIT: Final = 1238 +ERROR_LOGIN_TIME_RESTRICTION: Final = 1239 +ERROR_LOGIN_WKSTA_RESTRICTION: Final = 1240 +ERROR_INCORRECT_ADDRESS: Final = 1241 +ERROR_ALREADY_REGISTERED: Final = 1242 +ERROR_SERVICE_NOT_FOUND: Final = 1243 +ERROR_NOT_AUTHENTICATED: Final = 1244 +ERROR_NOT_LOGGED_ON: Final = 1245 +ERROR_CONTINUE: Final = 1246 +ERROR_ALREADY_INITIALIZED: Final = 1247 +ERROR_NO_MORE_DEVICES: Final = 1248 +ERROR_NO_SUCH_SITE: Final = 1249 +ERROR_DOMAIN_CONTROLLER_EXISTS: Final = 1250 +ERROR_ONLY_IF_CONNECTED: Final = 1251 +ERROR_OVERRIDE_NOCHANGES: Final = 1252 +ERROR_BAD_USER_PROFILE: Final = 1253 +ERROR_NOT_SUPPORTED_ON_SBS: Final = 1254 +ERROR_SERVER_SHUTDOWN_IN_PROGRESS: Final = 1255 +ERROR_HOST_DOWN: Final = 1256 +ERROR_NON_ACCOUNT_SID: Final = 1257 +ERROR_NON_DOMAIN_SID: Final = 1258 +ERROR_APPHELP_BLOCK: Final = 1259 +ERROR_ACCESS_DISABLED_BY_POLICY: Final = 1260 +ERROR_REG_NAT_CONSUMPTION: Final = 1261 +ERROR_CSCSHARE_OFFLINE: Final = 1262 +ERROR_PKINIT_FAILURE: Final = 1263 +ERROR_SMARTCARD_SUBSYSTEM_FAILURE: Final = 1264 +ERROR_DOWNGRADE_DETECTED: Final = 1265 +ERROR_MACHINE_LOCKED: Final = 1271 +ERROR_SMB_GUEST_LOGON_BLOCKED: Final = 1272 +ERROR_CALLBACK_SUPPLIED_INVALID_DATA: Final = 1273 +ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED: Final = 1274 +ERROR_DRIVER_BLOCKED: Final = 1275 +ERROR_INVALID_IMPORT_OF_NON_DLL: Final = 1276 +ERROR_ACCESS_DISABLED_WEBBLADE: Final = 1277 +ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER: Final = 1278 +ERROR_RECOVERY_FAILURE: Final = 1279 +ERROR_ALREADY_FIBER: Final = 1280 +ERROR_ALREADY_THREAD: Final = 1281 +ERROR_STACK_BUFFER_OVERRUN: Final = 1282 +ERROR_PARAMETER_QUOTA_EXCEEDED: Final = 1283 +ERROR_DEBUGGER_INACTIVE: Final = 1284 +ERROR_DELAY_LOAD_FAILED: Final = 1285 +ERROR_VDM_DISALLOWED: Final = 1286 +ERROR_UNIDENTIFIED_ERROR: Final = 1287 +ERROR_INVALID_CRUNTIME_PARAMETER: Final = 1288 +ERROR_BEYOND_VDL: Final = 1289 +ERROR_INCOMPATIBLE_SERVICE_SID_TYPE: Final = 1290 +ERROR_DRIVER_PROCESS_TERMINATED: Final = 1291 +ERROR_IMPLEMENTATION_LIMIT: Final = 1292 +ERROR_PROCESS_IS_PROTECTED: Final = 1293 +ERROR_SERVICE_NOTIFY_CLIENT_LAGGING: Final = 1294 +ERROR_DISK_QUOTA_EXCEEDED: Final = 1295 +ERROR_CONTENT_BLOCKED: Final = 1296 +ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE: Final = 1297 +ERROR_APP_HANG: Final = 1298 +ERROR_INVALID_LABEL: Final = 1299 +ERROR_NOT_ALL_ASSIGNED: Final = 1300 +ERROR_SOME_NOT_MAPPED: Final = 1301 +ERROR_NO_QUOTAS_FOR_ACCOUNT: Final = 1302 +ERROR_LOCAL_USER_SESSION_KEY: Final = 1303 +ERROR_NULL_LM_PASSWORD: Final = 1304 +ERROR_UNKNOWN_REVISION: Final = 1305 +ERROR_REVISION_MISMATCH: Final = 1306 +ERROR_INVALID_OWNER: Final = 1307 +ERROR_INVALID_PRIMARY_GROUP: Final = 1308 +ERROR_NO_IMPERSONATION_TOKEN: Final = 1309 +ERROR_CANT_DISABLE_MANDATORY: Final = 1310 +ERROR_NO_LOGON_SERVERS: Final = 1311 +ERROR_NO_SUCH_LOGON_SESSION: Final = 1312 +ERROR_NO_SUCH_PRIVILEGE: Final = 1313 +ERROR_PRIVILEGE_NOT_HELD: Final = 1314 +ERROR_INVALID_ACCOUNT_NAME: Final = 1315 +ERROR_USER_EXISTS: Final = 1316 +ERROR_NO_SUCH_USER: Final = 1317 +ERROR_GROUP_EXISTS: Final = 1318 +ERROR_NO_SUCH_GROUP: Final = 1319 +ERROR_MEMBER_IN_GROUP: Final = 1320 +ERROR_MEMBER_NOT_IN_GROUP: Final = 1321 +ERROR_LAST_ADMIN: Final = 1322 +ERROR_WRONG_PASSWORD: Final = 1323 +ERROR_ILL_FORMED_PASSWORD: Final = 1324 +ERROR_PASSWORD_RESTRICTION: Final = 1325 +ERROR_LOGON_FAILURE: Final = 1326 +ERROR_ACCOUNT_RESTRICTION: Final = 1327 +ERROR_INVALID_LOGON_HOURS: Final = 1328 +ERROR_INVALID_WORKSTATION: Final = 1329 +ERROR_PASSWORD_EXPIRED: Final = 1330 +ERROR_ACCOUNT_DISABLED: Final = 1331 +ERROR_NONE_MAPPED: Final = 1332 +ERROR_TOO_MANY_LUIDS_REQUESTED: Final = 1333 +ERROR_LUIDS_EXHAUSTED: Final = 1334 +ERROR_INVALID_SUB_AUTHORITY: Final = 1335 +ERROR_INVALID_ACL: Final = 1336 +ERROR_INVALID_SID: Final = 1337 +ERROR_INVALID_SECURITY_DESCR: Final = 1338 +ERROR_BAD_INHERITANCE_ACL: Final = 1340 +ERROR_SERVER_DISABLED: Final = 1341 +ERROR_SERVER_NOT_DISABLED: Final = 1342 +ERROR_INVALID_ID_AUTHORITY: Final = 1343 +ERROR_ALLOTTED_SPACE_EXCEEDED: Final = 1344 +ERROR_INVALID_GROUP_ATTRIBUTES: Final = 1345 +ERROR_BAD_IMPERSONATION_LEVEL: Final = 1346 +ERROR_CANT_OPEN_ANONYMOUS: Final = 1347 +ERROR_BAD_VALIDATION_CLASS: Final = 1348 +ERROR_BAD_TOKEN_TYPE: Final = 1349 +ERROR_NO_SECURITY_ON_OBJECT: Final = 1350 +ERROR_CANT_ACCESS_DOMAIN_INFO: Final = 1351 +ERROR_INVALID_SERVER_STATE: Final = 1352 +ERROR_INVALID_DOMAIN_STATE: Final = 1353 +ERROR_INVALID_DOMAIN_ROLE: Final = 1354 +ERROR_NO_SUCH_DOMAIN: Final = 1355 +ERROR_DOMAIN_EXISTS: Final = 1356 +ERROR_DOMAIN_LIMIT_EXCEEDED: Final = 1357 +ERROR_INTERNAL_DB_CORRUPTION: Final = 1358 +ERROR_INTERNAL_ERROR: Final = 1359 +ERROR_GENERIC_NOT_MAPPED: Final = 1360 +ERROR_BAD_DESCRIPTOR_FORMAT: Final = 1361 +ERROR_NOT_LOGON_PROCESS: Final = 1362 +ERROR_LOGON_SESSION_EXISTS: Final = 1363 +ERROR_NO_SUCH_PACKAGE: Final = 1364 +ERROR_BAD_LOGON_SESSION_STATE: Final = 1365 +ERROR_LOGON_SESSION_COLLISION: Final = 1366 +ERROR_INVALID_LOGON_TYPE: Final = 1367 +ERROR_CANNOT_IMPERSONATE: Final = 1368 +ERROR_RXACT_INVALID_STATE: Final = 1369 +ERROR_RXACT_COMMIT_FAILURE: Final = 1370 +ERROR_SPECIAL_ACCOUNT: Final = 1371 +ERROR_SPECIAL_GROUP: Final = 1372 +ERROR_SPECIAL_USER: Final = 1373 +ERROR_MEMBERS_PRIMARY_GROUP: Final = 1374 +ERROR_TOKEN_ALREADY_IN_USE: Final = 1375 +ERROR_NO_SUCH_ALIAS: Final = 1376 +ERROR_MEMBER_NOT_IN_ALIAS: Final = 1377 +ERROR_MEMBER_IN_ALIAS: Final = 1378 +ERROR_ALIAS_EXISTS: Final = 1379 +ERROR_LOGON_NOT_GRANTED: Final = 1380 +ERROR_TOO_MANY_SECRETS: Final = 1381 +ERROR_SECRET_TOO_LONG: Final = 1382 +ERROR_INTERNAL_DB_ERROR: Final = 1383 +ERROR_TOO_MANY_CONTEXT_IDS: Final = 1384 +ERROR_LOGON_TYPE_NOT_GRANTED: Final = 1385 +ERROR_NT_CROSS_ENCRYPTION_REQUIRED: Final = 1386 +ERROR_NO_SUCH_MEMBER: Final = 1387 +ERROR_INVALID_MEMBER: Final = 1388 +ERROR_TOO_MANY_SIDS: Final = 1389 +ERROR_LM_CROSS_ENCRYPTION_REQUIRED: Final = 1390 +ERROR_NO_INHERITANCE: Final = 1391 +ERROR_FILE_CORRUPT: Final = 1392 +ERROR_DISK_CORRUPT: Final = 1393 +ERROR_NO_USER_SESSION_KEY: Final = 1394 +ERROR_LICENSE_QUOTA_EXCEEDED: Final = 1395 +ERROR_WRONG_TARGET_NAME: Final = 1396 +ERROR_MUTUAL_AUTH_FAILED: Final = 1397 +ERROR_TIME_SKEW: Final = 1398 +ERROR_CURRENT_DOMAIN_NOT_ALLOWED: Final = 1399 +ERROR_INVALID_WINDOW_HANDLE: Final = 1400 +ERROR_INVALID_MENU_HANDLE: Final = 1401 +ERROR_INVALID_CURSOR_HANDLE: Final = 1402 +ERROR_INVALID_ACCEL_HANDLE: Final = 1403 +ERROR_INVALID_HOOK_HANDLE: Final = 1404 +ERROR_INVALID_DWP_HANDLE: Final = 1405 +ERROR_TLW_WITH_WSCHILD: Final = 1406 +ERROR_CANNOT_FIND_WND_CLASS: Final = 1407 +ERROR_WINDOW_OF_OTHER_THREAD: Final = 1408 +ERROR_HOTKEY_ALREADY_REGISTERED: Final = 1409 +ERROR_CLASS_ALREADY_EXISTS: Final = 1410 +ERROR_CLASS_DOES_NOT_EXIST: Final = 1411 +ERROR_CLASS_HAS_WINDOWS: Final = 1412 +ERROR_INVALID_INDEX: Final = 1413 +ERROR_INVALID_ICON_HANDLE: Final = 1414 +ERROR_PRIVATE_DIALOG_INDEX: Final = 1415 +ERROR_LISTBOX_ID_NOT_FOUND: Final = 1416 +ERROR_NO_WILDCARD_CHARACTERS: Final = 1417 +ERROR_CLIPBOARD_NOT_OPEN: Final = 1418 +ERROR_HOTKEY_NOT_REGISTERED: Final = 1419 +ERROR_WINDOW_NOT_DIALOG: Final = 1420 +ERROR_CONTROL_ID_NOT_FOUND: Final = 1421 +ERROR_INVALID_COMBOBOX_MESSAGE: Final = 1422 +ERROR_WINDOW_NOT_COMBOBOX: Final = 1423 +ERROR_INVALID_EDIT_HEIGHT: Final = 1424 +ERROR_DC_NOT_FOUND: Final = 1425 +ERROR_INVALID_HOOK_FILTER: Final = 1426 +ERROR_INVALID_FILTER_PROC: Final = 1427 +ERROR_HOOK_NEEDS_HMOD: Final = 1428 +ERROR_GLOBAL_ONLY_HOOK: Final = 1429 +ERROR_JOURNAL_HOOK_SET: Final = 1430 +ERROR_HOOK_NOT_INSTALLED: Final = 1431 +ERROR_INVALID_LB_MESSAGE: Final = 1432 +ERROR_SETCOUNT_ON_BAD_LB: Final = 1433 +ERROR_LB_WITHOUT_TABSTOPS: Final = 1434 +ERROR_DESTROY_OBJECT_OF_OTHER_THREAD: Final = 1435 +ERROR_CHILD_WINDOW_MENU: Final = 1436 +ERROR_NO_SYSTEM_MENU: Final = 1437 +ERROR_INVALID_MSGBOX_STYLE: Final = 1438 +ERROR_INVALID_SPI_VALUE: Final = 1439 +ERROR_SCREEN_ALREADY_LOCKED: Final = 1440 +ERROR_HWNDS_HAVE_DIFF_PARENT: Final = 1441 +ERROR_NOT_CHILD_WINDOW: Final = 1442 +ERROR_INVALID_GW_COMMAND: Final = 1443 +ERROR_INVALID_THREAD_ID: Final = 1444 +ERROR_NON_MDICHILD_WINDOW: Final = 1445 +ERROR_POPUP_ALREADY_ACTIVE: Final = 1446 +ERROR_NO_SCROLLBARS: Final = 1447 +ERROR_INVALID_SCROLLBAR_RANGE: Final = 1448 +ERROR_INVALID_SHOWWIN_COMMAND: Final = 1449 +ERROR_NO_SYSTEM_RESOURCES: Final = 1450 +ERROR_NONPAGED_SYSTEM_RESOURCES: Final = 1451 +ERROR_PAGED_SYSTEM_RESOURCES: Final = 1452 +ERROR_WORKING_SET_QUOTA: Final = 1453 +ERROR_PAGEFILE_QUOTA: Final = 1454 +ERROR_COMMITMENT_LIMIT: Final = 1455 +ERROR_MENU_ITEM_NOT_FOUND: Final = 1456 +ERROR_INVALID_KEYBOARD_HANDLE: Final = 1457 +ERROR_HOOK_TYPE_NOT_ALLOWED: Final = 1458 +ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION: Final = 1459 +ERROR_TIMEOUT: Final = 1460 +ERROR_INVALID_MONITOR_HANDLE: Final = 1461 +ERROR_INCORRECT_SIZE: Final = 1462 +ERROR_SYMLINK_CLASS_DISABLED: Final = 1463 +ERROR_SYMLINK_NOT_SUPPORTED: Final = 1464 +ERROR_XML_PARSE_ERROR: Final = 1465 +ERROR_XMLDSIG_ERROR: Final = 1466 +ERROR_RESTART_APPLICATION: Final = 1467 +ERROR_WRONG_COMPARTMENT: Final = 1468 +ERROR_AUTHIP_FAILURE: Final = 1469 +ERROR_NO_NVRAM_RESOURCES: Final = 1470 +ERROR_NOT_GUI_PROCESS: Final = 1471 +ERROR_EVENTLOG_FILE_CORRUPT: Final = 1500 +ERROR_EVENTLOG_CANT_START: Final = 1501 +ERROR_LOG_FILE_FULL: Final = 1502 +ERROR_EVENTLOG_FILE_CHANGED: Final = 1503 +ERROR_CONTAINER_ASSIGNED: Final = 1504 +ERROR_JOB_NO_CONTAINER: Final = 1505 +ERROR_INVALID_TASK_NAME: Final = 1550 +ERROR_INVALID_TASK_INDEX: Final = 1551 +ERROR_THREAD_ALREADY_IN_TASK: Final = 1552 +ERROR_INSTALL_SERVICE_FAILURE: Final = 1601 +ERROR_INSTALL_USEREXIT: Final = 1602 +ERROR_INSTALL_FAILURE: Final = 1603 +ERROR_INSTALL_SUSPEND: Final = 1604 +ERROR_UNKNOWN_PRODUCT: Final = 1605 +ERROR_UNKNOWN_FEATURE: Final = 1606 +ERROR_UNKNOWN_COMPONENT: Final = 1607 +ERROR_UNKNOWN_PROPERTY: Final = 1608 +ERROR_INVALID_HANDLE_STATE: Final = 1609 +ERROR_BAD_CONFIGURATION: Final = 1610 +ERROR_INDEX_ABSENT: Final = 1611 +ERROR_INSTALL_SOURCE_ABSENT: Final = 1612 +ERROR_INSTALL_PACKAGE_VERSION: Final = 1613 +ERROR_PRODUCT_UNINSTALLED: Final = 1614 +ERROR_BAD_QUERY_SYNTAX: Final = 1615 +ERROR_INVALID_FIELD: Final = 1616 +ERROR_DEVICE_REMOVED: Final = 1617 +ERROR_INSTALL_ALREADY_RUNNING: Final = 1618 +ERROR_INSTALL_PACKAGE_OPEN_FAILED: Final = 1619 +ERROR_INSTALL_PACKAGE_INVALID: Final = 1620 +ERROR_INSTALL_UI_FAILURE: Final = 1621 +ERROR_INSTALL_LOG_FAILURE: Final = 1622 +ERROR_INSTALL_LANGUAGE_UNSUPPORTED: Final = 1623 +ERROR_INSTALL_TRANSFORM_FAILURE: Final = 1624 +ERROR_INSTALL_PACKAGE_REJECTED: Final = 1625 +ERROR_FUNCTION_NOT_CALLED: Final = 1626 +ERROR_FUNCTION_FAILED: Final = 1627 +ERROR_INVALID_TABLE: Final = 1628 +ERROR_DATATYPE_MISMATCH: Final = 1629 +ERROR_UNSUPPORTED_TYPE: Final = 1630 +ERROR_CREATE_FAILED: Final = 1631 +ERROR_INSTALL_TEMP_UNWRITABLE: Final = 1632 +ERROR_INSTALL_PLATFORM_UNSUPPORTED: Final = 1633 +ERROR_INSTALL_NOTUSED: Final = 1634 +ERROR_PATCH_PACKAGE_OPEN_FAILED: Final = 1635 +ERROR_PATCH_PACKAGE_INVALID: Final = 1636 +ERROR_PATCH_PACKAGE_UNSUPPORTED: Final = 1637 +ERROR_PRODUCT_VERSION: Final = 1638 +ERROR_INVALID_COMMAND_LINE: Final = 1639 +ERROR_INSTALL_REMOTE_DISALLOWED: Final = 1640 +ERROR_SUCCESS_REBOOT_INITIATED: Final = 1641 +ERROR_PATCH_TARGET_NOT_FOUND: Final = 1642 +ERROR_PATCH_PACKAGE_REJECTED: Final = 1643 +ERROR_INSTALL_TRANSFORM_REJECTED: Final = 1644 +ERROR_INSTALL_REMOTE_PROHIBITED: Final = 1645 +ERROR_PATCH_REMOVAL_UNSUPPORTED: Final = 1646 +ERROR_UNKNOWN_PATCH: Final = 1647 +ERROR_PATCH_NO_SEQUENCE: Final = 1648 +ERROR_PATCH_REMOVAL_DISALLOWED: Final = 1649 +ERROR_INVALID_PATCH_XML: Final = 1650 +ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT: Final = 1651 +ERROR_INSTALL_SERVICE_SAFEBOOT: Final = 1652 +ERROR_FAIL_FAST_EXCEPTION: Final = 1653 +ERROR_INSTALL_REJECTED: Final = 1654 +ERROR_DYNAMIC_CODE_BLOCKED: Final = 1655 +ERROR_NOT_SAME_OBJECT: Final = 1656 +ERROR_STRICT_CFG_VIOLATION: Final = 1657 +ERROR_SET_CONTEXT_DENIED: Final = 1660 +ERROR_CROSS_PARTITION_VIOLATION: Final = 1661 +ERROR_RETURN_ADDRESS_HIJACK_ATTEMPT: Final = 1662 +RPC_S_INVALID_STRING_BINDING: Final = 1700 +RPC_S_WRONG_KIND_OF_BINDING: Final = 1701 +RPC_S_INVALID_BINDING: Final = 1702 +RPC_S_PROTSEQ_NOT_SUPPORTED: Final = 1703 +RPC_S_INVALID_RPC_PROTSEQ: Final = 1704 +RPC_S_INVALID_STRING_UUID: Final = 1705 +RPC_S_INVALID_ENDPOINT_FORMAT: Final = 1706 +RPC_S_INVALID_NET_ADDR: Final = 1707 +RPC_S_NO_ENDPOINT_FOUND: Final = 1708 +RPC_S_INVALID_TIMEOUT: Final = 1709 +RPC_S_OBJECT_NOT_FOUND: Final = 1710 +RPC_S_ALREADY_REGISTERED: Final = 1711 +RPC_S_TYPE_ALREADY_REGISTERED: Final = 1712 +RPC_S_ALREADY_LISTENING: Final = 1713 +RPC_S_NO_PROTSEQS_REGISTERED: Final = 1714 +RPC_S_NOT_LISTENING: Final = 1715 +RPC_S_UNKNOWN_MGR_TYPE: Final = 1716 +RPC_S_UNKNOWN_IF: Final = 1717 +RPC_S_NO_BINDINGS: Final = 1718 +RPC_S_NO_PROTSEQS: Final = 1719 +RPC_S_CANT_CREATE_ENDPOINT: Final = 1720 +RPC_S_OUT_OF_RESOURCES: Final = 1721 +RPC_S_SERVER_UNAVAILABLE: Final = 1722 +RPC_S_SERVER_TOO_BUSY: Final = 1723 +RPC_S_INVALID_NETWORK_OPTIONS: Final = 1724 +RPC_S_NO_CALL_ACTIVE: Final = 1725 +RPC_S_CALL_FAILED: Final = 1726 +RPC_S_CALL_FAILED_DNE: Final = 1727 +RPC_S_PROTOCOL_ERROR: Final = 1728 +RPC_S_PROXY_ACCESS_DENIED: Final = 1729 +RPC_S_UNSUPPORTED_TRANS_SYN: Final = 1730 +RPC_S_UNSUPPORTED_TYPE: Final = 1732 +RPC_S_INVALID_TAG: Final = 1733 +RPC_S_INVALID_BOUND: Final = 1734 +RPC_S_NO_ENTRY_NAME: Final = 1735 +RPC_S_INVALID_NAME_SYNTAX: Final = 1736 +RPC_S_UNSUPPORTED_NAME_SYNTAX: Final = 1737 +RPC_S_UUID_NO_ADDRESS: Final = 1739 +RPC_S_DUPLICATE_ENDPOINT: Final = 1740 +RPC_S_UNKNOWN_AUTHN_TYPE: Final = 1741 +RPC_S_MAX_CALLS_TOO_SMALL: Final = 1742 +RPC_S_STRING_TOO_LONG: Final = 1743 +RPC_S_PROTSEQ_NOT_FOUND: Final = 1744 +RPC_S_PROCNUM_OUT_OF_RANGE: Final = 1745 +RPC_S_BINDING_HAS_NO_AUTH: Final = 1746 +RPC_S_UNKNOWN_AUTHN_SERVICE: Final = 1747 +RPC_S_UNKNOWN_AUTHN_LEVEL: Final = 1748 +RPC_S_INVALID_AUTH_IDENTITY: Final = 1749 +RPC_S_UNKNOWN_AUTHZ_SERVICE: Final = 1750 +EPT_S_INVALID_ENTRY: Final = 1751 +EPT_S_CANT_PERFORM_OP: Final = 1752 +EPT_S_NOT_REGISTERED: Final = 1753 +RPC_S_NOTHING_TO_EXPORT: Final = 1754 +RPC_S_INCOMPLETE_NAME: Final = 1755 +RPC_S_INVALID_VERS_OPTION: Final = 1756 +RPC_S_NO_MORE_MEMBERS: Final = 1757 +RPC_S_NOT_ALL_OBJS_UNEXPORTED: Final = 1758 +RPC_S_INTERFACE_NOT_FOUND: Final = 1759 +RPC_S_ENTRY_ALREADY_EXISTS: Final = 1760 +RPC_S_ENTRY_NOT_FOUND: Final = 1761 +RPC_S_NAME_SERVICE_UNAVAILABLE: Final = 1762 +RPC_S_INVALID_NAF_ID: Final = 1763 +RPC_S_CANNOT_SUPPORT: Final = 1764 +RPC_S_NO_CONTEXT_AVAILABLE: Final = 1765 +RPC_S_INTERNAL_ERROR: Final = 1766 +RPC_S_ZERO_DIVIDE: Final = 1767 +RPC_S_ADDRESS_ERROR: Final = 1768 +RPC_S_FP_DIV_ZERO: Final = 1769 +RPC_S_FP_UNDERFLOW: Final = 1770 +RPC_S_FP_OVERFLOW: Final = 1771 +RPC_X_NO_MORE_ENTRIES: Final = 1772 +RPC_X_SS_CHAR_TRANS_OPEN_FAIL: Final = 1773 +RPC_X_SS_CHAR_TRANS_SHORT_FILE: Final = 1774 +RPC_X_SS_IN_NULL_CONTEXT: Final = 1775 +RPC_X_SS_CONTEXT_DAMAGED: Final = 1777 +RPC_X_SS_HANDLES_MISMATCH: Final = 1778 +RPC_X_SS_CANNOT_GET_CALL_HANDLE: Final = 1779 +RPC_X_NULL_REF_POINTER: Final = 1780 +RPC_X_ENUM_VALUE_OUT_OF_RANGE: Final = 1781 +RPC_X_BYTE_COUNT_TOO_SMALL: Final = 1782 +RPC_X_BAD_STUB_DATA: Final = 1783 +ERROR_INVALID_USER_BUFFER: Final = 1784 +ERROR_UNRECOGNIZED_MEDIA: Final = 1785 +ERROR_NO_TRUST_LSA_SECRET: Final = 1786 +ERROR_NO_TRUST_SAM_ACCOUNT: Final = 1787 +ERROR_TRUSTED_DOMAIN_FAILURE: Final = 1788 +ERROR_TRUSTED_RELATIONSHIP_FAILURE: Final = 1789 +ERROR_TRUST_FAILURE: Final = 1790 +RPC_S_CALL_IN_PROGRESS: Final = 1791 +ERROR_NETLOGON_NOT_STARTED: Final = 1792 +ERROR_ACCOUNT_EXPIRED: Final = 1793 +ERROR_REDIRECTOR_HAS_OPEN_HANDLES: Final = 1794 +ERROR_PRINTER_DRIVER_ALREADY_INSTALLED: Final = 1795 +ERROR_UNKNOWN_PORT: Final = 1796 +ERROR_UNKNOWN_PRINTER_DRIVER: Final = 1797 +ERROR_UNKNOWN_PRINTPROCESSOR: Final = 1798 +ERROR_INVALID_SEPARATOR_FILE: Final = 1799 +ERROR_INVALID_PRIORITY: Final = 1800 +ERROR_INVALID_PRINTER_NAME: Final = 1801 +ERROR_PRINTER_ALREADY_EXISTS: Final = 1802 +ERROR_INVALID_PRINTER_COMMAND: Final = 1803 +ERROR_INVALID_DATATYPE: Final = 1804 +ERROR_INVALID_ENVIRONMENT: Final = 1805 +RPC_S_NO_MORE_BINDINGS: Final = 1806 +ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: Final = 1807 +ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT: Final = 1808 +ERROR_NOLOGON_SERVER_TRUST_ACCOUNT: Final = 1809 +ERROR_DOMAIN_TRUST_INCONSISTENT: Final = 1810 +ERROR_SERVER_HAS_OPEN_HANDLES: Final = 1811 +ERROR_RESOURCE_DATA_NOT_FOUND: Final = 1812 +ERROR_RESOURCE_TYPE_NOT_FOUND: Final = 1813 +ERROR_RESOURCE_NAME_NOT_FOUND: Final = 1814 +ERROR_RESOURCE_LANG_NOT_FOUND: Final = 1815 +ERROR_NOT_ENOUGH_QUOTA: Final = 1816 +RPC_S_NO_INTERFACES: Final = 1817 +RPC_S_CALL_CANCELLED: Final = 1818 +RPC_S_BINDING_INCOMPLETE: Final = 1819 +RPC_S_COMM_FAILURE: Final = 1820 +RPC_S_UNSUPPORTED_AUTHN_LEVEL: Final = 1821 +RPC_S_NO_PRINC_NAME: Final = 1822 +RPC_S_NOT_RPC_ERROR: Final = 1823 +RPC_S_UUID_LOCAL_ONLY: Final = 1824 +RPC_S_SEC_PKG_ERROR: Final = 1825 +RPC_S_NOT_CANCELLED: Final = 1826 +RPC_X_INVALID_ES_ACTION: Final = 1827 +RPC_X_WRONG_ES_VERSION: Final = 1828 +RPC_X_WRONG_STUB_VERSION: Final = 1829 +RPC_X_INVALID_PIPE_OBJECT: Final = 1830 +RPC_X_WRONG_PIPE_ORDER: Final = 1831 +RPC_X_WRONG_PIPE_VERSION: Final = 1832 +RPC_S_COOKIE_AUTH_FAILED: Final = 1833 +RPC_S_DO_NOT_DISTURB: Final = 1834 +RPC_S_SYSTEM_HANDLE_COUNT_EXCEEDED: Final = 1835 +RPC_S_SYSTEM_HANDLE_TYPE_MISMATCH: Final = 1836 +RPC_S_GROUP_MEMBER_NOT_FOUND: Final = 1898 +EPT_S_CANT_CREATE: Final = 1899 +RPC_S_INVALID_OBJECT: Final = 1900 +ERROR_INVALID_TIME: Final = 1901 +ERROR_INVALID_FORM_NAME: Final = 1902 +ERROR_INVALID_FORM_SIZE: Final = 1903 +ERROR_ALREADY_WAITING: Final = 1904 +ERROR_PRINTER_DELETED: Final = 1905 +ERROR_INVALID_PRINTER_STATE: Final = 1906 +ERROR_PASSWORD_MUST_CHANGE: Final = 1907 +ERROR_DOMAIN_CONTROLLER_NOT_FOUND: Final = 1908 +ERROR_ACCOUNT_LOCKED_OUT: Final = 1909 +OR_INVALID_OXID: Final = 1910 +OR_INVALID_OID: Final = 1911 +OR_INVALID_SET: Final = 1912 +RPC_S_SEND_INCOMPLETE: Final = 1913 +RPC_S_INVALID_ASYNC_HANDLE: Final = 1914 +RPC_S_INVALID_ASYNC_CALL: Final = 1915 +RPC_X_PIPE_CLOSED: Final = 1916 +RPC_X_PIPE_DISCIPLINE_ERROR: Final = 1917 +RPC_X_PIPE_EMPTY: Final = 1918 +ERROR_NO_SITENAME: Final = 1919 +ERROR_CANT_ACCESS_FILE: Final = 1920 +ERROR_CANT_RESOLVE_FILENAME: Final = 1921 +RPC_S_ENTRY_TYPE_MISMATCH: Final = 1922 +RPC_S_NOT_ALL_OBJS_EXPORTED: Final = 1923 +RPC_S_INTERFACE_NOT_EXPORTED: Final = 1924 +RPC_S_PROFILE_NOT_ADDED: Final = 1925 +RPC_S_PRF_ELT_NOT_ADDED: Final = 1926 +RPC_S_PRF_ELT_NOT_REMOVED: Final = 1927 +RPC_S_GRP_ELT_NOT_ADDED: Final = 1928 +RPC_S_GRP_ELT_NOT_REMOVED: Final = 1929 +ERROR_KM_DRIVER_BLOCKED: Final = 1930 +ERROR_CONTEXT_EXPIRED: Final = 1931 +ERROR_PER_USER_TRUST_QUOTA_EXCEEDED: Final = 1932 +ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED: Final = 1933 +ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED: Final = 1934 +ERROR_AUTHENTICATION_FIREWALL_FAILED: Final = 1935 +ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED: Final = 1936 +ERROR_NTLM_BLOCKED: Final = 1937 +ERROR_PASSWORD_CHANGE_REQUIRED: Final = 1938 +ERROR_LOST_MODE_LOGON_RESTRICTION: Final = 1939 +ERROR_INVALID_PIXEL_FORMAT: Final = 2000 +ERROR_BAD_DRIVER: Final = 2001 +ERROR_INVALID_WINDOW_STYLE: Final = 2002 +ERROR_METAFILE_NOT_SUPPORTED: Final = 2003 +ERROR_TRANSFORM_NOT_SUPPORTED: Final = 2004 +ERROR_CLIPPING_NOT_SUPPORTED: Final = 2005 +ERROR_INVALID_CMM: Final = 2010 +ERROR_INVALID_PROFILE: Final = 2011 +ERROR_TAG_NOT_FOUND: Final = 2012 +ERROR_TAG_NOT_PRESENT: Final = 2013 +ERROR_DUPLICATE_TAG: Final = 2014 +ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE: Final = 2015 +ERROR_PROFILE_NOT_FOUND: Final = 2016 +ERROR_INVALID_COLORSPACE: Final = 2017 +ERROR_ICM_NOT_ENABLED: Final = 2018 +ERROR_DELETING_ICM_XFORM: Final = 2019 +ERROR_INVALID_TRANSFORM: Final = 2020 +ERROR_COLORSPACE_MISMATCH: Final = 2021 +ERROR_INVALID_COLORINDEX: Final = 2022 +ERROR_PROFILE_DOES_NOT_MATCH_DEVICE: Final = 2023 +ERROR_CONNECTED_OTHER_PASSWORD: Final = 2108 +ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT: Final = 2109 +ERROR_BAD_USERNAME: Final = 2202 +ERROR_NOT_CONNECTED: Final = 2250 +ERROR_OPEN_FILES: Final = 2401 +ERROR_ACTIVE_CONNECTIONS: Final = 2402 +ERROR_DEVICE_IN_USE: Final = 2404 +ERROR_UNKNOWN_PRINT_MONITOR: Final = 3000 +ERROR_PRINTER_DRIVER_IN_USE: Final = 3001 +ERROR_SPOOL_FILE_NOT_FOUND: Final = 3002 +ERROR_SPL_NO_STARTDOC: Final = 3003 +ERROR_SPL_NO_ADDJOB: Final = 3004 +ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED: Final = 3005 +ERROR_PRINT_MONITOR_ALREADY_INSTALLED: Final = 3006 +ERROR_INVALID_PRINT_MONITOR: Final = 3007 +ERROR_PRINT_MONITOR_IN_USE: Final = 3008 +ERROR_PRINTER_HAS_JOBS_QUEUED: Final = 3009 +ERROR_SUCCESS_REBOOT_REQUIRED: Final = 3010 +ERROR_SUCCESS_RESTART_REQUIRED: Final = 3011 +ERROR_PRINTER_NOT_FOUND: Final = 3012 +ERROR_PRINTER_DRIVER_WARNED: Final = 3013 +ERROR_PRINTER_DRIVER_BLOCKED: Final = 3014 +ERROR_PRINTER_DRIVER_PACKAGE_IN_USE: Final = 3015 +ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND: Final = 3016 +ERROR_FAIL_REBOOT_REQUIRED: Final = 3017 +ERROR_FAIL_REBOOT_INITIATED: Final = 3018 +ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED: Final = 3019 +ERROR_PRINT_JOB_RESTART_REQUIRED: Final = 3020 +ERROR_INVALID_PRINTER_DRIVER_MANIFEST: Final = 3021 +ERROR_PRINTER_NOT_SHAREABLE: Final = 3022 +ERROR_SERVER_SERVICE_CALL_REQUIRES_SMB1: Final = 3023 +ERROR_NETWORK_AUTHENTICATION_PROMPT_CANCELED: Final = 3024 +ERROR_REQUEST_PAUSED: Final = 3050 +ERROR_APPEXEC_CONDITION_NOT_SATISFIED: Final = 3060 +ERROR_APPEXEC_HANDLE_INVALIDATED: Final = 3061 +ERROR_APPEXEC_INVALID_HOST_GENERATION: Final = 3062 +ERROR_APPEXEC_UNEXPECTED_PROCESS_REGISTRATION: Final = 3063 +ERROR_APPEXEC_INVALID_HOST_STATE: Final = 3064 +ERROR_APPEXEC_NO_DONOR: Final = 3065 +ERROR_APPEXEC_HOST_ID_MISMATCH: Final = 3066 +ERROR_APPEXEC_UNKNOWN_USER: Final = 3067 +ERROR_APPEXEC_APP_COMPAT_BLOCK: Final = 3068 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT: Final = 3069 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT_TERMINATION: Final = 3070 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT_LICENSING: Final = 3071 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT_RESOURCES: Final = 3072 +ERROR_VRF_VOLATILE_CFG_AND_IO_ENABLED: Final = 3080 +ERROR_VRF_VOLATILE_NOT_STOPPABLE: Final = 3081 +ERROR_VRF_VOLATILE_SAFE_MODE: Final = 3082 +ERROR_VRF_VOLATILE_NOT_RUNNABLE_SYSTEM: Final = 3083 +ERROR_VRF_VOLATILE_NOT_SUPPORTED_RULECLASS: Final = 3084 +ERROR_VRF_VOLATILE_PROTECTED_DRIVER: Final = 3085 +ERROR_VRF_VOLATILE_NMI_REGISTERED: Final = 3086 +ERROR_VRF_VOLATILE_SETTINGS_CONFLICT: Final = 3087 +ERROR_DIF_IOCALLBACK_NOT_REPLACED: Final = 3190 +ERROR_DIF_LIVEDUMP_LIMIT_EXCEEDED: Final = 3191 +ERROR_DIF_VOLATILE_SECTION_NOT_LOCKED: Final = 3192 +ERROR_DIF_VOLATILE_DRIVER_HOTPATCHED: Final = 3193 +ERROR_DIF_VOLATILE_INVALID_INFO: Final = 3194 +ERROR_DIF_VOLATILE_DRIVER_IS_NOT_RUNNING: Final = 3195 +ERROR_DIF_VOLATILE_PLUGIN_IS_NOT_RUNNING: Final = 3196 +ERROR_DIF_VOLATILE_PLUGIN_CHANGE_NOT_ALLOWED: Final = 3197 +ERROR_DIF_VOLATILE_NOT_ALLOWED: Final = 3198 +ERROR_DIF_BINDING_API_NOT_FOUND: Final = 3199 +ERROR_IO_REISSUE_AS_CACHED: Final = 3950 +ERROR_WINS_INTERNAL: Final = 4000 +ERROR_CAN_NOT_DEL_LOCAL_WINS: Final = 4001 +ERROR_STATIC_INIT: Final = 4002 +ERROR_INC_BACKUP: Final = 4003 +ERROR_FULL_BACKUP: Final = 4004 +ERROR_REC_NON_EXISTENT: Final = 4005 +ERROR_RPL_NOT_ALLOWED: Final = 4006 +PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED: Final = 4050 +PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO: Final = 4051 +PEERDIST_ERROR_MISSING_DATA: Final = 4052 +PEERDIST_ERROR_NO_MORE: Final = 4053 +PEERDIST_ERROR_NOT_INITIALIZED: Final = 4054 +PEERDIST_ERROR_ALREADY_INITIALIZED: Final = 4055 +PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS: Final = 4056 +PEERDIST_ERROR_INVALIDATED: Final = 4057 +PEERDIST_ERROR_ALREADY_EXISTS: Final = 4058 +PEERDIST_ERROR_OPERATION_NOTFOUND: Final = 4059 +PEERDIST_ERROR_ALREADY_COMPLETED: Final = 4060 +PEERDIST_ERROR_OUT_OF_BOUNDS: Final = 4061 +PEERDIST_ERROR_VERSION_UNSUPPORTED: Final = 4062 +PEERDIST_ERROR_INVALID_CONFIGURATION: Final = 4063 +PEERDIST_ERROR_NOT_LICENSED: Final = 4064 +PEERDIST_ERROR_SERVICE_UNAVAILABLE: Final = 4065 +PEERDIST_ERROR_TRUST_FAILURE: Final = 4066 +ERROR_DHCP_ADDRESS_CONFLICT: Final = 4100 +ERROR_WMI_GUID_NOT_FOUND: Final = 4200 +ERROR_WMI_INSTANCE_NOT_FOUND: Final = 4201 +ERROR_WMI_ITEMID_NOT_FOUND: Final = 4202 +ERROR_WMI_TRY_AGAIN: Final = 4203 +ERROR_WMI_DP_NOT_FOUND: Final = 4204 +ERROR_WMI_UNRESOLVED_INSTANCE_REF: Final = 4205 +ERROR_WMI_ALREADY_ENABLED: Final = 4206 +ERROR_WMI_GUID_DISCONNECTED: Final = 4207 +ERROR_WMI_SERVER_UNAVAILABLE: Final = 4208 +ERROR_WMI_DP_FAILED: Final = 4209 +ERROR_WMI_INVALID_MOF: Final = 4210 +ERROR_WMI_INVALID_REGINFO: Final = 4211 +ERROR_WMI_ALREADY_DISABLED: Final = 4212 +ERROR_WMI_READ_ONLY: Final = 4213 +ERROR_WMI_SET_FAILURE: Final = 4214 +ERROR_NOT_APPCONTAINER: Final = 4250 +ERROR_APPCONTAINER_REQUIRED: Final = 4251 +ERROR_NOT_SUPPORTED_IN_APPCONTAINER: Final = 4252 +ERROR_INVALID_PACKAGE_SID_LENGTH: Final = 4253 +ERROR_INVALID_MEDIA: Final = 4300 +ERROR_INVALID_LIBRARY: Final = 4301 +ERROR_INVALID_MEDIA_POOL: Final = 4302 +ERROR_DRIVE_MEDIA_MISMATCH: Final = 4303 +ERROR_MEDIA_OFFLINE: Final = 4304 +ERROR_LIBRARY_OFFLINE: Final = 4305 +ERROR_EMPTY: Final = 4306 +ERROR_NOT_EMPTY: Final = 4307 +ERROR_MEDIA_UNAVAILABLE: Final = 4308 +ERROR_RESOURCE_DISABLED: Final = 4309 +ERROR_INVALID_CLEANER: Final = 4310 +ERROR_UNABLE_TO_CLEAN: Final = 4311 +ERROR_OBJECT_NOT_FOUND: Final = 4312 +ERROR_DATABASE_FAILURE: Final = 4313 +ERROR_DATABASE_FULL: Final = 4314 +ERROR_MEDIA_INCOMPATIBLE: Final = 4315 +ERROR_RESOURCE_NOT_PRESENT: Final = 4316 +ERROR_INVALID_OPERATION: Final = 4317 +ERROR_MEDIA_NOT_AVAILABLE: Final = 4318 +ERROR_DEVICE_NOT_AVAILABLE: Final = 4319 +ERROR_REQUEST_REFUSED: Final = 4320 +ERROR_INVALID_DRIVE_OBJECT: Final = 4321 +ERROR_LIBRARY_FULL: Final = 4322 +ERROR_MEDIUM_NOT_ACCESSIBLE: Final = 4323 +ERROR_UNABLE_TO_LOAD_MEDIUM: Final = 4324 +ERROR_UNABLE_TO_INVENTORY_DRIVE: Final = 4325 +ERROR_UNABLE_TO_INVENTORY_SLOT: Final = 4326 +ERROR_UNABLE_TO_INVENTORY_TRANSPORT: Final = 4327 +ERROR_TRANSPORT_FULL: Final = 4328 +ERROR_CONTROLLING_IEPORT: Final = 4329 +ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA: Final = 4330 +ERROR_CLEANER_SLOT_SET: Final = 4331 +ERROR_CLEANER_SLOT_NOT_SET: Final = 4332 +ERROR_CLEANER_CARTRIDGE_SPENT: Final = 4333 +ERROR_UNEXPECTED_OMID: Final = 4334 +ERROR_CANT_DELETE_LAST_ITEM: Final = 4335 +ERROR_MESSAGE_EXCEEDS_MAX_SIZE: Final = 4336 +ERROR_VOLUME_CONTAINS_SYS_FILES: Final = 4337 +ERROR_INDIGENOUS_TYPE: Final = 4338 +ERROR_NO_SUPPORTING_DRIVES: Final = 4339 +ERROR_CLEANER_CARTRIDGE_INSTALLED: Final = 4340 +ERROR_IEPORT_FULL: Final = 4341 +ERROR_FILE_OFFLINE: Final = 4350 +ERROR_REMOTE_STORAGE_NOT_ACTIVE: Final = 4351 +ERROR_REMOTE_STORAGE_MEDIA_ERROR: Final = 4352 +ERROR_NOT_A_REPARSE_POINT: Final = 4390 +ERROR_REPARSE_ATTRIBUTE_CONFLICT: Final = 4391 +ERROR_INVALID_REPARSE_DATA: Final = 4392 +ERROR_REPARSE_TAG_INVALID: Final = 4393 +ERROR_REPARSE_TAG_MISMATCH: Final = 4394 +ERROR_REPARSE_POINT_ENCOUNTERED: Final = 4395 +ERROR_APP_DATA_NOT_FOUND: Final = 4400 +ERROR_APP_DATA_EXPIRED: Final = 4401 +ERROR_APP_DATA_CORRUPT: Final = 4402 +ERROR_APP_DATA_LIMIT_EXCEEDED: Final = 4403 +ERROR_APP_DATA_REBOOT_REQUIRED: Final = 4404 +ERROR_SECUREBOOT_ROLLBACK_DETECTED: Final = 4420 +ERROR_SECUREBOOT_POLICY_VIOLATION: Final = 4421 +ERROR_SECUREBOOT_INVALID_POLICY: Final = 4422 +ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND: Final = 4423 +ERROR_SECUREBOOT_POLICY_NOT_SIGNED: Final = 4424 +ERROR_SECUREBOOT_NOT_ENABLED: Final = 4425 +ERROR_SECUREBOOT_FILE_REPLACED: Final = 4426 +ERROR_SECUREBOOT_POLICY_NOT_AUTHORIZED: Final = 4427 +ERROR_SECUREBOOT_POLICY_UNKNOWN: Final = 4428 +ERROR_SECUREBOOT_POLICY_MISSING_ANTIROLLBACKVERSION: Final = 4429 +ERROR_SECUREBOOT_PLATFORM_ID_MISMATCH: Final = 4430 +ERROR_SECUREBOOT_POLICY_ROLLBACK_DETECTED: Final = 4431 +ERROR_SECUREBOOT_POLICY_UPGRADE_MISMATCH: Final = 4432 +ERROR_SECUREBOOT_REQUIRED_POLICY_FILE_MISSING: Final = 4433 +ERROR_SECUREBOOT_NOT_BASE_POLICY: Final = 4434 +ERROR_SECUREBOOT_NOT_SUPPLEMENTAL_POLICY: Final = 4435 +ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED: Final = 4440 +ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED: Final = 4441 +ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED: Final = 4442 +ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED: Final = 4443 +ERROR_ALREADY_HAS_STREAM_ID: Final = 4444 +ERROR_SMR_GARBAGE_COLLECTION_REQUIRED: Final = 4445 +ERROR_WOF_WIM_HEADER_CORRUPT: Final = 4446 +ERROR_WOF_WIM_RESOURCE_TABLE_CORRUPT: Final = 4447 +ERROR_WOF_FILE_RESOURCE_TABLE_CORRUPT: Final = 4448 +ERROR_OBJECT_IS_IMMUTABLE: Final = 4449 +ERROR_VOLUME_NOT_SIS_ENABLED: Final = 4500 +ERROR_SYSTEM_INTEGRITY_ROLLBACK_DETECTED: Final = 4550 +ERROR_SYSTEM_INTEGRITY_POLICY_VIOLATION: Final = 4551 +ERROR_SYSTEM_INTEGRITY_INVALID_POLICY: Final = 4552 +ERROR_SYSTEM_INTEGRITY_POLICY_NOT_SIGNED: Final = 4553 +ERROR_SYSTEM_INTEGRITY_TOO_MANY_POLICIES: Final = 4554 +ERROR_SYSTEM_INTEGRITY_SUPPLEMENTAL_POLICY_NOT_AUTHORIZED: Final = 4555 +ERROR_SYSTEM_INTEGRITY_REPUTATION_MALICIOUS: Final = 4556 +ERROR_SYSTEM_INTEGRITY_REPUTATION_PUA: Final = 4557 +ERROR_SYSTEM_INTEGRITY_REPUTATION_DANGEROUS_EXT: Final = 4558 +ERROR_SYSTEM_INTEGRITY_REPUTATION_OFFLINE: Final = 4559 +ERROR_VSM_NOT_INITIALIZED: Final = 4560 +ERROR_VSM_DMA_PROTECTION_NOT_IN_USE: Final = 4561 +ERROR_PLATFORM_MANIFEST_NOT_AUTHORIZED: Final = 4570 +ERROR_PLATFORM_MANIFEST_INVALID: Final = 4571 +ERROR_PLATFORM_MANIFEST_FILE_NOT_AUTHORIZED: Final = 4572 +ERROR_PLATFORM_MANIFEST_CATALOG_NOT_AUTHORIZED: Final = 4573 +ERROR_PLATFORM_MANIFEST_BINARY_ID_NOT_FOUND: Final = 4574 +ERROR_PLATFORM_MANIFEST_NOT_ACTIVE: Final = 4575 +ERROR_PLATFORM_MANIFEST_NOT_SIGNED: Final = 4576 +ERROR_SYSTEM_INTEGRITY_REPUTATION_UNFRIENDLY_FILE: Final = 4580 +ERROR_SYSTEM_INTEGRITY_REPUTATION_UNATTAINABLE: Final = 4581 +ERROR_SYSTEM_INTEGRITY_REPUTATION_EXPLICIT_DENY_FILE: Final = 4582 +ERROR_DEPENDENT_RESOURCE_EXISTS: Final = 5001 +ERROR_DEPENDENCY_NOT_FOUND: Final = 5002 +ERROR_DEPENDENCY_ALREADY_EXISTS: Final = 5003 +ERROR_RESOURCE_NOT_ONLINE: Final = 5004 +ERROR_HOST_NODE_NOT_AVAILABLE: Final = 5005 +ERROR_RESOURCE_NOT_AVAILABLE: Final = 5006 +ERROR_RESOURCE_NOT_FOUND: Final = 5007 +ERROR_SHUTDOWN_CLUSTER: Final = 5008 +ERROR_CANT_EVICT_ACTIVE_NODE: Final = 5009 +ERROR_OBJECT_ALREADY_EXISTS: Final = 5010 +ERROR_OBJECT_IN_LIST: Final = 5011 +ERROR_GROUP_NOT_AVAILABLE: Final = 5012 +ERROR_GROUP_NOT_FOUND: Final = 5013 +ERROR_GROUP_NOT_ONLINE: Final = 5014 +ERROR_HOST_NODE_NOT_RESOURCE_OWNER: Final = 5015 +ERROR_HOST_NODE_NOT_GROUP_OWNER: Final = 5016 +ERROR_RESMON_CREATE_FAILED: Final = 5017 +ERROR_RESMON_ONLINE_FAILED: Final = 5018 +ERROR_RESOURCE_ONLINE: Final = 5019 +ERROR_QUORUM_RESOURCE: Final = 5020 +ERROR_NOT_QUORUM_CAPABLE: Final = 5021 +ERROR_CLUSTER_SHUTTING_DOWN: Final = 5022 +ERROR_INVALID_STATE: Final = 5023 +ERROR_RESOURCE_PROPERTIES_STORED: Final = 5024 +ERROR_NOT_QUORUM_CLASS: Final = 5025 +ERROR_CORE_RESOURCE: Final = 5026 +ERROR_QUORUM_RESOURCE_ONLINE_FAILED: Final = 5027 +ERROR_QUORUMLOG_OPEN_FAILED: Final = 5028 +ERROR_CLUSTERLOG_CORRUPT: Final = 5029 +ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE: Final = 5030 +ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE: Final = 5031 +ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND: Final = 5032 +ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE: Final = 5033 +ERROR_QUORUM_OWNER_ALIVE: Final = 5034 +ERROR_NETWORK_NOT_AVAILABLE: Final = 5035 +ERROR_NODE_NOT_AVAILABLE: Final = 5036 +ERROR_ALL_NODES_NOT_AVAILABLE: Final = 5037 +ERROR_RESOURCE_FAILED: Final = 5038 +ERROR_CLUSTER_INVALID_NODE: Final = 5039 +ERROR_CLUSTER_NODE_EXISTS: Final = 5040 +ERROR_CLUSTER_JOIN_IN_PROGRESS: Final = 5041 +ERROR_CLUSTER_NODE_NOT_FOUND: Final = 5042 +ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND: Final = 5043 +ERROR_CLUSTER_NETWORK_EXISTS: Final = 5044 +ERROR_CLUSTER_NETWORK_NOT_FOUND: Final = 5045 +ERROR_CLUSTER_NETINTERFACE_EXISTS: Final = 5046 +ERROR_CLUSTER_NETINTERFACE_NOT_FOUND: Final = 5047 +ERROR_CLUSTER_INVALID_REQUEST: Final = 5048 +ERROR_CLUSTER_INVALID_NETWORK_PROVIDER: Final = 5049 +ERROR_CLUSTER_NODE_DOWN: Final = 5050 +ERROR_CLUSTER_NODE_UNREACHABLE: Final = 5051 +ERROR_CLUSTER_NODE_NOT_MEMBER: Final = 5052 +ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS: Final = 5053 +ERROR_CLUSTER_INVALID_NETWORK: Final = 5054 +ERROR_CLUSTER_NODE_UP: Final = 5056 +ERROR_CLUSTER_IPADDR_IN_USE: Final = 5057 +ERROR_CLUSTER_NODE_NOT_PAUSED: Final = 5058 +ERROR_CLUSTER_NO_SECURITY_CONTEXT: Final = 5059 +ERROR_CLUSTER_NETWORK_NOT_INTERNAL: Final = 5060 +ERROR_CLUSTER_NODE_ALREADY_UP: Final = 5061 +ERROR_CLUSTER_NODE_ALREADY_DOWN: Final = 5062 +ERROR_CLUSTER_NETWORK_ALREADY_ONLINE: Final = 5063 +ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE: Final = 5064 +ERROR_CLUSTER_NODE_ALREADY_MEMBER: Final = 5065 +ERROR_CLUSTER_LAST_INTERNAL_NETWORK: Final = 5066 +ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS: Final = 5067 +ERROR_INVALID_OPERATION_ON_QUORUM: Final = 5068 +ERROR_DEPENDENCY_NOT_ALLOWED: Final = 5069 +ERROR_CLUSTER_NODE_PAUSED: Final = 5070 +ERROR_NODE_CANT_HOST_RESOURCE: Final = 5071 +ERROR_CLUSTER_NODE_NOT_READY: Final = 5072 +ERROR_CLUSTER_NODE_SHUTTING_DOWN: Final = 5073 +ERROR_CLUSTER_JOIN_ABORTED: Final = 5074 +ERROR_CLUSTER_INCOMPATIBLE_VERSIONS: Final = 5075 +ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED: Final = 5076 +ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED: Final = 5077 +ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND: Final = 5078 +ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED: Final = 5079 +ERROR_CLUSTER_RESNAME_NOT_FOUND: Final = 5080 +ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED: Final = 5081 +ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST: Final = 5082 +ERROR_CLUSTER_DATABASE_SEQMISMATCH: Final = 5083 +ERROR_RESMON_INVALID_STATE: Final = 5084 +ERROR_CLUSTER_GUM_NOT_LOCKER: Final = 5085 +ERROR_QUORUM_DISK_NOT_FOUND: Final = 5086 +ERROR_DATABASE_BACKUP_CORRUPT: Final = 5087 +ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT: Final = 5088 +ERROR_RESOURCE_PROPERTY_UNCHANGEABLE: Final = 5089 +ERROR_NO_ADMIN_ACCESS_POINT: Final = 5090 +ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE: Final = 5890 +ERROR_CLUSTER_QUORUMLOG_NOT_FOUND: Final = 5891 +ERROR_CLUSTER_MEMBERSHIP_HALT: Final = 5892 +ERROR_CLUSTER_INSTANCE_ID_MISMATCH: Final = 5893 +ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP: Final = 5894 +ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH: Final = 5895 +ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP: Final = 5896 +ERROR_CLUSTER_PARAMETER_MISMATCH: Final = 5897 +ERROR_NODE_CANNOT_BE_CLUSTERED: Final = 5898 +ERROR_CLUSTER_WRONG_OS_VERSION: Final = 5899 +ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME: Final = 5900 +ERROR_CLUSCFG_ALREADY_COMMITTED: Final = 5901 +ERROR_CLUSCFG_ROLLBACK_FAILED: Final = 5902 +ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT: Final = 5903 +ERROR_CLUSTER_OLD_VERSION: Final = 5904 +ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME: Final = 5905 +ERROR_CLUSTER_NO_NET_ADAPTERS: Final = 5906 +ERROR_CLUSTER_POISONED: Final = 5907 +ERROR_CLUSTER_GROUP_MOVING: Final = 5908 +ERROR_CLUSTER_RESOURCE_TYPE_BUSY: Final = 5909 +ERROR_RESOURCE_CALL_TIMED_OUT: Final = 5910 +ERROR_INVALID_CLUSTER_IPV6_ADDRESS: Final = 5911 +ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION: Final = 5912 +ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS: Final = 5913 +ERROR_CLUSTER_PARTIAL_SEND: Final = 5914 +ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION: Final = 5915 +ERROR_CLUSTER_INVALID_STRING_TERMINATION: Final = 5916 +ERROR_CLUSTER_INVALID_STRING_FORMAT: Final = 5917 +ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS: Final = 5918 +ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS: Final = 5919 +ERROR_CLUSTER_NULL_DATA: Final = 5920 +ERROR_CLUSTER_PARTIAL_READ: Final = 5921 +ERROR_CLUSTER_PARTIAL_WRITE: Final = 5922 +ERROR_CLUSTER_CANT_DESERIALIZE_DATA: Final = 5923 +ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT: Final = 5924 +ERROR_CLUSTER_NO_QUORUM: Final = 5925 +ERROR_CLUSTER_INVALID_IPV6_NETWORK: Final = 5926 +ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK: Final = 5927 +ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP: Final = 5928 +ERROR_DEPENDENCY_TREE_TOO_COMPLEX: Final = 5929 +ERROR_EXCEPTION_IN_RESOURCE_CALL: Final = 5930 +ERROR_CLUSTER_RHS_FAILED_INITIALIZATION: Final = 5931 +ERROR_CLUSTER_NOT_INSTALLED: Final = 5932 +ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE: Final = 5933 +ERROR_CLUSTER_MAX_NODES_IN_CLUSTER: Final = 5934 +ERROR_CLUSTER_TOO_MANY_NODES: Final = 5935 +ERROR_CLUSTER_OBJECT_ALREADY_USED: Final = 5936 +ERROR_NONCORE_GROUPS_FOUND: Final = 5937 +ERROR_FILE_SHARE_RESOURCE_CONFLICT: Final = 5938 +ERROR_CLUSTER_EVICT_INVALID_REQUEST: Final = 5939 +ERROR_CLUSTER_SINGLETON_RESOURCE: Final = 5940 +ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE: Final = 5941 +ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED: Final = 5942 +ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR: Final = 5943 +ERROR_CLUSTER_GROUP_BUSY: Final = 5944 +ERROR_CLUSTER_NOT_SHARED_VOLUME: Final = 5945 +ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR: Final = 5946 +ERROR_CLUSTER_SHARED_VOLUMES_IN_USE: Final = 5947 +ERROR_CLUSTER_USE_SHARED_VOLUMES_API: Final = 5948 +ERROR_CLUSTER_BACKUP_IN_PROGRESS: Final = 5949 +ERROR_NON_CSV_PATH: Final = 5950 +ERROR_CSV_VOLUME_NOT_LOCAL: Final = 5951 +ERROR_CLUSTER_WATCHDOG_TERMINATING: Final = 5952 +ERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES: Final = 5953 +ERROR_CLUSTER_INVALID_NODE_WEIGHT: Final = 5954 +ERROR_CLUSTER_RESOURCE_VETOED_CALL: Final = 5955 +ERROR_RESMON_SYSTEM_RESOURCES_LACKING: Final = 5956 +ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION: Final = 5957 +ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE: Final = 5958 +ERROR_CLUSTER_GROUP_QUEUED: Final = 5959 +ERROR_CLUSTER_RESOURCE_LOCKED_STATUS: Final = 5960 +ERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED: Final = 5961 +ERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS: Final = 5962 +ERROR_CLUSTER_DISK_NOT_CONNECTED: Final = 5963 +ERROR_DISK_NOT_CSV_CAPABLE: Final = 5964 +ERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE: Final = 5965 +ERROR_CLUSTER_SHARED_VOLUME_REDIRECTED: Final = 5966 +ERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED: Final = 5967 +ERROR_CLUSTER_CANNOT_RETURN_PROPERTIES: Final = 5968 +ERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES: Final = 5969 +ERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE: Final = 5970 +ERROR_CLUSTER_AFFINITY_CONFLICT: Final = 5971 +ERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE: Final = 5972 +ERROR_CLUSTER_UPGRADE_INCOMPATIBLE_VERSIONS: Final = 5973 +ERROR_CLUSTER_UPGRADE_FIX_QUORUM_NOT_SUPPORTED: Final = 5974 +ERROR_CLUSTER_UPGRADE_RESTART_REQUIRED: Final = 5975 +ERROR_CLUSTER_UPGRADE_IN_PROGRESS: Final = 5976 +ERROR_CLUSTER_UPGRADE_INCOMPLETE: Final = 5977 +ERROR_CLUSTER_NODE_IN_GRACE_PERIOD: Final = 5978 +ERROR_CLUSTER_CSV_IO_PAUSE_TIMEOUT: Final = 5979 +ERROR_NODE_NOT_ACTIVE_CLUSTER_MEMBER: Final = 5980 +ERROR_CLUSTER_RESOURCE_NOT_MONITORED: Final = 5981 +ERROR_CLUSTER_RESOURCE_DOES_NOT_SUPPORT_UNMONITORED: Final = 5982 +ERROR_CLUSTER_RESOURCE_IS_REPLICATED: Final = 5983 +ERROR_CLUSTER_NODE_ISOLATED: Final = 5984 +ERROR_CLUSTER_NODE_QUARANTINED: Final = 5985 +ERROR_CLUSTER_DATABASE_UPDATE_CONDITION_FAILED: Final = 5986 +ERROR_CLUSTER_SPACE_DEGRADED: Final = 5987 +ERROR_CLUSTER_TOKEN_DELEGATION_NOT_SUPPORTED: Final = 5988 +ERROR_CLUSTER_CSV_INVALID_HANDLE: Final = 5989 +ERROR_CLUSTER_CSV_SUPPORTED_ONLY_ON_COORDINATOR: Final = 5990 +ERROR_GROUPSET_NOT_AVAILABLE: Final = 5991 +ERROR_GROUPSET_NOT_FOUND: Final = 5992 +ERROR_GROUPSET_CANT_PROVIDE: Final = 5993 +ERROR_CLUSTER_FAULT_DOMAIN_PARENT_NOT_FOUND: Final = 5994 +ERROR_CLUSTER_FAULT_DOMAIN_INVALID_HIERARCHY: Final = 5995 +ERROR_CLUSTER_FAULT_DOMAIN_FAILED_S2D_VALIDATION: Final = 5996 +ERROR_CLUSTER_FAULT_DOMAIN_S2D_CONNECTIVITY_LOSS: Final = 5997 +ERROR_CLUSTER_INVALID_INFRASTRUCTURE_FILESERVER_NAME: Final = 5998 +ERROR_CLUSTERSET_MANAGEMENT_CLUSTER_UNREACHABLE: Final = 5999 +ERROR_ENCRYPTION_FAILED: Final = 6000 +ERROR_DECRYPTION_FAILED: Final = 6001 +ERROR_FILE_ENCRYPTED: Final = 6002 +ERROR_NO_RECOVERY_POLICY: Final = 6003 +ERROR_NO_EFS: Final = 6004 +ERROR_WRONG_EFS: Final = 6005 +ERROR_NO_USER_KEYS: Final = 6006 +ERROR_FILE_NOT_ENCRYPTED: Final = 6007 +ERROR_NOT_EXPORT_FORMAT: Final = 6008 +ERROR_FILE_READ_ONLY: Final = 6009 +ERROR_DIR_EFS_DISALLOWED: Final = 6010 +ERROR_EFS_SERVER_NOT_TRUSTED: Final = 6011 +ERROR_BAD_RECOVERY_POLICY: Final = 6012 +ERROR_EFS_ALG_BLOB_TOO_BIG: Final = 6013 +ERROR_VOLUME_NOT_SUPPORT_EFS: Final = 6014 +ERROR_EFS_DISABLED: Final = 6015 +ERROR_EFS_VERSION_NOT_SUPPORT: Final = 6016 +ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE: Final = 6017 +ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER: Final = 6018 +ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE: Final = 6019 +ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE: Final = 6020 +ERROR_CS_ENCRYPTION_FILE_NOT_CSE: Final = 6021 +ERROR_ENCRYPTION_POLICY_DENIES_OPERATION: Final = 6022 +ERROR_WIP_ENCRYPTION_FAILED: Final = 6023 +ERROR_NO_BROWSER_SERVERS_FOUND: Final = 6118 +SCHED_E_SERVICE_NOT_LOCALSYSTEM: Final = 6200 +ERROR_CLUSTER_OBJECT_IS_CLUSTER_SET_VM: Final = 6250 +ERROR_LOG_SECTOR_INVALID: Final = 6600 +ERROR_LOG_SECTOR_PARITY_INVALID: Final = 6601 +ERROR_LOG_SECTOR_REMAPPED: Final = 6602 +ERROR_LOG_BLOCK_INCOMPLETE: Final = 6603 +ERROR_LOG_INVALID_RANGE: Final = 6604 +ERROR_LOG_BLOCKS_EXHAUSTED: Final = 6605 +ERROR_LOG_READ_CONTEXT_INVALID: Final = 6606 +ERROR_LOG_RESTART_INVALID: Final = 6607 +ERROR_LOG_BLOCK_VERSION: Final = 6608 +ERROR_LOG_BLOCK_INVALID: Final = 6609 +ERROR_LOG_READ_MODE_INVALID: Final = 6610 +ERROR_LOG_NO_RESTART: Final = 6611 +ERROR_LOG_METADATA_CORRUPT: Final = 6612 +ERROR_LOG_METADATA_INVALID: Final = 6613 +ERROR_LOG_METADATA_INCONSISTENT: Final = 6614 +ERROR_LOG_RESERVATION_INVALID: Final = 6615 +ERROR_LOG_CANT_DELETE: Final = 6616 +ERROR_LOG_CONTAINER_LIMIT_EXCEEDED: Final = 6617 +ERROR_LOG_START_OF_LOG: Final = 6618 +ERROR_LOG_POLICY_ALREADY_INSTALLED: Final = 6619 +ERROR_LOG_POLICY_NOT_INSTALLED: Final = 6620 +ERROR_LOG_POLICY_INVALID: Final = 6621 +ERROR_LOG_POLICY_CONFLICT: Final = 6622 +ERROR_LOG_PINNED_ARCHIVE_TAIL: Final = 6623 +ERROR_LOG_RECORD_NONEXISTENT: Final = 6624 +ERROR_LOG_RECORDS_RESERVED_INVALID: Final = 6625 +ERROR_LOG_SPACE_RESERVED_INVALID: Final = 6626 +ERROR_LOG_TAIL_INVALID: Final = 6627 +ERROR_LOG_FULL: Final = 6628 +ERROR_COULD_NOT_RESIZE_LOG: Final = 6629 +ERROR_LOG_MULTIPLEXED: Final = 6630 +ERROR_LOG_DEDICATED: Final = 6631 +ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS: Final = 6632 +ERROR_LOG_ARCHIVE_IN_PROGRESS: Final = 6633 +ERROR_LOG_EPHEMERAL: Final = 6634 +ERROR_LOG_NOT_ENOUGH_CONTAINERS: Final = 6635 +ERROR_LOG_CLIENT_ALREADY_REGISTERED: Final = 6636 +ERROR_LOG_CLIENT_NOT_REGISTERED: Final = 6637 +ERROR_LOG_FULL_HANDLER_IN_PROGRESS: Final = 6638 +ERROR_LOG_CONTAINER_READ_FAILED: Final = 6639 +ERROR_LOG_CONTAINER_WRITE_FAILED: Final = 6640 +ERROR_LOG_CONTAINER_OPEN_FAILED: Final = 6641 +ERROR_LOG_CONTAINER_STATE_INVALID: Final = 6642 +ERROR_LOG_STATE_INVALID: Final = 6643 +ERROR_LOG_PINNED: Final = 6644 +ERROR_LOG_METADATA_FLUSH_FAILED: Final = 6645 +ERROR_LOG_INCONSISTENT_SECURITY: Final = 6646 +ERROR_LOG_APPENDED_FLUSH_FAILED: Final = 6647 +ERROR_LOG_PINNED_RESERVATION: Final = 6648 +ERROR_INVALID_TRANSACTION: Final = 6700 +ERROR_TRANSACTION_NOT_ACTIVE: Final = 6701 +ERROR_TRANSACTION_REQUEST_NOT_VALID: Final = 6702 +ERROR_TRANSACTION_NOT_REQUESTED: Final = 6703 +ERROR_TRANSACTION_ALREADY_ABORTED: Final = 6704 +ERROR_TRANSACTION_ALREADY_COMMITTED: Final = 6705 +ERROR_TM_INITIALIZATION_FAILED: Final = 6706 +ERROR_RESOURCEMANAGER_READ_ONLY: Final = 6707 +ERROR_TRANSACTION_NOT_JOINED: Final = 6708 +ERROR_TRANSACTION_SUPERIOR_EXISTS: Final = 6709 +ERROR_CRM_PROTOCOL_ALREADY_EXISTS: Final = 6710 +ERROR_TRANSACTION_PROPAGATION_FAILED: Final = 6711 +ERROR_CRM_PROTOCOL_NOT_FOUND: Final = 6712 +ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER: Final = 6713 +ERROR_CURRENT_TRANSACTION_NOT_VALID: Final = 6714 +ERROR_TRANSACTION_NOT_FOUND: Final = 6715 +ERROR_RESOURCEMANAGER_NOT_FOUND: Final = 6716 +ERROR_ENLISTMENT_NOT_FOUND: Final = 6717 +ERROR_TRANSACTIONMANAGER_NOT_FOUND: Final = 6718 +ERROR_TRANSACTIONMANAGER_NOT_ONLINE: Final = 6719 +ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION: Final = 6720 +ERROR_TRANSACTION_NOT_ROOT: Final = 6721 +ERROR_TRANSACTION_OBJECT_EXPIRED: Final = 6722 +ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED: Final = 6723 +ERROR_TRANSACTION_RECORD_TOO_LONG: Final = 6724 +ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED: Final = 6725 +ERROR_TRANSACTION_INTEGRITY_VIOLATED: Final = 6726 +ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH: Final = 6727 +ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT: Final = 6728 +ERROR_TRANSACTION_MUST_WRITETHROUGH: Final = 6729 +ERROR_TRANSACTION_NO_SUPERIOR: Final = 6730 +ERROR_HEURISTIC_DAMAGE_POSSIBLE: Final = 6731 +ERROR_TRANSACTIONAL_CONFLICT: Final = 6800 +ERROR_RM_NOT_ACTIVE: Final = 6801 +ERROR_RM_METADATA_CORRUPT: Final = 6802 +ERROR_DIRECTORY_NOT_RM: Final = 6803 +ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE: Final = 6805 +ERROR_LOG_RESIZE_INVALID_SIZE: Final = 6806 +ERROR_OBJECT_NO_LONGER_EXISTS: Final = 6807 +ERROR_STREAM_MINIVERSION_NOT_FOUND: Final = 6808 +ERROR_STREAM_MINIVERSION_NOT_VALID: Final = 6809 +ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION: Final = 6810 +ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT: Final = 6811 +ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS: Final = 6812 +ERROR_REMOTE_FILE_VERSION_MISMATCH: Final = 6814 +ERROR_HANDLE_NO_LONGER_VALID: Final = 6815 +ERROR_NO_TXF_METADATA: Final = 6816 +ERROR_LOG_CORRUPTION_DETECTED: Final = 6817 +ERROR_CANT_RECOVER_WITH_HANDLE_OPEN: Final = 6818 +ERROR_RM_DISCONNECTED: Final = 6819 +ERROR_ENLISTMENT_NOT_SUPERIOR: Final = 6820 +ERROR_RECOVERY_NOT_NEEDED: Final = 6821 +ERROR_RM_ALREADY_STARTED: Final = 6822 +ERROR_FILE_IDENTITY_NOT_PERSISTENT: Final = 6823 +ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY: Final = 6824 +ERROR_CANT_CROSS_RM_BOUNDARY: Final = 6825 +ERROR_TXF_DIR_NOT_EMPTY: Final = 6826 +ERROR_INDOUBT_TRANSACTIONS_EXIST: Final = 6827 +ERROR_TM_VOLATILE: Final = 6828 +ERROR_ROLLBACK_TIMER_EXPIRED: Final = 6829 +ERROR_TXF_ATTRIBUTE_CORRUPT: Final = 6830 +ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION: Final = 6831 +ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED: Final = 6832 +ERROR_LOG_GROWTH_FAILED: Final = 6833 +ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE: Final = 6834 +ERROR_TXF_METADATA_ALREADY_PRESENT: Final = 6835 +ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET: Final = 6836 +ERROR_TRANSACTION_REQUIRED_PROMOTION: Final = 6837 +ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION: Final = 6838 +ERROR_TRANSACTIONS_NOT_FROZEN: Final = 6839 +ERROR_TRANSACTION_FREEZE_IN_PROGRESS: Final = 6840 +ERROR_NOT_SNAPSHOT_VOLUME: Final = 6841 +ERROR_NO_SAVEPOINT_WITH_OPEN_FILES: Final = 6842 +ERROR_DATA_LOST_REPAIR: Final = 6843 +ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION: Final = 6844 +ERROR_TM_IDENTITY_MISMATCH: Final = 6845 +ERROR_FLOATED_SECTION: Final = 6846 +ERROR_CANNOT_ACCEPT_TRANSACTED_WORK: Final = 6847 +ERROR_CANNOT_ABORT_TRANSACTIONS: Final = 6848 +ERROR_BAD_CLUSTERS: Final = 6849 +ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION: Final = 6850 +ERROR_VOLUME_DIRTY: Final = 6851 +ERROR_NO_LINK_TRACKING_IN_TRANSACTION: Final = 6852 +ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION: Final = 6853 +ERROR_EXPIRED_HANDLE: Final = 6854 +ERROR_TRANSACTION_NOT_ENLISTED: Final = 6855 +ERROR_CTX_WINSTATION_NAME_INVALID: Final = 7001 +ERROR_CTX_INVALID_PD: Final = 7002 +ERROR_CTX_PD_NOT_FOUND: Final = 7003 +ERROR_CTX_WD_NOT_FOUND: Final = 7004 +ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY: Final = 7005 +ERROR_CTX_SERVICE_NAME_COLLISION: Final = 7006 +ERROR_CTX_CLOSE_PENDING: Final = 7007 +ERROR_CTX_NO_OUTBUF: Final = 7008 +ERROR_CTX_MODEM_INF_NOT_FOUND: Final = 7009 +ERROR_CTX_INVALID_MODEMNAME: Final = 7010 +ERROR_CTX_MODEM_RESPONSE_ERROR: Final = 7011 +ERROR_CTX_MODEM_RESPONSE_TIMEOUT: Final = 7012 +ERROR_CTX_MODEM_RESPONSE_NO_CARRIER: Final = 7013 +ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE: Final = 7014 +ERROR_CTX_MODEM_RESPONSE_BUSY: Final = 7015 +ERROR_CTX_MODEM_RESPONSE_VOICE: Final = 7016 +ERROR_CTX_TD_ERROR: Final = 7017 +ERROR_CTX_WINSTATION_NOT_FOUND: Final = 7022 +ERROR_CTX_WINSTATION_ALREADY_EXISTS: Final = 7023 +ERROR_CTX_WINSTATION_BUSY: Final = 7024 +ERROR_CTX_BAD_VIDEO_MODE: Final = 7025 +ERROR_CTX_GRAPHICS_INVALID: Final = 7035 +ERROR_CTX_LOGON_DISABLED: Final = 7037 +ERROR_CTX_NOT_CONSOLE: Final = 7038 +ERROR_CTX_CLIENT_QUERY_TIMEOUT: Final = 7040 +ERROR_CTX_CONSOLE_DISCONNECT: Final = 7041 +ERROR_CTX_CONSOLE_CONNECT: Final = 7042 +ERROR_CTX_SHADOW_DENIED: Final = 7044 +ERROR_CTX_WINSTATION_ACCESS_DENIED: Final = 7045 +ERROR_CTX_INVALID_WD: Final = 7049 +ERROR_CTX_SHADOW_INVALID: Final = 7050 +ERROR_CTX_SHADOW_DISABLED: Final = 7051 +ERROR_CTX_CLIENT_LICENSE_IN_USE: Final = 7052 +ERROR_CTX_CLIENT_LICENSE_NOT_SET: Final = 7053 +ERROR_CTX_LICENSE_NOT_AVAILABLE: Final = 7054 +ERROR_CTX_LICENSE_CLIENT_INVALID: Final = 7055 +ERROR_CTX_LICENSE_EXPIRED: Final = 7056 +ERROR_CTX_SHADOW_NOT_RUNNING: Final = 7057 +ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE: Final = 7058 +ERROR_ACTIVATION_COUNT_EXCEEDED: Final = 7059 +ERROR_CTX_WINSTATIONS_DISABLED: Final = 7060 +ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED: Final = 7061 +ERROR_CTX_SESSION_IN_USE: Final = 7062 +ERROR_CTX_NO_FORCE_LOGOFF: Final = 7063 +ERROR_CTX_ACCOUNT_RESTRICTION: Final = 7064 +ERROR_RDP_PROTOCOL_ERROR: Final = 7065 +ERROR_CTX_CDM_CONNECT: Final = 7066 +ERROR_CTX_CDM_DISCONNECT: Final = 7067 +ERROR_CTX_SECURITY_LAYER_ERROR: Final = 7068 +ERROR_TS_INCOMPATIBLE_SESSIONS: Final = 7069 +ERROR_TS_VIDEO_SUBSYSTEM_ERROR: Final = 7070 +FRS_ERR_INVALID_API_SEQUENCE: Final = 8001 +FRS_ERR_STARTING_SERVICE: Final = 8002 +FRS_ERR_STOPPING_SERVICE: Final = 8003 +FRS_ERR_INTERNAL_API: Final = 8004 +FRS_ERR_INTERNAL: Final = 8005 +FRS_ERR_SERVICE_COMM: Final = 8006 +FRS_ERR_INSUFFICIENT_PRIV: Final = 8007 +FRS_ERR_AUTHENTICATION: Final = 8008 +FRS_ERR_PARENT_INSUFFICIENT_PRIV: Final = 8009 +FRS_ERR_PARENT_AUTHENTICATION: Final = 8010 +FRS_ERR_CHILD_TO_PARENT_COMM: Final = 8011 +FRS_ERR_PARENT_TO_CHILD_COMM: Final = 8012 +FRS_ERR_SYSVOL_POPULATE: Final = 8013 +FRS_ERR_SYSVOL_POPULATE_TIMEOUT: Final = 8014 +FRS_ERR_SYSVOL_IS_BUSY: Final = 8015 +FRS_ERR_SYSVOL_DEMOTE: Final = 8016 +FRS_ERR_INVALID_SERVICE_PARAMETER: Final = 8017 +DS_S_SUCCESS: Final = NO_ERROR +ERROR_DS_NOT_INSTALLED: Final = 8200 +ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY: Final = 8201 +ERROR_DS_NO_ATTRIBUTE_OR_VALUE: Final = 8202 +ERROR_DS_INVALID_ATTRIBUTE_SYNTAX: Final = 8203 +ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED: Final = 8204 +ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS: Final = 8205 +ERROR_DS_BUSY: Final = 8206 +ERROR_DS_UNAVAILABLE: Final = 8207 +ERROR_DS_NO_RIDS_ALLOCATED: Final = 8208 +ERROR_DS_NO_MORE_RIDS: Final = 8209 +ERROR_DS_INCORRECT_ROLE_OWNER: Final = 8210 +ERROR_DS_RIDMGR_INIT_ERROR: Final = 8211 +ERROR_DS_OBJ_CLASS_VIOLATION: Final = 8212 +ERROR_DS_CANT_ON_NON_LEAF: Final = 8213 +ERROR_DS_CANT_ON_RDN: Final = 8214 +ERROR_DS_CANT_MOD_OBJ_CLASS: Final = 8215 +ERROR_DS_CROSS_DOM_MOVE_ERROR: Final = 8216 +ERROR_DS_GC_NOT_AVAILABLE: Final = 8217 +ERROR_SHARED_POLICY: Final = 8218 +ERROR_POLICY_OBJECT_NOT_FOUND: Final = 8219 +ERROR_POLICY_ONLY_IN_DS: Final = 8220 +ERROR_PROMOTION_ACTIVE: Final = 8221 +ERROR_NO_PROMOTION_ACTIVE: Final = 8222 +ERROR_DS_OPERATIONS_ERROR: Final = 8224 +ERROR_DS_PROTOCOL_ERROR: Final = 8225 +ERROR_DS_TIMELIMIT_EXCEEDED: Final = 8226 +ERROR_DS_SIZELIMIT_EXCEEDED: Final = 8227 +ERROR_DS_ADMIN_LIMIT_EXCEEDED: Final = 8228 +ERROR_DS_COMPARE_FALSE: Final = 8229 +ERROR_DS_COMPARE_TRUE: Final = 8230 +ERROR_DS_AUTH_METHOD_NOT_SUPPORTED: Final = 8231 +ERROR_DS_STRONG_AUTH_REQUIRED: Final = 8232 +ERROR_DS_INAPPROPRIATE_AUTH: Final = 8233 +ERROR_DS_AUTH_UNKNOWN: Final = 8234 +ERROR_DS_REFERRAL: Final = 8235 +ERROR_DS_UNAVAILABLE_CRIT_EXTENSION: Final = 8236 +ERROR_DS_CONFIDENTIALITY_REQUIRED: Final = 8237 +ERROR_DS_INAPPROPRIATE_MATCHING: Final = 8238 +ERROR_DS_CONSTRAINT_VIOLATION: Final = 8239 +ERROR_DS_NO_SUCH_OBJECT: Final = 8240 +ERROR_DS_ALIAS_PROBLEM: Final = 8241 +ERROR_DS_INVALID_DN_SYNTAX: Final = 8242 +ERROR_DS_IS_LEAF: Final = 8243 +ERROR_DS_ALIAS_DEREF_PROBLEM: Final = 8244 +ERROR_DS_UNWILLING_TO_PERFORM: Final = 8245 +ERROR_DS_LOOP_DETECT: Final = 8246 +ERROR_DS_NAMING_VIOLATION: Final = 8247 +ERROR_DS_OBJECT_RESULTS_TOO_LARGE: Final = 8248 +ERROR_DS_AFFECTS_MULTIPLE_DSAS: Final = 8249 +ERROR_DS_SERVER_DOWN: Final = 8250 +ERROR_DS_LOCAL_ERROR: Final = 8251 +ERROR_DS_ENCODING_ERROR: Final = 8252 +ERROR_DS_DECODING_ERROR: Final = 8253 +ERROR_DS_FILTER_UNKNOWN: Final = 8254 +ERROR_DS_PARAM_ERROR: Final = 8255 +ERROR_DS_NOT_SUPPORTED: Final = 8256 +ERROR_DS_NO_RESULTS_RETURNED: Final = 8257 +ERROR_DS_CONTROL_NOT_FOUND: Final = 8258 +ERROR_DS_CLIENT_LOOP: Final = 8259 +ERROR_DS_REFERRAL_LIMIT_EXCEEDED: Final = 8260 +ERROR_DS_SORT_CONTROL_MISSING: Final = 8261 +ERROR_DS_OFFSET_RANGE_ERROR: Final = 8262 +ERROR_DS_RIDMGR_DISABLED: Final = 8263 +ERROR_DS_ROOT_MUST_BE_NC: Final = 8301 +ERROR_DS_ADD_REPLICA_INHIBITED: Final = 8302 +ERROR_DS_ATT_NOT_DEF_IN_SCHEMA: Final = 8303 +ERROR_DS_MAX_OBJ_SIZE_EXCEEDED: Final = 8304 +ERROR_DS_OBJ_STRING_NAME_EXISTS: Final = 8305 +ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA: Final = 8306 +ERROR_DS_RDN_DOESNT_MATCH_SCHEMA: Final = 8307 +ERROR_DS_NO_REQUESTED_ATTS_FOUND: Final = 8308 +ERROR_DS_USER_BUFFER_TO_SMALL: Final = 8309 +ERROR_DS_ATT_IS_NOT_ON_OBJ: Final = 8310 +ERROR_DS_ILLEGAL_MOD_OPERATION: Final = 8311 +ERROR_DS_OBJ_TOO_LARGE: Final = 8312 +ERROR_DS_BAD_INSTANCE_TYPE: Final = 8313 +ERROR_DS_MASTERDSA_REQUIRED: Final = 8314 +ERROR_DS_OBJECT_CLASS_REQUIRED: Final = 8315 +ERROR_DS_MISSING_REQUIRED_ATT: Final = 8316 +ERROR_DS_ATT_NOT_DEF_FOR_CLASS: Final = 8317 +ERROR_DS_ATT_ALREADY_EXISTS: Final = 8318 +ERROR_DS_CANT_ADD_ATT_VALUES: Final = 8320 +ERROR_DS_SINGLE_VALUE_CONSTRAINT: Final = 8321 +ERROR_DS_RANGE_CONSTRAINT: Final = 8322 +ERROR_DS_ATT_VAL_ALREADY_EXISTS: Final = 8323 +ERROR_DS_CANT_REM_MISSING_ATT: Final = 8324 +ERROR_DS_CANT_REM_MISSING_ATT_VAL: Final = 8325 +ERROR_DS_ROOT_CANT_BE_SUBREF: Final = 8326 +ERROR_DS_NO_CHAINING: Final = 8327 +ERROR_DS_NO_CHAINED_EVAL: Final = 8328 +ERROR_DS_NO_PARENT_OBJECT: Final = 8329 +ERROR_DS_PARENT_IS_AN_ALIAS: Final = 8330 +ERROR_DS_CANT_MIX_MASTER_AND_REPS: Final = 8331 +ERROR_DS_CHILDREN_EXIST: Final = 8332 +ERROR_DS_OBJ_NOT_FOUND: Final = 8333 +ERROR_DS_ALIASED_OBJ_MISSING: Final = 8334 +ERROR_DS_BAD_NAME_SYNTAX: Final = 8335 +ERROR_DS_ALIAS_POINTS_TO_ALIAS: Final = 8336 +ERROR_DS_CANT_DEREF_ALIAS: Final = 8337 +ERROR_DS_OUT_OF_SCOPE: Final = 8338 +ERROR_DS_OBJECT_BEING_REMOVED: Final = 8339 +ERROR_DS_CANT_DELETE_DSA_OBJ: Final = 8340 +ERROR_DS_GENERIC_ERROR: Final = 8341 +ERROR_DS_DSA_MUST_BE_INT_MASTER: Final = 8342 +ERROR_DS_CLASS_NOT_DSA: Final = 8343 +ERROR_DS_INSUFF_ACCESS_RIGHTS: Final = 8344 +ERROR_DS_ILLEGAL_SUPERIOR: Final = 8345 +ERROR_DS_ATTRIBUTE_OWNED_BY_SAM: Final = 8346 +ERROR_DS_NAME_TOO_MANY_PARTS: Final = 8347 +ERROR_DS_NAME_TOO_LONG: Final = 8348 +ERROR_DS_NAME_VALUE_TOO_LONG: Final = 8349 +ERROR_DS_NAME_UNPARSEABLE: Final = 8350 +ERROR_DS_NAME_TYPE_UNKNOWN: Final = 8351 +ERROR_DS_NOT_AN_OBJECT: Final = 8352 +ERROR_DS_SEC_DESC_TOO_SHORT: Final = 8353 +ERROR_DS_SEC_DESC_INVALID: Final = 8354 +ERROR_DS_NO_DELETED_NAME: Final = 8355 +ERROR_DS_SUBREF_MUST_HAVE_PARENT: Final = 8356 +ERROR_DS_NCNAME_MUST_BE_NC: Final = 8357 +ERROR_DS_CANT_ADD_SYSTEM_ONLY: Final = 8358 +ERROR_DS_CLASS_MUST_BE_CONCRETE: Final = 8359 +ERROR_DS_INVALID_DMD: Final = 8360 +ERROR_DS_OBJ_GUID_EXISTS: Final = 8361 +ERROR_DS_NOT_ON_BACKLINK: Final = 8362 +ERROR_DS_NO_CROSSREF_FOR_NC: Final = 8363 +ERROR_DS_SHUTTING_DOWN: Final = 8364 +ERROR_DS_UNKNOWN_OPERATION: Final = 8365 +ERROR_DS_INVALID_ROLE_OWNER: Final = 8366 +ERROR_DS_COULDNT_CONTACT_FSMO: Final = 8367 +ERROR_DS_CROSS_NC_DN_RENAME: Final = 8368 +ERROR_DS_CANT_MOD_SYSTEM_ONLY: Final = 8369 +ERROR_DS_REPLICATOR_ONLY: Final = 8370 +ERROR_DS_OBJ_CLASS_NOT_DEFINED: Final = 8371 +ERROR_DS_OBJ_CLASS_NOT_SUBCLASS: Final = 8372 +ERROR_DS_NAME_REFERENCE_INVALID: Final = 8373 +ERROR_DS_CROSS_REF_EXISTS: Final = 8374 +ERROR_DS_CANT_DEL_MASTER_CROSSREF: Final = 8375 +ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD: Final = 8376 +ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX: Final = 8377 +ERROR_DS_DUP_RDN: Final = 8378 +ERROR_DS_DUP_OID: Final = 8379 +ERROR_DS_DUP_MAPI_ID: Final = 8380 +ERROR_DS_DUP_SCHEMA_ID_GUID: Final = 8381 +ERROR_DS_DUP_LDAP_DISPLAY_NAME: Final = 8382 +ERROR_DS_SEMANTIC_ATT_TEST: Final = 8383 +ERROR_DS_SYNTAX_MISMATCH: Final = 8384 +ERROR_DS_EXISTS_IN_MUST_HAVE: Final = 8385 +ERROR_DS_EXISTS_IN_MAY_HAVE: Final = 8386 +ERROR_DS_NONEXISTENT_MAY_HAVE: Final = 8387 +ERROR_DS_NONEXISTENT_MUST_HAVE: Final = 8388 +ERROR_DS_AUX_CLS_TEST_FAIL: Final = 8389 +ERROR_DS_NONEXISTENT_POSS_SUP: Final = 8390 +ERROR_DS_SUB_CLS_TEST_FAIL: Final = 8391 +ERROR_DS_BAD_RDN_ATT_ID_SYNTAX: Final = 8392 +ERROR_DS_EXISTS_IN_AUX_CLS: Final = 8393 +ERROR_DS_EXISTS_IN_SUB_CLS: Final = 8394 +ERROR_DS_EXISTS_IN_POSS_SUP: Final = 8395 +ERROR_DS_RECALCSCHEMA_FAILED: Final = 8396 +ERROR_DS_TREE_DELETE_NOT_FINISHED: Final = 8397 +ERROR_DS_CANT_DELETE: Final = 8398 +ERROR_DS_ATT_SCHEMA_REQ_ID: Final = 8399 +ERROR_DS_BAD_ATT_SCHEMA_SYNTAX: Final = 8400 +ERROR_DS_CANT_CACHE_ATT: Final = 8401 +ERROR_DS_CANT_CACHE_CLASS: Final = 8402 +ERROR_DS_CANT_REMOVE_ATT_CACHE: Final = 8403 +ERROR_DS_CANT_REMOVE_CLASS_CACHE: Final = 8404 +ERROR_DS_CANT_RETRIEVE_DN: Final = 8405 +ERROR_DS_MISSING_SUPREF: Final = 8406 +ERROR_DS_CANT_RETRIEVE_INSTANCE: Final = 8407 +ERROR_DS_CODE_INCONSISTENCY: Final = 8408 +ERROR_DS_DATABASE_ERROR: Final = 8409 +ERROR_DS_GOVERNSID_MISSING: Final = 8410 +ERROR_DS_MISSING_EXPECTED_ATT: Final = 8411 +ERROR_DS_NCNAME_MISSING_CR_REF: Final = 8412 +ERROR_DS_SECURITY_CHECKING_ERROR: Final = 8413 +ERROR_DS_SCHEMA_NOT_LOADED: Final = 8414 +ERROR_DS_SCHEMA_ALLOC_FAILED: Final = 8415 +ERROR_DS_ATT_SCHEMA_REQ_SYNTAX: Final = 8416 +ERROR_DS_GCVERIFY_ERROR: Final = 8417 +ERROR_DS_DRA_SCHEMA_MISMATCH: Final = 8418 +ERROR_DS_CANT_FIND_DSA_OBJ: Final = 8419 +ERROR_DS_CANT_FIND_EXPECTED_NC: Final = 8420 +ERROR_DS_CANT_FIND_NC_IN_CACHE: Final = 8421 +ERROR_DS_CANT_RETRIEVE_CHILD: Final = 8422 +ERROR_DS_SECURITY_ILLEGAL_MODIFY: Final = 8423 +ERROR_DS_CANT_REPLACE_HIDDEN_REC: Final = 8424 +ERROR_DS_BAD_HIERARCHY_FILE: Final = 8425 +ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED: Final = 8426 +ERROR_DS_CONFIG_PARAM_MISSING: Final = 8427 +ERROR_DS_COUNTING_AB_INDICES_FAILED: Final = 8428 +ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED: Final = 8429 +ERROR_DS_INTERNAL_FAILURE: Final = 8430 +ERROR_DS_UNKNOWN_ERROR: Final = 8431 +ERROR_DS_ROOT_REQUIRES_CLASS_TOP: Final = 8432 +ERROR_DS_REFUSING_FSMO_ROLES: Final = 8433 +ERROR_DS_MISSING_FSMO_SETTINGS: Final = 8434 +ERROR_DS_UNABLE_TO_SURRENDER_ROLES: Final = 8435 +ERROR_DS_DRA_GENERIC: Final = 8436 +ERROR_DS_DRA_INVALID_PARAMETER: Final = 8437 +ERROR_DS_DRA_BUSY: Final = 8438 +ERROR_DS_DRA_BAD_DN: Final = 8439 +ERROR_DS_DRA_BAD_NC: Final = 8440 +ERROR_DS_DRA_DN_EXISTS: Final = 8441 +ERROR_DS_DRA_INTERNAL_ERROR: Final = 8442 +ERROR_DS_DRA_INCONSISTENT_DIT: Final = 8443 +ERROR_DS_DRA_CONNECTION_FAILED: Final = 8444 +ERROR_DS_DRA_BAD_INSTANCE_TYPE: Final = 8445 +ERROR_DS_DRA_OUT_OF_MEM: Final = 8446 +ERROR_DS_DRA_MAIL_PROBLEM: Final = 8447 +ERROR_DS_DRA_REF_ALREADY_EXISTS: Final = 8448 +ERROR_DS_DRA_REF_NOT_FOUND: Final = 8449 +ERROR_DS_DRA_OBJ_IS_REP_SOURCE: Final = 8450 +ERROR_DS_DRA_DB_ERROR: Final = 8451 +ERROR_DS_DRA_NO_REPLICA: Final = 8452 +ERROR_DS_DRA_ACCESS_DENIED: Final = 8453 +ERROR_DS_DRA_NOT_SUPPORTED: Final = 8454 +ERROR_DS_DRA_RPC_CANCELLED: Final = 8455 +ERROR_DS_DRA_SOURCE_DISABLED: Final = 8456 +ERROR_DS_DRA_SINK_DISABLED: Final = 8457 +ERROR_DS_DRA_NAME_COLLISION: Final = 8458 +ERROR_DS_DRA_SOURCE_REINSTALLED: Final = 8459 +ERROR_DS_DRA_MISSING_PARENT: Final = 8460 +ERROR_DS_DRA_PREEMPTED: Final = 8461 +ERROR_DS_DRA_ABANDON_SYNC: Final = 8462 +ERROR_DS_DRA_SHUTDOWN: Final = 8463 +ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET: Final = 8464 +ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA: Final = 8465 +ERROR_DS_DRA_EXTN_CONNECTION_FAILED: Final = 8466 +ERROR_DS_INSTALL_SCHEMA_MISMATCH: Final = 8467 +ERROR_DS_DUP_LINK_ID: Final = 8468 +ERROR_DS_NAME_ERROR_RESOLVING: Final = 8469 +ERROR_DS_NAME_ERROR_NOT_FOUND: Final = 8470 +ERROR_DS_NAME_ERROR_NOT_UNIQUE: Final = 8471 +ERROR_DS_NAME_ERROR_NO_MAPPING: Final = 8472 +ERROR_DS_NAME_ERROR_DOMAIN_ONLY: Final = 8473 +ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: Final = 8474 +ERROR_DS_CONSTRUCTED_ATT_MOD: Final = 8475 +ERROR_DS_WRONG_OM_OBJ_CLASS: Final = 8476 +ERROR_DS_DRA_REPL_PENDING: Final = 8477 +ERROR_DS_DS_REQUIRED: Final = 8478 +ERROR_DS_INVALID_LDAP_DISPLAY_NAME: Final = 8479 +ERROR_DS_NON_BASE_SEARCH: Final = 8480 +ERROR_DS_CANT_RETRIEVE_ATTS: Final = 8481 +ERROR_DS_BACKLINK_WITHOUT_LINK: Final = 8482 +ERROR_DS_EPOCH_MISMATCH: Final = 8483 +ERROR_DS_SRC_NAME_MISMATCH: Final = 8484 +ERROR_DS_SRC_AND_DST_NC_IDENTICAL: Final = 8485 +ERROR_DS_DST_NC_MISMATCH: Final = 8486 +ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC: Final = 8487 +ERROR_DS_SRC_GUID_MISMATCH: Final = 8488 +ERROR_DS_CANT_MOVE_DELETED_OBJECT: Final = 8489 +ERROR_DS_PDC_OPERATION_IN_PROGRESS: Final = 8490 +ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD: Final = 8491 +ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION: Final = 8492 +ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS: Final = 8493 +ERROR_DS_NC_MUST_HAVE_NC_PARENT: Final = 8494 +ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE: Final = 8495 +ERROR_DS_DST_DOMAIN_NOT_NATIVE: Final = 8496 +ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER: Final = 8497 +ERROR_DS_CANT_MOVE_ACCOUNT_GROUP: Final = 8498 +ERROR_DS_CANT_MOVE_RESOURCE_GROUP: Final = 8499 +ERROR_DS_INVALID_SEARCH_FLAG: Final = 8500 +ERROR_DS_NO_TREE_DELETE_ABOVE_NC: Final = 8501 +ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE: Final = 8502 +ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE: Final = 8503 +ERROR_DS_SAM_INIT_FAILURE: Final = 8504 +ERROR_DS_SENSITIVE_GROUP_VIOLATION: Final = 8505 +ERROR_DS_CANT_MOD_PRIMARYGROUPID: Final = 8506 +ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD: Final = 8507 +ERROR_DS_NONSAFE_SCHEMA_CHANGE: Final = 8508 +ERROR_DS_SCHEMA_UPDATE_DISALLOWED: Final = 8509 +ERROR_DS_CANT_CREATE_UNDER_SCHEMA: Final = 8510 +ERROR_DS_INSTALL_NO_SRC_SCH_VERSION: Final = 8511 +ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE: Final = 8512 +ERROR_DS_INVALID_GROUP_TYPE: Final = 8513 +ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: Final = 8514 +ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: Final = 8515 +ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: Final = 8516 +ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: Final = 8517 +ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: Final = 8518 +ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: Final = 8519 +ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: Final = 8520 +ERROR_DS_HAVE_PRIMARY_MEMBERS: Final = 8521 +ERROR_DS_STRING_SD_CONVERSION_FAILED: Final = 8522 +ERROR_DS_NAMING_MASTER_GC: Final = 8523 +ERROR_DS_DNS_LOOKUP_FAILURE: Final = 8524 +ERROR_DS_COULDNT_UPDATE_SPNS: Final = 8525 +ERROR_DS_CANT_RETRIEVE_SD: Final = 8526 +ERROR_DS_KEY_NOT_UNIQUE: Final = 8527 +ERROR_DS_WRONG_LINKED_ATT_SYNTAX: Final = 8528 +ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD: Final = 8529 +ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY: Final = 8530 +ERROR_DS_CANT_START: Final = 8531 +ERROR_DS_INIT_FAILURE: Final = 8532 +ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: Final = 8533 +ERROR_DS_SOURCE_DOMAIN_IN_FOREST: Final = 8534 +ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: Final = 8535 +ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: Final = 8536 +ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: Final = 8537 +ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: Final = 8538 +ERROR_DS_SRC_SID_EXISTS_IN_FOREST: Final = 8539 +ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: Final = 8540 +ERROR_SAM_INIT_FAILURE: Final = 8541 +ERROR_DS_DRA_SCHEMA_INFO_SHIP: Final = 8542 +ERROR_DS_DRA_SCHEMA_CONFLICT: Final = 8543 +ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT: Final = 8544 +ERROR_DS_DRA_OBJ_NC_MISMATCH: Final = 8545 +ERROR_DS_NC_STILL_HAS_DSAS: Final = 8546 +ERROR_DS_GC_REQUIRED: Final = 8547 +ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: Final = 8548 +ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS: Final = 8549 +ERROR_DS_CANT_ADD_TO_GC: Final = 8550 +ERROR_DS_NO_CHECKPOINT_WITH_PDC: Final = 8551 +ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: Final = 8552 +ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC: Final = 8553 +ERROR_DS_INVALID_NAME_FOR_SPN: Final = 8554 +ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS: Final = 8555 +ERROR_DS_UNICODEPWD_NOT_IN_QUOTES: Final = 8556 +ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: Final = 8557 +ERROR_DS_MUST_BE_RUN_ON_DST_DC: Final = 8558 +ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: Final = 8559 +ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ: Final = 8560 +ERROR_DS_INIT_FAILURE_CONSOLE: Final = 8561 +ERROR_DS_SAM_INIT_FAILURE_CONSOLE: Final = 8562 +ERROR_DS_FOREST_VERSION_TOO_HIGH: Final = 8563 +ERROR_DS_DOMAIN_VERSION_TOO_HIGH: Final = 8564 +ERROR_DS_FOREST_VERSION_TOO_LOW: Final = 8565 +ERROR_DS_DOMAIN_VERSION_TOO_LOW: Final = 8566 +ERROR_DS_INCOMPATIBLE_VERSION: Final = 8567 +ERROR_DS_LOW_DSA_VERSION: Final = 8568 +ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN: Final = 8569 +ERROR_DS_NOT_SUPPORTED_SORT_ORDER: Final = 8570 +ERROR_DS_NAME_NOT_UNIQUE: Final = 8571 +ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4: Final = 8572 +ERROR_DS_OUT_OF_VERSION_STORE: Final = 8573 +ERROR_DS_INCOMPATIBLE_CONTROLS_USED: Final = 8574 +ERROR_DS_NO_REF_DOMAIN: Final = 8575 +ERROR_DS_RESERVED_LINK_ID: Final = 8576 +ERROR_DS_LINK_ID_NOT_AVAILABLE: Final = 8577 +ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: Final = 8578 +ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE: Final = 8579 +ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC: Final = 8580 +ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG: Final = 8581 +ERROR_DS_MODIFYDN_WRONG_GRANDPARENT: Final = 8582 +ERROR_DS_NAME_ERROR_TRUST_REFERRAL: Final = 8583 +ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER: Final = 8584 +ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD: Final = 8585 +ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2: Final = 8586 +ERROR_DS_THREAD_LIMIT_EXCEEDED: Final = 8587 +ERROR_DS_NOT_CLOSEST: Final = 8588 +ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF: Final = 8589 +ERROR_DS_SINGLE_USER_MODE_FAILED: Final = 8590 +ERROR_DS_NTDSCRIPT_SYNTAX_ERROR: Final = 8591 +ERROR_DS_NTDSCRIPT_PROCESS_ERROR: Final = 8592 +ERROR_DS_DIFFERENT_REPL_EPOCHS: Final = 8593 +ERROR_DS_DRS_EXTENSIONS_CHANGED: Final = 8594 +ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR: Final = 8595 +ERROR_DS_NO_MSDS_INTID: Final = 8596 +ERROR_DS_DUP_MSDS_INTID: Final = 8597 +ERROR_DS_EXISTS_IN_RDNATTID: Final = 8598 +ERROR_DS_AUTHORIZATION_FAILED: Final = 8599 +ERROR_DS_INVALID_SCRIPT: Final = 8600 +ERROR_DS_REMOTE_CROSSREF_OP_FAILED: Final = 8601 +ERROR_DS_CROSS_REF_BUSY: Final = 8602 +ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN: Final = 8603 +ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC: Final = 8604 +ERROR_DS_DUPLICATE_ID_FOUND: Final = 8605 +ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT: Final = 8606 +ERROR_DS_GROUP_CONVERSION_ERROR: Final = 8607 +ERROR_DS_CANT_MOVE_APP_BASIC_GROUP: Final = 8608 +ERROR_DS_CANT_MOVE_APP_QUERY_GROUP: Final = 8609 +ERROR_DS_ROLE_NOT_VERIFIED: Final = 8610 +ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL: Final = 8611 +ERROR_DS_DOMAIN_RENAME_IN_PROGRESS: Final = 8612 +ERROR_DS_EXISTING_AD_CHILD_NC: Final = 8613 +ERROR_DS_REPL_LIFETIME_EXCEEDED: Final = 8614 +ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER: Final = 8615 +ERROR_DS_LDAP_SEND_QUEUE_FULL: Final = 8616 +ERROR_DS_DRA_OUT_SCHEDULE_WINDOW: Final = 8617 +ERROR_DS_POLICY_NOT_KNOWN: Final = 8618 +ERROR_NO_SITE_SETTINGS_OBJECT: Final = 8619 +ERROR_NO_SECRETS: Final = 8620 +ERROR_NO_WRITABLE_DC_FOUND: Final = 8621 +ERROR_DS_NO_SERVER_OBJECT: Final = 8622 +ERROR_DS_NO_NTDSA_OBJECT: Final = 8623 +ERROR_DS_NON_ASQ_SEARCH: Final = 8624 +ERROR_DS_AUDIT_FAILURE: Final = 8625 +ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE: Final = 8626 +ERROR_DS_INVALID_SEARCH_FLAG_TUPLE: Final = 8627 +ERROR_DS_HIERARCHY_TABLE_TOO_DEEP: Final = 8628 +ERROR_DS_DRA_CORRUPT_UTD_VECTOR: Final = 8629 +ERROR_DS_DRA_SECRETS_DENIED: Final = 8630 +ERROR_DS_RESERVED_MAPI_ID: Final = 8631 +ERROR_DS_MAPI_ID_NOT_AVAILABLE: Final = 8632 +ERROR_DS_DRA_MISSING_KRBTGT_SECRET: Final = 8633 +ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST: Final = 8634 +ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST: Final = 8635 +ERROR_INVALID_USER_PRINCIPAL_NAME: Final = 8636 +ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS: Final = 8637 +ERROR_DS_OID_NOT_FOUND: Final = 8638 +ERROR_DS_DRA_RECYCLED_TARGET: Final = 8639 +ERROR_DS_DISALLOWED_NC_REDIRECT: Final = 8640 +ERROR_DS_HIGH_ADLDS_FFL: Final = 8641 +ERROR_DS_HIGH_DSA_VERSION: Final = 8642 +ERROR_DS_LOW_ADLDS_FFL: Final = 8643 +ERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION: Final = 8644 +ERROR_DS_UNDELETE_SAM_VALIDATION_FAILED: Final = 8645 +ERROR_INCORRECT_ACCOUNT_TYPE: Final = 8646 +ERROR_DS_SPN_VALUE_NOT_UNIQUE_IN_FOREST: Final = 8647 +ERROR_DS_UPN_VALUE_NOT_UNIQUE_IN_FOREST: Final = 8648 +ERROR_DS_MISSING_FOREST_TRUST: Final = 8649 +ERROR_DS_VALUE_KEY_NOT_UNIQUE: Final = 8650 +ERROR_WEAK_WHFBKEY_BLOCKED: Final = 8651 +ERROR_DS_PER_ATTRIBUTE_AUTHZ_FAILED_DURING_ADD: Final = 8652 +ERROR_LOCAL_POLICY_MODIFICATION_NOT_SUPPORTED: Final = 8653 +ERROR_POLICY_CONTROLLED_ACCOUNT: Final = 8654 +ERROR_LAPS_LEGACY_SCHEMA_MISSING: Final = 8655 +ERROR_LAPS_SCHEMA_MISSING: Final = 8656 +ERROR_LAPS_ENCRYPTION_REQUIRES_2016_DFL: Final = 8657 +DNS_ERROR_RESPONSE_CODES_BASE: Final = 9000 +DNS_ERROR_RCODE_NO_ERROR: Final = NO_ERROR +DNS_ERROR_MASK: Final = 0x00002328 +DNS_ERROR_RCODE_FORMAT_ERROR: Final = 9001 +DNS_ERROR_RCODE_SERVER_FAILURE: Final = 9002 +DNS_ERROR_RCODE_NAME_ERROR: Final = 9003 +DNS_ERROR_RCODE_NOT_IMPLEMENTED: Final = 9004 +DNS_ERROR_RCODE_REFUSED: Final = 9005 +DNS_ERROR_RCODE_YXDOMAIN: Final = 9006 +DNS_ERROR_RCODE_YXRRSET: Final = 9007 +DNS_ERROR_RCODE_NXRRSET: Final = 9008 +DNS_ERROR_RCODE_NOTAUTH: Final = 9009 +DNS_ERROR_RCODE_NOTZONE: Final = 9010 +DNS_ERROR_RCODE_BADSIG: Final = 9016 +DNS_ERROR_RCODE_BADKEY: Final = 9017 +DNS_ERROR_RCODE_BADTIME: Final = 9018 +DNS_ERROR_RCODE_LAST: Final = DNS_ERROR_RCODE_BADTIME +DNS_ERROR_DNSSEC_BASE: Final = 9100 +DNS_ERROR_KEYMASTER_REQUIRED: Final = 9101 +DNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE: Final = 9102 +DNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1: Final = 9103 +DNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS: Final = 9104 +DNS_ERROR_UNSUPPORTED_ALGORITHM: Final = 9105 +DNS_ERROR_INVALID_KEY_SIZE: Final = 9106 +DNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE: Final = 9107 +DNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION: Final = 9108 +DNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR: Final = 9109 +DNS_ERROR_UNEXPECTED_CNG_ERROR: Final = 9110 +DNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION: Final = 9111 +DNS_ERROR_KSP_NOT_ACCESSIBLE: Final = 9112 +DNS_ERROR_TOO_MANY_SKDS: Final = 9113 +DNS_ERROR_INVALID_ROLLOVER_PERIOD: Final = 9114 +DNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET: Final = 9115 +DNS_ERROR_ROLLOVER_IN_PROGRESS: Final = 9116 +DNS_ERROR_STANDBY_KEY_NOT_PRESENT: Final = 9117 +DNS_ERROR_NOT_ALLOWED_ON_ZSK: Final = 9118 +DNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD: Final = 9119 +DNS_ERROR_ROLLOVER_ALREADY_QUEUED: Final = 9120 +DNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE: Final = 9121 +DNS_ERROR_BAD_KEYMASTER: Final = 9122 +DNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD: Final = 9123 +DNS_ERROR_INVALID_NSEC3_ITERATION_COUNT: Final = 9124 +DNS_ERROR_DNSSEC_IS_DISABLED: Final = 9125 +DNS_ERROR_INVALID_XML: Final = 9126 +DNS_ERROR_NO_VALID_TRUST_ANCHORS: Final = 9127 +DNS_ERROR_ROLLOVER_NOT_POKEABLE: Final = 9128 +DNS_ERROR_NSEC3_NAME_COLLISION: Final = 9129 +DNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1: Final = 9130 +DNS_ERROR_PACKET_FMT_BASE: Final = 9500 +DNS_INFO_NO_RECORDS: Final = 9501 +DNS_ERROR_BAD_PACKET: Final = 9502 +DNS_ERROR_NO_PACKET: Final = 9503 +DNS_ERROR_RCODE: Final = 9504 +DNS_ERROR_UNSECURE_PACKET: Final = 9505 +DNS_STATUS_PACKET_UNSECURE: Final = DNS_ERROR_UNSECURE_PACKET +DNS_REQUEST_PENDING: Final = 9506 +DNS_ERROR_NO_MEMORY: Final = ERROR_OUTOFMEMORY +DNS_ERROR_INVALID_NAME: Final = ERROR_INVALID_NAME +DNS_ERROR_INVALID_DATA: Final = ERROR_INVALID_DATA +DNS_ERROR_GENERAL_API_BASE: Final = 9550 +DNS_ERROR_INVALID_TYPE: Final = 9551 +DNS_ERROR_INVALID_IP_ADDRESS: Final = 9552 +DNS_ERROR_INVALID_PROPERTY: Final = 9553 +DNS_ERROR_TRY_AGAIN_LATER: Final = 9554 +DNS_ERROR_NOT_UNIQUE: Final = 9555 +DNS_ERROR_NON_RFC_NAME: Final = 9556 +DNS_STATUS_FQDN: Final = 9557 +DNS_STATUS_DOTTED_NAME: Final = 9558 +DNS_STATUS_SINGLE_PART_NAME: Final = 9559 +DNS_ERROR_INVALID_NAME_CHAR: Final = 9560 +DNS_ERROR_NUMERIC_NAME: Final = 9561 +DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER: Final = 9562 +DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION: Final = 9563 +DNS_ERROR_CANNOT_FIND_ROOT_HINTS: Final = 9564 +DNS_ERROR_INCONSISTENT_ROOT_HINTS: Final = 9565 +DNS_ERROR_DWORD_VALUE_TOO_SMALL: Final = 9566 +DNS_ERROR_DWORD_VALUE_TOO_LARGE: Final = 9567 +DNS_ERROR_BACKGROUND_LOADING: Final = 9568 +DNS_ERROR_NOT_ALLOWED_ON_RODC: Final = 9569 +DNS_ERROR_NOT_ALLOWED_UNDER_DNAME: Final = 9570 +DNS_ERROR_DELEGATION_REQUIRED: Final = 9571 +DNS_ERROR_INVALID_POLICY_TABLE: Final = 9572 +DNS_ERROR_ADDRESS_REQUIRED: Final = 9573 +DNS_ERROR_ZONE_BASE: Final = 9600 +DNS_ERROR_ZONE_DOES_NOT_EXIST: Final = 9601 +DNS_ERROR_NO_ZONE_INFO: Final = 9602 +DNS_ERROR_INVALID_ZONE_OPERATION: Final = 9603 +DNS_ERROR_ZONE_CONFIGURATION_ERROR: Final = 9604 +DNS_ERROR_ZONE_HAS_NO_SOA_RECORD: Final = 9605 +DNS_ERROR_ZONE_HAS_NO_NS_RECORDS: Final = 9606 +DNS_ERROR_ZONE_LOCKED: Final = 9607 +DNS_ERROR_ZONE_CREATION_FAILED: Final = 9608 +DNS_ERROR_ZONE_ALREADY_EXISTS: Final = 9609 +DNS_ERROR_AUTOZONE_ALREADY_EXISTS: Final = 9610 +DNS_ERROR_INVALID_ZONE_TYPE: Final = 9611 +DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP: Final = 9612 +DNS_ERROR_ZONE_NOT_SECONDARY: Final = 9613 +DNS_ERROR_NEED_SECONDARY_ADDRESSES: Final = 9614 +DNS_ERROR_WINS_INIT_FAILED: Final = 9615 +DNS_ERROR_NEED_WINS_SERVERS: Final = 9616 +DNS_ERROR_NBSTAT_INIT_FAILED: Final = 9617 +DNS_ERROR_SOA_DELETE_INVALID: Final = 9618 +DNS_ERROR_FORWARDER_ALREADY_EXISTS: Final = 9619 +DNS_ERROR_ZONE_REQUIRES_MASTER_IP: Final = 9620 +DNS_ERROR_ZONE_IS_SHUTDOWN: Final = 9621 +DNS_ERROR_ZONE_LOCKED_FOR_SIGNING: Final = 9622 +DNS_ERROR_DATAFILE_BASE: Final = 9650 +DNS_ERROR_PRIMARY_REQUIRES_DATAFILE: Final = 9651 +DNS_ERROR_INVALID_DATAFILE_NAME: Final = 9652 +DNS_ERROR_DATAFILE_OPEN_FAILURE: Final = 9653 +DNS_ERROR_FILE_WRITEBACK_FAILED: Final = 9654 +DNS_ERROR_DATAFILE_PARSING: Final = 9655 +DNS_ERROR_DATABASE_BASE: Final = 9700 +DNS_ERROR_RECORD_DOES_NOT_EXIST: Final = 9701 +DNS_ERROR_RECORD_FORMAT: Final = 9702 +DNS_ERROR_NODE_CREATION_FAILED: Final = 9703 +DNS_ERROR_UNKNOWN_RECORD_TYPE: Final = 9704 +DNS_ERROR_RECORD_TIMED_OUT: Final = 9705 +DNS_ERROR_NAME_NOT_IN_ZONE: Final = 9706 +DNS_ERROR_CNAME_LOOP: Final = 9707 +DNS_ERROR_NODE_IS_CNAME: Final = 9708 +DNS_ERROR_CNAME_COLLISION: Final = 9709 +DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT: Final = 9710 +DNS_ERROR_RECORD_ALREADY_EXISTS: Final = 9711 +DNS_ERROR_SECONDARY_DATA: Final = 9712 +DNS_ERROR_NO_CREATE_CACHE_DATA: Final = 9713 +DNS_ERROR_NAME_DOES_NOT_EXIST: Final = 9714 +DNS_WARNING_PTR_CREATE_FAILED: Final = 9715 +DNS_WARNING_DOMAIN_UNDELETED: Final = 9716 +DNS_ERROR_DS_UNAVAILABLE: Final = 9717 +DNS_ERROR_DS_ZONE_ALREADY_EXISTS: Final = 9718 +DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE: Final = 9719 +DNS_ERROR_NODE_IS_DNAME: Final = 9720 +DNS_ERROR_DNAME_COLLISION: Final = 9721 +DNS_ERROR_ALIAS_LOOP: Final = 9722 +DNS_ERROR_OPERATION_BASE: Final = 9750 +DNS_INFO_AXFR_COMPLETE: Final = 9751 +DNS_ERROR_AXFR: Final = 9752 +DNS_INFO_ADDED_LOCAL_WINS: Final = 9753 +DNS_ERROR_SECURE_BASE: Final = 9800 +DNS_STATUS_CONTINUE_NEEDED: Final = 9801 +DNS_ERROR_SETUP_BASE: Final = 9850 +DNS_ERROR_NO_TCPIP: Final = 9851 +DNS_ERROR_NO_DNS_SERVERS: Final = 9852 +DNS_ERROR_DP_BASE: Final = 9900 +DNS_ERROR_DP_DOES_NOT_EXIST: Final = 9901 +DNS_ERROR_DP_ALREADY_EXISTS: Final = 9902 +DNS_ERROR_DP_NOT_ENLISTED: Final = 9903 +DNS_ERROR_DP_ALREADY_ENLISTED: Final = 9904 +DNS_ERROR_DP_NOT_AVAILABLE: Final = 9905 +DNS_ERROR_DP_FSMO_ERROR: Final = 9906 +DNS_ERROR_RRL_NOT_ENABLED: Final = 9911 +DNS_ERROR_RRL_INVALID_WINDOW_SIZE: Final = 9912 +DNS_ERROR_RRL_INVALID_IPV4_PREFIX: Final = 9913 +DNS_ERROR_RRL_INVALID_IPV6_PREFIX: Final = 9914 +DNS_ERROR_RRL_INVALID_TC_RATE: Final = 9915 +DNS_ERROR_RRL_INVALID_LEAK_RATE: Final = 9916 +DNS_ERROR_RRL_LEAK_RATE_LESSTHAN_TC_RATE: Final = 9917 +DNS_ERROR_VIRTUALIZATION_INSTANCE_ALREADY_EXISTS: Final = 9921 +DNS_ERROR_VIRTUALIZATION_INSTANCE_DOES_NOT_EXIST: Final = 9922 +DNS_ERROR_VIRTUALIZATION_TREE_LOCKED: Final = 9923 +DNS_ERROR_INVAILD_VIRTUALIZATION_INSTANCE_NAME: Final = 9924 +DNS_ERROR_DEFAULT_VIRTUALIZATION_INSTANCE: Final = 9925 +DNS_ERROR_ZONESCOPE_ALREADY_EXISTS: Final = 9951 +DNS_ERROR_ZONESCOPE_DOES_NOT_EXIST: Final = 9952 +DNS_ERROR_DEFAULT_ZONESCOPE: Final = 9953 +DNS_ERROR_INVALID_ZONESCOPE_NAME: Final = 9954 +DNS_ERROR_NOT_ALLOWED_WITH_ZONESCOPES: Final = 9955 +DNS_ERROR_LOAD_ZONESCOPE_FAILED: Final = 9956 +DNS_ERROR_ZONESCOPE_FILE_WRITEBACK_FAILED: Final = 9957 +DNS_ERROR_INVALID_SCOPE_NAME: Final = 9958 +DNS_ERROR_SCOPE_DOES_NOT_EXIST: Final = 9959 +DNS_ERROR_DEFAULT_SCOPE: Final = 9960 +DNS_ERROR_INVALID_SCOPE_OPERATION: Final = 9961 +DNS_ERROR_SCOPE_LOCKED: Final = 9962 +DNS_ERROR_SCOPE_ALREADY_EXISTS: Final = 9963 +DNS_ERROR_POLICY_ALREADY_EXISTS: Final = 9971 +DNS_ERROR_POLICY_DOES_NOT_EXIST: Final = 9972 +DNS_ERROR_POLICY_INVALID_CRITERIA: Final = 9973 +DNS_ERROR_POLICY_INVALID_SETTINGS: Final = 9974 +DNS_ERROR_CLIENT_SUBNET_IS_ACCESSED: Final = 9975 +DNS_ERROR_CLIENT_SUBNET_DOES_NOT_EXIST: Final = 9976 +DNS_ERROR_CLIENT_SUBNET_ALREADY_EXISTS: Final = 9977 +DNS_ERROR_SUBNET_DOES_NOT_EXIST: Final = 9978 +DNS_ERROR_SUBNET_ALREADY_EXISTS: Final = 9979 +DNS_ERROR_POLICY_LOCKED: Final = 9980 +DNS_ERROR_POLICY_INVALID_WEIGHT: Final = 9981 +DNS_ERROR_POLICY_INVALID_NAME: Final = 9982 +DNS_ERROR_POLICY_MISSING_CRITERIA: Final = 9983 +DNS_ERROR_INVALID_CLIENT_SUBNET_NAME: Final = 9984 +DNS_ERROR_POLICY_PROCESSING_ORDER_INVALID: Final = 9985 +DNS_ERROR_POLICY_SCOPE_MISSING: Final = 9986 +DNS_ERROR_POLICY_SCOPE_NOT_ALLOWED: Final = 9987 +DNS_ERROR_SERVERSCOPE_IS_REFERENCED: Final = 9988 +DNS_ERROR_ZONESCOPE_IS_REFERENCED: Final = 9989 +DNS_ERROR_POLICY_INVALID_CRITERIA_CLIENT_SUBNET: Final = 9990 +DNS_ERROR_POLICY_INVALID_CRITERIA_TRANSPORT_PROTOCOL: Final = 9991 +DNS_ERROR_POLICY_INVALID_CRITERIA_NETWORK_PROTOCOL: Final = 9992 +DNS_ERROR_POLICY_INVALID_CRITERIA_INTERFACE: Final = 9993 +DNS_ERROR_POLICY_INVALID_CRITERIA_FQDN: Final = 9994 +DNS_ERROR_POLICY_INVALID_CRITERIA_QUERY_TYPE: Final = 9995 +DNS_ERROR_POLICY_INVALID_CRITERIA_TIME_OF_DAY: Final = 9996 +WSABASEERR: Final = 10000 +WSAEINTR: Final = 10004 +WSAEBADF: Final = 10009 +WSAEACCES: Final = 10013 +WSAEFAULT: Final = 10014 +WSAEINVAL: Final = 10022 +WSAEMFILE: Final = 10024 +WSAEWOULDBLOCK: Final = 10035 +WSAEINPROGRESS: Final = 10036 +WSAEALREADY: Final = 10037 +WSAENOTSOCK: Final = 10038 +WSAEDESTADDRREQ: Final = 10039 +WSAEMSGSIZE: Final = 10040 +WSAEPROTOTYPE: Final = 10041 +WSAENOPROTOOPT: Final = 10042 +WSAEPROTONOSUPPORT: Final = 10043 +WSAESOCKTNOSUPPORT: Final = 10044 +WSAEOPNOTSUPP: Final = 10045 +WSAEPFNOSUPPORT: Final = 10046 +WSAEAFNOSUPPORT: Final = 10047 +WSAEADDRINUSE: Final = 10048 +WSAEADDRNOTAVAIL: Final = 10049 +WSAENETDOWN: Final = 10050 +WSAENETUNREACH: Final = 10051 +WSAENETRESET: Final = 10052 +WSAECONNABORTED: Final = 10053 +WSAECONNRESET: Final = 10054 +WSAENOBUFS: Final = 10055 +WSAEISCONN: Final = 10056 +WSAENOTCONN: Final = 10057 +WSAESHUTDOWN: Final = 10058 +WSAETOOMANYREFS: Final = 10059 +WSAETIMEDOUT: Final = 10060 +WSAECONNREFUSED: Final = 10061 +WSAELOOP: Final = 10062 +WSAENAMETOOLONG: Final = 10063 +WSAEHOSTDOWN: Final = 10064 +WSAEHOSTUNREACH: Final = 10065 +WSAENOTEMPTY: Final = 10066 +WSAEPROCLIM: Final = 10067 +WSAEUSERS: Final = 10068 +WSAEDQUOT: Final = 10069 +WSAESTALE: Final = 10070 +WSAEREMOTE: Final = 10071 +WSASYSNOTREADY: Final = 10091 +WSAVERNOTSUPPORTED: Final = 10092 +WSANOTINITIALISED: Final = 10093 +WSAEDISCON: Final = 10101 +WSAENOMORE: Final = 10102 +WSAECANCELLED: Final = 10103 +WSAEINVALIDPROCTABLE: Final = 10104 +WSAEINVALIDPROVIDER: Final = 10105 +WSAEPROVIDERFAILEDINIT: Final = 10106 +WSASYSCALLFAILURE: Final = 10107 +WSASERVICE_NOT_FOUND: Final = 10108 +WSATYPE_NOT_FOUND: Final = 10109 +WSA_E_NO_MORE: Final = 10110 +WSA_E_CANCELLED: Final = 10111 +WSAEREFUSED: Final = 10112 +WSAHOST_NOT_FOUND: Final = 11001 +WSATRY_AGAIN: Final = 11002 +WSANO_RECOVERY: Final = 11003 +WSANO_DATA: Final = 11004 +WSA_QOS_RECEIVERS: Final = 11005 +WSA_QOS_SENDERS: Final = 11006 +WSA_QOS_NO_SENDERS: Final = 11007 +WSA_QOS_NO_RECEIVERS: Final = 11008 +WSA_QOS_REQUEST_CONFIRMED: Final = 11009 +WSA_QOS_ADMISSION_FAILURE: Final = 11010 +WSA_QOS_POLICY_FAILURE: Final = 11011 +WSA_QOS_BAD_STYLE: Final = 11012 +WSA_QOS_BAD_OBJECT: Final = 11013 +WSA_QOS_TRAFFIC_CTRL_ERROR: Final = 11014 +WSA_QOS_GENERIC_ERROR: Final = 11015 +WSA_QOS_ESERVICETYPE: Final = 11016 +WSA_QOS_EFLOWSPEC: Final = 11017 +WSA_QOS_EPROVSPECBUF: Final = 11018 +WSA_QOS_EFILTERSTYLE: Final = 11019 +WSA_QOS_EFILTERTYPE: Final = 11020 +WSA_QOS_EFILTERCOUNT: Final = 11021 +WSA_QOS_EOBJLENGTH: Final = 11022 +WSA_QOS_EFLOWCOUNT: Final = 11023 +WSA_QOS_EUNKOWNPSOBJ: Final = 11024 +WSA_QOS_EPOLICYOBJ: Final = 11025 +WSA_QOS_EFLOWDESC: Final = 11026 +WSA_QOS_EPSFLOWSPEC: Final = 11027 +WSA_QOS_EPSFILTERSPEC: Final = 11028 +WSA_QOS_ESDMODEOBJ: Final = 11029 +WSA_QOS_ESHAPERATEOBJ: Final = 11030 +WSA_QOS_RESERVED_PETYPE: Final = 11031 +WSA_SECURE_HOST_NOT_FOUND: Final = 11032 +WSA_IPSEC_NAME_POLICY_ERROR: Final = 11033 +ERROR_IPSEC_QM_POLICY_EXISTS: Final = 13000 +ERROR_IPSEC_QM_POLICY_NOT_FOUND: Final = 13001 +ERROR_IPSEC_QM_POLICY_IN_USE: Final = 13002 +ERROR_IPSEC_MM_POLICY_EXISTS: Final = 13003 +ERROR_IPSEC_MM_POLICY_NOT_FOUND: Final = 13004 +ERROR_IPSEC_MM_POLICY_IN_USE: Final = 13005 +ERROR_IPSEC_MM_FILTER_EXISTS: Final = 13006 +ERROR_IPSEC_MM_FILTER_NOT_FOUND: Final = 13007 +ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: Final = 13008 +ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: Final = 13009 +ERROR_IPSEC_MM_AUTH_EXISTS: Final = 13010 +ERROR_IPSEC_MM_AUTH_NOT_FOUND: Final = 13011 +ERROR_IPSEC_MM_AUTH_IN_USE: Final = 13012 +ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: Final = 13013 +ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: Final = 13014 +ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: Final = 13015 +ERROR_IPSEC_TUNNEL_FILTER_EXISTS: Final = 13016 +ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: Final = 13017 +ERROR_IPSEC_MM_FILTER_PENDING_DELETION: Final = 13018 +ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: Final = 13019 +ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: Final = 13020 +ERROR_IPSEC_MM_POLICY_PENDING_DELETION: Final = 13021 +ERROR_IPSEC_MM_AUTH_PENDING_DELETION: Final = 13022 +ERROR_IPSEC_QM_POLICY_PENDING_DELETION: Final = 13023 +WARNING_IPSEC_MM_POLICY_PRUNED: Final = 13024 +WARNING_IPSEC_QM_POLICY_PRUNED: Final = 13025 +ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: Final = 13800 +ERROR_IPSEC_IKE_AUTH_FAIL: Final = 13801 +ERROR_IPSEC_IKE_ATTRIB_FAIL: Final = 13802 +ERROR_IPSEC_IKE_NEGOTIATION_PENDING: Final = 13803 +ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: Final = 13804 +ERROR_IPSEC_IKE_TIMED_OUT: Final = 13805 +ERROR_IPSEC_IKE_NO_CERT: Final = 13806 +ERROR_IPSEC_IKE_SA_DELETED: Final = 13807 +ERROR_IPSEC_IKE_SA_REAPED: Final = 13808 +ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: Final = 13809 +ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: Final = 13810 +ERROR_IPSEC_IKE_QUEUE_DROP_MM: Final = 13811 +ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: Final = 13812 +ERROR_IPSEC_IKE_DROP_NO_RESPONSE: Final = 13813 +ERROR_IPSEC_IKE_MM_DELAY_DROP: Final = 13814 +ERROR_IPSEC_IKE_QM_DELAY_DROP: Final = 13815 +ERROR_IPSEC_IKE_ERROR: Final = 13816 +ERROR_IPSEC_IKE_CRL_FAILED: Final = 13817 +ERROR_IPSEC_IKE_INVALID_KEY_USAGE: Final = 13818 +ERROR_IPSEC_IKE_INVALID_CERT_TYPE: Final = 13819 +ERROR_IPSEC_IKE_NO_PRIVATE_KEY: Final = 13820 +ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY: Final = 13821 +ERROR_IPSEC_IKE_DH_FAIL: Final = 13822 +ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED: Final = 13823 +ERROR_IPSEC_IKE_INVALID_HEADER: Final = 13824 +ERROR_IPSEC_IKE_NO_POLICY: Final = 13825 +ERROR_IPSEC_IKE_INVALID_SIGNATURE: Final = 13826 +ERROR_IPSEC_IKE_KERBEROS_ERROR: Final = 13827 +ERROR_IPSEC_IKE_NO_PUBLIC_KEY: Final = 13828 +ERROR_IPSEC_IKE_PROCESS_ERR: Final = 13829 +ERROR_IPSEC_IKE_PROCESS_ERR_SA: Final = 13830 +ERROR_IPSEC_IKE_PROCESS_ERR_PROP: Final = 13831 +ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: Final = 13832 +ERROR_IPSEC_IKE_PROCESS_ERR_KE: Final = 13833 +ERROR_IPSEC_IKE_PROCESS_ERR_ID: Final = 13834 +ERROR_IPSEC_IKE_PROCESS_ERR_CERT: Final = 13835 +ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: Final = 13836 +ERROR_IPSEC_IKE_PROCESS_ERR_HASH: Final = 13837 +ERROR_IPSEC_IKE_PROCESS_ERR_SIG: Final = 13838 +ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: Final = 13839 +ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: Final = 13840 +ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: Final = 13841 +ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: Final = 13842 +ERROR_IPSEC_IKE_INVALID_PAYLOAD: Final = 13843 +ERROR_IPSEC_IKE_LOAD_SOFT_SA: Final = 13844 +ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: Final = 13845 +ERROR_IPSEC_IKE_INVALID_COOKIE: Final = 13846 +ERROR_IPSEC_IKE_NO_PEER_CERT: Final = 13847 +ERROR_IPSEC_IKE_PEER_CRL_FAILED: Final = 13848 +ERROR_IPSEC_IKE_POLICY_CHANGE: Final = 13849 +ERROR_IPSEC_IKE_NO_MM_POLICY: Final = 13850 +ERROR_IPSEC_IKE_NOTCBPRIV: Final = 13851 +ERROR_IPSEC_IKE_SECLOADFAIL: Final = 13852 +ERROR_IPSEC_IKE_FAILSSPINIT: Final = 13853 +ERROR_IPSEC_IKE_FAILQUERYSSP: Final = 13854 +ERROR_IPSEC_IKE_SRVACQFAIL: Final = 13855 +ERROR_IPSEC_IKE_SRVQUERYCRED: Final = 13856 +ERROR_IPSEC_IKE_GETSPIFAIL: Final = 13857 +ERROR_IPSEC_IKE_INVALID_FILTER: Final = 13858 +ERROR_IPSEC_IKE_OUT_OF_MEMORY: Final = 13859 +ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: Final = 13860 +ERROR_IPSEC_IKE_INVALID_POLICY: Final = 13861 +ERROR_IPSEC_IKE_UNKNOWN_DOI: Final = 13862 +ERROR_IPSEC_IKE_INVALID_SITUATION: Final = 13863 +ERROR_IPSEC_IKE_DH_FAILURE: Final = 13864 +ERROR_IPSEC_IKE_INVALID_GROUP: Final = 13865 +ERROR_IPSEC_IKE_ENCRYPT: Final = 13866 +ERROR_IPSEC_IKE_DECRYPT: Final = 13867 +ERROR_IPSEC_IKE_POLICY_MATCH: Final = 13868 +ERROR_IPSEC_IKE_UNSUPPORTED_ID: Final = 13869 +ERROR_IPSEC_IKE_INVALID_HASH: Final = 13870 +ERROR_IPSEC_IKE_INVALID_HASH_ALG: Final = 13871 +ERROR_IPSEC_IKE_INVALID_HASH_SIZE: Final = 13872 +ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: Final = 13873 +ERROR_IPSEC_IKE_INVALID_AUTH_ALG: Final = 13874 +ERROR_IPSEC_IKE_INVALID_SIG: Final = 13875 +ERROR_IPSEC_IKE_LOAD_FAILED: Final = 13876 +ERROR_IPSEC_IKE_RPC_DELETE: Final = 13877 +ERROR_IPSEC_IKE_BENIGN_REINIT: Final = 13878 +ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: Final = 13879 +ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION: Final = 13880 +ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: Final = 13881 +ERROR_IPSEC_IKE_MM_LIMIT: Final = 13882 +ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: Final = 13883 +ERROR_IPSEC_IKE_QM_LIMIT: Final = 13884 +ERROR_IPSEC_IKE_MM_EXPIRED: Final = 13885 +ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID: Final = 13886 +ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH: Final = 13887 +ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID: Final = 13888 +ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD: Final = 13889 +ERROR_IPSEC_IKE_DOS_COOKIE_SENT: Final = 13890 +ERROR_IPSEC_IKE_SHUTTING_DOWN: Final = 13891 +ERROR_IPSEC_IKE_CGA_AUTH_FAILED: Final = 13892 +ERROR_IPSEC_IKE_PROCESS_ERR_NATOA: Final = 13893 +ERROR_IPSEC_IKE_INVALID_MM_FOR_QM: Final = 13894 +ERROR_IPSEC_IKE_QM_EXPIRED: Final = 13895 +ERROR_IPSEC_IKE_TOO_MANY_FILTERS: Final = 13896 +ERROR_IPSEC_IKE_NEG_STATUS_END: Final = 13897 +ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL: Final = 13898 +ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE: Final = 13899 +ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING: Final = 13900 +ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING: Final = 13901 +ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS: Final = 13902 +ERROR_IPSEC_IKE_RATELIMIT_DROP: Final = 13903 +ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE: Final = 13904 +ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE: Final = 13905 +ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE: Final = 13906 +ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY: Final = 13907 +ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE: Final = 13908 +ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END: Final = 13909 +ERROR_IPSEC_BAD_SPI: Final = 13910 +ERROR_IPSEC_SA_LIFETIME_EXPIRED: Final = 13911 +ERROR_IPSEC_WRONG_SA: Final = 13912 +ERROR_IPSEC_REPLAY_CHECK_FAILED: Final = 13913 +ERROR_IPSEC_INVALID_PACKET: Final = 13914 +ERROR_IPSEC_INTEGRITY_CHECK_FAILED: Final = 13915 +ERROR_IPSEC_CLEAR_TEXT_DROP: Final = 13916 +ERROR_IPSEC_AUTH_FIREWALL_DROP: Final = 13917 +ERROR_IPSEC_THROTTLE_DROP: Final = 13918 +ERROR_IPSEC_DOSP_BLOCK: Final = 13925 +ERROR_IPSEC_DOSP_RECEIVED_MULTICAST: Final = 13926 +ERROR_IPSEC_DOSP_INVALID_PACKET: Final = 13927 +ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED: Final = 13928 +ERROR_IPSEC_DOSP_MAX_ENTRIES: Final = 13929 +ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: Final = 13930 +ERROR_IPSEC_DOSP_NOT_INSTALLED: Final = 13931 +ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: Final = 13932 +ERROR_SXS_SECTION_NOT_FOUND: Final = 14000 +ERROR_SXS_CANT_GEN_ACTCTX: Final = 14001 +ERROR_SXS_INVALID_ACTCTXDATA_FORMAT: Final = 14002 +ERROR_SXS_ASSEMBLY_NOT_FOUND: Final = 14003 +ERROR_SXS_MANIFEST_FORMAT_ERROR: Final = 14004 +ERROR_SXS_MANIFEST_PARSE_ERROR: Final = 14005 +ERROR_SXS_ACTIVATION_CONTEXT_DISABLED: Final = 14006 +ERROR_SXS_KEY_NOT_FOUND: Final = 14007 +ERROR_SXS_VERSION_CONFLICT: Final = 14008 +ERROR_SXS_WRONG_SECTION_TYPE: Final = 14009 +ERROR_SXS_THREAD_QUERIES_DISABLED: Final = 14010 +ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET: Final = 14011 +ERROR_SXS_UNKNOWN_ENCODING_GROUP: Final = 14012 +ERROR_SXS_UNKNOWN_ENCODING: Final = 14013 +ERROR_SXS_INVALID_XML_NAMESPACE_URI: Final = 14014 +ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED: Final = 14015 +ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED: Final = 14016 +ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE: Final = 14017 +ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE: Final = 14018 +ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE: Final = 14019 +ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT: Final = 14020 +ERROR_SXS_DUPLICATE_DLL_NAME: Final = 14021 +ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME: Final = 14022 +ERROR_SXS_DUPLICATE_CLSID: Final = 14023 +ERROR_SXS_DUPLICATE_IID: Final = 14024 +ERROR_SXS_DUPLICATE_TLBID: Final = 14025 +ERROR_SXS_DUPLICATE_PROGID: Final = 14026 +ERROR_SXS_DUPLICATE_ASSEMBLY_NAME: Final = 14027 +ERROR_SXS_FILE_HASH_MISMATCH: Final = 14028 +ERROR_SXS_POLICY_PARSE_ERROR: Final = 14029 +ERROR_SXS_XML_E_MISSINGQUOTE: Final = 14030 +ERROR_SXS_XML_E_COMMENTSYNTAX: Final = 14031 +ERROR_SXS_XML_E_BADSTARTNAMECHAR: Final = 14032 +ERROR_SXS_XML_E_BADNAMECHAR: Final = 14033 +ERROR_SXS_XML_E_BADCHARINSTRING: Final = 14034 +ERROR_SXS_XML_E_XMLDECLSYNTAX: Final = 14035 +ERROR_SXS_XML_E_BADCHARDATA: Final = 14036 +ERROR_SXS_XML_E_MISSINGWHITESPACE: Final = 14037 +ERROR_SXS_XML_E_EXPECTINGTAGEND: Final = 14038 +ERROR_SXS_XML_E_MISSINGSEMICOLON: Final = 14039 +ERROR_SXS_XML_E_UNBALANCEDPAREN: Final = 14040 +ERROR_SXS_XML_E_INTERNALERROR: Final = 14041 +ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE: Final = 14042 +ERROR_SXS_XML_E_INCOMPLETE_ENCODING: Final = 14043 +ERROR_SXS_XML_E_MISSING_PAREN: Final = 14044 +ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE: Final = 14045 +ERROR_SXS_XML_E_MULTIPLE_COLONS: Final = 14046 +ERROR_SXS_XML_E_INVALID_DECIMAL: Final = 14047 +ERROR_SXS_XML_E_INVALID_HEXIDECIMAL: Final = 14048 +ERROR_SXS_XML_E_INVALID_UNICODE: Final = 14049 +ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK: Final = 14050 +ERROR_SXS_XML_E_UNEXPECTEDENDTAG: Final = 14051 +ERROR_SXS_XML_E_UNCLOSEDTAG: Final = 14052 +ERROR_SXS_XML_E_DUPLICATEATTRIBUTE: Final = 14053 +ERROR_SXS_XML_E_MULTIPLEROOTS: Final = 14054 +ERROR_SXS_XML_E_INVALIDATROOTLEVEL: Final = 14055 +ERROR_SXS_XML_E_BADXMLDECL: Final = 14056 +ERROR_SXS_XML_E_MISSINGROOT: Final = 14057 +ERROR_SXS_XML_E_UNEXPECTEDEOF: Final = 14058 +ERROR_SXS_XML_E_BADPEREFINSUBSET: Final = 14059 +ERROR_SXS_XML_E_UNCLOSEDSTARTTAG: Final = 14060 +ERROR_SXS_XML_E_UNCLOSEDENDTAG: Final = 14061 +ERROR_SXS_XML_E_UNCLOSEDSTRING: Final = 14062 +ERROR_SXS_XML_E_UNCLOSEDCOMMENT: Final = 14063 +ERROR_SXS_XML_E_UNCLOSEDDECL: Final = 14064 +ERROR_SXS_XML_E_UNCLOSEDCDATA: Final = 14065 +ERROR_SXS_XML_E_RESERVEDNAMESPACE: Final = 14066 +ERROR_SXS_XML_E_INVALIDENCODING: Final = 14067 +ERROR_SXS_XML_E_INVALIDSWITCH: Final = 14068 +ERROR_SXS_XML_E_BADXMLCASE: Final = 14069 +ERROR_SXS_XML_E_INVALID_STANDALONE: Final = 14070 +ERROR_SXS_XML_E_UNEXPECTED_STANDALONE: Final = 14071 +ERROR_SXS_XML_E_INVALID_VERSION: Final = 14072 +ERROR_SXS_XML_E_MISSINGEQUALS: Final = 14073 +ERROR_SXS_PROTECTION_RECOVERY_FAILED: Final = 14074 +ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT: Final = 14075 +ERROR_SXS_PROTECTION_CATALOG_NOT_VALID: Final = 14076 +ERROR_SXS_UNTRANSLATABLE_HRESULT: Final = 14077 +ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING: Final = 14078 +ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE: Final = 14079 +ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME: Final = 14080 +ERROR_SXS_ASSEMBLY_MISSING: Final = 14081 +ERROR_SXS_CORRUPT_ACTIVATION_STACK: Final = 14082 +ERROR_SXS_CORRUPTION: Final = 14083 +ERROR_SXS_EARLY_DEACTIVATION: Final = 14084 +ERROR_SXS_INVALID_DEACTIVATION: Final = 14085 +ERROR_SXS_MULTIPLE_DEACTIVATION: Final = 14086 +ERROR_SXS_PROCESS_TERMINATION_REQUESTED: Final = 14087 +ERROR_SXS_RELEASE_ACTIVATION_CONTEXT: Final = 14088 +ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: Final = 14089 +ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: Final = 14090 +ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: Final = 14091 +ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: Final = 14092 +ERROR_SXS_IDENTITY_PARSE_ERROR: Final = 14093 +ERROR_MALFORMED_SUBSTITUTION_STRING: Final = 14094 +ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN: Final = 14095 +ERROR_UNMAPPED_SUBSTITUTION_STRING: Final = 14096 +ERROR_SXS_ASSEMBLY_NOT_LOCKED: Final = 14097 +ERROR_SXS_COMPONENT_STORE_CORRUPT: Final = 14098 +ERROR_ADVANCED_INSTALLER_FAILED: Final = 14099 +ERROR_XML_ENCODING_MISMATCH: Final = 14100 +ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: Final = 14101 +ERROR_SXS_IDENTITIES_DIFFERENT: Final = 14102 +ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: Final = 14103 +ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY: Final = 14104 +ERROR_SXS_MANIFEST_TOO_BIG: Final = 14105 +ERROR_SXS_SETTING_NOT_REGISTERED: Final = 14106 +ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE: Final = 14107 +ERROR_SMI_PRIMITIVE_INSTALLER_FAILED: Final = 14108 +ERROR_GENERIC_COMMAND_FAILED: Final = 14109 +ERROR_SXS_FILE_HASH_MISSING: Final = 14110 +ERROR_SXS_DUPLICATE_ACTIVATABLE_CLASS: Final = 14111 +ERROR_EVT_INVALID_CHANNEL_PATH: Final = 15000 +ERROR_EVT_INVALID_QUERY: Final = 15001 +ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND: Final = 15002 +ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND: Final = 15003 +ERROR_EVT_INVALID_PUBLISHER_NAME: Final = 15004 +ERROR_EVT_INVALID_EVENT_DATA: Final = 15005 +ERROR_EVT_CHANNEL_NOT_FOUND: Final = 15007 +ERROR_EVT_MALFORMED_XML_TEXT: Final = 15008 +ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL: Final = 15009 +ERROR_EVT_CONFIGURATION_ERROR: Final = 15010 +ERROR_EVT_QUERY_RESULT_STALE: Final = 15011 +ERROR_EVT_QUERY_RESULT_INVALID_POSITION: Final = 15012 +ERROR_EVT_NON_VALIDATING_MSXML: Final = 15013 +ERROR_EVT_FILTER_ALREADYSCOPED: Final = 15014 +ERROR_EVT_FILTER_NOTELTSET: Final = 15015 +ERROR_EVT_FILTER_INVARG: Final = 15016 +ERROR_EVT_FILTER_INVTEST: Final = 15017 +ERROR_EVT_FILTER_INVTYPE: Final = 15018 +ERROR_EVT_FILTER_PARSEERR: Final = 15019 +ERROR_EVT_FILTER_UNSUPPORTEDOP: Final = 15020 +ERROR_EVT_FILTER_UNEXPECTEDTOKEN: Final = 15021 +ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL: Final = 15022 +ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE: Final = 15023 +ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE: Final = 15024 +ERROR_EVT_CHANNEL_CANNOT_ACTIVATE: Final = 15025 +ERROR_EVT_FILTER_TOO_COMPLEX: Final = 15026 +ERROR_EVT_MESSAGE_NOT_FOUND: Final = 15027 +ERROR_EVT_MESSAGE_ID_NOT_FOUND: Final = 15028 +ERROR_EVT_UNRESOLVED_VALUE_INSERT: Final = 15029 +ERROR_EVT_UNRESOLVED_PARAMETER_INSERT: Final = 15030 +ERROR_EVT_MAX_INSERTS_REACHED: Final = 15031 +ERROR_EVT_EVENT_DEFINITION_NOT_FOUND: Final = 15032 +ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: Final = 15033 +ERROR_EVT_VERSION_TOO_OLD: Final = 15034 +ERROR_EVT_VERSION_TOO_NEW: Final = 15035 +ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY: Final = 15036 +ERROR_EVT_PUBLISHER_DISABLED: Final = 15037 +ERROR_EVT_FILTER_OUT_OF_RANGE: Final = 15038 +ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE: Final = 15080 +ERROR_EC_LOG_DISABLED: Final = 15081 +ERROR_EC_CIRCULAR_FORWARDING: Final = 15082 +ERROR_EC_CREDSTORE_FULL: Final = 15083 +ERROR_EC_CRED_NOT_FOUND: Final = 15084 +ERROR_EC_NO_ACTIVE_CHANNEL: Final = 15085 +ERROR_MUI_FILE_NOT_FOUND: Final = 15100 +ERROR_MUI_INVALID_FILE: Final = 15101 +ERROR_MUI_INVALID_RC_CONFIG: Final = 15102 +ERROR_MUI_INVALID_LOCALE_NAME: Final = 15103 +ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME: Final = 15104 +ERROR_MUI_FILE_NOT_LOADED: Final = 15105 +ERROR_RESOURCE_ENUM_USER_STOP: Final = 15106 +ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED: Final = 15107 +ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME: Final = 15108 +ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE: Final = 15110 +ERROR_MRM_INVALID_PRICONFIG: Final = 15111 +ERROR_MRM_INVALID_FILE_TYPE: Final = 15112 +ERROR_MRM_UNKNOWN_QUALIFIER: Final = 15113 +ERROR_MRM_INVALID_QUALIFIER_VALUE: Final = 15114 +ERROR_MRM_NO_CANDIDATE: Final = 15115 +ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE: Final = 15116 +ERROR_MRM_RESOURCE_TYPE_MISMATCH: Final = 15117 +ERROR_MRM_DUPLICATE_MAP_NAME: Final = 15118 +ERROR_MRM_DUPLICATE_ENTRY: Final = 15119 +ERROR_MRM_INVALID_RESOURCE_IDENTIFIER: Final = 15120 +ERROR_MRM_FILEPATH_TOO_LONG: Final = 15121 +ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE: Final = 15122 +ERROR_MRM_INVALID_PRI_FILE: Final = 15126 +ERROR_MRM_NAMED_RESOURCE_NOT_FOUND: Final = 15127 +ERROR_MRM_MAP_NOT_FOUND: Final = 15135 +ERROR_MRM_UNSUPPORTED_PROFILE_TYPE: Final = 15136 +ERROR_MRM_INVALID_QUALIFIER_OPERATOR: Final = 15137 +ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE: Final = 15138 +ERROR_MRM_AUTOMERGE_ENABLED: Final = 15139 +ERROR_MRM_TOO_MANY_RESOURCES: Final = 15140 +ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_MERGE: Final = 15141 +ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_LOAD_UNLOAD_PRI_FILE: Final = 15142 +ERROR_MRM_NO_CURRENT_VIEW_ON_THREAD: Final = 15143 +ERROR_DIFFERENT_PROFILE_RESOURCE_MANAGER_EXIST: Final = 15144 +ERROR_OPERATION_NOT_ALLOWED_FROM_SYSTEM_COMPONENT: Final = 15145 +ERROR_MRM_DIRECT_REF_TO_NON_DEFAULT_RESOURCE: Final = 15146 +ERROR_MRM_GENERATION_COUNT_MISMATCH: Final = 15147 +ERROR_PRI_MERGE_VERSION_MISMATCH: Final = 15148 +ERROR_PRI_MERGE_MISSING_SCHEMA: Final = 15149 +ERROR_PRI_MERGE_LOAD_FILE_FAILED: Final = 15150 +ERROR_PRI_MERGE_ADD_FILE_FAILED: Final = 15151 +ERROR_PRI_MERGE_WRITE_FILE_FAILED: Final = 15152 +ERROR_PRI_MERGE_MULTIPLE_PACKAGE_FAMILIES_NOT_ALLOWED: Final = 15153 +ERROR_PRI_MERGE_MULTIPLE_MAIN_PACKAGES_NOT_ALLOWED: Final = 15154 +ERROR_PRI_MERGE_BUNDLE_PACKAGES_NOT_ALLOWED: Final = 15155 +ERROR_PRI_MERGE_MAIN_PACKAGE_REQUIRED: Final = 15156 +ERROR_PRI_MERGE_RESOURCE_PACKAGE_REQUIRED: Final = 15157 +ERROR_PRI_MERGE_INVALID_FILE_NAME: Final = 15158 +ERROR_MRM_PACKAGE_NOT_FOUND: Final = 15159 +ERROR_MRM_MISSING_DEFAULT_LANGUAGE: Final = 15160 +ERROR_MRM_SCOPE_ITEM_CONFLICT: Final = 15161 +ERROR_MCA_INVALID_CAPABILITIES_STRING: Final = 15200 +ERROR_MCA_INVALID_VCP_VERSION: Final = 15201 +ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: Final = 15202 +ERROR_MCA_MCCS_VERSION_MISMATCH: Final = 15203 +ERROR_MCA_UNSUPPORTED_MCCS_VERSION: Final = 15204 +ERROR_MCA_INTERNAL_ERROR: Final = 15205 +ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: Final = 15206 +ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE: Final = 15207 +ERROR_AMBIGUOUS_SYSTEM_DEVICE: Final = 15250 +ERROR_SYSTEM_DEVICE_NOT_FOUND: Final = 15299 +ERROR_HASH_NOT_SUPPORTED: Final = 15300 +ERROR_HASH_NOT_PRESENT: Final = 15301 +ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED: Final = 15321 +ERROR_GPIO_CLIENT_INFORMATION_INVALID: Final = 15322 +ERROR_GPIO_VERSION_NOT_SUPPORTED: Final = 15323 +ERROR_GPIO_INVALID_REGISTRATION_PACKET: Final = 15324 +ERROR_GPIO_OPERATION_DENIED: Final = 15325 +ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE: Final = 15326 +ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED: Final = 15327 +ERROR_CANNOT_SWITCH_RUNLEVEL: Final = 15400 +ERROR_INVALID_RUNLEVEL_SETTING: Final = 15401 +ERROR_RUNLEVEL_SWITCH_TIMEOUT: Final = 15402 +ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT: Final = 15403 +ERROR_RUNLEVEL_SWITCH_IN_PROGRESS: Final = 15404 +ERROR_SERVICES_FAILED_AUTOSTART: Final = 15405 +ERROR_COM_TASK_STOP_PENDING: Final = 15501 +ERROR_INSTALL_OPEN_PACKAGE_FAILED: Final = 15600 +ERROR_INSTALL_PACKAGE_NOT_FOUND: Final = 15601 +ERROR_INSTALL_INVALID_PACKAGE: Final = 15602 +ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED: Final = 15603 +ERROR_INSTALL_OUT_OF_DISK_SPACE: Final = 15604 +ERROR_INSTALL_NETWORK_FAILURE: Final = 15605 +ERROR_INSTALL_REGISTRATION_FAILURE: Final = 15606 +ERROR_INSTALL_DEREGISTRATION_FAILURE: Final = 15607 +ERROR_INSTALL_CANCEL: Final = 15608 +ERROR_INSTALL_FAILED: Final = 15609 +ERROR_REMOVE_FAILED: Final = 15610 +ERROR_PACKAGE_ALREADY_EXISTS: Final = 15611 +ERROR_NEEDS_REMEDIATION: Final = 15612 +ERROR_INSTALL_PREREQUISITE_FAILED: Final = 15613 +ERROR_PACKAGE_REPOSITORY_CORRUPTED: Final = 15614 +ERROR_INSTALL_POLICY_FAILURE: Final = 15615 +ERROR_PACKAGE_UPDATING: Final = 15616 +ERROR_DEPLOYMENT_BLOCKED_BY_POLICY: Final = 15617 +ERROR_PACKAGES_IN_USE: Final = 15618 +ERROR_RECOVERY_FILE_CORRUPT: Final = 15619 +ERROR_INVALID_STAGED_SIGNATURE: Final = 15620 +ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED: Final = 15621 +ERROR_INSTALL_PACKAGE_DOWNGRADE: Final = 15622 +ERROR_SYSTEM_NEEDS_REMEDIATION: Final = 15623 +ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN: Final = 15624 +ERROR_RESILIENCY_FILE_CORRUPT: Final = 15625 +ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING: Final = 15626 +ERROR_PACKAGE_MOVE_FAILED: Final = 15627 +ERROR_INSTALL_VOLUME_NOT_EMPTY: Final = 15628 +ERROR_INSTALL_VOLUME_OFFLINE: Final = 15629 +ERROR_INSTALL_VOLUME_CORRUPT: Final = 15630 +ERROR_NEEDS_REGISTRATION: Final = 15631 +ERROR_INSTALL_WRONG_PROCESSOR_ARCHITECTURE: Final = 15632 +ERROR_DEV_SIDELOAD_LIMIT_EXCEEDED: Final = 15633 +ERROR_INSTALL_OPTIONAL_PACKAGE_REQUIRES_MAIN_PACKAGE: Final = 15634 +ERROR_PACKAGE_NOT_SUPPORTED_ON_FILESYSTEM: Final = 15635 +ERROR_PACKAGE_MOVE_BLOCKED_BY_STREAMING: Final = 15636 +ERROR_INSTALL_OPTIONAL_PACKAGE_APPLICATIONID_NOT_UNIQUE: Final = 15637 +ERROR_PACKAGE_STAGING_ONHOLD: Final = 15638 +ERROR_INSTALL_INVALID_RELATED_SET_UPDATE: Final = 15639 +ERROR_INSTALL_OPTIONAL_PACKAGE_REQUIRES_MAIN_PACKAGE_FULLTRUST_CAPABILITY: Final = 15640 +ERROR_DEPLOYMENT_BLOCKED_BY_USER_LOG_OFF: Final = 15641 +ERROR_PROVISION_OPTIONAL_PACKAGE_REQUIRES_MAIN_PACKAGE_PROVISIONED: Final = 15642 +ERROR_PACKAGES_REPUTATION_CHECK_FAILED: Final = 15643 +ERROR_PACKAGES_REPUTATION_CHECK_TIMEDOUT: Final = 15644 +ERROR_DEPLOYMENT_OPTION_NOT_SUPPORTED: Final = 15645 +ERROR_APPINSTALLER_ACTIVATION_BLOCKED: Final = 15646 +ERROR_REGISTRATION_FROM_REMOTE_DRIVE_NOT_SUPPORTED: Final = 15647 +ERROR_APPX_RAW_DATA_WRITE_FAILED: Final = 15648 +ERROR_DEPLOYMENT_BLOCKED_BY_VOLUME_POLICY_PACKAGE: Final = 15649 +ERROR_DEPLOYMENT_BLOCKED_BY_VOLUME_POLICY_MACHINE: Final = 15650 +ERROR_DEPLOYMENT_BLOCKED_BY_PROFILE_POLICY: Final = 15651 +ERROR_DEPLOYMENT_FAILED_CONFLICTING_MUTABLE_PACKAGE_DIRECTORY: Final = 15652 +ERROR_SINGLETON_RESOURCE_INSTALLED_IN_ACTIVE_USER: Final = 15653 +ERROR_DIFFERENT_VERSION_OF_PACKAGED_SERVICE_INSTALLED: Final = 15654 +ERROR_SERVICE_EXISTS_AS_NON_PACKAGED_SERVICE: Final = 15655 +ERROR_PACKAGED_SERVICE_REQUIRES_ADMIN_PRIVILEGES: Final = 15656 +ERROR_REDIRECTION_TO_DEFAULT_ACCOUNT_NOT_ALLOWED: Final = 15657 +ERROR_PACKAGE_LACKS_CAPABILITY_TO_DEPLOY_ON_HOST: Final = 15658 +ERROR_UNSIGNED_PACKAGE_INVALID_CONTENT: Final = 15659 +ERROR_UNSIGNED_PACKAGE_INVALID_PUBLISHER_NAMESPACE: Final = 15660 +ERROR_SIGNED_PACKAGE_INVALID_PUBLISHER_NAMESPACE: Final = 15661 +ERROR_PACKAGE_EXTERNAL_LOCATION_NOT_ALLOWED: Final = 15662 +ERROR_INSTALL_FULLTRUST_HOSTRUNTIME_REQUIRES_MAIN_PACKAGE_FULLTRUST_CAPABILITY: Final = 15663 +ERROR_PACKAGE_LACKS_CAPABILITY_FOR_MANDATORY_STARTUPTASKS: Final = 15664 +ERROR_INSTALL_RESOLVE_HOSTRUNTIME_DEPENDENCY_FAILED: Final = 15665 +ERROR_MACHINE_SCOPE_NOT_ALLOWED: Final = 15666 +ERROR_CLASSIC_COMPAT_MODE_NOT_ALLOWED: Final = 15667 +ERROR_STAGEFROMUPDATEAGENT_PACKAGE_NOT_APPLICABLE: Final = 15668 +ERROR_PACKAGE_NOT_REGISTERED_FOR_USER: Final = 15669 +ERROR_PACKAGE_NAME_MISMATCH: Final = 15670 +ERROR_APPINSTALLER_URI_IN_USE: Final = 15671 +ERROR_APPINSTALLER_IS_MANAGED_BY_SYSTEM: Final = 15672 +APPMODEL_ERROR_NO_PACKAGE: Final = 15700 +APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT: Final = 15701 +APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT: Final = 15702 +APPMODEL_ERROR_NO_APPLICATION: Final = 15703 +APPMODEL_ERROR_DYNAMIC_PROPERTY_READ_FAILED: Final = 15704 +APPMODEL_ERROR_DYNAMIC_PROPERTY_INVALID: Final = 15705 +APPMODEL_ERROR_PACKAGE_NOT_AVAILABLE: Final = 15706 +APPMODEL_ERROR_NO_MUTABLE_DIRECTORY: Final = 15707 +ERROR_STATE_LOAD_STORE_FAILED: Final = 15800 +ERROR_STATE_GET_VERSION_FAILED: Final = 15801 +ERROR_STATE_SET_VERSION_FAILED: Final = 15802 +ERROR_STATE_STRUCTURED_RESET_FAILED: Final = 15803 +ERROR_STATE_OPEN_CONTAINER_FAILED: Final = 15804 +ERROR_STATE_CREATE_CONTAINER_FAILED: Final = 15805 +ERROR_STATE_DELETE_CONTAINER_FAILED: Final = 15806 +ERROR_STATE_READ_SETTING_FAILED: Final = 15807 +ERROR_STATE_WRITE_SETTING_FAILED: Final = 15808 +ERROR_STATE_DELETE_SETTING_FAILED: Final = 15809 +ERROR_STATE_QUERY_SETTING_FAILED: Final = 15810 +ERROR_STATE_READ_COMPOSITE_SETTING_FAILED: Final = 15811 +ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED: Final = 15812 +ERROR_STATE_ENUMERATE_CONTAINER_FAILED: Final = 15813 +ERROR_STATE_ENUMERATE_SETTINGS_FAILED: Final = 15814 +ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: Final = 15815 +ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: Final = 15816 +ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED: Final = 15817 +ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED: Final = 15818 +ERROR_API_UNAVAILABLE: Final = 15841 +STORE_ERROR_UNLICENSED: Final = 15861 +STORE_ERROR_UNLICENSED_USER: Final = 15862 +STORE_ERROR_PENDING_COM_TRANSACTION: Final = 15863 +STORE_ERROR_LICENSE_REVOKED: Final = 15864 +SEVERITY_SUCCESS: Final = 0 +SEVERITY_ERROR: Final = 1 + +def SUCCEEDED(hr): ... +def FAILED(hr): ... +def HRESULT_CODE(hr): ... +def SCODE_CODE(sc): ... +def HRESULT_FACILITY(hr): ... +def SCODE_FACILITY(sc): ... +def HRESULT_SEVERITY(hr): ... +def SCODE_SEVERITY(sc): ... + +FACILITY_NT_BIT: Final = 0x10000000 + +def HRESULT_FROM_WIN32(x): ... +def HRESULT_FROM_NT(x): ... +def GetScode(hr): ... +def ResultFromScode(sc): ... + +NOERROR: Final = 0 +E_UNEXPECTED: Final = -2147418113 +E_NOTIMPL: Final = -2147467263 +E_OUTOFMEMORY: Final = -2147024882 +E_INVALIDARG: Final = -2147024809 +E_NOINTERFACE: Final = -2147467262 +E_POINTER: Final = -2147467261 +E_HANDLE: Final = -2147024890 +E_ABORT: Final = -2147467260 +E_FAIL: Final = -2147467259 +E_ACCESSDENIED: Final = -2147024891 +E_PENDING: Final = -2147483638 +E_BOUNDS: Final = -2147483637 +E_CHANGED_STATE: Final = -2147483636 +E_ILLEGAL_STATE_CHANGE: Final = -2147483635 +E_ILLEGAL_METHOD_CALL: Final = -2147483634 +RO_E_METADATA_NAME_NOT_FOUND: Final = -2147483633 +RO_E_METADATA_NAME_IS_NAMESPACE: Final = -2147483632 +RO_E_METADATA_INVALID_TYPE_FORMAT: Final = -2147483631 +RO_E_INVALID_METADATA_FILE: Final = -2147483630 +RO_E_CLOSED: Final = -2147483629 +RO_E_EXCLUSIVE_WRITE: Final = -2147483628 +RO_E_CHANGE_NOTIFICATION_IN_PROGRESS: Final = -2147483627 +RO_E_ERROR_STRING_NOT_FOUND: Final = -2147483626 +E_STRING_NOT_NULL_TERMINATED: Final = -2147483625 +E_ILLEGAL_DELEGATE_ASSIGNMENT: Final = -2147483624 +E_ASYNC_OPERATION_NOT_STARTED: Final = -2147483623 +E_APPLICATION_EXITING: Final = -2147483622 +E_APPLICATION_VIEW_EXITING: Final = -2147483621 +RO_E_MUST_BE_AGILE: Final = -2147483620 +RO_E_UNSUPPORTED_FROM_MTA: Final = -2147483619 +RO_E_COMMITTED: Final = -2147483618 +RO_E_BLOCKED_CROSS_ASTA_CALL: Final = -2147483617 +RO_E_CANNOT_ACTIVATE_FULL_TRUST_SERVER: Final = -2147483616 +RO_E_CANNOT_ACTIVATE_UNIVERSAL_APPLICATION_SERVER: Final = -2147483615 +CO_E_INIT_TLS: Final = -2147467258 +CO_E_INIT_SHARED_ALLOCATOR: Final = -2147467257 +CO_E_INIT_MEMORY_ALLOCATOR: Final = -2147467256 +CO_E_INIT_CLASS_CACHE: Final = -2147467255 +CO_E_INIT_RPC_CHANNEL: Final = -2147467254 +CO_E_INIT_TLS_SET_CHANNEL_CONTROL: Final = -2147467253 +CO_E_INIT_TLS_CHANNEL_CONTROL: Final = -2147467252 +CO_E_INIT_UNACCEPTED_USER_ALLOCATOR: Final = -2147467251 +CO_E_INIT_SCM_MUTEX_EXISTS: Final = -2147467250 +CO_E_INIT_SCM_FILE_MAPPING_EXISTS: Final = -2147467249 +CO_E_INIT_SCM_MAP_VIEW_OF_FILE: Final = -2147467248 +CO_E_INIT_SCM_EXEC_FAILURE: Final = -2147467247 +CO_E_INIT_ONLY_SINGLE_THREADED: Final = -2147467246 +CO_E_CANT_REMOTE: Final = -2147467245 +CO_E_BAD_SERVER_NAME: Final = -2147467244 +CO_E_WRONG_SERVER_IDENTITY: Final = -2147467243 +CO_E_OLE1DDE_DISABLED: Final = -2147467242 +CO_E_RUNAS_SYNTAX: Final = -2147467241 +CO_E_CREATEPROCESS_FAILURE: Final = -2147467240 +CO_E_RUNAS_CREATEPROCESS_FAILURE: Final = -2147467239 +CO_E_RUNAS_LOGON_FAILURE: Final = -2147467238 +CO_E_LAUNCH_PERMSSION_DENIED: Final = -2147467237 +CO_E_START_SERVICE_FAILURE: Final = -2147467236 +CO_E_REMOTE_COMMUNICATION_FAILURE: Final = -2147467235 +CO_E_SERVER_START_TIMEOUT: Final = -2147467234 +CO_E_CLSREG_INCONSISTENT: Final = -2147467233 +CO_E_IIDREG_INCONSISTENT: Final = -2147467232 +CO_E_NOT_SUPPORTED: Final = -2147467231 +CO_E_RELOAD_DLL: Final = -2147467230 +CO_E_MSI_ERROR: Final = -2147467229 +CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT: Final = -2147467228 +CO_E_SERVER_PAUSED: Final = -2147467227 +CO_E_SERVER_NOT_PAUSED: Final = -2147467226 +CO_E_CLASS_DISABLED: Final = -2147467225 +CO_E_CLRNOTAVAILABLE: Final = -2147467224 +CO_E_ASYNC_WORK_REJECTED: Final = -2147467223 +CO_E_SERVER_INIT_TIMEOUT: Final = -2147467222 +CO_E_NO_SECCTX_IN_ACTIVATE: Final = -2147467221 +CO_E_TRACKER_CONFIG: Final = -2147467216 +CO_E_THREADPOOL_CONFIG: Final = -2147467215 +CO_E_SXS_CONFIG: Final = -2147467214 +CO_E_MALFORMED_SPN: Final = -2147467213 +CO_E_UNREVOKED_REGISTRATION_ON_APARTMENT_SHUTDOWN: Final = -2147467212 +CO_E_PREMATURE_STUB_RUNDOWN: Final = -2147467211 +S_OK: Final = 0 +S_FALSE: Final = 1 +OLE_E_FIRST: Final = -2147221504 +OLE_E_LAST: Final = -2147221249 +OLE_S_FIRST: Final = 0x00040000 +OLE_S_LAST: Final = 0x000400FF +OLE_E_OLEVERB: Final = -2147221504 +OLE_E_ADVF: Final = -2147221503 +OLE_E_ENUM_NOMORE: Final = -2147221502 +OLE_E_ADVISENOTSUPPORTED: Final = -2147221501 +OLE_E_NOCONNECTION: Final = -2147221500 +OLE_E_NOTRUNNING: Final = -2147221499 +OLE_E_NOCACHE: Final = -2147221498 +OLE_E_BLANK: Final = -2147221497 +OLE_E_CLASSDIFF: Final = -2147221496 +OLE_E_CANT_GETMONIKER: Final = -2147221495 +OLE_E_CANT_BINDTOSOURCE: Final = -2147221494 +OLE_E_STATIC: Final = -2147221493 +OLE_E_PROMPTSAVECANCELLED: Final = -2147221492 +OLE_E_INVALIDRECT: Final = -2147221491 +OLE_E_WRONGCOMPOBJ: Final = -2147221490 +OLE_E_INVALIDHWND: Final = -2147221489 +OLE_E_NOT_INPLACEACTIVE: Final = -2147221488 +OLE_E_CANTCONVERT: Final = -2147221487 +OLE_E_NOSTORAGE: Final = -2147221486 +DV_E_FORMATETC: Final = -2147221404 +DV_E_DVTARGETDEVICE: Final = -2147221403 +DV_E_STGMEDIUM: Final = -2147221402 +DV_E_STATDATA: Final = -2147221401 +DV_E_LINDEX: Final = -2147221400 +DV_E_TYMED: Final = -2147221399 +DV_E_CLIPFORMAT: Final = -2147221398 +DV_E_DVASPECT: Final = -2147221397 +DV_E_DVTARGETDEVICE_SIZE: Final = -2147221396 +DV_E_NOIVIEWOBJECT: Final = -2147221395 +DRAGDROP_E_FIRST: Final = -2147221248 +DRAGDROP_E_LAST: Final = -2147221233 +DRAGDROP_S_FIRST: Final = 0x00040100 +DRAGDROP_S_LAST: Final = 0x0004010F +DRAGDROP_E_NOTREGISTERED: Final = -2147221248 +DRAGDROP_E_ALREADYREGISTERED: Final = -2147221247 +DRAGDROP_E_INVALIDHWND: Final = -2147221246 +DRAGDROP_E_CONCURRENT_DRAG_ATTEMPTED: Final = -2147221245 +CLASSFACTORY_E_FIRST: Final = -2147221232 +CLASSFACTORY_E_LAST: Final = -2147221217 +CLASSFACTORY_S_FIRST: Final = 0x00040110 +CLASSFACTORY_S_LAST: Final = 0x0004011F +CLASS_E_NOAGGREGATION: Final = -2147221232 +CLASS_E_CLASSNOTAVAILABLE: Final = -2147221231 +CLASS_E_NOTLICENSED: Final = -2147221230 +MARSHAL_E_FIRST: Final = -2147221216 +MARSHAL_E_LAST: Final = -2147221201 +MARSHAL_S_FIRST: Final = 0x00040120 +MARSHAL_S_LAST: Final = 0x0004012F +DATA_E_FIRST: Final = -2147221200 +DATA_E_LAST: Final = -2147221185 +DATA_S_FIRST: Final = 0x00040130 +DATA_S_LAST: Final = 0x0004013F +VIEW_E_FIRST: Final = -2147221184 +VIEW_E_LAST: Final = -2147221169 +VIEW_S_FIRST: Final = 0x00040140 +VIEW_S_LAST: Final = 0x0004014F +VIEW_E_DRAW: Final = -2147221184 +REGDB_E_FIRST: Final = -2147221168 +REGDB_E_LAST: Final = -2147221153 +REGDB_S_FIRST: Final = 0x00040150 +REGDB_S_LAST: Final = 0x0004015F +REGDB_E_READREGDB: Final = -2147221168 +REGDB_E_WRITEREGDB: Final = -2147221167 +REGDB_E_KEYMISSING: Final = -2147221166 +REGDB_E_INVALIDVALUE: Final = -2147221165 +REGDB_E_CLASSNOTREG: Final = -2147221164 +REGDB_E_IIDNOTREG: Final = -2147221163 +REGDB_E_BADTHREADINGMODEL: Final = -2147221162 +REGDB_E_PACKAGEPOLICYVIOLATION: Final = -2147221161 +CAT_E_FIRST: Final = -2147221152 +CAT_E_LAST: Final = -2147221151 +CAT_E_CATIDNOEXIST: Final = -2147221152 +CAT_E_NODESCRIPTION: Final = -2147221151 +CS_E_FIRST: Final = -2147221148 +CS_E_LAST: Final = -2147221137 +CS_E_PACKAGE_NOTFOUND: Final = -2147221148 +CS_E_NOT_DELETABLE: Final = -2147221147 +CS_E_CLASS_NOTFOUND: Final = -2147221146 +CS_E_INVALID_VERSION: Final = -2147221145 +CS_E_NO_CLASSSTORE: Final = -2147221144 +CS_E_OBJECT_NOTFOUND: Final = -2147221143 +CS_E_OBJECT_ALREADY_EXISTS: Final = -2147221142 +CS_E_INVALID_PATH: Final = -2147221141 +CS_E_NETWORK_ERROR: Final = -2147221140 +CS_E_ADMIN_LIMIT_EXCEEDED: Final = -2147221139 +CS_E_SCHEMA_MISMATCH: Final = -2147221138 +CS_E_INTERNAL_ERROR: Final = -2147221137 +CACHE_E_FIRST: Final = -2147221136 +CACHE_E_LAST: Final = -2147221121 +CACHE_S_FIRST: Final = 0x00040170 +CACHE_S_LAST: Final = 0x0004017F +CACHE_E_NOCACHE_UPDATED: Final = -2147221136 +OLEOBJ_E_FIRST: Final = -2147221120 +OLEOBJ_E_LAST: Final = -2147221105 +OLEOBJ_S_FIRST: Final = 0x00040180 +OLEOBJ_S_LAST: Final = 0x0004018F +OLEOBJ_E_NOVERBS: Final = -2147221120 +OLEOBJ_E_INVALIDVERB: Final = -2147221119 +CLIENTSITE_E_FIRST: Final = -2147221104 +CLIENTSITE_E_LAST: Final = -2147221089 +CLIENTSITE_S_FIRST: Final = 0x00040190 +CLIENTSITE_S_LAST: Final = 0x0004019F +INPLACE_E_NOTUNDOABLE: Final = -2147221088 +INPLACE_E_NOTOOLSPACE: Final = -2147221087 +INPLACE_E_FIRST: Final = -2147221088 +INPLACE_E_LAST: Final = -2147221073 +INPLACE_S_FIRST: Final = 0x000401A0 +INPLACE_S_LAST: Final = 0x000401AF +ENUM_E_FIRST: Final = -2147221072 +ENUM_E_LAST: Final = -2147221057 +ENUM_S_FIRST: Final = 0x000401B0 +ENUM_S_LAST: Final = 0x000401BF +CONVERT10_E_FIRST: Final = -2147221056 +CONVERT10_E_LAST: Final = -2147221041 +CONVERT10_S_FIRST: Final = 0x000401C0 +CONVERT10_S_LAST: Final = 0x000401CF +CONVERT10_E_OLESTREAM_GET: Final = -2147221056 +CONVERT10_E_OLESTREAM_PUT: Final = -2147221055 +CONVERT10_E_OLESTREAM_FMT: Final = -2147221054 +CONVERT10_E_OLESTREAM_BITMAP_TO_DIB: Final = -2147221053 +CONVERT10_E_STG_FMT: Final = -2147221052 +CONVERT10_E_STG_NO_STD_STREAM: Final = -2147221051 +CONVERT10_E_STG_DIB_TO_BITMAP: Final = -2147221050 +CONVERT10_E_OLELINK_DISABLED: Final = -2147221049 +CLIPBRD_E_FIRST: Final = -2147221040 +CLIPBRD_E_LAST: Final = -2147221025 +CLIPBRD_S_FIRST: Final = 0x000401D0 +CLIPBRD_S_LAST: Final = 0x000401DF +CLIPBRD_E_CANT_OPEN: Final = -2147221040 +CLIPBRD_E_CANT_EMPTY: Final = -2147221039 +CLIPBRD_E_CANT_SET: Final = -2147221038 +CLIPBRD_E_BAD_DATA: Final = -2147221037 +CLIPBRD_E_CANT_CLOSE: Final = -2147221036 +MK_E_FIRST: Final = -2147221024 +MK_E_LAST: Final = -2147221009 +MK_S_FIRST: Final = 0x000401E0 +MK_S_LAST: Final = 0x000401EF +MK_E_CONNECTMANUALLY: Final = -2147221024 +MK_E_EXCEEDEDDEADLINE: Final = -2147221023 +MK_E_NEEDGENERIC: Final = -2147221022 +MK_E_UNAVAILABLE: Final = -2147221021 +MK_E_SYNTAX: Final = -2147221020 +MK_E_NOOBJECT: Final = -2147221019 +MK_E_INVALIDEXTENSION: Final = -2147221018 +MK_E_INTERMEDIATEINTERFACENOTSUPPORTED: Final = -2147221017 +MK_E_NOTBINDABLE: Final = -2147221016 +MK_E_NOTBOUND: Final = -2147221015 +MK_E_CANTOPENFILE: Final = -2147221014 +MK_E_MUSTBOTHERUSER: Final = -2147221013 +MK_E_NOINVERSE: Final = -2147221012 +MK_E_NOSTORAGE: Final = -2147221011 +MK_E_NOPREFIX: Final = -2147221010 +MK_E_ENUMERATION_FAILED: Final = -2147221009 +CO_E_FIRST: Final = -2147221008 +CO_E_LAST: Final = -2147220993 +CO_S_FIRST: Final = 0x000401F0 +CO_S_LAST: Final = 0x000401FF +CO_E_NOTINITIALIZED: Final = -2147221008 +CO_E_ALREADYINITIALIZED: Final = -2147221007 +CO_E_CANTDETERMINECLASS: Final = -2147221006 +CO_E_CLASSSTRING: Final = -2147221005 +CO_E_IIDSTRING: Final = -2147221004 +CO_E_APPNOTFOUND: Final = -2147221003 +CO_E_APPSINGLEUSE: Final = -2147221002 +CO_E_ERRORINAPP: Final = -2147221001 +CO_E_DLLNOTFOUND: Final = -2147221000 +CO_E_ERRORINDLL: Final = -2147220999 +CO_E_WRONGOSFORAPP: Final = -2147220998 +CO_E_OBJNOTREG: Final = -2147220997 +CO_E_OBJISREG: Final = -2147220996 +CO_E_OBJNOTCONNECTED: Final = -2147220995 +CO_E_APPDIDNTREG: Final = -2147220994 +CO_E_RELEASED: Final = -2147220993 +EVENT_E_FIRST: Final = -2147220992 +EVENT_E_LAST: Final = -2147220961 +EVENT_S_FIRST: Final = 0x00040200 +EVENT_S_LAST: Final = 0x0004021F +EVENT_S_SOME_SUBSCRIBERS_FAILED: Final = 0x00040200 +EVENT_E_ALL_SUBSCRIBERS_FAILED: Final = -2147220991 +EVENT_S_NOSUBSCRIBERS: Final = 0x00040202 +EVENT_E_QUERYSYNTAX: Final = -2147220989 +EVENT_E_QUERYFIELD: Final = -2147220988 +EVENT_E_INTERNALEXCEPTION: Final = -2147220987 +EVENT_E_INTERNALERROR: Final = -2147220986 +EVENT_E_INVALID_PER_USER_SID: Final = -2147220985 +EVENT_E_USER_EXCEPTION: Final = -2147220984 +EVENT_E_TOO_MANY_METHODS: Final = -2147220983 +EVENT_E_MISSING_EVENTCLASS: Final = -2147220982 +EVENT_E_NOT_ALL_REMOVED: Final = -2147220981 +EVENT_E_COMPLUS_NOT_INSTALLED: Final = -2147220980 +EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT: Final = -2147220979 +EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT: Final = -2147220978 +EVENT_E_INVALID_EVENT_CLASS_PARTITION: Final = -2147220977 +EVENT_E_PER_USER_SID_NOT_LOGGED_ON: Final = -2147220976 +TPC_E_INVALID_PROPERTY: Final = -2147220927 +TPC_E_NO_DEFAULT_TABLET: Final = -2147220974 +TPC_E_UNKNOWN_PROPERTY: Final = -2147220965 +TPC_E_INVALID_INPUT_RECT: Final = -2147220967 +TPC_E_INVALID_STROKE: Final = -2147220958 +TPC_E_INITIALIZE_FAIL: Final = -2147220957 +TPC_E_NOT_RELEVANT: Final = -2147220942 +TPC_E_INVALID_PACKET_DESCRIPTION: Final = -2147220941 +TPC_E_RECOGNIZER_NOT_REGISTERED: Final = -2147220939 +TPC_E_INVALID_RIGHTS: Final = -2147220938 +TPC_E_OUT_OF_ORDER_CALL: Final = -2147220937 +TPC_E_QUEUE_FULL: Final = -2147220936 +TPC_E_INVALID_CONFIGURATION: Final = -2147220935 +TPC_E_INVALID_DATA_FROM_RECOGNIZER: Final = -2147220934 +TPC_S_TRUNCATED: Final = 0x00040252 +TPC_S_INTERRUPTED: Final = 0x00040253 +TPC_S_NO_DATA_TO_PROCESS: Final = 0x00040254 +XACT_E_FIRST: Final = -2147168256 +XACT_E_LAST: Final = -2147168213 +XACT_S_FIRST: Final = 0x0004D000 +XACT_S_LAST: Final = 0x0004D010 +XACT_E_ALREADYOTHERSINGLEPHASE: Final = -2147168256 +XACT_E_CANTRETAIN: Final = -2147168255 +XACT_E_COMMITFAILED: Final = -2147168254 +XACT_E_COMMITPREVENTED: Final = -2147168253 +XACT_E_HEURISTICABORT: Final = -2147168252 +XACT_E_HEURISTICCOMMIT: Final = -2147168251 +XACT_E_HEURISTICDAMAGE: Final = -2147168250 +XACT_E_HEURISTICDANGER: Final = -2147168249 +XACT_E_ISOLATIONLEVEL: Final = -2147168248 +XACT_E_NOASYNC: Final = -2147168247 +XACT_E_NOENLIST: Final = -2147168246 +XACT_E_NOISORETAIN: Final = -2147168245 +XACT_E_NORESOURCE: Final = -2147168244 +XACT_E_NOTCURRENT: Final = -2147168243 +XACT_E_NOTRANSACTION: Final = -2147168242 +XACT_E_NOTSUPPORTED: Final = -2147168241 +XACT_E_UNKNOWNRMGRID: Final = -2147168240 +XACT_E_WRONGSTATE: Final = -2147168239 +XACT_E_WRONGUOW: Final = -2147168238 +XACT_E_XTIONEXISTS: Final = -2147168237 +XACT_E_NOIMPORTOBJECT: Final = -2147168236 +XACT_E_INVALIDCOOKIE: Final = -2147168235 +XACT_E_INDOUBT: Final = -2147168234 +XACT_E_NOTIMEOUT: Final = -2147168233 +XACT_E_ALREADYINPROGRESS: Final = -2147168232 +XACT_E_ABORTED: Final = -2147168231 +XACT_E_LOGFULL: Final = -2147168230 +XACT_E_TMNOTAVAILABLE: Final = -2147168229 +XACT_E_CONNECTION_DOWN: Final = -2147168228 +XACT_E_CONNECTION_DENIED: Final = -2147168227 +XACT_E_REENLISTTIMEOUT: Final = -2147168226 +XACT_E_TIP_CONNECT_FAILED: Final = -2147168225 +XACT_E_TIP_PROTOCOL_ERROR: Final = -2147168224 +XACT_E_TIP_PULL_FAILED: Final = -2147168223 +XACT_E_DEST_TMNOTAVAILABLE: Final = -2147168222 +XACT_E_TIP_DISABLED: Final = -2147168221 +XACT_E_NETWORK_TX_DISABLED: Final = -2147168220 +XACT_E_PARTNER_NETWORK_TX_DISABLED: Final = -2147168219 +XACT_E_XA_TX_DISABLED: Final = -2147168218 +XACT_E_UNABLE_TO_READ_DTC_CONFIG: Final = -2147168217 +XACT_E_UNABLE_TO_LOAD_DTC_PROXY: Final = -2147168216 +XACT_E_ABORTING: Final = -2147168215 +XACT_E_PUSH_COMM_FAILURE: Final = -2147168214 +XACT_E_PULL_COMM_FAILURE: Final = -2147168213 +XACT_E_LU_TX_DISABLED: Final = -2147168212 +XACT_E_CLERKNOTFOUND: Final = -2147168128 +XACT_E_CLERKEXISTS: Final = -2147168127 +XACT_E_RECOVERYINPROGRESS: Final = -2147168126 +XACT_E_TRANSACTIONCLOSED: Final = -2147168125 +XACT_E_INVALIDLSN: Final = -2147168124 +XACT_E_REPLAYREQUEST: Final = -2147168123 +XACT_S_ASYNC: Final = 0x0004D000 +XACT_S_DEFECT: Final = 0x0004D001 +XACT_S_READONLY: Final = 0x0004D002 +XACT_S_SOMENORETAIN: Final = 0x0004D003 +XACT_S_OKINFORM: Final = 0x0004D004 +XACT_S_MADECHANGESCONTENT: Final = 0x0004D005 +XACT_S_MADECHANGESINFORM: Final = 0x0004D006 +XACT_S_ALLNORETAIN: Final = 0x0004D007 +XACT_S_ABORTING: Final = 0x0004D008 +XACT_S_SINGLEPHASE: Final = 0x0004D009 +XACT_S_LOCALLY_OK: Final = 0x0004D00A +XACT_S_LASTRESOURCEMANAGER: Final = 0x0004D010 +CONTEXT_E_FIRST: Final = -2147164160 +CONTEXT_E_LAST: Final = -2147164113 +CONTEXT_S_FIRST: Final = 0x0004E000 +CONTEXT_S_LAST: Final = 0x0004E02F +CONTEXT_E_ABORTED: Final = -2147164158 +CONTEXT_E_ABORTING: Final = -2147164157 +CONTEXT_E_NOCONTEXT: Final = -2147164156 +CONTEXT_E_WOULD_DEADLOCK: Final = -2147164155 +CONTEXT_E_SYNCH_TIMEOUT: Final = -2147164154 +CONTEXT_E_OLDREF: Final = -2147164153 +CONTEXT_E_ROLENOTFOUND: Final = -2147164148 +CONTEXT_E_TMNOTAVAILABLE: Final = -2147164145 +CO_E_ACTIVATIONFAILED: Final = -2147164127 +CO_E_ACTIVATIONFAILED_EVENTLOGGED: Final = -2147164126 +CO_E_ACTIVATIONFAILED_CATALOGERROR: Final = -2147164125 +CO_E_ACTIVATIONFAILED_TIMEOUT: Final = -2147164124 +CO_E_INITIALIZATIONFAILED: Final = -2147164123 +CONTEXT_E_NOJIT: Final = -2147164122 +CONTEXT_E_NOTRANSACTION: Final = -2147164121 +CO_E_THREADINGMODEL_CHANGED: Final = -2147164120 +CO_E_NOIISINTRINSICS: Final = -2147164119 +CO_E_NOCOOKIES: Final = -2147164118 +CO_E_DBERROR: Final = -2147164117 +CO_E_NOTPOOLED: Final = -2147164116 +CO_E_NOTCONSTRUCTED: Final = -2147164115 +CO_E_NOSYNCHRONIZATION: Final = -2147164114 +CO_E_ISOLEVELMISMATCH: Final = -2147164113 +CO_E_CALL_OUT_OF_TX_SCOPE_NOT_ALLOWED: Final = -2147164112 +CO_E_EXIT_TRANSACTION_SCOPE_NOT_CALLED: Final = -2147164111 +OLE_S_USEREG: Final = 0x00040000 +OLE_S_STATIC: Final = 0x00040001 +OLE_S_MAC_CLIPFORMAT: Final = 0x00040002 +DRAGDROP_S_DROP: Final = 0x00040100 +DRAGDROP_S_CANCEL: Final = 0x00040101 +DRAGDROP_S_USEDEFAULTCURSORS: Final = 0x00040102 +DATA_S_SAMEFORMATETC: Final = 0x00040130 +VIEW_S_ALREADY_FROZEN: Final = 0x00040140 +CACHE_S_FORMATETC_NOTSUPPORTED: Final = 0x00040170 +CACHE_S_SAMECACHE: Final = 0x00040171 +CACHE_S_SOMECACHES_NOTUPDATED: Final = 0x00040172 +OLEOBJ_S_INVALIDVERB: Final = 0x00040180 +OLEOBJ_S_CANNOT_DOVERB_NOW: Final = 0x00040181 +OLEOBJ_S_INVALIDHWND: Final = 0x00040182 +INPLACE_S_TRUNCATED: Final = 0x000401A0 +CONVERT10_S_NO_PRESENTATION: Final = 0x000401C0 +MK_S_REDUCED_TO_SELF: Final = 0x000401E2 +MK_S_ME: Final = 0x000401E4 +MK_S_HIM: Final = 0x000401E5 +MK_S_US: Final = 0x000401E6 +MK_S_MONIKERALREADYREGISTERED: Final = 0x000401E7 +SCHED_S_TASK_READY: Final = 0x00041300 +SCHED_S_TASK_RUNNING: Final = 0x00041301 +SCHED_S_TASK_DISABLED: Final = 0x00041302 +SCHED_S_TASK_HAS_NOT_RUN: Final = 0x00041303 +SCHED_S_TASK_NO_MORE_RUNS: Final = 0x00041304 +SCHED_S_TASK_NOT_SCHEDULED: Final = 0x00041305 +SCHED_S_TASK_TERMINATED: Final = 0x00041306 +SCHED_S_TASK_NO_VALID_TRIGGERS: Final = 0x00041307 +SCHED_S_EVENT_TRIGGER: Final = 0x00041308 +SCHED_E_TRIGGER_NOT_FOUND: Final = -2147216631 +SCHED_E_TASK_NOT_READY: Final = -2147216630 +SCHED_E_TASK_NOT_RUNNING: Final = -2147216629 +SCHED_E_SERVICE_NOT_INSTALLED: Final = -2147216628 +SCHED_E_CANNOT_OPEN_TASK: Final = -2147216627 +SCHED_E_INVALID_TASK: Final = -2147216626 +SCHED_E_ACCOUNT_INFORMATION_NOT_SET: Final = -2147216625 +SCHED_E_ACCOUNT_NAME_NOT_FOUND: Final = -2147216624 +SCHED_E_ACCOUNT_DBASE_CORRUPT: Final = -2147216623 +SCHED_E_NO_SECURITY_SERVICES: Final = -2147216622 +SCHED_E_UNKNOWN_OBJECT_VERSION: Final = -2147216621 +SCHED_E_UNSUPPORTED_ACCOUNT_OPTION: Final = -2147216620 +SCHED_E_SERVICE_NOT_RUNNING: Final = -2147216619 +SCHED_E_UNEXPECTEDNODE: Final = -2147216618 +SCHED_E_NAMESPACE: Final = -2147216617 +SCHED_E_INVALIDVALUE: Final = -2147216616 +SCHED_E_MISSINGNODE: Final = -2147216615 +SCHED_E_MALFORMEDXML: Final = -2147216614 +SCHED_S_SOME_TRIGGERS_FAILED: Final = 0x0004131B +SCHED_S_BATCH_LOGON_PROBLEM: Final = 0x0004131C +SCHED_E_TOO_MANY_NODES: Final = -2147216611 +SCHED_E_PAST_END_BOUNDARY: Final = -2147216610 +SCHED_E_ALREADY_RUNNING: Final = -2147216609 +SCHED_E_USER_NOT_LOGGED_ON: Final = -2147216608 +SCHED_E_INVALID_TASK_HASH: Final = -2147216607 +SCHED_E_SERVICE_NOT_AVAILABLE: Final = -2147216606 +SCHED_E_SERVICE_TOO_BUSY: Final = -2147216605 +SCHED_E_TASK_ATTEMPTED: Final = -2147216604 +SCHED_S_TASK_QUEUED: Final = 0x00041325 +SCHED_E_TASK_DISABLED: Final = -2147216602 +SCHED_E_TASK_NOT_V1_COMPAT: Final = -2147216601 +SCHED_E_START_ON_DEMAND: Final = -2147216600 +SCHED_E_TASK_NOT_UBPM_COMPAT: Final = -2147216599 +SCHED_E_DEPRECATED_FEATURE_USED: Final = -2147216592 +CO_E_CLASS_CREATE_FAILED: Final = -2146959359 +CO_E_SCM_ERROR: Final = -2146959358 +CO_E_SCM_RPC_FAILURE: Final = -2146959357 +CO_E_BAD_PATH: Final = -2146959356 +CO_E_SERVER_EXEC_FAILURE: Final = -2146959355 +CO_E_OBJSRV_RPC_FAILURE: Final = -2146959354 +MK_E_NO_NORMALIZED: Final = -2146959353 +CO_E_SERVER_STOPPING: Final = -2146959352 +MEM_E_INVALID_ROOT: Final = -2146959351 +MEM_E_INVALID_LINK: Final = -2146959344 +MEM_E_INVALID_SIZE: Final = -2146959343 +CO_S_NOTALLINTERFACES: Final = 0x00080012 +CO_S_MACHINENAMENOTFOUND: Final = 0x00080013 +CO_E_MISSING_DISPLAYNAME: Final = -2146959339 +CO_E_RUNAS_VALUE_MUST_BE_AAA: Final = -2146959338 +CO_E_ELEVATION_DISABLED: Final = -2146959337 +APPX_E_PACKAGING_INTERNAL: Final = -2146958848 +APPX_E_INTERLEAVING_NOT_ALLOWED: Final = -2146958847 +APPX_E_RELATIONSHIPS_NOT_ALLOWED: Final = -2146958846 +APPX_E_MISSING_REQUIRED_FILE: Final = -2146958845 +APPX_E_INVALID_MANIFEST: Final = -2146958844 +APPX_E_INVALID_BLOCKMAP: Final = -2146958843 +APPX_E_CORRUPT_CONTENT: Final = -2146958842 +APPX_E_BLOCK_HASH_INVALID: Final = -2146958841 +APPX_E_REQUESTED_RANGE_TOO_LARGE: Final = -2146958840 +APPX_E_INVALID_SIP_CLIENT_DATA: Final = -2146958839 +APPX_E_INVALID_KEY_INFO: Final = -2146958838 +APPX_E_INVALID_CONTENTGROUPMAP: Final = -2146958837 +APPX_E_INVALID_APPINSTALLER: Final = -2146958836 +APPX_E_DELTA_BASELINE_VERSION_MISMATCH: Final = -2146958835 +APPX_E_DELTA_PACKAGE_MISSING_FILE: Final = -2146958834 +APPX_E_INVALID_DELTA_PACKAGE: Final = -2146958833 +APPX_E_DELTA_APPENDED_PACKAGE_NOT_ALLOWED: Final = -2146958832 +APPX_E_INVALID_PACKAGING_LAYOUT: Final = -2146958831 +APPX_E_INVALID_PACKAGESIGNCONFIG: Final = -2146958830 +APPX_E_RESOURCESPRI_NOT_ALLOWED: Final = -2146958829 +APPX_E_FILE_COMPRESSION_MISMATCH: Final = -2146958828 +APPX_E_INVALID_PAYLOAD_PACKAGE_EXTENSION: Final = -2146958827 +APPX_E_INVALID_ENCRYPTION_EXCLUSION_FILE_LIST: Final = -2146958826 +APPX_E_INVALID_PACKAGE_FOLDER_ACLS: Final = -2146958825 +APPX_E_INVALID_PUBLISHER_BRIDGING: Final = -2146958824 +APPX_E_DIGEST_MISMATCH: Final = -2146958823 +BT_E_SPURIOUS_ACTIVATION: Final = -2146958592 +DISP_E_UNKNOWNINTERFACE: Final = -2147352575 +DISP_E_MEMBERNOTFOUND: Final = -2147352573 +DISP_E_PARAMNOTFOUND: Final = -2147352572 +DISP_E_TYPEMISMATCH: Final = -2147352571 +DISP_E_UNKNOWNNAME: Final = -2147352570 +DISP_E_NONAMEDARGS: Final = -2147352569 +DISP_E_BADVARTYPE: Final = -2147352568 +DISP_E_EXCEPTION: Final = -2147352567 +DISP_E_OVERFLOW: Final = -2147352566 +DISP_E_BADINDEX: Final = -2147352565 +DISP_E_UNKNOWNLCID: Final = -2147352564 +DISP_E_ARRAYISLOCKED: Final = -2147352563 +DISP_E_BADPARAMCOUNT: Final = -2147352562 +DISP_E_PARAMNOTOPTIONAL: Final = -2147352561 +DISP_E_BADCALLEE: Final = -2147352560 +DISP_E_NOTACOLLECTION: Final = -2147352559 +DISP_E_DIVBYZERO: Final = -2147352558 +DISP_E_BUFFERTOOSMALL: Final = -2147352557 +TYPE_E_BUFFERTOOSMALL: Final = -2147319786 +TYPE_E_FIELDNOTFOUND: Final = -2147319785 +TYPE_E_INVDATAREAD: Final = -2147319784 +TYPE_E_UNSUPFORMAT: Final = -2147319783 +TYPE_E_REGISTRYACCESS: Final = -2147319780 +TYPE_E_LIBNOTREGISTERED: Final = -2147319779 +TYPE_E_UNDEFINEDTYPE: Final = -2147319769 +TYPE_E_QUALIFIEDNAMEDISALLOWED: Final = -2147319768 +TYPE_E_INVALIDSTATE: Final = -2147319767 +TYPE_E_WRONGTYPEKIND: Final = -2147319766 +TYPE_E_ELEMENTNOTFOUND: Final = -2147319765 +TYPE_E_AMBIGUOUSNAME: Final = -2147319764 +TYPE_E_NAMECONFLICT: Final = -2147319763 +TYPE_E_UNKNOWNLCID: Final = -2147319762 +TYPE_E_DLLFUNCTIONNOTFOUND: Final = -2147319761 +TYPE_E_BADMODULEKIND: Final = -2147317571 +TYPE_E_SIZETOOBIG: Final = -2147317563 +TYPE_E_DUPLICATEID: Final = -2147317562 +TYPE_E_INVALIDID: Final = -2147317553 +TYPE_E_TYPEMISMATCH: Final = -2147316576 +TYPE_E_OUTOFBOUNDS: Final = -2147316575 +TYPE_E_IOERROR: Final = -2147316574 +TYPE_E_CANTCREATETMPFILE: Final = -2147316573 +TYPE_E_CANTLOADLIBRARY: Final = -2147312566 +TYPE_E_INCONSISTENTPROPFUNCS: Final = -2147312509 +TYPE_E_CIRCULARTYPE: Final = -2147312508 +STG_E_INVALIDFUNCTION: Final = -2147287039 +STG_E_FILENOTFOUND: Final = -2147287038 +STG_E_PATHNOTFOUND: Final = -2147287037 +STG_E_TOOMANYOPENFILES: Final = -2147287036 +STG_E_ACCESSDENIED: Final = -2147287035 +STG_E_INVALIDHANDLE: Final = -2147287034 +STG_E_INSUFFICIENTMEMORY: Final = -2147287032 +STG_E_INVALIDPOINTER: Final = -2147287031 +STG_E_NOMOREFILES: Final = -2147287022 +STG_E_DISKISWRITEPROTECTED: Final = -2147287021 +STG_E_SEEKERROR: Final = -2147287015 +STG_E_WRITEFAULT: Final = -2147287011 +STG_E_READFAULT: Final = -2147287010 +STG_E_SHAREVIOLATION: Final = -2147287008 +STG_E_LOCKVIOLATION: Final = -2147287007 +STG_E_FILEALREADYEXISTS: Final = -2147286960 +STG_E_INVALIDPARAMETER: Final = -2147286953 +STG_E_MEDIUMFULL: Final = -2147286928 +STG_E_PROPSETMISMATCHED: Final = -2147286800 +STG_E_ABNORMALAPIEXIT: Final = -2147286790 +STG_E_INVALIDHEADER: Final = -2147286789 +STG_E_INVALIDNAME: Final = -2147286788 +STG_E_UNKNOWN: Final = -2147286787 +STG_E_UNIMPLEMENTEDFUNCTION: Final = -2147286786 +STG_E_INVALIDFLAG: Final = -2147286785 +STG_E_INUSE: Final = -2147286784 +STG_E_NOTCURRENT: Final = -2147286783 +STG_E_REVERTED: Final = -2147286782 +STG_E_CANTSAVE: Final = -2147286781 +STG_E_OLDFORMAT: Final = -2147286780 +STG_E_OLDDLL: Final = -2147286779 +STG_E_SHAREREQUIRED: Final = -2147286778 +STG_E_NOTFILEBASEDSTORAGE: Final = -2147286777 +STG_E_EXTANTMARSHALLINGS: Final = -2147286776 +STG_E_DOCFILECORRUPT: Final = -2147286775 +STG_E_BADBASEADDRESS: Final = -2147286768 +STG_E_DOCFILETOOLARGE: Final = -2147286767 +STG_E_NOTSIMPLEFORMAT: Final = -2147286766 +STG_E_INCOMPLETE: Final = -2147286527 +STG_E_TERMINATED: Final = -2147286526 +STG_S_CONVERTED: Final = 0x00030200 +STG_S_BLOCK: Final = 0x00030201 +STG_S_RETRYNOW: Final = 0x00030202 +STG_S_MONITORING: Final = 0x00030203 +STG_S_MULTIPLEOPENS: Final = 0x00030204 +STG_S_CONSOLIDATIONFAILED: Final = 0x00030205 +STG_S_CANNOTCONSOLIDATE: Final = 0x00030206 +STG_S_POWER_CYCLE_REQUIRED: Final = 0x00030207 +STG_E_FIRMWARE_SLOT_INVALID: Final = -2147286520 +STG_E_FIRMWARE_IMAGE_INVALID: Final = -2147286519 +STG_E_DEVICE_UNRESPONSIVE: Final = -2147286518 +STG_E_STATUS_COPY_PROTECTION_FAILURE: Final = -2147286267 +STG_E_CSS_AUTHENTICATION_FAILURE: Final = -2147286266 +STG_E_CSS_KEY_NOT_PRESENT: Final = -2147286265 +STG_E_CSS_KEY_NOT_ESTABLISHED: Final = -2147286264 +STG_E_CSS_SCRAMBLED_SECTOR: Final = -2147286263 +STG_E_CSS_REGION_MISMATCH: Final = -2147286262 +STG_E_RESETS_EXHAUSTED: Final = -2147286261 +RPC_E_CALL_REJECTED: Final = -2147418111 +RPC_E_CALL_CANCELED: Final = -2147418110 +RPC_E_CANTPOST_INSENDCALL: Final = -2147418109 +RPC_E_CANTCALLOUT_INASYNCCALL: Final = -2147418108 +RPC_E_CANTCALLOUT_INEXTERNALCALL: Final = -2147418107 +RPC_E_CONNECTION_TERMINATED: Final = -2147418106 +RPC_E_SERVER_DIED: Final = -2147418105 +RPC_E_CLIENT_DIED: Final = -2147418104 +RPC_E_INVALID_DATAPACKET: Final = -2147418103 +RPC_E_CANTTRANSMIT_CALL: Final = -2147418102 +RPC_E_CLIENT_CANTMARSHAL_DATA: Final = -2147418101 +RPC_E_CLIENT_CANTUNMARSHAL_DATA: Final = -2147418100 +RPC_E_SERVER_CANTMARSHAL_DATA: Final = -2147418099 +RPC_E_SERVER_CANTUNMARSHAL_DATA: Final = -2147418098 +RPC_E_INVALID_DATA: Final = -2147418097 +RPC_E_INVALID_PARAMETER: Final = -2147418096 +RPC_E_CANTCALLOUT_AGAIN: Final = -2147418095 +RPC_E_SERVER_DIED_DNE: Final = -2147418094 +RPC_E_SYS_CALL_FAILED: Final = -2147417856 +RPC_E_OUT_OF_RESOURCES: Final = -2147417855 +RPC_E_ATTEMPTED_MULTITHREAD: Final = -2147417854 +RPC_E_NOT_REGISTERED: Final = -2147417853 +RPC_E_FAULT: Final = -2147417852 +RPC_E_SERVERFAULT: Final = -2147417851 +RPC_E_CHANGED_MODE: Final = -2147417850 +RPC_E_INVALIDMETHOD: Final = -2147417849 +RPC_E_DISCONNECTED: Final = -2147417848 +RPC_E_RETRY: Final = -2147417847 +RPC_E_SERVERCALL_RETRYLATER: Final = -2147417846 +RPC_E_SERVERCALL_REJECTED: Final = -2147417845 +RPC_E_INVALID_CALLDATA: Final = -2147417844 +RPC_E_CANTCALLOUT_ININPUTSYNCCALL: Final = -2147417843 +RPC_E_WRONG_THREAD: Final = -2147417842 +RPC_E_THREAD_NOT_INIT: Final = -2147417841 +RPC_E_VERSION_MISMATCH: Final = -2147417840 +RPC_E_INVALID_HEADER: Final = -2147417839 +RPC_E_INVALID_EXTENSION: Final = -2147417838 +RPC_E_INVALID_IPID: Final = -2147417837 +RPC_E_INVALID_OBJECT: Final = -2147417836 +RPC_S_CALLPENDING: Final = -2147417835 +RPC_S_WAITONTIMER: Final = -2147417834 +RPC_E_CALL_COMPLETE: Final = -2147417833 +RPC_E_UNSECURE_CALL: Final = -2147417832 +RPC_E_TOO_LATE: Final = -2147417831 +RPC_E_NO_GOOD_SECURITY_PACKAGES: Final = -2147417830 +RPC_E_ACCESS_DENIED: Final = -2147417829 +RPC_E_REMOTE_DISABLED: Final = -2147417828 +RPC_E_INVALID_OBJREF: Final = -2147417827 +RPC_E_NO_CONTEXT: Final = -2147417826 +RPC_E_TIMEOUT: Final = -2147417825 +RPC_E_NO_SYNC: Final = -2147417824 +RPC_E_FULLSIC_REQUIRED: Final = -2147417823 +RPC_E_INVALID_STD_NAME: Final = -2147417822 +CO_E_FAILEDTOIMPERSONATE: Final = -2147417821 +CO_E_FAILEDTOGETSECCTX: Final = -2147417820 +CO_E_FAILEDTOOPENTHREADTOKEN: Final = -2147417819 +CO_E_FAILEDTOGETTOKENINFO: Final = -2147417818 +CO_E_TRUSTEEDOESNTMATCHCLIENT: Final = -2147417817 +CO_E_FAILEDTOQUERYCLIENTBLANKET: Final = -2147417816 +CO_E_FAILEDTOSETDACL: Final = -2147417815 +CO_E_ACCESSCHECKFAILED: Final = -2147417814 +CO_E_NETACCESSAPIFAILED: Final = -2147417813 +CO_E_WRONGTRUSTEENAMESYNTAX: Final = -2147417812 +CO_E_INVALIDSID: Final = -2147417811 +CO_E_CONVERSIONFAILED: Final = -2147417810 +CO_E_NOMATCHINGSIDFOUND: Final = -2147417809 +CO_E_LOOKUPACCSIDFAILED: Final = -2147417808 +CO_E_NOMATCHINGNAMEFOUND: Final = -2147417807 +CO_E_LOOKUPACCNAMEFAILED: Final = -2147417806 +CO_E_SETSERLHNDLFAILED: Final = -2147417805 +CO_E_FAILEDTOGETWINDIR: Final = -2147417804 +CO_E_PATHTOOLONG: Final = -2147417803 +CO_E_FAILEDTOGENUUID: Final = -2147417802 +CO_E_FAILEDTOCREATEFILE: Final = -2147417801 +CO_E_FAILEDTOCLOSEHANDLE: Final = -2147417800 +CO_E_EXCEEDSYSACLLIMIT: Final = -2147417799 +CO_E_ACESINWRONGORDER: Final = -2147417798 +CO_E_INCOMPATIBLESTREAMVERSION: Final = -2147417797 +CO_E_FAILEDTOOPENPROCESSTOKEN: Final = -2147417796 +CO_E_DECODEFAILED: Final = -2147417795 +CO_E_ACNOTINITIALIZED: Final = -2147417793 +CO_E_CANCEL_DISABLED: Final = -2147417792 +RPC_E_UNEXPECTED: Final = -2147352577 +ERROR_AUDITING_DISABLED: Final = -1073151999 +ERROR_ALL_SIDS_FILTERED: Final = -1073151998 +ERROR_BIZRULES_NOT_ENABLED: Final = -1073151997 +NTE_BAD_UID: Final = -2146893823 +NTE_BAD_HASH: Final = -2146893822 +NTE_BAD_KEY: Final = -2146893821 +NTE_BAD_LEN: Final = -2146893820 +NTE_BAD_DATA: Final = -2146893819 +NTE_BAD_SIGNATURE: Final = -2146893818 +NTE_BAD_VER: Final = -2146893817 +NTE_BAD_ALGID: Final = -2146893816 +NTE_BAD_FLAGS: Final = -2146893815 +NTE_BAD_TYPE: Final = -2146893814 +NTE_BAD_KEY_STATE: Final = -2146893813 +NTE_BAD_HASH_STATE: Final = -2146893812 +NTE_NO_KEY: Final = -2146893811 +NTE_NO_MEMORY: Final = -2146893810 +NTE_EXISTS: Final = -2146893809 +NTE_PERM: Final = -2146893808 +NTE_NOT_FOUND: Final = -2146893807 +NTE_DOUBLE_ENCRYPT: Final = -2146893806 +NTE_BAD_PROVIDER: Final = -2146893805 +NTE_BAD_PROV_TYPE: Final = -2146893804 +NTE_BAD_PUBLIC_KEY: Final = -2146893803 +NTE_BAD_KEYSET: Final = -2146893802 +NTE_PROV_TYPE_NOT_DEF: Final = -2146893801 +NTE_PROV_TYPE_ENTRY_BAD: Final = -2146893800 +NTE_KEYSET_NOT_DEF: Final = -2146893799 +NTE_KEYSET_ENTRY_BAD: Final = -2146893798 +NTE_PROV_TYPE_NO_MATCH: Final = -2146893797 +NTE_SIGNATURE_FILE_BAD: Final = -2146893796 +NTE_PROVIDER_DLL_FAIL: Final = -2146893795 +NTE_PROV_DLL_NOT_FOUND: Final = -2146893794 +NTE_BAD_KEYSET_PARAM: Final = -2146893793 +NTE_FAIL: Final = -2146893792 +NTE_SYS_ERR: Final = -2146893791 +NTE_SILENT_CONTEXT: Final = -2146893790 +NTE_TOKEN_KEYSET_STORAGE_FULL: Final = -2146893789 +NTE_TEMPORARY_PROFILE: Final = -2146893788 +NTE_FIXEDPARAMETER: Final = -2146893787 +NTE_INVALID_HANDLE: Final = -2146893786 +NTE_INVALID_PARAMETER: Final = -2146893785 +NTE_BUFFER_TOO_SMALL: Final = -2146893784 +NTE_NOT_SUPPORTED: Final = -2146893783 +NTE_NO_MORE_ITEMS: Final = -2146893782 +NTE_BUFFERS_OVERLAP: Final = -2146893781 +NTE_DECRYPTION_FAILURE: Final = -2146893780 +NTE_INTERNAL_ERROR: Final = -2146893779 +NTE_UI_REQUIRED: Final = -2146893778 +NTE_HMAC_NOT_SUPPORTED: Final = -2146893777 +NTE_DEVICE_NOT_READY: Final = -2146893776 +NTE_AUTHENTICATION_IGNORED: Final = -2146893775 +NTE_VALIDATION_FAILED: Final = -2146893774 +NTE_INCORRECT_PASSWORD: Final = -2146893773 +NTE_ENCRYPTION_FAILURE: Final = -2146893772 +NTE_DEVICE_NOT_FOUND: Final = -2146893771 +NTE_USER_CANCELLED: Final = -2146893770 +NTE_PASSWORD_CHANGE_REQUIRED: Final = -2146893769 +NTE_NOT_ACTIVE_CONSOLE: Final = -2146893768 +SEC_E_INSUFFICIENT_MEMORY: Final = -2146893056 +SEC_E_INVALID_HANDLE: Final = -2146893055 +SEC_E_UNSUPPORTED_FUNCTION: Final = -2146893054 +SEC_E_TARGET_UNKNOWN: Final = -2146893053 +SEC_E_INTERNAL_ERROR: Final = -2146893052 +SEC_E_SECPKG_NOT_FOUND: Final = -2146893051 +SEC_E_NOT_OWNER: Final = -2146893050 +SEC_E_CANNOT_INSTALL: Final = -2146893049 +SEC_E_INVALID_TOKEN: Final = -2146893048 +SEC_E_CANNOT_PACK: Final = -2146893047 +SEC_E_QOP_NOT_SUPPORTED: Final = -2146893046 +SEC_E_NO_IMPERSONATION: Final = -2146893045 +SEC_E_LOGON_DENIED: Final = -2146893044 +SEC_E_UNKNOWN_CREDENTIALS: Final = -2146893043 +SEC_E_NO_CREDENTIALS: Final = -2146893042 +SEC_E_MESSAGE_ALTERED: Final = -2146893041 +SEC_E_OUT_OF_SEQUENCE: Final = -2146893040 +SEC_E_NO_AUTHENTICATING_AUTHORITY: Final = -2146893039 +SEC_I_CONTINUE_NEEDED: Final = 0x00090312 +SEC_I_COMPLETE_NEEDED: Final = 0x00090313 +SEC_I_COMPLETE_AND_CONTINUE: Final = 0x00090314 +SEC_I_LOCAL_LOGON: Final = 0x00090315 +SEC_I_GENERIC_EXTENSION_RECEIVED: Final = 0x00090316 +SEC_E_BAD_PKGID: Final = -2146893034 +SEC_E_CONTEXT_EXPIRED: Final = -2146893033 +SEC_I_CONTEXT_EXPIRED: Final = 0x00090317 +SEC_E_INCOMPLETE_MESSAGE: Final = -2146893032 +SEC_E_INCOMPLETE_CREDENTIALS: Final = -2146893024 +SEC_E_BUFFER_TOO_SMALL: Final = -2146893023 +SEC_I_INCOMPLETE_CREDENTIALS: Final = 0x00090320 +SEC_I_RENEGOTIATE: Final = 0x00090321 +SEC_E_WRONG_PRINCIPAL: Final = -2146893022 +SEC_I_NO_LSA_CONTEXT: Final = 0x00090323 +SEC_E_TIME_SKEW: Final = -2146893020 +SEC_E_UNTRUSTED_ROOT: Final = -2146893019 +SEC_E_ILLEGAL_MESSAGE: Final = -2146893018 +SEC_E_CERT_UNKNOWN: Final = -2146893017 +SEC_E_CERT_EXPIRED: Final = -2146893016 +SEC_E_ENCRYPT_FAILURE: Final = -2146893015 +SEC_E_DECRYPT_FAILURE: Final = -2146893008 +SEC_E_ALGORITHM_MISMATCH: Final = -2146893007 +SEC_E_SECURITY_QOS_FAILED: Final = -2146893006 +SEC_E_UNFINISHED_CONTEXT_DELETED: Final = -2146893005 +SEC_E_NO_TGT_REPLY: Final = -2146893004 +SEC_E_NO_IP_ADDRESSES: Final = -2146893003 +SEC_E_WRONG_CREDENTIAL_HANDLE: Final = -2146893002 +SEC_E_CRYPTO_SYSTEM_INVALID: Final = -2146893001 +SEC_E_MAX_REFERRALS_EXCEEDED: Final = -2146893000 +SEC_E_MUST_BE_KDC: Final = -2146892999 +SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: Final = -2146892998 +SEC_E_TOO_MANY_PRINCIPALS: Final = -2146892997 +SEC_E_NO_PA_DATA: Final = -2146892996 +SEC_E_PKINIT_NAME_MISMATCH: Final = -2146892995 +SEC_E_SMARTCARD_LOGON_REQUIRED: Final = -2146892994 +SEC_E_SHUTDOWN_IN_PROGRESS: Final = -2146892993 +SEC_E_KDC_INVALID_REQUEST: Final = -2146892992 +SEC_E_KDC_UNABLE_TO_REFER: Final = -2146892991 +SEC_E_KDC_UNKNOWN_ETYPE: Final = -2146892990 +SEC_E_UNSUPPORTED_PREAUTH: Final = -2146892989 +SEC_E_DELEGATION_REQUIRED: Final = -2146892987 +SEC_E_BAD_BINDINGS: Final = -2146892986 +SEC_E_MULTIPLE_ACCOUNTS: Final = -2146892985 +SEC_E_NO_KERB_KEY: Final = -2146892984 +SEC_E_CERT_WRONG_USAGE: Final = -2146892983 +SEC_E_DOWNGRADE_DETECTED: Final = -2146892976 +SEC_E_SMARTCARD_CERT_REVOKED: Final = -2146892975 +SEC_E_ISSUING_CA_UNTRUSTED: Final = -2146892974 +SEC_E_REVOCATION_OFFLINE_C: Final = -2146892973 +SEC_E_PKINIT_CLIENT_FAILURE: Final = -2146892972 +SEC_E_SMARTCARD_CERT_EXPIRED: Final = -2146892971 +SEC_E_NO_S4U_PROT_SUPPORT: Final = -2146892970 +SEC_E_CROSSREALM_DELEGATION_FAILURE: Final = -2146892969 +SEC_E_REVOCATION_OFFLINE_KDC: Final = -2146892968 +SEC_E_ISSUING_CA_UNTRUSTED_KDC: Final = -2146892967 +SEC_E_KDC_CERT_EXPIRED: Final = -2146892966 +SEC_E_KDC_CERT_REVOKED: Final = -2146892965 +SEC_I_SIGNATURE_NEEDED: Final = 0x0009035C +SEC_E_INVALID_PARAMETER: Final = -2146892963 +SEC_E_DELEGATION_POLICY: Final = -2146892962 +SEC_E_POLICY_NLTM_ONLY: Final = -2146892961 +SEC_I_NO_RENEGOTIATION: Final = 0x00090360 +SEC_E_NO_CONTEXT: Final = -2146892959 +SEC_E_PKU2U_CERT_FAILURE: Final = -2146892958 +SEC_E_MUTUAL_AUTH_FAILED: Final = -2146892957 +SEC_I_MESSAGE_FRAGMENT: Final = 0x00090364 +SEC_E_ONLY_HTTPS_ALLOWED: Final = -2146892955 +SEC_I_CONTINUE_NEEDED_MESSAGE_OK: Final = 0x00090366 +SEC_E_APPLICATION_PROTOCOL_MISMATCH: Final = -2146892953 +SEC_I_ASYNC_CALL_PENDING: Final = 0x00090368 +SEC_E_INVALID_UPN_NAME: Final = -2146892951 +SEC_E_EXT_BUFFER_TOO_SMALL: Final = -2146892950 +SEC_E_INSUFFICIENT_BUFFERS: Final = -2146892949 +SEC_E_NO_SPM: Final = SEC_E_INTERNAL_ERROR +SEC_E_NOT_SUPPORTED: Final = SEC_E_UNSUPPORTED_FUNCTION +CRYPT_E_MSG_ERROR: Final = -2146889727 +CRYPT_E_UNKNOWN_ALGO: Final = -2146889726 +CRYPT_E_OID_FORMAT: Final = -2146889725 +CRYPT_E_INVALID_MSG_TYPE: Final = -2146889724 +CRYPT_E_UNEXPECTED_ENCODING: Final = -2146889723 +CRYPT_E_AUTH_ATTR_MISSING: Final = -2146889722 +CRYPT_E_HASH_VALUE: Final = -2146889721 +CRYPT_E_INVALID_INDEX: Final = -2146889720 +CRYPT_E_ALREADY_DECRYPTED: Final = -2146889719 +CRYPT_E_NOT_DECRYPTED: Final = -2146889718 +CRYPT_E_RECIPIENT_NOT_FOUND: Final = -2146889717 +CRYPT_E_CONTROL_TYPE: Final = -2146889716 +CRYPT_E_ISSUER_SERIALNUMBER: Final = -2146889715 +CRYPT_E_SIGNER_NOT_FOUND: Final = -2146889714 +CRYPT_E_ATTRIBUTES_MISSING: Final = -2146889713 +CRYPT_E_STREAM_MSG_NOT_READY: Final = -2146889712 +CRYPT_E_STREAM_INSUFFICIENT_DATA: Final = -2146889711 +CRYPT_I_NEW_PROTECTION_REQUIRED: Final = 0x00091012 +CRYPT_E_BAD_LEN: Final = -2146885631 +CRYPT_E_BAD_ENCODE: Final = -2146885630 +CRYPT_E_FILE_ERROR: Final = -2146885629 +CRYPT_E_NOT_FOUND: Final = -2146885628 +CRYPT_E_EXISTS: Final = -2146885627 +CRYPT_E_NO_PROVIDER: Final = -2146885626 +CRYPT_E_SELF_SIGNED: Final = -2146885625 +CRYPT_E_DELETED_PREV: Final = -2146885624 +CRYPT_E_NO_MATCH: Final = -2146885623 +CRYPT_E_UNEXPECTED_MSG_TYPE: Final = -2146885622 +CRYPT_E_NO_KEY_PROPERTY: Final = -2146885621 +CRYPT_E_NO_DECRYPT_CERT: Final = -2146885620 +CRYPT_E_BAD_MSG: Final = -2146885619 +CRYPT_E_NO_SIGNER: Final = -2146885618 +CRYPT_E_PENDING_CLOSE: Final = -2146885617 +CRYPT_E_REVOKED: Final = -2146885616 +CRYPT_E_NO_REVOCATION_DLL: Final = -2146885615 +CRYPT_E_NO_REVOCATION_CHECK: Final = -2146885614 +CRYPT_E_REVOCATION_OFFLINE: Final = -2146885613 +CRYPT_E_NOT_IN_REVOCATION_DATABASE: Final = -2146885612 +CRYPT_E_INVALID_NUMERIC_STRING: Final = -2146885600 +CRYPT_E_INVALID_PRINTABLE_STRING: Final = -2146885599 +CRYPT_E_INVALID_IA5_STRING: Final = -2146885598 +CRYPT_E_INVALID_X500_STRING: Final = -2146885597 +CRYPT_E_NOT_CHAR_STRING: Final = -2146885596 +CRYPT_E_FILERESIZED: Final = -2146885595 +CRYPT_E_SECURITY_SETTINGS: Final = -2146885594 +CRYPT_E_NO_VERIFY_USAGE_DLL: Final = -2146885593 +CRYPT_E_NO_VERIFY_USAGE_CHECK: Final = -2146885592 +CRYPT_E_VERIFY_USAGE_OFFLINE: Final = -2146885591 +CRYPT_E_NOT_IN_CTL: Final = -2146885590 +CRYPT_E_NO_TRUSTED_SIGNER: Final = -2146885589 +CRYPT_E_MISSING_PUBKEY_PARA: Final = -2146885588 +CRYPT_E_OBJECT_LOCATOR_OBJECT_NOT_FOUND: Final = -2146885587 +CRYPT_E_OSS_ERROR: Final = -2146881536 +OSS_MORE_BUF: Final = -2146881535 +OSS_NEGATIVE_UINTEGER: Final = -2146881534 +OSS_PDU_RANGE: Final = -2146881533 +OSS_MORE_INPUT: Final = -2146881532 +OSS_DATA_ERROR: Final = -2146881531 +OSS_BAD_ARG: Final = -2146881530 +OSS_BAD_VERSION: Final = -2146881529 +OSS_OUT_MEMORY: Final = -2146881528 +OSS_PDU_MISMATCH: Final = -2146881527 +OSS_LIMITED: Final = -2146881526 +OSS_BAD_PTR: Final = -2146881525 +OSS_BAD_TIME: Final = -2146881524 +OSS_INDEFINITE_NOT_SUPPORTED: Final = -2146881523 +OSS_MEM_ERROR: Final = -2146881522 +OSS_BAD_TABLE: Final = -2146881521 +OSS_TOO_LONG: Final = -2146881520 +OSS_CONSTRAINT_VIOLATED: Final = -2146881519 +OSS_FATAL_ERROR: Final = -2146881518 +OSS_ACCESS_SERIALIZATION_ERROR: Final = -2146881517 +OSS_NULL_TBL: Final = -2146881516 +OSS_NULL_FCN: Final = -2146881515 +OSS_BAD_ENCRULES: Final = -2146881514 +OSS_UNAVAIL_ENCRULES: Final = -2146881513 +OSS_CANT_OPEN_TRACE_WINDOW: Final = -2146881512 +OSS_UNIMPLEMENTED: Final = -2146881511 +OSS_OID_DLL_NOT_LINKED: Final = -2146881510 +OSS_CANT_OPEN_TRACE_FILE: Final = -2146881509 +OSS_TRACE_FILE_ALREADY_OPEN: Final = -2146881508 +OSS_TABLE_MISMATCH: Final = -2146881507 +OSS_TYPE_NOT_SUPPORTED: Final = -2146881506 +OSS_REAL_DLL_NOT_LINKED: Final = -2146881505 +OSS_REAL_CODE_NOT_LINKED: Final = -2146881504 +OSS_OUT_OF_RANGE: Final = -2146881503 +OSS_COPIER_DLL_NOT_LINKED: Final = -2146881502 +OSS_CONSTRAINT_DLL_NOT_LINKED: Final = -2146881501 +OSS_COMPARATOR_DLL_NOT_LINKED: Final = -2146881500 +OSS_COMPARATOR_CODE_NOT_LINKED: Final = -2146881499 +OSS_MEM_MGR_DLL_NOT_LINKED: Final = -2146881498 +OSS_PDV_DLL_NOT_LINKED: Final = -2146881497 +OSS_PDV_CODE_NOT_LINKED: Final = -2146881496 +OSS_API_DLL_NOT_LINKED: Final = -2146881495 +OSS_BERDER_DLL_NOT_LINKED: Final = -2146881494 +OSS_PER_DLL_NOT_LINKED: Final = -2146881493 +OSS_OPEN_TYPE_ERROR: Final = -2146881492 +OSS_MUTEX_NOT_CREATED: Final = -2146881491 +OSS_CANT_CLOSE_TRACE_FILE: Final = -2146881490 +CRYPT_E_ASN1_ERROR: Final = -2146881280 +CRYPT_E_ASN1_INTERNAL: Final = -2146881279 +CRYPT_E_ASN1_EOD: Final = -2146881278 +CRYPT_E_ASN1_CORRUPT: Final = -2146881277 +CRYPT_E_ASN1_LARGE: Final = -2146881276 +CRYPT_E_ASN1_CONSTRAINT: Final = -2146881275 +CRYPT_E_ASN1_MEMORY: Final = -2146881274 +CRYPT_E_ASN1_OVERFLOW: Final = -2146881273 +CRYPT_E_ASN1_BADPDU: Final = -2146881272 +CRYPT_E_ASN1_BADARGS: Final = -2146881271 +CRYPT_E_ASN1_BADREAL: Final = -2146881270 +CRYPT_E_ASN1_BADTAG: Final = -2146881269 +CRYPT_E_ASN1_CHOICE: Final = -2146881268 +CRYPT_E_ASN1_RULE: Final = -2146881267 +CRYPT_E_ASN1_UTF8: Final = -2146881266 +CRYPT_E_ASN1_PDU_TYPE: Final = -2146881229 +CRYPT_E_ASN1_NYI: Final = -2146881228 +CRYPT_E_ASN1_EXTENDED: Final = -2146881023 +CRYPT_E_ASN1_NOEOD: Final = -2146881022 +CERTSRV_E_BAD_REQUESTSUBJECT: Final = -2146877439 +CERTSRV_E_NO_REQUEST: Final = -2146877438 +CERTSRV_E_BAD_REQUESTSTATUS: Final = -2146877437 +CERTSRV_E_PROPERTY_EMPTY: Final = -2146877436 +CERTSRV_E_INVALID_CA_CERTIFICATE: Final = -2146877435 +CERTSRV_E_SERVER_SUSPENDED: Final = -2146877434 +CERTSRV_E_ENCODING_LENGTH: Final = -2146877433 +CERTSRV_E_ROLECONFLICT: Final = -2146877432 +CERTSRV_E_RESTRICTEDOFFICER: Final = -2146877431 +CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED: Final = -2146877430 +CERTSRV_E_NO_VALID_KRA: Final = -2146877429 +CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL: Final = -2146877428 +CERTSRV_E_NO_CAADMIN_DEFINED: Final = -2146877427 +CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE: Final = -2146877426 +CERTSRV_E_NO_DB_SESSIONS: Final = -2146877425 +CERTSRV_E_ALIGNMENT_FAULT: Final = -2146877424 +CERTSRV_E_ENROLL_DENIED: Final = -2146877423 +CERTSRV_E_TEMPLATE_DENIED: Final = -2146877422 +CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE: Final = -2146877421 +CERTSRV_E_ADMIN_DENIED_REQUEST: Final = -2146877420 +CERTSRV_E_NO_POLICY_SERVER: Final = -2146877419 +CERTSRV_E_WEAK_SIGNATURE_OR_KEY: Final = -2146877418 +CERTSRV_E_KEY_ATTESTATION_NOT_SUPPORTED: Final = -2146877417 +CERTSRV_E_ENCRYPTION_CERT_REQUIRED: Final = -2146877416 +CERTSRV_E_UNSUPPORTED_CERT_TYPE: Final = -2146875392 +CERTSRV_E_NO_CERT_TYPE: Final = -2146875391 +CERTSRV_E_TEMPLATE_CONFLICT: Final = -2146875390 +CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED: Final = -2146875389 +CERTSRV_E_ARCHIVED_KEY_REQUIRED: Final = -2146875388 +CERTSRV_E_SMIME_REQUIRED: Final = -2146875387 +CERTSRV_E_BAD_RENEWAL_SUBJECT: Final = -2146875386 +CERTSRV_E_BAD_TEMPLATE_VERSION: Final = -2146875385 +CERTSRV_E_TEMPLATE_POLICY_REQUIRED: Final = -2146875384 +CERTSRV_E_SIGNATURE_POLICY_REQUIRED: Final = -2146875383 +CERTSRV_E_SIGNATURE_COUNT: Final = -2146875382 +CERTSRV_E_SIGNATURE_REJECTED: Final = -2146875381 +CERTSRV_E_ISSUANCE_POLICY_REQUIRED: Final = -2146875380 +CERTSRV_E_SUBJECT_UPN_REQUIRED: Final = -2146875379 +CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED: Final = -2146875378 +CERTSRV_E_SUBJECT_DNS_REQUIRED: Final = -2146875377 +CERTSRV_E_ARCHIVED_KEY_UNEXPECTED: Final = -2146875376 +CERTSRV_E_KEY_LENGTH: Final = -2146875375 +CERTSRV_E_SUBJECT_EMAIL_REQUIRED: Final = -2146875374 +CERTSRV_E_UNKNOWN_CERT_TYPE: Final = -2146875373 +CERTSRV_E_CERT_TYPE_OVERLAP: Final = -2146875372 +CERTSRV_E_TOO_MANY_SIGNATURES: Final = -2146875371 +CERTSRV_E_RENEWAL_BAD_PUBLIC_KEY: Final = -2146875370 +CERTSRV_E_INVALID_EK: Final = -2146875369 +CERTSRV_E_INVALID_IDBINDING: Final = -2146875368 +CERTSRV_E_INVALID_ATTESTATION: Final = -2146875367 +CERTSRV_E_KEY_ATTESTATION: Final = -2146875366 +CERTSRV_E_CORRUPT_KEY_ATTESTATION: Final = -2146875365 +CERTSRV_E_EXPIRED_CHALLENGE: Final = -2146875364 +CERTSRV_E_INVALID_RESPONSE: Final = -2146875363 +CERTSRV_E_INVALID_REQUESTID: Final = -2146875362 +CERTSRV_E_REQUEST_PRECERTIFICATE_MISMATCH: Final = -2146875361 +CERTSRV_E_PENDING_CLIENT_RESPONSE: Final = -2146875360 +CERTSRV_E_SEC_EXT_DIRECTORY_SID_REQUIRED: Final = -2146875359 +XENROLL_E_KEY_NOT_EXPORTABLE: Final = -2146873344 +XENROLL_E_CANNOT_ADD_ROOT_CERT: Final = -2146873343 +XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND: Final = -2146873342 +XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH: Final = -2146873341 +XENROLL_E_RESPONSE_KA_HASH_MISMATCH: Final = -2146873340 +XENROLL_E_KEYSPEC_SMIME_MISMATCH: Final = -2146873339 +TRUST_E_SYSTEM_ERROR: Final = -2146869247 +TRUST_E_NO_SIGNER_CERT: Final = -2146869246 +TRUST_E_COUNTER_SIGNER: Final = -2146869245 +TRUST_E_CERT_SIGNATURE: Final = -2146869244 +TRUST_E_TIME_STAMP: Final = -2146869243 +TRUST_E_BAD_DIGEST: Final = -2146869232 +TRUST_E_MALFORMED_SIGNATURE: Final = -2146869231 +TRUST_E_BASIC_CONSTRAINTS: Final = -2146869223 +TRUST_E_FINANCIAL_CRITERIA: Final = -2146869218 +MSSIPOTF_E_OUTOFMEMRANGE: Final = -2146865151 +MSSIPOTF_E_CANTGETOBJECT: Final = -2146865150 +MSSIPOTF_E_NOHEADTABLE: Final = -2146865149 +MSSIPOTF_E_BAD_MAGICNUMBER: Final = -2146865148 +MSSIPOTF_E_BAD_OFFSET_TABLE: Final = -2146865147 +MSSIPOTF_E_TABLE_TAGORDER: Final = -2146865146 +MSSIPOTF_E_TABLE_LONGWORD: Final = -2146865145 +MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT: Final = -2146865144 +MSSIPOTF_E_TABLES_OVERLAP: Final = -2146865143 +MSSIPOTF_E_TABLE_PADBYTES: Final = -2146865142 +MSSIPOTF_E_FILETOOSMALL: Final = -2146865141 +MSSIPOTF_E_TABLE_CHECKSUM: Final = -2146865140 +MSSIPOTF_E_FILE_CHECKSUM: Final = -2146865139 +MSSIPOTF_E_FAILED_POLICY: Final = -2146865136 +MSSIPOTF_E_FAILED_HINTS_CHECK: Final = -2146865135 +MSSIPOTF_E_NOT_OPENTYPE: Final = -2146865134 +MSSIPOTF_E_FILE: Final = -2146865133 +MSSIPOTF_E_CRYPT: Final = -2146865132 +MSSIPOTF_E_BADVERSION: Final = -2146865131 +MSSIPOTF_E_DSIG_STRUCTURE: Final = -2146865130 +MSSIPOTF_E_PCONST_CHECK: Final = -2146865129 +MSSIPOTF_E_STRUCTURE: Final = -2146865128 +ERROR_CRED_REQUIRES_CONFIRMATION: Final = -2146865127 +NTE_OP_OK: Final = 0 +TRUST_E_PROVIDER_UNKNOWN: Final = -2146762751 +TRUST_E_ACTION_UNKNOWN: Final = -2146762750 +TRUST_E_SUBJECT_FORM_UNKNOWN: Final = -2146762749 +TRUST_E_SUBJECT_NOT_TRUSTED: Final = -2146762748 +DIGSIG_E_ENCODE: Final = -2146762747 +DIGSIG_E_DECODE: Final = -2146762746 +DIGSIG_E_EXTENSIBILITY: Final = -2146762745 +DIGSIG_E_CRYPTO: Final = -2146762744 +PERSIST_E_SIZEDEFINITE: Final = -2146762743 +PERSIST_E_SIZEINDEFINITE: Final = -2146762742 +PERSIST_E_NOTSELFSIZING: Final = -2146762741 +TRUST_E_NOSIGNATURE: Final = -2146762496 +CERT_E_EXPIRED: Final = -2146762495 +CERT_E_VALIDITYPERIODNESTING: Final = -2146762494 +CERT_E_ROLE: Final = -2146762493 +CERT_E_PATHLENCONST: Final = -2146762492 +CERT_E_CRITICAL: Final = -2146762491 +CERT_E_PURPOSE: Final = -2146762490 +CERT_E_ISSUERCHAINING: Final = -2146762489 +CERT_E_MALFORMED: Final = -2146762488 +CERT_E_UNTRUSTEDROOT: Final = -2146762487 +CERT_E_CHAINING: Final = -2146762486 +TRUST_E_FAIL: Final = -2146762485 +CERT_E_REVOKED: Final = -2146762484 +CERT_E_UNTRUSTEDTESTROOT: Final = -2146762483 +CERT_E_REVOCATION_FAILURE: Final = -2146762482 +CERT_E_CN_NO_MATCH: Final = -2146762481 +CERT_E_WRONG_USAGE: Final = -2146762480 +TRUST_E_EXPLICIT_DISTRUST: Final = -2146762479 +CERT_E_UNTRUSTEDCA: Final = -2146762478 +CERT_E_INVALID_POLICY: Final = -2146762477 +CERT_E_INVALID_NAME: Final = -2146762476 + +def HRESULT_FROM_SETUPAPI(x): ... + +SPAPI_E_EXPECTED_SECTION_NAME: Final = -2146500608 +SPAPI_E_BAD_SECTION_NAME_LINE: Final = -2146500607 +SPAPI_E_SECTION_NAME_TOO_LONG: Final = -2146500606 +SPAPI_E_GENERAL_SYNTAX: Final = -2146500605 +SPAPI_E_WRONG_INF_STYLE: Final = -2146500352 +SPAPI_E_SECTION_NOT_FOUND: Final = -2146500351 +SPAPI_E_LINE_NOT_FOUND: Final = -2146500350 +SPAPI_E_NO_BACKUP: Final = -2146500349 +SPAPI_E_NO_ASSOCIATED_CLASS: Final = -2146500096 +SPAPI_E_CLASS_MISMATCH: Final = -2146500095 +SPAPI_E_DUPLICATE_FOUND: Final = -2146500094 +SPAPI_E_NO_DRIVER_SELECTED: Final = -2146500093 +SPAPI_E_KEY_DOES_NOT_EXIST: Final = -2146500092 +SPAPI_E_INVALID_DEVINST_NAME: Final = -2146500091 +SPAPI_E_INVALID_CLASS: Final = -2146500090 +SPAPI_E_DEVINST_ALREADY_EXISTS: Final = -2146500089 +SPAPI_E_DEVINFO_NOT_REGISTERED: Final = -2146500088 +SPAPI_E_INVALID_REG_PROPERTY: Final = -2146500087 +SPAPI_E_NO_INF: Final = -2146500086 +SPAPI_E_NO_SUCH_DEVINST: Final = -2146500085 +SPAPI_E_CANT_LOAD_CLASS_ICON: Final = -2146500084 +SPAPI_E_INVALID_CLASS_INSTALLER: Final = -2146500083 +SPAPI_E_DI_DO_DEFAULT: Final = -2146500082 +SPAPI_E_DI_NOFILECOPY: Final = -2146500081 +SPAPI_E_INVALID_HWPROFILE: Final = -2146500080 +SPAPI_E_NO_DEVICE_SELECTED: Final = -2146500079 +SPAPI_E_DEVINFO_LIST_LOCKED: Final = -2146500078 +SPAPI_E_DEVINFO_DATA_LOCKED: Final = -2146500077 +SPAPI_E_DI_BAD_PATH: Final = -2146500076 +SPAPI_E_NO_CLASSINSTALL_PARAMS: Final = -2146500075 +SPAPI_E_FILEQUEUE_LOCKED: Final = -2146500074 +SPAPI_E_BAD_SERVICE_INSTALLSECT: Final = -2146500073 +SPAPI_E_NO_CLASS_DRIVER_LIST: Final = -2146500072 +SPAPI_E_NO_ASSOCIATED_SERVICE: Final = -2146500071 +SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE: Final = -2146500070 +SPAPI_E_DEVICE_INTERFACE_ACTIVE: Final = -2146500069 +SPAPI_E_DEVICE_INTERFACE_REMOVED: Final = -2146500068 +SPAPI_E_BAD_INTERFACE_INSTALLSECT: Final = -2146500067 +SPAPI_E_NO_SUCH_INTERFACE_CLASS: Final = -2146500066 +SPAPI_E_INVALID_REFERENCE_STRING: Final = -2146500065 +SPAPI_E_INVALID_MACHINENAME: Final = -2146500064 +SPAPI_E_REMOTE_COMM_FAILURE: Final = -2146500063 +SPAPI_E_MACHINE_UNAVAILABLE: Final = -2146500062 +SPAPI_E_NO_CONFIGMGR_SERVICES: Final = -2146500061 +SPAPI_E_INVALID_PROPPAGE_PROVIDER: Final = -2146500060 +SPAPI_E_NO_SUCH_DEVICE_INTERFACE: Final = -2146500059 +SPAPI_E_DI_POSTPROCESSING_REQUIRED: Final = -2146500058 +SPAPI_E_INVALID_COINSTALLER: Final = -2146500057 +SPAPI_E_NO_COMPAT_DRIVERS: Final = -2146500056 +SPAPI_E_NO_DEVICE_ICON: Final = -2146500055 +SPAPI_E_INVALID_INF_LOGCONFIG: Final = -2146500054 +SPAPI_E_DI_DONT_INSTALL: Final = -2146500053 +SPAPI_E_INVALID_FILTER_DRIVER: Final = -2146500052 +SPAPI_E_NON_WINDOWS_NT_DRIVER: Final = -2146500051 +SPAPI_E_NON_WINDOWS_DRIVER: Final = -2146500050 +SPAPI_E_NO_CATALOG_FOR_OEM_INF: Final = -2146500049 +SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE: Final = -2146500048 +SPAPI_E_NOT_DISABLEABLE: Final = -2146500047 +SPAPI_E_CANT_REMOVE_DEVINST: Final = -2146500046 +SPAPI_E_INVALID_TARGET: Final = -2146500045 +SPAPI_E_DRIVER_NONNATIVE: Final = -2146500044 +SPAPI_E_IN_WOW64: Final = -2146500043 +SPAPI_E_SET_SYSTEM_RESTORE_POINT: Final = -2146500042 +SPAPI_E_INCORRECTLY_COPIED_INF: Final = -2146500041 +SPAPI_E_SCE_DISABLED: Final = -2146500040 +SPAPI_E_UNKNOWN_EXCEPTION: Final = -2146500039 +SPAPI_E_PNP_REGISTRY_ERROR: Final = -2146500038 +SPAPI_E_REMOTE_REQUEST_UNSUPPORTED: Final = -2146500037 +SPAPI_E_NOT_AN_INSTALLED_OEM_INF: Final = -2146500036 +SPAPI_E_INF_IN_USE_BY_DEVICES: Final = -2146500035 +SPAPI_E_DI_FUNCTION_OBSOLETE: Final = -2146500034 +SPAPI_E_NO_AUTHENTICODE_CATALOG: Final = -2146500033 +SPAPI_E_AUTHENTICODE_DISALLOWED: Final = -2146500032 +SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER: Final = -2146500031 +SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED: Final = -2146500030 +SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED: Final = -2146500029 +SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH: Final = -2146500028 +SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE: Final = -2146500027 +SPAPI_E_DEVICE_INSTALLER_NOT_READY: Final = -2146500026 +SPAPI_E_DRIVER_STORE_ADD_FAILED: Final = -2146500025 +SPAPI_E_DEVICE_INSTALL_BLOCKED: Final = -2146500024 +SPAPI_E_DRIVER_INSTALL_BLOCKED: Final = -2146500023 +SPAPI_E_WRONG_INF_TYPE: Final = -2146500022 +SPAPI_E_FILE_HASH_NOT_IN_CATALOG: Final = -2146500021 +SPAPI_E_DRIVER_STORE_DELETE_FAILED: Final = -2146500020 +SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW: Final = -2146499840 +SPAPI_E_ERROR_NOT_INSTALLED: Final = -2146496512 +SCARD_S_SUCCESS: Final = NO_ERROR +SCARD_F_INTERNAL_ERROR: Final = -2146435071 +SCARD_E_CANCELLED: Final = -2146435070 +SCARD_E_INVALID_HANDLE: Final = -2146435069 +SCARD_E_INVALID_PARAMETER: Final = -2146435068 +SCARD_E_INVALID_TARGET: Final = -2146435067 +SCARD_E_NO_MEMORY: Final = -2146435066 +SCARD_F_WAITED_TOO_LONG: Final = -2146435065 +SCARD_E_INSUFFICIENT_BUFFER: Final = -2146435064 +SCARD_E_UNKNOWN_READER: Final = -2146435063 +SCARD_E_TIMEOUT: Final = -2146435062 +SCARD_E_SHARING_VIOLATION: Final = -2146435061 +SCARD_E_NO_SMARTCARD: Final = -2146435060 +SCARD_E_UNKNOWN_CARD: Final = -2146435059 +SCARD_E_CANT_DISPOSE: Final = -2146435058 +SCARD_E_PROTO_MISMATCH: Final = -2146435057 +SCARD_E_NOT_READY: Final = -2146435056 +SCARD_E_INVALID_VALUE: Final = -2146435055 +SCARD_E_SYSTEM_CANCELLED: Final = -2146435054 +SCARD_F_COMM_ERROR: Final = -2146435053 +SCARD_F_UNKNOWN_ERROR: Final = -2146435052 +SCARD_E_INVALID_ATR: Final = -2146435051 +SCARD_E_NOT_TRANSACTED: Final = -2146435050 +SCARD_E_READER_UNAVAILABLE: Final = -2146435049 +SCARD_P_SHUTDOWN: Final = -2146435048 +SCARD_E_PCI_TOO_SMALL: Final = -2146435047 +SCARD_E_READER_UNSUPPORTED: Final = -2146435046 +SCARD_E_DUPLICATE_READER: Final = -2146435045 +SCARD_E_CARD_UNSUPPORTED: Final = -2146435044 +SCARD_E_NO_SERVICE: Final = -2146435043 +SCARD_E_SERVICE_STOPPED: Final = -2146435042 +SCARD_E_UNEXPECTED: Final = -2146435041 +SCARD_E_ICC_INSTALLATION: Final = -2146435040 +SCARD_E_ICC_CREATEORDER: Final = -2146435039 +SCARD_E_UNSUPPORTED_FEATURE: Final = -2146435038 +SCARD_E_DIR_NOT_FOUND: Final = -2146435037 +SCARD_E_FILE_NOT_FOUND: Final = -2146435036 +SCARD_E_NO_DIR: Final = -2146435035 +SCARD_E_NO_FILE: Final = -2146435034 +SCARD_E_NO_ACCESS: Final = -2146435033 +SCARD_E_WRITE_TOO_MANY: Final = -2146435032 +SCARD_E_BAD_SEEK: Final = -2146435031 +SCARD_E_INVALID_CHV: Final = -2146435030 +SCARD_E_UNKNOWN_RES_MNG: Final = -2146435029 +SCARD_E_NO_SUCH_CERTIFICATE: Final = -2146435028 +SCARD_E_CERTIFICATE_UNAVAILABLE: Final = -2146435027 +SCARD_E_NO_READERS_AVAILABLE: Final = -2146435026 +SCARD_E_COMM_DATA_LOST: Final = -2146435025 +SCARD_E_NO_KEY_CONTAINER: Final = -2146435024 +SCARD_E_SERVER_TOO_BUSY: Final = -2146435023 +SCARD_E_PIN_CACHE_EXPIRED: Final = -2146435022 +SCARD_E_NO_PIN_CACHE: Final = -2146435021 +SCARD_E_READ_ONLY_CARD: Final = -2146435020 +SCARD_W_UNSUPPORTED_CARD: Final = -2146434971 +SCARD_W_UNRESPONSIVE_CARD: Final = -2146434970 +SCARD_W_UNPOWERED_CARD: Final = -2146434969 +SCARD_W_RESET_CARD: Final = -2146434968 +SCARD_W_REMOVED_CARD: Final = -2146434967 +SCARD_W_SECURITY_VIOLATION: Final = -2146434966 +SCARD_W_WRONG_CHV: Final = -2146434965 +SCARD_W_CHV_BLOCKED: Final = -2146434964 +SCARD_W_EOF: Final = -2146434963 +SCARD_W_CANCELLED_BY_USER: Final = -2146434962 +SCARD_W_CARD_NOT_AUTHENTICATED: Final = -2146434961 +SCARD_W_CACHE_ITEM_NOT_FOUND: Final = -2146434960 +SCARD_W_CACHE_ITEM_STALE: Final = -2146434959 +SCARD_W_CACHE_ITEM_TOO_BIG: Final = -2146434958 +COMADMIN_E_OBJECTERRORS: Final = -2146368511 +COMADMIN_E_OBJECTINVALID: Final = -2146368510 +COMADMIN_E_KEYMISSING: Final = -2146368509 +COMADMIN_E_ALREADYINSTALLED: Final = -2146368508 +COMADMIN_E_APP_FILE_WRITEFAIL: Final = -2146368505 +COMADMIN_E_APP_FILE_READFAIL: Final = -2146368504 +COMADMIN_E_APP_FILE_VERSION: Final = -2146368503 +COMADMIN_E_BADPATH: Final = -2146368502 +COMADMIN_E_APPLICATIONEXISTS: Final = -2146368501 +COMADMIN_E_ROLEEXISTS: Final = -2146368500 +COMADMIN_E_CANTCOPYFILE: Final = -2146368499 +COMADMIN_E_NOUSER: Final = -2146368497 +COMADMIN_E_INVALIDUSERIDS: Final = -2146368496 +COMADMIN_E_NOREGISTRYCLSID: Final = -2146368495 +COMADMIN_E_BADREGISTRYPROGID: Final = -2146368494 +COMADMIN_E_AUTHENTICATIONLEVEL: Final = -2146368493 +COMADMIN_E_USERPASSWDNOTVALID: Final = -2146368492 +COMADMIN_E_CLSIDORIIDMISMATCH: Final = -2146368488 +COMADMIN_E_REMOTEINTERFACE: Final = -2146368487 +COMADMIN_E_DLLREGISTERSERVER: Final = -2146368486 +COMADMIN_E_NOSERVERSHARE: Final = -2146368485 +COMADMIN_E_DLLLOADFAILED: Final = -2146368483 +COMADMIN_E_BADREGISTRYLIBID: Final = -2146368482 +COMADMIN_E_APPDIRNOTFOUND: Final = -2146368481 +COMADMIN_E_REGISTRARFAILED: Final = -2146368477 +COMADMIN_E_COMPFILE_DOESNOTEXIST: Final = -2146368476 +COMADMIN_E_COMPFILE_LOADDLLFAIL: Final = -2146368475 +COMADMIN_E_COMPFILE_GETCLASSOBJ: Final = -2146368474 +COMADMIN_E_COMPFILE_CLASSNOTAVAIL: Final = -2146368473 +COMADMIN_E_COMPFILE_BADTLB: Final = -2146368472 +COMADMIN_E_COMPFILE_NOTINSTALLABLE: Final = -2146368471 +COMADMIN_E_NOTCHANGEABLE: Final = -2146368470 +COMADMIN_E_NOTDELETEABLE: Final = -2146368469 +COMADMIN_E_SESSION: Final = -2146368468 +COMADMIN_E_COMP_MOVE_LOCKED: Final = -2146368467 +COMADMIN_E_COMP_MOVE_BAD_DEST: Final = -2146368466 +COMADMIN_E_REGISTERTLB: Final = -2146368464 +COMADMIN_E_SYSTEMAPP: Final = -2146368461 +COMADMIN_E_COMPFILE_NOREGISTRAR: Final = -2146368460 +COMADMIN_E_COREQCOMPINSTALLED: Final = -2146368459 +COMADMIN_E_SERVICENOTINSTALLED: Final = -2146368458 +COMADMIN_E_PROPERTYSAVEFAILED: Final = -2146368457 +COMADMIN_E_OBJECTEXISTS: Final = -2146368456 +COMADMIN_E_COMPONENTEXISTS: Final = -2146368455 +COMADMIN_E_REGFILE_CORRUPT: Final = -2146368453 +COMADMIN_E_PROPERTY_OVERFLOW: Final = -2146368452 +COMADMIN_E_NOTINREGISTRY: Final = -2146368450 +COMADMIN_E_OBJECTNOTPOOLABLE: Final = -2146368449 +COMADMIN_E_APPLID_MATCHES_CLSID: Final = -2146368442 +COMADMIN_E_ROLE_DOES_NOT_EXIST: Final = -2146368441 +COMADMIN_E_START_APP_NEEDS_COMPONENTS: Final = -2146368440 +COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM: Final = -2146368439 +COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY: Final = -2146368438 +COMADMIN_E_CAN_NOT_START_APP: Final = -2146368437 +COMADMIN_E_CAN_NOT_EXPORT_SYS_APP: Final = -2146368436 +COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT: Final = -2146368435 +COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER: Final = -2146368434 +COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE: Final = -2146368433 +COMADMIN_E_BASE_PARTITION_ONLY: Final = -2146368432 +COMADMIN_E_START_APP_DISABLED: Final = -2146368431 +COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME: Final = -2146368425 +COMADMIN_E_CAT_INVALID_PARTITION_NAME: Final = -2146368424 +COMADMIN_E_CAT_PARTITION_IN_USE: Final = -2146368423 +COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES: Final = -2146368422 +COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED: Final = -2146368421 +COMADMIN_E_AMBIGUOUS_APPLICATION_NAME: Final = -2146368420 +COMADMIN_E_AMBIGUOUS_PARTITION_NAME: Final = -2146368419 +COMADMIN_E_REGDB_NOTINITIALIZED: Final = -2146368398 +COMADMIN_E_REGDB_NOTOPEN: Final = -2146368397 +COMADMIN_E_REGDB_SYSTEMERR: Final = -2146368396 +COMADMIN_E_REGDB_ALREADYRUNNING: Final = -2146368395 +COMADMIN_E_MIG_VERSIONNOTSUPPORTED: Final = -2146368384 +COMADMIN_E_MIG_SCHEMANOTFOUND: Final = -2146368383 +COMADMIN_E_CAT_BITNESSMISMATCH: Final = -2146368382 +COMADMIN_E_CAT_UNACCEPTABLEBITNESS: Final = -2146368381 +COMADMIN_E_CAT_WRONGAPPBITNESS: Final = -2146368380 +COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED: Final = -2146368379 +COMADMIN_E_CAT_SERVERFAULT: Final = -2146368378 +COMQC_E_APPLICATION_NOT_QUEUED: Final = -2146368000 +COMQC_E_NO_QUEUEABLE_INTERFACES: Final = -2146367999 +COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE: Final = -2146367998 +COMQC_E_NO_IPERSISTSTREAM: Final = -2146367997 +COMQC_E_BAD_MESSAGE: Final = -2146367996 +COMQC_E_UNAUTHENTICATED: Final = -2146367995 +COMQC_E_UNTRUSTED_ENQUEUER: Final = -2146367994 +MSDTC_E_DUPLICATE_RESOURCE: Final = -2146367743 +COMADMIN_E_OBJECT_PARENT_MISSING: Final = -2146367480 +COMADMIN_E_OBJECT_DOES_NOT_EXIST: Final = -2146367479 +COMADMIN_E_APP_NOT_RUNNING: Final = -2146367478 +COMADMIN_E_INVALID_PARTITION: Final = -2146367477 +COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE: Final = -2146367475 +COMADMIN_E_USER_IN_SET: Final = -2146367474 +COMADMIN_E_CANTRECYCLELIBRARYAPPS: Final = -2146367473 +COMADMIN_E_CANTRECYCLESERVICEAPPS: Final = -2146367471 +COMADMIN_E_PROCESSALREADYRECYCLED: Final = -2146367470 +COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED: Final = -2146367469 +COMADMIN_E_CANTMAKEINPROCSERVICE: Final = -2146367468 +COMADMIN_E_PROGIDINUSEBYCLSID: Final = -2146367467 +COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET: Final = -2146367466 +COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED: Final = -2146367465 +COMADMIN_E_PARTITION_ACCESSDENIED: Final = -2146367464 +COMADMIN_E_PARTITION_MSI_ONLY: Final = -2146367463 +COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT: Final = -2146367462 +COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS: Final = -2146367461 +COMADMIN_E_COMP_MOVE_SOURCE: Final = -2146367460 +COMADMIN_E_COMP_MOVE_DEST: Final = -2146367459 +COMADMIN_E_COMP_MOVE_PRIVATE: Final = -2146367458 +COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET: Final = -2146367457 +COMADMIN_E_CANNOT_ALIAS_EVENTCLASS: Final = -2146367456 +COMADMIN_E_PRIVATE_ACCESSDENIED: Final = -2146367455 +COMADMIN_E_SAFERINVALID: Final = -2146367454 +COMADMIN_E_REGISTRY_ACCESSDENIED: Final = -2146367453 +COMADMIN_E_PARTITIONS_DISABLED: Final = -2146367452 +MENROLL_E_DEVICE_MESSAGE_FORMAT_ERROR: Final = -2145910783 +MENROLL_E_DEVICE_AUTHENTICATION_ERROR: Final = -2145910782 +MENROLL_E_DEVICE_AUTHORIZATION_ERROR: Final = -2145910781 +MENROLL_E_DEVICE_CERTIFICATEREQUEST_ERROR: Final = -2145910780 +MENROLL_E_DEVICE_CONFIGMGRSERVER_ERROR: Final = -2145910779 +MENROLL_E_DEVICE_INTERNALSERVICE_ERROR: Final = -2145910778 +MENROLL_E_DEVICE_INVALIDSECURITY_ERROR: Final = -2145910777 +MENROLL_E_DEVICE_UNKNOWN_ERROR: Final = -2145910776 +MENROLL_E_ENROLLMENT_IN_PROGRESS: Final = -2145910775 +MENROLL_E_DEVICE_ALREADY_ENROLLED: Final = -2145910774 +MENROLL_E_DISCOVERY_SEC_CERT_DATE_INVALID: Final = -2145910771 +MENROLL_E_PASSWORD_NEEDED: Final = -2145910770 +MENROLL_E_WAB_ERROR: Final = -2145910769 +MENROLL_E_CONNECTIVITY: Final = -2145910768 +MENROLL_S_ENROLLMENT_SUSPENDED: Final = 0x00180011 +MENROLL_E_INVALIDSSLCERT: Final = -2145910766 +MENROLL_E_DEVICECAPREACHED: Final = -2145910765 +MENROLL_E_DEVICENOTSUPPORTED: Final = -2145910764 +MENROLL_E_NOT_SUPPORTED: Final = -2145910763 +MENROLL_E_NOTELIGIBLETORENEW: Final = -2145910762 +MENROLL_E_INMAINTENANCE: Final = -2145910761 +MENROLL_E_USER_LICENSE: Final = -2145910760 +MENROLL_E_ENROLLMENTDATAINVALID: Final = -2145910759 +MENROLL_E_INSECUREREDIRECT: Final = -2145910758 +MENROLL_E_PLATFORM_WRONG_STATE: Final = -2145910757 +MENROLL_E_PLATFORM_LICENSE_ERROR: Final = -2145910756 +MENROLL_E_PLATFORM_UNKNOWN_ERROR: Final = -2145910755 +MENROLL_E_PROV_CSP_CERTSTORE: Final = -2145910754 +MENROLL_E_PROV_CSP_W7: Final = -2145910753 +MENROLL_E_PROV_CSP_DMCLIENT: Final = -2145910752 +MENROLL_E_PROV_CSP_PFW: Final = -2145910751 +MENROLL_E_PROV_CSP_MISC: Final = -2145910750 +MENROLL_E_PROV_UNKNOWN: Final = -2145910749 +MENROLL_E_PROV_SSLCERTNOTFOUND: Final = -2145910748 +MENROLL_E_PROV_CSP_APPMGMT: Final = -2145910747 +MENROLL_E_DEVICE_MANAGEMENT_BLOCKED: Final = -2145910746 +MENROLL_E_CERTPOLICY_PRIVATEKEYCREATION_FAILED: Final = -2145910745 +MENROLL_E_CERTAUTH_FAILED_TO_FIND_CERT: Final = -2145910744 +MENROLL_E_EMPTY_MESSAGE: Final = -2145910743 +MENROLL_E_USER_CANCELLED: Final = -2145910736 +MENROLL_E_MDM_NOT_CONFIGURED: Final = -2145910735 +MENROLL_E_CUSTOMSERVERERROR: Final = -2145910734 +WER_S_REPORT_DEBUG: Final = 0x001B0000 +WER_S_REPORT_UPLOADED: Final = 0x001B0001 +WER_S_REPORT_QUEUED: Final = 0x001B0002 +WER_S_DISABLED: Final = 0x001B0003 +WER_S_SUSPENDED_UPLOAD: Final = 0x001B0004 +WER_S_DISABLED_QUEUE: Final = 0x001B0005 +WER_S_DISABLED_ARCHIVE: Final = 0x001B0006 +WER_S_REPORT_ASYNC: Final = 0x001B0007 +WER_S_IGNORE_ASSERT_INSTANCE: Final = 0x001B0008 +WER_S_IGNORE_ALL_ASSERTS: Final = 0x001B0009 +WER_S_ASSERT_CONTINUE: Final = 0x001B000A +WER_S_THROTTLED: Final = 0x001B000B +WER_S_REPORT_UPLOADED_CAB: Final = 0x001B000C +WER_E_CRASH_FAILURE: Final = -2145681408 +WER_E_CANCELED: Final = -2145681407 +WER_E_NETWORK_FAILURE: Final = -2145681406 +WER_E_NOT_INITIALIZED: Final = -2145681405 +WER_E_ALREADY_REPORTING: Final = -2145681404 +WER_E_DUMP_THROTTLED: Final = -2145681403 +WER_E_INSUFFICIENT_CONSENT: Final = -2145681402 +WER_E_TOO_HEAVY: Final = -2145681401 + +def FILTER_HRESULT_FROM_FLT_NTSTATUS(x: int) -> int: ... + +ERROR_FLT_IO_COMPLETE: Final = 0x001F0001 +ERROR_FLT_NO_HANDLER_DEFINED: Final = -2145452031 +ERROR_FLT_CONTEXT_ALREADY_DEFINED: Final = -2145452030 +ERROR_FLT_INVALID_ASYNCHRONOUS_REQUEST: Final = -2145452029 +ERROR_FLT_DISALLOW_FAST_IO: Final = -2145452028 +ERROR_FLT_INVALID_NAME_REQUEST: Final = -2145452027 +ERROR_FLT_NOT_SAFE_TO_POST_OPERATION: Final = -2145452026 +ERROR_FLT_NOT_INITIALIZED: Final = -2145452025 +ERROR_FLT_FILTER_NOT_READY: Final = -2145452024 +ERROR_FLT_POST_OPERATION_CLEANUP: Final = -2145452023 +ERROR_FLT_INTERNAL_ERROR: Final = -2145452022 +ERROR_FLT_DELETING_OBJECT: Final = -2145452021 +ERROR_FLT_MUST_BE_NONPAGED_POOL: Final = -2145452020 +ERROR_FLT_DUPLICATE_ENTRY: Final = -2145452019 +ERROR_FLT_CBDQ_DISABLED: Final = -2145452018 +ERROR_FLT_DO_NOT_ATTACH: Final = -2145452017 +ERROR_FLT_DO_NOT_DETACH: Final = -2145452016 +ERROR_FLT_INSTANCE_ALTITUDE_COLLISION: Final = -2145452015 +ERROR_FLT_INSTANCE_NAME_COLLISION: Final = -2145452014 +ERROR_FLT_FILTER_NOT_FOUND: Final = -2145452013 +ERROR_FLT_VOLUME_NOT_FOUND: Final = -2145452012 +ERROR_FLT_INSTANCE_NOT_FOUND: Final = -2145452011 +ERROR_FLT_CONTEXT_ALLOCATION_NOT_FOUND: Final = -2145452010 +ERROR_FLT_INVALID_CONTEXT_REGISTRATION: Final = -2145452009 +ERROR_FLT_NAME_CACHE_MISS: Final = -2145452008 +ERROR_FLT_NO_DEVICE_OBJECT: Final = -2145452007 +ERROR_FLT_VOLUME_ALREADY_MOUNTED: Final = -2145452006 +ERROR_FLT_ALREADY_ENLISTED: Final = -2145452005 +ERROR_FLT_CONTEXT_ALREADY_LINKED: Final = -2145452004 +ERROR_FLT_NO_WAITER_FOR_REPLY: Final = -2145452000 +ERROR_FLT_REGISTRATION_BUSY: Final = -2145451997 +ERROR_FLT_WCOS_NOT_SUPPORTED: Final = -2145451996 +ERROR_HUNG_DISPLAY_DRIVER_THREAD: Final = -2144993279 +DWM_E_COMPOSITIONDISABLED: Final = -2144980991 +DWM_E_REMOTING_NOT_SUPPORTED: Final = -2144980990 +DWM_E_NO_REDIRECTION_SURFACE_AVAILABLE: Final = -2144980989 +DWM_E_NOT_QUEUING_PRESENTS: Final = -2144980988 +DWM_E_ADAPTER_NOT_FOUND: Final = -2144980987 +DWM_S_GDI_REDIRECTION_SURFACE: Final = 0x00263005 +DWM_E_TEXTURE_TOO_LARGE: Final = -2144980985 +DWM_S_GDI_REDIRECTION_SURFACE_BLT_VIA_GDI: Final = 0x00263008 +ERROR_MONITOR_NO_DESCRIPTOR: Final = 0x00261001 +ERROR_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT: Final = 0x00261002 +ERROR_MONITOR_INVALID_DESCRIPTOR_CHECKSUM: Final = -1071247357 +ERROR_MONITOR_INVALID_STANDARD_TIMING_BLOCK: Final = -1071247356 +ERROR_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED: Final = -1071247355 +ERROR_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK: Final = -1071247354 +ERROR_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK: Final = -1071247353 +ERROR_MONITOR_NO_MORE_DESCRIPTOR_DATA: Final = -1071247352 +ERROR_MONITOR_INVALID_DETAILED_TIMING_BLOCK: Final = -1071247351 +ERROR_MONITOR_INVALID_MANUFACTURE_DATE: Final = -1071247350 +ERROR_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER: Final = -1071243264 +ERROR_GRAPHICS_INSUFFICIENT_DMA_BUFFER: Final = -1071243263 +ERROR_GRAPHICS_INVALID_DISPLAY_ADAPTER: Final = -1071243262 +ERROR_GRAPHICS_ADAPTER_WAS_RESET: Final = -1071243261 +ERROR_GRAPHICS_INVALID_DRIVER_MODEL: Final = -1071243260 +ERROR_GRAPHICS_PRESENT_MODE_CHANGED: Final = -1071243259 +ERROR_GRAPHICS_PRESENT_OCCLUDED: Final = -1071243258 +ERROR_GRAPHICS_PRESENT_DENIED: Final = -1071243257 +ERROR_GRAPHICS_CANNOTCOLORCONVERT: Final = -1071243256 +ERROR_GRAPHICS_DRIVER_MISMATCH: Final = -1071243255 +ERROR_GRAPHICS_PARTIAL_DATA_POPULATED: Final = 0x4026200A +ERROR_GRAPHICS_PRESENT_REDIRECTION_DISABLED: Final = -1071243253 +ERROR_GRAPHICS_PRESENT_UNOCCLUDED: Final = -1071243252 +ERROR_GRAPHICS_WINDOWDC_NOT_AVAILABLE: Final = -1071243251 +ERROR_GRAPHICS_WINDOWLESS_PRESENT_DISABLED: Final = -1071243250 +ERROR_GRAPHICS_PRESENT_INVALID_WINDOW: Final = -1071243249 +ERROR_GRAPHICS_PRESENT_BUFFER_NOT_BOUND: Final = -1071243248 +ERROR_GRAPHICS_VAIL_STATE_CHANGED: Final = -1071243247 +ERROR_GRAPHICS_INDIRECT_DISPLAY_ABANDON_SWAPCHAIN: Final = -1071243246 +ERROR_GRAPHICS_INDIRECT_DISPLAY_DEVICE_STOPPED: Final = -1071243245 +ERROR_GRAPHICS_VAIL_FAILED_TO_SEND_CREATE_SUPERWETINK_MESSAGE: Final = -1071243244 +ERROR_GRAPHICS_VAIL_FAILED_TO_SEND_DESTROY_SUPERWETINK_MESSAGE: Final = -1071243243 +ERROR_GRAPHICS_VAIL_FAILED_TO_SEND_COMPOSITION_WINDOW_DPI_MESSAGE: Final = -1071243242 +ERROR_GRAPHICS_LINK_CONFIGURATION_IN_PROGRESS: Final = -1071243241 +ERROR_GRAPHICS_MPO_ALLOCATION_UNPINNED: Final = -1071243240 +ERROR_GRAPHICS_NO_VIDEO_MEMORY: Final = -1071243008 +ERROR_GRAPHICS_CANT_LOCK_MEMORY: Final = -1071243007 +ERROR_GRAPHICS_ALLOCATION_BUSY: Final = -1071243006 +ERROR_GRAPHICS_TOO_MANY_REFERENCES: Final = -1071243005 +ERROR_GRAPHICS_TRY_AGAIN_LATER: Final = -1071243004 +ERROR_GRAPHICS_TRY_AGAIN_NOW: Final = -1071243003 +ERROR_GRAPHICS_ALLOCATION_INVALID: Final = -1071243002 +ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE: Final = -1071243001 +ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED: Final = -1071243000 +ERROR_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION: Final = -1071242999 +ERROR_GRAPHICS_INVALID_ALLOCATION_USAGE: Final = -1071242992 +ERROR_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION: Final = -1071242991 +ERROR_GRAPHICS_ALLOCATION_CLOSED: Final = -1071242990 +ERROR_GRAPHICS_INVALID_ALLOCATION_INSTANCE: Final = -1071242989 +ERROR_GRAPHICS_INVALID_ALLOCATION_HANDLE: Final = -1071242988 +ERROR_GRAPHICS_WRONG_ALLOCATION_DEVICE: Final = -1071242987 +ERROR_GRAPHICS_ALLOCATION_CONTENT_LOST: Final = -1071242986 +ERROR_GRAPHICS_GPU_EXCEPTION_ON_DEVICE: Final = -1071242752 +ERROR_GRAPHICS_SKIP_ALLOCATION_PREPARATION: Final = 0x40262201 +ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY: Final = -1071242496 +ERROR_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED: Final = -1071242495 +ERROR_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED: Final = -1071242494 +ERROR_GRAPHICS_INVALID_VIDPN: Final = -1071242493 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE: Final = -1071242492 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET: Final = -1071242491 +ERROR_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED: Final = -1071242490 +ERROR_GRAPHICS_MODE_NOT_PINNED: Final = 0x00262307 +ERROR_GRAPHICS_INVALID_VIDPN_SOURCEMODESET: Final = -1071242488 +ERROR_GRAPHICS_INVALID_VIDPN_TARGETMODESET: Final = -1071242487 +ERROR_GRAPHICS_INVALID_FREQUENCY: Final = -1071242486 +ERROR_GRAPHICS_INVALID_ACTIVE_REGION: Final = -1071242485 +ERROR_GRAPHICS_INVALID_TOTAL_REGION: Final = -1071242484 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE: Final = -1071242480 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE: Final = -1071242479 +ERROR_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET: Final = -1071242478 +ERROR_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY: Final = -1071242477 +ERROR_GRAPHICS_MODE_ALREADY_IN_MODESET: Final = -1071242476 +ERROR_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET: Final = -1071242475 +ERROR_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET: Final = -1071242474 +ERROR_GRAPHICS_SOURCE_ALREADY_IN_SET: Final = -1071242473 +ERROR_GRAPHICS_TARGET_ALREADY_IN_SET: Final = -1071242472 +ERROR_GRAPHICS_INVALID_VIDPN_PRESENT_PATH: Final = -1071242471 +ERROR_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY: Final = -1071242470 +ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET: Final = -1071242469 +ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE: Final = -1071242468 +ERROR_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET: Final = -1071242467 +ERROR_GRAPHICS_NO_PREFERRED_MODE: Final = 0x0026231E +ERROR_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET: Final = -1071242465 +ERROR_GRAPHICS_STALE_MODESET: Final = -1071242464 +ERROR_GRAPHICS_INVALID_MONITOR_SOURCEMODESET: Final = -1071242463 +ERROR_GRAPHICS_INVALID_MONITOR_SOURCE_MODE: Final = -1071242462 +ERROR_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN: Final = -1071242461 +ERROR_GRAPHICS_MODE_ID_MUST_BE_UNIQUE: Final = -1071242460 +ERROR_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION: Final = -1071242459 +ERROR_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES: Final = -1071242458 +ERROR_GRAPHICS_PATH_NOT_IN_TOPOLOGY: Final = -1071242457 +ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE: Final = -1071242456 +ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET: Final = -1071242455 +ERROR_GRAPHICS_INVALID_MONITORDESCRIPTORSET: Final = -1071242454 +ERROR_GRAPHICS_INVALID_MONITORDESCRIPTOR: Final = -1071242453 +ERROR_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET: Final = -1071242452 +ERROR_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET: Final = -1071242451 +ERROR_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE: Final = -1071242450 +ERROR_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE: Final = -1071242449 +ERROR_GRAPHICS_RESOURCES_NOT_RELATED: Final = -1071242448 +ERROR_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE: Final = -1071242447 +ERROR_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE: Final = -1071242446 +ERROR_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET: Final = -1071242445 +ERROR_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER: Final = -1071242444 +ERROR_GRAPHICS_NO_VIDPNMGR: Final = -1071242443 +ERROR_GRAPHICS_NO_ACTIVE_VIDPN: Final = -1071242442 +ERROR_GRAPHICS_STALE_VIDPN_TOPOLOGY: Final = -1071242441 +ERROR_GRAPHICS_MONITOR_NOT_CONNECTED: Final = -1071242440 +ERROR_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY: Final = -1071242439 +ERROR_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE: Final = -1071242438 +ERROR_GRAPHICS_INVALID_VISIBLEREGION_SIZE: Final = -1071242437 +ERROR_GRAPHICS_INVALID_STRIDE: Final = -1071242436 +ERROR_GRAPHICS_INVALID_PIXELFORMAT: Final = -1071242435 +ERROR_GRAPHICS_INVALID_COLORBASIS: Final = -1071242434 +ERROR_GRAPHICS_INVALID_PIXELVALUEACCESSMODE: Final = -1071242433 +ERROR_GRAPHICS_TARGET_NOT_IN_TOPOLOGY: Final = -1071242432 +ERROR_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT: Final = -1071242431 +ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: Final = -1071242430 +ERROR_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN: Final = -1071242429 +ERROR_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL: Final = -1071242428 +ERROR_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION: Final = -1071242427 +ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED: Final = -1071242426 +ERROR_GRAPHICS_INVALID_GAMMA_RAMP: Final = -1071242425 +ERROR_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED: Final = -1071242424 +ERROR_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED: Final = -1071242423 +ERROR_GRAPHICS_MODE_NOT_IN_MODESET: Final = -1071242422 +ERROR_GRAPHICS_DATASET_IS_EMPTY: Final = 0x0026234B +ERROR_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET: Final = 0x0026234C +ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON: Final = -1071242419 +ERROR_GRAPHICS_INVALID_PATH_CONTENT_TYPE: Final = -1071242418 +ERROR_GRAPHICS_INVALID_COPYPROTECTION_TYPE: Final = -1071242417 +ERROR_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS: Final = -1071242416 +ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED: Final = 0x00262351 +ERROR_GRAPHICS_INVALID_SCANLINE_ORDERING: Final = -1071242414 +ERROR_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED: Final = -1071242413 +ERROR_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS: Final = -1071242412 +ERROR_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT: Final = -1071242411 +ERROR_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM: Final = -1071242410 +ERROR_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN: Final = -1071242409 +ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT: Final = -1071242408 +ERROR_GRAPHICS_MAX_NUM_PATHS_REACHED: Final = -1071242407 +ERROR_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION: Final = -1071242406 +ERROR_GRAPHICS_INVALID_CLIENT_TYPE: Final = -1071242405 +ERROR_GRAPHICS_CLIENTVIDPN_NOT_SET: Final = -1071242404 +ERROR_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED: Final = -1071242240 +ERROR_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED: Final = -1071242239 +ERROR_GRAPHICS_UNKNOWN_CHILD_STATUS: Final = 0x4026242F +ERROR_GRAPHICS_NOT_A_LINKED_ADAPTER: Final = -1071242192 +ERROR_GRAPHICS_LEADLINK_NOT_ENUMERATED: Final = -1071242191 +ERROR_GRAPHICS_CHAINLINKS_NOT_ENUMERATED: Final = -1071242190 +ERROR_GRAPHICS_ADAPTER_CHAIN_NOT_READY: Final = -1071242189 +ERROR_GRAPHICS_CHAINLINKS_NOT_STARTED: Final = -1071242188 +ERROR_GRAPHICS_CHAINLINKS_NOT_POWERED_ON: Final = -1071242187 +ERROR_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE: Final = -1071242186 +ERROR_GRAPHICS_LEADLINK_START_DEFERRED: Final = 0x40262437 +ERROR_GRAPHICS_NOT_POST_DEVICE_DRIVER: Final = -1071242184 +ERROR_GRAPHICS_POLLING_TOO_FREQUENTLY: Final = 0x40262439 +ERROR_GRAPHICS_START_DEFERRED: Final = 0x4026243A +ERROR_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED: Final = -1071242181 +ERROR_GRAPHICS_DEPENDABLE_CHILD_STATUS: Final = 0x4026243C +ERROR_GRAPHICS_OPM_NOT_SUPPORTED: Final = -1071241984 +ERROR_GRAPHICS_COPP_NOT_SUPPORTED: Final = -1071241983 +ERROR_GRAPHICS_UAB_NOT_SUPPORTED: Final = -1071241982 +ERROR_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS: Final = -1071241981 +ERROR_GRAPHICS_OPM_NO_VIDEO_OUTPUTS_EXIST: Final = -1071241979 +ERROR_GRAPHICS_OPM_INTERNAL_ERROR: Final = -1071241973 +ERROR_GRAPHICS_OPM_INVALID_HANDLE: Final = -1071241972 +ERROR_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH: Final = -1071241970 +ERROR_GRAPHICS_OPM_SPANNING_MODE_ENABLED: Final = -1071241969 +ERROR_GRAPHICS_OPM_THEATER_MODE_ENABLED: Final = -1071241968 +ERROR_GRAPHICS_PVP_HFS_FAILED: Final = -1071241967 +ERROR_GRAPHICS_OPM_INVALID_SRM: Final = -1071241966 +ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP: Final = -1071241965 +ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP: Final = -1071241964 +ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA: Final = -1071241963 +ERROR_GRAPHICS_OPM_HDCP_SRM_NEVER_SET: Final = -1071241962 +ERROR_GRAPHICS_OPM_RESOLUTION_TOO_HIGH: Final = -1071241961 +ERROR_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE: Final = -1071241960 +ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_NO_LONGER_EXISTS: Final = -1071241958 +ERROR_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS: Final = -1071241957 +ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS: Final = -1071241956 +ERROR_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST: Final = -1071241955 +ERROR_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR: Final = -1071241954 +ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS: Final = -1071241953 +ERROR_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED: Final = -1071241952 +ERROR_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST: Final = -1071241951 +ERROR_GRAPHICS_I2C_NOT_SUPPORTED: Final = -1071241856 +ERROR_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST: Final = -1071241855 +ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA: Final = -1071241854 +ERROR_GRAPHICS_I2C_ERROR_RECEIVING_DATA: Final = -1071241853 +ERROR_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED: Final = -1071241852 +ERROR_GRAPHICS_DDCCI_INVALID_DATA: Final = -1071241851 +ERROR_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE: Final = -1071241850 +ERROR_GRAPHICS_MCA_INVALID_CAPABILITIES_STRING: Final = -1071241849 +ERROR_GRAPHICS_MCA_INTERNAL_ERROR: Final = -1071241848 +ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND: Final = -1071241847 +ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH: Final = -1071241846 +ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM: Final = -1071241845 +ERROR_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE: Final = -1071241844 +ERROR_GRAPHICS_MONITOR_NO_LONGER_EXISTS: Final = -1071241843 +ERROR_GRAPHICS_DDCCI_CURRENT_CURRENT_VALUE_GREATER_THAN_MAXIMUM_VALUE: Final = -1071241768 +ERROR_GRAPHICS_MCA_INVALID_VCP_VERSION: Final = -1071241767 +ERROR_GRAPHICS_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: Final = -1071241766 +ERROR_GRAPHICS_MCA_MCCS_VERSION_MISMATCH: Final = -1071241765 +ERROR_GRAPHICS_MCA_UNSUPPORTED_MCCS_VERSION: Final = -1071241764 +ERROR_GRAPHICS_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: Final = -1071241762 +ERROR_GRAPHICS_MCA_UNSUPPORTED_COLOR_TEMPERATURE: Final = -1071241761 +ERROR_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED: Final = -1071241760 +ERROR_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME: Final = -1071241759 +ERROR_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP: Final = -1071241758 +ERROR_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED: Final = -1071241757 +ERROR_GRAPHICS_INVALID_POINTER: Final = -1071241756 +ERROR_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE: Final = -1071241755 +ERROR_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL: Final = -1071241754 +ERROR_GRAPHICS_INTERNAL_ERROR: Final = -1071241753 +ERROR_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS: Final = -1071249944 +NAP_E_INVALID_PACKET: Final = -2144927743 +NAP_E_MISSING_SOH: Final = -2144927742 +NAP_E_CONFLICTING_ID: Final = -2144927741 +NAP_E_NO_CACHED_SOH: Final = -2144927740 +NAP_E_STILL_BOUND: Final = -2144927739 +NAP_E_NOT_REGISTERED: Final = -2144927738 +NAP_E_NOT_INITIALIZED: Final = -2144927737 +NAP_E_MISMATCHED_ID: Final = -2144927736 +NAP_E_NOT_PENDING: Final = -2144927735 +NAP_E_ID_NOT_FOUND: Final = -2144927734 +NAP_E_MAXSIZE_TOO_SMALL: Final = -2144927733 +NAP_E_SERVICE_NOT_RUNNING: Final = -2144927732 +NAP_S_CERT_ALREADY_PRESENT: Final = 0x0027000D +NAP_E_ENTITY_DISABLED: Final = -2144927730 +NAP_E_NETSH_GROUPPOLICY_ERROR: Final = -2144927729 +NAP_E_TOO_MANY_CALLS: Final = -2144927728 +NAP_E_SHV_CONFIG_EXISTED: Final = -2144927727 +NAP_E_SHV_CONFIG_NOT_FOUND: Final = -2144927726 +NAP_E_SHV_TIMEOUT: Final = -2144927725 +TPM_E_ERROR_MASK: Final = -2144862208 +TPM_E_AUTHFAIL: Final = -2144862207 +TPM_E_BADINDEX: Final = -2144862206 +TPM_E_BAD_PARAMETER: Final = -2144862205 +TPM_E_AUDITFAILURE: Final = -2144862204 +TPM_E_CLEAR_DISABLED: Final = -2144862203 +TPM_E_DEACTIVATED: Final = -2144862202 +TPM_E_DISABLED: Final = -2144862201 +TPM_E_DISABLED_CMD: Final = -2144862200 +TPM_E_FAIL: Final = -2144862199 +TPM_E_BAD_ORDINAL: Final = -2144862198 +TPM_E_INSTALL_DISABLED: Final = -2144862197 +TPM_E_INVALID_KEYHANDLE: Final = -2144862196 +TPM_E_KEYNOTFOUND: Final = -2144862195 +TPM_E_INAPPROPRIATE_ENC: Final = -2144862194 +TPM_E_MIGRATEFAIL: Final = -2144862193 +TPM_E_INVALID_PCR_INFO: Final = -2144862192 +TPM_E_NOSPACE: Final = -2144862191 +TPM_E_NOSRK: Final = -2144862190 +TPM_E_NOTSEALED_BLOB: Final = -2144862189 +TPM_E_OWNER_SET: Final = -2144862188 +TPM_E_RESOURCES: Final = -2144862187 +TPM_E_SHORTRANDOM: Final = -2144862186 +TPM_E_SIZE: Final = -2144862185 +TPM_E_WRONGPCRVAL: Final = -2144862184 +TPM_E_BAD_PARAM_SIZE: Final = -2144862183 +TPM_E_SHA_THREAD: Final = -2144862182 +TPM_E_SHA_ERROR: Final = -2144862181 +TPM_E_FAILEDSELFTEST: Final = -2144862180 +TPM_E_AUTH2FAIL: Final = -2144862179 +TPM_E_BADTAG: Final = -2144862178 +TPM_E_IOERROR: Final = -2144862177 +TPM_E_ENCRYPT_ERROR: Final = -2144862176 +TPM_E_DECRYPT_ERROR: Final = -2144862175 +TPM_E_INVALID_AUTHHANDLE: Final = -2144862174 +TPM_E_NO_ENDORSEMENT: Final = -2144862173 +TPM_E_INVALID_KEYUSAGE: Final = -2144862172 +TPM_E_WRONG_ENTITYTYPE: Final = -2144862171 +TPM_E_INVALID_POSTINIT: Final = -2144862170 +TPM_E_INAPPROPRIATE_SIG: Final = -2144862169 +TPM_E_BAD_KEY_PROPERTY: Final = -2144862168 +TPM_E_BAD_MIGRATION: Final = -2144862167 +TPM_E_BAD_SCHEME: Final = -2144862166 +TPM_E_BAD_DATASIZE: Final = -2144862165 +TPM_E_BAD_MODE: Final = -2144862164 +TPM_E_BAD_PRESENCE: Final = -2144862163 +TPM_E_BAD_VERSION: Final = -2144862162 +TPM_E_NO_WRAP_TRANSPORT: Final = -2144862161 +TPM_E_AUDITFAIL_UNSUCCESSFUL: Final = -2144862160 +TPM_E_AUDITFAIL_SUCCESSFUL: Final = -2144862159 +TPM_E_NOTRESETABLE: Final = -2144862158 +TPM_E_NOTLOCAL: Final = -2144862157 +TPM_E_BAD_TYPE: Final = -2144862156 +TPM_E_INVALID_RESOURCE: Final = -2144862155 +TPM_E_NOTFIPS: Final = -2144862154 +TPM_E_INVALID_FAMILY: Final = -2144862153 +TPM_E_NO_NV_PERMISSION: Final = -2144862152 +TPM_E_REQUIRES_SIGN: Final = -2144862151 +TPM_E_KEY_NOTSUPPORTED: Final = -2144862150 +TPM_E_AUTH_CONFLICT: Final = -2144862149 +TPM_E_AREA_LOCKED: Final = -2144862148 +TPM_E_BAD_LOCALITY: Final = -2144862147 +TPM_E_READ_ONLY: Final = -2144862146 +TPM_E_PER_NOWRITE: Final = -2144862145 +TPM_E_FAMILYCOUNT: Final = -2144862144 +TPM_E_WRITE_LOCKED: Final = -2144862143 +TPM_E_BAD_ATTRIBUTES: Final = -2144862142 +TPM_E_INVALID_STRUCTURE: Final = -2144862141 +TPM_E_KEY_OWNER_CONTROL: Final = -2144862140 +TPM_E_BAD_COUNTER: Final = -2144862139 +TPM_E_NOT_FULLWRITE: Final = -2144862138 +TPM_E_CONTEXT_GAP: Final = -2144862137 +TPM_E_MAXNVWRITES: Final = -2144862136 +TPM_E_NOOPERATOR: Final = -2144862135 +TPM_E_RESOURCEMISSING: Final = -2144862134 +TPM_E_DELEGATE_LOCK: Final = -2144862133 +TPM_E_DELEGATE_FAMILY: Final = -2144862132 +TPM_E_DELEGATE_ADMIN: Final = -2144862131 +TPM_E_TRANSPORT_NOTEXCLUSIVE: Final = -2144862130 +TPM_E_OWNER_CONTROL: Final = -2144862129 +TPM_E_DAA_RESOURCES: Final = -2144862128 +TPM_E_DAA_INPUT_DATA0: Final = -2144862127 +TPM_E_DAA_INPUT_DATA1: Final = -2144862126 +TPM_E_DAA_ISSUER_SETTINGS: Final = -2144862125 +TPM_E_DAA_TPM_SETTINGS: Final = -2144862124 +TPM_E_DAA_STAGE: Final = -2144862123 +TPM_E_DAA_ISSUER_VALIDITY: Final = -2144862122 +TPM_E_DAA_WRONG_W: Final = -2144862121 +TPM_E_BAD_HANDLE: Final = -2144862120 +TPM_E_BAD_DELEGATE: Final = -2144862119 +TPM_E_BADCONTEXT: Final = -2144862118 +TPM_E_TOOMANYCONTEXTS: Final = -2144862117 +TPM_E_MA_TICKET_SIGNATURE: Final = -2144862116 +TPM_E_MA_DESTINATION: Final = -2144862115 +TPM_E_MA_SOURCE: Final = -2144862114 +TPM_E_MA_AUTHORITY: Final = -2144862113 +TPM_E_PERMANENTEK: Final = -2144862111 +TPM_E_BAD_SIGNATURE: Final = -2144862110 +TPM_E_NOCONTEXTSPACE: Final = -2144862109 +TPM_20_E_ASYMMETRIC: Final = -2144862079 +TPM_20_E_ATTRIBUTES: Final = -2144862078 +TPM_20_E_HASH: Final = -2144862077 +TPM_20_E_VALUE: Final = -2144862076 +TPM_20_E_HIERARCHY: Final = -2144862075 +TPM_20_E_KEY_SIZE: Final = -2144862073 +TPM_20_E_MGF: Final = -2144862072 +TPM_20_E_MODE: Final = -2144862071 +TPM_20_E_TYPE: Final = -2144862070 +TPM_20_E_HANDLE: Final = -2144862069 +TPM_20_E_KDF: Final = -2144862068 +TPM_20_E_RANGE: Final = -2144862067 +TPM_20_E_AUTH_FAIL: Final = -2144862066 +TPM_20_E_NONCE: Final = -2144862065 +TPM_20_E_PP: Final = -2144862064 +TPM_20_E_SCHEME: Final = -2144862062 +TPM_20_E_SIZE: Final = -2144862059 +TPM_20_E_SYMMETRIC: Final = -2144862058 +TPM_20_E_TAG: Final = -2144862057 +TPM_20_E_SELECTOR: Final = -2144862056 +TPM_20_E_INSUFFICIENT: Final = -2144862054 +TPM_20_E_SIGNATURE: Final = -2144862053 +TPM_20_E_KEY: Final = -2144862052 +TPM_20_E_POLICY_FAIL: Final = -2144862051 +TPM_20_E_INTEGRITY: Final = -2144862049 +TPM_20_E_TICKET: Final = -2144862048 +TPM_20_E_RESERVED_BITS: Final = -2144862047 +TPM_20_E_BAD_AUTH: Final = -2144862046 +TPM_20_E_EXPIRED: Final = -2144862045 +TPM_20_E_POLICY_CC: Final = -2144862044 +TPM_20_E_BINDING: Final = -2144862043 +TPM_20_E_CURVE: Final = -2144862042 +TPM_20_E_ECC_POINT: Final = -2144862041 +TPM_20_E_INITIALIZE: Final = -2144861952 +TPM_20_E_FAILURE: Final = -2144861951 +TPM_20_E_SEQUENCE: Final = -2144861949 +TPM_20_E_PRIVATE: Final = -2144861941 +TPM_20_E_HMAC: Final = -2144861927 +TPM_20_E_DISABLED: Final = -2144861920 +TPM_20_E_EXCLUSIVE: Final = -2144861919 +TPM_20_E_ECC_CURVE: Final = -2144861917 +TPM_20_E_AUTH_TYPE: Final = -2144861916 +TPM_20_E_AUTH_MISSING: Final = -2144861915 +TPM_20_E_POLICY: Final = -2144861914 +TPM_20_E_PCR: Final = -2144861913 +TPM_20_E_PCR_CHANGED: Final = -2144861912 +TPM_20_E_UPGRADE: Final = -2144861907 +TPM_20_E_TOO_MANY_CONTEXTS: Final = -2144861906 +TPM_20_E_AUTH_UNAVAILABLE: Final = -2144861905 +TPM_20_E_REBOOT: Final = -2144861904 +TPM_20_E_UNBALANCED: Final = -2144861903 +TPM_20_E_COMMAND_SIZE: Final = -2144861886 +TPM_20_E_COMMAND_CODE: Final = -2144861885 +TPM_20_E_AUTHSIZE: Final = -2144861884 +TPM_20_E_AUTH_CONTEXT: Final = -2144861883 +TPM_20_E_NV_RANGE: Final = -2144861882 +TPM_20_E_NV_SIZE: Final = -2144861881 +TPM_20_E_NV_LOCKED: Final = -2144861880 +TPM_20_E_NV_AUTHORIZATION: Final = -2144861879 +TPM_20_E_NV_UNINITIALIZED: Final = -2144861878 +TPM_20_E_NV_SPACE: Final = -2144861877 +TPM_20_E_NV_DEFINED: Final = -2144861876 +TPM_20_E_BAD_CONTEXT: Final = -2144861872 +TPM_20_E_CPHASH: Final = -2144861871 +TPM_20_E_PARENT: Final = -2144861870 +TPM_20_E_NEEDS_TEST: Final = -2144861869 +TPM_20_E_NO_RESULT: Final = -2144861868 +TPM_20_E_SENSITIVE: Final = -2144861867 +TPM_E_COMMAND_BLOCKED: Final = -2144861184 +TPM_E_INVALID_HANDLE: Final = -2144861183 +TPM_E_DUPLICATE_VHANDLE: Final = -2144861182 +TPM_E_EMBEDDED_COMMAND_BLOCKED: Final = -2144861181 +TPM_E_EMBEDDED_COMMAND_UNSUPPORTED: Final = -2144861180 +TPM_E_RETRY: Final = -2144860160 +TPM_E_NEEDS_SELFTEST: Final = -2144860159 +TPM_E_DOING_SELFTEST: Final = -2144860158 +TPM_E_DEFEND_LOCK_RUNNING: Final = -2144860157 +TPM_20_E_CONTEXT_GAP: Final = -2144859903 +TPM_20_E_OBJECT_MEMORY: Final = -2144859902 +TPM_20_E_SESSION_MEMORY: Final = -2144859901 +TPM_20_E_MEMORY: Final = -2144859900 +TPM_20_E_SESSION_HANDLES: Final = -2144859899 +TPM_20_E_OBJECT_HANDLES: Final = -2144859898 +TPM_20_E_LOCALITY: Final = -2144859897 +TPM_20_E_YIELDED: Final = -2144859896 +TPM_20_E_CANCELED: Final = -2144859895 +TPM_20_E_TESTING: Final = -2144859894 +TPM_20_E_NV_RATE: Final = -2144859872 +TPM_20_E_LOCKOUT: Final = -2144859871 +TPM_20_E_RETRY: Final = -2144859870 +TPM_20_E_NV_UNAVAILABLE: Final = -2144859869 +TBS_E_INTERNAL_ERROR: Final = -2144845823 +TBS_E_BAD_PARAMETER: Final = -2144845822 +TBS_E_INVALID_OUTPUT_POINTER: Final = -2144845821 +TBS_E_INVALID_CONTEXT: Final = -2144845820 +TBS_E_INSUFFICIENT_BUFFER: Final = -2144845819 +TBS_E_IOERROR: Final = -2144845818 +TBS_E_INVALID_CONTEXT_PARAM: Final = -2144845817 +TBS_E_SERVICE_NOT_RUNNING: Final = -2144845816 +TBS_E_TOO_MANY_TBS_CONTEXTS: Final = -2144845815 +TBS_E_TOO_MANY_RESOURCES: Final = -2144845814 +TBS_E_SERVICE_START_PENDING: Final = -2144845813 +TBS_E_PPI_NOT_SUPPORTED: Final = -2144845812 +TBS_E_COMMAND_CANCELED: Final = -2144845811 +TBS_E_BUFFER_TOO_LARGE: Final = -2144845810 +TBS_E_TPM_NOT_FOUND: Final = -2144845809 +TBS_E_SERVICE_DISABLED: Final = -2144845808 +TBS_E_NO_EVENT_LOG: Final = -2144845807 +TBS_E_ACCESS_DENIED: Final = -2144845806 +TBS_E_PROVISIONING_NOT_ALLOWED: Final = -2144845805 +TBS_E_PPI_FUNCTION_UNSUPPORTED: Final = -2144845804 +TBS_E_OWNERAUTH_NOT_FOUND: Final = -2144845803 +TBS_E_PROVISIONING_INCOMPLETE: Final = -2144845802 +TPMAPI_E_INVALID_STATE: Final = -2144796416 +TPMAPI_E_NOT_ENOUGH_DATA: Final = -2144796415 +TPMAPI_E_TOO_MUCH_DATA: Final = -2144796414 +TPMAPI_E_INVALID_OUTPUT_POINTER: Final = -2144796413 +TPMAPI_E_INVALID_PARAMETER: Final = -2144796412 +TPMAPI_E_OUT_OF_MEMORY: Final = -2144796411 +TPMAPI_E_BUFFER_TOO_SMALL: Final = -2144796410 +TPMAPI_E_INTERNAL_ERROR: Final = -2144796409 +TPMAPI_E_ACCESS_DENIED: Final = -2144796408 +TPMAPI_E_AUTHORIZATION_FAILED: Final = -2144796407 +TPMAPI_E_INVALID_CONTEXT_HANDLE: Final = -2144796406 +TPMAPI_E_TBS_COMMUNICATION_ERROR: Final = -2144796405 +TPMAPI_E_TPM_COMMAND_ERROR: Final = -2144796404 +TPMAPI_E_MESSAGE_TOO_LARGE: Final = -2144796403 +TPMAPI_E_INVALID_ENCODING: Final = -2144796402 +TPMAPI_E_INVALID_KEY_SIZE: Final = -2144796401 +TPMAPI_E_ENCRYPTION_FAILED: Final = -2144796400 +TPMAPI_E_INVALID_KEY_PARAMS: Final = -2144796399 +TPMAPI_E_INVALID_MIGRATION_AUTHORIZATION_BLOB: Final = -2144796398 +TPMAPI_E_INVALID_PCR_INDEX: Final = -2144796397 +TPMAPI_E_INVALID_DELEGATE_BLOB: Final = -2144796396 +TPMAPI_E_INVALID_CONTEXT_PARAMS: Final = -2144796395 +TPMAPI_E_INVALID_KEY_BLOB: Final = -2144796394 +TPMAPI_E_INVALID_PCR_DATA: Final = -2144796393 +TPMAPI_E_INVALID_OWNER_AUTH: Final = -2144796392 +TPMAPI_E_FIPS_RNG_CHECK_FAILED: Final = -2144796391 +TPMAPI_E_EMPTY_TCG_LOG: Final = -2144796390 +TPMAPI_E_INVALID_TCG_LOG_ENTRY: Final = -2144796389 +TPMAPI_E_TCG_SEPARATOR_ABSENT: Final = -2144796388 +TPMAPI_E_TCG_INVALID_DIGEST_ENTRY: Final = -2144796387 +TPMAPI_E_POLICY_DENIES_OPERATION: Final = -2144796386 +TPMAPI_E_NV_BITS_NOT_DEFINED: Final = -2144796385 +TPMAPI_E_NV_BITS_NOT_READY: Final = -2144796384 +TPMAPI_E_SEALING_KEY_NOT_AVAILABLE: Final = -2144796383 +TPMAPI_E_NO_AUTHORIZATION_CHAIN_FOUND: Final = -2144796382 +TPMAPI_E_SVN_COUNTER_NOT_AVAILABLE: Final = -2144796381 +TPMAPI_E_OWNER_AUTH_NOT_NULL: Final = -2144796380 +TPMAPI_E_ENDORSEMENT_AUTH_NOT_NULL: Final = -2144796379 +TPMAPI_E_AUTHORIZATION_REVOKED: Final = -2144796378 +TPMAPI_E_MALFORMED_AUTHORIZATION_KEY: Final = -2144796377 +TPMAPI_E_AUTHORIZING_KEY_NOT_SUPPORTED: Final = -2144796376 +TPMAPI_E_INVALID_AUTHORIZATION_SIGNATURE: Final = -2144796375 +TPMAPI_E_MALFORMED_AUTHORIZATION_POLICY: Final = -2144796374 +TPMAPI_E_MALFORMED_AUTHORIZATION_OTHER: Final = -2144796373 +TPMAPI_E_SEALING_KEY_CHANGED: Final = -2144796372 +TPMAPI_E_INVALID_TPM_VERSION: Final = -2144796371 +TPMAPI_E_INVALID_POLICYAUTH_BLOB_TYPE: Final = -2144796370 +TBSIMP_E_BUFFER_TOO_SMALL: Final = -2144796160 +TBSIMP_E_CLEANUP_FAILED: Final = -2144796159 +TBSIMP_E_INVALID_CONTEXT_HANDLE: Final = -2144796158 +TBSIMP_E_INVALID_CONTEXT_PARAM: Final = -2144796157 +TBSIMP_E_TPM_ERROR: Final = -2144796156 +TBSIMP_E_HASH_BAD_KEY: Final = -2144796155 +TBSIMP_E_DUPLICATE_VHANDLE: Final = -2144796154 +TBSIMP_E_INVALID_OUTPUT_POINTER: Final = -2144796153 +TBSIMP_E_INVALID_PARAMETER: Final = -2144796152 +TBSIMP_E_RPC_INIT_FAILED: Final = -2144796151 +TBSIMP_E_SCHEDULER_NOT_RUNNING: Final = -2144796150 +TBSIMP_E_COMMAND_CANCELED: Final = -2144796149 +TBSIMP_E_OUT_OF_MEMORY: Final = -2144796148 +TBSIMP_E_LIST_NO_MORE_ITEMS: Final = -2144796147 +TBSIMP_E_LIST_NOT_FOUND: Final = -2144796146 +TBSIMP_E_NOT_ENOUGH_SPACE: Final = -2144796145 +TBSIMP_E_NOT_ENOUGH_TPM_CONTEXTS: Final = -2144796144 +TBSIMP_E_COMMAND_FAILED: Final = -2144796143 +TBSIMP_E_UNKNOWN_ORDINAL: Final = -2144796142 +TBSIMP_E_RESOURCE_EXPIRED: Final = -2144796141 +TBSIMP_E_INVALID_RESOURCE: Final = -2144796140 +TBSIMP_E_NOTHING_TO_UNLOAD: Final = -2144796139 +TBSIMP_E_HASH_TABLE_FULL: Final = -2144796138 +TBSIMP_E_TOO_MANY_TBS_CONTEXTS: Final = -2144796137 +TBSIMP_E_TOO_MANY_RESOURCES: Final = -2144796136 +TBSIMP_E_PPI_NOT_SUPPORTED: Final = -2144796135 +TBSIMP_E_TPM_INCOMPATIBLE: Final = -2144796134 +TBSIMP_E_NO_EVENT_LOG: Final = -2144796133 +TPM_E_PPI_ACPI_FAILURE: Final = -2144795904 +TPM_E_PPI_USER_ABORT: Final = -2144795903 +TPM_E_PPI_BIOS_FAILURE: Final = -2144795902 +TPM_E_PPI_NOT_SUPPORTED: Final = -2144795901 +TPM_E_PPI_BLOCKED_IN_BIOS: Final = -2144795900 +TPM_E_PCP_ERROR_MASK: Final = -2144795648 +TPM_E_PCP_DEVICE_NOT_READY: Final = -2144795647 +TPM_E_PCP_INVALID_HANDLE: Final = -2144795646 +TPM_E_PCP_INVALID_PARAMETER: Final = -2144795645 +TPM_E_PCP_FLAG_NOT_SUPPORTED: Final = -2144795644 +TPM_E_PCP_NOT_SUPPORTED: Final = -2144795643 +TPM_E_PCP_BUFFER_TOO_SMALL: Final = -2144795642 +TPM_E_PCP_INTERNAL_ERROR: Final = -2144795641 +TPM_E_PCP_AUTHENTICATION_FAILED: Final = -2144795640 +TPM_E_PCP_AUTHENTICATION_IGNORED: Final = -2144795639 +TPM_E_PCP_POLICY_NOT_FOUND: Final = -2144795638 +TPM_E_PCP_PROFILE_NOT_FOUND: Final = -2144795637 +TPM_E_PCP_VALIDATION_FAILED: Final = -2144795636 +TPM_E_PCP_WRONG_PARENT: Final = -2144795634 +TPM_E_KEY_NOT_LOADED: Final = -2144795633 +TPM_E_NO_KEY_CERTIFICATION: Final = -2144795632 +TPM_E_KEY_NOT_FINALIZED: Final = -2144795631 +TPM_E_ATTESTATION_CHALLENGE_NOT_SET: Final = -2144795630 +TPM_E_NOT_PCR_BOUND: Final = -2144795629 +TPM_E_KEY_ALREADY_FINALIZED: Final = -2144795628 +TPM_E_KEY_USAGE_POLICY_NOT_SUPPORTED: Final = -2144795627 +TPM_E_KEY_USAGE_POLICY_INVALID: Final = -2144795626 +TPM_E_SOFT_KEY_ERROR: Final = -2144795625 +TPM_E_KEY_NOT_AUTHENTICATED: Final = -2144795624 +TPM_E_PCP_KEY_NOT_AIK: Final = -2144795623 +TPM_E_KEY_NOT_SIGNING_KEY: Final = -2144795622 +TPM_E_LOCKED_OUT: Final = -2144795621 +TPM_E_CLAIM_TYPE_NOT_SUPPORTED: Final = -2144795620 +TPM_E_VERSION_NOT_SUPPORTED: Final = -2144795619 +TPM_E_BUFFER_LENGTH_MISMATCH: Final = -2144795618 +TPM_E_PCP_IFX_RSA_KEY_CREATION_BLOCKED: Final = -2144795617 +TPM_E_PCP_TICKET_MISSING: Final = -2144795616 +TPM_E_PCP_RAW_POLICY_NOT_SUPPORTED: Final = -2144795615 +TPM_E_PCP_KEY_HANDLE_INVALIDATED: Final = -2144795614 +TPM_E_PCP_UNSUPPORTED_PSS_SALT: Final = 0x40290423 +TPM_E_PCP_PLATFORM_CLAIM_MAY_BE_OUTDATED: Final = 0x40290424 +TPM_E_PCP_PLATFORM_CLAIM_OUTDATED: Final = 0x40290425 +TPM_E_PCP_PLATFORM_CLAIM_REBOOT: Final = 0x40290426 +TPM_E_ZERO_EXHAUST_ENABLED: Final = -2144795392 +TPM_E_PROVISIONING_INCOMPLETE: Final = -2144795136 +TPM_E_INVALID_OWNER_AUTH: Final = -2144795135 +TPM_E_TOO_MUCH_DATA: Final = -2144795134 +TPM_E_TPM_GENERATED_EPS: Final = -2144795133 +PLA_E_DCS_NOT_FOUND: Final = -2144337918 +PLA_E_DCS_IN_USE: Final = -2144337750 +PLA_E_TOO_MANY_FOLDERS: Final = -2144337851 +PLA_E_NO_MIN_DISK: Final = -2144337808 +PLA_E_DCS_ALREADY_EXISTS: Final = -2144337737 +PLA_S_PROPERTY_IGNORED: Final = 0x00300100 +PLA_E_PROPERTY_CONFLICT: Final = -2144337663 +PLA_E_DCS_SINGLETON_REQUIRED: Final = -2144337662 +PLA_E_CREDENTIALS_REQUIRED: Final = -2144337661 +PLA_E_DCS_NOT_RUNNING: Final = -2144337660 +PLA_E_CONFLICT_INCL_EXCL_API: Final = -2144337659 +PLA_E_NETWORK_EXE_NOT_VALID: Final = -2144337658 +PLA_E_EXE_ALREADY_CONFIGURED: Final = -2144337657 +PLA_E_EXE_PATH_NOT_VALID: Final = -2144337656 +PLA_E_DC_ALREADY_EXISTS: Final = -2144337655 +PLA_E_DCS_START_WAIT_TIMEOUT: Final = -2144337654 +PLA_E_DC_START_WAIT_TIMEOUT: Final = -2144337653 +PLA_E_REPORT_WAIT_TIMEOUT: Final = -2144337652 +PLA_E_NO_DUPLICATES: Final = -2144337651 +PLA_E_EXE_FULL_PATH_REQUIRED: Final = -2144337650 +PLA_E_INVALID_SESSION_NAME: Final = -2144337649 +PLA_E_PLA_CHANNEL_NOT_ENABLED: Final = -2144337648 +PLA_E_TASKSCHED_CHANNEL_NOT_ENABLED: Final = -2144337647 +PLA_E_RULES_MANAGER_FAILED: Final = -2144337646 +PLA_E_CABAPI_FAILURE: Final = -2144337645 +FVE_E_LOCKED_VOLUME: Final = -2144272384 +FVE_E_NOT_ENCRYPTED: Final = -2144272383 +FVE_E_NO_TPM_BIOS: Final = -2144272382 +FVE_E_NO_MBR_METRIC: Final = -2144272381 +FVE_E_NO_BOOTSECTOR_METRIC: Final = -2144272380 +FVE_E_NO_BOOTMGR_METRIC: Final = -2144272379 +FVE_E_WRONG_BOOTMGR: Final = -2144272378 +FVE_E_SECURE_KEY_REQUIRED: Final = -2144272377 +FVE_E_NOT_ACTIVATED: Final = -2144272376 +FVE_E_ACTION_NOT_ALLOWED: Final = -2144272375 +FVE_E_AD_SCHEMA_NOT_INSTALLED: Final = -2144272374 +FVE_E_AD_INVALID_DATATYPE: Final = -2144272373 +FVE_E_AD_INVALID_DATASIZE: Final = -2144272372 +FVE_E_AD_NO_VALUES: Final = -2144272371 +FVE_E_AD_ATTR_NOT_SET: Final = -2144272370 +FVE_E_AD_GUID_NOT_FOUND: Final = -2144272369 +FVE_E_BAD_INFORMATION: Final = -2144272368 +FVE_E_TOO_SMALL: Final = -2144272367 +FVE_E_SYSTEM_VOLUME: Final = -2144272366 +FVE_E_FAILED_WRONG_FS: Final = -2144272365 +FVE_E_BAD_PARTITION_SIZE: Final = -2144272364 +FVE_E_NOT_SUPPORTED: Final = -2144272363 +FVE_E_BAD_DATA: Final = -2144272362 +FVE_E_VOLUME_NOT_BOUND: Final = -2144272361 +FVE_E_TPM_NOT_OWNED: Final = -2144272360 +FVE_E_NOT_DATA_VOLUME: Final = -2144272359 +FVE_E_AD_INSUFFICIENT_BUFFER: Final = -2144272358 +FVE_E_CONV_READ: Final = -2144272357 +FVE_E_CONV_WRITE: Final = -2144272356 +FVE_E_KEY_REQUIRED: Final = -2144272355 +FVE_E_CLUSTERING_NOT_SUPPORTED: Final = -2144272354 +FVE_E_VOLUME_BOUND_ALREADY: Final = -2144272353 +FVE_E_OS_NOT_PROTECTED: Final = -2144272352 +FVE_E_PROTECTION_DISABLED: Final = -2144272351 +FVE_E_RECOVERY_KEY_REQUIRED: Final = -2144272350 +FVE_E_FOREIGN_VOLUME: Final = -2144272349 +FVE_E_OVERLAPPED_UPDATE: Final = -2144272348 +FVE_E_TPM_SRK_AUTH_NOT_ZERO: Final = -2144272347 +FVE_E_FAILED_SECTOR_SIZE: Final = -2144272346 +FVE_E_FAILED_AUTHENTICATION: Final = -2144272345 +FVE_E_NOT_OS_VOLUME: Final = -2144272344 +FVE_E_AUTOUNLOCK_ENABLED: Final = -2144272343 +FVE_E_WRONG_BOOTSECTOR: Final = -2144272342 +FVE_E_WRONG_SYSTEM_FS: Final = -2144272341 +FVE_E_POLICY_PASSWORD_REQUIRED: Final = -2144272340 +FVE_E_CANNOT_SET_FVEK_ENCRYPTED: Final = -2144272339 +FVE_E_CANNOT_ENCRYPT_NO_KEY: Final = -2144272338 +FVE_E_BOOTABLE_CDDVD: Final = -2144272336 +FVE_E_PROTECTOR_EXISTS: Final = -2144272335 +FVE_E_RELATIVE_PATH: Final = -2144272334 +FVE_E_PROTECTOR_NOT_FOUND: Final = -2144272333 +FVE_E_INVALID_KEY_FORMAT: Final = -2144272332 +FVE_E_INVALID_PASSWORD_FORMAT: Final = -2144272331 +FVE_E_FIPS_RNG_CHECK_FAILED: Final = -2144272330 +FVE_E_FIPS_PREVENTS_RECOVERY_PASSWORD: Final = -2144272329 +FVE_E_FIPS_PREVENTS_EXTERNAL_KEY_EXPORT: Final = -2144272328 +FVE_E_NOT_DECRYPTED: Final = -2144272327 +FVE_E_INVALID_PROTECTOR_TYPE: Final = -2144272326 +FVE_E_NO_PROTECTORS_TO_TEST: Final = -2144272325 +FVE_E_KEYFILE_NOT_FOUND: Final = -2144272324 +FVE_E_KEYFILE_INVALID: Final = -2144272323 +FVE_E_KEYFILE_NO_VMK: Final = -2144272322 +FVE_E_TPM_DISABLED: Final = -2144272321 +FVE_E_NOT_ALLOWED_IN_SAFE_MODE: Final = -2144272320 +FVE_E_TPM_INVALID_PCR: Final = -2144272319 +FVE_E_TPM_NO_VMK: Final = -2144272318 +FVE_E_PIN_INVALID: Final = -2144272317 +FVE_E_AUTH_INVALID_APPLICATION: Final = -2144272316 +FVE_E_AUTH_INVALID_CONFIG: Final = -2144272315 +FVE_E_FIPS_DISABLE_PROTECTION_NOT_ALLOWED: Final = -2144272314 +FVE_E_FS_NOT_EXTENDED: Final = -2144272313 +FVE_E_FIRMWARE_TYPE_NOT_SUPPORTED: Final = -2144272312 +FVE_E_NO_LICENSE: Final = -2144272311 +FVE_E_NOT_ON_STACK: Final = -2144272310 +FVE_E_FS_MOUNTED: Final = -2144272309 +FVE_E_TOKEN_NOT_IMPERSONATED: Final = -2144272308 +FVE_E_DRY_RUN_FAILED: Final = -2144272307 +FVE_E_REBOOT_REQUIRED: Final = -2144272306 +FVE_E_DEBUGGER_ENABLED: Final = -2144272305 +FVE_E_RAW_ACCESS: Final = -2144272304 +FVE_E_RAW_BLOCKED: Final = -2144272303 +FVE_E_BCD_APPLICATIONS_PATH_INCORRECT: Final = -2144272302 +FVE_E_NOT_ALLOWED_IN_VERSION: Final = -2144272301 +FVE_E_NO_AUTOUNLOCK_MASTER_KEY: Final = -2144272300 +FVE_E_MOR_FAILED: Final = -2144272299 +FVE_E_HIDDEN_VOLUME: Final = -2144272298 +FVE_E_TRANSIENT_STATE: Final = -2144272297 +FVE_E_PUBKEY_NOT_ALLOWED: Final = -2144272296 +FVE_E_VOLUME_HANDLE_OPEN: Final = -2144272295 +FVE_E_NO_FEATURE_LICENSE: Final = -2144272294 +FVE_E_INVALID_STARTUP_OPTIONS: Final = -2144272293 +FVE_E_POLICY_RECOVERY_PASSWORD_NOT_ALLOWED: Final = -2144272292 +FVE_E_POLICY_RECOVERY_PASSWORD_REQUIRED: Final = -2144272291 +FVE_E_POLICY_RECOVERY_KEY_NOT_ALLOWED: Final = -2144272290 +FVE_E_POLICY_RECOVERY_KEY_REQUIRED: Final = -2144272289 +FVE_E_POLICY_STARTUP_PIN_NOT_ALLOWED: Final = -2144272288 +FVE_E_POLICY_STARTUP_PIN_REQUIRED: Final = -2144272287 +FVE_E_POLICY_STARTUP_KEY_NOT_ALLOWED: Final = -2144272286 +FVE_E_POLICY_STARTUP_KEY_REQUIRED: Final = -2144272285 +FVE_E_POLICY_STARTUP_PIN_KEY_NOT_ALLOWED: Final = -2144272284 +FVE_E_POLICY_STARTUP_PIN_KEY_REQUIRED: Final = -2144272283 +FVE_E_POLICY_STARTUP_TPM_NOT_ALLOWED: Final = -2144272282 +FVE_E_POLICY_STARTUP_TPM_REQUIRED: Final = -2144272281 +FVE_E_POLICY_INVALID_PIN_LENGTH: Final = -2144272280 +FVE_E_KEY_PROTECTOR_NOT_SUPPORTED: Final = -2144272279 +FVE_E_POLICY_PASSPHRASE_NOT_ALLOWED: Final = -2144272278 +FVE_E_POLICY_PASSPHRASE_REQUIRED: Final = -2144272277 +FVE_E_FIPS_PREVENTS_PASSPHRASE: Final = -2144272276 +FVE_E_OS_VOLUME_PASSPHRASE_NOT_ALLOWED: Final = -2144272275 +FVE_E_INVALID_BITLOCKER_OID: Final = -2144272274 +FVE_E_VOLUME_TOO_SMALL: Final = -2144272273 +FVE_E_DV_NOT_SUPPORTED_ON_FS: Final = -2144272272 +FVE_E_DV_NOT_ALLOWED_BY_GP: Final = -2144272271 +FVE_E_POLICY_USER_CERTIFICATE_NOT_ALLOWED: Final = -2144272270 +FVE_E_POLICY_USER_CERTIFICATE_REQUIRED: Final = -2144272269 +FVE_E_POLICY_USER_CERT_MUST_BE_HW: Final = -2144272268 +FVE_E_POLICY_USER_CONFIGURE_FDV_AUTOUNLOCK_NOT_ALLOWED: Final = -2144272267 +FVE_E_POLICY_USER_CONFIGURE_RDV_AUTOUNLOCK_NOT_ALLOWED: Final = -2144272266 +FVE_E_POLICY_USER_CONFIGURE_RDV_NOT_ALLOWED: Final = -2144272265 +FVE_E_POLICY_USER_ENABLE_RDV_NOT_ALLOWED: Final = -2144272264 +FVE_E_POLICY_USER_DISABLE_RDV_NOT_ALLOWED: Final = -2144272263 +FVE_E_POLICY_INVALID_PASSPHRASE_LENGTH: Final = -2144272256 +FVE_E_POLICY_PASSPHRASE_TOO_SIMPLE: Final = -2144272255 +FVE_E_RECOVERY_PARTITION: Final = -2144272254 +FVE_E_POLICY_CONFLICT_FDV_RK_OFF_AUK_ON: Final = -2144272253 +FVE_E_POLICY_CONFLICT_RDV_RK_OFF_AUK_ON: Final = -2144272252 +FVE_E_NON_BITLOCKER_OID: Final = -2144272251 +FVE_E_POLICY_PROHIBITS_SELFSIGNED: Final = -2144272250 +FVE_E_POLICY_CONFLICT_RO_AND_STARTUP_KEY_REQUIRED: Final = -2144272249 +FVE_E_CONV_RECOVERY_FAILED: Final = -2144272248 +FVE_E_VIRTUALIZED_SPACE_TOO_BIG: Final = -2144272247 +FVE_E_POLICY_CONFLICT_OSV_RP_OFF_ADB_ON: Final = -2144272240 +FVE_E_POLICY_CONFLICT_FDV_RP_OFF_ADB_ON: Final = -2144272239 +FVE_E_POLICY_CONFLICT_RDV_RP_OFF_ADB_ON: Final = -2144272238 +FVE_E_NON_BITLOCKER_KU: Final = -2144272237 +FVE_E_PRIVATEKEY_AUTH_FAILED: Final = -2144272236 +FVE_E_REMOVAL_OF_DRA_FAILED: Final = -2144272235 +FVE_E_OPERATION_NOT_SUPPORTED_ON_VISTA_VOLUME: Final = -2144272234 +FVE_E_CANT_LOCK_AUTOUNLOCK_ENABLED_VOLUME: Final = -2144272233 +FVE_E_FIPS_HASH_KDF_NOT_ALLOWED: Final = -2144272232 +FVE_E_ENH_PIN_INVALID: Final = -2144272231 +FVE_E_INVALID_PIN_CHARS: Final = -2144272230 +FVE_E_INVALID_DATUM_TYPE: Final = -2144272229 +FVE_E_EFI_ONLY: Final = -2144272228 +FVE_E_MULTIPLE_NKP_CERTS: Final = -2144272227 +FVE_E_REMOVAL_OF_NKP_FAILED: Final = -2144272226 +FVE_E_INVALID_NKP_CERT: Final = -2144272225 +FVE_E_NO_EXISTING_PIN: Final = -2144272224 +FVE_E_PROTECTOR_CHANGE_PIN_MISMATCH: Final = -2144272223 +FVE_E_PIN_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: Final = -2144272222 +FVE_E_PROTECTOR_CHANGE_MAX_PIN_CHANGE_ATTEMPTS_REACHED: Final = -2144272221 +FVE_E_POLICY_PASSPHRASE_REQUIRES_ASCII: Final = -2144272220 +FVE_E_FULL_ENCRYPTION_NOT_ALLOWED_ON_TP_STORAGE: Final = -2144272219 +FVE_E_WIPE_NOT_ALLOWED_ON_TP_STORAGE: Final = -2144272218 +FVE_E_KEY_LENGTH_NOT_SUPPORTED_BY_EDRIVE: Final = -2144272217 +FVE_E_NO_EXISTING_PASSPHRASE: Final = -2144272216 +FVE_E_PROTECTOR_CHANGE_PASSPHRASE_MISMATCH: Final = -2144272215 +FVE_E_PASSPHRASE_TOO_LONG: Final = -2144272214 +FVE_E_NO_PASSPHRASE_WITH_TPM: Final = -2144272213 +FVE_E_NO_TPM_WITH_PASSPHRASE: Final = -2144272212 +FVE_E_NOT_ALLOWED_ON_CSV_STACK: Final = -2144272211 +FVE_E_NOT_ALLOWED_ON_CLUSTER: Final = -2144272210 +FVE_E_EDRIVE_NO_FAILOVER_TO_SW: Final = -2144272209 +FVE_E_EDRIVE_BAND_IN_USE: Final = -2144272208 +FVE_E_EDRIVE_DISALLOWED_BY_GP: Final = -2144272207 +FVE_E_EDRIVE_INCOMPATIBLE_VOLUME: Final = -2144272206 +FVE_E_NOT_ALLOWED_TO_UPGRADE_WHILE_CONVERTING: Final = -2144272205 +FVE_E_EDRIVE_DV_NOT_SUPPORTED: Final = -2144272204 +FVE_E_NO_PREBOOT_KEYBOARD_DETECTED: Final = -2144272203 +FVE_E_NO_PREBOOT_KEYBOARD_OR_WINRE_DETECTED: Final = -2144272202 +FVE_E_POLICY_REQUIRES_STARTUP_PIN_ON_TOUCH_DEVICE: Final = -2144272201 +FVE_E_POLICY_REQUIRES_RECOVERY_PASSWORD_ON_TOUCH_DEVICE: Final = -2144272200 +FVE_E_WIPE_CANCEL_NOT_APPLICABLE: Final = -2144272199 +FVE_E_SECUREBOOT_DISABLED: Final = -2144272198 +FVE_E_SECUREBOOT_CONFIGURATION_INVALID: Final = -2144272197 +FVE_E_EDRIVE_DRY_RUN_FAILED: Final = -2144272196 +FVE_E_SHADOW_COPY_PRESENT: Final = -2144272195 +FVE_E_POLICY_INVALID_ENHANCED_BCD_SETTINGS: Final = -2144272194 +FVE_E_EDRIVE_INCOMPATIBLE_FIRMWARE: Final = -2144272193 +FVE_E_PROTECTOR_CHANGE_MAX_PASSPHRASE_CHANGE_ATTEMPTS_REACHED: Final = -2144272192 +FVE_E_PASSPHRASE_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: Final = -2144272191 +FVE_E_LIVEID_ACCOUNT_SUSPENDED: Final = -2144272190 +FVE_E_LIVEID_ACCOUNT_BLOCKED: Final = -2144272189 +FVE_E_NOT_PROVISIONED_ON_ALL_VOLUMES: Final = -2144272188 +FVE_E_DE_FIXED_DATA_NOT_SUPPORTED: Final = -2144272187 +FVE_E_DE_HARDWARE_NOT_COMPLIANT: Final = -2144272186 +FVE_E_DE_WINRE_NOT_CONFIGURED: Final = -2144272185 +FVE_E_DE_PROTECTION_SUSPENDED: Final = -2144272184 +FVE_E_DE_OS_VOLUME_NOT_PROTECTED: Final = -2144272183 +FVE_E_DE_DEVICE_LOCKEDOUT: Final = -2144272182 +FVE_E_DE_PROTECTION_NOT_YET_ENABLED: Final = -2144272181 +FVE_E_INVALID_PIN_CHARS_DETAILED: Final = -2144272180 +FVE_E_DEVICE_LOCKOUT_COUNTER_UNAVAILABLE: Final = -2144272179 +FVE_E_DEVICELOCKOUT_COUNTER_MISMATCH: Final = -2144272178 +FVE_E_BUFFER_TOO_LARGE: Final = -2144272177 +FVE_E_NO_SUCH_CAPABILITY_ON_TARGET: Final = -2144272176 +FVE_E_DE_PREVENTED_FOR_OS: Final = -2144272175 +FVE_E_DE_VOLUME_OPTED_OUT: Final = -2144272174 +FVE_E_DE_VOLUME_NOT_SUPPORTED: Final = -2144272173 +FVE_E_EOW_NOT_SUPPORTED_IN_VERSION: Final = -2144272172 +FVE_E_ADBACKUP_NOT_ENABLED: Final = -2144272171 +FVE_E_VOLUME_EXTEND_PREVENTS_EOW_DECRYPT: Final = -2144272170 +FVE_E_NOT_DE_VOLUME: Final = -2144272169 +FVE_E_PROTECTION_CANNOT_BE_DISABLED: Final = -2144272168 +FVE_E_OSV_KSR_NOT_ALLOWED: Final = -2144272167 +FVE_E_AD_BACKUP_REQUIRED_POLICY_NOT_SET_OS_DRIVE: Final = -2144272166 +FVE_E_AD_BACKUP_REQUIRED_POLICY_NOT_SET_FIXED_DRIVE: Final = -2144272165 +FVE_E_AD_BACKUP_REQUIRED_POLICY_NOT_SET_REMOVABLE_DRIVE: Final = -2144272164 +FVE_E_KEY_ROTATION_NOT_SUPPORTED: Final = -2144272163 +FVE_E_EXECUTE_REQUEST_SENT_TOO_SOON: Final = -2144272162 +FVE_E_KEY_ROTATION_NOT_ENABLED: Final = -2144272161 +FVE_E_DEVICE_NOT_JOINED: Final = -2144272160 +FVE_E_AAD_ENDPOINT_BUSY: Final = -2144272159 +FVE_E_INVALID_NBP_CERT: Final = -2144272158 +FVE_E_EDRIVE_BAND_ENUMERATION_FAILED: Final = -2144272157 +FVE_E_POLICY_ON_RDV_EXCLUSION_LIST: Final = -2144272156 +FVE_E_PREDICTED_TPM_PROTECTOR_NOT_SUPPORTED: Final = -2144272155 +FVE_E_SETUP_TPM_CALLBACK_NOT_SUPPORTED: Final = -2144272154 +FVE_E_TPM_CONTEXT_SETUP_NOT_SUPPORTED: Final = -2144272153 +FVE_E_UPDATE_INVALID_CONFIG: Final = -2144272152 +FVE_E_AAD_SERVER_FAIL_RETRY_AFTER: Final = -2144272151 +FVE_E_AAD_SERVER_FAIL_BACKOFF: Final = -2144272150 +FVE_E_DATASET_FULL: Final = -2144272149 +FVE_E_METADATA_FULL: Final = -2144272148 +FWP_E_CALLOUT_NOT_FOUND: Final = -2144206847 +FWP_E_CONDITION_NOT_FOUND: Final = -2144206846 +FWP_E_FILTER_NOT_FOUND: Final = -2144206845 +FWP_E_LAYER_NOT_FOUND: Final = -2144206844 +FWP_E_PROVIDER_NOT_FOUND: Final = -2144206843 +FWP_E_PROVIDER_CONTEXT_NOT_FOUND: Final = -2144206842 +FWP_E_SUBLAYER_NOT_FOUND: Final = -2144206841 +FWP_E_NOT_FOUND: Final = -2144206840 +FWP_E_ALREADY_EXISTS: Final = -2144206839 +FWP_E_IN_USE: Final = -2144206838 +FWP_E_DYNAMIC_SESSION_IN_PROGRESS: Final = -2144206837 +FWP_E_WRONG_SESSION: Final = -2144206836 +FWP_E_NO_TXN_IN_PROGRESS: Final = -2144206835 +FWP_E_TXN_IN_PROGRESS: Final = -2144206834 +FWP_E_TXN_ABORTED: Final = -2144206833 +FWP_E_SESSION_ABORTED: Final = -2144206832 +FWP_E_INCOMPATIBLE_TXN: Final = -2144206831 +FWP_E_TIMEOUT: Final = -2144206830 +FWP_E_NET_EVENTS_DISABLED: Final = -2144206829 +FWP_E_INCOMPATIBLE_LAYER: Final = -2144206828 +FWP_E_KM_CLIENTS_ONLY: Final = -2144206827 +FWP_E_LIFETIME_MISMATCH: Final = -2144206826 +FWP_E_BUILTIN_OBJECT: Final = -2144206825 +FWP_E_TOO_MANY_CALLOUTS: Final = -2144206824 +FWP_E_NOTIFICATION_DROPPED: Final = -2144206823 +FWP_E_TRAFFIC_MISMATCH: Final = -2144206822 +FWP_E_INCOMPATIBLE_SA_STATE: Final = -2144206821 +FWP_E_NULL_POINTER: Final = -2144206820 +FWP_E_INVALID_ENUMERATOR: Final = -2144206819 +FWP_E_INVALID_FLAGS: Final = -2144206818 +FWP_E_INVALID_NET_MASK: Final = -2144206817 +FWP_E_INVALID_RANGE: Final = -2144206816 +FWP_E_INVALID_INTERVAL: Final = -2144206815 +FWP_E_ZERO_LENGTH_ARRAY: Final = -2144206814 +FWP_E_NULL_DISPLAY_NAME: Final = -2144206813 +FWP_E_INVALID_ACTION_TYPE: Final = -2144206812 +FWP_E_INVALID_WEIGHT: Final = -2144206811 +FWP_E_MATCH_TYPE_MISMATCH: Final = -2144206810 +FWP_E_TYPE_MISMATCH: Final = -2144206809 +FWP_E_OUT_OF_BOUNDS: Final = -2144206808 +FWP_E_RESERVED: Final = -2144206807 +FWP_E_DUPLICATE_CONDITION: Final = -2144206806 +FWP_E_DUPLICATE_KEYMOD: Final = -2144206805 +FWP_E_ACTION_INCOMPATIBLE_WITH_LAYER: Final = -2144206804 +FWP_E_ACTION_INCOMPATIBLE_WITH_SUBLAYER: Final = -2144206803 +FWP_E_CONTEXT_INCOMPATIBLE_WITH_LAYER: Final = -2144206802 +FWP_E_CONTEXT_INCOMPATIBLE_WITH_CALLOUT: Final = -2144206801 +FWP_E_INCOMPATIBLE_AUTH_METHOD: Final = -2144206800 +FWP_E_INCOMPATIBLE_DH_GROUP: Final = -2144206799 +FWP_E_EM_NOT_SUPPORTED: Final = -2144206798 +FWP_E_NEVER_MATCH: Final = -2144206797 +FWP_E_PROVIDER_CONTEXT_MISMATCH: Final = -2144206796 +FWP_E_INVALID_PARAMETER: Final = -2144206795 +FWP_E_TOO_MANY_SUBLAYERS: Final = -2144206794 +FWP_E_CALLOUT_NOTIFICATION_FAILED: Final = -2144206793 +FWP_E_INVALID_AUTH_TRANSFORM: Final = -2144206792 +FWP_E_INVALID_CIPHER_TRANSFORM: Final = -2144206791 +FWP_E_INCOMPATIBLE_CIPHER_TRANSFORM: Final = -2144206790 +FWP_E_INVALID_TRANSFORM_COMBINATION: Final = -2144206789 +FWP_E_DUPLICATE_AUTH_METHOD: Final = -2144206788 +FWP_E_INVALID_TUNNEL_ENDPOINT: Final = -2144206787 +FWP_E_L2_DRIVER_NOT_READY: Final = -2144206786 +FWP_E_KEY_DICTATOR_ALREADY_REGISTERED: Final = -2144206785 +FWP_E_KEY_DICTATION_INVALID_KEYING_MATERIAL: Final = -2144206784 +FWP_E_CONNECTIONS_DISABLED: Final = -2144206783 +FWP_E_INVALID_DNS_NAME: Final = -2144206782 +FWP_E_STILL_ON: Final = -2144206781 +FWP_E_IKEEXT_NOT_RUNNING: Final = -2144206780 +FWP_E_DROP_NOICMP: Final = -2144206588 +WS_S_ASYNC: Final = 0x003D0000 +WS_S_END: Final = 0x003D0001 +WS_E_INVALID_FORMAT: Final = -2143485952 +WS_E_OBJECT_FAULTED: Final = -2143485951 +WS_E_NUMERIC_OVERFLOW: Final = -2143485950 +WS_E_INVALID_OPERATION: Final = -2143485949 +WS_E_OPERATION_ABORTED: Final = -2143485948 +WS_E_ENDPOINT_ACCESS_DENIED: Final = -2143485947 +WS_E_OPERATION_TIMED_OUT: Final = -2143485946 +WS_E_OPERATION_ABANDONED: Final = -2143485945 +WS_E_QUOTA_EXCEEDED: Final = -2143485944 +WS_E_NO_TRANSLATION_AVAILABLE: Final = -2143485943 +WS_E_SECURITY_VERIFICATION_FAILURE: Final = -2143485942 +WS_E_ADDRESS_IN_USE: Final = -2143485941 +WS_E_ADDRESS_NOT_AVAILABLE: Final = -2143485940 +WS_E_ENDPOINT_NOT_FOUND: Final = -2143485939 +WS_E_ENDPOINT_NOT_AVAILABLE: Final = -2143485938 +WS_E_ENDPOINT_FAILURE: Final = -2143485937 +WS_E_ENDPOINT_UNREACHABLE: Final = -2143485936 +WS_E_ENDPOINT_ACTION_NOT_SUPPORTED: Final = -2143485935 +WS_E_ENDPOINT_TOO_BUSY: Final = -2143485934 +WS_E_ENDPOINT_FAULT_RECEIVED: Final = -2143485933 +WS_E_ENDPOINT_DISCONNECTED: Final = -2143485932 +WS_E_PROXY_FAILURE: Final = -2143485931 +WS_E_PROXY_ACCESS_DENIED: Final = -2143485930 +WS_E_NOT_SUPPORTED: Final = -2143485929 +WS_E_PROXY_REQUIRES_BASIC_AUTH: Final = -2143485928 +WS_E_PROXY_REQUIRES_DIGEST_AUTH: Final = -2143485927 +WS_E_PROXY_REQUIRES_NTLM_AUTH: Final = -2143485926 +WS_E_PROXY_REQUIRES_NEGOTIATE_AUTH: Final = -2143485925 +WS_E_SERVER_REQUIRES_BASIC_AUTH: Final = -2143485924 +WS_E_SERVER_REQUIRES_DIGEST_AUTH: Final = -2143485923 +WS_E_SERVER_REQUIRES_NTLM_AUTH: Final = -2143485922 +WS_E_SERVER_REQUIRES_NEGOTIATE_AUTH: Final = -2143485921 +WS_E_INVALID_ENDPOINT_URL: Final = -2143485920 +WS_E_OTHER: Final = -2143485919 +WS_E_SECURITY_TOKEN_EXPIRED: Final = -2143485918 +WS_E_SECURITY_SYSTEM_FAILURE: Final = -2143485917 + +ERROR_NDIS_INTERFACE_CLOSING: Final = -2144075774 +ERROR_NDIS_BAD_VERSION: Final = -2144075772 +ERROR_NDIS_BAD_CHARACTERISTICS: Final = -2144075771 +ERROR_NDIS_ADAPTER_NOT_FOUND: Final = -2144075770 +ERROR_NDIS_OPEN_FAILED: Final = -2144075769 +ERROR_NDIS_DEVICE_FAILED: Final = -2144075768 +ERROR_NDIS_MULTICAST_FULL: Final = -2144075767 +ERROR_NDIS_MULTICAST_EXISTS: Final = -2144075766 +ERROR_NDIS_MULTICAST_NOT_FOUND: Final = -2144075765 +ERROR_NDIS_REQUEST_ABORTED: Final = -2144075764 +ERROR_NDIS_RESET_IN_PROGRESS: Final = -2144075763 +ERROR_NDIS_NOT_SUPPORTED: Final = -2144075589 +ERROR_NDIS_INVALID_PACKET: Final = -2144075761 +ERROR_NDIS_ADAPTER_NOT_READY: Final = -2144075759 +ERROR_NDIS_INVALID_LENGTH: Final = -2144075756 +ERROR_NDIS_INVALID_DATA: Final = -2144075755 +ERROR_NDIS_BUFFER_TOO_SHORT: Final = -2144075754 +ERROR_NDIS_INVALID_OID: Final = -2144075753 +ERROR_NDIS_ADAPTER_REMOVED: Final = -2144075752 +ERROR_NDIS_UNSUPPORTED_MEDIA: Final = -2144075751 +ERROR_NDIS_GROUP_ADDRESS_IN_USE: Final = -2144075750 +ERROR_NDIS_FILE_NOT_FOUND: Final = -2144075749 +ERROR_NDIS_ERROR_READING_FILE: Final = -2144075748 +ERROR_NDIS_ALREADY_MAPPED: Final = -2144075747 +ERROR_NDIS_RESOURCE_CONFLICT: Final = -2144075746 +ERROR_NDIS_MEDIA_DISCONNECTED: Final = -2144075745 +ERROR_NDIS_INVALID_ADDRESS: Final = -2144075742 +ERROR_NDIS_INVALID_DEVICE_REQUEST: Final = -2144075760 +ERROR_NDIS_PAUSED: Final = -2144075734 +ERROR_NDIS_INTERFACE_NOT_FOUND: Final = -2144075733 +ERROR_NDIS_UNSUPPORTED_REVISION: Final = -2144075732 +ERROR_NDIS_INVALID_PORT: Final = -2144075731 +ERROR_NDIS_INVALID_PORT_STATE: Final = -2144075730 +ERROR_NDIS_LOW_POWER_STATE: Final = -2144075729 +ERROR_NDIS_REINIT_REQUIRED: Final = -2144075728 +ERROR_NDIS_NO_QUEUES: Final = -2144075727 +ERROR_NDIS_DOT11_AUTO_CONFIG_ENABLED: Final = -2144067584 +ERROR_NDIS_DOT11_MEDIA_IN_USE: Final = -2144067583 +ERROR_NDIS_DOT11_POWER_STATE_INVALID: Final = -2144067582 +ERROR_NDIS_PM_WOL_PATTERN_LIST_FULL: Final = -2144067581 +ERROR_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL: Final = -2144067580 +ERROR_NDIS_DOT11_AP_CHANNEL_CURRENTLY_NOT_AVAILABLE: Final = -2144067579 +ERROR_NDIS_DOT11_AP_BAND_CURRENTLY_NOT_AVAILABLE: Final = -2144067578 +ERROR_NDIS_DOT11_AP_CHANNEL_NOT_ALLOWED: Final = -2144067577 +ERROR_NDIS_DOT11_AP_BAND_NOT_ALLOWED: Final = -2144067576 +ERROR_NDIS_INDICATION_REQUIRED: Final = 0x00340001 +ERROR_NDIS_OFFLOAD_POLICY: Final = -1070329841 +ERROR_NDIS_OFFLOAD_CONNECTION_REJECTED: Final = -1070329838 +ERROR_NDIS_OFFLOAD_PATH_REJECTED: Final = -1070329837 +ERROR_HV_INVALID_HYPERCALL_CODE: Final = -1070268414 +ERROR_HV_INVALID_HYPERCALL_INPUT: Final = -1070268413 +ERROR_HV_INVALID_ALIGNMENT: Final = -1070268412 +ERROR_HV_INVALID_PARAMETER: Final = -1070268411 +ERROR_HV_ACCESS_DENIED: Final = -1070268410 +ERROR_HV_INVALID_PARTITION_STATE: Final = -1070268409 +ERROR_HV_OPERATION_DENIED: Final = -1070268408 +ERROR_HV_UNKNOWN_PROPERTY: Final = -1070268407 +ERROR_HV_PROPERTY_VALUE_OUT_OF_RANGE: Final = -1070268406 +ERROR_HV_INSUFFICIENT_MEMORY: Final = -1070268405 +ERROR_HV_PARTITION_TOO_DEEP: Final = -1070268404 +ERROR_HV_INVALID_PARTITION_ID: Final = -1070268403 +ERROR_HV_INVALID_VP_INDEX: Final = -1070268402 +ERROR_HV_INVALID_PORT_ID: Final = -1070268399 +ERROR_HV_INVALID_CONNECTION_ID: Final = -1070268398 +ERROR_HV_INSUFFICIENT_BUFFERS: Final = -1070268397 +ERROR_HV_NOT_ACKNOWLEDGED: Final = -1070268396 +ERROR_HV_INVALID_VP_STATE: Final = -1070268395 +ERROR_HV_ACKNOWLEDGED: Final = -1070268394 +ERROR_HV_INVALID_SAVE_RESTORE_STATE: Final = -1070268393 +ERROR_HV_INVALID_SYNIC_STATE: Final = -1070268392 +ERROR_HV_OBJECT_IN_USE: Final = -1070268391 +ERROR_HV_INVALID_PROXIMITY_DOMAIN_INFO: Final = -1070268390 +ERROR_HV_NO_DATA: Final = -1070268389 +ERROR_HV_INACTIVE: Final = -1070268388 +ERROR_HV_NO_RESOURCES: Final = -1070268387 +ERROR_HV_FEATURE_UNAVAILABLE: Final = -1070268386 +ERROR_HV_INSUFFICIENT_BUFFER: Final = -1070268365 +ERROR_HV_INSUFFICIENT_DEVICE_DOMAINS: Final = -1070268360 +ERROR_HV_CPUID_FEATURE_VALIDATION: Final = -1070268356 +ERROR_HV_CPUID_XSAVE_FEATURE_VALIDATION: Final = -1070268355 +ERROR_HV_PROCESSOR_STARTUP_TIMEOUT: Final = -1070268354 +ERROR_HV_SMX_ENABLED: Final = -1070268353 +ERROR_HV_INVALID_LP_INDEX: Final = -1070268351 +ERROR_HV_INVALID_REGISTER_VALUE: Final = -1070268336 +ERROR_HV_INVALID_VTL_STATE: Final = -1070268335 +ERROR_HV_NX_NOT_DETECTED: Final = -1070268331 +ERROR_HV_INVALID_DEVICE_ID: Final = -1070268329 +ERROR_HV_INVALID_DEVICE_STATE: Final = -1070268328 +ERROR_HV_PENDING_PAGE_REQUESTS: Final = 0x00350059 +ERROR_HV_PAGE_REQUEST_INVALID: Final = -1070268320 +ERROR_HV_INVALID_CPU_GROUP_ID: Final = -1070268305 +ERROR_HV_INVALID_CPU_GROUP_STATE: Final = -1070268304 +ERROR_HV_OPERATION_FAILED: Final = -1070268303 +ERROR_HV_NOT_ALLOWED_WITH_NESTED_VIRT_ACTIVE: Final = -1070268302 +ERROR_HV_INSUFFICIENT_ROOT_MEMORY: Final = -1070268301 +ERROR_HV_EVENT_BUFFER_ALREADY_FREED: Final = -1070268300 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_MEMORY: Final = -1070268299 +ERROR_HV_DEVICE_NOT_IN_DOMAIN: Final = -1070268298 +ERROR_HV_NESTED_VM_EXIT: Final = -1070268297 +ERROR_HV_MSR_ACCESS_FAILED: Final = -1070268288 +ERROR_HV_INSUFFICIENT_MEMORY_MIRRORING: Final = -1070268287 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_MEMORY_MIRRORING: Final = -1070268286 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY: Final = -1070268285 +ERROR_HV_INSUFFICIENT_ROOT_MEMORY_MIRRORING: Final = -1070268284 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY_MIRRORING: Final = -1070268283 +ERROR_HV_NOT_PRESENT: Final = -1070264320 +ERROR_VID_DUPLICATE_HANDLER: Final = -1070137343 +ERROR_VID_TOO_MANY_HANDLERS: Final = -1070137342 +ERROR_VID_QUEUE_FULL: Final = -1070137341 +ERROR_VID_HANDLER_NOT_PRESENT: Final = -1070137340 +ERROR_VID_INVALID_OBJECT_NAME: Final = -1070137339 +ERROR_VID_PARTITION_NAME_TOO_LONG: Final = -1070137338 +ERROR_VID_MESSAGE_QUEUE_NAME_TOO_LONG: Final = -1070137337 +ERROR_VID_PARTITION_ALREADY_EXISTS: Final = -1070137336 +ERROR_VID_PARTITION_DOES_NOT_EXIST: Final = -1070137335 +ERROR_VID_PARTITION_NAME_NOT_FOUND: Final = -1070137334 +ERROR_VID_MESSAGE_QUEUE_ALREADY_EXISTS: Final = -1070137333 +ERROR_VID_EXCEEDED_MBP_ENTRY_MAP_LIMIT: Final = -1070137332 +ERROR_VID_MB_STILL_REFERENCED: Final = -1070137331 +ERROR_VID_CHILD_GPA_PAGE_SET_CORRUPTED: Final = -1070137330 +ERROR_VID_INVALID_NUMA_SETTINGS: Final = -1070137329 +ERROR_VID_INVALID_NUMA_NODE_INDEX: Final = -1070137328 +ERROR_VID_NOTIFICATION_QUEUE_ALREADY_ASSOCIATED: Final = -1070137327 +ERROR_VID_INVALID_MEMORY_BLOCK_HANDLE: Final = -1070137326 +ERROR_VID_PAGE_RANGE_OVERFLOW: Final = -1070137325 +ERROR_VID_INVALID_MESSAGE_QUEUE_HANDLE: Final = -1070137324 +ERROR_VID_INVALID_GPA_RANGE_HANDLE: Final = -1070137323 +ERROR_VID_NO_MEMORY_BLOCK_NOTIFICATION_QUEUE: Final = -1070137322 +ERROR_VID_MEMORY_BLOCK_LOCK_COUNT_EXCEEDED: Final = -1070137321 +ERROR_VID_INVALID_PPM_HANDLE: Final = -1070137320 +ERROR_VID_MBPS_ARE_LOCKED: Final = -1070137319 +ERROR_VID_MESSAGE_QUEUE_CLOSED: Final = -1070137318 +ERROR_VID_VIRTUAL_PROCESSOR_LIMIT_EXCEEDED: Final = -1070137317 +ERROR_VID_STOP_PENDING: Final = -1070137316 +ERROR_VID_INVALID_PROCESSOR_STATE: Final = -1070137315 +ERROR_VID_EXCEEDED_KM_CONTEXT_COUNT_LIMIT: Final = -1070137314 +ERROR_VID_KM_INTERFACE_ALREADY_INITIALIZED: Final = -1070137313 +ERROR_VID_MB_PROPERTY_ALREADY_SET_RESET: Final = -1070137312 +ERROR_VID_MMIO_RANGE_DESTROYED: Final = -1070137311 +ERROR_VID_INVALID_CHILD_GPA_PAGE_SET: Final = -1070137310 +ERROR_VID_RESERVE_PAGE_SET_IS_BEING_USED: Final = -1070137309 +ERROR_VID_RESERVE_PAGE_SET_TOO_SMALL: Final = -1070137308 +ERROR_VID_MBP_ALREADY_LOCKED_USING_RESERVED_PAGE: Final = -1070137307 +ERROR_VID_MBP_COUNT_EXCEEDED_LIMIT: Final = -1070137306 +ERROR_VID_SAVED_STATE_CORRUPT: Final = -1070137305 +ERROR_VID_SAVED_STATE_UNRECOGNIZED_ITEM: Final = -1070137304 +ERROR_VID_SAVED_STATE_INCOMPATIBLE: Final = -1070137303 +ERROR_VID_VTL_ACCESS_DENIED: Final = -1070137302 +ERROR_VID_INSUFFICIENT_RESOURCES_RESERVE: Final = -1070137301 +ERROR_VID_INSUFFICIENT_RESOURCES_PHYSICAL_BUFFER: Final = -1070137300 +ERROR_VID_INSUFFICIENT_RESOURCES_HV_DEPOSIT: Final = -1070137299 +ERROR_VID_MEMORY_TYPE_NOT_SUPPORTED: Final = -1070137298 +ERROR_VID_INSUFFICIENT_RESOURCES_WITHDRAW: Final = -1070137297 +ERROR_VID_PROCESS_ALREADY_SET: Final = -1070137296 +ERROR_VMCOMPUTE_TERMINATED_DURING_START: Final = -1070137088 +ERROR_VMCOMPUTE_IMAGE_MISMATCH: Final = -1070137087 +ERROR_VMCOMPUTE_HYPERV_NOT_INSTALLED: Final = -1070137086 +ERROR_VMCOMPUTE_OPERATION_PENDING: Final = -1070137085 +ERROR_VMCOMPUTE_TOO_MANY_NOTIFICATIONS: Final = -1070137084 +ERROR_VMCOMPUTE_INVALID_STATE: Final = -1070137083 +ERROR_VMCOMPUTE_UNEXPECTED_EXIT: Final = -1070137082 +ERROR_VMCOMPUTE_TERMINATED: Final = -1070137081 +ERROR_VMCOMPUTE_CONNECT_FAILED: Final = -1070137080 +ERROR_VMCOMPUTE_TIMEOUT: Final = -1070137079 +ERROR_VMCOMPUTE_CONNECTION_CLOSED: Final = -1070137078 +ERROR_VMCOMPUTE_UNKNOWN_MESSAGE: Final = -1070137077 +ERROR_VMCOMPUTE_UNSUPPORTED_PROTOCOL_VERSION: Final = -1070137076 +ERROR_VMCOMPUTE_INVALID_JSON: Final = -1070137075 +ERROR_VMCOMPUTE_SYSTEM_NOT_FOUND: Final = -1070137074 +ERROR_VMCOMPUTE_SYSTEM_ALREADY_EXISTS: Final = -1070137073 +ERROR_VMCOMPUTE_SYSTEM_ALREADY_STOPPED: Final = -1070137072 +ERROR_VMCOMPUTE_PROTOCOL_ERROR: Final = -1070137071 +ERROR_VMCOMPUTE_INVALID_LAYER: Final = -1070137070 +ERROR_VMCOMPUTE_WINDOWS_INSIDER_REQUIRED: Final = -1070137069 +HCS_E_TERMINATED_DURING_START: Final = -2143878912 +HCS_E_IMAGE_MISMATCH: Final = -2143878911 +HCS_E_HYPERV_NOT_INSTALLED: Final = -2143878910 +HCS_E_INVALID_STATE: Final = -2143878907 +HCS_E_UNEXPECTED_EXIT: Final = -2143878906 +HCS_E_TERMINATED: Final = -2143878905 +HCS_E_CONNECT_FAILED: Final = -2143878904 +HCS_E_CONNECTION_TIMEOUT: Final = -2143878903 +HCS_E_CONNECTION_CLOSED: Final = -2143878902 +HCS_E_UNKNOWN_MESSAGE: Final = -2143878901 +HCS_E_UNSUPPORTED_PROTOCOL_VERSION: Final = -2143878900 +HCS_E_INVALID_JSON: Final = -2143878899 +HCS_E_SYSTEM_NOT_FOUND: Final = -2143878898 +HCS_E_SYSTEM_ALREADY_EXISTS: Final = -2143878897 +HCS_E_SYSTEM_ALREADY_STOPPED: Final = -2143878896 +HCS_E_PROTOCOL_ERROR: Final = -2143878895 +HCS_E_INVALID_LAYER: Final = -2143878894 +HCS_E_WINDOWS_INSIDER_REQUIRED: Final = -2143878893 +HCS_E_SERVICE_NOT_AVAILABLE: Final = -2143878892 +HCS_E_OPERATION_NOT_STARTED: Final = -2143878891 +HCS_E_OPERATION_ALREADY_STARTED: Final = -2143878890 +HCS_E_OPERATION_PENDING: Final = -2143878889 +HCS_E_OPERATION_TIMEOUT: Final = -2143878888 +HCS_E_OPERATION_SYSTEM_CALLBACK_ALREADY_SET: Final = -2143878887 +HCS_E_OPERATION_RESULT_ALLOCATION_FAILED: Final = -2143878886 +HCS_E_ACCESS_DENIED: Final = -2143878885 +HCS_E_GUEST_CRITICAL_ERROR: Final = -2143878884 +HCS_E_PROCESS_INFO_NOT_AVAILABLE: Final = -2143878883 +HCS_E_SERVICE_DISCONNECT: Final = -2143878882 +HCS_E_PROCESS_ALREADY_STOPPED: Final = -2143878881 +HCS_E_SYSTEM_NOT_CONFIGURED_FOR_OPERATION: Final = -2143878880 +HCS_E_OPERATION_ALREADY_CANCELLED: Final = -2143878879 +ERROR_VNET_VIRTUAL_SWITCH_NAME_NOT_FOUND: Final = -1070136832 +ERROR_VID_REMOTE_NODE_PARENT_GPA_PAGES_USED: Final = -2143879167 +WHV_E_UNKNOWN_CAPABILITY: Final = -2143878400 +WHV_E_INSUFFICIENT_BUFFER: Final = -2143878399 +WHV_E_UNKNOWN_PROPERTY: Final = -2143878398 +WHV_E_UNSUPPORTED_HYPERVISOR_CONFIG: Final = -2143878397 +WHV_E_INVALID_PARTITION_CONFIG: Final = -2143878396 +WHV_E_GPA_RANGE_NOT_FOUND: Final = -2143878395 +WHV_E_VP_ALREADY_EXISTS: Final = -2143878394 +WHV_E_VP_DOES_NOT_EXIST: Final = -2143878393 +WHV_E_INVALID_VP_STATE: Final = -2143878392 +WHV_E_INVALID_VP_REGISTER_NAME: Final = -2143878391 +WHV_E_UNSUPPORTED_PROCESSOR_CONFIG: Final = -2143878384 +ERROR_VSMB_SAVED_STATE_FILE_NOT_FOUND: Final = -1070136320 +ERROR_VSMB_SAVED_STATE_CORRUPT: Final = -1070136319 +VM_SAVED_STATE_DUMP_E_PARTITION_STATE_NOT_FOUND: Final = -1070136064 +VM_SAVED_STATE_DUMP_E_GUEST_MEMORY_NOT_FOUND: Final = -1070136063 +VM_SAVED_STATE_DUMP_E_NO_VP_FOUND_IN_PARTITION_STATE: Final = -1070136062 +VM_SAVED_STATE_DUMP_E_NESTED_VIRTUALIZATION_NOT_SUPPORTED: Final = -1070136061 +VM_SAVED_STATE_DUMP_E_WINDOWS_KERNEL_IMAGE_NOT_FOUND: Final = -1070136060 +VM_SAVED_STATE_DUMP_E_VA_NOT_MAPPED: Final = -1070136059 +VM_SAVED_STATE_DUMP_E_INVALID_VP_STATE: Final = -1070136058 +VM_SAVED_STATE_DUMP_E_VP_VTL_NOT_ENABLED: Final = -1070136055 +ERROR_DM_OPERATION_LIMIT_EXCEEDED: Final = -1070135808 +ERROR_VOLMGR_INCOMPLETE_REGENERATION: Final = -2143813631 +ERROR_VOLMGR_INCOMPLETE_DISK_MIGRATION: Final = -2143813630 +ERROR_VOLMGR_DATABASE_FULL: Final = -1070071807 +ERROR_VOLMGR_DISK_CONFIGURATION_CORRUPTED: Final = -1070071806 +ERROR_VOLMGR_DISK_CONFIGURATION_NOT_IN_SYNC: Final = -1070071805 +ERROR_VOLMGR_PACK_CONFIG_UPDATE_FAILED: Final = -1070071804 +ERROR_VOLMGR_DISK_CONTAINS_NON_SIMPLE_VOLUME: Final = -1070071803 +ERROR_VOLMGR_DISK_DUPLICATE: Final = -1070071802 +ERROR_VOLMGR_DISK_DYNAMIC: Final = -1070071801 +ERROR_VOLMGR_DISK_ID_INVALID: Final = -1070071800 +ERROR_VOLMGR_DISK_INVALID: Final = -1070071799 +ERROR_VOLMGR_DISK_LAST_VOTER: Final = -1070071798 +ERROR_VOLMGR_DISK_LAYOUT_INVALID: Final = -1070071797 +ERROR_VOLMGR_DISK_LAYOUT_NON_BASIC_BETWEEN_BASIC_PARTITIONS: Final = -1070071796 +ERROR_VOLMGR_DISK_LAYOUT_NOT_CYLINDER_ALIGNED: Final = -1070071795 +ERROR_VOLMGR_DISK_LAYOUT_PARTITIONS_TOO_SMALL: Final = -1070071794 +ERROR_VOLMGR_DISK_LAYOUT_PRIMARY_BETWEEN_LOGICAL_PARTITIONS: Final = -1070071793 +ERROR_VOLMGR_DISK_LAYOUT_TOO_MANY_PARTITIONS: Final = -1070071792 +ERROR_VOLMGR_DISK_MISSING: Final = -1070071791 +ERROR_VOLMGR_DISK_NOT_EMPTY: Final = -1070071790 +ERROR_VOLMGR_DISK_NOT_ENOUGH_SPACE: Final = -1070071789 +ERROR_VOLMGR_DISK_REVECTORING_FAILED: Final = -1070071788 +ERROR_VOLMGR_DISK_SECTOR_SIZE_INVALID: Final = -1070071787 +ERROR_VOLMGR_DISK_SET_NOT_CONTAINED: Final = -1070071786 +ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_MEMBERS: Final = -1070071785 +ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_PLEXES: Final = -1070071784 +ERROR_VOLMGR_DYNAMIC_DISK_NOT_SUPPORTED: Final = -1070071783 +ERROR_VOLMGR_EXTENT_ALREADY_USED: Final = -1070071782 +ERROR_VOLMGR_EXTENT_NOT_CONTIGUOUS: Final = -1070071781 +ERROR_VOLMGR_EXTENT_NOT_IN_PUBLIC_REGION: Final = -1070071780 +ERROR_VOLMGR_EXTENT_NOT_SECTOR_ALIGNED: Final = -1070071779 +ERROR_VOLMGR_EXTENT_OVERLAPS_EBR_PARTITION: Final = -1070071778 +ERROR_VOLMGR_EXTENT_VOLUME_LENGTHS_DO_NOT_MATCH: Final = -1070071777 +ERROR_VOLMGR_FAULT_TOLERANT_NOT_SUPPORTED: Final = -1070071776 +ERROR_VOLMGR_INTERLEAVE_LENGTH_INVALID: Final = -1070071775 +ERROR_VOLMGR_MAXIMUM_REGISTERED_USERS: Final = -1070071774 +ERROR_VOLMGR_MEMBER_IN_SYNC: Final = -1070071773 +ERROR_VOLMGR_MEMBER_INDEX_DUPLICATE: Final = -1070071772 +ERROR_VOLMGR_MEMBER_INDEX_INVALID: Final = -1070071771 +ERROR_VOLMGR_MEMBER_MISSING: Final = -1070071770 +ERROR_VOLMGR_MEMBER_NOT_DETACHED: Final = -1070071769 +ERROR_VOLMGR_MEMBER_REGENERATING: Final = -1070071768 +ERROR_VOLMGR_ALL_DISKS_FAILED: Final = -1070071767 +ERROR_VOLMGR_NO_REGISTERED_USERS: Final = -1070071766 +ERROR_VOLMGR_NO_SUCH_USER: Final = -1070071765 +ERROR_VOLMGR_NOTIFICATION_RESET: Final = -1070071764 +ERROR_VOLMGR_NUMBER_OF_MEMBERS_INVALID: Final = -1070071763 +ERROR_VOLMGR_NUMBER_OF_PLEXES_INVALID: Final = -1070071762 +ERROR_VOLMGR_PACK_DUPLICATE: Final = -1070071761 +ERROR_VOLMGR_PACK_ID_INVALID: Final = -1070071760 +ERROR_VOLMGR_PACK_INVALID: Final = -1070071759 +ERROR_VOLMGR_PACK_NAME_INVALID: Final = -1070071758 +ERROR_VOLMGR_PACK_OFFLINE: Final = -1070071757 +ERROR_VOLMGR_PACK_HAS_QUORUM: Final = -1070071756 +ERROR_VOLMGR_PACK_WITHOUT_QUORUM: Final = -1070071755 +ERROR_VOLMGR_PARTITION_STYLE_INVALID: Final = -1070071754 +ERROR_VOLMGR_PARTITION_UPDATE_FAILED: Final = -1070071753 +ERROR_VOLMGR_PLEX_IN_SYNC: Final = -1070071752 +ERROR_VOLMGR_PLEX_INDEX_DUPLICATE: Final = -1070071751 +ERROR_VOLMGR_PLEX_INDEX_INVALID: Final = -1070071750 +ERROR_VOLMGR_PLEX_LAST_ACTIVE: Final = -1070071749 +ERROR_VOLMGR_PLEX_MISSING: Final = -1070071748 +ERROR_VOLMGR_PLEX_REGENERATING: Final = -1070071747 +ERROR_VOLMGR_PLEX_TYPE_INVALID: Final = -1070071746 +ERROR_VOLMGR_PLEX_NOT_RAID5: Final = -1070071745 +ERROR_VOLMGR_PLEX_NOT_SIMPLE: Final = -1070071744 +ERROR_VOLMGR_STRUCTURE_SIZE_INVALID: Final = -1070071743 +ERROR_VOLMGR_TOO_MANY_NOTIFICATION_REQUESTS: Final = -1070071742 +ERROR_VOLMGR_TRANSACTION_IN_PROGRESS: Final = -1070071741 +ERROR_VOLMGR_UNEXPECTED_DISK_LAYOUT_CHANGE: Final = -1070071740 +ERROR_VOLMGR_VOLUME_CONTAINS_MISSING_DISK: Final = -1070071739 +ERROR_VOLMGR_VOLUME_ID_INVALID: Final = -1070071738 +ERROR_VOLMGR_VOLUME_LENGTH_INVALID: Final = -1070071737 +ERROR_VOLMGR_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: Final = -1070071736 +ERROR_VOLMGR_VOLUME_NOT_MIRRORED: Final = -1070071735 +ERROR_VOLMGR_VOLUME_NOT_RETAINED: Final = -1070071734 +ERROR_VOLMGR_VOLUME_OFFLINE: Final = -1070071733 +ERROR_VOLMGR_VOLUME_RETAINED: Final = -1070071732 +ERROR_VOLMGR_NUMBER_OF_EXTENTS_INVALID: Final = -1070071731 +ERROR_VOLMGR_DIFFERENT_SECTOR_SIZE: Final = -1070071730 +ERROR_VOLMGR_BAD_BOOT_DISK: Final = -1070071729 +ERROR_VOLMGR_PACK_CONFIG_OFFLINE: Final = -1070071728 +ERROR_VOLMGR_PACK_CONFIG_ONLINE: Final = -1070071727 +ERROR_VOLMGR_NOT_PRIMARY_PACK: Final = -1070071726 +ERROR_VOLMGR_PACK_LOG_UPDATE_FAILED: Final = -1070071725 +ERROR_VOLMGR_NUMBER_OF_DISKS_IN_PLEX_INVALID: Final = -1070071724 +ERROR_VOLMGR_NUMBER_OF_DISKS_IN_MEMBER_INVALID: Final = -1070071723 +ERROR_VOLMGR_VOLUME_MIRRORED: Final = -1070071722 +ERROR_VOLMGR_PLEX_NOT_SIMPLE_SPANNED: Final = -1070071721 +ERROR_VOLMGR_NO_VALID_LOG_COPIES: Final = -1070071720 +ERROR_VOLMGR_PRIMARY_PACK_PRESENT: Final = -1070071719 +ERROR_VOLMGR_NUMBER_OF_DISKS_INVALID: Final = -1070071718 +ERROR_VOLMGR_MIRROR_NOT_SUPPORTED: Final = -1070071717 +ERROR_VOLMGR_RAID5_NOT_SUPPORTED: Final = -1070071716 +ERROR_BCD_NOT_ALL_ENTRIES_IMPORTED: Final = -2143748095 +ERROR_BCD_TOO_MANY_ELEMENTS: Final = -1070006270 +ERROR_BCD_NOT_ALL_ENTRIES_SYNCHRONIZED: Final = -2143748093 +ERROR_VHD_DRIVE_FOOTER_MISSING: Final = -1069940735 +ERROR_VHD_DRIVE_FOOTER_CHECKSUM_MISMATCH: Final = -1069940734 +ERROR_VHD_DRIVE_FOOTER_CORRUPT: Final = -1069940733 +ERROR_VHD_FORMAT_UNKNOWN: Final = -1069940732 +ERROR_VHD_FORMAT_UNSUPPORTED_VERSION: Final = -1069940731 +ERROR_VHD_SPARSE_HEADER_CHECKSUM_MISMATCH: Final = -1069940730 +ERROR_VHD_SPARSE_HEADER_UNSUPPORTED_VERSION: Final = -1069940729 +ERROR_VHD_SPARSE_HEADER_CORRUPT: Final = -1069940728 +ERROR_VHD_BLOCK_ALLOCATION_FAILURE: Final = -1069940727 +ERROR_VHD_BLOCK_ALLOCATION_TABLE_CORRUPT: Final = -1069940726 +ERROR_VHD_INVALID_BLOCK_SIZE: Final = -1069940725 +ERROR_VHD_BITMAP_MISMATCH: Final = -1069940724 +ERROR_VHD_PARENT_VHD_NOT_FOUND: Final = -1069940723 +ERROR_VHD_CHILD_PARENT_ID_MISMATCH: Final = -1069940722 +ERROR_VHD_CHILD_PARENT_TIMESTAMP_MISMATCH: Final = -1069940721 +ERROR_VHD_METADATA_READ_FAILURE: Final = -1069940720 +ERROR_VHD_METADATA_WRITE_FAILURE: Final = -1069940719 +ERROR_VHD_INVALID_SIZE: Final = -1069940718 +ERROR_VHD_INVALID_FILE_SIZE: Final = -1069940717 +ERROR_VIRTDISK_PROVIDER_NOT_FOUND: Final = -1069940716 +ERROR_VIRTDISK_NOT_VIRTUAL_DISK: Final = -1069940715 +ERROR_VHD_PARENT_VHD_ACCESS_DENIED: Final = -1069940714 +ERROR_VHD_CHILD_PARENT_SIZE_MISMATCH: Final = -1069940713 +ERROR_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED: Final = -1069940712 +ERROR_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT: Final = -1069940711 +ERROR_VIRTUAL_DISK_LIMITATION: Final = -1069940710 +ERROR_VHD_INVALID_TYPE: Final = -1069940709 +ERROR_VHD_INVALID_STATE: Final = -1069940708 +ERROR_VIRTDISK_UNSUPPORTED_DISK_SECTOR_SIZE: Final = -1069940707 +ERROR_VIRTDISK_DISK_ALREADY_OWNED: Final = -1069940706 +ERROR_VIRTDISK_DISK_ONLINE_AND_WRITABLE: Final = -1069940705 +ERROR_CTLOG_TRACKING_NOT_INITIALIZED: Final = -1069940704 +ERROR_CTLOG_LOGFILE_SIZE_EXCEEDED_MAXSIZE: Final = -1069940703 +ERROR_CTLOG_VHD_CHANGED_OFFLINE: Final = -1069940702 +ERROR_CTLOG_INVALID_TRACKING_STATE: Final = -1069940701 +ERROR_CTLOG_INCONSISTENT_TRACKING_FILE: Final = -1069940700 +ERROR_VHD_RESIZE_WOULD_TRUNCATE_DATA: Final = -1069940699 +ERROR_VHD_COULD_NOT_COMPUTE_MINIMUM_VIRTUAL_SIZE: Final = -1069940698 +ERROR_VHD_ALREADY_AT_OR_BELOW_MINIMUM_VIRTUAL_SIZE: Final = -1069940697 +ERROR_VHD_METADATA_FULL: Final = -1069940696 +ERROR_VHD_INVALID_CHANGE_TRACKING_ID: Final = -1069940695 +ERROR_VHD_CHANGE_TRACKING_DISABLED: Final = -1069940694 +ERROR_VHD_MISSING_CHANGE_TRACKING_INFORMATION: Final = -1069940688 +ERROR_VHD_UNEXPECTED_ID: Final = -1069940684 +ERROR_QUERY_STORAGE_ERROR: Final = -2143682559 +HCN_E_NETWORK_NOT_FOUND: Final = -2143617023 +HCN_E_ENDPOINT_NOT_FOUND: Final = -2143617022 +HCN_E_LAYER_NOT_FOUND: Final = -2143617021 +HCN_E_SWITCH_NOT_FOUND: Final = -2143617020 +HCN_E_SUBNET_NOT_FOUND: Final = -2143617019 +HCN_E_ADAPTER_NOT_FOUND: Final = -2143617018 +HCN_E_PORT_NOT_FOUND: Final = -2143617017 +HCN_E_POLICY_NOT_FOUND: Final = -2143617016 +HCN_E_VFP_PORTSETTING_NOT_FOUND: Final = -2143617015 +HCN_E_INVALID_NETWORK: Final = -2143617014 +HCN_E_INVALID_NETWORK_TYPE: Final = -2143617013 +HCN_E_INVALID_ENDPOINT: Final = -2143617012 +HCN_E_INVALID_POLICY: Final = -2143617011 +HCN_E_INVALID_POLICY_TYPE: Final = -2143617010 +HCN_E_INVALID_REMOTE_ENDPOINT_OPERATION: Final = -2143617009 +HCN_E_NETWORK_ALREADY_EXISTS: Final = -2143617008 +HCN_E_LAYER_ALREADY_EXISTS: Final = -2143617007 +HCN_E_POLICY_ALREADY_EXISTS: Final = -2143617006 +HCN_E_PORT_ALREADY_EXISTS: Final = -2143617005 +HCN_E_ENDPOINT_ALREADY_ATTACHED: Final = -2143617004 +HCN_E_REQUEST_UNSUPPORTED: Final = -2143617003 +HCN_E_MAPPING_NOT_SUPPORTED: Final = -2143617002 +HCN_E_DEGRADED_OPERATION: Final = -2143617001 +HCN_E_SHARED_SWITCH_MODIFICATION: Final = -2143617000 +HCN_E_GUID_CONVERSION_FAILURE: Final = -2143616999 +HCN_E_REGKEY_FAILURE: Final = -2143616998 +HCN_E_INVALID_JSON: Final = -2143616997 +HCN_E_INVALID_JSON_REFERENCE: Final = -2143616996 +HCN_E_ENDPOINT_SHARING_DISABLED: Final = -2143616995 +HCN_E_INVALID_IP: Final = -2143616994 +HCN_E_SWITCH_EXTENSION_NOT_FOUND: Final = -2143616993 +HCN_E_MANAGER_STOPPED: Final = -2143616992 +GCN_E_MODULE_NOT_FOUND: Final = -2143616991 +GCN_E_NO_REQUEST_HANDLERS: Final = -2143616990 +GCN_E_REQUEST_UNSUPPORTED: Final = -2143616989 +GCN_E_RUNTIMEKEYS_FAILED: Final = -2143616988 +GCN_E_NETADAPTER_TIMEOUT: Final = -2143616987 +GCN_E_NETADAPTER_NOT_FOUND: Final = -2143616986 +GCN_E_NETCOMPARTMENT_NOT_FOUND: Final = -2143616985 +GCN_E_NETINTERFACE_NOT_FOUND: Final = -2143616984 +GCN_E_DEFAULTNAMESPACE_EXISTS: Final = -2143616983 +HCN_E_ICS_DISABLED: Final = -2143616982 +HCN_E_ENDPOINT_NAMESPACE_ALREADY_EXISTS: Final = -2143616981 +HCN_E_ENTITY_HAS_REFERENCES: Final = -2143616980 +HCN_E_INVALID_INTERNAL_PORT: Final = -2143616979 +HCN_E_NAMESPACE_ATTACH_FAILED: Final = -2143616978 +HCN_E_ADDR_INVALID_OR_RESERVED: Final = -2143616977 +HCN_E_INVALID_PREFIX: Final = -2143616976 +HCN_E_OBJECT_USED_AFTER_UNLOAD: Final = -2143616975 +HCN_E_INVALID_SUBNET: Final = -2143616974 +HCN_E_INVALID_IP_SUBNET: Final = -2143616973 +HCN_E_ENDPOINT_NOT_ATTACHED: Final = -2143616972 +HCN_E_ENDPOINT_NOT_LOCAL: Final = -2143616971 +HCN_INTERFACEPARAMETERS_ALREADY_APPLIED: Final = -2143616970 +HCN_E_VFP_NOT_ALLOWED: Final = -2143616969 +SDIAG_E_CANCELLED: Final = -2143551232 +SDIAG_E_SCRIPT: Final = -2143551231 +SDIAG_E_POWERSHELL: Final = -2143551230 +SDIAG_E_MANAGEDHOST: Final = -2143551229 +SDIAG_E_NOVERIFIER: Final = -2143551228 +SDIAG_S_CANNOTRUN: Final = 0x003C0105 +SDIAG_E_DISABLED: Final = -2143551226 +SDIAG_E_TRUST: Final = -2143551225 +SDIAG_E_CANNOTRUN: Final = -2143551224 +SDIAG_E_VERSION: Final = -2143551223 +SDIAG_E_RESOURCE: Final = -2143551222 +SDIAG_E_ROOTCAUSE: Final = -2143551221 +WPN_E_CHANNEL_CLOSED: Final = -2143420160 +WPN_E_CHANNEL_REQUEST_NOT_COMPLETE: Final = -2143420159 +WPN_E_INVALID_APP: Final = -2143420158 +WPN_E_OUTSTANDING_CHANNEL_REQUEST: Final = -2143420157 +WPN_E_DUPLICATE_CHANNEL: Final = -2143420156 +WPN_E_PLATFORM_UNAVAILABLE: Final = -2143420155 +WPN_E_NOTIFICATION_POSTED: Final = -2143420154 +WPN_E_NOTIFICATION_HIDDEN: Final = -2143420153 +WPN_E_NOTIFICATION_NOT_POSTED: Final = -2143420152 +WPN_E_CLOUD_DISABLED: Final = -2143420151 +WPN_E_CLOUD_INCAPABLE: Final = -2143420144 +WPN_E_CLOUD_AUTH_UNAVAILABLE: Final = -2143420134 +WPN_E_CLOUD_SERVICE_UNAVAILABLE: Final = -2143420133 +WPN_E_FAILED_LOCK_SCREEN_UPDATE_INTIALIZATION: Final = -2143420132 +WPN_E_NOTIFICATION_DISABLED: Final = -2143420143 +WPN_E_NOTIFICATION_INCAPABLE: Final = -2143420142 +WPN_E_INTERNET_INCAPABLE: Final = -2143420141 +WPN_E_NOTIFICATION_TYPE_DISABLED: Final = -2143420140 +WPN_E_NOTIFICATION_SIZE: Final = -2143420139 +WPN_E_TAG_SIZE: Final = -2143420138 +WPN_E_ACCESS_DENIED: Final = -2143420137 +WPN_E_DUPLICATE_REGISTRATION: Final = -2143420136 +WPN_E_PUSH_NOTIFICATION_INCAPABLE: Final = -2143420135 +WPN_E_DEV_ID_SIZE: Final = -2143420128 +WPN_E_TAG_ALPHANUMERIC: Final = -2143420118 +WPN_E_INVALID_HTTP_STATUS_CODE: Final = -2143420117 +WPN_E_OUT_OF_SESSION: Final = -2143419904 +WPN_E_POWER_SAVE: Final = -2143419903 +WPN_E_IMAGE_NOT_FOUND_IN_CACHE: Final = -2143419902 +WPN_E_ALL_URL_NOT_COMPLETED: Final = -2143419901 +WPN_E_INVALID_CLOUD_IMAGE: Final = -2143419900 +WPN_E_NOTIFICATION_ID_MATCHED: Final = -2143419899 +WPN_E_CALLBACK_ALREADY_REGISTERED: Final = -2143419898 +WPN_E_TOAST_NOTIFICATION_DROPPED: Final = -2143419897 +WPN_E_STORAGE_LOCKED: Final = -2143419896 +WPN_E_GROUP_SIZE: Final = -2143419895 +WPN_E_GROUP_ALPHANUMERIC: Final = -2143419894 +WPN_E_CLOUD_DISABLED_FOR_APP: Final = -2143419893 +E_MBN_CONTEXT_NOT_ACTIVATED: Final = -2141945343 +E_MBN_BAD_SIM: Final = -2141945342 +E_MBN_DATA_CLASS_NOT_AVAILABLE: Final = -2141945341 +E_MBN_INVALID_ACCESS_STRING: Final = -2141945340 +E_MBN_MAX_ACTIVATED_CONTEXTS: Final = -2141945339 +E_MBN_PACKET_SVC_DETACHED: Final = -2141945338 +E_MBN_PROVIDER_NOT_VISIBLE: Final = -2141945337 +E_MBN_RADIO_POWER_OFF: Final = -2141945336 +E_MBN_SERVICE_NOT_ACTIVATED: Final = -2141945335 +E_MBN_SIM_NOT_INSERTED: Final = -2141945334 +E_MBN_VOICE_CALL_IN_PROGRESS: Final = -2141945333 +E_MBN_INVALID_CACHE: Final = -2141945332 +E_MBN_NOT_REGISTERED: Final = -2141945331 +E_MBN_PROVIDERS_NOT_FOUND: Final = -2141945330 +E_MBN_PIN_NOT_SUPPORTED: Final = -2141945329 +E_MBN_PIN_REQUIRED: Final = -2141945328 +E_MBN_PIN_DISABLED: Final = -2141945327 +E_MBN_FAILURE: Final = -2141945326 +E_MBN_INVALID_PROFILE: Final = -2141945320 +E_MBN_DEFAULT_PROFILE_EXIST: Final = -2141945319 +E_MBN_SMS_ENCODING_NOT_SUPPORTED: Final = -2141945312 +E_MBN_SMS_FILTER_NOT_SUPPORTED: Final = -2141945311 +E_MBN_SMS_INVALID_MEMORY_INDEX: Final = -2141945310 +E_MBN_SMS_LANG_NOT_SUPPORTED: Final = -2141945309 +E_MBN_SMS_MEMORY_FAILURE: Final = -2141945308 +E_MBN_SMS_NETWORK_TIMEOUT: Final = -2141945307 +E_MBN_SMS_UNKNOWN_SMSC_ADDRESS: Final = -2141945306 +E_MBN_SMS_FORMAT_NOT_SUPPORTED: Final = -2141945305 +E_MBN_SMS_OPERATION_NOT_ALLOWED: Final = -2141945304 +E_MBN_SMS_MEMORY_FULL: Final = -2141945303 +PEER_E_IPV6_NOT_INSTALLED: Final = -2140995583 +PEER_E_NOT_INITIALIZED: Final = -2140995582 +PEER_E_CANNOT_START_SERVICE: Final = -2140995581 +PEER_E_NOT_LICENSED: Final = -2140995580 +PEER_E_INVALID_GRAPH: Final = -2140995568 +PEER_E_DBNAME_CHANGED: Final = -2140995567 +PEER_E_DUPLICATE_GRAPH: Final = -2140995566 +PEER_E_GRAPH_NOT_READY: Final = -2140995565 +PEER_E_GRAPH_SHUTTING_DOWN: Final = -2140995564 +PEER_E_GRAPH_IN_USE: Final = -2140995563 +PEER_E_INVALID_DATABASE: Final = -2140995562 +PEER_E_TOO_MANY_ATTRIBUTES: Final = -2140995561 +PEER_E_CONNECTION_NOT_FOUND: Final = -2140995325 +PEER_E_CONNECT_SELF: Final = -2140995322 +PEER_E_ALREADY_LISTENING: Final = -2140995321 +PEER_E_NODE_NOT_FOUND: Final = -2140995320 +PEER_E_CONNECTION_FAILED: Final = -2140995319 +PEER_E_CONNECTION_NOT_AUTHENTICATED: Final = -2140995318 +PEER_E_CONNECTION_REFUSED: Final = -2140995317 +PEER_E_CLASSIFIER_TOO_LONG: Final = -2140995071 +PEER_E_TOO_MANY_IDENTITIES: Final = -2140995070 +PEER_E_NO_KEY_ACCESS: Final = -2140995069 +PEER_E_GROUPS_EXIST: Final = -2140995068 +PEER_E_RECORD_NOT_FOUND: Final = -2140994815 +PEER_E_DATABASE_ACCESSDENIED: Final = -2140994814 +PEER_E_DBINITIALIZATION_FAILED: Final = -2140994813 +PEER_E_MAX_RECORD_SIZE_EXCEEDED: Final = -2140994812 +PEER_E_DATABASE_ALREADY_PRESENT: Final = -2140994811 +PEER_E_DATABASE_NOT_PRESENT: Final = -2140994810 +PEER_E_IDENTITY_NOT_FOUND: Final = -2140994559 +PEER_E_EVENT_HANDLE_NOT_FOUND: Final = -2140994303 +PEER_E_INVALID_SEARCH: Final = -2140994047 +PEER_E_INVALID_ATTRIBUTES: Final = -2140994046 +PEER_E_INVITATION_NOT_TRUSTED: Final = -2140993791 +PEER_E_CHAIN_TOO_LONG: Final = -2140993789 +PEER_E_INVALID_TIME_PERIOD: Final = -2140993787 +PEER_E_CIRCULAR_CHAIN_DETECTED: Final = -2140993786 +PEER_E_CERT_STORE_CORRUPTED: Final = -2140993535 +PEER_E_NO_CLOUD: Final = -2140991487 +PEER_E_CLOUD_NAME_AMBIGUOUS: Final = -2140991483 +PEER_E_INVALID_RECORD: Final = -2140987376 +PEER_E_NOT_AUTHORIZED: Final = -2140987360 +PEER_E_PASSWORD_DOES_NOT_MEET_POLICY: Final = -2140987359 +PEER_E_DEFERRED_VALIDATION: Final = -2140987344 +PEER_E_INVALID_GROUP_PROPERTIES: Final = -2140987328 +PEER_E_INVALID_PEER_NAME: Final = -2140987312 +PEER_E_INVALID_CLASSIFIER: Final = -2140987296 +PEER_E_INVALID_FRIENDLY_NAME: Final = -2140987280 +PEER_E_INVALID_ROLE_PROPERTY: Final = -2140987279 +PEER_E_INVALID_CLASSIFIER_PROPERTY: Final = -2140987278 +PEER_E_INVALID_RECORD_EXPIRATION: Final = -2140987264 +PEER_E_INVALID_CREDENTIAL_INFO: Final = -2140987263 +PEER_E_INVALID_CREDENTIAL: Final = -2140987262 +PEER_E_INVALID_RECORD_SIZE: Final = -2140987261 +PEER_E_UNSUPPORTED_VERSION: Final = -2140987248 +PEER_E_GROUP_NOT_READY: Final = -2140987247 +PEER_E_GROUP_IN_USE: Final = -2140987246 +PEER_E_INVALID_GROUP: Final = -2140987245 +PEER_E_NO_MEMBERS_FOUND: Final = -2140987244 +PEER_E_NO_MEMBER_CONNECTIONS: Final = -2140987243 +PEER_E_UNABLE_TO_LISTEN: Final = -2140987242 +PEER_E_IDENTITY_DELETED: Final = -2140987232 +PEER_E_SERVICE_NOT_AVAILABLE: Final = -2140987231 +PEER_E_CONTACT_NOT_FOUND: Final = -2140971007 +PEER_S_GRAPH_DATA_CREATED: Final = 0x00630001 +PEER_S_NO_EVENT_DATA: Final = 0x00630002 +PEER_S_ALREADY_CONNECTED: Final = 0x00632000 +PEER_S_SUBSCRIPTION_EXISTS: Final = 0x00636000 +PEER_S_NO_CONNECTIVITY: Final = 0x00630005 +PEER_S_ALREADY_A_MEMBER: Final = 0x00630006 +PEER_E_CANNOT_CONVERT_PEER_NAME: Final = -2140979199 +PEER_E_INVALID_PEER_HOST_NAME: Final = -2140979198 +PEER_E_NO_MORE: Final = -2140979197 +PEER_E_PNRP_DUPLICATE_PEER_NAME: Final = -2140979195 +PEER_E_INVITE_CANCELLED: Final = -2140966912 +PEER_E_INVITE_RESPONSE_NOT_AVAILABLE: Final = -2140966911 +PEER_E_NOT_SIGNED_IN: Final = -2140966909 +PEER_E_PRIVACY_DECLINED: Final = -2140966908 +PEER_E_TIMEOUT: Final = -2140966907 +PEER_E_INVALID_ADDRESS: Final = -2140966905 +PEER_E_FW_EXCEPTION_DISABLED: Final = -2140966904 +PEER_E_FW_BLOCKED_BY_POLICY: Final = -2140966903 +PEER_E_FW_BLOCKED_BY_SHIELDS_UP: Final = -2140966902 +PEER_E_FW_DECLINED: Final = -2140966901 +UI_E_CREATE_FAILED: Final = -2144731135 +UI_E_SHUTDOWN_CALLED: Final = -2144731134 +UI_E_ILLEGAL_REENTRANCY: Final = -2144731133 +UI_E_OBJECT_SEALED: Final = -2144731132 +UI_E_VALUE_NOT_SET: Final = -2144731131 +UI_E_VALUE_NOT_DETERMINED: Final = -2144731130 +UI_E_INVALID_OUTPUT: Final = -2144731129 +UI_E_BOOLEAN_EXPECTED: Final = -2144731128 +UI_E_DIFFERENT_OWNER: Final = -2144731127 +UI_E_AMBIGUOUS_MATCH: Final = -2144731126 +UI_E_FP_OVERFLOW: Final = -2144731125 +UI_E_WRONG_THREAD: Final = -2144731124 +UI_E_STORYBOARD_ACTIVE: Final = -2144730879 +UI_E_STORYBOARD_NOT_PLAYING: Final = -2144730878 +UI_E_START_KEYFRAME_AFTER_END: Final = -2144730877 +UI_E_END_KEYFRAME_NOT_DETERMINED: Final = -2144730876 +UI_E_LOOPS_OVERLAP: Final = -2144730875 +UI_E_TRANSITION_ALREADY_USED: Final = -2144730874 +UI_E_TRANSITION_NOT_IN_STORYBOARD: Final = -2144730873 +UI_E_TRANSITION_ECLIPSED: Final = -2144730872 +UI_E_TIME_BEFORE_LAST_UPDATE: Final = -2144730871 +UI_E_TIMER_CLIENT_ALREADY_CONNECTED: Final = -2144730870 +UI_E_INVALID_DIMENSION: Final = -2144730869 +UI_E_PRIMITIVE_OUT_OF_BOUNDS: Final = -2144730868 +UI_E_WINDOW_CLOSED: Final = -2144730623 +E_BLUETOOTH_ATT_INVALID_HANDLE: Final = -2140864511 +E_BLUETOOTH_ATT_READ_NOT_PERMITTED: Final = -2140864510 +E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED: Final = -2140864509 +E_BLUETOOTH_ATT_INVALID_PDU: Final = -2140864508 +E_BLUETOOTH_ATT_INSUFFICIENT_AUTHENTICATION: Final = -2140864507 +E_BLUETOOTH_ATT_REQUEST_NOT_SUPPORTED: Final = -2140864506 +E_BLUETOOTH_ATT_INVALID_OFFSET: Final = -2140864505 +E_BLUETOOTH_ATT_INSUFFICIENT_AUTHORIZATION: Final = -2140864504 +E_BLUETOOTH_ATT_PREPARE_QUEUE_FULL: Final = -2140864503 +E_BLUETOOTH_ATT_ATTRIBUTE_NOT_FOUND: Final = -2140864502 +E_BLUETOOTH_ATT_ATTRIBUTE_NOT_LONG: Final = -2140864501 +E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION_KEY_SIZE: Final = -2140864500 +E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH: Final = -2140864499 +E_BLUETOOTH_ATT_UNLIKELY: Final = -2140864498 +E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION: Final = -2140864497 +E_BLUETOOTH_ATT_UNSUPPORTED_GROUP_TYPE: Final = -2140864496 +E_BLUETOOTH_ATT_INSUFFICIENT_RESOURCES: Final = -2140864495 +E_BLUETOOTH_ATT_UNKNOWN_ERROR: Final = -2140860416 +E_AUDIO_ENGINE_NODE_NOT_FOUND: Final = -2140798975 +E_HDAUDIO_EMPTY_CONNECTION_LIST: Final = -2140798974 +E_HDAUDIO_CONNECTION_LIST_NOT_SUPPORTED: Final = -2140798973 +E_HDAUDIO_NO_LOGICAL_DEVICES_CREATED: Final = -2140798972 +E_HDAUDIO_NULL_LINKED_LIST_ENTRY: Final = -2140798971 +STATEREPOSITORY_E_CONCURRENCY_LOCKING_FAILURE: Final = -2140733439 +STATEREPOSITORY_E_STATEMENT_INPROGRESS: Final = -2140733438 +STATEREPOSITORY_E_CONFIGURATION_INVALID: Final = -2140733437 +STATEREPOSITORY_E_UNKNOWN_SCHEMA_VERSION: Final = -2140733436 +STATEREPOSITORY_ERROR_DICTIONARY_CORRUPTED: Final = -2140733435 +STATEREPOSITORY_E_BLOCKED: Final = -2140733434 +STATEREPOSITORY_E_BUSY_RETRY: Final = -2140733433 +STATEREPOSITORY_E_BUSY_RECOVERY_RETRY: Final = -2140733432 +STATEREPOSITORY_E_LOCKED_RETRY: Final = -2140733431 +STATEREPOSITORY_E_LOCKED_SHAREDCACHE_RETRY: Final = -2140733430 +STATEREPOSITORY_E_TRANSACTION_REQUIRED: Final = -2140733429 +STATEREPOSITORY_E_BUSY_TIMEOUT_EXCEEDED: Final = -2140733428 +STATEREPOSITORY_E_BUSY_RECOVERY_TIMEOUT_EXCEEDED: Final = -2140733427 +STATEREPOSITORY_E_LOCKED_TIMEOUT_EXCEEDED: Final = -2140733426 +STATEREPOSITORY_E_LOCKED_SHAREDCACHE_TIMEOUT_EXCEEDED: Final = -2140733425 +STATEREPOSITORY_E_SERVICE_STOP_IN_PROGRESS: Final = -2140733424 +STATEREPOSTORY_E_NESTED_TRANSACTION_NOT_SUPPORTED: Final = -2140733423 +STATEREPOSITORY_ERROR_CACHE_CORRUPTED: Final = -2140733422 +STATEREPOSITORY_TRANSACTION_CALLER_ID_CHANGED: Final = 0x00670013 +STATEREPOSITORY_TRANSACTION_IN_PROGRESS: Final = -2140733420 +STATEREPOSITORY_E_CACHE_NOT_INIITALIZED: Final = -2140733419 +STATEREPOSITORY_E_DEPENDENCY_NOT_RESOLVED: Final = -2140733418 +ERROR_SPACES_POOL_WAS_DELETED: Final = 0x00E70001 +ERROR_SPACES_FAULT_DOMAIN_TYPE_INVALID: Final = -2132344831 +ERROR_SPACES_INTERNAL_ERROR: Final = -2132344830 +ERROR_SPACES_RESILIENCY_TYPE_INVALID: Final = -2132344829 +ERROR_SPACES_DRIVE_SECTOR_SIZE_INVALID: Final = -2132344828 +ERROR_SPACES_DRIVE_REDUNDANCY_INVALID: Final = -2132344826 +ERROR_SPACES_NUMBER_OF_DATA_COPIES_INVALID: Final = -2132344825 +ERROR_SPACES_PARITY_LAYOUT_INVALID: Final = -2132344824 +ERROR_SPACES_INTERLEAVE_LENGTH_INVALID: Final = -2132344823 +ERROR_SPACES_NUMBER_OF_COLUMNS_INVALID: Final = -2132344822 +ERROR_SPACES_NOT_ENOUGH_DRIVES: Final = -2132344821 +ERROR_SPACES_EXTENDED_ERROR: Final = -2132344820 +ERROR_SPACES_PROVISIONING_TYPE_INVALID: Final = -2132344819 +ERROR_SPACES_ALLOCATION_SIZE_INVALID: Final = -2132344818 +ERROR_SPACES_ENCLOSURE_AWARE_INVALID: Final = -2132344817 +ERROR_SPACES_WRITE_CACHE_SIZE_INVALID: Final = -2132344816 +ERROR_SPACES_NUMBER_OF_GROUPS_INVALID: Final = -2132344815 +ERROR_SPACES_DRIVE_OPERATIONAL_STATE_INVALID: Final = -2132344814 +ERROR_SPACES_ENTRY_INCOMPLETE: Final = -2132344813 +ERROR_SPACES_ENTRY_INVALID: Final = -2132344812 +ERROR_SPACES_UPDATE_COLUMN_STATE: Final = -2132344811 +ERROR_SPACES_MAP_REQUIRED: Final = -2132344810 +ERROR_SPACES_UNSUPPORTED_VERSION: Final = -2132344809 +ERROR_SPACES_CORRUPT_METADATA: Final = -2132344808 +ERROR_SPACES_DRT_FULL: Final = -2132344807 +ERROR_SPACES_INCONSISTENCY: Final = -2132344806 +ERROR_SPACES_LOG_NOT_READY: Final = -2132344805 +ERROR_SPACES_NO_REDUNDANCY: Final = -2132344804 +ERROR_SPACES_DRIVE_NOT_READY: Final = -2132344803 +ERROR_SPACES_DRIVE_SPLIT: Final = -2132344802 +ERROR_SPACES_DRIVE_LOST_DATA: Final = -2132344801 +ERROR_SPACES_MARK_DIRTY: Final = -2132344800 +ERROR_SPACES_FLUSH_METADATA: Final = -2132344795 +ERROR_SPACES_CACHE_FULL: Final = -2132344794 +ERROR_SPACES_REPAIR_IN_PROGRESS: Final = -2132344793 +ERROR_VOLSNAP_BOOTFILE_NOT_VALID: Final = -2138963967 +ERROR_VOLSNAP_ACTIVATION_TIMEOUT: Final = -2138963966 +ERROR_VOLSNAP_NO_BYPASSIO_WITH_SNAPSHOT: Final = -2138963965 +ERROR_TIERING_NOT_SUPPORTED_ON_VOLUME: Final = -2138898431 +ERROR_TIERING_VOLUME_DISMOUNT_IN_PROGRESS: Final = -2138898430 +ERROR_TIERING_STORAGE_TIER_NOT_FOUND: Final = -2138898429 +ERROR_TIERING_INVALID_FILE_ID: Final = -2138898428 +ERROR_TIERING_WRONG_CLUSTER_NODE: Final = -2138898427 +ERROR_TIERING_ALREADY_PROCESSING: Final = -2138898426 +ERROR_TIERING_CANNOT_PIN_OBJECT: Final = -2138898425 +ERROR_TIERING_FILE_IS_NOT_PINNED: Final = -2138898424 +ERROR_NOT_A_TIERED_VOLUME: Final = -2138898423 +ERROR_ATTRIBUTE_NOT_PRESENT: Final = -2138898422 +ERROR_SECCORE_INVALID_COMMAND: Final = -1058537472 +ERROR_NO_APPLICABLE_APP_LICENSES_FOUND: Final = -1058406399 +ERROR_CLIP_LICENSE_NOT_FOUND: Final = -1058406398 +ERROR_CLIP_DEVICE_LICENSE_MISSING: Final = -1058406397 +ERROR_CLIP_LICENSE_INVALID_SIGNATURE: Final = -1058406396 +ERROR_CLIP_KEYHOLDER_LICENSE_MISSING_OR_INVALID: Final = -1058406395 +ERROR_CLIP_LICENSE_EXPIRED: Final = -1058406394 +ERROR_CLIP_LICENSE_SIGNED_BY_UNKNOWN_SOURCE: Final = -1058406393 +ERROR_CLIP_LICENSE_NOT_SIGNED: Final = -1058406392 +ERROR_CLIP_LICENSE_HARDWARE_ID_OUT_OF_TOLERANCE: Final = -1058406391 +ERROR_CLIP_LICENSE_DEVICE_ID_MISMATCH: Final = -1058406390 +DXGI_STATUS_OCCLUDED: Final = 0x087A0001 +DXGI_STATUS_CLIPPED: Final = 0x087A0002 +DXGI_STATUS_NO_REDIRECTION: Final = 0x087A0004 +DXGI_STATUS_NO_DESKTOP_ACCESS: Final = 0x087A0005 +DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: Final = 0x087A0006 +DXGI_STATUS_MODE_CHANGED: Final = 0x087A0007 +DXGI_STATUS_MODE_CHANGE_IN_PROGRESS: Final = 0x087A0008 +DXGI_ERROR_INVALID_CALL: Final = -2005270527 +DXGI_ERROR_NOT_FOUND: Final = -2005270526 +DXGI_ERROR_MORE_DATA: Final = -2005270525 +DXGI_ERROR_UNSUPPORTED: Final = -2005270524 +DXGI_ERROR_DEVICE_REMOVED: Final = -2005270523 +DXGI_ERROR_DEVICE_HUNG: Final = -2005270522 +DXGI_ERROR_DEVICE_RESET: Final = -2005270521 +DXGI_ERROR_WAS_STILL_DRAWING: Final = -2005270518 +DXGI_ERROR_FRAME_STATISTICS_DISJOINT: Final = -2005270517 +DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: Final = -2005270516 +DXGI_ERROR_DRIVER_INTERNAL_ERROR: Final = -2005270496 +DXGI_ERROR_NONEXCLUSIVE: Final = -2005270495 +DXGI_ERROR_NOT_CURRENTLY_AVAILABLE: Final = -2005270494 +DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED: Final = -2005270493 +DXGI_ERROR_REMOTE_OUTOFMEMORY: Final = -2005270492 +DXGI_ERROR_ACCESS_LOST: Final = -2005270490 +DXGI_ERROR_WAIT_TIMEOUT: Final = -2005270489 +DXGI_ERROR_SESSION_DISCONNECTED: Final = -2005270488 +DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE: Final = -2005270487 +DXGI_ERROR_CANNOT_PROTECT_CONTENT: Final = -2005270486 +DXGI_ERROR_ACCESS_DENIED: Final = -2005270485 +DXGI_ERROR_NAME_ALREADY_EXISTS: Final = -2005270484 +DXGI_ERROR_SDK_COMPONENT_MISSING: Final = -2005270483 +DXGI_ERROR_NOT_CURRENT: Final = -2005270482 +DXGI_ERROR_HW_PROTECTION_OUTOFMEMORY: Final = -2005270480 +DXGI_ERROR_DYNAMIC_CODE_POLICY_VIOLATION: Final = -2005270479 +DXGI_ERROR_NON_COMPOSITED_UI: Final = -2005270478 +DXCORE_ERROR_EVENT_NOT_UNREGISTERED: Final = -2004877311 +PRESENTATION_ERROR_LOST: Final = -2004811775 +DXGI_STATUS_UNOCCLUDED: Final = 0x087A0009 +DXGI_STATUS_DDA_WAS_STILL_DRAWING: Final = 0x087A000A +DXGI_ERROR_MODE_CHANGE_IN_PROGRESS: Final = -2005270491 +DXGI_STATUS_PRESENT_REQUIRED: Final = 0x087A002F +DXGI_ERROR_CACHE_CORRUPT: Final = -2005270477 +DXGI_ERROR_CACHE_FULL: Final = -2005270476 +DXGI_ERROR_CACHE_HASH_COLLISION: Final = -2005270475 +DXGI_ERROR_ALREADY_EXISTS: Final = -2005270474 +DXGI_ERROR_MPO_UNPINNED: Final = -2005270428 +DXGI_DDI_ERR_WASSTILLDRAWING: Final = -2005204991 +DXGI_DDI_ERR_UNSUPPORTED: Final = -2005204990 +DXGI_DDI_ERR_NONEXCLUSIVE: Final = -2005204989 +D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: Final = -2005336063 +D3D10_ERROR_FILE_NOT_FOUND: Final = -2005336062 +D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: Final = -2005139455 +D3D11_ERROR_FILE_NOT_FOUND: Final = -2005139454 +D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS: Final = -2005139453 +D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD: Final = -2005139452 +D3D12_ERROR_ADAPTER_NOT_FOUND: Final = -2005008383 +D3D12_ERROR_DRIVER_VERSION_MISMATCH: Final = -2005008382 +D3D12_ERROR_INVALID_REDIST: Final = -2005008381 +D2DERR_WRONG_STATE: Final = -2003238911 +D2DERR_NOT_INITIALIZED: Final = -2003238910 +D2DERR_UNSUPPORTED_OPERATION: Final = -2003238909 +D2DERR_SCANNER_FAILED: Final = -2003238908 +D2DERR_SCREEN_ACCESS_DENIED: Final = -2003238907 +D2DERR_DISPLAY_STATE_INVALID: Final = -2003238906 +D2DERR_ZERO_VECTOR: Final = -2003238905 +D2DERR_INTERNAL_ERROR: Final = -2003238904 +D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED: Final = -2003238903 +D2DERR_INVALID_CALL: Final = -2003238902 +D2DERR_NO_HARDWARE_DEVICE: Final = -2003238901 +D2DERR_RECREATE_TARGET: Final = -2003238900 +D2DERR_TOO_MANY_SHADER_ELEMENTS: Final = -2003238899 +D2DERR_SHADER_COMPILE_FAILED: Final = -2003238898 +D2DERR_MAX_TEXTURE_SIZE_EXCEEDED: Final = -2003238897 +D2DERR_UNSUPPORTED_VERSION: Final = -2003238896 +D2DERR_BAD_NUMBER: Final = -2003238895 +D2DERR_WRONG_FACTORY: Final = -2003238894 +D2DERR_LAYER_ALREADY_IN_USE: Final = -2003238893 +D2DERR_POP_CALL_DID_NOT_MATCH_PUSH: Final = -2003238892 +D2DERR_WRONG_RESOURCE_DOMAIN: Final = -2003238891 +D2DERR_PUSH_POP_UNBALANCED: Final = -2003238890 +D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT: Final = -2003238889 +D2DERR_INCOMPATIBLE_BRUSH_TYPES: Final = -2003238888 +D2DERR_WIN32_ERROR: Final = -2003238887 +D2DERR_TARGET_NOT_GDI_COMPATIBLE: Final = -2003238886 +D2DERR_TEXT_EFFECT_IS_WRONG_TYPE: Final = -2003238885 +D2DERR_TEXT_RENDERER_NOT_RELEASED: Final = -2003238884 +D2DERR_EXCEEDS_MAX_BITMAP_SIZE: Final = -2003238883 +D2DERR_INVALID_GRAPH_CONFIGURATION: Final = -2003238882 +D2DERR_INVALID_INTERNAL_GRAPH_CONFIGURATION: Final = -2003238881 +D2DERR_CYCLIC_GRAPH: Final = -2003238880 +D2DERR_BITMAP_CANNOT_DRAW: Final = -2003238879 +D2DERR_OUTSTANDING_BITMAP_REFERENCES: Final = -2003238878 +D2DERR_ORIGINAL_TARGET_NOT_BOUND: Final = -2003238877 +D2DERR_INVALID_TARGET: Final = -2003238876 +D2DERR_BITMAP_BOUND_AS_TARGET: Final = -2003238875 +D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES: Final = -2003238874 +D2DERR_INTERMEDIATE_TOO_LARGE: Final = -2003238873 +D2DERR_EFFECT_IS_NOT_REGISTERED: Final = -2003238872 +D2DERR_INVALID_PROPERTY: Final = -2003238871 +D2DERR_NO_SUBPROPERTIES: Final = -2003238870 +D2DERR_PRINT_JOB_CLOSED: Final = -2003238869 +D2DERR_PRINT_FORMAT_NOT_SUPPORTED: Final = -2003238868 +D2DERR_TOO_MANY_TRANSFORM_INPUTS: Final = -2003238867 +D2DERR_INVALID_GLYPH_IMAGE: Final = -2003238866 +DWRITE_E_FILEFORMAT: Final = -2003283968 +DWRITE_E_UNEXPECTED: Final = -2003283967 +DWRITE_E_NOFONT: Final = -2003283966 +DWRITE_E_FILENOTFOUND: Final = -2003283965 +DWRITE_E_FILEACCESS: Final = -2003283964 +DWRITE_E_FONTCOLLECTIONOBSOLETE: Final = -2003283963 +DWRITE_E_ALREADYREGISTERED: Final = -2003283962 +DWRITE_E_CACHEFORMAT: Final = -2003283961 +DWRITE_E_CACHEVERSION: Final = -2003283960 +DWRITE_E_UNSUPPORTEDOPERATION: Final = -2003283959 +DWRITE_E_TEXTRENDERERINCOMPATIBLE: Final = -2003283958 +DWRITE_E_FLOWDIRECTIONCONFLICTS: Final = -2003283957 +DWRITE_E_NOCOLOR: Final = -2003283956 +DWRITE_E_REMOTEFONT: Final = -2003283955 +DWRITE_E_DOWNLOADCANCELLED: Final = -2003283954 +DWRITE_E_DOWNLOADFAILED: Final = -2003283953 +DWRITE_E_TOOMANYDOWNLOADS: Final = -2003283952 +WINCODEC_ERR_WRONGSTATE: Final = -2003292412 +WINCODEC_ERR_VALUEOUTOFRANGE: Final = -2003292411 +WINCODEC_ERR_UNKNOWNIMAGEFORMAT: Final = -2003292409 +WINCODEC_ERR_UNSUPPORTEDVERSION: Final = -2003292405 +WINCODEC_ERR_NOTINITIALIZED: Final = -2003292404 +WINCODEC_ERR_ALREADYLOCKED: Final = -2003292403 +WINCODEC_ERR_PROPERTYNOTFOUND: Final = -2003292352 +WINCODEC_ERR_PROPERTYNOTSUPPORTED: Final = -2003292351 +WINCODEC_ERR_PROPERTYSIZE: Final = -2003292350 +WINCODEC_ERR_CODECPRESENT: Final = -2003292349 +WINCODEC_ERR_CODECNOTHUMBNAIL: Final = -2003292348 +WINCODEC_ERR_PALETTEUNAVAILABLE: Final = -2003292347 +WINCODEC_ERR_CODECTOOMANYSCANLINES: Final = -2003292346 +WINCODEC_ERR_INTERNALERROR: Final = -2003292344 +WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS: Final = -2003292343 +WINCODEC_ERR_COMPONENTNOTFOUND: Final = -2003292336 +WINCODEC_ERR_IMAGESIZEOUTOFRANGE: Final = -2003292335 +WINCODEC_ERR_TOOMUCHMETADATA: Final = -2003292334 +WINCODEC_ERR_BADIMAGE: Final = -2003292320 +WINCODEC_ERR_BADHEADER: Final = -2003292319 +WINCODEC_ERR_FRAMEMISSING: Final = -2003292318 +WINCODEC_ERR_BADMETADATAHEADER: Final = -2003292317 +WINCODEC_ERR_BADSTREAMDATA: Final = -2003292304 +WINCODEC_ERR_STREAMWRITE: Final = -2003292303 +WINCODEC_ERR_STREAMREAD: Final = -2003292302 +WINCODEC_ERR_STREAMNOTAVAILABLE: Final = -2003292301 +WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT: Final = -2003292288 +WINCODEC_ERR_UNSUPPORTEDOPERATION: Final = -2003292287 +WINCODEC_ERR_INVALIDREGISTRATION: Final = -2003292278 +WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: Final = -2003292277 +WINCODEC_ERR_INSUFFICIENTBUFFER: Final = -2003292276 +WINCODEC_ERR_DUPLICATEMETADATAPRESENT: Final = -2003292275 +WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE: Final = -2003292274 +WINCODEC_ERR_UNEXPECTEDSIZE: Final = -2003292273 +WINCODEC_ERR_INVALIDQUERYREQUEST: Final = -2003292272 +WINCODEC_ERR_UNEXPECTEDMETADATATYPE: Final = -2003292271 +WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT: Final = -2003292270 +WINCODEC_ERR_INVALIDQUERYCHARACTER: Final = -2003292269 +WINCODEC_ERR_WIN32ERROR: Final = -2003292268 +WINCODEC_ERR_INVALIDPROGRESSIVELEVEL: Final = -2003292267 +WINCODEC_ERR_INVALIDJPEGSCANINDEX: Final = -2003292266 +MILERR_OBJECTBUSY: Final = -2003304447 +MILERR_INSUFFICIENTBUFFER: Final = -2003304446 +MILERR_WIN32ERROR: Final = -2003304445 +MILERR_SCANNER_FAILED: Final = -2003304444 +MILERR_SCREENACCESSDENIED: Final = -2003304443 +MILERR_DISPLAYSTATEINVALID: Final = -2003304442 +MILERR_NONINVERTIBLEMATRIX: Final = -2003304441 +MILERR_ZEROVECTOR: Final = -2003304440 +MILERR_TERMINATED: Final = -2003304439 +MILERR_BADNUMBER: Final = -2003304438 +MILERR_INTERNALERROR: Final = -2003304320 +MILERR_DISPLAYFORMATNOTSUPPORTED: Final = -2003304316 +MILERR_INVALIDCALL: Final = -2003304315 +MILERR_ALREADYLOCKED: Final = -2003304314 +MILERR_NOTLOCKED: Final = -2003304313 +MILERR_DEVICECANNOTRENDERTEXT: Final = -2003304312 +MILERR_GLYPHBITMAPMISSED: Final = -2003304311 +MILERR_MALFORMEDGLYPHCACHE: Final = -2003304310 +MILERR_GENERIC_IGNORE: Final = -2003304309 +MILERR_MALFORMED_GUIDELINE_DATA: Final = -2003304308 +MILERR_NO_HARDWARE_DEVICE: Final = -2003304307 +MILERR_NEED_RECREATE_AND_PRESENT: Final = -2003304306 +MILERR_ALREADY_INITIALIZED: Final = -2003304305 +MILERR_MISMATCHED_SIZE: Final = -2003304304 +MILERR_NO_REDIRECTION_SURFACE_AVAILABLE: Final = -2003304303 +MILERR_REMOTING_NOT_SUPPORTED: Final = -2003304302 +MILERR_QUEUED_PRESENT_NOT_SUPPORTED: Final = -2003304301 +MILERR_NOT_QUEUING_PRESENTS: Final = -2003304300 +MILERR_NO_REDIRECTION_SURFACE_RETRY_LATER: Final = -2003304299 +MILERR_TOOMANYSHADERELEMNTS: Final = -2003304298 +MILERR_MROW_READLOCK_FAILED: Final = -2003304297 +MILERR_MROW_UPDATE_FAILED: Final = -2003304296 +MILERR_SHADER_COMPILE_FAILED: Final = -2003304295 +MILERR_MAX_TEXTURE_SIZE_EXCEEDED: Final = -2003304294 +MILERR_QPC_TIME_WENT_BACKWARD: Final = -2003304293 +MILERR_DXGI_ENUMERATION_OUT_OF_SYNC: Final = -2003304291 +MILERR_ADAPTER_NOT_FOUND: Final = -2003304290 +MILERR_COLORSPACE_NOT_SUPPORTED: Final = -2003304289 +MILERR_PREFILTER_NOT_SUPPORTED: Final = -2003304288 +MILERR_DISPLAYID_ACCESS_DENIED: Final = -2003304287 +UCEERR_INVALIDPACKETHEADER: Final = -2003303424 +UCEERR_UNKNOWNPACKET: Final = -2003303423 +UCEERR_ILLEGALPACKET: Final = -2003303422 +UCEERR_MALFORMEDPACKET: Final = -2003303421 +UCEERR_ILLEGALHANDLE: Final = -2003303420 +UCEERR_HANDLELOOKUPFAILED: Final = -2003303419 +UCEERR_RENDERTHREADFAILURE: Final = -2003303418 +UCEERR_CTXSTACKFRSTTARGETNULL: Final = -2003303417 +UCEERR_CONNECTIONIDLOOKUPFAILED: Final = -2003303416 +UCEERR_BLOCKSFULL: Final = -2003303415 +UCEERR_MEMORYFAILURE: Final = -2003303414 +UCEERR_PACKETRECORDOUTOFRANGE: Final = -2003303413 +UCEERR_ILLEGALRECORDTYPE: Final = -2003303412 +UCEERR_OUTOFHANDLES: Final = -2003303411 +UCEERR_UNCHANGABLE_UPDATE_ATTEMPTED: Final = -2003303410 +UCEERR_NO_MULTIPLE_WORKER_THREADS: Final = -2003303409 +UCEERR_REMOTINGNOTSUPPORTED: Final = -2003303408 +UCEERR_MISSINGENDCOMMAND: Final = -2003303407 +UCEERR_MISSINGBEGINCOMMAND: Final = -2003303406 +UCEERR_CHANNELSYNCTIMEDOUT: Final = -2003303405 +UCEERR_CHANNELSYNCABANDONED: Final = -2003303404 +UCEERR_UNSUPPORTEDTRANSPORTVERSION: Final = -2003303403 +UCEERR_TRANSPORTUNAVAILABLE: Final = -2003303402 +UCEERR_FEEDBACK_UNSUPPORTED: Final = -2003303401 +UCEERR_COMMANDTRANSPORTDENIED: Final = -2003303400 +UCEERR_GRAPHICSSTREAMUNAVAILABLE: Final = -2003303399 +UCEERR_GRAPHICSSTREAMALREADYOPEN: Final = -2003303392 +UCEERR_TRANSPORTDISCONNECTED: Final = -2003303391 +UCEERR_TRANSPORTOVERLOADED: Final = -2003303390 +UCEERR_PARTITION_ZOMBIED: Final = -2003303389 +MILAVERR_NOCLOCK: Final = -2003303168 +MILAVERR_NOMEDIATYPE: Final = -2003303167 +MILAVERR_NOVIDEOMIXER: Final = -2003303166 +MILAVERR_NOVIDEOPRESENTER: Final = -2003303165 +MILAVERR_NOREADYFRAMES: Final = -2003303164 +MILAVERR_MODULENOTLOADED: Final = -2003303163 +MILAVERR_WMPFACTORYNOTREGISTERED: Final = -2003303162 +MILAVERR_INVALIDWMPVERSION: Final = -2003303161 +MILAVERR_INSUFFICIENTVIDEORESOURCES: Final = -2003303160 +MILAVERR_VIDEOACCELERATIONNOTAVAILABLE: Final = -2003303159 +MILAVERR_REQUESTEDTEXTURETOOBIG: Final = -2003303158 +MILAVERR_SEEKFAILED: Final = -2003303157 +MILAVERR_UNEXPECTEDWMPFAILURE: Final = -2003303156 +MILAVERR_MEDIAPLAYERCLOSED: Final = -2003303155 +MILAVERR_UNKNOWNHARDWAREERROR: Final = -2003303154 +MILEFFECTSERR_UNKNOWNPROPERTY: Final = -2003302898 +MILEFFECTSERR_EFFECTNOTPARTOFGROUP: Final = -2003302897 +MILEFFECTSERR_NOINPUTSOURCEATTACHED: Final = -2003302896 +MILEFFECTSERR_CONNECTORNOTCONNECTED: Final = -2003302895 +MILEFFECTSERR_CONNECTORNOTASSOCIATEDWITHEFFECT: Final = -2003302894 +MILEFFECTSERR_RESERVED: Final = -2003302893 +MILEFFECTSERR_CYCLEDETECTED: Final = -2003302892 +MILEFFECTSERR_EFFECTINMORETHANONEGRAPH: Final = -2003302891 +MILEFFECTSERR_EFFECTALREADYINAGRAPH: Final = -2003302890 +MILEFFECTSERR_EFFECTHASNOCHILDREN: Final = -2003302889 +MILEFFECTSERR_ALREADYATTACHEDTOLISTENER: Final = -2003302888 +MILEFFECTSERR_NOTAFFINETRANSFORM: Final = -2003302887 +MILEFFECTSERR_EMPTYBOUNDS: Final = -2003302886 +MILEFFECTSERR_OUTPUTSIZETOOLARGE: Final = -2003302885 +DWMERR_STATE_TRANSITION_FAILED: Final = -2003302656 +DWMERR_THEME_FAILED: Final = -2003302655 +DWMERR_CATASTROPHIC_FAILURE: Final = -2003302654 +DCOMPOSITION_ERROR_WINDOW_ALREADY_COMPOSED: Final = -2003302400 +DCOMPOSITION_ERROR_SURFACE_BEING_RENDERED: Final = -2003302399 +DCOMPOSITION_ERROR_SURFACE_NOT_BEING_RENDERED: Final = -2003302398 +ONL_E_INVALID_AUTHENTICATION_TARGET: Final = -2138701823 +ONL_E_ACCESS_DENIED_BY_TOU: Final = -2138701822 +ONL_E_INVALID_APPLICATION: Final = -2138701821 +ONL_E_PASSWORD_UPDATE_REQUIRED: Final = -2138701820 +ONL_E_ACCOUNT_UPDATE_REQUIRED: Final = -2138701819 +ONL_E_FORCESIGNIN: Final = -2138701818 +ONL_E_ACCOUNT_LOCKED: Final = -2138701817 +ONL_E_PARENTAL_CONSENT_REQUIRED: Final = -2138701816 +ONL_E_EMAIL_VERIFICATION_REQUIRED: Final = -2138701815 +ONL_E_ACCOUNT_SUSPENDED_COMPROIMISE: Final = -2138701814 +ONL_E_ACCOUNT_SUSPENDED_ABUSE: Final = -2138701813 +ONL_E_ACTION_REQUIRED: Final = -2138701812 +ONL_CONNECTION_COUNT_LIMIT: Final = -2138701811 +ONL_E_CONNECTED_ACCOUNT_CAN_NOT_SIGNOUT: Final = -2138701810 +ONL_E_USER_AUTHENTICATION_REQUIRED: Final = -2138701809 +ONL_E_REQUEST_THROTTLED: Final = -2138701808 +FA_E_MAX_PERSISTED_ITEMS_REACHED: Final = -2144927200 +FA_E_HOMEGROUP_NOT_AVAILABLE: Final = -2144927198 +E_MONITOR_RESOLUTION_TOO_LOW: Final = -2144927152 +E_ELEVATED_ACTIVATION_NOT_SUPPORTED: Final = -2144927151 +E_UAC_DISABLED: Final = -2144927150 +E_FULL_ADMIN_NOT_SUPPORTED: Final = -2144927149 +E_APPLICATION_NOT_REGISTERED: Final = -2144927148 +E_MULTIPLE_EXTENSIONS_FOR_APPLICATION: Final = -2144927147 +E_MULTIPLE_PACKAGES_FOR_FAMILY: Final = -2144927146 +E_APPLICATION_MANAGER_NOT_RUNNING: Final = -2144927145 +S_STORE_LAUNCHED_FOR_REMEDIATION: Final = 0x00270258 +S_APPLICATION_ACTIVATION_ERROR_HANDLED_BY_DIALOG: Final = 0x00270259 +E_APPLICATION_ACTIVATION_TIMED_OUT: Final = -2144927142 +E_APPLICATION_ACTIVATION_EXEC_FAILURE: Final = -2144927141 +E_APPLICATION_TEMPORARY_LICENSE_ERROR: Final = -2144927140 +E_APPLICATION_TRIAL_LICENSE_EXPIRED: Final = -2144927139 +E_SKYDRIVE_ROOT_TARGET_FILE_SYSTEM_NOT_SUPPORTED: Final = -2144927136 +E_SKYDRIVE_ROOT_TARGET_OVERLAP: Final = -2144927135 +E_SKYDRIVE_ROOT_TARGET_CANNOT_INDEX: Final = -2144927134 +E_SKYDRIVE_FILE_NOT_UPLOADED: Final = -2144927133 +E_SKYDRIVE_UPDATE_AVAILABILITY_FAIL: Final = -2144927132 +E_SKYDRIVE_ROOT_TARGET_VOLUME_ROOT_NOT_SUPPORTED: Final = -2144927131 +E_SYNCENGINE_FILE_SIZE_OVER_LIMIT: Final = -2013089791 +E_SYNCENGINE_FILE_SIZE_EXCEEDS_REMAINING_QUOTA: Final = -2013089790 +E_SYNCENGINE_UNSUPPORTED_FILE_NAME: Final = -2013089789 +E_SYNCENGINE_FOLDER_ITEM_COUNT_LIMIT_EXCEEDED: Final = -2013089788 +E_SYNCENGINE_FILE_SYNC_PARTNER_ERROR: Final = -2013089787 +E_SYNCENGINE_SYNC_PAUSED_BY_SERVICE: Final = -2013089786 +E_SYNCENGINE_FILE_IDENTIFIER_UNKNOWN: Final = -2013085694 +E_SYNCENGINE_SERVICE_AUTHENTICATION_FAILED: Final = -2013085693 +E_SYNCENGINE_UNKNOWN_SERVICE_ERROR: Final = -2013085692 +E_SYNCENGINE_SERVICE_RETURNED_UNEXPECTED_SIZE: Final = -2013085691 +E_SYNCENGINE_REQUEST_BLOCKED_BY_SERVICE: Final = -2013085690 +E_SYNCENGINE_REQUEST_BLOCKED_DUE_TO_CLIENT_ERROR: Final = -2013085689 +E_SYNCENGINE_FOLDER_INACCESSIBLE: Final = -2013081599 +E_SYNCENGINE_UNSUPPORTED_FOLDER_NAME: Final = -2013081598 +E_SYNCENGINE_UNSUPPORTED_MARKET: Final = -2013081597 +E_SYNCENGINE_PATH_LENGTH_LIMIT_EXCEEDED: Final = -2013081596 +E_SYNCENGINE_REMOTE_PATH_LENGTH_LIMIT_EXCEEDED: Final = -2013081595 +E_SYNCENGINE_CLIENT_UPDATE_NEEDED: Final = -2013081594 +E_SYNCENGINE_PROXY_AUTHENTICATION_REQUIRED: Final = -2013081593 +E_SYNCENGINE_STORAGE_SERVICE_PROVISIONING_FAILED: Final = -2013081592 +E_SYNCENGINE_UNSUPPORTED_REPARSE_POINT: Final = -2013081591 +E_SYNCENGINE_STORAGE_SERVICE_BLOCKED: Final = -2013081590 +E_SYNCENGINE_FOLDER_IN_REDIRECTION: Final = -2013081589 +EAS_E_POLICY_NOT_MANAGED_BY_OS: Final = -2141913087 +EAS_E_POLICY_COMPLIANT_WITH_ACTIONS: Final = -2141913086 +EAS_E_REQUESTED_POLICY_NOT_ENFORCEABLE: Final = -2141913085 +EAS_E_CURRENT_USER_HAS_BLANK_PASSWORD: Final = -2141913084 +EAS_E_REQUESTED_POLICY_PASSWORD_EXPIRATION_INCOMPATIBLE: Final = -2141913083 +EAS_E_USER_CANNOT_CHANGE_PASSWORD: Final = -2141913082 +EAS_E_ADMINS_HAVE_BLANK_PASSWORD: Final = -2141913081 +EAS_E_ADMINS_CANNOT_CHANGE_PASSWORD: Final = -2141913080 +EAS_E_LOCAL_CONTROLLED_USERS_CANNOT_CHANGE_PASSWORD: Final = -2141913079 +EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CONNECTED_ADMINS: Final = -2141913078 +EAS_E_CONNECTED_ADMINS_NEED_TO_CHANGE_PASSWORD: Final = -2141913077 +EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CURRENT_CONNECTED_USER: Final = -2141913076 +EAS_E_CURRENT_CONNECTED_USER_NEED_TO_CHANGE_PASSWORD: Final = -2141913075 +WEB_E_UNSUPPORTED_FORMAT: Final = -2089484287 +WEB_E_INVALID_XML: Final = -2089484286 +WEB_E_MISSING_REQUIRED_ELEMENT: Final = -2089484285 +WEB_E_MISSING_REQUIRED_ATTRIBUTE: Final = -2089484284 +WEB_E_UNEXPECTED_CONTENT: Final = -2089484283 +WEB_E_RESOURCE_TOO_LARGE: Final = -2089484282 +WEB_E_INVALID_JSON_STRING: Final = -2089484281 +WEB_E_INVALID_JSON_NUMBER: Final = -2089484280 +WEB_E_JSON_VALUE_NOT_FOUND: Final = -2089484279 +HTTP_E_STATUS_UNEXPECTED: Final = -2145845247 +HTTP_E_STATUS_UNEXPECTED_REDIRECTION: Final = -2145845245 +HTTP_E_STATUS_UNEXPECTED_CLIENT_ERROR: Final = -2145845244 +HTTP_E_STATUS_UNEXPECTED_SERVER_ERROR: Final = -2145845243 +HTTP_E_STATUS_AMBIGUOUS: Final = -2145844948 +HTTP_E_STATUS_MOVED: Final = -2145844947 +HTTP_E_STATUS_REDIRECT: Final = -2145844946 +HTTP_E_STATUS_REDIRECT_METHOD: Final = -2145844945 +HTTP_E_STATUS_NOT_MODIFIED: Final = -2145844944 +HTTP_E_STATUS_USE_PROXY: Final = -2145844943 +HTTP_E_STATUS_REDIRECT_KEEP_VERB: Final = -2145844941 +HTTP_E_STATUS_BAD_REQUEST: Final = -2145844848 +HTTP_E_STATUS_DENIED: Final = -2145844847 +HTTP_E_STATUS_PAYMENT_REQ: Final = -2145844846 +HTTP_E_STATUS_FORBIDDEN: Final = -2145844845 +HTTP_E_STATUS_NOT_FOUND: Final = -2145844844 +HTTP_E_STATUS_BAD_METHOD: Final = -2145844843 +HTTP_E_STATUS_NONE_ACCEPTABLE: Final = -2145844842 +HTTP_E_STATUS_PROXY_AUTH_REQ: Final = -2145844841 +HTTP_E_STATUS_REQUEST_TIMEOUT: Final = -2145844840 +HTTP_E_STATUS_CONFLICT: Final = -2145844839 +HTTP_E_STATUS_GONE: Final = -2145844838 +HTTP_E_STATUS_LENGTH_REQUIRED: Final = -2145844837 +HTTP_E_STATUS_PRECOND_FAILED: Final = -2145844836 +HTTP_E_STATUS_REQUEST_TOO_LARGE: Final = -2145844835 +HTTP_E_STATUS_URI_TOO_LONG: Final = -2145844834 +HTTP_E_STATUS_UNSUPPORTED_MEDIA: Final = -2145844833 +HTTP_E_STATUS_RANGE_NOT_SATISFIABLE: Final = -2145844832 +HTTP_E_STATUS_EXPECTATION_FAILED: Final = -2145844831 +HTTP_E_STATUS_SERVER_ERROR: Final = -2145844748 +HTTP_E_STATUS_NOT_SUPPORTED: Final = -2145844747 +HTTP_E_STATUS_BAD_GATEWAY: Final = -2145844746 +HTTP_E_STATUS_SERVICE_UNAVAIL: Final = -2145844745 +HTTP_E_STATUS_GATEWAY_TIMEOUT: Final = -2145844744 +HTTP_E_STATUS_VERSION_NOT_SUP: Final = -2145844743 +E_INVALID_PROTOCOL_OPERATION: Final = -2089418751 +E_INVALID_PROTOCOL_FORMAT: Final = -2089418750 +E_PROTOCOL_EXTENSIONS_NOT_SUPPORTED: Final = -2089418749 +E_SUBPROTOCOL_NOT_SUPPORTED: Final = -2089418748 +E_PROTOCOL_VERSION_NOT_SUPPORTED: Final = -2089418747 +INPUT_E_OUT_OF_ORDER: Final = -2143289344 +INPUT_E_REENTRANCY: Final = -2143289343 +INPUT_E_MULTIMODAL: Final = -2143289342 +INPUT_E_PACKET: Final = -2143289341 +INPUT_E_FRAME: Final = -2143289340 +INPUT_E_HISTORY: Final = -2143289339 +INPUT_E_DEVICE_INFO: Final = -2143289338 +INPUT_E_TRANSFORM: Final = -2143289337 +INPUT_E_DEVICE_PROPERTY: Final = -2143289336 +INET_E_INVALID_URL: Final = -2146697214 +INET_E_NO_SESSION: Final = -2146697213 +INET_E_CANNOT_CONNECT: Final = -2146697212 +INET_E_RESOURCE_NOT_FOUND: Final = -2146697211 +INET_E_OBJECT_NOT_FOUND: Final = -2146697210 +INET_E_DATA_NOT_AVAILABLE: Final = -2146697209 +INET_E_DOWNLOAD_FAILURE: Final = -2146697208 +INET_E_AUTHENTICATION_REQUIRED: Final = -2146697207 +INET_E_NO_VALID_MEDIA: Final = -2146697206 +INET_E_CONNECTION_TIMEOUT: Final = -2146697205 +INET_E_INVALID_REQUEST: Final = -2146697204 +INET_E_UNKNOWN_PROTOCOL: Final = -2146697203 +INET_E_SECURITY_PROBLEM: Final = -2146697202 +INET_E_CANNOT_LOAD_DATA: Final = -2146697201 +INET_E_CANNOT_INSTANTIATE_OBJECT: Final = -2146697200 +INET_E_INVALID_CERTIFICATE: Final = -2146697191 +INET_E_REDIRECT_FAILED: Final = -2146697196 +INET_E_REDIRECT_TO_DIR: Final = -2146697195 +ERROR_DBG_CREATE_PROCESS_FAILURE_LOCKDOWN: Final = -2135949311 +ERROR_DBG_ATTACH_PROCESS_FAILURE_LOCKDOWN: Final = -2135949310 +ERROR_DBG_CONNECT_SERVER_FAILURE_LOCKDOWN: Final = -2135949309 +ERROR_DBG_START_SERVER_FAILURE_LOCKDOWN: Final = -2135949308 +HSP_E_ERROR_MASK: Final = -2128084992 +HSP_E_INTERNAL_ERROR: Final = -2128080897 +HSP_BS_ERROR_MASK: Final = -2128080896 +HSP_BS_INTERNAL_ERROR: Final = -2128080641 +HSP_DRV_ERROR_MASK: Final = -2128019456 +HSP_DRV_INTERNAL_ERROR: Final = -2128019201 +HSP_BASE_ERROR_MASK: Final = -2128019200 +HSP_BASE_INTERNAL_ERROR: Final = -2128018945 +HSP_KSP_ERROR_MASK: Final = -2128018944 +HSP_KSP_DEVICE_NOT_READY: Final = -2128018943 +HSP_KSP_INVALID_PROVIDER_HANDLE: Final = -2128018942 +HSP_KSP_INVALID_KEY_HANDLE: Final = -2128018941 +HSP_KSP_INVALID_PARAMETER: Final = -2128018940 +HSP_KSP_BUFFER_TOO_SMALL: Final = -2128018939 +HSP_KSP_NOT_SUPPORTED: Final = -2128018938 +HSP_KSP_INVALID_DATA: Final = -2128018937 +HSP_KSP_INVALID_FLAGS: Final = -2128018936 +HSP_KSP_ALGORITHM_NOT_SUPPORTED: Final = -2128018935 +HSP_KSP_KEY_ALREADY_FINALIZED: Final = -2128018934 +HSP_KSP_KEY_NOT_FINALIZED: Final = -2128018933 +HSP_KSP_INVALID_KEY_TYPE: Final = -2128018932 +HSP_KSP_NO_MEMORY: Final = -2128018928 +HSP_KSP_PARAMETER_NOT_SET: Final = -2128018927 +HSP_KSP_KEY_EXISTS: Final = -2128018923 +HSP_KSP_KEY_MISSING: Final = -2128018922 +HSP_KSP_KEY_LOAD_FAIL: Final = -2128018921 +HSP_KSP_NO_MORE_ITEMS: Final = -2128018920 +HSP_KSP_INTERNAL_ERROR: Final = -2128018689 +ERROR_IO_PREEMPTED: Final = -1996423167 +JSCRIPT_E_CANTEXECUTE: Final = -1996357631 +WEP_E_NOT_PROVISIONED_ON_ALL_VOLUMES: Final = -2013200383 +WEP_E_FIXED_DATA_NOT_SUPPORTED: Final = -2013200382 +WEP_E_HARDWARE_NOT_COMPLIANT: Final = -2013200381 +WEP_E_LOCK_NOT_CONFIGURED: Final = -2013200380 +WEP_E_PROTECTION_SUSPENDED: Final = -2013200379 +WEP_E_NO_LICENSE: Final = -2013200378 +WEP_E_OS_NOT_PROTECTED: Final = -2013200377 +WEP_E_UNEXPECTED_FAIL: Final = -2013200376 +WEP_E_BUFFER_TOO_LARGE: Final = -2013200375 +ERROR_SVHDX_ERROR_STORED: Final = -1067712512 +ERROR_SVHDX_ERROR_NOT_AVAILABLE: Final = -1067647232 +ERROR_SVHDX_UNIT_ATTENTION_AVAILABLE: Final = -1067647231 +ERROR_SVHDX_UNIT_ATTENTION_CAPACITY_DATA_CHANGED: Final = -1067647230 +ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_PREEMPTED: Final = -1067647229 +ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_RELEASED: Final = -1067647228 +ERROR_SVHDX_UNIT_ATTENTION_REGISTRATIONS_PREEMPTED: Final = -1067647227 +ERROR_SVHDX_UNIT_ATTENTION_OPERATING_DEFINITION_CHANGED: Final = -1067647226 +ERROR_SVHDX_RESERVATION_CONFLICT: Final = -1067647225 +ERROR_SVHDX_WRONG_FILE_TYPE: Final = -1067647224 +ERROR_SVHDX_VERSION_MISMATCH: Final = -1067647223 +ERROR_VHD_SHARED: Final = -1067647222 +ERROR_SVHDX_NO_INITIATOR: Final = -1067647221 +ERROR_VHDSET_BACKING_STORAGE_NOT_FOUND: Final = -1067647220 +ERROR_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP: Final = -1067646976 +ERROR_SMB_BAD_CLUSTER_DIALECT: Final = -1067646975 +ERROR_SMB_NO_SIGNING_ALGORITHM_OVERLAP: Final = -1067646974 +WININET_E_OUT_OF_HANDLES: Final = -2147012895 +WININET_E_TIMEOUT: Final = -2147012894 +WININET_E_EXTENDED_ERROR: Final = -2147012893 +WININET_E_INTERNAL_ERROR: Final = -2147012892 +WININET_E_INVALID_URL: Final = -2147012891 +WININET_E_UNRECOGNIZED_SCHEME: Final = -2147012890 +WININET_E_NAME_NOT_RESOLVED: Final = -2147012889 +WININET_E_PROTOCOL_NOT_FOUND: Final = -2147012888 +WININET_E_INVALID_OPTION: Final = -2147012887 +WININET_E_BAD_OPTION_LENGTH: Final = -2147012886 +WININET_E_OPTION_NOT_SETTABLE: Final = -2147012885 +WININET_E_SHUTDOWN: Final = -2147012884 +WININET_E_INCORRECT_USER_NAME: Final = -2147012883 +WININET_E_INCORRECT_PASSWORD: Final = -2147012882 +WININET_E_LOGIN_FAILURE: Final = -2147012881 +WININET_E_INVALID_OPERATION: Final = -2147012880 +WININET_E_OPERATION_CANCELLED: Final = -2147012879 +WININET_E_INCORRECT_HANDLE_TYPE: Final = -2147012878 +WININET_E_INCORRECT_HANDLE_STATE: Final = -2147012877 +WININET_E_NOT_PROXY_REQUEST: Final = -2147012876 +WININET_E_REGISTRY_VALUE_NOT_FOUND: Final = -2147012875 +WININET_E_BAD_REGISTRY_PARAMETER: Final = -2147012874 +WININET_E_NO_DIRECT_ACCESS: Final = -2147012873 +WININET_E_NO_CONTEXT: Final = -2147012872 +WININET_E_NO_CALLBACK: Final = -2147012871 +WININET_E_REQUEST_PENDING: Final = -2147012870 +WININET_E_INCORRECT_FORMAT: Final = -2147012869 +WININET_E_ITEM_NOT_FOUND: Final = -2147012868 +WININET_E_CANNOT_CONNECT: Final = -2147012867 +WININET_E_CONNECTION_ABORTED: Final = -2147012866 +WININET_E_CONNECTION_RESET: Final = -2147012865 +WININET_E_FORCE_RETRY: Final = -2147012864 +WININET_E_INVALID_PROXY_REQUEST: Final = -2147012863 +WININET_E_NEED_UI: Final = -2147012862 +WININET_E_HANDLE_EXISTS: Final = -2147012860 +WININET_E_SEC_CERT_DATE_INVALID: Final = -2147012859 +WININET_E_SEC_CERT_CN_INVALID: Final = -2147012858 +WININET_E_HTTP_TO_HTTPS_ON_REDIR: Final = -2147012857 +WININET_E_HTTPS_TO_HTTP_ON_REDIR: Final = -2147012856 +WININET_E_MIXED_SECURITY: Final = -2147012855 +WININET_E_CHG_POST_IS_NON_SECURE: Final = -2147012854 +WININET_E_POST_IS_NON_SECURE: Final = -2147012853 +WININET_E_CLIENT_AUTH_CERT_NEEDED: Final = -2147012852 +WININET_E_INVALID_CA: Final = -2147012851 +WININET_E_CLIENT_AUTH_NOT_SETUP: Final = -2147012850 +WININET_E_ASYNC_THREAD_FAILED: Final = -2147012849 +WININET_E_REDIRECT_SCHEME_CHANGE: Final = -2147012848 +WININET_E_DIALOG_PENDING: Final = -2147012847 +WININET_E_RETRY_DIALOG: Final = -2147012846 +WININET_E_NO_NEW_CONTAINERS: Final = -2147012845 +WININET_E_HTTPS_HTTP_SUBMIT_REDIR: Final = -2147012844 +WININET_E_SEC_CERT_ERRORS: Final = -2147012841 +WININET_E_SEC_CERT_REV_FAILED: Final = -2147012839 +WININET_E_HEADER_NOT_FOUND: Final = -2147012746 +WININET_E_DOWNLEVEL_SERVER: Final = -2147012745 +WININET_E_INVALID_SERVER_RESPONSE: Final = -2147012744 +WININET_E_INVALID_HEADER: Final = -2147012743 +WININET_E_INVALID_QUERY_REQUEST: Final = -2147012742 +WININET_E_HEADER_ALREADY_EXISTS: Final = -2147012741 +WININET_E_REDIRECT_FAILED: Final = -2147012740 +WININET_E_SECURITY_CHANNEL_ERROR: Final = -2147012739 +WININET_E_UNABLE_TO_CACHE_FILE: Final = -2147012738 +WININET_E_TCPIP_NOT_INSTALLED: Final = -2147012737 +WININET_E_DISCONNECTED: Final = -2147012733 +WININET_E_SERVER_UNREACHABLE: Final = -2147012732 +WININET_E_PROXY_SERVER_UNREACHABLE: Final = -2147012731 +WININET_E_BAD_AUTO_PROXY_SCRIPT: Final = -2147012730 +WININET_E_UNABLE_TO_DOWNLOAD_SCRIPT: Final = -2147012729 +WININET_E_SEC_INVALID_CERT: Final = -2147012727 +WININET_E_SEC_CERT_REVOKED: Final = -2147012726 +WININET_E_FAILED_DUETOSECURITYCHECK: Final = -2147012725 +WININET_E_NOT_INITIALIZED: Final = -2147012724 +WININET_E_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: Final = -2147012722 +WININET_E_DECODING_FAILED: Final = -2147012721 +WININET_E_NOT_REDIRECTED: Final = -2147012736 +WININET_E_COOKIE_NEEDS_CONFIRMATION: Final = -2147012735 +WININET_E_COOKIE_DECLINED: Final = -2147012734 +WININET_E_REDIRECT_NEEDS_CONFIRMATION: Final = -2147012728 +SQLITE_E_ERROR: Final = -2018574335 +SQLITE_E_INTERNAL: Final = -2018574334 +SQLITE_E_PERM: Final = -2018574333 +SQLITE_E_ABORT: Final = -2018574332 +SQLITE_E_BUSY: Final = -2018574331 +SQLITE_E_LOCKED: Final = -2018574330 +SQLITE_E_NOMEM: Final = -2018574329 +SQLITE_E_READONLY: Final = -2018574328 +SQLITE_E_INTERRUPT: Final = -2018574327 +SQLITE_E_IOERR: Final = -2018574326 +SQLITE_E_CORRUPT: Final = -2018574325 +SQLITE_E_NOTFOUND: Final = -2018574324 +SQLITE_E_FULL: Final = -2018574323 +SQLITE_E_CANTOPEN: Final = -2018574322 +SQLITE_E_PROTOCOL: Final = -2018574321 +SQLITE_E_EMPTY: Final = -2018574320 +SQLITE_E_SCHEMA: Final = -2018574319 +SQLITE_E_TOOBIG: Final = -2018574318 +SQLITE_E_CONSTRAINT: Final = -2018574317 +SQLITE_E_MISMATCH: Final = -2018574316 +SQLITE_E_MISUSE: Final = -2018574315 +SQLITE_E_NOLFS: Final = -2018574314 +SQLITE_E_AUTH: Final = -2018574313 +SQLITE_E_FORMAT: Final = -2018574312 +SQLITE_E_RANGE: Final = -2018574311 +SQLITE_E_NOTADB: Final = -2018574310 +SQLITE_E_NOTICE: Final = -2018574309 +SQLITE_E_WARNING: Final = -2018574308 +SQLITE_E_ROW: Final = -2018574236 +SQLITE_E_DONE: Final = -2018574235 +SQLITE_E_IOERR_READ: Final = -2018574070 +SQLITE_E_IOERR_SHORT_READ: Final = -2018573814 +SQLITE_E_IOERR_WRITE: Final = -2018573558 +SQLITE_E_IOERR_FSYNC: Final = -2018573302 +SQLITE_E_IOERR_DIR_FSYNC: Final = -2018573046 +SQLITE_E_IOERR_TRUNCATE: Final = -2018572790 +SQLITE_E_IOERR_FSTAT: Final = -2018572534 +SQLITE_E_IOERR_UNLOCK: Final = -2018572278 +SQLITE_E_IOERR_RDLOCK: Final = -2018572022 +SQLITE_E_IOERR_DELETE: Final = -2018571766 +SQLITE_E_IOERR_BLOCKED: Final = -2018571510 +SQLITE_E_IOERR_NOMEM: Final = -2018571254 +SQLITE_E_IOERR_ACCESS: Final = -2018570998 +SQLITE_E_IOERR_CHECKRESERVEDLOCK: Final = -2018570742 +SQLITE_E_IOERR_LOCK: Final = -2018570486 +SQLITE_E_IOERR_CLOSE: Final = -2018570230 +SQLITE_E_IOERR_DIR_CLOSE: Final = -2018569974 +SQLITE_E_IOERR_SHMOPEN: Final = -2018569718 +SQLITE_E_IOERR_SHMSIZE: Final = -2018569462 +SQLITE_E_IOERR_SHMLOCK: Final = -2018569206 +SQLITE_E_IOERR_SHMMAP: Final = -2018568950 +SQLITE_E_IOERR_SEEK: Final = -2018568694 +SQLITE_E_IOERR_DELETE_NOENT: Final = -2018568438 +SQLITE_E_IOERR_MMAP: Final = -2018568182 +SQLITE_E_IOERR_GETTEMPPATH: Final = -2018567926 +SQLITE_E_IOERR_CONVPATH: Final = -2018567670 +SQLITE_E_IOERR_VNODE: Final = -2018567678 +SQLITE_E_IOERR_AUTH: Final = -2018567677 +SQLITE_E_LOCKED_SHAREDCACHE: Final = -2018574074 +SQLITE_E_BUSY_RECOVERY: Final = -2018574075 +SQLITE_E_BUSY_SNAPSHOT: Final = -2018573819 +SQLITE_E_CANTOPEN_NOTEMPDIR: Final = -2018574066 +SQLITE_E_CANTOPEN_ISDIR: Final = -2018573810 +SQLITE_E_CANTOPEN_FULLPATH: Final = -2018573554 +SQLITE_E_CANTOPEN_CONVPATH: Final = -2018573298 +SQLITE_E_CORRUPT_VTAB: Final = -2018574069 +SQLITE_E_READONLY_RECOVERY: Final = -2018574072 +SQLITE_E_READONLY_CANTLOCK: Final = -2018573816 +SQLITE_E_READONLY_ROLLBACK: Final = -2018573560 +SQLITE_E_READONLY_DBMOVED: Final = -2018573304 +SQLITE_E_ABORT_ROLLBACK: Final = -2018573820 +SQLITE_E_CONSTRAINT_CHECK: Final = -2018574061 +SQLITE_E_CONSTRAINT_COMMITHOOK: Final = -2018573805 +SQLITE_E_CONSTRAINT_FOREIGNKEY: Final = -2018573549 +SQLITE_E_CONSTRAINT_FUNCTION: Final = -2018573293 +SQLITE_E_CONSTRAINT_NOTNULL: Final = -2018573037 +SQLITE_E_CONSTRAINT_PRIMARYKEY: Final = -2018572781 +SQLITE_E_CONSTRAINT_TRIGGER: Final = -2018572525 +SQLITE_E_CONSTRAINT_UNIQUE: Final = -2018572269 +SQLITE_E_CONSTRAINT_VTAB: Final = -2018572013 +SQLITE_E_CONSTRAINT_ROWID: Final = -2018571757 +SQLITE_E_NOTICE_RECOVER_WAL: Final = -2018574053 +SQLITE_E_NOTICE_RECOVER_ROLLBACK: Final = -2018573797 +SQLITE_E_WARNING_AUTOINDEX: Final = -2018574052 +UTC_E_TOGGLE_TRACE_STARTED: Final = -2017128447 +UTC_E_ALTERNATIVE_TRACE_CANNOT_PREEMPT: Final = -2017128446 +UTC_E_AOT_NOT_RUNNING: Final = -2017128445 +UTC_E_SCRIPT_TYPE_INVALID: Final = -2017128444 +UTC_E_SCENARIODEF_NOT_FOUND: Final = -2017128443 +UTC_E_TRACEPROFILE_NOT_FOUND: Final = -2017128442 +UTC_E_FORWARDER_ALREADY_ENABLED: Final = -2017128441 +UTC_E_FORWARDER_ALREADY_DISABLED: Final = -2017128440 +UTC_E_EVENTLOG_ENTRY_MALFORMED: Final = -2017128439 +UTC_E_DIAGRULES_SCHEMAVERSION_MISMATCH: Final = -2017128438 +UTC_E_SCRIPT_TERMINATED: Final = -2017128437 +UTC_E_INVALID_CUSTOM_FILTER: Final = -2017128436 +UTC_E_TRACE_NOT_RUNNING: Final = -2017128435 +UTC_E_REESCALATED_TOO_QUICKLY: Final = -2017128434 +UTC_E_ESCALATION_ALREADY_RUNNING: Final = -2017128433 +UTC_E_PERFTRACK_ALREADY_TRACING: Final = -2017128432 +UTC_E_REACHED_MAX_ESCALATIONS: Final = -2017128431 +UTC_E_FORWARDER_PRODUCER_MISMATCH: Final = -2017128430 +UTC_E_INTENTIONAL_SCRIPT_FAILURE: Final = -2017128429 +UTC_E_SQM_INIT_FAILED: Final = -2017128428 +UTC_E_NO_WER_LOGGER_SUPPORTED: Final = -2017128427 +UTC_E_TRACERS_DONT_EXIST: Final = -2017128426 +UTC_E_WINRT_INIT_FAILED: Final = -2017128425 +UTC_E_SCENARIODEF_SCHEMAVERSION_MISMATCH: Final = -2017128424 +UTC_E_INVALID_FILTER: Final = -2017128423 +UTC_E_EXE_TERMINATED: Final = -2017128422 +UTC_E_ESCALATION_NOT_AUTHORIZED: Final = -2017128421 +UTC_E_SETUP_NOT_AUTHORIZED: Final = -2017128420 +UTC_E_CHILD_PROCESS_FAILED: Final = -2017128419 +UTC_E_COMMAND_LINE_NOT_AUTHORIZED: Final = -2017128418 +UTC_E_CANNOT_LOAD_SCENARIO_EDITOR_XML: Final = -2017128417 +UTC_E_ESCALATION_TIMED_OUT: Final = -2017128416 +UTC_E_SETUP_TIMED_OUT: Final = -2017128415 +UTC_E_TRIGGER_MISMATCH: Final = -2017128414 +UTC_E_TRIGGER_NOT_FOUND: Final = -2017128413 +UTC_E_SIF_NOT_SUPPORTED: Final = -2017128412 +UTC_E_DELAY_TERMINATED: Final = -2017128411 +UTC_E_DEVICE_TICKET_ERROR: Final = -2017128410 +UTC_E_TRACE_BUFFER_LIMIT_EXCEEDED: Final = -2017128409 +UTC_E_API_RESULT_UNAVAILABLE: Final = -2017128408 +UTC_E_RPC_TIMEOUT: Final = -2017128407 +UTC_E_RPC_WAIT_FAILED: Final = -2017128406 +UTC_E_API_BUSY: Final = -2017128405 +UTC_E_TRACE_MIN_DURATION_REQUIREMENT_NOT_MET: Final = -2017128404 +UTC_E_EXCLUSIVITY_NOT_AVAILABLE: Final = -2017128403 +UTC_E_GETFILE_FILE_PATH_NOT_APPROVED: Final = -2017128402 +UTC_E_ESCALATION_DIRECTORY_ALREADY_EXISTS: Final = -2017128401 +UTC_E_TIME_TRIGGER_ON_START_INVALID: Final = -2017128400 +UTC_E_TIME_TRIGGER_ONLY_VALID_ON_SINGLE_TRANSITION: Final = -2017128399 +UTC_E_TIME_TRIGGER_INVALID_TIME_RANGE: Final = -2017128398 +UTC_E_MULTIPLE_TIME_TRIGGER_ON_SINGLE_STATE: Final = -2017128397 +UTC_E_BINARY_MISSING: Final = -2017128396 +UTC_E_FAILED_TO_RESOLVE_CONTAINER_ID: Final = -2017128394 +UTC_E_UNABLE_TO_RESOLVE_SESSION: Final = -2017128393 +UTC_E_THROTTLED: Final = -2017128392 +UTC_E_UNAPPROVED_SCRIPT: Final = -2017128391 +UTC_E_SCRIPT_MISSING: Final = -2017128390 +UTC_E_SCENARIO_THROTTLED: Final = -2017128389 +UTC_E_API_NOT_SUPPORTED: Final = -2017128388 +UTC_E_GETFILE_EXTERNAL_PATH_NOT_APPROVED: Final = -2017128387 +UTC_E_TRY_GET_SCENARIO_TIMEOUT_EXCEEDED: Final = -2017128386 +UTC_E_CERT_REV_FAILED: Final = -2017128385 +UTC_E_FAILED_TO_START_NDISCAP: Final = -2017128384 +UTC_E_KERNELDUMP_LIMIT_REACHED: Final = -2017128383 +UTC_E_MISSING_AGGREGATE_EVENT_TAG: Final = -2017128382 +UTC_E_INVALID_AGGREGATION_STRUCT: Final = -2017128381 +UTC_E_ACTION_NOT_SUPPORTED_IN_DESTINATION: Final = -2017128380 +UTC_E_FILTER_MISSING_ATTRIBUTE: Final = -2017128379 +UTC_E_FILTER_INVALID_TYPE: Final = -2017128378 +UTC_E_FILTER_VARIABLE_NOT_FOUND: Final = -2017128377 +UTC_E_FILTER_FUNCTION_RESTRICTED: Final = -2017128376 +UTC_E_FILTER_VERSION_MISMATCH: Final = -2017128375 +UTC_E_FILTER_INVALID_FUNCTION: Final = -2017128368 +UTC_E_FILTER_INVALID_FUNCTION_PARAMS: Final = -2017128367 +UTC_E_FILTER_INVALID_COMMAND: Final = -2017128366 +UTC_E_FILTER_ILLEGAL_EVAL: Final = -2017128365 +UTC_E_TTTRACER_RETURNED_ERROR: Final = -2017128364 +UTC_E_AGENT_DIAGNOSTICS_TOO_LARGE: Final = -2017128363 +UTC_E_FAILED_TO_RECEIVE_AGENT_DIAGNOSTICS: Final = -2017128362 +UTC_E_SCENARIO_HAS_NO_ACTIONS: Final = -2017128361 +UTC_E_TTTRACER_STORAGE_FULL: Final = -2017128360 +UTC_E_INSUFFICIENT_SPACE_TO_START_TRACE: Final = -2017128359 +UTC_E_ESCALATION_CANCELLED_AT_SHUTDOWN: Final = -2017128358 +UTC_E_GETFILEINFOACTION_FILE_NOT_APPROVED: Final = -2017128357 +UTC_E_SETREGKEYACTION_TYPE_NOT_APPROVED: Final = -2017128356 +UTC_E_TRACE_THROTTLED: Final = -2017128355 +WINML_ERR_INVALID_DEVICE: Final = -2003828735 +WINML_ERR_INVALID_BINDING: Final = -2003828734 +WINML_ERR_VALUE_NOTFOUND: Final = -2003828733 +WINML_ERR_SIZE_MISMATCH: Final = -2003828732 +ERROR_QUIC_HANDSHAKE_FAILURE: Final = -2143223808 +ERROR_QUIC_VER_NEG_FAILURE: Final = -2143223807 +ERROR_QUIC_USER_CANCELED: Final = -2143223806 +ERROR_QUIC_INTERNAL_ERROR: Final = -2143223805 +ERROR_QUIC_PROTOCOL_VIOLATION: Final = -2143223804 +ERROR_QUIC_CONNECTION_IDLE: Final = -2143223803 +ERROR_QUIC_CONNECTION_TIMEOUT: Final = -2143223802 +ERROR_QUIC_ALPN_NEG_FAILURE: Final = -2143223801 +IORING_E_REQUIRED_FLAG_NOT_SUPPORTED: Final = -2142896127 +IORING_E_SUBMISSION_QUEUE_FULL: Final = -2142896126 +IORING_E_VERSION_NOT_SUPPORTED: Final = -2142896125 +IORING_E_SUBMISSION_QUEUE_TOO_BIG: Final = -2142896124 +IORING_E_COMPLETION_QUEUE_TOO_BIG: Final = -2142896123 +IORING_E_SUBMIT_IN_PROGRESS: Final = -2142896122 +IORING_E_CORRUPT: Final = -2142896121 +IORING_E_COMPLETION_QUEUE_TOO_FULL: Final = -2142896120 + +CDERR_DIALOGFAILURE: Final = 0xFFFF +CDERR_GENERALCODES: Final = 0x0000 +CDERR_STRUCTSIZE: Final = 0x0001 +CDERR_INITIALIZATION: Final = 0x0002 +CDERR_NOTEMPLATE: Final = 0x0003 +CDERR_NOHINSTANCE: Final = 0x0004 +CDERR_LOADSTRFAILURE: Final = 0x0005 +CDERR_FINDRESFAILURE: Final = 0x0006 +CDERR_LOADRESFAILURE: Final = 0x0007 +CDERR_LOCKRESFAILURE: Final = 0x0008 +CDERR_MEMALLOCFAILURE: Final = 0x0009 +CDERR_MEMLOCKFAILURE: Final = 0x000A +CDERR_NOHOOK: Final = 0x000B +CDERR_REGISTERMSGFAIL: Final = 0x000C +PDERR_PRINTERCODES: Final = 0x1000 +PDERR_SETUPFAILURE: Final = 0x1001 +PDERR_PARSEFAILURE: Final = 0x1002 +PDERR_RETDEFFAILURE: Final = 0x1003 +PDERR_LOADDRVFAILURE: Final = 0x1004 +PDERR_GETDEVMODEFAIL: Final = 0x1005 +PDERR_INITFAILURE: Final = 0x1006 +PDERR_NODEVICES: Final = 0x1007 +PDERR_NODEFAULTPRN: Final = 0x1008 +PDERR_DNDMMISMATCH: Final = 0x1009 +PDERR_CREATEICFAILURE: Final = 0x100A +PDERR_PRINTERNOTFOUND: Final = 0x100B +PDERR_DEFAULTDIFFERENT: Final = 0x100C +CFERR_CHOOSEFONTCODES: Final = 0x2000 +CFERR_NOFONTS: Final = 0x2001 +CFERR_MAXLESSTHANMIN: Final = 0x2002 +FNERR_FILENAMECODES: Final = 0x3000 +FNERR_SUBCLASSFAILURE: Final = 0x3001 +FNERR_INVALIDFILENAME: Final = 0x3002 +FNERR_BUFFERTOOSMALL: Final = 0x3003 +FRERR_FINDREPLACECODES: Final = 0x4000 +FRERR_BUFFERLENGTHZERO: Final = 0x4001 +CCERR_CHOOSECOLORCODES: Final = 0x5000 diff --git a/stubs/pywin32/win32/lib/winioctlcon.pyi b/stubs/pywin32/win32/lib/winioctlcon.pyi new file mode 100644 index 000000000000..1811b24aef2e --- /dev/null +++ b/stubs/pywin32/win32/lib/winioctlcon.pyi @@ -0,0 +1,662 @@ +from typing import Final + +import _win32typing +from ntsecuritycon import FILE_READ_DATA as FILE_READ_DATA, FILE_WRITE_DATA as FILE_WRITE_DATA + +def CTL_CODE(DeviceType: int, Function: int, Method: int, Access: int) -> int: ... +def DEVICE_TYPE_FROM_CTL_CODE(ctrlCode: int) -> int: ... + +FILE_DEVICE_BEEP: Final = 0x00000001 +FILE_DEVICE_CD_ROM: Final = 0x00000002 +FILE_DEVICE_CD_ROM_FILE_SYSTEM: Final = 0x00000003 +FILE_DEVICE_CONTROLLER: Final = 0x00000004 +FILE_DEVICE_DATALINK: Final = 0x00000005 +FILE_DEVICE_DFS: Final = 0x00000006 +FILE_DEVICE_DISK: Final = 0x00000007 +FILE_DEVICE_DISK_FILE_SYSTEM: Final = 0x00000008 +FILE_DEVICE_FILE_SYSTEM: Final = 0x00000009 +FILE_DEVICE_INPORT_PORT: Final = 0x0000000A +FILE_DEVICE_KEYBOARD: Final = 0x0000000B +FILE_DEVICE_MAILSLOT: Final = 0x0000000C +FILE_DEVICE_MIDI_IN: Final = 0x0000000D +FILE_DEVICE_MIDI_OUT: Final = 0x0000000E +FILE_DEVICE_MOUSE: Final = 0x0000000F +FILE_DEVICE_MULTI_UNC_PROVIDER: Final = 0x00000010 +FILE_DEVICE_NAMED_PIPE: Final = 0x00000011 +FILE_DEVICE_NETWORK: Final = 0x00000012 +FILE_DEVICE_NETWORK_BROWSER: Final = 0x00000013 +FILE_DEVICE_NETWORK_FILE_SYSTEM: Final = 0x00000014 +FILE_DEVICE_NULL: Final = 0x00000015 +FILE_DEVICE_PARALLEL_PORT: Final = 0x00000016 +FILE_DEVICE_PHYSICAL_NETCARD: Final = 0x00000017 +FILE_DEVICE_PRINTER: Final = 0x00000018 +FILE_DEVICE_SCANNER: Final = 0x00000019 +FILE_DEVICE_SERIAL_MOUSE_PORT: Final = 0x0000001A +FILE_DEVICE_SERIAL_PORT: Final = 0x0000001B +FILE_DEVICE_SCREEN: Final = 0x0000001C +FILE_DEVICE_SOUND: Final = 0x0000001D +FILE_DEVICE_STREAMS: Final = 0x0000001E +FILE_DEVICE_TAPE: Final = 0x0000001F +FILE_DEVICE_TAPE_FILE_SYSTEM: Final = 0x00000020 +FILE_DEVICE_TRANSPORT: Final = 0x00000021 +FILE_DEVICE_UNKNOWN: Final = 0x00000022 +FILE_DEVICE_VIDEO: Final = 0x00000023 +FILE_DEVICE_VIRTUAL_DISK: Final = 0x00000024 +FILE_DEVICE_WAVE_IN: Final = 0x00000025 +FILE_DEVICE_WAVE_OUT: Final = 0x00000026 +FILE_DEVICE_8042_PORT: Final = 0x00000027 +FILE_DEVICE_NETWORK_REDIRECTOR: Final = 0x00000028 +FILE_DEVICE_BATTERY: Final = 0x00000029 +FILE_DEVICE_BUS_EXTENDER: Final = 0x0000002A +FILE_DEVICE_MODEM: Final = 0x0000002B +FILE_DEVICE_VDM: Final = 0x0000002C +FILE_DEVICE_MASS_STORAGE: Final = 0x0000002D +FILE_DEVICE_SMB: Final = 0x0000002E +FILE_DEVICE_KS: Final = 0x0000002F +FILE_DEVICE_CHANGER: Final = 0x00000030 +FILE_DEVICE_SMARTCARD: Final = 0x00000031 +FILE_DEVICE_ACPI: Final = 0x00000032 +FILE_DEVICE_DVD: Final = 0x00000033 +FILE_DEVICE_FULLSCREEN_VIDEO: Final = 0x00000034 +FILE_DEVICE_DFS_FILE_SYSTEM: Final = 0x00000035 +FILE_DEVICE_DFS_VOLUME: Final = 0x00000036 +FILE_DEVICE_SERENUM: Final = 0x00000037 +FILE_DEVICE_TERMSRV: Final = 0x00000038 +FILE_DEVICE_KSEC: Final = 0x00000039 +FILE_DEVICE_FIPS: Final = 0x0000003A +FILE_DEVICE_INFINIBAND: Final = 0x0000003B +METHOD_BUFFERED: Final = 0 +METHOD_IN_DIRECT: Final = 1 +METHOD_OUT_DIRECT: Final = 2 +METHOD_NEITHER: Final = 3 +METHOD_DIRECT_TO_HARDWARE: Final = METHOD_IN_DIRECT +METHOD_DIRECT_FROM_HARDWARE: Final = METHOD_OUT_DIRECT +FILE_ANY_ACCESS: Final = 0 +FILE_SPECIAL_ACCESS: Final = FILE_ANY_ACCESS +FILE_READ_ACCESS: Final = 0x0001 +FILE_WRITE_ACCESS: Final = 0x0002 +IOCTL_STORAGE_BASE: Final = FILE_DEVICE_MASS_STORAGE +RECOVERED_WRITES_VALID: Final = 0x00000001 +UNRECOVERED_WRITES_VALID: Final = 0x00000002 +RECOVERED_READS_VALID: Final = 0x00000004 +UNRECOVERED_READS_VALID: Final = 0x00000008 +WRITE_COMPRESSION_INFO_VALID: Final = 0x00000010 +READ_COMPRESSION_INFO_VALID: Final = 0x00000020 +TAPE_RETURN_STATISTICS: Final = 0 +TAPE_RETURN_ENV_INFO: Final = 1 +TAPE_RESET_STATISTICS: Final = 2 +MEDIA_ERASEABLE: Final = 0x00000001 +MEDIA_WRITE_ONCE: Final = 0x00000002 +MEDIA_READ_ONLY: Final = 0x00000004 +MEDIA_READ_WRITE: Final = 0x00000008 +MEDIA_WRITE_PROTECTED: Final = 0x00000100 +MEDIA_CURRENTLY_MOUNTED: Final = 0x80000000 +IOCTL_DISK_BASE: Final = FILE_DEVICE_DISK +PARTITION_ENTRY_UNUSED: Final = 0x00 +PARTITION_FAT_12: Final = 0x01 +PARTITION_XENIX_1: Final = 0x02 +PARTITION_XENIX_2: Final = 0x03 +PARTITION_FAT_16: Final = 0x04 +PARTITION_EXTENDED: Final = 0x05 +PARTITION_HUGE: Final = 0x06 +PARTITION_IFS: Final = 0x07 +PARTITION_OS2BOOTMGR: Final = 0x0A +PARTITION_FAT32: Final = 0x0B +PARTITION_FAT32_XINT13: Final = 0x0C +PARTITION_XINT13: Final = 0x0E +PARTITION_XINT13_EXTENDED: Final = 0x0F +PARTITION_PREP: Final = 0x41 +PARTITION_LDM: Final = 0x42 +PARTITION_UNIX: Final = 0x63 +VALID_NTFT: Final = 0xC0 +PARTITION_NTFT: Final = 0x80 +GPT_ATTRIBUTE_PLATFORM_REQUIRED: Final = 0x00000001 +GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER: Final[int] +GPT_BASIC_DATA_ATTRIBUTE_HIDDEN: Final[int] +GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY: Final[int] +GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY: Final[int] +HIST_NO_OF_BUCKETS: Final = 24 +DISK_LOGGING_START: Final = 0 +DISK_LOGGING_STOP: Final = 1 +DISK_LOGGING_DUMP: Final = 2 +DISK_BINNING: Final = 3 +CAP_ATA_ID_CMD: Final = 1 +CAP_ATAPI_ID_CMD: Final = 2 +CAP_SMART_CMD: Final = 4 +ATAPI_ID_CMD: Final = 0xA1 +ID_CMD: Final = 0xEC +SMART_CMD: Final = 0xB0 +SMART_CYL_LOW: Final = 0x4F +SMART_CYL_HI: Final = 0xC2 +SMART_NO_ERROR: Final = 0 +SMART_IDE_ERROR: Final = 1 +SMART_INVALID_FLAG: Final = 2 +SMART_INVALID_COMMAND: Final = 3 +SMART_INVALID_BUFFER: Final = 4 +SMART_INVALID_DRIVE: Final = 5 +SMART_INVALID_IOCTL: Final = 6 +SMART_ERROR_NO_MEM: Final = 7 +SMART_INVALID_REGISTER: Final = 8 +SMART_NOT_SUPPORTED: Final = 9 +SMART_NO_IDE_DEVICE: Final = 10 +SMART_OFFLINE_ROUTINE_OFFLINE: Final = 0 +SMART_SHORT_SELFTEST_OFFLINE: Final = 1 +SMART_EXTENDED_SELFTEST_OFFLINE: Final = 2 +SMART_ABORT_OFFLINE_SELFTEST: Final = 127 +SMART_SHORT_SELFTEST_CAPTIVE: Final = 129 +SMART_EXTENDED_SELFTEST_CAPTIVE: Final = 130 +READ_ATTRIBUTE_BUFFER_SIZE: Final = 512 +IDENTIFY_BUFFER_SIZE: Final = 512 +READ_THRESHOLD_BUFFER_SIZE: Final = 512 +SMART_LOG_SECTOR_SIZE: Final = 512 +READ_ATTRIBUTES: Final = 0xD0 +READ_THRESHOLDS: Final = 0xD1 +ENABLE_DISABLE_AUTOSAVE: Final = 0xD2 +SAVE_ATTRIBUTE_VALUES: Final = 0xD3 +EXECUTE_OFFLINE_DIAGS: Final = 0xD4 +SMART_READ_LOG: Final = 0xD5 +SMART_WRITE_LOG: Final = 0xD6 +ENABLE_SMART: Final = 0xD8 +DISABLE_SMART: Final = 0xD9 +RETURN_SMART_STATUS: Final = 0xDA +ENABLE_DISABLE_AUTO_OFFLINE: Final = 0xDB +IOCTL_CHANGER_BASE: Final = FILE_DEVICE_CHANGER +MAX_VOLUME_ID_SIZE: Final = 36 +MAX_VOLUME_TEMPLATE_SIZE: Final = 40 +VENDOR_ID_LENGTH: Final = 8 +PRODUCT_ID_LENGTH: Final = 16 +REVISION_LENGTH: Final = 4 +SERIAL_NUMBER_LENGTH: Final = 32 +CHANGER_BAR_CODE_SCANNER_INSTALLED: Final = 0x00000001 +CHANGER_INIT_ELEM_STAT_WITH_RANGE: Final = 0x00000002 +CHANGER_CLOSE_IEPORT: Final = 0x00000004 +CHANGER_OPEN_IEPORT: Final = 0x00000008 +CHANGER_STATUS_NON_VOLATILE: Final = 0x00000010 +CHANGER_EXCHANGE_MEDIA: Final = 0x00000020 +CHANGER_CLEANER_SLOT: Final = 0x00000040 +CHANGER_LOCK_UNLOCK: Final = 0x00000080 +CHANGER_CARTRIDGE_MAGAZINE: Final = 0x00000100 +CHANGER_MEDIUM_FLIP: Final = 0x00000200 +CHANGER_POSITION_TO_ELEMENT: Final = 0x00000400 +CHANGER_REPORT_IEPORT_STATE: Final = 0x00000800 +CHANGER_STORAGE_DRIVE: Final = 0x00001000 +CHANGER_STORAGE_IEPORT: Final = 0x00002000 +CHANGER_STORAGE_SLOT: Final = 0x00004000 +CHANGER_STORAGE_TRANSPORT: Final = 0x00008000 +CHANGER_DRIVE_CLEANING_REQUIRED: Final = 0x00010000 +CHANGER_PREDISMOUNT_EJECT_REQUIRED: Final = 0x00020000 +CHANGER_CLEANER_ACCESS_NOT_VALID: Final = 0x00040000 +CHANGER_PREMOUNT_EJECT_REQUIRED: Final = 0x00080000 +CHANGER_VOLUME_IDENTIFICATION: Final = 0x00100000 +CHANGER_VOLUME_SEARCH: Final = 0x00200000 +CHANGER_VOLUME_ASSERT: Final = 0x00400000 +CHANGER_VOLUME_REPLACE: Final = 0x00800000 +CHANGER_VOLUME_UNDEFINE: Final = 0x01000000 +CHANGER_SERIAL_NUMBER_VALID: Final = 0x04000000 +CHANGER_DEVICE_REINITIALIZE_CAPABLE: Final = 0x08000000 +CHANGER_KEYPAD_ENABLE_DISABLE: Final = 0x10000000 +CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS: Final = 0x20000000 +CHANGER_RESERVED_BIT: Final = 0x80000000 +CHANGER_PREDISMOUNT_ALIGN_TO_SLOT: Final = 0x80000001 +CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE: Final = 0x80000002 +CHANGER_CLEANER_AUTODISMOUNT: Final = 0x80000004 +CHANGER_TRUE_EXCHANGE_CAPABLE: Final = 0x80000008 +CHANGER_SLOTS_USE_TRAYS: Final = 0x80000010 +CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR: Final = 0x80000020 +CHANGER_CLEANER_OPS_NOT_SUPPORTED: Final = 0x80000040 +CHANGER_IEPORT_USER_CONTROL_OPEN: Final = 0x80000080 +CHANGER_IEPORT_USER_CONTROL_CLOSE: Final = 0x80000100 +CHANGER_MOVE_EXTENDS_IEPORT: Final = 0x80000200 +CHANGER_MOVE_RETRACTS_IEPORT: Final = 0x80000400 +CHANGER_TO_TRANSPORT: Final = 0x01 +CHANGER_TO_SLOT: Final = 0x02 +CHANGER_TO_IEPORT: Final = 0x04 +CHANGER_TO_DRIVE: Final = 0x08 +LOCK_UNLOCK_IEPORT: Final = 0x01 +LOCK_UNLOCK_DOOR: Final = 0x02 +LOCK_UNLOCK_KEYPAD: Final = 0x04 +LOCK_ELEMENT: Final = 0 +UNLOCK_ELEMENT: Final = 1 +EXTEND_IEPORT: Final = 2 +RETRACT_IEPORT: Final = 3 +ELEMENT_STATUS_FULL: Final = 0x00000001 +ELEMENT_STATUS_IMPEXP: Final = 0x00000002 +ELEMENT_STATUS_EXCEPT: Final = 0x00000004 +ELEMENT_STATUS_ACCESS: Final = 0x00000008 +ELEMENT_STATUS_EXENAB: Final = 0x00000010 +ELEMENT_STATUS_INENAB: Final = 0x00000020 +ELEMENT_STATUS_PRODUCT_DATA: Final = 0x00000040 +ELEMENT_STATUS_LUN_VALID: Final = 0x00001000 +ELEMENT_STATUS_ID_VALID: Final = 0x00002000 +ELEMENT_STATUS_NOT_BUS: Final = 0x00008000 +ELEMENT_STATUS_INVERT: Final = 0x00400000 +ELEMENT_STATUS_SVALID: Final = 0x00800000 +ELEMENT_STATUS_PVOLTAG: Final = 0x10000000 +ELEMENT_STATUS_AVOLTAG: Final = 0x20000000 +ERROR_LABEL_UNREADABLE: Final = 0x00000001 +ERROR_LABEL_QUESTIONABLE: Final = 0x00000002 +ERROR_SLOT_NOT_PRESENT: Final = 0x00000004 +ERROR_DRIVE_NOT_INSTALLED: Final = 0x00000008 +ERROR_TRAY_MALFUNCTION: Final = 0x00000010 +ERROR_INIT_STATUS_NEEDED: Final = 0x00000011 +ERROR_UNHANDLED_ERROR: Final = 0xFFFFFFFF +SEARCH_ALL: Final = 0x0 +SEARCH_PRIMARY: Final = 0x1 +SEARCH_ALTERNATE: Final = 0x2 +SEARCH_ALL_NO_SEQ: Final = 0x4 +SEARCH_PRI_NO_SEQ: Final = 0x5 +SEARCH_ALT_NO_SEQ: Final = 0x6 +ASSERT_PRIMARY: Final = 0x8 +ASSERT_ALTERNATE: Final = 0x9 +REPLACE_PRIMARY: Final = 0xA +REPLACE_ALTERNATE: Final = 0xB +UNDEFINE_PRIMARY: Final = 0xC +UNDEFINE_ALTERNATE: Final = 0xD +USN_PAGE_SIZE: Final = 0x1000 +USN_REASON_DATA_OVERWRITE: Final = 0x00000001 +USN_REASON_DATA_EXTEND: Final = 0x00000002 +USN_REASON_DATA_TRUNCATION: Final = 0x00000004 +USN_REASON_NAMED_DATA_OVERWRITE: Final = 0x00000010 +USN_REASON_NAMED_DATA_EXTEND: Final = 0x00000020 +USN_REASON_NAMED_DATA_TRUNCATION: Final = 0x00000040 +USN_REASON_FILE_CREATE: Final = 0x00000100 +USN_REASON_FILE_DELETE: Final = 0x00000200 +USN_REASON_EA_CHANGE: Final = 0x00000400 +USN_REASON_SECURITY_CHANGE: Final = 0x00000800 +USN_REASON_RENAME_OLD_NAME: Final = 0x00001000 +USN_REASON_RENAME_NEW_NAME: Final = 0x00002000 +USN_REASON_INDEXABLE_CHANGE: Final = 0x00004000 +USN_REASON_BASIC_INFO_CHANGE: Final = 0x00008000 +USN_REASON_HARD_LINK_CHANGE: Final = 0x00010000 +USN_REASON_COMPRESSION_CHANGE: Final = 0x00020000 +USN_REASON_ENCRYPTION_CHANGE: Final = 0x00040000 +USN_REASON_OBJECT_ID_CHANGE: Final = 0x00080000 +USN_REASON_REPARSE_POINT_CHANGE: Final = 0x00100000 +USN_REASON_STREAM_CHANGE: Final = 0x00200000 +USN_REASON_TRANSACTED_CHANGE: Final = 0x00400000 +USN_REASON_CLOSE: Final = 0x80000000 +USN_DELETE_FLAG_DELETE: Final = 0x00000001 +USN_DELETE_FLAG_NOTIFY: Final = 0x00000002 +USN_DELETE_VALID_FLAGS: Final = 0x00000003 +USN_SOURCE_DATA_MANAGEMENT: Final = 0x00000001 +USN_SOURCE_AUXILIARY_DATA: Final = 0x00000002 +USN_SOURCE_REPLICATION_MANAGEMENT: Final = 0x00000004 +MARK_HANDLE_PROTECT_CLUSTERS: Final = 1 +MARK_HANDLE_TXF_SYSTEM_LOG: Final = 4 +MARK_HANDLE_NOT_TXF_SYSTEM_LOG: Final = 8 +VOLUME_IS_DIRTY: Final = 0x00000001 +VOLUME_UPGRADE_SCHEDULED: Final = 0x00000002 +VOLUME_SESSION_OPEN: Final = 4 +FILE_PREFETCH_TYPE_FOR_CREATE: Final = 1 +FILE_PREFETCH_TYPE_FOR_DIRENUM: Final = 2 +FILE_PREFETCH_TYPE_FOR_CREATE_EX: Final = 3 +FILE_PREFETCH_TYPE_FOR_DIRENUM_EX: Final = 4 +FILE_PREFETCH_TYPE_MAX: Final = 4 +FILESYSTEM_STATISTICS_TYPE_NTFS: Final = 1 +FILESYSTEM_STATISTICS_TYPE_FAT: Final = 2 +FILE_SET_ENCRYPTION: Final = 0x00000001 +FILE_CLEAR_ENCRYPTION: Final = 0x00000002 +STREAM_SET_ENCRYPTION: Final = 0x00000003 +STREAM_CLEAR_ENCRYPTION: Final = 0x00000004 +MAXIMUM_ENCRYPTION_VALUE: Final = 0x00000004 +ENCRYPTION_FORMAT_DEFAULT: Final = 0x01 +COMPRESSION_FORMAT_SPARSE: Final = 0x4000 +COPYFILE_SIS_LINK: Final = 0x0001 +COPYFILE_SIS_REPLACE: Final = 0x0002 +COPYFILE_SIS_FLAGS: Final = 0x0003 +WMI_DISK_GEOMETRY_GUID: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_CDROM: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_FLOPPY: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_COMPORT: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_DISK: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_STORAGEPORT: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_CDCHANGER: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_PARTITION: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_VOLUME: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_WRITEONCEDISK: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_TAPE: Final[_win32typing.PyIID] +GUID_DEVINTERFACE_MEDIUMCHANGER: Final[_win32typing.PyIID] +GUID_SERENUM_BUS_ENUMERATOR: Final = GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR +GUID_CLASS_COMPORT: Final = GUID_DEVINTERFACE_COMPORT +DiskClassGuid: Final = GUID_DEVINTERFACE_DISK +CdRomClassGuid: Final = GUID_DEVINTERFACE_CDROM +PartitionClassGuid: Final = GUID_DEVINTERFACE_PARTITION +TapeClassGuid: Final = GUID_DEVINTERFACE_TAPE +WriteOnceDiskClassGuid: Final = GUID_DEVINTERFACE_WRITEONCEDISK +VolumeClassGuid: Final = GUID_DEVINTERFACE_VOLUME +MediumChangerClassGuid: Final = GUID_DEVINTERFACE_MEDIUMCHANGER +FloppyClassGuid: Final = GUID_DEVINTERFACE_FLOPPY +CdChangerClassGuid: Final = GUID_DEVINTERFACE_CDCHANGER +StoragePortClassGuid: Final = GUID_DEVINTERFACE_STORAGEPORT +IOCTL_STORAGE_CHECK_VERIFY: Final = 2967552 +IOCTL_STORAGE_CHECK_VERIFY2: Final[int] +IOCTL_STORAGE_MEDIA_REMOVAL: Final[int] +IOCTL_STORAGE_EJECT_MEDIA: Final[int] +IOCTL_STORAGE_LOAD_MEDIA: Final[int] +IOCTL_STORAGE_LOAD_MEDIA2: Final[int] +IOCTL_STORAGE_RESERVE: Final[int] +IOCTL_STORAGE_RELEASE: Final[int] +IOCTL_STORAGE_FIND_NEW_DEVICES: Final[int] +IOCTL_STORAGE_EJECTION_CONTROL: Final[int] +IOCTL_STORAGE_MCN_CONTROL: Final[int] +IOCTL_STORAGE_GET_MEDIA_TYPES: Final[int] +IOCTL_STORAGE_GET_MEDIA_TYPES_EX: Final[int] +IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER: Final[int] +IOCTL_STORAGE_GET_HOTPLUG_INFO: Final[int] +IOCTL_STORAGE_SET_HOTPLUG_INFO: Final[int] +IOCTL_STORAGE_RESET_BUS: Final[int] +IOCTL_STORAGE_RESET_DEVICE: Final[int] +IOCTL_STORAGE_BREAK_RESERVATION: Final[int] +IOCTL_STORAGE_GET_DEVICE_NUMBER: Final[int] +IOCTL_STORAGE_PREDICT_FAILURE: Final[int] +IOCTL_DISK_GET_DRIVE_GEOMETRY: Final[int] +IOCTL_DISK_GET_PARTITION_INFO: Final[int] +IOCTL_DISK_SET_PARTITION_INFO: Final[int] +IOCTL_DISK_GET_DRIVE_LAYOUT: Final[int] +IOCTL_DISK_SET_DRIVE_LAYOUT: Final[int] +IOCTL_DISK_VERIFY: Final[int] +IOCTL_DISK_FORMAT_TRACKS: Final[int] +IOCTL_DISK_REASSIGN_BLOCKS: Final[int] +IOCTL_DISK_PERFORMANCE: Final[int] +IOCTL_DISK_IS_WRITABLE: Final[int] +IOCTL_DISK_LOGGING: Final[int] +IOCTL_DISK_FORMAT_TRACKS_EX: Final[int] +IOCTL_DISK_HISTOGRAM_STRUCTURE: Final[int] +IOCTL_DISK_HISTOGRAM_DATA: Final[int] +IOCTL_DISK_HISTOGRAM_RESET: Final[int] +IOCTL_DISK_REQUEST_STRUCTURE: Final[int] +IOCTL_DISK_REQUEST_DATA: Final[int] +IOCTL_DISK_PERFORMANCE_OFF: Final[int] +IOCTL_DISK_CONTROLLER_NUMBER: Final[int] +SMART_GET_VERSION: Final[int] +SMART_SEND_DRIVE_COMMAND: Final[int] +SMART_RCV_DRIVE_DATA: Final[int] +IOCTL_DISK_GET_PARTITION_INFO_EX: Final[int] +IOCTL_DISK_SET_PARTITION_INFO_EX: Final[int] +IOCTL_DISK_GET_DRIVE_LAYOUT_EX: Final[int] +IOCTL_DISK_SET_DRIVE_LAYOUT_EX: Final[int] +IOCTL_DISK_CREATE_DISK: Final[int] +IOCTL_DISK_GET_LENGTH_INFO: Final[int] +IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: Final[int] +IOCTL_DISK_REASSIGN_BLOCKS_EX: Final[int] +IOCTL_DISK_UPDATE_DRIVE_SIZE: Final[int] +IOCTL_DISK_GROW_PARTITION: Final[int] +IOCTL_DISK_GET_CACHE_INFORMATION: Final[int] +IOCTL_DISK_SET_CACHE_INFORMATION: Final[int] +OBSOLETE_IOCTL_STORAGE_RESET_BUS: Final[int] +OBSOLETE_IOCTL_STORAGE_RESET_DEVICE: Final[int] +OBSOLETE_DISK_GET_WRITE_CACHE_STATE: Final[int] +IOCTL_DISK_GET_WRITE_CACHE_STATE: Final = OBSOLETE_DISK_GET_WRITE_CACHE_STATE +IOCTL_DISK_DELETE_DRIVE_LAYOUT: Final[int] +IOCTL_DISK_UPDATE_PROPERTIES: Final[int] +IOCTL_DISK_FORMAT_DRIVE: Final[int] +IOCTL_DISK_SENSE_DEVICE: Final[int] +IOCTL_DISK_CHECK_VERIFY: Final[int] +IOCTL_DISK_MEDIA_REMOVAL: Final[int] +IOCTL_DISK_EJECT_MEDIA: Final[int] +IOCTL_DISK_LOAD_MEDIA: Final[int] +IOCTL_DISK_RESERVE: Final[int] +IOCTL_DISK_RELEASE: Final[int] +IOCTL_DISK_FIND_NEW_DEVICES: Final[int] +IOCTL_DISK_GET_MEDIA_TYPES: Final[int] +DISK_HISTOGRAM_SIZE: Final = 72 +HISTOGRAM_BUCKET_SIZE: Final = 8 +IOCTL_CHANGER_GET_PARAMETERS: Final[int] +IOCTL_CHANGER_GET_STATUS: Final[int] +IOCTL_CHANGER_GET_PRODUCT_DATA: Final[int] +IOCTL_CHANGER_SET_ACCESS: Final[int] +IOCTL_CHANGER_GET_ELEMENT_STATUS: Final[int] +IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS: Final[int] +IOCTL_CHANGER_SET_POSITION: Final[int] +IOCTL_CHANGER_EXCHANGE_MEDIUM: Final[int] +IOCTL_CHANGER_MOVE_MEDIUM: Final[int] +IOCTL_CHANGER_REINITIALIZE_TRANSPORT: Final[int] +IOCTL_CHANGER_QUERY_VOLUME_TAGS: Final[int] +IOCTL_SERIAL_LSRMST_INSERT: Final[int] +IOCTL_SERENUM_EXPOSE_HARDWARE: Final[int] +IOCTL_SERENUM_REMOVE_HARDWARE: Final[int] +IOCTL_SERENUM_PORT_DESC: Final[int] +IOCTL_SERENUM_GET_PORT_NAME: Final[int] +SERIAL_LSRMST_ESCAPE: Final = 0x00 +SERIAL_LSRMST_LSR_DATA: Final = 0x01 +SERIAL_LSRMST_LSR_NODATA: Final = 0x02 +SERIAL_LSRMST_MST: Final = 0x03 +SERIAL_IOC_FCR_FIFO_ENABLE: Final = 0x00000001 +SERIAL_IOC_FCR_RCVR_RESET: Final = 0x00000002 +SERIAL_IOC_FCR_XMIT_RESET: Final = 0x00000004 +SERIAL_IOC_FCR_DMA_MODE: Final = 0x00000008 +SERIAL_IOC_FCR_RES1: Final = 0x00000010 +SERIAL_IOC_FCR_RES2: Final = 0x00000020 +SERIAL_IOC_FCR_RCVR_TRIGGER_LSB: Final = 0x00000040 +SERIAL_IOC_FCR_RCVR_TRIGGER_MSB: Final = 0x00000080 +SERIAL_IOC_MCR_DTR: Final = 0x00000001 +SERIAL_IOC_MCR_RTS: Final = 0x00000002 +SERIAL_IOC_MCR_OUT1: Final = 0x00000004 +SERIAL_IOC_MCR_OUT2: Final = 0x00000008 +SERIAL_IOC_MCR_LOOP: Final = 0x00000010 +FSCTL_REQUEST_OPLOCK_LEVEL_1: Final[int] +FSCTL_REQUEST_OPLOCK_LEVEL_2: Final[int] +FSCTL_REQUEST_BATCH_OPLOCK: Final[int] +FSCTL_OPLOCK_BREAK_ACKNOWLEDGE: Final[int] +FSCTL_OPBATCH_ACK_CLOSE_PENDING: Final[int] +FSCTL_OPLOCK_BREAK_NOTIFY: Final[int] +FSCTL_LOCK_VOLUME: Final[int] +FSCTL_UNLOCK_VOLUME: Final[int] +FSCTL_DISMOUNT_VOLUME: Final[int] +FSCTL_IS_VOLUME_MOUNTED: Final[int] +FSCTL_IS_PATHNAME_VALID: Final[int] +FSCTL_MARK_VOLUME_DIRTY: Final[int] +FSCTL_QUERY_RETRIEVAL_POINTERS: Final[int] +FSCTL_GET_COMPRESSION: Final[int] +FSCTL_SET_COMPRESSION: Final[int] +FSCTL_MARK_AS_SYSTEM_HIVE: Final[int] +FSCTL_OPLOCK_BREAK_ACK_NO_2: Final[int] +FSCTL_INVALIDATE_VOLUMES: Final[int] +FSCTL_QUERY_FAT_BPB: Final[int] +FSCTL_REQUEST_FILTER_OPLOCK: Final[int] +FSCTL_FILESYSTEM_GET_STATISTICS: Final[int] +FSCTL_GET_NTFS_VOLUME_DATA: Final[int] +FSCTL_GET_NTFS_FILE_RECORD: Final[int] +FSCTL_GET_VOLUME_BITMAP: Final[int] +FSCTL_GET_RETRIEVAL_POINTERS: Final[int] +FSCTL_MOVE_FILE: Final[int] +FSCTL_IS_VOLUME_DIRTY: Final[int] +FSCTL_ALLOW_EXTENDED_DASD_IO: Final[int] +FSCTL_FIND_FILES_BY_SID: Final[int] +FSCTL_SET_OBJECT_ID: Final[int] +FSCTL_GET_OBJECT_ID: Final[int] +FSCTL_DELETE_OBJECT_ID: Final[int] +FSCTL_SET_REPARSE_POINT: Final[int] +FSCTL_GET_REPARSE_POINT: Final[int] +FSCTL_DELETE_REPARSE_POINT: Final[int] +FSCTL_ENUM_USN_DATA: Final[int] +FSCTL_SECURITY_ID_CHECK: Final[int] +FSCTL_READ_USN_JOURNAL: Final[int] +FSCTL_SET_OBJECT_ID_EXTENDED: Final[int] +FSCTL_CREATE_OR_GET_OBJECT_ID: Final[int] +FSCTL_SET_SPARSE: Final[int] +FSCTL_SET_ZERO_DATA: Final[int] +FSCTL_QUERY_ALLOCATED_RANGES: Final[int] +FSCTL_SET_ENCRYPTION: Final[int] +FSCTL_ENCRYPTION_FSCTL_IO: Final[int] +FSCTL_WRITE_RAW_ENCRYPTED: Final[int] +FSCTL_READ_RAW_ENCRYPTED: Final[int] +FSCTL_CREATE_USN_JOURNAL: Final[int] +FSCTL_READ_FILE_USN_DATA: Final[int] +FSCTL_WRITE_USN_CLOSE_RECORD: Final[int] +FSCTL_EXTEND_VOLUME: Final[int] +FSCTL_QUERY_USN_JOURNAL: Final[int] +FSCTL_DELETE_USN_JOURNAL: Final[int] +FSCTL_MARK_HANDLE: Final[int] +FSCTL_SIS_COPYFILE: Final[int] +FSCTL_SIS_LINK_FILES: Final[int] +FSCTL_HSM_MSG: Final[int] +FSCTL_HSM_DATA: Final[int] +FSCTL_RECALL_FILE: Final[int] +FSCTL_READ_FROM_PLEX: Final[int] +FSCTL_FILE_PREFETCH: Final[int] +FSCTL_MAKE_MEDIA_COMPATIBLE: Final[int] +FSCTL_SET_DEFECT_MANAGEMENT: Final[int] +FSCTL_QUERY_SPARING_INFO: Final[int] +FSCTL_QUERY_ON_DISK_VOLUME_INFO: Final[int] +FSCTL_SET_VOLUME_COMPRESSION_STATE: Final[int] +FSCTL_TXFS_MODIFY_RM: Final[int] +FSCTL_TXFS_QUERY_RM_INFORMATION: Final[int] +FSCTL_TXFS_ROLLFORWARD_REDO: Final[int] +FSCTL_TXFS_ROLLFORWARD_UNDO: Final[int] +FSCTL_TXFS_START_RM: Final[int] +FSCTL_TXFS_SHUTDOWN_RM: Final[int] +FSCTL_TXFS_READ_BACKUP_INFORMATION: Final[int] +FSCTL_TXFS_WRITE_BACKUP_INFORMATION: Final[int] +FSCTL_TXFS_CREATE_SECONDARY_RM: Final[int] +FSCTL_TXFS_GET_METADATA_INFO: Final[int] +FSCTL_TXFS_GET_TRANSACTED_VERSION: Final[int] +FSCTL_TXFS_CREATE_MINIVERSION: Final[int] +FSCTL_TXFS_TRANSACTION_ACTIVE: Final[int] +FSCTL_SET_ZERO_ON_DEALLOCATION: Final[int] +FSCTL_SET_REPAIR: Final[int] +FSCTL_GET_REPAIR: Final[int] +FSCTL_WAIT_FOR_REPAIR: Final[int] +FSCTL_INITIATE_REPAIR: Final[int] +FSCTL_CSC_INTERNAL: Final[int] +FSCTL_SHRINK_VOLUME: Final[int] +FSCTL_SET_SHORT_NAME_BEHAVIOR: Final[int] +FSCTL_DFSR_SET_GHOST_HANDLE_STATE: Final[int] +FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES: Final[int] +FSCTL_TXFS_LIST_TRANSACTIONS: Final[int] +FSCTL_QUERY_PAGEFILE_ENCRYPTION: Final[int] +IOCTL_VOLUME_BASE: Final = 86 +IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: Final[int] +IOCTL_VOLUME_ONLINE: Final[int] +IOCTL_VOLUME_OFFLINE: Final[int] +IOCTL_VOLUME_IS_CLUSTERED: Final[int] +IOCTL_VOLUME_GET_GPT_ATTRIBUTES: Final[int] +DDS_4mm: Final = 32 +MiniQic: Final = 33 +Travan: Final = 34 +QIC: Final = 35 +MP_8mm: Final = 36 +AME_8mm: Final = 37 +AIT1_8mm: Final = 38 +DLT: Final = 39 +NCTP: Final = 40 +IBM_3480: Final = 41 +IBM_3490E: Final = 42 +IBM_Magstar_3590: Final = 43 +IBM_Magstar_MP: Final = 44 +STK_DATA_D3: Final = 45 +SONY_DTF: Final = 46 +DV_6mm: Final = 47 +DMI: Final = 48 +SONY_D2: Final = 49 +CLEANER_CARTRIDGE: Final = 50 +CD_ROM: Final = 51 +CD_R: Final = 52 +CD_RW: Final = 53 +DVD_ROM: Final = 54 +DVD_R: Final = 55 +DVD_RW: Final = 56 +MO_3_RW: Final = 57 +MO_5_WO: Final = 58 +MO_5_RW: Final = 59 +MO_5_LIMDOW: Final = 60 +PC_5_WO: Final = 61 +PC_5_RW: Final = 62 +PD_5_RW: Final = 63 +ABL_5_WO: Final = 64 +PINNACLE_APEX_5_RW: Final = 65 +SONY_12_WO: Final = 66 +PHILIPS_12_WO: Final = 67 +HITACHI_12_WO: Final = 68 +CYGNET_12_WO: Final = 69 +KODAK_14_WO: Final = 70 +MO_NFR_525: Final = 71 +NIKON_12_RW: Final = 72 +IOMEGA_ZIP: Final = 73 +IOMEGA_JAZ: Final = 74 +SYQUEST_EZ135: Final = 75 +SYQUEST_EZFLYER: Final = 76 +SYQUEST_SYJET: Final = 77 +AVATAR_F2: Final = 78 +MP2_8mm: Final = 79 +DST_S: Final = 80 +DST_M: Final = 81 +DST_L: Final = 82 +VXATape_1: Final = 83 +VXATape_2: Final = 84 +STK_9840: Final = 85 +LTO_Ultrium: Final = 86 +LTO_Accelis: Final = 87 +DVD_RAM: Final = 88 +AIT_8mm: Final = 89 +ADR_1: Final = 90 +ADR_2: Final = 91 +STK_9940: Final = 92 +BusTypeUnknown: Final = 0 +BusTypeScsi: Final = 1 +BusTypeAtapi: Final = 2 +BusTypeAta: Final = 3 +BusType1394: Final = 4 +BusTypeSsa: Final = 5 +BusTypeFibre: Final = 6 +BusTypeUsb: Final = 7 +BusTypeRAID: Final = 8 +BusTypeiScsi: Final = 9 +BusTypeSas: Final = 10 +BusTypeSata: Final = 11 +BusTypeMaxReserved: Final = 127 +Unknown: Final = 0 +F5_1Pt2_512: Final = 1 +F3_1Pt44_512: Final = 2 +F3_2Pt88_512: Final = 3 +F3_20Pt8_512: Final = 4 +F3_720_512: Final = 5 +F5_360_512: Final = 6 +F5_320_512: Final = 7 +F5_320_1024: Final = 8 +F5_180_512: Final = 9 +F5_160_512: Final = 10 +RemovableMedia: Final = 11 +FixedMedia: Final = 12 +F3_120M_512: Final = 13 +F3_640_512: Final = 14 +F5_640_512: Final = 15 +F5_720_512: Final = 16 +F3_1Pt2_512: Final = 17 +F3_1Pt23_1024: Final = 18 +F5_1Pt23_1024: Final = 19 +F3_128Mb_512: Final = 20 +F3_230Mb_512: Final = 21 +F8_256_128: Final = 22 +F3_200Mb_512: Final = 23 +F3_240M_512: Final = 24 +F3_32M_512: Final = 25 +PARTITION_STYLE_MBR: Final = 0 +PARTITION_STYLE_GPT: Final = 1 +PARTITION_STYLE_RAW: Final = 2 +DetectNone: Final = 0 +DetectInt13: Final = 1 +DetectExInt13: Final = 2 +EqualPriority: Final = 0 +KeepPrefetchedData: Final = 1 +KeepReadData: Final = 2 +DiskWriteCacheNormal: Final = 0 +DiskWriteCacheForceDisable: Final = 1 +DiskWriteCacheDisableNotSupported: Final = 2 +RequestSize: Final = 0 +RequestLocation: Final = 1 +DeviceProblemNone: Final = 0 +DeviceProblemHardware: Final = 1 +DeviceProblemCHMError: Final = 2 +DeviceProblemDoorOpen: Final = 3 +DeviceProblemCalibrationError: Final = 4 +DeviceProblemTargetFailure: Final = 5 +DeviceProblemCHMMoveError: Final = 6 +DeviceProblemCHMZeroError: Final = 7 +DeviceProblemCartridgeInsertError: Final = 8 +DeviceProblemPositionError: Final = 9 +DeviceProblemSensorError: Final = 10 +DeviceProblemCartridgeEjectError: Final = 11 +DeviceProblemGripperError: Final = 12 +DeviceProblemDriveError: Final = 13 diff --git a/stubs/pywin32/win32/lib/winnt.pyi b/stubs/pywin32/win32/lib/winnt.pyi new file mode 100644 index 000000000000..eea472c68c3b --- /dev/null +++ b/stubs/pywin32/win32/lib/winnt.pyi @@ -0,0 +1,1134 @@ +from typing import Final + +APPLICATION_ERROR_MASK: Final = 536870912 +ERROR_SEVERITY_SUCCESS: Final = 0 +ERROR_SEVERITY_INFORMATIONAL: Final = 1073741824 +ERROR_SEVERITY_WARNING: Final = -2147483648 +ERROR_SEVERITY_ERROR: Final = -1073741824 +MINCHAR: Final = 128 +MAXCHAR: Final = 127 +MINSHORT: Final = 32768 +MAXSHORT: Final = 32767 +MINLONG: Final = -2147483648 +MAXLONG: Final = 2147483647 +MAXBYTE: Final = 255 +MAXWORD: Final = 65535 +MAXDWORD: Final = -1 +LANG_NEUTRAL: Final = 0 +LANG_AFRIKAANS: Final = 54 +LANG_ALBANIAN: Final = 28 +LANG_ARABIC: Final = 1 +LANG_BASQUE: Final = 45 +LANG_BELARUSIAN: Final = 35 +LANG_BULGARIAN: Final = 2 +LANG_CATALAN: Final = 3 +LANG_CHINESE: Final = 4 +LANG_CROATIAN: Final = 26 +LANG_CZECH: Final = 5 +LANG_DANISH: Final = 6 +LANG_DUTCH: Final = 19 +LANG_ENGLISH: Final = 9 +LANG_ESTONIAN: Final = 37 +LANG_FAEROESE: Final = 56 +LANG_FARSI: Final = 41 +LANG_FINNISH: Final = 11 +LANG_FRENCH: Final = 12 +LANG_GERMAN: Final = 7 +LANG_GREEK: Final = 8 +LANG_HEBREW: Final = 13 +LANG_HINDI: Final = 57 +LANG_HUNGARIAN: Final = 14 +LANG_ICELANDIC: Final = 15 +LANG_INDONESIAN: Final = 33 +LANG_ITALIAN: Final = 16 +LANG_JAPANESE: Final = 17 +LANG_KOREAN: Final = 18 +LANG_LATVIAN: Final = 38 +LANG_LITHUANIAN: Final = 39 +LANG_MACEDONIAN: Final = 47 +LANG_MALAY: Final = 62 +LANG_NORWEGIAN: Final = 20 +LANG_POLISH: Final = 21 +LANG_PORTUGUESE: Final = 22 +LANG_ROMANIAN: Final = 24 +LANG_RUSSIAN: Final = 25 +LANG_SERBIAN: Final = 26 +LANG_SLOVAK: Final = 27 +LANG_SLOVENIAN: Final = 36 +LANG_SPANISH: Final = 10 +LANG_SWAHILI: Final = 65 +LANG_SWEDISH: Final = 29 +LANG_THAI: Final = 30 +LANG_TURKISH: Final = 31 +LANG_UKRAINIAN: Final = 34 +LANG_VIETNAMESE: Final = 42 +SUBLANG_NEUTRAL: Final = 0 +SUBLANG_DEFAULT: Final = 1 +SUBLANG_SYS_DEFAULT: Final = 2 +SUBLANG_ARABIC_SAUDI_ARABIA: Final = 1 +SUBLANG_ARABIC_IRAQ: Final = 2 +SUBLANG_ARABIC_EGYPT: Final = 3 +SUBLANG_ARABIC_LIBYA: Final = 4 +SUBLANG_ARABIC_ALGERIA: Final = 5 +SUBLANG_ARABIC_MOROCCO: Final = 6 +SUBLANG_ARABIC_TUNISIA: Final = 7 +SUBLANG_ARABIC_OMAN: Final = 8 +SUBLANG_ARABIC_YEMEN: Final = 9 +SUBLANG_ARABIC_SYRIA: Final = 10 +SUBLANG_ARABIC_JORDAN: Final = 11 +SUBLANG_ARABIC_LEBANON: Final = 12 +SUBLANG_ARABIC_KUWAIT: Final = 13 +SUBLANG_ARABIC_UAE: Final = 14 +SUBLANG_ARABIC_BAHRAIN: Final = 15 +SUBLANG_ARABIC_QATAR: Final = 16 +SUBLANG_CHINESE_TRADITIONAL: Final = 1 +SUBLANG_CHINESE_SIMPLIFIED: Final = 2 +SUBLANG_CHINESE_HONGKONG: Final = 3 +SUBLANG_CHINESE_SINGAPORE: Final = 4 +SUBLANG_CHINESE_MACAU: Final = 5 +SUBLANG_DUTCH: Final = 1 +SUBLANG_DUTCH_BELGIAN: Final = 2 +SUBLANG_ENGLISH_US: Final = 1 +SUBLANG_ENGLISH_UK: Final = 2 +SUBLANG_ENGLISH_AUS: Final = 3 +SUBLANG_ENGLISH_CAN: Final = 4 +SUBLANG_ENGLISH_NZ: Final = 5 +SUBLANG_ENGLISH_EIRE: Final = 6 +SUBLANG_ENGLISH_SOUTH_AFRICA: Final = 7 +SUBLANG_ENGLISH_JAMAICA: Final = 8 +SUBLANG_ENGLISH_CARIBBEAN: Final = 9 +SUBLANG_ENGLISH_BELIZE: Final = 10 +SUBLANG_ENGLISH_TRINIDAD: Final = 11 +SUBLANG_ENGLISH_ZIMBABWE: Final = 12 +SUBLANG_ENGLISH_PHILIPPINES: Final = 13 +SUBLANG_FRENCH: Final = 1 +SUBLANG_FRENCH_BELGIAN: Final = 2 +SUBLANG_FRENCH_CANADIAN: Final = 3 +SUBLANG_FRENCH_SWISS: Final = 4 +SUBLANG_FRENCH_LUXEMBOURG: Final = 5 +SUBLANG_FRENCH_MONACO: Final = 6 +SUBLANG_GERMAN: Final = 1 +SUBLANG_GERMAN_SWISS: Final = 2 +SUBLANG_GERMAN_AUSTRIAN: Final = 3 +SUBLANG_GERMAN_LUXEMBOURG: Final = 4 +SUBLANG_GERMAN_LIECHTENSTEIN: Final = 5 +SUBLANG_ITALIAN: Final = 1 +SUBLANG_ITALIAN_SWISS: Final = 2 +SUBLANG_KOREAN: Final = 1 +SUBLANG_KOREAN_JOHAB: Final = 2 +SUBLANG_LITHUANIAN: Final = 1 +SUBLANG_LITHUANIAN_CLASSIC: Final = 2 +SUBLANG_MALAY_MALAYSIA: Final = 1 +SUBLANG_MALAY_BRUNEI_DARUSSALAM: Final = 2 +SUBLANG_NORWEGIAN_BOKMAL: Final = 1 +SUBLANG_NORWEGIAN_NYNORSK: Final = 2 +SUBLANG_PORTUGUESE: Final = 2 +SUBLANG_PORTUGUESE_BRAZILIAN: Final = 1 +SUBLANG_SERBIAN_LATIN: Final = 2 +SUBLANG_SERBIAN_CYRILLIC: Final = 3 +SUBLANG_SPANISH: Final = 1 +SUBLANG_SPANISH_MEXICAN: Final = 2 +SUBLANG_SPANISH_MODERN: Final = 3 +SUBLANG_SPANISH_GUATEMALA: Final = 4 +SUBLANG_SPANISH_COSTA_RICA: Final = 5 +SUBLANG_SPANISH_PANAMA: Final = 6 +SUBLANG_SPANISH_DOMINICAN_REPUBLIC: Final = 7 +SUBLANG_SPANISH_VENEZUELA: Final = 8 +SUBLANG_SPANISH_COLOMBIA: Final = 9 +SUBLANG_SPANISH_PERU: Final = 10 +SUBLANG_SPANISH_ARGENTINA: Final = 11 +SUBLANG_SPANISH_ECUADOR: Final = 12 +SUBLANG_SPANISH_CHILE: Final = 13 +SUBLANG_SPANISH_URUGUAY: Final = 14 +SUBLANG_SPANISH_PARAGUAY: Final = 15 +SUBLANG_SPANISH_BOLIVIA: Final = 16 +SUBLANG_SPANISH_EL_SALVADOR: Final = 17 +SUBLANG_SPANISH_HONDURAS: Final = 18 +SUBLANG_SPANISH_NICARAGUA: Final = 19 +SUBLANG_SPANISH_PUERTO_RICO: Final = 20 +SUBLANG_SWEDISH: Final = 1 +SUBLANG_SWEDISH_FINLAND: Final = 2 +SORT_DEFAULT: Final = 0 +SORT_JAPANESE_XJIS: Final = 0 +SORT_JAPANESE_UNICODE: Final = 1 +SORT_CHINESE_BIG5: Final = 0 +SORT_CHINESE_PRCP: Final = 0 +SORT_CHINESE_UNICODE: Final = 1 +SORT_CHINESE_PRC: Final = 2 +SORT_KOREAN_KSC: Final = 0 +SORT_KOREAN_UNICODE: Final = 1 +SORT_GERMAN_PHONE_BOOK: Final = 1 + +def PRIMARYLANGID(lgid: int) -> int: ... +def SUBLANGID(lgid: int) -> int: ... + +NLS_VALID_LOCALE_MASK: Final = 1048575 + +def LANGIDFROMLCID(lcid: int) -> int: ... +def SORTIDFROMLCID(lcid: int) -> int: ... + +MAXIMUM_WAIT_OBJECTS: Final = 64 +MAXIMUM_SUSPEND_COUNT: Final = MAXCHAR +EXCEPTION_NONCONTINUABLE: Final = 1 +EXCEPTION_MAXIMUM_PARAMETERS: Final = 15 +PROCESS_TERMINATE: Final = 1 +PROCESS_CREATE_THREAD: Final = 2 +PROCESS_VM_OPERATION: Final = 8 +PROCESS_VM_READ: Final = 16 +PROCESS_VM_WRITE: Final = 32 +PROCESS_DUP_HANDLE: Final = 64 +PROCESS_CREATE_PROCESS: Final = 128 +PROCESS_SET_QUOTA: Final = 256 +PROCESS_SET_INFORMATION: Final = 512 +PROCESS_QUERY_INFORMATION: Final = 1024 +PROCESS_SUSPEND_RESUME: Final = 2048 +PROCESS_QUERY_LIMITED_INFORMATION: Final = 4096 +PROCESS_SET_LIMITED_INFORMATION: Final = 8192 +MAXIMUM_PROCESSORS: Final = 32 +THREAD_TERMINATE: Final = 1 +THREAD_SUSPEND_RESUME: Final = 2 +THREAD_GET_CONTEXT: Final = 8 +THREAD_SET_CONTEXT: Final = 16 +THREAD_SET_INFORMATION: Final = 32 +THREAD_QUERY_INFORMATION: Final = 64 +THREAD_SET_THREAD_TOKEN: Final = 128 +THREAD_IMPERSONATE: Final = 256 +THREAD_DIRECT_IMPERSONATION: Final = 512 +THREAD_SET_LIMITED_INFORMATION: Final = 1024 +THREAD_QUERY_LIMITED_INFORMATION: Final = 2048 +THREAD_RESUME: Final = 4096 +JOB_OBJECT_ASSIGN_PROCESS: Final = 1 +JOB_OBJECT_SET_ATTRIBUTES: Final = 2 +JOB_OBJECT_QUERY: Final = 4 +JOB_OBJECT_TERMINATE: Final = 8 +TLS_MINIMUM_AVAILABLE: Final = 64 +THREAD_BASE_PRIORITY_LOWRT: Final = 15 +THREAD_BASE_PRIORITY_MAX: Final = 2 +THREAD_BASE_PRIORITY_MIN: Final = -2 +THREAD_BASE_PRIORITY_IDLE: Final = -15 +JOB_OBJECT_LIMIT_WORKINGSET: Final = 1 +JOB_OBJECT_LIMIT_PROCESS_TIME: Final = 2 +JOB_OBJECT_LIMIT_JOB_TIME: Final = 4 +JOB_OBJECT_LIMIT_ACTIVE_PROCESS: Final = 8 +JOB_OBJECT_LIMIT_AFFINITY: Final = 16 +JOB_OBJECT_LIMIT_PRIORITY_CLASS: Final = 32 +JOB_OBJECT_LIMIT_VALID_FLAGS: Final = 63 +EVENT_MODIFY_STATE: Final = 2 +MUTANT_QUERY_STATE: Final = 1 +SEMAPHORE_MODIFY_STATE: Final = 2 +TIME_ZONE_ID_UNKNOWN: Final = 0 +TIME_ZONE_ID_STANDARD: Final = 1 +TIME_ZONE_ID_DAYLIGHT: Final = 2 +PROCESSOR_INTEL_386: Final = 386 +PROCESSOR_INTEL_486: Final = 486 +PROCESSOR_INTEL_PENTIUM: Final = 586 +PROCESSOR_MIPS_R4000: Final = 4000 +PROCESSOR_ALPHA_21064: Final = 21064 +PROCESSOR_HITACHI_SH3: Final = 10003 +PROCESSOR_HITACHI_SH3E: Final = 10004 +PROCESSOR_HITACHI_SH4: Final = 10005 +PROCESSOR_MOTOROLA_821: Final = 821 +PROCESSOR_ARM_7TDMI: Final = 70001 +PROCESSOR_ARCHITECTURE_INTEL: Final = 0 +PROCESSOR_ARCHITECTURE_MIPS: Final = 1 +PROCESSOR_ARCHITECTURE_ALPHA: Final = 2 +PROCESSOR_ARCHITECTURE_PPC: Final = 3 +PROCESSOR_ARCHITECTURE_SH: Final = 4 +PROCESSOR_ARCHITECTURE_ARM: Final = 5 +PROCESSOR_ARCHITECTURE_IA64: Final = 6 +PROCESSOR_ARCHITECTURE_ALPHA64: Final = 7 +PROCESSOR_ARCHITECTURE_MSIL: Final = 8 +PROCESSOR_ARCHITECTURE_AMD64: Final = 9 +PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: Final = 10 +PROCESSOR_ARCHITECTURE_UNKNOWN: Final = 65535 +PF_FLOATING_POINT_PRECISION_ERRATA: Final = 0 +PF_FLOATING_POINT_EMULATED: Final = 1 +PF_COMPARE_EXCHANGE_DOUBLE: Final = 2 +PF_MMX_INSTRUCTIONS_AVAILABLE: Final = 3 +PF_PPC_MOVEMEM_64BIT_OK: Final = 4 +PF_ALPHA_BYTE_INSTRUCTIONS: Final = 5 +SECTION_QUERY: Final = 1 +SECTION_MAP_WRITE: Final = 2 +SECTION_MAP_READ: Final = 4 +SECTION_MAP_EXECUTE: Final = 8 +SECTION_EXTEND_SIZE: Final = 16 +PAGE_NOACCESS: Final = 1 +PAGE_READONLY: Final = 2 +PAGE_READWRITE: Final = 4 +PAGE_WRITECOPY: Final = 8 +PAGE_EXECUTE: Final = 16 +PAGE_EXECUTE_READ: Final = 32 +PAGE_EXECUTE_READWRITE: Final = 64 +PAGE_EXECUTE_WRITECOPY: Final = 128 +PAGE_GUARD: Final = 256 +PAGE_NOCACHE: Final = 512 +MEM_COMMIT: Final = 4096 +MEM_RESERVE: Final = 8192 +MEM_DECOMMIT: Final = 16384 +MEM_RELEASE: Final = 32768 +MEM_FREE: Final = 65536 +MEM_PRIVATE: Final = 131072 +MEM_MAPPED: Final = 262144 +MEM_RESET: Final = 524288 +MEM_TOP_DOWN: Final = 1048576 +MEM_4MB_PAGES: Final = -2147483648 +SEC_FILE: Final = 8388608 +SEC_IMAGE: Final = 16777216 +SEC_VLM: Final = 33554432 +SEC_RESERVE: Final = 67108864 +SEC_COMMIT: Final = 134217728 +SEC_NOCACHE: Final = 268435456 +MEM_IMAGE: Final = SEC_IMAGE +FILE_READ_DATA: Final = 1 +FILE_LIST_DIRECTORY: Final = 1 +FILE_WRITE_DATA: Final = 2 +FILE_ADD_FILE: Final = 2 +FILE_APPEND_DATA: Final = 4 +FILE_ADD_SUBDIRECTORY: Final = 4 +FILE_CREATE_PIPE_INSTANCE: Final = 4 +FILE_READ_EA: Final = 8 +FILE_WRITE_EA: Final = 16 +FILE_EXECUTE: Final = 32 +FILE_TRAVERSE: Final = 32 +FILE_DELETE_CHILD: Final = 64 +FILE_READ_ATTRIBUTES: Final = 128 +FILE_WRITE_ATTRIBUTES: Final = 256 +FILE_SHARE_READ: Final = 1 +FILE_SHARE_WRITE: Final = 2 +FILE_SHARE_DELETE: Final = 4 +FILE_ATTRIBUTE_READONLY: Final = 1 +FILE_ATTRIBUTE_HIDDEN: Final = 2 +FILE_ATTRIBUTE_SYSTEM: Final = 4 +FILE_ATTRIBUTE_DIRECTORY: Final = 16 +FILE_ATTRIBUTE_ARCHIVE: Final = 32 +FILE_ATTRIBUTE_DEVICE: Final = 64 +FILE_ATTRIBUTE_NORMAL: Final = 128 +FILE_ATTRIBUTE_TEMPORARY: Final = 256 +FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 +FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 +FILE_ATTRIBUTE_COMPRESSED: Final = 2048 +FILE_ATTRIBUTE_OFFLINE: Final = 4096 +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 +FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 +FILE_ATTRIBUTE_VIRTUAL: Final = 65536 +FILE_NOTIFY_CHANGE_FILE_NAME: Final = 1 +FILE_NOTIFY_CHANGE_DIR_NAME: Final = 2 +FILE_NOTIFY_CHANGE_ATTRIBUTES: Final = 4 +FILE_NOTIFY_CHANGE_SIZE: Final = 8 +FILE_NOTIFY_CHANGE_LAST_WRITE: Final = 16 +FILE_NOTIFY_CHANGE_LAST_ACCESS: Final = 32 +FILE_NOTIFY_CHANGE_CREATION: Final = 64 +FILE_NOTIFY_CHANGE_SECURITY: Final = 256 +FILE_ACTION_ADDED: Final = 1 +FILE_ACTION_REMOVED: Final = 2 +FILE_ACTION_MODIFIED: Final = 3 +FILE_ACTION_RENAMED_OLD_NAME: Final = 4 +FILE_ACTION_RENAMED_NEW_NAME: Final = 5 +FILE_CASE_SENSITIVE_SEARCH: Final = 1 +FILE_CASE_PRESERVED_NAMES: Final = 2 +FILE_UNICODE_ON_DISK: Final = 4 +FILE_PERSISTENT_ACLS: Final = 8 +FILE_FILE_COMPRESSION: Final = 16 +FILE_VOLUME_QUOTAS: Final = 32 +FILE_SUPPORTS_SPARSE_FILES: Final = 64 +FILE_SUPPORTS_REPARSE_POINTS: Final = 128 +FILE_SUPPORTS_REMOTE_STORAGE: Final = 256 +FILE_VOLUME_IS_COMPRESSED: Final = 32768 +FILE_SUPPORTS_OBJECT_IDS: Final = 65536 +FILE_SUPPORTS_ENCRYPTION: Final = 131072 +MAXIMUM_REPARSE_DATA_BUFFER_SIZE: Final = 16384 +IO_REPARSE_TAG_RESERVED_ZERO: Final = 0 +IO_REPARSE_TAG_RESERVED_ONE: Final = 1 +IO_REPARSE_TAG_SYMBOLIC_LINK: Final = 2 +IO_REPARSE_TAG_NSS: Final = 5 +IO_REPARSE_TAG_FILTER_MANAGER: Final = -2147483637 +IO_REPARSE_TAG_DFS: Final = -2147483638 +IO_REPARSE_TAG_SIS: Final = -2147483641 +IO_REPARSE_TAG_MOUNT_POINT: Final = -1610612733 +IO_REPARSE_TAG_HSM: Final = -1073741820 +IO_REPARSE_TAG_NSSRECOVER: Final = 8 +IO_REPARSE_TAG_RESERVED_MS_RANGE: Final = 256 +IO_REPARSE_TAG_RESERVED_RANGE: Final = IO_REPARSE_TAG_RESERVED_ONE +IO_COMPLETION_MODIFY_STATE: Final = 2 +DUPLICATE_CLOSE_SOURCE: Final = 1 +DUPLICATE_SAME_ACCESS: Final = 2 +DELETE: Final = 65536 +READ_CONTROL: Final = 131072 +WRITE_DAC: Final = 262144 +WRITE_OWNER: Final = 524288 +SYNCHRONIZE: Final = 1048576 +STANDARD_RIGHTS_REQUIRED: Final = 983040 +STANDARD_RIGHTS_READ: Final = READ_CONTROL +STANDARD_RIGHTS_WRITE: Final = READ_CONTROL +STANDARD_RIGHTS_EXECUTE: Final = READ_CONTROL +STANDARD_RIGHTS_ALL: Final = 2031616 +SPECIFIC_RIGHTS_ALL: Final = 65535 +IO_COMPLETION_ALL_ACCESS: Final = 2031619 +ACCESS_SYSTEM_SECURITY: Final = 16777216 +MAXIMUM_ALLOWED: Final = 33554432 +GENERIC_READ: Final = -2147483648 +GENERIC_WRITE: Final = 1073741824 +GENERIC_EXECUTE: Final = 536870912 +GENERIC_ALL: Final = 268435456 +SID_REVISION: Final = 1 +SID_MAX_SUB_AUTHORITIES: Final = 15 +SID_RECOMMENDED_SUB_AUTHORITIES: Final = 1 +SidTypeUser: Final = 1 +SidTypeGroup: Final = 2 +SidTypeDomain: Final = 3 +SidTypeAlias: Final = 4 +SidTypeWellKnownGroup: Final = 5 +SidTypeDeletedAccount: Final = 6 +SidTypeInvalid: Final = 7 +SidTypeUnknown: Final = 8 +SECURITY_NULL_RID: Final = 0 +SECURITY_WORLD_RID: Final = 0 +SECURITY_LOCAL_RID: Final = 0x00000000 +SECURITY_CREATOR_OWNER_RID: Final = 0 +SECURITY_CREATOR_GROUP_RID: Final = 1 +SECURITY_CREATOR_OWNER_SERVER_RID: Final = 2 +SECURITY_CREATOR_GROUP_SERVER_RID: Final = 3 +SECURITY_DIALUP_RID: Final = 1 +SECURITY_NETWORK_RID: Final = 2 +SECURITY_BATCH_RID: Final = 3 +SECURITY_INTERACTIVE_RID: Final = 4 +SECURITY_SERVICE_RID: Final = 6 +SECURITY_ANONYMOUS_LOGON_RID: Final = 7 +SECURITY_PROXY_RID: Final = 8 +SECURITY_SERVER_LOGON_RID: Final = 9 +SECURITY_PRINCIPAL_SELF_RID: Final = 10 +SECURITY_AUTHENTICATED_USER_RID: Final = 11 +SECURITY_LOGON_IDS_RID: Final = 5 +SECURITY_LOGON_IDS_RID_COUNT: Final = 3 +SECURITY_LOCAL_SYSTEM_RID: Final = 18 +SECURITY_NT_NON_UNIQUE: Final = 21 +SECURITY_BUILTIN_DOMAIN_RID: Final = 32 +DOMAIN_USER_RID_ADMIN: Final = 500 +DOMAIN_USER_RID_GUEST: Final = 501 +DOMAIN_GROUP_RID_ADMINS: Final = 512 +DOMAIN_GROUP_RID_USERS: Final = 513 +DOMAIN_GROUP_RID_GUESTS: Final = 514 +DOMAIN_ALIAS_RID_ADMINS: Final = 544 +DOMAIN_ALIAS_RID_USERS: Final = 545 +DOMAIN_ALIAS_RID_GUESTS: Final = 546 +DOMAIN_ALIAS_RID_POWER_USERS: Final = 547 +DOMAIN_ALIAS_RID_ACCOUNT_OPS: Final = 548 +DOMAIN_ALIAS_RID_SYSTEM_OPS: Final = 549 +DOMAIN_ALIAS_RID_PRINT_OPS: Final = 550 +DOMAIN_ALIAS_RID_BACKUP_OPS: Final = 551 +DOMAIN_ALIAS_RID_REPLICATOR: Final = 552 +SE_GROUP_MANDATORY: Final = 1 +SE_GROUP_ENABLED_BY_DEFAULT: Final = 2 +SE_GROUP_ENABLED: Final = 4 +SE_GROUP_OWNER: Final = 8 +SE_GROUP_LOGON_ID: Final = -1073741824 +ACL_REVISION: Final = 2 +ACL_REVISION_DS: Final = 4 +ACL_REVISION1: Final = 1 +ACL_REVISION2: Final = 2 +ACL_REVISION3: Final = 3 +ACL_REVISION4: Final = 4 +MAX_ACL_REVISION: Final = ACL_REVISION4 +ACCESS_MIN_MS_ACE_TYPE: Final = 0 +ACCESS_ALLOWED_ACE_TYPE: Final = 0 +ACCESS_DENIED_ACE_TYPE: Final = 1 +SYSTEM_AUDIT_ACE_TYPE: Final = 2 +SYSTEM_ALARM_ACE_TYPE: Final = 3 +ACCESS_MAX_MS_V2_ACE_TYPE: Final = 3 +ACCESS_ALLOWED_COMPOUND_ACE_TYPE: Final = 4 +ACCESS_MAX_MS_V3_ACE_TYPE: Final = 4 +ACCESS_MIN_MS_OBJECT_ACE_TYPE: Final = 5 +ACCESS_ALLOWED_OBJECT_ACE_TYPE: Final = 5 +ACCESS_DENIED_OBJECT_ACE_TYPE: Final = 6 +SYSTEM_AUDIT_OBJECT_ACE_TYPE: Final = 7 +SYSTEM_ALARM_OBJECT_ACE_TYPE: Final = 8 +ACCESS_MAX_MS_OBJECT_ACE_TYPE: Final = 8 +ACCESS_MAX_MS_V4_ACE_TYPE: Final = 8 +ACCESS_MAX_MS_ACE_TYPE: Final = 8 +ACCESS_ALLOWED_CALLBACK_ACE_TYPE: Final = 9 +ACCESS_DENIED_CALLBACK_ACE_TYPE: Final = 10 +ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: Final = 11 +ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: Final = 12 +SYSTEM_AUDIT_CALLBACK_ACE_TYPE: Final = 13 +SYSTEM_ALARM_CALLBACK_ACE_TYPE: Final = 14 +SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE: Final = 15 +SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE: Final = 16 +SYSTEM_MANDATORY_LABEL_ACE_TYPE: Final = 17 +ACCESS_MAX_MS_V5_ACE_TYPE: Final = 17 +OBJECT_INHERIT_ACE: Final = 1 +CONTAINER_INHERIT_ACE: Final = 2 +NO_PROPAGATE_INHERIT_ACE: Final = 4 +INHERIT_ONLY_ACE: Final = 8 +INHERITED_ACE: Final = 16 +VALID_INHERIT_FLAGS: Final = 31 +SUCCESSFUL_ACCESS_ACE_FLAG: Final = 64 +FAILED_ACCESS_ACE_FLAG: Final = 128 +ACE_OBJECT_TYPE_PRESENT: Final = 1 +ACE_INHERITED_OBJECT_TYPE_PRESENT: Final = 2 +SECURITY_DESCRIPTOR_REVISION: Final = 1 +SECURITY_DESCRIPTOR_REVISION1: Final = 1 +SECURITY_DESCRIPTOR_MIN_LENGTH: Final = 20 +SE_OWNER_DEFAULTED: Final = 1 +SE_GROUP_DEFAULTED: Final = 2 +SE_DACL_PRESENT: Final = 4 +SE_DACL_DEFAULTED: Final = 8 +SE_SACL_PRESENT: Final = 16 +SE_SACL_DEFAULTED: Final = 32 +SE_DACL_AUTO_INHERIT_REQ: Final = 256 +SE_SACL_AUTO_INHERIT_REQ: Final = 512 +SE_DACL_AUTO_INHERITED: Final = 1024 +SE_SACL_AUTO_INHERITED: Final = 2048 +SE_DACL_PROTECTED: Final = 4096 +SE_SACL_PROTECTED: Final = 8192 +SE_SELF_RELATIVE: Final = 32768 +ACCESS_OBJECT_GUID: Final = 0 +ACCESS_PROPERTY_SET_GUID: Final = 1 +ACCESS_PROPERTY_GUID: Final = 2 +ACCESS_MAX_LEVEL: Final = 4 +AUDIT_ALLOW_NO_PRIVILEGE: Final = 1 +ACCESS_DS_SOURCE_A: Final = "Directory Service" +ACCESS_DS_OBJECT_TYPE_NAME_A: Final = "Directory Service Object" +SE_PRIVILEGE_ENABLED_BY_DEFAULT: Final = 1 +SE_PRIVILEGE_ENABLED: Final = 2 +SE_PRIVILEGE_USED_FOR_ACCESS: Final = -2147483648 +PRIVILEGE_SET_ALL_NECESSARY: Final = 1 +SE_CREATE_TOKEN_NAME: Final = "SeCreateTokenPrivilege" +SE_ASSIGNPRIMARYTOKEN_NAME: Final = "SeAssignPrimaryTokenPrivilege" +SE_LOCK_MEMORY_NAME: Final = "SeLockMemoryPrivilege" +SE_INCREASE_QUOTA_NAME: Final = "SeIncreaseQuotaPrivilege" +SE_UNSOLICITED_INPUT_NAME: Final = "SeUnsolicitedInputPrivilege" +SE_MACHINE_ACCOUNT_NAME: Final = "SeMachineAccountPrivilege" +SE_TCB_NAME: Final = "SeTcbPrivilege" +SE_SECURITY_NAME: Final = "SeSecurityPrivilege" +SE_TAKE_OWNERSHIP_NAME: Final = "SeTakeOwnershipPrivilege" +SE_LOAD_DRIVER_NAME: Final = "SeLoadDriverPrivilege" +SE_SYSTEM_PROFILE_NAME: Final = "SeSystemProfilePrivilege" +SE_SYSTEMTIME_NAME: Final = "SeSystemtimePrivilege" +SE_PROF_SINGLE_PROCESS_NAME: Final = "SeProfileSingleProcessPrivilege" +SE_INC_BASE_PRIORITY_NAME: Final = "SeIncreaseBasePriorityPrivilege" +SE_CREATE_PAGEFILE_NAME: Final = "SeCreatePagefilePrivilege" +SE_CREATE_PERMANENT_NAME: Final = "SeCreatePermanentPrivilege" +SE_BACKUP_NAME: Final = "SeBackupPrivilege" +SE_RESTORE_NAME: Final = "SeRestorePrivilege" +SE_SHUTDOWN_NAME: Final = "SeShutdownPrivilege" +SE_DEBUG_NAME: Final = "SeDebugPrivilege" +SE_AUDIT_NAME: Final = "SeAuditPrivilege" +SE_SYSTEM_ENVIRONMENT_NAME: Final = "SeSystemEnvironmentPrivilege" +SE_CHANGE_NOTIFY_NAME: Final = "SeChangeNotifyPrivilege" +SE_REMOTE_SHUTDOWN_NAME: Final = "SeRemoteShutdownPrivilege" +TOKEN_ASSIGN_PRIMARY: Final = 1 +TOKEN_DUPLICATE: Final = 2 +TOKEN_IMPERSONATE: Final = 4 +TOKEN_QUERY: Final = 8 +TOKEN_QUERY_SOURCE: Final = 16 +TOKEN_ADJUST_PRIVILEGES: Final = 32 +TOKEN_ADJUST_GROUPS: Final = 64 +TOKEN_ADJUST_DEFAULT: Final = 128 +TOKEN_ALL_ACCESS: Final = 983295 +TOKEN_READ: Final = 131080 +TOKEN_WRITE: Final = 131296 +TOKEN_EXECUTE: Final = STANDARD_RIGHTS_EXECUTE +TOKEN_SOURCE_LENGTH: Final = 8 +TokenPrimary: Final = 1 +TokenImpersonation: Final = 2 +TokenUser: Final = 1 +TokenGroups: Final = 2 +TokenPrivileges: Final = 3 +TokenOwner: Final = 4 +TokenPrimaryGroup: Final = 5 +TokenDefaultDacl: Final = 6 +TokenSource: Final = 7 +TokenType: Final = 8 +TokenImpersonationLevel: Final = 9 +TokenStatistics: Final = 10 +TokenRestrictedSids: Final = 11 +TokenSessionId: Final = 12 +TokenGroupsAndPrivileges: Final = 13 +TokenSessionReference: Final = 14 +TokenSandBoxInert: Final = 15 +TokenAuditPolicy: Final = 16 +TokenOrigin: Final = 17 +TokenElevationType: Final = 18 +TokenLinkedToken: Final = 19 +TokenElevation: Final = 20 +TokenHasRestrictions: Final = 21 +TokenAccessInformation: Final = 22 +TokenVirtualizationAllowed: Final = 23 +TokenVirtualizationEnabled: Final = 24 +TokenIntegrityLevel: Final = 25 +TokenUIAccess: Final = 26 +TokenMandatoryPolicy: Final = 27 +TokenLogonSid: Final = 28 +OWNER_SECURITY_INFORMATION: Final = 0x00000001 +GROUP_SECURITY_INFORMATION: Final = 0x00000002 +DACL_SECURITY_INFORMATION: Final = 0x00000004 +SACL_SECURITY_INFORMATION: Final = 0x00000008 +LABEL_SECURITY_INFORMATION: Final = 0x00000010 +IMAGE_DOS_SIGNATURE: Final = 23117 +IMAGE_OS2_SIGNATURE: Final = 17742 +IMAGE_OS2_SIGNATURE_LE: Final = 17740 +IMAGE_VXD_SIGNATURE: Final = 17740 +IMAGE_NT_SIGNATURE: Final = 17744 +IMAGE_SIZEOF_FILE_HEADER: Final = 20 +IMAGE_FILE_RELOCS_STRIPPED: Final = 1 +IMAGE_FILE_EXECUTABLE_IMAGE: Final = 2 +IMAGE_FILE_LINE_NUMS_STRIPPED: Final = 4 +IMAGE_FILE_LOCAL_SYMS_STRIPPED: Final = 8 +IMAGE_FILE_AGGRESIVE_WS_TRIM: Final = 16 +IMAGE_FILE_LARGE_ADDRESS_AWARE: Final = 32 +IMAGE_FILE_BYTES_REVERSED_LO: Final = 128 +IMAGE_FILE_32BIT_MACHINE: Final = 256 +IMAGE_FILE_DEBUG_STRIPPED: Final = 512 +IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP: Final = 1024 +IMAGE_FILE_NET_RUN_FROM_SWAP: Final = 2048 +IMAGE_FILE_SYSTEM: Final = 4096 +IMAGE_FILE_DLL: Final = 8192 +IMAGE_FILE_UP_SYSTEM_ONLY: Final = 16384 +IMAGE_FILE_BYTES_REVERSED_HI: Final = 32768 +IMAGE_FILE_MACHINE_UNKNOWN: Final = 0 +IMAGE_FILE_MACHINE_I386: Final = 332 +IMAGE_FILE_MACHINE_R3000: Final = 354 +IMAGE_FILE_MACHINE_R4000: Final = 358 +IMAGE_FILE_MACHINE_R10000: Final = 360 +IMAGE_FILE_MACHINE_WCEMIPSV2: Final = 361 +IMAGE_FILE_MACHINE_ALPHA: Final = 388 +IMAGE_FILE_MACHINE_POWERPC: Final = 496 +IMAGE_FILE_MACHINE_SH3: Final = 418 +IMAGE_FILE_MACHINE_SH3E: Final = 420 +IMAGE_FILE_MACHINE_SH4: Final = 422 +IMAGE_FILE_MACHINE_ARM: Final = 448 +IMAGE_NUMBEROF_DIRECTORY_ENTRIES: Final = 16 +IMAGE_SIZEOF_ROM_OPTIONAL_HEADER: Final = 56 +IMAGE_SIZEOF_STD_OPTIONAL_HEADER: Final = 28 +IMAGE_SIZEOF_NT_OPTIONAL_HEADER: Final = 224 +IMAGE_NT_OPTIONAL_HDR_MAGIC: Final = 267 +IMAGE_ROM_OPTIONAL_HDR_MAGIC: Final = 263 +IMAGE_SUBSYSTEM_UNKNOWN: Final = 0 +IMAGE_SUBSYSTEM_NATIVE: Final = 1 +IMAGE_SUBSYSTEM_WINDOWS_GUI: Final = 2 +IMAGE_SUBSYSTEM_WINDOWS_CUI: Final = 3 +IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: Final = 4 +IMAGE_SUBSYSTEM_OS2_CUI: Final = 5 +IMAGE_SUBSYSTEM_POSIX_CUI: Final = 7 +IMAGE_SUBSYSTEM_RESERVED8: Final = 8 +IMAGE_DLLCHARACTERISTICS_WDM_DRIVER: Final = 8192 +IMAGE_DIRECTORY_ENTRY_EXPORT: Final = 0 +IMAGE_DIRECTORY_ENTRY_IMPORT: Final = 1 +IMAGE_DIRECTORY_ENTRY_RESOURCE: Final = 2 +IMAGE_DIRECTORY_ENTRY_EXCEPTION: Final = 3 +IMAGE_DIRECTORY_ENTRY_SECURITY: Final = 4 +IMAGE_DIRECTORY_ENTRY_BASERELOC: Final = 5 +IMAGE_DIRECTORY_ENTRY_DEBUG: Final = 6 +IMAGE_DIRECTORY_ENTRY_COPYRIGHT: Final = 7 +IMAGE_DIRECTORY_ENTRY_GLOBALPTR: Final = 8 +IMAGE_DIRECTORY_ENTRY_TLS: Final = 9 +IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: Final = 10 +IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: Final = 11 +IMAGE_DIRECTORY_ENTRY_IAT: Final = 12 +IMAGE_SIZEOF_SHORT_NAME: Final = 8 +IMAGE_SIZEOF_SECTION_HEADER: Final = 40 +IMAGE_SCN_TYPE_NO_PAD: Final = 8 +IMAGE_SCN_CNT_CODE: Final = 32 +IMAGE_SCN_CNT_INITIALIZED_DATA: Final = 64 +IMAGE_SCN_CNT_UNINITIALIZED_DATA: Final = 128 +IMAGE_SCN_LNK_OTHER: Final = 256 +IMAGE_SCN_LNK_INFO: Final = 512 +IMAGE_SCN_LNK_REMOVE: Final = 2048 +IMAGE_SCN_LNK_COMDAT: Final = 4096 +IMAGE_SCN_MEM_FARDATA: Final = 32768 +IMAGE_SCN_MEM_PURGEABLE: Final = 131072 +IMAGE_SCN_MEM_16BIT: Final = 131072 +IMAGE_SCN_MEM_LOCKED: Final = 262144 +IMAGE_SCN_MEM_PRELOAD: Final = 524288 +IMAGE_SCN_ALIGN_1BYTES: Final = 1048576 +IMAGE_SCN_ALIGN_2BYTES: Final = 2097152 +IMAGE_SCN_ALIGN_4BYTES: Final = 3145728 +IMAGE_SCN_ALIGN_8BYTES: Final = 4194304 +IMAGE_SCN_ALIGN_16BYTES: Final = 5242880 +IMAGE_SCN_ALIGN_32BYTES: Final = 6291456 +IMAGE_SCN_ALIGN_64BYTES: Final = 7340032 +IMAGE_SCN_LNK_NRELOC_OVFL: Final = 16777216 +IMAGE_SCN_MEM_DISCARDABLE: Final = 33554432 +IMAGE_SCN_MEM_NOT_CACHED: Final = 67108864 +IMAGE_SCN_MEM_NOT_PAGED: Final = 134217728 +IMAGE_SCN_MEM_SHARED: Final = 268435456 +IMAGE_SCN_MEM_EXECUTE: Final = 536870912 +IMAGE_SCN_MEM_READ: Final = 1073741824 +IMAGE_SCN_MEM_WRITE: Final = -2147483648 +IMAGE_SCN_SCALE_INDEX: Final = 1 +IMAGE_SIZEOF_SYMBOL: Final = 18 +IMAGE_SYM_TYPE_NULL: Final = 0 +IMAGE_SYM_TYPE_VOID: Final = 1 +IMAGE_SYM_TYPE_CHAR: Final = 2 +IMAGE_SYM_TYPE_SHORT: Final = 3 +IMAGE_SYM_TYPE_INT: Final = 4 +IMAGE_SYM_TYPE_LONG: Final = 5 +IMAGE_SYM_TYPE_FLOAT: Final = 6 +IMAGE_SYM_TYPE_DOUBLE: Final = 7 +IMAGE_SYM_TYPE_STRUCT: Final = 8 +IMAGE_SYM_TYPE_UNION: Final = 9 +IMAGE_SYM_TYPE_ENUM: Final = 10 +IMAGE_SYM_TYPE_MOE: Final = 11 +IMAGE_SYM_TYPE_BYTE: Final = 12 +IMAGE_SYM_TYPE_WORD: Final = 13 +IMAGE_SYM_TYPE_UINT: Final = 14 +IMAGE_SYM_TYPE_DWORD: Final = 15 +IMAGE_SYM_TYPE_PCODE: Final = 32768 +IMAGE_SYM_DTYPE_NULL: Final = 0 +IMAGE_SYM_DTYPE_POINTER: Final = 1 +IMAGE_SYM_DTYPE_FUNCTION: Final = 2 +IMAGE_SYM_DTYPE_ARRAY: Final = 3 +IMAGE_SYM_CLASS_NULL: Final = 0 +IMAGE_SYM_CLASS_AUTOMATIC: Final = 1 +IMAGE_SYM_CLASS_EXTERNAL: Final = 2 +IMAGE_SYM_CLASS_STATIC: Final = 3 +IMAGE_SYM_CLASS_REGISTER: Final = 4 +IMAGE_SYM_CLASS_EXTERNAL_DEF: Final = 5 +IMAGE_SYM_CLASS_LABEL: Final = 6 +IMAGE_SYM_CLASS_UNDEFINED_LABEL: Final = 7 +IMAGE_SYM_CLASS_MEMBER_OF_STRUCT: Final = 8 +IMAGE_SYM_CLASS_ARGUMENT: Final = 9 +IMAGE_SYM_CLASS_STRUCT_TAG: Final = 10 +IMAGE_SYM_CLASS_MEMBER_OF_UNION: Final = 11 +IMAGE_SYM_CLASS_UNION_TAG: Final = 12 +IMAGE_SYM_CLASS_TYPE_DEFINITION: Final = 13 +IMAGE_SYM_CLASS_UNDEFINED_STATIC: Final = 14 +IMAGE_SYM_CLASS_ENUM_TAG: Final = 15 +IMAGE_SYM_CLASS_MEMBER_OF_ENUM: Final = 16 +IMAGE_SYM_CLASS_REGISTER_PARAM: Final = 17 +IMAGE_SYM_CLASS_BIT_FIELD: Final = 18 +IMAGE_SYM_CLASS_FAR_EXTERNAL: Final = 68 +IMAGE_SYM_CLASS_BLOCK: Final = 100 +IMAGE_SYM_CLASS_FUNCTION: Final = 101 +IMAGE_SYM_CLASS_END_OF_STRUCT: Final = 102 +IMAGE_SYM_CLASS_FILE: Final = 103 +IMAGE_SYM_CLASS_SECTION: Final = 104 +IMAGE_SYM_CLASS_WEAK_EXTERNAL: Final = 105 +N_BTMASK: Final = 15 +N_TMASK: Final = 48 +N_TMASK1: Final = 192 +N_TMASK2: Final = 240 +N_BTSHFT: Final = 4 +N_TSHIFT: Final = 2 + +def BTYPE(x: int) -> int: ... +def ISPTR(x: int) -> bool: ... +def ISFCN(x: int) -> bool: ... +def ISARY(x: int) -> bool: ... +def INCREF(x: int) -> int: ... +def DECREF(x: int) -> int: ... + +IMAGE_SIZEOF_AUX_SYMBOL: Final = 18 +IMAGE_COMDAT_SELECT_NODUPLICATES: Final = 1 +IMAGE_COMDAT_SELECT_ANY: Final = 2 +IMAGE_COMDAT_SELECT_SAME_SIZE: Final = 3 +IMAGE_COMDAT_SELECT_EXACT_MATCH: Final = 4 +IMAGE_COMDAT_SELECT_ASSOCIATIVE: Final = 5 +IMAGE_COMDAT_SELECT_LARGEST: Final = 6 +IMAGE_COMDAT_SELECT_NEWEST: Final = 7 +IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY: Final = 1 +IMAGE_WEAK_EXTERN_SEARCH_LIBRARY: Final = 2 +IMAGE_WEAK_EXTERN_SEARCH_ALIAS: Final = 3 +IMAGE_SIZEOF_RELOCATION: Final = 10 +IMAGE_REL_I386_ABSOLUTE: Final = 0 +IMAGE_REL_I386_DIR16: Final = 1 +IMAGE_REL_I386_REL16: Final = 2 +IMAGE_REL_I386_DIR32: Final = 6 +IMAGE_REL_I386_DIR32NB: Final = 7 +IMAGE_REL_I386_SEG12: Final = 9 +IMAGE_REL_I386_SECTION: Final = 10 +IMAGE_REL_I386_SECREL: Final = 11 +IMAGE_REL_I386_REL32: Final = 20 +IMAGE_REL_MIPS_ABSOLUTE: Final = 0 +IMAGE_REL_MIPS_REFHALF: Final = 1 +IMAGE_REL_MIPS_REFWORD: Final = 2 +IMAGE_REL_MIPS_JMPADDR: Final = 3 +IMAGE_REL_MIPS_REFHI: Final = 4 +IMAGE_REL_MIPS_REFLO: Final = 5 +IMAGE_REL_MIPS_GPREL: Final = 6 +IMAGE_REL_MIPS_LITERAL: Final = 7 +IMAGE_REL_MIPS_SECTION: Final = 10 +IMAGE_REL_MIPS_SECREL: Final = 11 +IMAGE_REL_MIPS_SECRELLO: Final = 12 +IMAGE_REL_MIPS_SECRELHI: Final = 13 +IMAGE_REL_MIPS_REFWORDNB: Final = 34 +IMAGE_REL_MIPS_PAIR: Final = 37 +IMAGE_REL_ALPHA_ABSOLUTE: Final = 0 +IMAGE_REL_ALPHA_REFLONG: Final = 1 +IMAGE_REL_ALPHA_REFQUAD: Final = 2 +IMAGE_REL_ALPHA_GPREL32: Final = 3 +IMAGE_REL_ALPHA_LITERAL: Final = 4 +IMAGE_REL_ALPHA_LITUSE: Final = 5 +IMAGE_REL_ALPHA_GPDISP: Final = 6 +IMAGE_REL_ALPHA_BRADDR: Final = 7 +IMAGE_REL_ALPHA_HINT: Final = 8 +IMAGE_REL_ALPHA_INLINE_REFLONG: Final = 9 +IMAGE_REL_ALPHA_REFHI: Final = 10 +IMAGE_REL_ALPHA_REFLO: Final = 11 +IMAGE_REL_ALPHA_PAIR: Final = 12 +IMAGE_REL_ALPHA_MATCH: Final = 13 +IMAGE_REL_ALPHA_SECTION: Final = 14 +IMAGE_REL_ALPHA_SECREL: Final = 15 +IMAGE_REL_ALPHA_REFLONGNB: Final = 16 +IMAGE_REL_ALPHA_SECRELLO: Final = 17 +IMAGE_REL_ALPHA_SECRELHI: Final = 18 +IMAGE_REL_PPC_ABSOLUTE: Final = 0 +IMAGE_REL_PPC_ADDR64: Final = 1 +IMAGE_REL_PPC_ADDR32: Final = 2 +IMAGE_REL_PPC_ADDR24: Final = 3 +IMAGE_REL_PPC_ADDR16: Final = 4 +IMAGE_REL_PPC_ADDR14: Final = 5 +IMAGE_REL_PPC_REL24: Final = 6 +IMAGE_REL_PPC_REL14: Final = 7 +IMAGE_REL_PPC_TOCREL16: Final = 8 +IMAGE_REL_PPC_TOCREL14: Final = 9 +IMAGE_REL_PPC_ADDR32NB: Final = 10 +IMAGE_REL_PPC_SECREL: Final = 11 +IMAGE_REL_PPC_SECTION: Final = 12 +IMAGE_REL_PPC_IFGLUE: Final = 13 +IMAGE_REL_PPC_IMGLUE: Final = 14 +IMAGE_REL_PPC_SECREL16: Final = 15 +IMAGE_REL_PPC_REFHI: Final = 16 +IMAGE_REL_PPC_REFLO: Final = 17 +IMAGE_REL_PPC_PAIR: Final = 18 +IMAGE_REL_PPC_SECRELLO: Final = 19 +IMAGE_REL_PPC_SECRELHI: Final = 20 +IMAGE_REL_PPC_TYPEMASK: Final = 255 +IMAGE_REL_PPC_NEG: Final = 256 +IMAGE_REL_PPC_BRTAKEN: Final = 512 +IMAGE_REL_PPC_BRNTAKEN: Final = 1024 +IMAGE_REL_PPC_TOCDEFN: Final = 2048 +IMAGE_REL_SH3_ABSOLUTE: Final = 0 +IMAGE_REL_SH3_DIRECT16: Final = 1 +IMAGE_REL_SH3_DIRECT32: Final = 2 +IMAGE_REL_SH3_DIRECT8: Final = 3 +IMAGE_REL_SH3_DIRECT8_WORD: Final = 4 +IMAGE_REL_SH3_DIRECT8_LONG: Final = 5 +IMAGE_REL_SH3_DIRECT4: Final = 6 +IMAGE_REL_SH3_DIRECT4_WORD: Final = 7 +IMAGE_REL_SH3_DIRECT4_LONG: Final = 8 +IMAGE_REL_SH3_PCREL8_WORD: Final = 9 +IMAGE_REL_SH3_PCREL8_LONG: Final = 10 +IMAGE_REL_SH3_PCREL12_WORD: Final = 11 +IMAGE_REL_SH3_STARTOF_SECTION: Final = 12 +IMAGE_REL_SH3_SIZEOF_SECTION: Final = 13 +IMAGE_REL_SH3_SECTION: Final = 14 +IMAGE_REL_SH3_SECREL: Final = 15 +IMAGE_REL_SH3_DIRECT32_NB: Final = 16 +IMAGE_SIZEOF_LINENUMBER: Final = 6 +IMAGE_SIZEOF_BASE_RELOCATION: Final = 8 +IMAGE_REL_BASED_ABSOLUTE: Final = 0 +IMAGE_REL_BASED_HIGH: Final = 1 +IMAGE_REL_BASED_LOW: Final = 2 +IMAGE_REL_BASED_HIGHLOW: Final = 3 +IMAGE_REL_BASED_HIGHADJ: Final = 4 +IMAGE_REL_BASED_MIPS_JMPADDR: Final = 5 +IMAGE_REL_BASED_SECTION: Final = 6 +IMAGE_REL_BASED_REL32: Final = 7 +IMAGE_ARCHIVE_START_SIZE: Final = 8 +IMAGE_ARCHIVE_START: Final = "!\n" +IMAGE_ARCHIVE_END: Final = "`\n" +IMAGE_ARCHIVE_PAD: Final = "\n" +IMAGE_ARCHIVE_LINKER_MEMBER: Final = "/ " +IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR: Final = 60 +IMAGE_ORDINAL_FLAG: Final = -2147483648 + +def IMAGE_SNAP_BY_ORDINAL(Ordinal: int) -> bool: ... +def IMAGE_ORDINAL(Ordinal: int) -> int: ... + +IMAGE_RESOURCE_NAME_IS_STRING: Final = -2147483648 +IMAGE_RESOURCE_DATA_IS_DIRECTORY: Final = -2147483648 +IMAGE_DEBUG_TYPE_UNKNOWN: Final = 0 +IMAGE_DEBUG_TYPE_COFF: Final = 1 +IMAGE_DEBUG_TYPE_CODEVIEW: Final = 2 +IMAGE_DEBUG_TYPE_FPO: Final = 3 +IMAGE_DEBUG_TYPE_MISC: Final = 4 +IMAGE_DEBUG_TYPE_EXCEPTION: Final = 5 +IMAGE_DEBUG_TYPE_FIXUP: Final = 6 +IMAGE_DEBUG_TYPE_OMAP_TO_SRC: Final = 7 +IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: Final = 8 +IMAGE_DEBUG_TYPE_BORLAND: Final = 9 +FRAME_FPO: Final = 0 +FRAME_TRAP: Final = 1 +FRAME_TSS: Final = 2 +FRAME_NONFPO: Final = 3 +SIZEOF_RFPO_DATA: Final = 16 +IMAGE_DEBUG_MISC_EXENAME: Final = 1 +IMAGE_SEPARATE_DEBUG_SIGNATURE: Final = 18756 +IMAGE_SEPARATE_DEBUG_FLAGS_MASK: Final = 32768 +IMAGE_SEPARATE_DEBUG_MISMATCH: Final = 32768 +NULL: Final = 0 +HEAP_NO_SERIALIZE: Final = 1 +HEAP_GROWABLE: Final = 2 +HEAP_GENERATE_EXCEPTIONS: Final = 4 +HEAP_ZERO_MEMORY: Final = 8 +HEAP_REALLOC_IN_PLACE_ONLY: Final = 16 +HEAP_TAIL_CHECKING_ENABLED: Final = 32 +HEAP_FREE_CHECKING_ENABLED: Final = 64 +HEAP_DISABLE_COALESCE_ON_FREE: Final = 128 +HEAP_CREATE_ALIGN_16: Final = 65536 +HEAP_CREATE_ENABLE_TRACING: Final = 131072 +HEAP_MAXIMUM_TAG: Final = 4095 +HEAP_PSEUDO_TAG_FLAG: Final = 32768 +HEAP_TAG_SHIFT: Final = 16 +IS_TEXT_UNICODE_ASCII16: Final = 1 +IS_TEXT_UNICODE_REVERSE_ASCII16: Final = 16 +IS_TEXT_UNICODE_STATISTICS: Final = 2 +IS_TEXT_UNICODE_REVERSE_STATISTICS: Final = 32 +IS_TEXT_UNICODE_CONTROLS: Final = 4 +IS_TEXT_UNICODE_REVERSE_CONTROLS: Final = 64 +IS_TEXT_UNICODE_SIGNATURE: Final = 8 +IS_TEXT_UNICODE_REVERSE_SIGNATURE: Final = 128 +IS_TEXT_UNICODE_ILLEGAL_CHARS: Final = 256 +IS_TEXT_UNICODE_ODD_LENGTH: Final = 512 +IS_TEXT_UNICODE_DBCS_LEADBYTE: Final = 1024 +IS_TEXT_UNICODE_NULL_BYTES: Final = 4096 +IS_TEXT_UNICODE_UNICODE_MASK: Final = 15 +IS_TEXT_UNICODE_REVERSE_MASK: Final = 240 +IS_TEXT_UNICODE_NOT_UNICODE_MASK: Final = 3840 +IS_TEXT_UNICODE_NOT_ASCII_MASK: Final = 61440 +COMPRESSION_FORMAT_NONE: Final = 0 +COMPRESSION_FORMAT_DEFAULT: Final = 1 +COMPRESSION_FORMAT_LZNT1: Final = 2 +COMPRESSION_ENGINE_STANDARD: Final = 0 +COMPRESSION_ENGINE_MAXIMUM: Final = 256 +MESSAGE_RESOURCE_UNICODE: Final = 1 +RTL_CRITSECT_TYPE: Final = 0 +RTL_RESOURCE_TYPE: Final = 1 +SEF_DACL_AUTO_INHERIT: Final = 1 +SEF_SACL_AUTO_INHERIT: Final = 2 +SEF_DEFAULT_DESCRIPTOR_FOR_OBJECT: Final = 4 +SEF_AVOID_PRIVILEGE_CHECK: Final = 8 +DLL_PROCESS_ATTACH: Final = 1 +DLL_THREAD_ATTACH: Final = 2 +DLL_THREAD_DETACH: Final = 3 +DLL_PROCESS_DETACH: Final = 0 +EVENTLOG_SEQUENTIAL_READ: Final = 0x0001 +EVENTLOG_SEEK_READ: Final = 0x0002 +EVENTLOG_FORWARDS_READ: Final = 0x0004 +EVENTLOG_BACKWARDS_READ: Final = 0x0008 +EVENTLOG_SUCCESS: Final = 0x0000 +EVENTLOG_ERROR_TYPE: Final = 1 +EVENTLOG_WARNING_TYPE: Final = 2 +EVENTLOG_INFORMATION_TYPE: Final = 4 +EVENTLOG_AUDIT_SUCCESS: Final = 8 +EVENTLOG_AUDIT_FAILURE: Final = 16 +EVENTLOG_START_PAIRED_EVENT: Final = 1 +EVENTLOG_END_PAIRED_EVENT: Final = 2 +EVENTLOG_END_ALL_PAIRED_EVENTS: Final = 4 +EVENTLOG_PAIRED_EVENT_ACTIVE: Final = 8 +EVENTLOG_PAIRED_EVENT_INACTIVE: Final = 16 +KEY_QUERY_VALUE: Final = 1 +KEY_SET_VALUE: Final = 2 +KEY_CREATE_SUB_KEY: Final = 4 +KEY_ENUMERATE_SUB_KEYS: Final = 8 +KEY_NOTIFY: Final = 16 +KEY_CREATE_LINK: Final = 32 +KEY_READ: Final = 0x00020019 +KEY_WRITE: Final = 0x00020006 +KEY_EXECUTE: Final = 0x00020019 +KEY_ALL_ACCESS: Final = 0x000F003F +REG_OPTION_RESERVED: Final = 0 +REG_OPTION_NON_VOLATILE: Final = 0 +REG_OPTION_VOLATILE: Final = 1 +REG_OPTION_CREATE_LINK: Final = 2 +REG_OPTION_BACKUP_RESTORE: Final = 4 +REG_OPTION_OPEN_LINK: Final = 8 +REG_LEGAL_OPTION: Final = 15 +REG_CREATED_NEW_KEY: Final = 1 +REG_OPENED_EXISTING_KEY: Final = 2 +REG_STANDARD_FORMAT: Final = 1 +REG_LATEST_FORMAT: Final = 2 +REG_NO_COMPRESSION: Final = 4 +REG_WHOLE_HIVE_VOLATILE: Final = 1 +REG_REFRESH_HIVE: Final = 2 +REG_NO_LAZY_FLUSH: Final = 4 +REG_FORCE_RESTORE: Final = 8 +REG_NOTIFY_CHANGE_NAME: Final = 1 +REG_NOTIFY_CHANGE_ATTRIBUTES: Final = 2 +REG_NOTIFY_CHANGE_LAST_SET: Final = 4 +REG_NOTIFY_CHANGE_SECURITY: Final = 8 +REG_LEGAL_CHANGE_FILTER: Final = 15 +REG_NONE: Final = 0 +REG_SZ: Final = 1 +REG_EXPAND_SZ: Final = 2 +REG_BINARY: Final = 3 +REG_DWORD: Final = 4 +REG_DWORD_LITTLE_ENDIAN: Final = 4 +REG_DWORD_BIG_ENDIAN: Final = 5 +REG_LINK: Final = 6 +REG_MULTI_SZ: Final = 7 +REG_RESOURCE_LIST: Final = 8 +REG_FULL_RESOURCE_DESCRIPTOR: Final = 9 +REG_RESOURCE_REQUIREMENTS_LIST: Final = 10 +SERVICE_KERNEL_DRIVER: Final = 1 +SERVICE_FILE_SYSTEM_DRIVER: Final = 2 +SERVICE_ADAPTER: Final = 4 +SERVICE_RECOGNIZER_DRIVER: Final = 8 +SERVICE_DRIVER: Final = 11 +SERVICE_WIN32_OWN_PROCESS: Final = 16 +SERVICE_WIN32_SHARE_PROCESS: Final = 32 +SERVICE_WIN32: Final = 48 +SERVICE_INTERACTIVE_PROCESS: Final = 256 +SERVICE_TYPE_ALL: Final = 319 +SERVICE_BOOT_START: Final = 0 +SERVICE_SYSTEM_START: Final = 1 +SERVICE_AUTO_START: Final = 2 +SERVICE_DEMAND_START: Final = 3 +SERVICE_DISABLED: Final = 4 +SERVICE_ERROR_IGNORE: Final = 0 +SERVICE_ERROR_NORMAL: Final = 1 +SERVICE_ERROR_SEVERE: Final = 2 +SERVICE_ERROR_CRITICAL: Final = 3 +TAPE_ERASE_SHORT: Final = 0 +TAPE_ERASE_LONG: Final = 1 +TAPE_LOAD: Final = 0 +TAPE_UNLOAD: Final = 1 +TAPE_TENSION: Final = 2 +TAPE_LOCK: Final = 3 +TAPE_UNLOCK: Final = 4 +TAPE_FORMAT: Final = 5 +TAPE_SETMARKS: Final = 0 +TAPE_FILEMARKS: Final = 1 +TAPE_SHORT_FILEMARKS: Final = 2 +TAPE_LONG_FILEMARKS: Final = 3 +TAPE_ABSOLUTE_POSITION: Final = 0 +TAPE_LOGICAL_POSITION: Final = 1 +TAPE_PSEUDO_LOGICAL_POSITION: Final = 2 +TAPE_REWIND: Final = 0 +TAPE_ABSOLUTE_BLOCK: Final = 1 +TAPE_LOGICAL_BLOCK: Final = 2 +TAPE_PSEUDO_LOGICAL_BLOCK: Final = 3 +TAPE_SPACE_END_OF_DATA: Final = 4 +TAPE_SPACE_RELATIVE_BLOCKS: Final = 5 +TAPE_SPACE_FILEMARKS: Final = 6 +TAPE_SPACE_SEQUENTIAL_FMKS: Final = 7 +TAPE_SPACE_SETMARKS: Final = 8 +TAPE_SPACE_SEQUENTIAL_SMKS: Final = 9 +TAPE_DRIVE_FIXED: Final = 1 +TAPE_DRIVE_SELECT: Final = 2 +TAPE_DRIVE_INITIATOR: Final = 4 +TAPE_DRIVE_ERASE_SHORT: Final = 16 +TAPE_DRIVE_ERASE_LONG: Final = 32 +TAPE_DRIVE_ERASE_BOP_ONLY: Final = 64 +TAPE_DRIVE_ERASE_IMMEDIATE: Final = 128 +TAPE_DRIVE_TAPE_CAPACITY: Final = 256 +TAPE_DRIVE_TAPE_REMAINING: Final = 512 +TAPE_DRIVE_FIXED_BLOCK: Final = 1024 +TAPE_DRIVE_VARIABLE_BLOCK: Final = 2048 +TAPE_DRIVE_WRITE_PROTECT: Final = 4096 +TAPE_DRIVE_EOT_WZ_SIZE: Final = 8192 +TAPE_DRIVE_ECC: Final = 65536 +TAPE_DRIVE_COMPRESSION: Final = 131072 +TAPE_DRIVE_PADDING: Final = 262144 +TAPE_DRIVE_REPORT_SMKS: Final = 524288 +TAPE_DRIVE_GET_ABSOLUTE_BLK: Final = 1048576 +TAPE_DRIVE_GET_LOGICAL_BLK: Final = 2097152 +TAPE_DRIVE_SET_EOT_WZ_SIZE: Final = 4194304 +TAPE_DRIVE_EJECT_MEDIA: Final = 16777216 +TAPE_DRIVE_RESERVED_BIT: Final = -2147483648 +TAPE_DRIVE_LOAD_UNLOAD: Final = -2147483647 +TAPE_DRIVE_TENSION: Final = -2147483646 +TAPE_DRIVE_LOCK_UNLOCK: Final = -2147483644 +TAPE_DRIVE_REWIND_IMMEDIATE: Final = -2147483640 +TAPE_DRIVE_SET_BLOCK_SIZE: Final = -2147483632 +TAPE_DRIVE_LOAD_UNLD_IMMED: Final = -2147483616 +TAPE_DRIVE_TENSION_IMMED: Final = -2147483584 +TAPE_DRIVE_LOCK_UNLK_IMMED: Final = -2147483520 +TAPE_DRIVE_SET_ECC: Final = -2147483392 +TAPE_DRIVE_SET_COMPRESSION: Final = -2147483136 +TAPE_DRIVE_SET_PADDING: Final = -2147482624 +TAPE_DRIVE_SET_REPORT_SMKS: Final = -2147481600 +TAPE_DRIVE_ABSOLUTE_BLK: Final = -2147479552 +TAPE_DRIVE_ABS_BLK_IMMED: Final = -2147475456 +TAPE_DRIVE_LOGICAL_BLK: Final = -2147467264 +TAPE_DRIVE_LOG_BLK_IMMED: Final = -2147450880 +TAPE_DRIVE_END_OF_DATA: Final = -2147418112 +TAPE_DRIVE_RELATIVE_BLKS: Final = -2147352576 +TAPE_DRIVE_FILEMARKS: Final = -2147221504 +TAPE_DRIVE_SEQUENTIAL_FMKS: Final = -2146959360 +TAPE_DRIVE_SETMARKS: Final = -2146435072 +TAPE_DRIVE_SEQUENTIAL_SMKS: Final = -2145386496 +TAPE_DRIVE_REVERSE_POSITION: Final = -2143289344 +TAPE_DRIVE_SPACE_IMMEDIATE: Final = -2139095040 +TAPE_DRIVE_WRITE_SETMARKS: Final = -2130706432 +TAPE_DRIVE_WRITE_FILEMARKS: Final = -2113929216 +TAPE_DRIVE_WRITE_SHORT_FMKS: Final = -2080374784 +TAPE_DRIVE_WRITE_LONG_FMKS: Final = -2013265920 +TAPE_DRIVE_WRITE_MARK_IMMED: Final = -1879048192 +TAPE_DRIVE_FORMAT: Final = -1610612736 +TAPE_DRIVE_FORMAT_IMMEDIATE: Final = -1073741824 +TAPE_DRIVE_HIGH_FEATURES: Final = -2147483648 +TAPE_FIXED_PARTITIONS: Final = 0 +TAPE_SELECT_PARTITIONS: Final = 1 +TAPE_INITIATOR_PARTITIONS: Final = 2 +TRANSACTIONMANAGER_QUERY_INFORMATION: Final = 0x0001 +TRANSACTIONMANAGER_SET_INFORMATION: Final = 0x0002 +TRANSACTIONMANAGER_RECOVER: Final = 0x0004 +TRANSACTIONMANAGER_RENAME: Final = 0x0008 +TRANSACTIONMANAGER_CREATE_RM: Final = 0x0010 +TRANSACTIONMANAGER_BIND_TRANSACTION: Final = 0x0020 +TRANSACTIONMANAGER_GENERIC_READ: Final = 0x20001 +TRANSACTIONMANAGER_GENERIC_WRITE: Final = 0x2001E +TRANSACTIONMANAGER_GENERIC_EXECUTE: Final = STANDARD_RIGHTS_EXECUTE +TRANSACTIONMANAGER_ALL_ACCESS: Final = 0xF003F +TRANSACTION_QUERY_INFORMATION: Final = 0x0001 +TRANSACTION_SET_INFORMATION: Final = 0x0002 +TRANSACTION_ENLIST: Final = 0x0004 +TRANSACTION_COMMIT: Final = 0x0008 +TRANSACTION_ROLLBACK: Final = 0x0010 +TRANSACTION_PROPAGATE: Final = 0x0020 +TRANSACTION_SAVEPOINT: Final = 0x0040 +TRANSACTION_MARSHALL: Final = TRANSACTION_QUERY_INFORMATION +TRANSACTION_GENERIC_READ: Final = 0x120001 +TRANSACTION_GENERIC_WRITE: Final = 0x12007E +TRANSACTION_GENERIC_EXECUTE: Final = 0x120018 +TRANSACTION_ALL_ACCESS: Final = 0x1F007F +TRANSACTION_RESOURCE_MANAGER_RIGHTS: Final = 0x120037 +RESOURCEMANAGER_QUERY_INFORMATION: Final = 0x0001 +RESOURCEMANAGER_SET_INFORMATION: Final = 0x0002 +RESOURCEMANAGER_RECOVER: Final = 0x0004 +RESOURCEMANAGER_ENLIST: Final = 0x0008 +RESOURCEMANAGER_GET_NOTIFICATION: Final = 0x0010 +RESOURCEMANAGER_REGISTER_PROTOCOL: Final = 0x0020 +RESOURCEMANAGER_COMPLETE_PROPAGATION: Final = 0x0040 +RESOURCEMANAGER_GENERIC_READ: Final = 0x120001 +RESOURCEMANAGER_GENERIC_WRITE: Final = 0x12007E +RESOURCEMANAGER_GENERIC_EXECUTE: Final = 0x12005C +RESOURCEMANAGER_ALL_ACCESS: Final = 0x1F007F +ENLISTMENT_QUERY_INFORMATION: Final = 0x0001 +ENLISTMENT_SET_INFORMATION: Final = 0x0002 +ENLISTMENT_RECOVER: Final = 0x0004 +ENLISTMENT_SUBORDINATE_RIGHTS: Final = 0x0008 +ENLISTMENT_SUPERIOR_RIGHTS: Final = 0x0010 +ENLISTMENT_GENERIC_READ: Final = 0x20001 +ENLISTMENT_GENERIC_WRITE: Final = 0x2001E +ENLISTMENT_GENERIC_EXECUTE: Final = 0x2001C +ENLISTMENT_ALL_ACCESS: Final = 0xF001F +TransactionOutcomeUndetermined: Final = 1 +TransactionOutcomeCommitted: Final = 2 +TransactionOutcomeAborted: Final = 3 +TransactionStateNormal: Final = 1 +TransactionStateIndoubt: Final = 2 +TransactionStateCommittedNotify: Final = 3 +TransactionBasicInformation: Final = 0 +TransactionPropertiesInformation: Final = 1 +TransactionEnlistmentInformation: Final = 2 +TransactionFullInformation: Final = 3 +TransactionManagerBasicInformation: Final = 0 +TransactionManagerLogInformation: Final = 1 +TransactionManagerLogPathInformation: Final = 2 +TransactionManagerOnlineProbeInformation: Final = 3 +ResourceManagerBasicInformation: Final = 0 +ResourceManagerCompletionInformation: Final = 1 +ResourceManagerFullInformation: Final = 2 +ResourceManagerNameInformation: Final = 3 +EnlistmentBasicInformation: Final = 0 +EnlistmentRecoveryInformation: Final = 1 +EnlistmentFullInformation: Final = 2 +EnlistmentNameInformation: Final = 3 +KTMOBJECT_TRANSACTION: Final = 0 +KTMOBJECT_TRANSACTION_MANAGER: Final = 1 +KTMOBJECT_RESOURCE_MANAGER: Final = 2 +KTMOBJECT_ENLISTMENT: Final = 3 +KTMOBJECT_INVALID: Final = 4 diff --git a/stubs/pywin32/win32/lib/winperf.pyi b/stubs/pywin32/win32/lib/winperf.pyi new file mode 100644 index 000000000000..e1ad6c0e7dbe --- /dev/null +++ b/stubs/pywin32/win32/lib/winperf.pyi @@ -0,0 +1,73 @@ +from typing import Final + +PERF_DATA_VERSION: Final = 1 +PERF_DATA_REVISION: Final = 1 +PERF_NO_INSTANCES: Final = -1 +PERF_SIZE_DWORD: Final = 0x00000000 +PERF_SIZE_LARGE: Final = 0x00000100 +PERF_SIZE_ZERO: Final = 0x00000200 +PERF_SIZE_VARIABLE_LEN: Final = 0x00000300 +PERF_TYPE_NUMBER: Final = 0x00000000 +PERF_TYPE_COUNTER: Final = 0x00000400 +PERF_TYPE_TEXT: Final = 0x00000800 +PERF_TYPE_ZERO: Final = 0x00000C00 +PERF_NUMBER_HEX: Final = 0x00000000 +PERF_NUMBER_DECIMAL: Final = 0x00010000 +PERF_NUMBER_DEC_1000: Final = 0x00020000 +PERF_COUNTER_VALUE: Final = 0x00000000 +PERF_COUNTER_RATE: Final = 0x00010000 +PERF_COUNTER_FRACTION: Final = 0x00020000 +PERF_COUNTER_BASE: Final = 0x00030000 +PERF_COUNTER_ELAPSED: Final = 0x00040000 +PERF_COUNTER_QUEUELEN: Final = 0x00050000 +PERF_COUNTER_HISTOGRAM: Final = 0x00060000 +PERF_TEXT_UNICODE: Final = 0x00000000 +PERF_TEXT_ASCII: Final = 0x00010000 +PERF_TIMER_TICK: Final = 0x00000000 +PERF_TIMER_100NS: Final = 0x00100000 +PERF_OBJECT_TIMER: Final = 0x00200000 +PERF_DELTA_COUNTER: Final = 0x00400000 +PERF_DELTA_BASE: Final = 0x00800000 +PERF_INVERSE_COUNTER: Final = 0x01000000 +PERF_MULTI_COUNTER: Final = 0x02000000 +PERF_DISPLAY_NO_SUFFIX: Final = 0x00000000 +PERF_DISPLAY_PER_SEC: Final = 0x10000000 +PERF_DISPLAY_PERCENT: Final = 0x20000000 +PERF_DISPLAY_SECONDS: Final = 0x30000000 +PERF_DISPLAY_NOSHOW: Final = 0x40000000 +PERF_COUNTER_COUNTER: Final = 0x10410400 +PERF_COUNTER_TIMER: Final = 0x20410500 +PERF_COUNTER_QUEUELEN_TYPE: Final = 0x00450400 +PERF_COUNTER_LARGE_QUEUELEN_TYPE: Final = 0x00450500 +PERF_COUNTER_BULK_COUNT: Final = 0x10410500 +PERF_COUNTER_TEXT: Final = 0x00000B00 +PERF_COUNTER_RAWCOUNT: Final = 0x00010000 +PERF_COUNTER_LARGE_RAWCOUNT: Final = 0x00010100 +PERF_COUNTER_RAWCOUNT_HEX: Final = 0x00000000 +PERF_COUNTER_LARGE_RAWCOUNT_HEX: Final = 0x00000100 +PERF_SAMPLE_FRACTION: Final = 0x20C20400 +PERF_SAMPLE_COUNTER: Final = 0x00410400 +PERF_COUNTER_NODATA: Final = 0x40000200 +PERF_COUNTER_TIMER_INV: Final = 0x21410500 +PERF_SAMPLE_BASE: Final = 0x40030401 +PERF_AVERAGE_TIMER: Final = 0x30020400 +PERF_AVERAGE_BASE: Final = 0x40030402 +PERF_AVERAGE_BULK: Final = 0x40020500 +PERF_100NSEC_TIMER: Final = 0x20510500 +PERF_100NSEC_TIMER_INV: Final = 0x21510500 +PERF_COUNTER_MULTI_TIMER: Final = 0x22410500 +PERF_COUNTER_MULTI_TIMER_INV: Final = 0x23410500 +PERF_COUNTER_MULTI_BASE: Final = 0x42030500 +PERF_100NSEC_MULTI_TIMER: Final = 0x22510500 +PERF_100NSEC_MULTI_TIMER_INV: Final = 0x23510500 +PERF_RAW_FRACTION: Final = 0x20020400 +PERF_RAW_BASE: Final = 0x40030403 +PERF_ELAPSED_TIME: Final = 0x30240500 +PERF_COUNTER_HISTOGRAM_TYPE: Final = -0x80000000 +PERF_COUNTER_DELTA: Final = 0x00400400 +PERF_COUNTER_LARGE_DELTA: Final = 0x00400500 +PERF_DETAIL_NOVICE: Final = 100 +PERF_DETAIL_ADVANCED: Final = 200 +PERF_DETAIL_EXPERT: Final = 300 +PERF_DETAIL_WIZARD: Final = 400 +PERF_NO_UNIQUE_ID: Final = -1 diff --git a/stubs/pywin32/win32/lib/winxptheme.pyi b/stubs/pywin32/win32/lib/winxptheme.pyi new file mode 100644 index 000000000000..6f88b731dedd --- /dev/null +++ b/stubs/pywin32/win32/lib/winxptheme.pyi @@ -0,0 +1,25 @@ +import _win32typing + +def OpenThemeData(hwnd: int, pszClasslist: str, /) -> _win32typing.PyHTHEME: ... +def CloseThemeData(hTheme: _win32typing.PyHTHEME, /) -> None: ... +def DrawThemeBackground(hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pRect, pClipRect, /) -> None: ... +def DrawThemeText( + hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pszText: str, dwCharCount, dwTextFlags, dwTextFlags2, pRect, / +) -> None: ... +def GetThemeBackgroundContentRect(hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pBoundingRect, /): ... +def GetThemeBackgroundExtent(hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pContentRect, /): ... +def IsThemeActive() -> int: ... +def IsAppThemed() -> int: ... +def GetWindowTheme(hwnd: int, /) -> _win32typing.PyHTHEME: ... +def EnableThemeDialogTexture(hdlg, dwFlags, /) -> None: ... +def IsThemeDialogTextureEnabled(hdlg: int | None, /) -> bool: ... +def GetThemeAppProperties(): ... +def EnableTheming(fEnable, /) -> None: ... +def SetWindowTheme(hwnd: int, pszSubAppName: str, pszSubIdlist: str, /) -> None: ... +def GetCurrentThemeName() -> tuple[str, str, str]: ... + +ETDT_DISABLE: int +ETDT_ENABLE: int +ETDT_ENABLETAB: int +ETDT_USETABTEXTURE: int +UNICODE: int diff --git a/stubs/pywin32/win32/mmapfile.pyi b/stubs/pywin32/win32/mmapfile.pyi new file mode 100644 index 000000000000..8d943c3722e5 --- /dev/null +++ b/stubs/pywin32/win32/mmapfile.pyi @@ -0,0 +1,6 @@ +import _win32typing +from win32.lib.pywintypes import error as error + +def mmapfile( + File, Name, MaximumSize: int = ..., FileOffset: int = ..., NumberOfBytesToMap: int = ... +) -> _win32typing.Pymmapfile: ... diff --git a/stubs/pywin32/win32/odbc.pyi b/stubs/pywin32/win32/odbc.pyi new file mode 100644 index 000000000000..0a0b7f54047c --- /dev/null +++ b/stubs/pywin32/win32/odbc.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +import _win32typing + +def odbc(connectionString: str, /) -> _win32typing.connection: ... +def SQLDataSources(direction, /) -> tuple[Incomplete, Incomplete]: ... + +DATE: str +NUMBER: str +RAW: str +SQL_FETCH_ABSOLUTE: int +SQL_FETCH_FIRST: int +SQL_FETCH_FIRST_SYSTEM: int +SQL_FETCH_FIRST_USER: int +SQL_FETCH_LAST: int +SQL_FETCH_NEXT: int +SQL_FETCH_PRIOR: int +SQL_FETCH_RELATIVE: int +STRING: str +TYPES: tuple[Literal["STRING"], Literal["RAW"], Literal["NUMBER"], Literal["DATE"]] + +class error(Exception): + __name__: ClassVar[str] = "odbcError" + +# These all pretend to come from a module called "dbi", but that module doesn't exist +class dataError(Exception): ... +class integrityError(Exception): ... +class internalError(Exception): ... +class noError(Exception): ... +class opError(Exception): ... +class progError(Exception): ... diff --git a/stubs/pywin32/win32/perfmon.pyi b/stubs/pywin32/win32/perfmon.pyi new file mode 100644 index 000000000000..a7ea4e3d2081 --- /dev/null +++ b/stubs/pywin32/win32/perfmon.pyi @@ -0,0 +1,13 @@ +import _win32typing + +def LoadPerfCounterTextStrings(commandLine: str, /) -> None: ... +def UnloadPerfCounterTextStrings(commandLine: str, /) -> None: ... +def CounterDefinition() -> _win32typing.PyPERF_COUNTER_DEFINITION: ... +def ObjectType() -> _win32typing.PyPERF_OBJECT_TYPE: ... +def PerfMonManager( + serviceName: str, + seqPerfObTypes: list[_win32typing.PyPERF_OBJECT_TYPE], + mappingName: str | None = ..., + eventSourceName: str | None = ..., + /, +) -> _win32typing.PyPerfMonManager: ... diff --git a/stubs/pywin32/win32/servicemanager.pyi b/stubs/pywin32/win32/servicemanager.pyi new file mode 100644 index 000000000000..6acc15a79403 --- /dev/null +++ b/stubs/pywin32/win32/servicemanager.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +def CoInitializeEx() -> None: ... +def CoUninitialize() -> None: ... +def RegisterServiceCtrlHandler(serviceName: str, callback, extra_args: bool = ..., /): ... +def LogMsg(errorType: int, eventId: int, inserts: tuple[str, str] | None = ..., /) -> None: ... +def LogInfoMsg(msg: str, /) -> None: ... +def LogErrorMsg(msg: str, /) -> None: ... +def LogWarningMsg(msg: str, /) -> None: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def Debugging(newVal: int = ..., /): ... +def Initialize(eventSourceName: str | None = ..., eventSourceFile: str | None = ..., /) -> None: ... +def Finalize() -> None: ... +def PrepareToHostSingle(klass: Incomplete | None = ..., /) -> None: ... +def PrepareToHostMultiple(service_name: str, klass, /) -> None: ... +def RunningAsService(): ... +def SetEventSourceName(sourceName: str, registerNow: bool = ..., /) -> None: ... +def StartServiceCtrlDispatcher(): ... + +COINIT_APARTMENTTHREADED: int +COINIT_DISABLE_OLE1DDE: int +COINIT_MULTITHREADED: int +COINIT_SPEED_OVER_MEMORY: int +EVENTLOG_AUDIT_FAILURE: int +EVENTLOG_AUDIT_SUCCESS: int +EVENTLOG_ERROR_TYPE: int +EVENTLOG_INFORMATION_TYPE: int +EVENTLOG_WARNING_TYPE: int +PYS_SERVICE_STARTED: int +PYS_SERVICE_STARTING: int +PYS_SERVICE_STOPPED: int +PYS_SERVICE_STOPPING: int + +class startup_error(Exception): ... diff --git a/stubs/pywin32/win32/timer.pyi b/stubs/pywin32/win32/timer.pyi new file mode 100644 index 000000000000..ad8a7bcbe0b9 --- /dev/null +++ b/stubs/pywin32/win32/timer.pyi @@ -0,0 +1,6 @@ +from win32.lib.pywintypes import error as error + +def set_timer(Elapse, TimerFunc, /): ... +def kill_timer(timer_id, /): ... + +__version__: bytes diff --git a/stubs/pywin32/win32/win32api.pyi b/stubs/pywin32/win32/win32api.pyi new file mode 100644 index 000000000000..493dcce90c87 --- /dev/null +++ b/stubs/pywin32/win32/win32api.pyi @@ -0,0 +1,376 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Callable, Iterable +from typing import Literal, TypedDict, overload, type_check_only +from typing_extensions import deprecated + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +@type_check_only +class _MonitorInfo(TypedDict): + Monitor: tuple[int, int, int, int] + Work: tuple[int, int, int, int] + Flags: int + Device: str + +@type_check_only +class _FileVersionInfo(TypedDict): + Signature: int + StrucVersion: int + FileVersionMS: int + FileVersionLS: int + ProductVersionMS: int + ProductVersionLS: int + FileFlagsMask: int + FileFlags: int + FileOS: int + FileType: int + FileSubtype: int + FileDate: Incomplete | None + +@type_check_only +class _PwrCapabilitiesBatteryScale(TypedDict): + Granularity: int + Capacity: int + +@type_check_only +class _PwrCapabilities(TypedDict): + PowerButtonPresent: bool + SleepButtonPresent: bool + LidPresent: bool + SystemS1: bool + SystemS2: bool + SystemS3: bool + SystemS4: bool + SystemS5: bool + HiberFilePresent: bool + FullWake: bool + VideoDimPresent: bool + ApmPresent: bool + UpsPresent: bool + ThermalControl: bool + ProcessorThrottle: bool + ProcessorMinThrottle: int + ProcessorMaxThrottle: int + FastSystemS4: bool + spare2: Incomplete | None + DiskSpinDown: bool + spare3: Incomplete | None + SystemBatteriesPresent: bool + BatteriesAreShortTerm: bool + BatteryScale: tuple[_PwrCapabilitiesBatteryScale, ...] + AcOnLineWake: int + SoftLidWake: int + RtcWake: int + MinDeviceWakeState: int + DefaultLowLatencyWake: int + +def AbortSystemShutdown(computerName: str, /) -> None: ... +def InitiateSystemShutdown(computerName: str, message: str, timeOut, bForceClose, bRebootAfterShutdown, /) -> None: ... +def Apply(exceptionHandler, func, args, /): ... +def Beep(freq, dur, /) -> None: ... +def BeginUpdateResource(filename: str, delete, /) -> int: ... +def ChangeDisplaySettings(DevMode: _win32typing.PyDEVMODEW, Flags, /): ... +def ChangeDisplaySettingsEx(DeviceName: str | None = ..., DevMode: _win32typing.PyDEVMODEW | None = ..., Flags=...) -> int: ... +def ClipCursor(arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... +def CloseHandle(handle: int, /) -> None: ... +def CopyFile(src, dest: str, bFailOnExist: int = ..., /) -> None: ... +def DebugBreak() -> None: ... +def DeleteFile(fileName: str, /) -> None: ... + +@overload +def DragQueryFile(hDrop, fileNum: Literal[-1] = -1, /) -> int: ... # type: ignore[overload-overlap] +@overload +def DragQueryFile(hDrop, fileNum: int, /) -> str: ... + +def DragFinish(hDrop, /) -> None: ... +def DuplicateHandle( + hSourceProcess: int, hSource: int, hTargetProcessHandle: int, desiredAccess: int, bInheritHandle: int, options: int, / +) -> int: ... +def EndUpdateResource(handle: int, discard, /) -> None: ... +def EnumDisplayDevices(Device: str | None = ..., DevNum: int = ..., Flags: int = ...) -> _win32typing.PyDISPLAY_DEVICE: ... +def EnumDisplayMonitors( + hdc: int | None = ..., rcClip: _win32typing.PyRECT | None = ... +) -> list[tuple[_win32typing.PyHANDLE, _win32typing.PyHANDLE, tuple[int, int, int, int]]]: ... +def EnumDisplaySettings(DeviceName: str | None = ..., ModeNum: int = ...) -> _win32typing.PyDEVMODEW: ... +def EnumDisplaySettingsEx(DeviceName: str | None = ..., ModeNum=..., Flags=...) -> _win32typing.PyDEVMODEW: ... +def EnumResourceLanguages( + hmodule: int, lpType: _win32typing.PyResourceId, lpName: _win32typing.PyResourceId, / +) -> list[Incomplete]: ... +def EnumResourceNames(hmodule: int, resType: _win32typing.PyResourceId, /) -> list[str]: ... +def EnumResourceTypes(hmodule: int, /) -> list[Incomplete]: ... +def ExpandEnvironmentStrings(_in: str, /) -> str: ... +def ExitWindows(reserved1: int = ..., reserved2: int = ..., /) -> None: ... +def ExitWindowsEx(flags, reserved: int = ..., /) -> None: ... +def FindFiles(fileSpec: str, /): ... +def FindFirstChangeNotification(pathName: str, bSubDirs, _filter, /): ... +def FindNextChangeNotification(handle: int, /) -> None: ... +def FindCloseChangeNotification(handle, /) -> None: ... +def FindExecutable(filename: str, _dir: str, /) -> tuple[Incomplete, str]: ... +def FormatMessage( + flags: int, source: str | None = ..., messageId: int = ..., languageID: int = ..., inserts: Iterable[str] | None = ..., / +) -> str: ... +def FormatMessageW( + flags: int, source: int | None = ..., messageId: int = ..., languageID: int = ..., inserts: Iterable[str] | None = ..., / +) -> str: ... +def FreeLibrary(hModule: int, /) -> None: ... +def GenerateConsoleCtrlEvent(controlEvent: int, processGroupId: int, /) -> None: ... +def GetAsyncKeyState(key: int, /) -> int: ... +def GetCommandLine() -> str: ... +def GetComputerName() -> str: ... +def GetComputerNameEx(NameType: int, /) -> str: ... +def GetComputerObjectName(NameFormat: int, /) -> str: ... +def GetMonitorInfo(hMonitor: int) -> _MonitorInfo: ... +def GetUserName() -> str: ... +def GetUserNameEx(NameFormat: int, /) -> str: ... +def GetCursorPos() -> tuple[int, int]: ... +def GetCurrentThread() -> int: ... +def GetCurrentThreadId() -> int: ... +def GetCurrentProcessId() -> int: ... +def GetCurrentProcess() -> int: ... +def GetConsoleTitle() -> str: ... +def GetDateFormat(locale: int, flags: int, time: TimeType | None, _format: str | None = None, /) -> str: ... +def GetDiskFreeSpace(rootPath: str | None = None, /) -> tuple[int, int, int, int]: ... +def GetDiskFreeSpaceEx(rootPath: str | None = None, /) -> tuple[int, int, int]: ... +def GetDllDirectory() -> str: ... +def GetDomainName() -> str: ... +def GetEnvironmentVariable(variable: str, /) -> str | None: ... +def GetEnvironmentVariableW(Name: str, /) -> str | None: ... +def GetFileAttributes(pathName: str, /) -> int: ... +def GetFileVersionInfo(Filename: str, SubBlock: str, /) -> _FileVersionInfo: ... +def GetFocus(): ... +def GetFullPathName(fileName: str, /) -> str: ... +def GetHandleInformation(Object: int, /): ... +def GetKeyboardLayout(threadId: int = ..., /) -> int: ... +def GetKeyboardLayoutName() -> str: ... +def GetKeyboardState() -> bytes: ... +def GetKeyState(key: int, /) -> int: ... +def GetLastError() -> int: ... +def GetLastInputInfo() -> int: ... +def GetLocalTime() -> tuple[int, int, int, int, int, int, int, int]: ... +def GetLongPathName(fileName: str, /) -> str: ... +def GetLongPathNameW(fileName: str, /) -> str: ... +def GetLogicalDrives() -> int: ... +def GetLogicalDriveStrings() -> str: ... +def GetModuleFileName(hModule: int | None, /) -> str: ... +def GetModuleFileNameW(hModule: int | None, /) -> str: ... +def GetModuleHandle(fileName: str | None = None, /) -> int: ... +def GetPwrCapabilities() -> _PwrCapabilities: ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def GetProfileSection(section: str, iniName: str | None = ..., /) -> list[Incomplete]: ... +def GetProcAddress(hModule: int, functionName: _win32typing.PyResourceId, /): ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def GetProfileVal(section: str, entry: str, defValue: str, iniName: str | None = ..., /) -> str: ... +def GetShortPathName(path: str, /) -> str: ... +def GetStdHandle(handle: int, /) -> int: ... +def GetSysColor(index: int, /) -> int: ... +def GetSystemCpuSetInformation() -> list[_win32typing.PySYSTEM_CPU_SET_INFORMATION]: ... +def GetSystemDefaultLangID() -> int: ... +def GetSystemDefaultLCID() -> int: ... +def GetSystemDirectory() -> str: ... +def GetSystemFileCacheSize() -> tuple[int, int, int]: ... +def SetSystemFileCacheSize(MinimumFileCacheSize: int, MaximumFileCacheSize: int, Flags: int = ...) -> None: ... +def GetSystemInfo() -> tuple[int, int, int, int, int, int, int, int, tuple[int, int]]: ... +def GetNativeSystemInfo() -> tuple[int, int, int, int, int, int, int, int, tuple[int, int]]: ... +def GetSystemMetrics(index: int, /) -> int: ... +def GetSystemPowerStatus() -> dict[str, int]: ... +def GetSystemTime() -> tuple[int, int, int, int, int, int, int, int]: ... +def GetTempFileName(path: str, prefix: str, nUnique: int = ..., /) -> tuple[str, int]: ... +def GetTempPath() -> str: ... +def GetThreadLocale() -> int: ... +def GetTickCount() -> int: ... +def GetTimeFormat(locale: int, flags: int, time: TimeType | None, _format: str, /) -> str: ... + +@overload +def GetTimeZoneInformation( + times_as_tuples: Literal[True] = True, / +) -> tuple[ + int, + tuple[int, str, tuple[int, int, int, int, int, int, int, int], int, str, tuple[int, int, int, int, int, int, int, int], int], +]: ... +@overload +def GetTimeZoneInformation(times_as_tuples: Literal[False], /): ... + +def GetVersion() -> int: ... +def GetVersionEx(_format: int = ..., /) -> tuple[int, int, int, int, str]: ... +def GetVolumeInformation(path: str, /) -> tuple[str, int, int, int, str]: ... +def GetWindowsDirectory() -> str: ... +def GetWindowLong(hwnd: int | None, offset: int, /) -> int: ... +def GetUserDefaultLangID() -> int: ... +def GetUserDefaultLCID() -> int: ... +def GlobalMemoryStatus() -> dict[str, int]: ... +def GlobalMemoryStatusEx() -> dict[str, int]: ... +def keybd_event(bVk, bScan, dwFlags: int = ..., dwExtraInfo: int = ..., /) -> None: ... +def mouse_event(dx, dy, dwData, dwFlags: int = ..., dwExtraInfo=..., /) -> None: ... +def LoadCursor(hInstance: int, cursorid: _win32typing.PyResourceId, /) -> int: ... +def LoadKeyboardLayout(KLID: str, Flags: int = ..., /): ... +def LoadLibrary(fileName: str, /): ... +def LoadLibraryEx(fileName: str, handle: int, handle1, /) -> int: ... +def LoadResource(handle: int, _type: _win32typing.PyResourceId, name: _win32typing.PyResourceId, language, /) -> str: ... +def LoadString(handle: int, stringId, numChars: int = ..., /) -> str: ... +def MessageBeep(type: int = 0, /): ... +def MessageBox(hwnd: int | None, message: str, title: str | None = ..., style=..., language=..., /) -> int: ... +def MonitorFromPoint(pt: tuple[Incomplete, Incomplete], Flags: int = ...) -> int: ... +def MonitorFromRect(rc: _win32typing.PyRECT | tuple[int, int, int, int], Flags: int = ...) -> int: ... +def MonitorFromWindow(hwnd: int, Flags: int = ...) -> int: ... +def MoveFile(srcName: str, destName: str, /) -> None: ... +def MoveFileEx(srcName: str, destName: str, flag, /) -> None: ... +def OpenProcess(reqdAccess: int, bInherit: int | bool, pid: int, /) -> int: ... +def OutputDebugString(msg: str, /) -> None: ... +def PostMessage(hwnd: int, idMessage, wParam: Incomplete | None = ..., lParam: Incomplete | None = ..., /) -> None: ... +def PostQuitMessage(exitCode: int = ..., /) -> None: ... +def PostThreadMessage(tid, idMessage, wParam: Incomplete | None = ..., lParam: Incomplete | None = ..., /) -> None: ... +def RegCloseKey(key: _win32typing.PyHKEY, /) -> None: ... +def RegConnectRegistry(computerName: str, key, /): ... +def RegCopyTree(KeySrc: _win32typing.PyHKEY, SubKey: str, KeyDest: _win32typing.PyHKEY) -> None: ... +def RegCreateKey(key: _win32typing.PyHKEY | int, subKey: str, /) -> _win32typing.PyHKEY: ... +def RegCreateKeyEx( + Key: _win32typing.PyHKEY, + SubKey: str, + samDesired, + Class: str | None = ..., + Options=..., + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + Transaction: int | None = ..., +) -> tuple[_win32typing.PyHKEY, Incomplete]: ... +def RegDeleteKey(key: _win32typing.PyHKEY, subKey: str, /) -> None: ... +def RegDeleteKeyEx(Key: _win32typing.PyHKEY, SubKey: str, samDesired: int = ..., Transaction: int | None = ...) -> None: ... +def RegDeleteTree(Key: _win32typing.PyHKEY, SubKey: str) -> None: ... +def RegDeleteValue(key: _win32typing.PyHKEY, value: str, /) -> None: ... +def RegEnumKey(key: _win32typing.PyHKEY, index, /) -> str: ... +def RegEnumKeyEx(Key: _win32typing.PyHKEY, /): ... +def RegEnumKeyExW(Key: _win32typing.PyHKEY, /): ... +def RegEnumValue(key: _win32typing.PyHKEY, index, /) -> tuple[str, Incomplete, Incomplete]: ... +def RegFlushKey(key: _win32typing.PyHKEY, /) -> None: ... +def RegGetKeySecurity(key: _win32typing.PyHKEY, security_info, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def RegLoadKey(key: _win32typing.PyHKEY, subKey: str, filename: str, /) -> None: ... +def RegOpenCurrentUser(samDesired=..., /) -> _win32typing.PyHKEY: ... +def RegOpenKey( + key: _win32typing.PyHKEY | int, subkey: str | None, reserved: bool = ..., sam: int = ..., / +) -> _win32typing.PyHKEY: ... +def RegOpenKeyEx(key: _win32typing.PyHKEY, subKey: str, sam: int, reserved: bool = ..., /) -> _win32typing.PyHKEY: ... +def RegOpenKeyTransacted( + Key: _win32typing.PyHKEY, SubKey: str, samDesired, Transaction: int, Options: int = ... +) -> _win32typing.PyHKEY: ... +def RegOverridePredefKey(Key: _win32typing.PyHKEY, NewKey: _win32typing.PyHKEY) -> None: ... +def RegQueryValue(key: _win32typing.PyHKEY | int, subKey: str | None, /) -> str: ... +def RegQueryValueEx(key: _win32typing.PyHKEY | int, valueName: str | None, /) -> tuple[str, int]: ... +def RegQueryInfoKey(key: _win32typing.PyHKEY, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def RegQueryInfoKeyW(Key: _win32typing.PyHKEY, /): ... +def RegRestoreKey(Key: _win32typing.PyHKEY, File: str, Flags: int = ...) -> None: ... +def RegSaveKey(key: _win32typing.PyHKEY, filename: str, sa: _win32typing.PySECURITY_ATTRIBUTES | None = ..., /) -> None: ... +def RegSaveKeyEx( + Key: _win32typing.PyHKEY, File: str, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., Flags=... +) -> None: ... +def RegSetKeySecurity(key: _win32typing.PyHKEY, security_info, sd: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def RegSetValue(key: _win32typing.PyHKEY, subKey: str | None, _type, value: str, /) -> None: ... +def RegSetValueEx(key: _win32typing.PyHKEY, valueName: str, reserved, _type, value, /) -> None: ... +def RegUnLoadKey(key: _win32typing.PyHKEY, subKey: str, /) -> None: ... +def RegisterWindowMessage(msgString: str, /) -> None: ... +def RegNotifyChangeKeyValue(key: _win32typing.PyHKEY, bWatchSubTree, dwNotifyFilter, hKey: int, fAsynchronous, /) -> None: ... +def SearchPath(path: str, fileName: str, fileExt: str | None = ..., /): ... +def SendMessage(hwnd: int, idMessage, wParam: str | None = ..., lParam: str | None = ..., /) -> None: ... +def SetConsoleCtrlHandler(ctrlHandler: Callable[[int], bool], bAdd: bool, /) -> None: ... +def SetConsoleTitle(title: str, /) -> None: ... +def SetCursorPos(arg: tuple[Incomplete, Incomplete], /) -> None: ... +def SetDllDirectory(PathName: str, /) -> None: ... +def SetErrorMode(errorMode, /): ... +def SetFileAttributes(pathName: str, attrs, /): ... +def SetLastError(errVal: int, /): ... +def SetSysColors(Elements, RgbValues, /) -> None: ... +def SetLocalTime(SystemTime: TimeType, /) -> None: ... +def SetSystemTime(year, month, dayOfWeek, day, hour, minute, second, milliseconds, /): ... +def SetClassLong(hwnd: int, offset, val, /): ... +@deprecated("This function is obsolete, use `win32api.SetClassLong` instead.") +def SetClassWord(hwnd: int, offset, val, /): ... +def SetCursor(hCursor: int, /) -> int: ... +def SetEnvironmentVariable(Name, Value, /) -> None: ... +def SetEnvironmentVariableW(Name, Value, /) -> None: ... +def SetHandleInformation(Object: int, Mask, Flags, /) -> None: ... +def SetStdHandle(handle, handle1: int, /) -> None: ... +def SetSystemPowerState(Suspend, Force, /) -> None: ... +def SetThreadLocale(lcid, /) -> None: ... +def SetTimeZoneInformation(tzi, /): ... +def SetWindowLong(hwnd: int | None, offset: int, value: float, /) -> int: ... +@deprecated("This function is obsolete, use `win32api.SetWindowLong` instead.") +def SetWindowWord(hwnd, offset: int, val: int) -> int: ... +def ShellExecute(hwnd: int, op: str, file: str, params: str, _dir: str, bShow, /): ... +def ShowCursor(show, /): ... +def Sleep(time, bAlterable: int = ..., /): ... +def TerminateProcess(handle: int, exitCode: int, /) -> None: ... +def ToAsciiEx(vk, scancode, keyboardstate, flags: int = ..., hlayout: Incomplete | None = ..., /): ... +def UpdateResource( + handle: int, + type: _win32typing.PyResourceId | int, + name: _win32typing.PyResourceId | int, + data: ReadableBuffer | None, + language: int = ..., + /, +) -> None: ... +def VkKeyScan(char: str | bytes, /): ... +def WinExec(cmdLine: str, arg, /) -> None: ... +def WinHelp(hwnd: int, hlpFile: str, cmd, data: str | int = ..., /) -> None: ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def WriteProfileSection(section: str, data: str, iniName: str | None = ..., /): ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def WriteProfileVal(section: str, entry: str, value: str, iniName: str | None = ..., /) -> None: ... +def HIBYTE(val: int, /) -> int: ... +def LOBYTE(val: int, /) -> int: ... +def HIWORD(val: int, /) -> int: ... +def LOWORD(val: int, /) -> int: ... +def RGB(red: int, green: int, blue: int, /) -> int: ... +def MAKELANGID(PrimaryLanguage, SubLanguage, /): ... +def MAKEWORD(low, high, /): ... +def MAKELONG(low, high, /): ... +def CommandLineToArgv(cmdLine: str, /) -> list[str]: ... +def GetKeyboardLayoutList() -> tuple[int, int]: ... +def MapVirtualKey(vk: int, type: int, hlayout=None, /) -> int: ... +def MessageBoxEx(hwnd, message: str, title: str | None = ..., style: int = ..., language: int = ..., /) -> int: ... +def OpenThread(reqdAccess: int, bInherit, pid: int, /): ... +def SleepEx(time: int, bAlterable=0, /) -> int: ... +def VkKeyScanEx(char: str | bytes, hkl, /) -> int: ... + +NameCanonical: int +NameCanonicalEx: int +NameDisplay: int +NameFullyQualifiedDN: int +NameSamCompatible: int +NameServicePrincipal: int +NameUniqueId: int +NameUnknown: int +NameUserPrincipal: int +PyDISPLAY_DEVICEType = _win32typing.PyDISPLAY_DEVICE +REG_NOTIFY_CHANGE_ATTRIBUTES: int +REG_NOTIFY_CHANGE_LAST_SET: int +REG_NOTIFY_CHANGE_NAME: int +REG_NOTIFY_CHANGE_SECURITY: int +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +VFT_APP: int +VFT_DLL: int +VFT_DRV: int +VFT_FONT: int +VFT_STATIC_LIB: int +VFT_UNKNOWN: int +VFT_VXD: int +VOS_DOS: int +VOS_DOS_WINDOWS16: int +VOS_DOS_WINDOWS32: int +VOS_NT: int +VOS_NT_WINDOWS32: int +VOS_OS216: int +VOS_OS216_PM16: int +VOS_OS232: int +VOS_OS232_PM32: int +VOS_UNKNOWN: int +VOS__PM16: int +VOS__PM32: int +VOS__WINDOWS16: int +VOS__WINDOWS32: int +VS_FF_DEBUG: int +VS_FF_INFOINFERRED: int +VS_FF_PATCHED: int +VS_FF_PRERELEASE: int +VS_FF_PRIVATEBUILD: int +VS_FF_SPECIALBUILD: int diff --git a/stubs/pywin32/win32/win32clipboard.pyi b/stubs/pywin32/win32/win32clipboard.pyi new file mode 100644 index 000000000000..27ed86573bbe --- /dev/null +++ b/stubs/pywin32/win32/win32clipboard.pyi @@ -0,0 +1,48 @@ +from typing import Any, Final + +from win32.lib.pywintypes import error as error + +def ChangeClipboardChain(hWndRemove: int, hWndNewNext: int, /): ... +def CloseClipboard(): ... +def CountClipboardFormats(): ... +def EmptyClipboard(): ... +def EnumClipboardFormats(_format: int = ..., /): ... +def GetClipboardData(_format, /) -> Any: ... # str or bytes depending on the dib format +def GetClipboardDataHandle(_format, /): ... +def GetClipboardFormatName(_format, /) -> str: ... +def GetClipboardOwner(): ... +def GetClipboardSequenceNumber(): ... +def GetClipboardViewer(): ... +def GetGlobalMemory(hglobal: int, /) -> str: ... +def GetOpenClipboardWindow(): ... +def GetPriorityClipboardFormat(formats, /): ... +def IsClipboardFormatAvailable(format: int, /) -> int: ... +def OpenClipboard(hWnd: int | None = ..., /): ... +def RegisterClipboardFormat(name: str, /): ... +def SetClipboardData(_format, hMem, /): ... +def SetClipboardText(text, _format, /): ... +def SetClipboardViewer(hWndNewViewer: int, /) -> int: ... + +CF_BITMAP: Final[int] +CF_DIB: Final[int] +CF_DIBV5: Final[int] +CF_DIF: Final[int] +CF_DSPBITMAP: Final[int] +CF_DSPENHMETAFILE: Final[int] +CF_DSPMETAFILEPICT: Final[int] +CF_DSPTEXT: Final[int] +CF_ENHMETAFILE: Final[int] +CF_HDROP: Final[int] +CF_LOCALE: Final[int] +CF_MAX: Final[int] +CF_METAFILEPICT: Final[int] +CF_OEMTEXT: Final[int] +CF_OWNERDISPLAY: Final[int] +CF_PALETTE: Final[int] +CF_PENDATA: Final[int] +CF_RIFF: Final[int] +CF_SYLK: Final[int] +CF_TEXT: Final[int] +CF_TIFF: Final[int] +CF_UNICODETEXT: Final[int] +CF_WAVE: Final[int] diff --git a/stubs/pywin32/win32/win32console.pyi b/stubs/pywin32/win32/win32console.pyi new file mode 100644 index 000000000000..e007253a2637 --- /dev/null +++ b/stubs/pywin32/win32/win32console.pyi @@ -0,0 +1,82 @@ +from typing import Literal, overload +from typing_extensions import Never + +import _win32typing +from win32.lib.pywintypes import error as error + +def GetConsoleProcessList() -> tuple[int, ...]: ... +def CreateConsoleScreenBuffer( + DesiredAccess=..., ShareMode=..., SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., Flags=... +) -> _win32typing.PyConsoleScreenBuffer: ... +def GetConsoleDisplayMode(): ... +def AttachConsole(ProcessId) -> None: ... +def AllocConsole() -> None: ... +def FreeConsole() -> None: ... +def GetConsoleCP(): ... +def GetConsoleOutputCP(): ... +def SetConsoleCP(CodePageId) -> None: ... +def SetConsoleOutputCP(CodePageID) -> None: ... +def GetConsoleSelectionInfo(): ... +def AddConsoleAlias(Source, Target, ExeName) -> None: ... +def GetConsoleAliases(ExeName: str) -> str: ... +def GetConsoleAliasExes(): ... +def GetConsoleWindow(): ... +def GetNumberOfConsoleFonts(): ... +def SetConsoleTitle(ConsoleTitle: str) -> None: ... +def GetConsoleTitle(): ... + +@overload +def GenerateConsoleCtrlEvent(CtrlEvent: Literal[1], ProcessGroupId: Literal[0] = 0) -> Never: ... +@overload +def GenerateConsoleCtrlEvent(CtrlEvent: Literal[0, 1], ProcessGroupId: int) -> None: ... + +def GetStdHandle(StdHandle: int) -> _win32typing.PyConsoleScreenBuffer: ... + +ATTACH_PARENT_PROCESS: int +BACKGROUND_BLUE: int +BACKGROUND_GREEN: int +BACKGROUND_INTENSITY: int +BACKGROUND_RED: int +COMMON_LVB_GRID_HORIZONTAL: int +COMMON_LVB_GRID_LVERTICAL: int +COMMON_LVB_GRID_RVERTICAL: int +COMMON_LVB_LEADING_BYTE: int +COMMON_LVB_REVERSE_VIDEO: int +COMMON_LVB_TRAILING_BYTE: int +COMMON_LVB_UNDERSCORE: int +CONSOLE_FULLSCREEN: int +CONSOLE_FULLSCREEN_HARDWARE: int +CONSOLE_FULLSCREEN_MODE: int +CONSOLE_MOUSE_DOWN: int +CONSOLE_MOUSE_SELECTION: int +CONSOLE_NO_SELECTION: int +CONSOLE_SELECTION_IN_PROGRESS: int +CONSOLE_SELECTION_NOT_EMPTY: int +CONSOLE_TEXTMODE_BUFFER: int +CONSOLE_WINDOWED_MODE: int +CTRL_BREAK_EVENT: int +CTRL_C_EVENT: int +ENABLE_ECHO_INPUT: int +ENABLE_LINE_INPUT: int +ENABLE_MOUSE_INPUT: int +ENABLE_PROCESSED_INPUT: int +ENABLE_PROCESSED_OUTPUT: int +ENABLE_WINDOW_INPUT: int +ENABLE_WRAP_AT_EOL_OUTPUT: int +FOCUS_EVENT: int +FOREGROUND_BLUE: int +FOREGROUND_GREEN: int +FOREGROUND_INTENSITY: int +FOREGROUND_RED: int +KEY_EVENT: int +LOCALE_USER_DEFAULT: int +MENU_EVENT: int +MOUSE_EVENT: int +PyCOORDType = _win32typing.PyCOORD +PyConsoleScreenBufferType = _win32typing.PyConsoleScreenBuffer +PyINPUT_RECORDType = _win32typing.PyINPUT_RECORD +PySMALL_RECTType = _win32typing.PySMALL_RECT +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +WINDOW_BUFFER_SIZE_EVENT: int diff --git a/stubs/pywin32/win32/win32cred.pyi b/stubs/pywin32/win32/win32cred.pyi new file mode 100644 index 000000000000..e0b9c52d303d --- /dev/null +++ b/stubs/pywin32/win32/win32cred.pyi @@ -0,0 +1,91 @@ +from _typeshed import Incomplete + +def CredMarshalCredential(CredType, Credential: str) -> str: ... +def CredUnmarshalCredential(MarshaledCredential: str) -> tuple[Incomplete, str]: ... +def CredIsMarshaledCredential(MarshaledCredential: str) -> bool: ... +def CredEnumerate(Filter: str | None = ..., Flags: int = ...) -> tuple[dict[str, Incomplete], ...]: ... +def CredGetTargetInfo(TargetName: str, Flags: int = ...): ... +def CredGetSessionTypes(MaximumPersistCount: int = 7) -> tuple[int, ...]: ... +def CredWriteDomainCredentials(TargetInfo, Credential, Flags: int = ...) -> None: ... +def CredReadDomainCredentials(TargetInfo, Flags: int = ...) -> tuple[Incomplete, ...]: ... +def CredDelete(TargetName: str, Type, Flags: int = ...) -> None: ... +def CredWrite(Credential, Flags: int = ...) -> None: ... +def CredRead(TargetName: str, Type, Flags: int = ...): ... +def CredRename(OldTargetName: str, NewTargetName: str, Type, Flags: int = ...): ... +def CredUICmdLinePromptForCredentials( + TargetName: str, AuthError: int = ..., UserName: str | None = ..., Password: str | None = ..., Save: int = ..., Flags=... +) -> tuple[str, str, Incomplete]: ... +def CredUIPromptForCredentials( + TargetName: str, + AuthError: int = ..., + UserName: str | None = ..., + Password: str | None = ..., + Save: bool = ..., + Flags: int = ..., + UiInfo: Incomplete | None = ..., +) -> tuple[str, str, Incomplete]: ... +def CredUIConfirmCredentials(TargetName: str, Confirm) -> None: ... +def CredUIReadSSOCredW(Realm: str | None = ...) -> str: ... +def CredUIStoreSSOCredW(Realm: str, Username: str, Password: str, Persist) -> None: ... +def CredUIParseUserName(UserName: str) -> tuple[str, str]: ... + +CREDUI_FLAGS_ALWAYS_SHOW_UI: int +CREDUI_FLAGS_COMPLETE_USERNAME: int +CREDUI_FLAGS_DO_NOT_PERSIST: int +CREDUI_FLAGS_EXCLUDE_CERTIFICATES: int +CREDUI_FLAGS_EXPECT_CONFIRMATION: int +CREDUI_FLAGS_GENERIC_CREDENTIALS: int +CREDUI_FLAGS_INCORRECT_PASSWORD: int +CREDUI_FLAGS_KEEP_USERNAME: int +CREDUI_FLAGS_PASSWORD_ONLY_OK: int +CREDUI_FLAGS_PERSIST: int +CREDUI_FLAGS_PROMPT_VALID: int +CREDUI_FLAGS_REQUEST_ADMINISTRATOR: int +CREDUI_FLAGS_REQUIRE_CERTIFICATE: int +CREDUI_FLAGS_REQUIRE_SMARTCARD: int +CREDUI_FLAGS_SERVER_CREDENTIAL: int +CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX: int +CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS: int +CREDUI_FLAGS_VALIDATE_USERNAME: int +CREDUI_MAX_CAPTION_LENGTH: int +CREDUI_MAX_DOMAIN_TARGET_LENGTH: int +CREDUI_MAX_GENERIC_TARGET_LENGTH: int +CREDUI_MAX_MESSAGE_LENGTH: int +CREDUI_MAX_PASSWORD_LENGTH: int +CREDUI_MAX_USERNAME_LENGTH: int +CRED_ALLOW_NAME_RESOLUTION: int +CRED_CACHE_TARGET_INFORMATION: int +CRED_ENUMERATE_ALL_CREDENTIALS: int +CRED_FLAGS_OWF_CRED_BLOB: int +CRED_FLAGS_PASSWORD_FOR_CERT: int +CRED_FLAGS_PROMPT_NOW: int +CRED_FLAGS_USERNAME_TARGET: int +CRED_FLAGS_VALID_FLAGS: int +CRED_MAX_ATTRIBUTES: int +CRED_MAX_DOMAIN_TARGET_NAME_LENGTH: int +CRED_MAX_GENERIC_TARGET_NAME_LENGTH: int +CRED_MAX_STRING_LENGTH: int +CRED_MAX_USERNAME_LENGTH: int +CRED_MAX_VALUE_SIZE: int +CRED_PERSIST_ENTERPRISE: int +CRED_PERSIST_LOCAL_MACHINE: int +CRED_PERSIST_NONE: int +CRED_PERSIST_SESSION: int +CRED_PRESERVE_CREDENTIAL_BLOB: int +CRED_TI_CREATE_EXPLICIT_CRED: int +CRED_TI_DOMAIN_FORMAT_UNKNOWN: int +CRED_TI_ONLY_PASSWORD_REQUIRED: int +CRED_TI_SERVER_FORMAT_UNKNOWN: int +CRED_TI_USERNAME_TARGET: int +CRED_TI_VALID_FLAGS: int +CRED_TI_WORKGROUP_MEMBER: int +CRED_TYPE_DOMAIN_CERTIFICATE: int +CRED_TYPE_DOMAIN_EXTENDED: int +CRED_TYPE_DOMAIN_PASSWORD: int +CRED_TYPE_DOMAIN_VISIBLE_PASSWORD: int +CRED_TYPE_GENERIC: int +CRED_TYPE_GENERIC_CERTIFICATE: int +CRED_TYPE_MAXIMUM: int +CRED_TYPE_MAXIMUM_EX: int +CertCredential: int +UsernameTargetCredential: int diff --git a/stubs/pywin32/win32/win32crypt.pyi b/stubs/pywin32/win32/win32crypt.pyi new file mode 100644 index 000000000000..cf4056aaee0b --- /dev/null +++ b/stubs/pywin32/win32/win32crypt.pyi @@ -0,0 +1,173 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable, Sequence +from typing import Literal, overload + +import _win32typing + +def CryptProtectData( + DataIn: ReadableBuffer, + DataDescr: str | None = None, + OptionalEntropy: bytes | None = None, + Reserved: None = None, + PromptStruct: ( + tuple[int] + | tuple[int, int | _win32typing.PyHANDLE | None] + | tuple[int, int | _win32typing.PyHANDLE | None, str | None] + | None + ) = None, + Flags: int = 0, +) -> bytes: ... +def CryptUnprotectData( + DataIn: ReadableBuffer, + OptionalEntropy: bytes | None = None, + Reserved: None = None, + PromptStruct: ( + tuple[int] + | tuple[int, int | _win32typing.PyHANDLE | None] + | tuple[int, int | _win32typing.PyHANDLE | None, str | None] + | None + ) = None, + Flags: int = 0, +) -> tuple[str, bytes]: ... +def CryptEnumProviders() -> list[tuple[str, int]]: ... +def CryptEnumProviderTypes() -> list[tuple[str | None, int]]: ... +def CryptGetDefaultProvider(ProvType: int, Flags: int) -> str: ... +def CryptSetProviderEx(ProvName: str | None, ProvType: int, Flags: int) -> None: ... +def CryptAcquireContext( + Container: str | None, Provider: str | None, ProvType: int, Flags: int +) -> _win32typing.PyCRYPTPROV | None: ... +def CryptFindLocalizedName(CryptName: str) -> str | None: ... +def CertEnumSystemStore( + Flags: int, SystemStoreLocationPara: str | Sequence[int | _win32typing.PyHANDLE | str | None] | None = None +) -> list[str]: ... +def CertEnumSystemStoreLocation(Flags: int = 0) -> list[str]: ... +def CertEnumPhysicalStore(SystemStore: str, Flags: int) -> list[str]: ... +def CertRegisterSystemStore(SystemStore: str | Sequence[int | _win32typing.PyHANDLE | str | None], Flags: int) -> None: ... +def CertUnregisterSystemStore(SystemStore: str, Flags: int) -> None: ... +def CertOpenStore( + StoreProvider: int, + MsgAndCertEncodingType: int, + CryptProv: _win32typing.PyCRYPTPROV | None, + Flags: int, + Para: str | Sequence[int | _win32typing.PyHANDLE | str | None] | None, +) -> _win32typing.PyCERTSTORE | None: ... +def CertOpenSystemStore(SubsystemProtocol: str, Prov: _win32typing.PyCRYPTPROV | None = None) -> _win32typing.PyCERTSTORE: ... + +@overload +def CryptFindOIDInfo(KeyType: Literal[1], Key: bytes, GroupId: int = 0) -> _win32typing.OIDInfo: ... +@overload +def CryptFindOIDInfo(KeyType: Literal[2], Key: str, GroupId: int = 0) -> _win32typing.OIDInfo: ... +@overload +def CryptFindOIDInfo(KeyType: Literal[3], Key: int, GroupId: int = 0) -> _win32typing.OIDInfo: ... +@overload +def CryptFindOIDInfo(KeyType: Literal[4], Key: tuple[int, int], GroupId: int = 0) -> _win32typing.OIDInfo: ... + +def CertAlgIdToOID(AlgId: int) -> bytes | None: ... +def CertOIDToAlgId(ObjId: str) -> int: ... +def CryptGetKeyIdentifierProperty( + KeyIdentifier: ReadableBuffer, PropId: int = 2, Flags: int = 0, ComputerName: str | None = None +) -> _win32typing.ProveInfo: ... +def CryptEnumKeyIdentifierProperties( + KeyIdentifier: ReadableBuffer | None = None, PropId: int = 0, Flags: int = 0, ComputerName: str | None = None +) -> list[_win32typing.KeyIdentifier]: ... +def CryptEnumOIDInfo(GroupId: int = 0) -> list[_win32typing.OIDInfo]: ... +def CertAddSerializedElementToStore( + CertStore: _win32typing.PyCERTSTORE | None, + Element: ReadableBuffer, + AddDisposition: int, + ContextTypeFlags: int = 2, + Flags: int = 0, +) -> _win32typing.PyCERT_CONTEXT | _win32typing.PyCTL_CONTEXT | None: ... + +@overload +def CryptQueryObject( + ObjectType: Literal[1], + Object: ReadableBuffer, + ExpectedContentTypeFlags: int = 0x00003FFE, + ExpectedFormatTypeFlags: int = 0x0000000E, + Flags: int = 0, +) -> _win32typing.QueryObject: ... +@overload +def CryptQueryObject( + ObjectType: Literal[2], + Object: str, + ExpectedContentTypeFlags: int = 0x00003FFE, + ExpectedFormatTypeFlags: int = 0x0000000E, + Flags: int = 0, +) -> _win32typing.QueryObject: ... + +def CryptDecodeMessage( + EncodedBlob: ReadableBuffer, + DecryptPara: _win32typing.DecryptMessagePara, + VerifyPara: _win32typing.VerifyMessagePara | None = None, + MsgTypeFlags: int = -1, + SignerIndex: int = 0, + PrevInnerContentType: int = 0, + ReturnData: bool | Literal[0, 1] = True, +) -> _win32typing.DecodeMessage: ... +def CryptEncryptMessage( + EncryptPara: _win32typing.EncryptMessagePara, + RecipientCert: Iterable[_win32typing.PyCERT_CONTEXT] | None, + ToBeEncrypted: ReadableBuffer, +) -> bytes: ... +def CryptDecryptMessage( + DecryptPara: _win32typing.DecryptMessagePara, EncryptedBlob: ReadableBuffer +) -> tuple[bytes, _win32typing.PyCERT_CONTEXT]: ... +def CryptSignAndEncryptMessage( + SignPara: _win32typing.SignMessagePara, + EncryptPara: _win32typing.EncryptMessagePara, + RecipientCert: Iterable[_win32typing.PyCERT_CONTEXT] | None, + ToBeSignedAndEncrypted: ReadableBuffer, +) -> bytes: ... +def CryptVerifyMessageSignature( + SignedBlob: ReadableBuffer, + SignerIndex: int = 0, + VerifyPara: _win32typing.VerifyMessagePara | None = None, + ReturnData: bool | Literal[0, 1] = False, +) -> _win32typing.VerifyMessageSignature: ... +def CryptGetMessageCertificates( + SignedBlob: ReadableBuffer, + MsgAndCertEncodingType: int = ..., + CryptProv: _win32typing.PyCRYPTPROV | None = None, + Flags: int = 0, +) -> _win32typing.PyCERTSTORE: ... +def CryptGetMessageSignerCount(SignedBlob: ReadableBuffer, MsgEncodingType: int = ...) -> int: ... +def CryptSignMessage( + SignPara: _win32typing.SignMessagePara, ToBeSigned: Iterable[Incomplete], DetachedSignature: bool | Literal[0, 1] = False +) -> bytes: ... +def CryptVerifyDetachedMessageSignature( + SignerIndex: int, + DetachedSignBlob: ReadableBuffer, + ToBeSigned: Iterable[Incomplete], + VerifyPara: _win32typing.VerifyMessagePara | None = None, +) -> _win32typing.PyCERT_CONTEXT: ... +def CryptDecryptAndVerifyMessageSignature( + EncryptedBlob: ReadableBuffer, + DecryptPara: _win32typing.DecryptMessagePara, + VerifyPara: _win32typing.VerifyMessagePara | None = None, + SignerIndex: int = 0, +) -> _win32typing.DecryptAndVerifyMessageSignature: ... +def CryptEncodeObjectEx( + StructType: int | bytes, + StructInfo: Iterable[int | bytes] | _win32typing.CryptBitBlob, + Flags: int = 0, + CertEncodingType: int = ..., + EncodePara: None = None, +) -> bytes: ... +def CryptDecodeObjectEx( + StructType: int | bytes, Encoded: ReadableBuffer, Flags: int = 0, CertEncodingType: int = ..., DecodePara: None = None +): ... +def CertNameToStr(Name: ReadableBuffer, StrType: int = 1, CertEncodingType: int = 0x00000001) -> str: ... +def CryptFormatObject( + StructType: int | bytes, + Encoded: ReadableBuffer, + FormatStrType: int = 0, + CertEncodingType: int = 0x00000001, + FormatType: int = 0, + FormatStruct: None = None, +) -> str: ... +def PFXImportCertStore(PFX: ReadableBuffer, Password: str | None, Flags: int) -> _win32typing.PyCERTSTORE: ... +def PFXVerifyPassword(PFX: ReadableBuffer, Password: str | None, Flags: int) -> bool: ... +def PFXIsPFXBlob(PFX: ReadableBuffer) -> bool: ... +def CryptBinaryToString(Binary: ReadableBuffer, Flags: int) -> str: ... +def CryptStringToBinary(String: str, Flags: int) -> tuple[bytes, int, int]: ... diff --git a/stubs/pywin32/win32/win32event.pyi b/stubs/pywin32/win32/win32event.pyi new file mode 100644 index 000000000000..a79bb40f86b4 --- /dev/null +++ b/stubs/pywin32/win32/win32event.pyi @@ -0,0 +1,69 @@ +from collections.abc import Iterable + +import _win32typing +from win32.lib.pywintypes import error as error + +def CancelWaitableTimer() -> None: ... +def CreateEvent( + EventAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, + bManualReset: int | bool, + bInitialState: int | bool, + Name: str | None, + /, +) -> int: ... +def CreateMutex(MutexAttributes: _win32typing.PySECURITY_ATTRIBUTES, InitialOwner, Name: str, /) -> _win32typing.PyHANDLE: ... +def CreateSemaphore( + SemaphoreAttributes: _win32typing.PySECURITY_ATTRIBUTES, InitialCount, MaximumCount, SemaphoreName, / +) -> int: ... +def CreateWaitableTimer(TimerAttributes: _win32typing.PySECURITY_ATTRIBUTES, ManualReset, TimerName, /) -> int: ... +def CreateWaitableTimerEx( + lpTimerAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, lpTimerName: str | None, dwFlags: int, dwDesiredAccess: int, / +) -> _win32typing.PyHANDLE: ... +def MsgWaitForMultipleObjects(handlelist: Iterable[int], bWaitAll: int, milliseconds: int, wakeMask: int, /) -> int: ... +def MsgWaitForMultipleObjectsEx(handlelist: list[int], milliseconds, wakeMask, waitFlags, /): ... +def OpenEvent(desiredAccess, bInheritHandle, name: str, /) -> int: ... +def OpenMutex(desiredAccess, bInheritHandle, name: str, /) -> int: ... +def OpenSemaphore(desiredAccess, bInheritHandle, name: str, /) -> int: ... +def OpenWaitableTimer(desiredAccess, bInheritHandle, timerName, /) -> int: ... +def PulseEvent(hEvent: int, /) -> None: ... +def ReleaseMutex(hEvent: int, /) -> None: ... +def ReleaseSemaphore(hEvent: int, lReleaseCount, /): ... +def ResetEvent(hEvent: int, /) -> None: ... +def SetEvent(hEvent: int, /) -> None: ... +def SetWaitableTimer(handle: int, dueTime, period, func, param, resume_state, /) -> None: ... +def WaitForMultipleObjects(handlelist: list[int], bWaitAll, milliseconds, /): ... +def WaitForMultipleObjectsEx(handlelist: list[int], bWaitAll, milliseconds, bAlertable, /): ... +def WaitForSingleObject(hHandle: int, milliseconds: int, /) -> int: ... +def WaitForSingleObjectEx(hHandle: int, milliseconds, bAlertable, /): ... +def WaitForInputIdle(hProcess: int, milliseconds, /): ... +def SignalObjectAndWait(hSignal, hWaitOn, milliseconds, bAlertable, /): ... + +CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: int +CREATE_WAITABLE_TIMER_MANUAL_RESET: int +EVENT_ALL_ACCESS: int +EVENT_MODIFY_STATE: int +INFINITE: int +MAXIMUM_WAIT_OBJECTS: int +QS_ALLEVENTS: int +QS_ALLINPUT: int +QS_HOTKEY: int +QS_INPUT: int +QS_KEY: int +QS_MOUSE: int +QS_MOUSEBUTTON: int +QS_MOUSEMOVE: int +QS_PAINT: int +QS_POSTMESSAGE: int +QS_SENDMESSAGE: int +QS_TIMER: int +SYNCHRONIZE: int +TIMER_ALL_ACCESS: int +TIMER_MODIFY_STATE: int +TIMER_QUERY_STATE: int +WAIT_ABANDONED: int +WAIT_ABANDONED_0: int +WAIT_FAILED: int +WAIT_IO_COMPLETION: int +WAIT_OBJECT_0: int +WAIT_TIMEOUT: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32evtlog.pyi b/stubs/pywin32/win32/win32evtlog.pyi new file mode 100644 index 000000000000..8b3ce18ddb22 --- /dev/null +++ b/stubs/pywin32/win32/win32evtlog.pyi @@ -0,0 +1,272 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import _win32typing +from win32.lib.pywintypes import error as error + +def ReadEventLog( + Handle: _win32typing.PyEVTLOG_HANDLE, Flags: int, Offset: int, Size=..., / +) -> list[_win32typing.PyEventLogRecord]: ... +def ClearEventLog(handle: _win32typing.PyEVTLOG_HANDLE, eventLogName: str, /) -> None: ... +def BackupEventLog(handle, eventLogName: str, /) -> None: ... +def CloseEventLog(handle: _win32typing.PyEVTLOG_HANDLE, /) -> None: ... +def DeregisterEventSource(handle, /) -> None: ... +def NotifyChangeEventLog(handle, handle1, /) -> None: ... +def GetNumberOfEventLogRecords(handle: _win32typing.PyEVTLOG_HANDLE, /) -> int: ... +def GetOldestEventLogRecord(): ... +def OpenEventLog(serverName: str | None, sourceName: str, /) -> _win32typing.PyEVTLOG_HANDLE: ... +def RegisterEventSource(serverName: str | None, sourceName: str, /): ... +def OpenBackupEventLog(serverName: str, fileName: str, /) -> _win32typing.PyEVTLOG_HANDLE: ... +def ReportEvent( + EventLog: int, + Type: int, + Category: int, + EventID: int, + UserSid: _win32typing.PySID | None, + Strings: Iterable[str] | None, + RawData: bytes | None, + /, +) -> None: ... +def EvtOpenChannelEnum(Session: _win32typing.PyEVT_HANDLE | None = ..., Flags: int = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtFormatMessage(Metadata, Event, Flags, ResourceId=...): ... +def EvtNextChannelPath(ChannelEnum: _win32typing.PyEVT_HANDLE): ... +def EvtOpenLog(Path, Flags, Session: _win32typing.PyEVT_HANDLE | None = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtClearLog( + ChannelPath, TargetFilePath: Incomplete | None = ..., Session: _win32typing.PyEVT_HANDLE | None = ..., Flags: int = ... +) -> None: ... +def EvtExportLog( + Path, TargetFilePath, Flags, Query: Incomplete | None = ..., Session: _win32typing.PyEVT_HANDLE | None = ... +) -> None: ... +def EvtArchiveExportedLog(LogFilePath, Locale, Session: _win32typing.PyEVT_HANDLE | None = ..., Flags=...) -> None: ... +def EvtGetExtendedStatus(): ... +def EvtQuery( + Path: str, Flags: int, Query: str | None = ..., Session: _win32typing.PyEVT_HANDLE | None = ... +) -> _win32typing.PyEVT_HANDLE: ... +def EvtNext( + ResultSet: _win32typing.PyEVT_HANDLE, Count: int, Timeout: int = ..., Flags: int = ... +) -> tuple[_win32typing.PyEVT_HANDLE, ...]: ... +def EvtSeek( + ResultSet: _win32typing.PyEVT_HANDLE, Position, Flags, Bookmark: _win32typing.PyEVT_HANDLE | None = ..., Timeout: int = ... +) -> None: ... +def EvtCreateRenderContext(Flags): ... +def EvtRender(Event: _win32typing.PyEVT_HANDLE, Flags: int, Context=...): ... +def EvtSubscribe( + ChannelPath, + Flags, + SignalEvent: Incomplete | None = ..., + Callback: Incomplete | None = ..., + Context: Incomplete | None = ..., + Query: Incomplete | None = ..., + Session: _win32typing.PyEVT_HANDLE | None = ..., + Bookmark: _win32typing.PyEVT_HANDLE | None = ..., +) -> _win32typing.PyEVT_HANDLE: ... +def EvtCreateBookmark(BookmarkXML: Incomplete | None = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtUpdateBookmark(Bookmark: _win32typing.PyEVT_HANDLE, Event: _win32typing.PyEVT_HANDLE) -> _win32typing.PyEVT_HANDLE: ... +def EvtGetChannelConfigProperty( + ChannelConfig: _win32typing.PyEVT_HANDLE, PropertyId, Flags=... +) -> tuple[Incomplete, Incomplete]: ... +def EvtOpenChannelConfig( + ChannelPath, Session: _win32typing.PyEVT_HANDLE | None = ..., Flags=... +) -> _win32typing.PyEVT_HANDLE: ... +def EvtOpenSession( + Login: _win32typing.PyEVT_RPC_LOGIN, LoginClass, Timeout: int = ..., Flags=... +) -> _win32typing.PyEVT_HANDLE: ... +def EvtOpenPublisherEnum(Session: _win32typing.PyEVT_HANDLE | None = ..., Flags: int = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtNextPublisherId(PublisherEnum: _win32typing.PyEVT_HANDLE): ... +def EvtOpenPublisherMetadata( + PublisherIdentity: str, + Session: _win32typing.PyEVT_HANDLE | None = ..., + LogFilePath: Incomplete | None = ..., + Locale: int = ..., + Flags: int = ..., +) -> _win32typing.PyEVT_HANDLE: ... +def EvtGetPublisherMetadataProperty( + PublisherMetadata: _win32typing.PyEVT_HANDLE, PropertyId, Flags=... +) -> tuple[Incomplete, Incomplete]: ... +def EvtOpenEventMetadataEnum(PublisherMetadata: _win32typing.PyEVT_HANDLE, Flags=...) -> _win32typing.PyEVT_HANDLE: ... +def EvtNextEventMetadata(EventMetadataEnum: _win32typing.PyEVT_HANDLE, Flags=...) -> _win32typing.PyEVT_HANDLE: ... +def EvtGetEventMetadataProperty( + EventMetadata: _win32typing.PyEVT_HANDLE, PropertyId, Flags=... +) -> tuple[Incomplete, Incomplete]: ... +def EvtGetLogInfo(Log: _win32typing.PyEVT_HANDLE, PropertyId) -> tuple[Incomplete, Incomplete]: ... +def EvtGetEventInfo(Event: _win32typing.PyEVT_HANDLE, PropertyId) -> tuple[Incomplete, Incomplete]: ... +def EvtGetObjectArraySize(ObjectArray: _win32typing.PyEVT_HANDLE): ... +def EvtGetObjectArrayProperty( + ObjectArray: _win32typing.PyEVT_HANDLE, PropertyId, ArrayIndex, Flags=... +) -> tuple[Incomplete, Incomplete]: ... + +EVENTLOG_AUDIT_FAILURE: int +EVENTLOG_AUDIT_SUCCESS: int +EVENTLOG_BACKWARDS_READ: int +EVENTLOG_END_ALL_PAIRED_EVENTS: int +EVENTLOG_END_PAIRED_EVENT: int +EVENTLOG_ERROR_TYPE: int +EVENTLOG_FORWARDS_READ: int +EVENTLOG_INFORMATION_TYPE: int +EVENTLOG_PAIRED_EVENT_ACTIVE: int +EVENTLOG_PAIRED_EVENT_INACTIVE: int +EVENTLOG_SEEK_READ: int +EVENTLOG_SEQUENTIAL_READ: int +EVENTLOG_START_PAIRED_EVENT: int +EVENTLOG_SUCCESS: int +EVENTLOG_WARNING_TYPE: int +EventMetadataEventChannel: int +EventMetadataEventID: int +EventMetadataEventKeyword: int +EventMetadataEventLevel: int +EventMetadataEventMessageID: int +EventMetadataEventOpcode: int +EventMetadataEventTask: int +EventMetadataEventTemplate: int +EventMetadataEventVersion: int +EvtChannelConfigAccess: int +EvtChannelConfigClassicEventlog: int +EvtChannelConfigEnabled: int +EvtChannelConfigIsolation: int +EvtChannelConfigOwningPublisher: int +EvtChannelConfigPropertyIdEND: int +EvtChannelConfigType: int +EvtChannelLoggingConfigAutoBackup: int +EvtChannelLoggingConfigLogFilePath: int +EvtChannelLoggingConfigMaxSize: int +EvtChannelLoggingConfigRetention: int +EvtChannelPublishingConfigBufferSize: int +EvtChannelPublishingConfigClockType: int +EvtChannelPublishingConfigControlGuid: int +EvtChannelPublishingConfigKeywords: int +EvtChannelPublishingConfigLatency: int +EvtChannelPublishingConfigLevel: int +EvtChannelPublishingConfigMaxBuffers: int +EvtChannelPublishingConfigMinBuffers: int +EvtChannelPublishingConfigSidType: int +EvtEventMetadataPropertyIdEND: int +EvtEventPath: int +EvtEventPropertyIdEND: int +EvtEventQueryIDs: int +EvtExportLogChannelPath: int +EvtExportLogFilePath: int +EvtExportLogTolerateQueryErrors: int +EvtLogAttributes: int +EvtLogCreationTime: int +EvtLogFileSize: int +EvtLogFull: int +EvtLogLastAccessTime: int +EvtLogLastWriteTime: int +EvtLogNumberOfLogRecords: int +EvtLogOldestRecordNumber: int +EvtOpenChannelPath: int +EvtOpenFilePath: int +EvtPublisherMetadataChannelReferenceFlags: int +EvtPublisherMetadataChannelReferenceID: int +EvtPublisherMetadataChannelReferenceIndex: int +EvtPublisherMetadataChannelReferenceMessageID: int +EvtPublisherMetadataChannelReferencePath: int +EvtPublisherMetadataChannelReferences: int +EvtPublisherMetadataHelpLink: int +EvtPublisherMetadataKeywordMessageID: int +EvtPublisherMetadataKeywordName: int +EvtPublisherMetadataKeywords: int +EvtPublisherMetadataKeywordValue: int +EvtPublisherMetadataLevelMessageID: int +EvtPublisherMetadataLevelName: int +EvtPublisherMetadataLevels: int +EvtPublisherMetadataLevelValue: int +EvtPublisherMetadataMessageFilePath: int +EvtPublisherMetadataOpcodeMessageID: int +EvtPublisherMetadataOpcodeName: int +EvtPublisherMetadataOpcodes: int +EvtPublisherMetadataOpcodeValue: int +EvtPublisherMetadataParameterFilePath: int +EvtPublisherMetadataPropertyIdEND: int +EvtPublisherMetadataPublisherGuid: int +EvtPublisherMetadataPublisherMessageID: int +EvtPublisherMetadataResourceFilePath: int +EvtPublisherMetadataTaskEventGuid: int +EvtPublisherMetadataTaskMessageID: int +EvtPublisherMetadataTaskName: int +EvtPublisherMetadataTasks: int +EvtPublisherMetadataTaskValue: int +EvtQueryChannelPath: int +EvtQueryFilePath: int +EvtQueryForwardDirection: int +EvtQueryReverseDirection: int +EvtQueryTolerateQueryErrors: int +EvtRenderBookmark: int +EvtRenderEventValues: int +EvtRenderEventXml: int +EvtRpcLogin: int +EvtRpcLoginAuthDefault: int +EvtRpcLoginAuthKerberos: int +EvtRpcLoginAuthNegotiate: int +EvtRpcLoginAuthNTLM: int +EvtSeekOriginMask: int +EvtSeekRelativeToBookmark: int +EvtSeekRelativeToCurrent: int +EvtSeekRelativeToFirst: int +EvtSeekRelativeToLast: int +EvtSeekStrict: int +EvtSubscribeActionDeliver: int +EvtSubscribeActionError: int +EvtSubscribeOriginMask: int +EvtSubscribeStartAfterBookmark: int +EvtSubscribeStartAtOldestRecord: int +EvtSubscribeStrict: int +EvtSubscribeToFutureEvents: int +EvtSubscribeTolerateQueryErrors: int +EvtVarTypeAnsiString: int +EvtVarTypeBinary: int +EvtVarTypeBoolean: int +EvtVarTypeByte: int +EvtVarTypeDouble: int +EvtVarTypeEvtHandle: int +EvtVarTypeEvtXml: int +EvtVarTypeFileTime: int +EvtVarTypeGuid: int +EvtVarTypeHexInt32: int +EvtVarTypeHexInt64: int +EvtVarTypeInt16: int +EvtVarTypeInt32: int +EvtVarTypeInt64: int +EvtVarTypeNull: int +EvtVarTypeSByte: int +EvtVarTypeSid: int +EvtVarTypeSingle: int +EvtVarTypeSizeT: int +EvtVarTypeString: int +EvtVarTypeSysTime: int +EvtVarTypeUInt16: int +EvtVarTypeUInt32: int +EvtVarTypeUInt64: int +EvtChannelPublisherList: int +EvtFormatMessageChannel: int +EvtFormatMessageEvent: int +EvtFormatMessageId: int +EvtFormatMessageKeyword: int +EvtFormatMessageLevel: int +EvtFormatMessageOpcode: int +EvtFormatMessageProvider: int +EvtFormatMessageTask: int +EvtFormatMessageXml: int +EvtRenderContextSystem: int +EvtRenderContextUser: int +EvtRenderContextValues: int +EvtSystemActivityID: int +EvtSystemChannel: int +EvtSystemComputer: int +EvtSystemEventID: int +EvtSystemEventRecordId: int +EvtSystemKeywords: int +EvtSystemLevel: int +EvtSystemOpcode: int +EvtSystemProcessID: int +EvtSystemPropertyIdEND: int +EvtSystemProviderGuid: int +EvtSystemProviderName: int +EvtSystemQualifiers: int +EvtSystemRelatedActivityID: int +EvtSystemTask: int +EvtSystemThreadID: int +EvtSystemTimeCreated: int +EvtSystemUserID: int +EvtSystemVersion: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32file.pyi b/stubs/pywin32/win32/win32file.pyi new file mode 100644 index 000000000000..4cb0def25531 --- /dev/null +++ b/stubs/pywin32/win32/win32file.pyi @@ -0,0 +1,493 @@ +from _typeshed import Incomplete, WriteableBuffer +from socket import socket +from typing import TypeVar, overload +from typing_extensions import deprecated + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +_BufferT = TypeVar("_BufferT", bound=_win32typing.PyOVERLAPPEDReadBuffer | WriteableBuffer) + +def AreFileApisANSI(): ... +def CancelIo(handle: int, /) -> None: ... +def CopyFile(_from: str, to: str, bFailIfExists, /) -> None: ... +def CopyFileW(_from: str, to: str, bFailIfExists, /) -> None: ... +def CreateDirectory(name: str, sa: _win32typing.PySECURITY_ATTRIBUTES, /) -> None: ... +def CreateDirectoryW(name: str, sa: _win32typing.PySECURITY_ATTRIBUTES, /) -> None: ... +def CreateDirectoryEx(templateName: str, newDirectory: str, sa: _win32typing.PySECURITY_ATTRIBUTES, /) -> None: ... +def CreateFile( + fileName: str, + desiredAccess: int, + shareMode: int, + attributes: _win32typing.PySECURITY_ATTRIBUTES | None, + CreationDisposition: int, + flagsAndAttributes: int, + hTemplateFile: int | None, + /, +) -> _win32typing.PyHANDLE: ... +def CreateIoCompletionPort(handle: int, existing: int, completionKey, numThreads, /) -> int: ... +def CreateMailslot(Name, MaxMessageSize, ReadTimeout, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, /) -> int: ... +def GetMailslotInfo(Mailslot: int, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def SetMailslotInfo(Mailslot: int, ReadTimeout, /) -> None: ... +def DefineDosDevice(flags, deviceName: str, targetPath: str, /) -> None: ... +def DefineDosDeviceW(flags, deviceName: str, targetPath: str, /) -> None: ... +def DeleteFile(fileName: str, /) -> None: ... +def DeviceIoControl(Device: int, IoControlCode, InBuffer, OutBuffer, Overlapped: _win32typing.PyOVERLAPPED | None = ...): ... +def FindClose(hFindFile, /) -> None: ... +def FindCloseChangeNotification(hChangeHandle, /) -> None: ... +def FindFirstChangeNotification(pathName: str, bWatchSubtree, notifyFilter, /): ... +def FindNextChangeNotification(hChangeHandle, /): ... +def FlushFileBuffers(hFile: int, /) -> None: ... +def GetBinaryType(appName: str, /) -> int: ... +def GetDiskFreeSpace(rootPathName: str, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def GetDiskFreeSpaceEx(rootPathName: str, /) -> tuple[int, int, int]: ... +def GetDriveType(rootPathName: str, /): ... +def GetDriveTypeW(rootPathName: str, /): ... +def GetFileAttributes(fileName: str, /): ... +def GetFileAttributesW(fileName: str, /): ... +def GetFileTime( + handle: int, creationTime: TimeType, accessTime: TimeType, writeTime: TimeType, / +) -> tuple[TimeType, TimeType, TimeType]: ... +def SetFileTime( + File: int, + CreationTime: TimeType | None = ..., + LastAccessTime: TimeType | None = ..., + LastWriteTime: TimeType | None = ..., + UTCTimes: bool = ..., +) -> None: ... +def GetFileInformationByHandle(handle: int, /): ... +def GetCompressedFileSize(): ... +def GetFileSize(): ... +def AllocateReadBuffer(bufSize: int, /) -> _win32typing.PyOVERLAPPEDReadBuffer: ... + +@overload +def ReadFile(hFile: int, bufSize: int, overlapped: None = None, /) -> tuple[int, bytes]: ... +@overload +def ReadFile( + hFile: int, bufSize: int, overlapped: _win32typing.PyOVERLAPPED, / +) -> tuple[int, _win32typing.PyOVERLAPPEDReadBuffer]: ... +@overload +def ReadFile( + hFile: int, buffer: _win32typing.PyOVERLAPPEDReadBuffer | WriteableBuffer, overlapped: None = None, / +) -> tuple[int, bytes]: ... +@overload +def ReadFile(hFile: int, buffer: _BufferT, overlapped: _win32typing.PyOVERLAPPED, /) -> tuple[int, _BufferT]: ... + +def WriteFile( + hFile: int, data: str | bytes | _win32typing.PyOVERLAPPEDReadBuffer, ol: _win32typing.PyOVERLAPPED | None = ..., / +) -> tuple[int, int]: ... +def CloseHandle(handle: int, /) -> None: ... +def LockFileEx(hFile: int, _int, _int1, _int2, ol: _win32typing.PyOVERLAPPED | None = ..., /) -> None: ... +def UnlockFileEx(hFile: int, _int, _int1, ol: _win32typing.PyOVERLAPPED | None = ..., /) -> None: ... +def GetQueuedCompletionStatus(hPort: int, timeOut, /) -> tuple[Incomplete, Incomplete, Incomplete, _win32typing.PyOVERLAPPED]: ... +def PostQueuedCompletionStatus( + handle: int, numberOfbytes: int = ..., completionKey: int = ..., overlapped: _win32typing.PyOVERLAPPED | None = ..., / +): ... +def GetFileType(hFile: int, /): ... +def GetLogicalDrives(): ... +def GetOverlappedResult(hFile: int, overlapped: _win32typing.PyOVERLAPPED, bWait: int | bool, /) -> int: ... +def LockFile(hFile: int, offsetLow, offsetHigh, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh, /) -> None: ... +def MoveFile(existingFileName: str, newFileName: str, /) -> None: ... +def MoveFileW(existingFileName: str, newFileName: str, /) -> None: ... +def MoveFileEx(existingFileName: str, newFileName: str, flags, /) -> None: ... +def MoveFileExW(existingFileName: str, newFileName: str, flags, /) -> None: ... +def QueryDosDevice(DeviceName: str, /) -> str: ... +def ReadDirectoryChangesW( + handle: int, size, bWatchSubtree, dwNotifyFilter, overlapped: _win32typing.PyOVERLAPPED | None = ..., / +) -> None: ... +def FILE_NOTIFY_INFORMATION(buffer: str, size, /) -> tuple[tuple[Incomplete, Incomplete], ...]: ... +def SetCurrentDirectory(lpPathName: str, /) -> None: ... +def SetEndOfFile(hFile: int, /) -> None: ... +def SetFileApisToANSI() -> None: ... +def SetFileApisToOEM() -> None: ... +def SetFileAttributes(filename: str, newAttributes: int, /) -> None: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def SetFilePointer(handle: int, offset: tuple[int, int], moveMethod, /) -> None: ... +@overload +def SetFilePointer(handle: int, offset: int, moveMethod, /) -> None: ... + +def SetVolumeLabel(rootPathName: str, volumeName: str, /) -> None: ... +def UnlockFile(hFile: int, offsetLow, offsetHigh, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh, /) -> None: ... +def TransmitFile( + Socket, + File: int, + NumberOfBytesToWrite, + NumberOfBytesPerSend, + Overlapped: _win32typing.PyOVERLAPPED, + Flags, + Head: Incomplete | None = ..., + Tail: Incomplete | None = ..., +) -> None: ... +def ConnectEx( + s, name, Overlapped: _win32typing.PyOVERLAPPED, SendBuffer: Incomplete | None = ... +) -> tuple[Incomplete, Incomplete]: ... +def AcceptEx(slistening, sAccepting, buffer, ol: _win32typing.PyOVERLAPPED, /) -> None: ... +def CalculateSocketEndPointSize(socket, /): ... +def GetAcceptExSockaddrs( + sAccepting, buffer: _win32typing.PyOVERLAPPEDReadBuffer, / +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def WSAEventSelect(socket: socket, hEvent: int, networkEvents: int, /) -> None: ... +def WSAEnumNetworkEvents(s: socket, hEvent: int, /) -> dict[int, int]: ... +def WSAAsyncSelect(socket, hwnd: int, _int, networkEvents, /) -> None: ... +def WSASend(s, buffer: str, ol: _win32typing.PyOVERLAPPED, dwFlags, /) -> tuple[Incomplete, Incomplete]: ... +def WSARecv(s, buffer, ol: _win32typing.PyOVERLAPPED, dwFlags, /) -> tuple[Incomplete, Incomplete]: ... +def BuildCommDCB(_def: str, dcb: _win32typing.PyDCB, /) -> _win32typing.PyDCB: ... +def ClearCommError(handle: int, /) -> tuple[Incomplete, _win32typing.PyCOMSTAT]: ... +def EscapeCommFunction(handle: int, /) -> None: ... +def GetCommState(handle: int, /) -> _win32typing.PyDCB: ... +def SetCommState(handle: int, dcb: _win32typing.PyDCB, /) -> None: ... +def ClearCommBreak(handle: int, /) -> None: ... +def GetCommMask(handle: int, /): ... +def SetCommMask(handle: int, val, /): ... +def GetCommModemStatus(handle: int, /): ... +def GetCommTimeouts(handle: int, /): ... +def SetCommTimeouts(handle: int, val, /): ... +def PurgeComm(handle: int, action, /) -> None: ... +def SetCommBreak(handle: int, /) -> None: ... +def SetupComm(handle: int, dwInQueue, dwOutQueue, /) -> None: ... +def TransmitCommChar(handle: int, cChar, /) -> None: ... +def WaitCommEvent(handle: int, overlapped: _win32typing.PyOVERLAPPED, /) -> None: ... +def SetVolumeMountPoint(VolumeMountPoint: str, VolumeName: str) -> str: ... +def DeleteVolumeMountPoint(VolumeMountPoint: str) -> None: ... +def GetVolumeNameForVolumeMountPoint(VolumeMountPoint: str) -> str: ... +def GetVolumePathName(FileName: str, BufferLength: int = ...) -> str: ... +def GetVolumePathNamesForVolumeName(VolumeName: str) -> list[Incomplete]: ... +def CreateHardLink( + FileName: str, + ExistingFileName: str, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + Transaction: int | None = ..., +) -> None: ... +def CreateSymbolicLink(SymlinkFileName: str, TargetFileName: str, Flags: int = ..., Transaction: int | None = ...) -> None: ... +def EncryptFile(filename: str, /) -> None: ... +def DecryptFile(filename: str, /) -> None: ... +def EncryptionDisable(DirName: str, Disable, /) -> None: ... +def FileEncryptionStatus(FileName: str, /): ... +def QueryUsersOnEncryptedFile(FileName: str, /) -> tuple[_win32typing.PySID, str, Incomplete]: ... +def QueryRecoveryAgentsOnEncryptedFile(FileName: str, /) -> tuple[_win32typing.PySID, str, Incomplete]: ... +def RemoveUsersFromEncryptedFile(FileName: str, pHashes: tuple[tuple[_win32typing.PySID, str, Incomplete], ...], /) -> None: ... +def AddUsersToEncryptedFile(FileName: str, pUsers: tuple[tuple[_win32typing.PySID, str, Incomplete], ...], /) -> None: ... +def DuplicateEncryptionInfoFile( + SrcFileName: str, + DstFileName: str, + CreationDisposition, + Attributes, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> None: ... +def BackupRead( + hFile: int, NumberOfBytesToRead, Buffer, bAbort, bProcessSecurity, lpContext, / +) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def BackupSeek(hFile: int, NumberOfBytesToSeek: tuple[int, int], lpContext, /): ... +@overload +def BackupSeek(hFile: int, NumberOfBytesToSeek: int, lpContext, /): ... + +def BackupWrite( + hFile: int, NumberOfBytesToWrite, Buffer: str, bAbort, bProcessSecurity, lpContext, / +) -> tuple[Incomplete, Incomplete]: ... +def SetFileShortName(hFile: int, ShortName, /) -> None: ... +def CopyFileEx( + ExistingFileName, + NewFileName, + ProgressRoutine: _win32typing.CopyProgressRoutine | None = ..., + Data: Incomplete | None = ..., + Cancel: bool = ..., + CopyFlags: int = ..., + Transaction: int | None = ..., +) -> None: ... +def MoveFileWithProgress( + ExistingFileName, + NewFileName, + ProgressRoutine: _win32typing.CopyProgressRoutine | None = ..., + Data: Incomplete | None = ..., + Flags: int = ..., + Transaction: int | None = ..., +) -> None: ... +def ReplaceFile( + ReplacedFileName, + ReplacementFileName, + BackupFileName: Incomplete | None = ..., + ReplaceFlags: int = ..., + Exclude: Incomplete | None = ..., + Reserved: Incomplete | None = ..., + /, +) -> None: ... +def OpenEncryptedFileRaw(FileName, Flags, /): ... +def ReadEncryptedFileRaw(ExportCallback, CallbackContext, Context, /) -> None: ... +def WriteEncryptedFileRaw(ImportCallback, CallbackContext, Context, /) -> None: ... +def CloseEncryptedFileRaw(Context, /) -> None: ... +def CreateFileW( + FileName: str, + DesiredAccess, + ShareMode, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, + CreationDisposition, + FlagsAndAttributes, + TemplateFile: int | None = ..., + Transaction: int | None = ..., + MiniVersion: Incomplete | None = ..., + ExtendedParameter: Incomplete | None = ..., +) -> int: ... +def DeleteFileW(FileName: str, Transaction: int | None = ...) -> None: ... +def GetFileAttributesEx(FileName: str, InfoLevelId=..., Transaction: int | None = ...): ... +def SetFileAttributesW(FileName, FileAttributes, Transaction: int | None = ...) -> None: ... +def CreateDirectoryExW( + TemplateDirectory: str, + NewDirectory: str, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + Transaction: int | None = ..., +) -> None: ... +def RemoveDirectory(PathName: str, Transaction: int | None = ...) -> None: ... +def FindFilesW( + FileName: str, Transaction: int | None = ... +) -> list[tuple[int, Incomplete, Incomplete, Incomplete, int, int, int, int, str, str]]: ... +def FindFilesIterator(FileName: str, Transaction: int | None = ...): ... +def FindStreams(FileName: str, Transaction: int | None = ...) -> list[tuple[Incomplete, str]]: ... +def FindFileNames(FileName: str, Transaction: int | None = ...) -> list[str]: ... +def GetFinalPathNameByHandle(File: int, Flags) -> str: ... +def SfcGetNextProtectedFile() -> list[Incomplete]: ... +def SfcIsFileProtected(ProtFileName: str, /): ... +def GetLongPathName(ShortPath: str, Transaction: int | None = ...) -> str: ... +def GetFullPathName(FileName, Transaction: int | None = ...): ... +def Wow64DisableWow64FsRedirection(): ... +def Wow64RevertWow64FsRedirection(OldValue, /) -> None: ... +def GetFileInformationByHandleEx(File: int, FileInformationClass): ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def SetFileInformationByHandle(File: int, FileInformationClass, Information: tuple[int, int]) -> None: ... +@overload +def SetFileInformationByHandle(File: int, FileInformationClass, Information) -> None: ... + +def ReOpenFile(OriginalFile: int, DesiredAccess, ShareMode, Flags) -> int: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def OpenFileById( + File: int, + FileId: tuple[int, int], + DesiredAccess, + ShareMode, + Flags, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> int: ... +@overload +def OpenFileById( + File: int, + FileId: _win32typing.PyIID | int, + DesiredAccess, + ShareMode, + Flags, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> int: ... + +def DCB() -> _win32typing.PyDCB: ... +def GetFileAttributesExW(FileName: str, InfoLevelId: int = ..., Transaction: int | None = None): ... +def OVERLAPPED() -> _win32typing.PyOVERLAPPED: ... + +CALLBACK_CHUNK_FINISHED: int +CALLBACK_STREAM_SWITCH: int +CBR_110: int +CBR_115200: int +CBR_1200: int +CBR_128000: int +CBR_14400: int +CBR_19200: int +CBR_2400: int +CBR_256000: int +CBR_300: int +CBR_38400: int +CBR_4800: int +CBR_56000: int +CBR_57600: int +CBR_600: int +CBR_9600: int +CLRBREAK: int +CLRDTR: int +CLRRTS: int +COPY_FILE_ALLOW_DECRYPTED_DESTINATION: int +COPY_FILE_FAIL_IF_EXISTS: int +COPY_FILE_OPEN_SOURCE_FOR_WRITE: int +COPY_FILE_RESTARTABLE: int +CREATE_ALWAYS: int +CREATE_FOR_DIR: int +CREATE_FOR_IMPORT: int +CREATE_NEW: int +DRIVE_CDROM: int +DRIVE_FIXED: int +DRIVE_NO_ROOT_DIR: int +DRIVE_RAMDISK: int +DRIVE_REMOTE: int +DRIVE_REMOVABLE: int +DRIVE_UNKNOWN: int +DTR_CONTROL_DISABLE: int +DTR_CONTROL_ENABLE: int +DTR_CONTROL_HANDSHAKE: int +EV_BREAK: int +EV_CTS: int +EV_DSR: int +EV_ERR: int +EV_RING: int +EV_RLSD: int +EV_RXCHAR: int +EV_RXFLAG: int +EV_TXEMPTY: int +EVENPARITY: int +FD_ACCEPT: int +FD_CLOSE: int +FD_CONNECT: int +FD_GROUP_QOS: int +FD_OOB: int +FD_QOS: int +FD_READ: int +FD_ROUTING_INTERFACE_CHANGE: int +FD_WRITE: int +FILE_ALL_ACCESS: int +FILE_ATTRIBUTE_ARCHIVE: int +FILE_ATTRIBUTE_COMPRESSED: int +FILE_ATTRIBUTE_DIRECTORY: int +FILE_ATTRIBUTE_HIDDEN: int +FILE_ATTRIBUTE_NORMAL: int +FILE_ATTRIBUTE_OFFLINE: int +FILE_ATTRIBUTE_READONLY: int +FILE_ATTRIBUTE_SYSTEM: int +FILE_ATTRIBUTE_TEMPORARY: int +FILE_BEGIN: int +FILE_CURRENT: int +FILE_ENCRYPTABLE: int +FILE_END: int +FILE_FLAG_BACKUP_SEMANTICS: int +FILE_FLAG_DELETE_ON_CLOSE: int +FILE_FLAG_NO_BUFFERING: int +FILE_FLAG_OPEN_REPARSE_POINT: int +FILE_FLAG_OVERLAPPED: int +FILE_FLAG_POSIX_SEMANTICS: int +FILE_FLAG_RANDOM_ACCESS: int +FILE_FLAG_SEQUENTIAL_SCAN: int +FILE_FLAG_WRITE_THROUGH: int +FILE_GENERIC_READ: int +FILE_GENERIC_WRITE: int +FILE_IS_ENCRYPTED: int +FILE_READ_ONLY: int +FILE_ROOT_DIR: int +FILE_SHARE_DELETE: int +FILE_SHARE_READ: int +FILE_SHARE_WRITE: int +FILE_SYSTEM_ATTR: int +FILE_SYSTEM_DIR: int +FILE_SYSTEM_NOT_SUPPORT: int +FILE_TYPE_CHAR: int +FILE_TYPE_DISK: int +FILE_TYPE_PIPE: int +FILE_TYPE_UNKNOWN: int +FILE_UNKNOWN: int +FILE_USER_DISALLOWED: int +FileAllocationInfo: int +FileAttributeTagInfo: int +FileBasicInfo: int +FileCompressionInfo: int +FileDispositionInfo: int +FileEndOfFileInfo: int +FileIdBothDirectoryInfo: int +FileIdBothDirectoryRestartInfo: int +FileIdType: int +FileIoPriorityHintInfo: int +FileNameInfo: int +FileRenameInfo: int +FileStandardInfo: int +FileStreamInfo: int +GENERIC_EXECUTE: int +GENERIC_READ: int +GENERIC_WRITE: int +GetFileExInfoStandard: int +IoPriorityHintLow: int +IoPriorityHintNormal: int +IoPriorityHintVeryLow: int +MARKPARITY: int +MOVEFILE_COPY_ALLOWED: int +MOVEFILE_CREATE_HARDLINK: int +MOVEFILE_DELAY_UNTIL_REBOOT: int +MOVEFILE_FAIL_IF_NOT_TRACKABLE: int +MOVEFILE_REPLACE_EXISTING: int +MOVEFILE_WRITE_THROUGH: int +NOPARITY: int +ObjectIdType: int +ODDPARITY: int +ONE5STOPBITS: int +ONESTOPBIT: int +OPEN_ALWAYS: int +OPEN_EXISTING: int +OVERWRITE_HIDDEN: int +PROGRESS_CANCEL: int +PROGRESS_CONTINUE: int +PROGRESS_QUIET: int +PROGRESS_STOP: int +PURGE_RXABORT: int +PURGE_RXCLEAR: int +PURGE_TXABORT: int +PURGE_TXCLEAR: int +REPLACEFILE_IGNORE_MERGE_ERRORS: int +REPLACEFILE_WRITE_THROUGH: int +RTS_CONTROL_DISABLE: int +RTS_CONTROL_ENABLE: int +RTS_CONTROL_HANDSHAKE: int +RTS_CONTROL_TOGGLE: int +SCS_32BIT_BINARY: int +SCS_DOS_BINARY: int +SCS_OS216_BINARY: int +SCS_PIF_BINARY: int +SCS_POSIX_BINARY: int +SCS_WOW_BINARY: int +SECURITY_ANONYMOUS: int +SECURITY_CONTEXT_TRACKING: int +SECURITY_DELEGATION: int +SECURITY_EFFECTIVE_ONLY: int +SECURITY_IDENTIFICATION: int +SECURITY_IMPERSONATION: int +SETBREAK: int +SETDTR: int +SETRTS: int +SETXOFF: int +SETXON: int +SO_CONNECT_TIME: int +SO_UPDATE_ACCEPT_CONTEXT: int +SO_UPDATE_CONNECT_CONTEXT: int +SPACEPARITY: int +SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: int +SYMBOLIC_LINK_FLAG_DIRECTORY: int +TF_DISCONNECT: int +TF_REUSE_SOCKET: int +TF_USE_DEFAULT_WORKER: int +TF_USE_KERNEL_APC: int +TF_USE_SYSTEM_THREAD: int +TF_WRITE_BEHIND: int +TRUNCATE_EXISTING: int +TWOSTOPBITS: int +WSA_IO_PENDING: int +WSA_OPERATION_ABORTED: int +WSAECONNABORTED: int +WSAECONNRESET: int +WSAEDISCON: int +WSAEFAULT: int +WSAEINPROGRESS: int +WSAEINTR: int +WSAEINVAL: int +WSAEMSGSIZE: int +WSAENETDOWN: int +WSAENETRESET: int +WSAENOBUFS: int +WSAENOTCONN: int +WSAENOTSOCK: int +WSAEOPNOTSUPP: int +WSAESHUTDOWN: int +WSAEWOULDBLOCK: int +FD_ADDRESS_LIST_CHANGE: int +INVALID_HANDLE_VALUE: int +UNICODE: int + +# win32pipe.FDCreatePipe is the only known public method to expose this. But it opens both read and write handles. +def _open_osfhandle(osfhandle: _win32typing.PyHANDLE, flags: int, /) -> int: ... diff --git a/stubs/pywin32/win32/win32gui.pyi b/stubs/pywin32/win32/win32gui.pyi new file mode 100644 index 000000000000..a6e91aa5a14e --- /dev/null +++ b/stubs/pywin32/win32/win32gui.pyi @@ -0,0 +1,565 @@ +from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from typing import Any, Literal, TypeVar + +import _win32typing +from win32.lib.pywintypes import error as error + +_T = TypeVar("_T") + +def EnumFontFamilies(hdc: int, Family: str, EnumFontFamProc, Param, /): ... +def set_logger(logger, /) -> None: ... +def LOGFONT() -> _win32typing.PyLOGFONT: ... +def CreateFontIndirect(lplf: _win32typing.PyLOGFONT, /): ... +def GetObject(handle: int, /): ... +def GetObjectType(h: int, /): ... +def PyGetMemory(addr: int, len: int, /): ... +def PyGetString(addr, _len=..., /) -> str: ... +def PySetString(addr, String, maxLen, /): ... +def PySetMemory(addr, String, /): ... +def PyGetArraySignedLong(array, index, /): ... +def PyGetBufferAddressAndLen(obj, /): ... +def FlashWindow(hwnd: int, bInvert, /): ... +def FlashWindowEx(hwnd: int, dwFlags, uCount, dwTimeout, /): ... +def GetWindowLong(hwnd: int, index, /): ... +def GetClassLong(hwnd: int, index, /): ... +def SetWindowLong(hwnd: int, index, value, /): ... +def CallWindowProc(wndproc, hwnd: int, msg, wparam, lparam, /): ... +def CascadeWindows( + hwndObject: _win32typing.PyHANDLE | int | None, + how: int, + rectObject: _win32typing.PyRECT | tuple[int, int, int, int] | int | None = None, + childrenObject: tuple[_win32typing.PyHANDLE | int, ...] | None = None, + /, +) -> int: ... +def SendMessage( + hwnd: int | None, message: int, wparam: int | None = ..., lparam: ReadableBuffer | float | None = ..., / +) -> int: ... +def SendMessageTimeout( + hwnd: int, + message: int, + wparam: ReadableBuffer | float | None, + lparam: ReadableBuffer | float | None, + flags: int, + timeout: int, + /, +) -> tuple[int, int]: ... +def PostMessage( + hwnd: int | None, message: int, wparam: int | None = ..., lparam: ReadableBuffer | float | None = ..., / +) -> None: ... +def PostThreadMessage(threadId, message, wparam, lparam, /) -> None: ... +def ReplyMessage(result, /): ... +def ResetDC(hdc: int, devmode: _win32typing.PyDEVMODEW, /) -> int: ... +def RegisterWindowMessage(name: str, /): ... +def DefWindowProc( + hwnd: int | None, message: int, wparam: ReadableBuffer | float | None, lparam: ReadableBuffer | float | None, / +) -> int: ... +def EnumWindows(callback: Callable[[int, _T], int | None], extra: _T, /) -> None: ... +def EnumThreadWindows(dwThreadId, callback: Callable[[int, _T], int | None], extra: _T, /) -> None: ... +def EnumChildWindows( + hwnd: _win32typing.PyHANDLE | int | None, callback: Callable[[int, _T], int | None], extra: _T, / +) -> None: ... +def EnumDesktopWindows( + hDesktop: _win32typing.PyHANDLE | int | None, callback: Callable[[int, _T], int | None], extra: _T, / +) -> None: ... +def GetThreadDesktop(ThreadId: int, /) -> int: ... +def DialogBox(hInstance: int, TemplateName: _win32typing.PyResourceId, hWndParent: int, DialogFunc, InitParam: int = ..., /): ... +def DialogBoxParam(): ... +def DialogBoxIndirect( + hInstance: int, controllist: _win32typing.PyDialogTemplate, hWndParent: int, DialogFunc, InitParam: int = ..., / +): ... +def DialogBoxIndirectParam(): ... +def CreateDialogIndirect( + hInstance: int, controllist: _win32typing.PyDialogTemplate, hWndParent: int, DialogFunc, InitParam: int = ..., / +): ... +def EndDialog(hwnd: int, result, /) -> None: ... +def GetDlgItem(hDlg: int, IDDlgItem, /): ... +def GetDlgItemInt(hDlg: int, IDDlgItem, Signed, /) -> None: ... +def SetDlgItemInt(hDlg: int, IDDlgItem, Value, Signed, /) -> None: ... +def GetDlgCtrlID(hwnd: int, /): ... +def GetDlgItemText(hDlg: int, IDDlgItem, /) -> str: ... +def SetDlgItemText(hDlg: int, IDDlgItem, String, /) -> None: ... +def GetNextDlgTabItem(hDlg, hCtl, bPrevious, /): ... +def GetNextDlgGroupItem(hDlg, hCtl, bPrevious, /): ... +def SetWindowText() -> None: ... +def GetWindowText(hwnd: int, /) -> str: ... +def InitCommonControls() -> None: ... +def InitCommonControlsEx(flag, /) -> None: ... +def LoadCursor(hinstance, resid, /): ... +def SetCursor(hcursor, /): ... +def GetCursor(): ... +def GetCursorInfo() -> tuple[int, int, int, int]: ... +def CreateAcceleratorTable(accels: tuple[tuple[Incomplete, Incomplete, Incomplete], ...], /): ... +def LoadMenu(hinstance, resource_id: str, /): ... +def DestroyMenu() -> None: ... +def SetMenu(hwnd: int, hmenu, /) -> None: ... +def GetMenu(hwnd: int, /) -> int: ... +def LoadIcon(hinstance: int, resource_id_or_name: str | int, /) -> _win32typing.PyWNDCLASS: ... +def CopyIcon(hicon, /): ... +def DrawIcon(hDC, X, Y, hicon, /) -> None: ... +def DrawIconEx( + hDC, xLeft, yTop, hIcon, cxWidth, cyWidth, istepIfAniCur, hbrFlickerFreeDraw: _win32typing.PyGdiHANDLE, diFlags, / +) -> None: ... +def CreateIconIndirect(iconinfo: _win32typing.PyICONINFO, /): ... +def CreateIconFromResource(bits: str, fIcon, ver: int = ..., /) -> int: ... +def LoadImage(hinst: int, name: str, type: int, cxDesired: int, cyDesired: int, fuLoad: int, /) -> _win32typing.PyGdiHANDLE: ... +def DeleteObject(handle: int | _win32typing.PyGdiHANDLE, /) -> None: ... +def BitBlt( + hdcDest: int | _win32typing.PyGdiHANDLE, + x: int, + y: int, + width: int, + height: int, + hdcSrc: int | _win32typing.PyGdiHANDLE | None, + nXSrc: int, + nYSrc: int, + dwRop: int, + /, +) -> None: ... +def StretchBlt(hdcDest, x, y, width, height, hdcSrc, nXSrc, nYSrc, nWidthSrc, nHeightSrc, dwRop, /) -> None: ... +def PatBlt(hdc: int, XLeft, YLeft, Width, Height, Rop, /) -> None: ... +def SetStretchBltMode(hdc: int, StretchMode, /): ... +def GetStretchBltMode(hdc: int, /): ... +def TransparentBlt( + Dest: int, + XOriginDest, + YOriginDest, + WidthDest, + HeightDest, + Src: int, + XOriginSrc, + YOriginSrc, + WidthSrc, + HeightSrc, + Transparent, + /, +) -> None: ... +def MaskBlt( + Dest: int, XDest, YDest, Width, Height, Src: int, XSrc, YSrc, Mask: _win32typing.PyGdiHANDLE, xMask, yMask, Rop, / +) -> None: ... +def AlphaBlend( + Dest: int, + XOriginDest, + YOriginDest, + WidthDest, + HeightDest, + Src: int, + XOriginSrc, + YOriginSrc, + WidthSrc, + HeightSrc, + blendFunction: _win32typing.PyBLENDFUNCTION, + /, +) -> None: ... +def MessageBox(parent: _win32typing.PyHANDLE | int | None, text: str, caption: str, flags, /): ... +def MessageBeep(type, /) -> None: ... +def CreateWindow( + className: str | _win32typing.PyResourceId, + windowTitle: str | None, + style: int, + x: int, + y: int, + width: int, + height: int, + parent: int, + menu: int, + hinstance: int, + reserved: Incomplete | None, + /, +) -> int: ... +def DestroyWindow(_hwnd: int, /) -> None: ... +def EnableWindow(hWnd: int, bEnable, /): ... +def FindWindow(ClassName: _win32typing.PyResourceId | str | None, WindowName: str | None, /) -> int: ... +def FindWindowEx( + Parent: int | None, ChildAfter: int | None, ClassName: _win32typing.PyResourceId | str | None, WindowName: str | None, / +) -> int: ... +def DragAcceptFiles(hwnd: int, fAccept, /) -> None: ... +def DragDetect(hwnd: int, point: tuple[Incomplete, Incomplete], /) -> None: ... +def SetDoubleClickTime(newVal, /) -> None: ... +def GetDoubleClickTime(): ... +def HideCaret(hWnd: int, /) -> None: ... +def SetCaretPos(x, y, /) -> None: ... +def GetCaretPos() -> tuple[Incomplete, Incomplete]: ... +def ShowCaret(hWnd: int, /) -> None: ... +def ShowWindow(hWnd: int | None, cmdShow: int, /) -> int: ... +def IsWindowVisible(hwnd: int | None, /) -> int: ... +def IsWindowEnabled(hwnd: int | None, /) -> int: ... +def SetFocus(hwnd: int, /) -> None: ... +def GetFocus() -> None: ... +def UpdateWindow(hwnd: int, /) -> None: ... +def BringWindowToTop(hwnd: int, /) -> None: ... +def SetActiveWindow(hwnd: int, /): ... +def GetActiveWindow(): ... +def SetForegroundWindow(hwnd: int, /) -> None: ... +def GetForegroundWindow() -> int: ... +def GetClientRect(hwnd: int, /) -> tuple[int, int, int, int]: ... +def GetDC(hwnd: int, /): ... +def SaveDC(hdc: int, /): ... +def RestoreDC(hdc: int, SavedDC, /) -> None: ... +def DeleteDC(hdc: int | _win32typing.PyHANDLE, /) -> None: ... +def CreateCompatibleDC(dc: int | _win32typing.PyHANDLE | None, /) -> int: ... +def CreateCompatibleBitmap(hdc: int | _win32typing.PyHANDLE | None, width: int, height: int, /) -> _win32typing.PyGdiHANDLE: ... +def CreateBitmap(width: int, height: int, cPlanes: int, cBitsPerPixel: int, bitmap_bits: None, /) -> _win32typing.PyGdiHANDLE: ... +def SelectObject(hdc: int | _win32typing.PyHANDLE | None, object: int | _win32typing.PyHANDLE | None, /) -> int: ... +def GetCurrentObject(hdc: int, ObjectType, /) -> int: ... +def GetWindowRect(hwnd: int | _win32typing.PyHANDLE, /) -> tuple[int, int, int, int]: ... +def GetStockObject(Object, /) -> int: ... +def PostQuitMessage(rc: int, /) -> None: ... +def WaitMessage() -> None: ... +def SetWindowPos(hWnd: int, InsertAfter: int | None, X: int, Y: int, cx: int, cy: int, Flags: int, /) -> None: ... +def GetWindowPlacement(hwnd: int, /) -> tuple[int, int, tuple[int, int], tuple[int, int], tuple[int, int, int, int]]: ... +def SetWindowPlacement(hWnd: int, placement, /) -> None: ... +def RegisterClass(wndClass: _win32typing.PyWNDCLASS, /) -> _win32typing.PyResourceId: ... +def UnregisterClass(atom: _win32typing.PyResourceId, hinst: int, /) -> None: ... +def PumpMessages() -> None: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def GetMessage(hwnd: int, _min, _max, /): ... +def TranslateMessage(msg, /): ... +def DispatchMessage(msg, /): ... +def TranslateAccelerator(hwnd: int, haccel, msg, /): ... +def PeekMessage(hwnd: int, filterMin, filterMax, removalOptions, /): ... +def Shell_NotifyIcon(Message: int, nid: _win32typing.PyNOTIFYICONDATA, /) -> None: ... +def GetSystemMenu(hwnd: int, bRevert, /): ... +def DrawMenuBar(hwnd: int, /) -> None: ... +def MoveWindow(hwnd: int, x: int, y: int, width: int, height: int, bRepaint: bool, /) -> None: ... +def CloseWindow() -> None: ... +def DeleteMenu(hmenu, position, flags, /) -> None: ... +def RemoveMenu(hmenu, position, flags, /) -> None: ... +def CreateMenu(): ... +def CreatePopupMenu(): ... +def TrackPopupMenu(hmenu, flags, x, y, reserved, hwnd: int, prcRect: _win32typing.PyRECT, /): ... +def CommDlgExtendedError(): ... +def ExtractIcon(hinstance, moduleName: str, index, /): ... +def ExtractIconEx(moduleName: str, index, numIcons: int = ..., /): ... +def DestroyIcon(hicon, /) -> None: ... +def GetIconInfo(hicon: int, /) -> _win32typing.PyICONINFO: ... +def ScreenToClient( + hWnd: int | _win32typing.PyHANDLE, Point: tuple[Incomplete, Incomplete], / +) -> tuple[Incomplete, Incomplete]: ... +def ClientToScreen(hWnd: int, Point: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... +def PaintDesktop(hdc: int, /) -> None: ... +def RedrawWindow(hWnd: int, rcUpdate: tuple[int, int, int, int], hrgnUpdate: _win32typing.PyGdiHANDLE, flags, /) -> None: ... +def GetTextExtentPoint32(hdc: int, _str: str, /) -> tuple[Incomplete, Incomplete]: ... +def GetTextMetrics(): ... +def GetTextCharacterExtra(hdc: int, /): ... +def SetTextCharacterExtra(hdc: int, CharExtra, /): ... +def GetTextAlign(hdc: int, /): ... +def SetTextAlign(hdc: int, Mode, /): ... +def GetTextFace(hdc: int, /) -> str: ... +def GetMapMode(hdc: int, /): ... +def SetMapMode(hdc: int, MapMode, /): ... +def GetGraphicsMode(hdc: int, /): ... +def SetGraphicsMode(hdc: int, Mode, /): ... +def GetLayout(hdc: int, /): ... +def SetLayout(hdc: int, Layout, /): ... +def GetPolyFillMode(hdc: int, /): ... +def SetPolyFillMode(hdc: int, PolyFillMode, /): ... +def GetWorldTransform(hdc: int, /) -> _win32typing.PyXFORM: ... +def SetWorldTransform(hdc: int, Xform: _win32typing.PyXFORM, /) -> None: ... +def ModifyWorldTransform(hdc: int, Xform: _win32typing.PyXFORM, Mode, /) -> None: ... +def CombineTransform(xform1: _win32typing.PyXFORM, xform2: _win32typing.PyXFORM, /) -> _win32typing.PyXFORM: ... +def GetWindowOrgEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetWindowOrgEx(hdc: int, X, Y, /) -> tuple[Incomplete, Incomplete]: ... +def GetViewportOrgEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetViewportOrgEx(hdc: int, X, Y, /) -> tuple[Incomplete, Incomplete]: ... +def GetWindowExtEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetWindowExtEx(hdc: int, XExtent, YExtent, /) -> tuple[Incomplete, Incomplete]: ... +def GetViewportExtEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetViewportExtEx(hdc: int, XExtent, YExtent, /) -> tuple[Incomplete, Incomplete]: ... +def GradientFill(hdc, Vertex: tuple[_win32typing.PyTRIVERTEX, ...], Mesh, Mode, /) -> None: ... +def GetOpenFileName(OPENFILENAME: str, /): ... +def InsertMenuItem(hMenu, uItem, fByPosition, menuItem, /) -> None: ... +def SetMenuItemInfo(hMenu, uItem, fByPosition, menuItem, /) -> None: ... +def GetMenuItemInfo(hMenu: int, uItem: int, fByPosition: bool, menuItem: ReadableBuffer, /) -> None: ... +def GetMenuItemCount(hMenu: int | None, /) -> int: ... + +# Actually returns a list of int|tuple, but lists don't support positional types +def GetMenuItemRect(hWnd: int | None, hMenu: int | None, uItem: int, /) -> tuple[int, tuple[int, int, int, int]]: ... +def GetMenuState(hMenu, uID, flags, /): ... +def SetMenuDefaultItem(hMenu, uItem, fByPos, /) -> None: ... +def GetMenuDefaultItem(hMenu, fByPos, flags, /): ... +def AppendMenu() -> None: ... +def InsertMenu() -> None: ... +def EnableMenuItem() -> None: ... +def CheckMenuItem(): ... +def GetSubMenu(hMenu, nPos, /): ... +def ModifyMenu(hMnu, uPosition, uFlags, uIDNewItem, newItem: str, /) -> None: ... +def GetMenuItemID(hMenu, nPos, /): ... +def SetMenuItemBitmaps( + hMenu, uPosition, uFlags, hBitmapUnchecked: _win32typing.PyGdiHANDLE, hBitmapChecked: _win32typing.PyGdiHANDLE, / +) -> None: ... +def CheckMenuRadioItem(hMenu, idFirst, idLast, idCheck, uFlags, /) -> None: ... +def SetMenuInfo(hmenu, info, /) -> None: ... +def GetMenuInfo(hmenu: int, info: WriteableBuffer, /) -> None: ... +def DrawFocusRect(hDC: int, rc: tuple[int, int, int, int], /) -> None: ... +def DrawText(hDC: int, String, nCount, Rect: _win32typing.PyRECT, Format, /) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def LineTo(hdc: int, XEnd, YEnd, /) -> None: ... +def Ellipse(hdc: int, LeftRect, TopRect, RightRect, BottomRect, /) -> None: ... +def Pie(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def Arc(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def ArcTo(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def AngleArc(hdc: int, Y, Y1, Radius, StartAngle: float, SweepAngle: float, /) -> None: ... +def Chord(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def ExtFloodFill(arg: int, XStart, YStart, Color, FillType, /) -> None: ... +def SetPixel(hdc: int, X, Y, Color, /): ... +def GetPixel(hdc: int, XPos, YPos, /): ... +def GetROP2(hdc: int, /): ... +def SetROP2(hdc: int, DrawMode, /): ... +def SetPixelV(hdc: int, X, Y, Color, /) -> None: ... +def MoveToEx(hdc: int, X, Y, /) -> tuple[Incomplete, Incomplete]: ... +def GetCurrentPositionEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def GetArcDirection(hdc: int, /): ... +def SetArcDirection(hdc: int, ArcDirection, /): ... +def Polygon(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def Polyline(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PolylineTo(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PolyBezier(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PolyBezierTo(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PlgBlt( + Dest: int, + Point, + Src: int, + XSrc, + YSrc, + Width, + Height, + Mask: _win32typing.PyGdiHANDLE | None = ..., + xMask: int = ..., + yMask: int = ..., + /, +) -> None: ... +def CreatePolygonRgn(Points: list[tuple[Incomplete, Incomplete]], PolyFillMode, /) -> _win32typing.PyGdiHANDLE: ... +def ExtTextOut( + hdc: int, _int, _int1, _int2, rect: _win32typing.PyRECT, string, _tuple: tuple[tuple[Incomplete, Incomplete], ...], / +): ... +def GetTextColor(hdc, /): ... +def SetTextColor(hdc, color, /): ... +def GetBkMode(hdc: int, /): ... +def SetBkMode(hdc: int, BkMode, /): ... +def GetBkColor(hdc: int, /): ... +def SetBkColor(hdc: int, color, /): ... +def DrawEdge(hdc: int, rc: _win32typing.PyRECT, edge, Flags, /) -> _win32typing.PyRECT: ... +def FillRect(hDC: int, rc: _win32typing.PyRECT, hbr: _win32typing.PyGdiHANDLE, /) -> None: ... +def FillRgn(hdc: int, hrgn: _win32typing.PyGdiHANDLE, hbr: _win32typing.PyGdiHANDLE, /) -> None: ... +def PaintRgn(hdc: int, hrgn: _win32typing.PyGdiHANDLE, /) -> None: ... +def FrameRgn(hdc: int, hrgn, hbr, Width, Height, /) -> None: ... +def InvertRgn(hdc: int, hrgn, /) -> None: ... +def EqualRgn(SrcRgn1, SrcRgn2, /): ... +def PtInRegion(hrgn, X, Y, /): ... +def PtInRect(rect: tuple[int, int, int, int], point: tuple[Incomplete, Incomplete], /): ... +def RectInRegion(hrgn, rc: _win32typing.PyRECT, /): ... +def SetRectRgn(hrgn, LeftRect, TopRect, RightRect, BottomRect, /) -> None: ... +def CombineRgn(Dest, Src1, Src2, CombineMode, /): ... +def DrawAnimatedRects(hwnd: int, idAni, minCoords: _win32typing.PyRECT, restCoords: _win32typing.PyRECT, /) -> None: ... +def CreateSolidBrush(Color, /) -> _win32typing.PyGdiHANDLE: ... +def CreatePatternBrush(hbmp: _win32typing.PyGdiHANDLE, /) -> _win32typing.PyGdiHANDLE: ... +def CreateHatchBrush(Style, clrref, /) -> _win32typing.PyGdiHANDLE: ... +def CreatePen(PenStyle, Width, Color, /) -> _win32typing.PyGdiHANDLE: ... +def GetSysColor(Index: int, /) -> int: ... +def GetSysColorBrush(Index, /) -> _win32typing.PyGdiHANDLE: ... +def InvalidateRect(hWnd: int, Rect: _win32typing.PyRECT, Erase, /) -> None: ... +def FrameRect(hDC: int, rc: _win32typing.PyRECT, hbr: _win32typing.PyGdiHANDLE, /) -> None: ... +def InvertRect(hDC: int, rc: _win32typing.PyRECT, /) -> None: ... +def WindowFromDC(hDC: int, /) -> int: ... +def GetUpdateRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, Erase, /): ... +def GetWindowRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, /): ... +def SetWindowRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE | None, Redraw: bool, /) -> None: ... + +# Actually returns a list, but the length is always fixed +def GetWindowRgnBox(hWnd: _win32typing.PyHANDLE | int | None) -> tuple[int, tuple[int, int, int, int]]: ... +def ValidateRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, /) -> None: ... +def InvalidateRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, Erase, /) -> None: ... +def GetRgnBox(hrgn: _win32typing.PyGdiHANDLE, /) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def OffsetRgn(hrgn: _win32typing.PyGdiHANDLE, XOffset, YOffset, /): ... +def Rectangle(hdc: int, LeftRect, TopRect, RightRect, BottomRect, /) -> None: ... +def RoundRect(hdc: int, LeftRect, TopRect, RightRect, BottomRect, Width, Height, /) -> None: ... +def BeginPaint() -> tuple[Incomplete, Incomplete]: ... +def EndPaint(hwnd: int, ps, /) -> None: ... +def BeginPath(hdc: int, /) -> None: ... +def EndPath(hdc: int, /) -> None: ... +def AbortPath(hdc: int, /) -> None: ... +def CloseFigure(hdc: int, /) -> None: ... +def FlattenPath(hdc: int, /) -> None: ... +def FillPath(hdc: int, /) -> None: ... +def WidenPath(hdc: int, /) -> None: ... +def StrokePath(hdc: int, /) -> None: ... +def StrokeAndFillPath(hdc: int, /) -> None: ... +def GetMiterLimit(hdc: int, /) -> float: ... +def SetMiterLimit(hdc: int, NewLimit: float, /) -> float: ... +def PathToRegion(hdc: int, /) -> _win32typing.PyGdiHANDLE: ... +def GetPath(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def CreateRoundRectRgn(LeftRect, TopRect, RightRect, BottomRect, WidthEllipse, HeightEllipse, /): ... +def CreateRectRgnIndirect(rc: _win32typing.PyRECT, /): ... +def CreateEllipticRgnIndirect(rc: _win32typing.PyRECT, /): ... +def CreateWindowEx( + dwExStyle, className: str, windowTitle: str, style, x, y, width, height, parent, menu, hinstance, reserved, / +): ... +def GetParent(child: int, /) -> int: ... +def SetParent(child: int, child1: int | _win32typing.PyHANDLE | None, /) -> int: ... +def GetCursorPos() -> tuple[Incomplete, Incomplete]: ... +def GetDesktopWindow(): ... +def GetWindow(hWnd: int, uCmd: int, /) -> int: ... +def GetWindowDC(hWnd: int | _win32typing.PyHANDLE | None, /) -> int: ... +def IsIconic(hWnd: int, /) -> int: ... +def IsWindow(hWnd: int, /) -> int: ... +def IsChild(hWndParent: int, hWnd: int, /) -> int: ... +def ReleaseCapture() -> None: ... +def GetCapture(): ... +def SetCapture() -> None: ... + +# Exists and is documented as a wrapper around TrackMouseEvent +# See https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-_trackmouseevent +def _TrackMouseEvent(tme: tuple[int, int, int], /) -> _win32typing.TRACKMOUSEEVENT: ... +def ReleaseDC(hWnd: int | _win32typing.PyHANDLE | None, hDC: int | _win32typing.PyHANDLE | None, /) -> Literal[0, 1]: ... +def CreateCaret(hWnd: int, hBitmap: _win32typing.PyGdiHANDLE, nWidth, nHeight, /) -> None: ... +def DestroyCaret() -> None: ... +def ScrollWindowEx( + hWnd: int, dx, dy, rcScroll: _win32typing.PyRECT, rcClip: _win32typing.PyRECT, hrgnUpdate, flags, / +) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def SetScrollInfo(hwnd: int, nBar, scollInfo: _win32typing.PySCROLLINFO, bRedraw=..., /) -> None: ... +def GetScrollInfo(hwnd: int, nBar, mask, /) -> _win32typing.PySCROLLINFO: ... +def GetClassName(hwnd: _win32typing.PyHANDLE | int | None, /) -> str | None: ... +def RealGetWindowClass(hwnd: _win32typing.PyHANDLE | int | None, /) -> str | None: ... +def WindowFromPoint(point: tuple[int, int], /) -> int: ... +def ChildWindowFromPoint(hwndParent: int, point: tuple[Incomplete, Incomplete], /): ... +def CreateDC(Driver: str, Device: str, InitData: _win32typing.PyDEVMODEW, /): ... +def GetSaveFileNameW( + hwndOwner: int | None = ..., + hInstance: int | None = ..., + Filter: Incomplete | None = ..., + CustomFilter: Incomplete | None = ..., + FilterIndex: int = ..., + File: Incomplete | None = ..., + MaxFile: int = ..., + InitialDir: Incomplete | None = ..., + Title: Incomplete | None = ..., + Flags: int = ..., + DefExt: Incomplete | None = ..., + TemplateName: _win32typing.PyResourceId | None = ..., + /, +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def GetOpenFileNameW( + hwndOwner: int | None = ..., + hInstance: int | None = ..., + Filter: Incomplete | None = ..., + CustomFilter: Incomplete | None = ..., + FilterIndex: int = ..., + File: Incomplete | None = ..., + MaxFile: int = ..., + InitialDir: Incomplete | None = ..., + Title: Incomplete | None = ..., + Flags: int = ..., + DefExt: Incomplete | None = ..., + TemplateName: _win32typing.PyResourceId | None = ..., +) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +# Any: Return type is too varied based on Action. This would require an overload for all win32con.SPI_* literals +def SystemParametersInfo(Action: int, Param: Incomplete | None = ..., WinIni: int = ...) -> Any: ... +def SetLayeredWindowAttributes(hwnd: int, Key, Alpha, Flags) -> None: ... +def GetLayeredWindowAttributes(hwnd: int) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def UpdateLayeredWindow( + hwnd: int, + hdcDst: int | None = ..., + ptDst: tuple[Incomplete, Incomplete] | None = ..., + size: tuple[Incomplete, Incomplete] | None = ..., + hdcSrc: Incomplete | None = ..., + ptSrc: tuple[Incomplete, Incomplete] | None = ..., + Key: int = ..., + blend: tuple[int, int, int, int] = ..., + Flags: int = ..., +) -> None: ... +def AnimateWindow(hwnd: int, Time, Flags) -> None: ... +def CreateBrushIndirect(lb: _win32typing.PyLOGBRUSH, /) -> _win32typing.PyGdiHANDLE: ... +def ExtCreatePen(PenStyle, Width, lb: _win32typing.PyLOGBRUSH, Style: tuple[Incomplete, ...] | None = ..., /) -> int: ... +def DrawTextW(hDC: int, String: str, Count, Rect: _win32typing.PyRECT, Format) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def EnumPropsEx(hWnd: int, EnumFunc, Param, /) -> None: ... +def RegisterDeviceNotification(handle: int, _filter, flags, /) -> _win32typing.PyHDEVNOTIFY: ... +def UnregisterDeviceNotification() -> None: ... +def RegisterHotKey(hWnd: _win32typing.PyHANDLE | int | None, _id: int, Modifiers: int, vk: int, /) -> None: ... +def UnregisterHotKey(hWnd: _win32typing.PyHANDLE | int | None, _id: int, /) -> None: ... +def GetAncestor(hwnd: int, gaFlags: int, /) -> int: ... +def GetTopWindow(hWnd: int | None, /) -> int: ... +def ChildWindowFromPointEx(hwndParent: int, point: tuple[Incomplete, Incomplete], flags: int, /): ... +def CreateDialogIndirectParam(hInstance, controlList, hWndParent, DialogFunc, InitParam: int = 0, /) -> int: ... +def DestroyAcceleratorTable(haccel, /): ... +def Edit_GetLine(hwnd, line, size=..., /): ... +def GetModuleHandle(lpModuleName: str | None, /) -> int: ... +def GetWindowTextLength(hwnd, /) -> int: ... +def HIWORD(val: int, /) -> int: ... +def ImageList_Add(hImageList, hbmImage, hbmMask, /) -> int: ... +def ImageList_Create(cx: int, cy: int, flags: int, cInitial: int, cGrow: int, /): ... +def ImageList_Destroy(hImageList, /): ... +def ImageList_Draw(hImageList, i: int, hdcDst, x: int, y: int, fStyle, /): ... +def ImageList_DrawEx(hImageList, i: int, hdcDst, x: int, y: int, dx: int, dy: int, rgbBk, rgbFg, fStyle, /): ... +def ImageList_GetIcon(hImageList, i: int, flag: int, /): ... +def ImageList_GetImageCount(hImageList, /) -> int: ... +def ImageList_LoadBitmap(hInst, name, cx: int, cGrow: int, crMask, /): ... +def ImageList_LoadImage(hInst, name, cx: int, cGrow: int, crMask, uType, uFlags, /): ... +def ImageList_Remove(hImageList, i, /): ... +def ImageList_Replace(hImageList, i, hicon, /): ... +def ImageList_ReplaceIcon(hImageList, i, hicon, /): ... +def ImageList_SetBkColor(hImageList, Color, /): ... +def ImageList_SetOverlayImage(hImageList, iImage, iOverlay, /): ... +def LOWORD(val: int, /) -> int: ... +def ListView_SortItems(hwnd, callback, param=None, /) -> None: ... +def ListView_SortItemsEx(hwnd, callback, param=None, /) -> None: ... +def ValidateRect(hWnd, Rect, /): ... +def WNDCLASS() -> _win32typing.PyWNDCLASS: ... +def lpstr(address, /) -> bytes: ... + +CLR_NONE: int +ILC_COLOR: int +ILC_COLOR16: int +ILC_COLOR24: int +ILC_COLOR32: int +ILC_COLOR4: int +ILC_COLOR8: int +ILC_COLORDDB: int +ILC_MASK: int +ILD_BLEND: int +ILD_BLEND25: int +ILD_BLEND50: int +ILD_FOCUS: int +ILD_MASK: int +ILD_NORMAL: int +ILD_SELECTED: int +ILD_TRANSPARENT: int +IMAGE_BITMAP: int +IMAGE_CURSOR: int +IMAGE_ICON: int +LR_CREATEDIBSECTION: int +LR_DEFAULTCOLOR: int +LR_DEFAULTSIZE: int +LR_LOADFROMFILE: int +LR_LOADMAP3DCOLORS: int +LR_LOADTRANSPARENT: int +LR_MONOCHROME: int +LR_SHARED: int +LR_VGACOLOR: int +NIF_ICON: int +NIF_INFO: int +NIF_MESSAGE: int +NIF_STATE: int +NIF_TIP: int +NIIF_ERROR: int +NIIF_ICON_MASK: int +NIIF_INFO: int +NIIF_NONE: int +NIIF_NOSOUND: int +NIIF_WARNING: int +NIM_ADD: int +NIM_DELETE: int +NIM_MODIFY: int +NIM_SETVERSION: int +TPM_BOTTOMALIGN: int +TPM_CENTERALIGN: int +TPM_LEFTALIGN: int +TPM_LEFTBUTTON: int +TPM_NONOTIFY: int +TPM_RETURNCMD: int +TPM_RIGHTALIGN: int +TPM_RIGHTBUTTON: int +TPM_TOPALIGN: int +TPM_VCENTERALIGN: int +UNICODE: Literal[1] +dllhandle: int diff --git a/stubs/pywin32/win32/win32help.pyi b/stubs/pywin32/win32/win32help.pyi new file mode 100644 index 000000000000..811f588e67c2 --- /dev/null +++ b/stubs/pywin32/win32/win32help.pyi @@ -0,0 +1,180 @@ +import _win32typing + +def WinHelp(hwnd: int, hlpFile: str, cmd, data: str | None = ..., /) -> None: ... +def HH_AKLINK() -> _win32typing.PyHH_AKLINK: ... +def HH_FTS_QUERY() -> _win32typing.PyHH_FTS_QUERY: ... +def HH_POPUP() -> _win32typing.PyHH_POPUP: ... +def HH_WINTYPE() -> _win32typing.PyHH_WINTYPE: ... +def NMHDR() -> _win32typing.PyNMHDR: ... +def HHN_NOTIFY() -> _win32typing.PyHHN_NOTIFY: ... +def HHNTRACK() -> _win32typing.PyHHNTRACK: ... +def HtmlHelp(hwnd: int, file: str, cmd, data: str | tuple[int] | int = ..., /): ... + +debug: int +HH_ALINK_LOOKUP: int +HH_CLOSE_ALL: int +HH_DISPLAY_INDEX: int +HH_DISPLAY_SEARCH: int +HH_DISPLAY_TEXT_POPUP: int +HH_DISPLAY_TOC: int +HH_DISPLAY_TOPIC: int +HH_ENUM_CATEGORY: int +HH_ENUM_CATEGORY_IT: int +HH_ENUM_INFO_TYPE: int +HH_FTS_DEFAULT_PROXIMITY: int +HH_GET_LAST_ERROR: int +HH_GET_WIN_HANDLE: int +HH_GET_WIN_TYPE: int +HH_GPROPID_CONTENT_LANGUAGE: int +HH_GPROPID_CURRENT_SUBSET: int +HH_GPROPID_SINGLETHREAD: int +HH_GPROPID_TOOLBAR_MARGIN: int +HH_GPROPID_UI_LANGUAGE: int +HH_HELP_CONTEXT: int +HH_HELP_FINDER: int +HH_INITIALIZE: int +HH_KEYWORD_LOOKUP: int +HH_MAX_TABS_CUSTOM: int +HH_PRETRANSLATEMESSAGE: int +HH_RESERVED1: int +HH_RESERVED2: int +HH_RESERVED3: int +HH_RESET_IT_FILTER: int +HH_SET_EXCLUSIVE_FILTER: int +HH_SET_GLOBAL_PROPERTY: int +HH_SET_INCLUSIVE_FILTER: int +HH_SET_INFO_TYPE: int +HH_SET_WIN_TYPE: int +HH_SYNC: int +HH_TAB_AUTHOR: int +HH_TAB_CONTENTS: int +HH_TAB_CUSTOM_FIRST: int +HH_TAB_CUSTOM_LAST: int +HH_TAB_FAVORITES: int +HH_TAB_HISTORY: int +HH_TAB_INDEX: int +HH_TAB_SEARCH: int +HH_TP_HELP_CONTEXTMENU: int +HH_TP_HELP_WM_HELP: int +HH_UNINITIALIZE: int +HHACT_BACK: int +HHACT_CONTRACT: int +HHACT_CUSTOMIZE: int +HHACT_EXPAND: int +HHACT_FORWARD: int +HHACT_HIGHLIGHT: int +HHACT_HOME: int +HHACT_JUMP1: int +HHACT_JUMP2: int +HHACT_LAST_ENUM: int +HHACT_NOTES: int +HHACT_OPTIONS: int +HHACT_PRINT: int +HHACT_REFRESH: int +HHACT_STOP: int +HHACT_SYNC: int +HHACT_TAB_CONTENTS: int +HHACT_TAB_FAVORITES: int +HHACT_TAB_HISTORY: int +HHACT_TAB_INDEX: int +HHACT_TAB_SEARCH: int +HHACT_TOC_NEXT: int +HHACT_TOC_PREV: int +HHACT_ZOOM: int +HHN_FIRST: int +HHN_LAST: int +HHN_NAVCOMPLETE: int +HHN_TRACK: int +HHN_WINDOW_CREATE: int +HHWIN_BUTTON_BACK: int +HHWIN_BUTTON_BROWSE_BCK: int +HHWIN_BUTTON_BROWSE_FWD: int +HHWIN_BUTTON_CONTENTS: int +HHWIN_BUTTON_EXPAND: int +HHWIN_BUTTON_FAVORITES: int +HHWIN_BUTTON_FORWARD: int +HHWIN_BUTTON_HISTORY: int +HHWIN_BUTTON_HOME: int +HHWIN_BUTTON_INDEX: int +HHWIN_BUTTON_JUMP1: int +HHWIN_BUTTON_JUMP2: int +HHWIN_BUTTON_NOTES: int +HHWIN_BUTTON_OPTIONS: int +HHWIN_BUTTON_PRINT: int +HHWIN_BUTTON_REFRESH: int +HHWIN_BUTTON_SEARCH: int +HHWIN_BUTTON_STOP: int +HHWIN_BUTTON_SYNC: int +HHWIN_BUTTON_TOC_NEXT: int +HHWIN_BUTTON_TOC_PREV: int +HHWIN_BUTTON_ZOOM: int +HHWIN_DEF_BUTTONS: int +HHWIN_NAVTAB_BOTTOM: int +HHWIN_NAVTAB_LEFT: int +HHWIN_NAVTAB_TOP: int +HHWIN_PARAM_CUR_TAB: int +HHWIN_PARAM_EXPANSION: int +HHWIN_PARAM_EXSTYLES: int +HHWIN_PARAM_HISTORY_COUNT: int +HHWIN_PARAM_INFOTYPES: int +HHWIN_PARAM_NAV_WIDTH: int +HHWIN_PARAM_PROPERTIES: int +HHWIN_PARAM_RECT: int +HHWIN_PARAM_SHOWSTATE: int +HHWIN_PARAM_STYLES: int +HHWIN_PARAM_TABORDER: int +HHWIN_PARAM_TABPOS: int +HHWIN_PARAM_TB_FLAGS: int +HHWIN_PROP_AUTO_SYNC: int +HHWIN_PROP_CHANGE_TITLE: int +HHWIN_PROP_MENU: int +HHWIN_PROP_NAV_ONLY_WIN: int +HHWIN_PROP_NO_TOOLBAR: int +HHWIN_PROP_NODEF_EXSTYLES: int +HHWIN_PROP_NODEF_STYLES: int +HHWIN_PROP_NOTB_TEXT: int +HHWIN_PROP_NOTITLEBAR: int +HHWIN_PROP_ONTOP: int +HHWIN_PROP_POST_QUIT: int +HHWIN_PROP_TAB_ADVSEARCH: int +HHWIN_PROP_TAB_AUTOHIDESHOW: int +HHWIN_PROP_TAB_CUSTOM1: int +HHWIN_PROP_TAB_CUSTOM2: int +HHWIN_PROP_TAB_CUSTOM3: int +HHWIN_PROP_TAB_CUSTOM4: int +HHWIN_PROP_TAB_CUSTOM5: int +HHWIN_PROP_TAB_CUSTOM6: int +HHWIN_PROP_TAB_CUSTOM7: int +HHWIN_PROP_TAB_CUSTOM8: int +HHWIN_PROP_TAB_CUSTOM9: int +HHWIN_PROP_TAB_FAVORITES: int +HHWIN_PROP_TAB_HISTORY: int +HHWIN_PROP_TAB_SEARCH: int +HHWIN_PROP_TRACKING: int +HHWIN_PROP_TRI_PANE: int +HHWIN_PROP_USER_POS: int +HHWIN_TB_MARGIN: int +IDTB_BACK: int +IDTB_BROWSE_BACK: int +IDTB_BROWSE_FWD: int +IDTB_CONTENTS: int +IDTB_CONTRACT: int +IDTB_CUSTOMIZE: int +IDTB_EXPAND: int +IDTB_FAVORITES: int +IDTB_FORWARD: int +IDTB_HISTORY: int +IDTB_HOME: int +IDTB_INDEX: int +IDTB_JUMP1: int +IDTB_JUMP2: int +IDTB_NOTES: int +IDTB_OPTIONS: int +IDTB_PRINT: int +IDTB_REFRESH: int +IDTB_SEARCH: int +IDTB_STOP: int +IDTB_SYNC: int +IDTB_TOC_NEXT: int +IDTB_TOC_PREV: int +IDTB_ZOOM: int diff --git a/stubs/pywin32/win32/win32inet.pyi b/stubs/pywin32/win32/win32inet.pyi new file mode 100644 index 000000000000..77bd3645eed2 --- /dev/null +++ b/stubs/pywin32/win32/win32inet.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +def InternetSetCookie(url: str, lpszCookieName: str, data: str, /) -> None: ... +def InternetGetCookie(Url: str, CookieName: str, /) -> str: ... +def InternetAttemptConnect(Reserved: int = ..., /) -> None: ... +def InternetCheckConnection(Url: str, Flags: int = ..., Reserved: int = ..., /) -> None: ... +def InternetGoOnline(Url: str, Parent: Incomplete | None = ..., Flags: int = ..., /) -> None: ... +def InternetCloseHandle(handle: _win32typing.PyHINTERNET, /) -> None: ... +def InternetConnect( + Internet: _win32typing.PyHINTERNET, + ServerName: str, + ServerPort, + Username: str, + Password: str, + Service, + Flags, + Context: Incomplete | None = ..., +) -> None: ... +def InternetOpen(agent: str, proxyName: str, proxyBypass: str, flags) -> None: ... +def InternetOpenUrl( + Internet: _win32typing.PyHINTERNET, Url: str, Headers: str | None = ..., Flags: int = ..., Context: Incomplete | None = ... +) -> _win32typing.PyHINTERNET: ... +def InternetCanonicalizeUrl(url: str, flags: int = ..., /) -> str: ... +def InternetGetLastResponseInfo() -> tuple[Incomplete, str]: ... +def InternetReadFile(hInternet: _win32typing.PyHINTERNET, size, /) -> str: ... +def InternetWriteFile(File: _win32typing.PyHINTERNET, Buffer: str, /): ... +def FtpOpenFile( + Connect: _win32typing.PyHINTERNET, FileName: str, Access, Flags, Context: Incomplete | None = ... +) -> _win32typing.PyHINTERNET: ... +def FtpCommand( + Connect: _win32typing.PyHINTERNET, ExpectResponse, Flags, Command: str, Context: Incomplete | None = ... +) -> _win32typing.PyHINTERNET: ... +def InternetQueryOption(hInternet: _win32typing.PyHINTERNET, Option, /): ... +def InternetSetOption(hInternet: _win32typing.PyHINTERNET, Option, Buffer, /) -> None: ... +def FindFirstUrlCacheEntry(SearchPattern: Incomplete | None = ...) -> tuple[_win32typing.PyUrlCacheHANDLE, Incomplete]: ... +def FindNextUrlCacheEntry(EnumHandle: _win32typing.PyUrlCacheHANDLE): ... +def FindFirstUrlCacheEntryEx( + SearchPattern: Incomplete | None = ..., Flags: int = ..., Filter: int = ..., GroupId=... +) -> tuple[_win32typing.PyUrlCacheHANDLE, Incomplete]: ... +def FindNextUrlCacheEntryEx(EnumHandle: _win32typing.PyUrlCacheHANDLE): ... +def FindCloseUrlCache(EnumHandle: _win32typing.PyUrlCacheHANDLE) -> None: ... +def FindFirstUrlCacheGroup(Filter=...) -> tuple[_win32typing.PyUrlCacheHANDLE, Incomplete]: ... +def FindNextUrlCacheGroup(Find: int): ... +def GetUrlCacheEntryInfo(UrlName): ... +def DeleteUrlCacheGroup(GroupId, Attributes=...) -> None: ... +def CreateUrlCacheGroup(Flags: int = ...): ... +def CreateUrlCacheEntry(UrlName, ExpectedFileSize, FileExtension): ... +def CommitUrlCacheEntry( + UrlName, + LocalFileName, + CacheEntryType, + ExpireTime: TimeType | None = ..., + LastModifiedTime: TimeType | None = ..., + HeaderInfo: Incomplete | None = ..., + OriginalUrl: Incomplete | None = ..., +): ... +def SetUrlCacheEntryGroup(UrlName, Flags, GroupId) -> None: ... +def GetUrlCacheGroupAttribute(GroupId, Attributes=...): ... +def SetUrlCacheGroupAttribute(GroupId, Attributes, GroupInfo, Flags=...) -> None: ... +def DeleteUrlCacheEntry(UrlName, /) -> None: ... +def WinHttpGetDefaultProxyConfiguration(): ... +def WinHttpGetIEProxyConfigForCurrentUser() -> tuple[int, str, str, str]: ... +def WinHttpGetProxyForUrl(handle: _win32typing.PyHANDLE | int | None, url: str, options: tuple[int | str | None, ...], /): ... +def WinHttpOpen(lpszUserAgent: str, dwAccessType: int, lpszProxyName: str, lpszProxyBypass: str, dwFlags: int, /): ... + +UNICODE: int diff --git a/stubs/pywin32/win32/win32job.pyi b/stubs/pywin32/win32/win32job.pyi new file mode 100644 index 000000000000..7b3ded8d35f4 --- /dev/null +++ b/stubs/pywin32/win32/win32job.pyi @@ -0,0 +1,74 @@ +import _win32typing +from win32.lib.pywintypes import error as error + +def AssignProcessToJobObject(hJob: int, hProcess: int, /) -> None: ... +def CreateJobObject(jobAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, name: str, /) -> None: ... +def OpenJobObject(desiredAccess, inheritHandles, name, /) -> None: ... +def TerminateJobObject(hJob: int, exitCode, /) -> None: ... +def UserHandleGrantAccess(hUserHandle: int, hJob: int, grant, /) -> None: ... +def IsProcessInJob(hProcess: int, hJob: int, /): ... +def QueryInformationJobObject(Job: int, JobObjectInfoClass, /): ... +def SetInformationJobObject(Job: int, JobObjectInfoClass, JobObjectInfo, /) -> None: ... + +JOB_OBJECT_ALL_ACCESS: int +JOB_OBJECT_ASSIGN_PROCESS: int +JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS: int +JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS: int +JOB_OBJECT_LIMIT_ACTIVE_PROCESS: int +JOB_OBJECT_LIMIT_AFFINITY: int +JOB_OBJECT_LIMIT_BREAKAWAY_OK: int +JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: int +JOB_OBJECT_LIMIT_JOB_MEMORY: int +JOB_OBJECT_LIMIT_JOB_TIME: int +JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: int +JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME: int +JOB_OBJECT_LIMIT_PRIORITY_CLASS: int +JOB_OBJECT_LIMIT_PROCESS_MEMORY: int +JOB_OBJECT_LIMIT_PROCESS_TIME: int +JOB_OBJECT_LIMIT_SCHEDULING_CLASS: int +JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK: int +JOB_OBJECT_LIMIT_VALID_FLAGS: int +JOB_OBJECT_LIMIT_WORKINGSET: int +JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: int +JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: int +JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: int +JOB_OBJECT_MSG_END_OF_JOB_TIME: int +JOB_OBJECT_MSG_END_OF_PROCESS_TIME: int +JOB_OBJECT_MSG_EXIT_PROCESS: int +JOB_OBJECT_MSG_JOB_MEMORY_LIMIT: int +JOB_OBJECT_MSG_NEW_PROCESS: int +JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT: int +JOB_OBJECT_POST_AT_END_OF_JOB: int +JOB_OBJECT_QUERY: int +JOB_OBJECT_SECURITY_FILTER_TOKENS: int +JOB_OBJECT_SECURITY_NO_ADMIN: int +JOB_OBJECT_SECURITY_ONLY_TOKEN: int +JOB_OBJECT_SECURITY_RESTRICTED_TOKEN: int +JOB_OBJECT_SECURITY_VALID_FLAGS: int +JOB_OBJECT_SET_ATTRIBUTES: int +JOB_OBJECT_SET_SECURITY_ATTRIBUTES: int +JOB_OBJECT_TERMINATE: int +JOB_OBJECT_TERMINATE_AT_END_OF_JOB: int +JOB_OBJECT_UI_VALID_FLAGS: int +JOB_OBJECT_UILIMIT_ALL: int +JOB_OBJECT_UILIMIT_DESKTOP: int +JOB_OBJECT_UILIMIT_DISPLAYSETTINGS: int +JOB_OBJECT_UILIMIT_EXITWINDOWS: int +JOB_OBJECT_UILIMIT_GLOBALATOMS: int +JOB_OBJECT_UILIMIT_HANDLES: int +JOB_OBJECT_UILIMIT_NONE: int +JOB_OBJECT_UILIMIT_READCLIPBOARD: int +JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: int +JOB_OBJECT_UILIMIT_WRITECLIPBOARD: int +JobObjectAssociateCompletionPortInformation: int +JobObjectBasicAccountingInformation: int +JobObjectBasicAndIoAccountingInformation: int +JobObjectBasicLimitInformation: int +JobObjectBasicUIRestrictions: int +JobObjectEndOfJobTimeInformation: int +JobObjectExtendedLimitInformation: int +JobObjectJobSetInformation: int +JobObjectSecurityLimitInformation: int +MaxJobObjectInfoClass: int +JobObjectBasicProcessIdList: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32lz.pyi b/stubs/pywin32/win32/win32lz.pyi new file mode 100644 index 000000000000..711744c480b1 --- /dev/null +++ b/stubs/pywin32/win32/win32lz.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from win32.lib.pywintypes import error as error + +def GetExpandedName(Source, /) -> str: ... +def Close(handle, /) -> None: ... +def Copy(hSrc, hDest, /): ... +def Init(handle, /) -> None: ... +def OpenFile(fileName: str, action, /) -> tuple[Incomplete, Incomplete]: ... diff --git a/stubs/pywin32/win32/win32net.pyi b/stubs/pywin32/win32/win32net.pyi new file mode 100644 index 000000000000..2a01d0e39135 --- /dev/null +++ b/stubs/pywin32/win32/win32net.pyi @@ -0,0 +1,94 @@ +from _typeshed import Incomplete + +from win32.lib.pywintypes import error as error + +def NetGetJoinInformation() -> tuple[str, Incomplete]: ... +def NetGroupGetInfo(server: str, groupname: str, level, /): ... +def NetGroupGetUsers( + server: str, groupName: str, level, resumeHandle: int = ..., prefLen: int = ..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetGroupSetUsers(server: str, group: str, level, members: tuple[Incomplete, Incomplete], /) -> None: ... +def NetGroupSetInfo(server: str, groupname: str, level, data, /) -> None: ... +def NetGroupAdd(server: str, level, data, /) -> None: ... +def NetGroupAddUser(server: str, group: str, username: str, /) -> None: ... +def NetGroupDel(server: str, groupname: str, /) -> None: ... +def NetGroupDelUser(server: str, group: str, username: str, /) -> None: ... +def NetGroupEnum(server: str, level, prefLen, resumeHandle=..., /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetLocalGroupAddMembers(server: str, group: str, level, members: tuple[Incomplete, Incomplete], /) -> None: ... +def NetLocalGroupDelMembers(server: str, group: str, members: list[str], /) -> None: ... +def NetLocalGroupGetMembers( + server: str, groupName: str, level, resumeHandle: int = ..., prefLen: int = ..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetLocalGroupSetMembers(server: str, group: str, level, members: tuple[Incomplete, Incomplete], /) -> None: ... +def NetMessageBufferSend(domain: str, userName: str, fromName: str, message: str, /) -> None: ... +def NetMessageNameAdd(server, msgname, /) -> None: ... +def NetMessageNameDel(server, msgname, /) -> None: ... +def NetMessageNameEnum(Server, /) -> None: ... +def NetServerEnum( + server: str, level, _type, prefLen, domain: str | None = ..., resumeHandle: int = ..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetServerGetInfo(server: str, level, /): ... +def NetServerSetInfo(server: str, level, data, /) -> None: ... +def NetShareAdd(server: str, level, data, /) -> None: ... +def NetShareDel(server: str, shareName: str, reserved: int = ..., /) -> None: ... +def NetShareCheck(server: str, deviceName: str, /) -> tuple[Incomplete, Incomplete]: ... +def NetShareEnum( + server: str, level, prefLen, serverName, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetShareGetInfo(server: str, netname: str, level, /): ... +def NetShareSetInfo(server: str, netname: str, level, data, /) -> None: ... +def NetUserAdd(server: str, level, data, /) -> None: ... +def NetUserChangePassword(server: str, username: str, oldPassword: str, newPassword: str, /) -> None: ... +def NetUserEnum( + server: str, level, arg, prefLen, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetUserGetGroups(serverName: str, userName: str, /) -> list[tuple[Incomplete, Incomplete]]: ... +def NetUserGetInfo(server: str, username: str, level, /): ... +def NetUserGetLocalGroups(serverName: str, userName: str, flags, /) -> list[Incomplete]: ... +def NetUserSetInfo(server: str, username: str, level, data, /) -> None: ... +def NetUserDel(server: str, username: str, /) -> None: ... +def NetUserModalsGet(server: str, level, /): ... +def NetUserModalsSet(server: str, level, data, /) -> None: ... +def NetWkstaUserEnum( + server: str, level, prefLen, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetWkstaGetInfo(server: str, level, /): ... +def NetWkstaSetInfo(server: str, level, data, /) -> None: ... +def NetWkstaTransportEnum( + server: str, level, prefLen, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetWkstaTransportAdd(server: str, level, data, /) -> None: ... +def NetWkstaTransportDel(server: str, TransportName: str, ucond: int = ..., /) -> None: ... +def NetServerDiskEnum(server: str, level, /): ... +def NetUseAdd(server: str, level, data, /) -> None: ... +def NetUseDel(server: str, useName: str, forceCond: int = ..., /) -> None: ... +def NetUseEnum(server: str, level, prefLen, resumeHandle=..., /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetUseGetInfo(server: str, usename: str, level: int = ..., /): ... +def NetGetAnyDCName(server: str | None = ..., domain: str | None = ..., /) -> str: ... +def NetGetDCName(server: str | None = ..., domain: str | None = ..., /) -> str: ... +def NetSessionEnum( + level, server: str | None = ..., client: str | None = ..., username: str | None = ..., / +) -> tuple[Incomplete, ...]: ... +def NetSessionDel(server: str, client: str | None = ..., username: str | None = ..., /) -> None: ... +def NetSessionGetInfo(level, server: str, client: str, username: str, /): ... +def NetFileEnum( + level, servername: str | None = ..., basepath: str | None = ..., username: str | None = ..., / +) -> tuple[Incomplete, ...]: ... +def NetFileClose(servername: str, fileid, /) -> None: ... +def NetFileGetInfo(level, servername: str, fileid, /): ... +def NetStatisticsGet(server: str, service: str, level, options, /): ... +def NetServerComputerNameAdd(ServerName: str, EmulatedDomainName: str, EmulatedServerName: str, /) -> None: ... +def NetServerComputerNameDel(ServerName: str, EmulatedServerName: str, /) -> None: ... +def NetValidateName(Server: str, Name: str, NameType, Account: str | None = ..., Password: str | None = ..., /) -> None: ... +def NetValidatePasswordPolicy(Server: str, Qualifier, ValidationType, arg, /) -> None: ... +def NetLocalGroupAdd(server: str, level: int, data, /) -> None: ... +def NetLocalGroupDel(server: str, groupname: str, data, /) -> None: ... +def NetLocalGroupEnum(server: str, level: int, resumeHandle=..., prefLen: int = ..., /): ... +def NetLocalGroupGetInfo(server: str, groupname: str, level: int, /): ... +def NetLocalGroupSetInfo(server: str, groupname: str, level: int, data, /) -> None: ... + +SERVICE_SERVER: str +SERVICE_WORKSTATION: str +USE_FORCE: int +USE_LOTS_OF_FORCE: int +USE_NOFORCE: int diff --git a/stubs/pywin32/win32/win32pdh.pyi b/stubs/pywin32/win32/win32pdh.pyi new file mode 100644 index 000000000000..e70db79eb204 --- /dev/null +++ b/stubs/pywin32/win32/win32pdh.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def AddCounter(hQuery, path: str, userData: int = ..., /): ... +def AddEnglishCounter(hQuery, path: str, userData: int = ..., /): ... +def RemoveCounter(handle, /) -> None: ... +def EnumObjectItems(DataSource: str | None, machine: str | None, _object: str, detailLevel, flags=..., /): ... +def EnumObjects(DataSource: str | None, machine: str | None, detailLevel: int, refresh: bool = ..., /): ... +def OpenQuery(DataSource: Incomplete | None = ..., userData: int = ..., /): ... +def CloseQuery(handle, /) -> None: ... +def MakeCounterPath( + elements: tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete], flags=..., / +) -> str: ... +def GetCounterInfo(handle, bRetrieveExplainText, /) -> None: ... +def GetFormattedCounterValue(handle, _format, /) -> tuple[Incomplete, Incomplete]: ... +def CollectQueryData(hQuery, /) -> None: ... +def ValidatePath(path: str, /): ... +def ExpandCounterPath(wildCardPath: str, /) -> tuple[Incomplete, Incomplete]: ... +def ParseCounterPath( + path: str, flags=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... +def ParseInstanceName(instanceName: str, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def SetCounterScaleFactor(hCounter, factor, /) -> None: ... +def BrowseCounters( + Flags: tuple[Incomplete, ...] | None, + hWndOwner: int, + CallBack, + DefaultDetailLevel, + DialogBoxCaption: str | None = ..., + InitialPath: Incomplete | None = ..., + DataSource: Incomplete | None = ..., + ReturnMultiple: bool = ..., + CallBackArg: Incomplete | None = ..., +) -> str: ... +def ConnectMachine(machineName: str, /) -> str: ... +def LookupPerfIndexByName(machineName: str, instanceName: str, /): ... +def LookupPerfNameByIndex(machineName: str | None, index, /) -> str: ... +def GetFormattedCounterArray(handle: _win32typing.PyHANDLE | int | None, format: int, /) -> dict[Incomplete, Incomplete]: ... + +PDH_FMT_1000: int +PDH_FMT_ANSI: int +PDH_FMT_DOUBLE: int +PDH_FMT_LARGE: int +PDH_FMT_LONG: int +PDH_FMT_NODATA: int +PDH_FMT_NOSCALE: int +PDH_FMT_RAW: int +PDH_FMT_UNICODE: int +PDH_MAX_SCALE: int +PDH_MIN_SCALE: int +PDH_PATH_WBEM_INPUT: int +PDH_PATH_WBEM_RESULT: int +PDH_VERSION: int +PERF_DETAIL_ADVANCED: int +PERF_DETAIL_EXPERT: int +PERF_DETAIL_NOVICE: int +PERF_DETAIL_WIZARD: int + +class counter_status_error(Exception): ... + +PDH_FMT_NOCAP100: int diff --git a/stubs/pywin32/win32/win32pipe.pyi b/stubs/pywin32/win32/win32pipe.pyi new file mode 100644 index 000000000000..287f8aaeea85 --- /dev/null +++ b/stubs/pywin32/win32/win32pipe.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def GetNamedPipeHandleState( + hPipe: int, bGetCollectionData=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, str]: ... +def SetNamedPipeHandleState( + hPipe: int, Mode: int, MaxCollectionCount: Incomplete | None, CollectDataTimeout: Incomplete | None, / +) -> None: ... +def ConnectNamedPipe(hPipe: int, overlapped: _win32typing.PyOVERLAPPED | None = ..., /): ... +def TransactNamedPipe( + pipeName, + writeData: str, + buffer_bufSize: _win32typing.PyOVERLAPPEDReadBuffer, + overlapped: _win32typing.PyOVERLAPPED | None = ..., + /, +) -> str: ... +def CallNamedPipe(pipeName, data: str, bufSize, timeOut, /) -> str: ... +def CreatePipe(sa: _win32typing.PySECURITY_ATTRIBUTES, nSize: int, /) -> tuple[int, int]: ... +def FdCreatePipe(sa: _win32typing.PySECURITY_ATTRIBUTES, nSize, mode, /) -> tuple[Incomplete, Incomplete]: ... +def CreateNamedPipe( + pipeName: str, + openMode, + pipeMode, + nMaxInstances, + nOutBufferSize, + nInBufferSize, + nDefaultTimeOut, + sa: _win32typing.PySECURITY_ATTRIBUTES, + /, +) -> int: ... +def DisconnectNamedPipe(hFile: int, /) -> None: ... +def GetOverlappedResult(hFile: int, overlapped: _win32typing.PyOVERLAPPED, bWait: int | bool, /) -> int: ... +def WaitNamedPipe(pipeName: str, timeout, /) -> None: ... +def GetNamedPipeInfo(hNamedPipe: int, /) -> tuple[int, int, int, int]: ... +def PeekNamedPipe(hPipe: int, size: int, /) -> tuple[str, int, Incomplete]: ... +def GetNamedPipeClientProcessId(hPipe: int, /): ... +def GetNamedPipeServerProcessId(hPipe: int, /): ... +def GetNamedPipeClientSessionId(hPipe: int, /): ... +def GetNamedPipeServerSessionId(hPipe: int, /): ... +def popen(cmdstring: str, mode: str, /): ... +def popen2(*args): ... # incomplete +def popen3(*args): ... # incomplete +def popen4(*args): ... # incomplete + +FILE_FLAG_FIRST_PIPE_INSTANCE: int +PIPE_ACCEPT_REMOTE_CLIENTS: int +PIPE_REJECT_REMOTE_CLIENTS: int +NMPWAIT_NOWAIT: int +NMPWAIT_USE_DEFAULT_WAIT: int +NMPWAIT_WAIT_FOREVER: int +PIPE_ACCESS_DUPLEX: int +PIPE_ACCESS_INBOUND: int +PIPE_ACCESS_OUTBOUND: int +PIPE_NOWAIT: int +PIPE_READMODE_BYTE: int +PIPE_READMODE_MESSAGE: int +PIPE_TYPE_BYTE: int +PIPE_TYPE_MESSAGE: int +PIPE_UNLIMITED_INSTANCES: int +PIPE_WAIT: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32print.pyi b/stubs/pywin32/win32/win32print.pyi new file mode 100644 index 000000000000..224a05a570fb --- /dev/null +++ b/stubs/pywin32/win32/win32print.pyi @@ -0,0 +1,365 @@ +from typing import Final, Literal, overload + +import _win32typing + +def OpenPrinter(printer: str, Defaults: _win32typing.PrinterDefaults | None = None, /) -> _win32typing.PyPrinterHANDLE: ... + +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> _win32typing.PrinterInfo2Tuple: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[1], /) -> _win32typing.PrinterInfo1: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[2], /) -> _win32typing.PrinterInfo2: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[3], /) -> _win32typing.PrinterInfo3: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[4], /) -> _win32typing.PrinterInfo4: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[5], /) -> _win32typing.PrinterInfo5: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[6], /) -> _win32typing.PrinterInfo6: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[7], /) -> _win32typing.PrinterInfo7: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[8, 9], /) -> _win32typing.PrinterInfo89: ... + +@overload +def SetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[0], pPrinter: int | None, Command: int, /) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[2], pPrinter: _win32typing.PrinterInfo2, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[3], pPrinter: _win32typing.PrinterInfo3, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[4], pPrinter: _win32typing.PrinterInfo4, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[5], pPrinter: _win32typing.PrinterInfo5, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[6], pPrinter: _win32typing.PrinterInfo6, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[7], pPrinter: _win32typing.PrinterInfo7, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[8, 9], pPrinter: _win32typing.PrinterInfo89, Command: Literal[0], / +) -> None: ... + +def ClosePrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def AddPrinterConnection(printer: str, /) -> None: ... +def DeletePrinterConnection(printer: str, /) -> None: ... + +@overload +def EnumPrinters(flags: int, name: str | None = None, level: Literal[1] = 1, /) -> tuple[_win32typing.PrinterInfo1Tuple, ...]: ... +@overload +def EnumPrinters(flags: int, name: str | None, level: Literal[2], /) -> tuple[_win32typing.PrinterInfo2, ...]: ... +@overload +def EnumPrinters(flags: int, name: str | None, level: Literal[4], /) -> tuple[_win32typing.PrinterInfo4, ...]: ... +@overload +def EnumPrinters(flags: int, name: str | None, level: Literal[5], /) -> tuple[_win32typing.PrinterInfo5, ...]: ... + +def GetDefaultPrinter() -> str: ... +def GetDefaultPrinterW() -> str: ... +def SetDefaultPrinter(printer: str, /) -> None: ... +def SetDefaultPrinterW(Printer: str | None, /) -> None: ... +def StartDocPrinter( + hprinter: _win32typing.PyPrinterHANDLE, level: Literal[1], tuple: tuple[str, str | None, str | None], / +) -> int: ... +def EndDocPrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def AbortPrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def StartPagePrinter(hprinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def EndPagePrinter(hprinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def StartDoc(hdc: int, docinfo: tuple[str, str | None, str | None, int], /) -> int: ... +def EndDoc(hdc: int, /) -> None: ... +def AbortDoc(hdc: int, /) -> None: ... +def StartPage(hdc: int, /) -> None: ... +def EndPage(hdc: int, /) -> None: ... +def WritePrinter(hprinter: _win32typing.PyPrinterHANDLE, buf: bytes | bytearray | memoryview, /) -> int: ... + +@overload +def EnumJobs( + hPrinter: _win32typing.PyPrinterHANDLE, FirstJob: int, NoJobs: int, Level: Literal[1] = 1, / +) -> tuple[_win32typing.JobInfo1, ...]: ... +@overload +def EnumJobs( + hPrinter: _win32typing.PyPrinterHANDLE, FirstJob: int, NoJobs: int, Level: Literal[2], / +) -> tuple[_win32typing.JobInfo2, ...]: ... +@overload +def EnumJobs( + hPrinter: _win32typing.PyPrinterHANDLE, FirstJob: int, NoJobs: int, Level: Literal[3], / +) -> tuple[_win32typing.JobInfo3, ...]: ... + +@overload +def GetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[1] = 1, /) -> _win32typing.JobInfo1: ... +@overload +def GetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[2], /) -> _win32typing.JobInfo2: ... +@overload +def GetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[3], /) -> _win32typing.JobInfo3: ... + +@overload +def SetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[0], JobInfo: None, Command: int, /) -> None: ... +@overload +def SetJob( + hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[1], JobInfo: _win32typing.JobInfo1, Command: int, / +) -> None: ... +@overload +def SetJob( + hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[2], JobInfo: _win32typing.JobInfo2, Command: int, / +) -> None: ... +@overload +def SetJob( + hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[3], JobInfo: _win32typing.JobInfo3, Command: int, / +) -> None: ... + +def DocumentProperties( + HWnd: int, + hPrinter: _win32typing.PyPrinterHANDLE, + DeviceName: str, + DevModeOutput: _win32typing.PyDEVMODEW, + DevModeInput: _win32typing.PyDEVMODEW, + Mode: int, + /, +) -> int: ... +def EnumPrintProcessors(Server: str | None = None, Environment: str | None = None, /) -> tuple[str, ...]: ... +def EnumPrintProcessorDatatypes(ServerName: str | None, PrintProcessorName: str, /) -> tuple[str, ...]: ... + +@overload +def EnumPrinterDrivers( + Server: str | None = None, Environment: str | None = None, Level: Literal[1] = 1, / +) -> tuple[_win32typing.DriverInfo1, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[2], / +) -> tuple[_win32typing.DriverInfo2, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[3], / +) -> tuple[_win32typing.DriverInfo3, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[4], / +) -> tuple[_win32typing.DriverInfo4, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[5], / +) -> tuple[_win32typing.DriverInfo5, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[6], / +) -> tuple[_win32typing.DriverInfo6, ...]: ... + +def EnumForms(hprinter: _win32typing.PyPrinterHANDLE, /) -> tuple[_win32typing.FormInfo1, ...]: ... +def AddForm(hprinter: _win32typing.PyPrinterHANDLE, Form: _win32typing.FormInfo1, /) -> None: ... +def DeleteForm(hprinter: _win32typing.PyPrinterHANDLE, FormName: str, /) -> None: ... +def GetForm(hprinter: _win32typing.PyPrinterHANDLE, FormName: str, /) -> _win32typing.FormInfo1: ... +def SetForm(hprinter: _win32typing.PyPrinterHANDLE, FormName: str, Form: _win32typing.FormInfo1, /) -> None: ... +def AddJob(hprinter: _win32typing.PyPrinterHANDLE, /) -> tuple[str, int]: ... +def ScheduleJob(hprinter: _win32typing.PyPrinterHANDLE, JobId: int, /) -> None: ... + +@overload +# DC_MINEXTENT, DC_MAXEXTENT +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[4, 5], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> _win32typing.PrinterExtents: ... +@overload +# DC_ENUMRESOLUTIONS +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[13], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[_win32typing.PrinterDpi, ...]: ... +@overload +# DC_PAPERS, DC_BINS, DC_NUP, DC_MEDIATYPES +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[2, 6, 33, 35], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[int, ...]: ... +@overload +# DC_BINNAMES, DC_FILEDEPENDENCIES, DC_PAPERNAMES, DC_PERSONALITY, DC_MEDIAREADY, DC_MEDIATYPENAMES +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[12, 14, 16, 25, 29, 34], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[str, ...]: ... +@overload +# DC_PAPERSIZE +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[3], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[_win32typing.PrinterPaperSize, ...]: ... +@overload +# DC_FIELDS, DC_DUPLEX, DC_SIZE, DC_EXTRA, DC_VERSION, DC_DRIVER, DC_TRUETYPE, DC_ORIENTATION, DC_COPIES +# DC_COLLATE, DC_PRINTRATE, DC_PRINTRATEUNIT, DC_PRINTERMEM, DC_STAPLE, DC_PRINTRATEPPM, DC_COLORDEVICE +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, + Port: str, + Capability: Literal[1, 7, 8, 9, 10, 11, 15, 17, 18, 22, 26, 27, 28, 30, 31, 32], + DEVMODE: _win32typing.PyDEVMODEW | None = None, + /, +) -> int: ... +@overload +def DeviceCapabilities(Device: str, Port: str, Capability: int, DEVMODE: _win32typing.PyDEVMODEW | None = None, /) -> int: ... + +def GetDeviceCaps(hdc: int | _win32typing.PyHANDLE, Index: int, /) -> int: ... + +@overload +def EnumMonitors(Name: str | None, Level: Literal[1], /) -> tuple[_win32typing.MonitorInfo1, ...]: ... +@overload +def EnumMonitors(Name: str | None, Level: Literal[2], /) -> tuple[_win32typing.MonitorInfo2, ...]: ... + +@overload +def EnumPorts(Name: str | None, Level: Literal[1], /) -> tuple[_win32typing.PortInfo1, ...]: ... +@overload +def EnumPorts(Name: str | None, Level: Literal[2], /) -> tuple[_win32typing.PortInfo2, ...]: ... + +def GetPrintProcessorDirectory(Name: str | None = None, Environment: str | None = None, /) -> str: ... +def GetPrinterDriverDirectory(Name: str | None = None, Environment: str | None = None, /) -> str: ... +def AddPrinter(Name: str | None, Level: Literal[2], pPrinter: _win32typing.PrinterInfo2, /) -> _win32typing.PyPrinterHANDLE: ... +def DeletePrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def DeletePrinterDriver(Server: str | None, Environment: str | None, DriverName: str, /) -> None: ... +def DeletePrinterDriverEx( + Server: str | None, Environment: str | None, DriverName: str, DeleteFlag: int, VersionFlag: Literal[0, 1, 2, 3], / +) -> None: ... +def FlushPrinter(Printer: _win32typing.PyPrinterHANDLE, Buf: bytes, Sleep: int, /) -> int: ... + +DEF_PRIORITY: int +DI_APPBANDING: int +DI_ROPS_READ_DESTINATION: int +DPD_DELETE_ALL_FILES: int +DPD_DELETE_SPECIFIC_VERSION: int +DPD_DELETE_UNUSED_FILES: int +DSPRINT_PENDING: int +DSPRINT_PUBLISH: int +DSPRINT_REPUBLISH: int +DSPRINT_UNPUBLISH: int +DSPRINT_UPDATE: int +FORM_BUILTIN: int +FORM_PRINTER: int +FORM_USER: int +JOB_ACCESS_ADMINISTER: int +JOB_ACCESS_READ: int +JOB_ALL_ACCESS: int +JOB_CONTROL_CANCEL: int +JOB_CONTROL_DELETE: int +JOB_CONTROL_LAST_PAGE_EJECTED: int +JOB_CONTROL_PAUSE: int +JOB_CONTROL_RESTART: int +JOB_CONTROL_RESUME: int +JOB_CONTROL_SENT_TO_PRINTER: int +JOB_EXECUTE: int +JOB_INFO_1: int +JOB_POSITION_UNSPECIFIED: int +JOB_READ: int +JOB_STATUS_BLOCKED_DEVQ: int +JOB_STATUS_COMPLETE: int +JOB_STATUS_DELETED: int +JOB_STATUS_DELETING: int +JOB_STATUS_ERROR: int +JOB_STATUS_OFFLINE: int +JOB_STATUS_PAPEROUT: int +JOB_STATUS_PAUSED: int +JOB_STATUS_PRINTED: int +JOB_STATUS_PRINTING: int +JOB_STATUS_RESTART: int +JOB_STATUS_SPOOLING: int +JOB_STATUS_USER_INTERVENTION: int +JOB_WRITE: int +MAX_PRIORITY: int +MIN_PRIORITY: int +PORT_STATUS_DOOR_OPEN: int +PORT_STATUS_NO_TONER: int +PORT_STATUS_OFFLINE: int +PORT_STATUS_OUTPUT_BIN_FULL: int +PORT_STATUS_OUT_OF_MEMORY: int +PORT_STATUS_PAPER_JAM: int +PORT_STATUS_PAPER_OUT: int +PORT_STATUS_PAPER_PROBLEM: int +PORT_STATUS_POWER_SAVE: int +PORT_STATUS_TONER_LOW: int +PORT_STATUS_TYPE_ERROR: int +PORT_STATUS_TYPE_INFO: int +PORT_STATUS_TYPE_WARNING: int +PORT_STATUS_USER_INTERVENTION: int +PORT_STATUS_WARMING_UP: int +PORT_TYPE_NET_ATTACHED: int +PORT_TYPE_READ: int +PORT_TYPE_REDIRECTED: int +PORT_TYPE_WRITE: int +PRINTER_ACCESS_ADMINISTER: int +PRINTER_ACCESS_USE: int +PRINTER_ALL_ACCESS: int +PRINTER_ATTRIBUTE_DEFAULT: int +PRINTER_ATTRIBUTE_DIRECT: int +PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST: int +PRINTER_ATTRIBUTE_ENABLE_BIDI: int +PRINTER_ATTRIBUTE_ENABLE_DEVQ: int +PRINTER_ATTRIBUTE_FAX: int +PRINTER_ATTRIBUTE_HIDDEN: int +PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS: int +PRINTER_ATTRIBUTE_LOCAL: int +PRINTER_ATTRIBUTE_NETWORK: int +PRINTER_ATTRIBUTE_PUBLISHED: int +PRINTER_ATTRIBUTE_QUEUED: int +PRINTER_ATTRIBUTE_RAW_ONLY: int +PRINTER_ATTRIBUTE_SHARED: int +PRINTER_ATTRIBUTE_TS: int +PRINTER_ATTRIBUTE_WORK_OFFLINE: int +PRINTER_CONTROL_PAUSE: int +PRINTER_CONTROL_PURGE: int +PRINTER_CONTROL_RESUME: int +PRINTER_CONTROL_SET_STATUS: int +PRINTER_ENUM_CONNECTIONS: int +PRINTER_ENUM_CONTAINER: int +PRINTER_ENUM_DEFAULT: int +PRINTER_ENUM_EXPAND: int +PRINTER_ENUM_ICON1: int +PRINTER_ENUM_ICON2: int +PRINTER_ENUM_ICON3: int +PRINTER_ENUM_ICON4: int +PRINTER_ENUM_ICON5: int +PRINTER_ENUM_ICON6: int +PRINTER_ENUM_ICON7: int +PRINTER_ENUM_ICON8: int +PRINTER_ENUM_LOCAL: int +PRINTER_ENUM_NAME: int +PRINTER_ENUM_NETWORK: int +PRINTER_ENUM_REMOTE: int +PRINTER_ENUM_SHARED: int +PRINTER_EXECUTE: int +PRINTER_INFO_1: Final = 1 +PRINTER_READ: int +PRINTER_STATUS_BUSY: int +PRINTER_STATUS_DOOR_OPEN: int +PRINTER_STATUS_ERROR: int +PRINTER_STATUS_INITIALIZING: int +PRINTER_STATUS_IO_ACTIVE: int +PRINTER_STATUS_MANUAL_FEED: int +PRINTER_STATUS_NOT_AVAILABLE: int +PRINTER_STATUS_NO_TONER: int +PRINTER_STATUS_OFFLINE: int +PRINTER_STATUS_OUTPUT_BIN_FULL: int +PRINTER_STATUS_OUT_OF_MEMORY: int +PRINTER_STATUS_PAGE_PUNT: int +PRINTER_STATUS_PAPER_JAM: int +PRINTER_STATUS_PAPER_OUT: int +PRINTER_STATUS_PAPER_PROBLEM: int +PRINTER_STATUS_PAUSED: int +PRINTER_STATUS_PENDING_DELETION: int +PRINTER_STATUS_POWER_SAVE: int +PRINTER_STATUS_PRINTING: int +PRINTER_STATUS_PROCESSING: int +PRINTER_STATUS_SERVER_UNKNOWN: int +PRINTER_STATUS_TONER_LOW: int +PRINTER_STATUS_USER_INTERVENTION: int +PRINTER_STATUS_WAITING: int +PRINTER_STATUS_WARMING_UP: int +PRINTER_WRITE: int +SERVER_ACCESS_ADMINISTER: int +SERVER_ACCESS_ENUMERATE: int +SERVER_ALL_ACCESS: int +SERVER_EXECUTE: int +SERVER_READ: int +SERVER_WRITE: int diff --git a/stubs/pywin32/win32/win32process.pyi b/stubs/pywin32/win32/win32process.pyi new file mode 100644 index 000000000000..4dc05a0d8378 --- /dev/null +++ b/stubs/pywin32/win32/win32process.pyi @@ -0,0 +1,124 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def STARTUPINFO() -> _win32typing.PySTARTUPINFO: ... +def beginthreadex(sa: _win32typing.PySECURITY_ATTRIBUTES, stackSize, entryPoint, args, flags, /) -> tuple[int, Incomplete]: ... +def CreateRemoteThread( + hprocess: int, sa: _win32typing.PySECURITY_ATTRIBUTES, stackSize, entryPoint, Parameter, flags, / +) -> tuple[int, Incomplete]: ... +def CreateProcess( + appName: str | None, + commandLine: str, + processAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, + threadAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, + bInheritHandles: int | bool, + dwCreationFlags: int, + newEnvironment: dict[str, str] | None, + currentDirectory: str | None, + startupinfo: _win32typing.PySTARTUPINFO, + /, +) -> tuple[int, int, Incomplete, Incomplete]: ... +def CreateProcessAsUser( + hToken: int, + appName: str, + commandLine: str, + processAttributes: _win32typing.PySECURITY_ATTRIBUTES, + threadAttributes: _win32typing.PySECURITY_ATTRIBUTES, + bInheritHandles, + dwCreationFlags, + newEnvironment, + currentDirectory: str, + startupinfo: _win32typing.PySTARTUPINFO, + /, +) -> tuple[int, int, Incomplete, Incomplete]: ... +def GetCurrentProcess() -> int: ... +def GetProcessVersion(processId, /): ... +def GetCurrentProcessId(): ... +def GetStartupInfo() -> _win32typing.PySTARTUPINFO: ... +def GetPriorityClass(handle: int, /): ... +def GetExitCodeThread(handle: int, /): ... +def GetExitCodeProcess(handle: int, /) -> int: ... +def GetWindowThreadProcessId(hwnd: int | None, /) -> tuple[int, int]: ... +def SetThreadPriority(handle: int, nPriority, /) -> None: ... +def GetThreadPriority(handle: int, /): ... +def GetProcessPriorityBoost(Process: int, /): ... +def SetProcessPriorityBoost(Process: int, DisablePriorityBoost, /) -> None: ... +def GetThreadPriorityBoost(Thread: int, /): ... +def SetThreadPriorityBoost(Thread: int, DisablePriorityBoost, /) -> None: ... +def GetThreadIOPendingFlag(Thread: int, /): ... +def GetThreadTimes(Thread: int, /): ... +def GetProcessId(Process: int, /): ... +def SetPriorityClass(handle: int, dwPriorityClass: int, /) -> None: ... +def AttachThreadInput(idAttach, idAttachTo, Attach, /) -> None: ... +def SetThreadIdealProcessor(handle: int, dwIdealProcessor, /): ... +def GetProcessAffinityMask(hProcess: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetProcessAffinityMask(hProcess: int, mask, /) -> None: ... +def SetThreadAffinityMask(hThread: int, ThreadAffinityMask, /): ... +def SuspendThread(handle: int, /): ... +def ResumeThread(handle: int, /): ... +def TerminateProcess(handle: int, exitCode: int, /) -> None: ... +def ExitProcess(exitCode, /) -> None: ... +def EnumProcesses() -> tuple[Incomplete, Incomplete]: ... +def EnumProcessModules(hProcess: int, /) -> tuple[Incomplete, Incomplete]: ... +def EnumProcessModulesEx(hProcess: int, FilterFlag, /) -> tuple[Incomplete, Incomplete]: ... +def GetModuleFileNameEx(hProcess: int, hModule: int, /): ... +def GetProcessMemoryInfo(hProcess: int, /): ... +def GetProcessTimes(hProcess: int, /): ... +def GetProcessIoCounters(hProcess: int, /): ... +def GetProcessWindowStation() -> None: ... +def GetProcessWorkingSetSize(hProcess: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetProcessWorkingSetSize(hProcess: int, MinimumWorkingSetSize, MaximumWorkingSetSize, /) -> None: ... +def GetProcessShutdownParameters() -> tuple[Incomplete, Incomplete]: ... +def SetProcessShutdownParameters(Level, Flags, /) -> None: ... +def GetGuiResources(Process: int, Flags, /): ... +def IsWow64Process(Process: int | None = ..., /) -> bool: ... +def ReadProcessMemory(hProcess, address: int, size: int, /) -> bytes: ... +def VirtualAllocEx(hProcess, address: int, size: int, allocationType: int, flProtect: int, /): ... +def VirtualFreeEx(hProcess, address: int, size: int, freeType: int, /): ... +def WriteProcessMemory(hProcess, address, buf, /) -> int: ... + +ABOVE_NORMAL_PRIORITY_CLASS: int +BELOW_NORMAL_PRIORITY_CLASS: int +CREATE_BREAKAWAY_FROM_JOB: int +CREATE_DEFAULT_ERROR_MODE: int +CREATE_NEW_CONSOLE: int +CREATE_NEW_PROCESS_GROUP: int +CREATE_NO_WINDOW: int +CREATE_PRESERVE_CODE_AUTHZ_LEVEL: int +CREATE_SEPARATE_WOW_VDM: int +CREATE_SHARED_WOW_VDM: int +CREATE_SUSPENDED: int +CREATE_UNICODE_ENVIRONMENT: int +DEBUG_ONLY_THIS_PROCESS: int +DEBUG_PROCESS: int +DETACHED_PROCESS: int +HIGH_PRIORITY_CLASS: int +IDLE_PRIORITY_CLASS: int +MAXIMUM_PROCESSORS: int +NORMAL_PRIORITY_CLASS: int +REALTIME_PRIORITY_CLASS: int +STARTF_FORCEOFFFEEDBACK: int +STARTF_FORCEONFEEDBACK: int +STARTF_RUNFULLSCREEN: int +STARTF_USECOUNTCHARS: int +STARTF_USEFILLATTRIBUTE: int +STARTF_USEPOSITION: int +STARTF_USESHOWWINDOW: int +STARTF_USESIZE: int +STARTF_USESTDHANDLES: int +THREAD_MODE_BACKGROUND_BEGIN: int +THREAD_MODE_BACKGROUND_END: int +THREAD_PRIORITY_ABOVE_NORMAL: int +THREAD_PRIORITY_BELOW_NORMAL: int +THREAD_PRIORITY_HIGHEST: int +THREAD_PRIORITY_IDLE: int +THREAD_PRIORITY_LOWEST: int +THREAD_PRIORITY_NORMAL: int +THREAD_PRIORITY_TIME_CRITICAL: int +LIST_MODULES_32BIT: int +LIST_MODULES_64BIT: int +LIST_MODULES_ALL: int +LIST_MODULES_DEFAULT: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32profile.pyi b/stubs/pywin32/win32/win32profile.pyi new file mode 100644 index 000000000000..155a77cbdda2 --- /dev/null +++ b/stubs/pywin32/win32/win32profile.pyi @@ -0,0 +1,19 @@ +import _win32typing + +def CreateEnvironmentBlock(Token: int, Inherit): ... +def DeleteProfile(SidString: str, ProfilePath: str | None = ..., ComputerName: str | None = ...) -> None: ... +def ExpandEnvironmentStringsForUser(Token: int, Src: str) -> str: ... +def GetAllUsersProfileDirectory() -> str: ... +def GetDefaultUserProfileDirectory() -> str: ... +def GetEnvironmentStrings(): ... +def GetProfilesDirectory() -> str: ... +def GetProfileType(): ... +def GetUserProfileDirectory(Token: int) -> str: ... +def LoadUserProfile(hToken: int, ProfileInfo: _win32typing.PyPROFILEINFO) -> _win32typing.PyHKEY: ... +def UnloadUserProfile(Token: int, Profile: _win32typing.PyHKEY) -> None: ... + +PI_APPLYPOLICY: int +PI_NOUI: int +PT_MANDATORY: int +PT_ROAMING: int +PT_TEMPORARY: int diff --git a/stubs/pywin32/win32/win32ras.pyi b/stubs/pywin32/win32/win32ras.pyi new file mode 100644 index 000000000000..0dfce818c08f --- /dev/null +++ b/stubs/pywin32/win32/win32ras.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing import Final, Literal + +import _win32typing +from win32.lib.pywintypes import error as error + +def CreatePhonebookEntry(hWnd: int | _win32typing.PyHANDLE | None, fileName: str = ..., /) -> None: ... +def Dial( + dialExtensions: _win32typing.PyRASDIALEXTENSIONS | None, + fileName: str | None, + RasDialParams: Iterable[str], + callback: int | Callable[..., Incomplete] | None, + /, +) -> tuple[int, int]: ... +def EditPhonebookEntry(hWnd: int | _win32typing.PyHANDLE | None, fileName: str | None, entryName: str, /) -> None: ... +def EnumConnections() -> list[tuple[int, str, str, str]]: ... +def EnumEntries(reserved: str | None = None, fileName: str | None = None, /) -> tuple[str, ...]: ... +def GetConnectStatus(hrasconn: int | _win32typing.PyHANDLE | None, /) -> tuple[int, int, str, str]: ... +def GetEapUserIdentity( + phoneBook: str | None, entry: str, flags: int, hwnd: int | _win32typing.PyHANDLE | None = None, / +) -> _win32typing.PyRASEAPUSERIDENTITY | None: ... +def GetEntryDialParams(fileName: str | None, entryName: str, /) -> tuple[tuple[str, str, str, str, str, str], bool]: ... +def GetErrorString(error: int, /) -> str: ... +def HangUp(hras: int | _win32typing.PyHANDLE | None, /) -> None: ... +def IsHandleValid(hras: int | _win32typing.PyHANDLE | None, /) -> bool: ... +def SetEntryDialParams(fileName: str | None, RasDialParams: Iterable[str], bSavePassword: bool | Literal[0, 1], /) -> None: ... +def RASDIALEXTENSIONS() -> _win32typing.PyRASDIALEXTENSIONS: ... + +RASCS_OpenPort: Final[int] +RASCS_PortOpened: Final[int] +RASCS_ConnectDevice: Final[int] +RASCS_DeviceConnected: Final[int] +RASCS_AllDevicesConnected: Final[int] +RASCS_Authenticate: Final[int] +RASCS_AuthNotify: Final[int] +RASCS_AuthRetry: Final[int] +RASCS_AuthCallback: Final[int] +RASCS_AuthChangePassword: Final[int] +RASCS_AuthProject: Final[int] +RASCS_AuthLinkSpeed: Final[int] +RASCS_AuthAck: Final[int] +RASCS_ReAuthenticate: Final[int] +RASCS_Authenticated: Final[int] +RASCS_PrepareForCallback: Final[int] +RASCS_WaitForModemReset: Final[int] +RASCS_WaitForCallback: Final[int] +RASCS_Projected: Final[int] +RASCS_StartAuthentication: Final[int] +RASCS_CallbackComplete: Final[int] +RASCS_LogonNetwork: Final[int] +RASCS_Interactive: Final[int] +RASCS_RetryAuthentication: Final[int] +RASCS_CallbackSetByCaller: Final[int] +RASCS_PasswordExpired: Final[int] +RASCS_Connected: Final[int] +RASCS_Disconnected: Final[int] +RASEAPF_NonInteractive: Final[int] +RASEAPF_Logon: Final[int] +RASEAPF_Preview: Final[int] diff --git a/stubs/pywin32/win32/win32security.pyi b/stubs/pywin32/win32/win32security.pyi new file mode 100644 index 000000000000..477a5d2f63d1 --- /dev/null +++ b/stubs/pywin32/win32/win32security.pyi @@ -0,0 +1,606 @@ +from _typeshed import Incomplete +from typing import overload +from typing_extensions import deprecated + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +def DsGetSpn( + ServiceType, + ServiceClass: str, + ServiceName: str, + InstancePort: int = ..., + InstanceNames: tuple[str, ...] | None = ..., + InstancePorts: tuple[Incomplete, ...] | None = ..., + /, +) -> tuple[str, ...]: ... +def DsWriteAccountSpn(hDS: _win32typing.PyDS_HANDLE, Operation, Account: str, Spns: tuple[str, ...], /) -> None: ... +def DsBind(DomainController: str, DnsDomainName: str, /) -> _win32typing.PyDS_HANDLE: ... +def DsUnBind(hDS: _win32typing.PyDS_HANDLE, /) -> None: ... +def DsGetDcName( + computerName: str | None = ..., + domainName: str | None = ..., + domainGUID: _win32typing.PyIID | None = ..., + siteName: str | None = ..., + flags: int = ..., +): ... +def DsCrackNames( + hds: _win32typing.PyDS_HANDLE, flags, formatOffered, formatDesired, names: list[Incomplete], / +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def ACL(bufSize: int = ..., /) -> _win32typing.PyACL: ... +def SID() -> _win32typing.PySID: ... +def SECURITY_ATTRIBUTES() -> _win32typing.PySECURITY_ATTRIBUTES: ... +def SECURITY_DESCRIPTOR() -> _win32typing.PySECURITY_DESCRIPTOR: ... +def ImpersonateNamedPipeClient(handle, /) -> None: ... +def ImpersonateLoggedOnUser(handle: int, /) -> None: ... +def ImpersonateAnonymousToken(ThreadHandle: int, /) -> None: ... +def IsTokenRestricted(TokenHandle: int | None, /) -> bool: ... +def RevertToSelf() -> None: ... +def LogonUser(Username: str, Domain: str | None, Password: str, LogonType: int, LogonProvider: int) -> _win32typing.PyHANDLE: ... +def LogonUserEx( + Username: str, Domain: str, Password: str, LogonType, LogonProvider +) -> tuple[int, _win32typing.PySID, Incomplete, Incomplete]: ... +def LookupAccountName(systemName: str | None, accountName: str, /) -> tuple[_win32typing.PySID, str, int]: ... +def LookupAccountSid(systemName: str | None, sid: _win32typing.PySID, /) -> tuple[str, str, Incomplete]: ... +def GetBinarySid(SID: str, /) -> _win32typing.PySID: ... +def SetSecurityInfo( + handle: int, + ObjectType, + SecurityInfo, + Owner: _win32typing.PySID, + Group: _win32typing.PySID, + Dacl: _win32typing.PyACL, + Sacl: _win32typing.PyACL, + /, +) -> None: ... +def GetSecurityInfo(handle: int, ObjectType, SecurityInfo, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetNamedSecurityInfo( + ObjectName: str, + ObjectType: int, + SecurityInfo: int, + Owner: _win32typing.PySID | None, + Group: _win32typing.PySID | None, + Dacl: _win32typing.PyACL | None, + Sacl: _win32typing.PyACL | None, + /, +) -> None: ... +def GetNamedSecurityInfo(ObjectName: str, ObjectType: int, SecurityInfo: int, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def OpenProcessToken(processHandle, desiredAccess, /) -> int: ... +def LookupPrivilegeValue(systemName: str, privilegeName: str, /) -> int: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def LookupPrivilegeName(SystemName: str, luid: tuple[int, int], /) -> str: ... +@overload +def LookupPrivilegeName(SystemName: str, luid: int, /) -> str: ... + +def LookupPrivilegeDisplayName(SystemName: str, Name: str, /) -> str: ... +def AdjustTokenPrivileges( + TokenHandle: int, bDisableAllPrivileges, NewState: _win32typing.PyTOKEN_PRIVILEGES +) -> _win32typing.PyTOKEN_PRIVILEGES: ... +def AdjustTokenGroups(TokenHandle: int, ResetToDefault, NewState: _win32typing.PyTOKEN_GROUPS) -> _win32typing.PyTOKEN_GROUPS: ... +def GetTokenInformation(TokenHandle: int, TokenInformationClass, /): ... +def OpenThreadToken(handle: int, desiredAccess, openAsSelf, /): ... +def SetThreadToken(Thread: int, Token: int, /) -> None: ... +def GetFileSecurity(filename: str, info: int = ..., /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetFileSecurity(filename: str, info: int, security: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def GetUserObjectSecurity(handle: int, info, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetUserObjectSecurity(handle: int, info, security: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def GetKernelObjectSecurity(handle: int, info, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetKernelObjectSecurity(handle: int, info, security: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def SetTokenInformation(TokenHandle: int, TokenInformationClass, TokenInformation, /) -> None: ... +def LsaOpenPolicy(system_name: str, access_mask, /) -> _win32typing.PyLSA_HANDLE: ... +def LsaClose(PolicyHandle: int, /) -> None: ... +def LsaQueryInformationPolicy(PolicyHandle: _win32typing.PyLSA_HANDLE, InformationClass, /) -> None: ... +def LsaSetInformationPolicy(PolicyHandle: _win32typing.PyLSA_HANDLE, InformationClass, Information, /) -> None: ... +def LsaAddAccountRights( + PolicyHandle: _win32typing.PyLSA_HANDLE, AccountSid: _win32typing.PySID, UserRights: tuple[Incomplete, ...] +) -> None: ... +def LsaRemoveAccountRights( + PolicyHandle: _win32typing.PyLSA_HANDLE, AccountSid: _win32typing.PySID, AllRights, UserRights: tuple[Incomplete, ...] +) -> None: ... +def LsaEnumerateAccountRights(PolicyHandle: _win32typing.PyLSA_HANDLE, AccountSid: _win32typing.PySID, /) -> list[str]: ... +def LsaEnumerateAccountsWithUserRight( + PolicyHandle: _win32typing.PyLSA_HANDLE, UserRight, / +) -> tuple[_win32typing.PySID, ...]: ... +def ConvertSidToStringSid(Sid: _win32typing.PySID, /) -> str: ... +def ConvertStringSidToSid(StringSid: str, /) -> _win32typing.PySID: ... +def ConvertSecurityDescriptorToStringSecurityDescriptor( + SecurityDescriptor: _win32typing.PySECURITY_DESCRIPTOR, RequestedStringSDRevision, SecurityInformation, / +) -> str: ... +def ConvertStringSecurityDescriptorToSecurityDescriptor( + StringSecurityDescriptor: str, StringSDRevision, / +) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def LsaStorePrivateData(PolicyHandle: _win32typing.PyLSA_HANDLE, KeyName: str, PrivateData, /) -> None: ... +def LsaRetrievePrivateData(PolicyHandle: _win32typing.PyLSA_HANDLE, KeyName: str, /) -> str: ... +def LsaRegisterPolicyChangeNotification(InformationClass, NotificationEventHandle: int, /) -> None: ... +def LsaUnregisterPolicyChangeNotification(InformationClass, NotificationEventHandle: int, /) -> None: ... +def CryptEnumProviders() -> list[tuple[str, Incomplete]]: ... +def EnumerateSecurityPackages() -> tuple[Incomplete, ...]: ... +def AllocateLocallyUniqueId() -> None: ... +def ImpersonateSelf(ImpersonationLevel, /) -> None: ... +def DuplicateToken(ExistingTokenHandle: int, ImpersonationLevel, /) -> int: ... +def DuplicateTokenEx( + ExistingToken: int, + ImpersonationLevel, + DesiredAccess, + TokenType, + TokenAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> int: ... +def CheckTokenMembership(TokenHandle: int, SidToCheck: _win32typing.PySID, /): ... +def CreateRestrictedToken( + ExistingTokenHandle: int, + Flags, + SidsToDisable: tuple[_win32typing.PySID_AND_ATTRIBUTES, ...], + PrivilegesToDelete: tuple[_win32typing.PyLUID_AND_ATTRIBUTES, ...], + SidsToRestrict: tuple[_win32typing.PySID_AND_ATTRIBUTES, ...], +) -> int: ... +def LsaRegisterLogonProcess(LogonProcessName: str, /) -> _win32typing.PyLsaLogon_HANDLE: ... +def LsaConnectUntrusted() -> _win32typing.PyLsaLogon_HANDLE: ... +def LsaDeregisterLogonProcess(LsaHandle: _win32typing.PyLsaLogon_HANDLE, /) -> None: ... +def LsaLookupAuthenticationPackage(LsaHandle: _win32typing.PyLsaLogon_HANDLE, PackageName: str, /): ... +def LsaEnumerateLogonSessions() -> tuple[Incomplete, ...]: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def LsaGetLogonSessionData(LogonId: tuple[int, int], /) -> tuple[Incomplete, ...]: ... +@overload +def LsaGetLogonSessionData(LogonId: int, /) -> tuple[Incomplete, ...]: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def AcquireCredentialsHandle( + Principal, Package, CredentialUse, LogonID: tuple[int, int], AuthData, / +) -> tuple[_win32typing.PyCredHandle, TimeType]: ... +@overload +def AcquireCredentialsHandle( + Principal, Package, CredentialUse, LogonID: int | None, AuthData, / +) -> tuple[_win32typing.PyCredHandle, TimeType]: ... + +def InitializeSecurityContext( + Credential: _win32typing.PyCredHandle, + Context: _win32typing.PyCtxtHandle, + TargetName, + ContextReq, + TargetDataRep, + pInput: _win32typing.PySecBufferDesc, + NewContext: _win32typing.PyCtxtHandle, + pOutput: _win32typing.PySecBufferDesc, + /, +) -> tuple[Incomplete, Incomplete, TimeType]: ... +def AcceptSecurityContext( + Credential: _win32typing.PyCredHandle, + Context: _win32typing.PyCtxtHandle, + pInput: _win32typing.PySecBufferDesc, + ContextReq, + TargetDataRep, + NewContext: _win32typing.PyCtxtHandle, + pOutput: _win32typing.PySecBufferDesc, + /, +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def QuerySecurityPackageInfo(PackageName, /): ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def LsaCallAuthenticationPackage( + LsaHandle: _win32typing.PyLsaLogon_HANDLE, AuthenticationPackage, MessageType, ProtocolSubmitBuffer: tuple[int, int], / +) -> None: ... +@overload +def LsaCallAuthenticationPackage( + LsaHandle: _win32typing.PyLsaLogon_HANDLE, AuthenticationPackage, MessageType, ProtocolSubmitBuffer, / +) -> None: ... + +def TranslateName(accountName: str, accountNameFormat, accountNameFormat1, numChars=..., /) -> str: ... +def CreateWellKnownSid(WellKnownSidType, DomainSid: _win32typing.PySID | None = ..., /) -> _win32typing.PySID: ... +def MapGenericMask(AccessMask, GenericMapping: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /): ... + +ACCESS_ALLOWED_ACE_TYPE: int +ACCESS_ALLOWED_OBJECT_ACE_TYPE: int +ACCESS_DENIED_ACE_TYPE: int +ACCESS_DENIED_OBJECT_ACE_TYPE: int +ACL_REVISION: int +ACL_REVISION_DS: int +AuditCategoryAccountLogon: int +AuditCategoryAccountManagement: int +AuditCategoryDetailedTracking: int +AuditCategoryDirectoryServiceAccess: int +AuditCategoryLogon: int +AuditCategoryObjectAccess: int +AuditCategoryPolicyChange: int +AuditCategoryPrivilegeUse: int +AuditCategorySystem: int +CONTAINER_INHERIT_ACE: int +DACL_SECURITY_INFORMATION: int +DENY_ACCESS: int +DISABLE_MAX_PRIVILEGE: int +DS_SPN_ADD_SPN_OP: int +DS_SPN_DELETE_SPN_OP: int +DS_SPN_DN_HOST: int +DS_SPN_DNS_HOST: int +DS_SPN_DOMAIN: int +DS_SPN_NB_DOMAIN: int +DS_SPN_NB_HOST: int +DS_SPN_REPLACE_SPN_OP: int +DS_SPN_SERVICE: int +FAILED_ACCESS_ACE_FLAG: int +GRANT_ACCESS: int +GROUP_SECURITY_INFORMATION: int +INHERIT_ONLY_ACE: int +INHERITED_ACE: int +LABEL_SECURITY_INFORMATION: int +LOGON32_LOGON_BATCH: int +LOGON32_LOGON_INTERACTIVE: int +LOGON32_LOGON_NETWORK: int +LOGON32_LOGON_NETWORK_CLEARTEXT: int +LOGON32_LOGON_NEW_CREDENTIALS: int +LOGON32_LOGON_SERVICE: int +LOGON32_LOGON_UNLOCK: int +LOGON32_PROVIDER_DEFAULT: int +LOGON32_PROVIDER_WINNT35: int +LOGON32_PROVIDER_WINNT40: int +LOGON32_PROVIDER_WINNT50: int +NO_INHERITANCE: int +NO_PROPAGATE_INHERIT_ACE: int +NOT_USED_ACCESS: int +OBJECT_INHERIT_ACE: int +OWNER_SECURITY_INFORMATION: int +POLICY_ALL_ACCESS: int +POLICY_AUDIT_EVENT_FAILURE: int +POLICY_AUDIT_EVENT_NONE: int +POLICY_AUDIT_EVENT_SUCCESS: int +POLICY_AUDIT_EVENT_UNCHANGED: int +POLICY_AUDIT_LOG_ADMIN: int +POLICY_CREATE_ACCOUNT: int +POLICY_CREATE_PRIVILEGE: int +POLICY_CREATE_SECRET: int +POLICY_EXECUTE: int +POLICY_GET_PRIVATE_INFORMATION: int +POLICY_LOOKUP_NAMES: int +POLICY_NOTIFICATION: int +POLICY_READ: int +POLICY_SERVER_ADMIN: int +POLICY_SET_AUDIT_REQUIREMENTS: int +POLICY_SET_DEFAULT_QUOTA_LIMITS: int +POLICY_TRUST_ADMIN: int +POLICY_VIEW_AUDIT_INFORMATION: int +POLICY_VIEW_LOCAL_INFORMATION: int +POLICY_WRITE: int +PolicyAccountDomainInformation: int +PolicyAuditEventsInformation: int +PolicyAuditFullQueryInformation: int +PolicyAuditFullSetInformation: int +PolicyAuditLogInformation: int +PolicyDefaultQuotaInformation: int +PolicyDnsDomainInformation: int +PolicyLsaServerRoleInformation: int +PolicyModificationInformation: int +PolicyNotifyAccountDomainInformation: int +PolicyNotifyAuditEventsInformation: int +PolicyNotifyDnsDomainInformation: int +PolicyNotifyDomainEfsInformation: int +PolicyNotifyDomainKerberosTicketInformation: int +PolicyNotifyMachineAccountPasswordInformation: int +PolicyNotifyServerRoleInformation: int +PolicyPdAccountInformation: int +PolicyPrimaryDomainInformation: int +PolicyReplicaSourceInformation: int +PolicyServerDisabled: int +PolicyServerEnabled: int +PolicyServerRoleBackup: int +PolicyServerRolePrimary: int +PROTECTED_DACL_SECURITY_INFORMATION: int +PROTECTED_SACL_SECURITY_INFORMATION: int +REVOKE_ACCESS: int +SACL_SECURITY_INFORMATION: int +SANDBOX_INERT: int +SDDL_REVISION_1: int +SE_DACL_AUTO_INHERITED: int +SE_DACL_DEFAULTED: int +SE_DACL_PRESENT: int +SE_DACL_PROTECTED: int +SE_DS_OBJECT: int +SE_DS_OBJECT_ALL: int +SE_FILE_OBJECT: int +SE_GROUP_DEFAULTED: int +SE_GROUP_ENABLED: int +SE_GROUP_ENABLED_BY_DEFAULT: int +SE_GROUP_LOGON_ID: int +SE_GROUP_MANDATORY: int +SE_GROUP_OWNER: int +SE_GROUP_RESOURCE: int +SE_GROUP_USE_FOR_DENY_ONLY: int +SE_KERNEL_OBJECT: int +SE_LMSHARE: int +SE_OWNER_DEFAULTED: int +SE_PRINTER: int +SE_PRIVILEGE_ENABLED: int +SE_PRIVILEGE_ENABLED_BY_DEFAULT: int +SE_PRIVILEGE_REMOVED: int +SE_PRIVILEGE_USED_FOR_ACCESS: int +SE_PROVIDER_DEFINED_OBJECT: int +SE_REGISTRY_KEY: int +SE_REGISTRY_WOW64_32KEY: int +SE_SACL_AUTO_INHERITED: int +SE_SACL_DEFAULTED: int +SE_SACL_PRESENT: int +SE_SACL_PROTECTED: int +SE_SELF_RELATIVE: int +SE_SERVICE: int +SE_UNKNOWN_OBJECT_TYPE: int +SE_WINDOW_OBJECT: int +SE_WMIGUID_OBJECT: int +SECPKG_CRED_BOTH: int +SECPKG_CRED_INBOUND: int +SECPKG_CRED_OUTBOUND: int +SECPKG_FLAG_ACCEPT_WIN32_NAME: int +SECPKG_FLAG_CLIENT_ONLY: int +SECPKG_FLAG_CONNECTION: int +SECPKG_FLAG_DATAGRAM: int +SECPKG_FLAG_EXTENDED_ERROR: int +SECPKG_FLAG_IMPERSONATION: int +SECPKG_FLAG_INTEGRITY: int +SECPKG_FLAG_MULTI_REQUIRED: int +SECPKG_FLAG_PRIVACY: int +SECPKG_FLAG_STREAM: int +SECPKG_FLAG_TOKEN_ONLY: int +SECURITY_CREATOR_SID_AUTHORITY: int +SECURITY_LOCAL_SID_AUTHORITY: int +SECURITY_NON_UNIQUE_AUTHORITY: int +SECURITY_NT_AUTHORITY: int +SECURITY_NULL_SID_AUTHORITY: int +SECURITY_RESOURCE_MANAGER_AUTHORITY: int +SECURITY_WORLD_SID_AUTHORITY: int +SecurityAnonymous: int +SecurityDelegation: int +SecurityIdentification: int +SecurityImpersonation: int +SET_ACCESS: int +SET_AUDIT_FAILURE: int +SET_AUDIT_SUCCESS: int +SidTypeAlias: int +SidTypeComputer: int +SidTypeDeletedAccount: int +SidTypeDomain: int +SidTypeGroup: int +SidTypeInvalid: int +SidTypeUnknown: int +SidTypeUser: int +SidTypeWellKnownGroup: int +STYPE_DEVICE: int +STYPE_DISKTREE: int +STYPE_IPC: int +STYPE_PRINTQ: int +STYPE_SPECIAL: int +STYPE_TEMPORARY: int +SUB_CONTAINERS_AND_OBJECTS_INHERIT: int +SUB_CONTAINERS_ONLY_INHERIT: int +SUB_OBJECTS_ONLY_INHERIT: int +SUCCESSFUL_ACCESS_ACE_FLAG: int +SYSTEM_AUDIT_ACE_TYPE: int +SYSTEM_AUDIT_OBJECT_ACE_TYPE: int +TOKEN_ADJUST_DEFAULT: int +TOKEN_ADJUST_GROUPS: int +TOKEN_ADJUST_PRIVILEGES: int +TOKEN_ALL_ACCESS: int +TOKEN_ASSIGN_PRIMARY: int +TOKEN_DUPLICATE: int +TOKEN_EXECUTE: int +TOKEN_IMPERSONATE: int +TOKEN_QUERY: int +TOKEN_QUERY_SOURCE: int +TOKEN_READ: int +TOKEN_WRITE: int +TokenImpersonation: int +TokenPrimary: int +TrustedControllersInformation: int +TrustedDomainAuthInformation: int +TrustedDomainAuthInformationInternal: int +TrustedDomainFullInformation: int +TrustedDomainFullInformation2Internal: int +TrustedDomainFullInformationInternal: int +TrustedDomainInformationBasic: int +TrustedDomainInformationEx: int +TrustedDomainInformationEx2Internal: int +TrustedDomainNameInformation: int +TrustedPasswordInformation: int +TrustedPosixOffsetInformation: int +TRUSTEE_BAD_FORM: int +TRUSTEE_IS_ALIAS: int +TRUSTEE_IS_COMPUTER: int +TRUSTEE_IS_DELETED: int +TRUSTEE_IS_DOMAIN: int +TRUSTEE_IS_GROUP: int +TRUSTEE_IS_INVALID: int +TRUSTEE_IS_NAME: int +TRUSTEE_IS_OBJECTS_AND_NAME: int +TRUSTEE_IS_OBJECTS_AND_SID: int +TRUSTEE_IS_SID: int +TRUSTEE_IS_UNKNOWN: int +TRUSTEE_IS_USER: int +TRUSTEE_IS_WELL_KNOWN_GROUP: int +UNPROTECTED_DACL_SECURITY_INFORMATION: int +UNPROTECTED_SACL_SECURITY_INFORMATION: int +CredHandleType = _win32typing.PyCredHandle +CtxtHandleType = _win32typing.PyCtxtHandle + +def DsListDomainsInSite(hds, site: str, /): ... +def DsListInfoForServer(hds, server: str, /): ... +def DsListRoles(hds, /): ... +def DsListServersForDomainInSite(hds, domain: str, site: str, /): ... +def DsListServersInSite(hds, site: str, /): ... +def DsListSites(hds, /): ... + +GetPolicyHandle = LsaOpenPolicy + +MICROSOFT_KERBEROS_NAME_A: bytes +MSV1_0_PACKAGE_NAME: bytes +PyCredHandleType = _win32typing.PyCredHandle +PyCtxtHandleType = _win32typing.PyCtxtHandle +PySecBufferDescType = _win32typing.PySecBufferDesc +PySecBufferType = _win32typing.PySecBuffer +SE_ASSIGNPRIMARYTOKEN_NAME: str +SE_AUDIT_NAME: str +SE_BACKUP_NAME: str +SE_BATCH_LOGON_NAME: str +SE_CHANGE_NOTIFY_NAME: str +SE_CREATE_GLOBAL_NAME: str +SE_CREATE_PAGEFILE_NAME: str +SE_CREATE_PERMANENT_NAME: str +SE_CREATE_SYMBOLIC_LINK_NAME: str +SE_CREATE_TOKEN_NAME: str +SE_DEBUG_NAME: str +SE_DENY_BATCH_LOGON_NAME: str +SE_DENY_INTERACTIVE_LOGON_NAME: str +SE_DENY_NETWORK_LOGON_NAME: str +SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME: str +SE_DENY_SERVICE_LOGON_NAME: str +SE_ENABLE_DELEGATION_NAME: str +SE_GROUP_INTEGRITY: int +SE_GROUP_INTEGRITY_ENABLED: int +SE_IMPERSONATE_NAME: str +SE_INCREASE_QUOTA_NAME: str +SE_INC_BASE_PRIORITY_NAME: str +SE_INC_WORKING_SET_NAME: str +SE_INTERACTIVE_LOGON_NAME: str +SE_LOAD_DRIVER_NAME: str +SE_LOCK_MEMORY_NAME: str +SE_MACHINE_ACCOUNT_NAME: str +SE_MANAGE_VOLUME_NAME: str +SE_NETWORK_LOGON_NAME: str +SE_PROF_SINGLE_PROCESS_NAME: str +SE_RELABEL_NAME: str +SE_REMOTE_INTERACTIVE_LOGON_NAME: str +SE_REMOTE_SHUTDOWN_NAME: str +SE_RESTORE_NAME: str +SE_SECURITY_NAME: str +SE_SERVICE_LOGON_NAME: str +SE_SHUTDOWN_NAME: str +SE_SYNC_AGENT_NAME: str +SE_SYSTEMTIME_NAME: str +SE_SYSTEM_ENVIRONMENT_NAME: str +SE_SYSTEM_PROFILE_NAME: str +SE_TAKE_OWNERSHIP_NAME: str +SE_TCB_NAME: str +SE_TIME_ZONE_NAME: str +SE_TRUSTED_CREDMAN_ACCESS_NAME: str +SE_UNDOCK_NAME: str +SE_UNSOLICITED_INPUT_NAME: str +SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP: int +SYSTEM_MANDATORY_LABEL_NO_READ_UP: int +SYSTEM_MANDATORY_LABEL_NO_WRITE_UP: int +SYSTEM_MANDATORY_LABEL_VALID_MASK: int +SecBufferDescType = _win32typing.PySecBufferDesc +SecBufferType = _win32typing.PySecBuffer +TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN: int +TOKEN_MANDATORY_POLICY_NO_WRITE_UP: int +TOKEN_MANDATORY_POLICY_OFF: int +TOKEN_MANDATORY_POLICY_VALID_MASK: int +TokenAccessInformation: int +TokenAuditPolicy: int +TokenDefaultDacl: int +TokenElevation: int +TokenElevationType: int +TokenElevationTypeDefault: int +TokenElevationTypeFull: int +TokenElevationTypeLimited: int +TokenGroups: int +TokenGroupsAndPrivileges: int +TokenHasRestrictions: int +TokenImpersonationLevel: int +TokenIntegrityLevel: int +TokenLinkedToken: int +TokenLogonSid: int +TokenMandatoryPolicy: int +TokenOrigin: int +TokenOwner: int +TokenPrimaryGroup: int +TokenPrivileges: int +TokenRestrictedSids: int +TokenSandBoxInert: int +TokenSessionId: int +TokenSessionReference: int +TokenSource: int +TokenStatistics: int +TokenType: int +TokenUIAccess: int +TokenUser: int +TokenVirtualizationAllowed: int +TokenVirtualizationEnabled: int +UNICODE: int +WinAccountAdministratorSid: int +WinAccountCertAdminsSid: int +WinAccountComputersSid: int +WinAccountControllersSid: int +WinAccountDomainAdminsSid: int +WinAccountDomainGuestsSid: int +WinAccountDomainUsersSid: int +WinAccountEnterpriseAdminsSid: int +WinAccountGuestSid: int +WinAccountKrbtgtSid: int +WinAccountPolicyAdminsSid: int +WinAccountRasAndIasServersSid: int +WinAccountReadonlyControllersSid: int +WinAccountSchemaAdminsSid: int +WinAnonymousSid: int +WinAuthenticatedUserSid: int +WinBatchSid: int +WinBuiltinAccountOperatorsSid: int +WinBuiltinAdministratorsSid: int +WinBuiltinAuthorizationAccessSid: int +WinBuiltinBackupOperatorsSid: int +WinBuiltinCryptoOperatorsSid: int +WinBuiltinDCOMUsersSid: int +WinBuiltinDomainSid: int +WinBuiltinEventLogReadersGroup: int +WinBuiltinGuestsSid: int +WinBuiltinIUsersSid: int +WinBuiltinIncomingForestTrustBuildersSid: int +WinBuiltinNetworkConfigurationOperatorsSid: int +WinBuiltinPerfLoggingUsersSid: int +WinBuiltinPerfMonitoringUsersSid: int +WinBuiltinPowerUsersSid: int +WinBuiltinPreWindows2000CompatibleAccessSid: int +WinBuiltinPrintOperatorsSid: int +WinBuiltinRemoteDesktopUsersSid: int +WinBuiltinReplicatorSid: int +WinBuiltinSystemOperatorsSid: int +WinBuiltinTerminalServerLicenseServersSid: int +WinBuiltinUsersSid: int +WinCacheablePrincipalsGroupSid: int +WinCreatorGroupServerSid: int +WinCreatorGroupSid: int +WinCreatorOwnerRightsSid: int +WinCreatorOwnerServerSid: int +WinCreatorOwnerSid: int +WinDialupSid: int +WinDigestAuthenticationSid: int +WinEnterpriseControllersSid: int +WinEnterpriseReadonlyControllersSid: int +WinHighLabelSid: int +WinIUserSid: int +WinInteractiveSid: int +WinLocalServiceSid: int +WinLocalSid: int +WinLocalSystemSid: int +WinLogonIdsSid: int +WinLowLabelSid: int +WinMediumLabelSid: int +WinNTLMAuthenticationSid: int +WinNetworkServiceSid: int +WinNetworkSid: int +WinNonCacheablePrincipalsGroupSid: int +WinNtAuthoritySid: int +WinNullSid: int +WinOtherOrganizationSid: int +WinProxySid: int +WinRemoteLogonIdSid: int +WinRestrictedCodeSid: int +WinSChannelAuthenticationSid: int +WinSelfSid: int +WinServiceSid: int +WinSystemLabelSid: int +WinTerminalServerSid: int +WinThisOrganizationSid: int +WinUntrustedLabelSid: int +WinWorldSid: int +WinWriteRestrictedCodeSid: int diff --git a/stubs/pywin32/win32/win32service.pyi b/stubs/pywin32/win32/win32service.pyi new file mode 100644 index 000000000000..30797ebefee5 --- /dev/null +++ b/stubs/pywin32/win32/win32service.pyi @@ -0,0 +1,187 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import _win32typing +from win32.lib.pywintypes import error as error + +def GetThreadDesktop(ThreadId: int, /) -> _win32typing.PyHDESK: ... +def EnumWindowStations() -> tuple[tuple[str, Incomplete], ...]: ... +def GetUserObjectInformation(Handle: int, _type, /) -> None: ... +def SetUserObjectInformation(Handle: int, info, _type, /) -> None: ... +def OpenWindowStation(szWinSta, Inherit, DesiredAccess, /) -> _win32typing.PyHWINSTA: ... +def OpenDesktop(szDesktop, Flags, Inherit, DesiredAccess, /) -> _win32typing.PyHDESK: ... +def CreateDesktop( + Desktop, Flags, DesiredAccess, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, / +) -> _win32typing.PyHDESK: ... +def OpenInputDesktop(Flags, Inherit, DesiredAccess, /) -> _win32typing.PyHDESK: ... +def GetProcessWindowStation() -> _win32typing.PyHWINSTA: ... +def CreateWindowStation( + WindowStation, Flags, DesiredAccess, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, / +) -> _win32typing.PyHWINSTA: ... +def EnumServicesStatus( + hSCManager: _win32typing.PySC_HANDLE | int, ServiceType: int = ..., ServiceState: int = ..., / +) -> tuple[Incomplete, ...]: ... +def EnumServicesStatusEx( + SCManager: _win32typing.PySC_HANDLE, ServiceType, ServiceState, InfoLevel, GroupName: Incomplete | None = ..., / +) -> tuple[Incomplete, ...]: ... +def EnumDependentServices(hService: _win32typing.PySC_HANDLE, ServiceState, /) -> tuple[Incomplete, ...]: ... +def QueryServiceConfig(hService: _win32typing.PySC_HANDLE, /): ... +def StartService(hService: _win32typing.PySC_HANDLE, args: Iterable[str] | None, /) -> None: ... +def OpenService(scHandle: _win32typing.PySC_HANDLE, name: str, desiredAccess, /) -> _win32typing.PySC_HANDLE: ... +def OpenSCManager(machineName: str | None, dbName: str | None, desiredAccess: int, /) -> _win32typing.PySC_HANDLE: ... +def CloseServiceHandle(scHandle: _win32typing.PySC_HANDLE, /) -> None: ... +def QueryServiceStatus(hService: _win32typing.PySC_HANDLE, /) -> _win32typing.SERVICE_STATUS: ... +def QueryServiceStatusEx(hService: _win32typing.PySC_HANDLE, /) -> _win32typing.SERVICE_STATUS: ... +def SetServiceObjectSecurity( + Handle: _win32typing.PySC_HANDLE, SecurityInformation, SecurityDescriptor: _win32typing.PySECURITY_DESCRIPTOR, / +) -> None: ... +def QueryServiceObjectSecurity( + Handle: _win32typing.PySC_HANDLE, SecurityInformation, / +) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def GetServiceKeyName(hSCManager: _win32typing.PySC_HANDLE, DisplayName, /): ... +def GetServiceDisplayName(hSCManager: _win32typing.PySC_HANDLE, ServiceName, /): ... +def SetServiceStatus( + scHandle, serviceStatus: _win32typing.SERVICE_STATUS | tuple[int, int, int, int, int, int, int], / +) -> None: ... +def ControlService(scHandle: _win32typing.PySC_HANDLE, code, /) -> _win32typing.SERVICE_STATUS: ... +def DeleteService(scHandle: _win32typing.PySC_HANDLE, /) -> None: ... +def CreateService( + scHandle: _win32typing.PySC_HANDLE, + name: str, + displayName: str, + desiredAccess: int, + serviceType: int, + startType: int, + errorControl: int, + binaryFile: str, + loadOrderGroup: str | None, + bFetchTag: bool, + serviceDeps: Iterable[Incomplete] | None, + acctName: str | None, + password: str | None, + /, +) -> _win32typing.PySC_HANDLE: ... +def ChangeServiceConfig( + hService: _win32typing.PySC_HANDLE, + serviceType: int, + startType: int, + errorControl: int, + binaryFile: str | None, + loadOrderGroup: str | None, + bFetchTag: bool, + serviceDeps: Iterable[Incomplete] | None, + acctName: str | None, + password: str | None, + displayName: str | None, + /, +): ... +def LockServiceDatabase(sc_handle: _win32typing.PySC_HANDLE, /): ... +def UnlockServiceDatabase(lock, /): ... +def QueryServiceLockStatus(hSCManager: _win32typing.PySC_HANDLE, /) -> tuple[Incomplete, str, Incomplete]: ... +def ChangeServiceConfig2(hService: _win32typing.PySC_HANDLE, InfoLevel, info, /) -> None: ... +def QueryServiceConfig2(hService: _win32typing.PySC_HANDLE, InfoLevel, /): ... + +DBT_CONFIGCHANGECANCELED: int +DBT_CONFIGCHANGED: int +DBT_CUSTOMEVENT: int +DBT_DEVICEARRIVAL: int +DBT_DEVICEQUERYREMOVE: int +DBT_DEVICEQUERYREMOVEFAILED: int +DBT_DEVICEREMOVECOMPLETE: int +DBT_DEVICEREMOVEPENDING: int +DBT_DEVICETYPESPECIFIC: int +DBT_QUERYCHANGECONFIG: int +DF_ALLOWOTHERACCOUNTHOOK: int +SC_ACTION_NONE: int +SC_ACTION_REBOOT: int +SC_ACTION_RESTART: int +SC_ACTION_RUN_COMMAND: int +SC_ENUM_PROCESS_INFO: int +SC_GROUP_IDENTIFIER: int +SC_MANAGER_ALL_ACCESS: int +SC_MANAGER_CONNECT: int +SC_MANAGER_CREATE_SERVICE: int +SC_MANAGER_ENUMERATE_SERVICE: int +SC_MANAGER_LOCK: int +SC_MANAGER_MODIFY_BOOT_CONFIG: int +SC_MANAGER_QUERY_LOCK_STATUS: int +SERVICE_ACCEPT_HARDWAREPROFILECHANGE: int +SERVICE_ACCEPT_NETBINDCHANGE: int +SERVICE_ACCEPT_PARAMCHANGE: int +SERVICE_ACCEPT_PAUSE_CONTINUE: int +SERVICE_ACCEPT_POWEREVENT: int +SERVICE_ACCEPT_PRESHUTDOWN: int +SERVICE_ACCEPT_SESSIONCHANGE: int +SERVICE_ACCEPT_SHUTDOWN: int +SERVICE_ACCEPT_STOP: int +SERVICE_ACTIVE: int +SERVICE_ALL_ACCESS: int +SERVICE_AUTO_START: int +SERVICE_BOOT_START: int +SERVICE_CHANGE_CONFIG: int +SERVICE_CONFIG_DELAYED_AUTO_START_INFO: int +SERVICE_CONFIG_DESCRIPTION: int +SERVICE_CONFIG_FAILURE_ACTIONS: int +SERVICE_CONFIG_FAILURE_ACTIONS_FLAG: int +SERVICE_CONFIG_PRESHUTDOWN_INFO: int +SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO: int +SERVICE_CONFIG_SERVICE_SID_INFO: int +SERVICE_CONTINUE_PENDING: int +SERVICE_CONTROL_CONTINUE: int +SERVICE_CONTROL_DEVICEEVENT: int +SERVICE_CONTROL_HARDWAREPROFILECHANGE: int +SERVICE_CONTROL_INTERROGATE: int +SERVICE_CONTROL_NETBINDADD: int +SERVICE_CONTROL_NETBINDDISABLE: int +SERVICE_CONTROL_NETBINDENABLE: int +SERVICE_CONTROL_NETBINDREMOVE: int +SERVICE_CONTROL_PARAMCHANGE: int +SERVICE_CONTROL_PAUSE: int +SERVICE_CONTROL_POWEREVENT: int +SERVICE_CONTROL_PRESHUTDOWN: int +SERVICE_CONTROL_SESSIONCHANGE: int +SERVICE_CONTROL_SHUTDOWN: int +SERVICE_CONTROL_STOP: int +SERVICE_DEMAND_START: int +SERVICE_DISABLED: int +SERVICE_DRIVER: int +SERVICE_ENUMERATE_DEPENDENTS: int +SERVICE_ERROR_CRITICAL: int +SERVICE_ERROR_IGNORE: int +SERVICE_ERROR_NORMAL: int +SERVICE_ERROR_SEVERE: int +SERVICE_FILE_SYSTEM_DRIVER: int +SERVICE_INACTIVE: int +SERVICE_INTERACTIVE_PROCESS: int +SERVICE_INTERROGATE: int +SERVICE_KERNEL_DRIVER: int +SERVICE_NO_CHANGE: int +SERVICE_PAUSE_CONTINUE: int +SERVICE_PAUSE_PENDING: int +SERVICE_PAUSED: int +SERVICE_QUERY_CONFIG: int +SERVICE_QUERY_STATUS: int +SERVICE_RUNNING: int +SERVICE_SID_TYPE_NONE: int +SERVICE_SID_TYPE_RESTRICTED: int +SERVICE_SID_TYPE_UNRESTRICTED: int +SERVICE_SPECIFIC_ERROR: int +SERVICE_START: int +SERVICE_START_PENDING: int +SERVICE_STATE_ALL: int +SERVICE_STOP: int +SERVICE_STOP_PENDING: int +SERVICE_STOPPED: int +SERVICE_SYSTEM_START: int +SERVICE_USER_DEFINED_CONTROL: int +SERVICE_WIN32: int +SERVICE_WIN32_OWN_PROCESS: int +SERVICE_WIN32_SHARE_PROCESS: int +UOI_FLAGS: int +UOI_NAME: int +UOI_TYPE: int +UOI_USER_SID: int +WSF_VISIBLE: int +HDESKType = _win32typing.PyHDESK +HWINSTAType = _win32typing.PyHWINSTA +UNICODE: int diff --git a/stubs/pywin32/win32/win32trace.pyi b/stubs/pywin32/win32/win32trace.pyi new file mode 100644 index 000000000000..0ab7e8c3b837 --- /dev/null +++ b/stubs/pywin32/win32/win32trace.pyi @@ -0,0 +1,13 @@ +from win32.lib.pywintypes import error as error + +def GetHandle() -> int: ... +def GetTracer(): ... +def InitRead() -> None: ... +def InitWrite() -> None: ... +def TermRead() -> None: ... +def TermWrite() -> None: ... +def blockingread(milliSeconds: int = ..., /) -> str: ... +def flush() -> None: ... +def read() -> str: ... +def setprint() -> None: ... +def write(data: str, /) -> None: ... diff --git a/stubs/pywin32/win32/win32transaction.pyi b/stubs/pywin32/win32/win32transaction.pyi new file mode 100644 index 000000000000..26d5077d5a55 --- /dev/null +++ b/stubs/pywin32/win32/win32transaction.pyi @@ -0,0 +1,18 @@ +import _win32typing +from win32.lib.pywintypes import error as error + +def CreateTransaction( + TransactionAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + UOW: _win32typing.PyIID | None = ..., + CreateOptions: int = ..., + IsolationLevel: int = ..., + IsolationFlags: int = ..., + Timeout: int = ..., + Description: str | None = ..., +) -> int: ... +def RollbackTransaction(TransactionHandle: int) -> None: ... +def RollbackTransactionAsync(TransactionHandle: int) -> None: ... +def CommitTransaction(TransactionHandle: int) -> None: ... +def CommitTransactionAsync(TransactionHandle: int) -> None: ... +def GetTransactionId(TransactionHandle: int) -> _win32typing.PyIID: ... +def OpenTransaction(DesiredAccess, TransactionId: _win32typing.PyIID) -> int: ... diff --git a/stubs/pywin32/win32/win32ts.pyi b/stubs/pywin32/win32/win32ts.pyi new file mode 100644 index 000000000000..f9c2b5db1488 --- /dev/null +++ b/stubs/pywin32/win32/win32ts.pyi @@ -0,0 +1,97 @@ +from _typeshed import Incomplete + +def WTSOpenServer(ServerName: str) -> int: ... +def WTSCloseServer(Server: int) -> None: ... +def WTSQueryUserConfig(ServerName: str, UserName: str, WTSConfigClass): ... +def WTSSetUserConfig(ServerName: str, UserName: str, WTSConfigClass, Buffer) -> None: ... +def WTSEnumerateServers(DomainName: str | None = ..., Version: int = ..., Reserved=...) -> tuple[str, ...]: ... +def WTSEnumerateSessions(Server: int = ..., Version: int = ..., Reserved=...) -> tuple[dict[str, str | int], ...]: ... +def WTSLogoffSession(Server: int, SessionId: int, Wait: bool) -> None: ... +def WTSDisconnectSession(Server: int, SessionId: int, Wait: bool) -> None: ... +def WTSQuerySessionInformation(Server: int, SessionId: int, WTSInfoClass: int) -> str: ... +def WTSEnumerateProcesses(Server: int = ..., Version: int = ..., Reserved: int = ...) -> tuple[str, ...]: ... +def WTSQueryUserToken(SessionId) -> int: ... +def WTSShutdownSystem(Server: int, ShutdownFlag) -> None: ... +def WTSTerminateProcess(Server: int, ProcessId, ExitCode) -> None: ... +def ProcessIdToSessionId(ProcessId): ... +def WTSGetActiveConsoleSessionId(): ... +def WTSRegisterSessionNotification(Wnd: int, Flags) -> None: ... +def WTSUnRegisterSessionNotification(Wnd: int) -> None: ... +def WTSWaitSystemEvent(Server: int = ..., EventMask=...): ... +def WTSSendMessage(Server: int, SessionId, Title: str, Message: str, Style, Timeout, Wait): ... + +NOTIFY_FOR_ALL_SESSIONS: int +NOTIFY_FOR_THIS_SESSION: int +WTSActive: int +WTSApplicationName: int +WTSClientAddress: int +WTSClientBuildNumber: int +WTSClientDirectory: int +WTSClientDisplay: int +WTSClientHardwareId: int +WTSClientName: int +WTSClientProductId: int +WTSClientProtocolType: int +WTSIsRemoteSession: int +WTSConnectQuery: int +WTSConnectState: int +WTSConnected: int +WTSDisconnected: int +WTSDomainName: int +WTSDown: int +WTSIdle: int +WTSInit: int +WTSInitialProgram: int +WTSListen: int +WTSOEMId: int +WTSReset: int +WTSSessionId: int +WTSShadow: int +WTSUserConfigBrokenTimeoutSettings: int +WTSUserConfigInitialProgram: int +WTSUserConfigModemCallbackPhoneNumber: int +WTSUserConfigModemCallbackSettings: int +WTSUserConfigReconnectSettings: int +WTSUserConfigShadowingSettings: int +WTSUserConfigTerminalServerHomeDir: int +WTSUserConfigTerminalServerHomeDirDrive: int +WTSUserConfigTerminalServerProfilePath: int +WTSUserConfigTimeoutSettingsConnections: int +WTSUserConfigTimeoutSettingsDisconnections: int +WTSUserConfigTimeoutSettingsIdle: int +WTSUserConfigWorkingDirectory: int +WTSUserConfigfAllowLogonTerminalServer: int +WTSUserConfigfDeviceClientDefaultPrinter: int +WTSUserConfigfDeviceClientDrives: int +WTSUserConfigfDeviceClientPrinters: int +WTSUserConfigfInheritInitialProgram: int +WTSUserConfigfTerminalServerRemoteHomeDir: int +WTSUserName: int +WTSVirtualClientData: int +WTSVirtualFileHandle: int +WTSWinStationName: int +WTSWorkingDirectory: int +WTS_CURRENT_SERVER: int +WTS_CURRENT_SERVER_HANDLE: int +WTS_CURRENT_SERVER_NAME: Incomplete +WTS_CURRENT_SESSION: int +WTS_EVENT_ALL: int +WTS_EVENT_CONNECT: int +WTS_EVENT_CREATE: int +WTS_EVENT_DELETE: int +WTS_EVENT_DISCONNECT: int +WTS_EVENT_FLUSH: int +WTS_EVENT_LICENSE: int +WTS_EVENT_LOGOFF: int +WTS_EVENT_LOGON: int +WTS_EVENT_NONE: int +WTS_EVENT_RENAME: int +WTS_EVENT_STATECHANGE: int +WTS_PROTOCOL_TYPE_CONSOLE: int +WTS_PROTOCOL_TYPE_ICA: int +WTS_PROTOCOL_TYPE_RDP: int +WTS_WSD_FASTREBOOT: int +WTS_WSD_LOGOFF: int +WTS_WSD_POWEROFF: int +WTS_WSD_REBOOT: int +WTS_WSD_SHUTDOWN: int diff --git a/stubs/pywin32/win32/win32wnet.pyi b/stubs/pywin32/win32/win32wnet.pyi new file mode 100644 index 000000000000..6fd4e9b0e432 --- /dev/null +++ b/stubs/pywin32/win32/win32wnet.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def NCBBuffer(size, /): ... +def Netbios(ncb: _win32typing.NCB, /): ... +def WNetAddConnection2( + NetResource: _win32typing.PyNETRESOURCE, + Password: Incomplete | None = ..., + UserName: Incomplete | None = ..., + Flags: int = ..., +) -> None: ... +def WNetAddConnection3( + HwndOwner: int | _win32typing.PyHANDLE, + NetResource: _win32typing.PyNETRESOURCE, + Password: Incomplete | None = ..., + UserName: Incomplete | None = ..., + Flags: int = ..., +) -> None: ... +def WNetCancelConnection2(name: str, flags, force, /) -> None: ... +def WNetOpenEnum(scope, _type, usage, resource: _win32typing.PyNETRESOURCE, /) -> _win32typing.PyHANDLE: ... +def WNetCloseEnum(handle: _win32typing.PyHANDLE, /) -> None: ... +def WNetEnumResource(handle: _win32typing.PyHANDLE, maxExtries: int = ..., /) -> list[_win32typing.PyNETRESOURCE]: ... +def WNetGetUser(connection: str | None = ..., /) -> str: ... +def WNetGetUniversalName(localPath: str, infoLevel, /) -> str: ... +def WNetGetResourceInformation(NetResource: _win32typing.PyNETRESOURCE, /) -> tuple[_win32typing.PyNETRESOURCE, Incomplete]: ... +def WNetGetLastError() -> tuple[Incomplete, Incomplete, Incomplete]: ... +def WNetGetResourceParent(NetResource: _win32typing.PyNETRESOURCE, /) -> _win32typing.PyNETRESOURCE: ... +def WNetGetConnection(connection: str | None = ..., /) -> str: ... + +NETRESOURCE = _win32typing.PyNETRESOURCE +NCB = _win32typing.PyNCB +# old "deprecated" names, before types could create instances. +NETRESOURCEType = _win32typing.PyNETRESOURCE +NCBType = _win32typing.PyNCB diff --git a/stubs/pywin32/win32/winxpgui.pyi b/stubs/pywin32/win32/winxpgui.pyi new file mode 100644 index 000000000000..156611576b85 --- /dev/null +++ b/stubs/pywin32/win32/winxpgui.pyi @@ -0,0 +1,5 @@ +# The `winxpgui` module is obsolete and has been completely replaced +# by `win32gui` and `win32console.GetConsoleWindow`. Use those instead. + +from win32console import GetConsoleWindow as GetConsoleWindow +from win32gui import * diff --git a/stubs/pywin32/win32api.pyi b/stubs/pywin32/win32api.pyi new file mode 100644 index 000000000000..8beb8a8a1219 --- /dev/null +++ b/stubs/pywin32/win32api.pyi @@ -0,0 +1 @@ +from win32.win32api import * diff --git a/stubs/pywin32/win32clipboard.pyi b/stubs/pywin32/win32clipboard.pyi new file mode 100644 index 000000000000..77dbe6673232 --- /dev/null +++ b/stubs/pywin32/win32clipboard.pyi @@ -0,0 +1 @@ +from win32.win32clipboard import * diff --git a/stubs/pywin32/win32com/__init__.pyi b/stubs/pywin32/win32com/__init__.pyi new file mode 100644 index 000000000000..64402b719834 --- /dev/null +++ b/stubs/pywin32/win32com/__init__.pyi @@ -0,0 +1,9 @@ +from collections.abc import MutableSequence + +from . import gen_py as gen_py + +__gen_path__: str +__build_path__: str | None + +def SetupEnvironment() -> None: ... +def __PackageSupportBuildPath__(package_path: MutableSequence[str]) -> None: ... diff --git a/stubs/pywin32/win32com/adsi/__init__.pyi b/stubs/pywin32/win32com/adsi/__init__.pyi new file mode 100644 index 000000000000..548c6c6170dd --- /dev/null +++ b/stubs/pywin32/win32com/adsi/__init__.pyi @@ -0,0 +1 @@ +from win32comext.adsi import * diff --git a/stubs/pywin32/win32com/adsi/adsi.pyi b/stubs/pywin32/win32com/adsi/adsi.pyi new file mode 100644 index 000000000000..a6269d428cfa --- /dev/null +++ b/stubs/pywin32/win32com/adsi/adsi.pyi @@ -0,0 +1 @@ +from win32comext.adsi.adsi import * diff --git a/stubs/pywin32/win32com/adsi/adsicon.pyi b/stubs/pywin32/win32com/adsi/adsicon.pyi new file mode 100644 index 000000000000..1776450e43b8 --- /dev/null +++ b/stubs/pywin32/win32com/adsi/adsicon.pyi @@ -0,0 +1 @@ +from win32comext.adsi.adsicon import * diff --git a/stubs/pywin32/win32com/authorization/__init__.pyi b/stubs/pywin32/win32com/authorization/__init__.pyi new file mode 100644 index 000000000000..975c5a823b08 --- /dev/null +++ b/stubs/pywin32/win32com/authorization/__init__.pyi @@ -0,0 +1 @@ +from win32comext.authorization import * diff --git a/stubs/pywin32/win32com/authorization/authorization.pyi b/stubs/pywin32/win32com/authorization/authorization.pyi new file mode 100644 index 000000000000..0ad104f7ebbc --- /dev/null +++ b/stubs/pywin32/win32com/authorization/authorization.pyi @@ -0,0 +1 @@ +from win32comext.authorization.authorization import * diff --git a/stubs/pywin32/win32com/axcontrol/__init__.pyi b/stubs/pywin32/win32com/axcontrol/__init__.pyi new file mode 100644 index 000000000000..fde8be560785 --- /dev/null +++ b/stubs/pywin32/win32com/axcontrol/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axcontrol import * diff --git a/stubs/pywin32/win32com/axcontrol/axcontrol.pyi b/stubs/pywin32/win32com/axcontrol/axcontrol.pyi new file mode 100644 index 000000000000..d3c73448de56 --- /dev/null +++ b/stubs/pywin32/win32com/axcontrol/axcontrol.pyi @@ -0,0 +1 @@ +from win32comext.axcontrol.axcontrol import * diff --git a/stubs/pywin32/win32com/axdebug/__init__.pyi b/stubs/pywin32/win32com/axdebug/__init__.pyi new file mode 100644 index 000000000000..97d083e95e4c --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axdebug import * diff --git a/stubs/pywin32/win32com/axdebug/adb.pyi b/stubs/pywin32/win32com/axdebug/adb.pyi new file mode 100644 index 000000000000..48966a1195b0 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/adb.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.adb import * diff --git a/stubs/pywin32/win32com/axdebug/axdebug.pyi b/stubs/pywin32/win32com/axdebug/axdebug.pyi new file mode 100644 index 000000000000..45b111326729 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/axdebug.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.axdebug import * diff --git a/stubs/pywin32/win32com/axdebug/codecontainer.pyi b/stubs/pywin32/win32com/axdebug/codecontainer.pyi new file mode 100644 index 000000000000..60d3a50fb97e --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/codecontainer.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.codecontainer import * diff --git a/stubs/pywin32/win32com/axdebug/contexts.pyi b/stubs/pywin32/win32com/axdebug/contexts.pyi new file mode 100644 index 000000000000..c1c9fbfd99d3 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/contexts.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.contexts import * diff --git a/stubs/pywin32/win32com/axdebug/debugger.pyi b/stubs/pywin32/win32com/axdebug/debugger.pyi new file mode 100644 index 000000000000..83a0e9c9498f --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/debugger.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.debugger import * diff --git a/stubs/pywin32/win32com/axdebug/documents.pyi b/stubs/pywin32/win32com/axdebug/documents.pyi new file mode 100644 index 000000000000..e0d1bb7431c6 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/documents.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.documents import * diff --git a/stubs/pywin32/win32com/axdebug/expressions.pyi b/stubs/pywin32/win32com/axdebug/expressions.pyi new file mode 100644 index 000000000000..3816f76473c1 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/expressions.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.expressions import * diff --git a/stubs/pywin32/win32com/axdebug/gateways.pyi b/stubs/pywin32/win32com/axdebug/gateways.pyi new file mode 100644 index 000000000000..517204a57a89 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/gateways.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.gateways import * diff --git a/stubs/pywin32/win32com/axdebug/stackframe.pyi b/stubs/pywin32/win32com/axdebug/stackframe.pyi new file mode 100644 index 000000000000..3184248da855 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/stackframe.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.stackframe import * diff --git a/stubs/pywin32/win32com/axdebug/util.pyi b/stubs/pywin32/win32com/axdebug/util.pyi new file mode 100644 index 000000000000..1ea282e4c35a --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/util.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.util import * diff --git a/stubs/pywin32/win32com/axscript/__init__.pyi b/stubs/pywin32/win32com/axscript/__init__.pyi new file mode 100644 index 000000000000..afc72ec7e6a9 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axscript import * diff --git a/stubs/pywin32/win32com/axscript/asputil.pyi b/stubs/pywin32/win32com/axscript/asputil.pyi new file mode 100644 index 000000000000..1e04c857f72b --- /dev/null +++ b/stubs/pywin32/win32com/axscript/asputil.pyi @@ -0,0 +1 @@ +from win32comext.axscript.asputil import * diff --git a/stubs/pywin32/win32com/axscript/axscript.pyi b/stubs/pywin32/win32com/axscript/axscript.pyi new file mode 100644 index 000000000000..7ec0b348419d --- /dev/null +++ b/stubs/pywin32/win32com/axscript/axscript.pyi @@ -0,0 +1 @@ +from win32comext.axscript.axscript import * diff --git a/stubs/pywin32/win32com/axscript/client/__init__.pyi b/stubs/pywin32/win32com/axscript/client/__init__.pyi new file mode 100644 index 000000000000..203d0ab35080 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client import * diff --git a/stubs/pywin32/win32com/axscript/client/debug.pyi b/stubs/pywin32/win32com/axscript/client/debug.pyi new file mode 100644 index 000000000000..a39e0e145b4b --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/debug.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client.debug import * diff --git a/stubs/pywin32/win32com/axscript/client/error.pyi b/stubs/pywin32/win32com/axscript/client/error.pyi new file mode 100644 index 000000000000..f1a3310b6e6b --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/error.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client.error import * diff --git a/stubs/pywin32/win32com/axscript/client/framework.pyi b/stubs/pywin32/win32com/axscript/client/framework.pyi new file mode 100644 index 000000000000..cec9c9a8aaf8 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/framework.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client.framework import * diff --git a/stubs/pywin32/win32com/axscript/server/__init__.pyi b/stubs/pywin32/win32com/axscript/server/__init__.pyi new file mode 100644 index 000000000000..6cb0b07bc54c --- /dev/null +++ b/stubs/pywin32/win32com/axscript/server/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axscript.server import * diff --git a/stubs/pywin32/win32com/axscript/server/axsite.pyi b/stubs/pywin32/win32com/axscript/server/axsite.pyi new file mode 100644 index 000000000000..e07103462ce5 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/server/axsite.pyi @@ -0,0 +1 @@ +from win32comext.axscript.server.axsite import * diff --git a/stubs/pywin32/win32com/bits/__init__.pyi b/stubs/pywin32/win32com/bits/__init__.pyi new file mode 100644 index 000000000000..020ede08f21a --- /dev/null +++ b/stubs/pywin32/win32com/bits/__init__.pyi @@ -0,0 +1 @@ +from win32comext.bits import * diff --git a/stubs/pywin32/win32com/bits/bits.pyi b/stubs/pywin32/win32com/bits/bits.pyi new file mode 100644 index 000000000000..fcea1eb79ed5 --- /dev/null +++ b/stubs/pywin32/win32com/bits/bits.pyi @@ -0,0 +1 @@ +from win32comext.bits.bits import * diff --git a/stubs/pywin32/win32com/client/__init__.pyi b/stubs/pywin32/win32com/client/__init__.pyi new file mode 100644 index 000000000000..930c9586f3ab --- /dev/null +++ b/stubs/pywin32/win32com/client/__init__.pyi @@ -0,0 +1,75 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterator +from typing import Final, TypeAlias + +import _win32typing +from pythoncom import com_record +from win32.lib.pywintypes import IIDType +from win32com.client import dynamic + +_Stringifiable: TypeAlias = object + +def GetObject(Pathname: str | None = None, Class=None, clsctx=None) -> CDispatch: ... +def GetActiveObject(Class: str, clsctx=...): ... +def Moniker(Pathname: str, clsctx=...): ... +def Dispatch( + dispatch: str | dynamic.PyIDispatchType | IIDType | dynamic.PyIUnknownType, + userName: str | None = None, + resultCLSID: _Stringifiable | None = None, + typeinfo: _win32typing.PyITypeInfo | None = None, + clsctx: int = ..., +) -> dynamic.CDispatch: ... +def DispatchEx(clsid, machine=None, userName=None, resultCLSID=None, typeinfo=None, clsctx=None): ... + +class CDispatch(dynamic.CDispatch): + def __dir__(self) -> list[str]: ... + +def CastTo(ob, target, typelib=None): ... + +class Constants: + __dicts__: list[Incomplete] + def __getattr__(self, a: str): ... + +constants: Final[Constants] + +class EventsProxy: + def __init__(self, ob) -> None: ... + def __del__(self) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, val) -> None: ... + +def DispatchWithEvents(clsid, user_event_class) -> EventsProxy: ... +def WithEvents(disp, user_event_class): ... +def getevents(clsid): ... +def Record(name, object) -> com_record: ... +def register_record_class(cls) -> None: ... + +class DispatchBaseClass: + def __init__(self, oobj=None) -> None: ... + def __dir__(self) -> list[str]: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + +class CoClassBaseClass: + def __init__(self, oobj=None) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def __call__(self, *args, **kwargs): ... + def __str__(self, *args: Unused) -> str: ... # noqa: Y029 + def __int__(self, *args: Unused) -> int: ... + def __iter__(self) -> Iterator[Incomplete]: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + +class VARIANT: + varianttype: Incomplete + def __init__(self, vt, value) -> None: ... + + @property + def value(self): ... + @value.setter + def value(self, newval) -> None: ... + @value.deleter + def value(self) -> None: ... diff --git a/stubs/pywin32/win32com/client/build.pyi b/stubs/pywin32/win32com/client/build.pyi new file mode 100644 index 000000000000..5eba28add3f4 --- /dev/null +++ b/stubs/pywin32/win32com/client/build.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, Literal + +class NotSupportedException(Exception): ... + +DropIndirection: Final = "DropIndirection" +NoTranslateTypes: Final[list[int]] +NoTranslateMap: Final[set[int]] + +class MapEntry: + dispid: Incomplete + desc: Incomplete | None + names: Incomplete + doc: Incomplete + resultCLSID: Incomplete + resultDocumentation: Incomplete | None + wasProperty: Incomplete + hidden: bool | Literal[0, 1] + def __init__( + self, desc_or_id, names=None, doc=None, resultCLSID=..., resultDoc=None, hidden: bool | Literal[0, 1] = 0 + ) -> None: ... + def GetResultCLSID(self) -> Incomplete | None: ... + def GetResultCLSIDStr(self) -> str: ... + def GetResultName(self) -> Incomplete | None: ... + +class OleItem: + typename: ClassVar[str] + doc: Incomplete + python_name: Incomplete | None + bWritten: bool | Literal[0, 1] + bIsDispatch: bool | Literal[0, 1] + bIsSink: bool | Literal[0, 1] + clsid: Incomplete | None + co_class: Incomplete | None + def __init__(self, doc=None) -> None: ... + +class DispatchItem(OleItem): + typename: ClassVar[str] + propMap: dict[Incomplete, Incomplete] + propMapGet: dict[Incomplete, Incomplete] + propMapPut: dict[Incomplete, Incomplete] + mapFuncs: dict[Incomplete, Incomplete] + defaultDispatchName: Incomplete | None + hidden: bool | Literal[0, 1] + def __init__(self, typeinfo=None, attr=None, doc=None, bForUser: bool | Literal[0, 1] = 1) -> None: ... + clsid: Incomplete + bIsDispatch: bool | Literal[0, 1] + def Build(self, typeinfo, attr, bForUser: bool | Literal[0, 1] = 1) -> None: ... + def CountInOutOptArgs(self, argTuple: Iterable[Incomplete]) -> tuple[int, int, int]: ... + def MakeFuncMethod(self, entry, name: str, bMakeClass: bool | Literal[0, 1] = 1) -> list[str]: ... + def MakeDispatchFuncMethod(self, entry, name: str, bMakeClass: bool | Literal[0, 1] = 1) -> list[str]: ... + def MakeVarArgsFuncMethod(self, entry, name: str, bMakeClass: bool | Literal[0, 1] = 1) -> list[str]: ... + +class VTableItem(DispatchItem): + vtableFuncs: list[tuple[Incomplete, Incomplete, Incomplete]] + def Build(self, typeinfo, attr, bForUser: bool | Literal[0, 1] = 1) -> None: ... + +class LazyDispatchItem(DispatchItem): + typename: ClassVar[str] + clsid: Incomplete + def __init__(self, attr, doc) -> None: ... + +typeSubstMap: Final[dict[int, int]] +valid_identifier_chars: Final[str] + +def demunge_leading_underscores(className: str) -> str: ... +def MakePublicAttributeName(className: str, is_global: bool = False) -> str: ... +def MakeDefaultArgRepr(defArgVal) -> str | None: ... +def BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg, is_comment: bool = False) -> str: ... diff --git a/stubs/pywin32/win32com/client/dynamic.pyi b/stubs/pywin32/win32com/client/dynamic.pyi new file mode 100644 index 000000000000..100ca291d7cc --- /dev/null +++ b/stubs/pywin32/win32com/client/dynamic.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete +from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only + +import _win32typing +from win32.lib.pywintypes import IIDType +from win32com.client import build + +_T_co = TypeVar("_T_co", covariant=True) +_T = TypeVar("_T") + +@type_check_only +class _DispatchCreateClass(Protocol[_T_co]): + @staticmethod + def __call__( + IDispatch: str | PyIDispatchType | IIDType | PyIUnknownType, + olerepr: build.DispatchItem | build.LazyDispatchItem, + userName: str | None = None, + lazydata=None, + ) -> _T_co: ... + +debugging: int +debugging_attr: int +LCID: Final = 0x0 +ERRORS_BAD_CONTEXT: Final[list[int]] +ALL_INVOKE_TYPES: Final[list[int]] + +def debug_print(*args: object) -> None: ... +def debug_attr_print(*args: object) -> None: ... + +PyIDispatchType = _win32typing.PyIDispatch +PyIUnknownType = _win32typing.PyIUnknown + +@overload +def Dispatch( + IDispatch: str | PyIDispatchType | IIDType | PyIUnknownType, + userName: str | None, + createClass: _DispatchCreateClass[_T], + typeinfo: _win32typing.PyITypeInfo | None = None, + clsctx: int = ..., +) -> _T: ... +@overload +def Dispatch( + IDispatch: str | PyIDispatchType | IIDType | PyIUnknownType, + userName: str | None = None, + createClass: None = None, + typeinfo: _win32typing.PyITypeInfo | None = None, + clsctx: int = ..., +) -> CDispatch: ... + +def MakeOleRepr(IDispatch, typeinfo, typecomp) -> build.DispatchItem | build.LazyDispatchItem: ... +def DumbDispatch(IDispatch, userName=None, createClass=None, clsctx=...): ... + +class CDispatch: + def __init__(self, IDispatch, olerepr, userName=None, lazydata=None) -> None: ... + def __call__(self, *args): ... + def __bool__(self) -> bool: ... + def __dir__(self) -> list[str]: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __int__(self) -> int: ... + def __len__(self) -> int: ... + def __getitem__(self, index): ... + def __setitem__(self, index, *args) -> None: ... + def __LazyMap__(self, attr) -> Literal[0, 1] | None: ... + def __AttrToID__(self, attr): ... + ob: Incomplete + # CDispatch objects are dynamically generated and too complex to type + def __getattr__(self, attr: str) -> Any: ... + def __setattr__(self, attr: str, value: Any) -> None: ... diff --git a/stubs/pywin32/win32com/client/gencache.pyi b/stubs/pywin32/win32com/client/gencache.pyi new file mode 100644 index 000000000000..9f72ce3009aa --- /dev/null +++ b/stubs/pywin32/win32com/client/gencache.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator +from contextlib import contextmanager +from types import ModuleType +from typing import Literal +from typing_extensions import Never + +from win32.lib.pywintypes import IIDType +from win32com.client import dynamic + +bForDemandDefault: int +clsidToTypelib: dict[str, tuple[str, int, int, int]] +versionRedirectMap: dict[tuple[str, int, int, int], ModuleType | None] +is_readonly: bool +is_zip: bool +demandGeneratedTypeLibraries: dict[tuple[str, int, int, int], Incomplete] + +def __init__() -> None: ... + +pickleVersion: int + +@contextmanager +def ModuleMutex(module_name: str) -> Generator[None]: ... +def GetGeneratedFileName(clsid, lcid, major, minor) -> str: ... +def SplitGeneratedFileName(fname: str) -> tuple[str, ...]: ... +def GetGeneratePath() -> str: ... +def GetClassForProgID(progid: str) -> type | None: ... +def GetClassForCLSID(clsid) -> type | None: ... +def GetModuleForProgID(progid: str) -> ModuleType | None: ... +def GetModuleForCLSID(clsid) -> ModuleType | None: ... +def GetModuleForTypelib(typelibCLSID, lcid, major, minor) -> ModuleType: ... +def MakeModuleForTypelib( + typelibCLSID, + lcid, + major, + minor, + progressInstance=None, + bForDemand: bool | Literal[0, 1] = ..., + bBuildHidden: bool | Literal[0, 1] = 1, +) -> ModuleType: ... +def MakeModuleForTypelibInterface( + typelib_ob, progressInstance=None, bForDemand: bool | Literal[0, 1] = ..., bBuildHidden: bool | Literal[0, 1] = 1 +) -> ModuleType | None: ... +def EnsureModuleForTypelibInterface( + typelib_ob, progressInstance=None, bForDemand: bool | Literal[0, 1] = ..., bBuildHidden: bool | Literal[0, 1] = 1 +) -> ModuleType | None: ... +def ForgetAboutTypelibInterface(typelib_ob) -> None: ... +def EnsureModule( + typelibCLSID, + lcid, + major, + minor, + progressInstance=None, + bValidateFile: bool | Literal[0, 1] = ..., + bForDemand: bool | Literal[0, 1] = ..., + bBuildHidden: bool | Literal[0, 1] = 1, +) -> ModuleType | None: ... +def EnsureDispatch( + prog_id: str | dynamic.PyIDispatchType | IIDType | dynamic.PyIUnknownType, bForDemand: bool | Literal[0, 1] = 1 +) -> dynamic.CDispatch: ... +def AddModuleToCache(typelibclsid, lcid, major, minor, verbose: Unused = 1, bFlushNow: bool | Literal[0, 1] = ...) -> None: ... +def GetGeneratedInfos() -> list[tuple[Incomplete, Incomplete, Incomplete, Incomplete]]: ... +def Rebuild(verbose: bool | Literal[0, 1] = 1) -> None: ... +def usage() -> Never: ... diff --git a/stubs/pywin32/win32com/directsound/__init__.pyi b/stubs/pywin32/win32com/directsound/__init__.pyi new file mode 100644 index 000000000000..6ac36b68e0eb --- /dev/null +++ b/stubs/pywin32/win32com/directsound/__init__.pyi @@ -0,0 +1 @@ +from win32comext.directsound import * diff --git a/stubs/pywin32/win32com/directsound/directsound.pyi b/stubs/pywin32/win32com/directsound/directsound.pyi new file mode 100644 index 000000000000..ec66ab405b9a --- /dev/null +++ b/stubs/pywin32/win32com/directsound/directsound.pyi @@ -0,0 +1 @@ +from win32comext.directsound.directsound import * diff --git a/stubs/pywin32/win32com/gen_py/__init__.pyi b/stubs/pywin32/win32com/gen_py/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32com/ifilter/__init__.pyi b/stubs/pywin32/win32com/ifilter/__init__.pyi new file mode 100644 index 000000000000..258d3a36f592 --- /dev/null +++ b/stubs/pywin32/win32com/ifilter/__init__.pyi @@ -0,0 +1 @@ +from win32comext.ifilter import * diff --git a/stubs/pywin32/win32com/ifilter/ifilter.pyi b/stubs/pywin32/win32com/ifilter/ifilter.pyi new file mode 100644 index 000000000000..01872b20c9a2 --- /dev/null +++ b/stubs/pywin32/win32com/ifilter/ifilter.pyi @@ -0,0 +1 @@ +from win32comext.ifilter.ifilter import * diff --git a/stubs/pywin32/win32com/ifilter/ifiltercon.pyi b/stubs/pywin32/win32com/ifilter/ifiltercon.pyi new file mode 100644 index 000000000000..8f2260e73c0b --- /dev/null +++ b/stubs/pywin32/win32com/ifilter/ifiltercon.pyi @@ -0,0 +1 @@ +from win32comext.ifilter.ifiltercon import * diff --git a/stubs/pywin32/win32com/internet/__init__.pyi b/stubs/pywin32/win32com/internet/__init__.pyi new file mode 100644 index 000000000000..8fb46e57e584 --- /dev/null +++ b/stubs/pywin32/win32com/internet/__init__.pyi @@ -0,0 +1 @@ +from win32comext.internet import * diff --git a/stubs/pywin32/win32com/internet/inetcon.pyi b/stubs/pywin32/win32com/internet/inetcon.pyi new file mode 100644 index 000000000000..58e4a6236df5 --- /dev/null +++ b/stubs/pywin32/win32com/internet/inetcon.pyi @@ -0,0 +1 @@ +from win32comext.internet.inetcon import * diff --git a/stubs/pywin32/win32com/internet/internet.pyi b/stubs/pywin32/win32com/internet/internet.pyi new file mode 100644 index 000000000000..e08fbee40e46 --- /dev/null +++ b/stubs/pywin32/win32com/internet/internet.pyi @@ -0,0 +1 @@ +from win32comext.internet.internet import * diff --git a/stubs/pywin32/win32com/mapi/__init__.pyi b/stubs/pywin32/win32com/mapi/__init__.pyi new file mode 100644 index 000000000000..cc183a9712fe --- /dev/null +++ b/stubs/pywin32/win32com/mapi/__init__.pyi @@ -0,0 +1 @@ +from win32comext.mapi import * diff --git a/stubs/pywin32/win32com/mapi/emsabtags.pyi b/stubs/pywin32/win32com/mapi/emsabtags.pyi new file mode 100644 index 000000000000..d38198bb2755 --- /dev/null +++ b/stubs/pywin32/win32com/mapi/emsabtags.pyi @@ -0,0 +1 @@ +from win32comext.mapi.emsabtags import * diff --git a/stubs/pywin32/win32com/mapi/exchange.pyi b/stubs/pywin32/win32com/mapi/exchange.pyi new file mode 100644 index 000000000000..1d4b98a437f4 --- /dev/null +++ b/stubs/pywin32/win32com/mapi/exchange.pyi @@ -0,0 +1 @@ +from win32comext.mapi.exchange import * diff --git a/stubs/pywin32/win32com/mapi/mapi.pyi b/stubs/pywin32/win32com/mapi/mapi.pyi new file mode 100644 index 000000000000..e7bacd919a3b --- /dev/null +++ b/stubs/pywin32/win32com/mapi/mapi.pyi @@ -0,0 +1 @@ +from win32comext.mapi.mapi import * diff --git a/stubs/pywin32/win32com/mapi/mapitags.pyi b/stubs/pywin32/win32com/mapi/mapitags.pyi new file mode 100644 index 000000000000..f4ff53e2efed --- /dev/null +++ b/stubs/pywin32/win32com/mapi/mapitags.pyi @@ -0,0 +1 @@ +from win32comext.mapi.mapitags import * diff --git a/stubs/pywin32/win32com/mapi/mapiutil.pyi b/stubs/pywin32/win32com/mapi/mapiutil.pyi new file mode 100644 index 000000000000..cd19df1c9eb2 --- /dev/null +++ b/stubs/pywin32/win32com/mapi/mapiutil.pyi @@ -0,0 +1 @@ +from win32comext.mapi.mapiutil import * diff --git a/stubs/pywin32/win32com/olectl.pyi b/stubs/pywin32/win32com/olectl.pyi new file mode 100644 index 000000000000..bfd6283a5497 --- /dev/null +++ b/stubs/pywin32/win32com/olectl.pyi @@ -0,0 +1,56 @@ +from typing import Final + +FACILITY_CONTROL: Final = 0xA + +def MAKE_SCODE(sev: int, fac: int, code: int) -> int: ... +def STD_CTL_SCODE(n: int) -> int: ... + +CTL_E_ILLEGALFUNCTIONCALL: Final = -2146828283 +CTL_E_OVERFLOW: Final = -2146828282 +CTL_E_OUTOFMEMORY: Final = -2146828281 +CTL_E_DIVISIONBYZERO: Final = -2146828277 +CTL_E_OUTOFSTRINGSPACE: Final = -2146828274 +CTL_E_OUTOFSTACKSPACE: Final = -2146828260 +CTL_E_BADFILENAMEORNUMBER: Final = -2146828236 +CTL_E_FILENOTFOUND: Final = -2146828235 +CTL_E_BADFILEMODE: Final = -2146828234 +CTL_E_FILEALREADYOPEN: Final = -2146828233 +CTL_E_DEVICEIOERROR: Final = -2146828231 +CTL_E_FILEALREADYEXISTS: Final = -2146828230 +CTL_E_BADRECORDLENGTH: Final = -2146828229 +CTL_E_DISKFULL: Final = -2146828227 +CTL_E_BADRECORDNUMBER: Final = -2146828225 +CTL_E_BADFILENAME: Final = -2146828224 +CTL_E_TOOMANYFILES: Final = -2146828221 +CTL_E_DEVICEUNAVAILABLE: Final = -2146828220 +CTL_E_PERMISSIONDENIED: Final = -2146828218 +CTL_E_DISKNOTREADY: Final = -2146828217 +CTL_E_PATHFILEACCESSERROR: Final = -2146828213 +CTL_E_PATHNOTFOUND: Final = -2146828212 +CTL_E_INVALIDPATTERNSTRING: Final = -2146828195 +CTL_E_INVALIDUSEOFNULL: Final = -2146828194 +CTL_E_INVALIDFILEFORMAT: Final = -2146827967 +CTL_E_INVALIDPROPERTYVALUE: Final = -2146827908 +CTL_E_INVALIDPROPERTYARRAYINDEX: Final = -2146827907 +CTL_E_SETNOTSUPPORTEDATRUNTIME: Final = -2146827906 +CTL_E_SETNOTSUPPORTED: Final = -2146827905 +CTL_E_NEEDPROPERTYARRAYINDEX: Final = -2146827903 +CTL_E_SETNOTPERMITTED: Final = -2146827901 +CTL_E_GETNOTSUPPORTEDATRUNTIME: Final = -2146827895 +CTL_E_GETNOTSUPPORTED: Final = -2146827894 +CTL_E_PROPERTYNOTFOUND: Final = -2146827866 +CTL_E_INVALIDCLIPBOARDFORMAT: Final = -2146827828 +CTL_E_INVALIDPICTURE: Final = -2146827807 +CTL_E_PRINTERERROR: Final = -2146827806 +CTL_E_CANTSAVEFILETOTEMP: Final = -2146827553 +CTL_E_SEARCHTEXTNOTFOUND: Final = -2146827544 +CTL_E_REPLACEMENTSTOOLONG: Final = -2146827542 +CONNECT_E_FIRST: Final = -2147220992 +CONNECT_E_LAST: Final = -2147220977 +CONNECT_S_FIRST: Final = 262656 +CONNECT_S_LAST: Final = 262671 +CONNECT_E_NOCONNECTION: Final = -2147220992 +CONNECT_E_ADVISELIMIT: Final = -2147220991 +CONNECT_E_CANNOTCONNECT: Final = -2147220990 +CONNECT_E_OVERRIDDEN: Final = -2147220989 +CLASS_E_NOTLICENSED: Final = -2147221230 diff --git a/stubs/pywin32/win32com/propsys/__init__.pyi b/stubs/pywin32/win32com/propsys/__init__.pyi new file mode 100644 index 000000000000..34b721052b14 --- /dev/null +++ b/stubs/pywin32/win32com/propsys/__init__.pyi @@ -0,0 +1 @@ +from win32comext.propsys import * diff --git a/stubs/pywin32/win32com/propsys/propsys.pyi b/stubs/pywin32/win32com/propsys/propsys.pyi new file mode 100644 index 000000000000..c5afd3cba640 --- /dev/null +++ b/stubs/pywin32/win32com/propsys/propsys.pyi @@ -0,0 +1 @@ +from win32comext.propsys.propsys import * diff --git a/stubs/pywin32/win32com/propsys/pscon.pyi b/stubs/pywin32/win32com/propsys/pscon.pyi new file mode 100644 index 000000000000..0f35b47343f3 --- /dev/null +++ b/stubs/pywin32/win32com/propsys/pscon.pyi @@ -0,0 +1 @@ +from win32comext.propsys.pscon import * diff --git a/stubs/pywin32/win32com/server/__init__.pyi b/stubs/pywin32/win32com/server/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32com/server/connect.pyi b/stubs/pywin32/win32com/server/connect.pyi new file mode 100644 index 000000000000..d4f5e9994d9f --- /dev/null +++ b/stubs/pywin32/win32com/server/connect.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Final + +IConnectionPointContainer_methods: Final = ["EnumConnectionPoints", "FindConnectionPoint"] +IConnectionPoint_methods: Final = [ + "EnumConnections", + "Unadvise", + "Advise", + "GetConnectionPointContainer", + "GetConnectionInterface", +] + +class ConnectableServer: + cookieNo: int + connections: dict[int, Incomplete] + def EnumConnections(self) -> None: ... + def GetConnectionInterface(self) -> None: ... + def GetConnectionPointContainer(self): ... + def Advise(self, pUnk) -> int: ... + def Unadvise(self, cookie: int) -> None: ... + def EnumConnectionPoints(self) -> None: ... + def FindConnectionPoint(self, iid) -> Incomplete | None: ... diff --git a/stubs/pywin32/win32com/server/dispatcher.pyi b/stubs/pywin32/win32com/server/dispatcher.pyi new file mode 100644 index 000000000000..6c4c9dd74ace --- /dev/null +++ b/stubs/pywin32/win32com/server/dispatcher.pyi @@ -0,0 +1,18 @@ +from logging import Logger +from typing import TypeAlias + +from win32com.server.policy import BasicWrapPolicy + +class DispatcherBase: + policy: BasicWrapPolicy + logger: Logger + def __init__(self, policyClass, object) -> None: ... + +class DispatcherTrace(DispatcherBase): ... + +class DispatcherWin32trace(DispatcherTrace): + def __init__(self, policyClass, object) -> None: ... + +class DispatcherOutputDebugString(DispatcherTrace): ... + +DefaultDebugDispatcher: TypeAlias = DispatcherTrace diff --git a/stubs/pywin32/win32com/server/exception.pyi b/stubs/pywin32/win32com/server/exception.pyi new file mode 100644 index 000000000000..44427b52a099 --- /dev/null +++ b/stubs/pywin32/win32com/server/exception.pyi @@ -0,0 +1,21 @@ +import pythoncom + +class COMException(pythoncom.com_error): + scode: int + description: str + source: str | None + helpfile: str | None + helpcontext: int | None + def __init__( + self, + description: str | None = None, + scode: int | None = None, + source: str | None = None, + helpfile: str | None = None, + helpContext: int | None = None, + desc: str | None = None, + hresult: int | None = None, + ) -> None: ... + +def IsCOMException(t: type[BaseException] | None = None) -> bool: ... +def IsCOMServerException(t: type[BaseException] | None = None) -> bool: ... diff --git a/stubs/pywin32/win32com/server/factory.pyi b/stubs/pywin32/win32com/server/factory.pyi new file mode 100644 index 000000000000..3de546181158 --- /dev/null +++ b/stubs/pywin32/win32com/server/factory.pyi @@ -0,0 +1,9 @@ +from _typeshed import Unused +from collections.abc import Iterable + +from _win32typing import PyIClassFactory, PyIID + +def RegisterClassFactories( + clsids: Iterable[PyIID], flags: int | None = None, clsctx: int | None = None +) -> list[tuple[PyIClassFactory, int]]: ... +def RevokeClassFactories(infos: Iterable[tuple[Unused, int]]) -> None: ... diff --git a/stubs/pywin32/win32com/server/localserver.pyi b/stubs/pywin32/win32com/server/localserver.pyi new file mode 100644 index 000000000000..dd0f6c43efb0 --- /dev/null +++ b/stubs/pywin32/win32com/server/localserver.pyi @@ -0,0 +1,9 @@ +from collections.abc import Iterable +from typing import Final + +from _win32typing import PyIID + +usage: Final[str] + +def serve(clsids: Iterable[PyIID]) -> None: ... +def main() -> None: ... diff --git a/stubs/pywin32/win32com/server/policy.pyi b/stubs/pywin32/win32com/server/policy.pyi new file mode 100644 index 000000000000..a14cfe8d8c03 --- /dev/null +++ b/stubs/pywin32/win32com/server/policy.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from abc import ABC, abstractmethod +from typing import Any, Final + +import _win32typing + +__author__: Final[str] +S_OK: Final = 0 +IDispatchType: Incomplete +IUnknownType: Incomplete +regSpec: str +regPolicy: str +regDispatcher: str +regAddnPath: str + +def CreateInstance(clsid, reqIID: _win32typing.PyIID) -> _win32typing.PyIUnknown: ... + +class BasicWrapPolicy(ABC): + def __init__(self, object) -> None: ... + def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + @abstractmethod + def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + +class MappedWrapPolicy(BasicWrapPolicy): + _dispid_to_func_: dict[int, str] + def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + +class DesignatedWrapPolicy(MappedWrapPolicy): ... +class EventHandlerPolicy(DesignatedWrapPolicy): ... + +class DynamicPolicy(BasicWrapPolicy): + def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + +DefaultPolicy = DesignatedWrapPolicy + +# Imports an arbitrary object by it's fully-qualified name. +def resolve_func(spec: str) -> Any: ... + +# Imports and calls an arbitrary callable by it's fully-qualified name. +def call_func(spec: str, *args: Any) -> Any: ... + +DISPATCH_METHOD: int +DISPATCH_PROPERTYGET: int +DISPATCH_PROPERTYPUT: int +DISPATCH_PROPERTYPUTREF: int +DISPID_EVALUATE: int +DISPID_NEWENUM: int +DISPID_PROPERTYPUT: int +DISPID_STARTENUM: int +DISPID_VALUE: int diff --git a/stubs/pywin32/win32com/server/register.pyi b/stubs/pywin32/win32com/server/register.pyi new file mode 100644 index 000000000000..78fb2c6899fe --- /dev/null +++ b/stubs/pywin32/win32com/server/register.pyi @@ -0,0 +1,68 @@ +from collections.abc import Callable, Iterable, Mapping +from typing import Final, Literal, Protocol, TypedDict, TypeVar, type_check_only +from typing_extensions import Unpack + +from _win32typing import PyHKEY, PyIID + +_T = TypeVar("_T", PyHKEY, int) + +@type_check_only +class _RegisterClass(Protocol): + _reg_clsid_: PyIID + +@type_check_only +class _RegisterFlag(TypedDict, total=False): + quiet: bool + debug: bool + finalize_register: Callable[[], None] + +@type_check_only +class _UnregisterFlag(TypedDict, total=False): + quiet: bool + finalize_unregister: Callable[[], None] + +@type_check_only +class _ElevatedFlag(TypedDict, total=False): + quiet: bool + unattended: bool + hwnd: int + +@type_check_only +class _CommandFlag(_RegisterFlag, _UnregisterFlag, _ElevatedFlag): # type: ignore[misc] + ... + +CATID_PythonCOMServer: Final = "{B3EF80D0-68E2-11D0-A689-00C04FD658FF}" + +def recurse_delete_key(path: str | None, base: PyHKEY | int = -2147483648) -> None: ... +def RegisterServer( + clsid: PyIID, + pythonInstString: str | None = None, + desc: str | None = None, + progID: str | None = None, + verProgID: str | None = None, + defIcon: str | None = None, + threadingModel: Literal["apartment", "both", "free", "neutral"] = "both", + policy: str | None = None, + catids: list[PyIID] = [], + other: Mapping[str, str] = {}, + addPyComCat: bool | None = None, + dispatcher: str | None = None, + clsctx: int | None = None, + addnPath: str | None = None, +) -> None: ... +def GetUnregisterServerKeys( + clsid: PyIID, progID: str | None = None, verProgID: str | None = None, customKeys: Iterable[tuple[str, _T]] | None = None +) -> list[tuple[str, _T | int]]: ... +def UnregisterServer( + clsid: PyIID, + progID: str | None = None, + verProgID: str | None = None, + customKeys: Iterable[tuple[str, PyHKEY | int]] | None = None, +) -> None: ... +def GetRegisteredServerOption(clsid: PyIID, optionName: str) -> str | None: ... +def RegisterClasses(*classes: type[_RegisterClass], **flags: Unpack[_RegisterFlag]) -> None: ... +def UnregisterClasses(*classes: type[_RegisterClass], **flags: Unpack[_UnregisterFlag]) -> None: ... +def UnregisterInfoClasses(*classes: type[_RegisterClass]) -> list[tuple[str, PyHKEY | int]]: ... +def ReExecuteElevated(flags: _ElevatedFlag) -> None: ... +def UseCommandLine(*classes: type[_RegisterClass], **flags: Unpack[_CommandFlag]) -> list[tuple[str, PyHKEY | int]] | None: ... +def RegisterPyComCategory() -> None: ... diff --git a/stubs/pywin32/win32com/server/util.pyi b/stubs/pywin32/win32com/server/util.pyi new file mode 100644 index 000000000000..fda3f8187ea8 --- /dev/null +++ b/stubs/pywin32/win32com/server/util.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Literal + +import _win32typing + +def wrap( + ob, iid=None, usePolicy: type[Incomplete] | None = None, useDispatcher: type[Incomplete] | bool | Literal[0, 1] | None = None +): ... +def unwrap(ob): ... + +class ListEnumerator: + index: int + def __init__(self, data, index: int = 0, iid=...) -> None: ... + def Next(self, count: int): ... + def Skip(self, count: int) -> None: ... + def Reset(self) -> None: ... + def Clone(self): ... + +class ListEnumeratorGateway(ListEnumerator): + def Next(self, count: int) -> Iterable[Incomplete]: ... + +def NewEnum( + seq, + cls=..., + iid=..., + usePolicy: type[Incomplete] | None = None, + useDispatcher: type[Incomplete] | bool | Literal[0, 1] | None = None, +): ... + +class Collection: + data: Incomplete + def __init__(self, data=None, readOnly: bool | Literal[0, 1] = 0) -> None: ... + def Item(self, *args): ... + def Count(self): ... + def Add(self, value) -> None: ... + def Remove(self, index) -> None: ... + def Insert(self, index, value) -> None: ... + +def NewCollection(seq, cls=...) -> _win32typing.PyIUnknown: ... + +class FileStream: + file: Incomplete + def __init__(self, file: _win32typing.Pymmapfile) -> None: ... + def Read(self, amount): ... + def Write(self, data) -> int: ... + def Clone(self): ... + def CopyTo(self, dest, cb) -> tuple[int, int]: ... + def Seek(self, offset: int, origin: int) -> int: ... diff --git a/stubs/pywin32/win32com/shell/__init__.pyi b/stubs/pywin32/win32com/shell/__init__.pyi new file mode 100644 index 000000000000..1074dc68af86 --- /dev/null +++ b/stubs/pywin32/win32com/shell/__init__.pyi @@ -0,0 +1 @@ +from win32comext.shell import * diff --git a/stubs/pywin32/win32com/shell/shell.pyi b/stubs/pywin32/win32com/shell/shell.pyi new file mode 100644 index 000000000000..63f0421620f0 --- /dev/null +++ b/stubs/pywin32/win32com/shell/shell.pyi @@ -0,0 +1 @@ +from win32comext.shell.shell import * diff --git a/stubs/pywin32/win32com/shell/shellcon.pyi b/stubs/pywin32/win32com/shell/shellcon.pyi new file mode 100644 index 000000000000..d10057f464e4 --- /dev/null +++ b/stubs/pywin32/win32com/shell/shellcon.pyi @@ -0,0 +1 @@ +from win32comext.shell.shellcon import * diff --git a/stubs/pywin32/win32com/storagecon.pyi b/stubs/pywin32/win32com/storagecon.pyi new file mode 100644 index 000000000000..717bba5ebcba --- /dev/null +++ b/stubs/pywin32/win32com/storagecon.pyi @@ -0,0 +1,115 @@ +from typing import Final + +STGC_DEFAULT: Final = 0 +STGC_OVERWRITE: Final = 1 +STGC_ONLYIFCURRENT: Final = 2 +STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE: Final = 4 +STGC_CONSOLIDATE: Final = 8 +STGTY_STORAGE: Final = 1 +STGTY_STREAM: Final = 2 +STGTY_LOCKBYTES: Final = 3 +STGTY_PROPERTY: Final = 4 +STREAM_SEEK_SET: Final = 0 +STREAM_SEEK_CUR: Final = 1 +STREAM_SEEK_END: Final = 2 +LOCK_WRITE: Final = 1 +LOCK_EXCLUSIVE: Final = 2 +LOCK_ONLYONCE: Final = 4 +CWCSTORAGENAME: Final = 32 +STGM_DIRECT: Final = 0x00000000 +STGM_TRANSACTED: Final = 0x00010000 +STGM_SIMPLE: Final = 0x08000000 +STGM_READ: Final = 0x00000000 +STGM_WRITE: Final = 0x00000001 +STGM_READWRITE: Final = 0x00000002 +STGM_SHARE_DENY_NONE: Final = 0x00000040 +STGM_SHARE_DENY_READ: Final = 0x00000030 +STGM_SHARE_DENY_WRITE: Final = 0x00000020 +STGM_SHARE_EXCLUSIVE: Final = 0x00000010 +STGM_PRIORITY: Final = 0x00040000 +STGM_DELETEONRELEASE: Final = 0x04000000 +STGM_NOSCRATCH: Final = 0x00100000 +STGM_CREATE: Final = 0x00001000 +STGM_CONVERT: Final = 0x00020000 +STGM_FAILIFTHERE: Final = 0x00000000 +STGM_NOSNAPSHOT: Final = 0x00200000 +ASYNC_MODE_COMPATIBILITY: Final = 0x00000001 +ASYNC_MODE_DEFAULT: Final = 0x00000000 +STGTY_REPEAT: Final = 0x00000100 +STG_TOEND: Final = 0xFFFFFFFF +STG_LAYOUT_SEQUENTIAL: Final = 0x00000000 +STG_LAYOUT_INTERLEAVED: Final = 0x00000001 +COM_RIGHTS_EXECUTE: Final = 1 +COM_RIGHTS_EXECUTE_LOCAL: Final = 2 +COM_RIGHTS_EXECUTE_REMOTE: Final = 4 +COM_RIGHTS_ACTIVATE_LOCAL: Final = 8 +COM_RIGHTS_ACTIVATE_REMOTE: Final = 16 +STGFMT_DOCUMENT: Final = 0 +STGFMT_STORAGE: Final = 0 +STGFMT_NATIVE: Final = 1 +STGFMT_FILE: Final = 3 +STGFMT_ANY: Final = 4 +STGFMT_DOCFILE: Final = 5 +PID_DICTIONARY: Final = 0 +PID_CODEPAGE: Final = 1 +PID_FIRST_USABLE: Final = 2 +PID_FIRST_NAME_DEFAULT: Final = 4095 +PID_LOCALE: Final = -2147483648 +PID_MODIFY_TIME: Final = -2147483647 +PID_SECURITY: Final = -2147483646 +PID_BEHAVIOR: Final = -2147483645 +PID_ILLEGAL: Final = -1 +PID_MIN_READONLY: Final = -2147483648 +PID_MAX_READONLY: Final = -1073741825 +PIDDI_THUMBNAIL: Final = 0x00000002 +PIDSI_TITLE: Final = 2 +PIDSI_SUBJECT: Final = 3 +PIDSI_AUTHOR: Final = 4 +PIDSI_KEYWORDS: Final = 5 +PIDSI_COMMENTS: Final = 6 +PIDSI_TEMPLATE: Final = 7 +PIDSI_LASTAUTHOR: Final = 8 +PIDSI_REVNUMBER: Final = 9 +PIDSI_EDITTIME: Final = 10 +PIDSI_LASTPRINTED: Final = 11 +PIDSI_CREATE_DTM: Final = 12 +PIDSI_LASTSAVE_DTM: Final = 13 +PIDSI_PAGECOUNT: Final = 14 +PIDSI_WORDCOUNT: Final = 15 +PIDSI_CHARCOUNT: Final = 16 +PIDSI_THUMBNAIL: Final = 17 +PIDSI_APPNAME: Final = 18 +PIDSI_DOC_SECURITY: Final = 19 +PIDDSI_CATEGORY: Final = 2 +PIDDSI_PRESFORMAT: Final = 3 +PIDDSI_BYTECOUNT: Final = 4 +PIDDSI_LINECOUNT: Final = 5 +PIDDSI_PARCOUNT: Final = 6 +PIDDSI_SLIDECOUNT: Final = 7 +PIDDSI_NOTECOUNT: Final = 8 +PIDDSI_HIDDENCOUNT: Final = 9 +PIDDSI_MMCLIPCOUNT: Final = 10 +PIDDSI_SCALE: Final = 11 +PIDDSI_HEADINGPAIR: Final = 12 +PIDDSI_DOCPARTS: Final = 13 +PIDDSI_MANAGER: Final = 14 +PIDDSI_COMPANY: Final = 15 +PIDDSI_LINKSDIRTY: Final = 16 +PIDMSI_EDITOR: Final = 2 +PIDMSI_SUPPLIER: Final = 3 +PIDMSI_SOURCE: Final = 4 +PIDMSI_SEQUENCE_NO: Final = 5 +PIDMSI_PROJECT: Final = 6 +PIDMSI_STATUS: Final = 7 +PIDMSI_OWNER: Final = 8 +PIDMSI_RATING: Final = 9 +PIDMSI_PRODUCTION: Final = 10 +PIDMSI_COPYRIGHT: Final = 11 +PROPSETFLAG_DEFAULT: Final = 0 +PROPSETFLAG_NONSIMPLE: Final = 1 +PROPSETFLAG_ANSI: Final = 2 +PROPSETFLAG_UNBUFFERED: Final = 4 +PROPSETFLAG_CASE_SENSITIVE: Final = 8 +STGMOVE_MOVE: Final = 0 +STGMOVE_COPY: Final = 1 +STGMOVE_SHALLOWCOPY: Final = 2 diff --git a/stubs/pywin32/win32com/taskscheduler/__init__.pyi b/stubs/pywin32/win32com/taskscheduler/__init__.pyi new file mode 100644 index 000000000000..2d22e3f9c8ab --- /dev/null +++ b/stubs/pywin32/win32com/taskscheduler/__init__.pyi @@ -0,0 +1 @@ +from win32comext.taskscheduler import * diff --git a/stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi b/stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi new file mode 100644 index 000000000000..7771ba730155 --- /dev/null +++ b/stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi @@ -0,0 +1 @@ +from win32comext.taskscheduler.taskscheduler import * diff --git a/stubs/pywin32/win32com/universal.pyi b/stubs/pywin32/win32com/universal.pyi new file mode 100644 index 000000000000..2a52e6d26289 --- /dev/null +++ b/stubs/pywin32/win32com/universal.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing import Literal, SupportsIndex, TypeAlias + +import pythoncom + +com_error = pythoncom.com_error + +# Type of pythoncom._univgw.WriteFromOutTuple +# The two tuples must be of equal length +_WriteFromOutTupleType: TypeAlias = Callable[ + [tuple[Incomplete, ...] | None, tuple[Incomplete, ...] | None, int], Incomplete | None +] + +def RegisterInterfaces( + typelibGUID, lcid, major, minor, interface_names: Iterable[str] | None = None +) -> list[tuple[Incomplete, Incomplete, Incomplete]]: ... + +class Arg: + name: Incomplete + vt: Incomplete + inOut: Incomplete + default: Incomplete + clsid: Incomplete + size: Incomplete + offset: int + def __init__(self, arg_info, name=None) -> None: ... + +class Method: + dispid: Incomplete + invkind: Incomplete + name: Incomplete + args: list[Arg] + cbArgs: Incomplete + def __init__(self, method_info, isEventSink: bool | Literal[0, 1] = 0) -> None: ... + +class Definition: + def __init__(self, iid, is_dispatch, method_defs) -> None: ... + def iid(self): ... + def vtbl_argsizes(self) -> list[Incomplete]: ... + def vtbl_argcounts(self) -> list[int]: ... + def dispatch( + self, ob, index: SupportsIndex, argPtr, ReadFromInTuple=..., WriteFromOutTuple: _WriteFromOutTupleType = ... + ): ... diff --git a/stubs/pywin32/win32com/util.pyi b/stubs/pywin32/win32com/util.pyi new file mode 100644 index 000000000000..4b23324c4289 --- /dev/null +++ b/stubs/pywin32/win32com/util.pyi @@ -0,0 +1 @@ +def IIDToInterfaceName(iid) -> str: ... diff --git a/stubs/pywin32/win32comext/__init__.pyi b/stubs/pywin32/win32comext/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/adsi/__init__.pyi b/stubs/pywin32/win32comext/adsi/__init__.pyi new file mode 100644 index 000000000000..e409f094ef98 --- /dev/null +++ b/stubs/pywin32/win32comext/adsi/__init__.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete + +import _win32typing +import win32com.client + +# Re-export everything from win32comext/adsi/adsi.pyd +# Not using a star export because the redefinitions below mess up mypy, pyright and stubtest +from win32comext.adsi.adsi import ( + DBPROPSET_ADSISEARCH as DBPROPSET_ADSISEARCH, + ADsBuildEnumerator as ADsBuildEnumerator, + ADsEnumerateNext as ADsEnumerateNext, + ADsGetLastError as ADsGetLastError, + CLSID_AccessControlEntry as CLSID_AccessControlEntry, + CLSID_AccessControlList as CLSID_AccessControlList, + CLSID_ADsDSOObject as CLSID_ADsDSOObject, + CLSID_DsObjectPicker as CLSID_DsObjectPicker, + CLSID_SecurityDescriptor as CLSID_SecurityDescriptor, + DBGUID_LDAPDialect as DBGUID_LDAPDialect, + DSOP_SCOPE_INIT_INFOs as DSOP_SCOPE_INIT_INFOs, + IID_IADs as IID_IADs, + IID_IADsClass as IID_IADsClass, + IID_IADsCollection as IID_IADsCollection, + IID_IADsComputer as IID_IADsComputer, + IID_IADsComputerOperations as IID_IADsComputerOperations, + IID_IADsContainer as IID_IADsContainer, + IID_IADsDeleteOps as IID_IADsDeleteOps, + IID_IADsDomain as IID_IADsDomain, + IID_IADsFileService as IID_IADsFileService, + IID_IADsFileServiceOperations as IID_IADsFileServiceOperations, + IID_IADsFileShare as IID_IADsFileShare, + IID_IADsGroup as IID_IADsGroup, + IID_IADsLocality as IID_IADsLocality, + IID_IADsMembers as IID_IADsMembers, + IID_IADsNamespaces as IID_IADsNamespaces, + IID_IADsO as IID_IADsO, + IID_IADsOpenDSObject as IID_IADsOpenDSObject, + IID_IADsOU as IID_IADsOU, + IID_IADsPrintJob as IID_IADsPrintJob, + IID_IADsPrintJobOperations as IID_IADsPrintJobOperations, + IID_IADsPrintQueue as IID_IADsPrintQueue, + IID_IADsPrintQueueOperations as IID_IADsPrintQueueOperations, + IID_IADsProperty as IID_IADsProperty, + IID_IADsPropertyList as IID_IADsPropertyList, + IID_IADsResource as IID_IADsResource, + IID_IADsSearch as IID_IADsSearch, + IID_IADsService as IID_IADsService, + IID_IADsServiceOperations as IID_IADsServiceOperations, + IID_IADsSession as IID_IADsSession, + IID_IADsSyntax as IID_IADsSyntax, + IID_IADsUser as IID_IADsUser, + IID_IDirectoryObject as IID_IDirectoryObject, + IID_IDirectorySearch as IID_IDirectorySearch, + IID_IDsObjectPicker as IID_IDsObjectPicker, + LIBID_ADs as LIBID_ADs, + StringAsDS_SELECTION_LIST as StringAsDS_SELECTION_LIST, + error as error, +) + +LCID: int +IDispatchType: Incomplete +IADsContainerType: Incomplete + +class ADSIEnumerator: + index: int + def __init__(self, ob) -> None: ... + def __getitem__(self, index): ... + def __call__(self, index): ... + +class ADSIDispatch(win32com.client.CDispatch): + def __getattr__(self, attr: str): ... + def QueryInterface(self, iid): ... + +# Redefinition making "iid" optional. +def ADsGetObject(path, iid: _win32typing.PyIID = ...): ... + +# Redefinition with flipped "reserved" and "iid" arguments. +def ADsOpenObject(path, username, password, reserved: int = ..., iid: _win32typing.PyIID = ...): ... diff --git a/stubs/pywin32/win32comext/adsi/adsi.pyi b/stubs/pywin32/win32comext/adsi/adsi.pyi new file mode 100644 index 000000000000..350593ee7f16 --- /dev/null +++ b/stubs/pywin32/win32comext/adsi/adsi.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +import _win32typing +from win32.lib.pywintypes import com_error + +error: TypeAlias = com_error # noqa: Y042 + +def ADsOpenObject(path, username, password, iid: _win32typing.PyIID, reserved: int = ..., /): ... +def ADsGetObject(path, iid: _win32typing.PyIID, /): ... +def ADsBuildEnumerator(container: _win32typing.PyIADsContainer, /): ... +def ADsEnumerateNext(enum, num: int = ..., /): ... +def ADsGetLastError() -> tuple[Incomplete, Incomplete, Incomplete]: ... +def StringAsDS_SELECTION_LIST(buf, /): ... + +DSOP_SCOPE_INIT_INFOs = _win32typing.PyDSOP_SCOPE_INIT_INFOs +CLSID_ADsDSOObject: _win32typing.PyIID +CLSID_AccessControlEntry: _win32typing.PyIID +CLSID_AccessControlList: _win32typing.PyIID +CLSID_DsObjectPicker: _win32typing.PyIID +CLSID_SecurityDescriptor: _win32typing.PyIID +DBGUID_LDAPDialect: _win32typing.PyIID +DBPROPSET_ADSISEARCH: _win32typing.PyIID +IID_IADs: _win32typing.PyIID +IID_IADsClass: _win32typing.PyIID +IID_IADsCollection: _win32typing.PyIID +IID_IADsComputer: _win32typing.PyIID +IID_IADsComputerOperations: _win32typing.PyIID +IID_IADsContainer: _win32typing.PyIID +IID_IADsDeleteOps: _win32typing.PyIID +IID_IADsDomain: _win32typing.PyIID +IID_IADsFileService: _win32typing.PyIID +IID_IADsFileServiceOperations: _win32typing.PyIID +IID_IADsFileShare: _win32typing.PyIID +IID_IADsGroup: _win32typing.PyIID +IID_IADsLocality: _win32typing.PyIID +IID_IADsMembers: _win32typing.PyIID +IID_IADsNamespaces: _win32typing.PyIID +IID_IADsO: _win32typing.PyIID +IID_IADsOU: _win32typing.PyIID +IID_IADsOpenDSObject: _win32typing.PyIID +IID_IADsPrintJob: _win32typing.PyIID +IID_IADsPrintJobOperations: _win32typing.PyIID +IID_IADsPrintQueue: _win32typing.PyIID +IID_IADsPrintQueueOperations: _win32typing.PyIID +IID_IADsProperty: _win32typing.PyIID +IID_IADsPropertyList: _win32typing.PyIID +IID_IADsResource: _win32typing.PyIID +IID_IADsSearch: _win32typing.PyIID +IID_IADsService: _win32typing.PyIID +IID_IADsServiceOperations: _win32typing.PyIID +IID_IADsSession: _win32typing.PyIID +IID_IADsSyntax: _win32typing.PyIID +IID_IADsUser: _win32typing.PyIID +IID_IDirectoryObject: _win32typing.PyIID +IID_IDirectorySearch: _win32typing.PyIID +IID_IDsObjectPicker: _win32typing.PyIID +LIBID_ADs: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/adsi/adsicon.pyi b/stubs/pywin32/win32comext/adsi/adsicon.pyi new file mode 100644 index 000000000000..f31229dd089b --- /dev/null +++ b/stubs/pywin32/win32comext/adsi/adsicon.pyi @@ -0,0 +1,318 @@ +from _typeshed import Incomplete + +ADS_ATTR_CLEAR: int +ADS_ATTR_UPDATE: int +ADS_ATTR_APPEND: int +ADS_ATTR_DELETE: int +ADS_EXT_MINEXTDISPID: int +ADS_EXT_MAXEXTDISPID: int +ADS_EXT_INITCREDENTIALS: int +ADS_EXT_INITIALIZE_COMPLETE: int +ADS_SEARCHPREF_ASYNCHRONOUS: int +ADS_SEARCHPREF_DEREF_ALIASES: int +ADS_SEARCHPREF_SIZE_LIMIT: int +ADS_SEARCHPREF_TIME_LIMIT: int +ADS_SEARCHPREF_ATTRIBTYPES_ONLY: int +ADS_SEARCHPREF_SEARCH_SCOPE: int +ADS_SEARCHPREF_TIMEOUT: int +ADS_SEARCHPREF_PAGESIZE: int +ADS_SEARCHPREF_PAGED_TIME_LIMIT: int +ADS_SEARCHPREF_CHASE_REFERRALS: int +ADS_SEARCHPREF_SORT_ON: int +ADS_SEARCHPREF_CACHE_RESULTS: int +ADS_SEARCHPREF_DIRSYNC: int +ADS_SEARCHPREF_TOMBSTONE: int +ADS_SCOPE_BASE: int +ADS_SCOPE_ONELEVEL: int +ADS_SCOPE_SUBTREE: int +ADS_SECURE_AUTHENTICATION: int +ADS_USE_ENCRYPTION: int +ADS_USE_SSL: int +ADS_READONLY_SERVER: int +ADS_PROMPT_CREDENTIALS: int +ADS_NO_AUTHENTICATION: int +ADS_FAST_BIND: int +ADS_USE_SIGNING: int +ADS_USE_SEALING: int +ADS_USE_DELEGATION: int +ADS_SERVER_BIND: int +ADSTYPE_INVALID: int +ADSTYPE_DN_STRING: Incomplete +ADSTYPE_CASE_EXACT_STRING: Incomplete +ADSTYPE_CASE_IGNORE_STRING: Incomplete +ADSTYPE_PRINTABLE_STRING: Incomplete +ADSTYPE_NUMERIC_STRING: Incomplete +ADSTYPE_BOOLEAN: Incomplete +ADSTYPE_INTEGER: Incomplete +ADSTYPE_OCTET_STRING: Incomplete +ADSTYPE_UTC_TIME: Incomplete +ADSTYPE_LARGE_INTEGER: Incomplete +ADSTYPE_PROV_SPECIFIC: Incomplete +ADSTYPE_OBJECT_CLASS: Incomplete +ADSTYPE_CASEIGNORE_LIST: Incomplete +ADSTYPE_OCTET_LIST: Incomplete +ADSTYPE_PATH: Incomplete +ADSTYPE_POSTALADDRESS: Incomplete +ADSTYPE_TIMESTAMP: Incomplete +ADSTYPE_BACKLINK: Incomplete +ADSTYPE_TYPEDNAME: Incomplete +ADSTYPE_HOLD: Incomplete +ADSTYPE_NETADDRESS: Incomplete +ADSTYPE_REPLICAPOINTER: Incomplete +ADSTYPE_FAXNUMBER: Incomplete +ADSTYPE_EMAIL: Incomplete +ADSTYPE_NT_SECURITY_DESCRIPTOR: Incomplete +ADSTYPE_UNKNOWN: Incomplete +ADSTYPE_DN_WITH_BINARY: Incomplete +ADSTYPE_DN_WITH_STRING: Incomplete +ADS_PROPERTY_CLEAR: int +ADS_PROPERTY_UPDATE: int +ADS_PROPERTY_APPEND: int +ADS_PROPERTY_DELETE: int +ADS_SYSTEMFLAG_DISALLOW_DELETE: int +ADS_SYSTEMFLAG_CONFIG_ALLOW_RENAME: int +ADS_SYSTEMFLAG_CONFIG_ALLOW_MOVE: int +ADS_SYSTEMFLAG_CONFIG_ALLOW_LIMITED_MOVE: int +ADS_SYSTEMFLAG_DOMAIN_DISALLOW_RENAME: int +ADS_SYSTEMFLAG_DOMAIN_DISALLOW_MOVE: int +ADS_SYSTEMFLAG_CR_NTDS_NC: int +ADS_SYSTEMFLAG_CR_NTDS_DOMAIN: int +ADS_SYSTEMFLAG_ATTR_NOT_REPLICATED: int +ADS_SYSTEMFLAG_ATTR_IS_CONSTRUCTED: int +ADS_GROUP_TYPE_GLOBAL_GROUP: int +ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP: int +ADS_GROUP_TYPE_LOCAL_GROUP: int +ADS_GROUP_TYPE_UNIVERSAL_GROUP: int +ADS_GROUP_TYPE_SECURITY_ENABLED: int +ADS_UF_SCRIPT: int +ADS_UF_ACCOUNTDISABLE: int +ADS_UF_HOMEDIR_REQUIRED: int +ADS_UF_LOCKOUT: int +ADS_UF_PASSWD_NOTREQD: int +ADS_UF_PASSWD_CANT_CHANGE: int +ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: int +ADS_UF_TEMP_DUPLICATE_ACCOUNT: int +ADS_UF_NORMAL_ACCOUNT: int +ADS_UF_INTERDOMAIN_TRUST_ACCOUNT: int +ADS_UF_WORKSTATION_TRUST_ACCOUNT: int +ADS_UF_SERVER_TRUST_ACCOUNT: int +ADS_UF_DONT_EXPIRE_PASSWD: int +ADS_UF_MNS_LOGON_ACCOUNT: int +ADS_UF_SMARTCARD_REQUIRED: int +ADS_UF_TRUSTED_FOR_DELEGATION: int +ADS_UF_NOT_DELEGATED: int +ADS_UF_USE_DES_KEY_ONLY: int +ADS_UF_DONT_REQUIRE_PREAUTH: int +ADS_UF_PASSWORD_EXPIRED: int +ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: int +ADS_RIGHT_DELETE: int +ADS_RIGHT_READ_CONTROL: int +ADS_RIGHT_WRITE_DAC: int +ADS_RIGHT_WRITE_OWNER: int +ADS_RIGHT_SYNCHRONIZE: int +ADS_RIGHT_ACCESS_SYSTEM_SECURITY: int +ADS_RIGHT_GENERIC_READ: int +ADS_RIGHT_GENERIC_WRITE: int +ADS_RIGHT_GENERIC_EXECUTE: int +ADS_RIGHT_GENERIC_ALL: int +ADS_RIGHT_DS_CREATE_CHILD: int +ADS_RIGHT_DS_DELETE_CHILD: int +ADS_RIGHT_ACTRL_DS_LIST: int +ADS_RIGHT_DS_SELF: int +ADS_RIGHT_DS_READ_PROP: int +ADS_RIGHT_DS_WRITE_PROP: int +ADS_RIGHT_DS_DELETE_TREE: int +ADS_RIGHT_DS_LIST_OBJECT: int +ADS_RIGHT_DS_CONTROL_ACCESS: int +ADS_ACETYPE_ACCESS_ALLOWED: int +ADS_ACETYPE_ACCESS_DENIED: int +ADS_ACETYPE_SYSTEM_AUDIT: int +ADS_ACETYPE_ACCESS_ALLOWED_OBJECT: int +ADS_ACETYPE_ACCESS_DENIED_OBJECT: int +ADS_ACETYPE_SYSTEM_AUDIT_OBJECT: int +ADS_ACETYPE_SYSTEM_ALARM_OBJECT: int +ADS_ACETYPE_ACCESS_ALLOWED_CALLBACK: int +ADS_ACETYPE_ACCESS_DENIED_CALLBACK: int +ADS_ACETYPE_ACCESS_ALLOWED_CALLBACK_OBJECT: int +ADS_ACETYPE_ACCESS_DENIED_CALLBACK_OBJECT: int +ADS_ACETYPE_SYSTEM_AUDIT_CALLBACK: int +ADS_ACETYPE_SYSTEM_ALARM_CALLBACK: int +ADS_ACETYPE_SYSTEM_AUDIT_CALLBACK_OBJECT: int +ADS_ACETYPE_SYSTEM_ALARM_CALLBACK_OBJECT: int +ADS_ACEFLAG_INHERIT_ACE: int +ADS_ACEFLAG_NO_PROPAGATE_INHERIT_ACE: int +ADS_ACEFLAG_INHERIT_ONLY_ACE: int +ADS_ACEFLAG_INHERITED_ACE: int +ADS_ACEFLAG_VALID_INHERIT_FLAGS: int +ADS_ACEFLAG_SUCCESSFUL_ACCESS: int +ADS_ACEFLAG_FAILED_ACCESS: int +ADS_FLAG_OBJECT_TYPE_PRESENT: int +ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT: int +ADS_SD_CONTROL_SE_OWNER_DEFAULTED: int +ADS_SD_CONTROL_SE_GROUP_DEFAULTED: int +ADS_SD_CONTROL_SE_DACL_PRESENT: int +ADS_SD_CONTROL_SE_DACL_DEFAULTED: int +ADS_SD_CONTROL_SE_SACL_PRESENT: int +ADS_SD_CONTROL_SE_SACL_DEFAULTED: int +ADS_SD_CONTROL_SE_DACL_AUTO_INHERIT_REQ: int +ADS_SD_CONTROL_SE_SACL_AUTO_INHERIT_REQ: int +ADS_SD_CONTROL_SE_DACL_AUTO_INHERITED: int +ADS_SD_CONTROL_SE_SACL_AUTO_INHERITED: int +ADS_SD_CONTROL_SE_DACL_PROTECTED: int +ADS_SD_CONTROL_SE_SACL_PROTECTED: int +ADS_SD_CONTROL_SE_SELF_RELATIVE: int +ADS_SD_REVISION_DS: int +ADS_NAME_TYPE_1779: int +ADS_NAME_TYPE_CANONICAL: int +ADS_NAME_TYPE_NT4: int +ADS_NAME_TYPE_DISPLAY: int +ADS_NAME_TYPE_DOMAIN_SIMPLE: int +ADS_NAME_TYPE_ENTERPRISE_SIMPLE: int +ADS_NAME_TYPE_GUID: int +ADS_NAME_TYPE_UNKNOWN: int +ADS_NAME_TYPE_USER_PRINCIPAL_NAME: int +ADS_NAME_TYPE_CANONICAL_EX: int +ADS_NAME_TYPE_SERVICE_PRINCIPAL_NAME: int +ADS_NAME_TYPE_SID_OR_SID_HISTORY_NAME: int +ADS_NAME_INITTYPE_DOMAIN: int +ADS_NAME_INITTYPE_SERVER: int +ADS_NAME_INITTYPE_GC: int +ADS_OPTION_SERVERNAME: int +ADS_OPTION_REFERRALS: Incomplete +ADS_OPTION_PAGE_SIZE: Incomplete +ADS_OPTION_SECURITY_MASK: Incomplete +ADS_OPTION_MUTUAL_AUTH_STATUS: Incomplete +ADS_OPTION_QUOTA: Incomplete +ADS_OPTION_PASSWORD_PORTNUMBER: Incomplete +ADS_OPTION_PASSWORD_METHOD: Incomplete +ADS_SECURITY_INFO_OWNER: int +ADS_SECURITY_INFO_GROUP: int +ADS_SECURITY_INFO_DACL: int +ADS_SECURITY_INFO_SACL: int +ADS_SETTYPE_FULL: int +ADS_SETTYPE_PROVIDER: int +ADS_SETTYPE_SERVER: int +ADS_SETTYPE_DN: int +ADS_FORMAT_WINDOWS: int +ADS_FORMAT_WINDOWS_NO_SERVER: int +ADS_FORMAT_WINDOWS_DN: int +ADS_FORMAT_WINDOWS_PARENT: int +ADS_FORMAT_X500: int +ADS_FORMAT_X500_NO_SERVER: int +ADS_FORMAT_X500_DN: int +ADS_FORMAT_X500_PARENT: int +ADS_FORMAT_SERVER: int +ADS_FORMAT_PROVIDER: int +ADS_FORMAT_LEAF: int +ADS_DISPLAY_FULL: int +ADS_DISPLAY_VALUE_ONLY: int +ADS_ESCAPEDMODE_DEFAULT: int +ADS_ESCAPEDMODE_ON: int +ADS_ESCAPEDMODE_OFF: int +ADS_ESCAPEDMODE_OFF_EX: int +ADS_PATH_FILE: int +ADS_PATH_FILESHARE: int +ADS_PATH_REGISTRY: int +ADS_SD_FORMAT_IID: int +ADS_SD_FORMAT_RAW: int +ADS_SD_FORMAT_HEXSTRING: int +E_ADS_BAD_PATHNAME: Incomplete +E_ADS_INVALID_DOMAIN_OBJECT: Incomplete +E_ADS_INVALID_USER_OBJECT: Incomplete +E_ADS_INVALID_COMPUTER_OBJECT: Incomplete +E_ADS_UNKNOWN_OBJECT: Incomplete +E_ADS_PROPERTY_NOT_SET: Incomplete +E_ADS_PROPERTY_NOT_SUPPORTED: Incomplete +E_ADS_PROPERTY_INVALID: Incomplete +E_ADS_BAD_PARAMETER: Incomplete +E_ADS_OBJECT_UNBOUND: Incomplete +E_ADS_PROPERTY_NOT_MODIFIED: Incomplete +E_ADS_PROPERTY_MODIFIED: Incomplete +E_ADS_CANT_CONVERT_DATATYPE: Incomplete +E_ADS_PROPERTY_NOT_FOUND: Incomplete +E_ADS_OBJECT_EXISTS: Incomplete +E_ADS_SCHEMA_VIOLATION: Incomplete +E_ADS_COLUMN_NOT_SET: Incomplete +S_ADS_ERRORSOCCURRED: Incomplete +S_ADS_NOMORE_ROWS: Incomplete +S_ADS_NOMORE_COLUMNS: Incomplete +E_ADS_INVALID_FILTER: Incomplete +ADS_DEREF_NEVER: int +ADS_DEREF_SEARCHING: int +ADS_DEREF_FINDING: int +ADS_DEREF_ALWAYS: int +ADSIPROP_ASYNCHRONOUS: int +ADSIPROP_DEREF_ALIASES: int +ADSIPROP_SIZE_LIMIT: int +ADSIPROP_TIME_LIMIT: int +ADSIPROP_ATTRIBTYPES_ONLY: int +ADSIPROP_SEARCH_SCOPE: int +ADSIPROP_TIMEOUT: int +ADSIPROP_PAGESIZE: int +ADSIPROP_PAGED_TIME_LIMIT: int +ADSIPROP_CHASE_REFERRALS: int +ADSIPROP_SORT_ON: int +ADSIPROP_CACHE_RESULTS: int +ADSIPROP_ADSIFLAG: int +ADSI_DIALECT_LDAP: int +ADSI_DIALECT_SQL: int +ADS_CHASE_REFERRALS_NEVER: int +ADS_CHASE_REFERRALS_SUBORDINATE: int +ADS_CHASE_REFERRALS_EXTERNAL: int +ADS_CHASE_REFERRALS_ALWAYS: Incomplete +DSOP_SCOPE_TYPE_TARGET_COMPUTER: int +DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN: int +DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN: int +DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN: int +DSOP_SCOPE_TYPE_GLOBAL_CATALOG: int +DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN: int +DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN: int +DSOP_SCOPE_TYPE_WORKGROUP: int +DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE: int +DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE: int +DSOP_SCOPE_FLAG_STARTING_SCOPE: int +DSOP_SCOPE_FLAG_WANT_PROVIDER_WINNT: int +DSOP_SCOPE_FLAG_WANT_PROVIDER_LDAP: int +DSOP_SCOPE_FLAG_WANT_PROVIDER_GC: int +DSOP_SCOPE_FLAG_WANT_SID_PATH: int +DSOP_SCOPE_FLAG_WANT_DOWNLEVEL_BUILTIN_PATH: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_COMPUTERS: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_CONTACTS: int +DSOP_FILTER_INCLUDE_ADVANCED_VIEW: int +DSOP_FILTER_USERS: int +DSOP_FILTER_BUILTIN_GROUPS: int +DSOP_FILTER_WELL_KNOWN_PRINCIPALS: int +DSOP_FILTER_UNIVERSAL_GROUPS_DL: int +DSOP_FILTER_UNIVERSAL_GROUPS_SE: int +DSOP_FILTER_GLOBAL_GROUPS_DL: int +DSOP_FILTER_GLOBAL_GROUPS_SE: int +DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL: int +DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE: int +DSOP_FILTER_CONTACTS: int +DSOP_FILTER_COMPUTERS: int +DSOP_DOWNLEVEL_FILTER_USERS: int +DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS: int +DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS: int +DSOP_DOWNLEVEL_FILTER_COMPUTERS: int +DSOP_DOWNLEVEL_FILTER_WORLD: int +DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER: int +DSOP_DOWNLEVEL_FILTER_ANONYMOUS: int +DSOP_DOWNLEVEL_FILTER_BATCH: int +DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER: int +DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP: int +DSOP_DOWNLEVEL_FILTER_DIALUP: int +DSOP_DOWNLEVEL_FILTER_INTERACTIVE: int +DSOP_DOWNLEVEL_FILTER_NETWORK: int +DSOP_DOWNLEVEL_FILTER_SERVICE: int +DSOP_DOWNLEVEL_FILTER_SYSTEM: int +DSOP_DOWNLEVEL_FILTER_EXCLUDE_BUILTIN_GROUPS: int +DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER: int +DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS: int +DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE: int +DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE: int +DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON: int +DSOP_FLAG_MULTISELECT: int +DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK: int +CFSTR_DSOP_DS_SELECTION_LIST: str diff --git a/stubs/pywin32/win32comext/authorization/__init__.pyi b/stubs/pywin32/win32comext/authorization/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/authorization/authorization.pyi b/stubs/pywin32/win32comext/authorization/authorization.pyi new file mode 100644 index 000000000000..9c2074bac7d8 --- /dev/null +++ b/stubs/pywin32/win32comext/authorization/authorization.pyi @@ -0,0 +1,5 @@ +import _win32typing + +def EditSecurity(hwndOwner, psi): ... + +IID_ISecurityInformation: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/axcontrol/__init__.pyi b/stubs/pywin32/win32comext/axcontrol/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axcontrol/axcontrol.pyi b/stubs/pywin32/win32comext/axcontrol/axcontrol.pyi new file mode 100644 index 000000000000..53be3619c840 --- /dev/null +++ b/stubs/pywin32/win32comext/axcontrol/axcontrol.pyi @@ -0,0 +1,61 @@ +import _win32typing + +def OleCreate( + clsid, + clsid1, + obCLSID: _win32typing.PyIID, + obIID: _win32typing.PyIID, + renderopt, + obFormatEtc, + obOleClientSite: _win32typing.PyIOleClientSite, + obStorage: _win32typing.PyIStorage, + /, +) -> _win32typing.PyIOleObject: ... +def OleLoadPicture( + stream: _win32typing.PyIStream, size, runMode, arg: _win32typing.PyIID, arg1: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def OleLoadPicturePath( + url_or_path: str, unk, reserved, clr, arg: _win32typing.PyIID, arg1: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def OleSetContainedObject(unk: _win32typing.PyIUnknown, fContained, /) -> None: ... +def OleTranslateAccelerator(frame: _win32typing.PyIOleInPlaceFrame, frame_info, msg: _win32typing.PyMSG, /) -> None: ... + +EMBDHLP_CREATENOW: int +EMBDHLP_DELAYCREATE: int +EMBDHLP_INPROC_HANDLER: int +EMBDHLP_INPROC_SERVER: int +OLECLOSE_NOSAVE: int +OLECLOSE_PROMPTSAVE: int +OLECLOSE_SAVEIFDIRTY: int +OLECMDF_ENABLED: int +OLECMDF_LATCHED: int +OLECMDF_NINCHED: int +OLECMDF_SUPPORTED: int +OLECMDTEXTF_NAME: int +OLECMDTEXTF_NONE: int +OLECMDTEXTF_STATUS: int +OLECREATE_LEAVERUNNING: int +OLEIVERB_DISCARDUNDOSTATE: int +OLEIVERB_HIDE: int +OLEIVERB_INPLACEACTIVATE: int +OLEIVERB_OPEN: int +OLEIVERB_PRIMARY: int +OLEIVERB_SHOW: int +OLEIVERB_UIACTIVATE: int +IID_IObjectWithSite: _win32typing.PyIID +IID_IOleClientSite: _win32typing.PyIID +IID_IOleCommandTarget: _win32typing.PyIID +IID_IOleControl: _win32typing.PyIID +IID_IOleControlSite: _win32typing.PyIID +IID_IOleInPlaceActiveObject: _win32typing.PyIID +IID_IOleInPlaceFrame: _win32typing.PyIID +IID_IOleInPlaceObject: _win32typing.PyIID +IID_IOleInPlaceSite: _win32typing.PyIID +IID_IOleInPlaceSiteEx: _win32typing.PyIID +IID_IOleInPlaceSiteWindowless: _win32typing.PyIID +IID_IOleInPlaceUIWindow: _win32typing.PyIID +IID_IOleLink: _win32typing.PyIID +IID_IOleObject: _win32typing.PyIID +IID_ISpecifyPropertyPages: _win32typing.PyIID +IID_IViewObject: _win32typing.PyIID +IID_IViewObject2: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/axdebug/__init__.pyi b/stubs/pywin32/win32comext/axdebug/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axdebug/adb.pyi b/stubs/pywin32/win32comext/axdebug/adb.pyi new file mode 100644 index 000000000000..ec29264a8ed9 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/adb.pyi @@ -0,0 +1,71 @@ +import bdb +from _typeshed import Incomplete + +from win32comext.axdebug import gateways +from win32comext.axdebug.util import trace + +def fnull(*args) -> None: ... + +debugging: int +traceenter = fnull +tracev = fnull +traceenter = trace +tracev = trace + +class OutputReflector: + writefunc: Incomplete + file: Incomplete + def __init__(self, file, writefunc) -> None: ... + def __getattr__(self, name: str): ... + def write(self, message) -> None: ... + +g_adb: Incomplete + +def OnSetBreakPoint(codeContext, breakPointState, lineNo) -> None: ... + +class Adb(bdb.Bdb, gateways.RemoteDebugApplicationEvents): + debugApplication: Incomplete + debuggingThread: Incomplete + debuggingThreadStateHandle: Incomplete + stackSnifferCookie: Incomplete + codeContainerProvider: Incomplete + breakFlags: Incomplete + breakReason: Incomplete + appDebugger: Incomplete + appEventConnection: Incomplete + logicalbotframe: Incomplete + currentframe: Incomplete + recursiveData: Incomplete + def __init__(self) -> None: ... + def canonic(self, fname): ... + def reset(self) -> None: ... + def stop_here(self, frame): ... + def break_here(self, frame): ... + def break_anywhere(self, frame): ... + def dispatch_return(self, frame, arg): ... + def dispatch_line(self, frame): ... + def dispatch_call(self, frame, arg): ... + def trace_dispatch(self, frame, event, arg): ... + def user_line(self, frame) -> None: ... + def user_return(self, frame, return_value) -> None: ... + def user_exception(self, frame, exc_info) -> None: ... + def set_trace(self) -> None: ... # type: ignore[override] + def CloseApp(self) -> None: ... + stackSniffer: Incomplete + def AttachApp(self, debugApplication, codeContainerProvider) -> None: ... + def ResetAXDebugging(self) -> None: ... + botframe: Incomplete + stopframe: Incomplete + def SetupAXDebugging(self, baseFrame: Incomplete | None = ..., userFrame: Incomplete | None = ...) -> None: ... + def OnConnectDebugger(self, appDebugger): ... + def OnDisconnectDebugger(self) -> None: ... + def OnSetName(self, name) -> None: ... + def OnDebugOutput(self, string) -> None: ... + def OnClose(self) -> None: ... + def OnEnterBreakPoint(self, rdat) -> None: ... + def OnLeaveBreakPoint(self, rdat) -> None: ... + def OnCreateThread(self, rdat) -> None: ... + def OnDestroyThread(self, rdat) -> None: ... + def OnBreakFlagChange(self, abf, rdat) -> None: ... + +def Debugger(): ... diff --git a/stubs/pywin32/win32comext/axdebug/axdebug.pyi b/stubs/pywin32/win32comext/axdebug/axdebug.pyi new file mode 100644 index 000000000000..d4862d071ef4 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/axdebug.pyi @@ -0,0 +1,122 @@ +# Can't generate with stubgen because: +# "ImportError: DLL load failed while importing axdebug: The specified module could not be found." +import _win32typing + +def GetStackAddress() -> int: ... +def GetThreadStateHandle() -> int: ... +def SetThreadStateTrace(handle: int, func, /) -> None: ... + +APPBREAKFLAG_DEBUGGER_BLOCK: int +APPBREAKFLAG_DEBUGGER_HALT: int +APPBREAKFLAG_STEP: int +BREAKPOINT_DELETED: int +BREAKPOINT_DISABLED: int +BREAKPOINT_ENABLED: int +BREAKREASON_BREAKPOINT: int +BREAKREASON_DEBUGGER_BLOCK: int +BREAKREASON_DEBUGGER_HALT: int +BREAKREASON_ERROR: int +BREAKREASON_HOST_INITIATED: int +BREAKREASON_LANGUAGE_INITIATED: int +BREAKREASON_STEP: int +BREAKRESUMEACTION_ABORT: int +BREAKRESUMEACTION_CONTINUE: int +BREAKRESUMEACTION_STEP_INTO: int +BREAKRESUMEACTION_STEP_OUT: int +BREAKRESUMEACTION_STEP_OVER: int +CLSID_DefaultDebugSessionProvider: int +CLSID_MachineDebugManager: int +CLSID_ProcessDebugManager: int +DBGPROP_ATTRIB_ACCESS_FINAL: int +DBGPROP_ATTRIB_ACCESS_PRIVATE: int +DBGPROP_ATTRIB_ACCESS_PROTECTED: int +DBGPROP_ATTRIB_ACCESS_PUBLIC: int +DBGPROP_ATTRIB_HAS_EXTENDED_ATTRIBS: int +DBGPROP_ATTRIB_NO_ATTRIB: int +DBGPROP_ATTRIB_STORAGE_FIELD: int +DBGPROP_ATTRIB_STORAGE_GLOBAL: int +DBGPROP_ATTRIB_STORAGE_STATIC: int +DBGPROP_ATTRIB_STORAGE_VIRTUAL: int +DBGPROP_ATTRIB_TYPE_IS_CONSTANT: int +DBGPROP_ATTRIB_TYPE_IS_SYNCHRONIZED: int +DBGPROP_ATTRIB_TYPE_IS_VOLATILE: int +DBGPROP_ATTRIB_VALUE_IS_EXPANDABLE: int +DBGPROP_ATTRIB_VALUE_IS_INVALID: int +DBGPROP_ATTRIB_VALUE_READONLY: int +DBGPROP_INFO_ATTRIBUTES: int +DBGPROP_INFO_AUTOEXPAND: int +DBGPROP_INFO_DEBUGPROP: int +DBGPROP_INFO_FULLNAME: int +DBGPROP_INFO_NAME: int +DBGPROP_INFO_TYPE: int +DBGPROP_INFO_VALUE: int +DEBUG_TEXT_ALLOWBREAKPOINTS: int +DEBUG_TEXT_ISEXPRESSION: int +DOCUMENTNAMETYPE_APPNODE: int +DOCUMENTNAMETYPE_FILE_TAIL: int +DOCUMENTNAMETYPE_TITLE: int +DOCUMENTNAMETYPE_URL: int +ERRORRESUMEACTION_AbortCallAndReturnErrorToCaller: int +ERRORRESUMEACTION_ReexecuteErrorStatement: int +ERRORRESUMEACTION_SkipErrorStatement: int +EX_DBGPROP_INFO_DEBUGEXTPROP: int +EX_DBGPROP_INFO_ID: int +EX_DBGPROP_INFO_LOCKBYTES: int +EX_DBGPROP_INFO_NTYPE: int +EX_DBGPROP_INFO_NVALUE: int +SOURCETEXT_ATTR_COMMENT: int +SOURCETEXT_ATTR_FUNCTION_START: int +SOURCETEXT_ATTR_KEYWORD: int +SOURCETEXT_ATTR_NONSOURCE: int +SOURCETEXT_ATTR_NUMBER: int +SOURCETEXT_ATTR_OPERATOR: int +SOURCETEXT_ATTR_STRING: int +TEXT_DOC_ATTR_READONLY: int +APPBREAKFLAG_IN_BREAKPOINT: int +APPBREAKFLAG_STEPTYPE_BYTECODE: int +APPBREAKFLAG_STEPTYPE_MACHINE: int +APPBREAKFLAG_STEPTYPE_MASK: int +APPBREAKFLAG_STEPTYPE_SOURCE: int + +IID_IActiveScriptDebug: _win32typing.PyIID +IID_IActiveScriptErrorDebug: _win32typing.PyIID +IID_IActiveScriptSiteDebug: _win32typing.PyIID +IID_IApplicationDebugger: _win32typing.PyIID +IID_IDebugApplication: _win32typing.PyIID +IID_IDebugApplicationNode: _win32typing.PyIID +IID_IDebugApplicationNodeEvents: _win32typing.PyIID +IID_IDebugApplicationThread: _win32typing.PyIID +IID_IDebugCodeContext: _win32typing.PyIID +IID_IDebugDocument: _win32typing.PyIID +IID_IDebugDocumentContext: _win32typing.PyIID +IID_IDebugDocumentHelper: _win32typing.PyIID +IID_IDebugDocumentHost: _win32typing.PyIID +IID_IDebugDocumentInfo: _win32typing.PyIID +IID_IDebugDocumentProvider: _win32typing.PyIID +IID_IDebugDocumentText: _win32typing.PyIID +IID_IDebugDocumentTextAuthor: _win32typing.PyIID +IID_IDebugDocumentTextEvents: _win32typing.PyIID +IID_IDebugDocumentTextExternalAuthor: _win32typing.PyIID +IID_IDebugExpression: _win32typing.PyIID +IID_IDebugExpressionCallBack: _win32typing.PyIID +IID_IDebugExpressionContext: _win32typing.PyIID +IID_IDebugProperty: _win32typing.PyIID +IID_IDebugSessionProvider: _win32typing.PyIID +IID_IDebugStackFrame: _win32typing.PyIID +IID_IDebugStackFrameSniffer: _win32typing.PyIID +IID_IDebugStackFrameSnifferEx: _win32typing.PyIID +IID_IDebugSyncOperation: _win32typing.PyIID +IID_IEnumDebugApplicationNodes: _win32typing.PyIID +IID_IEnumDebugCodeContexts: _win32typing.PyIID +IID_IEnumDebugExpressionContexts: _win32typing.PyIID +IID_IEnumDebugPropertyInfo: _win32typing.PyIID +IID_IEnumDebugStackFrames: _win32typing.PyIID +IID_IEnumRemoteDebugApplicationThreads: _win32typing.PyIID +IID_IEnumRemoteDebugApplications: _win32typing.PyIID +IID_IMachineDebugManager: _win32typing.PyIID +IID_IMachineDebugManagerEvents: _win32typing.PyIID +IID_IProcessDebugManager: _win32typing.PyIID +IID_IProvideExpressionContexts: _win32typing.PyIID +IID_IRemoteDebugApplication: _win32typing.PyIID +IID_IRemoteDebugApplicationEvents: _win32typing.PyIID +IID_IRemoteDebugApplicationThread: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/axdebug/codecontainer.pyi b/stubs/pywin32/win32comext/axdebug/codecontainer.pyi new file mode 100644 index 000000000000..29dbc568a34b --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/codecontainer.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete + +class SourceCodeContainer: + sourceContext: Incomplete + text: Incomplete + nextLineNo: int + fileName: Incomplete + codeContexts: Incomplete + site: Incomplete + startLineNumber: Incomplete + debugDocument: Incomplete | None + def __init__( + self, + text, + fileName: str = ..., + sourceContext: int = ..., + startLineNumber: int = ..., + site: Incomplete | None = ..., + debugDocument: Incomplete | None = ..., + ) -> None: ... + def GetText(self): ... + def GetName(self, dnt) -> None: ... + def GetFileName(self): ... + def GetPositionOfLine(self, cLineNumber): ... + def GetLineOfPosition(self, charPos): ... + def GetNextLine(self): ... + def GetLine(self, num): ... + def GetNumChars(self): ... + def GetNumLines(self): ... + lastPos: int + attrs: Incomplete + def GetSyntaxColorAttributes(self): ... + def GetCodeContextAtPosition(self, charPos): ... + +class SourceModuleContainer(SourceCodeContainer): + module: Incomplete + def __init__(self, module) -> None: ... + text: Incomplete + def GetText(self): ... + def GetName(self, dnt): ... diff --git a/stubs/pywin32/win32comext/axdebug/contexts.pyi b/stubs/pywin32/win32comext/axdebug/contexts.pyi new file mode 100644 index 000000000000..f3d9528f774e --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/contexts.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways + +class DebugCodeContext(gateways.DebugCodeContext, gateways.DebugDocumentContext): + debugSite: Incomplete + offset: Incomplete + length: Incomplete + breakPointState: int + lineno: Incomplete + codeContainer: Incomplete + def __init__(self, lineNo, charPos, len, codeContainer, debugSite) -> None: ... + def GetDocumentContext(self): ... + def SetBreakPoint(self, bps) -> None: ... + def GetDocument(self): ... + def EnumCodeContexts(self): ... + +class EnumDebugCodeContexts(gateways.EnumDebugCodeContexts): ... diff --git a/stubs/pywin32/win32comext/axdebug/debugger.pyi b/stubs/pywin32/win32comext/axdebug/debugger.pyi new file mode 100644 index 000000000000..851ce60c20b2 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/debugger.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import documents + +currentDebugger: Incomplete + +class ModuleTreeNode: + moduleName: Incomplete + module: Incomplete + realNode: Incomplete + cont: Incomplete + def __init__(self, module) -> None: ... + def Attach(self, parentRealNode) -> None: ... + def Close(self) -> None: ... + +def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args) -> None: ... +def RefreshAllModules(builtItems, rootNode, create_node, create_node_args) -> None: ... + +class CodeContainerProvider(documents.CodeContainerProvider): + axdebugger: Incomplete + currentNumModules: Incomplete + nodes: Incomplete + def __init__(self, axdebugger) -> None: ... + def FromFileName(self, fname): ... + def Close(self) -> None: ... + +class OriginalInterfaceMaker: + cookie: Incomplete + def MakeInterfaces(self, pdm): ... + def CloseInterfaces(self, pdm) -> None: ... + +class SimpleHostStyleInterfaceMaker: + def MakeInterfaces(self, pdm): ... + def CloseInterfaces(self, pdm) -> None: ... + +class AXDebugger: + pydebugger: Incomplete + pdm: Incomplete + interfaceMaker: Incomplete + expressionCookie: Incomplete + def __init__(self, interfaceMaker: Incomplete | None = ..., processName: Incomplete | None = ...) -> None: ... + def Break(self) -> None: ... + app: Incomplete + root: Incomplete + def Close(self) -> None: ... + def RefreshAllModules(self, nodes, containerProvider) -> None: ... + def CreateApplicationNode(self, node, containerProvider): ... + +def Break() -> None: ... + +brk = Break +set_trace = Break + +def dosomethingelse() -> None: ... +def dosomething() -> None: ... +def test() -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/documents.pyi b/stubs/pywin32/win32comext/axdebug/documents.pyi new file mode 100644 index 000000000000..33b767822ea8 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/documents.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways + +def GetGoodFileName(fname): ... + +class DebugDocumentProvider(gateways.DebugDocumentProvider): + doc: Incomplete + def __init__(self, doc) -> None: ... + def GetName(self, dnt): ... + def GetDocumentClassId(self): ... + def GetDocument(self): ... + +class DebugDocumentText(gateways.DebugDocumentText): + codeContainer: Incomplete + def __init__(self, codeContainer) -> None: ... + def GetName(self, dnt): ... + def GetDocumentClassId(self): ... + def GetSize(self): ... + def GetPositionOfLine(self, cLineNumber): ... + def GetLineOfPosition(self, charPos): ... + def GetText(self, charPos, maxChars, wantAttr): ... + def GetPositionOfContext(self, context): ... + def GetContextOfPosition(self, charPos, maxChars): ... + +class CodeContainerProvider: + ccsAndNodes: Incomplete + def AddCodeContainer(self, cc, node: Incomplete | None = ...) -> None: ... + def FromFileName(self, fname): ... + def Close(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/expressions.pyi b/stubs/pywin32/win32comext/axdebug/expressions.pyi new file mode 100644 index 000000000000..2406702c2fbd --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/expressions.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete + +from win32com.server.util import ListEnumeratorGateway +from win32comext.axdebug import gateways + +def MakeNiceString(ob): ... + +class ProvideExpressionContexts(gateways.ProvideExpressionContexts): ... + +class ExpressionContext(gateways.DebugExpressionContext): + frame: Incomplete + def __init__(self, frame) -> None: ... + def ParseLanguageText(self, code, radix, delim, flags): ... + def GetLanguageInfo(self): ... + +class Expression(gateways.DebugExpression): + callback: Incomplete + frame: Incomplete + code: Incomplete + radix: Incomplete + delim: Incomplete + flags: Incomplete + isComplete: int + result: Incomplete + hresult: Incomplete + def __init__(self, frame, code, radix, delim, flags) -> None: ... + def Start(self, callback): ... + def Abort(self) -> None: ... + def QueryIsComplete(self): ... + def GetResultAsString(self): ... + def GetResultAsDebugProperty(self): ... + +def MakeEnumDebugProperty(object, dwFieldSpec, nRadix, iid, stackFrame: Incomplete | None = ...): ... +def GetPropertyInfo( + obname, + obvalue, + dwFieldSpec, + nRadix, + hresult: int = ..., + dictionary: Incomplete | None = ..., + stackFrame: Incomplete | None = ..., +): ... + +class EnumDebugPropertyInfo(ListEnumeratorGateway): + def GetCount(self): ... + +class DebugProperty: + name: Incomplete + value: Incomplete + parent: Incomplete + hresult: Incomplete + dictionary: Incomplete + stackFrame: Incomplete + def __init__( + self, + name, + value, + parent: Incomplete | None = ..., + hresult: int = ..., + dictionary: Incomplete | None = ..., + stackFrame: Incomplete | None = ..., + ) -> None: ... + def GetPropertyInfo(self, dwFieldSpec, nRadix): ... + def GetExtendedInfo(self) -> None: ... + def SetValueAsString(self, value, radix) -> None: ... + def EnumMembers(self, dwFieldSpec, nRadix, iid): ... + def GetParent(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/gateways.pyi b/stubs/pywin32/win32comext/axdebug/gateways.pyi new file mode 100644 index 000000000000..8ed3bb31692c --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/gateways.pyi @@ -0,0 +1,114 @@ +from _typeshed import Incomplete + +from win32com.server.util import ListEnumeratorGateway + +class EnumDebugCodeContexts(ListEnumeratorGateway): ... +class EnumDebugStackFrames(ListEnumeratorGateway): ... +class EnumDebugApplicationNodes(ListEnumeratorGateway): ... +class EnumRemoteDebugApplications(ListEnumeratorGateway): ... +class EnumRemoteDebugApplicationThreads(ListEnumeratorGateway): ... + +class DebugDocumentInfo: + def GetName(self, dnt) -> None: ... + def GetDocumentClassId(self) -> None: ... + +class DebugDocumentProvider(DebugDocumentInfo): + def GetDocument(self) -> None: ... + +class DebugApplicationNode(DebugDocumentProvider): + def EnumChildren(self) -> None: ... + def GetParent(self) -> None: ... + def SetDocumentProvider(self, pddp) -> None: ... + def Close(self) -> None: ... + def Attach(self, parent) -> None: ... + def Detach(self) -> None: ... + +class DebugApplicationNodeEvents: + def onAddChild(self, child) -> None: ... + def onRemoveChild(self, child) -> None: ... + def onDetach(self) -> None: ... + def onAttach(self, parent) -> None: ... + +class DebugDocument(DebugDocumentInfo): ... + +class DebugDocumentText(DebugDocument): + def GetDocumentAttributes(self) -> None: ... + def GetSize(self) -> None: ... + def GetPositionOfLine(self, cLineNumber) -> None: ... + def GetLineOfPosition(self, charPos) -> None: ... + def GetText(self, charPos, maxChars, wantAttr) -> None: ... + def GetPositionOfContext(self, debugDocumentContext) -> None: ... + def GetContextOfPosition(self, charPos, maxChars) -> None: ... + +class DebugDocumentTextExternalAuthor: + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class DebugDocumentTextEvents: + def onDestroy(self) -> None: ... + def onInsertText(self, cCharacterPosition, cNumToInsert) -> None: ... + def onRemoveText(self, cCharacterPosition, cNumToRemove) -> None: ... + def onReplaceText(self, cCharacterPosition, cNumToReplace) -> None: ... + def onUpdateTextAttributes(self, cCharacterPosition, cNumToUpdate) -> None: ... + def onUpdateDocumentAttributes(self, textdocattr) -> None: ... + +class DebugDocumentContext: + def GetDocument(self) -> None: ... + def EnumCodeContexts(self) -> None: ... + +class DebugCodeContext: + def GetDocumentContext(self) -> None: ... + def SetBreakPoint(self, bps) -> None: ... + +class DebugStackFrame: + def GetCodeContext(self) -> None: ... + def GetDescriptionString(self, fLong) -> None: ... + def GetLanguageString(self) -> None: ... + def GetThread(self) -> None: ... + def GetDebugProperty(self) -> None: ... + +class DebugDocumentHost: + def GetDeferredText(self, dwTextStartCookie, maxChars, bWantAttr) -> None: ... + def GetScriptTextAttributes(self, codeText, delimterText, flags) -> None: ... + def OnCreateDocumentContext(self) -> None: ... + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class DebugDocumentTextConnectServer: + cookieNo: int + connections: Incomplete + def EnumConnections(self) -> None: ... + def GetConnectionInterface(self) -> None: ... + def GetConnectionPointContainer(self): ... + def Advise(self, pUnk): ... + def Unadvise(self, cookie): ... + def EnumConnectionPoints(self) -> None: ... + def FindConnectionPoint(self, iid): ... + +class RemoteDebugApplicationEvents: + def OnConnectDebugger(self, appDebugger) -> None: ... + def OnDisconnectDebugger(self) -> None: ... + def OnSetName(self, name) -> None: ... + def OnDebugOutput(self, string) -> None: ... + def OnClose(self) -> None: ... + def OnEnterBreakPoint(self, rdat) -> None: ... + def OnLeaveBreakPoint(self, rdat) -> None: ... + def OnCreateThread(self, rdat) -> None: ... + def OnDestroyThread(self, rdat) -> None: ... + def OnBreakFlagChange(self, abf, rdat) -> None: ... + +class DebugExpressionContext: + def ParseLanguageText(self, code, radix, delim, flags) -> None: ... + def GetLanguageInfo(self) -> None: ... + +class DebugExpression: + def Start(self, callback) -> None: ... + def Abort(self) -> None: ... + def QueryIsComplete(self) -> None: ... + def GetResultAsString(self) -> None: ... + def GetResultAsDebugProperty(self) -> None: ... + +class ProvideExpressionContexts: + def EnumExpressionContexts(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/stackframe.pyi b/stubs/pywin32/win32comext/axdebug/stackframe.pyi new file mode 100644 index 000000000000..6c12e6d28d82 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/stackframe.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways + +class EnumDebugStackFrames(gateways.EnumDebugStackFrames): + def __init__(self, debugger) -> None: ... + def Next(self, count): ... + +class DebugStackFrame(gateways.DebugStackFrame): + frame: Incomplete + lineno: Incomplete + codeContainer: Incomplete + expressionContext: Incomplete + def __init__(self, frame, lineno, codeContainer) -> None: ... + def GetThread(self) -> None: ... + def GetCodeContext(self): ... + def GetDescriptionString(self, fLong): ... + def GetLanguageString(self, fLong): ... # type: ignore[override] + def GetDebugProperty(self): ... + +class DebugStackFrameSniffer: + debugger: Incomplete + def __init__(self, debugger) -> None: ... + def EnumStackFrames(self): ... + +class StackFrameDebugProperty: + frame: Incomplete + def __init__(self, frame) -> None: ... + def GetPropertyInfo(self, dwFieldSpec, nRadix) -> None: ... + def GetExtendedInfo(self) -> None: ... + def SetValueAsString(self, value, radix) -> None: ... + def EnumMembers(self, dwFieldSpec, nRadix, iid): ... + def GetParent(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/util.pyi b/stubs/pywin32/win32comext/axdebug/util.pyi new file mode 100644 index 000000000000..82b53ac6c07b --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/util.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +import win32com.server.dispatcher + +debugging: int + +def trace(*args) -> None: ... +def RaiseNotImpl(who: Incomplete | None = ...) -> None: ... + +class Dispatcher(win32com.server.dispatcher.DispatcherWin32trace): + def __init__(self, policyClass, object) -> None: ... diff --git a/stubs/pywin32/win32comext/axscript/__init__.pyi b/stubs/pywin32/win32comext/axscript/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axscript/asputil.pyi b/stubs/pywin32/win32comext/axscript/asputil.pyi new file mode 100644 index 000000000000..37227df960b9 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/asputil.pyi @@ -0,0 +1 @@ +def iif(cond, t, f): ... diff --git a/stubs/pywin32/win32comext/axscript/axscript.pyi b/stubs/pywin32/win32comext/axscript/axscript.pyi new file mode 100644 index 000000000000..8914786fa932 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/axscript.pyi @@ -0,0 +1,52 @@ +import _win32typing + +CATID_ActiveScript: _win32typing.PyIID +CATID_ActiveScriptParse: _win32typing.PyIID +IID_IActiveScript: _win32typing.PyIID +IID_IActiveScriptError: _win32typing.PyIID +IID_IActiveScriptParse: _win32typing.PyIID +IID_IActiveScriptParseProcedure: _win32typing.PyIID +IID_IActiveScriptSite: _win32typing.PyIID +IID_IObjectSafety: _win32typing.PyIID +IID_IProvideMultipleClassInfo: _win32typing.PyIID +INTERFACESAFE_FOR_UNTRUSTED_CALLER: int +INTERFACESAFE_FOR_UNTRUSTED_DATA: int +INTERFACE_USES_DISPEX: int +INTERFACE_USES_SECURITY_MANAGER: int +MULTICLASSINFO_GETIIDPRIMARY: int +MULTICLASSINFO_GETIIDSOURCE: int +MULTICLASSINFO_GETNUMRESERVEDDISPIDS: int +MULTICLASSINFO_GETTYPEINFO: int +SCRIPTINFO_ALL_FLAGS: int +SCRIPTINFO_ITYPEINFO: int +SCRIPTINFO_IUNKNOWN: int +SCRIPTINTERRUPT_ALL_FLAGS: int +SCRIPTINTERRUPT_DEBUG: int +SCRIPTINTERRUPT_RAISEEXCEPTION: int +SCRIPTITEM_ALL_FLAGS: int +SCRIPTITEM_CODEONLY: int +SCRIPTITEM_GLOBALMEMBERS: int +SCRIPTITEM_ISPERSISTENT: int +SCRIPTITEM_ISSOURCE: int +SCRIPTITEM_ISVISIBLE: int +SCRIPTITEM_NOCODE: int +SCRIPTPROC_ALL_FLAGS: int +SCRIPTPROC_HOSTMANAGESSOURCE: int +SCRIPTPROC_IMPLICIT_PARENTS: int +SCRIPTPROC_IMPLICIT_THIS: int +SCRIPTSTATE_CLOSED: int +SCRIPTSTATE_CONNECTED: int +SCRIPTSTATE_DISCONNECTED: int +SCRIPTSTATE_INITIALIZED: int +SCRIPTSTATE_STARTED: int +SCRIPTSTATE_UNINITIALIZED: int +SCRIPTTEXT_ALL_FLAGS: int +SCRIPTTEXT_ISEXPRESSION: int +SCRIPTTEXT_ISPERSISTENT: int +SCRIPTTEXT_ISVISIBLE: int +SCRIPTTHREADSTATE_NOTINSCRIPT: int +SCRIPTTHREADSTATE_RUNNING: int +SCRIPTTYPELIB_ISCONTROL: int +SCRIPTTYPELIB_ISPERSISTENT: int +SCRIPT_E_REPORTED: int +TIFLAGS_EXTENDDISPATCHONLY: int diff --git a/stubs/pywin32/win32comext/axscript/client/__init__.pyi b/stubs/pywin32/win32comext/axscript/client/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axscript/client/debug.pyi b/stubs/pywin32/win32comext/axscript/client/debug.pyi new file mode 100644 index 000000000000..8c1752564df6 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/client/debug.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways +from win32comext.axdebug.codecontainer import SourceCodeContainer + +debuggingTrace: int + +def trace(*args) -> None: ... + +class DebugManager: + scriptEngine: Incomplete + adb: Incomplete + rootNode: Incomplete + debugApplication: Incomplete + ccProvider: Incomplete + scriptSiteDebug: Incomplete + activeScriptDebug: Incomplete + codeContainers: Incomplete + def __init__(self, scriptEngine) -> None: ... + def Close(self) -> None: ... + def IsAnyHost(self): ... + def IsSimpleHost(self): ... + def HandleRuntimeError(self): ... + def OnEnterScript(self) -> None: ... + def OnLeaveScript(self) -> None: ... + def AddScriptBlock(self, codeBlock) -> None: ... + +class DebugCodeBlockContainer(SourceCodeContainer): + codeBlock: Incomplete + def __init__(self, codeBlock, site) -> None: ... + def GetName(self, dnt): ... + +class EnumDebugCodeContexts(gateways.EnumDebugCodeContexts): ... + +class ActiveScriptDebug: + debugMgr: Incomplete + scriptSiteDebug: Incomplete + codeContainers: Incomplete + def __init__(self, debugMgr, codeContainers) -> None: ... + def GetScriptTextAttributes(self, code, delim, flags): ... + def GetScriptletTextAttributes(self, code, delim, flags): ... + def EnumCodeContextsOfPosition(self, context, charOffset, numChars): ... diff --git a/stubs/pywin32/win32comext/axscript/client/error.pyi b/stubs/pywin32/win32comext/axscript/client/error.pyi new file mode 100644 index 000000000000..b35b7599cf31 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/client/error.pyi @@ -0,0 +1,35 @@ +from types import TracebackType + +from win32com.server.exception import COMException +from win32comext.axscript.client.debug import DebugManager +from win32comext.axscript.client.framework import AXScriptCodeBlock, COMScript +from win32comext.axscript.server.axsite import AXSite + +debugging: int + +def FormatForAX(text: str) -> str: ... +def ExpandTabs(text: str) -> str: ... +def AddCR(text: str) -> str: ... + +class IActiveScriptError: + def GetSourceLineText(self) -> str | None: ... + def GetSourcePosition(self) -> tuple[int, int, int]: ... + def GetExceptionInfo(self) -> AXScriptException: ... + +class AXScriptException(COMException): + sourceContext: int + startLineNo: int + linetext: str + def __init__( + self, + site: COMScript, + codeBlock: AXScriptCodeBlock | None, + exc_type: None = None, + exc_value: BaseException | None = None, + exc_traceback: None = None, + ) -> None: ... + def ExtractTracebackInfo(self, tb: TracebackType, site: COMScript) -> tuple[str, int, str, str | None]: ... + +def ProcessAXScriptException( + scriptingSite: AXSite, debugManager: DebugManager, exceptionInstance: AXScriptException +) -> COMException | AXScriptException | None: ... diff --git a/stubs/pywin32/win32comext/axscript/client/framework.pyi b/stubs/pywin32/win32comext/axscript/client/framework.pyi new file mode 100644 index 000000000000..19de3698f06a --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/client/framework.pyi @@ -0,0 +1,154 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +def RemoveCR(text): ... + +SCRIPTTEXT_FORCEEXECUTION: int +SCRIPTTEXT_ISEXPRESSION: int +SCRIPTTEXT_ISPERSISTENT: int +state_map: Incomplete + +def profile(fn, *args): ... + +class SafeOutput: + softspace: int + redir: Incomplete + def __init__(self, redir=None) -> None: ... + def write(self, message) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... + +def MakeValidSysOuts() -> None: ... +def trace(*args) -> None: ... +def RaiseAssert(scode, desc) -> Never: ... + +class AXScriptCodeBlock: + name: Incomplete + codeText: Incomplete + codeObject: Incomplete + sourceContextCookie: Incomplete + startLineNumber: Incomplete + flags: Incomplete + beenExecuted: int + def __init__(self, name: str, codeText: str, sourceContextCookie: int, startLineNumber: int, flags) -> None: ... + def GetFileName(self): ... + def GetDisplayName(self): ... + def GetLineNo(self, no: int): ... + +class Event: + name: str + def __init__(self) -> None: ... + def Reset(self) -> None: ... + def Close(self) -> None: ... + dispid: Incomplete + def Build(self, typeinfo, funcdesc) -> None: ... + +class EventSink: + events: Incomplete + connection: Incomplete + coDispatch: Incomplete + myScriptItem: Incomplete + myInvokeMethod: Incomplete + iid: Incomplete + def __init__(self, myItem, coDispatch) -> None: ... + def Reset(self) -> None: ... + def Close(self) -> None: ... + def GetSourceTypeInfo(self, typeinfo): ... + def BuildEvents(self) -> None: ... + def Connect(self) -> None: ... + def Disconnect(self) -> None: ... + +class ScriptItem: + parentItem: Incomplete + dispatch: Incomplete + name: Incomplete + flags: Incomplete + eventSink: Incomplete + subItems: Incomplete + createdConnections: int + isRegistered: int + def __init__(self, parentItem, name, dispatch, flags) -> None: ... + def Reset(self) -> None: ... + def Close(self) -> None: ... + def Register(self) -> None: ... + def IsGlobal(self): ... + def IsVisible(self): ... + def GetEngine(self): ... + def GetSubItemClass(self): ... + def GetSubItem(self, name): ... + def GetCreateSubItem(self, parentItem, name, dispatch, flags): ... + def CreateConnections(self) -> None: ... + def Connect(self) -> None: ... + def Disconnect(self) -> None: ... + def BuildEvents(self) -> None: ... + def FindBuildSubItemEvents(self) -> None: ... + def GetDefaultSourceTypeInfo(self, typeinfo): ... + +IActiveScriptMethods: Incomplete +IActiveScriptParseMethods: Incomplete +IObjectSafetyMethods: Incomplete +IActiveScriptParseProcedureMethods: Incomplete + +class COMScript: + baseThreadId: int + debugManager: Incomplete + threadState: Incomplete + scriptState: Incomplete + scriptSite: Incomplete + safetyOptions: int + lcid: int + subItems: Incomplete + scriptCodeBlocks: Incomplete + def __init__(self) -> None: ... + def InitNew(self) -> None: ... + def AddScriptlet( + self, defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber + ) -> None: ... + def ParseScriptText(self, code, itemName, context, delimiter, sourceContextCookie, startLineNumber, flags, bWantResult): ... + def ParseProcedureText( + self, code, formalParams, procName, itemName, unkContext, delimiter, contextCookie, startingLineNumber, flags + ) -> None: ... + def SetScriptSite(self, site) -> None: ... + def GetScriptSite(self, iid): ... + def SetScriptState(self, state) -> None: ... + def GetScriptState(self): ... + persistLoaded: int + def Close(self) -> None: ... + def AddNamedItem(self, name, flags) -> None: ... + def GetScriptDispatch(self, name) -> None: ... + def GetCurrentScriptThreadID(self): ... + def GetScriptThreadID(self, win32ThreadId): ... + def GetScriptThreadState(self, scriptThreadId): ... + def AddTypeLib(self, uuid, major, minor, flags) -> None: ... + def Clone(self) -> None: ... + def SetInterfaceSafetyOptions(self, iid, optionsMask, enabledOptions) -> None: ... + def GetInterfaceSafetyOptions(self, iid): ... + def ExecutePendingScripts(self) -> None: ... + def ProcessScriptItemEvent(self, item, event, lcid, wFlags, args): ... + def ResetNamedItems(self) -> None: ... + def GetCurrentSafetyOptions(self): ... + def ProcessNewNamedItemsConnections(self) -> None: ... + def RegisterNewNamedItems(self) -> None: ... + def RegisterNamedItem(self, item) -> None: ... + def CheckConnectedOrDisconnected(self) -> None: ... + def Connect(self) -> None: ... + def Run(self) -> None: ... + def Stop(self) -> None: ... + def Disconnect(self) -> None: ... + def ConnectEventHandlers(self) -> None: ... + def DisconnectEventHandlers(self) -> None: ... + def Reset(self) -> None: ... + def ChangeScriptState(self, state) -> None: ... + def ApplyInScriptedSection(self, codeBlock: AXScriptCodeBlock | None, fn, args): ... + def CompileInScriptedSection(self, codeBlock: AXScriptCodeBlock, type, realCode=None): ... + def ExecInScriptedSection(self, codeBlock: AXScriptCodeBlock, globals, locals=None): ... + def EvalInScriptedSection(self, codeBlock, globals, locals=None): ... + def HandleException(self, codeBlock: AXScriptCodeBlock | None) -> Never: ... + def BeginScriptedSection(self) -> None: ... + def EndScriptedSection(self) -> None: ... + def DisableInterrupts(self) -> None: ... + def EnableInterrupts(self) -> None: ... + def GetNamedItem(self, name): ... + def GetNamedItemClass(self): ... + +def dumptypeinfo(typeinfo) -> None: ... diff --git a/stubs/pywin32/win32comext/axscript/server/__init__.pyi b/stubs/pywin32/win32comext/axscript/server/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axscript/server/axsite.pyi b/stubs/pywin32/win32comext/axscript/server/axsite.pyi new file mode 100644 index 000000000000..aa77ad51b740 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/server/axsite.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete + +class AXEngine: + eScript: Incomplete + eParse: Incomplete + eSafety: Incomplete + def __init__(self, site, engine) -> None: ... + def __del__(self) -> None: ... + def GetScriptDispatch(self, name: Incomplete | None = ...): ... + def AddNamedItem(self, item, flags): ... + def AddCode(self, code, flags: int = ...) -> None: ... + def EvalCode(self, code): ... + def Start(self) -> None: ... + def Close(self) -> None: ... + def SetScriptState(self, state) -> None: ... + +IActiveScriptSite_methods: Incomplete + +class AXSite: + lcid: Incomplete + objModel: Incomplete + engine: Incomplete + def __init__(self, objModel=..., engine: Incomplete | None = ..., lcid: int = ...) -> None: ... + def AddEngine(self, engine): ... + def GetLCID(self): ... + def GetItemInfo(self, name, returnMask): ... + def GetDocVersionString(self): ... + def OnScriptTerminate(self, result, excepInfo) -> None: ... + def OnStateChange(self, state) -> None: ... + def OnScriptError(self, errorInterface): ... + def OnEnterScript(self) -> None: ... + def OnLeaveScript(self) -> None: ... diff --git a/stubs/pywin32/win32comext/bits/__init__.pyi b/stubs/pywin32/win32comext/bits/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/bits/bits.pyi b/stubs/pywin32/win32comext/bits/bits.pyi new file mode 100644 index 000000000000..8bc0c0563e93 --- /dev/null +++ b/stubs/pywin32/win32comext/bits/bits.pyi @@ -0,0 +1,61 @@ +import _win32typing + +BG_AUTH_SCHEME_BASIC: int +BG_AUTH_SCHEME_DIGEST: int +BG_AUTH_SCHEME_NEGOTIATE: int +BG_AUTH_SCHEME_NTLM: int +BG_AUTH_SCHEME_PASSPORT: int +BG_AUTH_TARGET_PROXY: int +BG_AUTH_TARGET_SERVER: int +BG_CERT_STORE_LOCATION_CURRENT_SERVICE: int +BG_CERT_STORE_LOCATION_CURRENT_USER: int +BG_CERT_STORE_LOCATION_CURRENT_USER_GROUP_POLICY: int +BG_CERT_STORE_LOCATION_LOCAL_MACHINE: int +BG_CERT_STORE_LOCATION_LOCAL_MACHINE_ENTERPRISE: int +BG_CERT_STORE_LOCATION_LOCAL_MACHINE_GROUP_POLICY: int +BG_CERT_STORE_LOCATION_SERVICES: int +BG_CERT_STORE_LOCATION_USERS: int +BG_ERROR_CONTEXT_GENERAL_QUEUE_MANAGER: int +BG_ERROR_CONTEXT_GENERAL_TRANSPORT: int +BG_ERROR_CONTEXT_LOCAL_FILE: int +BG_ERROR_CONTEXT_NONE: int +BG_ERROR_CONTEXT_QUEUE_MANAGER_NOTIFICATION: int +BG_ERROR_CONTEXT_REMOTE_APPLICATION: int +BG_ERROR_CONTEXT_REMOTE_FILE: int +BG_ERROR_CONTEXT_UNKNOWN: int +BG_JOB_ENUM_ALL_USERS: int +BG_JOB_PRIORITY_FOREGROUND: int +BG_JOB_PRIORITY_HIGH: int +BG_JOB_PRIORITY_LOW: int +BG_JOB_PRIORITY_NORMAL: int +BG_JOB_PROXY_USAGE_AUTODETECT: int +BG_JOB_PROXY_USAGE_NO_PROXY: int +BG_JOB_PROXY_USAGE_OVERRIDE: int +BG_JOB_PROXY_USAGE_PRECONFIG: int +BG_JOB_STATE_ACKNOWLEDGED: int +BG_JOB_STATE_CANCELLED: int +BG_JOB_STATE_CONNECTING: int +BG_JOB_STATE_ERROR: int +BG_JOB_STATE_QUEUED: int +BG_JOB_STATE_SUSPENDED: int +BG_JOB_STATE_TRANSFERRED: int +BG_JOB_STATE_TRANSFERRING: int +BG_JOB_STATE_TRANSIENT_ERROR: int +BG_JOB_TYPE_DOWNLOAD: int +BG_JOB_TYPE_UPLOAD: int +BG_JOB_TYPE_UPLOAD_REPLY: int +BG_NOTIFY_DISABLE: int +BG_NOTIFY_JOB_ERROR: int +BG_NOTIFY_JOB_MODIFICATION: int +BG_NOTIFY_JOB_TRANSFERRED: int +CLSID_BackgroundCopyManager: _win32typing.PyIID +IID_IBackgroundCopyCallback: _win32typing.PyIID +IID_IBackgroundCopyError: _win32typing.PyIID +IID_IBackgroundCopyFile: _win32typing.PyIID +IID_IBackgroundCopyFile2: _win32typing.PyIID +IID_IBackgroundCopyJob: _win32typing.PyIID +IID_IBackgroundCopyJob2: _win32typing.PyIID +IID_IBackgroundCopyJob3: _win32typing.PyIID +IID_IBackgroundCopyManager: _win32typing.PyIID +IID_IEnumBackgroundCopyFiles: _win32typing.PyIID +IID_IEnumBackgroundCopyJobs: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/directsound/__init__.pyi b/stubs/pywin32/win32comext/directsound/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/directsound/directsound.pyi b/stubs/pywin32/win32comext/directsound/directsound.pyi new file mode 100644 index 000000000000..1b53c8f84199 --- /dev/null +++ b/stubs/pywin32/win32comext/directsound/directsound.pyi @@ -0,0 +1,116 @@ +from _typeshed import Incomplete + +import _win32typing + +def DirectSoundCreate(guid: _win32typing.PyIID | None = ..., unk: Incomplete | None = ..., /) -> _win32typing.PyIUnknown: ... +def DirectSoundEnumerate(): ... +def DirectSoundCaptureCreate( + guid: _win32typing.PyIID | None = ..., unk: Incomplete | None = ..., / +) -> _win32typing.PyIUnknown: ... +def DirectSoundCaptureEnumerate(): ... +def DSCAPS() -> _win32typing.PyDSCAPS: ... +def DSBCAPS() -> _win32typing.PyDSBCAPS: ... +def DSCCAPS() -> _win32typing.PyDSCCAPS: ... +def DSCBCAPS() -> _win32typing.PyDSCBCAPS: ... +def DSBUFFERDESC() -> _win32typing.PyDSBUFFERDESC: ... +def DSCBUFFERDESC() -> _win32typing.PyDSCBUFFERDESC: ... + +DS3DMODE_DISABLE: int +DS3DMODE_HEADRELATIVE: int +DS3DMODE_NORMAL: int +DSBCAPS_CTRL3D: int +DSBCAPS_CTRLFREQUENCY: int +DSBCAPS_CTRLPAN: int +DSBCAPS_CTRLPOSITIONNOTIFY: int +DSBCAPS_CTRLVOLUME: int +DSBCAPS_GETCURRENTPOSITION2: int +DSBCAPS_GLOBALFOCUS: int +DSBCAPS_LOCHARDWARE: int +DSBCAPS_LOCSOFTWARE: int +DSBCAPS_MUTE3DATMAXDISTANCE: int +DSBCAPS_PRIMARYBUFFER: int +DSBCAPS_STATIC: int +DSBCAPS_STICKYFOCUS: int +DSBLOCK_ENTIREBUFFER: int +DSBLOCK_FROMWRITECURSOR: int +DSBPLAY_LOOPING: int +DSBSTATUS_BUFFERLOST: int +DSBSTATUS_LOOPING: int +DSBSTATUS_PLAYING: int +DSCAPS_CERTIFIED: int +DSCAPS_CONTINUOUSRATE: int +DSCAPS_EMULDRIVER: int +DSCAPS_PRIMARY16BIT: int +DSCAPS_PRIMARY8BIT: int +DSCAPS_PRIMARYMONO: int +DSCAPS_PRIMARYSTEREO: int +DSCAPS_SECONDARY16BIT: int +DSCAPS_SECONDARY8BIT: int +DSCAPS_SECONDARYMONO: int +DSCAPS_SECONDARYSTEREO: int +DSCBCAPS_WAVEMAPPED: int +DSCCAPS_EMULDRIVER: int +DSSCL_EXCLUSIVE: int +DSSCL_NORMAL: int +DSSCL_PRIORITY: int +DSSCL_WRITEPRIMARY: int +DSSPEAKER_GEOMETRY_MAX: int +DSSPEAKER_GEOMETRY_MIN: int +DSSPEAKER_GEOMETRY_NARROW: int +DSSPEAKER_GEOMETRY_WIDE: int +DSSPEAKER_HEADPHONE: int +DSSPEAKER_MONO: int +DSSPEAKER_QUAD: int +DSSPEAKER_STEREO: int +DSSPEAKER_SURROUND: int +DSBCAPSType = _win32typing.PyDSBCAPS +DSBFREQUENCY_MAX: int +DSBFREQUENCY_MIN: int +DSBFREQUENCY_ORIGINAL: int +DSBPAN_CENTER: int +DSBPAN_LEFT: int +DSBPAN_RIGHT: int +DSBPN_OFFSETSTOP: int +DSBSIZE_MAX: int +DSBSIZE_MIN: int +DSBUFFERDESCType = _win32typing.PyDSBUFFERDESC +DSBVOLUME_MAX: int +DSBVOLUME_MIN: int +DSCAPSType = _win32typing.PyDSCAPSType +DSCBCAPSType = _win32typing.PyDSCBCAPSType +DSCBLOCK_ENTIREBUFFER: int +DSCBSTART_LOOPING: int +DSCBSTATUS_CAPTURING: int +DSCBSTATUS_LOOPING: int +DSCBUFFERDESCType = _win32typing.PyDSCBUFFERDESC +DSCCAPSType = _win32typing.PyDSCCAPSType +DSERR_ACCESSDENIED: int +DSERR_ALLOCATED: int +DSERR_ALREADYINITIALIZED: int +DSERR_BADFORMAT: int +DSERR_BADSENDBUFFERGUID: int +DSERR_BUFFERLOST: int +DSERR_BUFFERTOOSMALL: int +DSERR_CONTROLUNAVAIL: int +DSERR_DS8_REQUIRED: int +DSERR_FXUNAVAILABLE: int +DSERR_GENERIC: int +DSERR_INVALIDCALL: int +DSERR_INVALIDPARAM: int +DSERR_NOAGGREGATION: int +DSERR_NODRIVER: int +DSERR_NOINTERFACE: int +DSERR_OBJECTNOTFOUND: int +DSERR_OTHERAPPHASPRIO: int +DSERR_OUTOFMEMORY: int +DSERR_PRIOLEVELNEEDED: int +DSERR_SENDLOOP: int +DSERR_UNINITIALIZED: int +DSERR_UNSUPPORTED: int +DS_NO_VIRTUALIZATION: int +DS_OK: int +IID_IDirectSound: _win32typing.PyIID +IID_IDirectSoundBuffer: _win32typing.PyIID +IID_IDirectSoundCapture: _win32typing.PyIID +IID_IDirectSoundCaptureBuffer: _win32typing.PyIID +IID_IDirectSoundNotify: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/ifilter/__init__.pyi b/stubs/pywin32/win32comext/ifilter/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/ifilter/ifilter.pyi b/stubs/pywin32/win32comext/ifilter/ifilter.pyi new file mode 100644 index 000000000000..f1c1e76b6bd6 --- /dev/null +++ b/stubs/pywin32/win32comext/ifilter/ifilter.pyi @@ -0,0 +1,33 @@ +import _win32typing + +def BindIFilterFromStorage(stg, /): ... +def BindIFilterFromStream(stg, /): ... +def LoadIFilter(path: str, /): ... + +CHUNK_EOC: int +CHUNK_EOP: int +CHUNK_EOS: int +CHUNK_EOW: int +CHUNK_NO_BREAK: int +CHUNK_TEXT: int +CHUNK_VALUE: int +FILTER_E_ACCESS: int +FILTER_E_EMBEDDING_UNAVAILABLE: int +FILTER_E_END_OF_CHUNKS: int +FILTER_E_LINK_UNAVAILABLE: int +FILTER_E_NO_MORE_TEXT: int +FILTER_E_NO_MORE_VALUES: int +FILTER_E_NO_TEXT: int +FILTER_E_NO_VALUES: int +FILTER_E_PASSWORD: int +FILTER_S_LAST_TEXT: int +IFILTER_FLAGS_OLE_PROPERTIES: int +IFILTER_INIT_APPLY_INDEX_ATTRIBUTES: int +IFILTER_INIT_APPLY_OTHER_ATTRIBUTES: int +IFILTER_INIT_CANON_HYPHENS: int +IFILTER_INIT_CANON_PARAGRAPHS: int +IFILTER_INIT_CANON_SPACES: int +IFILTER_INIT_HARD_LINE_BREAKS: int +IFILTER_INIT_INDEXING_ONLY: int +IFILTER_INIT_SEARCH_LINKS: int +IID_IFilter: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/ifilter/ifiltercon.pyi b/stubs/pywin32/win32comext/ifilter/ifiltercon.pyi new file mode 100644 index 000000000000..2b6623498eb4 --- /dev/null +++ b/stubs/pywin32/win32comext/ifilter/ifiltercon.pyi @@ -0,0 +1,103 @@ +from _typeshed import Incomplete + +PSGUID_STORAGE: Incomplete +PSGUID_SUMMARYINFORMATION: Incomplete +PSGUID_HTMLINFORMATION: Incomplete +PSGUID_HTML2_INFORMATION: Incomplete +IFILTER_INIT_CANON_PARAGRAPHS: int +IFILTER_INIT_HARD_LINE_BREAKS: int +IFILTER_INIT_CANON_HYPHENS: int +IFILTER_INIT_CANON_SPACES: int +IFILTER_INIT_APPLY_INDEX_ATTRIBUTES: int +IFILTER_INIT_APPLY_CRAWL_ATTRIBUTES: int +IFILTER_INIT_APPLY_OTHER_ATTRIBUTES: int +IFILTER_INIT_INDEXING_ONLY: int +IFILTER_INIT_SEARCH_LINKS: int +IFILTER_INIT_FILTER_OWNED_VALUE_OK: int +IFILTER_FLAGS_OLE_PROPERTIES: int +CHUNK_TEXT: int +CHUNK_VALUE: int +CHUNK_NO_BREAK: int +CHUNK_EOW: int +CHUNK_EOS: int +CHUNK_EOP: int +CHUNK_EOC: int +NOT_AN_ERROR: int +FILTER_E_END_OF_CHUNKS: int +FILTER_E_NO_MORE_TEXT: int +FILTER_E_NO_MORE_VALUES: int +FILTER_E_ACCESS: int +FILTER_W_MONIKER_CLIPPED: int +FILTER_E_NO_TEXT: int +FILTER_E_NO_VALUES: int +FILTER_E_EMBEDDING_UNAVAILABLE: int +FILTER_E_LINK_UNAVAILABLE: int +FILTER_S_LAST_TEXT: int +FILTER_S_LAST_VALUES: int +FILTER_E_PASSWORD: int +FILTER_E_UNKNOWNFORMAT: int +PROPSETFLAG_DEFAULT: int +PROPSETFLAG_NONSIMPLE: int +PROPSETFLAG_ANSI: int +PROPSETFLAG_UNBUFFERED: int +PROPSETFLAG_CASE_SENSITIVE: int +PROPSET_BEHAVIOR_CASE_SENSITIVE: int +PID_DICTIONARY: int +PID_CODEPAGE: int +PID_FIRST_USABLE: int +PID_FIRST_NAME_DEFAULT: int +PID_LOCALE: int +PID_MODIFY_TIME: int +PID_SECURITY: int +PID_BEHAVIOR: int +PID_ILLEGAL: int +PID_MIN_READONLY: int +PID_MAX_READONLY: int +PIDDI_THUMBNAIL: int +PIDSI_TITLE: int +PIDSI_SUBJECT: int +PIDSI_AUTHOR: int +PIDSI_KEYWORDS: int +PIDSI_COMMENTS: int +PIDSI_TEMPLATE: int +PIDSI_LASTAUTHOR: int +PIDSI_REVNUMBER: int +PIDSI_EDITTIME: int +PIDSI_LASTPRINTED: int +PIDSI_CREATE_DTM: int +PIDSI_LASTSAVE_DTM: int +PIDSI_PAGECOUNT: int +PIDSI_WORDCOUNT: int +PIDSI_CHARCOUNT: int +PIDSI_THUMBNAIL: int +PIDSI_APPNAME: int +PIDSI_DOC_SECURITY: int +PIDDSI_CATEGORY: int +PIDDSI_PRESFORMAT: int +PIDDSI_BYTECOUNT: int +PIDDSI_LINECOUNT: int +PIDDSI_PARCOUNT: int +PIDDSI_SLIDECOUNT: int +PIDDSI_NOTECOUNT: int +PIDDSI_HIDDENCOUNT: int +PIDDSI_MMCLIPCOUNT: int +PIDDSI_SCALE: int +PIDDSI_HEADINGPAIR: int +PIDDSI_DOCPARTS: int +PIDDSI_MANAGER: int +PIDDSI_COMPANY: int +PIDDSI_LINKSDIRTY: int +PIDMSI_EDITOR: int +PIDMSI_SUPPLIER: int +PIDMSI_SOURCE: int +PIDMSI_SEQUENCE_NO: int +PIDMSI_PROJECT: int +PIDMSI_STATUS: int +PIDMSI_OWNER: int +PIDMSI_RATING: int +PIDMSI_PRODUCTION: int +PIDMSI_COPYRIGHT: int +PRSPEC_INVALID: int +PRSPEC_LPWSTR: int +PRSPEC_PROPID: int +CCH_MAX_PROPSTG_NAME: int diff --git a/stubs/pywin32/win32comext/internet/__init__.pyi b/stubs/pywin32/win32comext/internet/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/internet/inetcon.pyi b/stubs/pywin32/win32comext/internet/inetcon.pyi new file mode 100644 index 000000000000..7a90c63576b4 --- /dev/null +++ b/stubs/pywin32/win32comext/internet/inetcon.pyi @@ -0,0 +1,254 @@ +from _typeshed import Incomplete + +INET_E_USE_DEFAULT_PROTOCOLHANDLER: int +INET_E_USE_DEFAULT_SETTING: int +INET_E_DEFAULT_ACTION: int +INET_E_QUERYOPTION_UNKNOWN: int +INET_E_REDIRECTING: int +INET_E_INVALID_URL: int +INET_E_NO_SESSION: int +INET_E_CANNOT_CONNECT: int +INET_E_RESOURCE_NOT_FOUND: int +INET_E_OBJECT_NOT_FOUND: int +INET_E_DATA_NOT_AVAILABLE: int +INET_E_DOWNLOAD_FAILURE: int +INET_E_AUTHENTICATION_REQUIRED: int +INET_E_NO_VALID_MEDIA: int +INET_E_CONNECTION_TIMEOUT: int +INET_E_INVALID_REQUEST: int +INET_E_UNKNOWN_PROTOCOL: int +INET_E_SECURITY_PROBLEM: int +INET_E_CANNOT_LOAD_DATA: int +INET_E_CANNOT_INSTANTIATE_OBJECT: int +INET_E_INVALID_CERTIFICATE: int +INET_E_REDIRECT_FAILED: int +INET_E_REDIRECT_TO_DIR: int +INET_E_CANNOT_LOCK_REQUEST: int +INET_E_USE_EXTEND_BINDING: int +INET_E_TERMINATED_BIND: int +INET_E_CODE_DOWNLOAD_DECLINED: int +INET_E_RESULT_DISPATCHED: int +INET_E_CANNOT_REPLACE_SFP_FILE: int +INET_E_CODE_INSTALL_SUPPRESSED: int +INET_E_CODE_INSTALL_BLOCKED_BY_HASH_POLICY: int +MKSYS_URLMONIKER: int +URL_MK_LEGACY: int +URL_MK_UNIFORM: int +URL_MK_NO_CANONICALIZE: int +FIEF_FLAG_FORCE_JITUI: int +FIEF_FLAG_PEEK: int +FIEF_FLAG_SKIP_INSTALLED_VERSION_CHECK: int +FMFD_DEFAULT: int +FMFD_URLASFILENAME: int +FMFD_ENABLEMIMESNIFFING: int +FMFD_IGNOREMIMETEXTPLAIN: int +URLMON_OPTION_USERAGENT: int +URLMON_OPTION_USERAGENT_REFRESH: int +URLMON_OPTION_URL_ENCODING: int +URLMON_OPTION_USE_BINDSTRINGCREDS: int +URLMON_OPTION_USE_BROWSERAPPSDOCUMENTS: int +CF_NULL: int +Uri_CREATE_ALLOW_RELATIVE: int +Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME: int +Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME: int +Uri_CREATE_NOFRAG: int +Uri_CREATE_NO_CANONICALIZE: int +Uri_CREATE_CANONICALIZE: int +Uri_CREATE_FILE_USE_DOS_PATH: int +Uri_CREATE_DECODE_EXTRA_INFO: int +Uri_CREATE_NO_DECODE_EXTRA_INFO: int +Uri_CREATE_CRACK_UNKNOWN_SCHEMES: int +Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES: int +Uri_CREATE_PRE_PROCESS_HTML_URI: int +Uri_CREATE_NO_PRE_PROCESS_HTML_URI: int +Uri_CREATE_IE_SETTINGS: int +Uri_CREATE_NO_IE_SETTINGS: int +Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS: int +Uri_DISPLAY_NO_FRAGMENT: int +Uri_PUNYCODE_IDN_HOST: int +Uri_DISPLAY_IDN_HOST: int +Uri_ENCODING_USER_INFO_AND_PATH_IS_PERCENT_ENCODED_UTF8: int +Uri_ENCODING_USER_INFO_AND_PATH_IS_CP: int +Uri_ENCODING_HOST_IS_IDN: int +Uri_ENCODING_HOST_IS_PERCENT_ENCODED_UTF8: int +Uri_ENCODING_HOST_IS_PERCENT_ENCODED_CP: int +Uri_ENCODING_QUERY_AND_FRAGMENT_IS_PERCENT_ENCODED_UTF8: int +Uri_ENCODING_QUERY_AND_FRAGMENT_IS_CP: int +Uri_ENCODING_RFC: Incomplete +UriBuilder_USE_ORIGINAL_FLAGS: int +WININETINFO_OPTION_LOCK_HANDLE: int +URLOSTRM_USECACHEDCOPY_ONLY: int +URLOSTRM_USECACHEDCOPY: int +URLOSTRM_GETNEWESTVERSION: int +SET_FEATURE_ON_THREAD: int +SET_FEATURE_ON_PROCESS: int +SET_FEATURE_IN_REGISTRY: int +SET_FEATURE_ON_THREAD_LOCALMACHINE: int +SET_FEATURE_ON_THREAD_INTRANET: int +SET_FEATURE_ON_THREAD_TRUSTED: int +SET_FEATURE_ON_THREAD_INTERNET: int +SET_FEATURE_ON_THREAD_RESTRICTED: int +GET_FEATURE_FROM_THREAD: int +GET_FEATURE_FROM_PROCESS: int +GET_FEATURE_FROM_REGISTRY: int +GET_FEATURE_FROM_THREAD_LOCALMACHINE: int +GET_FEATURE_FROM_THREAD_INTRANET: int +GET_FEATURE_FROM_THREAD_TRUSTED: int +GET_FEATURE_FROM_THREAD_INTERNET: int +GET_FEATURE_FROM_THREAD_RESTRICTED: int +PROTOCOLFLAG_NO_PICS_CHECK: int +MUTZ_NOSAVEDFILECHECK: int +MUTZ_ISFILE: int +MUTZ_ACCEPT_WILDCARD_SCHEME: int +MUTZ_ENFORCERESTRICTED: int +MUTZ_RESERVED: int +MUTZ_REQUIRESAVEDFILECHECK: int +MUTZ_DONT_UNESCAPE: int +MUTZ_DONT_USE_CACHE: int +MUTZ_FORCE_INTRANET_FLAGS: int +MUTZ_IGNORE_ZONE_MAPPINGS: int +MAX_SIZE_SECURITY_ID: int +URLACTION_MIN: int +URLACTION_DOWNLOAD_MIN: int +URLACTION_DOWNLOAD_SIGNED_ACTIVEX: int +URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX: int +URLACTION_DOWNLOAD_CURR_MAX: int +URLACTION_DOWNLOAD_MAX: int +URLACTION_ACTIVEX_MIN: int +URLACTION_ACTIVEX_RUN: int +URLPOLICY_ACTIVEX_CHECK_LIST: int +URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY: int +URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY: int +URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY: int +URLACTION_SCRIPT_OVERRIDE_SAFETY: int +URLACTION_ACTIVEX_CONFIRM_NOOBJECTSAFETY: int +URLACTION_ACTIVEX_TREATASUNTRUSTED: int +URLACTION_ACTIVEX_NO_WEBOC_SCRIPT: int +URLACTION_ACTIVEX_OVERRIDE_REPURPOSEDETECTION: int +URLACTION_ACTIVEX_OVERRIDE_OPTIN: int +URLACTION_ACTIVEX_SCRIPTLET_RUN: int +URLACTION_ACTIVEX_DYNSRC_VIDEO_AND_ANIMATION: int +URLACTION_ACTIVEX_CURR_MAX: int +URLACTION_ACTIVEX_MAX: int +URLACTION_SCRIPT_MIN: int +URLACTION_SCRIPT_RUN: int +URLACTION_SCRIPT_JAVA_USE: int +URLACTION_SCRIPT_SAFE_ACTIVEX: int +URLACTION_CROSS_DOMAIN_DATA: int +URLACTION_SCRIPT_PASTE: int +URLACTION_ALLOW_XDOMAIN_SUBFRAME_RESIZE: int +URLACTION_SCRIPT_CURR_MAX: int +URLACTION_SCRIPT_MAX: int +URLACTION_HTML_MIN: int +URLACTION_HTML_SUBMIT_FORMS: int +URLACTION_HTML_SUBMIT_FORMS_FROM: int +URLACTION_HTML_SUBMIT_FORMS_TO: int +URLACTION_HTML_FONT_DOWNLOAD: int +URLACTION_HTML_JAVA_RUN: int +URLACTION_HTML_USERDATA_SAVE: int +URLACTION_HTML_SUBFRAME_NAVIGATE: int +URLACTION_HTML_META_REFRESH: int +URLACTION_HTML_MIXED_CONTENT: int +URLACTION_HTML_INCLUDE_FILE_PATH: int +URLACTION_HTML_MAX: int +URLACTION_SHELL_MIN: int +URLACTION_SHELL_INSTALL_DTITEMS: int +URLACTION_SHELL_MOVE_OR_COPY: int +URLACTION_SHELL_FILE_DOWNLOAD: int +URLACTION_SHELL_VERB: int +URLACTION_SHELL_WEBVIEW_VERB: int +URLACTION_SHELL_SHELLEXECUTE: int +URLACTION_SHELL_EXECUTE_HIGHRISK: int +URLACTION_SHELL_EXECUTE_MODRISK: int +URLACTION_SHELL_EXECUTE_LOWRISK: int +URLACTION_SHELL_POPUPMGR: int +URLACTION_SHELL_RTF_OBJECTS_LOAD: int +URLACTION_SHELL_ENHANCED_DRAGDROP_SECURITY: int +URLACTION_SHELL_EXTENSIONSECURITY: int +URLACTION_SHELL_SECURE_DRAGSOURCE: int +URLACTION_SHELL_CURR_MAX: int +URLACTION_SHELL_MAX: int +URLACTION_NETWORK_MIN: int +URLACTION_CREDENTIALS_USE: int +URLPOLICY_CREDENTIALS_SILENT_LOGON_OK: int +URLPOLICY_CREDENTIALS_MUST_PROMPT_USER: int +URLPOLICY_CREDENTIALS_CONDITIONAL_PROMPT: int +URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY: int +URLACTION_AUTHENTICATE_CLIENT: int +URLPOLICY_AUTHENTICATE_CLEARTEXT_OK: int +URLPOLICY_AUTHENTICATE_CHALLENGE_RESPONSE: int +URLPOLICY_AUTHENTICATE_MUTUAL_ONLY: int +URLACTION_COOKIES: int +URLACTION_COOKIES_SESSION: int +URLACTION_CLIENT_CERT_PROMPT: int +URLACTION_COOKIES_THIRD_PARTY: int +URLACTION_COOKIES_SESSION_THIRD_PARTY: int +URLACTION_COOKIES_ENABLED: int +URLACTION_NETWORK_CURR_MAX: int +URLACTION_NETWORK_MAX: int +URLACTION_JAVA_MIN: int +URLACTION_JAVA_PERMISSIONS: int +URLPOLICY_JAVA_PROHIBIT: int +URLPOLICY_JAVA_HIGH: int +URLPOLICY_JAVA_MEDIUM: int +URLPOLICY_JAVA_LOW: int +URLPOLICY_JAVA_CUSTOM: int +URLACTION_JAVA_CURR_MAX: int +URLACTION_JAVA_MAX: int +URLACTION_INFODELIVERY_MIN: int +URLACTION_INFODELIVERY_NO_ADDING_CHANNELS: int +URLACTION_INFODELIVERY_NO_EDITING_CHANNELS: int +URLACTION_INFODELIVERY_NO_REMOVING_CHANNELS: int +URLACTION_INFODELIVERY_NO_ADDING_SUBSCRIPTIONS: int +URLACTION_INFODELIVERY_NO_EDITING_SUBSCRIPTIONS: int +URLACTION_INFODELIVERY_NO_REMOVING_SUBSCRIPTIONS: int +URLACTION_INFODELIVERY_NO_CHANNEL_LOGGING: int +URLACTION_INFODELIVERY_CURR_MAX: int +URLACTION_INFODELIVERY_MAX: int +URLACTION_CHANNEL_SOFTDIST_MIN: int +URLACTION_CHANNEL_SOFTDIST_PERMISSIONS: int +URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT: int +URLPOLICY_CHANNEL_SOFTDIST_PRECACHE: int +URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL: int +URLACTION_CHANNEL_SOFTDIST_MAX: int +URLACTION_BEHAVIOR_MIN: int +URLACTION_BEHAVIOR_RUN: int +URLPOLICY_BEHAVIOR_CHECK_LIST: int +URLACTION_FEATURE_MIN: int +URLACTION_FEATURE_MIME_SNIFFING: int +URLACTION_FEATURE_ZONE_ELEVATION: int +URLACTION_FEATURE_WINDOW_RESTRICTIONS: int +URLACTION_FEATURE_SCRIPT_STATUS_BAR: int +URLACTION_FEATURE_FORCE_ADDR_AND_STATUS: int +URLACTION_FEATURE_BLOCK_INPUT_PROMPTS: int +URLACTION_AUTOMATIC_DOWNLOAD_UI_MIN: int +URLACTION_AUTOMATIC_DOWNLOAD_UI: int +URLACTION_AUTOMATIC_ACTIVEX_UI: int +URLACTION_ALLOW_RESTRICTEDPROTOCOLS: int +URLACTION_ALLOW_APEVALUATION: int +URLACTION_WINDOWS_BROWSER_APPLICATIONS: int +URLACTION_XPS_DOCUMENTS: int +URLACTION_LOOSE_XAML: int +URLACTION_LOWRIGHTS: int +URLACTION_WINFX_SETUP: int +URLPOLICY_ALLOW: int +URLPOLICY_QUERY: int +URLPOLICY_DISALLOW: int +URLPOLICY_NOTIFY_ON_ALLOW: int +URLPOLICY_NOTIFY_ON_DISALLOW: int +URLPOLICY_LOG_ON_ALLOW: int +URLPOLICY_LOG_ON_DISALLOW: int +URLPOLICY_MASK_PERMISSIONS: int +URLPOLICY_DONTCHECKDLGBOX: int +URLZONE_ESC_FLAG: int +SECURITY_IE_STATE_GREEN: int +SECURITY_IE_STATE_RED: int +SOFTDIST_FLAG_USAGE_EMAIL: int +SOFTDIST_FLAG_USAGE_PRECACHE: int +SOFTDIST_FLAG_USAGE_AUTOINSTALL: int +SOFTDIST_FLAG_DELETE_SUBSCRIPTION: int +SOFTDIST_ADSTATE_NONE: int +SOFTDIST_ADSTATE_AVAILABLE: int +SOFTDIST_ADSTATE_DOWNLOADED: int +SOFTDIST_ADSTATE_INSTALLED: int +CONFIRMSAFETYACTION_LOADOBJECT: int diff --git a/stubs/pywin32/win32comext/internet/internet.pyi b/stubs/pywin32/win32comext/internet/internet.pyi new file mode 100644 index 000000000000..60d0fff7aa9f --- /dev/null +++ b/stubs/pywin32/win32comext/internet/internet.pyi @@ -0,0 +1,51 @@ +import _win32typing + +def CoInternetCreateSecurityManager(reserved, /) -> _win32typing.PyIInternetSecurityManager: ... +def CoInternetIsFeatureEnabled(flags, /): ... +def CoInternetSetFeatureEnabled(flags, enable, /): ... + +FEATURE_ADDON_MANAGEMENT: int +FEATURE_BEHAVIORS: int +FEATURE_DISABLE_MK_PROTOCOL: int +FEATURE_ENTRY_COUNT: int +FEATURE_GET_URL_DOM_FILEPATH_UNENCODED: int +FEATURE_HTTP_USERNAME_PASSWORD_DISABLE: int +FEATURE_LOCALMACHINE_LOCKDOWN: int +FEATURE_MIME_HANDLING: int +FEATURE_MIME_SNIFFING: int +FEATURE_OBJECT_CACHING: int +FEATURE_PROTOCOL_LOCKDOWN: int +FEATURE_RESTRICT_ACTIVEXINSTALL: int +FEATURE_RESTRICT_FILEDOWNLOAD: int +FEATURE_SAFE_BINDTOOBJECT: int +FEATURE_SECURITYBAND: int +FEATURE_UNC_SAVEDFILECHECK: int +FEATURE_VALIDATE_NAVIGATE_URL: int +FEATURE_WEBOC_POPUPMANAGEMENT: int +FEATURE_WINDOW_RESTRICTIONS: int +FEATURE_ZONE_ELEVATION: int +GET_FEATURE_FROM_PROCESS: int +GET_FEATURE_FROM_REGISTRY: int +GET_FEATURE_FROM_THREAD: int +GET_FEATURE_FROM_THREAD_INTERNET: int +GET_FEATURE_FROM_THREAD_INTRANET: int +GET_FEATURE_FROM_THREAD_LOCALMACHINE: int +GET_FEATURE_FROM_THREAD_RESTRICTED: int +GET_FEATURE_FROM_THREAD_TRUSTED: int +IID_IDocHostUIHandler: _win32typing.PyIID +IID_IHTMLOMWindowServices: _win32typing.PyIID +IID_IInternetBindInfo: _win32typing.PyIID +IID_IInternetPriority: _win32typing.PyIID +IID_IInternetProtocol: _win32typing.PyIID +IID_IInternetProtocolInfo: _win32typing.PyIID +IID_IInternetProtocolRoot: _win32typing.PyIID +IID_IInternetProtocolSink: _win32typing.PyIID +IID_IInternetSecurityManager: _win32typing.PyIID +SET_FEATURE_IN_REGISTRY: int +SET_FEATURE_ON_PROCESS: int +SET_FEATURE_ON_THREAD: int +SET_FEATURE_ON_THREAD_INTERNET: int +SET_FEATURE_ON_THREAD_INTRANET: int +SET_FEATURE_ON_THREAD_LOCALMACHINE: int +SET_FEATURE_ON_THREAD_RESTRICTED: int +SET_FEATURE_ON_THREAD_TRUSTED: int diff --git a/stubs/pywin32/win32comext/mapi/__init__.pyi b/stubs/pywin32/win32comext/mapi/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/mapi/emsabtags.pyi b/stubs/pywin32/win32comext/mapi/emsabtags.pyi new file mode 100644 index 000000000000..59cfd215c362 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/emsabtags.pyi @@ -0,0 +1,865 @@ +from _typeshed import Incomplete + +from win32comext.mapi.mapitags import ( + PROP_TAG as PROP_TAG, + PT_APPTIME as PT_APPTIME, + PT_BINARY as PT_BINARY, + PT_BOOLEAN as PT_BOOLEAN, + PT_CLSID as PT_CLSID, + PT_CURRENCY as PT_CURRENCY, + PT_DOUBLE as PT_DOUBLE, + PT_ERROR as PT_ERROR, + PT_FLOAT as PT_FLOAT, + PT_I2 as PT_I2, + PT_I4 as PT_I4, + PT_I8 as PT_I8, + PT_LONG as PT_LONG, + PT_LONGLONG as PT_LONGLONG, + PT_MV_APPTIME as PT_MV_APPTIME, + PT_MV_BINARY as PT_MV_BINARY, + PT_MV_CLSID as PT_MV_CLSID, + PT_MV_CURRENCY as PT_MV_CURRENCY, + PT_MV_DOUBLE as PT_MV_DOUBLE, + PT_MV_FLOAT as PT_MV_FLOAT, + PT_MV_I2 as PT_MV_I2, + PT_MV_I4 as PT_MV_I4, + PT_MV_I8 as PT_MV_I8, + PT_MV_LONG as PT_MV_LONG, + PT_MV_LONGLONG as PT_MV_LONGLONG, + PT_MV_R4 as PT_MV_R4, + PT_MV_R8 as PT_MV_R8, + PT_MV_SHORT as PT_MV_SHORT, + PT_MV_STRING8 as PT_MV_STRING8, + PT_MV_SYSTIME as PT_MV_SYSTIME, + PT_MV_TSTRING as PT_MV_TSTRING, + PT_MV_UNICODE as PT_MV_UNICODE, + PT_NULL as PT_NULL, + PT_OBJECT as PT_OBJECT, + PT_R4 as PT_R4, + PT_SHORT as PT_SHORT, + PT_STRING8 as PT_STRING8, + PT_SYSTIME as PT_SYSTIME, + PT_TSTRING as PT_TSTRING, + PT_UNICODE as PT_UNICODE, + PT_UNSPECIFIED as PT_UNSPECIFIED, +) + +AB_SHOW_PHANTOMS: int +AB_SHOW_OTHERS: int +EMS_AB_ADDRESS_LOOKUP: int +PR_EMS_AB_SERVER: Incomplete +PR_EMS_AB_SERVER_A: Incomplete +PR_EMS_AB_SERVER_W: Incomplete +PR_EMS_AB_CONTAINERID: Incomplete +PR_EMS_AB_DOS_ENTRYID: Incomplete +PR_EMS_AB_PARENT_ENTRYID: Incomplete +PR_EMS_AB_IS_MASTER: Incomplete +PR_EMS_AB_OBJECT_OID: Incomplete +PR_EMS_AB_HIERARCHY_PATH: Incomplete +PR_EMS_AB_HIERARCHY_PATH_A: Incomplete +PR_EMS_AB_HIERARCHY_PATH_W: Incomplete +PR_EMS_AB_CHILD_RDNS: Incomplete +MIN_EMS_AB_CONSTRUCTED_PROP_ID: int +PR_EMS_AB_OTHER_RECIPS: Incomplete +PR_EMS_AB_DISPLAY_NAME_PRINTABLE: Incomplete +PR_EMS_AB_DISPLAY_NAME_PRINTABLE_A: Incomplete +PR_EMS_AB_DISPLAY_NAME_PRINTABLE_W: Incomplete +PR_EMS_AB_ACCESS_CATEGORY: Incomplete +PR_EMS_AB_ACTIVATION_SCHEDULE: Incomplete +PR_EMS_AB_ACTIVATION_STYLE: Incomplete +PR_EMS_AB_ADDRESS_ENTRY_DISPLAY_TABLE: Incomplete +PR_EMS_AB_ADDRESS_ENTRY_DISPLAY_TABLE_MSDOS: Incomplete +PR_EMS_AB_ADDRESS_SYNTAX: Incomplete +PR_EMS_AB_ADDRESS_TYPE: Incomplete +PR_EMS_AB_ADDRESS_TYPE_A: Incomplete +PR_EMS_AB_ADDRESS_TYPE_W: Incomplete +PR_EMS_AB_ADMD: Incomplete +PR_EMS_AB_ADMD_A: Incomplete +PR_EMS_AB_ADMD_W: Incomplete +PR_EMS_AB_ADMIN_DESCRIPTION: Incomplete +PR_EMS_AB_ADMIN_DESCRIPTION_A: Incomplete +PR_EMS_AB_ADMIN_DESCRIPTION_W: Incomplete +PR_EMS_AB_ADMIN_DISPLAY_NAME: Incomplete +PR_EMS_AB_ADMIN_DISPLAY_NAME_A: Incomplete +PR_EMS_AB_ADMIN_DISPLAY_NAME_W: Incomplete +PR_EMS_AB_ADMIN_EXTENSION_DLL: Incomplete +PR_EMS_AB_ADMIN_EXTENSION_DLL_A: Incomplete +PR_EMS_AB_ADMIN_EXTENSION_DLL_W: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_A: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_W: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_O: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_T: Incomplete +PR_EMS_AB_ALT_RECIPIENT: Incomplete +PR_EMS_AB_ALT_RECIPIENT_A: Incomplete +PR_EMS_AB_ALT_RECIPIENT_W: Incomplete +PR_EMS_AB_ALT_RECIPIENT_O: Incomplete +PR_EMS_AB_ALT_RECIPIENT_T: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_A: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_W: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_O: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_T: Incomplete +PR_EMS_AB_ANCESTOR_ID: Incomplete +PR_EMS_AB_ASSOC_NT_ACCOUNT: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_A: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_W: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_O: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_T: Incomplete +PR_EMS_AB_ASSOCIATION_LIFETIME: Incomplete +PR_EMS_AB_AUTH_ORIG_BL: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_A: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_W: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_O: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_T: Incomplete +PR_EMS_AB_AUTHORITY_REVOCATION_LIST: Incomplete +PR_EMS_AB_AUTHORIZED_DOMAIN: Incomplete +PR_EMS_AB_AUTHORIZED_DOMAIN_A: Incomplete +PR_EMS_AB_AUTHORIZED_DOMAIN_W: Incomplete +PR_EMS_AB_AUTHORIZED_PASSWORD: Incomplete +PR_EMS_AB_AUTHORIZED_USER: Incomplete +PR_EMS_AB_AUTHORIZED_USER_A: Incomplete +PR_EMS_AB_AUTHORIZED_USER_W: Incomplete +PR_EMS_AB_AUTOREPLY: Incomplete +PR_EMS_AB_AUTOREPLY_MESSAGE: Incomplete +PR_EMS_AB_AUTOREPLY_MESSAGE_A: Incomplete +PR_EMS_AB_AUTOREPLY_MESSAGE_W: Incomplete +PR_EMS_AB_AUTOREPLY_SUBJECT: Incomplete +PR_EMS_AB_AUTOREPLY_SUBJECT_A: Incomplete +PR_EMS_AB_AUTOREPLY_SUBJECT_W: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_A: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_W: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_O: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_T: Incomplete +PR_EMS_AB_BUSINESS_CATEGORY: Incomplete +PR_EMS_AB_BUSINESS_CATEGORY_A: Incomplete +PR_EMS_AB_BUSINESS_CATEGORY_W: Incomplete +PR_EMS_AB_BUSINESS_ROLES: Incomplete +PR_EMS_AB_CA_CERTIFICATE: Incomplete +PR_EMS_AB_CAN_CREATE_PF: Incomplete +PR_EMS_AB_CAN_CREATE_PF_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_T: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_T: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_T: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_T: Incomplete +PR_EMS_AB_CAN_PRESERVE_DNS: Incomplete +PR_EMS_AB_CERTIFICATE_REVOCATION_LIST: Incomplete +PR_EMS_AB_CLOCK_ALERT_OFFSET: Incomplete +PR_EMS_AB_CLOCK_ALERT_REPAIR: Incomplete +PR_EMS_AB_CLOCK_WARNING_OFFSET: Incomplete +PR_EMS_AB_CLOCK_WARNING_REPAIR: Incomplete +PR_EMS_AB_COMPUTER_NAME: Incomplete +PR_EMS_AB_COMPUTER_NAME_A: Incomplete +PR_EMS_AB_COMPUTER_NAME_W: Incomplete +PR_EMS_AB_CONNECTED_DOMAINS: Incomplete +PR_EMS_AB_CONNECTED_DOMAINS_A: Incomplete +PR_EMS_AB_CONNECTED_DOMAINS_W: Incomplete +PR_EMS_AB_CONTAINER_INFO: Incomplete +PR_EMS_AB_COST: Incomplete +PR_EMS_AB_COUNTRY_NAME: Incomplete +PR_EMS_AB_COUNTRY_NAME_A: Incomplete +PR_EMS_AB_COUNTRY_NAME_W: Incomplete +PR_EMS_AB_CROSS_CERTIFICATE_PAIR: Incomplete +PR_EMS_AB_DELIV_CONT_LENGTH: Incomplete +PR_EMS_AB_DELIV_EITS: Incomplete +PR_EMS_AB_DELIV_EXT_CONT_TYPES: Incomplete +PR_EMS_AB_DELIVER_AND_REDIRECT: Incomplete +PR_EMS_AB_DELIVERY_MECHANISM: Incomplete +PR_EMS_AB_DESCRIPTION: Incomplete +PR_EMS_AB_DESCRIPTION_A: Incomplete +PR_EMS_AB_DESCRIPTION_W: Incomplete +PR_EMS_AB_DESTINATION_INDICATOR: Incomplete +PR_EMS_AB_DESTINATION_INDICATOR_A: Incomplete +PR_EMS_AB_DESTINATION_INDICATOR_W: Incomplete +PR_EMS_AB_DIAGNOSTIC_REG_KEY: Incomplete +PR_EMS_AB_DIAGNOSTIC_REG_KEY_A: Incomplete +PR_EMS_AB_DIAGNOSTIC_REG_KEY_W: Incomplete +PR_EMS_AB_DISPLAY_NAME_OVERRIDE: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_A: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_W: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_O: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_T: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_A: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_W: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_O: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_T: Incomplete +PR_EMS_AB_DL_MEMBER_RULE: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_A: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_W: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_O: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_T: Incomplete +PR_EMS_AB_DOMAIN_NAME: Incomplete +PR_EMS_AB_DOMAIN_NAME_A: Incomplete +PR_EMS_AB_DOMAIN_NAME_W: Incomplete +PR_EMS_AB_DSA_SIGNATURE: Incomplete +PR_EMS_AB_DXA_ADMIN_COPY: Incomplete +PR_EMS_AB_DXA_ADMIN_FORWARD: Incomplete +PR_EMS_AB_DXA_ADMIN_UPDATE: Incomplete +PR_EMS_AB_DXA_APPEND_REQCN: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_A: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_W: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_O: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_T: Incomplete +PR_EMS_AB_DXA_CONF_REQ_TIME: Incomplete +PR_EMS_AB_DXA_CONF_SEQ: Incomplete +PR_EMS_AB_DXA_CONF_SEQ_A: Incomplete +PR_EMS_AB_DXA_CONF_SEQ_W: Incomplete +PR_EMS_AB_DXA_CONF_SEQ_USN: Incomplete +PR_EMS_AB_DXA_EXCHANGE_OPTIONS: Incomplete +PR_EMS_AB_DXA_EXPORT_NOW: Incomplete +PR_EMS_AB_DXA_FLAGS: Incomplete +PR_EMS_AB_DXA_IMP_SEQ: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_A: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_W: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_TIME: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_USN: Incomplete +PR_EMS_AB_DXA_IMPORT_NOW: Incomplete +PR_EMS_AB_DXA_IN_TEMPLATE_MAP: Incomplete +PR_EMS_AB_DXA_IN_TEMPLATE_MAP_A: Incomplete +PR_EMS_AB_DXA_IN_TEMPLATE_MAP_W: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_A: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_W: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_O: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_T: Incomplete +PR_EMS_AB_DXA_LOGGING_LEVEL: Incomplete +PR_EMS_AB_DXA_NATIVE_ADDRESS_TYPE: Incomplete +PR_EMS_AB_DXA_NATIVE_ADDRESS_TYPE_A: Incomplete +PR_EMS_AB_DXA_NATIVE_ADDRESS_TYPE_W: Incomplete +PR_EMS_AB_DXA_OUT_TEMPLATE_MAP: Incomplete +PR_EMS_AB_DXA_OUT_TEMPLATE_MAP_A: Incomplete +PR_EMS_AB_DXA_OUT_TEMPLATE_MAP_W: Incomplete +PR_EMS_AB_DXA_PASSWORD: Incomplete +PR_EMS_AB_DXA_PASSWORD_A: Incomplete +PR_EMS_AB_DXA_PASSWORD_W: Incomplete +PR_EMS_AB_DXA_PREV_EXCHANGE_OPTIONS: Incomplete +PR_EMS_AB_DXA_PREV_EXPORT_NATIVE_ONLY: Incomplete +PR_EMS_AB_DXA_PREV_IN_EXCHANGE_SENSITIVITY: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_A: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_W: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_O: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_T: Incomplete +PR_EMS_AB_DXA_PREV_REPLICATION_SENSITIVITY: Incomplete +PR_EMS_AB_DXA_PREV_TEMPLATE_OPTIONS: Incomplete +PR_EMS_AB_DXA_PREV_TYPES: Incomplete +PR_EMS_AB_DXA_RECIPIENT_CP: Incomplete +PR_EMS_AB_DXA_RECIPIENT_CP_A: Incomplete +PR_EMS_AB_DXA_RECIPIENT_CP_W: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_A: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_W: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_O: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_T: Incomplete +PR_EMS_AB_DXA_REQ_SEQ: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_A: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_W: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_TIME: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_USN: Incomplete +PR_EMS_AB_DXA_REQNAME: Incomplete +PR_EMS_AB_DXA_REQNAME_A: Incomplete +PR_EMS_AB_DXA_REQNAME_W: Incomplete +PR_EMS_AB_DXA_SVR_SEQ: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_A: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_W: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_TIME: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_USN: Incomplete +PR_EMS_AB_DXA_TASK: Incomplete +PR_EMS_AB_DXA_TEMPLATE_OPTIONS: Incomplete +PR_EMS_AB_DXA_TEMPLATE_TIMESTAMP: Incomplete +PR_EMS_AB_DXA_TYPES: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_A: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_W: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_O: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_T: Incomplete +PR_EMS_AB_ENABLED_PROTOCOLS: Incomplete +PR_EMS_AB_ENCAPSULATION_METHOD: Incomplete +PR_EMS_AB_ENCRYPT: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_NA: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_NA_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_NA_W: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_OTHER: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_OTHER_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_OTHER_W: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_NA: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_NA_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_NA_W: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_OTHER: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_OTHER_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_OTHER_W: Incomplete +PR_EMS_AB_EXPAND_DLS_LOCALLY: Incomplete +PR_EMS_AB_EXPIRATION_TIME: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_A: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_W: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_O: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_T: Incomplete +PR_EMS_AB_EXPORT_CUSTOM_RECIPIENTS: Incomplete +PR_EMS_AB_EXTENDED_CHARS_ALLOWED: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_1: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_1_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_1_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_10: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_10_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_10_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_2: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_2_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_2_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_3: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_3_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_3_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_4: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_4_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_4_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_5: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_5_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_5_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_6: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_6_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_6_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_7: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_7_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_7_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_8: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_8_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_8_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_9: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_9_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_9_W: Incomplete +PR_EMS_AB_EXTENSION_DATA: Incomplete +PR_EMS_AB_EXTENSION_NAME: Incomplete +PR_EMS_AB_EXTENSION_NAME_A: Incomplete +PR_EMS_AB_EXTENSION_NAME_W: Incomplete +PR_EMS_AB_EXTENSION_NAME_INHERITED: Incomplete +PR_EMS_AB_EXTENSION_NAME_INHERITED_A: Incomplete +PR_EMS_AB_EXTENSION_NAME_INHERITED_W: Incomplete +PR_EMS_AB_FACSIMILE_TELEPHONE_NUMBER: Incomplete +PR_EMS_AB_FILE_VERSION: Incomplete +PR_EMS_AB_FILTER_LOCAL_ADDRESSES: Incomplete +PR_EMS_AB_FOLDER_PATHNAME: Incomplete +PR_EMS_AB_FOLDER_PATHNAME_A: Incomplete +PR_EMS_AB_FOLDER_PATHNAME_W: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_A: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_W: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_O: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_T: Incomplete +PR_EMS_AB_GARBAGE_COLL_PERIOD: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_CRED: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_CRED_A: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_CRED_W: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_DESIG: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_DESIG_A: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_DESIG_W: Incomplete +PR_EMS_AB_GATEWAY_PROXY: Incomplete +PR_EMS_AB_GATEWAY_PROXY_A: Incomplete +PR_EMS_AB_GATEWAY_PROXY_W: Incomplete +PR_EMS_AB_GATEWAY_ROUTING_TREE: Incomplete +PR_EMS_AB_GWART_LAST_MODIFIED: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_A: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_W: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_O: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_T: Incomplete +PR_EMS_AB_HAS_MASTER_NCS: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_A: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_W: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_O: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_T: Incomplete +PR_EMS_AB_HELP_DATA16: Incomplete +PR_EMS_AB_HELP_DATA32: Incomplete +PR_EMS_AB_HELP_FILE_NAME: Incomplete +PR_EMS_AB_HELP_FILE_NAME_A: Incomplete +PR_EMS_AB_HELP_FILE_NAME_W: Incomplete +PR_EMS_AB_HEURISTICS: Incomplete +PR_EMS_AB_HIDE_DL_MEMBERSHIP: Incomplete +PR_EMS_AB_HIDE_FROM_ADDRESS_BOOK: Incomplete +PR_EMS_AB_HOME_MDB: Incomplete +PR_EMS_AB_HOME_MDB_A: Incomplete +PR_EMS_AB_HOME_MDB_W: Incomplete +PR_EMS_AB_HOME_MDB_O: Incomplete +PR_EMS_AB_HOME_MDB_T: Incomplete +PR_EMS_AB_HOME_MDB_BL: Incomplete +PR_EMS_AB_HOME_MDB_BL_A: Incomplete +PR_EMS_AB_HOME_MDB_BL_W: Incomplete +PR_EMS_AB_HOME_MDB_BL_O: Incomplete +PR_EMS_AB_HOME_MDB_BL_T: Incomplete +PR_EMS_AB_HOME_MTA: Incomplete +PR_EMS_AB_HOME_MTA_A: Incomplete +PR_EMS_AB_HOME_MTA_W: Incomplete +PR_EMS_AB_HOME_MTA_O: Incomplete +PR_EMS_AB_HOME_MTA_T: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_A: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_W: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_O: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_T: Incomplete +PR_EMS_AB_IMPORT_CONTAINER: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_A: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_W: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_O: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_T: Incomplete +PR_EMS_AB_IMPORT_SENSITIVITY: Incomplete +PR_EMS_AB_IMPORTED_FROM: Incomplete +PR_EMS_AB_IMPORTED_FROM_A: Incomplete +PR_EMS_AB_IMPORTED_FROM_W: Incomplete +PR_EMS_AB_INBOUND_SITES: Incomplete +PR_EMS_AB_INBOUND_SITES_A: Incomplete +PR_EMS_AB_INBOUND_SITES_W: Incomplete +PR_EMS_AB_INBOUND_SITES_O: Incomplete +PR_EMS_AB_INBOUND_SITES_T: Incomplete +PR_EMS_AB_INSTANCE_TYPE: Incomplete +PR_EMS_AB_INTERNATIONAL_ISDN_NUMBER: Incomplete +PR_EMS_AB_INTERNATIONAL_ISDN_NUMBER_A: Incomplete +PR_EMS_AB_INTERNATIONAL_ISDN_NUMBER_W: Incomplete +PR_EMS_AB_INVOCATION_ID: Incomplete +PR_EMS_AB_IS_DELETED: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_A: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_W: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_O: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_T: Incomplete +PR_EMS_AB_IS_SINGLE_VALUED: Incomplete +PR_EMS_AB_KCC_STATUS: Incomplete +PR_EMS_AB_KM_SERVER: Incomplete +PR_EMS_AB_KM_SERVER_A: Incomplete +PR_EMS_AB_KM_SERVER_W: Incomplete +PR_EMS_AB_KM_SERVER_O: Incomplete +PR_EMS_AB_KM_SERVER_T: Incomplete +PR_EMS_AB_KNOWLEDGE_INFORMATION: Incomplete +PR_EMS_AB_KNOWLEDGE_INFORMATION_A: Incomplete +PR_EMS_AB_KNOWLEDGE_INFORMATION_W: Incomplete +PR_EMS_AB_LANGUAGE: Incomplete +PR_EMS_AB_LDAP_DISPLAY_NAME: Incomplete +PR_EMS_AB_LDAP_DISPLAY_NAME_A: Incomplete +PR_EMS_AB_LDAP_DISPLAY_NAME_W: Incomplete +PR_EMS_AB_LINE_WRAP: Incomplete +PR_EMS_AB_LINK_ID: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_A: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_W: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_ADDRESS: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_ADDRESS_A: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_ADDRESS_W: Incomplete +PR_EMS_AB_LOCAL_INITIAL_TURN: Incomplete +PR_EMS_AB_LOCAL_SCOPE: Incomplete +PR_EMS_AB_LOCAL_SCOPE_A: Incomplete +PR_EMS_AB_LOCAL_SCOPE_W: Incomplete +PR_EMS_AB_LOCAL_SCOPE_O: Incomplete +PR_EMS_AB_LOCAL_SCOPE_T: Incomplete +PR_EMS_AB_LOG_FILENAME: Incomplete +PR_EMS_AB_LOG_FILENAME_A: Incomplete +PR_EMS_AB_LOG_FILENAME_W: Incomplete +PR_EMS_AB_LOG_ROLLOVER_INTERVAL: Incomplete +PR_EMS_AB_MAINTAIN_AUTOREPLY_HISTORY: Incomplete +PR_EMS_AB_MANAGER: Incomplete +PR_EMS_AB_MANAGER_A: Incomplete +PR_EMS_AB_MANAGER_W: Incomplete +PR_EMS_AB_MANAGER_O: Incomplete +PR_EMS_AB_MANAGER_T: Incomplete +PR_EMS_AB_MAPI_DISPLAY_TYPE: Incomplete +PR_EMS_AB_MAPI_ID: Incomplete +PR_EMS_AB_MAXIMUM_OBJECT_ID: Incomplete +PR_EMS_AB_MDB_BACKOFF_INTERVAL: Incomplete +PR_EMS_AB_MDB_MSG_TIME_OUT_PERIOD: Incomplete +PR_EMS_AB_MDB_OVER_QUOTA_LIMIT: Incomplete +PR_EMS_AB_MDB_STORAGE_QUOTA: Incomplete +PR_EMS_AB_MDB_UNREAD_LIMIT: Incomplete +PR_EMS_AB_MDB_USE_DEFAULTS: Incomplete +PR_EMS_AB_MEMBER: Incomplete +PR_EMS_AB_MEMBER_A: Incomplete +PR_EMS_AB_MEMBER_W: Incomplete +PR_EMS_AB_MEMBER_O: Incomplete +PR_EMS_AB_MEMBER_T: Incomplete +PR_EMS_AB_MESSAGE_TRACKING_ENABLED: Incomplete +PR_EMS_AB_MONITOR_CLOCK: Incomplete +PR_EMS_AB_MONITOR_SERVERS: Incomplete +PR_EMS_AB_MONITOR_SERVICES: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_A: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_W: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_O: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_T: Incomplete +PR_EMS_AB_MONITORED_SERVERS: Incomplete +PR_EMS_AB_MONITORED_SERVERS_A: Incomplete +PR_EMS_AB_MONITORED_SERVERS_W: Incomplete +PR_EMS_AB_MONITORED_SERVERS_O: Incomplete +PR_EMS_AB_MONITORED_SERVERS_T: Incomplete +PR_EMS_AB_MONITORED_SERVICES: Incomplete +PR_EMS_AB_MONITORED_SERVICES_A: Incomplete +PR_EMS_AB_MONITORED_SERVICES_W: Incomplete +PR_EMS_AB_MONITORING_ALERT_DELAY: Incomplete +PR_EMS_AB_MONITORING_ALERT_UNITS: Incomplete +PR_EMS_AB_MONITORING_AVAILABILITY_STYLE: Incomplete +PR_EMS_AB_MONITORING_AVAILABILITY_WINDOW: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_A: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_W: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_O: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_T: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_A: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_W: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_O: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_T: Incomplete +PR_EMS_AB_MONITORING_ESCALATION_PROCEDURE: Incomplete +PR_EMS_AB_MONITORING_HOTSITE_POLL_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_HOTSITE_POLL_UNITS: Incomplete +PR_EMS_AB_MONITORING_MAIL_UPDATE_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_MAIL_UPDATE_UNITS: Incomplete +PR_EMS_AB_MONITORING_NORMAL_POLL_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_NORMAL_POLL_UNITS: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_A: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_W: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_O: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_T: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_A: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_W: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_O: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_T: Incomplete +PR_EMS_AB_MONITORING_RPC_UPDATE_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_RPC_UPDATE_UNITS: Incomplete +PR_EMS_AB_MONITORING_WARNING_DELAY: Incomplete +PR_EMS_AB_MONITORING_WARNING_UNITS: Incomplete +PR_EMS_AB_MTA_LOCAL_CRED: Incomplete +PR_EMS_AB_MTA_LOCAL_CRED_A: Incomplete +PR_EMS_AB_MTA_LOCAL_CRED_W: Incomplete +PR_EMS_AB_MTA_LOCAL_DESIG: Incomplete +PR_EMS_AB_MTA_LOCAL_DESIG_A: Incomplete +PR_EMS_AB_MTA_LOCAL_DESIG_W: Incomplete +PR_EMS_AB_N_ADDRESS: Incomplete +PR_EMS_AB_N_ADDRESS_TYPE: Incomplete +PR_EMS_AB_NETWORK_ADDRESS: Incomplete +PR_EMS_AB_NETWORK_ADDRESS_A: Incomplete +PR_EMS_AB_NETWORK_ADDRESS_W: Incomplete +PR_EMS_AB_NNTP_CHARACTER_SET: Incomplete +PR_EMS_AB_NNTP_CHARACTER_SET_A: Incomplete +PR_EMS_AB_NNTP_CHARACTER_SET_W: Incomplete +PR_EMS_AB_NNTP_CONTENT_FORMAT: Incomplete +PR_EMS_AB_NNTP_CONTENT_FORMAT_A: Incomplete +PR_EMS_AB_NNTP_CONTENT_FORMAT_W: Incomplete +PR_EMS_AB_NT_MACHINE_NAME: Incomplete +PR_EMS_AB_NT_MACHINE_NAME_A: Incomplete +PR_EMS_AB_NT_MACHINE_NAME_W: Incomplete +PR_EMS_AB_NT_SECURITY_DESCRIPTOR: Incomplete +PR_EMS_AB_NUM_OF_OPEN_RETRIES: Incomplete +PR_EMS_AB_NUM_OF_TRANSFER_RETRIES: Incomplete +PR_EMS_AB_OBJ_DIST_NAME: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_A: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_W: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_O: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_T: Incomplete +PR_EMS_AB_OBJECT_CLASS_CATEGORY: Incomplete +PR_EMS_AB_OBJECT_VERSION: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_A: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_W: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_O: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_T: Incomplete +PR_EMS_AB_OFF_LINE_AB_SCHEDULE: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_A: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_W: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_O: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_T: Incomplete +PR_EMS_AB_OFF_LINE_AB_STYLE: Incomplete +PR_EMS_AB_OID_TYPE: Incomplete +PR_EMS_AB_OM_OBJECT_CLASS: Incomplete +PR_EMS_AB_OM_SYNTAX: Incomplete +PR_EMS_AB_OOF_REPLY_TO_ORIGINATOR: Incomplete +PR_EMS_AB_OPEN_RETRY_INTERVAL: Incomplete +PR_EMS_AB_ORGANIZATION_NAME: Incomplete +PR_EMS_AB_ORGANIZATION_NAME_A: Incomplete +PR_EMS_AB_ORGANIZATION_NAME_W: Incomplete +PR_EMS_AB_ORGANIZATIONAL_UNIT_NAME: Incomplete +PR_EMS_AB_ORGANIZATIONAL_UNIT_NAME_A: Incomplete +PR_EMS_AB_ORGANIZATIONAL_UNIT_NAME_W: Incomplete +PR_EMS_AB_ORIGINAL_DISPLAY_TABLE: Incomplete +PR_EMS_AB_ORIGINAL_DISPLAY_TABLE_MSDOS: Incomplete +PR_EMS_AB_OUTBOUND_SITES: Incomplete +PR_EMS_AB_OUTBOUND_SITES_A: Incomplete +PR_EMS_AB_OUTBOUND_SITES_W: Incomplete +PR_EMS_AB_OUTBOUND_SITES_O: Incomplete +PR_EMS_AB_OUTBOUND_SITES_T: Incomplete +PR_EMS_AB_OWNER: Incomplete +PR_EMS_AB_OWNER_A: Incomplete +PR_EMS_AB_OWNER_W: Incomplete +PR_EMS_AB_OWNER_O: Incomplete +PR_EMS_AB_OWNER_T: Incomplete +PR_EMS_AB_OWNER_BL: Incomplete +PR_EMS_AB_OWNER_BL_A: Incomplete +PR_EMS_AB_OWNER_BL_W: Incomplete +PR_EMS_AB_OWNER_BL_O: Incomplete +PR_EMS_AB_OWNER_BL_T: Incomplete +PR_EMS_AB_P_SELECTOR: Incomplete +PR_EMS_AB_P_SELECTOR_INBOUND: Incomplete +PR_EMS_AB_PER_MSG_DIALOG_DISPLAY_TABLE: Incomplete +PR_EMS_AB_PER_RECIP_DIALOG_DISPLAY_TABLE: Incomplete +PR_EMS_AB_PERIOD_REP_SYNC_TIMES: Incomplete +PR_EMS_AB_PERIOD_REPL_STAGGER: Incomplete +PR_EMS_AB_PF_CONTACTS: Incomplete +PR_EMS_AB_PF_CONTACTS_A: Incomplete +PR_EMS_AB_PF_CONTACTS_W: Incomplete +PR_EMS_AB_PF_CONTACTS_O: Incomplete +PR_EMS_AB_PF_CONTACTS_T: Incomplete +PR_EMS_AB_POP_CHARACTER_SET: Incomplete +PR_EMS_AB_POP_CHARACTER_SET_A: Incomplete +PR_EMS_AB_POP_CHARACTER_SET_W: Incomplete +PR_EMS_AB_POP_CONTENT_FORMAT: Incomplete +PR_EMS_AB_POP_CONTENT_FORMAT_A: Incomplete +PR_EMS_AB_POP_CONTENT_FORMAT_W: Incomplete +PR_EMS_AB_POSTAL_ADDRESS: Incomplete +PR_EMS_AB_PREFERRED_DELIVERY_METHOD: Incomplete +PR_EMS_AB_PRMD: Incomplete +PR_EMS_AB_PRMD_A: Incomplete +PR_EMS_AB_PRMD_W: Incomplete +PR_EMS_AB_PROXY_ADDRESSES: Incomplete +PR_EMS_AB_PROXY_ADDRESSES_A: Incomplete +PR_EMS_AB_PROXY_ADDRESSES_W: Incomplete +PR_EMS_AB_PROXY_GENERATOR_DLL: Incomplete +PR_EMS_AB_PROXY_GENERATOR_DLL_A: Incomplete +PR_EMS_AB_PROXY_GENERATOR_DLL_W: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_A: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_W: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_O: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_T: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_A: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_W: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_O: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_T: Incomplete +PR_EMS_AB_QUOTA_NOTIFICATION_SCHEDULE: Incomplete +PR_EMS_AB_QUOTA_NOTIFICATION_STYLE: Incomplete +PR_EMS_AB_RANGE_LOWER: Incomplete +PR_EMS_AB_RANGE_UPPER: Incomplete +PR_EMS_AB_RAS_CALLBACK_NUMBER: Incomplete +PR_EMS_AB_RAS_CALLBACK_NUMBER_A: Incomplete +PR_EMS_AB_RAS_CALLBACK_NUMBER_W: Incomplete +PR_EMS_AB_RAS_PHONE_NUMBER: Incomplete +PR_EMS_AB_RAS_PHONE_NUMBER_A: Incomplete +PR_EMS_AB_RAS_PHONE_NUMBER_W: Incomplete +PR_EMS_AB_RAS_PHONEBOOK_ENTRY_NAME: Incomplete +PR_EMS_AB_RAS_PHONEBOOK_ENTRY_NAME_A: Incomplete +PR_EMS_AB_RAS_PHONEBOOK_ENTRY_NAME_W: Incomplete +PR_EMS_AB_RAS_REMOTE_SRVR_NAME: Incomplete +PR_EMS_AB_RAS_REMOTE_SRVR_NAME_A: Incomplete +PR_EMS_AB_RAS_REMOTE_SRVR_NAME_W: Incomplete +PR_EMS_AB_REGISTERED_ADDRESS: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_A: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_W: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_ADDRESS: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_ADDRESS_A: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_ADDRESS_W: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_A: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_W: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_O: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_T: Incomplete +PR_EMS_AB_REMOTE_SITE: Incomplete +PR_EMS_AB_REMOTE_SITE_A: Incomplete +PR_EMS_AB_REMOTE_SITE_W: Incomplete +PR_EMS_AB_REMOTE_SITE_O: Incomplete +PR_EMS_AB_REMOTE_SITE_T: Incomplete +PR_EMS_AB_REPLICATION_MAIL_MSG_SIZE: Incomplete +PR_EMS_AB_REPLICATION_SENSITIVITY: Incomplete +PR_EMS_AB_REPLICATION_STAGGER: Incomplete +PR_EMS_AB_REPORT_TO_ORIGINATOR: Incomplete +PR_EMS_AB_REPORT_TO_OWNER: Incomplete +PR_EMS_AB_REPORTS: Incomplete +PR_EMS_AB_REPORTS_A: Incomplete +PR_EMS_AB_REPORTS_W: Incomplete +PR_EMS_AB_REPORTS_O: Incomplete +PR_EMS_AB_REPORTS_T: Incomplete +PR_EMS_AB_REQ_SEQ: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_A: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_W: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_O: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_T: Incomplete +PR_EMS_AB_RID_SERVER: Incomplete +PR_EMS_AB_RID_SERVER_A: Incomplete +PR_EMS_AB_RID_SERVER_W: Incomplete +PR_EMS_AB_RID_SERVER_O: Incomplete +PR_EMS_AB_RID_SERVER_T: Incomplete +PR_EMS_AB_ROLE_OCCUPANT: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_A: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_W: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_O: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_T: Incomplete +PR_EMS_AB_ROUTING_LIST: Incomplete +PR_EMS_AB_ROUTING_LIST_A: Incomplete +PR_EMS_AB_ROUTING_LIST_W: Incomplete +PR_EMS_AB_RTS_CHECKPOINT_SIZE: Incomplete +PR_EMS_AB_RTS_RECOVERY_TIMEOUT: Incomplete +PR_EMS_AB_RTS_WINDOW_SIZE: Incomplete +PR_EMS_AB_RUNS_ON: Incomplete +PR_EMS_AB_RUNS_ON_A: Incomplete +PR_EMS_AB_RUNS_ON_W: Incomplete +PR_EMS_AB_RUNS_ON_O: Incomplete +PR_EMS_AB_RUNS_ON_T: Incomplete +PR_EMS_AB_S_SELECTOR: Incomplete +PR_EMS_AB_S_SELECTOR_INBOUND: Incomplete +PR_EMS_AB_SCHEMA_FLAGS: Incomplete +PR_EMS_AB_SCHEMA_VERSION: Incomplete +PR_EMS_AB_SEARCH_FLAGS: Incomplete +PR_EMS_AB_SEARCH_GUIDE: Incomplete +PR_EMS_AB_SECURITY_PROTOCOL: Incomplete +PR_EMS_AB_SEE_ALSO: Incomplete +PR_EMS_AB_SEE_ALSO_A: Incomplete +PR_EMS_AB_SEE_ALSO_W: Incomplete +PR_EMS_AB_SEE_ALSO_O: Incomplete +PR_EMS_AB_SEE_ALSO_T: Incomplete +PR_EMS_AB_SERIAL_NUMBER: Incomplete +PR_EMS_AB_SERIAL_NUMBER_A: Incomplete +PR_EMS_AB_SERIAL_NUMBER_W: Incomplete +PR_EMS_AB_SERVICE_ACTION_FIRST: Incomplete +PR_EMS_AB_SERVICE_ACTION_OTHER: Incomplete +PR_EMS_AB_SERVICE_ACTION_SECOND: Incomplete +PR_EMS_AB_SERVICE_RESTART_DELAY: Incomplete +PR_EMS_AB_SERVICE_RESTART_MESSAGE: Incomplete +PR_EMS_AB_SERVICE_RESTART_MESSAGE_A: Incomplete +PR_EMS_AB_SERVICE_RESTART_MESSAGE_W: Incomplete +PR_EMS_AB_SESSION_DISCONNECT_TIMER: Incomplete +PR_EMS_AB_SITE_AFFINITY: Incomplete +PR_EMS_AB_SITE_AFFINITY_A: Incomplete +PR_EMS_AB_SITE_AFFINITY_W: Incomplete +PR_EMS_AB_SITE_FOLDER_GUID: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_A: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_W: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_O: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_T: Incomplete +PR_EMS_AB_SITE_PROXY_SPACE: Incomplete +PR_EMS_AB_SITE_PROXY_SPACE_A: Incomplete +PR_EMS_AB_SITE_PROXY_SPACE_W: Incomplete +PR_EMS_AB_SPACE_LAST_COMPUTED: Incomplete +PR_EMS_AB_STREET_ADDRESS: Incomplete +PR_EMS_AB_STREET_ADDRESS_A: Incomplete +PR_EMS_AB_STREET_ADDRESS_W: Incomplete +PR_EMS_AB_SUB_REFS: Incomplete +PR_EMS_AB_SUB_REFS_A: Incomplete +PR_EMS_AB_SUB_REFS_W: Incomplete +PR_EMS_AB_SUB_REFS_O: Incomplete +PR_EMS_AB_SUB_REFS_T: Incomplete +PR_EMS_AB_SUB_SITE: Incomplete +PR_EMS_AB_SUB_SITE_A: Incomplete +PR_EMS_AB_SUB_SITE_W: Incomplete +PR_EMS_AB_SUBMISSION_CONT_LENGTH: Incomplete +PR_EMS_AB_SUPPORTED_APPLICATION_CONTEXT: Incomplete +PR_EMS_AB_SUPPORTING_STACK: Incomplete +PR_EMS_AB_SUPPORTING_STACK_A: Incomplete +PR_EMS_AB_SUPPORTING_STACK_W: Incomplete +PR_EMS_AB_SUPPORTING_STACK_O: Incomplete +PR_EMS_AB_SUPPORTING_STACK_T: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_A: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_W: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_O: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_T: Incomplete +PR_EMS_AB_T_SELECTOR: Incomplete +PR_EMS_AB_T_SELECTOR_INBOUND: Incomplete +PR_EMS_AB_TARGET_ADDRESS: Incomplete +PR_EMS_AB_TARGET_ADDRESS_A: Incomplete +PR_EMS_AB_TARGET_ADDRESS_W: Incomplete +PR_EMS_AB_TARGET_MTAS: Incomplete +PR_EMS_AB_TARGET_MTAS_A: Incomplete +PR_EMS_AB_TARGET_MTAS_W: Incomplete +PR_EMS_AB_TELEPHONE_NUMBER: Incomplete +PR_EMS_AB_TELEPHONE_NUMBER_A: Incomplete +PR_EMS_AB_TELEPHONE_NUMBER_W: Incomplete +PR_EMS_AB_TELETEX_TERMINAL_IDENTIFIER: Incomplete +PR_EMS_AB_TEMP_ASSOC_THRESHOLD: Incomplete +PR_EMS_AB_TOMBSTONE_LIFETIME: Incomplete +PR_EMS_AB_TRACKING_LOG_PATH_NAME: Incomplete +PR_EMS_AB_TRACKING_LOG_PATH_NAME_A: Incomplete +PR_EMS_AB_TRACKING_LOG_PATH_NAME_W: Incomplete +PR_EMS_AB_TRANS_RETRY_MINS: Incomplete +PR_EMS_AB_TRANS_TIMEOUT_MINS: Incomplete +PR_EMS_AB_TRANSFER_RETRY_INTERVAL: Incomplete +PR_EMS_AB_TRANSFER_TIMEOUT_NON_URGENT: Incomplete +PR_EMS_AB_TRANSFER_TIMEOUT_NORMAL: Incomplete +PR_EMS_AB_TRANSFER_TIMEOUT_URGENT: Incomplete +PR_EMS_AB_TRANSLATION_TABLE_USED: Incomplete +PR_EMS_AB_TRANSPORT_EXPEDITED_DATA: Incomplete +PR_EMS_AB_TRUST_LEVEL: Incomplete +PR_EMS_AB_TURN_REQUEST_THRESHOLD: Incomplete +PR_EMS_AB_TWO_WAY_ALTERNATE_FACILITY: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_A: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_W: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_O: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_T: Incomplete +PR_EMS_AB_USE_SERVER_VALUES: Incomplete +PR_EMS_AB_USER_PASSWORD: Incomplete +PR_EMS_AB_USN_CHANGED: Incomplete +PR_EMS_AB_USN_CREATED: Incomplete +PR_EMS_AB_USN_DSA_LAST_OBJ_REMOVED: Incomplete +PR_EMS_AB_USN_INTERSITE: Incomplete +PR_EMS_AB_USN_LAST_OBJ_REM: Incomplete +PR_EMS_AB_USN_SOURCE: Incomplete +PR_EMS_AB_WWW_HOME_PAGE: Incomplete +PR_EMS_AB_WWW_HOME_PAGE_A: Incomplete +PR_EMS_AB_WWW_HOME_PAGE_W: Incomplete +PR_EMS_AB_X121_ADDRESS: Incomplete +PR_EMS_AB_X121_ADDRESS_A: Incomplete +PR_EMS_AB_X121_ADDRESS_W: Incomplete +PR_EMS_AB_X25_CALL_USER_DATA_INCOMING: Incomplete +PR_EMS_AB_X25_CALL_USER_DATA_OUTGOING: Incomplete +PR_EMS_AB_X25_FACILITIES_DATA_INCOMING: Incomplete +PR_EMS_AB_X25_FACILITIES_DATA_OUTGOING: Incomplete +PR_EMS_AB_X25_LEASED_LINE_PORT: Incomplete +PR_EMS_AB_X25_LEASED_OR_SWITCHED: Incomplete +PR_EMS_AB_X25_REMOTE_MTA_PHONE: Incomplete +PR_EMS_AB_X25_REMOTE_MTA_PHONE_A: Incomplete +PR_EMS_AB_X25_REMOTE_MTA_PHONE_W: Incomplete +PR_EMS_AB_X400_ATTACHMENT_TYPE: Incomplete +PR_EMS_AB_X400_SELECTOR_SYNTAX: Incomplete +PR_EMS_AB_X500_ACCESS_CONTROL_LIST: Incomplete +PR_EMS_AB_XMIT_TIMEOUT_NON_URGENT: Incomplete +PR_EMS_AB_XMIT_TIMEOUT_NORMAL: Incomplete +PR_EMS_AB_XMIT_TIMEOUT_URGENT: Incomplete diff --git a/stubs/pywin32/win32comext/mapi/exchange.pyi b/stubs/pywin32/win32comext/mapi/exchange.pyi new file mode 100644 index 000000000000..ac1a9741be47 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/exchange.pyi @@ -0,0 +1,9 @@ +import _win32typing + +OPENSTORE_HOME_LOGON: int +OPENSTORE_OVERRIDE_HOME_MDB: int +OPENSTORE_PUBLIC: int +OPENSTORE_TAKE_OWNERSHIP: int +OPENSTORE_USE_ADMIN_PRIVILEGE: int +IID_IExchangeManageStore: _win32typing.PyIID +IID_IExchangeManageStoreEx: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/mapi/mapi.pyi b/stubs/pywin32/win32comext/mapi/mapi.pyi new file mode 100644 index 000000000000..f6895c629079 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/mapi.pyi @@ -0,0 +1,342 @@ +from _typeshed import Incomplete + +import _win32typing + +def HexFromBin(val: str, /) -> str: ... +def BinFromHex(val: str, /) -> str: ... +def MAPIUninitialize() -> None: ... +def MAPIInitialize(init: _win32typing.MAPIINIT_0, /) -> None: ... +def MAPILogonEx(uiParam, profileName: str, password: str | None = ..., flags=..., /) -> _win32typing.PyIMAPISession: ... +def MAPIAdminProfiles(fFlags, /) -> _win32typing.PyIProfAdmin: ... +def HrQueryAllRows( + table: _win32typing.PyIMAPITable, + properties: _win32typing.PySPropTagArray, + restrictions: _win32typing.PySRestriction, + sortOrderSet: _win32typing.PySSortOrderSet, + rowsMax, + /, +): ... +def RTFSync(message: _win32typing.PyIMessage, flags, /): ... +def WrapCompressedRTFStream(stream: _win32typing.PyIStream, flags, /) -> _win32typing.PyIStream: ... +def WrapCompressedRTFStreamEx(stream: _win32typing.PyIStream, wcsinfo, /) -> tuple[_win32typing.PyIStream, Incomplete]: ... +def OpenIMsgSession(): ... +def CloseIMsgSession() -> None: ... +def OpenIMsgOnIStg( + session, + support, + storage: _win32typing.PyIStorage, + callback: Incomplete | None = ..., + callbackData: int = ..., + flags: int = ..., + /, +) -> _win32typing.PyIMessage: ... +def RTFStreamToHTML(The_stream_to_read_the_uncompressed_RTF_from: _win32typing.PyIStream, /) -> None: ... +def OpenStreamOnFile(filename: str, flags: int = ..., prefix: str | None = ..., /) -> _win32typing.PyIStream: ... +def OpenStreamOnFileW(filename, flags: int = ..., prefix: Incomplete | None = ..., /) -> _win32typing.PyIStream: ... +def HrGetOneProp(prop: _win32typing.PyIMAPIProp, propTag, /): ... +def HrSetOneProp(prop: _win32typing.PyIMAPIProp, propValue: _win32typing.PySPropValue, /): ... +def HrAllocAdviseSink(callback, context, /): ... +def HrThisThreadAdviseSink(_object, /): ... +def HrDispatchNotifications(*args): ... # incomplete +def MAPIUIDFromBinary(sz: str | None, /): ... + +AB_NO_DIALOG: int +ATTACH_BY_REF_ONLY: int +ATTACH_BY_REF_RESOLVE: int +ATTACH_BY_REFERENCE: int +ATTACH_BY_VALUE: int +ATTACH_EMBEDDED_MSG: int +ATTACH_OLE: int +BMR_EQZ: int +BMR_NEZ: int +BOOKMARK_BEGINNING: int +BOOKMARK_CURRENT: int +BOOKMARK_END: int +CCSF_8BITHEADERS: int +CCSF_EMBEDDED_MESSAGE: int +CCSF_INCLUDE_BCC: int +CCSF_NO_MSGID: int +CCSF_NOHEADERS: int +CCSF_PLAIN_TEXT_ONLY: int +CCSF_PRESERVE_SOURCE: int +CCSF_SMTP: int +CCSF_USE_RTF: int +CCSF_USE_TNEF: int +CLEAR_NRN_PENDING: int +CLEAR_READ_FLAG: int +CLEAR_RN_PENDING: int +CONVENIENT_DEPTH: int +DEL_FOLDERS: int +DEL_MESSAGES: int +DELETE_HARD_DELETE: int +DIR_BACKWARD: int +FL_FULLSTRING: int +FL_IGNORECASE: int +FL_IGNORENONSPACE: int +FL_LOOSE: int +FL_PREFIX: int +FL_SUBSTRING: int +FLUSH_ASYNC_OK: int +FLUSH_DOWNLOAD: int +FLUSH_FORCE: int +FLUSH_NO_UI: int +FLUSH_UPLOAD: int +fnevCriticalError: int +fnevExtended: int +fnevNewMail: int +fnevObjectCopied: int +fnevObjectCreated: int +fnevObjectDeleted: int +fnevObjectModified: int +fnevObjectMoved: int +fnevReservedForMapi: int +fnevSearchComplete: int +fnevStatusObjectModified: int +fnevTableModified: int +FOLDER_DIALOG: int +FOLDER_GENERIC: int +FOLDER_SEARCH: int +FORCE_SAVE: int +GENERATE_RECEIPT_ONLY: int +KEEP_OPEN_READONLY: int +KEEP_OPEN_READWRITE: int +LOGOFF_ABORT: int +LOGOFF_COMPLETE: int +LOGOFF_INBOUND: int +LOGOFF_NO_WAIT: int +LOGOFF_ORDERLY: int +LOGOFF_OUTBOUND: int +LOGOFF_OUTBOUND_QUEUE: int +LOGOFF_PURGE: int +LOGOFF_QUIET: int +MAIL_E_NAMENOTFOUND: int +MAPI_ABCONT: int +MAPI_ADDRBOOK: int +MAPI_ALLOW_OTHERS: int +MAPI_ASSOCIATED: int +MAPI_ATTACH: int +MAPI_BCC: int +MAPI_BEST_ACCESS: int +MAPI_CC: int +MAPI_CREATE: int +MAPI_DEFAULT_SERVICES: int +MAPI_DEFERRED_ERRORS: int +MAPI_DIALOG: int +MAPI_E_ACCOUNT_DISABLED: int +MAPI_E_AMBIGUOUS_RECIP: int +MAPI_E_BAD_CHARWIDTH: int +MAPI_E_BAD_COLUMN: int +MAPI_E_BAD_VALUE: int +MAPI_E_BUSY: int +MAPI_E_CALL_FAILED: int +MAPI_E_CANCEL: int +MAPI_E_COLLISION: int +MAPI_E_COMPUTED: int +MAPI_E_CORRUPT_DATA: int +MAPI_E_CORRUPT_STORE: int +MAPI_E_DECLINE_COPY: int +MAPI_E_DISK_ERROR: int +MAPI_E_END_OF_SESSION: int +MAPI_E_EXTENDED_ERROR: int +MAPI_E_FAILONEPROVIDER: int +MAPI_E_FOLDER_CYCLE: int +MAPI_E_HAS_FOLDERS: int +MAPI_E_HAS_MESSAGES: int +MAPI_E_INTERFACE_NOT_SUPPORTED: int +MAPI_E_INVALID_ACCESS_TIME: int +MAPI_E_INVALID_BOOKMARK: int +MAPI_E_INVALID_ENTRYID: int +MAPI_E_INVALID_OBJECT: int +MAPI_E_INVALID_PARAMETER: int +MAPI_E_INVALID_TYPE: int +MAPI_E_INVALID_WORKSTATION_ACCOUNT: int +MAPI_E_LOCKID_LIMIT: int +MAPI_E_LOGON_FAILED: int +MAPI_E_MISSING_REQUIRED_COLUMN: int +MAPI_E_NAMED_PROP_QUOTA_EXCEEDED: int +MAPI_E_NETWORK_ERROR: int +MAPI_E_NO_ACCESS: int +MAPI_E_NO_RECIPIENTS: int +MAPI_E_NO_SUPPORT: int +MAPI_E_NO_SUPPRESS: int +MAPI_E_NON_STANDARD: int +MAPI_E_NOT_ENOUGH_DISK: int +MAPI_E_NOT_ENOUGH_MEMORY: int +MAPI_E_NOT_ENOUGH_RESOURCES: int +MAPI_E_NOT_FOUND: int +MAPI_E_NOT_IN_QUEUE: int +MAPI_E_NOT_INITIALIZED: int +MAPI_E_NOT_ME: int +MAPI_E_OBJECT_CHANGED: int +MAPI_E_OBJECT_DELETED: int +MAPI_E_OFFLINE: int +MAPI_E_PASSWORD_CHANGE_REQUIRED: int +MAPI_E_PASSWORD_EXPIRED: int +MAPI_E_PROFILE_DELETED: int +MAPI_E_RECONNECTED: int +MAPI_E_SESSION_LIMIT: int +MAPI_E_STORE_FULL: int +MAPI_E_STRING_TOO_LONG: int +MAPI_E_SUBMITTED: int +MAPI_E_TABLE_EMPTY: int +MAPI_E_TABLE_TOO_BIG: int +MAPI_E_TIMEOUT: int +MAPI_E_TOO_BIG: int +MAPI_E_TOO_COMPLEX: int +MAPI_E_TYPE_NO_SUPPORT: int +MAPI_E_UNABLE_TO_ABORT: int +MAPI_E_UNABLE_TO_COMPLETE: int +MAPI_E_UNCONFIGURED: int +MAPI_E_UNEXPECTED_ID: int +MAPI_E_UNEXPECTED_TYPE: int +MAPI_E_UNKNOWN_CPID: int +MAPI_E_UNKNOWN_ENTRYID: int +MAPI_E_UNKNOWN_FLAGS: int +MAPI_E_UNKNOWN_LCID: int +MAPI_E_USER_CANCEL: int +MAPI_E_VERSION: int +MAPI_E_WAIT: int +MAPI_EXPLICIT_PROFILE: int +MAPI_EXTENDED: int +MAPI_FOLDER: int +MAPI_FORCE_ACCESS: int +MAPI_FORCE_DOWNLOAD: int +MAPI_FORMINFO: int +MAPI_INIT_VERSION: int +MAPI_LOGON_UI: int +MAPI_MAILUSER: int +MAPI_MESSAGE: int +MAPI_MODIFY: int +MAPI_MOVE: int +MAPI_MULTITHREAD_NOTIFICATIONS: int +MAPI_NATIVE_BODY: int +MAPI_NATIVE_BODY_TYPE_HTML: int +MAPI_NATIVE_BODY_TYPE_PLAINTEXT: int +MAPI_NATIVE_BODY_TYPE_RTF: int +MAPI_NEW_SESSION: int +MAPI_NO_IDS: int +MAPI_NO_MAIL: int +MAPI_NO_STRINGS: int +MAPI_NOREPLACE: int +MAPI_NT_SERVICE: int +MAPI_P1: int +MAPI_PASSWORD_UI: int +MAPI_PROFSECT: int +MAPI_SERVICE_UI_ALWAYS: int +MAPI_SESSION: int +MAPI_STATUS: int +MAPI_STORE: int +MAPI_SUBMITTED: int +MAPI_TIMEOUT_SHORT: int +MAPI_TO: int +MAPI_UNICODE: int +MAPI_USE_DEFAULT: int +MAPI_W_APPROX_COUNT: int +MAPI_W_CANCEL_MESSAGE: int +MAPI_W_ERRORS_RETURNED: int +MAPI_W_NO_SERVICE: int +MAPI_W_PARTIAL_COMPLETION: int +MAPI_W_POSITION_CHANGED: int +MDB_NO_DIALOG: int +MDB_NO_MAIL: int +MDB_TEMPORARY: int +MDB_WRITE: int +MESSAGE_DIALOG: int +MODRECIP_ADD: int +MODRECIP_MODIFY: int +MODRECIP_REMOVE: int +NO_ATTACHMENT: int +OPEN_IF_EXISTS: int +PSTF_BEST_ENCRYPTION: int +PSTF_COMPRESSABLE_ENCRYPTION: int +PSTF_NO_ENCRYPTION: int +RELOP_EQ: int +RELOP_GE: int +RELOP_GT: int +RELOP_LE: int +RELOP_LT: int +RELOP_NE: int +RELOP_RE: int +RES_AND: int +RES_BITMASK: int +RES_COMMENT: int +RES_COMPAREPROPS: int +RES_CONTENT: int +RES_EXIST: int +RES_NOT: int +RES_OR: int +RES_PROPERTY: int +RES_SIZE: int +RES_SUBRESTRICTION: int +RTF_SYNC_BODY_CHANGED: int +RTF_SYNC_RTF_CHANGED: int +SERVICE_UI_ALLOWED: int +SERVICE_UI_ALWAYS: int +SHOW_SOFT_DELETES: int +SOF_UNIQUEFILENAME: int +STATUS_DEFAULT_STORE: int +STATUS_FLUSH_QUEUES: int +STATUS_INBOUND_FLUSH: int +STATUS_OUTBOUND_FLUSH: int +SUPPRESS_RECEIPT: int +TABLE_CHANGED: int +TABLE_ERROR: int +TABLE_RELOAD: int +TABLE_RESTRICT_DONE: int +TABLE_ROW_ADDED: int +TABLE_ROW_DELETED: int +TABLE_ROW_MODIFIED: int +TABLE_SETCOL_DONE: int +TABLE_SORT_ASCEND: int +TABLE_SORT_COMBINE: int +TABLE_SORT_DESCEND: int +TABLE_SORT_DONE: int +TBL_ALL_COLUMNS: int +TBL_ASYNC: int +TBL_BATCH: int +CLSID_IConverterSession: _win32typing.PyIID +CLSID_MailMessage: _win32typing.PyIID +IID_IABContainer: _win32typing.PyIID +IID_IAddrBook: _win32typing.PyIID +IID_IAttachment: _win32typing.PyIID +IID_IConverterSession: _win32typing.PyIID +IID_IDistList: _win32typing.PyIID +IID_IMAPIAdviseSink: _win32typing.PyIID +IID_IMAPIContainer: _win32typing.PyIID +IID_IMAPIFolder: _win32typing.PyIID +IID_IMAPIProp: _win32typing.PyIID +IID_IMAPISession: _win32typing.PyIID +IID_IMAPIStatus: _win32typing.PyIID +IID_IMAPITable: _win32typing.PyIID +IID_IMailUser: _win32typing.PyIID +IID_IMessage: _win32typing.PyIID +IID_IMsgServiceAdmin: _win32typing.PyIID +IID_IMsgServiceAdmin2: _win32typing.PyIID +IID_IMsgStore: _win32typing.PyIID +IID_IProfAdmin: _win32typing.PyIID +IID_IProfSect: _win32typing.PyIID +IID_IProviderAdmin: _win32typing.PyIID +MAPI_DISTLIST: int +MSPST_UID_PROVIDER: _win32typing.PyIID +PSETID_Address: _win32typing.PyIID +PSETID_AirSync: _win32typing.PyIID +PSETID_Appointment: _win32typing.PyIID +PSETID_Common: _win32typing.PyIID +PSETID_Log: _win32typing.PyIID +PSETID_Meeting: _win32typing.PyIID +PSETID_Messaging: _win32typing.PyIID +PSETID_Note: _win32typing.PyIID +PSETID_PostRss: _win32typing.PyIID +PSETID_Remote: _win32typing.PyIID +PSETID_Report: _win32typing.PyIID +PSETID_Sharing: _win32typing.PyIID +PSETID_Task: _win32typing.PyIID +PSETID_UnifiedMessaging: _win32typing.PyIID +PS_INTERNET_HEADERS: _win32typing.PyIID +PS_MAPI: _win32typing.PyIID +PS_PUBLIC_STRINGS: _win32typing.PyIID +PS_ROUTING_ADDRTYPE: _win32typing.PyIID +PS_ROUTING_DISPLAY_NAME: _win32typing.PyIID +PS_ROUTING_EMAIL_ADDRESSES: _win32typing.PyIID +PS_ROUTING_ENTRYID: _win32typing.PyIID +PS_ROUTING_SEARCH_KEY: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/mapi/mapitags.pyi b/stubs/pywin32/win32comext/mapi/mapitags.pyi new file mode 100644 index 000000000000..660f492e9e57 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/mapitags.pyi @@ -0,0 +1,991 @@ +MV_FLAG: int +PT_UNSPECIFIED: int +PT_NULL: int +PT_I2: int +PT_LONG: int +PT_R4: int +PT_DOUBLE: int +PT_CURRENCY: int +PT_APPTIME: int +PT_ERROR: int +PT_BOOLEAN: int +PT_OBJECT: int +PT_I8: int +PT_STRING8: int +PT_UNICODE: int +PT_SYSTIME: int +PT_CLSID: int +PT_BINARY: int +PT_SHORT: int +PT_I4: int +PT_FLOAT: int +PT_R8: int +PT_LONGLONG: int +PT_MV_I2: int +PT_MV_LONG: int +PT_MV_R4: int +PT_MV_DOUBLE: int +PT_MV_CURRENCY: int +PT_MV_APPTIME: int +PT_MV_SYSTIME: int +PT_MV_STRING8: int +PT_MV_BINARY: int +PT_MV_UNICODE: int +PT_MV_CLSID: int +PT_MV_I8: int +PT_MV_SHORT: int +PT_MV_I4: int +PT_MV_FLOAT: int +PT_MV_R8: int +PT_MV_LONGLONG: int +PT_TSTRING: int +PT_MV_TSTRING: int +PROP_TYPE_MASK: int + +def PROP_TYPE(ulPropTag: int) -> int: ... +def PROP_ID(ulPropTag: int) -> int: ... +def PROP_TAG(ulPropType: int, ulPropID: int) -> int: ... + +PROP_ID_NULL: int +PROP_ID_INVALID: int +PR_NULL: int +PR_ACKNOWLEDGEMENT_MODE: int +PR_ALTERNATE_RECIPIENT_ALLOWED: int +PR_AUTHORIZING_USERS: int +PR_AUTO_FORWARD_COMMENT: int +PR_AUTO_FORWARD_COMMENT_W: int +PR_AUTO_FORWARD_COMMENT_A: int +PR_AUTO_FORWARDED: int +PR_CONTENT_CONFIDENTIALITY_ALGORITHM_ID: int +PR_CONTENT_CORRELATOR: int +PR_CONTENT_IDENTIFIER: int +PR_CONTENT_IDENTIFIER_W: int +PR_CONTENT_IDENTIFIER_A: int +PR_CONTENT_LENGTH: int +PR_CONTENT_RETURN_REQUESTED: int +PR_CONVERSATION_KEY: int +PR_CONVERSION_EITS: int +PR_CONVERSION_WITH_LOSS_PROHIBITED: int +PR_CONVERTED_EITS: int +PR_DEFERRED_DELIVERY_TIME: int +PR_DELIVER_TIME: int +PR_DISCARD_REASON: int +PR_DISCLOSURE_OF_RECIPIENTS: int +PR_DL_EXPANSION_HISTORY: int +PR_DL_EXPANSION_PROHIBITED: int +PR_EXPIRY_TIME: int +PR_IMPLICIT_CONVERSION_PROHIBITED: int +PR_IMPORTANCE: int +PR_IPM_ID: int +PR_LATEST_DELIVERY_TIME: int +PR_MESSAGE_CLASS: int +PR_MESSAGE_CLASS_W: int +PR_MESSAGE_CLASS_A: int +PR_MESSAGE_DELIVERY_ID: int +PR_MESSAGE_SECURITY_LABEL: int +PR_OBSOLETED_IPMS: int +PR_ORIGINALLY_INTENDED_RECIPIENT_NAME: int +PR_ORIGINAL_EITS: int +PR_ORIGINATOR_CERTIFICATE: int +PR_ORIGINATOR_DELIVERY_REPORT_REQUESTED: int +PR_ORIGINATOR_RETURN_ADDRESS: int +PR_PARENT_KEY: int +PR_PRIORITY: int +PR_ORIGIN_CHECK: int +PR_PROOF_OF_SUBMISSION_REQUESTED: int +PR_READ_RECEIPT_REQUESTED: int +PR_RECEIPT_TIME: int +PR_RECIPIENT_REASSIGNMENT_PROHIBITED: int +PR_REDIRECTION_HISTORY: int +PR_RELATED_IPMS: int +PR_ORIGINAL_SENSITIVITY: int +PR_LANGUAGES: int +PR_LANGUAGES_W: int +PR_LANGUAGES_A: int +PR_REPLY_TIME: int +PR_REPORT_TAG: int +PR_REPORT_TIME: int +PR_RETURNED_IPM: int +PR_SECURITY: int +PR_INCOMPLETE_COPY: int +PR_SENSITIVITY: int +PR_SUBJECT: int +PR_SUBJECT_W: int +PR_SUBJECT_A: int +PR_SUBJECT_IPM: int +PR_CLIENT_SUBMIT_TIME: int +PR_REPORT_NAME: int +PR_REPORT_NAME_W: int +PR_REPORT_NAME_A: int +PR_SENT_REPRESENTING_SEARCH_KEY: int +PR_X400_CONTENT_TYPE: int +PR_SUBJECT_PREFIX: int +PR_SUBJECT_PREFIX_W: int +PR_SUBJECT_PREFIX_A: int +PR_NON_RECEIPT_REASON: int +PR_RECEIVED_BY_ENTRYID: int +PR_RECEIVED_BY_NAME: int +PR_RECEIVED_BY_NAME_W: int +PR_RECEIVED_BY_NAME_A: int +PR_SENT_REPRESENTING_ENTRYID: int +PR_SENT_REPRESENTING_NAME: int +PR_SENT_REPRESENTING_NAME_W: int +PR_SENT_REPRESENTING_NAME_A: int +PR_RCVD_REPRESENTING_ENTRYID: int +PR_RCVD_REPRESENTING_NAME: int +PR_RCVD_REPRESENTING_NAME_W: int +PR_RCVD_REPRESENTING_NAME_A: int +PR_REPORT_ENTRYID: int +PR_READ_RECEIPT_ENTRYID: int +PR_MESSAGE_SUBMISSION_ID: int +PR_PROVIDER_SUBMIT_TIME: int +PR_ORIGINAL_SUBJECT: int +PR_ORIGINAL_SUBJECT_W: int +PR_ORIGINAL_SUBJECT_A: int +PR_DISC_VAL: int +PR_ORIG_MESSAGE_CLASS: int +PR_ORIG_MESSAGE_CLASS_W: int +PR_ORIG_MESSAGE_CLASS_A: int +PR_ORIGINAL_AUTHOR_ENTRYID: int +PR_ORIGINAL_AUTHOR_NAME: int +PR_ORIGINAL_AUTHOR_NAME_W: int +PR_ORIGINAL_AUTHOR_NAME_A: int +PR_ORIGINAL_SUBMIT_TIME: int +PR_REPLY_RECIPIENT_ENTRIES: int +PR_REPLY_RECIPIENT_NAMES: int +PR_REPLY_RECIPIENT_NAMES_W: int +PR_REPLY_RECIPIENT_NAMES_A: int +PR_RECEIVED_BY_SEARCH_KEY: int +PR_RCVD_REPRESENTING_SEARCH_KEY: int +PR_READ_RECEIPT_SEARCH_KEY: int +PR_REPORT_SEARCH_KEY: int +PR_ORIGINAL_DELIVERY_TIME: int +PR_ORIGINAL_AUTHOR_SEARCH_KEY: int +PR_MESSAGE_TO_ME: int +PR_MESSAGE_CC_ME: int +PR_MESSAGE_RECIP_ME: int +PR_ORIGINAL_SENDER_NAME: int +PR_ORIGINAL_SENDER_NAME_W: int +PR_ORIGINAL_SENDER_NAME_A: int +PR_ORIGINAL_SENDER_ENTRYID: int +PR_ORIGINAL_SENDER_SEARCH_KEY: int +PR_ORIGINAL_SENT_REPRESENTING_NAME: int +PR_ORIGINAL_SENT_REPRESENTING_NAME_W: int +PR_ORIGINAL_SENT_REPRESENTING_NAME_A: int +PR_ORIGINAL_SENT_REPRESENTING_ENTRYID: int +PR_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY: int +PR_START_DATE: int +PR_END_DATE: int +PR_OWNER_APPT_ID: int +PR_RESPONSE_REQUESTED: int +PR_SENT_REPRESENTING_ADDRTYPE: int +PR_SENT_REPRESENTING_ADDRTYPE_W: int +PR_SENT_REPRESENTING_ADDRTYPE_A: int +PR_SENT_REPRESENTING_EMAIL_ADDRESS: int +PR_SENT_REPRESENTING_EMAIL_ADDRESS_W: int +PR_SENT_REPRESENTING_EMAIL_ADDRESS_A: int +PR_ORIGINAL_SENDER_ADDRTYPE: int +PR_ORIGINAL_SENDER_ADDRTYPE_W: int +PR_ORIGINAL_SENDER_ADDRTYPE_A: int +PR_ORIGINAL_SENDER_EMAIL_ADDRESS: int +PR_ORIGINAL_SENDER_EMAIL_ADDRESS_W: int +PR_ORIGINAL_SENDER_EMAIL_ADDRESS_A: int +PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE: int +PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE_W: int +PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE_A: int +PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS: int +PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS_W: int +PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS_A: int +PR_CONVERSATION_TOPIC: int +PR_CONVERSATION_TOPIC_W: int +PR_CONVERSATION_TOPIC_A: int +PR_CONVERSATION_INDEX: int +PR_ORIGINAL_DISPLAY_BCC: int +PR_ORIGINAL_DISPLAY_BCC_W: int +PR_ORIGINAL_DISPLAY_BCC_A: int +PR_ORIGINAL_DISPLAY_CC: int +PR_ORIGINAL_DISPLAY_CC_W: int +PR_ORIGINAL_DISPLAY_CC_A: int +PR_ORIGINAL_DISPLAY_TO: int +PR_ORIGINAL_DISPLAY_TO_W: int +PR_ORIGINAL_DISPLAY_TO_A: int +PR_RECEIVED_BY_ADDRTYPE: int +PR_RECEIVED_BY_ADDRTYPE_W: int +PR_RECEIVED_BY_ADDRTYPE_A: int +PR_RECEIVED_BY_EMAIL_ADDRESS: int +PR_RECEIVED_BY_EMAIL_ADDRESS_W: int +PR_RECEIVED_BY_EMAIL_ADDRESS_A: int +PR_RCVD_REPRESENTING_ADDRTYPE: int +PR_RCVD_REPRESENTING_ADDRTYPE_W: int +PR_RCVD_REPRESENTING_ADDRTYPE_A: int +PR_RCVD_REPRESENTING_EMAIL_ADDRESS: int +PR_RCVD_REPRESENTING_EMAIL_ADDRESS_W: int +PR_RCVD_REPRESENTING_EMAIL_ADDRESS_A: int +PR_ORIGINAL_AUTHOR_ADDRTYPE: int +PR_ORIGINAL_AUTHOR_ADDRTYPE_W: int +PR_ORIGINAL_AUTHOR_ADDRTYPE_A: int +PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS: int +PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS_W: int +PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS_A: int +PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE: int +PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE_W: int +PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE_A: int +PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS: int +PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS_W: int +PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS_A: int +PR_TRANSPORT_MESSAGE_HEADERS: int +PR_TRANSPORT_MESSAGE_HEADERS_W: int +PR_TRANSPORT_MESSAGE_HEADERS_A: int +PR_DELEGATION: int +PR_TNEF_CORRELATION_KEY: int +PR_BODY: int +PR_BODY_W: int +PR_BODY_A: int +PR_BODY_HTML: int +PR_BODY_HTML_W: int +PR_BODY_HTML_A: int +PR_REPORT_TEXT: int +PR_REPORT_TEXT_W: int +PR_REPORT_TEXT_A: int +PR_ORIGINATOR_AND_DL_EXPANSION_HISTORY: int +PR_REPORTING_DL_NAME: int +PR_REPORTING_MTA_CERTIFICATE: int +PR_RTF_SYNC_BODY_CRC: int +PR_RTF_SYNC_BODY_COUNT: int +PR_RTF_SYNC_BODY_TAG: int +PR_RTF_SYNC_BODY_TAG_W: int +PR_RTF_SYNC_BODY_TAG_A: int +PR_RTF_COMPRESSED: int +PR_RTF_SYNC_PREFIX_COUNT: int +PR_RTF_SYNC_TRAILING_COUNT: int +PR_ORIGINALLY_INTENDED_RECIP_ENTRYID: int +PR_CONTENT_INTEGRITY_CHECK: int +PR_EXPLICIT_CONVERSION: int +PR_IPM_RETURN_REQUESTED: int +PR_MESSAGE_TOKEN: int +PR_NDR_REASON_CODE: int +PR_NDR_DIAG_CODE: int +PR_NON_RECEIPT_NOTIFICATION_REQUESTED: int +PR_DELIVERY_POINT: int +PR_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED: int +PR_ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT: int +PR_PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY: int +PR_PHYSICAL_DELIVERY_MODE: int +PR_PHYSICAL_DELIVERY_REPORT_REQUEST: int +PR_PHYSICAL_FORWARDING_ADDRESS: int +PR_PHYSICAL_FORWARDING_ADDRESS_REQUESTED: int +PR_PHYSICAL_FORWARDING_PROHIBITED: int +PR_PHYSICAL_RENDITION_ATTRIBUTES: int +PR_PROOF_OF_DELIVERY: int +PR_PROOF_OF_DELIVERY_REQUESTED: int +PR_RECIPIENT_CERTIFICATE: int +PR_RECIPIENT_NUMBER_FOR_ADVICE: int +PR_RECIPIENT_NUMBER_FOR_ADVICE_W: int +PR_RECIPIENT_NUMBER_FOR_ADVICE_A: int +PR_RECIPIENT_TYPE: int +PR_REGISTERED_MAIL_TYPE: int +PR_REPLY_REQUESTED: int +PR_REQUESTED_DELIVERY_METHOD: int +PR_SENDER_ENTRYID: int +PR_SENDER_NAME: int +PR_SENDER_NAME_W: int +PR_SENDER_NAME_A: int +PR_SUPPLEMENTARY_INFO: int +PR_SUPPLEMENTARY_INFO_W: int +PR_SUPPLEMENTARY_INFO_A: int +PR_TYPE_OF_MTS_USER: int +PR_SENDER_SEARCH_KEY: int +PR_SENDER_ADDRTYPE: int +PR_SENDER_ADDRTYPE_W: int +PR_SENDER_ADDRTYPE_A: int +PR_SENDER_EMAIL_ADDRESS: int +PR_SENDER_EMAIL_ADDRESS_W: int +PR_SENDER_EMAIL_ADDRESS_A: int +PR_CURRENT_VERSION: int +PR_DELETE_AFTER_SUBMIT: int +PR_DISPLAY_BCC: int +PR_DISPLAY_BCC_W: int +PR_DISPLAY_BCC_A: int +PR_DISPLAY_CC: int +PR_DISPLAY_CC_W: int +PR_DISPLAY_CC_A: int +PR_DISPLAY_TO: int +PR_DISPLAY_TO_W: int +PR_DISPLAY_TO_A: int +PR_PARENT_DISPLAY: int +PR_PARENT_DISPLAY_W: int +PR_PARENT_DISPLAY_A: int +PR_MESSAGE_DELIVERY_TIME: int +PR_MESSAGE_FLAGS: int +PR_MESSAGE_SIZE: int +PR_PARENT_ENTRYID: int +PR_SENTMAIL_ENTRYID: int +PR_CORRELATE: int +PR_CORRELATE_MTSID: int +PR_DISCRETE_VALUES: int +PR_RESPONSIBILITY: int +PR_SPOOLER_STATUS: int +PR_TRANSPORT_STATUS: int +PR_MESSAGE_RECIPIENTS: int +PR_MESSAGE_ATTACHMENTS: int +PR_SUBMIT_FLAGS: int +PR_RECIPIENT_STATUS: int +PR_TRANSPORT_KEY: int +PR_MSG_STATUS: int +PR_MESSAGE_DOWNLOAD_TIME: int +PR_CREATION_VERSION: int +PR_MODIFY_VERSION: int +PR_HASATTACH: int +PR_BODY_CRC: int +PR_NORMALIZED_SUBJECT: int +PR_NORMALIZED_SUBJECT_W: int +PR_NORMALIZED_SUBJECT_A: int +PR_RTF_IN_SYNC: int +PR_ATTACH_SIZE: int +PR_ATTACH_NUM: int +PR_PREPROCESS: int +PR_ORIGINATING_MTA_CERTIFICATE: int +PR_PROOF_OF_SUBMISSION: int +PR_ENTRYID: int +PR_OBJECT_TYPE: int +PR_ICON: int +PR_MINI_ICON: int +PR_STORE_ENTRYID: int +PR_STORE_RECORD_KEY: int +PR_RECORD_KEY: int +PR_MAPPING_SIGNATURE: int +PR_ACCESS_LEVEL: int +PR_INSTANCE_KEY: int +PR_ROW_TYPE: int +PR_ACCESS: int +PR_ROWID: int +PR_DISPLAY_NAME: int +PR_DISPLAY_NAME_W: int +PR_DISPLAY_NAME_A: int +PR_ADDRTYPE: int +PR_ADDRTYPE_W: int +PR_ADDRTYPE_A: int +PR_EMAIL_ADDRESS: int +PR_EMAIL_ADDRESS_W: int +PR_EMAIL_ADDRESS_A: int +PR_COMMENT: int +PR_COMMENT_W: int +PR_COMMENT_A: int +PR_DEPTH: int +PR_PROVIDER_DISPLAY: int +PR_PROVIDER_DISPLAY_W: int +PR_PROVIDER_DISPLAY_A: int +PR_CREATION_TIME: int +PR_LAST_MODIFICATION_TIME: int +PR_RESOURCE_FLAGS: int +PR_PROVIDER_DLL_NAME: int +PR_PROVIDER_DLL_NAME_W: int +PR_PROVIDER_DLL_NAME_A: int +PR_SEARCH_KEY: int +PR_PROVIDER_UID: int +PR_PROVIDER_ORDINAL: int +PR_FORM_VERSION: int +PR_FORM_VERSION_W: int +PR_FORM_VERSION_A: int +PR_FORM_CLSID: int +PR_FORM_CONTACT_NAME: int +PR_FORM_CONTACT_NAME_W: int +PR_FORM_CONTACT_NAME_A: int +PR_FORM_CATEGORY: int +PR_FORM_CATEGORY_W: int +PR_FORM_CATEGORY_A: int +PR_FORM_CATEGORY_SUB: int +PR_FORM_CATEGORY_SUB_W: int +PR_FORM_CATEGORY_SUB_A: int +PR_FORM_HOST_MAP: int +PR_FORM_HIDDEN: int +PR_FORM_DESIGNER_NAME: int +PR_FORM_DESIGNER_NAME_W: int +PR_FORM_DESIGNER_NAME_A: int +PR_FORM_DESIGNER_GUID: int +PR_FORM_MESSAGE_BEHAVIOR: int +PR_DEFAULT_STORE: int +PR_STORE_SUPPORT_MASK: int +PR_STORE_STATE: int +PR_IPM_SUBTREE_SEARCH_KEY: int +PR_IPM_OUTBOX_SEARCH_KEY: int +PR_IPM_WASTEBASKET_SEARCH_KEY: int +PR_IPM_SENTMAIL_SEARCH_KEY: int +PR_MDB_PROVIDER: int +PR_RECEIVE_FOLDER_SETTINGS: int +PR_VALID_FOLDER_MASK: int +PR_IPM_SUBTREE_ENTRYID: int +PR_IPM_OUTBOX_ENTRYID: int +PR_IPM_WASTEBASKET_ENTRYID: int +PR_IPM_SENTMAIL_ENTRYID: int +PR_VIEWS_ENTRYID: int +PR_COMMON_VIEWS_ENTRYID: int +PR_FINDER_ENTRYID: int +PR_CONTAINER_FLAGS: int +PR_FOLDER_TYPE: int +PR_CONTENT_COUNT: int +PR_CONTENT_UNREAD: int +PR_CREATE_TEMPLATES: int +PR_DETAILS_TABLE: int +PR_SEARCH: int +PR_SELECTABLE: int +PR_SUBFOLDERS: int +PR_STATUS: int +PR_ANR: int +PR_ANR_W: int +PR_ANR_A: int +PR_CONTENTS_SORT_ORDER: int +PR_CONTAINER_HIERARCHY: int +PR_CONTAINER_CONTENTS: int +PR_FOLDER_ASSOCIATED_CONTENTS: int +PR_DEF_CREATE_DL: int +PR_DEF_CREATE_MAILUSER: int +PR_CONTAINER_CLASS: int +PR_CONTAINER_CLASS_W: int +PR_CONTAINER_CLASS_A: int +PR_CONTAINER_MODIFY_VERSION: int +PR_AB_PROVIDER_ID: int +PR_DEFAULT_VIEW_ENTRYID: int +PR_ASSOC_CONTENT_COUNT: int +PR_ATTACHMENT_X400_PARAMETERS: int +PR_ATTACH_DATA_OBJ: int +PR_ATTACH_DATA_BIN: int +PR_ATTACH_ENCODING: int +PR_ATTACH_EXTENSION: int +PR_ATTACH_EXTENSION_W: int +PR_ATTACH_EXTENSION_A: int +PR_ATTACH_FILENAME: int +PR_ATTACH_FILENAME_W: int +PR_ATTACH_FILENAME_A: int +PR_ATTACH_METHOD: int +PR_ATTACH_LONG_FILENAME: int +PR_ATTACH_LONG_FILENAME_W: int +PR_ATTACH_LONG_FILENAME_A: int +PR_ATTACH_PATHNAME: int +PR_ATTACH_PATHNAME_W: int +PR_ATTACH_PATHNAME_A: int +PR_ATTACH_RENDERING: int +PR_ATTACH_TAG: int +PR_RENDERING_POSITION: int +PR_ATTACH_TRANSPORT_NAME: int +PR_ATTACH_TRANSPORT_NAME_W: int +PR_ATTACH_TRANSPORT_NAME_A: int +PR_ATTACH_LONG_PATHNAME: int +PR_ATTACH_LONG_PATHNAME_W: int +PR_ATTACH_LONG_PATHNAME_A: int +PR_ATTACH_MIME_TAG: int +PR_ATTACH_MIME_TAG_W: int +PR_ATTACH_MIME_TAG_A: int +PR_ATTACH_ADDITIONAL_INFO: int +PR_DISPLAY_TYPE: int +PR_TEMPLATEID: int +PR_PRIMARY_CAPABILITY: int +PR_7BIT_DISPLAY_NAME: int +PR_ACCOUNT: int +PR_ACCOUNT_W: int +PR_ACCOUNT_A: int +PR_ALTERNATE_RECIPIENT: int +PR_CALLBACK_TELEPHONE_NUMBER: int +PR_CALLBACK_TELEPHONE_NUMBER_W: int +PR_CALLBACK_TELEPHONE_NUMBER_A: int +PR_CONVERSION_PROHIBITED: int +PR_DISCLOSE_RECIPIENTS: int +PR_GENERATION: int +PR_GENERATION_W: int +PR_GENERATION_A: int +PR_GIVEN_NAME: int +PR_GIVEN_NAME_W: int +PR_GIVEN_NAME_A: int +PR_GOVERNMENT_ID_NUMBER: int +PR_GOVERNMENT_ID_NUMBER_W: int +PR_GOVERNMENT_ID_NUMBER_A: int +PR_BUSINESS_TELEPHONE_NUMBER: int +PR_BUSINESS_TELEPHONE_NUMBER_W: int +PR_BUSINESS_TELEPHONE_NUMBER_A: int +PR_OFFICE_TELEPHONE_NUMBER: int +PR_OFFICE_TELEPHONE_NUMBER_W: int +PR_OFFICE_TELEPHONE_NUMBER_A: int +PR_HOME_TELEPHONE_NUMBER: int +PR_HOME_TELEPHONE_NUMBER_W: int +PR_HOME_TELEPHONE_NUMBER_A: int +PR_INITIALS: int +PR_INITIALS_W: int +PR_INITIALS_A: int +PR_KEYWORD: int +PR_KEYWORD_W: int +PR_KEYWORD_A: int +PR_LANGUAGE: int +PR_LANGUAGE_W: int +PR_LANGUAGE_A: int +PR_LOCATION: int +PR_LOCATION_W: int +PR_LOCATION_A: int +PR_MAIL_PERMISSION: int +PR_MHS_COMMON_NAME: int +PR_MHS_COMMON_NAME_W: int +PR_MHS_COMMON_NAME_A: int +PR_ORGANIZATIONAL_ID_NUMBER: int +PR_ORGANIZATIONAL_ID_NUMBER_W: int +PR_ORGANIZATIONAL_ID_NUMBER_A: int +PR_SURNAME: int +PR_SURNAME_W: int +PR_SURNAME_A: int +PR_ORIGINAL_ENTRYID: int +PR_ORIGINAL_DISPLAY_NAME: int +PR_ORIGINAL_DISPLAY_NAME_W: int +PR_ORIGINAL_DISPLAY_NAME_A: int +PR_ORIGINAL_SEARCH_KEY: int +PR_POSTAL_ADDRESS: int +PR_POSTAL_ADDRESS_W: int +PR_POSTAL_ADDRESS_A: int +PR_COMPANY_NAME: int +PR_COMPANY_NAME_W: int +PR_COMPANY_NAME_A: int +PR_TITLE: int +PR_TITLE_W: int +PR_TITLE_A: int +PR_DEPARTMENT_NAME: int +PR_DEPARTMENT_NAME_W: int +PR_DEPARTMENT_NAME_A: int +PR_OFFICE_LOCATION: int +PR_OFFICE_LOCATION_W: int +PR_OFFICE_LOCATION_A: int +PR_PRIMARY_TELEPHONE_NUMBER: int +PR_PRIMARY_TELEPHONE_NUMBER_W: int +PR_PRIMARY_TELEPHONE_NUMBER_A: int +PR_BUSINESS2_TELEPHONE_NUMBER: int +PR_BUSINESS2_TELEPHONE_NUMBER_W: int +PR_BUSINESS2_TELEPHONE_NUMBER_A: int +PR_OFFICE2_TELEPHONE_NUMBER: int +PR_OFFICE2_TELEPHONE_NUMBER_W: int +PR_OFFICE2_TELEPHONE_NUMBER_A: int +PR_MOBILE_TELEPHONE_NUMBER: int +PR_MOBILE_TELEPHONE_NUMBER_W: int +PR_MOBILE_TELEPHONE_NUMBER_A: int +PR_CELLULAR_TELEPHONE_NUMBER: int +PR_CELLULAR_TELEPHONE_NUMBER_W: int +PR_CELLULAR_TELEPHONE_NUMBER_A: int +PR_RADIO_TELEPHONE_NUMBER: int +PR_RADIO_TELEPHONE_NUMBER_W: int +PR_RADIO_TELEPHONE_NUMBER_A: int +PR_CAR_TELEPHONE_NUMBER: int +PR_CAR_TELEPHONE_NUMBER_W: int +PR_CAR_TELEPHONE_NUMBER_A: int +PR_OTHER_TELEPHONE_NUMBER: int +PR_OTHER_TELEPHONE_NUMBER_W: int +PR_OTHER_TELEPHONE_NUMBER_A: int +PR_TRANSMITABLE_DISPLAY_NAME: int +PR_TRANSMITABLE_DISPLAY_NAME_W: int +PR_TRANSMITABLE_DISPLAY_NAME_A: int +PR_PAGER_TELEPHONE_NUMBER: int +PR_PAGER_TELEPHONE_NUMBER_W: int +PR_PAGER_TELEPHONE_NUMBER_A: int +PR_BEEPER_TELEPHONE_NUMBER: int +PR_BEEPER_TELEPHONE_NUMBER_W: int +PR_BEEPER_TELEPHONE_NUMBER_A: int +PR_USER_CERTIFICATE: int +PR_PRIMARY_FAX_NUMBER: int +PR_PRIMARY_FAX_NUMBER_W: int +PR_PRIMARY_FAX_NUMBER_A: int +PR_BUSINESS_FAX_NUMBER: int +PR_BUSINESS_FAX_NUMBER_W: int +PR_BUSINESS_FAX_NUMBER_A: int +PR_HOME_FAX_NUMBER: int +PR_HOME_FAX_NUMBER_W: int +PR_HOME_FAX_NUMBER_A: int +PR_COUNTRY: int +PR_COUNTRY_W: int +PR_COUNTRY_A: int +PR_BUSINESS_ADDRESS_COUNTRY: int +PR_BUSINESS_ADDRESS_COUNTRY_W: int +PR_BUSINESS_ADDRESS_COUNTRY_A: int +PR_LOCALITY: int +PR_LOCALITY_W: int +PR_LOCALITY_A: int +PR_BUSINESS_ADDRESS_CITY: int +PR_BUSINESS_ADDRESS_CITY_W: int +PR_BUSINESS_ADDRESS_CITY_A: int +PR_STATE_OR_PROVINCE: int +PR_STATE_OR_PROVINCE_W: int +PR_STATE_OR_PROVINCE_A: int +PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE: int +PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE_W: int +PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE_A: int +PR_STREET_ADDRESS: int +PR_STREET_ADDRESS_W: int +PR_STREET_ADDRESS_A: int +PR_BUSINESS_ADDRESS_STREET: int +PR_BUSINESS_ADDRESS_STREET_W: int +PR_BUSINESS_ADDRESS_STREET_A: int +PR_POSTAL_CODE: int +PR_POSTAL_CODE_W: int +PR_POSTAL_CODE_A: int +PR_BUSINESS_ADDRESS_POSTAL_CODE: int +PR_BUSINESS_ADDRESS_POSTAL_CODE_W: int +PR_BUSINESS_ADDRESS_POSTAL_CODE_A: int +PR_POST_OFFICE_BOX: int +PR_POST_OFFICE_BOX_W: int +PR_POST_OFFICE_BOX_A: int +PR_BUSINESS_ADDRESS_POST_OFFICE_BOX: int +PR_BUSINESS_ADDRESS_POST_OFFICE_BOX_W: int +PR_BUSINESS_ADDRESS_POST_OFFICE_BOX_A: int +PR_TELEX_NUMBER: int +PR_TELEX_NUMBER_W: int +PR_TELEX_NUMBER_A: int +PR_ISDN_NUMBER: int +PR_ISDN_NUMBER_W: int +PR_ISDN_NUMBER_A: int +PR_ASSISTANT_TELEPHONE_NUMBER: int +PR_ASSISTANT_TELEPHONE_NUMBER_W: int +PR_ASSISTANT_TELEPHONE_NUMBER_A: int +PR_HOME2_TELEPHONE_NUMBER: int +PR_HOME2_TELEPHONE_NUMBER_W: int +PR_HOME2_TELEPHONE_NUMBER_A: int +PR_ASSISTANT: int +PR_ASSISTANT_W: int +PR_ASSISTANT_A: int +PR_SEND_RICH_INFO: int +PR_WEDDING_ANNIVERSARY: int +PR_BIRTHDAY: int +PR_HOBBIES: int +PR_HOBBIES_W: int +PR_HOBBIES_A: int +PR_MIDDLE_NAME: int +PR_MIDDLE_NAME_W: int +PR_MIDDLE_NAME_A: int +PR_DISPLAY_NAME_PREFIX: int +PR_DISPLAY_NAME_PREFIX_W: int +PR_DISPLAY_NAME_PREFIX_A: int +PR_PROFESSION: int +PR_PROFESSION_W: int +PR_PROFESSION_A: int +PR_PREFERRED_BY_NAME: int +PR_PREFERRED_BY_NAME_W: int +PR_PREFERRED_BY_NAME_A: int +PR_SPOUSE_NAME: int +PR_SPOUSE_NAME_W: int +PR_SPOUSE_NAME_A: int +PR_COMPUTER_NETWORK_NAME: int +PR_COMPUTER_NETWORK_NAME_W: int +PR_COMPUTER_NETWORK_NAME_A: int +PR_CUSTOMER_ID: int +PR_CUSTOMER_ID_W: int +PR_CUSTOMER_ID_A: int +PR_TTYTDD_PHONE_NUMBER: int +PR_TTYTDD_PHONE_NUMBER_W: int +PR_TTYTDD_PHONE_NUMBER_A: int +PR_FTP_SITE: int +PR_FTP_SITE_W: int +PR_FTP_SITE_A: int +PR_GENDER: int +PR_MANAGER_NAME: int +PR_MANAGER_NAME_W: int +PR_MANAGER_NAME_A: int +PR_NICKNAME: int +PR_NICKNAME_W: int +PR_NICKNAME_A: int +PR_PERSONAL_HOME_PAGE: int +PR_PERSONAL_HOME_PAGE_W: int +PR_PERSONAL_HOME_PAGE_A: int +PR_BUSINESS_HOME_PAGE: int +PR_BUSINESS_HOME_PAGE_W: int +PR_BUSINESS_HOME_PAGE_A: int +PR_CONTACT_VERSION: int +PR_CONTACT_ENTRYIDS: int +PR_CONTACT_ADDRTYPES: int +PR_CONTACT_ADDRTYPES_W: int +PR_CONTACT_ADDRTYPES_A: int +PR_CONTACT_DEFAULT_ADDRESS_INDEX: int +PR_CONTACT_EMAIL_ADDRESSES: int +PR_CONTACT_EMAIL_ADDRESSES_W: int +PR_CONTACT_EMAIL_ADDRESSES_A: int +PR_COMPANY_MAIN_PHONE_NUMBER: int +PR_COMPANY_MAIN_PHONE_NUMBER_W: int +PR_COMPANY_MAIN_PHONE_NUMBER_A: int +PR_CHILDRENS_NAMES: int +PR_CHILDRENS_NAMES_W: int +PR_CHILDRENS_NAMES_A: int +PR_HOME_ADDRESS_CITY: int +PR_HOME_ADDRESS_CITY_W: int +PR_HOME_ADDRESS_CITY_A: int +PR_HOME_ADDRESS_COUNTRY: int +PR_HOME_ADDRESS_COUNTRY_W: int +PR_HOME_ADDRESS_COUNTRY_A: int +PR_HOME_ADDRESS_POSTAL_CODE: int +PR_HOME_ADDRESS_POSTAL_CODE_W: int +PR_HOME_ADDRESS_POSTAL_CODE_A: int +PR_HOME_ADDRESS_STATE_OR_PROVINCE: int +PR_HOME_ADDRESS_STATE_OR_PROVINCE_W: int +PR_HOME_ADDRESS_STATE_OR_PROVINCE_A: int +PR_HOME_ADDRESS_STREET: int +PR_HOME_ADDRESS_STREET_W: int +PR_HOME_ADDRESS_STREET_A: int +PR_HOME_ADDRESS_POST_OFFICE_BOX: int +PR_HOME_ADDRESS_POST_OFFICE_BOX_W: int +PR_HOME_ADDRESS_POST_OFFICE_BOX_A: int +PR_OTHER_ADDRESS_CITY: int +PR_OTHER_ADDRESS_CITY_W: int +PR_OTHER_ADDRESS_CITY_A: int +PR_OTHER_ADDRESS_COUNTRY: int +PR_OTHER_ADDRESS_COUNTRY_W: int +PR_OTHER_ADDRESS_COUNTRY_A: int +PR_OTHER_ADDRESS_POSTAL_CODE: int +PR_OTHER_ADDRESS_POSTAL_CODE_W: int +PR_OTHER_ADDRESS_POSTAL_CODE_A: int +PR_OTHER_ADDRESS_STATE_OR_PROVINCE: int +PR_OTHER_ADDRESS_STATE_OR_PROVINCE_W: int +PR_OTHER_ADDRESS_STATE_OR_PROVINCE_A: int +PR_OTHER_ADDRESS_STREET: int +PR_OTHER_ADDRESS_STREET_W: int +PR_OTHER_ADDRESS_STREET_A: int +PR_OTHER_ADDRESS_POST_OFFICE_BOX: int +PR_OTHER_ADDRESS_POST_OFFICE_BOX_W: int +PR_OTHER_ADDRESS_POST_OFFICE_BOX_A: int +PR_STORE_PROVIDERS: int +PR_AB_PROVIDERS: int +PR_TRANSPORT_PROVIDERS: int +PR_DEFAULT_PROFILE: int +PR_AB_SEARCH_PATH: int +PR_AB_DEFAULT_DIR: int +PR_AB_DEFAULT_PAB: int +PR_FILTERING_HOOKS: int +PR_SERVICE_NAME: int +PR_SERVICE_NAME_W: int +PR_SERVICE_NAME_A: int +PR_SERVICE_DLL_NAME: int +PR_SERVICE_DLL_NAME_W: int +PR_SERVICE_DLL_NAME_A: int +PR_SERVICE_ENTRY_NAME: int +PR_SERVICE_UID: int +PR_SERVICE_EXTRA_UIDS: int +PR_SERVICES: int +PR_SERVICE_SUPPORT_FILES: int +PR_SERVICE_SUPPORT_FILES_W: int +PR_SERVICE_SUPPORT_FILES_A: int +PR_SERVICE_DELETE_FILES: int +PR_SERVICE_DELETE_FILES_W: int +PR_SERVICE_DELETE_FILES_A: int +PR_AB_SEARCH_PATH_UPDATE: int +PR_PROFILE_NAME: int +PR_PROFILE_NAME_A: int +PR_PROFILE_NAME_W: int +PR_IDENTITY_DISPLAY: int +PR_IDENTITY_DISPLAY_W: int +PR_IDENTITY_DISPLAY_A: int +PR_IDENTITY_ENTRYID: int +PR_RESOURCE_METHODS: int +PR_RESOURCE_TYPE: int +PR_STATUS_CODE: int +PR_IDENTITY_SEARCH_KEY: int +PR_OWN_STORE_ENTRYID: int +PR_RESOURCE_PATH: int +PR_RESOURCE_PATH_W: int +PR_RESOURCE_PATH_A: int +PR_STATUS_STRING: int +PR_STATUS_STRING_W: int +PR_STATUS_STRING_A: int +PR_X400_DEFERRED_DELIVERY_CANCEL: int +PR_HEADER_FOLDER_ENTRYID: int +PR_REMOTE_PROGRESS: int +PR_REMOTE_PROGRESS_TEXT: int +PR_REMOTE_PROGRESS_TEXT_W: int +PR_REMOTE_PROGRESS_TEXT_A: int +PR_REMOTE_VALIDATE_OK: int +PR_CONTROL_FLAGS: int +PR_CONTROL_STRUCTURE: int +PR_CONTROL_TYPE: int +PR_DELTAX: int +PR_DELTAY: int +PR_XPOS: int +PR_YPOS: int +PR_CONTROL_ID: int +PR_INITIAL_DETAILS_PANE: int +PROP_ID_SECURE_MIN: int +PROP_ID_SECURE_MAX: int +pidExchangeXmitReservedMin: int +pidExchangeNonXmitReservedMin: int +pidProfileMin: int +pidStoreMin: int +pidFolderMin: int +pidMessageReadOnlyMin: int +pidMessageWriteableMin: int +pidAttachReadOnlyMin: int +pidSpecialMin: int +pidAdminMin: int +pidSecureProfileMin: int +PR_PROFILE_VERSION: int +PR_PROFILE_CONFIG_FLAGS: int +PR_PROFILE_HOME_SERVER: int +PR_PROFILE_HOME_SERVER_DN: int +PR_PROFILE_HOME_SERVER_ADDRS: int +PR_PROFILE_USER: int +PR_PROFILE_CONNECT_FLAGS: int +PR_PROFILE_TRANSPORT_FLAGS: int +PR_PROFILE_UI_STATE: int +PR_PROFILE_UNRESOLVED_NAME: int +PR_PROFILE_UNRESOLVED_SERVER: int +PR_PROFILE_BINDING_ORDER: int +PR_PROFILE_MAX_RESTRICT: int +PR_PROFILE_AB_FILES_PATH: int +PR_PROFILE_OFFLINE_STORE_PATH: int +PR_PROFILE_OFFLINE_INFO: int +PR_PROFILE_ADDR_INFO: int +PR_PROFILE_OPTIONS_DATA: int +PR_PROFILE_SECURE_MAILBOX: int +PR_DISABLE_WINSOCK: int +PR_OST_ENCRYPTION: int +PR_PROFILE_OPEN_FLAGS: int +PR_PROFILE_TYPE: int +PR_PROFILE_MAILBOX: int +PR_PROFILE_SERVER: int +PR_PROFILE_SERVER_DN: int +PR_PROFILE_FAVFLD_DISPLAY_NAME: int +PR_PROFILE_FAVFLD_COMMENT: int +PR_PROFILE_ALLPUB_DISPLAY_NAME: int +PR_PROFILE_ALLPUB_COMMENT: int +OSTF_NO_ENCRYPTION: int +OSTF_COMPRESSABLE_ENCRYPTION: int +OSTF_BEST_ENCRYPTION: int +PR_NON_IPM_SUBTREE_ENTRYID: int +PR_EFORMS_REGISTRY_ENTRYID: int +PR_SPLUS_FREE_BUSY_ENTRYID: int +PR_OFFLINE_ADDRBOOK_ENTRYID: int +PR_EFORMS_FOR_LOCALE_ENTRYID: int +PR_FREE_BUSY_FOR_LOCAL_SITE_ENTRYID: int +PR_ADDRBOOK_FOR_LOCAL_SITE_ENTRYID: int +PR_OFFLINE_MESSAGE_ENTRYID: int +PR_IPM_FAVORITES_ENTRYID: int +PR_IPM_PUBLIC_FOLDERS_ENTRYID: int +PR_GW_MTSIN_ENTRYID: int +PR_GW_MTSOUT_ENTRYID: int +PR_TRANSFER_ENABLED: int +PR_TEST_LINE_SPEED: int +PR_HIERARCHY_SYNCHRONIZER: int +PR_CONTENTS_SYNCHRONIZER: int +PR_COLLECTOR: int +PR_FAST_TRANSFER: int +PR_STORE_OFFLINE: int +PR_IN_TRANSIT: int +PR_REPLICATION_STYLE: int +PR_REPLICATION_SCHEDULE: int +PR_REPLICATION_MESSAGE_PRIORITY: int +PR_OVERALL_MSG_AGE_LIMIT: int +PR_REPLICATION_ALWAYS_INTERVAL: int +PR_REPLICATION_MSG_SIZE: int +STYLE_ALWAYS_INTERVAL_DEFAULT: int +REPLICATION_MESSAGE_SIZE_LIMIT_DEFAULT: int +STYLE_NEVER: int +STYLE_NORMAL: int +STYLE_ALWAYS: int +STYLE_DEFAULT: int +PR_SOURCE_KEY: int +PR_PARENT_SOURCE_KEY: int +PR_CHANGE_KEY: int +PR_PREDECESSOR_CHANGE_LIST: int +PR_FOLDER_CHILD_COUNT: int +PR_RIGHTS: int +PR_ACL_TABLE: int +PR_RULES_TABLE: int +PR_HAS_RULES: int +PR_ADDRESS_BOOK_ENTRYID: int +PR_ACL_DATA: int +PR_RULES_DATA: int +PR_FOLDER_DESIGN_FLAGS: int +PR_DESIGN_IN_PROGRESS: int +PR_SECURE_ORIGINATION: int +PR_PUBLISH_IN_ADDRESS_BOOK: int +PR_RESOLVE_METHOD: int +PR_ADDRESS_BOOK_DISPLAY_NAME: int +PR_EFORMS_LOCALE_ID: int +PR_REPLICA_LIST: int +PR_OVERALL_AGE_LIMIT: int +RESOLVE_METHOD_DEFAULT: int +RESOLVE_METHOD_LAST_WRITER_WINS: int +RESOLVE_METHOD_NO_CONFLICT_NOTIFICATION: int +PR_PUBLIC_FOLDER_ENTRYID: int +PR_HAS_NAMED_PROPERTIES: int +PR_CREATOR_NAME: int +PR_CREATOR_ENTRYID: int +PR_LAST_MODIFIER_NAME: int +PR_LAST_MODIFIER_ENTRYID: int +PR_HAS_DAMS: int +PR_RULE_TRIGGER_HISTORY: int +PR_MOVE_TO_STORE_ENTRYID: int +PR_MOVE_TO_FOLDER_ENTRYID: int +PR_REPLICA_SERVER: int +PR_DEFERRED_SEND_NUMBER: int +PR_DEFERRED_SEND_UNITS: int +PR_EXPIRY_NUMBER: int +PR_EXPIRY_UNITS: int +PR_DEFERRED_SEND_TIME: int +PR_GW_ADMIN_OPERATIONS: int +PR_P1_CONTENT: int +PR_P1_CONTENT_TYPE: int +PR_CLIENT_ACTIONS: int +PR_DAM_ORIGINAL_ENTRYID: int +PR_DAM_BACK_PATCHED: int +PR_RULE_ERROR: int +PR_RULE_ACTION_TYPE: int +PR_RULE_ACTION_NUMBER: int +PR_RULE_FOLDER_ENTRYID: int +PR_CONFLICT_ENTRYID: int +PR_MESSAGE_LOCALE_ID: int +PR_STORAGE_QUOTA_LIMIT: int +PR_EXCESS_STORAGE_USED: int +PR_SVR_GENERATING_QUOTA_MSG: int +PR_DELEGATED_BY_RULE: int +MSGSTATUS_IN_CONFLICT: int +PR_IN_CONFLICT: int +PR_LONGTERM_ENTRYID_FROM_TABLE: int +PR_ORIGINATOR_NAME: int +PR_ORIGINATOR_ADDR: int +PR_ORIGINATOR_ADDRTYPE: int +PR_ORIGINATOR_ENTRYID: int +PR_ARRIVAL_TIME: int +PR_TRACE_INFO: int +PR_INTERNAL_TRACE_INFO: int +PR_SUBJECT_TRACE_INFO: int +PR_RECIPIENT_NUMBER: int +PR_MTS_SUBJECT_ID: int +PR_REPORT_DESTINATION_NAME: int +PR_REPORT_DESTINATION_ENTRYID: int +PR_CONTENT_SEARCH_KEY: int +PR_FOREIGN_ID: int +PR_FOREIGN_REPORT_ID: int +PR_FOREIGN_SUBJECT_ID: int +PR_MTS_ID: int +PR_MTS_REPORT_ID: int +PR_FOLDER_FLAGS: int +PR_LAST_ACCESS_TIME: int +PR_RESTRICTION_COUNT: int +PR_CATEG_COUNT: int +PR_CACHED_COLUMN_COUNT: int +PR_NORMAL_MSG_W_ATTACH_COUNT: int +PR_ASSOC_MSG_W_ATTACH_COUNT: int +PR_RECIPIENT_ON_NORMAL_MSG_COUNT: int +PR_RECIPIENT_ON_ASSOC_MSG_COUNT: int +PR_ATTACH_ON_NORMAL_MSG_COUNT: int +PR_ATTACH_ON_ASSOC_MSG_COUNT: int +PR_NORMAL_MESSAGE_SIZE: int +PR_NORMAL_MESSAGE_SIZE_EXTENDED: int +PR_ASSOC_MESSAGE_SIZE: int +PR_ASSOC_MESSAGE_SIZE_EXTENDED: int +PR_FOLDER_PATHNAME: int +PR_OWNER_COUNT: int +PR_CONTACT_COUNT: int +PR_MESSAGE_SIZE_EXTENDED: int +PR_USERFIELDS: int +PR_FORCE_USE_ENTRYID_SERVER: int +PR_PROFILE_MDB_DN: int +PST_EXTERN_PROPID_BASE: int +PR_PST_PATH: int +PR_PST_PATH_W: int +PR_PST_PATH_A: int +PR_PST_REMEMBER_PW: int +PR_PST_ENCRYPTION: int +PR_PST_PW_SZ_OLD: int +PR_PST_PW_SZ_OLD_W: int +PR_PST_PW_SZ_OLD_A: int +PR_PST_PW_SZ_NEW: int +PR_PST_PW_SZ_NEW_W: int +PR_PST_PW_SZ_NEW_A: int diff --git a/stubs/pywin32/win32comext/mapi/mapiutil.pyi b/stubs/pywin32/win32comext/mapi/mapiutil.pyi new file mode 100644 index 000000000000..a595c89686cb --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/mapiutil.pyi @@ -0,0 +1,15 @@ +prTable: dict[int, str] + +def GetPropTagName(pt): ... + +mapiErrorTable: dict[int, str] + +def GetScodeString(hr): ... + +ptTable: dict[int, str] + +def GetMapiTypeName(propType, rawType: bool = ...): ... +def GetProperties(obj, propList): ... +def GetAllProperties(obj, make_tag_names: bool = ...): ... +def SetPropertyValue(obj, prop, val) -> None: ... +def SetProperties(msg, propDict) -> None: ... diff --git a/stubs/pywin32/win32comext/propsys/__init__.pyi b/stubs/pywin32/win32comext/propsys/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/propsys/propsys.pyi b/stubs/pywin32/win32comext/propsys/propsys.pyi new file mode 100644 index 000000000000..090ef130f25b --- /dev/null +++ b/stubs/pywin32/win32comext/propsys/propsys.pyi @@ -0,0 +1,61 @@ +from typing import TypeAlias + +import _win32typing +from win32.lib.pywintypes import com_error + +error: TypeAlias = com_error # noqa: Y042 + +def PSGetItemPropertyHandler( + Item: _win32typing.PyIShellItem, riid: _win32typing.PyIID, ReadWrite: int, / +) -> _win32typing.PyIPropertyStore: ... +def PSGetPropertyDescription( + Key: _win32typing.PyPROPERTYKEY, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyDescription: ... +def PSGetPropertySystem(riid: _win32typing.PyIID, /) -> _win32typing.PyIPropertySystem: ... +def PSGetNameFromPropertyKey(Key: _win32typing.PyPROPERTYKEY, /) -> str: ... +def PSGetPropertyKeyFromName(Name, /) -> _win32typing.PyPROPERTYKEY: ... +def PSRegisterPropertySchema(filename, /) -> None: ... +def PSUnregisterPropertySchema(filename, /) -> None: ... +def SHGetPropertyStoreFromParsingName( + Path: str, BindCtx: _win32typing.PyIBindCtx | None = ..., Flags: int = ..., riid: _win32typing.PyIID | str = ..., / +) -> _win32typing.PyIPropertyStore: ... +def StgSerializePropVariant(propvar: _win32typing.PyPROPVARIANT, /): ... +def StgDeserializePropVariant(prop, /) -> _win32typing.PyPROPVARIANT: ... +def PSCreateMemoryPropertyStore(riid: _win32typing.PyIID, /) -> _win32typing.PyIPropertyStore: ... +def PSCreatePropertyStoreFromPropertySetStorage( + pss: _win32typing.PyIPropertySetStorage, Mode, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyStore: ... +def PSLookupPropertyHandlerCLSID(FilePath, /) -> _win32typing.PyIID: ... +def SHGetPropertyStoreForWindow(hwnd: int, riid: _win32typing.PyIID, /) -> _win32typing.PyIPropertyStore: ... +def PSGetPropertyFromPropertyStorage(ps, key: _win32typing.PyPROPERTYKEY, /) -> _win32typing.PyPROPVARIANT: ... +def PSGetNamedPropertyFromPropertyStorage(ps, name, /) -> _win32typing.PyPROPVARIANT: ... +def PSCreateSimplePropertyChange( + flags, key: _win32typing.PyPROPERTYKEY, val: _win32typing.PyPROPVARIANT, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyChange: ... +def PSCreatePropertyChangeArray() -> _win32typing.PyIPropertyChangeArray: ... +def SHSetDefaultProperties( + hwnd: int, + Item: _win32typing.PyIShellItem, + FileOpFlags: int = ..., + Sink: _win32typing.PyGFileOperationProgressSink | None = ..., + /, +) -> None: ... + +IID_IInitializeWithFile: _win32typing.PyIID +IID_IInitializeWithStream: _win32typing.PyIID +IID_INamedPropertyStore: _win32typing.PyIID +IID_IObjectWithPropertyKey: _win32typing.PyIID +IID_IPersistSerializedPropStorage: _win32typing.PyIID +IID_IPropertyChange: _win32typing.PyIID +IID_IPropertyChangeArray: _win32typing.PyIID +IID_IPropertyDescription: _win32typing.PyIID +IID_IPropertyDescriptionAliasInfo: _win32typing.PyIID +IID_IPropertyDescriptionList: _win32typing.PyIID +IID_IPropertyDescriptionSearchInfo: _win32typing.PyIID +IID_IPropertyEnumType: _win32typing.PyIID +IID_IPropertyEnumTypeList: _win32typing.PyIID +IID_IPropertyStore: _win32typing.PyIID +IID_IPropertyStoreCache: _win32typing.PyIID +IID_IPropertyStoreCapabilities: _win32typing.PyIID +IID_IPropertySystem: _win32typing.PyIID +PROPVARIANTType = _win32typing.PyPROPVARIANT diff --git a/stubs/pywin32/win32comext/propsys/pscon.pyi b/stubs/pywin32/win32comext/propsys/pscon.pyi new file mode 100644 index 000000000000..799bc0fa1382 --- /dev/null +++ b/stubs/pywin32/win32comext/propsys/pscon.pyi @@ -0,0 +1,695 @@ +from _typeshed import Incomplete + +PET_DISCRETEVALUE: int +PET_RANGEDVALUE: int +PET_DEFAULTVALUE: int +PET_ENDRANGE: int +PDTF_DEFAULT: int +PDTF_MULTIPLEVALUES: int +PDTF_ISINNATE: int +PDTF_ISGROUP: int +PDTF_CANGROUPBY: int +PDTF_CANSTACKBY: int +PDTF_ISTREEPROPERTY: int +PDTF_INCLUDEINFULLTEXTQUERY: int +PDTF_ISVIEWABLE: int +PDTF_ISQUERYABLE: int +PDTF_ISSYSTEMPROPERTY: int +PDTF_MASK_ALL: int +PDVF_DEFAULT: int +PDVF_CENTERALIGN: int +PDVF_RIGHTALIGN: int +PDVF_BEGINNEWGROUP: int +PDVF_FILLAREA: int +PDVF_SORTDESCENDING: int +PDVF_SHOWONLYIFPRESENT: int +PDVF_SHOWBYDEFAULT: int +PDVF_SHOWINPRIMARYLIST: int +PDVF_SHOWINSECONDARYLIST: int +PDVF_HIDELABEL: int +PDVF_HIDDEN: int +PDVF_CANWRAP: int +PDVF_MASK_ALL: int +PDDT_STRING: int +PDDT_NUMBER: int +PDDT_BOOLEAN: int +PDDT_DATETIME: int +PDDT_ENUMERATED: int +PDGR_DISCRETE: int +PDGR_ALPHANUMERIC: int +PDGR_SIZE: int +PDGR_DYNAMIC: int +PDGR_DATE: int +PDGR_PERCENT: int +PDGR_ENUMERATED: int +PDFF_DEFAULT: int +PDFF_PREFIXNAME: int +PDFF_FILENAME: int +PDFF_ALWAYSKB: int +PDFF_RESERVED_RIGHTTOLEFT: int +PDFF_SHORTTIME: int +PDFF_LONGTIME: int +PDFF_HIDETIME: int +PDFF_SHORTDATE: int +PDFF_LONGDATE: int +PDFF_HIDEDATE: int +PDFF_RELATIVEDATE: int +PDFF_USEEDITINVITATION: int +PDFF_READONLY: int +PDFF_NOAUTOREADINGORDER: int +PDSD_GENERAL: int +PDSD_A_Z: int +PDSD_LOWEST_HIGHEST: int +PDSD_SMALLEST_BIGGEST: int +PDSD_OLDEST_NEWEST: int +PDRDT_GENERAL: int +PDRDT_DATE: int +PDRDT_SIZE: int +PDRDT_COUNT: int +PDRDT_REVISION: int +PDRDT_LENGTH: int +PDRDT_DURATION: int +PDRDT_SPEED: int +PDRDT_RATE: int +PDRDT_RATING: int +PDRDT_PRIORITY: int +PDAT_DEFAULT: int +PDAT_FIRST: int +PDAT_SUM: int +PDAT_AVERAGE: int +PDAT_DATERANGE: int +PDAT_UNION: int +PDAT_MAX: int +PDAT_MIN: int +PDCOT_NONE: int +PDCOT_STRING: int +PDCOT_SIZE: int +PDCOT_DATETIME: int +PDCOT_BOOLEAN: int +PDCOT_NUMBER: int +PDSIF_DEFAULT: int +PDSIF_ININVERTEDINDEX: int +PDSIF_ISCOLUMN: int +PDSIF_ISCOLUMNSPARSE: int +PDCIT_NONE: int +PDCIT_ONDISK: int +PDCIT_INMEMORY: int +PDEF_ALL: int +PDEF_SYSTEM: int +PDEF_NONSYSTEM: int +PDEF_VIEWABLE: int +PDEF_QUERYABLE: int +PDEF_INFULLTEXTQUERY: int +PDEF_COLUMN: int +PSC_NORMAL: int +PSC_NOTINSOURCE: int +PSC_DIRTY: int +COP_IMPLICIT: int +COP_EQUAL: int +COP_NOTEQUAL: int +COP_LESSTHAN: int +COP_GREATERTHAN: int +COP_LESSTHANOREQUAL: int +COP_GREATERTHANOREQUAL: int +COP_VALUE_STARTSWITH: int +COP_VALUE_ENDSWITH: int +COP_VALUE_CONTAINS: int +COP_VALUE_NOTCONTAINS: int +COP_DOSWILDCARDS: int +COP_WORD_EQUAL: int +COP_WORD_STARTSWITH: int +COP_APPLICATION_SPECIFIC: int +FPSPS_READONLY: int +PKEY_PIDSTR_MAX: int +GUIDSTRING_MAX: Incomplete +PKEYSTR_MAX: Incomplete +PKEY_Audio_ChannelCount: Incomplete +PKEY_Audio_Compression: Incomplete +PKEY_Audio_EncodingBitrate: Incomplete +PKEY_Audio_Format: Incomplete +PKEY_Audio_IsVariableBitRate: Incomplete +PKEY_Audio_PeakValue: Incomplete +PKEY_Audio_SampleRate: Incomplete +PKEY_Audio_SampleSize: Incomplete +PKEY_Audio_StreamName: Incomplete +PKEY_Audio_StreamNumber: Incomplete +PKEY_Calendar_Duration: Incomplete +PKEY_Calendar_IsOnline: Incomplete +PKEY_Calendar_IsRecurring: Incomplete +PKEY_Calendar_Location: Incomplete +PKEY_Calendar_OptionalAttendeeAddresses: Incomplete +PKEY_Calendar_OptionalAttendeeNames: Incomplete +PKEY_Calendar_OrganizerAddress: Incomplete +PKEY_Calendar_OrganizerName: Incomplete +PKEY_Calendar_ReminderTime: Incomplete +PKEY_Calendar_RequiredAttendeeAddresses: Incomplete +PKEY_Calendar_RequiredAttendeeNames: Incomplete +PKEY_Calendar_Resources: Incomplete +PKEY_Calendar_ShowTimeAs: Incomplete +PKEY_Calendar_ShowTimeAsText: Incomplete +PKEY_Communication_AccountName: Incomplete +PKEY_Communication_Suffix: Incomplete +PKEY_Communication_TaskStatus: Incomplete +PKEY_Communication_TaskStatusText: Incomplete +PKEY_Computer_DecoratedFreeSpace: Incomplete +PKEY_Contact_Anniversary: Incomplete +PKEY_Contact_AssistantName: Incomplete +PKEY_Contact_AssistantTelephone: Incomplete +PKEY_Contact_Birthday: Incomplete +PKEY_Contact_BusinessAddress: Incomplete +PKEY_Contact_BusinessAddressCity: Incomplete +PKEY_Contact_BusinessAddressCountry: Incomplete +PKEY_Contact_BusinessAddressPostalCode: Incomplete +PKEY_Contact_BusinessAddressPostOfficeBox: Incomplete +PKEY_Contact_BusinessAddressState: Incomplete +PKEY_Contact_BusinessAddressStreet: Incomplete +PKEY_Contact_BusinessFaxNumber: Incomplete +PKEY_Contact_BusinessHomePage: Incomplete +PKEY_Contact_BusinessTelephone: Incomplete +PKEY_Contact_CallbackTelephone: Incomplete +PKEY_Contact_CarTelephone: Incomplete +PKEY_Contact_Children: Incomplete +PKEY_Contact_CompanyMainTelephone: Incomplete +PKEY_Contact_Department: Incomplete +PKEY_Contact_EmailAddress: Incomplete +PKEY_Contact_EmailAddress2: Incomplete +PKEY_Contact_EmailAddress3: Incomplete +PKEY_Contact_EmailAddresses: Incomplete +PKEY_Contact_EmailName: Incomplete +PKEY_Contact_FileAsName: Incomplete +PKEY_Contact_FirstName: Incomplete +PKEY_Contact_FullName: Incomplete +PKEY_Contact_Gender: Incomplete +PKEY_Contact_Hobbies: Incomplete +PKEY_Contact_HomeAddress: Incomplete +PKEY_Contact_HomeAddressCity: Incomplete +PKEY_Contact_HomeAddressCountry: Incomplete +PKEY_Contact_HomeAddressPostalCode: Incomplete +PKEY_Contact_HomeAddressPostOfficeBox: Incomplete +PKEY_Contact_HomeAddressState: Incomplete +PKEY_Contact_HomeAddressStreet: Incomplete +PKEY_Contact_HomeFaxNumber: Incomplete +PKEY_Contact_HomeTelephone: Incomplete +PKEY_Contact_IMAddress: Incomplete +PKEY_Contact_Initials: Incomplete +PKEY_Contact_JA_CompanyNamePhonetic: Incomplete +PKEY_Contact_JA_FirstNamePhonetic: Incomplete +PKEY_Contact_JA_LastNamePhonetic: Incomplete +PKEY_Contact_JobTitle: Incomplete +PKEY_Contact_Label: Incomplete +PKEY_Contact_LastName: Incomplete +PKEY_Contact_MailingAddress: Incomplete +PKEY_Contact_MiddleName: Incomplete +PKEY_Contact_MobileTelephone: Incomplete +PKEY_Contact_NickName: Incomplete +PKEY_Contact_OfficeLocation: Incomplete +PKEY_Contact_OtherAddress: Incomplete +PKEY_Contact_OtherAddressCity: Incomplete +PKEY_Contact_OtherAddressCountry: Incomplete +PKEY_Contact_OtherAddressPostalCode: Incomplete +PKEY_Contact_OtherAddressPostOfficeBox: Incomplete +PKEY_Contact_OtherAddressState: Incomplete +PKEY_Contact_OtherAddressStreet: Incomplete +PKEY_Contact_PagerTelephone: Incomplete +PKEY_Contact_PersonalTitle: Incomplete +PKEY_Contact_PrimaryAddressCity: Incomplete +PKEY_Contact_PrimaryAddressCountry: Incomplete +PKEY_Contact_PrimaryAddressPostalCode: Incomplete +PKEY_Contact_PrimaryAddressPostOfficeBox: Incomplete +PKEY_Contact_PrimaryAddressState: Incomplete +PKEY_Contact_PrimaryAddressStreet: Incomplete +PKEY_Contact_PrimaryEmailAddress: Incomplete +PKEY_Contact_PrimaryTelephone: Incomplete +PKEY_Contact_Profession: Incomplete +PKEY_Contact_SpouseName: Incomplete +PKEY_Contact_Suffix: Incomplete +PKEY_Contact_TelexNumber: Incomplete +PKEY_Contact_TTYTDDTelephone: Incomplete +PKEY_Contact_WebPage: Incomplete +PKEY_AcquisitionID: Incomplete +PKEY_ApplicationName: Incomplete +PKEY_Author: Incomplete +PKEY_Capacity: Incomplete +PKEY_Category: Incomplete +PKEY_Comment: Incomplete +PKEY_Company: Incomplete +PKEY_ComputerName: Incomplete +PKEY_ContainedItems: Incomplete +PKEY_ContentStatus: Incomplete +PKEY_ContentType: Incomplete +PKEY_Copyright: Incomplete +PKEY_DateAccessed: Incomplete +PKEY_DateAcquired: Incomplete +PKEY_DateArchived: Incomplete +PKEY_DateCompleted: Incomplete +PKEY_DateCreated: Incomplete +PKEY_DateImported: Incomplete +PKEY_DateModified: Incomplete +PKEY_DueDate: Incomplete +PKEY_EndDate: Incomplete +PKEY_FileAllocationSize: Incomplete +PKEY_FileAttributes: Incomplete +PKEY_FileCount: Incomplete +PKEY_FileDescription: Incomplete +PKEY_FileExtension: Incomplete +PKEY_FileFRN: Incomplete +PKEY_FileName: Incomplete +PKEY_FileOwner: Incomplete +PKEY_FileVersion: Incomplete +PKEY_FindData: Incomplete +PKEY_FlagColor: Incomplete +PKEY_FlagColorText: Incomplete +PKEY_FlagStatus: Incomplete +PKEY_FlagStatusText: Incomplete +PKEY_FreeSpace: Incomplete +PKEY_Identity: Incomplete +PKEY_Importance: Incomplete +PKEY_ImportanceText: Incomplete +PKEY_IsAttachment: Incomplete +PKEY_IsDeleted: Incomplete +PKEY_IsFlagged: Incomplete +PKEY_IsFlaggedComplete: Incomplete +PKEY_IsIncomplete: Incomplete +PKEY_IsRead: Incomplete +PKEY_IsSendToTarget: Incomplete +PKEY_IsShared: Incomplete +PKEY_ItemAuthors: Incomplete +PKEY_ItemDate: Incomplete +PKEY_ItemFolderNameDisplay: Incomplete +PKEY_ItemFolderPathDisplay: Incomplete +PKEY_ItemFolderPathDisplayNarrow: Incomplete +PKEY_ItemName: Incomplete +PKEY_ItemNameDisplay: Incomplete +PKEY_ItemNamePrefix: Incomplete +PKEY_ItemParticipants: Incomplete +PKEY_ItemPathDisplay: Incomplete +PKEY_ItemPathDisplayNarrow: Incomplete +PKEY_ItemType: Incomplete +PKEY_ItemTypeText: Incomplete +PKEY_ItemUrl: Incomplete +PKEY_Keywords: Incomplete +PKEY_Kind: Incomplete +PKEY_KindText: Incomplete +PKEY_Language: Incomplete +PKEY_MileageInformation: Incomplete +PKEY_MIMEType: Incomplete +PKEY_Null: Incomplete +PKEY_OfflineAvailability: Incomplete +PKEY_OfflineStatus: Incomplete +PKEY_OriginalFileName: Incomplete +PKEY_ParentalRating: Incomplete +PKEY_ParentalRatingReason: Incomplete +PKEY_ParentalRatingsOrganization: Incomplete +PKEY_ParsingBindContext: Incomplete +PKEY_ParsingName: Incomplete +PKEY_ParsingPath: Incomplete +PKEY_PerceivedType: Incomplete +PKEY_PercentFull: Incomplete +PKEY_Priority: Incomplete +PKEY_PriorityText: Incomplete +PKEY_Project: Incomplete +PKEY_ProviderItemID: Incomplete +PKEY_Rating: Incomplete +PKEY_RatingText: Incomplete +PKEY_Sensitivity: Incomplete +PKEY_SensitivityText: Incomplete +PKEY_SFGAOFlags: Incomplete +PKEY_SharedWith: Incomplete +PKEY_ShareUserRating: Incomplete +PKEY_Shell_OmitFromView: Incomplete +PKEY_SimpleRating: Incomplete +PKEY_Size: Incomplete +PKEY_SoftwareUsed: Incomplete +PKEY_SourceItem: Incomplete +PKEY_StartDate: Incomplete +PKEY_Status: Incomplete +PKEY_Subject: Incomplete +PKEY_Thumbnail: Incomplete +PKEY_ThumbnailCacheId: Incomplete +PKEY_ThumbnailStream: Incomplete +PKEY_Title: Incomplete +PKEY_TotalFileSize: Incomplete +PKEY_Trademarks: Incomplete +PKEY_Document_ByteCount: Incomplete +PKEY_Document_CharacterCount: Incomplete +PKEY_Document_ClientID: Incomplete +PKEY_Document_Contributor: Incomplete +PKEY_Document_DateCreated: Incomplete +PKEY_Document_DatePrinted: Incomplete +PKEY_Document_DateSaved: Incomplete +PKEY_Document_Division: Incomplete +PKEY_Document_DocumentID: Incomplete +PKEY_Document_HiddenSlideCount: Incomplete +PKEY_Document_LastAuthor: Incomplete +PKEY_Document_LineCount: Incomplete +PKEY_Document_Manager: Incomplete +PKEY_Document_MultimediaClipCount: Incomplete +PKEY_Document_NoteCount: Incomplete +PKEY_Document_PageCount: Incomplete +PKEY_Document_ParagraphCount: Incomplete +PKEY_Document_PresentationFormat: Incomplete +PKEY_Document_RevisionNumber: Incomplete +PKEY_Document_Security: Incomplete +PKEY_Document_SlideCount: Incomplete +PKEY_Document_Template: Incomplete +PKEY_Document_TotalEditingTime: Incomplete +PKEY_Document_Version: Incomplete +PKEY_Document_WordCount: Incomplete +PKEY_DRM_DatePlayExpires: Incomplete +PKEY_DRM_DatePlayStarts: Incomplete +PKEY_DRM_Description: Incomplete +PKEY_DRM_IsProtected: Incomplete +PKEY_DRM_PlayCount: Incomplete +PKEY_GPS_Altitude: Incomplete +PKEY_GPS_AltitudeDenominator: Incomplete +PKEY_GPS_AltitudeNumerator: Incomplete +PKEY_GPS_AltitudeRef: Incomplete +PKEY_GPS_AreaInformation: Incomplete +PKEY_GPS_Date: Incomplete +PKEY_GPS_DestBearing: Incomplete +PKEY_GPS_DestBearingDenominator: Incomplete +PKEY_GPS_DestBearingNumerator: Incomplete +PKEY_GPS_DestBearingRef: Incomplete +PKEY_GPS_DestDistance: Incomplete +PKEY_GPS_DestDistanceDenominator: Incomplete +PKEY_GPS_DestDistanceNumerator: Incomplete +PKEY_GPS_DestDistanceRef: Incomplete +PKEY_GPS_DestLatitude: Incomplete +PKEY_GPS_DestLatitudeDenominator: Incomplete +PKEY_GPS_DestLatitudeNumerator: Incomplete +PKEY_GPS_DestLatitudeRef: Incomplete +PKEY_GPS_DestLongitude: Incomplete +PKEY_GPS_DestLongitudeDenominator: Incomplete +PKEY_GPS_DestLongitudeNumerator: Incomplete +PKEY_GPS_DestLongitudeRef: Incomplete +PKEY_GPS_Differential: Incomplete +PKEY_GPS_DOP: Incomplete +PKEY_GPS_DOPDenominator: Incomplete +PKEY_GPS_DOPNumerator: Incomplete +PKEY_GPS_ImgDirection: Incomplete +PKEY_GPS_ImgDirectionDenominator: Incomplete +PKEY_GPS_ImgDirectionNumerator: Incomplete +PKEY_GPS_ImgDirectionRef: Incomplete +PKEY_GPS_Latitude: Incomplete +PKEY_GPS_LatitudeDenominator: Incomplete +PKEY_GPS_LatitudeNumerator: Incomplete +PKEY_GPS_LatitudeRef: Incomplete +PKEY_GPS_Longitude: Incomplete +PKEY_GPS_LongitudeDenominator: Incomplete +PKEY_GPS_LongitudeNumerator: Incomplete +PKEY_GPS_LongitudeRef: Incomplete +PKEY_GPS_MapDatum: Incomplete +PKEY_GPS_MeasureMode: Incomplete +PKEY_GPS_ProcessingMethod: Incomplete +PKEY_GPS_Satellites: Incomplete +PKEY_GPS_Speed: Incomplete +PKEY_GPS_SpeedDenominator: Incomplete +PKEY_GPS_SpeedNumerator: Incomplete +PKEY_GPS_SpeedRef: Incomplete +PKEY_GPS_Status: Incomplete +PKEY_GPS_Track: Incomplete +PKEY_GPS_TrackDenominator: Incomplete +PKEY_GPS_TrackNumerator: Incomplete +PKEY_GPS_TrackRef: Incomplete +PKEY_GPS_VersionID: Incomplete +PKEY_Image_BitDepth: Incomplete +PKEY_Image_ColorSpace: Incomplete +PKEY_Image_CompressedBitsPerPixel: Incomplete +PKEY_Image_CompressedBitsPerPixelDenominator: Incomplete +PKEY_Image_CompressedBitsPerPixelNumerator: Incomplete +PKEY_Image_Compression: Incomplete +PKEY_Image_CompressionText: Incomplete +PKEY_Image_Dimensions: Incomplete +PKEY_Image_HorizontalResolution: Incomplete +PKEY_Image_HorizontalSize: Incomplete +PKEY_Image_ImageID: Incomplete +PKEY_Image_ResolutionUnit: Incomplete +PKEY_Image_VerticalResolution: Incomplete +PKEY_Image_VerticalSize: Incomplete +PKEY_Journal_Contacts: Incomplete +PKEY_Journal_EntryType: Incomplete +PKEY_Link_Comment: Incomplete +PKEY_Link_DateVisited: Incomplete +PKEY_Link_Description: Incomplete +PKEY_Link_Status: Incomplete +PKEY_Link_TargetExtension: Incomplete +PKEY_Link_TargetParsingPath: Incomplete +PKEY_Link_TargetSFGAOFlags: Incomplete +PKEY_Media_AuthorUrl: Incomplete +PKEY_Media_AverageLevel: Incomplete +PKEY_Media_ClassPrimaryID: Incomplete +PKEY_Media_ClassSecondaryID: Incomplete +PKEY_Media_CollectionGroupID: Incomplete +PKEY_Media_CollectionID: Incomplete +PKEY_Media_ContentDistributor: Incomplete +PKEY_Media_ContentID: Incomplete +PKEY_Media_CreatorApplication: Incomplete +PKEY_Media_CreatorApplicationVersion: Incomplete +PKEY_Media_DateEncoded: Incomplete +PKEY_Media_DateReleased: Incomplete +PKEY_Media_Duration: Incomplete +PKEY_Media_DVDID: Incomplete +PKEY_Media_EncodedBy: Incomplete +PKEY_Media_EncodingSettings: Incomplete +PKEY_Media_FrameCount: Incomplete +PKEY_Media_MCDI: Incomplete +PKEY_Media_MetadataContentProvider: Incomplete +PKEY_Media_Producer: Incomplete +PKEY_Media_PromotionUrl: Incomplete +PKEY_Media_ProtectionType: Incomplete +PKEY_Media_ProviderRating: Incomplete +PKEY_Media_ProviderStyle: Incomplete +PKEY_Media_Publisher: Incomplete +PKEY_Media_SubscriptionContentId: Incomplete +PKEY_Media_SubTitle: Incomplete +PKEY_Media_UniqueFileIdentifier: Incomplete +PKEY_Media_UserNoAutoInfo: Incomplete +PKEY_Media_UserWebUrl: Incomplete +PKEY_Media_Writer: Incomplete +PKEY_Media_Year: Incomplete +PKEY_Message_AttachmentContents: Incomplete +PKEY_Message_AttachmentNames: Incomplete +PKEY_Message_BccAddress: Incomplete +PKEY_Message_BccName: Incomplete +PKEY_Message_CcAddress: Incomplete +PKEY_Message_CcName: Incomplete +PKEY_Message_ConversationID: Incomplete +PKEY_Message_ConversationIndex: Incomplete +PKEY_Message_DateReceived: Incomplete +PKEY_Message_DateSent: Incomplete +PKEY_Message_FromAddress: Incomplete +PKEY_Message_FromName: Incomplete +PKEY_Message_HasAttachments: Incomplete +PKEY_Message_IsFwdOrReply: Incomplete +PKEY_Message_MessageClass: Incomplete +PKEY_Message_SenderAddress: Incomplete +PKEY_Message_SenderName: Incomplete +PKEY_Message_Store: Incomplete +PKEY_Message_ToAddress: Incomplete +PKEY_Message_ToDoTitle: Incomplete +PKEY_Message_ToName: Incomplete +PKEY_Music_AlbumArtist: Incomplete +PKEY_Music_AlbumTitle: Incomplete +PKEY_Music_Artist: Incomplete +PKEY_Music_BeatsPerMinute: Incomplete +PKEY_Music_Composer: Incomplete +PKEY_Music_Conductor: Incomplete +PKEY_Music_ContentGroupDescription: Incomplete +PKEY_Music_Genre: Incomplete +PKEY_Music_InitialKey: Incomplete +PKEY_Music_Lyrics: Incomplete +PKEY_Music_Mood: Incomplete +PKEY_Music_PartOfSet: Incomplete +PKEY_Music_Period: Incomplete +PKEY_Music_SynchronizedLyrics: Incomplete +PKEY_Music_TrackNumber: Incomplete +PKEY_Note_Color: Incomplete +PKEY_Note_ColorText: Incomplete +PKEY_Photo_Aperture: Incomplete +PKEY_Photo_ApertureDenominator: Incomplete +PKEY_Photo_ApertureNumerator: Incomplete +PKEY_Photo_Brightness: Incomplete +PKEY_Photo_BrightnessDenominator: Incomplete +PKEY_Photo_BrightnessNumerator: Incomplete +PKEY_Photo_CameraManufacturer: Incomplete +PKEY_Photo_CameraModel: Incomplete +PKEY_Photo_CameraSerialNumber: Incomplete +PKEY_Photo_Contrast: Incomplete +PKEY_Photo_ContrastText: Incomplete +PKEY_Photo_DateTaken: Incomplete +PKEY_Photo_DigitalZoom: Incomplete +PKEY_Photo_DigitalZoomDenominator: Incomplete +PKEY_Photo_DigitalZoomNumerator: Incomplete +PKEY_Photo_Event: Incomplete +PKEY_Photo_EXIFVersion: Incomplete +PKEY_Photo_ExposureBias: Incomplete +PKEY_Photo_ExposureBiasDenominator: Incomplete +PKEY_Photo_ExposureBiasNumerator: Incomplete +PKEY_Photo_ExposureIndex: Incomplete +PKEY_Photo_ExposureIndexDenominator: Incomplete +PKEY_Photo_ExposureIndexNumerator: Incomplete +PKEY_Photo_ExposureProgram: Incomplete +PKEY_Photo_ExposureProgramText: Incomplete +PKEY_Photo_ExposureTime: Incomplete +PKEY_Photo_ExposureTimeDenominator: Incomplete +PKEY_Photo_ExposureTimeNumerator: Incomplete +PKEY_Photo_Flash: Incomplete +PKEY_Photo_FlashEnergy: Incomplete +PKEY_Photo_FlashEnergyDenominator: Incomplete +PKEY_Photo_FlashEnergyNumerator: Incomplete +PKEY_Photo_FlashManufacturer: Incomplete +PKEY_Photo_FlashModel: Incomplete +PKEY_Photo_FlashText: Incomplete +PKEY_Photo_FNumber: Incomplete +PKEY_Photo_FNumberDenominator: Incomplete +PKEY_Photo_FNumberNumerator: Incomplete +PKEY_Photo_FocalLength: Incomplete +PKEY_Photo_FocalLengthDenominator: Incomplete +PKEY_Photo_FocalLengthInFilm: Incomplete +PKEY_Photo_FocalLengthNumerator: Incomplete +PKEY_Photo_FocalPlaneXResolution: Incomplete +PKEY_Photo_FocalPlaneXResolutionDenominator: Incomplete +PKEY_Photo_FocalPlaneXResolutionNumerator: Incomplete +PKEY_Photo_FocalPlaneYResolution: Incomplete +PKEY_Photo_FocalPlaneYResolutionDenominator: Incomplete +PKEY_Photo_FocalPlaneYResolutionNumerator: Incomplete +PKEY_Photo_GainControl: Incomplete +PKEY_Photo_GainControlDenominator: Incomplete +PKEY_Photo_GainControlNumerator: Incomplete +PKEY_Photo_GainControlText: Incomplete +PKEY_Photo_ISOSpeed: Incomplete +PKEY_Photo_LensManufacturer: Incomplete +PKEY_Photo_LensModel: Incomplete +PKEY_Photo_LightSource: Incomplete +PKEY_Photo_MakerNote: Incomplete +PKEY_Photo_MakerNoteOffset: Incomplete +PKEY_Photo_MaxAperture: Incomplete +PKEY_Photo_MaxApertureDenominator: Incomplete +PKEY_Photo_MaxApertureNumerator: Incomplete +PKEY_Photo_MeteringMode: Incomplete +PKEY_Photo_MeteringModeText: Incomplete +PKEY_Photo_Orientation: Incomplete +PKEY_Photo_OrientationText: Incomplete +PKEY_Photo_PhotometricInterpretation: Incomplete +PKEY_Photo_PhotometricInterpretationText: Incomplete +PKEY_Photo_ProgramMode: Incomplete +PKEY_Photo_ProgramModeText: Incomplete +PKEY_Photo_RelatedSoundFile: Incomplete +PKEY_Photo_Saturation: Incomplete +PKEY_Photo_SaturationText: Incomplete +PKEY_Photo_Sharpness: Incomplete +PKEY_Photo_SharpnessText: Incomplete +PKEY_Photo_ShutterSpeed: Incomplete +PKEY_Photo_ShutterSpeedDenominator: Incomplete +PKEY_Photo_ShutterSpeedNumerator: Incomplete +PKEY_Photo_SubjectDistance: Incomplete +PKEY_Photo_SubjectDistanceDenominator: Incomplete +PKEY_Photo_SubjectDistanceNumerator: Incomplete +PKEY_Photo_TranscodedForSync: Incomplete +PKEY_Photo_WhiteBalance: Incomplete +PKEY_Photo_WhiteBalanceText: Incomplete +PKEY_PropGroup_Advanced: Incomplete +PKEY_PropGroup_Audio: Incomplete +PKEY_PropGroup_Calendar: Incomplete +PKEY_PropGroup_Camera: Incomplete +PKEY_PropGroup_Contact: Incomplete +PKEY_PropGroup_Content: Incomplete +PKEY_PropGroup_Description: Incomplete +PKEY_PropGroup_FileSystem: Incomplete +PKEY_PropGroup_General: Incomplete +PKEY_PropGroup_GPS: Incomplete +PKEY_PropGroup_Image: Incomplete +PKEY_PropGroup_Media: Incomplete +PKEY_PropGroup_MediaAdvanced: Incomplete +PKEY_PropGroup_Message: Incomplete +PKEY_PropGroup_Music: Incomplete +PKEY_PropGroup_Origin: Incomplete +PKEY_PropGroup_PhotoAdvanced: Incomplete +PKEY_PropGroup_RecordedTV: Incomplete +PKEY_PropGroup_Video: Incomplete +PKEY_PropList_ConflictPrompt: Incomplete +PKEY_PropList_ExtendedTileInfo: Incomplete +PKEY_PropList_FileOperationPrompt: Incomplete +PKEY_PropList_FullDetails: Incomplete +PKEY_PropList_InfoTip: Incomplete +PKEY_PropList_NonPersonal: Incomplete +PKEY_PropList_PreviewDetails: Incomplete +PKEY_PropList_PreviewTitle: Incomplete +PKEY_PropList_QuickTip: Incomplete +PKEY_PropList_TileInfo: Incomplete +PKEY_PropList_XPDetailsPanel: Incomplete +PKEY_RecordedTV_ChannelNumber: Incomplete +PKEY_RecordedTV_Credits: Incomplete +PKEY_RecordedTV_DateContentExpires: Incomplete +PKEY_RecordedTV_EpisodeName: Incomplete +PKEY_RecordedTV_IsATSCContent: Incomplete +PKEY_RecordedTV_IsClosedCaptioningAvailable: Incomplete +PKEY_RecordedTV_IsDTVContent: Incomplete +PKEY_RecordedTV_IsHDContent: Incomplete +PKEY_RecordedTV_IsRepeatBroadcast: Incomplete +PKEY_RecordedTV_IsSAP: Incomplete +PKEY_RecordedTV_NetworkAffiliation: Incomplete +PKEY_RecordedTV_OriginalBroadcastDate: Incomplete +PKEY_RecordedTV_ProgramDescription: Incomplete +PKEY_RecordedTV_RecordingTime: Incomplete +PKEY_RecordedTV_StationCallSign: Incomplete +PKEY_RecordedTV_StationName: Incomplete +PKEY_Search_AutoSummary: Incomplete +PKEY_Search_ContainerHash: Incomplete +PKEY_Search_Contents: Incomplete +PKEY_Search_EntryID: Incomplete +PKEY_Search_GatherTime: Incomplete +PKEY_Search_IsClosedDirectory: Incomplete +PKEY_Search_IsFullyContained: Incomplete +PKEY_Search_QueryFocusedSummary: Incomplete +PKEY_Search_Rank: Incomplete +PKEY_Search_Store: Incomplete +PKEY_Search_UrlToIndex: Incomplete +PKEY_Search_UrlToIndexWithModificationTime: Incomplete +PKEY_DescriptionID: Incomplete +PKEY_Link_TargetSFGAOFlagsStrings: Incomplete +PKEY_Link_TargetUrl: Incomplete +PKEY_Shell_SFGAOFlagsStrings: Incomplete +PKEY_Software_DateLastUsed: Incomplete +PKEY_Software_ProductName: Incomplete +PKEY_Software_ProductVersion: Incomplete +PKEY_Sync_Comments: Incomplete +PKEY_Sync_ConflictDescription: Incomplete +PKEY_Sync_ConflictFirstLocation: Incomplete +PKEY_Sync_ConflictSecondLocation: Incomplete +PKEY_Sync_HandlerCollectionID: Incomplete +PKEY_Sync_HandlerID: Incomplete +PKEY_Sync_HandlerName: Incomplete +PKEY_Sync_HandlerType: Incomplete +PKEY_Sync_HandlerTypeLabel: Incomplete +PKEY_Sync_ItemID: Incomplete +PKEY_Sync_ItemName: Incomplete +PKEY_Task_BillingInformation: Incomplete +PKEY_Task_CompletionStatus: Incomplete +PKEY_Task_Owner: Incomplete +PKEY_Video_Compression: Incomplete +PKEY_Video_Director: Incomplete +PKEY_Video_EncodingBitrate: Incomplete +PKEY_Video_FourCC: Incomplete +PKEY_Video_FrameHeight: Incomplete +PKEY_Video_FrameRate: Incomplete +PKEY_Video_FrameWidth: Incomplete +PKEY_Video_HorizontalAspectRatio: Incomplete +PKEY_Video_SampleSize: Incomplete +PKEY_Video_StreamName: Incomplete +PKEY_Video_StreamNumber: Incomplete +PKEY_Video_TotalBitrate: Incomplete +PKEY_Video_VerticalAspectRatio: Incomplete +PKEY_Volume_FileSystem: Incomplete +PKEY_Volume_IsMappedDrive: Incomplete +PKEY_Volume_IsRoot: Incomplete +PKEY_AppUserModel_RelaunchCommand: Incomplete +PKEY_AppUserModel_RelaunchIconResource: Incomplete +PKEY_AppUserModel_RelaunchDisplayNameResource: Incomplete +PKEY_AppUserModel_ID: Incomplete +PKEY_AppUserModel_IsDestListSeparator: Incomplete +PKEY_AppUserModel_ExcludeFromShowInNewInstall: Incomplete +PKEY_AppUserModel_PreventPinning: Incomplete +PKA_SET: int +PKA_APPEND: int +PKA_DELETE: int diff --git a/stubs/pywin32/win32comext/shell/__init__.pyi b/stubs/pywin32/win32comext/shell/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/shell/shell.pyi b/stubs/pywin32/win32comext/shell/shell.pyi new file mode 100644 index 000000000000..b8da6a3cc76c --- /dev/null +++ b/stubs/pywin32/win32comext/shell/shell.pyi @@ -0,0 +1,447 @@ +from _typeshed import Incomplete +from typing import Literal, TypeAlias, overload + +import _win32typing +from win32.lib.pywintypes import com_error + +error: TypeAlias = com_error # noqa: Y042 + +def AssocCreate() -> _win32typing.PyIQueryAssociations: ... +def AssocCreateForClasses() -> _win32typing.PyIUnknown: ... + +@overload +def DragQueryFile(hglobal: int | _win32typing.PyHANDLE | None, index: Literal[-1] = -1, /) -> int: ... # type: ignore[overload-overlap] +@overload +def DragQueryFile(hglobal: int | _win32typing.PyHANDLE | None, index: int, /) -> str: ... + +@overload +def DragQueryFileW(hglobal: int | _win32typing.PyHANDLE | None, index: Literal[-1] = -1, /) -> int: ... # type: ignore[overload-overlap] +@overload +def DragQueryFileW(hglobal: int | _win32typing.PyHANDLE | None, index: int, /) -> str: ... + +def DragQueryPoint(hglobal: int, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def IsUserAnAdmin() -> bool: ... +def SHCreateDataObject( + parent, children: list[Incomplete], do_inner: _win32typing.PyIDataObject, iid: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def SHCreateDefaultContextMenu(dcm, iid: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def SHCreateDefaultExtractIcon() -> _win32typing.PyIDefaultExtractIconInit: ... +def SHCreateShellFolderView( + sf: _win32typing.PyIShellFolder, viewOuter: _win32typing.PyIShellView | None = ..., callbacks: Incomplete | None = ..., / +) -> _win32typing.PyIShellView: ... +def SHCreateShellItemArray( + parent: _win32typing.PyIDL, sf: _win32typing.PyIShellFolder, children: list[_win32typing.PyIDL], / +) -> _win32typing.PyIShellItemArray: ... +def SHCreateShellItemArrayFromDataObject( + do: _win32typing.PyIDataObject, iid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItemArray: ... +def SHCreateShellItemArrayFromShellItem( + si: _win32typing.PyIShellItem, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItemArray: ... +def SHBrowseForFolder( + hwndOwner: int | None = ..., + pidlRoot: _win32typing.PyIDL | None = ..., + title: str | None = ..., + flags: int = ..., + callback: Incomplete | None = ..., + callback_data: Incomplete | None = ..., + /, +) -> tuple[_win32typing.PyIDL, Incomplete, Incomplete]: ... +def SHGetFileInfo( + name: _win32typing.PyIDL | str, dwFileAttributes, uFlags, infoAttrs: int = ..., / +) -> tuple[Incomplete, _win32typing.SHFILEINFO]: ... +def SHGetFolderPath(hwndOwner: int, nFolder, handle: int, flags, /) -> str: ... +def SHSetFolderPath(csidl, Path, hToken: int | None = ..., /) -> None: ... +def SHGetFolderLocation(hwndOwner: int, nFolder, hToken: int | None = ..., reserved=..., /) -> _win32typing.PyIDL: ... +def SHGetSpecialFolderPath(hwndOwner: int, nFolder, bCreate: int = ..., /) -> str: ... +def SHGetSpecialFolderLocation(hwndOwner: int, nFolder, /) -> _win32typing.PyIDL: ... +def SHAddToRecentDocs(Flags, data, /) -> None: ... +def SHEmptyRecycleBin(hwnd: int, path: str, flags, /) -> None: ... +def SHQueryRecycleBin(RootPath: str | None = ..., /) -> tuple[Incomplete, Incomplete]: ... +def SHGetDesktopFolder() -> _win32typing.PyIShellFolder: ... +def SHUpdateImage(HashItem: str, Index, Flags, ImageIndex, /) -> None: ... +def SHChangeNotify(EventId, Flags, Item1, Item2, /) -> None: ... +def SHChangeNotifyRegister(hwnd: int, sources, events, msg, /): ... +def SHChangeNotifyDeregister(_id, /) -> None: ... +def SHCreateItemFromParsingName(name, ctx: _win32typing.PyIBindCtx, riid: _win32typing.PyIID, /) -> _win32typing.PyIShellItem: ... +def SHCreateItemFromRelativeName( + Parent: _win32typing.PyIShellItem, Name, ctx: _win32typing.PyIBindCtx, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItem: ... +def SHCreateItemInKnownFolder( + FolderId: _win32typing.PyIID, Flags, Name, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItem: ... +def SHCreateItemWithParent( + Parent: _win32typing.PyIDL, sfParent: _win32typing.PyIShellFolder, child: _win32typing.PyIDL, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItem: ... +def SHGetInstanceExplorer() -> _win32typing.PyIUnknown: ... +def SHFileOperation(operation: _win32typing.SHFILEOPSTRUCT, /) -> tuple[Incomplete, Incomplete]: ... +def StringAsCIDA(pidl: str, /) -> tuple[_win32typing.PyIDL, Incomplete]: ... +def CIDAAsString(pidl: str, /) -> str: ... +def StringAsPIDL(pidl: str, /) -> _win32typing.PyIDL: ... +def AddressAsPIDL(address, /) -> _win32typing.PyIDL: ... +def PIDLAsString(pidl: _win32typing.PyIDL, /) -> str: ... +def SHGetSettings(mask: int = ..., /): ... +def FILEGROUPDESCRIPTORAsString(descriptors: list[Incomplete], arg, /) -> str: ... +def StringAsFILEGROUPDESCRIPTOR(buf, make_unicode: int = ..., /) -> list[Incomplete]: ... +def ShellExecuteEx( + fMask: int = ..., + hwnd: int = ..., + lpVerb: str = ..., + lpFile: str = ..., + lpParameters: str = ..., + lpDirectory: str = ..., + nShow: int = ..., + lpIDlist: _win32typing.PyIDL = ..., + lpClass: str = ..., + hkeyClass=..., + dwHotKey=..., + hIcon: int = ..., + hMonitor: int = ..., +): ... +def SHGetViewStatePropertyBag( + pidl: _win32typing.PyIDL, BagName: str, Flags, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyBag: ... +def SHILCreateFromPath(Path: str, Flags, /) -> tuple[_win32typing.PyIDL, Incomplete]: ... +def SHCreateShellItem( + pidlParent: _win32typing.PyIDL, sfParent: _win32typing.PyIShellFolder, Child: _win32typing.PyIDL, / +) -> _win32typing.PyIShellItem: ... +def SHOpenFolderAndSelectItems(Folder: _win32typing.PyIDL, Items: tuple[_win32typing.PyIDL, ...], Flags=...) -> None: ... +def SHCreateStreamOnFileEx( + File: str, Mode: int, Attributes: int, Create: bool, Template: None = None +) -> _win32typing.PyIStream: ... +def SetCurrentProcessExplicitAppUserModelID(AppID: str, /) -> None: ... +def GetCurrentProcessExplicitAppUserModelID() -> str: ... +def SHParseDisplayName(Name, Attributes, BindCtx: _win32typing.PyIBindCtx | None = ...) -> tuple[list[bytes], int]: ... +def SHCreateItemFromIDList(pidl, riid=..., /): ... +def SHCreateShellItemArrayFromIDLists(pidls, /): ... +def SHGetIDListFromObject(unk, /): ... +def SHGetNameFromIDList(pidl, flags: int, /): ... +def SHGetPathFromIDList(pidl, /): ... +def SHGetPathFromIDListW(Pidl, /): ... + +BHID_AssociationArray: _win32typing.PyIID +BHID_DataObject: _win32typing.PyIID +BHID_EnumItems: _win32typing.PyIID +BHID_Filter: _win32typing.PyIID +BHID_LinkTargetItem: _win32typing.PyIID +BHID_PropertyStore: _win32typing.PyIID +BHID_SFObject: _win32typing.PyIID +BHID_SFUIObject: _win32typing.PyIID +BHID_SFViewObject: _win32typing.PyIID +BHID_Storage: _win32typing.PyIID +BHID_StorageEnum: _win32typing.PyIID +BHID_Stream: _win32typing.PyIID +BHID_ThumbnailHandler: _win32typing.PyIID +BHID_Transfer: _win32typing.PyIID +CGID_DefView: _win32typing.PyIID +CGID_Explorer: _win32typing.PyIID +CGID_ExplorerBarDoc: _win32typing.PyIID +CGID_ShellDocView: _win32typing.PyIID +CGID_ShellServiceObject: _win32typing.PyIID +CLSID_ActiveDesktop: _win32typing.PyIID +CLSID_ApplicationDestinations: _win32typing.PyIID +CLSID_ApplicationDocumentLists: _win32typing.PyIID +CLSID_ControlPanel: _win32typing.PyIID +CLSID_DestinationList: _win32typing.PyIID +CLSID_DragDropHelper: _win32typing.PyIID +CLSID_EnumerableObjectCollection: _win32typing.PyIID +CLSID_FileOperation: _win32typing.PyIID +CLSID_Internet: _win32typing.PyIID +CLSID_InternetShortcut: _win32typing.PyIID +CLSID_KnownFolderManager: _win32typing.PyIID +CLSID_MyComputer: _win32typing.PyIID +CLSID_MyDocuments: _win32typing.PyIID +CLSID_NetworkDomain: _win32typing.PyIID +CLSID_NetworkPlaces: _win32typing.PyIID +CLSID_NetworkServer: _win32typing.PyIID +CLSID_NetworkShare: _win32typing.PyIID +CLSID_Printers: _win32typing.PyIID +CLSID_RecycleBin: _win32typing.PyIID +CLSID_ShellDesktop: _win32typing.PyIID +CLSID_ShellFSFolder: _win32typing.PyIID +CLSID_ShellItem: _win32typing.PyIID +CLSID_ShellLibrary: _win32typing.PyIID +CLSID_ShellLink: _win32typing.PyIID +CLSID_TaskbarList: _win32typing.PyIID +EP_AdvQueryPane: _win32typing.PyIID +EP_Commands: _win32typing.PyIID +EP_Commands_Organize: _win32typing.PyIID +EP_Commands_View: _win32typing.PyIID +EP_DetailsPane: _win32typing.PyIID +EP_NavPane: _win32typing.PyIID +EP_PreviewPane: _win32typing.PyIID +EP_QueryPane: _win32typing.PyIID +FMTID_AudioSummaryInformation: _win32typing.PyIID +FMTID_Briefcase: _win32typing.PyIID +FMTID_Displaced: _win32typing.PyIID +FMTID_ImageProperties: _win32typing.PyIID +FMTID_ImageSummaryInformation: _win32typing.PyIID +FMTID_InternetSite: _win32typing.PyIID +FMTID_Intshcut: _win32typing.PyIID +FMTID_MediaFileSummaryInformation: _win32typing.PyIID +FMTID_Misc: _win32typing.PyIID +FMTID_Query: _win32typing.PyIID +FMTID_ShellDetails: _win32typing.PyIID +FMTID_Storage: _win32typing.PyIID +FMTID_SummaryInformation: _win32typing.PyIID +FMTID_Volume: _win32typing.PyIID +FMTID_WebView: _win32typing.PyIID +FOLDERID_AddNewPrograms: _win32typing.PyIID +FOLDERID_AdminTools: _win32typing.PyIID +FOLDERID_AppUpdates: _win32typing.PyIID +FOLDERID_CDBurning: _win32typing.PyIID +FOLDERID_ChangeRemovePrograms: _win32typing.PyIID +FOLDERID_CommonAdminTools: _win32typing.PyIID +FOLDERID_CommonOEMLinks: _win32typing.PyIID +FOLDERID_CommonPrograms: _win32typing.PyIID +FOLDERID_CommonStartMenu: _win32typing.PyIID +FOLDERID_CommonStartup: _win32typing.PyIID +FOLDERID_CommonTemplates: _win32typing.PyIID +FOLDERID_ComputerFolder: _win32typing.PyIID +FOLDERID_ConflictFolder: _win32typing.PyIID +FOLDERID_ConnectionsFolder: _win32typing.PyIID +FOLDERID_Contacts: _win32typing.PyIID +FOLDERID_ControlPanelFolder: _win32typing.PyIID +FOLDERID_Cookies: _win32typing.PyIID +FOLDERID_Desktop: _win32typing.PyIID +FOLDERID_DeviceMetadataStore: _win32typing.PyIID +FOLDERID_Documents: _win32typing.PyIID +FOLDERID_DocumentsLibrary: _win32typing.PyIID +FOLDERID_Downloads: _win32typing.PyIID +FOLDERID_Favorites: _win32typing.PyIID +FOLDERID_Fonts: _win32typing.PyIID +FOLDERID_GameTasks: _win32typing.PyIID +FOLDERID_Games: _win32typing.PyIID +FOLDERID_History: _win32typing.PyIID +FOLDERID_HomeGroup: _win32typing.PyIID +FOLDERID_ImplicitAppShortcuts: _win32typing.PyIID +FOLDERID_InternetCache: _win32typing.PyIID +FOLDERID_InternetFolder: _win32typing.PyIID +FOLDERID_Libraries: _win32typing.PyIID +FOLDERID_Links: _win32typing.PyIID +FOLDERID_LocalAppData: _win32typing.PyIID +FOLDERID_LocalAppDataLow: _win32typing.PyIID +FOLDERID_LocalizedResourcesDir: _win32typing.PyIID +FOLDERID_Music: _win32typing.PyIID +FOLDERID_MusicLibrary: _win32typing.PyIID +FOLDERID_NetHood: _win32typing.PyIID +FOLDERID_NetworkFolder: _win32typing.PyIID +FOLDERID_OriginalImages: _win32typing.PyIID +FOLDERID_PhotoAlbums: _win32typing.PyIID +FOLDERID_Pictures: _win32typing.PyIID +FOLDERID_PicturesLibrary: _win32typing.PyIID +FOLDERID_Playlists: _win32typing.PyIID +FOLDERID_PrintHood: _win32typing.PyIID +FOLDERID_PrintersFolder: _win32typing.PyIID +FOLDERID_Profile: _win32typing.PyIID +FOLDERID_ProgramData: _win32typing.PyIID +FOLDERID_ProgramFiles: _win32typing.PyIID +FOLDERID_ProgramFilesCommon: _win32typing.PyIID +FOLDERID_ProgramFilesCommonX64: _win32typing.PyIID +FOLDERID_ProgramFilesCommonX86: _win32typing.PyIID +FOLDERID_ProgramFilesX64: _win32typing.PyIID +FOLDERID_ProgramFilesX86: _win32typing.PyIID +FOLDERID_Programs: _win32typing.PyIID +FOLDERID_Public: _win32typing.PyIID +FOLDERID_PublicDesktop: _win32typing.PyIID +FOLDERID_PublicDocuments: _win32typing.PyIID +FOLDERID_PublicDownloads: _win32typing.PyIID +FOLDERID_PublicGameTasks: _win32typing.PyIID +FOLDERID_PublicLibraries: _win32typing.PyIID +FOLDERID_PublicMusic: _win32typing.PyIID +FOLDERID_PublicPictures: _win32typing.PyIID +FOLDERID_PublicRingtones: _win32typing.PyIID +FOLDERID_PublicVideos: _win32typing.PyIID +FOLDERID_QuickLaunch: _win32typing.PyIID +FOLDERID_Recent: _win32typing.PyIID +FOLDERID_RecordedTVLibrary: _win32typing.PyIID +FOLDERID_RecycleBinFolder: _win32typing.PyIID +FOLDERID_ResourceDir: _win32typing.PyIID +FOLDERID_Ringtones: _win32typing.PyIID +FOLDERID_RoamingAppData: _win32typing.PyIID +FOLDERID_SEARCH_CSC: _win32typing.PyIID +FOLDERID_SEARCH_MAPI: _win32typing.PyIID +FOLDERID_SampleMusic: _win32typing.PyIID +FOLDERID_SamplePictures: _win32typing.PyIID +FOLDERID_SamplePlaylists: _win32typing.PyIID +FOLDERID_SampleVideos: _win32typing.PyIID +FOLDERID_SavedGames: _win32typing.PyIID +FOLDERID_SavedSearches: _win32typing.PyIID +FOLDERID_SearchHome: _win32typing.PyIID +FOLDERID_SendTo: _win32typing.PyIID +FOLDERID_SidebarDefaultParts: _win32typing.PyIID +FOLDERID_SidebarParts: _win32typing.PyIID +FOLDERID_StartMenu: _win32typing.PyIID +FOLDERID_Startup: _win32typing.PyIID +FOLDERID_SyncManagerFolder: _win32typing.PyIID +FOLDERID_SyncResultsFolder: _win32typing.PyIID +FOLDERID_SyncSetupFolder: _win32typing.PyIID +FOLDERID_System: _win32typing.PyIID +FOLDERID_SystemX86: _win32typing.PyIID +FOLDERID_Templates: _win32typing.PyIID +FOLDERID_UserPinned: _win32typing.PyIID +FOLDERID_UserProfiles: _win32typing.PyIID +FOLDERID_UserProgramFiles: _win32typing.PyIID +FOLDERID_UserProgramFilesCommon: _win32typing.PyIID +FOLDERID_UsersFiles: _win32typing.PyIID +FOLDERID_UsersLibraries: _win32typing.PyIID +FOLDERID_Videos: _win32typing.PyIID +FOLDERID_VideosLibrary: _win32typing.PyIID +FOLDERID_Windows: _win32typing.PyIID +FOLDERTYPEID_Communications: _win32typing.PyIID +FOLDERTYPEID_CompressedFolder: _win32typing.PyIID +FOLDERTYPEID_Contacts: _win32typing.PyIID +FOLDERTYPEID_ControlPanelCategory: _win32typing.PyIID +FOLDERTYPEID_ControlPanelClassic: _win32typing.PyIID +FOLDERTYPEID_Documents: _win32typing.PyIID +FOLDERTYPEID_Games: _win32typing.PyIID +FOLDERTYPEID_Generic: _win32typing.PyIID +FOLDERTYPEID_GenericLibrary: _win32typing.PyIID +FOLDERTYPEID_GenericSearchResults: _win32typing.PyIID +FOLDERTYPEID_Invalid: _win32typing.PyIID +FOLDERTYPEID_Music: _win32typing.PyIID +FOLDERTYPEID_NetworkExplorer: _win32typing.PyIID +FOLDERTYPEID_OpenSearch: _win32typing.PyIID +FOLDERTYPEID_OtherUsers: _win32typing.PyIID +FOLDERTYPEID_Pictures: _win32typing.PyIID +FOLDERTYPEID_Printers: _win32typing.PyIID +FOLDERTYPEID_PublishedItems: _win32typing.PyIID +FOLDERTYPEID_RecordedTV: _win32typing.PyIID +FOLDERTYPEID_RecycleBin: _win32typing.PyIID +FOLDERTYPEID_SavedGames: _win32typing.PyIID +FOLDERTYPEID_SearchConnector: _win32typing.PyIID +FOLDERTYPEID_SearchHome: _win32typing.PyIID +FOLDERTYPEID_Searches: _win32typing.PyIID +FOLDERTYPEID_SoftwareExplorer: _win32typing.PyIID +FOLDERTYPEID_StartMenu: _win32typing.PyIID +FOLDERTYPEID_UserFiles: _win32typing.PyIID +FOLDERTYPEID_UsersLibraries: _win32typing.PyIID +FOLDERTYPEID_Videos: _win32typing.PyIID +HOTKEYF_ALT: int +HOTKEYF_CONTROL: int +HOTKEYF_EXT: int +HOTKEYF_SHIFT: int +IID_CDefView: _win32typing.PyIID +IID_IADesktopP2: _win32typing.PyIID +IID_IActiveDesktop: _win32typing.PyIID +IID_IActiveDesktopP: _win32typing.PyIID +IID_IApplicationDestinations: _win32typing.PyIID +IID_IApplicationDocumentLists: _win32typing.PyIID +IID_IAsyncOperation: _win32typing.PyIID +IID_IBrowserFrameOptions: _win32typing.PyIID +IID_ICategorizer: _win32typing.PyIID +IID_ICategoryProvider: _win32typing.PyIID +IID_IColumnProvider: _win32typing.PyIID +IID_IContextMenu: _win32typing.PyIID +IID_IContextMenu2: _win32typing.PyIID +IID_IContextMenu3: _win32typing.PyIID +IID_ICopyHook: _win32typing.PyIID +IID_ICopyHookA: _win32typing.PyIID +IID_ICopyHookW: _win32typing.PyIID +IID_ICurrentItem: _win32typing.PyIID +IID_ICustomDestinationList: _win32typing.PyIID +IID_IDefaultExtractIconInit: _win32typing.PyIID +IID_IDeskBand: _win32typing.PyIID +IID_IDisplayItem: _win32typing.PyIID +IID_IDockingWindow: _win32typing.PyIID +IID_IDropTargetHelper: _win32typing.PyIID +IID_IEmptyVolumeCache: _win32typing.PyIID +IID_IEmptyVolumeCache2: _win32typing.PyIID +IID_IEmptyVolumeCacheCallBack: _win32typing.PyIID +IID_IEnumExplorerCommand: _win32typing.PyIID +IID_IEnumIDList: _win32typing.PyIID +IID_IEnumObjects: _win32typing.PyIID +IID_IEnumResources: _win32typing.PyIID +IID_IEnumShellItems: _win32typing.PyIID +IID_IExplorerBrowser: _win32typing.PyIID +IID_IExplorerBrowserEvents: _win32typing.PyIID +IID_IExplorerCommand: _win32typing.PyIID +IID_IExplorerCommandProvider: _win32typing.PyIID +IID_IExplorerPaneVisibility: _win32typing.PyIID +IID_IExtractIcon: _win32typing.PyIID +IID_IExtractIconW: _win32typing.PyIID +IID_IExtractImage: _win32typing.PyIID +IID_IFileOperation: _win32typing.PyIID +IID_IFileOperationProgressSink: _win32typing.PyIID +IID_IFolderView: _win32typing.PyIID +IID_IIdentityName: _win32typing.PyIID +IID_IKnownFolder: _win32typing.PyIID +IID_IKnownFolderManager: _win32typing.PyIID +IID_INameSpaceTreeControl: _win32typing.PyIID +IID_IObjectArray: _win32typing.PyIID +IID_IObjectCollection: _win32typing.PyIID +IID_IPersistFolder: _win32typing.PyIID +IID_IPersistFolder2: _win32typing.PyIID +IID_IQueryAssociations: _win32typing.PyIID +IID_IRelatedItem: _win32typing.PyIID +IID_IShellBrowser: _win32typing.PyIID +IID_IShellCopyHook: _win32typing.PyIID +IID_IShellCopyHookA: _win32typing.PyIID +IID_IShellCopyHookW: _win32typing.PyIID +IID_IShellExtInit: _win32typing.PyIID +IID_IShellFolder: _win32typing.PyIID +IID_IShellFolder2: _win32typing.PyIID +IID_IShellIcon: _win32typing.PyIID +IID_IShellIconOverlay: _win32typing.PyIID +IID_IShellIconOverlayIdentifier: _win32typing.PyIID +IID_IShellIconOverlayManager: _win32typing.PyIID +IID_IShellItem: _win32typing.PyIID +IID_IShellItem2: _win32typing.PyIID +IID_IShellItemArray: _win32typing.PyIID +IID_IShellItemResources: _win32typing.PyIID +IID_IShellLibrary: _win32typing.PyIID +IID_IShellLink: _win32typing.PyIID +IID_IShellLinkA: _win32typing.PyIID +IID_IShellLinkDataList: _win32typing.PyIID +IID_IShellLinkW: _win32typing.PyIID +IID_IShellView: _win32typing.PyIID +IID_ITaskbarList: _win32typing.PyIID +IID_ITransferAdviseSink: _win32typing.PyIID +IID_ITransferDestination: _win32typing.PyIID +IID_ITransferMediumItem: _win32typing.PyIID +IID_ITransferSource: _win32typing.PyIID +IID_IUniformResourceLocator: _win32typing.PyIID +ResourceTypeStream: _win32typing.PyIID +SID_CtxQueryAssociations: _win32typing.PyIID +SID_DefView: _win32typing.PyIID +SID_LinkSite: _win32typing.PyIID +SID_MenuShellFolder: _win32typing.PyIID +SID_SCommDlgBrowser: _win32typing.PyIID +SID_SGetViewFromViewDual: _win32typing.PyIID +SID_SInternetExplorer: _win32typing.PyIID +SID_SMenuBandBKContextMenu: _win32typing.PyIID +SID_SMenuBandBottom: _win32typing.PyIID +SID_SMenuBandBottomSelected: _win32typing.PyIID +SID_SMenuBandChild: _win32typing.PyIID +SID_SMenuBandContextMenuModifier: _win32typing.PyIID +SID_SMenuBandParent: _win32typing.PyIID +SID_SMenuBandTop: _win32typing.PyIID +SID_SMenuPopup: _win32typing.PyIID +SID_SProgressUI: _win32typing.PyIID +SID_SShellBrowser: _win32typing.PyIID +SID_SShellDesktop: _win32typing.PyIID +SID_STopLevelBrowser: _win32typing.PyIID +SID_STopWindow: _win32typing.PyIID +SID_SUrlHistory: _win32typing.PyIID +SID_SWebBrowserApp: _win32typing.PyIID +SID_ShellFolderViewCB: _win32typing.PyIID +SLGP_RAWPATH: int +SLGP_SHORTPATH: int +SLGP_UNCPRIORITY: int +SLR_ANY_MATCH: int +SLR_INVOKE_MSI: int +SLR_NOLINKINFO: int +SLR_NOSEARCH: int +SLR_NOTRACK: int +SLR_NOUPDATE: int +SLR_NO_UI: int +SLR_UPDATE: int +VID_Details: _win32typing.PyIID +VID_LargeIcons: _win32typing.PyIID +VID_List: _win32typing.PyIID +VID_SmallIcons: _win32typing.PyIID +VID_ThumbStrip: _win32typing.PyIID +VID_Thumbnails: _win32typing.PyIID +VID_Tile: _win32typing.PyIID + +def SHGetKnownFolderPath(fid, flags: int = 0, token=None, /): ... diff --git a/stubs/pywin32/win32comext/shell/shellcon.pyi b/stubs/pywin32/win32comext/shell/shellcon.pyi new file mode 100644 index 000000000000..8e6090af389b --- /dev/null +++ b/stubs/pywin32/win32comext/shell/shellcon.pyi @@ -0,0 +1,1413 @@ +from _typeshed import Incomplete + +WM_USER: int +DROPEFFECT_NONE: int +DROPEFFECT_COPY: int +DROPEFFECT_MOVE: int +DROPEFFECT_LINK: int +DROPEFFECT_SCROLL: int +FO_MOVE: int +FO_COPY: int +FO_DELETE: int +FO_RENAME: int +FOF_MULTIDESTFILES: int +FOF_CONFIRMMOUSE: int +FOF_SILENT: int +FOF_RENAMEONCOLLISION: int +FOF_NOCONFIRMATION: int +FOF_WANTMAPPINGHANDLE: int +FOF_ALLOWUNDO: int +FOF_FILESONLY: int +FOF_SIMPLEPROGRESS: int +FOF_NOCONFIRMMKDIR: int +FOF_NOERRORUI: int +FOF_NOCOPYSECURITYATTRIBS: int +FOF_NORECURSION: int +FOF_NO_CONNECTED_ELEMENTS: int +FOF_WANTNUKEWARNING: int +FOF_NORECURSEREPARSE: int +FOF_NO_UI: Incomplete +FOFX_NOSKIPJUNCTIONS: int +FOFX_PREFERHARDLINK: int +FOFX_SHOWELEVATIONPROMPT: int +FOFX_EARLYFAILURE: int +FOFX_PRESERVEFILEEXTENSIONS: int +FOFX_KEEPNEWERFILE: int +FOFX_NOCOPYHOOKS: int +FOFX_NOMINIMIZEBOX: int +FOFX_MOVEACLSACROSSVOLUMES: int +FOFX_DONTDISPLAYSOURCEPATH: int +FOFX_DONTDISPLAYDESTPATH: int +FOFX_REQUIREELEVATION: int +FOFX_COPYASDOWNLOAD: int +FOFX_DONTDISPLAYLOCATIONS: int +PO_DELETE: int +PO_RENAME: int +PO_PORTCHANGE: int +PO_REN_PORT: int +SE_ERR_FNF: int +SE_ERR_PNF: int +SE_ERR_ACCESSDENIED: int +SE_ERR_OOM: int +SE_ERR_DLLNOTFOUND: int +SE_ERR_SHARE: int +SE_ERR_ASSOCINCOMPLETE: int +SE_ERR_DDETIMEOUT: int +SE_ERR_DDEFAIL: int +SE_ERR_DDEBUSY: int +SE_ERR_NOASSOC: int +SEE_MASK_CLASSNAME: int +SEE_MASK_CLASSKEY: int +SEE_MASK_IDLIST: int +SEE_MASK_INVOKEIDLIST: int +SEE_MASK_ICON: int +SEE_MASK_HOTKEY: int +SEE_MASK_NOCLOSEPROCESS: int +SEE_MASK_CONNECTNETDRV: int +SEE_MASK_FLAG_DDEWAIT: int +SEE_MASK_DOENVSUBST: int +SEE_MASK_FLAG_NO_UI: int +SEE_MASK_UNICODE: int +SEE_MASK_NO_CONSOLE: int +SEE_MASK_ASYNCOK: int +SEE_MASK_HMONITOR: int +SHERB_NOCONFIRMATION: int +SHERB_NOPROGRESSUI: int +SHERB_NOSOUND: int +NIM_ADD: int +NIM_MODIFY: int +NIM_DELETE: int +NIF_MESSAGE: int +NIF_ICON: int +NIF_TIP: int +SHGFI_ICON: int +SHGFI_DISPLAYNAME: int +SHGFI_TYPENAME: int +SHGFI_ATTRIBUTES: int +SHGFI_ICONLOCATION: int +SHGFI_EXETYPE: int +SHGFI_SYSICONINDEX: int +SHGFI_LINKOVERLAY: int +SHGFI_SELECTED: int +SHGFI_ATTR_SPECIFIED: int +SHGFI_LARGEICON: int +SHGFI_SMALLICON: int +SHGFI_OPENICON: int +SHGFI_SHELLICONSIZE: int +SHGFI_PIDL: int +SHGFI_USEFILEATTRIBUTES: int +SHGNLI_PIDL: int +SHGNLI_PREFIXNAME: int +SHGNLI_NOUNIQUE: int +PRINTACTION_OPEN: int +PRINTACTION_PROPERTIES: int +PRINTACTION_NETINSTALL: int +PRINTACTION_NETINSTALLLINK: int +PRINTACTION_TESTPAGE: int +PRINTACTION_OPENNETPRN: int +PRINTACTION_DOCUMENTDEFAULTS: int +PRINTACTION_SERVERPROPERTIES: int +CMF_NORMAL: int +CMF_DEFAULTONLY: int +CMF_VERBSONLY: int +CMF_EXPLORE: int +CMF_NOVERBS: int +CMF_CANRENAME: int +CMF_NODEFAULT: int +CMF_INCLUDESTATIC: int +CMF_ITEMMENU: int +CMF_EXTENDEDVERBS: int +CMF_DISABLEDVERBS: int +CMF_ASYNCVERBSTATE: int +CMF_OPTIMIZEFORINVOKE: int +CMF_SYNCCASCADEMENU: int +CMF_DONOTPICKDEFAULT: int +CMF_RESERVED: int +GCS_VERBA: int +GCS_HELPTEXTA: int +GCS_VALIDATEA: int +GCS_VERBW: int +GCS_HELPTEXTW: int +GCS_VALIDATEW: int +GCS_UNICODE: int +GCS_VERB: int +GCS_HELPTEXT: int +GCS_VALIDATE: int +CMDSTR_NEWFOLDERA: str +CMDSTR_VIEWLISTA: str +CMDSTR_VIEWDETAILSA: str +CMDSTR_NEWFOLDER: str +CMDSTR_VIEWLIST: str +CMDSTR_VIEWDETAILS: str +CMIC_MASK_HOTKEY: int +CMIC_MASK_ICON: int +CMIC_MASK_FLAG_NO_UI: int +CMIC_MASK_UNICODE: int +CMIC_MASK_NO_CONSOLE: int +CMIC_MASK_ASYNCOK: int +CMIC_MASK_PTINVOKE: int +GIL_OPENICON: int +GIL_FORSHELL: int +GIL_ASYNC: int +GIL_DEFAULTICON: int +GIL_FORSHORTCUT: int +GIL_CHECKSHIELD: int +GIL_SIMULATEDOC: int +GIL_PERINSTANCE: int +GIL_PERCLASS: int +GIL_NOTFILENAME: int +GIL_DONTCACHE: int +GIL_SHIELD: int +GIL_FORCENOSHIELD: int +ISIOI_ICONFILE: int +ISIOI_ICONINDEX: int +ISIOI_SYSIMAGELISTINDEX: int +FVSIF_RECT: int +FVSIF_PINNED: int +FVSIF_NEWFAILED: int +FVSIF_NEWFILE: int +FVSIF_CANVIEWIT: int +FCIDM_SHVIEWFIRST: int +FCIDM_SHVIEWLAST: int +FCIDM_BROWSERFIRST: int +FCIDM_BROWSERLAST: int +FCIDM_GLOBALFIRST: int +FCIDM_GLOBALLAST: int +FCIDM_MENU_FILE: Incomplete +FCIDM_MENU_EDIT: Incomplete +FCIDM_MENU_VIEW: Incomplete +FCIDM_MENU_VIEW_SEP_OPTIONS: Incomplete +FCIDM_MENU_TOOLS: Incomplete +FCIDM_MENU_TOOLS_SEP_GOTO: Incomplete +FCIDM_MENU_HELP: Incomplete +FCIDM_MENU_FIND: Incomplete +FCIDM_MENU_EXPLORE: Incomplete +FCIDM_MENU_FAVORITES: Incomplete +FCIDM_TOOLBAR: Incomplete +FCIDM_STATUS: Incomplete +IDC_OFFLINE_HAND: int +SBSP_DEFBROWSER: int +SBSP_SAMEBROWSER: int +SBSP_NEWBROWSER: int +SBSP_DEFMODE: int +SBSP_OPENMODE: int +SBSP_EXPLOREMODE: int +SBSP_ABSOLUTE: int +SBSP_RELATIVE: int +SBSP_PARENT: int +SBSP_NAVIGATEBACK: int +SBSP_NAVIGATEFORWARD: int +SBSP_ALLOW_AUTONAVIGATE: int +SBSP_INITIATEDBYHLINKFRAME: int +SBSP_REDIRECT: int +SBSP_WRITENOHISTORY: int +SBSP_NOAUTOSELECT: int +FCW_STATUS: int +FCW_TOOLBAR: int +FCW_TREE: int +FCW_INTERNETBAR: int +FCW_PROGRESS: int +FCT_MERGE: int +FCT_CONFIGABLE: int +FCT_ADDTOEND: int +CDBOSC_SETFOCUS: int +CDBOSC_KILLFOCUS: int +CDBOSC_SELCHANGE: int +CDBOSC_RENAME: int +SVSI_DESELECT: int +SVSI_SELECT: int +SVSI_EDIT: int +SVSI_DESELECTOTHERS: int +SVSI_ENSUREVISIBLE: int +SVSI_FOCUSED: int +SVSI_TRANSLATEPT: int +SVSI_SELECTIONMARK: int +SVSI_POSITIONITEM: int +SVSI_CHECK: int +SVSI_CHECK2: int +SVSI_KEYBOARDSELECT: int +SVSI_NOTAKEFOCUS: int +SVGIO_BACKGROUND: int +SVGIO_SELECTION: int +SVGIO_ALLVIEW: int +SVGIO_CHECKED: Incomplete +SVGIO_TYPE_MASK: Incomplete +SVGIO_FLAG_VIEWORDER: int +STRRET_WSTR: int +STRRET_OFFSET: int +STRRET_CSTR: int +CSIDL_DESKTOP: int +CSIDL_INTERNET: int +CSIDL_PROGRAMS: int +CSIDL_CONTROLS: int +CSIDL_PRINTERS: int +CSIDL_PERSONAL: int +CSIDL_FAVORITES: int +CSIDL_STARTUP: int +CSIDL_RECENT: int +CSIDL_SENDTO: int +CSIDL_BITBUCKET: int +CSIDL_STARTMENU: int +CSIDL_MYDOCUMENTS: int +CSIDL_MYMUSIC: int +CSIDL_MYVIDEO: int +CSIDL_DESKTOPDIRECTORY: int +CSIDL_DRIVES: int +CSIDL_NETWORK: int +CSIDL_NETHOOD: int +CSIDL_FONTS: int +CSIDL_TEMPLATES: int +CSIDL_COMMON_STARTMENU: int +CSIDL_COMMON_PROGRAMS: int +CSIDL_COMMON_STARTUP: int +CSIDL_COMMON_DESKTOPDIRECTORY: int +CSIDL_APPDATA: int +CSIDL_PRINTHOOD: int +CSIDL_LOCAL_APPDATA: int +CSIDL_ALTSTARTUP: int +CSIDL_COMMON_ALTSTARTUP: int +CSIDL_COMMON_FAVORITES: int +CSIDL_INTERNET_CACHE: int +CSIDL_COOKIES: int +CSIDL_HISTORY: int +CSIDL_COMMON_APPDATA: int +CSIDL_WINDOWS: int +CSIDL_SYSTEM: int +CSIDL_PROGRAM_FILES: int +CSIDL_MYPICTURES: int +CSIDL_PROFILE: int +CSIDL_SYSTEMX86: int +CSIDL_PROGRAM_FILESX86: int +CSIDL_PROGRAM_FILES_COMMON: int +CSIDL_PROGRAM_FILES_COMMONX86: int +CSIDL_COMMON_TEMPLATES: int +CSIDL_COMMON_DOCUMENTS: int +CSIDL_COMMON_ADMINTOOLS: int +CSIDL_ADMINTOOLS: int +CSIDL_CONNECTIONS: int +CSIDL_COMMON_MUSIC: int +CSIDL_COMMON_PICTURES: int +CSIDL_COMMON_VIDEO: int +CSIDL_RESOURCES: int +CSIDL_RESOURCES_LOCALIZED: int +CSIDL_COMMON_OEM_LINKS: int +CSIDL_CDBURN_AREA: int +CSIDL_COMPUTERSNEARME: int +BIF_RETURNONLYFSDIRS: int +BIF_DONTGOBELOWDOMAIN: int +BIF_STATUSTEXT: int +BIF_RETURNFSANCESTORS: int +BIF_EDITBOX: int +BIF_VALIDATE: int +BIF_BROWSEFORCOMPUTER: int +BIF_BROWSEFORPRINTER: int +BIF_BROWSEINCLUDEFILES: int +BFFM_INITIALIZED: int +BFFM_SELCHANGED: int +BFFM_VALIDATEFAILEDA: int +BFFM_VALIDATEFAILEDW: int +BFFM_SETSTATUSTEXTA: Incomplete +BFFM_ENABLEOK: Incomplete +BFFM_SETSELECTIONA: Incomplete +BFFM_SETSELECTIONW: Incomplete +BFFM_SETSTATUSTEXTW: Incomplete +BFFM_SETSTATUSTEXT: Incomplete +BFFM_SETSELECTION: Incomplete +BFFM_VALIDATEFAILED: int +SFGAO_CANCOPY: int +SFGAO_CANMOVE: int +SFGAO_CANLINK: int +SFGAO_CANRENAME: int +SFGAO_CANDELETE: int +SFGAO_HASPROPSHEET: int +SFGAO_DROPTARGET: int +SFGAO_CAPABILITYMASK: int +SFGAO_LINK: int +SFGAO_SHARE: int +SFGAO_READONLY: int +SFGAO_GHOSTED: int +SFGAO_HIDDEN: int +SFGAO_DISPLAYATTRMASK: int +SFGAO_FILESYSANCESTOR: int +SFGAO_FOLDER: int +SFGAO_FILESYSTEM: int +SFGAO_HASSUBFOLDER: int +SFGAO_CONTENTSMASK: int +SFGAO_VALIDATE: int +SFGAO_REMOVABLE: int +SFGAO_COMPRESSED: int +SFGAO_BROWSABLE: int +SFGAO_NONENUMERATED: int +SFGAO_NEWCONTENT: int +SFGAO_STORAGE: int +DWFRF_NORMAL: int +DWFRF_DELETECONFIGDATA: int +DWFAF_HIDDEN: int +DBIM_MINSIZE: int +DBIM_MAXSIZE: int +DBIM_INTEGRAL: int +DBIM_ACTUAL: int +DBIM_TITLE: int +DBIM_MODEFLAGS: int +DBIM_BKCOLOR: int +DBIMF_NORMAL: int +DBIMF_VARIABLEHEIGHT: int +DBIMF_DEBOSSED: int +DBIMF_BKCOLOR: int +DBIF_VIEWMODE_NORMAL: int +DBIF_VIEWMODE_VERTICAL: int +DBIF_VIEWMODE_FLOATING: int +DBIF_VIEWMODE_TRANSPARENT: int +COMPONENT_TOP: int +COMP_TYPE_HTMLDOC: int +COMP_TYPE_PICTURE: int +COMP_TYPE_WEBSITE: int +COMP_TYPE_CONTROL: int +COMP_TYPE_CFHTML: int +COMP_TYPE_MAX: int +AD_APPLY_SAVE: int +AD_APPLY_HTMLGEN: int +AD_APPLY_REFRESH: int +AD_APPLY_ALL: Incomplete +AD_APPLY_FORCE: int +AD_APPLY_BUFFERED_REFRESH: int +WPSTYLE_CENTER: int +WPSTYLE_TILE: int +WPSTYLE_STRETCH: int +WPSTYLE_MAX: int +COMP_ELEM_TYPE: int +COMP_ELEM_CHECKED: int +COMP_ELEM_DIRTY: int +COMP_ELEM_NOSCROLL: int +COMP_ELEM_POS_LEFT: int +COMP_ELEM_POS_TOP: int +COMP_ELEM_SIZE_WIDTH: int +COMP_ELEM_SIZE_HEIGHT: int +COMP_ELEM_POS_ZINDEX: int +COMP_ELEM_SOURCE: int +COMP_ELEM_FRIENDLYNAME: int +COMP_ELEM_SUBSCRIBEDURL: int +ADDURL_SILENT: int +CFSTR_SHELLIDLIST: str +CFSTR_SHELLIDLISTOFFSET: str +CFSTR_NETRESOURCES: str +CFSTR_FILEDESCRIPTORA: str +CFSTR_FILEDESCRIPTORW: str +CFSTR_FILECONTENTS: str +CFSTR_FILENAMEA: str +CFSTR_FILENAMEW: str +CFSTR_PRINTERGROUP: str +CFSTR_FILENAMEMAPA: str +CFSTR_FILENAMEMAPW: str +CFSTR_SHELLURL: str +CFSTR_INETURLA: str +CFSTR_INETURLW: str +CFSTR_PREFERREDDROPEFFECT: str +CFSTR_PERFORMEDDROPEFFECT: str +CFSTR_PASTESUCCEEDED: str +CFSTR_INDRAGLOOP: str +CFSTR_DRAGCONTEXT: str +CFSTR_MOUNTEDVOLUME: str +CFSTR_PERSISTEDDATAOBJECT: str +CFSTR_TARGETCLSID: str +CFSTR_LOGICALPERFORMEDDROPEFFECT: str +CFSTR_AUTOPLAY_SHELLIDLISTS: str +CFSTR_FILEDESCRIPTOR: str +CFSTR_FILENAME: str +CFSTR_FILENAMEMAP: str +DVASPECT_SHORTNAME: int +SHCNE_RENAMEITEM: int +SHCNE_CREATE: int +SHCNE_DELETE: int +SHCNE_MKDIR: int +SHCNE_RMDIR: int +SHCNE_MEDIAINSERTED: int +SHCNE_MEDIAREMOVED: int +SHCNE_DRIVEREMOVED: int +SHCNE_DRIVEADD: int +SHCNE_NETSHARE: int +SHCNE_NETUNSHARE: int +SHCNE_ATTRIBUTES: int +SHCNE_UPDATEDIR: int +SHCNE_UPDATEITEM: int +SHCNE_SERVERDISCONNECT: int +SHCNE_UPDATEIMAGE: int +SHCNE_DRIVEADDGUI: int +SHCNE_RENAMEFOLDER: int +SHCNE_FREESPACE: int +SHCNE_EXTENDED_EVENT: int +SHCNE_ASSOCCHANGED: int +SHCNE_DISKEVENTS: int +SHCNE_GLOBALEVENTS: int +SHCNE_ALLEVENTS: int +SHCNE_INTERRUPT: int +SHCNEE_ORDERCHANGED: int +SHCNF_IDLIST: int +SHCNF_PATHA: int +SHCNF_PRINTERA: int +SHCNF_DWORD: int +SHCNF_PATHW: int +SHCNF_PRINTERW: int +SHCNF_TYPE: int +SHCNF_FLUSH: int +SHCNF_FLUSHNOWAIT: int +SHCNF_PATH: int +SHCNF_PRINTER: int +QIF_CACHED: int +QIF_DONTEXPANDFOLDER: int +SWFO_NEEDDISPATCH: int +SWFO_INCLUDEPENDING: int +SWFO_COOKIEPASSED: int +SWC_EXPLORER: int +SWC_BROWSER: int +SWC_3RDPARTY: int +SWC_CALLBACK: int +SWC_DESKTOP: int +SHARD_PIDL: int +SHARD_PATHA: int +SHARD_PATHW: int +SHARD_APPIDINFO: int +SHARD_APPIDINFOIDLIST: int +SHARD_LINK: int +SHARD_APPIDINFOLINK: int +SHARD_SHELLITEM: int +SHARD_PATH: int +SHGDFIL_FINDDATA: int +SHGDFIL_NETRESOURCE: int +SHGDFIL_DESCRIPTIONID: int +SHDID_ROOT_REGITEM: int +SHDID_FS_FILE: int +SHDID_FS_DIRECTORY: int +SHDID_FS_OTHER: int +SHDID_COMPUTER_DRIVE35: int +SHDID_COMPUTER_DRIVE525: int +SHDID_COMPUTER_REMOVABLE: int +SHDID_COMPUTER_FIXED: int +SHDID_COMPUTER_NETDRIVE: int +SHDID_COMPUTER_CDROM: int +SHDID_COMPUTER_RAMDISK: int +SHDID_COMPUTER_OTHER: int +SHDID_NET_DOMAIN: int +SHDID_NET_SERVER: int +SHDID_NET_SHARE: int +SHDID_NET_RESTOFNET: int +SHDID_NET_OTHER: int +PID_IS_URL: int +PID_IS_NAME: int +PID_IS_WORKINGDIR: int +PID_IS_HOTKEY: int +PID_IS_SHOWCMD: int +PID_IS_ICONINDEX: int +PID_IS_ICONFILE: int +PID_IS_WHATSNEW: int +PID_IS_AUTHOR: int +PID_IS_DESCRIPTION: int +PID_IS_COMMENT: int +PID_INTSITE_WHATSNEW: int +PID_INTSITE_AUTHOR: int +PID_INTSITE_LASTVISIT: int +PID_INTSITE_LASTMOD: int +PID_INTSITE_VISITCOUNT: int +PID_INTSITE_DESCRIPTION: int +PID_INTSITE_COMMENT: int +PID_INTSITE_FLAGS: int +PID_INTSITE_CONTENTLEN: int +PID_INTSITE_CONTENTCODE: int +PID_INTSITE_RECURSE: int +PID_INTSITE_WATCH: int +PID_INTSITE_SUBSCRIPTION: int +PID_INTSITE_URL: int +PID_INTSITE_TITLE: int +PID_INTSITE_CODEPAGE: int +PID_INTSITE_TRACKING: int +PIDISF_RECENTLYCHANGED: int +PIDISF_CACHEDSTICKY: int +PIDISF_CACHEIMAGES: int +PIDISF_FOLLOWALLLINKS: int +PIDISM_GLOBAL: int +PIDISM_WATCH: int +PIDISM_DONTWATCH: int +SSF_SHOWALLOBJECTS: int +SSF_SHOWEXTENSIONS: int +SSF_SHOWCOMPCOLOR: int +SSF_SHOWSYSFILES: int +SSF_DOUBLECLICKINWEBVIEW: int +SSF_SHOWATTRIBCOL: int +SSF_DESKTOPHTML: int +SSF_WIN95CLASSIC: int +SSF_DONTPRETTYPATH: int +SSF_SHOWINFOTIP: int +SSF_MAPNETDRVBUTTON: int +SSF_NOCONFIRMRECYCLE: int +SSF_HIDEICONS: int +ABM_NEW: int +ABM_REMOVE: int +ABM_QUERYPOS: int +ABM_SETPOS: int +ABM_GETSTATE: int +ABM_GETTASKBARPOS: int +ABM_ACTIVATE: int +ABM_GETAUTOHIDEBAR: int +ABM_SETAUTOHIDEBAR: int +ABM_WINDOWPOSCHANGED: int +ABN_STATECHANGE: int +ABN_POSCHANGED: int +ABN_FULLSCREENAPP: int +ABN_WINDOWARRANGE: int +ABS_AUTOHIDE: int +ABS_ALWAYSONTOP: int +ABE_LEFT: int +ABE_TOP: int +ABE_RIGHT: int +ABE_BOTTOM: int + +def EIRESID(x): ... + +SHCONTF_FOLDERS: int +SHCONTF_NONFOLDERS: int +SHCONTF_INCLUDEHIDDEN: int +SHCONTF_INIT_ON_FIRST_NEXT: int +SHCONTF_NETPRINTERSRCH: int +SHCONTF_SHAREABLE: int +SHCONTF_STORAGE: int +SHGDN_NORMAL: int +SHGDN_INFOLDER: int +SHGDN_FOREDITING: int +SHGDN_INCLUDE_NONFILESYS: int +SHGDN_FORADDRESSBAR: int +SHGDN_FORPARSING: int +BFO_NONE: int +BFO_BROWSER_PERSIST_SETTINGS: int +BFO_RENAME_FOLDER_OPTIONS_TOINTERNET: int +BFO_BOTH_OPTIONS: int +BIF_PREFER_INTERNET_SHORTCUT: int +BFO_BROWSE_NO_IN_NEW_PROCESS: int +BFO_ENABLE_HYPERLINK_TRACKING: int +BFO_USE_IE_OFFLINE_SUPPORT: int +BFO_SUBSTITUE_INTERNET_START_PAGE: int +BFO_USE_IE_LOGOBANDING: int +BFO_ADD_IE_TOCAPTIONBAR: int +BFO_USE_DIALUP_REF: int +BFO_USE_IE_TOOLBAR: int +BFO_NO_PARENT_FOLDER_SUPPORT: int +BFO_NO_REOPEN_NEXT_RESTART: int +BFO_GO_HOME_PAGE: int +BFO_PREFER_IEPROCESS: int +BFO_SHOW_NAVIGATION_CANCELLED: int +BFO_QUERY_ALL: int +PID_FINDDATA: int +PID_NETRESOURCE: int +PID_DESCRIPTIONID: int +PID_WHICHFOLDER: int +PID_NETWORKLOCATION: int +PID_COMPUTERNAME: int +PID_DISPLACED_FROM: int +PID_DISPLACED_DATE: int +PID_SYNC_COPY_IN: int +PID_MISC_STATUS: int +PID_MISC_ACCESSCOUNT: int +PID_MISC_OWNER: int +PID_HTMLINFOTIPFILE: int +PID_MISC_PICS: int +PID_DISPLAY_PROPERTIES: int +PID_INTROTEXT: int +PIDSI_ARTIST: int +PIDSI_SONGTITLE: int +PIDSI_ALBUM: int +PIDSI_YEAR: int +PIDSI_COMMENT: int +PIDSI_TRACK: int +PIDSI_GENRE: int +PIDSI_LYRICS: int +PIDDRSI_PROTECTED: int +PIDDRSI_DESCRIPTION: int +PIDDRSI_PLAYCOUNT: int +PIDDRSI_PLAYSTARTS: int +PIDDRSI_PLAYEXPIRES: int +PIDVSI_STREAM_NAME: int +PIDVSI_FRAME_WIDTH: int +PIDVSI_FRAME_HEIGHT: int +PIDVSI_TIMELENGTH: int +PIDVSI_FRAME_COUNT: int +PIDVSI_FRAME_RATE: int +PIDVSI_DATA_RATE: int +PIDVSI_SAMPLE_SIZE: int +PIDVSI_COMPRESSION: int +PIDVSI_STREAM_NUMBER: int +PIDASI_FORMAT: int +PIDASI_TIMELENGTH: int +PIDASI_AVG_DATA_RATE: int +PIDASI_SAMPLE_RATE: int +PIDASI_SAMPLE_SIZE: int +PIDASI_CHANNEL_COUNT: int +PIDASI_STREAM_NUMBER: int +PIDASI_STREAM_NAME: int +PIDASI_COMPRESSION: int +PID_CONTROLPANEL_CATEGORY: int +PID_VOLUME_FREE: int +PID_VOLUME_CAPACITY: int +PID_VOLUME_FILESYSTEM: int +PID_SHARE_CSC_STATUS: int +PID_LINK_TARGET: int +PID_QUERY_RANK: int +PROPSETFLAG_DEFAULT: int +PROPSETFLAG_NONSIMPLE: int +PROPSETFLAG_ANSI: int +PROPSETFLAG_UNBUFFERED: int +PROPSETFLAG_CASE_SENSITIVE: int +PROPSET_BEHAVIOR_CASE_SENSITIVE: int +PID_DICTIONARY: int +PID_CODEPAGE: int +PID_FIRST_USABLE: int +PID_FIRST_NAME_DEFAULT: int +PID_LOCALE: int +PID_MODIFY_TIME: int +PID_SECURITY: int +PID_BEHAVIOR: int +PID_ILLEGAL: int +PID_MIN_READONLY: int +PID_MAX_READONLY: int +PIDDI_THUMBNAIL: int +PIDSI_TITLE: int +PIDSI_SUBJECT: int +PIDSI_AUTHOR: int +PIDSI_KEYWORDS: int +PIDSI_COMMENTS: int +PIDSI_TEMPLATE: int +PIDSI_LASTAUTHOR: int +PIDSI_REVNUMBER: int +PIDSI_EDITTIME: int +PIDSI_LASTPRINTED: int +PIDSI_CREATE_DTM: int +PIDSI_LASTSAVE_DTM: int +PIDSI_PAGECOUNT: int +PIDSI_WORDCOUNT: int +PIDSI_CHARCOUNT: int +PIDSI_THUMBNAIL: int +PIDSI_APPNAME: int +PIDSI_DOC_SECURITY: int +PIDDSI_CATEGORY: int +PIDDSI_PRESFORMAT: int +PIDDSI_BYTECOUNT: int +PIDDSI_LINECOUNT: int +PIDDSI_PARCOUNT: int +PIDDSI_SLIDECOUNT: int +PIDDSI_NOTECOUNT: int +PIDDSI_HIDDENCOUNT: int +PIDDSI_MMCLIPCOUNT: int +PIDDSI_SCALE: int +PIDDSI_HEADINGPAIR: int +PIDDSI_DOCPARTS: int +PIDDSI_MANAGER: int +PIDDSI_COMPANY: int +PIDDSI_LINKSDIRTY: int +PIDMSI_EDITOR: int +PIDMSI_SUPPLIER: int +PIDMSI_SOURCE: int +PIDMSI_SEQUENCE_NO: int +PIDMSI_PROJECT: int +PIDMSI_STATUS: int +PIDMSI_OWNER: int +PIDMSI_RATING: int +PIDMSI_PRODUCTION: int +PIDMSI_COPYRIGHT: int +PRSPEC_INVALID: int +PRSPEC_LPWSTR: int +PRSPEC_PROPID: int +SHCIDS_ALLFIELDS: int +SHCIDS_CANONICALONLY: int +SHCIDS_BITMASK: int +SHCIDS_COLUMNMASK: int +SFGAO_CANMONIKER: int +SFGAO_HASSTORAGE: int +SFGAO_STREAM: int +SFGAO_STORAGEANCESTOR: int +SFGAO_STORAGECAPMASK: int +MAXPROPPAGES: int +PSP_DEFAULT: int +PSP_DLGINDIRECT: int +PSP_USEHICON: int +PSP_USEICONID: int +PSP_USETITLE: int +PSP_RTLREADING: int +PSP_HASHELP: int +PSP_USEREFPARENT: int +PSP_USECALLBACK: int +PSP_PREMATURE: int +PSP_HIDEHEADER: int +PSP_USEHEADERTITLE: int +PSP_USEHEADERSUBTITLE: int +PSP_USEFUSIONCONTEXT: int +PSPCB_ADDREF: int +PSPCB_RELEASE: int +PSPCB_CREATE: int +PSH_DEFAULT: int +PSH_PROPTITLE: int +PSH_USEHICON: int +PSH_USEICONID: int +PSH_PROPSHEETPAGE: int +PSH_WIZARDHASFINISH: int +PSH_WIZARD: int +PSH_USEPSTARTPAGE: int +PSH_NOAPPLYNOW: int +PSH_USECALLBACK: int +PSH_HASHELP: int +PSH_MODELESS: int +PSH_RTLREADING: int +PSH_WIZARDCONTEXTHELP: int +PSH_WIZARD97: int +PSH_WATERMARK: int +PSH_USEHBMWATERMARK: int +PSH_USEHPLWATERMARK: int +PSH_STRETCHWATERMARK: int +PSH_HEADER: int +PSH_USEHBMHEADER: int +PSH_USEPAGELANG: int +PSH_WIZARD_LITE: int +PSH_NOCONTEXTHELP: int +PSCB_INITIALIZED: int +PSCB_PRECREATE: int +PSCB_BUTTONPRESSED: int +PSNRET_NOERROR: int +PSNRET_INVALID: int +PSNRET_INVALID_NOCHANGEPAGE: int +PSNRET_MESSAGEHANDLED: int +PSWIZB_BACK: int +PSWIZB_NEXT: int +PSWIZB_FINISH: int +PSWIZB_DISABLEDFINISH: int +PSBTN_BACK: int +PSBTN_NEXT: int +PSBTN_FINISH: int +PSBTN_OK: int +PSBTN_APPLYNOW: int +PSBTN_CANCEL: int +PSBTN_HELP: int +PSBTN_MAX: int +ID_PSRESTARTWINDOWS: int +ID_PSREBOOTSYSTEM: Incomplete +WIZ_CXDLG: int +WIZ_CYDLG: int +WIZ_CXBMP: int +WIZ_BODYX: int +WIZ_BODYCX: int +PROP_SM_CXDLG: int +PROP_SM_CYDLG: int +PROP_MED_CXDLG: int +PROP_MED_CYDLG: int +PROP_LG_CXDLG: int +PROP_LG_CYDLG: int +ISOLATION_AWARE_USE_STATIC_LIBRARY: int +ISOLATION_AWARE_BUILD_STATIC_LIBRARY: int +SHCOLSTATE_TYPE_STR: int +SHCOLSTATE_TYPE_INT: int +SHCOLSTATE_TYPE_DATE: int +SHCOLSTATE_TYPEMASK: int +SHCOLSTATE_ONBYDEFAULT: int +SHCOLSTATE_SLOW: int +SHCOLSTATE_EXTENDED: int +SHCOLSTATE_SECONDARYUI: int +SHCOLSTATE_HIDDEN: int +SHCOLSTATE_PREFER_VARCMP: int +FWF_AUTOARRANGE: int +FWF_ABBREVIATEDNAMES: int +FWF_SNAPTOGRID: int +FWF_OWNERDATA: int +FWF_BESTFITWINDOW: int +FWF_DESKTOP: int +FWF_SINGLESEL: int +FWF_NOSUBFOLDERS: int +FWF_TRANSPARENT: int +FWF_NOCLIENTEDGE: int +FWF_NOSCROLL: int +FWF_ALIGNLEFT: int +FWF_NOICONS: int +FWF_SHOWSELALWAYS: int +FWF_NOVISIBLE: int +FWF_SINGLECLICKACTIVATE: int +FWF_NOWEBVIEW: int +FWF_HIDEFILENAMES: int +FWF_CHECKSELECT: int +FVM_FIRST: int +FVM_ICON: int +FVM_SMALLICON: int +FVM_LIST: int +FVM_DETAILS: int +FVM_THUMBNAIL: int +FVM_TILE: int +FVM_THUMBSTRIP: int +SVUIA_DEACTIVATE: int +SVUIA_ACTIVATE_NOFOCUS: int +SVUIA_ACTIVATE_FOCUS: int +SVUIA_INPLACEACTIVATE: int +SHCNRF_InterruptLevel: int +SHCNRF_ShellLevel: int +SHCNRF_RecursiveInterrupt: int +SHCNRF_NewDelivery: int +FD_CLSID: int +FD_SIZEPOINT: int +FD_ATTRIBUTES: int +FD_CREATETIME: int +FD_ACCESSTIME: int +FD_WRITESTIME: int +FD_FILESIZE: int +FD_PROGRESSUI: int +FD_LINKUI: int +ASSOCF_INIT_NOREMAPCLSID: int +ASSOCF_INIT_BYEXENAME: int +ASSOCF_OPEN_BYEXENAME: int +ASSOCF_INIT_DEFAULTTOSTAR: int +ASSOCF_INIT_DEFAULTTOFOLDER: int +ASSOCF_NOUSERSETTINGS: int +ASSOCF_NOTRUNCATE: int +ASSOCF_VERIFY: int +ASSOCF_REMAPRUNDLL: int +ASSOCF_NOFIXUPS: int +ASSOCF_IGNOREBASECLASS: int +ASSOCSTR_COMMAND: int +ASSOCSTR_EXECUTABLE: int +ASSOCSTR_FRIENDLYDOCNAME: int +ASSOCSTR_FRIENDLYAPPNAME: int +ASSOCSTR_NOOPEN: int +ASSOCSTR_SHELLNEWVALUE: int +ASSOCSTR_DDECOMMAND: int +ASSOCSTR_DDEIFEXEC: int +ASSOCSTR_DDEAPPLICATION: int +ASSOCSTR_DDETOPIC: int +ASSOCSTR_INFOTIP: int +ASSOCSTR_QUICKTIP: int +ASSOCSTR_TILEINFO: int +ASSOCSTR_CONTENTTYPE: int +ASSOCSTR_DEFAULTICON: int +ASSOCSTR_SHELLEXTENSION: int +ASSOCKEY_SHELLEXECCLASS: int +ASSOCKEY_APP: int +ASSOCKEY_CLASS: int +ASSOCKEY_BASECLASS: int +ASSOCDATA_MSIDESCRIPTOR: int +ASSOCDATA_NOACTIVATEHANDLER: int +ASSOCDATA_QUERYCLASSSTORE: int +ASSOCDATA_HASPERUSERASSOC: int +ASSOCDATA_EDITFLAGS: int +ASSOCDATA_VALUE: int +SHGVSPB_PERUSER: int +SHGVSPB_ALLUSERS: int +SHGVSPB_PERFOLDER: int +SHGVSPB_ALLFOLDERS: int +SHGVSPB_INHERIT: int +SHGVSPB_ROAM: int +SHGVSPB_NOAUTODEFAULTS: int +SHGVSPB_FOLDER: Incomplete +SHGVSPB_FOLDERNODEFAULTS: Incomplete +SHGVSPB_USERDEFAULTS: Incomplete +SHGVSPB_GLOBALDEAFAULTS: Incomplete +SFVM_REARRANGE: int +SFVM_ADDOBJECT: int +SFVM_REMOVEOBJECT: int +SFVM_UPDATEOBJECT: int +SFVM_GETSELECTEDOBJECTS: int +SFVM_SETITEMPOS: int +SFVM_SETCLIPBOARD: int +SFVM_SETPOINTS: int +SLDF_HAS_ID_LIST: int +SLDF_HAS_LINK_INFO: int +SLDF_HAS_NAME: int +SLDF_HAS_RELPATH: int +SLDF_HAS_WORKINGDIR: int +SLDF_HAS_ARGS: int +SLDF_HAS_ICONLOCATION: int +SLDF_UNICODE: int +SLDF_FORCE_NO_LINKINFO: int +SLDF_HAS_EXP_SZ: int +SLDF_RUN_IN_SEPARATE: int +SLDF_HAS_LOGO3ID: int +SLDF_HAS_DARWINID: int +SLDF_RUNAS_USER: int +SLDF_NO_PIDL_ALIAS: int +SLDF_FORCE_UNCNAME: int +SLDF_HAS_EXP_ICON_SZ: int +SLDF_RUN_WITH_SHIMLAYER: int +SLDF_RESERVED: int +EXP_SPECIAL_FOLDER_SIG: int +NT_CONSOLE_PROPS_SIG: int +NT_FE_CONSOLE_PROPS_SIG: int +EXP_DARWIN_ID_SIG: int +EXP_LOGO3_ID_SIG: int +EXP_SZ_ICON_SIG: int +EXP_SZ_LINK_SIG: int +IURL_SETURL_FL_GUESS_PROTOCOL: int +IURL_SETURL_FL_USE_DEFAULT_PROTOCOL: int +IURL_INVOKECOMMAND_FL_ALLOW_UI: int +IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB: int +IURL_INVOKECOMMAND_FL_DDEWAIT: int +IS_NORMAL: int +IS_FULLSCREEN: int +IS_SPLIT: int +IS_VALIDSIZESTATEBITS: Incomplete +IS_VALIDSTATEBITS: Incomplete +AD_APPLY_DYNAMICREFRESH: int +COMP_ELEM_ORIGINAL_CSI: int +COMP_ELEM_RESTORED_CSI: int +COMP_ELEM_CURITEMSTATE: int +COMP_ELEM_ALL: Incomplete +DTI_ADDUI_DEFAULT: int +DTI_ADDUI_DISPSUBWIZARD: int +DTI_ADDUI_POSITIONITEM: int +COMPONENT_DEFAULT_LEFT: int +COMPONENT_DEFAULT_TOP: int +SSM_CLEAR: int +SSM_SET: int +SSM_REFRESH: int +SSM_UPDATE: int +SCHEME_DISPLAY: int +SCHEME_EDIT: int +SCHEME_LOCAL: int +SCHEME_GLOBAL: int +SCHEME_REFRESH: int +SCHEME_UPDATE: int +SCHEME_DONOTUSE: int +SCHEME_CREATE: int +GADOF_DIRTY: int +EVCF_HASSETTINGS: int +EVCF_ENABLEBYDEFAULT: int +EVCF_REMOVEFROMLIST: int +EVCF_ENABLEBYDEFAULT_AUTO: int +EVCF_DONTSHOWIFZERO: int +EVCF_SETTINGSMODE: int +EVCF_OUTOFDISKSPACE: int +EVCCBF_LASTNOTIFICATION: int +EBO_NONE: int +EBO_NAVIGATEONCE: int +EBO_SHOWFRAMES: int +EBO_ALWAYSNAVIGATE: int +EBO_NOTRAVELLOG: int +EBO_NOWRAPPERWINDOW: int +EBF_NONE: int +EBF_SELECTFROMDATAOBJECT: int +EBF_NODROPTARGET: int +ECS_ENABLED: int +ECS_DISABLED: int +ECS_HIDDEN: int +ECS_CHECKBOX: int +ECS_CHECKED: int +ECF_HASSUBCOMMANDS: int +ECF_HASSPLITBUTTON: int +ECF_HIDELABEL: int +ECF_ISSEPARATOR: int +ECF_HASLUASHIELD: int +SIATTRIBFLAGS_AND: int +SIATTRIBFLAGS_OR: int +SIATTRIBFLAGS_APPCOMPAT: int +SIATTRIBFLAGS_MASK: int +SIGDN_NORMALDISPLAY: int +SIGDN_PARENTRELATIVEPARSING: int +SIGDN_DESKTOPABSOLUTEPARSING: int +SIGDN_PARENTRELATIVEEDITING: int +SIGDN_DESKTOPABSOLUTEEDITING: int +SIGDN_FILESYSPATH: int +SIGDN_URL: int +SIGDN_PARENTRELATIVEFORADDRESSBAR: int +SIGDN_PARENTRELATIVE: int +SICHINT_DISPLAY: Incomplete +SICHINT_ALLFIELDS: int +SICHINT_CANONICAL: int +ASSOCCLASS_SHELL_KEY: int +ASSOCCLASS_PROGID_KEY: int +ASSOCCLASS_PROGID_STR: int +ASSOCCLASS_CLSID_KEY: int +ASSOCCLASS_CLSID_STR: int +ASSOCCLASS_APP_KEY: int +ASSOCCLASS_APP_STR: int +ASSOCCLASS_SYSTEM_STR: int +ASSOCCLASS_FOLDER: int +ASSOCCLASS_STAR: int +NSTCS_HASEXPANDOS: int +NSTCS_HASLINES: int +NSTCS_SINGLECLICKEXPAND: int +NSTCS_FULLROWSELECT: int +NSTCS_SPRINGEXPAND: int +NSTCS_HORIZONTALSCROLL: int +NSTCS_ROOTHASEXPANDO: int +NSTCS_SHOWSELECTIONALWAYS: int +NSTCS_NOINFOTIP: int +NSTCS_EVENHEIGHT: int +NSTCS_NOREPLACEOPEN: int +NSTCS_DISABLEDRAGDROP: int +NSTCS_NOORDERSTREAM: int +NSTCS_RICHTOOLTIP: int +NSTCS_BORDER: int +NSTCS_NOEDITLABELS: int +NSTCS_TABSTOP: int +NSTCS_FAVORITESMODE: int +NSTCS_AUTOHSCROLL: int +NSTCS_FADEINOUTEXPANDOS: int +NSTCS_EMPTYTEXT: int +NSTCS_CHECKBOXES: int +NSTCS_PARTIALCHECKBOXES: int +NSTCS_EXCLUSIONCHECKBOXES: int +NSTCS_DIMMEDCHECKBOXES: int +NSTCS_NOINDENTCHECKS: int +NSTCS_ALLOWJUNCTIONS: int +NSTCS_SHOWTABSBUTTON: int +NSTCS_SHOWDELETEBUTTON: int +NSTCS_SHOWREFRESHBUTTON: int +NSTCRS_VISIBLE: int +NSTCRS_HIDDEN: int +NSTCRS_EXPANDED: int +NSTCIS_NONE: int +NSTCIS_SELECTED: int +NSTCIS_EXPANDED: int +NSTCIS_BOLD: int +NSTCIS_DISABLED: int +NSTCGNI_NEXT: int +NSTCGNI_NEXTVISIBLE: int +NSTCGNI_PREV: int +NSTCGNI_PREVVISIBLE: int +NSTCGNI_PARENT: int +NSTCGNI_CHILD: int +NSTCGNI_FIRSTVISIBLE: int +NSTCGNI_LASTVISIBLE: int +CLSID_ExplorerBrowser: str +IBrowserFrame_Methods: Incomplete +ICategorizer_Methods: Incomplete +ICategoryProvider_Methods: Incomplete +IContextMenu_Methods: Incomplete +IExplorerCommand_Methods: Incomplete +IExplorerCommandProvider_Methods: Incomplete +IOleWindow_Methods: Incomplete +IPersist_Methods: Incomplete +IPersistFolder_Methods: Incomplete +IPersistFolder2_Methods: Incomplete +IShellExtInit_Methods: Incomplete +IShellView_Methods: Incomplete +IShellFolder_Methods: Incomplete +IShellFolder2_Methods: Incomplete +GPS_DEFAULT: int +GPS_HANDLERPROPERTIESONLY: int +GPS_READWRITE: int +GPS_TEMPORARY: int +GPS_FASTPROPERTIESONLY: int +GPS_OPENSLOWITEM: int +GPS_DELAYCREATION: int +GPS_BESTEFFORT: int +GPS_MASK_VALID: int +STR_AVOID_DRIVE_RESTRICTION_POLICY: str +STR_BIND_DELEGATE_CREATE_OBJECT: str +STR_BIND_FOLDERS_READ_ONLY: str +STR_BIND_FOLDER_ENUM_MODE: str +STR_BIND_FORCE_FOLDER_SHORTCUT_RESOLVE: str +STR_DONT_PARSE_RELATIVE: str +STR_DONT_RESOLVE_LINK: str +STR_FILE_SYS_BIND_DATA: str +STR_GET_ASYNC_HANDLER: str +STR_GPS_BESTEFFORT: str +STR_GPS_DELAYCREATION: str +STR_GPS_FASTPROPERTIESONLY: str +STR_GPS_HANDLERPROPERTIESONLY: str +STR_GPS_NO_OPLOCK: str +STR_GPS_OPENSLOWITEM: str +STR_IFILTER_FORCE_TEXT_FILTER_FALLBACK: str +STR_IFILTER_LOAD_DEFINED_FILTER: str +STR_INTERNAL_NAVIGATE: str +STR_INTERNETFOLDER_PARSE_ONLY_URLMON_BINDABLE: str +STR_ITEM_CACHE_CONTEXT: str +STR_NO_VALIDATE_FILENAME_CHARS: str +STR_PARSE_ALLOW_INTERNET_SHELL_FOLDERS: str +STR_PARSE_AND_CREATE_ITEM: str +STR_PARSE_DONT_REQUIRE_VALIDATED_URLS: str +STR_PARSE_EXPLICIT_ASSOCIATION_SUCCESSFUL: str +STR_PARSE_PARTIAL_IDLIST: str +STR_PARSE_PREFER_FOLDER_BROWSING: str +STR_PARSE_PREFER_WEB_BROWSING: str +STR_PARSE_PROPERTYSTORE: str +STR_PARSE_SHELL_PROTOCOL_TO_FILE_OBJECTS: str +STR_PARSE_SHOW_NET_DIAGNOSTICS_UI: str +STR_PARSE_SKIP_NET_CACHE: str +STR_PARSE_TRANSLATE_ALIASES: str +STR_PARSE_WITH_EXPLICIT_ASSOCAPP: str +STR_PARSE_WITH_EXPLICIT_PROGID: str +STR_PARSE_WITH_PROPERTIES: str +STR_SKIP_BINDING_CLSID: str +STR_TRACK_CLSID: str +KF_REDIRECTION_CAPABILITIES_ALLOW_ALL: int +KF_REDIRECTION_CAPABILITIES_REDIRECTABLE: int +KF_REDIRECTION_CAPABILITIES_DENY_ALL: int +KF_REDIRECTION_CAPABILITIES_DENY_POLICY_REDIRECTED: int +KF_REDIRECTION_CAPABILITIES_DENY_POLICY: int +KF_REDIRECTION_CAPABILITIES_DENY_PERMISSIONS: int +KF_REDIRECT_USER_EXCLUSIVE: int +KF_REDIRECT_COPY_SOURCE_DACL: int +KF_REDIRECT_OWNER_USER: int +KF_REDIRECT_SET_OWNER_EXPLICIT: int +KF_REDIRECT_CHECK_ONLY: int +KF_REDIRECT_WITH_UI: int +KF_REDIRECT_UNPIN: int +KF_REDIRECT_PIN: int +KF_REDIRECT_COPY_CONTENTS: int +KF_REDIRECT_DEL_SOURCE_CONTENTS: int +KF_REDIRECT_EXCLUDE_ALL_KNOWN_SUBFOLDERS: int +KF_CATEGORY_VIRTUAL: int +KF_CATEGORY_FIXED: int +KF_CATEGORY_COMMON: int +KF_CATEGORY_PERUSER: int +FFFP_EXACTMATCH: int +FFFP_NEARESTPARENTMATCH: int +KF_FLAG_CREATE: int +KF_FLAG_DONT_VERIFY: int +KF_FLAG_DONT_UNEXPAND: int +KF_FLAG_NO_ALIAS: int +KF_FLAG_INIT: int +KF_FLAG_DEFAULT_PATH: int +KF_FLAG_NOT_PARENT_RELATIVE: int +KF_FLAG_SIMPLE_IDLIST: int +ADLT_RECENT: int +ADLT_FREQUENT: int +KDC_FREQUENT: int +KDC_RECENT: int +LFF_FORCEFILESYSTEM: int +LFF_STORAGEITEMS: int +LFF_ALLITEMS: int +DSFT_DETECT: int +DSFT_PRIVATE: int +DSFT_PUBLIC: int +LOF_DEFAULT: int +LOF_PINNEDTONAVPANE: int +LOF_MASK_ALL: int +LSF_FAILIFTHERE: int +LSF_OVERRIDEEXISTING: int +LSF_MAKEUNIQUENAME: int +TSF_NORMAL: int +TSF_FAIL_EXIST: int +TSF_RENAME_EXIST: int +TSF_OVERWRITE_EXIST: int +TSF_ALLOW_DECRYPTION: int +TSF_NO_SECURITY: int +TSF_COPY_CREATION_TIME: int +TSF_COPY_WRITE_TIME: int +TSF_USE_FULL_ACCESS: int +TSF_DELETE_RECYCLE_IF_POSSIBLE: int +TSF_COPY_HARD_LINK: int +TSF_COPY_LOCALIZED_NAME: int +TSF_MOVE_AS_COPY_DELETE: int +TSF_SUSPEND_SHELLEVENTS: int +TS_NONE: int +TS_PERFORMING: int +TS_PREPARING: int +TS_INDETERMINATE: int +COPYENGINE_S_YES: int +COPYENGINE_S_NOT_HANDLED: int +COPYENGINE_S_USER_RETRY: int +COPYENGINE_S_USER_IGNORED: int +COPYENGINE_S_MERGE: int +COPYENGINE_S_DONT_PROCESS_CHILDREN: int +COPYENGINE_S_ALREADY_DONE: int +COPYENGINE_S_PENDING: int +COPYENGINE_S_KEEP_BOTH: int +COPYENGINE_S_CLOSE_PROGRAM: int +COPYENGINE_S_COLLISIONRESOLVED: int +COPYENGINE_E_USER_CANCELLED: int +COPYENGINE_E_CANCELLED: int +COPYENGINE_E_REQUIRES_ELEVATION: int +COPYENGINE_E_SAME_FILE: int +COPYENGINE_E_DIFF_DIR: int +COPYENGINE_E_MANY_SRC_1_DEST: int +COPYENGINE_E_DEST_SUBTREE: int +COPYENGINE_E_DEST_SAME_TREE: int +COPYENGINE_E_FLD_IS_FILE_DEST: int +COPYENGINE_E_FILE_IS_FLD_DEST: int +COPYENGINE_E_FILE_TOO_LARGE: int +COPYENGINE_E_REMOVABLE_FULL: int +COPYENGINE_E_DEST_IS_RO_CD: int +COPYENGINE_E_DEST_IS_RW_CD: int +COPYENGINE_E_DEST_IS_R_CD: int +COPYENGINE_E_DEST_IS_RO_DVD: int +COPYENGINE_E_DEST_IS_RW_DVD: int +COPYENGINE_E_DEST_IS_R_DVD: int +COPYENGINE_E_SRC_IS_RO_CD: int +COPYENGINE_E_SRC_IS_RW_CD: int +COPYENGINE_E_SRC_IS_R_CD: int +COPYENGINE_E_SRC_IS_RO_DVD: int +COPYENGINE_E_SRC_IS_RW_DVD: int +COPYENGINE_E_SRC_IS_R_DVD: int +COPYENGINE_E_INVALID_FILES_SRC: int +COPYENGINE_E_INVALID_FILES_DEST: int +COPYENGINE_E_PATH_TOO_DEEP_SRC: int +COPYENGINE_E_PATH_TOO_DEEP_DEST: int +COPYENGINE_E_ROOT_DIR_SRC: int +COPYENGINE_E_ROOT_DIR_DEST: int +COPYENGINE_E_ACCESS_DENIED_SRC: int +COPYENGINE_E_ACCESS_DENIED_DEST: int +COPYENGINE_E_PATH_NOT_FOUND_SRC: int +COPYENGINE_E_PATH_NOT_FOUND_DEST: int +COPYENGINE_E_NET_DISCONNECT_SRC: int +COPYENGINE_E_NET_DISCONNECT_DEST: int +COPYENGINE_E_SHARING_VIOLATION_SRC: int +COPYENGINE_E_SHARING_VIOLATION_DEST: int +COPYENGINE_E_ALREADY_EXISTS_NORMAL: int +COPYENGINE_E_ALREADY_EXISTS_READONLY: int +COPYENGINE_E_ALREADY_EXISTS_SYSTEM: int +COPYENGINE_E_ALREADY_EXISTS_FOLDER: int +COPYENGINE_E_STREAM_LOSS: int +COPYENGINE_E_EA_LOSS: int +COPYENGINE_E_PROPERTY_LOSS: int +COPYENGINE_E_PROPERTIES_LOSS: int +COPYENGINE_E_ENCRYPTION_LOSS: int +COPYENGINE_E_DISK_FULL: int +COPYENGINE_E_DISK_FULL_CLEAN: int +COPYENGINE_E_EA_NOT_SUPPORTED: int +COPYENGINE_E_CANT_REACH_SOURCE: int +COPYENGINE_E_RECYCLE_UNKNOWN_ERROR: int +COPYENGINE_E_RECYCLE_FORCE_NUKE: int +COPYENGINE_E_RECYCLE_SIZE_TOO_BIG: int +COPYENGINE_E_RECYCLE_PATH_TOO_LONG: int +COPYENGINE_E_RECYCLE_BIN_NOT_FOUND: int +COPYENGINE_E_NEWFILE_NAME_TOO_LONG: int +COPYENGINE_E_NEWFOLDER_NAME_TOO_LONG: int +COPYENGINE_E_DIR_NOT_EMPTY: int +COPYENGINE_E_FAT_MAX_IN_ROOT: int +COPYENGINE_E_ACCESSDENIED_READONLY: int +COPYENGINE_E_REDIRECTED_TO_WEBPAGE: int +COPYENGINE_E_SERVER_BAD_FILE_TYPE: int +FOLDERID_NetworkFolder: str +FOLDERID_ComputerFolder: str +FOLDERID_InternetFolder: str +FOLDERID_ControlPanelFolder: str +FOLDERID_PrintersFolder: str +FOLDERID_SyncManagerFolder: str +FOLDERID_SyncSetupFolder: str +FOLDERID_ConflictFolder: str +FOLDERID_SyncResultsFolder: str +FOLDERID_RecycleBinFolder: str +FOLDERID_ConnectionsFolder: str +FOLDERID_Fonts: str +FOLDERID_Desktop: str +FOLDERID_Startup: str +FOLDERID_Programs: str +FOLDERID_StartMenu: str +FOLDERID_Recent: str +FOLDERID_SendTo: str +FOLDERID_Documents: str +FOLDERID_Favorites: str +FOLDERID_NetHood: str +FOLDERID_PrintHood: str +FOLDERID_Templates: str +FOLDERID_CommonStartup: str +FOLDERID_CommonPrograms: str +FOLDERID_CommonStartMenu: str +FOLDERID_PublicDesktop: str +FOLDERID_ProgramData: str +FOLDERID_CommonTemplates: str +FOLDERID_PublicDocuments: str +FOLDERID_RoamingAppData: str +FOLDERID_LocalAppData: str +FOLDERID_LocalAppDataLow: str +FOLDERID_InternetCache: str +FOLDERID_Cookies: str +FOLDERID_History: str +FOLDERID_System: str +FOLDERID_SystemX86: str +FOLDERID_Windows: str +FOLDERID_Profile: str +FOLDERID_Pictures: str +FOLDERID_ProgramFilesX86: str +FOLDERID_ProgramFilesCommonX86: str +FOLDERID_ProgramFilesX64: str +FOLDERID_ProgramFilesCommonX64: str +FOLDERID_ProgramFiles: str +FOLDERID_ProgramFilesCommon: str +FOLDERID_UserProgramFiles: str +FOLDERID_UserProgramFilesCommon: str +FOLDERID_AdminTools: str +FOLDERID_CommonAdminTools: str +FOLDERID_Music: str +FOLDERID_Videos: str +FOLDERID_Ringtones: str +FOLDERID_PublicPictures: str +FOLDERID_PublicMusic: str +FOLDERID_PublicVideos: str +FOLDERID_PublicRingtones: str +FOLDERID_ResourceDir: str +FOLDERID_LocalizedResourcesDir: str +FOLDERID_CommonOEMLinks: str +FOLDERID_CDBurning: str +FOLDERID_UserProfiles: str +FOLDERID_Playlists: str +FOLDERID_SamplePlaylists: str +FOLDERID_SampleMusic: str +FOLDERID_SamplePictures: str +FOLDERID_SampleVideos: str +FOLDERID_PhotoAlbums: str +FOLDERID_Public: str +FOLDERID_ChangeRemovePrograms: str +FOLDERID_AppUpdates: str +FOLDERID_AddNewPrograms: str +FOLDERID_Downloads: str +FOLDERID_PublicDownloads: str +FOLDERID_SavedSearches: str +FOLDERID_QuickLaunch: str +FOLDERID_Contacts: str +FOLDERID_SidebarParts: str +FOLDERID_SidebarDefaultParts: str +FOLDERID_PublicGameTasks: str +FOLDERID_GameTasks: str +FOLDERID_SavedGames: str +FOLDERID_Games: str +FOLDERID_SEARCH_MAPI: str +FOLDERID_SEARCH_CSC: str +FOLDERID_Links: str +FOLDERID_UsersFiles: str +FOLDERID_UsersLibraries: str +FOLDERID_SearchHome: str +FOLDERID_OriginalImages: str +FOLDERID_DocumentsLibrary: str +FOLDERID_MusicLibrary: str +FOLDERID_PicturesLibrary: str +FOLDERID_VideosLibrary: str +FOLDERID_RecordedTVLibrary: str +FOLDERID_HomeGroup: str +FOLDERID_HomeGroupCurrentUser: str +FOLDERID_DeviceMetadataStore: str +FOLDERID_Libraries: str +FOLDERID_PublicLibraries: str +FOLDERID_UserPinned: str +FOLDERID_ImplicitAppShortcuts: str +FOLDERID_AccountPictures: str +FOLDERID_PublicUserTiles: str +FOLDERID_AppsFolder: str +FOLDERID_StartMenuAllPrograms: str +FOLDERID_CommonStartMenuPlaces: str +FOLDERID_ApplicationShortcuts: str +FOLDERID_RoamingTiles: str +FOLDERID_RoamedTileImages: str +FOLDERID_Screenshots: str +FOLDERID_CameraRoll: str +FOLDERID_SkyDrive: str +FOLDERID_OneDrive: str +FOLDERID_SkyDriveDocuments: str +FOLDERID_SkyDrivePictures: str +FOLDERID_SkyDriveMusic: str +FOLDERID_SkyDriveCameraRoll: str +FOLDERID_SearchHistory: str +FOLDERID_SearchTemplates: str +FOLDERID_CameraRollLibrary: str +FOLDERID_SavedPictures: str +FOLDERID_SavedPicturesLibrary: str +FOLDERID_RetailDemo: str +FOLDERID_Device: str +FOLDERID_DevelopmentFiles: str +FOLDERID_Objects3D: str +FOLDERID_AppCaptures: str +FOLDERID_LocalDocuments: str +FOLDERID_LocalPictures: str +FOLDERID_LocalVideos: str +FOLDERID_LocalMusic: str +FOLDERID_LocalDownloads: str +FOLDERID_RecordedCalls: str +KF_FLAG_DEFAULT: int +KF_FLAG_FORCE_APP_DATA_REDIRECTION: int +KF_FLAG_RETURN_FILTER_REDIRECTION_TARGET: int +KF_FLAG_FORCE_PACKAGE_REDIRECTION: int +KF_FLAG_NO_PACKAGE_REDIRECTION: int +KF_FLAG_FORCE_APPCONTAINER_REDIRECTION: int +KF_FLAG_NO_APPCONTAINER_REDIRECTION: int +KF_FLAG_ALIAS_ONLY: int diff --git a/stubs/pywin32/win32comext/taskscheduler/__init__.pyi b/stubs/pywin32/win32comext/taskscheduler/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi b/stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi new file mode 100644 index 000000000000..b37d72241d5d --- /dev/null +++ b/stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi @@ -0,0 +1,83 @@ +import _win32typing + +CLSID_CTask: _win32typing.PyIID +CLSID_CTaskScheduler: _win32typing.PyIID +HIGH_PRIORITY_CLASS: int +IDLE_PRIORITY_CLASS: int +IID_IProvideTaskPage: _win32typing.PyIID +IID_IScheduledWorkItem: _win32typing.PyIID +IID_ITask: _win32typing.PyIID +IID_ITaskScheduler: _win32typing.PyIID +IID_ITaskTrigger: _win32typing.PyIID +NORMAL_PRIORITY_CLASS: int +REALTIME_PRIORITY_CLASS: int +SCHED_E_ACCOUNT_DBASE_CORRUPT: int +SCHED_E_ACCOUNT_INFORMATION_NOT_SET: int +SCHED_E_ACCOUNT_NAME_NOT_FOUND: int +SCHED_E_CANNOT_OPEN_TASK: int +SCHED_E_INVALID_TASK: int +SCHED_E_SERVICE_NOT_INSTALLED: int +SCHED_E_TASK_NOT_READY: int +SCHED_E_TASK_NOT_RUNNING: int +SCHED_E_TRIGGER_NOT_FOUND: int +SCHED_E_UNKNOWN_OBJECT_VERSION: int +SCHED_S_EVENT_TRIGGER: int +SCHED_S_TASK_DISABLED: int +SCHED_S_TASK_HAS_NOT_RUN: int +SCHED_S_TASK_NOT_SCHEDULED: int +SCHED_S_TASK_NO_MORE_RUNS: int +SCHED_S_TASK_NO_VALID_TRIGGERS: int +SCHED_S_TASK_READY: int +SCHED_S_TASK_RUNNING: int +SCHED_S_TASK_TERMINATED: int +TASKPAGE_SCHEDULE: int +TASKPAGE_SETTINGS: int +TASKPAGE_TASK: int +TASK_APRIL: int +TASK_AUGUST: int +TASK_DECEMBER: int +TASK_EVENT_TRIGGER_AT_LOGON: int +TASK_EVENT_TRIGGER_AT_SYSTEMSTART: int +TASK_EVENT_TRIGGER_ON_IDLE: int +TASK_FEBRUARY: int +TASK_FIRST_WEEK: int +TASK_FLAG_DELETE_WHEN_DONE: int +TASK_FLAG_DISABLED: int +TASK_FLAG_DONT_START_IF_ON_BATTERIES: int +TASK_FLAG_HIDDEN: int +TASK_FLAG_INTERACTIVE: int +TASK_FLAG_KILL_IF_GOING_ON_BATTERIES: int +TASK_FLAG_KILL_ON_IDLE_END: int +TASK_FLAG_RESTART_ON_IDLE_RESUME: int +TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET: int +TASK_FLAG_RUN_ONLY_IF_DOCKED: int +TASK_FLAG_RUN_ONLY_IF_LOGGED_ON: int +TASK_FLAG_START_ONLY_IF_IDLE: int +TASK_FLAG_SYSTEM_REQUIRED: int +TASK_FOURTH_WEEK: int +TASK_FRIDAY: int +TASK_JANUARY: int +TASK_JULY: int +TASK_JUNE: int +TASK_LAST_WEEK: int +TASK_MARCH: int +TASK_MAY: int +TASK_MONDAY: int +TASK_NOVEMBER: int +TASK_OCTOBER: int +TASK_SATURDAY: int +TASK_SECOND_WEEK: int +TASK_SEPTEMBER: int +TASK_SUNDAY: int +TASK_THIRD_WEEK: int +TASK_THURSDAY: int +TASK_TIME_TRIGGER_DAILY: int +TASK_TIME_TRIGGER_MONTHLYDATE: int +TASK_TIME_TRIGGER_MONTHLYDOW: int +TASK_TIME_TRIGGER_ONCE: int +TASK_TIME_TRIGGER_WEEKLY: int +TASK_TRIGGER_FLAG_DISABLED: int +TASK_TRIGGER_FLAG_HAS_END_DATE: int +TASK_TRIGGER_FLAG_KILL_AT_DURATION_END: int +TASK_TUESDAY: int +TASK_WEDNESDAY: int diff --git a/stubs/pywin32/win32con.pyi b/stubs/pywin32/win32con.pyi new file mode 100644 index 000000000000..54cfd26a805f --- /dev/null +++ b/stubs/pywin32/win32con.pyi @@ -0,0 +1 @@ +from win32.lib.win32con import * diff --git a/stubs/pywin32/win32console.pyi b/stubs/pywin32/win32console.pyi new file mode 100644 index 000000000000..f8539ed68b25 --- /dev/null +++ b/stubs/pywin32/win32console.pyi @@ -0,0 +1 @@ +from win32.win32console import * diff --git a/stubs/pywin32/win32cred.pyi b/stubs/pywin32/win32cred.pyi new file mode 100644 index 000000000000..6cb3e268e445 --- /dev/null +++ b/stubs/pywin32/win32cred.pyi @@ -0,0 +1 @@ +from win32.win32cred import * diff --git a/stubs/pywin32/win32crypt.pyi b/stubs/pywin32/win32crypt.pyi new file mode 100644 index 000000000000..223df5e3f82c --- /dev/null +++ b/stubs/pywin32/win32crypt.pyi @@ -0,0 +1 @@ +from win32.win32crypt import * diff --git a/stubs/pywin32/win32cryptcon.pyi b/stubs/pywin32/win32cryptcon.pyi new file mode 100644 index 000000000000..6df8b4407775 --- /dev/null +++ b/stubs/pywin32/win32cryptcon.pyi @@ -0,0 +1 @@ +from win32.lib.win32cryptcon import * diff --git a/stubs/pywin32/win32event.pyi b/stubs/pywin32/win32event.pyi new file mode 100644 index 000000000000..53191d417c02 --- /dev/null +++ b/stubs/pywin32/win32event.pyi @@ -0,0 +1 @@ +from win32.win32event import * diff --git a/stubs/pywin32/win32evtlog.pyi b/stubs/pywin32/win32evtlog.pyi new file mode 100644 index 000000000000..7c7ffe5ca0e5 --- /dev/null +++ b/stubs/pywin32/win32evtlog.pyi @@ -0,0 +1 @@ +from win32.win32evtlog import * diff --git a/stubs/pywin32/win32evtlogutil.pyi b/stubs/pywin32/win32evtlogutil.pyi new file mode 100644 index 000000000000..c37e5dd7b8af --- /dev/null +++ b/stubs/pywin32/win32evtlogutil.pyi @@ -0,0 +1 @@ +from win32.lib.win32evtlogutil import * diff --git a/stubs/pywin32/win32file.pyi b/stubs/pywin32/win32file.pyi new file mode 100644 index 000000000000..3a703a9739bc --- /dev/null +++ b/stubs/pywin32/win32file.pyi @@ -0,0 +1 @@ +from win32.win32file import * diff --git a/stubs/pywin32/win32gui.pyi b/stubs/pywin32/win32gui.pyi new file mode 100644 index 000000000000..3b2b41ae5c01 --- /dev/null +++ b/stubs/pywin32/win32gui.pyi @@ -0,0 +1 @@ +from win32.win32gui import * diff --git a/stubs/pywin32/win32gui_struct.pyi b/stubs/pywin32/win32gui_struct.pyi new file mode 100644 index 000000000000..3c7cd0a8a581 --- /dev/null +++ b/stubs/pywin32/win32gui_struct.pyi @@ -0,0 +1 @@ +from win32.lib.win32gui_struct import * diff --git a/stubs/pywin32/win32help.pyi b/stubs/pywin32/win32help.pyi new file mode 100644 index 000000000000..bd6fce5076c5 --- /dev/null +++ b/stubs/pywin32/win32help.pyi @@ -0,0 +1 @@ +from win32.win32help import * diff --git a/stubs/pywin32/win32inet.pyi b/stubs/pywin32/win32inet.pyi new file mode 100644 index 000000000000..98e6e47ff79a --- /dev/null +++ b/stubs/pywin32/win32inet.pyi @@ -0,0 +1 @@ +from win32.win32inet import * diff --git a/stubs/pywin32/win32inetcon.pyi b/stubs/pywin32/win32inetcon.pyi new file mode 100644 index 000000000000..db893b68d327 --- /dev/null +++ b/stubs/pywin32/win32inetcon.pyi @@ -0,0 +1 @@ +from win32.lib.win32inetcon import * diff --git a/stubs/pywin32/win32job.pyi b/stubs/pywin32/win32job.pyi new file mode 100644 index 000000000000..9c8f7891eb3d --- /dev/null +++ b/stubs/pywin32/win32job.pyi @@ -0,0 +1 @@ +from win32.win32job import * diff --git a/stubs/pywin32/win32lz.pyi b/stubs/pywin32/win32lz.pyi new file mode 100644 index 000000000000..64281098af98 --- /dev/null +++ b/stubs/pywin32/win32lz.pyi @@ -0,0 +1 @@ +from win32.win32lz import * diff --git a/stubs/pywin32/win32net.pyi b/stubs/pywin32/win32net.pyi new file mode 100644 index 000000000000..f318e55d74f0 --- /dev/null +++ b/stubs/pywin32/win32net.pyi @@ -0,0 +1 @@ +from win32.win32net import * diff --git a/stubs/pywin32/win32netcon.pyi b/stubs/pywin32/win32netcon.pyi new file mode 100644 index 000000000000..f86b2ef4ba93 --- /dev/null +++ b/stubs/pywin32/win32netcon.pyi @@ -0,0 +1 @@ +from win32.lib.win32netcon import * diff --git a/stubs/pywin32/win32pdh.pyi b/stubs/pywin32/win32pdh.pyi new file mode 100644 index 000000000000..739ad216e73f --- /dev/null +++ b/stubs/pywin32/win32pdh.pyi @@ -0,0 +1 @@ +from win32.win32pdh import * diff --git a/stubs/pywin32/win32pdhquery.pyi b/stubs/pywin32/win32pdhquery.pyi new file mode 100644 index 000000000000..2d0976fbbdac --- /dev/null +++ b/stubs/pywin32/win32pdhquery.pyi @@ -0,0 +1 @@ +from win32.lib.win32pdhquery import * diff --git a/stubs/pywin32/win32pipe.pyi b/stubs/pywin32/win32pipe.pyi new file mode 100644 index 000000000000..bf607d6b0d76 --- /dev/null +++ b/stubs/pywin32/win32pipe.pyi @@ -0,0 +1 @@ +from win32.win32pipe import * diff --git a/stubs/pywin32/win32print.pyi b/stubs/pywin32/win32print.pyi new file mode 100644 index 000000000000..ad2515011cce --- /dev/null +++ b/stubs/pywin32/win32print.pyi @@ -0,0 +1 @@ +from win32.win32print import * diff --git a/stubs/pywin32/win32process.pyi b/stubs/pywin32/win32process.pyi new file mode 100644 index 000000000000..86b050b2b958 --- /dev/null +++ b/stubs/pywin32/win32process.pyi @@ -0,0 +1 @@ +from win32.win32process import * diff --git a/stubs/pywin32/win32profile.pyi b/stubs/pywin32/win32profile.pyi new file mode 100644 index 000000000000..b89eef14bbe1 --- /dev/null +++ b/stubs/pywin32/win32profile.pyi @@ -0,0 +1 @@ +from win32.win32profile import * diff --git a/stubs/pywin32/win32ras.pyi b/stubs/pywin32/win32ras.pyi new file mode 100644 index 000000000000..455d2763b253 --- /dev/null +++ b/stubs/pywin32/win32ras.pyi @@ -0,0 +1 @@ +from win32.win32ras import * diff --git a/stubs/pywin32/win32security.pyi b/stubs/pywin32/win32security.pyi new file mode 100644 index 000000000000..bc0b8d20e5ef --- /dev/null +++ b/stubs/pywin32/win32security.pyi @@ -0,0 +1 @@ +from win32.win32security import * diff --git a/stubs/pywin32/win32service.pyi b/stubs/pywin32/win32service.pyi new file mode 100644 index 000000000000..b98158e9ab96 --- /dev/null +++ b/stubs/pywin32/win32service.pyi @@ -0,0 +1 @@ +from win32.win32service import * diff --git a/stubs/pywin32/win32serviceutil.pyi b/stubs/pywin32/win32serviceutil.pyi new file mode 100644 index 000000000000..1e989b027342 --- /dev/null +++ b/stubs/pywin32/win32serviceutil.pyi @@ -0,0 +1 @@ +from win32.lib.win32serviceutil import * diff --git a/stubs/pywin32/win32timezone.pyi b/stubs/pywin32/win32timezone.pyi new file mode 100644 index 000000000000..bd22d6774596 --- /dev/null +++ b/stubs/pywin32/win32timezone.pyi @@ -0,0 +1 @@ +from win32.lib.win32timezone import * diff --git a/stubs/pywin32/win32trace.pyi b/stubs/pywin32/win32trace.pyi new file mode 100644 index 000000000000..3ece62970b26 --- /dev/null +++ b/stubs/pywin32/win32trace.pyi @@ -0,0 +1 @@ +from win32.win32trace import * diff --git a/stubs/pywin32/win32transaction.pyi b/stubs/pywin32/win32transaction.pyi new file mode 100644 index 000000000000..bd529b0919a1 --- /dev/null +++ b/stubs/pywin32/win32transaction.pyi @@ -0,0 +1 @@ +from win32.win32transaction import * diff --git a/stubs/pywin32/win32ts.pyi b/stubs/pywin32/win32ts.pyi new file mode 100644 index 000000000000..dd0d8a231ffd --- /dev/null +++ b/stubs/pywin32/win32ts.pyi @@ -0,0 +1 @@ +from win32.win32ts import * diff --git a/stubs/pywin32/win32ui.pyi b/stubs/pywin32/win32ui.pyi new file mode 100644 index 000000000000..49ea5db902f4 --- /dev/null +++ b/stubs/pywin32/win32ui.pyi @@ -0,0 +1 @@ +from pythonwin.win32ui import * diff --git a/stubs/pywin32/win32uiole.pyi b/stubs/pywin32/win32uiole.pyi new file mode 100644 index 000000000000..b0ae818da649 --- /dev/null +++ b/stubs/pywin32/win32uiole.pyi @@ -0,0 +1 @@ +from pythonwin.win32uiole import * diff --git a/stubs/pywin32/win32verstamp.pyi b/stubs/pywin32/win32verstamp.pyi new file mode 100644 index 000000000000..a1f2de1e1c08 --- /dev/null +++ b/stubs/pywin32/win32verstamp.pyi @@ -0,0 +1 @@ +from win32.lib.win32verstamp import * diff --git a/stubs/pywin32/win32wnet.pyi b/stubs/pywin32/win32wnet.pyi new file mode 100644 index 000000000000..67facc0ca7b5 --- /dev/null +++ b/stubs/pywin32/win32wnet.pyi @@ -0,0 +1 @@ +from win32.win32wnet import * diff --git a/stubs/pywin32/winerror.pyi b/stubs/pywin32/winerror.pyi new file mode 100644 index 000000000000..d0bdce6c46ed --- /dev/null +++ b/stubs/pywin32/winerror.pyi @@ -0,0 +1 @@ +from win32.lib.winerror import * diff --git a/stubs/pywin32/winioctlcon.pyi b/stubs/pywin32/winioctlcon.pyi new file mode 100644 index 000000000000..6e51730f91b1 --- /dev/null +++ b/stubs/pywin32/winioctlcon.pyi @@ -0,0 +1 @@ +from win32.lib.winioctlcon import * diff --git a/stubs/pywin32/winnt.pyi b/stubs/pywin32/winnt.pyi new file mode 100644 index 000000000000..8bbdea596d2f --- /dev/null +++ b/stubs/pywin32/winnt.pyi @@ -0,0 +1 @@ +from win32.lib.winnt import * diff --git a/stubs/pywin32/winperf.pyi b/stubs/pywin32/winperf.pyi new file mode 100644 index 000000000000..d3138f48c8bd --- /dev/null +++ b/stubs/pywin32/winperf.pyi @@ -0,0 +1 @@ +from win32.lib.winperf import * diff --git a/stubs/pywin32/winxpgui.pyi b/stubs/pywin32/winxpgui.pyi new file mode 100644 index 000000000000..9a8e6233d577 --- /dev/null +++ b/stubs/pywin32/winxpgui.pyi @@ -0,0 +1 @@ +from win32.winxpgui import * diff --git a/stubs/pywin32/winxptheme.pyi b/stubs/pywin32/winxptheme.pyi new file mode 100644 index 000000000000..e4b09f60be7e --- /dev/null +++ b/stubs/pywin32/winxptheme.pyi @@ -0,0 +1 @@ +from win32.lib.winxptheme import * diff --git a/stubs/pyxdg/@tests/stubtest_allowlist.txt b/stubs/pyxdg/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..18311a04da36 --- /dev/null +++ b/stubs/pyxdg/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +xdg.IconTheme.basedir # This is a side-effect of a for loop rather than an intended part of the API. +xdg.DesktopEntry.DesktopEntry.checkCategorie # Exists for backwards compatibility. diff --git a/stubs/pyxdg/@tests/test_cases/check_IniFile.py b/stubs/pyxdg/@tests/test_cases/check_IniFile.py new file mode 100644 index 000000000000..2ca08cf09d36 --- /dev/null +++ b/stubs/pyxdg/@tests/test_cases/check_IniFile.py @@ -0,0 +1,278 @@ +from __future__ import annotations + +import re +from typing_extensions import assert_type + +from xdg.IniFile import IniFile + +# The "get" method is quite complex with many overloads. Check that many forms +# are valid. +# The function definition is: +# def get(self, key, group=None, locale=False, type="string", list=False, strict=False): + +# Get str +assert_type(IniFile().get("some_key"), str) +assert_type(IniFile().get("some_key", None), str) +assert_type(IniFile().get("some_key", "group"), str) +assert_type(IniFile().get("some_key", "group", False), str) +assert_type(IniFile().get("some_key", "group", True), str) +assert_type(IniFile().get("some_key", "group", True, "string"), str) +assert_type(IniFile().get("some_key", "group", True, "string", False), str) +assert_type(IniFile().get("some_key", "group", True, "string", False, False), str) +assert_type(IniFile().get("some_key", "group", True, "string", False, True), str) +# Keyword parameters +assert_type(IniFile().get("some_key", group=None), str) +assert_type(IniFile().get("some_key", group="group"), str) +assert_type(IniFile().get("some_key", locale=False), str) +assert_type(IniFile().get("some_key", locale=True), str) +assert_type(IniFile().get("some_key", strict=False), str) +assert_type(IniFile().get("some_key", strict=True), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True), str) +# Explicitly set type as string in keyword parameters. +assert_type(IniFile().get("some_key", type="string"), str) +assert_type(IniFile().get("some_key", group=None, type="string"), str) +assert_type(IniFile().get("some_key", group="group", type="string"), str) +assert_type(IniFile().get("some_key", locale=False, type="string"), str) +assert_type(IniFile().get("some_key", locale=True, type="string"), str) +assert_type(IniFile().get("some_key", strict=False, type="string"), str) +assert_type(IniFile().get("some_key", strict=True, type="string"), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, type="string"), str) +# Explicitly set list. +assert_type(IniFile().get("some_key", list=False), str) +assert_type(IniFile().get("some_key", group=None, list=False), str) +assert_type(IniFile().get("some_key", group="group", list=False), str) +assert_type(IniFile().get("some_key", locale=False, list=False), str) +assert_type(IniFile().get("some_key", locale=True, list=False), str) +assert_type(IniFile().get("some_key", strict=False, list=False), str) +assert_type(IniFile().get("some_key", strict=True, list=False), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=False), str) +# Explicitly set both. +assert_type(IniFile().get("some_key", list=False, type="string"), str) +assert_type(IniFile().get("some_key", group=None, list=False, type="string"), str) +assert_type(IniFile().get("some_key", group="group", list=False, type="string"), str) +assert_type(IniFile().get("some_key", locale=False, list=False, type="string"), str) +assert_type(IniFile().get("some_key", locale=True, list=False, type="string"), str) +assert_type(IniFile().get("some_key", strict=False, list=False, type="string"), str) +assert_type(IniFile().get("some_key", strict=True, list=False, type="string"), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=False, type="string"), str) + +# Get list[str] +assert_type(IniFile().get("some_key", "group", True, "string", True), list[str]) +assert_type(IniFile().get("some_key", "group", True, "string", True, False), list[str]) +assert_type(IniFile().get("some_key", "group", True, "string", True, True), list[str]) +# Keyword parameters +assert_type(IniFile().get("some_key", list=True, group=None), list[str]) +assert_type(IniFile().get("some_key", list=True, group="group"), list[str]) +assert_type(IniFile().get("some_key", list=True, locale=False), list[str]) +assert_type(IniFile().get("some_key", list=True, locale=True), list[str]) +assert_type(IniFile().get("some_key", list=True, strict=False), list[str]) +assert_type(IniFile().get("some_key", list=True, strict=True), list[str]) +assert_type(IniFile().get("some_key", list=True, group="group", locale=True, strict=True), list[str]) +# Explicitly set list +assert_type(IniFile().get("some_key", list=True), list[str]) +assert_type(IniFile().get("some_key", group=None, list=True), list[str]) +assert_type(IniFile().get("some_key", group="group", list=True), list[str]) +assert_type(IniFile().get("some_key", locale=False, list=True), list[str]) +assert_type(IniFile().get("some_key", locale=True, list=True), list[str]) +assert_type(IniFile().get("some_key", strict=False, list=True), list[str]) +assert_type(IniFile().get("some_key", strict=True, list=True), list[str]) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=True), list[str]) +# Explicitly set both +assert_type(IniFile().get("some_key", list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", group=None, list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", group="group", list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", locale=False, list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", locale=True, list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", strict=False, list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", strict=True, list=True, type="string"), list[str]) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=True, type="string"), list[str]) + +# Get bool +assert_type(IniFile().get("some_key", "group", True, "boolean"), bool) +assert_type(IniFile().get("some_key", "group", True, "boolean", False), bool) +assert_type(IniFile().get("some_key", "group", True, "boolean", False, False), bool) +assert_type(IniFile().get("some_key", "group", True, "boolean", False, True), bool) +# Keyword parameters +assert_type(IniFile().get("some_key", type="boolean"), bool) +assert_type(IniFile().get("some_key", type="boolean", group=None), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group"), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=False), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=True), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=False), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=True), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group", locale=True, strict=True), bool) +# Explicitly set list +assert_type(IniFile().get("some_key", type="boolean", list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", group=None, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group", list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=False, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=True, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=False, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=True, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group", locale=True, strict=True, list=False), bool) + +# Get list[bool] +assert_type(IniFile().get("some_key", "group", True, "boolean", True), list[bool]) +assert_type(IniFile().get("some_key", "group", True, "boolean", True, False), list[bool]) +assert_type(IniFile().get("some_key", "group", True, "boolean", True, True), list[bool]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="boolean", list=True), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, group=None), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, group="group"), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, locale=False), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, locale=True), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, strict=False), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, strict=True), list[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, group="group", locale=True, strict=True), list[bool]) + +# Get int +assert_type(IniFile().get("some_key", "group", True, "integer"), int) +assert_type(IniFile().get("some_key", "group", True, "integer", False), int) +assert_type(IniFile().get("some_key", "group", True, "integer", False, False), int) +assert_type(IniFile().get("some_key", "group", True, "integer", False, True), int) +# Keyword parameters +assert_type(IniFile().get("some_key", type="integer"), int) +assert_type(IniFile().get("some_key", type="integer", group=None), int) +assert_type(IniFile().get("some_key", type="integer", group="group"), int) +assert_type(IniFile().get("some_key", type="integer", locale=False), int) +assert_type(IniFile().get("some_key", type="integer", locale=True), int) +assert_type(IniFile().get("some_key", type="integer", strict=False), int) +assert_type(IniFile().get("some_key", type="integer", strict=True), int) +assert_type(IniFile().get("some_key", type="integer", group="group", locale=True, strict=True), int) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="integer", list=False), int) +assert_type(IniFile().get("some_key", type="integer", group=None, list=False), int) +assert_type(IniFile().get("some_key", type="integer", group="group", list=False), int) +assert_type(IniFile().get("some_key", type="integer", locale=False, list=False), int) +assert_type(IniFile().get("some_key", type="integer", locale=True, list=False), int) +assert_type(IniFile().get("some_key", type="integer", strict=False, list=False), int) +assert_type(IniFile().get("some_key", type="integer", strict=True, list=False), int) +assert_type(IniFile().get("some_key", type="integer", group="group", locale=True, strict=True, list=False), int) + +# Get list[int] +assert_type(IniFile().get("some_key", "group", True, "integer", True), list[int]) +assert_type(IniFile().get("some_key", "group", True, "integer", True, False), list[int]) +assert_type(IniFile().get("some_key", "group", True, "integer", True, True), list[int]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="integer", list=True), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, group=None), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, group="group"), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, locale=False), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, locale=True), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, strict=False), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, strict=True), list[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, group="group", locale=True, strict=True), list[int]) + +# Get float +assert_type(IniFile().get("some_key", "group", True, "numeric"), float) +assert_type(IniFile().get("some_key", "group", True, "numeric", False), float) +assert_type(IniFile().get("some_key", "group", True, "numeric", False, False), float) +assert_type(IniFile().get("some_key", "group", True, "numeric", False, True), float) +# Keyword parameters +assert_type(IniFile().get("some_key", type="numeric"), float) +assert_type(IniFile().get("some_key", type="numeric", group=None), float) +assert_type(IniFile().get("some_key", type="numeric", group="group"), float) +assert_type(IniFile().get("some_key", type="numeric", locale=False), float) +assert_type(IniFile().get("some_key", type="numeric", locale=True), float) +assert_type(IniFile().get("some_key", type="numeric", strict=False), float) +assert_type(IniFile().get("some_key", type="numeric", strict=True), float) +assert_type(IniFile().get("some_key", type="numeric", group="group", locale=True, strict=True), float) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="numeric", list=False), float) +assert_type(IniFile().get("some_key", type="numeric", group=None, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", group="group", list=False), float) +assert_type(IniFile().get("some_key", type="numeric", locale=False, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", locale=True, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", strict=False, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", strict=True, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", group="group", locale=True, strict=True, list=False), float) + +# Get list[float] +assert_type(IniFile().get("some_key", "group", True, "numeric", True), list[float]) +assert_type(IniFile().get("some_key", "group", True, "numeric", True, False), list[float]) +assert_type(IniFile().get("some_key", "group", True, "numeric", True, True), list[float]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="numeric", list=True), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, group=None), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, group="group"), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, locale=False), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, locale=True), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, strict=False), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, strict=True), list[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, group="group", locale=True, strict=True), list[float]) + +# Get regex +assert_type(IniFile().get("some_key", "group", True, "regex"), re.Pattern[str]) +assert_type(IniFile().get("some_key", "group", True, "regex", False), re.Pattern[str]) +assert_type(IniFile().get("some_key", "group", True, "regex", False, False), re.Pattern[str]) +assert_type(IniFile().get("some_key", "group", True, "regex", False, True), re.Pattern[str]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="regex"), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group=None), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group"), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=True), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=True), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group", locale=True, strict=True), re.Pattern[str]) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="regex", list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group=None, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group", list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=False, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=True, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=False, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=True, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group", locale=True, strict=True, list=False), re.Pattern[str]) + +# Get list[regex] +assert_type(IniFile().get("some_key", "group", True, "regex", True), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", "group", True, "regex", True, False), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", "group", True, "regex", True, True), list[re.Pattern[str]]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="regex", list=True), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, group=None), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, group="group"), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, locale=False), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, locale=True), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, strict=False), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, strict=True), list[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, group="group", locale=True, strict=True), list[re.Pattern[str]]) + +# Get point +assert_type(IniFile().get("some_key", "group", True, "point"), tuple[int, int]) +assert_type(IniFile().get("some_key", "group", True, "point", False), tuple[int, int]) +assert_type(IniFile().get("some_key", "group", True, "point", False, False), tuple[int, int]) +assert_type(IniFile().get("some_key", "group", True, "point", False, True), tuple[int, int]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="point"), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group=None), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group"), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=True), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=True), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group", locale=True, strict=True), tuple[int, int]) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="point", list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group=None, list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group", list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=False, list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=True, list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=False, list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=True, list=False), tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group", locale=True, strict=True, list=False), tuple[int, int]) + +# Get list[point] +assert_type(IniFile().get("some_key", "group", True, "point", True), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", "group", True, "point", True, False), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", "group", True, "point", True, True), list[tuple[int, int]]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="point", list=True), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, group=None), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, group="group"), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, locale=False), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, locale=True), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, strict=False), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, strict=True), list[tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, group="group", locale=True, strict=True), list[tuple[int, int]]) diff --git a/stubs/pyxdg/METADATA.toml b/stubs/pyxdg/METADATA.toml new file mode 100644 index 000000000000..a0370c6a8b74 --- /dev/null +++ b/stubs/pyxdg/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.28.*" +upstream-repository = "https://github.com/takluyver/pyxdg" diff --git a/stubs/pyxdg/xdg/BaseDirectory.pyi b/stubs/pyxdg/xdg/BaseDirectory.pyi new file mode 100644 index 000000000000..6c39679d8a20 --- /dev/null +++ b/stubs/pyxdg/xdg/BaseDirectory.pyi @@ -0,0 +1,18 @@ +from _typeshed import StrPath +from collections.abc import Iterator + +xdg_data_home: str +xdg_data_dirs: list[str] +xdg_config_home: str +xdg_config_dirs: list[str] +xdg_cache_home: str +xdg_state_home: str + +def save_config_path(*resource: StrPath) -> str: ... +def save_data_path(*resource: StrPath) -> str: ... +def save_cache_path(*resource: StrPath) -> str: ... +def save_state_path(*resource: StrPath) -> str: ... +def load_config_paths(*resource: StrPath) -> Iterator[str]: ... +def load_first_config(*resource: StrPath) -> str: ... +def load_data_paths(*resource: StrPath) -> Iterator[str]: ... +def get_runtime_dir(strict: bool = True) -> str: ... diff --git a/stubs/pyxdg/xdg/Config.pyi b/stubs/pyxdg/xdg/Config.pyi new file mode 100644 index 000000000000..d0866c29d7b5 --- /dev/null +++ b/stubs/pyxdg/xdg/Config.pyi @@ -0,0 +1,13 @@ +language: str +windowmanager: str | None +icon_theme: str +icon_size: int +cache_time: int +root_mode: bool + +def setWindowManager(wm: str) -> None: ... +def setIconTheme(theme: str) -> None: ... +def setIconSize(size: int) -> None: ... +def setCacheTime(time: int) -> None: ... +def setLocale(lang: str) -> None: ... +def setRootMode(boolean: bool) -> None: ... diff --git a/stubs/pyxdg/xdg/DesktopEntry.pyi b/stubs/pyxdg/xdg/DesktopEntry.pyi new file mode 100644 index 000000000000..251066b67c46 --- /dev/null +++ b/stubs/pyxdg/xdg/DesktopEntry.pyi @@ -0,0 +1,65 @@ +import re +from _typeshed import StrPath +from typing import Literal + +from xdg.IniFile import IniFile + +class DesktopEntry(IniFile): + defaultGroup: str + content: dict[str, dict[str, str]] + def __init__(self, filename: StrPath | None = None) -> None: ... + def parse(self, file: StrPath) -> None: ... # type: ignore[override] + def findTryExec(self) -> str | None: ... + def getType(self) -> str: ... + def getVersion(self) -> float: ... + def getVersionString(self) -> str: ... + def getName(self) -> str: ... + def getGenericName(self) -> str: ... + def getNoDisplay(self) -> bool: ... + def getComment(self) -> str: ... + def getIcon(self) -> str: ... + def getHidden(self) -> bool: ... + def getOnlyShowIn(self) -> list[str]: ... + def getNotShowIn(self) -> list[str]: ... + def getTryExec(self) -> str: ... + def getExec(self) -> str: ... + def getPath(self) -> str: ... + def getTerminal(self) -> bool: ... + def getMimeType(self) -> list[re.Pattern[str]]: ... + def getMimeTypes(self) -> list[str]: ... + def getCategories(self) -> list[str]: ... + def getStartupNotify(self) -> bool: ... + def getStartupWMClass(self) -> str: ... + def getURL(self) -> str: ... + def getServiceTypes(self) -> list[str]: ... + def getDocPath(self) -> str: ... + def getKeywords(self) -> list[str]: ... + def getInitialPreference(self) -> str: ... + def getDev(self) -> str: ... + def getFSType(self) -> str: ... + def getMountPoint(self) -> str: ... + def getReadonly(self) -> bool: ... + def getUnmountIcon(self) -> str: ... + def getMiniIcon(self) -> str: ... + def getTerminalOptions(self) -> str: ... + def getDefaultApp(self) -> str: ... + def getProtocols(self) -> list[str]: ... + def getExtensions(self) -> list[str]: ... + def getBinaryPattern(self) -> str: ... + def getMapNotify(self) -> str: ... + def getEncoding(self) -> str: ... + def getSwallowTitle(self) -> str: ... + def getSwallowExec(self) -> str: ... + def getSortOrder(self) -> list[str]: ... + def getFilePattern(self) -> re.Pattern[str]: ... + def getActions(self) -> list[str]: ... + filename: str + def new(self, filename: str) -> None: ... + type: Literal["Application", "Directory"] + name: str + def checkExtras(self) -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + def checkType(self, key: str, type: str) -> None: ... + def checkOnlyShowIn(self, value: str) -> None: ... + def checkCategories(self, value: str) -> None: ... diff --git a/stubs/pyxdg/xdg/Exceptions.pyi b/stubs/pyxdg/xdg/Exceptions.pyi new file mode 100644 index 000000000000..764a1b11216c --- /dev/null +++ b/stubs/pyxdg/xdg/Exceptions.pyi @@ -0,0 +1,41 @@ +debug: bool + +class Error(Exception): + msg: str + def __init__(self, msg: str) -> None: ... + +class ValidationError(Error): + msg: str + file: str + def __init__(self, msg: str, file: str) -> None: ... + +class ParsingError(Error): + msg: str + file: str + def __init__(self, msg: str, file: str) -> None: ... + +class NoKeyError(Error): + key: str + group: str + file: str + def __init__(self, key: str, group: str, file: str) -> None: ... + +class DuplicateKeyError(Error): + key: str + group: str + file: str + def __init__(self, key: str, group: str, file: str) -> None: ... + +class NoGroupError(Error): + group: str + file: str + def __init__(self, group: str, file: str) -> None: ... + +class DuplicateGroupError(Error): + group: str + file: str + def __init__(self, group: str, file: str) -> None: ... + +class NoThemeError(Error): + theme: str + def __init__(self, theme: str) -> None: ... diff --git a/stubs/pyxdg/xdg/IconTheme.pyi b/stubs/pyxdg/xdg/IconTheme.pyi new file mode 100644 index 000000000000..40ba87afda55 --- /dev/null +++ b/stubs/pyxdg/xdg/IconTheme.pyi @@ -0,0 +1,55 @@ +from _typeshed import StrPath +from collections.abc import Collection + +from xdg.IniFile import IniFile + +class IconTheme(IniFile): + def __init__(self) -> None: ... + dir: str + name: str + comment: str + directories: list[str] + type: str + def parse(self, file: StrPath) -> None: ... # type: ignore[override] + def getDir(self) -> str: ... + def getName(self) -> str: ... + def getComment(self) -> str: ... + def getInherits(self) -> list[str]: ... + def getDirectories(self) -> list[str]: ... + def getScaledDirectories(self) -> list[str]: ... + def getHidden(self) -> bool: ... + def getExample(self) -> str: ... + def getSize(self, directory: StrPath) -> int: ... + def getContext(self, directory: StrPath) -> str: ... + def getType(self, directory: StrPath) -> str: ... + def getMaxSize(self, directory: StrPath) -> int: ... + def getMinSize(self, directory: StrPath) -> int: ... + def getThreshold(self, directory: StrPath) -> int: ... + def getScale(self, directory: StrPath) -> int: ... + def checkExtras(self) -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + +class IconData(IniFile): + def __init__(self) -> None: ... + def parse(self, file: StrPath) -> None: ... # type: ignore[override] + def getDisplayName(self) -> str: ... + def getEmbeddedTextRectangle(self) -> list[int]: ... + def getAttachPoints(self) -> list[tuple[int, int]]: ... + def checkExtras(self) -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + +icondirs: list[str] +themes: list[IconTheme] +theme_cache: dict[str, IconTheme] +dir_cache: dict[str, tuple[str, float, float]] +icon_cache: dict[tuple[str, int, str, tuple[str, ...]], tuple[float, str]] + +def getIconPath( + iconname: str, size: int | None = None, theme: str | None = None, extensions: Collection[str] = ["png", "svg", "xpm"] +) -> str: ... +def getIconData(path: str) -> IconData: ... +def LookupIcon(iconname: str, size: int, theme: str, extensions: Collection[str]) -> str: ... +def DirectoryMatchesSize(subdir: str, iconsize: int, theme: str) -> bool: ... +def DirectorySizeDistance(subdir: str, iconsize: int, theme: str) -> int: ... diff --git a/stubs/pyxdg/xdg/IniFile.pyi b/stubs/pyxdg/xdg/IniFile.pyi new file mode 100644 index 000000000000..2fa7cb47aebd --- /dev/null +++ b/stubs/pyxdg/xdg/IniFile.pyi @@ -0,0 +1,256 @@ +import re +from collections.abc import Iterable, KeysView +from typing import Literal, overload + +def is_ascii(s: str) -> bool: ... + +class IniFile: + defaultGroup: str + fileExtension: str + filename: str + tainted: bool + content: dict[str, dict[str, str]] + warnings: list[str] + errors: list[str] + def __init__(self, filename: str | None = None) -> None: ... + def __cmp__(self, other: IniFile) -> bool: ... + def parse(self, filename: str, headers: Iterable[str] | None = None) -> None: ... + + @overload + def get( + self, + key: str, + group: str | None = None, + locale: bool = False, + type: Literal["string"] = "string", + list: Literal[False] = False, + strict: bool = False, + ) -> str: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["string"], list: Literal[True], strict: bool = False + ) -> list[str]: ... + @overload + def get( + self, + key: str, + *, + list: Literal[True], + group: str | None = None, + locale: bool = False, + type: Literal["string"] = "string", + strict: bool = False, + ) -> list[str]: ... + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["boolean"], + list: Literal[False] = False, + strict: bool = False, + ) -> bool: ... + @overload + def get( + self, + key: str, + *, + type: Literal["boolean"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> bool: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["boolean"], list: Literal[True], strict: bool = False + ) -> list[bool]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["boolean"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[bool]: ... + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["integer"], + list: Literal[False] = False, + strict: bool = False, + ) -> int: ... + @overload + def get( + self, + key: str, + *, + type: Literal["integer"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> int: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["integer"], list: Literal[True], strict: bool = False + ) -> list[int]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["integer"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[int]: ... + + # Float + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["numeric"], + list: Literal[False] = False, + strict: bool = False, + ) -> float: ... + @overload + def get( + self, + key: str, + *, + type: Literal["numeric"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> float: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["numeric"], list: Literal[True], strict: bool = False + ) -> list[float]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["numeric"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[float]: ... + + # Regex + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["regex"], + list: Literal[False] = False, + strict: bool = False, + ) -> re.Pattern[str]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["regex"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> re.Pattern[str]: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["regex"], list: Literal[True], strict: bool = False + ) -> list[re.Pattern[str]]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["regex"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[re.Pattern[str]]: ... + # point + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["point"], + list: Literal[False] = False, + strict: bool = False, + ) -> tuple[int, int]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["point"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> tuple[int, int]: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["point"], list: Literal[True], strict: bool = False + ) -> list[tuple[int, int]]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["point"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[tuple[int, int]]: ... + + def getList(self, string: str) -> list[str]: ... + def validate(self, report: Literal["All", "Warnings", "Errors"] = "All") -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + def checkValue( + self, + key: str, + value: str, + type: Literal["string", "localestring", "boolean", "numeric", "integer", "regex", "point"] = "string", + list: bool = False, + ) -> None: ... + def checkExtras(self) -> None: ... + def checkBoolean(self, value: str) -> Literal[1, 2] | None: ... + def checkNumber(self, value: str) -> Literal[1, 2] | None: ... + def checkInteger(self, value: str) -> Literal[1] | None: ... + def checkPoint(self, value: str) -> Literal[1] | None: ... + def checkString(self, value: str) -> Literal[0, 1]: ... + def checkRegex(self, value: str) -> Literal[1] | None: ... + def write(self, filename: str | None = None, trusted: bool = False) -> None: ... + def set(self, key: str, value: str, group: str | None = None, locale: bool = False) -> None: ... + def addGroup(self, group: str) -> None: ... + def removeGroup(self, group: str) -> bool: ... + def removeKey(self, key: str, group: str | None = None, locales: bool = True) -> str: ... + def groups(self) -> KeysView[str]: ... + def hasGroup(self, group: str) -> bool: ... + def hasKey(self, key: str, group: str | None = None) -> bool: ... + def getFileName(self) -> str: ... diff --git a/stubs/pyxdg/xdg/Locale.pyi b/stubs/pyxdg/xdg/Locale.pyi new file mode 100644 index 000000000000..6aa285ad348a --- /dev/null +++ b/stubs/pyxdg/xdg/Locale.pyi @@ -0,0 +1,8 @@ +from collections.abc import Iterable + +regex: str + +def expand_languages(languages: Iterable[str] | None = None) -> list[str]: ... +def update(language: str | None = None) -> None: ... + +langs: list[str] diff --git a/stubs/pyxdg/xdg/Menu.pyi b/stubs/pyxdg/xdg/Menu.pyi new file mode 100644 index 000000000000..0d56c6c28369 --- /dev/null +++ b/stubs/pyxdg/xdg/Menu.pyi @@ -0,0 +1,168 @@ +import ast +import xml.dom +from _typeshed import Unused +from collections.abc import Collection, Iterable, Iterator +from types import CodeType +from typing import Literal + +from .DesktopEntry import DesktopEntry + +DELETED: Literal["Deleted"] = "Deleted" +NO_DISPLAY: Literal["NoDisplay"] = "NoDisplay" +HIDDEN: Literal["Hidden"] = "Hidden" +EMPTY: Literal["Empty"] = "Empty" +NOT_SHOW_IN: Literal["NotShowIn"] = "NotShowIn" +NO_EXEC: Literal["NoExec"] = "NoExec" + +class Menu: + Name: str + Directory: Menu | None + Entries: list[str] + Doc: str + Filename: str + Depth: int + Parent: Menu | None + NotInXml: bool + Show: bool + Visible: int + AppDirs: list[str] + DefaultLayout: str | None + Deleted: bool | None + Directories: list[str] + DirectoryDirs: list[Menu] + Layout: Layout + MenuEntries: list[MenuEntry | Menu | Separator] + Moves: list[Move] + OnlyUnallocated: bool | None + Rules: list[Rule] + Submenus: list[Menu] + def __init__(self) -> None: ... + def __add__(self, other: Menu) -> Menu: ... + def __cmp__(self, other: Menu) -> int: ... + def __lt__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def getEntries(self, show_hidden: bool = False) -> Iterator[str]: ... + def getMenuEntry(self, desktopfileid: int, deep: bool = False) -> MenuEntry: ... + def getMenu(self, path: str) -> Menu: ... + def getPath(self, org: bool = False, toplevel: bool = False) -> str: ... + def getName(self) -> str: ... + def getGenericName(self) -> str: ... + def getComment(self) -> str: ... + def getIcon(self) -> str: ... + def sort(self) -> None: ... + def addSubmenu(self, newmenu: Menu) -> None: ... + def merge_inline(self, submenu: Menu) -> None: ... + +class Move: + Old: str + New: str + def __init__(self, old: str = "", new: str = "") -> None: ... + def __cmp__(self, other: Move) -> int: ... + +class Layout: + show_empty: bool + inline: bool + inline_limit: int + inline_header: bool + inline_alias: bool + def __init__( + self, + show_empty: bool = False, + inline: bool = False, + inline_limit: int = 4, + inline_header: bool = True, + inline_alias: bool = False, + ) -> None: ... + + @property + def order(self) -> list[list[str]]: ... + @order.setter + def order(self, order: list[list[str]]) -> None: ... + +class Rule: + TYPE_INCLUDE: Literal[0] + TYPE_EXCLUDE: Literal[1] + @classmethod + def fromFilename(cls, type: Literal[0, 1], filename: str) -> Rule: ... + Type: Literal[0, 1] + expression: ast.Expression + code: CodeType + def __init__(self, type: Literal[0, 1], expression: str) -> None: ... + def apply(self, menuentries: Iterable[MenuEntry], run: int) -> Iterable[MenuEntry]: ... + +class MenuEntry: + TYPE_USER: Literal["User"] + TYPE_SYSTEM: Literal["System"] + TYPE_BOTH: Literal["Both"] + DesktopEntry: DesktopEntry + Show: bool | Literal["Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] + Visible: Literal[1, 0, "Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] + Original: MenuEntry | None + Parents: list[Menu] + Allocated: bool + Add: bool + MatchedInclude: bool + Categories: list[str] + def __init__(self, filename: str, dir: str = "", prefix: str = "") -> None: ... + def save(self) -> None: ... + def getDir(self) -> str: ... + def getType(self) -> Literal["User", "System", "Both"]: ... + Filename: str + Prefix: str + DesktopFileID: str + def setAttributes(self, filename: str, dir: str = "", prefix: str = "") -> None: ... + def updateAttributes(self) -> None: ... + def __cmp__(self, other: MenuEntry) -> int: ... + def __lt__(self, other: MenuEntry) -> bool: ... + def __eq__(self, other: object) -> bool: ... + +class Separator: + Parent: Menu + Show: bool + def __init__(self, parent: Menu) -> None: ... + +class Header: + Name: str + GenericName: str + Comment: str + def __init__(self, name: str, generic_name: str, comment: str) -> None: ... + +TYPE_DIR: Literal[0] = 0 +TYPE_FILE: Literal[1] = 1 + +class XMLMenuBuilder: + debug: bool + def __init__(self, debug: bool = False) -> None: ... + cache: MenuEntryCache + def parse(self, filename: str | None = None) -> Menu: ... + def parse_menu(self, node: xml.dom.Node, filename: str) -> Menu: ... + def parse_node(self, node: xml.dom.Node, filename: str, parent: Menu | None = None) -> None: ... + def parse_layout(self, node: xml.dom.Node) -> Layout: ... + def parse_move(self, node: xml.dom.Node) -> Move: ... + def parse_rule(self, node: xml.dom.Node) -> Rule: ... + def parse_bool_op(self, node: xml.dom.Node, operator: ast.And | ast.Or) -> ast.BoolOp | ast.UnaryOp | ast.Compare | None: ... + def parse_rule_node(self, node: xml.dom.Node) -> ast.BoolOp | ast.UnaryOp | ast.Compare | None: ... + def parse_app_dir(self, value: str, filename: str, parent: str) -> None: ... + def parse_default_app_dir(self, filename: str, parent: str) -> None: ... + def parse_directory_dir(self, value: str, filename: str, parent: str) -> None: ... + def parse_default_directory_dir(self, filename: str, parent: str) -> None: ... + def parse_merge_file(self, value: str, child: Menu | MenuEntry, filename: str, parent: str) -> None: ... + def parse_merge_dir(self, value: str, child: Menu | MenuEntry, filename: str, parent: str) -> None: ... + def parse_default_merge_dirs(self, child: Menu | MenuEntry, filename: str, parent: str) -> None: ... + def merge_file(self, filename: str, child: Unused, parent: Menu) -> None: ... + def parse_legacy_dir(self, dir_: str, prefix: str, filename: str, parent: str) -> None: ... + def merge_legacy_dir(self, dir_: str, prefix: str, filename: str, parent: str) -> Menu: ... + def parse_kde_legacy_dirs(self, filename: str, parent: str) -> None: ... + def post_parse(self, menu: Menu) -> None: ... + def generate_not_only_allocated(self, menu: Menu) -> None: ... + def generate_only_allocated(self, menu: Menu) -> None: ... + def handle_moves(self, menu: Menu) -> None: ... + +class MenuEntryCache: + cacheEntries: dict[str, list[MenuEntry]] + cache: dict[str, list[MenuEntry]] + def __init__(self) -> None: ... + def add_menu_entries(self, dirs: Iterable[str], prefix: str = "", legacy: bool = False) -> None: ... + def get_menu_entries(self, dirs: Collection[str], legacy: bool = True) -> list[MenuEntry]: ... + +def parse(filename: str | None = None, debug: bool = False) -> XMLMenuBuilder: ... diff --git a/stubs/pyxdg/xdg/MenuEditor.pyi b/stubs/pyxdg/xdg/MenuEditor.pyi new file mode 100644 index 000000000000..a3dad5e2b8d8 --- /dev/null +++ b/stubs/pyxdg/xdg/MenuEditor.pyi @@ -0,0 +1,152 @@ +from _typeshed import StrPath, Unused +from typing import Literal, TypeAlias, overload +from xml.etree.ElementTree import ElementTree + +from .Menu import Menu, MenuEntry, Separator, XMLMenuBuilder + +_MenuItem: TypeAlias = Menu | MenuEntry | Separator + +class MenuEditor: + menu: Menu + filename: str + tree: ElementTree + parser: XMLMenuBuilder + filenames: list[str] + def __init__(self, menu: Menu | None = None, filename: StrPath | None = None, root: bool = False) -> None: ... + def parse(self, menu: Menu | None = None, filename: StrPath | None = None, root: bool = False) -> None: ... + def save(self) -> None: ... + + # All "before" or "after" items can be one, the other, or neither, but not both. + @overload + def createMenuEntry( + self, + parent: Menu | None, + name: str, + command: str | None = None, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + terminal: bool | None = None, + after: _MenuItem | None = None, + before: None = None, + ) -> MenuEntry: ... + @overload + def createMenuEntry( + self, + parent: Menu | None, + name: str, + command: str | None = None, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + terminal: bool | None = None, + after: None = None, + before: _MenuItem | None = None, + ) -> MenuEntry: ... + + @overload + def createMenu( + self, + parent: Menu | None, + name: str, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + after: _MenuItem | None = None, + before: None = None, + ) -> Menu: ... + @overload + def createMenu( + self, + parent: Menu | None, + name: str, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + after: None = None, + before: _MenuItem | None = None, + ) -> Menu: ... + + @overload + def createSeparator(self, parent: Menu, after: _MenuItem | None = None, before: None = None) -> Separator: ... + @overload + def createSeparator(self, parent: Menu, after: None = None, before: _MenuItem | None = None) -> Separator: ... + + @overload + def moveMenuEntry( + self, + menuentry: MenuEntry, + oldparent: Menu | None, + newparent: Menu | None, + after: _MenuItem | None = None, + before: None = None, + ) -> MenuEntry: ... + @overload + def moveMenuEntry( + self, + menuentry: MenuEntry, + oldparent: Menu | None, + newparent: Menu | None, + after: None = None, + before: _MenuItem | None = None, + ) -> MenuEntry: ... + + @overload + def moveMenu( + self, menu: Menu, oldparent: Menu, newparent: Menu, after: _MenuItem | None = None, before: None = None + ) -> Menu: ... + @overload + def moveMenu( + self, menu: Menu, oldparent: Menu, newparent: Menu, after: None = None, before: _MenuItem | None = None + ) -> Menu: ... + + @overload + def moveSeparator( + self, separator: Separator, parent: Menu, after: _MenuItem | None = None, before: None = None + ) -> Separator: ... + @overload + def moveSeparator( + self, separator: Separator, parent: Menu, after: None = None, before: _MenuItem | None = None + ) -> Separator: ... + + @overload + def copyMenuEntry( + self, menuentry: MenuEntry, oldparent: Unused, newparent: Menu, after: _MenuItem | None = None, before: None = None + ) -> MenuEntry: ... + @overload + def copyMenuEntry( + self, menuentry: MenuEntry, oldparent: Unused, newparent: Menu, after: None = None, before: _MenuItem | None = None + ) -> MenuEntry: ... + + def editMenuEntry( + self, + menuentry: MenuEntry, + name: str | None = None, + genericname: str | None = None, + comment: str | None = None, + command: str | None = None, + icon: str | None = None, + terminal: bool | None = None, + nodisplay: bool | None = None, + hidden: bool | None = None, + ) -> MenuEntry: ... + def editMenu( + self, + menu: Menu, + name: str | None = None, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + nodisplay: bool | None = None, + hidden: bool | None = None, + ) -> Menu: ... + def hideMenuEntry(self, menuentry: MenuEntry) -> None: ... + def unhideMenuEntry(self, menuentry: MenuEntry) -> None: ... + def hideMenu(self, menu: Menu) -> None: ... + def unhideMenu(self, menu: Menu) -> None: ... + def deleteMenuEntry(self, menuentry: MenuEntry) -> MenuEntry: ... + def revertMenuEntry(self, menuentry: MenuEntry) -> MenuEntry: ... + def deleteMenu(self, menu: Menu) -> Menu: ... + def revertMenu(self, menu: Menu) -> Menu: ... + def deleteSeparator(self, separator: Separator) -> Separator: ... + def getAction(self, entry: _MenuItem) -> Literal["none", "revert", "delete"]: ... diff --git a/stubs/pyxdg/xdg/Mime.pyi b/stubs/pyxdg/xdg/Mime.pyi new file mode 100644 index 000000000000..38607506caea --- /dev/null +++ b/stubs/pyxdg/xdg/Mime.pyi @@ -0,0 +1,102 @@ +import re +from _typeshed import StrOrBytesPath, SupportsLenAndGetItem, Unused +from collections import defaultdict +from collections.abc import Collection, Iterable +from io import BytesIO +from typing import Literal, TypeAlias +from typing_extensions import Self + +FREE_NS: str +types: dict[str, MIMEtype] +exts: Unused | None # This appears to be unused. +globs: GlobDB | None +literals: Unused | None # This appears to be unused. +magic: MagicDB | None +PY3: Literal[True] + +_MimeTypeWeightPair: TypeAlias = tuple[MIMEtype, int] + +def lookup(media: str, subtype: str | None = None) -> MIMEtype: ... + +class MIMEtype: + def __new__(cls, media: str, subtype: str | None = None) -> Self: ... + def get_comment(self) -> str: ... + def canonical(self) -> Self: ... + def inherits_from(self) -> set[MIMEtype]: ... + def __hash__(self) -> int: ... + +class UnknownMagicRuleFormat(ValueError): ... +class DiscardMagicRules(Exception): ... + +class MagicRule: + also: MagicRule | MagicMatchAny | None + start: int + value: bytes + mask: bytes | None + word: int + range: int + def __init__(self, start: int, value: bytes, mask: bytes, word: int, range: int) -> None: ... + rule_ending_re: re.Pattern[str] + @classmethod + def from_file(cls, f: BytesIO) -> tuple[int, MagicRule]: ... + def maxlen(self) -> int: ... + def match(self, buffer: SupportsLenAndGetItem[bytes]) -> bool: ... + def match0(self, buffer: SupportsLenAndGetItem[bytes]) -> bool: ... + +class MagicMatchAny: + rules: Collection[MagicRule] + def __init__(self, rules: Iterable[MagicRule]) -> None: ... + def match(self, buffer: SupportsLenAndGetItem[bytes]) -> bool: ... + def maxlen(self) -> int: ... + @classmethod + def from_file(cls, f: BytesIO) -> MagicMatchAny | MagicRule | None: ... + @classmethod + def from_rule_tree(cls, tree: list[MagicRule]) -> MagicMatchAny | MagicRule | None: ... + +class MagicDB: + bytype: defaultdict[MIMEtype, list[tuple[int, MagicRule]]] + def __init__(self) -> None: ... + def merge_file(self, fname: StrOrBytesPath) -> None: ... + alltypes: list[tuple[int, MIMEtype, MagicRule]] + maxlen: int + def finalise(self) -> None: ... + def match_data( + self, data: bytes, max_pri: int = 100, min_pri: int = 0, possible: Iterable[MIMEtype] | None = None + ) -> MIMEtype: ... + def match( + self, path: StrOrBytesPath, max_pri: int = 100, min_pri: int = 0, possible: Iterable[MIMEtype] | None = None + ) -> MIMEtype: ... + +class GlobDB: + allglobs: defaultdict[MIMEtype, list[tuple[int, str, str]]] + def __init__(self) -> None: ... + def merge_file(self, path: StrOrBytesPath) -> None: ... + exts: defaultdict[str, list[MIMEtype | int]] # Actually list[MIMEtype, int], but that's not valid. + cased_exts: defaultdict[str, list[MIMEtype | int]] # Actually list[MIMEtype, int], but that's not valid. + globs: list[tuple[re.Pattern[str], MIMEtype, int]] + literals: dict[str, _MimeTypeWeightPair] + cased_literals: dict[str, _MimeTypeWeightPair] + def finalise(self) -> None: ... + def first_match(self, path: StrOrBytesPath) -> _MimeTypeWeightPair | None: ... + def all_matches(self, path: StrOrBytesPath) -> list[_MimeTypeWeightPair]: ... + +text: MIMEtype +octet_stream: MIMEtype +inode_block: MIMEtype +inode_char: MIMEtype +inode_dir: MIMEtype +inode_fifo: MIMEtype +inode_socket: MIMEtype +inode_symlink: MIMEtype +inode_door: MIMEtype +app_exe: MIMEtype + +def update_cache() -> None: ... +def get_type_by_name(path: StrOrBytesPath) -> _MimeTypeWeightPair | None: ... +def get_type_by_contents(path: StrOrBytesPath, max_pri: int = 100, min_pri: int = 0) -> MIMEtype: ... +def get_type_by_data(data: bytes, max_pri: int = 100, min_pri: int = 0) -> MIMEtype: ... +def get_type(path: StrOrBytesPath, follow: bool = True, name_pri: int = 100) -> MIMEtype: ... +def get_type2(path: StrOrBytesPath, follow: bool = True) -> MIMEtype: ... +def is_text_file(path: StrOrBytesPath) -> bool: ... +def get_extensions(mimetype: MIMEtype) -> set[str]: ... +def install_mime_info(application: str, package_file: StrOrBytesPath) -> None: ... diff --git a/stubs/pyxdg/xdg/RecentFiles.pyi b/stubs/pyxdg/xdg/RecentFiles.pyi new file mode 100644 index 000000000000..742c9bdf6800 --- /dev/null +++ b/stubs/pyxdg/xdg/RecentFiles.pyi @@ -0,0 +1,26 @@ +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Iterable + +class RecentFiles: + RecentFiles: list[RecentFile] + filename: str + def __init__(self) -> None: ... + def parse(self, filename: StrPath | None = None) -> None: ... + def write(self, filename: StrOrBytesPath | None = None) -> None: ... + def getFiles( + self, mimetypes: Iterable[str] | None = None, groups: Iterable[str] | None = None, limit: int = 0 + ) -> list[RecentFile]: ... + def addFile(self, item: StrPath, mimetype: str, groups: Iterable[str] | None = None, private: bool = False) -> None: ... + def deleteFile(self, item: RecentFile | StrPath) -> None: ... + def sort(self) -> None: ... + +class RecentFile: + URI: str + MimeType: str + Timestamp: str + Private: bool + Groups: list[str] + def __init__(self) -> None: ... + def __cmp__(self, other: RecentFile) -> int: ... + def __lt__(self, other: RecentFile) -> bool: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/pyxdg/xdg/__init__.pyi b/stubs/pyxdg/xdg/__init__.pyi new file mode 100644 index 000000000000..5bf6489a50b7 --- /dev/null +++ b/stubs/pyxdg/xdg/__init__.pyi @@ -0,0 +1,15 @@ +from . import BaseDirectory, Config, DesktopEntry, Exceptions, IconTheme, IniFile, Locale, Menu, MenuEditor, Mime, RecentFiles + +__all__ = [ + "BaseDirectory", + "Config", + "DesktopEntry", + "Exceptions", + "IconTheme", + "IniFile", + "Locale", + "Menu", + "MenuEditor", + "Mime", + "RecentFiles", +] diff --git a/stubs/pyxdg/xdg/util.pyi b/stubs/pyxdg/xdg/util.pyi new file mode 100644 index 000000000000..15636e13529a --- /dev/null +++ b/stubs/pyxdg/xdg/util.pyi @@ -0,0 +1,6 @@ +from shutil import which as which +from typing import Literal + +PY3: Literal[True] + +def u(s: str) -> str: ... diff --git a/stubs/qrbill/@tests/stubtest_allowlist.txt b/stubs/qrbill/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7be909504ec4 --- /dev/null +++ b/stubs/qrbill/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Error: is inconsistent +# ====================== +# While the method provides default values for all arguments, the first two +# arguments always need to be provided, so it makes no sense to pretend that +# they are optional +qrbill.bill.QRBill.__init__ diff --git a/stubs/qrbill/METADATA.toml b/stubs/qrbill/METADATA.toml new file mode 100644 index 000000000000..468d224cb47d --- /dev/null +++ b/stubs/qrbill/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.2.*" +upstream-repository = "https://github.com/claudep/swiss-qr-bill" +dependencies = ["types-qrcode"] diff --git a/stubs/qrbill/qrbill/__init__.pyi b/stubs/qrbill/qrbill/__init__.pyi new file mode 100644 index 000000000000..995a9dd82092 --- /dev/null +++ b/stubs/qrbill/qrbill/__init__.pyi @@ -0,0 +1 @@ +from .bill import QRBill as QRBill diff --git a/stubs/qrbill/qrbill/bill.pyi b/stubs/qrbill/qrbill/bill.pyi new file mode 100644 index 000000000000..b89b902c45be --- /dev/null +++ b/stubs/qrbill/qrbill/bill.pyi @@ -0,0 +1,193 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterable, Iterator, Mapping +from decimal import Decimal +from pathlib import Path +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import deprecated + +from qrcode.image.svg import SvgPathImage + +# NOTE: Since svgwrite doesn't have any stubs we provide some type aliases, that +# we can choose to refine in the future, e.g. using a Protocol +_SvgDrawing: TypeAlias = Any # svgwrite.Drawing +_SvgGroup: TypeAlias = Any # svgwrite.container.Group + +# NOTE: Eventually we may want to consider replacing this with typed dicts, even +# if that means disallowing non-dict arguments. It should allow anything +# that is valid to pass into `Address.create`. +_AddressDict: TypeAlias = Mapping[str, str | None] + +IBAN_ALLOWED_COUNTRIES: list[str] +QR_IID: dict[str, int] +AMOUNT_REGEX: str +MM_TO_UU: float +BILL_HEIGHT: int +RECEIPT_WIDTH: str +PAYMENT_WIDTH: str +MAX_CHARS_PAYMENT_LINE: int +MAX_CHARS_RECEIPT_LINE: int +A4: tuple[str, str] +LABELS: dict[str, dict[str, str]] +SCISSORS_SVG_PATH: str + +class Address: + @overload + @classmethod + def create(cls, *, name: str | None = None, line1: str, line2: str | None = None, country: str | None) -> CombinedAddress: ... + @overload + @classmethod + def create(cls, *, name: str | None = None, line1: str | None = None, line2: str, country: str | None) -> CombinedAddress: ... + @overload + @classmethod + def create( + cls, + *, + name: str, + street: str | None = None, + house_num: str | None = None, + pcode: str, + city: str, + country: str | None = None, + ) -> StructuredAddress: ... + + @staticmethod + def parse_country(country: str | None) -> str: ... + +class CombinedAddress(Address): + combined: Final = True + name: str + line1: str + line2: str + country: str + def __init__( + self, *, name: str | None = None, line1: str | None = None, line2: str | None = None, country: str | None = None + ) -> None: ... + def data_list(self) -> list[str]: ... + def as_paragraph(self, max_chars: int = 72) -> Iterator[str]: ... + +class StructuredAddress(Address): + combined: Final = False + name: str + street: str + house_num: str + pcode: str + city: str + country: str + def __init__( + self, + *, + name: str | None = None, + street: str | None = None, + house_num: str | None = None, + pcode: str | None = None, + city: str | None = None, + country: str | None = None, + ) -> None: ... + def data_list(self) -> list[str]: ... + def as_paragraph(self, max_chars: int = 72) -> Iterator[str]: ... + +class QRBill: + qr_type: str + version: str + coding: int + allowed_currencies: tuple[Literal["CHF"], Literal["EUR"]] + font_family: str + creditor: CombinedAddress | StructuredAddress + final_creditor: CombinedAddress | StructuredAddress | None + debtor: CombinedAddress | StructuredAddress | None + ref_type: str + reference_number: str | None + account: str + account_is_qriban: bool + amount: str | None + currency: Literal["CHF", "EUR"] + additional_information: str + billing_information: str + + @overload + def __init__( + self, + account: str, + creditor: _AddressDict, + final_creditor: None = None, + amount: Decimal | str | None = None, + currency: Literal["CHF", "EUR"] = "CHF", + debtor: _AddressDict | None = None, + ref_number: None = None, + reference_number: str | None = None, + extra_infos: Literal[""] = "", + additional_information: str = "", + billing_information: str = "", + alt_procs: list[str] | tuple[()] | tuple[str] | tuple[str, str] = (), + language: Literal["en", "de", "fr", "it"] = "en", + top_line: bool = True, + payment_line: bool = True, + font_factor: int = 1, + ) -> None: ... + @overload + @deprecated("ref_number is deprecated and replaced by reference_number") + def __init__( + self, + account: str, + creditor: _AddressDict, + final_creditor: None = None, + amount: Decimal | str | None = None, + currency: Literal["CHF", "EUR"] = "CHF", + debtor: _AddressDict | None = None, + *, + ref_number: str, + reference_number: None = None, + extra_infos: str = "", + additional_information: str = "", + billing_information: str = "", + alt_procs: list[str] | tuple[()] | tuple[str] | tuple[str, str] = (), + language: Literal["en", "de", "fr", "it"] = "en", + top_line: bool = True, + payment_line: bool = True, + font_factor: int = 1, + ) -> None: ... + @overload + @deprecated("extra_infos is deprecated and replaced by additional_information") + def __init__( + self, + account: str, + creditor: _AddressDict, + final_creditor: None = None, + amount: Decimal | str | None = None, + currency: Literal["CHF", "EUR"] = "CHF", + debtor: _AddressDict | None = None, + ref_number: None = None, + reference_number: str | None = None, + *, + extra_infos: str, + additional_information: str = "", + billing_information: str = "", + alt_procs: list[str] | tuple[()] | tuple[str] | tuple[str, str] = (), + language: Literal["en", "de", "fr", "it"] = "en", + top_line: bool = True, + payment_line: bool = True, + font_factor: int = 1, + ) -> None: ... + + @property + def title_font_info(self) -> dict[str, Any]: ... + @property + def font_info(self) -> dict[str, Any]: ... + def head_font_info(self, part: str | None = None) -> dict[str, Any]: ... + @property + def proc_font_info(self) -> dict[str, Any]: ... + def qr_data(self) -> str: ... + def qr_image(self) -> SvgPathImage: ... + def draw_swiss_cross(self, dwg: _SvgDrawing, grp: _SvgGroup, origin: tuple[float, float], size: float) -> None: ... + def draw_blank_rect(self, dwg: _SvgDrawing, grp: _SvgGroup, x: float, y: float, width: float, height: float) -> None: ... + def label(self, txt: str) -> str: ... + def as_svg(self, file_out: str | Path | SupportsWrite[str], full_page: bool = False) -> None: ... + def transform_to_full_page(self, dwg: _SvgDrawing, bill: _SvgGroup) -> None: ... + def draw_bill(self, dwg: _SvgDrawing, horiz_scissors: bool = True) -> _SvgGroup: ... + +def add_mm(*mms: str | float) -> float: ... +def mm(val: str | float) -> float: ... +def format_ref_number(bill: QRBill) -> str: ... +def format_amount(amount_: str | float) -> str: ... +def wrap_infos(infos: Iterable[str]) -> Iterator[str]: ... +def replace_linebreaks(text: str | None) -> str: ... diff --git a/stubs/qrcode/@tests/stubtest_allowlist.txt b/stubs/qrcode/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e24fb492beb2 --- /dev/null +++ b/stubs/qrcode/@tests/stubtest_allowlist.txt @@ -0,0 +1,22 @@ +# Internal modules +qrcode\.compat +qrcode\.compat\..* +qrcode\.tests +qrcode\.tests\..* + +# Stub-only module +qrcode._types + +# Parameter "data" has unhelpful default value, which creates a QR code with string "None". +qrcode\.main\.make + +# Implementation has marked these methods as abstract without the class +# or its bases deriving from abc.ABCMeta +qrcode\.image\.base\.BaseImage\.(drawrect|new_image|save) + +# The implementation sets this attribute to None on the class but instances +# always set this to a PIL image instance. +qrcode\.image\.styles\.moduledrawers\.(pil\.)?CircleModuleDrawer.circle + +# Leaked loop counter +qrcode.base.i diff --git a/stubs/qrcode/METADATA.toml b/stubs/qrcode/METADATA.toml new file mode 100644 index 000000000000..f329321ac1f0 --- /dev/null +++ b/stubs/qrcode/METADATA.toml @@ -0,0 +1,7 @@ +version = "8.2.*" +upstream-repository = "https://github.com/lincolnloop/python-qrcode" +# must be a version of Pillow that is py.typed +dependencies = ["Pillow>=10.3.0"] + +[tool.stubtest] +extras = ["pil"] diff --git a/stubs/qrcode/qrcode/LUT.pyi b/stubs/qrcode/qrcode/LUT.pyi new file mode 100644 index 000000000000..2e7f6fa4dd4e --- /dev/null +++ b/stubs/qrcode/qrcode/LUT.pyi @@ -0,0 +1,3 @@ +from typing import Final + +rsPoly_LUT: Final[dict[int, list[int]]] diff --git a/stubs/qrcode/qrcode/__init__.pyi b/stubs/qrcode/qrcode/__init__.pyi new file mode 100644 index 000000000000..2109f5de5a0a --- /dev/null +++ b/stubs/qrcode/qrcode/__init__.pyi @@ -0,0 +1,22 @@ +from _typeshed import ConvertibleToInt + +from qrcode import image as image +from qrcode.constants import ( + ERROR_CORRECT_H as ERROR_CORRECT_H, + ERROR_CORRECT_L as ERROR_CORRECT_L, + ERROR_CORRECT_M as ERROR_CORRECT_M, + ERROR_CORRECT_Q as ERROR_CORRECT_Q, +) +from qrcode.main import GenericImage, QRCode as QRCode, make as make + +from ._types import ErrorCorrect, MaskPattern + +def run_example( + data: str = "http://www.lincolnloop.com", + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: type[GenericImage] | None = None, + mask_pattern: MaskPattern | None = None, +) -> None: ... diff --git a/stubs/qrcode/qrcode/_types.pyi b/stubs/qrcode/qrcode/_types.pyi new file mode 100644 index 000000000000..91676c18a6a5 --- /dev/null +++ b/stubs/qrcode/qrcode/_types.pyi @@ -0,0 +1,15 @@ +# Type aliases used in this stub package +from _typeshed import SupportsWrite +from typing import Any, Protocol, TypeAlias, type_check_only + +Box: TypeAlias = tuple[tuple[int, int], tuple[int, int]] +Ink: TypeAlias = tuple[int, int, int] | tuple[int, int, int, int] + +# Don't try to make these Literal[x, y, z] as this really wreaks +# havoc with overloads in mypy. +ErrorCorrect: TypeAlias = int +MaskPattern: TypeAlias = int + +@type_check_only +class Writeable(SupportsWrite[bytes], Protocol): + def seek(self, offset: int, /) -> Any: ... diff --git a/stubs/qrcode/qrcode/base.pyi b/stubs/qrcode/qrcode/base.pyi new file mode 100644 index 000000000000..0b5cd8aa385f --- /dev/null +++ b/stubs/qrcode/qrcode/base.pyi @@ -0,0 +1,27 @@ +from collections.abc import Iterator +from typing import NamedTuple, SupportsIndex + +from ._types import ErrorCorrect + +EXP_TABLE: list[int] +LOG_TABLE: list[int] +RS_BLOCK_OFFSET: dict[ErrorCorrect, int] +RS_BLOCK_TABLE: tuple[tuple[int, int, int] | tuple[int, int, int, int, int, int], ...] + +def glog(n: int) -> int: ... +def gexp(n: int) -> int: ... + +class Polynomial: + num: list[int] + def __init__(self, num: list[int], shift: int) -> None: ... + def __getitem__(self, index: SupportsIndex) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... + def __mul__(self, other: Polynomial) -> Polynomial: ... + def __mod__(self, other: Polynomial) -> Polynomial: ... + +class RSBlock(NamedTuple): + total_count: int + data_count: int + +def rs_blocks(version: int, error_correction: ErrorCorrect) -> list[RSBlock]: ... diff --git a/stubs/qrcode/qrcode/console_scripts.pyi b/stubs/qrcode/qrcode/console_scripts.pyi new file mode 100644 index 000000000000..44bc8d475a7e --- /dev/null +++ b/stubs/qrcode/qrcode/console_scripts.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable, Sequence + +from ._types import ErrorCorrect +from .image.base import BaseImage, DrawerAliases as DrawerAliases + +default_factories: dict[str, str] +error_correction: dict[str, ErrorCorrect] + +def main(args: Sequence[str] | None = None) -> None: ... +def get_factory(module: str) -> type[BaseImage]: ... +def get_drawer_help() -> str: ... +def commas(items: Iterable[str], joiner: str = "or") -> str: ... diff --git a/stubs/qrcode/qrcode/constants.pyi b/stubs/qrcode/qrcode/constants.pyi new file mode 100644 index 000000000000..dc308677fe5c --- /dev/null +++ b/stubs/qrcode/qrcode/constants.pyi @@ -0,0 +1,6 @@ +from typing import Final + +ERROR_CORRECT_L: Final = 1 +ERROR_CORRECT_M: Final = 0 +ERROR_CORRECT_Q: Final = 3 +ERROR_CORRECT_H: Final = 2 diff --git a/stubs/qrcode/qrcode/exceptions.pyi b/stubs/qrcode/qrcode/exceptions.pyi new file mode 100644 index 000000000000..982223889922 --- /dev/null +++ b/stubs/qrcode/qrcode/exceptions.pyi @@ -0,0 +1 @@ +class DataOverflowError(Exception): ... diff --git a/stubs/qrcode/qrcode/image/__init__.pyi b/stubs/qrcode/qrcode/image/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/qrcode/qrcode/image/base.pyi b/stubs/qrcode/qrcode/image/base.pyi new file mode 100644 index 000000000000..03a5133994f4 --- /dev/null +++ b/stubs/qrcode/qrcode/image/base.pyi @@ -0,0 +1,66 @@ +from collections.abc import Callable +from typing import IO, Any, TypeAlias + +from ..main import ModulesType, QRCode +from .styles.moduledrawers.base import QRModuleDrawer + +# The second element of the value tuple are keyword arguments used when +# constructing instances of the QRModuleDrawer type. +DrawerAliases: TypeAlias = dict[str, tuple[type[QRModuleDrawer], dict[str, Any]]] + +class BaseImage: + kind: str | None + allowed_kinds: tuple[str] | None + needs_context: bool + needs_processing: bool + needs_drawrect: bool + border: int + width: int + box_size: int + pixel_size: int + modules: list[list[bool | None]] + # the class accepts arbitrary additional positional arguments to accommodate + # subclasses with additional arguments. kwargs are forwarded to the `new_image()` call. + def __init__( + self, border: int, width: int, box_size: int, *args: Any, qrcode_modules: ModulesType | None, **kwargs: Any + ) -> None: ... + def drawrect(self, row: int, col: int) -> None: ... + def drawrect_context(self, row: int, col: int, qr: QRCode[Any]) -> None: ... + def process(self) -> None: ... + def save(self, stream: IO[bytes], kind: str | None = None) -> None: ... + def pixel_box(self, row: int, col: int) -> tuple[tuple[int, int], tuple[int, int]]: ... + # the new_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> Any: ... + def init_new_image(self) -> None: ... + # the get_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def get_image(self, **kwargs: Any) -> Any: ... + def check_kind(self, kind: str | None, transform: Callable[[str | None], str | None] | None = None) -> str | None: ... + def is_eye(self, row: int, col: int) -> bool: ... + +class BaseImageWithDrawer(BaseImage): + default_drawer_class: type[QRModuleDrawer] + drawer_aliases: DrawerAliases + def get_default_module_drawer(self) -> QRModuleDrawer: ... + def get_default_eye_drawer(self) -> QRModuleDrawer: ... + needs_context: bool + module_drawer: QRModuleDrawer + eye_drawer: QRModuleDrawer + # the class accepts arbitrary additional positional arguments to accommodate + # subclasses with additional arguments. kwargs are forwarded to the `new_image()` call + # via the BaseImage.__init__ method. + def __init__( + self, + border: int, + width: int, + box_size: int, + *args: Any, + qrcode_modules: ModulesType | None, + module_drawer: QRModuleDrawer | str | None = None, + eye_drawer: QRModuleDrawer | str | None = None, + **kwargs: Any, + ) -> None: ... + def get_drawer(self, drawer: QRModuleDrawer | str | None) -> QRModuleDrawer | None: ... + def init_new_image(self) -> None: ... + def drawrect_context(self, row: int, col: int, qr: QRCode[Any]) -> None: ... diff --git a/stubs/qrcode/qrcode/image/pil.pyi b/stubs/qrcode/qrcode/image/pil.pyi new file mode 100644 index 000000000000..635b069c6550 --- /dev/null +++ b/stubs/qrcode/qrcode/image/pil.pyi @@ -0,0 +1,30 @@ +from pathlib import Path +from typing import Any, Literal + +from PIL import Image + +from .._types import Writeable +from . import base + +class PilImage(base.BaseImage): + kind: Literal["PNG"] + fill_color: str + # the new_image and get_image methods accept arbitrary keyword arguments to + # accommodate subclasses with additional arguments. + def new_image(self, *, back_color: str = "white", fill_color: str = "black", **kwargs: Any) -> Image.Image: ... + def get_image(self, **kwargs: Any) -> Image.Image: ... + def drawrect(self, row: int, col: int) -> None: ... + # kwargs are passed on to PIL.Image.save, which also accepts arbitrary keyword arguments. + def save( # type: ignore[override] + self, + stream: str | bytes | Path | Writeable, + format: str | None = None, + *, + kind: str | None = None, + save_all: bool = ..., + bitmap_format: Literal["bmp", "png"] = ..., + optimize: bool = ..., + **kwargs: Any, + ) -> None: ... + # attribute access is forwarded to the wrapped PIL.Image.Image instance. + def __getattr__(self, name: str) -> Any: ... diff --git a/stubs/qrcode/qrcode/image/pure.pyi b/stubs/qrcode/qrcode/image/pure.pyi new file mode 100644 index 000000000000..5e5ec9c8c47b --- /dev/null +++ b/stubs/qrcode/qrcode/image/pure.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsWrite +from collections.abc import Generator +from typing import Any, Literal, TypeAlias + +from . import base + +# png.Writer; no types available +_Writer: TypeAlias = Any + +class PyPNGImage(base.BaseImage): + kind: str + allowed_kinds: tuple[Literal["PNG"]] + # the new_image and get_image methods accept arbitrary keyword arguments to + # accommodate subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> _Writer: ... + def get_image(self, **kwargs: Any) -> _Writer: ... + def drawrect(self, row: int, col: int) -> None: ... + def save(self, stream: SupportsWrite[bytes], kind: str | None = None) -> None: ... + def rows_iter(self) -> Generator[list[int], Any]: ... + def border_rows_iter(self) -> Generator[list[int], Any]: ... + +PymagingImage = PyPNGImage diff --git a/stubs/qrcode/qrcode/image/styledpil.pyi b/stubs/qrcode/qrcode/image/styledpil.pyi new file mode 100644 index 000000000000..c8e28463352e --- /dev/null +++ b/stubs/qrcode/qrcode/image/styledpil.pyi @@ -0,0 +1,56 @@ +from _typeshed import SupportsRead +from pathlib import Path +from typing import Any, Literal + +from PIL import Image + +from .._types import Ink, Writeable +from ..main import ModulesType +from . import base +from .styles.colormasks import QRColorMask +from .styles.moduledrawers import SquareModuleDrawer +from .styles.moduledrawers.base import QRModuleDrawer + +class StyledPilImage(base.BaseImageWithDrawer): + kind: Literal["PNG"] + color_mask: QRColorMask + default_drawer_class: type[SquareModuleDrawer] + embeded_image: Image.Image + embeded_image_resample: Image.Resampling + paint_color: Ink + # the class accepts arbitrary additional positional arguments to accommodate + # subclasses with additional arguments. kwargs are forwarded to the `new_image()` call + # via the BaseImage.__init__ method. + def __init__( + self, + border: int, + width: int, + box_size: int, + *args: Any, + qrcode_modules: ModulesType | None, + module_drawer: QRModuleDrawer | str | None = None, + eye_drawer: QRModuleDrawer | str | None = None, + color_mask: QRColorMask = ..., + embeded_image_path: str | bytes | Path | SupportsRead[bytes] | None = None, + embeded_image: Image.Image | None = None, + embeded_image_resample: Image.Resampling = ..., + **kwargs: Any, + ) -> None: ... + # the new_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> Image.Image: ... + def draw_embedded_image(self) -> None: ... + # kwargs are passed on to PIL.Image.save, which also accepts arbitrary keyword arguments. + def save( # type: ignore[override] + self, + stream: str | bytes | Path | Writeable, + format: str | None = None, + *, + kind: str | None = None, + save_all: bool = ..., + bitmap_format: Literal["bmp", "png"] = ..., + optimize: bool = ..., + **kwargs: Any, + ) -> None: ... + # attribute access is forwarded to the wrapped PIL.Image.Image instance. + def __getattr__(self, name: str) -> Any: ... diff --git a/stubs/qrcode/qrcode/image/styles/__init__.pyi b/stubs/qrcode/qrcode/image/styles/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/qrcode/qrcode/image/styles/colormasks.pyi b/stubs/qrcode/qrcode/image/styles/colormasks.pyi new file mode 100644 index 000000000000..4c66dd25e97a --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/colormasks.pyi @@ -0,0 +1,64 @@ +from _typeshed import SupportsRead +from pathlib import Path + +from PIL import Image + +from ..._types import Ink +from ..styledpil import StyledPilImage + +class QRColorMask: + back_color: Ink + has_transparency: bool + paint_color: Ink + # image is not actually used by any of the initialize implementations in this project. + def initialize(self, styledPilImage: StyledPilImage, image: Image.Image) -> None: ... + def apply_mask(self, image: Image.Image, use_cache: bool = False) -> None: ... + def get_fg_pixel(self, image: Image.Image, x: int, y: int) -> Ink: ... + def get_bg_pixel(self, image: Image.Image, x: int, y: int) -> Ink: ... + def interp_num(self, n1: int, n2: int, norm: float) -> int: ... + def interp_color(self, col1: Ink, col2: Ink, norm: float) -> Ink: ... + def extrap_num(self, n1: int, n2: int, interped_num: int) -> float | None: ... + def extrap_color(self, col1: Ink, col2: Ink, interped_color: Ink) -> float | None: ... + +class SolidFillColorMask(QRColorMask): + front_color: Ink + def __init__(self, back_color: Ink = (255, 255, 255), front_color: Ink = (0, 0, 0)) -> None: ... + def apply_mask(self, image: Image.Image) -> None: ... # type: ignore[override] + +class RadialGradiantColorMask(QRColorMask): + center_color: Ink + edge_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), center_color: Ink = (0, 0, 0), edge_color: Ink = (0, 0, 255) + ) -> None: ... + +class SquareGradiantColorMask(QRColorMask): + center_color: Ink + edge_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), center_color: Ink = (0, 0, 0), edge_color: Ink = (0, 0, 255) + ) -> None: ... + +class HorizontalGradiantColorMask(QRColorMask): + left_color: Ink + right_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), left_color: Ink = (0, 0, 0), right_color: Ink = (0, 0, 255) + ) -> None: ... + +class VerticalGradiantColorMask(QRColorMask): + top_color: Ink + bottom_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), top_color: Ink = (0, 0, 0), bottom_color: Ink = (0, 0, 255) + ) -> None: ... + +class ImageColorMask(QRColorMask): + color_img: Ink + def __init__( + self, + back_color: Ink = (255, 255, 255), + color_mask_path: str | bytes | Path | SupportsRead[bytes] | None = None, + color_mask_image: Image.Image | None = None, + ) -> None: ... + paint_color: Ink diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi new file mode 100644 index 000000000000..f51cacc6181d --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi @@ -0,0 +1,8 @@ +from .pil import ( + CircleModuleDrawer as CircleModuleDrawer, + GappedSquareModuleDrawer as GappedSquareModuleDrawer, + HorizontalBarsDrawer as HorizontalBarsDrawer, + RoundedModuleDrawer as RoundedModuleDrawer, + SquareModuleDrawer as SquareModuleDrawer, + VerticalBarsDrawer as VerticalBarsDrawer, +) diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi new file mode 100644 index 000000000000..74832b09b966 --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi @@ -0,0 +1,12 @@ +import abc + +from ...._types import Box +from ....main import ActiveWithNeighbors +from ...base import BaseImage + +class QRModuleDrawer(abc.ABC, metaclass=abc.ABCMeta): + needs_neighbors: bool = False + img: BaseImage + def initialize(self, img: BaseImage) -> None: ... + @abc.abstractmethod + def drawrect(self, box: Box, is_active: bool | ActiveWithNeighbors) -> None: ... diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi new file mode 100644 index 000000000000..637091661493 --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi @@ -0,0 +1,66 @@ +import abc +from typing import Literal + +from PIL import Image, ImageDraw + +from ...._types import Box +from ....main import ActiveWithNeighbors +from ...styledpil import StyledPilImage +from .base import QRModuleDrawer + +ANTIALIASING_FACTOR: int + +class StyledPilQRModuleDrawer(QRModuleDrawer, metaclass=abc.ABCMeta): + img: StyledPilImage + +class SquareModuleDrawer(StyledPilQRModuleDrawer): + imgDraw: ImageDraw.ImageDraw + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + +class GappedSquareModuleDrawer(StyledPilQRModuleDrawer): + size_ratio: float + def __init__(self, size_ratio: float = 0.8) -> None: ... + imgDraw: ImageDraw.ImageDraw + delta: float + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + +class CircleModuleDrawer(StyledPilQRModuleDrawer): + circle: Image.Image + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + +class RoundedModuleDrawer(StyledPilQRModuleDrawer): + needs_neighbors: Literal[True] + radius_ratio: float + def __init__(self, radius_ratio: float = 1) -> None: ... + corner_width: int + SQUARE: Image.Image + NW_ROUND: Image.Image + SW_ROUND: Image.Image + SE_ROUND: Image.Image + NE_ROUND: Image.Image + def setup_corners(self) -> None: ... + def drawrect(self, box: Box, is_active: ActiveWithNeighbors) -> None: ... # type: ignore[override] + +class VerticalBarsDrawer(StyledPilQRModuleDrawer): + needs_neighbors: Literal[True] + horizontal_shrink: float + def __init__(self, horizontal_shrink: float = 0.8) -> None: ... + half_height: int + delta: int + SQUARE: Image.Image + ROUND_TOP: Image.Image + ROUND_BOTTOM: Image.Image + def setup_edges(self) -> None: ... + def drawrect(self, box: Box, is_active: ActiveWithNeighbors) -> None: ... # type: ignore[override] + +class HorizontalBarsDrawer(StyledPilQRModuleDrawer): + needs_neighbors: Literal[True] + vertical_shrink: float + def __init__(self, vertical_shrink: float = 0.8) -> None: ... + half_width: int + delta: int + SQUARE: Image.Image + ROUND_LEFT: Image.Image + ROUND_RIGHT: Image.Image + def setup_edges(self) -> None: ... + def drawrect(self, box: Box, is_active: ActiveWithNeighbors) -> None: ... # type: ignore[override] diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi new file mode 100644 index 000000000000..dbbaa5653931 --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi @@ -0,0 +1,56 @@ +import abc +from decimal import Decimal +from typing import Any, NamedTuple +from xml.etree.ElementTree import Element, QName + +from ...._types import Box +from ...svg import SvgFragmentImage, SvgPathImage +from .base import QRModuleDrawer + +ANTIALIASING_FACTOR: int + +class Coords(NamedTuple): + x0: Decimal + y0: Decimal + x1: Decimal + y1: Decimal + xh: Decimal + yh: Decimal + +class BaseSvgQRModuleDrawer(QRModuleDrawer, metaclass=abc.ABCMeta): + img: SvgFragmentImage + size_ratio: Decimal + # kwargs are used to allow for subclasses with additional keyword arguments + def __init__(self, *, size_ratio: Decimal = ..., **kwargs: Any) -> None: ... + box_delta: float + box_size: Decimal + box_half: Decimal + def coords(self, box: Box) -> Coords: ... + +class SvgQRModuleDrawer(BaseSvgQRModuleDrawer, metaclass=abc.ABCMeta): + tag: str + tag_qname: QName + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + @abc.abstractmethod + def el(self, box: Box) -> Element: ... + +class SvgSquareDrawer(SvgQRModuleDrawer): + unit_size: str + def el(self, box: Box) -> Element: ... + +class SvgCircleDrawer(SvgQRModuleDrawer): + tag: str + radius: str + def el(self, box: Box) -> Element: ... + +class SvgPathQRModuleDrawer(BaseSvgQRModuleDrawer, metaclass=abc.ABCMeta): + img: SvgPathImage + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + @abc.abstractmethod + def subpath(self, box: Box) -> str: ... + +class SvgPathSquareDrawer(SvgPathQRModuleDrawer): + def subpath(self, box: Box) -> str: ... + +class SvgPathCircleDrawer(SvgPathQRModuleDrawer): + def subpath(self, box: Box) -> str: ... diff --git a/stubs/qrcode/qrcode/image/svg.pyi b/stubs/qrcode/qrcode/image/svg.pyi new file mode 100644 index 000000000000..b5f662dbf869 --- /dev/null +++ b/stubs/qrcode/qrcode/image/svg.pyi @@ -0,0 +1,69 @@ +import abc +from decimal import Decimal +from typing import Any, Literal, overload +from xml.etree.ElementTree import Element + +from . import base +from .styles.moduledrawers.base import QRModuleDrawer + +class SvgFragmentImage(base.BaseImageWithDrawer, metaclass=abc.ABCMeta): + kind: str + allowed_kinds: tuple[Literal["SVG"]] + default_drawer_class: type[QRModuleDrawer] + unit_size: Decimal | str + + @overload + def units(self, pixels: int | Decimal, text: Literal[False]) -> Decimal: ... + @overload + def units(self, pixels: int | Decimal, text: Literal[True] = True) -> str: ... + + # to_string is delegated to ET.Element.tostring, which dictates the overload + # options here. + @overload + def to_string( + self, + *, + encoding: None = None, + method: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + ) -> bytes: ... + @overload + def to_string( + self, + *, + encoding: Literal["unicode"], + method: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + ) -> str: ... + @overload + def to_string( + self, + *, + encoding: str, + method: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + ) -> Any: ... + + # the new_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> Element: ... + +class SvgImage(SvgFragmentImage, metaclass=abc.ABCMeta): + background: str | None + drawer_aliases: base.DrawerAliases + +class SvgPathImage(SvgImage, metaclass=abc.ABCMeta): + QR_PATH_STYLE: dict[str, str] + path: Element | None + +class SvgFillImage(SvgImage, metaclass=abc.ABCMeta): + background: str + +class SvgPathFillImage(SvgPathImage, metaclass=abc.ABCMeta): + background: str diff --git a/stubs/qrcode/qrcode/main.pyi b/stubs/qrcode/qrcode/main.pyi new file mode 100644 index 000000000000..2c2fb05b2f72 --- /dev/null +++ b/stubs/qrcode/qrcode/main.pyi @@ -0,0 +1,139 @@ +from _typeshed import ConvertibleToInt +from collections.abc import Sequence +from typing import Any, Generic, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from ._types import ErrorCorrect, MaskPattern +from .image.base import BaseImage +from .image.pil import PilImage +from .image.pure import PyPNGImage +from .util import QRData + +ModulesType: TypeAlias = list[list[bool | None]] +precomputed_qr_blanks: dict[int, ModulesType] + +_DefaultImage: TypeAlias = PilImage | PyPNGImage # PilImage if Pillow is installed, PyPNGImage otherwise +_AnySeq = TypeVar("_AnySeq", bound=Sequence[Any]) + +@overload +def make( + data: QRData | bytes | str, + *, + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: None = None, + mask_pattern: MaskPattern | None = None, +) -> _DefaultImage: ... +@overload +def make( + data: QRData | bytes | str, + *, + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: type[GenericImage], + mask_pattern: MaskPattern | None = None, +) -> GenericImage: ... + +def copy_2d_array(x: Sequence[_AnySeq]) -> list[_AnySeq]: ... + +class ActiveWithNeighbors(NamedTuple): + NW: bool + N: bool + NE: bool + W: bool + me: bool + E: bool + SW: bool + S: bool + SE: bool + def __bool__(self) -> bool: ... + +GenericImage = TypeVar("GenericImage", bound=BaseImage) # noqa: Y001 +GenericImageLocal = TypeVar("GenericImageLocal", bound=BaseImage) # noqa: Y001 + +@type_check_only +class _TTYWriter(Protocol): + def isatty(self) -> bool: ... + def write(self, s: str, /) -> object: ... + def flush(self) -> object: ... + +class QRCode(Generic[GenericImage]): + modules: ModulesType + error_correction: ErrorCorrect + box_size: int + border: int + image_factory: type[GenericImage] | None + + @overload + def __init__( + self, + version: ConvertibleToInt | None, + error_correction: ErrorCorrect, + box_size: ConvertibleToInt, + border: ConvertibleToInt, + image_factory: type[GenericImage], + mask_pattern: MaskPattern | None = None, + ) -> None: ... + @overload + def __init__( + self, + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + *, + image_factory: type[GenericImage], + mask_pattern: MaskPattern | None = None, + ) -> None: ... + @overload + def __init__( + self: QRCode[_DefaultImage], + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: None = None, + mask_pattern: MaskPattern | None = None, + ) -> None: ... + + @property + def version(self) -> int: ... + @version.setter + def version(self, value: ConvertibleToInt | None) -> None: ... + + @property + def mask_pattern(self) -> MaskPattern | None: ... + @mask_pattern.setter + def mask_pattern(self, pattern: MaskPattern | None) -> None: ... + + modules_count: int + data_cache: list[int] + data_list: list[QRData] + def clear(self) -> None: ... + def add_data(self, data: QRData | bytes | str, optimize: int = 20) -> None: ... + def make(self, fit: bool = True) -> None: ... + def makeImpl(self, test: bool, mask_pattern: MaskPattern) -> None: ... + def setup_position_probe_pattern(self, row: int, col: int) -> None: ... + def best_fit(self, start: int | None = None) -> int: ... + def best_mask_pattern(self) -> int: ... + def print_tty(self, out: _TTYWriter | None = None) -> None: ... + def print_ascii(self, out: _TTYWriter | None = None, tty: bool = False, invert: bool = False) -> None: ... + + # kwargs are passed on to the specific image factory used, and in turn passed through to + # their make_image method. + @overload + def make_image(self, image_factory: None = None, **kwargs: Any) -> GenericImage: ... + @overload + def make_image(self, image_factory: type[GenericImageLocal], **kwargs: Any) -> GenericImageLocal: ... + + def is_constrained(self, row: int, col: int) -> bool: ... + def setup_timing_pattern(self) -> None: ... + def setup_position_adjust_pattern(self) -> None: ... + def setup_type_number(self, test: bool) -> None: ... + def setup_type_info(self, test: bool, mask_pattern: MaskPattern) -> None: ... + def map_data(self, data: Sequence[int], mask_pattern: MaskPattern) -> None: ... + def get_matrix(self) -> list[list[bool]]: ... + def active_with_neighbors(self, row: int, col: int) -> ActiveWithNeighbors: ... diff --git a/stubs/qrcode/qrcode/release.pyi b/stubs/qrcode/qrcode/release.pyi new file mode 100644 index 000000000000..823dd58f3e15 --- /dev/null +++ b/stubs/qrcode/qrcode/release.pyi @@ -0,0 +1 @@ +def update_manpage(data: dict[str, str]) -> None: ... diff --git a/stubs/qrcode/qrcode/util.pyi b/stubs/qrcode/qrcode/util.pyi new file mode 100644 index 000000000000..0144c7951ecf --- /dev/null +++ b/stubs/qrcode/qrcode/util.pyi @@ -0,0 +1,70 @@ +from collections.abc import Callable, Generator +from re import Pattern +from typing import Final, Literal, TypeAlias, overload + +from ._types import ErrorCorrect, MaskPattern +from .base import RSBlock as RSBlock + +MODE_NUMBER: Final[int] = 1 +MODE_ALPHA_NUM: Final[int] = 2 +MODE_8BIT_BYTE: Final[int] = 4 +MODE_KANJI: Final[int] = 8 + +_MODE: TypeAlias = Literal[1, 2, 4, 8] + +MODE_SIZE_SMALL: Final[dict[_MODE, int]] +MODE_SIZE_MEDIUM: Final[dict[_MODE, int]] +MODE_SIZE_LARGE: Final[dict[_MODE, int]] + +ALPHA_NUM: Final[bytes] +RE_ALPHA_NUM: Final[Pattern[bytes]] +NUMBER_LENGTH: Final[dict[int, int]] +PATTERN_POSITION_TABLE: Final[list[list[int]]] +G15: Final[int] +G18: Final[int] +G15_MASK: Final[int] +PAD0: Final[int] +PAD1: Final[int] +BIT_LIMIT_TABLE: Final[list[list[int]]] + +# In the implementation, MODE_KANJI is not accepted in all places +_SupportedMode: TypeAlias = Literal[1, 2, 4] + +def BCH_type_info(data: int) -> int: ... +def BCH_type_number(data: int) -> int: ... +def BCH_digit(data: int) -> int: ... +def pattern_position(version: int) -> list[int]: ... +def mask_func(pattern: MaskPattern) -> Callable[[int, int], bool]: ... +def mode_sizes_for_version(version: int) -> dict[_MODE, int]: ... +def length_in_bits(mode: _MODE, version: int) -> int: ... +def check_version(version: int) -> None: ... +def lost_point(modules: list[list[bool | None]]) -> int: ... +def optimal_data_chunks(data: str | bytes, minimum: int = 4) -> Generator[QRData]: ... +def to_bytestring(data: str | bytes) -> bytes: ... +def optimal_mode(data: bytes) -> _SupportedMode: ... + +class QRData: + mode: _SupportedMode + data: bytes + + @overload + def __init__(self, data: bytes | str, mode: _SupportedMode | None = None, check_data: Literal[True] = True) -> None: ... + @overload + def __init__(self, data: bytes, mode: _SupportedMode | None = None, *, check_data: Literal[False]) -> None: ... + @overload + def __init__(self, data: bytes, mode: _SupportedMode | None, check_data: Literal[False]) -> None: ... + + def __len__(self) -> int: ... + def write(self, buffer: BitBuffer) -> None: ... + +class BitBuffer: + buffer: list[int] + length: int + def __init__(self) -> None: ... + def get(self, index: int) -> bool: ... + def put(self, num: int, length: int) -> None: ... + def __len__(self) -> int: ... + def put_bit(self, bit: bool) -> None: ... + +def create_bytes(buffer: BitBuffer, rs_blocks: list[RSBlock]) -> list[int]: ... +def create_data(version: int, error_correction: ErrorCorrect, data_list: list[QRData]) -> list[int]: ... diff --git a/stubs/rasterio/@tests/stubtest_allowlist.txt b/stubs/rasterio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..4b4577f911be --- /dev/null +++ b/stubs/rasterio/@tests/stubtest_allowlist.txt @@ -0,0 +1,42 @@ +# Stubs-only helper modules with no runtime counterpart. +rasterio\._typing + +# Stubs-only type aliases referenced in signatures only. +rasterio\.merge\.MethodFunction + +# Cython implementation-detail attributes auto-generated on every +# Cython-compiled module and extension class. +.*\.__pyx_capi__ +.*\.__test__ +.*\.__reduce_cython__ +.*\.__setstate_cython__ + +# attrs-generated introspection helpers on every @attr.s class. +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_props__ + +# attrs-generated comparators and pattern-matching dunders on the +# specific @attr.s classes in the package (these are auto-generated by +# `order=True` / `eq=True`; not part of the documented API surface). +rasterio\._path\._ParsedPath\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\._path\._UnparsedPath\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.env\.GDALVersion\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.rpc\.RPC\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.windows\.Window\.__(ge|gt|le|lt|match_args|replace)__ + +# Cython param-name drift and @disjoint_base markers for private +# extension modules. Public API surface is reconciled in the +# corresponding public `rasterio.*` modules. +rasterio\._base.* +rasterio\._io.* +rasterio\._env.* +rasterio\._err.* +rasterio\._features.* +rasterio\._transform.* + +# Vendored third-party packages — not part of rasterio's public API. +rasterio\._vendor\..* + +# Click-based CLI subpackage — not exposed through type-checked imports. +rasterio\.rio.* diff --git a/stubs/rasterio/METADATA.toml b/stubs/rasterio/METADATA.toml new file mode 100644 index 000000000000..b01fd962d5cc --- /dev/null +++ b/stubs/rasterio/METADATA.toml @@ -0,0 +1,4 @@ +version = "1.5.2" +upstream-repository = "https://github.com/rasterio/rasterio" +requires-python = ">=3.12" +dependencies = ["numpy>=2", "click>=8", "affine>=3"] diff --git a/stubs/rasterio/rasterio/__init__.pyi b/stubs/rasterio/rasterio/__init__.pyi new file mode 100644 index 000000000000..0fe6afa52c86 --- /dev/null +++ b/stubs/rasterio/rasterio/__init__.pyi @@ -0,0 +1,132 @@ +import logging +import os +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, NamedTuple, TypeAlias, overload + +from numpy.typing import DTypeLike, NDArray +from rasterio._base import DatasetBase as DatasetBase +from rasterio._io import Statistics as Statistics +from rasterio._path import _parse_path as _parse_path, _UnparsedPath as _UnparsedPath +from rasterio._show_versions import show_versions as show_versions +from rasterio._typing import AnyDataset, CRSInput, _Opener, _OpenOption +from rasterio._version import ( + gdal_version as gdal_version, + get_geos_version as get_geos_version, + get_proj_version as get_proj_version, +) +from rasterio._vsiopener import _opener_registration as _opener_registration +from rasterio.crs import CRS as CRS +from rasterio.drivers import driver_from_extension as driver_from_extension, is_blacklisted as is_blacklisted +from rasterio.dtypes import ( + bool_ as bool_, + check_dtype as check_dtype, + complex_ as complex_, + complex_int16 as complex_int16, + float16 as float16, + float32 as float32, + float64 as float64, + int8 as int8, + int16 as int16, + int32 as int32, + int64 as int64, + sbyte as sbyte, + ubyte as ubyte, + uint8 as uint8, + uint16 as uint16, + uint32 as uint32, + uint64 as uint64, +) +from rasterio.env import Env as Env, ensure_env_with_credentials as ensure_env_with_credentials +from rasterio.errors import ( + DriverCapabilityError as DriverCapabilityError, + RasterioDeprecationWarning as RasterioDeprecationWarning, + RasterioIOError as RasterioIOError, +) +from rasterio.io import ( + BufferedDatasetWriter as BufferedDatasetWriter, + DatasetReader as DatasetReader, + DatasetWriter as DatasetWriter, + FilePath as FilePath, + MemoryFile as MemoryFile, + get_writer_for_driver as get_writer_for_driver, + get_writer_for_path as get_writer_for_path, +) +from rasterio.profiles import default_gtiff_profile as default_gtiff_profile +from rasterio.transform import Affine as Affine, guard_transform as guard_transform + +__all__ = ["CRS", "Band", "Env", "band", "open", "pad"] + +__version__: Final[str] +__gdal_version__: Final[str] +__proj_version__: Final[str] +__geos_version__: Final[str] + +have_vsi_plugin: Final[bool] +log: logging.Logger + +_Fp: TypeAlias = str | os.PathLike[str] | MemoryFile | FilePath + +@overload +def open( + fp: _Fp, + mode: Literal["r"] = "r", + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetReader: ... +@overload +def open( + fp: _Fp, + mode: Literal["r+", "w", "w+"], + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetWriter: ... +@overload +def open( + fp: _Fp, + mode: str = "r", + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetReader | DatasetWriter: ... + +class Band(NamedTuple): + ds: AnyDataset + bidx: int | Sequence[int] + dtype: str + shape: tuple[int, ...] + +def band(ds: AnyDataset, bidx: int | Sequence[int]) -> Band: ... + +# `mode` and `**kwargs` mirror `numpy.pad`'s signature; see numpy.pad documentation. +def pad( + array: NDArray[Any], transform: Affine, pad_width: int, mode: str | Callable[..., Any] | None = None, **kwargs: Any +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/_base.pyi b/stubs/rasterio/rasterio/_base.pyi new file mode 100644 index 000000000000..503fc835e84f --- /dev/null +++ b/stubs/rasterio/rasterio/_base.pyi @@ -0,0 +1,173 @@ +import logging +import os +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self, deprecated + +from affine import Affine as Affine +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio._typing import Colormap, CRSInput, _OpenOption +from rasterio.control import GroundControlPoint +from rasterio.coords import BoundingBox +from rasterio.crs import CRS +from rasterio.enums import ColorInterp, Compression, Interleaving, MaskFlags, PhotometricInterp +from rasterio.profiles import Profile +from rasterio.rpc import RPC +from rasterio.windows import Window + +log: Final[logging.Logger] + +def get_dataset_driver(path: str) -> str: ... +def driver_supports_mode(drivername: str, creation_mode: str) -> bool: ... +def driver_can_create(drivername: str) -> bool: ... +def driver_can_create_copy(drivername: str) -> bool: ... +def tastes_like_gdal(seq: Affine | Sequence[float]) -> bool: ... +def _raster_driver_extensions() -> dict[str, str]: ... +def _can_create_osr(crs: CRSInput) -> bool: ... +def _transform( + src_crs: CRSInput, dst_crs: CRSInput, xs: Sequence[float], ys: Sequence[float], zs: Sequence[float] | None +) -> tuple[list[float], list[float], list[float]]: ... + +class DatasetBase: + name: str + mode: str + options: dict[str, Any] + width: int + height: int + shape: tuple[int, int] + driver: str + + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath | None = None, + driver: str | Sequence[str] | None = None, + sharing: bool = False, + thread_safe: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def read_crs(self) -> CRS | None: ... + def read_transform(self) -> list[float]: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def close(self) -> None: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + @property + def count(self) -> int: ... + @property + def indexes(self) -> tuple[int, ...]: ... + @property + def dtypes(self) -> tuple[str, ...]: ... + @property + def block_shapes(self) -> tuple[tuple[int, int], ...]: ... + def get_nodatavals(self) -> tuple[float | None, ...]: ... + @property + def nodatavals(self) -> tuple[float | None, ...]: ... + + @property + def nodata(self) -> float | None: ... + @nodata.setter + def nodata(self, value: float | None) -> None: ... + + @property + def mask_flag_enums(self) -> tuple[list[MaskFlags], ...]: ... + + @property + def crs(self) -> CRS: ... + @crs.setter + def crs(self, value: CRSInput) -> None: ... + + @property + def descriptions(self) -> tuple[str | None, ...]: ... + @descriptions.setter + def descriptions(self, value: Sequence[str | None]) -> None: ... + + def write_transform(self, transform: Sequence[float]) -> None: ... + + @property + def transform(self) -> Affine: ... + @transform.setter + def transform(self, value: Affine) -> None: ... + + @property + def offsets(self) -> tuple[float, ...]: ... + @offsets.setter + def offsets(self, value: Sequence[float]) -> None: ... + + @property + def scales(self) -> tuple[float, ...]: ... + @scales.setter + def scales(self, value: Sequence[float]) -> None: ... + + @property + def units(self) -> tuple[str | None, ...]: ... + @units.setter + def units(self, value: Sequence[str | None]) -> None: ... + + def block_window(self, bidx: int, i: int, j: int) -> Window: ... + def block_size(self, bidx: int, i: int, j: int) -> int: ... + def block_windows(self, bidx: int = 0) -> Iterable[tuple[tuple[int, int], Window]]: ... + @property + def bounds(self) -> BoundingBox: ... + @property + def res(self) -> tuple[float, float]: ... + @property + def meta(self) -> dict[str, Any]: ... + @property + def compression(self) -> Compression | None: ... + @property + def interleaving(self) -> Interleaving | None: ... + @property + def photometric(self) -> PhotometricInterp | None: ... + @property + @deprecated("DatasetBase.is_tiled will be removed in a future rasterio release; inspect block_shapes / profile directly.") + def is_tiled(self) -> bool: ... + @property + def profile(self) -> Profile: ... + def lnglat(self) -> tuple[float, float]: ... + def get_transform(self) -> list[float]: ... + @property + def subdatasets(self) -> list[str]: ... + def tag_namespaces(self, bidx: int = 0) -> list[str]: ... + def tags(self, bidx: int = 0, ns: str | None = None) -> dict[str, str]: ... + def get_tag_item(self, ns: str, dm: str | None = None, bidx: int = 0, ovr: int | None = None) -> str | None: ... + + @property + def colorinterp(self) -> tuple[ColorInterp, ...]: ... + @colorinterp.setter + def colorinterp(self, value: Sequence[ColorInterp]) -> None: ... + + def colormap(self, bidx: int) -> Colormap: ... + def overviews(self, bidx: int) -> list[int]: ... + def checksum(self, bidx: int, window: Window | None = None) -> int: ... + def get_gcps(self) -> tuple[list[GroundControlPoint], CRS]: ... + + @property + def gcps(self) -> tuple[list[GroundControlPoint], CRS]: ... + @gcps.setter + def gcps(self, value: tuple[Sequence[GroundControlPoint], CRSInput]) -> None: ... + + @property + def rpcs(self) -> RPC | None: ... + @rpcs.setter + def rpcs(self, value: RPC | None) -> None: ... + + @property + def files(self) -> list[str]: ... + +_GDAL_AT_LEAST_3_10: Final[bool] + +complex64: Final[str] +complex128: Final[str] +complex_int16: Final[str] +float32: Final[str] +float64: Final[str] +int16: Final[str] + +def _parse_path(path: str) -> _ParsedPath | _UnparsedPath: ... diff --git a/stubs/rasterio/rasterio/_env.pyi b/stubs/rasterio/rasterio/_env.pyi new file mode 100644 index 000000000000..60dadbc6b7b2 --- /dev/null +++ b/stubs/rasterio/rasterio/_env.pyi @@ -0,0 +1,43 @@ +from contextlib import AbstractContextManager +from typing import Final + +from rasterio._typing import _GDALOption as _GDALOption + +ca_bundle: Final[str] +code_map: Final[dict[int, int]] +level_map: Final[dict[int, int]] + +def gdal_version() -> str: ... +def get_gdal_config(key: str, normalize: bool = True) -> _GDALOption: ... +def set_gdal_config(key: str, val: _GDALOption, normalize: bool = True) -> None: ... +def del_gdal_config(key: str) -> None: ... +def get_gdal_data() -> str | None: ... +def get_proj_data_search_paths() -> list[str]: ... +def set_proj_data_search_path(path: str) -> None: ... +def driver_count() -> int: ... +def catch_errors() -> AbstractContextManager[None]: ... + +class ConfigEnv: + options: dict[str, _GDALOption] + def __init__(self, **options: _GDALOption) -> None: ... + def update_config_options(self, **kwargs: _GDALOption) -> None: ... + def clear_config_options(self) -> None: ... + def get_config_options(self) -> dict[str, _GDALOption]: ... + +class GDALEnv(ConfigEnv): + def __init__(self, **options: _GDALOption) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + +class GDALDataFinder: + def find_file(self, basename: str) -> str | None: ... + def search(self, prefix: str | None = None) -> str | None: ... + def search_wheel(self, prefix: str | None = None) -> str | None: ... + def search_prefix(self, prefix: str) -> str | None: ... + def search_debian(self, prefix: str) -> str | None: ... + +class PROJDataFinder: + def has_data(self) -> bool: ... + def search(self, prefix: str | None = None) -> str | None: ... + def search_wheel(self, prefix: str | None = None) -> str | None: ... + def search_prefix(self, prefix: str) -> str | None: ... diff --git a/stubs/rasterio/rasterio/_err.pyi b/stubs/rasterio/rasterio/_err.pyi new file mode 100644 index 000000000000..84e6be115d76 --- /dev/null +++ b/stubs/rasterio/rasterio/_err.pyi @@ -0,0 +1,41 @@ +from contextlib import AbstractContextManager +from enum import IntEnum +from typing import Final + +class GDALError(IntEnum): + none = 0 + debug = 1 + warning = 2 + failure = 3 + fatal = 4 + +class CPLE_BaseError(Exception): + error: int + errno: int + errmsg: str + def __init__(self, error: int, errno: int, errmsg: str) -> None: ... + +class CPLE_AppDefinedError(CPLE_BaseError): ... +class CPLE_AssertionFailedError(CPLE_BaseError): ... +class CPLE_FileIOError(CPLE_BaseError): ... +class CPLE_HttpResponseError(CPLE_BaseError): ... +class CPLE_IllegalArgError(CPLE_BaseError): ... +class CPLE_NoWriteAccessError(CPLE_BaseError): ... +class CPLE_NotSupportedError(CPLE_BaseError): ... +class CPLE_OpenFailedError(CPLE_BaseError): ... +class CPLE_OutOfMemoryError(CPLE_BaseError): ... +class CPLE_UserInterruptError(CPLE_BaseError): ... +class CPLE_AWSAccessDeniedError(CPLE_BaseError): ... +class CPLE_AWSBucketNotFoundError(CPLE_BaseError): ... +class CPLE_AWSError(CPLE_BaseError): ... +class CPLE_AWSInvalidCredentialsError(CPLE_BaseError): ... +class CPLE_AWSObjectNotFoundError(CPLE_BaseError): ... +class CPLE_AWSSignatureDoesNotMatchError(CPLE_BaseError): ... +class ObjectNullError(CPLE_BaseError): ... + +exception_map: Final[dict[int, type[CPLE_BaseError]]] + +class StackChecker: + def __init__(self) -> None: ... + +def stack_errors() -> AbstractContextManager[StackChecker]: ... diff --git a/stubs/rasterio/rasterio/_features.pyi b/stubs/rasterio/rasterio/_features.pyi new file mode 100644 index 000000000000..2fec9414185a --- /dev/null +++ b/stubs/rasterio/rasterio/_features.pyi @@ -0,0 +1,34 @@ +from collections.abc import Iterator +from typing import Any, Final + +from rasterio._typing import _OGRGeometry +from rasterio.enums import MergeAlg as MergeAlg + +GEOMETRY_TYPES: Final[dict[int, str]] +GEOJSON2OGR_GEOMETRY_TYPES: Final[dict[str, int]] + +bool_: Final[str] +int8: Final[str] +int16: Final[str] +int32: Final[str] +int64: Final[str] +uint8: Final[str] +uint16: Final[str] +uint32: Final[str] +uint64: Final[str] +float16: Final[str] +float32: Final[str] +float64: Final[str] + +# Cython-side builders. `geom` arguments are opaque C structs / OGR +# geometry handles passed through `__pyx_capi__`; not surfaced via the +# public `rasterio.features` API. +class GeomBuilder: + def build(self, geom: object) -> dict[str, Any]: ... + +class OGRGeomBuilder: + def build(self, geom: dict[str, Any]) -> _OGRGeometry: ... + +class ShapeIterator: + def __iter__(self) -> Iterator[tuple[dict[str, Any], float]]: ... + def __next__(self) -> tuple[dict[str, Any], float]: ... diff --git a/stubs/rasterio/rasterio/_filepath.pyi b/stubs/rasterio/rasterio/_filepath.pyi new file mode 100644 index 000000000000..0cd22e067c4c --- /dev/null +++ b/stubs/rasterio/rasterio/_filepath.pyi @@ -0,0 +1,14 @@ +from typing import TypeVar + +_FileT = TypeVar("_FileT") + +class FilePathBase: + # Cython base for FilePath; constructor and overall surface are + # implementation details — see `rasterio.io.FilePath` for the public API. + def __init__(self, *args: object, **kwargs: object) -> None: ... + def close(self) -> None: ... + def exists(self) -> bool: ... + +# Clones any file-like object (BytesIO, MemoryFile, fsspec file, Python +# file object); the returned object has the same concrete type as `fobj`. +def clone_file_obj(fobj: _FileT) -> _FileT: ... diff --git a/stubs/rasterio/rasterio/_io.pyi b/stubs/rasterio/rasterio/_io.pyi new file mode 100644 index 000000000000..bd0ce16ba759 --- /dev/null +++ b/stubs/rasterio/rasterio/_io.pyi @@ -0,0 +1,177 @@ +import os +from collections.abc import Iterator, Sequence +from typing import Any, BinaryIO, Final +from typing_extensions import Self, deprecated + +import numpy as np +from affine import Affine as Affine +from numpy.typing import DTypeLike, NDArray +from rasterio._base import DatasetBase +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio._typing import Colormap, CRSInput, Indexes, NumType, ShapeND, WindowInput, _GDALOption, _OpenOption +from rasterio.control import GroundControlPoint +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +def validate_resampling(resampling: Resampling) -> None: ... +def virtual_file_to_buffer(filename: str) -> bytes: ... +def _is_complex_int(dtype: DTypeLike) -> bool: ... +def _getnpdtype(dtype: DTypeLike) -> np.dtype[Any]: ... +def _gdal_typename(dt: DTypeLike) -> str: ... +def _get_gdal_dtype(type_name: DTypeLike) -> int: ... +def _boundless_vrt_doc( + src_dataset: DatasetBase, + nodata: float | None = None, + background: float | None = None, + hidenodata: bool = False, + width: int | None = None, + height: int | None = None, + transform: Affine | None = None, + masked: bool = False, + resampling: Resampling = ..., +) -> str: ... +def sample_gen( + dataset: DatasetBase, xy: Sequence[tuple[float, float]], indexes: Indexes | None = None, masked: bool = False +) -> Iterator[NDArray[Any]]: ... + +class Statistics: + min: float + max: float + mean: float + std: float + def __init__(self, min: float, max: float, mean: float, std: float) -> None: ... + +class DatasetReaderBase(DatasetBase): + def read( + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + window: WindowInput | None = None, + masked: bool = False, + out_shape: ShapeND | None = None, + boundless: bool = False, + resampling: Resampling = ..., + fill_value: NumType | None = None, + out_dtype: DTypeLike | None = None, + ) -> NDArray[Any]: ... + def read_masks( + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + boundless: bool = False, + resampling: Resampling = ..., + ) -> NDArray[Any]: ... + def dataset_mask( + self, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + boundless: bool = False, + resampling: Resampling = ..., + ) -> NDArray[Any]: ... + def sample( + self, xy: Sequence[tuple[float, float]], indexes: Indexes | None = None, masked: bool = False + ) -> Iterator[NDArray[Any]]: ... + def stats(self, *, indexes: Indexes | None = None, approx: bool = False) -> list[Statistics]: ... + @deprecated("DatasetReaderBase.statistics() will be removed in 2.0.0; please switch to stats().") + def statistics(self, bidx: int, approx: bool = False, clear_cache: bool = False) -> Statistics: ... + +class MemoryFileBase: + name: str + mode: str + closed: bool + def __init__( + self, + file_or_bytes: bytes | BinaryIO | None = None, + dirname: str | None = None, + filename: str | None = None, + ext: str = "", + ) -> None: ... + def __len__(self) -> int: ... + def exists(self) -> bool: ... + def getbuffer(self) -> memoryview: ... + def close(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def tell(self) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def write(self, data: bytes) -> int: ... + +class DatasetWriterBase(DatasetReaderBase): + name: str + mode: str + width: int + height: int + shape: tuple[int, int] + driver: str + + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath, + mode: str, + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + sharing: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def write( + self, arr: NDArray[Any], indexes: Indexes | None = None, window: WindowInput | None = None, masked: bool = False + ) -> None: ... + def write_band(self, bidx: int, src: NDArray[Any], window: WindowInput | None = None) -> None: ... + def update_tags(self, bidx: int = 0, ns: str | None = None, **kwargs: _GDALOption) -> None: ... + def set_band_description(self, bidx: int, value: str) -> None: ... + def set_band_unit(self, bidx: int, value: str) -> None: ... + def write_colormap(self, bidx: int, colormap: Colormap) -> None: ... + def write_mask(self, mask_array: NDArray[Any], window: WindowInput | None = None) -> None: ... + def build_overviews(self, factors: Sequence[int], resampling: Resampling = ...) -> None: ... + def update_stats( + self, *, stats: Sequence[Statistics] | None = None, indexes: Indexes | None = None, approx: bool = False + ) -> None: ... + def clear_stats(self) -> None: ... + +class MemoryDataset(DatasetWriterBase): + def __init__( + self, + image: NDArray[Any] | None = None, + dtype: DTypeLike | None = None, + count: int = 1, + width: int | None = None, + height: int | None = None, + transform: Affine | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + crs: CRSInput | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + +class BufferedDatasetWriterBase(DatasetWriterBase): + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath, + mode: str = "w", + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + sharing: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def stop(self) -> None: ... + +int8: Final[str] +uint8: Final[str] diff --git a/stubs/rasterio/rasterio/_path.pyi b/stubs/rasterio/rasterio/_path.pyi new file mode 100644 index 000000000000..cf9b098d569c --- /dev/null +++ b/stubs/rasterio/rasterio/_path.pyi @@ -0,0 +1,34 @@ +import os +from typing import Any, Final +from typing_extensions import Self + +SCHEMES: Final[dict[str, str]] +ARCHIVESCHEMES: Final[type[set[Any]]] +CURLSCHEMES: Final[set[str]] +REMOTESCHEMES: Final[set[str]] + +class _Path: + def as_vsi(self) -> str: ... + +class _ParsedPath(_Path): + path: str + archive: str | None + scheme: str | None + def __init__(self, path: str, archive: str | None, scheme: str | None) -> None: ... + @classmethod + def from_uri(cls, uri: str) -> Self: ... + @property + def name(self) -> str: ... + @property + def is_remote(self) -> bool: ... + @property + def is_local(self) -> bool: ... + +class _UnparsedPath(_Path): + path: str + def __init__(self, path: str) -> None: ... + @property + def name(self) -> str: ... + +def _parse_path(path: str | os.PathLike[str] | _Path) -> _ParsedPath | _UnparsedPath: ... +def _vsi_path(path: _Path) -> str: ... diff --git a/stubs/rasterio/rasterio/_show_versions.pyi b/stubs/rasterio/rasterio/_show_versions.pyi new file mode 100644 index 000000000000..1eeec0747405 --- /dev/null +++ b/stubs/rasterio/rasterio/_show_versions.pyi @@ -0,0 +1 @@ +def show_versions() -> None: ... diff --git a/stubs/rasterio/rasterio/_transform.pyi b/stubs/rasterio/rasterio/_transform.pyi new file mode 100644 index 000000000000..350f8c05cd60 --- /dev/null +++ b/stubs/rasterio/rasterio/_transform.pyi @@ -0,0 +1,16 @@ +from collections.abc import Sequence + +from rasterio._typing import _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.errors import TransformWarning as TransformWarning +from rasterio.rpc import RPC + +class GCPTransformerBase: + def __init__(self, gcps: Sequence[GroundControlPoint]) -> None: ... + def close(self) -> None: ... + +class RPCTransformerBase: + def __init__(self, rpcs: RPC, **kwargs: _GDALOption) -> None: ... + def close(self) -> None: ... + +def _transform_from_gcps(gcps: Sequence[GroundControlPoint]) -> tuple[float, ...]: ... diff --git a/stubs/rasterio/rasterio/_typing.pyi b/stubs/rasterio/rasterio/_typing.pyi new file mode 100644 index 000000000000..a1011123b397 --- /dev/null +++ b/stubs/rasterio/rasterio/_typing.pyi @@ -0,0 +1,64 @@ +from collections.abc import Callable, Mapping, Sequence +from enum import Enum +from typing import Any, BinaryIO, Protocol, TypeAlias, type_check_only + +from rasterio.crs import CRS +from rasterio.io import DatasetReaderBase, MemoryFile +from rasterio.windows import Window + +# `DatasetReaderBase` covers every readable dataset handle: DatasetReader, +# DatasetWriter, BufferedDatasetWriter, MemoryDataset, and WarpedVRT (via +# WarpedVRTReaderBase). `MemoryFile` is a file wrapper, not a dataset. +AnyDataset: TypeAlias = DatasetReaderBase | MemoryFile + +@type_check_only +class _SupportsGeoInterface(Protocol): + @property + def __geo_interface__(self) -> Mapping[str, Any]: ... + +@type_check_only +class _SupportsToWkt(Protocol): + def to_wkt(self) -> str: ... + +# A GeoJSON-like mapping, or any object exposing one through the +# `__geo_interface__` protocol (e.g. shapely / geopandas geometries). +# The runtime unwraps `__geo_interface__` before use, so both forms are +# accepted anywhere a geometry is expected. +Geometry: TypeAlias = Mapping[str, Any] | _SupportsGeoInterface # noqa: Y047 +Colormap: TypeAlias = dict[int, tuple[int, int, int] | tuple[int, int, int, int]] +# A WKT / PROJ string, an EPSG code, a PROJ dict, or any object exposing +# `to_wkt` (e.g. a pyproj CRS). `CRS.from_user_input` normalizes all of them. +CRSInput: TypeAlias = str | int | dict[str, str] | CRS | _SupportsToWkt +FileOrBytes: TypeAlias = BinaryIO | bytes +Indexes: TypeAlias = int | Sequence[int] +NumType: TypeAlias = int | float +ShapeND: TypeAlias = Sequence[int] +WindowInput: TypeAlias = Window | tuple[tuple[int, int], tuple[int, int]] + +# Scalar values accepted by every GDAL CSL-style option list: global +# config (`set_gdal_config` / `Env`), per-call warp options +# (NUM_THREADS, INIT_DEST, …), RPC/transformer options (RPC_HEIGHT, +# RPC_DEM, COORDINATE_OPERATION, …), and metadata tag values. The +# runtime stringifies each value at the C boundary and does not +# special-case Enum or tuple types here (use `_OpenOption` for those). +_GDALOption: TypeAlias = str | int | float | bool | None # noqa: Y047 + +# GDAL driver-specific open/creation option values. The runtime coerces +# every value to a string at the C boundary; documented usage covers +# scalars, Enum members (encoded as `.name.upper()`), and tuples of +# scalars (joined with commas). Lists are not handled specially — pass +# a tuple if you need a multi-value option. +_OpenOption: TypeAlias = str | int | float | bool | Enum | tuple[str | int | float | bool, ...] | None # noqa: Y047 + +# Opaque OGR geometry handle (a Cython-wrapped C object). Callers only +# pass it back to other Cython internals; the public API surfaces +# already-decoded GeoJSON-like dicts. +_OGRGeometry: TypeAlias = Any # noqa: Y047 + +# Scalar or arbitrarily nested list of scalars; used by helpers that +# recurse into sequences while preserving the nesting depth. +_NestedScalar: TypeAlias = float | list[_NestedScalar] # noqa: Y047 + +# fsspec-style opener forwarded to `rasterio.open(opener=...)`: +# `(path: str, mode: str) -> file-like`. +_Opener: TypeAlias = Callable[..., Any] # noqa: Y047 diff --git a/stubs/rasterio/rasterio/_version.pyi b/stubs/rasterio/rasterio/_version.pyi new file mode 100644 index 000000000000..063e03ad00dd --- /dev/null +++ b/stubs/rasterio/rasterio/_version.pyi @@ -0,0 +1,5 @@ +def gdal_version() -> str: ... +def get_gdal_version_info(key: str) -> str: ... +def check_gdal_version(major: int, minor: int) -> bool: ... +def get_geos_version() -> tuple[int, int, int]: ... +def get_proj_version() -> tuple[int, int, int]: ... diff --git a/stubs/rasterio/rasterio/_vsiopener.pyi b/stubs/rasterio/rasterio/_vsiopener.pyi new file mode 100644 index 000000000000..0354d31dc260 --- /dev/null +++ b/stubs/rasterio/rasterio/_vsiopener.pyi @@ -0,0 +1,36 @@ +from abc import ABC, abstractmethod +from contextlib import AbstractContextManager +from typing import Any, BinaryIO + +from rasterio.errors import OpenerRegistrationError as OpenerRegistrationError + +class FileContainer(ABC): + @abstractmethod + def open(self, path: str, mode: str = "r", **kwds: Any) -> BinaryIO: ... + @abstractmethod + def isdir(self, path: str) -> bool: ... + @abstractmethod + def isfile(self, path: str) -> bool: ... + @abstractmethod + def ls(self, path: str) -> list[str]: ... + @abstractmethod + def mtime(self, path: str) -> int: ... + @abstractmethod + def rm(self, path: str) -> None: ... + @abstractmethod + def size(self, path: str) -> int: ... + +class MultiByteRangeResource(ABC): + @abstractmethod + def get_byte_ranges(self, offsets: list[int], sizes: list[int]) -> list[bytes]: ... + +class MultiByteRangeResourceContainer(FileContainer): + @abstractmethod + def open(self, path: str, **kwds: Any) -> MultiByteRangeResource: ... # type: ignore[override] + +# Duck-typed adapter: `obj` may be a `FileContainer` subclass or any +# object exposing the fsspec filesystem protocol (`hasattr(obj, "file_size")`). +def to_pyopener(obj: Any) -> FileContainer: ... + +# `obj` accepts the same types as `to_pyopener` plus raw callables. +def _opener_registration(urlpath: str, obj: Any) -> AbstractContextManager[str]: ... diff --git a/stubs/rasterio/rasterio/_warp.pyi b/stubs/rasterio/rasterio/_warp.pyi new file mode 100644 index 000000000000..a50b4e37564f --- /dev/null +++ b/stubs/rasterio/rasterio/_warp.pyi @@ -0,0 +1,153 @@ +from collections.abc import Sequence +from typing import Any, Final, overload +from typing_extensions import deprecated + +from affine import Affine as Affine +from numpy.typing import DTypeLike, NDArray +from rasterio._io import DatasetReaderBase, DatasetWriterBase +from rasterio._typing import CRSInput, Geometry, Indexes, ShapeND, WindowInput, _GDALOption, _NestedScalar +from rasterio.control import GroundControlPoint +from rasterio.crs import CRS +from rasterio.dtypes import dtype_ranges as dtype_ranges +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +SUPPORTED_RESAMPLING: Final[list[Resampling]] +DEFAULT_NODATA_FLAG: Final[object] + +def recursive_round(val: _NestedScalar, precision: int) -> _NestedScalar: ... +def _transform_geom( + src_crs: CRSInput, dst_crs: CRSInput, geom: Geometry | Sequence[Geometry], precision: int +) -> dict[str, Any] | list[dict[str, Any]]: ... +def _reproject( + source: NDArray[Any] | Any, + destination: NDArray[Any] | Any, + src_transform: Affine | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + src_crs: CRSInput | None = None, + src_nodata: float | None = None, + dst_transform: Affine | None = None, + dst_crs: CRSInput | None = None, + dst_nodata: float | None = None, + dst_alpha: int = 0, + src_alpha: int = 0, + resampling: Resampling = ..., + init_dest_nodata: bool = True, + tolerance: float = 0.125, + num_threads: int = 1, + warp_mem_limit: int = 0, + working_data_type: int = 0, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[NDArray[Any], Affine]: ... +def _calculate_default_transform( + src_crs: CRSInput, + dst_crs: CRSInput, + width: int, + height: int, + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[Affine, int, int]: ... +def _transform_bounds( + src_crs: CRS, dst_crs: CRS, left: float, bottom: float, right: float, top: float, densify_pts: int +) -> tuple[float, float, float, float]: ... +def _suggested_proxy_vrt_doc( + width: int, + height: int, + transform: Affine | None = None, + crs: CRSInput | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, +) -> str: ... + +class WarpedVRTReaderBase(DatasetReaderBase): + src_dataset: DatasetReaderBase + src_crs: CRS + src_transform: Affine | None + resampling: Resampling + tolerance: float + src_nodata: float | None + dst_nodata: float | None + working_dtype: DTypeLike | None + warp_extras: dict[str, _GDALOption] + + @overload + @deprecated( + "Source datasets opened in modes other than 'r' emit a " + "RasterioDeprecationWarning and will be disallowed in a future rasterio " + "release; reopen the dataset read-only before wrapping it." + ) + def __init__( + self, + src_dataset: DatasetWriterBase, + src_crs: CRSInput | None = None, + crs: CRSInput | None = None, + resampling: Resampling = ..., + tolerance: float = 0.125, + src_nodata: float | None = ..., + nodata: float | None = ..., + width: int | None = None, + height: int | None = None, + src_transform: Affine | None = None, + transform: Affine | None = None, + init_dest_nodata: bool = True, + src_alpha: int = 0, + dst_alpha: int = 0, + add_alpha: bool = False, + warp_mem_limit: int = 0, + dtype: DTypeLike | None = None, + **warp_extras: _GDALOption, + ) -> None: ... + @overload + def __init__( + self, + src_dataset: DatasetReaderBase, + src_crs: CRSInput | None = None, + crs: CRSInput | None = None, + resampling: Resampling = ..., + tolerance: float = 0.125, + src_nodata: float | None = ..., + nodata: float | None = ..., + width: int | None = None, + height: int | None = None, + src_transform: Affine | None = None, + transform: Affine | None = None, + init_dest_nodata: bool = True, + src_alpha: int = 0, + dst_alpha: int = 0, + add_alpha: bool = False, + warp_mem_limit: int = 0, + dtype: DTypeLike | None = None, + **warp_extras: _GDALOption, + ) -> None: ... + + def read( # type: ignore[override] + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + window: WindowInput | None = None, + masked: bool = False, + out_shape: ShapeND | None = None, + resampling: Resampling = ..., + fill_value: float | None = None, + out_dtype: DTypeLike | None = None, + # Swallows the deprecated `boundless` kwarg (raises ValueError if True). + **kwargs: bool, + ) -> NDArray[Any]: ... + def read_masks( # type: ignore[override] + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + resampling: Resampling = ..., + # Swallows the deprecated `boundless` kwarg (raises ValueError if True). + **kwargs: bool, + ) -> NDArray[Any]: ... diff --git a/stubs/rasterio/rasterio/abc.pyi b/stubs/rasterio/rasterio/abc.pyi new file mode 100644 index 000000000000..d9ebb71719e0 --- /dev/null +++ b/stubs/rasterio/rasterio/abc.pyi @@ -0,0 +1 @@ +from rasterio._vsiopener import FileContainer as FileContainer, MultiByteRangeResourceContainer as MultiByteRangeResourceContainer diff --git a/stubs/rasterio/rasterio/cache.pyi b/stubs/rasterio/rasterio/cache.pyi new file mode 100644 index 000000000000..ab1f8b285843 --- /dev/null +++ b/stubs/rasterio/rasterio/cache.pyi @@ -0,0 +1,2 @@ +def invalidate(pattern: str) -> None: ... +def invalidate_all() -> None: ... diff --git a/stubs/rasterio/rasterio/control.pyi b/stubs/rasterio/rasterio/control.pyi new file mode 100644 index 000000000000..0fbec047e6be --- /dev/null +++ b/stubs/rasterio/rasterio/control.pyi @@ -0,0 +1,46 @@ +from collections.abc import Sequence +from typing import Literal, TypedDict, type_check_only + +@type_check_only +class GroundControlPointDict(TypedDict): + id: str + info: str | None + row: float + col: float + x: float + y: float + z: float | None + +@type_check_only +class GroundControlPointGeometry(TypedDict): + type: Literal["Point"] + coordinates: Sequence[float] + +@type_check_only +class GroundControlPointFeature(TypedDict): + id: str + type: Literal["Feature"] + geometry: GroundControlPointGeometry + properties: GroundControlPointDict + +class GroundControlPoint: + id: str + info: str | None + row: float + col: float + x: float + y: float + z: float | None + def __init__( + self, + row: float | None = None, + col: float | None = None, + x: float | None = None, + y: float | None = None, + z: float | None = None, + id: str | None = None, + info: str | None = None, + ) -> None: ... + def asdict(self) -> GroundControlPointDict: ... + @property + def __geo_interface__(self) -> GroundControlPointFeature: ... diff --git a/stubs/rasterio/rasterio/coords.pyi b/stubs/rasterio/rasterio/coords.pyi new file mode 100644 index 000000000000..c7b97fc2fe31 --- /dev/null +++ b/stubs/rasterio/rasterio/coords.pyi @@ -0,0 +1,11 @@ +from typing import NamedTuple, TypeAlias + +_Quadruple: TypeAlias = tuple[float, float, float, float] + +class BoundingBox(NamedTuple): + left: float + bottom: float + right: float + top: float + +def disjoint_bounds(bounds1: BoundingBox | _Quadruple, bounds2: BoundingBox | _Quadruple) -> bool: ... diff --git a/stubs/rasterio/rasterio/crs.pyi b/stubs/rasterio/rasterio/crs.pyi new file mode 100644 index 000000000000..400c4c939d68 --- /dev/null +++ b/stubs/rasterio/rasterio/crs.pyi @@ -0,0 +1,69 @@ +from collections.abc import Iterator, Mapping +from typing import Any +from typing_extensions import Self, deprecated, disjoint_base + +from rasterio.enums import WktVersion + +all_proj_keys: set[str] + +@disjoint_base +class CRS(Mapping[str, Any]): + def __init__(self, initialdata: Mapping[str, Any] | None = None, **kwargs: Any) -> None: ... + def __getitem__(self, key: str, /) -> Any: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __eq__(self, other: object, /) -> bool: ... + def __copy__(self) -> Self: ... + def __hash__(self) -> int: ... + def __getstate__(self) -> dict[str, Any]: ... + def __setstate__(self, state: Mapping[str, Any]) -> None: ... + def to_proj4(self) -> str: ... + def to_wkt(self, morph_to_esri_dialect: bool = False, version: WktVersion | str | None = None) -> str: ... + @property + def wkt(self) -> str: ... + def to_epsg(self, confidence_threshold: int = 70) -> int | None: ... + def to_authority(self, confidence_threshold: int = 70) -> tuple[str, str] | None: ... + def to_dict(self, projjson: bool = False) -> dict[str, Any]: ... + @property + def data(self) -> dict[str, Any]: ... + @property + def is_geographic(self) -> bool: ... + @property + def is_projected(self) -> bool: ... + @property + @deprecated("CRS.is_valid is deprecated since rasterio 1.4 and will be removed in 2.0.0.") + def is_valid(self) -> bool: ... + @property + def is_epsg_code(self) -> bool: ... + @property + def linear_units_factor(self) -> tuple[str, float]: ... + @property + def linear_units(self) -> str: ... + @property + def units_factor(self) -> tuple[str, float]: ... + @property + def geodetic_crs(self) -> CRS | None: ... + def to_string(self) -> str: ... + def equals(self, other: CRS, ignore_axis_order: bool = False) -> bool: ... + def get(self, item: str) -> Any: ... # type: ignore[override] + @staticmethod + def from_epsg(code: int | str) -> CRS: ... + @staticmethod + def from_authority(auth_name: str, code: int | str) -> CRS: ... + @staticmethod + def from_string(value: str, morph_from_esri_dialect: bool = False) -> CRS: ... + @staticmethod + def from_proj4(proj: str) -> CRS: ... + @staticmethod + def from_dict(initialdata: Mapping[str, Any] | None = None, **kwargs: Any) -> CRS: ... + @staticmethod + def from_wkt(wkt: str, morph_from_esri_dialect: bool = False) -> CRS: ... + # `value` is dispatched at runtime: CRS, int (EPSG), str (PROJ/WKT/auth), Mapping[str, Any], or any pyproj-CRS-like object. + @staticmethod + def from_user_input(value: Any, morph_from_esri_dialect: bool = False) -> CRS: ... + +def epsg_treats_as_latlong(input_crs: CRS) -> bool: ... +def epsg_treats_as_northingeasting(input_crs: CRS) -> bool: ... +def auth_preference(item: str) -> None: ... diff --git a/stubs/rasterio/rasterio/drivers.pyi b/stubs/rasterio/rasterio/drivers.pyi new file mode 100644 index 000000000000..96b6d727bd5b --- /dev/null +++ b/stubs/rasterio/rasterio/drivers.pyi @@ -0,0 +1,8 @@ +import os +from typing import Final + +blacklist: Final[dict[str, tuple[str, ...]]] + +def raster_driver_extensions() -> dict[str, str]: ... +def driver_from_extension(path: str | os.PathLike[str]) -> str: ... +def is_blacklisted(name: str, mode: str) -> bool: ... diff --git a/stubs/rasterio/rasterio/dtypes.pyi b/stubs/rasterio/rasterio/dtypes.pyi new file mode 100644 index 000000000000..f76501ed11d1 --- /dev/null +++ b/stubs/rasterio/rasterio/dtypes.pyi @@ -0,0 +1,46 @@ +from collections.abc import Sequence +from typing import Any, Final + +import numpy as np +from numpy.typing import ArrayLike, DTypeLike + +bool_: Final[str] +ubyte: Final[str] +uint8: Final[str] +sbyte: Final[str] +int8: Final[str] +uint16: Final[str] +int16: Final[str] +uint32: Final[str] +int32: Final[str] +int64: Final[str] +uint64: Final[str] +float16: Final[str] +float32: Final[str] +float64: Final[str] +complex_: Final[str] +complex64: Final[str] +complex128: Final[str] +complex_int16: Final[str] + +dtype_fwd: Final[dict[int, str | None]] +dtype_rev: Final[dict[str | None, int]] +typename_fwd: Final[dict[int, str]] +typename_rev: Final[dict[str, int]] +dtype_ranges: Final[dict[str, tuple[float, float]]] +dtype_info_registry: Final[dict[str, type]] + +# `numpy.finfo` instances cached at module import; used by `in_dtype_range`. +f16i: Final[np.finfo[np.float16]] +f32i: Final[np.finfo[np.float32]] +f64i: Final[np.finfo[np.float64]] + +def in_dtype_range(value: float, dtype: DTypeLike) -> bool: ... +def check_dtype(dt: DTypeLike) -> bool: ... +def get_minimum_dtype(values: ArrayLike) -> str: ... + +# isinstance check; accepts any object and returns True for numpy.ndarray +# and any object exposing `__array__`. +def is_ndarray(array: Any) -> bool: ... +def can_cast_dtype(values: ArrayLike, dtype: DTypeLike) -> bool: ... +def validate_dtype(values: ArrayLike, valid_dtypes: Sequence[DTypeLike]) -> bool: ... diff --git a/stubs/rasterio/rasterio/enums.pyi b/stubs/rasterio/rasterio/enums.pyi new file mode 100644 index 000000000000..6e1a2fc76a6b --- /dev/null +++ b/stubs/rasterio/rasterio/enums.pyi @@ -0,0 +1,126 @@ +from enum import Enum, IntEnum + +class TransformDirection(IntEnum): + forward = 1 + reverse = 0 + +class TransformMethod(Enum): + affine = "transform" + gcps = "gcps" + rpcs = "rpcs" + +class ColorInterp(IntEnum): + undefined = 0 + gray = 1 + grey = 1 + palette = 2 + red = 3 + green = 4 + blue = 5 + alpha = 6 + hue = 7 + saturation = 8 + lightness = 9 + cyan = 10 + magenta = 11 + yellow = 12 + black = 13 + Y = 14 + Cb = 15 + Cr = 16 + pan = 17 + coastal = 18 + rededge = 19 + nir = 20 + swir = 21 + mwir = 22 + lwir = 23 + tir = 24 + other_ir = 25 + sar_ka = 30 + sar_k = 31 + sar_ku = 32 + sar_x = 33 + sar_c = 34 + sar_s = 35 + sar_l = 36 + sar_p = 37 + +class Resampling(IntEnum): + nearest = 0 + bilinear = 1 + cubic = 2 + cubic_spline = 3 + lanczos = 4 + average = 5 + mode = 6 + gauss = 7 + max = 8 + min = 9 + med = 10 + q1 = 11 + q3 = 12 + sum = 13 + rms = 14 + +class OverviewResampling(IntEnum): + nearest = 0 + bilinear = 1 + cubic = 2 + cubic_spline = 3 + lanczos = 4 + average = 5 + mode = 6 + gauss = 7 + rms = 14 + +class Compression(Enum): + jpeg = "JPEG" + lzw = "LZW" + packbits = "PACKBITS" + deflate = "DEFLATE" + ccittrle = "CCITTRLE" + ccittfax3 = "CCITTFAX3" + ccittfax4 = "CCITTFAX4" + lzma = "LZMA" + none = "NONE" + zstd = "ZSTD" + lerc = "LERC" + lerc_deflate = "LERC_DEFLATE" + lerc_zstd = "LERC_ZSTD" + webp = "WEBP" + jpeg2000 = "JPEG2000" + +class Interleaving(Enum): + pixel = "PIXEL" + line = "LINE" + band = "BAND" + tile = "TILE" + +class MaskFlags(IntEnum): + all_valid = 1 + per_dataset = 2 + alpha = 4 + nodata = 8 + +class PhotometricInterp(Enum): + black = "MINISBLACK" + white = "MINISWHITE" + rgb = "RGB" + cmyk = "CMYK" + ycbcr = "YCbCr" + cielab = "CIELAB" + icclab = "ICCLAB" + itulab = "ITULAB" + +class MergeAlg(Enum): + replace = "REPLACE" + add = "ADD" + +class WktVersion(Enum): + WKT2_2015 = "WKT2_2015" + WKT2 = "WKT2" + WKT2_2019 = "WKT2_2018" + WKT1_GDAL = "WKT1_GDAL" + WKT1 = "WKT1" + WKT1_ESRI = "WKT1_ESRI" diff --git a/stubs/rasterio/rasterio/env.pyi b/stubs/rasterio/rasterio/env.pyi new file mode 100644 index 000000000000..3f5c57bfeb2a --- /dev/null +++ b/stubs/rasterio/rasterio/env.pyi @@ -0,0 +1,102 @@ +import logging +import threading +from collections.abc import Callable, Iterable +from types import TracebackType +from typing import Any, Final, TypeVar +from typing_extensions import Self, deprecated + +from rasterio._env import ( + GDALDataFinder as GDALDataFinder, + GDALEnv as GDALEnv, + PROJDataFinder as PROJDataFinder, + _GDALOption, + get_gdal_config as get_gdal_config, + set_gdal_config as set_gdal_config, + set_proj_data_search_path as set_proj_data_search_path, +) +from rasterio.errors import ( + EnvError as EnvError, + GDALVersionError as GDALVersionError, + RasterioDeprecationWarning as RasterioDeprecationWarning, +) +from rasterio.session import DummySession as DummySession, Session as Session + +_F = TypeVar("_F", bound=Callable[..., Any]) + +class ThreadEnv(threading.local): + def __init__(self) -> None: ... + +local: ThreadEnv +log: logging.Logger + +class Env: + session: Session + options: dict[str, _GDALOption] + context_options: dict[str, _GDALOption] + def __init__( + self, + session: Session | None = None, + aws_unsigned: bool = False, + profile_name: str | None = None, + session_class: Callable[..., Session] = ..., + **options: _GDALOption, + ) -> None: ... + @classmethod + def default_options(cls) -> dict[str, _GDALOption]: ... + # Forwarded to `cls(...)` after merging in default_options(); see __init__. + @classmethod + def from_defaults(cls, *args: Any, **kwargs: _GDALOption) -> Self: ... + def credentialize(self) -> None: ... + def aws_creds_from_context_options(self) -> dict[str, str]: ... + def drivers(self) -> dict[str, str]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: ... + +def defenv(**options: _GDALOption) -> None: ... +def getenv() -> dict[str, _GDALOption]: ... +def hasenv() -> bool: ... +def setenv(**options: _GDALOption) -> None: ... +@deprecated("Please use Env.session.hascreds() instead.") +def hascreds() -> bool: ... +def delenv() -> None: ... + +class NullContextManager: + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +def env_ctx_if_needed() -> Env | NullContextManager: ... +def ensure_env(f: _F) -> _F: ... +@deprecated("ensure_env_credentialled is a deprecated alias; use ensure_env_with_credentials instead.") +def ensure_env_credentialled(f: _F) -> _F: ... +def ensure_env_with_credentials(f: _F) -> _F: ... +def gdal_version() -> str: ... + +class GDALVersion: + major: int + minor: int + patch: int + def __init__(self, major: int = 0, minor: int = 0, patch: int = 0) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: GDALVersion) -> bool: ... + @classmethod + def parse(cls, input: str | GDALVersion, include_patch: bool = False) -> Self: ... + @classmethod + def runtime(cls, include_patch: bool = False) -> Self: ... + def at_least(self, other: str | GDALVersion, include_patch: bool = False) -> bool: ... + +def require_gdal_version( + version: str | GDALVersion, + param: str | None = None, + # `values` are matched against the decorated function's `param` argument; types depend on that argument. + values: Iterable[Any] | None = None, + is_max_version: bool = False, + reason: str = "", +) -> Callable[[_F], _F]: ... + +path: Final[str | None] diff --git a/stubs/rasterio/rasterio/errors.pyi b/stubs/rasterio/rasterio/errors.pyi new file mode 100644 index 000000000000..6e7425eb4fa7 --- /dev/null +++ b/stubs/rasterio/rasterio/errors.pyi @@ -0,0 +1,41 @@ +from click import FileError + +class RasterioError(Exception): ... +class InvalidArrayError(RasterioError): ... +class WindowError(RasterioError): ... +class CRSError(ValueError): ... +class EnvError(RasterioError): ... +class DriverCapabilityError(RasterioError, ValueError): ... +class DriverRegistrationError(ValueError): ... + +class FileOverwriteError(FileError): + def __init__(self, message: str) -> None: ... + +class RasterioIOError(RasterioError, OSError): ... +class NodataShadowWarning(UserWarning): ... +class NotGeoreferencedWarning(UserWarning): ... +class TransformWarning(UserWarning): ... +class RPCError(ValueError): ... +class InvalidShapeError(RasterioError, ValueError): ... +class ShapeSkipWarning(UserWarning): ... +class GDALBehaviorChangeException(RuntimeError): ... +class GDALOptionNotImplementedError(RasterioError): ... +class GDALVersionError(RasterioError): ... +class WindowEvaluationError(ValueError): ... +class RasterioDeprecationWarning(FutureWarning): ... +class RasterBlockError(RasterioError): ... +class BandOverviewError(UserWarning): ... +class WarpOptionsError(RasterioError): ... +class UnsupportedOperation(RasterioError): ... +class OverviewCreationError(RasterioError): ... +class DatasetAttributeError(RasterioError, NotImplementedError): ... +class PathError(RasterioError): ... +class ResamplingAlgorithmError(RasterioError): ... +class TransformError(RasterioError): ... +class WarpedVRTError(RasterioError): ... +class DatasetIOShapeError(RasterioError): ... +class WarpOperationError(RasterioError): ... +class StatisticsError(RasterioError): ... +class OpenerRegistrationError(RasterioError): ... +class MergeError(RasterioError): ... +class StackError(RasterioError): ... diff --git a/stubs/rasterio/rasterio/features.pyi b/stubs/rasterio/rasterio/features.pyi new file mode 100644 index 000000000000..303ca1f3de5e --- /dev/null +++ b/stubs/rasterio/rasterio/features.pyi @@ -0,0 +1,74 @@ +import logging +import os +from collections.abc import Iterable, Iterator +from typing import Any, Final, overload +from typing_extensions import deprecated + +import numpy as np +from affine import Affine as Affine +from numpy.typing import DTypeLike, NDArray +from rasterio._typing import Geometry as Geometry +from rasterio.enums import MergeAlg as MergeAlg +from rasterio.io import DatasetReaderBase +from rasterio.windows import Window as Window + +log: Final[logging.Logger] + +def geometry_mask( + geometries: Iterable[Geometry], out_shape: tuple[int, int], transform: Affine, all_touched: bool = False, invert: bool = False +) -> NDArray[np.bool_]: ... +def shapes( + source: NDArray[Any], mask: NDArray[np.bool_] | None = None, connectivity: int = 4, transform: Affine = ... +) -> Iterator[tuple[dict[str, Any], float | int]]: ... +def sieve( + source: NDArray[Any], size: int, out: NDArray[Any] | None = None, mask: NDArray[np.bool_] | None = None, connectivity: int = 4 +) -> NDArray[Any]: ... +def rasterize( + shapes: Iterable[tuple[Geometry, float] | Geometry], + out_shape: tuple[int, int] | None = None, + fill: float = 0, + nodata: float | None = None, + masked: bool = False, + out: NDArray[Any] | None = None, + transform: Affine = ..., + all_touched: bool = False, + merge_alg: MergeAlg = ..., + default_value: float = 1, + dtype: DTypeLike | None = None, + skip_invalid: bool = True, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> NDArray[Any]: ... +def bounds(geometry: Geometry, north_up: bool = True, transform: Affine | None = None) -> tuple[float, float, float, float]: ... + +@overload +def geometry_window( + dataset: DatasetReaderBase, shapes: Iterable[Geometry], pad_x: float = 0, pad_y: float = 0, *, boundless: bool = False +) -> Window: ... +@overload +@deprecated( + "`north_up`, `rotated`, and `pixel_precision` on features.geometry_window are " + "unused since rasterio 1.2.1 and will be removed in a future release." +) +def geometry_window( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + pad_x: float = 0, + pad_y: float = 0, + north_up: bool | None = None, + rotated: bool | None = None, + pixel_precision: float | None = None, + boundless: bool = False, +) -> Window: ... + +def is_valid_geom(geom: Geometry) -> bool: ... +def dataset_features( + src: DatasetReaderBase, + bidx: int | None = None, + sampling: int = 1, + band: bool = True, + as_mask: bool = False, + with_nodata: bool = False, + geographic: bool = True, + precision: int = -1, +) -> Iterator[dict[str, Any]]: ... diff --git a/stubs/rasterio/rasterio/fill.pyi b/stubs/rasterio/rasterio/fill.pyi new file mode 100644 index 000000000000..8f121f75a3a8 --- /dev/null +++ b/stubs/rasterio/rasterio/fill.pyi @@ -0,0 +1,11 @@ +from typing import Any + +from numpy.ma import MaskedArray +from numpy.typing import NDArray + +def fillnodata( + image: NDArray[Any] | MaskedArray[Any, Any], + mask: NDArray[Any] | None = None, + max_search_distance: float = 100.0, + smoothing_iterations: int = 0, +) -> NDArray[Any]: ... diff --git a/stubs/rasterio/rasterio/io.pyi b/stubs/rasterio/rasterio/io.pyi new file mode 100644 index 000000000000..c4308f98628a --- /dev/null +++ b/stubs/rasterio/rasterio/io.pyi @@ -0,0 +1,67 @@ +import logging +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self, deprecated + +from affine import Affine as Affine +from numpy.typing import DTypeLike +from rasterio._filepath import FilePathBase as FilePathBase +from rasterio._io import ( + BufferedDatasetWriterBase as BufferedDatasetWriterBase, + DatasetReaderBase as DatasetReaderBase, + DatasetWriterBase as DatasetWriterBase, + MemoryFileBase as MemoryFileBase, +) +from rasterio._typing import CRSInput, FileOrBytes, _OpenOption +from rasterio.transform import TransformMethodsMixin +from rasterio.windows import WindowMethodsMixin + +log: Final[logging.Logger] + +class DatasetReader(DatasetReaderBase, WindowMethodsMixin, TransformMethodsMixin): ... +class DatasetWriter(DatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin): ... +class BufferedDatasetWriter(BufferedDatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin): ... + +class MemoryFile(MemoryFileBase): + def __init__( + self, file_or_bytes: FileOrBytes | None = None, dirname: str | None = None, filename: str | None = None, ext: str = ".tif" + ) -> None: ... + def open( + self, + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + **kwargs: _OpenOption, + ) -> DatasetReader | DatasetWriter: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +class ZipMemoryFile(MemoryFile): + def __init__(self, file_or_bytes: FileOrBytes | None = None) -> None: ... + def open( # type: ignore[override] + self, path: str, driver: str | None = None, sharing: bool = False, thread_safe: bool = False, **kwargs: _OpenOption + ) -> DatasetReader: ... + +@deprecated("FilePath is supplanted by rasterio.open's `opener` keyword argument and will be removed in 2.0.0.") +class FilePath(FilePathBase): + # `filelike_obj`: any Python file-like object (BytesIO, fsspec file, etc.). + def __init__(self, filelike_obj: Any, dirname: str | None = None, filename: str | None = None) -> None: ... + def open( + self, driver: str | None = None, sharing: bool = False, thread_safe: bool = False, **kwargs: _OpenOption + ) -> DatasetReader: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +def get_writer_for_driver(driver: str) -> type[DatasetWriter | BufferedDatasetWriter] | None: ... +def get_writer_for_path(path: str, driver: str | None = None) -> type[DatasetWriter | BufferedDatasetWriter] | None: ... diff --git a/stubs/rasterio/rasterio/mask.pyi b/stubs/rasterio/rasterio/mask.pyi new file mode 100644 index 000000000000..e0259b0c1d42 --- /dev/null +++ b/stubs/rasterio/rasterio/mask.pyi @@ -0,0 +1,34 @@ +import logging +from collections.abc import Iterable +from typing import Any, Final + +from affine import Affine as Affine +from numpy.typing import NDArray +from rasterio._typing import Geometry +from rasterio.errors import WindowError as WindowError +from rasterio.features import geometry_mask as geometry_mask, geometry_window as geometry_window +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +def raster_geometry_mask( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + all_touched: bool = False, + invert: bool = False, + crop: bool = False, + pad: bool = False, + pad_width: float = 0.5, +) -> tuple[NDArray[Any], Affine, tuple[int, int, int, int]]: ... +def mask( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + all_touched: bool = False, + invert: bool = False, + nodata: float | None = None, + filled: bool = True, + crop: bool = False, + pad: bool = False, + pad_width: float = 0.5, + indexes: int | Iterable[int] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/merge.pyi b/stubs/rasterio/rasterio/merge.pyi new file mode 100644 index 000000000000..e9713eb21dcb --- /dev/null +++ b/stubs/rasterio/rasterio/merge.pyi @@ -0,0 +1,65 @@ +import logging +import os +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import deprecated + +from affine import Affine as Affine +from numpy.typing import DTypeLike, NDArray +from rasterio.enums import Resampling +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +MethodFunction: TypeAlias = Callable[..., None] +MERGE_METHODS: Final[dict[str, MethodFunction]] + +_Arr: TypeAlias = NDArray[Any] + +# `**kwargs` on each merge method accepts forwarded options from `merge()` (e.g. `index`); ignored otherwise. +def copy_first(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_last(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_min(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_max(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_sum(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_count(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... + +@overload +def merge( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + *, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + method: Literal["first", "last", "min", "max", "sum", "count"] | MethodFunction = "first", + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... +@overload +@deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") +def merge( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + precision: int | None = None, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + method: Literal["first", "last", "min", "max", "sum", "count"] | MethodFunction = "first", + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/path.pyi b/stubs/rasterio/rasterio/path.pyi new file mode 100644 index 000000000000..b5e935ebfd94 --- /dev/null +++ b/stubs/rasterio/rasterio/path.pyi @@ -0,0 +1,13 @@ +from typing import TypeAlias +from typing_extensions import deprecated + +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning + +ParsedPath: TypeAlias = _ParsedPath +UnparsedPath: TypeAlias = _UnparsedPath + +@deprecated("rasterio.path.parse_path is deprecated; use rasterio._path._parse_path or pass paths directly to rasterio.open.") +def parse_path(path: str) -> _ParsedPath | _UnparsedPath: ... +@deprecated("rasterio.path.vsi_path is deprecated; use rasterio._path._vsi_path directly.") +def vsi_path(path: _ParsedPath | _UnparsedPath) -> str: ... diff --git a/stubs/rasterio/rasterio/plot.pyi b/stubs/rasterio/rasterio/plot.pyi new file mode 100644 index 000000000000..a407bb686479 --- /dev/null +++ b/stubs/rasterio/rasterio/plot.pyi @@ -0,0 +1,49 @@ +import logging +from collections.abc import Mapping, Sequence +from typing import Any, Final, Literal + +from affine import Affine as Affine +from numpy.typing import NDArray +from rasterio.io import DatasetReader as DatasetReader +from rasterio.transform import guard_transform as guard_transform + +logger: Final[logging.Logger] + +# Returns the `matplotlib.pyplot` module (lazy import). +def get_plt() -> Any: ... + +# `ax`: matplotlib.axes.Axes; returns matplotlib.image.AxesImage or +# the input `ax` for contour plots. `**kwargs` are forwarded to +# matplotlib's `imshow`/`contour` call. +def show( + source: NDArray[Any] | DatasetReader | tuple[DatasetReader, int], + with_bounds: bool = True, + contour: bool = False, + contour_label_kws: Mapping[str, Any] | None = None, + indexes: Sequence[int] | None = None, + ax: Any | None = None, + title: str | None = None, + transform: Affine | None = None, + percent_range: tuple[float, float] | None = None, + adjust: bool = False, + **kwargs: Any, +) -> Any: ... +def plotting_extent( + source: NDArray[Any] | DatasetReader, transform: Affine | None = None +) -> tuple[float, float, float, float]: ... +def reshape_as_image(arr: NDArray[Any]) -> NDArray[Any]: ... +def reshape_as_raster(arr: NDArray[Any]) -> NDArray[Any]: ... + +# `ax`: matplotlib.axes.Axes; `**kwargs` are forwarded to matplotlib's `hist` call. +def show_hist( + source: NDArray[Any] | DatasetReader, + bins: int = 10, + masked: bool = True, + title: str = "Histogram", + ax: Any | None = None, + label: str | Sequence[str] | None = None, + range: tuple[float, float] | None = None, + **kwargs: Any, +) -> None: ... +def adjust_band(band: NDArray[Any], kind: Literal["linear", "log"] | None = None) -> NDArray[Any]: ... +def contrast_strech(arr: NDArray[Any], percent_range: tuple[float, float] = (2.0, 98.0)) -> NDArray[Any]: ... diff --git a/stubs/rasterio/rasterio/profiles.pyi b/stubs/rasterio/rasterio/profiles.pyi new file mode 100644 index 000000000000..27bc61f92351 --- /dev/null +++ b/stubs/rasterio/rasterio/profiles.pyi @@ -0,0 +1,15 @@ +from collections import UserDict +from typing import Any, ClassVar, Final + +# A `Profile` is a dict of GDAL driver-specific dataset-creation options +# (e.g. `count`, `dtype`, `compress`); value types depend on the option. +class Profile(UserDict[str, Any]): + defaults: ClassVar[dict[str, Any]] + def __init__(self, data: dict[str, Any] = ..., **kwds: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, val: Any) -> None: ... + +class DefaultGTiffProfile(Profile): + defaults: ClassVar[dict[str, Any]] + +default_gtiff_profile: Final[DefaultGTiffProfile] diff --git a/stubs/rasterio/rasterio/rpc.pyi b/stubs/rasterio/rasterio/rpc.pyi new file mode 100644 index 000000000000..b4e2be46df5c --- /dev/null +++ b/stubs/rasterio/rasterio/rpc.pyi @@ -0,0 +1,44 @@ +from collections.abc import Sequence +from typing import Any +from typing_extensions import Self + +class RPC: + height_off: float + height_scale: float + lat_off: float + lat_scale: float + line_den_coeff: Sequence[float] + line_num_coeff: Sequence[float] + line_off: float + line_scale: float + long_off: float + long_scale: float + samp_den_coeff: Sequence[float] + samp_num_coeff: Sequence[float] + samp_off: float + samp_scale: float + err_bias: float | None + err_rand: float | None + def __init__( + self, + height_off: float, + height_scale: float, + lat_off: float, + lat_scale: float, + line_den_coeff: Sequence[float], + line_num_coeff: Sequence[float], + line_off: float, + line_scale: float, + long_off: float, + long_scale: float, + samp_den_coeff: Sequence[float], + samp_num_coeff: Sequence[float], + samp_off: float, + samp_scale: float, + err_bias: float | None = None, + err_rand: float | None = None, + ) -> None: ... + def to_dict(self) -> dict[str, Any]: ... + def to_gdal(self) -> dict[str, str]: ... + @classmethod + def from_gdal(cls, rpcs: dict[str, str]) -> Self: ... diff --git a/stubs/rasterio/rasterio/sample.pyi b/stubs/rasterio/rasterio/sample.pyi new file mode 100644 index 000000000000..4d7722bae293 --- /dev/null +++ b/stubs/rasterio/rasterio/sample.pyi @@ -0,0 +1,13 @@ +from collections.abc import Iterable, Iterator, Sequence +from typing import Any + +from numpy.typing import NDArray +from rasterio.io import DatasetReaderBase + +def sample_gen( + dataset: DatasetReaderBase, + xy: Iterable[tuple[float, float]], + indexes: int | Sequence[int] | None = None, + masked: bool = False, +) -> Iterator[NDArray[Any]]: ... +def sort_xy(xy: Iterable[tuple[float, float]]) -> list[tuple[float, float]]: ... diff --git a/stubs/rasterio/rasterio/serde.pyi b/stubs/rasterio/rasterio/serde.pyi new file mode 100644 index 000000000000..fa06f4908611 --- /dev/null +++ b/stubs/rasterio/rasterio/serde.pyi @@ -0,0 +1,4 @@ +from functools import singledispatch + +@singledispatch +def to_json(obj: object) -> object: ... diff --git a/stubs/rasterio/rasterio/session.pyi b/stubs/rasterio/rasterio/session.pyi new file mode 100644 index 000000000000..4a78d07976a1 --- /dev/null +++ b/stubs/rasterio/rasterio/session.pyi @@ -0,0 +1,112 @@ +import logging +from typing import Any, Final + +log: Final[logging.Logger] + +def parse_bool(v: bool | str | int) -> bool: ... + +class Session: + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + def get_credential_options(self) -> dict[str, str]: ... + # `session` is a foreign session object (e.g. boto3.session.Session, + # google.auth.credentials.Credentials); the runtime dispatches by isinstance. + @staticmethod + def from_foreign_session(session: Any, cls: type[Session] | None = None) -> Session: ... + @staticmethod + def cls_from_path(path: str) -> type[Session]: ... + # Forwarded to the resolved session class' __init__; see its signature. + @staticmethod + def from_path(path: str, *args: Any, **kwargs: Any) -> Session: ... + @staticmethod + def aws_or_dummy(*args: Any, **kwargs: Any) -> Session: ... + @staticmethod + def from_environ(*args: Any, **kwargs: Any) -> Session: ... + +class DummySession(Session): + credentials: dict[str, str] + # Accepts and ignores any args (no credentials are configured). + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + def get_credential_options(self) -> dict[str, str]: ... + +class AWSSession(Session): + requester_pays: bool + unsigned: bool + endpoint_url: str | None + def __init__( + self, + # A `boto3.session.Session` instance, or None to construct one from the other kwargs. + session: Any | None = None, + aws_unsigned: bool | None = None, + aws_access_key_id: str | None = None, + aws_secret_access_key: str | None = None, + aws_session_token: str | None = None, + region_name: str | None = None, + profile_name: str | None = None, + endpoint_url: str | None = None, + requester_pays: bool = False, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class OSSSession(Session): + def __init__( + self, oss_access_key_id: str | None = None, oss_secret_access_key: str | None = None, oss_endpoint: str | None = None + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class GSSession(Session): + def __init__(self, google_application_credentials: str | None = None) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class SwiftSession(Session): + def __init__( + self, + # A `swiftclient.Connection` instance, or None to construct one from the other kwargs. + session: Any | None = None, + swift_storage_url: str | None = None, + swift_auth_token: str | None = None, + swift_auth_v1_url: str | None = None, + swift_user: str | None = None, + swift_key: str | None = None, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class AzureSession(Session): + unsigned: bool + storage_account: str | None + def __init__( + self, + azure_storage_connection_string: str | None = None, + azure_storage_account: str | None = None, + azure_storage_access_token: str | None = None, + azure_storage_access_key: str | None = None, + azure_storage_sas_token: str | None = None, + azure_unsigned: bool = False, + azure_tenant_id: str | None = None, + azure_client_id: str | None = None, + azure_federated_token_file: str | None = None, + azure_authority_host: str | None = None, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... diff --git a/stubs/rasterio/rasterio/shutil.pyi b/stubs/rasterio/rasterio/shutil.pyi new file mode 100644 index 000000000000..409a657b8b8d --- /dev/null +++ b/stubs/rasterio/rasterio/shutil.pyi @@ -0,0 +1,16 @@ +import os +from typing import Any + +from rasterio._typing import _OpenOption + +def exists(path: str | os.PathLike[str]) -> bool: ... +def copy( + # An open dataset handle (DatasetReader / DatasetWriter / DatasetBase) or a path. + src: str | os.PathLike[str] | Any, + dst: str | os.PathLike[str], + driver: str | None = None, + strict: bool = True, + **creation_options: _OpenOption, +) -> None: ... +def copyfiles(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: ... +def delete(path: str | os.PathLike[str], driver: str | None = None) -> None: ... diff --git a/stubs/rasterio/rasterio/stack.pyi b/stubs/rasterio/rasterio/stack.pyi new file mode 100644 index 000000000000..307ffa1a5b64 --- /dev/null +++ b/stubs/rasterio/rasterio/stack.pyi @@ -0,0 +1,28 @@ +import logging +import os +from collections.abc import Sequence +from typing import Any, Final + +from affine import Affine as Affine +from numpy.typing import DTypeLike, NDArray +from rasterio.enums import Resampling +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +def stack( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/tools.pyi b/stubs/rasterio/rasterio/tools.pyi new file mode 100644 index 000000000000..0d78bca77964 --- /dev/null +++ b/stubs/rasterio/rasterio/tools.pyi @@ -0,0 +1,19 @@ +import os +from collections.abc import Callable, Iterable +from typing import Any, Final + +class JSONSequenceTool: + func: Callable[..., Iterable[Any]] + def __init__(self, func: Callable[..., Iterable[Any]]) -> None: ... + def __call__( + self, + src_path: str | os.PathLike[str], + dst_path: str | os.PathLike[str], + src_kwargs: dict[str, Any] | None = None, + dst_kwargs: dict[str, Any] | None = None, + func_args: Iterable[Any] | None = None, + func_kwargs: dict[str, Any] | None = None, + config: dict[str, Any] | None = None, + ) -> None: ... + +dataset_features_tool: Final[JSONSequenceTool] diff --git a/stubs/rasterio/rasterio/transform.pyi b/stubs/rasterio/rasterio/transform.pyi new file mode 100644 index 000000000000..7a365f1a66d5 --- /dev/null +++ b/stubs/rasterio/rasterio/transform.pyi @@ -0,0 +1,112 @@ +from collections.abc import Callable, Sequence +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Self, deprecated + +from affine import Affine as Affine +from rasterio._transform import GCPTransformerBase, RPCTransformerBase +from rasterio._typing import _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.enums import TransformDirection as TransformDirection, TransformMethod as TransformMethod +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning +from rasterio.rpc import RPC + +_Sextuple: TypeAlias = tuple[float, float, float, float, float, float] +_OffsetOptions: TypeAlias = Literal["center", "ul", "ur", "ll", "lr"] +_RoundOperation: TypeAlias = Callable[[float], int] + +IDENTITY: Final[Affine] +GDAL_IDENTITY: Final[_Sextuple] + +class TransformMethodsMixin: + def xy( + self, + row: int | Sequence[int], + col: int | Sequence[int], + z: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + transform_method: TransformMethod = ..., + **rpc_options: _GDALOption, + ) -> tuple[float, float] | tuple[list[float], list[float]]: ... + def index( + self, + x: float | Sequence[float], + y: float | Sequence[float], + z: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + transform_method: TransformMethod = ..., + **rpc_options: _GDALOption, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + +def tastes_like_gdal(seq: Affine | _Sextuple) -> bool: ... +def guard_transform(transform: Affine | _Sextuple) -> Affine: ... +def from_origin(west: float, north: float, xsize: float, ysize: float) -> Affine: ... +def from_bounds(west: float, south: float, east: float, north: float, width: float, height: float) -> Affine: ... +def array_bounds(height: int, width: int, transform: Affine) -> tuple[float, float, float, float]: ... +def from_gcps(gcps: Sequence[GroundControlPoint]) -> Affine: ... +def xy( + transform: Affine | Sequence[GroundControlPoint] | RPC, + rows: int | Sequence[int], + cols: int | Sequence[int], + zs: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + **rpc_options: _GDALOption, +) -> tuple[float, float] | tuple[list[float], list[float]]: ... +def rowcol( + transform: Affine | Sequence[GroundControlPoint] | RPC, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + **rpc_options: _GDALOption, +) -> tuple[int, int] | tuple[list[int], list[int]]: ... +def get_transformer( + transform: Affine | Sequence[GroundControlPoint] | RPC, **rpc_options: _GDALOption +) -> type[TransformerBase]: ... + +class TransformerBase: + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def xy( + self, + rows: int | Sequence[int], + cols: int | Sequence[int], + zs: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + ) -> tuple[float, float] | tuple[list[float], list[float]]: ... + + @overload + def rowcol( + self, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + @overload + @deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") + def rowcol( + self, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + +class GDALTransformerBase(TransformerBase): + def __init__(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +class AffineTransformer(TransformerBase): + def __init__(self, affine_transform: Affine | _Sextuple) -> None: ... + +class GCPTransformer(GCPTransformerBase, GDALTransformerBase): + def __init__(self, gcps: Sequence[GroundControlPoint], tps: bool = False) -> None: ... + +class RPCTransformer(RPCTransformerBase, GDALTransformerBase): + def __init__(self, rpcs: RPC, **rpc_options: _GDALOption) -> None: ... diff --git a/stubs/rasterio/rasterio/vrt.pyi b/stubs/rasterio/rasterio/vrt.pyi new file mode 100644 index 000000000000..308e932590a2 --- /dev/null +++ b/stubs/rasterio/rasterio/vrt.pyi @@ -0,0 +1,13 @@ +from types import TracebackType +from typing_extensions import Self + +from rasterio._warp import WarpedVRTReaderBase +from rasterio.transform import TransformMethodsMixin +from rasterio.windows import WindowMethodsMixin + +class WarpedVRT(WarpedVRTReaderBase, WindowMethodsMixin, TransformMethodsMixin): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... diff --git a/stubs/rasterio/rasterio/warp.pyi b/stubs/rasterio/rasterio/warp.pyi new file mode 100644 index 000000000000..ffd58099a02f --- /dev/null +++ b/stubs/rasterio/rasterio/warp.pyi @@ -0,0 +1,85 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from typing import Any, Final, TypeAlias, overload +from typing_extensions import deprecated + +from affine import Affine as Affine +from numpy.typing import ArrayLike, NDArray +from rasterio._typing import CRSInput, Geometry, _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +_Resolution: TypeAlias = tuple[float, float] | float +_Gcps: TypeAlias = Sequence[GroundControlPoint] +_Rpcs: TypeAlias = RPC | Mapping[str, Any] + +SUPPORTED_RESAMPLING: Final[list[Resampling]] + +def transform( + src_crs: CRSInput, dst_crs: CRSInput, xs: ArrayLike, ys: ArrayLike, zs: ArrayLike | None = None +) -> tuple[list[float], list[float]] | tuple[list[float], list[float], list[float]]: ... + +@overload +def transform_geom( + src_crs: CRSInput, dst_crs: CRSInput, geom: Geometry | Sequence[Geometry], *, precision: float = -1 +) -> dict[str, Any] | list[dict[str, Any]]: ... +@overload +@deprecated( + "`antimeridian_cutting` and `antimeridian_offset` are no-ops since GDAL 2.2 " + "and will be removed in a future rasterio release. Call transform_geom " + "without them." +) +def transform_geom( + src_crs: CRSInput, + dst_crs: CRSInput, + geom: Geometry | Sequence[Geometry], + antimeridian_cutting: bool | None = None, + antimeridian_offset: float | None = None, + precision: float = -1, +) -> dict[str, Any] | list[dict[str, Any]]: ... + +def transform_bounds( + src_crs: CRSInput, dst_crs: CRSInput, left: float, bottom: float, right: float, top: float, densify_pts: int = 21 +) -> tuple[float, float, float, float]: ... +def reproject( + source: ArrayLike | Incomplete, + destination: ArrayLike | Incomplete | None = None, + src_transform: Affine | None = None, + gcps: _Gcps | None = None, + rpcs: _Rpcs | None = None, + src_crs: CRSInput | None = None, + src_nodata: float | None = None, + dst_transform: Affine | None = None, + dst_crs: CRSInput | None = None, + dst_nodata: float | None = None, + dst_resolution: _Resolution | None = None, + src_alpha: int = 0, + dst_alpha: int = 0, + masked: bool = False, + resampling: Resampling = ..., + num_threads: int = 1, + init_dest_nodata: bool = True, + tolerance: float = 0.125, + warp_mem_limit: int = 0, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[NDArray[Any], Affine]: ... +def aligned_target(transform: Affine, width: int, height: int, resolution: _Resolution) -> tuple[Affine, int, int]: ... +def calculate_default_transform( + src_crs: CRSInput, + dst_crs: CRSInput, + width: int, + height: int, + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + gcps: _Gcps | None = None, + rpcs: _Rpcs | None = None, + resolution: _Resolution | None = None, + dst_width: int | None = None, + dst_height: int | None = None, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[Affine, int, int]: ... diff --git a/stubs/rasterio/rasterio/windows.pyi b/stubs/rasterio/rasterio/windows.pyi new file mode 100644 index 000000000000..c5c80b9861f9 --- /dev/null +++ b/stubs/rasterio/rasterio/windows.pyi @@ -0,0 +1,80 @@ +from collections.abc import Callable, Sequence +from typing import Any, TypeAlias, overload +from typing_extensions import Self, deprecated + +from affine import Affine as Affine +from numpy.typing import NDArray +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning, WindowError as WindowError + +_Bounds: TypeAlias = tuple[float, float, float, float] +_Ranges: TypeAlias = tuple[tuple[int, int], tuple[int, int]] +_Slices: TypeAlias = tuple[slice, slice] + +class WindowMethodsMixin: + @overload + def window(self, left: float, bottom: float, right: float, top: float) -> Window: ... + @overload + @deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") + def window(self, left: float, bottom: float, right: float, top: float, precision: int | None = None) -> Window: ... + + def window_transform(self, window: Window) -> Affine: ... + def window_bounds(self, window: Window) -> _Bounds: ... + +def iter_args(function: Callable[..., Any]) -> Callable[..., Any]: ... +def toranges(window: Window | _Ranges) -> _Ranges: ... +def get_data_window(arr: NDArray[Any], nodata: float | None = None) -> Window: ... +def union(*windows: Window) -> Window: ... +def intersection(*windows: Window) -> Window: ... +def intersect(*windows: Window) -> bool: ... + +@overload +def from_bounds(left: float, bottom: float, right: float, top: float, transform: Affine | None = None) -> Window: ... +@overload +@deprecated( + "`height`, `width`, and `precision` on windows.from_bounds are unused since rasterio 1.3 and will be removed in 2.0.0." +) +def from_bounds( + left: float, + bottom: float, + right: float, + top: float, + transform: Affine | None = None, + height: int | None = None, + width: int | None = None, + precision: int | None = None, +) -> Window: ... + +def transform(window: Window, transform: Affine) -> Affine: ... +def bounds(window: Window, transform: Affine, height: int = 0, width: int = 0) -> _Bounds: ... +def crop(window: Window, height: int, width: int) -> Window: ... +def evaluate(window: Window, height: int, width: int, boundless: bool = False) -> Window: ... +def shape(window: Window, height: int = -1, width: int = -1) -> tuple[int, int]: ... +def window_index(window: Window, height: int = 0, width: int = 0) -> _Slices: ... +def round_window_to_full_blocks( + window: Window, block_shapes: Sequence[tuple[int, int]], height: int = 0, width: int = 0 +) -> Window: ... +def validate_length_value(instance: object, attribute: object, value: float) -> None: ... +def subdivide(window: Window, height: int, width: int) -> list[Window]: ... + +class Window: + col_off: float + row_off: float + width: float + height: float + def __init__(self, col_off: float, row_off: float, width: float, height: float) -> None: ... + def flatten(self) -> tuple[float, float, float, float]: ... + def todict(self) -> dict[str, float]: ... + def toranges(self) -> _Ranges: ... + def toslices(self) -> _Slices: ... + @classmethod + def from_slices( + cls, rows: slice | Sequence[int], cols: slice | Sequence[int], height: int = -1, width: int = -1, boundless: bool = False + ) -> Self: ... + # `**kwds` accepts the deprecated kwargs `op` (callable) and `pixel_precision` (int) emitted by rasterio < 1.3. + def round_lengths(self, **kwds: Any) -> Window: ... + @deprecated("Window.round_shape is deprecated and will be removed in Rasterio 2.0.0; use round_lengths instead.") + def round_shape(self, **kwds: Any) -> Window: ... + def round_offsets(self, **kwds: Any) -> Window: ... + def round(self, ndigits: int | None = None) -> Window: ... + def crop(self, height: int, width: int) -> Window: ... + def intersection(self, other: Window) -> Window: ... diff --git a/stubs/ratelimit/@tests/stubtest_allowlist.txt b/stubs/ratelimit/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5b0935ce9175 --- /dev/null +++ b/stubs/ratelimit/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# This file lacks __all__ and "now" is only used to set the default value of +# RateLimitDecorator.__init__()'s clock parameter +ratelimit.decorators.now diff --git a/stubs/ratelimit/METADATA.toml b/stubs/ratelimit/METADATA.toml new file mode 100644 index 000000000000..dbdb547943c9 --- /dev/null +++ b/stubs/ratelimit/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.2.*" +upstream-repository = "https://github.com/tomasbasham/ratelimit" diff --git a/stubs/ratelimit/ratelimit/__init__.pyi b/stubs/ratelimit/ratelimit/__init__.pyi new file mode 100644 index 000000000000..374329aaa37e --- /dev/null +++ b/stubs/ratelimit/ratelimit/__init__.pyi @@ -0,0 +1,7 @@ +from ratelimit.decorators import RateLimitDecorator, sleep_and_retry +from ratelimit.exception import RateLimitException + +limits = RateLimitDecorator +rate_limited = RateLimitDecorator + +__all__ = ["RateLimitException", "limits", "rate_limited", "sleep_and_retry"] diff --git a/stubs/ratelimit/ratelimit/decorators.pyi b/stubs/ratelimit/ratelimit/decorators.pyi new file mode 100644 index 000000000000..a31adc2fa819 --- /dev/null +++ b/stubs/ratelimit/ratelimit/decorators.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +class RateLimitDecorator: + def __init__( + self, calls: int = 15, period: float = 900, clock: Callable[[], float] = ..., raise_on_limit: bool = True + ) -> None: ... + def __call__(self, func: Callable[_P, _T]) -> Callable[_P, _T]: ... + +def sleep_and_retry(func: Callable[_P, _T]) -> Callable[_P, _T]: ... diff --git a/stubs/ratelimit/ratelimit/exception.pyi b/stubs/ratelimit/ratelimit/exception.pyi new file mode 100644 index 000000000000..2271781458b0 --- /dev/null +++ b/stubs/ratelimit/ratelimit/exception.pyi @@ -0,0 +1,3 @@ +class RateLimitException(Exception): + period_remaining: float + def __init__(self, message: str, period_remaining: float) -> None: ... diff --git a/stubs/redis/@tests/stubtest_allowlist.txt b/stubs/redis/@tests/stubtest_allowlist.txt deleted file mode 100644 index 14e9a205922b..000000000000 --- a/stubs/redis/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1 +0,0 @@ -redis.client.Pipeline.transaction # instance attribute has same name as superclass method diff --git a/stubs/redis/METADATA.toml b/stubs/redis/METADATA.toml deleted file mode 100644 index 0ca63cc11f20..000000000000 --- a/stubs/redis/METADATA.toml +++ /dev/null @@ -1,2 +0,0 @@ -version = "4.0.*" -requires = [] diff --git a/stubs/redis/redis/__init__.pyi b/stubs/redis/redis/__init__.pyi deleted file mode 100644 index 6d3cdcc9a956..000000000000 --- a/stubs/redis/redis/__init__.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from . import client, connection, exceptions, sentinel, utils - -Redis = client.Redis - -BlockingConnectionPool = connection.BlockingConnectionPool -Connection = connection.Connection -ConnectionPool = connection.ConnectionPool -SSLConnection = connection.SSLConnection -StrictRedis = client.StrictRedis -UnixDomainSocketConnection = connection.UnixDomainSocketConnection - -from_url = utils.from_url - -Sentinel = sentinel.Sentinel -SentinelConnectionPool = sentinel.SentinelConnectionPool -SentinelManagedConnection = sentinel.SentinelManagedConnection -SentinelManagedSSLConnection = sentinel.SentinelManagedSSLConnection - -AuthenticationError = exceptions.AuthenticationError -AuthenticationWrongNumberOfArgsError = exceptions.AuthenticationWrongNumberOfArgsError -BusyLoadingError = exceptions.BusyLoadingError -ChildDeadlockedError = exceptions.ChildDeadlockedError -ConnectionError = exceptions.ConnectionError -DataError = exceptions.DataError -InvalidResponse = exceptions.InvalidResponse -PubSubError = exceptions.PubSubError -ReadOnlyError = exceptions.ReadOnlyError -RedisError = exceptions.RedisError -ResponseError = exceptions.ResponseError -TimeoutError = exceptions.TimeoutError -WatchError = exceptions.WatchError diff --git a/stubs/redis/redis/client.pyi b/stubs/redis/redis/client.pyi deleted file mode 100644 index 05cdaaec3a03..000000000000 --- a/stubs/redis/redis/client.pyi +++ /dev/null @@ -1,861 +0,0 @@ -import builtins -import threading -from _typeshed import Self, SupportsItems -from datetime import datetime, timedelta -from typing import ( - Any, - Callable, - ClassVar, - Dict, - Generic, - Iterable, - Iterator, - Mapping, - Pattern, - Sequence, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal - -from .commands import CoreCommands, RedisModuleCommands, SentinelCommands -from .connection import ConnectionPool -from .lock import Lock -from .retry import Retry - -_ScoreCastFuncReturn = TypeVar("_ScoreCastFuncReturn") - -_Value = Union[bytes, float, int, str] -_Key = Union[str, bytes] - -# Lib returns str or bytes depending on value of decode_responses -_StrType = TypeVar("_StrType", bound=Union[str, bytes]) - -_VT = TypeVar("_VT") -_T = TypeVar("_T") - -class CaseInsensitiveDict(Dict[_StrType, _VT]): - def __init__(self, data: SupportsItems[_StrType, _VT]) -> None: ... - def update(self, data: SupportsItems[_StrType, _VT]) -> None: ... # type: ignore[override] - @overload - def get(self, k: _StrType, default: None = ...) -> _VT | None: ... - @overload - def get(self, k: _StrType, default: _VT | _T) -> _VT | _T: ... - # Overrides many other methods too, but without changing signature - -SYM_EMPTY: Any -SENTINEL_STATE_TYPES: Any - -def list_or_args(keys, args): ... -def timestamp_to_datetime(response): ... -def string_keys_to_dict(key_string, callback): ... -def parse_debug_object(response): ... -def parse_object(response, infotype): ... -def parse_info(response): ... -def parse_sentinel_state(item): ... -def parse_sentinel_master(response): ... -def parse_sentinel_masters(response): ... -def parse_sentinel_slaves_and_sentinels(response): ... -def parse_sentinel_get_master(response): ... -def pairs_to_dict(response, decode_keys: bool = ..., decode_string_values: bool = ...): ... -def pairs_to_dict_typed(response, type_info): ... -def zset_score_pairs(response, **options): ... -def sort_return_tuples(response, **options): ... -def int_or_none(response): ... -def float_or_none(response): ... -def bool_ok(response): ... -def parse_client_list(response, **options): ... -def parse_config_get(response, **options): ... -def parse_scan(response, **options): ... -def parse_hscan(response, **options): ... -def parse_zscan(response, **options): ... -def parse_slowlog_get(response, **options): ... - -_LockType = TypeVar("_LockType") - -class Redis(RedisModuleCommands, CoreCommands[_StrType], SentinelCommands, Generic[_StrType]): - RESPONSE_CALLBACKS: Any - @overload - @classmethod - def from_url( - cls, - url: str, - *, - host: str | None = ..., - port: int | None = ..., - db: int | None = ..., - password: str | None = ..., - socket_timeout: float | None = ..., - socket_connect_timeout: float | None = ..., - socket_keepalive: bool | None = ..., - socket_keepalive_options: Mapping[str, int | str] | None = ..., - connection_pool: ConnectionPool | None = ..., - unix_socket_path: str | None = ..., - encoding: str = ..., - encoding_errors: str = ..., - charset: str | None = ..., - errors: str | None = ..., - decode_responses: Literal[True], - retry_on_timeout: bool = ..., - ssl: bool = ..., - ssl_keyfile: str | None = ..., - ssl_certfile: str | None = ..., - ssl_cert_reqs: str | int | None = ..., - ssl_ca_certs: str | None = ..., - ssl_check_hostname: bool = ..., - max_connections: int | None = ..., - single_connection_client: bool = ..., - health_check_interval: float = ..., - client_name: str | None = ..., - username: str | None = ..., - ) -> Redis[str]: ... - @overload - @classmethod - def from_url( - cls, - url: str, - *, - host: str | None = ..., - port: int | None = ..., - db: int | None = ..., - password: str | None = ..., - socket_timeout: float | None = ..., - socket_connect_timeout: float | None = ..., - socket_keepalive: bool | None = ..., - socket_keepalive_options: Mapping[str, int | str] | None = ..., - connection_pool: ConnectionPool | None = ..., - unix_socket_path: str | None = ..., - encoding: str = ..., - encoding_errors: str = ..., - charset: str | None = ..., - errors: str | None = ..., - decode_responses: Literal[False] = ..., - retry_on_timeout: bool = ..., - ssl: bool = ..., - ssl_keyfile: str | None = ..., - ssl_certfile: str | None = ..., - ssl_cert_reqs: str | int | None = ..., - ssl_ca_certs: str | None = ..., - ssl_check_hostname: bool = ..., - max_connections: int | None = ..., - single_connection_client: bool = ..., - health_check_interval: float = ..., - client_name: str | None = ..., - username: str | None = ..., - ) -> Redis[bytes]: ... - connection_pool: Any - response_callbacks: Any - @overload - def __init__( - self: Redis[str], - host: str, - port: int, - db: int, - password: str | None, - socket_timeout: float | None, - socket_connect_timeout: float | None, - socket_keepalive: bool | None, - socket_keepalive_options: Mapping[str, int | str] | None, - connection_pool: ConnectionPool | None, - unix_socket_path: str | None, - encoding: str, - encoding_errors: str, - charset: str | None, - errors: str | None, - decode_responses: Literal[True], - retry_on_timeout: bool = ..., - ssl: bool = ..., - ssl_keyfile: str | None = ..., - ssl_certfile: str | None = ..., - ssl_cert_reqs: str | int | None = ..., - ssl_ca_certs: str | None = ..., - ssl_check_hostname: bool = ..., - max_connections: int | None = ..., - single_connection_client: bool = ..., - health_check_interval: float = ..., - client_name: str | None = ..., - username: str | None = ..., - retry: Retry | None = ..., - ) -> None: ... - @overload - def __init__( - self: Redis[str], - host: str = ..., - port: int = ..., - db: int = ..., - password: str | None = ..., - socket_timeout: float | None = ..., - socket_connect_timeout: float | None = ..., - socket_keepalive: bool | None = ..., - socket_keepalive_options: Mapping[str, int | str] | None = ..., - connection_pool: ConnectionPool | None = ..., - unix_socket_path: str | None = ..., - encoding: str = ..., - encoding_errors: str = ..., - charset: str | None = ..., - errors: str | None = ..., - *, - decode_responses: Literal[True], - retry_on_timeout: bool = ..., - ssl: bool = ..., - ssl_keyfile: str | None = ..., - ssl_certfile: str | None = ..., - ssl_cert_reqs: str | int | None = ..., - ssl_ca_certs: str | None = ..., - ssl_check_hostname: bool = ..., - max_connections: int | None = ..., - single_connection_client: bool = ..., - health_check_interval: float = ..., - client_name: str | None = ..., - username: str | None = ..., - retry: Retry | None = ..., - ) -> None: ... - @overload - def __init__( - self: Redis[bytes], - host: str = ..., - port: int = ..., - db: int = ..., - password: str | None = ..., - socket_timeout: float | None = ..., - socket_connect_timeout: float | None = ..., - socket_keepalive: bool | None = ..., - socket_keepalive_options: Mapping[str, int | str] | None = ..., - connection_pool: ConnectionPool | None = ..., - unix_socket_path: str | None = ..., - encoding: str = ..., - encoding_errors: str = ..., - charset: str | None = ..., - errors: str | None = ..., - decode_responses: Literal[False] = ..., - retry_on_timeout: bool = ..., - ssl: bool = ..., - ssl_keyfile: str | None = ..., - ssl_certfile: str | None = ..., - ssl_cert_reqs: str | int | None = ..., - ssl_ca_certs: str | None = ..., - ssl_check_hostname: bool = ..., - max_connections: int | None = ..., - single_connection_client: bool = ..., - health_check_interval: float = ..., - client_name: str | None = ..., - username: str | None = ..., - retry: Retry | None = ..., - ) -> None: ... - def set_response_callback(self, command, callback): ... - def pipeline(self, transaction: bool = ..., shard_hint: Any = ...) -> Pipeline[_StrType]: ... - def transaction(self, func, *watches, **kwargs): ... - @overload - def lock( - self, - name: _Key, - timeout: float | None = ..., - sleep: float = ..., - blocking_timeout: float | None = ..., - lock_class: None = ..., - thread_local: bool = ..., - ) -> Lock: ... - @overload - def lock( - self, - name: _Key, - timeout: float | None, - sleep: float, - blocking_timeout: float | None, - lock_class: Type[_LockType], - thread_local: bool = ..., - ) -> _LockType: ... - @overload - def lock( - self, - name: _Key, - timeout: float | None = ..., - sleep: float = ..., - blocking_timeout: float | None = ..., - *, - lock_class: Type[_LockType], - thread_local: bool = ..., - ) -> _LockType: ... - def pubsub(self, *, shard_hint: Any = ..., ignore_subscribe_messages: bool = ...) -> PubSub: ... - def execute_command(self, *args, **options): ... - def parse_response(self, connection, command_name, **options): ... - # TODO: Most of the following methods must be moved to the command classes. - def readwrite(self) -> bool: ... - def readonly(self) -> bool: ... - def config_get(self, pattern=...): ... - def config_set(self, name, value): ... - def config_resetstat(self): ... - def config_rewrite(self): ... - def dbsize(self) -> int: ... - def debug_object(self, key): ... - def echo(self, value: _Value) -> bytes: ... - def info(self, section: _Key | None = ...) -> Mapping[str, Any]: ... - def lastsave(self): ... - def object(self, infotype, key): ... - def ping(self) -> bool: ... - def save(self) -> bool: ... - def shutdown(self, save: bool = ..., nosave: bool = ...) -> None: ... - def slaveof(self, host=..., port=...): ... - def slowlog_get(self, num=...): ... - def slowlog_len(self): ... - def slowlog_reset(self): ... - def time(self): ... - def decr(self, name, amount=...) -> int: ... - def decrby(self, name, amount=...) -> int: ... - def delete(self, *names: _Key) -> int: ... - def __delitem__(self, _Key): ... - def dump(self, name): ... - def exists(self, *names: _Key) -> int: ... - __contains__: Any - def expire(self, name: _Key, time: int | timedelta) -> bool: ... - def expireat(self, name, when): ... - def get(self, name: _Key) -> _StrType | None: ... - def __getitem__(self, name): ... - def getbit(self, name: _Key, offset: int) -> int: ... - def getrange(self, key, start, end): ... - def getset(self, name, value) -> _StrType | None: ... - def incr(self, name: _Key, amount: int = ...) -> int: ... - def incrby(self, name: _Key, amount: int = ...) -> int: ... - def incrbyfloat(self, name: _Key, amount: float = ...) -> float: ... - def keys(self, pattern: _Key = ...) -> list[_StrType]: ... - def mget(self, keys: _Key | Iterable[_Key], *args: _Key) -> list[_StrType | None]: ... - def mset(self, mapping: Mapping[_Key, _Value]) -> Literal[True]: ... - def msetnx(self, mapping: Mapping[_Key, _Value]) -> bool: ... - def move(self, name: _Key, db: int) -> bool: ... - def persist(self, name: _Key) -> bool: ... - def pexpire(self, name: _Key, time: int | timedelta) -> Literal[1, 0]: ... - def pexpireat(self, name: _Key, when: int | datetime) -> Literal[1, 0]: ... - def psetex(self, name, time_ms, value): ... - def pttl(self, name): ... - def __setitem__(self, name, value): ... - def setbit(self, name: _Key, offset: int, value: int) -> int: ... - def setex(self, name: _Key, time: int | timedelta, value: _Value) -> bool: ... - def setnx(self, name: _Key, value: _Value) -> bool: ... - def setrange(self, name, offset, value): ... - def strlen(self, name): ... - def substr(self, name, start, end=...): ... - def ttl(self, name: _Key) -> int: ... - def type(self, name): ... - def watch(self, *names): ... - def unlink(self, *names: _Key) -> int: ... - def unwatch(self): ... - @overload - def blpop(self, keys: _Value | Iterable[_Value], timeout: Literal[0] = ...) -> tuple[_StrType, _StrType]: ... - @overload - def blpop(self, keys: _Value | Iterable[_Value], timeout: float) -> tuple[_StrType, _StrType] | None: ... - @overload - def brpop(self, keys: _Value | Iterable[_Value], timeout: Literal[0] = ...) -> tuple[_StrType, _StrType]: ... - @overload - def brpop(self, keys: _Value | Iterable[_Value], timeout: float) -> tuple[_StrType, _StrType] | None: ... - def brpoplpush(self, src, dst, timeout=...): ... - @overload - def sort( - self, - name: _Key, - start: int | None = ..., - num: int | None = ..., - by: _Key | None = ..., - get: _Key | Sequence[_Key] | None = ..., - desc: bool = ..., - alpha: bool = ..., - store: None = ..., - groups: bool = ..., - ) -> list[_StrType]: ... - @overload - def sort( - self, - name: _Key, - start: int | None = ..., - num: int | None = ..., - by: _Key | None = ..., - get: _Key | Sequence[_Key] | None = ..., - desc: bool = ..., - alpha: bool = ..., - *, - store: _Key, - groups: bool = ..., - ) -> int: ... - @overload - def sort( - self, - name: _Key, - start: int | None, - num: int | None, - by: _Key | None, - get: _Key | Sequence[_Key] | None, - desc: bool, - alpha: bool, - store: _Key, - groups: bool = ..., - ) -> int: ... - def scan( - self, cursor: int = ..., match: _Key | None = ..., count: int | None = ..., _type: str | None = ... - ) -> tuple[int, list[_StrType]]: ... - def scan_iter(self, match: str | None = ..., count: int | None = ..., _type: str | None = ...) -> Iterator[_StrType]: ... - def sscan( - self, name: _Key, cursor: int = ..., match: str | None = ..., count: int | None = ... - ) -> tuple[int, list[_StrType]]: ... - def sscan_iter(self, name: _Key, match: str | None = ..., count: int | None = ...): ... - def hscan( - self, name: _Key, cursor: int = ..., match: str | None = ..., count: int | None = ... - ) -> tuple[int, dict[_StrType, _StrType]]: ... - def hscan_iter(self, name: _Key, match: str | None = ..., count: int | None = ...): ... - def zscan(self, name, cursor=..., match=..., count=..., score_cast_func=...): ... - def zscan_iter(self, name, match=..., count=..., score_cast_func=...): ... - def sadd(self, name: _Key, *values: _Value) -> int: ... - def scard(self, name: _Key) -> int: ... - def sdiff(self, keys: _Key | Iterable[_Key], *args: _Key) -> builtins.set[_Value]: ... - def sdiffstore(self, dest: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> int: ... - def sinter(self, keys: _Key | Iterable[_Key], *args: _Key) -> builtins.set[_Value]: ... - def sinterstore(self, dest: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> int: ... - def sismember(self, name: _Key, value: _Value) -> bool: ... - def smembers(self, name: _Key) -> builtins.set[_StrType]: ... - def smove(self, src: _Key, dst: _Key, value: _Value) -> bool: ... - @overload - def spop(self, name: _Key, count: None = ...) -> _Value | None: ... - @overload - def spop(self, name: _Key, count: int) -> list[_Value]: ... - @overload - def srandmember(self, name: _Key, number: None = ...) -> _Value | None: ... - @overload - def srandmember(self, name: _Key, number: int) -> list[_Value]: ... - def srem(self, name: _Key, *values: _Value) -> int: ... - def sunion(self, keys: _Key | Iterable[_Key], *args: _Key) -> builtins.set[_Value]: ... - def sunionstore(self, dest: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> int: ... - def pfadd(self, name: _Key, *values: _Value) -> int: ... - def pfcount(self, name: _Key) -> int: ... - def pfmerge(self, dest: _Key, *sources: _Key) -> bool: ... - def hdel(self, name: _Key, *keys: _Key) -> int: ... - def hexists(self, name: _Key, key: _Key) -> bool: ... - def hget(self, name: _Key, key: _Key) -> _StrType | None: ... - def hgetall(self, name: _Key) -> dict[_StrType, _StrType]: ... - def hincrby(self, name: _Key, key: _Key, amount: int = ...) -> int: ... - def hincrbyfloat(self, name: _Key, key: _Key, amount: float = ...) -> float: ... - def hkeys(self, name: _Key) -> list[_StrType]: ... - def hlen(self, name: _Key) -> int: ... - @overload - def hset(self, name: _Key, key: _Key, value: _Value, mapping: Mapping[_Key, _Value] | None = ...) -> int: ... - @overload - def hset(self, name: _Key, key: None, value: None, mapping: Mapping[_Key, _Value]) -> int: ... - @overload - def hset(self, name: _Key, *, mapping: Mapping[_Key, _Value]) -> int: ... - def hsetnx(self, name: _Key, key: _Key, value: _Value) -> int: ... - def hmset(self, name: _Key, mapping: Mapping[_Key, _Value]) -> bool: ... - def hmget(self, name: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> list[_StrType | None]: ... - def hvals(self, name: _Key) -> list[_StrType]: ... - def publish(self, channel: _Key, message: _Key) -> int: ... - def eval(self, script, numkeys, *keys_and_args): ... - def evalsha(self, sha, numkeys, *keys_and_args): ... - def pubsub_channels(self, pattern: _Key = ...) -> list[str]: ... - def pubsub_numsub(self, *args: _Key) -> list[tuple[str, int]]: ... - def pubsub_numpat(self) -> int: ... - def monitor(self) -> Monitor: ... - def memory_stats(self) -> dict[str, Any]: ... - def memory_purge(self) -> bool: ... - def cluster(self, cluster_arg: str, *args: Any) -> Any: ... - def __enter__(self) -> Redis[_StrType]: ... - def __exit__(self, exc_type, exc_value, traceback): ... - def __del__(self) -> None: ... - def close(self) -> None: ... - def client(self) -> Redis[_StrType]: ... - -StrictRedis = Redis - -class PubSub: - PUBLISH_MESSAGE_TYPES: ClassVar[tuple[str, str]] - UNSUBSCRIBE_MESSAGE_TYPES: ClassVar[tuple[str, str]] - HEALTH_CHECK_MESSAGE: ClassVar[str] - connection_pool: Any - shard_hint: Any - ignore_subscribe_messages: Any - connection: Any - encoder: Any - health_check_response: Any - def __init__(self, connection_pool, shard_hint=..., ignore_subscribe_messages: bool = ...) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> None: ... - def __del__(self): ... - channels: Any - patterns: Any - def reset(self): ... - def close(self) -> None: ... - def on_connect(self, connection): ... - @property - def subscribed(self): ... - def execute_command(self, *args): ... - def parse_response(self, block: bool = ..., timeout: float = ...): ... - def psubscribe(self, *args: _Key, **kwargs: Callable[[Any], None]): ... - def punsubscribe(self, *args: _Key) -> None: ... - def subscribe(self, *args: _Key, **kwargs: Callable[[Any], None]) -> None: ... - def unsubscribe(self, *args: _Key) -> None: ... - def listen(self): ... - def get_message(self, ignore_subscribe_messages: bool = ..., timeout: float = ...) -> dict[str, Any] | None: ... - def handle_message(self, response, ignore_subscribe_messages: bool = ...) -> dict[str, Any] | None: ... - def run_in_thread(self, sleep_time: float = ..., daemon: bool = ..., exception_handler: Any | None = ...): ... - def ping(self, message: _Value | None = ...) -> None: ... - -class PubSubWorkerThread(threading.Thread): - daemon: Any - pubsub: Any - sleep_time: Any - exception_handler: Any - def __init__(self, pubsub, sleep_time, daemon: bool = ..., exception_handler: Any | None = ...) -> None: ... - def run(self) -> None: ... - def stop(self) -> None: ... - -class Pipeline(Redis[_StrType], Generic[_StrType]): - UNWATCH_COMMANDS: Any - connection_pool: Any - connection: Any - response_callbacks: Any - transaction: bool - shard_hint: Any - watching: bool - - command_stack: Any - scripts: Any - explicit_transaction: Any - def __init__(self, connection_pool, response_callbacks, transaction, shard_hint) -> None: ... - def __enter__(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def __exit__(self, exc_type, exc_value, traceback) -> None: ... - def __del__(self) -> None: ... - def __len__(self) -> int: ... - def __bool__(self) -> bool: ... - def discard(self) -> None: ... - def reset(self) -> None: ... - def multi(self) -> None: ... - def execute_command(self, *args, **options): ... - def immediate_execute_command(self, *args, **options): ... - def pipeline_execute_command(self, *args, **options): ... - def raise_first_error(self, commands, response): ... - def annotate_exception(self, exception, number, command): ... - def parse_response(self, connection, command_name, **options): ... - def load_scripts(self): ... - def execute(self, raise_on_error: bool = ...) -> list[Any]: ... - def watch(self, *names: _Key) -> bool: ... - def unwatch(self) -> bool: ... - # in the Redis implementation, the following methods are inherited from client. - def set_response_callback(self, command, callback): ... - def pipeline(self, transaction: bool = ..., shard_hint: Any = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def lock(self, name, timeout=..., sleep=..., blocking_timeout=..., lock_class=..., thread_local=...): ... - def acl_cat(self, category: str | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_deluser(self, username: str) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_genpass(self, bits: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_getuser(self, username: str) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_list(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_load(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_setuser( # type: ignore[override] - self, - username: str, - enabled: bool = ..., - nopass: bool = ..., - passwords: Sequence[str] | None = ..., - hashed_passwords: Sequence[str] | None = ..., - categories: Sequence[str] | None = ..., - commands: Sequence[str] | None = ..., - keys: Sequence[str] | None = ..., - reset: bool = ..., - reset_keys: bool = ..., - reset_passwords: bool = ..., - ) -> Pipeline[_StrType]: ... - def acl_users(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def acl_whoami(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def bgrewriteaof(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def bgsave(self, schedule: bool = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def client_id(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def client_kill(self, address: str) -> Pipeline[_StrType]: ... # type: ignore[override] - def client_list(self, _type: str | None = ..., client_id: list[str] = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def client_getname(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def client_setname(self, name: str) -> Pipeline[_StrType]: ... # type: ignore[override] - def readwrite(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def readonly(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def config_get(self, pattern=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def config_set(self, name, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def config_resetstat(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def config_rewrite(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def dbsize(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def debug_object(self, key) -> Pipeline[_StrType]: ... # type: ignore[override] - def echo(self, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def flushall(self, asynchronous: bool = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def flushdb(self, asynchronous: bool = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def info(self, section: _Key | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def lastsave(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def object(self, infotype, key) -> Pipeline[_StrType]: ... # type: ignore[override] - def ping(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def save(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_get_master_addr_by_name(self, service_name) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_master(self, service_name) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_masters(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_monitor(self, name, ip, port, quorum) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_remove(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_sentinels(self, service_name) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_set(self, name, option, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def sentinel_slaves(self, service_name) -> Pipeline[_StrType]: ... # type: ignore[override] - def slaveof(self, host=..., port=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def slowlog_get(self, num=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def slowlog_len(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def slowlog_reset(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def time(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def append(self, key, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def bitcount(self, key: _Key, start: int | None = ..., end: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def bitop(self, operation, dest, *keys) -> Pipeline[_StrType]: ... # type: ignore[override] - def bitpos(self, key, bit, start=..., end=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def decr(self, name, amount=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def delete(self, *names: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def __delitem__(self, _Key) -> None: ... - def dump(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def exists(self, *names: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def __contains__(self, *names: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def expire(self, name: _Key, time: int | timedelta) -> Pipeline[_StrType]: ... # type: ignore[override] - def expireat(self, name, when) -> Pipeline[_StrType]: ... # type: ignore[override] - def get(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def __getitem__(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def getbit(self, name: _Key, offset: int) -> Pipeline[_StrType]: ... # type: ignore[override] - def getrange(self, key, start, end) -> Pipeline[_StrType]: ... # type: ignore[override] - def getset(self, name, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def incr(self, name, amount=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def incrby(self, name, amount=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def incrbyfloat(self, name, amount=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def keys(self, pattern: _Key = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def mget(self, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def mset(self, mapping: Mapping[_Key, _Value]) -> Pipeline[_StrType]: ... # type: ignore[override] - def msetnx(self, mapping: Mapping[_Key, _Value]) -> Pipeline[_StrType]: ... # type: ignore[override] - def move(self, name: _Key, db: int) -> Pipeline[_StrType]: ... # type: ignore[override] - def persist(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def pexpire(self, name: _Key, time: int | timedelta) -> Pipeline[_StrType]: ... # type: ignore[override] - def pexpireat(self, name: _Key, when: int | datetime) -> Pipeline[_StrType]: ... # type: ignore[override] - def psetex(self, name, time_ms, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def pttl(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def randomkey(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def rename(self, src, dst) -> Pipeline[_StrType]: ... # type: ignore[override] - def renamenx(self, src, dst) -> Pipeline[_StrType]: ... # type: ignore[override] - def restore(self, name, ttl, value, replace: bool = ..., absttl: bool = ..., idletime: Any | None = ..., frequency: Any | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def set( # type: ignore[override] - self, - name: _Key, - value: _Value, - ex: None | int | timedelta = ..., - px: None | int | timedelta = ..., - nx: bool = ..., - xx: bool = ..., - keepttl: bool = ..., - get: bool = ..., - exat: Any | None = ..., - pxat: Any | None = ..., - ) -> Pipeline[_StrType]: ... - def __setitem__(self, name, value) -> None: ... - def setbit(self, name: _Key, offset: int, value: int) -> Pipeline[_StrType]: ... # type: ignore[override] - def setex(self, name: _Key, time: int | timedelta, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def setnx(self, name, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def setrange(self, name, offset, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def strlen(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def substr(self, name, start, end=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def ttl(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def type(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def unlink(self, *names: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def blmove( # type: ignore[override] - self, - first_list: _Key, - second_list: _Key, - timeout: float, - src: Literal["LEFT", "RIGHT"] = ..., - dest: Literal["LEFT", "RIGHT"] = ..., - ) -> Pipeline[_StrType]: ... - def blpop(self, keys: _Value | Iterable[_Value], timeout: float = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def brpop(self, keys: _Value | Iterable[_Value], timeout: float = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def brpoplpush(self, src, dst, timeout=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def lindex(self, name: _Key, index: int) -> Pipeline[_StrType]: ... # type: ignore[override] - def linsert( # type: ignore[override] - self, name: _Key, where: Literal["BEFORE", "AFTER", "before", "after"], refvalue: _Value, value: _Value - ) -> Pipeline[_StrType]: ... - def llen(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def lmove( # type: ignore[override] - self, first_list: _Key, second_list: _Key, src: Literal["LEFT", "RIGHT"] = ..., dest: Literal["LEFT", "RIGHT"] = ... - ) -> Pipeline[_StrType]: ... - def lpop(self, name, count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def lpush(self, name: _Value, *values: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def lpushx(self, name, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def lrange(self, name: _Key, start: int, end: int) -> Pipeline[_StrType]: ... # type: ignore[override] - def lrem(self, name: _Key, count: int, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def lset(self, name: _Key, index: int, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def ltrim(self, name: _Key, start: int, end: int) -> Pipeline[_StrType]: ... # type: ignore[override] - def rpop(self, name, count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def rpoplpush(self, src, dst) -> Pipeline[_StrType]: ... # type: ignore[override] - def rpush(self, name: _Value, *values: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def rpushx(self, name, value) -> Pipeline[_StrType]: ... # type: ignore[override] - def sort( # type: ignore[override] - self, - name: _Key, - start: int | None = ..., - num: int | None = ..., - by: _Key | None = ..., - get: _Key | Sequence[_Key] | None = ..., - desc: bool = ..., - alpha: bool = ..., - store: _Key | None = ..., - groups: bool = ..., - ) -> Pipeline[_StrType]: ... - def scan(self, cursor: int = ..., match: _Key | None = ..., count: int | None = ..., _type: str | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def scan_iter(self, match: str | None = ..., count: int | None = ..., _type: str | None = ...) -> Iterator[Any]: ... - def sscan(self, name: _Key, cursor: int = ..., match: str | None = ..., count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def sscan_iter(self, name: _Key, match: str | None = ..., count: int | None = ...) -> Iterator[Any]: ... - def hscan(self, name: _Key, cursor: int = ..., match: str | None = ..., count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def hscan_iter(self, name, match=..., count=...) -> Iterator[Any]: ... - def zscan(self, name, cursor=..., match=..., count=..., score_cast_func=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def zscan_iter(self, name, match=..., count=..., score_cast_func=...) -> Iterator[Any]: ... - def sadd(self, name: _Key, *values: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def scard(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def sdiff(self, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def sdiffstore(self, dest: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def sinter(self, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def sinterstore(self, dest: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def sismember(self, name: _Key, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def smembers(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def smove(self, src: _Key, dst: _Key, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def spop(self, name: _Key, count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def srandmember(self, name: _Key, number: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def srem(self, name: _Key, *values: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def sunion(self, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def sunionstore(self, dest: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def xack(self, name, groupname, *ids) -> Pipeline[_StrType]: ... # type: ignore[override] - def xadd(self, name, fields, id=..., maxlen=..., approximate: bool = ..., nomkstream: bool = ..., minid: Any | None = ..., limit: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xclaim( - self, name, groupname, consumername, min_idle_time, message_ids, idle=..., time=..., retrycount=..., force=..., justid=... - ) -> Pipeline[_StrType]: ... # type: ignore[override] - def xdel(self, name, *ids) -> Pipeline[_StrType]: ... # type: ignore[override] - def xgroup_create(self, name, groupname, id=..., mkstream=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xgroup_delconsumer(self, name, groupname, consumername) -> Pipeline[_StrType]: ... # type: ignore[override] - def xgroup_destroy(self, name, groupname) -> Pipeline[_StrType]: ... # type: ignore[override] - def xgroup_setid(self, name, groupname, id) -> Pipeline[_StrType]: ... # type: ignore[override] - def xinfo_consumers(self, name, groupname) -> Pipeline[_StrType]: ... # type: ignore[override] - def xinfo_groups(self, name) -> Pipeline[_StrType]: ... # type: ignore[override] - def xinfo_stream(self, name, full: bool = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xlen(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def xpending(self, name, groupname) -> Pipeline[_StrType]: ... # type: ignore[override] - def xpending_range(self, name, groupname, idle: Any | None = ..., min: int | None = ..., max: int | None = ..., count: int | None = ..., consumername=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xrange(self, name, min=..., max=..., count=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xread(self, streams, count=..., block=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xreadgroup(self, groupname, consumername, streams, count=..., block=..., noack=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xrevrange(self, name, max=..., min=..., count=...) -> Pipeline[_StrType]: ... # type: ignore[override] - def xtrim(self, name, maxlen: int | None = ..., approximate: bool = ..., minid: Any | None = ..., limit: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def zadd( # type: ignore[override] - self, - name: _Key, - mapping: Mapping[_Key, _Value], - nx: bool = ..., - xx: bool = ..., - ch: bool = ..., - incr: bool = ..., - gt: Any | None = ..., - lt: Any | None = ..., - ) -> Pipeline[_StrType]: ... - def zcard(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def zcount(self, name: _Key, min: _Value, max: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zincrby(self, name: _Key, amount: float, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zinterstore(self, dest: _Key, keys: Iterable[_Key], aggregate: Literal["SUM", "MIN", "MAX"] | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def zlexcount(self, name: _Key, min: _Value, max: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zpopmax(self, name: _Key, count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def zpopmin(self, name: _Key, count: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def bzpopmax(self, keys: _Key | Iterable[_Key], timeout: float = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def bzpopmin(self, keys: _Key | Iterable[_Key], timeout: float = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def zrange( # type: ignore[override] - self, - name: _Key, - start: int, - end: int, - desc: bool = ..., - withscores: bool = ..., - score_cast_func: Callable[[Any], Any] = ..., - byscore: bool = ..., - bylex: bool = ..., - offset: int | None = ..., - num: int | None = ..., - ) -> Pipeline[_StrType]: ... - def zrangebylex(self, name: _Key, min: _Value, max: _Value, start: int | None = ..., num: int | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def zrangebyscore( # type: ignore[override] - self, - name: _Key, - min: _Value, - max: _Value, - start: int | None = ..., - num: int | None = ..., - withscores: bool = ..., - score_cast_func: Callable[[Any], Any] = ..., - ) -> Pipeline[_StrType]: ... - def zrank(self, name: _Key, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zrem(self, name: _Key, *values: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zremrangebylex(self, name: _Key, min: _Value, max: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zremrangebyrank(self, name: _Key, min: _Value, max: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zremrangebyscore(self, name: _Key, min: _Value, max: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zrevrange( # type: ignore[override] - self, name: _Key, start: int, end: int, withscores: bool = ..., score_cast_func: Callable[[Any], Any] = ... - ) -> Pipeline[_StrType]: ... - def zrevrangebyscore( # type: ignore[override] - self, - name: _Key, - max: _Value, - min: _Value, - start: int | None = ..., - num: int | None = ..., - withscores: bool = ..., - score_cast_func: Callable[[Any], Any] = ..., - ) -> Pipeline[_StrType]: ... - def zrevrangebylex( # type: ignore[override] - self, name: _Key, max: _Value, min: _Value, start: int | None = ..., num: int | None = ... - ) -> Pipeline[_StrType]: ... - def zrevrank(self, name: _Key, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zscore(self, name: _Key, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def zunionstore(self, dest: _Key, keys: Iterable[_Key], aggregate: Literal["SUM", "MIN", "MAX"] | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def pfadd(self, name: _Key, *values: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def pfcount(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def pfmerge(self, dest: _Key, *sources: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hdel(self, name: _Key, *keys: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hexists(self, name: _Key, key: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hget(self, name: _Key, key: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hgetall(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hincrby(self, name: _Key, key: _Key, amount: int = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def hincrbyfloat(self, name: _Key, key: _Key, amount: float = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def hkeys(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hlen(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - @overload # type: ignore[override] - def hset(self, name: _Key, key: _Key, value: _Value, mapping: Mapping[_Key, _Value] | None = ...) -> Pipeline[_StrType]: ... - @overload # type: ignore[override] - def hset(self, name: _Key, key: None, value: None, mapping: Mapping[_Key, _Value]) -> Pipeline[_StrType]: ... - @overload # type: ignore[override] - def hset(self, name: _Key, *, mapping: Mapping[_Key, _Value]) -> Pipeline[_StrType]: ... - def hsetnx(self, name: _Key, key: _Key, value: _Value) -> Pipeline[_StrType]: ... # type: ignore[override] - def hmset(self, name: _Key, mapping: Mapping[_Key, _Value]) -> Pipeline[_StrType]: ... # type: ignore[override] - def hmget(self, name: _Key, keys: _Key | Iterable[_Key], *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def hvals(self, name: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def publish(self, channel: _Key, message: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def eval(self, script, numkeys, *keys_and_args) -> Pipeline[_StrType]: ... # type: ignore[override] - def evalsha(self, sha, numkeys, *keys_and_args) -> Pipeline[_StrType]: ... # type: ignore[override] - def script_exists(self, *args) -> Pipeline[_StrType]: ... # type: ignore[override] - def script_flush(self, sync_type: Any | None = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def script_kill(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def script_load(self, script) -> Pipeline[_StrType]: ... # type: ignore[override] - def register_script(self, script: str | _StrType) -> Script: ... # type: ignore[override] - def pubsub_channels(self, pattern: _Key = ...) -> Pipeline[_StrType]: ... # type: ignore[override] - def pubsub_numsub(self, *args: _Key) -> Pipeline[_StrType]: ... # type: ignore[override] - def pubsub_numpat(self) -> Pipeline[_StrType]: ... # type: ignore[override] - def monitor(self) -> Monitor: ... - def cluster(self, cluster_arg: str, *args: Any) -> Pipeline[_StrType]: ... # type: ignore[override] - def client(self) -> Any: ... - -class Script: - registered_client: Any - script: Any - sha: Any - def __init__(self, registered_client, script) -> None: ... - def __call__(self, keys=..., args=..., client=...): ... - -class Monitor(object): - command_re: Pattern[str] - monitor_re: Pattern[str] - def __init__(self, connection_pool) -> None: ... - def __enter__(self) -> Monitor: ... - def __exit__(self, *args: Any) -> None: ... - def next_command(self) -> dict[str, Any]: ... - def listen(self) -> Iterable[dict[str, Any]]: ... diff --git a/stubs/redis/redis/commands/__init__.pyi b/stubs/redis/redis/commands/__init__.pyi deleted file mode 100644 index 3debade74407..000000000000 --- a/stubs/redis/redis/commands/__init__.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from .core import CoreCommands as CoreCommands -from .helpers import list_or_args as list_or_args -from .redismodules import RedisModuleCommands as RedisModuleCommands -from .sentinel import SentinelCommands as SentinelCommands - -__all__ = ["CoreCommands", "RedisModuleCommands", "SentinelCommands", "list_or_args"] diff --git a/stubs/redis/redis/commands/core.pyi b/stubs/redis/redis/commands/core.pyi deleted file mode 100644 index cd279a09c5a6..000000000000 --- a/stubs/redis/redis/commands/core.pyi +++ /dev/null @@ -1,283 +0,0 @@ -from collections.abc import Callable, Iterable, Mapping, Sequence -from datetime import timedelta -from typing import Any, Generic, TypeVar, Union, overload -from typing_extensions import Literal - -from ..client import _Key, _Value - -_ScoreCastFuncReturn = TypeVar("_ScoreCastFuncReturn") -_StrType = TypeVar("_StrType", bound=Union[str, bytes]) - -class CoreCommands(Generic[_StrType]): - def acl_cat(self, category: str | None = ...) -> list[str]: ... - def acl_deluser(self, username: str) -> int: ... - def acl_genpass(self, bits: int | None = ...) -> str: ... - def acl_getuser(self, username: str) -> Any | None: ... - def acl_list(self) -> list[str]: ... - def acl_load(self) -> bool: ... - def acl_setuser( - self, - username: str, - enabled: bool = ..., - nopass: bool = ..., - passwords: Sequence[str] | None = ..., - hashed_passwords: Sequence[str] | None = ..., - categories: Sequence[str] | None = ..., - commands: Sequence[str] | None = ..., - keys: Sequence[str] | None = ..., - reset: bool = ..., - reset_keys: bool = ..., - reset_passwords: bool = ..., - ) -> bool: ... - def acl_users(self) -> list[str]: ... - def acl_whoami(self) -> str: ... - def append(self, key, value): ... - def bitcount(self, key: _Key, start: int | None = ..., end: int | None = ...) -> int: ... - def bitop(self, operation, dest, *keys): ... - def bitpos(self, key, bit, start=..., end=...): ... - def bgrewriteaof(self): ... - def bgsave(self, schedule: bool = ...): ... - def client_id(self) -> int: ... - def client_kill(self, address: str) -> bool: ... - def client_list(self, _type: str | None = ..., client_id: list[str] = ...) -> list[dict[str, str]]: ... - def client_getname(self) -> str | None: ... - def client_setname(self, name: str) -> bool: ... - def flushall(self, asynchronous: bool = ...) -> bool: ... - def flushdb(self, asynchronous: bool = ...) -> bool: ... - def lindex(self, name: _Key, index: int) -> _StrType | None: ... - def linsert( - self, name: _Key, where: Literal["BEFORE", "AFTER", "before", "after"], refvalue: _Value, value: _Value - ) -> int: ... - def llen(self, name: _Key) -> int: ... - def lmove( - self, first_list: _Key, second_list: _Key, src: Literal["LEFT", "RIGHT"] = ..., dest: Literal["LEFT", "RIGHT"] = ... - ) -> _Value: ... - def blmove( - self, - first_list: _Key, - second_list: _Key, - timeout: float, - src: Literal["LEFT", "RIGHT"] = ..., - dest: Literal["LEFT", "RIGHT"] = ..., - ) -> _Value | None: ... - def lpop(self, name, count: int | None = ...): ... - def lpush(self, name: _Value, *values: _Value) -> int: ... - def lpushx(self, name, value): ... - def lrange(self, name: _Key, start: int, end: int) -> list[_StrType]: ... - def lrem(self, name: _Key, count: int, value: _Value) -> int: ... - def lset(self, name: _Key, index: int, value: _Value) -> bool: ... - def ltrim(self, name: _Key, start: int, end: int) -> bool: ... - def randomkey(self): ... - def rename(self, src, dst): ... - def renamenx(self, src, dst): ... - def restore( - self, name, ttl, value, replace: bool = ..., absttl: bool = ..., idletime: Any | None = ..., frequency: Any | None = ... - ): ... - def rpop(self, name, count: int | None = ...): ... - def rpoplpush(self, src, dst): ... - def rpush(self, name: _Value, *values: _Value) -> int: ... - def rpushx(self, name, value): ... - def set( - self, - name: _Key, - value: _Value, - ex: None | int | timedelta = ..., - px: None | int | timedelta = ..., - nx: bool = ..., - xx: bool = ..., - keepttl: bool = ..., - get: bool = ..., - exat: Any | None = ..., - pxat: Any | None = ..., - ) -> bool | None: ... - def xack(self, name, groupname, *ids): ... - def xadd( - self, - name, - fields, - id: str = ..., - maxlen=..., - approximate: bool = ..., - nomkstream: bool = ..., - minid: Any | None = ..., - limit: Any | None = ..., - ): ... - def xclaim( - self, name, groupname, consumername, min_idle_time, message_ids, idle=..., time=..., retrycount=..., force=..., justid=... - ): ... - def xdel(self, name, *ids): ... - def xgroup_create(self, name, groupname, id=..., mkstream=...): ... - def xgroup_delconsumer(self, name, groupname, consumername): ... - def xgroup_destroy(self, name, groupname): ... - def xgroup_setid(self, name, groupname, id): ... - def xinfo_consumers(self, name, groupname): ... - def xinfo_groups(self, name): ... - def xinfo_stream(self, name, full: bool = ...): ... - def xlen(self, name: _Key) -> int: ... - def xpending(self, name, groupname): ... - def xpending_range( - self, - name, - groupname, - idle: Any | None = ..., - min: Any | None = ..., - max: Any | None = ..., - count: int | None = ..., - consumername: Any | None = ..., - ): ... - def xrange(self, name, min=..., max=..., count=...): ... - def xread(self, streams, count=..., block=...): ... - def xreadgroup(self, groupname, consumername, streams, count=..., block=..., noack=...): ... - def xrevrange(self, name, max=..., min=..., count=...): ... - def xtrim( - self, name, maxlen: Any | None = ..., approximate: bool = ..., minid: Any | None = ..., limit: Any | None = ... - ): ... - def zadd( - self, - name: _Key, - mapping: Mapping[_Key, _Value], - nx: bool = ..., - xx: bool = ..., - ch: bool = ..., - incr: bool = ..., - gt: Any | None = ..., - lt: Any | None = ..., - ) -> int: ... - def zcard(self, name: _Key) -> int: ... - def zcount(self, name: _Key, min: _Value, max: _Value) -> int: ... - def zincrby(self, name: _Key, amount: float, value: _Value) -> float: ... - def zinterstore(self, dest: _Key, keys: Iterable[_Key], aggregate: Literal["SUM", "MIN", "MAX"] | None = ...) -> int: ... - def zlexcount(self, name: _Key, min: _Value, max: _Value) -> int: ... - def zpopmax(self, name: _Key, count: int | None = ...) -> list[tuple[_StrType, float]]: ... - def zpopmin(self, name: _Key, count: int | None = ...) -> list[tuple[_StrType, float]]: ... - @overload - def bzpopmax(self, keys: _Key | Iterable[_Key], timeout: Literal[0] = ...) -> tuple[_StrType, _StrType, float]: ... - @overload - def bzpopmax(self, keys: _Key | Iterable[_Key], timeout: float) -> tuple[_StrType, _StrType, float] | None: ... - @overload - def bzpopmin(self, keys: _Key | Iterable[_Key], timeout: Literal[0] = ...) -> tuple[_StrType, _StrType, float]: ... - @overload - def bzpopmin(self, keys: _Key | Iterable[_Key], timeout: float) -> tuple[_StrType, _StrType, float] | None: ... - @overload - def zrange( - self, - name: _Key, - start: int, - end: int, - desc: bool = ..., - *, - withscores: Literal[True], - score_cast_func: Callable[[float], _ScoreCastFuncReturn] = ..., - byscore: bool = ..., - bylex: bool = ..., - offset: int | None = ..., - num: int | None = ..., - ) -> list[tuple[_StrType, _ScoreCastFuncReturn]]: ... - @overload - def zrange( - self, - name: _Key, - start: int, - end: int, - desc: bool = ..., - withscores: bool = ..., - score_cast_func: Callable[[Any], Any] = ..., - byscore: bool = ..., - bylex: bool = ..., - offset: int | None = ..., - num: int | None = ..., - ) -> list[_StrType]: ... - def zrangebylex( - self, name: _Key, min: _Value, max: _Value, start: int | None = ..., num: int | None = ... - ) -> list[_StrType]: ... - @overload - def zrangebyscore( - self, - name: _Key, - min: _Value, - max: _Value, - start: int | None = ..., - num: int | None = ..., - *, - withscores: Literal[True], - score_cast_func: Callable[[float], _ScoreCastFuncReturn] = ..., - ) -> list[tuple[_StrType, _ScoreCastFuncReturn]]: ... - @overload - def zrangebyscore( - self, - name: _Key, - min: _Value, - max: _Value, - start: int | None = ..., - num: int | None = ..., - withscores: bool = ..., - score_cast_func: Callable[[Any], Any] = ..., - ) -> list[_StrType]: ... - def zrank(self, name: _Key, value: _Value) -> int | None: ... - def zrem(self, name: _Key, *values: _Value) -> int: ... - def zremrangebylex(self, name: _Key, min: _Value, max: _Value) -> int: ... - def zremrangebyrank(self, name: _Key, min: int, max: int) -> int: ... - def zremrangebyscore(self, name: _Key, min: _Value, max: _Value) -> int: ... - @overload - def zrevrange( - self, - name: _Key, - start: int, - end: int, - *, - withscores: Literal[True], - score_cast_func: Callable[[float], _ScoreCastFuncReturn] = ..., - ) -> list[tuple[_StrType, _ScoreCastFuncReturn]]: ... - @overload - def zrevrange( - self, name: _Key, start: int, end: int, withscores: bool = ..., score_cast_func: Callable[[Any], Any] = ... - ) -> list[_StrType]: ... - @overload - def zrevrangebyscore( - self, - name: _Key, - max: _Value, - min: _Value, - start: int | None = ..., - num: int | None = ..., - *, - withscores: Literal[True], - score_cast_func: Callable[[float], _ScoreCastFuncReturn] = ..., - ) -> list[tuple[_StrType, _ScoreCastFuncReturn]]: ... - @overload - def zrevrangebyscore( - self, - name: _Key, - max: _Value, - min: _Value, - start: int | None = ..., - num: int | None = ..., - withscores: bool = ..., - score_cast_func: Callable[[Any], Any] = ..., - ) -> list[_StrType]: ... - def zrevrangebylex( - self, name: _Key, max: _Value, min: _Value, start: int | None = ..., num: int | None = ... - ) -> list[_StrType]: ... - def zrevrank(self, name: _Key, value: _Value) -> int | None: ... - def zscore(self, name: _Key, value: _Value) -> float | None: ... - def zunionstore(self, dest: _Key, keys: Iterable[_Key], aggregate: Literal["SUM", "MIN", "MAX"] | None = ...) -> int: ... - def script_exists(self, *args): ... - def script_flush(self, sync_type: Any | None = ...): ... - def script_kill(self): ... - def script_load(self, script): ... - def register_script(self, script: str | _StrType) -> Script: ... - -class Script: - def __init__(self, registered_client, script) -> None: ... - def __call__(self, keys=..., args=..., client: Any | None = ...): ... - -class BitFieldOperation: - def __init__(self, client, key, default_overflow: Any | None = ...): ... - def reset(self) -> None: ... - def overflow(self, overflow): ... - def incrby(self, fmt, offset, increment, overflow: Any | None = ...): ... - def get(self, fmt, offset): ... - def set(self, fmt, offset, value): ... - @property - def command(self): ... - def execute(self): ... diff --git a/stubs/redis/redis/commands/helpers.pyi b/stubs/redis/redis/commands/helpers.pyi deleted file mode 100644 index 231306845749..000000000000 --- a/stubs/redis/redis/commands/helpers.pyi +++ /dev/null @@ -1,6 +0,0 @@ -def list_or_args(keys, args): ... -def nativestr(x): ... -def delist(x): ... -def parse_to_list(response): ... -def random_string(length: int = ...) -> str: ... -def quote_string(v): ... diff --git a/stubs/redis/redis/commands/json/__init__.pyi b/stubs/redis/redis/commands/json/__init__.pyi deleted file mode 100644 index e67c7bfef39e..000000000000 --- a/stubs/redis/redis/commands/json/__init__.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Any - -from ...client import Pipeline as ClientPipeline -from .commands import JSONCommands - -class JSON(JSONCommands): - MODULE_CALLBACKS: dict[str, Any] - client: Any - execute_command: Any - MODULE_VERSION: Any | None - def __init__(self, client, version: Any | None = ..., decoder=..., encoder=...) -> None: ... - def pipeline(self, transaction: bool = ..., shard_hint: Any | None = ...) -> Pipeline: ... - -class Pipeline(JSONCommands, ClientPipeline): ... # type: ignore[misc] diff --git a/stubs/redis/redis/commands/json/commands.pyi b/stubs/redis/redis/commands/json/commands.pyi deleted file mode 100644 index e3bdc25a5ab3..000000000000 --- a/stubs/redis/redis/commands/json/commands.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any - -class JSONCommands: - def arrappend(self, name, path=..., *args): ... - def arrindex(self, name, path, scalar, start: int = ..., stop: int = ...): ... - def arrinsert(self, name, path, index, *args): ... - def arrlen(self, name, path=...): ... - def arrpop(self, name, path=..., index: int = ...): ... - def arrtrim(self, name, path, start, stop): ... - def type(self, name, path=...): ... - def resp(self, name, path=...): ... - def objkeys(self, name, path=...): ... - def objlen(self, name, path=...): ... - def numincrby(self, name, path, number): ... - def nummultby(self, name, path, number): ... - def clear(self, name, path=...): ... - def delete(self, key, path=...): ... - forget = delete - def get(self, name, *args, no_escape: bool = ...): ... - def mget(self, keys, path): ... - def set(self, name, path, obj, nx: bool = ..., xx: bool = ..., decode_keys: bool = ...): ... - def strlen(self, name, path: Any | None = ...): ... - def toggle(self, name, path=...): ... - def strappend(self, name, value, path=...): ... - def debug(self, subcommand, key: Any | None = ..., path=...): ... - def jsonget(self, *args, **kwargs): ... - def jsonmget(self, *args, **kwargs): ... - def jsonset(self, *args, **kwargs): ... diff --git a/stubs/redis/redis/commands/json/decoders.pyi b/stubs/redis/redis/commands/json/decoders.pyi deleted file mode 100644 index ccea24386cb4..000000000000 --- a/stubs/redis/redis/commands/json/decoders.pyi +++ /dev/null @@ -1,4 +0,0 @@ -def bulk_of_jsons(d): ... -def decode_dict_keys(obj): ... -def unstring(obj): ... -def decode_list(b): ... diff --git a/stubs/redis/redis/commands/json/path.pyi b/stubs/redis/redis/commands/json/path.pyi deleted file mode 100644 index d33df3045bea..000000000000 --- a/stubs/redis/redis/commands/json/path.pyi +++ /dev/null @@ -1,5 +0,0 @@ -class Path: - strPath: str - @staticmethod - def rootPath() -> str: ... - def __init__(self, path: str) -> None: ... diff --git a/stubs/redis/redis/commands/redismodules.pyi b/stubs/redis/redis/commands/redismodules.pyi deleted file mode 100644 index 9f807c99327a..000000000000 --- a/stubs/redis/redis/commands/redismodules.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from .json import JSON -from .search import Search -from .timeseries import TimeSeries - -class RedisModuleCommands: - def json(self, encoder=..., decoder=...) -> JSON: ... - def ft(self, index_name: str = ...) -> Search: ... - def ts(self) -> TimeSeries: ... diff --git a/stubs/redis/redis/commands/search/__init__.pyi b/stubs/redis/redis/commands/search/__init__.pyi deleted file mode 100644 index b08ea3713083..000000000000 --- a/stubs/redis/redis/commands/search/__init__.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from .commands import SearchCommands - -class Search(SearchCommands): - class BatchIndexer: - def __init__(self, client, chunk_size: int = ...) -> None: ... - def add_document( - self, - doc_id, - nosave: bool = ..., - score: float = ..., - payload: Any | None = ..., - replace: bool = ..., - partial: bool = ..., - no_create: bool = ..., - **fields, - ): ... - def add_document_hash(self, doc_id, score: float = ..., replace: bool = ...): ... - def commit(self): ... - def __init__(self, client, index_name: str = ...) -> None: ... diff --git a/stubs/redis/redis/commands/search/commands.pyi b/stubs/redis/redis/commands/search/commands.pyi deleted file mode 100644 index 459376b5f552..000000000000 --- a/stubs/redis/redis/commands/search/commands.pyi +++ /dev/null @@ -1,92 +0,0 @@ -from typing import Any -from typing_extensions import Literal - -NUMERIC: Literal["NUMERIC"] - -CREATE_CMD: Literal["FT.CREATE"] -ALTER_CMD: Literal["FT.ALTER"] -SEARCH_CMD: Literal["FT.SEARCH"] -ADD_CMD: Literal["FT.ADD"] -ADDHASH_CMD: Literal["FT.ADDHASH"] -DROP_CMD: Literal["FT.DROP"] -EXPLAIN_CMD: Literal["FT.EXPLAIN"] -EXPLAINCLI_CMD: Literal["FT.EXPLAINCLI"] -DEL_CMD: Literal["FT.DEL"] -AGGREGATE_CMD: Literal["FT.AGGREGATE"] -CURSOR_CMD: Literal["FT.CURSOR"] -SPELLCHECK_CMD: Literal["FT.SPELLCHECK"] -DICT_ADD_CMD: Literal["FT.DICTADD"] -DICT_DEL_CMD: Literal["FT.DICTDEL"] -DICT_DUMP_CMD: Literal["FT.DICTDUMP"] -GET_CMD: Literal["FT.GET"] -MGET_CMD: Literal["FT.MGET"] -CONFIG_CMD: Literal["FT.CONFIG"] -TAGVALS_CMD: Literal["FT.TAGVALS"] -ALIAS_ADD_CMD: Literal["FT.ALIASADD"] -ALIAS_UPDATE_CMD: Literal["FT.ALIASUPDATE"] -ALIAS_DEL_CMD: Literal["FT.ALIASDEL"] -INFO_CMD: Literal["FT.INFO"] -SUGADD_COMMAND: Literal["FT.SUGADD"] -SUGDEL_COMMAND: Literal["FT.SUGDEL"] -SUGLEN_COMMAND: Literal["FT.SUGLEN"] -SUGGET_COMMAND: Literal["FT.SUGGET"] -SYNUPDATE_CMD: Literal["FT.SYNUPDATE"] -SYNDUMP_CMD: Literal["FT.SYNDUMP"] - -NOOFFSETS: Literal["NOOFFSETS"] -NOFIELDS: Literal["NOFIELDS"] -STOPWORDS: Literal["STOPWORDS"] -WITHSCORES: Literal["WITHSCORES"] -FUZZY: Literal["FUZZY"] -WITHPAYLOADS: Literal["WITHPAYLOADS"] - -class SearchCommands: - def batch_indexer(self, chunk_size: int = ...): ... - def create_index( - self, - fields, - no_term_offsets: bool = ..., - no_field_flags: bool = ..., - stopwords: Any | None = ..., - definition: Any | None = ..., - ): ... - def alter_schema_add(self, fields): ... - def drop_index(self, delete_documents: bool = ...): ... - def dropindex(self, delete_documents: bool = ...): ... - def add_document( - self, - doc_id, - nosave: bool = ..., - score: float = ..., - payload: Any | None = ..., - replace: bool = ..., - partial: bool = ..., - language: Any | None = ..., - no_create: bool = ..., - **fields, - ): ... - def add_document_hash(self, doc_id, score: float = ..., language: Any | None = ..., replace: bool = ...): ... - def delete_document(self, doc_id, conn: Any | None = ..., delete_actual_document: bool = ...): ... - def load_document(self, id): ... - def get(self, *ids): ... - def info(self): ... - def search(self, query): ... - def explain(self, query): ... - def explain_cli(self, query): ... - def aggregate(self, query): ... - def spellcheck(self, query, distance: Any | None = ..., include: Any | None = ..., exclude: Any | None = ...): ... - def dict_add(self, name, *terms): ... - def dict_del(self, name, *terms): ... - def dict_dump(self, name): ... - def config_set(self, option, value): ... - def config_get(self, option): ... - def tagvals(self, tagfield): ... - def aliasadd(self, alias): ... - def aliasupdate(self, alias): ... - def aliasdel(self, alias): ... - def sugadd(self, key, *suggestions, **kwargs): ... - def suglen(self, key): ... - def sugdel(self, key, string): ... - def sugget(self, key, prefix, fuzzy: bool = ..., num: int = ..., with_scores: bool = ..., with_payloads: bool = ...): ... - def synupdate(self, groupid, skipinitial: bool = ..., *terms): ... - def syndump(self): ... diff --git a/stubs/redis/redis/commands/sentinel.pyi b/stubs/redis/redis/commands/sentinel.pyi deleted file mode 100644 index 545642fac979..000000000000 --- a/stubs/redis/redis/commands/sentinel.pyi +++ /dev/null @@ -1,14 +0,0 @@ -class SentinelCommands: - def sentinel(self, *args): ... - def sentinel_get_master_addr_by_name(self, service_name): ... - def sentinel_master(self, service_name): ... - def sentinel_masters(self): ... - def sentinel_monitor(self, name, ip, port, quorum): ... - def sentinel_remove(self, name): ... - def sentinel_sentinels(self, service_name): ... - def sentinel_set(self, name, option, value): ... - def sentinel_slaves(self, service_name): ... - def sentinel_reset(self, pattern): ... - def sentinel_failover(self, new_master_name): ... - def sentinel_ckquorum(self, new_master_name): ... - def sentinel_flushconfig(self): ... diff --git a/stubs/redis/redis/commands/timeseries/__init__.pyi b/stubs/redis/redis/commands/timeseries/__init__.pyi deleted file mode 100644 index fae4f849b17b..000000000000 --- a/stubs/redis/redis/commands/timeseries/__init__.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from ...client import Pipeline as ClientPipeline -from .commands import TimeSeriesCommands - -class TimeSeries(TimeSeriesCommands): - MODULE_CALLBACKS: dict[str, Any] - client: Any - execute_command: Any - def __init__(self, client: Any | None = ..., **kwargs) -> None: ... - def pipeline(self, transaction: bool = ..., shard_hint: Any | None = ...) -> Pipeline: ... - -class Pipeline(TimeSeriesCommands, ClientPipeline): ... # type: ignore[misc] diff --git a/stubs/redis/redis/commands/timeseries/commands.pyi b/stubs/redis/redis/commands/timeseries/commands.pyi deleted file mode 100644 index 4a5a19af17ba..000000000000 --- a/stubs/redis/redis/commands/timeseries/commands.pyi +++ /dev/null @@ -1,95 +0,0 @@ -from typing import Any -from typing_extensions import Literal - -ADD_CMD: Literal["TS.ADD"] -ALTER_CMD: Literal["TS.ALTER"] -CREATERULE_CMD: Literal["TS.CREATERULE"] -CREATE_CMD: Literal["TS.CREATE"] -DECRBY_CMD: Literal["TS.DECRBY"] -DELETERULE_CMD: Literal["TS.DELETERULE"] -DEL_CMD: Literal["TS.DEL"] -GET_CMD: Literal["TS.GET"] -INCRBY_CMD: Literal["TS.INCRBY"] -INFO_CMD: Literal["TS.INFO"] -MADD_CMD: Literal["TS.MADD"] -MGET_CMD: Literal["TS.MGET"] -MRANGE_CMD: Literal["TS.MRANGE"] -MREVRANGE_CMD: Literal["TS.MREVRANGE"] -QUERYINDEX_CMD: Literal["TS.QUERYINDEX"] -RANGE_CMD: Literal["TS.RANGE"] -REVRANGE_CMD: Literal["TS.REVRANGE"] - -class TimeSeriesCommands: - def create(self, key, **kwargs): ... - def alter(self, key, **kwargs): ... - def add(self, key, timestamp, value, **kwargs): ... - def madd(self, ktv_tuples): ... - def incrby(self, key, value, **kwargs): ... - def decrby(self, key, value, **kwargs): ... - def delete(self, key, from_time, to_time): ... - def createrule(self, source_key, dest_key, aggregation_type, bucket_size_msec): ... - def deleterule(self, source_key, dest_key): ... - def range( - self, - key, - from_time, - to_time, - count: Any | None = ..., - aggregation_type: Any | None = ..., - bucket_size_msec: int = ..., - filter_by_ts: Any | None = ..., - filter_by_min_value: Any | None = ..., - filter_by_max_value: Any | None = ..., - align: Any | None = ..., - ): ... - def revrange( - self, - key, - from_time, - to_time, - count: Any | None = ..., - aggregation_type: Any | None = ..., - bucket_size_msec: int = ..., - filter_by_ts: Any | None = ..., - filter_by_min_value: Any | None = ..., - filter_by_max_value: Any | None = ..., - align: Any | None = ..., - ): ... - def mrange( - self, - from_time, - to_time, - filters, - count: Any | None = ..., - aggregation_type: Any | None = ..., - bucket_size_msec: int = ..., - with_labels: bool = ..., - filter_by_ts: Any | None = ..., - filter_by_min_value: Any | None = ..., - filter_by_max_value: Any | None = ..., - groupby: Any | None = ..., - reduce: Any | None = ..., - select_labels: Any | None = ..., - align: Any | None = ..., - ): ... - def mrevrange( - self, - from_time, - to_time, - filters, - count: Any | None = ..., - aggregation_type: Any | None = ..., - bucket_size_msec: int = ..., - with_labels: bool = ..., - filter_by_ts: Any | None = ..., - filter_by_min_value: Any | None = ..., - filter_by_max_value: Any | None = ..., - groupby: Any | None = ..., - reduce: Any | None = ..., - select_labels: Any | None = ..., - align: Any | None = ..., - ): ... - def get(self, key): ... - def mget(self, filters, with_labels: bool = ...): ... - def info(self, key): ... - def queryindex(self, filters): ... diff --git a/stubs/redis/redis/commands/timeseries/info.pyi b/stubs/redis/redis/commands/timeseries/info.pyi deleted file mode 100644 index 425dd29d5024..000000000000 --- a/stubs/redis/redis/commands/timeseries/info.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -class TSInfo: - rules: list[Any] - labels: list[Any] - sourceKey: Any | None - chunk_count: Any | None - memory_usage: Any | None - total_samples: Any | None - retention_msecs: Any | None - last_time_stamp: Any | None - first_time_stamp: Any | None - - max_samples_per_chunk: Any | None - chunk_size: Any | None - duplicate_policy: Any | None - def __init__(self, args) -> None: ... diff --git a/stubs/redis/redis/commands/timeseries/utils.pyi b/stubs/redis/redis/commands/timeseries/utils.pyi deleted file mode 100644 index 4a0d52c4d5cc..000000000000 --- a/stubs/redis/redis/commands/timeseries/utils.pyi +++ /dev/null @@ -1,5 +0,0 @@ -def list_to_dict(aList): ... -def parse_range(response): ... -def parse_m_range(response): ... -def parse_get(response): ... -def parse_m_get(response): ... diff --git a/stubs/redis/redis/connection.pyi b/stubs/redis/redis/connection.pyi deleted file mode 100644 index 875068195014..000000000000 --- a/stubs/redis/redis/connection.pyi +++ /dev/null @@ -1,179 +0,0 @@ -from typing import Any, Mapping, Type - -from .retry import Retry - -ssl_available: Any -SYM_STAR: Any -SYM_DOLLAR: Any -SYM_CRLF: Any -SYM_EMPTY: Any -SERVER_CLOSED_CONNECTION_ERROR: Any - -class BaseParser: - EXCEPTION_CLASSES: Any - def parse_error(self, response): ... - -class SocketBuffer: - socket_read_size: Any - bytes_written: Any - bytes_read: Any - def __init__(self, socket, socket_read_size, socket_timeout) -> None: ... - @property - def length(self): ... - def read(self, length): ... - def readline(self): ... - def purge(self): ... - def close(self): ... - def can_read(self, timeout): ... - -class PythonParser(BaseParser): - encoding: Any - socket_read_size: Any - def __init__(self, socket_read_size) -> None: ... - def __del__(self): ... - def on_connect(self, connection): ... - def on_disconnect(self): ... - def can_read(self, timeout): ... - def read_response(self): ... - -class HiredisParser(BaseParser): - socket_read_size: Any - def __init__(self, socket_read_size) -> None: ... - def __del__(self): ... - def on_connect(self, connection): ... - def on_disconnect(self): ... - def can_read(self, timeout): ... - def read_from_socket(self, timeout=..., raise_on_timeout: bool = ...) -> bool: ... - def read_response(self): ... - -DefaultParser: Any - -class Encoder: - def __init__(self, encoding, encoding_errors, decode_responses: bool) -> None: ... - def encode(self, value: str | bytes | memoryview | bool | float) -> bytes: ... - def decode(self, value: str | bytes | memoryview, force: bool = ...) -> str: ... - -class Connection: - description_format: Any - pid: Any - host: Any - port: Any - db: Any - password: Any - socket_timeout: Any - socket_connect_timeout: Any - socket_keepalive: Any - socket_keepalive_options: Any - retry_on_timeout: Any - encoding: Any - encoding_errors: Any - decode_responses: Any - retry: Retry - def __init__( - self, - host: str = ..., - port: int = ..., - db: int = ..., - password: str | None = ..., - socket_timeout: float | None = ..., - socket_connect_timeout: float | None = ..., - socket_keepalive: bool = ..., - socket_keepalive_options: Mapping[str, int | str] | None = ..., - socket_type: int = ..., - retry_on_timeout: bool = ..., - encoding: str = ..., - encoding_errors: str = ..., - decode_responses: bool = ..., - parser_class: Type[BaseParser] = ..., - socket_read_size: int = ..., - health_check_interval: int = ..., - client_name: str | None = ..., - username: str | None = ..., - retry: Retry | None = ..., - ) -> None: ... - def __del__(self): ... - def register_connect_callback(self, callback): ... - def clear_connect_callbacks(self): ... - def connect(self): ... - def on_connect(self): ... - def disconnect(self): ... - def check_health(self) -> None: ... - def send_packed_command(self, command, check_health: bool = ...): ... - def send_command(self, *args): ... - def can_read(self, timeout=...): ... - def read_response(self): ... - def pack_command(self, *args): ... - def pack_commands(self, commands): ... - def repr_pieces(self) -> list[tuple[str, str]]: ... - -class SSLConnection(Connection): - description_format: Any - keyfile: Any - certfile: Any - cert_reqs: Any - ca_certs: Any - def __init__( - self, ssl_keyfile=..., ssl_certfile=..., ssl_cert_reqs=..., ssl_ca_certs=..., ssl_check_hostname: bool = ..., **kwargs - ) -> None: ... - -class UnixDomainSocketConnection(Connection): - description_format: Any - pid: Any - path: Any - db: Any - password: Any - socket_timeout: Any - retry_on_timeout: Any - encoding: Any - encoding_errors: Any - decode_responses: Any - retry: Retry - def __init__( - self, - path=..., - db: int = ..., - username=..., - password=..., - socket_timeout=..., - encoding: str = ..., - encoding_errors: str = ..., - decode_responses: bool = ..., - retry_on_timeout: bool = ..., - parser_class=..., - socket_read_size: int = ..., - health_check_interval: int = ..., - client_name=..., - retry: Retry | None = ..., - ) -> None: ... - def repr_pieces(self) -> list[tuple[str, str]]: ... - -class ConnectionPool: - @classmethod - def from_url(cls, url: str, *, db: int = ..., decode_components: bool = ..., **kwargs) -> ConnectionPool: ... - connection_class: Any - connection_kwargs: Any - max_connections: Any - def __init__(self, connection_class=..., max_connections=..., **connection_kwargs) -> None: ... - pid: Any - def reset(self): ... - def get_connection(self, command_name, *keys, **options): ... - def make_connection(self): ... - def release(self, connection): ... - def disconnect(self, inuse_connections: bool = ...): ... - def get_encoder(self) -> Encoder: ... - def owns_connection(self, connection: Connection) -> bool: ... - -class BlockingConnectionPool(ConnectionPool): - queue_class: Any - timeout: Any - def __init__(self, max_connections=..., timeout=..., connection_class=..., queue_class=..., **connection_kwargs) -> None: ... - pid: Any - pool: Any - def reset(self): ... - def make_connection(self): ... - def get_connection(self, command_name, *keys, **options): ... - def release(self, connection): ... - def disconnect(self): ... - -def to_bool(value: object) -> bool: ... -def parse_url(url: str) -> dict[str, Any]: ... diff --git a/stubs/redis/redis/exceptions.pyi b/stubs/redis/redis/exceptions.pyi deleted file mode 100644 index 7aff7f227042..000000000000 --- a/stubs/redis/redis/exceptions.pyi +++ /dev/null @@ -1,19 +0,0 @@ -class RedisError(Exception): ... -class AuthenticationError(RedisError): ... -class ConnectionError(RedisError): ... -class TimeoutError(RedisError): ... -class BusyLoadingError(ConnectionError): ... -class InvalidResponse(RedisError): ... -class ResponseError(RedisError): ... -class DataError(RedisError): ... -class PubSubError(RedisError): ... -class WatchError(RedisError): ... -class NoScriptError(ResponseError): ... -class ExecAbortError(ResponseError): ... -class ReadOnlyError(ResponseError): ... -class NoPermissionError(ResponseError): ... -class ModuleError(ResponseError): ... -class LockError(RedisError, ValueError): ... -class LockNotOwnedError(LockError): ... -class ChildDeadlockedError(Exception): ... -class AuthenticationWrongNumberOfArgsError(ResponseError): ... diff --git a/stubs/redis/redis/lock.pyi b/stubs/redis/redis/lock.pyi deleted file mode 100644 index 7d774ccd64e5..000000000000 --- a/stubs/redis/redis/lock.pyi +++ /dev/null @@ -1,43 +0,0 @@ -from types import TracebackType -from typing import Any, ClassVar, Protocol, Type - -from redis.client import Redis - -class _Local(Protocol): - token: str | bytes | None - -class Lock: - LUA_EXTEND_SCRIPT: ClassVar[str] - LUA_REACQUIRE_SCRIPT: ClassVar[str] - LUA_RELEASE_SCRIPT: ClassVar[str] - lua_extend: ClassVar[Any | None] - lua_reacquire: ClassVar[Any | None] - lua_release: ClassVar[Any | None] - local: _Local - def __init__( - self, - redis: Redis[Any], - name: str, - timeout: float | None = ..., - sleep: float = ..., - blocking: bool = ..., - blocking_timeout: float | None = ..., - thread_local: bool = ..., - ) -> None: ... - def register_scripts(self) -> None: ... - def __enter__(self) -> Lock: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... - def acquire( - self, blocking: bool | None = ..., blocking_timeout: None | int | float = ..., token: str | bytes | None = ... - ) -> bool: ... - def do_acquire(self, token: str | bytes) -> bool: ... - def locked(self) -> bool: ... - def owned(self) -> bool: ... - def release(self) -> None: ... - def do_release(self, expected_token: str | bytes) -> None: ... - def extend(self, additional_time: int | float, replace_ttl: bool = ...) -> bool: ... - def do_extend(self, additional_time: int | float, replace_ttl: bool) -> bool: ... - def reacquire(self) -> bool: ... - def do_reacquire(self) -> bool: ... diff --git a/stubs/redis/redis/retry.pyi b/stubs/redis/redis/retry.pyi deleted file mode 100644 index 3182bf5bc37c..000000000000 --- a/stubs/redis/redis/retry.pyi +++ /dev/null @@ -1,3 +0,0 @@ -class Retry: - def __init__(self, backoff, retries, supported_errors=...) -> None: ... - def call_with_retry(self, do, fail): ... diff --git a/stubs/redis/redis/sentinel.pyi b/stubs/redis/redis/sentinel.pyi deleted file mode 100644 index ef757caf7609..000000000000 --- a/stubs/redis/redis/sentinel.pyi +++ /dev/null @@ -1,55 +0,0 @@ -from typing import Any, Type, TypeVar, overload -from typing_extensions import Literal - -from redis.client import Redis -from redis.commands.sentinel import SentinelCommands -from redis.connection import Connection, ConnectionPool, SSLConnection -from redis.exceptions import ConnectionError - -_Redis = TypeVar("_Redis", bound=Redis[Any]) - -class MasterNotFoundError(ConnectionError): ... -class SlaveNotFoundError(ConnectionError): ... - -class SentinelManagedConnection(Connection): - connection_pool: Any - def __init__(self, **kwargs) -> None: ... - def connect_to(self, address) -> None: ... - def connect(self) -> None: ... - def read_response(self): ... - -class SentinelManagedSSLConnection(SentinelManagedConnection, SSLConnection): ... - -class SentinelConnectionPool(ConnectionPool): - is_master: bool - check_connection: bool - connection_kwargs: Any - service_name: str - sentinel_manager: Any - def __init__(self, service_name, sentinel_manager, **kwargs) -> None: ... - def reset(self) -> None: ... - def owns_connection(self, connection) -> bool: ... - def get_master_address(self): ... - def rotate_slaves(self): ... - -class Sentinel(SentinelCommands): - sentinel_kwargs: Any - sentinels: Any - min_other_sentinels: int - connection_kwargs: Any - def __init__( - self, sentinels, min_other_sentinels: int = ..., sentinel_kwargs: Any | None = ..., **connection_kwargs - ) -> None: ... - def check_master_state(self, state, service_name) -> bool: ... - def discover_master(self, service_name): ... - def filter_slaves(self, slaves): ... - def discover_slaves(self, service_name): ... - @overload - def master_for(self, service_name: str, *, connection_pool_class=..., **kwargs) -> Redis[Any]: ... - @overload - def master_for(self, service_name: str, redis_class: Type[_Redis] = ..., connection_pool_class=..., **kwargs) -> _Redis: ... - @overload - def slave_for(self, service_name: str, connection_pool_class=..., **kwargs) -> Redis[Any]: ... - @overload - def slave_for(self, service_name: str, redis_class: Type[_Redis] = ..., connection_pool_class=..., **kwargs) -> _Redis: ... - def execute_command(self, *args, **kwargs) -> Literal[True]: ... diff --git a/stubs/redis/redis/utils.pyi b/stubs/redis/redis/utils.pyi deleted file mode 100644 index 9df7a80e3b70..000000000000 --- a/stubs/redis/redis/utils.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from contextlib import AbstractContextManager -from typing import Any, TypeVar, overload -from typing_extensions import Literal - -from .client import Pipeline, Redis, _StrType - -_T = TypeVar("_T") - -HIREDIS_AVAILABLE: bool - -@overload -def from_url(url: str, *, db: int = ..., decode_responses: Literal[True], **kwargs: Any) -> Redis[str]: ... -@overload -def from_url(url: str, *, db: int = ..., decode_responses: Literal[False] = ..., **kwargs: Any) -> Redis[bytes]: ... -def pipeline(redis_obj: Redis[_StrType]) -> AbstractContextManager[Pipeline[_StrType]]: ... -@overload -def str_if_bytes(value: bytes) -> str: ... # type: ignore[misc] -@overload -def str_if_bytes(value: _T) -> _T: ... -def safe_str(value: object) -> str: ... diff --git a/stubs/regex/@tests/stubtest_allowlist.txt b/stubs/regex/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5629e03e968a --- /dev/null +++ b/stubs/regex/@tests/stubtest_allowlist.txt @@ -0,0 +1,15 @@ +# Not exported in C modules: +regex._regex.Splitter +regex._regex.Scanner + +# Implementation details: +regex._regex.compile +regex._regex.copyright +regex._regex.fold_case +regex._regex.get_all_cases +regex._regex.get_code_size +regex._regex.get_expand_on_folding +regex._regex.get_properties +regex._regex.has_property_value +regex._regex.CODE_SIZE +regex._regex.MAGIC diff --git a/stubs/regex/@tests/test_cases/check_finditer.py b/stubs/regex/@tests/test_cases/check_finditer.py new file mode 100644 index 000000000000..1b2576736d75 --- /dev/null +++ b/stubs/regex/@tests/test_cases/check_finditer.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +import regex + +# Regression tests for #9263 +assert_type(list(regex.finditer(r"foo", "foo")), list[regex.Match[str]]) +pat = regex.compile(rb"foo") +assert_type(list(pat.finditer(b"foo")), list[regex.Match[bytes]]) diff --git a/stubs/regex/METADATA.toml b/stubs/regex/METADATA.toml new file mode 100644 index 000000000000..58d3a62fe610 --- /dev/null +++ b/stubs/regex/METADATA.toml @@ -0,0 +1,2 @@ +version = "2026.9.29" +upstream-repository = "https://github.com/mrabarnett/mrab-regex" diff --git a/stubs/regex/regex/__init__.pyi b/stubs/regex/regex/__init__.pyi new file mode 100644 index 000000000000..d6f58927e4df --- /dev/null +++ b/stubs/regex/regex/__init__.pyi @@ -0,0 +1,65 @@ +from ._main import * + +# Sync with regex._main.__all__ +__all__ = [ + "cache_all", + "compile", + "DEFAULT_VERSION", + "escape", + "findall", + "finditer", + "fullmatch", + "match", + "prefixmatch", + "purge", + "search", + "split", + "splititer", + "sub", + "subf", + "subfn", + "subn", + "template", + "Scanner", + "A", + "ASCII", + "B", + "BESTMATCH", + "D", + "DEBUG", + "E", + "ENHANCEMATCH", + "S", + "DOTALL", + "F", + "FULLCASE", + "I", + "IGNORECASE", + "L", + "LOCALE", + "M", + "MULTILINE", + "P", + "POSIX", + "R", + "REVERSE", + "T", + "TEMPLATE", + "U", + "UNICODE", + "V0", + "VERSION0", + "V1", + "VERSION1", + "X", + "VERBOSE", + "W", + "WORD", + "error", + "Regex", + "__version__", + "__doc__", + "RegexFlag", + "Pattern", + "Match", +] diff --git a/stubs/regex/regex/_main.pyi b/stubs/regex/regex/_main.pyi new file mode 100644 index 000000000000..0e38ec3cad27 --- /dev/null +++ b/stubs/regex/regex/_main.pyi @@ -0,0 +1,759 @@ +from _typeshed import ReadableBuffer, Unused +from collections.abc import Callable, Mapping +from types import GenericAlias +from typing import Any, AnyStr, Generic, Literal, TypeVar, final, overload +from typing_extensions import Self + +from . import _regex +from ._regex_core import * + +_T = TypeVar("_T") + +__version__: str + +# Sync with regex.__init__.__all__ +__all__ = [ + "cache_all", + "compile", + "DEFAULT_VERSION", + "escape", + "findall", + "finditer", + "fullmatch", + "match", + "prefixmatch", + "purge", + "search", + "split", + "splititer", + "sub", + "subf", + "subfn", + "subn", + "template", + "Scanner", + "A", + "ASCII", + "B", + "BESTMATCH", + "D", + "DEBUG", + "E", + "ENHANCEMATCH", + "S", + "DOTALL", + "F", + "FULLCASE", + "I", + "IGNORECASE", + "L", + "LOCALE", + "M", + "MULTILINE", + "P", + "POSIX", + "R", + "REVERSE", + "T", + "TEMPLATE", + "U", + "UNICODE", + "V0", + "VERSION0", + "V1", + "VERSION1", + "X", + "VERBOSE", + "W", + "WORD", + "error", + "Regex", + "__version__", + "__doc__", + "RegexFlag", + "Pattern", + "Match", +] + +def compile( + pattern: AnyStr | Pattern[AnyStr], + flags: int = 0, + ignore_unused: bool = False, + cache_pattern: bool | None = None, + **kwargs: Any, +) -> Pattern[AnyStr]: ... + +@overload +def search( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[str] | None: ... +@overload +def search( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[bytes] | None: ... + +@overload +def match( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[str] | None: ... +@overload +def match( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[bytes] | None: ... + +prefixmatch = match + +@overload +def fullmatch( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[str] | None: ... +@overload +def fullmatch( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[bytes] | None: ... + +@overload +def split( + pattern: str | Pattern[str], + string: str, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[str | Any]: ... +@overload +def split( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[bytes | Any]: ... + +@overload +def splititer( + pattern: str | Pattern[str], + string: str, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Splitter[str]: ... +@overload +def splititer( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Splitter[bytes]: ... + +@overload +def findall( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[Any]: ... +@overload +def findall( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[Any]: ... + +@overload +def finditer( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Scanner[str]: ... +@overload +def finditer( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Scanner[bytes]: ... + +@overload +def sub( + pattern: str | Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> str: ... +@overload +def sub( + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> bytes: ... + +@overload +def subf( + pattern: str | Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> str: ... +@overload +def subf( + pattern: bytes | Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> bytes: ... + +@overload +def subn( + pattern: str | Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[str, int]: ... +@overload +def subn( + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[bytes, int]: ... + +@overload +def subfn( + pattern: str | Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[str, int]: ... +@overload +def subfn( + pattern: bytes | Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[bytes, int]: ... + +def purge() -> None: ... + +@overload +def cache_all(value: bool = True) -> None: ... +@overload +def cache_all(value: None) -> bool: ... + +def escape(pattern: AnyStr, special_only: bool = True, literal_spaces: bool = False) -> AnyStr: ... + +DEFAULT_VERSION = RegexFlag.VERSION0 + +def template(pattern: AnyStr | Pattern[AnyStr], flags: int = 0) -> Pattern[AnyStr]: ... + +Regex = compile + +@final +class Pattern(Generic[AnyStr]): + @property + def flags(self) -> int: ... + @property + def groupindex(self) -> Mapping[str, int]: ... + @property + def groups(self) -> int: ... + @property + def pattern(self) -> AnyStr: ... + @property + def named_lists(self) -> Mapping[str, frozenset[AnyStr]]: ... + + @overload + def search( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[str] | None: ... + @overload + def search( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[bytes] | None: ... + + @overload + def match( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[str] | None: ... + @overload + def match( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[bytes] | None: ... + + prefixmatch = match + + @overload + def fullmatch( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[str] | None: ... + @overload + def fullmatch( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[bytes] | None: ... + + @overload + def split( + self: Pattern[str], string: str, maxsplit: int = 0, concurrent: bool | None = None, timeout: float | None = None + ) -> list[str | Any]: ... + @overload + def split( + self: Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> list[bytes | Any]: ... + + @overload + def splititer( + self: Pattern[str], string: str, maxsplit: int = 0, concurrent: bool | None = None, timeout: float | None = None + ) -> _regex.Splitter[str]: ... + @overload + def splititer( + self: Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> _regex.Splitter[bytes]: ... + + @overload + def findall( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> list[Any]: ... + @overload + def findall( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> list[Any]: ... + + @overload + def finditer( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[str]: ... + @overload + def finditer( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[bytes]: ... + + @overload + def sub( + self: Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> str: ... + @overload + def sub( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> bytes: ... + + @overload + def subf( + self: Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> str: ... + @overload + def subf( + self: Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> bytes: ... + + @overload + def subn( + self: Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[str, int]: ... + @overload + def subn( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[bytes, int]: ... + + @overload + def subfn( + self: Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[str, int]: ... + @overload + def subfn( + self: Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[bytes, int]: ... + + @overload + def scanner( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[str]: ... + @overload + def scanner( + self: Pattern[bytes], + string: bytes, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[bytes]: ... + + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Unused, /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class Match(Generic[AnyStr]): + @property + def pos(self) -> int: ... + @property + def endpos(self) -> int: ... + @property + def lastindex(self) -> int | None: ... + @property + def lastgroup(self) -> str | None: ... + @property + def string(self) -> AnyStr: ... + @property + def re(self) -> Pattern[AnyStr]: ... + @property + def partial(self) -> bool: ... + @property + def regs(self) -> tuple[tuple[int, int], ...]: ... + @property + def fuzzy_counts(self) -> tuple[int, int, int]: ... + @property + def fuzzy_changes(self) -> tuple[list[int], list[int], list[int]]: ... + + @overload + def group(self, group: Literal[0] = 0, /) -> AnyStr: ... + @overload + def group(self, group: int | str = ..., /) -> AnyStr | Any: ... + @overload + def group(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[AnyStr | Any, ...]: ... + + @overload + def groups(self, default: None = None) -> tuple[AnyStr | Any, ...]: ... + @overload + def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... + + @overload + def groupdict(self, default: None = None) -> dict[str, AnyStr | Any]: ... + @overload + def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... + + @overload + def span(self, group: int | str = ..., /) -> tuple[int, int]: ... + @overload + def span(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[tuple[int, int], ...]: ... + + @overload + def spans(self, group: int | str = ..., /) -> list[tuple[int, int]]: ... + @overload + def spans(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[tuple[int, int]], ...]: ... + + @overload + def start(self, group: int | str = ..., /) -> int: ... + @overload + def start(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[int, ...]: ... + + @overload + def starts(self, group: int | str = ..., /) -> list[int]: ... + @overload + def starts(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[int], ...]: ... + + @overload + def end(self, group: int | str = ..., /) -> int: ... + @overload + def end(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[int, ...]: ... + + @overload + def ends(self, group: int | str = ..., /) -> list[int]: ... + @overload + def ends(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[int], ...]: ... + + def expand(self, template: AnyStr, /) -> AnyStr: ... + def expandf(self, format: AnyStr, /) -> AnyStr: ... + + @overload + def captures(self, group: int | str = ..., /) -> list[AnyStr]: ... + @overload + def captures(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[AnyStr], ...]: ... + + def capturesdict(self) -> dict[str, list[AnyStr]]: ... + def detach_string(self) -> None: ... + def allcaptures(self) -> tuple[list[AnyStr], ...]: ... + def allspans(self) -> tuple[list[tuple[int, int]], ...]: ... + + @overload + def __getitem__(self, key: Literal[0], /) -> AnyStr: ... + @overload + def __getitem__(self, key: int | str, /) -> AnyStr | Any: ... + + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Unused, /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stubs/regex/regex/_regex.pyi b/stubs/regex/regex/_regex.pyi new file mode 100644 index 000000000000..c80e1662c33d --- /dev/null +++ b/stubs/regex/regex/_regex.pyi @@ -0,0 +1,26 @@ +# This is actually a C-extension module. +# Not all types defined in C are exported to Python. +# For example: `Pattern` and `Match` are not exported +# and are redefined in `regex.regex module. + +from typing import Any, AnyStr, Generic, final +from typing_extensions import Self + +from ._main import Match, Pattern + +@final +class Splitter(Generic[AnyStr]): + @property + def pattern(self) -> Pattern[AnyStr]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> AnyStr | Any: ... + def split(self) -> AnyStr | Any: ... + +@final +class Scanner(Generic[AnyStr]): + @property + def pattern(self) -> Pattern[AnyStr]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> Match[AnyStr]: ... + def match(self) -> Match[AnyStr] | None: ... + def search(self) -> Match[AnyStr] | None: ... diff --git a/stubs/regex/regex/_regex_core.pyi b/stubs/regex/regex/_regex_core.pyi new file mode 100644 index 000000000000..d8f3014f9a73 --- /dev/null +++ b/stubs/regex/regex/_regex_core.pyi @@ -0,0 +1,130 @@ +import enum +from collections.abc import Callable +from typing import Any, AnyStr, Generic, TypeAlias + +from ._main import Pattern + +__all__ = [ + "A", + "ASCII", + "B", + "BESTMATCH", + "D", + "DEBUG", + "E", + "ENHANCEMATCH", + "F", + "FULLCASE", + "I", + "IGNORECASE", + "L", + "LOCALE", + "M", + "MULTILINE", + "P", + "POSIX", + "R", + "REVERSE", + "S", + "DOTALL", + "T", + "TEMPLATE", + "U", + "UNICODE", + "V0", + "VERSION0", + "V1", + "VERSION1", + "W", + "WORD", + "X", + "VERBOSE", + "error", + "Scanner", + "RegexFlag", +] + +class error(Exception): + def __init__(self, message: str, pattern: AnyStr | None = None, pos: int | None = None) -> None: ... + +class RegexFlag(enum.IntFlag): + A = 0x80 + ASCII = A + B = 0x1000 + BESTMATCH = B + D = 0x200 + DEBUG = D + E = 0x8000 + ENHANCEMATCH = E + F = 0x4000 + FULLCASE = F + I = 0x2 + IGNORECASE = I + L = 0x4 + LOCALE = L + M = 0x8 + MULTILINE = M + P = 0x10000 + POSIX = P + R = 0x400 + REVERSE = R + T = 0x1 + TEMPLATE = T + S = 0x10 + DOTALL = S + U = 0x20 + UNICODE = U + V0 = 0x2000 + VERSION0 = V0 + V1 = 0x100 + VERSION1 = V1 + W = 0x800 + WORD = W + X = 0x40 + VERBOSE = X + +ASCII = RegexFlag.ASCII +BESTMATCH = RegexFlag.BESTMATCH +DEBUG = RegexFlag.DEBUG +ENHANCEMATCH = RegexFlag.ENHANCEMATCH +FULLCASE = RegexFlag.FULLCASE +IGNORECASE = RegexFlag.IGNORECASE +LOCALE = RegexFlag.LOCALE +MULTILINE = RegexFlag.MULTILINE +POSIX = RegexFlag.POSIX +REVERSE = RegexFlag.REVERSE +TEMPLATE = RegexFlag.TEMPLATE +DOTALL = RegexFlag.DOTALL +UNICODE = RegexFlag.UNICODE +VERBOSE = RegexFlag.VERBOSE +VERSION0 = RegexFlag.VERSION0 +VERSION1 = RegexFlag.VERSION1 +WORD = RegexFlag.WORD +A = RegexFlag.A +B = RegexFlag.B +D = RegexFlag.D +E = RegexFlag.E +F = RegexFlag.F +I = RegexFlag.I +L = RegexFlag.L +M = RegexFlag.M +P = RegexFlag.P +R = RegexFlag.R +S = RegexFlag.S +U = RegexFlag.U +V0 = RegexFlag.V0 +V1 = RegexFlag.V1 +W = RegexFlag.W +X = RegexFlag.X +T = RegexFlag.T + +DEFAULT_VERSION = VERSION1 + +_Lexicon: TypeAlias = list[tuple[AnyStr, Callable[[Scanner[AnyStr], AnyStr], Any]]] + +class Scanner(Generic[AnyStr]): + lexicon: _Lexicon[AnyStr] + scanner: Pattern[AnyStr] + + def __init__(self, lexicon: _Lexicon[AnyStr], flags: int = 0) -> None: ... + def scan(self, string: AnyStr) -> tuple[list[Any], AnyStr]: ... diff --git a/stubs/reportlab/@tests/stubtest_allowlist.txt b/stubs/reportlab/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2b0026f6730c --- /dev/null +++ b/stubs/reportlab/@tests/stubtest_allowlist.txt @@ -0,0 +1,107 @@ +# TODO: missing from stub +reportlab.graphics.barcode.dmtx.__all__ +reportlab.rl_config.__all__ + +# Incorrect __all__ names in runtime +reportlab.graphics.barcode.eanbc.__all__ +reportlab.graphics.barcode.ecc200datamatrix.__all__ + +# shapeFragWord has two incompatible definitions, depending on whether +# uharfbuzz is installed or not. We use the version where uharfbuzz is +# installed. +reportlab.pdfbase.ttfonts.shapeFragWord + +# Error: is inconsistent +# ====================== +# The drawOn method violates LSP all over the place and it's usually +# optional parameters that only exist in a base class and some of them +# are internal only like _sW, so we've decided to omit these, in order +# to get less noise from derived classes that don't have these parameters +reportlab\.platypus\.(doctemplate\.|flowables\.)?[A-Za-z_]+\.drawOn + +# similarly the wrap/split methods use inconsistent names for their +# parameters, so we decided to make them positional-only +reportlab.graphics.shapes.Drawing.wrap +reportlab\.platypus\.(doctemplate\.|flowables\.|tableofcontents\.)?[A-Za-z_]+\.split +reportlab\.platypus\.(doctemplate\.|flowables\.|tableofcontents\.)?[A-Za-z_]+\.wrap +reportlab.platypus.multicol.MultiCol.split +reportlab.platypus.para.FastPara.split +reportlab.platypus.para.FastPara.wrap +reportlab.platypus.para.Para.split +reportlab.platypus.para.Para.wrap +reportlab.platypus.paragraph.Paragraph.split +reportlab.platypus.paragraph.Paragraph.wrap +reportlab.platypus.tables.Table.split +reportlab.platypus.tables.Table.wrap + +# these have an optional extra argument which isn't consistently used +# among subclasses, so we pretend it doesn't exist for now +reportlab.platypus.flowables._ContainerSpace.getSpaceAfter +reportlab.platypus.flowables._ContainerSpace.getSpaceBefore + +# this has an internal __boundary__ argument which confuses stubtest +# we've decided to just get rid of the argument in the stub entirely +reportlab.platypus.frames.Frame.drawBoundary + +# this is just a case-insensitive version of dict and changes in parameter +# names and them changing from positional-only to keyword or positional +# is entirely untintentional, for simplicity we assume these methods +# work the same as in the base class, there is only one exception +# where the signature actually is more restrictive in CIDict +reportlab.lib.utils.CIDict.get +reportlab.lib.utils.CIDict.pop +reportlab.lib.utils.CIDict.setdefault + +# __new__ just forwards the arguments to the super class +# it doesn't actually accept arbitrary arguments +reportlab.platypus.doctemplate.PTCycle.__new__ + + +# Error: not present in stub +# ========================== +# loop variables that weren't cleaned up +reportlab.lib.fonts.v +reportlab.graphics.barcode.code93.k +reportlab.graphics.barcode.code93.v +reportlab.graphics.barcode.qrencoder.i +reportlab.lib.fonts.k +reportlab.lib.pdfencrypt.i + +# should allow setting any attribute +reportlab.lib.abag.ABag.__setattr__ +reportlab.lib.styles.PropertySet.__setattr__ + +# *-imports that cause a mess we don't want to propagate +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.EVEN_ODD +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.FILL_EVEN_ODD +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.FILL_NON_ZERO +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.NON_ZERO_WINDING +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.STATE_DEFAULTS +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.decimalSymbol +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.pi +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.shapeChecking +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.verbose + +# messed up __all__ which contains just a string +reportlab.graphics.barcode.qr.__all__ + + +# Error: is not present at runtime +# ================================ +# These can have arbitrary attributes, so we add a __getattr__ +reportlab.lib.abag.ABag.__getattr__ +reportlab.lib.styles.PropertySet.__getattr__ + +# Only exists on renderPM backend +reportlab.graphics.utils.processGlyph + + +# Error: failed to find stubs +# =========================== +# Modules that are only used for testing +reportlab.graphics.testdrawings +reportlab.graphics.testshapes +reportlab.graphics.barcode.test + +# named tuple docstring +reportlab.pdfbase.ttfonts.ShapeData.__doc__ diff --git a/stubs/reportlab/@tests/test_cases/check_tables.py b/stubs/reportlab/@tests/test_cases/check_tables.py new file mode 100644 index 000000000000..0d1b93de8170 --- /dev/null +++ b/stubs/reportlab/@tests/test_cases/check_tables.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +from typing import Any + +from reportlab.lib import colors +from reportlab.lib.styles import getSampleStyleSheet +from reportlab.lib.units import inch +from reportlab.platypus.flowables import Image +from reportlab.platypus.paragraph import Paragraph +from reportlab.platypus.tables import Table, TableStyle + +data: list[list[Any]] + +# Verify all the examples from the docs work + +# +# TableStyle User Methods +# +LIST_STYLE = TableStyle( + [ + ("LINEABOVE", (0, 0), (-1, 0), 2, colors.green), + ("LINEABOVE", (0, 1), (-1, -1), 0.25, colors.black), + ("LINEBELOW", (0, -1), (-1, -1), 2, colors.green), + ("ALIGN", (1, 1), (-1, -1), "RIGHT"), + ] +) +LIST_STYLE.add("BACKGROUND", (0, 0), (-1, 0), colors.Color(0, 0.7, 0.7)) + +# +# TableStyle Cell Formatting Commands +# +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +t = Table(data) +t.setStyle(TableStyle([("BACKGROUND", (1, 1), (-2, -2), colors.green), ("TEXTCOLOR", (0, 0), (1, -1), colors.red)])) + +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +t = Table(data, 5 * [0.4 * inch], 4 * [0.4 * inch]) +# NOTE: I've modified this example to drop the optional TableStyle +# wrapper, so we test both variants +t.setStyle( + [ + ("ALIGN", (1, 1), (-2, -2), "RIGHT"), + ("TEXTCOLOR", (1, 1), (-2, -2), colors.red), + ("VALIGN", (0, 0), (0, -1), "TOP"), + ("TEXTCOLOR", (0, 0), (0, -1), colors.blue), + ("ALIGN", (0, -1), (-1, -1), "CENTER"), + ("VALIGN", (0, -1), (-1, -1), "MIDDLE"), + ("TEXTCOLOR", (0, -1), (-1, -1), colors.green), + ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), + ("BOX", (0, 0), (-1, -1), 0.25, colors.black), + ] +) + +# +# Table Style Line Commands +# +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +Table( + data, + style=[ + ("GRID", (1, 1), (-2, -2), 1, colors.green), + ("BOX", (0, 0), (1, -1), 2, colors.red), + ("LINEABOVE", (1, 2), (-2, 2), 1, colors.blue), + ("LINEBEFORE", (2, 1), (2, -2), 1, colors.pink), + ], +) + +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +Table( + data, + style=[ + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("GRID", (1, 1), (-2, -2), 1, colors.green), + ("BOX", (0, 0), (1, -1), 2, colors.red), + ("BOX", (0, 0), (-1, -1), 2, colors.black), + ("LINEABOVE", (1, 2), (-2, 2), 1, colors.blue), + ("LINEBEFORE", (2, 1), (2, -2), 1, colors.pink), + ("BACKGROUND", (0, 0), (0, 1), colors.pink), + ("BACKGROUND", (1, 1), (1, 2), colors.lavender), + ("BACKGROUND", (2, 2), (2, 3), colors.orange), + ], +) + +# +# Complex Cell Values +# +styleSheet = getSampleStyleSheet() +I = Image("foo.jpg") +I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth +I.drawWidth = 1.25 * inch +P0 = Paragraph( + """A paragraph + 1""", + styleSheet["BodyText"], +) +P = Paragraph( + """The ReportLab Left + Logo + Image""", + styleSheet["BodyText"], +) +data = [ + ["A", "B", "C", P0, "D"], + ["00", "01", "02", [I, P], "04"], + ["10", "11", "12", [P, I], "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +Table( + data, + style=[ + ("GRID", (1, 1), (-2, -2), 1, colors.green), + ("BOX", (0, 0), (1, -1), 2, colors.red), + ("LINEABOVE", (1, 2), (-2, 2), 1, colors.blue), + ("LINEBEFORE", (2, 1), (2, -2), 1, colors.pink), + ("BACKGROUND", (0, 0), (0, 1), colors.pink), + ("BACKGROUND", (1, 1), (1, 2), colors.lavender), + ("BACKGROUND", (2, 2), (2, 3), colors.orange), + ("BOX", (0, 0), (-1, -1), 2, colors.black), + ("GRID", (0, 0), (-1, -1), 0.5, colors.black), + ("VALIGN", (3, 0), (3, 0), "BOTTOM"), + ("BACKGROUND", (3, 0), (3, 0), colors.limegreen), + ("BACKGROUND", (3, 1), (3, 1), colors.khaki), + ("ALIGN", (3, 1), (3, 1), "CENTER"), + ("BACKGROUND", (3, 2), (3, 2), colors.beige), + ("ALIGN", (3, 2), (3, 2), "LEFT"), + ], +) + +# +# TableStyle Span Commands +# +data = [ + ["Top\\nLeft", "", "02", "03", "04"], + ["", "", "12", "13", "14"], + ["20", "21", "22", "Bottom\\nRight", ""], + ["30", "31", "32", "", ""], +] +Table( + data, + style=[ + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("BACKGROUND", (0, 0), (1, 1), colors.palegreen), + ("SPAN", (0, 0), (1, 1)), + ("BACKGROUND", (-2, -2), (-1, -1), colors.pink), + ("SPAN", (-2, -2), (-1, -1)), + ], +) + +# +# TableStyle Miscellaneous Commands +# +# NOTE: This one doesn't provide any actual examples, we just +# make sure these pass into TableStyle/Table when mixed +# with other commands +TableStyle([("NOSPLIT", (0, 0), (1, 1))]) +LIST_STYLE.add("NOSPLIT", (0, 0), (1, 1)) + +TableStyle([("ROUNDEDCORNERS", [0, 0, 5, 5])]) +TableStyle([("ROUNDEDCORNERS", (0, 0, 5, 5))]) +LIST_STYLE.add("ROUNDEDCORNERS", [0, 0, 5, 5]) +LIST_STYLE.add("ROUNDEDCORNERS", (0, 0, 5, 5)) + +Table( + [["foo"]], + style=[ + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("BACKGROUND", (0, 0), (0, 1), colors.pink), + ("NOSPLIT", (0, 0), (1, 1)), + ("ROUNDEDCORNERS", [0, 0, 5, 5]), + ], +) + + +# Testing the various possible data layouts +Table([["foo"]]) +Table([("foo",)]) +Table((["foo"],)) +Table((("foo",),)) diff --git a/stubs/reportlab/METADATA.toml b/stubs/reportlab/METADATA.toml new file mode 100644 index 000000000000..76eaaf6e7ca3 --- /dev/null +++ b/stubs/reportlab/METADATA.toml @@ -0,0 +1,7 @@ +version = "5.0.0" +# GitHub mirror of https://hg.reportlab.com/hg-public/reportlab/file +upstream-repository = "https://github.com/MrBitBucket/reportlab-mirror" + +[tool.stubtest] +apt-dependencies = ["libcairo2-dev"] +extras = ["pycairo"] diff --git a/stubs/reportlab/reportlab/__init__.pyi b/stubs/reportlab/reportlab/__init__.pyi new file mode 100644 index 000000000000..664f86e2f301 --- /dev/null +++ b/stubs/reportlab/reportlab/__init__.pyi @@ -0,0 +1,11 @@ +from _typeshed import SupportsRichComparison +from typing import Final, Literal, TypeVar + +_SupportsRichComparisonT = TypeVar("_SupportsRichComparisonT", bound=SupportsRichComparison) + +Version: Final[str] +__version__: Final[str] +__date__: Final[str] +__min_python_version__: Final[tuple[int, int]] + +def cmp(a: _SupportsRichComparisonT, b: _SupportsRichComparisonT) -> Literal[-1, 0, 1]: ... diff --git a/stubs/reportlab/reportlab/graphics/__init__.pyi b/stubs/reportlab/reportlab/graphics/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/graphics/barcode/__init__.pyi b/stubs/reportlab/reportlab/graphics/barcode/__init__.pyi new file mode 100644 index 000000000000..62d6c1381612 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/__init__.pyi @@ -0,0 +1,7 @@ +def registerWidget(widget) -> None: ... +def getCodes(): ... +def getCodeNames(): ... +def createBarcodeDrawing(codeName, **options): ... +def createBarcodeImageInMemory(codeName, **options): ... + +__all__ = ("registerWidget", "getCodes", "getCodeNames", "createBarcodeDrawing", "createBarcodeImageInMemory") diff --git a/stubs/reportlab/reportlab/graphics/barcode/code128.pyi b/stubs/reportlab/reportlab/graphics/barcode/code128.pyi new file mode 100644 index 000000000000..024bfcdf439f --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/code128.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import MultiWidthBarcode + +starta: Incomplete +startb: Incomplete +startc: Incomplete +stop: Incomplete +seta: Incomplete +setb: Incomplete +setc: Incomplete +setmap: Incomplete +cStarts: Incomplete +tos: Incomplete + +class Code128(MultiWidthBarcode): + barWidth: Incomplete + lquiet: Incomplete + rquiet: Incomplete + quiet: int + barHeight: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self): ... + decomposed: Incomplete + def decompose(self): ... + +class Code128Auto(Code128): + encoded: Incomplete + def encode(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/code39.pyi b/stubs/reportlab/reportlab/graphics/barcode/code39.pyi new file mode 100644 index 000000000000..bea530fb0076 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/code39.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class _Code39Base(Barcode): + barWidth: Incomplete + lquiet: Incomplete + rquiet: Incomplete + quiet: int + gap: Incomplete + barHeight: Incomplete + ratio: float + checksum: int + bearers: float + stop: int + def __init__(self, value: str = "", **args) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Standard39(_Code39Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self): ... + +class Extended39(_Code39Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: str + def encode(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/code93.pyi b/stubs/reportlab/reportlab/graphics/barcode/code93.pyi new file mode 100644 index 000000000000..cc436c1470bd --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/code93.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import MultiWidthBarcode + +class _Code93Base(MultiWidthBarcode): + barWidth: Incomplete + lquiet: Incomplete + rquiet: Incomplete + quiet: int + barHeight: Incomplete + stop: int + def __init__(self, value: str = "", **args) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Standard93(_Code93Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self): ... + +class Extended93(_Code93Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: str + def encode(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/common.pyi b/stubs/reportlab/reportlab/graphics/barcode/common.pyi new file mode 100644 index 000000000000..513fb79debf7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/common.pyi @@ -0,0 +1,127 @@ +from _typeshed import Incomplete + +from reportlab.platypus.flowables import Flowable + +class Barcode(Flowable): + fontName: str + fontSize: int + humanReadable: int + value: Incomplete + gap: Incomplete + def __init__(self, value: str = "", **kwd) -> None: ... + valid: int + validated: Incomplete + def validate(self) -> None: ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self) -> None: ... + barHeight: Incomplete + def computeSize(self, *args) -> None: ... + + @property + def width(self): ... + @width.setter + def width(self, v) -> None: ... + + @property + def height(self): ... + @height.setter + def height(self, v) -> None: ... + + def draw(self) -> None: ... + def drawHumanReadable(self) -> None: ... + def rect(self, x, y, w, h) -> None: ... + def annotate(self, x, y, text, fontName, fontSize, anchor: str = "middle") -> None: ... + +class MultiWidthBarcode(Barcode): + barHeight: Incomplete + def computeSize(self, *args) -> None: ... + def draw(self) -> None: ... + +class I2of5(Barcode): + patterns: Incomplete + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + bearerBox: bool + quiet: int + lquiet: Incomplete + rquiet: Incomplete + stop: int + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class MSI(Barcode): + patterns: Incomplete + stop: int + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + quiet: int + lquiet: Incomplete + rquiet: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Codabar(Barcode): + patterns: Incomplete + values: Incomplete + chars: Incomplete + stop: int + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + quiet: int + lquiet: Incomplete + rquiet: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + Valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Code11(Barcode): + chars: str + patterns: Incomplete + values: Incomplete + stop: int + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + quiet: int + lquiet: Incomplete + rquiet: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + Valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi b/stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi new file mode 100644 index 000000000000..480095e85683 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode +from reportlab.graphics.widgetbase import Widget + +class _DMTXCheck: + @classmethod + def pylibdmtx_check(cls) -> None: ... + +class DataMatrix(Barcode, _DMTXCheck): + color: Incomplete + bgColor: Incomplete + def __init__(self, value: str = "", **kwds) -> None: ... + + @property + def value(self): ... + @value.setter + def value(self, v) -> None: ... + + @property + def size(self): ... + @size.setter + def size(self, v) -> None: ... + + @property + def border(self): ... + @border.setter + def border(self, v) -> None: ... + + @property + def x(self): ... + @x.setter + def x(self, v) -> None: ... + + @property + def y(self): ... + @y.setter + def y(self, v) -> None: ... + + @property + def cellSize(self): ... + @cellSize.setter + def cellSize(self, v) -> None: ... + + @property + def encoding(self): ... + @encoding.setter + def encoding(self, v) -> None: ... + + @property + def anchor(self): ... + @anchor.setter + def anchor(self, v) -> None: ... + + def recalc(self) -> None: ... + @property + def matrix(self): ... + @property # type: ignore[misc] # TODO: for mypy < 1.16 + def width(self): ... # type: ignore[override] + @property # type: ignore[misc] # TODO: for mypy < 1.16 + def height(self): ... # type: ignore[override] + @property + def cellWidth(self): ... + @property + def cellHeight(self): ... + def draw(self) -> None: ... + +class DataMatrixWidget(Widget, _DMTXCheck): + codeName: str + value: Incomplete + def __init__(self, value: str = "Hello Cruel World!", **kwds) -> None: ... + def rect(self, x, y, w, h, fill: int = 1, stroke: int = 0) -> None: ... + def saveState(self, *args, **kwds) -> None: ... + restoreState = saveState + setStrokeColor = saveState + def setFillColor(self, c) -> None: ... + def draw(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi b/stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi new file mode 100644 index 000000000000..18b4045e005f --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.lib.attrmap import * + +class Ean13BarcodeWidget(PlotArea): + codeName: str + barHeight: Incomplete + barWidth: Incomplete + humanReadable: int + quiet: int + rquiet: Incomplete + lquiet: Incomplete + fontSize: int + fontName: str + textColor: Incomplete + barFillColor: Incomplete + barStrokeColor: Incomplete + barStrokeWidth: int + x: int + y: int + value: Incomplete + def __init__(self, value: str = "123456789012", **kw) -> None: ... + @property + def width(self): ... # type: ignore[override] + def wrap(self, aW, aH): ... + def draw(self): ... + +class Ean8BarcodeWidget(Ean13BarcodeWidget): + codeName: str + +class UPCA(Ean13BarcodeWidget): + codeName: str + +class Ean5BarcodeWidget(Ean13BarcodeWidget): + codeName: str + def draw(self): ... + +class ISBNBarcodeWidget(Ean13BarcodeWidget): + codeName: str + def draw(self): ... + +__all__ = ("Ean13BarcodeWidget", "Ean8BarcodeWidget", "UPCA", "Ean5BarcodeWidget", "ISBNBarcodeWidget") diff --git a/stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi b/stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi new file mode 100644 index 000000000000..e017b1bba63b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class ECC200DataMatrix(Barcode): + barWidth: int + row_modules: int + col_modules: int + row_regions: int + col_regions: int + cw_data: int + cw_ecc: int + row_usable_modules: Incomplete + col_usable_modules: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + valid: int + validated: Incomplete + def validate(self) -> None: ... + encoded: Incomplete + def encode(self): ... + def computeSize(self, *args) -> None: ... + def draw(self) -> None: ... + +__all__ = ("ECC200DataMatrix",) diff --git a/stubs/reportlab/reportlab/graphics/barcode/fourstate.pyi b/stubs/reportlab/reportlab/graphics/barcode/fourstate.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/reportlab/reportlab/graphics/barcode/lto.pyi b/stubs/reportlab/reportlab/graphics/barcode/lto.pyi new file mode 100644 index 000000000000..dde1e45e2e4a --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/lto.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.code39 import Standard39 + +class BaseLTOLabel(Standard39): + LABELWIDTH: Incomplete + LABELHEIGHT: Incomplete + LABELROUND: Incomplete + CODERATIO: float + CODENOMINALWIDTH: Incomplete + CODEBARHEIGHT: Incomplete + CODEBARWIDTH: Incomplete + CODEGAP = CODEBARWIDTH # pyrefly: ignore [unknown-name] + CODELQUIET: Incomplete + CODERQUIET: Incomplete + height: Incomplete + border: Incomplete + label: Incomplete + def __init__( + self, prefix: str = "", number=None, subtype: str = "1", border=None, checksum: bool = False, availheight=None + ) -> None: ... + def drawOn(self, canvas, x, y) -> None: ... + +class VerticalLTOLabel(BaseLTOLabel): + LABELFONT: Incomplete + BLOCKWIDTH: Incomplete + BLOCKHEIGHT: Incomplete + LINEWIDTH: float + NBBLOCKS: int + COLORSCHEME: Incomplete + colored: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def drawOn(self, canvas, x, y) -> None: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/qr.pyi b/stubs/reportlab/reportlab/graphics/barcode/qr.pyi new file mode 100644 index 000000000000..817ba00d72e0 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/qr.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from typing import type_check_only + +from reportlab.graphics.shapes import Rect +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.validators import Validator +from reportlab.platypus.flowables import Flowable + +__all__ = ["QrCodeWidget"] + +@type_check_only +class _isLevel(Validator): + def test(self, x): ... + +isLevel: _isLevel + +@type_check_only +class _isUnicodeOrQRList(Validator): + def test(self, x): ... + def normalize(self, x): ... + +isUnicodeOrQRList: _isUnicodeOrQRList + +class SRect(Rect): + def __init__(self, x, y, width, height, fillColor=...) -> None: ... + +class QrCodeWidget(Widget): + codeName: str + x: int + y: int + barFillColor: Incomplete + barStrokeColor: Incomplete + barStrokeWidth: int + barHeight: Incomplete + barWidth: Incomplete + barBorder: int + barLevel: str + qrVersion: Incomplete + value: Incomplete + def __init__(self, value: str = "Hello World", **kw) -> None: ... + def addData(self, value) -> None: ... + def draw(self): ... + +class QrCode(Flowable): + height: Incomplete + width: Incomplete + qrBorder: int + qrLevel: str + qrVersion: Incomplete + value: Incomplete + qr: Incomplete + def __init__(self, value=None, **kw) -> None: ... + def addData(self, value) -> None: ... + def draw(self) -> None: ... + def rect(self, x, y, w, h) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi b/stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi new file mode 100644 index 000000000000..5f4d2bb6f47b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi @@ -0,0 +1,202 @@ +from _typeshed import Incomplete + +unicode = str + +class QR: + valid: Incomplete + bits: Incomplete + group: int + data: Incomplete + def __init__(self, data) -> None: ... + def __len__(self) -> int: ... + @property + def bitlength(self): ... + def getLengthBits(self, ver): ... + def getLength(self): ... + def write_header(self, buffer, version) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRNumber(QR): + valid: Incomplete + chars: str + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + +class QRAlphaNum(QR): + valid: Incomplete + chars: str + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + +class QR8bitByte(QR): + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRKanji(QR): + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def unicode_to_qrkanji(self, data): ... + def write(self, buffer, version) -> None: ... + +class QRHanzi(QR): + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def unicode_to_qrhanzi(self, data): ... + def write_header(self, buffer, version) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRECI(QR): + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRStructAppend(QR): + mode: int + lengthbits: Incomplete + part: Incomplete + total: Incomplete + parity: Incomplete + def __init__(self, part, total, parity) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRFNC1First(QR): + mode: int + lengthbits: Incomplete + def __init__(self) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRFNC1Second(QR): + valid: Incomplete + mode: int + lengthbits: Incomplete + def write(self, buffer, version) -> None: ... + +class QRCode: + version: Incomplete + errorCorrectLevel: Incomplete + modules: Incomplete + moduleCount: int + dataCache: Incomplete + dataList: Incomplete + def __init__(self, version, errorCorrectLevel) -> None: ... + def addData(self, data) -> None: ... + def isDark(self, row, col): ... + def getModuleCount(self): ... + def calculate_version(self): ... + def make(self) -> None: ... + def makeImpl(self, test, maskPattern) -> None: ... + def setupPositionProbePattern(self, row, col) -> None: ... + def getBestMaskPattern(self): ... + def setupTimingPattern(self) -> None: ... + def setupPositionAdjustPattern(self) -> None: ... + def setupTypeNumber(self, test) -> None: ... + def setupTypeInfo(self, test, maskPattern) -> None: ... + def dataPosIterator(self): ... + def dataBitIterator(self, data): ... + def mapData(self, data, maskPattern) -> None: ... + PAD0: int + PAD1: int + @staticmethod + def createData(version, errorCorrectLevel, dataList): ... + @staticmethod + def createBytes(buffer, rsBlocks): ... + +class QRErrorCorrectLevel: + L: int + M: int + Q: int + H: int + +class QRMaskPattern: + PATTERN000: int + PATTERN001: int + PATTERN010: int + PATTERN011: int + PATTERN100: int + PATTERN101: int + PATTERN110: int + PATTERN111: int + +class QRUtil: + PATTERN_POSITION_TABLE: Incomplete + G15: Incomplete + G18: Incomplete + G15_MASK: Incomplete + @staticmethod + def getBCHTypeInfo(data): ... + @staticmethod + def getBCHTypeNumber(data): ... + @staticmethod + def getBCHDigit(data): ... + @staticmethod + def getPatternPosition(version): ... + maskPattern: Incomplete + @classmethod + def getMask(cls, maskPattern): ... + @staticmethod + def getErrorCorrectPolynomial(errorCorrectLength): ... + @classmethod + def maskScoreRule1vert(cls, modules): ... + @classmethod + def maskScoreRule2(cls, modules): ... + @classmethod + def maskScoreRule3hor(cls, modules, pattern=...): ... + @classmethod + def maskScoreRule4(cls, modules): ... + @classmethod + def getLostPoint(cls, qrCode): ... + +class QRMath: + @staticmethod + def glog(n): ... + @staticmethod + def gexp(n): ... + +EXP_TABLE: Incomplete +LOG_TABLE: Incomplete + +class QRPolynomial: + num: Incomplete + def __init__(self, num, shift) -> None: ... + def get(self, index): ... + def getLength(self): ... + def multiply(self, e): ... + def mod(self, e): ... + +class QRRSBlock: + RS_BLOCK_TABLE: Incomplete + totalCount: Incomplete + dataCount: Incomplete + def __init__(self, totalCount, dataCount) -> None: ... + @staticmethod + def getRSBlocks(version, errorCorrectLevel): ... + @staticmethod + def getRsBlockTable(version, errorCorrectLevel): ... + +class QRBitBuffer: + buffer: Incomplete + length: int + def __init__(self) -> None: ... + def get(self, index): ... + def put(self, num, length) -> None: ... + def getLengthInBits(self): ... + def putBit(self, bit) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/usps.pyi b/stubs/reportlab/reportlab/graphics/barcode/usps.pyi new file mode 100644 index 000000000000..455b99df3781 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/usps.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class FIM(Barcode): + barWidth: Incomplete + spaceWidth: Incomplete + barHeight: Incomplete + rquiet: Incomplete + lquiet: Incomplete + quiet: int + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: str + def validate(self): ... + decomposed: str + def decompose(self): ... + def computeSize(self) -> None: ... + def draw(self) -> None: ... + +class POSTNET(Barcode): + quiet: int + shortHeight: Incomplete + barHeight: Incomplete + barWidth: Incomplete + spaceWidth: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + validated: str + valid: int + def validate(self): ... + encoded: str + def encode(self): ... + decomposed: str + def decompose(self): ... + def computeSize(self) -> None: ... + def draw(self) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi b/stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi new file mode 100644 index 000000000000..069b94a2f30c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi @@ -0,0 +1,103 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class USPS_4State(Barcode): + tops: Incomplete + bottoms: Incomplete + dimensions: Incomplete + def __init__(self, value: str = "01234567094987654321", routing: str = "", **kwd) -> None: ... + @staticmethod + def scale(kind, D, s): ... + + @property + def tracking(self): ... + @tracking.setter + def tracking(self, tracking) -> None: ... + + @property + def routing(self): ... + @routing.setter + def routing(self, routing) -> None: ... + + @property + def widthSize(self): ... + @widthSize.setter + def widthSize(self, value) -> None: ... + + @property + def heightSize(self): ... + @heightSize.setter + def heightSize(self, value) -> None: ... + + @property + def fontSize(self): ... + @fontSize.setter + def fontSize(self, value) -> None: ... + + @property + def humanReadable(self): ... + @humanReadable.setter + def humanReadable(self, value) -> None: ... + + @property + def binary(self): ... + @property + def codewords(self): ... + @property + def table1(self): ... + @property + def table2(self): ... + @property + def characters(self): ... + @property + def barcodes(self): ... + table4: Incomplete + @property + def horizontalClearZone(self): ... + @property + def verticalClearZone(self): ... + + @property + def barWidth(self): ... + @barWidth.setter + def barWidth(self, value) -> None: ... + + @property + def pitch(self): ... + @pitch.setter + def pitch(self, value) -> None: ... + + @property + def barHeight(self): ... + @barHeight.setter + def barHeight(self, value) -> None: ... + + @property + def widthScale(self): ... + @property + def heightScale(self): ... + + @property + def width(self): ... + @width.setter + def width(self, v) -> None: ... + + @property + def height(self): ... + @height.setter + def height(self, v) -> None: ... + + def computeSize(self) -> None: ... + def wrap(self, aW, aH): ... + def draw(self) -> None: ... + + @property + def value(self): ... + @value.setter + def value(self, value) -> None: ... + + def drawHumanReadable(self) -> None: ... + def annotate(self, x, y, text, fontName, fontSize, anchor: str = "middle") -> None: ... + +__all__ = ("USPS_4State",) diff --git a/stubs/reportlab/reportlab/graphics/barcode/widgets.pyi b/stubs/reportlab/reportlab/graphics/barcode/widgets.pyi new file mode 100644 index 000000000000..2ea5c9d53937 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/widgets.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.lib.colors import black + +class _BarcodeWidget(PlotArea): + textColor = black + barFillColor = black + barStrokeColor: Incomplete + barStrokeWidth: int + x: int + def __init__(self, _value: str = "", **kw) -> None: ... + def rect(self, x, y, w, h, **kw) -> None: ... + canv: Incomplete + def draw(self): ... + def annotate(self, x, y, text, fontName, fontSize, anchor: str = "middle") -> None: ... + +class BarcodeI2of5(_BarcodeWidget): + codeName: Final = "I2of5" + def __init__(self, **kw) -> None: ... + +class BarcodeCode128(_BarcodeWidget): + codeName: Final = "Code128" + def __init__(self, **kw) -> None: ... + +class BarcodeStandard93(_BarcodeWidget): + codeName: Final = "Standard93" + def __init__(self, **kw) -> None: ... + +class BarcodeExtended93(_BarcodeWidget): + codeName: Final = "Extended93" + def __init__(self, **kw) -> None: ... + +class BarcodeStandard39(_BarcodeWidget): + codeName: Final = "Standard39" + def __init__(self, **kw) -> None: ... + +class BarcodeExtended39(_BarcodeWidget): + codeName: Final = "Extended39" + def __init__(self, **kw) -> None: ... + +class BarcodeMSI(_BarcodeWidget): + codeName: Final = "MSI" + def __init__(self, **kw) -> None: ... + +class BarcodeCodabar(_BarcodeWidget): + codeName: Final = "Codabar" + def __init__(self, **kw) -> None: ... + +class BarcodeCode11(_BarcodeWidget): + codeName: Final = "Code11" + def __init__(self, **kw) -> None: ... + +class BarcodeFIM(_BarcodeWidget): + codeName: Final = "FIM" + def __init__(self, **kw) -> None: ... + +class BarcodePOSTNET(_BarcodeWidget): + codeName: Final = "POSTNET" + def __init__(self, **kw) -> None: ... + +class BarcodeUSPS_4State(_BarcodeWidget): + codeName: Final = "USPS_4State" + def __init__(self, **kw) -> None: ... + +__all__ = ( + "BarcodeI2of5", + "BarcodeCode128", + "BarcodeStandard93", + "BarcodeExtended93", + "BarcodeStandard39", + "BarcodeExtended39", + "BarcodeMSI", + "BarcodeCodabar", + "BarcodeCode11", + "BarcodeFIM", + "BarcodePOSTNET", + "BarcodeUSPS_4State", +) diff --git a/stubs/reportlab/reportlab/graphics/charts/__init__.pyi b/stubs/reportlab/reportlab/graphics/charts/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/graphics/charts/areas.pyi b/stubs/reportlab/reportlab/graphics/charts/areas.pyi new file mode 100644 index 000000000000..018cf3518116 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/areas.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget + +__version__: Final[str] + +class PlotArea(Widget): + x: int + y: int + height: int + width: int + strokeColor: Incomplete + strokeWidth: int + fillColor: Incomplete + background: Incomplete + debug: int + def __init__(self) -> None: ... + def makeBackground(self): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/axes.pyi b/stubs/reportlab/reportlab/graphics/charts/axes.pyi new file mode 100644 index 000000000000..51274804d9e4 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/axes.pyi @@ -0,0 +1,205 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.textlabels import PMVLabel +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import Validator + +__version__: Final[str] + +class AxisLabelAnnotation: + def __init__(self, v, **kwds) -> None: ... + def __call__(self, axis): ... + +class AxisLineAnnotation: + def __init__(self, v, **kwds) -> None: ... + def __call__(self, axis): ... + +class AxisBackgroundAnnotation: + def __init__(self, colors, **kwds) -> None: ... + def __call__(self, axis): ... + +class TickLU: + accuracy: Incomplete + T: Incomplete + def __init__(self, *T, **kwds) -> None: ... + def __contains__(self, t) -> bool: ... + def __getitem__(self, t): ... + +class _AxisG(Widget): + def makeGrid(self, g, dim=None, parent=None, exclude=[]) -> None: ... + def getGridDims(self, start=None, end=None): ... + @property + def isYAxis(self): ... + @property + def isXAxis(self): ... + def addAnnotations(self, g, A=None) -> None: ... + def draw(self): ... + +class CALabel(PMVLabel): + def __init__(self, **kw) -> None: ... + +class CategoryAxis(_AxisG): + visible: int + visibleAxis: int + visibleTicks: int + visibleLabels: int + visibleGrid: int + drawGridLast: bool + strokeWidth: int + strokeColor: Incomplete + strokeDashArray: Incomplete + gridStrokeLineJoin: Incomplete + gridStrokeLineCap: Incomplete + gridStrokeMiterLimit: Incomplete + gridStrokeWidth: float + gridStrokeColor: Incomplete + gridStrokeDashArray: Incomplete + gridStart: Incomplete + strokeLineJoin: Incomplete + strokeLineCap: Incomplete + strokeMiterLimit: Incomplete + labels: Incomplete + categoryNames: Incomplete + joinAxis: Incomplete + joinAxisPos: Incomplete + joinAxisMode: Incomplete + labelAxisMode: str + reverseDirection: int + style: str + tickShift: int + loPad: int + hiPad: int + loLLen: int + hiLLen: int + def __init__(self) -> None: ... + def setPosition(self, x, y, length) -> None: ... + def configure(self, multiSeries, barWidth=None) -> None: ... + def scale(self, idx): ... + def midScale(self, idx): ... + +class _XTicks: + @property + def actualTickStrokeWidth(self): ... + @property + def actualTickStrokeColor(self): ... + def makeTicks(self): ... + +class _YTicks(_XTicks): + def makeTicks(self): ... + +class XCategoryAxis(_XTicks, CategoryAxis): + tickUp: int + tickDown: int + def __init__(self) -> None: ... + categoryNames: Incomplete + def demo(self): ... + def joinToAxis(self, yAxis, mode: str = "bottom", pos=None) -> None: ... + def loScale(self, idx): ... + def makeAxis(self): ... + def makeTickLabels(self): ... + +class YCategoryAxis(_YTicks, CategoryAxis): + tickLeft: int + tickRight: int + def __init__(self) -> None: ... + categoryNames: Incomplete + def demo(self): ... + def joinToAxis(self, xAxis, mode: str = "left", pos=None) -> None: ... + def loScale(self, idx): ... + def makeAxis(self): ... + def makeTickLabels(self): ... + +class TickLabeller: + def __call__(self, axis, value): ... + +class ValueAxis(_AxisG): + def __init__(self, **kw) -> None: ... + def setPosition(self, x, y, length) -> None: ... + def configure(self, dataSeries) -> None: ... + def makeTickLabels(self): ... + def scale(self, value): ... + +class XValueAxis(_XTicks, ValueAxis): + tickUp: int + tickDown: int + joinAxis: Incomplete + joinAxisMode: Incomplete + joinAxisPos: Incomplete + def __init__(self, **kw) -> None: ... + def demo(self): ... + def joinToAxis(self, yAxis, mode: str = "bottom", pos=None) -> None: ... + def makeAxis(self): ... + +def parseDayAndMonth(dmstr): ... + +class _isListOfDaysAndMonths(Validator): + def test(self, x): ... + def normalize(self, x): ... + +isListOfDaysAndMonths: Incomplete + +class NormalDateXValueAxis(XValueAxis): + bottomAxisLabelSlack: float + niceMonth: int + forceEndDate: int + forceFirstDate: int + forceDatesEachYear: Incomplete + dailyFreq: int + xLabelFormat: str + dayOfWeekName: Incomplete + monthName: Incomplete + specialTickClear: int + valueSteps: Incomplete + def __init__(self, **kw) -> None: ... + def configure(self, data) -> None: ... + +class YValueAxis(_YTicks, ValueAxis): + tickRight: int + tickLeft: int + joinAxis: Incomplete + joinAxisMode: Incomplete + joinAxisPos: Incomplete + def __init__(self) -> None: ... + def demo(self): ... + def joinToAxis(self, xAxis, mode: str = "left", pos=None) -> None: ... + def makeAxis(self): ... + +class TimeValueAxis: + labelTextFormat: Incomplete + def __init__(self, *args, **kwds) -> None: ... + def timeLabelTextFormatter(self, val): ... + +class XTimeValueAxis(TimeValueAxis, XValueAxis): + def __init__(self, *args, **kwds) -> None: ... + +class AdjYValueAxis(YValueAxis): + requiredRange: int + leftAxisPercent: int + leftAxisOrigShiftIPC: float + leftAxisOrigShiftMin: int + leftAxisSkipLL0: int + valueSteps: Incomplete + def __init__(self, **kw) -> None: ... + +class LogValueAxis(ValueAxis): ... + +class LogAxisTickLabeller(TickLabeller): + def __call__(self, axis, value): ... + +class LogAxisTickLabellerS(TickLabeller): + def __call__(self, axis, value): ... + +class LogAxisLabellingSetup: + labels: Incomplete + labelTextFormat: Incomplete + def __init__(self) -> None: ... + +class LogXValueAxis(LogValueAxis, LogAxisLabellingSetup, XValueAxis): + def __init__(self) -> None: ... + def scale(self, value): ... + +class LogYValueAxis(LogValueAxis, LogAxisLabellingSetup, YValueAxis): + def __init__(self) -> None: ... + def scale(self, value): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/barcharts.pyi b/stubs/reportlab/reportlab/graphics/charts/barcharts.pyi new file mode 100644 index 000000000000..303ca4bc20c1 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/barcharts.pyi @@ -0,0 +1,105 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.widgetbase import PropHolder + +__version__: Final[str] + +class BarChartProperties(PropHolder): + strokeColor: Incomplete + fillColor: Incomplete + strokeWidth: float + symbol: Incomplete + strokeDashArray: Incomplete + def __init__(self) -> None: ... + +class BarChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + categoryAxis: Incomplete + valueAxis: Incomplete + barSpacing: int + reversePlotOrder: int + data: Incomplete + useAbsolute: int + barWidth: int + groupSpacing: int + barLabels: Incomplete + barLabelFormat: Incomplete + barLabelArray: Incomplete + bars: Incomplete + naLabel: Incomplete + zIndexOverrides: Incomplete + def __init__(self) -> None: ... + def demo(self): ... + def getSeriesOrder(self) -> None: ... + def calcBarPositions(self) -> None: ... + def makeBars(self): ... + def draw(self): ... + +class VerticalBarChart(BarChart): ... +class HorizontalBarChart(BarChart): ... + +class _FakeGroup: + def __init__(self, cmp=None) -> None: ... + def add(self, what) -> None: ... + def value(self): ... + def sort(self) -> None: ... + +class BarChart3D(BarChart): + theta_x: float + theta_y: float + zDepth: Incomplete + zSpace: Incomplete + def calcBarPositions(self) -> None: ... + def makeBars(self): ... + +class VerticalBarChart3D(BarChart3D, VerticalBarChart): ... +class HorizontalBarChart3D(BarChart3D, HorizontalBarChart): ... + +def sampleV0a(): ... +def sampleV0b(): ... +def sampleV0c(): ... +def sampleV1(): ... +def sampleV2a(): ... +def sampleV2b(): ... +def sampleV2c(): ... +def sampleV3(): ... +def sampleV4a(): ... +def sampleV4b(): ... +def sampleV4c(): ... +def sampleV4d(): ... + +dataSample5: Incomplete + +def sampleV5a(): ... +def sampleV5b(): ... +def sampleV5c1(): ... +def sampleV5c2(): ... +def sampleV5c3(): ... +def sampleV5c4(): ... +def sampleH0a(): ... +def sampleH0b(): ... +def sampleH0c(): ... +def sampleH1(): ... +def sampleH2a(): ... +def sampleH2b(): ... +def sampleH2c(): ... +def sampleH3(): ... +def sampleH4a(): ... +def sampleH4b(): ... +def sampleH4c(): ... +def sampleH4d(): ... +def sampleH5a(): ... +def sampleH5b(): ... +def sampleH5c1(): ... +def sampleH5c2(): ... +def sampleH5c3(): ... +def sampleH5c4(): ... +def sampleSymbol1(): ... +def sampleStacked1(): ... + +class SampleH5c4(Drawing): + def __init__(self, width: int = 400, height: int = 200, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/dotbox.pyi b/stubs/reportlab/reportlab/graphics/charts/dotbox.pyi new file mode 100644 index 000000000000..d67fdfe982b9 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/dotbox.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +class DotBox(Widget): + xlabels: Incomplete + ylabels: Incomplete + labelFontName: str + labelFontSize: int + labelOffset: int + strokeWidth: float + gridDivWidth: Incomplete + gridColor: Incomplete + dotDiameter: Incomplete + dotColor: Incomplete + dotXPosition: int + dotYPosition: int + x: int + y: int + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/doughnut.pyi b/stubs/reportlab/reportlab/graphics/charts/doughnut.pyi new file mode 100644 index 000000000000..414bb8d5ae39 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/doughnut.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.piecharts import AbstractPieChart, WedgeProperties +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class SectorProperties(WedgeProperties): ... + +class Doughnut(AbstractPieChart): + x: int + y: int + width: int + height: int + data: Incomplete + labels: Incomplete + startAngle: int + direction: str + simpleLabels: int + checkLabelOverlap: int + sideLabels: int + innerRadiusFraction: Incomplete + slices: Incomplete + angleRange: int + def __init__(self, *, angleRange: int = 360, **kwds) -> None: ... + def demo(self): ... + def normalizeData(self, data=None): ... + def makeSectors(self): ... + def draw(self): ... + +def sample1(): ... +def sample2(): ... +def sample3(): ... +def sample4(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/legends.pyi b/stubs/reportlab/reportlab/graphics/charts/legends.pyi new file mode 100644 index 000000000000..ec3b453fba10 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/legends.pyi @@ -0,0 +1,101 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import PropHolder, Widget +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class SubColProperty(PropHolder): + dividerLines: int + +class LegendCallout: + def __call__(self, legend, g, thisx, y, colName) -> None: ... + +class LegendSwatchCallout(LegendCallout): + def __call__(self, legend, g, thisx, y, i, colName, swatch) -> None: ... # type: ignore[override] + +class LegendColEndCallout(LegendCallout): + def __call__(self, legend, g, x, xt, y, width, lWidth) -> None: ... # type: ignore[override] + +class Legend(Widget): + x: int + y: int + alignment: str + deltax: int + deltay: int + autoXPadding: int + autoYPadding: int + dx: int + dy: int + swdx: int + swdy: int + dxTextSpace: int + columnMaximum: int + colorNamePairs: Incomplete + fontName: Incomplete + fontSize: Incomplete + leading: Incomplete + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: Incomplete + swatchMarker: Incomplete + boxAnchor: str + yGap: int + variColumn: int + dividerLines: int + dividerWidth: float + dividerDashArray: Incomplete + dividerColor: Incomplete + dividerOffsX: Incomplete + dividerOffsY: int + colEndCallout: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + def demo(self): ... + +class TotalAnnotator(LegendColEndCallout): + lText: Incomplete + rText: Incomplete + fontName: Incomplete + fontSize: Incomplete + fillColor: Incomplete + dy: Incomplete + dx: Incomplete + dly: Incomplete + dlx: Incomplete + strokeWidth: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + def __init__( + self, + lText: str = "Total", + rText: str = "0.0", + fontName="Times-Roman", + fontSize: int = 10, + fillColor=..., + strokeWidth: float = 0.5, + strokeColor=..., + strokeDashArray=None, + dx: int = 0, + dy: int = 0, + dly: int = 0, + dlx=(0, 0), + ) -> None: ... + def __call__(self, legend, g, x, xt, y, width, lWidth) -> None: ... # type: ignore[override] + +class LineSwatch(Widget): + x: int + y: int + width: int + height: int + strokeColor: Incomplete + strokeDashArray: Incomplete + strokeWidth: int + def __init__(self) -> None: ... + def draw(self): ... + +class LineLegend(Legend): + dx: int + dy: int + def __init__(self) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/linecharts.pyi b/stubs/reportlab/reportlab/graphics/charts/linecharts.pyi new file mode 100644 index 000000000000..16d1c4bf69e7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/linecharts.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.widgetbase import PropHolder +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class LineChartProperties(PropHolder): ... + +class AbstractLineChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + +class LineChart(AbstractLineChart): ... + +class HorizontalLineChart(LineChart): + strokeColor: Incomplete + fillColor: Incomplete + categoryAxis: Incomplete + valueAxis: Incomplete + data: Incomplete + categoryNames: Incomplete + lines: Incomplete + useAbsolute: int + groupSpacing: int + lineLabels: Incomplete + lineLabelFormat: Incomplete + lineLabelArray: Incomplete + lineLabelNudge: int + joinedLines: int + inFill: int + reversePlotOrder: int + def __init__(self) -> None: ... + def demo(self): ... + def calcPositions(self) -> None: ... + def drawLabel(self, G, rowNo, colNo, x, y) -> None: ... + def makeLines(self): ... + def draw(self): ... + +class _FakeGroup: + def __init__(self) -> None: ... + def add(self, what) -> None: ... + def value(self): ... + def sort(self) -> None: ... + +class HorizontalLineChart3D(HorizontalLineChart): + theta_x: float + theta_y: float + zDepth: int + zSpace: int + def calcPositions(self) -> None: ... + def makeLines(self): ... + +class VerticalLineChart(LineChart): ... + +def sample1(): ... + +class SampleHorizontalLineChart(HorizontalLineChart): + def demo(self): ... + def makeBackground(self): ... + +def sample1a(): ... +def sample2(): ... +def sample3(): ... +def sampleCandleStick(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/lineplots.pyi b/stubs/reportlab/reportlab/graphics/charts/lineplots.pyi new file mode 100644 index 000000000000..77c6ad29d27d --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/lineplots.pyi @@ -0,0 +1,121 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.linecharts import AbstractLineChart +from reportlab.graphics.charts.utils import * +from reportlab.graphics.shapes import Polygon, _SetKeyWordArgs +from reportlab.graphics.widgetbase import PropHolder +from reportlab.graphics.widgets.grids import ShadedPolygon +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class LinePlotProperties(PropHolder): ... + +class InFillValue(int): + yValue: Incomplete + def __new__(cls, v, yValue=None): ... + +class Shader(_SetKeyWordArgs): + def shade(self, lp, g, rowNo, rowColor, row) -> None: ... + +class NoFiller: + def fill(self, lp, g, rowNo, rowColor, points) -> None: ... + +class Filler: + __dict__: Incomplete + def __init__(self, **kw) -> None: ... + def fill(self, lp, g, rowNo, rowColor, points) -> None: ... + +class ShadedPolyFiller(Filler, ShadedPolygon): ... +class PolyFiller(Filler, Polygon): ... + +class LinePlot(AbstractLineChart): + reversePlotOrder: int + xValueAxis: Incomplete + yValueAxis: Incomplete + data: Incomplete + lines: Incomplete + lineLabels: Incomplete + lineLabelFormat: Incomplete + lineLabelArray: Incomplete + lineLabelNudge: int + annotations: Incomplete + behindAxes: int + gridFirst: int + def __init__(self) -> None: ... + + @property + def joinedLines(self): ... + @joinedLines.setter + def joinedLines(self, v) -> None: ... + + def demo(self): ... + def calcPositions(self) -> None: ... + def drawLabel(self, G, rowNo, colNo, x, y) -> None: ... + def makeLines(self): ... + def draw(self): ... + def addCrossHair(self, name, xv, yv, strokeColor=..., strokeWidth: int = 1, beforeLines: bool = True): ... + +class LinePlot3D(LinePlot): + theta_x: float + theta_y: float + zDepth: int + zSpace: int + def calcPositions(self) -> None: ... + def makeLines(self): ... + +class SimpleTimeSeriesPlot(LinePlot): + xValueAxis: Incomplete + yValueAxis: Incomplete + data: Incomplete + def __init__(self) -> None: ... + +class GridLinePlot(SimpleTimeSeriesPlot): + scaleFactor: Incomplete + background: Incomplete + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... + +class AreaLinePlot(LinePlot): + reversePlotOrder: int + data: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class SplitLinePlot(AreaLinePlot): + xValueAxis: Incomplete + yValueAxis: Incomplete + data: Incomplete + def __init__(self) -> None: ... + +class ScatterPlot(LinePlot): + width: int + height: int + outerBorderOn: int + outerBorderColor: Incomplete + background: Incomplete + xLabel: str + yLabel: str + data: Incomplete + joinedLines: int + leftPadding: int + rightPadding: int + topPadding: int + bottomPadding: int + x: Incomplete + y: Incomplete + lineLabelFormat: str + lineLabelNudge: int + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... + +def sample1a(): ... +def sample1b(): ... +def sample1c(): ... +def preprocessData(series): ... +def sample2(): ... +def sampleFillPairedData(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/markers.pyi b/stubs/reportlab/reportlab/graphics/charts/markers.pyi new file mode 100644 index 000000000000..7c7c8a6750cd --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/markers.pyi @@ -0,0 +1,10 @@ +from typing import Final + +__version__: Final[str] + +def makeEmptySquare(x, y, size, color): ... +def makeFilledSquare(x, y, size, color): ... +def makeFilledDiamond(x, y, size, color): ... +def makeEmptyCircle(x, y, size, color): ... +def makeFilledCircle(x, y, size, color): ... +def makeSmiley(x, y, size, color): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/piecharts.pyi b/stubs/reportlab/reportlab/graphics/charts/piecharts.pyi new file mode 100644 index 000000000000..aa15c8d58846 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/piecharts.pyi @@ -0,0 +1,183 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.widgetbase import PropHolder +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class WedgeLabel(Label): ... + +class WedgeProperties(PropHolder): + strokeWidth: int + fillColor: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + strokeLineJoin: int + strokeLineCap: int + strokeMiterLimit: int + popout: int + fontName: Incomplete + fontSize: Incomplete + fontColor: Incomplete + labelRadius: float + label_dx: int + label_text: Incomplete + label_topPadding: int + label_boxAnchor: str + label_boxStrokeColor: Incomplete + label_boxStrokeWidth: float + label_boxFillColor: Incomplete + label_strokeColor: Incomplete + label_strokeWidth: float + label_leading: Incomplete + label_textAnchor: str + label_simple_pointer: int + label_visible: int + label_pointer_strokeColor: Incomplete + label_pointer_strokeWidth: float + label_pointer_elbowLength: int + label_pointer_edgePad: int + label_pointer_piePad: int + visible: int + shadingKind: Incomplete + shadingAmount: float + shadingAngle: float + shadingDirection: str + def __init__(self) -> None: ... + +class AbstractPieChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + +def boundsOverlap(P, Q): ... +def findOverlapRun(B, wrap: int = 1): ... +def fixLabelOverlaps(L, sideLabels: bool = False, mult0: float = 1.0) -> None: ... +def intervalIntersection(A, B): ... +def theta0(data, direction): ... + +class AngleData(float): + def __new__(cls, angle, data): ... + +class Pie(AbstractPieChart): + other_threshold: Incomplete + x: int + y: int + width: int + height: int + data: Incomplete + labels: Incomplete + startAngle: int + direction: str + simpleLabels: int + checkLabelOverlap: int + pointerLabelMode: Incomplete + sameRadii: bool + orderMode: str + xradius: Incomplete + sideLabels: int + sideLabelsOffset: float + slices: Incomplete + angleRange: int + def __init__(self, *, angleRange: int = 360, **kwds) -> None: ... + def demo(self): ... + centerx: Incomplete + centery: Incomplete + yradius: Incomplete + lu: Incomplete + ru: Incomplete + def makePointerLabels(self, angles, plMode): ... + def normalizeData(self, keepData: bool = False): ... + def makeAngles(self): ... + def makeWedges(self): ... + def draw(self): ... + +class LegendedPie(Pie): + x: int + y: int + height: int + width: int + data: Incomplete + labels: Incomplete + direction: str + pieAndLegend_colors: Incomplete + legendNumberOffset: int + legendNumberFormat: str + legend_data: Incomplete + legend1: Incomplete + legend_names: Incomplete + leftPadding: int + rightPadding: int + topPadding: int + bottomPadding: int + drawLegend: int + def __init__(self) -> None: ... + def draw(self): ... + def demo(self, drawing=None): ... + +class Wedge3dProperties(PropHolder): + strokeWidth: int + shading: float + visible: int + strokeColorShaded: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + popout: int + fontName: Incomplete + fontSize: Incomplete + fontColor: Incomplete + labelRadius: float + label_dx: int + label_text: Incomplete + label_topPadding: int + label_boxAnchor: str + label_boxStrokeColor: Incomplete + label_boxStrokeWidth: float + label_boxFillColor: Incomplete + label_strokeColor: Incomplete + label_strokeWidth: float + label_leading: Incomplete + label_textAnchor: str + label_visible: int + label_simple_pointer: int + def __init__(self) -> None: ... + +class _SL3D: + lo: Incomplete + hi: Incomplete + mid: Incomplete + not360: Incomplete + def __init__(self, lo, hi) -> None: ... + +class Pie3d(Pie): + perspective: int + depth_3d: int + angle_3d: int + def CX(self, i, d): ... + def CY(self, i, d): ... + def OX(self, i, o, d): ... + def OY(self, i, o, d): ... + def rad_dist(self, a): ... + slices: Incomplete + xradius: Incomplete + width: int + height: int + data: Incomplete + def __init__(self) -> None: ... + dy: Incomplete + def draw(self): ... + def demo(self): ... + +def sample0a(): ... +def sample0b(): ... +def sample1(): ... +def sample2(): ... +def sample3(): ... +def sample4(): ... +def sample5(): ... +def sample6(): ... +def sample7(): ... +def sample8(): ... +def sample9(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/slidebox.pyi b/stubs/reportlab/reportlab/graphics/charts/slidebox.pyi new file mode 100644 index 000000000000..5af8e999ae03 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/slidebox.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +class SlideBox(Widget): + labelFontName: str + labelFontSize: int + labelStrokeColor: Incomplete + labelFillColor: Incomplete + startColor: Incomplete + endColor: Incomplete + numberOfBoxes: int + trianglePosition: int + triangleHeight: Incomplete + triangleWidth: Incomplete + triangleFillColor: Incomplete + triangleStrokeColor: Incomplete + triangleStrokeWidth: float + boxHeight: Incomplete + boxWidth: Incomplete + boxSpacing: Incomplete + boxOutlineColor: Incomplete + boxOutlineWidth: float + leftPadding: int + rightPadding: int + topPadding: int + bottomPadding: int + background: Incomplete + sourceLabelText: str + sourceLabelOffset: Incomplete + sourceLabelFontName: str + sourceLabelFontSize: int + sourceLabelFillColor: Incomplete + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/spider.pyi b/stubs/reportlab/reportlab/graphics/charts/spider.pyi new file mode 100644 index 000000000000..e66e11bb7e8a --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/spider.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.piecharts import WedgeLabel +from reportlab.graphics.widgetbase import PropHolder +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class StrandProperty(PropHolder): + strokeWidth: int + fillColor: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + symbol: Incomplete + symbolSize: int + name: Incomplete + def __init__(self) -> None: ... + +class SpokeProperty(PropHolder): + strokeWidth: float + fillColor: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + visible: int + labelRadius: float + def __init__(self, **kw) -> None: ... + +class SpokeLabel(WedgeLabel): + def __init__(self, **kw) -> None: ... + +class StrandLabel(SpokeLabel): + format: str + dR: int + def __init__(self, **kw) -> None: ... + +class SpiderChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + data: Incomplete + labels: Incomplete + startAngle: int + direction: str + strands: Incomplete + spokes: Incomplete + spokeLabels: Incomplete + strandLabels: Incomplete + x: int + y: int + width: int + height: int + def __init__(self) -> None: ... + def demo(self): ... + def normalizeData(self, outer: float = 0.0): ... + def labelClass(self, kind): ... + def draw(self): ... + +def sample1(): ... +def sample2(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/textlabels.pyi b/stubs/reportlab/reportlab/graphics/charts/textlabels.pyi new file mode 100644 index 000000000000..c7b4fa1bc0d5 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/textlabels.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.utils import CustomDrawChanger +from reportlab.graphics.shapes import Drawing, Group +from reportlab.graphics.widgetbase import PropHolder, Widget +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class Label(Widget): + # TODO: This has more attributes. + x: Incomplete + y: Incomplete + def __init__(self, **kw) -> None: ... + + @property + def padding(self): ... + @padding.setter + def padding(self, p) -> None: ... + + def setText(self, text) -> None: ... + def setOrigin(self, x, y) -> None: ... + def demo(self) -> Drawing: ... + def computeSize(self) -> None: ... + def draw(self) -> Group: ... + +class LabelDecorator: + textAnchor: str + boxAnchor: str + def __init__(self) -> None: ... + def decorate(self, l, L) -> None: ... + def __call__(self, l) -> None: ... + +isOffsetMode: Incomplete + +class LabelOffset(PropHolder): + posMode: str + pos: int + def __init__(self) -> None: ... + +NoneOrInstanceOfLabelOffset: Incomplete + +class PMVLabel(Label): + def __init__(self, **kwds) -> None: ... + +class BarChartLabel(PMVLabel): + lineStrokeWidth: int + lineStrokeColor: Incomplete + fixedStart: Incomplete + nudge: int + def __init__(self, **kwds) -> None: ... + +class NA_Label(BarChartLabel): + text: str + def __init__(self) -> None: ... + +NoneOrInstanceOfNA_Label: Incomplete + +class RedNegativeChanger(CustomDrawChanger): + fillColor: Incomplete + def __init__(self, fillColor=...) -> None: ... + +class XLabel(Label): + ddfKlass: Incomplete + ddf: Incomplete + def __init__(self, *args, **kwds) -> None: ... + def computeSize(self) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/utils.pyi b/stubs/reportlab/reportlab/graphics/charts/utils.pyi new file mode 100644 index 000000000000..5139374047ea --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/utils.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from typing import Final, Literal + +__all__ = ( + "angle2corner", + "angle2dir", + "boxCornerCoords", + "CustomDrawChanger", + "DrawTimeCollector", + "FillPairedData", + "find_good_grid", + "find_interval", + "findNones", + "lineSegmentIntersect", + "makeCircularString", + "maverage", + "mkTimeTuple", + "nextRoundNumber", + "pairFixNones", + "pairMaverage", + "seconds2str", + "str2seconds", + "ticks", + "xyDist", +) +__version__: Final[str] + +def mkTimeTuple(timeString): ... +def str2seconds(timeString): ... +def seconds2str(seconds): ... +def nextRoundNumber(x): ... +def find_interval(lo, hi, I: int = 5): ... +def find_good_grid(lower, upper, n=(4, 5, 6, 7, 8, 9), grid=None): ... +def ticks(lower, upper, n=(4, 5, 6, 7, 8, 9), split: int = 1, percent: int = 0, grid=None, labelVOffset: int = 0): ... +def findNones(data): ... +def pairFixNones(pairs): ... +def maverage(data, n: int = 6): ... +def pairMaverage(data, n: int = 6): ... + +class DrawTimeCollector: + formats: Incomplete + disabled: bool + def __init__(self, formats=["gif"]) -> None: ... + def clear(self) -> None: ... + def record(self, func, node, *args, **kwds) -> None: ... + def __call__(self, node, canvas, renderer) -> None: ... + @staticmethod + def rectDrawTimeCallback(node, canvas, renderer, **kwds): ... + @staticmethod + def transformAndFlatten(A, p): ... + @property + def pmcanv(self): ... + def wedgeDrawTimeCallback(self, node, canvas, renderer, **kwds): ... + def save(self, fnroot) -> None: ... + +def xyDist(xxx_todo_changeme, xxx_todo_changeme1): ... +def lineSegmentIntersect(xxx_todo_changeme2, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5): ... +def makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside: int = 0, G=None, textAnchor: str = "start"): ... + +class CustomDrawChanger: + store: Incomplete + def __init__(self) -> None: ... + def __call__(self, change, obj) -> None: ... + +class FillPairedData(list[Incomplete]): + other: Incomplete + def __init__(self, v, other: int = 0) -> None: ... + +def angle2dir(angle: float) -> Literal["n", "ne", "e", "se", "s", "sw", "w", "nw", "c"]: ... +def angle2corner(angle: float) -> Literal["n", "ne", "e", "se", "s", "sw", "w", "nw", "c"]: ... +def boxCornerCoords(bb: Sequence[float], cn: Literal["n", "ne", "e", "se", "s", "sw", "w", "nw", "c"]) -> tuple[float, float]: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/utils3d.pyi b/stubs/reportlab/reportlab/graphics/charts/utils3d.pyi new file mode 100644 index 000000000000..c54c9e087c1b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/utils3d.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +class _YStrip: + y0: Incomplete + y1: Incomplete + slope: Incomplete + fillColor: Incomplete + fillColorShaded: Incomplete + def __init__(self, y0, y1, slope, fillColor, fillColorShaded, shading: float = 0.1) -> None: ... + +def mod_2pi(radians): ... + +class _Segment: + a: Incomplete + b: Incomplete + x0: Incomplete + x1: Incomplete + y0: Incomplete + y1: Incomplete + series: Incomplete + i: Incomplete + s: Incomplete + def __init__(self, s, i, data) -> None: ... + def intersect(self, o, I): ... + +def find_intersections(data, small: int = 0): ... diff --git a/stubs/reportlab/reportlab/graphics/renderPDF.pyi b/stubs/reportlab/reportlab/graphics/renderPDF.pyi new file mode 100644 index 000000000000..382d054f9f63 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderPDF.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus import Flowable + +__version__: Final[str] + +def draw(drawing: Drawing, canvas: Canvas, x: float, y: float, showBoundary=...) -> None: ... + +class _PDFRenderer(Renderer): + def __init__(self) -> None: ... + def drawNode(self, node) -> None: ... + def drawRect(self, rect) -> None: ... + def drawImage(self, image) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawPolyLine(self, polyline) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, polygon) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawPath(self, path) -> None: ... + def setStrokeColor(self, c) -> None: ... + def setFillColor(self, c) -> None: ... + def applyStateChanges(self, delta, newState) -> None: ... + +class GraphicsFlowable(Flowable): + drawing: Incomplete + width: Incomplete + height: Incomplete + def __init__(self, drawing) -> None: ... + def draw(self) -> None: ... + +def drawToFile(d: Drawing, fn: str | IO[bytes], msg: str = "", showBoundary=..., autoSize: int = 1, **kwds) -> None: ... +def drawToString(d: Drawing, msg: str = "", showBoundary=..., autoSize: int = 1, **kwds) -> str: ... +def test(outDir: str = "pdfout", shout: bool = False) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/renderPM.pyi b/stubs/reportlab/reportlab/graphics/renderPM.pyi new file mode 100644 index 000000000000..68833ea9da95 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderPM.pyi @@ -0,0 +1,132 @@ +from _typeshed import Incomplete +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas + +__version__: Final[str] + +def Color2Hex(c): ... +def CairoColor(c): ... +def draw(drawing: Drawing, canvas: Canvas, x: float, y: float, showBoundary=...) -> None: ... + +class _PMRenderer(Renderer): + def pop(self) -> None: ... + def push(self, node) -> None: ... + def applyState(self) -> None: ... + def initState(self, x, y) -> None: ... + def drawNode(self, node) -> None: ... + def drawRect(self, rect) -> None: ... + def drawLine(self, line) -> None: ... + def drawImage(self, image) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawPolyLine(self, polyline, _doClose: int = 0) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, polygon) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawPath(self, path): ... + +BEZIER_ARC_MAGIC: float + +class PMCanvas: + ctm: Incomplete + def __init__( + self, w, h, dpi: int = 72, bg: int = 16777215, configPIL=None, backend=None, backendFmt: str = "RGB" + ) -> None: ... + def toPIL(self): ... + def saveToFile(self, fn, fmt=None): ... + def saveToString(self, fmt: str = "GIF"): ... + def setFont(self, fontName, fontSize, leading=None) -> None: ... + def __setattr__(self, name, value) -> None: ... + def __getattr__(self, name): ... + def fillstrokepath(self, stroke: int = 1, fill: int = 1) -> None: ... + def bezierArcCCW(self, cx, cy, rx, ry, theta0, theta1): ... + def addEllipsoidalArc(self, cx, cy, rx, ry, ang1, ang2) -> None: ... + def drawCentredString( + self, x: float, y: float, text: str, text_anchor: str = "middle", direction: str | None = None, shaping: bool = False + ) -> None: ... + def drawRightString(self, text: str, x: float, y: float, direction: str | None = None) -> None: ... + def drawString( + self, + x: float, + y: float, + text: str, + _fontInfo=None, + text_anchor: str = "left", + direction: str | None = None, + shaping: bool = False, + ) -> None: ... + def line(self, x1, y1, x2, y2) -> None: ... + def rect(self, x, y, width, height, stroke: int = 1, fill: int = 1) -> None: ... + def roundRect(self, x, y, width, height, rx, ry) -> None: ... + def circle(self, cx, cy, r) -> None: ... + def ellipse(self, cx, cy, rx, ry) -> None: ... + def saveState(self) -> None: ... + fillColor: Incomplete + fillOpacity: Incomplete + def setFillColor(self, aColor) -> None: ... + strokeColor: Incomplete + strokeOpacity: Incomplete + def setStrokeColor(self, aColor) -> None: ... + restoreState = saveState + lineCap: Incomplete + def setLineCap(self, cap) -> None: ... + lineJoin: Incomplete + def setLineJoin(self, join) -> None: ... + strokeWidth: Incomplete + def setLineWidth(self, width) -> None: ... + def stringWidth(self, text, fontName=None, fontSize=None): ... + +def drawToPMCanvas( + d: Drawing, + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +): ... +def drawToPIL( + d: Drawing, + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +): ... +def drawToPILP( + d: Drawing, + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +): ... +def drawToFile( + d: Drawing, + fn: str | IO[bytes], + fmt: str = "GIF", + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +) -> None: ... +def drawToString( + d: Drawing, + fmt: str = "GIF", + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +) -> str: ... + +save = drawToFile + +def test(outDir: str = "pmout", shout: bool = False): ... diff --git a/stubs/reportlab/reportlab/graphics/renderPS.pyi b/stubs/reportlab/reportlab/graphics/renderPS.pyi new file mode 100644 index 000000000000..f7e47c5af40e --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderPS.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas + +__version__: Final[str] +PS_WinAnsiEncoding: Final[str] + +class PSCanvas: + comments: int + code: Incomplete + code_append: Incomplete + PostScriptLevel: Incomplete + def __init__(self, size=(300, 300), PostScriptLevel: int = 2) -> None: ... + def comment(self, msg) -> None: ... + def drawImage(self, image, x1, y1, width=None, height=None) -> None: ... + def clear(self) -> None: ... + def save(self, f=None) -> None: ... + def saveState(self) -> None: ... + def restoreState(self) -> None: ... + def stringWidth(self, s, font=None, fontSize=None): ... + def setLineCap(self, v) -> None: ... + def setLineJoin(self, v) -> None: ... + def setDash(self, array=[], phase: int = 0) -> None: ... + def setStrokeColor(self, color) -> None: ... + def setColor(self, color) -> None: ... + def setFillColor(self, color) -> None: ... + def setFillMode(self, v) -> None: ... + def setLineWidth(self, width) -> None: ... + def setFont(self, font, fontSize, leading=None) -> None: ... + def line(self, x1, y1, x2, y2) -> None: ... + def drawString(self, x, y, s, angle: int = 0, text_anchor: str = "left", textRenderMode: int = 0) -> None: ... + def drawCentredString(self, x, y, text, text_anchor: str = "middle", textRenderMode: int = 0) -> None: ... + def drawRightString(self, text, x, y, text_anchor: str = "end", textRenderMode: int = 0) -> None: ... + def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed: int = 0) -> None: ... + def rect(self, x1, y1, x2, y2, stroke: int = 1, fill: int = 1) -> None: ... + def roundRect(self, x1, y1, x2, y2, rx: int = 8, ry: int = 8) -> None: ... + def ellipse(self, x1, y1, x2, y2) -> None: ... + def circle(self, xc, yc, r) -> None: ... + def drawArc(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 360, fromcenter: int = 0) -> None: ... + def polygon(self, p, closed: int = 0, stroke: int = 1, fill: int = 1) -> None: ... + def lines(self, lineList, color=None, width=None) -> None: ... + def moveTo(self, x, y) -> None: ... + def lineTo(self, x, y) -> None: ... + def curveTo(self, x1, y1, x2, y2, x3, y3) -> None: ... + def closePath(self) -> None: ... + def polyLine(self, p) -> None: ... + def drawFigure(self, partList, closed: int = 0) -> None: ... + def translate(self, x, y) -> None: ... + def scale(self, x, y) -> None: ... + def transform(self, a, b, c, d, e, f) -> None: ... + +def draw(drawing: Drawing, canvas: Canvas, x: float = 0, y: float = 0, showBoundary=0) -> None: ... + +class _PSRenderer(Renderer): + def drawNode(self, node) -> None: ... + def drawRect(self, rect) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawPolyLine(self, p) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, p) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawPath(self, path, fillMode=None): ... + def applyStateChanges(self, delta, newState) -> None: ... + def drawImage(self, image) -> None: ... + +def drawToFile(d: Drawing, fn: IO[bytes], showBoundary=0, **kwd) -> None: ... +def drawToString(d: Drawing, showBoundary=0) -> str: ... +def test(outDir: str = "epsout", shout: bool = False) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/renderSVG.pyi b/stubs/reportlab/reportlab/graphics/renderSVG.pyi new file mode 100644 index 000000000000..b9611dad4138 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderSVG.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from math import cos as cos, pi as pi, sin as sin +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas + +AREA_STYLES: Final[Sequence[str]] +LINE_STYLES: Final[Sequence[str]] +TEXT_STYLES: Final[Sequence[str]] +EXTRA_STROKE_STYLES: Final[Sequence[str]] +EXTRA_FILL_STYLES: Final[Sequence[str]] + +def drawToString(d: Drawing, showBoundary=0, **kwds) -> str: ... +def drawToFile(d: Drawing, fn: str | IO[str], showBoundary=0, **kwds) -> None: ... +def draw(drawing: Drawing, canvas: Canvas, x: float = 0, y: float = 0, showBoundary=0) -> None: ... +def transformNode(doc, newTag, node=None, **attrDict): ... + +class EncodedWriter(list[Incomplete]): + BOMS: Incomplete + encoding: Incomplete + def __init__(self, encoding, bom: bool = False) -> None: ... + def write(self, u) -> None: ... + def getvalue(self): ... + +def py_fp_str(*args): ... + +class SVGCanvas: + verbose: Incomplete + encoding: Incomplete + bom: Incomplete + fontHacks: Incomplete + extraXmlDecl: Incomplete + code: Incomplete + style: Incomplete + path: str + fp_str: Incomplete + cfp_str: Incomplete + doc: Incomplete + svg: Incomplete + groupTree: Incomplete + scaleTree: Incomplete + currGroup: Incomplete + def __init__(self, size=(300, 300), encoding: str = "utf-8", verbose: int = 0, bom: bool = False, **kwds) -> None: ... + def save(self, fn=None) -> None: ... + def NOTUSED_stringWidth(self, s, font=None, fontSize=None): ... + def setLineCap(self, v) -> None: ... + def setLineJoin(self, v) -> None: ... + def setDash(self, array=[], phase: int = 0) -> None: ... + def setStrokeColor(self, color) -> None: ... + def setFillColor(self, color) -> None: ... + def setFillMode(self, v) -> None: ... + def setLineWidth(self, width) -> None: ... + def setFont(self, font, fontSize) -> None: ... + def rect(self, x1, y1, x2, y2, rx: int = 8, ry: int = 8, link_info=None, **_svgAttrs) -> None: ... + def roundRect(self, x1, y1, x2, y2, rx: int = 8, ry: int = 8, link_info=None, **_svgAttrs) -> None: ... + def drawString( + self, s, x, y, angle: int = 0, link_info=None, text_anchor: str = "left", textRenderMode: int = 0, **_svgAttrs + ) -> None: ... + def drawCentredString( + self, s, x, y, angle: int = 0, text_anchor: str = "middle", link_info=None, textRenderMode: int = 0, **_svgAttrs + ) -> None: ... + def drawRightString( + self, text, x, y, angle: int = 0, text_anchor: str = "end", link_info=None, textRenderMode: int = 0, **_svgAttrs + ) -> None: ... + def comment(self, data) -> None: ... + def drawImage(self, image, x, y, width, height, embed: bool = True) -> None: ... + def line(self, x1, y1, x2, y2) -> None: ... + def ellipse(self, x1, y1, x2, y2, link_info=None) -> None: ... + def circle(self, xc, yc, r, link_info=None) -> None: ... + def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed: int = 0) -> None: ... + def drawArc(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 360, fromcenter: int = 0) -> None: ... + def polygon(self, points, closed: int = 0, link_info=None) -> None: ... + def lines(self, lineList, color=None, width=None) -> None: ... + def polyLine(self, points) -> None: ... + def startGroup(self, attrDict={"transform": ""}): ... + def endGroup(self, currGroup) -> None: ... + def transform(self, a, b, c, d, e, f) -> None: ... + def translate(self, x, y) -> None: ... + def scale(self, sx, sy) -> None: ... + def moveTo(self, x, y) -> None: ... + def lineTo(self, x, y) -> None: ... + def curveTo(self, x1, y1, x2, y2, x3, y3) -> None: ... + def closePath(self) -> None: ... + def saveState(self) -> None: ... + def restoreState(self) -> None: ... + +class _SVGRenderer(Renderer): + verbose: int + def __init__(self) -> None: ... + def drawNode(self, node) -> None: ... + def drawGroup(self, group) -> None: ... + def drawRect(self, rect) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawPolyLine(self, p) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, p) -> None: ... + def drawPath(self, path, fillMode=0): ... + def drawImage(self, image) -> None: ... + def applyStateChanges(self, delta, newState) -> None: ... + +def test(outDir: str = "out-svg") -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/renderbase.pyi b/stubs/reportlab/reportlab/graphics/renderbase.pyi new file mode 100644 index 000000000000..e9d04c948872 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderbase.pyi @@ -0,0 +1,39 @@ +from typing import Final + +__version__: Final[str] + +def getStateDelta(shape): ... + +class StateTracker: + def __init__(self, defaults=None, defaultObj=None) -> None: ... + def push(self, delta) -> None: ... + def pop(self): ... + def getState(self): ... + def getCTM(self): ... + def __getitem__(self, key): ... + def __setitem__(self, key, value) -> None: ... + +def testStateTracker() -> None: ... +def renderScaledDrawing(d): ... + +class Renderer: + def undefined(self, operation) -> None: ... + def draw(self, drawing, canvas, x: int = 0, y: int = 0, showBoundary=...) -> None: ... + def initState(self, x, y) -> None: ... + def pop(self) -> None: ... + def drawNode(self, node) -> None: ... + def getStateValue(self, key): ... + def fillDerivedValues(self, node) -> None: ... + def drawNodeDispatcher(self, anode) -> None: ... + def drawGroup(self, group) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawPath(self, path) -> None: ... + def drawRect(self, rect) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawPolyLine(self, p) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, p) -> None: ... + def drawString(self, stringObj) -> None: ... + def applyStateChanges(self, delta, newState) -> None: ... + def drawImage(self, *args, **kwds) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/__init__.pyi b/stubs/reportlab/reportlab/graphics/samples/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/reportlab/reportlab/graphics/samples/bubble.pyi b/stubs/reportlab/reportlab/graphics/samples/bubble.pyi new file mode 100644 index 000000000000..c3498e0da7b7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/bubble.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class Bubble(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi b/stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi new file mode 100644 index 000000000000..92c971a781db --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ClusteredBar(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi b/stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi new file mode 100644 index 000000000000..e63bc6a30e89 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ClusteredColumn(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi b/stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi new file mode 100644 index 000000000000..daf8c0fb4e90 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +color01: Incomplete +color02: Incomplete +color03: Incomplete +color04: Incomplete +color05: Incomplete +color06: Incomplete +color07: Incomplete +color08: Incomplete +color09: Incomplete +color10: Incomplete +color01Light: Incomplete +color02Light: Incomplete +color03Light: Incomplete +color04Light: Incomplete +color05Light: Incomplete +color06Light: Incomplete +color07Light: Incomplete +color08Light: Incomplete +color09Light: Incomplete +color10Light: Incomplete +color01Dark: Incomplete +color02Dark: Incomplete +color03Dark: Incomplete +color04Dark: Incomplete +color05Dark: Incomplete +color06Dark: Incomplete +color07Dark: Incomplete +color08Dark: Incomplete +color09Dark: Incomplete +color10Dark: Incomplete +backgroundGrey: Incomplete diff --git a/stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi b/stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi new file mode 100644 index 000000000000..7421505c19bd --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ExplodedPie(_DrawingEditorMixin, Drawing): + background: Incomplete + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi b/stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi new file mode 100644 index 000000000000..f0032bdf91aa --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class FilledRadarChart(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/line_chart.pyi b/stubs/reportlab/reportlab/graphics/samples/line_chart.pyi new file mode 100644 index 000000000000..fa026e6cc4c9 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/line_chart.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class LineChart(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi b/stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi new file mode 100644 index 000000000000..0be656dabf2c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class LineChartWithMarkers(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/radar.pyi b/stubs/reportlab/reportlab/graphics/samples/radar.pyi new file mode 100644 index 000000000000..483c55c9ee2a --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/radar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class RadarChart(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/runall.pyi b/stubs/reportlab/reportlab/graphics/samples/runall.pyi new file mode 100644 index 000000000000..983f8c55d094 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/runall.pyi @@ -0,0 +1,3 @@ +def moduleClasses(mod): ... +def getclass(f): ... +def run(format, VERBOSE: int = 0) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/scatter.pyi b/stubs/reportlab/reportlab/graphics/samples/scatter.pyi new file mode 100644 index 000000000000..dd2df0cd8fdc --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/scatter.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class Scatter(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi b/stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi new file mode 100644 index 000000000000..708223a0dbbc --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ScatterLines(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi b/stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi new file mode 100644 index 000000000000..b7c25c476a21 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ScatterLinesMarkers(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi b/stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi new file mode 100644 index 000000000000..9b01626f09e3 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class SimplePie(_DrawingEditorMixin, Drawing): + background: Incomplete + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi b/stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi new file mode 100644 index 000000000000..2ee3aed65a88 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class StackedBar(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi b/stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi new file mode 100644 index 000000000000..f3b47c2c437c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class StackedColumn(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/shapes.pyi b/stubs/reportlab/reportlab/graphics/shapes.pyi new file mode 100644 index 000000000000..123a551ddc2e --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/shapes.pyi @@ -0,0 +1,381 @@ +from _typeshed import Incomplete, SupportsItems +from abc import abstractmethod +from collections.abc import Iterable, Sequence +from typing import Any, Final, Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Never, Self, Unpack + +from reportlab.lib.colors import Color +from reportlab.lib.validators import NoneOr, Validator +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus import Flowable +from reportlab.platypus.flowables import _HAlignment, _VAlignment + +_IntBool: TypeAlias = Literal[0, 1] +_BoolLike: TypeAlias = _IntBool | bool +_PathOp: TypeAlias = ( + tuple[Literal["moveTo"], float, float] + | tuple[Literal["lineTo"], float, float] + | tuple[Literal["curveTo"], float, float, float, float, float, float] + # close path may either be a tuple or just the string + | Literal["closePath"] + | tuple[Literal["closePath"]] + # fallback for list that is not type safe + | list[Any] +) + +# NOTE: These are derived from _attrMap and can optionally be +# verified at runtime +@type_check_only +class _GroupKwArgs(TypedDict, total=False): + transform: tuple[float, float, float, float, float, float] | list[float] | list[int] + # NOTE: This should be used with care, since it will replace elements + # it's mostly useful for circumventing validation logic and + # reusing the list, rather than populating a new list + contents: list[Shape] + strokeOverprint: _BoolLike + fillOverprint: _BoolLike + overprintMask: _BoolLike + +@type_check_only +class _DrawingKwArgs(_GroupKwArgs, total=False): + # TODO: Restrict to supported formats? + formats: list[str] | tuple[str, ...] + # NOTE: This looks like an implementation detail, so we may not + # want to include this in KwArgs + canv: Canvas + background: Shape | UserNode | None + # NOTE: The runtime validation for alignments is incorrect, so + # we assume it is turned off and allow all valid values + hAlign: _HAlignment + vAlign: _VAlignment + renderScale: float + initialFontName: str | None + initialFontSize: float | None + +@type_check_only +class _LineShapeKwArgs(TypedDict, total=False): + strokeColor: Color | None + strokeWidth: float + strokeLineCap: Literal[0, 1, 2] + strokeLineJoin: Literal[0, 1, 2] + strokeMiterLimit: float + strokeDashArray: Sequence[float] | tuple[float, Sequence[float]] + strokeOpacity: float | None + strokeOverprint: _BoolLike + overprintMask: _BoolLike + +@type_check_only +class _PathKwArgs(_LineShapeKwArgs, total=False): + fillColor: Color | None + fillOpacity: float + fillOverprint: _BoolLike + +@type_check_only +class _AllPathKwArgs(_PathKwArgs, total=False): + points: list[float] | None + operators: list[float] | None + isClipPath: _BoolLike + autoclose: Literal["svg", "pdf"] | None + fillMode: Literal[0, 1] + +@type_check_only +class _SolidShapeKwArgs(_PathKwArgs, total=False): + fillMode: Literal[0, 1] + +@type_check_only +class _DefinePathKwArgs(_SolidShapeKwArgs, total=False): + autoclose: Literal["svg", "pdf"] | None + bbox: tuple[float, float, float, float] | None + +@type_check_only +class _WedgeKwArgs(_SolidShapeKwArgs, total=False): + radius1: float | None + yradius1: float | None + +@type_check_only +class _StringKwArgs(TypedDict, total=False): + fontName: str + fontSize: float + fillColor: Color | None + textAnchor: Literal["start", "middle", "end", "numeric"] + encoding: str + textRenderMode: Literal[0, 1, 2, 3, 4, 5, 6, 7] + +__version__: Final[str] +isOpacity: NoneOr +NON_ZERO_WINDING: Final[str] +EVEN_ODD: Final[str] +STATE_DEFAULTS: Final[Incomplete] + +class _DrawTimeResizeable: ... + +class _SetKeyWordArgs: + def __init__(self, keywords: SupportsItems[str, Any] = {}) -> None: ... + +def getRectsBounds(rectList): ... +def getPathBounds(points): ... +def getPointsBounds(pointList): ... + +class Shape(_SetKeyWordArgs, _DrawTimeResizeable): + @abstractmethod + def copy(self) -> Self: ... + def getProperties(self, recur: int = 1) -> dict[str, Any]: ... + def setProperties(self, props) -> None: ... + def dumpProperties(self, prefix: str = "") -> None: ... + def verify(self) -> None: ... + @abstractmethod + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Group(Shape): + contents: list[Shape] + transform: tuple[float, float, float, float, float, float] | list[float] | list[int] + def __init__(self, *elements: Shape | UserNode, **keywords: Unpack[_GroupKwArgs]) -> None: ... + def add(self, node: Shape | UserNode, name: str | None = None) -> None: ... + def insert(self, i: int, n: Shape | UserNode, name: str | None = None) -> None: ... + def expandUserNodes(self) -> Group: ... + def copy(self) -> Self: ... + def rotate(self, theta: float, cx: float = 0, cy: float = 0) -> None: ... + def translate(self, dx: float, dy: float = 0) -> None: ... + def scale(self, sx: float, sy: float = 1) -> None: ... + def skew(self, kx: float, ky: float = 0) -> None: ... + def shift(self, x: float, y: float = 0) -> None: ... + # NOTE: This changes the object to a Drawing, rather than returning + # a new one, which is not ideal... + def asDrawing(self, width: float, height: float) -> None: ... + def getContents(self) -> list[Shape | UserNode]: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Drawing(Group, Flowable): + background: Shape | UserNode | None + renderScale: float + def __init__( + self, width: float = 400, height: float = 200, *nodes: Shape | UserNode, **keywords: Unpack[_DrawingKwArgs] + ) -> None: ... + def draw(self, showBoundary=...) -> None: ... + def expandUserNodes(self) -> Drawing: ... + def asGroup(self, *args: Shape | UserNode, **kw: Unpack[_GroupKwArgs]) -> Group: ... + def save( + self, + formats: Iterable[str] | None = None, + verbose: bool | None = None, + fnRoot: str | None = None, + outDir: str | None = None, + title: str = "", + **kw, + ): ... + def asString(self, format: str, verbose: bool | None = None, preview: int = 0, **kw) -> str: ... + def resized( + self, kind: Literal["fit", "fitx", "fity"] = "fit", lpad: float = 0, rpad: float = 0, bpad: float = 0, tpad: float = 0 + ) -> Drawing: ... + +class _DrawingEditorMixin: ... + +@type_check_only +class _isStrokeDashArray(Validator): + def test(self, x): ... + +isStrokeDashArray: _isStrokeDashArray + +class LineShape(Shape): + strokeColor: Color | None + strokeWidth: float + strokeLineCap: Literal[0, 1, 2] + strokeLineJoin: Literal[0, 1, 2] + strokeMiterLimit: float + strokeDashArray: Sequence[float] | tuple[float, Sequence[float]] + strokeOpacity: float | None + def __init__(self, kw: _LineShapeKwArgs) -> None: ... + @abstractmethod + def copy(self) -> Self: ... + @abstractmethod + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Line(LineShape): + x1: float + y1: float + x2: float + y2: float + def __init__(self, x1: float, y1: float, x2: float, y2: float, **kw: Unpack[_LineShapeKwArgs]) -> None: ... + # NOTE: For some reason Line doesn't implement copy + def copy(self) -> Never: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class SolidShape(LineShape): + fillColor: Color | None + fillOpacity: float | None + def __init__(self, kw: _SolidShapeKwArgs) -> None: ... + @abstractmethod + def copy(self) -> Self: ... + @abstractmethod + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Path(SolidShape): + points: list[float] + operators: list[float] + isClipPath: _BoolLike + autoclose: Literal["svg", "pdf"] | None + fillMode: Literal[0, 1] + def __init__( + self, + points: list[float] | None = None, + operators: list[float] | None = None, + isClipPath: _BoolLike = 0, + autoclose: Literal["svg", "pdf"] | None = None, + fillMode: Literal[0, 1] = 0, + **kw: Unpack[_PathKwArgs], + ) -> None: ... + def copy(self) -> Self: ... + def moveTo(self, x: float, y: float) -> None: ... + def lineTo(self, x: float, y: float) -> None: ... + def curveTo(self, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float) -> None: ... + def closePath(self) -> None: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +EmptyClipPath: Final[Path] + +def getArcPoints( + centerx: float, + centery: float, + radius: float, + startangledegrees: float, + endangledegrees: float, + yradius: float | None = None, + degreedelta: float | None = None, + reverse: _BoolLike | None = None, +) -> list[float]: ... + +class ArcPath(Path): + def addArc( + self, + centerx: float, + centery: float, + radius: float, + startangledegrees: float, + endangledegrees: float, + yradius: float | None = None, + degreedelta: float | None = None, + moveTo: _BoolLike | None = None, + reverse: _BoolLike | None = None, + ) -> None: ... + +def definePath( + pathSegs: Iterable[_PathOp] = [], isClipPath: _BoolLike = 0, dx: float = 0, dy: float = 0, **kw: Unpack[_DefinePathKwArgs] +) -> Path: ... + +class Rect(SolidShape): + x: float + y: float + width: float + height: float + rx: float + ry: float + def __init__( + self, x: float, y: float, width: float, height: float, rx: float = 0, ry: float = 0, **kw: _SolidShapeKwArgs + ) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Image(SolidShape): + x: float + y: float + width: float + height: float + path: Incomplete + def __init__(self, x: float, y: float, width: float, height: float, path, **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Circle(SolidShape): + cx: float + cy: float + r: float + def __init__(self, cx: float, cy: float, r: float, **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Ellipse(SolidShape): + cx: float + cy: float + rx: float + ry: float + def __init__(self, cx: float, cy: float, rx: float, ry: float, **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Wedge(SolidShape): + centerx: float + centery: float + radius: float + startangledegrees: float + endangledegrees: float + yradius: float | None + annular: bool + # NOTE: This one is not actually settable on the instance if runtime validation + # is turned on, but it seems bad to disallow it anyways + degreedelta: float + def __init__( + self, + centerx: float, + centery: float, + radius: float, + startangledegrees: float, + endangledegrees: float, + yradius: float | None = None, + annular: bool = False, + **kw: Unpack[_WedgeKwArgs], + ) -> None: ... + def asPolygon(self) -> Path | Polygon: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Polygon(SolidShape): + points: list[float] + def __init__(self, points: list[float] = [], **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class PolyLine(LineShape): + points: list[float] + def __init__(self, points: list[float] = [], **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Hatching(Path): + xyLists: Sequence[tuple[float, float]] + angles: Sequence[float] + spacings: Sequence[float] + def __init__( + self, + spacings: float | Sequence[float] = 2, + angles: float | Sequence[float] = 45, + xyLists: Sequence[tuple[float, float] | list[float]] = [], + **kwds: Unpack[_AllPathKwArgs], + ) -> None: ... + +def numericXShift( + tA, text: str, w: float, fontName: str, fontSize: float, encoding: str | None = None, pivotCharacter: str = "." +) -> float: ... + +class String(Shape): + encoding: str + x: float + y: float + text: str + textAnchor: Literal["start", "middle", "end", "numeric"] + fontName: str + fontSize: float + fillColor: Color | None + def __init__(self, x: float, y: float, text: str, **kw: Unpack[_StringKwArgs]) -> None: ... + def getEast(self): ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class UserNode(_DrawTimeResizeable): + @abstractmethod + def provideNode(self) -> Shape: ... + +class DirectDraw(Shape): + @abstractmethod + def drawDirectly(self, canvas: Canvas) -> None: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/svgpath.pyi b/stubs/reportlab/reportlab/graphics/svgpath.pyi new file mode 100644 index 000000000000..1c8f62625f79 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/svgpath.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from .shapes import Path, UserNode + +class SvgPath(Path, UserNode): + fillColor: Incomplete + def __init__(self, s, isClipPath: int = 0, autoclose=None, fillMode=0, **kw) -> None: ... + def provideNode(self): ... + +__all__ = ("SvgPath",) diff --git a/stubs/reportlab/reportlab/graphics/transform.pyi b/stubs/reportlab/reportlab/graphics/transform.pyi new file mode 100644 index 000000000000..820531addd22 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/transform.pyi @@ -0,0 +1,29 @@ +def nullTransform(): ... +def translate(dx: float, dy: float = 0): ... +def scale(sx: float, sy: float = 1): ... +def rotate(angle: float, cx: float = 0, cy: float = 0): ... +def skewX(angle: float): ... +def skewY(angle: float): ... +def mmult(A, B): ... +def combineTransforms(*T): ... +def inverse(A): ... +def zTransformPoint(A, v): ... +def transformPoint(A, v): ... +def transformPoints(matrix, V): ... +def zTransformPoints(matrix, V): ... + +__all__ = ( + "nullTransform", + "translate", + "scale", + "rotate", + "skewX", + "skewY", + "mmult", + "combineTransforms", + "inverse", + "zTransformPoint", + "transformPoint", + "transformPoints", + "zTransformPoints", +) diff --git a/stubs/reportlab/reportlab/graphics/utils.pyi b/stubs/reportlab/reportlab/graphics/utils.pyi new file mode 100644 index 000000000000..af61914c0058 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/utils.pyi @@ -0,0 +1,22 @@ +class RenderPMError(Exception): ... + +def setFont(gs, fontName, fontSize) -> None: ... +def pathNumTrunc(n): ... +def text2Path( + text, + x: int = 0, + y: int = 0, + fontName="Times-Roman", + fontSize: int = 1000, + anchor: str = "start", + truncate: int = 1, + pathReverse: int = 0, + gs=None, + **kwds, +): ... + +# NOTE: This only exists on some render backends +def processGlyph(G, truncate=1, pathReverse=0): ... +def text2PathDescription(text, x=0, y=0, fontName=..., fontSize=1000, anchor="start", truncate=1, pathReverse=0, gs=None): ... + +__all__ = ("setFont", "pathNumTrunc", "processGlyph", "text2PathDescription", "text2Path", "RenderPMError") diff --git a/stubs/reportlab/reportlab/graphics/widgetbase.pyi b/stubs/reportlab/reportlab/graphics/widgetbase.pyi new file mode 100644 index 000000000000..b937f01cc9e7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgetbase.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics import shapes +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class PropHolder: + def verify(self) -> None: ... + def __setattr__(self, name, value) -> None: ... + def getProperties(self, recur: int = 1): ... + def setProperties(self, propDict) -> None: ... + def dumpProperties(self, prefix: str = "") -> None: ... + +class Widget(PropHolder, shapes.UserNode): + def draw(self): ... # abstract, but not marked as @abstractmethod + def demo(self): ... # abstract, but not marked as @abstractmethod + def provideNode(self) -> shapes.Shape: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class ScaleWidget(Widget): + x: Incomplete + y: Incomplete + contents: Incomplete + scale: Incomplete + def __init__(self, x: int = 0, y: int = 0, scale: float = 1.0, contents=None) -> None: ... + def draw(self): ... + +class CloneMixin: + def clone(self, **kwds): ... + +class TypedPropertyCollection(PropHolder): + def __init__(self, exampleClass, **kwds) -> None: ... + def wKlassFactory(self, Klass): ... + def __getitem__(self, x): ... + def __contains__(self, key) -> bool: ... + def __setitem__(self, key, value) -> None: ... + def __len__(self) -> int: ... + def getProperties(self, recur: int = 1): ... + def setVector(self, **kw) -> None: ... + def __getattr__(self, name): ... + def __setattr__(self, name, value): ... + def checkAttr(self, key, a, default=None): ... + +def tpcGetItem(obj, x): ... +def isWKlass(obj): ... + +class StyleProperties(PropHolder): + def __init__(self, **kwargs) -> None: ... + def __setattr__(self, name, value) -> None: ... + +class TwoCircles(Widget): + leftCircle: Incomplete + rightCircle: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class Face(Widget): + x: int + y: int + size: int + skinColor: Incomplete + eyeColor: Incomplete + mood: str + def __init__(self) -> None: ... + def demo(self) -> None: ... + def draw(self): ... + +class TwoFaces(Widget): + faceOne: Incomplete + faceTwo: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + def demo(self) -> None: ... + +class Sizer(Widget): + contents: Incomplete + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self, *elements) -> None: ... + def add(self, node, name=None) -> None: ... + def getBounds(self): ... + def draw(self): ... + +class CandleStickProperties(PropHolder): + strokeWidth: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + crossWidth: Incomplete + crossLo: Incomplete + crossHi: Incomplete + boxWidth: Incomplete + boxFillColor: Incomplete + boxStrokeColor: Incomplete + boxStrokeWidth: Incomplete + boxStrokeDashArray: Incomplete + boxLo: Incomplete + boxMid: Incomplete + boxHi: Incomplete + boxSides: Incomplete + position: Incomplete + candleKind: Incomplete + axes: Incomplete + chart: Incomplete + def __init__(self, **kwds) -> None: ... + def __call__(self, _x, _y, _size, _color): ... + +def CandleSticks(**kwds): ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/__init__.pyi b/stubs/reportlab/reportlab/graphics/widgets/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi b/stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi new file mode 100644 index 000000000000..18bf1002c449 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi @@ -0,0 +1,11 @@ +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +class AdjustableArrow(Widget): + def __init__(self, **kwds) -> None: ... + def draw(self): ... + +class AdjustableArrowDrawing(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 100, height: int = 63, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi b/stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi new file mode 100644 index 000000000000..8e850d0f8d84 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget + +__version__: Final[str] + +class EventCalendar(Widget): + x: int + y: int + width: int + height: int + timeColWidth: Incomplete + trackRowHeight: int + data: Incomplete + trackNames: Incomplete + startTime: Incomplete + endTime: Incomplete + day: int + def __init__(self) -> None: ... + def computeSize(self) -> None: ... + def computeStartAndEndTimes(self) -> None: ... + def getAllTracks(self): ... + def getRelevantTalks(self, talkList): ... + def scaleTime(self, theTime): ... + def getTalkRect(self, startTime, duration, trackId, text): ... + def draw(self): ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/flags.pyi b/stubs/reportlab/reportlab/graphics/widgets/flags.pyi new file mode 100644 index 000000000000..69a282c17c1b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/flags.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgets.signsandsymbols import _Symbol +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] +validFlag: Incomplete + +class Star(_Symbol): + size: int + fillColor: Incomplete + strokeColor: Incomplete + angle: int + def __init__(self) -> None: ... + def demo(self): ... + def draw(self): ... + +class Flag(_Symbol): + kind: Incomplete + size: int + fillColor: Incomplete + border: int + def __init__(self, **kw) -> None: ... + def availableFlagNames(self): ... + def draw(self): ... + def clone(self): ... + def demo(self): ... + +def makeFlag(name): ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/grids.pyi b/stubs/reportlab/reportlab/graphics/widgets/grids.pyi new file mode 100644 index 000000000000..e098fe78fc84 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/grids.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from typing import Final +from typing_extensions import Never + +from reportlab.graphics.shapes import LineShape +from reportlab.graphics.widgetbase import Widget + +__version__: Final[str] + +def frange(start, end=None, inc=None): ... +def makeDistancesList(list): ... + +class Grid(Widget): + x: int + y: int + width: int + height: int + orientation: str + useLines: int + useRects: int + delta: int + delta0: int + deltaSteps: Incomplete + fillColor: Incomplete + stripeColors: Incomplete + strokeColor: Incomplete + strokeWidth: int + def __init__(self) -> None: ... + def demo(self): ... + def makeOuterRect(self): ... + def makeLinePosList(self, start, isX: int = 0): ... + def makeInnerLines(self): ... + def makeInnerTiles(self): ... + def draw(self): ... + +class DoubleGrid(Widget): + x: int + y: int + width: int + height: int + grid0: Incomplete + grid1: Incomplete + def __init__(self) -> None: ... + def demo(self): ... + def draw(self): ... + +class ShadedRect(Widget): + x: int + y: int + width: int + height: int + orientation: str + numShades: int + fillColorStart: Incomplete + fillColorEnd: Incomplete + strokeColor: Incomplete + strokeWidth: int + cylinderMode: int + def __init__(self, **kw) -> None: ... + def demo(self): ... + def draw(self): ... + +def colorRange(c0, c1, n): ... +def centroid(P): ... +def rotatedEnclosingRect(P, angle, rect): ... + +class ShadedPolygon(Widget, LineShape): + angle: int + fillColorStart: Incomplete + fillColorEnd: Incomplete + cylinderMode: int + numShades: int + points: Incomplete + def __init__(self, **kw) -> None: ... + def draw(self): ... + # NOTE: widgets don't implement this, only actual shapes + def copy(self) -> Never: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/markers.pyi b/stubs/reportlab/reportlab/graphics/widgets/markers.pyi new file mode 100644 index 000000000000..6201181a6f99 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/markers.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.validators import Validator + +__version__: Final[str] + +class Marker(Widget): + def __init__(self, *args, **kw) -> None: ... + def clone(self, **kwds): ... + def draw(self): ... + +def uSymbol2Symbol(uSymbol, x, y, color): ... + +class _isSymbol(Validator): + def test(self, x): ... + +isSymbol: Incomplete + +def makeMarker(name, **kw): ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi b/stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi new file mode 100644 index 000000000000..6b520e461fa5 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi @@ -0,0 +1,164 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class _Symbol(Widget): + x: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: float + def __init__(self) -> None: ... + def demo(self): ... + +class ETriangle(_Symbol): + def __init__(self) -> None: ... + def draw(self): ... + +class RTriangle(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class Octagon(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class Crossbox(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + crossColor: Incomplete + strokeColor: Incomplete + crosswidth: int + def __init__(self) -> None: ... + def draw(self): ... + +class Tickbox(_Symbol): + x: int + y: int + size: int + tickColor: Incomplete + strokeColor: Incomplete + fillColor: Incomplete + tickwidth: int + def __init__(self) -> None: ... + def draw(self): ... + +class SmileyFace(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class StopSign(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + stopColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class NoEntry(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + innerBarColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class NotAllowed(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class NoSmoking(NotAllowed): + def __init__(self) -> None: ... + def draw(self): ... + +class DangerSign(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + strokeWidth: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class YesNo(_Symbol): + x: int + y: int + size: int + tickcolor: Incomplete + crosscolor: Incomplete + testValue: int + def __init__(self) -> None: ... + def draw(self): ... + def demo(self): ... + +class FloppyDisk(_Symbol): + x: int + y: int + size: int + diskColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class ArrowOne(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeWidth: int + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class ArrowTwo(ArrowOne): + x: int + y: int + size: int + fillColor: Incomplete + strokeWidth: int + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class CrossHair(_Symbol): + x: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: float + innerGap: str + def __init__(self) -> None: ... + def draw(self): ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/table.pyi b/stubs/reportlab/reportlab/graphics/widgets/table.pyi new file mode 100644 index 000000000000..a38683fb2e8c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/table.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class TableWidget(Widget): + x: Incomplete + y: Incomplete + width: int + height: int + borderStrokeColor: Incomplete + fillColor: Incomplete + borderStrokeWidth: float + horizontalDividerStrokeColor: Incomplete + verticalDividerStrokeColor: Incomplete + horizontalDividerStrokeWidth: float + verticalDividerStrokeWidth: float + dividerDashArray: Incomplete + data: Incomplete + boxAnchor: str + fontSize: int + fontColor: Incomplete + alignment: str + textAnchor: str + def __init__(self, x: int = 10, y: int = 10, **kw) -> None: ... + def demo(self): ... + def draw(self): ... + def preProcessData(self, data): ... diff --git a/stubs/reportlab/reportlab/lib/PyFontify.pyi b/stubs/reportlab/reportlab/lib/PyFontify.pyi new file mode 100644 index 000000000000..cf5a8f4c7b38 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/PyFontify.pyi @@ -0,0 +1,22 @@ +import re +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +def replace(src, sep, rep): ... + +keywordsList: list[str] +commentPat: str +pat: str +quotePat: str +tripleQuotePat: str +nonKeyPat: str +keyPat: str +matchPat: str +matchRE: re.Pattern[str] +idKeyPat: str +idRE: re.Pattern[str] + +def fontify(pytext, searchfrom: int = 0, searchto=None) -> list[tuple[str, int, int, Incomplete]]: ... +def test(path) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/__init__.pyi b/stubs/reportlab/reportlab/lib/__init__.pyi new file mode 100644 index 000000000000..f2c66be57c66 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/__init__.pyi @@ -0,0 +1,4 @@ +from typing import Final + +__version__: Final[str] +RL_DEBUG: Final[bool] # initialised based on env diff --git a/stubs/reportlab/reportlab/lib/abag.pyi b/stubs/reportlab/reportlab/lib/abag.pyi new file mode 100644 index 000000000000..4c7d4d6851a0 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/abag.pyi @@ -0,0 +1,11 @@ +from typing import Any, Final +from typing_extensions import Self + +__version__: Final[str] + +class ABag: + def __init__(self, **attr: Any) -> None: ... + def clone(self, **attr: Any) -> Self: ... + # ABag can have arbitrary attributes + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/arciv.pyi b/stubs/reportlab/reportlab/lib/arciv.pyi new file mode 100644 index 000000000000..501f1df37996 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/arciv.pyi @@ -0,0 +1,9 @@ +class ArcIV: + def __init__(self, key) -> None: ... + def reset(self) -> None: ... + def encode(self, S: str | bytes | list[int]) -> bytes: ... + +def encode(text: str | bytes | list[int], key) -> bytes: ... +def decode(text: str | bytes | list[int], key) -> bytes: ... + +__all__ = ["ArcIV", "encode", "decode"] diff --git a/stubs/reportlab/reportlab/lib/attrmap.pyi b/stubs/reportlab/reportlab/lib/attrmap.pyi new file mode 100644 index 000000000000..a951823e0b91 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/attrmap.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +class CallableValue: + func: Incomplete + args: Incomplete + kw: Incomplete + def __init__(self, func, *args, **kw) -> None: ... + def __call__(self): ... + +class AttrMapValue: + validate: Incomplete + desc: Incomplete + def __init__(self, validate=None, desc=None, initial=None, advancedUsage: int = 0, **kw) -> None: ... + def __getattr__(self, name): ... + +class AttrMap(dict[str, AttrMapValue]): + def __init__(self, BASE=None, UNWANTED=[], **kw) -> None: ... + def remove(self, unwanted) -> None: ... + def clone(self, UNWANTED=[], **kw) -> AttrMap: ... + +def validateSetattr(obj, name, value) -> None: ... +def hook__setattr__(obj) -> None: ... +def addProxyAttribute(src, name, validate=None, desc=None, initial=None, dst=None) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/boxstuff.pyi b/stubs/reportlab/reportlab/lib/boxstuff.pyi new file mode 100644 index 000000000000..61578c5e15c1 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/boxstuff.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from typing import Final, Literal, overload + +__version__: Final[str] + +@overload +def rectCorner( + x, y, width, height, anchor: str = "sw", dims: Literal[True] = ... +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +@overload +def rectCorner(x, y, width, height, anchor: str = "sw", dims: Literal[False] | None = False) -> tuple[Incomplete, Incomplete]: ... + +def aspectRatioFix( + preserve, anchor, x, y, width, height, imWidth, imHeight, anchorAtXY: bool = False +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... diff --git a/stubs/reportlab/reportlab/lib/codecharts.pyi b/stubs/reportlab/reportlab/lib/codecharts.pyi new file mode 100644 index 000000000000..b91508e6c77a --- /dev/null +++ b/stubs/reportlab/reportlab/lib/codecharts.pyi @@ -0,0 +1,81 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.shapes import Group +from reportlab.graphics.widgetbase import Widget +from reportlab.platypus import Flowable + +__version__: Final[str] +adobe2codec: dict[str, str] + +class CodeChartBase(Flowable): + rows: Incomplete + width: Incomplete + height: Incomplete + ylist: Incomplete + xlist: Incomplete + def calcLayout(self) -> None: ... + def formatByte(self, byt) -> str: ... + def drawChars(self, charList) -> None: ... + def drawLabels(self, topLeft: str = "") -> None: ... + +class SingleByteEncodingChart(CodeChartBase): + codePoints: int + faceName: Incomplete + encodingName: Incomplete + fontName: Incomplete + charsPerRow: Incomplete + boxSize: Incomplete + hex: Incomplete + rowLabels: Incomplete + def __init__( + self, + faceName: str = "Helvetica", + encodingName: str = "WinAnsiEncoding", + charsPerRow: int = 16, + boxSize: int = 14, + hex: int = 1, + ) -> None: ... + def draw(self) -> None: ... + +class KutenRowCodeChart(CodeChartBase): + row: Incomplete + codePoints: int + boxSize: int + charsPerRow: int + rows: int + rowLabels: Incomplete + hex: int + faceName: Incomplete + encodingName: Incomplete + fontName: Incomplete + def __init__(self, row, faceName, encodingName) -> None: ... + def makeRow(self, row) -> list[bytes | list[None]]: ... + def draw(self) -> None: ... + +class Big5CodeChart(CodeChartBase): + row: Incomplete + codePoints: int + boxSize: int + charsPerRow: int + rows: int + hex: int + faceName: Incomplete + encodingName: Incomplete + rowLabels: Incomplete + fontName: Incomplete + def __init__(self, row, faceName, encodingName) -> None: ... + def makeRow(self, row) -> list[bytes | list[None]]: ... + def draw(self) -> None: ... + +def hBoxText(msg, canvas, x, y, fontName) -> None: ... + +class CodeWidget(Widget): + x: int + y: int + width: int + height: int + def __init__(self) -> None: ... + def draw(self) -> Group: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/lib/colors.pyi b/stubs/reportlab/reportlab/lib/colors.pyi new file mode 100644 index 000000000000..de0de9789c00 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/colors.pyi @@ -0,0 +1,325 @@ +from collections.abc import Iterable, Iterator +from typing import Final, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +_ColorT = TypeVar("_ColorT", bound=Color) +# NOTE: Reportlab is very inconsistent and sometimes uses the interpretation +# used in reportlab.pdfgen.textobject instead, so we pick a different name +_ConvertibleToColor: TypeAlias = Color | list[float] | tuple[float, float, float, float] | tuple[float, float, float] | str | int + +__version__: Final[str] + +class Color: + red: float + green: float + blue: float + alpha: float + def __init__(self, red: float = 0, green: float = 0, blue: float = 0, alpha: float = 1) -> None: ... + @property + def __key__(self) -> tuple[float, ...]: ... + def __hash__(self) -> int: ... + def __comparable__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + def rgb(self) -> tuple[float, float, float]: ... + def rgba(self) -> tuple[float, float, float, float]: ... + def bitmap_rgb(self) -> tuple[int, int, int]: ... + def bitmap_rgba(self) -> tuple[int, int, int, int]: ... + def hexval(self) -> str: ... + def hexvala(self) -> str: ... + def int_rgb(self) -> int: ... + def int_rgba(self) -> int: ... + def int_argb(self) -> int: ... + @property + def cKwds(self) -> Iterator[tuple[str, int]]: ... + # NOTE: Possible arguments depend on __init__, so this violates LSP + # For now we just leave it unchecked + def clone(self, **kwds) -> Self: ... + @property + def normalizedAlpha(self) -> float: ... + +def opaqueColor(c: object) -> bool: ... + +class CMYKColor(Color): + cyan: float + magenta: float + yellow: float + black: float + spotName: str | None + density: float + knockout: bool | None + alpha: float + def __init__( + self, + cyan: float = 0, + magenta: float = 0, + yellow: float = 0, + black: float = 0, + spotName: str | None = None, + density: float = 1, + knockout: bool | None = None, + alpha: float = 1, + ) -> None: ... + def fader(self, n: int, reverse: bool = False) -> list[Self]: ... + def cmyk(self) -> tuple[float, float, float, float]: ... + def cmyka(self) -> tuple[float, float, float, float, float]: ... + +class PCMYKColor(CMYKColor): + def __init__( + self, + cyan: float, + magenta: float, + yellow: float, + black: float, + density: float = 100, + spotName: str | None = None, + knockout: bool | None = None, + alpha: float = 100, + ) -> None: ... + +class CMYKColorSep(CMYKColor): + def __init__( + self, + cyan: float = 0, + magenta: float = 0, + yellow: float = 0, + black: float = 0, + spotName: str | None = None, + density: float = 1, + alpha: float = 1, + ) -> None: ... + +class PCMYKColorSep(PCMYKColor, CMYKColorSep): + def __init__( + self, + cyan: float = 0, + magenta: float = 0, + yellow: float = 0, + black: float = 0, + spotName: str | None = None, + density: float = 100, + alpha: float = 100, + ) -> None: ... + +def cmyk2rgb(cmyk: tuple[float, float, float, float], density: float = 1) -> tuple[float, float, float]: ... +def rgb2cmyk(r: float, g: float, b: float) -> tuple[float, float, float, float]: ... +def color2bw(colorRGB: Color) -> Color: ... +def HexColor(val: str | int, htmlOnly: bool = False, hasAlpha: bool = False) -> Color: ... +def linearlyInterpolatedColor(c0: _ColorT, c1: _ColorT, x0: float, x1: float, x: float) -> _ColorT: ... + +@overload +def obj_R_G_B( + c: Color | list[float] | tuple[float, float, float, float] | tuple[float, float, float], +) -> tuple[float, float, float]: ... +@overload +def obj_R_G_B(c: None) -> None: ... + +transparent: Color +ReportLabBlueOLD: Color +ReportLabBlue: Color +ReportLabBluePCMYK: Color +ReportLabLightBlue: Color +ReportLabFidBlue: Color +ReportLabFidRed: Color +ReportLabGreen: Color +ReportLabLightGreen: Color +aliceblue: Color +antiquewhite: Color +aqua: Color +aquamarine: Color +azure: Color +beige: Color +bisque: Color +black: Color +blanchedalmond: Color +blue: Color +blueviolet: Color +brown: Color +burlywood: Color +cadetblue: Color +chartreuse: Color +chocolate: Color +coral: Color +cornflowerblue: Color +cornflower: Color +cornsilk: Color +crimson: Color +cyan: Color +darkblue: Color +darkcyan: Color +darkgoldenrod: Color +darkgray: Color +darkgrey: Color +darkgreen: Color +darkkhaki: Color +darkmagenta: Color +darkolivegreen: Color +darkorange: Color +darkorchid: Color +darkred: Color +darksalmon: Color +darkseagreen: Color +darkslateblue: Color +darkslategray: Color +darkslategrey: Color +darkturquoise: Color +darkviolet: Color +deeppink: Color +deepskyblue: Color +dimgray: Color +dimgrey: Color +dodgerblue: Color +firebrick: Color +floralwhite: Color +forestgreen: Color +fuchsia: Color +gainsboro: Color +ghostwhite: Color +gold: Color +goldenrod: Color +gray: Color +grey: Color +green: Color +greenyellow: Color +honeydew: Color +hotpink: Color +indianred: Color +indigo: Color +ivory: Color +khaki: Color +lavender: Color +lavenderblush: Color +lawngreen: Color +lemonchiffon: Color +lightblue: Color +lightcoral: Color +lightcyan: Color +lightgoldenrodyellow: Color +lightgreen: Color +lightgrey: Color +lightpink: Color +lightsalmon: Color +lightseagreen: Color +lightskyblue: Color +lightslategray: Color +lightslategrey: Color +lightsteelblue: Color +lightyellow: Color +lime: Color +limegreen: Color +linen: Color +magenta: Color +maroon: Color +mediumaquamarine: Color +mediumblue: Color +mediumorchid: Color +mediumpurple: Color +mediumseagreen: Color +mediumslateblue: Color +mediumspringgreen: Color +mediumturquoise: Color +mediumvioletred: Color +midnightblue: Color +mintcream: Color +mistyrose: Color +moccasin: Color +navajowhite: Color +navy: Color +oldlace: Color +olive: Color +olivedrab: Color +orange: Color +orangered: Color +orchid: Color +palegoldenrod: Color +palegreen: Color +paleturquoise: Color +palevioletred: Color +papayawhip: Color +peachpuff: Color +peru: Color +pink: Color +plum: Color +powderblue: Color +purple: Color +red: Color +rosybrown: Color +royalblue: Color +saddlebrown: Color +salmon: Color +sandybrown: Color +seagreen: Color +seashell: Color +sienna: Color +silver: Color +skyblue: Color +slateblue: Color +slategray: Color +slategrey: Color +snow: Color +springgreen: Color +steelblue: Color +tan: Color +teal: Color +thistle: Color +tomato: Color +turquoise: Color +violet: Color +wheat: Color +white: Color +whitesmoke: Color +yellow: Color +yellowgreen: Color +fidblue: Color +fidred: Color +fidlightblue: Color +ColorType: type[Color] + +def colorDistance(col1: Color, col2: Color) -> float: ... +def cmykDistance(col1: Color, col2: Color) -> float: ... +def getAllNamedColors() -> dict[str, Color]: ... + +@overload +def describe(aColor: Color, mode: Literal[0] = 0) -> None: ... +@overload +def describe(aColor: Color, mode: Literal[1]) -> str: ... +@overload +def describe(aColor: Color, mode: Literal[2]) -> tuple[str, float]: ... + +def hue2rgb(m1: float, m2: float, h: float) -> float: ... +def hsl2rgb(h: float, s: float, l: float) -> tuple[float, float, float]: ... + +@type_check_only +class _cssParse: + def pcVal(self, v: str, n: str = "argument") -> float: ... + def rgbPcVal(self, v: str) -> float: ... + def rgbVal(self, v: str) -> float: ... + def floatVal(self, v: str) -> float: ... + def hueVal(self, v: str) -> float: ... + def alphaVal(self, v: str, c: float = 1, n: str = "alpha") -> float: ... + s: str + def __call__(self, s: str) -> Color: ... + +cssParse: _cssParse + +@type_check_only +class _toColor: + extraColorsNS: dict[str, Color] + def __init__(self) -> None: ... + def setExtraColorsNameSpace(self, NS: dict[str, Color]) -> None: ... + def __call__(self, arg: _ConvertibleToColor, default: Color | None = None) -> Color: ... + +toColor: _toColor + +@overload +def toColorOrNone(arg: None, default: Color | None) -> None: ... +@overload +def toColorOrNone(arg: _ConvertibleToColor, default: Color | None = None) -> Color: ... + +def setColors(**kw: _ConvertibleToColor) -> None: ... +def Whiter(c: _ColorT, f: float) -> _ColorT: ... +def Blacker(c: _ColorT, f: float) -> _ColorT: ... +def fade(aSpotColor: CMYKColor, percentages: Iterable[float]) -> list[CMYKColor]: ... diff --git a/stubs/reportlab/reportlab/lib/corp.pyi b/stubs/reportlab/reportlab/lib/corp.pyi new file mode 100644 index 000000000000..9c71b4a4cc9f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/corp.pyi @@ -0,0 +1,81 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Final + +from reportlab.graphics.shapes import Drawing, Group +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class RL_CorpLogo(Widget): + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: float + background: Incomplete + border: Incomplete + borderWidth: int + shadow: float + height: int + width: int + x: int + skewX: int + showPage: int + oColors: Incomplete + pageColors: Incomplete + prec: Incomplete + def __init__(self) -> None: ... + def demo(self) -> Drawing: ... + @staticmethod + def applyPrec(P, prec): ... + def draw(self) -> Group: ... + +class RL_CorpLogoReversed(RL_CorpLogo): + background: Incomplete + fillColor: Incomplete + def __init__(self) -> None: ... + +class RL_CorpLogoThin(Widget): + fillColor: Incomplete + strokeColor: Incomplete + x: int + y: int + height: Incomplete + width: Incomplete + def __init__(self) -> None: ... + def demo(self) -> Drawing: ... + def draw(self) -> Group: ... + +class ReportLabLogo: + origin: Incomplete + dimensions: Incomplete + powered_by: Incomplete + def __init__(self, atx: int = 0, aty: int = 0, width=180.0, height=108.0, powered_by: int = 0) -> None: ... + def draw(self, canvas) -> None: ... + +class RL_BusinessCard(Widget): + fillColor: Incomplete + strokeColor: Incomplete + altStrokeColor: Incomplete + x: int + y: int + height: Incomplete + width: Incomplete + borderWidth: Incomplete + bleed: Incomplete + cropMarks: int + border: int + name: str + position: str + telephone: str + mobile: str + fax: str + email: str + web: str + rh_blurb_top: Incomplete + def __init__(self) -> None: ... + def demo(self) -> Drawing: ... + def draw(self) -> Group: ... + +def test(formats: Iterable[str] = ["pdf", "eps", "jpg", "gif", "svg"]) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/enums.pyi b/stubs/reportlab/reportlab/lib/enums.pyi new file mode 100644 index 000000000000..56229718802f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/enums.pyi @@ -0,0 +1,7 @@ +from typing import Final + +__version__: Final[str] +TA_LEFT: Final = 0 +TA_CENTER: Final = 1 +TA_RIGHT: Final = 2 +TA_JUSTIFY: Final = 4 diff --git a/stubs/reportlab/reportlab/lib/extformat.pyi b/stubs/reportlab/reportlab/lib/extformat.pyi new file mode 100644 index 000000000000..4d9f857e35f8 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/extformat.pyi @@ -0,0 +1,9 @@ +from collections.abc import Mapping +from typing import Any, Final + +__version__: Final[str] + +def dictformat( + _format: str, L: Mapping[str, object] | None = {}, G: dict[str, Any] | None = {} # `L` and `G` are passed to `eval` function +) -> str: ... +def magicformat(format: str) -> str: ... diff --git a/stubs/reportlab/reportlab/lib/fontfinder.pyi b/stubs/reportlab/reportlab/lib/fontfinder.pyi new file mode 100644 index 000000000000..1cbcb05c185e --- /dev/null +++ b/stubs/reportlab/reportlab/lib/fontfinder.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from typing import Final +from typing_extensions import LiteralString + +__version__: Final[str] + +def asNative(s) -> str: ... + +EXTENSIONS: Final = [".ttf", ".ttc", ".otf", ".pfb", ".pfa"] +FF_FIXED: Final = 1 +FF_SERIF: Final = 2 +FF_SYMBOLIC: Final = 4 +FF_SCRIPT: Final = 8 +FF_NONSYMBOLIC: Final = 32 +FF_ITALIC: Final = 64 +FF_ALLCAP: Final = 65536 +FF_SMALLCAP: Final = 131072 +FF_FORCEBOLD: Final = 262144 + +class FontDescriptor: + name: Incomplete + fullName: Incomplete + familyName: Incomplete + styleName: Incomplete + isBold: bool + isItalic: bool + isFixedPitch: bool + isSymbolic: bool + typeCode: Incomplete + fileName: Incomplete + metricsFileName: Incomplete + timeModified: int + def __init__(self) -> None: ... + def getTag(self) -> LiteralString: ... + +class FontFinder: + useCache: Incomplete + validate: Incomplete + verbose: Incomplete + def __init__( + self, dirs=[], useCache: bool = True, validate: bool = False, recur: bool = False, fsEncoding=None, verbose: int = 0 + ) -> None: ... + def addDirectory(self, dirName, recur=None) -> None: ... + def addDirectories(self, dirNames, recur=None) -> None: ... + def getFamilyNames(self) -> list[bytes]: ... + def getFontsInFamily(self, familyName): ... + def getFamilyXmlReport(self) -> LiteralString: ... + def getFontsWithAttributes(self, **kwds) -> list[FontDescriptor]: ... + def getFont(self, familyName, bold: bool = False, italic: bool = False) -> FontDescriptor: ... + def save(self, fileName) -> None: ... + def load(self, fileName) -> None: ... + def search(self) -> None: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/lib/fonts.pyi b/stubs/reportlab/reportlab/lib/fonts.pyi new file mode 100644 index 000000000000..665e34909894 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/fonts.pyi @@ -0,0 +1,9 @@ +from typing import Final, Literal, TypeAlias + +_BoolInt: TypeAlias = Literal[0, 1] + +__version__: Final[str] + +def ps2tt(psfn: str) -> tuple[str, _BoolInt, _BoolInt]: ... +def tt2ps(fn: str, b: _BoolInt, i: _BoolInt) -> str: ... +def addMapping(face: str, bold: _BoolInt, italic: _BoolInt, psname: str) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/formatters.pyi b/stubs/reportlab/reportlab/lib/formatters.pyi new file mode 100644 index 000000000000..bb46a3be1d94 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/formatters.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from typing import Literal +from typing_extensions import LiteralString + +class Formatter: + pattern: str + def __init__(self, pattern: str) -> None: ... + def format(self, obj: object) -> str: ... + def __call__(self, x: object) -> str: ... + +class DecimalFormatter(Formatter): + calcPlaces: Incomplete + places: int + dot: Incomplete + comma: Incomplete + prefix: Incomplete + suffix: Incomplete + def __init__( + self, places: int | Literal["auto"] = 2, decimalSep: str = ".", thousandSep=None, prefix=None, suffix=None + ) -> None: ... + def format(self, num) -> LiteralString: ... + +__all__ = ("Formatter", "DecimalFormatter") diff --git a/stubs/reportlab/reportlab/lib/geomutils.pyi b/stubs/reportlab/reportlab/lib/geomutils.pyi new file mode 100644 index 000000000000..1fec093fb40c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/geomutils.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__version__: Final[str] + +def normalizeTRBL(p: float | tuple[float, ...] | list[float]) -> tuple[float, ...]: ... diff --git a/stubs/reportlab/reportlab/lib/logger.pyi b/stubs/reportlab/reportlab/lib/logger.pyi new file mode 100644 index 000000000000..ce7635c168ee --- /dev/null +++ b/stubs/reportlab/reportlab/lib/logger.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +class Logger: + def __init__(self) -> None: ... + def add(self, fp) -> None: ... + def remove(self, fp) -> None: ... + def write(self, text) -> None: ... + def __call__(self, text) -> None: ... + +logger: Logger + +class WarnOnce: + uttered: dict[Incomplete, Incomplete] + pfx: str + enabled: bool | int + def __init__(self, kind: str = "Warn") -> None: ... + def once(self, warning) -> None: ... + def __call__(self, warning) -> None: ... + +warnOnce: WarnOnce +infoOnce: WarnOnce diff --git a/stubs/reportlab/reportlab/lib/normalDate.pyi b/stubs/reportlab/reportlab/lib/normalDate.pyi new file mode 100644 index 000000000000..98e40086381d --- /dev/null +++ b/stubs/reportlab/reportlab/lib/normalDate.pyi @@ -0,0 +1,83 @@ +from _typeshed import ConvertibleToInt +from typing import Final, Literal +from typing_extensions import Self + +__version__: Final[str] + +def getStdMonthNames() -> list[str]: ... +def getStdShortMonthNames() -> list[str]: ... +def getStdDayNames() -> list[str]: ... +def getStdShortDayNames() -> list[str]: ... +def isLeapYear(year: int) -> Literal[0, 1]: ... + +class NormalDateException(Exception): ... + +class NormalDate: + def __init__(self, normalDate=None) -> None: ... + def add(self, days) -> None: ... + def __add__(self, days: int) -> Self: ... + def __radd__(self, days: int) -> Self: ... + def clone(self) -> Self: ... + def __lt__(self, other) -> bool: ... + def __le__(self, other) -> bool: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __ge__(self, other) -> bool: ... + def __gt__(self, other) -> bool: ... + def day(self) -> int: ... + def dayOfWeek(self) -> int: ... + @property + def __day_of_week_name__(self): ... + def dayOfWeekAbbrev(self): ... + def dayOfWeekName(self): ... + def dayOfYear(self) -> int: ... + def daysBetweenDates(self, normalDate) -> int: ... + def equals(self, target) -> bool | Literal[0]: ... + def endOfMonth(self) -> Self: ... + def firstDayOfMonth(self) -> Self: ... + def formatUS(self) -> str: ... + def formatUSCentury(self) -> str: ... + def formatMS(self, fmt): ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def isLeapYear(self) -> Literal[0, 1]: ... + def lastDayOfMonth(self) -> int: ... + def localeFormat(self) -> str: ... + def month(self) -> int: ... + @property + def __month_name__(self): ... + def monthAbbrev(self): ... + def monthName(self): ... + def normalize(self, scalar) -> None: ... + def range(self, days) -> list[NormalDate]: ... + def scalar(self) -> int: ... + def setDay(self, day) -> None: ... + def setMonth(self, month) -> None: ... + normalDate: int | None + def setNormalDate(self, normalDate) -> None: ... + def setYear(self, year) -> None: ... + def __sub__(self, v): ... + def __rsub__(self, v): ... + def toTuple(self) -> tuple[int, int, int]: ... + def year(self) -> int: ... + +def bigBang() -> NormalDate: ... +def bigCrunch() -> NormalDate: ... +def dayOfWeek(y: int, m: int, d: int) -> int: ... +def firstDayOfYear(year: int) -> int: ... +def FND(d): ... + +Epoch: NormalDate +ND = NormalDate +BDEpoch: ND +BDEpochScalar: int + +class BusinessDate(NormalDate): + def add(self, days: int) -> None: ... + def __add__(self, days: int) -> Self: ... + def __sub__(self, v): ... + def asNormalDate(self) -> ND: ... + def daysBetweenDates(self, normalDate) -> int: ... + def normalize(self, i: ConvertibleToInt) -> None: ... + def scalar(self): ... + def setNormalDate(self, normalDate) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/pagesizes.pyi b/stubs/reportlab/reportlab/lib/pagesizes.pyi new file mode 100644 index 000000000000..617b42c9338c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/pagesizes.pyi @@ -0,0 +1,51 @@ +from typing import Final + +__version__: Final[str] +A0: Final[tuple[float, float]] +A1: Final[tuple[float, float]] +A2: Final[tuple[float, float]] +A3: Final[tuple[float, float]] +A4: Final[tuple[float, float]] +A5: Final[tuple[float, float]] +A6: Final[tuple[float, float]] +A7: Final[tuple[float, float]] +A8: Final[tuple[float, float]] +A9: Final[tuple[float, float]] +A10: Final[tuple[float, float]] +B0: Final[tuple[float, float]] +B1: Final[tuple[float, float]] +B2: Final[tuple[float, float]] +B3: Final[tuple[float, float]] +B4: Final[tuple[float, float]] +B5: Final[tuple[float, float]] +B6: Final[tuple[float, float]] +B7: Final[tuple[float, float]] +B8: Final[tuple[float, float]] +B9: Final[tuple[float, float]] +B10: Final[tuple[float, float]] +C0: Final[tuple[float, float]] +C1: Final[tuple[float, float]] +C2: Final[tuple[float, float]] +C3: Final[tuple[float, float]] +C4: Final[tuple[float, float]] +C5: Final[tuple[float, float]] +C6: Final[tuple[float, float]] +C7: Final[tuple[float, float]] +C8: Final[tuple[float, float]] +C9: Final[tuple[float, float]] +C10: Final[tuple[float, float]] +LETTER: Final[tuple[float, float]] +LEGAL: Final[tuple[float, float]] +ELEVENSEVENTEEN: Final[tuple[float, float]] +JUNIOR_LEGAL: Final[tuple[float, float]] +HALF_LETTER: Final[tuple[float, float]] +GOV_LETTER: Final[tuple[float, float]] +GOV_LEGAL: Final[tuple[float, float]] +TABLOID: Final[tuple[float, float]] +LEDGER: Final[tuple[float, float]] +letter: Final[tuple[float, float]] +legal: Final[tuple[float, float]] +elevenSeventeen: Final[tuple[float, float]] + +def landscape(pagesize: tuple[float, float]) -> tuple[float, float]: ... +def portrait(pagesize: tuple[float, float]) -> tuple[float, float]: ... diff --git a/stubs/reportlab/reportlab/lib/pdfencrypt.pyi b/stubs/reportlab/reportlab/lib/pdfencrypt.pyi new file mode 100644 index 000000000000..50e9e4ba13de --- /dev/null +++ b/stubs/reportlab/reportlab/lib/pdfencrypt.pyi @@ -0,0 +1,133 @@ +import os +from _typeshed import Incomplete +from typing import Final + +from reportlab.pdfbase.pdfdoc import PDFObject +from reportlab.platypus.flowables import Flowable + +__version__: Final[str] + +def xorKey(num: int, key: bytes) -> bytes: ... + +CLOBBERID: int +CLOBBERPERMISSIONS: int +DEBUG: int +reserved1: int +reserved2: int +printable: int +modifiable: int +copypastable: int +annotatable: int +higherbits: int + +os_urandom = os.urandom + +class StandardEncryption: + prepared: int + userPassword: Incomplete + ownerPassword: Incomplete + revision: int + canPrint: Incomplete + canModify: Incomplete + canCopy: Incomplete + canAnnotate: Incomplete + O: Incomplete + def __init__( + self, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength=None, + ) -> None: ... + def setAllPermissions(self, value) -> None: ... + def permissionBits(self) -> int: ... + def encode(self, t) -> bytes: ... + P: Incomplete + key: Incomplete + U: Incomplete + UE: Incomplete + OE: Incomplete + Perms: Incomplete + objnum: Incomplete + def prepare(self, document, overrideID=None) -> None: ... + version: Incomplete + def register(self, objnum, version) -> None: ... + def info(self) -> StandardEncryptionDictionary: ... + +class StandardEncryptionDictionary(PDFObject): + __RefOnly__: int + revision: Incomplete + def __init__(self, O, OE, U, UE, P, Perms, revision) -> None: ... + def format(self, document) -> bytes: ... + +padding: str + +def hexText(text: str | bytes | bytearray) -> str: ... +def unHexText(hexText) -> bytes: ... + +PadString: bytes + +def checkRevision(revision): ... +def encryptionkey(password, OwnerKey, Permissions, FileId1, revision=None) -> bytes: ... +def computeO(userPassword, ownerPassword, revision) -> bytes: ... +def computeU( + encryptionkey, + encodestring=b"(\xbfN^Nu\x8aAd\x00NV\xff\xfa\x01\x08..\x00\xb6\xd0h>\x80/\x0c\xa9\xfedSiz", + revision=None, + documentId=None, +) -> bytes: ... +def checkU(encryptionkey, U) -> None: ... +def encodePDF(key, objectNumber, generationNumber, string, revision=None) -> bytes: ... +def equalityCheck(observed, expected, label) -> None: ... +def test() -> None: ... +def encryptCanvas( + canvas, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> None: ... + +class EncryptionFlowable(StandardEncryption, Flowable): + def wrap(self, availWidth, availHeight): ... + def draw(self) -> None: ... + +def encryptDocTemplate( + dt, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> None: ... +def encryptPdfInMemory( + inputPDF, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> bytes: ... +def encryptPdfOnDisk( + inputFileName, + outputFileName, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> int: ... +def scriptInterp() -> None: ... +def main() -> None: ... diff --git a/stubs/reportlab/reportlab/lib/pygments2xpre.pyi b/stubs/reportlab/reportlab/lib/pygments2xpre.pyi new file mode 100644 index 000000000000..b18d5296345f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/pygments2xpre.pyi @@ -0,0 +1,3 @@ +__all__ = ("pygments2xpre",) + +def pygments2xpre(s, language: str = "python"): ... diff --git a/stubs/reportlab/reportlab/lib/randomtext.pyi b/stubs/reportlab/reportlab/lib/randomtext.pyi new file mode 100644 index 000000000000..121b100edcd3 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/randomtext.pyi @@ -0,0 +1,19 @@ +from collections.abc import Sequence +from typing import Final + +__version__: Final[str] +STARTUP: Final[Sequence[str]] +COMPUTERS: Final[Sequence[str]] +BLAH: Final[Sequence[str]] +BUZZWORD: Final[Sequence[str]] +STARTREK: Final[Sequence[str]] +PRINTING: Final[Sequence[str]] +PYTHON: Final[Sequence[str]] +leadins: Final[Sequence[str]] +subjects: Final[Sequence[str]] +verbs: Final[Sequence[str]] +objects: Final[Sequence[str]] + +def format_wisdom(text: str, line_length: int = 72) -> str: ... +def chomsky(times: int = 1) -> str: ... +def randomText(theme: str | Sequence[str] = ..., sentences: int = 5) -> str: ... diff --git a/stubs/reportlab/reportlab/lib/rl_accel.pyi b/stubs/reportlab/reportlab/lib/rl_accel.pyi new file mode 100644 index 000000000000..fb6dcc74b0a4 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rl_accel.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import Literal + +def fp_str(*a) -> str: ... +def unicode2T1(utext, fonts) -> list[tuple[Incomplete, Incomplete]]: ... +def instanceStringWidthT1(self, text: str, size: float, encoding: str = "utf8") -> float: ... +def instanceStringWidthTTF(self, text: str, size: float, encoding: str = "utf8") -> float: ... +def hex32(i) -> str: ... +def add32(x: int, y: int) -> int: ... +def calcChecksum(data: str | bytes) -> int: ... +def escapePDF(s) -> str: ... +def asciiBase85Encode(input: str) -> str: ... +def asciiBase85Decode(input) -> bytes: ... +def sameFrag(f, g) -> bool | Literal[0]: ... + +__all__ = [ + "fp_str", + "unicode2T1", + "instanceStringWidthT1", + "instanceStringWidthTTF", + "asciiBase85Encode", + "asciiBase85Decode", + "escapePDF", + "sameFrag", + "calcChecksum", + "add32", + "hex32", +] diff --git a/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi b/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi new file mode 100644 index 000000000000..e70536e3ee0f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi @@ -0,0 +1,237 @@ +import ast +import math +import re +import time +from _typeshed import Incomplete +from collections.abc import Generator +from typing_extensions import Never, Self + +eval_debug: int +strTypes: tuple[type[bytes], type[str]] +isPy39: bool +isPy313: bool + +class BadCode(ValueError): ... + +augOps: dict[ast.operator, str] +__allowed_magic_methods__: frozenset[str] +__rl_unsafe__: frozenset[str] +__rl_unsafe_re__: re.Pattern[str] + +def copy_locations(new_node, old_node) -> None: ... + +class UntrustedAstTransformer(ast.NodeTransformer): + names_seen: Incomplete + nameIsAllowed: Incomplete + def __init__(self, names_seen=None, nameIsAllowed=None) -> None: ... + @property + def tmpName(self) -> str: ... + def error(self, node, msg) -> Never: ... + def guard_iter(self, node): ... + def is_starred(self, ob): ... + def gen_unpack_spec(self, tpl) -> ast.Dict: ... + def protect_unpack_sequence(self, target, value) -> ast.Call: ... + def gen_unpack_wrapper(self, node, target, ctx: str = "store") -> tuple[ast.Name, ast.Try]: ... + def gen_lambda(self, args, body) -> ast.Lambda: ... + def gen_del_stmt(self, name_to_del) -> ast.Delete: ... + def transform_slice(self, slice_): ... + def isAllowedName(self, node, name) -> None: ... + def check_function_argument_names(self, node) -> None: ... + def check_import_names(self, node) -> ast.AST: ... + def gen_attr_check(self, node, attr_name) -> ast.BoolOp: ... + def visit_Constant(self, node) -> ast.AST: ... + def visit_Name(self, node) -> ast.AST: ... + def visit_Call(self, node) -> ast.AST: ... + def visit_Attribute(self, node) -> ast.AST: ... + def visit_Subscript(self, node) -> ast.AST: ... + def visit_Assign(self, node): ... + def visit_AugAssign(self, node) -> ast.Assign: ... + # Bug in `reportlab`'s source code: + def visit_While(node): ... # type: ignore[override] + def visit_ExceptHandler(self, node) -> ast.AST: ... + def visit_With(self, node) -> ast.AST: ... + def visit_FunctionDef(self, node) -> ast.AST: ... + def visit_Lambda(self, node) -> ast.AST: ... + def visit_ClassDef(self, node) -> ast.stmt: ... + def visit_Import(self, node) -> ast.AST: ... + def visit_BinOp(self, node): ... + visit_ImportFrom = visit_Import # pyright: ignore[reportAssignmentType] + visit_For = guard_iter + visit_comprehension = guard_iter + def generic_visit(self, node: ast.AST) -> None: ... # type: ignore[override] + def not_allowed(self, node: ast.AST) -> Never: ... + def visit_children(self, node) -> ast.AST: ... + def visit(self, node): ... + visit_Ellipsis = not_allowed + visit_MatMult = not_allowed + visit_Exec = not_allowed + visit_Nonlocal = not_allowed + visit_AsyncFunctionDef = not_allowed + visit_Await = not_allowed + visit_AsyncFor = not_allowed + visit_AsyncWith = not_allowed + visit_Print = not_allowed + visit_Num = visit_children + visit_Str = visit_children + visit_Bytes = visit_children + visit_List = visit_children + visit_Tuple = visit_children + visit_Set = visit_children + visit_Dict = visit_children + visit_FormattedValue = visit_children + visit_JoinedStr = visit_children + visit_NameConstant = visit_children + visit_Load = visit_children + visit_Store = visit_children + visit_Del = visit_children + visit_Starred = visit_children + visit_Expression = visit_children + visit_Expr = visit_children + visit_UnaryOp = visit_children + visit_UAdd = visit_children + visit_USub = visit_children + visit_Not = visit_children + visit_Invert = visit_children + visit_Add = visit_children + visit_Sub = visit_children + visit_Mult = visit_children + visit_Div = visit_children + visit_FloorDiv = visit_children + visit_Pow = visit_children + visit_Mod = visit_children + visit_LShift = visit_children + visit_RShift = visit_children + visit_BitOr = visit_children + visit_BitXor = visit_children + visit_BitAnd = visit_children + visit_BoolOp = visit_children + visit_And = visit_children + visit_Or = visit_children + visit_Compare = visit_children + visit_Eq = visit_children + visit_NotEq = visit_children + visit_Lt = visit_children + visit_LtE = visit_children + visit_Gt = visit_children + visit_GtE = visit_children + visit_Is = visit_children + visit_IsNot = visit_children + visit_In = visit_children + visit_NotIn = visit_children + visit_keyword = visit_children + visit_IfExp = visit_children + visit_Index = visit_children + visit_Slice = visit_children + visit_ExtSlice = visit_children + visit_ListComp = visit_children + visit_SetComp = visit_children + visit_GeneratorExp = visit_children + visit_DictComp = visit_children + visit_Raise = visit_children + visit_Assert = visit_children + visit_Delete = visit_children + visit_Pass = visit_children + visit_alias = visit_children + visit_If = visit_children + visit_Break = visit_children + visit_Continue = visit_children + visit_Try = visit_children + visit_TryFinally = visit_children + visit_TryExcept = visit_children + visit_withitem = visit_children + visit_arguments = visit_children + visit_arg = visit_children + visit_Return = visit_children + visit_Yield = visit_children + visit_YieldFrom = visit_children + visit_Global = visit_children + visit_Module = visit_children + visit_Param = visit_children + +def astFormat(node): ... + +class __rl_SafeIter__: + __rl_iter__: Incomplete + __rl_owner__: Incomplete + def __init__(self, it, owner) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self): ... + next = __next__ + +__rl_safe_builtins__: Incomplete + +def safer_globals(g=None): ... + +math_log10 = math.log10 +__rl_undef__: Incomplete + +class __RL_SAFE_ENV__: + __time_time__ = time.time + __weakref_ref__: Incomplete + __slicetype__: Incomplete + timeout: Incomplete + allowed_magic_methods: Incomplete + __rl_gen_range__: Incomplete + __rl_real_iter__: Incomplete + real_bi: Incomplete + bi_replace: Incomplete + __rl_builtins__: Incomplete + def __init__(self, timeout=None, allowed_magic_methods=None, allowed_magic_names=None) -> None: ... + def __rl_type__(self, *args): ... + def __rl_check__(self) -> None: ... + def __rl_sd__(self, obj): ... + def __rl_getiter__(self, it): ... + def __rl_max__(self, arg, *args, **kwds): ... + def __rl_min__(self, arg, *args, **kwds): ... + def __rl_sum__(self, sequence, start: int = 0): ... + def __rl_enumerate__(self, seq): ... + def __rl_zip__(self, *args): ... + def __rl_hasattr__(self, obj, name): ... + def __rl_filter__(self, f, seq): ... + def __rl_map__(self, f, seq): ... + def __rl_any__(self, seq): ... + def __rl_all__(self, seq): ... + def __rl_sorted__(self, seq, **kwds): ... + def __rl_reversed__(self, seq): ... + def __rl_range__(self, start, *args): ... + def __rl_set__(self, it): ... + def __rl_frozenset__(self, it=()): ... + def __rl_iter_unpack_sequence__(self, it, spec, _getiter_) -> Generator[Incomplete]: ... + def __rl_unpack_sequence__(self, it, spec, _getiter_): ... + def __rl_is_allowed_name__(self, name, crash: bool = True) -> bool: ... + def __rl_getattr__(self, obj, a, *args): ... + def __rl_getitem__(self, obj, a): ... + __rl_tmax__: int + __rl_max_len__: int + __rl_max_pow_digits__: int + def __rl_add__(self, a, b): ... + def __rl_mult__(self, a, b): ... + def __rl_pow__(self, a, b): ... + def __rl_augAssign__(self, op, v, i): ... + def __rl_apply__(self, func, args, kwds): ... + def __rl_args_iter__(self, *args): ... + def __rl_list__(self, it): ... + def __rl_compile__( + self, src, fname: str = "", mode: str = "eval", flags: int = 0, inherit: bool = True, visit=None + ): ... + __rl_limit__: Incomplete + def __rl_safe_eval__( + self, expr, g, l, mode, timeout=None, allowed_magic_methods=None, __frame_depth__: int = 3, allowed_magic_names=None + ): ... + +class __rl_safe_eval__: + mode: str + env: Incomplete + def __init__(self) -> None: ... + def __call__(self, expr, g=None, l=None, timeout=None, allowed_magic_methods=None, allowed_magic_names=None): ... + +class __rl_safe_exec__(__rl_safe_eval__): + mode: str + +def rl_extended_literal_eval(expr, safe_callables=None, safe_names=None): ... + +rl_safe_exec: __rl_safe_exec__ +rl_safe_eval: __rl_safe_eval__ + +def __fix_set__(value, default=...): ... +def rl_less_safe_eval(expr, NS): ... diff --git a/stubs/reportlab/reportlab/lib/rltempfile.pyi b/stubs/reportlab/reportlab/lib/rltempfile.pyi new file mode 100644 index 000000000000..95675a82ce2b --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rltempfile.pyi @@ -0,0 +1,5 @@ +def get_rl_tempdir(*subdirs: str) -> str: ... +def get_rl_tempfile(fn: str | None = None) -> str: ... + +# The duplicate entry matches the runtime __all__. +__all__ = ("get_rl_tempdir", "get_rl_tempdir") # ruff: ignore[duplicate-entry-in-dunder-all] diff --git a/stubs/reportlab/reportlab/lib/rparsexml.pyi b/stubs/reportlab/reportlab/lib/rparsexml.pyi new file mode 100644 index 000000000000..bbfc9002a478 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rparsexml.pyi @@ -0,0 +1,34 @@ +from _typeshed import FileDescriptorOrPath, Unused +from collections.abc import Iterable +from typing import Final, type_check_only + +simpleparse: int + +@type_check_only +class _smartDecode: + @staticmethod + def __call__(s: str | bytes | bytearray) -> str: ... + +smartDecode: _smartDecode +NONAME: Final = "" +NAMEKEY: Final = 0 +CONTENTSKEY: Final = 1 +CDATAMARKER: Final = "" +replacelist: list[tuple[str, str]] + +def unEscapeContentList(contentList: Iterable[str]) -> list[str]: ... +def parsexmlSimple(xmltext, oneOutermostTag: int = 0, eoCB: Unused = None, entityReplacer=...): ... + +parsexml = parsexmlSimple + +def parseFile(filename: FileDescriptorOrPath): ... + +verbose: int + +def skip_prologue(text, cursor): ... +def parsexml0(xmltext, startingat: int = 0, toplevel: int = 1, entityReplacer=...): ... +def pprettyprint(parsedxml): ... +def testparse(s, dump: int = 0) -> None: ... +def test(dump: int = 0) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/sequencer.pyi b/stubs/reportlab/reportlab/lib/sequencer.pyi new file mode 100644 index 000000000000..f7fd2029ba72 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/sequencer.pyi @@ -0,0 +1,39 @@ +from collections.abc import Callable + +__all__ = ["Sequencer", "getSequencer", "setSequencer"] + +from typing import overload + +class _Counter: + _value: int + def __init__(self) -> None: ... + def setFormatter(self, formatFunc: Callable[[int], str]) -> None: ... + def reset(self, value: int | None = None) -> None: ... + def next(self) -> int: ... + __next__ = next + def _this(self) -> int: ... + def nextf(self) -> str: ... + def thisf(self) -> str: ... + def chain(self, otherCounter: _Counter) -> None: ... + +class Sequencer: + def __init__(self) -> None: ... + def __next__(self) -> int: ... + def next(self, counter=None) -> int: ... + def thisf(self, counter=None) -> str: ... + def nextf(self, counter=None) -> str: ... + def setDefaultCounter(self, default=None) -> None: ... + def registerFormat(self, format: str, func: Callable[[int], str]) -> None: ... + def setFormat(self, counter, format: str) -> None: ... + def reset(self, counter=None, base: int = 0) -> None: ... + def chain(self, parent, child) -> None: ... + def __getitem__(self, key: str) -> str: ... + def format(self, template: str) -> str: ... + def dump(self) -> None: ... + +def getSequencer() -> Sequencer: ... + +@overload +def setSequencer(seq: Sequencer) -> Sequencer: ... +@overload +def setSequencer(seq: None) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/styles.pyi b/stubs/reportlab/reportlab/lib/styles.pyi new file mode 100644 index 000000000000..6e550700e5eb --- /dev/null +++ b/stubs/reportlab/reportlab/lib/styles.pyi @@ -0,0 +1,185 @@ +from _typeshed import Incomplete +from typing import Any, ClassVar, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from reportlab.lib.colors import Color + +_AlignmentEnum: TypeAlias = Literal[0, 1, 2, 4] +# FIXME: There are some places in the code that expect upper-case versions +# so I'm unsure whether those would work in stylesheets as well +_AlignmentStr: TypeAlias = Literal["left", "center", "centre", "right", "justify"] +_Alignment: TypeAlias = _AlignmentEnum | _AlignmentStr +_T = TypeVar("_T") + +class PropertySet: + defaults: ClassVar[dict[str, Any]] + name: str + parent: PropertySet | None + def __init__(self, name: str, parent: PropertySet | None = None, **kw: Any) -> None: ... + def refresh(self) -> None: ... + def listAttrs(self, indent: str = "") -> None: ... + def clone(self, name: str, parent: PropertySet | None = None, **kwds: Any) -> Self: ... + # PropertySet can have arbitrary attributes + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +class ParagraphStyle(PropertySet): + # NOTE: We list the attributes this has for sure due to defaults + fontName: str + fontSize: float + leading: float + leftIndent: float + rightIndent: float + firstLineIndent: float + alignment: _Alignment + spaceBefore: float + spaceAfter: float + bulletFontName: str + bulletFontSize: float + bulletIndent: float + textColor: Color + backColor: Color | None + wordWrap: Incomplete | None + borderWidth: float + borderPadding: float + borderColor: Color | None + borderRadius: float | None + allowWidows: Incomplete + allowOrphans: Incomplete + textTransform: Incomplete | None + endDots: Incomplete | None + splitLongWords: Incomplete + underlineWidth: float + bulletAnchor: Literal["start", "middle", "end"] | float + justifyLastLine: Incomplete + justifyBreaks: Incomplete + spaceShrinkage: float + strikeWidth: float + underlineOffset: float + underlineGap: float + strikeOffset: float + strikeGap: float + linkUnderline: Incomplete + underlineColor: Color | None + strikeColor: Color | None + hyphenationLang: str + embeddedHyphenation: Incomplete + uriWasteReduce: float + # NOTE: We redefine __init__ for the same reason + def __init__( + self, + name: str, + parent: PropertySet | None = None, + *, + fontName: str = ..., + fontSize: float = ..., + leading: float = ..., + leftIndent: float = ..., + rightIndent: float = ..., + firstLineIndent: float = ..., + alignment: _Alignment = ..., + spaceBefore: float = ..., + spaceAfter: float = ..., + bulletFontName: str = ..., + bulletFontSize: float = ..., + bulletIndent: float = ..., + textColor: Color = ..., + backColor: Color | None = ..., + wordWrap: Incomplete | None = ..., + borderWidth: float = ..., + borderPadding: float = ..., + borderColor: Color | None = ..., + borderRadius: float | None = ..., + allowWidows=..., + allowOrphans=..., + textTransform: Incomplete | None = ..., + endDots: Incomplete | None = ..., + splitLongWords=..., + underlineWidth: float = ..., + bulletAnchor: Literal["start", "middle", "end"] | float = ..., + justifyLastLine=..., + justifyBreaks=..., + spaceShrinkage: float = ..., + strikeWidth: float = ..., + underlineOffset: float = ..., + underlineGap: float = ..., + strikeOffset: float = ..., + strikeGap: float = ..., + linkUnderline=..., + underlineColor: Color | None = ..., + strikeColor: Color | None = ..., + hyphenationLang: str = ..., + embeddedHyphenation=..., + uriWasteReduce: float = ..., + **kw: Any, + ) -> None: ... + +def str2alignment( + v: _AlignmentStr, + __map__: dict[_AlignmentStr, _AlignmentEnum] = {"centre": 1, "center": 1, "left": 0, "right": 2, "justify": 4}, +) -> _AlignmentEnum: ... + +class LineStyle(PropertySet): + # NOTE: We list the attributes this has for sure due to defaults + width: float + color: Color + def prepareCanvas(self, canvas) -> None: ... + # NOTE: We redefine __init__ for the same reason + def __init__( + self, name: str, parent: PropertySet | None = None, *, width: float = ..., color: Color = ..., **kw: Any + ) -> None: ... + +class ListStyle(PropertySet): + # NOTE: We list the attributes this has for sure due to defaults + leftIndent: float + rightIndent: float + bulletAlign: _Alignment + bulletType: str + bulletColor: Color + bulletFontName: str + bulletFontSize: float + bulletOffsetY: float + bulletDedent: Incomplete + bulletDir: Incomplete + bulletFormat: Incomplete | None + start: Incomplete | None + # NOTE: We redefine __init__ for the same reason + def __init__( + self, + name: str, + parent: PropertySet | None = None, + *, + leftIndent: float = ..., + rightIndent: float = ..., + bulletAlign: _Alignment = ..., + bulletType: str = ..., + bulletColor: Color = ..., + bulletFontName: str = ..., + bulletFontSize: float = ..., + bulletOffsetY: float = ..., + bulletDedent=..., + bulletDir=..., + bulletFormat: Incomplete | None = ..., + start: Incomplete | None = ..., + **kw: Any, + ) -> None: ... + +class StyleSheet1: + byName: dict[str, PropertySet] + byAlias: dict[str, PropertySet] + def __init__(self) -> None: ... + def __getitem__(self, key: str) -> PropertySet: ... + + @overload + def get(self, key: str) -> PropertySet: ... + @overload + def get(self, key: str, default: _T) -> PropertySet | _T: ... + + def __contains__(self, key: str) -> bool: ... + def has_key(self, key: str) -> bool: ... + def add(self, style: PropertySet, alias: str | None = None) -> None: ... + def list(self) -> None: ... + +def getSampleStyleSheet() -> StyleSheet1: ... + +__all__ = ("PropertySet", "ParagraphStyle", "str2alignment", "LineStyle", "ListStyle", "StyleSheet1", "getSampleStyleSheet") diff --git a/stubs/reportlab/reportlab/lib/testutils.pyi b/stubs/reportlab/reportlab/lib/testutils.pyi new file mode 100644 index 000000000000..7a55147e3739 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/testutils.pyi @@ -0,0 +1,74 @@ +import re +import unittest +from _typeshed import Incomplete, StrPath, Unused +from configparser import ConfigParser, _SectionName +from types import ModuleType +from typing import Final, Literal + +__version__: Final[str] + +def invariantSeed(n: float | str | bytes | bytearray | None) -> None: ... +def haveRenderPM() -> ModuleType | Literal[False]: ... + +DEJAVUSANS: Final = ("DejaVuSans", "DejaVuSans-Bold", "DejaVuSans-Oblique", "DejaVuSans-BoldOblique") + +def haveDejaVu() -> bool: ... +def isWritable(D: Unused) -> Literal[0, 1]: ... + +RL_HOME: str | None +testsFolder: str | None + +def setOutDir(name: str) -> str: ... +def mockUrlRead(name: str): ... +def outputfile(fn: StrPath | None) -> str: ... +def printLocation(depth: int = 1) -> None: ... +def makeSuiteForClasses(*classes: type[unittest.TestCase], testMethodPrefix: str | None = None) -> unittest.TestSuite: ... +def getCVSEntries(folder: StrPath, files: bool | Literal[1, 0] = 1, folders: bool | Literal[1, 0] = 0) -> list[str]: ... + +class ExtConfigParser(ConfigParser): + pat: re.Pattern[str] + def getstringlist(self, section: _SectionName, option: str): ... + +class GlobDirectoryWalker: + index: int + pattern: str + stack: list[str] + files: list[str] + directory: str + def __init__(self, directory: str, pattern: str = "*") -> None: ... + def __getitem__(self, index) -> str | None: ... + def filterFiles(self, folder, files): ... + +class RestrictedGlobDirectoryWalker(GlobDirectoryWalker): + ignorePatterns: Incomplete + def __init__(self, directory, pattern: str = "*", ignore=None) -> None: ... + def filterFiles(self, folder, files): ... + +class CVSGlobDirectoryWalker(GlobDirectoryWalker): + def filterFiles(self, folder, files): ... + +class SecureTestCase(unittest.TestCase): + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + +class NearTestCase(unittest.TestCase): + @staticmethod + def assertNear(a, b, accuracy: float = 1e-05) -> None: ... + +class ScriptThatMakesFileTest(unittest.TestCase): + scriptDir: Incomplete + scriptName: Incomplete + outFileName: Incomplete + verbose: Incomplete + def __init__(self, scriptDir, scriptName, outFileName, verbose: int = 0) -> None: ... + cwd: Incomplete + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + def runTest(self) -> None: ... + +def equalStrings(a: str | bytes, b: str | bytes, enc: str = "utf8") -> bool: ... +def eqCheck(r, x) -> None: ... +def rlextraNeeded() -> bool: ... +def rlSkipIf(cond, reason, __module__=None): ... +def rlSkipUnless(cond, reason, __module__=None): ... +def rlSkip(reason, __module__=None): ... diff --git a/stubs/reportlab/reportlab/lib/textsplit.pyi b/stubs/reportlab/reportlab/lib/textsplit.pyi new file mode 100644 index 000000000000..8ad3489c99a2 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/textsplit.pyi @@ -0,0 +1,20 @@ +import re +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Sequence +from typing import Final + +__version__: Final[str] +CANNOT_START_LINE: Final[Sequence[str]] +ALL_CANNOT_START: Final[str] +CANNOT_END_LINE: Final[Sequence[str]] +ALL_CANNOT_END: Final[str] + +def is_multi_byte(ch: str | bytes | bytearray) -> bool: ... +def getCharWidths(word: str, fontName: str, fontSize: float) -> list[float]: ... +def wordSplit(word, maxWidths, fontName, fontSize, encoding: str = "utf8") -> list[list[Incomplete]]: ... +def dumbSplit(word, widths, maxWidths) -> list[list[Incomplete]]: ... +def kinsokuShoriSplit(word, widths, availWidth) -> None: ... + +rx: re.Pattern[str] + +def cjkwrap(text: ReadableBuffer, width: float, encoding: str = "utf8"): ... diff --git a/stubs/reportlab/reportlab/lib/units.pyi b/stubs/reportlab/reportlab/lib/units.pyi new file mode 100644 index 000000000000..c22f629a211c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/units.pyi @@ -0,0 +1,9 @@ +from typing import Final + +__version__: Final[str] +inch: Final[float] +cm: Final[float] +mm: Final[float] +pica: Final[float] + +def toLength(s: str) -> float: ... diff --git a/stubs/reportlab/reportlab/lib/utils.pyi b/stubs/reportlab/reportlab/lib/utils.pyi new file mode 100644 index 000000000000..6ea6a6d1ea32 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/utils.pyi @@ -0,0 +1,221 @@ +import datetime as _datetime +import zipimport +from _typeshed import Incomplete, SupportsItems +from builtins import _ClassInfo +from collections.abc import Generator, Iterable, MutableMapping +from os import PathLike +from time import _TimeTuple, struct_time +from types import TracebackType +from typing import AnyStr, Final, Literal, TypeVar, overload, type_check_only +from typing_extensions import TypeIs +from urllib.request import _UrlopenRet + +from reportlab.lib.rltempfile import get_rl_tempdir as get_rl_tempdir, get_rl_tempfile as get_rl_tempfile + +from .rl_safe_eval import ( + rl_extended_literal_eval as rl_extended_literal_eval, + rl_safe_exec as rl_safe_exec, + safer_globals as safer_globals, +) + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +__version__: Final[str] + +@type_check_only +class _UNSET_: + @staticmethod + def __bool__() -> Literal[False]: ... + +__UNSET__: Final[_UNSET_] + +isPyPy: bool + +def isFunction(v: object) -> bool: ... +def isMethod(v: object, mt: type = ...) -> bool: ... +def isModule(v: object) -> bool: ... +def isSeq(v: object, _st: _ClassInfo = ...) -> bool: ... +def isNative(v: object) -> TypeIs[str]: ... + +strTypes: tuple[type[str], type[bytes]] + +def asBytes(v: str | bytes, enc: str = "utf8") -> bytes: ... +def asUnicode(v: str | bytes, enc: str = "utf8") -> str: ... +def asUnicodeEx(v: str | bytes, enc: str = "utf8") -> str: ... +def asNative(v: str | bytes, enc: str = "utf8") -> str: ... +def int2Byte(i: int) -> bytes: ... +def isStr(v: object) -> TypeIs[str | bytes]: ... +def isBytes(v: object) -> TypeIs[bytes]: ... +def isUnicode(v: object) -> TypeIs[str]: ... +def isClass(v: object) -> TypeIs[type]: ... +def isNonPrimitiveInstance(x: object) -> bool: ... +def instantiated(v: object) -> bool: ... +def bytestr(x: object, enc: str = "utf8") -> bytes: ... +def encode_label(args) -> str: ... +def decode_label(label: str): ... +def rawUnicode(s: str | bytes) -> str: ... +def rawBytes(s: str | bytes) -> bytes: ... + +rl_exec = exec + +def char2int(s: int | str | bytes) -> int: ... +def rl_reraise(t, v: BaseException, b: TracebackType | None = None) -> None: ... +def rl_add_builtins(**kwd) -> None: ... +def zipImported(ldr: zipimport.zipimporter | None = None) -> zipimport.zipimporter | None: ... + +class CIDict(dict[_KT, _VT]): + def __init__(self, *args, **kwds) -> None: ... + def update(self, D: SupportsItems[_KT, _VT]) -> None: ... # type: ignore[override] + +def markfilename(filename, creatorcode=None, filetype=None): ... + +__rl_loader__: Incomplete + +def rl_glob(pattern: AnyStr, glob=...) -> list[AnyStr]: ... +def isFileSystemDistro() -> bool: ... +def isCompactDistro() -> bool: ... +def isSourceDistro() -> bool: ... +def normalize_path(p: PathLike[AnyStr]) -> PathLike[AnyStr]: ... +def recursiveImport(modulename, baseDir=None, noCWD: int = 0, debug: int = 0): ... + +haveImages: Final[bool] + +class ArgvDictValue: + value: Incomplete + func: Incomplete + def __init__(self, value, func) -> None: ... + +def getArgvDict(**kw): ... +def getHyphenater(hDict=None): ... +def open_for_read_by_name(name, mode: str = "b"): ... +def rlUrlRead(name: str, headers: MutableMapping[str, str] | None = None) -> _UrlopenRet: ... +def open_for_read(name, mode: str = "b"): ... +def open_and_read(name, mode: str = "b"): ... +def open_and_readlines(name, mode: str = "t"): ... +def rl_isfile(fn, os_path_isfile=...): ... +def rl_isdir(pn, os_path_isdir=..., os_path_normpath=...): ... +def rl_listdir(pn, os_path_isdir=..., os_path_normpath=..., os_listdir=...): ... +def rl_getmtime(pn, os_path_isfile=..., os_path_normpath=..., os_path_getmtime=..., time_mktime=...): ... +def __rl_get_module__(name, dir): ... +def rl_get_module(name, dir): ... + +class ImageReader: + fileName: Incomplete + fp: Incomplete + def __init__(self, fileName, ident=None) -> None: ... + def identity(self) -> str: ... + @classmethod + def check_pil_image_size(cls, im) -> None: ... + @classmethod + def set_max_image_size(cls, max_image_size=None) -> None: ... + def jpeg_fh(self) -> None: ... + def getSize(self) -> tuple[int, int]: ... + mode: Incomplete + def getRGBData(self): ... + def getImageData(self): ... + def getTransparent(self): ... + +class LazyImageReader(ImageReader): ... + +def getImageData(imageFileName): ... + +class DebugMemo: + fn: Incomplete + stdout: Incomplete + store: Incomplete + def __init__( + self, + fn: str = "rl_dbgmemo.dbg", + mode: str = "w", + getScript: int = 1, + modules=(), + capture_traceback: int = 1, + stdout=None, + **kw, + ) -> None: ... + def add(self, **kw) -> None: ... + def dump(self) -> None: ... + def dumps(self): ... + def load(self) -> None: ... + def loads(self, s) -> None: ... + specials: Incomplete + def show(self) -> None: ... + def payload(self, name): ... + def __setitem__(self, name, value) -> None: ... + def __getitem__(self, name): ... + +def flatten(L): ... +def find_locals(func, depth: int = 0): ... + +class _FmtSelfDict: + obj: Incomplete + def __init__(self, obj, overrideArgs) -> None: ... + def __getitem__(self, k): ... + +class FmtSelfDict: ... + +def simpleSplit(text: str | bytes, fontName: str | None, fontSize: float, maxWidth: float | None): ... + +@overload +def escapeTextOnce(text: None) -> None: ... +@overload +def escapeTextOnce(text: str | bytes) -> str: ... + +def fileName2FSEnc(fn): ... +def prev_this_next(items): ... +def commasplit(s: str | bytes) -> list[str]: ... +def commajoin(l: Iterable[str | bytes]) -> str: ... +def findInPaths(fn, paths, isfile: bool = True, fail: bool = False): ... +def annotateException(msg: str, enc: str = "utf8", postMsg: str = "", sep: str = " ") -> None: ... +def escapeOnce(data: str) -> str: ... + +class IdentStr(str): + def __new__(cls, value): ... + +class RLString(str): + def __new__(cls, v, **kwds): ... + +def makeFileName(s): ... + +class FixedOffsetTZ(_datetime.tzinfo): + def __init__(self, h: float, m: float, name: str | None) -> None: ... + def utcoffset(self, dt: _datetime.datetime | None) -> _datetime.timedelta: ... + def tzname(self, dt: _datetime.datetime | None) -> str | None: ... + def dst(self, dt: _datetime.datetime | None) -> _datetime.timedelta: ... + +class TimeStamp: + tzname: str + t: float + lt: struct_time | _TimeTuple + YMDhms: tuple[int, ...] + dhh: int + dmm: int + def __init__(self, invariant: int | bool | None = None) -> None: ... + @property + def datetime(self) -> _datetime.datetime: ... + @property + def asctime(self) -> str: ... + +def recursiveGetAttr(obj, name, g=None): ... +def recursiveSetAttr(obj, name, value) -> None: ... +def recursiveDelAttr(obj, name) -> None: ... +def yieldNoneSplits(L) -> Generator[Incomplete]: ... + +class KlassStore: + lim: int + store: dict[str, type] + def __init__(self, lim: int = 127) -> None: ... + def add(self, k: str, v: type) -> None: ... + def __contains__(self, k) -> bool: ... + def __getitem__(self, k: str) -> type: ... + def get(self, k, default=None): ... + +@type_check_only +class _rl_warn: + def __init__(self) -> None: ... + def __call__(self, message: str) -> None: ... + @property + def warnings_seen(self) -> dict[str, set[str]]: ... + +rl_warn: _rl_warn diff --git a/stubs/reportlab/reportlab/lib/validators.pyi b/stubs/reportlab/reportlab/lib/validators.pyi new file mode 100644 index 000000000000..a739cafe87df --- /dev/null +++ b/stubs/reportlab/reportlab/lib/validators.pyi @@ -0,0 +1,169 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +class Percentage(float): ... + +class Validator: + def __call__(self, x): ... + def normalize(self, x): ... + def normalizeTest(self, x): ... + +class _isAnything(Validator): + def test(self, x): ... + +class _isNothing(Validator): + def test(self, x): ... + +class _isBoolean(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isString(Validator): + def test(self, x): ... + +class _isCodec(Validator): + def test(self, x): ... + +class _isNumber(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isInt(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isNumberOrNone(_isNumber): + def test(self, x): ... + def normalize(self, x): ... + +class _isListOfNumbersOrNone(Validator): + def test(self, x): ... + +class isNumberInRange(_isNumber): + min: Incomplete + max: Incomplete + def __init__(self, min, max) -> None: ... + def test(self, x): ... + +class _isListOfShapes(Validator): + def test(self, x): ... + +class _isListOfStringsOrNone(Validator): + def test(self, x): ... + +class _isTransform(Validator): + def test(self, x): ... + +class _isColor(Validator): + def test(self, x): ... + +class _isColorOrNone(Validator): + def test(self, x): ... + +class _isNormalDate(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isValidChild(Validator): + def test(self, x): ... + +class _isValidChildOrNone(_isValidChild): + def test(self, x): ... + +class _isCallable(Validator): + def test(self, x): ... + +class OneOf(Validator): + def __init__(self, enum, *args) -> None: ... + def test(self, x): ... + +class SequenceOf(Validator): + def __init__(self, elemTest, name=None, emptyOK: int = 1, NoneOK: int = 0, lo: int = 0, hi: int = 2147483647) -> None: ... + def test(self, x): ... + +class EitherOr(Validator): + def __init__(self, tests, name=None) -> None: ... + def test(self, x): ... + +class NoneOr(EitherOr): + def test(self, x): ... + +class NotSetOr(EitherOr): + def test(self, x): ... + @staticmethod + def conditionalValue(v, a): ... + +class _isNotSet(Validator): + def test(self, x): ... + +class Auto(Validator): + def __init__(self, **kw) -> None: ... + def test(self, x): ... + +class AutoOr(EitherOr): + def test(self, x): ... + +class isInstanceOf(Validator): + def __init__(self, klass=None) -> None: ... + def test(self, x): ... + +class isSubclassOf(Validator): + def __init__(self, klass=None) -> None: ... + def test(self, x): ... + +class matchesPattern(Validator): + def __init__(self, pattern) -> None: ... + def test(self, x): ... + +class DerivedValue: + def getValue(self, renderer, attr) -> None: ... + +class Inherit(DerivedValue): + def getValue(self, renderer, attr): ... + +inherit: Inherit + +class NumericAlign(str): + def __new__(cls, dp: str = ".", dpLen: int = 0): ... + +isAuto: Auto +isBoolean: _isBoolean +isString: _isString +isCodec: _isCodec +isNumber: _isNumber +isInt: _isInt +isNoneOrInt: NoneOr +isNumberOrNone: _isNumberOrNone +isTextAnchor: OneOf +isListOfNumbers: SequenceOf +isListOfNoneOrNumber: SequenceOf +isListOfListOfNoneOrNumber: SequenceOf +isListOfNumbersOrNone: _isListOfNumbersOrNone +isListOfShapes: _isListOfShapes +isListOfStrings: SequenceOf +isListOfStringsOrNone: _isListOfStringsOrNone +isTransform: _isTransform +isColor: _isColor +isListOfColors: SequenceOf +isColorOrNone: _isColorOrNone +isShape: _isValidChild +isValidChild: _isValidChild +isNoneOrShape: _isValidChildOrNone +isValidChildOrNone: _isValidChildOrNone +isAnything: _isAnything +isNothing: _isNothing +isXYCoord: SequenceOf +isBoxAnchor: OneOf +isNoneOrString: NoneOr +isNoneOrListOfNoneOrStrings: SequenceOf +isListOfNoneOrString: SequenceOf +isNoneOrListOfNoneOrNumbers: SequenceOf +isCallable: _isCallable +isNoneOrCallable: NoneOr +isStringOrCallable: EitherOr +isStringOrCallableOrNone: NoneOr +isStringOrNone: NoneOr +isNormalDate: _isNormalDate +isNotSet: _isNotSet diff --git a/stubs/reportlab/reportlab/lib/yaml.pyi b/stubs/reportlab/reportlab/lib/yaml.pyi new file mode 100644 index 000000000000..62cd8164c841 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/yaml.pyi @@ -0,0 +1,27 @@ +from _typeshed import FileDescriptorOrPath +from typing import Final + +__version__: Final[str] +PLAIN: Final = 1 +PREFORMATTED: Final = 2 +BULLETCHAR: Final = "\267" + +class BaseParser: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def parseFile(self, filename: FileDescriptorOrPath) -> list[tuple[str, str] | tuple[str, str, str]]: ... + def parseText(self, textBlock: str) -> list[tuple[str, str] | tuple[str, str, str]]: ... + def readLine(self, line: str) -> None: ... + def endPara(self) -> None: ... + def beginPre(self, stylename: str) -> None: ... + def endPre(self) -> None: ... + def image(self, filename: str) -> None: ... + +class Parser(BaseParser): + def vSpace(self, points) -> None: ... + def pageBreak(self) -> None: ... + def custom(self, moduleName: str, funcName: str) -> None: ... + def nextPageTemplate(self, templateName: str) -> None: ... + +def parseFile(filename: FileDescriptorOrPath) -> list[tuple[str, str] | tuple[str, str, str]]: ... +def parseText(textBlock: str) -> list[tuple[str, str] | tuple[str, str, str]]: ... diff --git a/stubs/reportlab/reportlab/pdfbase/__init__.pyi b/stubs/reportlab/reportlab/pdfbase/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/pdfbase/acroform.pyi b/stubs/reportlab/reportlab/pdfbase/acroform.pyi new file mode 100644 index 000000000000..aa8f2288ac84 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/acroform.pyi @@ -0,0 +1,340 @@ +from _typeshed import Incomplete +from weakref import ReferenceType + +from reportlab.lib.colors import Color +from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFObject, PDFStream + +__all__ = ("AcroForm",) + +visibilities: dict[str, int] +orientations: dict[str, list[Incomplete]] +fieldFlagValues: dict[str, int] +annotationFlagValues: dict[str, int] + +def bsPDF(borderWidth: int, borderStyle: str, dashLen) -> PDFDictionary: ... +def escPDF(s) -> str: ... +def makeFlags(s: int | str, d: dict[str, int] = ...) -> int: ... + +class PDFFromString(PDFObject): + def __init__(self, s: str | bytes) -> None: ... + def format(self, document) -> bytes: ... + +class RadioGroup(PDFObject): + TU: Incomplete + Ff: int + kids: list[Incomplete] + T: Incomplete + V: Incomplete + def __init__(self, name, tooltip: str = "", fieldFlags: str = "noToggleToOff required radio") -> None: ... + def format(self, doc) -> bytes: ... + +class AcroForm(PDFObject): + formFontNames: dict[str, str] + referenceMap: dict[Incomplete, Incomplete] + fonts: dict[str, str] + fields: list[Incomplete] + sigFlags: Incomplete + extras: dict[Incomplete, Incomplete] + def __init__(self, canv, **kwds) -> None: ... + @property + def useDefault(self) -> object: ... + @property + def canv(self) -> ReferenceType[Incomplete]: ... + def fontRef(self, f) -> str: ... + def format(self, doc) -> bytes: ... + def colorTuple(self, c): ... + def streamFillColor(self, c) -> str: ... + def streamStrokeColor(self, c) -> str: ... + def checkboxAP( + self, + key, + value, + buttonStyle: str = "circle", + shape: str = "square", + fillColor=None, + borderColor=None, + textColor=None, + borderWidth: int | None = None, + borderStyle: str = "solid", + size: int = 20, + dashLen: int = 3, + ) -> PDFStream: ... + @staticmethod + def circleArcStream(size, r, arcs=(0, 1, 2, 3), rotated: bool = False) -> str: ... + def zdMark(self, c, size, ds, iFontName) -> str: ... + def getRef(self, obj): ... + def getRefStr(self, obj) -> str: ... + def setDefault(self, name: str, value: Color | float | None) -> None: ... + def getDefaults( + self, textColor, borderColor, fillColor, borderWidth + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @staticmethod + def varyColors(key, t, b, f) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def checkForceBorder( + self, x, y, width, height, forceBorder, shape, borderStyle, borderWidth, borderColor, fillColor + ) -> None: ... + def checkbox( + self, + checked: bool = False, + buttonStyle: str = "check", + shape: str = "square", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "required", + forceBorder: bool = False, + relative: bool = False, + dashLen: int = 3, + ) -> None: ... + def radio( + self, + value=None, + selected: bool = False, + buttonStyle: str = "circle", + shape: str = "circle", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "noToggleToOff required radio", + forceBorder: bool = False, + relative: bool = False, + dashLen: int = 3, + ) -> None: ... + def makeStream(self, width, height, stream, **D) -> PDFStream: ... + def txAP( + self, + key, + value, + iFontName, + rFontName, + fontSize, + shape: str = "square", + fillColor=None, + borderColor=None, + textColor=None, + borderWidth: int | None = None, + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + dashLen: int = 3, + wkind: str = "textfield", + labels=[], + I=[], + sel_bg: str = "0.600006 0.756866 0.854904 rg", + sel_fg: str = "0 g", + ) -> PDFStream: ... + def makeFont(self, fontName: str | None) -> tuple[str, str]: ... + def textfield( + self, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + relative: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + def listbox( + self, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + relative: bool = False, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + maxlen=None, + options=[], + ) -> None: ... + def choice( + self, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "combo", + forceBorder: bool = False, + relative: bool = False, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + maxlen=None, + options=[], + ) -> None: ... + def checkboxRelative( + self, + *, + checked: bool = False, + buttonStyle: str = "check", + shape: str = "square", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "required", + forceBorder: bool = False, + dashLen: int = 3, + ) -> None: ... + def radioRelative( + self, + *, + value=None, + selected: bool = False, + buttonStyle: str = "circle", + shape: str = "circle", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "noToggleToOff required radio", + forceBorder: bool = False, + dashLen: int = 3, + ) -> None: ... + def textfieldRelative( + self, + *, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + def listboxRelative( + self, + *, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + def choiceRelative( + self, + *, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + @property + def encRefStr(self) -> str: ... + +class CBMark: + opNames: list[str] + opCount: tuple[int, ...] + ops: Incomplete + xmin: Incomplete + ymin: Incomplete + xmax: Incomplete + ymax: Incomplete + points: Incomplete + slack: Incomplete + def __init__(self, ops, points, bounds, slack: float = 0.05) -> None: ... + def scaledRender(self, size, ds: int = 0) -> str: ... diff --git a/stubs/reportlab/reportlab/pdfbase/cidfonts.pyi b/stubs/reportlab/reportlab/pdfbase/cidfonts.pyi new file mode 100644 index 000000000000..3d84603c4682 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/cidfonts.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +from reportlab.pdfbase import pdfmetrics + +__version__: Final[str] +DISABLE_CMAP: bool + +def findCMapFile(name: str) -> str: ... +def structToPDF(structure): ... + +class CIDEncoding(pdfmetrics.Encoding): + name: Incomplete + source: str | None + def __init__(self, name, useCache: bool | Literal[0, 1] = 1) -> None: ... + def parseCMAPFile(self, name) -> None: ... + def translate(self, text) -> list[Incomplete]: ... + def fastSave(self, directory) -> None: ... + def fastLoad(self, directory) -> None: ... + def getData(self) -> dict[str, Incomplete]: ... + +class CIDTypeFace(pdfmetrics.TypeFace): + def __init__(self, name) -> None: ... + def getCharWidth(self, characterId): ... + +class CIDFont(pdfmetrics.Font): + faceName: Incomplete + face: CIDTypeFace + encodingName: Incomplete + encoding: CIDEncoding + fontName: Incomplete + name: Incomplete + isVertical: bool + substitutionFonts: list[Incomplete] + def __init__(self, face, encoding) -> None: ... + def formatForPdf(self, text) -> str: ... + def stringWidth(self, text, size, encoding=None) -> float: ... + def addObjects(self, doc) -> None: ... + +class UnicodeCIDFont(CIDFont): + language: str + name: Incomplete + fontName: Incomplete + vertical: bool + isHalfWidth: bool + unicodeWidths: Incomplete + def __init__(self, face: str, isVertical: bool = False, isHalfWidth: bool = False) -> None: ... + def formatForPdf(self, text) -> str: ... + def stringWidth(self, text, size, encoding=None) -> float: ... + +def precalculate(cmapdir) -> None: ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi b/stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi new file mode 100644 index 000000000000..27cc2bc543ea --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi @@ -0,0 +1,633 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Final, Literal, TypeVar, overload + +_T = TypeVar("_T") + +__version__: Final[str] + +class PDFError(Exception): ... + +__InternalName__: Final[str] +__RefOnly__: Final[str] +__Comment__: Final[str] +BasicFonts: Final[str] +Pages: Final[str] +PDF_VERSION_DEFAULT: Final[tuple[int, int]] +PDF_SUPPORT_VERSION: Final[Mapping[str, tuple[int, int]]] + +def pdfdocEnc(x: str | _T) -> bytes | _T: ... +def format(element, document, toplevel: bool | Literal[0, 1] = 0): ... +def xObjectName(externalname: str) -> str: ... + +formName = xObjectName + +class NoEncryption: + def encode(self, t): ... + def prepare(self, document) -> None: ... + def register(self, objnum, version) -> None: ... + def info(self) -> None: ... + +class PDFObject: ... + +class DummyDoc(PDFObject): + encrypt: NoEncryption + +class PDFDocument(PDFObject): + defaultStreamFilters: Incomplete + encrypt: NoEncryption + objectcounter: int + shadingCounter: int + inObject: str | None + pageCounter: int + invariant: bool | Literal[0, 1] + idToObjectNumberAndVersion: dict[str, tuple[int, int]] + idToObject: dict[str, PDFObject] + idToOffset: dict[Incomplete, Incomplete] + numberToId: dict[int, str] + outline: PDFOutlines0 | PDFOutlines + Outlines: PDFOutlines0 | PDFOutlines + info: PDFInfo + fontMapping: dict[Incomplete, Incomplete] + delayedFonts: list[Incomplete] + def __init__( + self, + dummyoutline: bool | Literal[0, 1] | None = 0, + compression: bool | Literal[0, 1] | None = 1, + invariant: bool | Literal[0, 1] | None = 0, + filename=None, + pdfVersion=(1, 3), + lang=None, + ) -> None: ... + compression: bool | Literal[0, 1] | None + def setCompression(self, onoff: bool | Literal[0, 1] | None) -> None: ... + def ensureMinPdfVersion(self, *keys: str) -> None: ... + def updateSignature(self, thing) -> None: ... + def ID(self) -> bytes: ... + def SaveToFile(self, filename, canvas) -> None: ... + def GetPDFData(self, canvas) -> bytes: ... + def inPage(self) -> None: ... + def inForm(self) -> None: ... + def getInternalFontName(self, psfontname: str): ... + def thisPageName(self) -> str: ... + def thisPageRef(self) -> PDFObjectReference: ... + def addPage(self, page) -> None: ... + def addForm(self, name, form) -> None: ... + def annotationName(self, externalname) -> str: ... + def addAnnotation(self, name, annotation) -> None: ... + def refAnnotation(self, name) -> PDFObjectReference: ... + def addShading(self, shading) -> str: ... + def addColor(self, cmyk) -> tuple[Incomplete, Incomplete]: ... + def setTitle(self, title) -> None: ... + def setAuthor(self, author) -> None: ... + def setSubject(self, subject) -> None: ... + def setCreator(self, creator) -> None: ... + def setProducer(self, producer) -> None: ... + def setKeywords(self, keywords) -> None: ... + def setDateFormatter(self, dateFormatter) -> None: ... + def getAvailableFonts(self) -> list[Incomplete]: ... + __accum__: PDFFile + def format(self) -> bytes: ... + def hasForm(self, name: str) -> bool: ... + def getFormBBox(self, name: str, boxType: str = "MediaBox"): ... + def getXObjectName(self, name: str) -> str: ... + def xobjDict(self, formnames: Iterable[str]) -> PDFDictionary: ... + def Reference(self, obj, name=None): ... + +PDFtrue: Final = "true" +PDFfalse: Final = "false" +PDFnull: Final = "null" + +class PDFText(PDFObject): + t: Incomplete + enc: str + def __init__(self, t, enc: str = "utf-8") -> None: ... + def format(self, document) -> bytes: ... + +def PDFnumber(n: _T) -> _T: ... + +class PDFString(PDFObject): + unicodeEncValid: bool + s: str | bytes + escape: int + enc: str + def __init__(self, s: str | bytes | PDFString, escape: int = 1, enc: str = "auto") -> None: ... + def format(self, document) -> bytes: ... + +def PDFName(data, lo="!", hi="~") -> str: ... + +class PDFDictionary(PDFObject): + multiline: bool + dict: Incomplete + def __init__(self, dict=None) -> None: ... + def __setitem__(self, name, value) -> None: ... + def __getitem__(self, a): ... + def __contains__(self, a) -> bool: ... + def Reference(self, name, document) -> None: ... + def format(self, document, IND: bytes = b"\n ") -> bytes: ... + def copy(self) -> PDFDictionary: ... + def normalize(self) -> None: ... + +class checkPDFNames: + names: list[str] + def __init__(self, *names) -> None: ... + def __call__(self, value: str) -> str | None: ... + +@overload +def checkPDFBoolean(value: Literal["true"]) -> Literal["true"]: ... +@overload +def checkPDFBoolean(value: Literal["false"]) -> Literal["false"]: ... +@overload +def checkPDFBoolean(value: Any) -> None: ... + +class CheckedPDFDictionary(PDFDictionary): + validate: dict[str, Incomplete] + def __init__(self, dict=None, validate: dict[str, Incomplete] | None = None) -> None: ... + def __setitem__(self, name, value) -> None: ... + +class ViewerPreferencesPDFDictionary(CheckedPDFDictionary): + validate: dict[str, Incomplete] + +class PDFStreamFilterZCompress: + pdfname: str + def encode(self, text) -> bytes: ... + def decode(self, encoded) -> bytes: ... + +PDFZCompress: PDFStreamFilterZCompress + +class PDFStreamFilterBase85Encode: + pdfname: str + def encode(self, text) -> str: ... + def decode(self, text) -> bytes: ... + +PDFBase85Encode: PDFStreamFilterBase85Encode + +class PDFStream(PDFObject): + __RefOnly__: int + dictionary: Incomplete + content: Incomplete + filters: Incomplete + def __init__(self, dictionary=None, content=None, filters=None) -> None: ... + def format(self, document) -> bytes: ... + +def teststream(content=None) -> PDFStream: ... + +teststreamcontent: str + +class PDFArray(PDFObject): + multiline: bool + sequence: list[Incomplete] + def __init__(self, sequence) -> None: ... + def References(self, document) -> None: ... + def format(self, document, IND: bytes = b"\n ") -> bytes: ... + +class PDFArrayCompact(PDFArray): + multiline: bool + +class PDFIndirectObject(PDFObject): + __RefOnly__: int + name: str + content: Incomplete + def __init__(self, name: str, content) -> None: ... + def format(self, document) -> bytes: ... + +class PDFObjectReference(PDFObject): + name: str + def __init__(self, name: str) -> None: ... + def format(self, document) -> bytes: ... + +class PDFFile(PDFObject): + strings: list[bytes] + write: Callable[[bytes], None] + offset: int + def __init__(self, pdfVersion: tuple[int, int] = (1, 3)) -> None: ... + def closeOrReset(self) -> None: ... + def add(self, s) -> int: ... + def format(self, document) -> bytes: ... + +class PDFCrossReferenceSubsection(PDFObject): + firstentrynumber: Incomplete + idsequence: Incomplete + def __init__(self, firstentrynumber, idsequence) -> None: ... + def format(self, document) -> bytes: ... + +class PDFCrossReferenceTable(PDFObject): + sections: list[PDFCrossReferenceSubsection] + def __init__(self) -> None: ... + def addsection(self, firstentry, ids) -> None: ... + def format(self, document) -> bytes: ... + +class PDFTrailer(PDFObject): + startxref: Incomplete + def __init__(self, startxref, Size=None, Prev=None, Root=None, Info=None, ID=None, Encrypt=None) -> None: ... + def format(self, document) -> bytes: ... + +class PDFCatalog(PDFObject): + __Comment__: str + __RefOnly__: int + __Defaults__: dict[str, str | None] + __NoDefault__: list[str] + __Refs__ = __NoDefault__ # pyrefly: ignore [unknown-name] + def format(self, document) -> bytes: ... + def showOutline(self) -> None: ... + def showFullScreen(self) -> None: ... + PageLayout: Incomplete + def setPageLayout(self, layout) -> None: ... + PageMode: Incomplete + def setPageMode(self, mode) -> None: ... + def check_format(self, document) -> None: ... + +class PDFPages(PDFCatalog): + __Comment__: str + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __Refs__: Incomplete + pages: Incomplete + def __init__(self) -> None: ... + def __getitem__(self, item): ... + def addPage(self, page) -> None: ... + Kids: PDFArray + Count: int + def check_format(self, document) -> None: ... + +class PDFPage(PDFCatalog): + __Comment__: str + Override_default_compilation: int + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __Refs__: Incomplete + pagewidth: int + pageheight: int + stream: Incomplete + hasImages: bool | Literal[0, 1] + compression: bool | Literal[0, 1] + XObjects: Incomplete + Trans: Incomplete + def __init__(self) -> None: ... + def setCompression(self, onoff) -> None: ... + def setStream(self, code) -> None: ... + def setPageTransition(self, tranDict) -> None: ... + MediaBox: Incomplete + Annots: Incomplete + Contents: Incomplete + Resources: Incomplete + Parent: Incomplete + def check_format(self, document) -> None: ... + +class DuplicatePageLabelPage(Exception): ... + +class PDFPageLabels(PDFCatalog): + __comment__: Incomplete + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __Refs__: Incomplete + labels: Incomplete + def __init__(self) -> None: ... + def addPageLabel(self, page, label) -> None: ... + Nums: Incomplete + def format(self, document) -> bytes: ... + +class PDFPageLabel(PDFCatalog): + __Comment__: Incomplete + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __convertible__: str + ARABIC: str + ROMAN_UPPER: str + ROMAN_LOWER: str + LETTERS_UPPER: str + LETTERS_LOWER: str + S: Incomplete + St: Incomplete + P: Incomplete + def __init__(self, style=None, start=None, prefix=None) -> None: ... + def __lt__(self, oth): ... + +def testpage(document) -> None: ... + +DUMMYOUTLINE: str + +class PDFOutlines0(PDFObject): + __Comment__: str + text: str + __RefOnly__: int + def format(self, document) -> bytes: ... + +class OutlineEntryObject(PDFObject): + Title: Incomplete + Dest: Incomplete + Parent: Incomplete + Prev: Incomplete + Next: Incomplete + First: Incomplete + Last: Incomplete + Count: Incomplete + def format(self, document) -> bytes: ... + +class PDFOutlines(PDFObject): + mydestinations: Incomplete + ready: int | None + counter: int + currentlevel: int + destinationnamestotitles: Incomplete + destinationstotitles: Incomplete + levelstack: Incomplete + buildtree: Incomplete + closedict: Incomplete + def __init__(self) -> None: ... + def addOutlineEntry(self, destinationname, level: int = 0, title=None, closed=None) -> None: ... + def setDestinations(self, destinationtree) -> None: ... + def format(self, document) -> bytes: ... + def setNames(self, canvas, *nametree) -> None: ... + def setNameList(self, canvas, nametree) -> None: ... + def translateNames(self, canvas, object): ... + first: Incomplete + last: Incomplete + count: int + def prepare(self, document, canvas) -> None: ... + def maketree( + self, document, destinationtree, Parent=None, toplevel: bool | Literal[0, 1] = 0 + ) -> tuple[Incomplete, Incomplete]: ... + +def count(tree, closedict=None) -> int: ... + +class PDFInfo(PDFObject): + producer: Incomplete + creator: str + title: str + author: str + subject: str + keywords: str + trapped: str + def __init__(self) -> None: ... + def digest(self, md5object) -> None: ... + def format(self, document) -> bytes: ... + def copy(self): ... + +class Annotation(PDFObject): + defaults: Incomplete + required: tuple[str, ...] + permitted: tuple[str, ...] + def cvtdict(self, d: dict[str, Incomplete], escape: int = 1) -> dict[str, Incomplete]: ... + def AnnotationDict(self, **kw) -> PDFDictionary: ... + @abstractmethod + def Dict(self) -> PDFDictionary: ... + def format(self, document) -> bytes: ... + +class FreeTextAnnotation(Annotation): + permitted: tuple[str, ...] + Rect: Incomplete + Contents: Incomplete + DA: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Rect, Contents, DA, **kw) -> None: ... + def Dict(self) -> PDFDictionary: ... + +class LinkAnnotation(Annotation): + permitted: tuple[str, ...] + Border: Incomplete + Rect: Incomplete + Contents: Incomplete + Destination: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Rect, Contents, Destination, Border: str = "[0 0 1]", **kw) -> None: ... + def dummyDictString(self) -> str: ... + def Dict(self) -> PDFDictionary: ... + +class HighlightAnnotation(Annotation): + permitted: tuple[str, ...] + Rect: Incomplete + Contents: Incomplete + otherkw: dict[str, Incomplete] + QuadPoints: Incomplete + Color: Incomplete + def __init__(self, Rect, Contents, QuadPoints, Color=[0.83, 0.89, 0.95], **kw) -> None: ... + def cvtdict(self, d: dict[str, Incomplete], escape: int = 1) -> dict[str, Incomplete]: ... + def Dict(self) -> PDFDictionary: ... + +class TextAnnotation(HighlightAnnotation): + permitted: tuple[str, ...] + def __init__(self, Rect, Contents, **kw) -> None: ... + def Dict(self) -> PDFDictionary: ... + +def rect_to_quad(Rect) -> list[Incomplete]: ... + +class PDFRectangle(PDFObject): + def __init__(self, llx, lly, urx, ury) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDate(PDFObject): + dateFormatter: Incomplete + def __init__(self, ts=None, dateFormatter=None) -> None: ... + def format(self, doc) -> bytes: ... + +class Destination(PDFObject): + representation: None + page: None + name: Incomplete + fmt: Incomplete + def __init__(self, name) -> None: ... + def format(self, document) -> bytes: ... + def xyz(self, left, top, zoom) -> None: ... + def fit(self) -> None: ... + def fitb(self) -> None: ... + def fith(self, top) -> None: ... + def fitv(self, left) -> None: ... + def fitbh(self, top) -> None: ... + def fitbv(self, left) -> None: ... + def fitr(self, left, bottom, right, top) -> None: ... + def setPage(self, page) -> None: ... + +class PDFDestinationXYZ(PDFObject): + typename: str + page: Incomplete + top: Incomplete + zoom: Incomplete + left: Incomplete + def __init__(self, page, left, top, zoom) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFit(PDFObject): + typename: str + page: Incomplete + def __init__(self, page) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFitB(PDFDestinationFit): + typename: str + +class PDFDestinationFitH(PDFObject): + typename: str + page: Incomplete + top: Incomplete + def __init__(self, page, top) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFitBH(PDFDestinationFitH): + typename: str + +class PDFDestinationFitV(PDFObject): + typename: str + page: Incomplete + left: Incomplete + def __init__(self, page, left) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFitBV(PDFDestinationFitV): + typename: str + +class PDFDestinationFitR(PDFObject): + typename: str + page: Incomplete + left: Incomplete + bottom: Incomplete + right: Incomplete + top: Incomplete + def __init__(self, page, left, bottom, right, top) -> None: ... + def format(self, document) -> bytes: ... + +class PDFResourceDictionary(PDFObject): + ProcSet: Incomplete + def __init__(self, **kwds) -> None: ... + stdprocs: Incomplete + dict_attributes: Incomplete + def allProcs(self) -> None: ... + def basicProcs(self) -> None: ... + Font: Incomplete + def basicFonts(self) -> None: ... + def setColorSpace(self, colorsUsed) -> None: ... + def setShading(self, shadingUsed) -> None: ... + def format(self, document) -> bytes: ... + +class PDFType1Font(PDFObject): + __RefOnly__: int + name_attributes: Incomplete + Type: str + Subtype: str + local_attributes: Incomplete + def format(self, document) -> bytes: ... + +class PDFTrueTypeFont(PDFType1Font): + Subtype: str + +class PDFFormXObject(PDFObject): + XObjects: Incomplete + Annots: Incomplete + BBox: Incomplete + Matrix: Incomplete + Contents: Incomplete + stream: Incomplete + Resources: Incomplete + hasImages: bool | Literal[0, 1] + compression: bool | Literal[0, 1] + lowerx: Incomplete + lowery: Incomplete + upperx: Incomplete + uppery: Incomplete + def __init__(self, lowerx, lowery, upperx, uppery) -> None: ... + def setStreamList(self, data) -> None: ... + def BBoxList(self) -> list[Incomplete]: ... + def format(self, document) -> bytes: ... + +class PDFPostScriptXObject(PDFObject): + content: Incomplete + def __init__(self, content=None) -> None: ... + def format(self, document) -> bytes: ... + +class PDFImageXObject(PDFObject): + name: Incomplete + width: int + height: int + bitsPerComponent: int + colorSpace: str + streamContent: str + mask: Incomplete + def __init__(self, name, source=None, mask=None) -> None: ... + def loadImageFromA85(self, source) -> None: ... + def loadImageFromJPEG(self, imageFile) -> bool: ... + def loadImageFromRaw(self, source) -> None: ... + def loadImageFromSRC(self, im) -> None: ... + def format(self, document) -> bytes: ... + +class PDFSeparationCMYKColor: + cmyk: Incomplete + def __init__(self, cmyk) -> None: ... + def value(self) -> PDFArrayCompact: ... + +class PDFFunction(PDFObject): + defaults: Incomplete + required: tuple[str, ...] + permitted: tuple[str, ...] + def FunctionDict(self, **kw) -> PDFDictionary: ... + @abstractmethod + def Dict(self, document) -> PDFDictionary: ... + def format(self, document) -> bytes: ... + +class PDFExponentialFunction(PDFFunction): + defaults: Incomplete + required: tuple[str, ...] + permitted: tuple[str, ...] + C0: Incomplete + C1: Incomplete + N: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, C0, C1, N, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFStitchingFunction(PDFFunction): + required: tuple[str, ...] + permitted: tuple[str, ...] + Functions: Incomplete + Bounds: Incomplete + Encode: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Functions, Bounds, Encode, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFShading(PDFObject): + required: tuple[str, ...] + permitted: tuple[str, ...] + def ShadingDict(self, **kw) -> PDFDictionary: ... + @abstractmethod + def Dict(self, document) -> PDFDictionary: ... + def format(self, document) -> bytes: ... + +class PDFFunctionShading(PDFShading): + required: tuple[str, ...] + permitted: tuple[str, ...] + Function: Incomplete + ColorSpace: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Function, ColorSpace, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFAxialShading(PDFShading): + required: tuple[str, ...] + permitted: tuple[str, ...] + Coords: Incomplete + Function: Incomplete + ColorSpace: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, x0, y0, x1, y1, Function, ColorSpace, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFRadialShading(PDFShading): + required: tuple[str, ...] + permitted: tuple[str, ...] + Coords: Incomplete + Function: Incomplete + ColorSpace: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, x0, y0, r0, x1, y1, r1, Function, ColorSpace, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class XMP(PDFStream): + def __init__(self, path=None, creator=None) -> None: ... + def makeContent(self, doc): ... + # Param name is changed from the base class: + def format(self, doc) -> bytes: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfform.pyi b/stubs/reportlab/reportlab/pdfbase/pdfform.pyi new file mode 100644 index 000000000000..a747030f3d6a --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfform.pyi @@ -0,0 +1,86 @@ +from typing import Literal + +from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFObject, PDFStream, PDFString +from reportlab.pdfbase.pdfpattern import PDFPattern, PDFPatternIf + +def textFieldAbsolute( + canvas, title, x, y, width, height, value: str = "", maxlen: int = 1000000, multiline: bool | Literal[0, 1] = 0 +) -> None: ... +def textFieldRelative( + canvas, title, xR, yR, width, height, value: str = "", maxlen: int = 1000000, multiline: bool | Literal[0, 1] = 0 +) -> None: ... +def buttonFieldAbsolute(canvas, title, value, x, y, width: float = 16.7704, height: float = 14.907) -> None: ... +def buttonFieldRelative(canvas, title, value, xR, yR, width: float = 16.7704, height: float = 14.907) -> None: ... +def selectFieldAbsolute(canvas, title, value, options, x, y, width, height) -> None: ... +def selectFieldRelative(canvas, title, value, options, xR, yR, width, height) -> None: ... +def getForm(canvas) -> AcroForm: ... + +class AcroForm(PDFObject): + fields: list[PDFPattern] + def __init__(self) -> None: ... + def textField( + self, canvas, title, xmin, ymin, xmax, ymax, value: str = "", maxlen: int = 1000000, multiline: bool | Literal[0, 1] = 0 + ) -> None: ... + def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax) -> None: ... + def buttonField(self, canvas, title, value, xmin, ymin, width: float = 16.7704, height: float = 14.907) -> None: ... + def format(self, document) -> bytes: ... + +FormPattern: list[str | list[str] | PDFString | PDFPatternIf] + +def FormFontsDictionary() -> PDFDictionary: ... +def FormResources() -> PDFPattern: ... + +ZaDbPattern: list[str] +FormResourcesDictionaryPattern: list[str | list[str]] +FORMFONTNAMES: dict[str, str] +EncodingPattern: list[str | list[str]] +PDFDocEncodingPattern: list[str] + +def FormFont(BaseFont, Name) -> PDFPattern: ... + +FormFontPattern: list[str | list[str]] + +def resetPdfForm() -> None: ... +def TextField( + title, + value, + xmin, + ymin, + xmax, + ymax, + page, + maxlen: int = 1000000, + font: str = "Helvetica-Bold", + fontsize: int = 9, + R: int = 0, + G: int = 0, + B: float = 0.627, + multiline: bool | Literal[0, 1] = 0, +) -> PDFPattern: ... + +TextFieldPattern: list[str | list[str]] + +def SelectField( + title, + value, + options, + xmin, + ymin, + xmax, + ymax, + page, + font: str = "Helvetica-Bold", + fontsize: int = 9, + R: int = 0, + G: int = 0, + B: float = 0.627, +) -> PDFPattern: ... + +SelectFieldPattern: list[str | list[str]] + +def ButtonField(title, value, xmin, ymin, page, width: float = 16.7704, height: float = 14.907) -> PDFPattern: ... + +ButtonFieldPattern: list[str | list[str] | PDFString] + +def buttonStreamDictionary(width: float = 16.7704, height: float = 14.907) -> PDFDictionary: ... +def ButtonStream(content, width: float = 16.7704, height: float = 14.907) -> PDFStream: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi b/stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi new file mode 100644 index 000000000000..f2960d313f17 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi @@ -0,0 +1,90 @@ +from _typeshed import Incomplete, StrOrBytesPath +from typing import Final, Literal + +from reportlab.lib.rl_accel import unicode2T1 as unicode2T1 +from reportlab.pdfbase.pdfdoc import PDFDictionary + +__version__: Final[str] +standardFonts: Incomplete +standardEncodings: Incomplete + +class FontError(Exception): ... +class FontNotFoundError(Exception): ... + +def parseAFMFile(afmFileName: StrOrBytesPath) -> tuple[dict[Incomplete, Incomplete], list[Incomplete]]: ... + +class TypeFace: + name: Incomplete + glyphNames: Incomplete + glyphWidths: Incomplete + ascent: int + descent: int + familyName: Incomplete + bold: int + italic: int + requiredEncoding: str + builtIn: int + def __init__(self, name) -> None: ... + def getFontFiles(self) -> list[Incomplete]: ... + def findT1File(self, ext: str = ".pfb") -> str | None: ... + +def bruteForceSearchForFile(fn, searchPath=None): ... +def bruteForceSearchForAFM(faceName) -> str | None: ... + +class Encoding: + name: Incomplete + frozen: Literal[0, 1] + baseEncodingName: Incomplete + vector: tuple[Incomplete, ...] + def __init__(self, name, base=None) -> None: ... + def __getitem__(self, index): ... + def __setitem__(self, index, value) -> None: ... + def freeze(self) -> None: ... + def isEqual(self, other) -> bool: ... + def modifyRange(self, base, newNames) -> None: ... + def getDifferences(self, otherEnc) -> list[Incomplete]: ... + def makePDFObject(self) -> PDFDictionary | str: ... + +standardT1SubstitutionFonts: Incomplete + +class Font: + fontName: Incomplete + encoding: Incomplete + encName: Incomplete + substitutionFonts: Incomplete + shapable: bool + def __init__(self, name, faceName, encName, substitutionFonts=None) -> None: ... + def stringWidth(self, text: str | bytes, size: float, encoding: str = "utf8") -> float: ... + widths: list[int] + def addObjects(self, doc) -> None: ... + +PFB_MARKER: Final[str] +PFB_ASCII: Final[str] +PFB_BINARY: Final[str] +PFB_EOF: Final[str] + +class EmbeddedType1Face(TypeFace): + afmFileName: Incomplete + pfbFileName: Incomplete + requiredEncoding: Incomplete + def __init__(self, afmFileName, pfbFileName) -> None: ... + def getFontFiles(self) -> list[Incomplete]: ... + def addObjects(self, doc): ... + +def registerTypeFace(face) -> None: ... +def registerEncoding(enc) -> None: ... +def registerFontFamily(family, normal=None, bold=None, italic=None, boldItalic=None) -> None: ... +def registerFont(font) -> None: ... +def getTypeFace(faceName) -> TypeFace: ... +def getEncoding(encName) -> Encoding: ... +def findFontAndRegister(fontName: str) -> Font: ... +def getFont(fontName: str) -> Font: ... +def getAscentDescent(fontName: str, fontSize: float | None = None) -> tuple[float, float]: ... +def getAscent(fontName: str, fontSize: float | None = None) -> float: ... +def getDescent(fontName: str, fontSize: float | None = None) -> float: ... +def getRegisteredFontNames() -> list[Incomplete]: ... +def stringWidth(text: str | bytes, fontName: str, fontSize: float, encoding: str = "utf8") -> float: ... +def dumpFontData() -> None: ... +def test3widths(texts) -> None: ... +def testStringWidthAlgorithms() -> None: ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi b/stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi new file mode 100644 index 000000000000..1f98675e4bc0 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing_extensions import Self + +from reportlab.pdfbase.pdfdoc import PDFObject + +class PDFPattern(PDFObject): + __RefOnly__: int + pattern: Incomplete + arguments: dict[str, Incomplete] + def __init__(self, pattern_sequence, **keywordargs) -> None: ... + def __setitem__(self, item: str, value) -> None: ... + def __getitem__(self, item: str): ... + def eval(self, L) -> Iterator[bytes]: ... + def format(self, document) -> bytes: ... + def clone(self) -> Self: ... + +class PDFPatternIf: + cond: Incomplete + thenPart: Incomplete + elsePart: Incomplete + def __init__(self, cond, thenPart=[], elsePart=[]) -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfutils.pyi b/stubs/reportlab/reportlab/pdfbase/pdfutils.pyi new file mode 100644 index 000000000000..92406a359049 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfutils.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +__version__: Final[str] + +def makeA85Image(filename, IMG=None, detectJpeg: bool = False) -> list[Incomplete] | None: ... +def makeRawImage(filename, IMG=None, detectJpeg: bool = False) -> list[Incomplete] | None: ... +def cacheImageFile(filename, returnInMemory: bool | Literal[0, 1] = 0, IMG=None): ... +def preProcessImages(spec) -> None: ... +def cachedImageExists(filename) -> Literal[0, 1]: ... +def readJPEGInfo(image) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None: ... + +class _fusc: + def __init__(self, k, n) -> None: ... + def encrypt(self, s) -> str: ... + def decrypt(self, s) -> str: ... diff --git a/stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi b/stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi new file mode 100644 index 000000000000..c87628e05b09 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi @@ -0,0 +1,23 @@ +from typing import NamedTuple + +__all__ = ["RL_Codecs"] + +class StdCodecData(NamedTuple): + exceptions: dict[int, int | None] | None + rexceptions: dict[int, int | None] | None + +class ExtCodecData(NamedTuple): + baseName: str + exceptions: dict[int, int | None] | None + rexceptions: dict[int, int | None] | None + +class RL_Codecs: + def __init__(self) -> None: ... + @staticmethod + def register() -> None: ... + @staticmethod + def add_dynamic_codec(name: str, exceptions, rexceptions) -> None: ... + @staticmethod + def remove_dynamic_codec(name: str) -> None: ... + @staticmethod + def reset_dynamic_codecs() -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/ttfonts.pyi b/stubs/reportlab/reportlab/pdfbase/ttfonts.pyi new file mode 100644 index 000000000000..aab282f6c48b --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/ttfonts.pyi @@ -0,0 +1,192 @@ +from _typeshed import Incomplete, ReadableBuffer, StrOrBytesPath +from collections.abc import Sequence +from typing import Final, Literal, NamedTuple +from typing_extensions import Self +from weakref import WeakKeyDictionary + +from reportlab.pdfbase import pdfdoc, pdfmetrics + +__version__: Final[str] + +class TTFError(pdfdoc.PDFError): ... + +def SUBSETN(n, table: ReadableBuffer | None = ...) -> bytes: ... +def makeToUnicodeCMap(fontname: str, subset) -> str: ... +def splice(stream, offset, value): ... + +GF_ARG_1_AND_2_ARE_WORDS: Final = 1 +GF_ARGS_ARE_XY_VALUES: Final = 2 +GF_ROUND_XY_TO_GRID: Final = 4 +GF_WE_HAVE_A_SCALE: Final = 8 +GF_RESERVED: Final = 16 +GF_MORE_COMPONENTS: Final = 32 +GF_WE_HAVE_AN_X_AND_Y_SCALE: Final = 64 +GF_WE_HAVE_A_TWO_BY_TWO: Final = 128 +GF_WE_HAVE_INSTRUCTIONS: Final = 256 +GF_USE_MY_METRICS: Final = 512 +GF_OVERLAP_COMPOUND: Final = 1024 +GF_SCALED_COMPONENT_OFFSET: Final = 2048 +GF_UNSCALED_COMPONENT_OFFSET: Final = 4096 + +def TTFOpenFile(fn: StrOrBytesPath) -> tuple[StrOrBytesPath,]: ... + +class TTFontParser: + ttfVersions: tuple[int, ...] + ttcVersions: tuple[int, ...] + fileKind: str + validate: bool | Literal[0, 1] + subfontNameX: bytes + def __init__(self, file, validate: bool | Literal[0, 1] = 0, subfontIndex: int = 0) -> None: ... + ttcVersion: int + numSubfonts: int + subfontOffsets: list[int] + def readTTCHeader(self) -> None: ... + def getSubfont(self, subfontIndex: int) -> None: ... + numTables: int + searchRange: int + entrySelector: int + rangeShift: int + table: dict[Incomplete, Incomplete] + tables: list[Incomplete] + def readTableDirectory(self) -> None: ... + version: int + def readHeader(self) -> bool: ... + filename: Incomplete + def readFile(self, f) -> None: ... + def checksumTables(self) -> None: ... + def checksumFile(self) -> None: ... + def get_table_pos(self, tag) -> tuple[Incomplete, Incomplete]: ... + def seek(self, pos: int) -> None: ... + def skip(self, delta: int) -> None: ... + def seek_table(self, tag, offset_in_table: int = 0) -> int: ... + def read_tag(self) -> str: ... + def get_chunk(self, pos: int, length: int) -> bytes: ... + def read_uint8(self) -> int: ... + def read_ushort(self) -> int: ... + def read_ulong(self) -> int: ... + def read_short(self) -> int: ... + def get_ushort(self, pos: int) -> int: ... + def get_ulong(self, pos: int) -> int: ... + def get_table(self, tag): ... + +class TTFontMaker: + tables: dict[Incomplete, Incomplete] + def __init__(self) -> None: ... + def add(self, tag, data) -> None: ... + def makeStream(self) -> bytes: ... + +class CMapFmt2SubHeader(NamedTuple): + firstCode: int + entryCount: int + idDelta: int + idRangeOffset: int + +class TTFNameBytes(bytes): + ustr: Incomplete + def __new__(cls, b, enc: str = "utf8") -> Self: ... + +class TTFontFile(TTFontParser): + def __init__( + self, file, charInfo: bool | Literal[0, 1] = 1, validate: bool | Literal[0, 1] = 0, subfontIndex: int | str | bytes = 0 + ) -> None: ... + name: Incomplete + familyName: Incomplete + styleName: Incomplete + fullName: Incomplete + uniqueFontID: Incomplete + fontRevision: Incomplete + unitsPerEm: Incomplete + bbox: Incomplete + ascent: Incomplete + descent: Incomplete + capHeight: Incomplete + stemV: Incomplete + italicAngle: Incomplete + underlinePosition: Incomplete + underlineThickness: Incomplete + flags: Incomplete + numGlyphs: Incomplete + charToGlyph: Incomplete + defaultWidth: Incomplete + charWidths: Incomplete + hmetrics: Incomplete + glyphPos: Incomplete + def extractInfo(self, charInfo: bool | Literal[0, 1] = 1) -> None: ... + def makeSubset(self, subset: Sequence[Incomplete]) -> bytes: ... + +FF_FIXED: Final = 1 +FF_SERIF: Final = 2 +FF_SYMBOLIC: Final = 4 +FF_SCRIPT: Final = 8 +FF_NONSYMBOLIC: Final = 32 +FF_ITALIC: Final = 64 +FF_ALLCAP: Final = 65536 +FF_SMALLCAP: Final = 131072 +FF_FORCEBOLD: Final = 262144 + +class TTFontFace(TTFontFile, pdfmetrics.TypeFace): + def __init__(self, filename, validate: bool | Literal[0, 1] = 0, subfontIndex: int | str | bytes = 0) -> None: ... + def getCharWidth(self, code): ... + def addSubsetObjects(self, doc, fontname, subset): ... + +class TTEncoding: + name: str + def __init__(self) -> None: ... + +class TTFont: + class State: + namePrefix: str + nextCode: int + internalName: Incomplete + frozen: bool | Literal[0, 1] + subsets: Incomplete + def __init__(self, asciiReadable: bool | Literal[0, 1] | None = None, ttf=None) -> None: ... + + fontName: str + face: TTFontFace + encoding: TTEncoding + state: WeakKeyDictionary[Incomplete, State] + def __init__( + self, + name: str, + filename, + validate: bool | Literal[0, 1] = 0, + subfontIndex: int | str | bytes = 0, + asciiReadable: bool | Literal[0, 1] | None = None, + shapable: bool = True, + ) -> None: ... + def stringWidth(self, text, size, encoding: str = "utf8") -> float: ... + def splitString(self, text, doc, encoding: str = "utf-8") -> list[tuple[int, bytes]]: ... + def getSubsetInternalName(self, subset, doc) -> str: ... + def addObjects(self, doc) -> None: ... + @property + def hbFace(self) -> Incomplete | None: ... + def hbFont(self, fontSize: float = 10): ... + + @property + def shapable(self) -> bool: ... + @shapable.setter + def shapable(self, v) -> None: ... + + def pdfScale(self, v): ... + def unregister(self) -> None: ... + +class ShapedFragWord(list[Incomplete]): ... + +class ShapeData(NamedTuple): + cluster: int + x_advance: float + y_advance: float + x_offset: float + y_offset: float + width: float + +class ShapedStr(str): + def __new__(cls, s, shapeData: ShapeData | None = None) -> Self: ... + def __add__(self, other) -> ShapedStr: ... + def __radd__(self, other) -> ShapedStr: ... + +def shapeStr(s: str, fontName: str, fontSize: float, force: bool = False): ... +def freshTTFont(ttfn, ttfpath, **kwds) -> TTFont: ... +def makeShapedFragWord(w, K: list[Incomplete] = [], V: list[Incomplete] = []) -> type[ShapedFragWord]: ... +def shapeFragWord(w, features=None, force: bool = False): ... diff --git a/stubs/reportlab/reportlab/pdfgen/__init__.pyi b/stubs/reportlab/reportlab/pdfgen/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/pdfgen/canvas.pyi b/stubs/reportlab/reportlab/pdfgen/canvas.pyi new file mode 100644 index 000000000000..15b3827a28b7 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/canvas.pyi @@ -0,0 +1,297 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import IO, Literal + +from reportlab.lib.colors import Color, _ConvertibleToColor +from reportlab.pdfbase.acroform import AcroForm +from reportlab.pdfbase.pdfdoc import Destination +from reportlab.pdfgen.pathobject import PDFPathObject +from reportlab.pdfgen.textobject import PDFTextObject, _PDFColorSetter + +class ShowBoundaryValue: + color: _ConvertibleToColor | None + width: float + dashArray: Incomplete + def __init__( + self, + color: _ConvertibleToColor | None = (0, 0, 0), + width: float = 0.1, + dashArray: list[float] | tuple[float, ...] | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... + +class Canvas(_PDFColorSetter): + bottomup: bool | Literal[0, 1] + imageCaching: Incomplete + state_stack: list[Incomplete] + def __init__( + self, + filename: str | IO[bytes], + pagesize: tuple[float, float] | None = None, + bottomup: bool | Literal[0, 1] = 1, + pageCompression=None, + invariant=None, + verbosity: int = 0, + encrypt=None, + cropMarks=None, + pdfVersion=None, + enforceColorSpace=None, + initialFontName: float | None = None, + initialFontSize: float | None = None, + initialLeading: float | None = None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + lang=None, + ) -> None: ... + def setEncrypt(self, encrypt) -> None: ... + def init_graphics_state(self) -> None: ... + def push_state_stack(self) -> None: ... + def pop_state_stack(self) -> None: ... + STATE_ATTRIBUTES: list[str] + STATE_RANGE: list[int] + def setAuthor(self, author: str | None) -> None: ... + def setDateFormatter(self, dateFormatter) -> None: ... + def addOutlineEntry(self, title, key, level: int = 0, closed=None) -> None: ... + def setOutlineNames0(self, *nametree) -> None: ... + def setTitle(self, title: str | None) -> None: ... + def setSubject(self, subject: str | None) -> None: ... + def setCreator(self, creator: str | None) -> None: ... + def setProducer(self, producer: str | None) -> None: ... + def setKeywords(self, keywords: str | None) -> None: ... + def pageHasData(self) -> bool: ... + def showOutline(self) -> None: ... + def showFullScreen0(self) -> None: ... + def setBlendMode(self, v) -> None: ... + def showPage(self) -> None: ... + def setPageCallBack(self, func) -> None: ... + def bookmarkPage(self, key, fit: str = "Fit", left=None, top=None, bottom=None, right=None, zoom=None) -> Destination: ... + def bookmarkHorizontalAbsolute(self, key, top, left: int = 0, fit: str = "XYZ", **kw) -> Destination: ... + def bookmarkHorizontal(self, key, relativeX, relativeY, **kw) -> None: ... + def doForm(self, name) -> None: ... + def hasForm(self, name: str) -> bool: ... + def drawInlineImage( + self, + image, + x: float, + y: float, + width: float | None = None, + height: float | None = None, + preserveAspectRatio: bool = False, + anchor: str = "c", + anchorAtXY: bool = False, + showBoundary: bool = False, + extraReturn=None, + ) -> tuple[Incomplete, Incomplete]: ... + def drawImage( + self, + image, + x: float, + y: float, + width: float | None = None, + height: float | None = None, + mask=None, + preserveAspectRatio: bool = False, + anchor: str = "c", + anchorAtXY: bool = False, + showBoundary: bool = False, + extraReturn=None, + ) -> tuple[Incomplete, Incomplete]: ... + def beginForm(self, name, lowerx: int = 0, lowery: int = 0, upperx=None, uppery=None) -> None: ... + def endForm(self, **extra_attributes) -> None: ... + def addPostScriptCommand(self, command, position: int = 1) -> None: ... + def freeTextAnnotation( + self, contents, DA, Rect=None, addtopage: bool | Literal[0, 1] = 1, name=None, relative: bool | Literal[0, 1] = 0, **kw + ) -> None: ... + def textAnnotation( + self, contents, Rect=None, addtopage: bool | Literal[0, 1] = 1, name=None, relative: bool | Literal[0, 1] = 0, **kw + ) -> None: ... + textAnnotation0 = textAnnotation + def highlightAnnotation( + self, + contents, + Rect, + QuadPoints=None, + Color=[0.83, 0.89, 0.95], + addtopage: bool | Literal[0, 1] = 1, + name=None, + relative: bool | Literal[0, 1] = 0, + **kw, + ) -> None: ... + def inkAnnotation( + self, + contents, + InkList=None, + Rect=None, + addtopage: bool | Literal[0, 1] = 1, + name=None, + relative: bool | Literal[0, 1] = 0, + **kw, + ) -> None: ... + inkAnnotation0 = inkAnnotation + def linkAbsolute( + self, + contents, + destinationname, + Rect=None, + addtopage: bool | Literal[0, 1] = 1, + name=None, + thickness: int = 0, + color: Color | None = None, + dashArray=None, + **kw, + ) -> None: ... + def linkRect( + self, + contents, + destinationname, + Rect=None, + addtopage: bool | Literal[0, 1] = 1, + name=None, + relative: bool | Literal[0, 1] = 1, + thickness: int = 0, + color: Color | None = None, + dashArray=None, + **kw, + ) -> None: ... + def linkURL( + self, + url, + rect, + relative: bool | Literal[0, 1] = 0, + thickness: int = 0, + color: Color | None = None, + dashArray=None, + kind: str = "URI", + **kw, + ) -> None: ... + def getPageNumber(self) -> int: ... + def save(self) -> None: ... + def getpdfdata(self): ... + def setPageSize(self, size: tuple[float, float]) -> None: ... + def setCropBox(self, size, name: str = "crop") -> None: ... + def setTrimBox(self, size) -> None: ... + def setArtBox(self, size) -> None: ... + def setBleedBox(self, size) -> None: ... + # NOTE: Only accepts right angles + def setPageRotation(self, rot: float) -> None: ... + def addLiteral(self, s: object, escaped: Literal[0, 1] = 1) -> None: ... + def resetTransforms(self) -> None: ... + def transform(self, a: float, b: float, c: float, d: float, e: float, f: float) -> None: ... + def absolutePosition(self, x: float, y: float) -> tuple[float, float]: ... + def translate(self, dx: float, dy: float) -> None: ... + def scale(self, x: float, y: float) -> None: ... + def rotate(self, theta: float) -> None: ... + def skew(self, alpha: float, beta: float) -> None: ... + def saveState(self) -> None: ... + def restoreState(self) -> None: ... + def line(self, x1: float, y1: float, x2: float, y2: float) -> None: ... + def lines(self, linelist) -> None: ... + def cross( + self, + x: float, + y: float, + size: float = 5, + gap: float = 1, + text=None, + strokeColor=None, + strokeWidth: float | None = None, + fontSize: float = 3, + ) -> None: ... + def grid(self, xlist, ylist) -> None: ... + def bezier(self, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float) -> None: ... + def arc(self, x1: float, y1: float, x2: float, y2: float, startAng: float = 0, extent: float = 90) -> None: ... + def rect(self, x: float, y: float, width: float, height: float, stroke: float = 1, fill: float = 0) -> None: ... + def ellipse(self, x1: float, y1: float, x2: float, y2: float, stroke: float = 1, fill: float = 0) -> None: ... + def wedge( + self, x1: float, y1: float, x2: float, y2: float, startAng: float, extent: float, stroke: float = 1, fill: float = 0 + ) -> None: ... + def circle(self, x_cen: float, y_cen: float, r: float, stroke: float = 1, fill: float = 0) -> None: ... + def roundRect( + self, x: float, y: float, width: float, height: float, radius: float, stroke: float = 1, fill: float = 0 + ) -> None: ... + def shade(self, shading) -> None: ... + def linearGradient(self, x0: float, y0: float, x1: float, y1: float, colors, positions=None, extend: bool = True) -> None: ... + def radialGradient(self, x: float, y: float, radius: float, colors, positions=None, extend: bool = True) -> None: ... + def drawString( + self, + x: float, + y: float, + text: str, + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def drawRightString( + self, + x: float, + y: float, + text: str, + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def drawCentredString( + self, + x: float, + y: float, + text: str, + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def drawAlignedString( + self, + x: float, + y: float, + text: str, + pivotChar: str = ".", + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def getAvailableFonts(self) -> list[Incomplete]: ... + def listLoadedFonts0(self) -> list[Incomplete]: ... + def setFont(self, psfontname: str, size: float, leading: float | None = None) -> None: ... + def setFontSize(self, size: float | None = None, leading: float | None = None) -> None: ... + def stringWidth(self, text: str, fontName: str | None = None, fontSize: float | None = None) -> float: ... + def setLineWidth(self, width: float) -> None: ... + def setLineCap(self, mode) -> None: ... + def setLineJoin(self, mode) -> None: ... + def setMiterLimit(self, limit) -> None: ... + def setDash(self, array: list[float] | tuple[float, ...] | float = [], phase: float = 0) -> None: ... + def beginPath(self) -> PDFPathObject: ... + def drawPath(self, aPath, stroke: int = 1, fill: int = 0, fillMode=None) -> None: ... + def clipPath(self, aPath, stroke: int = 1, fill: int = 0, fillMode=None) -> None: ... + def beginText(self, x: float = 0, y: float = 0, direction: Literal["LTR", "RTL"] | None = None) -> PDFTextObject: ... + def drawText(self, aTextObject: PDFTextObject) -> None: ... + def setPageCompression(self, pageCompression: bool | Literal[0, 1] | None = 1) -> None: ... + def setPageDuration(self, duration=None) -> None: ... + def setPageTransition( + self, effectname: str | None = None, duration: float = 1, direction: float = 0, dimension: str = "H", motion: str = "I" + ) -> None: ... + def getCurrentPageContent(self) -> str: ... + def setViewerPreference(self, pref, value) -> None: ... + def getViewerPreference(self, pref): ... + def delViewerPreference(self, pref) -> None: ... + def setCatalogEntry(self, key: str, value) -> None: ... + def getCatalogEntry(self, key: str): ... + def delCatalogEntry(self, key: str) -> None: ... + def addPageLabel(self, pageNum, style=None, start=None, prefix=None) -> None: ... + @property + def acroForm(self) -> AcroForm: ... + def drawBoundary(self, sb, x1: float, y1: float, width: float, height: float) -> None: ... + # Following callbacks are accepted: canvas, kind and label + def setNamedCB(self, name: str, cb: Callable[[Canvas, str | None, str], None]) -> None: ... + def getNamedCB(self, name: str) -> Callable[[Canvas, str | None, str], None] | None: ... + +__all__ = ["Canvas", "ShowBoundaryValue"] diff --git a/stubs/reportlab/reportlab/pdfgen/pathobject.pyi b/stubs/reportlab/reportlab/pdfgen/pathobject.pyi new file mode 100644 index 000000000000..9e1c93ce5e38 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/pathobject.pyi @@ -0,0 +1,17 @@ +from typing import Final + +__version__: Final[str] + +class PDFPathObject: + def __init__(self, code=None) -> None: ... + def getCode(self) -> str: ... + def moveTo(self, x, y) -> None: ... + def lineTo(self, x, y) -> None: ... + def curveTo(self, x1, y1, x2, y2, x3, y3) -> None: ... + def arc(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 90) -> None: ... + def arcTo(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 90) -> None: ... + def rect(self, x, y, width, height) -> None: ... + def ellipse(self, x, y, width, height) -> None: ... + def circle(self, x_cen, y_cen, r) -> None: ... + def roundRect(self, x, y, width, height, radius) -> None: ... + def close(self) -> None: ... diff --git a/stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi b/stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi new file mode 100644 index 000000000000..ab3e5ad0523d --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +def bezierArc( + x1, y1, x2, y2, startAng: int = 0, extent: int = 90 +) -> list[tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]]: ... diff --git a/stubs/reportlab/reportlab/pdfgen/pdfimages.pyi b/stubs/reportlab/reportlab/pdfgen/pdfimages.pyi new file mode 100644 index 000000000000..83695d0069c4 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/pdfimages.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +__version__: Final[str] + +class PDFImage: + image: Incomplete + x: Incomplete + y: Incomplete + width: Incomplete + height: Incomplete + filename: Incomplete + imageCaching: bool | Literal[0, 1] + colorSpace: str + bitsPerComponent: int + filters: Incomplete + source: Incomplete + def __init__(self, image, x, y, width=None, height=None, caching: bool | Literal[0, 1] = 0) -> None: ... + def jpg_imagedata(self) -> tuple[list[str], Incomplete, Incomplete]: ... + def cache_imagedata(self) -> list[str]: ... + def PIL_imagedata(self) -> tuple[list[str], Incomplete, Incomplete]: ... + def non_jpg_imagedata(self, image) -> tuple[list[str], int, int]: ... + imageData: Incomplete + imgwidth: Incomplete + imgheight: Incomplete + def getImageData(self, preserveAspectRatio: bool = False) -> None: ... + def drawInlineImage( + self, + canvas, + preserveAspectRatio: bool = False, + anchor: str = "sw", + anchorAtXY: bool = False, + showBoundary: bool = False, + extraReturn=None, + ) -> bool: ... + def format(self, document) -> bytes: ... diff --git a/stubs/reportlab/reportlab/pdfgen/textobject.pyi b/stubs/reportlab/reportlab/pdfgen/textobject.pyi new file mode 100644 index 000000000000..31edb40dddb9 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/textobject.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import Final, Literal, TypeAlias + +from reportlab.lib.colors import Color +from reportlab.pdfbase.ttfonts import ShapedStr +from reportlab.pdfgen.canvas import Canvas + +# NOTE: This is slightly different from what toColor accepts and interprets +_Color: TypeAlias = Color | tuple[float, float, float, float] | tuple[float, float, float] | list[float] | str + +__version__: Final[str] +log2vis: Callable[..., str | None] +BidiStr: type[str] +BidiList: type[list[Incomplete]] +BidiIndex: Incomplete + +def bidiText(text: str, direction: str | None) -> str: ... +def bidiShapedText( + text: str, direction: str = "RTL", clean: bool = True, fontName: str = "Helvetica", fontSize: int = 10, shaping: bool = False +) -> tuple[ShapedStr | str, float]: ... +def isBidiStr(_: Unused) -> bool: ... +def isBidiList(_: Unused) -> bool: ... +def innerBidiStrWrap(s: str, bidiV: int = -1, bidiL: int = -1) -> str: ... +def bidiStrWrap(s: str, orig: str) -> str: ... +def bidiListWrap(L, orig) -> list[Incomplete]: ... +def bidiFragWord(w: str, direction: str | None = None, bidiV: int = -1, bidiL: int = -1, clean: bool = True): ... +def bidiWordList( + words: list[str] | tuple[str], direction: str = "RTL", clean: bool = True, wx: bool = False +) -> list[Incomplete]: ... + +rtlSupport: bool + +class _PDFColorSetter: + def setFillColorCMYK(self, c: float, m: float, y: float, k: float, alpha: float | None = None) -> None: ... + def setStrokeColorCMYK(self, c: float, m: float, y: float, k: float, alpha: float | None = None) -> None: ... + def setFillColorRGB(self, r: float, g: float, b: float, alpha: float | None = None) -> None: ... + def setStrokeColorRGB(self, r: float, g: float, b: float, alpha: float | None = None) -> None: ... + def setFillColor(self, aColor: _Color, alpha: float | None = None) -> None: ... + def setStrokeColor(self, aColor: _Color, alpha: float | None = None) -> None: ... + def setFillGray(self, gray: float, alpha: float | None = None) -> None: ... + def setStrokeGray(self, gray: float, alpha: float | None = None) -> None: ... + def setStrokeAlpha(self, a: float) -> None: ... + def setFillAlpha(self, a: float) -> None: ... + def setStrokeOverprint(self, a) -> None: ... + def setFillOverprint(self, a) -> None: ... + def setOverprintMask(self, a) -> None: ... + +class PDFTextObject(_PDFColorSetter): + direction: Literal["LTR", "RTL"] + def __init__(self, canvas: Canvas, x: float = 0, y: float = 0, direction: Literal["LTR", "RTL"] | None = None) -> None: ... + def getCode(self) -> str: ... + def setTextOrigin(self, x: float, y: float) -> None: ... + def setTextTransform(self, a: float, b: float, c: float, d: float, e: float, f: float) -> None: ... + def moveCursor(self, dx: float, dy: float) -> None: ... + def setXPos(self, dx: float) -> None: ... + def getCursor(self) -> tuple[float, float]: ... + def getStartOfLine(self) -> tuple[float, float]: ... + def getX(self) -> float: ... + def getY(self) -> float: ... + def setFont(self, psfontname: str, size: float, leading: float | None = None) -> None: ... + def setCharSpace(self, charSpace: float) -> None: ... + def setWordSpace(self, wordSpace: float) -> None: ... + def setHorizScale(self, horizScale: float) -> None: ... + def setLeading(self, leading: float) -> None: ... + def setTextRenderMode(self, mode: Literal[0, 1, 2, 3, 4, 5, 6, 7]) -> None: ... + def setRise(self, rise: float) -> None: ... + def textOut(self, text: str) -> None: ... + def textLine(self, text: str = "") -> None: ... + def textLines(self, stuff: list[str] | tuple[str, ...] | str, trim: Literal[0, 1] = 1) -> None: ... + def __nonzero__(self) -> bool: ... diff --git a/stubs/reportlab/reportlab/platypus/__init__.pyi b/stubs/reportlab/reportlab/platypus/__init__.pyi new file mode 100644 index 000000000000..973e8dec08fe --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/__init__.pyi @@ -0,0 +1,12 @@ +from typing import Final + +from .doctemplate import * +from .flowables import * +from .frames import * +from .multicol import * +from .paragraph import * +from .paraparser import * +from .tables import * +from .xpreformatted import * + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/platypus/doctemplate.pyi b/stubs/reportlab/reportlab/platypus/doctemplate.pyi new file mode 100644 index 000000000000..ca2ec31b2fe3 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/doctemplate.pyi @@ -0,0 +1,325 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from collections.abc import Callable +from typing import IO, Any, Literal, Protocol, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self, Unpack + +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus.flowables import Flowable +from reportlab.platypus.frames import Frame + +__all__ = ( + "ActionFlowable", + "BaseDocTemplate", + "CurrentFrameFlowable", + "FrameActionFlowable", + "FrameBreak", + "Indenter", + "IndexingFlowable", + "LayoutError", + "LCActionFlowable", + "NextFrameFlowable", + "NextPageTemplate", + "NotAtTopPageBreak", + "NullActionFlowable", + "PageAccumulator", + "PageBegin", + "PageTemplate", + "SimpleDocTemplate", +) + +# NOTE: Since we don't know what kind of DocTemplate we will use in a PageTemplate +# we'll leave the second argument at Any, since the workaround with unbound +# type vars didn't seem to work for this one +_PageCallback: TypeAlias = Callable[[Canvas, Any], object] + +@type_check_only +class _CanvasMaker(Protocol): + # NOTE: This matches a subset of Canvas.__init__ + def __call__( + self, + filename: str | IO[bytes], + /, + *, + pagesize=None, + pageCompression=None, + invariant=None, + enforceColorSpace=None, + initialFontName=None, + initialFontSize=None, + initialLeading=None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + lang=None, + ) -> Canvas: ... + +class LayoutError(Exception): ... + +# NOTE: While internal, this is used as sentinel value in PageTemplate +# and SimpleDocTemplate so in subclasses you may need to use this +def _doNothing(canvas: Canvas, doc: BaseDocTemplate) -> None: ... + +class PTCycle(list[PageTemplate]): + @property + def next_value(self) -> PageTemplate: ... + @property + def peek(self) -> PageTemplate: ... + +class IndexingFlowable(Flowable): + def isIndexing(self) -> Literal[1]: ... + def isSatisfied(self) -> int: ... + def notify(self, kind: str, stuff: Any) -> None: ... + def beforeBuild(self) -> None: ... + def afterBuild(self) -> None: ... + +class ActionFlowable(Flowable): + # NOTE: Technically action always has to contain a string referencing + # a handle_ method on the DocTemplate, while the rest are the args + # that should be passed to that method, but since the default arg + # on __init__ violates that we might as well keep things simple + action: tuple[Any, ...] + def __init__(self, action: list[Any] | tuple[Any, ...] = ()) -> None: ... + def apply(self, doc: BaseDocTemplate) -> None: ... + def __call__(self) -> Self: ... + +class NullActionFlowable(ActionFlowable): ... + +class LCActionFlowable(ActionFlowable): + locChanger: int + def draw(self) -> None: ... + +class NextFrameFlowable(ActionFlowable): + locChanger: int + def __init__(self, ix: int | str, resume: int = 0) -> None: ... + +class CurrentFrameFlowable(LCActionFlowable): + def __init__(self, ix: int | str, resume: int = 0) -> None: ... + +class _FrameBreak(LCActionFlowable): + def __call__(self, ix: int | str | None = None, resume: int = 0) -> Self: ... + def apply(self, doc: BaseDocTemplate) -> None: ... + +FrameBreak: _FrameBreak +PageBegin: LCActionFlowable + +class FrameActionFlowable(Flowable): + @abstractmethod + def __init__(self, *arg: Any, **kw: Any) -> None: ... + @abstractmethod + def frameAction(self, frame: Frame) -> None: ... + +class Indenter(FrameActionFlowable): + width: float + height: float + left: float + right: float + def __init__(self, left: float | str = 0, right: float | str = 0) -> None: ... + def frameAction(self, frame: Frame) -> None: ... + +class NotAtTopPageBreak(FrameActionFlowable): + locChanger: int + nextTemplate: Incomplete + def __init__(self, nextTemplate=None) -> None: ... + def frameAction(self, frame: Frame) -> None: ... + +class NextPageTemplate(ActionFlowable): + locChanger: int + def __init__(self, pt: str | int | list[str] | tuple[str, ...]) -> None: ... + +class PageTemplate: + id: str | None + frames: list[Frame] + onPage: _PageCallback + onPageEnd: _PageCallback + pagesize: tuple[float, float] + autoNextPageTemplate: Incomplete + cropBox: Incomplete + artBox: Incomplete + trimBox: Incomplete + bleedBox: Incomplete + def __init__( + self, + id: str | None = None, + frames: list[Frame] | Frame = [], + onPage: _PageCallback = ..., + onPageEnd: _PageCallback = ..., + pagesize: tuple[float, float] | None = None, + autoNextPageTemplate=None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + ) -> None: ... + def beforeDrawPage(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def checkPageSize(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def afterDrawPage(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + +class onDrawStr(str): + onDraw: Callable[[Canvas, str | None, str], object] + kind: str | None + label: str + def __new__( + cls, value: object, onDraw: Callable[[Canvas, str | None, str], object], label: str, kind: str | None = None + ) -> Self: ... + def __getnewargs__(self) -> tuple[str, Callable[[Canvas, str | None, str], object], str, str | None]: ... # type: ignore[override] + +_OnDrawStr: TypeAlias = onDrawStr + +class PageAccumulator: + name: str + data: list[tuple[Any, ...]] + def __init__(self, name: str | None = None) -> None: ... + def reset(self) -> None: ... + def add(self, *args) -> None: ... + def onDrawText(self, *args) -> str: ... + def __call__(self, canv: Canvas, kind: str | None, label: str) -> None: ... + def attachToPageTemplate(self, pt: PageTemplate) -> None: ... + def onPage(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def onPageEnd(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def pageEndAction(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def onDrawStr(self, value: object, *args) -> _OnDrawStr: ... + +@type_check_only +class _DocTemplateKwargs(TypedDict, total=False): + pagesize: Incomplete + pageTemplates: list[PageTemplate] + showBoundary: Incomplete + width: float + height: float + leftMargin: float + rightMargin: float + topMargin: float + bottomMargin: float + allowSplitting: Incomplete + title: Incomplete | None + author: Incomplete | None + subject: Incomplete | None + creator: Incomplete | None + producer: Incomplete | None + keywords: list[Incomplete] + invariant: Incomplete | None + pageCompression: Incomplete | None + rotation: Incomplete + encrypt: Incomplete | None + cropMarks: Incomplete | None + enforceColorSpace: Incomplete | None + displayDocTitle: Incomplete | None + lang: Incomplete | None + initialFontName: Incomplete | None + initialFontSize: Incomplete | None + initialLeading: Incomplete | None + cropBox: Incomplete | None + artBox: Incomplete | None + trimBox: Incomplete | None + bleedBox: Incomplete | None + keepTogetherClass: type[Flowable] + hideToolbar: Incomplete | None + hideMenubar: Incomplete | None + hideWindowUI: Incomplete | None + fitWindow: Incomplete | None + centerWindow: Incomplete | None + nonFullScreenPageMode: Incomplete | None + direction: Incomplete | None + viewArea: Incomplete | None + viewClip: Incomplete | None + printArea: Incomplete | None + printClip: Incomplete | None + printScaling: Incomplete | None + duplex: Incomplete | None + +class BaseDocTemplate: + filename: Incomplete + pagesize: Incomplete + pageTemplates: list[PageTemplate] + showBoundary: Incomplete + width: float + height: float + leftMargin: float + rightMargin: float + topMargin: float + bottomMargin: float + allowSplitting: Incomplete + title: Incomplete | None + author: Incomplete | None + subject: Incomplete | None + creator: Incomplete | None + producer: Incomplete | None + keywords: list[Incomplete] + invariant: Incomplete | None + pageCompression: Incomplete | None + rotation: Incomplete + encrypt: Incomplete | None + cropMarks: Incomplete | None + enforceColorSpace: Incomplete | None + displayDocTitle: Incomplete | None + lang: Incomplete | None + initialFontName: Incomplete | None + initialFontSize: Incomplete | None + initialLeading: Incomplete | None + cropBox: Incomplete | None + artBox: Incomplete | None + trimBox: Incomplete | None + bleedBox: Incomplete | None + keepTogetherClass: type[Flowable] + hideToolbar: Incomplete | None + hideMenubar: Incomplete | None + hideWindowUI: Incomplete | None + fitWindow: Incomplete | None + centerWindow: Incomplete | None + nonFullScreenPageMode: Incomplete | None + direction: Incomplete | None + viewArea: Incomplete | None + viewClip: Incomplete | None + printArea: Incomplete | None + printClip: Incomplete | None + printScaling: Incomplete | None + duplex: Incomplete | None + # NOTE: The following attributes only exist while/after pages are rendered + pageTemplate: PageTemplate + page: int + frame: Frame + canv: Canvas + def __init__(self, filename: str | IO[bytes], **kw: Unpack[_DocTemplateKwargs]) -> None: ... + def setPageCallBack(self, func: Callable[[int], object] | None) -> None: ... + def setProgressCallBack(self, func: Callable[[str, int], object] | None) -> None: ... + def clean_hanging(self) -> None: ... + def addPageTemplates(self, pageTemplates: list[PageTemplate] | tuple[PageTemplate, ...] | PageTemplate) -> None: ... + def handle_documentBegin(self) -> None: ... + def handle_pageBegin(self) -> None: ... + def handle_pageEnd(self) -> None: ... + def handle_pageBreak(self, slow: bool | None = None) -> None: ... + def handle_frameBegin(self, resume: int = 0, pageTopFlowables=None) -> None: ... + def handle_frameEnd(self, resume: int = 0) -> None: ... + def handle_nextPageTemplate(self, pt: str | int | list[str] | tuple[str, ...]) -> None: ... + def handle_nextFrame(self, fx: str | int, resume: int = 0) -> None: ... + def handle_currentFrame(self, fx: str | int, resume: int = 0) -> None: ... + def handle_breakBefore(self, flowables: list[Flowable]) -> None: ... + def handle_keepWithNext(self, flowables: list[Flowable]) -> None: ... + def handle_flowable(self, flowables: list[Flowable]) -> None: ... + def build( + self, flowables: list[Flowable], filename: str | IO[bytes] | None = None, canvasmaker: _CanvasMaker = ... + ) -> None: ... + def notify(self, kind: str, stuff: Any) -> None: ... + def pageRef(self, label: str) -> None: ... + def multiBuild(self, story: list[Flowable], maxPasses: int = 10, **buildKwds: Any) -> int: ... + def afterInit(self) -> None: ... + def beforeDocument(self) -> None: ... + def beforePage(self) -> None: ... + def afterPage(self) -> None: ... + def filterFlowables(self, flowables: list[Flowable]) -> None: ... + def afterFlowable(self, flowable: Flowable) -> None: ... + def docAssign(self, var: str, expr: object, lifetime: str) -> None: ... + def docExec(self, stmt: str, lifetime: str) -> None: ... + def docEval(self, expr: str) -> Any: ... + +class SimpleDocTemplate(BaseDocTemplate): + def handle_pageBegin(self) -> None: ... + def build( # type: ignore[override] + self, + flowables: list[Flowable], + onFirstPage: _PageCallback = ..., + onLaterPages: _PageCallback = ..., + canvasmaker: _CanvasMaker = ..., + ) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/figures.pyi b/stubs/reportlab/reportlab/platypus/figures.pyi new file mode 100644 index 000000000000..8433c7e14f04 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/figures.pyi @@ -0,0 +1,108 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.platypus import Flowable + +__version__: Final[str] +captionStyle: Incomplete + +class Figure(Flowable): + width: Incomplete + figureHeight: Incomplete + caption: Incomplete + captionFont: Incomplete + captionSize: Incomplete + captionTextColor: Incomplete + captionBackColor: Incomplete + captionGap: Incomplete + captionAlign: Incomplete + captionPosition: Incomplete + captionHeight: int + background: Incomplete + border: Incomplete + spaceBefore: Incomplete + spaceAfter: Incomplete + hAlign: Incomplete + def __init__( + self, + width, + height, + caption: str = "", + captionFont="Helvetica-Oblique", + captionSize: int = 12, + background=None, + captionTextColor=..., + captionBackColor=None, + border=None, + spaceBefore: int = 12, + spaceAfter: int = 12, + captionGap=None, + captionAlign: str = "centre", + captionPosition: str = "bottom", + hAlign: str = "CENTER", + ) -> None: ... + height: Incomplete + dx: Incomplete + def wrap(self, availWidth, availHeight): ... + def draw(self) -> None: ... + def drawBorder(self) -> None: ... + def drawBackground(self) -> None: ... + def drawCaption(self) -> None: ... + def drawFigure(self) -> None: ... + +def drawPage(canvas, x, y, width, height) -> None: ... + +class PageFigure(Figure): + caption: str + captionStyle: Incomplete + background: Incomplete + def __init__(self, background=None) -> None: ... + def drawVirtualPage(self) -> None: ... + def drawFigure(self) -> None: ... + +class PlatPropFigure1(PageFigure): + caption: str + def __init__(self) -> None: ... + def drawVirtualPage(self) -> None: ... + +class FlexFigure(Figure): + shrinkToFit: Incomplete + growToFit: Incomplete + scaleFactor: Incomplete + background: Incomplete + def __init__( + self, + width, + height, + caption, + background=None, + captionFont: str = "Helvetica-Oblique", + captionSize: int = 8, + captionTextColor=..., + shrinkToFit: int = 1, + growToFit: int = 1, + spaceBefore: int = 12, + spaceAfter: int = 12, + captionGap: int = 9, + captionAlign: str = "centre", + captionPosition: str = "top", + scaleFactor=None, + hAlign: str = "CENTER", + border: int = 1, + ) -> None: ... + def wrap(self, availWidth, availHeight): ... + def split(self, availWidth, availHeight): ... + +class ImageFigure(FlexFigure): + filename: Incomplete + def __init__(self, filename, caption, background=None, scaleFactor=None, hAlign: str = "CENTER", border=None) -> None: ... + def drawFigure(self) -> None: ... + +class DrawingFigure(FlexFigure): + drawing: Incomplete + growToFit: int + def __init__(self, modulename, classname, caption, baseDir=None, background=None) -> None: ... + def drawFigure(self) -> None: ... + +def demo1(canvas) -> None: ... +def test1() -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/flowables.pyi b/stubs/reportlab/reportlab/platypus/flowables.pyi new file mode 100644 index 000000000000..d3d0da2ed876 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/flowables.pyi @@ -0,0 +1,472 @@ +from _typeshed import Incomplete, SupportsRead, Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Never, Self + +from reportlab.lib.colors import Color +from reportlab.lib.styles import ListStyle, ParagraphStyle, PropertySet +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfgen.textobject import _Color +from reportlab.platypus.paragraph import Paragraph + +__all__ = [ + "AnchorFlowable", + "BalancedColumns", + "BulletDrawer", + "CallerMacro", + "CondPageBreak", + "DDIndenter", + "DocAssert", + "DocAssign", + "DocExec", + "DocIf", + "DocPara", + "DocWhile", + "FailOnDraw", + "FailOnWrap", + "Flowable", + "FrameBG", + "FrameSplitter", + "HRFlowable", + "Image", + "ImageAndFlowables", + "KeepInFrame", + "KeepTogether", + "LIIndenter", + "ListFlowable", + "ListItem", + "Macro", + "NullDraw", + "PTOContainer", + "PageBreak", + "PageBreakIfNotEmpty", + "ParagraphAndImage", + "Preformatted", + "SetPageTopFlowables", + "SetTopFlowables", + "SlowPageBreak", + "Spacer", + "TopPadder", + "TraceInfo", + "UseUpSpace", + "XBox", + "splitLine", + "splitLines", + "PlacedStory", +] + +_HAlignment: TypeAlias = Literal["LEFT", "CENTER", "CENTRE", "RIGHT", 0, 1, 2] +_VAlignment: TypeAlias = Literal["BOTTOM", "MIDDLE", "TOP"] +# FIXME: Consider using Sequence[Flowable] for covariance on list, even though +# that will give false negatives for non list or tuple sequences, it also +# would reduce type safety, since flowables don't copy the list +_FlowableSublist: TypeAlias = Flowable | list[Flowable] | tuple[Flowable, ...] +# NOTE: Technically can only be list or tuple, but would be annoying for variance +_NestedFlowable: TypeAlias = Flowable | Sequence[_NestedFlowable] + +@type_check_only +class _StyledFlowableFactory(Protocol): + # NOTE: We leave style at Any so people can specify a specific property set + def __call__(self, value: str, /, *, style: Any) -> Flowable: ... + +class TraceInfo: + srcFile: str + startLineNo: int + startLinePos: int + endLineNo: int + endLinePos: int + def __init__(self) -> None: ... + +class Flowable: + width: float + height: float + wrapped: int + hAlign: _HAlignment + vAlign: _VAlignment + encoding: str | None + # NOTE: this only exists during drawing, splitting and wrapping + canv: Canvas + # NOTE: The following attributes will not exist on all flowables, but + # they need to be settable on individual instances + keepWithNext: Incomplete + spaceAfter: float + spaceBefore: float + def __init__(self) -> None: ... + # NOTE: We pretend the optional internal _sW argument does not exist + # since not all flowables support it and we'd have to deal with + # a bunch of LSP errors. Conversely we will get type errors in + # subclasses that rely on the argument existing when called through + # super() inside their own implementation, so we can't really + # make everyone happy here, sigh... + def drawOn(self, canvas: Canvas, x: float, y: float) -> None: ... + def wrapOn(self, canv: Canvas, aW: float, aH: float) -> tuple[float, float]: ... + def wrap(self, aW: float, aH: float) -> tuple[float, float]: ... + def minWidth(self) -> float: ... + def splitOn(self, canv: Canvas, aW: float, aH: float) -> list[Flowable]: ... + def split(self, aW: float, aH: float, /) -> list[Flowable]: ... + def getKeepWithNext(self): ... + def getSpaceAfter(self) -> float: ... + def getSpaceBefore(self) -> float: ... + def isIndexing(self) -> int: ... + def identity(self, maxLen: int | None = None) -> str: ... + +class XBox(Flowable): + text: str + def __init__(self, width: float, height: float, text: str = "A Box") -> None: ... + def draw(self) -> None: ... + +def splitLines(lines, maximum_length, split_characters, new_line_characters): ... +def splitLine(line_to_split, lines_splitted, maximum_length, split_characters, new_line_characters) -> None: ... + +class Preformatted(Flowable): + style: ParagraphStyle + bulletText: str | None + lines: list[str] + def __init__( + self, + text: str, + # NOTE: Technically has to be a ParagraphStyle, but that would + # conflict with stylesheet["Style"] usage + style: PropertySet, + bulletText: str | None = None, + dedent: int = 0, + maxLineLength: int | None = None, + splitChars: str | None = None, + newLineChars: str = "", + ) -> None: ... + def draw(self) -> None: ... + +class Image(Flowable): + filename: str + # these are lazy, but __getattr__ ensures the image gets loaded + # as soon as these attributes are accessed + imageWidth: int + imageHeight: int + drawWidth: float + drawHeight: float + def __init__( + self, + # TODO: I think this might also accept a PIL.Image and other + # kinds of path representations, should be kept in sync + # with reportlab.lib.utils.ImageReader, except for the + # potential PIL.Image shortcut + filename: str | SupportsRead[bytes] | Incomplete, + width: float | None = None, + height: float | None = None, + kind: str = "direct", + mask: str = "auto", + lazy: int = 1, + hAlign: _HAlignment = "CENTER", + useDPI: bool = False, + ) -> None: ... + def draw(self) -> None: ... + +class NullDraw(Flowable): + def draw(self) -> None: ... + +class Spacer(NullDraw): + # NOTE: This may actually be a bug, it seems likely that Spacer is meant + # to set spaceBefore in the isGlue case. + spacebefore: float + def __init__(self, width: float, height: float, isGlue: bool = False) -> None: ... + +class UseUpSpace(NullDraw): ... + +class PageBreak(UseUpSpace): + locChanger: int + nextTemplate: str | None + def __init__(self, nextTemplate: str | None = None) -> None: ... + +class SlowPageBreak(PageBreak): ... +class PageBreakIfNotEmpty(PageBreak): ... + +class CondPageBreak(Spacer): + locChanger: int + def __init__(self, height: float) -> None: ... + +class _ContainerSpace: + def getSpaceBefore(self) -> float: ... + def getSpaceAfter(self) -> float: ... + +class KeepTogether(_ContainerSpace, Flowable): + splitAtTop: bool + # TODO: Consider using Sequence[Flowable] for covariance, even if reportlab + # only supports list/tuple + def __init__(self, flowables: _FlowableSublist | None, maxHeight=None) -> None: ... + +class KeepTogetherSplitAtTop(KeepTogether): + splitAtTop: bool + +class Macro(Flowable): + command: str + def __init__(self, command: str) -> None: ... + def draw(self) -> None: ... + +class CallerMacro(Flowable): + def __init__( + self, + drawCallable: Callable[[CallerMacro, float, float], object] | None = None, + wrapCallable: Callable[[CallerMacro, float, float], object] | None = None, + ) -> None: ... + def draw(self) -> None: ... + +class ParagraphAndImage(Flowable): + P: Paragraph + I: Image + xpad: float + ypad: float + def __init__(self, P: Paragraph, I: Image, xpad: float = 3, ypad: float = 3, side: str = "right") -> None: ... + def draw(self) -> None: ... + +class FailOnWrap(NullDraw): + def wrap(self, aW: float, aH: float) -> Never: ... + +class FailOnDraw(Flowable): + def draw(self) -> Never: ... + +class HRFlowable(Flowable): + width: float | str # type: ignore[assignment] + lineWidth: float + lineCap: str + color: _Color + dash: Incomplete | None + def __init__( + self, + width: float | str = "80%", + thickness: float = 1, + lineCap: str = "round", + color: _Color = ..., + spaceBefore: float = 1, + spaceAfter: float = 1, + hAlign: _HAlignment = "CENTER", + vAlign: _VAlignment = "BOTTOM", + dash=None, + ) -> None: ... + def draw(self) -> None: ... + +class _Container(_ContainerSpace): + def drawOn(self, canv: Canvas, x: float, y: float) -> None: ... + def copyContent(self, content: _FlowableSublist | None = None) -> None: ... + +class PTOContainer(_Container, Flowable): # pyrefly: ignore [inconsistent-inheritance] + def __init__( + self, content: _FlowableSublist | None, trailer: _FlowableSublist | None = None, header: _FlowableSublist | None = None + ) -> None: ... + +class KeepInFrame(_Container, Flowable): # pyrefly: ignore [inconsistent-inheritance] + name: str + maxWidth: float + maxHeight: float + mode: Literal["error", "continue", "shrink", "truncate"] + mergespace: Incomplete | None + fakeWidth: bool | None + def __init__( + self, + maxWidth: float, + maxHeight: float, + content: list[Flowable] = [], + mergeSpace: Incomplete | None = 1, + mode: Literal["error", "continue", "shrink", "truncate"] = "shrink", + name: str = "", + hAlign: str = "LEFT", + vAlign: str = "BOTTOM", + fakeWidth: bool | None = None, + ) -> None: ... + +class PlacedStory(Flowable): + def __init__( + self, + x, + y, + maxWidth: float, + maxHeight: float, + content: list[Flowable] = [], + mergeSpace: Incomplete | None = 1, + mode: Literal["error", "continue", "shrink", "truncate"] = "shrink", + name: str = "", + anchor: str = "sw", + fakeWidth: bool | None = None, + hAlign: str = "LEFT", + vAlign: str = "BOTTOM", + showBoundary=None, + origin="page", + ) -> None: ... + def wrap(self, _aW: Unused, _aH: Unused) -> tuple[Literal[0], Literal[0]]: ... + def drawOn(self, canv: Canvas, lx: float, ly: float, _sW=0) -> None: ... + +class _FindSplitterMixin: ... + +class ImageAndFlowables(_Container, _FindSplitterMixin, Flowable): # pyrefly: ignore [inconsistent-inheritance] + imageHref: str | None + def __init__( + self, + I: Image, + F: _FlowableSublist | None, + imageLeftPadding: float = 0, + imageRightPadding: float = 3, + imageTopPadding: float = 0, + imageBottomPadding: float = 3, + imageSide: str = "right", + imageHref: str | None = None, + ) -> None: ... + def deepcopy(self) -> Self: ... + +class BalancedColumns(_FindSplitterMixin, NullDraw): + name: str + showBoundary: Incomplete | None + endSlack: float + def __init__( + self, + F: _FlowableSublist | None, + nCols: int = 2, + needed: float = 72, + spaceBefore: float = 0, + spaceAfter: float = 0, + showBoundary=None, + leftPadding: float | None = None, + innerPadding: float | None = None, + rightPadding: float | None = None, + topPadding: float | None = None, + bottomPadding: float | None = None, + name: str = "", + endSlack: float = 0.1, + boxStrokeColor: Color | None = None, + boxStrokeWidth: float = 0, + boxFillColor: Color | None = None, + boxMargin: tuple[int, int, int, int] | tuple[int, int, int] | tuple[int, int] | tuple[int] | None = None, + vLinesStrokeColor: Color | None = None, + vLinesStrokeWidth: float | None = None, + ) -> None: ... + +class AnchorFlowable(Spacer): + def __init__(self, name: str) -> None: ... + +class FrameBG(AnchorFlowable): + start: bool + left: float + right: float + color: Color + strokeWidth: float + strokeColor: Color + strokeDashArray: list[float] | tuple[float, ...] | None + def __init__( + self, + color: Color | None = None, + left: float | str = 0, + right: float | str = 0, + start: bool = True, + strokeWidth: float | None = None, + strokeColor: Color | None = None, + strokeDashArray: list[float] | tuple[float, ...] | None = None, + ) -> None: ... + +class FrameSplitter(NullDraw): + nextTemplate: str + nextFrames: list[str] + gap: float + required: float + adjustHeight: bool + def __init__( + self, + nextTemplate: str, + nextFrames: list[str] | None = [], + gap: float = 10, + required: float = 72, + adjustHeight: bool = True, + ) -> None: ... + +class BulletDrawer: + value: str + def __init__( + self, + value: str = "0", + bulletAlign: str = "left", + bulletType: str = "1", + bulletColor: str = "black", + bulletFontName: str = "Helvetica", + bulletFontSize: int = 12, + bulletOffsetY: int = 0, + bulletDedent: int = 0, + bulletDir: str = "ltr", + bulletFormat=None, + ) -> None: ... + def drawOn(self, indenter: DDIndenter, canv: Canvas, x: float, y: float) -> None: ... + +class DDIndenter(Flowable): + def __init__(self, flowable: Flowable, leftIndent: float = 0, rightIndent: float = 0) -> None: ... + +class LIIndenter(DDIndenter): + def __init__( + self, + flowable: Flowable, + leftIndent: float = 0, + rightIndent: float = 0, + bullet=None, + spaceBefore: float | None = None, + spaceAfter: float | None = None, + ) -> None: ... + +class ListItem: + # NOTE: style has to be a ListStyle, but this will be annoying with sheet["ul"] + # TODO: Use Unpack for kwds with the ListStyle properties + value/spaceBefore/spaceAfter + def __init__(self, flowables: _FlowableSublist, style: PropertySet | None = None, **kwds) -> None: ... + +class ListFlowable(_Container, Flowable, _FindSplitterMixin): # pyrefly: ignore [inconsistent-inheritance] + style: ListStyle + # NOTE: style has to be a ListStyle, but this will be annoying with sheet["ul"] + # TODO: Use Unpack for kwds with the ListStyle properties + spaceBefore/spaceAfter + def __init__(self, flowables: Iterable[_NestedFlowable], start=None, style: PropertySet | None = None, **kwds) -> None: ... + +class TopPadder(Flowable): + # NOTE: TopPadder is mostly a transparent wrapper, we may consider trying + # something using __new__ in the future + def __init__(self, f: Flowable) -> None: ... + def __setattr__(self, a: str, v: Any) -> None: ... + def __getattr__(self, a: str) -> Any: ... + def __delattr__(self, a: str) -> None: ... + +class DocAssign(NullDraw): + args: tuple[Any, ...] + def __init__(self, var: str, expr: object, life: str = "forever") -> None: ... + def funcWrap(self, aW: float, aH: float) -> None: ... + def func(self) -> None: ... + +class DocExec(DocAssign): + def __init__(self, stmt: str, lifetime: str = "forever") -> None: ... + +class DocPara(DocAssign): + expr: object + format: str | None + style: PropertySet | None + klass: Incomplete + escape: bool + def __init__( + self, + expr: object, + format: str | None = None, + style: PropertySet | None = None, + klass: _StyledFlowableFactory | None = None, + escape: bool = True, + ) -> None: ... + def funcWrap(self, aW: float, aH: float) -> Any: ... + def func(self) -> Any: ... + def add_content(self, *args: Flowable) -> None: ... + def get_value(self, aW: float, aH: float) -> str: ... + +class DocAssert(DocPara): + def __init__(self, cond: object, format: str | None = None) -> None: ... + +class DocIf(DocPara): + blocks: tuple[_FlowableSublist, _FlowableSublist] + def __init__(self, cond: object, thenBlock: _FlowableSublist, elseBlock: _FlowableSublist = []) -> None: ... + def checkBlock(self, block: _FlowableSublist) -> list[Flowable] | tuple[Flowable, ...]: ... + +class DocWhile(DocIf): + block: _FlowableSublist + def __init__(self, cond: object, whileBlock: _FlowableSublist) -> None: ... + +class SetTopFlowables(NullDraw): + def __init__(self, F: list[Flowable], show: bool = False) -> None: ... + +class SetPageTopFlowables(NullDraw): + def __init__(self, F: list[Flowable], show: bool = False) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/frames.pyi b/stubs/reportlab/reportlab/platypus/frames.pyi new file mode 100644 index 000000000000..f8e832c1b83a --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/frames.pyi @@ -0,0 +1,38 @@ +from typing import Literal + +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus.flowables import Flowable + +class Frame: + id: str | None + x1: float + y1: float + width: float + height: float + leftPadding: float + bottomPadding: float + rightPadding: float + topPadding: float + showBoundary: int + def __init__( + self, + x1: float, + y1: float, + width: float, + height: float, + leftPadding: float = 6, + bottomPadding: float = 6, + rightPadding: float = 6, + topPadding: float = 6, + id: str | None = None, + showBoundary: int = 0, + overlapAttachedSpace=None, + _debug=None, + ) -> None: ... + def add(self, flowable: Flowable, canv: Canvas, trySplit: int = 0) -> Literal[0, 1]: ... + def split(self, flowable: Flowable, canv: Canvas) -> list[Flowable]: ... + def drawBoundary(self, canv: Canvas) -> None: ... + def addFromList(self, drawlist: list[Flowable], canv: Canvas) -> None: ... + def add_generated_content(self, *C: Flowable) -> None: ... + +__all__ = ("Frame",) diff --git a/stubs/reportlab/reportlab/platypus/multicol.pyi b/stubs/reportlab/reportlab/platypus/multicol.pyi new file mode 100644 index 000000000000..09fe9cdb8e31 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/multicol.pyi @@ -0,0 +1,19 @@ +from collections.abc import Sequence + +from .flowables import Flowable, _Container, _FindSplitterMixin + +class MultiCol(_Container, _FindSplitterMixin, Flowable): # pyrefly: ignore [inconsistent-inheritance] + contents: Sequence[Flowable] + widths: Sequence[float | str] + minHeightNeeded: float + def __init__( + self, + contents: Sequence[Flowable], + widths: Sequence[float | str], + minHeightNeeded: float = 36, + spaceBefore: float | None = None, + spaceAfter: float | None = None, + ) -> None: ... + def nWidths(self, aW: float) -> list[float]: ... + +__all__ = ["MultiCol"] diff --git a/stubs/reportlab/reportlab/platypus/para.pyi b/stubs/reportlab/reportlab/platypus/para.pyi new file mode 100644 index 000000000000..f2205c40992b --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/para.pyi @@ -0,0 +1,276 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Mapping +from typing import Any, Final, Literal, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +from reportlab.lib.colors import Color +from reportlab.lib.styles import ParagraphStyle, PropertySet, StyleSheet1 +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfgen.textobject import PDFTextObject, _Color +from reportlab.platypus.flowables import Flowable + +_T = TypeVar("_T") +_BoolInt: TypeAlias = Literal[0, 1] +_Op: TypeAlias = _SupportsWidthAndExecute | str | float | tuple[str, Unpack[tuple[Any, ...]]] +# NOTE: Output from pyRXP xml parser +_ParsedText: TypeAlias = tuple[str, dict[str, Any], list[_ParsedText], Any] | list[_ParsedText] | str + +@type_check_only +class _LineOpHandler(Protocol): + def start_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + def end_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + +@type_check_only +class _SupportsWidthAndExecute(Protocol): + def width(self, engine) -> float: ... + def execute(self, engine, textobject: PDFTextObject, canvas: Canvas) -> object: ... + +@type_check_only +class _SimpleStyleKwargs(TypedDict, total=False): + fontName: str + fontSize: float + leading: float + leftIndent: float + rightIndent: float + firstLineIndent: float + alignment: Literal[0, 1, 2, 4] + spaceBefore: float + spaceAfter: float + bulletFontName: str + bulletFontSize: float + bulletIndent: float + textColor: _Color + backColor: _Color | None + +debug: int +DUMPPROGRAM: int +TOOSMALLSPACE: float + +class paragraphEngine: + TEXT_STATE_VARIABLES: Final[tuple[str, ...]] + lineOpHandlers: list[_LineOpHandler] + program: list[_Op] + indent: float + baseindent: float + fontName: str + fontSize: float + leading: float + fontColor: _Color + x: float + y: float + alignment: Literal[0, 1, 2, 4] + # NOTE: The inner list matches TEXT_STATE_VARIABLES + textStateStack: list[list[Any]] + def __init__(self, program: list[_Op] | None = None) -> None: ... + def pushTextState(self) -> list[Any]: ... + def popTextState(self) -> None: ... + def format( + self, maxwidth: float, maxheight: float, program: list[_Op], leading: float = 0 + ) -> tuple[list[_Op], str, dict[str, Any], float]: ... + def getState(self) -> dict[str, Any]: ... + def resetState(self, state: dict[str, Any]) -> None: ... + def fitLine( + self, program: list[_Op], totalLength: float + ) -> tuple[Literal[0, 1], list[_Op], int, float, float, float, Literal[0, 1]]: ... + def centerAlign(self, line: list[_Op], lineLength: float, maxLength: float) -> list[_Op]: ... + def rightAlign(self, line: list[_Op], lineLength: float, maxLength: float) -> list[_Op]: ... + def insertShift(self, line: list[_Op], shift: float) -> list[_Op]: ... + def justifyAlign(self, line: list[_Op], lineLength: float, maxLength: float) -> list[_Op]: ... + def shrinkWrap(self, line: list[_Op]) -> list[_Op]: ... + def cleanProgram(self, line: list[_Op]) -> list[_Op]: ... + def runOpCodes(self, program: list[_Op], canvas: Canvas, textobject: PDFTextObject) -> dict[str, Any]: ... + +def stringLine(line: list[_Op], length: float) -> list[_Op]: ... +def simpleJustifyAlign(line: list[_Op], currentLength: float, maxLength: float) -> list[_Op]: ... +def readBool(text: str) -> _BoolInt: ... +def readAlignment(text: str) -> Literal[0, 1, 2, 4] | None: ... +def readLength(text: str) -> float: ... + +@overload +def lengthSequence(s: str, converter: Callable[[str], float] = ...) -> list[float]: ... +@overload +def lengthSequence(s: str, converter: Callable[[str], _T]) -> list[_T]: ... + +def readColor(text: str | None) -> Color | None: ... + +class StyleAttributeConverters: + fontSize: list[Callable[[str], float]] + leading: list[Callable[[str], float]] + leftIndent: list[Callable[[str], float]] + rightIndent: list[Callable[[str], float]] + firstLineIndent: list[Callable[[str], float]] + alignment: list[Callable[[str], Literal[0, 1, 2, 4] | None]] + spaceBefore: list[Callable[[str], float]] + spaceAfter: list[Callable[[str], float]] + bulletFontSize: list[Callable[[str], float]] + bulletIndent: list[Callable[[str], float]] + textColor: list[Callable[[str], Color | None]] + backColor: list[Callable[[str], Color | None]] + +class SimpleStyle: + name: str + fontName: str + fontSize: float + leading: float + leftIndent: float + rightIndent: float + firstLineIndent: float + alignment: Literal[0, 1, 2, 4] + spaceBefore: float + spaceAfter: float + bulletFontName: str + bulletFontSize: float + bulletIndent: float + textColor: _Color + backColor: _Color | None + # NOTE: We are being generous by allowing PropertySet i.e. ParagraphStyle here + # technically SimpleStyle is more strict and doesn't allow string alignments + def __init__(self, name: str, parent: SimpleStyle | PropertySet | None = None, **kw: Unpack[_SimpleStyleKwargs]) -> None: ... + def addAttributes(self, dictionary: Mapping[str, str | None]) -> None: ... + +DEFAULT_ALIASES: Final[dict[str, str]] + +class FastPara(Flowable): + style: SimpleStyle | ParagraphStyle + simpletext: str + lines: list[str] | None + # NOTE: We are being generous by allowing PropertySet i.e. ParagraphStyle here + # technically SimpleStyle is more strict and doesn't allow string alignments + def __init__(self, style: SimpleStyle | PropertySet, simpletext: str) -> None: ... + def draw(self) -> None: ... + +def defaultContext() -> dict[str, PropertySet]: ... +def buildContext(stylesheet: StyleSheet1 | None = None) -> dict[str, PropertySet]: ... + +class Para(Flowable): + baseindent: float + context: dict[str, PropertySet] + parsedText: _ParsedText + bulletText: str | None + style1: SimpleStyle | PropertySet + program: list[_Op] + formattedProgram: list[_Op] + remainder: _ParsedText + state: dict[str, Any] + bold: _BoolInt + italic: _BoolInt + face: str + size: float + def __init__( + self, + # NOTE: We are being generous by allowing PropertySet i.e. ParagraphStyle here + # technically SimpleStyle is more strict and doesn't allow string alignments + style: SimpleStyle | PropertySet, + parsedText: tuple[Any, ...] | None = None, + bulletText: str | None = None, + state: dict[str, Any] | None = None, + context: dict[str, PropertySet] | None = None, + baseindent: float = 0, + ) -> None: ... + def draw(self) -> None: ... + def compileProgram(self, parsedText: _ParsedText, program: list[_Op] | None = None) -> list[_Op]: ... + def linearize(self, program: list[_Op] | None = None, parsedText: _ParsedText | None = None) -> None: ... + def compileComponent(self, parsedText: _ParsedText, program: list[_Op]) -> None: ... + def shiftfont( + self, program: list[_Op], face: str | None = None, bold: _BoolInt | None = None, italic: _BoolInt | None = None + ): ... + def compile_(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_pageNumber(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_b(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_i(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_u(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_sub(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_ul(self, attdict, content, extra, program: list[_Op], tagname: str = "ul") -> None: ... + def compile_ol(self, attdict, content, extra, program: list[_Op]): ... + def compile_dl(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_super(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_font(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_a(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_link(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_setLink(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_bullet(self, attdict, content, extra, program: list[_Op]) -> None: ... + def do_bullet(self, text: str, program: list[_Op]) -> None: ... + def compile_tt(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_greek(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_evalString(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_name(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_getName(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_seq(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_seqReset(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_seqDefault(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_para(self, attdict, content, extra, program: list[_Op], stylename: str = "para.defaultStyle") -> None: ... + +class bulletMaker: + tagname: Literal["ul", "ol", "dl"] + style: str + typ: str + count: int + def __init__(self, tagname: Literal["ul", "ol", "dl"], atts, context) -> None: ... + def makeBullet(self, atts, bl: str | None = None) -> None: ... + +class EvalStringObject: + tagname: str + attdict: Incomplete + content: str + context: Incomplete + extra: Incomplete + op: Incomplete + def __init__(self, attdict, content: str, extra, context) -> None: ... + def getOp(self, tuple, engine): ... + def width(self, engine) -> float: ... + def execute(self, engine, textobject: PDFTextObject, canvas: Canvas) -> None: ... + +class SeqObject(EvalStringObject): ... +class NameObject(EvalStringObject): ... +class SeqDefaultObject(NameObject): ... +class SeqResetObject(NameObject): ... +class GetNameObject(EvalStringObject): ... + +class PageNumberObject: + example: str + def __init__(self, example: str = "XXX") -> None: ... + def width(self, engine) -> float: ... + def execute(self, engine, textobject: PDFTextObject, canvas: Canvas) -> None: ... + +def EmbedInRml2pdf() -> None: ... +def handleSpecialCharacters(engine, text: str, program: list[_Op] | None = None) -> list[_Op]: ... +def Paragraph( + text: str, + style: SimpleStyle | PropertySet, + bulletText: str | None = None, + frags: Unused | None = None, + context: dict[str, PropertySet] | None = None, +) -> Para | FastPara: ... + +class UnderLineHandler: + color: _Color | None + # NOTE: available after start_at + xStart: float + yStart: float + def __init__(self, color: _Color | None = None) -> None: ... + def start_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + def end_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + +UNDERLINE: Final[UnderLineHandler] + +class HotLink(UnderLineHandler): + url: str + def __init__(self, url: str) -> None: ... + def link(self, rect, canvas: Canvas) -> None: ... + +class InternalLink(HotLink): ... + +class DefDestination(HotLink): + defined: _BoolInt + +def splitspace(text: str) -> list[str]: ... + +testparagraph: str +testparagraph1: str + +def test2(canv, testpara) -> None: ... + +testlink: Incomplete +test_program: Incomplete + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/paragraph.pyi b/stubs/reportlab/reportlab/platypus/paragraph.pyi new file mode 100644 index 000000000000..6f38d99f8ec6 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/paragraph.pyi @@ -0,0 +1,40 @@ +from reportlab.lib.abag import ABag +from reportlab.lib.styles import ParagraphStyle, PropertySet +from reportlab.pdfgen.textobject import PDFTextObject +from reportlab.platypus.flowables import Flowable +from reportlab.platypus.paraparser import ParaFrag + +class ParaLines(ABag): ... +class FragLine(ABag): ... + +def cleanBlockQuotedText(text: str, joiner: str = " ") -> str: ... + +class Paragraph(Flowable): + text: str + frags: list[ParaFrag] + style: ParagraphStyle + bulletText: str | None + caseSensitive: int + encoding: str + def __init__( + self, + text: str, + # NOTE: This should be a ParagraphStyle + style: PropertySet | None = None, + bulletText: str | None = None, + frags: list[ParaFrag] | None = None, + caseSensitive: int = 1, + encoding: str = "utf8", + ) -> None: ... + def minWidth(self) -> float: ... + def draw(self) -> None: ... + def breakLines(self, width: float | list[float] | tuple[float, ...]) -> ParaLines | ParaFrag: ... + def breakLinesCJK(self, maxWidths: float | list[float] | tuple[float, ...]) -> ParaLines | ParaFrag: ... + def beginText(self, x: float, y: float) -> PDFTextObject: ... + def drawPara(self, debug: int = 0) -> None: ... + def getPlainText(self, identify: bool | None = None) -> str: ... + def getActualLineWidths0(self) -> list[float]: ... + @staticmethod + def dumpFrags(frags, indent: int = 4, full: bool = False) -> str: ... + +__all__ = ("Paragraph", "cleanBlockQuotedText", "ParaLines", "FragLine") diff --git a/stubs/reportlab/reportlab/platypus/paraparser.pyi b/stubs/reportlab/reportlab/platypus/paraparser.pyi new file mode 100644 index 000000000000..449946eb0806 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/paraparser.pyi @@ -0,0 +1,117 @@ +from _typeshed import Incomplete +from html.parser import HTMLParser + +from reportlab.lib.abag import ABag + +__all__ = ("ParaFrag", "ParaParser") + +class _PCT(float): + def __new__(cls, v): ... + def normalizedValue(self, normalizer): ... + def __copy__(self): ... + def __deepcopy__(self, mem): ... + +class _ExValidate: + tag: Incomplete + attr: Incomplete + def __init__(self, tag, attr) -> None: ... + def invalid(self, s) -> None: ... + def validate(self, parser, s): ... + def __call__(self, parser, s): ... + +class _CheckSup(_ExValidate): + fontSize: Incomplete + def validate(self, parser, s): ... + def __call__(self, parser, s): ... + +class _CheckUS(_ExValidate): + def validate(self, parser, s): ... + +class ParaFrag(ABag): ... + +class ParaParser(HTMLParser): + def __getattr__(self, attrName): ... + def start_b(self, attributes) -> None: ... + def end_b(self) -> None: ... + def start_strong(self, attributes) -> None: ... + def end_strong(self) -> None: ... + def start_i(self, attributes) -> None: ... + def end_i(self) -> None: ... + def start_em(self, attributes) -> None: ... + def end_em(self) -> None: ... + def start_u(self, attributes) -> None: ... + def end_u(self) -> None: ... + def start_strike(self, attributes) -> None: ... + def end_strike(self) -> None: ... + def start_link(self, attributes) -> None: ... + def end_link(self) -> None: ... + def start_a(self, attributes) -> None: ... + def end_a(self) -> None: ... + def start_img(self, attributes) -> None: ... + def end_img(self) -> None: ... + def start_super(self, attributes) -> None: ... + def end_super(self) -> None: ... + start_sup = start_super + end_sup = end_super + def start_sub(self, attributes) -> None: ... + def end_sub(self) -> None: ... + def start_nobr(self, attrs) -> None: ... + def end_nobr(self) -> None: ... + def handle_charref(self, name) -> None: ... + def syntax_error(self, lineno, message) -> None: ... + def start_greek(self, attr) -> None: ... + def end_greek(self) -> None: ... + def start_unichar(self, attr) -> None: ... + def end_unichar(self) -> None: ... + def start_font(self, attr) -> None: ... + def end_font(self) -> None: ... + def start_span(self, attr) -> None: ... + def end_span(self) -> None: ... + def start_br(self, attr) -> None: ... + def end_br(self) -> None: ... + def start_para(self, attr) -> None: ... + def end_para(self) -> None: ... + bFragList: Incomplete + def start_bullet(self, attr) -> None: ... + def end_bullet(self) -> None: ... + def start_seqdefault(self, attr) -> None: ... + def end_seqdefault(self) -> None: ... + def start_seqreset(self, attr) -> None: ... + def end_seqreset(self) -> None: ... + def start_seqchain(self, attr) -> None: ... + end_seqchain = end_seqreset + def start_seqformat(self, attr) -> None: ... + end_seqformat = end_seqreset + start_seqDefault = start_seqdefault + end_seqDefault = end_seqdefault + start_seqReset = start_seqreset + end_seqReset = end_seqreset + start_seqChain = start_seqchain + end_seqChain = end_seqchain + start_seqFormat = start_seqformat + end_seqFormat = end_seqformat + def start_seq(self, attr) -> None: ... + def end_seq(self) -> None: ... + def start_ondraw(self, attr) -> None: ... + start_onDraw = start_ondraw + end_onDraw = end_seq + end_ondraw = end_seq + def start_index(self, attr) -> None: ... + end_index = end_seq + def start_unknown(self, attr) -> None: ... + end_unknown = end_seq + def getAttributes(self, attr, attrMap): ... + verbose: Incomplete + caseSensitive: Incomplete + ignoreUnknownTags: Incomplete + def __init__( + self, verbose: int = 0, caseSensitive: int = 0, ignoreUnknownTags: int = 1, crashOnError: bool = True + ) -> None: ... + def handle_data(self, data) -> None: ... + def handle_cdata(self, data) -> None: ... + def tt_parse(self, tt, style): ... + def findSpanStyle(self, style) -> None: ... + def parse(self, text, style): ... + def handle_starttag(self, tag, attrs) -> None: ... + def handle_endtag(self, tag) -> None: ... + def handle_entityref(self, name) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/tableofcontents.pyi b/stubs/reportlab/reportlab/platypus/tableofcontents.pyi new file mode 100644 index 000000000000..0ae40aa5b850 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/tableofcontents.pyi @@ -0,0 +1,110 @@ +from _typeshed import Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Final, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +from reportlab.lib.styles import ParagraphStyle, PropertySet +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus.doctemplate import IndexingFlowable, _CanvasMaker +from reportlab.platypus.tables import TableStyle + +_T = TypeVar("_T") +_Entry: TypeAlias = tuple[int, str, int] | tuple[int, str, int, str | None] | Sequence[int | str | None] +_SequencerFormat: TypeAlias = Literal["I", "i", "123", "ABC", "abc"] + +@type_check_only +class _TableOfContentsKwargs(TypedDict, total=False): + rightColumnWidth: float + levelStyles: list[PropertySet] # should be ParagraphStyle + tableStyle: TableStyle + dotsMinLevel: int + formatter: Callable[[int], str] | None + +@type_check_only +class _SimpleIndexKwargs(TypedDict, total=False): + style: Iterable[PropertySet] | PropertySet | None # should be ParagraphStyle + dot: str | None + tableStyle: TableStyle | None + headers: bool + name: str | None + format: _SequencerFormat + offset: int + +__version__: Final[str] + +def unquote(txt: str) -> str: ... +def drawPageNumbers( + canvas: Canvas, + style: PropertySet, # should be ParagraphStyle + pages: Iterable[tuple[int | str, Unused]], + availWidth: float, + availHeight: float, + dot: str = " . ", + formatter: Unused | None = None, +) -> None: ... + +delta: float +epsilon: float +defaultLevelStyles: list[ParagraphStyle] +defaultTableStyle: TableStyle + +class TableOfContents(IndexingFlowable): + rightColumnWidth: float + levelStyles: list[ParagraphStyle] + tableStyle: TableStyle + dotsMinLevel: int + formatter: Callable[[int], str] | None + def __init__(self, **kwds: Unpack[_TableOfContentsKwargs]) -> None: ... + def isIndexing(self) -> Literal[1]: ... + def isSatisfied(self) -> bool: ... + def clearEntries(self) -> None: ... + def getLevelStyle(self, n: int) -> ParagraphStyle: ... + def addEntry(self, level: int, text: str, pageNum: int, key: str | None = None) -> None: ... + def addEntries(self, listOfEntries: Iterable[_Entry]) -> None: ... + +@overload +def makeTuple(x: tuple[_T, ...]) -> tuple[_T, ...]: ... +@overload +def makeTuple(x: list[_T]) -> tuple[_T, ...]: ... +@overload +def makeTuple(x: _T) -> tuple[_T, ...]: ... + +class SimpleIndex(IndexingFlowable): + # NOTE: Will be a list after getLevelStyle is called + textStyle: ParagraphStyle | Iterable[ParagraphStyle] | list[ParagraphStyle] + tableStyle: TableStyle + dot: str | None + headers: bool + name: str + formatFunc: Callable[[int], str] + offset: float + def __init__(self, **kwargs: Unpack[_SimpleIndexKwargs]) -> None: ... + def getFormatFunc(self, formatName): ... + def setup( + self, + style: PropertySet | None = None, # should be ParagraphStyle + dot: str | None = None, + tableStyle: TableStyle | None = None, + headers: bool = True, + name: str | None = None, + format: _SequencerFormat = "123", + offset: float = 0, + ) -> None: ... + def __call__(self, canv: Canvas, kind: str | None, label: str) -> None: ... + def getCanvasMaker(self, canvasmaker: _CanvasMaker = ...) -> _CanvasMaker: ... + def isIndexing(self) -> Literal[1]: ... + def isSatisfied(self) -> bool: ... + def clearEntries(self) -> None: ... + def addEntry(self, text: str, pageNum: tuple[int, str], key: str | None = None) -> None: ... + def draw(self) -> None: ... + def getLevelStyle(self, n: int) -> ParagraphStyle: ... + +AlphabeticIndex = SimpleIndex + +def listdiff(l1: list[Any], l2: list[_T]) -> tuple[int, list[_T]]: ... + +class ReferenceText(IndexingFlowable): + textPattern: str + target: str + paraStyle: ParagraphStyle + def __init__(self, textPattern: str, targetKey: str) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/tables.pyi b/stubs/reportlab/reportlab/platypus/tables.pyi new file mode 100644 index 000000000000..2bcee72979e2 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/tables.pyi @@ -0,0 +1,136 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from collections.abc import Collection, Iterable, Sequence +from typing import Any, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Unpack + +from reportlab.lib.colors import Color +from reportlab.lib.styles import PropertySet +from reportlab.lib.utils import _UNSET_ +from reportlab.platypus.flowables import Flowable, _HAlignment, _VAlignment + +__all__ = ("Table", "TableStyle", "CellStyle", "LongTable") + +_Color: TypeAlias = Color | list[float] | tuple[float, float, float, float] | tuple[float, float, float] | str | int +# TODO: consider creating a tagged union of all the possible commands, although +# this would restrict us to passing cmds to TableStyle.__init__ in a tuple +# since a list would not be able to be inferred correctly +# All commands are a tuple with a str opcode as the first element, followed +# by the arguments for that command. Most commands start with two positions +# indicating the cell-range affected by the command, the only exception is +# the ROUNDEDCORNERS command which applies to the whole table always. +_SpecialRow: TypeAlias = Literal["splitfirst", "splitlast", "inrowsplitstart", "inrowsplitend"] +_TableSectionCommand: TypeAlias = tuple[str, tuple[int | _SpecialRow, int], tuple[int, int], Unpack[tuple[Any, ...]]] +_CornerRadii: TypeAlias = tuple[float, float, float, float] | list[float] +_RoundedCornersTableCommand: TypeAlias = tuple[Literal["ROUNDEDCORNERS"], _CornerRadii | None] +_TableCommand: TypeAlias = _TableSectionCommand | _RoundedCornersTableCommand + +class CellStyle(PropertySet): + name: str + fontname: str + fontsize: float + leading: float + leftPadding: float + rightPadding: float + topPadding: float + bottomPadding: float + firstLineIndent: float + color: _Color + alignment: Literal["LEFT", "CENTER", "CENTRE", "RIGHT", "DECIMAL"] + background: _Color + valign: Literal["TOP", "MIDDLE", "BOTTOM"] + href: str | None + direction: str | None + shaping: Incomplete | None + destination: Incomplete | None + def __init__(self, name: str, parent: CellStyle | None = None) -> None: ... + def copy(self, result: CellStyle | None = None) -> CellStyle: ... + +class TableStyle: + # TODO: Add TypedDict for Table properties that can be set through the style + def __init__(self, cmds: Iterable[_TableCommand] | None = None, parent: TableStyle | None = None, **kw) -> None: ... + + @overload + def add(self, *cmd: Unpack[_TableSectionCommand]) -> None: ... + @overload + def add(self, *cmd: Unpack[_RoundedCornersTableCommand]) -> None: ... + + def getCommands(self) -> list[_TableCommand]: ... + +class ShadowStyle(NamedTuple): + dx: int | Incomplete = 10 # TODO: is either `int` or `float` + dy: int | Incomplete = -10 # TODO: is either `int` or `float` + color0: _Color = "grey" + color1: _Color = "white" + nshades: int = 30 + +class Table(Flowable): + ident: str | None + repeatRows: int + repeatCols: int + splitByRow: int + splitInRow: int + spaceBefore: float + spaceAfter: float + def __init__( + self, + # NOTE: Technically only list or tuple works but lack of covariance + # on list makes this too annoying + data: Sequence[list[Any] | tuple[Any, ...]], + colWidths: Sequence[float | str | None] | float | str | None = None, + rowHeights: Sequence[float | None] | float | None = None, + style: TableStyle | Iterable[_TableCommand] | None = None, + # docs say list/tuple, but the implementation allows any collection + repeatRows: int | Collection[int] = 0, + repeatCols: int | Collection[int] = 0, + splitByRow: int = 1, + splitInRow: int = 0, + emptyTableAction: Literal["error", "indicate", "ignore"] | None = None, + ident: str | None = None, + hAlign: _HAlignment | None = None, + vAlign: _VAlignment | None = None, + normalizedData: int = 0, + cellStyles: Sequence[Sequence[CellStyle]] | None = None, + rowSplitRange: tuple[int, int] | None = None, + spaceBefore: float | None = None, + spaceAfter: float | None = None, + longTableOptimize=None, + minRowHeights: Sequence[float] | None = None, + cornerRadii: _CornerRadii | _UNSET_ | None = ..., + renderCB: TableRenderCB | None = None, + shadow: ShadowStyle | None = None, + ) -> None: ... + def identity(self, maxLen: int | None = 30) -> str: ... + def normalizeData(self, data: Iterable[Iterable[Any]]) -> list[list[Any]]: ... + def minWidth(self) -> float: ... + def setStyle(self, tblstyle: TableStyle | Iterable[_TableCommand]) -> None: ... + def normCellRange(self, sc: int, ec: int, sr: int, er: int) -> tuple[int, int, int, int]: ... + def onSplit(self, T: Table, byRow: int = 1) -> None: ... + def draw(self) -> None: ... + +class LongTable(Table): ... + +class TableRenderCB: + def __call__(self, T: Table, cmd: str, *args: Any) -> None: ... + @abstractmethod + def startTable(self, T: Table) -> None: ... + @abstractmethod + def startBG(self, T: Table) -> None: ... + @abstractmethod + def endBG(self, T: Table) -> None: ... + @abstractmethod + def startRow(self, T: Table, rowNo: int) -> None: ... + @abstractmethod + def startCell( + self, T: Table, rowNo: int, colNo: int, cellval: Any, cellstyle: CellStyle, pos: tuple[int, int], size: tuple[int, int] + ) -> None: ... + @abstractmethod + def endCell(self, T: Table) -> None: ... + @abstractmethod + def endRow(self, T: Table) -> None: ... + @abstractmethod + def startLines(self, T: Table) -> None: ... + @abstractmethod + def endLines(self, T: Table) -> None: ... + @abstractmethod + def endTable(self, T: Table) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/xpreformatted.pyi b/stubs/reportlab/reportlab/platypus/xpreformatted.pyi new file mode 100644 index 000000000000..c5b5e4c81b4e --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/xpreformatted.pyi @@ -0,0 +1,32 @@ +from reportlab.lib.styles import PropertySet +from reportlab.platypus.paragraph import Paragraph, ParaLines +from reportlab.platypus.paraparser import ParaFrag + +class XPreformatted(Paragraph): + def __init__( + self, + text: str, + # NOTE: This should be a ParagraphStyle + style: PropertySet, + bulletText: str | None = None, + frags: list[ParaFrag] | None = None, + caseSensitive: int = 1, + dedent: int = 0, + ) -> None: ... + def breakLinesCJK(self, width: float | list[float] | tuple[float, ...]) -> ParaLines | ParaFrag: ... + +class PythonPreformatted(XPreformatted): + formats: dict[str, tuple[str, str]] + def __init__( + self, + text: str, + # NOTE: This should be a ParagraphStyle + style: PropertySet, + bulletText: str | None = None, + dedent: int = 0, + frags: list[ParaFrag] | None = None, + ) -> None: ... + def escapeHtml(self, text: str) -> str: ... + def fontify(self, code: str) -> str: ... + +__all__ = ("XPreformatted", "PythonPreformatted") diff --git a/stubs/reportlab/reportlab/rl_config.pyi b/stubs/reportlab/reportlab/rl_config.pyi new file mode 100644 index 000000000000..5267a7f269a5 --- /dev/null +++ b/stubs/reportlab/reportlab/rl_config.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Literal +from weakref import ReferenceType + +__all__ = ("_reset", "register_reset") + +def register_reset( + func: Callable[[], Callable[[], object] | None], callback: Callable[[ReferenceType[Any]], object] | None = None +) -> None: ... +def _reset() -> None: ... + +allowTableBoundsErrors: int +shapeChecking: int +defaultEncoding: str +defaultGraphicsFontName: str +pageCompression: int +useA85: int +defaultPageSize: tuple[float, float] +defaultImageCaching: int +warnOnMissingFontGlyphs: int +verbose: int +showBoundary: int +emptyTableAction: str +invariant: int +eps_preview_transparent: Incomplete +eps_preview: int +eps_ttf_embed: int +eps_ttf_embed_uid: int +overlapAttachedSpace: int +longTableOptimize: int +autoConvertEncoding: int +_FUZZ: float +wrapA85: int +fsEncodings: tuple[Literal["utf8"], Literal["cp1252"], Literal["cp430"]] +odbc_driver: str +platypus_link_underline: int +canvas_basefontname: str +allowShortTableRows: int +imageReaderFlags: int +paraFontSizeHeightOffset: int +canvas_baseColor: Incomplete +ignoreContainerActions: int +ttfAsciiReadable: int +pdfMultiLine: int +pdfComments: int +debug: int +listWrapOnFakeWidth: int +underlineWidth: str +underlineOffset: str +underlineGap: str +strikeWidth: str +strikeOffset: str +strikeGap: str +decimalSymbol: str +errorOnDuplicatePageLabelPage: int +autoGenerateMissingTTFName: int +allowTTFSubsetting: list[str] +spaceShrinkage: float +hyphenationLang: str +uriWasteReduce: int +embeddedHyphenation: int +hyphenationMinWordLength: int +reserveTTFNotdef: int +documentLang: Incomplete +encryptionStrength: int +trustedHosts: list[str] | None +trustedSchemes: list[str] +renderPMBackend: str +xmlParser: str +textPaths: str +toColorCanUse: str +defCWRF: float +unShapedFontGlob: list[str] | None +T1SearchPath: list[str] +TTFSearchPath: list[str] +CMapSearchPath: list[str] diff --git a/stubs/reportlab/reportlab/rl_settings.pyi b/stubs/reportlab/reportlab/rl_settings.pyi new file mode 100644 index 000000000000..8e36a529bb22 --- /dev/null +++ b/stubs/reportlab/reportlab/rl_settings.pyi @@ -0,0 +1,140 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +__version__: Final[str] + +# NOTE: All the attributes in this module are Final +# rl_config is the place to make changes +allowTableBoundsErrors: Final[int] +shapeChecking: Final[int] +defaultEncoding: Final[str] +defaultGraphicsFontName: Final[str] +pageCompression: Final[int] +useA85: Final[int] +defaultPageSize: Final[str] +defaultImageCaching: Final[int] +warnOnMissingFontGlyphs: Final[int] +verbose: Final[int] +showBoundary: Final[int] +emptyTableAction: Final[str] +invariant: Final[int] +eps_preview_transparent: Final[Incomplete] +eps_preview: Final[int] +eps_ttf_embed: Final[int] +eps_ttf_embed_uid: Final[int] +overlapAttachedSpace: Final[int] +longTableOptimize: Final[int] +autoConvertEncoding: Final[int] +_FUZZ: Final[float] +wrapA85: Final[int] +fsEncodings: Final[tuple[Literal["utf8"], Literal["cp1252"], Literal["cp430"]]] +odbc_driver: Final[str] +platypus_link_underline: Final[int] +canvas_basefontname: Final[str] +allowShortTableRows: Final[int] +imageReaderFlags: Final[int] +paraFontSizeHeightOffset: Final[int] +canvas_baseColor: Final[Incomplete] +ignoreContainerActions: Final[int] +ttfAsciiReadable: Final[int] +pdfMultiLine: Final[int] +pdfComments: Final[int] +debug: Final[int] +listWrapOnFakeWidth: Final[int] +underlineWidth: Final[str] +underlineOffset: Final[str] +underlineGap: Final[str] +strikeWidth: Final[str] +strikeOffset: Final[str] +strikeGap: Final[str] +decimalSymbol: Final[str] +errorOnDuplicatePageLabelPage: Final[int] +autoGenerateMissingTTFName: Final[int] +allowTTFSubsetting: Final[list[str]] +spaceShrinkage: Final[float] +hyphenationLang: Final[str] +uriWasteReduce: Final[int] +embeddedHyphenation: Final[int] +hyphenationMinWordLength: Final[int] +reserveTTFNotdef: Final[int] +documentLang: Final[Incomplete] +encryptionStrength: Final[int] +trustedHosts: Final[Incomplete] +trustedSchemes: Final[list[str]] +renderPMBackend: Final[str] +xmlParser: Final[str] +textPaths: Final[str] +toColorCanUse: Final[str] +defCWRF: Final[float] +unShapedFontGlob: list[str] | None +T1SearchPath: Final[tuple[str, ...]] +TTFSearchPath: Final[tuple[str, ...]] +CMapSearchPath: Final[tuple[str, ...]] + +__all__ = ( + "allowTableBoundsErrors", + "shapeChecking", + "defaultEncoding", + "defaultGraphicsFontName", + "pageCompression", + "useA85", + "defaultPageSize", + "defaultImageCaching", + "warnOnMissingFontGlyphs", + "verbose", + "showBoundary", + "emptyTableAction", + "invariant", + "eps_preview_transparent", + "eps_preview", + "eps_ttf_embed", + "eps_ttf_embed_uid", + "overlapAttachedSpace", + "longTableOptimize", + "autoConvertEncoding", + "_FUZZ", + "wrapA85", + "fsEncodings", + "odbc_driver", + "platypus_link_underline", + "canvas_basefontname", + "allowShortTableRows", + "imageReaderFlags", + "paraFontSizeHeightOffset", + "canvas_baseColor", + "ignoreContainerActions", + "ttfAsciiReadable", + "pdfMultiLine", + "pdfComments", + "debug", + "listWrapOnFakeWidth", + "T1SearchPath", + "TTFSearchPath", + "CMapSearchPath", + "decimalSymbol", + "errorOnDuplicatePageLabelPage", + "autoGenerateMissingTTFName", + "allowTTFSubsetting", + "spaceShrinkage", + "underlineWidth", + "underlineOffset", + "underlineGap", + "strikeWidth", + "strikeOffset", + "strikeGap", + "hyphenationLang", + "uriWasteReduce", + "embeddedHyphenation", + "hyphenationMinWordLength", + "reserveTTFNotdef", + "documentLang", + "encryptionStrength", + "trustedHosts", + "trustedSchemes", + "renderPMBackend", + "xmlParser", + "textPaths", + "toColorCanUse", + "defCWRF", + "unShapedFontGlob", +) diff --git a/stubs/requests-oauthlib/METADATA.toml b/stubs/requests-oauthlib/METADATA.toml new file mode 100644 index 000000000000..5ae6f9018d46 --- /dev/null +++ b/stubs/requests-oauthlib/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.0.*" +upstream-repository = "https://github.com/requests/requests-oauthlib" +dependencies = ["requests >= 2.34.0", "types-oauthlib"] diff --git a/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi b/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi new file mode 100644 index 000000000000..0a22c06d9e4f --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi @@ -0,0 +1,6 @@ +from .oauth1_auth import OAuth1 as OAuth1 +from .oauth1_session import OAuth1Session as OAuth1Session +from .oauth2_auth import OAuth2 as OAuth2 +from .oauth2_session import OAuth2Session as OAuth2Session, TokenUpdated as TokenUpdated + +__version__: str diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi new file mode 100644 index 000000000000..77a5568fad7a --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi @@ -0,0 +1,8 @@ +from .ebay import ebay_compliance_fix as ebay_compliance_fix +from .facebook import facebook_compliance_fix as facebook_compliance_fix +from .fitbit import fitbit_compliance_fix as fitbit_compliance_fix +from .instagram import instagram_compliance_fix as instagram_compliance_fix +from .mailchimp import mailchimp_compliance_fix as mailchimp_compliance_fix +from .plentymarkets import plentymarkets_compliance_fix as plentymarkets_compliance_fix +from .slack import slack_compliance_fix as slack_compliance_fix +from .weibo import weibo_compliance_fix as weibo_compliance_fix diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi new file mode 100644 index 000000000000..8a1384588d1b --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def douban_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi new file mode 100644 index 000000000000..58369d712b85 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def ebay_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi new file mode 100644 index 000000000000..6544ed533c45 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def facebook_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi new file mode 100644 index 000000000000..cd311cdc277a --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi @@ -0,0 +1,3 @@ +from requests_oauthlib import OAuth2Session + +def fitbit_compliance_fix(session: OAuth2Session) -> OAuth2Session: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi new file mode 100644 index 000000000000..342505444ff8 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def instagram_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi new file mode 100644 index 000000000000..f27eca44579d --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def mailchimp_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi new file mode 100644 index 000000000000..38f27441ebf8 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def plentymarkets_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi new file mode 100644 index 000000000000..f5f67b00e627 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def slack_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi new file mode 100644 index 000000000000..dd8c3b23b861 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def weibo_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi new file mode 100644 index 000000000000..75a2de35da1d --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi @@ -0,0 +1,35 @@ +from logging import Logger +from typing import Any + +from oauthlib.oauth1 import Client +from requests.auth import AuthBase + +CONTENT_TYPE_FORM_URLENCODED: str +CONTENT_TYPE_MULTI_PART: str +log: Logger + +class OAuth1(AuthBase): + client_class: type[Client] + client: Client + force_include_body: bool + def __init__( + self, + client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key=None, + verifier=None, + decoding: str | None = "utf-8", + client_class: type[Client] | None = None, + force_include_body: bool = False, + *, + realm=None, + encoding: str = "utf-8", + nonce=None, + timestamp=None, + **kwargs: Any, # passed to client_class's __init__ + ) -> None: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi new file mode 100644 index 000000000000..b7222d75de27 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Any, TypeAlias, TypedDict, type_check_only + +import requests +from oauthlib.oauth1 import Client + +from . import OAuth1 + +# should be dict[str, str] but could look different +_ParsedToken: TypeAlias = dict[str, Incomplete] + +@type_check_only +class _TokenDict(TypedDict, total=False): + oauth_token: Incomplete # oauthlib.oauth1.Client.resource_owner_key + oauth_token_secret: Incomplete # oauthlib.oauth1.Client.resource_token_secret + oauth_verifier: Incomplete # oauthlib.oauth1.Client.oauth_verifier + +log: Logger + +def urldecode(body): ... + +class TokenRequestDenied(ValueError): + response: requests.Response + def __init__(self, message: str, response: requests.Response) -> None: ... + @property + def status_code(self) -> int: ... + +class TokenMissing(ValueError): + response: requests.Response + def __init__(self, message: str, response: requests.Response) -> None: ... + +class VerifierMissing(ValueError): ... + +class OAuth1Session(requests.Session): + auth: OAuth1 + def __init__( + self, + client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key=None, + verifier=None, + client_class: type[Client] | None = None, + force_include_body: bool = False, + *, + decoding: str | None = "utf-8", + realm=None, + encoding: str = "utf-8", + nonce=None, + timestamp=None, + **kwargs: Any, # passed to client_class's __init__ + ) -> None: ... + + @property + def token(self) -> _TokenDict: ... + @token.setter + def token(self, value: _TokenDict) -> None: ... + + @property + def authorized(self) -> bool: ... + def authorization_url(self, url: str, request_token=None, **kwargs) -> str: ... + def fetch_request_token(self, url: str, realm=None, **request_kwargs) -> _ParsedToken: ... + def fetch_access_token(self, url: str, verifier=None, **request_kwargs) -> _ParsedToken: ... + def parse_authorization_response(self, url: str) -> _ParsedToken: ... + def rebuild_auth(self, prepared_request: requests.PreparedRequest, response: requests.Response) -> None: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi new file mode 100644 index 000000000000..9bd5a5258562 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi @@ -0,0 +1,5 @@ +from oauthlib.oauth2 import Client +from requests.auth import AuthBase + +class OAuth2(AuthBase): + def __init__(self, client_id=None, client: Client | None = None, token=None) -> None: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi new file mode 100644 index 000000000000..911045dcdf8d --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi @@ -0,0 +1,149 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Any, Literal, Protocol, TypeAlias, TypedDict, overload, type_check_only + +import requests +from oauthlib.oauth2 import Client +from requests import _types +from requests.cookies import RequestsCookieJar + +_Token: TypeAlias = dict[str, Incomplete] # oauthlib.oauth2.Client.token + +@type_check_only +class _AccessTokenResponseHook(Protocol): + def __call__(self, response: requests.Response, /) -> requests.Response: ... + +@type_check_only +class _RefreshTokenResponseHook(Protocol): + def __call__(self, response: requests.Response, /) -> requests.Response: ... + +@type_check_only +class _ProtectedRequestHook(Protocol): + def __call__(self, url, headers, data, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +@type_check_only +class _ComplianceHooks(TypedDict): + access_token_response: set[_AccessTokenResponseHook] + refresh_token_response: set[_RefreshTokenResponseHook] + protected_request: set[_ProtectedRequestHook] + +log: Logger + +class TokenUpdated(Warning): + token: Incomplete + def __init__(self, token) -> None: ... + +class OAuth2Session(requests.Session): + redirect_uri: Incomplete + state: Incomplete + auto_refresh_url: str | None + auto_refresh_kwargs: dict[str, Any] + token_updater: Incomplete + compliance_hook: _ComplianceHooks + def __init__( + self, + client_id=None, + client: Client | None = None, + auto_refresh_url: str | None = None, + auto_refresh_kwargs: dict[str, Any] | None = None, + scope=None, + redirect_uri=None, + token=None, + state=None, + token_updater=None, + pkce=None, + **kwargs, + ) -> None: ... + + @property + def scope(self) -> Incomplete | None: ... # oauthlib.oauth2.Client.scope + @scope.setter + def scope(self, value: Incomplete | None) -> None: ... + + def new_state(self): ... + + @property + def client_id(self) -> Incomplete | None: ... # oauthlib.oauth2.Client.client_id + @client_id.setter + def client_id(self, value: Incomplete | None) -> None: ... + @client_id.deleter + def client_id(self) -> None: ... + + @property + def token(self): ... # oauthlib.oauth2.Client.token + @token.setter + def token(self, value) -> None: ... + + @property + def access_token(self): ... # oauthlib.oauth2.Client.access_token + @access_token.setter + def access_token(self, value) -> None: ... + @access_token.deleter + def access_token(self) -> None: ... + + @property + def authorized(self) -> bool: ... + def authorization_url(self, url: str, state=None, **kwargs) -> tuple[str, str]: ... + def fetch_token( + self, + token_url: str, + code=None, + authorization_response=None, + body: str = "", + auth=None, + username=None, + password=None, + method: str = "POST", + force_querystring: bool = False, + timeout=None, + headers=None, + verify: bool | None = None, + proxies=None, + include_client_id=None, + client_secret=None, + cert=None, + **kwargs, + ) -> _Token: ... + def token_from_fragment(self, authorization_response: str) -> _Token: ... + def refresh_token( + self, + token_url: str, + refresh_token=None, + body: str = "", + auth=None, + timeout=None, + headers=None, + verify: bool | None = None, + proxies=None, + **kwargs, + ) -> _Token: ... + def request( # type: ignore[override] + self, + method: str | bytes, + url: str | bytes, + data: _types.DataType = None, + headers: _types.HeadersType = None, + withhold_token: bool = False, + client_id=None, + client_secret=None, + files: _types.FilesType = None, + *, + params: _types.ParamsType = None, + cookies: RequestsCookieJar | dict[str, str] | None = None, + auth: _types.AuthType = None, + timeout: _types.TimeoutType = None, + allow_redirects: bool = True, + proxies: dict[str, str] | None = None, + hooks: _types.HooksInputType | None = None, + stream: bool | None = None, + verify: _types.VerifyType | None = None, + cert: _types.CertType = None, + json=None, + ) -> requests.Response: ... + + @overload + def register_compliance_hook(self, hook_type: Literal["access_token_response"], hook: _AccessTokenResponseHook) -> None: ... + @overload + def register_compliance_hook(self, hook_type: Literal["refresh_token_response"], hook: _RefreshTokenResponseHook) -> None: ... + @overload + def register_compliance_hook(self, hook_type: Literal["protected_request"], hook: _ProtectedRequestHook) -> None: ... diff --git a/stubs/requests/@tests/stubtest_allowlist.txt b/stubs/requests/@tests/stubtest_allowlist.txt index 236bdeafdf90..9f24211ef4d4 100644 --- a/stubs/requests/@tests/stubtest_allowlist.txt +++ b/stubs/requests/@tests/stubtest_allowlist.txt @@ -1,105 +1,7 @@ -requests.Session.delete -requests.Session.get -requests.Session.head -requests.Session.options -requests.Session.patch -requests.Session.post -requests.Session.put -requests.adapters.HTTPResponse.__init__ -requests.adapters.PoolManager.connection_from_host -requests.adapters.PoolManager.connection_from_url -requests.adapters.PoolManager.urlopen -requests.adapters.Retry.is_forced_retry -requests.adapters.Retry.sleep -requests.api.delete -requests.api.get -requests.api.head -requests.api.options -requests.api.patch -requests.api.post -requests.api.put -requests.api.request -requests.compat.OrderedDict.fromkeys -requests.compat.OrderedDict.setdefault -requests.delete -requests.get -requests.head -requests.models.RequestField.__init__ -requests.models.RequestField.from_tuples -requests.options -requests.packages.VendorAlias -requests.packages.urllib3.HTTPConnectionPool.__init__ -requests.packages.urllib3.HTTPConnectionPool.urlopen -requests.packages.urllib3.HTTPResponse.__init__ -requests.packages.urllib3.HTTPSConnectionPool.__init__ -requests.packages.urllib3.NullHandler -requests.packages.urllib3.PoolManager.connection_from_host -requests.packages.urllib3.PoolManager.connection_from_url -requests.packages.urllib3.PoolManager.urlopen -requests.packages.urllib3.ProxyManager.__init__ -requests.packages.urllib3.ProxyManager.connection_from_host -requests.packages.urllib3.ProxyManager.urlopen -requests.packages.urllib3.Retry.is_forced_retry -requests.packages.urllib3.Retry.sleep -requests.packages.urllib3._collections.HTTPHeaderDict.from_httplib -requests.packages.urllib3._collections.HTTPHeaderDict.getlist -requests.packages.urllib3._collections.RLock -requests.packages.urllib3.connection.HTTPConnection.request -requests.packages.urllib3.connection.HTTPSConnection.__init__ -requests.packages.urllib3.connection.VerifiedHTTPSConnection.__init__ -requests.packages.urllib3.connection.VerifiedHTTPSConnection.set_cert -requests.packages.urllib3.connectionpool.ConnectionError -requests.packages.urllib3.connectionpool.HTTPConnection.request -requests.packages.urllib3.connectionpool.HTTPConnectionPool.__init__ -requests.packages.urllib3.connectionpool.HTTPConnectionPool.urlopen -requests.packages.urllib3.connectionpool.HTTPResponse.__init__ -requests.packages.urllib3.connectionpool.HTTPSConnection.__init__ -requests.packages.urllib3.connectionpool.HTTPSConnectionPool.__init__ -requests.packages.urllib3.connectionpool.ProxyError.__init__ -requests.packages.urllib3.connectionpool.RequestMethods.request_encode_url -requests.packages.urllib3.connectionpool.Retry.is_forced_retry -requests.packages.urllib3.connectionpool.Retry.sleep -requests.packages.urllib3.connectionpool.VerifiedHTTPSConnection.__init__ -requests.packages.urllib3.connectionpool.VerifiedHTTPSConnection.set_cert -requests.packages.urllib3.exceptions.ProxyError.__init__ -requests.packages.urllib3.fields.RequestField.__init__ -requests.packages.urllib3.fields.RequestField.from_tuples -requests.packages.urllib3.filepost.RequestField.__init__ -requests.packages.urllib3.filepost.RequestField.from_tuples -requests.packages.urllib3.poolmanager.PoolManager.connection_from_host -requests.packages.urllib3.poolmanager.PoolManager.connection_from_url -requests.packages.urllib3.poolmanager.PoolManager.urlopen -requests.packages.urllib3.poolmanager.ProxyManager.__init__ -requests.packages.urllib3.poolmanager.ProxyManager.connection_from_host -requests.packages.urllib3.poolmanager.ProxyManager.urlopen -requests.packages.urllib3.request.RequestMethods.request_encode_url -requests.packages.urllib3.response.HTTPHeaderDict.from_httplib -requests.packages.urllib3.response.HTTPHeaderDict.getlist -requests.packages.urllib3.response.HTTPResponse.__init__ -requests.packages.urllib3.response.PY3 -requests.packages.urllib3.util.Retry.is_forced_retry -requests.packages.urllib3.util.Retry.sleep -requests.packages.urllib3.util.connection.poll -requests.packages.urllib3.util.connection.select -requests.packages.urllib3.util.retry.Retry.is_forced_retry -requests.packages.urllib3.util.retry.Retry.sleep -requests.packages.urllib3.util.ssl_.create_default_context -requests.packages.urllib3.util.ssl_.ssl_wrap_socket -requests.patch -requests.post -requests.put -requests.request -requests.sessions.OrderedDict.fromkeys -requests.sessions.OrderedDict.setdefault -requests.sessions.Session.delete -requests.sessions.Session.get -requests.sessions.Session.head -requests.sessions.Session.options -requests.sessions.Session.patch -requests.sessions.Session.post -requests.sessions.Session.put -requests.sessions.SessionRedirectMixin.resolve_redirects -requests.structures.LookupDict.__getattr__ -requests.structures.LookupDict.get -requests.utils.OrderedDict.fromkeys -requests.utils.OrderedDict.setdefault +# Loop variables that leak into the global scope +requests.packages.mod +requests.packages.package +requests.packages.target + +# Should allow setting any attribute: +requests.structures.LookupDict.__setattr__ diff --git a/stubs/requests/@tests/test_cases/check_post.py b/stubs/requests/@tests/test_cases/check_post.py new file mode 100644 index 000000000000..d68a484d9c8e --- /dev/null +++ b/stubs/requests/@tests/test_cases/check_post.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from collections.abc import Iterable + +import requests + +# ================================================================================================= +# Regression test for #7988 (multiple files should be allowed for the "files" argument) +# This snippet comes from the requests documentation +# (https://requests.readthedocs.io/en/latest/user/advanced/#post-multiple-multipart-encoded-files), +# so should pass a type checker without error +# ================================================================================================= + + +url = "https://httpbin.org/post" +multiple_files = [ + ("images", ("foo.png", open("foo.png", "rb"), "image/png")), + ("images", ("bar.png", open("bar.png", "rb"), "image/png")), +] +r = requests.post(url, files=multiple_files) + + +# ================================================================================= +# Tests for various different types being passed into the "data" parameter +# (These all return "Any", so there's not much value in using assert_type here.) +# (Just test that type checkers don't emit an error if it doesn't fail at runtime.) +# ================================================================================= + + +# Arbitrary iterable +def gen() -> Iterable[bytes]: + yield b"foo" + yield b"bar" + + +requests.post("http://httpbin.org/anything", data=gen()).json()["data"] + +# bytes +requests.post("http://httpbin.org/anything", data=b"foobar").json()["data"] + +# str +requests.post("http://httpbin.org/anything", data="foobar").json()["data"] + +# Files +requests.post("http://httpbin.org/anything", data=open("/tmp/foobar", "rb", encoding="UTF-8")).json()["data"] +requests.post("http://httpbin.org/anything", data=open("/tmp/foobar", "r", encoding="UTF-8")).json()["data"] + +# Mappings +requests.post("http://httpbin.org/anything", data={b"foo": b"bar"}).json()["form"] +requests.post("http://httpbin.org/anything", data={"foo": "bar"}).json()["form"] + +# mappings represented by an list/tuple of key-values pairs +requests.post("http://httpbin.org/anything", data=[(b"foo", b"bar")]).json()["form"] +requests.post("http://httpbin.org/anything", data=[("foo", "bar")]).json()["form"] +requests.post("http://httpbin.org/anything", data=((b"foo", b"bar"),)).json()["form"] +requests.post("http://httpbin.org/anything", data=(("foo", "bar"),)).json()["form"] diff --git a/stubs/requests/METADATA.toml b/stubs/requests/METADATA.toml index 53ad05966f56..8f263ce769c9 100644 --- a/stubs/requests/METADATA.toml +++ b/stubs/requests/METADATA.toml @@ -1,2 +1,14 @@ -version = "2.26.*" -python2 = true +# requires a version of urllib3 with a py.typed file +version = "~=2.33.0" +upstream-repository = "https://github.com/psf/requests" +dependencies = ["urllib3>=2"] +extra-description = """\ + Note: `types-requests` has required `urllib3>=2` since v2.31.0.7. \ + If you need to install `types-requests` into an environment \ + that must also have `urllib3<2` installed into it, \ + you will have to use `types-requests<2.31.0.7`.\ + """ +obsolete-since = { version = "2.34.0", date = "2026-05-11" } + +[tool.stubtest] +extras = ["socks"] diff --git a/stubs/requests/requests/__init__.pyi b/stubs/requests/requests/__init__.pyi index 4c1a2d585355..199c59e9eea6 100644 --- a/stubs/requests/requests/__init__.pyi +++ b/stubs/requests/requests/__init__.pyi @@ -1,6 +1,4 @@ -import logging -from typing import Any, Text - +from . import __version__ as version_mod, packages as packages, utils as utils from .api import ( delete as delete, get as get, @@ -16,6 +14,7 @@ from .exceptions import ( ConnectTimeout as ConnectTimeout, FileModeWarning as FileModeWarning, HTTPError as HTTPError, + JSONDecodeError as JSONDecodeError, ReadTimeout as ReadTimeout, RequestException as RequestException, Timeout as Timeout, @@ -26,13 +25,15 @@ from .models import PreparedRequest as PreparedRequest, Request as Request, Resp from .sessions import Session as Session, session as session from .status_codes import codes as codes -__title__: Any -__build__: Any -__license__: Any -__copyright__: Any -__version__: Any - -class NullHandler(logging.Handler): - def emit(self, record): ... +__author__ = version_mod.__author__ +__author_email__ = version_mod.__author_email__ +__build__ = version_mod.__build__ +__cake__ = version_mod.__cake__ +__copyright__ = version_mod.__copyright__ +__description__ = version_mod.__description__ +__license__ = version_mod.__license__ +__title__ = version_mod.__title__ +__url__ = version_mod.__url__ +__version__ = version_mod.__version__ -def check_compatibility(urllib3_version: Text, chardet_version: Text | None, charset_normalizer_version: Text | None) -> None: ... +def check_compatibility(urllib3_version: str, chardet_version: str | None, charset_normalizer_version: str | None) -> None: ... diff --git a/stubs/requests/requests/__version__.pyi b/stubs/requests/requests/__version__.pyi new file mode 100644 index 000000000000..05c93ebcba6e --- /dev/null +++ b/stubs/requests/requests/__version__.pyi @@ -0,0 +1,12 @@ +from typing import Final + +__title__: Final = "requests" +__description__: Final[str] +__url__: Final[str] +__version__: Final[str] +__build__: Final[int] +__author__: Final[str] +__author_email__: Final[str] +__license__: Final[str] +__copyright__: Final[str] +__cake__: Final[str] diff --git a/stubs/requests/requests/adapters.pyi b/stubs/requests/requests/adapters.pyi index 34cc23ef5ca8..df4f1d401412 100644 --- a/stubs/requests/requests/adapters.pyi +++ b/stubs/requests/requests/adapters.pyi @@ -1,33 +1,57 @@ -from typing import Any, Container, Mapping, Text +from _typeshed import Incomplete +from collections.abc import Mapping +from ssl import SSLContext +from typing import Any, Literal, TypedDict, type_check_only +from typing_extensions import NotRequired, deprecated -from . import cookies, exceptions, models, structures, utils -from .packages.urllib3 import exceptions as urllib3_exceptions, poolmanager, response -from .packages.urllib3.util import retry +import urllib3 +from urllib3.connectionpool import ConnectionPool +from urllib3.contrib.socks import SOCKSProxyManager as SOCKSProxyManager +from urllib3.exceptions import ( + ConnectTimeoutError as ConnectTimeoutError, + MaxRetryError as MaxRetryError, + ProtocolError as ProtocolError, + ReadTimeoutError as ReadTimeoutError, + ResponseError as ResponseError, +) +from urllib3.poolmanager import PoolManager as PoolManager, proxy_from_url as proxy_from_url +from urllib3.util.retry import Retry as Retry -PreparedRequest = models.PreparedRequest -Response = models.Response -PoolManager = poolmanager.PoolManager -proxy_from_url = poolmanager.proxy_from_url -HTTPResponse = response.HTTPResponse -Retry = retry.Retry -DEFAULT_CA_BUNDLE_PATH = utils.DEFAULT_CA_BUNDLE_PATH -get_encoding_from_headers = utils.get_encoding_from_headers -prepend_scheme_if_needed = utils.prepend_scheme_if_needed -get_auth_from_url = utils.get_auth_from_url -urldefragauth = utils.urldefragauth -CaseInsensitiveDict = structures.CaseInsensitiveDict -ConnectTimeoutError = urllib3_exceptions.ConnectTimeoutError -MaxRetryError = urllib3_exceptions.MaxRetryError -ProtocolError = urllib3_exceptions.ProtocolError -ReadTimeoutError = urllib3_exceptions.ReadTimeoutError -ResponseError = urllib3_exceptions.ResponseError -extract_cookies_to_jar = cookies.extract_cookies_to_jar -ConnectionError = exceptions.ConnectionError -ConnectTimeout = exceptions.ConnectTimeout -ReadTimeout = exceptions.ReadTimeout -SSLError = exceptions.SSLError -ProxyError = exceptions.ProxyError -RetryError = exceptions.RetryError +from .cookies import extract_cookies_to_jar as extract_cookies_to_jar +from .exceptions import ( + ConnectionError as ConnectionError, + ConnectTimeout as ConnectTimeout, + ProxyError as ProxyError, + ReadTimeout as ReadTimeout, + RetryError as RetryError, + SSLError as SSLError, +) +from .models import PreparedRequest, Response as Response +from .structures import CaseInsensitiveDict as CaseInsensitiveDict +from .utils import ( + DEFAULT_CA_BUNDLE_PATH as DEFAULT_CA_BUNDLE_PATH, + _Uri, + get_auth_from_url as get_auth_from_url, + get_encoding_from_headers as get_encoding_from_headers, + prepend_scheme_if_needed as prepend_scheme_if_needed, + urldefragauth as urldefragauth, +) + +# Arguments to urllib3 connection_from_host() functions (except pool_kwargs). +@type_check_only +class _HostParams(TypedDict): + host: str + scheme: str + port: int + +@type_check_only +class _PoolKwargs(TypedDict): + ssl_context: NotRequired[SSLContext] + ca_certs: NotRequired[str] + ca_cert_dir: NotRequired[str] + cert_reqs: Literal["CERT_REQUIRED", "CERT_NONE"] + cert_file: NotRequired[str] + key_file: NotRequired[str] DEFAULT_POOLBLOCK: bool DEFAULT_POOLSIZE: int @@ -39,38 +63,75 @@ class BaseAdapter: def send( self, request: PreparedRequest, - stream: bool = ..., - timeout: None | float | tuple[float, float] | tuple[float, None] = ..., - verify: bool | str = ..., - cert: None | bytes | Text | Container[bytes | Text] = ..., - proxies: Mapping[str, str] | None = ..., + stream: bool = False, + timeout: float | tuple[float, float] | tuple[float, None] | None = None, + verify: bool | str = True, + cert: bytes | str | tuple[bytes | str, bytes | str] | None = None, + proxies: Mapping[str, str] | None = None, ) -> Response: ... def close(self) -> None: ... class HTTPAdapter(BaseAdapter): - __attrs__: Any + __attrs__: Incomplete max_retries: Retry - config: Any - proxy_manager: Any + config: Incomplete + proxy_manager: Incomplete def __init__( - self, pool_connections: int = ..., pool_maxsize: int = ..., max_retries: Retry | int | None = ..., pool_block: bool = ... + self, pool_connections: int = 10, pool_maxsize: int = 10, max_retries: Retry | int | None = 0, pool_block: bool = False + ) -> None: ... + poolmanager: Incomplete + def init_poolmanager( + self, + connections: int, + maxsize: int, + block: bool = False, + **pool_kwargs: Any, # Any: Arbitrary keyword arguments passed directly to urllib3's PoolManager constructor. + # Allowed types depend on urllib3 version, but typically include: + # ssl_version (int), cert_reqs (str), ca_certs (str), ca_cert_dir (str), + # ssl_context (ssl.SSLContext), socket_options (list), etc. + # We use Any because the exact set is dynamic and not fully specified in stubs. ) -> None: ... - poolmanager: Any - def init_poolmanager(self, connections, maxsize, block=..., **pool_kwargs): ... - def proxy_manager_for(self, proxy, **proxy_kwargs): ... + def proxy_manager_for( + self, + proxy: str, + **proxy_kwargs: Any, # Any: Same as pool_kwargs above, passed to ProxyManager or SOCKSProxyManager. + # May include: ssl_context, cert_reqs, ca_certs, ca_cert_dir, etc. + ) -> Any: # Any: Returns either urllib3.ProxyManager (for HTTP/HTTPS proxies) or SOCKSProxyManager (for SOCKS). + # The exact return type depends on the proxy scheme and is not needed by callers; using Any avoids + # circular imports or complex union types. In practice, the object adheres to a common interface. + ... + def cert_verify(self, conn, url, verify, cert): ... - def build_response(self, req, resp): ... - def get_connection(self, url, proxies=...): ... - def close(self): ... - def request_url(self, request, proxies): ... - def add_headers(self, request, **kwargs): ... - def proxy_headers(self, proxy): ... + def build_response(self, req: PreparedRequest, resp: urllib3.BaseHTTPResponse) -> Response: ... + def build_connection_pool_key_attributes( + self, request: PreparedRequest, verify: bool | str, cert: str | tuple[str, str] | None = None + ) -> tuple[_HostParams, _PoolKwargs]: ... + def get_connection_with_tls_context( + self, + request: PreparedRequest, + verify: bool | str | None, + proxies: Mapping[str, str] | None = None, + cert: tuple[str, str] | str | None = None, + ) -> ConnectionPool: ... + @deprecated("Use get_connection_with_tls_context() instead.") + def get_connection(self, url: _Uri, proxies: Mapping[str, str] | None = None) -> ConnectionPool: ... + def close(self) -> None: ... + def request_url(self, request: PreparedRequest, proxies: Mapping[str, str] | None) -> str: ... + def add_headers( + self, + request: PreparedRequest, + **kwargs: Any, # Any: Hook method for subclasses to add custom headers. + # The kwargs mirror the send() parameters: stream (bool), timeout (float|tuple), + # verify (bool|str), cert (str|tuple), proxies (dict). Base implementation ignores them. + # Using Any allows subclasses to access these arguments without repeating the full signature. + ) -> None: ... + def proxy_headers(self, proxy: str) -> dict[str, str]: ... def send( self, request: PreparedRequest, - stream: bool = ..., - timeout: None | float | tuple[float, float] | tuple[float, None] = ..., - verify: bool | str = ..., - cert: None | bytes | Text | Container[bytes | Text] = ..., - proxies: Mapping[str, str] | None = ..., + stream: bool = False, + timeout: float | tuple[float, float] | tuple[float, None] | None = None, + verify: bool | str = True, + cert: bytes | str | tuple[bytes | str, bytes | str] | None = None, + proxies: Mapping[str, str] | None = None, ) -> Response: ... diff --git a/stubs/requests/requests/api.pyi b/stubs/requests/requests/api.pyi index 1a241d308940..c29ff6472fc1 100644 --- a/stubs/requests/requests/api.pyi +++ b/stubs/requests/requests/api.pyi @@ -1,142 +1,154 @@ -from typing import Any, Text +from collections.abc import Mapping +from http.cookiejar import CookieJar +from typing import TypeAlias -from .models import Response -from .sessions import _Data, _Params +from .models import _JSON, Response +from .sessions import _Auth, _Cert, _Data, _Files, _HooksInput, _Params, _TextMapping, _Timeout, _Verify + +_HeadersMapping: TypeAlias = Mapping[str, str | bytes | None] def request( - method: Text | bytes, - url: Text | bytes, + method: str | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def get( - url: Text | bytes, - params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + url: str | bytes, + params: _Params | None = None, + *, + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def options( - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def head( - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def post( - url: Text | bytes, - data: _Data = ..., - json: Any | None = ..., + url: str | bytes, + data: _Data | None = None, + json: _JSON | None = None, + *, params: _Params | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., ) -> Response: ... def put( - url: Text | bytes, - data: _Data = ..., + url: str | bytes, + data: _Data | None = None, + *, params: _Params | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def patch( - url: Text | bytes, - data: _Data = ..., + url: str | bytes, + data: _Data | None = None, + *, params: _Params | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def delete( - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... diff --git a/stubs/requests/requests/auth.pyi b/stubs/requests/requests/auth.pyi index 97e81122237a..21ef4abf5faf 100644 --- a/stubs/requests/requests/auth.pyi +++ b/stubs/requests/requests/auth.pyi @@ -1,4 +1,4 @@ -from typing import Any, Text +from typing import Any from . import cookies, models, utils @@ -9,29 +9,29 @@ to_native_string = utils.to_native_string CONTENT_TYPE_FORM_URLENCODED: Any CONTENT_TYPE_MULTI_PART: Any -def _basic_auth_str(username: bytes | Text, password: bytes | Text) -> str: ... +def _basic_auth_str(username: bytes | str, password: bytes | str) -> str: ... class AuthBase: def __call__(self, r: models.PreparedRequest) -> models.PreparedRequest: ... class HTTPBasicAuth(AuthBase): - username: Any - password: Any - def __init__(self, username, password) -> None: ... + username: bytes | str + password: bytes | str + def __init__(self, username: bytes | str, password: bytes | str) -> None: ... def __call__(self, r): ... class HTTPProxyAuth(HTTPBasicAuth): def __call__(self, r): ... class HTTPDigestAuth(AuthBase): - username: Any - password: Any + username: bytes | str + password: bytes | str last_nonce: Any nonce_count: Any chal: Any pos: Any num_401_calls: Any - def __init__(self, username, password) -> None: ... + def __init__(self, username: bytes | str, password: bytes | str) -> None: ... def build_digest_header(self, method, url): ... def handle_redirect(self, r, **kwargs): ... def handle_401(self, r, **kwargs): ... diff --git a/stubs/requests/requests/certs.pyi b/stubs/requests/requests/certs.pyi new file mode 100644 index 000000000000..7c5857d69ad3 --- /dev/null +++ b/stubs/requests/requests/certs.pyi @@ -0,0 +1 @@ +# no public data diff --git a/stubs/requests/requests/compat.pyi b/stubs/requests/requests/compat.pyi index 3e798351874a..88b4736313fc 100644 --- a/stubs/requests/requests/compat.pyi +++ b/stubs/requests/requests/compat.pyi @@ -1,3 +1,29 @@ -import collections +from builtins import bytes as bytes, str as str +from collections import OrderedDict as OrderedDict -OrderedDict = collections.OrderedDict +# If simplejson is installed, JSONDecodeError is actually imported from there. +from json import JSONDecodeError as JSONDecodeError +from typing import Literal, TypeAlias +from urllib.parse import ( + quote as quote, + quote_plus as quote_plus, + unquote as unquote, + unquote_plus as unquote_plus, + urldefrag as urldefrag, + urlencode as urlencode, + urljoin as urljoin, + urlparse as urlparse, + urlsplit as urlsplit, + urlunparse as urlunparse, +) +from urllib.request import getproxies as getproxies, parse_http_list as parse_http_list, proxy_bypass as proxy_bypass + +is_urllib3_1: bool +is_py2: Literal[False] +is_py3: Literal[True] +has_simplejson: bool + +builtin_str: TypeAlias = str # noqa: Y042 +basestring: tuple[type, ...] +numeric_types: tuple[type, ...] +integer_types: tuple[type, ...] diff --git a/stubs/requests/requests/cookies.pyi b/stubs/requests/requests/cookies.pyi index 673852193703..dc0138d896fc 100644 --- a/stubs/requests/requests/cookies.pyi +++ b/stubs/requests/requests/cookies.pyi @@ -1,10 +1,8 @@ -import sys -from typing import Any, MutableMapping - -if sys.version_info >= (3, 0): - from http.cookiejar import CookieJar -else: - from cookielib import CookieJar +from _typeshed import SupportsKeysAndGetItem +from collections.abc import Iterator, MutableMapping +from http.cookiejar import Cookie, CookieJar, CookiePolicy +from http.cookies import Morsel +from typing import Any class MockRequest: type: Any @@ -15,7 +13,7 @@ class MockRequest: def get_full_url(self): ... def is_unverifiable(self): ... def has_header(self, name): ... - def get_header(self, name, default=...): ... + def get_header(self, name, default=None): ... def add_header(self, key, val): ... def add_unredirected_header(self, name, value): ... def get_new_headers(self): ... @@ -33,32 +31,32 @@ class MockResponse: def extract_cookies_to_jar(jar, request, response): ... def get_cookie_header(jar, request): ... -def remove_cookie_by_name(cookiejar, name, domain=..., path=...): ... +def remove_cookie_by_name(cookiejar, name, domain=None, path=None): ... class CookieConflictError(RuntimeError): ... -class RequestsCookieJar(CookieJar, MutableMapping[Any, Any]): - def get(self, name, default=..., domain=..., path=...): ... - def set(self, name, value, **kwargs): ... - def iterkeys(self): ... - def keys(self): ... - def itervalues(self): ... - def values(self): ... - def iteritems(self): ... - def items(self): ... - def list_domains(self): ... - def list_paths(self): ... - def multiple_domains(self): ... - def get_dict(self, domain=..., path=...): ... - def __getitem__(self, name): ... - def __setitem__(self, name, value): ... - def __delitem__(self, name): ... - def set_cookie(self, cookie, *args, **kwargs): ... - def update(self, other): ... - def copy(self): ... - def get_policy(self): ... +class RequestsCookieJar(CookieJar, MutableMapping[str, str]): # type: ignore[misc] # conflicting __iter__ in the base classes + def get(self, name: str, default: str | None = None, domain: str | None = None, path: str | None = None) -> str | None: ... # type: ignore[override] + def set(self, name: str, value: str | Morsel[dict[str, str]], **kwargs) -> Cookie | None: ... + def iterkeys(self) -> Iterator[str]: ... + def keys(self) -> list[str]: ... # type: ignore[override] + def itervalues(self) -> Iterator[str]: ... + def values(self) -> list[str]: ... # type: ignore[override] + def iteritems(self) -> Iterator[tuple[str, str]]: ... + def items(self) -> list[tuple[str, str]]: ... # type: ignore[override] + def list_domains(self) -> list[str]: ... + def list_paths(self) -> list[str]: ... + def multiple_domains(self) -> bool: ... + def get_dict(self, domain: str | None = None, path: str | None = None) -> dict[str, str]: ... + def __getitem__(self, name: str) -> str: ... + def __setitem__(self, name: str, value: str | Morsel[dict[str, str]]) -> None: ... + def __delitem__(self, name: str) -> None: ... + def set_cookie(self, cookie: Cookie, *args, **kwargs): ... + def update(self, other: CookieJar | SupportsKeysAndGetItem[str, str]): ... # type: ignore[override] + def copy(self) -> RequestsCookieJar: ... + def get_policy(self) -> CookiePolicy: ... def create_cookie(name, value, **kwargs): ... def morsel_to_cookie(morsel): ... -def cookiejar_from_dict(cookie_dict, cookiejar=..., overwrite=...): ... +def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): ... def merge_cookies(cookiejar, cookies): ... diff --git a/stubs/requests/requests/exceptions.pyi b/stubs/requests/requests/exceptions.pyi index 6ad059a3c01c..c76e78d4f52c 100644 --- a/stubs/requests/requests/exceptions.pyi +++ b/stubs/requests/requests/exceptions.pyi @@ -1,13 +1,25 @@ from typing import Any -from .packages.urllib3.exceptions import HTTPError as BaseHTTPError +from urllib3.exceptions import HTTPError as BaseHTTPError -class RequestException(IOError): - response: Any - request: Any - def __init__(self, *args, **kwargs) -> None: ... +from .compat import JSONDecodeError as CompatJSONDecodeError +from .models import Request, Response +from .sessions import PreparedRequest + +class RequestException(OSError): + response: Response | None + request: Request | PreparedRequest | None + def __init__( + self, *args: object, request: Request | PreparedRequest | None = ..., response: Response | None = ... + ) -> None: ... + +class InvalidJSONError(RequestException): ... +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): ... + +class HTTPError(RequestException): + request: Request | PreparedRequest | Any + response: Response | Any -class HTTPError(RequestException): ... class ConnectionError(RequestException): ... class ProxyError(ConnectionError): ... class SSLError(ConnectionError): ... diff --git a/stubs/requests/requests/help.pyi b/stubs/requests/requests/help.pyi new file mode 100644 index 000000000000..697afb1be11f --- /dev/null +++ b/stubs/requests/requests/help.pyi @@ -0,0 +1,40 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _VersionDict(TypedDict): + version: str + +@type_check_only +class _OptionalVersionDict(TypedDict): + version: str | None + +@type_check_only +class _PlatformDict(TypedDict): + system: str + release: str + +@type_check_only +class _ImplementationDict(_VersionDict): + name: str + +@type_check_only +class _PyOpenSSLDict(_OptionalVersionDict): + openssl_version: str + +@type_check_only +class _InfoDict(TypedDict): + platform: _PlatformDict + implementation: _ImplementationDict + system_ssl: _VersionDict + using_pyopenssl: bool + using_charset_normalizer: bool + pyOpenSSL: _PyOpenSSLDict + urllib3: _VersionDict + chardet: _OptionalVersionDict + charset_normalizer: _OptionalVersionDict + cryptography: _VersionDict + idna: _VersionDict + requests: _VersionDict + +def info() -> _InfoDict: ... +def main() -> None: ... diff --git a/stubs/requests/requests/hooks.pyi b/stubs/requests/requests/hooks.pyi index f706016ca386..73bef16cda1c 100644 --- a/stubs/requests/requests/hooks.pyi +++ b/stubs/requests/requests/hooks.pyi @@ -1,6 +1,6 @@ from typing import Any -HOOKS: Any +HOOKS: list[str] -def default_hooks(): ... +def default_hooks() -> dict[str, list[Any]]: ... def dispatch_hook(key, hooks, hook_data, **kwargs): ... diff --git a/stubs/requests/requests/models.pyi b/stubs/requests/requests/models.pyi index 957a0e074f78..0a598e596df7 100644 --- a/stubs/requests/requests/models.pyi +++ b/stubs/requests/requests/models.pyi @@ -1,13 +1,21 @@ import datetime +from _typeshed import Incomplete, MaybeNone, Unused +from collections.abc import Callable, Iterator from json import JSONDecoder -from typing import Any, Callable, Iterator, Text, Type +from typing import Any, TypeAlias +from typing_extensions import Self -from . import auth, cookies, exceptions, hooks, status_codes, structures, utils +from urllib3 import exceptions as urllib3_exceptions, fields, filepost, util +from urllib3.response import HTTPResponse + +from . import auth, cookies, exceptions, hooks, status_codes, utils +from .adapters import HTTPAdapter from .cookies import RequestsCookieJar -from .packages.urllib3 import exceptions as urllib3_exceptions, fields, filepost, util +from .structures import CaseInsensitiveDict as CaseInsensitiveDict + +_JSON: TypeAlias = Any # any object that can be serialized to JSON default_hooks = hooks.default_hooks -CaseInsensitiveDict = structures.CaseInsensitiveDict HTTPBasicAuth = auth.HTTPBasicAuth cookiejar_from_dict = cookies.cookiejar_from_dict get_cookie_header = cookies.get_cookie_header @@ -37,61 +45,81 @@ super_len = utils.super_len to_native_string = utils.to_native_string codes = status_codes.codes -REDIRECT_STATI: Any -DEFAULT_REDIRECT_LIMIT: Any -CONTENT_CHUNK_SIZE: Any -ITER_CHUNK_SIZE: Any +REDIRECT_STATI: tuple[int, ...] +DEFAULT_REDIRECT_LIMIT: int +CONTENT_CHUNK_SIZE: int +ITER_CHUNK_SIZE: int class RequestEncodingMixin: @property - def path_url(self): ... + def path_url(self) -> str: ... class RequestHooksMixin: def register_hook(self, event, hook): ... def deregister_hook(self, event, hook): ... class Request(RequestHooksMixin): - hooks: Any - method: Any - url: Any - headers: Any - files: Any - data: Any - json: Any - params: Any - auth: Any - cookies: Any + hooks: Incomplete + method: Incomplete + url: Incomplete + headers: Incomplete + files: Incomplete + data: Incomplete + json: _JSON | None + params: Incomplete + auth: Incomplete + cookies: Incomplete def __init__( - self, method=..., url=..., headers=..., files=..., data=..., params=..., auth=..., cookies=..., hooks=..., json=... + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json: _JSON | None = None, ) -> None: ... def prepare(self) -> PreparedRequest: ... class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): - method: str | Text | None - url: str | Text | None + method: str | None + url: str | None headers: CaseInsensitiveDict[str] - body: bytes | Text | None - hooks: Any + body: bytes | str | None + hooks: Incomplete def __init__(self) -> None: ... def prepare( - self, method=..., url=..., headers=..., files=..., data=..., params=..., auth=..., cookies=..., hooks=..., json=... + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, ) -> None: ... def copy(self) -> PreparedRequest: ... def prepare_method(self, method) -> None: ... def prepare_url(self, url, params) -> None: ... def prepare_headers(self, headers) -> None: ... - def prepare_body(self, data, files, json=...) -> None: ... - def prepare_content_length(self, body) -> None: ... - def prepare_auth(self, auth, url=...) -> None: ... + def prepare_body(self, data, files, json=None) -> None: ... + def prepare_content_length(self, body: bytes | str | None) -> None: ... + def prepare_auth(self, auth, url="") -> None: ... def prepare_cookies(self, cookies) -> None: ... def prepare_hooks(self, hooks) -> None: ... class Response: - __attrs__: Any + __attrs__: Incomplete _content: bytes | None # undocumented status_code: int headers: CaseInsensitiveDict[str] - raw: Any + raw: HTTPResponse | MaybeNone url: str encoding: str | None history: list[Response] @@ -99,12 +127,13 @@ class Response: cookies: RequestsCookieJar elapsed: datetime.timedelta request: PreparedRequest + connection: HTTPAdapter def __init__(self) -> None: ... def __bool__(self) -> bool: ... def __nonzero__(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... - def __enter__(self) -> Response: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... @property def next(self) -> PreparedRequest | None: ... @property @@ -115,18 +144,18 @@ class Response: def is_permanent_redirect(self) -> bool: ... @property def apparent_encoding(self) -> str: ... - def iter_content(self, chunk_size: int | None = ..., decode_unicode: bool = ...) -> Iterator[Any]: ... + def iter_content(self, chunk_size: int | None = 1, decode_unicode: bool = False) -> Iterator[Incomplete]: ... def iter_lines( - self, chunk_size: int | None = ..., decode_unicode: bool = ..., delimiter: Text | bytes | None = ... - ) -> Iterator[Any]: ... + self, chunk_size: int | None = 512, decode_unicode: bool = False, delimiter: str | bytes | None = None + ) -> Iterator[Incomplete]: ... @property - def content(self) -> bytes: ... + def content(self) -> bytes | MaybeNone: ... @property def text(self) -> str: ... def json( self, *, - cls: Type[JSONDecoder] | None = ..., + cls: type[JSONDecoder] | None = ..., object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., @@ -135,6 +164,6 @@ class Response: **kwds: Any, ) -> Any: ... @property - def links(self) -> dict[Any, Any]: ... + def links(self) -> dict[str, dict[str, str]]: ... def raise_for_status(self) -> None: ... def close(self) -> None: ... diff --git a/stubs/requests/requests/packages.pyi b/stubs/requests/requests/packages.pyi new file mode 100644 index 000000000000..22281ce4c6e3 --- /dev/null +++ b/stubs/requests/requests/packages.pyi @@ -0,0 +1,3 @@ +# requests also imports urllib3, idna, and chardet below +# requests.packages. The stubs don't reflect that and it's recommended to +# import these packages directly if needed. diff --git a/stubs/requests/requests/packages/__init__.pyi b/stubs/requests/requests/packages/__init__.pyi deleted file mode 100644 index b50dba35e4ae..000000000000 --- a/stubs/requests/requests/packages/__init__.pyi +++ /dev/null @@ -1,4 +0,0 @@ -class VendorAlias: - def __init__(self, package_names) -> None: ... - def find_module(self, fullname, path=...): ... - def load_module(self, name): ... diff --git a/stubs/requests/requests/packages/urllib3/__init__.pyi b/stubs/requests/requests/packages/urllib3/__init__.pyi deleted file mode 100644 index f63b8fa12da6..000000000000 --- a/stubs/requests/requests/packages/urllib3/__init__.pyi +++ /dev/null @@ -1,26 +0,0 @@ -import logging -from typing import Any - -from . import connectionpool, filepost, poolmanager, response -from .util import request as _request, retry, timeout, url - -__license__: Any - -HTTPConnectionPool = connectionpool.HTTPConnectionPool -HTTPSConnectionPool = connectionpool.HTTPSConnectionPool -connection_from_url = connectionpool.connection_from_url -encode_multipart_formdata = filepost.encode_multipart_formdata -PoolManager = poolmanager.PoolManager -ProxyManager = poolmanager.ProxyManager -proxy_from_url = poolmanager.proxy_from_url -HTTPResponse = response.HTTPResponse -make_headers = _request.make_headers -get_host = url.get_host -Timeout = timeout.Timeout -Retry = retry.Retry - -class NullHandler(logging.Handler): - def emit(self, record): ... - -def add_stderr_logger(level=...): ... -def disable_warnings(category=...): ... diff --git a/stubs/requests/requests/packages/urllib3/_collections.pyi b/stubs/requests/requests/packages/urllib3/_collections.pyi deleted file mode 100644 index 15aca7bd6209..000000000000 --- a/stubs/requests/requests/packages/urllib3/_collections.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any, MutableMapping, NoReturn, TypeVar - -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - -class RLock: - def __enter__(self): ... - def __exit__(self, exc_type, exc_value, traceback): ... - -class RecentlyUsedContainer(MutableMapping[_KT, _VT]): - ContainerCls: Any - dispose_func: Any - lock: Any - def __init__(self, maxsize=..., dispose_func=...) -> None: ... - def __getitem__(self, key): ... - def __setitem__(self, key, value): ... - def __delitem__(self, key): ... - def __len__(self): ... - def __iter__(self): ... - def clear(self): ... - def keys(self): ... - -class HTTPHeaderDict(MutableMapping[str, str]): - def __init__(self, headers=..., **kwargs) -> None: ... - def __setitem__(self, key, val): ... - def __getitem__(self, key): ... - def __delitem__(self, key): ... - def __contains__(self, key): ... - def __eq__(self, other): ... - def __iter__(self) -> NoReturn: ... - def __len__(self) -> int: ... - def __ne__(self, other): ... - values: Any - get: Any - update: Any - iterkeys: Any - itervalues: Any - def pop(self, key, default=...): ... - def discard(self, key): ... - def add(self, key, val): ... - def extend(self, *args, **kwargs): ... - def getlist(self, key): ... - getheaders: Any - getallmatchingheaders: Any - iget: Any - def copy(self): ... - def iteritems(self): ... - def itermerged(self): ... - def items(self): ... - @classmethod - def from_httplib(cls, message, duplicates=...): ... diff --git a/stubs/requests/requests/packages/urllib3/connection.pyi b/stubs/requests/requests/packages/urllib3/connection.pyi deleted file mode 100644 index 39d0f6abbc93..000000000000 --- a/stubs/requests/requests/packages/urllib3/connection.pyi +++ /dev/null @@ -1,64 +0,0 @@ -import ssl -import sys -from typing import Any - -from . import exceptions, util -from .packages import ssl_match_hostname -from .util import ssl_ - -if sys.version_info >= (3, 0): - from builtins import ConnectionError as ConnectionError - from http.client import HTTPConnection as _HTTPConnection, HTTPException as HTTPException -else: - from httplib import HTTPConnection as _HTTPConnection, HTTPException as HTTPException - class ConnectionError(Exception): ... - -class DummyConnection: ... - -BaseSSLError = ssl.SSLError - -ConnectTimeoutError = exceptions.ConnectTimeoutError -SystemTimeWarning = exceptions.SystemTimeWarning -SecurityWarning = exceptions.SecurityWarning -match_hostname = ssl_match_hostname.match_hostname -resolve_cert_reqs = ssl_.resolve_cert_reqs -resolve_ssl_version = ssl_.resolve_ssl_version -ssl_wrap_socket = ssl_.ssl_wrap_socket -assert_fingerprint = ssl_.assert_fingerprint -connection = util.connection - -port_by_scheme: Any -RECENT_DATE: Any - -class HTTPConnection(_HTTPConnection): - default_port: Any - default_socket_options: Any - is_verified: Any - source_address: Any - socket_options: Any - def __init__(self, *args, **kw) -> None: ... - def connect(self): ... - -class HTTPSConnection(HTTPConnection): - default_port: Any - key_file: Any - cert_file: Any - def __init__(self, host, port=..., key_file=..., cert_file=..., strict=..., timeout=..., **kw) -> None: ... - sock: Any - def connect(self): ... - -class VerifiedHTTPSConnection(HTTPSConnection): - cert_reqs: Any - ca_certs: Any - ssl_version: Any - assert_fingerprint: Any - key_file: Any - cert_file: Any - assert_hostname: Any - def set_cert(self, key_file=..., cert_file=..., cert_reqs=..., ca_certs=..., assert_hostname=..., assert_fingerprint=...): ... - sock: Any - auto_open: Any - is_verified: Any - def connect(self): ... - -UnverifiedHTTPSConnection = HTTPSConnection diff --git a/stubs/requests/requests/packages/urllib3/connectionpool.pyi b/stubs/requests/requests/packages/urllib3/connectionpool.pyi deleted file mode 100644 index 90832482d6d7..000000000000 --- a/stubs/requests/requests/packages/urllib3/connectionpool.pyi +++ /dev/null @@ -1,121 +0,0 @@ -from typing import Any - -from . import connection, exceptions, request, response -from .connection import BaseSSLError as BaseSSLError, ConnectionError as ConnectionError, HTTPException as HTTPException -from .packages import ssl_match_hostname -from .util import connection as _connection, retry, timeout, url - -ClosedPoolError = exceptions.ClosedPoolError -ProtocolError = exceptions.ProtocolError -EmptyPoolError = exceptions.EmptyPoolError -HostChangedError = exceptions.HostChangedError -LocationValueError = exceptions.LocationValueError -MaxRetryError = exceptions.MaxRetryError -ProxyError = exceptions.ProxyError -ReadTimeoutError = exceptions.ReadTimeoutError -SSLError = exceptions.SSLError -TimeoutError = exceptions.TimeoutError -InsecureRequestWarning = exceptions.InsecureRequestWarning -CertificateError = ssl_match_hostname.CertificateError -port_by_scheme = connection.port_by_scheme -DummyConnection = connection.DummyConnection -HTTPConnection = connection.HTTPConnection -HTTPSConnection = connection.HTTPSConnection -VerifiedHTTPSConnection = connection.VerifiedHTTPSConnection -RequestMethods = request.RequestMethods -HTTPResponse = response.HTTPResponse -is_connection_dropped = _connection.is_connection_dropped -Retry = retry.Retry -Timeout = timeout.Timeout -get_host = url.get_host - -xrange: Any -log: Any - -class ConnectionPool: - scheme: Any - QueueCls: Any - host: Any - port: Any - def __init__(self, host, port=...) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type, exc_val, exc_tb): ... - def close(self): ... - -class HTTPConnectionPool(ConnectionPool, RequestMethods): - scheme: Any - ConnectionCls: Any - strict: Any - timeout: Any - retries: Any - pool: Any - block: Any - proxy: Any - proxy_headers: Any - num_connections: Any - num_requests: Any - conn_kw: Any - def __init__( - self, - host, - port=..., - strict=..., - timeout=..., - maxsize=..., - block=..., - headers=..., - retries=..., - _proxy=..., - _proxy_headers=..., - **conn_kw, - ) -> None: ... - def close(self): ... - def is_same_host(self, url): ... - def urlopen( - self, - method, - url, - body=..., - headers=..., - retries=..., - redirect=..., - assert_same_host=..., - timeout=..., - pool_timeout=..., - release_conn=..., - **response_kw, - ): ... - -class HTTPSConnectionPool(HTTPConnectionPool): - scheme: Any - ConnectionCls: Any - key_file: Any - cert_file: Any - cert_reqs: Any - ca_certs: Any - ssl_version: Any - assert_hostname: Any - assert_fingerprint: Any - def __init__( - self, - host, - port=..., - strict=..., - timeout=..., - maxsize=..., - block=..., - headers=..., - retries=..., - _proxy=..., - _proxy_headers=..., - key_file=..., - cert_file=..., - cert_reqs=..., - ca_certs=..., - ssl_version=..., - assert_hostname=..., - assert_fingerprint=..., - **conn_kw, - ) -> None: ... - -def connection_from_url(url, **kw): ... diff --git a/stubs/requests/requests/packages/urllib3/exceptions.pyi b/stubs/requests/requests/packages/urllib3/exceptions.pyi deleted file mode 100644 index ddb4e83ba77e..000000000000 --- a/stubs/requests/requests/packages/urllib3/exceptions.pyi +++ /dev/null @@ -1,50 +0,0 @@ -from typing import Any - -class HTTPError(Exception): ... -class HTTPWarning(Warning): ... - -class PoolError(HTTPError): - pool: Any - def __init__(self, pool, message) -> None: ... - def __reduce__(self): ... - -class RequestError(PoolError): - url: Any - def __init__(self, pool, url, message) -> None: ... - def __reduce__(self): ... - -class SSLError(HTTPError): ... -class ProxyError(HTTPError): ... -class DecodeError(HTTPError): ... -class ProtocolError(HTTPError): ... - -ConnectionError: Any - -class MaxRetryError(RequestError): - reason: Any - def __init__(self, pool, url, reason=...) -> None: ... - -class HostChangedError(RequestError): - retries: Any - def __init__(self, pool, url, retries=...) -> None: ... - -class TimeoutStateError(HTTPError): ... -class TimeoutError(HTTPError): ... -class ReadTimeoutError(TimeoutError, RequestError): ... -class ConnectTimeoutError(TimeoutError): ... -class EmptyPoolError(PoolError): ... -class ClosedPoolError(PoolError): ... -class LocationValueError(ValueError, HTTPError): ... - -class LocationParseError(LocationValueError): - location: Any - def __init__(self, location) -> None: ... - -class ResponseError(HTTPError): - GENERIC_ERROR: Any - SPECIFIC_ERROR: Any - -class SecurityWarning(HTTPWarning): ... -class InsecureRequestWarning(SecurityWarning): ... -class SystemTimeWarning(SecurityWarning): ... -class InsecurePlatformWarning(SecurityWarning): ... diff --git a/stubs/requests/requests/packages/urllib3/fields.pyi b/stubs/requests/requests/packages/urllib3/fields.pyi deleted file mode 100644 index df18769b7263..000000000000 --- a/stubs/requests/requests/packages/urllib3/fields.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -def guess_content_type(filename, default=...): ... -def format_header_param(name, value): ... - -class RequestField: - data: Any - headers: Any - def __init__(self, name, data, filename=..., headers=...) -> None: ... - @classmethod - def from_tuples(cls, fieldname, value): ... - def render_headers(self): ... - def make_multipart(self, content_disposition=..., content_type=..., content_location=...): ... diff --git a/stubs/requests/requests/packages/urllib3/filepost.pyi b/stubs/requests/requests/packages/urllib3/filepost.pyi deleted file mode 100644 index 49bd7e046ab0..000000000000 --- a/stubs/requests/requests/packages/urllib3/filepost.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from . import fields - -RequestField = fields.RequestField - -writer: Any - -def choose_boundary(): ... -def iter_field_objects(fields): ... -def iter_fields(fields): ... -def encode_multipart_formdata(fields, boundary=...): ... diff --git a/stubs/requests/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi b/stubs/requests/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi deleted file mode 100644 index 1915c0e5d00c..000000000000 --- a/stubs/requests/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi +++ /dev/null @@ -1,4 +0,0 @@ -import ssl - -CertificateError = ssl.CertificateError -match_hostname = ssl.match_hostname diff --git a/stubs/requests/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi b/stubs/requests/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi deleted file mode 100644 index c21998013cf2..000000000000 --- a/stubs/requests/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi +++ /dev/null @@ -1,3 +0,0 @@ -class CertificateError(ValueError): ... - -def match_hostname(cert, hostname): ... diff --git a/stubs/requests/requests/packages/urllib3/poolmanager.pyi b/stubs/requests/requests/packages/urllib3/poolmanager.pyi deleted file mode 100644 index 68ad69622b66..000000000000 --- a/stubs/requests/requests/packages/urllib3/poolmanager.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any - -from .request import RequestMethods - -class PoolManager(RequestMethods): - proxy: Any - connection_pool_kw: Any - pools: Any - def __init__(self, num_pools=..., headers=..., **connection_pool_kw) -> None: ... - def __enter__(self): ... - def __exit__(self, exc_type, exc_val, exc_tb): ... - def clear(self): ... - def connection_from_host(self, host, port=..., scheme=...): ... - def connection_from_url(self, url): ... - # TODO: This was the original signature -- copied another one from base class to fix complaint. - # def urlopen(self, method, url, redirect=True, **kw): ... - def urlopen(self, method, url, body=..., headers=..., encode_multipart=..., multipart_boundary=..., **kw): ... - -class ProxyManager(PoolManager): - proxy: Any - proxy_headers: Any - def __init__(self, proxy_url, num_pools=..., headers=..., proxy_headers=..., **connection_pool_kw) -> None: ... - def connection_from_host(self, host, port=..., scheme=...): ... - # TODO: This was the original signature -- copied another one from base class to fix complaint. - # def urlopen(self, method, url, redirect=True, **kw): ... - def urlopen(self, method, url, body=..., headers=..., encode_multipart=..., multipart_boundary=..., **kw): ... - -def proxy_from_url(url, **kw): ... diff --git a/stubs/requests/requests/packages/urllib3/request.pyi b/stubs/requests/requests/packages/urllib3/request.pyi deleted file mode 100644 index b95ab295ba84..000000000000 --- a/stubs/requests/requests/packages/urllib3/request.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class RequestMethods: - headers: Any - def __init__(self, headers=...) -> None: ... - def urlopen(self, method, url, body=..., headers=..., encode_multipart=..., multipart_boundary=..., **kw): ... - def request(self, method, url, fields=..., headers=..., **urlopen_kw): ... - def request_encode_url(self, method, url, fields=..., **urlopen_kw): ... - def request_encode_body( - self, method, url, fields=..., headers=..., encode_multipart=..., multipart_boundary=..., **urlopen_kw - ): ... diff --git a/stubs/requests/requests/packages/urllib3/response.pyi b/stubs/requests/requests/packages/urllib3/response.pyi deleted file mode 100644 index 1c78b48a2572..000000000000 --- a/stubs/requests/requests/packages/urllib3/response.pyi +++ /dev/null @@ -1,66 +0,0 @@ -import io -from typing import Any - -from . import _collections, exceptions -from .connection import BaseSSLError as BaseSSLError, HTTPException as HTTPException -from .util import response - -HTTPHeaderDict = _collections.HTTPHeaderDict -ProtocolError = exceptions.ProtocolError -DecodeError = exceptions.DecodeError -ReadTimeoutError = exceptions.ReadTimeoutError -binary_type = bytes # six.binary_type -PY3 = True # six.PY3 -is_fp_closed = response.is_fp_closed - -class DeflateDecoder: - def __init__(self) -> None: ... - def __getattr__(self, name): ... - def decompress(self, data): ... - -class GzipDecoder: - def __init__(self) -> None: ... - def __getattr__(self, name): ... - def decompress(self, data): ... - -class HTTPResponse(io.IOBase): - CONTENT_DECODERS: Any - REDIRECT_STATUSES: Any - headers: Any - status: Any - version: Any - reason: Any - strict: Any - decode_content: Any - def __init__( - self, - body=..., - headers=..., - status=..., - version=..., - reason=..., - strict=..., - preload_content=..., - decode_content=..., - original_response=..., - pool=..., - connection=..., - ) -> None: ... - def get_redirect_location(self): ... - def release_conn(self): ... - @property - def data(self): ... - def tell(self): ... - def read(self, amt=..., decode_content=..., cache_content=...): ... - def stream(self, amt=..., decode_content=...): ... - @classmethod - def from_httplib(cls, r, **response_kw): ... - def getheaders(self): ... - def getheader(self, name, default=...): ... - def close(self): ... - @property - def closed(self): ... - def fileno(self): ... - def flush(self): ... - def readable(self): ... - def readinto(self, b): ... diff --git a/stubs/requests/requests/packages/urllib3/util/__init__.pyi b/stubs/requests/requests/packages/urllib3/util/__init__.pyi deleted file mode 100644 index 2d0d66dcb603..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/__init__.pyi +++ /dev/null @@ -1,20 +0,0 @@ -import ssl - -from . import connection, request, response, retry, ssl_, timeout, url - -is_connection_dropped = connection.is_connection_dropped -make_headers = request.make_headers -is_fp_closed = response.is_fp_closed -SSLContext = ssl.SSLContext -HAS_SNI = ssl_.HAS_SNI -assert_fingerprint = ssl_.assert_fingerprint -resolve_cert_reqs = ssl_.resolve_cert_reqs -resolve_ssl_version = ssl_.resolve_ssl_version -ssl_wrap_socket = ssl_.ssl_wrap_socket -current_time = timeout.current_time -Timeout = timeout.Timeout -Retry = retry.Retry -get_host = url.get_host -parse_url = url.parse_url -split_first = url.split_first -Url = url.Url diff --git a/stubs/requests/requests/packages/urllib3/util/connection.pyi b/stubs/requests/requests/packages/urllib3/util/connection.pyi deleted file mode 100644 index db77bd0095dd..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/connection.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any - -poll: Any -select: Any -HAS_IPV6: bool - -def is_connection_dropped(conn): ... -def create_connection(address, timeout=..., source_address=..., socket_options=...): ... diff --git a/stubs/requests/requests/packages/urllib3/util/request.pyi b/stubs/requests/requests/packages/urllib3/util/request.pyi deleted file mode 100644 index f770cd9faa73..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/request.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -# from ..packages import six - -# b = six.b - -ACCEPT_ENCODING: Any - -def make_headers( - keep_alive=..., accept_encoding=..., user_agent=..., basic_auth=..., proxy_basic_auth=..., disable_cache=... -): ... diff --git a/stubs/requests/requests/packages/urllib3/util/response.pyi b/stubs/requests/requests/packages/urllib3/util/response.pyi deleted file mode 100644 index 30463da4e4de..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/response.pyi +++ /dev/null @@ -1 +0,0 @@ -def is_fp_closed(obj): ... diff --git a/stubs/requests/requests/packages/urllib3/util/retry.pyi b/stubs/requests/requests/packages/urllib3/util/retry.pyi deleted file mode 100644 index c4aedaa6cc62..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/retry.pyi +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Any - -from .. import exceptions - -ConnectTimeoutError = exceptions.ConnectTimeoutError -MaxRetryError = exceptions.MaxRetryError -ProtocolError = exceptions.ProtocolError -ReadTimeoutError = exceptions.ReadTimeoutError -ResponseError = exceptions.ResponseError - -log: Any - -class Retry: - DEFAULT_METHOD_WHITELIST: Any - BACKOFF_MAX: Any - total: Any - connect: Any - read: Any - redirect: Any - status_forcelist: Any - method_whitelist: Any - backoff_factor: Any - raise_on_redirect: Any - def __init__( - self, - total=..., - connect=..., - read=..., - redirect=..., - status=..., - other=..., - allowed_methods=..., - status_forcelist=..., - backoff_factor=..., - raise_on_redirect=..., - raise_on_status=..., - history=..., - respect_retry_after_header=..., - remove_headers_on_redirect=..., - method_whitelist=..., - ) -> None: ... - def new(self, **kw): ... - @classmethod - def from_int(cls, retries, redirect=..., default=...): ... - def get_backoff_time(self): ... - def sleep(self): ... - def is_forced_retry(self, method, status_code): ... - def is_exhausted(self): ... - def increment(self, method=..., url=..., response=..., error=..., _pool=..., _stacktrace=...): ... diff --git a/stubs/requests/requests/packages/urllib3/util/ssl_.pyi b/stubs/requests/requests/packages/urllib3/util/ssl_.pyi deleted file mode 100644 index 1542e91da79a..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/ssl_.pyi +++ /dev/null @@ -1,30 +0,0 @@ -import ssl -from typing import Any - -from .. import exceptions - -SSLError = exceptions.SSLError -InsecurePlatformWarning = exceptions.InsecurePlatformWarning -SSLContext = ssl.SSLContext - -HAS_SNI: Any -create_default_context: Any -OP_NO_SSLv2: Any -OP_NO_SSLv3: Any -OP_NO_COMPRESSION: Any - -def assert_fingerprint(cert, fingerprint): ... -def resolve_cert_reqs(candidate): ... -def resolve_ssl_version(candidate): ... -def create_urllib3_context(ssl_version=..., cert_reqs=..., options=..., ciphers=...): ... -def ssl_wrap_socket( - sock, - keyfile=..., - certfile=..., - cert_reqs=..., - ca_certs=..., - server_hostname=..., - ssl_version=..., - ciphers=..., - ssl_context=..., -): ... diff --git a/stubs/requests/requests/packages/urllib3/util/timeout.pyi b/stubs/requests/requests/packages/urllib3/util/timeout.pyi deleted file mode 100644 index 25879d685ea9..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/timeout.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from .. import exceptions - -TimeoutStateError = exceptions.TimeoutStateError - -def current_time(): ... - -class Timeout: - DEFAULT_TIMEOUT: Any - total: Any - def __init__(self, total=..., connect=..., read=...) -> None: ... - @classmethod - def from_float(cls, timeout): ... - def clone(self): ... - def start_connect(self): ... - def get_connect_duration(self): ... - @property - def connect_timeout(self): ... - @property - def read_timeout(self): ... diff --git a/stubs/requests/requests/packages/urllib3/util/url.pyi b/stubs/requests/requests/packages/urllib3/util/url.pyi deleted file mode 100644 index 2d43e2d2626d..000000000000 --- a/stubs/requests/requests/packages/urllib3/util/url.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Any - -from .. import exceptions - -LocationParseError = exceptions.LocationParseError - -url_attrs: Any - -class Url: - slots: Any - def __new__(cls, scheme=..., auth=..., host=..., port=..., path=..., query=..., fragment=...): ... - @property - def hostname(self): ... - @property - def request_uri(self): ... - @property - def netloc(self): ... - @property - def url(self): ... - -def split_first(s, delims): ... -def parse_url(url): ... -def get_host(url): ... diff --git a/stubs/requests/requests/sessions.pyi b/stubs/requests/requests/sessions.pyi index 89ba100c02af..ee89384d9522 100644 --- a/stubs/requests/requests/sessions.pyi +++ b/stubs/requests/requests/sessions.pyi @@ -1,11 +1,13 @@ -from _typeshed import SupportsItems -from typing import IO, Any, Callable, Iterable, List, Mapping, MutableMapping, Optional, Text, Tuple, TypeVar, Union +from _typeshed import SupportsItems, SupportsRead, Unused +from collections.abc import Callable, Iterable, Mapping, MutableMapping +from typing import Any, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self -from . import adapters, auth as _auth, compat, cookies, exceptions, hooks, models, status_codes, structures, utils -from .models import Response -from .packages.urllib3 import _collections +from . import adapters, auth as _auth, compat, cookies, exceptions, hooks, models, status_codes, utils +from .models import _JSON, Response +from .structures import CaseInsensitiveDict as CaseInsensitiveDict -_BaseAdapter = adapters.BaseAdapter +_BaseAdapter: TypeAlias = adapters.BaseAdapter OrderedDict = compat.OrderedDict cookiejar_from_dict = cookies.cookiejar_from_dict extract_cookies_to_jar = cookies.extract_cookies_to_jar @@ -23,8 +25,6 @@ TooManyRedirects = exceptions.TooManyRedirects InvalidSchema = exceptions.InvalidSchema ChunkedEncodingError = exceptions.ChunkedEncodingError ContentDecodingError = exceptions.ContentDecodingError -RecentlyUsedContainer = _collections.RecentlyUsedContainer -CaseInsensitiveDict = structures.CaseInsensitiveDict HTTPAdapter = adapters.HTTPAdapter requote_uri = utils.requote_uri get_environ_proxies = utils.get_environ_proxies @@ -34,206 +34,281 @@ get_auth_from_url = utils.get_auth_from_url codes = status_codes.codes REDIRECT_STATI = models.REDIRECT_STATI +def preferred_clock() -> float: ... def merge_setting(request_setting, session_setting, dict_class=...): ... def merge_hooks(request_hooks, session_hooks, dict_class=...): ... class SessionRedirectMixin: - def resolve_redirects(self, resp, req, stream=..., timeout=..., verify=..., cert=..., proxies=...): ... + def resolve_redirects( + self, + resp, + req, + stream: bool = False, + timeout=None, + verify: bool = True, + cert=None, + proxies=None, + yield_requests: bool = False, + **adapter_kwargs, + ): ... def rebuild_auth(self, prepared_request, response): ... def rebuild_proxies(self, prepared_request, proxies): ... def should_strip_auth(self, old_url, new_url): ... + def rebuild_method(self, prepared_request: PreparedRequest, response: Response) -> None: ... + def get_redirect_target(self, resp: Response) -> str | None: ... -_Data = Union[None, Text, bytes, Mapping[str, Any], Mapping[Text, Any], Iterable[Tuple[Text, Optional[Text]]], IO[Any]] +_Data: TypeAlias = ( + # used in requests.models.PreparedRequest.prepare_body + # + # case: is_stream + # see requests.adapters.HTTPAdapter.send + # will be sent directly to http.HTTPConnection.send(...) (through urllib3) + Iterable[bytes] + # case: not is_stream + # will be modified before being sent to urllib3.HTTPConnectionPool.urlopen(body=...) + # see requests.models.RequestEncodingMixin._encode_params + # see requests.models.RequestEncodingMixin._encode_files + # note that keys&values are converted from Any to str by urllib.parse.urlencode + | str + | bytes + | SupportsRead[str | bytes] + | list[tuple[Any, Any]] + | tuple[tuple[Any, Any], ...] + | Mapping[Any, Any] +) +_Auth: TypeAlias = tuple[str, str] | _auth.AuthBase | Callable[[PreparedRequest], PreparedRequest] +_Cert: TypeAlias = str | tuple[str, str] +# Files is passed to requests.utils.to_key_val_list() +_FileName: TypeAlias = str | None +_FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes +_FileContentType: TypeAlias = str +_FileCustomHeaders: TypeAlias = Mapping[str, str] +_FileSpecTuple2: TypeAlias = tuple[_FileName, _FileContent] +_FileSpecTuple3: TypeAlias = tuple[_FileName, _FileContent, _FileContentType] +_FileSpecTuple4: TypeAlias = tuple[_FileName, _FileContent, _FileContentType, _FileCustomHeaders] +_FileSpec: TypeAlias = _FileContent | _FileSpecTuple2 | _FileSpecTuple3 | _FileSpecTuple4 +_Files: TypeAlias = Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] +_Hook: TypeAlias = Callable[[Response], Any] +_HooksInput: TypeAlias = Mapping[str, Iterable[_Hook] | _Hook] -_Hook = Callable[[Response], Any] -_Hooks = MutableMapping[Text, List[_Hook]] -_HooksInput = MutableMapping[Text, Union[Iterable[_Hook], _Hook]] +_ParamsMappingKeyType: TypeAlias = str | bytes | int | float +_ParamsMappingValueType: TypeAlias = str | bytes | int | float | Iterable[str | bytes | int | float] | None +_Params: TypeAlias = ( + SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType] + | tuple[_ParamsMappingKeyType, _ParamsMappingValueType] + | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]] + | str + | bytes +) +_TextMapping: TypeAlias = MutableMapping[str, str] +_HeadersUpdateMapping: TypeAlias = Mapping[str, str | bytes | None] +_Timeout: TypeAlias = float | tuple[float | None, float | None] +_Verify: TypeAlias = bool | str -_ParamsMappingKeyType = Union[Text, bytes, int, float] -_ParamsMappingValueType = Union[Text, bytes, int, float, Iterable[Union[Text, bytes, int, float]], None] -_Params = Union[ - SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], - Tuple[_ParamsMappingKeyType, _ParamsMappingValueType], - Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], - Union[Text, bytes], -] -_TextMapping = MutableMapping[Text, Text] -_SessionT = TypeVar("_SessionT", bound=Session) +@type_check_only +class _Settings(TypedDict): + verify: _Verify | None + proxies: _TextMapping + stream: bool + cert: _Cert | None class Session(SessionRedirectMixin): __attrs__: Any - headers: CaseInsensitiveDict[Text] - auth: None | tuple[Text, Text] | _auth.AuthBase | Callable[[PreparedRequest], PreparedRequest] + # See https://github.com/psf/requests/issues/5020#issuecomment-989082461: + # requests sets this as a CaseInsensitiveDict, but users may set it to any MutableMapping + headers: MutableMapping[str, str | bytes] + auth: _Auth | None proxies: _TextMapping - hooks: _Hooks + # Don't complain if: + # - value is assumed to be a list (which it is by default) + # - a _Hook is assigned directly, without wrapping it in a list (also works) + hooks: dict[str, list[_Hook] | Any] params: _Params stream: bool - verify: None | bool | Text - cert: None | Text | tuple[Text, Text] + verify: _Verify | None + cert: _Cert | None max_redirects: int trust_env: bool cookies: RequestsCookieJar - adapters: MutableMapping[Any, Any] - redirect_cache: RecentlyUsedContainer[Any, Any] + adapters: MutableMapping[str, _BaseAdapter] def __init__(self) -> None: ... - def __enter__(self: _SessionT) -> _SessionT: ... - def __exit__(self, *args) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... def prepare_request(self, request: Request) -> PreparedRequest: ... def request( self, - method: str, - url: str | bytes | Text, - params: _Params | None = ..., - data: _Data = ..., - headers: _TextMapping | None = ..., - cookies: None | RequestsCookieJar | _TextMapping = ..., - files: MutableMapping[Text, IO[Any]] - | MutableMapping[Text, tuple[Text, IO[Any]]] - | MutableMapping[Text, tuple[Text, IO[Any], Text]] - | MutableMapping[Text, tuple[Text, IO[Any], Text, _TextMapping]] - | None = ..., - auth: None | tuple[Text, Text] | _auth.AuthBase | Callable[[PreparedRequest], PreparedRequest] = ..., - timeout: None | float | tuple[float, float] | tuple[float, None] = ..., - allow_redirects: bool | None = ..., - proxies: _TextMapping | None = ..., - hooks: _HooksInput | None = ..., - stream: bool | None = ..., - verify: None | bool | Text = ..., - cert: Text | tuple[Text, Text] | None = ..., - json: Any | None = ..., + method: str | bytes, + url: str | bytes, + params: _Params | None = None, + data: _Data | None = None, + headers: _HeadersUpdateMapping | None = None, + cookies: RequestsCookieJar | _TextMapping | None = None, + files: _Files | None = None, + auth: _Auth | None = None, + timeout: _Timeout | None = None, + allow_redirects: bool = True, + proxies: _TextMapping | None = None, + hooks: _HooksInput | None = None, + stream: bool | None = None, + verify: _Verify | None = None, + cert: _Cert | None = None, + json: _JSON | None = None, ) -> Response: ... def get( self, - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def options( self, - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def head( self, - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def post( self, - url: Text | bytes, - data: _Data = ..., - json: Any | None = ..., + url: str | bytes, + data: _Data | None = None, + json: _JSON | None = None, + *, params: _Params | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., ) -> Response: ... def put( self, - url: Text | bytes, - data: _Data = ..., + url: str | bytes, + data: _Data | None = None, + *, params: _Params | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def patch( self, - url: Text | bytes, - data: _Data = ..., + url: str | bytes, + data: _Data | None = None, + *, params: _Params | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def delete( self, - url: Text | bytes, + url: str | bytes, + *, params: _Params | None = ..., - data: Any | None = ..., - headers: Any | None = ..., - cookies: Any | None = ..., - files: Any | None = ..., - auth: Any | None = ..., - timeout: Any | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., allow_redirects: bool = ..., - proxies: Any | None = ..., - hooks: Any | None = ..., - stream: Any | None = ..., - verify: Any | None = ..., - cert: Any | None = ..., - json: Any | None = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, ) -> Response: ... def send( - self, request: PreparedRequest, *, stream=..., verify=..., cert=..., proxies=..., allow_redirects: bool = ..., **kwargs + self, + request: PreparedRequest, + *, + stream: bool | None = ..., + verify: _Verify | None = ..., + proxies: _TextMapping | None = ..., + cert: _Cert | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + **kwargs: Any, ) -> Response: ... - def merge_environment_settings(self, url, proxies, stream, verify, cert): ... + def merge_environment_settings( + self, + url: str | bytes | None, + proxies: _TextMapping | None, + stream: bool | None, + verify: _Verify | None, + cert: _Cert | None, + ) -> _Settings: ... def get_adapter(self, url: str) -> _BaseAdapter: ... def close(self) -> None: ... - def mount(self, prefix: Text | bytes, adapter: _BaseAdapter) -> None: ... + def mount(self, prefix: str | bytes, adapter: _BaseAdapter) -> None: ... def session() -> Session: ... diff --git a/stubs/requests/requests/structures.pyi b/stubs/requests/requests/structures.pyi index ed7d9a2f225c..fbfffefce04b 100644 --- a/stubs/requests/requests/structures.pyi +++ b/stubs/requests/requests/structures.pyi @@ -1,9 +1,11 @@ -from typing import Any, Dict, Generic, Iterable, Iterator, Mapping, MutableMapping, TypeVar +from collections.abc import Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Generic, TypeVar, overload +_D = TypeVar("_D") _VT = TypeVar("_VT") class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]): - def __init__(self, data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = ..., **kwargs: _VT) -> None: ... + def __init__(self, data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None, **kwargs: _VT) -> None: ... def lower_items(self) -> Iterator[tuple[str, _VT]]: ... def __setitem__(self, key: str, value: _VT) -> None: ... def __getitem__(self, key: str) -> _VT: ... @@ -12,9 +14,13 @@ class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]): def __len__(self) -> int: ... def copy(self) -> CaseInsensitiveDict[_VT]: ... -class LookupDict(Dict[str, _VT]): +class LookupDict(dict[str, _VT]): name: Any - def __init__(self, name: Any = ...) -> None: ... + def __init__(self, name: Any = None) -> None: ... def __getitem__(self, key: str) -> _VT | None: ... # type: ignore[override] - def __getattr__(self, attr: str) -> _VT: ... - def __setattr__(self, attr: str, value: _VT) -> None: ... + def __setattr__(self, attr: str, value: _VT, /) -> None: ... + + @overload + def get(self, key: str, default: None = None) -> _VT | None: ... + @overload + def get(self, key: str, default: _D | _VT) -> _D | _VT: ... diff --git a/stubs/requests/requests/utils.pyi b/stubs/requests/requests/utils.pyi index 994652846491..87b608d7245b 100644 --- a/stubs/requests/requests/utils.pyi +++ b/stubs/requests/requests/utils.pyi @@ -1,54 +1,69 @@ -from typing import Any, AnyStr, Iterable, Mapping, Text +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Generator, Iterable, Mapping +from contextlib import _GeneratorContextManager +from io import BufferedWriter +from typing import AnyStr, TypeAlias from . import compat, cookies, exceptions, structures +from .models import PreparedRequest, Request +_Uri: TypeAlias = str | bytes OrderedDict = compat.OrderedDict -RequestsCookieJar = cookies.RequestsCookieJar cookiejar_from_dict = cookies.cookiejar_from_dict CaseInsensitiveDict = structures.CaseInsensitiveDict InvalidURL = exceptions.InvalidURL -NETRC_FILES: Any -DEFAULT_CA_BUNDLE_PATH: Any -DEFAULT_PORTS: Any +NETRC_FILES: tuple[str, str] +DEFAULT_CA_BUNDLE_PATH: str +DEFAULT_PORTS: dict[str, int] +DEFAULT_ACCEPT_ENCODING: str def dict_to_sequence(d): ... def super_len(o): ... -def get_netrc_auth(url, raise_errors: bool = ...): ... +def get_netrc_auth(url: _Uri, raise_errors: bool = False) -> tuple[str, str] | None: ... def guess_filename(obj): ... def extract_zipped_paths(path): ... +def atomic_open(filename: StrOrBytesPath) -> _GeneratorContextManager[BufferedWriter]: ... def from_key_val_list(value): ... def to_key_val_list(value): ... def parse_list_header(value): ... def parse_dict_header(value): ... -def unquote_header_value(value, is_filename=...): ... +def unquote_header_value(value, is_filename: bool = False): ... def dict_from_cookiejar(cj): ... def add_dict_to_cookiejar(cj, cookie_dict): ... def get_encodings_from_content(content): ... -def get_encoding_from_headers(headers): ... +def get_encoding_from_headers(headers: Mapping[str, str]) -> str | None: ... def stream_decode_response_unicode(iterator, r): ... -def iter_slices(string, slice_length): ... +def iter_slices(string: str, slice_length: int | None) -> Generator[str]: ... def get_unicode_from_response(r): ... -UNRESERVED_SET: Any +UNRESERVED_SET: frozenset[str] -def unquote_unreserved(uri): ... -def requote_uri(uri): ... -def address_in_network(ip, net): ... -def dotted_netmask(mask): ... -def is_ipv4_address(string_ip): ... -def is_valid_cidr(string_network): ... -def set_environ(env_name, value): ... -def should_bypass_proxies(url, no_proxy: Iterable[AnyStr] | None) -> bool: ... -def get_environ_proxies(url, no_proxy: Iterable[AnyStr] | None = ...) -> dict[Any, Any]: ... -def select_proxy(url: Text, proxies: Mapping[Any, Any] | None): ... -def default_user_agent(name=...): ... -def default_headers(): ... -def parse_header_links(value): ... +def unquote_unreserved(uri: str) -> str: ... +def requote_uri(uri: str) -> str: ... +def address_in_network(ip: str, net: str) -> bool: ... +def dotted_netmask(mask: int) -> str: ... +def is_ipv4_address(string_ip: str) -> bool: ... +def is_valid_cidr(string_network: str) -> bool: ... +def set_environ(env_name: str, value: None) -> _GeneratorContextManager[None]: ... +def should_bypass_proxies(url: _Uri, no_proxy: str | None) -> bool: ... +def get_environ_proxies(url: _Uri, no_proxy: Iterable[str] | None = None) -> dict[str, str]: ... +def select_proxy(url: _Uri, proxies: Mapping[str, str] | None) -> str | None: ... +def resolve_proxies( + request: Request | PreparedRequest, proxies: dict[str, str] | None, trust_env: bool = True +) -> dict[str, str]: ... +def default_user_agent(name: str = "python-requests") -> str: ... +def default_headers() -> CaseInsensitiveDict[str]: ... +def parse_header_links(value: str) -> list[dict[str, str]]: ... def guess_json_utf(data): ... def prepend_scheme_if_needed(url, new_scheme): ... -def get_auth_from_url(url): ... -def to_native_string(string, encoding=...): ... -def urldefragauth(url): ... -def rewind_body(prepared_request): ... +def get_auth_from_url(url: _Uri) -> tuple[str, str]: ... +def to_native_string(string, encoding="ascii"): ... +def urldefragauth(url: _Uri): ... +def rewind_body(prepared_request: PreparedRequest) -> None: ... def check_header_validity(header: tuple[AnyStr, AnyStr]) -> None: ... + +if sys.platform == "win32": + def proxy_bypass_registry(host: str) -> bool: ... + def proxy_bypass(host: str) -> bool: ... diff --git a/stubs/resampy/@tests/stubtest_allowlist.txt b/stubs/resampy/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c6295d94aa58 --- /dev/null +++ b/stubs/resampy/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Part of internal API which is not needed for public type stubs: +resampy.interpn diff --git a/stubs/resampy/METADATA.toml b/stubs/resampy/METADATA.toml new file mode 100644 index 000000000000..ed770025c32d --- /dev/null +++ b/stubs/resampy/METADATA.toml @@ -0,0 +1,4 @@ +version = "0.4.*" +upstream-repository = "https://github.com/bmcfee/resampy" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] diff --git a/stubs/resampy/resampy/__init__.pyi b/stubs/resampy/resampy/__init__.pyi new file mode 100644 index 000000000000..92d287f8a8fb --- /dev/null +++ b/stubs/resampy/resampy/__init__.pyi @@ -0,0 +1,2 @@ +from . import filters as filters +from .core import * diff --git a/stubs/resampy/resampy/core.pyi b/stubs/resampy/resampy/core.pyi new file mode 100644 index 000000000000..f4d29b1b925b --- /dev/null +++ b/stubs/resampy/resampy/core.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from typing import Any, TypeAlias, TypeVar + +import numpy as np + +__all__ = ["resample", "resample_nu"] + +# np.floating[Any] because precision is not important +_FloatArray = TypeVar("_FloatArray", bound=np.ndarray[tuple[int, ...], np.dtype[np.floating[Any]]]) +_FilterType: TypeAlias = str | Callable[[int], np.ndarray[tuple[int], np.dtype[np.float64]]] + +def resample( + x: _FloatArray, + sr_orig: float, + sr_new: float, + axis: int = -1, + filter: _FilterType = "kaiser_best", + parallel: bool = False, + *, + num_zeros: int = 64, + precision: int = 9, + rolloff: float = 0.945, +) -> _FloatArray: ... +def resample_nu( + x: _FloatArray, + sr_orig: float, + t_out: _FloatArray, + axis: int = -1, + filter: _FilterType = "kaiser_best", + parallel: bool = False, + *, + num_zeros: int = 64, + precision: int = 9, + rolloff: float = 0.945, +) -> _FloatArray: ... diff --git a/stubs/resampy/resampy/filters.pyi b/stubs/resampy/resampy/filters.pyi new file mode 100644 index 000000000000..07e85e4e26af --- /dev/null +++ b/stubs/resampy/resampy/filters.pyi @@ -0,0 +1,26 @@ +from collections.abc import Callable +from typing import TypeAlias + +import numpy as np + +__all__ = ["get_filter", "clear_cache", "sinc_window"] + +# Dictionary to cache loaded filters +FILTER_CACHE: dict[str, tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]] + +# List of filter functions available +FILTER_FUNCTIONS: list[str] + +_FilterType: TypeAlias = str | Callable[[int], np.ndarray[tuple[int], np.dtype[np.float64]]] + +def sinc_window( + num_zeros: int = 64, + precision: int = 9, + window: Callable[[int], np.ndarray[tuple[int], np.dtype[np.float64]]] | None = None, + rolloff: float = 0.945, +) -> tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]: ... +def get_filter( + name_or_function: _FilterType, *, num_zeros: int = 64, precision: int = 9, rolloff: float = 0.945 +) -> tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]: ... +def load_filter(filter_name: str) -> tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]: ... +def clear_cache() -> None: ... diff --git a/stubs/resampy/resampy/version.pyi b/stubs/resampy/resampy/version.pyi new file mode 100644 index 000000000000..24179934d795 --- /dev/null +++ b/stubs/resampy/resampy/version.pyi @@ -0,0 +1,4 @@ +from typing import Final + +short_version: Final[str] +version: Final[str] diff --git a/stubs/retry/@tests/stubtest_allowlist.txt b/stubs/retry/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0e4e3d2ea1ed --- /dev/null +++ b/stubs/retry/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +retry.compat +retry.tests +retry.tests.test_retry diff --git a/stubs/retry/METADATA.toml b/stubs/retry/METADATA.toml index 6f2870bcfb82..40237f386a7f 100644 --- a/stubs/retry/METADATA.toml +++ b/stubs/retry/METADATA.toml @@ -1,2 +1,2 @@ version = "0.9.*" -python2 = true +upstream-repository = "https://github.com/invl/retry" diff --git a/stubs/retry/retry/__init__.pyi b/stubs/retry/retry/__init__.pyi index 0cf7651b0569..6818afd2d64a 100644 --- a/stubs/retry/retry/__init__.pyi +++ b/stubs/retry/retry/__init__.pyi @@ -1 +1,3 @@ from .api import retry as retry + +__all__ = ["retry"] diff --git a/stubs/retry/retry/api.pyi b/stubs/retry/retry/api.pyi index a0b68c1a6d79..e550c1ca2c90 100644 --- a/stubs/retry/retry/api.pyi +++ b/stubs/retry/retry/api.pyi @@ -1,27 +1,30 @@ from _typeshed import IdentityFunction +from collections.abc import Callable, Sequence from logging import Logger -from typing import Any, Callable, Sequence, Tuple, Type, TypeVar +from typing import Any, TypeVar _R = TypeVar("_R") +logging_logger: Logger + def retry_call( f: Callable[..., _R], - fargs: Sequence[Any] | None = ..., - fkwargs: dict[str, Any] | None = ..., - exceptions: Type[Exception] | Tuple[Type[Exception], ...] = ..., - tries: int = ..., - delay: float = ..., - max_delay: float | None = ..., - backoff: float = ..., - jitter: tuple[float, float] | float = ..., + fargs: Sequence[Any] | None = None, + fkwargs: dict[str, Any] | None = None, + exceptions: type[Exception] | tuple[type[Exception], ...] = ..., + tries: int = -1, + delay: float = 0, + max_delay: float | None = None, + backoff: float = 1, + jitter: tuple[float, float] | float = 0, logger: Logger | None = ..., ) -> _R: ... def retry( - exceptions: Type[Exception] | Tuple[Type[Exception], ...] = ..., - tries: int = ..., - delay: float = ..., - max_delay: float | None = ..., - backoff: float = ..., - jitter: tuple[float, float] | float = ..., + exceptions: type[Exception] | tuple[type[Exception], ...] = ..., + tries: int = -1, + delay: float = 0, + max_delay: float | None = None, + backoff: float = 1, + jitter: tuple[float, float] | float = 0, logger: Logger | None = ..., ) -> IdentityFunction: ... diff --git a/stubs/rfc3339-validator/METADATA.toml b/stubs/rfc3339-validator/METADATA.toml new file mode 100644 index 000000000000..d2bb8f30a310 --- /dev/null +++ b/stubs/rfc3339-validator/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.1.*" +upstream-repository = "https://github.com/naimetti/rfc3339-validator" diff --git a/stubs/rfc3339-validator/rfc3339_validator.pyi b/stubs/rfc3339-validator/rfc3339_validator.pyi new file mode 100644 index 000000000000..71f545bf2415 --- /dev/null +++ b/stubs/rfc3339-validator/rfc3339_validator.pyi @@ -0,0 +1,10 @@ +import re +from typing import Final + +__version__: Final[str] +__author__: Final[str] +__email__: Final[str] +RFC3339_REGEX_FLAGS: Final[int] +RFC3339_REGEX: Final[re.Pattern[str]] + +def validate_rfc3339(date_string: str) -> bool: ... diff --git a/stubs/s2clientprotocol/@tests/stubtest_allowlist.txt b/stubs/s2clientprotocol/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b2e471a072ca --- /dev/null +++ b/stubs/s2clientprotocol/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# All modules ending with *_pb2 fail to import +# The error message is "TypeError: Descriptors cannot be created directly. +# If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0." +s2clientprotocol\..+_pb2 diff --git a/stubs/s2clientprotocol/METADATA.toml b/stubs/s2clientprotocol/METADATA.toml new file mode 100644 index 000000000000..04ffb1ba31f9 --- /dev/null +++ b/stubs/s2clientprotocol/METADATA.toml @@ -0,0 +1,7 @@ +# Whenever you update version here, PACKAGE_VERSION should be updated +# in scripts/sync_protobuf/s2clientprotocol.py and vice-versa. +# When updating, also re-run the script +version = "5.*" +upstream-repository = "https://github.com/Blizzard/s2client-proto" +dependencies = ["types-protobuf"] +extra-description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 27.2 on [s2client-proto 5.0.12.91115.0](https://github.com/Blizzard/s2client-proto/tree/c04df4adbe274858a4eb8417175ee32ad02fd609)." diff --git a/stubs/s2clientprotocol/s2clientprotocol/build.pyi b/stubs/s2clientprotocol/s2clientprotocol/build.pyi new file mode 100644 index 000000000000..53949f46173c --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/build.pyi @@ -0,0 +1,5 @@ +from subprocess import _CMD + +def game_version() -> str: ... +def git_commit_hash() -> str: ... +def read_command_output(cmd: _CMD) -> list[str]: ... diff --git a/stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi new file mode 100644 index 000000000000..cfa0bec86506 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi @@ -0,0 +1,177 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Race: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _RaceEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Race.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NoRace: _Race.ValueType # 0 + Terran: _Race.ValueType # 1 + Zerg: _Race.ValueType # 2 + Protoss: _Race.ValueType # 3 + Random: _Race.ValueType # 4 + +class Race(_Race, metaclass=_RaceEnumTypeWrapper): ... + +NoRace: Race.ValueType # 0 +Terran: Race.ValueType # 1 +Zerg: Race.ValueType # 2 +Protoss: Race.ValueType # 3 +Random: Race.ValueType # 4 +global___Race = Race + +@typing.final +class AvailableAbility(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + REQUIRES_POINT_FIELD_NUMBER: builtins.int + ability_id: builtins.int + requires_point: builtins.bool + def __init__(self, *, ability_id: builtins.int | None = ..., requires_point: builtins.bool | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["ability_id", b"ability_id", "requires_point", b"requires_point"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["ability_id", b"ability_id", "requires_point", b"requires_point"] + ) -> None: ... + +global___AvailableAbility = AvailableAbility + +@typing.final +class ImageData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BITS_PER_PIXEL_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + DATA_FIELD_NUMBER: builtins.int + bits_per_pixel: builtins.int + """Number of bits per pixel; 8 bits for a byte etc.""" + data: builtins.bytes + """Binary data; the size of this buffer in bytes is width * height * bits_per_pixel / 8.""" + @property + def size(self) -> global___Size2DI: + """Dimension in pixels.""" + + def __init__( + self, *, bits_per_pixel: builtins.int | None = ..., size: global___Size2DI | None = ..., data: builtins.bytes | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["bits_per_pixel", b"bits_per_pixel", "data", b"data", "size", b"size"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["bits_per_pixel", b"bits_per_pixel", "data", b"data", "size", b"size"] + ) -> None: ... + +global___ImageData = ImageData + +@typing.final +class PointI(google.protobuf.message.Message): + """Point on the screen/minimap (e.g., 0..64). + Note: bottom left of the screen is 0, 0. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + x: builtins.int + y: builtins.int + def __init__(self, *, x: builtins.int | None = ..., y: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> None: ... + +global___PointI = PointI + +@typing.final +class RectangleI(google.protobuf.message.Message): + """Screen space rectangular area.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + P0_FIELD_NUMBER: builtins.int + P1_FIELD_NUMBER: builtins.int + @property + def p0(self) -> global___PointI: ... + @property + def p1(self) -> global___PointI: ... + def __init__(self, *, p0: global___PointI | None = ..., p1: global___PointI | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> None: ... + +global___RectangleI = RectangleI + +@typing.final +class Point2D(google.protobuf.message.Message): + """Point on the game board, 0..255. + Note: bottom left of the screen is 0, 0. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + x: builtins.float + y: builtins.float + def __init__(self, *, x: builtins.float | None = ..., y: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> None: ... + +global___Point2D = Point2D + +@typing.final +class Point(google.protobuf.message.Message): + """Point on the game board, 0..255. + Note: bottom left of the screen is 0, 0. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + Z_FIELD_NUMBER: builtins.int + x: builtins.float + y: builtins.float + z: builtins.float + def __init__( + self, *, x: builtins.float | None = ..., y: builtins.float | None = ..., z: builtins.float | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y", "z", b"z"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y", "z", b"z"]) -> None: ... + +global___Point = Point + +@typing.final +class Size2DI(google.protobuf.message.Message): + """Screen dimensions.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + x: builtins.int + y: builtins.int + def __init__(self, *, x: builtins.int | None = ..., y: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> None: ... + +global___Size2DI = Size2DI diff --git a/stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi new file mode 100644 index 000000000000..cd68bb65df02 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi @@ -0,0 +1,615 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Attribute: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AttributeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Attribute.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Light: _Attribute.ValueType # 1 + Armored: _Attribute.ValueType # 2 + Biological: _Attribute.ValueType # 3 + Mechanical: _Attribute.ValueType # 4 + Robotic: _Attribute.ValueType # 5 + Psionic: _Attribute.ValueType # 6 + Massive: _Attribute.ValueType # 7 + Structure: _Attribute.ValueType # 8 + Hover: _Attribute.ValueType # 9 + Heroic: _Attribute.ValueType # 10 + Summoned: _Attribute.ValueType # 11 + +class Attribute(_Attribute, metaclass=_AttributeEnumTypeWrapper): ... + +Light: Attribute.ValueType # 1 +Armored: Attribute.ValueType # 2 +Biological: Attribute.ValueType # 3 +Mechanical: Attribute.ValueType # 4 +Robotic: Attribute.ValueType # 5 +Psionic: Attribute.ValueType # 6 +Massive: Attribute.ValueType # 7 +Structure: Attribute.ValueType # 8 +Hover: Attribute.ValueType # 9 +Heroic: Attribute.ValueType # 10 +Summoned: Attribute.ValueType # 11 +global___Attribute = Attribute + +@typing.final +class AbilityData(google.protobuf.message.Message): + """May not relevant: queueable (everything is queueable). + May not be important: AbilSetId - marine stim, marauder stim. + Stuff omitted: transient. + Stuff that may be important: cost, range, Alignment, targetfilters. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Target: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TargetEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[AbilityData._Target.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Point: AbilityData._Target.ValueType # 2 + """Requires a target position.""" + Unit: AbilityData._Target.ValueType # 3 + """Requires a unit to target. Given by position using feature layers.""" + PointOrUnit: AbilityData._Target.ValueType # 4 + """Requires either a target point or target unit.""" + PointOrNone: AbilityData._Target.ValueType # 5 + """Requires either a target point or no target. (eg. building add-ons)""" + + class Target(_Target, metaclass=_TargetEnumTypeWrapper): ... + Point: AbilityData.Target.ValueType # 2 + """Requires a target position.""" + Unit: AbilityData.Target.ValueType # 3 + """Requires a unit to target. Given by position using feature layers.""" + PointOrUnit: AbilityData.Target.ValueType # 4 + """Requires either a target point or target unit.""" + PointOrNone: AbilityData.Target.ValueType # 5 + """Requires either a target point or no target. (eg. building add-ons)""" + + ABILITY_ID_FIELD_NUMBER: builtins.int + LINK_NAME_FIELD_NUMBER: builtins.int + LINK_INDEX_FIELD_NUMBER: builtins.int + BUTTON_NAME_FIELD_NUMBER: builtins.int + FRIENDLY_NAME_FIELD_NUMBER: builtins.int + HOTKEY_FIELD_NUMBER: builtins.int + REMAPS_TO_ABILITY_ID_FIELD_NUMBER: builtins.int + AVAILABLE_FIELD_NUMBER: builtins.int + TARGET_FIELD_NUMBER: builtins.int + ALLOW_MINIMAP_FIELD_NUMBER: builtins.int + ALLOW_AUTOCAST_FIELD_NUMBER: builtins.int + IS_BUILDING_FIELD_NUMBER: builtins.int + FOOTPRINT_RADIUS_FIELD_NUMBER: builtins.int + IS_INSTANT_PLACEMENT_FIELD_NUMBER: builtins.int + CAST_RANGE_FIELD_NUMBER: builtins.int + ability_id: builtins.int + """Stable ID.""" + link_name: builtins.str + """Catalog name of the ability.""" + link_index: builtins.int + """Catalog index of the ability.""" + button_name: builtins.str + """Name used for the command card. May not always be set.""" + friendly_name: builtins.str + """A human friendly name when the button name or link name isn't descriptive.""" + hotkey: builtins.str + """Hotkey. May not always be set.""" + remaps_to_ability_id: builtins.int + """This ability id may be represented by the given more generic id.""" + available: builtins.bool + """If true, the ability may be used by this set of mods/map.""" + target: global___AbilityData.Target.ValueType + """Determines if a point is optional or required.""" + allow_minimap: builtins.bool + """Can be cast in the minimap.""" + allow_autocast: builtins.bool + """Autocast can be set.""" + is_building: builtins.bool + """Requires placement to construct a building.""" + footprint_radius: builtins.float + """Estimation of the footprint size. Need a better footprint.""" + is_instant_placement: builtins.bool + """Placement next to an existing structure, e.g., an add-on like a Tech Lab.""" + cast_range: builtins.float + """Range unit can cast ability without needing to approach target.""" + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + link_name: builtins.str | None = ..., + link_index: builtins.int | None = ..., + button_name: builtins.str | None = ..., + friendly_name: builtins.str | None = ..., + hotkey: builtins.str | None = ..., + remaps_to_ability_id: builtins.int | None = ..., + available: builtins.bool | None = ..., + target: global___AbilityData.Target.ValueType | None = ..., + allow_minimap: builtins.bool | None = ..., + allow_autocast: builtins.bool | None = ..., + is_building: builtins.bool | None = ..., + footprint_radius: builtins.float | None = ..., + is_instant_placement: builtins.bool | None = ..., + cast_range: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "allow_autocast", + b"allow_autocast", + "allow_minimap", + b"allow_minimap", + "available", + b"available", + "button_name", + b"button_name", + "cast_range", + b"cast_range", + "footprint_radius", + b"footprint_radius", + "friendly_name", + b"friendly_name", + "hotkey", + b"hotkey", + "is_building", + b"is_building", + "is_instant_placement", + b"is_instant_placement", + "link_index", + b"link_index", + "link_name", + b"link_name", + "remaps_to_ability_id", + b"remaps_to_ability_id", + "target", + b"target", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "allow_autocast", + b"allow_autocast", + "allow_minimap", + b"allow_minimap", + "available", + b"available", + "button_name", + b"button_name", + "cast_range", + b"cast_range", + "footprint_radius", + b"footprint_radius", + "friendly_name", + b"friendly_name", + "hotkey", + b"hotkey", + "is_building", + b"is_building", + "is_instant_placement", + b"is_instant_placement", + "link_index", + b"link_index", + "link_name", + b"link_name", + "remaps_to_ability_id", + b"remaps_to_ability_id", + "target", + b"target", + ], + ) -> None: ... + +global___AbilityData = AbilityData + +@typing.final +class DamageBonus(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ATTRIBUTE_FIELD_NUMBER: builtins.int + BONUS_FIELD_NUMBER: builtins.int + attribute: global___Attribute.ValueType + bonus: builtins.float + def __init__(self, *, attribute: global___Attribute.ValueType | None = ..., bonus: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["attribute", b"attribute", "bonus", b"bonus"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["attribute", b"attribute", "bonus", b"bonus"]) -> None: ... + +global___DamageBonus = DamageBonus + +@typing.final +class Weapon(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _TargetType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TargetTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Weapon._TargetType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Ground: Weapon._TargetType.ValueType # 1 + Air: Weapon._TargetType.ValueType # 2 + Any: Weapon._TargetType.ValueType # 3 + + class TargetType(_TargetType, metaclass=_TargetTypeEnumTypeWrapper): ... + Ground: Weapon.TargetType.ValueType # 1 + Air: Weapon.TargetType.ValueType # 2 + Any: Weapon.TargetType.ValueType # 3 + + TYPE_FIELD_NUMBER: builtins.int + DAMAGE_FIELD_NUMBER: builtins.int + DAMAGE_BONUS_FIELD_NUMBER: builtins.int + ATTACKS_FIELD_NUMBER: builtins.int + RANGE_FIELD_NUMBER: builtins.int + SPEED_FIELD_NUMBER: builtins.int + type: global___Weapon.TargetType.ValueType + damage: builtins.float + attacks: builtins.int + """Number of hits per attack. (eg. Colossus has 2 beams)""" + range: builtins.float + speed: builtins.float + """Time between attacks.""" + @property + def damage_bonus(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DamageBonus]: ... + def __init__( + self, + *, + type: global___Weapon.TargetType.ValueType | None = ..., + damage: builtins.float | None = ..., + damage_bonus: collections.abc.Iterable[global___DamageBonus] | None = ..., + attacks: builtins.int | None = ..., + range: builtins.float | None = ..., + speed: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "attacks", b"attacks", "damage", b"damage", "range", b"range", "speed", b"speed", "type", b"type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "attacks", + b"attacks", + "damage", + b"damage", + "damage_bonus", + b"damage_bonus", + "range", + b"range", + "speed", + b"speed", + "type", + b"type", + ], + ) -> None: ... + +global___Weapon = Weapon + +@typing.final +class UnitTypeData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + AVAILABLE_FIELD_NUMBER: builtins.int + CARGO_SIZE_FIELD_NUMBER: builtins.int + MINERAL_COST_FIELD_NUMBER: builtins.int + VESPENE_COST_FIELD_NUMBER: builtins.int + FOOD_REQUIRED_FIELD_NUMBER: builtins.int + FOOD_PROVIDED_FIELD_NUMBER: builtins.int + ABILITY_ID_FIELD_NUMBER: builtins.int + RACE_FIELD_NUMBER: builtins.int + BUILD_TIME_FIELD_NUMBER: builtins.int + HAS_VESPENE_FIELD_NUMBER: builtins.int + HAS_MINERALS_FIELD_NUMBER: builtins.int + SIGHT_RANGE_FIELD_NUMBER: builtins.int + TECH_ALIAS_FIELD_NUMBER: builtins.int + UNIT_ALIAS_FIELD_NUMBER: builtins.int + TECH_REQUIREMENT_FIELD_NUMBER: builtins.int + REQUIRE_ATTACHED_FIELD_NUMBER: builtins.int + ATTRIBUTES_FIELD_NUMBER: builtins.int + MOVEMENT_SPEED_FIELD_NUMBER: builtins.int + ARMOR_FIELD_NUMBER: builtins.int + WEAPONS_FIELD_NUMBER: builtins.int + unit_id: builtins.int + """Stable ID.""" + name: builtins.str + """Catalog name of the unit.""" + available: builtins.bool + """If true, the ability may be used by this set of mods/map.""" + cargo_size: builtins.int + """Number of cargo slots it occupies in transports.""" + mineral_cost: builtins.int + vespene_cost: builtins.int + food_required: builtins.float + food_provided: builtins.float + ability_id: builtins.int + """The ability that builds this unit.""" + race: s2clientprotocol.common_pb2.Race.ValueType + build_time: builtins.float + has_vespene: builtins.bool + has_minerals: builtins.bool + sight_range: builtins.float + """Range unit reveals vision.""" + unit_alias: builtins.int + """The morphed variant of this unit.""" + tech_requirement: builtins.int + """Structure required to build this unit. (Or any with the same tech_alias)""" + require_attached: builtins.bool + """Whether tech_requirement is an add-on.""" + movement_speed: builtins.float + armor: builtins.float + @property + def tech_alias(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Other units that satisfy the same tech requirement.""" + + @property + def attributes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___Attribute.ValueType]: + """Values include changes from upgrades""" + + @property + def weapons(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Weapon]: ... + def __init__( + self, + *, + unit_id: builtins.int | None = ..., + name: builtins.str | None = ..., + available: builtins.bool | None = ..., + cargo_size: builtins.int | None = ..., + mineral_cost: builtins.int | None = ..., + vespene_cost: builtins.int | None = ..., + food_required: builtins.float | None = ..., + food_provided: builtins.float | None = ..., + ability_id: builtins.int | None = ..., + race: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + build_time: builtins.float | None = ..., + has_vespene: builtins.bool | None = ..., + has_minerals: builtins.bool | None = ..., + sight_range: builtins.float | None = ..., + tech_alias: collections.abc.Iterable[builtins.int] | None = ..., + unit_alias: builtins.int | None = ..., + tech_requirement: builtins.int | None = ..., + require_attached: builtins.bool | None = ..., + attributes: collections.abc.Iterable[global___Attribute.ValueType] | None = ..., + movement_speed: builtins.float | None = ..., + armor: builtins.float | None = ..., + weapons: collections.abc.Iterable[global___Weapon] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "armor", + b"armor", + "available", + b"available", + "build_time", + b"build_time", + "cargo_size", + b"cargo_size", + "food_provided", + b"food_provided", + "food_required", + b"food_required", + "has_minerals", + b"has_minerals", + "has_vespene", + b"has_vespene", + "mineral_cost", + b"mineral_cost", + "movement_speed", + b"movement_speed", + "name", + b"name", + "race", + b"race", + "require_attached", + b"require_attached", + "sight_range", + b"sight_range", + "tech_requirement", + b"tech_requirement", + "unit_alias", + b"unit_alias", + "unit_id", + b"unit_id", + "vespene_cost", + b"vespene_cost", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "armor", + b"armor", + "attributes", + b"attributes", + "available", + b"available", + "build_time", + b"build_time", + "cargo_size", + b"cargo_size", + "food_provided", + b"food_provided", + "food_required", + b"food_required", + "has_minerals", + b"has_minerals", + "has_vespene", + b"has_vespene", + "mineral_cost", + b"mineral_cost", + "movement_speed", + b"movement_speed", + "name", + b"name", + "race", + b"race", + "require_attached", + b"require_attached", + "sight_range", + b"sight_range", + "tech_alias", + b"tech_alias", + "tech_requirement", + b"tech_requirement", + "unit_alias", + b"unit_alias", + "unit_id", + b"unit_id", + "vespene_cost", + b"vespene_cost", + "weapons", + b"weapons", + ], + ) -> None: ... + +global___UnitTypeData = UnitTypeData + +@typing.final +class UpgradeData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UPGRADE_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + MINERAL_COST_FIELD_NUMBER: builtins.int + VESPENE_COST_FIELD_NUMBER: builtins.int + RESEARCH_TIME_FIELD_NUMBER: builtins.int + ABILITY_ID_FIELD_NUMBER: builtins.int + upgrade_id: builtins.int + """Stable ID.""" + name: builtins.str + mineral_cost: builtins.int + vespene_cost: builtins.int + research_time: builtins.float + ability_id: builtins.int + def __init__( + self, + *, + upgrade_id: builtins.int | None = ..., + name: builtins.str | None = ..., + mineral_cost: builtins.int | None = ..., + vespene_cost: builtins.int | None = ..., + research_time: builtins.float | None = ..., + ability_id: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "mineral_cost", + b"mineral_cost", + "name", + b"name", + "research_time", + b"research_time", + "upgrade_id", + b"upgrade_id", + "vespene_cost", + b"vespene_cost", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "mineral_cost", + b"mineral_cost", + "name", + b"name", + "research_time", + b"research_time", + "upgrade_id", + b"upgrade_id", + "vespene_cost", + b"vespene_cost", + ], + ) -> None: ... + +global___UpgradeData = UpgradeData + +@typing.final +class BuffData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BUFF_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + buff_id: builtins.int + """Stable ID.""" + name: builtins.str + def __init__(self, *, buff_id: builtins.int | None = ..., name: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["buff_id", b"buff_id", "name", b"name"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["buff_id", b"buff_id", "name", b"name"]) -> None: ... + +global___BuffData = BuffData + +@typing.final +class EffectData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EFFECT_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + FRIENDLY_NAME_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + effect_id: builtins.int + """Stable ID.""" + name: builtins.str + friendly_name: builtins.str + radius: builtins.float + def __init__( + self, + *, + effect_id: builtins.int | None = ..., + name: builtins.str | None = ..., + friendly_name: builtins.str | None = ..., + radius: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "effect_id", b"effect_id", "friendly_name", b"friendly_name", "name", b"name", "radius", b"radius" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "effect_id", b"effect_id", "friendly_name", b"friendly_name", "name", b"name", "radius", b"radius" + ], + ) -> None: ... + +global___EffectData = EffectData diff --git a/stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi new file mode 100644 index 000000000000..eba2ae972064 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi @@ -0,0 +1,501 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _DebugGameState: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DebugGameStateEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_DebugGameState.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + show_map: _DebugGameState.ValueType # 1 + control_enemy: _DebugGameState.ValueType # 2 + food: _DebugGameState.ValueType # 3 + free: _DebugGameState.ValueType # 4 + all_resources: _DebugGameState.ValueType # 5 + god: _DebugGameState.ValueType # 6 + minerals: _DebugGameState.ValueType # 7 + gas: _DebugGameState.ValueType # 8 + cooldown: _DebugGameState.ValueType # 9 + tech_tree: _DebugGameState.ValueType # 10 + upgrade: _DebugGameState.ValueType # 11 + fast_build: _DebugGameState.ValueType # 12 + +class DebugGameState(_DebugGameState, metaclass=_DebugGameStateEnumTypeWrapper): ... + +show_map: DebugGameState.ValueType # 1 +control_enemy: DebugGameState.ValueType # 2 +food: DebugGameState.ValueType # 3 +free: DebugGameState.ValueType # 4 +all_resources: DebugGameState.ValueType # 5 +god: DebugGameState.ValueType # 6 +minerals: DebugGameState.ValueType # 7 +gas: DebugGameState.ValueType # 8 +cooldown: DebugGameState.ValueType # 9 +tech_tree: DebugGameState.ValueType # 10 +upgrade: DebugGameState.ValueType # 11 +fast_build: DebugGameState.ValueType # 12 +global___DebugGameState = DebugGameState + +@typing.final +class DebugCommand(google.protobuf.message.Message): + """Issue various useful commands to the game engine.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DRAW_FIELD_NUMBER: builtins.int + GAME_STATE_FIELD_NUMBER: builtins.int + CREATE_UNIT_FIELD_NUMBER: builtins.int + KILL_UNIT_FIELD_NUMBER: builtins.int + TEST_PROCESS_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + END_GAME_FIELD_NUMBER: builtins.int + UNIT_VALUE_FIELD_NUMBER: builtins.int + game_state: global___DebugGameState.ValueType + @property + def draw(self) -> global___DebugDraw: ... + @property + def create_unit(self) -> global___DebugCreateUnit: ... + @property + def kill_unit(self) -> global___DebugKillUnit: ... + @property + def test_process(self) -> global___DebugTestProcess: ... + @property + def score(self) -> global___DebugSetScore: + """Useful only for single-player "curriculum" maps.""" + + @property + def end_game(self) -> global___DebugEndGame: ... + @property + def unit_value(self) -> global___DebugSetUnitValue: ... + def __init__( + self, + *, + draw: global___DebugDraw | None = ..., + game_state: global___DebugGameState.ValueType | None = ..., + create_unit: global___DebugCreateUnit | None = ..., + kill_unit: global___DebugKillUnit | None = ..., + test_process: global___DebugTestProcess | None = ..., + score: global___DebugSetScore | None = ..., + end_game: global___DebugEndGame | None = ..., + unit_value: global___DebugSetUnitValue | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "command", + b"command", + "create_unit", + b"create_unit", + "draw", + b"draw", + "end_game", + b"end_game", + "game_state", + b"game_state", + "kill_unit", + b"kill_unit", + "score", + b"score", + "test_process", + b"test_process", + "unit_value", + b"unit_value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "command", + b"command", + "create_unit", + b"create_unit", + "draw", + b"draw", + "end_game", + b"end_game", + "game_state", + b"game_state", + "kill_unit", + b"kill_unit", + "score", + b"score", + "test_process", + b"test_process", + "unit_value", + b"unit_value", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["command", b"command"] + ) -> ( + typing.Literal["draw", "game_state", "create_unit", "kill_unit", "test_process", "score", "end_game", "unit_value"] | None + ): ... + +global___DebugCommand = DebugCommand + +@typing.final +class DebugDraw(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TEXT_FIELD_NUMBER: builtins.int + LINES_FIELD_NUMBER: builtins.int + BOXES_FIELD_NUMBER: builtins.int + SPHERES_FIELD_NUMBER: builtins.int + @property + def text(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugText]: ... + @property + def lines(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugLine]: ... + @property + def boxes(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugBox]: ... + @property + def spheres(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugSphere]: ... + def __init__( + self, + *, + text: collections.abc.Iterable[global___DebugText] | None = ..., + lines: collections.abc.Iterable[global___DebugLine] | None = ..., + boxes: collections.abc.Iterable[global___DebugBox] | None = ..., + spheres: collections.abc.Iterable[global___DebugSphere] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["boxes", b"boxes", "lines", b"lines", "spheres", b"spheres", "text", b"text"] + ) -> None: ... + +global___DebugDraw = DebugDraw + +@typing.final +class Line(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + P0_FIELD_NUMBER: builtins.int + P1_FIELD_NUMBER: builtins.int + @property + def p0(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def p1(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, *, p0: s2clientprotocol.common_pb2.Point | None = ..., p1: s2clientprotocol.common_pb2.Point | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> None: ... + +global___Line = Line + +@typing.final +class Color(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + R_FIELD_NUMBER: builtins.int + G_FIELD_NUMBER: builtins.int + B_FIELD_NUMBER: builtins.int + r: builtins.int + g: builtins.int + b: builtins.int + def __init__(self, *, r: builtins.int | None = ..., g: builtins.int | None = ..., b: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["b", b"b", "g", b"g", "r", b"r"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["b", b"b", "g", b"g", "r", b"r"]) -> None: ... + +global___Color = Color + +@typing.final +class DebugText(google.protobuf.message.Message): + """Display debug text on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + TEXT_FIELD_NUMBER: builtins.int + VIRTUAL_POS_FIELD_NUMBER: builtins.int + WORLD_POS_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + text: builtins.str + """Text to display.""" + size: builtins.int + """Pixel height of the text. Defaults to 8px.""" + @property + def color(self) -> global___Color: ... + @property + def virtual_pos(self) -> s2clientprotocol.common_pb2.Point: + """Virtualized position in 2D (the screen is 0..1, 0..1 for any resolution).""" + + @property + def world_pos(self) -> s2clientprotocol.common_pb2.Point: + """Position in the world.""" + + def __init__( + self, + *, + color: global___Color | None = ..., + text: builtins.str | None = ..., + virtual_pos: s2clientprotocol.common_pb2.Point | None = ..., + world_pos: s2clientprotocol.common_pb2.Point | None = ..., + size: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "color", b"color", "size", b"size", "text", b"text", "virtual_pos", b"virtual_pos", "world_pos", b"world_pos" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "color", b"color", "size", b"size", "text", b"text", "virtual_pos", b"virtual_pos", "world_pos", b"world_pos" + ], + ) -> None: ... + +global___DebugText = DebugText + +@typing.final +class DebugLine(google.protobuf.message.Message): + """Display debug lines on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + LINE_FIELD_NUMBER: builtins.int + @property + def color(self) -> global___Color: ... + @property + def line(self) -> global___Line: + """World space line.""" + + def __init__(self, *, color: global___Color | None = ..., line: global___Line | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["color", b"color", "line", b"line"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["color", b"color", "line", b"line"]) -> None: ... + +global___DebugLine = DebugLine + +@typing.final +class DebugBox(google.protobuf.message.Message): + """Display debug boxes on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + MIN_FIELD_NUMBER: builtins.int + MAX_FIELD_NUMBER: builtins.int + @property + def color(self) -> global___Color: ... + @property + def min(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def max(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + color: global___Color | None = ..., + min: s2clientprotocol.common_pb2.Point | None = ..., + max: s2clientprotocol.common_pb2.Point | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["color", b"color", "max", b"max", "min", b"min"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["color", b"color", "max", b"max", "min", b"min"]) -> None: ... + +global___DebugBox = DebugBox + +@typing.final +class DebugSphere(google.protobuf.message.Message): + """Display debug spheres on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + P_FIELD_NUMBER: builtins.int + R_FIELD_NUMBER: builtins.int + r: builtins.float + @property + def color(self) -> global___Color: ... + @property + def p(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + color: global___Color | None = ..., + p: s2clientprotocol.common_pb2.Point | None = ..., + r: builtins.float | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["color", b"color", "p", b"p", "r", b"r"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["color", b"color", "p", b"p", "r", b"r"]) -> None: ... + +global___DebugSphere = DebugSphere + +@typing.final +class DebugCreateUnit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TYPE_FIELD_NUMBER: builtins.int + OWNER_FIELD_NUMBER: builtins.int + POS_FIELD_NUMBER: builtins.int + QUANTITY_FIELD_NUMBER: builtins.int + unit_type: builtins.int + owner: builtins.int + quantity: builtins.int + @property + def pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, + *, + unit_type: builtins.int | None = ..., + owner: builtins.int | None = ..., + pos: s2clientprotocol.common_pb2.Point2D | None = ..., + quantity: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["owner", b"owner", "pos", b"pos", "quantity", b"quantity", "unit_type", b"unit_type"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["owner", b"owner", "pos", b"pos", "quantity", b"quantity", "unit_type", b"unit_type"] + ) -> None: ... + +global___DebugCreateUnit = DebugCreateUnit + +@typing.final +class DebugKillUnit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TAG_FIELD_NUMBER: builtins.int + @property + def tag(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, tag: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["tag", b"tag"]) -> None: ... + +global___DebugKillUnit = DebugKillUnit + +@typing.final +class DebugTestProcess(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Test: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TestEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugTestProcess._Test.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + hang: DebugTestProcess._Test.ValueType # 1 + crash: DebugTestProcess._Test.ValueType # 2 + exit: DebugTestProcess._Test.ValueType # 3 + + class Test(_Test, metaclass=_TestEnumTypeWrapper): ... + hang: DebugTestProcess.Test.ValueType # 1 + crash: DebugTestProcess.Test.ValueType # 2 + exit: DebugTestProcess.Test.ValueType # 3 + + TEST_FIELD_NUMBER: builtins.int + DELAY_MS_FIELD_NUMBER: builtins.int + test: global___DebugTestProcess.Test.ValueType + delay_ms: builtins.int + def __init__( + self, *, test: global___DebugTestProcess.Test.ValueType | None = ..., delay_ms: builtins.int | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["delay_ms", b"delay_ms", "test", b"test"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["delay_ms", b"delay_ms", "test", b"test"]) -> None: ... + +global___DebugTestProcess = DebugTestProcess + +@typing.final +class DebugSetScore(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SCORE_FIELD_NUMBER: builtins.int + score: builtins.float + def __init__(self, *, score: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["score", b"score"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["score", b"score"]) -> None: ... + +global___DebugSetScore = DebugSetScore + +@typing.final +class DebugEndGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _EndResult: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _EndResultEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugEndGame._EndResult.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Surrender: DebugEndGame._EndResult.ValueType # 1 + """Default if nothing is set. The current player admits defeat.""" + DeclareVictory: DebugEndGame._EndResult.ValueType # 2 + + class EndResult(_EndResult, metaclass=_EndResultEnumTypeWrapper): ... + Surrender: DebugEndGame.EndResult.ValueType # 1 + """Default if nothing is set. The current player admits defeat.""" + DeclareVictory: DebugEndGame.EndResult.ValueType # 2 + + END_RESULT_FIELD_NUMBER: builtins.int + end_result: global___DebugEndGame.EndResult.ValueType + def __init__(self, *, end_result: global___DebugEndGame.EndResult.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["end_result", b"end_result"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end_result", b"end_result"]) -> None: ... + +global___DebugEndGame = DebugEndGame + +@typing.final +class DebugSetUnitValue(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _UnitValue: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _UnitValueEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugSetUnitValue._UnitValue.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Energy: DebugSetUnitValue._UnitValue.ValueType # 1 + Life: DebugSetUnitValue._UnitValue.ValueType # 2 + Shields: DebugSetUnitValue._UnitValue.ValueType # 3 + + class UnitValue(_UnitValue, metaclass=_UnitValueEnumTypeWrapper): ... + Energy: DebugSetUnitValue.UnitValue.ValueType # 1 + Life: DebugSetUnitValue.UnitValue.ValueType # 2 + Shields: DebugSetUnitValue.UnitValue.ValueType # 3 + + UNIT_VALUE_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + UNIT_TAG_FIELD_NUMBER: builtins.int + unit_value: global___DebugSetUnitValue.UnitValue.ValueType + value: builtins.float + unit_tag: builtins.int + def __init__( + self, + *, + unit_value: global___DebugSetUnitValue.UnitValue.ValueType | None = ..., + value: builtins.float | None = ..., + unit_tag: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["unit_tag", b"unit_tag", "unit_value", b"unit_value", "value", b"value"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["unit_tag", b"unit_tag", "unit_value", b"unit_value", "value", b"value"] + ) -> None: ... + +global___DebugSetUnitValue = DebugSetUnitValue diff --git a/stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi new file mode 100644 index 000000000000..5c14aaba748c --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi @@ -0,0 +1,459 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _ActionResult: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ActionResultEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ActionResult.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Success: _ActionResult.ValueType # 1 + NotSupported: _ActionResult.ValueType # 2 + Error: _ActionResult.ValueType # 3 + CantQueueThatOrder: _ActionResult.ValueType # 4 + Retry: _ActionResult.ValueType # 5 + Cooldown: _ActionResult.ValueType # 6 + QueueIsFull: _ActionResult.ValueType # 7 + RallyQueueIsFull: _ActionResult.ValueType # 8 + NotEnoughMinerals: _ActionResult.ValueType # 9 + NotEnoughVespene: _ActionResult.ValueType # 10 + NotEnoughTerrazine: _ActionResult.ValueType # 11 + NotEnoughCustom: _ActionResult.ValueType # 12 + NotEnoughFood: _ActionResult.ValueType # 13 + FoodUsageImpossible: _ActionResult.ValueType # 14 + NotEnoughLife: _ActionResult.ValueType # 15 + NotEnoughShields: _ActionResult.ValueType # 16 + NotEnoughEnergy: _ActionResult.ValueType # 17 + LifeSuppressed: _ActionResult.ValueType # 18 + ShieldsSuppressed: _ActionResult.ValueType # 19 + EnergySuppressed: _ActionResult.ValueType # 20 + NotEnoughCharges: _ActionResult.ValueType # 21 + CantAddMoreCharges: _ActionResult.ValueType # 22 + TooMuchMinerals: _ActionResult.ValueType # 23 + TooMuchVespene: _ActionResult.ValueType # 24 + TooMuchTerrazine: _ActionResult.ValueType # 25 + TooMuchCustom: _ActionResult.ValueType # 26 + TooMuchFood: _ActionResult.ValueType # 27 + TooMuchLife: _ActionResult.ValueType # 28 + TooMuchShields: _ActionResult.ValueType # 29 + TooMuchEnergy: _ActionResult.ValueType # 30 + MustTargetUnitWithLife: _ActionResult.ValueType # 31 + MustTargetUnitWithShields: _ActionResult.ValueType # 32 + MustTargetUnitWithEnergy: _ActionResult.ValueType # 33 + CantTrade: _ActionResult.ValueType # 34 + CantSpend: _ActionResult.ValueType # 35 + CantTargetThatUnit: _ActionResult.ValueType # 36 + CouldntAllocateUnit: _ActionResult.ValueType # 37 + UnitCantMove: _ActionResult.ValueType # 38 + TransportIsHoldingPosition: _ActionResult.ValueType # 39 + BuildTechRequirementsNotMet: _ActionResult.ValueType # 40 + CantFindPlacementLocation: _ActionResult.ValueType # 41 + CantBuildOnThat: _ActionResult.ValueType # 42 + CantBuildTooCloseToDropOff: _ActionResult.ValueType # 43 + CantBuildLocationInvalid: _ActionResult.ValueType # 44 + CantSeeBuildLocation: _ActionResult.ValueType # 45 + CantBuildTooCloseToCreepSource: _ActionResult.ValueType # 46 + CantBuildTooCloseToResources: _ActionResult.ValueType # 47 + CantBuildTooFarFromWater: _ActionResult.ValueType # 48 + CantBuildTooFarFromCreepSource: _ActionResult.ValueType # 49 + CantBuildTooFarFromBuildPowerSource: _ActionResult.ValueType # 50 + CantBuildOnDenseTerrain: _ActionResult.ValueType # 51 + CantTrainTooFarFromTrainPowerSource: _ActionResult.ValueType # 52 + CantLandLocationInvalid: _ActionResult.ValueType # 53 + CantSeeLandLocation: _ActionResult.ValueType # 54 + CantLandTooCloseToCreepSource: _ActionResult.ValueType # 55 + CantLandTooCloseToResources: _ActionResult.ValueType # 56 + CantLandTooFarFromWater: _ActionResult.ValueType # 57 + CantLandTooFarFromCreepSource: _ActionResult.ValueType # 58 + CantLandTooFarFromBuildPowerSource: _ActionResult.ValueType # 59 + CantLandTooFarFromTrainPowerSource: _ActionResult.ValueType # 60 + CantLandOnDenseTerrain: _ActionResult.ValueType # 61 + AddOnTooFarFromBuilding: _ActionResult.ValueType # 62 + MustBuildRefineryFirst: _ActionResult.ValueType # 63 + BuildingIsUnderConstruction: _ActionResult.ValueType # 64 + CantFindDropOff: _ActionResult.ValueType # 65 + CantLoadOtherPlayersUnits: _ActionResult.ValueType # 66 + NotEnoughRoomToLoadUnit: _ActionResult.ValueType # 67 + CantUnloadUnitsThere: _ActionResult.ValueType # 68 + CantWarpInUnitsThere: _ActionResult.ValueType # 69 + CantLoadImmobileUnits: _ActionResult.ValueType # 70 + CantRechargeImmobileUnits: _ActionResult.ValueType # 71 + CantRechargeUnderConstructionUnits: _ActionResult.ValueType # 72 + CantLoadThatUnit: _ActionResult.ValueType # 73 + NoCargoToUnload: _ActionResult.ValueType # 74 + LoadAllNoTargetsFound: _ActionResult.ValueType # 75 + NotWhileOccupied: _ActionResult.ValueType # 76 + CantAttackWithoutAmmo: _ActionResult.ValueType # 77 + CantHoldAnyMoreAmmo: _ActionResult.ValueType # 78 + TechRequirementsNotMet: _ActionResult.ValueType # 79 + MustLockdownUnitFirst: _ActionResult.ValueType # 80 + MustTargetUnit: _ActionResult.ValueType # 81 + MustTargetInventory: _ActionResult.ValueType # 82 + MustTargetVisibleUnit: _ActionResult.ValueType # 83 + MustTargetVisibleLocation: _ActionResult.ValueType # 84 + MustTargetWalkableLocation: _ActionResult.ValueType # 85 + MustTargetPawnableUnit: _ActionResult.ValueType # 86 + YouCantControlThatUnit: _ActionResult.ValueType # 87 + YouCantIssueCommandsToThatUnit: _ActionResult.ValueType # 88 + MustTargetResources: _ActionResult.ValueType # 89 + RequiresHealTarget: _ActionResult.ValueType # 90 + RequiresRepairTarget: _ActionResult.ValueType # 91 + NoItemsToDrop: _ActionResult.ValueType # 92 + CantHoldAnyMoreItems: _ActionResult.ValueType # 93 + CantHoldThat: _ActionResult.ValueType # 94 + TargetHasNoInventory: _ActionResult.ValueType # 95 + CantDropThisItem: _ActionResult.ValueType # 96 + CantMoveThisItem: _ActionResult.ValueType # 97 + CantPawnThisUnit: _ActionResult.ValueType # 98 + MustTargetCaster: _ActionResult.ValueType # 99 + CantTargetCaster: _ActionResult.ValueType # 100 + MustTargetOuter: _ActionResult.ValueType # 101 + CantTargetOuter: _ActionResult.ValueType # 102 + MustTargetYourOwnUnits: _ActionResult.ValueType # 103 + CantTargetYourOwnUnits: _ActionResult.ValueType # 104 + MustTargetFriendlyUnits: _ActionResult.ValueType # 105 + CantTargetFriendlyUnits: _ActionResult.ValueType # 106 + MustTargetNeutralUnits: _ActionResult.ValueType # 107 + CantTargetNeutralUnits: _ActionResult.ValueType # 108 + MustTargetEnemyUnits: _ActionResult.ValueType # 109 + CantTargetEnemyUnits: _ActionResult.ValueType # 110 + MustTargetAirUnits: _ActionResult.ValueType # 111 + CantTargetAirUnits: _ActionResult.ValueType # 112 + MustTargetGroundUnits: _ActionResult.ValueType # 113 + CantTargetGroundUnits: _ActionResult.ValueType # 114 + MustTargetStructures: _ActionResult.ValueType # 115 + CantTargetStructures: _ActionResult.ValueType # 116 + MustTargetLightUnits: _ActionResult.ValueType # 117 + CantTargetLightUnits: _ActionResult.ValueType # 118 + MustTargetArmoredUnits: _ActionResult.ValueType # 119 + CantTargetArmoredUnits: _ActionResult.ValueType # 120 + MustTargetBiologicalUnits: _ActionResult.ValueType # 121 + CantTargetBiologicalUnits: _ActionResult.ValueType # 122 + MustTargetHeroicUnits: _ActionResult.ValueType # 123 + CantTargetHeroicUnits: _ActionResult.ValueType # 124 + MustTargetRoboticUnits: _ActionResult.ValueType # 125 + CantTargetRoboticUnits: _ActionResult.ValueType # 126 + MustTargetMechanicalUnits: _ActionResult.ValueType # 127 + CantTargetMechanicalUnits: _ActionResult.ValueType # 128 + MustTargetPsionicUnits: _ActionResult.ValueType # 129 + CantTargetPsionicUnits: _ActionResult.ValueType # 130 + MustTargetMassiveUnits: _ActionResult.ValueType # 131 + CantTargetMassiveUnits: _ActionResult.ValueType # 132 + MustTargetMissile: _ActionResult.ValueType # 133 + CantTargetMissile: _ActionResult.ValueType # 134 + MustTargetWorkerUnits: _ActionResult.ValueType # 135 + CantTargetWorkerUnits: _ActionResult.ValueType # 136 + MustTargetEnergyCapableUnits: _ActionResult.ValueType # 137 + CantTargetEnergyCapableUnits: _ActionResult.ValueType # 138 + MustTargetShieldCapableUnits: _ActionResult.ValueType # 139 + CantTargetShieldCapableUnits: _ActionResult.ValueType # 140 + MustTargetFlyers: _ActionResult.ValueType # 141 + CantTargetFlyers: _ActionResult.ValueType # 142 + MustTargetBuriedUnits: _ActionResult.ValueType # 143 + CantTargetBuriedUnits: _ActionResult.ValueType # 144 + MustTargetCloakedUnits: _ActionResult.ValueType # 145 + CantTargetCloakedUnits: _ActionResult.ValueType # 146 + MustTargetUnitsInAStasisField: _ActionResult.ValueType # 147 + CantTargetUnitsInAStasisField: _ActionResult.ValueType # 148 + MustTargetUnderConstructionUnits: _ActionResult.ValueType # 149 + CantTargetUnderConstructionUnits: _ActionResult.ValueType # 150 + MustTargetDeadUnits: _ActionResult.ValueType # 151 + CantTargetDeadUnits: _ActionResult.ValueType # 152 + MustTargetRevivableUnits: _ActionResult.ValueType # 153 + CantTargetRevivableUnits: _ActionResult.ValueType # 154 + MustTargetHiddenUnits: _ActionResult.ValueType # 155 + CantTargetHiddenUnits: _ActionResult.ValueType # 156 + CantRechargeOtherPlayersUnits: _ActionResult.ValueType # 157 + MustTargetHallucinations: _ActionResult.ValueType # 158 + CantTargetHallucinations: _ActionResult.ValueType # 159 + MustTargetInvulnerableUnits: _ActionResult.ValueType # 160 + CantTargetInvulnerableUnits: _ActionResult.ValueType # 161 + MustTargetDetectedUnits: _ActionResult.ValueType # 162 + CantTargetDetectedUnits: _ActionResult.ValueType # 163 + CantTargetUnitWithEnergy: _ActionResult.ValueType # 164 + CantTargetUnitWithShields: _ActionResult.ValueType # 165 + MustTargetUncommandableUnits: _ActionResult.ValueType # 166 + CantTargetUncommandableUnits: _ActionResult.ValueType # 167 + MustTargetPreventDefeatUnits: _ActionResult.ValueType # 168 + CantTargetPreventDefeatUnits: _ActionResult.ValueType # 169 + MustTargetPreventRevealUnits: _ActionResult.ValueType # 170 + CantTargetPreventRevealUnits: _ActionResult.ValueType # 171 + MustTargetPassiveUnits: _ActionResult.ValueType # 172 + CantTargetPassiveUnits: _ActionResult.ValueType # 173 + MustTargetStunnedUnits: _ActionResult.ValueType # 174 + CantTargetStunnedUnits: _ActionResult.ValueType # 175 + MustTargetSummonedUnits: _ActionResult.ValueType # 176 + CantTargetSummonedUnits: _ActionResult.ValueType # 177 + MustTargetUser1: _ActionResult.ValueType # 178 + CantTargetUser1: _ActionResult.ValueType # 179 + MustTargetUnstoppableUnits: _ActionResult.ValueType # 180 + CantTargetUnstoppableUnits: _ActionResult.ValueType # 181 + MustTargetResistantUnits: _ActionResult.ValueType # 182 + CantTargetResistantUnits: _ActionResult.ValueType # 183 + MustTargetDazedUnits: _ActionResult.ValueType # 184 + CantTargetDazedUnits: _ActionResult.ValueType # 185 + CantLockdown: _ActionResult.ValueType # 186 + CantMindControl: _ActionResult.ValueType # 187 + MustTargetDestructibles: _ActionResult.ValueType # 188 + CantTargetDestructibles: _ActionResult.ValueType # 189 + MustTargetItems: _ActionResult.ValueType # 190 + CantTargetItems: _ActionResult.ValueType # 191 + NoCalldownAvailable: _ActionResult.ValueType # 192 + WaypointListFull: _ActionResult.ValueType # 193 + MustTargetRace: _ActionResult.ValueType # 194 + CantTargetRace: _ActionResult.ValueType # 195 + MustTargetSimilarUnits: _ActionResult.ValueType # 196 + CantTargetSimilarUnits: _ActionResult.ValueType # 197 + CantFindEnoughTargets: _ActionResult.ValueType # 198 + AlreadySpawningLarva: _ActionResult.ValueType # 199 + CantTargetExhaustedResources: _ActionResult.ValueType # 200 + CantUseMinimap: _ActionResult.ValueType # 201 + CantUseInfoPanel: _ActionResult.ValueType # 202 + OrderQueueIsFull: _ActionResult.ValueType # 203 + CantHarvestThatResource: _ActionResult.ValueType # 204 + HarvestersNotRequired: _ActionResult.ValueType # 205 + AlreadyTargeted: _ActionResult.ValueType # 206 + CantAttackWeaponsDisabled: _ActionResult.ValueType # 207 + CouldntReachTarget: _ActionResult.ValueType # 208 + TargetIsOutOfRange: _ActionResult.ValueType # 209 + TargetIsTooClose: _ActionResult.ValueType # 210 + TargetIsOutOfArc: _ActionResult.ValueType # 211 + CantFindTeleportLocation: _ActionResult.ValueType # 212 + InvalidItemClass: _ActionResult.ValueType # 213 + CantFindCancelOrder: _ActionResult.ValueType # 214 + +class ActionResult(_ActionResult, metaclass=_ActionResultEnumTypeWrapper): ... + +Success: ActionResult.ValueType # 1 +NotSupported: ActionResult.ValueType # 2 +Error: ActionResult.ValueType # 3 +CantQueueThatOrder: ActionResult.ValueType # 4 +Retry: ActionResult.ValueType # 5 +Cooldown: ActionResult.ValueType # 6 +QueueIsFull: ActionResult.ValueType # 7 +RallyQueueIsFull: ActionResult.ValueType # 8 +NotEnoughMinerals: ActionResult.ValueType # 9 +NotEnoughVespene: ActionResult.ValueType # 10 +NotEnoughTerrazine: ActionResult.ValueType # 11 +NotEnoughCustom: ActionResult.ValueType # 12 +NotEnoughFood: ActionResult.ValueType # 13 +FoodUsageImpossible: ActionResult.ValueType # 14 +NotEnoughLife: ActionResult.ValueType # 15 +NotEnoughShields: ActionResult.ValueType # 16 +NotEnoughEnergy: ActionResult.ValueType # 17 +LifeSuppressed: ActionResult.ValueType # 18 +ShieldsSuppressed: ActionResult.ValueType # 19 +EnergySuppressed: ActionResult.ValueType # 20 +NotEnoughCharges: ActionResult.ValueType # 21 +CantAddMoreCharges: ActionResult.ValueType # 22 +TooMuchMinerals: ActionResult.ValueType # 23 +TooMuchVespene: ActionResult.ValueType # 24 +TooMuchTerrazine: ActionResult.ValueType # 25 +TooMuchCustom: ActionResult.ValueType # 26 +TooMuchFood: ActionResult.ValueType # 27 +TooMuchLife: ActionResult.ValueType # 28 +TooMuchShields: ActionResult.ValueType # 29 +TooMuchEnergy: ActionResult.ValueType # 30 +MustTargetUnitWithLife: ActionResult.ValueType # 31 +MustTargetUnitWithShields: ActionResult.ValueType # 32 +MustTargetUnitWithEnergy: ActionResult.ValueType # 33 +CantTrade: ActionResult.ValueType # 34 +CantSpend: ActionResult.ValueType # 35 +CantTargetThatUnit: ActionResult.ValueType # 36 +CouldntAllocateUnit: ActionResult.ValueType # 37 +UnitCantMove: ActionResult.ValueType # 38 +TransportIsHoldingPosition: ActionResult.ValueType # 39 +BuildTechRequirementsNotMet: ActionResult.ValueType # 40 +CantFindPlacementLocation: ActionResult.ValueType # 41 +CantBuildOnThat: ActionResult.ValueType # 42 +CantBuildTooCloseToDropOff: ActionResult.ValueType # 43 +CantBuildLocationInvalid: ActionResult.ValueType # 44 +CantSeeBuildLocation: ActionResult.ValueType # 45 +CantBuildTooCloseToCreepSource: ActionResult.ValueType # 46 +CantBuildTooCloseToResources: ActionResult.ValueType # 47 +CantBuildTooFarFromWater: ActionResult.ValueType # 48 +CantBuildTooFarFromCreepSource: ActionResult.ValueType # 49 +CantBuildTooFarFromBuildPowerSource: ActionResult.ValueType # 50 +CantBuildOnDenseTerrain: ActionResult.ValueType # 51 +CantTrainTooFarFromTrainPowerSource: ActionResult.ValueType # 52 +CantLandLocationInvalid: ActionResult.ValueType # 53 +CantSeeLandLocation: ActionResult.ValueType # 54 +CantLandTooCloseToCreepSource: ActionResult.ValueType # 55 +CantLandTooCloseToResources: ActionResult.ValueType # 56 +CantLandTooFarFromWater: ActionResult.ValueType # 57 +CantLandTooFarFromCreepSource: ActionResult.ValueType # 58 +CantLandTooFarFromBuildPowerSource: ActionResult.ValueType # 59 +CantLandTooFarFromTrainPowerSource: ActionResult.ValueType # 60 +CantLandOnDenseTerrain: ActionResult.ValueType # 61 +AddOnTooFarFromBuilding: ActionResult.ValueType # 62 +MustBuildRefineryFirst: ActionResult.ValueType # 63 +BuildingIsUnderConstruction: ActionResult.ValueType # 64 +CantFindDropOff: ActionResult.ValueType # 65 +CantLoadOtherPlayersUnits: ActionResult.ValueType # 66 +NotEnoughRoomToLoadUnit: ActionResult.ValueType # 67 +CantUnloadUnitsThere: ActionResult.ValueType # 68 +CantWarpInUnitsThere: ActionResult.ValueType # 69 +CantLoadImmobileUnits: ActionResult.ValueType # 70 +CantRechargeImmobileUnits: ActionResult.ValueType # 71 +CantRechargeUnderConstructionUnits: ActionResult.ValueType # 72 +CantLoadThatUnit: ActionResult.ValueType # 73 +NoCargoToUnload: ActionResult.ValueType # 74 +LoadAllNoTargetsFound: ActionResult.ValueType # 75 +NotWhileOccupied: ActionResult.ValueType # 76 +CantAttackWithoutAmmo: ActionResult.ValueType # 77 +CantHoldAnyMoreAmmo: ActionResult.ValueType # 78 +TechRequirementsNotMet: ActionResult.ValueType # 79 +MustLockdownUnitFirst: ActionResult.ValueType # 80 +MustTargetUnit: ActionResult.ValueType # 81 +MustTargetInventory: ActionResult.ValueType # 82 +MustTargetVisibleUnit: ActionResult.ValueType # 83 +MustTargetVisibleLocation: ActionResult.ValueType # 84 +MustTargetWalkableLocation: ActionResult.ValueType # 85 +MustTargetPawnableUnit: ActionResult.ValueType # 86 +YouCantControlThatUnit: ActionResult.ValueType # 87 +YouCantIssueCommandsToThatUnit: ActionResult.ValueType # 88 +MustTargetResources: ActionResult.ValueType # 89 +RequiresHealTarget: ActionResult.ValueType # 90 +RequiresRepairTarget: ActionResult.ValueType # 91 +NoItemsToDrop: ActionResult.ValueType # 92 +CantHoldAnyMoreItems: ActionResult.ValueType # 93 +CantHoldThat: ActionResult.ValueType # 94 +TargetHasNoInventory: ActionResult.ValueType # 95 +CantDropThisItem: ActionResult.ValueType # 96 +CantMoveThisItem: ActionResult.ValueType # 97 +CantPawnThisUnit: ActionResult.ValueType # 98 +MustTargetCaster: ActionResult.ValueType # 99 +CantTargetCaster: ActionResult.ValueType # 100 +MustTargetOuter: ActionResult.ValueType # 101 +CantTargetOuter: ActionResult.ValueType # 102 +MustTargetYourOwnUnits: ActionResult.ValueType # 103 +CantTargetYourOwnUnits: ActionResult.ValueType # 104 +MustTargetFriendlyUnits: ActionResult.ValueType # 105 +CantTargetFriendlyUnits: ActionResult.ValueType # 106 +MustTargetNeutralUnits: ActionResult.ValueType # 107 +CantTargetNeutralUnits: ActionResult.ValueType # 108 +MustTargetEnemyUnits: ActionResult.ValueType # 109 +CantTargetEnemyUnits: ActionResult.ValueType # 110 +MustTargetAirUnits: ActionResult.ValueType # 111 +CantTargetAirUnits: ActionResult.ValueType # 112 +MustTargetGroundUnits: ActionResult.ValueType # 113 +CantTargetGroundUnits: ActionResult.ValueType # 114 +MustTargetStructures: ActionResult.ValueType # 115 +CantTargetStructures: ActionResult.ValueType # 116 +MustTargetLightUnits: ActionResult.ValueType # 117 +CantTargetLightUnits: ActionResult.ValueType # 118 +MustTargetArmoredUnits: ActionResult.ValueType # 119 +CantTargetArmoredUnits: ActionResult.ValueType # 120 +MustTargetBiologicalUnits: ActionResult.ValueType # 121 +CantTargetBiologicalUnits: ActionResult.ValueType # 122 +MustTargetHeroicUnits: ActionResult.ValueType # 123 +CantTargetHeroicUnits: ActionResult.ValueType # 124 +MustTargetRoboticUnits: ActionResult.ValueType # 125 +CantTargetRoboticUnits: ActionResult.ValueType # 126 +MustTargetMechanicalUnits: ActionResult.ValueType # 127 +CantTargetMechanicalUnits: ActionResult.ValueType # 128 +MustTargetPsionicUnits: ActionResult.ValueType # 129 +CantTargetPsionicUnits: ActionResult.ValueType # 130 +MustTargetMassiveUnits: ActionResult.ValueType # 131 +CantTargetMassiveUnits: ActionResult.ValueType # 132 +MustTargetMissile: ActionResult.ValueType # 133 +CantTargetMissile: ActionResult.ValueType # 134 +MustTargetWorkerUnits: ActionResult.ValueType # 135 +CantTargetWorkerUnits: ActionResult.ValueType # 136 +MustTargetEnergyCapableUnits: ActionResult.ValueType # 137 +CantTargetEnergyCapableUnits: ActionResult.ValueType # 138 +MustTargetShieldCapableUnits: ActionResult.ValueType # 139 +CantTargetShieldCapableUnits: ActionResult.ValueType # 140 +MustTargetFlyers: ActionResult.ValueType # 141 +CantTargetFlyers: ActionResult.ValueType # 142 +MustTargetBuriedUnits: ActionResult.ValueType # 143 +CantTargetBuriedUnits: ActionResult.ValueType # 144 +MustTargetCloakedUnits: ActionResult.ValueType # 145 +CantTargetCloakedUnits: ActionResult.ValueType # 146 +MustTargetUnitsInAStasisField: ActionResult.ValueType # 147 +CantTargetUnitsInAStasisField: ActionResult.ValueType # 148 +MustTargetUnderConstructionUnits: ActionResult.ValueType # 149 +CantTargetUnderConstructionUnits: ActionResult.ValueType # 150 +MustTargetDeadUnits: ActionResult.ValueType # 151 +CantTargetDeadUnits: ActionResult.ValueType # 152 +MustTargetRevivableUnits: ActionResult.ValueType # 153 +CantTargetRevivableUnits: ActionResult.ValueType # 154 +MustTargetHiddenUnits: ActionResult.ValueType # 155 +CantTargetHiddenUnits: ActionResult.ValueType # 156 +CantRechargeOtherPlayersUnits: ActionResult.ValueType # 157 +MustTargetHallucinations: ActionResult.ValueType # 158 +CantTargetHallucinations: ActionResult.ValueType # 159 +MustTargetInvulnerableUnits: ActionResult.ValueType # 160 +CantTargetInvulnerableUnits: ActionResult.ValueType # 161 +MustTargetDetectedUnits: ActionResult.ValueType # 162 +CantTargetDetectedUnits: ActionResult.ValueType # 163 +CantTargetUnitWithEnergy: ActionResult.ValueType # 164 +CantTargetUnitWithShields: ActionResult.ValueType # 165 +MustTargetUncommandableUnits: ActionResult.ValueType # 166 +CantTargetUncommandableUnits: ActionResult.ValueType # 167 +MustTargetPreventDefeatUnits: ActionResult.ValueType # 168 +CantTargetPreventDefeatUnits: ActionResult.ValueType # 169 +MustTargetPreventRevealUnits: ActionResult.ValueType # 170 +CantTargetPreventRevealUnits: ActionResult.ValueType # 171 +MustTargetPassiveUnits: ActionResult.ValueType # 172 +CantTargetPassiveUnits: ActionResult.ValueType # 173 +MustTargetStunnedUnits: ActionResult.ValueType # 174 +CantTargetStunnedUnits: ActionResult.ValueType # 175 +MustTargetSummonedUnits: ActionResult.ValueType # 176 +CantTargetSummonedUnits: ActionResult.ValueType # 177 +MustTargetUser1: ActionResult.ValueType # 178 +CantTargetUser1: ActionResult.ValueType # 179 +MustTargetUnstoppableUnits: ActionResult.ValueType # 180 +CantTargetUnstoppableUnits: ActionResult.ValueType # 181 +MustTargetResistantUnits: ActionResult.ValueType # 182 +CantTargetResistantUnits: ActionResult.ValueType # 183 +MustTargetDazedUnits: ActionResult.ValueType # 184 +CantTargetDazedUnits: ActionResult.ValueType # 185 +CantLockdown: ActionResult.ValueType # 186 +CantMindControl: ActionResult.ValueType # 187 +MustTargetDestructibles: ActionResult.ValueType # 188 +CantTargetDestructibles: ActionResult.ValueType # 189 +MustTargetItems: ActionResult.ValueType # 190 +CantTargetItems: ActionResult.ValueType # 191 +NoCalldownAvailable: ActionResult.ValueType # 192 +WaypointListFull: ActionResult.ValueType # 193 +MustTargetRace: ActionResult.ValueType # 194 +CantTargetRace: ActionResult.ValueType # 195 +MustTargetSimilarUnits: ActionResult.ValueType # 196 +CantTargetSimilarUnits: ActionResult.ValueType # 197 +CantFindEnoughTargets: ActionResult.ValueType # 198 +AlreadySpawningLarva: ActionResult.ValueType # 199 +CantTargetExhaustedResources: ActionResult.ValueType # 200 +CantUseMinimap: ActionResult.ValueType # 201 +CantUseInfoPanel: ActionResult.ValueType # 202 +OrderQueueIsFull: ActionResult.ValueType # 203 +CantHarvestThatResource: ActionResult.ValueType # 204 +HarvestersNotRequired: ActionResult.ValueType # 205 +AlreadyTargeted: ActionResult.ValueType # 206 +CantAttackWeaponsDisabled: ActionResult.ValueType # 207 +CouldntReachTarget: ActionResult.ValueType # 208 +TargetIsOutOfRange: ActionResult.ValueType # 209 +TargetIsTooClose: ActionResult.ValueType # 210 +TargetIsOutOfArc: ActionResult.ValueType # 211 +CantFindTeleportLocation: ActionResult.ValueType # 212 +InvalidItemClass: ActionResult.ValueType # 213 +CantFindCancelOrder: ActionResult.ValueType # 214 +global___ActionResult = ActionResult diff --git a/stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi new file mode 100644 index 000000000000..2df098c7eb4a --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi @@ -0,0 +1,228 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import s2clientprotocol.common_pb2 +import s2clientprotocol.error_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class RequestQuery(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PATHING_FIELD_NUMBER: builtins.int + ABILITIES_FIELD_NUMBER: builtins.int + PLACEMENTS_FIELD_NUMBER: builtins.int + IGNORE_RESOURCE_REQUIREMENTS_FIELD_NUMBER: builtins.int + ignore_resource_requirements: builtins.bool + """Ignores requirements like food, minerals and so on.""" + @property + def pathing(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RequestQueryPathing]: ... + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RequestQueryAvailableAbilities]: ... + @property + def placements( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RequestQueryBuildingPlacement]: ... + def __init__( + self, + *, + pathing: collections.abc.Iterable[global___RequestQueryPathing] | None = ..., + abilities: collections.abc.Iterable[global___RequestQueryAvailableAbilities] | None = ..., + placements: collections.abc.Iterable[global___RequestQueryBuildingPlacement] | None = ..., + ignore_resource_requirements: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["ignore_resource_requirements", b"ignore_resource_requirements"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "abilities", + b"abilities", + "ignore_resource_requirements", + b"ignore_resource_requirements", + "pathing", + b"pathing", + "placements", + b"placements", + ], + ) -> None: ... + +global___RequestQuery = RequestQuery + +@typing.final +class ResponseQuery(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PATHING_FIELD_NUMBER: builtins.int + ABILITIES_FIELD_NUMBER: builtins.int + PLACEMENTS_FIELD_NUMBER: builtins.int + @property + def pathing(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ResponseQueryPathing]: ... + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ResponseQueryAvailableAbilities]: ... + @property + def placements( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ResponseQueryBuildingPlacement]: ... + def __init__( + self, + *, + pathing: collections.abc.Iterable[global___ResponseQueryPathing] | None = ..., + abilities: collections.abc.Iterable[global___ResponseQueryAvailableAbilities] | None = ..., + placements: collections.abc.Iterable[global___ResponseQueryBuildingPlacement] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["abilities", b"abilities", "pathing", b"pathing", "placements", b"placements"] + ) -> None: ... + +global___ResponseQuery = ResponseQuery + +@typing.final +class RequestQueryPathing(google.protobuf.message.Message): + """--------------------------------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_POS_FIELD_NUMBER: builtins.int + UNIT_TAG_FIELD_NUMBER: builtins.int + END_POS_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + @property + def start_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + @property + def end_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, + *, + start_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + unit_tag: builtins.int | None = ..., + end_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["end_pos", b"end_pos", "start", b"start", "start_pos", b"start_pos", "unit_tag", b"unit_tag"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal["end_pos", b"end_pos", "start", b"start", "start_pos", b"start_pos", "unit_tag", b"unit_tag"], + ) -> None: ... + def WhichOneof(self, oneof_group: typing.Literal["start", b"start"]) -> typing.Literal["start_pos", "unit_tag"] | None: ... + +global___RequestQueryPathing = RequestQueryPathing + +@typing.final +class ResponseQueryPathing(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DISTANCE_FIELD_NUMBER: builtins.int + distance: builtins.float + """0 if no path exists""" + def __init__(self, *, distance: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["distance", b"distance"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["distance", b"distance"]) -> None: ... + +global___ResponseQueryPathing = ResponseQueryPathing + +@typing.final +class RequestQueryAvailableAbilities(google.protobuf.message.Message): + """--------------------------------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TAG_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + def __init__(self, *, unit_tag: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["unit_tag", b"unit_tag"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["unit_tag", b"unit_tag"]) -> None: ... + +global___RequestQueryAvailableAbilities = RequestQueryAvailableAbilities + +@typing.final +class ResponseQueryAvailableAbilities(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITIES_FIELD_NUMBER: builtins.int + UNIT_TAG_FIELD_NUMBER: builtins.int + UNIT_TYPE_ID_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + unit_type_id: builtins.int + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.AvailableAbility]: ... + def __init__( + self, + *, + abilities: collections.abc.Iterable[s2clientprotocol.common_pb2.AvailableAbility] | None = ..., + unit_tag: builtins.int | None = ..., + unit_type_id: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["unit_tag", b"unit_tag", "unit_type_id", b"unit_type_id"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["abilities", b"abilities", "unit_tag", b"unit_tag", "unit_type_id", b"unit_type_id"] + ) -> None: ... + +global___ResponseQueryAvailableAbilities = ResponseQueryAvailableAbilities + +@typing.final +class RequestQueryBuildingPlacement(google.protobuf.message.Message): + """--------------------------------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_POS_FIELD_NUMBER: builtins.int + PLACING_UNIT_TAG_FIELD_NUMBER: builtins.int + ability_id: builtins.int + placing_unit_tag: builtins.int + """Not required""" + @property + def target_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + placing_unit_tag: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", b"ability_id", "placing_unit_tag", b"placing_unit_tag", "target_pos", b"target_pos" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", b"ability_id", "placing_unit_tag", b"placing_unit_tag", "target_pos", b"target_pos" + ], + ) -> None: ... + +global___RequestQueryBuildingPlacement = RequestQueryBuildingPlacement + +@typing.final +class ResponseQueryBuildingPlacement(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RESULT_FIELD_NUMBER: builtins.int + result: s2clientprotocol.error_pb2.ActionResult.ValueType + def __init__(self, *, result: s2clientprotocol.error_pb2.ActionResult.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["result", b"result"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["result", b"result"]) -> None: ... + +global___ResponseQueryBuildingPlacement = ResponseQueryBuildingPlacement diff --git a/stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi new file mode 100644 index 000000000000..a50167f1e087 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi @@ -0,0 +1,1024 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _DisplayType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DisplayTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_DisplayType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Visible: _DisplayType.ValueType # 1 + """Fully visible""" + Snapshot: _DisplayType.ValueType # 2 + """Dimmed version of unit left behind after entering fog of war""" + Hidden: _DisplayType.ValueType # 3 + """Fully hidden""" + Placeholder: _DisplayType.ValueType # 4 + """Building that hasn't started construction.""" + +class DisplayType(_DisplayType, metaclass=_DisplayTypeEnumTypeWrapper): ... + +Visible: DisplayType.ValueType # 1 +"""Fully visible""" +Snapshot: DisplayType.ValueType # 2 +"""Dimmed version of unit left behind after entering fog of war""" +Hidden: DisplayType.ValueType # 3 +"""Fully hidden""" +Placeholder: DisplayType.ValueType # 4 +"""Building that hasn't started construction.""" +global___DisplayType = DisplayType + +class _Alliance: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AllianceEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Alliance.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Self: _Alliance.ValueType # 1 + Ally: _Alliance.ValueType # 2 + Neutral: _Alliance.ValueType # 3 + Enemy: _Alliance.ValueType # 4 + +class Alliance(_Alliance, metaclass=_AllianceEnumTypeWrapper): ... + +Self: Alliance.ValueType # 1 +Ally: Alliance.ValueType # 2 +Neutral: Alliance.ValueType # 3 +Enemy: Alliance.ValueType # 4 +global___Alliance = Alliance + +class _CloakState: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CloakStateEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CloakState.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CloakedUnknown: _CloakState.ValueType # 0 + """Under the fog, so unknown whether it's cloaked or not.""" + Cloaked: _CloakState.ValueType # 1 + CloakedDetected: _CloakState.ValueType # 2 + NotCloaked: _CloakState.ValueType # 3 + CloakedAllied: _CloakState.ValueType # 4 + +class CloakState(_CloakState, metaclass=_CloakStateEnumTypeWrapper): ... + +CloakedUnknown: CloakState.ValueType # 0 +"""Under the fog, so unknown whether it's cloaked or not.""" +Cloaked: CloakState.ValueType # 1 +CloakedDetected: CloakState.ValueType # 2 +NotCloaked: CloakState.ValueType # 3 +CloakedAllied: CloakState.ValueType # 4 +global___CloakState = CloakState + +@typing.final +class StartRaw(google.protobuf.message.Message): + """ + Start + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_SIZE_FIELD_NUMBER: builtins.int + PATHING_GRID_FIELD_NUMBER: builtins.int + TERRAIN_HEIGHT_FIELD_NUMBER: builtins.int + PLACEMENT_GRID_FIELD_NUMBER: builtins.int + PLAYABLE_AREA_FIELD_NUMBER: builtins.int + START_LOCATIONS_FIELD_NUMBER: builtins.int + @property + def map_size(self) -> s2clientprotocol.common_pb2.Size2DI: + """Width and height of the map.""" + + @property + def pathing_grid(self) -> s2clientprotocol.common_pb2.ImageData: + """1 bit bitmap of the pathing grid.""" + + @property + def terrain_height(self) -> s2clientprotocol.common_pb2.ImageData: + """1 byte bitmap of the terrain height.""" + + @property + def placement_grid(self) -> s2clientprotocol.common_pb2.ImageData: + """1 bit bitmap of the building placement grid.""" + + @property + def playable_area(self) -> s2clientprotocol.common_pb2.RectangleI: + """The playable cells.""" + + @property + def start_locations( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.Point2D]: + """Possible start locations for players.""" + + def __init__( + self, + *, + map_size: s2clientprotocol.common_pb2.Size2DI | None = ..., + pathing_grid: s2clientprotocol.common_pb2.ImageData | None = ..., + terrain_height: s2clientprotocol.common_pb2.ImageData | None = ..., + placement_grid: s2clientprotocol.common_pb2.ImageData | None = ..., + playable_area: s2clientprotocol.common_pb2.RectangleI | None = ..., + start_locations: collections.abc.Iterable[s2clientprotocol.common_pb2.Point2D] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "map_size", + b"map_size", + "pathing_grid", + b"pathing_grid", + "placement_grid", + b"placement_grid", + "playable_area", + b"playable_area", + "terrain_height", + b"terrain_height", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "map_size", + b"map_size", + "pathing_grid", + b"pathing_grid", + "placement_grid", + b"placement_grid", + "playable_area", + b"playable_area", + "start_locations", + b"start_locations", + "terrain_height", + b"terrain_height", + ], + ) -> None: ... + +global___StartRaw = StartRaw + +@typing.final +class ObservationRaw(google.protobuf.message.Message): + """ + Observation + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_FIELD_NUMBER: builtins.int + UNITS_FIELD_NUMBER: builtins.int + MAP_STATE_FIELD_NUMBER: builtins.int + EVENT_FIELD_NUMBER: builtins.int + EFFECTS_FIELD_NUMBER: builtins.int + RADAR_FIELD_NUMBER: builtins.int + @property + def player(self) -> global___PlayerRaw: ... + @property + def units(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Unit]: ... + @property + def map_state(self) -> global___MapState: + """Fog of war, creep and so on. Board stuff that changes per frame.""" + + @property + def event(self) -> global___Event: ... + @property + def effects(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Effect]: ... + @property + def radar(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RadarRing]: ... + def __init__( + self, + *, + player: global___PlayerRaw | None = ..., + units: collections.abc.Iterable[global___Unit] | None = ..., + map_state: global___MapState | None = ..., + event: global___Event | None = ..., + effects: collections.abc.Iterable[global___Effect] | None = ..., + radar: collections.abc.Iterable[global___RadarRing] | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["event", b"event", "map_state", b"map_state", "player", b"player"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "effects", + b"effects", + "event", + b"event", + "map_state", + b"map_state", + "player", + b"player", + "radar", + b"radar", + "units", + b"units", + ], + ) -> None: ... + +global___ObservationRaw = ObservationRaw + +@typing.final +class RadarRing(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POS_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + radius: builtins.float + @property + def pos(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__(self, *, pos: s2clientprotocol.common_pb2.Point | None = ..., radius: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius"]) -> None: ... + +global___RadarRing = RadarRing + +@typing.final +class PowerSource(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POS_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + TAG_FIELD_NUMBER: builtins.int + radius: builtins.float + tag: builtins.int + @property + def pos(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + pos: s2clientprotocol.common_pb2.Point | None = ..., + radius: builtins.float | None = ..., + tag: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius", "tag", b"tag"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius", "tag", b"tag"]) -> None: ... + +global___PowerSource = PowerSource + +@typing.final +class PlayerRaw(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POWER_SOURCES_FIELD_NUMBER: builtins.int + CAMERA_FIELD_NUMBER: builtins.int + UPGRADE_IDS_FIELD_NUMBER: builtins.int + @property + def power_sources(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PowerSource]: ... + @property + def camera(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def upgrade_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """TODO: Add to UI observation?""" + + def __init__( + self, + *, + power_sources: collections.abc.Iterable[global___PowerSource] | None = ..., + camera: s2clientprotocol.common_pb2.Point | None = ..., + upgrade_ids: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["camera", b"camera"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["camera", b"camera", "power_sources", b"power_sources", "upgrade_ids", b"upgrade_ids"] + ) -> None: ... + +global___PlayerRaw = PlayerRaw + +@typing.final +class UnitOrder(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_WORLD_SPACE_POS_FIELD_NUMBER: builtins.int + TARGET_UNIT_TAG_FIELD_NUMBER: builtins.int + PROGRESS_FIELD_NUMBER: builtins.int + ability_id: builtins.int + target_unit_tag: builtins.int + progress: builtins.float + """Progress of train abilities. Range: [0.0, 1.0]""" + @property + def target_world_space_pos(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_world_space_pos: s2clientprotocol.common_pb2.Point | None = ..., + target_unit_tag: builtins.int | None = ..., + progress: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "progress", + b"progress", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "progress", + b"progress", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["target", b"target"] + ) -> typing.Literal["target_world_space_pos", "target_unit_tag"] | None: ... + +global___UnitOrder = UnitOrder + +@typing.final +class PassengerUnit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TAG_FIELD_NUMBER: builtins.int + HEALTH_FIELD_NUMBER: builtins.int + HEALTH_MAX_FIELD_NUMBER: builtins.int + SHIELD_FIELD_NUMBER: builtins.int + SHIELD_MAX_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + ENERGY_MAX_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + tag: builtins.int + health: builtins.float + health_max: builtins.float + shield: builtins.float + shield_max: builtins.float + energy: builtins.float + energy_max: builtins.float + unit_type: builtins.int + def __init__( + self, + *, + tag: builtins.int | None = ..., + health: builtins.float | None = ..., + health_max: builtins.float | None = ..., + shield: builtins.float | None = ..., + shield_max: builtins.float | None = ..., + energy: builtins.float | None = ..., + energy_max: builtins.float | None = ..., + unit_type: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "energy", + b"energy", + "energy_max", + b"energy_max", + "health", + b"health", + "health_max", + b"health_max", + "shield", + b"shield", + "shield_max", + b"shield_max", + "tag", + b"tag", + "unit_type", + b"unit_type", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "energy", + b"energy", + "energy_max", + b"energy_max", + "health", + b"health", + "health_max", + b"health_max", + "shield", + b"shield", + "shield_max", + b"shield_max", + "tag", + b"tag", + "unit_type", + b"unit_type", + ], + ) -> None: ... + +global___PassengerUnit = PassengerUnit + +@typing.final +class RallyTarget(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POINT_FIELD_NUMBER: builtins.int + TAG_FIELD_NUMBER: builtins.int + tag: builtins.int + """Only if it's targeting a unit.""" + @property + def point(self) -> s2clientprotocol.common_pb2.Point: + """Will always be filled.""" + + def __init__(self, *, point: s2clientprotocol.common_pb2.Point | None = ..., tag: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["point", b"point", "tag", b"tag"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["point", b"point", "tag", b"tag"]) -> None: ... + +global___RallyTarget = RallyTarget + +@typing.final +class Unit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DISPLAY_TYPE_FIELD_NUMBER: builtins.int + ALLIANCE_FIELD_NUMBER: builtins.int + TAG_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + OWNER_FIELD_NUMBER: builtins.int + POS_FIELD_NUMBER: builtins.int + FACING_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + CLOAK_FIELD_NUMBER: builtins.int + BUFF_IDS_FIELD_NUMBER: builtins.int + DETECT_RANGE_FIELD_NUMBER: builtins.int + RADAR_RANGE_FIELD_NUMBER: builtins.int + IS_SELECTED_FIELD_NUMBER: builtins.int + IS_ON_SCREEN_FIELD_NUMBER: builtins.int + IS_BLIP_FIELD_NUMBER: builtins.int + IS_POWERED_FIELD_NUMBER: builtins.int + IS_ACTIVE_FIELD_NUMBER: builtins.int + ATTACK_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + ARMOR_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + SHIELD_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + HEALTH_FIELD_NUMBER: builtins.int + HEALTH_MAX_FIELD_NUMBER: builtins.int + SHIELD_FIELD_NUMBER: builtins.int + SHIELD_MAX_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + ENERGY_MAX_FIELD_NUMBER: builtins.int + MINERAL_CONTENTS_FIELD_NUMBER: builtins.int + VESPENE_CONTENTS_FIELD_NUMBER: builtins.int + IS_FLYING_FIELD_NUMBER: builtins.int + IS_BURROWED_FIELD_NUMBER: builtins.int + IS_HALLUCINATION_FIELD_NUMBER: builtins.int + ORDERS_FIELD_NUMBER: builtins.int + ADD_ON_TAG_FIELD_NUMBER: builtins.int + PASSENGERS_FIELD_NUMBER: builtins.int + CARGO_SPACE_TAKEN_FIELD_NUMBER: builtins.int + CARGO_SPACE_MAX_FIELD_NUMBER: builtins.int + ASSIGNED_HARVESTERS_FIELD_NUMBER: builtins.int + IDEAL_HARVESTERS_FIELD_NUMBER: builtins.int + WEAPON_COOLDOWN_FIELD_NUMBER: builtins.int + ENGAGED_TARGET_TAG_FIELD_NUMBER: builtins.int + BUFF_DURATION_REMAIN_FIELD_NUMBER: builtins.int + BUFF_DURATION_MAX_FIELD_NUMBER: builtins.int + RALLY_TARGETS_FIELD_NUMBER: builtins.int + display_type: global___DisplayType.ValueType + """Fields are populated based on type/alliance""" + alliance: global___Alliance.ValueType + tag: builtins.int + """Unique identifier for a unit""" + unit_type: builtins.int + owner: builtins.int + facing: builtins.float + radius: builtins.float + build_progress: builtins.float + """Range: [0.0, 1.0]""" + cloak: global___CloakState.ValueType + detect_range: builtins.float + radar_range: builtins.float + is_selected: builtins.bool + is_on_screen: builtins.bool + """Visible and within the camera frustrum.""" + is_blip: builtins.bool + """Detected by sensor tower""" + is_powered: builtins.bool + is_active: builtins.bool + """Building is training/researching (ie animated).""" + attack_upgrade_level: builtins.int + armor_upgrade_level: builtins.int + shield_upgrade_level: builtins.int + health: builtins.float + """Not populated for snapshots""" + health_max: builtins.float + shield: builtins.float + shield_max: builtins.float + energy: builtins.float + energy_max: builtins.float + mineral_contents: builtins.int + vespene_contents: builtins.int + is_flying: builtins.bool + is_burrowed: builtins.bool + is_hallucination: builtins.bool + """Unit is your own or detected as a hallucination.""" + add_on_tag: builtins.int + cargo_space_taken: builtins.int + cargo_space_max: builtins.int + assigned_harvesters: builtins.int + ideal_harvesters: builtins.int + weapon_cooldown: builtins.float + engaged_target_tag: builtins.int + buff_duration_remain: builtins.int + """How long a buff or unit is still around (eg mule, broodling, chronoboost).""" + buff_duration_max: builtins.int + """How long the buff or unit is still around (eg mule, broodling, chronoboost).""" + @property + def pos(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def buff_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def orders(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitOrder]: + """Not populated for enemies""" + + @property + def passengers(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PassengerUnit]: ... + @property + def rally_targets(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RallyTarget]: ... + def __init__( + self, + *, + display_type: global___DisplayType.ValueType | None = ..., + alliance: global___Alliance.ValueType | None = ..., + tag: builtins.int | None = ..., + unit_type: builtins.int | None = ..., + owner: builtins.int | None = ..., + pos: s2clientprotocol.common_pb2.Point | None = ..., + facing: builtins.float | None = ..., + radius: builtins.float | None = ..., + build_progress: builtins.float | None = ..., + cloak: global___CloakState.ValueType | None = ..., + buff_ids: collections.abc.Iterable[builtins.int] | None = ..., + detect_range: builtins.float | None = ..., + radar_range: builtins.float | None = ..., + is_selected: builtins.bool | None = ..., + is_on_screen: builtins.bool | None = ..., + is_blip: builtins.bool | None = ..., + is_powered: builtins.bool | None = ..., + is_active: builtins.bool | None = ..., + attack_upgrade_level: builtins.int | None = ..., + armor_upgrade_level: builtins.int | None = ..., + shield_upgrade_level: builtins.int | None = ..., + health: builtins.float | None = ..., + health_max: builtins.float | None = ..., + shield: builtins.float | None = ..., + shield_max: builtins.float | None = ..., + energy: builtins.float | None = ..., + energy_max: builtins.float | None = ..., + mineral_contents: builtins.int | None = ..., + vespene_contents: builtins.int | None = ..., + is_flying: builtins.bool | None = ..., + is_burrowed: builtins.bool | None = ..., + is_hallucination: builtins.bool | None = ..., + orders: collections.abc.Iterable[global___UnitOrder] | None = ..., + add_on_tag: builtins.int | None = ..., + passengers: collections.abc.Iterable[global___PassengerUnit] | None = ..., + cargo_space_taken: builtins.int | None = ..., + cargo_space_max: builtins.int | None = ..., + assigned_harvesters: builtins.int | None = ..., + ideal_harvesters: builtins.int | None = ..., + weapon_cooldown: builtins.float | None = ..., + engaged_target_tag: builtins.int | None = ..., + buff_duration_remain: builtins.int | None = ..., + buff_duration_max: builtins.int | None = ..., + rally_targets: collections.abc.Iterable[global___RallyTarget] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "add_on_tag", + b"add_on_tag", + "alliance", + b"alliance", + "armor_upgrade_level", + b"armor_upgrade_level", + "assigned_harvesters", + b"assigned_harvesters", + "attack_upgrade_level", + b"attack_upgrade_level", + "buff_duration_max", + b"buff_duration_max", + "buff_duration_remain", + b"buff_duration_remain", + "build_progress", + b"build_progress", + "cargo_space_max", + b"cargo_space_max", + "cargo_space_taken", + b"cargo_space_taken", + "cloak", + b"cloak", + "detect_range", + b"detect_range", + "display_type", + b"display_type", + "energy", + b"energy", + "energy_max", + b"energy_max", + "engaged_target_tag", + b"engaged_target_tag", + "facing", + b"facing", + "health", + b"health", + "health_max", + b"health_max", + "ideal_harvesters", + b"ideal_harvesters", + "is_active", + b"is_active", + "is_blip", + b"is_blip", + "is_burrowed", + b"is_burrowed", + "is_flying", + b"is_flying", + "is_hallucination", + b"is_hallucination", + "is_on_screen", + b"is_on_screen", + "is_powered", + b"is_powered", + "is_selected", + b"is_selected", + "mineral_contents", + b"mineral_contents", + "owner", + b"owner", + "pos", + b"pos", + "radar_range", + b"radar_range", + "radius", + b"radius", + "shield", + b"shield", + "shield_max", + b"shield_max", + "shield_upgrade_level", + b"shield_upgrade_level", + "tag", + b"tag", + "unit_type", + b"unit_type", + "vespene_contents", + b"vespene_contents", + "weapon_cooldown", + b"weapon_cooldown", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "add_on_tag", + b"add_on_tag", + "alliance", + b"alliance", + "armor_upgrade_level", + b"armor_upgrade_level", + "assigned_harvesters", + b"assigned_harvesters", + "attack_upgrade_level", + b"attack_upgrade_level", + "buff_duration_max", + b"buff_duration_max", + "buff_duration_remain", + b"buff_duration_remain", + "buff_ids", + b"buff_ids", + "build_progress", + b"build_progress", + "cargo_space_max", + b"cargo_space_max", + "cargo_space_taken", + b"cargo_space_taken", + "cloak", + b"cloak", + "detect_range", + b"detect_range", + "display_type", + b"display_type", + "energy", + b"energy", + "energy_max", + b"energy_max", + "engaged_target_tag", + b"engaged_target_tag", + "facing", + b"facing", + "health", + b"health", + "health_max", + b"health_max", + "ideal_harvesters", + b"ideal_harvesters", + "is_active", + b"is_active", + "is_blip", + b"is_blip", + "is_burrowed", + b"is_burrowed", + "is_flying", + b"is_flying", + "is_hallucination", + b"is_hallucination", + "is_on_screen", + b"is_on_screen", + "is_powered", + b"is_powered", + "is_selected", + b"is_selected", + "mineral_contents", + b"mineral_contents", + "orders", + b"orders", + "owner", + b"owner", + "passengers", + b"passengers", + "pos", + b"pos", + "radar_range", + b"radar_range", + "radius", + b"radius", + "rally_targets", + b"rally_targets", + "shield", + b"shield", + "shield_max", + b"shield_max", + "shield_upgrade_level", + b"shield_upgrade_level", + "tag", + b"tag", + "unit_type", + b"unit_type", + "vespene_contents", + b"vespene_contents", + "weapon_cooldown", + b"weapon_cooldown", + ], + ) -> None: ... + +global___Unit = Unit + +@typing.final +class MapState(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VISIBILITY_FIELD_NUMBER: builtins.int + CREEP_FIELD_NUMBER: builtins.int + @property + def visibility(self) -> s2clientprotocol.common_pb2.ImageData: + """1 byte visibility layer.""" + + @property + def creep(self) -> s2clientprotocol.common_pb2.ImageData: + """1 bit creep layer.""" + + def __init__( + self, + *, + visibility: s2clientprotocol.common_pb2.ImageData | None = ..., + creep: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["creep", b"creep", "visibility", b"visibility"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["creep", b"creep", "visibility", b"visibility"]) -> None: ... + +global___MapState = MapState + +@typing.final +class Event(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEAD_UNITS_FIELD_NUMBER: builtins.int + @property + def dead_units(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, dead_units: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dead_units", b"dead_units"]) -> None: ... + +global___Event = Event + +@typing.final +class Effect(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EFFECT_ID_FIELD_NUMBER: builtins.int + POS_FIELD_NUMBER: builtins.int + ALLIANCE_FIELD_NUMBER: builtins.int + OWNER_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + effect_id: builtins.int + alliance: global___Alliance.ValueType + owner: builtins.int + radius: builtins.float + @property + def pos(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.Point2D]: + """Effect may impact multiple locations. (eg. Lurker attack)""" + + def __init__( + self, + *, + effect_id: builtins.int | None = ..., + pos: collections.abc.Iterable[s2clientprotocol.common_pb2.Point2D] | None = ..., + alliance: global___Alliance.ValueType | None = ..., + owner: builtins.int | None = ..., + radius: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["alliance", b"alliance", "effect_id", b"effect_id", "owner", b"owner", "radius", b"radius"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alliance", b"alliance", "effect_id", b"effect_id", "owner", b"owner", "pos", b"pos", "radius", b"radius" + ], + ) -> None: ... + +global___Effect = Effect + +@typing.final +class ActionRaw(google.protobuf.message.Message): + """ + Action + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_COMMAND_FIELD_NUMBER: builtins.int + CAMERA_MOVE_FIELD_NUMBER: builtins.int + TOGGLE_AUTOCAST_FIELD_NUMBER: builtins.int + @property + def unit_command(self) -> global___ActionRawUnitCommand: ... + @property + def camera_move(self) -> global___ActionRawCameraMove: ... + @property + def toggle_autocast(self) -> global___ActionRawToggleAutocast: ... + def __init__( + self, + *, + unit_command: global___ActionRawUnitCommand | None = ..., + camera_move: global___ActionRawCameraMove | None = ..., + toggle_autocast: global___ActionRawToggleAutocast | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "toggle_autocast", + b"toggle_autocast", + "unit_command", + b"unit_command", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "toggle_autocast", + b"toggle_autocast", + "unit_command", + b"unit_command", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> typing.Literal["unit_command", "camera_move", "toggle_autocast"] | None: ... + +global___ActionRaw = ActionRaw + +@typing.final +class ActionRawUnitCommand(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_WORLD_SPACE_POS_FIELD_NUMBER: builtins.int + TARGET_UNIT_TAG_FIELD_NUMBER: builtins.int + UNIT_TAGS_FIELD_NUMBER: builtins.int + QUEUE_COMMAND_FIELD_NUMBER: builtins.int + ability_id: builtins.int + target_unit_tag: builtins.int + queue_command: builtins.bool + @property + def target_world_space_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + @property + def unit_tags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_world_space_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + target_unit_tag: builtins.int | None = ..., + unit_tags: collections.abc.Iterable[builtins.int] | None = ..., + queue_command: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + "unit_tags", + b"unit_tags", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["target", b"target"] + ) -> typing.Literal["target_world_space_pos", "target_unit_tag"] | None: ... + +global___ActionRawUnitCommand = ActionRawUnitCommand + +@typing.final +class ActionRawCameraMove(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CENTER_WORLD_SPACE_FIELD_NUMBER: builtins.int + @property + def center_world_space(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__(self, *, center_world_space: s2clientprotocol.common_pb2.Point | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["center_world_space", b"center_world_space"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["center_world_space", b"center_world_space"]) -> None: ... + +global___ActionRawCameraMove = ActionRawCameraMove + +@typing.final +class ActionRawToggleAutocast(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + UNIT_TAGS_FIELD_NUMBER: builtins.int + ability_id: builtins.int + @property + def unit_tags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, *, ability_id: builtins.int | None = ..., unit_tags: collections.abc.Iterable[builtins.int] | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["ability_id", b"ability_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["ability_id", b"ability_id", "unit_tags", b"unit_tags"]) -> None: ... + +global___ActionRawToggleAutocast = ActionRawToggleAutocast diff --git a/stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi new file mode 100644 index 000000000000..fbf53b67a613 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi @@ -0,0 +1,2896 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 +import s2clientprotocol.data_pb2 +import s2clientprotocol.debug_pb2 +import s2clientprotocol.error_pb2 +import s2clientprotocol.query_pb2 +import s2clientprotocol.raw_pb2 +import s2clientprotocol.score_pb2 +import s2clientprotocol.spatial_pb2 +import s2clientprotocol.ui_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Status: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _StatusEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Status.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + launched: _Status.ValueType # 1 + """Game has been launch and is not yet doing anything.""" + init_game: _Status.ValueType # 2 + """Create game has been called, and the host is awaiting players.""" + in_game: _Status.ValueType # 3 + """In a single or multiplayer game.""" + in_replay: _Status.ValueType # 4 + """In a replay.""" + ended: _Status.ValueType # 5 + """Game has ended, can still request game info, but ready for a new game.""" + quit: _Status.ValueType # 6 + """Application is shutting down.""" + unknown: _Status.ValueType # 99 + """Should not happen, but indicates an error if it occurs.""" + +class Status(_Status, metaclass=_StatusEnumTypeWrapper): ... + +launched: Status.ValueType # 1 +"""Game has been launch and is not yet doing anything.""" +init_game: Status.ValueType # 2 +"""Create game has been called, and the host is awaiting players.""" +in_game: Status.ValueType # 3 +"""In a single or multiplayer game.""" +in_replay: Status.ValueType # 4 +"""In a replay.""" +ended: Status.ValueType # 5 +"""Game has ended, can still request game info, but ready for a new game.""" +quit: Status.ValueType # 6 +"""Application is shutting down.""" +unknown: Status.ValueType # 99 +"""Should not happen, but indicates an error if it occurs.""" +global___Status = Status + +class _Difficulty: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DifficultyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Difficulty.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + VeryEasy: _Difficulty.ValueType # 1 + Easy: _Difficulty.ValueType # 2 + Medium: _Difficulty.ValueType # 3 + MediumHard: _Difficulty.ValueType # 4 + Hard: _Difficulty.ValueType # 5 + Harder: _Difficulty.ValueType # 6 + VeryHard: _Difficulty.ValueType # 7 + CheatVision: _Difficulty.ValueType # 8 + CheatMoney: _Difficulty.ValueType # 9 + CheatInsane: _Difficulty.ValueType # 10 + +class Difficulty(_Difficulty, metaclass=_DifficultyEnumTypeWrapper): + """ + Game Setup + """ + +VeryEasy: Difficulty.ValueType # 1 +Easy: Difficulty.ValueType # 2 +Medium: Difficulty.ValueType # 3 +MediumHard: Difficulty.ValueType # 4 +Hard: Difficulty.ValueType # 5 +Harder: Difficulty.ValueType # 6 +VeryHard: Difficulty.ValueType # 7 +CheatVision: Difficulty.ValueType # 8 +CheatMoney: Difficulty.ValueType # 9 +CheatInsane: Difficulty.ValueType # 10 +global___Difficulty = Difficulty + +class _PlayerType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _PlayerTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_PlayerType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Participant: _PlayerType.ValueType # 1 + Computer: _PlayerType.ValueType # 2 + Observer: _PlayerType.ValueType # 3 + +class PlayerType(_PlayerType, metaclass=_PlayerTypeEnumTypeWrapper): ... + +Participant: PlayerType.ValueType # 1 +Computer: PlayerType.ValueType # 2 +Observer: PlayerType.ValueType # 3 +global___PlayerType = PlayerType + +class _AIBuild: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AIBuildEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_AIBuild.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RandomBuild: _AIBuild.ValueType # 1 + Rush: _AIBuild.ValueType # 2 + Timing: _AIBuild.ValueType # 3 + Power: _AIBuild.ValueType # 4 + Macro: _AIBuild.ValueType # 5 + Air: _AIBuild.ValueType # 6 + +class AIBuild(_AIBuild, metaclass=_AIBuildEnumTypeWrapper): ... + +RandomBuild: AIBuild.ValueType # 1 +Rush: AIBuild.ValueType # 2 +Timing: AIBuild.ValueType # 3 +Power: AIBuild.ValueType # 4 +Macro: AIBuild.ValueType # 5 +Air: AIBuild.ValueType # 6 +global___AIBuild = AIBuild + +class _Alert: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AlertEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Alert.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AlertError: _Alert.ValueType # 3 + AddOnComplete: _Alert.ValueType # 4 + BuildingComplete: _Alert.ValueType # 5 + BuildingUnderAttack: _Alert.ValueType # 6 + LarvaHatched: _Alert.ValueType # 7 + MergeComplete: _Alert.ValueType # 8 + MineralsExhausted: _Alert.ValueType # 9 + MorphComplete: _Alert.ValueType # 10 + MothershipComplete: _Alert.ValueType # 11 + MULEExpired: _Alert.ValueType # 12 + NuclearLaunchDetected: _Alert.ValueType # 1 + NukeComplete: _Alert.ValueType # 13 + NydusWormDetected: _Alert.ValueType # 2 + ResearchComplete: _Alert.ValueType # 14 + TrainError: _Alert.ValueType # 15 + TrainUnitComplete: _Alert.ValueType # 16 + TrainWorkerComplete: _Alert.ValueType # 17 + TransformationComplete: _Alert.ValueType # 18 + UnitUnderAttack: _Alert.ValueType # 19 + UpgradeComplete: _Alert.ValueType # 20 + VespeneExhausted: _Alert.ValueType # 21 + WarpInComplete: _Alert.ValueType # 22 + +class Alert(_Alert, metaclass=_AlertEnumTypeWrapper): ... + +AlertError: Alert.ValueType # 3 +AddOnComplete: Alert.ValueType # 4 +BuildingComplete: Alert.ValueType # 5 +BuildingUnderAttack: Alert.ValueType # 6 +LarvaHatched: Alert.ValueType # 7 +MergeComplete: Alert.ValueType # 8 +MineralsExhausted: Alert.ValueType # 9 +MorphComplete: Alert.ValueType # 10 +MothershipComplete: Alert.ValueType # 11 +MULEExpired: Alert.ValueType # 12 +NuclearLaunchDetected: Alert.ValueType # 1 +NukeComplete: Alert.ValueType # 13 +NydusWormDetected: Alert.ValueType # 2 +ResearchComplete: Alert.ValueType # 14 +TrainError: Alert.ValueType # 15 +TrainUnitComplete: Alert.ValueType # 16 +TrainWorkerComplete: Alert.ValueType # 17 +TransformationComplete: Alert.ValueType # 18 +UnitUnderAttack: Alert.ValueType # 19 +UpgradeComplete: Alert.ValueType # 20 +VespeneExhausted: Alert.ValueType # 21 +WarpInComplete: Alert.ValueType # 22 +global___Alert = Alert + +class _Result: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ResultEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Result.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Victory: _Result.ValueType # 1 + Defeat: _Result.ValueType # 2 + Tie: _Result.ValueType # 3 + Undecided: _Result.ValueType # 4 + +class Result(_Result, metaclass=_ResultEnumTypeWrapper): ... + +Victory: Result.ValueType # 1 +Defeat: Result.ValueType # 2 +Tie: Result.ValueType # 3 +Undecided: Result.ValueType # 4 +global___Result = Result + +@typing.final +class Request(google.protobuf.message.Message): + """ + Request/Response + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CREATE_GAME_FIELD_NUMBER: builtins.int + JOIN_GAME_FIELD_NUMBER: builtins.int + RESTART_GAME_FIELD_NUMBER: builtins.int + START_REPLAY_FIELD_NUMBER: builtins.int + LEAVE_GAME_FIELD_NUMBER: builtins.int + QUICK_SAVE_FIELD_NUMBER: builtins.int + QUICK_LOAD_FIELD_NUMBER: builtins.int + QUIT_FIELD_NUMBER: builtins.int + GAME_INFO_FIELD_NUMBER: builtins.int + OBSERVATION_FIELD_NUMBER: builtins.int + ACTION_FIELD_NUMBER: builtins.int + OBS_ACTION_FIELD_NUMBER: builtins.int + STEP_FIELD_NUMBER: builtins.int + DATA_FIELD_NUMBER: builtins.int + QUERY_FIELD_NUMBER: builtins.int + SAVE_REPLAY_FIELD_NUMBER: builtins.int + MAP_COMMAND_FIELD_NUMBER: builtins.int + REPLAY_INFO_FIELD_NUMBER: builtins.int + AVAILABLE_MAPS_FIELD_NUMBER: builtins.int + SAVE_MAP_FIELD_NUMBER: builtins.int + PING_FIELD_NUMBER: builtins.int + DEBUG_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + id: builtins.int + @property + def create_game(self) -> global___RequestCreateGame: + """Game Setup + Send to host to initialize game. + """ + + @property + def join_game(self) -> global___RequestJoinGame: + """Send to host and all clients for game to begin.""" + + @property + def restart_game(self) -> global___RequestRestartGame: + """Single player only. Reinitializes the game with the same player setup.""" + + @property + def start_replay(self) -> global___RequestStartReplay: + """Start playing a replay.""" + + @property + def leave_game(self) -> global___RequestLeaveGame: + """Multiplayer only. Disconnects from a multiplayer game, equivalent to surrender.""" + + @property + def quick_save(self) -> global___RequestQuickSave: + """Saves game to an in-memory bookmark.""" + + @property + def quick_load(self) -> global___RequestQuickLoad: + """Loads from an in-memory bookmark.""" + + @property + def quit(self) -> global___RequestQuit: + """Terminates the application.""" + + @property + def game_info(self) -> global___RequestGameInfo: + """During Game + Static data about the current game and map. + """ + + @property + def observation(self) -> global___RequestObservation: + """Snapshot of the current game state.""" + + @property + def action(self) -> global___RequestAction: + """Executes an action for a participant.""" + + @property + def obs_action(self) -> global___RequestObserverAction: + """Executes an action for an observer.""" + + @property + def step(self) -> global___RequestStep: + """Advances the game simulation.""" + + @property + def data(self) -> global___RequestData: + """Data about different gameplay elements. May be different for different games.""" + + @property + def query(self) -> s2clientprotocol.query_pb2.RequestQuery: + """Additional methods for inspecting game state.""" + + @property + def save_replay(self) -> global___RequestSaveReplay: + """Generates a replay.""" + + @property + def map_command(self) -> global___RequestMapCommand: + """Execute a particular trigger through a string interface""" + + @property + def replay_info(self) -> global___RequestReplayInfo: + """Other. + Returns metadata about a replay file. Does not load the replay. + """ + + @property + def available_maps(self) -> global___RequestAvailableMaps: + """Returns directory of maps that can be played on.""" + + @property + def save_map(self) -> global___RequestSaveMap: + """Saves binary map data to the local temp directory.""" + + @property + def ping(self) -> global___RequestPing: + """Debugging + Network ping for testing connection. + """ + + @property + def debug(self) -> global___RequestDebug: + """Display debug information and execute debug actions.""" + + def __init__( + self, + *, + create_game: global___RequestCreateGame | None = ..., + join_game: global___RequestJoinGame | None = ..., + restart_game: global___RequestRestartGame | None = ..., + start_replay: global___RequestStartReplay | None = ..., + leave_game: global___RequestLeaveGame | None = ..., + quick_save: global___RequestQuickSave | None = ..., + quick_load: global___RequestQuickLoad | None = ..., + quit: global___RequestQuit | None = ..., + game_info: global___RequestGameInfo | None = ..., + observation: global___RequestObservation | None = ..., + action: global___RequestAction | None = ..., + obs_action: global___RequestObserverAction | None = ..., + step: global___RequestStep | None = ..., + data: global___RequestData | None = ..., + query: s2clientprotocol.query_pb2.RequestQuery | None = ..., + save_replay: global___RequestSaveReplay | None = ..., + map_command: global___RequestMapCommand | None = ..., + replay_info: global___RequestReplayInfo | None = ..., + available_maps: global___RequestAvailableMaps | None = ..., + save_map: global___RequestSaveMap | None = ..., + ping: global___RequestPing | None = ..., + debug: global___RequestDebug | None = ..., + id: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "request", + b"request", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "step", + b"step", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "request", + b"request", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "step", + b"step", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["request", b"request"] + ) -> ( + typing.Literal[ + "create_game", + "join_game", + "restart_game", + "start_replay", + "leave_game", + "quick_save", + "quick_load", + "quit", + "game_info", + "observation", + "action", + "obs_action", + "step", + "data", + "query", + "save_replay", + "map_command", + "replay_info", + "available_maps", + "save_map", + "ping", + "debug", + ] + | None + ): ... + +global___Request = Request + +@typing.final +class Response(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CREATE_GAME_FIELD_NUMBER: builtins.int + JOIN_GAME_FIELD_NUMBER: builtins.int + RESTART_GAME_FIELD_NUMBER: builtins.int + START_REPLAY_FIELD_NUMBER: builtins.int + LEAVE_GAME_FIELD_NUMBER: builtins.int + QUICK_SAVE_FIELD_NUMBER: builtins.int + QUICK_LOAD_FIELD_NUMBER: builtins.int + QUIT_FIELD_NUMBER: builtins.int + GAME_INFO_FIELD_NUMBER: builtins.int + OBSERVATION_FIELD_NUMBER: builtins.int + ACTION_FIELD_NUMBER: builtins.int + OBS_ACTION_FIELD_NUMBER: builtins.int + STEP_FIELD_NUMBER: builtins.int + DATA_FIELD_NUMBER: builtins.int + QUERY_FIELD_NUMBER: builtins.int + SAVE_REPLAY_FIELD_NUMBER: builtins.int + REPLAY_INFO_FIELD_NUMBER: builtins.int + AVAILABLE_MAPS_FIELD_NUMBER: builtins.int + SAVE_MAP_FIELD_NUMBER: builtins.int + MAP_COMMAND_FIELD_NUMBER: builtins.int + PING_FIELD_NUMBER: builtins.int + DEBUG_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + ERROR_FIELD_NUMBER: builtins.int + STATUS_FIELD_NUMBER: builtins.int + id: builtins.int + status: global___Status.ValueType + """Should be sent back with all responses.""" + @property + def create_game(self) -> global___ResponseCreateGame: ... + @property + def join_game(self) -> global___ResponseJoinGame: ... + @property + def restart_game(self) -> global___ResponseRestartGame: ... + @property + def start_replay(self) -> global___ResponseStartReplay: ... + @property + def leave_game(self) -> global___ResponseLeaveGame: ... + @property + def quick_save(self) -> global___ResponseQuickSave: ... + @property + def quick_load(self) -> global___ResponseQuickLoad: ... + @property + def quit(self) -> global___ResponseQuit: ... + @property + def game_info(self) -> global___ResponseGameInfo: ... + @property + def observation(self) -> global___ResponseObservation: ... + @property + def action(self) -> global___ResponseAction: ... + @property + def obs_action(self) -> global___ResponseObserverAction: ... + @property + def step(self) -> global___ResponseStep: ... + @property + def data(self) -> global___ResponseData: ... + @property + def query(self) -> s2clientprotocol.query_pb2.ResponseQuery: ... + @property + def save_replay(self) -> global___ResponseSaveReplay: ... + @property + def replay_info(self) -> global___ResponseReplayInfo: ... + @property + def available_maps(self) -> global___ResponseAvailableMaps: ... + @property + def save_map(self) -> global___ResponseSaveMap: ... + @property + def map_command(self) -> global___ResponseMapCommand: ... + @property + def ping(self) -> global___ResponsePing: + """Debugging""" + + @property + def debug(self) -> global___ResponseDebug: ... + @property + def error(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """If command is missing, this will contain the error. Otherwise this will contain any warnings.""" + + def __init__( + self, + *, + create_game: global___ResponseCreateGame | None = ..., + join_game: global___ResponseJoinGame | None = ..., + restart_game: global___ResponseRestartGame | None = ..., + start_replay: global___ResponseStartReplay | None = ..., + leave_game: global___ResponseLeaveGame | None = ..., + quick_save: global___ResponseQuickSave | None = ..., + quick_load: global___ResponseQuickLoad | None = ..., + quit: global___ResponseQuit | None = ..., + game_info: global___ResponseGameInfo | None = ..., + observation: global___ResponseObservation | None = ..., + action: global___ResponseAction | None = ..., + obs_action: global___ResponseObserverAction | None = ..., + step: global___ResponseStep | None = ..., + data: global___ResponseData | None = ..., + query: s2clientprotocol.query_pb2.ResponseQuery | None = ..., + save_replay: global___ResponseSaveReplay | None = ..., + replay_info: global___ResponseReplayInfo | None = ..., + available_maps: global___ResponseAvailableMaps | None = ..., + save_map: global___ResponseSaveMap | None = ..., + map_command: global___ResponseMapCommand | None = ..., + ping: global___ResponsePing | None = ..., + debug: global___ResponseDebug | None = ..., + id: builtins.int | None = ..., + error: collections.abc.Iterable[builtins.str] | None = ..., + status: global___Status.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "response", + b"response", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "status", + b"status", + "step", + b"step", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "error", + b"error", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "response", + b"response", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "status", + b"status", + "step", + b"step", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["response", b"response"] + ) -> ( + typing.Literal[ + "create_game", + "join_game", + "restart_game", + "start_replay", + "leave_game", + "quick_save", + "quick_load", + "quit", + "game_info", + "observation", + "action", + "obs_action", + "step", + "data", + "query", + "save_replay", + "replay_info", + "available_maps", + "save_map", + "map_command", + "ping", + "debug", + ] + | None + ): ... + +global___Response = Response + +@typing.final +class RequestCreateGame(google.protobuf.message.Message): + """----------------------------------------------------------------------------- + If successful, puts the game into the status: init_game. + The next expected request should be RequestJoinGame. Can also quit (exit). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOCAL_MAP_FIELD_NUMBER: builtins.int + BATTLENET_MAP_NAME_FIELD_NUMBER: builtins.int + PLAYER_SETUP_FIELD_NUMBER: builtins.int + DISABLE_FOG_FIELD_NUMBER: builtins.int + RANDOM_SEED_FIELD_NUMBER: builtins.int + REALTIME_FIELD_NUMBER: builtins.int + battlenet_map_name: builtins.str + """Map published to BattleNet""" + disable_fog: builtins.bool + random_seed: builtins.int + """Sets the pseudo-random seed for the game.""" + realtime: builtins.bool + """If set, the game plays in real time.""" + @property + def local_map(self) -> global___LocalMap: + """Local .SC2Map file""" + + @property + def player_setup(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerSetup]: ... + def __init__( + self, + *, + local_map: global___LocalMap | None = ..., + battlenet_map_name: builtins.str | None = ..., + player_setup: collections.abc.Iterable[global___PlayerSetup] | None = ..., + disable_fog: builtins.bool | None = ..., + random_seed: builtins.int | None = ..., + realtime: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "Map", + b"Map", + "battlenet_map_name", + b"battlenet_map_name", + "disable_fog", + b"disable_fog", + "local_map", + b"local_map", + "random_seed", + b"random_seed", + "realtime", + b"realtime", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "Map", + b"Map", + "battlenet_map_name", + b"battlenet_map_name", + "disable_fog", + b"disable_fog", + "local_map", + b"local_map", + "player_setup", + b"player_setup", + "random_seed", + b"random_seed", + "realtime", + b"realtime", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["Map", b"Map"] + ) -> typing.Literal["local_map", "battlenet_map_name"] | None: ... + +global___RequestCreateGame = RequestCreateGame + +@typing.final +class LocalMap(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_PATH_FIELD_NUMBER: builtins.int + MAP_DATA_FIELD_NUMBER: builtins.int + map_path: builtins.str + """A map can be specified either by a file path or the data of the .SC2Map file. + If you provide both, it will play the game using map_data and store map_path + into the replay. (260 character max) + """ + map_data: builtins.bytes + def __init__(self, *, map_path: builtins.str | None = ..., map_data: builtins.bytes | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> None: ... + +global___LocalMap = LocalMap + +@typing.final +class ResponseCreateGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseCreateGame._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingMap: ResponseCreateGame._Error.ValueType # 1 + InvalidMapPath: ResponseCreateGame._Error.ValueType # 2 + InvalidMapData: ResponseCreateGame._Error.ValueType # 3 + InvalidMapName: ResponseCreateGame._Error.ValueType # 4 + InvalidMapHandle: ResponseCreateGame._Error.ValueType # 5 + MissingPlayerSetup: ResponseCreateGame._Error.ValueType # 6 + InvalidPlayerSetup: ResponseCreateGame._Error.ValueType # 7 + MultiplayerUnsupported: ResponseCreateGame._Error.ValueType # 8 + """Multiplayer is not supported in the current build.""" + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingMap: ResponseCreateGame.Error.ValueType # 1 + InvalidMapPath: ResponseCreateGame.Error.ValueType # 2 + InvalidMapData: ResponseCreateGame.Error.ValueType # 3 + InvalidMapName: ResponseCreateGame.Error.ValueType # 4 + InvalidMapHandle: ResponseCreateGame.Error.ValueType # 5 + MissingPlayerSetup: ResponseCreateGame.Error.ValueType # 6 + InvalidPlayerSetup: ResponseCreateGame.Error.ValueType # 7 + MultiplayerUnsupported: ResponseCreateGame.Error.ValueType # 8 + """Multiplayer is not supported in the current build.""" + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + error: global___ResponseCreateGame.Error.ValueType + error_details: builtins.str + def __init__( + self, *, error: global___ResponseCreateGame.Error.ValueType | None = ..., error_details: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> None: ... + +global___ResponseCreateGame = ResponseCreateGame + +@typing.final +class RequestJoinGame(google.protobuf.message.Message): + """----------------------------------------------------------------------------- + If successful, puts the game into the status: in_game. Will be able to + request actions, observations and step the game. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RACE_FIELD_NUMBER: builtins.int + OBSERVED_PLAYER_ID_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + SERVER_PORTS_FIELD_NUMBER: builtins.int + CLIENT_PORTS_FIELD_NUMBER: builtins.int + SHARED_PORT_FIELD_NUMBER: builtins.int + PLAYER_NAME_FIELD_NUMBER: builtins.int + HOST_IP_FIELD_NUMBER: builtins.int + race: s2clientprotocol.common_pb2.Race.ValueType + """Join as participant""" + observed_player_id: builtins.int + """Join as observer""" + shared_port: builtins.int + """Currently only a singe client is supported. + deprecated + """ + player_name: builtins.str + """Use this to set the player's name to something other than autogenerated name.""" + host_ip: builtins.str + """Both game creator and joiner should provide the ip address of the game creator in order to play remotely. Defaults to localhost.""" + @property + def options(self) -> global___InterfaceOptions: + """This is limited to what is specified in RequestCreateGame, but you can request less information if you want.""" + + @property + def server_ports(self) -> global___PortSet: + """Do not set in the single-player case. This is the port a server will use.""" + + @property + def client_ports(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PortSet]: + """Do not set in the single-player case. These are the ports clients will use to initialize communication.""" + + def __init__( + self, + *, + race: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + observed_player_id: builtins.int | None = ..., + options: global___InterfaceOptions | None = ..., + server_ports: global___PortSet | None = ..., + client_ports: collections.abc.Iterable[global___PortSet] | None = ..., + shared_port: builtins.int | None = ..., + player_name: builtins.str | None = ..., + host_ip: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "host_ip", + b"host_ip", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "participation", + b"participation", + "player_name", + b"player_name", + "race", + b"race", + "server_ports", + b"server_ports", + "shared_port", + b"shared_port", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "client_ports", + b"client_ports", + "host_ip", + b"host_ip", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "participation", + b"participation", + "player_name", + b"player_name", + "race", + b"race", + "server_ports", + b"server_ports", + "shared_port", + b"shared_port", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["participation", b"participation"] + ) -> typing.Literal["race", "observed_player_id"] | None: ... + +global___RequestJoinGame = RequestJoinGame + +@typing.final +class PortSet(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GAME_PORT_FIELD_NUMBER: builtins.int + BASE_PORT_FIELD_NUMBER: builtins.int + game_port: builtins.int + """Game right now needs two internal ports to establish a multiplay game on the local host.""" + base_port: builtins.int + def __init__(self, *, game_port: builtins.int | None = ..., base_port: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["base_port", b"base_port", "game_port", b"game_port"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["base_port", b"base_port", "game_port", b"game_port"]) -> None: ... + +global___PortSet = PortSet + +@typing.final +class ResponseJoinGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseJoinGame._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingParticipation: ResponseJoinGame._Error.ValueType # 1 + InvalidObservedPlayerId: ResponseJoinGame._Error.ValueType # 2 + MissingOptions: ResponseJoinGame._Error.ValueType # 3 + MissingPorts: ResponseJoinGame._Error.ValueType # 4 + GameFull: ResponseJoinGame._Error.ValueType # 5 + LaunchError: ResponseJoinGame._Error.ValueType # 6 + FeatureUnsupported: ResponseJoinGame._Error.ValueType # 7 + """Multiplayer specific. + Multiplayer is not supported in the current build for the requested features. + """ + NoSpaceForUser: ResponseJoinGame._Error.ValueType # 8 + MapDoesNotExist: ResponseJoinGame._Error.ValueType # 9 + CannotOpenMap: ResponseJoinGame._Error.ValueType # 10 + ChecksumError: ResponseJoinGame._Error.ValueType # 11 + NetworkError: ResponseJoinGame._Error.ValueType # 12 + OtherError: ResponseJoinGame._Error.ValueType # 13 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingParticipation: ResponseJoinGame.Error.ValueType # 1 + InvalidObservedPlayerId: ResponseJoinGame.Error.ValueType # 2 + MissingOptions: ResponseJoinGame.Error.ValueType # 3 + MissingPorts: ResponseJoinGame.Error.ValueType # 4 + GameFull: ResponseJoinGame.Error.ValueType # 5 + LaunchError: ResponseJoinGame.Error.ValueType # 6 + FeatureUnsupported: ResponseJoinGame.Error.ValueType # 7 + """Multiplayer specific. + Multiplayer is not supported in the current build for the requested features. + """ + NoSpaceForUser: ResponseJoinGame.Error.ValueType # 8 + MapDoesNotExist: ResponseJoinGame.Error.ValueType # 9 + CannotOpenMap: ResponseJoinGame.Error.ValueType # 10 + ChecksumError: ResponseJoinGame.Error.ValueType # 11 + NetworkError: ResponseJoinGame.Error.ValueType # 12 + OtherError: ResponseJoinGame.Error.ValueType # 13 + + PLAYER_ID_FIELD_NUMBER: builtins.int + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + player_id: builtins.int + error: global___ResponseJoinGame.Error.ValueType + error_details: builtins.str + def __init__( + self, + *, + player_id: builtins.int | None = ..., + error: global___ResponseJoinGame.Error.ValueType | None = ..., + error_details: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["error", b"error", "error_details", b"error_details", "player_id", b"player_id"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["error", b"error", "error_details", b"error_details", "player_id", b"player_id"] + ) -> None: ... + +global___ResponseJoinGame = ResponseJoinGame + +@typing.final +class RequestRestartGame(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestRestartGame = RequestRestartGame + +@typing.final +class ResponseRestartGame(google.protobuf.message.Message): + """The defaultRestartGameLoops is specified to be (1<<18) by default""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseRestartGame._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + LaunchError: ResponseRestartGame._Error.ValueType # 1 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + LaunchError: ResponseRestartGame.Error.ValueType # 1 + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + NEED_HARD_RESET_FIELD_NUMBER: builtins.int + error: global___ResponseRestartGame.Error.ValueType + error_details: builtins.str + need_hard_reset: builtins.bool + """This will occur once the simulation_loop is greater then defaultRestartGameLoops""" + def __init__( + self, + *, + error: global___ResponseRestartGame.Error.ValueType | None = ..., + error_details: builtins.str | None = ..., + need_hard_reset: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["error", b"error", "error_details", b"error_details", "need_hard_reset", b"need_hard_reset"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal["error", b"error", "error_details", b"error_details", "need_hard_reset", b"need_hard_reset"], + ) -> None: ... + +global___ResponseRestartGame = ResponseRestartGame + +@typing.final +class RequestStartReplay(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLAY_PATH_FIELD_NUMBER: builtins.int + REPLAY_DATA_FIELD_NUMBER: builtins.int + MAP_DATA_FIELD_NUMBER: builtins.int + OBSERVED_PLAYER_ID_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + DISABLE_FOG_FIELD_NUMBER: builtins.int + REALTIME_FIELD_NUMBER: builtins.int + RECORD_REPLAY_FIELD_NUMBER: builtins.int + replay_path: builtins.str + replay_data: builtins.bytes + map_data: builtins.bytes + """Overrides the map path stored in the replay.""" + observed_player_id: builtins.int + disable_fog: builtins.bool + realtime: builtins.bool + record_replay: builtins.bool + """Allow RequestSaveReplay from a replay. Useful for truncating a replay, or restoring tracker.events.""" + @property + def options(self) -> global___InterfaceOptions: ... + def __init__( + self, + *, + replay_path: builtins.str | None = ..., + replay_data: builtins.bytes | None = ..., + map_data: builtins.bytes | None = ..., + observed_player_id: builtins.int | None = ..., + options: global___InterfaceOptions | None = ..., + disable_fog: builtins.bool | None = ..., + realtime: builtins.bool | None = ..., + record_replay: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "disable_fog", + b"disable_fog", + "map_data", + b"map_data", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "realtime", + b"realtime", + "record_replay", + b"record_replay", + "replay", + b"replay", + "replay_data", + b"replay_data", + "replay_path", + b"replay_path", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "disable_fog", + b"disable_fog", + "map_data", + b"map_data", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "realtime", + b"realtime", + "record_replay", + b"record_replay", + "replay", + b"replay", + "replay_data", + b"replay_data", + "replay_path", + b"replay_path", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["replay", b"replay"] + ) -> typing.Literal["replay_path", "replay_data"] | None: ... + +global___RequestStartReplay = RequestStartReplay + +@typing.final +class ResponseStartReplay(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseStartReplay._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingReplay: ResponseStartReplay._Error.ValueType # 1 + InvalidReplayPath: ResponseStartReplay._Error.ValueType # 2 + InvalidReplayData: ResponseStartReplay._Error.ValueType # 3 + InvalidMapData: ResponseStartReplay._Error.ValueType # 4 + InvalidObservedPlayerId: ResponseStartReplay._Error.ValueType # 5 + MissingOptions: ResponseStartReplay._Error.ValueType # 6 + LaunchError: ResponseStartReplay._Error.ValueType # 7 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingReplay: ResponseStartReplay.Error.ValueType # 1 + InvalidReplayPath: ResponseStartReplay.Error.ValueType # 2 + InvalidReplayData: ResponseStartReplay.Error.ValueType # 3 + InvalidMapData: ResponseStartReplay.Error.ValueType # 4 + InvalidObservedPlayerId: ResponseStartReplay.Error.ValueType # 5 + MissingOptions: ResponseStartReplay.Error.ValueType # 6 + LaunchError: ResponseStartReplay.Error.ValueType # 7 + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + error: global___ResponseStartReplay.Error.ValueType + error_details: builtins.str + def __init__( + self, *, error: global___ResponseStartReplay.Error.ValueType | None = ..., error_details: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> None: ... + +global___ResponseStartReplay = ResponseStartReplay + +@typing.final +class RequestMapCommand(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TRIGGER_CMD_FIELD_NUMBER: builtins.int + trigger_cmd: builtins.str + def __init__(self, *, trigger_cmd: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["trigger_cmd", b"trigger_cmd"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["trigger_cmd", b"trigger_cmd"]) -> None: ... + +global___RequestMapCommand = RequestMapCommand + +@typing.final +class ResponseMapCommand(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseMapCommand._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NoTriggerError: ResponseMapCommand._Error.ValueType # 1 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + NoTriggerError: ResponseMapCommand.Error.ValueType # 1 + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + error: global___ResponseMapCommand.Error.ValueType + error_details: builtins.str + def __init__( + self, *, error: global___ResponseMapCommand.Error.ValueType | None = ..., error_details: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> None: ... + +global___ResponseMapCommand = ResponseMapCommand + +@typing.final +class RequestLeaveGame(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestLeaveGame = RequestLeaveGame + +@typing.final +class ResponseLeaveGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseLeaveGame = ResponseLeaveGame + +@typing.final +class RequestQuickSave(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestQuickSave = RequestQuickSave + +@typing.final +class ResponseQuickSave(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseQuickSave = ResponseQuickSave + +@typing.final +class RequestQuickLoad(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestQuickLoad = RequestQuickLoad + +@typing.final +class ResponseQuickLoad(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseQuickLoad = ResponseQuickLoad + +@typing.final +class RequestQuit(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestQuit = RequestQuit + +@typing.final +class ResponseQuit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseQuit = ResponseQuit + +@typing.final +class RequestGameInfo(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestGameInfo = RequestGameInfo + +@typing.final +class ResponseGameInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_NAME_FIELD_NUMBER: builtins.int + MOD_NAMES_FIELD_NUMBER: builtins.int + LOCAL_MAP_PATH_FIELD_NUMBER: builtins.int + PLAYER_INFO_FIELD_NUMBER: builtins.int + START_RAW_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + map_name: builtins.str + local_map_path: builtins.str + @property + def mod_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + @property + def player_info(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerInfo]: ... + @property + def start_raw(self) -> s2clientprotocol.raw_pb2.StartRaw: + """Populated if Raw interface is enabled.""" + + @property + def options(self) -> global___InterfaceOptions: ... + def __init__( + self, + *, + map_name: builtins.str | None = ..., + mod_names: collections.abc.Iterable[builtins.str] | None = ..., + local_map_path: builtins.str | None = ..., + player_info: collections.abc.Iterable[global___PlayerInfo] | None = ..., + start_raw: s2clientprotocol.raw_pb2.StartRaw | None = ..., + options: global___InterfaceOptions | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "local_map_path", b"local_map_path", "map_name", b"map_name", "options", b"options", "start_raw", b"start_raw" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "local_map_path", + b"local_map_path", + "map_name", + b"map_name", + "mod_names", + b"mod_names", + "options", + b"options", + "player_info", + b"player_info", + "start_raw", + b"start_raw", + ], + ) -> None: ... + +global___ResponseGameInfo = ResponseGameInfo + +@typing.final +class RequestObservation(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DISABLE_FOG_FIELD_NUMBER: builtins.int + GAME_LOOP_FIELD_NUMBER: builtins.int + disable_fog: builtins.bool + game_loop: builtins.int + """In realtime the request will only return once the simulation game loop has reached this value. When not realtime this value is ignored.""" + def __init__(self, *, disable_fog: builtins.bool | None = ..., game_loop: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["disable_fog", b"disable_fog", "game_loop", b"game_loop"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["disable_fog", b"disable_fog", "game_loop", b"game_loop"]) -> None: ... + +global___RequestObservation = RequestObservation + +@typing.final +class ResponseObservation(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTIONS_FIELD_NUMBER: builtins.int + ACTION_ERRORS_FIELD_NUMBER: builtins.int + OBSERVATION_FIELD_NUMBER: builtins.int + PLAYER_RESULT_FIELD_NUMBER: builtins.int + CHAT_FIELD_NUMBER: builtins.int + @property + def actions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Action]: + """Actions this player did since the last Observation.""" + + @property + def action_errors(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ActionError]: + """Equivalent of UI "red text" errors.""" + + @property + def observation(self) -> global___Observation: ... + @property + def player_result(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerResult]: + """Only populated if the game ended during this step.""" + + @property + def chat(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ChatReceived]: ... + def __init__( + self, + *, + actions: collections.abc.Iterable[global___Action] | None = ..., + action_errors: collections.abc.Iterable[global___ActionError] | None = ..., + observation: global___Observation | None = ..., + player_result: collections.abc.Iterable[global___PlayerResult] | None = ..., + chat: collections.abc.Iterable[global___ChatReceived] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["observation", b"observation"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action_errors", + b"action_errors", + "actions", + b"actions", + "chat", + b"chat", + "observation", + b"observation", + "player_result", + b"player_result", + ], + ) -> None: ... + +global___ResponseObservation = ResponseObservation + +@typing.final +class ChatReceived(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + player_id: builtins.int + message: builtins.str + def __init__(self, *, player_id: builtins.int | None = ..., message: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["message", b"message", "player_id", b"player_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["message", b"message", "player_id", b"player_id"]) -> None: ... + +global___ChatReceived = ChatReceived + +@typing.final +class RequestAction(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTIONS_FIELD_NUMBER: builtins.int + @property + def actions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Action]: ... + def __init__(self, *, actions: collections.abc.Iterable[global___Action] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["actions", b"actions"]) -> None: ... + +global___RequestAction = RequestAction + +@typing.final +class ResponseAction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RESULT_FIELD_NUMBER: builtins.int + @property + def result( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[s2clientprotocol.error_pb2.ActionResult.ValueType]: ... + def __init__( + self, *, result: collections.abc.Iterable[s2clientprotocol.error_pb2.ActionResult.ValueType] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["result", b"result"]) -> None: ... + +global___ResponseAction = ResponseAction + +@typing.final +class RequestObserverAction(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTIONS_FIELD_NUMBER: builtins.int + @property + def actions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ObserverAction]: ... + def __init__(self, *, actions: collections.abc.Iterable[global___ObserverAction] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["actions", b"actions"]) -> None: ... + +global___RequestObserverAction = RequestObserverAction + +@typing.final +class ResponseObserverAction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseObserverAction = ResponseObserverAction + +@typing.final +class RequestStep(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COUNT_FIELD_NUMBER: builtins.int + count: builtins.int + """Number of game loops to simulate for the next frame.""" + def __init__(self, *, count: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["count", b"count"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["count", b"count"]) -> None: ... + +global___RequestStep = RequestStep + +@typing.final +class ResponseStep(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SIMULATION_LOOP_FIELD_NUMBER: builtins.int + simulation_loop: builtins.int + """ Max simulation_loop is (1<<19) before "end of time" will occur + The "end of time" is classified as the maximum number of game loops or absolute game time + representable as a positive fixed point number. + When we reach the "end of time", permanently pause the game and end the game for all. + """ + def __init__(self, *, simulation_loop: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["simulation_loop", b"simulation_loop"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["simulation_loop", b"simulation_loop"]) -> None: ... + +global___ResponseStep = ResponseStep + +@typing.final +class RequestData(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + UNIT_TYPE_ID_FIELD_NUMBER: builtins.int + UPGRADE_ID_FIELD_NUMBER: builtins.int + BUFF_ID_FIELD_NUMBER: builtins.int + EFFECT_ID_FIELD_NUMBER: builtins.int + ability_id: builtins.bool + unit_type_id: builtins.bool + upgrade_id: builtins.bool + buff_id: builtins.bool + effect_id: builtins.bool + def __init__( + self, + *, + ability_id: builtins.bool | None = ..., + unit_type_id: builtins.bool | None = ..., + upgrade_id: builtins.bool | None = ..., + buff_id: builtins.bool | None = ..., + effect_id: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "buff_id", + b"buff_id", + "effect_id", + b"effect_id", + "unit_type_id", + b"unit_type_id", + "upgrade_id", + b"upgrade_id", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "buff_id", + b"buff_id", + "effect_id", + b"effect_id", + "unit_type_id", + b"unit_type_id", + "upgrade_id", + b"upgrade_id", + ], + ) -> None: ... + +global___RequestData = RequestData + +@typing.final +class ResponseData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITIES_FIELD_NUMBER: builtins.int + UNITS_FIELD_NUMBER: builtins.int + UPGRADES_FIELD_NUMBER: builtins.int + BUFFS_FIELD_NUMBER: builtins.int + EFFECTS_FIELD_NUMBER: builtins.int + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.AbilityData]: ... + @property + def units( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.UnitTypeData]: ... + @property + def upgrades( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.UpgradeData]: ... + @property + def buffs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.BuffData]: ... + @property + def effects( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.EffectData]: ... + def __init__( + self, + *, + abilities: collections.abc.Iterable[s2clientprotocol.data_pb2.AbilityData] | None = ..., + units: collections.abc.Iterable[s2clientprotocol.data_pb2.UnitTypeData] | None = ..., + upgrades: collections.abc.Iterable[s2clientprotocol.data_pb2.UpgradeData] | None = ..., + buffs: collections.abc.Iterable[s2clientprotocol.data_pb2.BuffData] | None = ..., + effects: collections.abc.Iterable[s2clientprotocol.data_pb2.EffectData] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "abilities", b"abilities", "buffs", b"buffs", "effects", b"effects", "units", b"units", "upgrades", b"upgrades" + ], + ) -> None: ... + +global___ResponseData = ResponseData + +@typing.final +class RequestSaveReplay(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestSaveReplay = RequestSaveReplay + +@typing.final +class ResponseSaveReplay(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DATA_FIELD_NUMBER: builtins.int + data: builtins.bytes + def __init__(self, *, data: builtins.bytes | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["data", b"data"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["data", b"data"]) -> None: ... + +global___ResponseSaveReplay = ResponseSaveReplay + +@typing.final +class RequestReplayInfo(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLAY_PATH_FIELD_NUMBER: builtins.int + REPLAY_DATA_FIELD_NUMBER: builtins.int + DOWNLOAD_DATA_FIELD_NUMBER: builtins.int + replay_path: builtins.str + """Limitation: might fail if the replay file is currently loaded.""" + replay_data: builtins.bytes + download_data: builtins.bool + """Ensure the data and binary are downloaded if this is an old version replay.""" + def __init__( + self, + *, + replay_path: builtins.str | None = ..., + replay_data: builtins.bytes | None = ..., + download_data: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "download_data", b"download_data", "replay", b"replay", "replay_data", b"replay_data", "replay_path", b"replay_path" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "download_data", b"download_data", "replay", b"replay", "replay_data", b"replay_data", "replay_path", b"replay_path" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["replay", b"replay"] + ) -> typing.Literal["replay_path", "replay_data"] | None: ... + +global___RequestReplayInfo = RequestReplayInfo + +@typing.final +class PlayerInfoExtra(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_INFO_FIELD_NUMBER: builtins.int + PLAYER_RESULT_FIELD_NUMBER: builtins.int + PLAYER_MMR_FIELD_NUMBER: builtins.int + PLAYER_APM_FIELD_NUMBER: builtins.int + player_mmr: builtins.int + player_apm: builtins.int + @property + def player_info(self) -> global___PlayerInfo: ... + @property + def player_result(self) -> global___PlayerResult: ... + def __init__( + self, + *, + player_info: global___PlayerInfo | None = ..., + player_result: global___PlayerResult | None = ..., + player_mmr: builtins.int | None = ..., + player_apm: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "player_apm", + b"player_apm", + "player_info", + b"player_info", + "player_mmr", + b"player_mmr", + "player_result", + b"player_result", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "player_apm", + b"player_apm", + "player_info", + b"player_info", + "player_mmr", + b"player_mmr", + "player_result", + b"player_result", + ], + ) -> None: ... + +global___PlayerInfoExtra = PlayerInfoExtra + +@typing.final +class ResponseReplayInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseReplayInfo._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingReplay: ResponseReplayInfo._Error.ValueType # 1 + InvalidReplayPath: ResponseReplayInfo._Error.ValueType # 2 + InvalidReplayData: ResponseReplayInfo._Error.ValueType # 3 + ParsingError: ResponseReplayInfo._Error.ValueType # 4 + DownloadError: ResponseReplayInfo._Error.ValueType # 5 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingReplay: ResponseReplayInfo.Error.ValueType # 1 + InvalidReplayPath: ResponseReplayInfo.Error.ValueType # 2 + InvalidReplayData: ResponseReplayInfo.Error.ValueType # 3 + ParsingError: ResponseReplayInfo.Error.ValueType # 4 + DownloadError: ResponseReplayInfo.Error.ValueType # 5 + + MAP_NAME_FIELD_NUMBER: builtins.int + LOCAL_MAP_PATH_FIELD_NUMBER: builtins.int + PLAYER_INFO_FIELD_NUMBER: builtins.int + GAME_DURATION_LOOPS_FIELD_NUMBER: builtins.int + GAME_DURATION_SECONDS_FIELD_NUMBER: builtins.int + GAME_VERSION_FIELD_NUMBER: builtins.int + DATA_VERSION_FIELD_NUMBER: builtins.int + DATA_BUILD_FIELD_NUMBER: builtins.int + BASE_BUILD_FIELD_NUMBER: builtins.int + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + map_name: builtins.str + local_map_path: builtins.str + game_duration_loops: builtins.int + game_duration_seconds: builtins.float + game_version: builtins.str + data_version: builtins.str + data_build: builtins.int + base_build: builtins.int + error: global___ResponseReplayInfo.Error.ValueType + error_details: builtins.str + @property + def player_info(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerInfoExtra]: ... + def __init__( + self, + *, + map_name: builtins.str | None = ..., + local_map_path: builtins.str | None = ..., + player_info: collections.abc.Iterable[global___PlayerInfoExtra] | None = ..., + game_duration_loops: builtins.int | None = ..., + game_duration_seconds: builtins.float | None = ..., + game_version: builtins.str | None = ..., + data_version: builtins.str | None = ..., + data_build: builtins.int | None = ..., + base_build: builtins.int | None = ..., + error: global___ResponseReplayInfo.Error.ValueType | None = ..., + error_details: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "error", + b"error", + "error_details", + b"error_details", + "game_duration_loops", + b"game_duration_loops", + "game_duration_seconds", + b"game_duration_seconds", + "game_version", + b"game_version", + "local_map_path", + b"local_map_path", + "map_name", + b"map_name", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "error", + b"error", + "error_details", + b"error_details", + "game_duration_loops", + b"game_duration_loops", + "game_duration_seconds", + b"game_duration_seconds", + "game_version", + b"game_version", + "local_map_path", + b"local_map_path", + "map_name", + b"map_name", + "player_info", + b"player_info", + ], + ) -> None: ... + +global___ResponseReplayInfo = ResponseReplayInfo + +@typing.final +class RequestAvailableMaps(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestAvailableMaps = RequestAvailableMaps + +@typing.final +class ResponseAvailableMaps(google.protobuf.message.Message): + """This will only contain locally cached BattleNet maps. + To download all ladder maps, log in and queue into a ladder match. + To download any other map, play a custom game on that map. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOCAL_MAP_PATHS_FIELD_NUMBER: builtins.int + BATTLENET_MAP_NAMES_FIELD_NUMBER: builtins.int + @property + def local_map_paths(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """All the maps in the "Maps/" directory.""" + + @property + def battlenet_map_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """All the maps in the BattleNet cache.""" + + def __init__( + self, + *, + local_map_paths: collections.abc.Iterable[builtins.str] | None = ..., + battlenet_map_names: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["battlenet_map_names", b"battlenet_map_names", "local_map_paths", b"local_map_paths"] + ) -> None: ... + +global___ResponseAvailableMaps = ResponseAvailableMaps + +@typing.final +class RequestSaveMap(google.protobuf.message.Message): + """----------------------------------------------------------------------------- + Copies map data into the path specified. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_PATH_FIELD_NUMBER: builtins.int + MAP_DATA_FIELD_NUMBER: builtins.int + map_path: builtins.str + """Path the game process will write to, relative to the temp directory. (260 character max)""" + map_data: builtins.bytes + """Binary map data of a .SC2Map.""" + def __init__(self, *, map_path: builtins.str | None = ..., map_data: builtins.bytes | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> None: ... + +global___RequestSaveMap = RequestSaveMap + +@typing.final +class ResponseSaveMap(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseSaveMap._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + InvalidMapData: ResponseSaveMap._Error.ValueType # 1 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + InvalidMapData: ResponseSaveMap.Error.ValueType # 1 + + ERROR_FIELD_NUMBER: builtins.int + error: global___ResponseSaveMap.Error.ValueType + def __init__(self, *, error: global___ResponseSaveMap.Error.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error"]) -> None: ... + +global___ResponseSaveMap = ResponseSaveMap + +@typing.final +class RequestPing(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestPing = RequestPing + +@typing.final +class ResponsePing(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GAME_VERSION_FIELD_NUMBER: builtins.int + DATA_VERSION_FIELD_NUMBER: builtins.int + DATA_BUILD_FIELD_NUMBER: builtins.int + BASE_BUILD_FIELD_NUMBER: builtins.int + game_version: builtins.str + data_version: builtins.str + data_build: builtins.int + base_build: builtins.int + def __init__( + self, + *, + game_version: builtins.str | None = ..., + data_version: builtins.str | None = ..., + data_build: builtins.int | None = ..., + base_build: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "game_version", + b"game_version", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "game_version", + b"game_version", + ], + ) -> None: ... + +global___ResponsePing = ResponsePing + +@typing.final +class RequestDebug(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEBUG_FIELD_NUMBER: builtins.int + @property + def debug( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.debug_pb2.DebugCommand]: ... + def __init__(self, *, debug: collections.abc.Iterable[s2clientprotocol.debug_pb2.DebugCommand] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["debug", b"debug"]) -> None: ... + +global___RequestDebug = RequestDebug + +@typing.final +class ResponseDebug(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseDebug = ResponseDebug + +@typing.final +class PlayerSetup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TYPE_FIELD_NUMBER: builtins.int + RACE_FIELD_NUMBER: builtins.int + DIFFICULTY_FIELD_NUMBER: builtins.int + PLAYER_NAME_FIELD_NUMBER: builtins.int + AI_BUILD_FIELD_NUMBER: builtins.int + type: global___PlayerType.ValueType + race: s2clientprotocol.common_pb2.Race.ValueType + """Only used for a computer player.""" + difficulty: global___Difficulty.ValueType + player_name: builtins.str + ai_build: global___AIBuild.ValueType + def __init__( + self, + *, + type: global___PlayerType.ValueType | None = ..., + race: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + difficulty: global___Difficulty.ValueType | None = ..., + player_name: builtins.str | None = ..., + ai_build: global___AIBuild.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ai_build", b"ai_build", "difficulty", b"difficulty", "player_name", b"player_name", "race", b"race", "type", b"type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ai_build", b"ai_build", "difficulty", b"difficulty", "player_name", b"player_name", "race", b"race", "type", b"type" + ], + ) -> None: ... + +global___PlayerSetup = PlayerSetup + +@typing.final +class SpatialCameraSetup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RESOLUTION_FIELD_NUMBER: builtins.int + MINIMAP_RESOLUTION_FIELD_NUMBER: builtins.int + WIDTH_FIELD_NUMBER: builtins.int + CROP_TO_PLAYABLE_AREA_FIELD_NUMBER: builtins.int + ALLOW_CHEATING_LAYERS_FIELD_NUMBER: builtins.int + width: builtins.float + """Below are only relevant for feature layers. + Set the screen camera width in world units. + """ + crop_to_playable_area: builtins.bool + """Crop minimap to the playable area.""" + allow_cheating_layers: builtins.bool + """Return unit_type on the minimap, and potentially other cheating layers.""" + @property + def resolution(self) -> s2clientprotocol.common_pb2.Size2DI: ... + @property + def minimap_resolution(self) -> s2clientprotocol.common_pb2.Size2DI: ... + def __init__( + self, + *, + resolution: s2clientprotocol.common_pb2.Size2DI | None = ..., + minimap_resolution: s2clientprotocol.common_pb2.Size2DI | None = ..., + width: builtins.float | None = ..., + crop_to_playable_area: builtins.bool | None = ..., + allow_cheating_layers: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "allow_cheating_layers", + b"allow_cheating_layers", + "crop_to_playable_area", + b"crop_to_playable_area", + "minimap_resolution", + b"minimap_resolution", + "resolution", + b"resolution", + "width", + b"width", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "allow_cheating_layers", + b"allow_cheating_layers", + "crop_to_playable_area", + b"crop_to_playable_area", + "minimap_resolution", + b"minimap_resolution", + "resolution", + b"resolution", + "width", + b"width", + ], + ) -> None: ... + +global___SpatialCameraSetup = SpatialCameraSetup + +@typing.final +class InterfaceOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RAW_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + FEATURE_LAYER_FIELD_NUMBER: builtins.int + RENDER_FIELD_NUMBER: builtins.int + SHOW_CLOAKED_FIELD_NUMBER: builtins.int + SHOW_BURROWED_SHADOWS_FIELD_NUMBER: builtins.int + SHOW_PLACEHOLDERS_FIELD_NUMBER: builtins.int + RAW_AFFECTS_SELECTION_FIELD_NUMBER: builtins.int + RAW_CROP_TO_PLAYABLE_AREA_FIELD_NUMBER: builtins.int + raw: builtins.bool + """Interface options""" + score: builtins.bool + show_cloaked: builtins.bool + """By default cloaked units are completely hidden. This shows some details.""" + show_burrowed_shadows: builtins.bool + """By default burrowed units are completely hidden. This shows some details for those that produce a shadow.""" + show_placeholders: builtins.bool + """Return placeholder units (buildings to be constructed), both for raw and feature layers.""" + raw_affects_selection: builtins.bool + """By default raw actions select, act and revert the selection. This is useful + if you're playing simultaneously with the agent so it doesn't steal your + selection. This inflates APM (due to deselect) and makes the actions hard + to follow in a replay. Setting this to true will cause raw actions to do + select, act, but not revert the selection. + """ + raw_crop_to_playable_area: builtins.bool + """Changes the coordinates in raw.proto to be relative to the playable area. + The map_size and playable_area will be the diagonal of the real playable area. + """ + @property + def feature_layer(self) -> global___SpatialCameraSetup: + """Omit to disable.""" + + @property + def render(self) -> global___SpatialCameraSetup: + """Omit to disable.""" + + def __init__( + self, + *, + raw: builtins.bool | None = ..., + score: builtins.bool | None = ..., + feature_layer: global___SpatialCameraSetup | None = ..., + render: global___SpatialCameraSetup | None = ..., + show_cloaked: builtins.bool | None = ..., + show_burrowed_shadows: builtins.bool | None = ..., + show_placeholders: builtins.bool | None = ..., + raw_affects_selection: builtins.bool | None = ..., + raw_crop_to_playable_area: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "feature_layer", + b"feature_layer", + "raw", + b"raw", + "raw_affects_selection", + b"raw_affects_selection", + "raw_crop_to_playable_area", + b"raw_crop_to_playable_area", + "render", + b"render", + "score", + b"score", + "show_burrowed_shadows", + b"show_burrowed_shadows", + "show_cloaked", + b"show_cloaked", + "show_placeholders", + b"show_placeholders", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "feature_layer", + b"feature_layer", + "raw", + b"raw", + "raw_affects_selection", + b"raw_affects_selection", + "raw_crop_to_playable_area", + b"raw_crop_to_playable_area", + "render", + b"render", + "score", + b"score", + "show_burrowed_shadows", + b"show_burrowed_shadows", + "show_cloaked", + b"show_cloaked", + "show_placeholders", + b"show_placeholders", + ], + ) -> None: ... + +global___InterfaceOptions = InterfaceOptions + +@typing.final +class PlayerInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + RACE_REQUESTED_FIELD_NUMBER: builtins.int + RACE_ACTUAL_FIELD_NUMBER: builtins.int + DIFFICULTY_FIELD_NUMBER: builtins.int + AI_BUILD_FIELD_NUMBER: builtins.int + PLAYER_NAME_FIELD_NUMBER: builtins.int + player_id: builtins.int + """Identifier that will be used to reference this player. + SC2 will always assign playerIds starting from 1 in standard Melee maps. This may not be true in custom maps. + """ + type: global___PlayerType.ValueType + race_requested: s2clientprotocol.common_pb2.Race.ValueType + race_actual: s2clientprotocol.common_pb2.Race.ValueType + """Only populated for your player or when watching replay""" + difficulty: global___Difficulty.ValueType + ai_build: global___AIBuild.ValueType + player_name: builtins.str + def __init__( + self, + *, + player_id: builtins.int | None = ..., + type: global___PlayerType.ValueType | None = ..., + race_requested: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + race_actual: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + difficulty: global___Difficulty.ValueType | None = ..., + ai_build: global___AIBuild.ValueType | None = ..., + player_name: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ai_build", + b"ai_build", + "difficulty", + b"difficulty", + "player_id", + b"player_id", + "player_name", + b"player_name", + "race_actual", + b"race_actual", + "race_requested", + b"race_requested", + "type", + b"type", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ai_build", + b"ai_build", + "difficulty", + b"difficulty", + "player_id", + b"player_id", + "player_name", + b"player_name", + "race_actual", + b"race_actual", + "race_requested", + b"race_requested", + "type", + b"type", + ], + ) -> None: ... + +global___PlayerInfo = PlayerInfo + +@typing.final +class PlayerCommon(google.protobuf.message.Message): + """ + During Game + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + MINERALS_FIELD_NUMBER: builtins.int + VESPENE_FIELD_NUMBER: builtins.int + FOOD_CAP_FIELD_NUMBER: builtins.int + FOOD_USED_FIELD_NUMBER: builtins.int + FOOD_ARMY_FIELD_NUMBER: builtins.int + FOOD_WORKERS_FIELD_NUMBER: builtins.int + IDLE_WORKER_COUNT_FIELD_NUMBER: builtins.int + ARMY_COUNT_FIELD_NUMBER: builtins.int + WARP_GATE_COUNT_FIELD_NUMBER: builtins.int + LARVA_COUNT_FIELD_NUMBER: builtins.int + player_id: builtins.int + minerals: builtins.int + vespene: builtins.int + food_cap: builtins.int + food_used: builtins.int + food_army: builtins.int + food_workers: builtins.int + idle_worker_count: builtins.int + army_count: builtins.int + warp_gate_count: builtins.int + larva_count: builtins.int + def __init__( + self, + *, + player_id: builtins.int | None = ..., + minerals: builtins.int | None = ..., + vespene: builtins.int | None = ..., + food_cap: builtins.int | None = ..., + food_used: builtins.int | None = ..., + food_army: builtins.int | None = ..., + food_workers: builtins.int | None = ..., + idle_worker_count: builtins.int | None = ..., + army_count: builtins.int | None = ..., + warp_gate_count: builtins.int | None = ..., + larva_count: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "army_count", + b"army_count", + "food_army", + b"food_army", + "food_cap", + b"food_cap", + "food_used", + b"food_used", + "food_workers", + b"food_workers", + "idle_worker_count", + b"idle_worker_count", + "larva_count", + b"larva_count", + "minerals", + b"minerals", + "player_id", + b"player_id", + "vespene", + b"vespene", + "warp_gate_count", + b"warp_gate_count", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "army_count", + b"army_count", + "food_army", + b"food_army", + "food_cap", + b"food_cap", + "food_used", + b"food_used", + "food_workers", + b"food_workers", + "idle_worker_count", + b"idle_worker_count", + "larva_count", + b"larva_count", + "minerals", + b"minerals", + "player_id", + b"player_id", + "vespene", + b"vespene", + "warp_gate_count", + b"warp_gate_count", + ], + ) -> None: ... + +global___PlayerCommon = PlayerCommon + +@typing.final +class Observation(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GAME_LOOP_FIELD_NUMBER: builtins.int + PLAYER_COMMON_FIELD_NUMBER: builtins.int + ALERTS_FIELD_NUMBER: builtins.int + ABILITIES_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + RAW_DATA_FIELD_NUMBER: builtins.int + FEATURE_LAYER_DATA_FIELD_NUMBER: builtins.int + RENDER_DATA_FIELD_NUMBER: builtins.int + UI_DATA_FIELD_NUMBER: builtins.int + game_loop: builtins.int + @property + def player_common(self) -> global___PlayerCommon: ... + @property + def alerts(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___Alert.ValueType]: ... + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.AvailableAbility]: + """Abilities available in the selection. Enabled if in this list, disabled otherwise.""" + + @property + def score(self) -> s2clientprotocol.score_pb2.Score: ... + @property + def raw_data(self) -> s2clientprotocol.raw_pb2.ObservationRaw: + """Populated if Raw interface is enabled.""" + + @property + def feature_layer_data(self) -> s2clientprotocol.spatial_pb2.ObservationFeatureLayer: + """Populated if Feature Layer interface is enabled.""" + + @property + def render_data(self) -> s2clientprotocol.spatial_pb2.ObservationRender: + """Populated if Render interface is enabled.""" + + @property + def ui_data(self) -> s2clientprotocol.ui_pb2.ObservationUI: + """Populated if Feature Layer or Render interface is enabled.""" + + def __init__( + self, + *, + game_loop: builtins.int | None = ..., + player_common: global___PlayerCommon | None = ..., + alerts: collections.abc.Iterable[global___Alert.ValueType] | None = ..., + abilities: collections.abc.Iterable[s2clientprotocol.common_pb2.AvailableAbility] | None = ..., + score: s2clientprotocol.score_pb2.Score | None = ..., + raw_data: s2clientprotocol.raw_pb2.ObservationRaw | None = ..., + feature_layer_data: s2clientprotocol.spatial_pb2.ObservationFeatureLayer | None = ..., + render_data: s2clientprotocol.spatial_pb2.ObservationRender | None = ..., + ui_data: s2clientprotocol.ui_pb2.ObservationUI | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "feature_layer_data", + b"feature_layer_data", + "game_loop", + b"game_loop", + "player_common", + b"player_common", + "raw_data", + b"raw_data", + "render_data", + b"render_data", + "score", + b"score", + "ui_data", + b"ui_data", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "abilities", + b"abilities", + "alerts", + b"alerts", + "feature_layer_data", + b"feature_layer_data", + "game_loop", + b"game_loop", + "player_common", + b"player_common", + "raw_data", + b"raw_data", + "render_data", + b"render_data", + "score", + b"score", + "ui_data", + b"ui_data", + ], + ) -> None: ... + +global___Observation = Observation + +@typing.final +class Action(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTION_RAW_FIELD_NUMBER: builtins.int + ACTION_FEATURE_LAYER_FIELD_NUMBER: builtins.int + ACTION_RENDER_FIELD_NUMBER: builtins.int + ACTION_UI_FIELD_NUMBER: builtins.int + ACTION_CHAT_FIELD_NUMBER: builtins.int + GAME_LOOP_FIELD_NUMBER: builtins.int + game_loop: builtins.int + """Populated for actions in ResponseObservation. The game loop on which the action was executed.""" + @property + def action_raw(self) -> s2clientprotocol.raw_pb2.ActionRaw: + """Populated if Raw interface is enabled.""" + + @property + def action_feature_layer(self) -> s2clientprotocol.spatial_pb2.ActionSpatial: + """Populated if Feature Layer interface is enabled.""" + + @property + def action_render(self) -> s2clientprotocol.spatial_pb2.ActionSpatial: + """Not implemented. Populated if Render interface is enabled.""" + + @property + def action_ui(self) -> s2clientprotocol.ui_pb2.ActionUI: + """Populated if Feature Layer or Render interface is enabled.""" + + @property + def action_chat(self) -> global___ActionChat: + """Chat messages as a player typing into the chat channel.""" + + def __init__( + self, + *, + action_raw: s2clientprotocol.raw_pb2.ActionRaw | None = ..., + action_feature_layer: s2clientprotocol.spatial_pb2.ActionSpatial | None = ..., + action_render: s2clientprotocol.spatial_pb2.ActionSpatial | None = ..., + action_ui: s2clientprotocol.ui_pb2.ActionUI | None = ..., + action_chat: global___ActionChat | None = ..., + game_loop: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action_chat", + b"action_chat", + "action_feature_layer", + b"action_feature_layer", + "action_raw", + b"action_raw", + "action_render", + b"action_render", + "action_ui", + b"action_ui", + "game_loop", + b"game_loop", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action_chat", + b"action_chat", + "action_feature_layer", + b"action_feature_layer", + "action_raw", + b"action_raw", + "action_render", + b"action_render", + "action_ui", + b"action_ui", + "game_loop", + b"game_loop", + ], + ) -> None: ... + +global___Action = Action + +@typing.final +class ActionChat(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Channel: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ChannelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionChat._Channel.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Broadcast: ActionChat._Channel.ValueType # 1 + Team: ActionChat._Channel.ValueType # 2 + + class Channel(_Channel, metaclass=_ChannelEnumTypeWrapper): ... + Broadcast: ActionChat.Channel.ValueType # 1 + Team: ActionChat.Channel.ValueType # 2 + + CHANNEL_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + channel: global___ActionChat.Channel.ValueType + message: builtins.str + def __init__( + self, *, channel: global___ActionChat.Channel.ValueType | None = ..., message: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["channel", b"channel", "message", b"message"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["channel", b"channel", "message", b"message"]) -> None: ... + +global___ActionChat = ActionChat + +@typing.final +class ActionError(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TAG_FIELD_NUMBER: builtins.int + ABILITY_ID_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + """Only populated when using raw interface.""" + ability_id: builtins.int + result: s2clientprotocol.error_pb2.ActionResult.ValueType + def __init__( + self, + *, + unit_tag: builtins.int | None = ..., + ability_id: builtins.int | None = ..., + result: s2clientprotocol.error_pb2.ActionResult.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["ability_id", b"ability_id", "result", b"result", "unit_tag", b"unit_tag"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["ability_id", b"ability_id", "result", b"result", "unit_tag", b"unit_tag"] + ) -> None: ... + +global___ActionError = ActionError + +@typing.final +class ObserverAction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_PERSPECTIVE_FIELD_NUMBER: builtins.int + CAMERA_MOVE_FIELD_NUMBER: builtins.int + CAMERA_FOLLOW_PLAYER_FIELD_NUMBER: builtins.int + CAMERA_FOLLOW_UNITS_FIELD_NUMBER: builtins.int + @property + def player_perspective(self) -> global___ActionObserverPlayerPerspective: + """Not implemented""" + + @property + def camera_move(self) -> global___ActionObserverCameraMove: ... + @property + def camera_follow_player(self) -> global___ActionObserverCameraFollowPlayer: ... + @property + def camera_follow_units(self) -> global___ActionObserverCameraFollowUnits: + """Not implemented""" + + def __init__( + self, + *, + player_perspective: global___ActionObserverPlayerPerspective | None = ..., + camera_move: global___ActionObserverCameraMove | None = ..., + camera_follow_player: global___ActionObserverCameraFollowPlayer | None = ..., + camera_follow_units: global___ActionObserverCameraFollowUnits | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_follow_player", + b"camera_follow_player", + "camera_follow_units", + b"camera_follow_units", + "camera_move", + b"camera_move", + "player_perspective", + b"player_perspective", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_follow_player", + b"camera_follow_player", + "camera_follow_units", + b"camera_follow_units", + "camera_move", + b"camera_move", + "player_perspective", + b"player_perspective", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> typing.Literal["player_perspective", "camera_move", "camera_follow_player", "camera_follow_units"] | None: ... + +global___ObserverAction = ObserverAction + +@typing.final +class ActionObserverPlayerPerspective(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + player_id: builtins.int + """0 to observe "Everyone" """ + def __init__(self, *, player_id: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["player_id", b"player_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["player_id", b"player_id"]) -> None: ... + +global___ActionObserverPlayerPerspective = ActionObserverPlayerPerspective + +@typing.final +class ActionObserverCameraMove(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + WORLD_POS_FIELD_NUMBER: builtins.int + DISTANCE_FIELD_NUMBER: builtins.int + distance: builtins.float + """Distance between camera and terrain. Larger value zooms out camera. + Defaults to standard camera distance if set to 0. + """ + @property + def world_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, *, world_pos: s2clientprotocol.common_pb2.Point2D | None = ..., distance: builtins.float | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["distance", b"distance", "world_pos", b"world_pos"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["distance", b"distance", "world_pos", b"world_pos"]) -> None: ... + +global___ActionObserverCameraMove = ActionObserverCameraMove + +@typing.final +class ActionObserverCameraFollowPlayer(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + player_id: builtins.int + """Not implemented. Value must be [1, 15]""" + def __init__(self, *, player_id: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["player_id", b"player_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["player_id", b"player_id"]) -> None: ... + +global___ActionObserverCameraFollowPlayer = ActionObserverCameraFollowPlayer + +@typing.final +class ActionObserverCameraFollowUnits(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TAGS_FIELD_NUMBER: builtins.int + @property + def unit_tags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, unit_tags: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["unit_tags", b"unit_tags"]) -> None: ... + +global___ActionObserverCameraFollowUnits = ActionObserverCameraFollowUnits + +@typing.final +class PlayerResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + player_id: builtins.int + result: global___Result.ValueType + def __init__(self, *, player_id: builtins.int | None = ..., result: global___Result.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["player_id", b"player_id", "result", b"result"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["player_id", b"player_id", "result", b"result"]) -> None: ... + +global___PlayerResult = PlayerResult diff --git a/stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi new file mode 100644 index 000000000000..611578a5c889 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi @@ -0,0 +1,406 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Score(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ScoreType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ScoreTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Score._ScoreType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Curriculum: Score._ScoreType.ValueType # 1 + """map generated score (from curriculum maps with special scoring)""" + Melee: Score._ScoreType.ValueType # 2 + """summation of in-progress and current units/buildings value + minerals + vespene""" + + class ScoreType(_ScoreType, metaclass=_ScoreTypeEnumTypeWrapper): ... + Curriculum: Score.ScoreType.ValueType # 1 + """map generated score (from curriculum maps with special scoring)""" + Melee: Score.ScoreType.ValueType # 2 + """summation of in-progress and current units/buildings value + minerals + vespene""" + + SCORE_TYPE_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + SCORE_DETAILS_FIELD_NUMBER: builtins.int + score_type: global___Score.ScoreType.ValueType + score: builtins.int + """Note: check score_type to know whether this is a melee score or curriculum score""" + @property + def score_details(self) -> global___ScoreDetails: ... + def __init__( + self, + *, + score_type: global___Score.ScoreType.ValueType | None = ..., + score: builtins.int | None = ..., + score_details: global___ScoreDetails | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["score", b"score", "score_details", b"score_details", "score_type", b"score_type"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["score", b"score", "score_details", b"score_details", "score_type", b"score_type"] + ) -> None: ... + +global___Score = Score + +@typing.final +class CategoryScoreDetails(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NONE_FIELD_NUMBER: builtins.int + ARMY_FIELD_NUMBER: builtins.int + ECONOMY_FIELD_NUMBER: builtins.int + TECHNOLOGY_FIELD_NUMBER: builtins.int + UPGRADE_FIELD_NUMBER: builtins.int + none: builtins.float + """Used when no other category is configured in game data""" + army: builtins.float + economy: builtins.float + technology: builtins.float + upgrade: builtins.float + def __init__( + self, + *, + none: builtins.float | None = ..., + army: builtins.float | None = ..., + economy: builtins.float | None = ..., + technology: builtins.float | None = ..., + upgrade: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "army", b"army", "economy", b"economy", "none", b"none", "technology", b"technology", "upgrade", b"upgrade" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "army", b"army", "economy", b"economy", "none", b"none", "technology", b"technology", "upgrade", b"upgrade" + ], + ) -> None: ... + +global___CategoryScoreDetails = CategoryScoreDetails + +@typing.final +class VitalScoreDetails(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LIFE_FIELD_NUMBER: builtins.int + SHIELDS_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + life: builtins.float + shields: builtins.float + energy: builtins.float + def __init__( + self, *, life: builtins.float | None = ..., shields: builtins.float | None = ..., energy: builtins.float | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["energy", b"energy", "life", b"life", "shields", b"shields"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["energy", b"energy", "life", b"life", "shields", b"shields"]) -> None: ... + +global___VitalScoreDetails = VitalScoreDetails + +@typing.final +class ScoreDetails(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + IDLE_PRODUCTION_TIME_FIELD_NUMBER: builtins.int + IDLE_WORKER_TIME_FIELD_NUMBER: builtins.int + TOTAL_VALUE_UNITS_FIELD_NUMBER: builtins.int + TOTAL_VALUE_STRUCTURES_FIELD_NUMBER: builtins.int + KILLED_VALUE_UNITS_FIELD_NUMBER: builtins.int + KILLED_VALUE_STRUCTURES_FIELD_NUMBER: builtins.int + COLLECTED_MINERALS_FIELD_NUMBER: builtins.int + COLLECTED_VESPENE_FIELD_NUMBER: builtins.int + COLLECTION_RATE_MINERALS_FIELD_NUMBER: builtins.int + COLLECTION_RATE_VESPENE_FIELD_NUMBER: builtins.int + SPENT_MINERALS_FIELD_NUMBER: builtins.int + SPENT_VESPENE_FIELD_NUMBER: builtins.int + FOOD_USED_FIELD_NUMBER: builtins.int + KILLED_MINERALS_FIELD_NUMBER: builtins.int + KILLED_VESPENE_FIELD_NUMBER: builtins.int + LOST_MINERALS_FIELD_NUMBER: builtins.int + LOST_VESPENE_FIELD_NUMBER: builtins.int + FRIENDLY_FIRE_MINERALS_FIELD_NUMBER: builtins.int + FRIENDLY_FIRE_VESPENE_FIELD_NUMBER: builtins.int + USED_MINERALS_FIELD_NUMBER: builtins.int + USED_VESPENE_FIELD_NUMBER: builtins.int + TOTAL_USED_MINERALS_FIELD_NUMBER: builtins.int + TOTAL_USED_VESPENE_FIELD_NUMBER: builtins.int + TOTAL_DAMAGE_DEALT_FIELD_NUMBER: builtins.int + TOTAL_DAMAGE_TAKEN_FIELD_NUMBER: builtins.int + TOTAL_HEALED_FIELD_NUMBER: builtins.int + CURRENT_APM_FIELD_NUMBER: builtins.int + CURRENT_EFFECTIVE_APM_FIELD_NUMBER: builtins.int + idle_production_time: builtins.float + """Sum of time any available structure able to produce a unit is not. The time stacks, as in, three idle barracks will increase idle_production_time three times quicker than just one.""" + idle_worker_time: builtins.float + """Sum of time any worker is not mining. Note a worker building is not idle and three idle workers will increase this value three times quicker than just one.""" + total_value_units: builtins.float + """Sum of minerals and vespene spent on completed units.""" + total_value_structures: builtins.float + """Sum of minerals and vespene spent on completed structures.""" + killed_value_units: builtins.float + """Sum of minerals and vespene of units, belonging to the opponent, that the player has destroyed.""" + killed_value_structures: builtins.float + """Sum of minerals and vespene of structures, belonging to the opponent, that the player has destroyed.""" + collected_minerals: builtins.float + """Sum of minerals collected by the player.""" + collected_vespene: builtins.float + """Sum of vespene collected by the player.""" + collection_rate_minerals: builtins.float + """Estimated income of minerals over the next minute based on the players current income. The unit is minerals per minute.""" + collection_rate_vespene: builtins.float + """Estimated income of vespene over the next minute based on the players current income. The unit is vespene per minute.""" + spent_minerals: builtins.float + """Sum of spent minerals at the moment it is spent. For example, this number is incremented by 50 the moment an scv is queued in a command center. It is decremented by 50 if that unit is canceled.""" + spent_vespene: builtins.float + """Sum of spent vespene at the moment it is spent. For example, this number is incremented by 50 when a reaper is queued but decremented by 50 if it is canceled.""" + current_apm: builtins.float + """Recent raw APM.""" + current_effective_apm: builtins.float + """Recent effective APM.""" + @property + def food_used(self) -> global___CategoryScoreDetails: + """The following entries contains floating point values for the following catgories: + none - There is no category defined in game data. + army - This category includes all military units but not workers. + economy - This category contains town halls, supply structures, vespene buildings and workers. + technology - This category is any structure that produces units or upgrades, Barracks and Engineering Bays both fall in this category, for example. + upgrade - This category is upgrades such as warp gate or weapons upgrades. + + Sum of food, or supply, utilized in the categories above. + """ + + @property + def killed_minerals(self) -> global___CategoryScoreDetails: + """Sum of enemies catagories destroyed in minerals.""" + + @property + def killed_vespene(self) -> global___CategoryScoreDetails: + """Sum of enemies catagories destroyed in vespene.""" + + @property + def lost_minerals(self) -> global___CategoryScoreDetails: + """Sum of lost minerals for the player in each category.""" + + @property + def lost_vespene(self) -> global___CategoryScoreDetails: + """Sum of lost vespene for the player in each category.""" + + @property + def friendly_fire_minerals(self) -> global___CategoryScoreDetails: + """Sum of the lost minerals via destroying the players own units/buildings.""" + + @property + def friendly_fire_vespene(self) -> global___CategoryScoreDetails: + """Sum of the lost vespene via destroying the players own units/buildings.""" + + @property + def used_minerals(self) -> global___CategoryScoreDetails: + """Sum of used minerals for the player in each category for each existing unit or upgrade. Therefore if a unit died worth 50 mierals this number will be decremented by 50.""" + + @property + def used_vespene(self) -> global___CategoryScoreDetails: + """Sum of used vespene for the player in each category. Therefore if a unit died worth 50 vespene this number will be decremented by 50.""" + + @property + def total_used_minerals(self) -> global___CategoryScoreDetails: + """Sum of used minerals throughout the entire game for each category. Unliked used_minerals, this value is never decremented.""" + + @property + def total_used_vespene(self) -> global___CategoryScoreDetails: + """Sum of used vespene throughout the entire game for each category. Unliked used_vespene, this value is never decremented.""" + + @property + def total_damage_dealt(self) -> global___VitalScoreDetails: + """Sum of damage dealt to the player's opponent for each category.""" + + @property + def total_damage_taken(self) -> global___VitalScoreDetails: + """Sum of damage taken by the player for each category.""" + + @property + def total_healed(self) -> global___VitalScoreDetails: + """Sum of health healed by the player. Note that technology can be healed (by queens) or repaired (by scvs).""" + + def __init__( + self, + *, + idle_production_time: builtins.float | None = ..., + idle_worker_time: builtins.float | None = ..., + total_value_units: builtins.float | None = ..., + total_value_structures: builtins.float | None = ..., + killed_value_units: builtins.float | None = ..., + killed_value_structures: builtins.float | None = ..., + collected_minerals: builtins.float | None = ..., + collected_vespene: builtins.float | None = ..., + collection_rate_minerals: builtins.float | None = ..., + collection_rate_vespene: builtins.float | None = ..., + spent_minerals: builtins.float | None = ..., + spent_vespene: builtins.float | None = ..., + food_used: global___CategoryScoreDetails | None = ..., + killed_minerals: global___CategoryScoreDetails | None = ..., + killed_vespene: global___CategoryScoreDetails | None = ..., + lost_minerals: global___CategoryScoreDetails | None = ..., + lost_vespene: global___CategoryScoreDetails | None = ..., + friendly_fire_minerals: global___CategoryScoreDetails | None = ..., + friendly_fire_vespene: global___CategoryScoreDetails | None = ..., + used_minerals: global___CategoryScoreDetails | None = ..., + used_vespene: global___CategoryScoreDetails | None = ..., + total_used_minerals: global___CategoryScoreDetails | None = ..., + total_used_vespene: global___CategoryScoreDetails | None = ..., + total_damage_dealt: global___VitalScoreDetails | None = ..., + total_damage_taken: global___VitalScoreDetails | None = ..., + total_healed: global___VitalScoreDetails | None = ..., + current_apm: builtins.float | None = ..., + current_effective_apm: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "collected_minerals", + b"collected_minerals", + "collected_vespene", + b"collected_vespene", + "collection_rate_minerals", + b"collection_rate_minerals", + "collection_rate_vespene", + b"collection_rate_vespene", + "current_apm", + b"current_apm", + "current_effective_apm", + b"current_effective_apm", + "food_used", + b"food_used", + "friendly_fire_minerals", + b"friendly_fire_minerals", + "friendly_fire_vespene", + b"friendly_fire_vespene", + "idle_production_time", + b"idle_production_time", + "idle_worker_time", + b"idle_worker_time", + "killed_minerals", + b"killed_minerals", + "killed_value_structures", + b"killed_value_structures", + "killed_value_units", + b"killed_value_units", + "killed_vespene", + b"killed_vespene", + "lost_minerals", + b"lost_minerals", + "lost_vespene", + b"lost_vespene", + "spent_minerals", + b"spent_minerals", + "spent_vespene", + b"spent_vespene", + "total_damage_dealt", + b"total_damage_dealt", + "total_damage_taken", + b"total_damage_taken", + "total_healed", + b"total_healed", + "total_used_minerals", + b"total_used_minerals", + "total_used_vespene", + b"total_used_vespene", + "total_value_structures", + b"total_value_structures", + "total_value_units", + b"total_value_units", + "used_minerals", + b"used_minerals", + "used_vespene", + b"used_vespene", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "collected_minerals", + b"collected_minerals", + "collected_vespene", + b"collected_vespene", + "collection_rate_minerals", + b"collection_rate_minerals", + "collection_rate_vespene", + b"collection_rate_vespene", + "current_apm", + b"current_apm", + "current_effective_apm", + b"current_effective_apm", + "food_used", + b"food_used", + "friendly_fire_minerals", + b"friendly_fire_minerals", + "friendly_fire_vespene", + b"friendly_fire_vespene", + "idle_production_time", + b"idle_production_time", + "idle_worker_time", + b"idle_worker_time", + "killed_minerals", + b"killed_minerals", + "killed_value_structures", + b"killed_value_structures", + "killed_value_units", + b"killed_value_units", + "killed_vespene", + b"killed_vespene", + "lost_minerals", + b"lost_minerals", + "lost_vespene", + b"lost_vespene", + "spent_minerals", + b"spent_minerals", + "spent_vespene", + b"spent_vespene", + "total_damage_dealt", + b"total_damage_dealt", + "total_damage_taken", + b"total_damage_taken", + "total_healed", + b"total_healed", + "total_used_minerals", + b"total_used_minerals", + "total_used_vespene", + b"total_used_vespene", + "total_value_structures", + b"total_value_structures", + "total_value_units", + b"total_value_units", + "used_minerals", + b"used_minerals", + "used_vespene", + b"used_vespene", + ], + ) -> None: ... + +global___ScoreDetails = ScoreDetails diff --git a/stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi new file mode 100644 index 000000000000..5fd2301ac84b --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi @@ -0,0 +1,712 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class ObservationFeatureLayer(google.protobuf.message.Message): + """ + Observation - Feature Layer + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RENDERS_FIELD_NUMBER: builtins.int + MINIMAP_RENDERS_FIELD_NUMBER: builtins.int + @property + def renders(self) -> global___FeatureLayers: ... + @property + def minimap_renders(self) -> global___FeatureLayersMinimap: ... + def __init__( + self, *, renders: global___FeatureLayers | None = ..., minimap_renders: global___FeatureLayersMinimap | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["minimap_renders", b"minimap_renders", "renders", b"renders"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["minimap_renders", b"minimap_renders", "renders", b"renders"]) -> None: ... + +global___ObservationFeatureLayer = ObservationFeatureLayer + +@typing.final +class FeatureLayers(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HEIGHT_MAP_FIELD_NUMBER: builtins.int + VISIBILITY_MAP_FIELD_NUMBER: builtins.int + CREEP_FIELD_NUMBER: builtins.int + POWER_FIELD_NUMBER: builtins.int + PLAYER_ID_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + SELECTED_FIELD_NUMBER: builtins.int + UNIT_HIT_POINTS_FIELD_NUMBER: builtins.int + UNIT_HIT_POINTS_RATIO_FIELD_NUMBER: builtins.int + UNIT_ENERGY_FIELD_NUMBER: builtins.int + UNIT_ENERGY_RATIO_FIELD_NUMBER: builtins.int + UNIT_SHIELDS_FIELD_NUMBER: builtins.int + UNIT_SHIELDS_RATIO_FIELD_NUMBER: builtins.int + PLAYER_RELATIVE_FIELD_NUMBER: builtins.int + UNIT_DENSITY_AA_FIELD_NUMBER: builtins.int + UNIT_DENSITY_FIELD_NUMBER: builtins.int + EFFECTS_FIELD_NUMBER: builtins.int + HALLUCINATIONS_FIELD_NUMBER: builtins.int + CLOAKED_FIELD_NUMBER: builtins.int + BLIP_FIELD_NUMBER: builtins.int + BUFFS_FIELD_NUMBER: builtins.int + BUFF_DURATION_FIELD_NUMBER: builtins.int + ACTIVE_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + BUILDABLE_FIELD_NUMBER: builtins.int + PATHABLE_FIELD_NUMBER: builtins.int + PLACEHOLDER_FIELD_NUMBER: builtins.int + @property + def height_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Terrain height. World space units of [-200, 200] encoded into [0, 255].""" + + @property + def visibility_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. 0=Hidden, 1=Fogged, 2=Visible, 3=FullHidden""" + + @property + def creep(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Zerg creep.""" + + @property + def power(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Protoss power.""" + + @property + def player_id(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Participants: [1, 15] Neutral: 16""" + + @property + def unit_type(self) -> s2clientprotocol.common_pb2.ImageData: + """int32. Unique identifier for type of unit.""" + + @property + def selected(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Selected units.""" + + @property + def unit_hit_points(self) -> s2clientprotocol.common_pb2.ImageData: + """int32.""" + + @property + def unit_hit_points_ratio(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of current health to max health. [0%, 100%] encoded into [0, 255].""" + + @property + def unit_energy(self) -> s2clientprotocol.common_pb2.ImageData: + """int32.""" + + @property + def unit_energy_ratio(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of current energy to max energy. [0%, 100%] encoded into [0, 255].""" + + @property + def unit_shields(self) -> s2clientprotocol.common_pb2.ImageData: + """int32.""" + + @property + def unit_shields_ratio(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of current shields to max shields. [0%, 100%] encoded into [0, 255].""" + + @property + def player_relative(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. See "Alliance" enum in raw.proto. Range: [1, 4]""" + + @property + def unit_density_aa(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Density of units overlapping a pixel, anti-aliased. [0.0, 16.0f] encoded into [0, 255].""" + + @property + def unit_density(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Count of units overlapping a pixel.""" + + @property + def effects(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Visuals of persistent abilities. (eg. Psistorm)""" + + @property + def hallucinations(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is a hallucination.""" + + @property + def cloaked(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is cloaked. Hidden units will show up too, but with less details in other layers.""" + + @property + def blip(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is a blip.""" + + @property + def buffs(self) -> s2clientprotocol.common_pb2.ImageData: + """int32. One of the buffs applied to this unit. Extras are ignored.""" + + @property + def buff_duration(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of buff remaining. [0%, 100%] encoded into [0, 255].""" + + @property + def active(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is active.""" + + @property + def build_progress(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. How far along the building is building something. [0%, 100%] encoded into [0, 255].""" + + @property + def buildable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a building can be built here.""" + + @property + def pathable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a unit can walk here.""" + + @property + def placeholder(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is a placeholder building to be constructed.""" + + def __init__( + self, + *, + height_map: s2clientprotocol.common_pb2.ImageData | None = ..., + visibility_map: s2clientprotocol.common_pb2.ImageData | None = ..., + creep: s2clientprotocol.common_pb2.ImageData | None = ..., + power: s2clientprotocol.common_pb2.ImageData | None = ..., + player_id: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_type: s2clientprotocol.common_pb2.ImageData | None = ..., + selected: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_hit_points: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_hit_points_ratio: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_energy: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_energy_ratio: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_shields: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_shields_ratio: s2clientprotocol.common_pb2.ImageData | None = ..., + player_relative: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_density_aa: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_density: s2clientprotocol.common_pb2.ImageData | None = ..., + effects: s2clientprotocol.common_pb2.ImageData | None = ..., + hallucinations: s2clientprotocol.common_pb2.ImageData | None = ..., + cloaked: s2clientprotocol.common_pb2.ImageData | None = ..., + blip: s2clientprotocol.common_pb2.ImageData | None = ..., + buffs: s2clientprotocol.common_pb2.ImageData | None = ..., + buff_duration: s2clientprotocol.common_pb2.ImageData | None = ..., + active: s2clientprotocol.common_pb2.ImageData | None = ..., + build_progress: s2clientprotocol.common_pb2.ImageData | None = ..., + buildable: s2clientprotocol.common_pb2.ImageData | None = ..., + pathable: s2clientprotocol.common_pb2.ImageData | None = ..., + placeholder: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "active", + b"active", + "blip", + b"blip", + "buff_duration", + b"buff_duration", + "buffs", + b"buffs", + "build_progress", + b"build_progress", + "buildable", + b"buildable", + "cloaked", + b"cloaked", + "creep", + b"creep", + "effects", + b"effects", + "hallucinations", + b"hallucinations", + "height_map", + b"height_map", + "pathable", + b"pathable", + "placeholder", + b"placeholder", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "power", + b"power", + "selected", + b"selected", + "unit_density", + b"unit_density", + "unit_density_aa", + b"unit_density_aa", + "unit_energy", + b"unit_energy", + "unit_energy_ratio", + b"unit_energy_ratio", + "unit_hit_points", + b"unit_hit_points", + "unit_hit_points_ratio", + b"unit_hit_points_ratio", + "unit_shields", + b"unit_shields", + "unit_shields_ratio", + b"unit_shields_ratio", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "active", + b"active", + "blip", + b"blip", + "buff_duration", + b"buff_duration", + "buffs", + b"buffs", + "build_progress", + b"build_progress", + "buildable", + b"buildable", + "cloaked", + b"cloaked", + "creep", + b"creep", + "effects", + b"effects", + "hallucinations", + b"hallucinations", + "height_map", + b"height_map", + "pathable", + b"pathable", + "placeholder", + b"placeholder", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "power", + b"power", + "selected", + b"selected", + "unit_density", + b"unit_density", + "unit_density_aa", + b"unit_density_aa", + "unit_energy", + b"unit_energy", + "unit_energy_ratio", + b"unit_energy_ratio", + "unit_hit_points", + b"unit_hit_points", + "unit_hit_points_ratio", + b"unit_hit_points_ratio", + "unit_shields", + b"unit_shields", + "unit_shields_ratio", + b"unit_shields_ratio", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> None: ... + +global___FeatureLayers = FeatureLayers + +@typing.final +class FeatureLayersMinimap(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HEIGHT_MAP_FIELD_NUMBER: builtins.int + VISIBILITY_MAP_FIELD_NUMBER: builtins.int + CREEP_FIELD_NUMBER: builtins.int + CAMERA_FIELD_NUMBER: builtins.int + PLAYER_ID_FIELD_NUMBER: builtins.int + PLAYER_RELATIVE_FIELD_NUMBER: builtins.int + SELECTED_FIELD_NUMBER: builtins.int + ALERTS_FIELD_NUMBER: builtins.int + BUILDABLE_FIELD_NUMBER: builtins.int + PATHABLE_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + @property + def height_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Terrain height. World space units of [-200, 200] encoded into [0, 255].""" + + @property + def visibility_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. 0=Hidden, 1=Fogged, 2=Visible, 3=FullHidden""" + + @property + def creep(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Zerg creep.""" + + @property + def camera(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Area covered by the camera.""" + + @property + def player_id(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Participants: [1, 15] Neutral: 16""" + + @property + def player_relative(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. See "Alliance" enum in raw.proto. Range: [1, 4]""" + + @property + def selected(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Selected units.""" + + @property + def alerts(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Shows 'UnitAttacked' alert location.""" + + @property + def buildable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a building can be built here.""" + + @property + def pathable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a unit can walk here.""" + + @property + def unit_type(self) -> s2clientprotocol.common_pb2.ImageData: + """Cheat layers, enable with SpatialCameraSetup.allow_cheating_layers. + int32. Unique identifier for type of unit. + """ + + def __init__( + self, + *, + height_map: s2clientprotocol.common_pb2.ImageData | None = ..., + visibility_map: s2clientprotocol.common_pb2.ImageData | None = ..., + creep: s2clientprotocol.common_pb2.ImageData | None = ..., + camera: s2clientprotocol.common_pb2.ImageData | None = ..., + player_id: s2clientprotocol.common_pb2.ImageData | None = ..., + player_relative: s2clientprotocol.common_pb2.ImageData | None = ..., + selected: s2clientprotocol.common_pb2.ImageData | None = ..., + alerts: s2clientprotocol.common_pb2.ImageData | None = ..., + buildable: s2clientprotocol.common_pb2.ImageData | None = ..., + pathable: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_type: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "alerts", + b"alerts", + "buildable", + b"buildable", + "camera", + b"camera", + "creep", + b"creep", + "height_map", + b"height_map", + "pathable", + b"pathable", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "selected", + b"selected", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alerts", + b"alerts", + "buildable", + b"buildable", + "camera", + b"camera", + "creep", + b"creep", + "height_map", + b"height_map", + "pathable", + b"pathable", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "selected", + b"selected", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> None: ... + +global___FeatureLayersMinimap = FeatureLayersMinimap + +@typing.final +class ObservationRender(google.protobuf.message.Message): + """ + Observation - Rendered + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_FIELD_NUMBER: builtins.int + MINIMAP_FIELD_NUMBER: builtins.int + @property + def map(self) -> s2clientprotocol.common_pb2.ImageData: ... + @property + def minimap(self) -> s2clientprotocol.common_pb2.ImageData: ... + def __init__( + self, + *, + map: s2clientprotocol.common_pb2.ImageData | None = ..., + minimap: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["map", b"map", "minimap", b"minimap"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["map", b"map", "minimap", b"minimap"]) -> None: ... + +global___ObservationRender = ObservationRender + +@typing.final +class ActionSpatial(google.protobuf.message.Message): + """ + Action + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_COMMAND_FIELD_NUMBER: builtins.int + CAMERA_MOVE_FIELD_NUMBER: builtins.int + UNIT_SELECTION_POINT_FIELD_NUMBER: builtins.int + UNIT_SELECTION_RECT_FIELD_NUMBER: builtins.int + @property + def unit_command(self) -> global___ActionSpatialUnitCommand: ... + @property + def camera_move(self) -> global___ActionSpatialCameraMove: ... + @property + def unit_selection_point(self) -> global___ActionSpatialUnitSelectionPoint: ... + @property + def unit_selection_rect(self) -> global___ActionSpatialUnitSelectionRect: ... + def __init__( + self, + *, + unit_command: global___ActionSpatialUnitCommand | None = ..., + camera_move: global___ActionSpatialCameraMove | None = ..., + unit_selection_point: global___ActionSpatialUnitSelectionPoint | None = ..., + unit_selection_rect: global___ActionSpatialUnitSelectionRect | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "unit_command", + b"unit_command", + "unit_selection_point", + b"unit_selection_point", + "unit_selection_rect", + b"unit_selection_rect", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "unit_command", + b"unit_command", + "unit_selection_point", + b"unit_selection_point", + "unit_selection_rect", + b"unit_selection_rect", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> typing.Literal["unit_command", "camera_move", "unit_selection_point", "unit_selection_rect"] | None: ... + +global___ActionSpatial = ActionSpatial + +@typing.final +class ActionSpatialUnitCommand(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_SCREEN_COORD_FIELD_NUMBER: builtins.int + TARGET_MINIMAP_COORD_FIELD_NUMBER: builtins.int + QUEUE_COMMAND_FIELD_NUMBER: builtins.int + ability_id: builtins.int + queue_command: builtins.bool + """Equivalent to shift+command.""" + @property + def target_screen_coord(self) -> s2clientprotocol.common_pb2.PointI: ... + @property + def target_minimap_coord(self) -> s2clientprotocol.common_pb2.PointI: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_screen_coord: s2clientprotocol.common_pb2.PointI | None = ..., + target_minimap_coord: s2clientprotocol.common_pb2.PointI | None = ..., + queue_command: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_minimap_coord", + b"target_minimap_coord", + "target_screen_coord", + b"target_screen_coord", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_minimap_coord", + b"target_minimap_coord", + "target_screen_coord", + b"target_screen_coord", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["target", b"target"] + ) -> typing.Literal["target_screen_coord", "target_minimap_coord"] | None: ... + +global___ActionSpatialUnitCommand = ActionSpatialUnitCommand + +@typing.final +class ActionSpatialCameraMove(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CENTER_MINIMAP_FIELD_NUMBER: builtins.int + @property + def center_minimap(self) -> s2clientprotocol.common_pb2.PointI: + """Simulates a click on the minimap to move the camera.""" + + def __init__(self, *, center_minimap: s2clientprotocol.common_pb2.PointI | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["center_minimap", b"center_minimap"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["center_minimap", b"center_minimap"]) -> None: ... + +global___ActionSpatialCameraMove = ActionSpatialCameraMove + +@typing.final +class ActionSpatialUnitSelectionPoint(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionSpatialUnitSelectionPoint._Type.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Select: ActionSpatialUnitSelectionPoint._Type.ValueType # 1 + """Equivalent to normal click. Changes selection to unit.""" + Toggle: ActionSpatialUnitSelectionPoint._Type.ValueType # 2 + """Equivalent to shift+click. Toggle selection of unit.""" + AllType: ActionSpatialUnitSelectionPoint._Type.ValueType # 3 + """Equivalent to control+click. Selects all units of a given type.""" + AddAllType: ActionSpatialUnitSelectionPoint._Type.ValueType # 4 + """Equivalent to shift+control+click. Selects all units of a given type.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + Select: ActionSpatialUnitSelectionPoint.Type.ValueType # 1 + """Equivalent to normal click. Changes selection to unit.""" + Toggle: ActionSpatialUnitSelectionPoint.Type.ValueType # 2 + """Equivalent to shift+click. Toggle selection of unit.""" + AllType: ActionSpatialUnitSelectionPoint.Type.ValueType # 3 + """Equivalent to control+click. Selects all units of a given type.""" + AddAllType: ActionSpatialUnitSelectionPoint.Type.ValueType # 4 + """Equivalent to shift+control+click. Selects all units of a given type.""" + + SELECTION_SCREEN_COORD_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + type: global___ActionSpatialUnitSelectionPoint.Type.ValueType + @property + def selection_screen_coord(self) -> s2clientprotocol.common_pb2.PointI: ... + def __init__( + self, + *, + selection_screen_coord: s2clientprotocol.common_pb2.PointI | None = ..., + type: global___ActionSpatialUnitSelectionPoint.Type.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["selection_screen_coord", b"selection_screen_coord", "type", b"type"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["selection_screen_coord", b"selection_screen_coord", "type", b"type"] + ) -> None: ... + +global___ActionSpatialUnitSelectionPoint = ActionSpatialUnitSelectionPoint + +@typing.final +class ActionSpatialUnitSelectionRect(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SELECTION_SCREEN_COORD_FIELD_NUMBER: builtins.int + SELECTION_ADD_FIELD_NUMBER: builtins.int + selection_add: builtins.bool + """Equivalent to shift+drag. Adds units to selection.""" + @property + def selection_screen_coord( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.RectangleI]: + """Eventually this should not be an array, but a single field (multiple would be cheating).""" + + def __init__( + self, + *, + selection_screen_coord: collections.abc.Iterable[s2clientprotocol.common_pb2.RectangleI] | None = ..., + selection_add: builtins.bool | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["selection_add", b"selection_add", "selection_screen_coord", b"selection_screen_coord"] + ) -> None: ... + +global___ActionSpatialUnitSelectionRect = ActionSpatialUnitSelectionRect diff --git a/stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi new file mode 100644 index 000000000000..2608a8aa142c --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi @@ -0,0 +1,681 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class ObservationUI(google.protobuf.message.Message): + """ + Observation + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GROUPS_FIELD_NUMBER: builtins.int + SINGLE_FIELD_NUMBER: builtins.int + MULTI_FIELD_NUMBER: builtins.int + CARGO_FIELD_NUMBER: builtins.int + PRODUCTION_FIELD_NUMBER: builtins.int + @property + def groups(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ControlGroup]: ... + @property + def single(self) -> global___SinglePanel: ... + @property + def multi(self) -> global___MultiPanel: ... + @property + def cargo(self) -> global___CargoPanel: ... + @property + def production(self) -> global___ProductionPanel: ... + def __init__( + self, + *, + groups: collections.abc.Iterable[global___ControlGroup] | None = ..., + single: global___SinglePanel | None = ..., + multi: global___MultiPanel | None = ..., + cargo: global___CargoPanel | None = ..., + production: global___ProductionPanel | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cargo", b"cargo", "multi", b"multi", "panel", b"panel", "production", b"production", "single", b"single" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "cargo", + b"cargo", + "groups", + b"groups", + "multi", + b"multi", + "panel", + b"panel", + "production", + b"production", + "single", + b"single", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["panel", b"panel"] + ) -> typing.Literal["single", "multi", "cargo", "production"] | None: ... + +global___ObservationUI = ObservationUI + +@typing.final +class ControlGroup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CONTROL_GROUP_INDEX_FIELD_NUMBER: builtins.int + LEADER_UNIT_TYPE_FIELD_NUMBER: builtins.int + COUNT_FIELD_NUMBER: builtins.int + control_group_index: builtins.int + leader_unit_type: builtins.int + count: builtins.int + def __init__( + self, + *, + control_group_index: builtins.int | None = ..., + leader_unit_type: builtins.int | None = ..., + count: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "control_group_index", b"control_group_index", "count", b"count", "leader_unit_type", b"leader_unit_type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "control_group_index", b"control_group_index", "count", b"count", "leader_unit_type", b"leader_unit_type" + ], + ) -> None: ... + +global___ControlGroup = ControlGroup + +@typing.final +class UnitInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TYPE_FIELD_NUMBER: builtins.int + PLAYER_RELATIVE_FIELD_NUMBER: builtins.int + HEALTH_FIELD_NUMBER: builtins.int + SHIELDS_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + TRANSPORT_SLOTS_TAKEN_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + ADD_ON_FIELD_NUMBER: builtins.int + MAX_HEALTH_FIELD_NUMBER: builtins.int + MAX_SHIELDS_FIELD_NUMBER: builtins.int + MAX_ENERGY_FIELD_NUMBER: builtins.int + unit_type: builtins.int + player_relative: builtins.int + health: builtins.int + shields: builtins.int + energy: builtins.int + transport_slots_taken: builtins.int + build_progress: builtins.float + """Range: [0.0, 1.0]""" + max_health: builtins.int + max_shields: builtins.int + max_energy: builtins.int + @property + def add_on(self) -> global___UnitInfo: ... + def __init__( + self, + *, + unit_type: builtins.int | None = ..., + player_relative: builtins.int | None = ..., + health: builtins.int | None = ..., + shields: builtins.int | None = ..., + energy: builtins.int | None = ..., + transport_slots_taken: builtins.int | None = ..., + build_progress: builtins.float | None = ..., + add_on: global___UnitInfo | None = ..., + max_health: builtins.int | None = ..., + max_shields: builtins.int | None = ..., + max_energy: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "add_on", + b"add_on", + "build_progress", + b"build_progress", + "energy", + b"energy", + "health", + b"health", + "max_energy", + b"max_energy", + "max_health", + b"max_health", + "max_shields", + b"max_shields", + "player_relative", + b"player_relative", + "shields", + b"shields", + "transport_slots_taken", + b"transport_slots_taken", + "unit_type", + b"unit_type", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "add_on", + b"add_on", + "build_progress", + b"build_progress", + "energy", + b"energy", + "health", + b"health", + "max_energy", + b"max_energy", + "max_health", + b"max_health", + "max_shields", + b"max_shields", + "player_relative", + b"player_relative", + "shields", + b"shields", + "transport_slots_taken", + b"transport_slots_taken", + "unit_type", + b"unit_type", + ], + ) -> None: ... + +global___UnitInfo = UnitInfo + +@typing.final +class SinglePanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_FIELD_NUMBER: builtins.int + ATTACK_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + ARMOR_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + SHIELD_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + BUFFS_FIELD_NUMBER: builtins.int + attack_upgrade_level: builtins.int + armor_upgrade_level: builtins.int + shield_upgrade_level: builtins.int + @property + def unit(self) -> global___UnitInfo: ... + @property + def buffs(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + unit: global___UnitInfo | None = ..., + attack_upgrade_level: builtins.int | None = ..., + armor_upgrade_level: builtins.int | None = ..., + shield_upgrade_level: builtins.int | None = ..., + buffs: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "armor_upgrade_level", + b"armor_upgrade_level", + "attack_upgrade_level", + b"attack_upgrade_level", + "shield_upgrade_level", + b"shield_upgrade_level", + "unit", + b"unit", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "armor_upgrade_level", + b"armor_upgrade_level", + "attack_upgrade_level", + b"attack_upgrade_level", + "buffs", + b"buffs", + "shield_upgrade_level", + b"shield_upgrade_level", + "unit", + b"unit", + ], + ) -> None: ... + +global___SinglePanel = SinglePanel + +@typing.final +class MultiPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNITS_FIELD_NUMBER: builtins.int + @property + def units(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitInfo]: ... + def __init__(self, *, units: collections.abc.Iterable[global___UnitInfo] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["units", b"units"]) -> None: ... + +global___MultiPanel = MultiPanel + +@typing.final +class CargoPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_FIELD_NUMBER: builtins.int + PASSENGERS_FIELD_NUMBER: builtins.int + SLOTS_AVAILABLE_FIELD_NUMBER: builtins.int + slots_available: builtins.int + """TODO: Change to cargo size""" + @property + def unit(self) -> global___UnitInfo: ... + @property + def passengers(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitInfo]: ... + def __init__( + self, + *, + unit: global___UnitInfo | None = ..., + passengers: collections.abc.Iterable[global___UnitInfo] | None = ..., + slots_available: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["slots_available", b"slots_available", "unit", b"unit"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["passengers", b"passengers", "slots_available", b"slots_available", "unit", b"unit"] + ) -> None: ... + +global___CargoPanel = CargoPanel + +@typing.final +class BuildItem(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + ability_id: builtins.int + build_progress: builtins.float + """Range: [0.0, 1.0]""" + def __init__(self, *, ability_id: builtins.int | None = ..., build_progress: builtins.float | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["ability_id", b"ability_id", "build_progress", b"build_progress"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["ability_id", b"ability_id", "build_progress", b"build_progress"] + ) -> None: ... + +global___BuildItem = BuildItem + +@typing.final +class ProductionPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_FIELD_NUMBER: builtins.int + BUILD_QUEUE_FIELD_NUMBER: builtins.int + PRODUCTION_QUEUE_FIELD_NUMBER: builtins.int + @property + def unit(self) -> global___UnitInfo: ... + @property + def build_queue(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitInfo]: + """build_queue ONLY gives information about units that are being produced. + Use production_queue instead to see both units being trained as well as research in the queue. + """ + + @property + def production_queue(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BuildItem]: ... + def __init__( + self, + *, + unit: global___UnitInfo | None = ..., + build_queue: collections.abc.Iterable[global___UnitInfo] | None = ..., + production_queue: collections.abc.Iterable[global___BuildItem] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["unit", b"unit"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["build_queue", b"build_queue", "production_queue", b"production_queue", "unit", b"unit"] + ) -> None: ... + +global___ProductionPanel = ProductionPanel + +@typing.final +class ActionUI(google.protobuf.message.Message): + """ + Action + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CONTROL_GROUP_FIELD_NUMBER: builtins.int + SELECT_ARMY_FIELD_NUMBER: builtins.int + SELECT_WARP_GATES_FIELD_NUMBER: builtins.int + SELECT_LARVA_FIELD_NUMBER: builtins.int + SELECT_IDLE_WORKER_FIELD_NUMBER: builtins.int + MULTI_PANEL_FIELD_NUMBER: builtins.int + CARGO_PANEL_FIELD_NUMBER: builtins.int + PRODUCTION_PANEL_FIELD_NUMBER: builtins.int + TOGGLE_AUTOCAST_FIELD_NUMBER: builtins.int + @property + def control_group(self) -> global___ActionControlGroup: ... + @property + def select_army(self) -> global___ActionSelectArmy: ... + @property + def select_warp_gates(self) -> global___ActionSelectWarpGates: ... + @property + def select_larva(self) -> global___ActionSelectLarva: ... + @property + def select_idle_worker(self) -> global___ActionSelectIdleWorker: ... + @property + def multi_panel(self) -> global___ActionMultiPanel: ... + @property + def cargo_panel(self) -> global___ActionCargoPanelUnload: ... + @property + def production_panel(self) -> global___ActionProductionPanelRemoveFromQueue: ... + @property + def toggle_autocast(self) -> global___ActionToggleAutocast: ... + def __init__( + self, + *, + control_group: global___ActionControlGroup | None = ..., + select_army: global___ActionSelectArmy | None = ..., + select_warp_gates: global___ActionSelectWarpGates | None = ..., + select_larva: global___ActionSelectLarva | None = ..., + select_idle_worker: global___ActionSelectIdleWorker | None = ..., + multi_panel: global___ActionMultiPanel | None = ..., + cargo_panel: global___ActionCargoPanelUnload | None = ..., + production_panel: global___ActionProductionPanelRemoveFromQueue | None = ..., + toggle_autocast: global___ActionToggleAutocast | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "cargo_panel", + b"cargo_panel", + "control_group", + b"control_group", + "multi_panel", + b"multi_panel", + "production_panel", + b"production_panel", + "select_army", + b"select_army", + "select_idle_worker", + b"select_idle_worker", + "select_larva", + b"select_larva", + "select_warp_gates", + b"select_warp_gates", + "toggle_autocast", + b"toggle_autocast", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "cargo_panel", + b"cargo_panel", + "control_group", + b"control_group", + "multi_panel", + b"multi_panel", + "production_panel", + b"production_panel", + "select_army", + b"select_army", + "select_idle_worker", + b"select_idle_worker", + "select_larva", + b"select_larva", + "select_warp_gates", + b"select_warp_gates", + "toggle_autocast", + b"toggle_autocast", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> ( + typing.Literal[ + "control_group", + "select_army", + "select_warp_gates", + "select_larva", + "select_idle_worker", + "multi_panel", + "cargo_panel", + "production_panel", + "toggle_autocast", + ] + | None + ): ... + +global___ActionUI = ActionUI + +@typing.final +class ActionControlGroup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ControlGroupAction: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ControlGroupActionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionControlGroup._ControlGroupAction.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Recall: ActionControlGroup._ControlGroupAction.ValueType # 1 + """Equivalent to number hotkey. Replaces current selection with control group.""" + Set: ActionControlGroup._ControlGroupAction.ValueType # 2 + """Equivalent to Control + number hotkey. Sets control group to current selection.""" + Append: ActionControlGroup._ControlGroupAction.ValueType # 3 + """Equivalent to Shift + number hotkey. Adds current selection into control group.""" + SetAndSteal: ActionControlGroup._ControlGroupAction.ValueType # 4 + """Equivalent to Control + Alt + number hotkey. Sets control group to current selection. Units are removed from other control groups.""" + AppendAndSteal: ActionControlGroup._ControlGroupAction.ValueType # 5 + """Equivalent to Shift + Alt + number hotkey. Adds current selection into control group. Units are removed from other control groups.""" + + class ControlGroupAction(_ControlGroupAction, metaclass=_ControlGroupActionEnumTypeWrapper): ... + Recall: ActionControlGroup.ControlGroupAction.ValueType # 1 + """Equivalent to number hotkey. Replaces current selection with control group.""" + Set: ActionControlGroup.ControlGroupAction.ValueType # 2 + """Equivalent to Control + number hotkey. Sets control group to current selection.""" + Append: ActionControlGroup.ControlGroupAction.ValueType # 3 + """Equivalent to Shift + number hotkey. Adds current selection into control group.""" + SetAndSteal: ActionControlGroup.ControlGroupAction.ValueType # 4 + """Equivalent to Control + Alt + number hotkey. Sets control group to current selection. Units are removed from other control groups.""" + AppendAndSteal: ActionControlGroup.ControlGroupAction.ValueType # 5 + """Equivalent to Shift + Alt + number hotkey. Adds current selection into control group. Units are removed from other control groups.""" + + ACTION_FIELD_NUMBER: builtins.int + CONTROL_GROUP_INDEX_FIELD_NUMBER: builtins.int + action: global___ActionControlGroup.ControlGroupAction.ValueType + control_group_index: builtins.int + def __init__( + self, + *, + action: global___ActionControlGroup.ControlGroupAction.ValueType | None = ..., + control_group_index: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["action", b"action", "control_group_index", b"control_group_index"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["action", b"action", "control_group_index", b"control_group_index"] + ) -> None: ... + +global___ActionControlGroup = ActionControlGroup + +@typing.final +class ActionSelectArmy(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SELECTION_ADD_FIELD_NUMBER: builtins.int + selection_add: builtins.bool + def __init__(self, *, selection_add: builtins.bool | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> None: ... + +global___ActionSelectArmy = ActionSelectArmy + +@typing.final +class ActionSelectWarpGates(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SELECTION_ADD_FIELD_NUMBER: builtins.int + selection_add: builtins.bool + def __init__(self, *, selection_add: builtins.bool | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> None: ... + +global___ActionSelectWarpGates = ActionSelectWarpGates + +@typing.final +class ActionSelectLarva(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ActionSelectLarva = ActionSelectLarva + +@typing.final +class ActionSelectIdleWorker(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionSelectIdleWorker._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Set: ActionSelectIdleWorker._Type.ValueType # 1 + """Equivalent to click with no modifiers. Replaces selection with single idle worker.""" + Add: ActionSelectIdleWorker._Type.ValueType # 2 + """Equivalent to shift+click. Adds single idle worker to current selection.""" + All: ActionSelectIdleWorker._Type.ValueType # 3 + """Equivalent to control+click. Selects all idle workers.""" + AddAll: ActionSelectIdleWorker._Type.ValueType # 4 + """Equivalent to shift+control+click. Adds all idle workers to current selection.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + Set: ActionSelectIdleWorker.Type.ValueType # 1 + """Equivalent to click with no modifiers. Replaces selection with single idle worker.""" + Add: ActionSelectIdleWorker.Type.ValueType # 2 + """Equivalent to shift+click. Adds single idle worker to current selection.""" + All: ActionSelectIdleWorker.Type.ValueType # 3 + """Equivalent to control+click. Selects all idle workers.""" + AddAll: ActionSelectIdleWorker.Type.ValueType # 4 + """Equivalent to shift+control+click. Adds all idle workers to current selection.""" + + TYPE_FIELD_NUMBER: builtins.int + type: global___ActionSelectIdleWorker.Type.ValueType + def __init__(self, *, type: global___ActionSelectIdleWorker.Type.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["type", b"type"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["type", b"type"]) -> None: ... + +global___ActionSelectIdleWorker = ActionSelectIdleWorker + +@typing.final +class ActionMultiPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionMultiPanel._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SingleSelect: ActionMultiPanel._Type.ValueType # 1 + """Click on icon""" + DeselectUnit: ActionMultiPanel._Type.ValueType # 2 + """Shift Click on icon""" + SelectAllOfType: ActionMultiPanel._Type.ValueType # 3 + """Control Click on icon.""" + DeselectAllOfType: ActionMultiPanel._Type.ValueType # 4 + """Control+Shift Click on icon.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + SingleSelect: ActionMultiPanel.Type.ValueType # 1 + """Click on icon""" + DeselectUnit: ActionMultiPanel.Type.ValueType # 2 + """Shift Click on icon""" + SelectAllOfType: ActionMultiPanel.Type.ValueType # 3 + """Control Click on icon.""" + DeselectAllOfType: ActionMultiPanel.Type.ValueType # 4 + """Control+Shift Click on icon.""" + + TYPE_FIELD_NUMBER: builtins.int + UNIT_INDEX_FIELD_NUMBER: builtins.int + type: global___ActionMultiPanel.Type.ValueType + unit_index: builtins.int + def __init__( + self, *, type: global___ActionMultiPanel.Type.ValueType | None = ..., unit_index: builtins.int | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["type", b"type", "unit_index", b"unit_index"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["type", b"type", "unit_index", b"unit_index"]) -> None: ... + +global___ActionMultiPanel = ActionMultiPanel + +@typing.final +class ActionCargoPanelUnload(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_INDEX_FIELD_NUMBER: builtins.int + unit_index: builtins.int + def __init__(self, *, unit_index: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> None: ... + +global___ActionCargoPanelUnload = ActionCargoPanelUnload + +@typing.final +class ActionProductionPanelRemoveFromQueue(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_INDEX_FIELD_NUMBER: builtins.int + unit_index: builtins.int + def __init__(self, *, unit_index: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> None: ... + +global___ActionProductionPanelRemoveFromQueue = ActionProductionPanelRemoveFromQueue + +@typing.final +class ActionToggleAutocast(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + ability_id: builtins.int + def __init__(self, *, ability_id: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["ability_id", b"ability_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["ability_id", b"ability_id"]) -> None: ... + +global___ActionToggleAutocast = ActionToggleAutocast diff --git a/stubs/scp/METADATA.toml b/stubs/scp/METADATA.toml new file mode 100644 index 000000000000..4456de13a4d5 --- /dev/null +++ b/stubs/scp/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.16.*" +upstream-repository = "https://github.com/jbardin/scp.py" +dependencies = ["types-paramiko"] diff --git a/stubs/scp/scp.pyi b/stubs/scp/scp.pyi new file mode 100644 index 000000000000..a7b9ae28b963 --- /dev/null +++ b/stubs/scp/scp.pyi @@ -0,0 +1,83 @@ +from collections.abc import Callable, Iterable +from pathlib import PurePath +from types import TracebackType +from typing import Final, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Self + +from paramiko.channel import Channel +from paramiko.transport import Transport + +__version__: Final[str] + +SCP_COMMAND: Final = b"scp" +PATH_TYPES: Final[tuple[type[str], type[bytes], type[PurePath]]] +bytes_sep: Final[bytes] + +PathTypes: TypeAlias = str | bytes | PurePath + +@type_check_only +class _PutFOReader(Protocol): + def read(self, size: int, /) -> str | bytes | bytearray: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: Literal[0, 2], /) -> object: ... + +def asbytes(s: PathTypes) -> bytes: ... +def asunicode(s: bytes | str) -> str: ... +def asunicode_win(s: bytes | str) -> str: ... + +class SCPClient: + transport: Transport + buff_size: int + socket_timeout: float | None + channel: Channel | None + preserve_times: bool + sanitize: Callable[[bytes], bytes] + peername: tuple[str, int] + scp_command: bytes + def __init__( + self, + transport: Transport, + buff_size: int = 16384, + socket_timeout: float | None = 10.0, + progress: Callable[[str | bytes, int, int], None] | None = None, + progress4: Callable[[str | bytes, int, int, tuple[str, int]], None] | None = None, + sanitize: Callable[[bytes], bytes] | Literal[False] = ..., + limit_bw: int | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def put( + self, + files: PathTypes | Iterable[PathTypes], + remote_path: PathTypes = b".", + recursive: bool = False, + preserve_times: bool = False, + ) -> None: ... + def putfo(self, fl: _PutFOReader, remote_path: PathTypes, mode: str | bytes = "0644", size: int | None = None) -> None: ... + def get( + self, + remote_path: PathTypes | Iterable[PathTypes], + local_path: PathTypes = "", + recursive: bool = False, + preserve_times: bool = False, + ) -> None: ... + def close(self) -> None: ... + +class SCPException(Exception): ... + +def put( + transport: Transport, + files: PathTypes | Iterable[PathTypes], + remote_path: PathTypes = b".", + recursive: bool = False, + preserve_times: bool = False, +) -> None: ... +def get( + transport: Transport, + remote_path: PathTypes | Iterable[PathTypes], + local_path: PathTypes = "", + recursive: bool = False, + preserve_times: bool = False, +) -> None: ... diff --git a/stubs/seaborn/@tests/stubtest_allowlist.txt b/stubs/seaborn/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..31b226b5a849 --- /dev/null +++ b/stubs/seaborn/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +seaborn._core.scales.(Pipeline|TransFuncs) # aliases defined in `if TYPE_CHECKING` block +seaborn.external.docscrape.NumpyDocString.__str__ # weird signature + +seaborn.axisgrid.Grid.tight_layout # the method doesn't really take pos args but runtime has *args + +seaborn.external.appdirs.unicode diff --git a/stubs/seaborn/METADATA.toml b/stubs/seaborn/METADATA.toml new file mode 100644 index 000000000000..960160f52d9c --- /dev/null +++ b/stubs/seaborn/METADATA.toml @@ -0,0 +1,4 @@ +version = "0.13.2" +upstream-repository = "https://github.com/mwaskom/seaborn" +# Requires a version of numpy and matplotlib with a `py.typed` file +dependencies = ["matplotlib>=3.8", "numpy>=1.20", "pandas-stubs"] diff --git a/stubs/seaborn/seaborn/__init__.pyi b/stubs/seaborn/seaborn/__init__.pyi new file mode 100644 index 000000000000..f8a92d1d6515 --- /dev/null +++ b/stubs/seaborn/seaborn/__init__.pyi @@ -0,0 +1,13 @@ +from . import cm as cm +from .axisgrid import * +from .categorical import * +from .colors import crayons as crayons, xkcd_rgb as xkcd_rgb +from .distributions import * +from .matrix import * +from .miscplot import * +from .palettes import * +from .rcmod import * +from .regression import * +from .relational import * +from .utils import * +from .widgets import * diff --git a/stubs/seaborn/seaborn/_core/__init__.pyi b/stubs/seaborn/seaborn/_core/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/_core/data.pyi b/stubs/seaborn/seaborn/_core/data.pyi new file mode 100644 index 000000000000..7686ead8de08 --- /dev/null +++ b/stubs/seaborn/seaborn/_core/data.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import TypeVar, overload + +from pandas import DataFrame +from seaborn._core.typing import DataSource, SupportsDataFrame, VariableSpec + +_T = TypeVar("_T", Mapping[Incomplete, Incomplete], None) + +class PlotData: + frame: DataFrame + frames: dict[tuple[str, str], DataFrame] + names: dict[str, str | None] + ids: dict[str, str | int] + source_data: DataSource + source_vars: dict[str, VariableSpec] + def __init__(self, data: DataSource, variables: dict[str, VariableSpec]) -> None: ... + def __contains__(self, key: str) -> bool: ... + def join(self, data: DataSource, variables: dict[str, VariableSpec] | None) -> PlotData: ... + +@overload +def handle_data_source(data: _T) -> _T: ... +@overload +def handle_data_source(data: SupportsDataFrame) -> DataFrame: ... + +def convert_dataframe_to_pandas(data: object) -> DataFrame: ... diff --git a/stubs/seaborn/seaborn/_core/exceptions.pyi b/stubs/seaborn/seaborn/_core/exceptions.pyi new file mode 100644 index 000000000000..c453083b113f --- /dev/null +++ b/stubs/seaborn/seaborn/_core/exceptions.pyi @@ -0,0 +1 @@ +class PlotSpecError(RuntimeError): ... diff --git a/stubs/seaborn/seaborn/_core/groupby.pyi b/stubs/seaborn/seaborn/_core/groupby.pyi new file mode 100644 index 000000000000..a07f2757c56b --- /dev/null +++ b/stubs/seaborn/seaborn/_core/groupby.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Hashable, Mapping +from typing import Concatenate, ParamSpec, TypeAlias + +from numpy import ufunc +from pandas import DataFrame + +# pandas._typing.AggFuncTypeFrame is partially Unknown +_AggFuncTypeBase: TypeAlias = Callable[..., Incomplete] | str | ufunc +_AggFuncTypeDictFrame: TypeAlias = Mapping[Hashable, _AggFuncTypeBase | list[_AggFuncTypeBase]] +_AggFuncTypeFrame: TypeAlias = _AggFuncTypeBase | list[_AggFuncTypeBase] | _AggFuncTypeDictFrame + +_P = ParamSpec("_P") + +class GroupBy: + order: dict[str, list[Incomplete] | None] + def __init__(self, order: list[str] | dict[str, list[Incomplete] | None]) -> None: ... + # Signature based on pandas.core.groupby.generic.DataFrameGroupBy.aggregate + # args and kwargs possible values depend on func which itself can be + # an attribute name, a mapping, a callable, or lead to a jitted numba function + def agg( + self, + data: DataFrame, + func: _AggFuncTypeFrame = ..., + *args, + engine: str | None = None, + engine_kwargs: dict[str, bool] | None = None, + **kwargs, + ) -> DataFrame: ... + def apply( + self, data: DataFrame, func: Callable[Concatenate[DataFrame, _P], DataFrame], *args: _P.args, **kwargs: _P.kwargs + ) -> DataFrame: ... diff --git a/stubs/seaborn/seaborn/_core/moves.pyi b/stubs/seaborn/seaborn/_core/moves.pyi new file mode 100644 index 000000000000..ed3f7f5e439a --- /dev/null +++ b/stubs/seaborn/seaborn/_core/moves.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from dataclasses import dataclass +from typing import ClassVar + +from pandas import DataFrame +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale +from seaborn._core.typing import Default + +default: Default + +@dataclass +class Move: + group_by_orient: ClassVar[bool] + def __call__(self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale]) -> DataFrame: ... + +@dataclass +class Jitter(Move): + width: float | Default = ... + x: float = 0 + y: float = 0 + seed: int | None = None + +@dataclass +class Dodge(Move): + empty: str = "keep" + gap: float = 0 + by: list[str] | None = None + +@dataclass +class Stack(Move): ... + +@dataclass +class Shift(Move): + x: float = 0 + y: float = 0 + +@dataclass +class Norm(Move): + func: Callable[..., Incomplete] | str = "max" + where: str | None = None + by: list[str] | None = None + percent: bool = False diff --git a/stubs/seaborn/seaborn/_core/plot.pyi b/stubs/seaborn/seaborn/_core/plot.pyi new file mode 100644 index 000000000000..8b8a5633dd44 --- /dev/null +++ b/stubs/seaborn/seaborn/_core/plot.pyi @@ -0,0 +1,153 @@ +import inspect +import os +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Generator +from contextlib import contextmanager +from typing import IO, Any, Literal, TypedDict, TypeVar +from typing_extensions import Never, Self + +import matplotlib as mpl +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.figure import Figure, SubFigure +from matplotlib.transforms import Bbox +from matplotlib.typing import ColorType +from seaborn._core.data import PlotData +from seaborn._core.moves import Move +from seaborn._core.scales import Scale +from seaborn._core.typing import DataSource, Default, OrderSpec, VariableSpec, VariableSpecList +from seaborn._marks.base import Mark +from seaborn._stats.base import Stat + +_ClsT = TypeVar("_ClsT", bound=type[Any]) + +default: Default + +class Layer(TypedDict, total=False): + mark: Mark + stat: Stat | None + move: Move | list[Move] | None + data: PlotData + source: DataSource + vars: dict[str, VariableSpec] + orient: str + legend: bool + label: str | None + +class FacetSpec(TypedDict, total=False): + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + wrap: int | None + +class PairSpec(TypedDict, total=False): + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + cross: bool + wrap: int | None + +@contextmanager +def theme_context(params: dict[str, Any]) -> Generator[None]: ... +def build_plot_signature(cls: _ClsT) -> _ClsT: ... # -> _ClsT & "__signature__ protocol" + +class ThemeConfig(mpl.RcParams): + THEME_GROUPS: list[str] + def __init__(self) -> None: ... + def reset(self) -> None: ... + def update(self, other: SupportsKeysAndGetItem[Incomplete, Incomplete] | None = None, /, **kwds) -> None: ... # type: ignore[override] + +class DisplayConfig(TypedDict): + format: Literal["png", "svg"] + scaling: float + hidpi: bool + +class PlotConfig: + def __init__(self) -> None: ... + @property + def theme(self) -> dict[str, Any]: ... + @property + def display(self) -> DisplayConfig: ... + +@build_plot_signature +class Plot: + __signature__: inspect.Signature + config: PlotConfig + def __init__(self, *args: DataSource | VariableSpec, data: DataSource = None, **variables: VariableSpec) -> None: ... + def __add__(self, other: Never) -> Never: ... + def on(self, target: Axes | SubFigure | Figure) -> Plot: ... + def add( + self, + mark: Mark, + *transforms: Stat | Move, + orient: str | None = None, + legend: bool = True, + label: str | None = None, + data: DataSource = None, + **variables: VariableSpec, + ) -> Plot: ... + def pair( + self, x: VariableSpecList = None, y: VariableSpecList = None, wrap: int | None = None, cross: bool = True + ) -> Plot: ... + def facet( + self, + col: VariableSpec = None, + row: VariableSpec = None, + order: OrderSpec | dict[str, OrderSpec] = None, + wrap: int | None = None, + ) -> Plot: ... + def scale(self, **scales: Scale) -> Plot: ... + def share(self, **shares: bool | str) -> Plot: ... + def limit(self, **limits: tuple[Any, Any]) -> Plot: ... + def label(self, *, title: str | None = None, legend: str | None = None, **variables: str | Callable[[str], str]) -> Plot: ... + def layout( + self, + *, + size: tuple[float, float] | Default = ..., + engine: str | Default | None = ..., + extent: tuple[float, float, float, float] | Default = ..., + ) -> Plot: ... + def theme(self, config: dict[str, Any], /) -> Plot: ... + # Same signature as Plotter.save + def save( + self, + loc: str | os.PathLike[Any] | IO[Any], + *, + transparent: bool | None = None, + dpi: float | None = 96, + facecolor: ColorType | Literal["auto"] | None = ..., + edgecolor: ColorType | Literal["auto"] | None = ..., + orientation: str = "protrait", + format: str | None = None, + bbox_inches: Literal["tight"] | Bbox | None = None, + pad_inches: float | None = None, + bbox_extra_artists: list[Artist] | None = None, + backend: str | None = None, + **kwargs: Any, + ) -> Self: ... + # Same signature as Plotter.show + def show(self, *, block: bool | None = None) -> None: ... + def plot(self, pyplot: bool = False) -> Plotter: ... + +class Plotter: + def __init__(self, pyplot: bool, theme: dict[str, Any]) -> None: ... + def save( + self, + loc: str | os.PathLike[Any] | IO[Any], + *, + # From matplotlib.figure.Figure.savefig + transparent: bool | None = None, + # keyword-only arguments below are the same as matplotlib.backend_bases.FigureCanvasBase.print_figure + # but with different defaults + dpi: float | None = 96, + facecolor: ColorType | Literal["auto"] | None = ..., + edgecolor: ColorType | Literal["auto"] | None = ..., + orientation: str = "protrait", + format: str | None = None, + bbox_inches: Literal["tight"] | Bbox | None = None, + pad_inches: float | None = None, + bbox_extra_artists: list[Artist] | None = None, + backend: str | None = None, + # Further **kwargs can truly be anything from an overridden Canvas method that is still passed down + **kwargs: Any, + ) -> Self: ... + # Same as matplotlib.backend_bases._Bases. No other backend override show + def show(self, *, block: bool | None = None) -> None: ... diff --git a/stubs/seaborn/seaborn/_core/properties.pyi b/stubs/seaborn/seaborn/_core/properties.pyi new file mode 100644 index 000000000000..548cc5a9d3ce --- /dev/null +++ b/stubs/seaborn/seaborn/_core/properties.pyi @@ -0,0 +1,97 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, TypeAlias + +from matplotlib.markers import MarkerStyle +from matplotlib.path import Path +from numpy.typing import ArrayLike +from pandas import Series +from seaborn._core.scales import Scale + +RGBTuple: TypeAlias = tuple[float, float, float] +RGBATuple: TypeAlias = tuple[float, float, float, float] +ColorSpec: TypeAlias = RGBTuple | RGBATuple | str +DashPattern: TypeAlias = tuple[float, ...] +DashPatternWithOffset: TypeAlias = tuple[float, DashPattern | None] +MarkerPattern: TypeAlias = float | str | tuple[int, int, float] | list[tuple[float, float]] | Path | MarkerStyle +Mapping: TypeAlias = Callable[[ArrayLike], ArrayLike] + +class Property: + legend: bool + normed: bool + variable: Incomplete + def __init__(self, variable: str | None = None) -> None: ... + def default_scale(self, data: Series[Any]) -> Scale: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + def standardize(self, val: Any) -> Any: ... + +class Coordinate(Property): + legend: bool + normed: bool + +class IntervalProperty(Property): + legend: bool + normed: bool + @property + def default_range(self) -> tuple[float, float]: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +class PointSize(IntervalProperty): ... + +class LineWidth(IntervalProperty): + @property + def default_range(self) -> tuple[float, float]: ... + +class EdgeWidth(IntervalProperty): + @property + def default_range(self) -> tuple[float, float]: ... + +class Stroke(IntervalProperty): ... +class Alpha(IntervalProperty): ... +class Offset(IntervalProperty): ... + +class FontSize(IntervalProperty): + @property + def default_range(self) -> tuple[float, float]: ... + +class ObjectProperty(Property): + legend: bool + normed: bool + null_value: Any + def default_scale(self, data: Series[Any]) -> Scale: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +class Marker(ObjectProperty): + null_value: Incomplete + def standardize(self, val: MarkerPattern) -> MarkerStyle: ... + +class LineStyle(ObjectProperty): + null_value: str + def standardize(self, val: str | DashPattern) -> DashPatternWithOffset: ... + +class TextAlignment(ObjectProperty): + legend: bool + +class HorizontalAlignment(TextAlignment): ... +class VerticalAlignment(TextAlignment): ... + +class Color(Property): + legend: bool + normed: bool + def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +class Fill(Property): + legend: bool + normed: bool + def default_scale(self, data: Series[Any]) -> Scale: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def standardize(self, val: Any) -> bool: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +PROPERTY_CLASSES: dict[str, type[Property]] +PROPERTIES: dict[str, Property] diff --git a/stubs/seaborn/seaborn/_core/rules.pyi b/stubs/seaborn/seaborn/_core/rules.pyi new file mode 100644 index 000000000000..8f07c919295a --- /dev/null +++ b/stubs/seaborn/seaborn/_core/rules.pyi @@ -0,0 +1,14 @@ +from collections import UserString +from typing import Any, Literal + +from pandas import Series + +class VarType(UserString): + allowed: tuple[str, ...] + def __init__(self, data: str) -> None: ... + def __eq__(self, other: str) -> bool: ... # type: ignore[override] + +def variable_type( + vector: Series[Any], boolean_type: Literal["numeric", "categorical", "boolean"] = "numeric", strict_boolean: bool = False +) -> VarType: ... +def categorical_order(vector: Series[Any], order: list[Any] | None = None) -> list[Any]: ... diff --git a/stubs/seaborn/seaborn/_core/scales.pyi b/stubs/seaborn/seaborn/_core/scales.pyi new file mode 100644 index 000000000000..d9783cae9cc5 --- /dev/null +++ b/stubs/seaborn/seaborn/_core/scales.pyi @@ -0,0 +1,100 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any, ClassVar, TypeAlias +from typing_extensions import Self + +from matplotlib.axis import Ticker +from matplotlib.scale import ScaleBase +from matplotlib.ticker import Formatter, Locator +from matplotlib.units import ConversionInterface +from numpy.typing import ArrayLike, NDArray +from pandas import Series +from seaborn._core.typing import Default + +TransFuncs: TypeAlias = tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] +Pipeline: TypeAlias = Sequence[Callable[[Any], Any] | None] + +class Scale: + values: tuple[Incomplete, ...] | str | list[Incomplete] | dict[Incomplete, Incomplete] | None + def __post_init__(self) -> None: ... + def tick(self) -> Self: ... + def label(self) -> Self: ... + def __call__(self, data: Series[Any]) -> ArrayLike: ... + +@dataclass +class Boolean(Scale): + values: tuple[Incomplete, ...] | list[Incomplete] | dict[Incomplete, Incomplete] | None = None + def tick(self, locator: Locator | None = None) -> Self: ... + def label(self, formatter: Formatter | None = None) -> Self: ... + +@dataclass +class Nominal(Scale): + values: tuple[Incomplete, ...] | str | list[Incomplete] | dict[Incomplete, Incomplete] | None = None + order: list[Incomplete] | None = None + def tick(self, locator: Locator | None = None) -> Self: ... + def label(self, formatter: Formatter | None = None) -> Self: ... + +@dataclass +class Ordinal(Scale): ... + +@dataclass +class Discrete(Scale): ... + +@dataclass +class ContinuousBase(Scale): + values: tuple[Incomplete, ...] | str | None = None + norm: tuple[Incomplete, ...] | None = None + +@dataclass +class Continuous(ContinuousBase): + values: tuple[Incomplete, ...] | str | None = None + trans: str | TransFuncs | None = None + def tick( + self, + locator: Locator | None = None, + *, + at: Sequence[float] | None = None, + upto: int | None = None, + count: int | None = None, + every: float | None = None, + between: tuple[float, float] | None = None, + minor: int | None = None, + ) -> Self: ... + def label( + self, + formatter: Formatter | None = None, + *, + like: str | Callable[[float], str] | None = None, + base: int | Default | None = ..., + unit: str | None = None, + ) -> Self: ... + +@dataclass +class Temporal(ContinuousBase): + trans: ClassVar[Incomplete] # not sure it is a classvar but the runtime has no annotation so it is not a dataclass field + def tick(self, locator: Locator | None = None, *, upto: int | None = None) -> Self: ... + def label(self, formatter: Formatter | None = None, *, concise: bool = False) -> Self: ... + +class PseudoAxis: + axis_name: str + converter: ConversionInterface | None + units: Incomplete | None + scale: ScaleBase + major: Ticker + minor: Ticker + def __init__(self, scale: ScaleBase) -> None: ... + def set_view_interval(self, vmin: float, vmax: float) -> None: ... + def get_view_interval(self) -> tuple[float, float]: ... + def set_data_interval(self, vmin: float, vmax: float) -> None: ... + def get_data_interval(self) -> tuple[float, float]: ... + def get_tick_space(self) -> int: ... + def set_major_locator(self, locator: Locator) -> None: ... + def set_major_formatter(self, formatter: Formatter) -> None: ... + def set_minor_locator(self, locator: Locator) -> None: ... + def set_minor_formatter(self, formatter: Formatter) -> None: ... + def set_units(self, units) -> None: ... + def update_units(self, x) -> None: ... + def convert_units(self, x): ... + def get_scale(self) -> ScaleBase: ... + def get_majorticklocs(self) -> NDArray[Incomplete]: ... diff --git a/stubs/seaborn/seaborn/_core/subplots.pyi b/stubs/seaborn/seaborn/_core/subplots.pyi new file mode 100644 index 000000000000..a3713e2f30de --- /dev/null +++ b/stubs/seaborn/seaborn/_core/subplots.pyi @@ -0,0 +1,19 @@ +from collections.abc import Iterator +from typing import Any + +from matplotlib.axes import Axes +from matplotlib.figure import Figure, SubFigure +from seaborn._core.plot import FacetSpec, PairSpec + +class Subplots: + subplot_spec: dict[str, Any] + def __init__(self, subplot_spec: dict[str, Any], facet_spec: FacetSpec, pair_spec: PairSpec) -> None: ... + def init_figure( + self, + pair_spec: PairSpec, + pyplot: bool = False, + figure_kws: dict[str, Any] | None = None, + target: Axes | Figure | SubFigure | None = None, + ) -> Figure: ... + def __iter__(self) -> Iterator[dict[str, Any]]: ... + def __len__(self) -> int: ... diff --git a/stubs/seaborn/seaborn/_core/typing.pyi b/stubs/seaborn/seaborn/_core/typing.pyi new file mode 100644 index 000000000000..c114bdf8f09f --- /dev/null +++ b/stubs/seaborn/seaborn/_core/typing.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from datetime import date, datetime, timedelta +from typing import Any, Protocol, TypeAlias, type_check_only + +from matplotlib.colors import Colormap, Normalize +from numpy import ndarray +from pandas import DataFrame, Index, Series, Timedelta, Timestamp + +@type_check_only +class SupportsDataFrame(Protocol): + def __dataframe__(self, nan_as_null: bool = ..., allow_copy: bool = ...): ... + +ColumnName: TypeAlias = str | bytes | date | datetime | timedelta | bool | complex | Timestamp | Timedelta +Vector: TypeAlias = Series[Any] | Index[Any] | ndarray[Any, Any] +VariableSpec: TypeAlias = ColumnName | Vector | None +VariableSpecList: TypeAlias = list[VariableSpec] | Index[Any] | None +DataSource: TypeAlias = DataFrame | SupportsDataFrame | Mapping[Any, Incomplete] | None +OrderSpec: TypeAlias = Iterable[str] | None +NormSpec: TypeAlias = tuple[float | None, float | None] | Normalize | None +PaletteSpec: TypeAlias = str | list[Incomplete] | dict[Incomplete, Incomplete] | Colormap | None +DiscreteValueSpec: TypeAlias = dict[Incomplete, Incomplete] | list[Incomplete] | None +ContinuousValueSpec: TypeAlias = tuple[float, float] | list[float] | dict[Any, float] | None + +class Default: ... +class Deprecated: ... + +default: Default +deprecated: Deprecated diff --git a/stubs/seaborn/seaborn/_marks/__init__.pyi b/stubs/seaborn/seaborn/_marks/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/_marks/area.pyi b/stubs/seaborn/seaborn/_marks/area.pyi new file mode 100644 index 000000000000..04cca8781ee7 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/area.pyi @@ -0,0 +1,28 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableBool, MappableColor, MappableFloat, MappableStyle, Mark, document_properties + +class AreaBase: ... + +@document_properties +@dataclass +class Area(AreaBase, Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + baseline: MappableFloat = ... + +@document_properties +@dataclass +class Band(AreaBase, Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/bar.pyi b/stubs/seaborn/seaborn/_marks/bar.pyi new file mode 100644 index 000000000000..5cee9ad83af8 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/bar.pyi @@ -0,0 +1,31 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableBool, MappableColor, MappableFloat, MappableStyle, Mark, document_properties + +class BarBase(Mark): ... + +@document_properties +@dataclass +class Bar(BarBase): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + width: MappableFloat = ... + baseline: MappableFloat = ... + +@document_properties +@dataclass +class Bars(BarBase): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + width: MappableFloat = ... + baseline: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/base.pyi b/stubs/seaborn/seaborn/_marks/base.pyi new file mode 100644 index 000000000000..80989c2f4274 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/base.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from dataclasses import dataclass +from typing import Any, TypeAlias, TypeVar + +from numpy.typing import NDArray +from pandas import DataFrame +from seaborn._core.properties import DashPattern, DashPatternWithOffset, RGBATuple +from seaborn._core.scales import Scale + +_MarkT = TypeVar("_MarkT", bound=type[Mark]) + +class Mappable: + def __init__( + self, val: Any = None, depend: str | None = None, rc: str | None = None, auto: bool = False, grouping: bool = True + ) -> None: ... + @property + def depend(self) -> Any: ... # -> str | None + @property + def grouping(self) -> bool: ... + @property + def default(self) -> Any: ... + +MappableBool: TypeAlias = bool | Mappable +MappableString: TypeAlias = str | Mappable +MappableFloat: TypeAlias = float | Mappable +MappableColor: TypeAlias = str | tuple[Incomplete, ...] | Mappable +MappableStyle: TypeAlias = str | DashPattern | DashPatternWithOffset | Mappable + +@dataclass +class Mark: + artist_kws: dict[str, Any] = ... + +def resolve_properties(mark: Mark, data: DataFrame, scales: dict[str, Scale]) -> dict[str, Any]: ... +def resolve_color( + mark: Mark, data: DataFrame | dict[str, Any], prefix: str = "", scales: dict[str, Scale] | None = None +) -> RGBATuple | NDArray[Incomplete]: ... +def document_properties(mark: _MarkT) -> _MarkT: ... diff --git a/stubs/seaborn/seaborn/_marks/dot.pyi b/stubs/seaborn/seaborn/_marks/dot.pyi new file mode 100644 index 000000000000..6b5a0428a3de --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/dot.pyi @@ -0,0 +1,39 @@ +from dataclasses import dataclass + +from seaborn._marks.base import ( + MappableBool, + MappableColor, + MappableFloat, + MappableString, + MappableStyle, + Mark, + document_properties, +) + +class DotBase(Mark): ... + +@document_properties +@dataclass +class Dot(DotBase): + marker: MappableString = ... + pointsize: MappableFloat = ... + stroke: MappableFloat = ... + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + +@document_properties +@dataclass +class Dots(DotBase): + marker: MappableString = ... + pointsize: MappableFloat = ... + stroke: MappableFloat = ... + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + fillcolor: MappableColor = ... + fillalpha: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/line.pyi b/stubs/seaborn/seaborn/_marks/line.pyi new file mode 100644 index 000000000000..71594380a7f7 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/line.pyi @@ -0,0 +1,42 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableColor, MappableFloat, MappableString, Mark, document_properties + +@document_properties +@dataclass +class Path(Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + linewidth: MappableFloat = ... + linestyle: MappableString = ... + marker: MappableString = ... + pointsize: MappableFloat = ... + fillcolor: MappableColor = ... + edgecolor: MappableColor = ... + edgewidth: MappableFloat = ... + +@document_properties +@dataclass +class Line(Path): ... + +@document_properties +@dataclass +class Paths(Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + linewidth: MappableFloat = ... + linestyle: MappableString = ... + def __post_init__(self) -> None: ... + +@document_properties +@dataclass +class Lines(Paths): ... + +@document_properties +@dataclass +class Range(Paths): ... + +@document_properties +@dataclass +class Dash(Paths): + width: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/text.pyi b/stubs/seaborn/seaborn/_marks/text.pyi new file mode 100644 index 000000000000..a8c72fe0cdcc --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/text.pyi @@ -0,0 +1,14 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableColor, MappableFloat, MappableString, Mark, document_properties + +@document_properties +@dataclass +class Text(Mark): + text: MappableString = ... + color: MappableColor = ... + alpha: MappableFloat = ... + fontsize: MappableFloat = ... + halign: MappableString = ... + valign: MappableString = ... + offset: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_stats/__init__.pyi b/stubs/seaborn/seaborn/_stats/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/_stats/aggregation.pyi b/stubs/seaborn/seaborn/_stats/aggregation.pyi new file mode 100644 index 000000000000..cf30b12a2dc4 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/aggregation.pyi @@ -0,0 +1,19 @@ +from collections.abc import Callable +from dataclasses import dataclass + +from seaborn._core.typing import Vector +from seaborn._stats.base import Stat + +@dataclass +class Agg(Stat): + func: str | Callable[[Vector], float] = "mean" + +@dataclass +class Est(Stat): + func: str | Callable[[Vector], float] = "mean" + errorbar: str | tuple[str, float] = ("ci", 95) + n_boot: int = 1000 + seed: int | None = None + +@dataclass +class Rolling(Stat): ... diff --git a/stubs/seaborn/seaborn/_stats/base.pyi b/stubs/seaborn/seaborn/_stats/base.pyi new file mode 100644 index 000000000000..7f3184b4e72b --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/base.pyi @@ -0,0 +1,11 @@ +from dataclasses import dataclass +from typing import ClassVar + +from pandas import DataFrame +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale + +@dataclass +class Stat: + group_by_orient: ClassVar[bool] + def __call__(self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale]) -> DataFrame: ... diff --git a/stubs/seaborn/seaborn/_stats/counting.pyi b/stubs/seaborn/seaborn/_stats/counting.pyi new file mode 100644 index 000000000000..b6283af97cdd --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/counting.pyi @@ -0,0 +1,19 @@ +from dataclasses import dataclass + +from numpy.typing import ArrayLike +from seaborn._stats.base import Stat + +@dataclass +class Count(Stat): ... + +@dataclass +class Hist(Stat): + stat: str = "count" + bins: str | int | ArrayLike = "auto" + binwidth: float | None = None + binrange: tuple[float, float] | None = None + common_norm: bool | list[str] = True + common_bins: bool | list[str] = True + cumulative: bool = False + discrete: bool = False + def __post_init__(self) -> None: ... diff --git a/stubs/seaborn/seaborn/_stats/density.pyi b/stubs/seaborn/seaborn/_stats/density.pyi new file mode 100644 index 000000000000..386424ccbcd3 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/density.pyi @@ -0,0 +1,15 @@ +from dataclasses import dataclass + +from seaborn._stats.base import Stat +from seaborn.external.kde import _BwMethodType + +@dataclass +class KDE(Stat): + bw_adjust: float = 1 + bw_method: _BwMethodType = "scott" + common_norm: bool | list[str] = True + common_grid: bool | list[str] = True + gridsize: int | None = 200 + cut: float = 3 + cumulative: bool = False + def __post_init__(self) -> None: ... diff --git a/stubs/seaborn/seaborn/_stats/order.pyi b/stubs/seaborn/seaborn/_stats/order.pyi new file mode 100644 index 000000000000..8950dc411d36 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/order.pyi @@ -0,0 +1,8 @@ +from dataclasses import dataclass + +from seaborn._stats.base import Stat + +@dataclass +class Perc(Stat): + k: int | list[float] = 5 + method: str = "linear" diff --git a/stubs/seaborn/seaborn/_stats/regression.pyi b/stubs/seaborn/seaborn/_stats/regression.pyi new file mode 100644 index 000000000000..c5f9fcf25170 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/regression.pyi @@ -0,0 +1,11 @@ +from dataclasses import dataclass + +from seaborn._stats.base import Stat + +@dataclass +class PolyFit(Stat): + order: int = 2 + gridsize: int = 100 + +@dataclass +class OLSFit(Stat): ... diff --git a/stubs/seaborn/seaborn/algorithms.pyi b/stubs/seaborn/seaborn/algorithms.pyi new file mode 100644 index 000000000000..d413cdee161c --- /dev/null +++ b/stubs/seaborn/seaborn/algorithms.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable +from typing import Any, overload +from typing_extensions import deprecated + +from numpy.typing import ArrayLike, NDArray + +from .utils import _Seed + +@overload +def bootstrap( + *args: ArrayLike, + n_boot: int = 10000, + func: str | Callable[..., Any] = "mean", + axis: int | None = None, + units: ArrayLike | None = None, + seed: _Seed | None = None, +) -> NDArray[Any]: ... +@overload +@deprecated("Parameter `random_seed` is deprecated in favor of `seed`") +def bootstrap( + *args: ArrayLike, + n_boot: int = 10000, + func: str | Callable[..., Any] = "mean", + axis: int | None = None, + units: ArrayLike | None = None, + seed: _Seed | None = None, + random_seed: _Seed | None = None, +) -> NDArray[Any]: ... diff --git a/stubs/seaborn/seaborn/axisgrid.pyi b/stubs/seaborn/seaborn/axisgrid.pyi new file mode 100644 index 000000000000..80014f241ea7 --- /dev/null +++ b/stubs/seaborn/seaborn/axisgrid.pyi @@ -0,0 +1,402 @@ +import os +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterable, Mapping +from typing import IO, Any, Concatenate, Literal, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self, deprecated + +import numpy as np +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.backend_bases import MouseEvent, RendererBase +from matplotlib.colors import Colormap +from matplotlib.figure import Figure +from matplotlib.font_manager import FontProperties +from matplotlib.gridspec import SubplotSpec +from matplotlib.legend import Legend +from matplotlib.patches import Patch +from matplotlib.path import Path as mpl_Path +from matplotlib.patheffects import AbstractPathEffect +from matplotlib.scale import ScaleBase +from matplotlib.text import Text +from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath +from matplotlib.typing import ColorType, LineStyleType, MarkerType +from numpy.typing import ArrayLike, NDArray +from pandas import DataFrame, Series + +from ._core.typing import ColumnName, DataSource, NormSpec, SupportsDataFrame +from .palettes import _RGBColorPalette +from .utils import _DataSourceWideForm, _Palette, _Vector + +__all__ = ["FacetGrid", "PairGrid", "JointGrid", "pairplot", "jointplot"] + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +_LiteralFont: TypeAlias = Literal["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"] + +class _BaseGrid: + def set( + self, + *, + # Keywords follow `matplotlib.axes.Axes.set`. Each keyword corresponds to a `set_` method + adjustable: Literal["box", "datalim"] = ..., + agg_filter: Callable[[ArrayLike, float], tuple[NDArray[np.floating[Any]], float, float]] | None = ..., + alpha: float | None = ..., + anchor: str | tuple[float, float] = ..., + animated: bool = ..., + aspect: float | Literal["auto", "equal"] = ..., + autoscale_on: bool = ..., + autoscalex_on: bool = ..., + autoscaley_on: bool = ..., + axes_locator: Callable[[Axes, RendererBase], Bbox] = ..., + axisbelow: bool | Literal["line"] = ..., + box_aspect: float | None = ..., + clip_box: BboxBase | None = ..., + clip_on: bool = ..., + clip_path: Patch | mpl_Path | TransformedPath | None = ..., + facecolor: ColorType | None = ..., + frame_on: bool = ..., + gid: str | None = ..., + in_layout: bool = ..., + label: object = ..., + mouseover: bool = ..., + navigate: bool = ..., + path_effects: list[AbstractPathEffect] = ..., + picker: bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]] | None = ..., + position: Bbox | tuple[float, float, float, float] = ..., + prop_cycle=..., # TODO: use cycler.Cycler when cycler gets typed + rasterization_zorder: float | None = ..., + rasterized: bool = ..., + sketch_params: float | None = ..., + snap: bool | None = ..., + subplotspec: SubplotSpec = ..., + title: str = ..., + transform: Transform | None = ..., + url: str | None = ..., + visible: bool = ..., + xbound: float | tuple[float | None, float | None] | None = ..., + xlabel: str = ..., + xlim: float | tuple[float | None, float | None] | None = ..., + xmargin: float = ..., + xscale: str | ScaleBase = ..., + xticklabels: Iterable[str | Text] = ..., + xticks: ArrayLike = ..., + ybound: float | tuple[float | None, float | None] | None = ..., + ylabel: str = ..., + ylim: float | tuple[float | None, float | None] | None = ..., + ymargin: float = ..., + yscale: str | ScaleBase = ..., + yticklabels: Iterable[str | Text] = ..., + yticks: ArrayLike = ..., + zorder: float = ..., + **kwargs: Any, + ) -> Self: ... + @property + @deprecated("Attribute `fig` is deprecated in favor of `figure`") + def fig(self) -> Figure: ... + @property + def figure(self) -> Figure: ... + def apply(self, func: Callable[Concatenate[Self, _P], object], *args: _P.args, **kwargs: _P.kwargs) -> Self: ... + def pipe(self, func: Callable[Concatenate[Self, _P], _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + def savefig( + self, + # Signature follows `matplotlib.figure.Figure.savefig` + fname: str | os.PathLike[Any] | IO[Any], + *, + transparent: bool | None = None, + dpi: float | Literal["figure"] | None = 96, + facecolor: ColorType | Literal["auto"] | None = "auto", + edgecolor: ColorType | Literal["auto"] | None = "auto", + orientation: Literal["landscape", "portrait"] = "portrait", + format: str | None = None, + bbox_inches: Literal["tight"] | Bbox | None = "tight", + pad_inches: float | Literal["layout"] | None = None, + backend: str | None = None, + **kwargs: Any, + ) -> None: ... + +class Grid(_BaseGrid): + def __init__(self) -> None: ... + def tight_layout( + self, + *, + # Keywords follow `matplotlib.figure.Figure.tight_layout` + pad: float = 1.08, + h_pad: float | None = None, + w_pad: float | None = None, + rect: tuple[float, float, float, float] | None = None, + ) -> Self: ... + def add_legend( + self, + # Cannot use precise key type with union for legend_data because of invariant Mapping keys + legend_data: Mapping[Any, Artist] | None = None, + title: str | None = None, + label_order: list[str] | None = None, + adjust_subtitles: bool = False, + *, + # Keywords follow `matplotlib.legend.Legend` + loc: str | int | tuple[float, float] | None = None, + numpoints: int | None = None, + markerscale: float | None = None, + markerfirst: bool = True, + reverse: bool = False, + scatterpoints: int | None = None, + scatteryoffsets: Iterable[float] | None = None, + prop: FontProperties | dict[str, Any] | None = None, + fontsize: int | _LiteralFont | None = None, + labelcolor: str | Iterable[str] | None = None, + borderpad: float | None = None, + labelspacing: float | None = None, + handlelength: float | None = None, + handleheight: float | None = None, + handletextpad: float | None = None, + borderaxespad: float | None = None, + columnspacing: float | None = None, + ncols: int = 1, + mode: Literal["expand"] | None = None, + fancybox: bool | None = None, + shadow: bool | dict[str, int] | dict[str, float] | None = None, + title_fontsize: int | _LiteralFont | None = None, + framealpha: float | None = None, + edgecolor: ColorType | None = None, + facecolor: ColorType | None = None, + bbox_to_anchor: BboxBase | tuple[float, float] | tuple[float, float, float, float] | None = None, + bbox_transform: Transform | None = None, + frameon: bool | None = None, + handler_map: None = None, + title_fontproperties: FontProperties | None = None, + alignment: Literal["center", "left", "right"] = "center", + ncol: int = 1, + draggable: bool = False, + ) -> Self: ... + @property + def legend(self) -> Legend | None: ... + def tick_params( + self, + axis: Literal["x", "y", "both"] = "both", + *, + # Keywords follow `matplotlib.axes.Axes.tick_params` + which: Literal["major", "minor", "both"] = "major", + reset: bool = False, + direction: Literal["in", "out", "inout"] = ..., + length: float = ..., + width: float = ..., + color: ColorType = ..., + pad: float = ..., + labelsize: float | str = ..., + labelcolor: ColorType = ..., + labelfontfamily: str = ..., + colors: ColorType = ..., + zorder: float = ..., + bottom: bool = ..., + top: bool = ..., + left: bool = ..., + right: bool = ..., + labelbottom: bool = ..., + labeltop: bool = ..., + labelleft: bool = ..., + labelright: bool = ..., + labelrotation: float = ..., + grid_color: ColorType = ..., + grid_alpha: float = ..., + grid_linewidth: float = ..., + grid_linestyle: str = ..., + **kwargs: Any, + ) -> Self: ... + +class FacetGrid(Grid): + data: DataFrame + row_names: list[Any] + col_names: list[Any] + hue_names: list[Any] | None + hue_kws: dict[str, Any] + def __init__( + self, + data: DataFrame | SupportsDataFrame, + *, + row: str | None = None, + col: str | None = None, + hue: str | None = None, + col_wrap: int | None = None, + sharex: bool | Literal["col", "row"] = True, + sharey: bool | Literal["col", "row"] = True, + height: float = 3, + aspect: float = 1, + palette: _Palette | None = None, + row_order: Iterable[Any] | None = None, + col_order: Iterable[Any] | None = None, + hue_order: Iterable[Any] | None = None, + hue_kws: dict[str, Any] | None = None, + dropna: bool = False, + legend_out: bool = True, + despine: bool = True, + margin_titles: bool = False, + xlim: tuple[float, float] | None = None, + ylim: tuple[float, float] | None = None, + subplot_kws: dict[str, Any] | None = None, + gridspec_kws: dict[str, Any] | None = None, + ) -> None: ... + def facet_data(self) -> Generator[tuple[tuple[int, int, int], DataFrame]]: ... + def map(self, func: Callable[..., object], *args: str, **kwargs: Any) -> Self: ... + def map_dataframe(self, func: Callable[..., object], *args: str, **kwargs: Any) -> Self: ... + def facet_axis(self, row_i: int, col_j: int, modify_state: bool = True) -> Axes: ... + # `despine` should be kept roughly in line with `seaborn.utils.despine` + def despine( + self, + *, + ax: Axes | None = None, + top: bool = True, + right: bool = True, + left: bool = False, + bottom: bool = False, + offset: int | Mapping[str, int] | None = None, + trim: bool = False, + ) -> Self: ... + def set_axis_labels( + self, x_var: str | None = None, y_var: str | None = None, clear_inner: bool = True, **kwargs: Any + ) -> Self: ... + def set_xlabels(self, label: str | None = None, clear_inner: bool = True, **kwargs: Any) -> Self: ... + def set_ylabels(self, label: str | None = None, clear_inner: bool = True, **kwargs: Any) -> Self: ... + def set_xticklabels(self, labels: Iterable[str | Text] | None = None, step: int | None = None, **kwargs: Any) -> Self: ... + def set_yticklabels(self, labels: Iterable[str | Text] | None = None, **kwargs: Any) -> Self: ... + def set_titles( + self, template: str | None = None, row_template: str | None = None, col_template: str | None = None, **kwargs: Any + ) -> Self: ... + def refline( + self, + *, + x: float | None = None, + y: float | None = None, + color: ColorType = ".5", + linestyle: LineStyleType = "--", + **line_kws: Any, + ) -> Self: ... + @property + def axes(self) -> NDArray[Incomplete]: ... # array of `Axes` + @property + def ax(self) -> Axes: ... + @property + def axes_dict(self) -> dict[Any, Axes]: ... + +class PairGrid(Grid): + x_vars: list[str] + y_vars: list[str] + square_grid: bool + axes: NDArray[Incomplete] # two-dimensional array of `Axes` + data: DataFrame + diag_sharey: bool + diag_vars: list[str] | None + diag_axes: list[Axes] | None + hue_names: list[str] + hue_vals: Series[Any] + hue_kws: dict[str, Any] + palette: _RGBColorPalette + def __init__( + self, + data: DataFrame | SupportsDataFrame, + *, + hue: str | None = None, + vars: Iterable[str] | None = None, + x_vars: Iterable[str] | str | None = None, + y_vars: Iterable[str] | str | None = None, + hue_order: Iterable[str] | None = None, + palette: _Palette | None = None, + hue_kws: dict[str, Any] | None = None, + corner: bool = False, + diag_sharey: bool = True, + height: float = 2.5, + aspect: float = 1, + layout_pad: float = 0.5, + despine: bool = True, + dropna: bool = False, + ) -> None: ... + def map(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_lower(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_upper(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_offdiag(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_diag(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + +class JointGrid(_BaseGrid): + ax_joint: Axes + ax_marg_x: Axes + ax_marg_y: Axes + x: Series[Any] + y: Series[Any] + hue: Series[Any] + def __init__( + self, + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + height: float = 6, + ratio: float = 5, + space: float = 0.2, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + dropna: bool = False, + xlim: float | tuple[float, float] | None = None, + ylim: float | tuple[float, float] | None = None, + marginal_ticks: bool = False, + ) -> None: ... + def plot(self, joint_func: Callable[..., object], marginal_func: Callable[..., object], **kwargs: Any) -> Self: ... + def plot_joint(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def plot_marginals(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def refline( + self, + *, + x: float | None = None, + y: float | None = None, + joint: bool = True, + marginal: bool = True, + color: ColorType = ".5", + linestyle: LineStyleType = "--", + **line_kws: Any, + ) -> Self: ... + def set_axis_labels(self, xlabel: str = "", ylabel: str = "", **kwargs: Any) -> Self: ... + +def pairplot( + data: DataFrame, + *, + hue: str | None = None, + hue_order: Iterable[str] | None = None, + palette: _Palette | None = None, + vars: Iterable[str] | None = None, + x_vars: Iterable[str] | str | None = None, + y_vars: Iterable[str] | str | None = None, + kind: Literal["scatter", "kde", "hist", "reg"] = "scatter", + diag_kind: Literal["auto", "hist", "kde"] | None = "auto", + markers: MarkerType | list[MarkerType] | None = None, + height: float = 2.5, + aspect: float = 1, + corner: bool = False, + dropna: bool = False, + plot_kws: dict[str, Any] | None = None, + diag_kws: dict[str, Any] | None = None, + grid_kws: dict[str, Any] | None = None, + size: float | None = None, # deprecated +) -> PairGrid: ... +def jointplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + kind: Literal["scatter", "kde", "hist", "hex", "reg", "resid"] = "scatter", + height: float = 6, + ratio: float = 5, + space: float = 0.2, + dropna: bool = False, + xlim: float | tuple[float, float] | None = None, + ylim: float | tuple[float, float] | None = None, + color: ColorType | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + marginal_ticks: bool = False, + joint_kws: dict[str, Any] | None = None, + marginal_kws: dict[str, Any] | None = None, + **kwargs: Any, +) -> JointGrid: ... diff --git a/stubs/seaborn/seaborn/categorical.pyi b/stubs/seaborn/seaborn/categorical.pyi new file mode 100644 index 000000000000..eed93a807628 --- /dev/null +++ b/stubs/seaborn/seaborn/categorical.pyi @@ -0,0 +1,294 @@ +from collections.abc import Callable, Iterable +from typing import Any, Literal + +from matplotlib.axes import Axes +from matplotlib.typing import ColorType, LineStyleType, MarkerType + +from ._core.typing import ColumnName, DataSource, Default, NormSpec +from .axisgrid import FacetGrid +from .external.kde import _BwMethodType +from .utils import _DataSourceWideForm, _ErrorBar, _Estimator, _Legend, _LogScale, _Palette, _Seed, _Vector + +__all__ = ["catplot", "stripplot", "swarmplot", "boxplot", "violinplot", "boxenplot", "pointplot", "barplot", "countplot"] + +def boxplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + dodge: bool | Literal["auto"] = "auto", + width: float = 0.8, + gap: float = 0, + whis: float | tuple[float, float] = 1.5, + linecolor: ColorType = "auto", + linewidth: float | None = None, + fliersize: float | None = None, + hue_norm: NormSpec = None, + native_scale: bool = False, + log_scale: _LogScale | None = None, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def violinplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + inner: str | None = "box", + split: bool = False, + width: float = 0.8, + dodge: bool | Literal["auto"] = "auto", + gap: float = 0, + linewidth: float | None = None, + linecolor: ColorType = "auto", + cut: float = 2, + gridsize: int = 100, + bw_method: _BwMethodType = "scott", + bw_adjust: float = 1, + density_norm: Literal["area", "count", "width"] = "area", + common_norm: bool | None = False, + hue_norm: NormSpec = None, + formatter: Callable[[Any], str] | None = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + legend: _Legend = "auto", + scale=..., # deprecated + scale_hue=..., # deprecated + bw=..., # deprecated + inner_kws: dict[str, Any] | None = None, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def boxenplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + dodge: bool | Literal["auto"] = "auto", + width: float = 0.8, + gap: float = 0, + linewidth: float | None = None, + linecolor: ColorType | None = None, + width_method: Literal["exponential", "linear", "area"] = "exponential", + k_depth: Literal["tukey", "proportion", "trustworthy", "full"] | int = "tukey", + outlier_prop: float = 0.007, + trust_alpha: float = 0.05, + showfliers: bool = True, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + scale=..., # deprecated + box_kws: dict[str, Any] | None = None, + flier_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def stripplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + jitter: float | Literal[True] = True, + dodge: bool = False, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + size: float = 5, + edgecolor: ColorType | Default = ..., + linewidth: float = 0, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def swarmplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + dodge: bool = False, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + size: float = 5, + edgecolor: ColorType | None = None, + linewidth: float = 0, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + warn_thresh: float = 0.05, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def barplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + estimator: _Estimator = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + seed: _Seed | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + hue_norm: NormSpec = None, + width: float = 0.8, + dodge: bool | Literal["auto"] = "auto", + gap: float = 0, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + capsize: float = 0, + err_kws: dict[str, Any] | None = None, + ci=..., # deprecated + errcolor=..., # deprecated + errwidth=..., # deprecated + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def pointplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + estimator: _Estimator = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + seed: _Seed | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + hue_norm: NormSpec = None, + markers: MarkerType | list[MarkerType] | Default = ..., + linestyles: LineStyleType | list[LineStyleType] | Default = ..., + dodge: bool = False, + log_scale: _LogScale | None = None, + native_scale: bool = False, + orient: Literal["v", "h", "x", "y"] | None = None, + capsize: float = 0, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + err_kws: dict[str, Any] | None = None, + ci=..., # deprecated + errwidth=..., # deprecated + join=..., # deprecated + scale=..., # deprecated + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def countplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + hue_norm: NormSpec = None, + stat: Literal["count", "percent", "proportion", "probability"] = "count", + width: float = 0.8, + dodge: bool | Literal["auto"] = "auto", + gap: float = 0, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def catplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + row: ColumnName | _Vector | None = None, + col: ColumnName | _Vector | None = None, + kind: Literal["strip", "swarm", "box", "violin", "boxen", "point", "bar", "count"] = "strip", + estimator: _Estimator = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + seed: _Seed | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + row_order: Iterable[ColumnName] | None = None, + col_order: Iterable[ColumnName] | None = None, + col_wrap: int | None = None, + height: float = 5, + aspect: float = 1, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + hue_norm: NormSpec = None, + legend: _Legend = "auto", + legend_out: bool = True, + sharex: bool = True, + sharey: bool = True, + margin_titles: bool = False, + facet_kws: dict[str, Any] | None = None, + ci=..., # deprecated + **kwargs: Any, +) -> FacetGrid: ... diff --git a/stubs/seaborn/seaborn/cm.pyi b/stubs/seaborn/seaborn/cm.pyi new file mode 100644 index 000000000000..85c912b97d2d --- /dev/null +++ b/stubs/seaborn/seaborn/cm.pyi @@ -0,0 +1,15 @@ +from matplotlib.colors import ListedColormap + +# generated +rocket: ListedColormap +mako: ListedColormap +icefire: ListedColormap +vlag: ListedColormap +flare: ListedColormap +crest: ListedColormap +rocket_r: ListedColormap +mako_r: ListedColormap +icefire_r: ListedColormap +vlag_r: ListedColormap +flare_r: ListedColormap +crest_r: ListedColormap diff --git a/stubs/seaborn/seaborn/colors/__init__.pyi b/stubs/seaborn/seaborn/colors/__init__.pyi new file mode 100644 index 000000000000..f2f1b9731393 --- /dev/null +++ b/stubs/seaborn/seaborn/colors/__init__.pyi @@ -0,0 +1,2 @@ +from .crayons import crayons as crayons +from .xkcd_rgb import xkcd_rgb as xkcd_rgb diff --git a/stubs/seaborn/seaborn/colors/crayons.pyi b/stubs/seaborn/seaborn/colors/crayons.pyi new file mode 100644 index 000000000000..c0479d29f98f --- /dev/null +++ b/stubs/seaborn/seaborn/colors/crayons.pyi @@ -0,0 +1 @@ +crayons: dict[str, str] diff --git a/stubs/seaborn/seaborn/colors/xkcd_rgb.pyi b/stubs/seaborn/seaborn/colors/xkcd_rgb.pyi new file mode 100644 index 000000000000..0ac3abc8087c --- /dev/null +++ b/stubs/seaborn/seaborn/colors/xkcd_rgb.pyi @@ -0,0 +1 @@ +xkcd_rgb: dict[str, str] diff --git a/stubs/seaborn/seaborn/distributions.pyi b/stubs/seaborn/seaborn/distributions.pyi new file mode 100644 index 000000000000..036a0d9d4e43 --- /dev/null +++ b/stubs/seaborn/seaborn/distributions.pyi @@ -0,0 +1,171 @@ +from collections.abc import Iterable +from typing import Any, Literal, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import deprecated + +from matplotlib.axes import Axes +from matplotlib.colors import Colormap +from matplotlib.typing import ColorType +from numpy.typing import ArrayLike + +from ._core.typing import ColumnName, DataSource, NormSpec +from .axisgrid import FacetGrid +from .external.kde import _BwMethodType +from .utils import _DataSourceWideForm, _LogScale, _Palette, _Vector + +__all__ = ["displot", "histplot", "kdeplot", "ecdfplot", "rugplot", "distplot"] + +_T = TypeVar("_T") +_OneOrPair: TypeAlias = _T | tuple[_T, _T] + +@type_check_only +class _Fit(Protocol): + def fit(self, a: ArrayLike) -> tuple[ArrayLike, ...]: ... + def pdf(self, x: ArrayLike, *params: ArrayLike) -> ArrayLike: ... + +def histplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + stat: str = "count", + bins: _OneOrPair[str | int | ArrayLike] = "auto", + binwidth: float | tuple[float, float] | None = None, + binrange: _OneOrPair[tuple[float, float]] | None = None, + discrete: bool | None = None, + cumulative: bool = False, + common_bins: bool = True, + common_norm: bool = True, + multiple: Literal["layer", "dodge", "stack", "fill"] = "layer", + element: Literal["bars", "step", "poly"] = "bars", + fill: bool = True, + shrink: float = 1, + kde: bool = False, + kde_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + thresh: float | None = 0, + pthresh: float | None = None, + pmax: float | None = None, + cbar: bool = False, + cbar_ax: Axes | None = None, + cbar_kws: dict[str, Any] | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + color: ColorType | None = None, + log_scale: _LogScale | None = None, + legend: bool = True, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def kdeplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + color: ColorType | None = None, + fill: bool | None = None, + multiple: Literal["layer", "stack", "fill"] = "layer", + common_norm: bool = True, + common_grid: bool = False, + cumulative: bool = False, + bw_method: _BwMethodType = "scott", + bw_adjust: float = 1, + warn_singular: bool = True, + log_scale: _LogScale | None = None, + levels: int | Iterable[float] = 10, + thresh: float = 0.05, + gridsize: int = 200, + cut: float = 3, + clip: _OneOrPair[tuple[float | None, float | None]] | None = None, + legend: bool = True, + cbar: bool = False, + cbar_ax: Axes | None = None, + cbar_kws: dict[str, Any] | None = None, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def ecdfplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + stat: Literal["proportion", "percent", "count"] = "proportion", + complementary: bool = False, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + legend: bool = True, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def rugplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + height: float = 0.025, + expand_margins: bool = True, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + legend: bool = True, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def displot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + row: ColumnName | _Vector | None = None, + col: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + kind: Literal["hist", "kde", "ecdf"] = "hist", + rug: bool = False, + rug_kws: dict[str, Any] | None = None, + log_scale: _LogScale | None = None, + legend: bool = True, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + color: ColorType | None = None, + col_wrap: int | None = None, + row_order: Iterable[ColumnName] | None = None, + col_order: Iterable[ColumnName] | None = None, + height: float = 5, + aspect: float = 1, + facet_kws: dict[str, Any] | None = None, + **kwargs: Any, +) -> FacetGrid: ... +@deprecated("Function `distplot` is deprecated and will be removed in seaborn v0.14.0") +def distplot( + a: ArrayLike | None = None, + bins: ArrayLike | None = None, + hist: bool = True, + kde: bool = True, + rug: bool = False, + fit: _Fit | None = None, + hist_kws: dict[str, Any] | None = None, + kde_kws: dict[str, Any] | None = None, + rug_kws: dict[str, Any] | None = None, + fit_kws: dict[str, Any] | None = None, + color: ColorType | None = None, + vertical: bool = False, + norm_hist: bool = False, + axlabel: str | Literal[False] | None = None, + label: str | None = None, + ax: Axes | None = None, + x: ArrayLike | None = None, +) -> Axes: ... diff --git a/stubs/seaborn/seaborn/external/__init__.pyi b/stubs/seaborn/seaborn/external/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/external/appdirs.pyi b/stubs/seaborn/seaborn/external/appdirs.pyi new file mode 100644 index 000000000000..d9291bbb8d1e --- /dev/null +++ b/stubs/seaborn/seaborn/external/appdirs.pyi @@ -0,0 +1,9 @@ +from typing import Literal + +__version__: str +__version_info__: tuple[int, int, int] +system: str + +def user_cache_dir( + appname: str | None = None, appauthor: Literal[False] | str | None = None, version: str | None = None, opinion: bool = True +) -> str: ... diff --git a/stubs/seaborn/seaborn/external/docscrape.pyi b/stubs/seaborn/seaborn/external/docscrape.pyi new file mode 100644 index 000000000000..5d3e5e1b5807 --- /dev/null +++ b/stubs/seaborn/seaborn/external/docscrape.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence +from typing import Any, ClassVar, NamedTuple, SupportsIndex, TypeVar, overload + +_S = TypeVar("_S", bound=MutableSequence[str]) + +def strip_blank_lines(l: _S) -> _S: ... + +class Reader: + def __init__(self, data: str | list[str]) -> None: ... + + @overload + def __getitem__(self, n: slice) -> list[str]: ... + @overload + def __getitem__(self, n: SupportsIndex) -> str: ... + + def reset(self) -> None: ... + def read(self) -> str: ... + def seek_next_non_empty_line(self) -> None: ... + def eof(self) -> bool: ... + def read_to_condition(self, condition_func: Callable[[str], bool]) -> list[str]: ... + def read_to_next_empty_line(self) -> list[str]: ... + def read_to_next_unindented_line(self) -> list[str]: ... + def peek(self, n: int = 0) -> str: ... + def is_empty(self) -> bool: ... + +class ParseError(Exception): ... + +class Parameter(NamedTuple): + name: str + type: str + desc: list[str] + +class NumpyDocString(Mapping[str, Any]): + sections: ClassVar[dict[str, Any]] + def __init__(self, docstring: str, config: Unused = {}) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, val: Any) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + empty_description: str + +def indent(str: str | None, indent: int = 4) -> str: ... +def dedent_lines(lines: Iterable[str]) -> list[str]: ... +def header(text: str, style: str = "-") -> str: ... + +class FunctionDoc(NumpyDocString): + def __init__(self, func: object, role: str = "func", doc: str | None = None, config: Unused = {}) -> None: ... + def get_func(self) -> tuple[Incomplete, str]: ... + +class ClassDoc(NumpyDocString): + extra_public_methods: list[str] + show_inherited_members: bool + + @overload + def __init__( + self, cls: None, doc: str, modulename: str = "", func_doc: type[FunctionDoc] = ..., config: Mapping[str, Any] = {} + ) -> None: ... + @overload + def __init__( + self, + cls: type, + doc: str | None = None, + modulename: str = "", + func_doc: type[FunctionDoc] = ..., + config: Mapping[str, Any] = {}, + ) -> None: ... + + @property + def methods(self) -> list[str]: ... + @property + def properties(self) -> list[str]: ... diff --git a/stubs/seaborn/seaborn/external/husl.pyi b/stubs/seaborn/seaborn/external/husl.pyi new file mode 100644 index 000000000000..f76e09c84764 --- /dev/null +++ b/stubs/seaborn/seaborn/external/husl.pyi @@ -0,0 +1,42 @@ +from collections.abc import Iterable + +m: list[list[float]] +m_inv: list[list[float]] +refX: float +refY: float +refZ: float +refU: float +refV: float +lab_e: float +lab_k: float + +def husl_to_rgb(h: float, s: float, l: float) -> list[float]: ... +def husl_to_hex(h: float, s: float, l: float) -> str: ... +def rgb_to_husl(r: float, g: float, b: float) -> list[float]: ... +def hex_to_husl(hex: str) -> list[float]: ... +def huslp_to_rgb(h: float, s: float, l: float) -> list[float]: ... +def huslp_to_hex(h: float, s: float, l: float) -> str: ... +def rgb_to_huslp(r: float, g: float, b: float) -> list[float]: ... +def hex_to_huslp(hex: str) -> list[float]: ... +def lch_to_rgb(l: float, c: float, h: float) -> list[float]: ... +def rgb_to_lch(r: float, g: float, b: float) -> list[float]: ... +def max_chroma(L: float, H: float) -> float: ... +def max_chroma_pastel(L: float) -> float: ... +def dot_product(a: Iterable[float], b: Iterable[float]) -> float: ... +def f(t: float) -> float: ... +def f_inv(t: float) -> float: ... +def from_linear(c: float) -> float: ... +def to_linear(c: float) -> float: ... +def rgb_prepare(triple: Iterable[float]) -> list[int]: ... +def hex_to_rgb(hex: str) -> list[float]: ... +def rgb_to_hex(triple: Iterable[float]) -> str: ... +def xyz_to_rgb(triple: Iterable[float]) -> list[float]: ... +def rgb_to_xyz(triple: Iterable[float]) -> list[float]: ... +def xyz_to_luv(triple: Iterable[float]) -> list[float]: ... +def luv_to_xyz(triple: Iterable[float]) -> list[float]: ... +def luv_to_lch(triple: Iterable[float]) -> list[float]: ... +def lch_to_luv(triple: Iterable[float]) -> list[float]: ... +def husl_to_lch(triple: Iterable[float]) -> list[float]: ... +def lch_to_husl(triple: Iterable[float]) -> list[float]: ... +def huslp_to_lch(triple: Iterable[float]) -> list[float]: ... +def lch_to_huslp(triple: Iterable[float]) -> list[float]: ... diff --git a/stubs/seaborn/seaborn/external/kde.pyi b/stubs/seaborn/seaborn/external/kde.pyi new file mode 100644 index 000000000000..76769a3fd5f8 --- /dev/null +++ b/stubs/seaborn/seaborn/external/kde.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable +from typing import Any, Literal, Protocol, TypeAlias, type_check_only + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +__all__ = ["gaussian_kde"] + +# define a "Gaussian KDE" protocol so that we can also pass `scipy.stats.gaussian_kde` to +# functions that expect it without adding a dependency on scipy +@type_check_only +class _GaussianKDELike(Protocol): + dataset: NDArray[np.float64] + def __init__(self, dataset: ArrayLike, bw_method: Any | None = ..., weights: ArrayLike | None = ...) -> None: ... + def evaluate(self, points: ArrayLike) -> NDArray[Any]: ... + def __call__(self, points: ArrayLike) -> NDArray[Any]: ... + def scotts_factor(self) -> float: ... + def silverman_factor(self) -> float: ... + def covariance_factor(self) -> float: ... + def pdf(self, x: ArrayLike) -> NDArray[Any]: ... + def set_bandwidth(self, bw_method: Any | None = ...) -> None: ... + @property + def weights(self) -> NDArray[Any]: ... + @property + def neff(self) -> NDArray[Any]: ... + +_Scalar: TypeAlias = float | np.number[Any] +_BwMethodType: TypeAlias = Literal["scott", "silverman"] | Callable[[_GaussianKDELike], _Scalar] | _Scalar | None + +class gaussian_kde: + dataset: NDArray[np.float64] + def __init__(self, dataset: ArrayLike, bw_method: _BwMethodType = None, weights: ArrayLike | None = None) -> None: ... + def evaluate(self, points: ArrayLike) -> NDArray[np.float64]: ... + __call__ = evaluate + def scotts_factor(self) -> float: ... + def silverman_factor(self) -> float: ... + covariance_factor = scotts_factor + def set_bandwidth(self, bw_method: _BwMethodType = None) -> None: ... + def pdf(self, x: ArrayLike) -> NDArray[np.float64]: ... + @property + def weights(self) -> NDArray[np.float64]: ... + @property + def neff(self) -> NDArray[np.float64]: ... diff --git a/stubs/seaborn/seaborn/external/version.pyi b/stubs/seaborn/seaborn/external/version.pyi new file mode 100644 index 000000000000..fb9d9b3b11a3 --- /dev/null +++ b/stubs/seaborn/seaborn/external/version.pyi @@ -0,0 +1,45 @@ +__all__ = ["Version", "InvalidVersion", "VERSION_PATTERN"] + +class InvalidVersion(ValueError): ... + +class _BaseVersion: + def __hash__(self) -> int: ... + def __lt__(self, other: _BaseVersion) -> bool: ... + def __le__(self, other: _BaseVersion) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ge__(self, other: _BaseVersion) -> bool: ... + def __gt__(self, other: _BaseVersion) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +VERSION_PATTERN: str + +class Version(_BaseVersion): + def __init__(self, version: str) -> None: ... + @property + def epoch(self) -> int: ... + @property + def release(self) -> tuple[int, ...]: ... + @property + def pre(self) -> tuple[str, int] | None: ... + @property + def post(self) -> int | None: ... + @property + def dev(self) -> int | None: ... + @property + def local(self) -> str | None: ... + @property + def public(self) -> str: ... + @property + def base_version(self) -> str: ... + @property + def is_prerelease(self) -> bool: ... + @property + def is_postrelease(self) -> bool: ... + @property + def is_devrelease(self) -> bool: ... + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... diff --git a/stubs/seaborn/seaborn/matrix.pyi b/stubs/seaborn/seaborn/matrix.pyi new file mode 100644 index 000000000000..50214ffaaae3 --- /dev/null +++ b/stubs/seaborn/seaborn/matrix.pyi @@ -0,0 +1,220 @@ +from _typeshed import Incomplete +from collections.abc import Hashable, Iterable, Mapping, Sequence +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self + +import numpy as np +import pandas as pd +from matplotlib.axes import Axes +from matplotlib.colors import Colormap, ListedColormap, Normalize +from matplotlib.gridspec import GridSpec +from matplotlib.typing import ColorType +from numpy._typing import _ArrayLikeInt_co +from numpy.typing import ArrayLike, NDArray + +from .axisgrid import Grid + +# pandas._typing.ListLikeU is partially Unknown +_ListLikeU: TypeAlias = Sequence[Incomplete] | NDArray[Incomplete] | pd.Series[Incomplete] | pd.Index[Incomplete] +_ConvertibleToDataFrame: TypeAlias = ( + _ListLikeU + | pd.DataFrame + | dict[Incomplete, Incomplete] + | Iterable[_ListLikeU | tuple[Hashable, _ListLikeU] | dict[Incomplete, Incomplete]] + | None +) +_FlatOrNestedSequenceOfColors: TypeAlias = ( + Sequence[ColorType] + | Sequence[Iterable[ColorType]] + | NDArray[Incomplete] + | pd.Index[Incomplete] + | pd.Series[Incomplete] + | pd.DataFrame +) + +__all__ = ["heatmap", "clustermap"] + +def heatmap( + data: pd.DataFrame | ArrayLike, + *, + vmin: float | None = None, + vmax: float | None = None, + cmap: str | list[ColorType] | Colormap | None = None, + center: float | None = None, + robust: bool = False, + annot: bool | ArrayLike | None = None, + fmt: str = ".2g", + annot_kws: dict[str, Incomplete] | None = None, + linewidths: float = 0, + linecolor: ColorType = "white", + cbar: bool = True, + cbar_kws: dict[str, Incomplete] | None = None, + cbar_ax: Axes | None = None, + square: bool = False, + xticklabels: Literal["auto"] | bool | int | Sequence[str] = "auto", + yticklabels: Literal["auto"] | bool | int | Sequence[str] = "auto", + mask: NDArray[np.bool_] | pd.DataFrame | None = None, + ax: Axes | None = None, + # Kwargs below passed to matplotlib.axes.Axes.pcolormesh + alpha: float | None = None, + norm: str | Normalize | None = None, + shading: Literal["flat", "nearest", "gouraud", "auto"] | None = None, + antialiased: bool = False, + **kwargs, +) -> Axes: ... + +@type_check_only +class _Dendogram(TypedDict): + icoord: list[list[float]] + dcoord: list[list[float]] + ivl: list[str] + leaves: list[int] + color_list: list[str] + leaves_color_list: list[str] + +class _DendrogramPlotter: + axis: int + array: NDArray[np.floating] + data: pd.DataFrame + shape: tuple[int, int] + metric: str + method: str + label: bool + rotate: bool + linkage: NDArray[np.floating] + dendrogram: _Dendogram + xticks: list[float] | NDArray[np.floating] + yticks: list[float] | NDArray[np.floating] + xticklabels: list[str] + yticklabels: list[str] + ylabel: str + xlabel: str + dependent_coord: list[list[float]] + independent_coord: list[list[float]] + def __init__( + self, + data: pd.DataFrame, + linkage: NDArray[np.floating] | None, + metric: str, + method: str, + axis: int, + label: bool, + rotate: bool, + ) -> None: ... + @property + def calculated_linkage(self) -> NDArray[np.float64]: ... + def calculate_dendrogram(self) -> _Dendogram: ... + @property + def reordered_ind(self) -> list[int]: ... + def plot(self, ax: Axes, tree_kws: dict[str, Incomplete]) -> Self: ... + +def dendrogram( + data: pd.DataFrame, + *, + linkage: NDArray[np.floating] | None = None, + axis: int = 1, + label: bool = True, + metric: str = "euclidean", + method: str = "average", + rotate: bool = False, + tree_kws: dict[str, Incomplete] | None = None, + ax: Axes | None = None, +) -> _DendrogramPlotter: ... + +class ClusterGrid(Grid): + data: pd.DataFrame + data2d: pd.DataFrame + mask: pd.DataFrame + row_colors: list[list[tuple[float, float, float]]] | None + row_color_labels: list[str] | None + col_colors: list[list[tuple[float, float, float]]] | None + col_color_labels: list[str] | None + gs: GridSpec + ax_row_dendrogram: Axes + ax_col_dendrogram: Axes + ax_row_colors: Axes | None + ax_col_colors: Axes | None + ax_heatmap: Axes + ax_cbar: Axes | None + cax: Axes | None + cbar_pos: tuple[float, float, float, float] | None + dendrogram_row: _DendrogramPlotter | None + dendrogram_col: _DendrogramPlotter | None + def __init__( + self, + data: _ConvertibleToDataFrame, + pivot_kws: Mapping[str, Incomplete] | None = None, + z_score: int | None = None, + standard_scale: int | None = None, + figsize: tuple[float, float] | None = None, + row_colors: _FlatOrNestedSequenceOfColors | None = None, + col_colors: _FlatOrNestedSequenceOfColors | None = None, + mask: NDArray[np.bool_] | pd.DataFrame | None = None, + dendrogram_ratio: float | tuple[float, float] | None = None, + colors_ratio: float | tuple[float, float] | None = None, + cbar_pos: tuple[float, float, float, float] | None = None, + ) -> None: ... + def format_data( + self, + data: pd.DataFrame, + pivot_kws: Mapping[str, Incomplete] | None, + z_score: int | None = None, + standard_scale: int | None = None, + ) -> pd.DataFrame: ... + @staticmethod + def z_score(data2d: pd.DataFrame, axis: int = 1) -> pd.DataFrame: ... + @staticmethod + def standard_scale(data2d: pd.DataFrame, axis: int = 1) -> pd.DataFrame: ... + def dim_ratios(self, colors: ArrayLike | None, dendrogram_ratio: float, colors_ratio: float) -> list[float]: ... + @staticmethod + def color_list_to_matrix_and_cmap( + colors: _FlatOrNestedSequenceOfColors, ind: _ArrayLikeInt_co, axis: int = 0 + ) -> tuple[NDArray[np.int_], ListedColormap]: ... + def plot_dendrograms( + self, + row_cluster: bool, + col_cluster: bool, + metric: str, + method: str, + row_linkage: NDArray[np.floating] | None, + col_linkage: NDArray[np.floating] | None, + tree_kws: dict[str, Incomplete] | None, + ) -> None: ... + def plot_colors(self, xind: _ArrayLikeInt_co, yind: _ArrayLikeInt_co, **kws) -> None: ... + def plot_matrix(self, colorbar_kws: dict[str, Incomplete], xind: _ArrayLikeInt_co, yind: _ArrayLikeInt_co, **kws) -> None: ... + def plot( + self, + metric: str, + method: str, + colorbar_kws: dict[str, Incomplete] | None, + row_cluster: bool, + col_cluster: bool, + row_linkage: NDArray[np.floating] | None, + col_linkage: NDArray[np.floating] | None, + tree_kws: dict[str, Incomplete] | None, + **kws, + ) -> Self: ... + +def clustermap( + data: _ConvertibleToDataFrame, + *, + pivot_kws: dict[str, Incomplete] | None = None, + method: str = "average", + metric: str = "euclidean", + z_score: int | None = None, + standard_scale: int | None = None, + figsize: tuple[float, float] | None = (10, 10), + cbar_kws: dict[str, Incomplete] | None = None, + row_cluster: bool = True, + col_cluster: bool = True, + row_linkage: NDArray[np.floating] | None = None, + col_linkage: NDArray[np.floating] | None = None, + row_colors: _FlatOrNestedSequenceOfColors | None = None, + col_colors: _FlatOrNestedSequenceOfColors | None = None, + mask: NDArray[np.bool_] | pd.DataFrame | None = None, + dendrogram_ratio: float | tuple[float, float] = 0.2, + colors_ratio: float | tuple[float, float] = 0.03, + cbar_pos: tuple[float, float, float, float] | None = (0.02, 0.8, 0.05, 0.18), + tree_kws: dict[str, Incomplete] | None = None, + **kwargs, +) -> ClusterGrid: ... diff --git a/stubs/seaborn/seaborn/miscplot.pyi b/stubs/seaborn/seaborn/miscplot.pyi new file mode 100644 index 000000000000..82e8dbac5e2c --- /dev/null +++ b/stubs/seaborn/seaborn/miscplot.pyi @@ -0,0 +1,9 @@ +from _typeshed import Unused +from collections.abc import Sequence + +from matplotlib.typing import ColorType + +__all__ = ["palplot", "dogplot"] + +def palplot(pal: Sequence[ColorType], size: int = 1) -> None: ... +def dogplot(*_: Unused, **__: Unused) -> None: ... diff --git a/stubs/seaborn/seaborn/objects.pyi b/stubs/seaborn/seaborn/objects.pyi new file mode 100644 index 000000000000..4f757e0bba32 --- /dev/null +++ b/stubs/seaborn/seaborn/objects.pyi @@ -0,0 +1,21 @@ +from seaborn._core.moves import Dodge as Dodge, Jitter as Jitter, Move as Move, Norm as Norm, Shift as Shift, Stack as Stack +from seaborn._core.plot import Plot as Plot +from seaborn._core.scales import ( + Boolean as Boolean, + Continuous as Continuous, + Nominal as Nominal, + Scale as Scale, + Temporal as Temporal, +) +from seaborn._marks.area import Area as Area, Band as Band +from seaborn._marks.bar import Bar as Bar, Bars as Bars +from seaborn._marks.base import Mark as Mark +from seaborn._marks.dot import Dot as Dot, Dots as Dots +from seaborn._marks.line import Dash as Dash, Line as Line, Lines as Lines, Path as Path, Paths as Paths, Range as Range +from seaborn._marks.text import Text as Text +from seaborn._stats.aggregation import Agg as Agg, Est as Est +from seaborn._stats.base import Stat as Stat +from seaborn._stats.counting import Count as Count, Hist as Hist +from seaborn._stats.density import KDE as KDE +from seaborn._stats.order import Perc as Perc +from seaborn._stats.regression import PolyFit as PolyFit diff --git a/stubs/seaborn/seaborn/palettes.pyi b/stubs/seaborn/seaborn/palettes.pyi new file mode 100644 index 000000000000..c64d4d1234fe --- /dev/null +++ b/stubs/seaborn/seaborn/palettes.pyi @@ -0,0 +1,159 @@ +from collections.abc import Iterable, Sequence +from typing import Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from matplotlib.colors import Colormap, LinearSegmentedColormap, ListedColormap +from matplotlib.typing import ColorType + +__all__ = [ + "color_palette", + "hls_palette", + "husl_palette", + "mpl_palette", + "dark_palette", + "light_palette", + "diverging_palette", + "blend_palette", + "xkcd_palette", + "crayon_palette", + "cubehelix_palette", + "set_color_codes", +] + +_ColorT = TypeVar("_ColorT", bound=ColorType) + +SEABORN_PALETTES: dict[str, list[str]] +MPL_QUAL_PALS: dict[str, int] +QUAL_PALETTE_SIZES: dict[str, int] +QUAL_PALETTES: list[str] + +class _ColorPalette(list[_ColorT]): + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def as_hex(self) -> _ColorPalette[str]: ... + +_RGBColorPalette: TypeAlias = _ColorPalette[tuple[float, float, float]] +_SeabornPaletteName: TypeAlias = Literal[ + "deep", "deep6", "muted", "muted6", "pastel", "pastel6", "bright", "bright6", "dark", "dark6", "colorblind", "colorblind6" +] + +@overload +def color_palette( # type: ignore[overload-overlap] + palette: _SeabornPaletteName | None = None, n_colors: int | None = None, desat: float | None = None, *, as_cmap: Literal[True] +) -> list[str]: ... # this might be a bug in seaborn because we expect the return type to be a Colormap instance +@overload +def color_palette( + palette: str | Sequence[ColorType], n_colors: int | None = None, desat: float | None = None, *, as_cmap: Literal[True] +) -> Colormap: ... +@overload +def color_palette( + palette: str | Sequence[ColorType] | None = None, + n_colors: int | None = None, + desat: float | None = None, + as_cmap: Literal[False] = False, +) -> _RGBColorPalette: ... + +@overload +def hls_palette( + n_colors: int = 6, h: float = 0.01, l: float = 0.6, s: float = 0.65, *, as_cmap: Literal[True] +) -> ListedColormap: ... +@overload +def hls_palette( + n_colors: int = 6, h: float = 0.01, l: float = 0.6, s: float = 0.65, as_cmap: Literal[False] = False +) -> _RGBColorPalette: ... + +@overload +def husl_palette( + n_colors: int = 6, h: float = 0.01, s: float = 0.9, l: float = 0.65, *, as_cmap: Literal[True] +) -> ListedColormap: ... +@overload +def husl_palette( + n_colors: int = 6, h: float = 0.01, s: float = 0.9, l: float = 0.65, as_cmap: Literal[False] = False +) -> _RGBColorPalette: ... + +@overload +def mpl_palette(name: str, n_colors: int = 6, *, as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def mpl_palette(name: str, n_colors: int = 6, as_cmap: Literal[False] = False) -> _RGBColorPalette: ... + +@overload +def dark_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, *, as_cmap: Literal[True], input: str = "rgb" +) -> LinearSegmentedColormap: ... +@overload +def dark_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, as_cmap: Literal[False] = False, input: str = "rgb" +) -> _RGBColorPalette: ... + +@overload +def light_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, *, as_cmap: Literal[True], input: str = "rgb" +) -> LinearSegmentedColormap: ... +@overload +def light_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, as_cmap: Literal[False] = False, input: str = "rgb" +) -> _RGBColorPalette: ... + +@overload +def diverging_palette( + h_neg: float, + h_pos: float, + s: float = 75, + l: float = 50, + sep: int = 1, + n: int = 6, + center: Literal["light", "dark"] = "light", + *, + as_cmap: Literal[True], +) -> LinearSegmentedColormap: ... +@overload +def diverging_palette( + h_neg: float, + h_pos: float, + s: float = 75, + l: float = 50, + sep: int = 1, + n: int = 6, + center: Literal["light", "dark"] = "light", + as_cmap: Literal[False] = False, +) -> _RGBColorPalette: ... + +@overload +def blend_palette( + colors: Iterable[ColorType], n_colors: int = 6, *, as_cmap: Literal[True], input: str = "rgb" +) -> LinearSegmentedColormap: ... +@overload +def blend_palette( + colors: Iterable[ColorType], n_colors: int = 6, as_cmap: Literal[False] = False, input: str = "rgb" +) -> _RGBColorPalette: ... + +def xkcd_palette(colors: Iterable[str]) -> _RGBColorPalette: ... +def crayon_palette(colors: Iterable[str]) -> _RGBColorPalette: ... + +@overload +def cubehelix_palette( + n_colors: int = 6, + start: float = 0, + rot: float = 0.4, + gamma: float = 1.0, + hue: float = 0.8, + light: float = 0.85, + dark: float = 0.15, + reverse: bool = False, + *, + as_cmap: Literal[True], +) -> ListedColormap: ... +@overload +def cubehelix_palette( + n_colors: int = 6, + start: float = 0, + rot: float = 0.4, + gamma: float = 1.0, + hue: float = 0.8, + light: float = 0.85, + dark: float = 0.15, + reverse: bool = False, + as_cmap: Literal[False] = False, +) -> _RGBColorPalette: ... + +def set_color_codes(palette: str = "deep") -> None: ... diff --git a/stubs/seaborn/seaborn/rcmod.pyi b/stubs/seaborn/seaborn/rcmod.pyi new file mode 100644 index 000000000000..04c669d74f0e --- /dev/null +++ b/stubs/seaborn/seaborn/rcmod.pyi @@ -0,0 +1,74 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from typing import Any, Literal, TypeVar +from typing_extensions import deprecated + +from matplotlib.typing import ColorType + +__all__ = [ + "set_theme", + "set", + "reset_defaults", + "reset_orig", + "axes_style", + "set_style", + "plotting_context", + "set_context", + "set_palette", +] + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_F = TypeVar("_F", bound=Callable[..., Any]) + +def set_theme( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] = "notebook", + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] = "darkgrid", + palette: str | Sequence[ColorType] | None = "deep", + font: str = "sans-serif", + font_scale: float = 1, + color_codes: bool = True, + rc: dict[str, Any] | None = None, +) -> None: ... +@deprecated("Function `set` is deprecated in favor of `set_theme`") +def set( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] = "notebook", + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] = "darkgrid", + palette: str | Sequence[ColorType] | None = "deep", + font: str = "sans-serif", + font_scale: float = 1, + color_codes: bool = True, + rc: dict[str, Any] | None = None, +) -> None: ... +def reset_defaults() -> None: ... +def reset_orig() -> None: ... +def axes_style( + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] | None = None, + rc: dict[str, Any] | None = None, +) -> _AxesStyle[str, Any]: ... +def set_style( + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] | None = None, + rc: dict[str, Any] | None = None, +) -> None: ... +def plotting_context( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] | None = None, + font_scale: float = 1, + rc: dict[str, Any] | None = None, +) -> _PlottingContext[str, Any]: ... +def set_context( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] | None = None, + font_scale: float = 1, + rc: dict[str, Any] | None = None, +) -> None: ... + +class _RCAesthetics(dict[_KT, _VT]): + def __enter__(self) -> None: ... + def __exit__(self, exc_type: Unused, exc_value: Unused, exc_tb: Unused) -> None: ... + def __call__(self, func: _F) -> _F: ... + +class _AxesStyle(_RCAesthetics[_KT, _VT]): ... +class _PlottingContext(_RCAesthetics[_KT, _VT]): ... + +def set_palette( + palette: str | Sequence[ColorType] | None, n_colors: int | None = None, desat: float | None = None, color_codes: bool = False +) -> None: ... diff --git a/stubs/seaborn/seaborn/regression.pyi b/stubs/seaborn/seaborn/regression.pyi new file mode 100644 index 000000000000..615035fa1206 --- /dev/null +++ b/stubs/seaborn/seaborn/regression.pyi @@ -0,0 +1,163 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing import Any, Literal, TypeAlias, overload + +import pandas as pd +from matplotlib.axes import Axes +from matplotlib.typing import ColorType +from numpy.typing import NDArray + +from .axisgrid import FacetGrid +from .utils import _Palette, _Seed + +__all__ = ["lmplot", "regplot", "residplot"] + +_Vector: TypeAlias = list[Incomplete] | pd.Series[Incomplete] | pd.Index[Incomplete] | NDArray[Incomplete] + +def lmplot( + data: pd.DataFrame, + *, + x: str | None = None, + y: str | None = None, + hue: str | None = None, + col: str | None = None, + row: str | None = None, + palette: _Palette | None = None, + col_wrap: int | None = None, + height: float = 5, + aspect: float = 1, + markers: str = "o", + sharex: bool | Literal["col", "row"] | None = None, # deprecated + sharey: bool | Literal["col", "row"] | None = None, # deprecated + hue_order: Iterable[str] | None = None, + col_order: Iterable[str] | None = None, + row_order: Iterable[str] | None = None, + legend: bool = True, + legend_out: bool | None = None, # deprecated + x_estimator: Callable[[Incomplete], Incomplete] | None = None, + x_bins: int | _Vector | None = None, + x_ci: Literal["ci", "sd"] | int | None = "ci", + scatter: bool = True, + fit_reg: bool = True, + ci: int | None = 95, + n_boot: int = 1000, + units: str | None = None, + seed: _Seed | None = None, + order: int = 1, + logistic: bool = False, + lowess: bool = False, + robust: bool = False, + logx: bool = False, + x_partial: str | None = None, + y_partial: str | None = None, + truncate: bool = True, + x_jitter: float | None = None, + y_jitter: float | None = None, + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + facet_kws: dict[str, Any] | None = None, +) -> FacetGrid: ... + +@overload +def regplot( + data: None = None, + *, + x: _Vector | None = None, + y: _Vector | None = None, + x_estimator: Callable[[Incomplete], Incomplete] | None = None, + x_bins: int | _Vector | None = None, + x_ci: Literal["ci", "sd"] | int | None = "ci", + scatter: bool = True, + fit_reg: bool = True, + ci: int | None = 95, + n_boot: int = 1000, + units: _Vector | None = None, + seed: _Seed | None = None, + order: int = 1, + logistic: bool = False, + lowess: bool = False, + robust: bool = False, + logx: bool = False, + x_partial: _Vector | None = None, + y_partial: _Vector | None = None, + truncate: bool = True, + dropna: bool = True, + x_jitter: float | None = None, + y_jitter: float | None = None, + label: str | None = None, + color: ColorType | None = None, + marker: str = "o", + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... +@overload +def regplot( + data: pd.DataFrame, + *, + x: str | _Vector | None = None, + y: str | _Vector | None = None, + x_estimator: Callable[[Incomplete], Incomplete] | None = None, + x_bins: int | _Vector | None = None, + x_ci: Literal["ci", "sd"] | int | None = "ci", + scatter: bool = True, + fit_reg: bool = True, + ci: int | None = 95, + n_boot: int = 1000, + units: str | _Vector | None = None, + seed: _Seed | None = None, + order: int = 1, + logistic: bool = False, + lowess: bool = False, + robust: bool = False, + logx: bool = False, + x_partial: str | _Vector | None = None, + y_partial: str | _Vector | None = None, + truncate: bool = True, + dropna: bool = True, + x_jitter: float | None = None, + y_jitter: float | None = None, + label: str | None = None, + color: ColorType | None = None, + marker: str = "o", + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... + +@overload +def residplot( + data: None = None, + *, + x: _Vector | None = None, + y: _Vector | None = None, + x_partial: _Vector | None = None, + y_partial: _Vector | None = None, + lowess: bool = False, + order: int = 1, + robust: bool = False, + dropna: bool = True, + label: str | None = None, + color: ColorType | None = None, + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... +@overload +def residplot( + data: pd.DataFrame, + *, + x: str | _Vector | None = None, + y: str | _Vector | None = None, + x_partial: str | _Vector | None = None, + y_partial: str | _Vector | None = None, + lowess: bool = False, + order: int = 1, + robust: bool = False, + dropna: bool = True, + label: str | None = None, + color: ColorType | None = None, + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... diff --git a/stubs/seaborn/seaborn/relational.pyi b/stubs/seaborn/seaborn/relational.pyi new file mode 100644 index 000000000000..7b4ebc48bf2c --- /dev/null +++ b/stubs/seaborn/seaborn/relational.pyi @@ -0,0 +1,102 @@ +from collections.abc import Iterable, Mapping, Sequence +from typing import Any, Literal, TypeAlias + +from matplotlib.axes import Axes +from matplotlib.colors import Colormap +from matplotlib.typing import MarkerType + +from ._core.typing import ColumnName, DataSource, NormSpec +from .axisgrid import FacetGrid +from .utils import _DataSourceWideForm, _ErrorBar, _Estimator, _Legend, _Palette, _Seed, _Vector + +__all__ = ["relplot", "scatterplot", "lineplot"] + +_Sizes: TypeAlias = list[int] | list[float] | dict[str, int] | dict[str, float] | tuple[float, float] +_DashType: TypeAlias = tuple[None, None] | Sequence[float] # See matplotlib.lines.Line2D.set_dashes +# "dashes" and "markers" require dict but we use mapping to avoid long unions because dict is invariant in its value type +_Dashes: TypeAlias = bool | Sequence[_DashType] | Mapping[Any, _DashType] +_Markers: TypeAlias = bool | Sequence[MarkerType] | Mapping[Any, MarkerType] + +def lineplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + size: ColumnName | _Vector | None = None, + style: ColumnName | _Vector | None = None, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + sizes: _Sizes | None = None, + size_order: Iterable[ColumnName] | None = None, + size_norm: NormSpec = None, + dashes: _Dashes | None = True, + markers: _Markers | None = None, + style_order: Iterable[ColumnName] | None = None, + estimator: _Estimator | None = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + seed: _Seed | None = None, + orient: Literal["x", "y"] = "x", + sort: bool = True, + err_style: Literal["band", "bars"] = "band", + err_kws: dict[str, Any] | None = None, + legend: _Legend = "auto", + ci: str | int | None = "deprecated", # deprecated + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def scatterplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + size: ColumnName | _Vector | None = None, + style: ColumnName | _Vector | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + sizes: _Sizes | None = None, + size_order: Iterable[ColumnName] | None = None, + size_norm: NormSpec = None, + markers: _Markers | None = True, + style_order: Iterable[ColumnName] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def relplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + size: ColumnName | _Vector | None = None, + style: ColumnName | _Vector | None = None, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + row: ColumnName | _Vector | None = None, + col: ColumnName | _Vector | None = None, + col_wrap: int | None = None, + row_order: Iterable[ColumnName] | None = None, + col_order: Iterable[ColumnName] | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + sizes: _Sizes | None = None, + size_order: Iterable[ColumnName] | None = None, + size_norm: NormSpec = None, + markers: _Markers | None = None, + dashes: _Dashes | None = None, + style_order: Iterable[ColumnName] | None = None, + legend: _Legend = "auto", + kind: Literal["scatter", "line"] = "scatter", + height: float = 5, + aspect: float = 1, + facet_kws: dict[str, Any] | None = None, + **kwargs: Any, +) -> FacetGrid: ... diff --git a/stubs/seaborn/seaborn/utils.pyi b/stubs/seaborn/seaborn/utils.pyi new file mode 100644 index 000000000000..66859f2188a2 --- /dev/null +++ b/stubs/seaborn/seaborn/utils.pyi @@ -0,0 +1,115 @@ +import datetime as dt +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import deprecated + +import numpy as np +import pandas as pd +from matplotlib.axes import Axes +from matplotlib.figure import Figure +from matplotlib.legend import Legend +from matplotlib.text import Text +from matplotlib.ticker import Locator +from matplotlib.typing import ColorType +from numpy.typing import ArrayLike, NDArray +from pandas import DataFrame + +from .axisgrid import Grid + +__all__ = [ + "desaturate", + "saturate", + "set_hls_values", + "move_legend", + "despine", + "get_dataset_names", + "get_data_home", + "load_dataset", +] + +_VectorT = TypeVar("_VectorT", bound=SupportsGetItem[Any, Any]) + +# Type aliases used heavily throughout seaborn +_ErrorBar: TypeAlias = str | tuple[str, float] | Callable[[Iterable[float]], tuple[float, float]] # noqa: Y047 +_Estimator: TypeAlias = str | Callable[..., Incomplete] # noqa: Y047 +_Legend: TypeAlias = Literal["auto", "brief", "full"] | bool # noqa: Y047 +_LogScale: TypeAlias = bool | float | tuple[bool | float, bool | float] # noqa: Y047 +# `palette` requires dict but we use mapping to avoid a very long union because dict is invariant in its value type +_Palette: TypeAlias = str | Sequence[ColorType] | Mapping[Any, ColorType] # noqa: Y047 +_Seed: TypeAlias = int | np.random.Generator | np.random.RandomState # noqa: Y047 +_Scalar: TypeAlias = ( + # numeric + float + | complex + | np.number[Any] + # dates + | dt.date + | dt.datetime + | dt.timedelta + | pd.Timestamp + | pd.Timedelta + # categorical + | bool + | str + | bytes + | None +) +_Vector: TypeAlias = Iterable[_Scalar] +_DataSourceWideForm: TypeAlias = ( # noqa: Y047 + # Mapping of keys to "convertible to pd.Series" vectors + Mapping[Any, _Vector] + # Sequence of "convertible to pd.Series" vectors + | Sequence[_Vector] + # A "convertible to pd.DataFrame" table + | Mapping[Any, Mapping[Any, _Scalar]] + | NDArray[Any] + # Flat "convertible to pd.Series" vector of scalars + | Sequence[_Scalar] +) + +DATASET_SOURCE: str +DATASET_NAMES_URL: str + +def ci_to_errsize(cis: ArrayLike, heights: ArrayLike) -> NDArray[np.float64]: ... +def desaturate(color: ColorType, prop: float) -> tuple[float, float, float]: ... +def saturate(color: ColorType) -> tuple[float, float, float]: ... +def set_hls_values( + color: ColorType, h: float | None = None, l: float | None = None, s: float | None = None +) -> tuple[float, float, float]: ... +@deprecated("Function `axlabel` is deprecated and will be removed in a future version") +def axlabel(xlabel: str, ylabel: str, **kwargs: Any) -> None: ... +def remove_na(vector: _VectorT) -> _VectorT: ... +def get_color_cycle() -> list[str]: ... + +# `despine` should be kept roughly in line with `seaborn.axisgrid.FacetGrid.despine` +def despine( + fig: Figure | None = None, + ax: Axes | None = None, + top: bool = True, + right: bool = True, + left: bool = False, + bottom: bool = False, + offset: int | Mapping[str, int] | None = None, + trim: bool = False, +) -> None: ... +def move_legend(obj: Grid | Axes | Figure, loc: str | int, **kwargs: Any) -> None: ... +def ci( + a: float | ArrayLike, which: float | ArrayLike = 95, axis: SupportsIndex | Sequence[SupportsIndex] | None = None +) -> NDArray[np.float64]: ... +def get_dataset_names() -> list[str]: ... +def get_data_home(data_home: str | None = None) -> str: ... +def load_dataset(name: str, cache: bool = True, data_home: str | None = None, **kws: Any) -> DataFrame: ... +def axis_ticklabels_overlap(labels: Iterable[Text]) -> bool: ... +def axes_ticklabels_overlap(ax: Axes) -> tuple[bool, bool]: ... +def locator_to_legend_entries(locator: Locator, limits: Iterable[float], dtype) -> tuple[list[Incomplete], list[str]]: ... + +@overload +def relative_luminance(color: ColorType) -> float: ... # type: ignore[overload-overlap] +@overload +def relative_luminance(color: Sequence[ColorType]) -> NDArray[np.float64]: ... +@overload +def relative_luminance(color: ColorType | Sequence[ColorType] | ArrayLike) -> float | NDArray[np.float64]: ... + +def to_utf8(obj: object) -> str: ... +def adjust_legend_subtitles(legend: Legend) -> None: ... # not public API diff --git a/stubs/seaborn/seaborn/widgets.pyi b/stubs/seaborn/seaborn/widgets.pyi new file mode 100644 index 000000000000..64fd59ff27ab --- /dev/null +++ b/stubs/seaborn/seaborn/widgets.pyi @@ -0,0 +1,40 @@ +from typing import Literal, overload + +from matplotlib.colors import LinearSegmentedColormap + +__all__ = [ + "choose_colorbrewer_palette", + "choose_cubehelix_palette", + "choose_dark_palette", + "choose_light_palette", + "choose_diverging_palette", +] + +@overload +def choose_colorbrewer_palette( + data_type: Literal["sequential", "diverging", "qualitative"], as_cmap: Literal[True] +) -> LinearSegmentedColormap: ... +@overload +def choose_colorbrewer_palette( + data_type: Literal["sequential", "diverging", "qualitative"], as_cmap: Literal[False] = False +) -> list[tuple[float, float, float]]: ... + +@overload +def choose_dark_palette(input: str = "husl", *, as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_dark_palette(input: str = "husl", as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... + +@overload +def choose_light_palette(input: str = "husl", *, as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_light_palette(input: str = "husl", as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... + +@overload +def choose_diverging_palette(as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_diverging_palette(as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... + +@overload +def choose_cubehelix_palette(as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_cubehelix_palette(as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... diff --git a/stubs/selenium/METADATA.toml b/stubs/selenium/METADATA.toml deleted file mode 100644 index ed87da948251..000000000000 --- a/stubs/selenium/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "3.141.*" diff --git a/stubs/selenium/selenium/common/__init__.pyi b/stubs/selenium/selenium/common/__init__.pyi deleted file mode 100644 index baafbaf5476e..000000000000 --- a/stubs/selenium/selenium/common/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from . import exceptions as exceptions diff --git a/stubs/selenium/selenium/common/exceptions.pyi b/stubs/selenium/selenium/common/exceptions.pyi deleted file mode 100644 index f3f9f6dc9514..000000000000 --- a/stubs/selenium/selenium/common/exceptions.pyi +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Any - -class WebDriverException(Exception): - msg: Any - screen: Any - stacktrace: Any - def __init__(self, msg: Any | None = ..., screen: Any | None = ..., stacktrace: Any | None = ...) -> None: ... - -class ErrorInResponseException(WebDriverException): - response: Any - def __init__(self, response, msg) -> None: ... - -class InvalidSwitchToTargetException(WebDriverException): ... -class NoSuchFrameException(InvalidSwitchToTargetException): ... -class NoSuchWindowException(InvalidSwitchToTargetException): ... -class NoSuchElementException(WebDriverException): ... -class NoSuchAttributeException(WebDriverException): ... -class StaleElementReferenceException(WebDriverException): ... -class InvalidElementStateException(WebDriverException): ... - -class UnexpectedAlertPresentException(WebDriverException): - alert_text: Any - def __init__( - self, msg: Any | None = ..., screen: Any | None = ..., stacktrace: Any | None = ..., alert_text: Any | None = ... - ) -> None: ... - -class NoAlertPresentException(WebDriverException): ... -class ElementNotVisibleException(InvalidElementStateException): ... -class ElementNotInteractableException(InvalidElementStateException): ... -class ElementNotSelectableException(InvalidElementStateException): ... -class InvalidCookieDomainException(WebDriverException): ... -class UnableToSetCookieException(WebDriverException): ... -class RemoteDriverServerException(WebDriverException): ... -class TimeoutException(WebDriverException): ... -class MoveTargetOutOfBoundsException(WebDriverException): ... -class UnexpectedTagNameException(WebDriverException): ... -class InvalidSelectorException(NoSuchElementException): ... -class ImeNotAvailableException(WebDriverException): ... -class ImeActivationFailedException(WebDriverException): ... -class InvalidArgumentException(WebDriverException): ... -class JavascriptException(WebDriverException): ... -class NoSuchCookieException(WebDriverException): ... -class ScreenshotException(WebDriverException): ... -class ElementClickInterceptedException(WebDriverException): ... -class InsecureCertificateException(WebDriverException): ... -class InvalidCoordinatesException(WebDriverException): ... -class InvalidSessionIdException(WebDriverException): ... -class SessionNotCreatedException(WebDriverException): ... -class UnknownMethodException(WebDriverException): ... diff --git a/stubs/selenium/selenium/webdriver/__init__.pyi b/stubs/selenium/selenium/webdriver/__init__.pyi deleted file mode 100644 index 8f2711601c1e..000000000000 --- a/stubs/selenium/selenium/webdriver/__init__.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from .android.webdriver import WebDriver as Android -from .blackberry.webdriver import WebDriver as BlackBerry -from .chrome.options import Options as ChromeOptions -from .chrome.webdriver import WebDriver as Chrome -from .common.action_chains import ActionChains as ActionChains -from .common.desired_capabilities import DesiredCapabilities as DesiredCapabilities -from .common.proxy import Proxy as Proxy -from .common.touch_actions import TouchActions as TouchActions -from .edge.webdriver import WebDriver as Edge -from .firefox.firefox_profile import FirefoxProfile as FirefoxProfile -from .firefox.options import Options as FirefoxOptions -from .firefox.webdriver import WebDriver as Firefox -from .ie.options import Options as IeOptions -from .ie.webdriver import WebDriver as Ie -from .opera.webdriver import WebDriver as Opera -from .phantomjs.webdriver import WebDriver as PhantomJS -from .remote.webdriver import WebDriver as Remote -from .safari.webdriver import WebDriver as Safari -from .webkitgtk.options import Options as WebKitGTKOptions -from .webkitgtk.webdriver import WebDriver as WebKitGTK - -# We need an explicit __all__ because some of the above won't otherwise be exported. -__all__ = [ - "Firefox", - "FirefoxProfile", - "FirefoxOptions", - "Chrome", - "ChromeOptions", - "Ie", - "IeOptions", - "Edge", - "Opera", - "Safari", - "BlackBerry", - "PhantomJS", - "Android", - "WebKitGTK", - "WebKitGTKOptions", - "Remote", - "DesiredCapabilities", - "ActionChains", - "TouchActions", - "Proxy", -] diff --git a/stubs/selenium/selenium/webdriver/android/webdriver.pyi b/stubs/selenium/selenium/webdriver/android/webdriver.pyi deleted file mode 100644 index c310c4acd75f..000000000000 --- a/stubs/selenium/selenium/webdriver/android/webdriver.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from selenium.webdriver.common.desired_capabilities import DesiredCapabilities as DesiredCapabilities -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -class WebDriver(RemoteWebDriver): - def __init__(self, host: str = ..., port: int = ..., desired_capabilities=...) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/blackberry/webdriver.pyi b/stubs/selenium/selenium/webdriver/blackberry/webdriver.pyi deleted file mode 100644 index 8caafb6c450c..000000000000 --- a/stubs/selenium/selenium/webdriver/blackberry/webdriver.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -LOAD_TIMEOUT: int - -class WebDriver(RemoteWebDriver): - def __init__( - self, device_password, bb_tools_dir: Any | None = ..., hostip: str = ..., port: int = ..., desired_capabilities=... - ): ... - def quit(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/chrome/options.pyi b/stubs/selenium/selenium/webdriver/chrome/options.pyi deleted file mode 100644 index 83baf8ac019c..000000000000 --- a/stubs/selenium/selenium/webdriver/chrome/options.pyi +++ /dev/null @@ -1,30 +0,0 @@ -class Options: - KEY: str - def __init__(self) -> None: ... - @property - def binary_location(self): ... - @binary_location.setter - def binary_location(self, value) -> None: ... - @property - def capabilities(self): ... - def set_capability(self, name, value) -> None: ... - @property - def debugger_address(self): ... - @debugger_address.setter - def debugger_address(self, value) -> None: ... - @property - def arguments(self): ... - def add_argument(self, argument) -> None: ... - @property - def extensions(self): ... - def add_extension(self, extension) -> None: ... - def add_encoded_extension(self, extension) -> None: ... - @property - def experimental_options(self): ... - def add_experimental_option(self, name, value) -> None: ... - @property - def headless(self): ... - @headless.setter - def headless(self, value) -> None: ... - def set_headless(self, headless: bool = ...) -> None: ... - def to_capabilities(self): ... diff --git a/stubs/selenium/selenium/webdriver/chrome/remote_connection.pyi b/stubs/selenium/selenium/webdriver/chrome/remote_connection.pyi deleted file mode 100644 index 0e5870aef884..000000000000 --- a/stubs/selenium/selenium/webdriver/chrome/remote_connection.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from selenium.webdriver.remote.remote_connection import RemoteConnection as RemoteConnection - -class ChromeRemoteConnection(RemoteConnection): - def __init__(self, remote_server_addr, keep_alive: bool = ...) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/chrome/service.pyi b/stubs/selenium/selenium/webdriver/chrome/service.pyi deleted file mode 100644 index d581b790174e..000000000000 --- a/stubs/selenium/selenium/webdriver/chrome/service.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - service_args: Any - def __init__( - self, executable_path, port: int = ..., service_args: Any | None = ..., log_path: Any | None = ..., env: Any | None = ... - ) -> None: ... - def command_line_args(self): ... diff --git a/stubs/selenium/selenium/webdriver/chrome/webdriver.pyi b/stubs/selenium/selenium/webdriver/chrome/webdriver.pyi deleted file mode 100644 index 754ebf51583f..000000000000 --- a/stubs/selenium/selenium/webdriver/chrome/webdriver.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -from .remote_connection import ChromeRemoteConnection as ChromeRemoteConnection - -class WebDriver(RemoteWebDriver): - service: Any - def __init__( - self, - executable_path: str = ..., - port: int = ..., - options: Any | None = ..., - service_args: Any | None = ..., - desired_capabilities: Any | None = ..., - service_log_path: Any | None = ..., - chrome_options: Any | None = ..., - keep_alive: bool = ..., - ) -> None: ... - def launch_app(self, id): ... - def get_network_conditions(self): ... - def set_network_conditions(self, **network_conditions) -> None: ... - def execute_cdp_cmd(self, cmd, cmd_args): ... - def quit(self) -> None: ... - def create_options(self): ... diff --git a/stubs/selenium/selenium/webdriver/common/action_chains.pyi b/stubs/selenium/selenium/webdriver/common/action_chains.pyi deleted file mode 100644 index e1ab3cda0db9..000000000000 --- a/stubs/selenium/selenium/webdriver/common/action_chains.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.command import Command as Command - -from .actions.action_builder import ActionBuilder as ActionBuilder -from .utils import keys_to_typing as keys_to_typing - -class ActionChains: - w3c_actions: Any - def __init__(self, driver) -> None: ... - def perform(self) -> None: ... - def reset_actions(self) -> None: ... - def click(self, on_element: Any | None = ...): ... - def click_and_hold(self, on_element: Any | None = ...): ... - def context_click(self, on_element: Any | None = ...): ... - def double_click(self, on_element: Any | None = ...): ... - def drag_and_drop(self, source, target): ... - def drag_and_drop_by_offset(self, source, xoffset, yoffset): ... - def key_down(self, value, element: Any | None = ...): ... - def key_up(self, value, element: Any | None = ...): ... - def move_by_offset(self, xoffset, yoffset): ... - def move_to_element(self, to_element): ... - def move_to_element_with_offset(self, to_element, xoffset, yoffset): ... - def pause(self, seconds): ... - def release(self, on_element: Any | None = ...): ... - def send_keys(self, *keys_to_send): ... - def send_keys_to_element(self, element, *keys_to_send): ... - def __enter__(self): ... - def __exit__(self, _type, _value, _traceback) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/action_builder.pyi b/stubs/selenium/selenium/webdriver/common/actions/action_builder.pyi deleted file mode 100644 index 40be962861d0..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/action_builder.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.command import Command as Command - -from . import interaction as interaction -from .key_actions import KeyActions as KeyActions -from .key_input import KeyInput as KeyInput -from .pointer_actions import PointerActions as PointerActions -from .pointer_input import PointerInput as PointerInput - -class ActionBuilder: - devices: Any - driver: Any - def __init__(self, driver, mouse: Any | None = ..., keyboard: Any | None = ...) -> None: ... - def get_device_with(self, name): ... - @property - def pointer_inputs(self): ... - @property - def key_inputs(self): ... - @property - def key_action(self): ... - @property - def pointer_action(self): ... - def add_key_input(self, name): ... - def add_pointer_input(self, kind, name): ... - def perform(self) -> None: ... - def clear_actions(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/input_device.pyi b/stubs/selenium/selenium/webdriver/common/actions/input_device.pyi deleted file mode 100644 index 461e84e98df7..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/input_device.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Any - -class InputDevice: - name: Any - actions: Any - def __init__(self, name: Any | None = ...) -> None: ... - def add_action(self, action) -> None: ... - def clear_actions(self) -> None: ... - def create_pause(self, duraton: int = ...) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/interaction.pyi b/stubs/selenium/selenium/webdriver/common/actions/interaction.pyi deleted file mode 100644 index 61cb9eec9b00..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/interaction.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -KEY: str -POINTER: str -NONE: str -SOURCE_TYPES: Any -POINTER_MOUSE: str -POINTER_TOUCH: str -POINTER_PEN: str -POINTER_KINDS: Any - -class Interaction: - PAUSE: str - source: Any - def __init__(self, source) -> None: ... - -class Pause(Interaction): - source: Any - duration: Any - def __init__(self, source, duration: int = ...) -> None: ... - def encode(self): ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/key_actions.pyi b/stubs/selenium/selenium/webdriver/common/actions/key_actions.pyi deleted file mode 100644 index b5412a65bde7..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/key_actions.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from ..utils import keys_to_typing as keys_to_typing -from .interaction import KEY as KEY, Interaction as Interaction -from .key_input import KeyInput as KeyInput - -class KeyActions(Interaction): - source: Any - def __init__(self, source: Any | None = ...) -> None: ... - def key_down(self, letter): ... - def key_up(self, letter): ... - def pause(self, duration: int = ...): ... - def send_keys(self, text): ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/key_input.pyi b/stubs/selenium/selenium/webdriver/common/actions/key_input.pyi deleted file mode 100644 index 744422672e81..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/key_input.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Any - -from . import interaction as interaction -from .input_device import InputDevice as InputDevice -from .interaction import Interaction as Interaction, Pause as Pause - -class KeyInput(InputDevice): - name: Any - type: Any - def __init__(self, name) -> None: ... - def encode(self): ... - def create_key_down(self, key) -> None: ... - def create_key_up(self, key) -> None: ... - def create_pause(self, pause_duration: int = ...) -> None: ... - -class TypingInteraction(Interaction): - type: Any - key: Any - def __init__(self, source, type_, key) -> None: ... - def encode(self): ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/mouse_button.pyi b/stubs/selenium/selenium/webdriver/common/actions/mouse_button.pyi deleted file mode 100644 index 603c6f6bc31d..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/mouse_button.pyi +++ /dev/null @@ -1,4 +0,0 @@ -class MouseButton: - LEFT: int - MIDDLE: int - RIGHT: int diff --git a/stubs/selenium/selenium/webdriver/common/actions/pointer_actions.pyi b/stubs/selenium/selenium/webdriver/common/actions/pointer_actions.pyi deleted file mode 100644 index 4cf6e0ce1508..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/pointer_actions.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webelement import WebElement as WebElement - -from . import interaction as interaction -from .interaction import Interaction as Interaction -from .mouse_button import MouseButton as MouseButton -from .pointer_input import PointerInput as PointerInput - -class PointerActions(Interaction): - source: Any - def __init__(self, source: Any | None = ...) -> None: ... - def pointer_down(self, button=...) -> None: ... - def pointer_up(self, button=...) -> None: ... - def move_to(self, element, x: Any | None = ..., y: Any | None = ...): ... - def move_by(self, x, y): ... - def move_to_location(self, x, y): ... - def click(self, element: Any | None = ...): ... - def context_click(self, element: Any | None = ...): ... - def click_and_hold(self, element: Any | None = ...): ... - def release(self): ... - def double_click(self, element: Any | None = ...) -> None: ... - def pause(self, duration: int = ...): ... diff --git a/stubs/selenium/selenium/webdriver/common/actions/pointer_input.pyi b/stubs/selenium/selenium/webdriver/common/actions/pointer_input.pyi deleted file mode 100644 index 1647f90f1afd..000000000000 --- a/stubs/selenium/selenium/webdriver/common/actions/pointer_input.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -from .input_device import InputDevice as InputDevice -from .interaction import POINTER as POINTER, POINTER_KINDS as POINTER_KINDS - -class PointerInput(InputDevice): - DEFAULT_MOVE_DURATION: int - type: Any - kind: Any - name: Any - def __init__(self, kind, name) -> None: ... - def create_pointer_move(self, duration=..., x: Any | None = ..., y: Any | None = ..., origin: Any | None = ...) -> None: ... - def create_pointer_down(self, button) -> None: ... - def create_pointer_up(self, button) -> None: ... - def create_pointer_cancel(self) -> None: ... - def create_pause(self, pause_duration) -> None: ... # type: ignore[override] - def encode(self): ... diff --git a/stubs/selenium/selenium/webdriver/common/alert.pyi b/stubs/selenium/selenium/webdriver/common/alert.pyi deleted file mode 100644 index 942702218263..000000000000 --- a/stubs/selenium/selenium/webdriver/common/alert.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -class Alert: - driver: Any - def __init__(self, driver) -> None: ... - @property - def text(self): ... - def dismiss(self) -> None: ... - def accept(self) -> None: ... - def send_keys(self, keysToSend) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/by.pyi b/stubs/selenium/selenium/webdriver/common/by.pyi deleted file mode 100644 index fbdf77bd6a97..000000000000 --- a/stubs/selenium/selenium/webdriver/common/by.pyi +++ /dev/null @@ -1,9 +0,0 @@ -class By: - ID: str - XPATH: str - LINK_TEXT: str - PARTIAL_LINK_TEXT: str - NAME: str - TAG_NAME: str - CLASS_NAME: str - CSS_SELECTOR: str diff --git a/stubs/selenium/selenium/webdriver/common/desired_capabilities.pyi b/stubs/selenium/selenium/webdriver/common/desired_capabilities.pyi deleted file mode 100644 index c9b16cae2793..000000000000 --- a/stubs/selenium/selenium/webdriver/common/desired_capabilities.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -class DesiredCapabilities: - FIREFOX: Any - INTERNETEXPLORER: Any - EDGE: Any - CHROME: Any - OPERA: Any - SAFARI: Any - HTMLUNIT: Any - HTMLUNITWITHJS: Any - IPHONE: Any - IPAD: Any - ANDROID: Any - PHANTOMJS: Any - WEBKITGTK: Any diff --git a/stubs/selenium/selenium/webdriver/common/html5/application_cache.pyi b/stubs/selenium/selenium/webdriver/common/html5/application_cache.pyi deleted file mode 100644 index 248010ea25d1..000000000000 --- a/stubs/selenium/selenium/webdriver/common/html5/application_cache.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -class ApplicationCache: - UNCACHED: int - IDLE: int - CHECKING: int - DOWNLOADING: int - UPDATE_READY: int - OBSOLETE: int - driver: Any - def __init__(self, driver) -> None: ... - @property - def status(self): ... diff --git a/stubs/selenium/selenium/webdriver/common/keys.pyi b/stubs/selenium/selenium/webdriver/common/keys.pyi deleted file mode 100644 index b93ef383be9e..000000000000 --- a/stubs/selenium/selenium/webdriver/common/keys.pyi +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any - -class Keys: - NULL: str - CANCEL: str - HELP: str - BACKSPACE: str - BACK_SPACE: Any - TAB: str - CLEAR: str - RETURN: str - ENTER: str - SHIFT: str - LEFT_SHIFT: Any - CONTROL: str - LEFT_CONTROL: Any - ALT: str - LEFT_ALT: Any - PAUSE: str - ESCAPE: str - SPACE: str - PAGE_UP: str - PAGE_DOWN: str - END: str - HOME: str - LEFT: str - ARROW_LEFT: Any - UP: str - ARROW_UP: Any - RIGHT: str - ARROW_RIGHT: Any - DOWN: str - ARROW_DOWN: Any - INSERT: str - DELETE: str - SEMICOLON: str - EQUALS: str - NUMPAD0: str - NUMPAD1: str - NUMPAD2: str - NUMPAD3: str - NUMPAD4: str - NUMPAD5: str - NUMPAD6: str - NUMPAD7: str - NUMPAD8: str - NUMPAD9: str - MULTIPLY: str - ADD: str - SEPARATOR: str - SUBTRACT: str - DECIMAL: str - DIVIDE: str - F1: str - F2: str - F3: str - F4: str - F5: str - F6: str - F7: str - F8: str - F9: str - F10: str - F11: str - F12: str - META: str - COMMAND: str diff --git a/stubs/selenium/selenium/webdriver/common/proxy.pyi b/stubs/selenium/selenium/webdriver/common/proxy.pyi deleted file mode 100644 index a058d9dee6b9..000000000000 --- a/stubs/selenium/selenium/webdriver/common/proxy.pyi +++ /dev/null @@ -1,70 +0,0 @@ -from typing import Any - -class ProxyTypeFactory: - @staticmethod - def make(ff_value, string): ... - -class ProxyType: - DIRECT: Any - MANUAL: Any - PAC: Any - RESERVED_1: Any - AUTODETECT: Any - SYSTEM: Any - UNSPECIFIED: Any - @classmethod - def load(cls, value): ... - -class Proxy: - proxyType: Any - autodetect: bool - ftpProxy: str - httpProxy: str - noProxy: str - proxyAutoconfigUrl: str - sslProxy: str - socksProxy: str - socksUsername: str - socksPassword: str - def __init__(self, raw: Any | None = ...) -> None: ... - @property - def proxy_type(self): ... - @proxy_type.setter - def proxy_type(self, value) -> None: ... - @property - def auto_detect(self): ... - @auto_detect.setter - def auto_detect(self, value) -> None: ... - @property - def ftp_proxy(self): ... - @ftp_proxy.setter - def ftp_proxy(self, value) -> None: ... - @property - def http_proxy(self): ... - @http_proxy.setter - def http_proxy(self, value) -> None: ... - @property - def no_proxy(self): ... - @no_proxy.setter - def no_proxy(self, value) -> None: ... - @property - def proxy_autoconfig_url(self): ... - @proxy_autoconfig_url.setter - def proxy_autoconfig_url(self, value) -> None: ... - @property - def ssl_proxy(self): ... - @ssl_proxy.setter - def ssl_proxy(self, value) -> None: ... - @property - def socks_proxy(self): ... - @socks_proxy.setter - def socks_proxy(self, value) -> None: ... - @property - def socks_username(self): ... - @socks_username.setter - def socks_username(self, value) -> None: ... - @property - def socks_password(self): ... - @socks_password.setter - def socks_password(self, value) -> None: ... - def add_to_capabilities(self, capabilities) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/service.pyi b/stubs/selenium/selenium/webdriver/common/service.pyi deleted file mode 100644 index f8b28110852c..000000000000 --- a/stubs/selenium/selenium/webdriver/common/service.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -class Service: - path: Any - port: Any - start_error_message: Any - log_file: Any - env: Any - def __init__( - self, executable, port: int = ..., log_file=..., env: Any | None = ..., start_error_message: str = ... - ) -> None: ... - @property - def service_url(self): ... - def command_line_args(self) -> None: ... - process: Any - def start(self) -> None: ... - def assert_process_still_running(self) -> None: ... - def is_connectable(self): ... - def send_remote_shutdown_command(self) -> None: ... - def stop(self) -> None: ... - def __del__(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/touch_actions.pyi b/stubs/selenium/selenium/webdriver/common/touch_actions.pyi deleted file mode 100644 index 04a5d1717681..000000000000 --- a/stubs/selenium/selenium/webdriver/common/touch_actions.pyi +++ /dev/null @@ -1,15 +0,0 @@ -class TouchActions: - def __init__(self, driver) -> None: ... - def perform(self) -> None: ... - def tap(self, on_element): ... - def double_tap(self, on_element): ... - def tap_and_hold(self, xcoord, ycoord): ... - def move(self, xcoord, ycoord): ... - def release(self, xcoord, ycoord): ... - def scroll(self, xoffset, yoffset): ... - def scroll_from_element(self, on_element, xoffset, yoffset): ... - def long_press(self, on_element): ... - def flick(self, xspeed, yspeed): ... - def flick_element(self, on_element, xoffset, yoffset, speed): ... - def __enter__(self): ... - def __exit__(self, _type, _value, _traceback) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/common/utils.pyi b/stubs/selenium/selenium/webdriver/common/utils.pyi deleted file mode 100644 index ffd77721b0e6..000000000000 --- a/stubs/selenium/selenium/webdriver/common/utils.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from selenium.webdriver.common.keys import Keys as Keys - -basestring = str - -def free_port(): ... -def find_connectable_ip(host, port: Any | None = ...): ... -def join_host_port(host, port): ... -def is_connectable(port, host: str = ...): ... -def is_url_connectable(port): ... -def keys_to_typing(value): ... diff --git a/stubs/selenium/selenium/webdriver/edge/options.pyi b/stubs/selenium/selenium/webdriver/edge/options.pyi deleted file mode 100644 index 990c0923eda9..000000000000 --- a/stubs/selenium/selenium/webdriver/edge/options.pyi +++ /dev/null @@ -1,10 +0,0 @@ -class Options: - def __init__(self) -> None: ... - @property - def page_load_strategy(self): ... - @page_load_strategy.setter - def page_load_strategy(self, value) -> None: ... - @property - def capabilities(self): ... - def set_capability(self, name, value) -> None: ... - def to_capabilities(self): ... diff --git a/stubs/selenium/selenium/webdriver/edge/service.pyi b/stubs/selenium/selenium/webdriver/edge/service.pyi deleted file mode 100644 index 87abed56f260..000000000000 --- a/stubs/selenium/selenium/webdriver/edge/service.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - service_args: Any - def __init__(self, executable_path, port: int = ..., verbose: bool = ..., log_path: Any | None = ...) -> None: ... - def command_line_args(self): ... diff --git a/stubs/selenium/selenium/webdriver/edge/webdriver.pyi b/stubs/selenium/selenium/webdriver/edge/webdriver.pyi deleted file mode 100644 index 1a76a70c2fdf..000000000000 --- a/stubs/selenium/selenium/webdriver/edge/webdriver.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -class WebDriver(RemoteWebDriver): - port: Any - edge_service: Any - def __init__( - self, - executable_path: str = ..., - capabilities: Any | None = ..., - port: int = ..., - verbose: bool = ..., - service_log_path: Any | None = ..., - log_path: Any | None = ..., - keep_alive: bool = ..., - ) -> None: ... - def quit(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/firefox/extension_connection.pyi b/stubs/selenium/selenium/webdriver/firefox/extension_connection.pyi deleted file mode 100644 index d47e2b80d9d2..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/extension_connection.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.remote_connection import RemoteConnection as RemoteConnection - -LOGGER: Any -PORT: int -HOST: Any - -class ExtensionConnection(RemoteConnection): - profile: Any - binary: Any - def __init__(self, host, firefox_profile, firefox_binary: Any | None = ..., timeout: int = ...) -> None: ... - def quit(self, sessionId: Any | None = ...) -> None: ... - def connect(self): ... - @classmethod - def connect_and_quit(cls) -> None: ... - @classmethod - def is_connectable(cls) -> None: ... - -class ExtensionConnectionError(Exception): ... diff --git a/stubs/selenium/selenium/webdriver/firefox/firefox_binary.pyi b/stubs/selenium/selenium/webdriver/firefox/firefox_binary.pyi deleted file mode 100644 index 4b146ba458e9..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/firefox_binary.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class FirefoxBinary: - NO_FOCUS_LIBRARY_NAME: str - command_line: Any - def __init__(self, firefox_path: Any | None = ..., log_file: Any | None = ...) -> None: ... - def add_command_line_options(self, *args) -> None: ... - profile: Any - def launch_browser(self, profile, timeout: int = ...) -> None: ... - def kill(self) -> None: ... - def which(self, fname): ... diff --git a/stubs/selenium/selenium/webdriver/firefox/firefox_profile.pyi b/stubs/selenium/selenium/webdriver/firefox/firefox_profile.pyi deleted file mode 100644 index 885b25454f9b..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/firefox_profile.pyi +++ /dev/null @@ -1,41 +0,0 @@ -from typing import Any - -WEBDRIVER_EXT: str -WEBDRIVER_PREFERENCES: str -EXTENSION_NAME: str - -class AddonFormatError(Exception): ... - -class FirefoxProfile: - ANONYMOUS_PROFILE_NAME: str - DEFAULT_PREFERENCES: Any - default_preferences: Any - profile_dir: Any - tempfolder: Any - extensionsDir: Any - userPrefs: Any - def __init__(self, profile_directory: Any | None = ...) -> None: ... - def set_preference(self, key, value) -> None: ... - def add_extension(self, extension=...) -> None: ... - def update_preferences(self) -> None: ... - @property - def path(self): ... - @property - def port(self): ... - @port.setter - def port(self, port) -> None: ... - @property - def accept_untrusted_certs(self): ... - @accept_untrusted_certs.setter - def accept_untrusted_certs(self, value) -> None: ... - @property - def assume_untrusted_cert_issuer(self): ... - @assume_untrusted_cert_issuer.setter - def assume_untrusted_cert_issuer(self, value) -> None: ... - @property - def native_events_enabled(self): ... - @native_events_enabled.setter - def native_events_enabled(self, value) -> None: ... - @property - def encoded(self): ... - def set_proxy(self, proxy) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/firefox/options.pyi b/stubs/selenium/selenium/webdriver/firefox/options.pyi deleted file mode 100644 index d5f52f8f5dc7..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/options.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Any - -class Log: - level: Any - def __init__(self) -> None: ... - def to_capabilities(self): ... - -class Options: - KEY: str - log: Any - def __init__(self) -> None: ... - @property - def binary(self): ... - @binary.setter - def binary(self, new_binary) -> None: ... - @property - def binary_location(self): ... - @binary_location.setter - def binary_location(self, value) -> None: ... - @property - def accept_insecure_certs(self): ... - @accept_insecure_certs.setter - def accept_insecure_certs(self, value) -> None: ... - @property - def capabilities(self): ... - def set_capability(self, name, value) -> None: ... - @property - def preferences(self): ... - def set_preference(self, name, value) -> None: ... - @property - def proxy(self): ... - @proxy.setter - def proxy(self, value) -> None: ... - @property - def profile(self): ... - @profile.setter - def profile(self, new_profile) -> None: ... - @property - def arguments(self): ... - def add_argument(self, argument) -> None: ... - @property - def headless(self): ... - @headless.setter - def headless(self, value) -> None: ... - def set_headless(self, headless: bool = ...) -> None: ... - def to_capabilities(self): ... diff --git a/stubs/selenium/selenium/webdriver/firefox/remote_connection.pyi b/stubs/selenium/selenium/webdriver/firefox/remote_connection.pyi deleted file mode 100644 index 7bfe0847234f..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/remote_connection.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from selenium.webdriver.remote.remote_connection import RemoteConnection as RemoteConnection - -class FirefoxRemoteConnection(RemoteConnection): - def __init__(self, remote_server_addr, keep_alive: bool = ...) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/firefox/service.pyi b/stubs/selenium/selenium/webdriver/firefox/service.pyi deleted file mode 100644 index a28db4351515..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/service.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - service_args: Any - def __init__( - self, executable_path, port: int = ..., service_args: Any | None = ..., log_path: str = ..., env: Any | None = ... - ) -> None: ... - def command_line_args(self): ... - def send_remote_shutdown_command(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/firefox/webdriver.pyi b/stubs/selenium/selenium/webdriver/firefox/webdriver.pyi deleted file mode 100644 index e76cf3bfdd95..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/webdriver.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from collections.abc import Generator -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -from .extension_connection import ExtensionConnection as ExtensionConnection -from .firefox_binary import FirefoxBinary as FirefoxBinary -from .firefox_profile import FirefoxProfile as FirefoxProfile -from .options import Options as Options -from .remote_connection import FirefoxRemoteConnection as FirefoxRemoteConnection -from .service import Service as Service -from .webelement import FirefoxWebElement as FirefoxWebElement - -basestring = str - -class WebDriver(RemoteWebDriver): - NATIVE_EVENTS_ALLOWED: Any - CONTEXT_CHROME: str - CONTEXT_CONTENT: str - binary: Any - profile: Any - service: Any - def __init__( - self, - firefox_profile: Any | None = ..., - firefox_binary: Any | None = ..., - timeout: int = ..., - capabilities: Any | None = ..., - proxy: Any | None = ..., - executable_path: str = ..., - options: Any | None = ..., - service_log_path: str = ..., - firefox_options: Any | None = ..., - service_args: Any | None = ..., - desired_capabilities: Any | None = ..., - log_path: Any | None = ..., - keep_alive: bool = ..., - ) -> None: ... - def quit(self) -> None: ... - @property - def firefox_profile(self): ... - def set_context(self, context) -> None: ... - def context(self, context) -> Generator[None, None, None]: ... - def install_addon(self, path, temporary: Any | None = ...): ... - def uninstall_addon(self, identifier) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/firefox/webelement.pyi b/stubs/selenium/selenium/webdriver/firefox/webelement.pyi deleted file mode 100644 index 1a4b49fc6159..000000000000 --- a/stubs/selenium/selenium/webdriver/firefox/webelement.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from selenium.webdriver.remote.webelement import WebElement as RemoteWebElement - -class FirefoxWebElement(RemoteWebElement): - @property - def anonymous_children(self): ... - def find_anonymous_element_by_attribute(self, name, value): ... diff --git a/stubs/selenium/selenium/webdriver/ie/options.pyi b/stubs/selenium/selenium/webdriver/ie/options.pyi deleted file mode 100644 index e32af1727411..000000000000 --- a/stubs/selenium/selenium/webdriver/ie/options.pyi +++ /dev/null @@ -1,95 +0,0 @@ -class ElementScrollBehavior: - TOP: int - BOTTOM: int - -class Options: - KEY: str - SWITCHES: str - BROWSER_ATTACH_TIMEOUT: str - ELEMENT_SCROLL_BEHAVIOR: str - ENSURE_CLEAN_SESSION: str - FILE_UPLOAD_DIALOG_TIMEOUT: str - FORCE_CREATE_PROCESS_API: str - FORCE_SHELL_WINDOWS_API: str - FULL_PAGE_SCREENSHOT: str - IGNORE_PROTECTED_MODE_SETTINGS: str - IGNORE_ZOOM_LEVEL: str - INITIAL_BROWSER_URL: str - NATIVE_EVENTS: str - PERSISTENT_HOVER: str - REQUIRE_WINDOW_FOCUS: str - USE_PER_PROCESS_PROXY: str - VALIDATE_COOKIE_DOCUMENT_TYPE: str - def __init__(self) -> None: ... - @property - def arguments(self): ... - def add_argument(self, argument) -> None: ... - @property - def options(self): ... - @property - def capabilities(self): ... - def set_capability(self, name, value) -> None: ... - @property - def browser_attach_timeout(self): ... - @browser_attach_timeout.setter - def browser_attach_timeout(self, value) -> None: ... - @property - def element_scroll_behavior(self): ... - @element_scroll_behavior.setter - def element_scroll_behavior(self, value) -> None: ... - @property - def ensure_clean_session(self): ... - @ensure_clean_session.setter - def ensure_clean_session(self, value) -> None: ... - @property - def file_upload_dialog_timeout(self): ... - @file_upload_dialog_timeout.setter - def file_upload_dialog_timeout(self, value) -> None: ... - @property - def force_create_process_api(self): ... - @force_create_process_api.setter - def force_create_process_api(self, value) -> None: ... - @property - def force_shell_windows_api(self): ... - @force_shell_windows_api.setter - def force_shell_windows_api(self, value) -> None: ... - @property - def full_page_screenshot(self): ... - @full_page_screenshot.setter - def full_page_screenshot(self, value) -> None: ... - @property - def ignore_protected_mode_settings(self): ... - @ignore_protected_mode_settings.setter - def ignore_protected_mode_settings(self, value) -> None: ... - @property - def ignore_zoom_level(self): ... - @ignore_zoom_level.setter - def ignore_zoom_level(self, value) -> None: ... - @property - def initial_browser_url(self): ... - @initial_browser_url.setter - def initial_browser_url(self, value) -> None: ... - @property - def native_events(self): ... - @native_events.setter - def native_events(self, value) -> None: ... - @property - def persistent_hover(self): ... - @persistent_hover.setter - def persistent_hover(self, value) -> None: ... - @property - def require_window_focus(self): ... - @require_window_focus.setter - def require_window_focus(self, value) -> None: ... - @property - def use_per_process_proxy(self): ... - @use_per_process_proxy.setter - def use_per_process_proxy(self, value) -> None: ... - @property - def validate_cookie_document_type(self): ... - @validate_cookie_document_type.setter - def validate_cookie_document_type(self, value) -> None: ... - @property - def additional_options(self): ... - def add_additional_option(self, name, value) -> None: ... - def to_capabilities(self): ... diff --git a/stubs/selenium/selenium/webdriver/ie/service.pyi b/stubs/selenium/selenium/webdriver/ie/service.pyi deleted file mode 100644 index faae611e7670..000000000000 --- a/stubs/selenium/selenium/webdriver/ie/service.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - service_args: Any - def __init__( - self, executable_path, port: int = ..., host: Any | None = ..., log_level: Any | None = ..., log_file: Any | None = ... - ) -> None: ... - def command_line_args(self): ... diff --git a/stubs/selenium/selenium/webdriver/ie/webdriver.pyi b/stubs/selenium/selenium/webdriver/ie/webdriver.pyi deleted file mode 100644 index 94e00380ea1c..000000000000 --- a/stubs/selenium/selenium/webdriver/ie/webdriver.pyi +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -from .options import Options as Options -from .service import Service as Service - -DEFAULT_TIMEOUT: int -DEFAULT_PORT: int -DEFAULT_HOST: Any -DEFAULT_LOG_LEVEL: Any -DEFAULT_SERVICE_LOG_PATH: Any - -class WebDriver(RemoteWebDriver): - port: Any - host: Any - iedriver: Any - def __init__( - self, - executable_path: str = ..., - capabilities: Any | None = ..., - port=..., - timeout=..., - host=..., - log_level=..., - service_log_path=..., - options: Any | None = ..., - ie_options: Any | None = ..., - desired_capabilities: Any | None = ..., - log_file: Any | None = ..., - keep_alive: bool = ..., - ) -> None: ... - def quit(self) -> None: ... - def create_options(self): ... diff --git a/stubs/selenium/selenium/webdriver/opera/options.pyi b/stubs/selenium/selenium/webdriver/opera/options.pyi deleted file mode 100644 index 508b61b51e15..000000000000 --- a/stubs/selenium/selenium/webdriver/opera/options.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from selenium.webdriver.chrome.options import Options as ChromeOptions - -class Options(ChromeOptions): - KEY: str - def __init__(self) -> None: ... - @property - def capabilities(self): ... - def set_capability(self, name, value) -> None: ... - @property - def android_package_name(self): ... - @android_package_name.setter - def android_package_name(self, value) -> None: ... - @property - def android_device_socket(self): ... - @android_device_socket.setter - def android_device_socket(self, value) -> None: ... - @property - def android_command_line_file(self): ... - @android_command_line_file.setter - def android_command_line_file(self, value) -> None: ... - def to_capabilities(self): ... - -class AndroidOptions(Options): - android_package_name: str - def __init__(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/opera/webdriver.pyi b/stubs/selenium/selenium/webdriver/opera/webdriver.pyi deleted file mode 100644 index bad77b141e2d..000000000000 --- a/stubs/selenium/selenium/webdriver/opera/webdriver.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any - -from selenium.webdriver.chrome.webdriver import WebDriver as ChromiumDriver - -from .options import Options as Options - -class OperaDriver(ChromiumDriver): - def __init__( - self, - executable_path: Any | None = ..., - port: int = ..., - options: Any | None = ..., - service_args: Any | None = ..., - desired_capabilities: Any | None = ..., - service_log_path: Any | None = ..., - opera_options: Any | None = ..., - keep_alive: bool = ..., - ) -> None: ... - def create_options(self): ... - -class WebDriver(OperaDriver): - class ServiceType: - CHROMIUM: int - def __init__( - self, - desired_capabilities: Any | None = ..., - executable_path: Any | None = ..., - port: int = ..., - service_log_path: Any | None = ..., - service_args: Any | None = ..., - options: Any | None = ..., - ) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/phantomjs/service.pyi b/stubs/selenium/selenium/webdriver/phantomjs/service.pyi deleted file mode 100644 index bc6d763b91e8..000000000000 --- a/stubs/selenium/selenium/webdriver/phantomjs/service.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - service_args: Any - def __init__(self, executable_path, port: int = ..., service_args: Any | None = ..., log_path: Any | None = ...) -> None: ... - def command_line_args(self): ... - @property - def service_url(self): ... - def send_remote_shutdown_command(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/phantomjs/webdriver.pyi b/stubs/selenium/selenium/webdriver/phantomjs/webdriver.pyi deleted file mode 100644 index e57f48858580..000000000000 --- a/stubs/selenium/selenium/webdriver/phantomjs/webdriver.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -from .service import Service as Service - -class WebDriver(RemoteWebDriver): - service: Any - def __init__( - self, - executable_path: str = ..., - port: int = ..., - desired_capabilities=..., - service_args: Any | None = ..., - service_log_path: Any | None = ..., - ) -> None: ... - def quit(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/remote/command.pyi b/stubs/selenium/selenium/webdriver/remote/command.pyi deleted file mode 100644 index 18918be0622e..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/command.pyi +++ /dev/null @@ -1,126 +0,0 @@ -class Command: - STATUS: str - NEW_SESSION: str - GET_ALL_SESSIONS: str - DELETE_SESSION: str - CLOSE: str - QUIT: str - GET: str - GO_BACK: str - GO_FORWARD: str - REFRESH: str - ADD_COOKIE: str - GET_COOKIE: str - GET_ALL_COOKIES: str - DELETE_COOKIE: str - DELETE_ALL_COOKIES: str - FIND_ELEMENT: str - FIND_ELEMENTS: str - FIND_CHILD_ELEMENT: str - FIND_CHILD_ELEMENTS: str - CLEAR_ELEMENT: str - CLICK_ELEMENT: str - SEND_KEYS_TO_ELEMENT: str - SEND_KEYS_TO_ACTIVE_ELEMENT: str - SUBMIT_ELEMENT: str - UPLOAD_FILE: str - GET_CURRENT_WINDOW_HANDLE: str - W3C_GET_CURRENT_WINDOW_HANDLE: str - GET_WINDOW_HANDLES: str - W3C_GET_WINDOW_HANDLES: str - GET_WINDOW_SIZE: str - W3C_GET_WINDOW_SIZE: str - W3C_GET_WINDOW_POSITION: str - GET_WINDOW_POSITION: str - SET_WINDOW_SIZE: str - W3C_SET_WINDOW_SIZE: str - SET_WINDOW_RECT: str - GET_WINDOW_RECT: str - SET_WINDOW_POSITION: str - W3C_SET_WINDOW_POSITION: str - SWITCH_TO_WINDOW: str - SWITCH_TO_FRAME: str - SWITCH_TO_PARENT_FRAME: str - GET_ACTIVE_ELEMENT: str - W3C_GET_ACTIVE_ELEMENT: str - GET_CURRENT_URL: str - GET_PAGE_SOURCE: str - GET_TITLE: str - EXECUTE_SCRIPT: str - W3C_EXECUTE_SCRIPT: str - W3C_EXECUTE_SCRIPT_ASYNC: str - GET_ELEMENT_TEXT: str - GET_ELEMENT_VALUE: str - GET_ELEMENT_TAG_NAME: str - SET_ELEMENT_SELECTED: str - IS_ELEMENT_SELECTED: str - IS_ELEMENT_ENABLED: str - IS_ELEMENT_DISPLAYED: str - GET_ELEMENT_LOCATION: str - GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW: str - GET_ELEMENT_SIZE: str - GET_ELEMENT_RECT: str - GET_ELEMENT_ATTRIBUTE: str - GET_ELEMENT_PROPERTY: str - GET_ELEMENT_VALUE_OF_CSS_PROPERTY: str - SCREENSHOT: str - ELEMENT_SCREENSHOT: str - IMPLICIT_WAIT: str - EXECUTE_ASYNC_SCRIPT: str - SET_SCRIPT_TIMEOUT: str - SET_TIMEOUTS: str - MAXIMIZE_WINDOW: str - W3C_MAXIMIZE_WINDOW: str - GET_LOG: str - GET_AVAILABLE_LOG_TYPES: str - FULLSCREEN_WINDOW: str - MINIMIZE_WINDOW: str - DISMISS_ALERT: str - W3C_DISMISS_ALERT: str - ACCEPT_ALERT: str - W3C_ACCEPT_ALERT: str - SET_ALERT_VALUE: str - W3C_SET_ALERT_VALUE: str - GET_ALERT_TEXT: str - W3C_GET_ALERT_TEXT: str - SET_ALERT_CREDENTIALS: str - W3C_ACTIONS: str - W3C_CLEAR_ACTIONS: str - CLICK: str - DOUBLE_CLICK: str - MOUSE_DOWN: str - MOUSE_UP: str - MOVE_TO: str - SET_SCREEN_ORIENTATION: str - GET_SCREEN_ORIENTATION: str - SINGLE_TAP: str - TOUCH_DOWN: str - TOUCH_UP: str - TOUCH_MOVE: str - TOUCH_SCROLL: str - DOUBLE_TAP: str - LONG_PRESS: str - FLICK: str - EXECUTE_SQL: str - GET_LOCATION: str - SET_LOCATION: str - GET_APP_CACHE: str - GET_APP_CACHE_STATUS: str - CLEAR_APP_CACHE: str - GET_LOCAL_STORAGE_ITEM: str - REMOVE_LOCAL_STORAGE_ITEM: str - GET_LOCAL_STORAGE_KEYS: str - SET_LOCAL_STORAGE_ITEM: str - CLEAR_LOCAL_STORAGE: str - GET_LOCAL_STORAGE_SIZE: str - GET_SESSION_STORAGE_ITEM: str - REMOVE_SESSION_STORAGE_ITEM: str - GET_SESSION_STORAGE_KEYS: str - SET_SESSION_STORAGE_ITEM: str - CLEAR_SESSION_STORAGE: str - GET_SESSION_STORAGE_SIZE: str - GET_NETWORK_CONNECTION: str - SET_NETWORK_CONNECTION: str - CURRENT_CONTEXT_HANDLE: str - CONTEXT_HANDLES: str - SWITCH_TO_CONTEXT: str diff --git a/stubs/selenium/selenium/webdriver/remote/errorhandler.pyi b/stubs/selenium/selenium/webdriver/remote/errorhandler.pyi deleted file mode 100644 index 5bdaa4629387..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/errorhandler.pyi +++ /dev/null @@ -1,74 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import ( - ElementClickInterceptedException as ElementClickInterceptedException, - ElementNotInteractableException as ElementNotInteractableException, - ElementNotSelectableException as ElementNotSelectableException, - ElementNotVisibleException as ElementNotVisibleException, - ErrorInResponseException as ErrorInResponseException, - ImeActivationFailedException as ImeActivationFailedException, - ImeNotAvailableException as ImeNotAvailableException, - InsecureCertificateException as InsecureCertificateException, - InvalidArgumentException as InvalidArgumentException, - InvalidCookieDomainException as InvalidCookieDomainException, - InvalidCoordinatesException as InvalidCoordinatesException, - InvalidElementStateException as InvalidElementStateException, - InvalidSelectorException as InvalidSelectorException, - InvalidSessionIdException as InvalidSessionIdException, - JavascriptException as JavascriptException, - MoveTargetOutOfBoundsException as MoveTargetOutOfBoundsException, - NoAlertPresentException as NoAlertPresentException, - NoSuchCookieException as NoSuchCookieException, - NoSuchElementException as NoSuchElementException, - NoSuchFrameException as NoSuchFrameException, - NoSuchWindowException as NoSuchWindowException, - ScreenshotException as ScreenshotException, - SessionNotCreatedException as SessionNotCreatedException, - StaleElementReferenceException as StaleElementReferenceException, - TimeoutException as TimeoutException, - UnableToSetCookieException as UnableToSetCookieException, - UnexpectedAlertPresentException as UnexpectedAlertPresentException, - UnknownMethodException as UnknownMethodException, - WebDriverException as WebDriverException, -) - -class ErrorCode: - SUCCESS: int - NO_SUCH_ELEMENT: Any - NO_SUCH_FRAME: Any - UNKNOWN_COMMAND: Any - STALE_ELEMENT_REFERENCE: Any - ELEMENT_NOT_VISIBLE: Any - INVALID_ELEMENT_STATE: Any - UNKNOWN_ERROR: Any - ELEMENT_IS_NOT_SELECTABLE: Any - JAVASCRIPT_ERROR: Any - XPATH_LOOKUP_ERROR: Any - TIMEOUT: Any - NO_SUCH_WINDOW: Any - INVALID_COOKIE_DOMAIN: Any - UNABLE_TO_SET_COOKIE: Any - UNEXPECTED_ALERT_OPEN: Any - NO_ALERT_OPEN: Any - SCRIPT_TIMEOUT: Any - INVALID_ELEMENT_COORDINATES: Any - IME_NOT_AVAILABLE: Any - IME_ENGINE_ACTIVATION_FAILED: Any - INVALID_SELECTOR: Any - SESSION_NOT_CREATED: Any - MOVE_TARGET_OUT_OF_BOUNDS: Any - INVALID_XPATH_SELECTOR: Any - INVALID_XPATH_SELECTOR_RETURN_TYPER: Any - ELEMENT_NOT_INTERACTABLE: Any - INSECURE_CERTIFICATE: Any - INVALID_ARGUMENT: Any - INVALID_COORDINATES: Any - INVALID_SESSION_ID: Any - NO_SUCH_COOKIE: Any - UNABLE_TO_CAPTURE_SCREEN: Any - ELEMENT_CLICK_INTERCEPTED: Any - UNKNOWN_METHOD: Any - METHOD_NOT_ALLOWED: Any - -class ErrorHandler: - def check_response(self, response) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/remote/file_detector.pyi b/stubs/selenium/selenium/webdriver/remote/file_detector.pyi deleted file mode 100644 index cbb4739b45a7..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/file_detector.pyi +++ /dev/null @@ -1,13 +0,0 @@ -import abc -from typing import Any - -class FileDetector(metaclass=abc.ABCMeta): - __metaclass__: Any - @abc.abstractmethod - def is_local_file(self, *keys): ... - -class UselessFileDetector(FileDetector): - def is_local_file(self, *keys) -> None: ... - -class LocalFileDetector(FileDetector): - def is_local_file(self, *keys): ... diff --git a/stubs/selenium/selenium/webdriver/remote/mobile.pyi b/stubs/selenium/selenium/webdriver/remote/mobile.pyi deleted file mode 100644 index 2f05913c32e4..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/mobile.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any - -from .command import Command as Command - -class Mobile: - class ConnectionType: - mask: Any - def __init__(self, mask) -> None: ... - @property - def airplane_mode(self): ... - @property - def wifi(self): ... - @property - def data(self): ... - ALL_NETWORK: Any - WIFI_NETWORK: Any - DATA_NETWORK: Any - AIRPLANE_MODE: Any - def __init__(self, driver) -> None: ... - @property - def network_connection(self): ... - def set_network_connection(self, network): ... - @property - def context(self): ... - @context.setter - def context(self, new_context) -> None: ... - @property - def contexts(self): ... diff --git a/stubs/selenium/selenium/webdriver/remote/remote_connection.pyi b/stubs/selenium/selenium/webdriver/remote/remote_connection.pyi deleted file mode 100644 index 9e6d103fda24..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/remote_connection.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -from .command import Command as Command -from .errorhandler import ErrorCode as ErrorCode - -LOGGER: Any - -class RemoteConnection: - @classmethod - def get_timeout(cls): ... - @classmethod - def set_timeout(cls, timeout) -> None: ... - @classmethod - def reset_timeout(cls) -> None: ... - @classmethod - def get_remote_connection_headers(cls, parsed_url, keep_alive: bool = ...): ... - keep_alive: Any - def __init__(self, remote_server_addr, keep_alive: bool = ..., resolve_ip: bool = ...) -> None: ... - def execute(self, command, params): ... diff --git a/stubs/selenium/selenium/webdriver/remote/switch_to.pyi b/stubs/selenium/selenium/webdriver/remote/switch_to.pyi deleted file mode 100644 index 52e8b96fc567..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/switch_to.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from selenium.common.exceptions import ( - NoSuchElementException as NoSuchElementException, - NoSuchFrameException as NoSuchFrameException, - NoSuchWindowException as NoSuchWindowException, -) -from selenium.webdriver.common.alert import Alert as Alert -from selenium.webdriver.common.by import By as By - -from .command import Command as Command - -basestring = str - -class SwitchTo: - def __init__(self, driver) -> None: ... - @property - def active_element(self): ... - @property - def alert(self): ... - def default_content(self) -> None: ... - def frame(self, frame_reference) -> None: ... - def parent_frame(self) -> None: ... - def window(self, window_name) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/remote/utils.pyi b/stubs/selenium/selenium/webdriver/remote/utils.pyi deleted file mode 100644 index d9cea7304605..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/utils.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any - -LOGGER: Any - -def format_json(json_struct): ... -def dump_json(json_struct): ... -def load_json(s): ... -def unzip_to_temp_dir(zip_file_name): ... diff --git a/stubs/selenium/selenium/webdriver/remote/webdriver.pyi b/stubs/selenium/selenium/webdriver/remote/webdriver.pyi deleted file mode 100644 index 2f117cb0016d..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/webdriver.pyi +++ /dev/null @@ -1,126 +0,0 @@ -from collections.abc import Generator -from typing import Any - -from selenium.common.exceptions import ( - InvalidArgumentException as InvalidArgumentException, - NoSuchCookieException as NoSuchCookieException, - WebDriverException as WebDriverException, -) -from selenium.webdriver.common.by import By as By -from selenium.webdriver.common.html5.application_cache import ApplicationCache as ApplicationCache - -from .command import Command as Command -from .errorhandler import ErrorHandler as ErrorHandler -from .file_detector import FileDetector as FileDetector, LocalFileDetector as LocalFileDetector -from .mobile import Mobile as Mobile -from .remote_connection import RemoteConnection as RemoteConnection -from .switch_to import SwitchTo as SwitchTo -from .webelement import WebElement as WebElement - -class WebDriver: - command_executor: Any - session_id: Any - capabilities: Any - error_handler: Any - def __init__( - self, - command_executor: str | RemoteConnection = ..., - desired_capabilities: Any | None = ..., - browser_profile: Any | None = ..., - proxy: Any | None = ..., - keep_alive: bool = ..., - file_detector: Any | None = ..., - options: Any | None = ..., - ) -> None: ... - def __enter__(self): ... - def __exit__(self, *args) -> None: ... - def file_detector_context(self, file_detector_class, *args, **kwargs) -> Generator[None, None, None]: ... - @property - def mobile(self): ... - @property - def name(self) -> str: ... - def start_client(self) -> None: ... - def stop_client(self) -> None: ... - w3c: Any - def start_session(self, capabilities, browser_profile: Any | None = ...) -> None: ... - def create_web_element(self, element_id) -> WebElement: ... - def execute(self, driver_command, params: Any | None = ...): ... - def get(self, url) -> None: ... - @property - def title(self) -> str: ... - def find_element_by_id(self, id_) -> WebElement: ... - def find_elements_by_id(self, id_) -> list[WebElement]: ... - def find_element_by_xpath(self, xpath) -> WebElement: ... - def find_elements_by_xpath(self, xpath) -> list[WebElement]: ... - def find_element_by_link_text(self, link_text) -> WebElement: ... - def find_elements_by_link_text(self, text) -> list[WebElement]: ... - def find_element_by_partial_link_text(self, link_text) -> WebElement: ... - def find_elements_by_partial_link_text(self, link_text) -> list[WebElement]: ... - def find_element_by_name(self, name) -> WebElement: ... - def find_elements_by_name(self, name) -> list[WebElement]: ... - def find_element_by_tag_name(self, name) -> WebElement: ... - def find_elements_by_tag_name(self, name) -> list[WebElement]: ... - def find_element_by_class_name(self, name) -> WebElement: ... - def find_elements_by_class_name(self, name) -> list[WebElement]: ... - def find_element_by_css_selector(self, css_selector) -> WebElement: ... - def find_elements_by_css_selector(self, css_selector) -> list[WebElement]: ... - def execute_script(self, script, *args): ... - def execute_async_script(self, script, *args): ... - @property - def current_url(self) -> str: ... - @property - def page_source(self) -> str: ... - def close(self) -> None: ... - def quit(self) -> None: ... - @property - def current_window_handle(self) -> str: ... - @property - def window_handles(self) -> list[str]: ... - def maximize_window(self) -> None: ... - def fullscreen_window(self) -> None: ... - def minimize_window(self) -> None: ... - @property - def switch_to(self) -> SwitchTo: ... - def switch_to_active_element(self): ... - def switch_to_window(self, window_name) -> None: ... - def switch_to_frame(self, frame_reference) -> None: ... - def switch_to_default_content(self) -> None: ... - def switch_to_alert(self): ... - def back(self) -> None: ... - def forward(self) -> None: ... - def refresh(self) -> None: ... - def get_cookies(self): ... - def get_cookie(self, name): ... - def delete_cookie(self, name) -> None: ... - def delete_all_cookies(self) -> None: ... - def add_cookie(self, cookie_dict) -> None: ... - def implicitly_wait(self, time_to_wait) -> None: ... - def set_script_timeout(self, time_to_wait) -> None: ... - def set_page_load_timeout(self, time_to_wait) -> None: ... - def find_element(self, by=..., value: Any | None = ...) -> WebElement: ... - def find_elements(self, by=..., value: Any | None = ...) -> list[WebElement]: ... - @property - def desired_capabilities(self): ... - def get_screenshot_as_file(self, filename) -> bool: ... - def save_screenshot(self, filename) -> bool: ... - def get_screenshot_as_png(self) -> bytes: ... - def get_screenshot_as_base64(self) -> str: ... - def set_window_size(self, width, height, windowHandle: str = ...) -> None: ... - def get_window_size(self, windowHandle: str = ...): ... - def set_window_position(self, x, y, windowHandle: str = ...): ... - def get_window_position(self, windowHandle: str = ...): ... - def get_window_rect(self): ... - def set_window_rect(self, x: Any | None = ..., y: Any | None = ..., width: Any | None = ..., height: Any | None = ...): ... - @property - def file_detector(self): ... - @file_detector.setter - def file_detector(self, detector) -> None: ... - @property - def orientation(self): ... - @orientation.setter - def orientation(self, value) -> None: ... - @property - def application_cache(self): ... - @property - def log_types(self): ... - def get_log(self, log_type): ... diff --git a/stubs/selenium/selenium/webdriver/remote/webelement.pyi b/stubs/selenium/selenium/webdriver/remote/webelement.pyi deleted file mode 100644 index 8aa4772566f6..000000000000 --- a/stubs/selenium/selenium/webdriver/remote/webelement.pyi +++ /dev/null @@ -1,64 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import WebDriverException as WebDriverException -from selenium.webdriver.common.by import By as By - -from .command import Command as Command - -getAttribute_js: Any -isDisplayed_js: Any - -class WebElement: - def __init__(self, parent, id_, w3c: bool = ...) -> None: ... - @property - def tag_name(self): ... - @property - def text(self): ... - def click(self) -> None: ... - def submit(self) -> None: ... - def clear(self) -> None: ... - def get_property(self, name): ... - def get_attribute(self, name): ... - def is_selected(self): ... - def is_enabled(self): ... - def find_element_by_id(self, id_): ... - def find_elements_by_id(self, id_): ... - def find_element_by_name(self, name): ... - def find_elements_by_name(self, name): ... - def find_element_by_link_text(self, link_text): ... - def find_elements_by_link_text(self, link_text): ... - def find_element_by_partial_link_text(self, link_text): ... - def find_elements_by_partial_link_text(self, link_text): ... - def find_element_by_tag_name(self, name): ... - def find_elements_by_tag_name(self, name): ... - def find_element_by_xpath(self, xpath): ... - def find_elements_by_xpath(self, xpath): ... - def find_element_by_class_name(self, name): ... - def find_elements_by_class_name(self, name): ... - def find_element_by_css_selector(self, css_selector): ... - def find_elements_by_css_selector(self, css_selector): ... - def send_keys(self, *value) -> None: ... - def is_displayed(self): ... - @property - def location_once_scrolled_into_view(self): ... - @property - def size(self): ... - def value_of_css_property(self, property_name): ... - @property - def location(self): ... - @property - def rect(self): ... - @property - def screenshot_as_base64(self): ... - @property - def screenshot_as_png(self): ... - def screenshot(self, filename): ... - @property - def parent(self): ... - @property - def id(self): ... - def __eq__(self, element): ... - def __ne__(self, element): ... - def find_element(self, by=..., value: Any | None = ...): ... - def find_elements(self, by=..., value: Any | None = ...): ... - def __hash__(self): ... diff --git a/stubs/selenium/selenium/webdriver/safari/permissions.pyi b/stubs/selenium/selenium/webdriver/safari/permissions.pyi deleted file mode 100644 index dc83876e033e..000000000000 --- a/stubs/selenium/selenium/webdriver/safari/permissions.pyi +++ /dev/null @@ -1,2 +0,0 @@ -class Permission: - GET_USER_MEDIA: str diff --git a/stubs/selenium/selenium/webdriver/safari/remote_connection.pyi b/stubs/selenium/selenium/webdriver/safari/remote_connection.pyi deleted file mode 100644 index ae5623f8008a..000000000000 --- a/stubs/selenium/selenium/webdriver/safari/remote_connection.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from selenium.webdriver.remote.remote_connection import RemoteConnection as RemoteConnection - -class SafariRemoteConnection(RemoteConnection): - def __init__(self, remote_server_addr, keep_alive: bool = ...) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/safari/service.pyi b/stubs/selenium/selenium/webdriver/safari/service.pyi deleted file mode 100644 index d45b0525d48e..000000000000 --- a/stubs/selenium/selenium/webdriver/safari/service.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - service_args: Any - quiet: Any - def __init__(self, executable_path, port: int = ..., quiet: bool = ..., service_args: Any | None = ...) -> None: ... - def command_line_args(self): ... - @property - def service_url(self): ... diff --git a/stubs/selenium/selenium/webdriver/safari/webdriver.pyi b/stubs/selenium/selenium/webdriver/safari/webdriver.pyi deleted file mode 100644 index 3f9c07b549b6..000000000000 --- a/stubs/selenium/selenium/webdriver/safari/webdriver.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import WebDriverException as WebDriverException -from selenium.webdriver.common.desired_capabilities import DesiredCapabilities as DesiredCapabilities -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -from .remote_connection import SafariRemoteConnection as SafariRemoteConnection -from .service import Service as Service - -class WebDriver(RemoteWebDriver): - service: Any - def __init__( - self, - port: int = ..., - executable_path: str = ..., - reuse_service: bool = ..., - desired_capabilities=..., - quiet: bool = ..., - keep_alive: bool = ..., - service_args: Any | None = ..., - ) -> None: ... - def quit(self) -> None: ... - def set_permission(self, permission, value) -> None: ... - def get_permission(self, permission): ... - def debug(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/support/abstract_event_listener.pyi b/stubs/selenium/selenium/webdriver/support/abstract_event_listener.pyi deleted file mode 100644 index afea81634f32..000000000000 --- a/stubs/selenium/selenium/webdriver/support/abstract_event_listener.pyi +++ /dev/null @@ -1,20 +0,0 @@ -class AbstractEventListener: - def before_navigate_to(self, url, driver) -> None: ... - def after_navigate_to(self, url, driver) -> None: ... - def before_navigate_back(self, driver) -> None: ... - def after_navigate_back(self, driver) -> None: ... - def before_navigate_forward(self, driver) -> None: ... - def after_navigate_forward(self, driver) -> None: ... - def before_find(self, by, value, driver) -> None: ... - def after_find(self, by, value, driver) -> None: ... - def before_click(self, element, driver) -> None: ... - def after_click(self, element, driver) -> None: ... - def before_change_value_of(self, element, driver) -> None: ... - def after_change_value_of(self, element, driver) -> None: ... - def before_execute_script(self, script, driver) -> None: ... - def after_execute_script(self, script, driver) -> None: ... - def before_close(self, driver) -> None: ... - def after_close(self, driver) -> None: ... - def before_quit(self, driver) -> None: ... - def after_quit(self, driver) -> None: ... - def on_exception(self, exception, driver) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/support/color.pyi b/stubs/selenium/selenium/webdriver/support/color.pyi deleted file mode 100644 index 48bde30212a9..000000000000 --- a/stubs/selenium/selenium/webdriver/support/color.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any - -RGB_PATTERN: str -RGB_PCT_PATTERN: str -RGBA_PATTERN: str -RGBA_PCT_PATTERN: str -HEX_PATTERN: str -HEX3_PATTERN: str -HSL_PATTERN: str -HSLA_PATTERN: str - -class Color: - match_obj: Any - @staticmethod - def from_string(str_): ... - red: Any - green: Any - blue: Any - alpha: Any - def __init__(self, red, green, blue, alpha: int = ...) -> None: ... - @property - def rgb(self): ... - @property - def rgba(self): ... - @property - def hex(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __hash__(self): ... - -Colors: Any diff --git a/stubs/selenium/selenium/webdriver/support/event_firing_webdriver.pyi b/stubs/selenium/selenium/webdriver/support/event_firing_webdriver.pyi deleted file mode 100644 index 0720d7f3bf98..000000000000 --- a/stubs/selenium/selenium/webdriver/support/event_firing_webdriver.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import WebDriverException as WebDriverException -from selenium.webdriver.common.by import By as By -from selenium.webdriver.remote.webdriver import WebDriver as WebDriver -from selenium.webdriver.remote.webelement import WebElement as WebElement - -from .abstract_event_listener import AbstractEventListener as AbstractEventListener - -class EventFiringWebDriver: - def __init__(self, driver, event_listener) -> None: ... - @property - def wrapped_driver(self): ... - def get(self, url) -> None: ... - def back(self) -> None: ... - def forward(self) -> None: ... - def execute_script(self, script, *args): ... - def execute_async_script(self, script, *args): ... - def close(self) -> None: ... - def quit(self) -> None: ... - def find_element(self, by=..., value: Any | None = ...): ... - def find_elements(self, by=..., value: Any | None = ...): ... - def find_element_by_id(self, id_): ... - def find_elements_by_id(self, id_): ... - def find_element_by_xpath(self, xpath): ... - def find_elements_by_xpath(self, xpath): ... - def find_element_by_link_text(self, link_text): ... - def find_elements_by_link_text(self, text): ... - def find_element_by_partial_link_text(self, link_text): ... - def find_elements_by_partial_link_text(self, link_text): ... - def find_element_by_name(self, name): ... - def find_elements_by_name(self, name): ... - def find_element_by_tag_name(self, name): ... - def find_elements_by_tag_name(self, name): ... - def find_element_by_class_name(self, name): ... - def find_elements_by_class_name(self, name): ... - def find_element_by_css_selector(self, css_selector): ... - def find_elements_by_css_selector(self, css_selector): ... - def __setattr__(self, item, value) -> None: ... - def __getattr__(self, name): ... - -class EventFiringWebElement: - def __init__(self, webelement, ef_driver) -> None: ... - @property - def wrapped_element(self): ... - def click(self) -> None: ... - def clear(self) -> None: ... - def send_keys(self, *value) -> None: ... - def find_element(self, by=..., value: Any | None = ...): ... - def find_elements(self, by=..., value: Any | None = ...): ... - def find_element_by_id(self, id_): ... - def find_elements_by_id(self, id_): ... - def find_element_by_name(self, name): ... - def find_elements_by_name(self, name): ... - def find_element_by_link_text(self, link_text): ... - def find_elements_by_link_text(self, link_text): ... - def find_element_by_partial_link_text(self, link_text): ... - def find_elements_by_partial_link_text(self, link_text): ... - def find_element_by_tag_name(self, name): ... - def find_elements_by_tag_name(self, name): ... - def find_element_by_xpath(self, xpath): ... - def find_elements_by_xpath(self, xpath): ... - def find_element_by_class_name(self, name): ... - def find_elements_by_class_name(self, name): ... - def find_element_by_css_selector(self, css_selector): ... - def find_elements_by_css_selector(self, css_selector): ... - def __setattr__(self, item, value) -> None: ... - def __getattr__(self, name): ... diff --git a/stubs/selenium/selenium/webdriver/support/events.pyi b/stubs/selenium/selenium/webdriver/support/events.pyi deleted file mode 100644 index 1e3e7dd86b37..000000000000 --- a/stubs/selenium/selenium/webdriver/support/events.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from .abstract_event_listener import AbstractEventListener as AbstractEventListener -from .event_firing_webdriver import EventFiringWebDriver as EventFiringWebDriver diff --git a/stubs/selenium/selenium/webdriver/support/expected_conditions.pyi b/stubs/selenium/selenium/webdriver/support/expected_conditions.pyi deleted file mode 100644 index 642f4015f1c6..000000000000 --- a/stubs/selenium/selenium/webdriver/support/expected_conditions.pyi +++ /dev/null @@ -1,140 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import ( - NoAlertPresentException as NoAlertPresentException, - NoSuchElementException as NoSuchElementException, - NoSuchFrameException as NoSuchFrameException, - StaleElementReferenceException as StaleElementReferenceException, - WebDriverException as WebDriverException, -) -from selenium.webdriver.remote.webdriver import WebElement as WebElement - -class title_is: - title: Any - def __init__(self, title) -> None: ... - def __call__(self, driver): ... - -class title_contains: - title: Any - def __init__(self, title) -> None: ... - def __call__(self, driver): ... - -class presence_of_element_located: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class url_contains: - url: Any - def __init__(self, url) -> None: ... - def __call__(self, driver): ... - -class url_matches: - pattern: Any - def __init__(self, pattern) -> None: ... - def __call__(self, driver): ... - -class url_to_be: - url: Any - def __init__(self, url) -> None: ... - def __call__(self, driver): ... - -class url_changes: - url: Any - def __init__(self, url) -> None: ... - def __call__(self, driver): ... - -class visibility_of_element_located: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class visibility_of: - element: Any - def __init__(self, element) -> None: ... - def __call__(self, ignored): ... - -class presence_of_all_elements_located: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class visibility_of_any_elements_located: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class visibility_of_all_elements_located: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class text_to_be_present_in_element: - locator: Any - text: Any - def __init__(self, locator, text_) -> None: ... - def __call__(self, driver): ... - -class text_to_be_present_in_element_value: - locator: Any - text: Any - def __init__(self, locator, text_) -> None: ... - def __call__(self, driver): ... - -class frame_to_be_available_and_switch_to_it: - frame_locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class invisibility_of_element_located: - target: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class invisibility_of_element(invisibility_of_element_located): ... - -class element_to_be_clickable: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class staleness_of: - element: Any - def __init__(self, element) -> None: ... - def __call__(self, ignored): ... - -class element_to_be_selected: - element: Any - def __init__(self, element) -> None: ... - def __call__(self, ignored): ... - -class element_located_to_be_selected: - locator: Any - def __init__(self, locator) -> None: ... - def __call__(self, driver): ... - -class element_selection_state_to_be: - element: Any - is_selected: Any - def __init__(self, element, is_selected) -> None: ... - def __call__(self, ignored): ... - -class element_located_selection_state_to_be: - locator: Any - is_selected: Any - def __init__(self, locator, is_selected) -> None: ... - def __call__(self, driver): ... - -class number_of_windows_to_be: - num_windows: Any - def __init__(self, num_windows) -> None: ... - def __call__(self, driver): ... - -class new_window_is_opened: - current_handles: Any - def __init__(self, current_handles) -> None: ... - def __call__(self, driver): ... - -class alert_is_present: - def __init__(self) -> None: ... - def __call__(self, driver): ... diff --git a/stubs/selenium/selenium/webdriver/support/select.pyi b/stubs/selenium/selenium/webdriver/support/select.pyi deleted file mode 100644 index 690656a3b1b7..000000000000 --- a/stubs/selenium/selenium/webdriver/support/select.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import ( - NoSuchElementException as NoSuchElementException, - UnexpectedTagNameException as UnexpectedTagNameException, -) -from selenium.webdriver.common.by import By as By - -class Select: - is_multiple: Any - def __init__(self, webelement) -> None: ... - @property - def options(self): ... - @property - def all_selected_options(self): ... - @property - def first_selected_option(self): ... - def select_by_value(self, value) -> None: ... - def select_by_index(self, index) -> None: ... - def select_by_visible_text(self, text) -> None: ... - def deselect_all(self) -> None: ... - def deselect_by_value(self, value) -> None: ... - def deselect_by_index(self, index) -> None: ... - def deselect_by_visible_text(self, text) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/support/ui.pyi b/stubs/selenium/selenium/webdriver/support/ui.pyi deleted file mode 100644 index 5ab0b93a1ee6..000000000000 --- a/stubs/selenium/selenium/webdriver/support/ui.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from .select import Select as Select -from .wait import WebDriverWait as WebDriverWait diff --git a/stubs/selenium/selenium/webdriver/support/wait.pyi b/stubs/selenium/selenium/webdriver/support/wait.pyi deleted file mode 100644 index 51063488f970..000000000000 --- a/stubs/selenium/selenium/webdriver/support/wait.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from selenium.common.exceptions import NoSuchElementException as NoSuchElementException, TimeoutException as TimeoutException - -POLL_FREQUENCY: float -IGNORED_EXCEPTIONS: Any - -class WebDriverWait: - def __init__(self, driver, timeout, poll_frequency=..., ignored_exceptions: Any | None = ...) -> None: ... - def until(self, method, message: str = ...): ... - def until_not(self, method, message: str = ...): ... diff --git a/stubs/selenium/selenium/webdriver/webkitgtk/options.pyi b/stubs/selenium/selenium/webdriver/webkitgtk/options.pyi deleted file mode 100644 index 61f298c4e935..000000000000 --- a/stubs/selenium/selenium/webdriver/webkitgtk/options.pyi +++ /dev/null @@ -1,18 +0,0 @@ -class Options: - KEY: str - def __init__(self) -> None: ... - @property - def capabilities(self): ... - def set_capability(self, name, value) -> None: ... - @property - def binary_location(self): ... - @binary_location.setter - def binary_location(self, value) -> None: ... - @property - def arguments(self): ... - def add_argument(self, argument) -> None: ... - @property - def overlay_scrollbars_enabled(self): ... - @overlay_scrollbars_enabled.setter - def overlay_scrollbars_enabled(self, value) -> None: ... - def to_capabilities(self): ... diff --git a/stubs/selenium/selenium/webdriver/webkitgtk/service.pyi b/stubs/selenium/selenium/webdriver/webkitgtk/service.pyi deleted file mode 100644 index dc2804fea4c5..000000000000 --- a/stubs/selenium/selenium/webdriver/webkitgtk/service.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any - -from selenium.webdriver.common import service as service - -class Service(service.Service): - def __init__(self, executable_path, port: int = ..., log_path: Any | None = ...) -> None: ... - def command_line_args(self): ... - def send_remote_shutdown_command(self) -> None: ... diff --git a/stubs/selenium/selenium/webdriver/webkitgtk/webdriver.pyi b/stubs/selenium/selenium/webdriver/webkitgtk/webdriver.pyi deleted file mode 100644 index 4bc5b02c8f4e..000000000000 --- a/stubs/selenium/selenium/webdriver/webkitgtk/webdriver.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any - -from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver - -from .service import Service as Service - -class WebDriver(RemoteWebDriver): - service: Any - def __init__( - self, - executable_path: str = ..., - port: int = ..., - options: Any | None = ..., - desired_capabilities=..., - service_log_path: Any | None = ..., - keep_alive: bool = ..., - ) -> None: ... - def quit(self) -> None: ... diff --git a/stubs/setuptools/@tests/stubtest_allowlist.txt b/stubs/setuptools/@tests/stubtest_allowlist.txt index e06f40603b47..f1daacd06921 100644 --- a/stubs/setuptools/@tests/stubtest_allowlist.txt +++ b/stubs/setuptools/@tests/stubtest_allowlist.txt @@ -1,28 +1,84 @@ -pkg_resources.Distribution.__cmp__ -pkg_resources.Distribution.activate -pkg_resources.Distribution.get_entry_map -pkg_resources.EggMetadata.__init__ -pkg_resources.EggProvider.__init__ -pkg_resources.Environment.best_match -pkg_resources.Environment.obtain -pkg_resources.FileMetadata.__init__ -pkg_resources.IMetadataProvider.get_metadata -pkg_resources.IMetadataProvider.get_metadata_lines -pkg_resources.IMetadataProvider.has_metadata -pkg_resources.IMetadataProvider.metadata_isdir -pkg_resources.IMetadataProvider.metadata_listdir -pkg_resources.IMetadataProvider.run_script -pkg_resources.IResourceManager -pkg_resources.NullProvider.__init__ -pkg_resources.Requirement.__init__ -pkg_resources.WorkingSet.find_plugins -pkg_resources.WorkingSet.resolve -pkg_resources.WorkingSet.subscribe -pkg_resources.ZipProvider.__init__ -pkg_resources.declare_namespace -pkg_resources.fixup_namespace_packages -pkg_resources.get_entry_map -pkg_resources.get_provider -pkg_resources.py31compat -pkg_resources.split_sections -pkg_resources.to_filename +# Is a functools.partial, so stubtest says "is not a function" +setuptools._distutils._modified.newer_pairwise_group + +# Dynamically created in __init__ +setuptools._distutils.dist.Distribution.get_name +setuptools._distutils.dist.Distribution.get_version +setuptools._distutils.dist.Distribution.get_fullname +setuptools._distutils.dist.Distribution.get_author +setuptools._distutils.dist.Distribution.get_author_email +setuptools._distutils.dist.Distribution.get_maintainer +setuptools._distutils.dist.Distribution.get_maintainer_email +setuptools._distutils.dist.Distribution.get_contact +setuptools._distutils.dist.Distribution.get_contact_email +setuptools._distutils.dist.Distribution.get_url +setuptools._distutils.dist.Distribution.get_license +setuptools._distutils.dist.Distribution.get_licence +setuptools._distutils.dist.Distribution.get_description +setuptools._distutils.dist.Distribution.get_long_description +setuptools._distutils.dist.Distribution.get_keywords +setuptools._distutils.dist.Distribution.get_platforms +setuptools._distutils.dist.Distribution.get_classifiers +setuptools._distutils.dist.Distribution.get_download_url +setuptools._distutils.dist.Distribution.get_requires +setuptools._distutils.dist.Distribution.get_provides +setuptools._distutils.dist.Distribution.get_obsoletes + +# Missing objects from setuptools._distutils +setuptools._distutils.archive_util.ARCHIVE_FORMATS +setuptools._distutils.archive_util.check_archive_formats +setuptools._distutils.cmd.Command.dump_options +setuptools._distutils.command.build_ext.extension_name_re +setuptools._distutils.command.install.HAS_USER_SITE +setuptools._distutils.command.install.INSTALL_SCHEMES +setuptools._distutils.command.install.SCHEME_KEYS +setuptools._distutils.command.install.WINDOWS_SCHEME +setuptools._distutils.command.install_lib.PYTHON_SOURCE_EXTENSION +setuptools._distutils.dist.fix_help_options +setuptools._distutils.extension.read_setup_file +setuptools._distutils.filelist.findall +setuptools._distutils.filelist.glob_to_re +setuptools._distutils.filelist.translate_pattern +setuptools._distutils.sysconfig.BASE_EXEC_PREFIX +setuptools._distutils.sysconfig.BASE_PREFIX +setuptools._distutils.sysconfig.IS_PYPY +setuptools._distutils.sysconfig.build_flags +setuptools._distutils.sysconfig.expand_makefile_vars +setuptools._distutils.sysconfig.get_python_version +setuptools._distutils.sysconfig.parse_config_h +setuptools._distutils.sysconfig.parse_makefile +setuptools._distutils.sysconfig.project_base +setuptools._distutils.sysconfig.python_build + +# Missing submodules from setuptools._distutils +# (Many of these may be implementation details, +# in an already private vendored module, +# but they can be added if people ask for them) +setuptools._distutils.command.__all__ +setuptools._distutils.command.bdist_dumb +setuptools._distutils.command.build_scripts +setuptools._distutils.command.check +setuptools._distutils.command.clean +setuptools._distutils.command.config +setuptools._distutils.command.install_egg_info +setuptools._distutils.command.install_headers +setuptools._distutils.compat.* +setuptools._distutils.core +setuptools._distutils.debug +setuptools._distutils.dir_util +setuptools._distutils.fancy_getopt +setuptools._distutils.file_util +setuptools._distutils.log +setuptools._distutils.text_file +setuptools._distutils.version.Version._cmp # abstract method +setuptools._distutils.version.Version.parse # abstract method +setuptools._distutils.version.suppress_known_deprecation +setuptools._distutils.versionpredicate + +# Reexported from setuptools._distutils; problems should be fixed there +distutils\..+ + +# Private APIs, tests and other vendored code +setuptools.config._validate_pyproject.* +setuptools.compat.* +setuptools.command.build_py.build_py.existing_egg_info_dir diff --git a/stubs/setuptools/@tests/test_cases/check_distutils.py b/stubs/setuptools/@tests/test_cases/check_distutils.py new file mode 100644 index 000000000000..cbd3e645c545 --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_distutils.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import distutils.command.sdist +from _typeshed import StrPath +from os import PathLike +from pathlib import Path + +from setuptools._distutils.ccompiler import CCompiler + +c = distutils.command.sdist.sdist + +# Test CCompiler().compile with varied sources + +compiler = CCompiler() + +str_list: list[str] = ["file1.c", "file2.c"] +compiler.compile(sources=str_list) + +path_list: list[Path] = [Path("file1.c"), Path("file2.c")] +compiler.compile(sources=path_list) + +pathlike_list: list[PathLike[str]] = [Path("file1.c"), Path("file2.c")] +compiler.compile(sources=pathlike_list) + +strpath_list: list[StrPath] = [Path("file1.c"), "file2.c"] +compiler.compile(sources=strpath_list) + +# Direct literals should also work +compiler.compile(sources=["file1.c", "file2.c"]) +compiler.compile(sources=[Path("file1.c"), Path("file2.c")]) +compiler.compile(sources=[Path("file1.c"), "file2.c"]) diff --git a/stubs/setuptools/@tests/test_cases/check_extension.py b/stubs/setuptools/@tests/test_cases/check_extension.py new file mode 100644 index 000000000000..c798d4eb98ad --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_extension.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from os import PathLike +from pathlib import Path + +from setuptools import Extension + +# Dummy extensions +ext1 = Extension(name="test1", sources=["file1.c", "file2.c"]) # plain list[str] works + +path_sources: list[Path] = [Path("file1.c"), Path("file2.c")] +ext2 = Extension(name="test2", sources=path_sources) # list of Path(s) + +mixed_sources: list[str | PathLike[str]] = [Path("file1.c"), "file2.c"] # or list[StrPath] +ext3 = Extension(name="test3", sources=mixed_sources) # mixed types diff --git a/stubs/setuptools/@tests/test_cases/check_protocols.py b/stubs/setuptools/@tests/test_cases/check_protocols.py new file mode 100644 index 000000000000..20573855ac44 --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_protocols.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from typing import Any + +from setuptools.command.editable_wheel import EditableStrategy, _LinkTree, _StaticPth, _TopLevelFinder +from setuptools.config.expand import EnsurePackagesDiscovered +from setuptools.config.pyprojecttoml import _EnsurePackagesDiscovered + +# We don't care about the __init__ methods, only about if an instance respects the Protocol +_: Any = object() + +# Test EditableStrategy Protocol implementers +editable_strategy: EditableStrategy +editable_strategy = _StaticPth(_, _, _) +editable_strategy = _LinkTree(_, _, _, _) +editable_strategy = _TopLevelFinder(_, _) +# Not EditableStrategy due to incompatible __call__ method +editable_strategy = EnsurePackagesDiscovered(_) # type: ignore +editable_strategy = _EnsurePackagesDiscovered(_, _, _) # type: ignore diff --git a/stubs/setuptools/@tests/test_cases/check_setup.py b/stubs/setuptools/@tests/test_cases/check_setup.py new file mode 100644 index 000000000000..b6bac7b01de5 --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_setup.py @@ -0,0 +1,23 @@ +from typing_extensions import assert_type + +from setuptools import Command as setuptools_Command, Distribution as setuptools_Distribution, setup +from setuptools._distutils.cmd import Command as distutils_Command +from setuptools._distutils.dist import Distribution as distutils_Distribution + +# Ensure that any distutils-derived classes are usable w/o type variance issues +assert_type( + setup( + cmdclass=dict[str, type[distutils_Command]](), + command_obj=dict[str, distutils_Command](), + distclass=distutils_Distribution, + ), + distutils_Distribution, +) +assert_type( + setup( + cmdclass=dict[str, type[setuptools_Command]](), + command_obj=dict[str, setuptools_Command](), + distclass=setuptools_Distribution, + ), + setuptools_Distribution, +) diff --git a/stubs/setuptools/METADATA.toml b/stubs/setuptools/METADATA.toml index ff6e4177e062..f7ba41591377 100644 --- a/stubs/setuptools/METADATA.toml +++ b/stubs/setuptools/METADATA.toml @@ -1 +1,19 @@ -version = "57.4.*" +version = "84.0.*" +upstream-repository = "https://github.com/pypa/setuptools" +extra-description = """\ +Given that `pkg_resources` is typed since `setuptools >= 71.1`, \ +it is no longer included with `types-setuptools`. +""" + +[tool.stubtest] +# darwin is equivalent to linux for OS-specific methods +ci-platforms = ["linux", "win32"] +stubtest-dependencies = ["more_itertools", "tomli"] + +# Stubtest fails on trying to run mypy on the source files rather than our stubs +[mypy-tests.distutils1] +module-name = "setuptools._distutils.compilers.C.*" +values = { ignore_errors = true } +[mypy-tests.distutils2] +module-name = "setuptools._distutils.compilers.platform.detect" +values = { ignore_errors = true } diff --git a/stubs/setuptools/distutils/__init__.pyi b/stubs/setuptools/distutils/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/setuptools/distutils/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/setuptools/distutils/_modified.pyi b/stubs/setuptools/distutils/_modified.pyi new file mode 100644 index 000000000000..e916197a5ae2 --- /dev/null +++ b/stubs/setuptools/distutils/_modified.pyi @@ -0,0 +1 @@ +from setuptools._distutils._modified import * diff --git a/stubs/setuptools/distutils/_msvccompiler.pyi b/stubs/setuptools/distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..f2ead92dea06 --- /dev/null +++ b/stubs/setuptools/distutils/_msvccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils._msvccompiler import * diff --git a/stubs/setuptools/distutils/archive_util.pyi b/stubs/setuptools/distutils/archive_util.pyi new file mode 100644 index 000000000000..115f30506461 --- /dev/null +++ b/stubs/setuptools/distutils/archive_util.pyi @@ -0,0 +1 @@ +from setuptools._distutils.archive_util import * diff --git a/stubs/setuptools/distutils/ccompiler.pyi b/stubs/setuptools/distutils/ccompiler.pyi new file mode 100644 index 000000000000..d8f1af11ef33 --- /dev/null +++ b/stubs/setuptools/distutils/ccompiler.pyi @@ -0,0 +1,12 @@ +from setuptools._distutils.ccompiler import * +from setuptools._distutils.ccompiler import CCompiler as CCompiler + +__all__ = [ + "CompileError", + "LinkError", + "gen_lib_options", + "gen_preprocess_options", + "get_default_compiler", + "new_compiler", + "show_compilers", +] diff --git a/stubs/setuptools/distutils/cmd.pyi b/stubs/setuptools/distutils/cmd.pyi new file mode 100644 index 000000000000..235ca5680913 --- /dev/null +++ b/stubs/setuptools/distutils/cmd.pyi @@ -0,0 +1 @@ +from setuptools._distutils.cmd import * diff --git a/stubs/setuptools/distutils/command/__init__.pyi b/stubs/setuptools/distutils/command/__init__.pyi new file mode 100644 index 000000000000..adeb472a515f --- /dev/null +++ b/stubs/setuptools/distutils/command/__init__.pyi @@ -0,0 +1,39 @@ +from . import ( + bdist as bdist, + bdist_rpm as bdist_rpm, + build as build, + build_clib as build_clib, + build_ext as build_ext, + build_py as build_py, + # build_scripts as build_scripts, + # check as check, + # clean as clean, + install as install, + # install_data as install_data, + # install_headers as install_headers, + install_lib as install_lib, + install_scripts as install_scripts, + sdist as sdist, +) + +# Commented out commands are not stubbed. +# (Many of these may be implementation details, +# but they can be added if people ask for them) +__all__ = [ + "build", + "build_py", + "build_ext", + "build_clib", + # "build_scripts", + # "clean", + "install", + "install_lib", + # "install_headers", + "install_scripts", + # "install_data", + "sdist", + "bdist", + # "bdist_dumb", + "bdist_rpm", + # "check", +] diff --git a/stubs/setuptools/distutils/command/bdist.pyi b/stubs/setuptools/distutils/command/bdist.pyi new file mode 100644 index 000000000000..3445de9fbe0c --- /dev/null +++ b/stubs/setuptools/distutils/command/bdist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.bdist import * diff --git a/stubs/setuptools/distutils/command/bdist_rpm.pyi b/stubs/setuptools/distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..32e88d493a3f --- /dev/null +++ b/stubs/setuptools/distutils/command/bdist_rpm.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.bdist_rpm import * diff --git a/stubs/setuptools/distutils/command/build.pyi b/stubs/setuptools/distutils/command/build.pyi new file mode 100644 index 000000000000..1fe7d1e73415 --- /dev/null +++ b/stubs/setuptools/distutils/command/build.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build import * diff --git a/stubs/setuptools/distutils/command/build_clib.pyi b/stubs/setuptools/distutils/command/build_clib.pyi new file mode 100644 index 000000000000..f60f41aa89f4 --- /dev/null +++ b/stubs/setuptools/distutils/command/build_clib.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build_clib import * diff --git a/stubs/setuptools/distutils/command/build_ext.pyi b/stubs/setuptools/distutils/command/build_ext.pyi new file mode 100644 index 000000000000..c1967156809e --- /dev/null +++ b/stubs/setuptools/distutils/command/build_ext.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build_ext import * diff --git a/stubs/setuptools/distutils/command/build_py.pyi b/stubs/setuptools/distutils/command/build_py.pyi new file mode 100644 index 000000000000..0d97b743f7de --- /dev/null +++ b/stubs/setuptools/distutils/command/build_py.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build_py import * diff --git a/stubs/setuptools/distutils/command/install.pyi b/stubs/setuptools/distutils/command/install.pyi new file mode 100644 index 000000000000..6ef0aca09e23 --- /dev/null +++ b/stubs/setuptools/distutils/command/install.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install import * diff --git a/stubs/setuptools/distutils/command/install_data.pyi b/stubs/setuptools/distutils/command/install_data.pyi new file mode 100644 index 000000000000..039f8b41c901 --- /dev/null +++ b/stubs/setuptools/distutils/command/install_data.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install_data import * diff --git a/stubs/setuptools/distutils/command/install_lib.pyi b/stubs/setuptools/distutils/command/install_lib.pyi new file mode 100644 index 000000000000..bfcfe358cb1e --- /dev/null +++ b/stubs/setuptools/distutils/command/install_lib.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install_lib import * diff --git a/stubs/setuptools/distutils/command/install_scripts.pyi b/stubs/setuptools/distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..3cebd5543427 --- /dev/null +++ b/stubs/setuptools/distutils/command/install_scripts.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install_scripts import * diff --git a/stubs/setuptools/distutils/command/sdist.pyi b/stubs/setuptools/distutils/command/sdist.pyi new file mode 100644 index 000000000000..50a819163764 --- /dev/null +++ b/stubs/setuptools/distutils/command/sdist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.sdist import * diff --git a/stubs/setuptools/distutils/compilers/C/base.pyi b/stubs/setuptools/distutils/compilers/C/base.pyi new file mode 100644 index 000000000000..5e58ee9cbe68 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/base.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.base import * diff --git a/stubs/setuptools/distutils/compilers/C/cygwin.pyi b/stubs/setuptools/distutils/compilers/C/cygwin.pyi new file mode 100644 index 000000000000..9b7a9d9e0ca0 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/cygwin.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.cygwin import * diff --git a/stubs/setuptools/distutils/compilers/C/errors.pyi b/stubs/setuptools/distutils/compilers/C/errors.pyi new file mode 100644 index 000000000000..6cc2192bd587 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/errors.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.errors import * diff --git a/stubs/setuptools/distutils/compilers/C/msvc.pyi b/stubs/setuptools/distutils/compilers/C/msvc.pyi new file mode 100644 index 000000000000..733c0ce32c3b --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/msvc.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.msvc import * diff --git a/stubs/setuptools/distutils/compilers/C/unix.pyi b/stubs/setuptools/distutils/compilers/C/unix.pyi new file mode 100644 index 000000000000..d4dbeff6b110 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/unix.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.unix import * diff --git a/stubs/setuptools/distutils/compilers/C/zos.pyi b/stubs/setuptools/distutils/compilers/C/zos.pyi new file mode 100644 index 000000000000..921cd46b47ef --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/zos.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.zos import * diff --git a/stubs/setuptools/distutils/compilers/errors.pyi b/stubs/setuptools/distutils/compilers/errors.pyi new file mode 100644 index 000000000000..ab573602be36 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/errors.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.errors import * diff --git a/stubs/setuptools/distutils/compilers/platform/detect.pyi b/stubs/setuptools/distutils/compilers/platform/detect.pyi new file mode 100644 index 000000000000..aaf32add0a26 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/platform/detect.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.platform.detect import * diff --git a/stubs/setuptools/distutils/compilers/platform/macos.pyi b/stubs/setuptools/distutils/compilers/platform/macos.pyi new file mode 100644 index 000000000000..5d87f38778dd --- /dev/null +++ b/stubs/setuptools/distutils/compilers/platform/macos.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.platform.macos import * diff --git a/stubs/setuptools/distutils/cygwinccompiler.pyi b/stubs/setuptools/distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..1784f31d60fc --- /dev/null +++ b/stubs/setuptools/distutils/cygwinccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils.cygwinccompiler import * diff --git a/stubs/setuptools/distutils/dep_util.pyi b/stubs/setuptools/distutils/dep_util.pyi new file mode 100644 index 000000000000..22008d8cf747 --- /dev/null +++ b/stubs/setuptools/distutils/dep_util.pyi @@ -0,0 +1 @@ +from setuptools._distutils.dep_util import * diff --git a/stubs/setuptools/distutils/dist.pyi b/stubs/setuptools/distutils/dist.pyi new file mode 100644 index 000000000000..b6cdf2bd9f2a --- /dev/null +++ b/stubs/setuptools/distutils/dist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.dist import * diff --git a/stubs/setuptools/distutils/errors.pyi b/stubs/setuptools/distutils/errors.pyi new file mode 100644 index 000000000000..28a21bf13e2a --- /dev/null +++ b/stubs/setuptools/distutils/errors.pyi @@ -0,0 +1 @@ +from setuptools._distutils.errors import * diff --git a/stubs/setuptools/distutils/extension.pyi b/stubs/setuptools/distutils/extension.pyi new file mode 100644 index 000000000000..95b5cf764dfd --- /dev/null +++ b/stubs/setuptools/distutils/extension.pyi @@ -0,0 +1 @@ +from setuptools._distutils.extension import * diff --git a/stubs/setuptools/distutils/filelist.pyi b/stubs/setuptools/distutils/filelist.pyi new file mode 100644 index 000000000000..fe746bbdcfe4 --- /dev/null +++ b/stubs/setuptools/distutils/filelist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.filelist import * diff --git a/stubs/setuptools/distutils/spawn.pyi b/stubs/setuptools/distutils/spawn.pyi new file mode 100644 index 000000000000..4432100c0024 --- /dev/null +++ b/stubs/setuptools/distutils/spawn.pyi @@ -0,0 +1 @@ +from setuptools._distutils.spawn import * diff --git a/stubs/setuptools/distutils/sysconfig.pyi b/stubs/setuptools/distutils/sysconfig.pyi new file mode 100644 index 000000000000..9b50b49872bc --- /dev/null +++ b/stubs/setuptools/distutils/sysconfig.pyi @@ -0,0 +1 @@ +from setuptools._distutils.sysconfig import * diff --git a/stubs/setuptools/distutils/unixccompiler.pyi b/stubs/setuptools/distutils/unixccompiler.pyi new file mode 100644 index 000000000000..fcbf9e199041 --- /dev/null +++ b/stubs/setuptools/distutils/unixccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils.unixccompiler import * diff --git a/stubs/setuptools/distutils/util.pyi b/stubs/setuptools/distutils/util.pyi new file mode 100644 index 000000000000..b5723b79d9ff --- /dev/null +++ b/stubs/setuptools/distutils/util.pyi @@ -0,0 +1 @@ +from setuptools._distutils.util import * diff --git a/stubs/setuptools/distutils/version.pyi b/stubs/setuptools/distutils/version.pyi new file mode 100644 index 000000000000..1cac35f20653 --- /dev/null +++ b/stubs/setuptools/distutils/version.pyi @@ -0,0 +1 @@ +from setuptools._distutils.version import * diff --git a/stubs/setuptools/distutils/zosccompiler.pyi b/stubs/setuptools/distutils/zosccompiler.pyi new file mode 100644 index 000000000000..b69c6320e43b --- /dev/null +++ b/stubs/setuptools/distutils/zosccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils.zosccompiler import * diff --git a/stubs/setuptools/pkg_resources/__init__.pyi b/stubs/setuptools/pkg_resources/__init__.pyi deleted file mode 100644 index 9f121f3340fc..000000000000 --- a/stubs/setuptools/pkg_resources/__init__.pyi +++ /dev/null @@ -1,270 +0,0 @@ -import importlib.abc -import types -import zipimport -from abc import ABCMeta -from typing import IO, Any, Callable, Generator, Iterable, Optional, Sequence, Tuple, TypeVar, Union, overload - -LegacyVersion = Any # from packaging.version -Version = Any # from packaging.version - -_T = TypeVar("_T") -_NestedStr = Union[str, Iterable[Union[str, Iterable[Any]]]] -_InstallerType = Callable[[Requirement], Optional[Distribution]] -_EPDistType = Union[Distribution, Requirement, str] -_MetadataType = Optional[IResourceProvider] -_PkgReqType = Union[str, Requirement] -_DistFinderType = Callable[[_Importer, str, bool], Generator[Distribution, None, None]] -_NSHandlerType = Callable[[_Importer, str, str, types.ModuleType], str] - -def declare_namespace(name: str) -> None: ... -def fixup_namespace_packages(path_item: str) -> None: ... - -class WorkingSet: - entries: list[str] - def __init__(self, entries: Iterable[str] | None = ...) -> None: ... - def require(self, *requirements: _NestedStr) -> Sequence[Distribution]: ... - def run_script(self, requires: str, script_name: str) -> None: ... - def iter_entry_points(self, group: str, name: str | None = ...) -> Generator[EntryPoint, None, None]: ... - def add_entry(self, entry: str) -> None: ... - def __contains__(self, dist: Distribution) -> bool: ... - def __iter__(self) -> Generator[Distribution, None, None]: ... - def find(self, req: Requirement) -> Distribution | None: ... - def resolve( - self, requirements: Iterable[Requirement], env: Environment | None = ..., installer: _InstallerType | None = ... - ) -> list[Distribution]: ... - def add(self, dist: Distribution, entry: str | None = ..., insert: bool = ..., replace: bool = ...) -> None: ... - def subscribe(self, callback: Callable[[Distribution], None]) -> None: ... - def find_plugins( - self, plugin_env: Environment, full_env: Environment | None = ..., fallback: bool = ... - ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ... - -working_set: WorkingSet = ... - -require = working_set.require -run_script = working_set.run_script -iter_entry_points = working_set.iter_entry_points -add_activation_listener = working_set.subscribe - -class Environment: - def __init__(self, search_path: Sequence[str] | None = ..., platform: str | None = ..., python: str | None = ...) -> None: ... - def __getitem__(self, project_name: str) -> list[Distribution]: ... - def __iter__(self) -> Generator[str, None, None]: ... - def add(self, dist: Distribution) -> None: ... - def remove(self, dist: Distribution) -> None: ... - def can_add(self, dist: Distribution) -> bool: ... - def __add__(self, other: Distribution | Environment) -> Environment: ... - def __iadd__(self, other: Distribution | Environment) -> Environment: ... - @overload - def best_match(self, req: Requirement, working_set: WorkingSet) -> Distribution: ... - @overload - def best_match(self, req: Requirement, working_set: WorkingSet, installer: Callable[[Requirement], _T] = ...) -> _T: ... - @overload - def obtain(self, requirement: Requirement) -> None: ... - @overload - def obtain(self, requirement: Requirement, installer: Callable[[Requirement], _T] = ...) -> _T: ... - def scan(self, search_path: Sequence[str] | None = ...) -> None: ... - -def parse_requirements(strs: str | Iterable[str]) -> Generator[Requirement, None, None]: ... - -class Requirement: - unsafe_name: str - project_name: str - key: str - extras: Tuple[str, ...] - specs: list[tuple[str, str]] - # TODO: change this to packaging.markers.Marker | None once we can import - # packaging.markers - marker: Any | None - @staticmethod - def parse(s: str | Iterable[str]) -> Requirement: ... - def __contains__(self, item: Distribution | str | Tuple[str, ...]) -> bool: ... - def __eq__(self, other_requirement: Any) -> bool: ... - -def load_entry_point(dist: _EPDistType, group: str, name: str) -> Any: ... -def get_entry_info(dist: _EPDistType, group: str, name: str) -> EntryPoint | None: ... -@overload -def get_entry_map(dist: _EPDistType) -> dict[str, dict[str, EntryPoint]]: ... -@overload -def get_entry_map(dist: _EPDistType, group: str) -> dict[str, EntryPoint]: ... - -class EntryPoint: - name: str - module_name: str - attrs: Tuple[str, ...] - extras: Tuple[str, ...] - dist: Distribution | None - def __init__( - self, - name: str, - module_name: str, - attrs: Tuple[str, ...] = ..., - extras: Tuple[str, ...] = ..., - dist: Distribution | None = ..., - ) -> None: ... - @classmethod - def parse(cls, src: str, dist: Distribution | None = ...) -> EntryPoint: ... - @classmethod - def parse_group(cls, group: str, lines: str | Sequence[str], dist: Distribution | None = ...) -> dict[str, EntryPoint]: ... - @classmethod - def parse_map( - cls, data: dict[str, str | Sequence[str]] | str | Sequence[str], dist: Distribution | None = ... - ) -> dict[str, EntryPoint]: ... - def load(self, require: bool = ..., env: Environment | None = ..., installer: _InstallerType | None = ...) -> Any: ... - def require(self, env: Environment | None = ..., installer: _InstallerType | None = ...) -> None: ... - def resolve(self) -> Any: ... - -def find_distributions(path_item: str, only: bool = ...) -> Generator[Distribution, None, None]: ... -def get_distribution(dist: Requirement | str | Distribution) -> Distribution: ... - -class Distribution(IResourceProvider, IMetadataProvider): - PKG_INFO: str - location: str - project_name: str - key: str - extras: list[str] - version: str - parsed_version: Tuple[str, ...] - py_version: str - platform: str | None - precedence: int - def __init__( - self, - location: str | None = ..., - metadata: _MetadataType = ..., - project_name: str | None = ..., - version: str | None = ..., - py_version: str = ..., - platform: str | None = ..., - precedence: int = ..., - ) -> None: ... - @classmethod - def from_location( - cls, location: str, basename: str, metadata: _MetadataType = ..., **kw: str | None | int - ) -> Distribution: ... - @classmethod - def from_filename(cls, filename: str, metadata: _MetadataType = ..., **kw: str | None | int) -> Distribution: ... - def activate(self, path: list[str] | None = ...) -> None: ... - def as_requirement(self) -> Requirement: ... - def requires(self, extras: Tuple[str, ...] = ...) -> list[Requirement]: ... - def clone(self, **kw: str | int | None) -> Requirement: ... - def egg_name(self) -> str: ... - def __cmp__(self, other: Any) -> bool: ... - def get_entry_info(self, group: str, name: str) -> EntryPoint | None: ... - @overload - def get_entry_map(self) -> dict[str, dict[str, EntryPoint]]: ... - @overload - def get_entry_map(self, group: str) -> dict[str, EntryPoint]: ... - def load_entry_point(self, group: str, name: str) -> Any: ... - -EGG_DIST: int -BINARY_DIST: int -SOURCE_DIST: int -CHECKOUT_DIST: int -DEVELOP_DIST: int - -def resource_exists(package_or_requirement: _PkgReqType, resource_name: str) -> bool: ... -def resource_stream(package_or_requirement: _PkgReqType, resource_name: str) -> IO[bytes]: ... -def resource_string(package_or_requirement: _PkgReqType, resource_name: str) -> bytes: ... -def resource_isdir(package_or_requirement: _PkgReqType, resource_name: str) -> bool: ... -def resource_listdir(package_or_requirement: _PkgReqType, resource_name: str) -> list[str]: ... -def resource_filename(package_or_requirement: _PkgReqType, resource_name: str) -> str: ... -def set_extraction_path(path: str) -> None: ... -def cleanup_resources(force: bool = ...) -> list[str]: ... - -class IResourceManager: - def resource_exists(self, package_or_requirement: _PkgReqType, resource_name: str) -> bool: ... - def resource_stream(self, package_or_requirement: _PkgReqType, resource_name: str) -> IO[bytes]: ... - def resource_string(self, package_or_requirement: _PkgReqType, resource_name: str) -> bytes: ... - def resource_isdir(self, package_or_requirement: _PkgReqType, resource_name: str) -> bool: ... - def resource_listdir(self, package_or_requirement: _PkgReqType, resource_name: str) -> list[str]: ... - def resource_filename(self, package_or_requirement: _PkgReqType, resource_name: str) -> str: ... - def set_extraction_path(self, path: str) -> None: ... - def cleanup_resources(self, force: bool = ...) -> list[str]: ... - def get_cache_path(self, archive_name: str, names: Iterable[str] = ...) -> str: ... - def extraction_error(self) -> None: ... - def postprocess(self, tempname: str, filename: str) -> None: ... - -@overload -def get_provider(package_or_requirement: str) -> IResourceProvider: ... -@overload -def get_provider(package_or_requirement: Requirement) -> Distribution: ... - -class IMetadataProvider: - def has_metadata(self, name: str) -> bool: ... - def metadata_isdir(self, name: str) -> bool: ... - def metadata_listdir(self, name: str) -> list[str]: ... - def get_metadata(self, name: str) -> str: ... - def get_metadata_lines(self, name: str) -> Generator[str, None, None]: ... - def run_script(self, script_name: str, namespace: dict[str, Any]) -> None: ... - -class ResolutionError(Exception): ... - -class DistributionNotFound(ResolutionError): - @property - def req(self) -> Requirement: ... - @property - def requirers(self) -> set[str]: ... - @property - def requirers_str(self) -> str: ... - def report(self) -> str: ... - -class VersionConflict(ResolutionError): - @property - def dist(self) -> Any: ... - @property - def req(self) -> Any: ... - def report(self) -> str: ... - def with_context(self, required_by: set[Distribution | str]) -> VersionConflict: ... - -class ContextualVersionConflict(VersionConflict): - @property - def required_by(self) -> set[Distribution | str]: ... - -class UnknownExtra(ResolutionError): ... - -class ExtractionError(Exception): - manager: IResourceManager - cache_path: str - original_error: Exception - -class _Importer(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader, metaclass=ABCMeta): ... - -def register_finder(importer_type: type, distribution_finder: _DistFinderType) -> None: ... -def register_loader_type(loader_type: type, provider_factory: Callable[[types.ModuleType], IResourceProvider]) -> None: ... -def register_namespace_handler(importer_type: type, namespace_handler: _NSHandlerType) -> None: ... - -class IResourceProvider(IMetadataProvider): ... -class NullProvider: ... -class EggProvider(NullProvider): ... -class DefaultProvider(EggProvider): ... - -class PathMetadata(DefaultProvider, IResourceProvider): - def __init__(self, path: str, egg_info: str) -> None: ... - -class ZipProvider(EggProvider): ... - -class EggMetadata(ZipProvider, IResourceProvider): - def __init__(self, zipimporter: zipimport.zipimporter) -> None: ... - -class EmptyProvider(NullProvider): ... - -empty_provider: EmptyProvider - -class FileMetadata(EmptyProvider, IResourceProvider): - def __init__(self, path_to_pkg_info: str) -> None: ... - -def parse_version(v: str) -> Version | LegacyVersion: ... -def yield_lines(strs: _NestedStr) -> Generator[str, None, None]: ... -def split_sections(strs: _NestedStr) -> Generator[tuple[str | None, str], None, None]: ... -def safe_name(name: str) -> str: ... -def safe_version(version: str) -> str: ... -def safe_extra(extra: str) -> str: ... -def to_filename(name_or_version: str) -> str: ... -def get_build_platform() -> str: ... -def get_platform() -> str: ... -def get_supported_platform() -> str: ... -def compatible_platforms(provided: str | None, required: str | None) -> bool: ... -def get_default_cache() -> str: ... -def get_importer(path_item: str) -> _Importer: ... -def ensure_directory(path: str) -> None: ... -def normalize_path(filename: str) -> str: ... diff --git a/stubs/setuptools/pkg_resources/py31compat.pyi b/stubs/setuptools/pkg_resources/py31compat.pyi deleted file mode 100644 index 162da65e0e67..000000000000 --- a/stubs/setuptools/pkg_resources/py31compat.pyi +++ /dev/null @@ -1,5 +0,0 @@ -import os - -needs_makedirs: bool - -makedirs = os.makedirs diff --git a/stubs/setuptools/setuptools/__init__.pyi b/stubs/setuptools/setuptools/__init__.pyi index 25bd93d13671..e89fce7ebdc6 100644 --- a/stubs/setuptools/setuptools/__init__.pyi +++ b/stubs/setuptools/setuptools/__init__.pyi @@ -1,72 +1,274 @@ +from _typeshed import Incomplete, StrPath from abc import abstractmethod -from collections.abc import Iterable, Mapping -from distutils.core import Command as _Command -from typing import Any, Type +from collections.abc import ItemsView, Iterable, Mapping, Sequence +from typing import Any, Literal, Protocol, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, NotRequired -from setuptools._deprecation_warning import SetuptoolsDeprecationWarning as SetuptoolsDeprecationWarning -from setuptools.depends import Require as Require -from setuptools.dist import Distribution as Distribution -from setuptools.extension import Extension as Extension +from ._distutils.cmd import Command as _Command +from ._distutils.dist import Distribution as _Distribution +from ._distutils.extension import Extension as _Extension +from .command.alias import alias +from .command.bdist_egg import bdist_egg +from .command.bdist_rpm import bdist_rpm +from .command.bdist_wheel import bdist_wheel +from .command.build import build +from .command.build_clib import build_clib +from .command.build_ext import build_ext +from .command.build_py import build_py +from .command.develop import develop +from .command.dist_info import dist_info +from .command.easy_install import easy_install +from .command.editable_wheel import editable_wheel +from .command.egg_info import egg_info +from .command.install import install +from .command.install_egg_info import install_egg_info +from .command.install_lib import install_lib +from .command.install_scripts import install_scripts +from .command.rotate import rotate +from .command.saveopts import saveopts +from .command.sdist import sdist +from .command.setopt import setopt +from .depends import Require as Require +from .discovery import _Finder +from .dist import Distribution as Distribution +from .extension import Extension as Extension +from .warnings import SetuptoolsDeprecationWarning as SetuptoolsDeprecationWarning + +_CommandT = TypeVar("_CommandT", bound=_Command) +_DistributionT = TypeVar("_DistributionT", bound=_Distribution, default=Distribution) +_KT = TypeVar("_KT") +_VT_co = TypeVar("_VT_co", covariant=True) + +__all__ = [ + "setup", + "Distribution", + "Command", + "Extension", + "Require", + "SetuptoolsDeprecationWarning", + "find_packages", + "find_namespace_packages", +] __version__: str -class PackageFinder: - @classmethod - def find(cls, where: str = ..., exclude: Iterable[str] = ..., include: Iterable[str] = ...) -> list[str]: ... +# We need any Command subclass to be valid +# Any: pyright would accept using covariance in __setitem__, but mypy won't let a dict be assignable to this protocol +# This is unsound, but it's a quirk of setuptools' internals +@type_check_only +class _DictLike(Protocol[_KT, _VT_co]): + # See note about using _VT_co instead of Any + def get(self, key: _KT, default: Any | None = None, /) -> _VT_co | None: ... + def items(self) -> ItemsView[_KT, _VT_co]: ... + def keys(self) -> Iterable[_KT]: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + def __contains__(self, x: object, /) -> bool: ... + +@type_check_only +class _MutableDictLike(_DictLike[_KT, _VT_co], Protocol): + # See note about using _VT_co instead of Any + def __setitem__(self, key: _KT, value: Any, /) -> None: ... + def setdefault(self, key: _KT, default: Any, /) -> _VT_co: ... -class PEP420PackageFinder(PackageFinder): ... +@type_check_only +class _BuildInfo(TypedDict): + sources: list[str] | tuple[str, ...] + obj_deps: NotRequired[dict[str, list[str] | tuple[str, ...]]] + macros: NotRequired[list[tuple[str] | tuple[str, str | None]]] + include_dirs: NotRequired[list[str]] + cflags: NotRequired[list[str]] -find_packages = PackageFinder.find -find_namespace_packages = PEP420PackageFinder.find +find_packages = _Finder.find +find_namespace_packages = _Finder.find def setup( *, - name: str = ..., - version: str = ..., - description: str = ..., - long_description: str = ..., - author: str = ..., - author_email: str = ..., - maintainer: str = ..., - maintainer_email: str = ..., - url: str = ..., - download_url: str = ..., - packages: list[str] = ..., - py_modules: list[str] = ..., - scripts: list[str] = ..., - ext_modules: list[Extension] = ..., - classifiers: list[str] = ..., - distclass: Type[Distribution] = ..., - script_name: str = ..., - script_args: list[str] = ..., - options: Mapping[str, Any] = ..., - license: str = ..., - keywords: list[str] | str = ..., - platforms: list[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., - data_files: list[tuple[str, list[str]]] = ..., - package_dir: Mapping[str, str] = ..., - obsoletes: list[str] = ..., - provides: list[str] = ..., - requires: list[str] = ..., - command_packages: list[str] = ..., - command_options: Mapping[str, Mapping[str, tuple[Any, Any]]] = ..., - package_data: Mapping[str, list[str]] = ..., - include_package_data: bool = ..., - libraries: list[str] = ..., - headers: list[str] = ..., - ext_package: str = ..., - include_dirs: list[str] = ..., - password: str = ..., - fullname: str = ..., + # Attributes from distutils.dist.DistributionMetadata.set_* + # These take priority over attributes from distutils.dist.DistributionMetadata.__init__ + keywords: str | Iterable[str] = ..., + platforms: str | Iterable[str] = ..., + classifiers: str | Iterable[str] = ..., + requires: Iterable[str] = ..., + provides: Iterable[str] = ..., + obsoletes: Iterable[str] = ..., + # Attributes from distutils.dist.DistributionMetadata.__init__ + # These take priority over attributes from distutils.dist.Distribution.__init__ + name: str | None = None, + version: str | None = None, + author: str | None = None, + author_email: str | None = None, + maintainer: str | None = None, + maintainer_email: str | None = None, + url: str | None = None, + license: str | None = None, + description: str | None = None, + long_description: str | None = None, + download_url: str | None = None, + # Attributes from distutils.dist.Distribution.__init__ (except self.metadata) + # These take priority over attributes from distutils.dist.Distribution.display_option_names + verbose: bool = True, + help: bool = False, + cmdclass: _MutableDictLike[str, type[_Command]] = {}, + command_packages: str | list[str] | None = None, + script_name: StrPath | None = ..., # default is actually set in distutils.core.setup + script_args: list[str] | None = ..., # default is actually set in distutils.core.setup + command_options: _MutableDictLike[str, _DictLike[str, tuple[str, str]]] = {}, + packages: list[str] | None = None, + package_dir: Mapping[str, str] | None = None, + py_modules: list[str] | None = None, + libraries: list[tuple[str, _BuildInfo]] | None = None, + headers: list[str] | None = None, + ext_modules: Sequence[_Extension] | None = None, + ext_package: str | None = None, + include_dirs: list[str] | None = None, + extra_path: Never = ..., # Deprecated + scripts: list[str] | None = None, + data_files: list[tuple[str, Sequence[str]]] | None = None, + password: str = "", + command_obj: _MutableDictLike[str, _Command] = {}, + have_run: _MutableDictLike[str, bool] = {}, + # kwargs used directly in distutils.dist.Distribution.__init__ + options: Mapping[str, Mapping[str, str]] | None = None, + licence: Never = ..., # Deprecated + # Attributes from distutils.dist.Distribution.display_option_names + # (this can more easily be copied from the `if TYPE_CHECKING` block) + help_commands: bool = False, + fullname: str | Literal[False] = False, + contact: str | Literal[False] = False, + contact_email: str | Literal[False] = False, + # kwargs used directly in setuptools.dist.Distribution.__init__ + # and attributes from setuptools.dist.Distribution.__init__ + package_data: _DictLike[str, list[str]] = {}, + dist_files: list[tuple[str, str, str]] = [], + include_package_data: bool | None = None, + exclude_package_data: _DictLike[str, list[str]] | None = None, + src_root: str | None = None, + dependency_links: list[str] = [], + setup_requires: list[str] = [], + # From Distribution._DISTUTILS_UNSUPPORTED_METADATA set in Distribution._set_metadata_defaults + long_description_content_type: str | None = None, + project_urls: _DictLike[Incomplete, Incomplete] = {}, + provides_extras: _MutableDictLike[Incomplete, Incomplete] = {}, + license_expression: str | None = None, + license_file: Never = ..., # Deprecated + license_files: Iterable[str] | None = None, + install_requires: str | Iterable[str] = [], + extras_require: _DictLike[Incomplete, Incomplete] = {}, + # kwargs used directly in distutils.core.setup + distclass: type[_DistributionT] = Distribution, # type: ignore[assignment] # noqa: Y011 # ty:ignore[invalid-parameter-default] + # Custom Distributions could accept more params **attrs: Any, -) -> None: ... +) -> _DistributionT: ... class Command(_Command): command_consumes_arguments: bool + distribution: Distribution + dry_run: bool + # Any: Dynamic command subclass attributes def __init__(self, dist: Distribution, **kw: Any) -> None: ... - def ensure_string_list(self, option: str | list[str]) -> None: ... - def reinitialize_command(self, command: _Command | str, reinit_subcommands: int = ..., **kw: Any) -> _Command: ... + + # Note: Commands that setuptools doesn't re-expose are considered deprecated (they must be imported from distutils directly) + # So we're not listing them here. This list comes directly from the setuptools/command folder. Minus the test command. + @overload # type: ignore[override] + def get_finalized_command(self, command: Literal["alias"], create: bool | Literal[0, 1] = 1) -> alias: ... + @overload + def get_finalized_command(self, command: Literal["bdist_egg"], create: bool | Literal[0, 1] = 1) -> bdist_egg: ... + @overload + def get_finalized_command(self, command: Literal["bdist_rpm"], create: bool | Literal[0, 1] = 1) -> bdist_rpm: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["bdist_wheel"], create: bool | Literal[0, 1] = 1) -> bdist_wheel: ... + @overload + def get_finalized_command(self, command: Literal["build"], create: bool | Literal[0, 1] = 1) -> build: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["build_clib"], create: bool | Literal[0, 1] = 1) -> build_clib: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["build_ext"], create: bool | Literal[0, 1] = 1) -> build_ext: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["build_py"], create: bool | Literal[0, 1] = 1) -> build_py: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["develop"], create: bool | Literal[0, 1] = 1) -> develop: ... + @overload + def get_finalized_command(self, command: Literal["dist_info"], create: bool | Literal[0, 1] = 1) -> dist_info: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["easy_install"], create: bool | Literal[0, 1] = 1) -> easy_install: ... + @overload + def get_finalized_command(self, command: Literal["editable_wheel"], create: bool | Literal[0, 1] = 1) -> editable_wheel: ... + @overload + def get_finalized_command(self, command: Literal["egg_info"], create: bool | Literal[0, 1] = 1) -> egg_info: ... + @overload + def get_finalized_command(self, command: Literal["install"], create: bool | Literal[0, 1] = 1) -> install: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command( + self, command: Literal["install_egg_info"], create: bool | Literal[0, 1] = 1 + ) -> install_egg_info: ... + @overload + def get_finalized_command(self, command: Literal["install_lib"], create: bool | Literal[0, 1] = 1) -> install_lib: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["install_scripts"], create: bool | Literal[0, 1] = 1) -> install_scripts: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["rotate"], create: bool | Literal[0, 1] = 1) -> rotate: ... + @overload + def get_finalized_command(self, command: Literal["saveopts"], create: bool | Literal[0, 1] = 1) -> saveopts: ... + @overload + def get_finalized_command(self, command: Literal["sdist"], create: bool | Literal[0, 1] = 1) -> sdist: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["setopt"], create: bool | Literal[0, 1] = 1) -> setopt: ... + @overload + def get_finalized_command(self, command: str, create: bool | Literal[0, 1] = 1) -> Command: ... + + @overload # type: ignore[override] # Extra **kw param + def reinitialize_command(self, command: Literal["alias"], reinit_subcommands: bool = False, **kw) -> alias: ... + @overload + def reinitialize_command(self, command: Literal["bdist_egg"], reinit_subcommands: bool = False, **kw) -> bdist_egg: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool = False, **kw) -> bdist_rpm: ... + @overload + def reinitialize_command(self, command: Literal["bdist_wheel"], reinit_subcommands: bool = False, **kw) -> bdist_wheel: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool = False, **kw) -> build: ... + @overload + def reinitialize_command(self, command: Literal["build_clib"], reinit_subcommands: bool = False, **kw) -> build_clib: ... + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool = False, **kw) -> build_ext: ... + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool = False, **kw) -> build_py: ... + @overload + def reinitialize_command(self, command: Literal["develop"], reinit_subcommands: bool = False, **kw) -> develop: ... + @overload + def reinitialize_command(self, command: Literal["dist_info"], reinit_subcommands: bool = False, **kw) -> dist_info: ... + @overload + def reinitialize_command(self, command: Literal["easy_install"], reinit_subcommands: bool = False, **kw) -> easy_install: ... + @overload + def reinitialize_command( + self, command: Literal["editable_wheel"], reinit_subcommands: bool = False, **kw + ) -> editable_wheel: ... + @overload + def reinitialize_command(self, command: Literal["egg_info"], reinit_subcommands: bool = False, **kw) -> egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool = False, **kw) -> install: ... + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool = False, **kw + ) -> install_egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install_lib"], reinit_subcommands: bool = False, **kw) -> install_lib: ... + @overload + def reinitialize_command( + self, command: Literal["install_scripts"], reinit_subcommands: bool = False, **kw + ) -> install_scripts: ... + @overload + def reinitialize_command(self, command: Literal["rotate"], reinit_subcommands: bool = False, **kw) -> rotate: ... + @overload + def reinitialize_command(self, command: Literal["saveopts"], reinit_subcommands: bool = False, **kw) -> saveopts: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool = False, **kw) -> sdist: ... + @overload + def reinitialize_command(self, command: Literal["setopt"], reinit_subcommands: bool = False, **kw) -> setopt: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False, **kw) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False, **kw) -> _CommandT: ... + @abstractmethod def initialize_options(self) -> None: ... @abstractmethod diff --git a/stubs/setuptools/setuptools/_deprecation_warning.pyi b/stubs/setuptools/setuptools/_deprecation_warning.pyi deleted file mode 100644 index 43a7220c6659..000000000000 --- a/stubs/setuptools/setuptools/_deprecation_warning.pyi +++ /dev/null @@ -1 +0,0 @@ -class SetuptoolsDeprecationWarning(Warning): ... diff --git a/stubs/setuptools/setuptools/_distutils/__init__.pyi b/stubs/setuptools/setuptools/_distutils/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/setuptools/setuptools/_distutils/_modified.pyi b/stubs/setuptools/setuptools/_distutils/_modified.pyi new file mode 100644 index 000000000000..b64061d5c4b2 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/_modified.pyi @@ -0,0 +1,17 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterable +from typing import Literal, TypeVar + +_SourcesT = TypeVar("_SourcesT", bound=StrOrBytesPath) +_TargetsT = TypeVar("_TargetsT", bound=StrOrBytesPath) + +def newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool: ... +def newer_pairwise( + sources: Iterable[_SourcesT], targets: Iterable[_TargetsT], newer: Callable[[_SourcesT, _TargetsT], bool] = ... +) -> tuple[list[_SourcesT], list[_TargetsT]]: ... +def newer_group( + sources: Iterable[StrOrBytesPath], target: StrOrBytesPath, missing: Literal["error", "ignore", "newer"] = "error" +) -> bool: ... +def newer_pairwise_group( + sources: Iterable[_SourcesT], targets: Iterable[_TargetsT], *, newer: Callable[[_SourcesT, _TargetsT], bool] = ... +) -> tuple[list[_SourcesT], list[_TargetsT]]: ... diff --git a/stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi b/stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..8471ccab28fa --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi @@ -0,0 +1,5 @@ +from .compilers.C import msvc + +__all__ = ["MSVCCompiler"] + +MSVCCompiler = msvc.Compiler diff --git a/stubs/setuptools/setuptools/_distutils/archive_util.pyi b/stubs/setuptools/setuptools/_distutils/archive_util.pyi new file mode 100644 index 000000000000..2c6dae867a6b --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/archive_util.pyi @@ -0,0 +1,33 @@ +from _typeshed import StrOrBytesPath, StrPath +from typing import Literal, overload + +@overload +def make_archive( + base_name: str, + format: str, + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... +@overload +def make_archive( + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... + +def make_tarball( + base_name: str, + base_dir: StrPath, + compress: Literal["gzip", "bzip2", "xz"] | None = "gzip", + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... +def make_zipfile(base_name: str, base_dir: StrPath, verbose: bool = False) -> str: ... diff --git a/stubs/setuptools/setuptools/_distutils/ccompiler.pyi b/stubs/setuptools/setuptools/_distutils/ccompiler.pyi new file mode 100644 index 000000000000..f63dfd6e9ec4 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/ccompiler.pyi @@ -0,0 +1,17 @@ +from .compilers.C import base +from .compilers.C.base import gen_lib_options, gen_preprocess_options, get_default_compiler, new_compiler +from .compilers.C.errors import CompileError, LinkError + +__all__ = [ + "CompileError", + "LinkError", + "gen_lib_options", + "gen_preprocess_options", + "get_default_compiler", + "new_compiler", + "show_compilers", +] + +CCompiler = base.Compiler + +def show_compilers() -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/cmd.pyi b/stubs/setuptools/setuptools/_distutils/cmd.pyi new file mode 100644 index 000000000000..272bf0ba7c0c --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/cmd.pyi @@ -0,0 +1,128 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath, Unused +from abc import abstractmethod +from collections.abc import Callable, Sequence +from typing import Any, ClassVar, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack + +from .dist import Distribution + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) +_CommandT = TypeVar("_CommandT", bound=Command) +_Ts = TypeVarTuple("_Ts") + +class Command: + distribution: Distribution + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] + user_options: ClassVar[ + # Specifying both because list is invariant. Avoids mypy override assignment issues + list[tuple[str, str, str]] + | list[tuple[str, str | None, str]] + ] + verbose: bool + force: bool | None + help: bool + finalized: bool + def __init__(self, dist: Distribution) -> None: ... + def ensure_finalized(self) -> None: ... + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + def announce(self, msg: str, level: int = 10) -> None: ... + def debug_print(self, msg: str) -> None: ... + def ensure_string(self, option: str, default: str | None = None) -> None: ... + def ensure_string_list(self, option: str) -> None: ... + def ensure_filename(self, option: str) -> None: ... + def ensure_dirname(self, option: str) -> None: ... + def get_command_name(self) -> str: ... + def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: ... + # NOTE: Because this is private setuptools implementation and we don't re-expose all commands here, + # we're not overloading each and every command possibility. + def get_finalized_command(self, command: str, create: bool = True) -> Command: ... + + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def run_command(self, command: str) -> None: ... + def get_sub_commands(self) -> list[str]: ... + def warn(self, msg: str) -> None: ... + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def copy_file( + self, + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_StrPathT | str, bool]: ... + @overload + def copy_file( + self, + infile: BytesPath, + outfile: _BytesPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_BytesPathT | bytes, bool]: ... + + def copy_tree( + self, + infile: StrPath, + outfile: str, + preserve_mode: bool = True, + preserve_times: bool = True, + preserve_symlinks: bool = False, + level: Unused = 1, + ) -> list[str]: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ... + + def spawn(self, cmd: Sequence[StrOrBytesPath], search_path: Unused = True, level: Unused = 1) -> None: ... + + @overload + def make_archive( + self, + base_name: str, + format: str, + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + @overload + def make_archive( + self, + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + + def make_file( + self, + infiles: str | list[str] | tuple[str, ...], + outfile: StrOrBytesPath, + func: Callable[[Unpack[_Ts]], Unused], + args: tuple[Unpack[_Ts]], + exec_msg: str | None = None, + skip_msg: str | None = None, + level: Unused = 1, + ) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/__init__.pyi b/stubs/setuptools/setuptools/_distutils/command/__init__.pyi new file mode 100644 index 000000000000..f6b93d32846a --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/__init__.pyi @@ -0,0 +1,39 @@ +from . import ( + bdist as bdist, + bdist_rpm as bdist_rpm, + build as build, + build_clib as build_clib, + build_ext as build_ext, + build_py as build_py, + # build_scripts as build_scripts, + # check as check, + # clean as clean, + install as install, + install_data as install_data, + # install_headers as install_headers, + install_lib as install_lib, + install_scripts as install_scripts, + sdist as sdist, +) + +# Commented out commands are not stubbed. +# (Many of these may be implementation details, +# but they can be added if people ask for them) +__all__ = [ + "build", + "build_py", + "build_ext", + "build_clib", + # "build_scripts", + # "clean", + "install", + "install_lib", + # "install_headers", + "install_scripts", + "install_data", + "sdist", + "bdist", + # "bdist_dumb", + "bdist_rpm", + # "check", +] diff --git a/stubs/setuptools/setuptools/_distutils/command/bdist.pyi b/stubs/setuptools/setuptools/_distutils/command/bdist.pyi new file mode 100644 index 000000000000..4c95b17011b1 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/bdist.pyi @@ -0,0 +1,26 @@ +from _typeshed import Unused +from collections.abc import Callable +from typing import ClassVar +from typing_extensions import deprecated + +from ..cmd import Command + +def show_formats() -> None: ... + +class ListCompat(dict[str, tuple[str, str]]): + @deprecated("format_commands is now a dict. append is deprecated") + def append(self, item: Unused) -> None: ... + +class bdist(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + no_format_option: ClassVar[tuple[str, ...]] + default_format: ClassVar[dict[str, str]] + format_commands: ClassVar[ListCompat] + format_command = format_commands # pyrefly: ignore [unknown-name] + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi b/stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..fed7833ed5e9 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class bdist_rpm(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + bdist_base: Incomplete + rpm_base: Incomplete + dist_dir: Incomplete + python: Incomplete + fix_python: Incomplete + spec_only: Incomplete + binary_only: Incomplete + source_only: Incomplete + use_bzip2: Incomplete + distribution_name: Incomplete + group: Incomplete + release: Incomplete + serial: Incomplete + vendor: Incomplete + packager: Incomplete + doc_files: Incomplete + changelog: Incomplete + icon: Incomplete + prep_script: Incomplete + build_script: Incomplete + install_script: Incomplete + clean_script: Incomplete + verify_script: Incomplete + pre_install: Incomplete + post_install: Incomplete + pre_uninstall: Incomplete + post_uninstall: Incomplete + prep: Incomplete + provides: Incomplete + requires: Incomplete + conflicts: Incomplete + build_requires: Incomplete + obsoletes: Incomplete + keep_temp: bool + use_rpm_opt_flags: bool + rpm3_mode: bool + no_autoreq: bool + force_arch: Incomplete + quiet: bool + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def finalize_package_data(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build.pyi b/stubs/setuptools/setuptools/_distutils/command/build.pyi new file mode 100644 index 000000000000..619b5e059b45 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +class build(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_base: str + build_purelib: Incomplete + build_platlib: Incomplete + build_lib: Incomplete + build_temp: Incomplete + build_scripts: Incomplete + compiler: Incomplete + plat_name: Incomplete + debug: Incomplete + force: bool + executable: Incomplete + parallel: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def has_pure_modules(self) -> bool: ... + def has_c_libraries(self) -> bool: ... + def has_ext_modules(self) -> bool: ... + def has_scripts(self) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build_clib.pyi b/stubs/setuptools/setuptools/_distutils/command/build_clib.pyi new file mode 100644 index 000000000000..e416a6dfe44d --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build_clib.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +class build_clib(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_clib: Incomplete + build_temp: Incomplete + libraries: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + debug: Incomplete + force: bool + compiler: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_library_list(self, libraries) -> None: ... + def get_library_names(self): ... + def get_source_files(self): ... + def build_libraries(self, libraries) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi b/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi new file mode 100644 index 000000000000..91a7ba47b1db --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..ccompiler import CCompiler +from ..cmd import Command +from ..extension import Extension + +class build_ext(Command): + description: ClassVar[str] + sep_by: Incomplete + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + extensions: list[Extension] | None + build_lib: str + plat_name: str + build_temp: str + inplace: bool + package: str | None + include_dirs: list[str] + define: Incomplete + undef: Incomplete + libraries: list[str] + library_dirs: list[str] + rpath: list[str] + link_objects: Incomplete + debug: Incomplete + force: bool | None + compiler: str | CCompiler | None + swig: Incomplete + swig_cpp: Incomplete + swig_opts: list[str] + user: Incomplete + parallel: int | None + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_extensions_list(self, extensions) -> None: ... + def get_source_files(self): ... + def get_outputs(self): ... + def build_extensions(self) -> None: ... + def build_extension(self, ext) -> None: ... + def swig_sources(self, sources, extension): ... + def find_swig(self): ... + def get_ext_fullpath(self, ext_name: str) -> str: ... + def get_ext_fullname(self, ext_name: str) -> str: ... + def get_ext_filename(self, ext_name: str) -> str: ... + def get_export_symbols(self, ext: Extension) -> list[str]: ... + def get_libraries(self, ext: Extension) -> list[str]: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build_py.pyi b/stubs/setuptools/setuptools/_distutils/command/build_py.pyi new file mode 100644 index 000000000000..967e27a32236 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build_py.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class build_py(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + build_lib: Incomplete + py_modules: Incomplete + package: Incomplete + package_data: Incomplete + package_dir: Incomplete + compile: bool + optimize: bool + force: Incomplete + def initialize_options(self) -> None: ... + packages: Incomplete + data_files: Incomplete + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_data_files(self): ... + def find_data_files(self, package, src_dir): ... + def build_package_data(self) -> None: ... + def get_package_dir(self, package): ... + def check_package(self, package, package_dir): ... + def check_module(self, module, module_file): ... + def find_package_modules(self, package, package_dir): ... + def find_modules(self): ... + def find_all_modules(self): ... + def get_source_files(self): ... + def get_module_outfile(self, build_dir, package, module): ... + def get_outputs(self, include_bytecode: bool = True) -> list[str]: ... + def build_module(self, module, module_file, package): ... + def build_modules(self) -> None: ... + def build_packages(self) -> None: ... + def byte_compile(self, files) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install.pyi b/stubs/setuptools/setuptools/_distutils/command/install.pyi new file mode 100644 index 000000000000..02d63c8f7518 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from collections import ChainMap +from typing import Any, ClassVar + +from ..cmd import Command + +class install(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + prefix: str | None + exec_prefix: Incomplete + home: str | None + user: bool + install_base: str | None + install_platbase: str | None + root: str | None + install_purelib: str | None + install_platlib: str | None + install_headers: str | None + install_lib: str | None + install_scripts: str | None + install_data: str | None + install_userbase: Incomplete + install_usersite: Incomplete + compile: Incomplete + optimize: Incomplete + extra_path: Incomplete + install_path_file: bool + force: bool + skip_build: bool + warn_dir: bool + build_base: Incomplete + build_lib: Incomplete + record: Incomplete + def initialize_options(self) -> None: ... + config_vars: ChainMap[str, Any] # Any: Same as sysconfig.get_config_vars + install_libbase: Incomplete + def finalize_options(self) -> None: ... + def dump_dirs(self, msg) -> None: ... + def finalize_unix(self) -> None: ... + def finalize_other(self) -> None: ... + def select_scheme(self, name) -> None: ... + def expand_basedirs(self) -> None: ... + def expand_dirs(self) -> None: ... + def convert_paths(self, *names) -> None: ... + path_file: Incomplete + extra_dirs: Incomplete + def handle_extra_path(self) -> None: ... + def change_roots(self, *names) -> None: ... + def create_home_path(self) -> None: ... + def run(self) -> None: ... + def create_path_file(self) -> None: ... + def get_outputs(self): ... + def get_inputs(self): ... + def has_lib(self) -> bool: ... + def has_headers(self) -> bool: ... + def has_scripts(self) -> bool: ... + def has_data(self) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install_data.pyi b/stubs/setuptools/setuptools/_distutils/command/install_data.pyi new file mode 100644 index 000000000000..777e28428fe6 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install_data.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_data(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: Incomplete + install_dir: Incomplete + outfiles: Incomplete + root: Incomplete + force: bool + data_files: Incomplete + warn_dir: bool + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install_lib.pyi b/stubs/setuptools/setuptools/_distutils/command/install_lib.pyi new file mode 100644 index 000000000000..2494af393e19 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install_lib.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete, MaybeNone +from typing import ClassVar + +from ..cmd import Command + +class install_lib(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + install_dir: Incomplete + build_dir: Incomplete + force: bool + compile: Incomplete + optimize: Incomplete + skip_build: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def build(self) -> None: ... + def install(self) -> list[str] | MaybeNone: ... + def byte_compile(self, files) -> None: ... + def get_outputs(self): ... + def get_inputs(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi b/stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..356e8621ee10 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_scripts(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + force: bool + build_dir: Incomplete + skip_build: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + outfiles: list[str] + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/command/sdist.pyi b/stubs/setuptools/setuptools/_distutils/command/sdist.pyi new file mode 100644 index 000000000000..4dc38b055cc6 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/sdist.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +def show_formats() -> None: ... + +class sdist(Command): + description: ClassVar[str] + + def checking_metadata(self): ... + + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + negative_opt: ClassVar[dict[str, str]] + READMES: ClassVar[tuple[str, ...]] + template: Incomplete + manifest: Incomplete + use_defaults: bool + prune: bool + manifest_only: bool + force_manifest: bool + formats: Incomplete + keep_temp: bool + dist_dir: Incomplete + archive_files: Incomplete + metadata_check: int # Soon to be updated to boolean upstream + owner: Incomplete + group: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + filelist: Incomplete + def run(self) -> None: ... + def get_file_list(self) -> None: ... + def add_defaults(self) -> None: ... + def read_template(self) -> None: ... + def prune_file_list(self) -> None: ... + def write_manifest(self) -> None: ... + def read_manifest(self) -> None: ... + def make_release_tree(self, base_dir, files) -> None: ... + def make_distribution(self) -> None: ... + def get_archive_files(self): ... + +def is_comment(line: str) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi new file mode 100644 index 000000000000..05fb8399721e --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi @@ -0,0 +1,215 @@ +from _typeshed import BytesPath, Incomplete, StrOrBytesPath, StrPath, Unused +from collections.abc import Callable, Iterable, Sequence +from subprocess import _ENV +from typing import ClassVar, Final, Literal, TypeAlias, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack, deprecated + +_Macro: TypeAlias = tuple[str] | tuple[str, str | None] +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) +_Ts = TypeVarTuple("_Ts") + +class Compiler: + compiler_type: ClassVar[str] + description: ClassVar[str] + executables: ClassVar[dict[str, Incomplete]] + + # Subclasses that rely on the standard filename generation methods + # implemented below should override these + src_extensions: ClassVar[list[str] | None] + obj_extension: ClassVar[str | None] + static_lib_extension: ClassVar[str | None] + shared_lib_extension: ClassVar[str | None] + static_lib_format: ClassVar[str | None] + shared_lib_format: ClassVar[str | None] + exe_extension: ClassVar[str | None] + + language_map: ClassVar[dict[str, str]] + language_order: ClassVar[list[str]] + force: bool + verbose: bool + output_dir: str | None + macros: list[_Macro] + include_dirs: list[str] + libraries: list[str] + library_dirs: list[str] + runtime_library_dirs: list[str] + objects: list[str] + + SHARED_OBJECT: Final = "shared_object" + SHARED_LIBRARY: Final = "shared_library" + EXECUTABLE: Final = "executable" + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + def add_include_dir(self, dir: str) -> None: ... + def set_include_dirs(self, dirs: list[str]) -> None: ... + def add_library(self, libname: str) -> None: ... + def set_libraries(self, libnames: list[str]) -> None: ... + def add_library_dir(self, dir: str) -> None: ... + def set_library_dirs(self, dirs: list[str]) -> None: ... + def add_runtime_library_dir(self, dir: str) -> None: ... + def set_runtime_library_dirs(self, dirs: list[str]) -> None: ... + def define_macro(self, name: str, value: str | None = None) -> None: ... + def undefine_macro(self, name: str) -> None: ... + def add_link_object(self, object: str) -> None: ... + def set_link_objects(self, objects: list[str]) -> None: ... + def detect_language(self, sources: str | list[str]) -> str | None: ... + def find_library_file(self, dirs: Iterable[str], lib: str, debug: bool = False) -> str | None: ... + + @overload + def has_function( + self, funcname: str, libraries: list[str] | None = None, library_dirs: list[str] | tuple[str, ...] | None = None + ) -> bool: ... + @overload + @deprecated("The `includes`, `include_dirs` parameters are deprecated.") + def has_function( + self, + funcname: str, + includes: Iterable[str] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + ) -> bool: ... + + def library_dir_option(self, dir: str) -> str: ... + def library_option(self, lib: str) -> str: ... + def runtime_library_dir_option(self, dir: str) -> str | list[str]: ... + def initialize(self, plat_name: str | None = None) -> None: ... + def configure_system(self) -> None: ... + def set_executables(self, **kwargs: str) -> None: ... + def set_executable(self, key: str, value) -> None: ... + def compile( + self, + sources: Sequence[StrPath], + output_dir: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + depends: list[str] | tuple[str, ...] | None = None, + ) -> list[str]: ... + def create_static_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + debug: bool = False, + target_lang: str | None = None, + ) -> None: ... + def link( + self, + target_desc: str, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_executable( + self, + objects: list[str] | tuple[str, ...], + output_progname: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_shared_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_shared_object( + self, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + def preprocess( + self, + source: StrPath, + output_file: StrPath | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + extra_preargs: list[str] | None = None, + extra_postargs: Iterable[str] | None = None, + ) -> None: ... + + @overload + def executable_filename(self, basename: str, strip_dir: Literal[False] = False, output_dir: StrPath = "") -> str: ... + @overload + def executable_filename(self, basename: StrPath, strip_dir: Literal[True], output_dir: StrPath = "") -> str: ... + + def library_filename( + self, libname: str, lib_type: str = "static", strip_dir: bool = False, output_dir: StrPath = "" + ) -> str: ... + @property + def out_extensions(self) -> dict[str, str]: ... + def object_filenames( + self, source_filenames: Iterable[StrPath], strip_dir: bool = False, output_dir: StrPath | None = "" + ) -> list[str]: ... + + @overload + def shared_object_filename(self, basename: str, strip_dir: Literal[False] = False, output_dir: StrPath = "") -> str: ... + @overload + def shared_object_filename(self, basename: StrPath, strip_dir: Literal[True], output_dir: StrPath = "") -> str: ... + + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def call(self, cmd: Sequence[StrOrBytesPath], *, env: _ENV | None = None, **kwargs) -> None: ... + def spawn(self, cmd: Sequence[StrOrBytesPath], *, env: _ENV | None = None, **kwargs) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT) -> _BytesPathT | bytes: ... + + def announce(self, msg: str, level: int = 1) -> None: ... + def warn(self, msg: str) -> None: ... + def debug_print(self, msg: str) -> None: ... + +def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: ... + +compiler_class: dict[str, tuple[str, str, str]] + +def show_compilers() -> None: ... +def get_compilers() -> dict[str, type[Compiler]]: ... +def new_compiler( + plat: str | None = None, compiler: str | None = None, verbose: bool = False, force: bool = False +) -> Compiler: ... +def gen_preprocess_options(macros: Iterable[_Macro], include_dirs: Iterable[str]) -> list[str]: ... +def gen_lib_options( + compiler: Compiler, library_dirs: Iterable[str], runtime_library_dirs: Iterable[str], libraries: Iterable[str] +) -> list[str]: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi new file mode 100644 index 000000000000..62469a25df49 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi @@ -0,0 +1,71 @@ +from _typeshed import StrPath +from collections.abc import Callable, Iterable +from shlex import _ShlexInstream +from typing import ClassVar, Final, Literal +from typing_extensions import Never, deprecated + +from ...version import LooseVersion +from . import unix + +def get_msvcr() -> list[str]: ... + +class Compiler(unix.Compiler): + compiler_type: ClassVar[str] + description: ClassVar[str] + obj_extension: ClassVar[str] + static_lib_extension: ClassVar[str] + shared_lib_extension: ClassVar[str] + dylib_lib_extension: ClassVar[str] + static_lib_format: ClassVar[str] + shared_lib_format: ClassVar[str] + dylib_lib_format: ClassVar[str] + exe_extension: ClassVar[str] + cc: str + cxx: str + linker_dll: str + linker_dll_cxx: str + dll_libraries: list[str] + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + @property + @deprecated( + "gcc_version attribute of CygwinCCompiler is deprecated. " + "Instead of returning actual gcc version a fixed value 11.2.0 is returned." + ) + def gcc_version(self) -> LooseVersion: ... + # `objects` and `libraries` uses list methods + def link( + self, + target_desc: str, + objects: list[str], # type: ignore[override] + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | None = None, # type: ignore[override] + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + # cygwin doesn't support rpath; prints a warning and returns an empty list + def runtime_library_dir_option(self, dir: str) -> list[Never]: ... # type: ignore[override] + @property + def out_extensions(self) -> dict[str, str]: ... + +class MinGW32Compiler(Compiler): + compiler_type: ClassVar[str] + description: ClassVar[str] + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + def configure_system(self) -> None: ... + def runtime_library_dir_option(self, dir: str) -> Never: ... + +CONFIG_H_OK: Final = "ok" +CONFIG_H_NOTOK: Final = "not ok" +CONFIG_H_UNCERTAIN: Final = "uncertain" + +def check_config_h() -> tuple[Literal["ok", "not ok", "uncertain"], str]: ... +def is_cygwincc(cc: str | _ShlexInstream) -> bool: ... + +get_versions: Callable[[], tuple[LooseVersion | None, ...]] | None diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi new file mode 100644 index 000000000000..280e85790683 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi @@ -0,0 +1,6 @@ +from ..errors import Error + +class PreprocessError(Error): ... +class CompileError(Error): ... +class LibError(Error): ... +class LinkError(Error): ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi new file mode 100644 index 000000000000..5631b5ca4f56 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi @@ -0,0 +1,25 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence +from typing import ClassVar, Final + +from . import base + +PLAT_SPEC_TO_RUNTIME: Final[dict[str, str]] + +class Compiler(base.Compiler): + compiler_type: ClassVar[str] + description: ClassVar[str] + src_extensions: ClassVar[list[str]] + res_extension: ClassVar[str] + obj_extension: ClassVar[str] + static_lib_extension: ClassVar[str] + shared_lib_extension: ClassVar[str] + shared_lib_format: ClassVar[str] + static_lib_format = shared_lib_format # pyrefly: ignore [unknown-name] + exe_extension: ClassVar[str] + initialized: bool + plat_name: str | None + def initialize(self, plat_name: str | None = None) -> None: ... + @property + def out_extensions(self) -> dict[str, str]: ... + def call(self, cmd: Sequence[StrOrBytesPath], *, env=None, **kwargs) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi new file mode 100644 index 000000000000..7b54ecbdcac8 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi @@ -0,0 +1,19 @@ +from typing import ClassVar + +from . import base + +class Compiler(base.Compiler): + compiler_type: ClassVar[str] + description: ClassVar[str] + src_extensions: ClassVar[list[str]] + obj_extension: ClassVar[str] + static_lib_extension: ClassVar[str] + shared_lib_extension: ClassVar[str] + dylib_lib_extension: ClassVar[str] + xcode_stub_lib_extension: ClassVar[str] + static_lib_format: ClassVar[str] + shared_lib_format: ClassVar[str] + dylib_lib_format: ClassVar[str] + xcode_stub_lib_format: ClassVar[str] + def configure_system(self) -> None: ... + def runtime_library_dir_option(self, dir: str) -> str | list[str]: ... # type: ignore[override] diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi new file mode 100644 index 000000000000..1db69f4cdca8 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi @@ -0,0 +1,29 @@ +from _typeshed import StrPath +from collections.abc import Iterable +from typing import ClassVar, Literal + +from . import unix + +class Compiler(unix.Compiler): + compiler_type: ClassVar[str] + description: ClassVar[str] + src_extensions: ClassVar[list[str]] + zos_compiler: Literal["ibm-openxl", "ibm-xlclang", "ibm-xlc"] + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + def runtime_library_dir_option(self, dir: str) -> str: ... + def link( + self, + target_desc: str, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/errors.pyi b/stubs/setuptools/setuptools/_distutils/compilers/errors.pyi new file mode 100644 index 000000000000..287be1b8200d --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/errors.pyi @@ -0,0 +1,3 @@ +class Error(Exception): ... +class UnknownFileType(Error): ... +class PlatformError(Error): ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/platform/detect.pyi b/stubs/setuptools/setuptools/_distutils/compilers/platform/detect.pyi new file mode 100644 index 000000000000..1b890d82eadf --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/platform/detect.pyi @@ -0,0 +1,3 @@ +def get_host_platform() -> str: ... +def get_platform() -> str: ... +def is_mingw() -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/platform/macos.pyi b/stubs/setuptools/setuptools/_distutils/compilers/platform/macos.pyi new file mode 100644 index 000000000000..22da842310bb --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/platform/macos.pyi @@ -0,0 +1,11 @@ +from collections.abc import Mapping +from typing import Any, Final, TypeVar + +_MappingT = TypeVar("_MappingT", bound=Mapping[Any, Any]) + +VERSION_VAR: Final = "MACOSX_DEPLOYMENT_TARGET" + +def customize_compiler(config_vars) -> None: ... +def _target_ver_from_syscfg(): ... +def target_ver() -> str | None: ... +def inject_ver(env: _MappingT | None) -> _MappingT | dict[str, str | int] | None: ... diff --git a/stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi b/stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..db2a886c6882 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable + +from .compilers.C import cygwin +from .compilers.C.cygwin import ( + CONFIG_H_NOTOK as CONFIG_H_NOTOK, + CONFIG_H_OK as CONFIG_H_OK, + CONFIG_H_UNCERTAIN as CONFIG_H_UNCERTAIN, + check_config_h as check_config_h, + get_msvcr as get_msvcr, + is_cygwincc as is_cygwincc, +) +from .version import LooseVersion + +__all__ = [ + "CONFIG_H_NOTOK", + "CONFIG_H_OK", + "CONFIG_H_UNCERTAIN", + "CygwinCCompiler", + "Mingw32CCompiler", + "check_config_h", + "get_msvcr", + "is_cygwincc", +] + +CygwinCCompiler = cygwin.Compiler +Mingw32CCompiler = cygwin.MinGW32Compiler + +get_versions: Callable[[], tuple[LooseVersion | None, ...]] | None diff --git a/stubs/setuptools/setuptools/_distutils/dep_util.pyi b/stubs/setuptools/setuptools/_distutils/dep_util.pyi new file mode 100644 index 000000000000..88cd92f00160 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/dep_util.pyi @@ -0,0 +1 @@ +from ._modified import newer as newer, newer_group as newer_group, newer_pairwise as newer_pairwise diff --git a/stubs/setuptools/setuptools/_distutils/dist.pyi b/stubs/setuptools/setuptools/_distutils/dist.pyi new file mode 100644 index 000000000000..fe8c517c3a46 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/dist.pyi @@ -0,0 +1,179 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsWrite +from collections.abc import Iterable, Mapping, MutableMapping +from re import Pattern +from typing import IO, ClassVar, Literal, TypeAlias, TypeVar, overload + +from .cmd import Command +from .extension import Extension + +command_re: Pattern[str] + +_OptionsList: TypeAlias = list[tuple[str, str | None, str, int] | tuple[str, str | None, str]] +_CommandT = TypeVar("_CommandT", bound=Command) + +class DistributionMetadata: + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... + name: str | None + version: str | None + author: str | None + author_email: str | None + maintainer: str | None + maintainer_email: str | None + url: str | None + license: str | None + description: str | None + long_description: str | None + keywords: str | list[str] | None + platforms: str | list[str] | None + classifiers: str | list[str] | None + download_url: str | None + provides: list[str] | None + requires: list[str] | None + obsoletes: list[str] | None + def read_pkg_file(self, file: IO[str]) -> None: ... + def write_pkg_info(self, base_dir: StrPath) -> None: ... + def write_pkg_file(self, file: SupportsWrite[str]) -> None: ... + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str | None: ... + def get_author_email(self) -> str | None: ... + def get_maintainer(self) -> str | None: ... + def get_maintainer_email(self) -> str | None: ... + def get_contact(self) -> str | None: ... + def get_contact_email(self) -> str | None: ... + def get_url(self) -> str | None: ... + def get_license(self) -> str | None: ... + get_licence = get_license + def get_description(self) -> str | None: ... + def get_long_description(self) -> str | None: ... + def get_keywords(self) -> str | list[str]: ... + def set_keywords(self, value: str | Iterable[str]) -> None: ... + def get_platforms(self) -> str | list[str] | None: ... + def set_platforms(self, value: str | Iterable[str]) -> None: ... + def get_classifiers(self) -> str | list[str]: ... + def set_classifiers(self, value): ... + def get_download_url(self) -> str | None: ... + def get_requires(self) -> str | list[str]: ... + def set_requires(self, value: Iterable[str]) -> None: ... + def get_provides(self) -> str | list[str]: ... + def set_provides(self, value: Iterable[str]) -> None: ... + def get_obsoletes(self) -> str | list[str]: ... + def set_obsoletes(self, value: Iterable[str]) -> None: ... + +class Distribution: + cmdclass: dict[str, type[Command]] + metadata: DistributionMetadata + def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ... + def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ... + def parse_config_files(self, filenames: Iterable[str] | None = None) -> None: ... + global_options: ClassVar[_OptionsList] + common_usage: ClassVar[str] + display_options: ClassVar[_OptionsList] + display_option_names: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + verbose: bool + help: bool + command_packages: str | list[str] | None + script_name: StrPath | None + script_args: list[str] | None + command_options: dict[str, dict[str, tuple[str, str]]] + dist_files: list[tuple[str, str, str]] + packages: list[str] | None + package_data: dict[str, list[str]] + package_dir: Mapping[str, str] | None + py_modules: list[str] | None + libraries: list[tuple[str, dict[str, Incomplete]]] | None + headers: list[str] | None + ext_modules: list[Extension] | None + ext_package: str | None + include_dirs: list[str] | None + extra_path: Incomplete + scripts: list[str] | None + data_files: list[tuple[str, list[str]]] | None + password: str + command_obj: dict[str, Command] + have_run: dict[str, bool] + want_user_cfg: bool + def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None: ... + def find_config_files(self): ... + commands: Incomplete + def parse_command_line(self): ... + def finalize_options(self) -> None: ... + def handle_display_options(self, option_order): ... + def print_command_list(self, commands, header, max_length) -> None: ... + def print_commands(self) -> None: ... + def get_command_list(self): ... + def get_command_packages(self): ... + + # NOTE: Because this is private setuptools implementation and we don't re-expose all commands here, + # we're not overloading each and every command possibility. + @overload + def get_command_obj(self, command: str, create: Literal[True] = True) -> Command: ... + @overload + def get_command_obj(self, command: str, create: Literal[False]) -> Command | None: ... + + def get_command_class(self, command: str) -> type[Command]: ... + + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def announce(self, msg, level: int = 20) -> None: ... + def run_commands(self) -> None: ... + def run_command(self, command: str) -> None: ... + def has_pure_modules(self) -> bool: ... + def has_ext_modules(self) -> bool: ... + def has_c_libraries(self) -> bool: ... + def has_modules(self) -> bool: ... + def has_headers(self) -> bool: ... + def has_scripts(self) -> bool: ... + def has_data_files(self) -> bool: ... + def is_pure(self) -> bool: ... + + # Default getter methods generated in __init__ from self.metadata._METHOD_BASENAMES + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> str | list[str]: ... + def get_platforms(self) -> str | list[str]: ... + def get_classifiers(self) -> str | list[str]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> list[str]: ... + def get_provides(self) -> list[str]: ... + def get_obsoletes(self) -> list[str]: ... + + # Default attributes generated in __init__ from self.display_option_names + help_commands: bool + name: str | Literal[False] + version: str | Literal[False] + fullname: str | Literal[False] + author: str | Literal[False] + author_email: str | Literal[False] + maintainer: str | Literal[False] + maintainer_email: str | Literal[False] + contact: str | Literal[False] + contact_email: str | Literal[False] + url: str | Literal[False] + license: str | Literal[False] + licence: str | Literal[False] + description: str | Literal[False] + long_description: str | Literal[False] + platforms: str | list[str] | Literal[False] + classifiers: str | list[str] | Literal[False] + keywords: str | list[str] | Literal[False] + provides: list[str] | Literal[False] + requires: list[str] | Literal[False] + obsoletes: list[str] | Literal[False] diff --git a/stubs/setuptools/setuptools/_distutils/errors.pyi b/stubs/setuptools/setuptools/_distutils/errors.pyi new file mode 100644 index 000000000000..76960eb1ac25 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/errors.pyi @@ -0,0 +1,46 @@ +from .compilers.C.errors import ( + CompileError as CompileError, + LibError as LibError, + LinkError as LinkError, + PreprocessError as PreprocessError, +) +from .compilers.errors import Error as _Error, UnknownFileType as _UnknownFileType + +CCompilerError = _Error +UnknownFileError = _UnknownFileType + +__all__ = [ + "CCompilerError", + "CompileError", + "DistutilsArgError", + "DistutilsByteCompileError", + "DistutilsClassError", + "DistutilsError", + "DistutilsExecError", + "DistutilsFileError", + "DistutilsGetoptError", + "DistutilsInternalError", + "DistutilsModuleError", + "DistutilsOptionError", + "DistutilsPlatformError", + "DistutilsSetupError", + "DistutilsTemplateError", + "LibError", + "LinkError", + "PreprocessError", + "UnknownFileError", +] + +class DistutilsError(Exception): ... +class DistutilsModuleError(DistutilsError): ... +class DistutilsClassError(DistutilsError): ... +class DistutilsGetoptError(DistutilsError): ... +class DistutilsArgError(DistutilsError): ... +class DistutilsFileError(DistutilsError): ... +class DistutilsOptionError(DistutilsError): ... +class DistutilsSetupError(DistutilsError): ... +class DistutilsPlatformError(DistutilsError): ... +class DistutilsExecError(DistutilsError): ... +class DistutilsInternalError(DistutilsError): ... +class DistutilsTemplateError(DistutilsError): ... +class DistutilsByteCompileError(DistutilsError): ... diff --git a/stubs/setuptools/setuptools/_distutils/extension.pyi b/stubs/setuptools/setuptools/_distutils/extension.pyi new file mode 100644 index 000000000000..a1711fb8bcb9 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/extension.pyi @@ -0,0 +1,23 @@ +from _typeshed import StrPath +from collections.abc import Iterable +from dataclasses import dataclass + +@dataclass() +class Extension: + name: str + sources: Iterable[StrPath] + include_dirs: list[str] = ... + define_macros: list[tuple[str, str | None]] = ... + undef_macros: list[str] = ... + library_dirs: list[str] = ... + libraries: list[str] = ... + runtime_library_dirs: list[str] = ... + extra_objects: list[str] = ... + extra_compile_args: list[str] = ... + extra_link_args: list[str] = ... + export_symbols: list[str] = ... + swig_opts: list[str] = ... + depends: list[str] = ... + language: str | None = None + optional: bool = False + def __post_init__(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/filelist.pyi b/stubs/setuptools/setuptools/_distutils/filelist.pyi new file mode 100644 index 000000000000..c9e063474d18 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/filelist.pyi @@ -0,0 +1,40 @@ +from _typeshed import StrPath, Unused +from collections.abc import Iterable +from re import Pattern +from typing import Literal, overload + +# class is entirely undocumented +class FileList: + allfiles: Iterable[str] | None + files: list[str] + def __init__(self, warn: Unused = None, debug_print: Unused = None) -> None: ... + def set_allfiles(self, allfiles: Iterable[str]) -> None: ... + def findall(self, dir: StrPath = ".") -> None: ... + def debug_print(self, msg: object) -> None: ... + def append(self, item: str) -> None: ... + def extend(self, items: Iterable[str]) -> None: ... + def sort(self) -> None: ... + def remove_duplicates(self) -> None: ... + def process_template_line(self, line: str) -> None: ... + + @overload + def include_pattern( + self, pattern: str | None, anchor: bool = True, prefix: str | None = None, is_regex: Literal[False] = False + ) -> bool: ... + @overload + def include_pattern( + self, pattern: str | Pattern[str], anchor: bool = True, prefix: str | None = None, *, is_regex: Literal[True] + ) -> bool: ... + @overload + def include_pattern(self, pattern: str | Pattern[str], anchor: bool, prefix: str | None, is_regex: Literal[True]) -> bool: ... + + @overload + def exclude_pattern( + self, pattern: str | None, anchor: bool = True, prefix: str | None = None, is_regex: Literal[False] = False + ) -> bool: ... + @overload + def exclude_pattern( + self, pattern: str | Pattern[str], anchor: bool = True, prefix: str | None = None, *, is_regex: Literal[True] + ) -> bool: ... + @overload + def exclude_pattern(self, pattern: str | Pattern[str], anchor: bool, prefix: str | None, is_regex: Literal[True]) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/spawn.pyi b/stubs/setuptools/setuptools/_distutils/spawn.pyi new file mode 100644 index 000000000000..60e386c2fce2 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/spawn.pyi @@ -0,0 +1,6 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence +from subprocess import _ENV + +def spawn(cmd: Sequence[StrOrBytesPath], *, env: _ENV | None = None, **kwargs) -> None: ... +def find_executable(executable: str, path: str | None = None) -> str | None: ... diff --git a/stubs/setuptools/setuptools/_distutils/sysconfig.pyi b/stubs/setuptools/setuptools/_distutils/sysconfig.pyi new file mode 100644 index 000000000000..50df58168ab0 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/sysconfig.pyi @@ -0,0 +1,24 @@ +from typing import Final, Literal, overload +from typing_extensions import deprecated + +from setuptools._distutils.ccompiler import CCompiler + +PREFIX: Final[str] +EXEC_PREFIX: Final[str] + +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support will be removed when this module is synchronized with stdlib Python 3.11") +def get_config_var(name: Literal["SO"]) -> int | str | None: ... +@overload +def get_config_var(name: str) -> int | str | None: ... + +@overload +def get_config_vars() -> dict[str, str | int]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[str | int | None]: ... + +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... +def get_python_inc(plat_specific: bool = False, prefix: str | None = None) -> str: ... +def get_python_lib(plat_specific: bool = False, standard_lib: bool = False, prefix: str | None = None) -> str: ... +def customize_compiler(compiler: CCompiler) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/unixccompiler.pyi b/stubs/setuptools/setuptools/_distutils/unixccompiler.pyi new file mode 100644 index 000000000000..9cd30ad9a64e --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/unixccompiler.pyi @@ -0,0 +1,3 @@ +from .compilers.C import unix + +UnixCCompiler = unix.Compiler diff --git a/stubs/setuptools/setuptools/_distutils/util.pyi b/stubs/setuptools/setuptools/_distutils/util.pyi new file mode 100644 index 000000000000..ac4c1f849842 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/util.pyi @@ -0,0 +1,38 @@ +from _typeshed import StrPath, Unused +from collections.abc import Callable, Iterable, Mapping +from typing import Literal +from typing_extensions import TypeVarTuple, Unpack + +from .compilers.platform import detect, macos + +_Ts = TypeVarTuple("_Ts") + +get_host_platform = detect.get_host_platform +get_platform = detect.get_platform +is_mingw = detect.is_mingw +MACOSX_VERSION_VAR = macos.VERSION_VAR +get_macosx_target_ver = macos.target_ver +get_macosx_target_ver_from_syscfg = macos._target_ver_from_syscfg + +def split_version(s: str) -> list[int]: ... +def convert_path(pathname: StrPath) -> str: ... +def change_root(new_root: StrPath, pathname: StrPath) -> str: ... +def check_environ() -> None: ... +def subst_vars(s: str, local_vars: Mapping[str, object]) -> str: ... +def grok_environment_error(exc: object, prefix: str = "error: ") -> str: ... +def split_quoted(s: str) -> list[str]: ... +def execute( + func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, verbose: bool = False +) -> None: ... +def strtobool(val: str) -> Literal[0, 1]: ... +def byte_compile( + py_files: Iterable[str], + optimize: int = 0, + force: bool = False, + prefix: str | None = None, + base_dir: str | None = None, + verbose: bool = True, + direct: bool | None = None, +) -> None: ... +def rfc822_escape(header: str) -> str: ... +def is_freethreaded() -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/version.pyi b/stubs/setuptools/setuptools/_distutils/version.pyi new file mode 100644 index 000000000000..94b0512e37f5 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/version.pyi @@ -0,0 +1,35 @@ +from abc import abstractmethod +from re import Pattern +from typing_extensions import Self, deprecated + +@deprecated("The `Version` class is deprecated. Use `packaging.version` instead.") +class Version: + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Self | str) -> bool: ... + def __le__(self, other: Self | str) -> bool: ... + def __gt__(self, other: Self | str) -> bool: ... + def __ge__(self, other: Self | str) -> bool: ... + @abstractmethod + def __init__(self, vstring: str | None = None) -> None: ... + @abstractmethod + def parse(self, vstring: str) -> Self: ... + @abstractmethod + def _cmp(self, other: Self | str) -> bool: ... + +@deprecated("The `StrictVersion` class is deprecated. Use `packaging.version` instead.") +class StrictVersion(Version): + version_re: Pattern[str] + version: tuple[int, int, int] + prerelease: tuple[str, int] | None + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def _cmp(self, other: Self | str) -> bool: ... + +@deprecated("The `LooseVersion` class is deprecated. Use `packaging.version` instead.") +class LooseVersion(Version): + component_re: Pattern[str] + vstring: str + version: tuple[str | int, ...] + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def _cmp(self, other: Self | str) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/zosccompiler.pyi b/stubs/setuptools/setuptools/_distutils/zosccompiler.pyi new file mode 100644 index 000000000000..e49630ac6ed8 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/zosccompiler.pyi @@ -0,0 +1,3 @@ +from .compilers.C import zos + +zOSCCompiler = zos.Compiler diff --git a/stubs/setuptools/setuptools/archive_util.pyi b/stubs/setuptools/setuptools/archive_util.pyi index cbc27e020dfd..acadce09a7ca 100644 --- a/stubs/setuptools/setuptools/archive_util.pyi +++ b/stubs/setuptools/setuptools/archive_util.pyi @@ -1,12 +1,24 @@ -from distutils.errors import DistutilsError -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable + +from ._distutils.errors import DistutilsError + +__all__ = [ + "unpack_archive", + "unpack_zipfile", + "unpack_tarfile", + "default_filter", + "UnrecognizedFormat", + "extraction_drivers", + "unpack_directory", +] class UnrecognizedFormat(DistutilsError): ... def default_filter(src, dst): ... -def unpack_archive(filename, extract_dir, progress_filter=..., drivers: Any | None = ...) -> None: ... +def unpack_archive(filename, extract_dir, progress_filter=..., drivers=None) -> None: ... def unpack_directory(filename, extract_dir, progress_filter=...) -> None: ... def unpack_zipfile(filename, extract_dir, progress_filter=...) -> None: ... def unpack_tarfile(filename, extract_dir, progress_filter=...): ... -extraction_drivers: Any +extraction_drivers: tuple[Callable[..., Incomplete], ...] diff --git a/stubs/setuptools/setuptools/build_meta.pyi b/stubs/setuptools/setuptools/build_meta.pyi index 1e3e81f6f60c..08f3128cda37 100644 --- a/stubs/setuptools/setuptools/build_meta.pyi +++ b/stubs/setuptools/setuptools/build_meta.pyi @@ -1,30 +1,64 @@ -from typing import Any +from _typeshed import Incomplete, StrPath +from collections.abc import Mapping +from contextlib import _GeneratorContextManager +from typing import TypeAlias +from typing_extensions import Never -from setuptools import dist +from . import dist + +__all__ = [ + "get_requires_for_build_sdist", + "get_requires_for_build_wheel", + "prepare_metadata_for_build_wheel", + "build_wheel", + "build_sdist", + "get_requires_for_build_editable", + "prepare_metadata_for_build_editable", + "build_editable", + "__legacy__", + "SetupRequirementsError", +] + +_ConfigSettings: TypeAlias = Mapping[str, str | list[str] | None] | None class SetupRequirementsError(BaseException): - specifiers: Any + specifiers: Incomplete def __init__(self, specifiers) -> None: ... class Distribution(dist.Distribution): - def fetch_build_eggs(self, specifiers) -> None: ... + def fetch_build_eggs(self, specifiers) -> Never: ... @classmethod - def patch(cls) -> None: ... + def patch(cls) -> _GeneratorContextManager[None]: ... class _BuildMetaBackend: - def run_setup(self, setup_script: str = ...) -> None: ... - def get_requires_for_build_wheel(self, config_settings: Any | None = ...): ... - def get_requires_for_build_sdist(self, config_settings: Any | None = ...): ... - def prepare_metadata_for_build_wheel(self, metadata_directory, config_settings: Any | None = ...): ... - def build_wheel(self, wheel_directory, config_settings: Any | None = ..., metadata_directory: Any | None = ...): ... - def build_sdist(self, sdist_directory, config_settings: Any | None = ...): ... + def run_setup(self, setup_script: str = "setup.py") -> None: ... + def get_requires_for_build_wheel(self, config_settings: _ConfigSettings = None) -> list[str]: ... + def get_requires_for_build_sdist(self, config_settings: _ConfigSettings = None) -> list[str]: ... + def prepare_metadata_for_build_wheel(self, metadata_directory: StrPath, config_settings: _ConfigSettings = None) -> str: ... + def build_wheel( + self, wheel_directory: StrPath, config_settings: _ConfigSettings = None, metadata_directory: StrPath | None = None + ) -> str: ... + def build_sdist(self, sdist_directory: StrPath, config_settings: _ConfigSettings = None) -> str: ... + def build_editable( + self, wheel_directory: StrPath, config_settings: _ConfigSettings = None, metadata_directory: StrPath | None = None + ) -> str: ... + def get_requires_for_build_editable(self, config_settings: _ConfigSettings = None) -> list[str]: ... + def prepare_metadata_for_build_editable( + self, metadata_directory: StrPath, config_settings: _ConfigSettings = None + ) -> str: ... class _BuildMetaLegacyBackend(_BuildMetaBackend): - def run_setup(self, setup_script: str = ...) -> None: ... - -get_requires_for_build_wheel: Any -get_requires_for_build_sdist: Any -prepare_metadata_for_build_wheel: Any -build_wheel: Any -build_sdist: Any -__legacy__: Any + def run_setup(self, setup_script: str = "setup.py") -> None: ... + +_BACKEND: _BuildMetaBackend +get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel +get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist +prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel +build_wheel = _BACKEND.build_wheel +build_sdist = _BACKEND.build_sdist + +get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable +prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable +build_editable = _BACKEND.build_editable + +__legacy__: _BuildMetaLegacyBackend diff --git a/stubs/setuptools/setuptools/command/alias.pyi b/stubs/setuptools/setuptools/command/alias.pyi index ff79d933a431..cd3b4d9b5b74 100644 --- a/stubs/setuptools/setuptools/command/alias.pyi +++ b/stubs/setuptools/setuptools/command/alias.pyi @@ -1,16 +1,17 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar -from setuptools.command.setopt import option_base +from .setopt import option_base def shquote(arg): ... class alias(option_base): description: str command_consumes_arguments: bool - user_options: Any - boolean_options: Any - args: Any - remove: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + args: Incomplete + remove: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/bdist_egg.pyi b/stubs/setuptools/setuptools/command/bdist_egg.pyi index fca2f7579a8a..9c25dcc1799c 100644 --- a/stubs/setuptools/setuptools/command/bdist_egg.pyi +++ b/stubs/setuptools/setuptools/command/bdist_egg.pyi @@ -1,48 +1,57 @@ -from typing import Any +from _typeshed import GenericPath, Incomplete, StrPath +from collections.abc import Iterator +from types import CodeType +from typing import ClassVar, Final, Literal, TypeVar +from zipfile import _ZipFileMode -from setuptools import Command +from .. import Command + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_StrOrBytesT = TypeVar("_StrOrBytesT", str, bytes) def strip_module(filename): ... -def sorted_walk(dir) -> None: ... +def sorted_walk(dir: GenericPath[_StrOrBytesT]) -> Iterator[tuple[_StrOrBytesT, list[_StrOrBytesT], list[_StrOrBytesT]]]: ... def write_stub(resource, pyfile) -> None: ... class bdist_egg(Command): description: str - user_options: Any - boolean_options: Any - bdist_dir: Any - plat_name: Any - keep_temp: int - dist_dir: Any - skip_build: int - egg_output: Any - exclude_source_files: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + bdist_dir: Incomplete + plat_name: str + keep_temp: bool + dist_dir: Incomplete + skip_build: bool + egg_output: Incomplete + exclude_source_files: Incomplete def initialize_options(self) -> None: ... - egg_info: Any + egg_info: Incomplete def finalize_options(self) -> None: ... def do_install_data(self) -> None: ... def get_outputs(self): ... def call_command(self, cmdname, **kw): ... - stubs: Any + stubs: Incomplete def run(self) -> None: ... def zap_pyfiles(self) -> None: ... def zip_safe(self): ... - def gen_header(self): ... + def gen_header(self) -> Literal["w"]: ... def copy_metadata_to(self, target_dir) -> None: ... def get_ext_outputs(self): ... -NATIVE_EXTENSIONS: Any +NATIVE_EXTENSIONS: Final[dict[str, None]] -def walk_egg(egg_dir) -> None: ... +def walk_egg(egg_dir: StrPath) -> Iterator[tuple[str, list[str], list[str]]]: ... def analyze_egg(egg_dir, stubs): ... def write_safety_flag(egg_dir, safe) -> None: ... -safety_flags: Any +safety_flags: Incomplete def scan_module(egg_dir, base, name, stubs): ... -def iter_symbols(code) -> None: ... -def can_scan(): ... +def iter_symbols(code: CodeType) -> Iterator[str]: ... +def can_scan() -> bool: ... -INSTALL_DIRECTORY_ATTRS: Any +INSTALL_DIRECTORY_ATTRS: Final[list[str]] -def make_zipfile(zip_filename, base_dir, verbose: int = ..., dry_run: int = ..., compress: bool = ..., mode: str = ...): ... +def make_zipfile( + zip_filename: _StrPathT, base_dir, verbose: bool = False, compress: bool = True, mode: _ZipFileMode = "w" +) -> _StrPathT: ... diff --git a/stubs/setuptools/setuptools/command/bdist_rpm.pyi b/stubs/setuptools/setuptools/command/bdist_rpm.pyi index 4942eafe98e8..cb79f3dbf156 100644 --- a/stubs/setuptools/setuptools/command/bdist_rpm.pyi +++ b/stubs/setuptools/setuptools/command/bdist_rpm.pyi @@ -1,4 +1,7 @@ -import distutils.command.bdist_rpm as orig +from setuptools.dist import Distribution + +from .._distutils.command import bdist_rpm as orig class bdist_rpm(orig.bdist_rpm): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/bdist_wheel.pyi b/stubs/setuptools/setuptools/command/bdist_wheel.pyi new file mode 100644 index 000000000000..d6538ab52d4c --- /dev/null +++ b/stubs/setuptools/setuptools/command/bdist_wheel.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, Literal + +from setuptools import Command + +def safe_version(version: str) -> str: ... + +setuptools_major_version: Final[int] + +PY_LIMITED_API_PATTERN: Final[str] + +def python_tag() -> str: ... +def get_platform(archive_root: str | None) -> str: ... +def get_flag(var: str, fallback: bool, expected: bool = True, warn: bool = True) -> bool: ... +def get_abi_tag() -> str | None: ... +def safer_version(version: str) -> str: ... + +class bdist_wheel(Command): + description: ClassVar[str] + supported_compressions: ClassVar[dict[str, int]] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + + bdist_dir: str | None + data_dir: str + plat_name: str | None + plat_tag: str | None + format: str + keep_temp: bool + dist_dir: str | None + egginfo_dir: str | None + root_is_pure: bool | None + skip_build: bool + relative: bool + owner: Incomplete | None + group: Incomplete | None + universal: bool + compression: str | int + python_tag: str + build_number: str | None + py_limited_api: str | Literal[False] + plat_name_supplied: bool + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @property + def wheel_dist_name(self) -> str: ... + def get_tag(self) -> tuple[str, str, str]: ... + def run(self) -> None: ... + def write_wheelfile(self, wheelfile_base: str, generator: str = ...) -> None: ... + @property + def license_paths(self) -> Iterable[str]: ... + def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None: ... diff --git a/stubs/setuptools/setuptools/command/build.pyi b/stubs/setuptools/setuptools/command/build.pyi new file mode 100644 index 000000000000..5263a05bda51 --- /dev/null +++ b/stubs/setuptools/setuptools/command/build.pyi @@ -0,0 +1,18 @@ +from typing import Protocol + +from setuptools.dist import Distribution + +from .._distutils.command.build import build as _build + +class build(_build): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + +class SubCommand(Protocol): + editable_mode: bool + build_lib: str + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_source_files(self) -> list[str]: ... + def get_outputs(self) -> list[str]: ... + def get_output_mapping(self) -> dict[str, str]: ... diff --git a/stubs/setuptools/setuptools/command/build_clib.pyi b/stubs/setuptools/setuptools/command/build_clib.pyi index c088f7d790c3..6f657c2c7c2f 100644 --- a/stubs/setuptools/setuptools/command/build_clib.pyi +++ b/stubs/setuptools/setuptools/command/build_clib.pyi @@ -1,4 +1,8 @@ -import distutils.command.build_clib as orig +from setuptools.dist import Distribution + +from .._distutils.command import build_clib as orig class build_clib(orig.build_clib): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + def build_libraries(self, libraries) -> None: ... diff --git a/stubs/setuptools/setuptools/command/build_ext.pyi b/stubs/setuptools/setuptools/command/build_ext.pyi index b627be35698d..34366afb3ee0 100644 --- a/stubs/setuptools/setuptools/command/build_ext.pyi +++ b/stubs/setuptools/setuptools/command/build_ext.pyi @@ -1,44 +1,51 @@ -from distutils.command.build_ext import build_ext as _build_ext -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar + +from setuptools.dist import Distribution + +from .._distutils.command.build_ext import build_ext as _build_ext have_rtld: bool use_stubs: bool libtype: str -def if_dl(s): ... def get_abi3_suffix(): ... class build_ext(_build_ext): - inplace: Any + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + editable_mode: ClassVar[bool] + inplace: bool def run(self) -> None: ... def copy_extensions_to_source(self) -> None: ... def get_ext_filename(self, fullname): ... - shlib_compiler: Any - shlibs: Any - ext_map: Any + shlib_compiler: Incomplete + shlibs: list[Incomplete] + ext_map: dict[Incomplete, Incomplete] def initialize_options(self) -> None: ... - extensions: Any + extensions: list[Incomplete] def finalize_options(self) -> None: ... def setup_shlib_compiler(self) -> None: ... def get_export_symbols(self, ext): ... - compiler: Any + compiler: Incomplete def build_extension(self, ext) -> None: ... def links_to_dynamic(self, ext): ... - def get_outputs(self): ... - def write_stub(self, output_dir, ext, compile: bool = ...) -> None: ... + def get_source_files(self) -> list[str]: ... + def get_outputs(self) -> list[str]: ... + def get_output_mapping(self) -> dict[str, str]: ... + def write_stub(self, output_dir, ext, compile: bool = False) -> None: ... def link_shared_object( self, objects, output_libname, - output_dir: Any | None = ..., - libraries: Any | None = ..., - library_dirs: Any | None = ..., - runtime_library_dirs: Any | None = ..., - export_symbols: Any | None = ..., - debug: int = ..., - extra_preargs: Any | None = ..., - extra_postargs: Any | None = ..., - build_temp: Any | None = ..., - target_lang: Any | None = ..., + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug: bool = False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, ) -> None: ... diff --git a/stubs/setuptools/setuptools/command/build_py.pyi b/stubs/setuptools/setuptools/command/build_py.pyi index 8e121cb10826..7a2435bed01c 100644 --- a/stubs/setuptools/setuptools/command/build_py.pyi +++ b/stubs/setuptools/setuptools/command/build_py.pyi @@ -1,27 +1,43 @@ -import distutils.command.build_py as orig -from typing import Any +from _typeshed import Incomplete, StrPath, Unused +from typing import ClassVar -from setuptools.lib2to3_ex import Mixin2to3 +from setuptools.dist import Distribution + +from .._distutils.cmd import _StrPathT +from .._distutils.command import build_py as orig def make_writable(target) -> None: ... -class build_py(orig.build_py, Mixin2to3): - package_data: Any - exclude_package_data: Any +class build_py(orig.build_py): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + editable_mode: ClassVar[bool] + package_data: dict[str, list[str]] + exclude_package_data: dict[Incomplete, Incomplete] def finalize_options(self) -> None: ... + def copy_file( # type: ignore[override] # No overload, str support only + self, + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_StrPathT | str, bool]: ... def run(self) -> None: ... - data_files: Any - def __getattr__(self, attr): ... - def build_module(self, module, module_file, package): ... - def find_data_files(self, package, src_dir): ... + data_files: list[tuple[str, str, str, list[str]]] + def __getattr__(self, attr: str): ... + def get_data_files_without_manifest(self) -> list[tuple[str, str, str, list[str]]]: ... + def find_data_files(self, package, src_dir) -> list[str]: ... + def get_outputs(self, include_bytecode: bool = True) -> list[str]: ... # type: ignore[override] # Using a real boolean instead of 0|1 def build_package_data(self) -> None: ... - manifest_files: Any + manifest_files: dict[str, list[str]] + def get_output_mapping(self) -> dict[str, str]: ... def analyze_manifest(self) -> None: ... def get_data_files(self) -> None: ... def check_package(self, package, package_dir): ... - packages_checked: Any def initialize_options(self) -> None: ... - def get_package_dir(self, package): ... + packages_checked: dict[Incomplete, Incomplete] + def get_package_dir(self, package: str) -> str: ... def exclude_data_files(self, package, src_dir, files): ... def assert_relative(path): ... diff --git a/stubs/setuptools/setuptools/command/develop.pyi b/stubs/setuptools/setuptools/command/develop.pyi index 8b099dc802a0..afad2e9a4568 100644 --- a/stubs/setuptools/setuptools/command/develop.pyi +++ b/stubs/setuptools/setuptools/command/develop.pyi @@ -1,31 +1,24 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar +from typing_extensions import deprecated -from setuptools import namespaces -from setuptools.command.easy_install import easy_install +from setuptools import Command +from setuptools.warnings import SetuptoolsDeprecationWarning -class develop(namespaces.DevelopInstaller, easy_install): - description: str - user_options: Any - boolean_options: Any - command_consumes_arguments: bool - multi_version: bool - def run(self) -> None: ... # type: ignore[override] - uninstall: Any - egg_path: Any - setup_path: Any - always_copy_from: str +class develop(Command): + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + no_deps: bool + user: bool + prefix: Incomplete + index_url: Incomplete + def run(self) -> None: ... + @deprecated( + "develop command is deprecated. Please avoid running `setup.py` and `develop`. " + "Instead, use standards-based tools like pip or uv." + ) def initialize_options(self) -> None: ... - args: Any - egg_link: Any - egg_base: Any - dist: Any def finalize_options(self) -> None: ... - def install_for_development(self) -> None: ... - def uninstall_link(self) -> None: ... - def install_egg_scripts(self, dist): ... - def install_wrapper_scripts(self, dist): ... -class VersionlessRequirement: - def __init__(self, dist) -> None: ... - def __getattr__(self, name): ... - def as_requirement(self): ... +class DevelopDeprecationWarning(SetuptoolsDeprecationWarning): ... diff --git a/stubs/setuptools/setuptools/command/dist_info.pyi b/stubs/setuptools/setuptools/command/dist_info.pyi index aa9d3f40911d..1343b926905b 100644 --- a/stubs/setuptools/setuptools/command/dist_info.pyi +++ b/stubs/setuptools/setuptools/command/dist_info.pyi @@ -1,10 +1,12 @@ -from distutils.core import Command -from typing import Any +from typing import ClassVar + +from .._distutils.cmd import Command class dist_info(Command): description: str - user_options: Any - egg_base: Any + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/easy_install.pyi b/stubs/setuptools/setuptools/command/easy_install.pyi index 11f8224e69ad..101bc1d69449 100644 --- a/stubs/setuptools/setuptools/command/easy_install.pyi +++ b/stubs/setuptools/setuptools/command/easy_install.pyi @@ -1,150 +1,11 @@ -from typing import Any, List +from abc import abstractmethod -from pkg_resources import Environment -from setuptools import Command, SetuptoolsDeprecationWarning - -def samefile(p1, p2): ... +from setuptools import Command class easy_install(Command): - description: str - command_consumes_arguments: bool - user_options: Any - boolean_options: Any - negative_opt: Any - create_index: Any - user: int - zip_ok: Any - install_dir: Any - index_url: Any - find_links: Any - build_directory: Any - args: Any - optimize: Any - upgrade: Any - editable: Any - root: Any - version: Any - install_purelib: Any - install_platlib: Any - install_headers: Any - install_lib: Any - install_scripts: Any - install_data: Any - install_base: Any - install_platbase: Any - install_userbase: Any - install_usersite: Any - no_find_links: Any - package_index: Any - pth_file: Any - site_dirs: Any - installed_projects: Any - verbose: Any + @abstractmethod def initialize_options(self) -> None: ... - def delete_blockers(self, blockers) -> None: ... - config_vars: Any - script_dir: Any - all_site_dirs: Any - shadow_path: Any - local_index: Any - outputs: Any + @abstractmethod def finalize_options(self) -> None: ... - def expand_basedirs(self) -> None: ... - def expand_dirs(self) -> None: ... - def run(self, show_deprecation: bool = ...) -> None: ... - def pseudo_tempname(self): ... - def warn_deprecated_options(self) -> None: ... - def check_site_dir(self) -> None: ... - def cant_write_to_target(self) -> None: ... - def check_pth_processing(self): ... - def install_egg_scripts(self, dist) -> None: ... - def add_output(self, path) -> None: ... - def not_editable(self, spec) -> None: ... - def check_editable(self, spec) -> None: ... - def easy_install(self, spec, deps: bool = ...): ... - def install_item(self, spec, download, tmpdir, deps, install_needed: bool = ...): ... - def select_scheme(self, name) -> None: ... - def process_distribution(self, requirement, dist, deps: bool = ..., *info) -> None: ... - def should_unzip(self, dist): ... - def maybe_move(self, spec, dist_filename, setup_base): ... - def install_wrapper_scripts(self, dist) -> None: ... - def install_script(self, dist, script_name, script_text, dev_path: Any | None = ...) -> None: ... - def write_script(self, script_name, contents, mode: str = ..., blockers=...) -> None: ... - def install_eggs(self, spec, dist_filename, tmpdir): ... - def egg_distribution(self, egg_path): ... - def install_egg(self, egg_path, tmpdir): ... - def install_exe(self, dist_filename, tmpdir): ... - def exe_to_egg(self, dist_filename, egg_tmp): ... - def install_wheel(self, wheel_path, tmpdir): ... - def installation_report(self, req, dist, what: str = ...): ... - def report_editable(self, spec, setup_script): ... - def run_setup(self, setup_script, setup_base, args) -> None: ... - def build_and_install(self, setup_script, setup_base): ... - def update_pth(self, dist) -> None: ... - def unpack_progress(self, src, dst): ... - def unpack_and_compile(self, egg_path, destination): ... - def byte_compile(self, to_compile) -> None: ... - def create_home_path(self) -> None: ... - INSTALL_SCHEMES: Any - DEFAULT_SCHEME: Any - -def extract_wininst_cfg(dist_filename): ... -def get_exe_prefixes(exe_filename): ... - -class PthDistributions(Environment): - dirty: bool - filename: Any - sitedirs: Any - basedir: Any - def __init__(self, filename, sitedirs=...) -> None: ... - def save(self) -> None: ... - def add(self, dist) -> None: ... - def remove(self, dist) -> None: ... - def make_relative(self, path): ... - -class RewritePthDistributions(PthDistributions): - prelude: Any - postlude: Any - -class CommandSpec(List[str]): - options: Any - split_args: Any - @classmethod - def best(cls): ... - @classmethod - def from_param(cls, param): ... - @classmethod - def from_environment(cls): ... - @classmethod - def from_string(cls, string): ... - def install_options(self, script_text) -> None: ... - def as_header(self): ... - -class WindowsCommandSpec(CommandSpec): - split_args: Any - -class ScriptWriter: - template: Any - command_spec_class: Any - @classmethod - def get_script_args(cls, dist, executable: Any | None = ..., wininst: bool = ...): ... - @classmethod - def get_script_header(cls, script_text, executable: Any | None = ..., wininst: bool = ...): ... - @classmethod - def get_args(cls, dist, header: Any | None = ...) -> None: ... - @classmethod - def get_writer(cls, force_windows): ... - @classmethod - def best(cls): ... - @classmethod - def get_header(cls, script_text: str = ..., executable: Any | None = ...): ... - -class WindowsScriptWriter(ScriptWriter): - command_spec_class: Any - @classmethod - def get_writer(cls): ... - @classmethod - def best(cls): ... - -class WindowsExecutableLauncherWriter(WindowsScriptWriter): ... -class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning): ... + @abstractmethod + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/editable_wheel.pyi b/stubs/setuptools/setuptools/command/editable_wheel.pyi new file mode 100644 index 000000000000..d9aececdac84 --- /dev/null +++ b/stubs/setuptools/setuptools/command/editable_wheel.pyi @@ -0,0 +1,78 @@ +from _typeshed import Incomplete, StrPath, Unused +from collections.abc import Iterator, Mapping +from enum import Enum +from pathlib import Path +from types import TracebackType +from typing import ClassVar, Protocol, TypeAlias +from typing_extensions import Self + +from .. import Command, errors, namespaces +from ..dist import Distribution +from ..warnings import SetuptoolsWarning + +# Actually from wheel.wheelfile import WheelFile +_WheelFile: TypeAlias = Incomplete + +class _EditableMode(Enum): + STRICT = "strict" + LENIENT = "lenient" + COMPAT = "compat" + @classmethod + def convert(cls, mode: str | None) -> _EditableMode: ... + +class editable_wheel(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + dist_dir: Incomplete + dist_info_dir: Incomplete + project_dir: Incomplete + mode: Incomplete + def initialize_options(self) -> None: ... + package_dir: dict[Incomplete, Incomplete] + def finalize_options(self) -> None: ... + def run(self) -> None: ... + +class EditableStrategy(Protocol): + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]) -> Unused: ... + def __enter__(self) -> Self: ... + def __exit__( + self, _exc_type: type[BaseException] | None, _exc_value: BaseException | None, _traceback: TracebackType | None + ) -> Unused: ... + +class _StaticPth: + dist: Distribution + name: str + path_entries: list[Path] + def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None: ... + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]): ... + def __enter__(self) -> Self: ... + def __exit__(self, _exc_type: Unused, _exc_value: Unused, _traceback: Unused) -> None: ... + +class _LinkTree(_StaticPth): + auxiliary_dir: Path + build_lib: Path + def __init__(self, dist: Distribution, name: str, auxiliary_dir: StrPath, build_lib: StrPath) -> None: ... + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]): ... + def __enter__(self) -> Self: ... + def __exit__(self, _exc_type: Unused, _exc_value: Unused, _traceback: Unused) -> None: ... + +class _TopLevelFinder: + dist: Distribution + name: str + def __init__(self, dist: Distribution, name: str) -> None: ... + def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]: ... + def get_implementation(self) -> Iterator[tuple[str, bytes]]: ... + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]): ... + def __enter__(self) -> Self: ... + def __exit__(self, _exc_type: Unused, _exc_value: Unused, _traceback: Unused) -> None: ... + +class _NamespaceInstaller(namespaces.Installer): + distribution: Incomplete + src_root: Incomplete + installation_dir: Incomplete + editable_name: Incomplete + outputs: list[str] + def __init__(self, distribution, installation_dir, editable_name, src_root) -> None: ... + +class InformationOnly(SetuptoolsWarning): ... +class LinksNotSupported(errors.FileError): ... diff --git a/stubs/setuptools/setuptools/command/egg_info.pyi b/stubs/setuptools/setuptools/command/egg_info.pyi index 3be97afb49c2..10069f414f16 100644 --- a/stubs/setuptools/setuptools/command/egg_info.pyi +++ b/stubs/setuptools/setuptools/command/egg_info.pyi @@ -1,46 +1,51 @@ -from distutils.filelist import FileList as _FileList -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar, Final -from setuptools import Command, SetuptoolsDeprecationWarning -from setuptools.command.sdist import sdist +from .. import Command, SetuptoolsDeprecationWarning +from .._distutils.filelist import FileList as _FileList +from .sdist import sdist + +PY_MAJOR: Final[str] def translate_pattern(glob): ... class InfoCommon: - tag_build: Any - tag_date: Any + tag_build: Incomplete + tag_date: Incomplete @property def name(self): ... def tagged_version(self): ... def tags(self): ... - vtags: Any + @property + def vtags(self): ... class egg_info(InfoCommon, Command): description: str - user_options: Any - boolean_options: Any - negative_opt: Any - egg_base: Any - egg_name: Any - egg_info: Any - egg_version: Any - broken_egg_info: bool + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + egg_base: Incomplete + egg_name: Incomplete + egg_info: Incomplete + egg_version: Incomplete def initialize_options(self) -> None: ... + @property - def tag_svn_revision(self) -> None: ... + def tag_svn_revision(self) -> int | None: ... @tag_svn_revision.setter def tag_svn_revision(self, value) -> None: ... + def save_version_info(self, filename) -> None: ... def finalize_options(self) -> None: ... - def write_or_delete_file(self, what, filename, data, force: bool = ...) -> None: ... + def write_or_delete_file(self, what, filename, data, force: bool = False) -> None: ... def write_file(self, what, filename, data) -> None: ... def delete_file(self, filename) -> None: ... def run(self) -> None: ... - filelist: Any + filelist: Incomplete def find_sources(self) -> None: ... - def check_broken_egg_info(self) -> None: ... class FileList(_FileList): + def __init__(self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False) -> None: ... def process_template_line(self, line) -> None: ... def include(self, pattern): ... def exclude(self, pattern): ... @@ -55,19 +60,18 @@ class FileList(_FileList): class manifest_maker(sdist): template: str - use_defaults: int - prune: int - manifest_only: int - force_manifest: int + use_defaults: bool + prune: bool + manifest_only: bool + force_manifest: bool def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... - filelist: Any + filelist: FileList def run(self) -> None: ... def write_manifest(self) -> None: ... def warn(self, msg) -> None: ... def add_defaults(self) -> None: ... def add_license_files(self) -> None: ... - def prune_file_list(self) -> None: ... def write_file(filename, contents) -> None: ... def write_pkg_info(cmd, basename, filename) -> None: ... @@ -76,8 +80,7 @@ def write_requirements(cmd, basename, filename) -> None: ... def write_setup_requirements(cmd, basename, filename) -> None: ... def write_toplevel_names(cmd, basename, filename) -> None: ... def overwrite_arg(cmd, basename, filename) -> None: ... -def write_arg(cmd, basename, filename, force: bool = ...) -> None: ... +def write_arg(cmd, basename, filename, force: bool = False) -> None: ... def write_entries(cmd, basename, filename) -> None: ... -def get_pkg_info_revision(): ... class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning): ... diff --git a/stubs/setuptools/setuptools/command/install.pyi b/stubs/setuptools/setuptools/command/install.pyi index 50594f2d3102..2c4e07f318e2 100644 --- a/stubs/setuptools/setuptools/command/install.pyi +++ b/stubs/setuptools/setuptools/command/install.pyi @@ -1,16 +1,21 @@ -import distutils.command.install as orig -from typing import Any +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, ClassVar + +from setuptools.dist import Distribution + +from .._distutils.command import install as orig class install(orig.install): - user_options: Any - boolean_options: Any - new_commands: Any - old_and_unmanageable: Any - single_version_externally_managed: Any + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + # Any to work around variance issues + new_commands: ClassVar[list[tuple[str, Callable[[Any], bool]] | None]] + old_and_unmanageable: Incomplete + single_version_externally_managed: bool | None def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... - path_file: Any + path_file: Incomplete extra_dirs: str def handle_extra_path(self): ... - def run(self): ... - def do_egg_install(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/install_egg_info.pyi b/stubs/setuptools/setuptools/command/install_egg_info.pyi index 2977e32c280e..2c32f1a6bac2 100644 --- a/stubs/setuptools/setuptools/command/install_egg_info.pyi +++ b/stubs/setuptools/setuptools/command/install_egg_info.pyi @@ -1,15 +1,16 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar -from setuptools import Command, namespaces +from .. import Command, namespaces class install_egg_info(namespaces.Installer, Command): description: str - user_options: Any - install_dir: Any + user_options: ClassVar[list[tuple[str, str, str]]] + install_dir: Incomplete def initialize_options(self) -> None: ... - source: Any - target: Any - outputs: Any + source: Incomplete + target: str + outputs: list[str] def finalize_options(self) -> None: ... def run(self) -> None: ... def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/command/install_lib.pyi b/stubs/setuptools/setuptools/command/install_lib.pyi index cd76c475216d..a7576d20a35a 100644 --- a/stubs/setuptools/setuptools/command/install_lib.pyi +++ b/stubs/setuptools/setuptools/command/install_lib.pyi @@ -1,9 +1,20 @@ -import distutils.command.install_lib as orig +from _typeshed import StrPath, Unused + +from setuptools.dist import Distribution + +from .._distutils.command import install_lib as orig class install_lib(orig.install_lib): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution def run(self) -> None: ... def get_exclusions(self): ... def copy_tree( - self, infile, outfile, preserve_mode: int = ..., preserve_times: int = ..., preserve_symlinks: int = ..., level: int = ... + self, + infile: StrPath, + outfile: str, + preserve_mode: bool = True, + preserve_times: bool = True, + preserve_symlinks: bool = False, + level: Unused = 1, ): ... def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/command/install_scripts.pyi b/stubs/setuptools/setuptools/command/install_scripts.pyi index 354faa7f04a2..f131b0f7c4fa 100644 --- a/stubs/setuptools/setuptools/command/install_scripts.pyi +++ b/stubs/setuptools/setuptools/command/install_scripts.pyi @@ -1,9 +1,11 @@ -import distutils.command.install_scripts as orig -from typing import Any +from setuptools.dist import Distribution + +from .._distutils.command import install_scripts as orig class install_scripts(orig.install_scripts): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution no_ep: bool def initialize_options(self) -> None: ... - outfiles: Any + outfiles: list[str] def run(self) -> None: ... - def write_script(self, script_name, contents, mode: str = ..., *ignored) -> None: ... + def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None: ... diff --git a/stubs/setuptools/setuptools/command/py36compat.pyi b/stubs/setuptools/setuptools/command/py36compat.pyi deleted file mode 100644 index 2143abc0577b..000000000000 --- a/stubs/setuptools/setuptools/command/py36compat.pyi +++ /dev/null @@ -1,5 +0,0 @@ -import sys - -class sdist_add_defaults: - if sys.version_info < (3, 7): - def add_defaults(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/register.pyi b/stubs/setuptools/setuptools/command/register.pyi deleted file mode 100644 index 02c63f18e193..000000000000 --- a/stubs/setuptools/setuptools/command/register.pyi +++ /dev/null @@ -1,4 +0,0 @@ -import distutils.command.register as orig - -class register(orig.register): - def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/rotate.pyi b/stubs/setuptools/setuptools/command/rotate.pyi index 5d5de6f18e01..653a380bc29a 100644 --- a/stubs/setuptools/setuptools/command/rotate.pyi +++ b/stubs/setuptools/setuptools/command/rotate.pyi @@ -1,14 +1,15 @@ -from typing import Any +from _typeshed import Incomplete +from typing import ClassVar -from setuptools import Command +from .. import Command class rotate(Command): description: str - user_options: Any - boolean_options: Any - match: Any - dist_dir: Any - keep: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + match: Incomplete + dist_dir: Incomplete + keep: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/saveopts.pyi b/stubs/setuptools/setuptools/command/saveopts.pyi index 09d435c6343a..c96862b29284 100644 --- a/stubs/setuptools/setuptools/command/saveopts.pyi +++ b/stubs/setuptools/setuptools/command/saveopts.pyi @@ -1,4 +1,4 @@ -from setuptools.command.setopt import option_base +from .setopt import option_base class saveopts(option_base): description: str diff --git a/stubs/setuptools/setuptools/command/sdist.pyi b/stubs/setuptools/setuptools/command/sdist.pyi index 0d150e7ee672..77c87df95d0b 100644 --- a/stubs/setuptools/setuptools/command/sdist.pyi +++ b/stubs/setuptools/setuptools/command/sdist.pyi @@ -1,19 +1,24 @@ -import distutils.command.sdist as orig -from typing import Any +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar -from .py36compat import sdist_add_defaults +from setuptools.dist import Distribution -def walk_revctrl(dirname: str = ...) -> None: ... +from .._distutils.command import sdist as orig -class sdist(sdist_add_defaults, orig.sdist): - user_options: Any - negative_opt: Any - README_EXTENSIONS: Any - READMES: Any - filelist: Any +def walk_revctrl(dirname: str = "") -> Iterator[Incomplete]: ... + +class sdist(orig.sdist): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + user_options: ClassVar[list[tuple[str, str | None, str]]] + negative_opt: ClassVar[dict[str, str]] + README_EXTENSIONS: ClassVar[list[str]] + READMES: ClassVar[tuple[str, ...]] + filelist: Incomplete def run(self) -> None: ... def initialize_options(self) -> None: ... def make_distribution(self) -> None: ... + def prune_file_list(self) -> None: ... def check_readme(self) -> None: ... def make_release_tree(self, base_dir, files) -> None: ... def read_manifest(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/setopt.pyi b/stubs/setuptools/setuptools/command/setopt.pyi index 0461717a9b64..62957a112fa4 100644 --- a/stubs/setuptools/setuptools/command/setopt.pyi +++ b/stubs/setuptools/setuptools/command/setopt.pyi @@ -1,17 +1,20 @@ +from _typeshed import Incomplete from abc import abstractmethod -from typing import Any +from typing import ClassVar -from setuptools import Command +from .. import Command -def config_file(kind: str = ...): ... -def edit_config(filename, settings, dry_run: bool = ...) -> None: ... +__all__ = ["config_file", "edit_config", "option_base", "setopt"] + +def config_file(kind: str = "local"): ... +def edit_config(filename, settings) -> None: ... class option_base(Command): - user_options: Any - boolean_options: Any - global_config: Any - user_config: Any - filename: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + global_config: Incomplete + user_config: Incomplete + filename: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... @abstractmethod @@ -19,12 +22,12 @@ class option_base(Command): class setopt(option_base): description: str - user_options: Any - boolean_options: Any - command: Any - option: Any - set_value: Any - remove: Any + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + command: Incomplete + option: Incomplete + set_value: Incomplete + remove: Incomplete def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/test.pyi b/stubs/setuptools/setuptools/command/test.pyi index 8d0309ab023e..536179f18f09 100644 --- a/stubs/setuptools/setuptools/command/test.pyi +++ b/stubs/setuptools/setuptools/command/test.pyi @@ -1,40 +1,15 @@ -from _typeshed import Self -from types import ModuleType -from typing import Any, Callable, Generic, TypeVar, overload -from unittest import TestLoader, TestSuite +from typing import ClassVar +from typing_extensions import Never, deprecated -from setuptools import Command - -_T = TypeVar("_T") - -class ScanningLoader(TestLoader): - def __init__(self) -> None: ... - def loadTestsFromModule(self, module: ModuleType, pattern: Any | None = ...) -> list[TestSuite]: ... # type: ignore[override] - -class NonDataProperty(Generic[_T]): - fget: Callable[..., _T] - def __init__(self, fget: Callable[..., _T]) -> None: ... - @overload - def __get__(self: Self, obj: None, objtype: object = ...) -> Self: ... - @overload - def __get__(self, obj: Any, objtype: object = ...) -> _T: ... +from .. import Command +@deprecated("""\ +The test command is disabled and references to it are deprecated. \ +Please remove any references to `setuptools.command.test` in all supported versions of the affected package.\ +""") class test(Command): - description: str - user_options: Any - test_suite: Any - test_module: Any - test_loader: Any - test_runner: Any + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str, str]]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... - # TODO: uncomment once https://github.com/python/mypy/pull/10884 is released - # def test_args(self): ... - def with_project_on_sys_path(self, func) -> None: ... - def project_on_sys_path(self, include_dists=...): ... - @staticmethod - def paths_on_pythonpath(paths) -> None: ... - @staticmethod - def install_dists(dist): ... - def run(self) -> None: ... - def run_tests(self) -> None: ... + def run(self) -> Never: ... diff --git a/stubs/setuptools/setuptools/command/upload.pyi b/stubs/setuptools/setuptools/command/upload.pyi deleted file mode 100644 index ea60d6e6b5ec..000000000000 --- a/stubs/setuptools/setuptools/command/upload.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from distutils.command import upload as orig - -class upload(orig.upload): - def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/upload_docs.pyi b/stubs/setuptools/setuptools/command/upload_docs.pyi deleted file mode 100644 index 0660bff722dd..000000000000 --- a/stubs/setuptools/setuptools/command/upload_docs.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any, ClassVar - -from .upload import upload - -class upload_docs(upload): - DEFAULT_REPOSITORY: ClassVar[str] - description: ClassVar[str] - user_options: ClassVar[list[tuple[str, str | None, str]]] - boolean_options: ClassVar[list[str]] - def has_sphinx(self): ... - sub_commands: Any - upload_dir: Any - target_dir: Any - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def create_zipfile(self, filename) -> None: ... - def run(self) -> None: ... - def upload_file(self, filename) -> None: ... # type: ignore[override] diff --git a/stubs/setuptools/setuptools/config.pyi b/stubs/setuptools/setuptools/config.pyi deleted file mode 100644 index fb1862c1cd89..000000000000 --- a/stubs/setuptools/setuptools/config.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Any - -class StaticModule: - def __init__(self, name) -> None: ... - def __getattr__(self, attr): ... - -def patch_path(path) -> None: ... -def read_configuration(filepath, find_others: bool = ..., ignore_option_errors: bool = ...): ... -def configuration_to_dict(handlers): ... -def parse_configuration(distribution, command_options, ignore_option_errors: bool = ...): ... - -class ConfigHandler: - section_prefix: Any - aliases: Any - ignore_option_errors: Any - target_obj: Any - sections: Any - set_options: Any - def __init__(self, target_obj, options, ignore_option_errors: bool = ...) -> None: ... - @property - def parsers(self) -> None: ... - def __setitem__(self, option_name, value) -> None: ... - def parse_section(self, section_options) -> None: ... - def parse(self) -> None: ... - -class ConfigMetadataHandler(ConfigHandler): - section_prefix: str - aliases: Any - strict_mode: bool - package_dir: Any - def __init__(self, target_obj, options, ignore_option_errors: bool = ..., package_dir: Any | None = ...) -> None: ... - @property - def parsers(self): ... - -class ConfigOptionsHandler(ConfigHandler): - section_prefix: str - @property - def parsers(self): ... - def parse_section_packages__find(self, section_options): ... - def parse_section_entry_points(self, section_options) -> None: ... - def parse_section_package_data(self, section_options) -> None: ... - def parse_section_exclude_package_data(self, section_options) -> None: ... - def parse_section_extras_require(self, section_options) -> None: ... - def parse_section_data_files(self, section_options) -> None: ... diff --git a/stubs/setuptools/setuptools/config/__init__.pyi b/stubs/setuptools/setuptools/config/__init__.pyi new file mode 100644 index 000000000000..61e17fdccf16 --- /dev/null +++ b/stubs/setuptools/setuptools/config/__init__.pyi @@ -0,0 +1,3 @@ +from .setupcfg import parse_configuration as parse_configuration, read_configuration as read_configuration + +__all__ = ("parse_configuration", "read_configuration") diff --git a/stubs/setuptools/setuptools/config/expand.pyi b/stubs/setuptools/setuptools/config/expand.pyi new file mode 100644 index 000000000000..c85a43bfcfea --- /dev/null +++ b/stubs/setuptools/setuptools/config/expand.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Callable, Iterable, Iterator, Mapping +from importlib.machinery import ModuleSpec +from types import TracebackType +from typing import TypeVar +from typing_extensions import Self + +from ..dist import Distribution + +_K = TypeVar("_K") +_V_co = TypeVar("_V_co", covariant=True) + +class StaticModule: + def __init__(self, name: str, spec: ModuleSpec) -> None: ... + def __getattr__(self, attr: str): ... + +def glob_relative(patterns: Iterable[str], root_dir: StrPath | None = None) -> list[str]: ... +def read_files(filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None) -> str: ... +def read_attr(attr_desc: str, package_dir: Mapping[str, str] | None = None, root_dir: StrPath | None = None): ... +def resolve_class( + qualified_class_name: str, package_dir: Mapping[str, str] | None = None, root_dir: StrPath | None = None +) -> Callable[..., Incomplete]: ... +def cmdclass( + values: dict[str, str], package_dir: Mapping[str, str] | None = None, root_dir: StrPath | None = None +) -> dict[str, Callable[..., Incomplete]]: ... +def find_packages( + *, namespaces: bool = True, fill_package_dir: dict[str, str] | None = None, root_dir: StrPath | None = None, **kwargs +) -> list[str]: ... +def version(value: Callable[[], Incomplete] | Iterable[str | int] | str) -> str: ... +def canonic_package_data(package_data: dict[Incomplete, Incomplete]) -> dict[Incomplete, Incomplete]: ... +def canonic_data_files( + data_files: list[Incomplete] | dict[Incomplete, Incomplete], root_dir: StrPath | None = None +) -> list[tuple[str, list[str]]]: ... +def entry_points(text: str, text_source: str = "entry-points") -> dict[str, dict[str, str]]: ... + +class EnsurePackagesDiscovered: + def __init__(self, distribution: Distribution) -> None: ... + def __call__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + @property + def package_dir(self) -> LazyMappingProxy[str, str]: ... + +class LazyMappingProxy(Mapping[_K, _V_co]): + def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None: ... + def __getitem__(self, key: _K) -> _V_co: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_K]: ... diff --git a/stubs/setuptools/setuptools/config/pyprojecttoml.pyi b/stubs/setuptools/setuptools/config/pyprojecttoml.pyi new file mode 100644 index 000000000000..45febbdafb2d --- /dev/null +++ b/stubs/setuptools/setuptools/config/pyprojecttoml.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete, StrPath +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from ..dist import Distribution +from . import expand + +def load_file(filepath: StrPath) -> dict[Incomplete, Incomplete]: ... +def validate(config: dict[Incomplete, Incomplete], filepath: StrPath) -> bool: ... +def apply_configuration(dist: Distribution, filepath: StrPath, ignore_option_errors: bool = False) -> Distribution: ... +def read_configuration( + filepath: StrPath, expand: bool = True, ignore_option_errors: bool = False, dist: Distribution | None = None +) -> dict[str, Any]: ... +def expand_configuration( + config: dict[Incomplete, Incomplete], + root_dir: StrPath | None = None, + ignore_option_errors: bool = False, + dist: Distribution | None = None, +) -> dict[Incomplete, Incomplete]: ... + +class _ConfigExpander: + config: dict[Incomplete, Incomplete] + root_dir: StrPath + project_cfg: Incomplete + dynamic: Incomplete + setuptools_cfg: Incomplete + dynamic_cfg: Incomplete + ignore_option_errors: bool + def __init__( + self, + config: dict[Incomplete, Incomplete], + root_dir: StrPath | None = None, + ignore_option_errors: bool = False, + dist: Distribution | None = None, + ) -> None: ... + def expand(self): ... + +class _EnsurePackagesDiscovered(expand.EnsurePackagesDiscovered): + def __init__( + self, distribution: Distribution, project_cfg: dict[Incomplete, Incomplete], setuptools_cfg: dict[Incomplete, Incomplete] + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... diff --git a/stubs/setuptools/setuptools/config/setupcfg.pyi b/stubs/setuptools/setuptools/config/setupcfg.pyi new file mode 100644 index 000000000000..35eb6821565f --- /dev/null +++ b/stubs/setuptools/setuptools/config/setupcfg.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete, StrPath +from abc import abstractmethod +from collections.abc import Callable, Iterable +from typing import Any, ClassVar, Generic, TypeAlias, TypeVar + +from .._distutils.dist import DistributionMetadata +from ..dist import Distribution +from . import expand + +SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]] +AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions] +Target = TypeVar("Target", Distribution, DistributionMetadata) # noqa: Y001 # Exists at runtime + +def read_configuration( + filepath: StrPath, find_others: bool = False, ignore_option_errors: bool = False +) -> dict[Incomplete, Incomplete]: ... +def apply_configuration(dist: Distribution, filepath: StrPath) -> Distribution: ... +def configuration_to_dict( + handlers: Iterable[ConfigHandler[Distribution] | ConfigHandler[DistributionMetadata]], +) -> dict[Incomplete, Incomplete]: ... +def parse_configuration( + distribution: Distribution, command_options: AllCommandOptions, ignore_option_errors: bool = False +) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]: ... + +class ConfigHandler(Generic[Target]): + section_prefix: str + aliases: ClassVar[dict[str, str]] + ignore_option_errors: Incomplete + target_obj: Target + sections: dict[str, SingleCommandOptions] + set_options: list[str] + ensure_discovered: expand.EnsurePackagesDiscovered + def __init__( + self, + target_obj: Target, + options: AllCommandOptions, + ignore_option_errors, + ensure_discovered: expand.EnsurePackagesDiscovered, + ) -> None: ... + @property + @abstractmethod + def parsers(self) -> dict[str, Callable[..., Incomplete]]: ... + def __setitem__(self, option_name, value): ... + def parse_section(self, section_options) -> None: ... + def parse(self) -> None: ... + +class ConfigMetadataHandler(ConfigHandler[DistributionMetadata]): + section_prefix: str + aliases: ClassVar[dict[str, str]] + strict_mode: bool + package_dir: dict[Incomplete, Incomplete] | None + root_dir: StrPath | None + def __init__( + self, + target_obj: DistributionMetadata, + options: AllCommandOptions, + ignore_option_errors: bool, + ensure_discovered: expand.EnsurePackagesDiscovered, + package_dir: dict[Incomplete, Incomplete] | None = None, + root_dir: StrPath | None = ".", + ) -> None: ... + @property + def parsers(self) -> dict[str, Callable[..., Incomplete]]: ... + +class ConfigOptionsHandler(ConfigHandler[Distribution]): + section_prefix: str + root_dir: str | None + package_dir: dict[str, str] + def __init__( + self, + target_obj: Distribution, + options: AllCommandOptions, + ignore_option_errors: bool, + ensure_discovered: expand.EnsurePackagesDiscovered, + ) -> None: ... + @property + def parsers(self) -> dict[str, Callable[..., Incomplete]]: ... + def parse_section_packages__find(self, section_options): ... + def parse_section_entry_points(self, section_options) -> None: ... + def parse_section_package_data(self, section_options) -> None: ... + def parse_section_exclude_package_data(self, section_options) -> None: ... + def parse_section_extras_require(self, section_options) -> None: ... + def parse_section_data_files(self, section_options) -> None: ... diff --git a/stubs/setuptools/setuptools/dep_util.pyi b/stubs/setuptools/setuptools/dep_util.pyi deleted file mode 100644 index 0ac008029257..000000000000 --- a/stubs/setuptools/setuptools/dep_util.pyi +++ /dev/null @@ -1 +0,0 @@ -def newer_pairwise_group(sources_groups, targets): ... diff --git a/stubs/setuptools/setuptools/depends.pyi b/stubs/setuptools/setuptools/depends.pyi index 13a011bef17e..64c5cb9afa89 100644 --- a/stubs/setuptools/setuptools/depends.pyi +++ b/stubs/setuptools/setuptools/depends.pyi @@ -1,14 +1,20 @@ -from typing import Any +from typing import IO, Any, Literal, TypeVar + +_T = TypeVar("_T") + +__all__ = ["Require", "find_module", "get_module_constant", "extract_constant"] + +def find_module( + module, paths=None +) -> tuple[IO[Any], str | None, tuple[str, Literal["", "r", "rb"], Literal[7, 6, 1, 2, 3, -1]]]: ... class Require: - def __init__( - self, name, requested_version, module, homepage: str = ..., attribute: Any | None = ..., format: Any | None = ... - ) -> None: ... + def __init__(self, name, requested_version, module, homepage: str = "", attribute=None, format=None) -> None: ... def full_name(self): ... def version_ok(self, version): ... - def get_version(self, paths: Any | None = ..., default: str = ...): ... - def is_present(self, paths: Any | None = ...): ... - def is_current(self, paths: Any | None = ...): ... + def get_version(self, paths=None, default: _T | Literal["unknown"] = "unknown") -> _T | Literal["unknown"] | Any | None: ... + def is_present(self, paths=None): ... + def is_current(self, paths=None): ... -def get_module_constant(module, symbol, default: int = ..., paths: Any | None = ...): ... -def extract_constant(code, symbol, default: int = ...): ... +def get_module_constant(module, symbol, default: _T | int = -1, paths=None) -> _T | int | Any | None: ... +def extract_constant(code, symbol, default: _T | int = -1) -> _T | int | Any | None: ... diff --git a/stubs/setuptools/setuptools/discovery.pyi b/stubs/setuptools/setuptools/discovery.pyi new file mode 100644 index 000000000000..9059a381f578 --- /dev/null +++ b/stubs/setuptools/setuptools/discovery.pyi @@ -0,0 +1,43 @@ +import itertools +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Mapping +from typing import ClassVar + +from . import Distribution + +chain_iter = itertools.chain.from_iterable + +class _Filter: + def __init__(self, *patterns: str) -> None: ... + def __call__(self, item: str) -> bool: ... + def __contains__(self, item: str) -> bool: ... + +class _Finder: + ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] + @classmethod + def find(cls, where: StrPath = ".", exclude: Iterable[str] = (), include: Iterable[str] = ("*",)) -> list[str]: ... + +class PackageFinder(_Finder): + ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] + +class PEP420PackageFinder(PackageFinder): ... +class ModuleFinder(_Finder): ... + +class FlatLayoutPackageFinder(PEP420PackageFinder): + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] + +class FlatLayoutModuleFinder(ModuleFinder): + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] + +class ConfigDiscovery: + dist: Incomplete + def __init__(self, distribution: Distribution) -> None: ... + def __call__(self, force: bool = False, name: bool = True, ignore_ext_modules: bool = False) -> None: ... + def analyse_name(self) -> None: ... + +def remove_nested_packages(packages: list[str]) -> list[str]: ... +def remove_stubs(packages: list[str]) -> list[str]: ... +def find_parent_package(packages: list[str], package_dir: Mapping[str, str], root_dir: StrPath) -> str | None: ... +def find_package_path(name: str, package_dir: Mapping[str, str], root_dir: StrPath) -> str: ... +def construct_package_dir(packages: list[str], package_path: StrPath) -> dict[str, str]: ... diff --git a/stubs/setuptools/setuptools/dist.pyi b/stubs/setuptools/setuptools/dist.pyi index a53f22bc379b..a17b46c69fe9 100644 --- a/stubs/setuptools/setuptools/dist.pyi +++ b/stubs/setuptools/setuptools/dist.pyi @@ -1,35 +1,199 @@ -from distutils.core import Distribution as _Distribution -from typing import Any +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Iterator, MutableMapping +from importlib import metadata +from typing import Literal, TypeVar, overload -from setuptools import SetuptoolsDeprecationWarning +from . import Command, SetuptoolsDeprecationWarning +from ._distutils.cmd import Command as _Command +from ._distutils.dist import Distribution as _Distribution +from .command.alias import alias +from .command.bdist_egg import bdist_egg +from .command.bdist_rpm import bdist_rpm +from .command.bdist_wheel import bdist_wheel +from .command.build import build +from .command.build_clib import build_clib +from .command.build_ext import build_ext +from .command.build_py import build_py +from .command.develop import develop +from .command.dist_info import dist_info +from .command.easy_install import easy_install +from .command.editable_wheel import editable_wheel +from .command.egg_info import egg_info +from .command.install import install +from .command.install_egg_info import install_egg_info +from .command.install_lib import install_lib +from .command.install_scripts import install_scripts +from .command.rotate import rotate +from .command.saveopts import saveopts +from .command.sdist import sdist +from .command.setopt import setopt + +_CommandT = TypeVar("_CommandT", bound=_Command) + +__all__ = ["Distribution"] class Distribution(_Distribution): - def patch_missing_pkg_info(self, attrs) -> None: ... - package_data: Any - dist_files: Any - src_root: Any - dependency_links: Any - setup_requires: Any - def __init__(self, attrs: Any | None = ...) -> None: ... - def warn_dash_deprecation(self, opt, section): ... - def make_option_lowercase(self, opt, section): ... - def parse_config_files(self, filenames: Any | None = ..., ignore_option_errors: bool = ...) -> None: ... - def fetch_build_eggs(self, requires): ... - def finalize_options(self): ... - def get_egg_cache_dir(self): ... + include_package_data: bool | None + exclude_package_data: dict[str, list[str]] | None + src_root: str | None + dependency_links: list[str] + setup_requires: list[str] + def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ... + def parse_config_files(self, filenames: Iterable[StrPath] | None = None, ignore_option_errors: bool = False) -> None: ... + def fetch_build_eggs(self, requires: str | Iterable[str]) -> list[metadata.Distribution]: ... + def get_egg_cache_dir(self) -> str: ... def fetch_build_egg(self, req): ... - def get_command_class(self, command): ... - def print_commands(self): ... - def get_command_list(self): ... + + # NOTE: Commands that setuptools doesn't re-expose are considered deprecated (they must be imported from distutils directly) + # So we're not listing them here. This list comes directly from the setuptools/command folder. Minus the test command. + @overload # type: ignore[override] + def get_command_obj(self, command: Literal["alias"], create: Literal[1, True] = 1) -> alias: ... + @overload + def get_command_obj(self, command: Literal["bdist_egg"], create: Literal[1, True] = 1) -> bdist_egg: ... + @overload + def get_command_obj(self, command: Literal["bdist_rpm"], create: Literal[1, True] = 1) -> bdist_rpm: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["bdist_wheel"], create: Literal[1, True] = 1) -> bdist_wheel: ... + @overload + def get_command_obj(self, command: Literal["build"], create: Literal[1, True] = 1) -> build: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["build_clib"], create: Literal[1, True] = 1) -> build_clib: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["build_ext"], create: Literal[1, True] = 1) -> build_ext: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["build_py"], create: Literal[1, True] = 1) -> build_py: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["develop"], create: Literal[1, True] = 1) -> develop: ... + @overload + def get_command_obj(self, command: Literal["dist_info"], create: Literal[1, True] = 1) -> dist_info: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["easy_install"], create: Literal[1, True] = 1) -> easy_install: ... + @overload + def get_command_obj(self, command: Literal["editable_wheel"], create: Literal[1, True] = 1) -> editable_wheel: ... + @overload + def get_command_obj(self, command: Literal["egg_info"], create: Literal[1, True] = 1) -> egg_info: ... + @overload + def get_command_obj(self, command: Literal["install"], create: Literal[1, True] = 1) -> install: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["install_egg_info"], create: Literal[1, True] = 1) -> install_egg_info: ... + @overload + def get_command_obj(self, command: Literal["install_lib"], create: Literal[1, True] = 1) -> install_lib: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["install_scripts"], create: Literal[1, True] = 1) -> install_scripts: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["rotate"], create: Literal[1, True] = 1) -> rotate: ... + @overload + def get_command_obj(self, command: Literal["saveopts"], create: Literal[1, True] = 1) -> saveopts: ... + @overload + def get_command_obj(self, command: Literal["sdist"], create: Literal[1, True] = 1) -> sdist: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["setopt"], create: Literal[1, True] = 1) -> setopt: ... + @overload + def get_command_obj(self, command: str, create: Literal[1, True] = 1) -> Command: ... + # Not replicating the overloads for "Command | None", user may use "isinstance" + @overload + def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ... + + @overload + def get_command_class(self, command: Literal["alias"]) -> type[alias]: ... + @overload + def get_command_class(self, command: Literal["bdist_egg"]) -> type[bdist_egg]: ... + @overload + def get_command_class(self, command: Literal["bdist_rpm"]) -> type[bdist_rpm]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["bdist_wheel"]) -> type[bdist_wheel]: ... + @overload + def get_command_class(self, command: Literal["build"]) -> type[build]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["build_clib"]) -> type[build_clib]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["build_ext"]) -> type[build_ext]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["build_py"]) -> type[build_py]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["develop"]) -> type[develop]: ... + @overload + def get_command_class(self, command: Literal["dist_info"]) -> type[dist_info]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["easy_install"]) -> type[easy_install]: ... + @overload + def get_command_class(self, command: Literal["editable_wheel"]) -> type[editable_wheel]: ... + @overload + def get_command_class(self, command: Literal["egg_info"]) -> type[egg_info]: ... + @overload + def get_command_class(self, command: Literal["install"]) -> type[install]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["install_egg_info"]) -> type[install_egg_info]: ... + @overload + def get_command_class(self, command: Literal["install_lib"]) -> type[install_lib]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["install_scripts"]) -> type[install_scripts]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["rotate"]) -> type[rotate]: ... + @overload + def get_command_class(self, command: Literal["saveopts"]) -> type[saveopts]: ... + @overload + def get_command_class(self, command: Literal["sdist"]) -> type[sdist]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["setopt"]) -> type[setopt]: ... + @overload + def get_command_class(self, command: str) -> type[Command]: ... + + @overload # type: ignore[override] + def reinitialize_command(self, command: Literal["alias"], reinit_subcommands: bool = False) -> alias: ... + @overload + def reinitialize_command(self, command: Literal["bdist_egg"], reinit_subcommands: bool = False) -> bdist_egg: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool = False) -> bdist_rpm: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["bdist_wheel"], reinit_subcommands: bool = False) -> bdist_wheel: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool = False) -> build: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["build_clib"], reinit_subcommands: bool = False) -> build_clib: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool = False) -> build_ext: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool = False) -> build_py: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["develop"], reinit_subcommands: bool = False) -> develop: ... + @overload + def reinitialize_command(self, command: Literal["dist_info"], reinit_subcommands: bool = False) -> dist_info: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["easy_install"], reinit_subcommands: bool = False) -> easy_install: ... + @overload + def reinitialize_command(self, command: Literal["editable_wheel"], reinit_subcommands: bool = False) -> editable_wheel: ... + @overload + def reinitialize_command(self, command: Literal["egg_info"], reinit_subcommands: bool = False) -> egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool = False) -> install: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool = False + ) -> install_egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install_lib"], reinit_subcommands: bool = False) -> install_lib: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["install_scripts"], reinit_subcommands: bool = False) -> install_scripts: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["rotate"], reinit_subcommands: bool = False) -> rotate: ... + @overload + def reinitialize_command(self, command: Literal["saveopts"], reinit_subcommands: bool = False) -> saveopts: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool = False) -> sdist: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["setopt"], reinit_subcommands: bool = False) -> setopt: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + def include(self, **attrs) -> None: ... - packages: Any - py_modules: Any - ext_modules: Any - def exclude_package(self, package) -> None: ... - def has_contents_for(self, package): ... + def exclude_package(self, package: str) -> None: ... + def has_contents_for(self, package: str) -> bool: ... def exclude(self, **attrs) -> None: ... - def get_cmdline_options(self): ... - def iter_distribution_names(self) -> None: ... + def get_cmdline_options(self) -> dict[str, dict[str, str | None]]: ... + def iter_distribution_names(self) -> Iterator[str]: ... def handle_display_options(self, option_order): ... class DistDeprecationWarning(SetuptoolsDeprecationWarning): ... diff --git a/stubs/setuptools/setuptools/errors.pyi b/stubs/setuptools/setuptools/errors.pyi index 0791eeee9f47..9723a11d514f 100644 --- a/stubs/setuptools/setuptools/errors.pyi +++ b/stubs/setuptools/setuptools/errors.pyi @@ -1,3 +1,24 @@ -from distutils.errors import DistutilsError +from ._distutils import errors as _distutils_errors -class RemovedCommandError(DistutilsError, RuntimeError): ... +ByteCompileError = _distutils_errors.DistutilsByteCompileError +CCompilerError = _distutils_errors.CCompilerError +ClassError = _distutils_errors.DistutilsClassError +CompileError = _distutils_errors.CompileError +ExecError = _distutils_errors.DistutilsExecError +FileError = _distutils_errors.DistutilsFileError +InternalError = _distutils_errors.DistutilsInternalError +LibError = _distutils_errors.LibError +LinkError = _distutils_errors.LinkError +ModuleError = _distutils_errors.DistutilsModuleError +OptionError = _distutils_errors.DistutilsOptionError +PlatformError = _distutils_errors.DistutilsPlatformError +PreprocessError = _distutils_errors.PreprocessError +SetupError = _distutils_errors.DistutilsSetupError +TemplateError = _distutils_errors.DistutilsTemplateError +UnknownFileError = _distutils_errors.UnknownFileError +BaseError = _distutils_errors.DistutilsError + +class InvalidConfigError(OptionError): ... +class RemovedConfigError(OptionError): ... +class RemovedCommandError(BaseError, RuntimeError): ... +class PackageDiscoveryError(BaseError, RuntimeError): ... diff --git a/stubs/setuptools/setuptools/extension.pyi b/stubs/setuptools/setuptools/extension.pyi index ac7cf1c866b1..0f9c99214ad2 100644 --- a/stubs/setuptools/setuptools/extension.pyi +++ b/stubs/setuptools/setuptools/extension.pyi @@ -1,10 +1,32 @@ -from distutils.core import Extension as _Extension -from typing import Any +from _typeshed import StrPath +from collections.abc import Iterable -have_pyrex: Any +from ._distutils.extension import Extension as _Extension + +def have_pyrex() -> bool: ... class Extension(_Extension): - py_limited_api: Any - def __init__(self, name, sources, *args, **kw) -> None: ... + py_limited_api: bool + def __init__( + self, + name: str, + sources: Iterable[StrPath], + include_dirs: list[str] | None = None, + define_macros: list[tuple[str, str | None]] | None = None, + undef_macros: list[str] | None = None, + library_dirs: list[str] | None = None, + libraries: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + extra_objects: list[str] | None = None, + extra_compile_args: list[str] | None = None, + extra_link_args: list[str] | None = None, + export_symbols: list[str] | None = None, + swig_opts: list[str] | None = None, + depends: list[str] | None = None, + language: str | None = None, + optional: bool | None = None, + *, + py_limited_api: bool = False, + ) -> None: ... class Library(Extension): ... diff --git a/stubs/setuptools/setuptools/extern/__init__.pyi b/stubs/setuptools/setuptools/extern/__init__.pyi deleted file mode 100644 index dcc8e3b56a59..000000000000 --- a/stubs/setuptools/setuptools/extern/__init__.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -class VendorImporter: - root_name: Any - vendored_names: Any - vendor_pkg: Any - def __init__(self, root_name, vendored_names=..., vendor_pkg: Any | None = ...) -> None: ... - @property - def search_path(self) -> None: ... - def load_module(self, fullname): ... - def create_module(self, spec): ... - def exec_module(self, module) -> None: ... - def find_spec(self, fullname, path: Any | None = ..., target: Any | None = ...): ... - def install(self) -> None: ... - -names: Any diff --git a/stubs/setuptools/setuptools/glob.pyi b/stubs/setuptools/setuptools/glob.pyi index 3da334debc03..a89dadc475f7 100644 --- a/stubs/setuptools/setuptools/glob.pyi +++ b/stubs/setuptools/setuptools/glob.pyi @@ -1,3 +1,9 @@ -def glob(pathname, recursive: bool = ...): ... -def iglob(pathname, recursive: bool = ...): ... +from collections.abc import Iterator +from typing import TypeVar + +_StrOrBytesT = TypeVar("_StrOrBytesT", str, bytes) +__all__ = ["glob", "iglob", "escape"] + +def glob(pathname: _StrOrBytesT, recursive: bool = False) -> list[_StrOrBytesT]: ... +def iglob(pathname: _StrOrBytesT, recursive: bool = False) -> Iterator[_StrOrBytesT]: ... def escape(pathname): ... diff --git a/stubs/setuptools/setuptools/installer.pyi b/stubs/setuptools/setuptools/installer.pyi index 0d3eaf68c0c4..8902dd66f711 100644 --- a/stubs/setuptools/setuptools/installer.pyi +++ b/stubs/setuptools/setuptools/installer.pyi @@ -1,2 +1,14 @@ -def fetch_build_egg(dist, req): ... -def strip_marker(req): ... +from importlib import metadata +from typing import Any +from typing_extensions import deprecated + +@deprecated(""" + `setuptools.installer` and `fetch_build_eggs` are deprecated. + Requirements should be satisfied by a PEP 517 installer. + If you are using pip, you can try `pip install --use-pep517`. + """) +def fetch_build_egg(dist, req) -> metadata.Distribution | metadata.PathDistribution: ... + +# Returns packaging.requirements.Requirement +# But since this module is deprecated, we avoid declaring a dependency on packaging +def strip_marker(req) -> Any: ... diff --git a/stubs/setuptools/setuptools/lib2to3_ex.pyi b/stubs/setuptools/setuptools/lib2to3_ex.pyi deleted file mode 100644 index d8194ae031f7..000000000000 --- a/stubs/setuptools/setuptools/lib2to3_ex.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from distutils.util import Mixin2to3 as _Mixin2to3 -from lib2to3.refactor import RefactoringTool - -class DistutilsRefactoringTool(RefactoringTool): - def log_error(self, msg, *args, **kw) -> None: ... # type: ignore[override] - def log_message(self, msg, *args) -> None: ... - def log_debug(self, msg, *args) -> None: ... - -class Mixin2to3(_Mixin2to3): - def run_2to3(self, files, doctests: bool = ...) -> None: ... diff --git a/stubs/setuptools/setuptools/logging.pyi b/stubs/setuptools/setuptools/logging.pyi new file mode 100644 index 000000000000..4f87159e22a8 --- /dev/null +++ b/stubs/setuptools/setuptools/logging.pyi @@ -0,0 +1,2 @@ +def configure() -> None: ... +def set_threshold(level: int) -> int: ... diff --git a/stubs/setuptools/setuptools/modified.pyi b/stubs/setuptools/setuptools/modified.pyi new file mode 100644 index 000000000000..0437d4efc3ed --- /dev/null +++ b/stubs/setuptools/setuptools/modified.pyi @@ -0,0 +1,3 @@ +from ._distutils._modified import newer, newer_group, newer_pairwise, newer_pairwise_group + +__all__ = ["newer", "newer_pairwise", "newer_group", "newer_pairwise_group"] diff --git a/stubs/setuptools/setuptools/monkey.pyi b/stubs/setuptools/setuptools/monkey.pyi index dca3245d3285..c69326ab1fd5 100644 --- a/stubs/setuptools/setuptools/monkey.pyi +++ b/stubs/setuptools/setuptools/monkey.pyi @@ -1,6 +1,16 @@ -def get_unpatched(item): ... -def get_unpatched_class(cls): ... +from types import FunctionType +from typing import TypeVar, overload + +_T = TypeVar("_T") +_UnpatchT = TypeVar("_UnpatchT", type, FunctionType) +__all__: list[str] = [] + +@overload +def get_unpatched(item: _UnpatchT) -> _UnpatchT: ... # type: ignore[overload-overlap] +@overload +def get_unpatched(item: object) -> None: ... + +def get_unpatched_class(cls: type[_T]) -> type[_T]: ... def patch_all() -> None: ... def patch_func(replacement, target_mod, func_name) -> None: ... def get_unpatched_function(candidate): ... -def patch_for_msvc_specialized_compiler(): ... diff --git a/stubs/setuptools/setuptools/msvc.pyi b/stubs/setuptools/setuptools/msvc.pyi index 0bf9ce791a4d..433b0b161fd2 100644 --- a/stubs/setuptools/setuptools/msvc.pyi +++ b/stubs/setuptools/setuptools/msvc.pyi @@ -1,145 +1,168 @@ -from typing import Any +import sys +from typing import Final, TypedDict, overload +from typing_extensions import LiteralString, NotRequired -class winreg: - HKEY_USERS: Any - HKEY_CURRENT_USER: Any - HKEY_LOCAL_MACHINE: Any - HKEY_CLASSES_ROOT: Any +if sys.platform == "win32": + import winreg as winreg + from os import environ as environ +else: + class winreg: + HKEY_USERS: Final[None] + HKEY_CURRENT_USER: Final[None] + HKEY_LOCAL_MACHINE: Final[None] + HKEY_CLASSES_ROOT: Final[None] -def msvc9_find_vcvarsall(version): ... -def msvc9_query_vcvarsall(ver, arch: str = ..., *args, **kwargs): ... + environ: dict[str, str] -PLAT_SPEC_TO_RUNTIME: Any +class PlatformInfo: + current_cpu: Final[str] -def msvc14_get_vc_env(plat_spec): ... -def msvc14_gen_lib_options(*args, **kwargs): ... + arch: str -class PlatformInfo: - current_cpu: Any - arch: Any - def __init__(self, arch) -> None: ... - @property - def target_cpu(self): ... - def target_is_x86(self): ... - def current_is_x86(self): ... - def current_dir(self, hidex86: bool = ..., x64: bool = ...): ... - def target_dir(self, hidex86: bool = ..., x64: bool = ...): ... - def cross_dir(self, forcex86: bool = ...): ... + def __init__(self, arch: str) -> None: ... + @property + def target_cpu(self) -> str: ... + def target_is_x86(self) -> bool: ... + def current_is_x86(self) -> bool: ... + def current_dir(self, hidex86: bool = False, x64: bool = False) -> str: ... + def target_dir(self, hidex86: bool = False, x64: bool = False) -> str: ... + def cross_dir(self, forcex86: bool = False) -> str: ... class RegistryInfo: - HKEYS: Any - pi: Any - def __init__(self, platform_info) -> None: ... + if sys.platform == "win32": + HKEYS: Final[tuple[int, int, int, int]] + else: + HKEYS: Final[tuple[None, None, None, None]] + + pi: PlatformInfo + + def __init__(self, platform_info: PlatformInfo) -> None: ... @property - def visualstudio(self): ... + def visualstudio(self) -> LiteralString: ... @property - def sxs(self): ... + def sxs(self) -> LiteralString: ... @property - def vc(self): ... + def vc(self) -> LiteralString: ... @property - def vs(self): ... + def vs(self) -> LiteralString: ... @property - def vc_for_python(self): ... + def vc_for_python(self) -> LiteralString: ... @property - def microsoft_sdk(self): ... + def microsoft_sdk(self) -> LiteralString: ... @property - def windows_sdk(self): ... + def windows_sdk(self) -> LiteralString: ... @property - def netfx_sdk(self): ... + def netfx_sdk(self) -> LiteralString: ... @property - def windows_kits_roots(self): ... - def microsoft(self, key, x86: bool = ...): ... - def lookup(self, key, name): ... + def windows_kits_roots(self) -> LiteralString: ... + + @overload + def microsoft(self, key: LiteralString, x86: bool = False) -> LiteralString: ... + @overload + def microsoft(self, key: str, x86: bool = False) -> str: ... # type: ignore[misc] + + def lookup(self, key: str, name: str) -> str | None: ... class SystemInfo: - WinDir: Any - ProgramFiles: Any - ProgramFilesx86: Any - ri: Any - pi: Any - known_vs_paths: Any - vs_ver: Any - def __init__(self, registry_info, vc_ver: Any | None = ...) -> None: ... - def find_reg_vs_vers(self): ... - def find_programdata_vs_vers(self): ... + WinDir: Final[str] + ProgramFiles: Final[str] + ProgramFilesx86: Final[str] + + ri: RegistryInfo + pi: PlatformInfo + known_vs_paths: dict[float, str] + vs_ver: float + vc_ver: float + + def __init__(self, registry_info: RegistryInfo, vc_ver: float | None = None) -> None: ... + def find_reg_vs_vers(self) -> list[float]: ... + def find_programdata_vs_vers(self) -> dict[float, str]: ... @property - def VSInstallDir(self): ... + def VSInstallDir(self) -> str: ... @property - def VCInstallDir(self): ... + def VCInstallDir(self) -> str: ... @property - def WindowsSdkVersion(self): ... + def WindowsSdkVersion(self) -> tuple[LiteralString, ...]: ... @property - def WindowsSdkLastVersion(self): ... + def WindowsSdkLastVersion(self) -> str: ... @property - def WindowsSdkDir(self): ... + def WindowsSdkDir(self) -> str | None: ... @property - def WindowsSDKExecutablePath(self): ... + def WindowsSDKExecutablePath(self) -> str | None: ... @property - def FSharpInstallDir(self): ... + def FSharpInstallDir(self) -> str: ... @property - def UniversalCRTSdkDir(self): ... + def UniversalCRTSdkDir(self) -> str | None: ... @property - def UniversalCRTSdkLastVersion(self): ... + def UniversalCRTSdkLastVersion(self) -> str: ... @property - def NetFxSdkVersion(self): ... + def NetFxSdkVersion(self) -> tuple[LiteralString, ...]: ... @property - def NetFxSdkDir(self): ... + def NetFxSdkDir(self) -> str: ... @property - def FrameworkDir32(self): ... + def FrameworkDir32(self) -> str: ... @property - def FrameworkDir64(self): ... + def FrameworkDir64(self) -> str: ... @property - def FrameworkVersion32(self): ... + def FrameworkVersion32(self) -> tuple[str, ...]: ... @property - def FrameworkVersion64(self): ... + def FrameworkVersion64(self) -> tuple[str, ...]: ... + +class _EnvironmentDict(TypedDict): + include: str + lib: str + libpath: str + path: str + py_vcruntime_redist: NotRequired[str | None] class EnvironmentInfo: - pi: Any - ri: Any - si: Any - def __init__(self, arch, vc_ver: Any | None = ..., vc_min_ver: int = ...) -> None: ... + pi: PlatformInfo + ri: RegistryInfo + si: SystemInfo + + def __init__(self, arch: str, vc_ver: float | None = None, vc_min_ver: float = 0) -> None: ... @property - def vs_ver(self): ... + def vs_ver(self) -> float: ... @property - def vc_ver(self): ... + def vc_ver(self) -> float: ... @property - def VSTools(self): ... + def VSTools(self) -> list[str]: ... @property - def VCIncludes(self): ... + def VCIncludes(self) -> list[str]: ... @property - def VCLibraries(self): ... + def VCLibraries(self) -> list[str]: ... @property - def VCStoreRefs(self): ... + def VCStoreRefs(self) -> list[str]: ... @property - def VCTools(self): ... + def VCTools(self) -> list[str]: ... @property - def OSLibraries(self): ... + def OSLibraries(self) -> list[str]: ... @property - def OSIncludes(self): ... + def OSIncludes(self) -> list[str]: ... @property - def OSLibpath(self): ... + def OSLibpath(self) -> list[str]: ... @property - def SdkTools(self): ... + def SdkTools(self) -> list[str]: ... @property - def SdkSetup(self): ... + def SdkSetup(self) -> list[str]: ... @property - def FxTools(self): ... + def FxTools(self) -> list[str]: ... @property - def NetFxSDKLibraries(self): ... + def NetFxSDKLibraries(self) -> list[str]: ... @property - def NetFxSDKIncludes(self): ... + def NetFxSDKIncludes(self) -> list[str]: ... @property - def VsTDb(self): ... + def VsTDb(self) -> list[str]: ... @property - def MSBuild(self): ... + def MSBuild(self) -> list[str]: ... @property - def HTMLHelpWorkshop(self): ... + def HTMLHelpWorkshop(self) -> list[str]: ... @property - def UCRTLibraries(self): ... + def UCRTLibraries(self) -> list[str]: ... @property - def UCRTIncludes(self): ... + def UCRTIncludes(self) -> list[str]: ... @property - def FSharp(self): ... + def FSharp(self) -> list[str]: ... @property - def VCRuntimeRedist(self): ... - def return_env(self, exists: bool = ...): ... + def VCRuntimeRedist(self) -> str | None: ... + def return_env(self, exists: bool = True) -> _EnvironmentDict: ... diff --git a/stubs/setuptools/setuptools/namespaces.pyi b/stubs/setuptools/setuptools/namespaces.pyi index b85fcec71da8..9170ecfdd5e6 100644 --- a/stubs/setuptools/setuptools/namespaces.pyi +++ b/stubs/setuptools/setuptools/namespaces.pyi @@ -1,6 +1,6 @@ -from typing import Any +import itertools -flatten: Any +flatten = itertools.chain.from_iterable class Installer: nspkg_ext: str diff --git a/stubs/setuptools/setuptools/package_index.pyi b/stubs/setuptools/setuptools/package_index.pyi deleted file mode 100644 index f4d14b9407db..000000000000 --- a/stubs/setuptools/setuptools/package_index.pyi +++ /dev/null @@ -1,84 +0,0 @@ -import configparser -from typing import Any - -from pkg_resources import Environment - -def parse_bdist_wininst(name): ... -def distros_for_url(url, metadata: Any | None = ...) -> None: ... -def interpret_distro_name( - location, basename, metadata, py_version: Any | None = ..., precedence=..., platform: Any | None = ... -) -> None: ... - -class ContentChecker: - def feed(self, block) -> None: ... - def is_valid(self): ... - def report(self, reporter, template) -> None: ... - -class HashChecker(ContentChecker): - pattern: Any - hash_name: Any - hash: Any - expected: Any - def __init__(self, hash_name, expected) -> None: ... - @classmethod - def from_url(cls, url): ... - def feed(self, block) -> None: ... - def is_valid(self): ... - def report(self, reporter, template): ... - -class PackageIndex(Environment): - index_url: Any - scanned_urls: Any - fetched_urls: Any - package_pages: Any - allows: Any - to_scan: Any - opener: Any - def __init__( - self, index_url: str = ..., hosts=..., ca_bundle: Any | None = ..., verify_ssl: bool = ..., *args, **kw - ) -> None: ... - def process_url(self, url, retrieve: bool = ...) -> None: ... - def process_filename(self, fn, nested: bool = ...) -> None: ... - def url_ok(self, url, fatal: bool = ...): ... - def scan_egg_links(self, search_path) -> None: ... - def scan_egg_link(self, path, entry) -> None: ... - def process_index(self, url, page): ... - def need_version_info(self, url) -> None: ... - def scan_all(self, msg: Any | None = ..., *args) -> None: ... - def find_packages(self, requirement) -> None: ... - def obtain(self, requirement, installer: Any | None = ...): ... - def check_hash(self, checker, filename, tfp) -> None: ... - def add_find_links(self, urls) -> None: ... - def prescan(self) -> None: ... - def not_found_in_index(self, requirement) -> None: ... - def download(self, spec, tmpdir): ... - def fetch_distribution( - self, - requirement, - tmpdir, - force_scan: bool = ..., - source: bool = ..., - develop_ok: bool = ..., - local_index: Any | None = ..., - ): ... - def fetch(self, requirement, tmpdir, force_scan: bool = ..., source: bool = ...): ... - def gen_setup(self, filename, fragment, tmpdir): ... - dl_blocksize: int - def reporthook(self, url, filename, blocknum, blksize, size) -> None: ... - def open_url(self, url, warning: Any | None = ...): ... - def scan_url(self, url) -> None: ... - def debug(self, msg, *args) -> None: ... - def info(self, msg, *args) -> None: ... - def warn(self, msg, *args) -> None: ... - -class Credential: - username: Any - password: Any - def __init__(self, username, password) -> None: ... - def __iter__(self): ... - -class PyPIConfig(configparser.RawConfigParser): - def __init__(self) -> None: ... - @property - def creds_by_repository(self): ... - def find_credential(self, url): ... diff --git a/stubs/setuptools/setuptools/sandbox.pyi b/stubs/setuptools/setuptools/sandbox.pyi deleted file mode 100644 index 293d11288081..000000000000 --- a/stubs/setuptools/setuptools/sandbox.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from distutils.errors import DistutilsError -from typing import Any - -class UnpickleableException(Exception): - @staticmethod - def dump(type, exc): ... - -class ExceptionSaver: - def __enter__(self): ... - def __exit__(self, type, exc, tb): ... - def resume(self) -> None: ... - -def run_setup(setup_script, args): ... - -class AbstractSandbox: - def __init__(self) -> None: ... - def __enter__(self) -> None: ... - def __exit__(self, exc_type, exc_value, traceback) -> None: ... - def run(self, func): ... - -class DirectorySandbox(AbstractSandbox): - write_ops: Any - def __init__(self, sandbox, exceptions=...) -> None: ... - def tmpnam(self) -> None: ... - def open(self, file, flags, mode: int = ..., *args, **kw): ... - -class SandboxViolation(DistutilsError): - tmpl: Any diff --git a/stubs/setuptools/setuptools/unicode_utils.pyi b/stubs/setuptools/setuptools/unicode_utils.pyi index 6c799c8b8250..4ab4afd02181 100644 --- a/stubs/setuptools/setuptools/unicode_utils.pyi +++ b/stubs/setuptools/setuptools/unicode_utils.pyi @@ -1,3 +1,4 @@ def decompose(path): ... +def normalize(text): ... def filesys_decode(path): ... def try_encode(string, enc): ... diff --git a/stubs/setuptools/setuptools/warnings.pyi b/stubs/setuptools/setuptools/warnings.pyi new file mode 100644 index 000000000000..81d3bcfb3922 --- /dev/null +++ b/stubs/setuptools/setuptools/warnings.pyi @@ -0,0 +1,19 @@ +from typing import TypeAlias + +_DueDate: TypeAlias = tuple[int, int, int] # time tuple + +class SetuptoolsWarning(UserWarning): + @classmethod + def emit( + cls, + summary: str | None = None, + details: str | None = None, + due_date: _DueDate | None = None, + see_docs: str | None = None, + see_url: str | None = None, + stacklevel: int = 2, + **kwargs, + ) -> None: ... + +class InformationOnly(SetuptoolsWarning): ... +class SetuptoolsDeprecationWarning(SetuptoolsWarning): ... diff --git a/stubs/setuptools/setuptools/wheel.pyi b/stubs/setuptools/setuptools/wheel.pyi index fe8d564af79d..ae56166a8556 100644 --- a/stubs/setuptools/setuptools/wheel.pyi +++ b/stubs/setuptools/setuptools/wheel.pyi @@ -1,12 +1,14 @@ -from typing import Any +from _typeshed import Incomplete +from collections.abc import Generator -WHEEL_NAME: Any +WHEEL_NAME: Incomplete NAMESPACE_PACKAGE_INIT: str def unpack(src_dir, dst_dir) -> None: ... +def disable_info_traces() -> Generator[None]: ... class Wheel: - filename: Any + filename: Incomplete def __init__(self, filename) -> None: ... def tags(self): ... def is_compatible(self): ... diff --git a/stubs/setuptools/setuptools/windows_support.pyi b/stubs/setuptools/setuptools/windows_support.pyi index ec0c7586238b..7daf9e3a66cc 100644 --- a/stubs/setuptools/setuptools/windows_support.pyi +++ b/stubs/setuptools/setuptools/windows_support.pyi @@ -1,2 +1,2 @@ def windows_only(func): ... -def hide_file(path) -> None: ... +def hide_file(path: str) -> None: ... diff --git a/stubs/shapely/@tests/stubtest_allowlist.txt b/stubs/shapely/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..fd759a27a630 --- /dev/null +++ b/stubs/shapely/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +shapely\.conftest +shapely\.tests.* + +shapely\._typing # stubs only module diff --git a/stubs/shapely/METADATA.toml b/stubs/shapely/METADATA.toml new file mode 100644 index 000000000000..326a70f2733c --- /dev/null +++ b/stubs/shapely/METADATA.toml @@ -0,0 +1,4 @@ +version = "2.1.*" +upstream-repository = "https://github.com/shapely/shapely" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] diff --git a/stubs/shapely/shapely/__init__.pyi b/stubs/shapely/shapely/__init__.pyi new file mode 100644 index 000000000000..22e9b97f7ee6 --- /dev/null +++ b/stubs/shapely/shapely/__init__.pyi @@ -0,0 +1,35 @@ +from typing import Final + +from . import affinity as affinity +from ._coverage import * +from ._geometry import * +from .constructive import * +from .coordinates import * +from .creation import * +from .errors import setup_signal_checks as setup_signal_checks +from .geometry import ( + GeometryCollection as GeometryCollection, + LinearRing as LinearRing, + LineString as LineString, + MultiLineString as MultiLineString, + MultiPoint as MultiPoint, + MultiPolygon as MultiPolygon, + Point as Point, + Polygon as Polygon, +) +from .io import * +from .lib import ( + Geometry as Geometry, + GEOSException as GEOSException, + geos_capi_version as geos_capi_version, + geos_capi_version_string as geos_capi_version_string, + geos_version as geos_version, + geos_version_string as geos_version_string, +) +from .linear import * +from .measurement import * +from .predicates import * +from .set_operations import * +from .strtree import * + +__version__: Final[str] diff --git a/stubs/shapely/shapely/_coverage.pyi b/stubs/shapely/shapely/_coverage.pyi new file mode 100644 index 000000000000..fefc40e02d48 --- /dev/null +++ b/stubs/shapely/shapely/_coverage.pyi @@ -0,0 +1,16 @@ +from typing import overload + +import numpy as np + +from ._typing import ArrayLike, GeoArray, GeoArrayLikeSeq, OptGeoArrayLike +from .geometry import Polygon + +__all__ = ["coverage_invalid_edges", "coverage_is_valid", "coverage_simplify"] + +def coverage_is_valid(geometry: OptGeoArrayLike, gap_width: float = 0.0, **kwargs) -> np.bool_: ... +def coverage_invalid_edges(geometry: OptGeoArrayLike, gap_width: float = 0.0, **kwargs) -> GeoArray: ... + +@overload +def coverage_simplify(geometry: Polygon, tolerance: ArrayLike[float], *, simplify_boundary: bool = True) -> Polygon: ... +@overload +def coverage_simplify(geometry: GeoArrayLikeSeq, tolerance: ArrayLike[float], *, simplify_boundary: bool = True) -> GeoArray: ... diff --git a/stubs/shapely/shapely/_enum.pyi b/stubs/shapely/shapely/_enum.pyi new file mode 100644 index 000000000000..c36e15fed401 --- /dev/null +++ b/stubs/shapely/shapely/_enum.pyi @@ -0,0 +1,5 @@ +from enum import IntEnum + +class ParamEnum(IntEnum): # type: ignore[misc] # Enum with no members + @classmethod + def get_value(cls, item: str) -> int: ... diff --git a/stubs/shapely/shapely/_geometry.pyi b/stubs/shapely/shapely/_geometry.pyi new file mode 100644 index 000000000000..7e9b64f1a71d --- /dev/null +++ b/stubs/shapely/shapely/_geometry.pyi @@ -0,0 +1,209 @@ +from enum import IntEnum +from typing import Any, Literal, SupportsIndex, TypeAlias, overload + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, OptGeoT +from .geometry import LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from .geometry.base import BaseGeometry, BaseMultipartGeometry +from .lib import Geometry + +__all__ = [ + "GeometryType", + "force_2d", + "force_3d", + "get_coordinate_dimension", + "get_dimensions", + "get_exterior_ring", + "get_geometry", + "get_interior_ring", + "get_m", + "get_num_coordinates", + "get_num_geometries", + "get_num_interior_rings", + "get_num_points", + "get_parts", + "get_point", + "get_precision", + "get_rings", + "get_srid", + "get_type_id", + "get_x", + "get_y", + "get_z", + "set_precision", + "set_srid", +] + +_PrecisionMode: TypeAlias = Literal["valid_output", "pointwise", "keep_collapsed", 0, 1, 2] + +class GeometryType(IntEnum): + MISSING = -1 + POINT = 0 + LINESTRING = 1 + LINEARRING = 2 + POLYGON = 3 + MULTIPOINT = 4 + MULTILINESTRING = 5 + MULTIPOLYGON = 6 + GEOMETRYCOLLECTION = 7 + +@overload +def get_type_id(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_type_id(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_dimensions(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_dimensions(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_coordinate_dimension(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_coordinate_dimension(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_num_coordinates(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_coordinates(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_srid(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_srid(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def set_srid(geometry: OptGeoT, srid: SupportsIndex, **kwargs) -> OptGeoT: ... +@overload +def set_srid(geometry: OptGeoArrayLikeSeq, srid: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def set_srid(geometry: OptGeoArrayLike, srid: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_x(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_x(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_y(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_y(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_z(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_z(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_m(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_m(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_point(geometry: LineString, index: SupportsIndex, **kwargs) -> Point | Any: ... +@overload +def get_point(geometry: Point | Polygon | BaseMultipartGeometry | None, index: SupportsIndex, **kwargs) -> None: ... +@overload +def get_point(geometry: Geometry, index: SupportsIndex, **kwargs) -> Point | None: ... +@overload +def get_point(geometry: OptGeoArrayLikeSeq, index: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def get_point(geometry: OptGeoArrayLike, index: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_num_points(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_points(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_exterior_ring(geometry: Polygon, **kwargs) -> LinearRing: ... +@overload +def get_exterior_ring(geometry: Point | LineString | BaseMultipartGeometry | None, **kwargs) -> None: ... +@overload +def get_exterior_ring(geometry: Geometry, **kwargs) -> LinearRing | None: ... +@overload +def get_exterior_ring(geometry: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... + +@overload +def get_interior_ring(geometry: Polygon, index: SupportsIndex, **kwargs) -> LinearRing | Any: ... +@overload +def get_interior_ring(geometry: Point | LineString | BaseMultipartGeometry | None, index: SupportsIndex, **kwargs) -> None: ... +@overload +def get_interior_ring(geometry: Geometry, index: SupportsIndex, **kwargs) -> LinearRing | None: ... +@overload +def get_interior_ring(geometry: OptGeoArrayLikeSeq, index: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def get_interior_ring(geometry: OptGeoArrayLike, index: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_num_interior_rings(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_interior_rings(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_geometry(geometry: MultiPoint, index: SupportsIndex, **kwargs) -> Point | Any: ... +@overload +def get_geometry(geometry: MultiLineString, index: SupportsIndex, **kwargs) -> LineString | Any: ... +@overload +def get_geometry(geometry: MultiPolygon, index: SupportsIndex, **kwargs) -> Polygon | Any: ... +@overload +def get_geometry(geometry: BaseMultipartGeometry, index: SupportsIndex, **kwargs) -> BaseGeometry | Any: ... +@overload +def get_geometry(geometry: None, index: SupportsIndex, **kwargs) -> None: ... +@overload +def get_geometry(geometry: Geometry | None, index: SupportsIndex, **kwargs) -> BaseGeometry | None: ... +@overload +def get_geometry(geometry: OptGeoArrayLikeSeq, index: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def get_geometry(geometry: OptGeoArrayLike, index: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_parts(geometry: OptGeoArrayLike, return_index: Literal[False] = False) -> GeoArray: ... +@overload +def get_parts(geometry: OptGeoArrayLike, return_index: Literal[True]) -> tuple[GeoArray, NDArray[np.int64]]: ... +@overload +def get_parts(geometry: OptGeoArrayLike, return_index: bool) -> GeoArray | tuple[GeoArray, NDArray[np.int64]]: ... + +@overload +def get_rings(geometry: OptGeoArrayLike, return_index: Literal[False] = False) -> GeoArray: ... +@overload +def get_rings(geometry: OptGeoArrayLike, return_index: Literal[True]) -> tuple[GeoArray, NDArray[np.int64]]: ... +@overload +def get_rings(geometry: OptGeoArrayLike, return_index: bool) -> GeoArray | tuple[GeoArray, NDArray[np.int64]]: ... + +@overload +def get_num_geometries(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_geometries(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_precision(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_precision(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +class SetPrecisionMode(ParamEnum): + valid_output = 0 + pointwise = 1 + keep_collapsed = 2 + +@overload +def set_precision(geometry: OptGeoT, grid_size: float, mode: _PrecisionMode = "valid_output", **kwargs) -> OptGeoT: ... +@overload +def set_precision( + geometry: OptGeoArrayLikeSeq, grid_size: float, mode: _PrecisionMode = "valid_output", **kwargs +) -> GeoArray: ... + +@overload +def force_2d(geometry: OptGeoT, **kwargs) -> OptGeoT: ... +@overload +def force_2d(geometry: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... + +@overload +def force_3d(geometry: OptGeoT, z: float = 0.0, **kwargs) -> OptGeoT: ... +@overload +def force_3d(geometry: OptGeoArrayLikeSeq, z: ArrayLike[float] = 0.0, **kwargs) -> GeoArray: ... +@overload +def force_3d(geometry: OptGeoArrayLike, z: ArrayLikeSeq[float], **kwargs) -> GeoArray: ... diff --git a/stubs/shapely/shapely/_ragged_array.pyi b/stubs/shapely/shapely/_ragged_array.pyi new file mode 100644 index 000000000000..a0822d55e5c6 --- /dev/null +++ b/stubs/shapely/shapely/_ragged_array.pyi @@ -0,0 +1,14 @@ +import numpy as np +from numpy.typing import NDArray + +from ._geometry import GeometryType +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLikeSeq + +def to_ragged_array( + geometries: OptGeoArrayLikeSeq, include_z: bool | None = None, include_m: bool | None = None +) -> tuple[GeometryType, NDArray[np.float64], tuple[NDArray[np.int32], ...]]: ... +def from_ragged_array( + geometry_type: GeometryType, coords: ArrayLike[float], offsets: ArrayLikeSeq[int] | None = None +) -> GeoArray: ... + +__all__ = ["to_ragged_array", "from_ragged_array"] diff --git a/stubs/shapely/shapely/_typing.pyi b/stubs/shapely/shapely/_typing.pyi new file mode 100644 index 000000000000..ed62e8b881eb --- /dev/null +++ b/stubs/shapely/shapely/_typing.pyi @@ -0,0 +1,75 @@ +import sys +from _typeshed import SupportsWrite as SupportsWrite +from collections.abc import Sequence +from typing import Any, Literal, Protocol, TypeAlias, TypedDict, TypeVar, type_check_only + +import numpy as np +import numpy.typing as npt + +from .lib import Geometry + +if sys.version_info >= (3, 12): + from collections.abc import Buffer + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_DType = TypeVar("_DType", bound=np.dtype[Any]) +_DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype[Any]) + +GeoT = TypeVar("GeoT", bound=Geometry) # noqa: Y001 +OptGeoT = TypeVar("OptGeoT", bound=Geometry | None) # noqa: Y001 + +@type_check_only +class SupportsArray(Protocol[_DType_co]): + def __array__(self) -> np.ndarray[Any, _DType_co]: ... + +# TODO: revisit when mypy is happy with generic recursive type alias +# NestedSequence: TypeAlias = Sequence[_T] | Sequence[NestedSequence[_T]] +NestedSequence: TypeAlias = Sequence[_T] | Sequence[Sequence[_T]] | Sequence[Sequence[Sequence[_T]]] +DualArrayLike: TypeAlias = SupportsArray[_DType] | NestedSequence[SupportsArray[_DType]] | NestedSequence[_T] + +# array-like sequences: objects accepted by np.array that produce at least 1-D arrays +if sys.version_info >= (3, 12): + ArrayLikeSeq: TypeAlias = Buffer | DualArrayLike[np.dtype[Any], _T] +else: + ArrayLikeSeq: TypeAlias = DualArrayLike[np.dtype[Any], _T] +GeoArrayLikeSeq: TypeAlias = ArrayLikeSeq[Geometry] +OptGeoArrayLikeSeq: TypeAlias = ArrayLikeSeq[Geometry | None] + +# array-like: objects accepted by np.array that may also produce 0-D array +ArrayLike: TypeAlias = _T | ArrayLikeSeq[_T] +GeoArrayLike: TypeAlias = ArrayLike[Geometry] +OptGeoArrayLike: TypeAlias = ArrayLike[Geometry | None] + +# There is no way to pronounce "array of BaseGeometry" currently because of the restriction on +# NDArray type variable to np.dtype and because np.object_ is not generic. +# Note the use of `BaseGeometry` instead of `Geometry` as the alias is used in return types. +GeoArray: TypeAlias = npt.NDArray[np.object_] + +@type_check_only +class SupportsGeoInterface(Protocol): + @property + def __geo_interface__(self) -> dict[str, Any]: ... + +# Unlike _typeshed.SupportsRead, this protocol does not require a length parameter +@type_check_only +class SupportsRead(Protocol[_T_co]): + def read(self) -> _T_co: ... + +CastingKind: TypeAlias = Literal["no", "equiv", "safe", "same_kind", "unsafe"] +OrderKind: TypeAlias = Literal["K", "A", "C", "F"] + +@type_check_only +class _UFuncKwargsBase(TypedDict, total=False): + where: npt.ArrayLike + casting: CastingKind + order: OrderKind + dtype: np.dtype[Any] | type[Any] + subok: bool + +@type_check_only +class UFuncKwargs(_UFuncKwargsBase, total=False): + out: npt.NDArray[Any] | tuple[npt.NDArray[Any], ...] + +@type_check_only +class UFuncKwargsNoOut(_UFuncKwargsBase, total=False): ... diff --git a/stubs/shapely/shapely/_version.pyi b/stubs/shapely/shapely/_version.pyi new file mode 100644 index 000000000000..249ab567c82e --- /dev/null +++ b/stubs/shapely/shapely/_version.pyi @@ -0,0 +1,6 @@ +from typing import TypedDict + +version_json: str +_Versions = TypedDict("_Versions", {"date": str, "dirty": bool, "error": None, "full-revisionid": str, "version": str}) + +def get_versions() -> _Versions: ... diff --git a/stubs/shapely/shapely/affinity.pyi b/stubs/shapely/shapely/affinity.pyi new file mode 100644 index 000000000000..d5e230db085f --- /dev/null +++ b/stubs/shapely/shapely/affinity.pyi @@ -0,0 +1,24 @@ +from collections.abc import Collection +from typing import Literal, TypeAlias, overload + +from ._typing import GeoT +from .geometry import Point +from .lib import Geometry + +__all__ = ["affine_transform", "rotate", "scale", "skew", "translate"] + +_Origin: TypeAlias = Literal["center", "centroid"] | Point | tuple[float, float] | tuple[float, float, float] + +def affine_transform(geom: GeoT, matrix: Collection[float]) -> GeoT: ... + +@overload +def interpret_origin(geom: Geometry, origin: _Origin, ndim: Literal[2]) -> tuple[float, float]: ... +@overload +def interpret_origin(geom: Geometry, origin: _Origin, ndim: Literal[3]) -> tuple[float, float, float]: ... +@overload +def interpret_origin(geom: Geometry, origin: _Origin, ndim: int) -> tuple[float, float] | tuple[float, float, float]: ... + +def rotate(geom: GeoT, angle: float, origin: _Origin = "center", use_radians: bool = False) -> GeoT: ... +def scale(geom: GeoT, xfact: float = 1.0, yfact: float = 1.0, zfact: float = 1.0, origin: _Origin = "center") -> GeoT: ... +def skew(geom: GeoT, xs: float = 0.0, ys: float = 0.0, origin: _Origin = "center", use_radians: bool = False) -> GeoT: ... +def translate(geom: GeoT, xoff: float = 0.0, yoff: float = 0.0, zoff: float = 0.0) -> GeoT: ... diff --git a/stubs/shapely/shapely/algorithms/__init__.pyi b/stubs/shapely/shapely/algorithms/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/shapely/shapely/algorithms/cga.pyi b/stubs/shapely/shapely/algorithms/cga.pyi new file mode 100644 index 000000000000..de6ecd5ed1cc --- /dev/null +++ b/stubs/shapely/shapely/algorithms/cga.pyi @@ -0,0 +1,5 @@ +import numpy as np + +from ..geometry import LinearRing + +def signed_area(ring: LinearRing) -> np.float64: ... diff --git a/stubs/shapely/shapely/algorithms/polylabel.pyi b/stubs/shapely/shapely/algorithms/polylabel.pyi new file mode 100644 index 000000000000..5d9777c30eab --- /dev/null +++ b/stubs/shapely/shapely/algorithms/polylabel.pyi @@ -0,0 +1,3 @@ +from ..geometry import Point, Polygon + +def polylabel(polygon: Polygon, tolerance: float = 1.0) -> Point: ... diff --git a/stubs/shapely/shapely/constructive.pyi b/stubs/shapely/shapely/constructive.pyi new file mode 100644 index 000000000000..e3d21dedb46d --- /dev/null +++ b/stubs/shapely/shapely/constructive.pyi @@ -0,0 +1,634 @@ +from collections.abc import Sequence +from typing import Any, Literal, SupportsIndex, overload +from typing_extensions import Unpack + +from ._enum import ParamEnum +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, OptGeoT, UFuncKwargs +from .geometry import GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from .geometry.base import BaseGeometry, BaseMultipartGeometry +from .lib import Geometry + +__all__ = [ + "BufferCapStyle", + "BufferJoinStyle", + "boundary", + "buffer", + "build_area", + "centroid", + "clip_by_rect", + "concave_hull", + "constrained_delaunay_triangles", + "convex_hull", + "delaunay_triangles", + "envelope", + "extract_unique_points", + "make_valid", + "maximum_inscribed_circle", + "minimum_bounding_circle", + "minimum_clearance_line", + "minimum_rotated_rectangle", + "node", + "normalize", + "offset_curve", + "orient_polygons", + "oriented_envelope", + "point_on_surface", + "polygonize", + "polygonize_full", + "remove_repeated_points", + "reverse", + "segmentize", + "simplify", + "snap", + "voronoi_polygons", +] + +class BufferCapStyle(ParamEnum): + round = 1 + flat = 2 + square = 3 + +class BufferJoinStyle(ParamEnum): + round = 1 + mitre = 2 + bevel = 3 + +@overload +def boundary(geometry: Point | MultiPoint, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection: ... +@overload +def boundary(geometry: LineString | MultiLineString, **kwargs: Unpack[UFuncKwargs]) -> MultiPoint: ... +@overload +def boundary(geometry: Polygon | MultiPolygon, **kwargs: Unpack[UFuncKwargs]) -> MultiLineString: ... +@overload +def boundary(geometry: GeometryCollection | None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def boundary(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseMultipartGeometry | Any: ... +@overload +def boundary(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def buffer( + geometry: Geometry, + distance: float, + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> Polygon: ... +@overload +def buffer( + geometry: None, + distance: float, + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def buffer( + geometry: Geometry | None, + distance: float, + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> Polygon | None: ... +@overload +def buffer( + geometry: OptGeoArrayLike, + distance: ArrayLikeSeq[float], + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def buffer( + geometry: OptGeoArrayLikeSeq, + distance: ArrayLike[float], + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def offset_curve( + geometry: Geometry, + distance: float, + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString: ... +@overload +def offset_curve( + geometry: None, + distance: float, + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def offset_curve( + geometry: Geometry | None, + distance: float, + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString | None: ... +@overload +def offset_curve( + geometry: OptGeoArrayLike, + distance: ArrayLikeSeq[float], + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def offset_curve( + geometry: OptGeoArrayLikeSeq, + distance: ArrayLike[float], + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def centroid(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def centroid(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def centroid(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Point | None: ... +@overload +def centroid(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def clip_by_rect( + geometry: Geometry, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def clip_by_rect(geometry: None, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def clip_by_rect( + geometry: Geometry | None, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | None: ... +@overload +def clip_by_rect( + geometry: OptGeoArrayLikeSeq, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def concave_hull( + geometry: Geometry, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def concave_hull(geometry: None, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def concave_hull( + geometry: Geometry | None, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | None: ... +@overload +def concave_hull( + geometry: OptGeoArrayLikeSeq, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def convex_hull(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def convex_hull(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def convex_hull(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def convex_hull(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float = 0.0, only_edges: Literal[False] = False, **kwargs: Unpack[UFuncKwargs] +) -> GeometryCollection: ... +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float, only_edges: Literal[True], **kwargs: Unpack[UFuncKwargs] +) -> MultiLineString: ... +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float = 0.0, *, only_edges: Literal[True], **kwargs: Unpack[UFuncKwargs] +) -> MultiLineString: ... +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float = 0.0, only_edges: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> GeometryCollection | MultiLineString: ... +@overload +def delaunay_triangles( + geometry: None, tolerance: float = 0.0, only_edges: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def delaunay_triangles( + geometry: Geometry | None, tolerance: float = 0.0, only_edges: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> GeometryCollection | MultiLineString | None: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLike, tolerance: ArrayLike[float], only_edges: ArrayLikeSeq[bool], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLike, tolerance: ArrayLike[float] = 0.0, *, only_edges: ArrayLikeSeq[bool], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], only_edges: ArrayLike[bool] = False, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLikeSeq, + tolerance: ArrayLike[float] = 0.0, + only_edges: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def constrained_delaunay_triangles(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection: ... # type: ignore[overload-overlap] +@overload +def constrained_delaunay_triangles(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... # type: ignore[overload-overlap] +@overload +def constrained_delaunay_triangles(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection | None: ... # type: ignore[overload-overlap] +@overload +def constrained_delaunay_triangles(geometry: OptGeoArrayLikeSeq | OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def envelope(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def envelope(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def envelope(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def envelope(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def envelope(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def extract_unique_points(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> MultiPoint: ... +@overload +def extract_unique_points(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def extract_unique_points(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> MultiPoint | None: ... +@overload +def extract_unique_points(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def build_area(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def build_area(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def build_area(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def build_area(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +# make_valid with `method="linework"` only accepts `keep_collapsed=True` +@overload +def make_valid( + geometry: Geometry, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> BaseGeometry: ... +@overload +def make_valid( + geometry: None, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def make_valid( + geometry: Geometry | None, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> BaseGeometry | None: ... +@overload +def make_valid( + geometry: OptGeoArrayLikeSeq, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def make_valid( + geometry: Geometry, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def make_valid( + geometry: None, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def make_valid( + geometry: Geometry | None, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | None: ... +@overload +def make_valid( + geometry: OptGeoArrayLikeSeq, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def minimum_clearance_line(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def minimum_clearance_line(geometry: LineString | Polygon | BaseMultipartGeometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon: ... +@overload +def minimum_clearance_line(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point: ... +@overload +def minimum_clearance_line(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def minimum_clearance_line(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point | None: ... +@overload +def minimum_clearance_line(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def normalize(geometry: OptGeoT, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def normalize(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def point_on_surface(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def point_on_surface(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def point_on_surface(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Point | None: ... +@overload +def point_on_surface(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def node(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> MultiLineString: ... +@overload +def node(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def node(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> MultiLineString | None: ... +@overload +def node(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def polygonize(geometries: Sequence[Geometry | None], **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection: ... +@overload +def polygonize(geometries: Sequence[Sequence[Geometry | None]], **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... +@overload +def polygonize(geometries: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection | GeoArray: ... + +@overload +def polygonize_full( + geometries: Sequence[Geometry | None], **kwargs: Unpack[UFuncKwargs] +) -> tuple[GeometryCollection, GeometryCollection, GeometryCollection, GeometryCollection]: ... +@overload +def polygonize_full( + geometries: Sequence[Sequence[Geometry | None]], **kwargs: Unpack[UFuncKwargs] +) -> tuple[GeoArray, GeoArray, GeoArray, GeoArray]: ... +@overload +def polygonize_full( + geometries: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs] +) -> ( + tuple[GeometryCollection, GeometryCollection, GeometryCollection, GeometryCollection] + | tuple[GeoArray, GeoArray, GeoArray, GeoArray] +): ... + +@overload +def remove_repeated_points(geometry: OptGeoT, tolerance: float = 0.0, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def remove_repeated_points(geometry: OptGeoArrayLikeSeq, tolerance: float = 0.0, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def reverse(geometry: OptGeoT, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def reverse(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def segmentize(geometry: OptGeoT, max_segment_length: float, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def segmentize(geometry: OptGeoArrayLike, max_segment_length: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... +@overload +def segmentize(geometry: OptGeoArrayLikeSeq, max_segment_length: ArrayLike[float], **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def simplify(geometry: OptGeoT, tolerance: float, preserve_topology: bool = True, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def simplify( + geometry: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], preserve_topology: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def simplify( + geometry: OptGeoArrayLikeSeq, tolerance: ArrayLike[float], preserve_topology: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def snap(geometry: OptGeoT, reference: Geometry, tolerance: float, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def snap(geometry: Geometry | None, reference: None, tolerance: float, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def snap( + geometry: OptGeoArrayLikeSeq, reference: OptGeoArrayLike, tolerance: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def snap( + geometry: OptGeoArrayLike, reference: OptGeoArrayLikeSeq, tolerance: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def snap( + geometry: OptGeoArrayLike, reference: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: Literal[False] = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeometryCollection[Polygon]: ... +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float, + extend_to: Geometry | None, + only_edges: Literal[True], + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString: ... +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + *, + only_edges: Literal[True], + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString: ... +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: bool = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeometryCollection[Polygon] | LineString | MultiLineString: ... +@overload +def voronoi_polygons( + geometry: None, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: bool = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def voronoi_polygons( + geometry: Geometry | None, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: bool = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeometryCollection[Polygon] | LineString | MultiLineString | None: ... +@overload # `geometry` as sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLikeSeq, + tolerance: ArrayLike[float] = 0.0, + extend_to: OptGeoArrayLike = None, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `tolerance` as sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLikeSeq[float], + extend_to: OptGeoArrayLike = None, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def voronoi_polygons( # `extend_to` as positional sequence-like + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float], + extend_to: OptGeoArrayLikeSeq, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `extend_to` as keyword sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + *, + extend_to: OptGeoArrayLikeSeq, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def voronoi_polygons( # `only_edges` as positional sequence-like + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float], + extend_to: OptGeoArrayLike, + only_edges: ArrayLikeSeq[bool], + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def voronoi_polygons( # `only_edges` as keyword sequence-like + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + extend_to: OptGeoArrayLike = None, + *, + only_edges: ArrayLikeSeq[bool], + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `ordered` as positional sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float], + extend_to: OptGeoArrayLike, + only_edges: ArrayLike[bool], + ordered: ArrayLikeSeq[bool], + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `ordered` as keyword sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + extend_to: OptGeoArrayLike = None, + *, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLikeSeq[bool], + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def oriented_envelope(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def oriented_envelope(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def oriented_envelope(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def oriented_envelope(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def oriented_envelope(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +minimum_rotated_rectangle = oriented_envelope + +@overload +def minimum_bounding_circle(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def minimum_bounding_circle(geometry: LineString | Polygon | BaseMultipartGeometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon: ... +@overload +def minimum_bounding_circle(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point: ... +@overload +def minimum_bounding_circle(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def minimum_bounding_circle(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point | None: ... +@overload +def minimum_bounding_circle(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def maximum_inscribed_circle( + geometry: Polygon | MultiPolygon, tolerance: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> LineString: ... +@overload +def maximum_inscribed_circle(geometry: None, tolerance: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def maximum_inscribed_circle( + geometry: Polygon | MultiPolygon | None, tolerance: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> LineString | None: ... +@overload +def maximum_inscribed_circle( + geometry: OptGeoArrayLikeSeq, tolerance: ArrayLike[float] | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def maximum_inscribed_circle( + geometry: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def orient_polygons(geometry: OptGeoT, *, exterior_cw: bool = False, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def orient_polygons(geometry: OptGeoArrayLikeSeq, *, exterior_cw: bool = False, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... diff --git a/stubs/shapely/shapely/coordinates.pyi b/stubs/shapely/shapely/coordinates.pyi new file mode 100644 index 000000000000..fd3d1284c10f --- /dev/null +++ b/stubs/shapely/shapely/coordinates.pyi @@ -0,0 +1,54 @@ +from collections.abc import Callable +from typing import Literal, overload + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLikeSeq, GeoArray, GeoT, OptGeoArrayLike, OptGeoArrayLikeSeq, OptGeoT + +__all__ = ["transform", "count_coordinates", "get_coordinates", "set_coordinates"] + +@overload +def transform( + geometry: OptGeoT, + transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], + include_z: bool = False, + *, + interleaved: bool = True, +) -> OptGeoT: ... +@overload +def transform( + geometry: OptGeoArrayLikeSeq, + transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], + include_z: bool = False, + *, + interleaved: bool = True, +) -> GeoArray: ... + +def count_coordinates(geometry: OptGeoArrayLike) -> int: ... + +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool = False, return_index: Literal[False] = False, *, include_m: bool = False +) -> NDArray[np.float64]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool = False, *, return_index: Literal[True], include_m: bool = False +) -> tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool, return_index: Literal[True], *, include_m: bool = False +) -> tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool = False, *, return_index: bool, include_m: bool = False +) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool, return_index: bool, *, include_m: bool = False +) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.int64]]: ... + +@overload +def set_coordinates(geometry: GeoT, coordinates: ArrayLikeSeq[float]) -> GeoT: ... +@overload +def set_coordinates(geometry: OptGeoArrayLikeSeq, coordinates: ArrayLikeSeq[float]) -> GeoArray: ... diff --git a/stubs/shapely/shapely/coords.pyi b/stubs/shapely/shapely/coords.pyi new file mode 100644 index 000000000000..7ea73aa8404a --- /dev/null +++ b/stubs/shapely/shapely/coords.pyi @@ -0,0 +1,20 @@ +from array import array +from collections.abc import Iterator +from typing import Literal, overload + +import numpy as np +from numpy.typing import DTypeLike, NDArray + +class CoordinateSequence: + def __init__(self, coords: NDArray[np.float64]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[tuple[float, ...]]: ... + + @overload + def __getitem__(self, key: int) -> tuple[float, ...]: ... + @overload + def __getitem__(self, key: slice) -> list[tuple[float, ...]]: ... + + def __array__(self, dtype: DTypeLike | None = None, copy: Literal[True] | None = None) -> NDArray[np.float64]: ... + @property + def xy(self) -> tuple[array[float], array[float]]: ... diff --git a/stubs/shapely/shapely/creation.pyi b/stubs/shapely/shapely/creation.pyi new file mode 100644 index 000000000000..a51ff551071d --- /dev/null +++ b/stubs/shapely/shapely/creation.pyi @@ -0,0 +1,331 @@ +from collections.abc import Sequence +from typing import Literal, SupportsIndex, TypeAlias, overload +from typing_extensions import Unpack + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._geometry import GeometryType +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, UFuncKwargsNoOut +from .geometry import GeometryCollection, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from .lib import Geometry + +__all__ = [ + "box", + "destroy_prepared", + "empty", + "geometrycollections", + "linearrings", + "linestrings", + "multilinestrings", + "multipoints", + "multipolygons", + "points", + "polygons", + "prepare", +] + +class HandleNaN(ParamEnum): + allow = 0 + skip = 1 + error = 2 + +_HandleNaN: TypeAlias = Literal["allow", "skip", "error"] | HandleNaN + +@overload +def points( + coords: float, + y: float, + z: float | None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], # acts as x +) -> Point: ... +@overload +def points( + coords: Sequence[float], + y: None = None, + z: None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], # acts as x, y[, z] +) -> Point: ... +@overload +def points( + coords: Sequence[float], # acts as (x1, x2, ...) + y: Sequence[float], # must be (y1, y2, ...) + z: Sequence[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def points( + coords: Sequence[Sequence[float]], # acts as (x1, x2, ...), (y1, y2, ...)[, (z1, z2, ...)] + y: None = None, + z: None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def points( + coords: ArrayLike[float], + y: ArrayLike[float], + z: ArrayLike[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Point | GeoArray: ... +@overload +def points( + coords: ArrayLikeSeq[float], + y: ArrayLike[float] | None = None, + z: ArrayLike[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Point | GeoArray: ... + +@overload +def linestrings( + coords: Sequence[float], # acts as (x1, x2, ...) + y: Sequence[float], + z: Sequence[float] | None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LineString: ... +@overload +def linestrings( + coords: Sequence[Sequence[float]], # acts as (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LineString: ... +@overload +def linestrings( + coords: Sequence[Sequence[Sequence[float]]], # acts as seq of (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def linestrings( + coords: ArrayLikeSeq[float], + y: ArrayLikeSeq[float] | None = None, + z: ArrayLikeSeq[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LineString | GeoArray: ... + +@overload +def linearrings( + coords: Sequence[float], # acts as (x1, x2, ...) + y: Sequence[float], + z: Sequence[float] | None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LinearRing: ... +@overload +def linearrings( + coords: Sequence[Sequence[float]], # acts as (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LinearRing: ... +@overload +def linearrings( + coords: Sequence[Sequence[Sequence[float]]], # acts as seq of (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def linearrings( + coords: ArrayLikeSeq[float], + y: ArrayLikeSeq[float] | None = None, + z: ArrayLikeSeq[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LinearRing | GeoArray: ... + +@overload +def polygons( + geometries: LinearRing | Sequence[Sequence[float]] | None, + holes: ArrayLikeSeq[float] | OptGeoArrayLikeSeq | None = None, + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Polygon: ... +@overload +def polygons( + geometries: Sequence[LinearRing | Sequence[Sequence[float]] | None], + holes: ArrayLikeSeq[float] | OptGeoArrayLikeSeq | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def polygons( + geometries: ArrayLikeSeq[float] | OptGeoArrayLikeSeq, + holes: ArrayLikeSeq[float] | OptGeoArrayLikeSeq | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Polygon | GeoArray: ... + +@overload +def box(xmin: float, ymin: float, xmax: float, ymax: float, ccw: bool = True, **kwargs: Unpack[UFuncKwargsNoOut]) -> Polygon: ... +@overload +def box( + xmin: ArrayLikeSeq[float], + ymin: ArrayLikeSeq[float], + xmax: ArrayLikeSeq[float], + ymax: ArrayLikeSeq[float], + ccw: bool = True, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... + +@overload +def multipoints( + geometries: Sequence[Point | Sequence[float] | None], + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPoint: ... +@overload +def multipoints( + geometries: Sequence[Sequence[Point | Sequence[float] | None]], + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def multipoints( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPoint | GeoArray: ... + +@overload +def multilinestrings( + geometries: Sequence[LineString | Sequence[Sequence[float]] | None], + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiLineString: ... +@overload +def multilinestrings( + geometries: Sequence[Sequence[LineString | Sequence[Sequence[float]] | None]], + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def multilinestrings( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiLineString | GeoArray: ... + +@overload +def multipolygons( + geometries: Sequence[Polygon | Sequence[Sequence[float]] | None], + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPolygon: ... +@overload +def multipolygons( + geometries: Sequence[Sequence[Polygon | Sequence[Sequence[float]] | None]], + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def multipolygons( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPolygon | GeoArray: ... + +@overload +def geometrycollections( + geometries: Sequence[Geometry | None], indices: None = None, out: None = None, **kwargs: Unpack[UFuncKwargsNoOut] +) -> GeometryCollection: ... +@overload +def geometrycollections( + geometries: Sequence[Sequence[Geometry | None]], + indices: ArrayLikeSeq[int] | None = None, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def geometrycollections( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeometryCollection | GeoArray: ... + +def prepare(geometry: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargsNoOut]) -> None: ... +def destroy_prepared(geometry: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargsNoOut]) -> None: ... +def empty( + shape: SupportsIndex | Sequence[SupportsIndex], geom_type: GeometryType | int | None = None, order: Literal["C", "F"] = "C" +) -> NDArray[np.object_]: ... diff --git a/stubs/shapely/shapely/decorators.pyi b/stubs/shapely/shapely/decorators.pyi new file mode 100644 index 000000000000..fe5131950cec --- /dev/null +++ b/stubs/shapely/shapely/decorators.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable, Container +from typing import TypeVar + +_F = TypeVar("_F", bound=Callable[..., object]) + +class requires_geos: + version: tuple[int, int, int] + def __init__(self, version: str) -> None: ... + def __call__(self, func: _F) -> _F: ... + +def multithreading_enabled(func: _F) -> _F: ... +def deprecate_positional(should_be_kwargs: Container[str], category: type[Warning] = ...) -> Callable[..., object]: ... diff --git a/stubs/shapely/shapely/errors.pyi b/stubs/shapely/shapely/errors.pyi new file mode 100644 index 000000000000..3cef1a428ab0 --- /dev/null +++ b/stubs/shapely/shapely/errors.pyi @@ -0,0 +1,17 @@ +from .lib import GEOSException as GEOSException, ShapelyError as ShapelyError + +def setup_signal_checks(interval: int = 10000) -> None: ... + +class UnsupportedGEOSVersionError(ShapelyError): ... +class DimensionError(ShapelyError): ... +class TopologicalError(ShapelyError): ... +class ShapelyDeprecationWarning(FutureWarning): ... +class EmptyPartError(ShapelyError): ... +class GeometryTypeError(ShapelyError): ... + +# deprecated aliases +ReadingError = ShapelyError +WKBReadingError = ShapelyError +WKTReadingError = ShapelyError +PredicateError = ShapelyError +InvalidGeometryError = ShapelyError diff --git a/stubs/shapely/shapely/geometry/__init__.pyi b/stubs/shapely/shapely/geometry/__init__.pyi new file mode 100644 index 000000000000..97227a3a41fa --- /dev/null +++ b/stubs/shapely/shapely/geometry/__init__.pyi @@ -0,0 +1,25 @@ +from .base import CAP_STYLE as CAP_STYLE, JOIN_STYLE as JOIN_STYLE +from .collection import GeometryCollection as GeometryCollection +from .geo import box as box, mapping as mapping, shape as shape +from .linestring import LineString as LineString +from .multilinestring import MultiLineString as MultiLineString +from .multipoint import MultiPoint as MultiPoint +from .multipolygon import MultiPolygon as MultiPolygon +from .point import Point as Point +from .polygon import LinearRing as LinearRing, Polygon as Polygon + +__all__ = [ + "box", + "shape", + "mapping", + "Point", + "LineString", + "Polygon", + "MultiPoint", + "MultiLineString", + "MultiPolygon", + "GeometryCollection", + "LinearRing", + "CAP_STYLE", + "JOIN_STYLE", +] diff --git a/stubs/shapely/shapely/geometry/base.pyi b/stubs/shapely/shapely/geometry/base.pyi new file mode 100644 index 000000000000..e4138123166b --- /dev/null +++ b/stubs/shapely/shapely/geometry/base.pyi @@ -0,0 +1,326 @@ +from array import array +from collections.abc import Iterator +from typing import Any, Generic, Literal, overload +from typing_extensions import Never, Self, TypeVar, deprecated + +import numpy as np +from numpy.typing import NDArray + +from .._typing import ArrayLikeSeq, GeoArray, GeoT, OptGeoArrayLike, OptGeoArrayLikeSeq +from ..constructive import BufferCapStyle, BufferJoinStyle +from ..coords import CoordinateSequence +from ..lib import Geometry +from .collection import GeometryCollection +from .point import Point +from .polygon import Polygon + +GEOMETRY_TYPES: list[str] + +@deprecated("Function 'geom_factory' is deprecated.") +def geom_factory(g: int, parent: object | None = None) -> Any: ... +def dump_coords(geom: Geometry) -> list[tuple[float, float] | list[tuple[float, float]]]: ... + +class CAP_STYLE: + round: Literal[BufferCapStyle.round] + flat: Literal[BufferCapStyle.flat] + square: Literal[BufferCapStyle.square] + +class JOIN_STYLE: + round: Literal[BufferJoinStyle.round] + mitre: Literal[BufferJoinStyle.mitre] + bevel: Literal[BufferJoinStyle.bevel] + +class BaseGeometry(Geometry): + __slots__: list[str] = [] + @deprecated( + "Directly calling 'BaseGeometry()' is deprecated. To create an empty geometry, " + "use one of the subclasses instead, for example 'GeometryCollection()'." + ) + def __new__(self) -> GeometryCollection: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __format__(self, format_spec: str) -> str: ... + + @overload + def __and__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __and__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __and__(self, other: None) -> None: ... + + @overload + def __or__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __or__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __or__(self, other: None) -> None: ... + + @overload + def __sub__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __sub__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __sub__(self, other: None) -> None: ... + + @overload + def __xor__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __xor__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __xor__(self, other: None) -> None: ... + + def __eq__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __hash__(self) -> int: ... + @property + def coords(self) -> CoordinateSequence: ... + @property + def xy(self) -> tuple[array[float], array[float]]: ... + @property + def __geo_interface__(self) -> dict[str, Any]: ... + @deprecated("Method 'geometryType()' is deprecated. Use attribute 'geom_type' instead.") + def geometryType(self) -> str: ... + @property + @deprecated("Attribute 'type' is deprecated. Use attribute 'geom_type' instead.") + def type(self) -> str: ... + @property + def wkt(self) -> str: ... + @property + def wkb(self) -> bytes: ... + @property + def wkb_hex(self) -> str: ... + def svg(self, scale_factor: float = 1.0, **kwargs) -> str: ... + def _repr_svg_(self) -> str: ... + @property + def geom_type(self) -> str: ... + @property + def area(self) -> float: ... + + @overload + def distance(self, other: Geometry | None) -> float: ... + @overload + def distance(self, other: OptGeoArrayLikeSeq) -> NDArray[np.float64]: ... + + @overload + def hausdorff_distance(self, other: Geometry | None) -> float: ... + @overload + def hausdorff_distance(self, other: OptGeoArrayLikeSeq) -> NDArray[np.float64]: ... + + @property + def length(self) -> float: ... + @property + def minimum_clearance(self) -> float: ... + @property + def boundary(self) -> BaseMultipartGeometry | Any: ... # is None for GeometryCollection + @property + def bounds(self) -> tuple[float, float, float, float]: ... + @property + def centroid(self) -> Point: ... + def point_on_surface(self) -> Point: ... + def representative_point(self) -> Point: ... + @property + def convex_hull(self) -> BaseGeometry: ... + @property + def envelope(self) -> BaseGeometry: ... + @property + def oriented_envelope(self) -> BaseGeometry: ... + @property + def minimum_rotated_rectangle(self) -> BaseGeometry: ... + def buffer( + self, + distance: float, + quad_segs: int = 16, + cap_style: BufferCapStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + *, + quadsegs: int | None = None, # deprecated + resolution: int | None = None, # deprecated + ) -> Polygon: ... + def simplify(self, tolerance: float, preserve_topology: bool = True) -> BaseGeometry: ... + def normalize(self) -> BaseGeometry: ... + + @overload + def difference(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def difference(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def difference(self, other: None, grid_size: float | None = None) -> None: ... + + @overload + def intersection(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def intersection(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def intersection(self, other: None, grid_size: float | None = None) -> None: ... + + @overload + def symmetric_difference(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def symmetric_difference(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def symmetric_difference(self, other: None, grid_size: float | None = None) -> None: ... + + @overload + def union(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def union(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def union(self, other: None, grid_size: float | None = None) -> None: ... + + @property + def has_z(self) -> bool: ... + @property + def has_m(self) -> bool: ... + @property + def is_empty(self) -> bool: ... + @property + def is_ring(self) -> bool: ... + @property + def is_closed(self) -> bool: ... + @property + def is_simple(self) -> bool: ... + @property + def is_valid(self) -> bool: ... + + @overload + def relate(self, other: Geometry) -> str: ... + @overload + def relate(self, other: OptGeoArrayLikeSeq) -> NDArray[np.str_]: ... + @overload + def relate(self, other: None) -> None: ... + + @overload + def covers(self, other: Geometry | None) -> bool: ... + @overload + def covers(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def covered_by(self, other: Geometry | None) -> bool: ... + @overload + def covered_by(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def contains(self, other: Geometry | None) -> bool: ... + @overload + def contains(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def contains_properly(self, other: Geometry | None) -> bool: ... + @overload + def contains_properly(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def crosses(self, other: Geometry | None) -> bool: ... + @overload + def crosses(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def disjoint(self, other: Geometry | None) -> bool: ... + @overload + def disjoint(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def equals(self, other: Geometry | None) -> bool: ... + @overload + def equals(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def intersects(self, other: Geometry | None) -> bool: ... + @overload + def intersects(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def overlaps(self, other: Geometry | None) -> bool: ... + @overload + def overlaps(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def touches(self, other: Geometry | None) -> bool: ... + @overload + def touches(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def within(self, other: Geometry | None) -> bool: ... + @overload + def within(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def dwithin(self, other: Geometry | None, distance: float) -> bool: ... + @overload + def dwithin(self, other: OptGeoArrayLikeSeq, distance: float) -> NDArray[np.bool_]: ... + @overload + def dwithin(self, other: OptGeoArrayLike, distance: ArrayLikeSeq[float]) -> NDArray[np.bool_]: ... + + @overload + def equals_exact(self, other: Geometry | None, tolerance: float = 0.0, *, normalize: bool = False) -> bool: ... + @overload + def equals_exact( + self, other: OptGeoArrayLikeSeq, tolerance: float = 0.0, *, normalize: bool = False + ) -> NDArray[np.bool_]: ... + @overload + def equals_exact( + self, other: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], *, normalize: bool = False + ) -> NDArray[np.bool_]: ... + + @overload + def relate_pattern(self, other: Geometry | None, pattern: str) -> bool: ... + @overload + def relate_pattern(self, other: OptGeoArrayLikeSeq, pattern: str) -> NDArray[np.bool_]: ... + + @overload + def line_locate_point(self, other: Point | None, normalized: bool = False) -> float: ... + @overload + def line_locate_point(self, other: OptGeoArrayLikeSeq, normalized: bool = False) -> NDArray[np.float64]: ... + + @overload + def project(self, other: Point | None, normalized: bool = False) -> float: ... + @overload + def project(self, other: OptGeoArrayLikeSeq, normalized: bool = False) -> NDArray[np.float64]: ... + + @overload + def line_interpolate_point(self, distance: float, normalized: bool = False) -> Point: ... + @overload + def line_interpolate_point(self, distance: ArrayLikeSeq[float], normalized: bool = False) -> GeoArray: ... + + @overload + def interpolate(self, distance: float, normalized: bool = False) -> Point: ... + @overload + def interpolate(self, distance: ArrayLikeSeq[float], normalized: bool = False) -> GeoArray: ... + + @overload + def segmentize(self, max_segment_length: float) -> Self: ... + @overload + def segmentize(self, max_segment_length: ArrayLikeSeq[float]) -> GeoArray: ... + + def reverse(self) -> Self: ... + +_GeoT_co = TypeVar("_GeoT_co", bound=Geometry, default=BaseGeometry, covariant=True) + +class BaseMultipartGeometry(BaseGeometry, Generic[_GeoT_co]): + __slots__: list[str] = [] + @property + def coords(self) -> Never: ... + @property + def geoms(self) -> GeometrySequence[Self]: ... + def svg(self, scale_factor: float = 1.0, color: str | None = None) -> str: ... # type: ignore[override] + +_P_co = TypeVar("_P_co", covariant=True, bound=BaseMultipartGeometry[Geometry]) + +class GeometrySequence(Generic[_P_co]): + def __init__(self, parent: _P_co) -> None: ... + def __iter__(self: GeometrySequence[BaseMultipartGeometry[GeoT]]) -> Iterator[GeoT]: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self: GeometrySequence[BaseMultipartGeometry[GeoT]], key: int | np.integer[Any]) -> GeoT: ... + @overload + def __getitem__(self, key: slice) -> _P_co: ... + +class EmptyGeometry(BaseGeometry): + @deprecated( + "The 'EmptyGeometry()' constructor is deprecated. Use one of the " + "geometry subclasses instead, for example 'GeometryCollection()'." + ) + def __new__(self) -> GeometryCollection: ... # type: ignore[misc] diff --git a/stubs/shapely/shapely/geometry/collection.pyi b/stubs/shapely/shapely/geometry/collection.pyi new file mode 100644 index 000000000000..abc1b7e42af1 --- /dev/null +++ b/stubs/shapely/shapely/geometry/collection.pyi @@ -0,0 +1,23 @@ +from collections.abc import Collection +from typing import Literal, overload +from typing_extensions import Self + +from .._typing import OptGeoArrayLike +from .base import BaseMultipartGeometry, GeometrySequence, _GeoT_co + +class GeometryCollection(BaseMultipartGeometry[_GeoT_co]): + # Overloads of __new__ are used because mypy is unable to narrow the typevar otherwise + __slots__: list[str] = [] + + @overload + def __new__( + self, geoms: BaseMultipartGeometry[_GeoT_co] | GeometrySequence[BaseMultipartGeometry[_GeoT_co]] | Collection[_GeoT_co] + ) -> Self: ... + @overload + def __new__(self, geoms: OptGeoArrayLike = None) -> Self: ... + + # more precise base overrides + @property + def geom_type(self) -> Literal["GeometryCollection"]: ... + @property + def boundary(self) -> None: ... diff --git a/stubs/shapely/shapely/geometry/geo.pyi b/stubs/shapely/shapely/geometry/geo.pyi new file mode 100644 index 000000000000..ac1c48664f48 --- /dev/null +++ b/stubs/shapely/shapely/geometry/geo.pyi @@ -0,0 +1,9 @@ +from typing import Any + +from .._typing import SupportsGeoInterface +from .base import BaseGeometry +from .polygon import Polygon + +def box(minx: float, miny: float, maxx: float, maxy: float, ccw: bool = True) -> Polygon: ... +def shape(context: dict[str, Any] | SupportsGeoInterface) -> BaseGeometry: ... +def mapping(ob: SupportsGeoInterface) -> dict[str, Any]: ... diff --git a/stubs/shapely/shapely/geometry/linestring.pyi b/stubs/shapely/shapely/geometry/linestring.pyi new file mode 100644 index 000000000000..54649d1e6963 --- /dev/null +++ b/stubs/shapely/shapely/geometry/linestring.pyi @@ -0,0 +1,48 @@ +from collections.abc import Iterable +from typing import Literal, SupportsFloat, SupportsIndex, TypeAlias +from typing_extensions import Self + +from .._typing import ArrayLikeSeq +from ..constructive import BufferJoinStyle +from .base import BaseGeometry +from .multilinestring import MultiLineString +from .multipoint import MultiPoint +from .point import Point +from .polygon import Polygon + +__all__ = ["LineString"] + +_ConvertibleToLineString: TypeAlias = LineString | ArrayLikeSeq[float] | Iterable[Point | Iterable[SupportsFloat]] + +class LineString(BaseGeometry): + __slots__: list[str] = [] + def __new__(self, coordinates: _ConvertibleToLineString | None = None) -> Self: ... + def svg(self, scale_factor: float = 1.0, stroke_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + def offset_curve( + self, + distance: float, + quad_segs: SupportsIndex = 16, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = ..., + mitre_limit: float = 5.0, + ) -> LineString | MultiLineString: ... + def parallel_offset( # to be deprecated + self, + distance: float, + side: str = "right", + resolution: SupportsIndex = 16, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = ..., + mitre_limit: float = 5.0, + ) -> LineString | MultiLineString: ... + # more precise base overrides + @property + def geom_type(self) -> Literal["LineString", "LinearRing"]: ... # LinearRing is a subclass of LineString + @property + def boundary(self) -> MultiPoint: ... + @property + def convex_hull(self) -> LineString: ... + @property + def envelope(self) -> Polygon: ... + @property + def oriented_envelope(self) -> LineString: ... + @property + def minimum_rotated_rectangle(self) -> LineString: ... diff --git a/stubs/shapely/shapely/geometry/multilinestring.pyi b/stubs/shapely/shapely/geometry/multilinestring.pyi new file mode 100644 index 000000000000..ec0f6c53857c --- /dev/null +++ b/stubs/shapely/shapely/geometry/multilinestring.pyi @@ -0,0 +1,19 @@ +from collections.abc import Collection +from typing import Literal +from typing_extensions import Self + +from .base import BaseMultipartGeometry +from .linestring import LineString, _ConvertibleToLineString +from .multipoint import MultiPoint + +__all__ = ["MultiLineString"] + +class MultiLineString(BaseMultipartGeometry[LineString]): + __slots__: list[str] = [] + def __new__(self, lines: BaseMultipartGeometry | Collection[_ConvertibleToLineString] | None = None) -> Self: ... + def svg(self, scale_factor: float = 1.0, stroke_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["MultiLineString"]: ... + @property + def boundary(self) -> MultiPoint: ... diff --git a/stubs/shapely/shapely/geometry/multipoint.pyi b/stubs/shapely/shapely/geometry/multipoint.pyi new file mode 100644 index 000000000000..c931c474d165 --- /dev/null +++ b/stubs/shapely/shapely/geometry/multipoint.pyi @@ -0,0 +1,24 @@ +from collections.abc import Collection +from typing import Literal +from typing_extensions import Self + +from .base import BaseMultipartGeometry +from .collection import GeometryCollection +from .point import Point, _PointLike + +__all__ = ["MultiPoint"] + +class MultiPoint(BaseMultipartGeometry[Point]): + # Note on "points" type in `__new__`: + # * `Collection` here is loose as the expected type should support "__getitem__". + # * `Sequence` is more correct but it will lead to False positives with common types + # like np.ndarray, pd.Index, pd.Series, ... + # I went with Collection as false negatives seem better to me than false positives in this case + __slots__: list[str] = [] + def __new__(self, points: MultiPoint | Collection[_PointLike] | None = None) -> Self: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["MultiPoint"]: ... + @property + def boundary(self) -> GeometryCollection: ... # empty geometry collection diff --git a/stubs/shapely/shapely/geometry/multipolygon.pyi b/stubs/shapely/shapely/geometry/multipolygon.pyi new file mode 100644 index 000000000000..0c60c5fa7da9 --- /dev/null +++ b/stubs/shapely/shapely/geometry/multipolygon.pyi @@ -0,0 +1,26 @@ +from collections.abc import Collection +from typing import Literal +from typing_extensions import Self + +from .base import BaseMultipartGeometry +from .multilinestring import MultiLineString +from .polygon import Polygon, _PolygonHolesLike, _PolygonShellLike + +__all__ = ["MultiPolygon"] + +class MultiPolygon(BaseMultipartGeometry[Polygon]): + __slots__: list[str] = [] + def __new__( + self, + polygons: ( + BaseMultipartGeometry + | Collection[Polygon | tuple[_PolygonShellLike] | tuple[_PolygonShellLike, _PolygonHolesLike] | None] + | None + ) = None, + ) -> Self: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["MultiPolygon"]: ... + @property + def boundary(self) -> MultiLineString: ... diff --git a/stubs/shapely/shapely/geometry/point.pyi b/stubs/shapely/shapely/geometry/point.pyi new file mode 100644 index 000000000000..5f37e65a7b93 --- /dev/null +++ b/stubs/shapely/shapely/geometry/point.pyi @@ -0,0 +1,46 @@ +from collections.abc import Iterable +from typing import Literal, TypeAlias, overload +from typing_extensions import Self + +from .._typing import ArrayLikeSeq +from .base import BaseGeometry +from .collection import GeometryCollection + +__all__ = ["Point"] + +_PointLike: TypeAlias = Point | Iterable[float] | ArrayLikeSeq[float] + +class Point(BaseGeometry): + __slots__: list[str] = [] + + @overload # no args: empty point + def __new__(self) -> Self: ... + @overload # one arg: (x, y[, z]) tuple or a Point instance + def __new__(self, coords: _PointLike, /) -> Self: ... + @overload # two args: (x, y) tuple + def __new__(self, x: float, y: float, /) -> Self: ... + @overload # three args: (x, y, z) tuple + def __new__(self, x: float, y: float, z: float, /) -> Self: ... + + @property + def x(self) -> float: ... + @property + def y(self) -> float: ... + @property + def z(self) -> float: ... + @property + def m(self) -> float: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["Point"]: ... + @property + def boundary(self) -> GeometryCollection: ... # empty geometry collection + @property + def convex_hull(self) -> Point: ... + @property + def envelope(self) -> Point: ... + @property + def oriented_envelope(self) -> Point: ... + @property + def minimum_rotated_rectangle(self) -> Point: ... diff --git a/stubs/shapely/shapely/geometry/polygon.pyi b/stubs/shapely/shapely/geometry/polygon.pyi new file mode 100644 index 000000000000..e52857a88946 --- /dev/null +++ b/stubs/shapely/shapely/geometry/polygon.pyi @@ -0,0 +1,52 @@ +from collections.abc import Collection +from typing import Literal, TypeAlias, overload +from typing_extensions import Never, Self + +from .base import BaseGeometry +from .linestring import LineString, _ConvertibleToLineString +from .multilinestring import MultiLineString + +__all__ = ["orient", "Polygon", "LinearRing"] + +_ConvertibleToLinearRing: TypeAlias = _ConvertibleToLineString # same alias but with better name for doc purposes +_PolygonShellLike: TypeAlias = Polygon | _ConvertibleToLinearRing | None +_PolygonHolesLike: TypeAlias = Collection[_ConvertibleToLinearRing | None] | None + +class LinearRing(LineString): + __slots__: list[str] = [] + def __new__(self, coordinates: _ConvertibleToLinearRing | None = None) -> Self: ... + @property + def is_ccw(self) -> bool: ... + @property + def geom_type(self) -> Literal["LinearRing"]: ... + +class InteriorRingSequence: + def __init__(self, parent: Polygon) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> LinearRing: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, key: int) -> LinearRing: ... + @overload + def __getitem__(self, key: slice) -> list[LinearRing]: ... + +class Polygon(BaseGeometry): + __slots__: list[str] = [] + def __new__(self, shell: _PolygonShellLike = None, holes: _PolygonHolesLike = None) -> Self: ... + @property + def exterior(self) -> LinearRing: ... + @property + def interiors(self) -> list[LinearRing] | InteriorRingSequence: ... + @property + def coords(self) -> Never: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + @classmethod + def from_bounds(cls, xmin: float, ymin: float, xmax: float, ymax: float) -> Self: ... + # more precise base overrides + @property + def geom_type(self) -> Literal["Polygon"]: ... + @property + def boundary(self) -> MultiLineString: ... + +def orient(polygon: Polygon, sign: float = 1.0) -> Polygon: ... diff --git a/stubs/shapely/shapely/geos.pyi b/stubs/shapely/shapely/geos.pyi new file mode 100644 index 000000000000..669802c38a36 --- /dev/null +++ b/stubs/shapely/shapely/geos.pyi @@ -0,0 +1,3 @@ +geos_version_string: str +geos_version: tuple[int, int, int] +geos_capi_version: tuple[int, int, int] diff --git a/stubs/shapely/shapely/io.pyi b/stubs/shapely/shapely/io.pyi new file mode 100644 index 000000000000..2506df3e6c3b --- /dev/null +++ b/stubs/shapely/shapely/io.pyi @@ -0,0 +1,176 @@ +from _typeshed import Incomplete +from typing import Literal, TypeAlias, overload +from typing_extensions import Unpack + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._ragged_array import from_ragged_array as from_ragged_array, to_ragged_array as to_ragged_array +from ._typing import ArrayLikeSeq, GeoArray, OptGeoArrayLikeSeq, UFuncKwargs +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = ["from_geojson", "from_ragged_array", "from_wkb", "from_wkt", "to_geojson", "to_ragged_array", "to_wkb", "to_wkt"] + +_OutputDimension: TypeAlias = Literal[2, 3, 4] + +# Mypy and stubtest aren't happy with the following definition and +# raise is a reserved keyword, so we cannot use the class syntax of enums +# DecodingErrorOptions = ParamEnum("DecodingErrorOptions", {"ignore": 0, "warn": 1, "raise": 2, "fix": 3}) +DecodingErrorOptions: Incomplete + +class WKBFlavorOptions(ParamEnum): + extended = 1 + iso = 2 + +@overload +def to_wkt( + geometry: None, + rounding_precision: int = 6, + trim: bool = True, + output_dimension: _OutputDimension | None = None, + old_3d: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def to_wkt( + geometry: Geometry, + rounding_precision: int = 6, + trim: bool = True, + output_dimension: _OutputDimension | None = None, + old_3d: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> str: ... +@overload +def to_wkt( + geometry: OptGeoArrayLikeSeq, + rounding_precision: int = 6, + trim: bool = True, + output_dimension: _OutputDimension | None = None, + old_3d: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.str_]: ... + +@overload +def to_wkb( + geometry: None, + hex: bool = False, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def to_wkb( + geometry: Geometry, + hex: Literal[False] = False, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> bytes: ... +@overload +def to_wkb( + geometry: Geometry, + hex: Literal[True], + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> str: ... +@overload +def to_wkb( + geometry: Geometry, + hex: bool, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> bytes | str: ... +@overload +def to_wkb( + geometry: OptGeoArrayLikeSeq, + hex: Literal[False] = False, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bytes_]: ... +@overload +def to_wkb( + geometry: OptGeoArrayLikeSeq, + hex: Literal[True], + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.str_]: ... +@overload +def to_wkb( + geometry: OptGeoArrayLikeSeq, + hex: bool, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bytes_] | NDArray[np.str_]: ... + +@overload +def to_geojson(geometry: None, indent: int | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def to_geojson(geometry: Geometry, indent: int | None = None, **kwargs: Unpack[UFuncKwargs]) -> str: ... +@overload +def to_geojson(geometry: OptGeoArrayLikeSeq, indent: int | None = None, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.str_]: ... + +@overload +def from_wkt( + geometry: None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def from_wkt( # type: ignore[overload-overlap] + geometry: str, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def from_wkt( + geometry: ArrayLikeSeq[str | None], + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def from_wkb( + geometry: None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def from_wkb( # type: ignore[overload-overlap] + geometry: str | bytes, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def from_wkb( + geometry: ArrayLikeSeq[str | bytes | None], + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def from_geojson( + geometry: None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def from_geojson( # type: ignore[overload-overlap] + geometry: str | bytes, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def from_geojson( + geometry: ArrayLikeSeq[str | bytes | None], + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... diff --git a/stubs/shapely/shapely/lib.pyi b/stubs/shapely/shapely/lib.pyi new file mode 100644 index 000000000000..ea224928eab6 --- /dev/null +++ b/stubs/shapely/shapely/lib.pyi @@ -0,0 +1,182 @@ +from typing import Literal, SupportsIndex, final, overload +from typing_extensions import Never, Self, disjoint_base + +import numpy as np +from numpy.typing import NDArray + +area: np.ufunc +boundary: np.ufunc +bounds: np.ufunc +box: np.ufunc +buffer: np.ufunc +build_area: np.ufunc +centroid: np.ufunc +clip_by_rect: np.ufunc +concave_hull: np.ufunc +constrained_delaunay_triangles: np.ufunc +contains: np.ufunc +contains_properly: np.ufunc +contains_xy: np.ufunc +convex_hull: np.ufunc +coverage_invalid_edges: np.ufunc +coverage_is_valid: np.ufunc +coverage_simplify: np.ufunc +coverage_union: np.ufunc +covered_by: np.ufunc +covers: np.ufunc +create_collection: np.ufunc +crosses: np.ufunc +delaunay_triangles: np.ufunc +destroy_prepared: np.ufunc +difference: np.ufunc +difference_prec: np.ufunc +disjoint: np.ufunc +disjoint_subset_union: np.ufunc +distance: np.ufunc +dwithin: np.ufunc +envelope: np.ufunc +equals: np.ufunc +equals_exact: np.ufunc +equals_identical: np.ufunc +extract_unique_points: np.ufunc +force_2d: np.ufunc +force_3d: np.ufunc +frechet_distance: np.ufunc +frechet_distance_densify: np.ufunc +from_geojson: np.ufunc +from_wkb: np.ufunc +from_wkt: np.ufunc +get_coordinate_dimension: np.ufunc +get_dimensions: np.ufunc +get_exterior_ring: np.ufunc +get_geometry: np.ufunc +get_interior_ring: np.ufunc +get_m: np.ufunc +get_num_coordinates: np.ufunc +get_num_geometries: np.ufunc +get_num_interior_rings: np.ufunc +get_num_points: np.ufunc +get_point: np.ufunc +get_precision: np.ufunc +get_srid: np.ufunc +get_type_id: np.ufunc +has_m: np.ufunc +get_x: np.ufunc +get_y: np.ufunc +get_z: np.ufunc +has_z: np.ufunc +hausdorff_distance: np.ufunc +hausdorff_distance_densify: np.ufunc +intersection: np.ufunc +intersection_all: np.ufunc +intersection_prec: np.ufunc +intersects: np.ufunc +intersects_xy: np.ufunc +is_ccw: np.ufunc +is_closed: np.ufunc +is_empty: np.ufunc +is_geometry: np.ufunc +is_missing: np.ufunc +is_prepared: np.ufunc +is_ring: np.ufunc +is_simple: np.ufunc +is_valid: np.ufunc +is_valid_input: np.ufunc +is_valid_reason: np.ufunc +length: np.ufunc +line_interpolate_point: np.ufunc +line_interpolate_point_normalized: np.ufunc +line_locate_point: np.ufunc +line_locate_point_normalized: np.ufunc +line_merge: np.ufunc +line_merge_directed: np.ufunc +linearrings: np.ufunc +linestrings: np.ufunc +make_valid: np.ufunc +make_valid_with_params: np.ufunc +maximum_inscribed_circle: np.ufunc +minimum_bounding_circle: np.ufunc +minimum_bounding_radius: np.ufunc +minimum_clearance: np.ufunc +minimum_clearance_line: np.ufunc +node: np.ufunc +normalize: np.ufunc +offset_curve: np.ufunc +orient_polygons: np.ufunc +oriented_envelope: np.ufunc +overlaps: np.ufunc +point_on_surface: np.ufunc +points: np.ufunc +polygonize: np.ufunc +polygonize_full: np.ufunc +polygons: np.ufunc +prepare: np.ufunc +relate: np.ufunc +relate_pattern: np.ufunc +remove_repeated_points: np.ufunc +reverse: np.ufunc +segmentize: np.ufunc +set_precision: np.ufunc +set_srid: np.ufunc +shared_paths: np.ufunc +shortest_line: np.ufunc +simplify: np.ufunc +simplify_preserve_topology: np.ufunc +snap: np.ufunc +symmetric_difference: np.ufunc +symmetric_difference_all: np.ufunc +symmetric_difference_prec: np.ufunc +to_geojson: np.ufunc +to_wkb: np.ufunc +to_wkt: np.ufunc +touches: np.ufunc +unary_union: np.ufunc +unary_union_prec: np.ufunc +union: np.ufunc +union_prec: np.ufunc +voronoi_polygons: np.ufunc +within: np.ufunc +geos_capi_version: tuple[int, int, int] +geos_capi_version_string: str +geos_version: tuple[int, int, int] +geos_version_string: str +registry: list[type[Geometry]] + +@disjoint_base +class Geometry: + def __hash__(self) -> int: ... + def __eq__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __ge__(self, other: Never, /) -> bool: ... + def __gt__(self, other: Never, /) -> bool: ... + def __le__(self, other: Never, /) -> bool: ... + def __lt__(self, other: Never, /) -> bool: ... + +@final +class STRtree: + count: int + def __new__(cls, geoms: NDArray[np.object_], node_capacity: SupportsIndex, /, **kwargs: object) -> Self: ... + def dwithin(self, geoms: NDArray[np.object_], distances: NDArray[np.float64], /) -> NDArray[np.int64]: ... + def nearest(self, geoms: NDArray[np.object_], /) -> NDArray[np.int64]: ... + def query(self, geoms: NDArray[np.object_], predicate: SupportsIndex, /) -> NDArray[np.int64]: ... + def query_nearest( + self, geoms: NDArray[np.object_], max_distance: float, exclusive: SupportsIndex, all_matches: SupportsIndex, / + ) -> tuple[NDArray[np.int64], NDArray[np.float64]]: ... + +class ShapelyError(Exception): ... +class GEOSException(ShapelyError): ... + +def count_coordinates(geoms: NDArray[np.object_], /) -> int: ... + +@overload +def get_coordinates(arr: NDArray[np.object_], include_z: bool, return_index: Literal[False], /) -> NDArray[np.float64]: ... +@overload +def get_coordinates( + arr: NDArray[np.object_], include_z: bool, return_index: Literal[True], / +) -> tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + arr: NDArray[np.object_], include_z: bool, return_index: bool, / +) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.int64]]: ... + +def set_coordinates(geoms: NDArray[np.object_], coords: NDArray[np.float64], /) -> NDArray[np.object_]: ... diff --git a/stubs/shapely/shapely/linear.pyi b/stubs/shapely/shapely/linear.pyi new file mode 100644 index 000000000000..904a00ce1f95 --- /dev/null +++ b/stubs/shapely/shapely/linear.pyi @@ -0,0 +1,73 @@ +from typing import overload + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq +from .geometry import GeometryCollection, LineString, MultiLineString, Point +from .lib import Geometry + +__all__ = ["line_interpolate_point", "line_locate_point", "line_merge", "shared_paths", "shortest_line"] + +@overload +def line_interpolate_point(line: None, distance: float, normalized: bool = False, **kwargs) -> None: ... +@overload +def line_interpolate_point( + line: None, distance: ArrayLikeSeq[float], normalized: bool = False, **kwargs +) -> NDArray[np.object_]: ... # Array of None +@overload +def line_interpolate_point( + line: LineString | MultiLineString | GeometryCollection, distance: float, normalized: bool = False, **kwargs +) -> Point: ... +@overload +def line_interpolate_point( + line: LineString | MultiLineString | GeometryCollection, distance: ArrayLikeSeq[float], normalized: bool = False, **kwargs +) -> GeoArray: ... +@overload +def line_interpolate_point( + line: OptGeoArrayLikeSeq, distance: ArrayLike[float], normalized: bool = False, **kwargs +) -> GeoArray: ... + +@overload +def line_locate_point( + line: LineString | MultiLineString | GeometryCollection | None, other: Point | None, normalized: bool = False, **kwargs +) -> np.float64: ... +@overload +def line_locate_point( + line: LineString | MultiLineString | GeometryCollection | None, other: OptGeoArrayLikeSeq, normalized: bool = False, **kwargs +) -> NDArray[np.float64]: ... +@overload +def line_locate_point( + line: OptGeoArrayLikeSeq, other: OptGeoArrayLike, normalized: bool = False, **kwargs +) -> NDArray[np.float64]: ... + +@overload +def line_merge(line: None, directed: bool = False, **kwargs) -> None: ... +@overload +def line_merge(line: Geometry, directed: bool = False, **kwargs) -> LineString | MultiLineString | GeometryCollection: ... +@overload +def line_merge(line: OptGeoArrayLikeSeq, directed: bool = False, **kwargs) -> GeoArray: ... + +@overload +def shared_paths(a: LineString | MultiLineString | None, b: None, **kwargs) -> None: ... +@overload +def shared_paths(a: None, b: LineString | MultiLineString | None, **kwargs) -> None: ... +@overload +def shared_paths( + a: LineString | MultiLineString, b: LineString | MultiLineString, **kwargs +) -> GeometryCollection[MultiLineString]: ... +@overload +def shared_paths(a: LineString | MultiLineString | None, b: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... +@overload +def shared_paths(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs) -> GeoArray: ... + +@overload +def shortest_line(a: Geometry | None, b: None, **kwargs) -> None: ... +@overload +def shortest_line(a: None, b: Geometry | None, **kwargs) -> None: ... +@overload +def shortest_line(a: Geometry, b: Geometry, **kwargs) -> LineString: ... +@overload +def shortest_line(a: Geometry | None, b: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... +@overload +def shortest_line(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs) -> GeoArray: ... diff --git a/stubs/shapely/shapely/measurement.pyi b/stubs/shapely/shapely/measurement.pyi new file mode 100644 index 000000000000..b0291b92f633 --- /dev/null +++ b/stubs/shapely/shapely/measurement.pyi @@ -0,0 +1,75 @@ +from typing import overload + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLike, ArrayLikeSeq, OptGeoArrayLike, OptGeoArrayLikeSeq +from .lib import Geometry + +__all__ = [ + "area", + "bounds", + "distance", + "frechet_distance", + "hausdorff_distance", + "length", + "minimum_bounding_radius", + "minimum_clearance", + "total_bounds", +] + +@overload +def area(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def area(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def distance(a: Geometry | None, b: Geometry | None, **kwargs) -> np.float64: ... +@overload +def distance(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs) -> NDArray[np.float64]: ... +@overload +def distance(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +def bounds(geometry: OptGeoArrayLike, **kwargs) -> NDArray[np.float64]: ... +def total_bounds(geometry: OptGeoArrayLike, **kwargs) -> NDArray[np.float64]: ... + +@overload +def length(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def length(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def hausdorff_distance(a: Geometry | None, b: Geometry | None, densify: float | None = None, **kwargs) -> np.float64: ... +@overload +def hausdorff_distance(a: OptGeoArrayLike, b: OptGeoArrayLike, densify: ArrayLikeSeq[float], **kwargs) -> NDArray[np.float64]: ... +@overload +def hausdorff_distance( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... +@overload +def hausdorff_distance( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... + +@overload +def frechet_distance(a: Geometry | None, b: Geometry | None, densify: float | None = None, **kwargs) -> np.float64: ... +@overload +def frechet_distance(a: OptGeoArrayLike, b: OptGeoArrayLike, densify: ArrayLikeSeq[float], **kwargs) -> NDArray[np.float64]: ... +@overload +def frechet_distance( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... +@overload +def frechet_distance( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... + +@overload +def minimum_clearance(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def minimum_clearance(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def minimum_bounding_radius(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def minimum_bounding_radius(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... diff --git a/stubs/shapely/shapely/ops.pyi b/stubs/shapely/shapely/ops.pyi new file mode 100644 index 000000000000..206f91861b3e --- /dev/null +++ b/stubs/shapely/shapely/ops.pyi @@ -0,0 +1,104 @@ +from collections.abc import Callable, Iterable +from typing import Any, Literal, overload + +from ._typing import GeoT, OptGeoArrayLike, SupportsGeoInterface +from .algorithms.polylabel import polylabel as polylabel +from .geometry import GeometryCollection, LineString, MultiLineString, Point, Polygon +from .geometry.base import BaseGeometry, BaseMultipartGeometry, GeometrySequence +from .geometry.linestring import _ConvertibleToLineString +from .lib import Geometry + +__all__ = [ + "clip_by_rect", + "linemerge", + "nearest_points", + "operator", + "orient", + "polygonize", + "polygonize_full", + "shared_paths", + "snap", + "split", + "substring", + "transform", + "triangulate", + "unary_union", + "validate", + "voronoi_diagram", +] + +class CollectionOperator: + @overload + def shapeup(self, ob: GeoT) -> GeoT: ... # type: ignore[overload-overlap] + @overload + def shapeup(self, ob: dict[str, Any] | SupportsGeoInterface) -> BaseGeometry: ... # type: ignore[overload-overlap] + @overload + def shapeup(self, ob: _ConvertibleToLineString) -> LineString: ... + + def polygonize( + self, lines: OptGeoArrayLike | Iterable[_ConvertibleToLineString | None] + ) -> GeometrySequence[GeometryCollection[Polygon]]: ... + def polygonize_full( + self, lines: OptGeoArrayLike | Iterable[_ConvertibleToLineString | None] + ) -> tuple[ + GeometryCollection[Polygon], GeometryCollection[LineString], GeometryCollection[LineString], GeometryCollection[Polygon] + ]: ... + def linemerge( + self, lines: MultiLineString | BaseMultipartGeometry | Iterable[_ConvertibleToLineString], directed: bool = False + ) -> LineString | MultiLineString: ... + def unary_union(self, geoms: OptGeoArrayLike) -> BaseGeometry: ... + +operator: CollectionOperator +polygonize = operator.polygonize +polygonize_full = operator.polygonize_full +linemerge = operator.linemerge +unary_union = operator.unary_union + +# This is also an alias to operator method but we want to mark it as deprecated +@overload # edges false +def triangulate(geom: Geometry, tolerance: float = 0.0, edges: Literal[False] = False) -> list[Polygon]: ... +@overload # edges true (keyword) +def triangulate(geom: Geometry, tolerance: float = 0.0, *, edges: Literal[True]) -> list[LineString]: ... +@overload # edges true (positional) +def triangulate(geom: Geometry, tolerance: float, edges: Literal[True]) -> list[LineString]: ... +@overload # fallback +def triangulate(geom: Geometry, tolerance: float = 0.0, edges: bool = False) -> list[Polygon] | list[LineString]: ... + +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None = None, tolerance: float = 0.0, edges: Literal[False] = False +) -> GeometryCollection[Polygon]: ... +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None, tolerance: float, edges: Literal[True] +) -> GeometryCollection[LineString | MultiLineString]: ... +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None = None, tolerance: float = 0.0, *, edges: Literal[True] +) -> GeometryCollection[LineString | MultiLineString]: ... +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None = None, tolerance: float = 0.0, edges: bool = False +) -> GeometryCollection[Polygon | LineString | MultiLineString]: ... + +@overload +def validate(geom: None) -> None: ... +@overload +def validate(geom: Geometry) -> str: ... +@overload +def validate(geom: Geometry | None) -> str | None: ... + +def transform(func: Callable[[float, float, float | None], tuple[float, ...]], geom: GeoT) -> GeoT: ... +def nearest_points(g1: Geometry, g2: Geometry) -> tuple[Point, Point]: ... +def snap(g1: GeoT, g2: Geometry, tolerance: float) -> GeoT: ... +def shared_paths(g1: LineString, g2: LineString) -> GeometryCollection[MultiLineString]: ... + +class SplitOp: + @staticmethod + def split(geom: Geometry, splitter: Geometry) -> GeometryCollection: ... + +split = SplitOp.split + +def substring(geom: LineString, start_dist: float, end_dist: float, normalized: bool = False) -> Point | LineString: ... +def clip_by_rect(geom: Geometry, xmin: float, ymin: float, xmax: float, ymax: float) -> BaseGeometry: ... +def orient(geom: GeoT, sign: float = 1.0) -> GeoT: ... diff --git a/stubs/shapely/shapely/plotting.pyi b/stubs/shapely/shapely/plotting.pyi new file mode 100644 index 000000000000..5afa968029c4 --- /dev/null +++ b/stubs/shapely/shapely/plotting.pyi @@ -0,0 +1,79 @@ +from typing import Any, Literal, overload + +from matplotlib.axes import Axes # type: ignore[import-not-found] +from matplotlib.lines import Line2D # type: ignore[import-not-found] +from matplotlib.patches import PathPatch # type: ignore[import-not-found] +from matplotlib.typing import ColorType # type: ignore[import-not-found] + +from .geometry import LinearRing, LineString, MultiLineString, MultiPolygon, Polygon +from .lib import Geometry + +def patch_from_polygon(polygon: Polygon | MultiPolygon, **kwargs: Any) -> PathPatch: ... + +@overload +def plot_polygon( + polygon: Polygon | MultiPolygon, + ax: Axes | None = None, + add_points: Literal[True] = True, + color: ColorType | None = None, + facecolor: ColorType | None = None, + edgecolor: ColorType | None = None, + linewidth: float | None = None, + **kwargs: Any, +) -> tuple[PathPatch, Line2D]: ... +@overload +def plot_polygon( + polygon: Polygon | MultiPolygon, + ax: Axes | None = None, + *, + add_points: Literal[False], + color: ColorType | None = None, + facecolor: ColorType | None = None, + edgecolor: ColorType | None = None, + linewidth: float | None = None, + **kwargs: Any, +) -> PathPatch: ... +@overload +def plot_polygon( + polygon: Polygon | MultiPolygon, + ax: Axes | None, + add_points: Literal[False], + color: ColorType | None = None, + facecolor: ColorType | None = None, + edgecolor: ColorType | None = None, + linewidth: float | None = None, + **kwargs: Any, +) -> PathPatch: ... + +@overload +def plot_line( + line: LineString | LinearRing | MultiLineString, + ax: Axes | None = None, + add_points: Literal[True] = True, + color: ColorType | None = None, + linewidth: float = 2, + **kwargs: Any, +) -> tuple[PathPatch, Line2D]: ... +@overload +def plot_line( + line: LineString | LinearRing | MultiLineString, + ax: Axes | None = None, + *, + add_points: Literal[False], + color: ColorType | None = None, + linewidth: float = 2, + **kwargs: Any, +) -> PathPatch: ... +@overload +def plot_line( + line: LineString | LinearRing | MultiLineString, + ax: Axes | None, + add_points: Literal[False], + color: ColorType | None = None, + linewidth: float = 2, + **kwargs: Any, +) -> PathPatch: ... + +def plot_points( + geom: Geometry, ax: Axes | None = None, color: ColorType | None = None, marker: str = "o", **kwargs: Any +) -> Line2D: ... diff --git a/stubs/shapely/shapely/predicates.pyi b/stubs/shapely/shapely/predicates.pyi new file mode 100644 index 000000000000..03e2a2fd4b50 --- /dev/null +++ b/stubs/shapely/shapely/predicates.pyi @@ -0,0 +1,303 @@ +from typing import Any, Literal, TypeGuard, overload +from typing_extensions import Unpack + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLike, ArrayLikeSeq, OptGeoArrayLike, OptGeoArrayLikeSeq, UFuncKwargs +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = [ + "contains", + "contains_properly", + "contains_xy", + "covered_by", + "covers", + "crosses", + "disjoint", + "dwithin", + "equals", + "equals_exact", + "equals_identical", + "has_m", + "has_z", + "intersects", + "intersects_xy", + "is_ccw", + "is_closed", + "is_empty", + "is_geometry", + "is_missing", + "is_prepared", + "is_ring", + "is_simple", + "is_valid", + "is_valid_input", + "is_valid_reason", + "overlaps", + "relate", + "relate_pattern", + "touches", + "within", +] + +@overload +def has_z(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def has_z(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def has_m(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def has_m(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_ccw(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_ccw(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_closed(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_closed(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_empty(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_empty(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_geometry(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[True]]: ... # type: ignore[overload-overlap] +@overload +def is_geometry(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[False]]: ... +@overload +def is_geometry(geometry: ArrayLikeSeq[Any], **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... # type: ignore[overload-overlap] +@overload +def is_geometry(geometry: object, **kwargs: Unpack[UFuncKwargs]) -> TypeGuard[BaseGeometry]: ... + +@overload +def is_missing(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[False]]: ... # type: ignore[overload-overlap] +@overload +def is_missing(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[True]]: ... +@overload +def is_missing(geometry: ArrayLikeSeq[Any], **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... # type: ignore[overload-overlap] +@overload +def is_missing(geometry: object, **kwargs: Unpack[UFuncKwargs]) -> TypeGuard[None]: ... + +@overload +def is_prepared(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_prepared(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_valid_input(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[True]]: ... # type: ignore[overload-overlap] +@overload +def is_valid_input(geometry: ArrayLikeSeq[Any], **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... # type: ignore[overload-overlap] +@overload +def is_valid_input(geometry: object, **kwargs: Unpack[UFuncKwargs]) -> TypeGuard[BaseGeometry | None]: ... + +@overload +def is_ring(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_ring(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_simple(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_simple(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_valid(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_valid(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_valid_reason(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def is_valid_reason(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> str: ... +@overload +def is_valid_reason(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.object_]: ... + +@overload +def crosses(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def crosses(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def crosses(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def contains(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def contains(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def contains(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def contains_properly(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def contains_properly(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def contains_properly(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def covered_by(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def covered_by(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def covered_by(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def covers(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def covers(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def covers(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def disjoint(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def disjoint(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def disjoint(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def equals(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def equals(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def equals(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def intersects(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def intersects(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def intersects(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def overlaps(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def overlaps(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def overlaps(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def touches(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def touches(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def touches(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def within(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def within(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def within(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def equals_exact( + a: Geometry | None, b: Geometry | None, tolerance: float = 0.0, *, normalize: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> np.bool_: ... +@overload +def equals_exact( + a: OptGeoArrayLike, + b: OptGeoArrayLike, + tolerance: ArrayLikeSeq[float], + *, + normalize: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bool_]: ... +@overload +def equals_exact( + a: OptGeoArrayLikeSeq, + b: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + *, + normalize: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bool_]: ... +@overload +def equals_exact( + a: OptGeoArrayLike, + b: OptGeoArrayLikeSeq, + tolerance: ArrayLike[float] = 0.0, + *, + normalize: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bool_]: ... + +@overload +def equals_identical(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def equals_identical(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def equals_identical(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def relate(a: Geometry | None, b: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def relate(a: None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def relate(a: Geometry, b: Geometry, **kwargs: Unpack[UFuncKwargs]) -> str: ... +@overload +def relate(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.object_]: ... +@overload +def relate(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.object_]: ... + +@overload +def relate_pattern(a: Geometry | None, b: Geometry | None, pattern: str, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def relate_pattern( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, pattern: str, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def relate_pattern( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, pattern: str, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... + +@overload +def dwithin(a: Geometry | None, b: Geometry | None, distance: float, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def dwithin(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, distance: float, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def dwithin(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, distance: float, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def contains_xy(geom: Geometry | None, x: float, y: float, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def contains_xy( + geom: OptGeoArrayLike, x: ArrayLikeSeq[float], y: None = None, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def contains_xy( + geom: Geometry | None, x: ArrayLike[float], y: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def contains_xy( + geom: Geometry | None, x: ArrayLikeSeq[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def contains_xy( + geom: OptGeoArrayLikeSeq, x: ArrayLike[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... + +@overload +def intersects_xy(geom: Geometry | None, x: float, y: float, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def intersects_xy( + geom: OptGeoArrayLike, x: ArrayLikeSeq[float], y: None = None, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def intersects_xy( + geom: Geometry | None, x: ArrayLike[float], y: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def intersects_xy( + geom: Geometry | None, x: ArrayLikeSeq[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def intersects_xy( + geom: OptGeoArrayLikeSeq, x: ArrayLike[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... diff --git a/stubs/shapely/shapely/prepared.pyi b/stubs/shapely/shapely/prepared.pyi new file mode 100644 index 000000000000..e89026dc3d36 --- /dev/null +++ b/stubs/shapely/shapely/prepared.pyi @@ -0,0 +1,20 @@ +from typing import Generic, Literal + +from ._typing import GeoT +from .lib import Geometry + +class PreparedGeometry(Generic[GeoT]): + context: GeoT + prepared: Literal[True] + def __init__(self, context: GeoT | PreparedGeometry[GeoT]) -> None: ... + def contains(self, other: Geometry | None) -> bool: ... + def contains_properly(self, other: Geometry | None) -> bool: ... + def covers(self, other: Geometry | None) -> bool: ... + def crosses(self, other: Geometry | None) -> bool: ... + def disjoint(self, other: Geometry | None) -> bool: ... + def intersects(self, other: Geometry | None) -> bool: ... + def overlaps(self, other: Geometry | None) -> bool: ... + def touches(self, other: Geometry | None) -> bool: ... + def within(self, other: Geometry | None) -> bool: ... + +def prep(ob: GeoT | PreparedGeometry[GeoT]) -> PreparedGeometry[GeoT]: ... diff --git a/stubs/shapely/shapely/set_operations.pyi b/stubs/shapely/shapely/set_operations.pyi new file mode 100644 index 000000000000..f1972a624d7f --- /dev/null +++ b/stubs/shapely/shapely/set_operations.pyi @@ -0,0 +1,137 @@ +from typing import overload +from typing_extensions import Unpack, deprecated + +from ._typing import GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, UFuncKwargs +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = [ + "coverage_union", + "coverage_union_all", + "difference", + "disjoint_subset_union", + "disjoint_subset_union_all", + "intersection", + "intersection_all", + "symmetric_difference", + "symmetric_difference_all", + "unary_union", + "union", + "union_all", +] + +@overload +def difference(a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def difference(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def difference(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def difference( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def difference( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def intersection(a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def intersection(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def intersection(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def intersection( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def intersection( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def intersection_all(geometries: OptGeoArrayLike, axis: None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def intersection_all(geometries: OptGeoArrayLikeSeq, axis: int, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | GeoArray: ... + +@overload +def symmetric_difference( + a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def symmetric_difference(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def symmetric_difference(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def symmetric_difference( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def symmetric_difference( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +@deprecated("symmetric_difference_all behaves incorrectly and will be removed in a future version.") +def symmetric_difference_all(geometries: OptGeoArrayLike, axis: None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +@deprecated("symmetric_difference_all behaves incorrectly and will be removed in a future version.") +def symmetric_difference_all( + geometries: OptGeoArrayLikeSeq, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... + +@overload +def union(a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def union(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def union(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def union( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def union( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def union_all( + geometries: OptGeoArrayLike, grid_size: float | None = None, axis: None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def union_all( + geometries: OptGeoArrayLikeSeq, grid_size: float | None = None, *, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... +@overload +def union_all( + geometries: OptGeoArrayLikeSeq, grid_size: float | None, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... + +unary_union = union_all + +@overload +def coverage_union( + a: OptGeoArrayLike, b: OptGeoArrayLike, *, axis: None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def coverage_union( + a: OptGeoArrayLike, b: OptGeoArrayLike, *, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... + +@overload +def coverage_union_all(geometries: OptGeoArrayLike, axis: None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def coverage_union_all(geometries: OptGeoArrayLikeSeq, axis: int, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | GeoArray: ... + +def disjoint_subset_union(a: OptGeoArrayLike, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | GeoArray: ... + +@overload +def disjoint_subset_union_all( + geometries: OptGeoArrayLike, *, axis: None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def disjoint_subset_union_all( + geometries: OptGeoArrayLikeSeq, *, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... diff --git a/stubs/shapely/shapely/speedups.pyi b/stubs/shapely/shapely/speedups.pyi new file mode 100644 index 000000000000..c2b505f068d9 --- /dev/null +++ b/stubs/shapely/shapely/speedups.pyi @@ -0,0 +1,12 @@ +from typing import Final +from typing_extensions import deprecated + +__all__ = ["available", "enable", "disable", "enabled"] + +available: Final = True +enabled: Final = True + +@deprecated("Function `enable` is deprecated and no longer has any effect. Speedups are always available.") +def enable() -> None: ... +@deprecated("Function `disable` is deprecated and no longer has any effect. Speedups are always available.") +def disable() -> None: ... diff --git a/stubs/shapely/shapely/strtree.pyi b/stubs/shapely/shapely/strtree.pyi new file mode 100644 index 000000000000..c9728d0f687c --- /dev/null +++ b/stubs/shapely/shapely/strtree.pyi @@ -0,0 +1,84 @@ +from typing import Any, Literal, SupportsIndex, TypeAlias, overload + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._typing import ArrayLike, GeoArray, GeoArrayLikeSeq, OptGeoArrayLike +from .lib import Geometry + +__all__ = ["STRtree"] + +_BinaryPredicate: TypeAlias = Literal[ + "intersects", "within", "contains", "overlaps", "crosses", "touches", "covers", "covered_by", "contains_properly" +] + +class BinaryPredicate(ParamEnum): + intersects = 1 + within = 2 + contains = 3 + overlaps = 4 + crosses = 5 + touches = 6 + covers = 7 + covered_by = 8 + contains_properly = 9 + +class STRtree: + def __init__(self, geoms: GeoArrayLikeSeq, node_capacity: SupportsIndex = 10) -> None: ... + def __len__(self) -> int: ... + @property + def geometries(self) -> GeoArray: ... + + @overload + def query( + self, geometry: OptGeoArrayLike, predicate: Literal["dwithin"], distance: ArrayLike[float] + ) -> NDArray[np.int64]: ... + @overload + def query( + self, geometry: OptGeoArrayLike, predicate: _BinaryPredicate | None = None, distance: object = None + ) -> NDArray[np.int64]: ... + + # nearest may return `None` if the tree is empty, use the "Any trick" + @overload + def nearest(self, geometry: Geometry) -> np.int64 | Any: ... + @overload + def nearest(self, geometry: GeoArrayLikeSeq) -> NDArray[np.int64] | Any: ... + + @overload # return_distance=False + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None = None, + return_distance: Literal[False] = False, + exclusive: bool = False, + all_matches: bool = True, + ) -> NDArray[np.int64]: ... + @overload # return_distance=True keyword + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None = None, + *, + return_distance: Literal[True], + exclusive: bool = False, + all_matches: bool = True, + ) -> tuple[NDArray[np.int64], NDArray[np.float64]]: ... + @overload # return_distance=True positional + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None, + return_distance: Literal[True], + exclusive: bool = False, + all_matches: bool = True, + ) -> tuple[NDArray[np.int64], NDArray[np.float64]]: ... + @overload # return_distance=bool fallback + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None = None, + return_distance: bool = False, + exclusive: bool = False, + all_matches: bool = True, + ) -> NDArray[np.int64] | tuple[NDArray[np.int64], NDArray[np.float64]]: ... diff --git a/stubs/shapely/shapely/testing.pyi b/stubs/shapely/shapely/testing.pyi new file mode 100644 index 000000000000..1acff3f0a071 --- /dev/null +++ b/stubs/shapely/shapely/testing.pyi @@ -0,0 +1,14 @@ +from ._typing import ArrayLike, OptGeoArrayLike + +__all__ = ["assert_geometries_equal"] + +def assert_geometries_equal( + x: OptGeoArrayLike, + y: OptGeoArrayLike, + tolerance: ArrayLike[float] = 1e-7, + equal_none: bool = True, + equal_nan: bool = True, + normalize: bool = False, + err_msg: str = "", + verbose: bool = True, +) -> None: ... diff --git a/stubs/shapely/shapely/validation.pyi b/stubs/shapely/shapely/validation.pyi new file mode 100644 index 000000000000..579199d6dd75 --- /dev/null +++ b/stubs/shapely/shapely/validation.pyi @@ -0,0 +1,7 @@ +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = ["explain_validity", "make_valid"] + +def explain_validity(ob: Geometry) -> str: ... +def make_valid(ob: Geometry) -> BaseGeometry: ... diff --git a/stubs/shapely/shapely/vectorized/__init__.pyi b/stubs/shapely/shapely/vectorized/__init__.pyi new file mode 100644 index 000000000000..c7b42e6c5e0a --- /dev/null +++ b/stubs/shapely/shapely/vectorized/__init__.pyi @@ -0,0 +1,47 @@ +from typing import overload +from typing_extensions import deprecated + +import numpy as np +from numpy.typing import NDArray + +from .._typing import ArrayLike, ArrayLikeSeq +from ..lib import Geometry +from ..prepared import PreparedGeometry + +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains(geometry: Geometry | PreparedGeometry[Geometry], x: float, y: float) -> np.bool_: ... +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLikeSeq[float], y: ArrayLike[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLikeSeq[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLike[float] +) -> np.bool_ | NDArray[np.bool_]: ... + +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches(geometry: Geometry | PreparedGeometry[Geometry], x: float, y: float) -> np.bool_: ... +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLikeSeq[float], y: ArrayLike[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLikeSeq[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLike[float] +) -> np.bool_ | NDArray[np.bool_]: ... diff --git a/stubs/shapely/shapely/wkb.pyi b/stubs/shapely/shapely/wkb.pyi new file mode 100644 index 000000000000..9a9adffe2884 --- /dev/null +++ b/stubs/shapely/shapely/wkb.pyi @@ -0,0 +1,18 @@ +from typing import Literal, overload + +from ._typing import SupportsRead, SupportsWrite +from .geometry.base import BaseGeometry +from .lib import Geometry + +def loads(data: str | bytes, hex: bool = False) -> BaseGeometry: ... +def load(fp: SupportsRead[str] | SupportsRead[bytes], hex: bool = False) -> BaseGeometry: ... + +@overload +def dumps(ob: Geometry, hex: Literal[False] = False, srid: int | None = None, **kw) -> bytes: ... +@overload +def dumps(ob: Geometry, hex: Literal[True], srid: int | None = None, **kw) -> str: ... + +@overload +def dump(ob: Geometry, fp: SupportsWrite[bytes], hex: Literal[False] = False, *, srid: int | None = None, **kw) -> None: ... +@overload +def dump(ob: Geometry, fp: SupportsWrite[str], hex: Literal[True], *, srid: int | None = None, **kw) -> None: ... diff --git a/stubs/shapely/shapely/wkt.pyi b/stubs/shapely/shapely/wkt.pyi new file mode 100644 index 000000000000..cb56d4f386b6 --- /dev/null +++ b/stubs/shapely/shapely/wkt.pyi @@ -0,0 +1,8 @@ +from ._typing import SupportsRead, SupportsWrite +from .geometry.base import BaseGeometry +from .lib import Geometry + +def loads(data: str) -> BaseGeometry: ... +def load(fp: SupportsRead[str]) -> BaseGeometry: ... +def dumps(ob: Geometry, trim: bool = False, rounding_precision: int = -1, **kw) -> str: ... +def dump(ob: Geometry, fp: SupportsWrite[str], *, trim: bool = False, rounding_precision: int = -1, **kw) -> None: ... diff --git a/stubs/simple-websocket/METADATA.toml b/stubs/simple-websocket/METADATA.toml new file mode 100644 index 000000000000..85219da88908 --- /dev/null +++ b/stubs/simple-websocket/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.1.*" +upstream-repository = "https://github.com/miguelgrinberg/simple-websocket" +dependencies = ["wsproto"] diff --git a/stubs/simple-websocket/simple_websocket/__init__.pyi b/stubs/simple-websocket/simple_websocket/__init__.pyi new file mode 100644 index 000000000000..d3da863383ca --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/__init__.pyi @@ -0,0 +1,3 @@ +from .aiows import AioClient as AioClient, AioServer as AioServer +from .errors import ConnectionClosed as ConnectionClosed, ConnectionError as ConnectionError +from .ws import Client as Client, Server as Server diff --git a/stubs/simple-websocket/simple_websocket/aiows.pyi b/stubs/simple-websocket/simple_websocket/aiows.pyi new file mode 100644 index 000000000000..066a243cb78e --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/aiows.pyi @@ -0,0 +1,130 @@ +import asyncio +import socket +from _typeshed import Incomplete, Unused +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Awaitable, Callable +from ssl import SSLContext +from typing import Any, Literal, TypedDict, type_check_only + +from wsproto import ConnectionType, WSConnection +from wsproto.events import Request +from wsproto.frame_protocol import CloseReason + +from .asgi import WebSocketASGI, _SocketDataBase, _SocketDataBytes, _SocketDataProtocol, _SocketDataStr + +class AioBase: + subprotocol: str | None + connection_type: ConnectionType + receive_bytes: int + ping_interval: float | None + max_message_size: int | None + pong_received: bool + input_buffer: list[bytes | str] + incoming_message: bytes | str | None + incoming_message_len: int + connected: bool + is_server: bool + close_reason: CloseReason + close_message: str + rsock: asyncio.StreamReader + wsock: asyncio.StreamWriter + event: asyncio.Event + ws: WSConnection | None + task: asyncio.Task[None] + def __init__( + self, + connection_type: ConnectionType | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ) -> None: ... + async def connect(self) -> None: ... + async def handshake(self) -> None: ... + # data can be antyhing. a special case is made for `bytes`, anything else is converted to `str`. + async def send(self, data: bytes | Any) -> None: ... + async def receive(self, timeout: float | None = None) -> bytes | str | None: ... + async def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +@type_check_only +class _AioServerRequest(TypedDict): + # this is `aiohttp.web.Request` + aiohttp: Incomplete + sock: None + headers: None + +class AioServer(AioBase): + request: _AioServerRequest + headers: dict[str, Any] + subprotocols: list[str] + is_server: Literal[True] + mode: str + connected: bool + def __init__( + self, + request: _AioServerRequest, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ) -> None: ... + @classmethod + async def accept( + cls, + # this is `aiohttp.web.Request` + aiohttp=None, + asgi: ( + tuple[ + WSGIEnvironment, + Callable[[], Awaitable[_SocketDataBytes | _SocketDataStr]], + Callable[[_SocketDataBase | _SocketDataProtocol | _SocketDataBytes | _SocketDataStr], Awaitable[None]], + ] + | None + ) = None, + sock: socket.socket | None = None, + headers: dict[str, Any] | None = None, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ) -> WebSocketASGI | AioServer: ... + async def handshake(self) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +class AioClient(AioBase): + url: str + ssl_context: SSLContext | None + is_secure: bool + host: str + port: int + path: str + subprotocols: list[str] + extra_headeers: list[tuple[bytes, bytes]] + subprotocol: str | None + connected: bool + def __init__( + self, + url: str, + subprotocols: list[str] | None = None, + headers: dict[str, Any] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + ) -> None: ... + # the source code itself has this override + @classmethod + async def connect( # type: ignore[override] + cls, + url: str, + subprotocols: list[str] | None = None, + headers: dict[str, Any] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + thread_class: Unused = None, + event_class: Unused = None, + ) -> AioClient: ... + async def handshake(self) -> None: ... + async def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... diff --git a/stubs/simple-websocket/simple_websocket/asgi.pyi b/stubs/simple-websocket/simple_websocket/asgi.pyi new file mode 100644 index 000000000000..92e802188c5e --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/asgi.pyi @@ -0,0 +1,44 @@ +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Awaitable, Callable +from typing import TypedDict, type_check_only + +@type_check_only +class _SocketDataBase(TypedDict): + type: str + +@type_check_only +class _SocketDataProtocol(_SocketDataBase): + subprotocol: str | None + +@type_check_only +class _SocketDataStr(_SocketDataBase): + text: str + +@type_check_only +class _SocketDataBytes(_SocketDataBase): + bytes: bytes + +class WebSocketASGI: + subprotocols: list[str] + subprotocol: str + connected: bool + # this is set in `close` to `False` + conncted: bool + def __init__( + self, + scope: WSGIEnvironment, + receive: Callable[[], Awaitable[_SocketDataBytes | _SocketDataStr]], + send: Callable[[_SocketDataBase | _SocketDataProtocol | _SocketDataBytes | _SocketDataStr], Awaitable[None]], + subprotocols: list[str] | None = None, + ) -> None: ... + @classmethod + async def accept( + cls, + scope: WSGIEnvironment, + receive: Callable[[], Awaitable[_SocketDataBytes | _SocketDataStr]], + send: Callable[[_SocketDataBase | _SocketDataProtocol | _SocketDataBytes | _SocketDataStr], Awaitable[None]], + subprotocols: list[str] | None = None, + ) -> WebSocketASGI: ... + async def receive(self) -> bytes | str: ... + async def send(self, data: bytes | str) -> None: ... + async def close(self) -> None: ... diff --git a/stubs/simple-websocket/simple_websocket/errors.pyi b/stubs/simple-websocket/simple_websocket/errors.pyi new file mode 100644 index 000000000000..88e25065121e --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/errors.pyi @@ -0,0 +1,12 @@ +from wsproto.frame_protocol import CloseReason + +class SimpleWebsocketError(RuntimeError): ... + +class ConnectionError(SimpleWebsocketError): + status_code: int | None + def __init__(self, status_code: int | None = None) -> None: ... + +class ConnectionClosed(SimpleWebsocketError): + reason: CloseReason + message: str | None + def __init__(self, reason: CloseReason = ..., message: str | None = None) -> None: ... diff --git a/stubs/simple-websocket/simple_websocket/ws.pyi b/stubs/simple-websocket/simple_websocket/ws.pyi new file mode 100644 index 000000000000..0366967d6d5a --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/ws.pyi @@ -0,0 +1,136 @@ +import socket +import threading +from _typeshed import FileDescriptorLike +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Callable +from selectors import SelectorKey +from ssl import SSLContext +from typing import Any, Protocol, type_check_only + +from wsproto import ConnectionType, WSConnection +from wsproto.events import Request +from wsproto.frame_protocol import CloseReason + +@type_check_only +class _ThreadClassProtocol(Protocol): + name: str + # this accepts any callable as the target, like `threading.Thread` + def __init__(self, target: Callable[..., Any]) -> None: ... + def start(self) -> None: ... + +@type_check_only +class _EventClassProtocol(Protocol): + def clear(self) -> None: ... + def set(self) -> None: ... + def wait(self, timeout: float | None = None) -> bool: ... + +@type_check_only +class _SelectorClassProtocol(Protocol): + # the signature of `register` here is the same as `selectors._BaseSelectorImpl` from the stdlib + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + # the signature of `select` here is the same as `selectors.DefaultSelector` from the stdlib + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + def close(self) -> None: ... + +class Base: + subprotocol: str | None + sock: socket.socket | None + receive_bytes: int + ping_interval: float | None + max_message_size: int | None + pong_received: bool + input_buffer: list[bytes | str] + incoming_message: bytes | str | None + incoming_message_len: int + connected: bool + is_server: bool + close_reason: CloseReason + close_message: str | None + selector_class: type[_SelectorClassProtocol] + event: _EventClassProtocol | threading.Event + ws: WSConnection + thread: _ThreadClassProtocol | threading.Thread + def __init__( + self, + sock: socket.socket | None = None, + connection_type: ConnectionType | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + selector_class: type[_SelectorClassProtocol] | None = None, + ) -> None: ... + def handshake(self) -> None: ... + # data can be antyhing. a special case is made for `bytes`, anything else is converted to `str`. + def send(self, data: bytes | Any) -> None: ... + def receive(self, timeout: float | None = None) -> bytes | str | None: ... + def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +class Server(Base): + environ: WSGIEnvironment + subprotocols: list[str] + mode: str + connected: bool + def __init__( + self, + environ: WSGIEnvironment, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + selector_class: type[_SelectorClassProtocol] | None = None, + ) -> None: ... + @classmethod + def accept( + cls, + environ: WSGIEnvironment, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + selector_class: type[_SelectorClassProtocol] | None = None, + ) -> Server: ... + def handshake(self) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +class Client(Base): + host: str + port: int + path: str + subprotocols: list[str] + extra_headeers: list[tuple[bytes, bytes]] + subprotocol: str | None + connected: bool + def __init__( + self, + url: str, + subprotocols: list[str] | None = None, + headers: dict[bytes, bytes] | list[tuple[bytes, bytes]] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + ) -> None: ... + @classmethod + def connect( + cls, + url: str, + subprotocols: list[str] | None = None, + headers: dict[bytes, bytes] | list[tuple[bytes, bytes]] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + ) -> Client: ... + def handshake(self) -> None: ... + def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... diff --git a/stubs/simplejson/@tests/stubtest_allowlist.txt b/stubs/simplejson/@tests/stubtest_allowlist.txt index e55375de8da9..ebb5d87976c4 100644 --- a/stubs/simplejson/@tests/stubtest_allowlist.txt +++ b/stubs/simplejson/@tests/stubtest_allowlist.txt @@ -1,18 +1,16 @@ -simplejson.JSONDecodeError.__init__ -simplejson.JSONDecoder.__init__ -simplejson.JSONDecoder.decode -simplejson.JSONDecoder.raw_decode -simplejson.JSONEncoder.__init__ -simplejson.JSONEncoder.iterencode -simplejson.JSONEncoderForHTML.iterencode -simplejson.decoder.JSONDecoder.__init__ -simplejson.decoder.JSONDecoder.decode -simplejson.decoder.JSONDecoder.raw_decode -simplejson.dump -simplejson.dumps -simplejson.encoder.JSONEncoder.__init__ -simplejson.encoder.JSONEncoder.iterencode -simplejson.encoder.JSONEncoderForHTML.iterencode -simplejson.load -simplejson.loads +# Speedups (C vs Python inconsistency): +simplejson.scanner.make_scanner simplejson.scanner.JSONDecodeError.__init__ +simplejson.encoder.c_make_encoder +simplejson.encoder.c_encode_basestring +simplejson.encoder.py_encode_basestring +simplejson.encoder.c_encode_basestring_ascii +simplejson.encoder.py_encode_basestring_ascii + +# Tests are not included: +simplejson.tests.* + +# Internal and compat tools: +simplejson.compat +simplejson.ordered_dict +simplejson.tool diff --git a/stubs/simplejson/@tests/test_cases/check_simplejson.py b/stubs/simplejson/@tests/test_cases/check_simplejson.py new file mode 100644 index 000000000000..c62fd73dad6e --- /dev/null +++ b/stubs/simplejson/@tests/test_cases/check_simplejson.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from simplejson import JSONEncoder, dumps + + +class CustomEncoder(JSONEncoder): # eventhough it does not have `extra_kw` arg. + ... + + +# We are only testing `dumps` here, because they are all the same: +dumps([], extra_kw=True) # type: ignore + +# Ok: +assert_type(dumps([], cls=CustomEncoder, extra_kw=True), str) diff --git a/stubs/simplejson/METADATA.toml b/stubs/simplejson/METADATA.toml index e8d5c242ddd3..4813872ae3e1 100644 --- a/stubs/simplejson/METADATA.toml +++ b/stubs/simplejson/METADATA.toml @@ -1,2 +1,2 @@ -version = "3.17.*" -python2 = true +version = "4.2.*" +upstream-repository = "https://github.com/simplejson/simplejson" diff --git a/stubs/simplejson/simplejson/__init__.pyi b/stubs/simplejson/simplejson/__init__.pyi index 798a77062823..b89f04f64fdf 100644 --- a/stubs/simplejson/simplejson/__init__.pyi +++ b/stubs/simplejson/simplejson/__init__.pyi @@ -1,13 +1,189 @@ -from typing import IO, Any, Text, Union +from _typeshed import SupportsRichComparison +from collections import OrderedDict +from collections.abc import Callable +from typing import IO, Any, TypeAlias, TypeVar, overload from simplejson.decoder import JSONDecoder as JSONDecoder from simplejson.encoder import JSONEncoder as JSONEncoder, JSONEncoderForHTML as JSONEncoderForHTML from simplejson.raw_json import RawJSON as RawJSON from simplejson.scanner import JSONDecodeError as JSONDecodeError -_LoadsString = Union[Text, bytes, bytearray] +_LoadsString: TypeAlias = str | bytes | bytearray +_T = TypeVar("_T") -def dumps(obj: Any, *args: Any, **kwds: Any) -> str: ... -def dump(obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ... -def loads(s: _LoadsString, **kwds: Any) -> Any: ... -def load(fp: IO[str], **kwds: Any) -> Any: ... +@overload +def dumps( + obj: Any, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + *, + cls: type[JSONEncoder], + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, + **kw: Any, +) -> str: ... +@overload +def dumps( + obj: Any, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + cls: type[JSONEncoder] | None = None, + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, +) -> str: ... + +@overload +def dump( + obj: Any, + fp: IO[str], + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + *, + cls: type[JSONEncoder], + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, + **kw: Any, +) -> None: ... +@overload +def dump( + obj: Any, + fp: IO[str], + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + cls: type[JSONEncoder] | None = None, + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, +) -> None: ... + +@overload +def loads( + s: _LoadsString, + encoding: str | None = None, + *, + cls: type[JSONDecoder], + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value + **kw: Any, +) -> Any: ... +@overload +def loads( + s: _LoadsString, + encoding: str | None = None, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value +) -> Any: ... + +@overload +def load( + fp: IO[str], + encoding: str | None = None, + *, + cls: type[JSONDecoder], + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value + **kw: Any, +) -> Any: ... +@overload +def load( + fp: IO[str], + encoding: str | None = None, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value +) -> Any: ... + +def simple_first(kv: tuple[_T, object]) -> tuple[bool, _T]: ... + +__all__ = [ + "dump", + "dumps", + "load", + "loads", + "JSONDecoder", + "JSONDecodeError", + "JSONEncoder", + "OrderedDict", + "simple_first", + "RawJSON", +] diff --git a/stubs/simplejson/simplejson/decoder.pyi b/stubs/simplejson/simplejson/decoder.pyi index 0d726afc5143..3fc18bc176e5 100644 --- a/stubs/simplejson/simplejson/decoder.pyi +++ b/stubs/simplejson/simplejson/decoder.pyi @@ -1,6 +1,40 @@ -from typing import Any, Match +from _typeshed import Incomplete +from collections.abc import Callable +from re import Match +from typing import Any, Literal -class JSONDecoder(object): - def __init__(self, **kwargs: Any) -> None: ... - def decode(self, s: str, _w: Match[str], _PY3: bool): ... - def raw_decode(self, s: str, idx: int, _w: Match[str], _PY3: bool): ... +class JSONDecoder: + encoding: str + object_hook: Callable[[dict[Any, Any]], Any] | None + # transforms a list of (key, json_value) pairs to an arbitrary value + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None + parse_float: Callable[[str], Any] | None + parse_int: Callable[[str], Any] | None + parse_constant: Callable[[str], Any] | None + strict: bool + array_hook: Callable[[list[Any]], Any] | None # transforms a JSON value to an arbitrary value + # They have many parameters, it might be better to use Protocol: + parse_object: Callable[..., tuple[Incomplete, int]] + parse_array: Callable[..., tuple[Incomplete, int]] + parse_string: Callable[..., tuple[Incomplete, int]] + memo: dict[Any, Any] + scan_once: Callable[[str, int], tuple[bool, int]] + + def __init__( + self, + encoding: str | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value + ) -> None: ... + def decode(self, s: str, _w: Callable[[str, int], Match[str]] = ..., _PY3: Literal[True] = True) -> Any: ... + def raw_decode( + self, s: str, idx: int = 0, _w: Callable[[str, int], Match[str]] = ..., _PY3: Literal[True] = True + ) -> tuple[Any, int]: ... + +__all__ = ["JSONDecoder"] diff --git a/stubs/simplejson/simplejson/encoder.pyi b/stubs/simplejson/simplejson/encoder.pyi index 9a3c5e4d9aa8..9f82016fe917 100644 --- a/stubs/simplejson/simplejson/encoder.pyi +++ b/stubs/simplejson/simplejson/encoder.pyi @@ -1,9 +1,61 @@ +import re +from _typeshed import SupportsRichComparison +from collections.abc import Callable, Iterator from typing import Any +from typing_extensions import Never -class JSONEncoder(object): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def encode(self, o: Any): ... - def default(self, o: Any): ... - def iterencode(self, o: Any, _one_shot: bool): ... +ESCAPE: re.Pattern[str] +ESCAPE_ASCII: re.Pattern[str] +HAS_UTF8: re.Pattern[str] +ESCAPE_DCT: dict[str, str] +FLOAT_REPR: Callable[[object], str] + +class JSONEncoder: + item_separator: str + key_separator: str + skipkeys: bool + ensure_ascii: bool + check_circular: bool + allow_nan: bool + sort_keys: bool + indent: str + encoding: str + use_decimal: bool + namedtuple_as_object: bool + tuple_as_array: bool + bigint_as_string: bool + item_sort_key: Callable[[Any], SupportsRichComparison] | None + for_json: bool + ignore_nan: bool + int_as_string_bitcount: int | None + iterable_as_array: bool + + def __init__( + self, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + sort_keys: bool = False, + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, + ) -> None: ... + def encode(self, o: Any) -> str: ... + def default(self, o: Any) -> Never: ... + def iterencode(self, o: Any) -> Iterator[str]: ... class JSONEncoderForHTML(JSONEncoder): ... + +def encode_basestring(s: str | bytes, /) -> str: ... +def encode_basestring_ascii(s: str | bytes, /) -> str: ... diff --git a/stubs/simplejson/simplejson/errors.pyi b/stubs/simplejson/simplejson/errors.pyi index 10cff3f28203..b4b6539c652e 100644 --- a/stubs/simplejson/simplejson/errors.pyi +++ b/stubs/simplejson/simplejson/errors.pyi @@ -1,7 +1,7 @@ __all__ = ["JSONDecodeError"] def linecol(doc: str, pos: int) -> tuple[int, int]: ... -def errmsg(msg: str, doc: str, pos: int, end: int | None = ...) -> str: ... +def errmsg(msg: str, doc: str, pos: int, end: int | None = None) -> str: ... class JSONDecodeError(ValueError): msg: str @@ -12,5 +12,5 @@ class JSONDecodeError(ValueError): colno: int endlineno: int | None endcolno: int | None - def __init__(self, msg: str, doc: str, pos: int, end: int | None = ...) -> None: ... + def __init__(self, msg: str, doc: str, pos: int, end: int | None = None) -> None: ... def __reduce__(self) -> tuple[JSONDecodeError, tuple[str, str, int, int | None]]: ... diff --git a/stubs/simplejson/simplejson/raw_json.pyi b/stubs/simplejson/simplejson/raw_json.pyi index 25976ea00345..bacd7550aa82 100644 --- a/stubs/simplejson/simplejson/raw_json.pyi +++ b/stubs/simplejson/simplejson/raw_json.pyi @@ -1,3 +1,3 @@ -class RawJSON(object): +class RawJSON: encoded_json: str def __init__(self, encoded_json: str) -> None: ... diff --git a/stubs/simplejson/simplejson/scanner.pyi b/stubs/simplejson/simplejson/scanner.pyi index 42b828a6905d..2e7f9fe58eda 100644 --- a/stubs/simplejson/simplejson/scanner.pyi +++ b/stubs/simplejson/simplejson/scanner.pyi @@ -1,9 +1,17 @@ +from collections.abc import Callable + +from simplejson.decoder import JSONDecoder + class JSONDecodeError(ValueError): - msg: str = ... - doc: str = ... - pos: int = ... - end: int | None = ... - lineno: int = ... - colno: int = ... - endlineno: int | None = ... - endcolno: int | None = ... + msg: str + doc: str + pos: int + end: int | None + lineno: int + colno: int + endlineno: int | None + endcolno: int | None + +def make_scanner(context: JSONDecoder) -> Callable[[str, int], tuple[bool, int]]: ... + +__all__ = ["make_scanner", "JSONDecodeError"] diff --git a/stubs/singledispatch/METADATA.toml b/stubs/singledispatch/METADATA.toml index 839f7d3a9b8e..9bdcc7abbe8d 100644 --- a/stubs/singledispatch/METADATA.toml +++ b/stubs/singledispatch/METADATA.toml @@ -1,2 +1,2 @@ -version = "3.7.*" -python2 = true +version = "4.1.*" +upstream-repository = "https://github.com/jaraco/singledispatch" diff --git a/stubs/singledispatch/singledispatch.pyi b/stubs/singledispatch/singledispatch.pyi index f264047ac201..62e59c9fe30f 100644 --- a/stubs/singledispatch/singledispatch.pyi +++ b/stubs/singledispatch/singledispatch.pyi @@ -1,15 +1,38 @@ -from typing import Any, Callable, Generic, Mapping, TypeVar, overload +from collections.abc import Callable, Mapping +from typing import Any, Generic, TypeVar, overload, type_check_only _T = TypeVar("_T") +_S = TypeVar("_S") +@type_check_only class _SingleDispatchCallable(Generic[_T]): registry: Mapping[Any, Callable[..., _T]] def dispatch(self, cls: Any) -> Callable[..., _T]: ... + @overload def register(self, cls: Any) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... @overload def register(self, cls: Any, func: Callable[..., _T]) -> Callable[..., _T]: ... + def _clear_cache(self) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... + +class singledispatchmethod(Generic[_T]): + dispatcher: _SingleDispatchCallable[_T] + func: Callable[..., _T] + def __init__(self, func: Callable[..., _T]) -> None: ... + @property + def __isabstractmethod__(self) -> bool: ... + + @overload + def register(self, cls: type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = ...) -> Callable[..., _T]: ... + @overload + def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... + + def __get__(self, obj: _S, cls: type[_S] | None = ...) -> Callable[..., _T]: ... + +__all__ = ["singledispatch", "singledispatchmethod"] diff --git a/stubs/six/@python2/six/__init__.pyi b/stubs/six/@python2/six/__init__.pyi deleted file mode 100644 index 5c448102bd4a..000000000000 --- a/stubs/six/@python2/six/__init__.pyi +++ /dev/null @@ -1,121 +0,0 @@ -from __future__ import print_function - -import types -import typing -import unittest -from __builtin__ import unichr as unichr -from functools import wraps as wraps -from StringIO import StringIO as StringIO -from typing import ( - Any, - AnyStr, - Callable, - ItemsView, - Iterable, - KeysView, - Mapping, - NoReturn, - Pattern, - Text, - Tuple, - Type, - TypeVar, - ValuesView, - overload, -) -from typing_extensions import Literal - -from . import moves - -BytesIO = StringIO - -_T = TypeVar("_T") -_K = TypeVar("_K") -_V = TypeVar("_V") - -__author__: str -__version__: str - -PY2: Literal[True] -PY3: Literal[False] -PY34: Literal[False] - -string_types: tuple[Type[str], Type[unicode]] -integer_types: tuple[Type[int], Type[long]] -class_types: tuple[Type[Type[Any]], Type[types.ClassType]] -text_type: Type[unicode] -binary_type: Type[str] - -MAXSIZE: int - -def advance_iterator(it: typing.Iterator[_T]) -> _T: ... - -next = advance_iterator - -def callable(obj: object) -> bool: ... -def get_unbound_function(unbound: types.MethodType) -> types.FunctionType: ... -def create_bound_method(func: types.FunctionType, obj: object) -> types.MethodType: ... -def create_unbound_method(func: types.FunctionType, cls: type | types.ClassType) -> types.MethodType: ... - -class Iterator: - def next(self) -> Any: ... - -def get_method_function(meth: types.MethodType) -> types.FunctionType: ... -def get_method_self(meth: types.MethodType) -> object | None: ... -def get_function_closure(fun: types.FunctionType) -> Tuple[types._Cell, ...] | None: ... -def get_function_code(fun: types.FunctionType) -> types.CodeType: ... -def get_function_defaults(fun: types.FunctionType) -> Tuple[Any, ...] | None: ... -def get_function_globals(fun: types.FunctionType) -> dict[str, Any]: ... -def iterkeys(d: Mapping[_K, _V]) -> typing.Iterator[_K]: ... -def itervalues(d: Mapping[_K, _V]) -> typing.Iterator[_V]: ... -def iteritems(d: Mapping[_K, _V]) -> typing.Iterator[tuple[_K, _V]]: ... - -# def iterlists - -def viewkeys(d: Mapping[_K, _V]) -> KeysView[_K]: ... -def viewvalues(d: Mapping[_K, _V]) -> ValuesView[_V]: ... -def viewitems(d: Mapping[_K, _V]) -> ItemsView[_K, _V]: ... -def b(s: str) -> str: ... -def u(s: str) -> unicode: ... - -int2byte = chr - -def byte2int(bs: str) -> int: ... -def indexbytes(buf: str, i: int) -> int: ... -def iterbytes(buf: str) -> typing.Iterator[int]: ... -def assertCountEqual(self: unittest.TestCase, first: Iterable[_T], second: Iterable[_T], msg: str = ...) -> None: ... -@overload -def assertRaisesRegex(self: unittest.TestCase, msg: str = ...) -> Any: ... -@overload -def assertRaisesRegex(self: unittest.TestCase, callable_obj: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: ... -def assertRegex(self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: str = ...) -> None: ... -def reraise(tp: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None = ...) -> NoReturn: ... -def exec_(_code_: unicode | types.CodeType, _globs_: dict[str, Any] = ..., _locs_: dict[str, Any] = ...): ... -def raise_from(value: BaseException | Type[BaseException], from_value: BaseException | None) -> NoReturn: ... - -print_ = print - -def with_metaclass(meta: type, *bases: type) -> type: ... -def add_metaclass(metaclass: type) -> Callable[[_T], _T]: ... -def ensure_binary(s: bytes | Text, encoding: str = ..., errors: str = ...) -> bytes: ... -def ensure_str(s: bytes | Text, encoding: str = ..., errors: str = ...) -> str: ... -def ensure_text(s: bytes | Text, encoding: str = ..., errors: str = ...) -> Text: ... -def python_2_unicode_compatible(klass: _T) -> _T: ... - -class _LazyDescr(object): - name: str - def __init__(self, name: str) -> None: ... - def __get__(self, obj: object | None, type: Type[Any] | None = ...) -> Any: ... - -class MovedModule(_LazyDescr): - mod: str - def __init__(self, name: str, old: str, new: str | None = ...) -> None: ... - def __getattr__(self, attr: str) -> Any: ... - -class MovedAttribute(_LazyDescr): - mod: str - attr: str - def __init__(self, name: str, old_mod: str, new_mod: str, old_attr: str | None = ..., new_attr: str | None = ...) -> None: ... - -def add_move(move: MovedModule | MovedAttribute) -> None: ... -def remove_move(name: str) -> None: ... diff --git a/stubs/six/@python2/six/moves/BaseHTTPServer.pyi b/stubs/six/@python2/six/moves/BaseHTTPServer.pyi deleted file mode 100644 index 16f7a9dc12fa..000000000000 --- a/stubs/six/@python2/six/moves/BaseHTTPServer.pyi +++ /dev/null @@ -1 +0,0 @@ -from BaseHTTPServer import * diff --git a/stubs/six/@python2/six/moves/CGIHTTPServer.pyi b/stubs/six/@python2/six/moves/CGIHTTPServer.pyi deleted file mode 100644 index b39390c67abf..000000000000 --- a/stubs/six/@python2/six/moves/CGIHTTPServer.pyi +++ /dev/null @@ -1 +0,0 @@ -from CGIHTTPServer import * diff --git a/stubs/six/@python2/six/moves/SimpleHTTPServer.pyi b/stubs/six/@python2/six/moves/SimpleHTTPServer.pyi deleted file mode 100644 index 97cfe7717d33..000000000000 --- a/stubs/six/@python2/six/moves/SimpleHTTPServer.pyi +++ /dev/null @@ -1 +0,0 @@ -from SimpleHTTPServer import * diff --git a/stubs/six/@python2/six/moves/__init__.pyi b/stubs/six/@python2/six/moves/__init__.pyi deleted file mode 100644 index 5f34153f2b4c..000000000000 --- a/stubs/six/@python2/six/moves/__init__.pyi +++ /dev/null @@ -1,78 +0,0 @@ -# Stubs for six.moves -# -# Note: Commented out items means they weren't implemented at the time. -# Uncomment them when the modules have been added to the typeshed. -import __builtin__ -import itertools -import os -import pipes -from __builtin__ import intern as intern, reduce as reduce, xrange as xrange -from cStringIO import StringIO as _cStringIO -from StringIO import StringIO as StringIO -from UserDict import UserDict as UserDict -from UserList import UserList as UserList -from UserString import UserString as UserString - -# import Tkinter as tkinter -# import Dialog as tkinter_dialog -# import FileDialog as tkinter_filedialog -# import ScrolledText as tkinter_scrolledtext -# import SimpleDialog as tkinter_simpledialog -# import Tix as tkinter_tix -# import ttk as tkinter_ttk -# import Tkconstants as tkinter_constants -# import Tkdnd as tkinter_dnd -# import tkColorChooser as tkinter_colorchooser -# import tkCommonDialog as tkinter_commondialog -# import tkFileDialog as tkinter_tkfiledialog -# import tkFont as tkinter_font -# import tkMessageBox as tkinter_messagebox -# import tkSimpleDialog as tkinter_tksimpledialog -# import email.MIMEBase as email_mime_base -# import email.MIMEMultipart as email_mime_multipart -# import email.MIMENonMultipart as email_mime_nonmultipart -# import copy_reg as copyreg -# import gdbm as dbm_gnu -from . import ( - BaseHTTPServer, - CGIHTTPServer, - SimpleHTTPServer, - _dummy_thread, - _thread, - configparser, - cPickle, - email_mime_text, - html_entities, - html_parser, - http_client, - http_cookiejar, - http_cookies, - queue, - reprlib, - socketserver, - urllib, - urllib_error, - urllib_parse, - urllib_robotparser, - xmlrpc_client, -) - -# import SimpleXMLRPCServer as xmlrpc_server - -builtins = __builtin__ -input = __builtin__.raw_input -reload_module = __builtin__.reload -range = __builtin__.xrange - -cStringIO = _cStringIO - -filter = itertools.ifilter -filterfalse = itertools.ifilterfalse -map = itertools.imap -zip = itertools.izip -zip_longest = itertools.izip_longest - -getcwdb = os.getcwd -getcwd = os.getcwdu - -shlex_quote = pipes.quote diff --git a/stubs/six/@python2/six/moves/_dummy_thread.pyi b/stubs/six/@python2/six/moves/_dummy_thread.pyi deleted file mode 100644 index 3efe922c9257..000000000000 --- a/stubs/six/@python2/six/moves/_dummy_thread.pyi +++ /dev/null @@ -1 +0,0 @@ -from dummy_thread import * diff --git a/stubs/six/@python2/six/moves/_thread.pyi b/stubs/six/@python2/six/moves/_thread.pyi deleted file mode 100644 index b27f4c70d6e7..000000000000 --- a/stubs/six/@python2/six/moves/_thread.pyi +++ /dev/null @@ -1 +0,0 @@ -from thread import * diff --git a/stubs/six/@python2/six/moves/cPickle.pyi b/stubs/six/@python2/six/moves/cPickle.pyi deleted file mode 100644 index ca829a7509c9..000000000000 --- a/stubs/six/@python2/six/moves/cPickle.pyi +++ /dev/null @@ -1 +0,0 @@ -from cPickle import * diff --git a/stubs/six/@python2/six/moves/collections_abc.pyi b/stubs/six/@python2/six/moves/collections_abc.pyi deleted file mode 100644 index 94005615cbed..000000000000 --- a/stubs/six/@python2/six/moves/collections_abc.pyi +++ /dev/null @@ -1 +0,0 @@ -from collections import * diff --git a/stubs/six/@python2/six/moves/configparser.pyi b/stubs/six/@python2/six/moves/configparser.pyi deleted file mode 100644 index b2da53afb83e..000000000000 --- a/stubs/six/@python2/six/moves/configparser.pyi +++ /dev/null @@ -1 +0,0 @@ -from ConfigParser import * diff --git a/stubs/six/@python2/six/moves/email_mime_base.pyi b/stubs/six/@python2/six/moves/email_mime_base.pyi deleted file mode 100644 index 4df155c939d5..000000000000 --- a/stubs/six/@python2/six/moves/email_mime_base.pyi +++ /dev/null @@ -1 +0,0 @@ -from email.mime.base import * diff --git a/stubs/six/@python2/six/moves/email_mime_multipart.pyi b/stubs/six/@python2/six/moves/email_mime_multipart.pyi deleted file mode 100644 index 4f312412bbc0..000000000000 --- a/stubs/six/@python2/six/moves/email_mime_multipart.pyi +++ /dev/null @@ -1 +0,0 @@ -from email.mime.multipart import * diff --git a/stubs/six/@python2/six/moves/email_mime_nonmultipart.pyi b/stubs/six/@python2/six/moves/email_mime_nonmultipart.pyi deleted file mode 100644 index c15c8c0440b5..000000000000 --- a/stubs/six/@python2/six/moves/email_mime_nonmultipart.pyi +++ /dev/null @@ -1 +0,0 @@ -from email.mime.nonmultipart import * diff --git a/stubs/six/@python2/six/moves/email_mime_text.pyi b/stubs/six/@python2/six/moves/email_mime_text.pyi deleted file mode 100644 index 214bf1e24267..000000000000 --- a/stubs/six/@python2/six/moves/email_mime_text.pyi +++ /dev/null @@ -1 +0,0 @@ -from email.MIMEText import * diff --git a/stubs/six/@python2/six/moves/html_entities.pyi b/stubs/six/@python2/six/moves/html_entities.pyi deleted file mode 100644 index 9e15d010deee..000000000000 --- a/stubs/six/@python2/six/moves/html_entities.pyi +++ /dev/null @@ -1 +0,0 @@ -from htmlentitydefs import * diff --git a/stubs/six/@python2/six/moves/html_parser.pyi b/stubs/six/@python2/six/moves/html_parser.pyi deleted file mode 100644 index 984cee67f405..000000000000 --- a/stubs/six/@python2/six/moves/html_parser.pyi +++ /dev/null @@ -1 +0,0 @@ -from HTMLParser import * diff --git a/stubs/six/@python2/six/moves/http_client.pyi b/stubs/six/@python2/six/moves/http_client.pyi deleted file mode 100644 index 24ef0b4cb4b6..000000000000 --- a/stubs/six/@python2/six/moves/http_client.pyi +++ /dev/null @@ -1 +0,0 @@ -from httplib import * diff --git a/stubs/six/@python2/six/moves/http_cookiejar.pyi b/stubs/six/@python2/six/moves/http_cookiejar.pyi deleted file mode 100644 index 1357ad3b0559..000000000000 --- a/stubs/six/@python2/six/moves/http_cookiejar.pyi +++ /dev/null @@ -1 +0,0 @@ -from cookielib import * diff --git a/stubs/six/@python2/six/moves/http_cookies.pyi b/stubs/six/@python2/six/moves/http_cookies.pyi deleted file mode 100644 index 5115c0dff173..000000000000 --- a/stubs/six/@python2/six/moves/http_cookies.pyi +++ /dev/null @@ -1 +0,0 @@ -from Cookie import * diff --git a/stubs/six/@python2/six/moves/queue.pyi b/stubs/six/@python2/six/moves/queue.pyi deleted file mode 100644 index 7ce3ccb32802..000000000000 --- a/stubs/six/@python2/six/moves/queue.pyi +++ /dev/null @@ -1 +0,0 @@ -from Queue import * diff --git a/stubs/six/@python2/six/moves/reprlib.pyi b/stubs/six/@python2/six/moves/reprlib.pyi deleted file mode 100644 index 40ad103841e9..000000000000 --- a/stubs/six/@python2/six/moves/reprlib.pyi +++ /dev/null @@ -1 +0,0 @@ -from repr import * diff --git a/stubs/six/@python2/six/moves/socketserver.pyi b/stubs/six/@python2/six/moves/socketserver.pyi deleted file mode 100644 index c80a6e7b57cb..000000000000 --- a/stubs/six/@python2/six/moves/socketserver.pyi +++ /dev/null @@ -1 +0,0 @@ -from SocketServer import * diff --git a/stubs/six/@python2/six/moves/urllib/__init__.pyi b/stubs/six/@python2/six/moves/urllib/__init__.pyi deleted file mode 100644 index d08209c51cc1..000000000000 --- a/stubs/six/@python2/six/moves/urllib/__init__.pyi +++ /dev/null @@ -1,5 +0,0 @@ -import six.moves.urllib.error as error -import six.moves.urllib.parse as parse -import six.moves.urllib.request as request -import six.moves.urllib.response as response -import six.moves.urllib.robotparser as robotparser diff --git a/stubs/six/@python2/six/moves/urllib/error.pyi b/stubs/six/@python2/six/moves/urllib/error.pyi deleted file mode 100644 index 0c6c1c3bd79c..000000000000 --- a/stubs/six/@python2/six/moves/urllib/error.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from urllib import ContentTooShortError as ContentTooShortError -from urllib2 import HTTPError as HTTPError, URLError as URLError diff --git a/stubs/six/@python2/six/moves/urllib/parse.pyi b/stubs/six/@python2/six/moves/urllib/parse.pyi deleted file mode 100644 index 569b0732429d..000000000000 --- a/stubs/six/@python2/six/moves/urllib/parse.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from urllib import ( - quote as quote, - quote_plus as quote_plus, - splitquery as splitquery, - splittag as splittag, - splituser as splituser, - unquote as unquote, - unquote_plus as unquote_plus, - urlencode as urlencode, -) -from urlparse import ( - ParseResult as ParseResult, - SplitResult as SplitResult, - parse_qs as parse_qs, - parse_qsl as parse_qsl, - urldefrag as urldefrag, - urljoin as urljoin, - urlparse as urlparse, - urlsplit as urlsplit, - urlunparse as urlunparse, - urlunsplit as urlunsplit, - uses_fragment as uses_fragment, - uses_netloc as uses_netloc, - uses_params as uses_params, - uses_query as uses_query, - uses_relative as uses_relative, -) - -unquote_to_bytes = unquote diff --git a/stubs/six/@python2/six/moves/urllib/request.pyi b/stubs/six/@python2/six/moves/urllib/request.pyi deleted file mode 100644 index 549bd407c722..000000000000 --- a/stubs/six/@python2/six/moves/urllib/request.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from urllib import ( - FancyURLopener as FancyURLopener, - URLopener as URLopener, - getproxies as getproxies, - pathname2url as pathname2url, - proxy_bypass as proxy_bypass, - url2pathname as url2pathname, - urlcleanup as urlcleanup, - urlretrieve as urlretrieve, -) -from urllib2 import ( - AbstractBasicAuthHandler as AbstractBasicAuthHandler, - AbstractDigestAuthHandler as AbstractDigestAuthHandler, - BaseHandler as BaseHandler, - CacheFTPHandler as CacheFTPHandler, - FileHandler as FileHandler, - FTPHandler as FTPHandler, - HTTPBasicAuthHandler as HTTPBasicAuthHandler, - HTTPCookieProcessor as HTTPCookieProcessor, - HTTPDefaultErrorHandler as HTTPDefaultErrorHandler, - HTTPDigestAuthHandler as HTTPDigestAuthHandler, - HTTPErrorProcessor as HTTPErrorProcessor, - HTTPHandler as HTTPHandler, - HTTPPasswordMgr as HTTPPasswordMgr, - HTTPPasswordMgrWithDefaultRealm as HTTPPasswordMgrWithDefaultRealm, - HTTPRedirectHandler as HTTPRedirectHandler, - HTTPSHandler as HTTPSHandler, - OpenerDirector as OpenerDirector, - ProxyBasicAuthHandler as ProxyBasicAuthHandler, - ProxyDigestAuthHandler as ProxyDigestAuthHandler, - ProxyHandler as ProxyHandler, - Request as Request, - UnknownHandler as UnknownHandler, - build_opener as build_opener, - install_opener as install_opener, - parse_http_list as parse_http_list, - parse_keqv_list as parse_keqv_list, - urlopen as urlopen, -) diff --git a/stubs/six/@python2/six/moves/urllib/response.pyi b/stubs/six/@python2/six/moves/urllib/response.pyi deleted file mode 100644 index b560da8a5852..000000000000 --- a/stubs/six/@python2/six/moves/urllib/response.pyi +++ /dev/null @@ -1 +0,0 @@ -from urllib import addbase as addbase, addclosehook as addclosehook, addinfo as addinfo, addinfourl as addinfourl diff --git a/stubs/six/@python2/six/moves/urllib/robotparser.pyi b/stubs/six/@python2/six/moves/urllib/robotparser.pyi deleted file mode 100644 index 11eef5040766..000000000000 --- a/stubs/six/@python2/six/moves/urllib/robotparser.pyi +++ /dev/null @@ -1 +0,0 @@ -from robotparser import RobotFileParser as RobotFileParser diff --git a/stubs/six/@python2/six/moves/urllib_error.pyi b/stubs/six/@python2/six/moves/urllib_error.pyi deleted file mode 100644 index b5608125d2ad..000000000000 --- a/stubs/six/@python2/six/moves/urllib_error.pyi +++ /dev/null @@ -1 +0,0 @@ -from .urllib.error import * diff --git a/stubs/six/@python2/six/moves/urllib_parse.pyi b/stubs/six/@python2/six/moves/urllib_parse.pyi deleted file mode 100644 index bdb4d1c03e68..000000000000 --- a/stubs/six/@python2/six/moves/urllib_parse.pyi +++ /dev/null @@ -1 +0,0 @@ -from .urllib.parse import * diff --git a/stubs/six/@python2/six/moves/urllib_request.pyi b/stubs/six/@python2/six/moves/urllib_request.pyi deleted file mode 100644 index dc03dcecc118..000000000000 --- a/stubs/six/@python2/six/moves/urllib_request.pyi +++ /dev/null @@ -1 +0,0 @@ -from .urllib.request import * diff --git a/stubs/six/@python2/six/moves/urllib_response.pyi b/stubs/six/@python2/six/moves/urllib_response.pyi deleted file mode 100644 index bbee52256e31..000000000000 --- a/stubs/six/@python2/six/moves/urllib_response.pyi +++ /dev/null @@ -1 +0,0 @@ -from .urllib.response import * diff --git a/stubs/six/@python2/six/moves/urllib_robotparser.pyi b/stubs/six/@python2/six/moves/urllib_robotparser.pyi deleted file mode 100644 index ddb63b781523..000000000000 --- a/stubs/six/@python2/six/moves/urllib_robotparser.pyi +++ /dev/null @@ -1 +0,0 @@ -from robotparser import * diff --git a/stubs/six/@python2/six/moves/xmlrpc_client.pyi b/stubs/six/@python2/six/moves/xmlrpc_client.pyi deleted file mode 100644 index 1b3bd7468cfa..000000000000 --- a/stubs/six/@python2/six/moves/xmlrpc_client.pyi +++ /dev/null @@ -1 +0,0 @@ -from xmlrpclib import * diff --git a/stubs/six/@tests/stubtest_allowlist.txt b/stubs/six/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d1870c38df1e --- /dev/null +++ b/stubs/six/@tests/stubtest_allowlist.txt @@ -0,0 +1,29 @@ +# Problems inherited from the standard library +six.create_bound_method.__closure__ +six.create_bound_method.__code__ +six.create_bound_method.__defaults__ +six.moves.* + +# Implemented using "operator" functions in the implementation +six.get_function_closure +six.get_function_code +six.get_function_defaults +six.get_function_globals +six.get_method_function +six.get_method_self +six.viewitems +six.viewkeys +six.viewvalues +# Should be `byte2int: operator.itemgetter[int]`. But `itemgetter.__call__` returns `Any` +six.byte2int + +# Utils +six.Module_six_moves_urllib +six.Module_six_moves_urllib_error +six.Module_six_moves_urllib_parse +six.Module_six_moves_urllib_request +six.Module_six_moves_urllib_response +six.Module_six_moves_urllib_robotparser + +# Belongs to `django.utils.six` +six.iterlists diff --git a/stubs/six/METADATA.toml b/stubs/six/METADATA.toml index 90e0456946aa..bf036333b2b7 100644 --- a/stubs/six/METADATA.toml +++ b/stubs/six/METADATA.toml @@ -1,2 +1,2 @@ -version = "1.16.*" -python2 = true +version = "1.17.*" +upstream-repository = "https://github.com/benjaminp/six" diff --git a/stubs/six/six/__init__.pyi b/stubs/six/six/__init__.pyi index 1f36799d6cfe..b137922b7482 100644 --- a/stubs/six/six/__init__.pyi +++ b/stubs/six/six/__init__.pyi @@ -1,15 +1,17 @@ -from __future__ import print_function - +import operator import types import unittest -from builtins import next as next +from _typeshed import IdentityFunction, SupportsGetItem, Unused +from builtins import callable as callable, next as next from collections.abc import Callable, ItemsView, Iterable, Iterator as _Iterator, KeysView, Mapping, ValuesView from functools import wraps as wraps +from importlib.util import spec_from_loader as spec_from_loader from io import BytesIO as BytesIO, StringIO as StringIO -from typing import Any, AnyStr, NoReturn, Pattern, Tuple, Type, TypeVar, overload -from typing_extensions import Literal +from re import Pattern +from typing import Any, AnyStr, Literal, TypeVar, overload +from typing_extensions import Never -from . import moves as moves +from six import moves as moves _T = TypeVar("_T") _K = TypeVar("_K") @@ -22,33 +24,31 @@ PY2: Literal[False] PY3: Literal[True] PY34: Literal[True] -string_types: tuple[Type[str]] -integer_types: tuple[Type[int]] -class_types: tuple[Type[Type[Any]]] +string_types: tuple[type[str]] +integer_types: tuple[type[int]] +class_types: tuple[type[type]] text_type = str binary_type = bytes MAXSIZE: int -def callable(obj: object) -> bool: ... def get_unbound_function(unbound: types.FunctionType) -> types.FunctionType: ... -def create_bound_method(func: types.FunctionType, obj: object) -> types.MethodType: ... + +create_bound_method = types.MethodType + def create_unbound_method(func: types.FunctionType, cls: type) -> types.FunctionType: ... Iterator = object def get_method_function(meth: types.MethodType) -> types.FunctionType: ... -def get_method_self(meth: types.MethodType) -> object | None: ... -def get_function_closure(fun: types.FunctionType) -> Tuple[types._Cell, ...] | None: ... +def get_method_self(meth: types.MethodType) -> object: ... +def get_function_closure(fun: types.FunctionType) -> tuple[types.CellType, ...] | None: ... def get_function_code(fun: types.FunctionType) -> types.CodeType: ... -def get_function_defaults(fun: types.FunctionType) -> Tuple[Any, ...] | None: ... +def get_function_defaults(fun: types.FunctionType) -> tuple[Any, ...] | None: ... def get_function_globals(fun: types.FunctionType) -> dict[str, Any]: ... def iterkeys(d: Mapping[_K, Any]) -> _Iterator[_K]: ... def itervalues(d: Mapping[Any, _V]) -> _Iterator[_V]: ... def iteritems(d: Mapping[_K, _V]) -> _Iterator[tuple[_K, _V]]: ... - -# def iterlists - def viewkeys(d: Mapping[_K, Any]) -> KeysView[_K]: ... def viewvalues(d: Mapping[Any, _V]) -> ValuesView[_V]: ... def viewitems(d: Mapping[_K, _V]) -> ItemsView[_K, _V]: ... @@ -58,46 +58,55 @@ def u(s: str) -> str: ... unichr = chr def int2byte(i: int) -> bytes: ... -def byte2int(bs: bytes) -> int: ... -def indexbytes(buf: bytes, i: int) -> int: ... -def iterbytes(buf: bytes) -> _Iterator[int]: ... + +# Should be `byte2int: operator.itemgetter[int]`. But `itemgetter.__call__` returns `Any` +def byte2int(obj: SupportsGetItem[int, _T]) -> _T: ... + +indexbytes = operator.getitem +iterbytes = iter + def assertCountEqual(self: unittest.TestCase, first: Iterable[_T], second: Iterable[_T], msg: str | None = ...) -> None: ... + @overload def assertRaisesRegex(self: unittest.TestCase, msg: str | None = ...) -> Any: ... @overload -def assertRaisesRegex(self: unittest.TestCase, callable_obj: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: ... -def assertRegex( - self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: str | None = ... -) -> None: ... +def assertRaisesRegex(self: unittest.TestCase, callable_obj: Callable[..., object], *args: Any, **kwargs: Any) -> Any: ... + +def assertRegex(self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... +def assertNotRegex(self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... exec_ = exec -def reraise(tp: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None = ...) -> NoReturn: ... -def raise_from(value: BaseException | Type[BaseException], from_value: BaseException | None) -> NoReturn: ... +def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None = None) -> Never: ... +def raise_from(value: BaseException | type[BaseException], from_value: BaseException | None) -> Never: ... print_ = print def with_metaclass(meta: type, *bases: type) -> type: ... -def add_metaclass(metaclass: type) -> Callable[[_T], _T]: ... -def ensure_binary(s: bytes | str, encoding: str = ..., errors: str = ...) -> bytes: ... -def ensure_str(s: bytes | str, encoding: str = ..., errors: str = ...) -> str: ... -def ensure_text(s: bytes | str, encoding: str = ..., errors: str = ...) -> str: ... +def add_metaclass(metaclass: type) -> IdentityFunction: ... +def ensure_binary(s: bytes | str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... +def ensure_str(s: bytes | str, encoding: str = "utf-8", errors: str = "strict") -> str: ... +def ensure_text(s: bytes | str, encoding: str = "utf-8", errors: str = "strict") -> str: ... def python_2_unicode_compatible(klass: _T) -> _T: ... class _LazyDescr: name: str def __init__(self, name: str) -> None: ... - def __get__(self, obj: object | None, type: Type[Any] | None = ...) -> Any: ... + def __get__(self, obj: object, tp: Unused) -> Any: ... class MovedModule(_LazyDescr): mod: str - def __init__(self, name: str, old: str, new: str | None = ...) -> None: ... + def __init__(self, name: str, old: str, new: str | None = None) -> None: ... def __getattr__(self, attr: str) -> Any: ... class MovedAttribute(_LazyDescr): mod: str attr: str - def __init__(self, name: str, old_mod: str, new_mod: str, old_attr: str | None = ..., new_attr: str | None = ...) -> None: ... + def __init__( + self, name: str, old_mod: str, new_mod: str, old_attr: str | None = None, new_attr: str | None = None + ) -> None: ... def add_move(move: MovedModule | MovedAttribute) -> None: ... def remove_move(name: str) -> None: ... + +advance_iterator = next diff --git a/stubs/six/six/moves/__init__.pyi b/stubs/six/six/moves/__init__.pyi index 3455676db51e..ae64ae674f03 100644 --- a/stubs/six/six/moves/__init__.pyi +++ b/stubs/six/six/moves/__init__.pyi @@ -20,7 +20,6 @@ from sys import intern as intern # import tkinter.scrolledtext as tkinter_scrolledtext # import tkinter.simpledialog as tkinter_simpledialog # import tkinter.tix as tkinter_tix -# import copyreg as copyreg # import dbm.gnu as dbm_gnu from . import ( BaseHTTPServer as BaseHTTPServer, @@ -30,6 +29,7 @@ from . import ( _thread as _thread, builtins as builtins, configparser as configparser, + copyreg as copyreg, cPickle as cPickle, email_mime_base as email_mime_base, email_mime_multipart as email_mime_multipart, diff --git a/stubs/six/six/moves/_dummy_thread.pyi b/stubs/six/six/moves/_dummy_thread.pyi index 410232d07417..25952a61494f 100644 --- a/stubs/six/six/moves/_dummy_thread.pyi +++ b/stubs/six/six/moves/_dummy_thread.pyi @@ -1,6 +1 @@ -import sys - -if sys.version_info >= (3, 9): - from _thread import * -else: - from _dummy_thread import * +from _thread import * diff --git a/stubs/six/six/moves/builtins.pyi b/stubs/six/six/moves/builtins.pyi index 9596ba032aa0..2b1b40808aca 100644 --- a/stubs/six/six/moves/builtins.pyi +++ b/stubs/six/six/moves/builtins.pyi @@ -1 +1,3 @@ -from builtins import * +# six explicitly re-exports builtins. Normally this is something we'd want to avoid. +# But this is specifically a compatibility package. +from builtins import * # ruff: ignore[unnecessary-builtin-import] diff --git a/stubs/six/six/moves/configparser.pyi b/stubs/six/six/moves/configparser.pyi index 044861ce0c38..3367dbd19622 100644 --- a/stubs/six/six/moves/configparser.pyi +++ b/stubs/six/six/moves/configparser.pyi @@ -1 +1,3 @@ +# Error is not included in __all__ so export it explicitly from configparser import * +from configparser import Error as Error diff --git a/stubs/six/six/moves/copyreg.pyi b/stubs/six/six/moves/copyreg.pyi new file mode 100644 index 000000000000..1848b74c35a3 --- /dev/null +++ b/stubs/six/six/moves/copyreg.pyi @@ -0,0 +1 @@ +from copyreg import * diff --git a/stubs/six/six/moves/http_client.pyi b/stubs/six/six/moves/http_client.pyi index 36d29b9551bc..ecfce42f02c3 100644 --- a/stubs/six/six/moves/http_client.pyi +++ b/stubs/six/six/moves/http_client.pyi @@ -1 +1,61 @@ +# Many definitions are not included in http.client.__all__ from http.client import * +from http.client import ( + ACCEPTED as ACCEPTED, + BAD_GATEWAY as BAD_GATEWAY, + BAD_REQUEST as BAD_REQUEST, + CONFLICT as CONFLICT, + CONTINUE as CONTINUE, + CREATED as CREATED, + EXPECTATION_FAILED as EXPECTATION_FAILED, + FAILED_DEPENDENCY as FAILED_DEPENDENCY, + FORBIDDEN as FORBIDDEN, + FOUND as FOUND, + GATEWAY_TIMEOUT as GATEWAY_TIMEOUT, + GONE as GONE, + HTTP_PORT as HTTP_PORT, + HTTP_VERSION_NOT_SUPPORTED as HTTP_VERSION_NOT_SUPPORTED, + HTTPS_PORT as HTTPS_PORT, + IM_USED as IM_USED, + INSUFFICIENT_STORAGE as INSUFFICIENT_STORAGE, + INTERNAL_SERVER_ERROR as INTERNAL_SERVER_ERROR, + LENGTH_REQUIRED as LENGTH_REQUIRED, + LOCKED as LOCKED, + METHOD_NOT_ALLOWED as METHOD_NOT_ALLOWED, + MOVED_PERMANENTLY as MOVED_PERMANENTLY, + MULTI_STATUS as MULTI_STATUS, + MULTIPLE_CHOICES as MULTIPLE_CHOICES, + NETWORK_AUTHENTICATION_REQUIRED as NETWORK_AUTHENTICATION_REQUIRED, + NO_CONTENT as NO_CONTENT, + NON_AUTHORITATIVE_INFORMATION as NON_AUTHORITATIVE_INFORMATION, + NOT_ACCEPTABLE as NOT_ACCEPTABLE, + NOT_EXTENDED as NOT_EXTENDED, + NOT_FOUND as NOT_FOUND, + NOT_IMPLEMENTED as NOT_IMPLEMENTED, + NOT_MODIFIED as NOT_MODIFIED, + OK as OK, + PARTIAL_CONTENT as PARTIAL_CONTENT, + PAYMENT_REQUIRED as PAYMENT_REQUIRED, + PRECONDITION_FAILED as PRECONDITION_FAILED, + PRECONDITION_REQUIRED as PRECONDITION_REQUIRED, + PROCESSING as PROCESSING, + PROXY_AUTHENTICATION_REQUIRED as PROXY_AUTHENTICATION_REQUIRED, + REQUEST_ENTITY_TOO_LARGE as REQUEST_ENTITY_TOO_LARGE, + REQUEST_HEADER_FIELDS_TOO_LARGE as REQUEST_HEADER_FIELDS_TOO_LARGE, + REQUEST_TIMEOUT as REQUEST_TIMEOUT, + REQUEST_URI_TOO_LONG as REQUEST_URI_TOO_LONG, + REQUESTED_RANGE_NOT_SATISFIABLE as REQUESTED_RANGE_NOT_SATISFIABLE, + RESET_CONTENT as RESET_CONTENT, + SEE_OTHER as SEE_OTHER, + SERVICE_UNAVAILABLE as SERVICE_UNAVAILABLE, + SWITCHING_PROTOCOLS as SWITCHING_PROTOCOLS, + TEMPORARY_REDIRECT as TEMPORARY_REDIRECT, + TOO_MANY_REQUESTS as TOO_MANY_REQUESTS, + UNAUTHORIZED as UNAUTHORIZED, + UNPROCESSABLE_ENTITY as UNPROCESSABLE_ENTITY, + UNSUPPORTED_MEDIA_TYPE as UNSUPPORTED_MEDIA_TYPE, + UPGRADE_REQUIRED as UPGRADE_REQUIRED, + USE_PROXY as USE_PROXY, + HTTPMessage as HTTPMessage, + parse_headers as parse_headers, +) diff --git a/stubs/six/six/moves/http_cookies.pyi b/stubs/six/six/moves/http_cookies.pyi index 9c59a53977bc..1e168c8e7138 100644 --- a/stubs/six/six/moves/http_cookies.pyi +++ b/stubs/six/six/moves/http_cookies.pyi @@ -1 +1,3 @@ +# Morsel is not included in __all__ so export it explicitly from http.cookies import * +from http.cookies import Morsel as Morsel diff --git a/stubs/six/six/moves/urllib/__init__.pyi b/stubs/six/six/moves/urllib/__init__.pyi index d08209c51cc1..fa6dc977937d 100644 --- a/stubs/six/six/moves/urllib/__init__.pyi +++ b/stubs/six/six/moves/urllib/__init__.pyi @@ -1,5 +1 @@ -import six.moves.urllib.error as error -import six.moves.urllib.parse as parse -import six.moves.urllib.request as request -import six.moves.urllib.response as response -import six.moves.urllib.robotparser as robotparser +from six.moves.urllib import error as error, parse as parse, request as request, response as response, robotparser as robotparser diff --git a/stubs/six/six/moves/urllib/request.pyi b/stubs/six/six/moves/urllib/request.pyi index 9b670b4d98b0..69d402c61659 100644 --- a/stubs/six/six/moves/urllib/request.pyi +++ b/stubs/six/six/moves/urllib/request.pyi @@ -1,3 +1,5 @@ +import sys + # Stubs for six.moves.urllib.request # # Note: Commented out items means they weren't implemented at the time. @@ -8,7 +10,6 @@ from urllib.request import ( AbstractDigestAuthHandler as AbstractDigestAuthHandler, BaseHandler as BaseHandler, CacheFTPHandler as CacheFTPHandler, - FancyURLopener as FancyURLopener, FileHandler as FileHandler, FTPHandler as FTPHandler, HTTPBasicAuthHandler as HTTPBasicAuthHandler, @@ -27,7 +28,6 @@ from urllib.request import ( ProxyHandler as ProxyHandler, Request as Request, UnknownHandler as UnknownHandler, - URLopener as URLopener, build_opener as build_opener, getproxies as getproxies, install_opener as install_opener, @@ -39,3 +39,6 @@ from urllib.request import ( urlopen as urlopen, urlretrieve as urlretrieve, ) + +if sys.version_info < (3, 14): + from urllib.request import FancyURLopener as FancyURLopener, URLopener as URLopener diff --git a/stubs/slumber/@tests/stubtest_allowlist.txt b/stubs/slumber/@tests/stubtest_allowlist.txt deleted file mode 100644 index 15230d95a77b..000000000000 --- a/stubs/slumber/@tests/stubtest_allowlist.txt +++ /dev/null @@ -1,2 +0,0 @@ -slumber.API.__init__ -slumber.Resource.as_raw diff --git a/stubs/slumber/METADATA.toml b/stubs/slumber/METADATA.toml index 7431acfe0fa8..c26264bafec2 100644 --- a/stubs/slumber/METADATA.toml +++ b/stubs/slumber/METADATA.toml @@ -1 +1,3 @@ version = "0.7.*" +upstream-repository = "https://github.com/samgiles/slumber" +dependencies = ["requests>=2.34.0"] diff --git a/stubs/slumber/slumber/__init__.pyi b/stubs/slumber/slumber/__init__.pyi index 8d6f59e49a86..4169c337c152 100644 --- a/stubs/slumber/slumber/__init__.pyi +++ b/stubs/slumber/slumber/__init__.pyi @@ -1,30 +1,43 @@ from typing import Any +from typing_extensions import Self + +from requests import Response, Session +from requests._types import AuthType, DataType, FilesType, _ParamsMappingValueType + +from .serialize import Serializer + +__all__ = ["Resource", "API"] class ResourceAttributesMixin: - def __getattr__(self, item): ... + # Exists at runtime: + def __getattr__(self, item: str) -> Any: ... class Resource(ResourceAttributesMixin): - def __init__(self, *args, **kwargs) -> None: ... - def __call__(self, id: Any | None = ..., format: Any | None = ..., url_override: Any | None = ...): ... - def as_raw(self): ... - def get(self, **kwargs): ... - def options(self, **kwargs): ... - def head(self, **kwargs): ... - def post(self, data: Any | None = ..., files: Any | None = ..., **kwargs): ... - def patch(self, data: Any | None = ..., files: Any | None = ..., **kwargs): ... - def put(self, data: Any | None = ..., files: Any | None = ..., **kwargs): ... - def delete(self, **kwargs): ... - def url(self): ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __call__(self, id: str | None = None, format: str | None = None, url_override: str | None = None) -> Self: ... + def get(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def options(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def head(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def post( + self, data: DataType | None = None, files: FilesType | None = None, **kwargs: _ParamsMappingValueType + ) -> Response: ... + def patch( + self, data: DataType | None = None, files: FilesType | None = None, **kwargs: _ParamsMappingValueType + ) -> Response: ... + def put( + self, data: DataType | None = None, files: FilesType | None = None, **kwargs: _ParamsMappingValueType + ) -> Response: ... + def delete(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def url(self) -> str: ... class API(ResourceAttributesMixin): - resource_class: Any + resource_class: type[Resource] def __init__( self, - base_url: Any | None = ..., - auth: Any | None = ..., - format: Any | None = ..., - append_slash: bool = ..., - session: Any | None = ..., - serializer: Any | None = ..., - raw: bool = ..., + base_url: str | None = None, + auth: AuthType | None = None, + format: str | None = None, + append_slash: bool = True, + session: Session | None = None, + serializer: Serializer | None = None, ) -> None: ... diff --git a/stubs/slumber/slumber/exceptions.pyi b/stubs/slumber/slumber/exceptions.pyi index a077fd22a9ab..20cac92d7479 100644 --- a/stubs/slumber/slumber/exceptions.pyi +++ b/stubs/slumber/slumber/exceptions.pyi @@ -1,7 +1,9 @@ +from typing import Any + class SlumberBaseException(Exception): ... class SlumberHttpBaseException(SlumberBaseException): - def __init__(self, *args, **kwargs) -> None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... class HttpClientError(SlumberHttpBaseException): ... class HttpNotFoundError(HttpClientError): ... diff --git a/stubs/slumber/slumber/serialize.pyi b/stubs/slumber/slumber/serialize.pyi index a3cb19796925..49a611cc084b 100644 --- a/stubs/slumber/slumber/serialize.pyi +++ b/stubs/slumber/slumber/serialize.pyi @@ -1,29 +1,27 @@ -from typing import Any +from typing import Any, TypeAlias + +_Data: TypeAlias = str | bytes | bytearray class BaseSerializer: - content_types: Any - key: Any - def get_content_type(self): ... - def loads(self, data) -> None: ... - def dumps(self, data) -> None: ... + content_types: list[str] | None + key: str | None + def get_content_type(self) -> str: ... + def loads(self, data: _Data) -> Any: ... + def dumps(self, data: _Data) -> Any: ... class JsonSerializer(BaseSerializer): - content_types: Any + content_types: list[str] key: str - def loads(self, data): ... - def dumps(self, data): ... class YamlSerializer(BaseSerializer): - content_types: Any + content_types: list[str] key: str - def loads(self, data): ... - def dumps(self, data): ... class Serializer: - serializers: Any - default: Any - def __init__(self, default: Any | None = ..., serializers: Any | None = ...) -> None: ... - def get_serializer(self, name: Any | None = ..., content_type: Any | None = ...): ... - def loads(self, data, format: Any | None = ...): ... - def dumps(self, data, format: Any | None = ...): ... - def get_content_type(self, format: Any | None = ...): ... + serializers: list[BaseSerializer] + default: str + def __init__(self, default: str | None = None, serializers: list[BaseSerializer] | None = None) -> None: ... + def get_serializer(self, name: str | None = None, content_type: str | None = None) -> BaseSerializer: ... + def loads(self, data: _Data, format: str | None = None) -> Any: ... + def dumps(self, data: _Data, format: str | None = None) -> Any: ... + def get_content_type(self, format: str | None = None) -> str: ... diff --git a/stubs/slumber/slumber/utils.pyi b/stubs/slumber/slumber/utils.pyi index 818c5a39f8bc..3dc0c9ee6dc8 100644 --- a/stubs/slumber/slumber/utils.pyi +++ b/stubs/slumber/slumber/utils.pyi @@ -1,3 +1,10 @@ -def url_join(base, *args): ... -def copy_kwargs(dictionary): ... -def iterator(d): ... +from collections.abc import ItemsView, Mapping, MutableMapping +from typing import Any, TypeVar + +_KT = TypeVar("_KT") +_VT_co = TypeVar("_VT_co", covariant=True) +_MM = TypeVar("_MM", bound=MutableMapping[Any, Any]) + +def url_join(base: str, *args: str) -> str: ... +def copy_kwargs(dictionary: _MM) -> _MM: ... +def iterator(d: Mapping[_KT, _VT_co]) -> ItemsView[_KT, _VT_co]: ... diff --git a/stubs/str2bool/METADATA.toml b/stubs/str2bool/METADATA.toml new file mode 100644 index 000000000000..603a54f0026b --- /dev/null +++ b/stubs/str2bool/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1" +upstream-repository = "https://github.com/symonsoft/str2bool" diff --git a/stubs/str2bool/str2bool/__init__.pyi b/stubs/str2bool/str2bool/__init__.pyi new file mode 100644 index 000000000000..d7d801d9a239 --- /dev/null +++ b/stubs/str2bool/str2bool/__init__.pyi @@ -0,0 +1,8 @@ +from typing import Literal, overload + +@overload +def str2bool(value: str, raise_exc: Literal[True]) -> bool: ... +@overload +def str2bool(value: str, raise_exc: bool = False) -> bool | None: ... + +def str2bool_exc(value: str) -> bool: ... diff --git a/stubs/stripe/METADATA.toml b/stubs/stripe/METADATA.toml deleted file mode 100644 index 5d262932f608..000000000000 --- a/stubs/stripe/METADATA.toml +++ /dev/null @@ -1 +0,0 @@ -version = "2.59.*" diff --git a/stubs/stripe/stripe/__init__.pyi b/stubs/stripe/stripe/__init__.pyi deleted file mode 100644 index c0c1a3d6ae83..000000000000 --- a/stubs/stripe/stripe/__init__.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any - -from stripe.api_resources import * -from stripe.oauth import OAuth as OAuth -from stripe.webhook import Webhook as Webhook, WebhookSignature as WebhookSignature - -api_key: Any -client_id: Any -api_base: str -connect_api_base: str -upload_api_base: str -api_version: Any -verify_ssl_certs: bool -proxy: Any -default_http_client: Any -app_info: Any -enable_telemetry: bool -max_network_retries: int -ca_bundle_path: Any -log: Any - -def set_app_info(name, partner_id: Any | None = ..., url: Any | None = ..., version: Any | None = ...) -> None: ... diff --git a/stubs/stripe/stripe/api_requestor.pyi b/stubs/stripe/stripe/api_requestor.pyi deleted file mode 100644 index 59887448a046..000000000000 --- a/stubs/stripe/stripe/api_requestor.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any - -from stripe import error as error, http_client as http_client, oauth_error as oauth_error, version as version -from stripe.multipart_data_generator import MultipartDataGenerator as MultipartDataGenerator -from stripe.stripe_response import StripeResponse as StripeResponse, StripeStreamResponse as StripeStreamResponse - -class APIRequestor: - api_base: Any - api_key: Any - api_version: Any - stripe_account: Any - def __init__( - self, - key: Any | None = ..., - client: Any | None = ..., - api_base: Any | None = ..., - api_version: Any | None = ..., - account: Any | None = ..., - ) -> None: ... - @classmethod - def format_app_info(cls, info): ... - def request(self, method, url, params: Any | None = ..., headers: Any | None = ...): ... - def request_stream(self, method, url, params: Any | None = ..., headers: Any | None = ...): ... - def handle_error_response(self, rbody, rcode, resp, rheaders) -> None: ... - def specific_api_error(self, rbody, rcode, resp, rheaders, error_data): ... - def specific_oauth_error(self, rbody, rcode, resp, rheaders, error_code): ... - def request_headers(self, api_key, method): ... - def request_raw( - self, method, url, params: Any | None = ..., supplied_headers: Any | None = ..., is_streaming: bool = ... - ): ... - def interpret_response(self, rbody, rcode, rheaders): ... - def interpret_streaming_response(self, stream, rcode, rheaders): ... diff --git a/stubs/stripe/stripe/api_resources/__init__.pyi b/stubs/stripe/stripe/api_resources/__init__.pyi deleted file mode 100644 index 2bf4dae4f0b8..000000000000 --- a/stubs/stripe/stripe/api_resources/__init__.pyi +++ /dev/null @@ -1,79 +0,0 @@ -from stripe.api_resources import ( - billing_portal as billing_portal, - checkout as checkout, - identity as identity, - issuing as issuing, - radar as radar, - reporting as reporting, - sigma as sigma, - terminal as terminal, -) -from stripe.api_resources.account import Account as Account -from stripe.api_resources.account_link import AccountLink as AccountLink -from stripe.api_resources.alipay_account import AlipayAccount as AlipayAccount -from stripe.api_resources.apple_pay_domain import ApplePayDomain as ApplePayDomain -from stripe.api_resources.application_fee import ApplicationFee as ApplicationFee -from stripe.api_resources.application_fee_refund import ApplicationFeeRefund as ApplicationFeeRefund -from stripe.api_resources.balance import Balance as Balance -from stripe.api_resources.balance_transaction import BalanceTransaction as BalanceTransaction -from stripe.api_resources.bank_account import BankAccount as BankAccount -from stripe.api_resources.bitcoin_receiver import BitcoinReceiver as BitcoinReceiver -from stripe.api_resources.bitcoin_transaction import BitcoinTransaction as BitcoinTransaction -from stripe.api_resources.capability import Capability as Capability -from stripe.api_resources.card import Card as Card -from stripe.api_resources.charge import Charge as Charge -from stripe.api_resources.country_spec import CountrySpec as CountrySpec -from stripe.api_resources.coupon import Coupon as Coupon -from stripe.api_resources.credit_note import CreditNote as CreditNote -from stripe.api_resources.credit_note_line_item import CreditNoteLineItem as CreditNoteLineItem -from stripe.api_resources.customer import Customer as Customer -from stripe.api_resources.customer_balance_transaction import CustomerBalanceTransaction as CustomerBalanceTransaction -from stripe.api_resources.dispute import Dispute as Dispute -from stripe.api_resources.ephemeral_key import EphemeralKey as EphemeralKey -from stripe.api_resources.error_object import ErrorObject as ErrorObject, OAuthErrorObject as OAuthErrorObject -from stripe.api_resources.event import Event as Event -from stripe.api_resources.exchange_rate import ExchangeRate as ExchangeRate -from stripe.api_resources.file import File as File, FileUpload as FileUpload -from stripe.api_resources.file_link import FileLink as FileLink -from stripe.api_resources.invoice import Invoice as Invoice -from stripe.api_resources.invoice_item import InvoiceItem as InvoiceItem -from stripe.api_resources.invoice_line_item import InvoiceLineItem as InvoiceLineItem -from stripe.api_resources.issuer_fraud_record import IssuerFraudRecord as IssuerFraudRecord -from stripe.api_resources.line_item import LineItem as LineItem -from stripe.api_resources.list_object import ListObject as ListObject -from stripe.api_resources.login_link import LoginLink as LoginLink -from stripe.api_resources.mandate import Mandate as Mandate -from stripe.api_resources.order import Order as Order -from stripe.api_resources.order_return import OrderReturn as OrderReturn -from stripe.api_resources.payment_intent import PaymentIntent as PaymentIntent -from stripe.api_resources.payment_method import PaymentMethod as PaymentMethod -from stripe.api_resources.payout import Payout as Payout -from stripe.api_resources.person import Person as Person -from stripe.api_resources.plan import Plan as Plan -from stripe.api_resources.price import Price as Price -from stripe.api_resources.product import Product as Product -from stripe.api_resources.promotion_code import PromotionCode as PromotionCode -from stripe.api_resources.quote import Quote as Quote -from stripe.api_resources.recipient import Recipient as Recipient -from stripe.api_resources.recipient_transfer import RecipientTransfer as RecipientTransfer -from stripe.api_resources.refund import Refund as Refund -from stripe.api_resources.reversal import Reversal as Reversal -from stripe.api_resources.review import Review as Review -from stripe.api_resources.setup_attempt import SetupAttempt as SetupAttempt -from stripe.api_resources.setup_intent import SetupIntent as SetupIntent -from stripe.api_resources.sku import SKU as SKU -from stripe.api_resources.source import Source as Source -from stripe.api_resources.source_transaction import SourceTransaction as SourceTransaction -from stripe.api_resources.subscription import Subscription as Subscription -from stripe.api_resources.subscription_item import SubscriptionItem as SubscriptionItem -from stripe.api_resources.subscription_schedule import SubscriptionSchedule as SubscriptionSchedule -from stripe.api_resources.tax_code import TaxCode as TaxCode -from stripe.api_resources.tax_id import TaxId as TaxId -from stripe.api_resources.tax_rate import TaxRate as TaxRate -from stripe.api_resources.three_d_secure import ThreeDSecure as ThreeDSecure -from stripe.api_resources.token import Token as Token -from stripe.api_resources.topup import Topup as Topup -from stripe.api_resources.transfer import Transfer as Transfer -from stripe.api_resources.usage_record import UsageRecord as UsageRecord -from stripe.api_resources.usage_record_summary import UsageRecordSummary as UsageRecordSummary -from stripe.api_resources.webhook_endpoint import WebhookEndpoint as WebhookEndpoint diff --git a/stubs/stripe/stripe/api_resources/abstract/__init__.pyi b/stubs/stripe/stripe/api_resources/abstract/__init__.pyi deleted file mode 100644 index a3d77265cb2c..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/__init__.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from stripe.api_resources.abstract.api_resource import APIResource as APIResource -from stripe.api_resources.abstract.createable_api_resource import CreateableAPIResource as CreateableAPIResource -from stripe.api_resources.abstract.custom_method import custom_method as custom_method -from stripe.api_resources.abstract.deletable_api_resource import DeletableAPIResource as DeletableAPIResource -from stripe.api_resources.abstract.listable_api_resource import ListableAPIResource as ListableAPIResource -from stripe.api_resources.abstract.nested_resource_class_methods import ( - nested_resource_class_methods as nested_resource_class_methods, -) -from stripe.api_resources.abstract.singleton_api_resource import SingletonAPIResource as SingletonAPIResource -from stripe.api_resources.abstract.updateable_api_resource import UpdateableAPIResource as UpdateableAPIResource -from stripe.api_resources.abstract.verify_mixin import VerifyMixin as VerifyMixin diff --git a/stubs/stripe/stripe/api_resources/abstract/api_resource.pyi b/stubs/stripe/stripe/api_resources/abstract/api_resource.pyi deleted file mode 100644 index b6e5f16a67dd..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/api_resource.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor, error as error -from stripe.stripe_object import StripeObject as StripeObject - -class APIResource(StripeObject): - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params): ... - def refresh(self): ... - @classmethod - def class_url(cls): ... - def instance_url(self): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/createable_api_resource.pyi b/stubs/stripe/stripe/api_resources/abstract/createable_api_resource.pyi deleted file mode 100644 index ebc47b807f71..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/createable_api_resource.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract.api_resource import APIResource as APIResource - -class CreateableAPIResource(APIResource): - @classmethod - def create( - cls, - api_key: Any | None = ..., - idempotency_key: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - **params, - ): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/custom_method.pyi b/stubs/stripe/stripe/api_resources/abstract/custom_method.pyi deleted file mode 100644 index fc352568fae0..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/custom_method.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from typing import Any - -def custom_method(name, http_verb, http_path: Any | None = ..., is_streaming: bool = ...): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/deletable_api_resource.pyi b/stubs/stripe/stripe/api_resources/abstract/deletable_api_resource.pyi deleted file mode 100644 index cd8de7131fbc..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/deletable_api_resource.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract.api_resource import APIResource as APIResource - -class DeletableAPIResource(APIResource): - def delete(self, **params): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/listable_api_resource.pyi b/stubs/stripe/stripe/api_resources/abstract/listable_api_resource.pyi deleted file mode 100644 index a1c1e0793f6c..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/listable_api_resource.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract.api_resource import APIResource as APIResource - -class ListableAPIResource(APIResource): - @classmethod - def auto_paging_iter(cls, *args, **params): ... - @classmethod - def list(cls, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/nested_resource_class_methods.pyi b/stubs/stripe/stripe/api_resources/abstract/nested_resource_class_methods.pyi deleted file mode 100644 index 38c2d65fc448..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/nested_resource_class_methods.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor - -def nested_resource_class_methods( - resource, path: Any | None = ..., operations: Any | None = ..., resource_plural: Any | None = ... -): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/singleton_api_resource.pyi b/stubs/stripe/stripe/api_resources/abstract/singleton_api_resource.pyi deleted file mode 100644 index 602ae3564332..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/singleton_api_resource.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract.api_resource import APIResource as APIResource - -class SingletonAPIResource(APIResource): - @classmethod - def retrieve(cls, **params): ... - @classmethod - def class_url(cls): ... - def instance_url(self): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/updateable_api_resource.pyi b/stubs/stripe/stripe/api_resources/abstract/updateable_api_resource.pyi deleted file mode 100644 index 13ca7072c187..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/updateable_api_resource.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract.api_resource import APIResource as APIResource - -class UpdateableAPIResource(APIResource): - @classmethod - def modify(cls, sid, **params): ... - def save(self, idempotency_key: Any | None = ...): ... diff --git a/stubs/stripe/stripe/api_resources/abstract/verify_mixin.pyi b/stubs/stripe/stripe/api_resources/abstract/verify_mixin.pyi deleted file mode 100644 index 2b5f795e47be..000000000000 --- a/stubs/stripe/stripe/api_resources/abstract/verify_mixin.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import Any - -class VerifyMixin: - def verify(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/account.pyi b/stubs/stripe/stripe/api_resources/account.pyi deleted file mode 100644 index 39cb243e9763..000000000000 --- a/stubs/stripe/stripe/api_resources/account.pyi +++ /dev/null @@ -1,73 +0,0 @@ -from typing import Any - -from stripe import oauth as oauth -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, - nested_resource_class_methods as nested_resource_class_methods, -) - -class Account(CreateableAPIResource, DeletableAPIResource, ListableAPIResource): - OBJECT_NAME: str - def reject(self, idempotency_key: Any | None = ..., **params): ... - @classmethod - def retrieve(cls, id: Any | None = ..., api_key: Any | None = ..., **params): ... - @classmethod - def modify(cls, id: Any | None = ..., **params): ... - def instance_url(self): ... - def persons(self, **params): ... - def deauthorize(self, **params): ... - def serialize(self, previous): ... - @classmethod - def capabilitys_url(cls, id, nested_id=...): ... - @classmethod - def capabilitys_request( - cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params - ): ... - @classmethod - def retrieve_capability(cls, id, nested_id, **params): ... - @classmethod - def modify_capability(cls, id, nested_id, **params): ... - @classmethod - def list_capabilities(cls, id, **params): ... - @classmethod - def external_accounts_url(cls, id, nested_id=...): ... - @classmethod - def external_accounts_request( - cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params - ): ... - @classmethod - def create_external_account(cls, id, **params): ... - @classmethod - def retrieve_external_account(cls, id, nested_id, **params): ... - @classmethod - def modify_external_account(cls, id, nested_id, **params): ... - @classmethod - def delete_external_account(cls, id, nested_id, **params): ... - @classmethod - def list_external_accounts(cls, id, **params): ... - @classmethod - def login_links_url(cls, id, nested_id=...): ... - @classmethod - def login_links_request( - cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params - ): ... - @classmethod - def create_login_link(cls, id, **params): ... - @classmethod - def persons_url(cls, id, nested_id=...): ... - @classmethod - def persons_request(cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params): ... - @classmethod - def create_person(cls, id, **params): ... - @classmethod - def retrieve_person(cls, id, nested_id, **params): ... - @classmethod - def modify_person(cls, id, nested_id, **params): ... - @classmethod - def delete_person(cls, id, nested_id, **params): ... - @classmethod - def list_persons(cls, id, **params): ... diff --git a/stubs/stripe/stripe/api_resources/account_link.pyi b/stubs/stripe/stripe/api_resources/account_link.pyi deleted file mode 100644 index a50565c5b9e5..000000000000 --- a/stubs/stripe/stripe/api_resources/account_link.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import CreateableAPIResource as CreateableAPIResource - -class AccountLink(CreateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/alipay_account.pyi b/stubs/stripe/stripe/api_resources/alipay_account.pyi deleted file mode 100644 index e9a5991dd235..000000000000 --- a/stubs/stripe/stripe/api_resources/alipay_account.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - DeletableAPIResource as DeletableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) -from stripe.api_resources.customer import Customer as Customer - -class AlipayAccount(DeletableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def modify(cls, customer, id, **params): ... - @classmethod - def retrieve( - cls, id, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/apple_pay_domain.pyi b/stubs/stripe/stripe/api_resources/apple_pay_domain.pyi deleted file mode 100644 index 0e9332010c49..000000000000 --- a/stubs/stripe/stripe/api_resources/apple_pay_domain.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, -) - -class ApplePayDomain(CreateableAPIResource, DeletableAPIResource, ListableAPIResource): - OBJECT_NAME: str - @classmethod - def class_url(cls): ... diff --git a/stubs/stripe/stripe/api_resources/application_fee.pyi b/stubs/stripe/stripe/api_resources/application_fee.pyi deleted file mode 100644 index e6f0ec58911b..000000000000 --- a/stubs/stripe/stripe/api_resources/application_fee.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - ListableAPIResource as ListableAPIResource, - nested_resource_class_methods as nested_resource_class_methods, -) - -class ApplicationFee(ListableAPIResource): - OBJECT_NAME: str - def refund(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/application_fee_refund.pyi b/stubs/stripe/stripe/api_resources/application_fee_refund.pyi deleted file mode 100644 index 1d8822cf6775..000000000000 --- a/stubs/stripe/stripe/api_resources/application_fee_refund.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources import ApplicationFee as ApplicationFee -from stripe.api_resources.abstract import UpdateableAPIResource as UpdateableAPIResource - -class ApplicationFeeRefund(UpdateableAPIResource): - OBJECT_NAME: str - @classmethod - def modify(cls, fee, sid, **params): ... - def instance_url(self): ... - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/balance.pyi b/stubs/stripe/stripe/api_resources/balance.pyi deleted file mode 100644 index 03a33a9baeb2..000000000000 --- a/stubs/stripe/stripe/api_resources/balance.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import SingletonAPIResource as SingletonAPIResource - -class Balance(SingletonAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/balance_transaction.pyi b/stubs/stripe/stripe/api_resources/balance_transaction.pyi deleted file mode 100644 index bdbf7b88e614..000000000000 --- a/stubs/stripe/stripe/api_resources/balance_transaction.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class BalanceTransaction(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/bank_account.pyi b/stubs/stripe/stripe/api_resources/bank_account.pyi deleted file mode 100644 index a662c8619888..000000000000 --- a/stubs/stripe/stripe/api_resources/bank_account.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Any - -from stripe import error as error -from stripe.api_resources.abstract import ( - DeletableAPIResource as DeletableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - VerifyMixin as VerifyMixin, -) -from stripe.api_resources.account import Account as Account -from stripe.api_resources.customer import Customer as Customer - -class BankAccount(DeletableAPIResource, UpdateableAPIResource, VerifyMixin): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def modify(cls, sid, **params) -> None: ... - @classmethod - def retrieve( - cls, id, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/billing_portal/__init__.pyi b/stubs/stripe/stripe/api_resources/billing_portal/__init__.pyi deleted file mode 100644 index 8132f0963886..000000000000 --- a/stubs/stripe/stripe/api_resources/billing_portal/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from stripe.api_resources.billing_portal.configuration import Configuration as Configuration -from stripe.api_resources.billing_portal.session import Session as Session diff --git a/stubs/stripe/stripe/api_resources/billing_portal/configuration.pyi b/stubs/stripe/stripe/api_resources/billing_portal/configuration.pyi deleted file mode 100644 index 875989abc46a..000000000000 --- a/stubs/stripe/stripe/api_resources/billing_portal/configuration.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Configuration(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/billing_portal/session.pyi b/stubs/stripe/stripe/api_resources/billing_portal/session.pyi deleted file mode 100644 index 1bce47c9961c..000000000000 --- a/stubs/stripe/stripe/api_resources/billing_portal/session.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import CreateableAPIResource as CreateableAPIResource - -class Session(CreateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/bitcoin_receiver.pyi b/stubs/stripe/stripe/api_resources/bitcoin_receiver.pyi deleted file mode 100644 index 933736a3cf62..000000000000 --- a/stubs/stripe/stripe/api_resources/bitcoin_receiver.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource -from stripe.api_resources.customer import Customer as Customer - -class BitcoinReceiver(ListableAPIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def class_url(cls): ... diff --git a/stubs/stripe/stripe/api_resources/bitcoin_transaction.pyi b/stubs/stripe/stripe/api_resources/bitcoin_transaction.pyi deleted file mode 100644 index 0f354550af29..000000000000 --- a/stubs/stripe/stripe/api_resources/bitcoin_transaction.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class BitcoinTransaction(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/capability.pyi b/stubs/stripe/stripe/api_resources/capability.pyi deleted file mode 100644 index 9d3f1a752b51..000000000000 --- a/stubs/stripe/stripe/api_resources/capability.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import UpdateableAPIResource as UpdateableAPIResource -from stripe.api_resources.account import Account as Account - -class Capability(UpdateableAPIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def modify(cls, sid, **params) -> None: ... - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/card.pyi b/stubs/stripe/stripe/api_resources/card.pyi deleted file mode 100644 index a8c5a4ce3939..000000000000 --- a/stubs/stripe/stripe/api_resources/card.pyi +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Any - -from stripe import error as error -from stripe.api_resources.abstract import ( - DeletableAPIResource as DeletableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) -from stripe.api_resources.account import Account as Account -from stripe.api_resources.customer import Customer as Customer -from stripe.api_resources.recipient import Recipient as Recipient - -class Card(DeletableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def modify(cls, sid, **params) -> None: ... - @classmethod - def retrieve( - cls, id, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/charge.pyi b/stubs/stripe/stripe/api_resources/charge.pyi deleted file mode 100644 index 2e3467e67bc5..000000000000 --- a/stubs/stripe/stripe/api_resources/charge.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Charge(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def capture(self, idempotency_key: Any | None = ..., **params): ... - def refund(self, idempotency_key: Any | None = ..., **params): ... - def update_dispute(self, idempotency_key: Any | None = ..., **params): ... - def close_dispute(self, idempotency_key: Any | None = ..., **params): ... - def mark_as_fraudulent(self, idempotency_key: Any | None = ...): ... - def mark_as_safe(self, idempotency_key: Any | None = ...): ... diff --git a/stubs/stripe/stripe/api_resources/checkout/__init__.pyi b/stubs/stripe/stripe/api_resources/checkout/__init__.pyi deleted file mode 100644 index acbde55c0c1e..000000000000 --- a/stubs/stripe/stripe/api_resources/checkout/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from stripe.api_resources.checkout.session import Session as Session diff --git a/stubs/stripe/stripe/api_resources/checkout/session.pyi b/stubs/stripe/stripe/api_resources/checkout/session.pyi deleted file mode 100644 index 9e165da4c10f..000000000000 --- a/stubs/stripe/stripe/api_resources/checkout/session.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - nested_resource_class_methods as nested_resource_class_methods, -) - -class Session(CreateableAPIResource, ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/country_spec.pyi b/stubs/stripe/stripe/api_resources/country_spec.pyi deleted file mode 100644 index 45613f088bb5..000000000000 --- a/stubs/stripe/stripe/api_resources/country_spec.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class CountrySpec(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/coupon.pyi b/stubs/stripe/stripe/api_resources/coupon.pyi deleted file mode 100644 index d00e8f1c5ab2..000000000000 --- a/stubs/stripe/stripe/api_resources/coupon.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Coupon(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/credit_note.pyi b/stubs/stripe/stripe/api_resources/credit_note.pyi deleted file mode 100644 index 06c0d944eb47..000000000000 --- a/stubs/stripe/stripe/api_resources/credit_note.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class CreditNote(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def void_credit_note(self, idempotency_key: Any | None = ..., **params): ... - @classmethod - def preview(cls, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/credit_note_line_item.pyi b/stubs/stripe/stripe/api_resources/credit_note_line_item.pyi deleted file mode 100644 index 276818b9ee3b..000000000000 --- a/stubs/stripe/stripe/api_resources/credit_note_line_item.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class CreditNoteLineItem(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/customer.pyi b/stubs/stripe/stripe/api_resources/customer.pyi deleted file mode 100644 index 4010c7a5c2be..000000000000 --- a/stubs/stripe/stripe/api_resources/customer.pyi +++ /dev/null @@ -1,53 +0,0 @@ -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, - nested_resource_class_methods as nested_resource_class_methods, -) - -class Customer(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def delete_discount(self, **params) -> None: ... - @classmethod - def balance_transactions_url(cls, id, nested_id=...): ... - @classmethod - def balance_transactions_request( - cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params - ): ... - @classmethod - def create_balance_transaction(cls, id, **params): ... - @classmethod - def retrieve_balance_transaction(cls, id, nested_id, **params): ... - @classmethod - def modify_balance_transaction(cls, id, nested_id, **params): ... - @classmethod - def list_balance_transactions(cls, id, **params): ... - @classmethod - def sources_url(cls, id, nested_id=...): ... - @classmethod - def sources_request(cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params): ... - @classmethod - def create_source(cls, id, **params): ... - @classmethod - def retrieve_source(cls, id, nested_id, **params): ... - @classmethod - def modify_source(cls, id, nested_id, **params): ... - @classmethod - def delete_source(cls, id, nested_id, **params): ... - @classmethod - def list_sources(cls, id, **params): ... - @classmethod - def tax_ids_url(cls, id, nested_id=...): ... - @classmethod - def tax_ids_request(cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params): ... - @classmethod - def create_tax_id(cls, id, **params): ... - @classmethod - def retrieve_tax_id(cls, id, nested_id, **params): ... - @classmethod - def delete_tax_id(cls, id, nested_id, **params): ... - @classmethod - def list_tax_ids(cls, id, **params): ... diff --git a/stubs/stripe/stripe/api_resources/customer_balance_transaction.pyi b/stubs/stripe/stripe/api_resources/customer_balance_transaction.pyi deleted file mode 100644 index 32654b300bfd..000000000000 --- a/stubs/stripe/stripe/api_resources/customer_balance_transaction.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import APIResource as APIResource -from stripe.api_resources.customer import Customer as Customer - -class CustomerBalanceTransaction(APIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/dispute.pyi b/stubs/stripe/stripe/api_resources/dispute.pyi deleted file mode 100644 index 6cf76052c3b5..000000000000 --- a/stubs/stripe/stripe/api_resources/dispute.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Dispute(ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def close(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/ephemeral_key.pyi b/stubs/stripe/stripe/api_resources/ephemeral_key.pyi deleted file mode 100644 index e2059eac7b49..000000000000 --- a/stubs/stripe/stripe/api_resources/ephemeral_key.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import DeletableAPIResource as DeletableAPIResource - -class EphemeralKey(DeletableAPIResource): - OBJECT_NAME: str - @classmethod - def create( - cls, - api_key: Any | None = ..., - idempotency_key: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - **params, - ): ... diff --git a/stubs/stripe/stripe/api_resources/error_object.pyi b/stubs/stripe/stripe/api_resources/error_object.pyi deleted file mode 100644 index cf13a84100cf..000000000000 --- a/stubs/stripe/stripe/api_resources/error_object.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Any - -from stripe.stripe_object import StripeObject as StripeObject - -class ErrorObject(StripeObject): - def refresh_from( - self, - values, - api_key: Any | None = ..., - partial: bool = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - last_response: Any | None = ..., - ): ... - -class OAuthErrorObject(StripeObject): - def refresh_from( - self, - values, - api_key: Any | None = ..., - partial: bool = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - last_response: Any | None = ..., - ): ... diff --git a/stubs/stripe/stripe/api_resources/event.pyi b/stubs/stripe/stripe/api_resources/event.pyi deleted file mode 100644 index 32ec04d396eb..000000000000 --- a/stubs/stripe/stripe/api_resources/event.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class Event(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/exchange_rate.pyi b/stubs/stripe/stripe/api_resources/exchange_rate.pyi deleted file mode 100644 index c6ae5b9e3f8a..000000000000 --- a/stubs/stripe/stripe/api_resources/exchange_rate.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class ExchangeRate(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/file.pyi b/stubs/stripe/stripe/api_resources/file.pyi deleted file mode 100644 index d92200fa73bb..000000000000 --- a/stubs/stripe/stripe/api_resources/file.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class File(ListableAPIResource): - OBJECT_NAME: str - OBJECT_NAME_ALT: str - @classmethod - def class_url(cls): ... - @classmethod - def create( - cls, - api_key: Any | None = ..., - api_version: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - **params, - ): ... - -FileUpload = File diff --git a/stubs/stripe/stripe/api_resources/file_link.pyi b/stubs/stripe/stripe/api_resources/file_link.pyi deleted file mode 100644 index af55248f9291..000000000000 --- a/stubs/stripe/stripe/api_resources/file_link.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class FileLink(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/identity/__init__.pyi b/stubs/stripe/stripe/api_resources/identity/__init__.pyi deleted file mode 100644 index 6285d40f1530..000000000000 --- a/stubs/stripe/stripe/api_resources/identity/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from stripe.api_resources.identity.verification_report import VerificationReport as VerificationReport -from stripe.api_resources.identity.verification_session import VerificationSession as VerificationSession diff --git a/stubs/stripe/stripe/api_resources/identity/verification_report.pyi b/stubs/stripe/stripe/api_resources/identity/verification_report.pyi deleted file mode 100644 index 873d0d57ed6f..000000000000 --- a/stubs/stripe/stripe/api_resources/identity/verification_report.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class VerificationReport(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/identity/verification_session.pyi b/stubs/stripe/stripe/api_resources/identity/verification_session.pyi deleted file mode 100644 index 1ae41f56081a..000000000000 --- a/stubs/stripe/stripe/api_resources/identity/verification_session.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class VerificationSession(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... - def redact(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/invoice.pyi b/stubs/stripe/stripe/api_resources/invoice.pyi deleted file mode 100644 index 625604ba4563..000000000000 --- a/stubs/stripe/stripe/api_resources/invoice.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Invoice(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def finalize_invoice(self, idempotency_key: Any | None = ..., **params): ... - def mark_uncollectible(self, idempotency_key: Any | None = ..., **params): ... - def pay(self, idempotency_key: Any | None = ..., **params): ... - def send_invoice(self, idempotency_key: Any | None = ..., **params): ... - def void_invoice(self, idempotency_key: Any | None = ..., **params): ... - @classmethod - def upcoming( - cls, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ): ... diff --git a/stubs/stripe/stripe/api_resources/invoice_item.pyi b/stubs/stripe/stripe/api_resources/invoice_item.pyi deleted file mode 100644 index cd5eee9bf325..000000000000 --- a/stubs/stripe/stripe/api_resources/invoice_item.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class InvoiceItem(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/invoice_line_item.pyi b/stubs/stripe/stripe/api_resources/invoice_line_item.pyi deleted file mode 100644 index 4d33401eebeb..000000000000 --- a/stubs/stripe/stripe/api_resources/invoice_line_item.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class InvoiceLineItem(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/issuer_fraud_record.pyi b/stubs/stripe/stripe/api_resources/issuer_fraud_record.pyi deleted file mode 100644 index 25d5e80f85ae..000000000000 --- a/stubs/stripe/stripe/api_resources/issuer_fraud_record.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class IssuerFraudRecord(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/issuing/__init__.pyi b/stubs/stripe/stripe/api_resources/issuing/__init__.pyi deleted file mode 100644 index 51cba72251f2..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/__init__.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from stripe.api_resources.issuing.authorization import Authorization as Authorization -from stripe.api_resources.issuing.card import Card as Card -from stripe.api_resources.issuing.card_details import CardDetails as CardDetails -from stripe.api_resources.issuing.cardholder import Cardholder as Cardholder -from stripe.api_resources.issuing.dispute import Dispute as Dispute -from stripe.api_resources.issuing.transaction import Transaction as Transaction diff --git a/stubs/stripe/stripe/api_resources/issuing/authorization.pyi b/stubs/stripe/stripe/api_resources/issuing/authorization.pyi deleted file mode 100644 index 82058b9144d8..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/authorization.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Authorization(ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def approve(self, idempotency_key: Any | None = ..., **params): ... - def decline(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/issuing/card.pyi b/stubs/stripe/stripe/api_resources/issuing/card.pyi deleted file mode 100644 index d5bb8c227bbf..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/card.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Card(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def details(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/issuing/card_details.pyi b/stubs/stripe/stripe/api_resources/issuing/card_details.pyi deleted file mode 100644 index 9d963f88681e..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/card_details.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class CardDetails(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/issuing/cardholder.pyi b/stubs/stripe/stripe/api_resources/issuing/cardholder.pyi deleted file mode 100644 index c08889ad08dc..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/cardholder.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Cardholder(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/issuing/dispute.pyi b/stubs/stripe/stripe/api_resources/issuing/dispute.pyi deleted file mode 100644 index cfec61ff1740..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/dispute.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Dispute(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def submit(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/issuing/transaction.pyi b/stubs/stripe/stripe/api_resources/issuing/transaction.pyi deleted file mode 100644 index 66ea728df446..000000000000 --- a/stubs/stripe/stripe/api_resources/issuing/transaction.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from stripe.api_resources.abstract import ( - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Transaction(ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/line_item.pyi b/stubs/stripe/stripe/api_resources/line_item.pyi deleted file mode 100644 index 77317c4e2be6..000000000000 --- a/stubs/stripe/stripe/api_resources/line_item.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import APIResource as APIResource - -class LineItem(APIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/list_object.pyi b/stubs/stripe/stripe/api_resources/list_object.pyi deleted file mode 100644 index bce7cd603435..000000000000 --- a/stubs/stripe/stripe/api_resources/list_object.pyi +++ /dev/null @@ -1,35 +0,0 @@ -from collections.abc import Generator -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.stripe_object import StripeObject as StripeObject - -class ListObject(StripeObject): - OBJECT_NAME: str - def list(self, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params): ... - def create( - self, - api_key: Any | None = ..., - idempotency_key: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - **params, - ): ... - def retrieve( - self, id, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ): ... - def __getitem__(self, k): ... - def __iter__(self): ... - def __len__(self): ... - def __reversed__(self): ... - def auto_paging_iter(self) -> Generator[Any, None, None]: ... - @classmethod - def empty_list(cls, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ...): ... - @property - def is_empty(self): ... - def next_page( - self, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ): ... - def previous_page( - self, api_key: Any | None = ..., stripe_version: Any | None = ..., stripe_account: Any | None = ..., **params - ): ... diff --git a/stubs/stripe/stripe/api_resources/login_link.pyi b/stubs/stripe/stripe/api_resources/login_link.pyi deleted file mode 100644 index 9333af640ace..000000000000 --- a/stubs/stripe/stripe/api_resources/login_link.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class LoginLink(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/mandate.pyi b/stubs/stripe/stripe/api_resources/mandate.pyi deleted file mode 100644 index eb16554db959..000000000000 --- a/stubs/stripe/stripe/api_resources/mandate.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import APIResource as APIResource - -class Mandate(APIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/order.pyi b/stubs/stripe/stripe/api_resources/order.pyi deleted file mode 100644 index 14d57647f95d..000000000000 --- a/stubs/stripe/stripe/api_resources/order.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Order(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def pay(self, idempotency_key: Any | None = ..., **params): ... - def return_order(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/order_return.pyi b/stubs/stripe/stripe/api_resources/order_return.pyi deleted file mode 100644 index a5515fe3dd81..000000000000 --- a/stubs/stripe/stripe/api_resources/order_return.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class OrderReturn(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/payment_intent.pyi b/stubs/stripe/stripe/api_resources/payment_intent.pyi deleted file mode 100644 index c5761ca208d0..000000000000 --- a/stubs/stripe/stripe/api_resources/payment_intent.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class PaymentIntent(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... - def capture(self, idempotency_key: Any | None = ..., **params): ... - def confirm(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/payment_method.pyi b/stubs/stripe/stripe/api_resources/payment_method.pyi deleted file mode 100644 index da90f0e959fe..000000000000 --- a/stubs/stripe/stripe/api_resources/payment_method.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class PaymentMethod(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def attach(self, idempotency_key: Any | None = ..., **params): ... - def detach(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/payout.pyi b/stubs/stripe/stripe/api_resources/payout.pyi deleted file mode 100644 index 4d20db18e7da..000000000000 --- a/stubs/stripe/stripe/api_resources/payout.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Payout(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... - def reverse(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/person.pyi b/stubs/stripe/stripe/api_resources/person.pyi deleted file mode 100644 index 8ebef88e9646..000000000000 --- a/stubs/stripe/stripe/api_resources/person.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import UpdateableAPIResource as UpdateableAPIResource -from stripe.api_resources.account import Account as Account - -class Person(UpdateableAPIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def modify(cls, sid, **params) -> None: ... - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/plan.pyi b/stubs/stripe/stripe/api_resources/plan.pyi deleted file mode 100644 index 6f1338074ea5..000000000000 --- a/stubs/stripe/stripe/api_resources/plan.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Plan(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/price.pyi b/stubs/stripe/stripe/api_resources/price.pyi deleted file mode 100644 index 7c1c73688724..000000000000 --- a/stubs/stripe/stripe/api_resources/price.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Price(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/product.pyi b/stubs/stripe/stripe/api_resources/product.pyi deleted file mode 100644 index 8e42ea069d5c..000000000000 --- a/stubs/stripe/stripe/api_resources/product.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Product(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/promotion_code.pyi b/stubs/stripe/stripe/api_resources/promotion_code.pyi deleted file mode 100644 index 0bc9cb5003ab..000000000000 --- a/stubs/stripe/stripe/api_resources/promotion_code.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class PromotionCode(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/quote.pyi b/stubs/stripe/stripe/api_resources/quote.pyi deleted file mode 100644 index 5dd2bb450ae5..000000000000 --- a/stubs/stripe/stripe/api_resources/quote.pyi +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Quote(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def accept(self, idempotency_key: Any | None = ..., **params): ... - def cancel(self, idempotency_key: Any | None = ..., **params): ... - def finalize_quote(self, idempotency_key: Any | None = ..., **params): ... - def list_line_items(self, idempotency_key: Any | None = ..., **params): ... - def pdf( - self, - api_key: Any | None = ..., - api_version: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - **params, - ): ... diff --git a/stubs/stripe/stripe/api_resources/radar/__init__.pyi b/stubs/stripe/stripe/api_resources/radar/__init__.pyi deleted file mode 100644 index a7fe6cd8b6af..000000000000 --- a/stubs/stripe/stripe/api_resources/radar/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from stripe.api_resources.radar.early_fraud_warning import EarlyFraudWarning as EarlyFraudWarning -from stripe.api_resources.radar.value_list import ValueList as ValueList -from stripe.api_resources.radar.value_list_item import ValueListItem as ValueListItem diff --git a/stubs/stripe/stripe/api_resources/radar/early_fraud_warning.pyi b/stubs/stripe/stripe/api_resources/radar/early_fraud_warning.pyi deleted file mode 100644 index e1a2b49a35be..000000000000 --- a/stubs/stripe/stripe/api_resources/radar/early_fraud_warning.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class EarlyFraudWarning(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/radar/value_list.pyi b/stubs/stripe/stripe/api_resources/radar/value_list.pyi deleted file mode 100644 index 956aba4fa655..000000000000 --- a/stubs/stripe/stripe/api_resources/radar/value_list.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class ValueList(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/radar/value_list_item.pyi b/stubs/stripe/stripe/api_resources/radar/value_list_item.pyi deleted file mode 100644 index 5e7deb333a37..000000000000 --- a/stubs/stripe/stripe/api_resources/radar/value_list_item.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, -) - -class ValueListItem(CreateableAPIResource, DeletableAPIResource, ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/recipient.pyi b/stubs/stripe/stripe/api_resources/recipient.pyi deleted file mode 100644 index de8758b74f62..000000000000 --- a/stubs/stripe/stripe/api_resources/recipient.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Recipient(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/recipient_transfer.pyi b/stubs/stripe/stripe/api_resources/recipient_transfer.pyi deleted file mode 100644 index e7ce9880f30a..000000000000 --- a/stubs/stripe/stripe/api_resources/recipient_transfer.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class RecipientTransfer(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/refund.pyi b/stubs/stripe/stripe/api_resources/refund.pyi deleted file mode 100644 index c401c30a825e..000000000000 --- a/stubs/stripe/stripe/api_resources/refund.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Refund(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/reporting/__init__.pyi b/stubs/stripe/stripe/api_resources/reporting/__init__.pyi deleted file mode 100644 index df2b4de93d1b..000000000000 --- a/stubs/stripe/stripe/api_resources/reporting/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from stripe.api_resources.reporting.report_run import ReportRun as ReportRun -from stripe.api_resources.reporting.report_type import ReportType as ReportType diff --git a/stubs/stripe/stripe/api_resources/reporting/report_run.pyi b/stubs/stripe/stripe/api_resources/reporting/report_run.pyi deleted file mode 100644 index 5e1251498321..000000000000 --- a/stubs/stripe/stripe/api_resources/reporting/report_run.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, -) - -class ReportRun(CreateableAPIResource, ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/reporting/report_type.pyi b/stubs/stripe/stripe/api_resources/reporting/report_type.pyi deleted file mode 100644 index aef5fbf851ca..000000000000 --- a/stubs/stripe/stripe/api_resources/reporting/report_type.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class ReportType(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/reversal.pyi b/stubs/stripe/stripe/api_resources/reversal.pyi deleted file mode 100644 index 58bd5fb10f74..000000000000 --- a/stubs/stripe/stripe/api_resources/reversal.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import UpdateableAPIResource as UpdateableAPIResource -from stripe.api_resources.transfer import Transfer as Transfer - -class Reversal(UpdateableAPIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def modify(cls, sid, **params) -> None: ... - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/review.pyi b/stubs/stripe/stripe/api_resources/review.pyi deleted file mode 100644 index 943b3c88afd2..000000000000 --- a/stubs/stripe/stripe/api_resources/review.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource, custom_method as custom_method - -class Review(ListableAPIResource): - OBJECT_NAME: str - def approve(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/setup_attempt.pyi b/stubs/stripe/stripe/api_resources/setup_attempt.pyi deleted file mode 100644 index aa89f2eedb32..000000000000 --- a/stubs/stripe/stripe/api_resources/setup_attempt.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class SetupAttempt(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/setup_intent.pyi b/stubs/stripe/stripe/api_resources/setup_intent.pyi deleted file mode 100644 index b9763132bec1..000000000000 --- a/stubs/stripe/stripe/api_resources/setup_intent.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class SetupIntent(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... - def confirm(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/sigma/__init__.pyi b/stubs/stripe/stripe/api_resources/sigma/__init__.pyi deleted file mode 100644 index 0b669a58d520..000000000000 --- a/stubs/stripe/stripe/api_resources/sigma/__init__.pyi +++ /dev/null @@ -1 +0,0 @@ -from stripe.api_resources.sigma.scheduled_query_run import ScheduledQueryRun as ScheduledQueryRun diff --git a/stubs/stripe/stripe/api_resources/sigma/scheduled_query_run.pyi b/stubs/stripe/stripe/api_resources/sigma/scheduled_query_run.pyi deleted file mode 100644 index 5445216f1a16..000000000000 --- a/stubs/stripe/stripe/api_resources/sigma/scheduled_query_run.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class ScheduledQueryRun(ListableAPIResource): - OBJECT_NAME: str - @classmethod - def class_url(cls): ... diff --git a/stubs/stripe/stripe/api_resources/sku.pyi b/stubs/stripe/stripe/api_resources/sku.pyi deleted file mode 100644 index 2b7b548ffc11..000000000000 --- a/stubs/stripe/stripe/api_resources/sku.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class SKU(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/source.pyi b/stubs/stripe/stripe/api_resources/source.pyi deleted file mode 100644 index 24424657713a..000000000000 --- a/stubs/stripe/stripe/api_resources/source.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from stripe import error as error -from stripe.api_resources import Customer as Customer -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - VerifyMixin as VerifyMixin, - nested_resource_class_methods as nested_resource_class_methods, -) - -class Source(CreateableAPIResource, UpdateableAPIResource, VerifyMixin): - OBJECT_NAME: str - def detach(self, idempotency_key: Any | None = ..., **params): ... - def source_transactions(self, **params): ... diff --git a/stubs/stripe/stripe/api_resources/source_transaction.pyi b/stubs/stripe/stripe/api_resources/source_transaction.pyi deleted file mode 100644 index 48570cbfb332..000000000000 --- a/stubs/stripe/stripe/api_resources/source_transaction.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class SourceTransaction(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/subscription.pyi b/stubs/stripe/stripe/api_resources/subscription.pyi deleted file mode 100644 index ddd2ce49b9f4..000000000000 --- a/stubs/stripe/stripe/api_resources/subscription.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Subscription(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def delete_discount(self, **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/subscription_item.pyi b/stubs/stripe/stripe/api_resources/subscription_item.pyi deleted file mode 100644 index df891e925e34..000000000000 --- a/stubs/stripe/stripe/api_resources/subscription_item.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - nested_resource_class_methods as nested_resource_class_methods, -) - -class SubscriptionItem(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def usage_record_summaries(self, **params): ... - @classmethod - def usage_records_url(cls, id, nested_id=...): ... - @classmethod - def usage_records_request( - cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params - ): ... - @classmethod - def create_usage_record(cls, id, **params): ... - @classmethod - def usage_record_summarys_url(cls, id, nested_id=...): ... - @classmethod - def usage_record_summarys_request( - cls, method, url, api_key=..., idempotency_key=..., stripe_version=..., stripe_account=..., **params - ): ... - @classmethod - def list_usage_record_summaries(cls, id, **params): ... diff --git a/stubs/stripe/stripe/api_resources/subscription_schedule.pyi b/stubs/stripe/stripe/api_resources/subscription_schedule.pyi deleted file mode 100644 index 06998029de64..000000000000 --- a/stubs/stripe/stripe/api_resources/subscription_schedule.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class SubscriptionSchedule(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... - def release(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/tax_code.pyi b/stubs/stripe/stripe/api_resources/tax_code.pyi deleted file mode 100644 index ed37e5671055..000000000000 --- a/stubs/stripe/stripe/api_resources/tax_code.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import ListableAPIResource as ListableAPIResource - -class TaxCode(ListableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/tax_id.pyi b/stubs/stripe/stripe/api_resources/tax_id.pyi deleted file mode 100644 index 25d6fa1edf97..000000000000 --- a/stubs/stripe/stripe/api_resources/tax_id.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import APIResource as APIResource -from stripe.api_resources.customer import Customer as Customer - -class TaxId(APIResource): - OBJECT_NAME: str - def instance_url(self): ... - @classmethod - def retrieve(cls, id, api_key: Any | None = ..., **params) -> None: ... diff --git a/stubs/stripe/stripe/api_resources/tax_rate.pyi b/stubs/stripe/stripe/api_resources/tax_rate.pyi deleted file mode 100644 index 41cad550ad15..000000000000 --- a/stubs/stripe/stripe/api_resources/tax_rate.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class TaxRate(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/terminal/__init__.pyi b/stubs/stripe/stripe/api_resources/terminal/__init__.pyi deleted file mode 100644 index 27b995d4a739..000000000000 --- a/stubs/stripe/stripe/api_resources/terminal/__init__.pyi +++ /dev/null @@ -1,3 +0,0 @@ -from stripe.api_resources.terminal.connection_token import ConnectionToken as ConnectionToken -from stripe.api_resources.terminal.location import Location as Location -from stripe.api_resources.terminal.reader import Reader as Reader diff --git a/stubs/stripe/stripe/api_resources/terminal/connection_token.pyi b/stubs/stripe/stripe/api_resources/terminal/connection_token.pyi deleted file mode 100644 index 2d0dc48df420..000000000000 --- a/stubs/stripe/stripe/api_resources/terminal/connection_token.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import CreateableAPIResource as CreateableAPIResource - -class ConnectionToken(CreateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/terminal/location.pyi b/stubs/stripe/stripe/api_resources/terminal/location.pyi deleted file mode 100644 index 1bb0ee003d67..000000000000 --- a/stubs/stripe/stripe/api_resources/terminal/location.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Location(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/terminal/reader.pyi b/stubs/stripe/stripe/api_resources/terminal/reader.pyi deleted file mode 100644 index d8333b91c85e..000000000000 --- a/stubs/stripe/stripe/api_resources/terminal/reader.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class Reader(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/three_d_secure.pyi b/stubs/stripe/stripe/api_resources/three_d_secure.pyi deleted file mode 100644 index 4ab7469a779b..000000000000 --- a/stubs/stripe/stripe/api_resources/three_d_secure.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from stripe.api_resources.abstract import CreateableAPIResource as CreateableAPIResource - -class ThreeDSecure(CreateableAPIResource): - OBJECT_NAME: str - @classmethod - def class_url(cls): ... diff --git a/stubs/stripe/stripe/api_resources/token.pyi b/stubs/stripe/stripe/api_resources/token.pyi deleted file mode 100644 index 307de97b6d8f..000000000000 --- a/stubs/stripe/stripe/api_resources/token.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.api_resources.abstract import CreateableAPIResource as CreateableAPIResource - -class Token(CreateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/topup.pyi b/stubs/stripe/stripe/api_resources/topup.pyi deleted file mode 100644 index ff0f1d35bbb7..000000000000 --- a/stubs/stripe/stripe/api_resources/topup.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, -) - -class Topup(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/transfer.pyi b/stubs/stripe/stripe/api_resources/transfer.pyi deleted file mode 100644 index 16774b6315ba..000000000000 --- a/stubs/stripe/stripe/api_resources/transfer.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, - custom_method as custom_method, - nested_resource_class_methods as nested_resource_class_methods, -) - -class Transfer(CreateableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str - def cancel(self, idempotency_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/api_resources/usage_record.pyi b/stubs/stripe/stripe/api_resources/usage_record.pyi deleted file mode 100644 index bdd663bfa445..000000000000 --- a/stubs/stripe/stripe/api_resources/usage_record.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor -from stripe.api_resources.abstract.api_resource import APIResource as APIResource - -class UsageRecord(APIResource): - OBJECT_NAME: str - @classmethod - def create( - cls, - api_key: Any | None = ..., - idempotency_key: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - **params, - ): ... diff --git a/stubs/stripe/stripe/api_resources/usage_record_summary.pyi b/stubs/stripe/stripe/api_resources/usage_record_summary.pyi deleted file mode 100644 index 1af44a751605..000000000000 --- a/stubs/stripe/stripe/api_resources/usage_record_summary.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from stripe.stripe_object import StripeObject as StripeObject - -class UsageRecordSummary(StripeObject): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/api_resources/webhook_endpoint.pyi b/stubs/stripe/stripe/api_resources/webhook_endpoint.pyi deleted file mode 100644 index 508f943c4b6c..000000000000 --- a/stubs/stripe/stripe/api_resources/webhook_endpoint.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from stripe.api_resources.abstract import ( - CreateableAPIResource as CreateableAPIResource, - DeletableAPIResource as DeletableAPIResource, - ListableAPIResource as ListableAPIResource, - UpdateableAPIResource as UpdateableAPIResource, -) - -class WebhookEndpoint(CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME: str diff --git a/stubs/stripe/stripe/error.pyi b/stubs/stripe/stripe/error.pyi deleted file mode 100644 index fcda1ba3e10a..000000000000 --- a/stubs/stripe/stripe/error.pyi +++ /dev/null @@ -1,75 +0,0 @@ -from typing import Any - -class StripeError(Exception): - http_body: Any - http_status: Any - json_body: Any - headers: Any - code: Any - request_id: Any - error: Any - def __init__( - self, - message: Any | None = ..., - http_body: Any | None = ..., - http_status: Any | None = ..., - json_body: Any | None = ..., - headers: Any | None = ..., - code: Any | None = ..., - ) -> None: ... - @property - def user_message(self): ... - def construct_error_object(self): ... - -class APIError(StripeError): ... - -class APIConnectionError(StripeError): - should_retry: Any - def __init__( - self, - message, - http_body: Any | None = ..., - http_status: Any | None = ..., - json_body: Any | None = ..., - headers: Any | None = ..., - code: Any | None = ..., - should_retry: bool = ..., - ) -> None: ... - -class StripeErrorWithParamCode(StripeError): ... - -class CardError(StripeErrorWithParamCode): - param: Any - def __init__( - self, - message, - param, - code, - http_body: Any | None = ..., - http_status: Any | None = ..., - json_body: Any | None = ..., - headers: Any | None = ..., - ) -> None: ... - -class IdempotencyError(StripeError): ... - -class InvalidRequestError(StripeErrorWithParamCode): - param: Any - def __init__( - self, - message, - param, - code: Any | None = ..., - http_body: Any | None = ..., - http_status: Any | None = ..., - json_body: Any | None = ..., - headers: Any | None = ..., - ) -> None: ... - -class AuthenticationError(StripeError): ... -class PermissionError(StripeError): ... -class RateLimitError(StripeError): ... - -class SignatureVerificationError(StripeError): - sig_header: Any - def __init__(self, message, sig_header, http_body: Any | None = ...) -> None: ... diff --git a/stubs/stripe/stripe/http_client.pyi b/stubs/stripe/stripe/http_client.pyi deleted file mode 100644 index cc65f9c6adcf..000000000000 --- a/stubs/stripe/stripe/http_client.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any - -from stripe import error as error -from stripe.request_metrics import RequestMetrics as RequestMetrics - -version: Any -major: Any -minor: Any -patch: Any - -def new_default_http_client(*args, **kwargs): ... - -class HTTPClient: - MAX_DELAY: int - INITIAL_DELAY: float - MAX_RETRY_AFTER: int - def __init__(self, verify_ssl_certs: bool = ..., proxy: Any | None = ...) -> None: ... - def request_with_retries(self, method, url, headers, post_data: Any | None = ...): ... - def request_stream_with_retries(self, method, url, headers, post_data: Any | None = ...): ... - def request(self, method, url, headers, post_data: Any | None = ...) -> None: ... - def request_stream(self, method, url, headers, post_data: Any | None = ...) -> None: ... - def close(self) -> None: ... - -class RequestsClient(HTTPClient): - name: str - def __init__(self, timeout: int = ..., session: Any | None = ..., **kwargs) -> None: ... - def request(self, method, url, headers, post_data: Any | None = ...): ... - def request_stream(self, method, url, headers, post_data: Any | None = ...): ... - def close(self) -> None: ... - -class UrlFetchClient(HTTPClient): - name: str - def __init__(self, verify_ssl_certs: bool = ..., proxy: Any | None = ..., deadline: int = ...) -> None: ... - def request(self, method, url, headers, post_data: Any | None = ...): ... - def request_stream(self, method, url, headers, post_data: Any | None = ...): ... - def close(self) -> None: ... - -class PycurlClient(HTTPClient): - name: str - def __init__(self, verify_ssl_certs: bool = ..., proxy: Any | None = ...) -> None: ... - def parse_headers(self, data): ... - def request(self, method, url, headers, post_data: Any | None = ...): ... - def request_stream(self, method, url, headers, post_data: Any | None = ...): ... - def close(self) -> None: ... - -class Urllib2Client(HTTPClient): - name: str - def __init__(self, verify_ssl_certs: bool = ..., proxy: Any | None = ...) -> None: ... - def request(self, method, url, headers, post_data: Any | None = ...): ... - def request_stream(self, method, url, headers, post_data: Any | None = ...): ... - def close(self) -> None: ... diff --git a/stubs/stripe/stripe/multipart_data_generator.pyi b/stubs/stripe/stripe/multipart_data_generator.pyi deleted file mode 100644 index 7867aa9f238d..000000000000 --- a/stubs/stripe/stripe/multipart_data_generator.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -class MultipartDataGenerator: - data: Any - line_break: str - boundary: Any - chunk_size: Any - def __init__(self, chunk_size: int = ...) -> None: ... - def add_params(self, params) -> None: ... - def param_header(self): ... - def get_post_data(self): ... diff --git a/stubs/stripe/stripe/oauth.pyi b/stubs/stripe/stripe/oauth.pyi deleted file mode 100644 index 979652c026e7..000000000000 --- a/stubs/stripe/stripe/oauth.pyi +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Any - -from stripe import api_requestor as api_requestor, connect_api_base as connect_api_base, error as error - -class OAuth: - @staticmethod - def authorize_url(express: bool = ..., **params): ... - @staticmethod - def token(api_key: Any | None = ..., **params): ... - @staticmethod - def deauthorize(api_key: Any | None = ..., **params): ... diff --git a/stubs/stripe/stripe/oauth_error.pyi b/stubs/stripe/stripe/oauth_error.pyi deleted file mode 100644 index b963512e7a90..000000000000 --- a/stubs/stripe/stripe/oauth_error.pyi +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any - -from stripe.error import StripeError as StripeError - -class OAuthError(StripeError): - def __init__( - self, - code, - description, - http_body: Any | None = ..., - http_status: Any | None = ..., - json_body: Any | None = ..., - headers: Any | None = ..., - ) -> None: ... - def construct_error_object(self): ... - -class InvalidClientError(OAuthError): ... -class InvalidGrantError(OAuthError): ... -class InvalidRequestError(OAuthError): ... -class InvalidScopeError(OAuthError): ... -class UnsupportedGrantTypeError(OAuthError): ... -class UnsupportedResponseTypeError(OAuthError): ... diff --git a/stubs/stripe/stripe/object_classes.pyi b/stubs/stripe/stripe/object_classes.pyi deleted file mode 100644 index dca9ea4b60c7..000000000000 --- a/stubs/stripe/stripe/object_classes.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any - -from stripe import api_resources as api_resources - -OBJECT_CLASSES: Any diff --git a/stubs/stripe/stripe/request_metrics.pyi b/stubs/stripe/stripe/request_metrics.pyi deleted file mode 100644 index 73952d617895..000000000000 --- a/stubs/stripe/stripe/request_metrics.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any - -class RequestMetrics: - request_id: Any - request_duration_ms: Any - def __init__(self, request_id, request_duration_ms) -> None: ... - def payload(self): ... diff --git a/stubs/stripe/stripe/stripe_object.pyi b/stubs/stripe/stripe/stripe_object.pyi deleted file mode 100644 index 25ed72a9de70..000000000000 --- a/stubs/stripe/stripe/stripe_object.pyi +++ /dev/null @@ -1,54 +0,0 @@ -import json -from typing import Any, Dict - -from stripe import api_requestor as api_requestor - -class StripeObject(Dict[Any, Any]): - class ReprJSONEncoder(json.JSONEncoder): - def default(self, obj): ... - def __init__( - self, - id: Any | None = ..., - api_key: Any | None = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - last_response: Any | None = ..., - **params, - ) -> None: ... - @property - def last_response(self): ... - def update(self, update_dict): ... - def __setattr__(self, k, v): ... - def __getattr__(self, k): ... - def __delattr__(self, k): ... - def __setitem__(self, k, v) -> None: ... - def __getitem__(self, k): ... - def __delitem__(self, k) -> None: ... - def __reduce__(self): ... - @classmethod - def construct_from( - cls, values, key, stripe_version: Any | None = ..., stripe_account: Any | None = ..., last_response: Any | None = ... - ): ... - api_key: Any - stripe_version: Any - stripe_account: Any - def refresh_from( - self, - values, - api_key: Any | None = ..., - partial: bool = ..., - stripe_version: Any | None = ..., - stripe_account: Any | None = ..., - last_response: Any | None = ..., - ) -> None: ... - @classmethod - def api_base(cls) -> None: ... - def request(self, method, url, params: Any | None = ..., headers: Any | None = ...): ... - def request_stream(self, method, url, params: Any | None = ..., headers: Any | None = ...): ... - def to_dict(self): ... - def to_dict_recursive(self): ... - @property - def stripe_id(self): ... - def serialize(self, previous): ... - def __copy__(self): ... - def __deepcopy__(self, memo): ... diff --git a/stubs/stripe/stripe/stripe_response.pyi b/stubs/stripe/stripe/stripe_response.pyi deleted file mode 100644 index 305857037f35..000000000000 --- a/stubs/stripe/stripe/stripe_response.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any - -class StripeResponseBase: - code: Any - headers: Any - def __init__(self, code, headers) -> None: ... - @property - def idempotency_key(self): ... - @property - def request_id(self): ... - -class StripeResponse(StripeResponseBase): - body: Any - data: Any - def __init__(self, body, code, headers) -> None: ... - -class StripeStreamResponse(StripeResponseBase): - io: Any - def __init__(self, io, code, headers) -> None: ... diff --git a/stubs/stripe/stripe/util.pyi b/stubs/stripe/stripe/util.pyi deleted file mode 100644 index e3590f18867a..000000000000 --- a/stubs/stripe/stripe/util.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any, overload - -def utf8(value): ... -def log_debug(message, **params) -> None: ... -def log_info(message, **params) -> None: ... -def dashboard_link(request_id): ... -def logfmt(props): ... - -class class_method_variant: - class_method_name: Any - def __init__(self, class_method_name) -> None: ... - method: Any - def __call__(self, method): ... - def __get__(self, obj, objtype: Any | None = ...): ... - -@overload -def populate_headers(idempotency_key: None) -> None: ... -@overload -def populate_headers(idempotency_key: str) -> dict[str, str]: ... diff --git a/stubs/stripe/stripe/version.pyi b/stubs/stripe/stripe/version.pyi deleted file mode 100644 index 3acee936dc41..000000000000 --- a/stubs/stripe/stripe/version.pyi +++ /dev/null @@ -1 +0,0 @@ -VERSION: str diff --git a/stubs/stripe/stripe/webhook.pyi b/stubs/stripe/stripe/webhook.pyi deleted file mode 100644 index d5eac8dbade7..000000000000 --- a/stubs/stripe/stripe/webhook.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any - -from stripe import error as error - -class Webhook: - DEFAULT_TOLERANCE: int - @staticmethod - def construct_event(payload, sig_header, secret, tolerance=..., api_key: Any | None = ...): ... - -class WebhookSignature: - EXPECTED_SCHEME: str - @classmethod - def verify_header(cls, payload, header, secret, tolerance: Any | None = ...): ... diff --git a/stubs/tabulate/METADATA.toml b/stubs/tabulate/METADATA.toml index 78fa4d13f8bb..7deacccbf1f4 100644 --- a/stubs/tabulate/METADATA.toml +++ b/stubs/tabulate/METADATA.toml @@ -1,2 +1,2 @@ -version = "0.8.*" -python2 = true +version = "0.10.*" +upstream-repository = "https://github.com/astanin/python-tabulate" diff --git a/stubs/tabulate/tabulate.pyi b/stubs/tabulate/tabulate.pyi deleted file mode 100644 index 8b5efde5bf08..000000000000 --- a/stubs/tabulate/tabulate.pyi +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Any, Callable, Container, Iterable, List, Mapping, NamedTuple, Sequence, Union - -LATEX_ESCAPE_RULES: dict[str, str] -MIN_PADDING: int -PRESERVE_WHITESPACE: bool -WIDE_CHARS_MODE: bool -multiline_formats: dict[str, str] -tabulate_formats: list[str] - -class Line(NamedTuple): - begin: str - hline: str - sep: str - end: str - -class DataRow(NamedTuple): - begin: str - sep: str - end: str - -_TableFormatLine = Union[None, Line, Callable[[List[int], List[str]], str]] -_TableFormatRow = Union[None, DataRow, Callable[[List[Any], List[int], List[str]], str]] - -class TableFormat(NamedTuple): - lineabove: _TableFormatLine - linebelowheader: _TableFormatLine - linebetweenrows: _TableFormatLine - linebelow: _TableFormatLine - headerrow: _TableFormatRow - datarow: _TableFormatRow - padding: int - with_header_hide: Container[str] | None - -def simple_separated_format(separator: str) -> TableFormat: ... -def tabulate( - tabular_data: Mapping[str, Iterable[Any]] | Iterable[Iterable[Any]], - headers: str | dict[str, str] | Sequence[str] = ..., - tablefmt: str | TableFormat = ..., - floatfmt: str | Iterable[str] = ..., - numalign: str | None = ..., - stralign: str | None = ..., - missingval: str | Iterable[str] = ..., - showindex: str | bool | Iterable[Any] = ..., - disable_numparse: bool | Iterable[int] = ..., - colalign: Iterable[str | None] | None = ..., -) -> str: ... diff --git a/stubs/tabulate/tabulate/__init__.pyi b/stubs/tabulate/tabulate/__init__.pyi new file mode 100644 index 000000000000..9a312a37db14 --- /dev/null +++ b/stubs/tabulate/tabulate/__init__.pyi @@ -0,0 +1,71 @@ +from collections.abc import Callable, Container, Iterable, Mapping, Sequence +from typing import Any, Final, Literal, NamedTuple, TypeAlias +from typing_extensions import Self + +__all__ = ["tabulate", "tabulate_formats", "simple_separated_format"] + +__version__: Final[str] +# These constants are meant to be configurable +# https://github.com/astanin/python-tabulate#text-formatting +PRESERVE_WHITESPACE: bool +MIN_PADDING: int +# https://github.com/astanin/python-tabulate#wide-fullwidth-cjk-symbols +WIDE_CHARS_MODE: bool +SEPARATING_LINE: str + +class Line(NamedTuple): + begin: str + hline: str + sep: str + end: str + +class DataRow(NamedTuple): + begin: str + sep: str + end: str + +_TableFormatLine: TypeAlias = Line | Callable[[list[int], list[str]], str] | None +_TableFormatRow: TypeAlias = DataRow | Callable[[list[Any], list[int], list[str]], str] | None + +class TableFormat(NamedTuple): + lineabove: _TableFormatLine + linebelowheader: _TableFormatLine + linebetweenrows: _TableFormatLine + linebelow: _TableFormatLine + headerrow: _TableFormatRow + datarow: _TableFormatRow + padding: int + with_header_hide: Container[str] | None + +LATEX_ESCAPE_RULES: Final[dict[str, str]] +tabulate_formats: list[str] +multiline_formats: dict[str, str] + +def simple_separated_format(separator: str) -> TableFormat: ... +def tabulate( + # The key is converted using str(). + tabular_data: Mapping[Any, Iterable[Any]] | Iterable[Iterable[Any]], + headers: str | dict[str, str] | Sequence[str] = (), + tablefmt: str | TableFormat = "simple", + floatfmt: str | Iterable[str] = "g", + intfmt: str | Iterable[str] = "", + numalign: str | None = "default", + stralign: str | None = "default", + missingval: str | Iterable[str] = "", + showindex: str | bool | Iterable[Any] = "default", + disable_numparse: bool | Iterable[int] = False, + colglobalalign: Literal["right", "center", "decimal", "left"] | None = None, + colalign: Iterable[str | None] | None = None, + preserve_whitespace: bool = False, + maxcolwidths: int | Iterable[int | None] | None = None, + headersglobalalign: Literal["right", "center", "left"] | None = None, + headersalign: Iterable[str | None] | None = None, + rowalign: str | Iterable[str] | None = None, + maxheadercolwidths: int | Iterable[int] | None = None, + break_long_words: bool = True, + break_on_hyphens: bool = True, +) -> str: ... + +class JupyterHTMLStr(str): + @property + def str(self) -> Self: ... diff --git a/stubs/tensorflow/@tests/stubtest_allowlist.txt b/stubs/tensorflow/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..92811b4f79b4 --- /dev/null +++ b/stubs/tensorflow/@tests/stubtest_allowlist.txt @@ -0,0 +1,115 @@ +# Some methods are dynamically patched onto to instances as they +# may depend on whether code is executed in graph/eager/v1/v2/etc. +# Tensorflow supports multiple modes of execution which changes some +# of the attributes/methods/even class hierarchies. +tensorflow.Tensor.__int__ +tensorflow.Tensor.numpy +tensorflow.Tensor.__index__ +# Incomplete +tensorflow.sparse.SparseTensor.__getattr__ +tensorflow.SparseTensor.__getattr__ +tensorflow.TensorShape.__getattr__ +tensorflow.dtypes.DType.__getattr__ +tensorflow.RaggedTensor.__getattr__ +tensorflow.DType.__getattr__ +tensorflow.Graph.__getattr__ +tensorflow.Operation.__getattr__ +tensorflow.Variable.__getattr__ +tensorflow.keras.layers.Layer.__getattr__ +tensorflow.python.feature_column.feature_column_v2.SharedEmbeddingColumnCreator.__getattr__ +tensorflow.GradientTape.__getattr__ +tensorflow.data.Dataset.__getattr__ +tensorflow.experimental.Optional.__getattr__ +tensorflow.autodiff.GradientTape.__getattr__ + +# The Tensor methods below were removed in 2.14, however they are still defined for the +# internal subclasses that are used at runtime/in practice. +tensorflow.Tensor.consumers +tensorflow.Tensor.graph +tensorflow.Tensor.op + +# Internal undocumented API +tensorflow.RaggedTensor.__init__ +tensorflow.data.Dataset.__init__ + +# Has an undocumented extra argument that tf.Variable which acts like subclass +# (by dynamically patching tf.Tensor methods) does not preserve. +tensorflow.Tensor.__getitem__ +# stub internal utilities +tensorflow._aliases + +# Tensorflow imports are cursed. +# import tensorflow.initializers +# import tensorflow as tf +# tf.initializers +# Usually these two ways are same module, but for tensorflow the first way +# often does not work and the second way does. The documentation describes +# tf.initializers as module and has that type if accessed the second way, +# but the real module file is completely different name (even package) and dynamically handled. +# tf.initializers at runtime is +tensorflow.initializers +# Other cursed import magic similar to the one above. +tensorflow.distribute.coordinator +tensorflow.distribute.experimental.coordinator + +# __call__ in tensorflow classes often allow keyword usage, but +# when you subclass those classes it is not expected to handle keyword case. As an example, +# class MyLayer(tf.keras.layers.Layer): +# def call(self, x): +# ... +# is common even though Layer.call is defined like def call(self, inputs). Treating inputs as +# a keyword argument would lead to many false positives with typical subclass usage. +# Additional awkwardness for Layer's is call may optionally have training/mask as keyword arguments and some +# layers do while others do not. At runtime call is not intended to be used directly by users, +# but instead through __call__ which extracts out the training/mask arguments. Trying to describe +# this better in stubs would similarly add many false positive Liskov violations. +tensorflow.keras.layers.*.call +tensorflow.keras.regularizers.Regularizer.__call__ +tensorflow.keras.constraints.Constraint.__call__ + +# Layer/Model class does good deal of __new__ magic and actually returns one of two different internal +# types depending on tensorflow execution mode. This feels like implementation internal. +tensorflow.keras.layers.Layer.__new__ + +# build/compute_output_shape are marked positional only in stubs +# as argument name is inconsistent across layer's and looks like +# an implementation detail as documentation never mentions the +# disagreements. +tensorflow.keras.layers.*.build +tensorflow.keras.layers.*.compute_output_shape + +# pb2.pyi generated by mypy-protobuf diverge with runtime in many ways. These stubs +# are mainly tested in mypy-protobuf. +.*_pb2.* + +# Uses namedtuple at runtime, but NamedTuple in stubs and the two disagree about the name of +# __new__ first argument (cls vs cls_). +tensorflow.io.RaggedFeature.__new__ +tensorflow.io.FixedLenSequenceFeature.__new__ +tensorflow.io.FixedLenFeature.__new__ +tensorflow.io.SparseFeature.__new__ + +# Metaclass inconsistency. The runtime metaclass is defined from c++ extension and is undocumented. +tensorflow.io.TFRecordWriter +tensorflow.experimental.dtensor.Mesh + +# stubtest does not pass for protobuf generated stubs. +tensorflow.train.Example.* +tensorflow.train.BytesList.* +tensorflow.train.Feature.* +tensorflow.train.FloatList.* +tensorflow.train.Int64List.* +tensorflow.train.ClusterDef.* +tensorflow.train.ServerDef.* + +# The python module cannot be accessed directly, so to stubtest it appears that it is not present at runtime. +# However it can be accessed by doing: +# from tensorflow import python +# python.X +tensorflow.python.* + +# The modules below are re-exported from tensorflow.python, and they therefore appear missing to stubtest. +tensorflow.distribute.Strategy + +# sigmoid_cross_entropy_with_logits has default values (None), however those values are not valid. +tensorflow.nn.sigmoid_cross_entropy_with_logits diff --git a/stubs/tensorflow/METADATA.toml b/stubs/tensorflow/METADATA.toml new file mode 100644 index 000000000000..7366aee540b5 --- /dev/null +++ b/stubs/tensorflow/METADATA.toml @@ -0,0 +1,16 @@ +# Using an exact number in the specifier for scripts/sync_protobuf/tensorflow.py +# When updating, also re-run the script +version = "~=2.18.0" +upstream-repository = "https://github.com/tensorflow/tensorflow" +# requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20", "types-protobuf", "requests>=2.34.0"] +extra-description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 27.2 on `tensorflow==2.18.0`." +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true +# TODO: Support/update to keras 3.7 +stubtest-dependencies = ["keras==3.6.*"] +# tensorflow 2.19 doesn't support Python 3.13: +# https://github.com/tensorflow/tensorflow/issues/78774 +skip = true diff --git a/stubs/tensorflow/tensorflow/__init__.pyi b/stubs/tensorflow/tensorflow/__init__.pyi new file mode 100644 index 000000000000..2580dec2f797 --- /dev/null +++ b/stubs/tensorflow/tensorflow/__init__.pyi @@ -0,0 +1,523 @@ +import abc +from _typeshed import Incomplete, Unused +from abc import ABC, ABCMeta, abstractmethod +from builtins import bool as _bool, slice as _slice +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import contextmanager +from enum import Enum +from types import TracebackType +from typing import Any, Generic, Literal, ParamSpec, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from google.protobuf.message import Message +from tensorflow import ( + data as data, + debugging as debugging, + experimental as experimental, + feature_column as feature_column, + image as image, + initializers as initializers, + io as io, + keras as keras, + math as math, + nn as nn, + random as random, + types as types, +) +from tensorflow._aliases import ( + AnyArray, + DTypeLike, + IntArray, + IntTensorCompatible, + RaggedTensorLike, + ScalarTensorCompatible, + ShapeLike, + Signature, + Slice, + SparseTensorCompatible, + TensorCompatible, + TensorLike, + UIntTensorCompatible, +) +from tensorflow.autodiff import GradientTape as GradientTape +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.dtypes import * +from tensorflow.experimental.dtensor import Layout +from tensorflow.keras import losses as losses +from tensorflow.linalg import eye as eye, matmul as matmul + +# Most tf.math functions are exported as tf, but sadly not all are. +from tensorflow.math import ( + abs as abs, + add as add, + add_n as add_n, + argmax as argmax, + argmin as argmin, + cos as cos, + cosh as cosh, + divide as divide, + equal as equal, + greater as greater, + greater_equal as greater_equal, + less as less, + less_equal as less_equal, + logical_and as logical_and, + logical_not as logical_not, + logical_or as logical_or, + maximum as maximum, + minimum as minimum, + multiply as multiply, + not_equal as not_equal, + pow as pow, + reduce_max as reduce_max, + reduce_mean as reduce_mean, + reduce_min as reduce_min, + reduce_prod as reduce_prod, + reduce_sum as reduce_sum, + round as round, + sigmoid as sigmoid, + sign as sign, + sin as sin, + sinh as sinh, + sqrt as sqrt, + square as square, + subtract as subtract, + tanh as tanh, +) +from tensorflow.python.trackable.autotrackable import AutoTrackable +from tensorflow.sparse import SparseTensor as SparseTensor + +# Tensors ideally should be a generic type, but properly typing data type/shape +# will be a lot of work. Until we have good non-generic tensorflow stubs, +# we will skip making Tensor generic. Also good type hints for shapes will +# run quickly into many places where type system is not strong enough today. +# So shape typing is probably not worth doing anytime soon. +class Tensor: + def __init__(self, op: Operation, value_index: int, dtype: DType) -> None: ... + def consumers(self) -> list[Incomplete]: ... + @property + def shape(self) -> TensorShape: ... + def get_shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @property + def graph(self) -> Graph: ... + @property + def name(self) -> str: ... + @property + def op(self) -> Operation: ... + def numpy(self) -> AnyArray: ... + def __array__(self, dtype: DTypeLike | None = None) -> AnyArray: ... + def __int__(self) -> int: ... + def __abs__(self, name: str | None = None) -> Tensor: ... + def __add__(self, other: TensorCompatible) -> Tensor: ... + def __radd__(self, other: TensorCompatible) -> Tensor: ... + def __sub__(self, other: TensorCompatible) -> Tensor: ... + def __rsub__(self, other: TensorCompatible) -> Tensor: ... + def __mul__(self, other: TensorCompatible) -> Tensor: ... + def __rmul__(self, other: TensorCompatible) -> Tensor: ... + def __pow__(self, other: TensorCompatible) -> Tensor: ... + def __matmul__(self, other: TensorCompatible) -> Tensor: ... + def __rmatmul__(self, other: TensorCompatible) -> Tensor: ... + def __floordiv__(self, other: TensorCompatible) -> Tensor: ... + def __rfloordiv__(self, other: TensorCompatible) -> Tensor: ... + def __truediv__(self, other: TensorCompatible) -> Tensor: ... + def __rtruediv__(self, other: TensorCompatible) -> Tensor: ... + def __neg__(self, name: str | None = None) -> Tensor: ... + def __and__(self, other: TensorCompatible) -> Tensor: ... + def __rand__(self, other: TensorCompatible) -> Tensor: ... + def __or__(self, other: TensorCompatible) -> Tensor: ... + def __ror__(self, other: TensorCompatible) -> Tensor: ... + def __eq__(self, other: TensorCompatible) -> Tensor: ... # type: ignore[override] + def __ne__(self, other: TensorCompatible) -> Tensor: ... # type: ignore[override] + def __ge__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __gt__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __le__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __lt__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __bool__(self) -> _bool: ... + def __getitem__(self, slice_spec: Slice | tuple[Slice, ...]) -> Tensor: ... + def __len__(self) -> int: ... + # This only works for rank 0 tensors. + def __index__(self) -> int: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class VariableSynchronization(Enum): + AUTO = 0 + NONE = 1 + ON_WRITE = 2 + ON_READ = 3 + +class VariableAggregation(Enum): + NONE = 0 + SUM = 1 + MEAN = 2 + ONLY_FIRST_REPLICA = 3 + +class _VariableMetaclass(type): ... + +# Variable class in intent/documentation is a Tensor. In implementation there's +# TODO: comment to make it Tensor. It is not actually Tensor type wise, but even +# dynamically patches on most methods of tf.Tensor +# https://github.com/tensorflow/tensorflow/blob/9524a636cae9ae3f0554203c1ba7ee29c85fcf12/tensorflow/python/ops/variables.py#L1086. +class Variable(Tensor, metaclass=_VariableMetaclass): + def __init__( + self, + initial_value: Tensor | Callable[[], Tensor] | None = None, + trainable: _bool | None = None, + validate_shape: _bool = True, + # Valid non-None values are deprecated. + caching_device: None = None, + name: str | None = None, + # Real type is VariableDef protobuf type. Can be added after adding script + # to generate tensorflow protobuf stubs with mypy-protobuf. + variable_def=None, + dtype: DTypeLike | None = None, + import_scope: str | None = None, + constraint: Callable[[Tensor], Tensor] | None = None, + synchronization: VariableSynchronization = ..., + aggregation: VariableAggregation = ..., + shape: ShapeLike | None = None, + experimental_enable_variable_lifting: _bool = True, + ) -> None: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class RaggedTensor(metaclass=ABCMeta): + def bounding_shape( + self, axis: TensorCompatible | None = None, name: str | None = None, out_type: DTypeLike | None = None + ) -> Tensor: ... + @classmethod + def from_sparse(cls, st_input: SparseTensor, name: str | None = None, row_splits_dtype: DTypeLike = ...) -> RaggedTensor: ... + def to_sparse(self, name: str | None = None) -> SparseTensor: ... + def to_tensor( + self, default_value: float | str | None = None, name: str | None = None, shape: ShapeLike | None = None + ) -> Tensor: ... + def __add__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __radd__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __sub__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __mul__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __rmul__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __floordiv__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __truediv__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __getitem__(self, slice_spec: Slice | tuple[Slice, ...]) -> RaggedTensor: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class Operation: + def __init__( + self, + node_def, + g: Graph, + # isinstance is used so can not be Sequence/Iterable. + inputs: list[Tensor] | None = None, + output_types: Unused = None, + control_inputs: Iterable[Tensor | Operation] | None = None, + input_types: Iterable[DType] | None = None, + original_op: Operation | None = None, + op_def=None, + ) -> None: ... + @property + def inputs(self) -> list[Tensor]: ... + @property + def outputs(self) -> list[Tensor]: ... + @property + def device(self) -> str: ... + @property + def name(self) -> str: ... + @property + def type(self) -> str: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class TensorShape(metaclass=ABCMeta): + __slots__ = ["_dims"] + def __init__(self, dims: ShapeLike) -> None: ... + @property + def rank(self) -> int: ... + def as_list(self) -> list[int | None]: ... + def assert_has_rank(self, rank: int) -> None: ... + def assert_is_compatible_with(self, other: Iterable[int | None]) -> None: ... + def __bool__(self) -> _bool: ... + + @overload + def __getitem__(self, key: int) -> int | None: ... + @overload + def __getitem__(self, key: _slice) -> TensorShape: ... + + def __iter__(self) -> Iterator[int | None]: ... + def __len__(self) -> int: ... + def __add__(self, other: Iterable[int | None]) -> TensorShape: ... + def __radd__(self, other: Iterable[int | None]) -> TensorShape: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class Graph: + def add_to_collection(self, name: str, value: object) -> None: ... + def add_to_collections(self, names: Iterable[str] | str, value: object) -> None: ... + @contextmanager + def as_default(self) -> Generator[Self]: ... + def finalize(self) -> None: ... + def get_tensor_by_name(self, name: str) -> Tensor: ... + def get_operation_by_name(self, name: str) -> Operation: ... + def get_operations(self) -> list[Operation]: ... + def get_name_scope(self) -> str: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class IndexedSlices(metaclass=ABCMeta): + def __init__(self, values: Tensor, indices: Tensor, dense_shape: Tensor | None = None) -> None: ... + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + @property + def dense_shape(self) -> Tensor | None: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @property + def name(self) -> str: ... + @property + def op(self) -> Operation: ... + @property + def graph(self) -> Graph: ... + @property + def device(self) -> str: ... + def __neg__(self) -> IndexedSlices: ... + def consumers(self) -> list[Operation]: ... + +class name_scope(metaclass=abc.ABCMeta): + def __init__(self, name: str) -> None: ... + def __enter__(self) -> str: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) -> None: ... + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_NameScope: TypeAlias = name_scope + +class Module(AutoTrackable): + def __init__(self, name: str | None = None) -> None: ... + @property + def name(self) -> str: ... + @property + def name_scope(self) -> _NameScope: ... + # Documentation only specifies these as returning Sequence. Actual + # implementation does tuple. + @property + def variables(self) -> Sequence[Variable]: ... + @property + def trainable_variables(self) -> Sequence[Variable]: ... + @property + def non_trainable_variables(self) -> Sequence[Variable]: ... + @property + def submodules(self) -> Sequence[Module]: ... + @classmethod + def with_name_scope(cls, method: Callable[_P, _R]) -> Callable[_P, _R]: ... + +class UnconnectedGradients(Enum): + NONE = "none" + ZERO = "zero" + +_SpecProto = TypeVar("_SpecProto", bound=Message) + +class TypeSpec(ABC, Generic[_SpecProto]): + __slots__ = ["_cached_cmp_key"] + @property + @abstractmethod + def value_type(self) -> Any: ... + def experimental_as_proto(self) -> _SpecProto: ... + @classmethod + def experimental_from_proto(cls, proto: _SpecProto) -> Self: ... + @classmethod + def experimental_type_proto(cls) -> type[_SpecProto]: ... + def is_compatible_with(self, spec_or_value: Self | TensorCompatible | SparseTensor | RaggedTensor) -> _bool: ... + # Incomplete as tf.types is not yet covered. + def is_subtype_of(self, other) -> _bool: ... + def most_specific_common_supertype(self, others: Sequence[Incomplete]) -> Self | None: ... + def most_specific_compatible_type(self, other: Self) -> Self: ... + +class TensorSpec(TypeSpec[struct_pb2.TensorSpecProto]): + __slots__: list[str] = [] + def __init__(self, shape: ShapeLike, dtype: DTypeLike = ..., name: str | None = None) -> None: ... + @property + def value_type(self) -> Tensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @property + def name(self) -> str | None: ... + @classmethod + def from_spec(cls, spec: TypeSpec[Any], name: str | None = None) -> Self: ... + @classmethod + def from_tensor(cls, tensor: Tensor, name: str | None = None) -> Self: ... + def is_compatible_with(self, spec_or_tensor: Self | TensorCompatible) -> _bool: ... # type: ignore[override] + +class SparseTensorSpec(TypeSpec[struct_pb2.TypeSpecProto]): + __slots__ = ["_shape", "_dtype"] + def __init__(self, shape: ShapeLike | None = None, dtype: DTypeLike = ...) -> None: ... + @property + def value_type(self) -> SparseTensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @classmethod + def from_value(cls, value: SparseTensor) -> Self: ... + +class RaggedTensorSpec(TypeSpec[struct_pb2.TypeSpecProto]): + __slots__ = ["_shape", "_dtype", "_ragged_rank", "_row_splits_dtype", "_flat_values_spec"] + def __init__( + self, + shape: ShapeLike | None = None, + dtype: DTypeLike = ..., + ragged_rank: int | None = None, + row_splits_dtype: DTypeLike = ..., + flat_values_spec: TypeSpec[Any] | None = None, + ) -> None: ... + @property + def value_type(self) -> RaggedTensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @classmethod + def from_value(cls, value: RaggedTensor) -> Self: ... + +newaxis: None + +def convert_to_tensor( + value: TensorCompatible | IndexedSlices, + dtype: DTypeLike | None = None, + dtype_hint: DTypeLike | None = None, + name: str | None = None, +) -> Tensor: ... + +@overload +def expand_dims(input: TensorCompatible, axis: int, name: str | None = None) -> Tensor: ... +@overload +def expand_dims(input: RaggedTensor, axis: int, name: str | None = None) -> RaggedTensor: ... + +@overload +def concat(values: TensorCompatible, axis: int, name: str | None = "concat") -> Tensor: ... +@overload +def concat(values: Sequence[RaggedTensor], axis: int, name: str | None = "concat") -> RaggedTensor: ... + +@overload +def squeeze( + input: TensorCompatible, axis: int | tuple[int, ...] | list[int] | None = None, name: str | None = None +) -> Tensor: ... +@overload +def squeeze(input: RaggedTensor, axis: int | tuple[int, ...] | list[int], name: str | None = None) -> RaggedTensor: ... + +def slice(input_: TensorCompatible, begin: IntTensorCompatible, size: IntTensorCompatible, name: str | None = None) -> Tensor: ... +def split( + value: TensorCompatible, + num_or_size_splits: int | TensorCompatible, + axis: int | Tensor = 0, + num: int | None = None, + name: str | None = "split", +) -> list[Tensor]: ... +def stack(values: TensorCompatible, axis: int = 0, name: str | None = "stack") -> Tensor: ... +def tensor_scatter_nd_update( + tensor: TensorCompatible, indices: TensorCompatible, updates: TensorCompatible, name: str | None = None +) -> Tensor: ... +def constant( + value: TensorCompatible, dtype: DTypeLike | None = None, shape: ShapeLike | None = None, name: str | None = "Const" +) -> Tensor: ... + +@overload +def cast(x: TensorCompatible, dtype: DTypeLike, name: str | None = None) -> Tensor: ... +@overload +def cast(x: SparseTensor, dtype: DTypeLike, name: str | None = None) -> SparseTensor: ... +@overload +def cast(x: RaggedTensor, dtype: DTypeLike, name: str | None = None) -> RaggedTensor: ... + +def zeros(shape: ShapeLike, dtype: DTypeLike = ..., name: str | None = None, layout: Layout | None = None) -> Tensor: ... +def ones(shape: ShapeLike, dtype: DTypeLike = ..., name: str | None = None, layout: Layout | None = None) -> Tensor: ... + +@overload +def zeros_like( + input: TensorCompatible | IndexedSlices, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> Tensor: ... +@overload +def zeros_like( + input: RaggedTensor, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> RaggedTensor: ... + +@overload +def ones_like( + input: TensorCompatible, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> Tensor: ... +@overload +def ones_like( + input: RaggedTensor, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> RaggedTensor: ... + +def reshape(tensor: TensorCompatible, shape: ShapeLike | Tensor, name: str | None = None) -> Tensor: ... +def reverse(tensor: TensorCompatible, axis: IntTensorCompatible, name: str | None = None) -> Tensor: ... + +_ElemT = TypeVar("_ElemT", bound=TensorLike) +_RetT = TypeVar("_RetT", bound=TensorLike) + +@overload +def map_fn( + fn: Callable[[_ElemT], _RetT], + elems: _ElemT, + dtype: DTypeLike | None = None, + parallel_iterations: int | None = None, + back_prop: _bool = True, + swap_memory: _bool = False, + infer_shape: _bool = True, + name: str | None = None, + fn_output_signature: Signature | None = None, +) -> _RetT: ... +@overload +def map_fn( + fn: Callable[[Tensor], _RetT], + elems: TensorCompatible, + dtype: DTypeLike | None = None, + parallel_iterations: int | None = None, + back_prop: _bool = True, + swap_memory: _bool = False, + infer_shape: _bool = True, + name: str | None = None, + fn_output_signature: Signature | None = None, +) -> _RetT: ... + +def pad( + tensor: TensorCompatible, + paddings: Tensor | IntArray | Iterable[Iterable[int]], + mode: Literal["CONSTANT", "constant", "REFLECT", "reflect", "SYMMETRIC", "symmetric"] = "CONSTANT", + constant_values: ScalarTensorCompatible = 0, + name: str | None = None, +) -> Tensor: ... +def shape(input: SparseTensorCompatible, out_type: DTypeLike | None = None, name: str | None = None) -> Tensor: ... +def where( + condition: TensorCompatible, x: TensorCompatible | None = None, y: TensorCompatible | None = None, name: str | None = None +) -> Tensor: ... +def gather_nd( + params: TensorCompatible, + indices: UIntTensorCompatible, + batch_dims: UIntTensorCompatible = 0, + name: str | None = None, + bad_indices_policy: Literal["", "DEFAULT", "ERROR", "IGNORE"] = "", +) -> Tensor: ... +def transpose( + a: Tensor, perm: Sequence[int] | IntArray | None = None, conjugate: _bool = False, name: str = "transpose" +) -> Tensor: ... +def clip_by_value( + t: Tensor | IndexedSlices, clip_value_min: TensorCompatible, clip_value_max: TensorCompatible, name: str | None = None +) -> Tensor: ... +def tile(input: RaggedTensorLike, multiples: Tensor | Sequence[int], name: str | None = None) -> Tensor: ... + +@overload +def range( + limit: int | Tensor, /, *, delta: int | Tensor = 1, dtype: DTypeLike | None = None, name: str | None = "range" +) -> Tensor: ... +@overload +def range( + start: int | Tensor = 0, + limit: int | Tensor = 0, + delta: int | Tensor = 1, + dtype: DTypeLike | None = None, + name: str | None = "range", +) -> Tensor: ... + +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/tensorflow/tensorflow/_aliases.pyi b/stubs/tensorflow/tensorflow/_aliases.pyi new file mode 100644 index 000000000000..a3ac8f423437 --- /dev/null +++ b/stubs/tensorflow/tensorflow/_aliases.pyi @@ -0,0 +1,73 @@ +# Commonly used type aliases. +# Everything in this module is private for stubs. There is no runtime equivalent. + +from collections.abc import Iterable, Mapping, Sequence +from typing import Any, Protocol, TypeAlias, TypeVar, type_check_only + +import numpy as np +import numpy.typing as npt +import tensorflow as tf +from tensorflow.dtypes import DType +from tensorflow.keras.layers import InputSpec + +_T = TypeVar("_T") +ContainerGeneric: TypeAlias = Mapping[str, ContainerGeneric[_T]] | Sequence[ContainerGeneric[_T]] | _T + +TensorLike: TypeAlias = tf.Tensor | tf.RaggedTensor | tf.SparseTensor +SparseTensorLike: TypeAlias = tf.Tensor | tf.SparseTensor +RaggedTensorLike: TypeAlias = tf.Tensor | tf.RaggedTensor +# _RaggedTensorLikeT = TypeVar("_RaggedTensorLikeT", tf.Tensor, tf.RaggedTensor) +Gradients: TypeAlias = tf.Tensor | tf.IndexedSlices + +@type_check_only +class KerasSerializable1(Protocol): + def get_config(self) -> dict[str, Any]: ... + +@type_check_only +class KerasSerializable2(Protocol): + __name__: str + +KerasSerializable: TypeAlias = KerasSerializable1 | KerasSerializable2 + +TensorValue: TypeAlias = tf.Tensor # Alias for a 0D Tensor +Integer: TypeAlias = TensorValue | int | IntArray | np.number[Any] # Here IntArray are assumed to be 0D. +Float: TypeAlias = Integer | float | FloatArray +Slice: TypeAlias = tf.Tensor | tf.RaggedTensor | int | slice | None +FloatDataSequence: TypeAlias = Sequence[float] | Sequence[FloatDataSequence] +IntDataSequence: TypeAlias = Sequence[int] | Sequence[IntDataSequence] +StrDataSequence: TypeAlias = Sequence[str] | Sequence[StrDataSequence] +DataSequence: TypeAlias = FloatDataSequence | StrDataSequence | IntDataSequence +ScalarTensorCompatible: TypeAlias = tf.Tensor | str | float | np.ndarray[Any, Any] | np.number[Any] +UIntTensorCompatible: TypeAlias = tf.Tensor | int | UIntArray +IntTensorCompatible: TypeAlias = tf.Tensor | int | IntArray | Sequence[IntTensorCompatible] +FloatTensorCompatible: TypeAlias = tf.Tensor | int | IntArray | float | FloatArray | np.number[Any] +StringTensorCompatible: TypeAlias = tf.Tensor | str | npt.NDArray[np.str_] | Sequence[StringTensorCompatible] + +TensorCompatible: TypeAlias = ScalarTensorCompatible | Sequence[TensorCompatible] +# _TensorCompatibleT = TypeVar("_TensorCompatibleT", bound=TensorCompatible) +# Sparse tensors are very annoying. Some operations work on them, but many do not. +# You will need to manually verify if an operation supports them. SparseTensorCompatible is intended to be a +# broader type than TensorCompatible and not all operations will support broader version. If unsure, +# use TensorCompatible instead. +SparseTensorCompatible: TypeAlias = TensorCompatible | tf.SparseTensor +# TensorFlow tries to convert anything passed as input. Meaning that even if, for example, only a Tensor of int32 +# is allowed, a numpy array of strings that can be converted to int32 will work. Therefore having anything more specific +# then AnyArray might cause false positives, while AnyArray might cause false negatives. +TensorOrArray: TypeAlias = tf.Tensor | AnyArray + +ShapeLike: TypeAlias = tf.TensorShape | Iterable[ScalarTensorCompatible | None] | int | tf.Tensor +DTypeLike: TypeAlias = DType | str | np.dtype[Any] | int +Signature: TypeAlias = DType | tf.RaggedTensorSpec | tf.SparseTensorSpec | Sequence[Signature] + +ContainerTensors: TypeAlias = ContainerGeneric[tf.Tensor] +ContainerTensorsLike: TypeAlias = ContainerGeneric[TensorLike] +ContainerTensorCompatible: TypeAlias = ContainerGeneric[TensorCompatible] +ContainerGradients: TypeAlias = ContainerGeneric[Gradients] +ContainerTensorShape: TypeAlias = ContainerGeneric[tf.TensorShape] +ContainerInputSpec: TypeAlias = ContainerGeneric[InputSpec] + +AnyArray: TypeAlias = npt.NDArray[Any] +FloatArray: TypeAlias = npt.NDArray[np.float16 | np.float32 | np.float64] +UIntArray: TypeAlias = npt.NDArray[np.uint | np.uint8 | np.uint16 | np.uint32 | np.uint64] +SignedIntArray: TypeAlias = npt.NDArray[np.int_ | np.int8 | np.int16 | np.int32 | np.int64] +IntArray: TypeAlias = UIntArray | SignedIntArray diff --git a/stubs/tensorflow/tensorflow/audio.pyi b/stubs/tensorflow/tensorflow/audio.pyi new file mode 100644 index 000000000000..480c72ad2e4c --- /dev/null +++ b/stubs/tensorflow/tensorflow/audio.pyi @@ -0,0 +1,7 @@ +import tensorflow as tf +from tensorflow._aliases import Integer, StringTensorCompatible + +def decode_wav( + contents: StringTensorCompatible, desired_channels: int = -1, desired_samples: int = -1, name: str | None = None +) -> tuple[tf.Tensor, tf.Tensor]: ... +def encode_wav(audio: tf.Tensor, sample_rate: Integer, name: str | None = None) -> tf.Tensor: ... diff --git a/stubs/tensorflow/tensorflow/autodiff.pyi b/stubs/tensorflow/tensorflow/autodiff.pyi new file mode 100644 index 000000000000..23bce8f0254e --- /dev/null +++ b/stubs/tensorflow/tensorflow/autodiff.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete +from builtins import bool as _bool +from collections.abc import Generator, Mapping, Sequence +from contextlib import contextmanager +from types import TracebackType +from typing import overload +from typing_extensions import Self + +import tensorflow as tf +from tensorflow import Tensor, UnconnectedGradients, Variable +from tensorflow._aliases import ContainerGradients, ContainerTensors, ContainerTensorsLike, Gradients, TensorLike + +class ForwardAccumulator: + def __init__(self, primals: Tensor, tangents: Tensor) -> None: ... + def jvp( + self, primals: Tensor, unconnected_gradients: tf.UnconnectedGradients = tf.UnconnectedGradients.NONE # noqa: Y011 + ) -> Tensor | None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) -> None: ... + +class GradientTape: + def __init__(self, persistent: _bool = False, watch_accessed_variables: _bool = True) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) -> None: ... + + # Higher kinded types would be nice here and these overloads are a way to simulate some of them. + @overload + def gradient( + self, + target: ContainerTensors, + sources: TensorLike, + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> Gradients: ... + @overload + def gradient( + self, + target: ContainerTensors, + sources: Sequence[Tensor], + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> list[Gradients]: ... + @overload + def gradient( + self, + target: ContainerTensors, + sources: Mapping[str, Tensor], + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> dict[str, Gradients]: ... + @overload + def gradient( + self, + target: ContainerTensors, + sources: ContainerTensors, + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> ContainerGradients: ... + + @contextmanager + def stop_recording(self) -> Generator[None]: ... + def reset(self) -> None: ... + def watch(self, tensor: ContainerTensorsLike) -> None: ... + def watched_variables(self) -> tuple[Variable, ...]: ... + def __getattr__(self, name: str) -> Incomplete: ... diff --git a/stubs/tensorflow/tensorflow/autograph/__init__.pyi b/stubs/tensorflow/tensorflow/autograph/__init__.pyi new file mode 100644 index 000000000000..32246d94b8aa --- /dev/null +++ b/stubs/tensorflow/tensorflow/autograph/__init__.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +from tensorflow.autograph.experimental import Feature + +_Type = TypeVar("_Type") + +def set_verbosity(level: int, alsologtostdout: bool = False) -> None: ... +def to_code( + entity: Callable[..., Any], + recursive: bool = True, + experimental_optional_features: Feature | tuple[Feature, ...] | None = None, +) -> str: ... +def to_graph( + entity: _Type, recursive: bool = True, experimental_optional_features: Feature | tuple[Feature, ...] | None = None +) -> _Type: ... +def trace(*args: Any) -> None: ... diff --git a/stubs/tensorflow/tensorflow/autograph/experimental.pyi b/stubs/tensorflow/tensorflow/autograph/experimental.pyi new file mode 100644 index 000000000000..559c230db66f --- /dev/null +++ b/stubs/tensorflow/tensorflow/autograph/experimental.pyi @@ -0,0 +1,30 @@ +from collections.abc import Callable, Iterable +from enum import Enum +from typing import ParamSpec, TypeVar, overload + +import tensorflow as tf +from tensorflow._aliases import Integer + +_Param = ParamSpec("_Param") +_RetType = TypeVar("_RetType") + +class Feature(Enum): + ALL = "ALL" + ASSERT_STATEMENTS = "ASSERT_STATEMENTS" + AUTO_CONTROL_DEPS = "AUTO_CONTROL_DEPS" + BUILTIN_FUNCTIONS = "BUILTIN_FUNCTIONS" + EQUALITY_OPERATORS = "EQUALITY_OPERATORS" + LISTS = "LISTS" + NAME_SCOPES = "NAME_SCOPES" + +@overload +def do_not_convert(func: Callable[_Param, _RetType]) -> Callable[_Param, _RetType]: ... +@overload +def do_not_convert(func: None = None) -> Callable[[Callable[_Param, _RetType]], Callable[_Param, _RetType]]: ... + +def set_loop_options( + parallel_iterations: Integer = ..., + swap_memory: bool = ..., + maximum_iterations: Integer = ..., + shape_invariants: Iterable[tuple[tf.Tensor, tf.TensorShape]] = ..., +) -> None: ... diff --git a/stubs/tensorflow/tensorflow/bitwise.pyi b/stubs/tensorflow/tensorflow/bitwise.pyi new file mode 100644 index 000000000000..10671acebe88 --- /dev/null +++ b/stubs/tensorflow/tensorflow/bitwise.pyi @@ -0,0 +1,41 @@ +from typing import Any, TypeAlias, overload + +import numpy as np +import tensorflow as tf +from tensorflow._aliases import FloatArray, IntArray + +# The alias below is not fully accurate, since TensorFlow casts the inputs, they have some additional +# requirements. For example y needs to be castable into x's dtype. Moreover, x and y cannot both be booleans. +# Properly typing the bitwise functions would be overly complicated and unlikely to provide much benefits +# since most people use Tensors, it was therefore not done. +_BitwiseCompatible: TypeAlias = tf.Tensor | int | FloatArray | IntArray | np.number[Any] + +@overload +def bitwise_and(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def bitwise_and(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def bitwise_or(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def bitwise_or(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def bitwise_xor(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def bitwise_xor(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def invert(x: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def invert(x: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def left_shift(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def left_shift(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def right_shift(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def right_shift(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi new file mode 100644 index 000000000000..9057959cc005 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi @@ -0,0 +1,2113 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +This proto file defines messages which represent the HLO module. This is a +full fidelity serialization of the c++ HLO constructs. + +Many of the protos below are simple 1-to-1 serializations of the +corresponding C++ classes, e.g., HloModule, HloComputation, and +HloInstruction. + +FIELD NAMES ARE IMPORTANT + +Unlike most protos, you can't safely change the names of fields, even if you +keep the numeric ids the same. This is because we sometimes serialize these +protos as JSON, which includes the field names in the serialization. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.compiler.xla.xla_data_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _CustomCallSchedule: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CustomCallScheduleEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CustomCallSchedule.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SCHEDULE_NONE: _CustomCallSchedule.ValueType # 0 + SCHEDULE_LATEST: _CustomCallSchedule.ValueType # 1 + SCHEDULE_EARLIEST: _CustomCallSchedule.ValueType # 2 + +class CustomCallSchedule(_CustomCallSchedule, metaclass=_CustomCallScheduleEnumTypeWrapper): ... + +SCHEDULE_NONE: CustomCallSchedule.ValueType # 0 +SCHEDULE_LATEST: CustomCallSchedule.ValueType # 1 +SCHEDULE_EARLIEST: CustomCallSchedule.ValueType # 2 +global___CustomCallSchedule = CustomCallSchedule + +class _CustomCallApiVersion: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CustomCallApiVersionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CustomCallApiVersion.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + API_VERSION_UNSPECIFIED: _CustomCallApiVersion.ValueType # 0 + API_VERSION_ORIGINAL: _CustomCallApiVersion.ValueType # 1 + """The first version of the API, with the following signatures: + + CPU: + void do_custom_call(void* out, const void** in); + + GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len); + """ + API_VERSION_STATUS_RETURNING: _CustomCallApiVersion.ValueType # 2 + """When the ability to return success/failure status was added: + + CPU: + void do_custom_call(void* out, const void** in, + XlaCustomCallStatus* status); + + GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + """ + API_VERSION_STATUS_RETURNING_UNIFIED: _CustomCallApiVersion.ValueType # 3 + """Fixes the API signatures on the CPU side of the version STATUS_RETURNING by + adding the opaque string so that the custom call API is consistent across + CPUs and GPUs. For GPUs, the behaviors invoked by + API_VERSION_STATUS_RETURNING and API_VERSION_STATUS_RETURNING_UNIFIED are + the same. + + CPU: + void do_custom_call(void* out, const void** in, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + + GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + """ + API_VERSION_TYPED_FFI: _CustomCallApiVersion.ValueType # 4 + """Api version implementing XLA runtime custom call calling convention. These + custom calls can be registered as an XLA runtime custom call (1) or as XLA + runtime FFI binding (2). + + This type of custom call uses custom ABI to pass type information along + with custom call arguments. Also it passes buffer arguments together with + data type, sizes and strides. + + Example: (XLA runtime custom call) + + absl::Status DoCustomCall(StridedMemrefView arg, float attr); + + CustomCall::Bind("custom_call") + .Arg() + .Attr("attr") + .To(DoCustomCall); + + (1) xla/runtime/custom_call.h + (2) xla/runtime/ffi/ffi.h + """ + +class CustomCallApiVersion(_CustomCallApiVersion, metaclass=_CustomCallApiVersionEnumTypeWrapper): + """The version of the API used by the custom call function. The signatures for + each version are given below. + TODO(b/189822916): Remove this enum when all clients are migrated to the + status-returning API. + """ + +API_VERSION_UNSPECIFIED: CustomCallApiVersion.ValueType # 0 +API_VERSION_ORIGINAL: CustomCallApiVersion.ValueType # 1 +"""The first version of the API, with the following signatures: + +CPU: + void do_custom_call(void* out, const void** in); + +GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len); +""" +API_VERSION_STATUS_RETURNING: CustomCallApiVersion.ValueType # 2 +"""When the ability to return success/failure status was added: + +CPU: + void do_custom_call(void* out, const void** in, + XlaCustomCallStatus* status); + +GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); +""" +API_VERSION_STATUS_RETURNING_UNIFIED: CustomCallApiVersion.ValueType # 3 +"""Fixes the API signatures on the CPU side of the version STATUS_RETURNING by +adding the opaque string so that the custom call API is consistent across +CPUs and GPUs. For GPUs, the behaviors invoked by +API_VERSION_STATUS_RETURNING and API_VERSION_STATUS_RETURNING_UNIFIED are +the same. + +CPU: + void do_custom_call(void* out, const void** in, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + +GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); +""" +API_VERSION_TYPED_FFI: CustomCallApiVersion.ValueType # 4 +"""Api version implementing XLA runtime custom call calling convention. These +custom calls can be registered as an XLA runtime custom call (1) or as XLA +runtime FFI binding (2). + +This type of custom call uses custom ABI to pass type information along +with custom call arguments. Also it passes buffer arguments together with +data type, sizes and strides. + +Example: (XLA runtime custom call) + + absl::Status DoCustomCall(StridedMemrefView arg, float attr); + + CustomCall::Bind("custom_call") + .Arg() + .Attr("attr") + .To(DoCustomCall); + +(1) xla/runtime/custom_call.h +(2) xla/runtime/ffi/ffi.h +""" +global___CustomCallApiVersion = CustomCallApiVersion + +class _Kind: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _KindEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Kind.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNDEFINED_ALIAS: _Kind.ValueType # 0 + """Define a UNDEFINED_ALIAS equal to zero to get around the default-0 proto3 + behavior and missing has_*() APIs. + """ + MAY_ALIAS: _Kind.ValueType # 1 + """The buffers may or may not alias at runtime.""" + MUST_ALIAS: _Kind.ValueType # 2 + """The buffers must alias at runtime.""" + +class Kind(_Kind, metaclass=_KindEnumTypeWrapper): ... + +UNDEFINED_ALIAS: Kind.ValueType # 0 +"""Define a UNDEFINED_ALIAS equal to zero to get around the default-0 proto3 +behavior and missing has_*() APIs. +""" +MAY_ALIAS: Kind.ValueType # 1 +"""The buffers may or may not alias at runtime.""" +MUST_ALIAS: Kind.ValueType # 2 +"""The buffers must alias at runtime.""" +global___Kind = Kind + +@typing.final +class HloInstructionProto(google.protobuf.message.Message): + """Serialization of HloInstruction. + Next ID: 90 + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class SliceDimensions(google.protobuf.message.Message): + """Describes the [begin, end) index range and stride for slices.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_FIELD_NUMBER: builtins.int + LIMIT_FIELD_NUMBER: builtins.int + STRIDE_FIELD_NUMBER: builtins.int + start: builtins.int + limit: builtins.int + stride: builtins.int + def __init__( + self, *, start: builtins.int | None = ..., limit: builtins.int | None = ..., stride: builtins.int | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["limit", b"limit", "start", b"start", "stride", b"stride"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + OPCODE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + METADATA_FIELD_NUMBER: builtins.int + LITERAL_FIELD_NUMBER: builtins.int + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + FUSION_KIND_FIELD_NUMBER: builtins.int + TUPLE_INDEX_FIELD_NUMBER: builtins.int + DIMENSIONS_FIELD_NUMBER: builtins.int + WINDOW_FIELD_NUMBER: builtins.int + CONVOLUTION_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + FEATURE_GROUP_COUNT_FIELD_NUMBER: builtins.int + BATCH_GROUP_COUNT_FIELD_NUMBER: builtins.int + SLICE_DIMENSIONS_FIELD_NUMBER: builtins.int + EXPONENT_BITS_FIELD_NUMBER: builtins.int + MANTISSA_BITS_FIELD_NUMBER: builtins.int + DYNAMIC_SLICE_SIZES_FIELD_NUMBER: builtins.int + PADDING_CONFIG_FIELD_NUMBER: builtins.int + OUTFEED_CONFIG_FIELD_NUMBER: builtins.int + DISTRIBUTION_FIELD_NUMBER: builtins.int + EPSILON_FIELD_NUMBER: builtins.int + FEATURE_INDEX_FIELD_NUMBER: builtins.int + CHANNEL_ID_FIELD_NUMBER: builtins.int + INFEED_CONFIG_FIELD_NUMBER: builtins.int + CUSTOM_CALL_TARGET_FIELD_NUMBER: builtins.int + OUTFEED_SHAPE_FIELD_NUMBER: builtins.int + DOT_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + FFT_TYPE_FIELD_NUMBER: builtins.int + FFT_LENGTH_FIELD_NUMBER: builtins.int + COMPARISON_DIRECTION_FIELD_NUMBER: builtins.int + GATHER_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + GATHER_SLICE_SIZES_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + OPERAND_IDS_FIELD_NUMBER: builtins.int + CONTROL_PREDECESSOR_IDS_FIELD_NUMBER: builtins.int + CALLED_COMPUTATION_IDS_FIELD_NUMBER: builtins.int + SHARDING_FIELD_NUMBER: builtins.int + BACKEND_CONFIG_FIELD_NUMBER: builtins.int + REPLICA_GROUPS_FIELD_NUMBER: builtins.int + ALL_REDUCE_ID_FIELD_NUMBER: builtins.int + USE_GLOBAL_DEVICE_IDS_FIELD_NUMBER: builtins.int + IS_HOST_TRANSFER_FIELD_NUMBER: builtins.int + IS_STABLE_FIELD_NUMBER: builtins.int + SCATTER_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + PRECISION_CONFIG_FIELD_NUMBER: builtins.int + SOURCE_TARGET_PAIRS_FIELD_NUMBER: builtins.int + DOMAIN_ENTRY_SHARDING_FIELD_NUMBER: builtins.int + DOMAIN_EXIT_SHARDING_FIELD_NUMBER: builtins.int + CONSTRAIN_LAYOUT_FIELD_NUMBER: builtins.int + OPERAND_SHAPES_WITH_LAYOUT_FIELD_NUMBER: builtins.int + TRIANGULAR_SOLVE_OPTIONS_FIELD_NUMBER: builtins.int + CHOLESKY_OPTIONS_FIELD_NUMBER: builtins.int + PARAMETER_REPLICATION_FIELD_NUMBER: builtins.int + CUSTOM_CALL_HAS_SIDE_EFFECT_FIELD_NUMBER: builtins.int + OUTPUT_OPERAND_ALIASING_FIELD_NUMBER: builtins.int + CUSTOM_CALL_SCHEDULE_FIELD_NUMBER: builtins.int + DELTA_FIELD_NUMBER: builtins.int + INDICES_ARE_SORTED_FIELD_NUMBER: builtins.int + FRONTEND_ATTRIBUTES_FIELD_NUMBER: builtins.int + UNIQUE_INDICES_FIELD_NUMBER: builtins.int + RNG_ALGORITHM_FIELD_NUMBER: builtins.int + COMPARISON_TYPE_FIELD_NUMBER: builtins.int + IS_CROSS_PROGRAM_PREFETCH_FIELD_NUMBER: builtins.int + CROSS_PROGRAM_PREFETCH_INDEX_FIELD_NUMBER: builtins.int + PADDING_TYPE_FIELD_NUMBER: builtins.int + CUSTOM_CALL_API_VERSION_FIELD_NUMBER: builtins.int + ASYNC_EXECUTION_THREAD_FIELD_NUMBER: builtins.int + K_FIELD_NUMBER: builtins.int + LARGEST_FIELD_NUMBER: builtins.int + STATISTICS_VIZ_FIELD_NUMBER: builtins.int + DOT_SPARSITY_FIELD_NUMBER: builtins.int + COLLECTIVE_DEVICE_LIST_FIELD_NUMBER: builtins.int + ORIGINAL_VALUE_FIELD_NUMBER: builtins.int + IS_COMPOSITE_FIELD_NUMBER: builtins.int + name: builtins.str + opcode: builtins.str + parameter_number: builtins.int + """Parameter number is only present for kParameter.""" + fusion_kind: builtins.str + """Fusion state, only present for kFusion.""" + tuple_index: builtins.int + """Index for kGetTupleElement.""" + feature_group_count: builtins.int + """The number of feature groups. Used for a convolution. Must be a divisor of + the input feature dimension and output feature dimension. If not specified, + it will use a default value of 1. + """ + batch_group_count: builtins.int + exponent_bits: builtins.int + """The bit sizes for a reduce-precision operation.""" + mantissa_bits: builtins.int + outfeed_config: builtins.bytes + """Outfeed configuration information, only present for kOutfeed.""" + distribution: tensorflow.compiler.xla.xla_data_pb2.RandomDistribution.ValueType + """The distribution requested for random number generation. + Only present for kRng. + """ + epsilon: builtins.float + """A small float number added to the variance to avoid divide-by-zero error. + Only present for kBatchNormTraining, kBatchNormInference, and + kBatchNormGrad. + """ + feature_index: builtins.int + """An integer value representing the index of the feature dimension. + Only present for kBatchNormTraining, kBatchNormInference, and + kBatchNormGrad. + """ + channel_id: builtins.int + """Represents a unique identifier for each Send/Recv instruction pair or + optionally for collective instructions (AllReduce, CollectivePermute, + AllToAll). Non-positive channel_id is equivalent to no channel id. + """ + infeed_config: builtins.bytes + """The string representation of the infeed configuration.""" + custom_call_target: builtins.str + """Name of a external target (eg, global symbol) to call, only present for + kCustomCall. + """ + fft_type: tensorflow.compiler.xla.xla_data_pb2.FftType.ValueType + """FFT type (FFT, IFFT, etc).""" + comparison_direction: builtins.str + """Comparison direction only used for kCompare.""" + id: builtins.int + """The id of this instruction.""" + backend_config: builtins.bytes + """Backend configuration for the instruction. Has backend-specific meaning.""" + all_reduce_id: builtins.int + """Deprecated, but keeping it for backward compatibility. Use channel_id. + Non-positive all_reduce_id is equivalent to no all_reduce_id. + """ + use_global_device_ids: builtins.bool + """If true, interprets ids in ReplicaGroup as global device ids, which is + a linearized id of `replica_id * partition_count + partition_id`. + """ + is_host_transfer: builtins.bool + """Whether this Send/Recv instruction transfers data to/from the host. Only + present for Send and Recv instructions and their SendDone and RecvDone + partners. + """ + is_stable: builtins.bool + """Whether this Sort instruction should be stable.""" + constrain_layout: builtins.bool + """For custom call this indicates that the layouts are constrained. If + constrain_layout is true then the 'shape' field must contain a layout, and + 'operand_shapes_with_layout' must contain a shape with layout for each + operand. + """ + custom_call_has_side_effect: builtins.bool + """Whether the kCustomCall instruction has side-effects, only present for + kCustomCall. + """ + custom_call_schedule: global___CustomCallSchedule.ValueType + """Specifies the desired schedule for the custom-call. The field is only + present for custom-call. + """ + delta: builtins.int + """The delta value for kRngGetAndUpdateState.""" + indices_are_sorted: builtins.bool + """Specifies if the gather/scatter indices are guaranteed to be sorted by the + caller. + """ + unique_indices: builtins.bool + """Specifies if all elements updated are guaranteed to be unique by + the caller. + """ + rng_algorithm: tensorflow.compiler.xla.xla_data_pb2.RandomAlgorithm.ValueType + """RNG algorithm used by kRngBitGenerator.""" + comparison_type: builtins.str + """The comparison type used for kCompare.""" + is_cross_program_prefetch: builtins.bool + """Specifies if this is a cross-program-prefetch, used by kCopyStart. + Deprecated and replaced by optional_cross_program_prefetch_index. + """ + cross_program_prefetch_index: builtins.int + padding_type: tensorflow.compiler.xla.xla_data_pb2.PaddingType.ValueType + """If a convolution is dynamic, a dynamic padding type will be specified.""" + custom_call_api_version: global___CustomCallApiVersion.ValueType + """The API version used by the custom call function. This field is only + present for custom-call. + TODO(b/189822916): Remove this field when all clients are migrated to the + status-returning API. + """ + async_execution_thread: builtins.str + """Represents a unique execution thread name for one or more async groups. + Each HLO module may contain a main thread and one or more parallel threads. + Empty async_execution_thread is equivalent to main thread. + """ + k: builtins.int + """Represents the K value for top-k.""" + largest: builtins.bool + """Represents the largest flag for top-k.""" + is_composite: builtins.bool + """Specifies if a call instruction is a composite.""" + @property + def shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ShapeProto: ... + @property + def metadata(self) -> tensorflow.compiler.xla.xla_data_pb2.OpMetadata: ... + @property + def literal(self) -> tensorflow.compiler.xla.xla_data_pb2.LiteralProto: + """Literal, only present for kConstant.""" + + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Dimensions present for some operations that require reshaping or + broadcasting, including Reshape, Reduce, ReduceWindow, and Reverse. + """ + + @property + def window(self) -> tensorflow.compiler.xla.xla_data_pb2.Window: + """Describes the window in a windowed operation such as convolution.""" + + @property + def convolution_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.ConvolutionDimensionNumbers: + """Describes the dimension numbers used for a convolution.""" + + @property + def slice_dimensions( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloInstructionProto.SliceDimensions]: ... + @property + def dynamic_slice_sizes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Describes the [start, start + size) range size for a dynamic slice + ('start' is specified dynamically in the second operand of the operation). + """ + + @property + def padding_config(self) -> tensorflow.compiler.xla.xla_data_pb2.PaddingConfig: + """The padding configuration that describes the edge padding and interior + padding of this pad instruction. Only set for pad instructions. + """ + + @property + def outfeed_shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ShapeProto: + """Shape of outfeed request.""" + + @property + def dot_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.DotDimensionNumbers: + """Describes the dimension numbers used for a dot operation""" + + @property + def fft_length(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """FFT length.""" + + @property + def gather_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.GatherDimensionNumbers: + """Gather dimension numbers.""" + + @property + def gather_slice_sizes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def operand_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def control_predecessor_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def called_computation_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: ... + @property + def replica_groups( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.ReplicaGroup]: + """Deprecated, but keeping for backward compatibility. + Use collective_device_list. Cross replica op fields. + """ + + @property + def scatter_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.ScatterDimensionNumbers: ... + @property + def precision_config(self) -> tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig: + """Precision configuration for the instruction. Has backend-specific meaning.""" + + @property + def source_target_pairs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.SourceTarget]: + """Collective permute field.""" + + @property + def domain_entry_sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: + """Sharding for kDomain instructions.""" + + @property + def domain_exit_sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: ... + @property + def operand_shapes_with_layout( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.ShapeProto]: ... + @property + def triangular_solve_options(self) -> tensorflow.compiler.xla.xla_data_pb2.TriangularSolveOptions: + """Options for TriangularSolve""" + + @property + def cholesky_options(self) -> tensorflow.compiler.xla.xla_data_pb2.CholeskyOptions: + """Options for Cholesky""" + + @property + def parameter_replication(self) -> tensorflow.compiler.xla.xla_data_pb2.ParameterReplication: + """Describes how parameters behave with regards to replicas.""" + + @property + def output_operand_aliasing( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.compiler.xla.xla_data_pb2.OutputOperandAliasing + ]: + """A list of OutputOperandAliasing pairs that specifies aliasing buffers + between output and operands for kCustomCall and kFusion. + """ + + @property + def frontend_attributes(self) -> tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes: + """Frontend attributes to pass to the XLA backend.""" + + @property + def statistics_viz(self) -> tensorflow.compiler.xla.xla_data_pb2.StatisticsViz: + """Represents the information for tracking propagation of values within HLO + graph. + """ + + @property + def dot_sparsity( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.compiler.xla.xla_data_pb2.SparsityDescriptor + ]: + """Sparsity descriptor for dot operation.""" + + @property + def collective_device_list(self) -> tensorflow.compiler.xla.xla_data_pb2.CollectiveDeviceListProto: + """Represents the list of devices that participate in a collective operation.""" + + @property + def original_value(self) -> tensorflow.compiler.xla.xla_data_pb2.OriginalValueProto: + """For HLO value tracking.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + opcode: builtins.str | None = ..., + shape: tensorflow.compiler.xla.xla_data_pb2.ShapeProto | None = ..., + metadata: tensorflow.compiler.xla.xla_data_pb2.OpMetadata | None = ..., + literal: tensorflow.compiler.xla.xla_data_pb2.LiteralProto | None = ..., + parameter_number: builtins.int | None = ..., + fusion_kind: builtins.str | None = ..., + tuple_index: builtins.int | None = ..., + dimensions: collections.abc.Iterable[builtins.int] | None = ..., + window: tensorflow.compiler.xla.xla_data_pb2.Window | None = ..., + convolution_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.ConvolutionDimensionNumbers | None = ..., + feature_group_count: builtins.int | None = ..., + batch_group_count: builtins.int | None = ..., + slice_dimensions: collections.abc.Iterable[global___HloInstructionProto.SliceDimensions] | None = ..., + exponent_bits: builtins.int | None = ..., + mantissa_bits: builtins.int | None = ..., + dynamic_slice_sizes: collections.abc.Iterable[builtins.int] | None = ..., + padding_config: tensorflow.compiler.xla.xla_data_pb2.PaddingConfig | None = ..., + outfeed_config: builtins.bytes | None = ..., + distribution: tensorflow.compiler.xla.xla_data_pb2.RandomDistribution.ValueType | None = ..., + epsilon: builtins.float | None = ..., + feature_index: builtins.int | None = ..., + channel_id: builtins.int | None = ..., + infeed_config: builtins.bytes | None = ..., + custom_call_target: builtins.str | None = ..., + outfeed_shape: tensorflow.compiler.xla.xla_data_pb2.ShapeProto | None = ..., + dot_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.DotDimensionNumbers | None = ..., + fft_type: tensorflow.compiler.xla.xla_data_pb2.FftType.ValueType | None = ..., + fft_length: collections.abc.Iterable[builtins.int] | None = ..., + comparison_direction: builtins.str | None = ..., + gather_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.GatherDimensionNumbers | None = ..., + gather_slice_sizes: collections.abc.Iterable[builtins.int] | None = ..., + id: builtins.int | None = ..., + operand_ids: collections.abc.Iterable[builtins.int] | None = ..., + control_predecessor_ids: collections.abc.Iterable[builtins.int] | None = ..., + called_computation_ids: collections.abc.Iterable[builtins.int] | None = ..., + sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + backend_config: builtins.bytes | None = ..., + replica_groups: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.ReplicaGroup] | None = ..., + all_reduce_id: builtins.int | None = ..., + use_global_device_ids: builtins.bool | None = ..., + is_host_transfer: builtins.bool | None = ..., + is_stable: builtins.bool | None = ..., + scatter_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.ScatterDimensionNumbers | None = ..., + precision_config: tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig | None = ..., + source_target_pairs: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.SourceTarget] | None = ..., + domain_entry_sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + domain_exit_sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + constrain_layout: builtins.bool | None = ..., + operand_shapes_with_layout: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.ShapeProto] | None = ..., + triangular_solve_options: tensorflow.compiler.xla.xla_data_pb2.TriangularSolveOptions | None = ..., + cholesky_options: tensorflow.compiler.xla.xla_data_pb2.CholeskyOptions | None = ..., + parameter_replication: tensorflow.compiler.xla.xla_data_pb2.ParameterReplication | None = ..., + custom_call_has_side_effect: builtins.bool | None = ..., + output_operand_aliasing: ( + collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.OutputOperandAliasing] | None + ) = ..., + custom_call_schedule: global___CustomCallSchedule.ValueType | None = ..., + delta: builtins.int | None = ..., + indices_are_sorted: builtins.bool | None = ..., + frontend_attributes: tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes | None = ..., + unique_indices: builtins.bool | None = ..., + rng_algorithm: tensorflow.compiler.xla.xla_data_pb2.RandomAlgorithm.ValueType | None = ..., + comparison_type: builtins.str | None = ..., + is_cross_program_prefetch: builtins.bool | None = ..., + cross_program_prefetch_index: builtins.int | None = ..., + padding_type: tensorflow.compiler.xla.xla_data_pb2.PaddingType.ValueType | None = ..., + custom_call_api_version: global___CustomCallApiVersion.ValueType | None = ..., + async_execution_thread: builtins.str | None = ..., + k: builtins.int | None = ..., + largest: builtins.bool | None = ..., + statistics_viz: tensorflow.compiler.xla.xla_data_pb2.StatisticsViz | None = ..., + dot_sparsity: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.SparsityDescriptor] | None = ..., + collective_device_list: tensorflow.compiler.xla.xla_data_pb2.CollectiveDeviceListProto | None = ..., + original_value: tensorflow.compiler.xla.xla_data_pb2.OriginalValueProto | None = ..., + is_composite: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cholesky_options", + b"cholesky_options", + "collective_device_list", + b"collective_device_list", + "convolution_dimension_numbers", + b"convolution_dimension_numbers", + "cross_program_prefetch_index", + b"cross_program_prefetch_index", + "domain_entry_sharding", + b"domain_entry_sharding", + "domain_exit_sharding", + b"domain_exit_sharding", + "dot_dimension_numbers", + b"dot_dimension_numbers", + "frontend_attributes", + b"frontend_attributes", + "gather_dimension_numbers", + b"gather_dimension_numbers", + "literal", + b"literal", + "metadata", + b"metadata", + "optional_cross_program_prefetch_index", + b"optional_cross_program_prefetch_index", + "original_value", + b"original_value", + "outfeed_shape", + b"outfeed_shape", + "padding_config", + b"padding_config", + "parameter_replication", + b"parameter_replication", + "precision_config", + b"precision_config", + "scatter_dimension_numbers", + b"scatter_dimension_numbers", + "shape", + b"shape", + "sharding", + b"sharding", + "statistics_viz", + b"statistics_viz", + "triangular_solve_options", + b"triangular_solve_options", + "window", + b"window", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "all_reduce_id", + b"all_reduce_id", + "async_execution_thread", + b"async_execution_thread", + "backend_config", + b"backend_config", + "batch_group_count", + b"batch_group_count", + "called_computation_ids", + b"called_computation_ids", + "channel_id", + b"channel_id", + "cholesky_options", + b"cholesky_options", + "collective_device_list", + b"collective_device_list", + "comparison_direction", + b"comparison_direction", + "comparison_type", + b"comparison_type", + "constrain_layout", + b"constrain_layout", + "control_predecessor_ids", + b"control_predecessor_ids", + "convolution_dimension_numbers", + b"convolution_dimension_numbers", + "cross_program_prefetch_index", + b"cross_program_prefetch_index", + "custom_call_api_version", + b"custom_call_api_version", + "custom_call_has_side_effect", + b"custom_call_has_side_effect", + "custom_call_schedule", + b"custom_call_schedule", + "custom_call_target", + b"custom_call_target", + "delta", + b"delta", + "dimensions", + b"dimensions", + "distribution", + b"distribution", + "domain_entry_sharding", + b"domain_entry_sharding", + "domain_exit_sharding", + b"domain_exit_sharding", + "dot_dimension_numbers", + b"dot_dimension_numbers", + "dot_sparsity", + b"dot_sparsity", + "dynamic_slice_sizes", + b"dynamic_slice_sizes", + "epsilon", + b"epsilon", + "exponent_bits", + b"exponent_bits", + "feature_group_count", + b"feature_group_count", + "feature_index", + b"feature_index", + "fft_length", + b"fft_length", + "fft_type", + b"fft_type", + "frontend_attributes", + b"frontend_attributes", + "fusion_kind", + b"fusion_kind", + "gather_dimension_numbers", + b"gather_dimension_numbers", + "gather_slice_sizes", + b"gather_slice_sizes", + "id", + b"id", + "indices_are_sorted", + b"indices_are_sorted", + "infeed_config", + b"infeed_config", + "is_composite", + b"is_composite", + "is_cross_program_prefetch", + b"is_cross_program_prefetch", + "is_host_transfer", + b"is_host_transfer", + "is_stable", + b"is_stable", + "k", + b"k", + "largest", + b"largest", + "literal", + b"literal", + "mantissa_bits", + b"mantissa_bits", + "metadata", + b"metadata", + "name", + b"name", + "opcode", + b"opcode", + "operand_ids", + b"operand_ids", + "operand_shapes_with_layout", + b"operand_shapes_with_layout", + "optional_cross_program_prefetch_index", + b"optional_cross_program_prefetch_index", + "original_value", + b"original_value", + "outfeed_config", + b"outfeed_config", + "outfeed_shape", + b"outfeed_shape", + "output_operand_aliasing", + b"output_operand_aliasing", + "padding_config", + b"padding_config", + "padding_type", + b"padding_type", + "parameter_number", + b"parameter_number", + "parameter_replication", + b"parameter_replication", + "precision_config", + b"precision_config", + "replica_groups", + b"replica_groups", + "rng_algorithm", + b"rng_algorithm", + "scatter_dimension_numbers", + b"scatter_dimension_numbers", + "shape", + b"shape", + "sharding", + b"sharding", + "slice_dimensions", + b"slice_dimensions", + "source_target_pairs", + b"source_target_pairs", + "statistics_viz", + b"statistics_viz", + "triangular_solve_options", + b"triangular_solve_options", + "tuple_index", + b"tuple_index", + "unique_indices", + b"unique_indices", + "use_global_device_ids", + b"use_global_device_ids", + "window", + b"window", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["optional_cross_program_prefetch_index", b"optional_cross_program_prefetch_index"] + ) -> typing.Literal["cross_program_prefetch_index"] | None: ... + +global___HloInstructionProto = HloInstructionProto + +@typing.final +class HloComputationProto(google.protobuf.message.Message): + """Serialization of HloComputation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + INSTRUCTIONS_FIELD_NUMBER: builtins.int + PROGRAM_SHAPE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + ROOT_ID_FIELD_NUMBER: builtins.int + IS_FUSION_COMPUTATION_FIELD_NUMBER: builtins.int + EXECUTION_THREAD_FIELD_NUMBER: builtins.int + name: builtins.str + id: builtins.int + """The id of this computation.""" + root_id: builtins.int + """The id of the root of the computation.""" + is_fusion_computation: builtins.bool + """Whether this is a fusion computation. Fusion computations should use this + to determine whether they are a fusion in CreateFromProto since the + parent fusion_instruction_ may get removed and be nullptr. + """ + execution_thread: builtins.str + """The name of execution thread this computation belongs to.""" + @property + def instructions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloInstructionProto]: + """The array of instructions is always in a valid dependency order, where + operands appear before their users. + """ + + @property + def program_shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto: + """The program shape (with layout) of this computation.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + instructions: collections.abc.Iterable[global___HloInstructionProto] | None = ..., + program_shape: tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto | None = ..., + id: builtins.int | None = ..., + root_id: builtins.int | None = ..., + is_fusion_computation: builtins.bool | None = ..., + execution_thread: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["program_shape", b"program_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "execution_thread", + b"execution_thread", + "id", + b"id", + "instructions", + b"instructions", + "is_fusion_computation", + b"is_fusion_computation", + "name", + b"name", + "program_shape", + b"program_shape", + "root_id", + b"root_id", + ], + ) -> None: ... + +global___HloComputationProto = HloComputationProto + +@typing.final +class HloScheduleProto(google.protobuf.message.Message): + """Serialization of an HLO schedule. An HLO schedule contains a total order of + instructions for each non-fusion computation in the module. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class InstructionSequence(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INSTRUCTION_IDS_FIELD_NUMBER: builtins.int + @property + def instruction_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, instruction_ids: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["instruction_ids", b"instruction_ids"]) -> None: ... + + @typing.final + class SequencesEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.int + @property + def value(self) -> global___HloScheduleProto.InstructionSequence: ... + def __init__( + self, *, key: builtins.int | None = ..., value: global___HloScheduleProto.InstructionSequence | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + SEQUENCES_FIELD_NUMBER: builtins.int + @property + def sequences( + self, + ) -> google.protobuf.internal.containers.MessageMap[builtins.int, global___HloScheduleProto.InstructionSequence]: + """Map from computation id to sequence.""" + + def __init__( + self, *, sequences: collections.abc.Mapping[builtins.int, global___HloScheduleProto.InstructionSequence] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["sequences", b"sequences"]) -> None: ... + +global___HloScheduleProto = HloScheduleProto + +@typing.final +class HloInputOutputAliasProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class AliasEntryProto(google.protobuf.message.Message): + """The following proto describes a pair of aliased an input + (described by parameter number and a ShapeIndex of the parameter) + and an output (described by a ShapeIndex of the root + instruction). For example: + + entry = { + output_shape_index={1}, + parameter_number=0, + parameter_shape_index={1, 2}, + } + + This entry indicates that the first parameter's {1, 2} element is + aliased with the {1} element of the root instruction. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OUTPUT_SHAPE_INDEX_FIELD_NUMBER: builtins.int + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + KIND_FIELD_NUMBER: builtins.int + parameter_number: builtins.int + """Number of the parameter in entry computation.""" + kind: global___Kind.ValueType + """The kind of alias to be setup.""" + @property + def output_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ShapeIndex of the root hlo.""" + + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ShapeIndex of the parameter instruction.""" + + def __init__( + self, + *, + output_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + kind: global___Kind.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "kind", + b"kind", + "output_shape_index", + b"output_shape_index", + "parameter_number", + b"parameter_number", + "parameter_shape_index", + b"parameter_shape_index", + ], + ) -> None: ... + + ENTRIES_FIELD_NUMBER: builtins.int + @property + def entries( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___HloInputOutputAliasProto.AliasEntryProto + ]: ... + def __init__( + self, *, entries: collections.abc.Iterable[global___HloInputOutputAliasProto.AliasEntryProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["entries", b"entries"]) -> None: ... + +global___HloInputOutputAliasProto = HloInputOutputAliasProto + +@typing.final +class HloBufferDonorProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class BufferDonorEntryProto(google.protobuf.message.Message): + """The following proto describes an input (described by parameter number and a + ShapeIndex of the parameter) that can donate its butter to any output + tensor. It is similar to HloInputOutputAliasProto, but without a paired + output. For example: + + entry = { + parameter_number=0, + parameter_shape_index={1, 2}, + } + + This entry indicates that the first parameter's {1, 2} element can donate + its buffer. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + parameter_number: builtins.int + """Number of the parameter in entry computation.""" + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ShapeIndex of the parameter instruction.""" + + def __init__( + self, + *, + parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "parameter_number", b"parameter_number", "parameter_shape_index", b"parameter_shape_index" + ], + ) -> None: ... + + ENTRIES_FIELD_NUMBER: builtins.int + @property + def entries( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___HloBufferDonorProto.BufferDonorEntryProto + ]: ... + def __init__( + self, *, entries: collections.abc.Iterable[global___HloBufferDonorProto.BufferDonorEntryProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["entries", b"entries"]) -> None: ... + +global___HloBufferDonorProto = HloBufferDonorProto + +@typing.final +class CrossProgramPrefetch(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PARAMETER_FIELD_NUMBER: builtins.int + INDEX_FIELD_NUMBER: builtins.int + OFFSET_FIELD_NUMBER: builtins.int + parameter: builtins.int + offset: builtins.int + @property + def index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + parameter: builtins.int | None = ..., + index: collections.abc.Iterable[builtins.int] | None = ..., + offset: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["index", b"index", "offset", b"offset", "parameter", b"parameter"] + ) -> None: ... + +global___CrossProgramPrefetch = CrossProgramPrefetch + +@typing.final +class StackFrameIndexProto(google.protobuf.message.Message): + """Serialization of stack frames index representations. + Stack frames index presented in four flat arrays: + 1. File names array. + 2. Function names array. + 3. File location array. + 4. Frame array. + All reference ids in sub-protos are 1-based positions of the + entity in the flat array. + Ids are 1-based to keep 0 value as representation of non-set property. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FileLocation(google.protobuf.message.Message): + """Serialization of file position.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_NAME_ID_FIELD_NUMBER: builtins.int + FUNCTION_NAME_ID_FIELD_NUMBER: builtins.int + LINE_FIELD_NUMBER: builtins.int + COLUMN_FIELD_NUMBER: builtins.int + file_name_id: builtins.int + """1-based position of file name.""" + function_name_id: builtins.int + """1-based position of function name.""" + line: builtins.int + """Line number.""" + column: builtins.int + """Column number.""" + def __init__( + self, + *, + file_name_id: builtins.int | None = ..., + function_name_id: builtins.int | None = ..., + line: builtins.int | None = ..., + column: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "column", b"column", "file_name_id", b"file_name_id", "function_name_id", b"function_name_id", "line", b"line" + ], + ) -> None: ... + + @typing.final + class StackFrame(google.protobuf.message.Message): + """Serialization of frame.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_LOCATION_ID_FIELD_NUMBER: builtins.int + PARENT_FRAME_ID_FIELD_NUMBER: builtins.int + file_location_id: builtins.int + """1-based position of file location.""" + parent_frame_id: builtins.int + """1-based position of the parent frame.""" + def __init__( + self, *, file_location_id: builtins.int | None = ..., parent_frame_id: builtins.int | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["file_location_id", b"file_location_id", "parent_frame_id", b"parent_frame_id"] + ) -> None: ... + + FILE_NAMES_FIELD_NUMBER: builtins.int + FUNCTION_NAMES_FIELD_NUMBER: builtins.int + FILE_LOCATIONS_FIELD_NUMBER: builtins.int + STACK_FRAMES_FIELD_NUMBER: builtins.int + @property + def file_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Flat index array of file names.""" + + @property + def function_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Flat index array of function names.""" + + @property + def file_locations( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___StackFrameIndexProto.FileLocation]: + """Flat index array of file locations.""" + + @property + def stack_frames( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___StackFrameIndexProto.StackFrame]: + """Flat index array of frames.""" + + def __init__( + self, + *, + file_names: collections.abc.Iterable[builtins.str] | None = ..., + function_names: collections.abc.Iterable[builtins.str] | None = ..., + file_locations: collections.abc.Iterable[global___StackFrameIndexProto.FileLocation] | None = ..., + stack_frames: collections.abc.Iterable[global___StackFrameIndexProto.StackFrame] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "file_locations", + b"file_locations", + "file_names", + b"file_names", + "function_names", + b"function_names", + "stack_frames", + b"stack_frames", + ], + ) -> None: ... + +global___StackFrameIndexProto = StackFrameIndexProto + +@typing.final +class HloModuleProto(google.protobuf.message.Message): + """Serialization of HloModule.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ProfileType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ProfileTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[HloModuleProto._ProfileType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + INVALID: HloModuleProto._ProfileType.ValueType # 0 + FLAG: HloModuleProto._ProfileType.ValueType # 1 + FUSION: HloModuleProto._ProfileType.ValueType # 2 + LAYOUT: HloModuleProto._ProfileType.ValueType # 3 + DOT: HloModuleProto._ProfileType.ValueType # 4 + FLAGNET: HloModuleProto._ProfileType.ValueType # 5 + + class ProfileType(_ProfileType, metaclass=_ProfileTypeEnumTypeWrapper): + """The type of optimization profile in use for module-level optimizations.""" + + INVALID: HloModuleProto.ProfileType.ValueType # 0 + FLAG: HloModuleProto.ProfileType.ValueType # 1 + FUSION: HloModuleProto.ProfileType.ValueType # 2 + LAYOUT: HloModuleProto.ProfileType.ValueType # 3 + DOT: HloModuleProto.ProfileType.ValueType # 4 + FLAGNET: HloModuleProto.ProfileType.ValueType # 5 + + @typing.final + class ProfileInfo(google.protobuf.message.Message): + """Information about the optimization profile that this module contains.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PROFILE_TYPE_FIELD_NUMBER: builtins.int + RELATIVE_SPEEDUP_FIELD_NUMBER: builtins.int + PROFILE_SOURCE_FIELD_NUMBER: builtins.int + COMPILATION_EVENT_FIELD_NUMBER: builtins.int + FINGERPRINT_FIELD_NUMBER: builtins.int + profile_type: global___HloModuleProto.ProfileType.ValueType + """The optimization profiles that this module contains.""" + relative_speedup: builtins.float + """Speedup of tuned config compared to default config.""" + profile_source: tensorflow.compiler.xla.xla_data_pb2.ProfileSource.ValueType + """The source of the optimization profile that this module contains.""" + compilation_event: tensorflow.compiler.xla.xla_data_pb2.CompilationEvent.ValueType + """The compilation event that triggered the use of the profile.""" + fingerprint: builtins.str + """The fingerprint of the unoptimized module this profile was applied to.""" + def __init__( + self, + *, + profile_type: global___HloModuleProto.ProfileType.ValueType | None = ..., + relative_speedup: builtins.float | None = ..., + profile_source: tensorflow.compiler.xla.xla_data_pb2.ProfileSource.ValueType | None = ..., + compilation_event: tensorflow.compiler.xla.xla_data_pb2.CompilationEvent.ValueType | None = ..., + fingerprint: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_event", + b"compilation_event", + "fingerprint", + b"fingerprint", + "profile_source", + b"profile_source", + "profile_type", + b"profile_type", + "relative_speedup", + b"relative_speedup", + ], + ) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + ENTRY_COMPUTATION_NAME_FIELD_NUMBER: builtins.int + ENTRY_COMPUTATION_ID_FIELD_NUMBER: builtins.int + COMPUTATIONS_FIELD_NUMBER: builtins.int + HOST_PROGRAM_SHAPE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + SCHEDULE_FIELD_NUMBER: builtins.int + INPUT_OUTPUT_ALIAS_FIELD_NUMBER: builtins.int + BUFFER_DONOR_FIELD_NUMBER: builtins.int + CROSS_PROGRAM_PREFETCHES_FIELD_NUMBER: builtins.int + IS_DYNAMIC_FIELD_NUMBER: builtins.int + SPMD_OUTPUT_SHARDING_FIELD_NUMBER: builtins.int + SPMD_PARAMETERS_SHARDINGS_FIELD_NUMBER: builtins.int + USE_AUTO_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + PROFILE_INFO_FIELD_NUMBER: builtins.int + DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + STACK_FRAME_INDEX_FIELD_NUMBER: builtins.int + FRONTEND_ATTRIBUTES_FIELD_NUMBER: builtins.int + name: builtins.str + entry_computation_name: builtins.str + entry_computation_id: builtins.int + id: builtins.int + """The id of this module.""" + is_dynamic: builtins.bool + """True if the module contains dynamic computation.""" + use_auto_spmd_partitioning: builtins.bool + """Uses AutoSharding pass or not.""" + @property + def computations(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloComputationProto]: + """The array of computations is always in a valid dependency order, where + callees appear before their callers. + """ + + @property + def host_program_shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto: + """The host program shape (with layout) of the entry computation.""" + + @property + def schedule(self) -> global___HloScheduleProto: + """The schedule for this module.""" + + @property + def input_output_alias(self) -> global___HloInputOutputAliasProto: + """Describes alias information between inputs and outputs.""" + + @property + def buffer_donor(self) -> global___HloBufferDonorProto: + """Describes the information of input buffer donors.""" + + @property + def cross_program_prefetches( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CrossProgramPrefetch]: ... + @property + def spmd_output_sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: ... + @property + def spmd_parameters_shardings( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.OpSharding]: ... + @property + def profile_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleProto.ProfileInfo]: + """Profile information for the HLO module.""" + + @property + def device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: + """DeviceAssignment object information.""" + + @property + def stack_frame_index(self) -> global___StackFrameIndexProto: + """Stack frames index.""" + + @property + def frontend_attributes(self) -> tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes: + """Frontend attributes to pass to the XLA backend.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + entry_computation_name: builtins.str | None = ..., + entry_computation_id: builtins.int | None = ..., + computations: collections.abc.Iterable[global___HloComputationProto] | None = ..., + host_program_shape: tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto | None = ..., + id: builtins.int | None = ..., + schedule: global___HloScheduleProto | None = ..., + input_output_alias: global___HloInputOutputAliasProto | None = ..., + buffer_donor: global___HloBufferDonorProto | None = ..., + cross_program_prefetches: collections.abc.Iterable[global___CrossProgramPrefetch] | None = ..., + is_dynamic: builtins.bool | None = ..., + spmd_output_sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + spmd_parameters_shardings: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.OpSharding] | None = ..., + use_auto_spmd_partitioning: builtins.bool | None = ..., + profile_info: collections.abc.Iterable[global___HloModuleProto.ProfileInfo] | None = ..., + device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + stack_frame_index: global___StackFrameIndexProto | None = ..., + frontend_attributes: tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "buffer_donor", + b"buffer_donor", + "device_assignment", + b"device_assignment", + "frontend_attributes", + b"frontend_attributes", + "host_program_shape", + b"host_program_shape", + "input_output_alias", + b"input_output_alias", + "schedule", + b"schedule", + "spmd_output_sharding", + b"spmd_output_sharding", + "stack_frame_index", + b"stack_frame_index", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_donor", + b"buffer_donor", + "computations", + b"computations", + "cross_program_prefetches", + b"cross_program_prefetches", + "device_assignment", + b"device_assignment", + "entry_computation_id", + b"entry_computation_id", + "entry_computation_name", + b"entry_computation_name", + "frontend_attributes", + b"frontend_attributes", + "host_program_shape", + b"host_program_shape", + "id", + b"id", + "input_output_alias", + b"input_output_alias", + "is_dynamic", + b"is_dynamic", + "name", + b"name", + "profile_info", + b"profile_info", + "schedule", + b"schedule", + "spmd_output_sharding", + b"spmd_output_sharding", + "spmd_parameters_shardings", + b"spmd_parameters_shardings", + "stack_frame_index", + b"stack_frame_index", + "use_auto_spmd_partitioning", + b"use_auto_spmd_partitioning", + ], + ) -> None: ... + +global___HloModuleProto = HloModuleProto + +@typing.final +class LogicalBufferProto(google.protobuf.message.Message): + """Serialization of LogicalBuffer.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Location(google.protobuf.message.Message): + """Location represents an instruction and its shape index, which uniquely + identifies a point where a buffer is needed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INSTRUCTION_NAME_FIELD_NUMBER: builtins.int + INSTRUCTION_ID_FIELD_NUMBER: builtins.int + SHAPE_INDEX_FIELD_NUMBER: builtins.int + instruction_name: builtins.str + """TODO(b/239098765): Remove instruction_name and computation_name.""" + instruction_id: builtins.int + @property + def shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + instruction_name: builtins.str | None = ..., + instruction_id: builtins.int | None = ..., + shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "instruction_id", b"instruction_id", "instruction_name", b"instruction_name", "shape_index", b"shape_index" + ], + ) -> None: ... + + ID_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + DEFINED_AT_FIELD_NUMBER: builtins.int + COLOR_FIELD_NUMBER: builtins.int + id: builtins.int + size: builtins.int + color: builtins.int + @property + def defined_at(self) -> global___LogicalBufferProto.Location: + """The location where the buffer is defined.""" + + def __init__( + self, + *, + id: builtins.int | None = ..., + size: builtins.int | None = ..., + defined_at: global___LogicalBufferProto.Location | None = ..., + color: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["defined_at", b"defined_at"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["color", b"color", "defined_at", b"defined_at", "id", b"id", "size", b"size"] + ) -> None: ... + +global___LogicalBufferProto = LogicalBufferProto + +@typing.final +class BufferAllocationProto(google.protobuf.message.Message): + """Serialization of BufferAllocation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Assigned(google.protobuf.message.Message): + """Assigned represents a single LogicalBuffer that is assigned to this + BufferAllocation. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOGICAL_BUFFER_ID_FIELD_NUMBER: builtins.int + OFFSET_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + logical_buffer_id: builtins.int + offset: builtins.int + size: builtins.int + def __init__( + self, + *, + logical_buffer_id: builtins.int | None = ..., + offset: builtins.int | None = ..., + size: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["logical_buffer_id", b"logical_buffer_id", "offset", b"offset", "size", b"size"] + ) -> None: ... + + INDEX_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + IS_THREAD_LOCAL_FIELD_NUMBER: builtins.int + IS_TUPLE_FIELD_NUMBER: builtins.int + IS_ENTRY_COMPUTATION_PARAMETER_FIELD_NUMBER: builtins.int + IS_CONSTANT_FIELD_NUMBER: builtins.int + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + MAYBE_LIVE_OUT_FIELD_NUMBER: builtins.int + COLOR_FIELD_NUMBER: builtins.int + ASSIGNED_FIELD_NUMBER: builtins.int + index: builtins.int + size: builtins.int + is_thread_local: builtins.bool + is_tuple: builtins.bool + is_entry_computation_parameter: builtins.bool + is_constant: builtins.bool + parameter_number: builtins.int + maybe_live_out: builtins.bool + color: builtins.int + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def assigned( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BufferAllocationProto.Assigned]: ... + def __init__( + self, + *, + index: builtins.int | None = ..., + size: builtins.int | None = ..., + is_thread_local: builtins.bool | None = ..., + is_tuple: builtins.bool | None = ..., + is_entry_computation_parameter: builtins.bool | None = ..., + is_constant: builtins.bool | None = ..., + parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + maybe_live_out: builtins.bool | None = ..., + color: builtins.int | None = ..., + assigned: collections.abc.Iterable[global___BufferAllocationProto.Assigned] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "assigned", + b"assigned", + "color", + b"color", + "index", + b"index", + "is_constant", + b"is_constant", + "is_entry_computation_parameter", + b"is_entry_computation_parameter", + "is_thread_local", + b"is_thread_local", + "is_tuple", + b"is_tuple", + "maybe_live_out", + b"maybe_live_out", + "parameter_number", + b"parameter_number", + "parameter_shape_index", + b"parameter_shape_index", + "size", + b"size", + ], + ) -> None: ... + +global___BufferAllocationProto = BufferAllocationProto + +@typing.final +class HeapSimulatorTrace(google.protobuf.message.Message): + """A trace of a HeapSimulator run.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Event(google.protobuf.message.Message): + """The trace includes a list of events, where each event describes one action + performed by the heap simulator. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Kind: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _KindEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[HeapSimulatorTrace.Event._Kind.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ALLOC: HeapSimulatorTrace.Event._Kind.ValueType # 0 + """A memory region was allocated for the buffer.""" + FREE: HeapSimulatorTrace.Event._Kind.ValueType # 1 + """A memory region was freed for the buffer.""" + SHARE_WITH: HeapSimulatorTrace.Event._Kind.ValueType # 2 + """A buffer was shared with another (canonical) buffer. This is similar to + ALLOC, except that instead of allocating a new region of memory, the + memory region of the canonical buffer is directly re-used. Multiple + buffers may share with the same canonical buffer. The lifetime of the + canonical buffer is extended to the union of all lifetimes. + """ + + class Kind(_Kind, metaclass=_KindEnumTypeWrapper): ... + ALLOC: HeapSimulatorTrace.Event.Kind.ValueType # 0 + """A memory region was allocated for the buffer.""" + FREE: HeapSimulatorTrace.Event.Kind.ValueType # 1 + """A memory region was freed for the buffer.""" + SHARE_WITH: HeapSimulatorTrace.Event.Kind.ValueType # 2 + """A buffer was shared with another (canonical) buffer. This is similar to + ALLOC, except that instead of allocating a new region of memory, the + memory region of the canonical buffer is directly re-used. Multiple + buffers may share with the same canonical buffer. The lifetime of the + canonical buffer is extended to the union of all lifetimes. + """ + + KIND_FIELD_NUMBER: builtins.int + BUFFER_ID_FIELD_NUMBER: builtins.int + COMPUTATION_NAME_FIELD_NUMBER: builtins.int + INSTRUCTION_NAME_FIELD_NUMBER: builtins.int + SHARE_WITH_CANONICAL_ID_FIELD_NUMBER: builtins.int + kind: global___HeapSimulatorTrace.Event.Kind.ValueType + buffer_id: builtins.int + """The id of the LogicalBuffer that the event applies to.""" + computation_name: builtins.str + """The HloInstruction that the simulation was processing that caused this + event to occur, identified by its computation and instruction name. E.g. + buffers defined by instruction A are allocated when processing A. + """ + instruction_name: builtins.str + share_with_canonical_id: builtins.int + """The id of the canonical LogicalBuffer that the buffer shares with. Only + set for SHARE_WITH events. + """ + def __init__( + self, + *, + kind: global___HeapSimulatorTrace.Event.Kind.ValueType | None = ..., + buffer_id: builtins.int | None = ..., + computation_name: builtins.str | None = ..., + instruction_name: builtins.str | None = ..., + share_with_canonical_id: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_id", + b"buffer_id", + "computation_name", + b"computation_name", + "instruction_name", + b"instruction_name", + "kind", + b"kind", + "share_with_canonical_id", + b"share_with_canonical_id", + ], + ) -> None: ... + + EVENTS_FIELD_NUMBER: builtins.int + WHOLE_MODULE_SIMULATION_FIELD_NUMBER: builtins.int + BUFFER_ALLOCATION_INDEX_FIELD_NUMBER: builtins.int + whole_module_simulation: builtins.bool + buffer_allocation_index: builtins.int + @property + def events( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HeapSimulatorTrace.Event]: ... + def __init__( + self, + *, + events: collections.abc.Iterable[global___HeapSimulatorTrace.Event] | None = ..., + whole_module_simulation: builtins.bool | None = ..., + buffer_allocation_index: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_allocation_index", + b"buffer_allocation_index", + "events", + b"events", + "whole_module_simulation", + b"whole_module_simulation", + ], + ) -> None: ... + +global___HeapSimulatorTrace = HeapSimulatorTrace + +@typing.final +class HloModuleGroupProto(google.protobuf.message.Message): + """An abstraction representing a set of HLO module built to run concurrently + across different devices. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + HLO_MODULES_FIELD_NUMBER: builtins.int + name: builtins.str + @property + def hlo_modules(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleProto]: ... + def __init__( + self, *, name: builtins.str | None = ..., hlo_modules: collections.abc.Iterable[global___HloModuleProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["hlo_modules", b"hlo_modules", "name", b"name"]) -> None: ... + +global___HloModuleGroupProto = HloModuleGroupProto + +@typing.final +class BufferAssignmentProto(google.protobuf.message.Message): + """Serialization of BufferAssignment.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class BufferAlias(google.protobuf.message.Message): + """Alias represents a source LogicalBuffer, and the buffer location that + aliases it. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOURCE_BUFFER_ID_FIELD_NUMBER: builtins.int + LOCATION_FIELD_NUMBER: builtins.int + source_buffer_id: builtins.int + @property + def location(self) -> global___LogicalBufferProto.Location: ... + def __init__( + self, *, source_buffer_id: builtins.int | None = ..., location: global___LogicalBufferProto.Location | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["location", b"location"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["location", b"location", "source_buffer_id", b"source_buffer_id"] + ) -> None: ... + + LOGICAL_BUFFERS_FIELD_NUMBER: builtins.int + BUFFER_ALIASES_FIELD_NUMBER: builtins.int + BUFFER_ALLOCATIONS_FIELD_NUMBER: builtins.int + HEAP_SIMULATOR_TRACES_FIELD_NUMBER: builtins.int + @property + def logical_buffers( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___LogicalBufferProto]: ... + @property + def buffer_aliases( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BufferAssignmentProto.BufferAlias]: ... + @property + def buffer_allocations( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BufferAllocationProto]: ... + @property + def heap_simulator_traces( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HeapSimulatorTrace]: ... + def __init__( + self, + *, + logical_buffers: collections.abc.Iterable[global___LogicalBufferProto] | None = ..., + buffer_aliases: collections.abc.Iterable[global___BufferAssignmentProto.BufferAlias] | None = ..., + buffer_allocations: collections.abc.Iterable[global___BufferAllocationProto] | None = ..., + heap_simulator_traces: collections.abc.Iterable[global___HeapSimulatorTrace] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_aliases", + b"buffer_aliases", + "buffer_allocations", + b"buffer_allocations", + "heap_simulator_traces", + b"heap_simulator_traces", + "logical_buffers", + b"logical_buffers", + ], + ) -> None: ... + +global___BufferAssignmentProto = BufferAssignmentProto + +@typing.final +class HloProto(google.protobuf.message.Message): + """Grouping message that contains all of the information above.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HLO_MODULE_FIELD_NUMBER: builtins.int + BUFFER_ASSIGNMENT_FIELD_NUMBER: builtins.int + @property + def hlo_module(self) -> global___HloModuleProto: ... + @property + def buffer_assignment(self) -> global___BufferAssignmentProto: ... + def __init__( + self, *, hlo_module: global___HloModuleProto | None = ..., buffer_assignment: global___BufferAssignmentProto | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["buffer_assignment", b"buffer_assignment", "hlo_module", b"hlo_module"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["buffer_assignment", b"buffer_assignment", "hlo_module", b"hlo_module"] + ) -> None: ... + +global___HloProto = HloProto + +@typing.final +class HloSnapshot(google.protobuf.message.Message): + """Encapsulates HloProto together with the arguments, result, and + execution_platform. This message is used for purposes such as + analysis/replay/file-storage. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HLO_FIELD_NUMBER: builtins.int + ARGUMENTS_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + EXECUTION_PLATFORM_FIELD_NUMBER: builtins.int + execution_platform: builtins.str + """The name of the platform used to run the graph.""" + @property + def hlo(self) -> global___HloProto: + """The hlo graph.""" + + @property + def arguments( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.LiteralProto]: + """The arguments passed to the graph.""" + + @property + def result(self) -> tensorflow.compiler.xla.xla_data_pb2.LiteralProto: + """The result of the graph.""" + + def __init__( + self, + *, + hlo: global___HloProto | None = ..., + arguments: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.LiteralProto] | None = ..., + result: tensorflow.compiler.xla.xla_data_pb2.LiteralProto | None = ..., + execution_platform: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["hlo", b"hlo", "result", b"result"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "arguments", b"arguments", "execution_platform", b"execution_platform", "hlo", b"hlo", "result", b"result" + ], + ) -> None: ... + +global___HloSnapshot = HloSnapshot + +@typing.final +class HloModuleMetadataProto(google.protobuf.message.Message): + """Metadata for an HLO module. Dumped after HLO passes and before LLO lowering + with filename module_####.metadata.textproto, where #### is + canonical_module_id. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CANONICAL_MODULE_ID_FIELD_NUMBER: builtins.int + MODULE_GROUP_NAME_FIELD_NUMBER: builtins.int + ORIGINAL_MODULE_ID_FIELD_NUMBER: builtins.int + PARTITIONED_MODULE_IDS_FIELD_NUMBER: builtins.int + PASS_METADATA_FIELD_NUMBER: builtins.int + canonical_module_id: builtins.int + """Uniquely identifies an HloModuleMetadata. Equal to the first unique_id + of the module (a module may go through multiple unique_ids). If a module + is partitioned into multiple modules, those modules will each have a new + HloModuleMetadata with a different canonical_module_id. + """ + module_group_name: builtins.str + """Name of the module group that the module is part of.""" + original_module_id: builtins.int + """The canonical module id of the module that this one is partitioned from, + if applicable. + """ + @property + def partitioned_module_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The canonical module ids of the modules that this one is partitioned into, + if applicable. + """ + + @property + def pass_metadata(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloPassMetadata]: + """Metadata for the HLO passes that are run on the module.""" + + def __init__( + self, + *, + canonical_module_id: builtins.int | None = ..., + module_group_name: builtins.str | None = ..., + original_module_id: builtins.int | None = ..., + partitioned_module_ids: collections.abc.Iterable[builtins.int] | None = ..., + pass_metadata: collections.abc.Iterable[global___HloPassMetadata] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "canonical_module_id", + b"canonical_module_id", + "module_group_name", + b"module_group_name", + "original_module_id", + b"original_module_id", + "partitioned_module_ids", + b"partitioned_module_ids", + "pass_metadata", + b"pass_metadata", + ], + ) -> None: ... + +global___HloModuleMetadataProto = HloModuleMetadataProto + +@typing.final +class HloPassMetadata(google.protobuf.message.Message): + """Metadata for one run of an HLO pass on a module. Provides more information + when processing debug dumps of HloProtos about the order of HLO passes and + various other stats like duration. `pass_id` may also be used to identify a + particular run of a pass in debug info that propagates through stages of + compilation. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PASS_ID_FIELD_NUMBER: builtins.int + PASS_NAME_FIELD_NUMBER: builtins.int + PIPELINE_NAME_FIELD_NUMBER: builtins.int + DUMP_FILENAMES_FIELD_NUMBER: builtins.int + MODULE_CHANGED_FIELD_NUMBER: builtins.int + MODULE_ID_FIELD_NUMBER: builtins.int + MODULE_GROUP_MODULE_IDS_FIELD_NUMBER: builtins.int + START_TIMESTAMP_USEC_FIELD_NUMBER: builtins.int + END_TIMESTAMP_USEC_FIELD_NUMBER: builtins.int + CUSTOM_METADATA_FIELD_NUMBER: builtins.int + pass_id: builtins.int + """For a given module, pass_id uniquely identifies a run of an HLO pass on + that module. Note that a pass_id may not always refer to the same pass + because the order of passes during compilation may change. For finding + metadata for a particular pass, pass_name and pipeline_name would be more + reliable, although note that they may not be unique. + """ + pass_name: builtins.str + pipeline_name: builtins.str + module_changed: builtins.bool + """Return value of pass.Run(). True if this pass changed the module, or, in + the case where the module was run through this pass as part of a module + group, true if this pass changed any module in the same module group. + """ + module_id: builtins.int + """The unique_id of the module that this pass is run on. May be different from + the canonical_module_id of the HloModuleMetadata that this HloPassMetadata + is inside. + """ + start_timestamp_usec: builtins.int + """Timestamp before and after the pass is run. Note they may be equal.""" + end_timestamp_usec: builtins.int + @property + def dump_filenames(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Filenames of the dumps of the module after this pass ran. Module may be + dumped in multiple formats, and the order of formats in this field will + stay consistent across passes. + """ + + @property + def module_group_module_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """If the module went through this pass as part of a module group, this is + set as the ids of all the modules in the module group. Empty otherwise. + """ + + @property + def custom_metadata(self) -> google.protobuf.any_pb2.Any: + """Custom metadata for the pass.""" + + def __init__( + self, + *, + pass_id: builtins.int | None = ..., + pass_name: builtins.str | None = ..., + pipeline_name: builtins.str | None = ..., + dump_filenames: collections.abc.Iterable[builtins.str] | None = ..., + module_changed: builtins.bool | None = ..., + module_id: builtins.int | None = ..., + module_group_module_ids: collections.abc.Iterable[builtins.int] | None = ..., + start_timestamp_usec: builtins.int | None = ..., + end_timestamp_usec: builtins.int | None = ..., + custom_metadata: google.protobuf.any_pb2.Any | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["custom_metadata", b"custom_metadata"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "custom_metadata", + b"custom_metadata", + "dump_filenames", + b"dump_filenames", + "end_timestamp_usec", + b"end_timestamp_usec", + "module_changed", + b"module_changed", + "module_group_module_ids", + b"module_group_module_ids", + "module_id", + b"module_id", + "pass_id", + b"pass_id", + "pass_name", + b"pass_name", + "pipeline_name", + b"pipeline_name", + "start_timestamp_usec", + b"start_timestamp_usec", + ], + ) -> None: ... + +global___HloPassMetadata = HloPassMetadata diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi new file mode 100644 index 000000000000..5699e8cc13fc --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi @@ -0,0 +1,187 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2018 The OpenXLA Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +============================================================================== +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class HloProfilePrinterData(google.protobuf.message.Message): + """Describes how to pretty-print a profile counter array gathered for a specific + HloModule. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class HloInstructionInfo(google.protobuf.message.Message): + """Pretty-printer information about an HloInstruction.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LONG_NAME_FIELD_NUMBER: builtins.int + SHORT_NAME_FIELD_NUMBER: builtins.int + CATEGORY_FIELD_NUMBER: builtins.int + FLOP_COUNT_FIELD_NUMBER: builtins.int + TRANSCENDENTAL_COUNT_FIELD_NUMBER: builtins.int + BYTES_ACCESSED_FIELD_NUMBER: builtins.int + OPTIMAL_SECONDS_FIELD_NUMBER: builtins.int + PROFILE_INDEX_FIELD_NUMBER: builtins.int + long_name: builtins.str + short_name: builtins.str + category: builtins.str + flop_count: builtins.float + """Metrics computed by HloCostAnalysis.""" + transcendental_count: builtins.float + bytes_accessed: builtins.int + optimal_seconds: builtins.float + profile_index: builtins.int + """The index into the profile counters array for the HloInstruction + corresponding to this HloInstructionInfo. + """ + def __init__( + self, + *, + long_name: builtins.str | None = ..., + short_name: builtins.str | None = ..., + category: builtins.str | None = ..., + flop_count: builtins.float | None = ..., + transcendental_count: builtins.float | None = ..., + bytes_accessed: builtins.int | None = ..., + optimal_seconds: builtins.float | None = ..., + profile_index: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bytes_accessed", + b"bytes_accessed", + "category", + b"category", + "flop_count", + b"flop_count", + "long_name", + b"long_name", + "optimal_seconds", + b"optimal_seconds", + "profile_index", + b"profile_index", + "short_name", + b"short_name", + "transcendental_count", + b"transcendental_count", + ], + ) -> None: ... + + @typing.final + class HloComputationInfo(google.protobuf.message.Message): + """Pretty-printer information about an HloComputation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + PROFILE_INDEX_FIELD_NUMBER: builtins.int + INSTRUCTION_INFOS_FIELD_NUMBER: builtins.int + name: builtins.str + profile_index: builtins.int + """The index into the profile counters array for the HloComputation + corresponding to this HloComputationInfo. + """ + @property + def instruction_infos( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___HloProfilePrinterData.HloInstructionInfo + ]: + """HloInstructionInfos for every HloInstruction in the HloComputation for + corresponding to this HloComputattionInfo. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + profile_index: builtins.int | None = ..., + instruction_infos: collections.abc.Iterable[global___HloProfilePrinterData.HloInstructionInfo] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "instruction_infos", b"instruction_infos", "name", b"name", "profile_index", b"profile_index" + ], + ) -> None: ... + + @typing.final + class ExtraMetricsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + COMPUTATION_INFOS_FIELD_NUMBER: builtins.int + PROFILE_COUNTERS_SIZE_FIELD_NUMBER: builtins.int + EXTRA_METRICS_FIELD_NUMBER: builtins.int + ENTRY_COMPUTATION_FIELD_NUMBER: builtins.int + profile_counters_size: builtins.int + """The size of the profile counters array we will pretty-print.""" + entry_computation: builtins.str + """Name of the entry computation.""" + @property + def computation_infos( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloProfilePrinterData.HloComputationInfo]: + """HloComputationInfos for every HloComputation in the HloModule.""" + + @property + def extra_metrics(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: + """Maps extra metric name to the index into the profile counters array.""" + + def __init__( + self, + *, + computation_infos: collections.abc.Iterable[global___HloProfilePrinterData.HloComputationInfo] | None = ..., + profile_counters_size: builtins.int | None = ..., + extra_metrics: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + entry_computation: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "computation_infos", + b"computation_infos", + "entry_computation", + b"entry_computation", + "extra_metrics", + b"extra_metrics", + "profile_counters_size", + b"profile_counters_size", + ], + ) -> None: ... + +global___HloProfilePrinterData = HloProfilePrinterData diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi new file mode 100644 index 000000000000..30b4ef4a491a --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi @@ -0,0 +1,284 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.duration_pb2 +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import google.protobuf.timestamp_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class PassMetrics(google.protobuf.message.Message): + """Defines pass specific metrics.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MODULE_ID_FIELD_NUMBER: builtins.int + PASS_NAME_FIELD_NUMBER: builtins.int + PASS_DURATION_FIELD_NUMBER: builtins.int + CUSTOM_METRICS_FIELD_NUMBER: builtins.int + module_id: builtins.int + """Unique ID of the module on which the pass was run.""" + pass_name: builtins.str + """The name of the pass.""" + @property + def pass_duration(self) -> google.protobuf.duration_pb2.Duration: + """Duration of the pass.""" + + @property + def custom_metrics(self) -> google.protobuf.any_pb2.Any: + """Custom pass metrics. This is kept opaque, via `google.protobuf.Any`, in + order to decouple pass agnostic compilation logs from possibly proprietary + compiler passes. + """ + + def __init__( + self, + *, + module_id: builtins.int | None = ..., + pass_name: builtins.str | None = ..., + pass_duration: google.protobuf.duration_pb2.Duration | None = ..., + custom_metrics: google.protobuf.any_pb2.Any | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["custom_metrics", b"custom_metrics", "pass_duration", b"pass_duration"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "custom_metrics", + b"custom_metrics", + "module_id", + b"module_id", + "pass_duration", + b"pass_duration", + "pass_name", + b"pass_name", + ], + ) -> None: ... + +global___PassMetrics = PassMetrics + +@typing.final +class JobInfo(google.protobuf.message.Message): + """Defines compilation job information.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + CELL_FIELD_NUMBER: builtins.int + USER_FIELD_NUMBER: builtins.int + UID_FIELD_NUMBER: builtins.int + TASK_ID_FIELD_NUMBER: builtins.int + TASK_UID_FIELD_NUMBER: builtins.int + name: builtins.str + """Name of the job running compilation.""" + cell: builtins.str + """Cell in which the job is running.""" + user: builtins.str + """User running the job.""" + uid: builtins.int + """Unique id when combined with user and cell field.""" + task_id: builtins.int + """Task index, which will not change across job restarts.""" + task_uid: builtins.int + """Task unique id, which may change across job restarts.""" + def __init__( + self, + *, + name: builtins.str | None = ..., + cell: builtins.str | None = ..., + user: builtins.str | None = ..., + uid: builtins.int | None = ..., + task_id: builtins.int | None = ..., + task_uid: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "_cell", + b"_cell", + "_name", + b"_name", + "_task_id", + b"_task_id", + "_task_uid", + b"_task_uid", + "_uid", + b"_uid", + "_user", + b"_user", + "cell", + b"cell", + "name", + b"name", + "task_id", + b"task_id", + "task_uid", + b"task_uid", + "uid", + b"uid", + "user", + b"user", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "_cell", + b"_cell", + "_name", + b"_name", + "_task_id", + b"_task_id", + "_task_uid", + b"_task_uid", + "_uid", + b"_uid", + "_user", + b"_user", + "cell", + b"cell", + "name", + b"name", + "task_id", + b"task_id", + "task_uid", + b"task_uid", + "uid", + b"uid", + "user", + b"user", + ], + ) -> None: ... + + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_cell", b"_cell"]) -> typing.Literal["cell"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_name", b"_name"]) -> typing.Literal["name"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_task_id", b"_task_id"]) -> typing.Literal["task_id"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_task_uid", b"_task_uid"]) -> typing.Literal["task_uid"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_uid", b"_uid"]) -> typing.Literal["uid"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_user", b"_user"]) -> typing.Literal["user"] | None: ... + +global___JobInfo = JobInfo + +@typing.final +class CompilationLogEntry(google.protobuf.message.Message): + """Defines XLA compilation metrics.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _CompilationStage: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CompilationStageEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[CompilationLogEntry._CompilationStage.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNSPECIFIED: CompilationLogEntry._CompilationStage.ValueType # 0 + END_TO_END: CompilationLogEntry._CompilationStage.ValueType # 1 + HLO_PASSES: CompilationLogEntry._CompilationStage.ValueType # 2 + CODE_GENERATION: CompilationLogEntry._CompilationStage.ValueType # 3 + BACKEND_PASSES: CompilationLogEntry._CompilationStage.ValueType # 4 + + class CompilationStage(_CompilationStage, metaclass=_CompilationStageEnumTypeWrapper): + """Defines compilation stages for which metrics are collected.""" + + UNSPECIFIED: CompilationLogEntry.CompilationStage.ValueType # 0 + END_TO_END: CompilationLogEntry.CompilationStage.ValueType # 1 + HLO_PASSES: CompilationLogEntry.CompilationStage.ValueType # 2 + CODE_GENERATION: CompilationLogEntry.CompilationStage.ValueType # 3 + BACKEND_PASSES: CompilationLogEntry.CompilationStage.ValueType # 4 + + TIMESTAMP_FIELD_NUMBER: builtins.int + STAGE_FIELD_NUMBER: builtins.int + DURATION_FIELD_NUMBER: builtins.int + TASK_INDEX_FIELD_NUMBER: builtins.int + PASS_METRICS_FIELD_NUMBER: builtins.int + MODULE_IDS_FIELD_NUMBER: builtins.int + JOB_INFO_FIELD_NUMBER: builtins.int + stage: global___CompilationLogEntry.CompilationStage.ValueType + """Compilation stage recorded by this log entry.""" + task_index: builtins.int + """Task index from which this log entry was recorded or + -1 if the task index could not be fetched. In the case task_index is not + equal to -1, it is guaranteed to match the task_id in job_info. + """ + @property + def timestamp(self) -> google.protobuf.timestamp_pb2.Timestamp: + """Time when the event captured by this log entry occurred.""" + + @property + def duration(self) -> google.protobuf.duration_pb2.Duration: + """Duration of the given compilation stage.""" + + @property + def pass_metrics(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PassMetrics]: + """Pass specific metrics.""" + + @property + def module_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """IDs of modules on which the compilation stage was run.""" + + @property + def job_info(self) -> global___JobInfo: + """Job information.""" + + def __init__( + self, + *, + timestamp: google.protobuf.timestamp_pb2.Timestamp | None = ..., + stage: global___CompilationLogEntry.CompilationStage.ValueType | None = ..., + duration: google.protobuf.duration_pb2.Duration | None = ..., + task_index: builtins.int | None = ..., + pass_metrics: collections.abc.Iterable[global___PassMetrics] | None = ..., + module_ids: collections.abc.Iterable[builtins.int] | None = ..., + job_info: global___JobInfo | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["duration", b"duration", "job_info", b"job_info", "timestamp", b"timestamp"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "duration", + b"duration", + "job_info", + b"job_info", + "module_ids", + b"module_ids", + "pass_metrics", + b"pass_metrics", + "stage", + b"stage", + "task_index", + b"task_index", + "timestamp", + b"timestamp", + ], + ) -> None: ... + +global___CompilationLogEntry = CompilationLogEntry diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi new file mode 100644 index 000000000000..6b3b31b94f3d --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi @@ -0,0 +1,59 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2022 The OpenXLA Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +============================================================================== +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class TestCompilationEnvironment1(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOME_FLAG_FIELD_NUMBER: builtins.int + some_flag: builtins.int + def __init__(self, *, some_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["some_flag", b"some_flag"]) -> None: ... + +global___TestCompilationEnvironment1 = TestCompilationEnvironment1 + +@typing.final +class TestCompilationEnvironment2(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOME_OTHER_FLAG_FIELD_NUMBER: builtins.int + some_other_flag: builtins.int + def __init__(self, *, some_other_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["some_other_flag", b"some_other_flag"]) -> None: ... + +global___TestCompilationEnvironment2 = TestCompilationEnvironment2 + +@typing.final +class TestCompilationEnvironment3(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + A_THIRD_FLAG_FIELD_NUMBER: builtins.int + a_third_flag: builtins.int + def __init__(self, *, a_third_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["a_third_flag", b"a_third_flag"]) -> None: ... + +global___TestCompilationEnvironment3 = TestCompilationEnvironment3 diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi new file mode 100644 index 000000000000..e17f9559b648 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi @@ -0,0 +1,167 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2023 The OpenXLA Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +============================================================================== +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.duration_pb2 +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.compiler.xla.service.hlo_pb2 +import tensorflow.tsl.protobuf.status_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CompilerPerfStats(google.protobuf.message.Message): + """Statistics on how long various parts of compilation took. + Not all durations may be relevant for all producers of this message, in + which irrelevant fields should simply be skipped. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INIT_DURATION_FIELD_NUMBER: builtins.int + HLO_VERIFICATION_DURATION_FIELD_NUMBER: builtins.int + COMPILATION_PROLOGUE_DURATION_FIELD_NUMBER: builtins.int + COMPILATION_DURATION_FIELD_NUMBER: builtins.int + TOTAL_DURATION_FIELD_NUMBER: builtins.int + @property + def init_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to initialize the compiler?""" + + @property + def hlo_verification_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to verify the HLO?""" + + @property + def compilation_prologue_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to prepare for compilation after verification?""" + + @property + def compilation_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to compile?""" + + @property + def total_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did everything take?""" + + def __init__( + self, + *, + init_duration: google.protobuf.duration_pb2.Duration | None = ..., + hlo_verification_duration: google.protobuf.duration_pb2.Duration | None = ..., + compilation_prologue_duration: google.protobuf.duration_pb2.Duration | None = ..., + compilation_duration: google.protobuf.duration_pb2.Duration | None = ..., + total_duration: google.protobuf.duration_pb2.Duration | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "compilation_duration", + b"compilation_duration", + "compilation_prologue_duration", + b"compilation_prologue_duration", + "hlo_verification_duration", + b"hlo_verification_duration", + "init_duration", + b"init_duration", + "total_duration", + b"total_duration", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_duration", + b"compilation_duration", + "compilation_prologue_duration", + b"compilation_prologue_duration", + "hlo_verification_duration", + b"hlo_verification_duration", + "init_duration", + b"init_duration", + "total_duration", + b"total_duration", + ], + ) -> None: ... + +global___CompilerPerfStats = CompilerPerfStats + +@typing.final +class CompilationResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class CountersEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + HLO_MODULE_FIELD_NUMBER: builtins.int + PERF_STATS_FIELD_NUMBER: builtins.int + STATUS_FIELD_NUMBER: builtins.int + COUNTERS_FIELD_NUMBER: builtins.int + @property + def hlo_module(self) -> tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto: + """The compiled HLO. Only set when compilation succeeds.""" + + @property + def perf_stats(self) -> global___CompilerPerfStats: + """Always set when compilation succeeds. May or may not be set when + compilation fails. + """ + + @property + def status(self) -> tensorflow.tsl.protobuf.status_pb2.StatusProto: + """Always set even when compilation succeeds.""" + + @property + def counters(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: + """Collects counters collected during compilation. Not every producer may + include counter support at all or any particular counter. + """ + + def __init__( + self, + *, + hlo_module: tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto | None = ..., + perf_stats: global___CompilerPerfStats | None = ..., + status: tensorflow.tsl.protobuf.status_pb2.StatusProto | None = ..., + counters: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["hlo_module", b"hlo_module", "perf_stats", b"perf_stats", "status", b"status"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "counters", b"counters", "hlo_module", b"hlo_module", "perf_stats", b"perf_stats", "status", b"status" + ], + ) -> None: ... + +global___CompilationResult = CompilationResult diff --git a/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi new file mode 100644 index 000000000000..0fe33b725b8e --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi @@ -0,0 +1,218 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class MemAllocatorStats(google.protobuf.message.Message): + """Some of the data from AllocatorStats""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NUM_ALLOCS_FIELD_NUMBER: builtins.int + BYTES_IN_USE_FIELD_NUMBER: builtins.int + PEAK_BYTES_IN_USE_FIELD_NUMBER: builtins.int + LARGEST_ALLOC_SIZE_FIELD_NUMBER: builtins.int + FRAGMENTATION_METRIC_FIELD_NUMBER: builtins.int + num_allocs: builtins.int + bytes_in_use: builtins.int + peak_bytes_in_use: builtins.int + largest_alloc_size: builtins.int + fragmentation_metric: builtins.float + def __init__( + self, + *, + num_allocs: builtins.int | None = ..., + bytes_in_use: builtins.int | None = ..., + peak_bytes_in_use: builtins.int | None = ..., + largest_alloc_size: builtins.int | None = ..., + fragmentation_metric: builtins.float | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bytes_in_use", + b"bytes_in_use", + "fragmentation_metric", + b"fragmentation_metric", + "largest_alloc_size", + b"largest_alloc_size", + "num_allocs", + b"num_allocs", + "peak_bytes_in_use", + b"peak_bytes_in_use", + ], + ) -> None: ... + +global___MemAllocatorStats = MemAllocatorStats + +@typing.final +class MemChunk(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ADDRESS_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + REQUESTED_SIZE_FIELD_NUMBER: builtins.int + BIN_FIELD_NUMBER: builtins.int + OP_NAME_FIELD_NUMBER: builtins.int + FREED_AT_COUNT_FIELD_NUMBER: builtins.int + ACTION_COUNT_FIELD_NUMBER: builtins.int + IN_USE_FIELD_NUMBER: builtins.int + STEP_ID_FIELD_NUMBER: builtins.int + address: builtins.int + size: builtins.int + requested_size: builtins.int + bin: builtins.int + op_name: builtins.str + freed_at_count: builtins.int + action_count: builtins.int + in_use: builtins.bool + step_id: builtins.int + def __init__( + self, + *, + address: builtins.int | None = ..., + size: builtins.int | None = ..., + requested_size: builtins.int | None = ..., + bin: builtins.int | None = ..., + op_name: builtins.str | None = ..., + freed_at_count: builtins.int | None = ..., + action_count: builtins.int | None = ..., + in_use: builtins.bool | None = ..., + step_id: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "action_count", + b"action_count", + "address", + b"address", + "bin", + b"bin", + "freed_at_count", + b"freed_at_count", + "in_use", + b"in_use", + "op_name", + b"op_name", + "requested_size", + b"requested_size", + "size", + b"size", + "step_id", + b"step_id", + ], + ) -> None: ... + +global___MemChunk = MemChunk + +@typing.final +class BinSummary(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BIN_FIELD_NUMBER: builtins.int + TOTAL_BYTES_IN_USE_FIELD_NUMBER: builtins.int + TOTAL_BYTES_IN_BIN_FIELD_NUMBER: builtins.int + TOTAL_CHUNKS_IN_USE_FIELD_NUMBER: builtins.int + TOTAL_CHUNKS_IN_BIN_FIELD_NUMBER: builtins.int + bin: builtins.int + total_bytes_in_use: builtins.int + total_bytes_in_bin: builtins.int + total_chunks_in_use: builtins.int + total_chunks_in_bin: builtins.int + def __init__( + self, + *, + bin: builtins.int | None = ..., + total_bytes_in_use: builtins.int | None = ..., + total_bytes_in_bin: builtins.int | None = ..., + total_chunks_in_use: builtins.int | None = ..., + total_chunks_in_bin: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bin", + b"bin", + "total_bytes_in_bin", + b"total_bytes_in_bin", + "total_bytes_in_use", + b"total_bytes_in_use", + "total_chunks_in_bin", + b"total_chunks_in_bin", + "total_chunks_in_use", + b"total_chunks_in_use", + ], + ) -> None: ... + +global___BinSummary = BinSummary + +@typing.final +class SnapShot(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTION_COUNT_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + action_count: builtins.int + size: builtins.int + def __init__(self, *, action_count: builtins.int | None = ..., size: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["action_count", b"action_count", "size", b"size"]) -> None: ... + +global___SnapShot = SnapShot + +@typing.final +class MemoryDump(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ALLOCATOR_NAME_FIELD_NUMBER: builtins.int + BIN_SUMMARY_FIELD_NUMBER: builtins.int + CHUNK_FIELD_NUMBER: builtins.int + SNAP_SHOT_FIELD_NUMBER: builtins.int + STATS_FIELD_NUMBER: builtins.int + allocator_name: builtins.str + @property + def bin_summary(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinSummary]: ... + @property + def chunk(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___MemChunk]: ... + @property + def snap_shot(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___SnapShot]: ... + @property + def stats(self) -> global___MemAllocatorStats: ... + def __init__( + self, + *, + allocator_name: builtins.str | None = ..., + bin_summary: collections.abc.Iterable[global___BinSummary] | None = ..., + chunk: collections.abc.Iterable[global___MemChunk] | None = ..., + snap_shot: collections.abc.Iterable[global___SnapShot] | None = ..., + stats: global___MemAllocatorStats | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["stats", b"stats"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "allocator_name", + b"allocator_name", + "bin_summary", + b"bin_summary", + "chunk", + b"chunk", + "snap_shot", + b"snap_shot", + "stats", + b"stats", + ], + ) -> None: ... + +global___MemoryDump = MemoryDump diff --git a/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi new file mode 100644 index 000000000000..a0cd6ef6a44b --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi @@ -0,0 +1,707 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing the results of benchmarks and unit tests.""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import google.protobuf.wrappers_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class EntryValue(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DOUBLE_VALUE_FIELD_NUMBER: builtins.int + STRING_VALUE_FIELD_NUMBER: builtins.int + double_value: builtins.float + string_value: builtins.str + def __init__(self, *, double_value: builtins.float | None = ..., string_value: builtins.str | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["double_value", b"double_value", "kind", b"kind", "string_value", b"string_value"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["double_value", b"double_value", "kind", b"kind", "string_value", b"string_value"] + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> typing.Literal["double_value", "string_value"] | None: ... + +global___EntryValue = EntryValue + +@typing.final +class MetricEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + MIN_VALUE_FIELD_NUMBER: builtins.int + MAX_VALUE_FIELD_NUMBER: builtins.int + name: builtins.str + """Metric name""" + value: builtins.float + """Metric value""" + @property + def min_value(self) -> google.protobuf.wrappers_pb2.DoubleValue: + """The minimum acceptable value for the metric if specified""" + + @property + def max_value(self) -> google.protobuf.wrappers_pb2.DoubleValue: + """The maximum acceptable value for the metric if specified""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + value: builtins.float | None = ..., + min_value: google.protobuf.wrappers_pb2.DoubleValue | None = ..., + max_value: google.protobuf.wrappers_pb2.DoubleValue | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["max_value", b"max_value", "min_value", b"min_value"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["max_value", b"max_value", "min_value", b"min_value", "name", b"name", "value", b"value"] + ) -> None: ... + +global___MetricEntry = MetricEntry + +@typing.final +class BenchmarkEntry(google.protobuf.message.Message): + """Each unit test or benchmark in a test or benchmark run provides + some set of information. Here we provide some reasonable keys + one would expect to see, with optional key/value pairs for things + we haven't considered. + + This BenchmarkEntry should be emitted by each unit test or benchmark + reporter. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ExtrasEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___EntryValue: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___EntryValue | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + ITERS_FIELD_NUMBER: builtins.int + CPU_TIME_FIELD_NUMBER: builtins.int + WALL_TIME_FIELD_NUMBER: builtins.int + THROUGHPUT_FIELD_NUMBER: builtins.int + EXTRAS_FIELD_NUMBER: builtins.int + METRICS_FIELD_NUMBER: builtins.int + name: builtins.str + """The name of the specific benchmark or test + (e.g. BM_AdjustContrast_gpu_B_W_H) + """ + iters: builtins.int + """If a benchmark, how many iterations it was run for""" + cpu_time: builtins.float + """Total cpu time used for all iterations (in seconds)""" + wall_time: builtins.float + """Total wall time used for all iterations (in seconds)""" + throughput: builtins.float + """Throughput (in MB/s)""" + @property + def extras(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___EntryValue]: + """Generic map from result key to value.""" + + @property + def metrics(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___MetricEntry]: + """Metric name, value and expected range. This can include accuracy metrics + typically used to determine whether the accuracy test has passed + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + iters: builtins.int | None = ..., + cpu_time: builtins.float | None = ..., + wall_time: builtins.float | None = ..., + throughput: builtins.float | None = ..., + extras: collections.abc.Mapping[builtins.str, global___EntryValue] | None = ..., + metrics: collections.abc.Iterable[global___MetricEntry] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "cpu_time", + b"cpu_time", + "extras", + b"extras", + "iters", + b"iters", + "metrics", + b"metrics", + "name", + b"name", + "throughput", + b"throughput", + "wall_time", + b"wall_time", + ], + ) -> None: ... + +global___BenchmarkEntry = BenchmarkEntry + +@typing.final +class BenchmarkEntries(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ENTRY_FIELD_NUMBER: builtins.int + @property + def entry(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BenchmarkEntry]: ... + def __init__(self, *, entry: collections.abc.Iterable[global___BenchmarkEntry] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["entry", b"entry"]) -> None: ... + +global___BenchmarkEntries = BenchmarkEntries + +@typing.final +class BuildConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MODE_FIELD_NUMBER: builtins.int + CC_FLAGS_FIELD_NUMBER: builtins.int + OPTS_FIELD_NUMBER: builtins.int + mode: builtins.str + """opt, dbg, etc""" + @property + def cc_flags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """CC compiler flags, if known""" + + @property + def opts(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Bazel compilation options, if known""" + + def __init__( + self, + *, + mode: builtins.str | None = ..., + cc_flags: collections.abc.Iterable[builtins.str] | None = ..., + opts: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["cc_flags", b"cc_flags", "mode", b"mode", "opts", b"opts"]) -> None: ... + +global___BuildConfiguration = BuildConfiguration + +@typing.final +class CommitId(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CHANGELIST_FIELD_NUMBER: builtins.int + HASH_FIELD_NUMBER: builtins.int + SNAPSHOT_FIELD_NUMBER: builtins.int + PENDING_CHANGELIST_FIELD_NUMBER: builtins.int + changelist: builtins.int + """Submitted changelist.""" + hash: builtins.str + snapshot: builtins.str + """Hash of intermediate change between hash/changelist and what was tested. + Not used if the build is from a commit without modifications. + """ + pending_changelist: builtins.int + """Changelist tested if the change list is not already submitted.""" + def __init__( + self, + *, + changelist: builtins.int | None = ..., + hash: builtins.str | None = ..., + snapshot: builtins.str | None = ..., + pending_changelist: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["changelist", b"changelist", "hash", b"hash", "kind", b"kind"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "changelist", + b"changelist", + "hash", + b"hash", + "kind", + b"kind", + "pending_changelist", + b"pending_changelist", + "snapshot", + b"snapshot", + ], + ) -> None: ... + def WhichOneof(self, oneof_group: typing.Literal["kind", b"kind"]) -> typing.Literal["changelist", "hash"] | None: ... + +global___CommitId = CommitId + +@typing.final +class CPUInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class CacheSizeEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + NUM_CORES_FIELD_NUMBER: builtins.int + NUM_CORES_ALLOWED_FIELD_NUMBER: builtins.int + MHZ_PER_CPU_FIELD_NUMBER: builtins.int + CPU_INFO_FIELD_NUMBER: builtins.int + CPU_GOVERNOR_FIELD_NUMBER: builtins.int + CACHE_SIZE_FIELD_NUMBER: builtins.int + num_cores: builtins.int + num_cores_allowed: builtins.int + mhz_per_cpu: builtins.float + """How fast are these cpus?""" + cpu_info: builtins.str + """Additional cpu information. For example, + Intel Ivybridge with HyperThreading (24 cores) dL1:32KB dL2:256KB dL3:30MB + """ + cpu_governor: builtins.str + """What kind of cpu scaling is enabled on the host. + Examples include "performance", "ondemand", "conservative", "mixed". + """ + @property + def cache_size(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: + """Cache sizes (in bytes), e.g. "L2": 262144 (for 256KB)""" + + def __init__( + self, + *, + num_cores: builtins.int | None = ..., + num_cores_allowed: builtins.int | None = ..., + mhz_per_cpu: builtins.float | None = ..., + cpu_info: builtins.str | None = ..., + cpu_governor: builtins.str | None = ..., + cache_size: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "cache_size", + b"cache_size", + "cpu_governor", + b"cpu_governor", + "cpu_info", + b"cpu_info", + "mhz_per_cpu", + b"mhz_per_cpu", + "num_cores", + b"num_cores", + "num_cores_allowed", + b"num_cores_allowed", + ], + ) -> None: ... + +global___CPUInfo = CPUInfo + +@typing.final +class MemoryInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TOTAL_FIELD_NUMBER: builtins.int + AVAILABLE_FIELD_NUMBER: builtins.int + total: builtins.int + """Total virtual memory in bytes""" + available: builtins.int + """Immediately available memory in bytes""" + def __init__(self, *, total: builtins.int | None = ..., available: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["available", b"available", "total", b"total"]) -> None: ... + +global___MemoryInfo = MemoryInfo + +@typing.final +class GPUInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MODEL_FIELD_NUMBER: builtins.int + UUID_FIELD_NUMBER: builtins.int + BUS_ID_FIELD_NUMBER: builtins.int + model: builtins.str + """e.g. "Tesla K40c" """ + uuid: builtins.str + """Final entry in output of "nvidia-smi -L" """ + bus_id: builtins.str + """e.g. "0000:04:00.0" """ + def __init__( + self, *, model: builtins.str | None = ..., uuid: builtins.str | None = ..., bus_id: builtins.str | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["bus_id", b"bus_id", "model", b"model", "uuid", b"uuid"]) -> None: ... + +global___GPUInfo = GPUInfo + +@typing.final +class PlatformInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BITS_FIELD_NUMBER: builtins.int + LINKAGE_FIELD_NUMBER: builtins.int + MACHINE_FIELD_NUMBER: builtins.int + RELEASE_FIELD_NUMBER: builtins.int + SYSTEM_FIELD_NUMBER: builtins.int + VERSION_FIELD_NUMBER: builtins.int + bits: builtins.str + """e.g. '64bit'""" + linkage: builtins.str + """e.g. 'ELF'""" + machine: builtins.str + """e.g. 'i386'""" + release: builtins.str + """e.g. '3.13.0-76-generic'""" + system: builtins.str + """e.g. 'Linux'""" + version: builtins.str + """e.g. '#120-Ubuntu SMP Mon Jan 18 15:59:10 UTC 2016'""" + def __init__( + self, + *, + bits: builtins.str | None = ..., + linkage: builtins.str | None = ..., + machine: builtins.str | None = ..., + release: builtins.str | None = ..., + system: builtins.str | None = ..., + version: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bits", + b"bits", + "linkage", + b"linkage", + "machine", + b"machine", + "release", + b"release", + "system", + b"system", + "version", + b"version", + ], + ) -> None: ... + +global___PlatformInfo = PlatformInfo + +@typing.final +class AvailableDeviceInfo(google.protobuf.message.Message): + """Matches DeviceAttributes""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + MEMORY_LIMIT_FIELD_NUMBER: builtins.int + PHYSICAL_DESCRIPTION_FIELD_NUMBER: builtins.int + name: builtins.str + """Device name.""" + type: builtins.str + """Device type, e.g. 'CPU' or 'GPU'.""" + memory_limit: builtins.int + """Memory capacity in bytes.""" + physical_description: builtins.str + """The physical description of this device.""" + def __init__( + self, + *, + name: builtins.str | None = ..., + type: builtins.str | None = ..., + memory_limit: builtins.int | None = ..., + physical_description: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "memory_limit", b"memory_limit", "name", b"name", "physical_description", b"physical_description", "type", b"type" + ], + ) -> None: ... + +global___AvailableDeviceInfo = AvailableDeviceInfo + +@typing.final +class MachineConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HOSTNAME_FIELD_NUMBER: builtins.int + SERIAL_IDENTIFIER_FIELD_NUMBER: builtins.int + PLATFORM_INFO_FIELD_NUMBER: builtins.int + CPU_INFO_FIELD_NUMBER: builtins.int + DEVICE_INFO_FIELD_NUMBER: builtins.int + AVAILABLE_DEVICE_INFO_FIELD_NUMBER: builtins.int + MEMORY_INFO_FIELD_NUMBER: builtins.int + hostname: builtins.str + """Host name of machine that ran the benchmark.""" + serial_identifier: builtins.str + """Unique serial number of the machine.""" + @property + def platform_info(self) -> global___PlatformInfo: + """Additional platform information.""" + + @property + def cpu_info(self) -> global___CPUInfo: + """CPU Information.""" + + @property + def device_info(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.any_pb2.Any]: + """Other devices that are attached and relevant (e.g. GPUInfo).""" + + @property + def available_device_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___AvailableDeviceInfo]: + """Devices accessible to the test (e.g. as given by list_local_devices).""" + + @property + def memory_info(self) -> global___MemoryInfo: ... + def __init__( + self, + *, + hostname: builtins.str | None = ..., + serial_identifier: builtins.str | None = ..., + platform_info: global___PlatformInfo | None = ..., + cpu_info: global___CPUInfo | None = ..., + device_info: collections.abc.Iterable[google.protobuf.any_pb2.Any] | None = ..., + available_device_info: collections.abc.Iterable[global___AvailableDeviceInfo] | None = ..., + memory_info: global___MemoryInfo | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["cpu_info", b"cpu_info", "memory_info", b"memory_info", "platform_info", b"platform_info"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "available_device_info", + b"available_device_info", + "cpu_info", + b"cpu_info", + "device_info", + b"device_info", + "hostname", + b"hostname", + "memory_info", + b"memory_info", + "platform_info", + b"platform_info", + "serial_identifier", + b"serial_identifier", + ], + ) -> None: ... + +global___MachineConfiguration = MachineConfiguration + +@typing.final +class RunConfiguration(google.protobuf.message.Message): + """Run-specific items such as arguments to the test / benchmark.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class EnvVarsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.str + def __init__(self, *, key: builtins.str | None = ..., value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + ARGUMENT_FIELD_NUMBER: builtins.int + ENV_VARS_FIELD_NUMBER: builtins.int + @property + def argument(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + @property + def env_vars(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.str]: + """Environment variables used to run the test/benchmark.""" + + def __init__( + self, + *, + argument: collections.abc.Iterable[builtins.str] | None = ..., + env_vars: collections.abc.Mapping[builtins.str, builtins.str] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["argument", b"argument", "env_vars", b"env_vars"]) -> None: ... + +global___RunConfiguration = RunConfiguration + +@typing.final +class TestResults(google.protobuf.message.Message): + """The output of one benchmark / test run. Each run contains a list of + tests or benchmarks, stored as BenchmarkEntry messages. + + This message should be emitted by the reporter (which runs the + test / BM in a subprocess and then reads the emitted BenchmarkEntry messages; + usually from a serialized json file, finally collecting them along + with additional information about the test run. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _BenchmarkType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _BenchmarkTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[TestResults._BenchmarkType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNKNOWN: TestResults._BenchmarkType.ValueType # 0 + """Fallback for protos written before Type was introduced.""" + CPP_MICROBENCHMARK: TestResults._BenchmarkType.ValueType # 1 + PYTHON_BENCHMARK: TestResults._BenchmarkType.ValueType # 2 + ANDROID_BENCHMARK: TestResults._BenchmarkType.ValueType # 3 + EDGE_BENCHMARK: TestResults._BenchmarkType.ValueType # 4 + IOS_BENCHMARK: TestResults._BenchmarkType.ValueType # 5 + + class BenchmarkType(_BenchmarkType, metaclass=_BenchmarkTypeEnumTypeWrapper): + """The type of benchmark.""" + + UNKNOWN: TestResults.BenchmarkType.ValueType # 0 + """Fallback for protos written before Type was introduced.""" + CPP_MICROBENCHMARK: TestResults.BenchmarkType.ValueType # 1 + PYTHON_BENCHMARK: TestResults.BenchmarkType.ValueType # 2 + ANDROID_BENCHMARK: TestResults.BenchmarkType.ValueType # 3 + EDGE_BENCHMARK: TestResults.BenchmarkType.ValueType # 4 + IOS_BENCHMARK: TestResults.BenchmarkType.ValueType # 5 + + TARGET_FIELD_NUMBER: builtins.int + ENTRIES_FIELD_NUMBER: builtins.int + BUILD_CONFIGURATION_FIELD_NUMBER: builtins.int + COMMIT_ID_FIELD_NUMBER: builtins.int + START_TIME_FIELD_NUMBER: builtins.int + RUN_TIME_FIELD_NUMBER: builtins.int + MACHINE_CONFIGURATION_FIELD_NUMBER: builtins.int + RUN_CONFIGURATION_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + BENCHMARK_TYPE_FIELD_NUMBER: builtins.int + RUN_MODE_FIELD_NUMBER: builtins.int + TF_VERSION_FIELD_NUMBER: builtins.int + target: builtins.str + """The target of the run, e.g.: + //tensorflow/core:kernels_adjust_contrast_op_benchmark_test + """ + start_time: builtins.int + """The time the run started (in seconds of UTC time since Unix epoch)""" + run_time: builtins.float + """The amount of time the total run took (wall time in seconds)""" + name: builtins.str + """Benchmark target identifier.""" + benchmark_type: global___TestResults.BenchmarkType.ValueType + run_mode: builtins.str + """Used for differentiating between continuous and debug builds. + Must be one of: + * cbuild: results from continuous build. + * presubmit: results from oneshot requests. + * culprit: results from culprit finder rerun. + """ + tf_version: builtins.str + """TensorFlow version this benchmark runs against. + This can be either set to full version or just the major version. + """ + @property + def entries(self) -> global___BenchmarkEntries: + """The list of tests or benchmarks in this run.""" + + @property + def build_configuration(self) -> global___BuildConfiguration: + """The configuration of the build (compiled opt? with cuda? any copts?)""" + + @property + def commit_id(self) -> global___CommitId: + """The commit id (git hash or changelist)""" + + @property + def machine_configuration(self) -> global___MachineConfiguration: + """Machine-specific parameters (Platform and CPU info)""" + + @property + def run_configuration(self) -> global___RunConfiguration: + """Run-specific parameters (arguments, etc)""" + + def __init__( + self, + *, + target: builtins.str | None = ..., + entries: global___BenchmarkEntries | None = ..., + build_configuration: global___BuildConfiguration | None = ..., + commit_id: global___CommitId | None = ..., + start_time: builtins.int | None = ..., + run_time: builtins.float | None = ..., + machine_configuration: global___MachineConfiguration | None = ..., + run_configuration: global___RunConfiguration | None = ..., + name: builtins.str | None = ..., + benchmark_type: global___TestResults.BenchmarkType.ValueType | None = ..., + run_mode: builtins.str | None = ..., + tf_version: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "build_configuration", + b"build_configuration", + "commit_id", + b"commit_id", + "entries", + b"entries", + "machine_configuration", + b"machine_configuration", + "run_configuration", + b"run_configuration", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "benchmark_type", + b"benchmark_type", + "build_configuration", + b"build_configuration", + "commit_id", + b"commit_id", + "entries", + b"entries", + "machine_configuration", + b"machine_configuration", + "name", + b"name", + "run_configuration", + b"run_configuration", + "run_mode", + b"run_mode", + "run_time", + b"run_time", + "start_time", + b"start_time", + "target", + b"target", + "tf_version", + b"tf_version", + ], + ) -> None: ... + +global___TestResults = TestResults diff --git a/stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi new file mode 100644 index 000000000000..de86f1c8f255 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi @@ -0,0 +1,2681 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2017 The OpenXLA Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +============================================================================== +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _PrimitiveType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _PrimitiveTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_PrimitiveType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PRIMITIVE_TYPE_INVALID: _PrimitiveType.ValueType # 0 + """Invalid primitive type to serve as default.""" + PRED: _PrimitiveType.ValueType # 1 + """Predicates are two-state booleans.""" + S2: _PrimitiveType.ValueType # 26 + """Signed integral values of fixed width.""" + S4: _PrimitiveType.ValueType # 21 + S8: _PrimitiveType.ValueType # 2 + S16: _PrimitiveType.ValueType # 3 + S32: _PrimitiveType.ValueType # 4 + S64: _PrimitiveType.ValueType # 5 + U2: _PrimitiveType.ValueType # 27 + """Unsigned integral values of fixed width.""" + U4: _PrimitiveType.ValueType # 22 + U8: _PrimitiveType.ValueType # 6 + U16: _PrimitiveType.ValueType # 7 + U32: _PrimitiveType.ValueType # 8 + U64: _PrimitiveType.ValueType # 9 + F16: _PrimitiveType.ValueType # 10 + """Floating-point values of fixed width. + + Note: if f16s are not natively supported on the device, they will be + converted to f16 from f32 at arbirary points in the computation. + """ + F32: _PrimitiveType.ValueType # 11 + BF16: _PrimitiveType.ValueType # 16 + """Truncated 16 bit floating-point format. This is similar to IEEE's 16 bit + floating-point format, but uses 1 bit for the sign, 8 bits for the exponent + and 7 bits for the mantissa. + """ + F64: _PrimitiveType.ValueType # 12 + F8E5M2: _PrimitiveType.ValueType # 19 + """FP8 dtypes, as described in this paper: https://arxiv.org/abs/2209.05433 + + F8E5M2 has 5 exponent bits and 2 mantissa bits, and is similar to the + existing IEEE types. + + F8E4M3FN has 4 exponent bits and 3 mantissa bits. The "FN" means only + Finite and NaN values are supported. Unlike IEEE types, infinities are not + supported. NaN is represented when the exponent and mantissa bits are all + 1s. All other values are finite. + + F8E4M3B11FNUZ has 4 exponent bits and 3 mantissa bits and a bias of 11. The + "FNUZ" means only Finite and NaN values are supported; zero is unsigned. + Unlike IEEE types, infinities are not supported. NaN is represented when + the exponent and mantissa bits are all 0s with a sign bit of 1. All other + values are finite. + + Support for these dtypes is under development. They do not yet work + properly in most cases. + TODO(b/259609697): Fully support FP8. + """ + F8E4M3FN: _PrimitiveType.ValueType # 20 + F8E4M3B11FNUZ: _PrimitiveType.ValueType # 23 + F8E5M2FNUZ: _PrimitiveType.ValueType # 24 + """FP8 dtypes, as described in this paper: https://arxiv.org/abs/2206.02915 + + F8E5M2FNUZ has 5 exponent bits and 2 mantissa bits. + F8E4M3FNUZ has 4 exponent bits and 3 mantissa bits. + + The "FNUZ" means only Finite and NaN values are supported; zero is + unsigned. Unlike IEEE types, infinities are not supported. NaN is + represented when the exponent and mantissa bits are all 0s with a sign bit + of 1. All other values are finite. + + These differences mean there's an additional exponent value available. To + keep the same dynamic range as an IEEE-like FP8 type, the exponent is + biased one more than would be expected given the number of exponent bits + (8 for Float8E4M3FNUZ and 16 for Float8E5M2FNUZ). + """ + F8E4M3FNUZ: _PrimitiveType.ValueType # 25 + C64: _PrimitiveType.ValueType # 15 + """Complex values of fixed width. + Paired F32 (real, imag), as in std::complex. + """ + C128: _PrimitiveType.ValueType # 18 + """Paired F64 (real, imag), as in std::complex.""" + TUPLE: _PrimitiveType.ValueType # 13 + """A tuple is a polymorphic sequence; e.g. a shape that holds different + sub-shapes. They are used for things like returning multiple values from a + computation; e.g. a computation that returns weights and biases may have a + signature that results in a tuple like (f32[784x2000], f32[2000]) + + If a shape proto has the tuple element type, it may not have any entries + in the dimensions field. + """ + OPAQUE_TYPE: _PrimitiveType.ValueType # 14 + """An opaque type used for passing context-specific data to a custom + operation. Shapes of this primitive type will have empty dimensions and + tuple_shapes fields. + + (OPAQUE would be a better name for this identifier, but that conflicts with + a macro defined in windows.h.) + """ + TOKEN: _PrimitiveType.ValueType # 17 + """A token type threaded between side-effecting operations. Shapes of this + primitive type will have empty dimensions and tuple_shapes fields. + """ + +class PrimitiveType(_PrimitiveType, metaclass=_PrimitiveTypeEnumTypeWrapper): + """Primitive types are the individual values that can be held in rectangular + multidimensional arrays. A description of the rectangular multidimensional + array dimensions / primitive type is given by Shape, below. + + LINT.IfChange + """ + +PRIMITIVE_TYPE_INVALID: PrimitiveType.ValueType # 0 +"""Invalid primitive type to serve as default.""" +PRED: PrimitiveType.ValueType # 1 +"""Predicates are two-state booleans.""" +S2: PrimitiveType.ValueType # 26 +"""Signed integral values of fixed width.""" +S4: PrimitiveType.ValueType # 21 +S8: PrimitiveType.ValueType # 2 +S16: PrimitiveType.ValueType # 3 +S32: PrimitiveType.ValueType # 4 +S64: PrimitiveType.ValueType # 5 +U2: PrimitiveType.ValueType # 27 +"""Unsigned integral values of fixed width.""" +U4: PrimitiveType.ValueType # 22 +U8: PrimitiveType.ValueType # 6 +U16: PrimitiveType.ValueType # 7 +U32: PrimitiveType.ValueType # 8 +U64: PrimitiveType.ValueType # 9 +F16: PrimitiveType.ValueType # 10 +"""Floating-point values of fixed width. + +Note: if f16s are not natively supported on the device, they will be +converted to f16 from f32 at arbirary points in the computation. +""" +F32: PrimitiveType.ValueType # 11 +BF16: PrimitiveType.ValueType # 16 +"""Truncated 16 bit floating-point format. This is similar to IEEE's 16 bit +floating-point format, but uses 1 bit for the sign, 8 bits for the exponent +and 7 bits for the mantissa. +""" +F64: PrimitiveType.ValueType # 12 +F8E5M2: PrimitiveType.ValueType # 19 +"""FP8 dtypes, as described in this paper: https://arxiv.org/abs/2209.05433 + +F8E5M2 has 5 exponent bits and 2 mantissa bits, and is similar to the +existing IEEE types. + +F8E4M3FN has 4 exponent bits and 3 mantissa bits. The "FN" means only +Finite and NaN values are supported. Unlike IEEE types, infinities are not +supported. NaN is represented when the exponent and mantissa bits are all +1s. All other values are finite. + +F8E4M3B11FNUZ has 4 exponent bits and 3 mantissa bits and a bias of 11. The +"FNUZ" means only Finite and NaN values are supported; zero is unsigned. +Unlike IEEE types, infinities are not supported. NaN is represented when +the exponent and mantissa bits are all 0s with a sign bit of 1. All other +values are finite. + +Support for these dtypes is under development. They do not yet work +properly in most cases. +TODO(b/259609697): Fully support FP8. +""" +F8E4M3FN: PrimitiveType.ValueType # 20 +F8E4M3B11FNUZ: PrimitiveType.ValueType # 23 +F8E5M2FNUZ: PrimitiveType.ValueType # 24 +"""FP8 dtypes, as described in this paper: https://arxiv.org/abs/2206.02915 + +F8E5M2FNUZ has 5 exponent bits and 2 mantissa bits. +F8E4M3FNUZ has 4 exponent bits and 3 mantissa bits. + +The "FNUZ" means only Finite and NaN values are supported; zero is +unsigned. Unlike IEEE types, infinities are not supported. NaN is +represented when the exponent and mantissa bits are all 0s with a sign bit +of 1. All other values are finite. + +These differences mean there's an additional exponent value available. To +keep the same dynamic range as an IEEE-like FP8 type, the exponent is +biased one more than would be expected given the number of exponent bits +(8 for Float8E4M3FNUZ and 16 for Float8E5M2FNUZ). +""" +F8E4M3FNUZ: PrimitiveType.ValueType # 25 +C64: PrimitiveType.ValueType # 15 +"""Complex values of fixed width. +Paired F32 (real, imag), as in std::complex. +""" +C128: PrimitiveType.ValueType # 18 +"""Paired F64 (real, imag), as in std::complex.""" +TUPLE: PrimitiveType.ValueType # 13 +"""A tuple is a polymorphic sequence; e.g. a shape that holds different +sub-shapes. They are used for things like returning multiple values from a +computation; e.g. a computation that returns weights and biases may have a +signature that results in a tuple like (f32[784x2000], f32[2000]) + +If a shape proto has the tuple element type, it may not have any entries +in the dimensions field. +""" +OPAQUE_TYPE: PrimitiveType.ValueType # 14 +"""An opaque type used for passing context-specific data to a custom +operation. Shapes of this primitive type will have empty dimensions and +tuple_shapes fields. + +(OPAQUE would be a better name for this identifier, but that conflicts with +a macro defined in windows.h.) +""" +TOKEN: PrimitiveType.ValueType # 17 +"""A token type threaded between side-effecting operations. Shapes of this +primitive type will have empty dimensions and tuple_shapes fields. +""" +global___PrimitiveType = PrimitiveType + +class _DimLevelType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DimLevelTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_DimLevelType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DIM_DENSE: _DimLevelType.ValueType # 0 + """The corresponding dimension is Dense, every entry is stored.""" + DIM_COMPRESSED: _DimLevelType.ValueType # 1 + """The corresponding dimension is Compressed, only nonzeros are stored.""" + DIM_SINGLETON: _DimLevelType.ValueType # 2 + """The corresponding dimension contains a single coordinate, no sibling + elements for each parent. + """ + DIM_LOOSE_COMPRESSED: _DimLevelType.ValueType # 3 + """The corresponding dimension is Compressed, but with potential trailing + zeros, thus an extra upper bound (high) is used to exclude those zeros. + E.g., indices = [1, 2, 0, 0, 3, 4, 0, 0], position = [(0, 2), (4, 6)]. + """ + +class DimLevelType(_DimLevelType, metaclass=_DimLevelTypeEnumTypeWrapper): + """A DimLevelType indicates the encoding method for a dimension in an array. + The semantics of this field are identical to those of the MLIR SparseTensor + dialect. + This should be kept in sync with the SparseTensor DimLevelType enum: + https://github.com/llvm/llvm-project/blob/5674a3c88088e668b684326c2194a6282e8270ff/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td#L86 + """ + +DIM_DENSE: DimLevelType.ValueType # 0 +"""The corresponding dimension is Dense, every entry is stored.""" +DIM_COMPRESSED: DimLevelType.ValueType # 1 +"""The corresponding dimension is Compressed, only nonzeros are stored.""" +DIM_SINGLETON: DimLevelType.ValueType # 2 +"""The corresponding dimension contains a single coordinate, no sibling +elements for each parent. +""" +DIM_LOOSE_COMPRESSED: DimLevelType.ValueType # 3 +"""The corresponding dimension is Compressed, but with potential trailing +zeros, thus an extra upper bound (high) is used to exclude those zeros. +E.g., indices = [1, 2, 0, 0, 3, 4, 0, 0], position = [(0, 2), (4, 6)]. +""" +global___DimLevelType = DimLevelType + +class _ProfileType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ProfileTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ProfileType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + INVALID: _ProfileType.ValueType # 0 + WINDOW: _ProfileType.ValueType # 1 + FLAG: _ProfileType.ValueType # 2 + INTEGER: _ProfileType.ValueType # 3 + +class ProfileType(_ProfileType, metaclass=_ProfileTypeEnumTypeWrapper): + """The type optimization profiles in use for Op-level optimizations.""" + +INVALID: ProfileType.ValueType # 0 +WINDOW: ProfileType.ValueType # 1 +FLAG: ProfileType.ValueType # 2 +INTEGER: ProfileType.ValueType # 3 +global___ProfileType = ProfileType + +class _ProfileSource: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ProfileSourceEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ProfileSource.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PROFILE_SOURCE_UNKNOWN_SOURCE: _ProfileSource.ValueType # 0 + PROFILE_SOURCE_EMBEDDED: _ProfileSource.ValueType # 1 + PROFILE_SOURCE_REMOTE: _ProfileSource.ValueType # 2 + +class ProfileSource(_ProfileSource, metaclass=_ProfileSourceEnumTypeWrapper): + """The source of the optimization profile.""" + +PROFILE_SOURCE_UNKNOWN_SOURCE: ProfileSource.ValueType # 0 +PROFILE_SOURCE_EMBEDDED: ProfileSource.ValueType # 1 +PROFILE_SOURCE_REMOTE: ProfileSource.ValueType # 2 +global___ProfileSource = ProfileSource + +class _CompilationEvent: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CompilationEventEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CompilationEvent.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + COMPILATION_EVENT_UNKNOWN_EVENT: _CompilationEvent.ValueType # 0 + COMPILATION_EVENT_FIRST_COMPILATION: _CompilationEvent.ValueType # 1 + COMPILATION_EVENT_RECOMPILATION: _CompilationEvent.ValueType # 2 + +class CompilationEvent(_CompilationEvent, metaclass=_CompilationEventEnumTypeWrapper): + """The compilation event that triggered the use of the profile.""" + +COMPILATION_EVENT_UNKNOWN_EVENT: CompilationEvent.ValueType # 0 +COMPILATION_EVENT_FIRST_COMPILATION: CompilationEvent.ValueType # 1 +COMPILATION_EVENT_RECOMPILATION: CompilationEvent.ValueType # 2 +global___CompilationEvent = CompilationEvent + +class _PaddingType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _PaddingTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_PaddingType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PADDING_INVALID: _PaddingType.ValueType # 0 + PADDING_VALID: _PaddingType.ValueType # 1 + """Only valid portion of the base are covered.""" + PADDING_SAME: _PaddingType.ValueType # 2 + """Extra is added to produce same output size as the input.""" + +class PaddingType(_PaddingType, metaclass=_PaddingTypeEnumTypeWrapper): ... + +PADDING_INVALID: PaddingType.ValueType # 0 +PADDING_VALID: PaddingType.ValueType # 1 +"""Only valid portion of the base are covered.""" +PADDING_SAME: PaddingType.ValueType # 2 +"""Extra is added to produce same output size as the input.""" +global___PaddingType = PaddingType + +class _FftType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _FftTypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_FftType.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + FFT: _FftType.ValueType # 0 + """Forward FFT; complex in, complex out.""" + IFFT: _FftType.ValueType # 1 + """Inverse FFT; complex in, complex out.""" + RFFT: _FftType.ValueType # 2 + """Forward real FFT; real in, fft_length / 2 + 1 complex out""" + IRFFT: _FftType.ValueType # 3 + """Inverse real FFT; fft_length / 2 + 1 complex in,""" + +class FftType(_FftType, metaclass=_FftTypeEnumTypeWrapper): ... + +FFT: FftType.ValueType # 0 +"""Forward FFT; complex in, complex out.""" +IFFT: FftType.ValueType # 1 +"""Inverse FFT; complex in, complex out.""" +RFFT: FftType.ValueType # 2 +"""Forward real FFT; real in, fft_length / 2 + 1 complex out""" +IRFFT: FftType.ValueType # 3 +"""Inverse real FFT; fft_length / 2 + 1 complex in,""" +global___FftType = FftType + +class _SparsityType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _SparsityTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_SparsityType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SPARSITY_INVALID: _SparsityType.ValueType # 0 + SPARSITY_STRUCTURED_N_M: _SparsityType.ValueType # 1 + """Structured N:M sparsity.""" + +class SparsityType(_SparsityType, metaclass=_SparsityTypeEnumTypeWrapper): ... + +SPARSITY_INVALID: SparsityType.ValueType # 0 +SPARSITY_STRUCTURED_N_M: SparsityType.ValueType # 1 +"""Structured N:M sparsity.""" +global___SparsityType = SparsityType + +class _RandomDistribution: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _RandomDistributionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_RandomDistribution.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RNG_INVALID: _RandomDistribution.ValueType # 0 + RNG_UNIFORM: _RandomDistribution.ValueType # 1 + """Creates a uniform-distribution-generated random number on the semi-open + interval [parameter[0], parameter[1]). + """ + RNG_NORMAL: _RandomDistribution.ValueType # 2 + """Creates a normal-distribution-generated random number with mean + parameter[0] and standard deviation parameter[1]. + """ + +class RandomDistribution(_RandomDistribution, metaclass=_RandomDistributionEnumTypeWrapper): ... + +RNG_INVALID: RandomDistribution.ValueType # 0 +RNG_UNIFORM: RandomDistribution.ValueType # 1 +"""Creates a uniform-distribution-generated random number on the semi-open +interval [parameter[0], parameter[1]). +""" +RNG_NORMAL: RandomDistribution.ValueType # 2 +"""Creates a normal-distribution-generated random number with mean +parameter[0] and standard deviation parameter[1]. +""" +global___RandomDistribution = RandomDistribution + +class _RandomAlgorithm: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _RandomAlgorithmEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_RandomAlgorithm.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RNG_DEFAULT: _RandomAlgorithm.ValueType # 0 + """Backend dependent default algorithm.""" + RNG_THREE_FRY: _RandomAlgorithm.ValueType # 1 + RNG_PHILOX: _RandomAlgorithm.ValueType # 2 + """Next: 2""" + +class RandomAlgorithm(_RandomAlgorithm, metaclass=_RandomAlgorithmEnumTypeWrapper): ... + +RNG_DEFAULT: RandomAlgorithm.ValueType # 0 +"""Backend dependent default algorithm.""" +RNG_THREE_FRY: RandomAlgorithm.ValueType # 1 +RNG_PHILOX: RandomAlgorithm.ValueType # 2 +"""Next: 2""" +global___RandomAlgorithm = RandomAlgorithm + +@typing.final +class PaddingConfig(google.protobuf.message.Message): + """Describes the padding configuration for Pad operation. The padding amount on + both edges as well as between the elements are specified for each dimension. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class PaddingConfigDimension(google.protobuf.message.Message): + """Describes the padding configuration for a dimension.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDGE_PADDING_LOW_FIELD_NUMBER: builtins.int + EDGE_PADDING_HIGH_FIELD_NUMBER: builtins.int + INTERIOR_PADDING_FIELD_NUMBER: builtins.int + edge_padding_low: builtins.int + """Padding amount on the low-end (next to the index 0). May be negative.""" + edge_padding_high: builtins.int + """Padding amount on the high-end (next to the highest index). May be + negative. + """ + interior_padding: builtins.int + """Padding amount between the elements. May not be negative.""" + def __init__( + self, + *, + edge_padding_low: builtins.int | None = ..., + edge_padding_high: builtins.int | None = ..., + interior_padding: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "edge_padding_high", + b"edge_padding_high", + "edge_padding_low", + b"edge_padding_low", + "interior_padding", + b"interior_padding", + ], + ) -> None: ... + + DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def dimensions( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PaddingConfig.PaddingConfigDimension]: + """The padding configuration for all dimensions.""" + + def __init__( + self, *, dimensions: collections.abc.Iterable[global___PaddingConfig.PaddingConfigDimension] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["dimensions", b"dimensions"]) -> None: ... + +global___PaddingConfig = PaddingConfig + +@typing.final +class TileProto(google.protobuf.message.Message): + """Describes a tile used in tiling-based layout. Refer to + g3doc/third_party/xla/docs/tiled_layout.md for details about tiling-based + layout. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Number of elements in each dimension of the tile. It's ordered from the + most major dimension of the tile to the most minor dimension of the tile. + The dimensions correspond to a suffix of the dimensions of the shape being + tiled. + """ + + def __init__(self, *, dimensions: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dimensions", b"dimensions"]) -> None: ... + +global___TileProto = TileProto + +@typing.final +class SplitConfigProto(google.protobuf.message.Message): + """Describes how data should be split between different memories.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIMENSION_FIELD_NUMBER: builtins.int + SPLIT_INDICES_FIELD_NUMBER: builtins.int + dimension: builtins.int + """The dimension that is split.""" + @property + def split_indices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The indices where each split point occurs. For example, if the dimension + size is 1024, a split_indices value of {512} indicates a two-way split of + data through the middle. + """ + + def __init__( + self, *, dimension: builtins.int | None = ..., split_indices: collections.abc.Iterable[builtins.int] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["dimension", b"dimension", "split_indices", b"split_indices"]) -> None: ... + +global___SplitConfigProto = SplitConfigProto + +@typing.final +class LayoutProto(google.protobuf.message.Message): + """A layout describes how the array is placed in (1D) memory space. This + includes the minor-to-major ordering of dimensions within a shape. + + Clients must specify the layouts of input Literals to the + computation. Layouts specified in interior operations which take Shapes (for + example, Convert) are ignored. + + See the XLA documentation for more information on shapes and layouts. + + LINT.IfChange + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIM_LEVEL_TYPES_FIELD_NUMBER: builtins.int + DIM_UNIQUE_FIELD_NUMBER: builtins.int + DIM_ORDERED_FIELD_NUMBER: builtins.int + MINOR_TO_MAJOR_FIELD_NUMBER: builtins.int + TILES_FIELD_NUMBER: builtins.int + TAIL_PADDING_ALIGNMENT_IN_ELEMENTS_FIELD_NUMBER: builtins.int + ELEMENT_SIZE_IN_BITS_FIELD_NUMBER: builtins.int + MEMORY_SPACE_FIELD_NUMBER: builtins.int + INDEX_PRIMITIVE_TYPE_FIELD_NUMBER: builtins.int + POINTER_PRIMITIVE_TYPE_FIELD_NUMBER: builtins.int + PHYSICAL_SHAPE_FIELD_NUMBER: builtins.int + DYNAMIC_SHAPE_METADATA_PREFIX_BYTES_FIELD_NUMBER: builtins.int + SPLIT_CONFIGS_FIELD_NUMBER: builtins.int + tail_padding_alignment_in_elements: builtins.int + """The shape is padded at the end to multiple of, in terms of number of + elements. This is useful when tiling does not bring the shape to certain + desired granules. Tiling effectively pads/reshapes/transposes the shape + to another shape. This field pads the total number of elements of that + new shape to a multiple of certain number of elements. This is useful such + as we want a layout which does not tile the data but still requires it to + be padded to certain number of elements. + """ + element_size_in_bits: builtins.int + """(Optional) Bit size of each element. When unspecified or being 0, default + to ShapeUtil::ByteSizeOfPrimitiveType. + """ + memory_space: builtins.int + """Memory space where this array resides. The integer field is interpreted in + a backend-specific manner. + """ + index_primitive_type: global___PrimitiveType.ValueType + """The integer types to be used for indices and pointers. These fields must + not be used unless the layout represents a sparse array. The PrimitiveType + must correspond to an unsigned integer (U8, U16, U32, or U64). + If not provided, the compiler will use the largest unsigned integer + that is naturally supported by the target device (U32 or U64 in currently + supported devices). + """ + pointer_primitive_type: global___PrimitiveType.ValueType + dynamic_shape_metadata_prefix_bytes: builtins.int + """The dynamic shape metadata size in bytes in front of the shape data. The + field may be non-zero for a static shape whose associated buffer is for a + dynamic shape, e.g. a result of SliceToDynamic. + """ + @property + def dim_level_types( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___DimLevelType.ValueType]: + """The dimension level type list for this array, specifying the way in which + each array dimension is represented in memory. If this list is empty, the + array is assumed to be dense. + """ + + @property + def dim_unique(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Whether each dimension is unique or ordered. Each of the following lists + must be empty, or have one entry for each entry of dim_level_types. If + either list is empty, all dimensions are assumed to be unique and ordered, + respectively. Entries in this list may not be false for some DimLevelType + values (such as DIM_DENSE in particular). + """ + + @property + def dim_ordered(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def minor_to_major(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Sequence of dimension numbers, from minor (fastest varying index) to major + (slowest varying index). This field is required. + """ + + @property + def tiles(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___TileProto]: + """A sequence of tiles, starting from the tile that's applied first to the + Shape. + + TODO(b/119839262): implement tiling in each backend or add Unimplemented + error. + """ + + @property + def physical_shape(self) -> global___ShapeProto: + """The physical, on-device shape used to represent the shape this layout + belongs to. Only used for sparse arrays. + The layout(s) contained within the physical shape should not also contain + a physical shape. + """ + + @property + def split_configs(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___SplitConfigProto]: + """The split configurations which describe if/how the data is split between + different memories. + """ + + def __init__( + self, + *, + dim_level_types: collections.abc.Iterable[global___DimLevelType.ValueType] | None = ..., + dim_unique: collections.abc.Iterable[builtins.bool] | None = ..., + dim_ordered: collections.abc.Iterable[builtins.bool] | None = ..., + minor_to_major: collections.abc.Iterable[builtins.int] | None = ..., + tiles: collections.abc.Iterable[global___TileProto] | None = ..., + tail_padding_alignment_in_elements: builtins.int | None = ..., + element_size_in_bits: builtins.int | None = ..., + memory_space: builtins.int | None = ..., + index_primitive_type: global___PrimitiveType.ValueType | None = ..., + pointer_primitive_type: global___PrimitiveType.ValueType | None = ..., + physical_shape: global___ShapeProto | None = ..., + dynamic_shape_metadata_prefix_bytes: builtins.int | None = ..., + split_configs: collections.abc.Iterable[global___SplitConfigProto] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["physical_shape", b"physical_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dim_level_types", + b"dim_level_types", + "dim_ordered", + b"dim_ordered", + "dim_unique", + b"dim_unique", + "dynamic_shape_metadata_prefix_bytes", + b"dynamic_shape_metadata_prefix_bytes", + "element_size_in_bits", + b"element_size_in_bits", + "index_primitive_type", + b"index_primitive_type", + "memory_space", + b"memory_space", + "minor_to_major", + b"minor_to_major", + "physical_shape", + b"physical_shape", + "pointer_primitive_type", + b"pointer_primitive_type", + "split_configs", + b"split_configs", + "tail_padding_alignment_in_elements", + b"tail_padding_alignment_in_elements", + "tiles", + b"tiles", + ], + ) -> None: ... + +global___LayoutProto = LayoutProto + +@typing.final +class ShapeProto(google.protobuf.message.Message): + """A shape describes the number of dimensions in the array, the size of each + dimension, and the primitive component type. + + Tuples are a special case in that they have rank zero and have tuple_shapes + defined. + + See the XLA documentation for more information on shapes and layouts. + + LINT.IfChange + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ELEMENT_TYPE_FIELD_NUMBER: builtins.int + DIMENSIONS_FIELD_NUMBER: builtins.int + TUPLE_SHAPES_FIELD_NUMBER: builtins.int + LAYOUT_FIELD_NUMBER: builtins.int + IS_DYNAMIC_DIMENSION_FIELD_NUMBER: builtins.int + element_type: global___PrimitiveType.ValueType + """The element type for this shape.""" + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The size (number of elements) for each dimension, or an upper bound on the + size if the dimension is dynamic. In XLA, dimensions are numbered from 0 + to N-1 for an N-dimensional array. The first element of 'dimensions' is the + size of dimension 0, the second element is the size of dimension 1, and so + forth. Empty list indicates a scalar. + + If the respective element in 'is_dimension_dynamic' is true then the value + in this field represents an upper bound on the size of the dimension. + """ + + @property + def tuple_shapes(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShapeProto]: + """For tuples only, the shapes of constituent shapes in the tuple sequence.""" + + @property + def layout(self) -> global___LayoutProto: + """The layout used to back this shape.""" + + @property + def is_dynamic_dimension(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """For arrays, this indicates whether or not each dimension is + dynamically-sized. The number of elements in this repeated field should be + zero (indicating that no dimensions are dynamic) or equal to the number of + elements in the 'dimensions' field. + """ + + def __init__( + self, + *, + element_type: global___PrimitiveType.ValueType | None = ..., + dimensions: collections.abc.Iterable[builtins.int] | None = ..., + tuple_shapes: collections.abc.Iterable[global___ShapeProto] | None = ..., + layout: global___LayoutProto | None = ..., + is_dynamic_dimension: collections.abc.Iterable[builtins.bool] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["layout", b"layout"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dimensions", + b"dimensions", + "element_type", + b"element_type", + "is_dynamic_dimension", + b"is_dynamic_dimension", + "layout", + b"layout", + "tuple_shapes", + b"tuple_shapes", + ], + ) -> None: ... + +global___ShapeProto = ShapeProto + +@typing.final +class ProgramShapeProto(google.protobuf.message.Message): + """Shape of the parameters and output of a computation (like a traditional + function signature). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PARAMETERS_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + PARAMETER_NAMES_FIELD_NUMBER: builtins.int + @property + def parameters(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShapeProto]: ... + @property + def result(self) -> global___ShapeProto: ... + @property + def parameter_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + def __init__( + self, + *, + parameters: collections.abc.Iterable[global___ShapeProto] | None = ..., + result: global___ShapeProto | None = ..., + parameter_names: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["result", b"result"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["parameter_names", b"parameter_names", "parameters", b"parameters", "result", b"result"] + ) -> None: ... + +global___ProgramShapeProto = ProgramShapeProto + +@typing.final +class ComputationStats(google.protobuf.message.Message): + """Statistics of a computation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FLOP_COUNT_FIELD_NUMBER: builtins.int + TRANSCENDENTAL_COUNT_FIELD_NUMBER: builtins.int + flop_count: builtins.float + """The number of floating point operations in the computation.""" + transcendental_count: builtins.float + """The number of transcendental operations (e.g., exp) in the computation.""" + def __init__(self, *, flop_count: builtins.float | None = ..., transcendental_count: builtins.float | None = ...) -> None: ... + def ClearField( + self, field_name: typing.Literal["flop_count", b"flop_count", "transcendental_count", b"transcendental_count"] + ) -> None: ... + +global___ComputationStats = ComputationStats + +@typing.final +class OpMetadata(google.protobuf.message.Message): + """Symbolization metadata for HLO Instructions. + + This metadata is used for debugging XLA code generation, as well as + performance profiling of XLA-generated executables. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ProfileInfo(google.protobuf.message.Message): + """Information about the optimization profile that this operation contains.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PROFILE_TYPE_FIELD_NUMBER: builtins.int + RELATIVE_SPEEDUP_FIELD_NUMBER: builtins.int + PROFILE_SOURCE_FIELD_NUMBER: builtins.int + COMPILATION_EVENT_FIELD_NUMBER: builtins.int + relative_speedup: builtins.float + """Speedup of tuned config compared to default config. + TODO(b/203817882) Set the relative_speedup. + """ + profile_source: global___ProfileSource.ValueType + """The source of the optimization profiles that this operation contains.""" + compilation_event: global___CompilationEvent.ValueType + """The compilation event that triggered the use of the profiles.""" + @property + def profile_type( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___ProfileType.ValueType]: + """The type of optimization profiles that this operation contains.""" + + def __init__( + self, + *, + profile_type: collections.abc.Iterable[global___ProfileType.ValueType] | None = ..., + relative_speedup: builtins.float | None = ..., + profile_source: global___ProfileSource.ValueType | None = ..., + compilation_event: global___CompilationEvent.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_event", + b"compilation_event", + "profile_source", + b"profile_source", + "profile_type", + b"profile_type", + "relative_speedup", + b"relative_speedup", + ], + ) -> None: ... + + OP_TYPE_FIELD_NUMBER: builtins.int + OP_NAME_FIELD_NUMBER: builtins.int + SOURCE_FILE_FIELD_NUMBER: builtins.int + SOURCE_LINE_FIELD_NUMBER: builtins.int + PROFILE_TYPE_FIELD_NUMBER: builtins.int + SIZE_OF_GENERATED_CODE_IN_BYTES_FIELD_NUMBER: builtins.int + SIZE_OF_MEMORY_WORKING_SET_IN_BYTES_FIELD_NUMBER: builtins.int + PROFILE_INFO_FIELD_NUMBER: builtins.int + DEDUPLICATED_NAME_FIELD_NUMBER: builtins.int + PRESERVE_LAYOUT_FIELD_NUMBER: builtins.int + STACK_FRAME_ID_FIELD_NUMBER: builtins.int + SCHEDULING_NAME_FIELD_NUMBER: builtins.int + op_type: builtins.str + """The framework op name that generated this XLA op. + + Frameworks that build on top of XLA should mirror the names of their ops + back to users by specifying the op_type. In this way, even if the + framework's "ops" are implemented as multiple XLA HLO Ops, they can be + grouped appropriately. (e.g. if a SoftMax layer is emitted into XLA as + multiple ops, then each op should have the op_type be "SoftMax".) + """ + op_name: builtins.str + """The user-specified name of the op. + + This name is often unique within a computation. Note: some frameworks + add auto-generated names if the user does not provide one. + """ + source_file: builtins.str + """Indicate a file and line that this op is associated to in a user's program. + + e.g. it could be the file and line of user code that generated the op. + """ + source_line: builtins.int + size_of_generated_code_in_bytes: builtins.int + """The footprint of the generated code for the instruction.""" + size_of_memory_working_set_in_bytes: builtins.int + """The size of the working set, i.e., the amount of memory, used by the + instruction in a compiler-managed fast device memory. + """ + deduplicated_name: builtins.str + """Deduplicated HLO name for this op. In some cases, we can have multiple + instructions (e.g. fusions) that are considered duplicates. We want to + group them together under the same name so that we can group them together + during analysis (e.g. HLO Op Profile tool in Xprof). + E.g. If we have fusion.1, fusion.2, and fusion.3 marked as duplicates, + fusion.2 and fusion.3 will have deduplicated_name = fusion.1 + """ + preserve_layout: builtins.bool + """Whether to preserve the layout of the HLO op.""" + stack_frame_id: builtins.int + """1-based position of the frame in frames flat array. + Ids are 1-based to keep 0 value as representation of non-set property. + """ + scheduling_name: builtins.str + """Instruction name available upon scheduling.""" + @property + def profile_type(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___ProfileType.ValueType]: + """Deprecated, use [ProfileInfo][profile_type] instead.""" + + @property + def profile_info(self) -> global___OpMetadata.ProfileInfo: + """Profile information for the Op.""" + + def __init__( + self, + *, + op_type: builtins.str | None = ..., + op_name: builtins.str | None = ..., + source_file: builtins.str | None = ..., + source_line: builtins.int | None = ..., + profile_type: collections.abc.Iterable[global___ProfileType.ValueType] | None = ..., + size_of_generated_code_in_bytes: builtins.int | None = ..., + size_of_memory_working_set_in_bytes: builtins.int | None = ..., + profile_info: global___OpMetadata.ProfileInfo | None = ..., + deduplicated_name: builtins.str | None = ..., + preserve_layout: builtins.bool | None = ..., + stack_frame_id: builtins.int | None = ..., + scheduling_name: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["profile_info", b"profile_info"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deduplicated_name", + b"deduplicated_name", + "op_name", + b"op_name", + "op_type", + b"op_type", + "preserve_layout", + b"preserve_layout", + "profile_info", + b"profile_info", + "profile_type", + b"profile_type", + "scheduling_name", + b"scheduling_name", + "size_of_generated_code_in_bytes", + b"size_of_generated_code_in_bytes", + "size_of_memory_working_set_in_bytes", + b"size_of_memory_working_set_in_bytes", + "source_file", + b"source_file", + "source_line", + b"source_line", + "stack_frame_id", + b"stack_frame_id", + ], + ) -> None: ... + +global___OpMetadata = OpMetadata + +@typing.final +class ExecutionProfile(google.protobuf.message.Message): + """Profile data from the execution of a computation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COMPILATION_CACHE_HIT_FIELD_NUMBER: builtins.int + COMPILE_TIME_MS_FIELD_NUMBER: builtins.int + COMPUTE_CYCLE_COUNT_FIELD_NUMBER: builtins.int + COMPUTE_TIME_NS_FIELD_NUMBER: builtins.int + COMPUTE_AND_TRANSFER_TIME_NS_FIELD_NUMBER: builtins.int + EXECUTABLE_SIZE_IN_BYTES_FIELD_NUMBER: builtins.int + PROFILE_CACHE_HIT_FIELD_NUMBER: builtins.int + WARMUP_RUN_EXECUTED_FIELD_NUMBER: builtins.int + compilation_cache_hit: builtins.bool + """Whether the executable was read from the compilation cache.""" + compile_time_ms: builtins.int + """The time in milliseconds spent to compile the computation. This only set if + the executable was not read from the compilation cache + (compilation_cache_hit == false). + """ + compute_cycle_count: builtins.int + """The number of cycles spent for the computation. This does not include the + time taken for the data transfers between the host and the device. This is + a target-dependent field and only used for debugging purposes. + """ + compute_time_ns: builtins.int + """The time in nanoseconds spent for the computation, without data transfer.""" + compute_and_transfer_time_ns: builtins.int + """The time in nanoseconds spent for the entire computation, including the + result data transfer time. Current implementation does not spend any cycles + for the input data transfer since the memory is initialized with the proper + values before the execution. + """ + executable_size_in_bytes: builtins.int + """The size of the binary code in the executable.""" + profile_cache_hit: builtins.bool + """Whether this profile was drawn from a cache of profiles instead of from + execution on the hardware. + """ + warmup_run_executed: builtins.bool + """Whether a warm-up run of the computation was executed before the + measured execution. + """ + def __init__( + self, + *, + compilation_cache_hit: builtins.bool | None = ..., + compile_time_ms: builtins.int | None = ..., + compute_cycle_count: builtins.int | None = ..., + compute_time_ns: builtins.int | None = ..., + compute_and_transfer_time_ns: builtins.int | None = ..., + executable_size_in_bytes: builtins.int | None = ..., + profile_cache_hit: builtins.bool | None = ..., + warmup_run_executed: builtins.bool | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_cache_hit", + b"compilation_cache_hit", + "compile_time_ms", + b"compile_time_ms", + "compute_and_transfer_time_ns", + b"compute_and_transfer_time_ns", + "compute_cycle_count", + b"compute_cycle_count", + "compute_time_ns", + b"compute_time_ns", + "executable_size_in_bytes", + b"executable_size_in_bytes", + "profile_cache_hit", + b"profile_cache_hit", + "warmup_run_executed", + b"warmup_run_executed", + ], + ) -> None: ... + +global___ExecutionProfile = ExecutionProfile + +@typing.final +class ExecutionHandle(google.protobuf.message.Message): + """Handle given to a user that represents an execution that the user launched + asynchronously on the device. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HANDLE_FIELD_NUMBER: builtins.int + handle: builtins.int + def __init__(self, *, handle: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["handle", b"handle"]) -> None: ... + +global___ExecutionHandle = ExecutionHandle + +@typing.final +class GlobalDataHandle(google.protobuf.message.Message): + """Handle given to a user that represents a globally accessible allocation. + Contrast this against a ComputationDataHandle, which is not globally + accessible, since it only exists within a specific computation. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HANDLE_FIELD_NUMBER: builtins.int + handle: builtins.int + def __init__(self, *, handle: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["handle", b"handle"]) -> None: ... + +global___GlobalDataHandle = GlobalDataHandle + +@typing.final +class DeviceHandle(google.protobuf.message.Message): + """Handle given to a user that represents a replicated virtual device. Each + replicated device represents N physical devices for execution where N is the + number of replicas. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HANDLE_FIELD_NUMBER: builtins.int + DEVICE_COUNT_FIELD_NUMBER: builtins.int + handle: builtins.int + device_count: builtins.int + """The number of model-parallel virtual devices that communicate via XLA + Send/Recv instructions. + """ + def __init__(self, *, handle: builtins.int | None = ..., device_count: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["device_count", b"device_count", "handle", b"handle"]) -> None: ... + +global___DeviceHandle = DeviceHandle + +@typing.final +class ChannelHandle(google.protobuf.message.Message): + """Handle given to a user to represent a channel between two computations + via a Send and Recv instruction pair. Channels are unbuffered, so Send + Send instructions will be blocked until the data is transferred. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ChannelType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ChannelTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ChannelHandle._ChannelType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CHANNEL_TYPE_INVALID: ChannelHandle._ChannelType.ValueType # 0 + """Invalid primitive type to serve as default.""" + DEVICE_TO_DEVICE: ChannelHandle._ChannelType.ValueType # 1 + """A channel for sending data between devices.""" + DEVICE_TO_HOST: ChannelHandle._ChannelType.ValueType # 2 + """A channel for sending data from the device to the host. Can only be used + with a Send operation. + """ + HOST_TO_DEVICE: ChannelHandle._ChannelType.ValueType # 3 + """A channel for sending data from the host to the device. Can only be used + with a Recv operation. + """ + + class ChannelType(_ChannelType, metaclass=_ChannelTypeEnumTypeWrapper): ... + CHANNEL_TYPE_INVALID: ChannelHandle.ChannelType.ValueType # 0 + """Invalid primitive type to serve as default.""" + DEVICE_TO_DEVICE: ChannelHandle.ChannelType.ValueType # 1 + """A channel for sending data between devices.""" + DEVICE_TO_HOST: ChannelHandle.ChannelType.ValueType # 2 + """A channel for sending data from the device to the host. Can only be used + with a Send operation. + """ + HOST_TO_DEVICE: ChannelHandle.ChannelType.ValueType # 3 + """A channel for sending data from the host to the device. Can only be used + with a Recv operation. + """ + + HANDLE_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + handle: builtins.int + type: global___ChannelHandle.ChannelType.ValueType + def __init__( + self, *, handle: builtins.int | None = ..., type: global___ChannelHandle.ChannelType.ValueType | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["handle", b"handle", "type", b"type"]) -> None: ... + +global___ChannelHandle = ChannelHandle + +@typing.final +class DeviceAssignmentProto(google.protobuf.message.Message): + """DeviceAssignmentProto is a serialized form of DeviceAssignment class, which + represents the device ids assigned to a set of replicated computations. + See xla::DeviceAssignment class comment for more details. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ComputationDevice(google.protobuf.message.Message): + """Each logical computation runs on replica_count physical devices. + ComputationDevice represents the device ids assinged to the replicas. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICA_DEVICE_IDS_FIELD_NUMBER: builtins.int + @property + def replica_device_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, replica_device_ids: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["replica_device_ids", b"replica_device_ids"]) -> None: ... + + REPLICA_COUNT_FIELD_NUMBER: builtins.int + COMPUTATION_COUNT_FIELD_NUMBER: builtins.int + COMPUTATION_DEVICES_FIELD_NUMBER: builtins.int + replica_count: builtins.int + computation_count: builtins.int + @property + def computation_devices( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___DeviceAssignmentProto.ComputationDevice + ]: ... + def __init__( + self, + *, + replica_count: builtins.int | None = ..., + computation_count: builtins.int | None = ..., + computation_devices: collections.abc.Iterable[global___DeviceAssignmentProto.ComputationDevice] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "computation_count", + b"computation_count", + "computation_devices", + b"computation_devices", + "replica_count", + b"replica_count", + ], + ) -> None: ... + +global___DeviceAssignmentProto = DeviceAssignmentProto + +@typing.final +class LiteralProto(google.protobuf.message.Message): + """Literals are used when the server and client need to exchange materialized + data / results. Literals are also used to describe constants used in + computations. + + Transfers to/from the client are encoded in literal form, and the structure + of the repeated fields is implied by the shape. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SHAPE_FIELD_NUMBER: builtins.int + PREDS_FIELD_NUMBER: builtins.int + S2S_FIELD_NUMBER: builtins.int + S4S_FIELD_NUMBER: builtins.int + S8S_FIELD_NUMBER: builtins.int + U2S_FIELD_NUMBER: builtins.int + U4S_FIELD_NUMBER: builtins.int + U8S_FIELD_NUMBER: builtins.int + S32S_FIELD_NUMBER: builtins.int + S64S_FIELD_NUMBER: builtins.int + U32S_FIELD_NUMBER: builtins.int + U64S_FIELD_NUMBER: builtins.int + F32S_FIELD_NUMBER: builtins.int + F64S_FIELD_NUMBER: builtins.int + C64S_FIELD_NUMBER: builtins.int + C128S_FIELD_NUMBER: builtins.int + TUPLE_LITERALS_FIELD_NUMBER: builtins.int + F16S_FIELD_NUMBER: builtins.int + BF16S_FIELD_NUMBER: builtins.int + U16S_FIELD_NUMBER: builtins.int + S16S_FIELD_NUMBER: builtins.int + F8E5M2S_FIELD_NUMBER: builtins.int + F8E4M3FNS_FIELD_NUMBER: builtins.int + F8E4M3B11FNUZS_FIELD_NUMBER: builtins.int + F8E5M2FNUZS_FIELD_NUMBER: builtins.int + F8E4M3FNUZS_FIELD_NUMBER: builtins.int + SPARSE_INDICES_FIELD_NUMBER: builtins.int + s2s: builtins.bytes + s4s: builtins.bytes + s8s: builtins.bytes + u2s: builtins.bytes + u4s: builtins.bytes + u8s: builtins.bytes + f16s: builtins.bytes + """The F16s, BF16s, U16s and S16s are encoded in little endian byte order""" + bf16s: builtins.bytes + u16s: builtins.bytes + s16s: builtins.bytes + f8e5m2s: builtins.bytes + f8e4m3fns: builtins.bytes + f8e4m3b11fnuzs: builtins.bytes + f8e5m2fnuzs: builtins.bytes + f8e4m3fnuzs: builtins.bytes + @property + def shape(self) -> global___ShapeProto: ... + @property + def preds(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def s32s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def s64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def u32s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def u64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def f32s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + @property + def f64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + @property + def c64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + """Stored as interleaved real, imag floats.""" + + @property + def c128s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + """Stored as interleaved real, imag doubles.""" + + @property + def tuple_literals(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___LiteralProto]: ... + @property + def sparse_indices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Next = 28""" + + def __init__( + self, + *, + shape: global___ShapeProto | None = ..., + preds: collections.abc.Iterable[builtins.bool] | None = ..., + s2s: builtins.bytes | None = ..., + s4s: builtins.bytes | None = ..., + s8s: builtins.bytes | None = ..., + u2s: builtins.bytes | None = ..., + u4s: builtins.bytes | None = ..., + u8s: builtins.bytes | None = ..., + s32s: collections.abc.Iterable[builtins.int] | None = ..., + s64s: collections.abc.Iterable[builtins.int] | None = ..., + u32s: collections.abc.Iterable[builtins.int] | None = ..., + u64s: collections.abc.Iterable[builtins.int] | None = ..., + f32s: collections.abc.Iterable[builtins.float] | None = ..., + f64s: collections.abc.Iterable[builtins.float] | None = ..., + c64s: collections.abc.Iterable[builtins.float] | None = ..., + c128s: collections.abc.Iterable[builtins.float] | None = ..., + tuple_literals: collections.abc.Iterable[global___LiteralProto] | None = ..., + f16s: builtins.bytes | None = ..., + bf16s: builtins.bytes | None = ..., + u16s: builtins.bytes | None = ..., + s16s: builtins.bytes | None = ..., + f8e5m2s: builtins.bytes | None = ..., + f8e4m3fns: builtins.bytes | None = ..., + f8e4m3b11fnuzs: builtins.bytes | None = ..., + f8e5m2fnuzs: builtins.bytes | None = ..., + f8e4m3fnuzs: builtins.bytes | None = ..., + sparse_indices: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["shape", b"shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bf16s", + b"bf16s", + "c128s", + b"c128s", + "c64s", + b"c64s", + "f16s", + b"f16s", + "f32s", + b"f32s", + "f64s", + b"f64s", + "f8e4m3b11fnuzs", + b"f8e4m3b11fnuzs", + "f8e4m3fns", + b"f8e4m3fns", + "f8e4m3fnuzs", + b"f8e4m3fnuzs", + "f8e5m2fnuzs", + b"f8e5m2fnuzs", + "f8e5m2s", + b"f8e5m2s", + "preds", + b"preds", + "s16s", + b"s16s", + "s2s", + b"s2s", + "s32s", + b"s32s", + "s4s", + b"s4s", + "s64s", + b"s64s", + "s8s", + b"s8s", + "shape", + b"shape", + "sparse_indices", + b"sparse_indices", + "tuple_literals", + b"tuple_literals", + "u16s", + b"u16s", + "u2s", + b"u2s", + "u32s", + b"u32s", + "u4s", + b"u4s", + "u64s", + b"u64s", + "u8s", + b"u8s", + ], + ) -> None: ... + +global___LiteralProto = LiteralProto + +@typing.final +class WindowDimension(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SIZE_FIELD_NUMBER: builtins.int + STRIDE_FIELD_NUMBER: builtins.int + PADDING_LOW_FIELD_NUMBER: builtins.int + PADDING_HIGH_FIELD_NUMBER: builtins.int + WINDOW_DILATION_FIELD_NUMBER: builtins.int + BASE_DILATION_FIELD_NUMBER: builtins.int + WINDOW_REVERSAL_FIELD_NUMBER: builtins.int + size: builtins.int + """The size of the window in this dimension. For a rectangle, this would be + the width or height. + """ + stride: builtins.int + """The stride at which the window moves across the base area in this + dimension. In other words, this is the spacing between different + positions of the window in this dimension. + """ + padding_low: builtins.int + """If positive, means the amount of padding to add to the base area at the low + end of this dimension; if negative, its negative means the number of + elements removed from the low end of this dimension. For example, in the + horizontal dimension of a rectangle, this would be the number of padding + values to pad on the left, given that indices increase when going right. + The actual padding value depends upon the context. Convolution pads with + zeros. ReduceWindow and SelectAndScatter pads with the reduce function's + init value. + """ + padding_high: builtins.int + """As padding_low, but on the high end of this dimension. For example, in the + horizontal dimension of a rectangle, this would be the number of values to + pad on the right, given that indices increase when going right. + """ + window_dilation: builtins.int + """Dilation factor of the sliding window in this dimension. A dilation factor + of 1 means no dilation. window_dilation - 1 no-op entries ("holes") are + implicitly placed between each kernel element. This value may not be less + than 1. See documentation for convolution. + """ + base_dilation: builtins.int + """Dilation factor of the base area in this dimension. A dilation factor of 1 + means no dilation. base_dilation - 1 no-op entries ("holes") are implicitly + placed between each base area element. This value may not be less than 1. + See documentation for convolution. + """ + window_reversal: builtins.bool + """Window reversal means that this dimension was logically reversed before the + operation. + """ + def __init__( + self, + *, + size: builtins.int | None = ..., + stride: builtins.int | None = ..., + padding_low: builtins.int | None = ..., + padding_high: builtins.int | None = ..., + window_dilation: builtins.int | None = ..., + base_dilation: builtins.int | None = ..., + window_reversal: builtins.bool | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "base_dilation", + b"base_dilation", + "padding_high", + b"padding_high", + "padding_low", + b"padding_low", + "size", + b"size", + "stride", + b"stride", + "window_dilation", + b"window_dilation", + "window_reversal", + b"window_reversal", + ], + ) -> None: ... + +global___WindowDimension = WindowDimension + +@typing.final +class Window(google.protobuf.message.Message): + """Describes the windowing in an operation such as convolution. + + The window is moved across a base area and for each position of the + window a computation is performed. The field below describes the + window and the movement of the window across a base area. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___WindowDimension]: ... + def __init__(self, *, dimensions: collections.abc.Iterable[global___WindowDimension] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dimensions", b"dimensions"]) -> None: ... + +global___Window = Window + +@typing.final +class GatherDimensionNumbers(google.protobuf.message.Message): + """Describes the dimension numbers for a gather operation. + + See https://www.tensorflow.org/performance/xla/operation_semantics#gather for + more details. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OFFSET_DIMS_FIELD_NUMBER: builtins.int + COLLAPSED_SLICE_DIMS_FIELD_NUMBER: builtins.int + START_INDEX_MAP_FIELD_NUMBER: builtins.int + INDEX_VECTOR_DIM_FIELD_NUMBER: builtins.int + OPERAND_BATCHING_DIMS_FIELD_NUMBER: builtins.int + START_INDICES_BATCHING_DIMS_FIELD_NUMBER: builtins.int + index_vector_dim: builtins.int + """The dimension in the start_indices input that contains the starting + indices. + """ + @property + def offset_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ "Window indices" is a term for a set of indices that index into the + interior of a dynamic-slice from the input tensor, the starting indices for + which were computed from output_gather_dims (see the operation semantic for + how this is defined) and the start_indices tensor. + + The window indices for a specific output index Out is computed as: + + i = 0 + for (k : [0, input_tensor_shape.rank)) + window_indices[k] = + if k in collapsed_slice_dims + then 0 + else Out[offset_dims[i++]] + """ + + @property + def collapsed_slice_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def start_index_map(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is interpreted as a map from i to start_index_map[i]. It + transforms the gather index looked up from the start_indices tensor into + the starting index in the input space. + """ + + @property + def operand_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimensions in the operand.""" + + @property + def start_indices_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimensions in the index, and it should be the same size + as operand_batching_dims. + """ + + def __init__( + self, + *, + offset_dims: collections.abc.Iterable[builtins.int] | None = ..., + collapsed_slice_dims: collections.abc.Iterable[builtins.int] | None = ..., + start_index_map: collections.abc.Iterable[builtins.int] | None = ..., + index_vector_dim: builtins.int | None = ..., + operand_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + start_indices_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "collapsed_slice_dims", + b"collapsed_slice_dims", + "index_vector_dim", + b"index_vector_dim", + "offset_dims", + b"offset_dims", + "operand_batching_dims", + b"operand_batching_dims", + "start_index_map", + b"start_index_map", + "start_indices_batching_dims", + b"start_indices_batching_dims", + ], + ) -> None: ... + +global___GatherDimensionNumbers = GatherDimensionNumbers + +@typing.final +class ScatterDimensionNumbers(google.protobuf.message.Message): + """Describes the dimension numbers for a scatter operation. + + All the fields are similar to the corresponding fields in + GatherDimensionNumbers. Differences are noted below. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UPDATE_WINDOW_DIMS_FIELD_NUMBER: builtins.int + INSERTED_WINDOW_DIMS_FIELD_NUMBER: builtins.int + SCATTER_DIMS_TO_OPERAND_DIMS_FIELD_NUMBER: builtins.int + INDEX_VECTOR_DIM_FIELD_NUMBER: builtins.int + INPUT_BATCHING_DIMS_FIELD_NUMBER: builtins.int + SCATTER_INDICES_BATCHING_DIMS_FIELD_NUMBER: builtins.int + index_vector_dim: builtins.int + @property + def update_window_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The set of dimensions in the updates shape that are window dimensions.""" + + @property + def inserted_window_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The set of window dimensions that must be inserted into the updates shape.""" + + @property + def scatter_dims_to_operand_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def input_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimension in the input.""" + + @property + def scatter_indices_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimension in the index.""" + + def __init__( + self, + *, + update_window_dims: collections.abc.Iterable[builtins.int] | None = ..., + inserted_window_dims: collections.abc.Iterable[builtins.int] | None = ..., + scatter_dims_to_operand_dims: collections.abc.Iterable[builtins.int] | None = ..., + index_vector_dim: builtins.int | None = ..., + input_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + scatter_indices_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "index_vector_dim", + b"index_vector_dim", + "input_batching_dims", + b"input_batching_dims", + "inserted_window_dims", + b"inserted_window_dims", + "scatter_dims_to_operand_dims", + b"scatter_dims_to_operand_dims", + "scatter_indices_batching_dims", + b"scatter_indices_batching_dims", + "update_window_dims", + b"update_window_dims", + ], + ) -> None: ... + +global___ScatterDimensionNumbers = ScatterDimensionNumbers + +@typing.final +class ConvolutionDimensionNumbers(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INPUT_BATCH_DIMENSION_FIELD_NUMBER: builtins.int + INPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + INPUT_SPATIAL_DIMENSIONS_FIELD_NUMBER: builtins.int + KERNEL_INPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + KERNEL_OUTPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + KERNEL_SPATIAL_DIMENSIONS_FIELD_NUMBER: builtins.int + OUTPUT_BATCH_DIMENSION_FIELD_NUMBER: builtins.int + OUTPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + OUTPUT_SPATIAL_DIMENSIONS_FIELD_NUMBER: builtins.int + input_batch_dimension: builtins.int + """The number of the dimension that represents batch in the input.""" + input_feature_dimension: builtins.int + """The number of the dimension that represents features in the input.""" + kernel_input_feature_dimension: builtins.int + """The number of the dimension that represents input features in the + convolutional kernel (rhs). + """ + kernel_output_feature_dimension: builtins.int + """The number of the dimension that represents output features in + the convolutional kernel (rhs). + """ + output_batch_dimension: builtins.int + """The number of the dimension that represents batch in the output.""" + output_feature_dimension: builtins.int + """The number of the dimension that represents features in the output.""" + @property + def input_spatial_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers for the spatial dimensions that the window + moves through in the input. + """ + + @property + def kernel_spatial_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers for the spatial dimensions that the window + moves through in the kernel (rhs). window.strides(0) is the + stride in the kernel_spatial_dimensions(0) dimension. + """ + + @property + def output_spatial_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers for the spatial dimensions that the window + moves through in the output. + """ + + def __init__( + self, + *, + input_batch_dimension: builtins.int | None = ..., + input_feature_dimension: builtins.int | None = ..., + input_spatial_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + kernel_input_feature_dimension: builtins.int | None = ..., + kernel_output_feature_dimension: builtins.int | None = ..., + kernel_spatial_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + output_batch_dimension: builtins.int | None = ..., + output_feature_dimension: builtins.int | None = ..., + output_spatial_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "input_batch_dimension", + b"input_batch_dimension", + "input_feature_dimension", + b"input_feature_dimension", + "input_spatial_dimensions", + b"input_spatial_dimensions", + "kernel_input_feature_dimension", + b"kernel_input_feature_dimension", + "kernel_output_feature_dimension", + b"kernel_output_feature_dimension", + "kernel_spatial_dimensions", + b"kernel_spatial_dimensions", + "output_batch_dimension", + b"output_batch_dimension", + "output_feature_dimension", + b"output_feature_dimension", + "output_spatial_dimensions", + b"output_spatial_dimensions", + ], + ) -> None: ... + +global___ConvolutionDimensionNumbers = ConvolutionDimensionNumbers + +@typing.final +class DotDimensionNumbers(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LHS_CONTRACTING_DIMENSIONS_FIELD_NUMBER: builtins.int + RHS_CONTRACTING_DIMENSIONS_FIELD_NUMBER: builtins.int + LHS_BATCH_DIMENSIONS_FIELD_NUMBER: builtins.int + RHS_BATCH_DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def lhs_contracting_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'lhs' contracting dimensions.""" + + @property + def rhs_contracting_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'rhs' contracting dimensions.""" + + @property + def lhs_batch_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'lhs' batch dimensions.""" + + @property + def rhs_batch_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'rhs' batch dimensions.""" + + def __init__( + self, + *, + lhs_contracting_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + rhs_contracting_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + lhs_batch_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + rhs_batch_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "lhs_batch_dimensions", + b"lhs_batch_dimensions", + "lhs_contracting_dimensions", + b"lhs_contracting_dimensions", + "rhs_batch_dimensions", + b"rhs_batch_dimensions", + "rhs_contracting_dimensions", + b"rhs_contracting_dimensions", + ], + ) -> None: ... + +global___DotDimensionNumbers = DotDimensionNumbers + +@typing.final +class SparsityDescriptor(google.protobuf.message.Message): + """Contains sparsity metadata for a sparse dot operation. + The only supported type atm is structured 2:4 sparsity, which is natively + supported on NVidia GPUs. + Restrictions: + - only one operand of the dot operation may be sparse; + - only the contracting dimension may be sparse. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TYPE_FIELD_NUMBER: builtins.int + INDEX_FIELD_NUMBER: builtins.int + DIMENSION_FIELD_NUMBER: builtins.int + N_FIELD_NUMBER: builtins.int + M_FIELD_NUMBER: builtins.int + type: global___SparsityType.ValueType + index: builtins.int + """Sparse operand index (0 or 1).""" + dimension: builtins.int + """Sparse dimension number.""" + n: builtins.int + """Structured N:M sparsity (N < M).""" + m: builtins.int + def __init__( + self, + *, + type: global___SparsityType.ValueType | None = ..., + index: builtins.int | None = ..., + dimension: builtins.int | None = ..., + n: builtins.int | None = ..., + m: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["dimension", b"dimension", "index", b"index", "m", b"m", "n", b"n", "type", b"type"] + ) -> None: ... + +global___SparsityDescriptor = SparsityDescriptor + +@typing.final +class TriangularSolveOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Transpose: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TransposeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[TriangularSolveOptions._Transpose.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TRANSPOSE_INVALID: TriangularSolveOptions._Transpose.ValueType # 0 + NO_TRANSPOSE: TriangularSolveOptions._Transpose.ValueType # 1 + """Don't transpose 'a'.""" + TRANSPOSE: TriangularSolveOptions._Transpose.ValueType # 2 + """Transpose 'a'.""" + ADJOINT: TriangularSolveOptions._Transpose.ValueType # 3 + """Complex conjugate and transpose 'a'.""" + + class Transpose(_Transpose, metaclass=_TransposeEnumTypeWrapper): + """Should we transpose or use the adjoint of 'a'?""" + + TRANSPOSE_INVALID: TriangularSolveOptions.Transpose.ValueType # 0 + NO_TRANSPOSE: TriangularSolveOptions.Transpose.ValueType # 1 + """Don't transpose 'a'.""" + TRANSPOSE: TriangularSolveOptions.Transpose.ValueType # 2 + """Transpose 'a'.""" + ADJOINT: TriangularSolveOptions.Transpose.ValueType # 3 + """Complex conjugate and transpose 'a'.""" + + LEFT_SIDE_FIELD_NUMBER: builtins.int + LOWER_FIELD_NUMBER: builtins.int + UNIT_DIAGONAL_FIELD_NUMBER: builtins.int + TRANSPOSE_A_FIELD_NUMBER: builtins.int + left_side: builtins.bool + """If true, solves ax = b. If false, solves xa = b.""" + lower: builtins.bool + """If true, 'a' is lower triangular. If false, 'a' is upper triangular.""" + unit_diagonal: builtins.bool + """If true, the diagonal elements of 'a' are assumed to be 1 and not accessed.""" + transpose_a: global___TriangularSolveOptions.Transpose.ValueType + def __init__( + self, + *, + left_side: builtins.bool | None = ..., + lower: builtins.bool | None = ..., + unit_diagonal: builtins.bool | None = ..., + transpose_a: global___TriangularSolveOptions.Transpose.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "left_side", b"left_side", "lower", b"lower", "transpose_a", b"transpose_a", "unit_diagonal", b"unit_diagonal" + ], + ) -> None: ... + +global___TriangularSolveOptions = TriangularSolveOptions + +@typing.final +class CholeskyOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOWER_FIELD_NUMBER: builtins.int + lower: builtins.bool + """If true, uses the lower triangle of `a`. If false, uses the upper triangle + of `a`. + """ + def __init__(self, *, lower: builtins.bool | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["lower", b"lower"]) -> None: ... + +global___CholeskyOptions = CholeskyOptions + +@typing.final +class SortOptions(google.protobuf.message.Message): + """Attributes of the sort custom call (cub::DeviceRadixSort).""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DESCENDING_FIELD_NUMBER: builtins.int + descending: builtins.bool + def __init__(self, *, descending: builtins.bool | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["descending", b"descending"]) -> None: ... + +global___SortOptions = SortOptions + +@typing.final +class FrontendAttributes(google.protobuf.message.Message): + """Generic map of attributes used to pass hints / configuration options from + the Python frontend to the XLA backend. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class MapEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.str + def __init__(self, *, key: builtins.str | None = ..., value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + MAP_FIELD_NUMBER: builtins.int + @property + def map(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.str]: ... + def __init__(self, *, map: collections.abc.Mapping[builtins.str, builtins.str] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["map", b"map"]) -> None: ... + +global___FrontendAttributes = FrontendAttributes + +@typing.final +class Statistic(google.protobuf.message.Message): + """Represents a single statistic to track.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STAT_NAME_FIELD_NUMBER: builtins.int + STAT_VAL_FIELD_NUMBER: builtins.int + stat_name: builtins.str + """Must be a single word consisting of any alphanumeric characters""" + stat_val: builtins.float + """Must be within a range of [0, 100], in order for the graph dumper to + properly render the statistic onto the graph. + """ + def __init__(self, *, stat_name: builtins.str | None = ..., stat_val: builtins.float | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["stat_name", b"stat_name", "stat_val", b"stat_val"]) -> None: ... + +global___Statistic = Statistic + +@typing.final +class StatisticsViz(google.protobuf.message.Message): + """Represents the information needed to visualize propagation statistics when + rendering an HLO graph. This includes an array of statistics as well as the + index of the statistic to render. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STAT_INDEX_TO_VISUALIZE_FIELD_NUMBER: builtins.int + STATISTICS_FIELD_NUMBER: builtins.int + stat_index_to_visualize: builtins.int + @property + def statistics(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Statistic]: ... + def __init__( + self, + *, + stat_index_to_visualize: builtins.int | None = ..., + statistics: collections.abc.Iterable[global___Statistic] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["stat_index_to_visualize", b"stat_index_to_visualize", "statistics", b"statistics"] + ) -> None: ... + +global___StatisticsViz = StatisticsViz + +@typing.final +class OpSharding(google.protobuf.message.Message): + """LINT.IfChange""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[OpSharding._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + REPLICATED: OpSharding._Type.ValueType # 0 + """This sharding is replicated across all devices (implies maximal, + all other fields are unused). + """ + MAXIMAL: OpSharding._Type.ValueType # 1 + """This sharding is maximal - one device runs the entire operation.""" + TUPLE: OpSharding._Type.ValueType # 2 + """This sharding is a tuple - only the tuple_shardings field is valid.""" + OTHER: OpSharding._Type.ValueType # 3 + """None of the above; tile_shape and tile_assignment are both used.""" + MANUAL: OpSharding._Type.ValueType # 4 + """This op is manually sharded: the shapes are already partitioned and the + partitioner should not change this op. + """ + UNKNOWN: OpSharding._Type.ValueType # 5 + """This sharding is a placeholder sharding with lowest precedence, it can be + overwriten by any other shardings. + """ + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + REPLICATED: OpSharding.Type.ValueType # 0 + """This sharding is replicated across all devices (implies maximal, + all other fields are unused). + """ + MAXIMAL: OpSharding.Type.ValueType # 1 + """This sharding is maximal - one device runs the entire operation.""" + TUPLE: OpSharding.Type.ValueType # 2 + """This sharding is a tuple - only the tuple_shardings field is valid.""" + OTHER: OpSharding.Type.ValueType # 3 + """None of the above; tile_shape and tile_assignment are both used.""" + MANUAL: OpSharding.Type.ValueType # 4 + """This op is manually sharded: the shapes are already partitioned and the + partitioner should not change this op. + """ + UNKNOWN: OpSharding.Type.ValueType # 5 + """This sharding is a placeholder sharding with lowest precedence, it can be + overwriten by any other shardings. + """ + + class _ShardGroupType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ShardGroupTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[OpSharding._ShardGroupType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AS: OpSharding._ShardGroupType.ValueType # 0 + """This op will be sharded exactly the same as the other op. (hard + restriction) + """ + LIKE: OpSharding._ShardGroupType.ValueType # 1 + """This op will try to allow sharding propagation within the same group even + there is no data dependencies among them, but there is no guarantee that + the final shardings within the same group will be exactly the same. (soft + restriction) + """ + + class ShardGroupType(_ShardGroupType, metaclass=_ShardGroupTypeEnumTypeWrapper): + """Used to decide whether this op is to be sharded like some other ops, or to + which other ops will be sharded like. + """ + + AS: OpSharding.ShardGroupType.ValueType # 0 + """This op will be sharded exactly the same as the other op. (hard + restriction) + """ + LIKE: OpSharding.ShardGroupType.ValueType # 1 + """This op will try to allow sharding propagation within the same group even + there is no data dependencies among them, but there is no guarantee that + the final shardings within the same group will be exactly the same. (soft + restriction) + """ + + TYPE_FIELD_NUMBER: builtins.int + TILE_SHAPE_FIELD_NUMBER: builtins.int + TILE_ASSIGNMENT_DIMENSIONS_FIELD_NUMBER: builtins.int + TILE_ASSIGNMENT_DEVICES_FIELD_NUMBER: builtins.int + TUPLE_SHARDINGS_FIELD_NUMBER: builtins.int + REPLICATE_ON_LAST_TILE_DIM_FIELD_NUMBER: builtins.int + METADATA_FIELD_NUMBER: builtins.int + LAST_TILE_DIMS_FIELD_NUMBER: builtins.int + IOTA_RESHAPE_DIMS_FIELD_NUMBER: builtins.int + IOTA_TRANSPOSE_PERM_FIELD_NUMBER: builtins.int + IS_SHARD_GROUP_FIELD_NUMBER: builtins.int + SHARD_GROUP_ID_FIELD_NUMBER: builtins.int + SHARD_GROUP_TYPE_FIELD_NUMBER: builtins.int + type: global___OpSharding.Type.ValueType + replicate_on_last_tile_dim: builtins.bool + """Only used for OTHER type. If true, data is sharded according to other + dimensions of tile_assignment(), but replicated across devices along the + last dimension. (Experimental) + """ + is_shard_group: builtins.bool + """This field decides whether this op is in a shard group.""" + shard_group_id: builtins.int + """This field is used to store the unique id of the shard group.""" + shard_group_type: global___OpSharding.ShardGroupType.ValueType + @property + def tile_shape(self) -> global___ShapeProto: + """The shape of the sharded tile.""" + + @property + def tile_assignment_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The shape of the tile assignment tensor - this must be the same rank as + tile_shape and the product of its dimensions must equal + tile_assignment_devices.size(). + """ + + @property + def tile_assignment_devices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Flattened list of device IDs. The order of flattening is the same as used + by IndexUtil::MultiToLinearIndex(tile_assignment_shape). + Only one of tile_assignment_devices and iota_dimensions shall be non-empty. + """ + + @property + def tuple_shardings(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OpSharding]: + """If type == TUPLE, the sub-shardings, one per leaf node in the tuple shape, + in pre-order. The tuple shape could be nested; here we store just a + flattened list of all leaves in the tuple shape. Note that the tuple shape + is not stored here; shardings do not store the shapes to which they are + applied, this is inferred from the instruction this sharding gets attached + to. + """ + + @property + def metadata(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OpMetadata]: + """This field is used to track the source of this sharding, usually derived + from instructions. Multple metadata may be populated if sharding is + combined with other shardings. Metadata are to not be populated when + type == TUPLE and instead metadata should be set on individual tuple + elements. + """ + + @property + def last_tile_dims( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___OpSharding.Type.ValueType]: + """This field is used to represented the sharding type of each subgroup. + For example, sharding={devices=[2,2,2,2]0,1,2,...,15 last_tile_dims={ + replicate, manual, unreduced}} means that each of the last 3 dimensions + in [2,2,2,2] represents a subgrouping in replicate, manual, + unreduced sharding type respectively. + """ + + @property + def iota_reshape_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Dimensions used to reshape the 1D iota array of device IDs. + Only one of tile_assignment_devices and iota_reshape_dims shall be + non-empty. + """ + + @property + def iota_transpose_perm(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Dimension permutations to transposed the iota array reshaped to + iota_reshape_dims. This must have the same size as iota_reshape_dims. + """ + + def __init__( + self, + *, + type: global___OpSharding.Type.ValueType | None = ..., + tile_shape: global___ShapeProto | None = ..., + tile_assignment_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + tile_assignment_devices: collections.abc.Iterable[builtins.int] | None = ..., + tuple_shardings: collections.abc.Iterable[global___OpSharding] | None = ..., + replicate_on_last_tile_dim: builtins.bool | None = ..., + metadata: collections.abc.Iterable[global___OpMetadata] | None = ..., + last_tile_dims: collections.abc.Iterable[global___OpSharding.Type.ValueType] | None = ..., + iota_reshape_dims: collections.abc.Iterable[builtins.int] | None = ..., + iota_transpose_perm: collections.abc.Iterable[builtins.int] | None = ..., + is_shard_group: builtins.bool | None = ..., + shard_group_id: builtins.int | None = ..., + shard_group_type: global___OpSharding.ShardGroupType.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["tile_shape", b"tile_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "iota_reshape_dims", + b"iota_reshape_dims", + "iota_transpose_perm", + b"iota_transpose_perm", + "is_shard_group", + b"is_shard_group", + "last_tile_dims", + b"last_tile_dims", + "metadata", + b"metadata", + "replicate_on_last_tile_dim", + b"replicate_on_last_tile_dim", + "shard_group_id", + b"shard_group_id", + "shard_group_type", + b"shard_group_type", + "tile_assignment_devices", + b"tile_assignment_devices", + "tile_assignment_dimensions", + b"tile_assignment_dimensions", + "tile_shape", + b"tile_shape", + "tuple_shardings", + b"tuple_shardings", + "type", + b"type", + ], + ) -> None: ... + +global___OpSharding = OpSharding + +@typing.final +class ReplicaGroup(google.protobuf.message.Message): + """Describes the replica groups in a cross replica op (e.g., all-reduce and + all-to-all). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICA_IDS_FIELD_NUMBER: builtins.int + @property + def replica_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The ids of the replicas that belongs to the same group. The ordering of the + ids matters in some ops (e.g., all-to-all). + """ + + def __init__(self, *, replica_ids: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["replica_ids", b"replica_ids"]) -> None: ... + +global___ReplicaGroup = ReplicaGroup + +@typing.final +class IotaReplicaGroupListProto(google.protobuf.message.Message): + """Represents a list of replica groups (a list of list of devices) with + reshaping and transposing an iota array (iota tile assignment). Can be used + to represent certain common patterns of device lists in a compact, scalable + format. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NUM_REPLICA_GROUPS_FIELD_NUMBER: builtins.int + NUM_DEVICES_PER_GROUP_FIELD_NUMBER: builtins.int + IOTA_RESHAPE_DIMS_FIELD_NUMBER: builtins.int + IOTA_TRANSPOSE_PERM_FIELD_NUMBER: builtins.int + num_replica_groups: builtins.int + """Number of replica groups.""" + num_devices_per_group: builtins.int + """Number of devices per group.""" + @property + def iota_reshape_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimensions used to reshape the 1D iota array of device IDs.""" + + @property + def iota_transpose_perm(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension permutations to transposed the iota array reshaped to + iota_reshape_dims. This must have the same size as iota_reshape_dims. + """ + + def __init__( + self, + *, + num_replica_groups: builtins.int | None = ..., + num_devices_per_group: builtins.int | None = ..., + iota_reshape_dims: collections.abc.Iterable[builtins.int] | None = ..., + iota_transpose_perm: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "iota_reshape_dims", + b"iota_reshape_dims", + "iota_transpose_perm", + b"iota_transpose_perm", + "num_devices_per_group", + b"num_devices_per_group", + "num_replica_groups", + b"num_replica_groups", + ], + ) -> None: ... + +global___IotaReplicaGroupListProto = IotaReplicaGroupListProto + +@typing.final +class CollectiveDeviceListProto(google.protobuf.message.Message): + """Represents a series of devices participating in a collective operation (e.g., + all-reduce and all-to-all). While this directly translates to a list of + replica groups, it may be used to represent these lists in a compact form. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICA_GROUPS_FIELD_NUMBER: builtins.int + IOTA_REPLICA_GROUP_LIST_FIELD_NUMBER: builtins.int + @property + def replica_groups(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ReplicaGroup]: + """ReplicaGroupV1: List of replica groups. Legacy way of representing device + lists. + """ + + @property + def iota_replica_group_list(self) -> global___IotaReplicaGroupListProto: + """ReplicaGroupV2: Represents a list of replica groups with reshaping and + transposing an iota array. + """ + + def __init__( + self, + *, + replica_groups: collections.abc.Iterable[global___ReplicaGroup] | None = ..., + iota_replica_group_list: global___IotaReplicaGroupListProto | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["iota_replica_group_list", b"iota_replica_group_list"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal["iota_replica_group_list", b"iota_replica_group_list", "replica_groups", b"replica_groups"], + ) -> None: ... + +global___CollectiveDeviceListProto = CollectiveDeviceListProto + +@typing.final +class SourceTarget(google.protobuf.message.Message): + """Describes the source target pair in the collective permute op.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOURCE_FIELD_NUMBER: builtins.int + TARGET_FIELD_NUMBER: builtins.int + source: builtins.int + target: builtins.int + def __init__(self, *, source: builtins.int | None = ..., target: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["source", b"source", "target", b"target"]) -> None: ... + +global___SourceTarget = SourceTarget + +@typing.final +class PrecisionConfig(google.protobuf.message.Message): + """Used to indicate the precision configuration. It has backend specific + meaning. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Precision: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _PrecisionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[PrecisionConfig._Precision.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DEFAULT: PrecisionConfig._Precision.ValueType # 0 + HIGH: PrecisionConfig._Precision.ValueType # 1 + HIGHEST: PrecisionConfig._Precision.ValueType # 2 + PACKED_NIBBLE: PrecisionConfig._Precision.ValueType # 3 + """Each U8/S8 value in a tensor actually represents 2 nibble values.""" + + class Precision(_Precision, metaclass=_PrecisionEnumTypeWrapper): ... + DEFAULT: PrecisionConfig.Precision.ValueType # 0 + HIGH: PrecisionConfig.Precision.ValueType # 1 + HIGHEST: PrecisionConfig.Precision.ValueType # 2 + PACKED_NIBBLE: PrecisionConfig.Precision.ValueType # 3 + """Each U8/S8 value in a tensor actually represents 2 nibble values.""" + + class _Algorithm: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _AlgorithmEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[PrecisionConfig._Algorithm.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ALG_UNSET: PrecisionConfig._Algorithm.ValueType # 0 + """If the algorithm is `ALG_UNSET`, we will decide the algorithm based on + the operand_precision values (for now). + """ + ALG_DOT_ANY_F8_ANY_F8_F32: PrecisionConfig._Algorithm.ValueType # 1 + """The storage type can be any 8-bit floating point type.""" + ALG_DOT_ANY_F8_ANY_F8_F32_FAST_ACCUM: PrecisionConfig._Algorithm.ValueType # 2 + """The storage type can be any 8-bit floating point type. Intermediate + results will not periodically be promoted to a higher precision. This + corresponds to CUBLASLT_MATMUL_DESC_FAST_ACCUM. Triton's + maxNumImpreciseAcc=32 setting may be similar. + """ + ALG_DOT_F16_F16_F16: PrecisionConfig._Algorithm.ValueType # 3 + ALG_DOT_F16_F16_F32: PrecisionConfig._Algorithm.ValueType # 4 + ALG_DOT_BF16_BF16_BF16: PrecisionConfig._Algorithm.ValueType # 5 + ALG_DOT_BF16_BF16_F32: PrecisionConfig._Algorithm.ValueType # 6 + ALG_DOT_BF16_BF16_F32_X3: PrecisionConfig._Algorithm.ValueType # 7 + """An algorithm which uses 3 BF16_BF16_F32 matmuls to achieve better + precision. + """ + ALG_DOT_BF16_BF16_F32_X6: PrecisionConfig._Algorithm.ValueType # 8 + """An algorithm which uses 6 BF16_BF16_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_TF32_TF32_F32: PrecisionConfig._Algorithm.ValueType # 9 + ALG_DOT_TF32_TF32_F32_X3: PrecisionConfig._Algorithm.ValueType # 10 + """An algorithm which uses 3 TF32_TF32_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_F32_F32_F32: PrecisionConfig._Algorithm.ValueType # 11 + ALG_DOT_F64_F64_F64: PrecisionConfig._Algorithm.ValueType # 12 + + class Algorithm(_Algorithm, metaclass=_AlgorithmEnumTypeWrapper): + """The algorithm used to evaluate the instruction. + + The naming convention for the dot instruction is + ALG_DOT_{A_TYPE}_{B_TYPE}_{ACCUM_TYPE}[_X{NUM_OPS}] where A_TYPE, B_TYPE + and ACCUM_TYPE correspond to the types in the "primitive dot operations" + (such as TensorCore operations) and NUM_OPS is the number of such + operations used per "primitive tile". When the NUM_OPS + field is skipped, it is assumed to be 1. The types mentioned in the name + are independent of the storage types. + + In general ATYPE and BTYPE are the precisions that the LHS and RHS of the + operation are rounded to and ACCUMTYPE is the accumulation type. If a + backend does not support the given algorithm, an error is raised. The + Algorithm enum is intended to eventually replace the Precision enum. + """ + + ALG_UNSET: PrecisionConfig.Algorithm.ValueType # 0 + """If the algorithm is `ALG_UNSET`, we will decide the algorithm based on + the operand_precision values (for now). + """ + ALG_DOT_ANY_F8_ANY_F8_F32: PrecisionConfig.Algorithm.ValueType # 1 + """The storage type can be any 8-bit floating point type.""" + ALG_DOT_ANY_F8_ANY_F8_F32_FAST_ACCUM: PrecisionConfig.Algorithm.ValueType # 2 + """The storage type can be any 8-bit floating point type. Intermediate + results will not periodically be promoted to a higher precision. This + corresponds to CUBLASLT_MATMUL_DESC_FAST_ACCUM. Triton's + maxNumImpreciseAcc=32 setting may be similar. + """ + ALG_DOT_F16_F16_F16: PrecisionConfig.Algorithm.ValueType # 3 + ALG_DOT_F16_F16_F32: PrecisionConfig.Algorithm.ValueType # 4 + ALG_DOT_BF16_BF16_BF16: PrecisionConfig.Algorithm.ValueType # 5 + ALG_DOT_BF16_BF16_F32: PrecisionConfig.Algorithm.ValueType # 6 + ALG_DOT_BF16_BF16_F32_X3: PrecisionConfig.Algorithm.ValueType # 7 + """An algorithm which uses 3 BF16_BF16_F32 matmuls to achieve better + precision. + """ + ALG_DOT_BF16_BF16_F32_X6: PrecisionConfig.Algorithm.ValueType # 8 + """An algorithm which uses 6 BF16_BF16_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_TF32_TF32_F32: PrecisionConfig.Algorithm.ValueType # 9 + ALG_DOT_TF32_TF32_F32_X3: PrecisionConfig.Algorithm.ValueType # 10 + """An algorithm which uses 3 TF32_TF32_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_F32_F32_F32: PrecisionConfig.Algorithm.ValueType # 11 + ALG_DOT_F64_F64_F64: PrecisionConfig.Algorithm.ValueType # 12 + + OPERAND_PRECISION_FIELD_NUMBER: builtins.int + ALGORITHM_FIELD_NUMBER: builtins.int + algorithm: global___PrecisionConfig.Algorithm.ValueType + """Currently doesn't do anything, but we plan to support it for dot and + possibly more instructions. + + TODO(b/316147294): Support this on GPU and add this to StableHLO as well. + + If this is set, then `operand_precision` should be set to DEFAULT and it + will be ignored. + """ + @property + def operand_precision( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___PrecisionConfig.Precision.ValueType]: ... + def __init__( + self, + *, + operand_precision: collections.abc.Iterable[global___PrecisionConfig.Precision.ValueType] | None = ..., + algorithm: global___PrecisionConfig.Algorithm.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["algorithm", b"algorithm", "operand_precision", b"operand_precision"] + ) -> None: ... + +global___PrecisionConfig = PrecisionConfig + +@typing.final +class ParameterReplication(google.protobuf.message.Message): + """Describes whether all data-parallelism replicas will receive the same + parameter data at each buffer. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICATED_AT_LEAF_BUFFERS_FIELD_NUMBER: builtins.int + @property + def replicated_at_leaf_buffers(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """A list of boolean values for the flattened leaf buffers. Each value + indicates whether the corresponding leaf buffer is replicated. + + If this field is empty, it means no buffer is replicated. Otherwise, the + number of elements in this field must match the number of leaf buffers in + the HLO instruction's shape. + """ + + def __init__(self, *, replicated_at_leaf_buffers: collections.abc.Iterable[builtins.bool] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["replicated_at_leaf_buffers", b"replicated_at_leaf_buffers"]) -> None: ... + +global___ParameterReplication = ParameterReplication + +@typing.final +class WhileLoopBackendConfig(google.protobuf.message.Message): + """A backend-config for kWhile loops that stores the loop's trip count, if it is + known. + + This is useful for backends that can implement a `for i in 0..N` loop more + efficiently than a `while` loop. For example, on GPUs, we can implement a + `for i in 0..N` loop by enqueueing the kernels for the loop body N times, + whereas implementing a `while` loop requires a host-device sync on each + iteration. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class KnownTripCount(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + N_FIELD_NUMBER: builtins.int + n: builtins.int + def __init__(self, *, n: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["n", b"n"]) -> None: ... + + KNOWN_TRIP_COUNT_FIELD_NUMBER: builtins.int + @property + def known_trip_count(self) -> global___WhileLoopBackendConfig.KnownTripCount: + """This indirection lets us distinguish between known-trip-count == 0 and + unknown-trip-count. + """ + + def __init__(self, *, known_trip_count: global___WhileLoopBackendConfig.KnownTripCount | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["known_trip_count", b"known_trip_count"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["known_trip_count", b"known_trip_count"]) -> None: ... + +global___WhileLoopBackendConfig = WhileLoopBackendConfig + +@typing.final +class OutputOperandAliasing(google.protobuf.message.Message): + """Specifies a pair of output/operand buffers that alias each other for + kCustomCall and kFusion + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OUTPUT_SHAPE_INDEX_FIELD_NUMBER: builtins.int + OPERAND_INDEX_FIELD_NUMBER: builtins.int + OPERAND_SHAPE_INDEX_FIELD_NUMBER: builtins.int + operand_index: builtins.int + @property + def output_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def operand_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + output_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + operand_index: builtins.int | None = ..., + operand_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "operand_index", + b"operand_index", + "operand_shape_index", + b"operand_shape_index", + "output_shape_index", + b"output_shape_index", + ], + ) -> None: ... + +global___OutputOperandAliasing = OutputOperandAliasing + +@typing.final +class OriginalArrayProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LEAF_SHAPE_INDEX_FIELD_NUMBER: builtins.int + INSTRUCTION_NAME_FIELD_NUMBER: builtins.int + SHAPE_INDEX_FIELD_NUMBER: builtins.int + instruction_name: builtins.str + @property + def leaf_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + leaf_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + instruction_name: builtins.str | None = ..., + shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "instruction_name", b"instruction_name", "leaf_shape_index", b"leaf_shape_index", "shape_index", b"shape_index" + ], + ) -> None: ... + +global___OriginalArrayProto = OriginalArrayProto + +@typing.final +class OriginalValueProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LEAVES_FIELD_NUMBER: builtins.int + @property + def leaves(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OriginalArrayProto]: ... + def __init__(self, *, leaves: collections.abc.Iterable[global___OriginalArrayProto] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["leaves", b"leaves"]) -> None: ... + +global___OriginalValueProto = OriginalValueProto diff --git a/stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi new file mode 100644 index 000000000000..17820b9e12c0 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi @@ -0,0 +1,2558 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2017 The OpenXLA Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +============================================================================== +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.compiler.xla.service.hlo_pb2 +import tensorflow.compiler.xla.xla_data_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CompilationEnvironmentsProto(google.protobuf.message.Message): + """Proto version of `xla::CompilationEnvironments`.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ENVIRONMENTS_FIELD_NUMBER: builtins.int + @property + def environments( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.any_pb2.Any]: ... + def __init__(self, *, environments: collections.abc.Iterable[google.protobuf.any_pb2.Any] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["environments", b"environments"]) -> None: ... + +global___CompilationEnvironmentsProto = CompilationEnvironmentsProto + +@typing.final +class DebugOptions(google.protobuf.message.Message): + """Debugging options for XLA. These options may change at any time - there are + no guarantees about backward or forward compatibility for these fields. + + Debug options naming and organization: + + 1. Backend-agnostic options: `xla_$flag_name` - go first, and sorted + alphabetically by the flag name. + + 2. Backend-specific options: `xla_$backend_$flag_name` - must be in the + corresponding backend section, and sorted alphabetically by the flag name. + --------------------------------------------------------------------------// + XLA backend-agnostic options. + --------------------------------------------------------------------------// + go/keep-sorted start + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ShapeChecks: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ShapeChecksEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._ShapeChecks.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + IGNORE: DebugOptions._ShapeChecks.ValueType # 0 + """Do not insert any shape checks for dynamically shaped operations; output + buffers might contain garbage data if shapes don't match. + """ + RUNTIME: DebugOptions._ShapeChecks.ValueType # 1 + """Check shapes at runtime, will insert an extra synchronization if shapes + cannot be proven correct at compile time. + """ + COMPILE_TIME: DebugOptions._ShapeChecks.ValueType # 2 + """Will refuse to compile any program where shape correctness can not be + established at compile time. + """ + + class ShapeChecks(_ShapeChecks, metaclass=_ShapeChecksEnumTypeWrapper): ... + IGNORE: DebugOptions.ShapeChecks.ValueType # 0 + """Do not insert any shape checks for dynamically shaped operations; output + buffers might contain garbage data if shapes don't match. + """ + RUNTIME: DebugOptions.ShapeChecks.ValueType # 1 + """Check shapes at runtime, will insert an extra synchronization if shapes + cannot be proven correct at compile time. + """ + COMPILE_TIME: DebugOptions.ShapeChecks.ValueType # 2 + """Will refuse to compile any program where shape correctness can not be + established at compile time. + """ + + class _StepMarkerLocation: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _StepMarkerLocationEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._StepMarkerLocation.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + STEP_MARK_AT_ENTRY: DebugOptions._StepMarkerLocation.ValueType # 0 + """Generate a step marker at the program entry. This handles the case where + each step is done by one or multiple program execution(s). Only the first + program will be tagged for generating a step marker at the program entry. + This is the default. + """ + STEP_MARK_AT_TOP_LEVEL_WHILE_LOOP: DebugOptions._StepMarkerLocation.ValueType # 1 + """Generate a step marker at each iteration of the top level while loop, + which is assumed to be a training loop. + """ + STEP_MARK_AT_SECOND_LEVEL_WHILE_LOOP: DebugOptions._StepMarkerLocation.ValueType # 3 + """Generate a step marker at each iteration of the second level while loops, + which is assumed to be a training or eval loop. + """ + STEP_MARK_NONE: DebugOptions._StepMarkerLocation.ValueType # 2 + """No step marker generated.""" + + class StepMarkerLocation(_StepMarkerLocation, metaclass=_StepMarkerLocationEnumTypeWrapper): ... + STEP_MARK_AT_ENTRY: DebugOptions.StepMarkerLocation.ValueType # 0 + """Generate a step marker at the program entry. This handles the case where + each step is done by one or multiple program execution(s). Only the first + program will be tagged for generating a step marker at the program entry. + This is the default. + """ + STEP_MARK_AT_TOP_LEVEL_WHILE_LOOP: DebugOptions.StepMarkerLocation.ValueType # 1 + """Generate a step marker at each iteration of the top level while loop, + which is assumed to be a training loop. + """ + STEP_MARK_AT_SECOND_LEVEL_WHILE_LOOP: DebugOptions.StepMarkerLocation.ValueType # 3 + """Generate a step marker at each iteration of the second level while loops, + which is assumed to be a training or eval loop. + """ + STEP_MARK_NONE: DebugOptions.StepMarkerLocation.ValueType # 2 + """No step marker generated.""" + + class _CollectiveOpType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CollectiveOpTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._CollectiveOpType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NOOP: DebugOptions._CollectiveOpType.ValueType # 0 + ALLREDUCE: DebugOptions._CollectiveOpType.ValueType # 1 + ALLGATHER: DebugOptions._CollectiveOpType.ValueType # 2 + REDUCESCATTER: DebugOptions._CollectiveOpType.ValueType # 3 + COLLECTIVEBROADCAST: DebugOptions._CollectiveOpType.ValueType # 4 + ALLTOALL: DebugOptions._CollectiveOpType.ValueType # 5 + COLLECTIVEPERMUTE: DebugOptions._CollectiveOpType.ValueType # 6 + + class CollectiveOpType(_CollectiveOpType, metaclass=_CollectiveOpTypeEnumTypeWrapper): + """Enum to define all collective ops + that xla supports. + """ + + NOOP: DebugOptions.CollectiveOpType.ValueType # 0 + ALLREDUCE: DebugOptions.CollectiveOpType.ValueType # 1 + ALLGATHER: DebugOptions.CollectiveOpType.ValueType # 2 + REDUCESCATTER: DebugOptions.CollectiveOpType.ValueType # 3 + COLLECTIVEBROADCAST: DebugOptions.CollectiveOpType.ValueType # 4 + ALLTOALL: DebugOptions.CollectiveOpType.ValueType # 5 + COLLECTIVEPERMUTE: DebugOptions.CollectiveOpType.ValueType # 6 + + class _CommandBufferCmdType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CommandBufferCmdTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._CommandBufferCmdType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + INVALID: DebugOptions._CommandBufferCmdType.ValueType # 0 + FUSION: DebugOptions._CommandBufferCmdType.ValueType # 1 + CUBLAS: DebugOptions._CommandBufferCmdType.ValueType # 2 + CUDNN: DebugOptions._CommandBufferCmdType.ValueType # 3 + COLLECTIVES: DebugOptions._CommandBufferCmdType.ValueType # 4 + CONDITIONALS: DebugOptions._CommandBufferCmdType.ValueType # 5 + CUSTOM_CALL: DebugOptions._CommandBufferCmdType.ValueType # 6 + CUBLASLT: DebugOptions._CommandBufferCmdType.ValueType # 7 + + class CommandBufferCmdType(_CommandBufferCmdType, metaclass=_CommandBufferCmdTypeEnumTypeWrapper): + """Commands are categorized into 5 types: + FUSION represents regular fusion kernels. + CUBLAS/CUBLASLT, CUDNN, and COLLECTIVES represent library calls. + CONDITIONALS represents control flow. + """ + + INVALID: DebugOptions.CommandBufferCmdType.ValueType # 0 + FUSION: DebugOptions.CommandBufferCmdType.ValueType # 1 + CUBLAS: DebugOptions.CommandBufferCmdType.ValueType # 2 + CUDNN: DebugOptions.CommandBufferCmdType.ValueType # 3 + COLLECTIVES: DebugOptions.CommandBufferCmdType.ValueType # 4 + CONDITIONALS: DebugOptions.CommandBufferCmdType.ValueType # 5 + CUSTOM_CALL: DebugOptions.CommandBufferCmdType.ValueType # 6 + CUBLASLT: DebugOptions.CommandBufferCmdType.ValueType # 7 + + class _PartitioningAlgorithm: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _PartitioningAlgorithmEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._PartitioningAlgorithm.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PARTITIONING_ALGORITHM_NOOP: DebugOptions._PartitioningAlgorithm.ValueType # 0 + PARTITIONING_ALGORITHM_EXP0: DebugOptions._PartitioningAlgorithm.ValueType # 1 + PARTITIONING_ALGORITHM_EXP1: DebugOptions._PartitioningAlgorithm.ValueType # 2 + PARTITIONING_ALGORITHM_EXP2: DebugOptions._PartitioningAlgorithm.ValueType # 3 + + class PartitioningAlgorithm(_PartitioningAlgorithm, metaclass=_PartitioningAlgorithmEnumTypeWrapper): ... + PARTITIONING_ALGORITHM_NOOP: DebugOptions.PartitioningAlgorithm.ValueType # 0 + PARTITIONING_ALGORITHM_EXP0: DebugOptions.PartitioningAlgorithm.ValueType # 1 + PARTITIONING_ALGORITHM_EXP1: DebugOptions.PartitioningAlgorithm.ValueType # 2 + PARTITIONING_ALGORITHM_EXP2: DebugOptions.PartitioningAlgorithm.ValueType # 3 + + class _WhileLoopUnrolling: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _WhileLoopUnrollingEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._WhileLoopUnrolling.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + WHILE_LOOP_UNROLLING_NO_UNROLL: DebugOptions._WhileLoopUnrolling.ValueType # 0 + WHILE_LOOP_UNROLLING_DOUBLE_BUFFER: DebugOptions._WhileLoopUnrolling.ValueType # 1 + """Has the same effect as setting + `xla_gpu_enable_while_loop_double_buffering`. + """ + WHILE_LOOP_UNROLLING_FULL_UNROLL: DebugOptions._WhileLoopUnrolling.ValueType # 2 + """Enables full loop unrolling using the same strategy as `DOUBLE_BUFFER`.""" + + class WhileLoopUnrolling(_WhileLoopUnrolling, metaclass=_WhileLoopUnrollingEnumTypeWrapper): ... + WHILE_LOOP_UNROLLING_NO_UNROLL: DebugOptions.WhileLoopUnrolling.ValueType # 0 + WHILE_LOOP_UNROLLING_DOUBLE_BUFFER: DebugOptions.WhileLoopUnrolling.ValueType # 1 + """Has the same effect as setting + `xla_gpu_enable_while_loop_double_buffering`. + """ + WHILE_LOOP_UNROLLING_FULL_UNROLL: DebugOptions.WhileLoopUnrolling.ValueType # 2 + """Enables full loop unrolling using the same strategy as `DOUBLE_BUFFER`.""" + + class _AutotuneCacheMode: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _AutotuneCacheModeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._AutotuneCacheMode.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AUTOTUNE_CACHE_MODE_UNSPECIFIED: DebugOptions._AutotuneCacheMode.ValueType # 0 + AUTOTUNE_CACHE_MODE_UPDATE: DebugOptions._AutotuneCacheMode.ValueType # 1 + """If the cache exists per fusion autotuner loads it and terminates, + otherwise runs autotuner and dumps the result. + """ + AUTOTUNE_CACHE_MODE_READ: DebugOptions._AutotuneCacheMode.ValueType # 2 + """Sets readonly access to the cache for the per fusion autotuner. Same as + above, but doesn't dump anything. + """ + + class AutotuneCacheMode(_AutotuneCacheMode, metaclass=_AutotuneCacheModeEnumTypeWrapper): ... + AUTOTUNE_CACHE_MODE_UNSPECIFIED: DebugOptions.AutotuneCacheMode.ValueType # 0 + AUTOTUNE_CACHE_MODE_UPDATE: DebugOptions.AutotuneCacheMode.ValueType # 1 + """If the cache exists per fusion autotuner loads it and terminates, + otherwise runs autotuner and dumps the result. + """ + AUTOTUNE_CACHE_MODE_READ: DebugOptions.AutotuneCacheMode.ValueType # 2 + """Sets readonly access to the cache for the per fusion autotuner. Same as + above, but doesn't dump anything. + """ + + @typing.final + class XlaBackendExtraOptionsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.str + def __init__(self, *, key: builtins.str | None = ..., value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + XLA_CPU_ENABLE_CONCURRENCY_OPTIMIZED_SCHEDULER_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_FAST_MATH_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_FAST_MIN_MAX_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_DIVISION_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_FUNCTIONS_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_INFS_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_NANS_FIELD_NUMBER: builtins.int + XLA_CPU_USE_THUNK_RUNTIME_FIELD_NUMBER: builtins.int + XLA_CPU_PARALLEL_CODEGEN_SPLIT_COUNT_FIELD_NUMBER: builtins.int + XLA_CPU_PREFER_VECTOR_WIDTH_FIELD_NUMBER: builtins.int + XLA_GPU_EXPERIMENTAL_AUTOTUNE_CACHE_MODE_FIELD_NUMBER: builtins.int + XLA_GPU_EXPERIMENTAL_DISABLE_BINARY_LIBRARIES_FIELD_NUMBER: builtins.int + XLA_GPU_EXPERIMENTAL_ENABLE_TRITON_SOFTMAX_PRIORITY_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_UNSUPPORTED_ENABLE_TRITON_GEMM_FIELD_NUMBER: builtins.int + XLA_HLO_GRAPH_ADDRESSES_FIELD_NUMBER: builtins.int + XLA_HLO_PROFILE_FIELD_NUMBER: builtins.int + XLA_DISABLE_HLO_PASSES_FIELD_NUMBER: builtins.int + XLA_ENABLE_HLO_PASSES_ONLY_FIELD_NUMBER: builtins.int + XLA_DISABLE_ALL_HLO_PASSES_FIELD_NUMBER: builtins.int + XLA_BACKEND_OPTIMIZATION_LEVEL_FIELD_NUMBER: builtins.int + XLA_EMBED_IR_IN_EXECUTABLE_FIELD_NUMBER: builtins.int + XLA_ELIMINATE_HLO_IMPLICIT_BROADCAST_FIELD_NUMBER: builtins.int + XLA_CPU_MULTI_THREAD_EIGEN_FIELD_NUMBER: builtins.int + XLA_GPU_CUDA_DATA_DIR_FIELD_NUMBER: builtins.int + XLA_GPU_FTZ_FIELD_NUMBER: builtins.int + XLA_LLVM_ENABLE_ALIAS_SCOPE_METADATA_FIELD_NUMBER: builtins.int + XLA_LLVM_ENABLE_NOALIAS_METADATA_FIELD_NUMBER: builtins.int + XLA_LLVM_ENABLE_INVARIANT_LOAD_METADATA_FIELD_NUMBER: builtins.int + XLA_LLVM_DISABLE_EXPENSIVE_PASSES_FIELD_NUMBER: builtins.int + XLA_TEST_ALL_OUTPUT_LAYOUTS_FIELD_NUMBER: builtins.int + XLA_TEST_ALL_INPUT_LAYOUTS_FIELD_NUMBER: builtins.int + XLA_HLO_GRAPH_SHARDING_COLOR_FIELD_NUMBER: builtins.int + XLA_CPU_USE_MKL_DNN_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_FAST_MIN_MAX_FIELD_NUMBER: builtins.int + XLA_ALLOW_EXCESS_PRECISION_FIELD_NUMBER: builtins.int + XLA_GPU_CRASH_ON_VERIFICATION_FAILURES_FIELD_NUMBER: builtins.int + XLA_GPU_AUTOTUNE_LEVEL_FIELD_NUMBER: builtins.int + XLA_FORCE_HOST_PLATFORM_DEVICE_COUNT_FIELD_NUMBER: builtins.int + XLA_GPU_DISABLE_GPUASM_OPTIMIZATIONS_FIELD_NUMBER: builtins.int + XLA_GPU_SHAPE_CHECKS_FIELD_NUMBER: builtins.int + XLA_HLO_EVALUATOR_USE_FAST_PATH_FIELD_NUMBER: builtins.int + XLA_ALLOW_SCALAR_INDEX_DYNAMIC_OPS_FIELD_NUMBER: builtins.int + XLA_STEP_MARKER_LOCATION_FIELD_NUMBER: builtins.int + XLA_DUMP_TO_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_MODULE_RE_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_PASS_RE_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_TEXT_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_PROTO_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_DOT_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_URL_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_HTML_FIELD_NUMBER: builtins.int + XLA_DUMP_FUSION_VISUALIZATION_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_SNAPSHOTS_FIELD_NUMBER: builtins.int + XLA_DUMP_INCLUDE_TIMESTAMP_FIELD_NUMBER: builtins.int + XLA_DUMP_MAX_HLO_MODULES_FIELD_NUMBER: builtins.int + XLA_DUMP_MODULE_METADATA_FIELD_NUMBER: builtins.int + XLA_DUMP_COMPRESS_PROTOS_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_LONG_TEXT_FIELD_NUMBER: builtins.int + XLA_GPU_FORCE_CONV_NCHW_FIELD_NUMBER: builtins.int + XLA_GPU_FORCE_CONV_NHWC_FIELD_NUMBER: builtins.int + XLA_GPU_PTX_FILE_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_LLVMIR_FIELD_NUMBER: builtins.int + XLA_DUMP_ENABLE_MLIR_PRETTY_FORM_FIELD_NUMBER: builtins.int + XLA_GPU_ALGORITHM_DENYLIST_PATH_FIELD_NUMBER: builtins.int + XLA_TPU_DETECT_NAN_FIELD_NUMBER: builtins.int + XLA_TPU_DETECT_INF_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_XPROF_TRACEME_FIELD_NUMBER: builtins.int + XLA_GPU_UNSAFE_FALLBACK_TO_DRIVER_ON_PTXAS_NOT_FOUND_FIELD_NUMBER: builtins.int + XLA_GPU_ASM_EXTRA_FLAGS_FIELD_NUMBER: builtins.int + XLA_MULTIHEAP_SIZE_CONSTRAINT_PER_HEAP_FIELD_NUMBER: builtins.int + XLA_DETAILED_LOGGING_FIELD_NUMBER: builtins.int + XLA_ENABLE_DUMPING_FIELD_NUMBER: builtins.int + XLA_GPU_FORCE_COMPILATION_PARALLELISM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LLVM_MODULE_COMPILATION_PARALLELISM_FIELD_NUMBER: builtins.int + XLA_GPU_DETERMINISTIC_OPS_FIELD_NUMBER: builtins.int + XLA_GPU_LLVM_IR_FILE_FIELD_NUMBER: builtins.int + XLA_GPU_DISABLE_ASYNC_COLLECTIVES_FIELD_NUMBER: builtins.int + XLA_GPU_ALL_REDUCE_COMBINE_THRESHOLD_BYTES_FIELD_NUMBER: builtins.int + XLA_GPU_ALL_GATHER_COMBINE_THRESHOLD_BYTES_FIELD_NUMBER: builtins.int + XLA_GPU_REDUCE_SCATTER_COMBINE_THRESHOLD_BYTES_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_ALL_GATHER_COMBINE_BY_DIM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_REDUCE_SCATTER_COMBINE_BY_DIM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_REASSOCIATION_FOR_CONVERTED_AR_FIELD_NUMBER: builtins.int + XLA_GPU_ALL_REDUCE_BLUECONNECT_NUM_DEVICES_PER_HOST_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_WHILE_LOOP_REDUCE_SCATTER_CODE_MOTION_FIELD_NUMBER: builtins.int + XLA_GPU_COLLECTIVE_INFLATION_FACTOR_FIELD_NUMBER: builtins.int + XLA_LLVM_FORCE_INLINE_BEFORE_SPLIT_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_FRONTEND_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_FMHA_FIELD_NUMBER: builtins.int + XLA_GPU_FUSED_ATTENTION_USE_CUDNN_RNG_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_LAYER_NORM_FIELD_NUMBER: builtins.int + XLA_DUMP_DISABLE_METADATA_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_PIPELINE_RE_FIELD_NUMBER: builtins.int + XLA_GPU_STRICT_CONV_ALGORITHM_PICKER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUSTOM_FUSIONS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUSTOM_FUSIONS_RE_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_DYNAMIC_SLICE_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_TERMINATION_TIMEOUT_SECONDS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_SHARED_CONSTANTS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUBLASLT_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_COMMAND_BUFFER_FIELD_NUMBER: builtins.int + XLA_GPU_GRAPH_MIN_GRAPH_SIZE_FIELD_NUMBER: builtins.int + XLA_GPU_GRAPH_ENABLE_CONCURRENT_REGION_FIELD_NUMBER: builtins.int + XLA_GPU_REDZONE_SCRATCH_MAX_MEGABYTES_FIELD_NUMBER: builtins.int + XLA_GPU_REDZONE_PADDING_BYTES_FIELD_NUMBER: builtins.int + XLA_CPU_USE_ACL_FIELD_NUMBER: builtins.int + XLA_CPU_STRICT_DOT_CONV_MATH_FIELD_NUMBER: builtins.int + XLA_GPU_USE_RUNTIME_FUSION_FIELD_NUMBER: builtins.int + XLA_DUMP_LATENCY_HIDING_SCHEDULE_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_MLIR_TILING_AND_FUSION_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_CUSTOM_MATMUL_TILING_FIELD_NUMBER: builtins.int + XLA_CPU_MATMUL_TILING_M_DIM_FIELD_NUMBER: builtins.int + XLA_CPU_MATMUL_TILING_N_DIM_FIELD_NUMBER: builtins.int + XLA_CPU_MATMUL_TILING_K_DIM_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_MLIR_FUSION_OUTLINING_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_EXPERIMENTAL_DEALLOCATION_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LATENCY_HIDING_SCHEDULER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_HIGHEST_PRIORITY_ASYNC_STREAM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_ANALYTICAL_LATENCY_ESTIMATOR_FIELD_NUMBER: builtins.int + XLA_GPU_LHS_ENABLE_GPU_ASYNC_TRACKER_FIELD_NUMBER: builtins.int + XLA_GPU_PGLE_PROFILE_FILE_OR_DIRECTORY_PATH_FIELD_NUMBER: builtins.int + XLA_GPU_MEMORY_LIMIT_SLOP_FACTOR_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_COLLECTIVES_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_ALL_REDUCE_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_ALL_GATHER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_REDUCE_SCATTER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_P2P_FIELD_NUMBER: builtins.int + XLA_GPU_RUN_POST_LAYOUT_COLLECTIVE_PIPELINER_FIELD_NUMBER: builtins.int + XLA_GPU_COLLECTIVE_PERMUTE_DECOMPOSER_THRESHOLD_FIELD_NUMBER: builtins.int + XLA_PARTITIONING_ALGORITHM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_TRITON_GEMM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_INT8X32_CONVOLUTION_REORDERING_FIELD_NUMBER: builtins.int + XLA_GPU_TRITON_GEMM_ANY_FIELD_NUMBER: builtins.int + XLA_GPU_EXHAUSTIVE_TILING_SEARCH_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PRIORITY_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_AUTOTUNE_RESULTS_TO_FIELD_NUMBER: builtins.int + XLA_GPU_LOAD_AUTOTUNE_RESULTS_FROM_FIELD_NUMBER: builtins.int + XLA_GPU_TARGET_CONFIG_FILENAME_FIELD_NUMBER: builtins.int + XLA_GPU_AUTO_SPMD_PARTITIONING_MEMORY_BUDGET_GB_FIELD_NUMBER: builtins.int + XLA_GPU_AUTO_SPMD_PARTITIONING_MEMORY_BUDGET_RATIO_FIELD_NUMBER: builtins.int + XLA_GPU_TRITON_GEMM_DISABLE_REDUCED_PRECISION_REDUCTION_FIELD_NUMBER: builtins.int + XLA_GPU_TRITON_FUSION_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_AUTOTUNED_GEMM_FUSIONS_FIELD_NUMBER: builtins.int + XLA_GPU_OVERRIDE_GEMM_AUTOTUNER_FIELD_NUMBER: builtins.int + XLA_GPU_COPY_INSERTION_USE_REGION_ANALYSIS_FIELD_NUMBER: builtins.int + XLA_GPU_COLLECT_COST_MODEL_STATS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_SPLIT_K_AUTOTUNING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_REDUCTION_EPILOGUE_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_CLIQUE_OPTIMIZATION_FIELD_NUMBER: builtins.int + XLA_GPU_MOCK_CUSTOM_CALLS_FIELD_NUMBER: builtins.int + XLA_GPU_CUBLAS_FALLBACK_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_WHILE_LOOP_DOUBLE_BUFFERING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_WHILE_LOOP_UNROLLING_FIELD_NUMBER: builtins.int + XLA_GPU_ENSURE_MINOR_DOT_CONTRACTION_DIMS_FIELD_NUMBER: builtins.int + XLA_GPU_FILTER_KERNELS_SPILLING_REGISTERS_ON_AUTOTUNING_FIELD_NUMBER: builtins.int + XLA_DEBUG_BUFFER_ASSIGNMENT_SHOW_MAX_FIELD_NUMBER: builtins.int + XLA_GPU_LLVM_VERIFICATION_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUB_RADIX_SORT_FIELD_NUMBER: builtins.int + XLA_GPU_THRESHOLD_FOR_WINDOWED_EINSUM_MIB_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_TRITON_HOPPER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_USER_BUFFERS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_COMM_SPLITTING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_PER_STREAM_COMMS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LIBNVPTXCOMPILER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_DOT_STRENGTH_REDUCTION_FIELD_NUMBER: builtins.int + XLA_GPU_MULTI_STREAMED_WINDOWED_EINSUM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_BF16_6WAY_GEMM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_BF16_3WAY_GEMM_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_COLLECTIVE_MAX_NCHANNELS_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_P2P_MAX_NCHANNELS_FIELD_NUMBER: builtins.int + XLA_GPU_MLIR_EMITTER_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_GEMM_REWRITE_SIZE_THRESHOLD_FIELD_NUMBER: builtins.int + XLA_GPU_REQUIRE_COMPLETE_AOT_AUTOTUNE_RESULTS_FIELD_NUMBER: builtins.int + XLA_GPU_CUDNN_GEMM_FUSION_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_USE_MEMCPY_LOCAL_P2P_FIELD_NUMBER: builtins.int + XLA_GPU_AUTOTUNE_MAX_SOLUTIONS_FIELD_NUMBER: builtins.int + XLA_DUMP_LARGE_CONSTANTS_FIELD_NUMBER: builtins.int + XLA_GPU_VERIFY_TRITON_FUSION_NUMERICS_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_AUTOTUNE_LOGS_TO_FIELD_NUMBER: builtins.int + XLA_REDUCE_WINDOW_REWRITE_BASE_LENGTH_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_HOST_MEMORY_OFFLOADING_FIELD_NUMBER: builtins.int + XLA_GPU_EXCLUDE_NONDETERMINISTIC_OPS_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_TERMINATE_ON_ERROR_FIELD_NUMBER: builtins.int + XLA_GPU_SHARD_AUTOTUNING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_APPROX_COSTLY_COLLECTIVES_FIELD_NUMBER: builtins.int + XLA_GPU_KERNEL_CACHE_FILE_FIELD_NUMBER: builtins.int + XLA_GPU_UNSAFE_PIPELINED_LOOP_ANNOTATOR_FIELD_NUMBER: builtins.int + XLA_GPU_PER_FUSION_AUTOTUNE_CACHE_DIR_FIELD_NUMBER: builtins.int + XLA_CMD_BUFFER_TRACE_CACHE_SIZE_FIELD_NUMBER: builtins.int + XLA_GPU_TEMP_BUFFER_USE_SEPARATE_COLOR_FIELD_NUMBER: builtins.int + LEGACY_COMMAND_BUFFER_CUSTOM_CALL_TARGETS_FIELD_NUMBER: builtins.int + XLA_SYNTAX_SUGAR_ASYNC_OPS_FIELD_NUMBER: builtins.int + XLA_GPU_AUTOTUNE_GEMM_RTOL_FIELD_NUMBER: builtins.int + XLA_ENABLE_COMMAND_BUFFERS_DURING_PROFILING_FIELD_NUMBER: builtins.int + XLA_GPU_CUDNN_GEMM_MAX_PLANS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LIBNVJITLINK_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_TRITON_GEMM_INT4_FIELD_NUMBER: builtins.int + XLA_GPU_ASYNC_DOT_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PGLE_ACCURACY_CHECKER_FIELD_NUMBER: builtins.int + XLA_GPU_EXECUTABLE_WARN_STUCK_TIMEOUT_SECONDS_FIELD_NUMBER: builtins.int + XLA_GPU_EXECUTABLE_TERMINATE_TIMEOUT_SECONDS_FIELD_NUMBER: builtins.int + XLA_EXPERIMENTAL_IGNORE_CHANNEL_ID_FIELD_NUMBER: builtins.int + XLA_BACKEND_EXTRA_OPTIONS_FIELD_NUMBER: builtins.int + xla_cpu_enable_concurrency_optimized_scheduler: builtins.bool + """--------------------------------------------------------------------------// + XLA:CPU options. + --------------------------------------------------------------------------// + + go/keep-sorted start newline_separated=yes + + When true, XLA:CPU uses HLO module scheduler that is optimized for + extracting concurrency at the cost of extra memory: we extend the live + ranges of temporaries to allow XLA runtime to schedule independent + operations in parallel on separate threads. + """ + xla_cpu_enable_fast_math: builtins.bool + """When true, "unsafe" mathematical optimizations are enabled. These + transformations include but are not limited to: + + - Reducing the precision of operations (e.g. using an approximate sin + function, or transforming x/y into x * (1/y)). + - Assuming that operations never produce or consume NaN or +/- Inf (this + behavior can be adjusted using xla_cpu_fast_math_allow_{nans|infs}). + - Assuming that +0 and -0 are indistinguishable. + """ + xla_cpu_enable_fast_min_max: builtins.bool + """When false we lower the Minimum and Maximum hlos in the CPU backend such + that Min(NotNaN, NaN) = Min(NaN, NotNaN) = NaN. In other words, if flag + this is false we always propagate NaNs through Min and Max. + + Note, this does not correspond to the exact same behavior as the gpu flag + below! + """ + xla_cpu_fast_math_honor_division: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we forbid + to use the reciprocal of an argument instead of division. Ignored when + xla_cpu_enable_fast_math is false. + """ + xla_cpu_fast_math_honor_functions: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we forbid + to approximate calculations for functions. Ignored when + xla_cpu_enable_fast_math is false. + """ + xla_cpu_fast_math_honor_infs: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we allow + operations to produce infinites. Ignored when xla_cpu_enable_fast_math is + false. + """ + xla_cpu_fast_math_honor_nans: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we allow + operations to produce NaNs. Ignored when xla_cpu_enable_fast_math is + false. + """ + xla_cpu_use_thunk_runtime: builtins.bool + """When true, XLA:CPU uses the thunk runtime to execute compiled program.""" + xla_cpu_parallel_codegen_split_count: builtins.int + """The number of parts to split the LLVM module into before codegen. This + allows XLA to compile all parts in parallel, and resolve kernel symbols + from different dynamic libraries. + """ + xla_cpu_prefer_vector_width: builtins.int + """A `prefer-vector-width` value that is passed to the LLVM backend. Default + value is `256` (AVX2 on x86 platforms). + """ + xla_gpu_experimental_autotune_cache_mode: global___DebugOptions.AutotuneCacheMode.ValueType + """--------------------------------------------------------------------------// + XLA:GPU options. + --------------------------------------------------------------------------// + go/keep-sorted start newline_separated=yes skip_lines=1 + + Specifies the behavior of per kernel autotuning cache. + """ + xla_gpu_experimental_disable_binary_libraries: builtins.bool + """Experimentally disables binary libraries in GPU compiler passes.""" + xla_gpu_experimental_enable_triton_softmax_priority_fusion: builtins.bool + """Gates the experimental feature coupling the Triton Softmax pattern matcher + with priority fusion. + """ + xla_gpu_unsupported_enable_triton_gemm: builtins.bool + """Internal debug/testing flag to switch Triton GEMM fusions on or off.""" + xla_hlo_graph_addresses: builtins.bool + """--------------------------------------------------------------------------// + A bag of XLA options that have to be categorized. + --------------------------------------------------------------------------// + + Show addresses of HLO ops in graph dump. + """ + xla_hlo_profile: builtins.bool + """Instrument the computation to collect per-HLO cycle counts.""" + xla_disable_all_hlo_passes: builtins.bool + """Disables all HLO passes. Notes that some passes are necessary for + correctness and the invariants that must be satisfied by "fully optimized" + HLO are different for different devices and may change over time. The only + "guarantee", such as it is, is that if you compile XLA and dump the + optimized HLO for some graph, you should be able to run it again on the + same device with the same build of XLA. + """ + xla_backend_optimization_level: builtins.int + """Numerical optimization level for the XLA compiler backend; the specific + interpretation of this value is left to the backends. + """ + xla_embed_ir_in_executable: builtins.bool + """Embed the compiler IR as a string in the executable.""" + xla_eliminate_hlo_implicit_broadcast: builtins.bool + """Eliminate implicit broadcasts when lowering user computations to HLO + instructions; use explicit broadcast instead. + """ + xla_cpu_multi_thread_eigen: builtins.bool + """When generating calls to Eigen in the CPU backend, use multi-threaded Eigen + mode. + """ + xla_gpu_cuda_data_dir: builtins.str + """Path to directory with cuda/ptx tools and libraries.""" + xla_gpu_ftz: builtins.bool + """Enable flush-to-zero semantics in the GPU backend.""" + xla_llvm_enable_alias_scope_metadata: builtins.bool + """If true, in LLVM-based backends, emit !alias.scope metadata in + generated IR. + """ + xla_llvm_enable_noalias_metadata: builtins.bool + """If true, in LLVM-based backends, emit !noalias metadata in the + generated IR. + """ + xla_llvm_enable_invariant_load_metadata: builtins.bool + """If true, in LLVM-based backends, emit !invariant.load metadata in + the generated IR. + """ + xla_llvm_disable_expensive_passes: builtins.bool + """If true, a set of expensive LLVM optimization passes will not be run.""" + xla_test_all_output_layouts: builtins.bool + """This is used by ClientLibraryTestBase::ComputeAndCompare*. If true, the + computation will run n! times with all permunations of layouts for the + output shape in rank n. For example, with a 3D shape, all permutations of + the set {0, 1, 2} are tried. + """ + xla_test_all_input_layouts: builtins.bool + """This is used by ClientLibraryTestBase::ComputeAndCompare*. If true, the + computation will run for all permunations of layouts of all input + arguments. For example, with 2 input arguments in 2D and 4D shapes, the + computation will run 2! * 4! times. + """ + xla_hlo_graph_sharding_color: builtins.bool + """Assign colors based on sharding information when generating the Graphviz + HLO graph. + """ + xla_cpu_use_mkl_dnn: builtins.bool + """Generate calls to MKL-DNN in the CPU backend.""" + xla_gpu_enable_fast_min_max: builtins.bool + """When true we lower the Minimum and Maximum hlos in the GPU backend such + that Min(NotNaN, NaN) = Min(NaN, NotNaN) = NotNaN. In other words, if flag + this is true we don't propagate NaNs through Min and Max. + + Note, this does not correspond to the exact same behavior as the cpu flag + above! + """ + xla_allow_excess_precision: builtins.bool + """Allows xla to increase the output precision of floating point operations + and all floating-point conversions to be simplified, including those + that affect the numerics. The `FloatNormalization` pass inserts many + `f32 -> bf16 -> f32` conversion pairs. These are not removed by the + `AlgebraicSimplifier`, as that will only simplify conversions that are + no-ops, e.g. `bf16 -> f32 -> bf16`. Removing these improves accuracy. + """ + xla_gpu_crash_on_verification_failures: builtins.bool + """Crashes the program when any kind of verification fails, instead of just + logging the failures. One example is cross checking of convolution results + among different algorithms. + """ + xla_gpu_autotune_level: builtins.int + """0: Disable gemm and convolution autotuning. + 1: Enable autotuning, but disable correctness checking. + 2: Also set output buffers to random numbers during autotuning. + 3: Also reset output buffers to random numbers after autotuning each + algorithm. + 4+: Also check for correct outputs and for out-of-bounds reads/writes. + + Default: 4. + """ + xla_force_host_platform_device_count: builtins.int + """Force the host platform to pretend that there are these many host + "devices". All these devices are backed by the same threadpool. Defaults + to 1. + + Setting this to anything other than 1 can increase overhead from context + switching but we let the user override this behavior to help run tests on + the host that run models in parallel across multiple devices. + """ + xla_gpu_disable_gpuasm_optimizations: builtins.bool + """If set to true XLA:GPU invokes `ptxas` with -O0 (default is -O3).""" + xla_gpu_shape_checks: global___DebugOptions.ShapeChecks.ValueType + xla_hlo_evaluator_use_fast_path: builtins.bool + """Enable fast math with eigen in the HLO evaluator.""" + xla_allow_scalar_index_dynamic_ops: builtins.bool + """Temporary option to allow support for both the R1 and the scalar index + versions of DynamicSlice and DynamicUpdateSlice. Only used for testing. + """ + xla_step_marker_location: global___DebugOptions.StepMarkerLocation.ValueType + """Option to emit a target-specific marker to indicate the start of a training + step. The location of the marker (if any) is determined by the option + value. + """ + xla_dump_to: builtins.str + """ + BEGIN flags controlling dumping HLO modules for debugging. + + When dumping is enabled, HLO modules dumped at the very beginning and end + of compilation, and optionally also during the pass pipeline. + + In general, if you set one of these flags, we will try to infer reasonable + defaults for the others. For example: + + * Setting --xla_dump_to=/tmp/foo without specifying a format + with --xla_dump_hlo_as_* will turn on --xla_dump_hlo_as_text. + + * Setting --xla_dump_hlo_as_text without specifying --xla_dump_to will + dump to stdout. + + Directory to dump into. + """ + xla_dump_hlo_module_re: builtins.str + """If specified, will only dump modules which match this regexp.""" + xla_dump_hlo_pass_re: builtins.str + """If this flag is specified, will also dump HLO before and after passes that + match this regular expression. Set to .* to dump before/after all passes. + """ + xla_dump_hlo_as_text: builtins.bool + """Specifies the format that HLO is dumped in. Multiple of these may be + specified. + """ + xla_dump_hlo_as_proto: builtins.bool + xla_dump_hlo_as_dot: builtins.bool + xla_dump_hlo_as_url: builtins.bool + xla_dump_hlo_as_html: builtins.bool + """Dump HLO graphs as an HTML (DOT -> SVG inlined in HTML)""" + xla_dump_fusion_visualization: builtins.bool + """Dump the visualization of the fusion progress.""" + xla_dump_hlo_snapshots: builtins.bool + """If true, every time an HLO module is run, we will dump an HloSnapshot + (essentially, a serialized module plus its inputs) to the --xla_dump_to + directory. + """ + xla_dump_include_timestamp: builtins.bool + """Include a timestamp in the dumped filenames.""" + xla_dump_max_hlo_modules: builtins.int + """Max number of hlo module dumps in a directory. Set to < 0 for unbounded.""" + xla_dump_module_metadata: builtins.bool + """Dump HloModuleMetadata as a text proto for each HLO module.""" + xla_dump_compress_protos: builtins.bool + """GZip-compress protos dumped via --xla_dump_hlo_as_proto.""" + xla_dump_hlo_as_long_text: builtins.bool + """Dump HLO in long text format. Ignored unless xla_dump_hlo_as_text is true.""" + xla_gpu_force_conv_nchw: builtins.bool + """ + END flags controlling dumping HLO modules. + + Overrides for XLA GPU's convolution layout heuristic. + """ + xla_gpu_force_conv_nhwc: builtins.bool + xla_gpu_dump_llvmir: builtins.bool + """Whether to dump llvm ir when compiling to ptx.""" + xla_dump_enable_mlir_pretty_form: builtins.bool + """Whether to dump mlir using pretty print form.""" + xla_gpu_algorithm_denylist_path: builtins.str + """Denylist for cuDNN convolutions.""" + xla_tpu_detect_nan: builtins.bool + """Debug options that trigger execution errors when NaN or Inf are detected.""" + xla_tpu_detect_inf: builtins.bool + xla_cpu_enable_xprof_traceme: builtins.bool + """True if TraceMe annotations are enabled for XLA:CPU.""" + xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found: builtins.bool + """It is usually preferable to not fallback to the driver; it can consume more + memory, or have bugs. + """ + xla_gpu_asm_extra_flags: builtins.str + """Extra parameters to pass the GPU assembler.""" + xla_multiheap_size_constraint_per_heap: builtins.int + """Per-heap size constraint. New heaps will be created if per-heap max size is + reached. + """ + xla_detailed_logging: builtins.bool + """Enable detailed logging into vlog. If this is disabled, no + compilation summary will be printed in the end of computation. + """ + xla_enable_dumping: builtins.bool + """Enable HLO dumping. If this is disabled, no HLO modules will be dumped.""" + xla_gpu_force_compilation_parallelism: builtins.int + """Overrides normal multi-threaded compilation setting to use this many + threads. Setting to 0 (the default value) means no enforcement. + """ + xla_gpu_enable_llvm_module_compilation_parallelism: builtins.bool + xla_gpu_deterministic_ops: builtins.bool + """Guarantees run-to-run determinism. + This flag implies --xla_gpu_exclude_nondeterministic_ops and in addition + disables autotuning. + """ + xla_gpu_all_reduce_combine_threshold_bytes: builtins.int + """Size threshold (in bytes) for the GPU collective combiners.""" + xla_gpu_all_gather_combine_threshold_bytes: builtins.int + xla_gpu_reduce_scatter_combine_threshold_bytes: builtins.int + xla_gpu_enable_all_gather_combine_by_dim: builtins.bool + """Combine all-gather/scatter-reduce ops with the same dimension or + irrespective of their dimension. + """ + xla_gpu_enable_reduce_scatter_combine_by_dim: builtins.bool + xla_gpu_enable_reassociation_for_converted_ar: builtins.bool + """Enable allreduce reassociation on allreduces that are converted to a wider + type. The resulting allreduce will be promoted to a wider-typed allreduce. + """ + xla_gpu_all_reduce_blueconnect_num_devices_per_host: builtins.int + """Number of devices per host for first stage of BlueConnect decomposition + pass. The pass will attempt to decompose all-reduces ops into a + ReduceScatter-AllReduce-AllGather sequence, with the initial ReduceScatter + being performed over all of the devices in the same host. Set to < 1 to + disable all-reduce decomposition. + """ + xla_gpu_enable_while_loop_reduce_scatter_code_motion: builtins.bool + """Enable hoisting of reduce-scatter out of while loops.""" + xla_gpu_collective_inflation_factor: builtins.int + """Inflate collective cost by running each collective multiple times.""" + xla_llvm_force_inline_before_split: builtins.bool + """Whether to force inline before llvm module split to get a more balanced + splits for parallel compilation. + """ + xla_gpu_enable_cudnn_frontend: builtins.bool + """Whether to use the cuDNN frontend API for convolutions when possible.""" + xla_gpu_enable_cudnn_fmha: builtins.bool + xla_gpu_fused_attention_use_cudnn_rng: builtins.bool + xla_gpu_enable_cudnn_layer_norm: builtins.bool + """Rewrite layer norm patterns into cuDNN library calls.""" + xla_dump_disable_metadata: builtins.bool + """Disable dumping metadata in HLO dumps.""" + xla_dump_hlo_pipeline_re: builtins.str + """If this flag is specified, will only dump HLO before and after passes in + the pass pipeline that matches this regular expression. Default empty value + enables dumping in all pipelines. + """ + xla_gpu_strict_conv_algorithm_picker: builtins.bool + """If true, abort immediately when conv algorithm picker fails, rather than + logging a warning and proceeding with fallback. + """ + xla_gpu_enable_custom_fusions: builtins.bool + """If true, XLA will try to pattern match subgraphs of HLO operations into + custom fusions registered in the current process (pre-compiled hand written + kernels, e.g. various GEMM fusions writtent in CUTLASS). + """ + xla_gpu_enable_custom_fusions_re: builtins.str + """A regular expression enabling only a subset of custom fusions. Enabled only + if `xla_gpu_enable_custom_fusion` set to true. + """ + xla_gpu_enable_dynamic_slice_fusion: builtins.bool + """Enables address computation fusion to optimize dynamic-slice and + dynamic-update-slice operations around library calls. + """ + xla_gpu_nccl_termination_timeout_seconds: builtins.int + """Timeout in seconds before terminating jobs that are stuck in a NCCL + Rendezvous. Negative value disables the timeout and will not terminate. + """ + xla_gpu_enable_shared_constants: builtins.bool + """Enables shared constants for XLA/GPU. This allows large constants to be + shared among multiple GPU executables. + """ + xla_gpu_enable_cublaslt: builtins.bool + """Whether to use cuBLASLt for GEMMs on GPUs.""" + xla_gpu_graph_min_graph_size: builtins.int + """This number determines how many moved instructions like fusion kernels are + required for a region to be captured as a function to be launched as a GPU + graph. + """ + xla_gpu_graph_enable_concurrent_region: builtins.bool + """Identify concurrent regions in GPU graphs and execute them concurrently.""" + xla_gpu_redzone_scratch_max_megabytes: builtins.int + """Size threshold (in megabytes) for the GPU redzone scratch allocator.""" + xla_gpu_redzone_padding_bytes: builtins.int + """Amount of padding the redzone allocator will put on one side of each buffer + it allocates. (So the buffer's total size will be increased by 2x this + value.) + + Higher values make it more likely that we'll catch an out-of-bounds read or + write. Smaller values consume less memory during autotuning. Note that a + fused cudnn conv has up to 6 total buffers (4 inputs, 1 output, and 1 + scratch), so this can be multiplied by quite a lot. + """ + xla_cpu_use_acl: builtins.bool + """Generate calls to Arm Compute Library in the CPU backend.""" + xla_cpu_strict_dot_conv_math: builtins.bool + """By default, XLA:CPU will run fp16 dot/conv as fp32, as this is generally + (much) faster on our hardware. Set this flag to disable this behavior. + """ + xla_gpu_use_runtime_fusion: builtins.bool + """An option to enable using cuDNN runtime compiled fusion kernels which is + available and recommended for Ampere+ GPUs. + """ + xla_dump_latency_hiding_schedule: builtins.bool + xla_cpu_enable_mlir_tiling_and_fusion: builtins.bool + """By default, MLIR lowering will use Linalg elementwise fusion. If this flag + is enabled, the pipeline will use tiling, fusion, peeling, vectorization + instead. + """ + xla_cpu_enable_custom_matmul_tiling: builtins.bool + """XLA:CPU-Next tiling parameters for matmul.""" + xla_cpu_matmul_tiling_m_dim: builtins.int + xla_cpu_matmul_tiling_n_dim: builtins.int + xla_cpu_matmul_tiling_k_dim: builtins.int + xla_cpu_enable_mlir_fusion_outlining: builtins.bool + xla_cpu_enable_experimental_deallocation: builtins.bool + """If set, use the experimental deallocation pass from mlir-hlo.""" + xla_gpu_enable_latency_hiding_scheduler: builtins.bool + xla_gpu_enable_highest_priority_async_stream: builtins.bool + xla_gpu_enable_analytical_latency_estimator: builtins.bool + xla_gpu_lhs_enable_gpu_async_tracker: builtins.bool + xla_gpu_pgle_profile_file_or_directory_path: builtins.str + xla_gpu_memory_limit_slop_factor: builtins.int + xla_gpu_enable_pipelined_collectives: builtins.bool + xla_gpu_enable_pipelined_all_reduce: builtins.bool + xla_gpu_enable_pipelined_all_gather: builtins.bool + xla_gpu_enable_pipelined_reduce_scatter: builtins.bool + xla_gpu_enable_pipelined_p2p: builtins.bool + xla_gpu_run_post_layout_collective_pipeliner: builtins.bool + xla_gpu_collective_permute_decomposer_threshold: builtins.int + """The minimum data size in bytes to trigger collective-permute-decomposer + transformation. + """ + xla_partitioning_algorithm: global___DebugOptions.PartitioningAlgorithm.ValueType + """The partitioning algorithm to be used in the PartitionAssignment pass.""" + xla_gpu_enable_triton_gemm: builtins.bool + xla_gpu_enable_cudnn_int8x32_convolution_reordering: builtins.bool + xla_gpu_triton_gemm_any: builtins.bool + """Creates triton fusion for all supported gemms. + To make sure only triton gemm is chosen by the autotuner run with + `xla_gpu_cublas_fallback` set to false. + """ + xla_gpu_exhaustive_tiling_search: builtins.bool + xla_gpu_enable_priority_fusion: builtins.bool + xla_gpu_dump_autotune_results_to: builtins.str + """File to write autotune results to. It will be a binary file unless the name + ends with .txt or .textproto. Warning: The results are written at every + compilation, possibly multiple times per process. This only works on CUDA. + """ + xla_gpu_load_autotune_results_from: builtins.str + """File to load autotune results from. It will be considered a binary file + unless the name ends with .txt or .textproto. At most one loading will + happen during the lifetime of one process, even if the first one is + unsuccessful or different file paths are passed here. This only works on + CUDA. + """ + xla_gpu_target_config_filename: builtins.str + """Description of the target platform in GpuTargetConfigProto format; if + provided, deviceless compilation is assumed, and the current device is + ignored. + """ + xla_gpu_auto_spmd_partitioning_memory_budget_gb: builtins.int + """Memory budget in GB per device for AutoSharding.""" + xla_gpu_auto_spmd_partitioning_memory_budget_ratio: builtins.float + """See the definition of the + xla_gpu_auto_spmd_partitioning_memory_budget_ratio flag for the meaning of + this field. + """ + xla_gpu_triton_gemm_disable_reduced_precision_reduction: builtins.bool + xla_gpu_triton_fusion_level: builtins.int + xla_gpu_dump_autotuned_gemm_fusions: builtins.bool + xla_gpu_override_gemm_autotuner: builtins.str + xla_gpu_copy_insertion_use_region_analysis: builtins.bool + xla_gpu_collect_cost_model_stats: builtins.bool + """If true, each fusion instruction will have a cost model runtime estimate in + backend config after compilation. + """ + xla_gpu_enable_split_k_autotuning: builtins.bool + xla_gpu_enable_reduction_epilogue_fusion: builtins.bool + """Whether reduction epilogue fusion is enabled in fusion passes.""" + xla_gpu_enable_nccl_clique_optimization: builtins.bool + """Allow early return when acquiring NCCL cliques.""" + xla_gpu_mock_custom_calls: builtins.bool + """Replace custom calls with noop operations.""" + xla_gpu_cublas_fallback: builtins.bool + """Allow Triton GEMM autotuning to fall back to cuBLAS when that is + faster. + """ + xla_gpu_enable_while_loop_double_buffering: builtins.bool + """Enable double buffering for loops.""" + xla_gpu_enable_while_loop_unrolling: global___DebugOptions.WhileLoopUnrolling.ValueType + """Determine the while loop unrolling scheme.""" + xla_gpu_ensure_minor_dot_contraction_dims: builtins.bool + """Change the layout of the second triton dot operand to be column major. + Only works for (bf16 x bf16) -> bf16. + """ + xla_gpu_filter_kernels_spilling_registers_on_autotuning: builtins.bool + """Filter out kernels that spill registers during autotuning.""" + xla_debug_buffer_assignment_show_max: builtins.int + """Maximum number of buffers to print when debugging buffer assignment.""" + xla_gpu_llvm_verification_level: builtins.int + xla_gpu_enable_cub_radix_sort: builtins.bool + """Enable radix sort using CUB.""" + xla_gpu_threshold_for_windowed_einsum_mib: builtins.int + """Threshold to enable windowed einsum (collective matmul) in MB.""" + xla_gpu_enable_triton_hopper: builtins.bool + """Enables currently disabled features within Triton for Hopper.""" + xla_gpu_enable_nccl_user_buffers: builtins.bool + """Enable NCCL user buffers.""" + xla_gpu_enable_nccl_comm_splitting: builtins.bool + """Enable NCCL communicator splitting.""" + xla_gpu_enable_nccl_per_stream_comms: builtins.bool + """Enable NCCL per stream communicators.""" + xla_gpu_enable_libnvptxcompiler: builtins.bool + """If enabled, uses the libnvptxcompiler library to compile PTX to cuBIN.""" + xla_gpu_enable_dot_strength_reduction: builtins.bool + xla_gpu_multi_streamed_windowed_einsum: builtins.bool + """Whether to use multiple compute streams to run windowed einsum.""" + xla_gpu_enable_bf16_6way_gemm: builtins.bool + """If enabled, uses bf16_6way gemm to compute F32 gemm.""" + xla_gpu_enable_bf16_3way_gemm: builtins.bool + """If enabled, uses bf16_3way gemm to compute F32 gemm.""" + xla_gpu_nccl_collective_max_nchannels: builtins.int + """Specify the maximum number of channels(SMs) NCCL + will use for collective operations. + """ + xla_gpu_nccl_p2p_max_nchannels: builtins.int + """Specify the maximum number of channels(SMs) NCCL + will use for p2p operations. + """ + xla_gpu_mlir_emitter_level: builtins.int + """Choose the level of mlir emitters that are enabled. + Current levels: + 0: Disabled. + 1: Loop emitter + 2: + Loop-like emitters + 3: + Transpose + 4: + Reduce + """ + xla_gpu_gemm_rewrite_size_threshold: builtins.int + """Threshold to rewrite matmul to cuBLAS or Triton (minimum combined number of + elements of both matrices in non-batch dimensions to be considered for a + rewrite). + """ + xla_gpu_require_complete_aot_autotune_results: builtins.bool + """If true, will require complete AOT autotuning results; in the case of + missing AOT result, the model will not be compiled or executed, a + `NotFound` error will be returned. + """ + xla_gpu_cudnn_gemm_fusion_level: builtins.int + """Let GEMM fusion autotuning probe cuDNN as a backend. + Current levels: + 0: Disabled. + 1: Fusions of GEMM, elementwise, transpose/reshape operations. + 2: + Broadcasts, slicing. + 3: + Nontrivial noncontracting dimension reshapes/transposes. + """ + xla_gpu_use_memcpy_local_p2p: builtins.bool + """This instructs the runtime whether to use + memcpy for p2p communication when source and + target are located within a node(nvlink). + """ + xla_gpu_autotune_max_solutions: builtins.int + """If non-zero, limits the number of solutions to be used by GEMM autotuner. + This might be useful if underlying math library returns too many GEMM + solutions. + """ + xla_dump_large_constants: builtins.bool + """If true, large constants will be printed out when dumping HLOs.""" + xla_gpu_verify_triton_fusion_numerics: builtins.bool + """If true, will verify that the numerical results of Triton fusions match + the results of regular emitters. + """ + xla_gpu_dump_autotune_logs_to: builtins.str + """File to write autotune logs to. It will stored in txt format.""" + xla_reduce_window_rewrite_base_length: builtins.int + """Base length to rewrite the reduce window to, no rewrite if set to 0.""" + xla_gpu_enable_host_memory_offloading: builtins.bool + """If true, will enable host memory offloading on a device.""" + xla_gpu_exclude_nondeterministic_ops: builtins.bool + """Excludes non-deterministic ops from compiled executables. + Unlike --xla_gpu_deterministic_ops does not disable autotuning - the + compilation itself can be non-deterministic. + At present, the HLO op SelectAndScatter does not have a + deterministic XLA:GPU implementation. + Compilation errors out if SelectAndScatter is encountered. + Scatter ops can non-deterministic by default; these get converted to + a deterministic implementation. + """ + xla_gpu_nccl_terminate_on_error: builtins.bool + """If true, Nccl errors will terminate the process.""" + xla_gpu_shard_autotuning: builtins.bool + xla_gpu_enable_approx_costly_collectives: builtins.bool + xla_gpu_kernel_cache_file: builtins.str + xla_gpu_unsafe_pipelined_loop_annotator: builtins.bool + """Recognises rotate-right patterns (slice, slice, concat) within a while + loop and labels the while loop as a pipelined while loop. This is an + unsafe flag. + """ + xla_gpu_per_fusion_autotune_cache_dir: builtins.str + xla_cmd_buffer_trace_cache_size: builtins.int + """The command buffer trace cache size, increasing the cache size may + sometimes reduces the chances of doing command buffer tracing for + updating command buffer instance. + """ + xla_gpu_temp_buffer_use_separate_color: builtins.bool + """Enable this flag will use a separate memory space color for + temp buffer, and then will use separate memory allocator to allocate it, + as there is no other memory allocation interference, + it will allocate temp buffer to some fix address on every iteration, + which is good for cuda-graph perf. + """ + xla_syntax_sugar_async_ops: builtins.bool + """This flag is used for controlling HLO dumping and NVTX marker. If turned + on, both HLO dumping and NVTX marker will use syntactic sugar wrappers + as op names, while the actual op names will be shown if turned off. + + Here is an example HLO excerpt with the flag off: + + async_computation { + param_0 = f32[1,4,8]{1,0,2} parameter(0) + ROOT all-to-all.3.1 = f32[1,4,8]{1,0,2} all-to-all(param_0), + replica_groups={{0,1,2,3,4,5,6,7}}, dimensions={2} + } + ... + + all-to-all-start = + ((f32[1,4,8]{1,0,2}), f32[1,4,8]{1,0,2}) async-start(bitcast.24.0), + calls=async_computation, backend_config={...} + all-to-all-done = f32[1,4,8]{1,0,2} async-done(all-to-all-start) + + and with the flag on: + + all-to-all-start = ((f32[1,4,8]{1,0,2}), f32[1,4,8]{1,0,2}) + all-to-all-start(bitcast.24.0), + replica_groups={{0,1,2,3,4,5,6,7}}, dimensions={2}, + backend_config={...} + all-to-all-done = f32[1,4,8]{1,0,2} all-to-all-done(all-to-all-start) + """ + xla_gpu_autotune_gemm_rtol: builtins.float + """Relative precision for comparing different GEMM solutions""" + xla_enable_command_buffers_during_profiling: builtins.bool + """Allow launching command buffers while profiling active. + When disabled, execute in op-by-op mode. + TODO(b/355487968): Remove this option when validation complete. + """ + xla_gpu_cudnn_gemm_max_plans: builtins.int + """Limit for the number of kernel configurations (plans) to use during + autotuning of cuDNN GEMM fusions. The more - the slower the autotuning + but potentially higher the performance. + """ + xla_gpu_enable_libnvjitlink: builtins.bool + """If enabled, uses the libnvjitlink library for PTX compilation and linking""" + xla_gpu_enable_triton_gemm_int4: builtins.bool + """If enabled, generates triton gemm kernels for int4 inputs.""" + xla_gpu_async_dot: builtins.bool + """If true, XLA will wrap `dot` operations into async computations in an + effort to parallelize matrix operations. + """ + xla_gpu_enable_pgle_accuracy_checker: builtins.bool + """Enables strict PGLE checking. If an FDO profile is specified and latency + hiding scheduler encounters missing instructions in the profile + compilation will halt. + """ + xla_gpu_executable_warn_stuck_timeout_seconds: builtins.int + """Timeouts for RendezvousSingle stuck warning and termination.""" + xla_gpu_executable_terminate_timeout_seconds: builtins.int + xla_experimental_ignore_channel_id: builtins.bool + """Whether to ignore channel ids(including verifier channel id checks) + for collectives in the given HLO. + """ + @property + def xla_disable_hlo_passes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """List of HLO passes to disable/enable. These names must exactly match the + pass names as specified by the HloPassInterface::name() method. + + At least one of xla_disable_hlo_passes and xla_enable_hlo_passes_only must + be empty. + """ + + @property + def xla_enable_hlo_passes_only(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + @property + def xla_gpu_ptx_file(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Paths to files with ptx code.""" + + @property + def xla_gpu_llvm_ir_file(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Paths to files with LLVM code.""" + + @property + def xla_gpu_disable_async_collectives( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___DebugOptions.CollectiveOpType.ValueType]: ... + @property + def xla_gpu_enable_command_buffer( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___DebugOptions.CommandBufferCmdType.ValueType]: + """Determine the types of commands that are recorded into command buffers.""" + + @property + def legacy_command_buffer_custom_call_targets( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Custom call targets with legacy registry API (non FFI API), + that support recording to command buffer custom command, + i.e., custom call target supports cuda-graph capturing for CUDA devices. + This flag is read if CUSTOM_CALL command type is recorded into + command buffer. + """ + + @property + def xla_backend_extra_options(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.str]: + """Next id: 331 + + Extra options to pass to the compilation backend (e.g. LLVM); specific + interpretation of these values is left to the backend. + """ + + def __init__( + self, + *, + xla_cpu_enable_concurrency_optimized_scheduler: builtins.bool | None = ..., + xla_cpu_enable_fast_math: builtins.bool | None = ..., + xla_cpu_enable_fast_min_max: builtins.bool | None = ..., + xla_cpu_fast_math_honor_division: builtins.bool | None = ..., + xla_cpu_fast_math_honor_functions: builtins.bool | None = ..., + xla_cpu_fast_math_honor_infs: builtins.bool | None = ..., + xla_cpu_fast_math_honor_nans: builtins.bool | None = ..., + xla_cpu_use_thunk_runtime: builtins.bool | None = ..., + xla_cpu_parallel_codegen_split_count: builtins.int | None = ..., + xla_cpu_prefer_vector_width: builtins.int | None = ..., + xla_gpu_experimental_autotune_cache_mode: global___DebugOptions.AutotuneCacheMode.ValueType | None = ..., + xla_gpu_experimental_disable_binary_libraries: builtins.bool | None = ..., + xla_gpu_experimental_enable_triton_softmax_priority_fusion: builtins.bool | None = ..., + xla_gpu_unsupported_enable_triton_gemm: builtins.bool | None = ..., + xla_hlo_graph_addresses: builtins.bool | None = ..., + xla_hlo_profile: builtins.bool | None = ..., + xla_disable_hlo_passes: collections.abc.Iterable[builtins.str] | None = ..., + xla_enable_hlo_passes_only: collections.abc.Iterable[builtins.str] | None = ..., + xla_disable_all_hlo_passes: builtins.bool | None = ..., + xla_backend_optimization_level: builtins.int | None = ..., + xla_embed_ir_in_executable: builtins.bool | None = ..., + xla_eliminate_hlo_implicit_broadcast: builtins.bool | None = ..., + xla_cpu_multi_thread_eigen: builtins.bool | None = ..., + xla_gpu_cuda_data_dir: builtins.str | None = ..., + xla_gpu_ftz: builtins.bool | None = ..., + xla_llvm_enable_alias_scope_metadata: builtins.bool | None = ..., + xla_llvm_enable_noalias_metadata: builtins.bool | None = ..., + xla_llvm_enable_invariant_load_metadata: builtins.bool | None = ..., + xla_llvm_disable_expensive_passes: builtins.bool | None = ..., + xla_test_all_output_layouts: builtins.bool | None = ..., + xla_test_all_input_layouts: builtins.bool | None = ..., + xla_hlo_graph_sharding_color: builtins.bool | None = ..., + xla_cpu_use_mkl_dnn: builtins.bool | None = ..., + xla_gpu_enable_fast_min_max: builtins.bool | None = ..., + xla_allow_excess_precision: builtins.bool | None = ..., + xla_gpu_crash_on_verification_failures: builtins.bool | None = ..., + xla_gpu_autotune_level: builtins.int | None = ..., + xla_force_host_platform_device_count: builtins.int | None = ..., + xla_gpu_disable_gpuasm_optimizations: builtins.bool | None = ..., + xla_gpu_shape_checks: global___DebugOptions.ShapeChecks.ValueType | None = ..., + xla_hlo_evaluator_use_fast_path: builtins.bool | None = ..., + xla_allow_scalar_index_dynamic_ops: builtins.bool | None = ..., + xla_step_marker_location: global___DebugOptions.StepMarkerLocation.ValueType | None = ..., + xla_dump_to: builtins.str | None = ..., + xla_dump_hlo_module_re: builtins.str | None = ..., + xla_dump_hlo_pass_re: builtins.str | None = ..., + xla_dump_hlo_as_text: builtins.bool | None = ..., + xla_dump_hlo_as_proto: builtins.bool | None = ..., + xla_dump_hlo_as_dot: builtins.bool | None = ..., + xla_dump_hlo_as_url: builtins.bool | None = ..., + xla_dump_hlo_as_html: builtins.bool | None = ..., + xla_dump_fusion_visualization: builtins.bool | None = ..., + xla_dump_hlo_snapshots: builtins.bool | None = ..., + xla_dump_include_timestamp: builtins.bool | None = ..., + xla_dump_max_hlo_modules: builtins.int | None = ..., + xla_dump_module_metadata: builtins.bool | None = ..., + xla_dump_compress_protos: builtins.bool | None = ..., + xla_dump_hlo_as_long_text: builtins.bool | None = ..., + xla_gpu_force_conv_nchw: builtins.bool | None = ..., + xla_gpu_force_conv_nhwc: builtins.bool | None = ..., + xla_gpu_ptx_file: collections.abc.Iterable[builtins.str] | None = ..., + xla_gpu_dump_llvmir: builtins.bool | None = ..., + xla_dump_enable_mlir_pretty_form: builtins.bool | None = ..., + xla_gpu_algorithm_denylist_path: builtins.str | None = ..., + xla_tpu_detect_nan: builtins.bool | None = ..., + xla_tpu_detect_inf: builtins.bool | None = ..., + xla_cpu_enable_xprof_traceme: builtins.bool | None = ..., + xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found: builtins.bool | None = ..., + xla_gpu_asm_extra_flags: builtins.str | None = ..., + xla_multiheap_size_constraint_per_heap: builtins.int | None = ..., + xla_detailed_logging: builtins.bool | None = ..., + xla_enable_dumping: builtins.bool | None = ..., + xla_gpu_force_compilation_parallelism: builtins.int | None = ..., + xla_gpu_enable_llvm_module_compilation_parallelism: builtins.bool | None = ..., + xla_gpu_deterministic_ops: builtins.bool | None = ..., + xla_gpu_llvm_ir_file: collections.abc.Iterable[builtins.str] | None = ..., + xla_gpu_disable_async_collectives: ( + collections.abc.Iterable[global___DebugOptions.CollectiveOpType.ValueType] | None + ) = ..., + xla_gpu_all_reduce_combine_threshold_bytes: builtins.int | None = ..., + xla_gpu_all_gather_combine_threshold_bytes: builtins.int | None = ..., + xla_gpu_reduce_scatter_combine_threshold_bytes: builtins.int | None = ..., + xla_gpu_enable_all_gather_combine_by_dim: builtins.bool | None = ..., + xla_gpu_enable_reduce_scatter_combine_by_dim: builtins.bool | None = ..., + xla_gpu_enable_reassociation_for_converted_ar: builtins.bool | None = ..., + xla_gpu_all_reduce_blueconnect_num_devices_per_host: builtins.int | None = ..., + xla_gpu_enable_while_loop_reduce_scatter_code_motion: builtins.bool | None = ..., + xla_gpu_collective_inflation_factor: builtins.int | None = ..., + xla_llvm_force_inline_before_split: builtins.bool | None = ..., + xla_gpu_enable_cudnn_frontend: builtins.bool | None = ..., + xla_gpu_enable_cudnn_fmha: builtins.bool | None = ..., + xla_gpu_fused_attention_use_cudnn_rng: builtins.bool | None = ..., + xla_gpu_enable_cudnn_layer_norm: builtins.bool | None = ..., + xla_dump_disable_metadata: builtins.bool | None = ..., + xla_dump_hlo_pipeline_re: builtins.str | None = ..., + xla_gpu_strict_conv_algorithm_picker: builtins.bool | None = ..., + xla_gpu_enable_custom_fusions: builtins.bool | None = ..., + xla_gpu_enable_custom_fusions_re: builtins.str | None = ..., + xla_gpu_enable_dynamic_slice_fusion: builtins.bool | None = ..., + xla_gpu_nccl_termination_timeout_seconds: builtins.int | None = ..., + xla_gpu_enable_shared_constants: builtins.bool | None = ..., + xla_gpu_enable_cublaslt: builtins.bool | None = ..., + xla_gpu_enable_command_buffer: ( + collections.abc.Iterable[global___DebugOptions.CommandBufferCmdType.ValueType] | None + ) = ..., + xla_gpu_graph_min_graph_size: builtins.int | None = ..., + xla_gpu_graph_enable_concurrent_region: builtins.bool | None = ..., + xla_gpu_redzone_scratch_max_megabytes: builtins.int | None = ..., + xla_gpu_redzone_padding_bytes: builtins.int | None = ..., + xla_cpu_use_acl: builtins.bool | None = ..., + xla_cpu_strict_dot_conv_math: builtins.bool | None = ..., + xla_gpu_use_runtime_fusion: builtins.bool | None = ..., + xla_dump_latency_hiding_schedule: builtins.bool | None = ..., + xla_cpu_enable_mlir_tiling_and_fusion: builtins.bool | None = ..., + xla_cpu_enable_custom_matmul_tiling: builtins.bool | None = ..., + xla_cpu_matmul_tiling_m_dim: builtins.int | None = ..., + xla_cpu_matmul_tiling_n_dim: builtins.int | None = ..., + xla_cpu_matmul_tiling_k_dim: builtins.int | None = ..., + xla_cpu_enable_mlir_fusion_outlining: builtins.bool | None = ..., + xla_cpu_enable_experimental_deallocation: builtins.bool | None = ..., + xla_gpu_enable_latency_hiding_scheduler: builtins.bool | None = ..., + xla_gpu_enable_highest_priority_async_stream: builtins.bool | None = ..., + xla_gpu_enable_analytical_latency_estimator: builtins.bool | None = ..., + xla_gpu_lhs_enable_gpu_async_tracker: builtins.bool | None = ..., + xla_gpu_pgle_profile_file_or_directory_path: builtins.str | None = ..., + xla_gpu_memory_limit_slop_factor: builtins.int | None = ..., + xla_gpu_enable_pipelined_collectives: builtins.bool | None = ..., + xla_gpu_enable_pipelined_all_reduce: builtins.bool | None = ..., + xla_gpu_enable_pipelined_all_gather: builtins.bool | None = ..., + xla_gpu_enable_pipelined_reduce_scatter: builtins.bool | None = ..., + xla_gpu_enable_pipelined_p2p: builtins.bool | None = ..., + xla_gpu_run_post_layout_collective_pipeliner: builtins.bool | None = ..., + xla_gpu_collective_permute_decomposer_threshold: builtins.int | None = ..., + xla_partitioning_algorithm: global___DebugOptions.PartitioningAlgorithm.ValueType | None = ..., + xla_gpu_enable_triton_gemm: builtins.bool | None = ..., + xla_gpu_enable_cudnn_int8x32_convolution_reordering: builtins.bool | None = ..., + xla_gpu_triton_gemm_any: builtins.bool | None = ..., + xla_gpu_exhaustive_tiling_search: builtins.bool | None = ..., + xla_gpu_enable_priority_fusion: builtins.bool | None = ..., + xla_gpu_dump_autotune_results_to: builtins.str | None = ..., + xla_gpu_load_autotune_results_from: builtins.str | None = ..., + xla_gpu_target_config_filename: builtins.str | None = ..., + xla_gpu_auto_spmd_partitioning_memory_budget_gb: builtins.int | None = ..., + xla_gpu_auto_spmd_partitioning_memory_budget_ratio: builtins.float | None = ..., + xla_gpu_triton_gemm_disable_reduced_precision_reduction: builtins.bool | None = ..., + xla_gpu_triton_fusion_level: builtins.int | None = ..., + xla_gpu_dump_autotuned_gemm_fusions: builtins.bool | None = ..., + xla_gpu_override_gemm_autotuner: builtins.str | None = ..., + xla_gpu_copy_insertion_use_region_analysis: builtins.bool | None = ..., + xla_gpu_collect_cost_model_stats: builtins.bool | None = ..., + xla_gpu_enable_split_k_autotuning: builtins.bool | None = ..., + xla_gpu_enable_reduction_epilogue_fusion: builtins.bool | None = ..., + xla_gpu_enable_nccl_clique_optimization: builtins.bool | None = ..., + xla_gpu_mock_custom_calls: builtins.bool | None = ..., + xla_gpu_cublas_fallback: builtins.bool | None = ..., + xla_gpu_enable_while_loop_double_buffering: builtins.bool | None = ..., + xla_gpu_enable_while_loop_unrolling: global___DebugOptions.WhileLoopUnrolling.ValueType | None = ..., + xla_gpu_ensure_minor_dot_contraction_dims: builtins.bool | None = ..., + xla_gpu_filter_kernels_spilling_registers_on_autotuning: builtins.bool | None = ..., + xla_debug_buffer_assignment_show_max: builtins.int | None = ..., + xla_gpu_llvm_verification_level: builtins.int | None = ..., + xla_gpu_enable_cub_radix_sort: builtins.bool | None = ..., + xla_gpu_threshold_for_windowed_einsum_mib: builtins.int | None = ..., + xla_gpu_enable_triton_hopper: builtins.bool | None = ..., + xla_gpu_enable_nccl_user_buffers: builtins.bool | None = ..., + xla_gpu_enable_nccl_comm_splitting: builtins.bool | None = ..., + xla_gpu_enable_nccl_per_stream_comms: builtins.bool | None = ..., + xla_gpu_enable_libnvptxcompiler: builtins.bool | None = ..., + xla_gpu_enable_dot_strength_reduction: builtins.bool | None = ..., + xla_gpu_multi_streamed_windowed_einsum: builtins.bool | None = ..., + xla_gpu_enable_bf16_6way_gemm: builtins.bool | None = ..., + xla_gpu_enable_bf16_3way_gemm: builtins.bool | None = ..., + xla_gpu_nccl_collective_max_nchannels: builtins.int | None = ..., + xla_gpu_nccl_p2p_max_nchannels: builtins.int | None = ..., + xla_gpu_mlir_emitter_level: builtins.int | None = ..., + xla_gpu_gemm_rewrite_size_threshold: builtins.int | None = ..., + xla_gpu_require_complete_aot_autotune_results: builtins.bool | None = ..., + xla_gpu_cudnn_gemm_fusion_level: builtins.int | None = ..., + xla_gpu_use_memcpy_local_p2p: builtins.bool | None = ..., + xla_gpu_autotune_max_solutions: builtins.int | None = ..., + xla_dump_large_constants: builtins.bool | None = ..., + xla_gpu_verify_triton_fusion_numerics: builtins.bool | None = ..., + xla_gpu_dump_autotune_logs_to: builtins.str | None = ..., + xla_reduce_window_rewrite_base_length: builtins.int | None = ..., + xla_gpu_enable_host_memory_offloading: builtins.bool | None = ..., + xla_gpu_exclude_nondeterministic_ops: builtins.bool | None = ..., + xla_gpu_nccl_terminate_on_error: builtins.bool | None = ..., + xla_gpu_shard_autotuning: builtins.bool | None = ..., + xla_gpu_enable_approx_costly_collectives: builtins.bool | None = ..., + xla_gpu_kernel_cache_file: builtins.str | None = ..., + xla_gpu_unsafe_pipelined_loop_annotator: builtins.bool | None = ..., + xla_gpu_per_fusion_autotune_cache_dir: builtins.str | None = ..., + xla_cmd_buffer_trace_cache_size: builtins.int | None = ..., + xla_gpu_temp_buffer_use_separate_color: builtins.bool | None = ..., + legacy_command_buffer_custom_call_targets: collections.abc.Iterable[builtins.str] | None = ..., + xla_syntax_sugar_async_ops: builtins.bool | None = ..., + xla_gpu_autotune_gemm_rtol: builtins.float | None = ..., + xla_enable_command_buffers_during_profiling: builtins.bool | None = ..., + xla_gpu_cudnn_gemm_max_plans: builtins.int | None = ..., + xla_gpu_enable_libnvjitlink: builtins.bool | None = ..., + xla_gpu_enable_triton_gemm_int4: builtins.bool | None = ..., + xla_gpu_async_dot: builtins.bool | None = ..., + xla_gpu_enable_pgle_accuracy_checker: builtins.bool | None = ..., + xla_gpu_executable_warn_stuck_timeout_seconds: builtins.int | None = ..., + xla_gpu_executable_terminate_timeout_seconds: builtins.int | None = ..., + xla_experimental_ignore_channel_id: builtins.bool | None = ..., + xla_backend_extra_options: collections.abc.Mapping[builtins.str, builtins.str] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "legacy_command_buffer_custom_call_targets", + b"legacy_command_buffer_custom_call_targets", + "xla_allow_excess_precision", + b"xla_allow_excess_precision", + "xla_allow_scalar_index_dynamic_ops", + b"xla_allow_scalar_index_dynamic_ops", + "xla_backend_extra_options", + b"xla_backend_extra_options", + "xla_backend_optimization_level", + b"xla_backend_optimization_level", + "xla_cmd_buffer_trace_cache_size", + b"xla_cmd_buffer_trace_cache_size", + "xla_cpu_enable_concurrency_optimized_scheduler", + b"xla_cpu_enable_concurrency_optimized_scheduler", + "xla_cpu_enable_custom_matmul_tiling", + b"xla_cpu_enable_custom_matmul_tiling", + "xla_cpu_enable_experimental_deallocation", + b"xla_cpu_enable_experimental_deallocation", + "xla_cpu_enable_fast_math", + b"xla_cpu_enable_fast_math", + "xla_cpu_enable_fast_min_max", + b"xla_cpu_enable_fast_min_max", + "xla_cpu_enable_mlir_fusion_outlining", + b"xla_cpu_enable_mlir_fusion_outlining", + "xla_cpu_enable_mlir_tiling_and_fusion", + b"xla_cpu_enable_mlir_tiling_and_fusion", + "xla_cpu_enable_xprof_traceme", + b"xla_cpu_enable_xprof_traceme", + "xla_cpu_fast_math_honor_division", + b"xla_cpu_fast_math_honor_division", + "xla_cpu_fast_math_honor_functions", + b"xla_cpu_fast_math_honor_functions", + "xla_cpu_fast_math_honor_infs", + b"xla_cpu_fast_math_honor_infs", + "xla_cpu_fast_math_honor_nans", + b"xla_cpu_fast_math_honor_nans", + "xla_cpu_matmul_tiling_k_dim", + b"xla_cpu_matmul_tiling_k_dim", + "xla_cpu_matmul_tiling_m_dim", + b"xla_cpu_matmul_tiling_m_dim", + "xla_cpu_matmul_tiling_n_dim", + b"xla_cpu_matmul_tiling_n_dim", + "xla_cpu_multi_thread_eigen", + b"xla_cpu_multi_thread_eigen", + "xla_cpu_parallel_codegen_split_count", + b"xla_cpu_parallel_codegen_split_count", + "xla_cpu_prefer_vector_width", + b"xla_cpu_prefer_vector_width", + "xla_cpu_strict_dot_conv_math", + b"xla_cpu_strict_dot_conv_math", + "xla_cpu_use_acl", + b"xla_cpu_use_acl", + "xla_cpu_use_mkl_dnn", + b"xla_cpu_use_mkl_dnn", + "xla_cpu_use_thunk_runtime", + b"xla_cpu_use_thunk_runtime", + "xla_debug_buffer_assignment_show_max", + b"xla_debug_buffer_assignment_show_max", + "xla_detailed_logging", + b"xla_detailed_logging", + "xla_disable_all_hlo_passes", + b"xla_disable_all_hlo_passes", + "xla_disable_hlo_passes", + b"xla_disable_hlo_passes", + "xla_dump_compress_protos", + b"xla_dump_compress_protos", + "xla_dump_disable_metadata", + b"xla_dump_disable_metadata", + "xla_dump_enable_mlir_pretty_form", + b"xla_dump_enable_mlir_pretty_form", + "xla_dump_fusion_visualization", + b"xla_dump_fusion_visualization", + "xla_dump_hlo_as_dot", + b"xla_dump_hlo_as_dot", + "xla_dump_hlo_as_html", + b"xla_dump_hlo_as_html", + "xla_dump_hlo_as_long_text", + b"xla_dump_hlo_as_long_text", + "xla_dump_hlo_as_proto", + b"xla_dump_hlo_as_proto", + "xla_dump_hlo_as_text", + b"xla_dump_hlo_as_text", + "xla_dump_hlo_as_url", + b"xla_dump_hlo_as_url", + "xla_dump_hlo_module_re", + b"xla_dump_hlo_module_re", + "xla_dump_hlo_pass_re", + b"xla_dump_hlo_pass_re", + "xla_dump_hlo_pipeline_re", + b"xla_dump_hlo_pipeline_re", + "xla_dump_hlo_snapshots", + b"xla_dump_hlo_snapshots", + "xla_dump_include_timestamp", + b"xla_dump_include_timestamp", + "xla_dump_large_constants", + b"xla_dump_large_constants", + "xla_dump_latency_hiding_schedule", + b"xla_dump_latency_hiding_schedule", + "xla_dump_max_hlo_modules", + b"xla_dump_max_hlo_modules", + "xla_dump_module_metadata", + b"xla_dump_module_metadata", + "xla_dump_to", + b"xla_dump_to", + "xla_eliminate_hlo_implicit_broadcast", + b"xla_eliminate_hlo_implicit_broadcast", + "xla_embed_ir_in_executable", + b"xla_embed_ir_in_executable", + "xla_enable_command_buffers_during_profiling", + b"xla_enable_command_buffers_during_profiling", + "xla_enable_dumping", + b"xla_enable_dumping", + "xla_enable_hlo_passes_only", + b"xla_enable_hlo_passes_only", + "xla_experimental_ignore_channel_id", + b"xla_experimental_ignore_channel_id", + "xla_force_host_platform_device_count", + b"xla_force_host_platform_device_count", + "xla_gpu_algorithm_denylist_path", + b"xla_gpu_algorithm_denylist_path", + "xla_gpu_all_gather_combine_threshold_bytes", + b"xla_gpu_all_gather_combine_threshold_bytes", + "xla_gpu_all_reduce_blueconnect_num_devices_per_host", + b"xla_gpu_all_reduce_blueconnect_num_devices_per_host", + "xla_gpu_all_reduce_combine_threshold_bytes", + b"xla_gpu_all_reduce_combine_threshold_bytes", + "xla_gpu_asm_extra_flags", + b"xla_gpu_asm_extra_flags", + "xla_gpu_async_dot", + b"xla_gpu_async_dot", + "xla_gpu_auto_spmd_partitioning_memory_budget_gb", + b"xla_gpu_auto_spmd_partitioning_memory_budget_gb", + "xla_gpu_auto_spmd_partitioning_memory_budget_ratio", + b"xla_gpu_auto_spmd_partitioning_memory_budget_ratio", + "xla_gpu_autotune_gemm_rtol", + b"xla_gpu_autotune_gemm_rtol", + "xla_gpu_autotune_level", + b"xla_gpu_autotune_level", + "xla_gpu_autotune_max_solutions", + b"xla_gpu_autotune_max_solutions", + "xla_gpu_collect_cost_model_stats", + b"xla_gpu_collect_cost_model_stats", + "xla_gpu_collective_inflation_factor", + b"xla_gpu_collective_inflation_factor", + "xla_gpu_collective_permute_decomposer_threshold", + b"xla_gpu_collective_permute_decomposer_threshold", + "xla_gpu_copy_insertion_use_region_analysis", + b"xla_gpu_copy_insertion_use_region_analysis", + "xla_gpu_crash_on_verification_failures", + b"xla_gpu_crash_on_verification_failures", + "xla_gpu_cublas_fallback", + b"xla_gpu_cublas_fallback", + "xla_gpu_cuda_data_dir", + b"xla_gpu_cuda_data_dir", + "xla_gpu_cudnn_gemm_fusion_level", + b"xla_gpu_cudnn_gemm_fusion_level", + "xla_gpu_cudnn_gemm_max_plans", + b"xla_gpu_cudnn_gemm_max_plans", + "xla_gpu_deterministic_ops", + b"xla_gpu_deterministic_ops", + "xla_gpu_disable_async_collectives", + b"xla_gpu_disable_async_collectives", + "xla_gpu_disable_gpuasm_optimizations", + b"xla_gpu_disable_gpuasm_optimizations", + "xla_gpu_dump_autotune_logs_to", + b"xla_gpu_dump_autotune_logs_to", + "xla_gpu_dump_autotune_results_to", + b"xla_gpu_dump_autotune_results_to", + "xla_gpu_dump_autotuned_gemm_fusions", + b"xla_gpu_dump_autotuned_gemm_fusions", + "xla_gpu_dump_llvmir", + b"xla_gpu_dump_llvmir", + "xla_gpu_enable_all_gather_combine_by_dim", + b"xla_gpu_enable_all_gather_combine_by_dim", + "xla_gpu_enable_analytical_latency_estimator", + b"xla_gpu_enable_analytical_latency_estimator", + "xla_gpu_enable_approx_costly_collectives", + b"xla_gpu_enable_approx_costly_collectives", + "xla_gpu_enable_bf16_3way_gemm", + b"xla_gpu_enable_bf16_3way_gemm", + "xla_gpu_enable_bf16_6way_gemm", + b"xla_gpu_enable_bf16_6way_gemm", + "xla_gpu_enable_command_buffer", + b"xla_gpu_enable_command_buffer", + "xla_gpu_enable_cub_radix_sort", + b"xla_gpu_enable_cub_radix_sort", + "xla_gpu_enable_cublaslt", + b"xla_gpu_enable_cublaslt", + "xla_gpu_enable_cudnn_fmha", + b"xla_gpu_enable_cudnn_fmha", + "xla_gpu_enable_cudnn_frontend", + b"xla_gpu_enable_cudnn_frontend", + "xla_gpu_enable_cudnn_int8x32_convolution_reordering", + b"xla_gpu_enable_cudnn_int8x32_convolution_reordering", + "xla_gpu_enable_cudnn_layer_norm", + b"xla_gpu_enable_cudnn_layer_norm", + "xla_gpu_enable_custom_fusions", + b"xla_gpu_enable_custom_fusions", + "xla_gpu_enable_custom_fusions_re", + b"xla_gpu_enable_custom_fusions_re", + "xla_gpu_enable_dot_strength_reduction", + b"xla_gpu_enable_dot_strength_reduction", + "xla_gpu_enable_dynamic_slice_fusion", + b"xla_gpu_enable_dynamic_slice_fusion", + "xla_gpu_enable_fast_min_max", + b"xla_gpu_enable_fast_min_max", + "xla_gpu_enable_highest_priority_async_stream", + b"xla_gpu_enable_highest_priority_async_stream", + "xla_gpu_enable_host_memory_offloading", + b"xla_gpu_enable_host_memory_offloading", + "xla_gpu_enable_latency_hiding_scheduler", + b"xla_gpu_enable_latency_hiding_scheduler", + "xla_gpu_enable_libnvjitlink", + b"xla_gpu_enable_libnvjitlink", + "xla_gpu_enable_libnvptxcompiler", + b"xla_gpu_enable_libnvptxcompiler", + "xla_gpu_enable_llvm_module_compilation_parallelism", + b"xla_gpu_enable_llvm_module_compilation_parallelism", + "xla_gpu_enable_nccl_clique_optimization", + b"xla_gpu_enable_nccl_clique_optimization", + "xla_gpu_enable_nccl_comm_splitting", + b"xla_gpu_enable_nccl_comm_splitting", + "xla_gpu_enable_nccl_per_stream_comms", + b"xla_gpu_enable_nccl_per_stream_comms", + "xla_gpu_enable_nccl_user_buffers", + b"xla_gpu_enable_nccl_user_buffers", + "xla_gpu_enable_pgle_accuracy_checker", + b"xla_gpu_enable_pgle_accuracy_checker", + "xla_gpu_enable_pipelined_all_gather", + b"xla_gpu_enable_pipelined_all_gather", + "xla_gpu_enable_pipelined_all_reduce", + b"xla_gpu_enable_pipelined_all_reduce", + "xla_gpu_enable_pipelined_collectives", + b"xla_gpu_enable_pipelined_collectives", + "xla_gpu_enable_pipelined_p2p", + b"xla_gpu_enable_pipelined_p2p", + "xla_gpu_enable_pipelined_reduce_scatter", + b"xla_gpu_enable_pipelined_reduce_scatter", + "xla_gpu_enable_priority_fusion", + b"xla_gpu_enable_priority_fusion", + "xla_gpu_enable_reassociation_for_converted_ar", + b"xla_gpu_enable_reassociation_for_converted_ar", + "xla_gpu_enable_reduce_scatter_combine_by_dim", + b"xla_gpu_enable_reduce_scatter_combine_by_dim", + "xla_gpu_enable_reduction_epilogue_fusion", + b"xla_gpu_enable_reduction_epilogue_fusion", + "xla_gpu_enable_shared_constants", + b"xla_gpu_enable_shared_constants", + "xla_gpu_enable_split_k_autotuning", + b"xla_gpu_enable_split_k_autotuning", + "xla_gpu_enable_triton_gemm", + b"xla_gpu_enable_triton_gemm", + "xla_gpu_enable_triton_gemm_int4", + b"xla_gpu_enable_triton_gemm_int4", + "xla_gpu_enable_triton_hopper", + b"xla_gpu_enable_triton_hopper", + "xla_gpu_enable_while_loop_double_buffering", + b"xla_gpu_enable_while_loop_double_buffering", + "xla_gpu_enable_while_loop_reduce_scatter_code_motion", + b"xla_gpu_enable_while_loop_reduce_scatter_code_motion", + "xla_gpu_enable_while_loop_unrolling", + b"xla_gpu_enable_while_loop_unrolling", + "xla_gpu_ensure_minor_dot_contraction_dims", + b"xla_gpu_ensure_minor_dot_contraction_dims", + "xla_gpu_exclude_nondeterministic_ops", + b"xla_gpu_exclude_nondeterministic_ops", + "xla_gpu_executable_terminate_timeout_seconds", + b"xla_gpu_executable_terminate_timeout_seconds", + "xla_gpu_executable_warn_stuck_timeout_seconds", + b"xla_gpu_executable_warn_stuck_timeout_seconds", + "xla_gpu_exhaustive_tiling_search", + b"xla_gpu_exhaustive_tiling_search", + "xla_gpu_experimental_autotune_cache_mode", + b"xla_gpu_experimental_autotune_cache_mode", + "xla_gpu_experimental_disable_binary_libraries", + b"xla_gpu_experimental_disable_binary_libraries", + "xla_gpu_experimental_enable_triton_softmax_priority_fusion", + b"xla_gpu_experimental_enable_triton_softmax_priority_fusion", + "xla_gpu_filter_kernels_spilling_registers_on_autotuning", + b"xla_gpu_filter_kernels_spilling_registers_on_autotuning", + "xla_gpu_force_compilation_parallelism", + b"xla_gpu_force_compilation_parallelism", + "xla_gpu_force_conv_nchw", + b"xla_gpu_force_conv_nchw", + "xla_gpu_force_conv_nhwc", + b"xla_gpu_force_conv_nhwc", + "xla_gpu_ftz", + b"xla_gpu_ftz", + "xla_gpu_fused_attention_use_cudnn_rng", + b"xla_gpu_fused_attention_use_cudnn_rng", + "xla_gpu_gemm_rewrite_size_threshold", + b"xla_gpu_gemm_rewrite_size_threshold", + "xla_gpu_graph_enable_concurrent_region", + b"xla_gpu_graph_enable_concurrent_region", + "xla_gpu_graph_min_graph_size", + b"xla_gpu_graph_min_graph_size", + "xla_gpu_kernel_cache_file", + b"xla_gpu_kernel_cache_file", + "xla_gpu_lhs_enable_gpu_async_tracker", + b"xla_gpu_lhs_enable_gpu_async_tracker", + "xla_gpu_llvm_ir_file", + b"xla_gpu_llvm_ir_file", + "xla_gpu_llvm_verification_level", + b"xla_gpu_llvm_verification_level", + "xla_gpu_load_autotune_results_from", + b"xla_gpu_load_autotune_results_from", + "xla_gpu_memory_limit_slop_factor", + b"xla_gpu_memory_limit_slop_factor", + "xla_gpu_mlir_emitter_level", + b"xla_gpu_mlir_emitter_level", + "xla_gpu_mock_custom_calls", + b"xla_gpu_mock_custom_calls", + "xla_gpu_multi_streamed_windowed_einsum", + b"xla_gpu_multi_streamed_windowed_einsum", + "xla_gpu_nccl_collective_max_nchannels", + b"xla_gpu_nccl_collective_max_nchannels", + "xla_gpu_nccl_p2p_max_nchannels", + b"xla_gpu_nccl_p2p_max_nchannels", + "xla_gpu_nccl_terminate_on_error", + b"xla_gpu_nccl_terminate_on_error", + "xla_gpu_nccl_termination_timeout_seconds", + b"xla_gpu_nccl_termination_timeout_seconds", + "xla_gpu_override_gemm_autotuner", + b"xla_gpu_override_gemm_autotuner", + "xla_gpu_per_fusion_autotune_cache_dir", + b"xla_gpu_per_fusion_autotune_cache_dir", + "xla_gpu_pgle_profile_file_or_directory_path", + b"xla_gpu_pgle_profile_file_or_directory_path", + "xla_gpu_ptx_file", + b"xla_gpu_ptx_file", + "xla_gpu_reduce_scatter_combine_threshold_bytes", + b"xla_gpu_reduce_scatter_combine_threshold_bytes", + "xla_gpu_redzone_padding_bytes", + b"xla_gpu_redzone_padding_bytes", + "xla_gpu_redzone_scratch_max_megabytes", + b"xla_gpu_redzone_scratch_max_megabytes", + "xla_gpu_require_complete_aot_autotune_results", + b"xla_gpu_require_complete_aot_autotune_results", + "xla_gpu_run_post_layout_collective_pipeliner", + b"xla_gpu_run_post_layout_collective_pipeliner", + "xla_gpu_shape_checks", + b"xla_gpu_shape_checks", + "xla_gpu_shard_autotuning", + b"xla_gpu_shard_autotuning", + "xla_gpu_strict_conv_algorithm_picker", + b"xla_gpu_strict_conv_algorithm_picker", + "xla_gpu_target_config_filename", + b"xla_gpu_target_config_filename", + "xla_gpu_temp_buffer_use_separate_color", + b"xla_gpu_temp_buffer_use_separate_color", + "xla_gpu_threshold_for_windowed_einsum_mib", + b"xla_gpu_threshold_for_windowed_einsum_mib", + "xla_gpu_triton_fusion_level", + b"xla_gpu_triton_fusion_level", + "xla_gpu_triton_gemm_any", + b"xla_gpu_triton_gemm_any", + "xla_gpu_triton_gemm_disable_reduced_precision_reduction", + b"xla_gpu_triton_gemm_disable_reduced_precision_reduction", + "xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found", + b"xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found", + "xla_gpu_unsafe_pipelined_loop_annotator", + b"xla_gpu_unsafe_pipelined_loop_annotator", + "xla_gpu_unsupported_enable_triton_gemm", + b"xla_gpu_unsupported_enable_triton_gemm", + "xla_gpu_use_memcpy_local_p2p", + b"xla_gpu_use_memcpy_local_p2p", + "xla_gpu_use_runtime_fusion", + b"xla_gpu_use_runtime_fusion", + "xla_gpu_verify_triton_fusion_numerics", + b"xla_gpu_verify_triton_fusion_numerics", + "xla_hlo_evaluator_use_fast_path", + b"xla_hlo_evaluator_use_fast_path", + "xla_hlo_graph_addresses", + b"xla_hlo_graph_addresses", + "xla_hlo_graph_sharding_color", + b"xla_hlo_graph_sharding_color", + "xla_hlo_profile", + b"xla_hlo_profile", + "xla_llvm_disable_expensive_passes", + b"xla_llvm_disable_expensive_passes", + "xla_llvm_enable_alias_scope_metadata", + b"xla_llvm_enable_alias_scope_metadata", + "xla_llvm_enable_invariant_load_metadata", + b"xla_llvm_enable_invariant_load_metadata", + "xla_llvm_enable_noalias_metadata", + b"xla_llvm_enable_noalias_metadata", + "xla_llvm_force_inline_before_split", + b"xla_llvm_force_inline_before_split", + "xla_multiheap_size_constraint_per_heap", + b"xla_multiheap_size_constraint_per_heap", + "xla_partitioning_algorithm", + b"xla_partitioning_algorithm", + "xla_reduce_window_rewrite_base_length", + b"xla_reduce_window_rewrite_base_length", + "xla_step_marker_location", + b"xla_step_marker_location", + "xla_syntax_sugar_async_ops", + b"xla_syntax_sugar_async_ops", + "xla_test_all_input_layouts", + b"xla_test_all_input_layouts", + "xla_test_all_output_layouts", + b"xla_test_all_output_layouts", + "xla_tpu_detect_inf", + b"xla_tpu_detect_inf", + "xla_tpu_detect_nan", + b"xla_tpu_detect_nan", + ], + ) -> None: ... + +global___DebugOptions = DebugOptions + +@typing.final +class GpuCompilationEnvironment(google.protobuf.message.Message): + """Contains flags which affects the GPU compilation result. + These flags are part of Debug Options as of now, and will be migrated to + this proto. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DUMMY_FLAG_FIELD_NUMBER: builtins.int + dummy_flag: builtins.int + """Temporary dummy flag is added to test the flow. + To be removed when we add flags here. + """ + def __init__(self, *, dummy_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dummy_flag", b"dummy_flag"]) -> None: ... + +global___GpuCompilationEnvironment = GpuCompilationEnvironment + +@typing.final +class ShardableValueUpdatePairProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INPUT_PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + OUTPUT_SHAPE_INDEX_FIELD_NUMBER: builtins.int + input_parameter_number: builtins.int + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def output_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + input_parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + output_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "input_parameter_number", + b"input_parameter_number", + "output_shape_index", + b"output_shape_index", + "parameter_shape_index", + b"parameter_shape_index", + ], + ) -> None: ... + +global___ShardableValueUpdatePairProto = ShardableValueUpdatePairProto + +@typing.final +class ExecutionOptions(google.protobuf.message.Message): + """These settings control how XLA compiles and/or runs code. Not all settings + will have an effect on every platform. + + When adding new fields, keep in mind that boolean fields default to false. + Next id: 25. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SHAPE_WITH_OUTPUT_LAYOUT_FIELD_NUMBER: builtins.int + SEED_FIELD_NUMBER: builtins.int + DEBUG_OPTIONS_FIELD_NUMBER: builtins.int + DEVICE_HANDLES_FIELD_NUMBER: builtins.int + NUM_REPLICAS_FIELD_NUMBER: builtins.int + DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + ALIAS_PASSTHROUGH_PARAMS_FIELD_NUMBER: builtins.int + NUM_PARTITIONS_FIELD_NUMBER: builtins.int + LAUNCH_ID_FIELD_NUMBER: builtins.int + USE_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + USE_AUTO_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_SHAPE_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_IDS_FIELD_NUMBER: builtins.int + DEDUPLICATE_HLO_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_PARAMETERS_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_OUTPUT_FIELD_NUMBER: builtins.int + PARAM_REQUIRES_BROADCAST_VIA_COLLECTIVES_FIELD_NUMBER: builtins.int + ALLOW_SEPARATE_SHARDING_PROGRAMS_FIELD_NUMBER: builtins.int + SHARDABLE_VALUE_UPDATE_PAIRS_FIELD_NUMBER: builtins.int + FDO_PROFILE_FIELD_NUMBER: builtins.int + DEVICE_MEMORY_SIZE_FIELD_NUMBER: builtins.int + USE_SHARDY_PARTITIONER_FIELD_NUMBER: builtins.int + seed: builtins.int + """Used to seed random-number generators used in this computation. If this is + 0, we generate a seed ourselves. + + TODO(b/32083678): Changing the seed unnecessarily forces a recompilation. + """ + num_replicas: builtins.int + """Number of replicas of the computation to run. If zero, uses the default + number of replicas for the XLA service. + """ + alias_passthrough_params: builtins.bool + """Alias input and output buffers for parameters that are passed-through XLA + modules without being changed. + """ + num_partitions: builtins.int + """Number of partitions of the computation to run (model parallelism). + If zero, uses the default number of partitions for the XLA service. + """ + launch_id: builtins.int + """Used to identify a set of programs that should be launch together.""" + use_spmd_partitioning: builtins.bool + """Indicates whether to use SPMD (true) or MPMD (false) partitioning when + num_partitions > 1 and XLA is requested to partition the input program. + """ + use_auto_spmd_partitioning: builtins.bool + """Whether to automatically generate XLA shardings for SPMD partitioner.""" + deduplicate_hlo: builtins.bool + """If set, deduplicate hlo into function calls to reduce binary size. Only + works on TPU. + """ + allow_separate_sharding_programs: builtins.bool + """If enabled, the compiler may generate sharding and unsharding programs as + separate HLO modules, and modify the main program's input and output to + be sharded. + """ + fdo_profile: builtins.bytes + """Profiling data for feedback directed optimizations. Note that this is not + the only way to feed FDO data into the compiler and individual backends + may choose to get FDO data by other means. + """ + device_memory_size: builtins.int + """Amount of device memory available for the executable to use.""" + use_shardy_partitioner: builtins.bool + """Use Shardy, a new partitioner, to replace the existing + ShardingPropagation and SpmdPartitioner. See go/xla-sdy-pipeline for + details. + """ + @property + def shape_with_output_layout(self) -> tensorflow.compiler.xla.xla_data_pb2.ShapeProto: + """This optional field's layout is used as a hint when storing the output of + this computation. Subsequent transfers of this output array to the client + may be faster when using this layout. + + We use a Shape here to accommodate computations that return a tuple. + """ + + @property + def debug_options(self) -> global___DebugOptions: ... + @property + def device_handles( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.DeviceHandle]: + """This optional field specifies a particular set of devices to run the + computation on. The computation will be partitioned across these devices. + If not provided, the default device will be chosen. + """ + + @property + def device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: + """This optional field specifies the device assignment if known at compile + time. + """ + + @property + def auto_spmd_partitioning_mesh_shape(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Device mesh shape used to create the sharding search space when + use_auto_spmd_partitioning=true. + """ + + @property + def auto_spmd_partitioning_mesh_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Device mesh ids compatible with the above mesh_shape used when + use_auto_spmd_partitioning=true. + """ + + @property + def allow_spmd_sharding_propagation_to_parameters( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Allows sharding propagation to propagate to the parameters. This changes + the input shape of the computation (which is undesirable), but it can be + used to allow to run partial compilation to determine what would be the + input sharding of a computation if XLA would be allowed to propagate the + sharding which can be used by higher level framework as a way to query + intermediate sharding of operations when multiple computation would be + chained and merged together. + This is a vector of bool, because the user can control which parameters can + have the sharding substituted. If only one boolean value is passed in the + vector that is interpreted as the value to be applied for every parameter. + """ + + @property + def allow_spmd_sharding_propagation_to_output( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Allows sharding propagation to propagate to the outputs. This changes the + output shape of the computation (which is undesirable), but it can be used + to allow to run partial compilation to determine what would be the output + sharding of a computation if XLA would be allowed to propagate the sharding + which can be used by higher level framework as a way to query intermediate + sharding of operations when multiple computation would be chained and + merged together. + This is a vector of bool, because the user can control (if the output of + the computation is a tuple) which elements of the tuple can have the + sharding substituted and which don't. If only one boolean value is passed + in the vector that's interpreted as the value to be applied for every + single element of the output tuple. One value per element of the tuple + means that each value is attached to one of the output elements. + """ + + @property + def param_requires_broadcast_via_collectives( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Whether to broadcast args across all replicas. One entry per arg.""" + + @property + def shardable_value_update_pairs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShardableValueUpdatePairProto]: + """The list of input/output pairs in the main program that could be sharded.""" + + def __init__( + self, + *, + shape_with_output_layout: tensorflow.compiler.xla.xla_data_pb2.ShapeProto | None = ..., + seed: builtins.int | None = ..., + debug_options: global___DebugOptions | None = ..., + device_handles: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.DeviceHandle] | None = ..., + num_replicas: builtins.int | None = ..., + device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + alias_passthrough_params: builtins.bool | None = ..., + num_partitions: builtins.int | None = ..., + launch_id: builtins.int | None = ..., + use_spmd_partitioning: builtins.bool | None = ..., + use_auto_spmd_partitioning: builtins.bool | None = ..., + auto_spmd_partitioning_mesh_shape: collections.abc.Iterable[builtins.int] | None = ..., + auto_spmd_partitioning_mesh_ids: collections.abc.Iterable[builtins.int] | None = ..., + deduplicate_hlo: builtins.bool | None = ..., + allow_spmd_sharding_propagation_to_parameters: collections.abc.Iterable[builtins.bool] | None = ..., + allow_spmd_sharding_propagation_to_output: collections.abc.Iterable[builtins.bool] | None = ..., + param_requires_broadcast_via_collectives: collections.abc.Iterable[builtins.bool] | None = ..., + allow_separate_sharding_programs: builtins.bool | None = ..., + shardable_value_update_pairs: collections.abc.Iterable[global___ShardableValueUpdatePairProto] | None = ..., + fdo_profile: builtins.bytes | None = ..., + device_memory_size: builtins.int | None = ..., + use_shardy_partitioner: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "debug_options", + b"debug_options", + "device_assignment", + b"device_assignment", + "shape_with_output_layout", + b"shape_with_output_layout", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alias_passthrough_params", + b"alias_passthrough_params", + "allow_separate_sharding_programs", + b"allow_separate_sharding_programs", + "allow_spmd_sharding_propagation_to_output", + b"allow_spmd_sharding_propagation_to_output", + "allow_spmd_sharding_propagation_to_parameters", + b"allow_spmd_sharding_propagation_to_parameters", + "auto_spmd_partitioning_mesh_ids", + b"auto_spmd_partitioning_mesh_ids", + "auto_spmd_partitioning_mesh_shape", + b"auto_spmd_partitioning_mesh_shape", + "debug_options", + b"debug_options", + "deduplicate_hlo", + b"deduplicate_hlo", + "device_assignment", + b"device_assignment", + "device_handles", + b"device_handles", + "device_memory_size", + b"device_memory_size", + "fdo_profile", + b"fdo_profile", + "launch_id", + b"launch_id", + "num_partitions", + b"num_partitions", + "num_replicas", + b"num_replicas", + "param_requires_broadcast_via_collectives", + b"param_requires_broadcast_via_collectives", + "seed", + b"seed", + "shape_with_output_layout", + b"shape_with_output_layout", + "shardable_value_update_pairs", + b"shardable_value_update_pairs", + "use_auto_spmd_partitioning", + b"use_auto_spmd_partitioning", + "use_shardy_partitioner", + b"use_shardy_partitioner", + "use_spmd_partitioning", + b"use_spmd_partitioning", + ], + ) -> None: ... + +global___ExecutionOptions = ExecutionOptions + +@typing.final +class HloModuleConfigProto(google.protobuf.message.Message): + """Serialization of HloModuleConfig. See the C++ class definition for + descriptions of each field. + There are no guarantees of backwards or forwards compatibility. + Next id: 36. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _FusionConfigCollection: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _FusionConfigCollectionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[HloModuleConfigProto._FusionConfigCollection.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + OFF: HloModuleConfigProto._FusionConfigCollection.ValueType # 0 + """Do not collect configuration.""" + PER_EDGE: HloModuleConfigProto._FusionConfigCollection.ValueType # 1 + """Collect per-edge configuration.""" + PER_NODE: HloModuleConfigProto._FusionConfigCollection.ValueType # 2 + """Collect per-node configuration.""" + + class FusionConfigCollection(_FusionConfigCollection, metaclass=_FusionConfigCollectionEnumTypeWrapper): ... + OFF: HloModuleConfigProto.FusionConfigCollection.ValueType # 0 + """Do not collect configuration.""" + PER_EDGE: HloModuleConfigProto.FusionConfigCollection.ValueType # 1 + """Collect per-edge configuration.""" + PER_NODE: HloModuleConfigProto.FusionConfigCollection.ValueType # 2 + """Collect per-node configuration.""" + + @typing.final + class BoolList(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALS_FIELD_NUMBER: builtins.int + @property + def vals(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + def __init__(self, *, vals: collections.abc.Iterable[builtins.bool] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["vals", b"vals"]) -> None: ... + + @typing.final + class Int64List(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALS_FIELD_NUMBER: builtins.int + @property + def vals(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, vals: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["vals", b"vals"]) -> None: ... + + @typing.final + class Int64ListList(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LISTS_FIELD_NUMBER: builtins.int + @property + def lists( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.Int64List]: ... + def __init__(self, *, lists: collections.abc.Iterable[global___HloModuleConfigProto.Int64List] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["lists", b"lists"]) -> None: ... + + @typing.final + class DotConfigEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___HloModuleConfigProto.Int64List: ... + def __init__( + self, *, key: builtins.str | None = ..., value: global___HloModuleConfigProto.Int64List | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + @typing.final + class AnalysisAllowanceMapEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + ENTRY_COMPUTATION_LAYOUT_FIELD_NUMBER: builtins.int + SEED_FIELD_NUMBER: builtins.int + LAUNCH_ID_FIELD_NUMBER: builtins.int + REPLICA_COUNT_FIELD_NUMBER: builtins.int + NUM_PARTITIONS_FIELD_NUMBER: builtins.int + PARAM_REQUIRES_BROADCAST_VIA_COLLECTIVES_FIELD_NUMBER: builtins.int + USE_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + USE_AUTO_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_SHAPE_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_IDS_FIELD_NUMBER: builtins.int + DEDUPLICATE_HLO_FIELD_NUMBER: builtins.int + INTRA_OP_PARALLELISM_THREADS_FIELD_NUMBER: builtins.int + DEVICE_TYPE_FIELD_NUMBER: builtins.int + DEBUG_OPTIONS_FIELD_NUMBER: builtins.int + STATIC_DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + PRE_SIMULATION_DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + ALLOW_SEPARATE_SHARDING_PROGRAMS_FIELD_NUMBER: builtins.int + SHARDABLE_VALUE_UPDATE_PAIRS_FIELD_NUMBER: builtins.int + ALIAS_PASSTHROUGH_PARAMS_FIELD_NUMBER: builtins.int + CONTENT_AWARE_COMPUTATION_SORTING_FIELD_NUMBER: builtins.int + FUSION_CONFIG_COLLECTION_FIELD_NUMBER: builtins.int + FUSION_CONFIG_FIELD_NUMBER: builtins.int + DOT_CONFIG_FIELD_NUMBER: builtins.int + LAYOUT_CONFIG_FIELD_NUMBER: builtins.int + MEMORY_SPACE_ASSIGNMENT_CONFIG_FIELD_NUMBER: builtins.int + PHASE_ORDERING_CONFIG_FIELD_NUMBER: builtins.int + PHASE_INDEX_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_PARAMETERS_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_OUTPUT_FIELD_NUMBER: builtins.int + ANALYSIS_ALLOWANCE_MAP_FIELD_NUMBER: builtins.int + MATRIX_UNIT_OPERAND_PRECISION_FIELD_NUMBER: builtins.int + FDO_PROFILE_FIELD_NUMBER: builtins.int + DEVICE_MEMORY_SIZE_FIELD_NUMBER: builtins.int + USE_SHARDY_PARTITIONER_FIELD_NUMBER: builtins.int + seed: builtins.int + launch_id: builtins.int + replica_count: builtins.int + num_partitions: builtins.int + use_spmd_partitioning: builtins.bool + use_auto_spmd_partitioning: builtins.bool + deduplicate_hlo: builtins.bool + intra_op_parallelism_threads: builtins.int + device_type: builtins.str + allow_separate_sharding_programs: builtins.bool + alias_passthrough_params: builtins.bool + content_aware_computation_sorting: builtins.bool + fusion_config_collection: global___HloModuleConfigProto.FusionConfigCollection.ValueType + phase_index: builtins.int + matrix_unit_operand_precision: tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig.Precision.ValueType + fdo_profile: builtins.bytes + device_memory_size: builtins.int + use_shardy_partitioner: builtins.bool + @property + def entry_computation_layout(self) -> tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto: ... + @property + def param_requires_broadcast_via_collectives( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def auto_spmd_partitioning_mesh_shape( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def auto_spmd_partitioning_mesh_ids( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def debug_options(self) -> global___DebugOptions: ... + @property + def static_device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: ... + @property + def pre_simulation_device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: + """The original device assignment before being changed by a simulator. + Simulators, like HybridSim, may change the device assignment to a smaller + topology, to make simulation easier. + """ + + @property + def shardable_value_update_pairs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShardableValueUpdatePairProto]: ... + @property + def fusion_config( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.BoolList]: ... + @property + def dot_config( + self, + ) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___HloModuleConfigProto.Int64List]: ... + @property + def layout_config( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.Int64ListList]: ... + @property + def memory_space_assignment_config( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def phase_ordering_config( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.BoolList]: ... + @property + def allow_spmd_sharding_propagation_to_parameters( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def allow_spmd_sharding_propagation_to_output( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def analysis_allowance_map(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: ... + def __init__( + self, + *, + entry_computation_layout: tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto | None = ..., + seed: builtins.int | None = ..., + launch_id: builtins.int | None = ..., + replica_count: builtins.int | None = ..., + num_partitions: builtins.int | None = ..., + param_requires_broadcast_via_collectives: collections.abc.Iterable[builtins.bool] | None = ..., + use_spmd_partitioning: builtins.bool | None = ..., + use_auto_spmd_partitioning: builtins.bool | None = ..., + auto_spmd_partitioning_mesh_shape: collections.abc.Iterable[builtins.int] | None = ..., + auto_spmd_partitioning_mesh_ids: collections.abc.Iterable[builtins.int] | None = ..., + deduplicate_hlo: builtins.bool | None = ..., + intra_op_parallelism_threads: builtins.int | None = ..., + device_type: builtins.str | None = ..., + debug_options: global___DebugOptions | None = ..., + static_device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + pre_simulation_device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + allow_separate_sharding_programs: builtins.bool | None = ..., + shardable_value_update_pairs: collections.abc.Iterable[global___ShardableValueUpdatePairProto] | None = ..., + alias_passthrough_params: builtins.bool | None = ..., + content_aware_computation_sorting: builtins.bool | None = ..., + fusion_config_collection: global___HloModuleConfigProto.FusionConfigCollection.ValueType | None = ..., + fusion_config: collections.abc.Iterable[global___HloModuleConfigProto.BoolList] | None = ..., + dot_config: collections.abc.Mapping[builtins.str, global___HloModuleConfigProto.Int64List] | None = ..., + layout_config: collections.abc.Iterable[global___HloModuleConfigProto.Int64ListList] | None = ..., + memory_space_assignment_config: collections.abc.Iterable[builtins.int] | None = ..., + phase_ordering_config: collections.abc.Iterable[global___HloModuleConfigProto.BoolList] | None = ..., + phase_index: builtins.int | None = ..., + allow_spmd_sharding_propagation_to_parameters: collections.abc.Iterable[builtins.bool] | None = ..., + allow_spmd_sharding_propagation_to_output: collections.abc.Iterable[builtins.bool] | None = ..., + analysis_allowance_map: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + matrix_unit_operand_precision: tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig.Precision.ValueType | None = ..., + fdo_profile: builtins.bytes | None = ..., + device_memory_size: builtins.int | None = ..., + use_shardy_partitioner: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "debug_options", + b"debug_options", + "entry_computation_layout", + b"entry_computation_layout", + "pre_simulation_device_assignment", + b"pre_simulation_device_assignment", + "static_device_assignment", + b"static_device_assignment", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alias_passthrough_params", + b"alias_passthrough_params", + "allow_separate_sharding_programs", + b"allow_separate_sharding_programs", + "allow_spmd_sharding_propagation_to_output", + b"allow_spmd_sharding_propagation_to_output", + "allow_spmd_sharding_propagation_to_parameters", + b"allow_spmd_sharding_propagation_to_parameters", + "analysis_allowance_map", + b"analysis_allowance_map", + "auto_spmd_partitioning_mesh_ids", + b"auto_spmd_partitioning_mesh_ids", + "auto_spmd_partitioning_mesh_shape", + b"auto_spmd_partitioning_mesh_shape", + "content_aware_computation_sorting", + b"content_aware_computation_sorting", + "debug_options", + b"debug_options", + "deduplicate_hlo", + b"deduplicate_hlo", + "device_memory_size", + b"device_memory_size", + "device_type", + b"device_type", + "dot_config", + b"dot_config", + "entry_computation_layout", + b"entry_computation_layout", + "fdo_profile", + b"fdo_profile", + "fusion_config", + b"fusion_config", + "fusion_config_collection", + b"fusion_config_collection", + "intra_op_parallelism_threads", + b"intra_op_parallelism_threads", + "launch_id", + b"launch_id", + "layout_config", + b"layout_config", + "matrix_unit_operand_precision", + b"matrix_unit_operand_precision", + "memory_space_assignment_config", + b"memory_space_assignment_config", + "num_partitions", + b"num_partitions", + "param_requires_broadcast_via_collectives", + b"param_requires_broadcast_via_collectives", + "phase_index", + b"phase_index", + "phase_ordering_config", + b"phase_ordering_config", + "pre_simulation_device_assignment", + b"pre_simulation_device_assignment", + "replica_count", + b"replica_count", + "seed", + b"seed", + "shardable_value_update_pairs", + b"shardable_value_update_pairs", + "static_device_assignment", + b"static_device_assignment", + "use_auto_spmd_partitioning", + b"use_auto_spmd_partitioning", + "use_shardy_partitioner", + b"use_shardy_partitioner", + "use_spmd_partitioning", + b"use_spmd_partitioning", + ], + ) -> None: ... + +global___HloModuleConfigProto = HloModuleConfigProto + +@typing.final +class HloModuleProtoWithConfig(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HLO_MODULE_FIELD_NUMBER: builtins.int + CONFIG_FIELD_NUMBER: builtins.int + @property + def hlo_module(self) -> tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto: ... + @property + def config(self) -> global___HloModuleConfigProto: ... + def __init__( + self, + *, + hlo_module: tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto | None = ..., + config: global___HloModuleConfigProto | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["config", b"config", "hlo_module", b"hlo_module"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["config", b"config", "hlo_module", b"hlo_module"]) -> None: ... + +global___HloModuleProtoWithConfig = HloModuleProtoWithConfig + +@typing.final +class ScheduleProto(google.protobuf.message.Message): + """A trace estimated by the Latency Hiding Scheduler.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Instruction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ID_FIELD_NUMBER: builtins.int + START_TIMESTAMP_CYCLES_FIELD_NUMBER: builtins.int + END_TIMESTAMP_CYCLES_FIELD_NUMBER: builtins.int + id: builtins.int + """Instruction id (matches the id in HloInstructionProto).""" + start_timestamp_cycles: builtins.float + """Start and end timestamps in cycles.""" + end_timestamp_cycles: builtins.float + def __init__( + self, + *, + id: builtins.int | None = ..., + start_timestamp_cycles: builtins.float | None = ..., + end_timestamp_cycles: builtins.float | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "end_timestamp_cycles", b"end_timestamp_cycles", "id", b"id", "start_timestamp_cycles", b"start_timestamp_cycles" + ], + ) -> None: ... + + INSTRUCTIONS_FIELD_NUMBER: builtins.int + COMPUTATION_ID_FIELD_NUMBER: builtins.int + HLO_MODULE_FIELD_NUMBER: builtins.int + CYCLES_PER_MICROSECOND_FIELD_NUMBER: builtins.int + computation_id: builtins.int + """Computation id (matches the id in HloComputationProto).""" + cycles_per_microsecond: builtins.int + @property + def instructions( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScheduleProto.Instruction]: ... + @property + def hlo_module(self) -> tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto: ... + def __init__( + self, + *, + instructions: collections.abc.Iterable[global___ScheduleProto.Instruction] | None = ..., + computation_id: builtins.int | None = ..., + hlo_module: tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto | None = ..., + cycles_per_microsecond: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["hlo_module", b"hlo_module"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "computation_id", + b"computation_id", + "cycles_per_microsecond", + b"cycles_per_microsecond", + "hlo_module", + b"hlo_module", + "instructions", + b"instructions", + ], + ) -> None: ... + +global___ScheduleProto = ScheduleProto diff --git a/stubs/tensorflow/tensorflow/config/__init__.pyi b/stubs/tensorflow/tensorflow/config/__init__.pyi new file mode 100644 index 000000000000..c68b78bd6181 --- /dev/null +++ b/stubs/tensorflow/tensorflow/config/__init__.pyi @@ -0,0 +1,12 @@ +from typing import NamedTuple + +from tensorflow.config import experimental as experimental + +class PhysicalDevice(NamedTuple): + name: str + device_type: str + +def list_physical_devices(device_type: str | None = None) -> list[PhysicalDevice]: ... +def get_visible_devices(device_type: str | None = None) -> list[PhysicalDevice]: ... +def set_visible_devices(devices: list[PhysicalDevice] | PhysicalDevice, device_type: str | None = None) -> None: ... +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/tensorflow/tensorflow/config/experimental.pyi b/stubs/tensorflow/tensorflow/config/experimental.pyi new file mode 100644 index 000000000000..aa9dcc53ed2e --- /dev/null +++ b/stubs/tensorflow/tensorflow/config/experimental.pyi @@ -0,0 +1,17 @@ +import typing_extensions +from typing import TypedDict, type_check_only + +from tensorflow.config import PhysicalDevice + +@type_check_only +class _MemoryInfo(TypedDict): + current: int + peak: int + +def get_memory_info(device: str) -> _MemoryInfo: ... +def reset_memory_stats(device: str) -> None: ... +@typing_extensions.deprecated("This function is deprecated in favor of tf.config.experimental.get_memory_info") +def get_memory_usage(device: PhysicalDevice) -> int: ... +def get_memory_growth(device: PhysicalDevice) -> bool: ... +def set_memory_growth(device: PhysicalDevice, enable: bool) -> None: ... +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi b/stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi new file mode 100644 index 000000000000..9ffaef3d17a0 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi @@ -0,0 +1,153 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing the configuration of the ExampleParserOp.""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class VarLenFeatureProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DTYPE_FIELD_NUMBER: builtins.int + VALUES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + INDICES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + SHAPES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + values_output_tensor_name: builtins.str + indices_output_tensor_name: builtins.str + shapes_output_tensor_name: builtins.str + def __init__( + self, + *, + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + values_output_tensor_name: builtins.str | None = ..., + indices_output_tensor_name: builtins.str | None = ..., + shapes_output_tensor_name: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "dtype", + b"dtype", + "indices_output_tensor_name", + b"indices_output_tensor_name", + "shapes_output_tensor_name", + b"shapes_output_tensor_name", + "values_output_tensor_name", + b"values_output_tensor_name", + ], + ) -> None: ... + +global___VarLenFeatureProto = VarLenFeatureProto + +@typing.final +class FixedLenFeatureProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DTYPE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + DEFAULT_VALUE_FIELD_NUMBER: builtins.int + VALUES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + values_output_tensor_name: builtins.str + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + @property + def default_value(self) -> tensorflow.core.framework.tensor_pb2.TensorProto: ... + def __init__( + self, + *, + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + default_value: tensorflow.core.framework.tensor_pb2.TensorProto | None = ..., + values_output_tensor_name: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["default_value", b"default_value", "shape", b"shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_value", + b"default_value", + "dtype", + b"dtype", + "shape", + b"shape", + "values_output_tensor_name", + b"values_output_tensor_name", + ], + ) -> None: ... + +global___FixedLenFeatureProto = FixedLenFeatureProto + +@typing.final +class FeatureConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIXED_LEN_FEATURE_FIELD_NUMBER: builtins.int + VAR_LEN_FEATURE_FIELD_NUMBER: builtins.int + @property + def fixed_len_feature(self) -> global___FixedLenFeatureProto: ... + @property + def var_len_feature(self) -> global___VarLenFeatureProto: ... + def __init__( + self, + *, + fixed_len_feature: global___FixedLenFeatureProto | None = ..., + var_len_feature: global___VarLenFeatureProto | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "config", b"config", "fixed_len_feature", b"fixed_len_feature", "var_len_feature", b"var_len_feature" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "config", b"config", "fixed_len_feature", b"fixed_len_feature", "var_len_feature", b"var_len_feature" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["config", b"config"] + ) -> typing.Literal["fixed_len_feature", "var_len_feature"] | None: ... + +global___FeatureConfiguration = FeatureConfiguration + +@typing.final +class ExampleParserConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureMapEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___FeatureConfiguration: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___FeatureConfiguration | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FEATURE_MAP_FIELD_NUMBER: builtins.int + @property + def feature_map(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___FeatureConfiguration]: ... + def __init__( + self, *, feature_map: collections.abc.Mapping[builtins.str, global___FeatureConfiguration] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["feature_map", b"feature_map"]) -> None: ... + +global___ExampleParserConfiguration = ExampleParserConfiguration diff --git a/stubs/tensorflow/tensorflow/core/example/example_pb2.pyi b/stubs/tensorflow/tensorflow/core/example/example_pb2.pyi new file mode 100644 index 000000000000..63cf2c14f17a --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/example/example_pb2.pyi @@ -0,0 +1,330 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing input data Examples for machine learning +model training or inference. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message +import tensorflow.core.example.feature_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Example(google.protobuf.message.Message): + """An Example is a mostly-normalized data format for storing data for + training and inference. It contains a key-value store (features); where + each key (string) maps to a Feature message (which is oneof packed BytesList, + FloatList, or Int64List). This flexible and compact format allows the + storage of large amounts of typed data, but requires that the data shape + and use be determined by the configuration files and parsers that are used to + read and write this format. That is, the Example is mostly *not* a + self-describing format. In TensorFlow, Examples are read in row-major + format, so any configuration that describes data with rank-2 or above + should keep this in mind. If you flatten a matrix into a FloatList it should + be stored as [ row 0 ... row 1 ... row M-1 ] + + An Example for a movie recommendation application: + features { + feature { + key: "age" + value { float_list { + value: 29.0 + }} + } + feature { + key: "movie" + value { bytes_list { + value: "The Shawshank Redemption" + value: "Fight Club" + }} + } + feature { + key: "movie_ratings" + value { float_list { + value: 9.0 + value: 9.7 + }} + } + feature { + key: "suggestion" + value { bytes_list { + value: "Inception" + }} + } + # Note that this feature exists to be used as a label in training. + # E.g., if training a logistic regression model to predict purchase + # probability in our learning tool we would set the label feature to + # "suggestion_purchased". + feature { + key: "suggestion_purchased" + value { float_list { + value: 1.0 + }} + } + # Similar to "suggestion_purchased" above this feature exists to be used + # as a label in training. + # E.g., if training a linear regression model to predict purchase + # price in our learning tool we would set the label feature to + # "purchase_price". + feature { + key: "purchase_price" + value { float_list { + value: 9.99 + }} + } + } + + A conformant Example data set obeys the following conventions: + - If a Feature K exists in one example with data type T, it must be of + type T in all other examples when present. It may be omitted. + - The number of instances of Feature K list data may vary across examples, + depending on the requirements of the model. + - If a Feature K doesn't exist in an example, a K-specific default will be + used, if configured. + - If a Feature K exists in an example but contains no items, the intent + is considered to be an empty tensor and no default will be used. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURES_FIELD_NUMBER: builtins.int + @property + def features(self) -> tensorflow.core.example.feature_pb2.Features: ... + def __init__(self, *, features: tensorflow.core.example.feature_pb2.Features | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["features", b"features"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["features", b"features"]) -> None: ... + +global___Example = Example + +@typing.final +class SequenceExample(google.protobuf.message.Message): + """A SequenceExample is an Example representing one or more sequences, and + some context. The context contains features which apply to the entire + example. The feature_lists contain a key, value map where each key is + associated with a repeated set of Features (a FeatureList). + A FeatureList thus represents the values of a feature identified by its key + over time / frames. + + Below is a SequenceExample for a movie recommendation application recording a + sequence of ratings by a user. The time-independent features ("locale", + "age", "favorites") describing the user are part of the context. The sequence + of movies the user rated are part of the feature_lists. For each movie in the + sequence we have information on its name and actors and the user's rating. + This information is recorded in three separate feature_list(s). + In the example below there are only two movies. All three feature_list(s), + namely "movie_ratings", "movie_names", and "actors" have a feature value for + both movies. Note, that "actors" is itself a bytes_list with multiple + strings per movie. + + context: { + feature: { + key : "locale" + value: { + bytes_list: { + value: [ "pt_BR" ] + } + } + } + feature: { + key : "age" + value: { + float_list: { + value: [ 19.0 ] + } + } + } + feature: { + key : "favorites" + value: { + bytes_list: { + value: [ "Majesty Rose", "Savannah Outen", "One Direction" ] + } + } + } + } + feature_lists: { + feature_list: { + key : "movie_ratings" + value: { + feature: { + float_list: { + value: [ 4.5 ] + } + } + feature: { + float_list: { + value: [ 5.0 ] + } + } + } + } + feature_list: { + key : "movie_names" + value: { + feature: { + bytes_list: { + value: [ "The Shawshank Redemption" ] + } + } + feature: { + bytes_list: { + value: [ "Fight Club" ] + } + } + } + } + feature_list: { + key : "actors" + value: { + feature: { + bytes_list: { + value: [ "Tim Robbins", "Morgan Freeman" ] + } + } + feature: { + bytes_list: { + value: [ "Brad Pitt", "Edward Norton", "Helena Bonham Carter" ] + } + } + } + } + } + + A conformant SequenceExample data set obeys the following conventions: + + Context: + - All conformant context features K must obey the same conventions as + a conformant Example's features (see above). + Feature lists: + - A FeatureList L may be missing in an example; it is up to the + parser configuration to determine if this is allowed or considered + an empty list (zero length). + - If a FeatureList L exists, it may be empty (zero length). + - If a FeatureList L is non-empty, all features within the FeatureList + must have the same data type T. Even across SequenceExamples, the type T + of the FeatureList identified by the same key must be the same. An entry + without any values may serve as an empty feature. + - If a FeatureList L is non-empty, it is up to the parser configuration + to determine if all features within the FeatureList must + have the same size. The same holds for this FeatureList across multiple + examples. + - For sequence modeling, e.g.: + http://colah.github.io/posts/2015-08-Understanding-LSTMs/ + https://github.com/tensorflow/nmt + the feature lists represent a sequence of frames. + In this scenario, all FeatureLists in a SequenceExample have the same + number of Feature messages, so that the ith element in each FeatureList + is part of the ith frame (or time step). + Examples of conformant and non-conformant examples' FeatureLists: + + Conformant FeatureLists: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + Non-conformant FeatureLists (mismatched types): + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { int64_list: { value: [ 5 ] } } } + } } + + Conditionally conformant FeatureLists, the parser configuration determines + if the feature sizes must match: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0, 6.0 ] } } } + } } + + Conformant pair of SequenceExample + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } + feature: { float_list: { value: [ 2.0 ] } } } + } } + + Conformant pair of SequenceExample + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { } + } } + + Conditionally conformant pair of SequenceExample, the parser configuration + determines if the second feature_lists is consistent (zero-length) or + invalid (missing "movie_ratings"): + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { } + + Non-conformant pair of SequenceExample (mismatched types) + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { int64_list: { value: [ 4 ] } } + feature: { int64_list: { value: [ 5 ] } } + feature: { int64_list: { value: [ 2 ] } } } + } } + + Conditionally conformant pair of SequenceExample; the parser configuration + determines if the feature sizes must match: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.0 ] } } + feature: { float_list: { value: [ 5.0, 3.0 ] } } + } } + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CONTEXT_FIELD_NUMBER: builtins.int + FEATURE_LISTS_FIELD_NUMBER: builtins.int + @property + def context(self) -> tensorflow.core.example.feature_pb2.Features: ... + @property + def feature_lists(self) -> tensorflow.core.example.feature_pb2.FeatureLists: ... + def __init__( + self, + *, + context: tensorflow.core.example.feature_pb2.Features | None = ..., + feature_lists: tensorflow.core.example.feature_pb2.FeatureLists | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["context", b"context", "feature_lists", b"feature_lists"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["context", b"context", "feature_lists", b"feature_lists"]) -> None: ... + +global___SequenceExample = SequenceExample diff --git a/stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi b/stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi new file mode 100644 index 000000000000..9bec4dd165e0 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi @@ -0,0 +1,222 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing features for machine learning model +training or inference. + +There are three base Feature types: + - bytes + - float + - int64 + +A Feature contains Lists which may hold zero or more values. These +lists are the base values BytesList, FloatList, Int64List. + +Features are organized into categories by name. The Features message +contains the mapping from name to Feature. + +Example Features for a movie recommendation application: + feature { + key: "age" + value { float_list { + value: 29.0 + }} + } + feature { + key: "movie" + value { bytes_list { + value: "The Shawshank Redemption" + value: "Fight Club" + }} + } + feature { + key: "movie_ratings" + value { float_list { + value: 9.0 + value: 9.7 + }} + } + feature { + key: "suggestion" + value { bytes_list { + value: "Inception" + }} + } + feature { + key: "suggestion_purchased" + value { int64_list { + value: 1 + }} + } + feature { + key: "purchase_price" + value { float_list { + value: 9.99 + }} + } +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class BytesList(google.protobuf.message.Message): + """LINT.IfChange + Containers to hold repeated fundamental values. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + @property + def value(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bytes]: ... + def __init__(self, *, value: collections.abc.Iterable[builtins.bytes] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___BytesList = BytesList + +@typing.final +class FloatList(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + @property + def value(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + def __init__(self, *, value: collections.abc.Iterable[builtins.float] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___FloatList = FloatList + +@typing.final +class Int64List(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + @property + def value(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, value: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___Int64List = Int64List + +@typing.final +class Feature(google.protobuf.message.Message): + """Containers for non-sequential data.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BYTES_LIST_FIELD_NUMBER: builtins.int + FLOAT_LIST_FIELD_NUMBER: builtins.int + INT64_LIST_FIELD_NUMBER: builtins.int + @property + def bytes_list(self) -> global___BytesList: ... + @property + def float_list(self) -> global___FloatList: ... + @property + def int64_list(self) -> global___Int64List: ... + def __init__( + self, + *, + bytes_list: global___BytesList | None = ..., + float_list: global___FloatList | None = ..., + int64_list: global___Int64List | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "bytes_list", b"bytes_list", "float_list", b"float_list", "int64_list", b"int64_list", "kind", b"kind" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bytes_list", b"bytes_list", "float_list", b"float_list", "int64_list", b"int64_list", "kind", b"kind" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> typing.Literal["bytes_list", "float_list", "int64_list"] | None: ... + +global___Feature = Feature + +@typing.final +class Features(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___Feature: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___Feature | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FEATURE_FIELD_NUMBER: builtins.int + @property + def feature(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Feature]: + """Map from feature name to feature.""" + + def __init__(self, *, feature: collections.abc.Mapping[builtins.str, global___Feature] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["feature", b"feature"]) -> None: ... + +global___Features = Features + +@typing.final +class FeatureList(google.protobuf.message.Message): + """Containers for sequential data. + + A FeatureList contains lists of Features. These may hold zero or more + Feature values. + + FeatureLists are organized into categories by name. The FeatureLists message + contains the mapping from name to FeatureList. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURE_FIELD_NUMBER: builtins.int + @property + def feature(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Feature]: ... + def __init__(self, *, feature: collections.abc.Iterable[global___Feature] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["feature", b"feature"]) -> None: ... + +global___FeatureList = FeatureList + +@typing.final +class FeatureLists(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureListEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___FeatureList: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___FeatureList | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FEATURE_LIST_FIELD_NUMBER: builtins.int + @property + def feature_list(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___FeatureList]: + """Map from feature name to feature list.""" + + def __init__(self, *, feature_list: collections.abc.Mapping[builtins.str, global___FeatureList] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["feature_list", b"feature_list"]) -> None: ... + +global___FeatureLists = FeatureLists diff --git a/stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi new file mode 100644 index 000000000000..9f4e541f2299 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi @@ -0,0 +1,64 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class AllocationDescription(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REQUESTED_BYTES_FIELD_NUMBER: builtins.int + ALLOCATED_BYTES_FIELD_NUMBER: builtins.int + ALLOCATOR_NAME_FIELD_NUMBER: builtins.int + ALLOCATION_ID_FIELD_NUMBER: builtins.int + HAS_SINGLE_REFERENCE_FIELD_NUMBER: builtins.int + PTR_FIELD_NUMBER: builtins.int + requested_bytes: builtins.int + """Total number of bytes requested""" + allocated_bytes: builtins.int + """Total number of bytes allocated if known""" + allocator_name: builtins.str + """Name of the allocator used""" + allocation_id: builtins.int + """Identifier of the allocated buffer if known""" + has_single_reference: builtins.bool + """Set if this tensor only has one remaining reference""" + ptr: builtins.int + """Address of the allocation.""" + def __init__( + self, + *, + requested_bytes: builtins.int | None = ..., + allocated_bytes: builtins.int | None = ..., + allocator_name: builtins.str | None = ..., + allocation_id: builtins.int | None = ..., + has_single_reference: builtins.bool | None = ..., + ptr: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "allocated_bytes", + b"allocated_bytes", + "allocation_id", + b"allocation_id", + "allocator_name", + b"allocator_name", + "has_single_reference", + b"has_single_reference", + "ptr", + b"ptr", + "requested_bytes", + b"requested_bytes", + ], + ) -> None: ... + +global___AllocationDescription = AllocationDescription diff --git a/stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi new file mode 100644 index 000000000000..b3d8c424234f --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi @@ -0,0 +1,312 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Defines the text format for including per-op API definition and +overrides for client language op code generators. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.core.framework.attr_value_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class ApiDef(google.protobuf.message.Message): + """Used to specify and override the default API & behavior in the + generated code for client languages, from what you would get from + the OpDef alone. There will be a set of ApiDefs that are common + to all client languages, and another set per client language. + The per-client-language ApiDefs will inherit values from the + common ApiDefs which it can either replace or modify. + + We separate the API definition from the OpDef so we can evolve the + API while remaining backwards compatible when interpreting old + graphs. Overrides go in an "api_def.pbtxt" file with a text-format + ApiDefs message. + + WARNING: Be *very* careful changing the API for any existing op -- + you can change the semantics of existing code. These changes may + need to wait until a major release of TensorFlow to avoid breaking + our compatibility promises. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Visibility: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _VisibilityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ApiDef._Visibility.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DEFAULT_VISIBILITY: ApiDef._Visibility.ValueType # 0 + """Normally this is "VISIBLE" unless you are inheriting a + different value from another ApiDef. + """ + VISIBLE: ApiDef._Visibility.ValueType # 1 + """Publicly visible in the API.""" + SKIP: ApiDef._Visibility.ValueType # 2 + """Do not include this op in the generated API. If visibility is + set to 'SKIP', other fields are ignored for this op. + """ + HIDDEN: ApiDef._Visibility.ValueType # 3 + """Hide this op by putting it into an internal namespace (or whatever + is appropriate in the target language). + """ + + class Visibility(_Visibility, metaclass=_VisibilityEnumTypeWrapper): ... + DEFAULT_VISIBILITY: ApiDef.Visibility.ValueType # 0 + """Normally this is "VISIBLE" unless you are inheriting a + different value from another ApiDef. + """ + VISIBLE: ApiDef.Visibility.ValueType # 1 + """Publicly visible in the API.""" + SKIP: ApiDef.Visibility.ValueType # 2 + """Do not include this op in the generated API. If visibility is + set to 'SKIP', other fields are ignored for this op. + """ + HIDDEN: ApiDef.Visibility.ValueType # 3 + """Hide this op by putting it into an internal namespace (or whatever + is appropriate in the target language). + """ + + @typing.final + class Endpoint(google.protobuf.message.Message): + """If you specify any endpoint, this will replace all of the + inherited endpoints. The first endpoint should be the + "canonical" endpoint, and should not be deprecated (unless all + endpoints are deprecated). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATION_VERSION_FIELD_NUMBER: builtins.int + name: builtins.str + """Name should be either like "CamelCaseName" or + "Package.CamelCaseName". Client-language-specific ApiDefs may + use a snake_case convention instead of CamelCase. + """ + deprecated: builtins.bool + """Set if this endpoint is deprecated. If set to true, a message suggesting + to use a non-deprecated endpoint instead will be printed. If all + endpoints are deprecated, set deprecation_message in ApiDef instead. + """ + deprecation_version: builtins.int + """Major version when an endpoint will be deleted. For e.g. set this + value to 2 if endpoint should be removed in TensorFlow 2.0 and + deprecated in versions before that. + """ + def __init__( + self, + *, + name: builtins.str | None = ..., + deprecated: builtins.bool | None = ..., + deprecation_version: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", b"deprecated", "deprecation_version", b"deprecation_version", "name", b"name" + ], + ) -> None: ... + + @typing.final + class Arg(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + RENAME_TO_FIELD_NUMBER: builtins.int + DESCRIPTION_FIELD_NUMBER: builtins.int + name: builtins.str + rename_to: builtins.str + """Change the name used to access this arg in the API from what + is used in the GraphDef. Note that these names in `backticks` + will also be replaced in the summary & description fields. + """ + description: builtins.str + """Note: this will replace any inherited arg doc. There is no + current way of modifying arg descriptions (other than replacing + them entirely) as can be done with op descriptions. + """ + def __init__( + self, *, name: builtins.str | None = ..., rename_to: builtins.str | None = ..., description: builtins.str | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["description", b"description", "name", b"name", "rename_to", b"rename_to"] + ) -> None: ... + + @typing.final + class Attr(google.protobuf.message.Message): + """Description of the graph-construction-time configuration of this + Op. That is to say, this describes the attr fields that will + be specified in the NodeDef. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + RENAME_TO_FIELD_NUMBER: builtins.int + DEFAULT_VALUE_FIELD_NUMBER: builtins.int + DESCRIPTION_FIELD_NUMBER: builtins.int + name: builtins.str + rename_to: builtins.str + """Change the name used to access this attr in the API from what + is used in the GraphDef. Note that these names in `backticks` + will also be replaced in the summary & description fields. + """ + description: builtins.str + """Note: this will replace any inherited attr doc, there is no current + way of modifying attr descriptions as can be done with op descriptions. + """ + @property + def default_value(self) -> tensorflow.core.framework.attr_value_pb2.AttrValue: + """Specify a new default value to use for this attr. This default + will be used when creating new graphs, as opposed to the + default in the OpDef, which will be used when interpreting old + GraphDefs. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + rename_to: builtins.str | None = ..., + default_value: tensorflow.core.framework.attr_value_pb2.AttrValue | None = ..., + description: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["default_value", b"default_value"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_value", b"default_value", "description", b"description", "name", b"name", "rename_to", b"rename_to" + ], + ) -> None: ... + + GRAPH_OP_NAME_FIELD_NUMBER: builtins.int + DEPRECATION_MESSAGE_FIELD_NUMBER: builtins.int + DEPRECATION_VERSION_FIELD_NUMBER: builtins.int + VISIBILITY_FIELD_NUMBER: builtins.int + ENDPOINT_FIELD_NUMBER: builtins.int + IN_ARG_FIELD_NUMBER: builtins.int + OUT_ARG_FIELD_NUMBER: builtins.int + ARG_ORDER_FIELD_NUMBER: builtins.int + ATTR_FIELD_NUMBER: builtins.int + SUMMARY_FIELD_NUMBER: builtins.int + DESCRIPTION_FIELD_NUMBER: builtins.int + DESCRIPTION_PREFIX_FIELD_NUMBER: builtins.int + DESCRIPTION_SUFFIX_FIELD_NUMBER: builtins.int + graph_op_name: builtins.str + """Name of the op (in the OpDef) to specify the API for.""" + deprecation_message: builtins.str + """If this op is deprecated, set deprecation message to the message + that should be logged when this op is used. + The message should indicate alternative op to use, if any. + """ + deprecation_version: builtins.int + """Major version when the op will be deleted. For e.g. set this + value to 2 if op API should be removed in TensorFlow 2.0 and + deprecated in versions before that. + """ + visibility: global___ApiDef.Visibility.ValueType + summary: builtins.str + """One-line human-readable description of what the Op does.""" + description: builtins.str + """Additional, longer human-readable description of what the Op does.""" + description_prefix: builtins.str + """Modify an existing/inherited description by adding text to the beginning + or end. + """ + description_suffix: builtins.str + @property + def endpoint(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Endpoint]: ... + @property + def in_arg(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Arg]: ... + @property + def out_arg(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Arg]: ... + @property + def arg_order(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """List of original in_arg names to specify new argument order. + Length of arg_order should be either empty to keep current order + or match size of in_arg. + """ + + @property + def attr(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Attr]: ... + def __init__( + self, + *, + graph_op_name: builtins.str | None = ..., + deprecation_message: builtins.str | None = ..., + deprecation_version: builtins.int | None = ..., + visibility: global___ApiDef.Visibility.ValueType | None = ..., + endpoint: collections.abc.Iterable[global___ApiDef.Endpoint] | None = ..., + in_arg: collections.abc.Iterable[global___ApiDef.Arg] | None = ..., + out_arg: collections.abc.Iterable[global___ApiDef.Arg] | None = ..., + arg_order: collections.abc.Iterable[builtins.str] | None = ..., + attr: collections.abc.Iterable[global___ApiDef.Attr] | None = ..., + summary: builtins.str | None = ..., + description: builtins.str | None = ..., + description_prefix: builtins.str | None = ..., + description_suffix: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "arg_order", + b"arg_order", + "attr", + b"attr", + "deprecation_message", + b"deprecation_message", + "deprecation_version", + b"deprecation_version", + "description", + b"description", + "description_prefix", + b"description_prefix", + "description_suffix", + b"description_suffix", + "endpoint", + b"endpoint", + "graph_op_name", + b"graph_op_name", + "in_arg", + b"in_arg", + "out_arg", + b"out_arg", + "summary", + b"summary", + "visibility", + b"visibility", + ], + ) -> None: ... + +global___ApiDef = ApiDef + +@typing.final +class ApiDefs(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OP_FIELD_NUMBER: builtins.int + @property + def op(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef]: ... + def __init__(self, *, op: collections.abc.Iterable[global___ApiDef] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["op", b"op"]) -> None: ... + +global___ApiDefs = ApiDefs diff --git a/stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi new file mode 100644 index 000000000000..bc36030c511d --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi @@ -0,0 +1,274 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class AttrValue(google.protobuf.message.Message): + """Protocol buffer representing the value for an attr used to configure an Op. + Comment indicates the corresponding attr type. Only the field matching the + attr type may be filled. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ListValue(google.protobuf.message.Message): + """LINT.IfChange""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + S_FIELD_NUMBER: builtins.int + I_FIELD_NUMBER: builtins.int + F_FIELD_NUMBER: builtins.int + B_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + TENSOR_FIELD_NUMBER: builtins.int + FUNC_FIELD_NUMBER: builtins.int + @property + def s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bytes]: + """ "list(string)" """ + + @property + def i(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ "list(int)" """ + + @property + def f(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + """ "list(float)" """ + + @property + def b(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """ "list(bool)" """ + + @property + def type( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[ + tensorflow.core.framework.types_pb2.DataType.ValueType + ]: + """ "list(type)" """ + + @property + def shape( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto + ]: + """ "list(shape)" """ + + @property + def tensor( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.core.framework.tensor_pb2.TensorProto + ]: + """ "list(tensor)" """ + + @property + def func(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___NameAttrList]: + """ "list(attr)" """ + + def __init__( + self, + *, + s: collections.abc.Iterable[builtins.bytes] | None = ..., + i: collections.abc.Iterable[builtins.int] | None = ..., + f: collections.abc.Iterable[builtins.float] | None = ..., + b: collections.abc.Iterable[builtins.bool] | None = ..., + type: collections.abc.Iterable[tensorflow.core.framework.types_pb2.DataType.ValueType] | None = ..., + shape: collections.abc.Iterable[tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto] | None = ..., + tensor: collections.abc.Iterable[tensorflow.core.framework.tensor_pb2.TensorProto] | None = ..., + func: collections.abc.Iterable[global___NameAttrList] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "b", + b"b", + "f", + b"f", + "func", + b"func", + "i", + b"i", + "s", + b"s", + "shape", + b"shape", + "tensor", + b"tensor", + "type", + b"type", + ], + ) -> None: ... + + S_FIELD_NUMBER: builtins.int + I_FIELD_NUMBER: builtins.int + F_FIELD_NUMBER: builtins.int + B_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + TENSOR_FIELD_NUMBER: builtins.int + LIST_FIELD_NUMBER: builtins.int + FUNC_FIELD_NUMBER: builtins.int + PLACEHOLDER_FIELD_NUMBER: builtins.int + s: builtins.bytes + """"string" """ + i: builtins.int + """"int" """ + f: builtins.float + """"float" """ + b: builtins.bool + """"bool" """ + type: tensorflow.core.framework.types_pb2.DataType.ValueType + """"type" """ + placeholder: builtins.str + """This is a placeholder only used in nodes defined inside a + function. It indicates the attr value will be supplied when + the function is instantiated. For example, let us suppose a + node "N" in function "FN". "N" has an attr "A" with value + placeholder = "foo". When FN is instantiated with attr "foo" + set to "bar", the instantiated node N's attr A will have been + given the value "bar". + """ + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: + """ "shape" """ + + @property + def tensor(self) -> tensorflow.core.framework.tensor_pb2.TensorProto: + """ "tensor" """ + + @property + def list(self) -> global___AttrValue.ListValue: + """any "list(...)" """ + + @property + def func(self) -> global___NameAttrList: + """ "func" represents a function. func.name is a function's name or + a primitive op's name. func.attr.first is the name of an attr + defined for that function. func.attr.second is the value for + that attr in the instantiation. + """ + + def __init__( + self, + *, + s: builtins.bytes | None = ..., + i: builtins.int | None = ..., + f: builtins.float | None = ..., + b: builtins.bool | None = ..., + type: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + tensor: tensorflow.core.framework.tensor_pb2.TensorProto | None = ..., + list: global___AttrValue.ListValue | None = ..., + func: global___NameAttrList | None = ..., + placeholder: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "b", + b"b", + "f", + b"f", + "func", + b"func", + "i", + b"i", + "list", + b"list", + "placeholder", + b"placeholder", + "s", + b"s", + "shape", + b"shape", + "tensor", + b"tensor", + "type", + b"type", + "value", + b"value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "b", + b"b", + "f", + b"f", + "func", + b"func", + "i", + b"i", + "list", + b"list", + "placeholder", + b"placeholder", + "s", + b"s", + "shape", + b"shape", + "tensor", + b"tensor", + "type", + b"type", + "value", + b"value", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["value", b"value"] + ) -> typing.Literal["s", "i", "f", "b", "type", "shape", "tensor", "list", "func", "placeholder"] | None: ... + +global___AttrValue = AttrValue + +@typing.final +class NameAttrList(google.protobuf.message.Message): + """A list of attr names and their values. The whole list is attached + with a string name. E.g., MatMul[T=float]. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class AttrEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___AttrValue: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___AttrValue | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + ATTR_FIELD_NUMBER: builtins.int + name: builtins.str + @property + def attr(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___AttrValue]: ... + def __init__( + self, *, name: builtins.str | None = ..., attr: collections.abc.Mapping[builtins.str, global___AttrValue] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["attr", b"attr", "name", b"name"]) -> None: ... + +global___NameAttrList = NameAttrList diff --git a/stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi new file mode 100644 index 000000000000..3ba7d01628bf --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi @@ -0,0 +1,229 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CostGraphDef(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Node(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class InputInfo(google.protobuf.message.Message): + """Inputs of this node. They must be executed before this node can be + executed. An input is a particular output of another node, specified + by the node id and the output index. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PRECEDING_NODE_FIELD_NUMBER: builtins.int + PRECEDING_PORT_FIELD_NUMBER: builtins.int + preceding_node: builtins.int + preceding_port: builtins.int + def __init__( + self, *, preceding_node: builtins.int | None = ..., preceding_port: builtins.int | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["preceding_node", b"preceding_node", "preceding_port", b"preceding_port"] + ) -> None: ... + + @typing.final + class OutputInfo(google.protobuf.message.Message): + """Outputs of this node.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SIZE_FIELD_NUMBER: builtins.int + ALIAS_INPUT_PORT_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + DTYPE_FIELD_NUMBER: builtins.int + size: builtins.int + alias_input_port: builtins.int + """If >= 0, the output is an alias of an input. Note that an alias input + may itself be an alias. The algorithm will therefore need to follow + those pointers. + """ + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + def __init__( + self, + *, + size: builtins.int | None = ..., + alias_input_port: builtins.int | None = ..., + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["shape", b"shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alias_input_port", b"alias_input_port", "dtype", b"dtype", "shape", b"shape", "size", b"size" + ], + ) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + DEVICE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + INPUT_INFO_FIELD_NUMBER: builtins.int + OUTPUT_INFO_FIELD_NUMBER: builtins.int + TEMPORARY_MEMORY_SIZE_FIELD_NUMBER: builtins.int + PERSISTENT_MEMORY_SIZE_FIELD_NUMBER: builtins.int + HOST_TEMP_MEMORY_SIZE_FIELD_NUMBER: builtins.int + DEVICE_TEMP_MEMORY_SIZE_FIELD_NUMBER: builtins.int + DEVICE_PERSISTENT_MEMORY_SIZE_FIELD_NUMBER: builtins.int + COMPUTE_COST_FIELD_NUMBER: builtins.int + COMPUTE_TIME_FIELD_NUMBER: builtins.int + MEMORY_TIME_FIELD_NUMBER: builtins.int + IS_FINAL_FIELD_NUMBER: builtins.int + CONTROL_INPUT_FIELD_NUMBER: builtins.int + INACCURATE_FIELD_NUMBER: builtins.int + name: builtins.str + """The name of the node. Names are globally unique.""" + device: builtins.str + """The device of the node. Can be empty if the node is mapped to the + default partition or partitioning hasn't been run yet. + """ + id: builtins.int + """The id of the node. Node ids are only unique inside a partition.""" + temporary_memory_size: builtins.int + """Temporary memory used by this node.""" + persistent_memory_size: builtins.int + """Persistent memory used by this node.""" + host_temp_memory_size: builtins.int + device_temp_memory_size: builtins.int + device_persistent_memory_size: builtins.int + compute_cost: builtins.int + """Estimate of the computational cost of this node, in microseconds.""" + compute_time: builtins.int + """Analytical estimate of the computational cost of this node, in + microseconds. + """ + memory_time: builtins.int + """Analytical estimate of the memory access cost of this node, in + microseconds. + """ + is_final: builtins.bool + """If true, the output is permanent: it can't be discarded, because this + node is part of the "final output". Nodes may depend on final nodes. + """ + inaccurate: builtins.bool + """Are the costs inaccurate?""" + @property + def input_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.Node.InputInfo]: ... + @property + def output_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.Node.OutputInfo]: ... + @property + def control_input(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Ids of the control inputs for this node.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + device: builtins.str | None = ..., + id: builtins.int | None = ..., + input_info: collections.abc.Iterable[global___CostGraphDef.Node.InputInfo] | None = ..., + output_info: collections.abc.Iterable[global___CostGraphDef.Node.OutputInfo] | None = ..., + temporary_memory_size: builtins.int | None = ..., + persistent_memory_size: builtins.int | None = ..., + host_temp_memory_size: builtins.int | None = ..., + device_temp_memory_size: builtins.int | None = ..., + device_persistent_memory_size: builtins.int | None = ..., + compute_cost: builtins.int | None = ..., + compute_time: builtins.int | None = ..., + memory_time: builtins.int | None = ..., + is_final: builtins.bool | None = ..., + control_input: collections.abc.Iterable[builtins.int] | None = ..., + inaccurate: builtins.bool | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compute_cost", + b"compute_cost", + "compute_time", + b"compute_time", + "control_input", + b"control_input", + "device", + b"device", + "device_persistent_memory_size", + b"device_persistent_memory_size", + "device_temp_memory_size", + b"device_temp_memory_size", + "host_temp_memory_size", + b"host_temp_memory_size", + "id", + b"id", + "inaccurate", + b"inaccurate", + "input_info", + b"input_info", + "is_final", + b"is_final", + "memory_time", + b"memory_time", + "name", + b"name", + "output_info", + b"output_info", + "persistent_memory_size", + b"persistent_memory_size", + "temporary_memory_size", + b"temporary_memory_size", + ], + ) -> None: ... + + @typing.final + class AggregatedCost(google.protobuf.message.Message): + """Total cost of this graph, typically used for balancing decisions.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COST_FIELD_NUMBER: builtins.int + DIMENSION_FIELD_NUMBER: builtins.int + cost: builtins.float + """Aggregated cost value.""" + dimension: builtins.str + """Aggregated cost dimension (e.g. 'memory', 'compute', 'network').""" + def __init__(self, *, cost: builtins.float | None = ..., dimension: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["cost", b"cost", "dimension", b"dimension"]) -> None: ... + + NODE_FIELD_NUMBER: builtins.int + COST_FIELD_NUMBER: builtins.int + @property + def node(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.Node]: ... + @property + def cost( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.AggregatedCost]: ... + def __init__( + self, + *, + node: collections.abc.Iterable[global___CostGraphDef.Node] | None = ..., + cost: collections.abc.Iterable[global___CostGraphDef.AggregatedCost] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["cost", b"cost", "node", b"node"]) -> None: ... + +global___CostGraphDef = CostGraphDef diff --git a/stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi new file mode 100644 index 000000000000..1bf1c41641cc --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi @@ -0,0 +1,110 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.full_type_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CppShapeInferenceResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class HandleShapeAndType(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SHAPE_FIELD_NUMBER: builtins.int + DTYPE_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + @property + def type(self) -> tensorflow.core.framework.full_type_pb2.FullTypeDef: ... + def __init__( + self, + *, + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + type: tensorflow.core.framework.full_type_pb2.FullTypeDef | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["shape", b"shape", "type", b"type"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["dtype", b"dtype", "shape", b"shape", "type", b"type"]) -> None: ... + + @typing.final + class HandleData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + IS_SET_FIELD_NUMBER: builtins.int + SHAPE_AND_TYPE_FIELD_NUMBER: builtins.int + is_set: builtins.bool + @property + def shape_and_type( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___CppShapeInferenceResult.HandleShapeAndType + ]: + """Only valid if .""" + + def __init__( + self, + *, + is_set: builtins.bool | None = ..., + shape_and_type: collections.abc.Iterable[global___CppShapeInferenceResult.HandleShapeAndType] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["is_set", b"is_set", "shape_and_type", b"shape_and_type"]) -> None: ... + + SHAPE_FIELD_NUMBER: builtins.int + HANDLE_DATA_FIELD_NUMBER: builtins.int + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + @property + def handle_data(self) -> global___CppShapeInferenceResult.HandleData: ... + def __init__( + self, + *, + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + handle_data: global___CppShapeInferenceResult.HandleData | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["handle_data", b"handle_data", "shape", b"shape"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["handle_data", b"handle_data", "shape", b"shape"]) -> None: ... + +global___CppShapeInferenceResult = CppShapeInferenceResult + +@typing.final +class CppShapeInferenceInputsNeeded(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INPUT_TENSORS_NEEDED_FIELD_NUMBER: builtins.int + INPUT_TENSORS_AS_SHAPES_NEEDED_FIELD_NUMBER: builtins.int + @property + def input_tensors_needed(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def input_tensors_as_shapes_needed( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + input_tensors_needed: collections.abc.Iterable[builtins.int] | None = ..., + input_tensors_as_shapes_needed: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "input_tensors_as_shapes_needed", b"input_tensors_as_shapes_needed", "input_tensors_needed", b"input_tensors_needed" + ], + ) -> None: ... + +global___CppShapeInferenceInputsNeeded = CppShapeInferenceInputsNeeded diff --git a/stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi new file mode 100644 index 000000000000..afde78f967f6 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi @@ -0,0 +1,25 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Metadata(google.protobuf.message.Message): + """next: 2""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + name: builtins.bytes + def __init__(self, *, name: builtins.bytes | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["name", b"name"]) -> None: ... + +global___Metadata = Metadata diff --git a/stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi new file mode 100644 index 000000000000..284c97869d3c --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi @@ -0,0 +1,724 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.core.framework.model_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _AutoShardPolicy: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AutoShardPolicyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_AutoShardPolicy.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AUTO: _AutoShardPolicy.ValueType # 0 + """AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding.""" + FILE: _AutoShardPolicy.ValueType # 1 + """FILE: Shards by input files (i.e. each worker will get a set of files to + process). When this option is selected, make sure that there is at least as + many files as workers. If there are fewer input files than workers, a + runtime error will be raised. + """ + DATA: _AutoShardPolicy.ValueType # 2 + """DATA: Shards by elements produced by the dataset. Each worker will process + the whole dataset and discard the portion that is not for itself. Note that + for this mode to correctly partitions the dataset elements, the dataset + needs to produce elements in a deterministic order. + """ + HINT: _AutoShardPolicy.ValueType # 3 + """HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated + as a placeholder to replace with `shard(num_workers, worker_index)`. + """ + OFF: _AutoShardPolicy.ValueType # -1 + """OFF: No sharding will be performed.""" + +class AutoShardPolicy(_AutoShardPolicy, metaclass=_AutoShardPolicyEnumTypeWrapper): + """Represents the type of auto-sharding we enable.""" + +AUTO: AutoShardPolicy.ValueType # 0 +"""AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding.""" +FILE: AutoShardPolicy.ValueType # 1 +"""FILE: Shards by input files (i.e. each worker will get a set of files to +process). When this option is selected, make sure that there is at least as +many files as workers. If there are fewer input files than workers, a +runtime error will be raised. +""" +DATA: AutoShardPolicy.ValueType # 2 +"""DATA: Shards by elements produced by the dataset. Each worker will process +the whole dataset and discard the portion that is not for itself. Note that +for this mode to correctly partitions the dataset elements, the dataset +needs to produce elements in a deterministic order. +""" +HINT: AutoShardPolicy.ValueType # 3 +"""HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated +as a placeholder to replace with `shard(num_workers, worker_index)`. +""" +OFF: AutoShardPolicy.ValueType # -1 +"""OFF: No sharding will be performed.""" +global___AutoShardPolicy = AutoShardPolicy + +class _ExternalStatePolicy: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ExternalStatePolicyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ExternalStatePolicy.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + POLICY_WARN: _ExternalStatePolicy.ValueType # 0 + POLICY_IGNORE: _ExternalStatePolicy.ValueType # 1 + POLICY_FAIL: _ExternalStatePolicy.ValueType # 2 + +class ExternalStatePolicy(_ExternalStatePolicy, metaclass=_ExternalStatePolicyEnumTypeWrapper): + """Represents how to handle external state during serialization.""" + +POLICY_WARN: ExternalStatePolicy.ValueType # 0 +POLICY_IGNORE: ExternalStatePolicy.ValueType # 1 +POLICY_FAIL: ExternalStatePolicy.ValueType # 2 +global___ExternalStatePolicy = ExternalStatePolicy + +@typing.final +class AutotuneOptions(google.protobuf.message.Message): + """next: 6""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ENABLED_FIELD_NUMBER: builtins.int + CPU_BUDGET_FIELD_NUMBER: builtins.int + RAM_BUDGET_FIELD_NUMBER: builtins.int + AUTOTUNE_ALGORITHM_FIELD_NUMBER: builtins.int + INITIAL_PARALLELISM_FIELD_NUMBER: builtins.int + enabled: builtins.bool + cpu_budget: builtins.int + ram_budget: builtins.int + autotune_algorithm: tensorflow.core.framework.model_pb2.AutotuneAlgorithm.ValueType + initial_parallelism: builtins.int + def __init__( + self, + *, + enabled: builtins.bool | None = ..., + cpu_budget: builtins.int | None = ..., + ram_budget: builtins.int | None = ..., + autotune_algorithm: tensorflow.core.framework.model_pb2.AutotuneAlgorithm.ValueType | None = ..., + initial_parallelism: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "autotune_algorithm", + b"autotune_algorithm", + "cpu_budget", + b"cpu_budget", + "enabled", + b"enabled", + "initial_parallelism", + b"initial_parallelism", + "optional_autotune_algorithm", + b"optional_autotune_algorithm", + "optional_cpu_budget", + b"optional_cpu_budget", + "optional_enabled", + b"optional_enabled", + "optional_initial_parallelism", + b"optional_initial_parallelism", + "optional_ram_budget", + b"optional_ram_budget", + "ram_budget", + b"ram_budget", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "autotune_algorithm", + b"autotune_algorithm", + "cpu_budget", + b"cpu_budget", + "enabled", + b"enabled", + "initial_parallelism", + b"initial_parallelism", + "optional_autotune_algorithm", + b"optional_autotune_algorithm", + "optional_cpu_budget", + b"optional_cpu_budget", + "optional_enabled", + b"optional_enabled", + "optional_initial_parallelism", + b"optional_initial_parallelism", + "optional_ram_budget", + b"optional_ram_budget", + "ram_budget", + b"ram_budget", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_autotune_algorithm", b"optional_autotune_algorithm"] + ) -> typing.Literal["autotune_algorithm"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_cpu_budget", b"optional_cpu_budget"] + ) -> typing.Literal["cpu_budget"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_enabled", b"optional_enabled"] + ) -> typing.Literal["enabled"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_initial_parallelism", b"optional_initial_parallelism"] + ) -> typing.Literal["initial_parallelism"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_ram_budget", b"optional_ram_budget"] + ) -> typing.Literal["ram_budget"] | None: ... + +global___AutotuneOptions = AutotuneOptions + +@typing.final +class CardinalityOptions(google.protobuf.message.Message): + """next: 2""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ComputeLevel: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ComputeLevelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[CardinalityOptions._ComputeLevel.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CARDINALITY_COMPUTE_UNSPECIFIED: CardinalityOptions._ComputeLevel.ValueType # 0 + CARDINALITY_COMPUTE_LOW: CardinalityOptions._ComputeLevel.ValueType # 1 + """Cardinality will only be computed if it can be determined in a cheap + manner (ie. without reading from file sources). If the cardinality would + be nontrivial to compute, Cardinality() will return UNKNOWN_CARDINALITY. + """ + CARDINALITY_COMPUTE_MODERATE: CardinalityOptions._ComputeLevel.ValueType # 2 + """Moderate effort will be made to determine cardinality, such as reading + index data from source files. If significant work is needed to compute + cardinality (e.g. reading entire source file contents or executing user + defined functions), Cardinality() will return UNKNOWN_CARDINALITY. + """ + + class ComputeLevel(_ComputeLevel, metaclass=_ComputeLevelEnumTypeWrapper): ... + CARDINALITY_COMPUTE_UNSPECIFIED: CardinalityOptions.ComputeLevel.ValueType # 0 + CARDINALITY_COMPUTE_LOW: CardinalityOptions.ComputeLevel.ValueType # 1 + """Cardinality will only be computed if it can be determined in a cheap + manner (ie. without reading from file sources). If the cardinality would + be nontrivial to compute, Cardinality() will return UNKNOWN_CARDINALITY. + """ + CARDINALITY_COMPUTE_MODERATE: CardinalityOptions.ComputeLevel.ValueType # 2 + """Moderate effort will be made to determine cardinality, such as reading + index data from source files. If significant work is needed to compute + cardinality (e.g. reading entire source file contents or executing user + defined functions), Cardinality() will return UNKNOWN_CARDINALITY. + """ + + COMPUTE_LEVEL_FIELD_NUMBER: builtins.int + compute_level: global___CardinalityOptions.ComputeLevel.ValueType + def __init__(self, *, compute_level: global___CardinalityOptions.ComputeLevel.ValueType | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["compute_level", b"compute_level"]) -> None: ... + +global___CardinalityOptions = CardinalityOptions + +@typing.final +class DistributeOptions(google.protobuf.message.Message): + """next: 3""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + AUTO_SHARD_POLICY_FIELD_NUMBER: builtins.int + NUM_DEVICES_FIELD_NUMBER: builtins.int + auto_shard_policy: global___AutoShardPolicy.ValueType + num_devices: builtins.int + def __init__( + self, *, auto_shard_policy: global___AutoShardPolicy.ValueType | None = ..., num_devices: builtins.int | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["num_devices", b"num_devices", "optional_num_devices", b"optional_num_devices"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "auto_shard_policy", + b"auto_shard_policy", + "num_devices", + b"num_devices", + "optional_num_devices", + b"optional_num_devices", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["optional_num_devices", b"optional_num_devices"] + ) -> typing.Literal["num_devices"] | None: ... + +global___DistributeOptions = DistributeOptions + +@typing.final +class OptimizationOptions(google.protobuf.message.Message): + """next: 22""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + APPLY_DEFAULT_OPTIMIZATIONS_FIELD_NUMBER: builtins.int + FILTER_FUSION_FIELD_NUMBER: builtins.int + MAP_AND_BATCH_FUSION_FIELD_NUMBER: builtins.int + MAP_AND_FILTER_FUSION_FIELD_NUMBER: builtins.int + MAP_FUSION_FIELD_NUMBER: builtins.int + MAP_PARALLELIZATION_FIELD_NUMBER: builtins.int + NOOP_ELIMINATION_FIELD_NUMBER: builtins.int + PARALLEL_BATCH_FIELD_NUMBER: builtins.int + SHUFFLE_AND_REPEAT_FUSION_FIELD_NUMBER: builtins.int + FILTER_PARALLELIZATION_FIELD_NUMBER: builtins.int + INJECT_PREFETCH_FIELD_NUMBER: builtins.int + SEQ_INTERLEAVE_PREFETCH_FIELD_NUMBER: builtins.int + apply_default_optimizations: builtins.bool + filter_fusion: builtins.bool + map_and_batch_fusion: builtins.bool + map_and_filter_fusion: builtins.bool + map_fusion: builtins.bool + map_parallelization: builtins.bool + noop_elimination: builtins.bool + parallel_batch: builtins.bool + shuffle_and_repeat_fusion: builtins.bool + filter_parallelization: builtins.bool + inject_prefetch: builtins.bool + seq_interleave_prefetch: builtins.bool + def __init__( + self, + *, + apply_default_optimizations: builtins.bool | None = ..., + filter_fusion: builtins.bool | None = ..., + map_and_batch_fusion: builtins.bool | None = ..., + map_and_filter_fusion: builtins.bool | None = ..., + map_fusion: builtins.bool | None = ..., + map_parallelization: builtins.bool | None = ..., + noop_elimination: builtins.bool | None = ..., + parallel_batch: builtins.bool | None = ..., + shuffle_and_repeat_fusion: builtins.bool | None = ..., + filter_parallelization: builtins.bool | None = ..., + inject_prefetch: builtins.bool | None = ..., + seq_interleave_prefetch: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "apply_default_optimizations", + b"apply_default_optimizations", + "filter_fusion", + b"filter_fusion", + "filter_parallelization", + b"filter_parallelization", + "inject_prefetch", + b"inject_prefetch", + "map_and_batch_fusion", + b"map_and_batch_fusion", + "map_and_filter_fusion", + b"map_and_filter_fusion", + "map_fusion", + b"map_fusion", + "map_parallelization", + b"map_parallelization", + "noop_elimination", + b"noop_elimination", + "optional_apply_default_optimizations", + b"optional_apply_default_optimizations", + "optional_filter_fusion", + b"optional_filter_fusion", + "optional_filter_parallelization", + b"optional_filter_parallelization", + "optional_inject_prefetch", + b"optional_inject_prefetch", + "optional_map_and_batch_fusion", + b"optional_map_and_batch_fusion", + "optional_map_and_filter_fusion", + b"optional_map_and_filter_fusion", + "optional_map_fusion", + b"optional_map_fusion", + "optional_map_parallelization", + b"optional_map_parallelization", + "optional_noop_elimination", + b"optional_noop_elimination", + "optional_parallel_batch", + b"optional_parallel_batch", + "optional_seq_interleave_prefetch", + b"optional_seq_interleave_prefetch", + "optional_shuffle_and_repeat_fusion", + b"optional_shuffle_and_repeat_fusion", + "parallel_batch", + b"parallel_batch", + "seq_interleave_prefetch", + b"seq_interleave_prefetch", + "shuffle_and_repeat_fusion", + b"shuffle_and_repeat_fusion", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "apply_default_optimizations", + b"apply_default_optimizations", + "filter_fusion", + b"filter_fusion", + "filter_parallelization", + b"filter_parallelization", + "inject_prefetch", + b"inject_prefetch", + "map_and_batch_fusion", + b"map_and_batch_fusion", + "map_and_filter_fusion", + b"map_and_filter_fusion", + "map_fusion", + b"map_fusion", + "map_parallelization", + b"map_parallelization", + "noop_elimination", + b"noop_elimination", + "optional_apply_default_optimizations", + b"optional_apply_default_optimizations", + "optional_filter_fusion", + b"optional_filter_fusion", + "optional_filter_parallelization", + b"optional_filter_parallelization", + "optional_inject_prefetch", + b"optional_inject_prefetch", + "optional_map_and_batch_fusion", + b"optional_map_and_batch_fusion", + "optional_map_and_filter_fusion", + b"optional_map_and_filter_fusion", + "optional_map_fusion", + b"optional_map_fusion", + "optional_map_parallelization", + b"optional_map_parallelization", + "optional_noop_elimination", + b"optional_noop_elimination", + "optional_parallel_batch", + b"optional_parallel_batch", + "optional_seq_interleave_prefetch", + b"optional_seq_interleave_prefetch", + "optional_shuffle_and_repeat_fusion", + b"optional_shuffle_and_repeat_fusion", + "parallel_batch", + b"parallel_batch", + "seq_interleave_prefetch", + b"seq_interleave_prefetch", + "shuffle_and_repeat_fusion", + b"shuffle_and_repeat_fusion", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_apply_default_optimizations", b"optional_apply_default_optimizations"] + ) -> typing.Literal["apply_default_optimizations"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_filter_fusion", b"optional_filter_fusion"] + ) -> typing.Literal["filter_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_filter_parallelization", b"optional_filter_parallelization"] + ) -> typing.Literal["filter_parallelization"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_inject_prefetch", b"optional_inject_prefetch"] + ) -> typing.Literal["inject_prefetch"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_and_batch_fusion", b"optional_map_and_batch_fusion"] + ) -> typing.Literal["map_and_batch_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_and_filter_fusion", b"optional_map_and_filter_fusion"] + ) -> typing.Literal["map_and_filter_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_fusion", b"optional_map_fusion"] + ) -> typing.Literal["map_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_parallelization", b"optional_map_parallelization"] + ) -> typing.Literal["map_parallelization"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_noop_elimination", b"optional_noop_elimination"] + ) -> typing.Literal["noop_elimination"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_parallel_batch", b"optional_parallel_batch"] + ) -> typing.Literal["parallel_batch"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_seq_interleave_prefetch", b"optional_seq_interleave_prefetch"] + ) -> typing.Literal["seq_interleave_prefetch"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_shuffle_and_repeat_fusion", b"optional_shuffle_and_repeat_fusion"] + ) -> typing.Literal["shuffle_and_repeat_fusion"] | None: ... + +global___OptimizationOptions = OptimizationOptions + +@typing.final +class ServiceOptions(google.protobuf.message.Message): + """next: 2""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PINNED_FIELD_NUMBER: builtins.int + pinned: builtins.bool + def __init__(self, *, pinned: builtins.bool | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["optional_pinned", b"optional_pinned", "pinned", b"pinned"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["optional_pinned", b"optional_pinned", "pinned", b"pinned"]) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["optional_pinned", b"optional_pinned"] + ) -> typing.Literal["pinned"] | None: ... + +global___ServiceOptions = ServiceOptions + +@typing.final +class ThreadingOptions(google.protobuf.message.Message): + """next: 3""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAX_INTRA_OP_PARALLELISM_FIELD_NUMBER: builtins.int + PRIVATE_THREADPOOL_SIZE_FIELD_NUMBER: builtins.int + max_intra_op_parallelism: builtins.int + private_threadpool_size: builtins.int + def __init__( + self, *, max_intra_op_parallelism: builtins.int | None = ..., private_threadpool_size: builtins.int | None = ... + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "max_intra_op_parallelism", + b"max_intra_op_parallelism", + "optional_max_intra_op_parallelism", + b"optional_max_intra_op_parallelism", + "optional_private_threadpool_size", + b"optional_private_threadpool_size", + "private_threadpool_size", + b"private_threadpool_size", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "max_intra_op_parallelism", + b"max_intra_op_parallelism", + "optional_max_intra_op_parallelism", + b"optional_max_intra_op_parallelism", + "optional_private_threadpool_size", + b"optional_private_threadpool_size", + "private_threadpool_size", + b"private_threadpool_size", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_max_intra_op_parallelism", b"optional_max_intra_op_parallelism"] + ) -> typing.Literal["max_intra_op_parallelism"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_private_threadpool_size", b"optional_private_threadpool_size"] + ) -> typing.Literal["private_threadpool_size"] | None: ... + +global___ThreadingOptions = ThreadingOptions + +@typing.final +class Options(google.protobuf.message.Message): + """Message stored with Dataset objects to control how datasets are processed and + optimized. + + next: 13 + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DATASET_NAME_FIELD_NUMBER: builtins.int + FRAMEWORK_TYPE_FIELD_NUMBER: builtins.int + DETERMINISTIC_FIELD_NUMBER: builtins.int + AUTOTUNE_OPTIONS_FIELD_NUMBER: builtins.int + DISTRIBUTE_OPTIONS_FIELD_NUMBER: builtins.int + OPTIMIZATION_OPTIONS_FIELD_NUMBER: builtins.int + SERVICE_OPTIONS_FIELD_NUMBER: builtins.int + SLACK_FIELD_NUMBER: builtins.int + THREADING_OPTIONS_FIELD_NUMBER: builtins.int + EXTERNAL_STATE_POLICY_FIELD_NUMBER: builtins.int + SYMBOLIC_CHECKPOINT_FIELD_NUMBER: builtins.int + WARM_START_FIELD_NUMBER: builtins.int + dataset_name: builtins.str + deterministic: builtins.bool + slack: builtins.bool + external_state_policy: global___ExternalStatePolicy.ValueType + symbolic_checkpoint: builtins.bool + warm_start: builtins.bool + @property + def framework_type(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """List of frameworks used to generate this dataset.""" + + @property + def autotune_options(self) -> global___AutotuneOptions: + """The autotune options associated with the dataset.""" + + @property + def distribute_options(self) -> global___DistributeOptions: + """The distribution strategy options associated with the dataset.""" + + @property + def optimization_options(self) -> global___OptimizationOptions: + """The optimization options associated with the dataset.""" + + @property + def service_options(self) -> global___ServiceOptions: + """The tf.data service options associated with the dataset.""" + + @property + def threading_options(self) -> global___ThreadingOptions: + """The threading options associated with the dataset.""" + + def __init__( + self, + *, + dataset_name: builtins.str | None = ..., + framework_type: collections.abc.Iterable[builtins.str] | None = ..., + deterministic: builtins.bool | None = ..., + autotune_options: global___AutotuneOptions | None = ..., + distribute_options: global___DistributeOptions | None = ..., + optimization_options: global___OptimizationOptions | None = ..., + service_options: global___ServiceOptions | None = ..., + slack: builtins.bool | None = ..., + threading_options: global___ThreadingOptions | None = ..., + external_state_policy: global___ExternalStatePolicy.ValueType | None = ..., + symbolic_checkpoint: builtins.bool | None = ..., + warm_start: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "autotune_options", + b"autotune_options", + "dataset_name", + b"dataset_name", + "deterministic", + b"deterministic", + "distribute_options", + b"distribute_options", + "external_state_policy", + b"external_state_policy", + "optimization_options", + b"optimization_options", + "optional_dataset_name", + b"optional_dataset_name", + "optional_deterministic", + b"optional_deterministic", + "optional_external_state_policy", + b"optional_external_state_policy", + "optional_slack", + b"optional_slack", + "optional_symbolic_checkpoint", + b"optional_symbolic_checkpoint", + "optional_warm_start", + b"optional_warm_start", + "service_options", + b"service_options", + "slack", + b"slack", + "symbolic_checkpoint", + b"symbolic_checkpoint", + "threading_options", + b"threading_options", + "warm_start", + b"warm_start", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "autotune_options", + b"autotune_options", + "dataset_name", + b"dataset_name", + "deterministic", + b"deterministic", + "distribute_options", + b"distribute_options", + "external_state_policy", + b"external_state_policy", + "framework_type", + b"framework_type", + "optimization_options", + b"optimization_options", + "optional_dataset_name", + b"optional_dataset_name", + "optional_deterministic", + b"optional_deterministic", + "optional_external_state_policy", + b"optional_external_state_policy", + "optional_slack", + b"optional_slack", + "optional_symbolic_checkpoint", + b"optional_symbolic_checkpoint", + "optional_warm_start", + b"optional_warm_start", + "service_options", + b"service_options", + "slack", + b"slack", + "symbolic_checkpoint", + b"symbolic_checkpoint", + "threading_options", + b"threading_options", + "warm_start", + b"warm_start", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_dataset_name", b"optional_dataset_name"] + ) -> typing.Literal["dataset_name"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_deterministic", b"optional_deterministic"] + ) -> typing.Literal["deterministic"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_external_state_policy", b"optional_external_state_policy"] + ) -> typing.Literal["external_state_policy"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["optional_slack", b"optional_slack"]) -> typing.Literal["slack"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_symbolic_checkpoint", b"optional_symbolic_checkpoint"] + ) -> typing.Literal["symbolic_checkpoint"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_warm_start", b"optional_warm_start"] + ) -> typing.Literal["warm_start"] | None: ... + +global___Options = Options diff --git a/stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi new file mode 100644 index 000000000000..0cfb9bb85928 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi @@ -0,0 +1,116 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CompressedComponentMetadata(google.protobuf.message.Message): + """This file contains protocol buffers for working with tf.data Datasets. + + Metadata describing a compressed component of a dataset element. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DTYPE_FIELD_NUMBER: builtins.int + TENSOR_SHAPE_FIELD_NUMBER: builtins.int + UNCOMPRESSED_BYTES_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + """The dtype of the component tensor.""" + @property + def tensor_shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: + """The shape of the component tensor.""" + + @property + def uncompressed_bytes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The amount of uncompressed tensor data. + - For string tensors, there is an element for each string indicating the + size of the string. + - For all other tensors, there is a single element indicating the size of + the tensor. + """ + + def __init__( + self, + *, + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + tensor_shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + uncompressed_bytes: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["tensor_shape", b"tensor_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dtype", b"dtype", "tensor_shape", b"tensor_shape", "uncompressed_bytes", b"uncompressed_bytes" + ], + ) -> None: ... + +global___CompressedComponentMetadata = CompressedComponentMetadata + +@typing.final +class CompressedElement(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DATA_FIELD_NUMBER: builtins.int + COMPONENT_METADATA_FIELD_NUMBER: builtins.int + VERSION_FIELD_NUMBER: builtins.int + data: builtins.bytes + """Compressed tensor bytes for all components of the element.""" + version: builtins.int + """Version of the CompressedElement. CompressedElements may be stored on disk + and read back by later versions of code, so we store a version number to + help readers understand which version they are reading. When you add a new + field to this proto, you need to increment kCompressedElementVersion in + tensorflow/core/data/compression_utils.cc. + """ + @property + def component_metadata( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CompressedComponentMetadata]: + """Metadata for the components of the element.""" + + def __init__( + self, + *, + data: builtins.bytes | None = ..., + component_metadata: collections.abc.Iterable[global___CompressedComponentMetadata] | None = ..., + version: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["component_metadata", b"component_metadata", "data", b"data", "version", b"version"] + ) -> None: ... + +global___CompressedElement = CompressedElement + +@typing.final +class UncompressedElement(google.protobuf.message.Message): + """An uncompressed dataset element.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COMPONENTS_FIELD_NUMBER: builtins.int + @property + def components( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.core.framework.tensor_pb2.TensorProto + ]: ... + def __init__( + self, *, components: collections.abc.Iterable[tensorflow.core.framework.tensor_pb2.TensorProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["components", b"components"]) -> None: ... + +global___UncompressedElement = UncompressedElement diff --git a/stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi new file mode 100644 index 000000000000..41abb3a43b72 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi @@ -0,0 +1,140 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class InterconnectLink(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEVICE_ID_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + STRENGTH_FIELD_NUMBER: builtins.int + device_id: builtins.int + type: builtins.str + strength: builtins.int + def __init__( + self, *, device_id: builtins.int | None = ..., type: builtins.str | None = ..., strength: builtins.int | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["device_id", b"device_id", "strength", b"strength", "type", b"type"] + ) -> None: ... + +global___InterconnectLink = InterconnectLink + +@typing.final +class LocalLinks(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LINK_FIELD_NUMBER: builtins.int + @property + def link(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___InterconnectLink]: ... + def __init__(self, *, link: collections.abc.Iterable[global___InterconnectLink] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["link", b"link"]) -> None: ... + +global___LocalLinks = LocalLinks + +@typing.final +class DeviceLocality(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BUS_ID_FIELD_NUMBER: builtins.int + NUMA_NODE_FIELD_NUMBER: builtins.int + LINKS_FIELD_NUMBER: builtins.int + bus_id: builtins.int + """Optional bus locality of device. Default value of 0 means + no specific locality. Specific localities are indexed from 1. + """ + numa_node: builtins.int + """Optional NUMA locality of device.""" + @property + def links(self) -> global___LocalLinks: + """Optional local interconnect links to other devices.""" + + def __init__( + self, *, bus_id: builtins.int | None = ..., numa_node: builtins.int | None = ..., links: global___LocalLinks | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["links", b"links"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["bus_id", b"bus_id", "links", b"links", "numa_node", b"numa_node"] + ) -> None: ... + +global___DeviceLocality = DeviceLocality + +@typing.final +class DeviceAttributes(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + DEVICE_TYPE_FIELD_NUMBER: builtins.int + MEMORY_LIMIT_FIELD_NUMBER: builtins.int + LOCALITY_FIELD_NUMBER: builtins.int + INCARNATION_FIELD_NUMBER: builtins.int + PHYSICAL_DEVICE_DESC_FIELD_NUMBER: builtins.int + XLA_GLOBAL_ID_FIELD_NUMBER: builtins.int + name: builtins.str + """Fully specified name of the device within a cluster.""" + device_type: builtins.str + """String representation of device_type.""" + memory_limit: builtins.int + """Memory capacity of device in bytes.""" + incarnation: builtins.int + """A device is assigned a global unique number each time it is + initialized. "incarnation" should never be 0. + """ + physical_device_desc: builtins.str + """String representation of the physical device that this device maps to.""" + xla_global_id: builtins.int + """A physical device ID for use in XLA DeviceAssignments, unique across + clients in a multi-client setup. Set to -1 if unavailable, non-negative + otherwise. + """ + @property + def locality(self) -> global___DeviceLocality: + """Platform-specific data about device that may be useful + for supporting efficient data transfers. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + device_type: builtins.str | None = ..., + memory_limit: builtins.int | None = ..., + locality: global___DeviceLocality | None = ..., + incarnation: builtins.int | None = ..., + physical_device_desc: builtins.str | None = ..., + xla_global_id: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["locality", b"locality"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "device_type", + b"device_type", + "incarnation", + b"incarnation", + "locality", + b"locality", + "memory_limit", + b"memory_limit", + "name", + b"name", + "physical_device_desc", + b"physical_device_desc", + "xla_global_id", + b"xla_global_id", + ], + ) -> None: ... + +global___DeviceAttributes = DeviceAttributes diff --git a/stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi new file mode 100644 index 000000000000..8025593122d5 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi @@ -0,0 +1,617 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _FullTypeId: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _FullTypeIdEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_FullTypeId.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TFT_UNSET: _FullTypeId.ValueType # 0 + """The default represents an uninitialized values.""" + TFT_VAR: _FullTypeId.ValueType # 1 + """Type symbols. Used to construct more complex type expressions like + algebraic data types. + + Type variables may serve as placeholder for any other type ID in type + templates. + + Examples: + TFT_DATASET[TFT_VAR["T"]] is a Dataset returning a type indicated by "T". + TFT_TENSOR[TFT_VAR["T"]] is a Tensor of n element type indicated by "T". + TFT_TENSOR[TFT_VAR["T"]], TFT_TENSOR[TFT_VAR["T"]] are two tensors of + identical element types. + TFT_TENSOR[TFT_VAR["P"]], TFT_TENSOR[TFT_VAR["Q"]] are two tensors of + independent element types. + """ + TFT_ANY: _FullTypeId.ValueType # 2 + """Wildcard type. Describes a parameter of unknown type. In TensorFlow, that + can mean either a "Top" type (accepts any type), or a dynamically typed + object whose type is unknown in context. + Important: "unknown" does not necessarily mean undeterminable! + """ + TFT_PRODUCT: _FullTypeId.ValueType # 3 + """The algebraic product type. This is an algebraic type that may be used just + for logical grouping. Not to confused with TFT_TUPLE which describes a + concrete object of several elements. + + Example: + TFT_DATASET[TFT_PRODUCT[TFT_TENSOR[TFT_INT32], TFT_TENSOR[TFT_FLOAT64]]] + is a Dataset producing two tensors, an integer one and a float one. + """ + TFT_NAMED: _FullTypeId.ValueType # 4 + """Represents a named field, with the name stored in the attribute. + + Parametrization: + TFT_NAMED[]{} + * is the type of the field + * is the field name, as string (thpugh can theoretically be an int + as well) + + Example: + TFT_RECORD[ + TFT_NAMED[TFT_TENSOR[TFT_INT32]]{'foo'}, + TFT_NAMED[TFT_TENSOR[TFT_FLOAT32]]{'bar'}, + ] + is a structure with two fields, an int tensor "foo" and a float tensor + "bar". + """ + TFT_FOR_EACH: _FullTypeId.ValueType # 20 + """Template definition. Expands the variables by repeating a template as + arguments of container. + + Parametrization: + TFT_FOR_EACH[,